diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000..5378fe089b --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* -text \ No newline at end of file diff --git a/.github/workflows/cpp-ci-serial-programs.yml b/.github/workflows/cpp-ci-serial-programs.yml index 016a5a7fcc..fa84978aba 100644 --- a/.github/workflows/cpp-ci-serial-programs.yml +++ b/.github/workflows/cpp-ci-serial-programs.yml @@ -1,68 +1,70 @@ -name: C++ CI Serial Programs - -on: [push, pull_request, workflow_dispatch] - -jobs: - build: - runs-on: ${{ matrix.os }} - - strategy: - fail-fast: false - matrix: - os: [windows-2025, macos-13, ubuntu-24.04] - qt_version: ['6.9.0'] - include: - - qt_version: '6.9.0' - qt_version_major: '6' - qt_modules: 'qtmultimedia qtserialport' - - steps: - - uses: actions/checkout@v4 - with: - path: Arduino-Source - - uses: actions/checkout@v4 - with: - repository: 'PokemonAutomation/Packages' - path: Packages - - name: Install dependencies - if: startsWith(matrix.os, 'ubuntu') - run: | - sudo apt update - sudo apt install libopencv-dev - - name: Install dependencies - if: startsWith(matrix.os, 'mac') - run: | - brew install opencv onnxruntime - - uses: jurplel/install-qt-action@v4 - with: - version: ${{ matrix.qt_version }} - modules: ${{ matrix.qt_modules }} - - name: Generate binaries - run: | - cd Arduino-Source/SerialPrograms - mkdir bin - cd bin - cmake .. -DQT_MAJOR:STRING=${{ matrix.qt_version_major }} - cmake --build . --config Release --parallel 10 - - name: Copy resources - if: startsWith(matrix.os, 'windows') - run: | - robocopy Packages/SerialPrograms/Resources Output/Resources /s - robocopy Packages/PABotBase/PABotBase-Switch Output/PABotBase /s - robocopy Arduino-Source/SerialPrograms/bin Output/Binaries *.dll - robocopy Arduino-Source/SerialPrograms/bin/Release Output/Binaries SerialPrograms.exe - echo https://github.com/${{github.repository}}/commit/${{github.sha}} > Output/version.txt - write-host "Robocopy exited with exit code:" $lastexitcode - if ($lastexitcode -eq 1) - { - exit 0 - } - else - { - exit 1 - } - - uses: actions/upload-artifact@v4 - if: startsWith(matrix.os, 'windows') - with: - name: Serial Programs for windows (${{ matrix.qt_version }}) - path: Output +name: C++ CI Serial Programs + +on: [push, pull_request, workflow_dispatch] + +jobs: + build: + runs-on: ${{ matrix.os }} + + strategy: + fail-fast: false + matrix: + os: [windows-2025, macos-13, ubuntu-24.04] + qt_version: ['6.9.1'] + include: + - qt_version: '6.9.1' + qt_version_major: '6' + qt_modules: 'qtmultimedia qtserialport' + + steps: + - uses: actions/checkout@v4 + with: + path: Arduino-Source + submodules: 'recursive' + - uses: actions/checkout@v4 + with: + repository: 'PokemonAutomation/Packages' + path: Packages + - uses: jurplel/install-qt-action@v4 + with: + version: ${{ matrix.qt_version }} + modules: ${{ matrix.qt_modules }} + - name: Install dependencies + if: startsWith(matrix.os, 'ubuntu') + run: | + sudo apt update + sudo apt upgrade + sudo apt install libopencv-dev + - name: Install dependencies + if: startsWith(matrix.os, 'mac') + run: | + brew install opencv onnxruntime + - name: Generate binaries + run: | + cd Arduino-Source/SerialPrograms + mkdir bin + cd bin + cmake .. -DQT_MAJOR:STRING=${{ matrix.qt_version_major }} + cmake --build . --config Release --parallel 10 + - name: Copy resources + if: startsWith(matrix.os, 'windows') + run: | + robocopy Packages/SerialPrograms/Resources Output/Resources /s + robocopy Packages/PABotBase/PABotBase-Switch Output/PABotBase /s + robocopy Arduino-Source/SerialPrograms/bin Output/Binaries *.dll + robocopy Arduino-Source/SerialPrograms/bin/Release Output/Binaries SerialPrograms.exe + echo https://github.com/${{github.repository}}/commit/${{github.sha}} > Output/version.txt + write-host "Robocopy exited with exit code:" $lastexitcode + if ($lastexitcode -eq 1) + { + exit 0 + } + else + { + exit 1 + } + - uses: actions/upload-artifact@v4 + if: startsWith(matrix.os, 'windows') + with: + name: Serial Programs for windows (${{ matrix.qt_version }}) + path: Output diff --git a/.gitignore b/.gitignore index bc563f616b..7d8cd42553 100644 --- a/.gitignore +++ b/.gitignore @@ -1,57 +1,57 @@ -SerialPrograms/bin/ - -.vscode - -# macOS hidden system file -.DS_Store - -build-*/ -build/ - -# Qt config file on a user basis -*.pro.user - -# all other common C++ ignorables -# Prerequisites -*.d - -# Compiled Object files -*.slo -*.lo -*.o -*.obj - -# Precompiled Headers -*.gch -*.pch - -# Compiled Dynamic libraries -SerialPrograms/*.so -SerialPrograms/*.dylib -SerialPrograms/*.dll - -# Fortran module files -*.mod -*.smod - -# Compiled Static libraries -SerialPrograms/*.lai -SerialPrograms/*.la -SerialPrograms/*.a -SerialPrograms/*.lib - -# Executables -*.exe -*.out -*.app - -.vs -Resources/* -SerialPrograms/CMakeLists.txt.user -opencv_world4110d.dll - -# Python cache -__pycache__ - -# Jupyter Notebooks -*.ipynb +SerialPrograms/bin/ + +.vscode + +# macOS hidden system file +.DS_Store + +build-*/ +build/ + +# Qt config file on a user basis +*.pro.user + +# all other common C++ ignorables +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +SerialPrograms/*.so +SerialPrograms/*.dylib +SerialPrograms/*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +SerialPrograms/*.lai +SerialPrograms/*.la +SerialPrograms/*.a +SerialPrograms/*.lib + +# Executables +*.exe +*.out +*.app + +.vs +Resources/* +SerialPrograms/CMakeLists.txt.user +opencv_world4110d.dll + +# Python cache +__pycache__ + +# Jupyter Notebooks +*.ipynb diff --git a/3rdParty/ONNX/OnnxToolsPA.h b/3rdParty/ONNX/OnnxToolsPA.h index ed20b4a6c4..7e038f75ae 100644 --- a/3rdParty/ONNX/OnnxToolsPA.h +++ b/3rdParty/ONNX/OnnxToolsPA.h @@ -1,38 +1,38 @@ -/* Simple Integer Option - * - * From: https://github.com/PokemonAutomation/ - * - * This option is thread-safe. - * - */ - -#ifndef PokemonAutomation_3rdParty_OnnxToolsPA_H -#define PokemonAutomation_3rdParty_OnnxToolsPA_H - -#include -#include -#include "Common/Cpp/Unicode.h" - -namespace PokemonAutomation{ - -#ifdef _WIN32 - -inline std::wstring str_to_onnx_str(const std::string& str){ - return utf8_to_wstr(str); -} - - -#else - - -inline std::string str_to_onnx_str(std::string str){ - return str; -} - - -#endif - - - -} -#endif +/* Simple Integer Option + * + * From: https://github.com/PokemonAutomation/ + * + * This option is thread-safe. + * + */ + +#ifndef PokemonAutomation_3rdParty_OnnxToolsPA_H +#define PokemonAutomation_3rdParty_OnnxToolsPA_H + +#include +#include +#include "Common/Cpp/Unicode.h" + +namespace PokemonAutomation{ + +#ifdef _WIN32 + +inline std::wstring str_to_onnx_str(const std::string& str){ + return utf8_to_wstr(str); +} + + +#else + + +inline std::string str_to_onnx_str(std::string str){ + return str; +} + + +#endif + + + +} +#endif diff --git a/3rdParty/ONNX/cpu_provider_factory.h b/3rdParty/ONNX/cpu_provider_factory.h index 292678692b..3aa39ca860 100644 --- a/3rdParty/ONNX/cpu_provider_factory.h +++ b/3rdParty/ONNX/cpu_provider_factory.h @@ -1,19 +1,19 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#include "onnxruntime_c_api.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \param use_arena zero: false. non-zero: true. - */ -ORT_EXPORT -ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_CPU, _In_ OrtSessionOptions* options, int use_arena) -ORT_ALL_ARGS_NONNULL; - -#ifdef __cplusplus -} -#endif +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#include "onnxruntime_c_api.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \param use_arena zero: false. non-zero: true. + */ +ORT_EXPORT +ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_CPU, _In_ OrtSessionOptions* options, int use_arena) +ORT_ALL_ARGS_NONNULL; + +#ifdef __cplusplus +} +#endif diff --git a/3rdParty/ONNX/onnxruntime_c_api.h b/3rdParty/ONNX/onnxruntime_c_api.h index b01b7e48dc..6cda7f00f4 100644 --- a/3rdParty/ONNX/onnxruntime_c_api.h +++ b/3rdParty/ONNX/onnxruntime_c_api.h @@ -1,6195 +1,6195 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// See docs\c_cxx\README.md on generating the Doxygen documentation from this file - -/** \mainpage ONNX Runtime - * - * ONNX Runtime is a high-performance inference and training graph execution engine for deep learning models. - * - * ONNX Runtime's C, C++ APIs offer an easy to use interface to onboard and execute onnx models. - * - \subpage c_cpp_api "Core C, C++ APIs" - * - \subpage training_c_cpp_api "Training C, C++ APIs for on-device training" - * - * \page c_cpp_api Core C, C++ APIs - *

C

- * - * ::OrtApi - Click here to go to the structure with all C API functions. - * - *

C++

- * - * ::Ort - Click here to go to the namespace holding all of the C++ wrapper classes - * - * It is a set of header only wrapper classes around the C API. The goal is to turn the C style return value error codes into C++ exceptions, and to - * automate memory management through standard C++ RAII principles. - * - * \addtogroup Global - * ONNX Runtime C API - * @{ - */ - -#pragma once -#include -#include -#include -#include - -/** \brief The API version defined in this header - * - * This value is used by some API functions to behave as this version of the header expects. - */ -#define ORT_API_VERSION 22 - -#ifdef __cplusplus -extern "C" { -#endif - -//! @} -// SAL2 Definitions -#ifndef _MSC_VER -#define _In_ -#define _In_z_ -#define _In_opt_ -#define _In_opt_z_ -#define _Out_ -#define _Outptr_ -#define _Out_opt_ -#define _Inout_ -#define _Inout_opt_ -#define _Frees_ptr_opt_ -#define _Ret_maybenull_ -#define _Ret_notnull_ -#define _Check_return_ -#define _Outptr_result_maybenull_ -#define _In_reads_(X) -#define _Inout_updates_(X) -#define _Out_writes_(X) -#define _Inout_updates_all_(X) -#define _Out_writes_bytes_all_(X) -#define _Out_writes_all_(X) -#define _Success_(X) -#define _Outptr_result_buffer_maybenull_(X) -#define ORT_ALL_ARGS_NONNULL __attribute__((nonnull)) -#else -#include -#define ORT_ALL_ARGS_NONNULL -#endif - -#ifdef _WIN32 -// Define ORT_DLL_IMPORT if your program is dynamically linked to Ort. -// dllexport is not used, we use a .def file. -#ifdef ORT_DLL_IMPORT -#define ORT_EXPORT __declspec(dllimport) -#else -#define ORT_EXPORT -#endif -#define ORT_API_CALL _stdcall -#define ORT_MUST_USE_RESULT -#define ORTCHAR_T wchar_t -#else -// To make symbols visible on macOS/iOS -#ifdef __APPLE__ -#define ORT_EXPORT __attribute__((visibility("default"))) -#else -#define ORT_EXPORT -#endif -#define ORT_API_CALL -#define ORT_MUST_USE_RESULT __attribute__((warn_unused_result)) -#define ORTCHAR_T char -#endif - -/// ORTCHAR_T, ORT_TSTR are reserved specifically for path handling. -/// All other strings are UTF-8 encoded, use char and std::string -#ifndef ORT_TSTR -#ifdef _WIN32 -#define ORT_TSTR(X) L##X -// When X is a macro, L##X is not defined. In this case, we need to use ORT_TSTR_ON_MACRO. -#define ORT_TSTR_ON_MACRO(X) L"" X -#else -#define ORT_TSTR(X) X -#define ORT_TSTR_ON_MACRO(X) X -#endif -#endif - -// On Windows, ORT_FILE is a wchar_t version of the __FILE__ macro. -// Otherwise, ORT_FILE is equivalent to __FILE__. -#ifndef ORT_FILE -#define ORT_FILE_INTERNAL(x) ORT_TSTR(x) -#define ORT_FILE ORT_FILE_INTERNAL(__FILE__) -#endif - -// Any pointer marked with _In_ or _Out_, cannot be NULL. - -// Windows users should use unicode paths when possible to bypass the MAX_PATH limitation -// Every pointer marked with _In_ or _Out_, cannot be NULL. Caller should ensure that. -// for ReleaseXXX(...) functions, they can accept NULL pointer. - -#ifdef __cplusplus -// For any compiler with C++11 support, MSVC 2015 and greater, or Clang version supporting noexcept. -// Such complex condition is needed because compilers set __cplusplus value differently. -#ifndef __has_feature -#define __has_feature(x) 0 -#endif -#if ((__cplusplus >= 201103L) || (_MSC_VER >= 1900) || (defined(__has_feature) && __has_feature(cxx_noexcept))) -#define NO_EXCEPTION noexcept -#else -#define NO_EXCEPTION throw() -#endif -#else -#define NO_EXCEPTION -#endif - -// __VA_ARGS__ on Windows and Linux are different -#define ORT_API(RETURN_TYPE, NAME, ...) RETURN_TYPE ORT_API_CALL NAME(__VA_ARGS__) NO_EXCEPTION - -#define ORT_API_STATUS(NAME, ...) \ - _Success_(return == 0) _Check_return_ _Ret_maybenull_ OrtStatusPtr ORT_API_CALL NAME(__VA_ARGS__) \ - NO_EXCEPTION ORT_MUST_USE_RESULT - -// XXX: Unfortunately, SAL annotations are known to not work with function pointers -#define ORT_API2_STATUS(NAME, ...) \ - _Check_return_ _Ret_maybenull_ OrtStatusPtr(ORT_API_CALL* NAME)(__VA_ARGS__) NO_EXCEPTION ORT_MUST_USE_RESULT - -// Used in *.cc files. Almost as same as ORT_API_STATUS, except without ORT_MUST_USE_RESULT and ORT_EXPORT -#define ORT_API_STATUS_IMPL(NAME, ...) \ - _Success_(return == 0) _Check_return_ _Ret_maybenull_ OrtStatusPtr ORT_API_CALL NAME(__VA_ARGS__) NO_EXCEPTION - -#define ORT_CLASS_RELEASE(X) void(ORT_API_CALL * Release##X)(_Frees_ptr_opt_ Ort##X * input) - -#ifdef __DOXYGEN__ -#undef ORT_API_STATUS -#define ORT_API_STATUS(NAME, ...) OrtStatus* NAME(__VA_ARGS__) -#undef ORT_API2_STATUS -#define ORT_API2_STATUS(NAME, ...) OrtStatus* NAME(__VA_ARGS__) -#undef ORT_CLASS_RELEASE -#define ORT_CLASS_RELEASE(X) void Release##X(Ort##X* input) -#undef NO_EXCEPTION -#define NO_EXCEPTION -#endif -/** \addtogroup Global - * ONNX Runtime C API - * @{ - */ - -/** Copied from TensorProto::DataType - * Currently, Ort doesn't support complex64, complex128 - */ -typedef enum ONNXTensorElementDataType { - ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED, - ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, // maps to c type float - ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8, // maps to c type uint8_t - ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8, // maps to c type int8_t - ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16, // maps to c type uint16_t - ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16, // maps to c type int16_t - ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32, // maps to c type int32_t - ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64, // maps to c type int64_t - ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING, // maps to c++ type std::string - ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL, - ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16, - ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE, // maps to c type double - ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32, // maps to c type uint32_t - ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64, // maps to c type uint64_t - ONNX_TENSOR_ELEMENT_DATA_TYPE_COMPLEX64, // complex with float32 real and imaginary components - ONNX_TENSOR_ELEMENT_DATA_TYPE_COMPLEX128, // complex with float64 real and imaginary components - ONNX_TENSOR_ELEMENT_DATA_TYPE_BFLOAT16, // Non-IEEE floating-point format based on IEEE754 single-precision - // float 8 types were introduced in onnx 1.14, see https://onnx.ai/onnx/technical/float8.html - ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FN, // Non-IEEE floating-point format based on IEEE754 single-precision - ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FNUZ, // Non-IEEE floating-point format based on IEEE754 single-precision - ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2, // Non-IEEE floating-point format based on IEEE754 single-precision - ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2FNUZ, // Non-IEEE floating-point format based on IEEE754 single-precision - // Int4 types were introduced in ONNX 1.16. See https://onnx.ai/onnx/technical/int4.html - ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT4, // maps to a pair of packed uint4 values (size == 1 byte) - ONNX_TENSOR_ELEMENT_DATA_TYPE_INT4 // maps to a pair of packed int4 values (size == 1 byte) -} ONNXTensorElementDataType; - -// Synced with onnx TypeProto oneof -typedef enum ONNXType { - ONNX_TYPE_UNKNOWN, - ONNX_TYPE_TENSOR, - ONNX_TYPE_SEQUENCE, - ONNX_TYPE_MAP, - ONNX_TYPE_OPAQUE, - ONNX_TYPE_SPARSETENSOR, - ONNX_TYPE_OPTIONAL -} ONNXType; - -// These types are synced with internal -// SparseFormatFlags -typedef enum OrtSparseFormat { - ORT_SPARSE_UNDEFINED = 0, - ORT_SPARSE_COO = 0x1, - ORT_SPARSE_CSRC = 0x2, - ORT_SPARSE_BLOCK_SPARSE = 0x4 -} OrtSparseFormat; - -// Enum allows to query sparse tensor indices -enum OrtSparseIndicesFormat { - ORT_SPARSE_COO_INDICES, - ORT_SPARSE_CSR_INNER_INDICES, - ORT_SPARSE_CSR_OUTER_INDICES, - ORT_SPARSE_BLOCK_SPARSE_INDICES -}; - -/** \brief Logging severity levels - * - * In typical API usage, specifying a logging severity level specifies the minimum severity of log messages to show. - */ -typedef enum OrtLoggingLevel { - ORT_LOGGING_LEVEL_VERBOSE, ///< Verbose informational messages (least severe). - ORT_LOGGING_LEVEL_INFO, ///< Informational messages. - ORT_LOGGING_LEVEL_WARNING, ///< Warning messages. - ORT_LOGGING_LEVEL_ERROR, ///< Error messages. - ORT_LOGGING_LEVEL_FATAL, ///< Fatal error messages (most severe). -} OrtLoggingLevel; - -typedef enum OrtErrorCode { - ORT_OK, - ORT_FAIL, - ORT_INVALID_ARGUMENT, - ORT_NO_SUCHFILE, - ORT_NO_MODEL, - ORT_ENGINE_ERROR, - ORT_RUNTIME_EXCEPTION, - ORT_INVALID_PROTOBUF, - ORT_MODEL_LOADED, - ORT_NOT_IMPLEMENTED, - ORT_INVALID_GRAPH, - ORT_EP_FAIL, - ORT_MODEL_LOAD_CANCELED, - ORT_MODEL_REQUIRES_COMPILATION, -} OrtErrorCode; - -typedef enum OrtOpAttrType { - ORT_OP_ATTR_UNDEFINED = 0, - ORT_OP_ATTR_INT, - ORT_OP_ATTR_INTS, - ORT_OP_ATTR_FLOAT, - ORT_OP_ATTR_FLOATS, - ORT_OP_ATTR_STRING, - ORT_OP_ATTR_STRINGS, -} OrtOpAttrType; - -//! @} -#define ORT_RUNTIME_CLASS(X) \ - struct Ort##X; \ - typedef struct Ort##X Ort##X - -/** \addtogroup Global - * ONNX Runtime C API - * @{ - */ -// The actual types defined have an Ort prefix -ORT_RUNTIME_CLASS(Env); -ORT_RUNTIME_CLASS(Status); // nullptr for Status* indicates success -ORT_RUNTIME_CLASS(MemoryInfo); -ORT_RUNTIME_CLASS(IoBinding); -ORT_RUNTIME_CLASS(Session); // Don't call ReleaseSession from Dllmain (because session owns a thread pool) -ORT_RUNTIME_CLASS(Value); -ORT_RUNTIME_CLASS(RunOptions); -ORT_RUNTIME_CLASS(TypeInfo); -ORT_RUNTIME_CLASS(TensorTypeAndShapeInfo); -ORT_RUNTIME_CLASS(MapTypeInfo); -ORT_RUNTIME_CLASS(SequenceTypeInfo); -ORT_RUNTIME_CLASS(OptionalTypeInfo); -ORT_RUNTIME_CLASS(SessionOptions); -ORT_RUNTIME_CLASS(CustomOpDomain); -ORT_RUNTIME_CLASS(ModelMetadata); -ORT_RUNTIME_CLASS(ThreadPoolParams); -ORT_RUNTIME_CLASS(ThreadingOptions); -ORT_RUNTIME_CLASS(ArenaCfg); -ORT_RUNTIME_CLASS(PrepackedWeightsContainer); -ORT_RUNTIME_CLASS(TensorRTProviderOptionsV2); -ORT_RUNTIME_CLASS(NvTensorRtRtxProviderOptions); -ORT_RUNTIME_CLASS(CUDAProviderOptionsV2); -ORT_RUNTIME_CLASS(CANNProviderOptions); -ORT_RUNTIME_CLASS(DnnlProviderOptions); -ORT_RUNTIME_CLASS(Op); -ORT_RUNTIME_CLASS(OpAttr); -ORT_RUNTIME_CLASS(Logger); -ORT_RUNTIME_CLASS(ShapeInferContext); -ORT_RUNTIME_CLASS(LoraAdapter); -ORT_RUNTIME_CLASS(ValueInfo); -ORT_RUNTIME_CLASS(Node); -ORT_RUNTIME_CLASS(Graph); -ORT_RUNTIME_CLASS(Model); -ORT_RUNTIME_CLASS(ModelCompilationOptions); -ORT_RUNTIME_CLASS(HardwareDevice); -ORT_RUNTIME_CLASS(EpDevice); -ORT_RUNTIME_CLASS(KeyValuePairs); - -#ifdef _MSC_VER -typedef _Return_type_success_(return == 0) OrtStatus* OrtStatusPtr; -#else -typedef OrtStatus* OrtStatusPtr; -#endif - -/** \brief Memory allocation interface - * - * Structure of function pointers that defines a memory allocator. This can be created and filled in by the user for custom allocators. - * - * When an allocator is passed to any function, be sure that the allocator object is not destroyed until the last allocated object using it is freed. - */ -typedef struct OrtAllocator { - uint32_t version; ///< Must be initialized to ORT_API_VERSION - void*(ORT_API_CALL* Alloc)(struct OrtAllocator* this_, size_t size); ///< Returns a pointer to an allocated block of `size` bytes - void(ORT_API_CALL* Free)(struct OrtAllocator* this_, void* p); ///< Free a block of memory previously allocated with OrtAllocator::Alloc - const struct OrtMemoryInfo*(ORT_API_CALL* Info)(const struct OrtAllocator* this_); ///< Return a pointer to an ::OrtMemoryInfo that describes this allocator - /** - * @brief Optional allocation function to use for memory allocations made during session initialization. - * Use this function if you want to separate allocations made by ORT during Run() calls from - * those made during session initialization. This allows for separate memory management strategies for these allocations. - */ - void*(ORT_API_CALL* Reserve)(struct OrtAllocator* this_, size_t size); ///< Returns a pointer to an allocated block of `size` bytes -} OrtAllocator; - -typedef void(ORT_API_CALL* OrtLoggingFunction)( - void* param, OrtLoggingLevel severity, const char* category, const char* logid, const char* code_location, - const char* message); - -/** \brief Graph optimization level - * - * Refer to https://www.onnxruntime.ai/docs/performance/graph-optimizations.html#graph-optimization-levels - * for an in-depth understanding of the Graph Optimization Levels. - */ -typedef enum GraphOptimizationLevel { - ORT_DISABLE_ALL = 0, - ORT_ENABLE_BASIC = 1, - ORT_ENABLE_EXTENDED = 2, - ORT_ENABLE_ALL = 99 -} GraphOptimizationLevel; - -typedef enum ExecutionMode { - ORT_SEQUENTIAL = 0, - ORT_PARALLEL = 1, -} ExecutionMode; - -/** \brief Language projection identifiers - * /see OrtApi::SetLanguageProjection - */ -typedef enum OrtLanguageProjection { - ORT_PROJECTION_C = 0, - ORT_PROJECTION_CPLUSPLUS = 1, - ORT_PROJECTION_CSHARP = 2, - ORT_PROJECTION_PYTHON = 3, - ORT_PROJECTION_JAVA = 4, - ORT_PROJECTION_WINML = 5, - ORT_PROJECTION_NODEJS = 6, -} OrtLanguageProjection; - -struct OrtKernelInfo; -typedef struct OrtKernelInfo OrtKernelInfo; -struct OrtKernelContext; -typedef struct OrtKernelContext OrtKernelContext; -struct OrtCustomOp; -typedef struct OrtCustomOp OrtCustomOp; - -typedef enum OrtAllocatorType { - OrtInvalidAllocator = -1, - OrtDeviceAllocator = 0, - OrtArenaAllocator = 1 -} OrtAllocatorType; - -/** \brief Memory types for allocated memory, execution provider specific types should be extended in each provider. - */ -// Whenever this struct is updated, please also update the MakeKey function in onnxruntime / core / framework / execution_provider.cc -typedef enum OrtMemType { - OrtMemTypeCPUInput = -2, ///< Any CPU memory used by non-CPU execution provider - OrtMemTypeCPUOutput = -1, ///< CPU accessible memory outputted by non-CPU execution provider, i.e. CUDA_PINNED - OrtMemTypeCPU = OrtMemTypeCPUOutput, ///< Temporary CPU accessible memory allocated by non-CPU execution provider, i.e. CUDA_PINNED - OrtMemTypeDefault = 0, ///< The default allocator for execution provider -} OrtMemType; - -/** \brief This mimics OrtDevice type constants so they can be returned in the API - */ -typedef enum OrtMemoryInfoDeviceType { - OrtMemoryInfoDeviceType_CPU = 0, - OrtMemoryInfoDeviceType_GPU = 1, - OrtMemoryInfoDeviceType_FPGA = 2 -} OrtMemoryInfoDeviceType; - -typedef enum OrtHardwareDeviceType { - OrtHardwareDeviceType_CPU, - OrtHardwareDeviceType_GPU, - OrtHardwareDeviceType_NPU -} OrtHardwareDeviceType; - -/** \brief These are the default EP selection policies used by ORT when doing automatic EP selection. - */ -typedef enum OrtExecutionProviderDevicePolicy { - OrtExecutionProviderDevicePolicy_DEFAULT, - OrtExecutionProviderDevicePolicy_PREFER_CPU, - OrtExecutionProviderDevicePolicy_PREFER_NPU, - OrtExecutionProviderDevicePolicy_PREFER_GPU, - OrtExecutionProviderDevicePolicy_MAX_PERFORMANCE, - OrtExecutionProviderDevicePolicy_MAX_EFFICIENCY, - OrtExecutionProviderDevicePolicy_MIN_OVERALL_POWER, -} OrtExecutionProviderDevicePolicy; - -/** \brief Delegate to allow providing custom OrtEpDevice selection logic - * - * This delegate is called by the EP selection code to allow the user to provide custom device selection logic. - * The user can use this to select OrtEpDevice instances from the list of available devices. - * - * \param ep_devices The list of available devices. - * \param num_devices The number of available devices. - * \param model_metadata The model metadata. - * \param runtime_metadata The runtime metadata. May be nullptr. - * \param selected Pre-allocated array to populate with selected OrtEpDevice pointers from ep_devices. - * \param max_ep_devices The maximum number of devices that can be selected in the pre-allocated array. - Currently the maximum is 8. - * \param num_ep_devices The number of selected devices. - * \param state Opaque pointer. Required to use the delegate from other languages like C# and python. - * - * \return OrtStatus* Selection status. Return nullptr on success. - * Use CreateStatus to provide error info. Use ORT_FAIL as the error code. - * ORT will release the OrtStatus* if not null. - */ -typedef OrtStatus* (*EpSelectionDelegate)(_In_ const OrtEpDevice** ep_devices, - _In_ size_t num_devices, - _In_ const OrtKeyValuePairs* model_metadata, - _In_opt_ const OrtKeyValuePairs* runtime_metadata, - _Inout_ const OrtEpDevice** selected, - _In_ size_t max_selected, - _Out_ size_t* num_selected, - _In_ void* state); - -/** \brief Algorithm to use for cuDNN Convolution Op - */ -typedef enum OrtCudnnConvAlgoSearch { - OrtCudnnConvAlgoSearchExhaustive, // expensive exhaustive benchmarking using cudnnFindConvolutionForwardAlgorithmEx - OrtCudnnConvAlgoSearchHeuristic, // lightweight heuristic based search using cudnnGetConvolutionForwardAlgorithm_v7 - OrtCudnnConvAlgoSearchDefault, // default algorithm using CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM -} OrtCudnnConvAlgoSearch; - -/** \brief CUDA Provider Options - * - * \see OrtApi::SessionOptionsAppendExecutionProvider_CUDA - */ -typedef struct OrtCUDAProviderOptions { -#ifdef __cplusplus - OrtCUDAProviderOptions() - : device_id{}, - cudnn_conv_algo_search{OrtCudnnConvAlgoSearchExhaustive}, - gpu_mem_limit{SIZE_MAX}, - arena_extend_strategy{}, - do_copy_in_default_stream{1}, - has_user_compute_stream{}, - user_compute_stream{}, - default_memory_arena_cfg{}, - tunable_op_enable{false}, - tunable_op_tuning_enable{false}, - tunable_op_max_tuning_duration_ms{} {} -#endif - - /** \brief CUDA device Id - * Defaults to 0. - */ - int device_id; - - /** \brief CUDA Convolution algorithm search configuration. - * See enum OrtCudnnConvAlgoSearch for more details. - * Defaults to OrtCudnnConvAlgoSearchExhaustive. - */ - OrtCudnnConvAlgoSearch cudnn_conv_algo_search; - - /** \brief CUDA memory limit (To use all possible memory pass in maximum size_t) - * Defaults to SIZE_MAX. - * \note If a ::OrtArenaCfg has been applied, it will override this field - */ - size_t gpu_mem_limit; - - /** \brief Strategy used to grow the memory arena - * 0 = kNextPowerOfTwo
- * 1 = kSameAsRequested
- * Defaults to 0. - * \note If a ::OrtArenaCfg has been applied, it will override this field - */ - int arena_extend_strategy; - - /** \brief Flag indicating if copying needs to take place on the same stream as the compute stream in the CUDA EP - * 0 = Use separate streams for copying and compute. - * 1 = Use the same stream for copying and compute. - * Defaults to 1. - * WARNING: Setting this to 0 may result in data races for some models. - * Please see issue #4829 for more details. - */ - int do_copy_in_default_stream; - - /** \brief Flag indicating if there is a user provided compute stream - * Defaults to 0. - */ - int has_user_compute_stream; - - /** \brief User provided compute stream. - * If provided, please set `has_user_compute_stream` to 1. - */ - void* user_compute_stream; - - /** \brief CUDA memory arena configuration parameters - */ - OrtArenaCfg* default_memory_arena_cfg; - - /** \brief Enable TunableOp for using. - * Set it to 1/0 to enable/disable TunableOp. Otherwise, it is disabled by default. - * This option can be overridden by environment variable ORT_CUDA_TUNABLE_OP_ENABLE. - */ - int tunable_op_enable; - - /** \brief Enable TunableOp for tuning. - * Set it to 1/0 to enable/disable TunableOp tuning. Otherwise, it is disabled by default. - * This option can be overridden by environment variable ORT_CUDA_TUNABLE_OP_TUNING_ENABLE. - */ - int tunable_op_tuning_enable; - - /** \brief Max tuning duration time limit for each instance of TunableOp. - * Defaults to 0 to disable the limit. - */ - int tunable_op_max_tuning_duration_ms; - -} OrtCUDAProviderOptions; - -/** \brief ROCM Provider Options - * - * \see OrtApi::SessionOptionsAppendExecutionProvider_ROCM - */ -typedef struct OrtROCMProviderOptions { -#ifdef __cplusplus - OrtROCMProviderOptions() - : device_id{}, - miopen_conv_exhaustive_search{0}, - gpu_mem_limit{SIZE_MAX}, - arena_extend_strategy{}, - do_copy_in_default_stream{1}, - has_user_compute_stream{}, - user_compute_stream{}, - default_memory_arena_cfg{}, - enable_hip_graph{false}, - tunable_op_enable{false}, - tunable_op_tuning_enable{false}, - tunable_op_max_tuning_duration_ms{} {} -#endif - - /** \brief ROCM device Id - * Defaults to 0. - */ - int device_id; - - /** \brief ROCM MIOpen Convolution algorithm exaustive search option. - * Defaults to 0 (false). - */ - int miopen_conv_exhaustive_search; - - /** \brief ROCM memory limit (To use all possible memory pass in maximum size_t) - * Defaults to SIZE_MAX. - * \note If a ::OrtArenaCfg has been applied, it will override this field - */ - size_t gpu_mem_limit; - - /** \brief Strategy used to grow the memory arena - * 0 = kNextPowerOfTwo
- * 1 = kSameAsRequested
- * Defaults to 0. - * \note If a ::OrtArenaCfg has been applied, it will override this field - */ - int arena_extend_strategy; - - /** \brief Flag indicating if copying needs to take place on the same stream as the compute stream in the ROCM EP - * 0 = Use separate streams for copying and compute. - * 1 = Use the same stream for copying and compute. - * Defaults to 1. - * WARNING: Setting this to 0 may result in data races for some models. - * Please see issue #4829 for more details. - */ - int do_copy_in_default_stream; - - /** \brief Flag indicating if there is a user provided compute stream - * Defaults to 0. - */ - int has_user_compute_stream; - - /** \brief User provided compute stream. - * If provided, please set `has_user_compute_stream` to 1. - */ - void* user_compute_stream; - - /** \brief ROCM memory arena configuration parameters - */ - OrtArenaCfg* default_memory_arena_cfg; - - int enable_hip_graph; - - /** \brief Enable TunableOp for using. - * Set it to 1/0 to enable/disable TunableOp. Otherwise, it is disabled by default. - * This option can be overridden by environment variable ORT_ROCM_TUNABLE_OP_ENABLE. - */ - int tunable_op_enable; - - /** \brief Enable TunableOp for tuning. - * Set it to 1/0 to enable/disable TunableOp tuning. Otherwise, it is disabled by default. - * This option can be overridden by environment variable ORT_ROCM_TUNABLE_OP_TUNING_ENABLE. - */ - int tunable_op_tuning_enable; - - /** \brief Max tuning duration time limit for each instance of TunableOp. - * Defaults to 0 to disable the limit. - */ - int tunable_op_max_tuning_duration_ms; - -} OrtROCMProviderOptions; - -/** \brief TensorRT Provider Options - * - * \see OrtApi::SessionOptionsAppendExecutionProvider_TensorRT - */ -typedef struct OrtTensorRTProviderOptions { - int device_id; ///< CUDA device id (0 = default device) - int has_user_compute_stream; // indicator of user specified CUDA compute stream. - void* user_compute_stream; // user specified CUDA compute stream. - int trt_max_partition_iterations; // maximum iterations for TensorRT parser to get capability - int trt_min_subgraph_size; // minimum size of TensorRT subgraphs - size_t trt_max_workspace_size; // maximum workspace size for TensorRT. - int trt_fp16_enable; // enable TensorRT FP16 precision. Default 0 = false, nonzero = true - int trt_int8_enable; // enable TensorRT INT8 precision. Default 0 = false, nonzero = true - const char* trt_int8_calibration_table_name; // TensorRT INT8 calibration table name. - int trt_int8_use_native_calibration_table; // use native TensorRT generated calibration table. Default 0 = false, nonzero = true - int trt_dla_enable; // enable DLA. Default 0 = false, nonzero = true - int trt_dla_core; // DLA core number. Default 0 - int trt_dump_subgraphs; // dump TRT subgraph. Default 0 = false, nonzero = true - int trt_engine_cache_enable; // enable engine caching. Default 0 = false, nonzero = true - const char* trt_engine_cache_path; // specify engine cache path - int trt_engine_decryption_enable; // enable engine decryption. Default 0 = false, nonzero = true - const char* trt_engine_decryption_lib_path; // specify engine decryption library path - int trt_force_sequential_engine_build; // force building TensorRT engine sequentially. Default 0 = false, nonzero = true - // This is the legacy struct and don't add new fields here. - // For new field that can be represented by string, please add it in include/onnxruntime/core/providers/tensorrt/tensorrt_provider_options.h - // For non-string field, need to create a new separate api to handle it. -} OrtTensorRTProviderOptions; - -/** \brief MIGraphX Provider Options - * - * \see OrtApi::SessionOptionsAppendExecutionProvider_MIGraphX - */ -typedef struct OrtMIGraphXProviderOptions { - int device_id; // hip device id. - int migraphx_fp16_enable; // MIGraphX FP16 precision. Default 0 = false, nonzero = true - int migraphx_int8_enable; // MIGraphX INT8 precision. Default 0 = false, nonzero = true - int migraphx_use_native_calibration_table; // MIGraphx INT8 cal table. Default 0 = false, noznero = true - const char* migraphx_int8_calibration_table_name; // MIGraphx INT8 calibration table name - int migraphx_save_compiled_model; // migraphx save compiled model. Default 0 = false, noznero = true - const char* migraphx_save_model_path; // migraphx model path name - int migraphx_load_compiled_model; // migraphx int8 cal table. Default 0 = false, noznero = true - const char* migraphx_load_model_path; // migraphx model path name - bool migraphx_exhaustive_tune; // migraphx tuned compile Default = false -} OrtMIGraphXProviderOptions; - -/** \brief OpenVINO Provider Options - * \brief This Struct is frozen since ORT 1.13.0. Its maintained part of Legacy API for compatibility. - * \brief For latest OpenVINO Provider Options update to the ProviderOptions map. - * \brief Latest OpenVINO Provider Options are listed in the - * \htmlonly - * onnxruntime document. - * \endhtmlonly - * \see OrtApi::SessionOptionsAppendExecutionProvider() - */ -typedef struct OrtOpenVINOProviderOptions { -#ifdef __cplusplus - OrtOpenVINOProviderOptions() : device_type{}, - enable_npu_fast_compile{}, - device_id{}, - num_of_threads{}, - cache_dir{}, - context{}, - enable_opencl_throttling{}, - enable_dynamic_shapes{} {} -#endif - /** \brief Device type string - * - * Valid settings are one of: "CPU_FP32", "CPU_FP16", "GPU_FP32", "GPU_FP16" - */ - const char* device_type; - unsigned char enable_npu_fast_compile; ///< 0 = disabled, nonzero = enabled - const char* device_id; - size_t num_of_threads; ///< 0 = Use default number of threads - const char* cache_dir; // path is set to empty by default - void* context; - unsigned char enable_opencl_throttling; ///< 0 = disabled, nonzero = enabled - unsigned char enable_dynamic_shapes; ///< 0 = disabled, nonzero = enabled -} OrtOpenVINOProviderOptions; - -struct OrtApi; -typedef struct OrtApi OrtApi; - -struct OrtTrainingApi; -typedef struct OrtTrainingApi OrtTrainingApi; - -struct OrtModelEditorApi; -typedef struct OrtModelEditorApi OrtModelEditorApi; - -struct OrtCompileApi; -typedef struct OrtCompileApi OrtCompileApi; - -struct OrtEpApi; -typedef struct OrtEpApi OrtEpApi; - -/** \brief The helper interface to get the right version of OrtApi - * - * Get a pointer to this structure through ::OrtGetApiBase - */ -struct OrtApiBase { - /** \brief Get a pointer to the requested version of the ::OrtApi - * - * \param[in] version Must be ::ORT_API_VERSION - * \return The ::OrtApi for the version requested, nullptr will be returned if this version is unsupported, for example when using a runtime - * older than the version created with this header file. - * - * One can call GetVersionString() to get the version of the Onnxruntime library for logging - * and error reporting purposes. - */ - const OrtApi*(ORT_API_CALL* GetApi)(uint32_t version)NO_EXCEPTION; - - /** \brief Returns a null terminated string of the version of the Onnxruntime library (eg: "1.8.1") - * - * \return UTF-8 encoded version string. Do not deallocate the returned buffer. - */ - const char*(ORT_API_CALL* GetVersionString)(void)NO_EXCEPTION; -}; - -typedef struct OrtApiBase OrtApiBase; - -/** \brief The Onnxruntime library's entry point to access the C API - * - * Call this to get the a pointer to an ::OrtApiBase - */ -ORT_EXPORT const OrtApiBase* ORT_API_CALL OrtGetApiBase(void) NO_EXCEPTION; - -/** \brief Thread work loop function - * - * Onnxruntime will provide the working loop on custom thread creation - * Argument is an onnxruntime built-in type which will be provided when thread pool calls OrtCustomCreateThreadFn - */ -typedef void (*OrtThreadWorkerFn)(void* ort_worker_fn_param); - -typedef const struct OrtCustomHandleType { - char __place_holder; -}* OrtCustomThreadHandle; - -/** \brief Ort custom thread creation function - * - * The function should return a thread handle to be used in onnxruntime thread pools - * Onnxruntime will throw exception on return value of nullptr or 0, indicating that the function failed to create a thread - */ -typedef OrtCustomThreadHandle (*OrtCustomCreateThreadFn)(void* ort_custom_thread_creation_options, OrtThreadWorkerFn ort_thread_worker_fn, void* ort_worker_fn_param); - -/** \brief Custom thread join function - * - * Onnxruntime thread pool destructor will call the function to join a custom thread. - * Argument ort_custom_thread_handle is the value returned by OrtCustomCreateThreadFn - */ -typedef void (*OrtCustomJoinThreadFn)(OrtCustomThreadHandle ort_custom_thread_handle); - -typedef OrtStatus*(ORT_API_CALL* RegisterCustomOpsFn)(OrtSessionOptions* options, const OrtApiBase* api); - -/** \brief Callback function for RunAsync - * - * \param[in] user_data User specific data that passed back to the callback - * \param[out] outputs On succeed, outputs host inference results, on error, the value will be nullptr - * \param[out] num_outputs Number of outputs, on error, the value will be zero - * \param[out] status On error, status will provide details - */ -typedef void (*RunAsyncCallbackFn)(void* user_data, OrtValue** outputs, size_t num_outputs, OrtStatusPtr status); - -/** \brief The C API - * - * All C API functions are defined inside this structure as pointers to functions. - * Call OrtApiBase::GetApi to get a pointer to it - * - * \nosubgrouping - */ -struct OrtApi { - /// \name OrtStatus - /// @{ - - /** - * \brief Create an OrtStatus from a null terminated string - * - * \param[in] code - * \param[in] msg A null-terminated string. Its contents will be copied. - * \return A new OrtStatus object, must be destroyed with OrtApi::ReleaseStatus - */ - OrtStatus*(ORT_API_CALL* CreateStatus)(OrtErrorCode code, _In_ const char* msg)NO_EXCEPTION ORT_ALL_ARGS_NONNULL; - - /** \brief Get OrtErrorCode from OrtStatus - * - * \param[in] status - * \return OrtErrorCode that \p status was created with - */ - OrtErrorCode(ORT_API_CALL* GetErrorCode)(_In_ const OrtStatus* status) NO_EXCEPTION ORT_ALL_ARGS_NONNULL; - - /** \brief Get error string from OrtStatus - * - * \param[in] status - * \return The error message inside the `status`. Do not free the returned value. - */ - const char*(ORT_API_CALL* GetErrorMessage)(_In_ const OrtStatus* status)NO_EXCEPTION ORT_ALL_ARGS_NONNULL; - - /// @} - /// \name OrtEnv - /// @{ - - /** \brief Create an OrtEnv - * - * \note Invoking this function will return the same instance of the environment as that returned by a previous call - * to another env creation function; all arguments to this function will be ignored. - * \param[in] log_severity_level The log severity level. - * \param[in] logid The log identifier. - * \param[out] out Returned newly created OrtEnv. Must be freed with OrtApi::ReleaseEnv - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateEnv, OrtLoggingLevel log_severity_level, _In_ const char* logid, _Outptr_ OrtEnv** out); - - /** \brief Create an OrtEnv - * - * \note Invoking this function will return the same instance of the environment as that returned by a previous call - * to another env creation function; all arguments to this function will be ignored. If you want to provide your - * own logging function, consider setting it using the SetUserLoggingFunction API instead. - * \param[in] logging_function A pointer to a logging function. - * \param[in] logger_param A pointer to arbitrary data passed as the ::OrtLoggingFunction `param` parameter to - * `logging_function`. This parameter is optional. - * \param[in] log_severity_level The log severity level. - * \param[in] logid The log identifier. - * \param[out] out Returned newly created OrtEnv. Must be freed with OrtApi::ReleaseEnv - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateEnvWithCustomLogger, _In_ OrtLoggingFunction logging_function, _In_opt_ void* logger_param, - _In_ OrtLoggingLevel log_severity_level, _In_ const char* logid, _Outptr_ OrtEnv** out); - - /** \brief Enable Telemetry - * - * \note Telemetry events are on by default since they are lightweight - * \param[in] env - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(EnableTelemetryEvents, _In_ const OrtEnv* env); - /** \brief Disable Telemetry - * - * \see OrtApi::EnableTelemetryEvents - * \param[in] env - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(DisableTelemetryEvents, _In_ const OrtEnv* env); - - /// @} - /// \name OrtSession - /// @{ - - /** \brief Create an OrtSession from a model file - * - * \param[in] env - * \param[in] model_path - * \param[in] options - * \param[out] out Returned newly created OrtSession. Must be freed with OrtApi::ReleaseSession - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - // TODO: document the path separator convention? '/' vs '\' - // TODO: should specify the access characteristics of model_path. Is this read only during the - // execution of CreateSession, or does the OrtSession retain a handle to the file/directory - // and continue to access throughout the OrtSession lifetime? - // What sort of access is needed to model_path : read or read/write? - ORT_API2_STATUS(CreateSession, _In_ const OrtEnv* env, _In_ const ORTCHAR_T* model_path, - _In_ const OrtSessionOptions* options, _Outptr_ OrtSession** out); - - /** \brief Create an OrtSession from memory - * - * \param[in] env - * \param[in] model_data - * \param[in] model_data_length - * \param[in] options - * \param[out] out Returned newly created OrtSession. Must be freed with OrtApi::ReleaseSession - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateSessionFromArray, _In_ const OrtEnv* env, - _In_ const void* model_data, size_t model_data_length, - _In_ const OrtSessionOptions* options, _Outptr_ OrtSession** out); - - /** \brief Run the model in an ::OrtSession - * - * Will not return until the model run has completed. Multiple threads might be used to run the model based on - * the options in the ::OrtSession and settings used when creating the ::OrtEnv - * - * \param[in] session - * \param[in] run_options If nullptr, will use a default ::OrtRunOptions - * \param[in] input_names Array of null terminated UTF8 encoded strings of the input names - * \param[in] inputs Array of ::OrtValue%s of the input values - * \param[in] input_len Number of elements in the input_names and inputs arrays - * \param[in] output_names Array of null terminated UTF8 encoded strings of the output names - * \param[in] output_names_len Number of elements in the output_names and outputs array - * \param[out] outputs Array of ::OrtValue%s that the outputs are stored in. This can also be - * an array of nullptr values, in this case ::OrtValue objects will be allocated and pointers - * to them will be set into the `outputs` array. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(Run, _Inout_ OrtSession* session, _In_opt_ const OrtRunOptions* run_options, - _In_reads_(input_len) const char* const* input_names, - _In_reads_(input_len) const OrtValue* const* inputs, size_t input_len, - _In_reads_(output_names_len) const char* const* output_names, size_t output_names_len, - _Inout_updates_all_(output_names_len) OrtValue** outputs); - - /// @} - /// \name OrtSessionOptions - /// @{ - - /** \brief Create an ::OrtSessionOptions object - * - * To use additional providers, you must build ORT with the extra providers enabled. Then call one of these - * functions to enable them in the session:
- * OrtSessionOptionsAppendExecutionProvider_CPU
- * OrtSessionOptionsAppendExecutionProvider_CUDA
- * OrtSessionOptionsAppendExecutionProvider_(remaining providers...)
- * The order they are called indicates the preference order as well. In other words call this method - * on your most preferred execution provider first followed by the less preferred ones. - * If none are called Ort will use its internal CPU execution provider. - * - * \param[out] options The newly created OrtSessionOptions. Must be freed with OrtApi::ReleaseSessionOptions - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateSessionOptions, _Outptr_ OrtSessionOptions** options); - - /** \brief Set filepath to save optimized model after graph level transformations - * - * \param[in] options - * \param[in] optimized_model_filepath - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetOptimizedModelFilePath, _Inout_ OrtSessionOptions* options, - _In_ const ORTCHAR_T* optimized_model_filepath); - - /** \brief Create a copy of an existing ::OrtSessionOptions - * - * \param[in] in_options OrtSessionOptions to copy - * \param[out] out_options Returned newly created ::OrtSessionOptions. Must be freed with OrtApi::ReleaseSessionOptions - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CloneSessionOptions, _In_ const OrtSessionOptions* in_options, - _Outptr_ OrtSessionOptions** out_options); - - /** \brief Set execution mode - * - * Controls whether you want to execute operators in your graph sequentially or in parallel. Usually when the model - * has many branches, setting this option to ExecutionMode.ORT_PARALLEL will give you better performance. - * See [docs/ONNX_Runtime_Perf_Tuning.md] for more details. - * - * \param[in] options - * \param[in] execution_mode - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetSessionExecutionMode, _Inout_ OrtSessionOptions* options, ExecutionMode execution_mode); - - /** \brief Enable profiling for a session - * - * \param[in] options - * \param[in] profile_file_prefix - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(EnableProfiling, _Inout_ OrtSessionOptions* options, _In_ const ORTCHAR_T* profile_file_prefix); - - /** \brief Disable profiling for a session - * - * \param[in] options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(DisableProfiling, _Inout_ OrtSessionOptions* options); - - /** \brief Enable the memory pattern optimization - * - * The idea is if the input shapes are the same, we could trace the internal memory allocation - * and generate a memory pattern for future request. So next time we could just do one allocation - * with a big chunk for all the internal memory allocation. - * \note Memory pattern optimization is only available when Sequential Execution mode is enabled (see OrtApi::SetSessionExecutionMode) - * - * \see OrtApi::DisableMemPattern - * - * \param[in] options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(EnableMemPattern, _Inout_ OrtSessionOptions* options); - - /** \brief Disable the memory pattern optimization - * - * \see OrtApi::EnableMemPattern - * - * \param[in] options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(DisableMemPattern, _Inout_ OrtSessionOptions* options); - - /** \brief Enable the memory arena on CPU - * - * Arena may pre-allocate memory for future usage. - * - * \param[in] options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(EnableCpuMemArena, _Inout_ OrtSessionOptions* options); - - /** \brief Disable the memory arena on CPU - * - * \param[in] options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(DisableCpuMemArena, _Inout_ OrtSessionOptions* options); - - /** \brief Set session log id - * - * \param[in] options - * \param[in] logid The log identifier. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetSessionLogId, _Inout_ OrtSessionOptions* options, const char* logid); - - /** \brief Set session log verbosity level - * - * Applies to session load, initialization, etc - * - * \param[in] options - * \param[in] session_log_verbosity_level \snippet{doc} snippets.dox Log Verbosity Level - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetSessionLogVerbosityLevel, _Inout_ OrtSessionOptions* options, int session_log_verbosity_level); - - /** \brief Set session log severity level - * - * \param[in] options - * \param[in] session_log_severity_level The log severity level (refer to ::OrtLoggingLevel for possible values). - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetSessionLogSeverityLevel, _Inout_ OrtSessionOptions* options, int session_log_severity_level); - - /** \brief Set the optimization level to apply when loading a graph - * - * Please see https://onnxruntime.ai/docs/performance/model-optimizations/graph-optimizations.html for an in-depth explanation - * \param[in,out] options The session options object - * \param[in] graph_optimization_level The optimization level - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetSessionGraphOptimizationLevel, _Inout_ OrtSessionOptions* options, - GraphOptimizationLevel graph_optimization_level); - - /** \brief Sets the number of threads used to parallelize the execution within nodes - * - * When running a single node operation, ex. add, this sets the maximum number of threads to use. - * - * \note If built with OpenMP, this has no effect on the number of threads used. In this case - * use the OpenMP env variables to configure the number of intra op num threads. - * - * \param[in] options - * \param[in] intra_op_num_threads Number of threads to use
- * A value of 0 will use the default number of threads
- * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetIntraOpNumThreads, _Inout_ OrtSessionOptions* options, int intra_op_num_threads); - - /** \brief Sets the number of threads used to parallelize the execution of the graph - * - * If nodes can be run in parallel, this sets the maximum number of threads to use to run them in parallel. - * - * \note If sequential execution is enabled this value is ignored, it acts as if it was set to 1. - * - * \param[in] options - * \param[in] inter_op_num_threads Number of threads to use
- * A value of 0 will use the default number of threads
- * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetInterOpNumThreads, _Inout_ OrtSessionOptions* options, int inter_op_num_threads); - - /// @} - /// \name OrtCustomOpDomain - /// @{ - - /** \brief Create a custom op domain - * - * \param[in] domain - * \param[out] out Newly created domain. Must be freed with OrtApi::ReleaseCustomOpDomain - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateCustomOpDomain, _In_ const char* domain, _Outptr_ OrtCustomOpDomain** out); - - /** \brief Add a custom op to a custom op domain - * - * \note The OrtCustomOp* pointer must remain valid until the ::OrtCustomOpDomain using it is released - * - * \param[in] custom_op_domain - * \param[in] op - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CustomOpDomain_Add, _Inout_ OrtCustomOpDomain* custom_op_domain, _In_ const OrtCustomOp* op); - - /// @} - /// \name OrtSessionOptions - /// @{ - - /** \brief Add custom op domain to a session options - * - * \note The OrtCustomOpDomain* must not be deleted until all sessions using it are released - * - * \param[in] options - * \param[in] custom_op_domain - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(AddCustomOpDomain, _Inout_ OrtSessionOptions* options, _In_ OrtCustomOpDomain* custom_op_domain); - - /** \deprecated Use OrtApi::RegisterCustomOpsLibrary_V2. - * - * Registers custom ops from a shared library. - * - * Loads a shared library (dll on windows, so on linux, etc) named 'library_path' and looks for this entry point: - * OrtStatus* RegisterCustomOps(OrtSessionOptions * options, const OrtApiBase* api); - * It then passes in the provided session options to this function along with the api base. - * The handle to the loaded library is returned in library_handle. It can be freed by the caller after all sessions using the passed in - * session options are destroyed, or if an error occurs and it is non null. - * - * \param[in] options - * \param[in] library_path - * \param[out] library_handle OS specific handle to the loaded library (Use FreeLibrary on Windows, dlclose on Linux, etc.. to unload) - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(RegisterCustomOpsLibrary, _Inout_ OrtSessionOptions* options, _In_ const char* library_path, _Outptr_ void** library_handle); - - /// @} - /// \name OrtSession - /// @{ - - /** \brief Get input count for a session - * - * This number must also match the number of inputs passed to OrtApi::Run - * - * \see OrtApi::SessionGetInputTypeInfo, OrtApi::SessionGetInputName, OrtApi::Session - * - * \param[in] session - * \param[out] out Number of inputs - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionGetInputCount, _In_ const OrtSession* session, _Out_ size_t* out); - - /** \brief Get output count for a session - * - * This number must also match the number of outputs returned by OrtApi::Run - * - * \see OrtApi::SessionGetOutputTypeInfo, OrtApi::SessionGetOutputName, OrtApi::Session - * - * \param[in] session - * \param[out] out Number of outputs - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionGetOutputCount, _In_ const OrtSession* session, _Out_ size_t* out); - - /** \brief Get overridable initializer count - * - * \see OrtApi::SessionGetOverridableInitializerTypeInfo, OrtApi::SessionGetOverridableInitializerName - * - * \param[in] session - * \param[in] out - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionGetOverridableInitializerCount, _In_ const OrtSession* session, _Out_ size_t* out); - - /** \brief Get input type information - * - * \param[in] session - * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetInputCount returns (exclusive) - * \param[out] type_info Must be freed with OrtApi::ReleaseTypeInfo - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionGetInputTypeInfo, _In_ const OrtSession* session, size_t index, _Outptr_ OrtTypeInfo** type_info); - - /** \brief Get output type information - * - * \param[in] session - * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetOutputCount returns (exclusive) - * \param[out] type_info Must be freed with OrtApi::ReleaseTypeInfo - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionGetOutputTypeInfo, _In_ const OrtSession* session, size_t index, _Outptr_ OrtTypeInfo** type_info); - - /** \brief Get overridable initializer type information - * - * \param[in] session - * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetOverridableInitializerCount returns (exclusive) - * \param[out] type_info Must be freed with OrtApi::ReleaseTypeInfo - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionGetOverridableInitializerTypeInfo, _In_ const OrtSession* session, size_t index, _Outptr_ OrtTypeInfo** type_info); - - /** \brief Get input name - * - * \param[in] session - * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetInputCount returns (exclusive) - * \param[in] allocator - * \param[out] value Set to a null terminated UTF-8 encoded string allocated using `allocator`. Must be freed using `allocator`. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionGetInputName, _In_ const OrtSession* session, size_t index, _Inout_ OrtAllocator* allocator, _Outptr_ char** value); - - /** \brief Get output name - * - * \param[in] session - * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetOutputCount returns (exclusive) - * \param[in] allocator - * \param[out] value Set to a null terminated UTF-8 encoded string allocated using `allocator`. Must be freed using `allocator`. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionGetOutputName, _In_ const OrtSession* session, size_t index, _Inout_ OrtAllocator* allocator, _Outptr_ char** value); - - /** \brief Get overridable initializer name - * - * \param[in] session - * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetOverridableInitializerCount returns (exclusive) - * \param[in] allocator - * \param[out] value Set to a null terminated UTF-8 encoded string allocated using `allocator`. Must be freed using `allocator`. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionGetOverridableInitializerName, _In_ const OrtSession* session, size_t index, - _Inout_ OrtAllocator* allocator, _Outptr_ char** value); - - /// @} - /// \name OrtRunOptions - /// @{ - - /** \brief Create an OrtRunOptions - * - * \param[out] out Returned newly created ::OrtRunOptions. Must be freed with OrtApi::ReleaseRunOptions - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateRunOptions, _Outptr_ OrtRunOptions** out); - - /** \brief Set per-run log verbosity level - * - * \see OrtApi::RunOptionsGetRunLogVerbosityLevel - * - * \param[in] options - * \param[in] log_verbosity_level \snippet{doc} snippets.dox Log Verbosity Level - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(RunOptionsSetRunLogVerbosityLevel, _Inout_ OrtRunOptions* options, int log_verbosity_level); - - /** \brief Set per-run log severity level - * - * \see OrtApi::RunOptionsGetRunLogSeverityLevel - * - * \param[in] options - * \param[in] log_severity_level The log severity level (refer to ::OrtLoggingLevel for possible values). - */ - ORT_API2_STATUS(RunOptionsSetRunLogSeverityLevel, _Inout_ OrtRunOptions* options, int log_severity_level); - - /** \brief Set per-run tag - * - * This is used in a per-run log identifier. - * - * \see OrtApi::RunOptionsGetRunTag - * - * \param[in] options - * \param[in] run_tag The run tag. - */ - ORT_API2_STATUS(RunOptionsSetRunTag, _Inout_ OrtRunOptions* options, _In_ const char* run_tag); - - /** \brief Get per-run log verbosity level - * - * \see OrtApi::RunOptionsSetRunLogVerbosityLevel - * - * \param[in] options - * \param[out] log_verbosity_level \snippet{doc} snippets.dox Log Verbosity Level - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(RunOptionsGetRunLogVerbosityLevel, _In_ const OrtRunOptions* options, - _Out_ int* log_verbosity_level); - - /** \brief Get per-run log severity level - * - * \see OrtApi::RunOptionsSetRunLogSeverityLevel - * - * \param[in] options - * \param[out] log_severity_level The log severity level (refer to ::OrtLoggingLevel for possible values). - */ - ORT_API2_STATUS(RunOptionsGetRunLogSeverityLevel, _In_ const OrtRunOptions* options, _Out_ int* log_severity_level); - - /** \brief Get per-run tag - * - * This is used in a per-run log identifier. - * - * \see OrtApi::RunOptionsSetRunTag - * - * \param[in] options - * \param[out] run_tag The run tag. - * Do not free this value, it is owned by `options`. It will be invalidated if the run tag - * changes (i.e., with OrtApi::RunOptionsSetRunTag) or `options` is freed. - */ - ORT_API2_STATUS(RunOptionsGetRunTag, _In_ const OrtRunOptions* options, _Out_ const char** run_tag); - - /** \brief Set terminate flag - * - * If a currently executing session needs to be force terminated, this can be called from another thread to force it to fail with an error. - * - * \param[in] options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(RunOptionsSetTerminate, _Inout_ OrtRunOptions* options); - - /** \brief Clears the terminate flag - * - * Used so the OrtRunOptions instance can be used in a new OrtApi::Run call without it instantly terminating - * - * \param[in] options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(RunOptionsUnsetTerminate, _Inout_ OrtRunOptions* options); - - /// @} - /// \name OrtValue - /// @{ - - /** \brief Create a tensor - * - * Create a tensor using a supplied ::OrtAllocator - * - * \param[in] allocator - * \param[in] shape Pointer to the tensor shape dimensions. - * \param[in] shape_len The number of tensor shape dimensions. - * \param[in] type - * \param[out] out Returns newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateTensorAsOrtValue, _Inout_ OrtAllocator* allocator, _In_ const int64_t* shape, size_t shape_len, - ONNXTensorElementDataType type, _Outptr_ OrtValue** out); - - /** \brief Create a tensor backed by a user supplied buffer - * - * Create a tensor with user's buffer. You can fill the buffer either before calling this function or after. - * p_data is owned by caller. ReleaseValue won't release p_data. - * - * If you wish to transfer ownership of p_data to ORT use CreateTensorWithDataAndDeleterAsOrtValue. - * - * \param[in] info Memory description of where the p_data buffer resides (CPU vs GPU etc). - * \param[in] p_data Pointer to the data buffer. - * \param[in] p_data_len The number of bytes in the data buffer. - * \param[in] shape Pointer to the tensor shape dimensions. - * \param[in] shape_len The number of tensor shape dimensions. - * \param[in] type The data type. - * \param[out] out Returns newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateTensorWithDataAsOrtValue, _In_ const OrtMemoryInfo* info, _Inout_ void* p_data, - size_t p_data_len, _In_ const int64_t* shape, size_t shape_len, ONNXTensorElementDataType type, - _Outptr_ OrtValue** out); - - /** \brief Return if an ::OrtValue is a tensor type - * - * \param[in] value A tensor type (string tensors are not supported) - * \param[out] out Set to 1 iff ::OrtValue is a tensor, 0 otherwise - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(IsTensor, _In_ const OrtValue* value, _Out_ int* out); - - /** \brief Get a pointer to the raw data inside a tensor - * - * Used to read/write/modify the internal tensor data directly. - * \note The returned pointer is valid until the \p value is destroyed. - * - * \param[in] value A tensor type (string tensors are not supported) - * \param[out] out Filled in with a pointer to the internal storage - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetTensorMutableData, _In_ OrtValue* value, _Outptr_ void** out); - - /** \brief Set all strings at once in a string tensor - * - * \param[in,out] value A tensor of type ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING - * \param[in] s An array of strings. Each string in this array must be null terminated. - * \param[in] s_len Count of strings in s (Must match the size of \p value's tensor shape) - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(FillStringTensor, _Inout_ OrtValue* value, _In_ const char* const* s, size_t s_len); - - /** \brief Get total byte length for all strings in a string tensor - * - * Typically used with OrtApi::GetStringTensorContent - * - * \param[in] value A tensor of type ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING - * \param[out] len Total byte length of all strings (does not include trailing nulls) - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetStringTensorDataLength, _In_ const OrtValue* value, _Out_ size_t* len); - - /** \brief Get all strings from a string tensor - * - * An example of the results:
- * Given \p value is a string tensor with the strings { "This" "is" "a" "test" }
- * \p s must have a size of 11 bytes
- * \p offsets must have 4 elements
- * After the call, these values will be filled in:
- * \p s will contain "Thisisatest"
- * \p offsets will contain { 0, 4, 6, 7 }
- * The length of the last string is just s_len - offsets[last] - * - * \param[in] value A tensor of type ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING - * \param[in] s Buffer to sequentially write all tensor strings to. Each string is NOT null-terminated. - * \param[in] s_len Number of bytes of buffer pointed to by \p s (Get it from OrtApi::GetStringTensorDataLength) - * \param[out] offsets Array of start offsets into the strings written to \p s - * \param[in] offsets_len Number of elements in offsets - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetStringTensorContent, _In_ const OrtValue* value, _Out_writes_bytes_all_(s_len) void* s, - size_t s_len, _Out_writes_all_(offsets_len) size_t* offsets, size_t offsets_len); - - /// @} - /// \name OrtTypeInfo - /// @{ - - /** \brief Get ::OrtTensorTypeAndShapeInfo from an ::OrtTypeInfo - * - * \param[in] type_info - * \param[out] out Do not free this value, it will be valid until type_info is freed. - * If type_info does not represent tensor, this value will be set to nullptr. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CastTypeInfoToTensorInfo, _In_ const OrtTypeInfo* type_info, - _Outptr_result_maybenull_ const OrtTensorTypeAndShapeInfo** out); - - /** \brief Get ::ONNXType from ::OrtTypeInfo - * - * \param[in] type_info - * \param[out] out - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetOnnxTypeFromTypeInfo, _In_ const OrtTypeInfo* type_info, _Out_ enum ONNXType* out); - - /// @} - /// \name OrtTensorTypeAndShapeInfo - /// @{ - - /** \brief Create an ::OrtTensorTypeAndShapeInfo object - * - * \param[out] out Returns newly created ::OrtTensorTypeAndShapeInfo. Must be freed with OrtApi::ReleaseTensorTypeAndShapeInfo - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateTensorTypeAndShapeInfo, _Outptr_ OrtTensorTypeAndShapeInfo** out); - - /** \brief Set element type in ::OrtTensorTypeAndShapeInfo - * - * \param[in] info - * \param[in] type - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetTensorElementType, _Inout_ OrtTensorTypeAndShapeInfo* info, enum ONNXTensorElementDataType type); - - /** \brief Set shape information in ::OrtTensorTypeAndShapeInfo - * - * \param[in] info - * \param[in] dim_values Array with `dim_count` elements. Can contain negative values. - * \param[in] dim_count Number of elements in `dim_values` - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetDimensions, OrtTensorTypeAndShapeInfo* info, _In_ const int64_t* dim_values, size_t dim_count); - - /** \brief Get element type in ::OrtTensorTypeAndShapeInfo - * - * \see OrtApi::SetTensorElementType - * - * \param[in] info - * \param[out] out - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetTensorElementType, _In_ const OrtTensorTypeAndShapeInfo* info, - _Out_ enum ONNXTensorElementDataType* out); - - /** \brief Get dimension count in ::OrtTensorTypeAndShapeInfo - * - * \see OrtApi::GetDimensions - * - * \param[in] info - * \param[out] out - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetDimensionsCount, _In_ const OrtTensorTypeAndShapeInfo* info, _Out_ size_t* out); - - /** \brief Get dimensions in ::OrtTensorTypeAndShapeInfo - * - * \param[in] info - * \param[out] dim_values Array with `dim_values_length` elements. On return, filled with the dimensions stored in the ::OrtTensorTypeAndShapeInfo - * \param[in] dim_values_length Number of elements in `dim_values`. Use OrtApi::GetDimensionsCount to get this value - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetDimensions, _In_ const OrtTensorTypeAndShapeInfo* info, _Out_ int64_t* dim_values, - size_t dim_values_length); - - /** \brief Get symbolic dimension names in ::OrtTensorTypeAndShapeInfo - * - * \param[in] info - * \param[in] dim_params Array with `dim_params_length` elements. On return filled with pointers to null terminated strings of the dimension names - * \param[in] dim_params_length Number of elements in `dim_params`. Use OrtApi::GetDimensionsCount to get this value - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetSymbolicDimensions, _In_ const OrtTensorTypeAndShapeInfo* info, - _Out_writes_all_(dim_params_length) const char* dim_params[], size_t dim_params_length); - - /** \brief Get total number of elements in a tensor shape from an ::OrtTensorTypeAndShapeInfo - * - * Return the number of elements specified by the tensor shape (all dimensions multiplied by each other). - * For 0 dimensions, 1 is returned. If any dimension is less than 0, the result is always -1. - * - * Examples:
- * [] = 1
- * [1,3,4] = 12
- * [2,0,4] = 0
- * [-1,3,4] = -1
- * - * \param[in] info - * \param[out] out Number of elements - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetTensorShapeElementCount, _In_ const OrtTensorTypeAndShapeInfo* info, _Out_ size_t* out); - - /// @} - /// \name OrtValue - /// @{ - - /** \brief Get type and shape information from a tensor ::OrtValue - * - * \param[in] value Must be a tensor (not a map/sequence/etc) or will return failure - * \param[out] out Newly created ::OrtTensorTypeAndShapeInfo. Must be freed with OrtApi::ReleaseTensorTypeAndShapeInfo - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetTensorTypeAndShape, _In_ const OrtValue* value, _Outptr_ OrtTensorTypeAndShapeInfo** out); - - /** \brief Get type information of an OrtValue - * - * \param[in] value - * \param[out] out Newly created ::OrtTypeInfo. Must be freed with OrtApi::ReleaseTypeInfo - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetTypeInfo, _In_ const OrtValue* value, _Outptr_result_maybenull_ OrtTypeInfo** out); - - /** \brief Get ONNXType of an ::OrtValue - * - * \param[in] value - * \param[out] out - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetValueType, _In_ const OrtValue* value, _Out_ enum ONNXType* out); - - /// @} - /// \name OrtMemoryInfo - /// @{ - - /** \brief Create an ::OrtMemoryInfo - * - * \param[in] name - * \param[in] type - * \param[in] id - * \param[in] mem_type - * \param[out] out Newly created ::OrtMemoryInfo. Must be freed with OrtAPi::ReleaseMemoryInfo - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateMemoryInfo, _In_ const char* name, enum OrtAllocatorType type, int id, - enum OrtMemType mem_type, _Outptr_ OrtMemoryInfo** out); - - /** \brief Create an ::OrtMemoryInfo for CPU memory - * - * Special case version of OrtApi::CreateMemoryInfo for CPU based memory. Same as using OrtApi::CreateMemoryInfo with name = "Cpu" and id = 0. - * - * \param[in] type - * \param[in] mem_type - * \param[out] out - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateCpuMemoryInfo, enum OrtAllocatorType type, enum OrtMemType mem_type, - _Outptr_ OrtMemoryInfo** out); - - /** \brief Compare ::OrtMemoryInfo objects for equality - * - * Compares all settings of each ::OrtMemoryInfo for equality - * - * \param[in] info1 - * \param[in] info2 - * \param[out] out Set to 0 if equal, -1 if not equal - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CompareMemoryInfo, _In_ const OrtMemoryInfo* info1, _In_ const OrtMemoryInfo* info2, _Out_ int* out); - - /** \brief Get name from ::OrtMemoryInfo - * - * \param[in] ptr - * \param[out] out Writes null terminated string to this pointer. Do NOT free the returned pointer. It is valid for the lifetime of the ::OrtMemoryInfo - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(MemoryInfoGetName, _In_ const OrtMemoryInfo* ptr, _Out_ const char** out); - - /** \brief Get the id from ::OrtMemoryInfo - */ - ORT_API2_STATUS(MemoryInfoGetId, _In_ const OrtMemoryInfo* ptr, _Out_ int* out); - - /** \brief Get the ::OrtMemType from ::OrtMemoryInfo - */ - ORT_API2_STATUS(MemoryInfoGetMemType, _In_ const OrtMemoryInfo* ptr, _Out_ OrtMemType* out); - - /** \brief Get the ::OrtAllocatorType from ::OrtMemoryInfo - */ - ORT_API2_STATUS(MemoryInfoGetType, _In_ const OrtMemoryInfo* ptr, _Out_ OrtAllocatorType* out); - - /// @} - /// \name OrtAllocator - /// @{ - - /// \brief Calls OrtAllocator::Alloc function - ORT_API2_STATUS(AllocatorAlloc, _Inout_ OrtAllocator* ort_allocator, size_t size, _Outptr_ void** out); - /// \brief Calls OrtAllocator::Free function - ORT_API2_STATUS(AllocatorFree, _Inout_ OrtAllocator* ort_allocator, void* p); - /// \brief Calls OrtAllocator::Info function - ORT_API2_STATUS(AllocatorGetInfo, _In_ const OrtAllocator* ort_allocator, _Outptr_ const struct OrtMemoryInfo** out); - - /** \brief Get the default allocator - * - * The default allocator is a CPU based, non-arena. Always returns the same pointer to the same default allocator. - * - * \param[out] out Returned value should NOT be freed - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetAllocatorWithDefaultOptions, _Outptr_ OrtAllocator** out); - - /// @} - /// \name OrtSessionOptions - /// @{ - - /** \brief Override session symbolic dimensions - * - * Override symbolic dimensions (by specific denotation strings) with actual values if known at session initialization time to enable - * optimizations that can take advantage of fixed values (such as memory planning, etc) - * - * \param[in] options - * \param[in] dim_denotation - * \param[in] dim_value - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(AddFreeDimensionOverride, _Inout_ OrtSessionOptions* options, _In_ const char* dim_denotation, - _In_ int64_t dim_value); - - /// @} - /// \name OrtValue - /// @{ - - /* Internal information (not seen in Doxygen) - * - * APIs to support non-tensor types - map and sequence. - * Currently only the following types are supported - * Note: the following types should be kept in sync with data_types.h - * Map types - * ========= - * std::map - * std::map - * std::map - * std::map - * std::map - * std::map - * std::map - * std::map - * - * Sequence types - * ============== - * std::vector - * std::vector - * std::vector - * std::vector - * std::vector> - * std::vector - */ - - /** \brief Get non tensor data from an ::OrtValue - * - * If `value` is of type ONNX_TYPE_MAP, you need to retrieve the keys and values - * separately. Use index=0 to retrieve keys and index=1 to retrieve values. - * If `value` is of type ONNX_TYPE_SEQUENCE, use index to retrieve the index'th element - * of the sequence. - * - * \param[in] value - * \param[in] index See above for usage based on `value` type - * \param[in] allocator Allocator used to allocate ::OrtValue - * \param[out] out Created ::OrtValue that holds the element requested. Must be freed with OrtApi::ReleaseValue - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetValue, _In_ const OrtValue* value, int index, _Inout_ OrtAllocator* allocator, - _Outptr_ OrtValue** out); - - /** \brief Get non tensor value count from an ::OrtValue - * - * If `value` is of type ONNX_TYPE_MAP 2 will always be returned. For ONNX_TYPE_SEQUENCE - * the number of elements in the sequence will be returned - * - * \param[in] value - * \param[out] out - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetValueCount, _In_ const OrtValue* value, _Out_ size_t* out); - - /** \brief Create a map or sequence ::OrtValue - * - * To construct a map (ONNX_TYPE_MAP), use num_values = 2 and `in` should be an array of 2 ::OrtValue%s - * representing keys and values.
- * - * To construct a sequence (ONNX_TYPE_SEQUENCE), use num_values = N where N is the number of the elements in the - * sequence. 'in' should be an array of N ::OrtValue%s. - * - * \param[in] in See above for details - * \param[in] num_values - * \param[in] value_type Must be either ONNX_TYPE_MAP or ONNX_TYPE_SEQUENCE - * \param[out] out Newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateValue, _In_reads_(num_values) const OrtValue* const* in, size_t num_values, - enum ONNXType value_type, _Outptr_ OrtValue** out); - - /** \brief Create an opaque (custom user defined type) ::OrtValue - * - * Constructs an ::OrtValue that contains a value of non-standard type created for - * experiments or while awaiting standardization. ::OrtValue in this case would contain - * an internal representation of the Opaque type. Opaque types are distinguished from - * each other by two strings 1) domain and 2) type name. The combination of the two - * must be unique, so the type representation is properly identified internally. The combination - * must be properly registered from within ORT at both compile/run time or by another API. - * - * To construct the ::OrtValue pass domain and type names, also a pointer to a data container - * the type of which must be known to both ORT and the client program. That data container may or may - * not match the internal representation of the Opaque type. The sizeof(data_container) is passed for - * verification purposes. - * - * \param[in] domain_name Null terminated string of the domain name - * \param[in] type_name Null terminated string of the type name - * \param[in] data_container User pointer Data to populate ::OrtValue - * \param[in] data_container_size Size in bytes of what `data_container` points to - * \param[out] out Newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateOpaqueValue, _In_z_ const char* domain_name, _In_z_ const char* type_name, - _In_ const void* data_container, size_t data_container_size, _Outptr_ OrtValue** out); - - /** \brief Get internal data from an opaque (custom user defined type) ::OrtValue - * - * Copies internal data from an opaque value into a user provided buffer - * - * \see OrtApi::CreateOpaqueValue - * - * \param[in] domain_name Null terminated string of the domain name - * \param[in] type_name Null terminated string of the type name - * \param[in] in The opaque ::OrtValue - * \param[out] data_container Buffer to copy data into - * \param[out] data_container_size Size in bytes of the buffer pointed to by data_container. Must match the size of the internal buffer. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetOpaqueValue, _In_ const char* domain_name, _In_ const char* type_name, _In_ const OrtValue* in, - _Out_ void* data_container, size_t data_container_size); - - /// @} - /// \name OrtKernelInfo - /// Custom operator APIs. - /// @{ - - /** \brief Get a float stored as an attribute in the graph node - * - * \param[in] info ::OrtKernelInfo instance - * \param[in] name Null terminated string of the name of the attribute - * \param[out] out Pointer to memory where the attribute will be stored - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(KernelInfoGetAttribute_float, _In_ const OrtKernelInfo* info, _In_ const char* name, - _Out_ float* out); - - /** \brief Fetch a 64-bit int stored as an attribute in the graph node - * - * \param[in] info ::OrtKernelInfo instance - * \param[in] name Null terminated string of the name of the attribute - * \param[out] out Pointer to memory where the attribute will be stored - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(KernelInfoGetAttribute_int64, _In_ const OrtKernelInfo* info, _In_ const char* name, - _Out_ int64_t* out); - - /** \brief Fetch a string stored as an attribute in the graph node - * - * If `out` is nullptr, the value of `size` is set to the true size of the string - * attribute, and a success status is returned. - * - * If the `size` parameter is greater than or equal to the actual string attribute's size, - * the value of `size` is set to the true size of the string attribute, the provided memory - * is filled with the attribute's contents, and a success status is returned. - * - * If the `size` parameter is less than the actual string attribute's size and `out` - * is not nullptr, the value of `size` is set to the true size of the string attribute - * and a failure status is returned.) - * - * \param[in] info ::OrtKernelInfo instance - * \param[in] name Null terminated string of the name of the attribute - * \param[out] out Pointer to memory where the attribute will be stored - * \param[in,out] size See above comments for details - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(KernelInfoGetAttribute_string, _In_ const OrtKernelInfo* info, _In_ const char* name, _Out_ char* out, - _Inout_ size_t* size); - - /// @} - /// \name OrtKernelContext - /// Custom operator APIs. - /// @{ - - /** \brief Used for custom operators, get the input count of a kernel - * - * \see ::OrtCustomOp - */ - ORT_API2_STATUS(KernelContext_GetInputCount, _In_ const OrtKernelContext* context, _Out_ size_t* out); - - /** \brief Used for custom operators, get the output count of a kernel - * - * \see ::OrtCustomOp - */ - ORT_API2_STATUS(KernelContext_GetOutputCount, _In_ const OrtKernelContext* context, _Out_ size_t* out); - - /** \brief Used for custom operators, get an input of a kernel - * - * The function attempts fetches the input of the kernel. If the input is optional - * and not present, the function returns success and out is set to nullptr. - * - * \param[in] context ::OrtKernelContext instance - * \param[in] index See KernelContext_GetInputCount for boundaries check. - * \param[out] out OrtValue if the input is present otherwise is set nullptr - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(KernelContext_GetInput, _In_ const OrtKernelContext* context, _In_ size_t index, - _Out_ const OrtValue** out); - - /** \brief Used for custom operators, get an output of a kernel - * - * The function attempts fetches the output of the kernel. If the output is optional - * and not present, the function returns success and out is set to nullptr. - * - * \param[in] context ::OrtKernelContext instance - * \param[in] index See KernelContext_GetOutputCount for boundaries check. - * \param[in] dim_values output dimensions - * \param[in] dim_count number of dimensions - * \param[out] out a ptr to OrtValue to output otherwise set to nullptr - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(KernelContext_GetOutput, _Inout_ OrtKernelContext* context, _In_ size_t index, - _In_ const int64_t* dim_values, size_t dim_count, _Outptr_ OrtValue** out); - - /// @} - /// \name OrtEnv - /// @{ - ORT_CLASS_RELEASE(Env); - /// @} - /// \name OrtStatus - /// @{ - ORT_CLASS_RELEASE(Status); - /// @} - /// \name OrtMemoryInfo - /// @{ - ORT_CLASS_RELEASE(MemoryInfo); - /// @} - /// \name OrtSession - /// @{ - ORT_CLASS_RELEASE(Session); // Don't call ReleaseSession from Dllmain (because session owns a thread pool) - /// @} - /// \name OrtValue - /// @{ - ORT_CLASS_RELEASE(Value); - /// @} - /// \name OrtRunOptions - /// @{ - ORT_CLASS_RELEASE(RunOptions); - /// @} - /// \name OrtTypeInfo - /// @{ - ORT_CLASS_RELEASE(TypeInfo); - /// @} - /// \name OrtTensorTypeAndShapeInfo - /// @{ - ORT_CLASS_RELEASE(TensorTypeAndShapeInfo); - /// @} - /// \name OrtSessionOptions - /// @{ - ORT_CLASS_RELEASE(SessionOptions); - /// @} - /// \name OrtCustomOpDomain - /// @{ - ORT_CLASS_RELEASE(CustomOpDomain); - - /// @} - /// \name OrtTypeInfo - /// @{ - - /** \brief Get denotation from type information - * - * Augments ::OrtTypeInfo to return denotations on the type. - * - * This is used by WinML to determine if an input/output is intended to be an Image or a Tensor. - * - * \param[in] type_info - * \param[out] denotation Pointer to the null terminated denotation string is written to this pointer. This pointer is valid until the object is destroyed or the name is changed, do not free. - * \param[out] len Length in bytes of the string returned in `denotation` - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetDenotationFromTypeInfo, _In_ const OrtTypeInfo* type_info, _Out_ const char** const denotation, - _Out_ size_t* len); - - /** \brief Get detailed map information from an ::OrtTypeInfo - * - * This augments ::OrtTypeInfo to return an ::OrtMapTypeInfo when the type is a map. - * The OrtMapTypeInfo has additional information about the map's key type and value type. - * - * This is used by WinML to support model reflection APIs. - * - * \param[out] type_info - * \param[out] out A pointer to the ::OrtMapTypeInfo. Do not free this value. If type_info - * does not contain a map, this value will be set to nullptr. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CastTypeInfoToMapTypeInfo, _In_ const OrtTypeInfo* type_info, - _Outptr_result_maybenull_ const OrtMapTypeInfo** out); - - /** \brief Cast ::OrtTypeInfo to an ::OrtSequenceTypeInfo - * - * This api augments ::OrtTypeInfo to return an ::OrtSequenceTypeInfo when the type is a sequence. - * The ::OrtSequenceTypeInfo has additional information about the sequence's element type. - * - * This is used by WinML to support model reflection APIs. - * - * \param[in] type_info - * \param[out] out A pointer to the OrtSequenceTypeInfo. Do not free this value. If type_info - * doesn not contain a sequence, this value will be set to nullptr. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CastTypeInfoToSequenceTypeInfo, _In_ const OrtTypeInfo* type_info, - _Outptr_result_maybenull_ const OrtSequenceTypeInfo** out); - - /// @} - /// \name OrtMapTypeInfo - /// @{ - - /** \brief Get key type from an ::OrtMapTypeInfo - * - * Key types are restricted to being scalar types. - * - * This is used by WinML to support model reflection APIs. - * - * \param[in] map_type_info - * \param[out] out - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetMapKeyType, _In_ const OrtMapTypeInfo* map_type_info, _Out_ enum ONNXTensorElementDataType* out); - - /** \brief Get the value type from an ::OrtMapTypeInfo - * - * \param[in] map_type_info - * \param[out] type_info A copy of the OrtTypeInfo for the map value type. - * The user must free this value with ReleaseTypeInfo. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetMapValueType, _In_ const OrtMapTypeInfo* map_type_info, _Outptr_ OrtTypeInfo** type_info); - - /// @} - /// \name OrtSequenceTypeInfo - /// @{ - - /** \brief Get element type from an ::OrtSequenceTypeInfo - * - * This is used by WinML to support model reflection APIs. - * - * \param[in] sequence_type_info - * \param[out] type_info A copy of the OrtTypeInfo for the sequence element type. - * The user must free this value with ReleaseTypeInfo. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetSequenceElementType, _In_ const OrtSequenceTypeInfo* sequence_type_info, - _Outptr_ OrtTypeInfo** type_info); - - /// @} - /// \name OrtMapTypeInfo - /// @{ - ORT_CLASS_RELEASE(MapTypeInfo); - /// @} - /// \name OrtSequenceTypeInfo - /// @{ - ORT_CLASS_RELEASE(SequenceTypeInfo); - - /// @} - /// \name OrtSession - /// @{ - - /** \brief End profiling and return filename of the profile data - * - * Profiling is turned on through OrtApi::EnableProfiling - * - * \param[in] session - * \param[in] allocator - * \param[out] out Null terminated string of the filename, allocated using `allocator`. Must be freed using `allocator` - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionEndProfiling, _In_ OrtSession* session, _Inout_ OrtAllocator* allocator, _Outptr_ char** out); - - /** \brief Get ::OrtModelMetadata from an ::OrtSession - * - * \param[in] session - * \param[out] out Newly created ::OrtModelMetadata. Must be freed using OrtApi::ReleaseModelMetadata - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionGetModelMetadata, _In_ const OrtSession* session, _Outptr_ OrtModelMetadata** out); - - /// @} - /// \name OrtModelMetadata - /// @{ - - /** \brief Get `producer name` from an ::OrtModelMetadata - * - * \param[in] model_metadata - * \param[in] allocator - * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(ModelMetadataGetProducerName, _In_ const OrtModelMetadata* model_metadata, - _Inout_ OrtAllocator* allocator, _Outptr_ char** value); - - /** \brief Get `graph name` from an ::OrtModelMetadata - * - * \param[in] model_metadata - * \param[in] allocator - * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(ModelMetadataGetGraphName, _In_ const OrtModelMetadata* model_metadata, - _Inout_ OrtAllocator* allocator, _Outptr_ char** value); - - /** \brief Get `domain` from an ::OrtModelMetadata - * - * \param[in] model_metadata - * \param[in] allocator - * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(ModelMetadataGetDomain, _In_ const OrtModelMetadata* model_metadata, _Inout_ OrtAllocator* allocator, - _Outptr_ char** value); - - /** \brief Get `description` from an ::OrtModelMetadata - * - * \param[in] model_metadata - * \param[in] allocator - * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(ModelMetadataGetDescription, _In_ const OrtModelMetadata* model_metadata, - _Inout_ OrtAllocator* allocator, _Outptr_ char** value); - - /** \brief Return data for a key in the custom metadata map in an ::OrtModelMetadata - * - * \param[in] model_metadata - * \param[in] allocator - * \param[in] key Null terminated string - * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` - * `value` will be set to nullptr if the given key is not found in the custom metadata map. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(ModelMetadataLookupCustomMetadataMap, _In_ const OrtModelMetadata* model_metadata, - _Inout_ OrtAllocator* allocator, _In_ const char* key, _Outptr_result_maybenull_ char** value); - - /** \brief Get version number from an ::OrtModelMetadata - * - * \param[in] model_metadata - * \param[out] value Set to the version number - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(ModelMetadataGetVersion, _In_ const OrtModelMetadata* model_metadata, _Out_ int64_t* value); - - ORT_CLASS_RELEASE(ModelMetadata); - - /// @} - /// \name OrtEnv - /// @{ - - /** \brief Create an OrtEnv - * - * Create an environment with global threadpools that will be shared across sessions. - * Use this in conjunction with OrtApi::DisablePerSessionThreads or else the session will use - * its own thread pools. - * - * \param[in] log_severity_level The log severity level. - * \param[in] logid The log identifier. - * \param[in] tp_options - * \param[out] out Returned newly created OrtEnv. Must be freed with OrtApi::ReleaseEnv - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateEnvWithGlobalThreadPools, OrtLoggingLevel log_severity_level, _In_ const char* logid, - _In_ const OrtThreadingOptions* tp_options, _Outptr_ OrtEnv** out); - - /// @} - /// \name OrtSessionOptions - /// @{ - - /** \brief Use global thread pool on a session - * - * Disable using per session thread pool and use the shared global threadpool. - * This should be used in conjunction with OrtApi::CreateEnvWithGlobalThreadPools. - * - * \param[in] options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(DisablePerSessionThreads, _Inout_ OrtSessionOptions* options); - - /// @} - /// \name OrtThreadingOptions - /// @{ - - /** \brief Create an ::OrtThreadingOptions - * - * \param[out] out Newly created ::OrtThreadingOptions. Must be freed with OrtApi::ReleaseThreadingOptions - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateThreadingOptions, _Outptr_ OrtThreadingOptions** out); - - ORT_CLASS_RELEASE(ThreadingOptions); - - /// @} - /// \name OrtModelMetadata - /// @{ - - /** - * - * \param[in] model_metadata - * \param[in] allocator - * \param[out] keys Array of null terminated strings (array count = num_keys) allocated using `allocator`. - * The strings and the pointer array must be freed using `allocator` - * `keys` will be set to nullptr if the custom metadata map is empty. - * \param[out] num_keys Set to the number of elements in the `keys` array - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(ModelMetadataGetCustomMetadataMapKeys, _In_ const OrtModelMetadata* model_metadata, - _Inout_ OrtAllocator* allocator, _Outptr_result_buffer_maybenull_(*num_keys) char*** keys, _Out_ int64_t* num_keys); - - /// @} - /// \name OrtSessionOptions - /// @{ - - /** - * - * Override symbolic dimensions (by specific name strings) with actual values - * if known at session initialization time to enable optimizations that can - * take advantage of fixed values (such as memory planning, etc) - * - */ - ORT_API2_STATUS(AddFreeDimensionOverrideByName, - _Inout_ OrtSessionOptions* options, _In_ const char* dim_name, - _In_ int64_t dim_value); - - /// @} - /// \name Misc - /// @{ - - /** \brief Get the names of all available providers - * - * \note The providers in the list are not guaranteed to be usable. They may fail to load due to missing system dependencies. - * For example, if the CUDA/cuDNN libraries are not installed, the CUDA provider will report an error when it is added to the session options. - * - * \param[out] out_ptr Set to a pointer to an array of null terminated strings of the available providers. The entries and the - * array itself must be freed using OrtApi::ReleaseAvailableProviders - * \param[out] provider_length Set to the number of entries in the `out_ptr` array - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetAvailableProviders, _Outptr_ char*** out_ptr, _Out_ int* provider_length); - - /** \brief Release data from OrtApi::GetAvailableProviders. This API will never fail - * so you can rely on it in a noexcept code. - * - * \param[in] ptr The `out_ptr` result from OrtApi::GetAvailableProviders. - * \param[in] providers_length The `provider_length` result from OrtApi::GetAvailableProviders - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(ReleaseAvailableProviders, _In_ char** ptr, - _In_ int providers_length); - - /// @} - /// \name OrtValue - /// @{ - - /** \brief Get the length of a single string in a string tensor - * - * \param[in] value A string tensor - * \param[in] index Index of the string in the tensor - * \param[out] out Set to number of bytes of the string element - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetStringTensorElementLength, _In_ const OrtValue* value, size_t index, _Out_ size_t* out); - - /** \brief Get a single string from a string tensor - * - * \param[in] value A string tensor - * \param[in] s_len Number of bytes in the `s` buffer. Must match the value returned by OrtApi::GetStringTensorElementLength. - * \param[in] index Index of the string in the tensor - * \param[out] s The string element contents in UTF-8 encoding. The string is NOT null-terminated. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetStringTensorElement, _In_ const OrtValue* value, size_t s_len, size_t index, _Out_writes_bytes_all_(s_len) void* s); - - /** \brief Set a single string in a string tensor - * - * \param[in] value A string tensor - * \param[in] s A null terminated UTF-8 encoded string - * \param[in] index Index of the string in the tensor to set - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(FillStringTensorElement, _Inout_ OrtValue* value, _In_ const char* s, size_t index); - - /// @} - /// \name OrtSessionOptions - /// @{ - - /** \brief Set a session configuration entry as a pair of strings - * - * If a configuration with same key exists, this will overwrite the configuration with the given config_value. - * - * The config_key and the format of config_value are defined in onnxruntime_session_options_config_keys.h - * - * \param[in] options - * \param[in] config_key A null terminated string representation of the config key - * \param[in] config_value A null terminated string representation of the config value - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(AddSessionConfigEntry, _Inout_ OrtSessionOptions* options, - _In_z_ const char* config_key, _In_z_ const char* config_value); - - /// @} - /// \name OrtAllocator - /// @{ - - /** \brief Create an allocator for an ::OrtSession following an ::OrtMemoryInfo - * - * \param[in] session - * \param[in] mem_info valid ::OrtMemoryInfo instance - * \param[out] out Newly created ::OrtAllocator. Must be freed with OrtApi::ReleaseAllocator - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateAllocator, _In_ const OrtSession* session, _In_ const OrtMemoryInfo* mem_info, - _Outptr_ OrtAllocator** out); - - /** \brief Release an ::OrtAllocator obtained from OrtApi::CreateAllocator - */ - ORT_CLASS_RELEASE(Allocator); - - /// @} - /// \name OrtSession - /// @{ - - /** \brief Run a model using Io Bindings for the inputs & outputs - * - * \see OrtApi::Run - * - * \param[in] session - * \param[in] run_options - * \param[in] binding_ptr - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(RunWithBinding, _Inout_ OrtSession* session, _In_ const OrtRunOptions* run_options, _In_ const OrtIoBinding* binding_ptr); - - /** \brief Create an ::OrtIoBinding instance - * - * An IoBinding object allows one to bind pre-allocated ::OrtValue%s to input names. - * Thus if you want to use a raw on device buffer as input or output you can avoid - * extra copy during runtime. - * - * \param[in] session - * \param[out] out Newly created ::OrtIoBinding. Must be freed with OrtApi::ReleaseIoBinding - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateIoBinding, _Inout_ OrtSession* session, _Outptr_ OrtIoBinding** out); - - /// @} - /// \name OrtIoBinding - /// @{ - - /** \brief Release an ::OrtIoBinding obtained from OrtApi::CreateIoBinding - */ - ORT_CLASS_RELEASE(IoBinding); - - /** \brief Bind an ::OrtValue to an ::OrtIoBinding input - * - * When using OrtApi::RunWithBinding this value is used for the named input - * - * \param[in] binding_ptr - * \param[in] name Name for the model input - * \param[in] val_ptr ::OrtValue of Tensor type. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(BindInput, _Inout_ OrtIoBinding* binding_ptr, _In_ const char* name, _In_ const OrtValue* val_ptr); - - /** \brief Bind an ::OrtValue to an ::OrtIoBinding output - * - * When using OrtApi::RunWithBinding this value is used for the named output - * - * \param[in] binding_ptr - * \param[in] name Null terminated string of the model output name - * \param[in] val_ptr ::OrtValue of Tensor type. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(BindOutput, _Inout_ OrtIoBinding* binding_ptr, _In_ const char* name, _In_ const OrtValue* val_ptr); - - /** \brief Bind an ::OrtIoBinding output to a device - * - * Binds the ::OrtValue to a device which is specified by ::OrtMemoryInfo. - * You can either create an instance of ::OrtMemoryInfo with a device id or obtain one from the allocator that you have created/are using - * This is useful when one or more outputs have dynamic shapes and, it is hard to pre-allocate and bind a chunk of - * memory within ::OrtValue ahead of time. - * - * \see OrtApi::RunWithBinding - * - * \param[in] binding_ptr - * \param[in] name Null terminated string of the device name - * \param[in] mem_info_ptr - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(BindOutputToDevice, _Inout_ OrtIoBinding* binding_ptr, _In_ const char* name, _In_ const OrtMemoryInfo* mem_info_ptr); - - /** \brief Get the names of an ::OrtIoBinding's outputs - * - * Returns the names of the outputs in the order they were bound. This is useful after running the model - * with bound outputs because the returned names are in order in which output ::OrtValue are returned. This is useful if - * the order of outputs and their names is not known. - * - * \param[in] binding_ptr - * \param[in] allocator Allocator used to allocate continuous buffers for output strings and lengths. - * \param[out] buffer Returns an array of non-null terminated UTF-8 strings. The number of strings stored is returned in the count parameter. - * This buffer is allocated using `allocator` and must be freed using it. - * \param[out] lengths Returns an array of `count` lengths of the strings returned in `buffer` - * This buffer is allocated using `allocator` and must be freed using it. - * \param[out] count Number of strings returned. If `binding_ptr` has no bound outputs, zero is returned, - * no memory allocation is performed and buffer and lengths are set to nullptr. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetBoundOutputNames, _In_ const OrtIoBinding* binding_ptr, _In_ OrtAllocator* allocator, - _Out_ char** buffer, _Out_writes_all_(count) size_t** lengths, _Out_ size_t* count); - - /** \brief Get the output ::OrtValue objects from an ::OrtIoBinding - * - * Returns an array of pointers to individually allocated ::OrtValue%s that contain results of a model execution with OrtApi::RunWithBinding - * The array contains the same number of ::OrtValue%s and they are in the same order as they were bound with OrtApi::BindOutput - * or OrtApi::BindOutputToDevice. - * - * The returned ::OrtValue%s must be released using OrtApi::ReleaseValue after they are no longer needed. - * The array is allocated using the specified instance of the allocator and must be freed using the same allocator after - * all the ::OrtValue%s contained therein are individually released. - * - * \param[in] binding_ptr - * \param[in] allocator Allocator used to allocate output array - * \param[out] output Set to the allocated array of allocated ::OrtValue outputs. Set to nullptr if there are 0 outputs. - * \param[out] output_count Set to number of ::OrtValue%s returned - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetBoundOutputValues, _In_ const OrtIoBinding* binding_ptr, _In_ OrtAllocator* allocator, - _Out_writes_all_(output_count) OrtValue*** output, _Out_ size_t* output_count); - - /** \brief Clears any previously set Inputs for an ::OrtIoBinding - */ - void(ORT_API_CALL* ClearBoundInputs)(_Inout_ OrtIoBinding* binding_ptr) NO_EXCEPTION ORT_ALL_ARGS_NONNULL; - - /** \brief Clears any previously set Outputs for an ::OrtIoBinding - */ - void(ORT_API_CALL* ClearBoundOutputs)(_Inout_ OrtIoBinding* binding_ptr) NO_EXCEPTION ORT_ALL_ARGS_NONNULL; - - /// @} - /// \name OrtValue - /// @{ - - /** \brief Direct memory access to a specified tensor element - * - * For example, given a tensor with shape of [3,224,224], a pointer to the element at location [2,150,128] can be retrieved - * - * This function only works for numeric type tensors (No strings, etc). - * This is a no-copy method whose returned pointer is valid until the passed in ::OrtValue is free'd. - * - * \param[in] value - * \param[in] location_values Pointer to an array of index values that specify an element's location relative to its shape - * \param[in] location_values_count Number of elements in location_values. Must match the number of elements in the tensor's shape. - * \param[out] out Set to a pointer to the element specified - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(TensorAt, _Inout_ OrtValue* value, const int64_t* location_values, size_t location_values_count, _Outptr_ void** out); - - /// @} - /// \name OrtEnv - /// @{ - - /** \brief Create an allocator and register it with the ::OrtEnv - * - * Enables sharing the allocator between multiple sessions that use the same env instance. - * Lifetime of the created allocator will be valid for the duration of the environment. - * Returns an error if an allocator with the same ::OrtMemoryInfo is already registered. - * - * See https://onnxruntime.ai/docs/get-started/with-c.html for details. - * - * \param[in] env ::OrtEnv instance - * \param[in] mem_info - * \param[in] arena_cfg Pass nullptr for defaults - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateAndRegisterAllocator, _Inout_ OrtEnv* env, _In_ const OrtMemoryInfo* mem_info, - _In_ const OrtArenaCfg* arena_cfg); - - /** \brief Set language projection - * - * Set the language projection for collecting telemetry data when Env is created. - * - * The default is ORT_PROJECTION_C, which means it will classify the language not in the list to C also. - * - * \param[in] ort_env - * \param[in] projection - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetLanguageProjection, _In_ const OrtEnv* ort_env, _In_ OrtLanguageProjection projection); - - /// @} - /// \name OrtSession - /// @{ - - /** \brief Return the time that profiling was started - * - * \note The timer precision varies per platform. On Windows and MacOS, the precision will be ~100ns - * - * \param[in] session - * \param[out] out nanoseconds of profiling's start time - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionGetProfilingStartTimeNs, _In_ const OrtSession* session, _Outptr_ uint64_t* out); - - /// @} - /// \name OrtThreadingOptions - /// @{ - - /** \brief Set global intra-op thread count - * - * This configures the global thread pool options to be used in the call to OrtApi::CreateEnvWithGlobalThreadPools - * - * \param[in] tp_options - * \param[in] intra_op_num_threads Number of threads, special values:
- * 0 = Use default thread count
- * 1 = The invoking thread will be used; no threads will be created in the thread pool. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetGlobalIntraOpNumThreads, _Inout_ OrtThreadingOptions* tp_options, int intra_op_num_threads); - - /** \brief Set global inter-op thread count - * - * This configures the global thread pool options to be used in the call to OrtApi::CreateEnvWithGlobalThreadPools - * - * \param[in] tp_options - * \param[in] inter_op_num_threads Number of threads, special values:
- * 0 = Use default thread count
- * 1 = The invoking thread will be used; no threads will be created in the thread pool. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetGlobalInterOpNumThreads, _Inout_ OrtThreadingOptions* tp_options, int inter_op_num_threads); - - /** \brief Set global spin control options - * - * This will configure the global thread pool options to be used in the call to OrtApi::CreateEnvWithGlobalThreadPools. - * Allow spinning of thread pools when their queues are empty. This will set the value for both - * inter_op and intra_op threadpools. - * - * \param[in] tp_options - * \param[in] allow_spinning Valid values are 0 or 1.
- * 0 = It won't spin (recommended if CPU usage is high)
- * 1 = Threadpool will spin to wait for queue to become non-empty - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetGlobalSpinControl, _Inout_ OrtThreadingOptions* tp_options, int allow_spinning); - - /// @} - /// \name OrtSessionOptions - /// @{ - - /** \brief Add a pre-allocated initializer to a session - * - * If a model contains an initializer with a name that is same as the name passed to this call, - * ORT will use this initializer instance instead of deserializing one from the model file. This - * is useful when you want to share the same initializer across sessions. - * - * \param[in] options - * \param[in] name Null terminated string of the initializer name - * \param[in] val ::OrtValue containing the initializer. Its lifetime and the underlying initializer buffer must be - * managed by the user (created using the OrtApi::CreateTensorWithDataAsOrtValue) and it must outlive the session object - * to which it is added. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(AddInitializer, _Inout_ OrtSessionOptions* options, _In_z_ const char* name, - _In_ const OrtValue* val); - - /// @} - /// \name OrtEnv - /// @{ - - /** - * Create a custom environment with global threadpools and logger that will be shared across sessions. - * Use this in conjunction with OrtApi::DisablePerSessionThreads or else the session will use - * its own thread pools. - * - * \param[in] logging_function A pointer to a logging function. - * \param[in] logger_param A pointer to arbitrary data passed as the ::OrtLoggingFunction `param` parameter to - * `logging_function`. - * \param[in] log_severity_level The log severity level. - * \param[in] logid The log identifier. - * \param[in] tp_options - * \param[out] out Newly created OrtEnv. Must be freed with OrtApi::ReleaseEnv - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateEnvWithCustomLoggerAndGlobalThreadPools, OrtLoggingFunction logging_function, _In_opt_ void* logger_param, OrtLoggingLevel log_severity_level, - _In_ const char* logid, _In_ const struct OrtThreadingOptions* tp_options, _Outptr_ OrtEnv** out); - - /// @} - /// \name OrtSessionOptions - /// @{ - - /** \brief Append CUDA provider to session options - * - * If CUDA is not available (due to a non CUDA enabled build, or if CUDA is not installed on the system), this function will return failure. - * - * \param[in] options - * \param[in] cuda_options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_CUDA, - _In_ OrtSessionOptions* options, _In_ const OrtCUDAProviderOptions* cuda_options); - - /** \brief Append ROCM execution provider to the session options - * - * If ROCM is not available (due to a non ROCM enabled build, or if ROCM is not installed on the system), this function will return failure. - * - * \param[in] options - * \param[in] rocm_options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_ROCM, - _In_ OrtSessionOptions* options, _In_ const OrtROCMProviderOptions* rocm_options); - - /** \brief Append OpenVINO execution provider to the session options - * - * If OpenVINO is not available (due to a non OpenVINO enabled build, or if OpenVINO is not installed on the system), this function will fail. - * - * \param[in] options - * \param[in] provider_options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_OpenVINO, - _In_ OrtSessionOptions* options, _In_ const OrtOpenVINOProviderOptions* provider_options); - - /// @} - /// \name OrtThreadingOptions - /// @{ - - /** \brief Set threading flush-to-zero and denormal-as-zero - * - * Sets global thread pool options to be used in the call to OrtApi::CreateEnvWithGlobalThreadPools. - * Flush-to-zero and denormal-as-zero are applied to threads in both intra and inter global thread pool. - * \note This option is not needed if the models used have no denormals. Having no denormals is recommended as this option may hurt model accuracy. - * - * \param[in] tp_options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetGlobalDenormalAsZero, _Inout_ OrtThreadingOptions* tp_options); - - /// @} - /// \name OrtArenaCfg - /// @{ - - /** \deprecated Use OrtApi::CreateArenaCfgV2 - * - * This will create the configuration of an arena that can eventually be used to define an arena based allocator's behavior - * - * \param[in] max_mem Use 0 to allow ORT to choose the default - * \param[in] arena_extend_strategy Use -1 to allow ORT to choose the default, 0 = kNextPowerOfTwo, 1 = kSameAsRequested - * \param[in] initial_chunk_size_bytes Use -1 to allow ORT to choose the default - * \param[in] max_dead_bytes_per_chunk Use -1 to allow ORT to choose the default - * \param[in] out A pointer to an OrtArenaCfg instance - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateArenaCfg, _In_ size_t max_mem, int arena_extend_strategy, int initial_chunk_size_bytes, - int max_dead_bytes_per_chunk, _Outptr_ OrtArenaCfg** out); - - ORT_CLASS_RELEASE(ArenaCfg); - - /// @} - /// \name OrtModelMetadata - /// @{ - - /** - * Use this to obtain the description of the graph present in the model - * (doc_string field of the GraphProto message within the ModelProto message). - * If it doesn't exist, an empty string will be returned. - * - * \param[in] model_metadata An instance of ::OrtModelMetadata - * \param[in] allocator Allocator used to allocate the string that will be returned back - * \param[out] value Set to a null terminated string allocated using `allocator`. The caller is responsible for freeing it using `allocator` - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(ModelMetadataGetGraphDescription, _In_ const OrtModelMetadata* model_metadata, - _Inout_ OrtAllocator* allocator, _Outptr_ char** value); - - /// @} - /// \name OrtSessionOptions - /// @{ - - /** \brief Append TensorRT provider to session options - * - * If TensorRT is not available (due to a non TensorRT enabled build, or if TensorRT is not installed on the system), this function will return failure. - * - * \param[in] options - * \param[in] tensorrt_options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_TensorRT, - _In_ OrtSessionOptions* options, _In_ const OrtTensorRTProviderOptions* tensorrt_options); - - /// @} - /// \name Misc - /// @{ - - /** \brief Set current GPU device ID - * - * Set the current device id of the GPU execution provider (CUDA/tensorrt/rocm). The device id should be less - * than the total number of devices available. This is only useful when multiple-GPUs are installed and it is - * required to restrict execution to a single GPU. - * - * \param[in] device_id - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetCurrentGpuDeviceId, _In_ int device_id); - - /** \brief Get current GPU device ID - * - * Get the current device id of the GPU execution provider (CUDA/tensorrt/rocm). - * - * \see OrtApi::SetCurrentGpuDeviceId - * - * \param[out] device_id - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetCurrentGpuDeviceId, _In_ int* device_id); - - /// @} - /// \name OrtKernelInfo - /// Custom operator APIs. - /// @{ - - /** \brief Fetch an array of int64_t values stored as an attribute in the graph node - * - * - * If `out` is nullptr, the value of `size` is set to the true size of the attribute - * array's size, and a success status is returned. - * - * If the `size` parameter is greater than or equal to the actual attribute array's size, - * the value of `size` is set to the true size of the attribute array's size, - * the provided memory is filled with the attribute's contents, - * and a success status is returned. - * - * If the `size` parameter is less than the actual attribute array's size and `out` - * is not nullptr, the value of `size` is set to the true size of the attribute array's size - * and a failure status is returned.) - * - * \param[in] info instance - * \param[in] name name of the attribute to be parsed - * \param[out] out pointer to memory where the attribute's contents are to be stored - * \param[in, out] size actual size of attribute array - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(KernelInfoGetAttributeArray_float, _In_ const OrtKernelInfo* info, _In_ const char* name, - _Out_ float* out, _Inout_ size_t* size); - - /** \brief Fetch an array of int64_t values stored as an attribute in the graph node - * - * If `out` is nullptr, the value of `size` is set to the true size of the attribute - * array's size, and a success status is returned. - * - * If the `size` parameter is greater than or equal to the actual attribute array's size, - * the value of `size` is set to the true size of the attribute array's size, - * the provided memory is filled with the attribute's contents, - * and a success status is returned. - * - * If the `size` parameter is less than the actual attribute array's size and `out` - * is not nullptr, the value of `size` is set to the true size of the attribute array's size - * and a failure status is returned.) - * - * \param[in] info instance - * \param[in] name name of the attribute to be parsed - * \param[out] out pointer to memory where the attribute's contents are to be stored - * \param[in, out] size actual size of attribute array - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(KernelInfoGetAttributeArray_int64, _In_ const OrtKernelInfo* info, _In_ const char* name, - _Out_ int64_t* out, _Inout_ size_t* size); - - /// @} - /// \name OrtArenaCfg - /// @{ - - /** \brief Create an ::OrtArenaCfg - * - * Create the configuration of an arena that can eventually be used to define an arena based allocator's behavior. - * - * Supported keys are (See https://onnxruntime.ai/docs/get-started/with-c.html for details on what the - * following parameters mean and how to choose these values.): - * "max_mem": Maximum memory that can be allocated by the arena based allocator. - * Use 0 for ORT to pick the best value. Default is 0. - * "arena_extend_strategy": 0 = kNextPowerOfTwo, 1 = kSameAsRequested. - * Use -1 to allow ORT to choose the default. - * "initial_chunk_size_bytes": (Possible) Size of the first allocation in the arena. - * Only relevant if arena strategy is `kNextPowerOfTwo`. Use -1 to allow ORT to choose the default. - * Ultimately, the first allocation size is determined by the allocation memory request. - * "max_dead_bytes_per_chunk": Threshold of unused memory in an allocated chunk of arena memory after - * crossing which the current chunk is chunked into 2. - * "initial_growth_chunk_size_bytes": (Possible) Size of the second allocation in the arena. - * Only relevant if arena strategy is `kNextPowerOfTwo`. Use -1 to allow ORT to choose the default. - * "max_power_of_two_extend_bytes": The maximum enxtend size if arena strategy is `kNextPowerOfTwo`. - * It is not an allocation limit, it is only a limit for extension when requested byte is less than the limit. - * When requested bytes is more than the limit, allocator will still return as requested. - * Use -1 to allow ORT to choose the default 1GB for max_power_of_two_extend_bytes. - * Ultimately, the allocation size is determined by the allocation memory request. - * Further allocation sizes are governed by the arena extend strategy. - * - * \param[in] arena_config_keys Keys to configure the arena - * \param[in] arena_config_values Values to configure the arena - * \param[in] num_keys Number of keys in `arena_config_keys` and `arena_config_values` - * \param[out] out Newly created ::OrtArenaCfg. Must be freed with OrtApi::ReleaseArenaCfg - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateArenaCfgV2, _In_reads_(num_keys) const char* const* arena_config_keys, - _In_reads_(num_keys) const size_t* arena_config_values, _In_ size_t num_keys, - _Outptr_ OrtArenaCfg** out); - - /// @} - /// \name OrtRunOptions - /// @{ - - /** \brief Set a single run configuration entry as a pair of strings - * - * If a configuration with same key exists, this will overwrite the configuration with the given config_value - * - * The config_key and the format of config_value are defined in onnxruntime_run_options_config_keys.h - * - * \param[in] options - * \param[in] config_key A null terminated string representation of the config key - * \param[in] config_value A null terminated string representation of the config value - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(AddRunConfigEntry, _Inout_ OrtRunOptions* options, - _In_z_ const char* config_key, _In_z_ const char* config_value); - - /// @} - /// \name OrtPrepackedWeightsContainer - /// @{ - - /** \brief Create an ::OrtPrepackedWeightsContainer - * - * This container will hold pre-packed buffers of shared initializers for sharing between sessions - * (i.e.) if there are shared initializers that can be shared between sessions, the pre-packed buffers - * of these (if any) may possibly be shared to provide memory footprint savings. Pass this container - * to sessions that you would like to share pre-packed buffers of shared initializers at session - * creation time. - * - * \param[out] out Newly created ::OrtPrepackedWeightsContainer. Must be freed with OrtApi::ReleasePrepackedWeightsContainer - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreatePrepackedWeightsContainer, _Outptr_ OrtPrepackedWeightsContainer** out); - - /** \brief Release OrtPrepackedWeightsContainer instance - * - * \note instance must not be released until the sessions using it are released - */ - ORT_CLASS_RELEASE(PrepackedWeightsContainer); - - /// @} - /// \name OrtSession - /// @{ - - /** \brief Create session with prepacked weights container - * - * Same functionality offered by OrtApi::CreateSession except that a container that contains - * pre-packed weights' buffers is written into/read from by the created session. - * This is useful when used in conjunction with OrtApi::AddInitializer which injects - * shared initializer info into sessions. Wherever possible, the pre-packed versions of these - * shared initializers are cached in this container so that multiple sessions can just re-use - * these instead of duplicating these in memory. - * - * \param[in] env OrtEnv instance instance - * \param[in] model_path Null terminated string of the path (wchar on Windows, char otherwise) - * \param[in] options - * \param[in] prepacked_weights_container - * \param[out] out Newly created ::OrtSession. Must be freed with OrtApi::ReleaseSession - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateSessionWithPrepackedWeightsContainer, _In_ const OrtEnv* env, _In_ const ORTCHAR_T* model_path, - _In_ const OrtSessionOptions* options, - _Inout_ OrtPrepackedWeightsContainer* prepacked_weights_container, - _Outptr_ OrtSession** out); - - /** \brief Create session from memory with prepacked weights container - * - * Same functionality offered by OrtApi::CreateSessionFromArray except that a container that contains - * pre-packed weights' buffers is written into/read from by the created session. - * This is useful when used in conjunction with OrtApi::AddInitializer which injects - * shared initializer info into sessions. Wherever possible, the pre-packed versions of these - * shared initializers are cached in this container so that multiple sessions can just re-use - * these instead of duplicating these in memory. - * - * \param[in] env - * \param[in] model_data Array of bytes holding the model - * \param[in] model_data_length Number of bytes in `model_data_model` - * \param[in] options - * \param[in] prepacked_weights_container - * \param[out] out Newly created ::OrtSession. Must be freed with OrtApi::ReleaseSession - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateSessionFromArrayWithPrepackedWeightsContainer, _In_ const OrtEnv* env, - _In_ const void* model_data, size_t model_data_length, - _In_ const OrtSessionOptions* options, - _Inout_ OrtPrepackedWeightsContainer* prepacked_weights_container, - _Outptr_ OrtSession** out); - - /// @} - /// \name OrtSessionOptions - /// @{ - - /** \brief Append TensorRT execution provider to the session options - * - * If TensorRT is not available (due to a non TensorRT enabled build), this function will return failure. - * - * This is slightly different from OrtApi::SessionOptionsAppendExecutionProvider_TensorRT, it takes an - * ::OrtTensorRTProviderOptions which is publicly defined. This takes an opaque ::OrtTensorRTProviderOptionsV2 - * which must be created with OrtApi::CreateTensorRTProviderOptions. - * - * For OrtApi::SessionOptionsAppendExecutionProvider_TensorRT, the user needs to instantiate ::OrtTensorRTProviderOptions - * as well as allocate/release buffers for some members of ::OrtTensorRTProviderOptions. - * Here, OrtApi::CreateTensorRTProviderOptions and Ortapi::ReleaseTensorRTProviderOptions will do the memory management for you. - * - * \param[in] options - * \param[in] tensorrt_options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_TensorRT_V2, - _In_ OrtSessionOptions* options, _In_ const OrtTensorRTProviderOptionsV2* tensorrt_options); - - /// @} - /// \name OrtTensorRTProviderOptionsV2 - /// @{ - - /** \brief Create an OrtTensorRTProviderOptionsV2 - * - * \param[out] out Newly created ::OrtTensorRTProviderOptionsV2. Must be released with OrtApi::ReleaseTensorRTProviderOptions - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateTensorRTProviderOptions, _Outptr_ OrtTensorRTProviderOptionsV2** out); - - /** \brief Set options in a TensorRT Execution Provider. - * - * Please refer to https://onnxruntime.ai/docs/execution-providers/TensorRT-ExecutionProvider.html#cc - * to know the available keys and values. Key should be in null terminated string format of the member of ::OrtTensorRTProviderOptionsV2 - * and value should be its related range. Recreates the options and only sets the supplied values. - * - * For example, key="trt_max_workspace_size" and value="2147483648" - * - * \param[in] tensorrt_options - * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys - * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values - * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(UpdateTensorRTProviderOptions, _Inout_ OrtTensorRTProviderOptionsV2* tensorrt_options, - _In_reads_(num_keys) const char* const* provider_options_keys, - _In_reads_(num_keys) const char* const* provider_options_values, - _In_ size_t num_keys); - - /** \brief Get serialized TensorRT provider options string. - * - * For example, "trt_max_workspace_size=2147483648;trt_max_partition_iterations=10;trt_int8_enable=1;......" - * - * \param tensorrt_options - OrtTensorRTProviderOptionsV2 instance - * \param allocator - a ptr to an instance of OrtAllocator obtained with OrtApi::CreateAllocator or OrtApi::GetAllocatorWithDefaultOptions - * the specified allocator will be used to allocate continuous buffers for output strings and lengths. - * \param ptr - is a UTF-8 null terminated string allocated using 'allocator'. The caller is responsible for using the same allocator to free it. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetTensorRTProviderOptionsAsString, _In_ const OrtTensorRTProviderOptionsV2* tensorrt_options, _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); - - /** \brief Release an ::OrtTensorRTProviderOptionsV2 - * - * \note This is an exception in the naming convention of other Release* functions, as the name of the method does not have the V2 suffix, but the type does - */ - void(ORT_API_CALL* ReleaseTensorRTProviderOptions)(_Frees_ptr_opt_ OrtTensorRTProviderOptionsV2* input); - - /// @} - /// \name OrtSessionOptions - /// @{ - - /** \brief Enable custom operators - * - * See onnxruntime-extensions: https://github.com/microsoft/onnxruntime-extensions.git - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(EnableOrtCustomOps, _Inout_ OrtSessionOptions* options); - - /// @} - /// \name OrtAllocator - /// @{ - - /** \brief Register a custom allocator - * - * Enables sharing between multiple sessions that use the same env instance. - * Returns an error if an allocator with the same ::OrtMemoryInfo is already registered. - * - * The behavior of this is exactly the same as OrtApi::CreateAndRegisterAllocator except - * instead of ORT creating an allocator based on provided info, in this case - * ORT uses the user-provided custom allocator. - * See https://onnxruntime.ai/docs/get-started/with-c.html for details. - * - * \param[in] env - * \param[in] allocator User provided allocator - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(RegisterAllocator, _Inout_ OrtEnv* env, _In_ OrtAllocator* allocator); - - /** \brief Unregister a custom allocator - * - * It is an error if you provide an ::OrtMemoryInfo not corresponding to any - * registered allocators for sharing. - * - * \param[in] env - * \param[in] mem_info - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(UnregisterAllocator, _Inout_ OrtEnv* env, - _In_ const OrtMemoryInfo* mem_info); - - /// @} - /// \name OrtValue - /// @{ - - /** \brief Sets *out to 1 iff an ::OrtValue is a SparseTensor, and 0 otherwise - * - * \param[in] value existing ::OrtValue - * \param[out] out unless an error occurs, contains 1 iff the value contains an instance - * of sparse tensor or 0 otherwise. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(IsSparseTensor, _In_ const OrtValue* value, _Out_ int* out); - - /** \brief Create an ::OrtValue with a sparse tensor that is empty. - * - * Use FillSparseTensor() functions to populate sparse tensor with non-zero values and - * format specific indices data. - * Use ReleaseValue to destroy the sparse tensor, this will also release the buffer inside the output value - * if any was allocated. - * \param[in,out] allocator allocator to use when performing an allocation. Allocation will be performed - * by FillSparseTensor() APIs. The lifespan of the allocator instance must eclipse the lifespan - * this sparse tensor instance as the same allocator will be used to free memory. - * \param[in] dense_shape shape of the original dense tensor - * \param[in] dense_shape_len number of shape dimensions being passed - * \param[in] type must be one of TENSOR_ELEMENT_DATA_TYPE_xxxx - * \param[out] out Should be freed by calling ReleaseValue - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateSparseTensorAsOrtValue, _Inout_ OrtAllocator* allocator, _In_ const int64_t* dense_shape, - size_t dense_shape_len, ONNXTensorElementDataType type, _Outptr_ OrtValue** out); - - /** - * This fills populates an empty tensor that was created using OrtApi::CreateSparseTensorAsOrtValue. - * This will allocate required memory and copy the supplied NNZ values and COO indices into that memory allocation. - * Memory allocation is performed using the allocator that was specified with OrtApi::CreateSparseTensorAsOrtValue. - * - * \param[in,out] ort_value ::OrtValue to populate with data - * \param[in] data_mem_info serves to identify the location of the data to be copied. If the allocator specified - * at the creation time has memory info that is not the same as mem_info argument to this function a X-device copy will be performed. - * String data is assumed to be on CPU and will only be copied into a CPU allocated buffer. - * \param[in] values_shape pointer to values shape array - * \param[in] values_shape_len length of the values_shape - * \param[in] values pointer to an array of values. For strings, pass const char**. - * \param[in] indices_data pointer to a location of COO indices - * \param[in] indices_num number of COO indices - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(FillSparseTensorCoo, _Inout_ OrtValue* ort_value, _In_ const OrtMemoryInfo* data_mem_info, - _In_ const int64_t* values_shape, size_t values_shape_len, _In_ const void* values, - _In_ const int64_t* indices_data, size_t indices_num); - - /** - * This fills populates an empty tensor that was created using OrtApi::CreateSparseTensorAsOrtValue. - * This will allocate required memory and copy the supplied NNZ values and CSR indices into that memory allocation. - * Memory allocation is performed using the allocator that was specified with OrtApi::CreateSparseTensorAsOrtValue. - * - * \param[in,out] ort_value ::OrtValue to populate with data - * \param[in] data_mem_info serves to identify the location of the data to be copied. If the allocator specified - * at the creation time has memory info that is not the same as mem_info argument to this function a X-device copy will be performed. - * String data is assumed to be on CPU and will only be copied into a CPU allocated buffer. - * \param[in] values_shape pointer to values shape array - * \param[in] values_shape_len length of the values_shape - * \param[in] values - pointer to an array of values. For strings, pass const char**. - * \param[in] inner_indices_data pointer to a location of CSR inner indices - * \param[in] inner_indices_num number of CSR inner indices - * \param[in] outer_indices_data pointer to a location of CSR outer indices - * \param[in] outer_indices_num number of CSR outer indices - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(FillSparseTensorCsr, _Inout_ OrtValue* ort_value, _In_ const OrtMemoryInfo* data_mem_info, - _In_ const int64_t* values_shape, size_t values_shape_len, _In_ const void* values, - _In_ const int64_t* inner_indices_data, size_t inner_indices_num, - _In_ const int64_t* outer_indices_data, size_t outer_indices_num); - - /** - * This fills populates an empty tensor that was created using OrtApi::CreateSparseTensorAsOrtValue. - * This will allocate required memory and copy the supplied NNZ values and BlockSparse indices into that memory allocation. - * Memory allocation is performed using the allocator that was specified with OrtApi::CreateSparseTensorAsOrtValue. - * - * \param[in,out] ort_value ::OrtValue to populate with data - * \param[in] data_mem_info serves to identify the location of the data to be copied. If the allocator specified - * at the creation time has memory info that is not the same as mem_info argument to this function a X-device copy will be performed. - * String data is assumed to be on CPU and will only be copied into a CPU allocated buffer. - * \param[in] values_shape - * \param[in] values_shape_len - * \param[in] values structure with values information - * \param[in] indices_shape_data pointer to a location of indices shape - * \param[in] indices_shape_len length of the block sparse indices shape - * \param[in] indices_data pointer to a location of indices data. Shape will determine the length of the indices data. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(FillSparseTensorBlockSparse, _Inout_ OrtValue* ort_value, _In_ const OrtMemoryInfo* data_mem_info, - _In_ const int64_t* values_shape, size_t values_shape_len, _In_ const void* values, - _In_ const int64_t* indices_shape_data, size_t indices_shape_len, - _In_ const int32_t* indices_data); - - /** - * Create an ::OrtValue with a sparse tensor. This is the first step. - * Next, use UseIndices() functions to supply sparse tensor with - * format specific indices data and set its sparse format to a specific enum value. - * This will not perform memory allocations. It will - * use supplied user buffer which should outlive the created sparse tensor. - * Use OrtApi::ReleaseValue to destroy the sparse tensor. It would not release the supplied values buffer. - * This function can not be used to map strings from the user allocated memory. Strings must always be copied - * and have UTF-8 encoding. Therefore, use OrtApi::CreateSparseTensorAsOrtValue above and then fill it with data - * using appropriate Make*() function. - * - * \param[in] info memory info where sparse values reside. - * \param[in,out] p_data pointer to a user allocated buffer with values. To create a full sparse tensor with no non-zero - * values, pass nullptr - * \param[in] dense_shape shape of the original dense tensor - * \param[in] dense_shape_len number of shape dimensions being passed - * \param[in] values_shape shape of the values data. To create a fully sparse tensor with no non-zero values, - * pass {0} shape. - * \param[in] values_shape_len number of values shape dimensions - * \param[in] type must be one of TENSOR_ELEMENT_DATA_TYPE_xxxx - * \param[out] out Should be freed by calling ReleaseValue - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateSparseTensorWithValuesAsOrtValue, _In_ const OrtMemoryInfo* info, _Inout_ void* p_data, - _In_ const int64_t* dense_shape, size_t dense_shape_len, - _In_ const int64_t* values_shape, size_t values_shape_len, - ONNXTensorElementDataType type, _Outptr_ OrtValue** out); - - /** - * This assigns Coo format indices to the SparseTensor that was created by - * OrtApi::CreateSparseTensorWithValuesAsOrtValue above. It also sets OrtSparseFormat to - * ORT_SPARSE_COO. This will not allocate any additional memory for data. The life span of - * indices_data buffer should eclipse the life span of this ::OrtValue. - * - * \param[in,out] ort_value ::OrtValue instance constructed with OrtApi::CreateSparseTensorWithValuesAsOrtValue - * \param[in,out] indices_data pointer to a user pre-allocated buffer or nullptr for fully sparse tensors. - * \param[in] indices_num number of COO indices. Should either be 0 for fully sparse tensors, be equal - * to the number of nnz values specified to OrtApi::CreateSparseTensorWithValuesAsOrtValue for 1-D {nnz} indices or - * be twice as number of nnz values for a 2-D indices {nnz, 2} - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(UseCooIndices, _Inout_ OrtValue* ort_value, _Inout_ int64_t* indices_data, size_t indices_num); - - /** - * The assigns CSR format indices to the SparseTensor that was created by - * OrtApi::CreateSparseTensorWithValuesAsOrtValue above. It also sets OrtSparseFormat to - * ORT_SPARSE_CSRC. This will not allocate any additional memory for data. The life spans of - * inner_data and outer_data buffers should eclipse the life span of this ::OrtValue. - * - * \param[in,out] ort_value ::OrtValue instance constructed with OrtApi::CreateSparseTensorWithValuesAsOrtValue - * \param[in,out] inner_data pointer to a user pre-allocated buffer or nullptr for fully sparse tensors. - * \param[in] inner_num number of inner CSR indices. Should either be 0 for fully sparse tensors or be equal - * to the number of nnz values specified to OrtApi::CreateSparseTensorWithValuesAsOrtValue. - * \param[in,out] outer_data pointer to user pre-allocated buffer or nullptr for fully sparse tensors. - * \param[in] outer_num number of CSR outer indices. Should either be 0 for fully sparse tensors or - * equal to rows + 1 of the dense shape. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(UseCsrIndices, _Inout_ OrtValue* ort_value, _Inout_ int64_t* inner_data, size_t inner_num, - _Inout_ int64_t* outer_data, size_t outer_num); - - /** - * The assigns BlockSparse format indices to the SparseTensor that was created by - * OrtApi::CreateSparseTensorWithValuesAsOrtValue above. It also sets OrtSparseFormat to - * ORT_SPARSE_BLOCK_SPARSE. This will not allocate any additional memory for data. The life span of - * indices_data buffer must eclipse the lifespan of this ::OrtValue. - * - * \param[in,out] ort_value OrtValue instance constructed with OrtApi::CreateSparseTensorWithValuesAsOrtValue - * \param[in] indices_shape pointer to indices shape. Use {0} for fully sparse tensors - * \param[in] indices_shape_len length of the indices shape - * \param[in,out] indices_data pointer to user pre-allocated buffer or nullptr for fully sparse tensors. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(UseBlockSparseIndices, _Inout_ OrtValue* ort_value, const int64_t* indices_shape, size_t indices_shape_len, _Inout_ int32_t* indices_data); - - /** \brief Returns sparse tensor format enum iff a given ort value contains an instance of sparse tensor. - * - * \param[in] ort_value ::OrtValue that contains an instance of sparse tensor - * \param[out] out pointer to out parameter - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetSparseTensorFormat, _In_ const OrtValue* ort_value, _Out_ enum OrtSparseFormat* out); - - /** \brief Returns data type and shape of sparse tensor values (nnz) iff ::OrtValue contains a SparseTensor. - * - * \param[in] ort_value An ::OrtValue that contains a fully constructed sparse tensor - * \param[out] out Must be freed by OrtApi::ReleaseTensorTypeAndShapeInfo - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetSparseTensorValuesTypeAndShape, _In_ const OrtValue* ort_value, _Outptr_ OrtTensorTypeAndShapeInfo** out); - - /** \brief Returns numeric data for sparse tensor values (nnz). For string values use GetStringTensor*(). - * - * \param[in] ort_value an instance of ::OrtValue containing sparse tensor - * \param[out] out returns a pointer to values data. Do not attempt to free this ptr. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetSparseTensorValues, _In_ const OrtValue* ort_value, _Outptr_ const void** out); - - /** \brief Returns data type, shape for the type of indices specified by indices_format. - * - * \param[in] ort_value ::OrtValue containing sparse tensor. - * \param[in] indices_format One of the indices formats. It is an error to request a format that the sparse - * tensor does not contain. - * \param[out] out an instance of ::OrtTensorTypeAndShapeInfo. Must be freed by OrtApi::ReleaseTensorTypeAndShapeInfo - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetSparseTensorIndicesTypeShape, _In_ const OrtValue* ort_value, enum OrtSparseIndicesFormat indices_format, _Outptr_ OrtTensorTypeAndShapeInfo** out); - - /** \brief Returns indices data for the type of the indices specified by indices_format - * - * \param[in] ort_value ::OrtValue containing sparse tensor. - * \param[in] indices_format One of the indices formats. It is an error to request a format that the sparse tensor does not contain. - * \param[out] num_indices Pointer to where the number of indices entries is returned - * \param[out] indices Returned pointer to the indices data. Do not free the returned pointer as it refers to internal data owned by the ::OrtValue - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetSparseTensorIndices, _In_ const OrtValue* ort_value, enum OrtSparseIndicesFormat indices_format, _Out_ size_t* num_indices, _Outptr_ const void** indices); - /// @} - /// \name OrtSessionOptions - /// @{ - - /** - * \brief Sets out to 1 iff an optional type OrtValue has an element, 0 otherwise (OrtValue is None) - * Use this API to find if the optional type OrtValue is None or not. - * If the optional type OrtValue is not None, use the OrtValue just like any other OrtValue. - * For example, if you get an OrtValue that corresponds to Optional(tensor) and - * if HasValue() returns true, use it as tensor and so on. - - * \param[in] value Input OrtValue. - * \param[out] out indicating if the input OrtValue contains data (1) or if it is a None (0) - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(HasValue, _In_ const OrtValue* value, _Out_ int* out); - - /// @} - /// \name OrtKernelContext - /// Custom operator APIs. - /// @{ - - /** \brief Used for custom operators, gets the GPU compute stream to use to launch the custom a GPU kernel - * \see ::OrtCustomOp - * \param[in] context OrtKernelContext instance - * \param[out] out Returns pointer to a GPU compute stream that can be used to launch the custom GPU kernel. - * If retrieving the GPU compute stream is not relevant (GPU not enabled in the build, kernel partitioned to - * some other EP), then a nullptr is returned as the output param. - * Do not free or mutate the returned pointer as it refers to internal data owned by the underlying session. - * Only use it for custom kernel launching. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(KernelContext_GetGPUComputeStream, _In_ const OrtKernelContext* context, _Outptr_ void** out); - - /// @} - /// \name GetTensorMemoryInfo - /// @{ - /** \brief Returns a pointer to the ::OrtMemoryInfo of a Tensor - * \param[in] value ::OrtValue containing tensor. - * \param[out] mem_info ::OrtMemoryInfo of the tensor. Do NOT free the returned pointer. It is valid for the lifetime of the ::OrtValue - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetTensorMemoryInfo, _In_ const OrtValue* value, _Out_ const OrtMemoryInfo** mem_info); - - /// @} - /// \name GetExecutionProviderApi - /// @{ - /** \brief Get a pointer to the requested version of the Execution Provider specific - * API extensions to the OrtApi - * \param[in] provider_name The name of the execution provider name. Currently only the following - * values are supported: "DML". - * \param[in] version Must be ::ORT_API_VERSION. - * \param[out] provider_api A void pointer containing a reference to the execution provider versioned api structure. - * For example, the provider_api pointer can be cast to the OrtDmlApi* when the provider_name is "DML". - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetExecutionProviderApi, _In_ const char* provider_name, _In_ uint32_t version, _Outptr_ const void** provider_api); - - /// @} - - /// \name SessionOptions - /// @{ - /** \brief Set custom thread creation function - * - * \param[in] options Session options - * \param[in] ort_custom_create_thread_fn Custom thread creation function - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionOptionsSetCustomCreateThreadFn, _Inout_ OrtSessionOptions* options, _In_ OrtCustomCreateThreadFn ort_custom_create_thread_fn); - - /** \brief Set creation options for custom thread - * - * \param[in] options Session options - * \param[in] ort_custom_thread_creation_options Custom thread creation options (can be nullptr) - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionOptionsSetCustomThreadCreationOptions, _Inout_ OrtSessionOptions* options, _In_ void* ort_custom_thread_creation_options); - - /** \brief Set custom thread join function - * - * \param[in] options Session options - * \param[in] ort_custom_join_thread_fn Custom join thread function, must not be nullptr when ort_custom_create_thread_fn is set - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionOptionsSetCustomJoinThreadFn, _Inout_ OrtSessionOptions* options, _In_ OrtCustomJoinThreadFn ort_custom_join_thread_fn); - /// @} - - /// \name OrtThreadingOptions - /// @{ - /** \brief Set custom thread creation function for global thread pools - * - * \param[inout] tp_options - * \param[in] ort_custom_create_thread_fn Custom thread creation function - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetGlobalCustomCreateThreadFn, _Inout_ OrtThreadingOptions* tp_options, _In_ OrtCustomCreateThreadFn ort_custom_create_thread_fn); - - /** \brief Set custom thread creation options for global thread pools - * - * \param[inout] tp_options - * \param[in] ort_custom_thread_creation_options Custom thread creation options (can be nullptr) - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetGlobalCustomThreadCreationOptions, _Inout_ OrtThreadingOptions* tp_options, _In_ void* ort_custom_thread_creation_options); - - /** \brief Set custom thread join function for global thread pools - * - * \param[inout] tp_options - * \param[in] ort_custom_join_thread_fn Custom thread join function, must not be nullptr when global ort_custom_create_thread_fn is set - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetGlobalCustomJoinThreadFn, _Inout_ OrtThreadingOptions* tp_options, _In_ OrtCustomJoinThreadFn ort_custom_join_thread_fn); - /// @} - - /** \brief Synchronize bound inputs. The call may be necessary for some providers, such as cuda, - * in case the system that allocated bound memory operated on a different stream. However, the - * operation is provider specific and could be a no-op. - * - * \param[inout] binding_ptr - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SynchronizeBoundInputs, _Inout_ OrtIoBinding* binding_ptr); - - /** \brief Synchronize bound outputs. The call may be necessary for some providers, such as cuda, - * in case the system that allocated bound memory operated on a different stream. However, the - * operation is provider specific and could be a no-op. - * - * \param[inout] binding_ptr - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SynchronizeBoundOutputs, _Inout_ OrtIoBinding* binding_ptr); - - /// \name OrtSessionOptions - /// @{ - - /** \brief Append CUDA execution provider to the session options - * - * If CUDA is not available (due to a non CUDA enabled build), this function will return failure. - * - * This is slightly different from OrtApi::SessionOptionsAppendExecutionProvider_CUDA, it takes an - * ::OrtCUDAProviderOptions which is publicly defined. This takes an opaque ::OrtCUDAProviderOptionsV2 - * which must be created with OrtApi::CreateCUDAProviderOptions. - * - * For OrtApi::SessionOptionsAppendExecutionProvider_CUDA, the user needs to instantiate ::OrtCUDAProviderOptions - * as well as allocate/release buffers for some members of ::OrtCUDAProviderOptions. - * Here, OrtApi::CreateCUDAProviderOptions and Ortapi::ReleaseCUDAProviderOptions will do the memory management for you. - * - * \param[in] options - * \param[in] cuda_options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.11. - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_CUDA_V2, - _In_ OrtSessionOptions* options, _In_ const OrtCUDAProviderOptionsV2* cuda_options); - - /// @} - /// \name OrtCUDAProviderOptionsV2 - /// @{ - - /** \brief Create an OrtCUDAProviderOptionsV2 - * - * \param[out] out Newly created ::OrtCUDAProviderOptionsV2. Must be released with OrtApi::ReleaseCudaProviderOptions - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.11. - */ - ORT_API2_STATUS(CreateCUDAProviderOptions, _Outptr_ OrtCUDAProviderOptionsV2** out); - - /** \brief Set options in a CUDA Execution Provider. - * - * Please refer to https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html#configuration-options - * to know the available keys and values. Key should be in null terminated string format of the member of ::OrtCUDAProviderOptionsV2 - * and value should be its related range. Recreates the options and only sets the supplied values. - * - * For example, key="device_id" and value="0" - * - * \param[in] cuda_options - * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys - * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values - * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.11. - */ - ORT_API2_STATUS(UpdateCUDAProviderOptions, _Inout_ OrtCUDAProviderOptionsV2* cuda_options, - _In_reads_(num_keys) const char* const* provider_options_keys, - _In_reads_(num_keys) const char* const* provider_options_values, - _In_ size_t num_keys); - - /** - * Get serialized CUDA provider options string. - * - * For example, "device_id=0;arena_extend_strategy=0;......" - * - * \param cuda_options - OrtCUDAProviderOptionsV2 instance - * \param allocator - a ptr to an instance of OrtAllocator obtained with CreateAllocator() or GetAllocatorWithDefaultOptions() - * the specified allocator will be used to allocate continuous buffers for output strings and lengths. - * \param ptr - is a UTF-8 null terminated string allocated using 'allocator'. The caller is responsible for using the same allocator to free it. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.11. - */ - ORT_API2_STATUS(GetCUDAProviderOptionsAsString, _In_ const OrtCUDAProviderOptionsV2* cuda_options, _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); - - /** \brief Release an ::OrtCUDAProviderOptionsV2 - * - * \note This is an exception in the naming convention of other Release* functions, as the name of the method does not have the V2 suffix, but the type does - * - * \since Version 1.11. - */ - void(ORT_API_CALL* ReleaseCUDAProviderOptions)(_Frees_ptr_opt_ OrtCUDAProviderOptionsV2* input); - - /// @} - - /** \brief Append MIGraphX provider to session options - * - * If MIGraphX is not available (due to a non MIGraphX enabled build, or if MIGraphX is not installed on the system), this function will return failure. - * - * \param[in] options - * \param[in] migraphx_options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.11. - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_MIGraphX, - _In_ OrtSessionOptions* options, _In_ const OrtMIGraphXProviderOptions* migraphx_options); - - /** \brief Replace initialized Tensors with external data with the data provided in initializers. - * - * The function will find the initialized TensorProtos with external data in the graph with the provided names and - * replace them with the provided tensors. The API verifies that the TensorProto being replaced - * has an external data reference and has the same name, dimensions and data type as its replacement. The replacement - * will occur before any of the optimizations take place. The data will be copied into the graph - * since TensorProto can't refer to the user provided buffers. - * - * Once the model has been loaded, the OrtValue(s) added to SessionOptions instance will be removed - * from the internal SessionOptions copy to save memory, the user provided buffers can then be deallocated - * and the SessionOptions instance that refers to them can be destroyed. - * - * \param[in] options - * \param[in] initializer_names Array of null terminated UTF-8 encoded strings of the initializers names. - * \param[in] initializers Array of ::OrtValue type - * \param[in] num_initializers Number of elements in the initializer_names and initializers - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.12. - */ - ORT_API2_STATUS(AddExternalInitializers, _In_ OrtSessionOptions* options, - _In_reads_(num_initializers) const char* const* initializer_names, - _In_reads_(num_initializers) const OrtValue* const* initializers, size_t num_initializers); - - /** \brief: Create attribute of onnxruntime operator - * - * \param[in] name Name of the attribute - * \param[in] data Data content of the attribute - * \param[in] len Number of bytes stored in data - * \param[in] type Data type - * \param[out] op_attr Attribute that has been created, which must be released by OrtApi::ReleaseOpAttr - * - * \since Version 1.12. - */ - ORT_API2_STATUS(CreateOpAttr, - _In_ const char* name, - _In_ const void* data, - _In_ int len, - _In_ OrtOpAttrType type, - _Outptr_ OrtOpAttr** op_attr); - - /* \brief: Release op attribute - * - * \param[in] opAttr Attribute created by OrtApi::CreateOpAttr - * - * \since Version 1.12. - */ - ORT_CLASS_RELEASE(OpAttr); - - /** \brief: Create onnxruntime native operator - * - * \param[in] info Kernel info - * \param[in] op_name Operator name - * \param[in] domain Operator domain - * \param[in] version Operator opset version - * \param[in] type_constraint_names Name of the type contraints, such as "T" or "T1" - * \param[in] type_constraint_values Type of each contraints - * \param[in] type_constraint_count Number of contraints - * \param[in] attr_values Attributes used to initialize the operator - * \param[in] attr_count Number of the attributes - * \param[in] input_count Number of inputs - * \param[in] output_count Number of outputs - * \param[out] ort_op Operator that has been created - * - * \since Version 1.12. - */ - ORT_API2_STATUS(CreateOp, - _In_ const OrtKernelInfo* info, - _In_z_ const char* op_name, - _In_z_ const char* domain, - int version, - _In_reads_(type_constraint_count) const char** type_constraint_names, - _In_reads_(type_constraint_count) const ONNXTensorElementDataType* type_constraint_values, - int type_constraint_count, - _In_reads_(attr_count) const OrtOpAttr* const* attr_values, - int attr_count, - int input_count, - int output_count, - _Outptr_ OrtOp** ort_op); - - /** \brief: Invoke the operator created by OrtApi::CreateOp - * The inputs must follow the order as specified in onnx specification - * - * \param[in] context Kernel context - * \param[in] ort_op Operator that has been created - * \param[in] input_values Array of inputs - * \param[in] input_count Number of inputs - * \param[in] output_values Array of outputs - * \param[in] output_count Number of outputs - * - * \since Version 1.12. - */ - ORT_API2_STATUS(InvokeOp, - _In_ const OrtKernelContext* context, - _In_ const OrtOp* ort_op, - _In_ const OrtValue* const* input_values, - _In_ int input_count, - _Inout_ OrtValue* const* output_values, - _In_ int output_count); - - /* \brief: Release an onnxruntime operator - * - * \param[in] Op Operator created by OrtApi::CreateOp - * - * \since Version 1.12. - */ - ORT_CLASS_RELEASE(Op); - - /** \brief: Append execution provider to the session options. - * \param[in] options - * \param[in] provider_name - provider to add. - * \param[in] provider_options_keys - keys to configure the provider options - * \param[in] provider_options_values - values to configure the provider options - * \param[in] num_keys - number of keys passed in - * - * Currently supported provider names: - * QNNExecutionProvider (or QNN) - * OpenVINOExecutionProvider (or OpenVINO) - * XnnpackExecutionProvider (or XNNPACK) - * WebNNExecutionProvider (or WEBNN) - * WebGpuExecutionProvider (or WebGPU) - * AzureExecutionProvider (or AZURE) - * JsExecutionProvider (or JS) - * VitisAIExecutionProvider (or VitisAI) - * CoreMLExecutionProvider (or CoreML) - * - * Note: If an execution provider has a dedicated SessionOptionsAppendExecutionProvider_ function - * that should be used to add it. - * - * QNN supported keys: - * "backend_type": Type of QNN backend. Specifies a backend path that is the associated QNN backend library file - * name. E.g., given backend type "htp", on Windows, the backend path would be "QnnHtp.dll", and on other - * platforms, it would be "libQnnHtp.so". Mutually exclusive with "backend_path". - * Available options: - * -# "cpu" - * -# "gpu" - * -# "htp": Default. - * -# "saver" - * "backend_path": File path to QNN backend library. Mutually exclusive with "backend_type". - * "profiling_level": QNN profiling level. - * Available options: - * -# "off": Default. - * -# "basic" - * -# "detailed" - * "profiling_file_path": QNN profiling file path if ETW not enabled. - * "rpc_control_latency": QNN RPC control latency. - * "vtcm_mb": QNN VTCM size in MB. default to 0(not set). - * "htp_performance_mode": QNN performance mode. - * Available options: - * -# "burst" - * -# "balanced" - * -# "default": Default. - * -# "high_performance" - * -# "high_power_saver" - * -# "low_balanced" - * -# "extreme_power_saver" - * -# "low_power_saver" - * -# "power_saver" - * -# "sustained_high_performance" - * "qnn_saver_path": File path to the QNN Saver backend library. If specified, QNN Saver will be enabled and will - * dump QNN API calls to disk for replay/debugging. QNN Saver produces incorrect model inference results and - * may alter model/EP partitioning. Use only for debugging. - * "qnn_context_priority": QNN context priority. - * Available options: - * -# "low" - * -# "normal": Default. - * -# "normal_high" - * -# "high" - * "htp_graph_finalization_optimization_mode": Set the optimization mode for graph finalization on the HTP backend. - * Available options: - * -# "0": Default. - * -# "1": Faster preparation time, less optimal graph. - * -# "2": Longer preparation time, more optimal graph. - * -# "3": Longest preparation time, most likely even more optimal graph. See QNN SDK documentation for specific - * details. - * "soc_model": The SoC model number. Refer to the QNN SDK documentation for valid values. - * Defaults to "0" (unknown). - * "htp_arch": The minimum HTP architecture the driver will use to select compatible QNN operators. - * Available options: - * -# "0": Default (none). - * -# "68" - * -# "69" - * -# "73" - * -# "75" - * "device_id": The ID of the device to use when setting 'htp_arch'. Defaults to "0" (for single device). - * "enable_htp_fp16_precision": Used for float32 model for HTP backend. - * Enable the float32 model to be inferenced with fp16 precision. Otherwise, it will be fp32 precision. - * -# "0": With fp32 precision. - * -# "1": Default. With fp16 precision. - * "offload_graph_io_quantization": Offload graph input quantization and graph output dequantization to another - * execution provider (typically CPU EP). - * -# "0": Disabled. QNN EP will handle quantization and dequantization of graph I/O. - * -# "1": Enabled. This is the default value. - * "enable_htp_spill_fill_buffer": Enable HTP spill fill buffer setting. The flag is used while generating context - * binary. - * -# "0": Default. Disabled. - * -# "1": Enabled. - * "enable_htp_shared_memory_allocator": Enable the QNN HTP shared memory allocator. Requires libcdsprpc.so/dll to - * be available. - * -# "0": Default. Disabled. - * -# "1": Enabled. - * "dump_json_qnn_graph": Set to "1" to dump QNN graphs generated by QNN EP as JSON files. Each graph partition - * assigned to QNN EP is dumped to a separate file. - * "json_qnn_graph_dir": Directory in which to dump QNN JSON graphs. If not specified, QNN graphs are dumped in the - * program's current working directory. Ignored if "dump_json_qnn_graph" is not set. - * - * XNNPACK supported keys: - * "intra_op_num_threads": number of thread-pool size to use for XNNPACK execution provider. - * default value is 0, which means to use the session thread-pool size. - * - * \since Version 1.12. - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider, _In_ OrtSessionOptions* options, - _In_ const char* provider_name, - _In_reads_(num_keys) const char* const* provider_options_keys, - _In_reads_(num_keys) const char* const* provider_options_values, - _In_ size_t num_keys); - - /* \brief: Get a copy of kernel info - * - * \param[in] info Kernel info - * \param[out] info_copy Copy of kernel info - * - * \since Version 1.12. - */ - ORT_API2_STATUS(CopyKernelInfo, - _In_ const OrtKernelInfo* info, - _Outptr_ OrtKernelInfo** info_copy); - - /* \brief: Release kernel info - * - * \param[in] KernelInfo A copy of kernel info returned by CopyKernelInfo - * - * \since Version 1.12. - */ - ORT_CLASS_RELEASE(KernelInfo); - - /// \name Ort Training - /// @{ - /** \brief Gets the Training C Api struct - * - * Call this function to access the ::OrtTrainingApi structure that holds pointers to functions that enable - * training with onnxruntime. - * \note A NULL pointer will be returned and no error message will be printed if the training api - * is not supported with this build. A NULL pointer will be returned and an error message will be - * printed if the provided version is unsupported, for example when using a runtime older than the - * version created with this header file. - * - * \param[in] version Must be ::ORT_API_VERSION - * \return The ::OrtTrainingApi struct for the version requested. - * - * \since Version 1.13 - */ - const OrtTrainingApi*(ORT_API_CALL* GetTrainingApi)(uint32_t version)NO_EXCEPTION; - - /// @} - - /** \brief Append CANN provider to session options - * - * If CANN is not available (due to a non CANN enabled build, or if CANN is not installed on the system), this function will return failure. - * - * \param[in] options - * \param[in] cann_options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.13. - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_CANN, - _In_ OrtSessionOptions* options, _In_ const OrtCANNProviderOptions* cann_options); - - /** \brief Create an OrtCANNProviderOptions - * - * \param[out] out created ::OrtCANNProviderOptions. Must be released with OrtApi::ReleaseCANNProviderOptions - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.13. - */ - ORT_API2_STATUS(CreateCANNProviderOptions, _Outptr_ OrtCANNProviderOptions** out); - - /** \brief Set options in a CANN Execution Provider. - * - * \param[in] cann_options - * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys - * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values - * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.13. - */ - ORT_API2_STATUS(UpdateCANNProviderOptions, _Inout_ OrtCANNProviderOptions* cann_options, - _In_reads_(num_keys) const char* const* provider_options_keys, - _In_reads_(num_keys) const char* const* provider_options_values, - _In_ size_t num_keys); - - /** \brief Get serialized CANN provider options string. - * - * \param[in] cann_options OrtCANNProviderOptions instance - * \param[in] allocator a ptr to an instance of OrtAllocator obtained with CreateAllocator() - * or GetAllocatorWithDefaultOptions(), the specified allocator will be used to allocate - * continuous buffers for output strings and lengths. - * \param[out] ptr is a UTF-8 null terminated string allocated using 'allocator'. - * The caller is responsible for using the same allocator to free it. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.13. - */ - ORT_API2_STATUS(GetCANNProviderOptionsAsString, _In_ const OrtCANNProviderOptions* cann_options, - _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); - - /** \brief Release an OrtCANNProviderOptions - * - * \param[in] input The pointer of OrtCANNProviderOptions which will been deleted - * - * \since Version 1.13. - */ - void(ORT_API_CALL* ReleaseCANNProviderOptions)(_Frees_ptr_opt_ OrtCANNProviderOptions* input); - - /* \brief Get OrtDevice type from MemoryInfo - * - * \since Version 1.14 - */ - void(ORT_API_CALL* MemoryInfoGetDeviceType)(_In_ const OrtMemoryInfo* ptr, _Out_ OrtMemoryInfoDeviceType* out); - - /* \brief Update the OrtEnv instance with custom log severity level - * - * \param[in] ort_env The OrtEnv instance being used - * \param[in] log_severity_level The log severity level. - * - * \since Version 1.14. - */ - ORT_API2_STATUS(UpdateEnvWithCustomLogLevel, _In_ OrtEnv* ort_env, OrtLoggingLevel log_severity_level); - - /* \brief Set affinities for intra op threads - * - * Affinity string follows format: - * logical_processor_id,logical_processor_id;logical_processor_id,logical_processor_id - * Semicolon isolates configurations among threads, while comma split processors where ith thread expected to attach to. - * e.g. 1,2,3;4,5 - * specifies affinities for two threads, with the 1st thread attach to the 1st, 2nd, and 3rd processor, and 2nd thread to the 4th and 5th. - * To ease the configuration, an "interval" is also allowed: - * e.g. 1-8;8-16;17-24 - * orders that the 1st thread runs on first eight processors, 2nd thread runs on next eight processors, and so forth. - * Note: - * 1. Once set, the number of thread affinities must equal to intra_op_num_threads - 1, - * ort does not set affinity on the main thread which is started and managed by the calling app; - * 2. For windows, ort will infer the group id from a logical processor id, for example, assuming there are two groups with each has 64 logical processors, - * an id of 64 will be inferred as the last processor of the 1st group, while 65 will be interpreted as the 1st processor of the second group. - * Hence 64-65 is an invalid configuration, because a windows thread cannot be attached to processors across group boundary. - * - * \since Version 1.14 - */ - ORT_API2_STATUS(SetGlobalIntraOpThreadAffinity, _Inout_ OrtThreadingOptions* tp_options, const char* affinity_string); - - /** \brief Register custom ops from a shared library. - * - * Loads a shared library (.dll on windows, .so on linux, etc) named 'library_name' and looks for this entry point: - * OrtStatus* RegisterCustomOps(OrtSessionOptions * options, const OrtApiBase* api); - * It then passes in the provided session options to this function along with the api base. - * - * The handle to the loaded library is automatically released by ORT when the last OrtSession that references the - * library handle is released. If no OrtSession is created, then the library handle is released when the provided - * OrtSessionOptions is released. - * - * \param[in] options The session options. - * \param[in] library_name The name of the shared library to load and register. Refer to OS-specific dynamic library - * loading utilities (e.g., LoadLibraryEx on Windows or dlopen on Linux/MacOS) for information - * on the format of library names and search paths. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.14 - */ - ORT_API2_STATUS(RegisterCustomOpsLibrary_V2, _Inout_ OrtSessionOptions* options, _In_ const ORTCHAR_T* library_name); - - /** \brief Register custom ops by calling a RegisterCustomOpsFn function. - * - * Searches for registration_func_name and if found calls it. - * - * The library containing the function must either be linked against or previously loaded by the executable. - * - * If you want ONNX Runtime to load the library and manage its lifetime, use RegisterCustomOpsLibrary_V2. - * - * RegisterCustomOpsUsingFunction can be used in scenarios where it may not be possible for ONNX Runtime to load - * the library from a path. e.g. mobile platforms where the library must be linked into the app. - * - * The registration function must have the signature of RegisterCustomOpsFn: - * OrtStatus* (*fn)(OrtSessionOptions* options, const OrtApiBase* api); - * - * See https://onnxruntime.ai/docs/reference/operators/add-custom-op.html for details on how the registration - * function should be implemented. - * - * \param[in] options OrtSessionOptions that is passed through as the first argument in the call to the - * registration function. - * \param[in] registration_func_name Name of registration function to use. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.14 - */ - ORT_API2_STATUS(RegisterCustomOpsUsingFunction, _Inout_ OrtSessionOptions* options, - _In_ const char* registration_func_name); - - /// \name OrtKernelInfo - /// Custom operator APIs. - /// @{ - - /** \brief Get the number of inputs from ::OrtKernelInfo. - * - * Used in the CreateKernel callback of an OrtCustomOp to query the number of inputs - * during kernel/session creation. - * - * \param[in] info Instance of ::OrtKernelInfo. - * \param[out] out Pointer to variable assigned with the result on success. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.14 - */ - ORT_API2_STATUS(KernelInfo_GetInputCount, _In_ const OrtKernelInfo* info, _Out_ size_t* out); - - /** \brief Get the number of outputs from ::OrtKernelInfo. - * - * Used in the CreateKernel callback of an OrtCustomOp to query the number of outputs - * during kernel/session creation. - * - * \param[in] info Instance of ::OrtKernelInfo. - * \param[out] out Pointer to variable assigned with the result on success. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.14 - */ - ORT_API2_STATUS(KernelInfo_GetOutputCount, _In_ const OrtKernelInfo* info, _Out_ size_t* out); - - /** \brief Get the name of a ::OrtKernelInfo's input. - * - * Used in the CreateKernel callback of an OrtCustomOp to query an input's name - * during kernel/session creation. - * - * If `out` is nullptr, the value of `size` is set to the size of the name - * string (including null-terminator), and a success status is returned. - * - * If the `size` parameter is greater than or equal to the name string's size, - * the value of `size` is set to the true size of the string (including null-terminator), - * the provided memory is filled with the string's contents, and a success status is returned. - * - * If the `size` parameter is less than the actual string's size and `out` - * is not nullptr, the value of `size` is set to the true size of the string - * and a failure status is returned. - * - * \param[in] info An instance of ::OrtKernelInfo. - * \param[in] index The index of the input name to get. Returns a failure status if out-of-bounds. - * \param[out] out Memory location into which to write the UTF-8 null-terminated string representing the input's name. - * \param[in,out] size Pointer to the size of the `out` buffer. See above comments for details. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.14 - */ - ORT_API2_STATUS(KernelInfo_GetInputName, _In_ const OrtKernelInfo* info, size_t index, _Out_ char* out, - _Inout_ size_t* size); - - /** \brief Get the name of a ::OrtKernelInfo's output. - * - * Used in the CreateKernel callback of an OrtCustomOp to query an output's name - * during kernel/session creation. - * - * If `out` is nullptr, the value of `size` is set to the size of the name - * string (including null-terminator), and a success status is returned. - * - * If the `size` parameter is greater than or equal to the name string's size, - * the value of `size` is set to the true size of the string (including null-terminator), - * the provided memory is filled with the string's contents, and a success status is returned. - * - * If the `size` parameter is less than the actual string's size and `out` - * is not nullptr, the value of `size` is set to the true size of the string - * and a failure status is returned. - * - * \param[in] info An instance of ::OrtKernelInfo. - * \param[in] index The index of the output name to get. Returns a failure status if out-of-bounds. - * \param[out] out Memory location into which to write the UTF-8 null-terminated string representing the output's - * name. - * \param[in,out] size Pointer to the size of the `out` buffer. See above comments for details. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.14 - */ - ORT_API2_STATUS(KernelInfo_GetOutputName, _In_ const OrtKernelInfo* info, size_t index, _Out_ char* out, - _Inout_ size_t* size); - - /** \brief Get the type information for a ::OrtKernelInfo's input. - * - * Used in the CreateKernel callback of an OrtCustomOp to query the shape and type information - * of an input during kernel/session creation. - * - * \param[in] info An instance of ::OrtKernelInfo. - * \param[in] index Which input to get the type information for - * \param[out] type_info Pointer set to the resulting ::OrtTypeInfo. Must be freed with OrtApi::ReleaseTypeInfo. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.14 - */ - ORT_API2_STATUS(KernelInfo_GetInputTypeInfo, _In_ const OrtKernelInfo* info, size_t index, - _Outptr_ OrtTypeInfo** type_info); - - /** \brief Get the type information for a ::OrtKernelInfo's output. - * - * Used in the CreateKernel callback of an OrtCustomOp to query the shape and type information - * of an output during kernel/session creation. - * - * \param[in] info An instance of ::OrtKernelInfo. - * \param[in] index Which input to get the type information for - * \param[out] type_info Pointer set to the resulting ::OrtTypeInfo. Must be freed with OrtApi::ReleaseTypeInfo. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.14 - */ - ORT_API2_STATUS(KernelInfo_GetOutputTypeInfo, _In_ const OrtKernelInfo* info, size_t index, - _Outptr_ OrtTypeInfo** type_info); - - /** \brief Get a ::OrtValue tensor stored as an attribute in the graph node. - * - * Used in the CreateKernel callback of an OrtCustomOp to get a tensor attribute. - * - * \param[in] info ::OrtKernelInfo instance. - * \param[in] name UTF-8 null-terminated string representing the attribute's name. - * \param[in] allocator Allocator used to allocate the internal tensor state. - * \param[out] out Returns newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue, - * which will also free internal tensor state allocated with the provided allocator. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(KernelInfoGetAttribute_tensor, _In_ const OrtKernelInfo* info, _In_z_ const char* name, - _Inout_ OrtAllocator* allocator, _Outptr_ OrtValue** out); - - /// @} - /// \name OrtSessionOptions - /// Custom operator APIs - /// @{ - - /** \brief Checks if the given session configuration entry exists. - * - * The config_key formats are defined in onnxruntime_session_options_config_keys.h - * - * Can be used in a custom operator library to check for session configuration entries - * that target one or more custom operators in the library. Example: The config entry - * custom_op.myop.some_key targets a custom op named "myop". - * - * \param[in] options The ::OrtSessionOptions instance. - * \param[in] config_key A null-terminated UTF-8 string representation of the configuration key. - * \param[out] out Pointer set to 1 if the entry exists and 0 otherwise. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.14 - */ - ORT_API2_STATUS(HasSessionConfigEntry, _In_ const OrtSessionOptions* options, - _In_z_ const char* config_key, _Out_ int* out); - - /** \brief Get a session configuration value. - * - * Returns a failure status if the configuration key does not exist. - * The config_key and the format of config_value are defined in onnxruntime_session_options_config_keys.h - * - * If `config_value` is nullptr, the value of `size` is set to the true size of the string - * value (including null-terminator), and a success status is returned. - * - * If the `size` parameter is greater than or equal to the actual string value's size, - * the value of `size` is set to the true size of the string value, the provided memory - * is filled with the value's contents, and a success status is returned. - * - * If the `size` parameter is less than the actual string value's size and `config_value` - * is not nullptr, the value of `size` is set to the true size of the string value - * and a failure status is returned. - * - * Can be used in a custom operator library to get session configuration entries - * that target one or more custom operators in the library. Example: The config entry - * custom_op.myop.some_key targets a custom op named "myop". - * - * \param[in] options The session options. - * \param[in] config_key A null-terminated UTF-8 string representation of the config key. - * \param[in] config_value Pointer to memory where the null-terminated UTF-8 string value will be stored. - * \param[in,out] size Pointer to the size of the `config_value` buffer. See above comments for details. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.14 - */ - ORT_API2_STATUS(GetSessionConfigEntry, _In_ const OrtSessionOptions* options, - _In_z_ const char* config_key, _Out_ char* config_value, _Inout_ size_t* size); - - /// @} - - /** \brief Append dnnl provider to session options - * - * If oneDNN is not available, this function will return failure. - * - * \param[in] options - * \param[in] dnnl_options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.15. - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_Dnnl, - _In_ OrtSessionOptions* options, _In_ const OrtDnnlProviderOptions* dnnl_options); - - /** \brief Create an OrtDnnlProviderOptions - * - * \param[out] out Newly created ::OrtDnnlProviderOptions. Must be released with OrtApi::ReleaseDnnlProviderOptions - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.15. - */ - ORT_API2_STATUS(CreateDnnlProviderOptions, _Outptr_ OrtDnnlProviderOptions** out); - - /** \brief Set options in a oneDNN Execution Provider. - * - * Key should be in null terminated string format of the member of ::OrtDnnlProviderOptions - * and value should be its related range. - * - * For example, key="use_arena" and value="1" - * - * \param[in] dnnl_options - * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys - * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values - * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.15. - */ - ORT_API2_STATUS(UpdateDnnlProviderOptions, _Inout_ OrtDnnlProviderOptions* dnnl_options, - _In_reads_(num_keys) const char* const* provider_options_keys, - _In_reads_(num_keys) const char* const* provider_options_values, - _In_ size_t num_keys); - - /** - * Get serialized oneDNN provider options string. - * - * For example, "use_arena=1;......" - * - * \param dnnl_options - OrtDnnlProviderOptions instance - * \param allocator - a ptr to an instance of OrtAllocator obtained with CreateAllocator() or GetAllocatorWithDefaultOptions() - * the specified allocator will be used to allocate continuous buffers for output strings and lengths. - * \param ptr - is a UTF-8 null terminated string allocated using 'allocator'. The caller is responsible for using the same allocator to free it. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.15. - */ - ORT_API2_STATUS(GetDnnlProviderOptionsAsString, _In_ const OrtDnnlProviderOptions* dnnl_options, _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); - - /** \brief Release an ::OrtDnnlProviderOptions - * - * \since Version 1.15. - */ - void(ORT_API_CALL* ReleaseDnnlProviderOptions)(_Frees_ptr_opt_ OrtDnnlProviderOptions* input); - - /// \name OrtKernelInfo - /// Custom operator APIs. - /// @{ - - /** \brief Get the graph node name from ::OrtKernelInfo. - * - * If `out` is nullptr, the value of `size` is set to the size of the name - * string (including null-terminator), and a success status is returned. - * - * If the `size` parameter is greater than or equal to the name string's size, - * the value of `size` is set to the true size of the string (including null-terminator), - * the provided memory is filled with the string's contents, and a success status is returned. - * - * If the `size` parameter is less than the actual string's size and `out` - * is not nullptr, the value of `size` is set to the true size of the string - * and a failure status is returned. - * - * Can be used in a custom operator's CreateKernel callback to get the name of the operator's node name in the graph. - * - * \param[in] info An instance of ::OrtKernelInfo. - * \param[out] out Memory location into which to write the UTF-8 null-terminated string representing the name. - * \param[in,out] size Pointer to the size of the `out` buffer. See above comments for details. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.15 - */ - ORT_API2_STATUS(KernelInfo_GetNodeName, _In_ const OrtKernelInfo* info, _Out_ char* out, _Inout_ size_t* size); - - /** \brief Get the session logger from ::OrtKernelInfo. - * - * Used in the CreateKernel callback of an OrtCustomOp to get a logger that can be used to log - * messages. - * - * \param[in] info An instance of ::OrtKernelInfo. - * \param[out] logger Pointer set to the session's ::OrtLogger. Owned by ONNX Runtime, so do not free. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.15 - */ - ORT_API2_STATUS(KernelInfo_GetLogger, _In_ const OrtKernelInfo* info, _Outptr_ const OrtLogger** logger); - - /// @} - /// \name OrtKernelContext - /// Custom operator APIs. - /// @{ - - /** \brief Get the runtime logger from ::OrtKernelContext. - * - * Used in the KernelCompute callback of an OrtCustomOp to get a logger that can be used to log - * messages during inference. - * - * \param[in] context An instance of ::OrtKernelContext. - * \param[out] logger Pointer set to the kernel context's ::OrtLogger. Owned by ONNX Runtime, so do not free. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.15 - */ - ORT_API2_STATUS(KernelContext_GetLogger, _In_ const OrtKernelContext* context, _Outptr_ const OrtLogger** logger); - - /// @} - /// \name OrtLogger - /// Custom operator APIs. - /// @{ - - /** \brief Logs a message at the given severity level using the provided ::OrtLogger. - * - * Only messages with a severity level equal or greater than the ::OrtLogger's logging severity level - * are logged. Use OrtApi::Logger_GetLoggingSeverityLevel to get the ::OrtLogger's logging severity - * level. - * - * Can be used in custom operators to log messages with the logger retrieved via OrtApi::KernelInfo_GetLogger. - * - * \param[in] logger The ::OrtLogger instance. - * \param[in] log_severity_level The message's severity level. - * \param[in] message The message to log. - * \param[in] file_path The filepath of the file in which the message is logged. Usually the value of ORT_FILE. - * \param[in] line_number The file line number in which the message is logged. Usually the value of __LINE__. - * \param[in] func_name The name of the function in which the message is logged. Usually the value of __FUNCTION__. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.15 - */ - ORT_API2_STATUS(Logger_LogMessage, _In_ const OrtLogger* logger, OrtLoggingLevel log_severity_level, - _In_z_ const char* message, _In_z_ const ORTCHAR_T* file_path, int line_number, - _In_z_ const char* func_name); - - /** \brief Get the logging severity level of the ::OrtLogger. - * - * Can be used in a custom operator to get the logging serverity level of the ::OrtLogger associated with - * the ::OrtKernelInfo. - * - * \param[in] logger The ::OrtLogger instance. - * \param[out] out Pointer to variable assigned with the logging severity level on success. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.15 - */ - ORT_API2_STATUS(Logger_GetLoggingSeverityLevel, _In_ const OrtLogger* logger, _Out_ OrtLoggingLevel* out); - - /// @} - - /** \brief Get a ::OrtValue tensor stored as a constant initializer in the graph node. - * - * Used in the CreateKernel callback of an OrtCustomOp to get a tensor value. - * - * \param[in] info ::OrtKernelInfo instance. - * \param[in] index The node index. - * \param[out] is_constant Is it a constant node input or not. - * \param[out] out The OrtValue tensor value. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.15. - */ - ORT_API2_STATUS(KernelInfoGetConstantInput_tensor, _In_ const OrtKernelInfo* info, size_t index, _Out_ int* is_constant, _Outptr_ const OrtValue** out); - - /** \brief Get Optional Type information from an ::OrtTypeInfo - * - * This augments ::OrtTypeInfo to return an ::OrtOptionalTypeInfo when the type is optional. - * The OrtOptionalTypeInfo also has a nested ::OrtTypeInfo that describes the type of the optional value. - * ::OrtOptionalTypeInfo type can only appear within model metadata to describe inputs/outputs. - * The actual OrtValues that are supplied in place of optional type inputs should contain - * specific type that is described by ::OrtOptionalTypeInfo. - * - * So the picture: ::OrtTypeInfo -> ::OrtOptionalTypeInfo -> ::OrtTypeInfo (describes the type that can be supplied - * in place of the optional type when creating the actual ::OrtValue). - * - * \param[in] type_info - * \param[out] out A pointer to the ::OrtOptionalTypeInfo. Do not free this value, - * it is owned by OrtTypeInfo instance. When the type_info does not represent - * optional type, nullptr is returned in out. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.15. - */ - ORT_API2_STATUS(CastTypeInfoToOptionalTypeInfo, _In_ const OrtTypeInfo* type_info, - _Outptr_result_maybenull_ const OrtOptionalTypeInfo** out); - - /** \brief Get OrtTypeInfo for the allowed contained type from an ::OrtOptionalTypeInfo. - * - * This augments ::OrtOptionalTypeInfo to return an ::OrtTypeInfo for the contained type. - * The OrtOptionalTypeInfo has a nested ::OrtTypeInfo that describes the type of the optional value. - * ::OrtOptionalTypeInfo type can only appear within model metadata to describe inputs/outputs. - * The actual OrtValues that are supplied in place of optional type inputs should contain - * specific type that is described by the returned ::OrtTypeInfo. - * - * \param[in] optional_type_info - * \param[out] out A copy of ::OrtTypeInfo for what the optional value could be. - * The user must free this value with ReleaseTypeInfo. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.15. - */ - ORT_API2_STATUS(GetOptionalContainedTypeInfo, _In_ const OrtOptionalTypeInfo* optional_type_info, - _Outptr_ OrtTypeInfo** out); - - /** \brief Set a single string in a string tensor - * Do not zero terminate the string data. - * - * \param[in] value A string tensor - * \param[in] index - flat index of the element - * \param[in] length_in_bytes length of the buffer in utf-8 bytes (without the null terminator) - * \param[inout] buffer - address of return value - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetResizedStringTensorElementBuffer, _Inout_ OrtValue* value, _In_ size_t index, _In_ size_t length_in_bytes, _Inout_ char** buffer); - - /** \brief Get Allocator from KernelContext for a specific memoryInfo. Please use C API ReleaseAllocator to release out object - * - * \param[in] context OrtKernelContext instance - * \param[in] mem_info OrtMemoryInfo instance - * \param[out] out A pointer to OrtAllocator. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.15. - */ - ORT_API2_STATUS(KernelContext_GetAllocator, _In_ const OrtKernelContext* context, _In_ const OrtMemoryInfo* mem_info, _Outptr_ OrtAllocator** out); - - /** \brief Returns a null terminated string of the build info including git info and cxx flags - * - * \return UTF-8 encoded version string. Do not deallocate the returned buffer. - * - * \since Version 1.15. - */ - const char*(ORT_API_CALL* GetBuildInfoString)(void); - - /// \name OrtROCMProviderOptions - /// @{ - - /** \brief Create an OrtROCMProviderOptions - * - * \param[out] out Newly created ::OrtROCMProviderOptions. Must be released with OrtApi::ReleaseROCMProviderOptions - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.16. - */ - ORT_API2_STATUS(CreateROCMProviderOptions, _Outptr_ OrtROCMProviderOptions** out); - - /** \brief Set options in a ROCm Execution Provider. - * - * Please refer to https://onnxruntime.ai/docs/execution-providers/ROCm-ExecutionProvider.html - * to know the available keys and values. Key should be in null terminated string format of the member of - * ::OrtROCMProviderOptions and value should be its related range. - * - * For example, key="device_id" and value="0" - * - * \param[in] rocm_options - * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys - * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values - * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.16. - */ - ORT_API2_STATUS(UpdateROCMProviderOptions, _Inout_ OrtROCMProviderOptions* rocm_options, - _In_reads_(num_keys) const char* const* provider_options_keys, - _In_reads_(num_keys) const char* const* provider_options_values, - _In_ size_t num_keys); - - /** - * Get serialized ROCm provider options string. - * - * For example, "device_id=0;arena_extend_strategy=0;......" - * - * \param rocm_options - OrtROCMProviderOptions instance - * \param allocator - a ptr to an instance of OrtAllocator obtained with CreateAllocator() or GetAllocatorWithDefaultOptions() - * the specified allocator will be used to allocate continuous buffers for output strings and lengths. - * \param ptr - is a UTF-8 null terminated string allocated using 'allocator'. The caller is responsible for using the same allocator to free it. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.16. - */ - ORT_API2_STATUS(GetROCMProviderOptionsAsString, _In_ const OrtROCMProviderOptions* rocm_options, _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); - - /** \brief Release an ::OrtROCMProviderOptions - * - * \note This is an exception in the naming convention of other Release* functions, as the name of the method does not have the V2 suffix, but the type does - * - * \since Version 1.16. - */ - void(ORT_API_CALL* ReleaseROCMProviderOptions)(_Frees_ptr_opt_ OrtROCMProviderOptions* input); - - /** \brief Create an allocator with specific type and register it with the ::OrtEnv - * This API enhance CreateAndRegisterAllocator that it can create an allocator with specific type, not just CPU allocator - * Enables sharing the allocator between multiple sessions that use the same env instance. - * Lifetime of the created allocator will be valid for the duration of the environment. - * Returns an error if an allocator with the same ::OrtMemoryInfo is already registered. - * \param[in] env OrtEnv instance - * \param[in] provider_type ExecutionProvider type - * \param[in] mem_info OrtMemoryInfo instance - * \param[in] arena_cfg Arena configuration - * \param[in] provider_options_keys key of the provider options map - * \param[in] provider_options_values value of the provider options map - * \param[in] num_keys Length of the provider options map - */ - ORT_API2_STATUS(CreateAndRegisterAllocatorV2, _Inout_ OrtEnv* env, _In_ const char* provider_type, _In_ const OrtMemoryInfo* mem_info, _In_ const OrtArenaCfg* arena_cfg, - _In_reads_(num_keys) const char* const* provider_options_keys, _In_reads_(num_keys) const char* const* provider_options_values, _In_ size_t num_keys); - - /** \brief Run the model asynchronously in a thread owned by intra op thread pool - * - * \param[in] session - * \param[in] run_options If nullptr, will use a default ::OrtRunOptions - * \param[in] input_names Array of null terminated UTF8 encoded strings of the input names - * \param[in] input Array of ::OrtValue%s of the input values - * \param[in] input_len Number of elements in the input_names and inputs arrays - * \param[in] output_names Array of null terminated UTF8 encoded strings of the output names - * \param[in] output_names_len Number of elements in the output_names and outputs array - * \param[out] output OrtValue* array of size output_names_len. - * On calling RunAsync, output[i] could either be a null or a pointer to a preallocated OrtValue. - * Later, the output array will be passed to run_async_callback with all null(s) filled with valid - * OrtValue pointer(s) allocated by onnxruntime. - * NOTE: it is customer's duty to finally release the output array and each of its member, - * regardless of whether the member (OrtValue*) is allocated by onnxruntime or preallocated by the customer. - * \param[in] run_async_callback Callback function on model run completion - * \param[in] user_data User data that pass back to run_async_callback - */ - ORT_API2_STATUS(RunAsync, _Inout_ OrtSession* session, _In_opt_ const OrtRunOptions* run_options, - _In_reads_(input_len) const char* const* input_names, - _In_reads_(input_len) const OrtValue* const* input, size_t input_len, - _In_reads_(output_names_len) const char* const* output_names, size_t output_names_len, - _Inout_updates_all_(output_names_len) OrtValue** output, - _In_ RunAsyncCallbackFn run_async_callback, _In_opt_ void* user_data); - - /** - * Update TensorRT EP provider option where its data type is pointer, for example 'user_compute_stream'. - * If the data type of the provider option can be represented by string please use UpdateTensorRTProviderOptions. - * - * Note: It's caller's responsibility to properly manage the lifetime of the instance pointed by this pointer. - * - * \param tensorrt_options - OrtTensorRTProviderOptionsV2 instance - * \param key - Name of the provider option - * \param value - A pointer to the instance that will be assigned to this provider option - * - * \since Version 1.16. - */ - ORT_API2_STATUS(UpdateTensorRTProviderOptionsWithValue, _Inout_ OrtTensorRTProviderOptionsV2* tensorrt_options, _In_ const char* key, _In_ void* value); - - /** - * Get TensorRT EP provider option where its data type is pointer. - * If the data type of the provider option can be represented by string please use GetTensorRTProviderOptionsAsString. - * - * \param tensorrt_options - OrtTensorRTProviderOptionsV2 instance - * \param key - Name of the provider option - * \param ptr - A pointer to the instance that is kept by the provider option - * - * \since Version 1.16. - */ - ORT_API2_STATUS(GetTensorRTProviderOptionsByName, _In_ const OrtTensorRTProviderOptionsV2* tensorrt_options, _In_ const char* key, _Outptr_ void** ptr); - - /** - * Update CUDA EP provider option where its data type is pointer, for example 'user_compute_stream'. - * If the data type of the provider option can be represented by string please use UpdateCUDAProviderOptions. - * - * Note: It's caller's responsibility to properly manage the lifetime of the instance pointed by this pointer. - * - * \param cuda_options - OrtCUDAProviderOptionsV2 instance - * \param key - Name of the provider option - * \param value - A pointer to the instance that will be assigned to this provider option - * - * \since Version 1.16. - */ - ORT_API2_STATUS(UpdateCUDAProviderOptionsWithValue, _Inout_ OrtCUDAProviderOptionsV2* cuda_options, _In_ const char* key, _In_ void* value); - - /** - * Get CUDA EP provider option where its data type is pointer. - * If the data type of the provider option can be represented by string please use GetCUDAProviderOptionsAsString. - * - * \param cuda_options - OrtCUDAProviderOptionsV2 instance - * \param key - Name of the provider option - * \param ptr - A pointer to the instance that is kept by the provider option - * - * \since Version 1.16. - */ - ORT_API2_STATUS(GetCUDAProviderOptionsByName, _In_ const OrtCUDAProviderOptionsV2* cuda_options, _In_ const char* key, _Outptr_ void** ptr); - - /** - * Get a EP resource. - * E.g. a cuda stream or a cublas handle - * - * \param context - Kernel context - * \param resource_version - Version of the resource - * \param resource_id - Type of resource - * \param resource - A pointer to returned resource - * - * \since Version 1.16. - */ - ORT_API2_STATUS(KernelContext_GetResource, _In_ const OrtKernelContext* context, _In_ int resource_version, - _In_ int resource_id, _Outptr_ void** resource); - - /** \brief Set user logging function - * - * By default the logger created by the CreateEnv* functions is used to create the session logger as well. - * This function allows a user to override this default session logger with a logger of their own choosing. This way - * the user doesn't have to create a separate environment with a custom logger. This addresses the problem when - * the user already created an env but now wants to use a different logger for a specific session (for debugging or - * other reasons). - * - * \param[in] options - * \param[in] user_logging_function A pointer to a logging function. - * \param[in] user_logging_param A pointer to arbitrary data passed as the ::OrtLoggingFunction `param` parameter to - * `user_logging_function`. This parameter is optional. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.17. - */ - ORT_API2_STATUS(SetUserLoggingFunction, _Inout_ OrtSessionOptions* options, - _In_ OrtLoggingFunction user_logging_function, _In_opt_ void* user_logging_param); - - /** - * Get number of input from OrtShapeInferContext - * - * \param[in] context - * \param[out] out The number of inputs - * - * \since Version 1.17. - */ - ORT_API2_STATUS(ShapeInferContext_GetInputCount, _In_ const OrtShapeInferContext* context, _Out_ size_t* out); - - /** - * Get type and shape info of an input - * - * \param[in] context - * \param[in] index The index of the input - * \param[out] info Type shape info of the input - * - * \since Version 1.17. - */ - ORT_API2_STATUS(ShapeInferContext_GetInputTypeShape, _In_ const OrtShapeInferContext* context, _In_ size_t index, _Outptr_ OrtTensorTypeAndShapeInfo** info); - - /** - * Get attribute from OrtShapeInferContext. Note that OrtShapeInferContext is a per-node context, one could only read attribute from current node. - * - * \param[in] context - * \param[in] attr_name Name of the attribute - * \param[out] attr Handle of the attribute fetched - * - * \since Version 1.17. - */ - ORT_API2_STATUS(ShapeInferContext_GetAttribute, _In_ const OrtShapeInferContext* context, _In_ const char* attr_name, _Outptr_ const OrtOpAttr** attr); - - /** - * Set type and shape info of an output - * - * \param[in] context - * \param[in] index The index of the output - * \param[out] info Type shape info of the output - * - * \since Version 1.17. - */ - ORT_API2_STATUS(ShapeInferContext_SetOutputTypeShape, _In_ const OrtShapeInferContext* context, _In_ size_t index, _In_ const OrtTensorTypeAndShapeInfo* info); - - /** - * Set symbolic shape to type shape info - * - * \param[in] info Type shape info - * \param[in] dim_params Symbolic strings - * \param[in] dim_params_length Number of strings - * - * \since Version 1.17. - */ - ORT_API2_STATUS(SetSymbolicDimensions, _In_ OrtTensorTypeAndShapeInfo* info, _In_ const char* dim_params[], _In_ size_t dim_params_length); - - /** - * Read contents of an attribute to data - * - * \param[in] op_attr - * \param[in] type Attribute type - * \param[out] data Memory address to save raw content of the attribute - * \param[in] len Number of bytes allowed to store in data - * \param[out] out Number of bytes required to save the data when the call failed, or the real number of bytes saved to data on success - * - * \since Version 1.17. - */ - ORT_API2_STATUS(ReadOpAttr, _In_ const OrtOpAttr* op_attr, _In_ OrtOpAttrType type, _Inout_ void* data, _In_ size_t len, _Out_ size_t* out); - - /** \brief Set whether to use deterministic compute. - * - * Default is false. If set to true, this will enable deterministic compute for GPU kernels where possible. - * Note that this most likely will have a performance cost. - * - * \param[in] options - * \param[in] value - * - * \since Version 1.17. - */ - ORT_API2_STATUS(SetDeterministicCompute, _Inout_ OrtSessionOptions* options, bool value); - - /** - * Run fn in parallel - * - * \param[in] context - * \param[in] fn Function accepting usr_data and an integer as iterator - * \param[in] total The number of times fn is to be invoked - * \param[in] num_batch Number of batches by which the "total" is to be divided in maximum. When zero, there is no limit - * \param[in] usr_data User data to be passed back to fn - * - * \since Version 1.17. - */ - ORT_API2_STATUS(KernelContext_ParallelFor, _In_ const OrtKernelContext* context, _In_ void (*fn)(void*, size_t), _In_ size_t total, _In_ size_t num_batch, _In_ void* usr_data); - - /** \brief Append OpenVINO execution provider to the session options - * - * If OpenVINO is not available (due to a non OpenVINO enabled build, or if OpenVINO is not installed on the system), this function will fail. - * - * \param[in] options - * \param[in] provider_options_keys - * \param[in] provider_options_values - * \param[in] num_keys - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.17. - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_OpenVINO_V2, - _In_ OrtSessionOptions* options, - _In_reads_(num_keys) const char* const* provider_options_keys, - _In_reads_(num_keys) const char* const* provider_options_values, - _In_ size_t num_keys); - - /** \brief Append VitisAI provider to session options - * - * If VitisAI is not available (due to a non VitisAI enabled build, or if VitisAI is not installed on the system), this function will return failure. - * - * \param[in] options - * \param[in] provider_options_keys - * \param[in] provider_options_values - * \param[in] num_keys - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.18. - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_VitisAI, - _In_ OrtSessionOptions* options, - _In_reads_(num_keys) const char* const* provider_options_keys, - _In_reads_(num_keys) const char* const* provider_options_values, - _In_ size_t num_keys); - - /** \brief Get scratch buffer from the corresponding allocator under the sepcific OrtMemoryInfo object. - * NOTE: callers are responsible to release this scratch buffer from the corresponding allocator - * \param[in] context OrtKernelContext instance - * \param[in] mem_info OrtMemoryInfo instance - * \param[in] count_or_bytes How many bytes is this scratch buffer - * \param[out] out A pointer to the scrach buffer - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.18. - */ - ORT_API2_STATUS(KernelContext_GetScratchBuffer, _In_ const OrtKernelContext* context, _In_ const OrtMemoryInfo* mem_info, _In_ size_t count_or_bytes, _Outptr_ void** out); - - /** \brief Get allocator from KernelInfo for a specific memory type. Please use C API ReleaseAllocator to release out object - * - * \param[in] info OrtKernelInfo instance - * \param[in] mem_type OrtMemType object - * \param[out] out A pointer to OrtAllocator - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.18. - */ - ORT_API2_STATUS(KernelInfoGetAllocator, _In_ const OrtKernelInfo* info, _In_ OrtMemType mem_type, _Outptr_ OrtAllocator** out); - - /** \brief Replace initialized Tensors with external data with the provided files in memory - * - * The function will find the initialized TensorProtos with external data in the graph with the provided - * external file names and the file content in memory. The API gets the external file name, offset, data length - * from TensorProto, and locate the tensor data from the file in memory buffer. - * It creates a Tensor to replace the existing Tensor in graph. The replacement - * will occur before any of the optimizations take place. The data will be copied into the graph - * since TensorProto can't refer to the user provided buffers. - * - * \param[in] options - * \param[in] external_initializer_file_names Array of null terminated UTF-8 encoded strings of the file names - * which holds the external initializers. - * \param[in] external_initializer_file_buffer_array Array of pointers to the buffer of the file content. - * The buffer can be freed after session creation. - * \param[in] external_initializer_file_lengths Array of size_t to indicate the length of file content - * \param[in] num_external_initializer_files Number of external files - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.18. - */ - ORT_API2_STATUS(AddExternalInitializersFromFilesInMemory, _In_ OrtSessionOptions* options, - _In_reads_(num_external_initializer_files) const ORTCHAR_T* const* external_initializer_file_names, - _In_reads_(num_external_initializer_files) char* const* external_initializer_file_buffer_array, - _In_reads_(num_external_initializer_files) const size_t* external_initializer_file_lengths, - size_t num_external_initializer_files); - - /** \brief Create an OrtLoraAdapter - * - * The function attempts to locate file specified by adapter_file_path, read it and create an OrtLoraAdapter - * instance. The adapter_file_path should be a valid path to a file that contains a valid Lora Adapter - * format. The function attempts to validate the format at load time. The file will always be memory mapped, unless - * the platform does not support memory mapping, in which case the file will be read into memory. - * - * \param[in] adapter_file_path adapter file path. - * \param[in] allocator optional pointer to a device allocator. If specified - * data is copied to the device at some point before Run() is invoked. If nullptr, data stays on CPU. - * The data would still be copied to device if required by the model at inference time. - * \param[out] out A pointer to a newly created OrtLoraAdapter instance. Must be released with - * OrtApi::ReleaseLoraAdapter. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.20. - */ - ORT_API2_STATUS(CreateLoraAdapter, const ORTCHAR_T* adapter_file_path, _In_ OrtAllocator* allocator, - _Outptr_ OrtLoraAdapter** out); - - /** \brief Create an OrtLoraAdapter - * - * The function copies the bytes from the array and creates an OrtLoraAdapter instance. - * - * - * \param[in] bytes pointer to a valid Lora Adapter format buffer. - * \param[in] num_bytes length of bytes buffer. - * \param[in] allocator optional pointer to a device allocator. If specified - * data is copied to the device at some point before Run() is invoked. If nullptr, data stays on CPU. - * The data would still be copied to device if required by the model at inference time. - * \param[out] out A pointer to a newly created OrtLoraAdapter instance. Must be released with - * OrtApi::ReleaseLoraAdapter. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.20. - */ - ORT_API2_STATUS(CreateLoraAdapterFromArray, _In_ const void* bytes, size_t num_bytes, _In_ OrtAllocator* allocator, - _Outptr_ OrtLoraAdapter** out); - - /** \brief Release an ::OrtLoraAdapter obtained from OrtApi::CreateLoraAdapter - */ - ORT_CLASS_RELEASE(LoraAdapter); - - /** \brief Add the Lora Adapter to the list of active adapters. - * - * The function adds the Lora Adapter to the list of active adapters. The Lora Adapter must be created with - * OrtApi::CreateLoraAdapter or FromArray. The Lora Adapter will be used by the session to run the model. - * The instance of the OrtRunOptions can then be used to customize the Run() calls. - * More than one OrtLoraAdapter can be active at the same time. Lora Parameters that belong to different - * Lora adapters that will be active at the same time must not overlap. - * This setting does not affect RunWithBinding. - * - * \param[in] options OrtRunOptions instance - * \param[in] adapter OrtLoraAdapter instance - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.20. - */ - ORT_API2_STATUS(RunOptionsAddActiveLoraAdapter, _Inout_ OrtRunOptions* options, _In_ const OrtLoraAdapter* adapter); - - /// @} - /// \name OrtEpDynamicOptions - /// @{ - - /** \brief Set DynamicOptions for EPs (Execution Providers) - * - * Valid options can be found in `include\onnxruntime\core\session\onnxruntime_session_options_config_keys.h` - * Look for `kOrtEpDynamicOptions` - * - * \param[in] sess OrtSession - * \param[in] keys Array of null terminated UTF8 encoded strings of EP dynamic option keys - * \param[in] values Array of null terminated UTF8 encoded string of EP dynamic option values - * \param[in] kv_len Number of elements in the keys and values arrays - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.20. - */ - ORT_API2_STATUS(SetEpDynamicOptions, _Inout_ OrtSession* sess, _In_reads_(kv_len) const char* const* keys, - _In_reads_(kv_len) const char* const* values, _In_ size_t kv_len); - - /** \brief Release an OrtValueInfo instance if it was not added to an OrtGraph. - * \since Version 1.22. - */ - ORT_CLASS_RELEASE(ValueInfo); - - /** \brief Release an OrtNode if it was not added to an OrtGraph. - * \since Version 1.22. - */ - ORT_CLASS_RELEASE(Node); - - /** \brief Release an OrtGraph. - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.22. - */ - ORT_CLASS_RELEASE(Graph); - - /** \brief Release an OrtModel. - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.22. - */ - ORT_CLASS_RELEASE(Model); - - /** \brief Get the value name from an OrtValueInfo instance. - * \param[in] value_info The OrtValueInfo instance. - * \param[out] name The name of the OrtValueInfo - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.22. - */ - ORT_API2_STATUS(GetValueInfoName, _In_ const OrtValueInfo* value_info, _Out_ const char** name); - - /** \brief Get the type information from an OrtValueInfo instance. - * \param[in] value_info The OrtValueInfo instance. - * \param[out] type_info The type info of the OrtValueInfo - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.22. - */ - ORT_API2_STATUS(GetValueInfoTypeInfo, _In_ const OrtValueInfo* value_info, _Outptr_ const OrtTypeInfo** type_info); - - /** \brief Get the Model Editor API instance - * - * Get the Model Editor API instance to create a new model or augment an existing model. - * - * \return Model Editor API struct - * - * \since Version 1.22. - */ - const OrtModelEditorApi*(ORT_API_CALL* GetModelEditorApi)(); - - /** \brief Create an OrtValue for a Tensor that uses pre-existing memory. - * - * ORT will take ownership of the memory and free it using the provided deleter when no longer in use. - * - * \param[in] deleter OrtAllocator instance that will be used to free the memory. - * Only the OrtAllocator:Info and OrtAllocator::Release functions are required. - * The OrtMemoryInfo returned by OrtAllocator::Info must match the location of p_data. - * \param[in] p_data Pointer to the memory that will be used by the Tensor. ORT will take ownership of the memory. - * \param[in] p_data_len Length of the memory in bytes. - * \param[in] shape Dimensions of the Tensor. All values should be > 0. - * \param[in] shape_len Number of dimensions in the shape array. - * \param[in] type Data type of the Tensor. - * \param[out] out Newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateTensorWithDataAndDeleterAsOrtValue, _In_ OrtAllocator* deleter, - _In_ void* p_data, size_t p_data_len, - _In_ const int64_t* shape, size_t shape_len, - ONNXTensorElementDataType type, - _Outptr_ OrtValue** out); - - /** \brief sets load cancellation flag to abort session loading process. - * - * \param[in] options instance that was passed to the session at creation time. - * \param[in] cancel setting this to true after model loading process was initiated will - * attempt to cancel the loading process. If cancellation is successful, CreateSession() - * CreateSessionFromArray() or any other session creation API that take session options as an - * argument will return an OrtStatus indicating that session loading was canceled at user request, - * error code ORT_MODEL_LOAD_CANCELED. - * The APIs above would not return any valid Session instance. This is the best case effort and the result - * is not guaranteed. The session may have already been created and initialized - * before the cancellation request was issued. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(SessionOptionsSetLoadCancellationFlag, _Inout_ OrtSessionOptions* options, - _In_ bool cancel); - - /** \brief Get the Compile API instance. - * - * Get the Compile API instance to compile ONNX models. Execution providers that support compilation fuse a subgraph - * into an EPContext node that wraps a provider-specific binary representation of the subgraph. - * For more details about the EPContext design, refer to: - * \htmlonly - * EPContext design document. - * \endhtmlonly - * - * \return Compile API struct instance. - * - * \since Version 1.22. - */ - const OrtCompileApi*(ORT_API_CALL* GetCompileApi)(); - - // - // OrtKeyValuePairs - // - - /** \brief Create an OrtKeyValuePairs instance. - * - * \param[out] out A pointer to a newly created OrtKeyValuePairs instance. - * - * \note Must be released by calling ReleaseKeyValuePairs. - * - * \since Version 1.22. - */ - void(ORT_API_CALL* CreateKeyValuePairs)(_Outptr_ OrtKeyValuePairs** out); - - /** \brief Add a key-value pair to the OrtKeyValuePairs instance. - * - * \param[in] kvps OrtKeyValuePairs instance. - * \param[in] key Key to be added. - * \param[in] value Value to be added. - * - * \note The `key` and `value` are copied internally. - * - * \since Version 1.22. - */ - - void(ORT_API_CALL* AddKeyValuePair)(_In_ OrtKeyValuePairs* kvps, _In_ const char* key, _In_ const char* value); - - /** \brief Get the value associated with a key in the OrtKeyValuePairs instance. - * - * \param[in] kvps OrtKeyValuePairs instance. - * \param[in] key Key to be searched. - * - * \return The value associated with the key, or nullptr if the key does not exist. - * - * \since Version 1.22. - */ - const char*(ORT_API_CALL* GetKeyValue)(_In_ const OrtKeyValuePairs* kvps, _In_ const char* key); - - /** \brief Get all the key-value pairs from the OrtKeyValuePairs instance. - * - * \param[in] kvps OrtKeyValuePairs instance. - * \param[out] keys Array of keys from `kvps`. - * \param[out] values Array of values from `kvps`. - * \param[out] num_entries Number of entries in `keys` and `values`. - * - * \since Version 1.22. - */ - void(ORT_API_CALL* GetKeyValuePairs)(_In_ const OrtKeyValuePairs* kvps, - _Outptr_ const char* const** keys, _Outptr_ const char* const** values, - _Out_ size_t* num_entries); - - /** \brief Remove a key-value pair from the OrtKeyValuePairs instance. - * - * \param[in] kvps OrtKeyValuePairs instance. - * \param[in] key Key to be removed. No error if not found. - * - * \since Version 1.22. - */ - void(ORT_API_CALL* RemoveKeyValuePair)(_In_ OrtKeyValuePairs* kvps, _In_ const char* key); - - /** \brief Release an OrtKeyValuePairs instance. - * - * \param[in] input OrtKeyValuePairs instance to be released. - * - * \since Version 1.22. - */ - ORT_CLASS_RELEASE(KeyValuePairs); - - /** \brief Register an execution provider library with ORT. - * - * The library must export 'CreateEpFactories' and 'ReleaseEpFactory' functions. - * See OrtEpApi for more details. - * - * \param[in] env The OrtEnv instance to register the library in. - * \param[in] registration_name The name to register the execution provider library under. - * \param[in] path The path to the execution provider library. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(RegisterExecutionProviderLibrary, _In_ OrtEnv* env, _In_ const char* registration_name, - _In_ const ORTCHAR_T* path); - - /** \brief Unregister an execution provider library with ORT. - * - * ORT will call ReleaseEpFactory for all factories created by the library, and unload the library. - * - * You MUST ensure there are no Session instances using execution providers created by the library - * before calling this function. - * - * \param[in] env The OrtEnv instance to unregister the library from. - * \param[in] registration_name The name the execution provider library was registered under. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(UnregisterExecutionProviderLibrary, _In_ OrtEnv* env, _In_ const char* registration_name); - - /** \brief Get the list of available OrtEpDevice instances. - * - * Each OrtEpDevice instance contains details of the execution provider and the device it will use. - * - * \param[in] env The OrtEnv instance to query. - * \param[out] ep_devices The OrtEpDevice instances that the execution provider will use. - * \param[out] num_ep_devices The number of OrtEpDevice instances returned. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(GetEpDevices, _In_ const OrtEnv* env, - _Outptr_ const OrtEpDevice* const** ep_devices, _Out_ size_t* num_ep_devices); - - /** \brief Append the execution provider that is responsible for the selected OrtEpDevice instances - * to the session options. - * - * \param[in] session_options Session options to add execution provider to. - * \param[in] env Environment that execution providers were registered with. - * \param[in] ep_devices One or more OrtEpDevice instances to create an execution provider for. - * Obtain from GetEpDevices. All OrtEpDevice instances must be from the same execution - * provider. It is only necessary to provide multiple OrtEpDevices if you want to use the - * same execution provider for multiple devices. - * e.g. the EP is capable of running on GPU and NPU. - * \param[in] num_ep_devices Number of OrtEpDevice instances. - * \param[in] ep_option_keys Optional keys to configure the execution provider. - * \param[in] ep_option_vals Optional values to configure the execution provider. - * \param[in] num_ep_options Number of execution provide options to add. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_V2, _In_ OrtSessionOptions* session_options, - _In_ OrtEnv* env, - _In_reads_(num_ep_devices) const OrtEpDevice* const* ep_devices, _In_ size_t num_ep_devices, - _In_reads_(num_op_options) const char* const* ep_option_keys, - _In_reads_(num_op_options) const char* const* ep_option_vals, - size_t num_ep_options); - - /** \brief Set the execution provider selection policy for the session. - * - * Allows users to specify a device selection policy for automatic execution provider (EP) selection. - * If custom selection is required please use SessionOptionsSetEpSelectionPolicyDelegate instead. - * - * \param[in] session_options The OrtSessionOptions instance. - * \param[in] policy The device selection policy to use (see OrtExecutionProviderDevicePolicy). - * - * \since Version 1.22 - */ - ORT_API2_STATUS(SessionOptionsSetEpSelectionPolicy, _In_ OrtSessionOptions* session_options, - _In_ OrtExecutionProviderDevicePolicy policy); - - /** \brief Set the execution provider selection policy delegate for the session. - * - * Allows users to provide a custom device selection policy for automatic execution provider (EP) selection. - * - * \param[in] session_options The OrtSessionOptions instance. - * \param[in] delegate Delegate callback for custom selection. - * \param[in] delegate_state Optional state that will be passed to the delegate callback. nullptr if not required. - * - * \since Version 1.22 - */ - ORT_API2_STATUS(SessionOptionsSetEpSelectionPolicyDelegate, _In_ OrtSessionOptions* session_options, - _In_ EpSelectionDelegate delegate, - _In_opt_ void* delegate_state); - - /** \brief Get the hardware device type. - * - * \param[in] device The OrtHardwareDevice instance to query. - * \return The hardware device type. - * - * \since Version 1.22. - */ - OrtHardwareDeviceType(ORT_API_CALL* HardwareDevice_Type)(_In_ const OrtHardwareDevice* device); - - /** \brief Get the hardware device's vendor identifier. - * - * \param[in] device The OrtHardwareDevice instance to query. - * \return The hardware device vendor identifier. - * - * \since Version 1.22. - */ - uint32_t(ORT_API_CALL* HardwareDevice_VendorId)(_In_ const OrtHardwareDevice* device); - - /** \brief Get the hardware device's vendor name. - * - * \param[in] device The OrtHardwareDevice instance to query. - * \return The hardware device's vendor name. - * - * \since Version 1.22. - */ - const char*(ORT_API_CALL* HardwareDevice_Vendor)(_In_ const OrtHardwareDevice* device); - - /** \brief Get the hardware device's unique identifier. - * - * \param[in] device The OrtHardwareDevice instance to query. - * \return The device id. - * - * \note This is not a unique identifier. It identifies the hardware type when combined with vendor id. - * \since Version 1.22. - */ - uint32_t(ORT_API_CALL* HardwareDevice_DeviceId)(_In_ const OrtHardwareDevice* device); - - /** \brief Get hardware device metadata. - * - * \param[in] device The OrtHardwareDevice instance to query. - * \return An OrtKeyValuePairs instance containing the metadata for the device. - * Note: ORT owns the instance so the user must not call ReleaseKeyValuePairs with it. - * - * \since Version 1.22. - */ - const OrtKeyValuePairs*(ORT_API_CALL* HardwareDevice_Metadata)(_In_ const OrtHardwareDevice* device); - - /** \brief Get the execution provider name. - * - * \param[in] ep_device The OrtEpDevice instance to query. - * \return The execution provider name. - * - * \since Version 1.22. - */ - const char*(ORT_API_CALL* EpDevice_EpName)(_In_ const OrtEpDevice* ep_device); - - /** \brief Get the execution provider's vendor name. - * - * \param[in] ep_device The OrtEpDevice instance to query. - * \return The execution provider's vendor name. - * - * \since Version 1.22. - */ - const char*(ORT_API_CALL* EpDevice_EpVendor)(_In_ const OrtEpDevice* ep_device); - - /** \brief Get the metadata for the OrtEpDevice. - * - * \param[in] ep_device The OrtEpDevice instance to query. - * \return An OrtKeyValuePairs instance containing the metadata for the device. - * - * \since Version 1.22. - */ - const OrtKeyValuePairs*(ORT_API_CALL* EpDevice_EpMetadata)(_In_ const OrtEpDevice* ep_device); - - /** \brief Get the execution provider options for the OrtEpDevice. - * - * \param[in] ep_device The OrtEpDevice instance to query. - * \return An OrtKeyValuePairs instance containing the execution provider options for the device. - * - * \since Version 1.22. - */ - const OrtKeyValuePairs*(ORT_API_CALL* EpDevice_EpOptions)(_In_ const OrtEpDevice* ep_device); - - /** \brief Get the OrtHardwareDevice instance for the OrtEpDevice. - * - * \param[in] ep_device The OrtEpDevice instance to query. - * \return The OrtHardwareDevice instance for the device. - * - * \since Version 1.22. - */ - const OrtHardwareDevice*(ORT_API_CALL* EpDevice_Device)(_In_ const OrtEpDevice* ep_device); - - /** \brief Get the OrtEpApi instance for implementing an execution provider. - * - * \since Version 1.22. - */ - const OrtEpApi*(ORT_API_CALL* GetEpApi)(); -}; - -/* - * Steps to use a custom op: - * 1 Create an OrtCustomOpDomain with the domain name used by the custom ops - * 2 Create an OrtCustomOp structure for each op and add them to the domain - * 3 Call OrtAddCustomOpDomain to add the custom domain of ops to the session options - */ - -// Specifies some characteristics of inputs/outputs of custom ops: -// Specify if the inputs/outputs are one of: -// 1) Non-optional (input/output must be present in the node) -// 2) Optional (input/output may be absent in the node) -// 3) Variadic: A variadic input or output specifies N (i.e., the minimum arity) or more operands. -// Only the last input or output of a custom op may be marked as variadic. -// The homogeneity of the variadic input or output determines whether all operands must be of the same -// tensor element type. -typedef enum OrtCustomOpInputOutputCharacteristic { - INPUT_OUTPUT_REQUIRED = 0, - INPUT_OUTPUT_OPTIONAL, - INPUT_OUTPUT_VARIADIC, -} OrtCustomOpInputOutputCharacteristic; - -/* - * The OrtCustomOp structure defines a custom op's schema and its kernel callbacks. The callbacks are filled in by - * the implementor of the custom op. - */ -struct OrtCustomOp { - uint32_t version; // Must be initialized to ORT_API_VERSION - - // This callback creates the kernel, which is a user defined - // parameter that is passed to the Kernel* callbacks below. It is - // recommended to use CreateKernelV2 which allows for a safe error - // propagation by returning an OrtStatusPtr. - void*(ORT_API_CALL* CreateKernel)(_In_ const struct OrtCustomOp* op, _In_ const OrtApi* api, - _In_ const OrtKernelInfo* info); - - // Returns the name of the op - const char*(ORT_API_CALL* GetName)(_In_ const struct OrtCustomOp* op); - - // Returns the type of the execution provider, return nullptr to use CPU execution provider - const char*(ORT_API_CALL* GetExecutionProviderType)(_In_ const struct OrtCustomOp* op); - - // Returns the count and types of the input & output tensors - ONNXTensorElementDataType(ORT_API_CALL* GetInputType)(_In_ const struct OrtCustomOp* op, _In_ size_t index); - size_t(ORT_API_CALL* GetInputTypeCount)(_In_ const struct OrtCustomOp* op); - ONNXTensorElementDataType(ORT_API_CALL* GetOutputType)(_In_ const struct OrtCustomOp* op, _In_ size_t index); - size_t(ORT_API_CALL* GetOutputTypeCount)(_In_ const struct OrtCustomOp* op); - - // Perform a computation step. It is recommended to use - // KernelComputeV2 which allows for a safe error propagation by - // returning an OrtStatusPtr. - void(ORT_API_CALL* KernelCompute)(_In_ void* op_kernel, _In_ OrtKernelContext* context); - void(ORT_API_CALL* KernelDestroy)(_In_ void* op_kernel); - - // Returns the characteristics of the input & output tensors - OrtCustomOpInputOutputCharacteristic(ORT_API_CALL* GetInputCharacteristic)(_In_ const struct OrtCustomOp* op, _In_ size_t index); - OrtCustomOpInputOutputCharacteristic(ORT_API_CALL* GetOutputCharacteristic)(_In_ const struct OrtCustomOp* op, _In_ size_t index); - - // Returns the memory type of the input tensors. This API allows the custom op - // to place the inputs on specific devices. By default, it returns - // OrtMemTypeDefault, which means the input is placed on the default device for - // the execution provider. If the inputs need to be with different memory tyeps, - // this function can be overridden to return the specific memory types. - OrtMemType(ORT_API_CALL* GetInputMemoryType)(_In_ const struct OrtCustomOp* op, _In_ size_t index); - - // Returns the minimum number of input arguments expected for the variadic input. - // Applicable only for custom ops that have a variadic input. - int(ORT_API_CALL* GetVariadicInputMinArity)(_In_ const struct OrtCustomOp* op); - - // Returns true (non-zero) if all arguments of a variadic input have to be of the same type (homogeneous), - // and false (zero) otherwise. - // Applicable only for custom ops that have a variadic input. - int(ORT_API_CALL* GetVariadicInputHomogeneity)(_In_ const struct OrtCustomOp* op); - - // Returns the minimum number of output values expected for the variadic output. - // Applicable only for custom ops that have a variadic output. - int(ORT_API_CALL* GetVariadicOutputMinArity)(_In_ const struct OrtCustomOp* op); - - // Returns true (non-zero) if all outputs values of a variadic output have to be of the same type (homogeneous), - // and false (zero) otherwise. - // Applicable only for custom ops that have a variadic output. - int(ORT_API_CALL* GetVariadicOutputHomogeneity)(_In_ const struct OrtCustomOp* op); - - // Create the kernel state which is passed to each compute call. - OrtStatusPtr(ORT_API_CALL* CreateKernelV2)(_In_ const struct OrtCustomOp* op, _In_ const OrtApi* api, - _In_ const OrtKernelInfo* info, - _Out_ void** kernel); - - // Perform the computation step. - OrtStatusPtr(ORT_API_CALL* KernelComputeV2)(_In_ void* op_kernel, _In_ OrtKernelContext* context); - - OrtStatusPtr(ORT_API_CALL* InferOutputShapeFn)(_In_ const struct OrtCustomOp* op, _In_ OrtShapeInferContext*); - - // Get start range - int(ORT_API_CALL* GetStartVersion)(_In_ const struct OrtCustomOp* op); - int(ORT_API_CALL* GetEndVersion)(_In_ const struct OrtCustomOp* op); - - // Get the inplace_map that defines which output can reuse which input - // Callers will provide 2 raw int* and pass in their address, this function will fill these 2 arrays - // when return, output (*output_index)[i] may reuse the input (*input_index[i]). - // The return value is the size of these 2 arrays. - // Callers are responsible to delete these 2 arrays after use by calling OrtCustomOp::ReleaseMayInplace(). - size_t(ORT_API_CALL* GetMayInplace)(_Out_ int** input_index, _Out_ int** output_index); - - // Release the pointer input_index and output_index allocated from GetMayInplace() function. - // If GetMayInplace() is defined, this function MUST be defined as well. - void(ORT_API_CALL* ReleaseMayInplace)(_Frees_ptr_opt_ int* input_index, _Frees_ptr_opt_ int* output_index); - - // Same as GetMayInplace() and ReleaseMayInplace() - size_t(ORT_API_CALL* GetAliasMap)(_Out_ int** input_index, _Out_ int** output_index); - void(ORT_API_CALL* ReleaseAliasMap)(_Frees_ptr_opt_ int* input_index, _Frees_ptr_opt_ int* output_index); -}; - -/** - * ORT Model Editor API - */ - -/** - * \brief The OrtModelEditorApi struct provides functions to create or edit an ONNX model. - * - * See onnxruntime/test/shared_lib/test_model_editor_api.cc for example usage. - * - * \since Version 1.22. - */ -struct OrtModelEditorApi { - // Model building/editing requires a full build. We return nullptr from GetModelEditorApi if this is a minimal - // build, so it doesn't matter if there are no function pointers in this struct as a user will never get an - // OrtModelEditorApi instance. We do however need a dummy field to avoid empty struct warning. -#if defined(ORT_MINIMAL_BUILD) - const bool not_defined_in_this_build; -#else - /** \brief Create an OrtTypeInfo instance for a Tensor. - * - * Create an OrtTypeInfo instance for a Tensor to use as graph inputs/outputs with the Model Editor API. - * - * User can release `tensor_info` after creating the OrtTypeInfo. - * - * \param[in] tensor_info Tensor type and shape information. - * \param[out] type_info TypeInfo instance for the tensor. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateTensorTypeInfo, _In_ const OrtTensorTypeAndShapeInfo* tensor_info, - _Outptr_ OrtTypeInfo** type_info); - - /** \brief Create an OrtTypeInfo instance for a SparseTensor. - * - * Create an OrtTypeInfo instance for a SparseTensor to use as graph inputs/outputs with the Model Editor API. - * - * User can release `tensor_info` after creating the OrtTypeInfo. - * - * \param[in] tensor_info SparseTensor type and shape information. - * \param[out] type_info TypeInfo instance for the tensor. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateSparseTensorTypeInfo, _In_ const OrtTensorTypeAndShapeInfo* tensor_info, - _Outptr_ OrtTypeInfo** type_info); - - /** \brief Create an OrtTypeInfo instance for a Map. - * - * Create an OrtTypeInfo instance for a Map to use as graph inputs/outputs with the Model Editor API. - * - * User can release `map_value_type` after creating the OrtTypeInfo. - * - * \param[in] map_key_type Key type for the map. - * \param[in] map_value_type Value type for the map. - * \param[out] type_info TypeInfo instance for the map. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateMapTypeInfo, ONNXTensorElementDataType map_key_type, _In_ const OrtTypeInfo* map_value_type, - _Outptr_ OrtTypeInfo** type_info); - - /** \brief Create an OrtTypeInfo instance for a Sequence. - * - * Create an OrtTypeInfo instance for a Sequence to use as graph inputs/outputs with the Model Editor API. - * - * User can release `sequence_type` after creating the OrtTypeInfo. - * - * \param[in] sequence_type Sequence type and shape information. - * \param[out] type_info TypeInfo instance for the sequence. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateSequenceTypeInfo, _In_ const OrtTypeInfo* sequence_type, _Outptr_ OrtTypeInfo** type_info); - - /** \brief Create an OrtTypeInfo instance for an Optional. - * - * Create an OrtTypeInfo instance for an Optional to use as graph inputs/outputs with the Model Editor API. - * - * User can release `contained_type` after creating the OrtTypeInfo. - * - * \param[in] contained_type Tensor type and shape information. - * \param[out] type_info TypeInfo instance for the tensor. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateOptionalTypeInfo, _In_ const OrtTypeInfo* contained_type, _Outptr_ OrtTypeInfo** type_info); - - /** \brief Create an OrtValueInfo for use as an OrtGraph input or output. - * - * \param[in] name The name of the input or output. - * \param[in] type_info The type information for the input or output. The provided value is copied. - * \param[out] value_info The OrtValueInfo instance. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateValueInfo, _In_ const char* name, _In_ const OrtTypeInfo* type_info, - _Outptr_ OrtValueInfo** value_info); - - /** \brief Create an OrtNode to add to an OrtGraph. - * - * Create an OrtNode. - * - * Create attributes with CreateOpAttr. OrtOpAttr instances are copied. - * - * \param[in] operator_name The name of the operator. - * \param[in] domain_name The domain of the operator. Use an empty string for ONNX operators. - * \param[in] node_name The name of the node. - * \param[in] input_names The names of the inputs. - * \param[in] input_names_len The number of input names. - * \param[in] output_names The names of the outputs. - * \param[in] output_names_len The number of output names. - * \param[in] attributes The optional attributes of the node. - * \param[in] attribs_len The number of attributes. May be zero. - * \param[out] node The OrtNode instance. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateNode, _In_ const char* operator_name, _In_ const char* domain_name, _In_ const char* node_name, - _In_reads_(input_names_len) const char* const* input_names, size_t input_names_len, - _In_reads_(output_names_len) const char* const* output_names, size_t output_names_len, - _In_reads_(attribs_len) _In_opt_ OrtOpAttr** attributes, _In_ size_t attribs_len, - _Outptr_ OrtNode** node); - - /** \brief Create an OrtGraph - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateGraph, _Outptr_ OrtGraph** graph); - - /** \brief Set the inputs for the OrtGraph. - * - * Set the graph inputs. This will replace any existing inputs with the new values. - * The OrtGraph takes ownership of the OrtValueInfo instances and you should NOT call ReleaseOrtValueInfo. - * - * \param[in] graph The OrtGraph instance to update. - * \param[in] inputs The input OrtValueInfo instances. - * \param[in] inputs_len The number of input OrtValueInfo instances. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(SetGraphInputs, _Inout_ OrtGraph* graph, - _In_reads_(inputs_len) _In_ OrtValueInfo** inputs, _In_ size_t inputs_len); - - /** \brief Set the outputs for the OrtGraph. - * - * Set the graph outputs. This will replace any existing outputs with the new values. - * The OrtGraph takes ownership of the OrtValueInfo instances provided and you should NOT call ReleaseOrtValueInfo. - * - * \param[in] graph The OrtGraph instance to update. - * \param[in] outputs The output OrtValueInfo instances. - * \param[in] outputs_len The number of output OrtValueInfo instances. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(SetGraphOutputs, _Inout_ OrtGraph* graph, - _In_reads_(outputs_len) _In_ OrtValueInfo** outputs, _In_ size_t outputs_len); - - /** \brief Add an initializer to the OrtGraph - * - * ORT will take ownership of the OrtValue and you should NOT call ReleaseOrtValue. - * - * Two options: - * - * Allocated memory: - * Use CreateTensorAsOrtValue (allocates memory) and populate the tensor with the data. - * Set `data_is_external` to false. - * - * Pre-existing memory: - * Use CreateTensorWithDataAsOrtValue or CreateTensorWithDataAndDeleterAsOrtValue to create an OrtValue - * with a tensor that contains a pointer to the existing data. - * Set `data_is_external` to true. - * - * The pointer must remain valid for the duration of the inference session. - * If using CreateTensorWithDataAsOrtValue you are responsible for freeing the memory after the inference session - * is released. - * If using CreateTensorWithDataAndDeleterAsOrtValue, ORT will free the memory using the provided deleter as - * soon as the OrtValue is no longer in use. - * - * NOTE: A tensor containing pre-existing memory MUST have 128 bytes of data or more. - * For smaller tensors use CreateTensorAsOrtValue. - * - * ONNX shape inferencing does not support external data. An initializer involved in shape inferencing is - * typically small (a single value or limited by the rank of a tensor) and uses less than 128 bytes of - * memory, so this limit acts as a simple catch-all rule to avoid issues. - * e.g. Reshape's `shape`, Clip's `min` and `max`, various ops `axes`. - * - * \param[in] graph The OrtGraph instance to update. - * \param[in] name The value name for the initializer. - * \param[in] tensor The OrtValue instance containing the tensor data. - * \param[in] data_is_external Set to true if the data is external and should not be copied. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(AddInitializerToGraph, _Inout_ OrtGraph* graph, _In_ const char* name, _In_ OrtValue* tensor, - bool data_is_external); - - /** \brief Add an OrtNode to an OrtGraph - * - * Add the node to the graph. The OrtGraph will take ownership of OrtNode and you should NOT call ReleaseOrtNode. - * - * \param[in] graph The OrtGraph instance to update. - * \param[in] node The OrtNode instance to add to the graph. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(AddNodeToGraph, _Inout_ OrtGraph* graph, _In_ OrtNode* node); - - /** \brief Create an OrtModel. - * - * Create an OrtModel. - * - * This can be used to build a new model, or to augment an existing model. - * - * \param[in] domain_names The domain names for the model. - * If augmenting an existing model add additional domains if needed. - * \param[in] opset_versions The opset versions for the model. - * If augmenting an existing model add additional opset versions if needed. - * \param[in] opset_entries_len The number of domain_names and opset_versions entries. - * Domain and opset entries should be 1:1 - * \param[out] model The OrtModel instance. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateModel, - _In_reads_(opset_entries_len) const char* const* domain_names, - _In_reads_(opset_entries_len) const int* opset_versions, - size_t opset_entries_len, - _Outptr_ OrtModel** model); - - /** \brief Add an OrtGraph to an OrtModel. - * - * Add the graph to a model. This should be called once when creating a new model. - * - * The OrtModel takes ownership of the OrtGraph and you should NOT call ReleaseOrtGraph. - * - * \param[in] model The OrtModel instance to update. - * \param[in] graph The OrtGraph instance to add to the model. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(AddGraphToModel, _Inout_ OrtModel* model, _In_ OrtGraph* graph); - - /** \brief Create an OrtSession using the OrtModel. - * - * Create an inference session using the OrtModel instance. - * The OrtModel should have been populated with an OrtGraph containing nodes and initializers, and SetGraphInputs - * and SetGraphOutputs must have been called. - * This will validate the model, run optimizers, and prepare the session for inferencing. - * - * ReleaseOrtModel must be called to free the OrtModel after session creation. - * - * \param[in] env The OrtEnv instance. - * \param[in] model The OrtModel instance. - * \param[in] options The OrtSessionOptions instance. - * \param[out] out The OrtSession instance. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateSessionFromModel, _In_ const OrtEnv* env, _In_ const OrtModel* model, - _In_ const OrtSessionOptions* options, _Outptr_ OrtSession** out); - - /** \brief Create an OrtSession to augment an existing model. - * - * Create an OrtSession with an existing model that will be augmented with additional nodes and initializers. - * Nodes can be added before or after the existing nodes in the model. ONNX Runtime will connect the nodes when the - * model is finalized. - * - * To add nodes and initializers to the existing model, first create an OrtModel using CreateModel. - * Add nodes and initializers to the OrtModel using AddNodeToGraph and AddInitializerToGraph. - * Graph inputs/outputs should be updated with SetGraphInputs and SetGraphOutputs as needed to reflect changes made - * by the new nodes. The list of graph inputs/outputs should be for the overall model and not just the new nodes. - * - * Add the new information from the OrtModel to the original model using ApplyModelToSession, and prepare the - * session for inferencing by calling FinalizeModelEditorSession. - * - * \param{in} env The OrtEnv instance. - * \param{in} model_path The path to the existing ONNX model to augment. - * \param{in} options The OrtSessionOptions instance. - * \param{out} out The created OrtSession instance. - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateModelEditorSession, _In_ const OrtEnv* env, _In_ const ORTCHAR_T* model_path, - _In_ const OrtSessionOptions* options, - _Outptr_ OrtSession** out); - - /** \brief Create an OrtSession to augment an existing model. - * - * Create an OrtSession with an existing model that will be augmented with additional nodes and initializers. - * Nodes can be added before or after the existing nodes in the model. ONNX Runtime will connect the nodes when the - * model is finalized. - * - * To add nodes and initializers to the existing model, first create an OrtModel using CreateModel. - * Add nodes and initializers to the OrtModel using AddNodeToGraph and AddInitializerToGraph. - * Graph inputs/outputs should be updated with SetGraphInputs and SetGraphOutputs as needed to reflect changes made - * by the new nodes. The list of graph inputs/outputs should be for the overall model and not just the new nodes. - * - * Add the new information from the OrtModel to the original model using ApplyModelToSession, and prepare the - * session for inferencing by calling FinalizeModelEditorSession. - * - * \param{in} env The OrtEnv instance. - * \param{in} model_data The model data for the existing model to augment. - * \param{in} model_data_length The length of the model data. - * \param{in} options The OrtSessionOptions instance. - * \param{out} out The created OrtSession instance. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateModelEditorSessionFromArray, _In_ const OrtEnv* env, - _In_ const void* model_data, size_t model_data_length, - _In_ const OrtSessionOptions* options, - _Outptr_ OrtSession** out); - - /** \brief Query the session for the opset version of a domain. - * - * When using the Model Editor API to augment a model, any new nodes must conform to the opset version of the - * original model. To do that the user must be able to discover that opset version. - * Returns an error if the domain is not used in the model. - * - * \param[in] session OrtSession to query - * \param[in] domain Domain to query. The ONNX domain is an empty string. - * \param[out] opset The opset version of the domain. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(SessionGetOpsetForDomain, _In_ const OrtSession* session, _In_ const char* domain, _Out_ int* opset); - - /** \brief Apply changes to augment the ONNX model in a session created using CreateModelEditorSession[FromArray] - * - * Adds new nodes and updates graph inputs/outputs using `model` to augment the original ONNX model in the session. - * All changes will be validated. - * Call FinalizeModelEditorSession to prepare the session for inferencing. - * - * Existing input/outputs will only be updated if the OrtGraph inputs/outputs are set in the OrtModel. - * i.e. you don't need to call SetGraphInputs/SetGraphOutputs if they are unchanged. - * - * ReleaseOrtModel must be called to free the OrtModel after it is applied to the session. - * - * \param[in] session OrtSession to update. Session must have been created using CreateModelEditorSession[FromArray]. - * \param[in] model OrtModel containing new nodes, new initializers, and updated graph input and/or output info. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(ApplyModelToModelEditorSession, _Inout_ OrtSession* session, _In_ OrtModel* model); - - /** \brief Finalize the Model Editor session that was created using CreateModelEditorSession[FromArray]. - * - * Finalize the Model Editor session that augmented an ONNX model by adding new nodes. - * This will run optimizers and prepare the session for inferencing. - * - * \param[in] session OrtSession to finalize. Session must have been created using CreateModelEditorSession[FromArray]. - * \param[in] options OrtSessionOptions to use for the session. - * \param[in] prepacked_weights_container Optional OrtPrepackedWeightsContainer to use for the session. - Set to nullptr if not used. - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(FinalizeModelEditorSession, _Inout_ OrtSession* session, _In_ const OrtSessionOptions* options, - _In_opt_ OrtPrepackedWeightsContainer* prepacked_weights_container); -#endif // !defined(ORT_MINIMAL_BUILD) -}; - -/** - * ORT Compile API - */ - -/** - * \brief The OrtCompileApi struct provides functions to compile ONNX models. - * - * Execution providers that support compilation fuse a subgraph into an EPContext node that wraps a provider-specific - * binary representation of the subgraph. - * For more details about the EPContext design, refer to: - * \htmlonly - * EPContext design document. - * \endhtmlonly - * - * Example (error handling not shown): - * OrtStatus* status = NULL; - * OrtCompileApi* compile_api = ort_api->GetCompileApi(); - * OrtModelCompilationOptions* compile_options = NULL; - * - * status = compile_api->CreateModelCompilationOptionsFromSessionOptions(env, session_options, &compile_options); - * status = compile_api->ModelCompilationOptions_SetInputModelPath(compile_options, ORT_TSTR("model.onnx")); - * status = compile_api->ModelCompilationOptions_SetOutputModelPath(compile_options, ORT_TSTR("model.compiled.onnx")); - * status = compile_api->CompileModel(env, compile_options); - * compile_api->ReleaseModelCompilationOptions(compile_options); - * - * \since Version 1.22. - */ -struct OrtCompileApi { - /// @} - /// \name OrtModelCompilationOptions - /// @{ - ORT_CLASS_RELEASE(ModelCompilationOptions); - - /** \brief Creates an OrtModelCompilationOptions object from an existing OrtSessionOptions object. - * - * An OrtModelCompilationOptions object contains the settings used to generate a compiled ONNX model. - * The OrtSessionOptions object has the execution providers with which the model will be compiled. - * - * ReleaseOrtModelCompilationsOptions must be called to free the OrtModelCompilationOptions after calling - * CompileModel. - * - * \param[in] env OrtEnv object. - * \param[in] session_options The OrtSessionOptions instance from which to create the OrtModelCompilationOptions. - * \param[out] out The created OrtModelCompilationOptions instance. - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateModelCompilationOptionsFromSessionOptions, _In_ const OrtEnv* env, - _In_ const OrtSessionOptions* session_options, _Outptr_ OrtModelCompilationOptions** out); - - /** \brief Sets the file path to the input ONNX model to compile. - * - * The input model's location (e.g., file path or memory buffer) must be set with either - * ModelCompilationOptions_SetInputModelPath or ModelCompilationOptions_SetInputModelFromBuffer. - * - * \param[in] model_compile_options The OrtModelCompilationOptions instance. - * \param[in] input_model_path Null terminated string of the path (wchar on Windows, char otherwise). - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(ModelCompilationOptions_SetInputModelPath, _In_ OrtModelCompilationOptions* model_compile_options, - _In_ const ORTCHAR_T* input_model_path); - - /** \brief Sets the buffer that stores the bytes of the loaded ONNX model to compile. - * - * The input model's location (e.g., file path or memory buffer) must be set with either - * ModelCompilationOptions_SetInputModelPath or ModelCompilationOptions_SetInputModelFromBuffer. - * - * \param[in] model_compile_options The OrtModelCompilationOptions instance. - * \param[in] input_model_data Buffer containing the loaded ONNX model bytes. - * \param[in] input_model_data_size The number of bytes in the `input_model_data` buffer. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(ModelCompilationOptions_SetInputModelFromBuffer, - _In_ OrtModelCompilationOptions* model_compile_options, - _In_ const void* input_model_data, - size_t input_model_data_size); - - /** \brief Sets the file path for the output ONNX model generated by CompileModel. - * - * The output model's location (e.g., file path or memory buffer) can be set with either - * ModelCompilationOptions_SetOutputModelPath or ModelCompilationOptions_SetOutputModelBuffer. - * - * If the output model's location is not set, ONNX Runtime will generate an output file with a path based on - * the input model's file path. Examples: - * /Path/my_model.onnx -> /Path/my_model_ctx.onnx - * /Path/my_model -> /Path/my_model_ctx.onnx - * - * \param[in] model_compile_options The OrtModelCompilationOptions instance. - * \param[in] output_model_path Null terminated string of the path (wchar on Windows, char otherwise). - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(ModelCompilationOptions_SetOutputModelPath, _In_ OrtModelCompilationOptions* model_compile_options, - _In_ const ORTCHAR_T* output_model_path); - - /** \brief Optionally sets the file that should store external initializers for the compiled ONNX model. - * If not set, initializers are stored within the model. - * - * Only initializers for nodes that were not compiled are stored in the external initializers file. - * Compiled nodes contain their initializer data within the `ep_cache_context` attribute of EPContext nodes. - * Refer to ModelCompilationOptions_SetEpContextEmbedMode. - * - * \param[in] model_compile_options The OrtModelCompilationOptions instance. - * \param[in] external_initializers_file_path Null terminated string of the path to the file. - * \param[in] external_initializers_size_threshold Initializers larger than this threshold are stored in the file. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(ModelCompilationOptions_SetOutputModelExternalInitializersFile, - _In_ OrtModelCompilationOptions* model_compile_options, - _In_ const ORTCHAR_T* external_initializers_file_path, - size_t external_initializers_size_threshold); - - /** \brief Configures model compilation to store the output compiled ONNX model in a buffer. - * - * The caller passes an OrtAllocator that ONNX Runtime uses to allocate memory for the buffer. - * - * The output model's location (e.g., file path or memory buffer) can be set with either - * ModelCompilationOptions_SetOutputModelPath or ModelCompilationOptions_SetOutputModelBuffer. - * - * If the output model's location is not set, ONNX Runtime will generate an output file with a path based on - * the input model's file path. Examples: - * /Path/my_model.onnx -> /Path/my_model_ctx.onnx - * /Path/my_model -> /Path/my_model_ctx.onnx - * - * \param[in] model_compile_options The OrtModelCompilationOptions instance. - * \param[in] allocator The allocator used to allocate the buffer for the compiled model. - * \param[out] output_model_buffer_ptr Pointer to the buffer that stores the compiled model. - * \param[out] output_model_buffer_size_ptr Pointer set to the size of output model in bytes. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(ModelCompilationOptions_SetOutputModelBuffer, - _In_ OrtModelCompilationOptions* model_compile_options, - _Inout_ OrtAllocator* allocator, - _Outptr_ void** output_model_buffer_ptr, - _Out_ size_t* output_model_buffer_size_ptr); - - /** \brief Enables or disables the embedding of EPContext binary data into the `ep_cache_context` attribute - * of EPContext nodes. Defaults to false. - * - * If enabled, the `ep_cache_context` attribute of EPContext nodes will store the context binary data, which may - * include weights for compiled subgraphs. - * - * If disabled, the `ep_cache_context` attribute of EPContext nodes will contain the path to the file containing the - * context binary data. The path is set by the execution provider creating the EPContext node. - * - * More details relate to EPContext design refers to: - * \htmlonly - * EPContext design document. - * \endhtmlonly - * - * \param[in] model_compile_options The OrtModelCompilationOptions instance. - * \param[in] embed_ep_context_in_model True to embed EPContext binary data into the EPContext node - * `ep_cache_context` attributes. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(ModelCompilationOptions_SetEpContextEmbedMode, _In_ OrtModelCompilationOptions* model_compile_options, - bool embed_ep_context_in_model); - - /** \brief Compiles an input ONNX model with the given compilation options. - * - * \param[in] env OrtEnv object. - * \param[in] model_options The compilation options that defines compilation options for a model. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CompileModel, _In_ const OrtEnv* env, _In_ const OrtModelCompilationOptions* model_options); -}; - -ORT_RUNTIME_CLASS(Ep); -ORT_RUNTIME_CLASS(EpFactory); - -struct OrtEpApi { - /** \brief Create an OrtEpDevice for the EP and an OrtHardwareDevice. - * \param[in] ep_factory Execution provider factory that is creating the instance. - * \param[in] hardware_device Hardware device that the EP can utilize. - * \param[in] ep_metadata Optional OrtKeyValuePairs instance for execution provider metadata that may be used - * during execution provider selection and passed to CreateEp. - * ep_device will copy this instance and the user should call ReleaseKeyValuePairs. - * \param[in] ep_options Optional OrtKeyValuePairs instance for execution provider options that will be added - * to the Session configuration options if the execution provider is selected. - * ep_device will copy this instance and the user should call ReleaseKeyValuePairs. - * \param ep_device OrtExecutionDevice that is created. - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateEpDevice, _In_ OrtEpFactory* ep_factory, - _In_ const OrtHardwareDevice* hardware_device, - _In_opt_ const OrtKeyValuePairs* ep_metadata, - _In_opt_ const OrtKeyValuePairs* ep_options, - _Out_ OrtEpDevice** ep_device); - - ORT_CLASS_RELEASE(EpDevice); -}; - -/** - * \brief The OrtEp struct provides functions to implement for an execution provider. - * \since Version 1.22. - */ -struct OrtEp { - /** \brief The ONNX Runtime version the execution provider was compiled with. - * - * Implementation should set to ORT_API_VERSION. - * ORT will use this to ensure it does not call functions that were not available when the library was compiled. - * - * \since Version 1.22. - */ - uint32_t ort_version_supported; - - /** \brief Get the execution provider name. - * - * \param[in] this_ptr The OrtEp instance. - * \return The execution provider name. - * - * \note Returned string is owned by ORT and valid until UnregisterExecutionProviderLibrary is called. - * - * \since Version 1.22. - */ - const char*(ORT_API_CALL* GetName)(const OrtEp* this_ptr); - - // OrtStatus* GetCapability(OrtEp* ep, const OrtGraph* graph, - // size_t* num_supported_subgraphs, - // OrtIndexedSubgraph** supported_subgraphs, OrtAllocator* allocator); - - // OrtStatus* Compile(OrtEp* ep, const OrtGraph** graphs, OrtNode** fused_graph_nodes, - // size_t count, OrtNodeComputeInfo* node_compute_infos); - - // TODO: Implement OrtEpApi and the complete OrtEp interface as the next step. -}; - -/** \brief The function signature that ORT will call to create OrtEpFactory instances. - * - * This must be available in a function called 'CreateEpFactories' in the execution provider library. - * - * \param[in] registered_name The name the execution library is registered with by RegisterExecutionProviderLibrary - * \param[in] ort_api_base The OrtApiBase instance that is used by the factory to get the OrtApi instance for the - * version of ORT that the library was compiled against. - * \param[in,out] factories The implementation should create and add OrtEpFactory instances to this - * pre-allocated array. - * i.e. usage is `factories[0] = new MyEpFactory();` - * \param[in] max_factories The maximum number of OrtEpFactory instances that can be added to `factories`. - * Current default is to allow 4 factories. This can be increased in the future if needed. - * \param[out] num_factories The number of OrtEpFactory instances created by the factory and added to `factories`. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ -typedef OrtStatus* (*CreateEpApiFactoriesFn)(_In_ const char* registered_name, _In_ const OrtApiBase* ort_api_base, - _Inout_ OrtEpFactory** factories, _In_ size_t max_factories, - _Out_ size_t* num_factories); - -/** \brief The function signature that ORT will call to release an OrtEpFactory instance. - * - * This must be available in a function called 'ReleaseEpFactory' in the execution provider library. - * - * \param[in] factory The OrtEpFactory instance to release. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ -typedef OrtStatus* (*ReleaseEpApiFactoryFn)(_In_ OrtEpFactory* factory); - -/** - * \brief The OrtEpFactory provides functions to create and manage execution providers. - * \since Version 1.22. - */ -struct OrtEpFactory { - /** \brief The ONNX Runtime version the execution provider was compiled with. - * - * Implementation should set to ORT_API_VERSION. - * ORT will use this to ensure it does not call functions that were not available when the library was compiled. - * - * \since Version 1.22. - */ - uint32_t ort_version_supported; - - /** \brief Get the name the of the execution provider that the factory creates. - * - * \param[in] this_ptr The OrtEpFactory instance. - * \return The name of the execution provider the factory creates. - * - * \since Version 1.22. - */ - const char*(ORT_API_CALL* GetName)(const OrtEpFactory* this_ptr); - - /** \brief Get the name of vendor who owns the execution provider that the factory creates. - * - * \param[in] this_ptr The OrtEpFactory instance. - * \return vendor The vendor name of the execution provider the factory creates. - * - * \since Version 1.22. - */ - const char*(ORT_API_CALL* GetVendor)(const OrtEpFactory* this_ptr); // return EP vendor - - /** \brief Get information from the execution provider if it supports the OrtHardwareDevice. - * - * \param[in] this_ptr The OrtEpFactory instance. - * Non-const as the factory is passed through to the CreateEp call via the OrtEpDevice. - * \param[in] devices The OrtHardwareDevice instances that are available. - * \param[in] num_devices The number of OrtHardwareDevice instances. - * \param[out] ep_devices OrtEpDevice instances for each OrtHardwareDevice that the EP can use. - * The implementation should call OrtEpApi::CreateEpDevice to create, and add the OrtEpDevice - * instances to this pre-allocated array. ORT will take ownership of the values returned. - * i.e. usage is `ep_devices[0] = ;` - * \param[in] max_ep_devices The maximum number of OrtEpDevices that can be added to ep_devices. - * Current default is 8. This can be increased if needed. - * \param[out] num_ep_devices The number of EP devices added to ep_devices. - * \return true if the factory can create an execution provider that uses `device`. - * - * \note ORT will take ownership or ep_metadata and/or ep_options if they are not null. - * - * \since Version 1.22. - */ - OrtStatus*(ORT_API_CALL* GetSupportedDevices)(_In_ OrtEpFactory* this_ptr, - _In_reads_(num_devices) const OrtHardwareDevice* const* devices, - _In_ size_t num_devices, - _Inout_ OrtEpDevice** ep_devices, - _In_ size_t max_ep_devices, - _Out_ size_t* num_ep_devices); - - /** \brief Function to create an OrtEp instance for use in a Session. - * - * ORT will call ReleaseEp to release the instance when it is no longer needed. - * - * \param[in] this_ptr The OrtEpFactory instance. - * \param[in] devices The OrtHardwareDevice instances that the execution provider was selected to use. - * \param[in] ep_metadata_pairs Execution provider metadata that was provided to OrtEpApi::CreateEpDevice, for each - * device. - * \param[in] num_devices The number of devices the execution provider was selected for. - * \param[in] session_options The OrtSessionOptions instance that contains the configuration options for the - * session. This will include ep_options from GetSupportedDevices as well as any - * user provided overrides. - * Execution provider options will have been added with a prefix of 'ep..'. - * The OrtSessionOptions instance will NOT be valid after this call and should not be - * stored for later use. - * \param[in] logger The OrtLogger instance for the session that the execution provider should use for logging. - * \param[out] ep The OrtEp instance created by the factory. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version . This is a placeholder. - */ - OrtStatus*(ORT_API_CALL* CreateEp)(_In_ OrtEpFactory* this_ptr, - _In_reads_(num_devices) const OrtHardwareDevice* const* devices, - _In_reads_(num_devices) const OrtKeyValuePairs* const* ep_metadata_pairs, - _In_ size_t num_devices, - _In_ const OrtSessionOptions* session_options, - _In_ const OrtLogger* logger, _Outptr_ OrtEp** ep); - - /** \brief Release the OrtEp instance. - * - * \param[in] this_ptr The OrtEpFactory instance. - * \param[in] ep The OrtEp instance to release. - * - * \since Version . This is a placeholder. - */ - void(ORT_API_CALL* ReleaseEp)(OrtEpFactory* this_ptr, struct OrtEp* ep); -}; - -/* - * This is the old way to add the CUDA provider to the session, please use SessionOptionsAppendExecutionProvider_CUDA above to access the latest functionality - * This function always exists, but will only succeed if Onnxruntime was built with CUDA support and the CUDA provider shared library exists - * - * \param device_id CUDA device id, starts from zero. - */ -ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_CUDA, _In_ OrtSessionOptions* options, int device_id); - -/* - * This is the old way to add the ROCm provider to the session, please use - * SessionOptionsAppendExecutionProvider_ROCM above to access the latest functionality - * This function always exists, but will only succeed if Onnxruntime was built with - * HIP support and the ROCm provider shared library exists - * - * \param device_id HIP device id, starts from zero. - */ -ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_ROCM, _In_ OrtSessionOptions* options, int device_id); - -/* - * This is the old way to add the MIGraphX provider to the session, please use - * SessionOptionsAppendExecutionProvider_MIGraphX above to access the latest functionality - * This function always exists, but will only succeed if Onnxruntime was built with - * HIP support and the MIGraphX provider shared library exists - * - * \param device_id HIP device id, starts from zero. - */ -ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_MIGraphX, _In_ OrtSessionOptions* options, int device_id); - -/* - * This is the old way to add the oneDNN provider to the session, please use - * SessionOptionsAppendExecutionProvider_oneDNN above to access the latest functionality - * This function always exists, but will only succeed if Onnxruntime was built with - * oneDNN support and the oneDNN provider shared library exists - * - * \param use_arena zero: false. non-zero: true. - */ -ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_Dnnl, _In_ OrtSessionOptions* options, int use_arena); - -/* - * This is the old way to add the TensorRT provider to the session, please use SessionOptionsAppendExecutionProvider_TensorRT_V2 above to access the latest functionality - * This function always exists, but will only succeed if Onnxruntime was built with TensorRT support and the TensorRT provider shared library exists - * - * \param device_id CUDA device id, starts from zero. - */ -ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_Tensorrt, _In_ OrtSessionOptions* options, int device_id); - -#ifdef __cplusplus -} -#endif -/// @} +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// See docs\c_cxx\README.md on generating the Doxygen documentation from this file + +/** \mainpage ONNX Runtime + * + * ONNX Runtime is a high-performance inference and training graph execution engine for deep learning models. + * + * ONNX Runtime's C, C++ APIs offer an easy to use interface to onboard and execute onnx models. + * - \subpage c_cpp_api "Core C, C++ APIs" + * - \subpage training_c_cpp_api "Training C, C++ APIs for on-device training" + * + * \page c_cpp_api Core C, C++ APIs + *

C

+ * + * ::OrtApi - Click here to go to the structure with all C API functions. + * + *

C++

+ * + * ::Ort - Click here to go to the namespace holding all of the C++ wrapper classes + * + * It is a set of header only wrapper classes around the C API. The goal is to turn the C style return value error codes into C++ exceptions, and to + * automate memory management through standard C++ RAII principles. + * + * \addtogroup Global + * ONNX Runtime C API + * @{ + */ + +#pragma once +#include +#include +#include +#include + +/** \brief The API version defined in this header + * + * This value is used by some API functions to behave as this version of the header expects. + */ +#define ORT_API_VERSION 22 + +#ifdef __cplusplus +extern "C" { +#endif + +//! @} +// SAL2 Definitions +#ifndef _MSC_VER +#define _In_ +#define _In_z_ +#define _In_opt_ +#define _In_opt_z_ +#define _Out_ +#define _Outptr_ +#define _Out_opt_ +#define _Inout_ +#define _Inout_opt_ +#define _Frees_ptr_opt_ +#define _Ret_maybenull_ +#define _Ret_notnull_ +#define _Check_return_ +#define _Outptr_result_maybenull_ +#define _In_reads_(X) +#define _Inout_updates_(X) +#define _Out_writes_(X) +#define _Inout_updates_all_(X) +#define _Out_writes_bytes_all_(X) +#define _Out_writes_all_(X) +#define _Success_(X) +#define _Outptr_result_buffer_maybenull_(X) +#define ORT_ALL_ARGS_NONNULL __attribute__((nonnull)) +#else +#include +#define ORT_ALL_ARGS_NONNULL +#endif + +#ifdef _WIN32 +// Define ORT_DLL_IMPORT if your program is dynamically linked to Ort. +// dllexport is not used, we use a .def file. +#ifdef ORT_DLL_IMPORT +#define ORT_EXPORT __declspec(dllimport) +#else +#define ORT_EXPORT +#endif +#define ORT_API_CALL _stdcall +#define ORT_MUST_USE_RESULT +#define ORTCHAR_T wchar_t +#else +// To make symbols visible on macOS/iOS +#ifdef __APPLE__ +#define ORT_EXPORT __attribute__((visibility("default"))) +#else +#define ORT_EXPORT +#endif +#define ORT_API_CALL +#define ORT_MUST_USE_RESULT __attribute__((warn_unused_result)) +#define ORTCHAR_T char +#endif + +/// ORTCHAR_T, ORT_TSTR are reserved specifically for path handling. +/// All other strings are UTF-8 encoded, use char and std::string +#ifndef ORT_TSTR +#ifdef _WIN32 +#define ORT_TSTR(X) L##X +// When X is a macro, L##X is not defined. In this case, we need to use ORT_TSTR_ON_MACRO. +#define ORT_TSTR_ON_MACRO(X) L"" X +#else +#define ORT_TSTR(X) X +#define ORT_TSTR_ON_MACRO(X) X +#endif +#endif + +// On Windows, ORT_FILE is a wchar_t version of the __FILE__ macro. +// Otherwise, ORT_FILE is equivalent to __FILE__. +#ifndef ORT_FILE +#define ORT_FILE_INTERNAL(x) ORT_TSTR(x) +#define ORT_FILE ORT_FILE_INTERNAL(__FILE__) +#endif + +// Any pointer marked with _In_ or _Out_, cannot be NULL. + +// Windows users should use unicode paths when possible to bypass the MAX_PATH limitation +// Every pointer marked with _In_ or _Out_, cannot be NULL. Caller should ensure that. +// for ReleaseXXX(...) functions, they can accept NULL pointer. + +#ifdef __cplusplus +// For any compiler with C++11 support, MSVC 2015 and greater, or Clang version supporting noexcept. +// Such complex condition is needed because compilers set __cplusplus value differently. +#ifndef __has_feature +#define __has_feature(x) 0 +#endif +#if ((__cplusplus >= 201103L) || (_MSC_VER >= 1900) || (defined(__has_feature) && __has_feature(cxx_noexcept))) +#define NO_EXCEPTION noexcept +#else +#define NO_EXCEPTION throw() +#endif +#else +#define NO_EXCEPTION +#endif + +// __VA_ARGS__ on Windows and Linux are different +#define ORT_API(RETURN_TYPE, NAME, ...) RETURN_TYPE ORT_API_CALL NAME(__VA_ARGS__) NO_EXCEPTION + +#define ORT_API_STATUS(NAME, ...) \ + _Success_(return == 0) _Check_return_ _Ret_maybenull_ OrtStatusPtr ORT_API_CALL NAME(__VA_ARGS__) \ + NO_EXCEPTION ORT_MUST_USE_RESULT + +// XXX: Unfortunately, SAL annotations are known to not work with function pointers +#define ORT_API2_STATUS(NAME, ...) \ + _Check_return_ _Ret_maybenull_ OrtStatusPtr(ORT_API_CALL* NAME)(__VA_ARGS__) NO_EXCEPTION ORT_MUST_USE_RESULT + +// Used in *.cc files. Almost as same as ORT_API_STATUS, except without ORT_MUST_USE_RESULT and ORT_EXPORT +#define ORT_API_STATUS_IMPL(NAME, ...) \ + _Success_(return == 0) _Check_return_ _Ret_maybenull_ OrtStatusPtr ORT_API_CALL NAME(__VA_ARGS__) NO_EXCEPTION + +#define ORT_CLASS_RELEASE(X) void(ORT_API_CALL * Release##X)(_Frees_ptr_opt_ Ort##X * input) + +#ifdef __DOXYGEN__ +#undef ORT_API_STATUS +#define ORT_API_STATUS(NAME, ...) OrtStatus* NAME(__VA_ARGS__) +#undef ORT_API2_STATUS +#define ORT_API2_STATUS(NAME, ...) OrtStatus* NAME(__VA_ARGS__) +#undef ORT_CLASS_RELEASE +#define ORT_CLASS_RELEASE(X) void Release##X(Ort##X* input) +#undef NO_EXCEPTION +#define NO_EXCEPTION +#endif +/** \addtogroup Global + * ONNX Runtime C API + * @{ + */ + +/** Copied from TensorProto::DataType + * Currently, Ort doesn't support complex64, complex128 + */ +typedef enum ONNXTensorElementDataType { + ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED, + ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, // maps to c type float + ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8, // maps to c type uint8_t + ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8, // maps to c type int8_t + ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16, // maps to c type uint16_t + ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16, // maps to c type int16_t + ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32, // maps to c type int32_t + ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64, // maps to c type int64_t + ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING, // maps to c++ type std::string + ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL, + ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16, + ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE, // maps to c type double + ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32, // maps to c type uint32_t + ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64, // maps to c type uint64_t + ONNX_TENSOR_ELEMENT_DATA_TYPE_COMPLEX64, // complex with float32 real and imaginary components + ONNX_TENSOR_ELEMENT_DATA_TYPE_COMPLEX128, // complex with float64 real and imaginary components + ONNX_TENSOR_ELEMENT_DATA_TYPE_BFLOAT16, // Non-IEEE floating-point format based on IEEE754 single-precision + // float 8 types were introduced in onnx 1.14, see https://onnx.ai/onnx/technical/float8.html + ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FN, // Non-IEEE floating-point format based on IEEE754 single-precision + ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FNUZ, // Non-IEEE floating-point format based on IEEE754 single-precision + ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2, // Non-IEEE floating-point format based on IEEE754 single-precision + ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2FNUZ, // Non-IEEE floating-point format based on IEEE754 single-precision + // Int4 types were introduced in ONNX 1.16. See https://onnx.ai/onnx/technical/int4.html + ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT4, // maps to a pair of packed uint4 values (size == 1 byte) + ONNX_TENSOR_ELEMENT_DATA_TYPE_INT4 // maps to a pair of packed int4 values (size == 1 byte) +} ONNXTensorElementDataType; + +// Synced with onnx TypeProto oneof +typedef enum ONNXType { + ONNX_TYPE_UNKNOWN, + ONNX_TYPE_TENSOR, + ONNX_TYPE_SEQUENCE, + ONNX_TYPE_MAP, + ONNX_TYPE_OPAQUE, + ONNX_TYPE_SPARSETENSOR, + ONNX_TYPE_OPTIONAL +} ONNXType; + +// These types are synced with internal +// SparseFormatFlags +typedef enum OrtSparseFormat { + ORT_SPARSE_UNDEFINED = 0, + ORT_SPARSE_COO = 0x1, + ORT_SPARSE_CSRC = 0x2, + ORT_SPARSE_BLOCK_SPARSE = 0x4 +} OrtSparseFormat; + +// Enum allows to query sparse tensor indices +enum OrtSparseIndicesFormat { + ORT_SPARSE_COO_INDICES, + ORT_SPARSE_CSR_INNER_INDICES, + ORT_SPARSE_CSR_OUTER_INDICES, + ORT_SPARSE_BLOCK_SPARSE_INDICES +}; + +/** \brief Logging severity levels + * + * In typical API usage, specifying a logging severity level specifies the minimum severity of log messages to show. + */ +typedef enum OrtLoggingLevel { + ORT_LOGGING_LEVEL_VERBOSE, ///< Verbose informational messages (least severe). + ORT_LOGGING_LEVEL_INFO, ///< Informational messages. + ORT_LOGGING_LEVEL_WARNING, ///< Warning messages. + ORT_LOGGING_LEVEL_ERROR, ///< Error messages. + ORT_LOGGING_LEVEL_FATAL, ///< Fatal error messages (most severe). +} OrtLoggingLevel; + +typedef enum OrtErrorCode { + ORT_OK, + ORT_FAIL, + ORT_INVALID_ARGUMENT, + ORT_NO_SUCHFILE, + ORT_NO_MODEL, + ORT_ENGINE_ERROR, + ORT_RUNTIME_EXCEPTION, + ORT_INVALID_PROTOBUF, + ORT_MODEL_LOADED, + ORT_NOT_IMPLEMENTED, + ORT_INVALID_GRAPH, + ORT_EP_FAIL, + ORT_MODEL_LOAD_CANCELED, + ORT_MODEL_REQUIRES_COMPILATION, +} OrtErrorCode; + +typedef enum OrtOpAttrType { + ORT_OP_ATTR_UNDEFINED = 0, + ORT_OP_ATTR_INT, + ORT_OP_ATTR_INTS, + ORT_OP_ATTR_FLOAT, + ORT_OP_ATTR_FLOATS, + ORT_OP_ATTR_STRING, + ORT_OP_ATTR_STRINGS, +} OrtOpAttrType; + +//! @} +#define ORT_RUNTIME_CLASS(X) \ + struct Ort##X; \ + typedef struct Ort##X Ort##X + +/** \addtogroup Global + * ONNX Runtime C API + * @{ + */ +// The actual types defined have an Ort prefix +ORT_RUNTIME_CLASS(Env); +ORT_RUNTIME_CLASS(Status); // nullptr for Status* indicates success +ORT_RUNTIME_CLASS(MemoryInfo); +ORT_RUNTIME_CLASS(IoBinding); +ORT_RUNTIME_CLASS(Session); // Don't call ReleaseSession from Dllmain (because session owns a thread pool) +ORT_RUNTIME_CLASS(Value); +ORT_RUNTIME_CLASS(RunOptions); +ORT_RUNTIME_CLASS(TypeInfo); +ORT_RUNTIME_CLASS(TensorTypeAndShapeInfo); +ORT_RUNTIME_CLASS(MapTypeInfo); +ORT_RUNTIME_CLASS(SequenceTypeInfo); +ORT_RUNTIME_CLASS(OptionalTypeInfo); +ORT_RUNTIME_CLASS(SessionOptions); +ORT_RUNTIME_CLASS(CustomOpDomain); +ORT_RUNTIME_CLASS(ModelMetadata); +ORT_RUNTIME_CLASS(ThreadPoolParams); +ORT_RUNTIME_CLASS(ThreadingOptions); +ORT_RUNTIME_CLASS(ArenaCfg); +ORT_RUNTIME_CLASS(PrepackedWeightsContainer); +ORT_RUNTIME_CLASS(TensorRTProviderOptionsV2); +ORT_RUNTIME_CLASS(NvTensorRtRtxProviderOptions); +ORT_RUNTIME_CLASS(CUDAProviderOptionsV2); +ORT_RUNTIME_CLASS(CANNProviderOptions); +ORT_RUNTIME_CLASS(DnnlProviderOptions); +ORT_RUNTIME_CLASS(Op); +ORT_RUNTIME_CLASS(OpAttr); +ORT_RUNTIME_CLASS(Logger); +ORT_RUNTIME_CLASS(ShapeInferContext); +ORT_RUNTIME_CLASS(LoraAdapter); +ORT_RUNTIME_CLASS(ValueInfo); +ORT_RUNTIME_CLASS(Node); +ORT_RUNTIME_CLASS(Graph); +ORT_RUNTIME_CLASS(Model); +ORT_RUNTIME_CLASS(ModelCompilationOptions); +ORT_RUNTIME_CLASS(HardwareDevice); +ORT_RUNTIME_CLASS(EpDevice); +ORT_RUNTIME_CLASS(KeyValuePairs); + +#ifdef _MSC_VER +typedef _Return_type_success_(return == 0) OrtStatus* OrtStatusPtr; +#else +typedef OrtStatus* OrtStatusPtr; +#endif + +/** \brief Memory allocation interface + * + * Structure of function pointers that defines a memory allocator. This can be created and filled in by the user for custom allocators. + * + * When an allocator is passed to any function, be sure that the allocator object is not destroyed until the last allocated object using it is freed. + */ +typedef struct OrtAllocator { + uint32_t version; ///< Must be initialized to ORT_API_VERSION + void*(ORT_API_CALL* Alloc)(struct OrtAllocator* this_, size_t size); ///< Returns a pointer to an allocated block of `size` bytes + void(ORT_API_CALL* Free)(struct OrtAllocator* this_, void* p); ///< Free a block of memory previously allocated with OrtAllocator::Alloc + const struct OrtMemoryInfo*(ORT_API_CALL* Info)(const struct OrtAllocator* this_); ///< Return a pointer to an ::OrtMemoryInfo that describes this allocator + /** + * @brief Optional allocation function to use for memory allocations made during session initialization. + * Use this function if you want to separate allocations made by ORT during Run() calls from + * those made during session initialization. This allows for separate memory management strategies for these allocations. + */ + void*(ORT_API_CALL* Reserve)(struct OrtAllocator* this_, size_t size); ///< Returns a pointer to an allocated block of `size` bytes +} OrtAllocator; + +typedef void(ORT_API_CALL* OrtLoggingFunction)( + void* param, OrtLoggingLevel severity, const char* category, const char* logid, const char* code_location, + const char* message); + +/** \brief Graph optimization level + * + * Refer to https://www.onnxruntime.ai/docs/performance/graph-optimizations.html#graph-optimization-levels + * for an in-depth understanding of the Graph Optimization Levels. + */ +typedef enum GraphOptimizationLevel { + ORT_DISABLE_ALL = 0, + ORT_ENABLE_BASIC = 1, + ORT_ENABLE_EXTENDED = 2, + ORT_ENABLE_ALL = 99 +} GraphOptimizationLevel; + +typedef enum ExecutionMode { + ORT_SEQUENTIAL = 0, + ORT_PARALLEL = 1, +} ExecutionMode; + +/** \brief Language projection identifiers + * /see OrtApi::SetLanguageProjection + */ +typedef enum OrtLanguageProjection { + ORT_PROJECTION_C = 0, + ORT_PROJECTION_CPLUSPLUS = 1, + ORT_PROJECTION_CSHARP = 2, + ORT_PROJECTION_PYTHON = 3, + ORT_PROJECTION_JAVA = 4, + ORT_PROJECTION_WINML = 5, + ORT_PROJECTION_NODEJS = 6, +} OrtLanguageProjection; + +struct OrtKernelInfo; +typedef struct OrtKernelInfo OrtKernelInfo; +struct OrtKernelContext; +typedef struct OrtKernelContext OrtKernelContext; +struct OrtCustomOp; +typedef struct OrtCustomOp OrtCustomOp; + +typedef enum OrtAllocatorType { + OrtInvalidAllocator = -1, + OrtDeviceAllocator = 0, + OrtArenaAllocator = 1 +} OrtAllocatorType; + +/** \brief Memory types for allocated memory, execution provider specific types should be extended in each provider. + */ +// Whenever this struct is updated, please also update the MakeKey function in onnxruntime / core / framework / execution_provider.cc +typedef enum OrtMemType { + OrtMemTypeCPUInput = -2, ///< Any CPU memory used by non-CPU execution provider + OrtMemTypeCPUOutput = -1, ///< CPU accessible memory outputted by non-CPU execution provider, i.e. CUDA_PINNED + OrtMemTypeCPU = OrtMemTypeCPUOutput, ///< Temporary CPU accessible memory allocated by non-CPU execution provider, i.e. CUDA_PINNED + OrtMemTypeDefault = 0, ///< The default allocator for execution provider +} OrtMemType; + +/** \brief This mimics OrtDevice type constants so they can be returned in the API + */ +typedef enum OrtMemoryInfoDeviceType { + OrtMemoryInfoDeviceType_CPU = 0, + OrtMemoryInfoDeviceType_GPU = 1, + OrtMemoryInfoDeviceType_FPGA = 2 +} OrtMemoryInfoDeviceType; + +typedef enum OrtHardwareDeviceType { + OrtHardwareDeviceType_CPU, + OrtHardwareDeviceType_GPU, + OrtHardwareDeviceType_NPU +} OrtHardwareDeviceType; + +/** \brief These are the default EP selection policies used by ORT when doing automatic EP selection. + */ +typedef enum OrtExecutionProviderDevicePolicy { + OrtExecutionProviderDevicePolicy_DEFAULT, + OrtExecutionProviderDevicePolicy_PREFER_CPU, + OrtExecutionProviderDevicePolicy_PREFER_NPU, + OrtExecutionProviderDevicePolicy_PREFER_GPU, + OrtExecutionProviderDevicePolicy_MAX_PERFORMANCE, + OrtExecutionProviderDevicePolicy_MAX_EFFICIENCY, + OrtExecutionProviderDevicePolicy_MIN_OVERALL_POWER, +} OrtExecutionProviderDevicePolicy; + +/** \brief Delegate to allow providing custom OrtEpDevice selection logic + * + * This delegate is called by the EP selection code to allow the user to provide custom device selection logic. + * The user can use this to select OrtEpDevice instances from the list of available devices. + * + * \param ep_devices The list of available devices. + * \param num_devices The number of available devices. + * \param model_metadata The model metadata. + * \param runtime_metadata The runtime metadata. May be nullptr. + * \param selected Pre-allocated array to populate with selected OrtEpDevice pointers from ep_devices. + * \param max_ep_devices The maximum number of devices that can be selected in the pre-allocated array. + Currently the maximum is 8. + * \param num_ep_devices The number of selected devices. + * \param state Opaque pointer. Required to use the delegate from other languages like C# and python. + * + * \return OrtStatus* Selection status. Return nullptr on success. + * Use CreateStatus to provide error info. Use ORT_FAIL as the error code. + * ORT will release the OrtStatus* if not null. + */ +typedef OrtStatus* (*EpSelectionDelegate)(_In_ const OrtEpDevice** ep_devices, + _In_ size_t num_devices, + _In_ const OrtKeyValuePairs* model_metadata, + _In_opt_ const OrtKeyValuePairs* runtime_metadata, + _Inout_ const OrtEpDevice** selected, + _In_ size_t max_selected, + _Out_ size_t* num_selected, + _In_ void* state); + +/** \brief Algorithm to use for cuDNN Convolution Op + */ +typedef enum OrtCudnnConvAlgoSearch { + OrtCudnnConvAlgoSearchExhaustive, // expensive exhaustive benchmarking using cudnnFindConvolutionForwardAlgorithmEx + OrtCudnnConvAlgoSearchHeuristic, // lightweight heuristic based search using cudnnGetConvolutionForwardAlgorithm_v7 + OrtCudnnConvAlgoSearchDefault, // default algorithm using CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM +} OrtCudnnConvAlgoSearch; + +/** \brief CUDA Provider Options + * + * \see OrtApi::SessionOptionsAppendExecutionProvider_CUDA + */ +typedef struct OrtCUDAProviderOptions { +#ifdef __cplusplus + OrtCUDAProviderOptions() + : device_id{}, + cudnn_conv_algo_search{OrtCudnnConvAlgoSearchExhaustive}, + gpu_mem_limit{SIZE_MAX}, + arena_extend_strategy{}, + do_copy_in_default_stream{1}, + has_user_compute_stream{}, + user_compute_stream{}, + default_memory_arena_cfg{}, + tunable_op_enable{false}, + tunable_op_tuning_enable{false}, + tunable_op_max_tuning_duration_ms{} {} +#endif + + /** \brief CUDA device Id + * Defaults to 0. + */ + int device_id; + + /** \brief CUDA Convolution algorithm search configuration. + * See enum OrtCudnnConvAlgoSearch for more details. + * Defaults to OrtCudnnConvAlgoSearchExhaustive. + */ + OrtCudnnConvAlgoSearch cudnn_conv_algo_search; + + /** \brief CUDA memory limit (To use all possible memory pass in maximum size_t) + * Defaults to SIZE_MAX. + * \note If a ::OrtArenaCfg has been applied, it will override this field + */ + size_t gpu_mem_limit; + + /** \brief Strategy used to grow the memory arena + * 0 = kNextPowerOfTwo
+ * 1 = kSameAsRequested
+ * Defaults to 0. + * \note If a ::OrtArenaCfg has been applied, it will override this field + */ + int arena_extend_strategy; + + /** \brief Flag indicating if copying needs to take place on the same stream as the compute stream in the CUDA EP + * 0 = Use separate streams for copying and compute. + * 1 = Use the same stream for copying and compute. + * Defaults to 1. + * WARNING: Setting this to 0 may result in data races for some models. + * Please see issue #4829 for more details. + */ + int do_copy_in_default_stream; + + /** \brief Flag indicating if there is a user provided compute stream + * Defaults to 0. + */ + int has_user_compute_stream; + + /** \brief User provided compute stream. + * If provided, please set `has_user_compute_stream` to 1. + */ + void* user_compute_stream; + + /** \brief CUDA memory arena configuration parameters + */ + OrtArenaCfg* default_memory_arena_cfg; + + /** \brief Enable TunableOp for using. + * Set it to 1/0 to enable/disable TunableOp. Otherwise, it is disabled by default. + * This option can be overridden by environment variable ORT_CUDA_TUNABLE_OP_ENABLE. + */ + int tunable_op_enable; + + /** \brief Enable TunableOp for tuning. + * Set it to 1/0 to enable/disable TunableOp tuning. Otherwise, it is disabled by default. + * This option can be overridden by environment variable ORT_CUDA_TUNABLE_OP_TUNING_ENABLE. + */ + int tunable_op_tuning_enable; + + /** \brief Max tuning duration time limit for each instance of TunableOp. + * Defaults to 0 to disable the limit. + */ + int tunable_op_max_tuning_duration_ms; + +} OrtCUDAProviderOptions; + +/** \brief ROCM Provider Options + * + * \see OrtApi::SessionOptionsAppendExecutionProvider_ROCM + */ +typedef struct OrtROCMProviderOptions { +#ifdef __cplusplus + OrtROCMProviderOptions() + : device_id{}, + miopen_conv_exhaustive_search{0}, + gpu_mem_limit{SIZE_MAX}, + arena_extend_strategy{}, + do_copy_in_default_stream{1}, + has_user_compute_stream{}, + user_compute_stream{}, + default_memory_arena_cfg{}, + enable_hip_graph{false}, + tunable_op_enable{false}, + tunable_op_tuning_enable{false}, + tunable_op_max_tuning_duration_ms{} {} +#endif + + /** \brief ROCM device Id + * Defaults to 0. + */ + int device_id; + + /** \brief ROCM MIOpen Convolution algorithm exaustive search option. + * Defaults to 0 (false). + */ + int miopen_conv_exhaustive_search; + + /** \brief ROCM memory limit (To use all possible memory pass in maximum size_t) + * Defaults to SIZE_MAX. + * \note If a ::OrtArenaCfg has been applied, it will override this field + */ + size_t gpu_mem_limit; + + /** \brief Strategy used to grow the memory arena + * 0 = kNextPowerOfTwo
+ * 1 = kSameAsRequested
+ * Defaults to 0. + * \note If a ::OrtArenaCfg has been applied, it will override this field + */ + int arena_extend_strategy; + + /** \brief Flag indicating if copying needs to take place on the same stream as the compute stream in the ROCM EP + * 0 = Use separate streams for copying and compute. + * 1 = Use the same stream for copying and compute. + * Defaults to 1. + * WARNING: Setting this to 0 may result in data races for some models. + * Please see issue #4829 for more details. + */ + int do_copy_in_default_stream; + + /** \brief Flag indicating if there is a user provided compute stream + * Defaults to 0. + */ + int has_user_compute_stream; + + /** \brief User provided compute stream. + * If provided, please set `has_user_compute_stream` to 1. + */ + void* user_compute_stream; + + /** \brief ROCM memory arena configuration parameters + */ + OrtArenaCfg* default_memory_arena_cfg; + + int enable_hip_graph; + + /** \brief Enable TunableOp for using. + * Set it to 1/0 to enable/disable TunableOp. Otherwise, it is disabled by default. + * This option can be overridden by environment variable ORT_ROCM_TUNABLE_OP_ENABLE. + */ + int tunable_op_enable; + + /** \brief Enable TunableOp for tuning. + * Set it to 1/0 to enable/disable TunableOp tuning. Otherwise, it is disabled by default. + * This option can be overridden by environment variable ORT_ROCM_TUNABLE_OP_TUNING_ENABLE. + */ + int tunable_op_tuning_enable; + + /** \brief Max tuning duration time limit for each instance of TunableOp. + * Defaults to 0 to disable the limit. + */ + int tunable_op_max_tuning_duration_ms; + +} OrtROCMProviderOptions; + +/** \brief TensorRT Provider Options + * + * \see OrtApi::SessionOptionsAppendExecutionProvider_TensorRT + */ +typedef struct OrtTensorRTProviderOptions { + int device_id; ///< CUDA device id (0 = default device) + int has_user_compute_stream; // indicator of user specified CUDA compute stream. + void* user_compute_stream; // user specified CUDA compute stream. + int trt_max_partition_iterations; // maximum iterations for TensorRT parser to get capability + int trt_min_subgraph_size; // minimum size of TensorRT subgraphs + size_t trt_max_workspace_size; // maximum workspace size for TensorRT. + int trt_fp16_enable; // enable TensorRT FP16 precision. Default 0 = false, nonzero = true + int trt_int8_enable; // enable TensorRT INT8 precision. Default 0 = false, nonzero = true + const char* trt_int8_calibration_table_name; // TensorRT INT8 calibration table name. + int trt_int8_use_native_calibration_table; // use native TensorRT generated calibration table. Default 0 = false, nonzero = true + int trt_dla_enable; // enable DLA. Default 0 = false, nonzero = true + int trt_dla_core; // DLA core number. Default 0 + int trt_dump_subgraphs; // dump TRT subgraph. Default 0 = false, nonzero = true + int trt_engine_cache_enable; // enable engine caching. Default 0 = false, nonzero = true + const char* trt_engine_cache_path; // specify engine cache path + int trt_engine_decryption_enable; // enable engine decryption. Default 0 = false, nonzero = true + const char* trt_engine_decryption_lib_path; // specify engine decryption library path + int trt_force_sequential_engine_build; // force building TensorRT engine sequentially. Default 0 = false, nonzero = true + // This is the legacy struct and don't add new fields here. + // For new field that can be represented by string, please add it in include/onnxruntime/core/providers/tensorrt/tensorrt_provider_options.h + // For non-string field, need to create a new separate api to handle it. +} OrtTensorRTProviderOptions; + +/** \brief MIGraphX Provider Options + * + * \see OrtApi::SessionOptionsAppendExecutionProvider_MIGraphX + */ +typedef struct OrtMIGraphXProviderOptions { + int device_id; // hip device id. + int migraphx_fp16_enable; // MIGraphX FP16 precision. Default 0 = false, nonzero = true + int migraphx_int8_enable; // MIGraphX INT8 precision. Default 0 = false, nonzero = true + int migraphx_use_native_calibration_table; // MIGraphx INT8 cal table. Default 0 = false, noznero = true + const char* migraphx_int8_calibration_table_name; // MIGraphx INT8 calibration table name + int migraphx_save_compiled_model; // migraphx save compiled model. Default 0 = false, noznero = true + const char* migraphx_save_model_path; // migraphx model path name + int migraphx_load_compiled_model; // migraphx int8 cal table. Default 0 = false, noznero = true + const char* migraphx_load_model_path; // migraphx model path name + bool migraphx_exhaustive_tune; // migraphx tuned compile Default = false +} OrtMIGraphXProviderOptions; + +/** \brief OpenVINO Provider Options + * \brief This Struct is frozen since ORT 1.13.0. Its maintained part of Legacy API for compatibility. + * \brief For latest OpenVINO Provider Options update to the ProviderOptions map. + * \brief Latest OpenVINO Provider Options are listed in the + * \htmlonly + * onnxruntime document. + * \endhtmlonly + * \see OrtApi::SessionOptionsAppendExecutionProvider() + */ +typedef struct OrtOpenVINOProviderOptions { +#ifdef __cplusplus + OrtOpenVINOProviderOptions() : device_type{}, + enable_npu_fast_compile{}, + device_id{}, + num_of_threads{}, + cache_dir{}, + context{}, + enable_opencl_throttling{}, + enable_dynamic_shapes{} {} +#endif + /** \brief Device type string + * + * Valid settings are one of: "CPU_FP32", "CPU_FP16", "GPU_FP32", "GPU_FP16" + */ + const char* device_type; + unsigned char enable_npu_fast_compile; ///< 0 = disabled, nonzero = enabled + const char* device_id; + size_t num_of_threads; ///< 0 = Use default number of threads + const char* cache_dir; // path is set to empty by default + void* context; + unsigned char enable_opencl_throttling; ///< 0 = disabled, nonzero = enabled + unsigned char enable_dynamic_shapes; ///< 0 = disabled, nonzero = enabled +} OrtOpenVINOProviderOptions; + +struct OrtApi; +typedef struct OrtApi OrtApi; + +struct OrtTrainingApi; +typedef struct OrtTrainingApi OrtTrainingApi; + +struct OrtModelEditorApi; +typedef struct OrtModelEditorApi OrtModelEditorApi; + +struct OrtCompileApi; +typedef struct OrtCompileApi OrtCompileApi; + +struct OrtEpApi; +typedef struct OrtEpApi OrtEpApi; + +/** \brief The helper interface to get the right version of OrtApi + * + * Get a pointer to this structure through ::OrtGetApiBase + */ +struct OrtApiBase { + /** \brief Get a pointer to the requested version of the ::OrtApi + * + * \param[in] version Must be ::ORT_API_VERSION + * \return The ::OrtApi for the version requested, nullptr will be returned if this version is unsupported, for example when using a runtime + * older than the version created with this header file. + * + * One can call GetVersionString() to get the version of the Onnxruntime library for logging + * and error reporting purposes. + */ + const OrtApi*(ORT_API_CALL* GetApi)(uint32_t version)NO_EXCEPTION; + + /** \brief Returns a null terminated string of the version of the Onnxruntime library (eg: "1.8.1") + * + * \return UTF-8 encoded version string. Do not deallocate the returned buffer. + */ + const char*(ORT_API_CALL* GetVersionString)(void)NO_EXCEPTION; +}; + +typedef struct OrtApiBase OrtApiBase; + +/** \brief The Onnxruntime library's entry point to access the C API + * + * Call this to get the a pointer to an ::OrtApiBase + */ +ORT_EXPORT const OrtApiBase* ORT_API_CALL OrtGetApiBase(void) NO_EXCEPTION; + +/** \brief Thread work loop function + * + * Onnxruntime will provide the working loop on custom thread creation + * Argument is an onnxruntime built-in type which will be provided when thread pool calls OrtCustomCreateThreadFn + */ +typedef void (*OrtThreadWorkerFn)(void* ort_worker_fn_param); + +typedef const struct OrtCustomHandleType { + char __place_holder; +}* OrtCustomThreadHandle; + +/** \brief Ort custom thread creation function + * + * The function should return a thread handle to be used in onnxruntime thread pools + * Onnxruntime will throw exception on return value of nullptr or 0, indicating that the function failed to create a thread + */ +typedef OrtCustomThreadHandle (*OrtCustomCreateThreadFn)(void* ort_custom_thread_creation_options, OrtThreadWorkerFn ort_thread_worker_fn, void* ort_worker_fn_param); + +/** \brief Custom thread join function + * + * Onnxruntime thread pool destructor will call the function to join a custom thread. + * Argument ort_custom_thread_handle is the value returned by OrtCustomCreateThreadFn + */ +typedef void (*OrtCustomJoinThreadFn)(OrtCustomThreadHandle ort_custom_thread_handle); + +typedef OrtStatus*(ORT_API_CALL* RegisterCustomOpsFn)(OrtSessionOptions* options, const OrtApiBase* api); + +/** \brief Callback function for RunAsync + * + * \param[in] user_data User specific data that passed back to the callback + * \param[out] outputs On succeed, outputs host inference results, on error, the value will be nullptr + * \param[out] num_outputs Number of outputs, on error, the value will be zero + * \param[out] status On error, status will provide details + */ +typedef void (*RunAsyncCallbackFn)(void* user_data, OrtValue** outputs, size_t num_outputs, OrtStatusPtr status); + +/** \brief The C API + * + * All C API functions are defined inside this structure as pointers to functions. + * Call OrtApiBase::GetApi to get a pointer to it + * + * \nosubgrouping + */ +struct OrtApi { + /// \name OrtStatus + /// @{ + + /** + * \brief Create an OrtStatus from a null terminated string + * + * \param[in] code + * \param[in] msg A null-terminated string. Its contents will be copied. + * \return A new OrtStatus object, must be destroyed with OrtApi::ReleaseStatus + */ + OrtStatus*(ORT_API_CALL* CreateStatus)(OrtErrorCode code, _In_ const char* msg)NO_EXCEPTION ORT_ALL_ARGS_NONNULL; + + /** \brief Get OrtErrorCode from OrtStatus + * + * \param[in] status + * \return OrtErrorCode that \p status was created with + */ + OrtErrorCode(ORT_API_CALL* GetErrorCode)(_In_ const OrtStatus* status) NO_EXCEPTION ORT_ALL_ARGS_NONNULL; + + /** \brief Get error string from OrtStatus + * + * \param[in] status + * \return The error message inside the `status`. Do not free the returned value. + */ + const char*(ORT_API_CALL* GetErrorMessage)(_In_ const OrtStatus* status)NO_EXCEPTION ORT_ALL_ARGS_NONNULL; + + /// @} + /// \name OrtEnv + /// @{ + + /** \brief Create an OrtEnv + * + * \note Invoking this function will return the same instance of the environment as that returned by a previous call + * to another env creation function; all arguments to this function will be ignored. + * \param[in] log_severity_level The log severity level. + * \param[in] logid The log identifier. + * \param[out] out Returned newly created OrtEnv. Must be freed with OrtApi::ReleaseEnv + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateEnv, OrtLoggingLevel log_severity_level, _In_ const char* logid, _Outptr_ OrtEnv** out); + + /** \brief Create an OrtEnv + * + * \note Invoking this function will return the same instance of the environment as that returned by a previous call + * to another env creation function; all arguments to this function will be ignored. If you want to provide your + * own logging function, consider setting it using the SetUserLoggingFunction API instead. + * \param[in] logging_function A pointer to a logging function. + * \param[in] logger_param A pointer to arbitrary data passed as the ::OrtLoggingFunction `param` parameter to + * `logging_function`. This parameter is optional. + * \param[in] log_severity_level The log severity level. + * \param[in] logid The log identifier. + * \param[out] out Returned newly created OrtEnv. Must be freed with OrtApi::ReleaseEnv + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateEnvWithCustomLogger, _In_ OrtLoggingFunction logging_function, _In_opt_ void* logger_param, + _In_ OrtLoggingLevel log_severity_level, _In_ const char* logid, _Outptr_ OrtEnv** out); + + /** \brief Enable Telemetry + * + * \note Telemetry events are on by default since they are lightweight + * \param[in] env + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(EnableTelemetryEvents, _In_ const OrtEnv* env); + /** \brief Disable Telemetry + * + * \see OrtApi::EnableTelemetryEvents + * \param[in] env + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(DisableTelemetryEvents, _In_ const OrtEnv* env); + + /// @} + /// \name OrtSession + /// @{ + + /** \brief Create an OrtSession from a model file + * + * \param[in] env + * \param[in] model_path + * \param[in] options + * \param[out] out Returned newly created OrtSession. Must be freed with OrtApi::ReleaseSession + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + // TODO: document the path separator convention? '/' vs '\' + // TODO: should specify the access characteristics of model_path. Is this read only during the + // execution of CreateSession, or does the OrtSession retain a handle to the file/directory + // and continue to access throughout the OrtSession lifetime? + // What sort of access is needed to model_path : read or read/write? + ORT_API2_STATUS(CreateSession, _In_ const OrtEnv* env, _In_ const ORTCHAR_T* model_path, + _In_ const OrtSessionOptions* options, _Outptr_ OrtSession** out); + + /** \brief Create an OrtSession from memory + * + * \param[in] env + * \param[in] model_data + * \param[in] model_data_length + * \param[in] options + * \param[out] out Returned newly created OrtSession. Must be freed with OrtApi::ReleaseSession + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateSessionFromArray, _In_ const OrtEnv* env, + _In_ const void* model_data, size_t model_data_length, + _In_ const OrtSessionOptions* options, _Outptr_ OrtSession** out); + + /** \brief Run the model in an ::OrtSession + * + * Will not return until the model run has completed. Multiple threads might be used to run the model based on + * the options in the ::OrtSession and settings used when creating the ::OrtEnv + * + * \param[in] session + * \param[in] run_options If nullptr, will use a default ::OrtRunOptions + * \param[in] input_names Array of null terminated UTF8 encoded strings of the input names + * \param[in] inputs Array of ::OrtValue%s of the input values + * \param[in] input_len Number of elements in the input_names and inputs arrays + * \param[in] output_names Array of null terminated UTF8 encoded strings of the output names + * \param[in] output_names_len Number of elements in the output_names and outputs array + * \param[out] outputs Array of ::OrtValue%s that the outputs are stored in. This can also be + * an array of nullptr values, in this case ::OrtValue objects will be allocated and pointers + * to them will be set into the `outputs` array. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(Run, _Inout_ OrtSession* session, _In_opt_ const OrtRunOptions* run_options, + _In_reads_(input_len) const char* const* input_names, + _In_reads_(input_len) const OrtValue* const* inputs, size_t input_len, + _In_reads_(output_names_len) const char* const* output_names, size_t output_names_len, + _Inout_updates_all_(output_names_len) OrtValue** outputs); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Create an ::OrtSessionOptions object + * + * To use additional providers, you must build ORT with the extra providers enabled. Then call one of these + * functions to enable them in the session:
+ * OrtSessionOptionsAppendExecutionProvider_CPU
+ * OrtSessionOptionsAppendExecutionProvider_CUDA
+ * OrtSessionOptionsAppendExecutionProvider_(remaining providers...)
+ * The order they are called indicates the preference order as well. In other words call this method + * on your most preferred execution provider first followed by the less preferred ones. + * If none are called Ort will use its internal CPU execution provider. + * + * \param[out] options The newly created OrtSessionOptions. Must be freed with OrtApi::ReleaseSessionOptions + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateSessionOptions, _Outptr_ OrtSessionOptions** options); + + /** \brief Set filepath to save optimized model after graph level transformations + * + * \param[in] options + * \param[in] optimized_model_filepath + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetOptimizedModelFilePath, _Inout_ OrtSessionOptions* options, + _In_ const ORTCHAR_T* optimized_model_filepath); + + /** \brief Create a copy of an existing ::OrtSessionOptions + * + * \param[in] in_options OrtSessionOptions to copy + * \param[out] out_options Returned newly created ::OrtSessionOptions. Must be freed with OrtApi::ReleaseSessionOptions + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CloneSessionOptions, _In_ const OrtSessionOptions* in_options, + _Outptr_ OrtSessionOptions** out_options); + + /** \brief Set execution mode + * + * Controls whether you want to execute operators in your graph sequentially or in parallel. Usually when the model + * has many branches, setting this option to ExecutionMode.ORT_PARALLEL will give you better performance. + * See [docs/ONNX_Runtime_Perf_Tuning.md] for more details. + * + * \param[in] options + * \param[in] execution_mode + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetSessionExecutionMode, _Inout_ OrtSessionOptions* options, ExecutionMode execution_mode); + + /** \brief Enable profiling for a session + * + * \param[in] options + * \param[in] profile_file_prefix + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(EnableProfiling, _Inout_ OrtSessionOptions* options, _In_ const ORTCHAR_T* profile_file_prefix); + + /** \brief Disable profiling for a session + * + * \param[in] options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(DisableProfiling, _Inout_ OrtSessionOptions* options); + + /** \brief Enable the memory pattern optimization + * + * The idea is if the input shapes are the same, we could trace the internal memory allocation + * and generate a memory pattern for future request. So next time we could just do one allocation + * with a big chunk for all the internal memory allocation. + * \note Memory pattern optimization is only available when Sequential Execution mode is enabled (see OrtApi::SetSessionExecutionMode) + * + * \see OrtApi::DisableMemPattern + * + * \param[in] options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(EnableMemPattern, _Inout_ OrtSessionOptions* options); + + /** \brief Disable the memory pattern optimization + * + * \see OrtApi::EnableMemPattern + * + * \param[in] options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(DisableMemPattern, _Inout_ OrtSessionOptions* options); + + /** \brief Enable the memory arena on CPU + * + * Arena may pre-allocate memory for future usage. + * + * \param[in] options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(EnableCpuMemArena, _Inout_ OrtSessionOptions* options); + + /** \brief Disable the memory arena on CPU + * + * \param[in] options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(DisableCpuMemArena, _Inout_ OrtSessionOptions* options); + + /** \brief Set session log id + * + * \param[in] options + * \param[in] logid The log identifier. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetSessionLogId, _Inout_ OrtSessionOptions* options, const char* logid); + + /** \brief Set session log verbosity level + * + * Applies to session load, initialization, etc + * + * \param[in] options + * \param[in] session_log_verbosity_level \snippet{doc} snippets.dox Log Verbosity Level + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetSessionLogVerbosityLevel, _Inout_ OrtSessionOptions* options, int session_log_verbosity_level); + + /** \brief Set session log severity level + * + * \param[in] options + * \param[in] session_log_severity_level The log severity level (refer to ::OrtLoggingLevel for possible values). + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetSessionLogSeverityLevel, _Inout_ OrtSessionOptions* options, int session_log_severity_level); + + /** \brief Set the optimization level to apply when loading a graph + * + * Please see https://onnxruntime.ai/docs/performance/model-optimizations/graph-optimizations.html for an in-depth explanation + * \param[in,out] options The session options object + * \param[in] graph_optimization_level The optimization level + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetSessionGraphOptimizationLevel, _Inout_ OrtSessionOptions* options, + GraphOptimizationLevel graph_optimization_level); + + /** \brief Sets the number of threads used to parallelize the execution within nodes + * + * When running a single node operation, ex. add, this sets the maximum number of threads to use. + * + * \note If built with OpenMP, this has no effect on the number of threads used. In this case + * use the OpenMP env variables to configure the number of intra op num threads. + * + * \param[in] options + * \param[in] intra_op_num_threads Number of threads to use
+ * A value of 0 will use the default number of threads
+ * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetIntraOpNumThreads, _Inout_ OrtSessionOptions* options, int intra_op_num_threads); + + /** \brief Sets the number of threads used to parallelize the execution of the graph + * + * If nodes can be run in parallel, this sets the maximum number of threads to use to run them in parallel. + * + * \note If sequential execution is enabled this value is ignored, it acts as if it was set to 1. + * + * \param[in] options + * \param[in] inter_op_num_threads Number of threads to use
+ * A value of 0 will use the default number of threads
+ * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetInterOpNumThreads, _Inout_ OrtSessionOptions* options, int inter_op_num_threads); + + /// @} + /// \name OrtCustomOpDomain + /// @{ + + /** \brief Create a custom op domain + * + * \param[in] domain + * \param[out] out Newly created domain. Must be freed with OrtApi::ReleaseCustomOpDomain + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateCustomOpDomain, _In_ const char* domain, _Outptr_ OrtCustomOpDomain** out); + + /** \brief Add a custom op to a custom op domain + * + * \note The OrtCustomOp* pointer must remain valid until the ::OrtCustomOpDomain using it is released + * + * \param[in] custom_op_domain + * \param[in] op + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CustomOpDomain_Add, _Inout_ OrtCustomOpDomain* custom_op_domain, _In_ const OrtCustomOp* op); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Add custom op domain to a session options + * + * \note The OrtCustomOpDomain* must not be deleted until all sessions using it are released + * + * \param[in] options + * \param[in] custom_op_domain + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(AddCustomOpDomain, _Inout_ OrtSessionOptions* options, _In_ OrtCustomOpDomain* custom_op_domain); + + /** \deprecated Use OrtApi::RegisterCustomOpsLibrary_V2. + * + * Registers custom ops from a shared library. + * + * Loads a shared library (dll on windows, so on linux, etc) named 'library_path' and looks for this entry point: + * OrtStatus* RegisterCustomOps(OrtSessionOptions * options, const OrtApiBase* api); + * It then passes in the provided session options to this function along with the api base. + * The handle to the loaded library is returned in library_handle. It can be freed by the caller after all sessions using the passed in + * session options are destroyed, or if an error occurs and it is non null. + * + * \param[in] options + * \param[in] library_path + * \param[out] library_handle OS specific handle to the loaded library (Use FreeLibrary on Windows, dlclose on Linux, etc.. to unload) + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(RegisterCustomOpsLibrary, _Inout_ OrtSessionOptions* options, _In_ const char* library_path, _Outptr_ void** library_handle); + + /// @} + /// \name OrtSession + /// @{ + + /** \brief Get input count for a session + * + * This number must also match the number of inputs passed to OrtApi::Run + * + * \see OrtApi::SessionGetInputTypeInfo, OrtApi::SessionGetInputName, OrtApi::Session + * + * \param[in] session + * \param[out] out Number of inputs + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetInputCount, _In_ const OrtSession* session, _Out_ size_t* out); + + /** \brief Get output count for a session + * + * This number must also match the number of outputs returned by OrtApi::Run + * + * \see OrtApi::SessionGetOutputTypeInfo, OrtApi::SessionGetOutputName, OrtApi::Session + * + * \param[in] session + * \param[out] out Number of outputs + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetOutputCount, _In_ const OrtSession* session, _Out_ size_t* out); + + /** \brief Get overridable initializer count + * + * \see OrtApi::SessionGetOverridableInitializerTypeInfo, OrtApi::SessionGetOverridableInitializerName + * + * \param[in] session + * \param[in] out + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetOverridableInitializerCount, _In_ const OrtSession* session, _Out_ size_t* out); + + /** \brief Get input type information + * + * \param[in] session + * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetInputCount returns (exclusive) + * \param[out] type_info Must be freed with OrtApi::ReleaseTypeInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetInputTypeInfo, _In_ const OrtSession* session, size_t index, _Outptr_ OrtTypeInfo** type_info); + + /** \brief Get output type information + * + * \param[in] session + * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetOutputCount returns (exclusive) + * \param[out] type_info Must be freed with OrtApi::ReleaseTypeInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetOutputTypeInfo, _In_ const OrtSession* session, size_t index, _Outptr_ OrtTypeInfo** type_info); + + /** \brief Get overridable initializer type information + * + * \param[in] session + * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetOverridableInitializerCount returns (exclusive) + * \param[out] type_info Must be freed with OrtApi::ReleaseTypeInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetOverridableInitializerTypeInfo, _In_ const OrtSession* session, size_t index, _Outptr_ OrtTypeInfo** type_info); + + /** \brief Get input name + * + * \param[in] session + * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetInputCount returns (exclusive) + * \param[in] allocator + * \param[out] value Set to a null terminated UTF-8 encoded string allocated using `allocator`. Must be freed using `allocator`. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetInputName, _In_ const OrtSession* session, size_t index, _Inout_ OrtAllocator* allocator, _Outptr_ char** value); + + /** \brief Get output name + * + * \param[in] session + * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetOutputCount returns (exclusive) + * \param[in] allocator + * \param[out] value Set to a null terminated UTF-8 encoded string allocated using `allocator`. Must be freed using `allocator`. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetOutputName, _In_ const OrtSession* session, size_t index, _Inout_ OrtAllocator* allocator, _Outptr_ char** value); + + /** \brief Get overridable initializer name + * + * \param[in] session + * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetOverridableInitializerCount returns (exclusive) + * \param[in] allocator + * \param[out] value Set to a null terminated UTF-8 encoded string allocated using `allocator`. Must be freed using `allocator`. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetOverridableInitializerName, _In_ const OrtSession* session, size_t index, + _Inout_ OrtAllocator* allocator, _Outptr_ char** value); + + /// @} + /// \name OrtRunOptions + /// @{ + + /** \brief Create an OrtRunOptions + * + * \param[out] out Returned newly created ::OrtRunOptions. Must be freed with OrtApi::ReleaseRunOptions + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateRunOptions, _Outptr_ OrtRunOptions** out); + + /** \brief Set per-run log verbosity level + * + * \see OrtApi::RunOptionsGetRunLogVerbosityLevel + * + * \param[in] options + * \param[in] log_verbosity_level \snippet{doc} snippets.dox Log Verbosity Level + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(RunOptionsSetRunLogVerbosityLevel, _Inout_ OrtRunOptions* options, int log_verbosity_level); + + /** \brief Set per-run log severity level + * + * \see OrtApi::RunOptionsGetRunLogSeverityLevel + * + * \param[in] options + * \param[in] log_severity_level The log severity level (refer to ::OrtLoggingLevel for possible values). + */ + ORT_API2_STATUS(RunOptionsSetRunLogSeverityLevel, _Inout_ OrtRunOptions* options, int log_severity_level); + + /** \brief Set per-run tag + * + * This is used in a per-run log identifier. + * + * \see OrtApi::RunOptionsGetRunTag + * + * \param[in] options + * \param[in] run_tag The run tag. + */ + ORT_API2_STATUS(RunOptionsSetRunTag, _Inout_ OrtRunOptions* options, _In_ const char* run_tag); + + /** \brief Get per-run log verbosity level + * + * \see OrtApi::RunOptionsSetRunLogVerbosityLevel + * + * \param[in] options + * \param[out] log_verbosity_level \snippet{doc} snippets.dox Log Verbosity Level + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(RunOptionsGetRunLogVerbosityLevel, _In_ const OrtRunOptions* options, + _Out_ int* log_verbosity_level); + + /** \brief Get per-run log severity level + * + * \see OrtApi::RunOptionsSetRunLogSeverityLevel + * + * \param[in] options + * \param[out] log_severity_level The log severity level (refer to ::OrtLoggingLevel for possible values). + */ + ORT_API2_STATUS(RunOptionsGetRunLogSeverityLevel, _In_ const OrtRunOptions* options, _Out_ int* log_severity_level); + + /** \brief Get per-run tag + * + * This is used in a per-run log identifier. + * + * \see OrtApi::RunOptionsSetRunTag + * + * \param[in] options + * \param[out] run_tag The run tag. + * Do not free this value, it is owned by `options`. It will be invalidated if the run tag + * changes (i.e., with OrtApi::RunOptionsSetRunTag) or `options` is freed. + */ + ORT_API2_STATUS(RunOptionsGetRunTag, _In_ const OrtRunOptions* options, _Out_ const char** run_tag); + + /** \brief Set terminate flag + * + * If a currently executing session needs to be force terminated, this can be called from another thread to force it to fail with an error. + * + * \param[in] options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(RunOptionsSetTerminate, _Inout_ OrtRunOptions* options); + + /** \brief Clears the terminate flag + * + * Used so the OrtRunOptions instance can be used in a new OrtApi::Run call without it instantly terminating + * + * \param[in] options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(RunOptionsUnsetTerminate, _Inout_ OrtRunOptions* options); + + /// @} + /// \name OrtValue + /// @{ + + /** \brief Create a tensor + * + * Create a tensor using a supplied ::OrtAllocator + * + * \param[in] allocator + * \param[in] shape Pointer to the tensor shape dimensions. + * \param[in] shape_len The number of tensor shape dimensions. + * \param[in] type + * \param[out] out Returns newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateTensorAsOrtValue, _Inout_ OrtAllocator* allocator, _In_ const int64_t* shape, size_t shape_len, + ONNXTensorElementDataType type, _Outptr_ OrtValue** out); + + /** \brief Create a tensor backed by a user supplied buffer + * + * Create a tensor with user's buffer. You can fill the buffer either before calling this function or after. + * p_data is owned by caller. ReleaseValue won't release p_data. + * + * If you wish to transfer ownership of p_data to ORT use CreateTensorWithDataAndDeleterAsOrtValue. + * + * \param[in] info Memory description of where the p_data buffer resides (CPU vs GPU etc). + * \param[in] p_data Pointer to the data buffer. + * \param[in] p_data_len The number of bytes in the data buffer. + * \param[in] shape Pointer to the tensor shape dimensions. + * \param[in] shape_len The number of tensor shape dimensions. + * \param[in] type The data type. + * \param[out] out Returns newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateTensorWithDataAsOrtValue, _In_ const OrtMemoryInfo* info, _Inout_ void* p_data, + size_t p_data_len, _In_ const int64_t* shape, size_t shape_len, ONNXTensorElementDataType type, + _Outptr_ OrtValue** out); + + /** \brief Return if an ::OrtValue is a tensor type + * + * \param[in] value A tensor type (string tensors are not supported) + * \param[out] out Set to 1 iff ::OrtValue is a tensor, 0 otherwise + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(IsTensor, _In_ const OrtValue* value, _Out_ int* out); + + /** \brief Get a pointer to the raw data inside a tensor + * + * Used to read/write/modify the internal tensor data directly. + * \note The returned pointer is valid until the \p value is destroyed. + * + * \param[in] value A tensor type (string tensors are not supported) + * \param[out] out Filled in with a pointer to the internal storage + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetTensorMutableData, _In_ OrtValue* value, _Outptr_ void** out); + + /** \brief Set all strings at once in a string tensor + * + * \param[in,out] value A tensor of type ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING + * \param[in] s An array of strings. Each string in this array must be null terminated. + * \param[in] s_len Count of strings in s (Must match the size of \p value's tensor shape) + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(FillStringTensor, _Inout_ OrtValue* value, _In_ const char* const* s, size_t s_len); + + /** \brief Get total byte length for all strings in a string tensor + * + * Typically used with OrtApi::GetStringTensorContent + * + * \param[in] value A tensor of type ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING + * \param[out] len Total byte length of all strings (does not include trailing nulls) + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetStringTensorDataLength, _In_ const OrtValue* value, _Out_ size_t* len); + + /** \brief Get all strings from a string tensor + * + * An example of the results:
+ * Given \p value is a string tensor with the strings { "This" "is" "a" "test" }
+ * \p s must have a size of 11 bytes
+ * \p offsets must have 4 elements
+ * After the call, these values will be filled in:
+ * \p s will contain "Thisisatest"
+ * \p offsets will contain { 0, 4, 6, 7 }
+ * The length of the last string is just s_len - offsets[last] + * + * \param[in] value A tensor of type ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING + * \param[in] s Buffer to sequentially write all tensor strings to. Each string is NOT null-terminated. + * \param[in] s_len Number of bytes of buffer pointed to by \p s (Get it from OrtApi::GetStringTensorDataLength) + * \param[out] offsets Array of start offsets into the strings written to \p s + * \param[in] offsets_len Number of elements in offsets + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetStringTensorContent, _In_ const OrtValue* value, _Out_writes_bytes_all_(s_len) void* s, + size_t s_len, _Out_writes_all_(offsets_len) size_t* offsets, size_t offsets_len); + + /// @} + /// \name OrtTypeInfo + /// @{ + + /** \brief Get ::OrtTensorTypeAndShapeInfo from an ::OrtTypeInfo + * + * \param[in] type_info + * \param[out] out Do not free this value, it will be valid until type_info is freed. + * If type_info does not represent tensor, this value will be set to nullptr. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CastTypeInfoToTensorInfo, _In_ const OrtTypeInfo* type_info, + _Outptr_result_maybenull_ const OrtTensorTypeAndShapeInfo** out); + + /** \brief Get ::ONNXType from ::OrtTypeInfo + * + * \param[in] type_info + * \param[out] out + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetOnnxTypeFromTypeInfo, _In_ const OrtTypeInfo* type_info, _Out_ enum ONNXType* out); + + /// @} + /// \name OrtTensorTypeAndShapeInfo + /// @{ + + /** \brief Create an ::OrtTensorTypeAndShapeInfo object + * + * \param[out] out Returns newly created ::OrtTensorTypeAndShapeInfo. Must be freed with OrtApi::ReleaseTensorTypeAndShapeInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateTensorTypeAndShapeInfo, _Outptr_ OrtTensorTypeAndShapeInfo** out); + + /** \brief Set element type in ::OrtTensorTypeAndShapeInfo + * + * \param[in] info + * \param[in] type + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetTensorElementType, _Inout_ OrtTensorTypeAndShapeInfo* info, enum ONNXTensorElementDataType type); + + /** \brief Set shape information in ::OrtTensorTypeAndShapeInfo + * + * \param[in] info + * \param[in] dim_values Array with `dim_count` elements. Can contain negative values. + * \param[in] dim_count Number of elements in `dim_values` + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetDimensions, OrtTensorTypeAndShapeInfo* info, _In_ const int64_t* dim_values, size_t dim_count); + + /** \brief Get element type in ::OrtTensorTypeAndShapeInfo + * + * \see OrtApi::SetTensorElementType + * + * \param[in] info + * \param[out] out + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetTensorElementType, _In_ const OrtTensorTypeAndShapeInfo* info, + _Out_ enum ONNXTensorElementDataType* out); + + /** \brief Get dimension count in ::OrtTensorTypeAndShapeInfo + * + * \see OrtApi::GetDimensions + * + * \param[in] info + * \param[out] out + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetDimensionsCount, _In_ const OrtTensorTypeAndShapeInfo* info, _Out_ size_t* out); + + /** \brief Get dimensions in ::OrtTensorTypeAndShapeInfo + * + * \param[in] info + * \param[out] dim_values Array with `dim_values_length` elements. On return, filled with the dimensions stored in the ::OrtTensorTypeAndShapeInfo + * \param[in] dim_values_length Number of elements in `dim_values`. Use OrtApi::GetDimensionsCount to get this value + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetDimensions, _In_ const OrtTensorTypeAndShapeInfo* info, _Out_ int64_t* dim_values, + size_t dim_values_length); + + /** \brief Get symbolic dimension names in ::OrtTensorTypeAndShapeInfo + * + * \param[in] info + * \param[in] dim_params Array with `dim_params_length` elements. On return filled with pointers to null terminated strings of the dimension names + * \param[in] dim_params_length Number of elements in `dim_params`. Use OrtApi::GetDimensionsCount to get this value + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetSymbolicDimensions, _In_ const OrtTensorTypeAndShapeInfo* info, + _Out_writes_all_(dim_params_length) const char* dim_params[], size_t dim_params_length); + + /** \brief Get total number of elements in a tensor shape from an ::OrtTensorTypeAndShapeInfo + * + * Return the number of elements specified by the tensor shape (all dimensions multiplied by each other). + * For 0 dimensions, 1 is returned. If any dimension is less than 0, the result is always -1. + * + * Examples:
+ * [] = 1
+ * [1,3,4] = 12
+ * [2,0,4] = 0
+ * [-1,3,4] = -1
+ * + * \param[in] info + * \param[out] out Number of elements + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetTensorShapeElementCount, _In_ const OrtTensorTypeAndShapeInfo* info, _Out_ size_t* out); + + /// @} + /// \name OrtValue + /// @{ + + /** \brief Get type and shape information from a tensor ::OrtValue + * + * \param[in] value Must be a tensor (not a map/sequence/etc) or will return failure + * \param[out] out Newly created ::OrtTensorTypeAndShapeInfo. Must be freed with OrtApi::ReleaseTensorTypeAndShapeInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetTensorTypeAndShape, _In_ const OrtValue* value, _Outptr_ OrtTensorTypeAndShapeInfo** out); + + /** \brief Get type information of an OrtValue + * + * \param[in] value + * \param[out] out Newly created ::OrtTypeInfo. Must be freed with OrtApi::ReleaseTypeInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetTypeInfo, _In_ const OrtValue* value, _Outptr_result_maybenull_ OrtTypeInfo** out); + + /** \brief Get ONNXType of an ::OrtValue + * + * \param[in] value + * \param[out] out + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetValueType, _In_ const OrtValue* value, _Out_ enum ONNXType* out); + + /// @} + /// \name OrtMemoryInfo + /// @{ + + /** \brief Create an ::OrtMemoryInfo + * + * \param[in] name + * \param[in] type + * \param[in] id + * \param[in] mem_type + * \param[out] out Newly created ::OrtMemoryInfo. Must be freed with OrtAPi::ReleaseMemoryInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateMemoryInfo, _In_ const char* name, enum OrtAllocatorType type, int id, + enum OrtMemType mem_type, _Outptr_ OrtMemoryInfo** out); + + /** \brief Create an ::OrtMemoryInfo for CPU memory + * + * Special case version of OrtApi::CreateMemoryInfo for CPU based memory. Same as using OrtApi::CreateMemoryInfo with name = "Cpu" and id = 0. + * + * \param[in] type + * \param[in] mem_type + * \param[out] out + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateCpuMemoryInfo, enum OrtAllocatorType type, enum OrtMemType mem_type, + _Outptr_ OrtMemoryInfo** out); + + /** \brief Compare ::OrtMemoryInfo objects for equality + * + * Compares all settings of each ::OrtMemoryInfo for equality + * + * \param[in] info1 + * \param[in] info2 + * \param[out] out Set to 0 if equal, -1 if not equal + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CompareMemoryInfo, _In_ const OrtMemoryInfo* info1, _In_ const OrtMemoryInfo* info2, _Out_ int* out); + + /** \brief Get name from ::OrtMemoryInfo + * + * \param[in] ptr + * \param[out] out Writes null terminated string to this pointer. Do NOT free the returned pointer. It is valid for the lifetime of the ::OrtMemoryInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(MemoryInfoGetName, _In_ const OrtMemoryInfo* ptr, _Out_ const char** out); + + /** \brief Get the id from ::OrtMemoryInfo + */ + ORT_API2_STATUS(MemoryInfoGetId, _In_ const OrtMemoryInfo* ptr, _Out_ int* out); + + /** \brief Get the ::OrtMemType from ::OrtMemoryInfo + */ + ORT_API2_STATUS(MemoryInfoGetMemType, _In_ const OrtMemoryInfo* ptr, _Out_ OrtMemType* out); + + /** \brief Get the ::OrtAllocatorType from ::OrtMemoryInfo + */ + ORT_API2_STATUS(MemoryInfoGetType, _In_ const OrtMemoryInfo* ptr, _Out_ OrtAllocatorType* out); + + /// @} + /// \name OrtAllocator + /// @{ + + /// \brief Calls OrtAllocator::Alloc function + ORT_API2_STATUS(AllocatorAlloc, _Inout_ OrtAllocator* ort_allocator, size_t size, _Outptr_ void** out); + /// \brief Calls OrtAllocator::Free function + ORT_API2_STATUS(AllocatorFree, _Inout_ OrtAllocator* ort_allocator, void* p); + /// \brief Calls OrtAllocator::Info function + ORT_API2_STATUS(AllocatorGetInfo, _In_ const OrtAllocator* ort_allocator, _Outptr_ const struct OrtMemoryInfo** out); + + /** \brief Get the default allocator + * + * The default allocator is a CPU based, non-arena. Always returns the same pointer to the same default allocator. + * + * \param[out] out Returned value should NOT be freed + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetAllocatorWithDefaultOptions, _Outptr_ OrtAllocator** out); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Override session symbolic dimensions + * + * Override symbolic dimensions (by specific denotation strings) with actual values if known at session initialization time to enable + * optimizations that can take advantage of fixed values (such as memory planning, etc) + * + * \param[in] options + * \param[in] dim_denotation + * \param[in] dim_value + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(AddFreeDimensionOverride, _Inout_ OrtSessionOptions* options, _In_ const char* dim_denotation, + _In_ int64_t dim_value); + + /// @} + /// \name OrtValue + /// @{ + + /* Internal information (not seen in Doxygen) + * + * APIs to support non-tensor types - map and sequence. + * Currently only the following types are supported + * Note: the following types should be kept in sync with data_types.h + * Map types + * ========= + * std::map + * std::map + * std::map + * std::map + * std::map + * std::map + * std::map + * std::map + * + * Sequence types + * ============== + * std::vector + * std::vector + * std::vector + * std::vector + * std::vector> + * std::vector + */ + + /** \brief Get non tensor data from an ::OrtValue + * + * If `value` is of type ONNX_TYPE_MAP, you need to retrieve the keys and values + * separately. Use index=0 to retrieve keys and index=1 to retrieve values. + * If `value` is of type ONNX_TYPE_SEQUENCE, use index to retrieve the index'th element + * of the sequence. + * + * \param[in] value + * \param[in] index See above for usage based on `value` type + * \param[in] allocator Allocator used to allocate ::OrtValue + * \param[out] out Created ::OrtValue that holds the element requested. Must be freed with OrtApi::ReleaseValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetValue, _In_ const OrtValue* value, int index, _Inout_ OrtAllocator* allocator, + _Outptr_ OrtValue** out); + + /** \brief Get non tensor value count from an ::OrtValue + * + * If `value` is of type ONNX_TYPE_MAP 2 will always be returned. For ONNX_TYPE_SEQUENCE + * the number of elements in the sequence will be returned + * + * \param[in] value + * \param[out] out + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetValueCount, _In_ const OrtValue* value, _Out_ size_t* out); + + /** \brief Create a map or sequence ::OrtValue + * + * To construct a map (ONNX_TYPE_MAP), use num_values = 2 and `in` should be an array of 2 ::OrtValue%s + * representing keys and values.
+ * + * To construct a sequence (ONNX_TYPE_SEQUENCE), use num_values = N where N is the number of the elements in the + * sequence. 'in' should be an array of N ::OrtValue%s. + * + * \param[in] in See above for details + * \param[in] num_values + * \param[in] value_type Must be either ONNX_TYPE_MAP or ONNX_TYPE_SEQUENCE + * \param[out] out Newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateValue, _In_reads_(num_values) const OrtValue* const* in, size_t num_values, + enum ONNXType value_type, _Outptr_ OrtValue** out); + + /** \brief Create an opaque (custom user defined type) ::OrtValue + * + * Constructs an ::OrtValue that contains a value of non-standard type created for + * experiments or while awaiting standardization. ::OrtValue in this case would contain + * an internal representation of the Opaque type. Opaque types are distinguished from + * each other by two strings 1) domain and 2) type name. The combination of the two + * must be unique, so the type representation is properly identified internally. The combination + * must be properly registered from within ORT at both compile/run time or by another API. + * + * To construct the ::OrtValue pass domain and type names, also a pointer to a data container + * the type of which must be known to both ORT and the client program. That data container may or may + * not match the internal representation of the Opaque type. The sizeof(data_container) is passed for + * verification purposes. + * + * \param[in] domain_name Null terminated string of the domain name + * \param[in] type_name Null terminated string of the type name + * \param[in] data_container User pointer Data to populate ::OrtValue + * \param[in] data_container_size Size in bytes of what `data_container` points to + * \param[out] out Newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateOpaqueValue, _In_z_ const char* domain_name, _In_z_ const char* type_name, + _In_ const void* data_container, size_t data_container_size, _Outptr_ OrtValue** out); + + /** \brief Get internal data from an opaque (custom user defined type) ::OrtValue + * + * Copies internal data from an opaque value into a user provided buffer + * + * \see OrtApi::CreateOpaqueValue + * + * \param[in] domain_name Null terminated string of the domain name + * \param[in] type_name Null terminated string of the type name + * \param[in] in The opaque ::OrtValue + * \param[out] data_container Buffer to copy data into + * \param[out] data_container_size Size in bytes of the buffer pointed to by data_container. Must match the size of the internal buffer. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetOpaqueValue, _In_ const char* domain_name, _In_ const char* type_name, _In_ const OrtValue* in, + _Out_ void* data_container, size_t data_container_size); + + /// @} + /// \name OrtKernelInfo + /// Custom operator APIs. + /// @{ + + /** \brief Get a float stored as an attribute in the graph node + * + * \param[in] info ::OrtKernelInfo instance + * \param[in] name Null terminated string of the name of the attribute + * \param[out] out Pointer to memory where the attribute will be stored + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelInfoGetAttribute_float, _In_ const OrtKernelInfo* info, _In_ const char* name, + _Out_ float* out); + + /** \brief Fetch a 64-bit int stored as an attribute in the graph node + * + * \param[in] info ::OrtKernelInfo instance + * \param[in] name Null terminated string of the name of the attribute + * \param[out] out Pointer to memory where the attribute will be stored + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelInfoGetAttribute_int64, _In_ const OrtKernelInfo* info, _In_ const char* name, + _Out_ int64_t* out); + + /** \brief Fetch a string stored as an attribute in the graph node + * + * If `out` is nullptr, the value of `size` is set to the true size of the string + * attribute, and a success status is returned. + * + * If the `size` parameter is greater than or equal to the actual string attribute's size, + * the value of `size` is set to the true size of the string attribute, the provided memory + * is filled with the attribute's contents, and a success status is returned. + * + * If the `size` parameter is less than the actual string attribute's size and `out` + * is not nullptr, the value of `size` is set to the true size of the string attribute + * and a failure status is returned.) + * + * \param[in] info ::OrtKernelInfo instance + * \param[in] name Null terminated string of the name of the attribute + * \param[out] out Pointer to memory where the attribute will be stored + * \param[in,out] size See above comments for details + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelInfoGetAttribute_string, _In_ const OrtKernelInfo* info, _In_ const char* name, _Out_ char* out, + _Inout_ size_t* size); + + /// @} + /// \name OrtKernelContext + /// Custom operator APIs. + /// @{ + + /** \brief Used for custom operators, get the input count of a kernel + * + * \see ::OrtCustomOp + */ + ORT_API2_STATUS(KernelContext_GetInputCount, _In_ const OrtKernelContext* context, _Out_ size_t* out); + + /** \brief Used for custom operators, get the output count of a kernel + * + * \see ::OrtCustomOp + */ + ORT_API2_STATUS(KernelContext_GetOutputCount, _In_ const OrtKernelContext* context, _Out_ size_t* out); + + /** \brief Used for custom operators, get an input of a kernel + * + * The function attempts fetches the input of the kernel. If the input is optional + * and not present, the function returns success and out is set to nullptr. + * + * \param[in] context ::OrtKernelContext instance + * \param[in] index See KernelContext_GetInputCount for boundaries check. + * \param[out] out OrtValue if the input is present otherwise is set nullptr + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelContext_GetInput, _In_ const OrtKernelContext* context, _In_ size_t index, + _Out_ const OrtValue** out); + + /** \brief Used for custom operators, get an output of a kernel + * + * The function attempts fetches the output of the kernel. If the output is optional + * and not present, the function returns success and out is set to nullptr. + * + * \param[in] context ::OrtKernelContext instance + * \param[in] index See KernelContext_GetOutputCount for boundaries check. + * \param[in] dim_values output dimensions + * \param[in] dim_count number of dimensions + * \param[out] out a ptr to OrtValue to output otherwise set to nullptr + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelContext_GetOutput, _Inout_ OrtKernelContext* context, _In_ size_t index, + _In_ const int64_t* dim_values, size_t dim_count, _Outptr_ OrtValue** out); + + /// @} + /// \name OrtEnv + /// @{ + ORT_CLASS_RELEASE(Env); + /// @} + /// \name OrtStatus + /// @{ + ORT_CLASS_RELEASE(Status); + /// @} + /// \name OrtMemoryInfo + /// @{ + ORT_CLASS_RELEASE(MemoryInfo); + /// @} + /// \name OrtSession + /// @{ + ORT_CLASS_RELEASE(Session); // Don't call ReleaseSession from Dllmain (because session owns a thread pool) + /// @} + /// \name OrtValue + /// @{ + ORT_CLASS_RELEASE(Value); + /// @} + /// \name OrtRunOptions + /// @{ + ORT_CLASS_RELEASE(RunOptions); + /// @} + /// \name OrtTypeInfo + /// @{ + ORT_CLASS_RELEASE(TypeInfo); + /// @} + /// \name OrtTensorTypeAndShapeInfo + /// @{ + ORT_CLASS_RELEASE(TensorTypeAndShapeInfo); + /// @} + /// \name OrtSessionOptions + /// @{ + ORT_CLASS_RELEASE(SessionOptions); + /// @} + /// \name OrtCustomOpDomain + /// @{ + ORT_CLASS_RELEASE(CustomOpDomain); + + /// @} + /// \name OrtTypeInfo + /// @{ + + /** \brief Get denotation from type information + * + * Augments ::OrtTypeInfo to return denotations on the type. + * + * This is used by WinML to determine if an input/output is intended to be an Image or a Tensor. + * + * \param[in] type_info + * \param[out] denotation Pointer to the null terminated denotation string is written to this pointer. This pointer is valid until the object is destroyed or the name is changed, do not free. + * \param[out] len Length in bytes of the string returned in `denotation` + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetDenotationFromTypeInfo, _In_ const OrtTypeInfo* type_info, _Out_ const char** const denotation, + _Out_ size_t* len); + + /** \brief Get detailed map information from an ::OrtTypeInfo + * + * This augments ::OrtTypeInfo to return an ::OrtMapTypeInfo when the type is a map. + * The OrtMapTypeInfo has additional information about the map's key type and value type. + * + * This is used by WinML to support model reflection APIs. + * + * \param[out] type_info + * \param[out] out A pointer to the ::OrtMapTypeInfo. Do not free this value. If type_info + * does not contain a map, this value will be set to nullptr. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CastTypeInfoToMapTypeInfo, _In_ const OrtTypeInfo* type_info, + _Outptr_result_maybenull_ const OrtMapTypeInfo** out); + + /** \brief Cast ::OrtTypeInfo to an ::OrtSequenceTypeInfo + * + * This api augments ::OrtTypeInfo to return an ::OrtSequenceTypeInfo when the type is a sequence. + * The ::OrtSequenceTypeInfo has additional information about the sequence's element type. + * + * This is used by WinML to support model reflection APIs. + * + * \param[in] type_info + * \param[out] out A pointer to the OrtSequenceTypeInfo. Do not free this value. If type_info + * doesn not contain a sequence, this value will be set to nullptr. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CastTypeInfoToSequenceTypeInfo, _In_ const OrtTypeInfo* type_info, + _Outptr_result_maybenull_ const OrtSequenceTypeInfo** out); + + /// @} + /// \name OrtMapTypeInfo + /// @{ + + /** \brief Get key type from an ::OrtMapTypeInfo + * + * Key types are restricted to being scalar types. + * + * This is used by WinML to support model reflection APIs. + * + * \param[in] map_type_info + * \param[out] out + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetMapKeyType, _In_ const OrtMapTypeInfo* map_type_info, _Out_ enum ONNXTensorElementDataType* out); + + /** \brief Get the value type from an ::OrtMapTypeInfo + * + * \param[in] map_type_info + * \param[out] type_info A copy of the OrtTypeInfo for the map value type. + * The user must free this value with ReleaseTypeInfo. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetMapValueType, _In_ const OrtMapTypeInfo* map_type_info, _Outptr_ OrtTypeInfo** type_info); + + /// @} + /// \name OrtSequenceTypeInfo + /// @{ + + /** \brief Get element type from an ::OrtSequenceTypeInfo + * + * This is used by WinML to support model reflection APIs. + * + * \param[in] sequence_type_info + * \param[out] type_info A copy of the OrtTypeInfo for the sequence element type. + * The user must free this value with ReleaseTypeInfo. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetSequenceElementType, _In_ const OrtSequenceTypeInfo* sequence_type_info, + _Outptr_ OrtTypeInfo** type_info); + + /// @} + /// \name OrtMapTypeInfo + /// @{ + ORT_CLASS_RELEASE(MapTypeInfo); + /// @} + /// \name OrtSequenceTypeInfo + /// @{ + ORT_CLASS_RELEASE(SequenceTypeInfo); + + /// @} + /// \name OrtSession + /// @{ + + /** \brief End profiling and return filename of the profile data + * + * Profiling is turned on through OrtApi::EnableProfiling + * + * \param[in] session + * \param[in] allocator + * \param[out] out Null terminated string of the filename, allocated using `allocator`. Must be freed using `allocator` + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionEndProfiling, _In_ OrtSession* session, _Inout_ OrtAllocator* allocator, _Outptr_ char** out); + + /** \brief Get ::OrtModelMetadata from an ::OrtSession + * + * \param[in] session + * \param[out] out Newly created ::OrtModelMetadata. Must be freed using OrtApi::ReleaseModelMetadata + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetModelMetadata, _In_ const OrtSession* session, _Outptr_ OrtModelMetadata** out); + + /// @} + /// \name OrtModelMetadata + /// @{ + + /** \brief Get `producer name` from an ::OrtModelMetadata + * + * \param[in] model_metadata + * \param[in] allocator + * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ModelMetadataGetProducerName, _In_ const OrtModelMetadata* model_metadata, + _Inout_ OrtAllocator* allocator, _Outptr_ char** value); + + /** \brief Get `graph name` from an ::OrtModelMetadata + * + * \param[in] model_metadata + * \param[in] allocator + * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ModelMetadataGetGraphName, _In_ const OrtModelMetadata* model_metadata, + _Inout_ OrtAllocator* allocator, _Outptr_ char** value); + + /** \brief Get `domain` from an ::OrtModelMetadata + * + * \param[in] model_metadata + * \param[in] allocator + * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ModelMetadataGetDomain, _In_ const OrtModelMetadata* model_metadata, _Inout_ OrtAllocator* allocator, + _Outptr_ char** value); + + /** \brief Get `description` from an ::OrtModelMetadata + * + * \param[in] model_metadata + * \param[in] allocator + * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ModelMetadataGetDescription, _In_ const OrtModelMetadata* model_metadata, + _Inout_ OrtAllocator* allocator, _Outptr_ char** value); + + /** \brief Return data for a key in the custom metadata map in an ::OrtModelMetadata + * + * \param[in] model_metadata + * \param[in] allocator + * \param[in] key Null terminated string + * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` + * `value` will be set to nullptr if the given key is not found in the custom metadata map. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ModelMetadataLookupCustomMetadataMap, _In_ const OrtModelMetadata* model_metadata, + _Inout_ OrtAllocator* allocator, _In_ const char* key, _Outptr_result_maybenull_ char** value); + + /** \brief Get version number from an ::OrtModelMetadata + * + * \param[in] model_metadata + * \param[out] value Set to the version number + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ModelMetadataGetVersion, _In_ const OrtModelMetadata* model_metadata, _Out_ int64_t* value); + + ORT_CLASS_RELEASE(ModelMetadata); + + /// @} + /// \name OrtEnv + /// @{ + + /** \brief Create an OrtEnv + * + * Create an environment with global threadpools that will be shared across sessions. + * Use this in conjunction with OrtApi::DisablePerSessionThreads or else the session will use + * its own thread pools. + * + * \param[in] log_severity_level The log severity level. + * \param[in] logid The log identifier. + * \param[in] tp_options + * \param[out] out Returned newly created OrtEnv. Must be freed with OrtApi::ReleaseEnv + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateEnvWithGlobalThreadPools, OrtLoggingLevel log_severity_level, _In_ const char* logid, + _In_ const OrtThreadingOptions* tp_options, _Outptr_ OrtEnv** out); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Use global thread pool on a session + * + * Disable using per session thread pool and use the shared global threadpool. + * This should be used in conjunction with OrtApi::CreateEnvWithGlobalThreadPools. + * + * \param[in] options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(DisablePerSessionThreads, _Inout_ OrtSessionOptions* options); + + /// @} + /// \name OrtThreadingOptions + /// @{ + + /** \brief Create an ::OrtThreadingOptions + * + * \param[out] out Newly created ::OrtThreadingOptions. Must be freed with OrtApi::ReleaseThreadingOptions + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateThreadingOptions, _Outptr_ OrtThreadingOptions** out); + + ORT_CLASS_RELEASE(ThreadingOptions); + + /// @} + /// \name OrtModelMetadata + /// @{ + + /** + * + * \param[in] model_metadata + * \param[in] allocator + * \param[out] keys Array of null terminated strings (array count = num_keys) allocated using `allocator`. + * The strings and the pointer array must be freed using `allocator` + * `keys` will be set to nullptr if the custom metadata map is empty. + * \param[out] num_keys Set to the number of elements in the `keys` array + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ModelMetadataGetCustomMetadataMapKeys, _In_ const OrtModelMetadata* model_metadata, + _Inout_ OrtAllocator* allocator, _Outptr_result_buffer_maybenull_(*num_keys) char*** keys, _Out_ int64_t* num_keys); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** + * + * Override symbolic dimensions (by specific name strings) with actual values + * if known at session initialization time to enable optimizations that can + * take advantage of fixed values (such as memory planning, etc) + * + */ + ORT_API2_STATUS(AddFreeDimensionOverrideByName, + _Inout_ OrtSessionOptions* options, _In_ const char* dim_name, + _In_ int64_t dim_value); + + /// @} + /// \name Misc + /// @{ + + /** \brief Get the names of all available providers + * + * \note The providers in the list are not guaranteed to be usable. They may fail to load due to missing system dependencies. + * For example, if the CUDA/cuDNN libraries are not installed, the CUDA provider will report an error when it is added to the session options. + * + * \param[out] out_ptr Set to a pointer to an array of null terminated strings of the available providers. The entries and the + * array itself must be freed using OrtApi::ReleaseAvailableProviders + * \param[out] provider_length Set to the number of entries in the `out_ptr` array + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetAvailableProviders, _Outptr_ char*** out_ptr, _Out_ int* provider_length); + + /** \brief Release data from OrtApi::GetAvailableProviders. This API will never fail + * so you can rely on it in a noexcept code. + * + * \param[in] ptr The `out_ptr` result from OrtApi::GetAvailableProviders. + * \param[in] providers_length The `provider_length` result from OrtApi::GetAvailableProviders + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ReleaseAvailableProviders, _In_ char** ptr, + _In_ int providers_length); + + /// @} + /// \name OrtValue + /// @{ + + /** \brief Get the length of a single string in a string tensor + * + * \param[in] value A string tensor + * \param[in] index Index of the string in the tensor + * \param[out] out Set to number of bytes of the string element + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetStringTensorElementLength, _In_ const OrtValue* value, size_t index, _Out_ size_t* out); + + /** \brief Get a single string from a string tensor + * + * \param[in] value A string tensor + * \param[in] s_len Number of bytes in the `s` buffer. Must match the value returned by OrtApi::GetStringTensorElementLength. + * \param[in] index Index of the string in the tensor + * \param[out] s The string element contents in UTF-8 encoding. The string is NOT null-terminated. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetStringTensorElement, _In_ const OrtValue* value, size_t s_len, size_t index, _Out_writes_bytes_all_(s_len) void* s); + + /** \brief Set a single string in a string tensor + * + * \param[in] value A string tensor + * \param[in] s A null terminated UTF-8 encoded string + * \param[in] index Index of the string in the tensor to set + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(FillStringTensorElement, _Inout_ OrtValue* value, _In_ const char* s, size_t index); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Set a session configuration entry as a pair of strings + * + * If a configuration with same key exists, this will overwrite the configuration with the given config_value. + * + * The config_key and the format of config_value are defined in onnxruntime_session_options_config_keys.h + * + * \param[in] options + * \param[in] config_key A null terminated string representation of the config key + * \param[in] config_value A null terminated string representation of the config value + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(AddSessionConfigEntry, _Inout_ OrtSessionOptions* options, + _In_z_ const char* config_key, _In_z_ const char* config_value); + + /// @} + /// \name OrtAllocator + /// @{ + + /** \brief Create an allocator for an ::OrtSession following an ::OrtMemoryInfo + * + * \param[in] session + * \param[in] mem_info valid ::OrtMemoryInfo instance + * \param[out] out Newly created ::OrtAllocator. Must be freed with OrtApi::ReleaseAllocator + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateAllocator, _In_ const OrtSession* session, _In_ const OrtMemoryInfo* mem_info, + _Outptr_ OrtAllocator** out); + + /** \brief Release an ::OrtAllocator obtained from OrtApi::CreateAllocator + */ + ORT_CLASS_RELEASE(Allocator); + + /// @} + /// \name OrtSession + /// @{ + + /** \brief Run a model using Io Bindings for the inputs & outputs + * + * \see OrtApi::Run + * + * \param[in] session + * \param[in] run_options + * \param[in] binding_ptr + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(RunWithBinding, _Inout_ OrtSession* session, _In_ const OrtRunOptions* run_options, _In_ const OrtIoBinding* binding_ptr); + + /** \brief Create an ::OrtIoBinding instance + * + * An IoBinding object allows one to bind pre-allocated ::OrtValue%s to input names. + * Thus if you want to use a raw on device buffer as input or output you can avoid + * extra copy during runtime. + * + * \param[in] session + * \param[out] out Newly created ::OrtIoBinding. Must be freed with OrtApi::ReleaseIoBinding + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateIoBinding, _Inout_ OrtSession* session, _Outptr_ OrtIoBinding** out); + + /// @} + /// \name OrtIoBinding + /// @{ + + /** \brief Release an ::OrtIoBinding obtained from OrtApi::CreateIoBinding + */ + ORT_CLASS_RELEASE(IoBinding); + + /** \brief Bind an ::OrtValue to an ::OrtIoBinding input + * + * When using OrtApi::RunWithBinding this value is used for the named input + * + * \param[in] binding_ptr + * \param[in] name Name for the model input + * \param[in] val_ptr ::OrtValue of Tensor type. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(BindInput, _Inout_ OrtIoBinding* binding_ptr, _In_ const char* name, _In_ const OrtValue* val_ptr); + + /** \brief Bind an ::OrtValue to an ::OrtIoBinding output + * + * When using OrtApi::RunWithBinding this value is used for the named output + * + * \param[in] binding_ptr + * \param[in] name Null terminated string of the model output name + * \param[in] val_ptr ::OrtValue of Tensor type. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(BindOutput, _Inout_ OrtIoBinding* binding_ptr, _In_ const char* name, _In_ const OrtValue* val_ptr); + + /** \brief Bind an ::OrtIoBinding output to a device + * + * Binds the ::OrtValue to a device which is specified by ::OrtMemoryInfo. + * You can either create an instance of ::OrtMemoryInfo with a device id or obtain one from the allocator that you have created/are using + * This is useful when one or more outputs have dynamic shapes and, it is hard to pre-allocate and bind a chunk of + * memory within ::OrtValue ahead of time. + * + * \see OrtApi::RunWithBinding + * + * \param[in] binding_ptr + * \param[in] name Null terminated string of the device name + * \param[in] mem_info_ptr + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(BindOutputToDevice, _Inout_ OrtIoBinding* binding_ptr, _In_ const char* name, _In_ const OrtMemoryInfo* mem_info_ptr); + + /** \brief Get the names of an ::OrtIoBinding's outputs + * + * Returns the names of the outputs in the order they were bound. This is useful after running the model + * with bound outputs because the returned names are in order in which output ::OrtValue are returned. This is useful if + * the order of outputs and their names is not known. + * + * \param[in] binding_ptr + * \param[in] allocator Allocator used to allocate continuous buffers for output strings and lengths. + * \param[out] buffer Returns an array of non-null terminated UTF-8 strings. The number of strings stored is returned in the count parameter. + * This buffer is allocated using `allocator` and must be freed using it. + * \param[out] lengths Returns an array of `count` lengths of the strings returned in `buffer` + * This buffer is allocated using `allocator` and must be freed using it. + * \param[out] count Number of strings returned. If `binding_ptr` has no bound outputs, zero is returned, + * no memory allocation is performed and buffer and lengths are set to nullptr. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetBoundOutputNames, _In_ const OrtIoBinding* binding_ptr, _In_ OrtAllocator* allocator, + _Out_ char** buffer, _Out_writes_all_(count) size_t** lengths, _Out_ size_t* count); + + /** \brief Get the output ::OrtValue objects from an ::OrtIoBinding + * + * Returns an array of pointers to individually allocated ::OrtValue%s that contain results of a model execution with OrtApi::RunWithBinding + * The array contains the same number of ::OrtValue%s and they are in the same order as they were bound with OrtApi::BindOutput + * or OrtApi::BindOutputToDevice. + * + * The returned ::OrtValue%s must be released using OrtApi::ReleaseValue after they are no longer needed. + * The array is allocated using the specified instance of the allocator and must be freed using the same allocator after + * all the ::OrtValue%s contained therein are individually released. + * + * \param[in] binding_ptr + * \param[in] allocator Allocator used to allocate output array + * \param[out] output Set to the allocated array of allocated ::OrtValue outputs. Set to nullptr if there are 0 outputs. + * \param[out] output_count Set to number of ::OrtValue%s returned + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetBoundOutputValues, _In_ const OrtIoBinding* binding_ptr, _In_ OrtAllocator* allocator, + _Out_writes_all_(output_count) OrtValue*** output, _Out_ size_t* output_count); + + /** \brief Clears any previously set Inputs for an ::OrtIoBinding + */ + void(ORT_API_CALL* ClearBoundInputs)(_Inout_ OrtIoBinding* binding_ptr) NO_EXCEPTION ORT_ALL_ARGS_NONNULL; + + /** \brief Clears any previously set Outputs for an ::OrtIoBinding + */ + void(ORT_API_CALL* ClearBoundOutputs)(_Inout_ OrtIoBinding* binding_ptr) NO_EXCEPTION ORT_ALL_ARGS_NONNULL; + + /// @} + /// \name OrtValue + /// @{ + + /** \brief Direct memory access to a specified tensor element + * + * For example, given a tensor with shape of [3,224,224], a pointer to the element at location [2,150,128] can be retrieved + * + * This function only works for numeric type tensors (No strings, etc). + * This is a no-copy method whose returned pointer is valid until the passed in ::OrtValue is free'd. + * + * \param[in] value + * \param[in] location_values Pointer to an array of index values that specify an element's location relative to its shape + * \param[in] location_values_count Number of elements in location_values. Must match the number of elements in the tensor's shape. + * \param[out] out Set to a pointer to the element specified + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(TensorAt, _Inout_ OrtValue* value, const int64_t* location_values, size_t location_values_count, _Outptr_ void** out); + + /// @} + /// \name OrtEnv + /// @{ + + /** \brief Create an allocator and register it with the ::OrtEnv + * + * Enables sharing the allocator between multiple sessions that use the same env instance. + * Lifetime of the created allocator will be valid for the duration of the environment. + * Returns an error if an allocator with the same ::OrtMemoryInfo is already registered. + * + * See https://onnxruntime.ai/docs/get-started/with-c.html for details. + * + * \param[in] env ::OrtEnv instance + * \param[in] mem_info + * \param[in] arena_cfg Pass nullptr for defaults + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateAndRegisterAllocator, _Inout_ OrtEnv* env, _In_ const OrtMemoryInfo* mem_info, + _In_ const OrtArenaCfg* arena_cfg); + + /** \brief Set language projection + * + * Set the language projection for collecting telemetry data when Env is created. + * + * The default is ORT_PROJECTION_C, which means it will classify the language not in the list to C also. + * + * \param[in] ort_env + * \param[in] projection + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetLanguageProjection, _In_ const OrtEnv* ort_env, _In_ OrtLanguageProjection projection); + + /// @} + /// \name OrtSession + /// @{ + + /** \brief Return the time that profiling was started + * + * \note The timer precision varies per platform. On Windows and MacOS, the precision will be ~100ns + * + * \param[in] session + * \param[out] out nanoseconds of profiling's start time + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetProfilingStartTimeNs, _In_ const OrtSession* session, _Outptr_ uint64_t* out); + + /// @} + /// \name OrtThreadingOptions + /// @{ + + /** \brief Set global intra-op thread count + * + * This configures the global thread pool options to be used in the call to OrtApi::CreateEnvWithGlobalThreadPools + * + * \param[in] tp_options + * \param[in] intra_op_num_threads Number of threads, special values:
+ * 0 = Use default thread count
+ * 1 = The invoking thread will be used; no threads will be created in the thread pool. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetGlobalIntraOpNumThreads, _Inout_ OrtThreadingOptions* tp_options, int intra_op_num_threads); + + /** \brief Set global inter-op thread count + * + * This configures the global thread pool options to be used in the call to OrtApi::CreateEnvWithGlobalThreadPools + * + * \param[in] tp_options + * \param[in] inter_op_num_threads Number of threads, special values:
+ * 0 = Use default thread count
+ * 1 = The invoking thread will be used; no threads will be created in the thread pool. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetGlobalInterOpNumThreads, _Inout_ OrtThreadingOptions* tp_options, int inter_op_num_threads); + + /** \brief Set global spin control options + * + * This will configure the global thread pool options to be used in the call to OrtApi::CreateEnvWithGlobalThreadPools. + * Allow spinning of thread pools when their queues are empty. This will set the value for both + * inter_op and intra_op threadpools. + * + * \param[in] tp_options + * \param[in] allow_spinning Valid values are 0 or 1.
+ * 0 = It won't spin (recommended if CPU usage is high)
+ * 1 = Threadpool will spin to wait for queue to become non-empty + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetGlobalSpinControl, _Inout_ OrtThreadingOptions* tp_options, int allow_spinning); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Add a pre-allocated initializer to a session + * + * If a model contains an initializer with a name that is same as the name passed to this call, + * ORT will use this initializer instance instead of deserializing one from the model file. This + * is useful when you want to share the same initializer across sessions. + * + * \param[in] options + * \param[in] name Null terminated string of the initializer name + * \param[in] val ::OrtValue containing the initializer. Its lifetime and the underlying initializer buffer must be + * managed by the user (created using the OrtApi::CreateTensorWithDataAsOrtValue) and it must outlive the session object + * to which it is added. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(AddInitializer, _Inout_ OrtSessionOptions* options, _In_z_ const char* name, + _In_ const OrtValue* val); + + /// @} + /// \name OrtEnv + /// @{ + + /** + * Create a custom environment with global threadpools and logger that will be shared across sessions. + * Use this in conjunction with OrtApi::DisablePerSessionThreads or else the session will use + * its own thread pools. + * + * \param[in] logging_function A pointer to a logging function. + * \param[in] logger_param A pointer to arbitrary data passed as the ::OrtLoggingFunction `param` parameter to + * `logging_function`. + * \param[in] log_severity_level The log severity level. + * \param[in] logid The log identifier. + * \param[in] tp_options + * \param[out] out Newly created OrtEnv. Must be freed with OrtApi::ReleaseEnv + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateEnvWithCustomLoggerAndGlobalThreadPools, OrtLoggingFunction logging_function, _In_opt_ void* logger_param, OrtLoggingLevel log_severity_level, + _In_ const char* logid, _In_ const struct OrtThreadingOptions* tp_options, _Outptr_ OrtEnv** out); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Append CUDA provider to session options + * + * If CUDA is not available (due to a non CUDA enabled build, or if CUDA is not installed on the system), this function will return failure. + * + * \param[in] options + * \param[in] cuda_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_CUDA, + _In_ OrtSessionOptions* options, _In_ const OrtCUDAProviderOptions* cuda_options); + + /** \brief Append ROCM execution provider to the session options + * + * If ROCM is not available (due to a non ROCM enabled build, or if ROCM is not installed on the system), this function will return failure. + * + * \param[in] options + * \param[in] rocm_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_ROCM, + _In_ OrtSessionOptions* options, _In_ const OrtROCMProviderOptions* rocm_options); + + /** \brief Append OpenVINO execution provider to the session options + * + * If OpenVINO is not available (due to a non OpenVINO enabled build, or if OpenVINO is not installed on the system), this function will fail. + * + * \param[in] options + * \param[in] provider_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_OpenVINO, + _In_ OrtSessionOptions* options, _In_ const OrtOpenVINOProviderOptions* provider_options); + + /// @} + /// \name OrtThreadingOptions + /// @{ + + /** \brief Set threading flush-to-zero and denormal-as-zero + * + * Sets global thread pool options to be used in the call to OrtApi::CreateEnvWithGlobalThreadPools. + * Flush-to-zero and denormal-as-zero are applied to threads in both intra and inter global thread pool. + * \note This option is not needed if the models used have no denormals. Having no denormals is recommended as this option may hurt model accuracy. + * + * \param[in] tp_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetGlobalDenormalAsZero, _Inout_ OrtThreadingOptions* tp_options); + + /// @} + /// \name OrtArenaCfg + /// @{ + + /** \deprecated Use OrtApi::CreateArenaCfgV2 + * + * This will create the configuration of an arena that can eventually be used to define an arena based allocator's behavior + * + * \param[in] max_mem Use 0 to allow ORT to choose the default + * \param[in] arena_extend_strategy Use -1 to allow ORT to choose the default, 0 = kNextPowerOfTwo, 1 = kSameAsRequested + * \param[in] initial_chunk_size_bytes Use -1 to allow ORT to choose the default + * \param[in] max_dead_bytes_per_chunk Use -1 to allow ORT to choose the default + * \param[in] out A pointer to an OrtArenaCfg instance + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateArenaCfg, _In_ size_t max_mem, int arena_extend_strategy, int initial_chunk_size_bytes, + int max_dead_bytes_per_chunk, _Outptr_ OrtArenaCfg** out); + + ORT_CLASS_RELEASE(ArenaCfg); + + /// @} + /// \name OrtModelMetadata + /// @{ + + /** + * Use this to obtain the description of the graph present in the model + * (doc_string field of the GraphProto message within the ModelProto message). + * If it doesn't exist, an empty string will be returned. + * + * \param[in] model_metadata An instance of ::OrtModelMetadata + * \param[in] allocator Allocator used to allocate the string that will be returned back + * \param[out] value Set to a null terminated string allocated using `allocator`. The caller is responsible for freeing it using `allocator` + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ModelMetadataGetGraphDescription, _In_ const OrtModelMetadata* model_metadata, + _Inout_ OrtAllocator* allocator, _Outptr_ char** value); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Append TensorRT provider to session options + * + * If TensorRT is not available (due to a non TensorRT enabled build, or if TensorRT is not installed on the system), this function will return failure. + * + * \param[in] options + * \param[in] tensorrt_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_TensorRT, + _In_ OrtSessionOptions* options, _In_ const OrtTensorRTProviderOptions* tensorrt_options); + + /// @} + /// \name Misc + /// @{ + + /** \brief Set current GPU device ID + * + * Set the current device id of the GPU execution provider (CUDA/tensorrt/rocm). The device id should be less + * than the total number of devices available. This is only useful when multiple-GPUs are installed and it is + * required to restrict execution to a single GPU. + * + * \param[in] device_id + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetCurrentGpuDeviceId, _In_ int device_id); + + /** \brief Get current GPU device ID + * + * Get the current device id of the GPU execution provider (CUDA/tensorrt/rocm). + * + * \see OrtApi::SetCurrentGpuDeviceId + * + * \param[out] device_id + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetCurrentGpuDeviceId, _In_ int* device_id); + + /// @} + /// \name OrtKernelInfo + /// Custom operator APIs. + /// @{ + + /** \brief Fetch an array of int64_t values stored as an attribute in the graph node + * + * + * If `out` is nullptr, the value of `size` is set to the true size of the attribute + * array's size, and a success status is returned. + * + * If the `size` parameter is greater than or equal to the actual attribute array's size, + * the value of `size` is set to the true size of the attribute array's size, + * the provided memory is filled with the attribute's contents, + * and a success status is returned. + * + * If the `size` parameter is less than the actual attribute array's size and `out` + * is not nullptr, the value of `size` is set to the true size of the attribute array's size + * and a failure status is returned.) + * + * \param[in] info instance + * \param[in] name name of the attribute to be parsed + * \param[out] out pointer to memory where the attribute's contents are to be stored + * \param[in, out] size actual size of attribute array + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelInfoGetAttributeArray_float, _In_ const OrtKernelInfo* info, _In_ const char* name, + _Out_ float* out, _Inout_ size_t* size); + + /** \brief Fetch an array of int64_t values stored as an attribute in the graph node + * + * If `out` is nullptr, the value of `size` is set to the true size of the attribute + * array's size, and a success status is returned. + * + * If the `size` parameter is greater than or equal to the actual attribute array's size, + * the value of `size` is set to the true size of the attribute array's size, + * the provided memory is filled with the attribute's contents, + * and a success status is returned. + * + * If the `size` parameter is less than the actual attribute array's size and `out` + * is not nullptr, the value of `size` is set to the true size of the attribute array's size + * and a failure status is returned.) + * + * \param[in] info instance + * \param[in] name name of the attribute to be parsed + * \param[out] out pointer to memory where the attribute's contents are to be stored + * \param[in, out] size actual size of attribute array + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelInfoGetAttributeArray_int64, _In_ const OrtKernelInfo* info, _In_ const char* name, + _Out_ int64_t* out, _Inout_ size_t* size); + + /// @} + /// \name OrtArenaCfg + /// @{ + + /** \brief Create an ::OrtArenaCfg + * + * Create the configuration of an arena that can eventually be used to define an arena based allocator's behavior. + * + * Supported keys are (See https://onnxruntime.ai/docs/get-started/with-c.html for details on what the + * following parameters mean and how to choose these values.): + * "max_mem": Maximum memory that can be allocated by the arena based allocator. + * Use 0 for ORT to pick the best value. Default is 0. + * "arena_extend_strategy": 0 = kNextPowerOfTwo, 1 = kSameAsRequested. + * Use -1 to allow ORT to choose the default. + * "initial_chunk_size_bytes": (Possible) Size of the first allocation in the arena. + * Only relevant if arena strategy is `kNextPowerOfTwo`. Use -1 to allow ORT to choose the default. + * Ultimately, the first allocation size is determined by the allocation memory request. + * "max_dead_bytes_per_chunk": Threshold of unused memory in an allocated chunk of arena memory after + * crossing which the current chunk is chunked into 2. + * "initial_growth_chunk_size_bytes": (Possible) Size of the second allocation in the arena. + * Only relevant if arena strategy is `kNextPowerOfTwo`. Use -1 to allow ORT to choose the default. + * "max_power_of_two_extend_bytes": The maximum enxtend size if arena strategy is `kNextPowerOfTwo`. + * It is not an allocation limit, it is only a limit for extension when requested byte is less than the limit. + * When requested bytes is more than the limit, allocator will still return as requested. + * Use -1 to allow ORT to choose the default 1GB for max_power_of_two_extend_bytes. + * Ultimately, the allocation size is determined by the allocation memory request. + * Further allocation sizes are governed by the arena extend strategy. + * + * \param[in] arena_config_keys Keys to configure the arena + * \param[in] arena_config_values Values to configure the arena + * \param[in] num_keys Number of keys in `arena_config_keys` and `arena_config_values` + * \param[out] out Newly created ::OrtArenaCfg. Must be freed with OrtApi::ReleaseArenaCfg + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateArenaCfgV2, _In_reads_(num_keys) const char* const* arena_config_keys, + _In_reads_(num_keys) const size_t* arena_config_values, _In_ size_t num_keys, + _Outptr_ OrtArenaCfg** out); + + /// @} + /// \name OrtRunOptions + /// @{ + + /** \brief Set a single run configuration entry as a pair of strings + * + * If a configuration with same key exists, this will overwrite the configuration with the given config_value + * + * The config_key and the format of config_value are defined in onnxruntime_run_options_config_keys.h + * + * \param[in] options + * \param[in] config_key A null terminated string representation of the config key + * \param[in] config_value A null terminated string representation of the config value + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(AddRunConfigEntry, _Inout_ OrtRunOptions* options, + _In_z_ const char* config_key, _In_z_ const char* config_value); + + /// @} + /// \name OrtPrepackedWeightsContainer + /// @{ + + /** \brief Create an ::OrtPrepackedWeightsContainer + * + * This container will hold pre-packed buffers of shared initializers for sharing between sessions + * (i.e.) if there are shared initializers that can be shared between sessions, the pre-packed buffers + * of these (if any) may possibly be shared to provide memory footprint savings. Pass this container + * to sessions that you would like to share pre-packed buffers of shared initializers at session + * creation time. + * + * \param[out] out Newly created ::OrtPrepackedWeightsContainer. Must be freed with OrtApi::ReleasePrepackedWeightsContainer + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreatePrepackedWeightsContainer, _Outptr_ OrtPrepackedWeightsContainer** out); + + /** \brief Release OrtPrepackedWeightsContainer instance + * + * \note instance must not be released until the sessions using it are released + */ + ORT_CLASS_RELEASE(PrepackedWeightsContainer); + + /// @} + /// \name OrtSession + /// @{ + + /** \brief Create session with prepacked weights container + * + * Same functionality offered by OrtApi::CreateSession except that a container that contains + * pre-packed weights' buffers is written into/read from by the created session. + * This is useful when used in conjunction with OrtApi::AddInitializer which injects + * shared initializer info into sessions. Wherever possible, the pre-packed versions of these + * shared initializers are cached in this container so that multiple sessions can just re-use + * these instead of duplicating these in memory. + * + * \param[in] env OrtEnv instance instance + * \param[in] model_path Null terminated string of the path (wchar on Windows, char otherwise) + * \param[in] options + * \param[in] prepacked_weights_container + * \param[out] out Newly created ::OrtSession. Must be freed with OrtApi::ReleaseSession + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateSessionWithPrepackedWeightsContainer, _In_ const OrtEnv* env, _In_ const ORTCHAR_T* model_path, + _In_ const OrtSessionOptions* options, + _Inout_ OrtPrepackedWeightsContainer* prepacked_weights_container, + _Outptr_ OrtSession** out); + + /** \brief Create session from memory with prepacked weights container + * + * Same functionality offered by OrtApi::CreateSessionFromArray except that a container that contains + * pre-packed weights' buffers is written into/read from by the created session. + * This is useful when used in conjunction with OrtApi::AddInitializer which injects + * shared initializer info into sessions. Wherever possible, the pre-packed versions of these + * shared initializers are cached in this container so that multiple sessions can just re-use + * these instead of duplicating these in memory. + * + * \param[in] env + * \param[in] model_data Array of bytes holding the model + * \param[in] model_data_length Number of bytes in `model_data_model` + * \param[in] options + * \param[in] prepacked_weights_container + * \param[out] out Newly created ::OrtSession. Must be freed with OrtApi::ReleaseSession + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateSessionFromArrayWithPrepackedWeightsContainer, _In_ const OrtEnv* env, + _In_ const void* model_data, size_t model_data_length, + _In_ const OrtSessionOptions* options, + _Inout_ OrtPrepackedWeightsContainer* prepacked_weights_container, + _Outptr_ OrtSession** out); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Append TensorRT execution provider to the session options + * + * If TensorRT is not available (due to a non TensorRT enabled build), this function will return failure. + * + * This is slightly different from OrtApi::SessionOptionsAppendExecutionProvider_TensorRT, it takes an + * ::OrtTensorRTProviderOptions which is publicly defined. This takes an opaque ::OrtTensorRTProviderOptionsV2 + * which must be created with OrtApi::CreateTensorRTProviderOptions. + * + * For OrtApi::SessionOptionsAppendExecutionProvider_TensorRT, the user needs to instantiate ::OrtTensorRTProviderOptions + * as well as allocate/release buffers for some members of ::OrtTensorRTProviderOptions. + * Here, OrtApi::CreateTensorRTProviderOptions and Ortapi::ReleaseTensorRTProviderOptions will do the memory management for you. + * + * \param[in] options + * \param[in] tensorrt_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_TensorRT_V2, + _In_ OrtSessionOptions* options, _In_ const OrtTensorRTProviderOptionsV2* tensorrt_options); + + /// @} + /// \name OrtTensorRTProviderOptionsV2 + /// @{ + + /** \brief Create an OrtTensorRTProviderOptionsV2 + * + * \param[out] out Newly created ::OrtTensorRTProviderOptionsV2. Must be released with OrtApi::ReleaseTensorRTProviderOptions + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateTensorRTProviderOptions, _Outptr_ OrtTensorRTProviderOptionsV2** out); + + /** \brief Set options in a TensorRT Execution Provider. + * + * Please refer to https://onnxruntime.ai/docs/execution-providers/TensorRT-ExecutionProvider.html#cc + * to know the available keys and values. Key should be in null terminated string format of the member of ::OrtTensorRTProviderOptionsV2 + * and value should be its related range. Recreates the options and only sets the supplied values. + * + * For example, key="trt_max_workspace_size" and value="2147483648" + * + * \param[in] tensorrt_options + * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys + * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values + * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(UpdateTensorRTProviderOptions, _Inout_ OrtTensorRTProviderOptionsV2* tensorrt_options, + _In_reads_(num_keys) const char* const* provider_options_keys, + _In_reads_(num_keys) const char* const* provider_options_values, + _In_ size_t num_keys); + + /** \brief Get serialized TensorRT provider options string. + * + * For example, "trt_max_workspace_size=2147483648;trt_max_partition_iterations=10;trt_int8_enable=1;......" + * + * \param tensorrt_options - OrtTensorRTProviderOptionsV2 instance + * \param allocator - a ptr to an instance of OrtAllocator obtained with OrtApi::CreateAllocator or OrtApi::GetAllocatorWithDefaultOptions + * the specified allocator will be used to allocate continuous buffers for output strings and lengths. + * \param ptr - is a UTF-8 null terminated string allocated using 'allocator'. The caller is responsible for using the same allocator to free it. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetTensorRTProviderOptionsAsString, _In_ const OrtTensorRTProviderOptionsV2* tensorrt_options, _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); + + /** \brief Release an ::OrtTensorRTProviderOptionsV2 + * + * \note This is an exception in the naming convention of other Release* functions, as the name of the method does not have the V2 suffix, but the type does + */ + void(ORT_API_CALL* ReleaseTensorRTProviderOptions)(_Frees_ptr_opt_ OrtTensorRTProviderOptionsV2* input); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Enable custom operators + * + * See onnxruntime-extensions: https://github.com/microsoft/onnxruntime-extensions.git + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(EnableOrtCustomOps, _Inout_ OrtSessionOptions* options); + + /// @} + /// \name OrtAllocator + /// @{ + + /** \brief Register a custom allocator + * + * Enables sharing between multiple sessions that use the same env instance. + * Returns an error if an allocator with the same ::OrtMemoryInfo is already registered. + * + * The behavior of this is exactly the same as OrtApi::CreateAndRegisterAllocator except + * instead of ORT creating an allocator based on provided info, in this case + * ORT uses the user-provided custom allocator. + * See https://onnxruntime.ai/docs/get-started/with-c.html for details. + * + * \param[in] env + * \param[in] allocator User provided allocator + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(RegisterAllocator, _Inout_ OrtEnv* env, _In_ OrtAllocator* allocator); + + /** \brief Unregister a custom allocator + * + * It is an error if you provide an ::OrtMemoryInfo not corresponding to any + * registered allocators for sharing. + * + * \param[in] env + * \param[in] mem_info + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(UnregisterAllocator, _Inout_ OrtEnv* env, + _In_ const OrtMemoryInfo* mem_info); + + /// @} + /// \name OrtValue + /// @{ + + /** \brief Sets *out to 1 iff an ::OrtValue is a SparseTensor, and 0 otherwise + * + * \param[in] value existing ::OrtValue + * \param[out] out unless an error occurs, contains 1 iff the value contains an instance + * of sparse tensor or 0 otherwise. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(IsSparseTensor, _In_ const OrtValue* value, _Out_ int* out); + + /** \brief Create an ::OrtValue with a sparse tensor that is empty. + * + * Use FillSparseTensor() functions to populate sparse tensor with non-zero values and + * format specific indices data. + * Use ReleaseValue to destroy the sparse tensor, this will also release the buffer inside the output value + * if any was allocated. + * \param[in,out] allocator allocator to use when performing an allocation. Allocation will be performed + * by FillSparseTensor() APIs. The lifespan of the allocator instance must eclipse the lifespan + * this sparse tensor instance as the same allocator will be used to free memory. + * \param[in] dense_shape shape of the original dense tensor + * \param[in] dense_shape_len number of shape dimensions being passed + * \param[in] type must be one of TENSOR_ELEMENT_DATA_TYPE_xxxx + * \param[out] out Should be freed by calling ReleaseValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateSparseTensorAsOrtValue, _Inout_ OrtAllocator* allocator, _In_ const int64_t* dense_shape, + size_t dense_shape_len, ONNXTensorElementDataType type, _Outptr_ OrtValue** out); + + /** + * This fills populates an empty tensor that was created using OrtApi::CreateSparseTensorAsOrtValue. + * This will allocate required memory and copy the supplied NNZ values and COO indices into that memory allocation. + * Memory allocation is performed using the allocator that was specified with OrtApi::CreateSparseTensorAsOrtValue. + * + * \param[in,out] ort_value ::OrtValue to populate with data + * \param[in] data_mem_info serves to identify the location of the data to be copied. If the allocator specified + * at the creation time has memory info that is not the same as mem_info argument to this function a X-device copy will be performed. + * String data is assumed to be on CPU and will only be copied into a CPU allocated buffer. + * \param[in] values_shape pointer to values shape array + * \param[in] values_shape_len length of the values_shape + * \param[in] values pointer to an array of values. For strings, pass const char**. + * \param[in] indices_data pointer to a location of COO indices + * \param[in] indices_num number of COO indices + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(FillSparseTensorCoo, _Inout_ OrtValue* ort_value, _In_ const OrtMemoryInfo* data_mem_info, + _In_ const int64_t* values_shape, size_t values_shape_len, _In_ const void* values, + _In_ const int64_t* indices_data, size_t indices_num); + + /** + * This fills populates an empty tensor that was created using OrtApi::CreateSparseTensorAsOrtValue. + * This will allocate required memory and copy the supplied NNZ values and CSR indices into that memory allocation. + * Memory allocation is performed using the allocator that was specified with OrtApi::CreateSparseTensorAsOrtValue. + * + * \param[in,out] ort_value ::OrtValue to populate with data + * \param[in] data_mem_info serves to identify the location of the data to be copied. If the allocator specified + * at the creation time has memory info that is not the same as mem_info argument to this function a X-device copy will be performed. + * String data is assumed to be on CPU and will only be copied into a CPU allocated buffer. + * \param[in] values_shape pointer to values shape array + * \param[in] values_shape_len length of the values_shape + * \param[in] values - pointer to an array of values. For strings, pass const char**. + * \param[in] inner_indices_data pointer to a location of CSR inner indices + * \param[in] inner_indices_num number of CSR inner indices + * \param[in] outer_indices_data pointer to a location of CSR outer indices + * \param[in] outer_indices_num number of CSR outer indices + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(FillSparseTensorCsr, _Inout_ OrtValue* ort_value, _In_ const OrtMemoryInfo* data_mem_info, + _In_ const int64_t* values_shape, size_t values_shape_len, _In_ const void* values, + _In_ const int64_t* inner_indices_data, size_t inner_indices_num, + _In_ const int64_t* outer_indices_data, size_t outer_indices_num); + + /** + * This fills populates an empty tensor that was created using OrtApi::CreateSparseTensorAsOrtValue. + * This will allocate required memory and copy the supplied NNZ values and BlockSparse indices into that memory allocation. + * Memory allocation is performed using the allocator that was specified with OrtApi::CreateSparseTensorAsOrtValue. + * + * \param[in,out] ort_value ::OrtValue to populate with data + * \param[in] data_mem_info serves to identify the location of the data to be copied. If the allocator specified + * at the creation time has memory info that is not the same as mem_info argument to this function a X-device copy will be performed. + * String data is assumed to be on CPU and will only be copied into a CPU allocated buffer. + * \param[in] values_shape + * \param[in] values_shape_len + * \param[in] values structure with values information + * \param[in] indices_shape_data pointer to a location of indices shape + * \param[in] indices_shape_len length of the block sparse indices shape + * \param[in] indices_data pointer to a location of indices data. Shape will determine the length of the indices data. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(FillSparseTensorBlockSparse, _Inout_ OrtValue* ort_value, _In_ const OrtMemoryInfo* data_mem_info, + _In_ const int64_t* values_shape, size_t values_shape_len, _In_ const void* values, + _In_ const int64_t* indices_shape_data, size_t indices_shape_len, + _In_ const int32_t* indices_data); + + /** + * Create an ::OrtValue with a sparse tensor. This is the first step. + * Next, use UseIndices() functions to supply sparse tensor with + * format specific indices data and set its sparse format to a specific enum value. + * This will not perform memory allocations. It will + * use supplied user buffer which should outlive the created sparse tensor. + * Use OrtApi::ReleaseValue to destroy the sparse tensor. It would not release the supplied values buffer. + * This function can not be used to map strings from the user allocated memory. Strings must always be copied + * and have UTF-8 encoding. Therefore, use OrtApi::CreateSparseTensorAsOrtValue above and then fill it with data + * using appropriate Make*() function. + * + * \param[in] info memory info where sparse values reside. + * \param[in,out] p_data pointer to a user allocated buffer with values. To create a full sparse tensor with no non-zero + * values, pass nullptr + * \param[in] dense_shape shape of the original dense tensor + * \param[in] dense_shape_len number of shape dimensions being passed + * \param[in] values_shape shape of the values data. To create a fully sparse tensor with no non-zero values, + * pass {0} shape. + * \param[in] values_shape_len number of values shape dimensions + * \param[in] type must be one of TENSOR_ELEMENT_DATA_TYPE_xxxx + * \param[out] out Should be freed by calling ReleaseValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateSparseTensorWithValuesAsOrtValue, _In_ const OrtMemoryInfo* info, _Inout_ void* p_data, + _In_ const int64_t* dense_shape, size_t dense_shape_len, + _In_ const int64_t* values_shape, size_t values_shape_len, + ONNXTensorElementDataType type, _Outptr_ OrtValue** out); + + /** + * This assigns Coo format indices to the SparseTensor that was created by + * OrtApi::CreateSparseTensorWithValuesAsOrtValue above. It also sets OrtSparseFormat to + * ORT_SPARSE_COO. This will not allocate any additional memory for data. The life span of + * indices_data buffer should eclipse the life span of this ::OrtValue. + * + * \param[in,out] ort_value ::OrtValue instance constructed with OrtApi::CreateSparseTensorWithValuesAsOrtValue + * \param[in,out] indices_data pointer to a user pre-allocated buffer or nullptr for fully sparse tensors. + * \param[in] indices_num number of COO indices. Should either be 0 for fully sparse tensors, be equal + * to the number of nnz values specified to OrtApi::CreateSparseTensorWithValuesAsOrtValue for 1-D {nnz} indices or + * be twice as number of nnz values for a 2-D indices {nnz, 2} + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(UseCooIndices, _Inout_ OrtValue* ort_value, _Inout_ int64_t* indices_data, size_t indices_num); + + /** + * The assigns CSR format indices to the SparseTensor that was created by + * OrtApi::CreateSparseTensorWithValuesAsOrtValue above. It also sets OrtSparseFormat to + * ORT_SPARSE_CSRC. This will not allocate any additional memory for data. The life spans of + * inner_data and outer_data buffers should eclipse the life span of this ::OrtValue. + * + * \param[in,out] ort_value ::OrtValue instance constructed with OrtApi::CreateSparseTensorWithValuesAsOrtValue + * \param[in,out] inner_data pointer to a user pre-allocated buffer or nullptr for fully sparse tensors. + * \param[in] inner_num number of inner CSR indices. Should either be 0 for fully sparse tensors or be equal + * to the number of nnz values specified to OrtApi::CreateSparseTensorWithValuesAsOrtValue. + * \param[in,out] outer_data pointer to user pre-allocated buffer or nullptr for fully sparse tensors. + * \param[in] outer_num number of CSR outer indices. Should either be 0 for fully sparse tensors or + * equal to rows + 1 of the dense shape. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(UseCsrIndices, _Inout_ OrtValue* ort_value, _Inout_ int64_t* inner_data, size_t inner_num, + _Inout_ int64_t* outer_data, size_t outer_num); + + /** + * The assigns BlockSparse format indices to the SparseTensor that was created by + * OrtApi::CreateSparseTensorWithValuesAsOrtValue above. It also sets OrtSparseFormat to + * ORT_SPARSE_BLOCK_SPARSE. This will not allocate any additional memory for data. The life span of + * indices_data buffer must eclipse the lifespan of this ::OrtValue. + * + * \param[in,out] ort_value OrtValue instance constructed with OrtApi::CreateSparseTensorWithValuesAsOrtValue + * \param[in] indices_shape pointer to indices shape. Use {0} for fully sparse tensors + * \param[in] indices_shape_len length of the indices shape + * \param[in,out] indices_data pointer to user pre-allocated buffer or nullptr for fully sparse tensors. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(UseBlockSparseIndices, _Inout_ OrtValue* ort_value, const int64_t* indices_shape, size_t indices_shape_len, _Inout_ int32_t* indices_data); + + /** \brief Returns sparse tensor format enum iff a given ort value contains an instance of sparse tensor. + * + * \param[in] ort_value ::OrtValue that contains an instance of sparse tensor + * \param[out] out pointer to out parameter + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetSparseTensorFormat, _In_ const OrtValue* ort_value, _Out_ enum OrtSparseFormat* out); + + /** \brief Returns data type and shape of sparse tensor values (nnz) iff ::OrtValue contains a SparseTensor. + * + * \param[in] ort_value An ::OrtValue that contains a fully constructed sparse tensor + * \param[out] out Must be freed by OrtApi::ReleaseTensorTypeAndShapeInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetSparseTensorValuesTypeAndShape, _In_ const OrtValue* ort_value, _Outptr_ OrtTensorTypeAndShapeInfo** out); + + /** \brief Returns numeric data for sparse tensor values (nnz). For string values use GetStringTensor*(). + * + * \param[in] ort_value an instance of ::OrtValue containing sparse tensor + * \param[out] out returns a pointer to values data. Do not attempt to free this ptr. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetSparseTensorValues, _In_ const OrtValue* ort_value, _Outptr_ const void** out); + + /** \brief Returns data type, shape for the type of indices specified by indices_format. + * + * \param[in] ort_value ::OrtValue containing sparse tensor. + * \param[in] indices_format One of the indices formats. It is an error to request a format that the sparse + * tensor does not contain. + * \param[out] out an instance of ::OrtTensorTypeAndShapeInfo. Must be freed by OrtApi::ReleaseTensorTypeAndShapeInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetSparseTensorIndicesTypeShape, _In_ const OrtValue* ort_value, enum OrtSparseIndicesFormat indices_format, _Outptr_ OrtTensorTypeAndShapeInfo** out); + + /** \brief Returns indices data for the type of the indices specified by indices_format + * + * \param[in] ort_value ::OrtValue containing sparse tensor. + * \param[in] indices_format One of the indices formats. It is an error to request a format that the sparse tensor does not contain. + * \param[out] num_indices Pointer to where the number of indices entries is returned + * \param[out] indices Returned pointer to the indices data. Do not free the returned pointer as it refers to internal data owned by the ::OrtValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetSparseTensorIndices, _In_ const OrtValue* ort_value, enum OrtSparseIndicesFormat indices_format, _Out_ size_t* num_indices, _Outptr_ const void** indices); + /// @} + /// \name OrtSessionOptions + /// @{ + + /** + * \brief Sets out to 1 iff an optional type OrtValue has an element, 0 otherwise (OrtValue is None) + * Use this API to find if the optional type OrtValue is None or not. + * If the optional type OrtValue is not None, use the OrtValue just like any other OrtValue. + * For example, if you get an OrtValue that corresponds to Optional(tensor) and + * if HasValue() returns true, use it as tensor and so on. + + * \param[in] value Input OrtValue. + * \param[out] out indicating if the input OrtValue contains data (1) or if it is a None (0) + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(HasValue, _In_ const OrtValue* value, _Out_ int* out); + + /// @} + /// \name OrtKernelContext + /// Custom operator APIs. + /// @{ + + /** \brief Used for custom operators, gets the GPU compute stream to use to launch the custom a GPU kernel + * \see ::OrtCustomOp + * \param[in] context OrtKernelContext instance + * \param[out] out Returns pointer to a GPU compute stream that can be used to launch the custom GPU kernel. + * If retrieving the GPU compute stream is not relevant (GPU not enabled in the build, kernel partitioned to + * some other EP), then a nullptr is returned as the output param. + * Do not free or mutate the returned pointer as it refers to internal data owned by the underlying session. + * Only use it for custom kernel launching. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelContext_GetGPUComputeStream, _In_ const OrtKernelContext* context, _Outptr_ void** out); + + /// @} + /// \name GetTensorMemoryInfo + /// @{ + /** \brief Returns a pointer to the ::OrtMemoryInfo of a Tensor + * \param[in] value ::OrtValue containing tensor. + * \param[out] mem_info ::OrtMemoryInfo of the tensor. Do NOT free the returned pointer. It is valid for the lifetime of the ::OrtValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetTensorMemoryInfo, _In_ const OrtValue* value, _Out_ const OrtMemoryInfo** mem_info); + + /// @} + /// \name GetExecutionProviderApi + /// @{ + /** \brief Get a pointer to the requested version of the Execution Provider specific + * API extensions to the OrtApi + * \param[in] provider_name The name of the execution provider name. Currently only the following + * values are supported: "DML". + * \param[in] version Must be ::ORT_API_VERSION. + * \param[out] provider_api A void pointer containing a reference to the execution provider versioned api structure. + * For example, the provider_api pointer can be cast to the OrtDmlApi* when the provider_name is "DML". + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetExecutionProviderApi, _In_ const char* provider_name, _In_ uint32_t version, _Outptr_ const void** provider_api); + + /// @} + + /// \name SessionOptions + /// @{ + /** \brief Set custom thread creation function + * + * \param[in] options Session options + * \param[in] ort_custom_create_thread_fn Custom thread creation function + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionOptionsSetCustomCreateThreadFn, _Inout_ OrtSessionOptions* options, _In_ OrtCustomCreateThreadFn ort_custom_create_thread_fn); + + /** \brief Set creation options for custom thread + * + * \param[in] options Session options + * \param[in] ort_custom_thread_creation_options Custom thread creation options (can be nullptr) + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionOptionsSetCustomThreadCreationOptions, _Inout_ OrtSessionOptions* options, _In_ void* ort_custom_thread_creation_options); + + /** \brief Set custom thread join function + * + * \param[in] options Session options + * \param[in] ort_custom_join_thread_fn Custom join thread function, must not be nullptr when ort_custom_create_thread_fn is set + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionOptionsSetCustomJoinThreadFn, _Inout_ OrtSessionOptions* options, _In_ OrtCustomJoinThreadFn ort_custom_join_thread_fn); + /// @} + + /// \name OrtThreadingOptions + /// @{ + /** \brief Set custom thread creation function for global thread pools + * + * \param[inout] tp_options + * \param[in] ort_custom_create_thread_fn Custom thread creation function + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetGlobalCustomCreateThreadFn, _Inout_ OrtThreadingOptions* tp_options, _In_ OrtCustomCreateThreadFn ort_custom_create_thread_fn); + + /** \brief Set custom thread creation options for global thread pools + * + * \param[inout] tp_options + * \param[in] ort_custom_thread_creation_options Custom thread creation options (can be nullptr) + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetGlobalCustomThreadCreationOptions, _Inout_ OrtThreadingOptions* tp_options, _In_ void* ort_custom_thread_creation_options); + + /** \brief Set custom thread join function for global thread pools + * + * \param[inout] tp_options + * \param[in] ort_custom_join_thread_fn Custom thread join function, must not be nullptr when global ort_custom_create_thread_fn is set + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetGlobalCustomJoinThreadFn, _Inout_ OrtThreadingOptions* tp_options, _In_ OrtCustomJoinThreadFn ort_custom_join_thread_fn); + /// @} + + /** \brief Synchronize bound inputs. The call may be necessary for some providers, such as cuda, + * in case the system that allocated bound memory operated on a different stream. However, the + * operation is provider specific and could be a no-op. + * + * \param[inout] binding_ptr + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SynchronizeBoundInputs, _Inout_ OrtIoBinding* binding_ptr); + + /** \brief Synchronize bound outputs. The call may be necessary for some providers, such as cuda, + * in case the system that allocated bound memory operated on a different stream. However, the + * operation is provider specific and could be a no-op. + * + * \param[inout] binding_ptr + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SynchronizeBoundOutputs, _Inout_ OrtIoBinding* binding_ptr); + + /// \name OrtSessionOptions + /// @{ + + /** \brief Append CUDA execution provider to the session options + * + * If CUDA is not available (due to a non CUDA enabled build), this function will return failure. + * + * This is slightly different from OrtApi::SessionOptionsAppendExecutionProvider_CUDA, it takes an + * ::OrtCUDAProviderOptions which is publicly defined. This takes an opaque ::OrtCUDAProviderOptionsV2 + * which must be created with OrtApi::CreateCUDAProviderOptions. + * + * For OrtApi::SessionOptionsAppendExecutionProvider_CUDA, the user needs to instantiate ::OrtCUDAProviderOptions + * as well as allocate/release buffers for some members of ::OrtCUDAProviderOptions. + * Here, OrtApi::CreateCUDAProviderOptions and Ortapi::ReleaseCUDAProviderOptions will do the memory management for you. + * + * \param[in] options + * \param[in] cuda_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.11. + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_CUDA_V2, + _In_ OrtSessionOptions* options, _In_ const OrtCUDAProviderOptionsV2* cuda_options); + + /// @} + /// \name OrtCUDAProviderOptionsV2 + /// @{ + + /** \brief Create an OrtCUDAProviderOptionsV2 + * + * \param[out] out Newly created ::OrtCUDAProviderOptionsV2. Must be released with OrtApi::ReleaseCudaProviderOptions + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.11. + */ + ORT_API2_STATUS(CreateCUDAProviderOptions, _Outptr_ OrtCUDAProviderOptionsV2** out); + + /** \brief Set options in a CUDA Execution Provider. + * + * Please refer to https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html#configuration-options + * to know the available keys and values. Key should be in null terminated string format of the member of ::OrtCUDAProviderOptionsV2 + * and value should be its related range. Recreates the options and only sets the supplied values. + * + * For example, key="device_id" and value="0" + * + * \param[in] cuda_options + * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys + * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values + * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.11. + */ + ORT_API2_STATUS(UpdateCUDAProviderOptions, _Inout_ OrtCUDAProviderOptionsV2* cuda_options, + _In_reads_(num_keys) const char* const* provider_options_keys, + _In_reads_(num_keys) const char* const* provider_options_values, + _In_ size_t num_keys); + + /** + * Get serialized CUDA provider options string. + * + * For example, "device_id=0;arena_extend_strategy=0;......" + * + * \param cuda_options - OrtCUDAProviderOptionsV2 instance + * \param allocator - a ptr to an instance of OrtAllocator obtained with CreateAllocator() or GetAllocatorWithDefaultOptions() + * the specified allocator will be used to allocate continuous buffers for output strings and lengths. + * \param ptr - is a UTF-8 null terminated string allocated using 'allocator'. The caller is responsible for using the same allocator to free it. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.11. + */ + ORT_API2_STATUS(GetCUDAProviderOptionsAsString, _In_ const OrtCUDAProviderOptionsV2* cuda_options, _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); + + /** \brief Release an ::OrtCUDAProviderOptionsV2 + * + * \note This is an exception in the naming convention of other Release* functions, as the name of the method does not have the V2 suffix, but the type does + * + * \since Version 1.11. + */ + void(ORT_API_CALL* ReleaseCUDAProviderOptions)(_Frees_ptr_opt_ OrtCUDAProviderOptionsV2* input); + + /// @} + + /** \brief Append MIGraphX provider to session options + * + * If MIGraphX is not available (due to a non MIGraphX enabled build, or if MIGraphX is not installed on the system), this function will return failure. + * + * \param[in] options + * \param[in] migraphx_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.11. + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_MIGraphX, + _In_ OrtSessionOptions* options, _In_ const OrtMIGraphXProviderOptions* migraphx_options); + + /** \brief Replace initialized Tensors with external data with the data provided in initializers. + * + * The function will find the initialized TensorProtos with external data in the graph with the provided names and + * replace them with the provided tensors. The API verifies that the TensorProto being replaced + * has an external data reference and has the same name, dimensions and data type as its replacement. The replacement + * will occur before any of the optimizations take place. The data will be copied into the graph + * since TensorProto can't refer to the user provided buffers. + * + * Once the model has been loaded, the OrtValue(s) added to SessionOptions instance will be removed + * from the internal SessionOptions copy to save memory, the user provided buffers can then be deallocated + * and the SessionOptions instance that refers to them can be destroyed. + * + * \param[in] options + * \param[in] initializer_names Array of null terminated UTF-8 encoded strings of the initializers names. + * \param[in] initializers Array of ::OrtValue type + * \param[in] num_initializers Number of elements in the initializer_names and initializers + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.12. + */ + ORT_API2_STATUS(AddExternalInitializers, _In_ OrtSessionOptions* options, + _In_reads_(num_initializers) const char* const* initializer_names, + _In_reads_(num_initializers) const OrtValue* const* initializers, size_t num_initializers); + + /** \brief: Create attribute of onnxruntime operator + * + * \param[in] name Name of the attribute + * \param[in] data Data content of the attribute + * \param[in] len Number of bytes stored in data + * \param[in] type Data type + * \param[out] op_attr Attribute that has been created, which must be released by OrtApi::ReleaseOpAttr + * + * \since Version 1.12. + */ + ORT_API2_STATUS(CreateOpAttr, + _In_ const char* name, + _In_ const void* data, + _In_ int len, + _In_ OrtOpAttrType type, + _Outptr_ OrtOpAttr** op_attr); + + /* \brief: Release op attribute + * + * \param[in] opAttr Attribute created by OrtApi::CreateOpAttr + * + * \since Version 1.12. + */ + ORT_CLASS_RELEASE(OpAttr); + + /** \brief: Create onnxruntime native operator + * + * \param[in] info Kernel info + * \param[in] op_name Operator name + * \param[in] domain Operator domain + * \param[in] version Operator opset version + * \param[in] type_constraint_names Name of the type contraints, such as "T" or "T1" + * \param[in] type_constraint_values Type of each contraints + * \param[in] type_constraint_count Number of contraints + * \param[in] attr_values Attributes used to initialize the operator + * \param[in] attr_count Number of the attributes + * \param[in] input_count Number of inputs + * \param[in] output_count Number of outputs + * \param[out] ort_op Operator that has been created + * + * \since Version 1.12. + */ + ORT_API2_STATUS(CreateOp, + _In_ const OrtKernelInfo* info, + _In_z_ const char* op_name, + _In_z_ const char* domain, + int version, + _In_reads_(type_constraint_count) const char** type_constraint_names, + _In_reads_(type_constraint_count) const ONNXTensorElementDataType* type_constraint_values, + int type_constraint_count, + _In_reads_(attr_count) const OrtOpAttr* const* attr_values, + int attr_count, + int input_count, + int output_count, + _Outptr_ OrtOp** ort_op); + + /** \brief: Invoke the operator created by OrtApi::CreateOp + * The inputs must follow the order as specified in onnx specification + * + * \param[in] context Kernel context + * \param[in] ort_op Operator that has been created + * \param[in] input_values Array of inputs + * \param[in] input_count Number of inputs + * \param[in] output_values Array of outputs + * \param[in] output_count Number of outputs + * + * \since Version 1.12. + */ + ORT_API2_STATUS(InvokeOp, + _In_ const OrtKernelContext* context, + _In_ const OrtOp* ort_op, + _In_ const OrtValue* const* input_values, + _In_ int input_count, + _Inout_ OrtValue* const* output_values, + _In_ int output_count); + + /* \brief: Release an onnxruntime operator + * + * \param[in] Op Operator created by OrtApi::CreateOp + * + * \since Version 1.12. + */ + ORT_CLASS_RELEASE(Op); + + /** \brief: Append execution provider to the session options. + * \param[in] options + * \param[in] provider_name - provider to add. + * \param[in] provider_options_keys - keys to configure the provider options + * \param[in] provider_options_values - values to configure the provider options + * \param[in] num_keys - number of keys passed in + * + * Currently supported provider names: + * QNNExecutionProvider (or QNN) + * OpenVINOExecutionProvider (or OpenVINO) + * XnnpackExecutionProvider (or XNNPACK) + * WebNNExecutionProvider (or WEBNN) + * WebGpuExecutionProvider (or WebGPU) + * AzureExecutionProvider (or AZURE) + * JsExecutionProvider (or JS) + * VitisAIExecutionProvider (or VitisAI) + * CoreMLExecutionProvider (or CoreML) + * + * Note: If an execution provider has a dedicated SessionOptionsAppendExecutionProvider_ function + * that should be used to add it. + * + * QNN supported keys: + * "backend_type": Type of QNN backend. Specifies a backend path that is the associated QNN backend library file + * name. E.g., given backend type "htp", on Windows, the backend path would be "QnnHtp.dll", and on other + * platforms, it would be "libQnnHtp.so". Mutually exclusive with "backend_path". + * Available options: + * -# "cpu" + * -# "gpu" + * -# "htp": Default. + * -# "saver" + * "backend_path": File path to QNN backend library. Mutually exclusive with "backend_type". + * "profiling_level": QNN profiling level. + * Available options: + * -# "off": Default. + * -# "basic" + * -# "detailed" + * "profiling_file_path": QNN profiling file path if ETW not enabled. + * "rpc_control_latency": QNN RPC control latency. + * "vtcm_mb": QNN VTCM size in MB. default to 0(not set). + * "htp_performance_mode": QNN performance mode. + * Available options: + * -# "burst" + * -# "balanced" + * -# "default": Default. + * -# "high_performance" + * -# "high_power_saver" + * -# "low_balanced" + * -# "extreme_power_saver" + * -# "low_power_saver" + * -# "power_saver" + * -# "sustained_high_performance" + * "qnn_saver_path": File path to the QNN Saver backend library. If specified, QNN Saver will be enabled and will + * dump QNN API calls to disk for replay/debugging. QNN Saver produces incorrect model inference results and + * may alter model/EP partitioning. Use only for debugging. + * "qnn_context_priority": QNN context priority. + * Available options: + * -# "low" + * -# "normal": Default. + * -# "normal_high" + * -# "high" + * "htp_graph_finalization_optimization_mode": Set the optimization mode for graph finalization on the HTP backend. + * Available options: + * -# "0": Default. + * -# "1": Faster preparation time, less optimal graph. + * -# "2": Longer preparation time, more optimal graph. + * -# "3": Longest preparation time, most likely even more optimal graph. See QNN SDK documentation for specific + * details. + * "soc_model": The SoC model number. Refer to the QNN SDK documentation for valid values. + * Defaults to "0" (unknown). + * "htp_arch": The minimum HTP architecture the driver will use to select compatible QNN operators. + * Available options: + * -# "0": Default (none). + * -# "68" + * -# "69" + * -# "73" + * -# "75" + * "device_id": The ID of the device to use when setting 'htp_arch'. Defaults to "0" (for single device). + * "enable_htp_fp16_precision": Used for float32 model for HTP backend. + * Enable the float32 model to be inferenced with fp16 precision. Otherwise, it will be fp32 precision. + * -# "0": With fp32 precision. + * -# "1": Default. With fp16 precision. + * "offload_graph_io_quantization": Offload graph input quantization and graph output dequantization to another + * execution provider (typically CPU EP). + * -# "0": Disabled. QNN EP will handle quantization and dequantization of graph I/O. + * -# "1": Enabled. This is the default value. + * "enable_htp_spill_fill_buffer": Enable HTP spill fill buffer setting. The flag is used while generating context + * binary. + * -# "0": Default. Disabled. + * -# "1": Enabled. + * "enable_htp_shared_memory_allocator": Enable the QNN HTP shared memory allocator. Requires libcdsprpc.so/dll to + * be available. + * -# "0": Default. Disabled. + * -# "1": Enabled. + * "dump_json_qnn_graph": Set to "1" to dump QNN graphs generated by QNN EP as JSON files. Each graph partition + * assigned to QNN EP is dumped to a separate file. + * "json_qnn_graph_dir": Directory in which to dump QNN JSON graphs. If not specified, QNN graphs are dumped in the + * program's current working directory. Ignored if "dump_json_qnn_graph" is not set. + * + * XNNPACK supported keys: + * "intra_op_num_threads": number of thread-pool size to use for XNNPACK execution provider. + * default value is 0, which means to use the session thread-pool size. + * + * \since Version 1.12. + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider, _In_ OrtSessionOptions* options, + _In_ const char* provider_name, + _In_reads_(num_keys) const char* const* provider_options_keys, + _In_reads_(num_keys) const char* const* provider_options_values, + _In_ size_t num_keys); + + /* \brief: Get a copy of kernel info + * + * \param[in] info Kernel info + * \param[out] info_copy Copy of kernel info + * + * \since Version 1.12. + */ + ORT_API2_STATUS(CopyKernelInfo, + _In_ const OrtKernelInfo* info, + _Outptr_ OrtKernelInfo** info_copy); + + /* \brief: Release kernel info + * + * \param[in] KernelInfo A copy of kernel info returned by CopyKernelInfo + * + * \since Version 1.12. + */ + ORT_CLASS_RELEASE(KernelInfo); + + /// \name Ort Training + /// @{ + /** \brief Gets the Training C Api struct + * + * Call this function to access the ::OrtTrainingApi structure that holds pointers to functions that enable + * training with onnxruntime. + * \note A NULL pointer will be returned and no error message will be printed if the training api + * is not supported with this build. A NULL pointer will be returned and an error message will be + * printed if the provided version is unsupported, for example when using a runtime older than the + * version created with this header file. + * + * \param[in] version Must be ::ORT_API_VERSION + * \return The ::OrtTrainingApi struct for the version requested. + * + * \since Version 1.13 + */ + const OrtTrainingApi*(ORT_API_CALL* GetTrainingApi)(uint32_t version)NO_EXCEPTION; + + /// @} + + /** \brief Append CANN provider to session options + * + * If CANN is not available (due to a non CANN enabled build, or if CANN is not installed on the system), this function will return failure. + * + * \param[in] options + * \param[in] cann_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.13. + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_CANN, + _In_ OrtSessionOptions* options, _In_ const OrtCANNProviderOptions* cann_options); + + /** \brief Create an OrtCANNProviderOptions + * + * \param[out] out created ::OrtCANNProviderOptions. Must be released with OrtApi::ReleaseCANNProviderOptions + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.13. + */ + ORT_API2_STATUS(CreateCANNProviderOptions, _Outptr_ OrtCANNProviderOptions** out); + + /** \brief Set options in a CANN Execution Provider. + * + * \param[in] cann_options + * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys + * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values + * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.13. + */ + ORT_API2_STATUS(UpdateCANNProviderOptions, _Inout_ OrtCANNProviderOptions* cann_options, + _In_reads_(num_keys) const char* const* provider_options_keys, + _In_reads_(num_keys) const char* const* provider_options_values, + _In_ size_t num_keys); + + /** \brief Get serialized CANN provider options string. + * + * \param[in] cann_options OrtCANNProviderOptions instance + * \param[in] allocator a ptr to an instance of OrtAllocator obtained with CreateAllocator() + * or GetAllocatorWithDefaultOptions(), the specified allocator will be used to allocate + * continuous buffers for output strings and lengths. + * \param[out] ptr is a UTF-8 null terminated string allocated using 'allocator'. + * The caller is responsible for using the same allocator to free it. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.13. + */ + ORT_API2_STATUS(GetCANNProviderOptionsAsString, _In_ const OrtCANNProviderOptions* cann_options, + _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); + + /** \brief Release an OrtCANNProviderOptions + * + * \param[in] input The pointer of OrtCANNProviderOptions which will been deleted + * + * \since Version 1.13. + */ + void(ORT_API_CALL* ReleaseCANNProviderOptions)(_Frees_ptr_opt_ OrtCANNProviderOptions* input); + + /* \brief Get OrtDevice type from MemoryInfo + * + * \since Version 1.14 + */ + void(ORT_API_CALL* MemoryInfoGetDeviceType)(_In_ const OrtMemoryInfo* ptr, _Out_ OrtMemoryInfoDeviceType* out); + + /* \brief Update the OrtEnv instance with custom log severity level + * + * \param[in] ort_env The OrtEnv instance being used + * \param[in] log_severity_level The log severity level. + * + * \since Version 1.14. + */ + ORT_API2_STATUS(UpdateEnvWithCustomLogLevel, _In_ OrtEnv* ort_env, OrtLoggingLevel log_severity_level); + + /* \brief Set affinities for intra op threads + * + * Affinity string follows format: + * logical_processor_id,logical_processor_id;logical_processor_id,logical_processor_id + * Semicolon isolates configurations among threads, while comma split processors where ith thread expected to attach to. + * e.g. 1,2,3;4,5 + * specifies affinities for two threads, with the 1st thread attach to the 1st, 2nd, and 3rd processor, and 2nd thread to the 4th and 5th. + * To ease the configuration, an "interval" is also allowed: + * e.g. 1-8;8-16;17-24 + * orders that the 1st thread runs on first eight processors, 2nd thread runs on next eight processors, and so forth. + * Note: + * 1. Once set, the number of thread affinities must equal to intra_op_num_threads - 1, + * ort does not set affinity on the main thread which is started and managed by the calling app; + * 2. For windows, ort will infer the group id from a logical processor id, for example, assuming there are two groups with each has 64 logical processors, + * an id of 64 will be inferred as the last processor of the 1st group, while 65 will be interpreted as the 1st processor of the second group. + * Hence 64-65 is an invalid configuration, because a windows thread cannot be attached to processors across group boundary. + * + * \since Version 1.14 + */ + ORT_API2_STATUS(SetGlobalIntraOpThreadAffinity, _Inout_ OrtThreadingOptions* tp_options, const char* affinity_string); + + /** \brief Register custom ops from a shared library. + * + * Loads a shared library (.dll on windows, .so on linux, etc) named 'library_name' and looks for this entry point: + * OrtStatus* RegisterCustomOps(OrtSessionOptions * options, const OrtApiBase* api); + * It then passes in the provided session options to this function along with the api base. + * + * The handle to the loaded library is automatically released by ORT when the last OrtSession that references the + * library handle is released. If no OrtSession is created, then the library handle is released when the provided + * OrtSessionOptions is released. + * + * \param[in] options The session options. + * \param[in] library_name The name of the shared library to load and register. Refer to OS-specific dynamic library + * loading utilities (e.g., LoadLibraryEx on Windows or dlopen on Linux/MacOS) for information + * on the format of library names and search paths. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(RegisterCustomOpsLibrary_V2, _Inout_ OrtSessionOptions* options, _In_ const ORTCHAR_T* library_name); + + /** \brief Register custom ops by calling a RegisterCustomOpsFn function. + * + * Searches for registration_func_name and if found calls it. + * + * The library containing the function must either be linked against or previously loaded by the executable. + * + * If you want ONNX Runtime to load the library and manage its lifetime, use RegisterCustomOpsLibrary_V2. + * + * RegisterCustomOpsUsingFunction can be used in scenarios where it may not be possible for ONNX Runtime to load + * the library from a path. e.g. mobile platforms where the library must be linked into the app. + * + * The registration function must have the signature of RegisterCustomOpsFn: + * OrtStatus* (*fn)(OrtSessionOptions* options, const OrtApiBase* api); + * + * See https://onnxruntime.ai/docs/reference/operators/add-custom-op.html for details on how the registration + * function should be implemented. + * + * \param[in] options OrtSessionOptions that is passed through as the first argument in the call to the + * registration function. + * \param[in] registration_func_name Name of registration function to use. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(RegisterCustomOpsUsingFunction, _Inout_ OrtSessionOptions* options, + _In_ const char* registration_func_name); + + /// \name OrtKernelInfo + /// Custom operator APIs. + /// @{ + + /** \brief Get the number of inputs from ::OrtKernelInfo. + * + * Used in the CreateKernel callback of an OrtCustomOp to query the number of inputs + * during kernel/session creation. + * + * \param[in] info Instance of ::OrtKernelInfo. + * \param[out] out Pointer to variable assigned with the result on success. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(KernelInfo_GetInputCount, _In_ const OrtKernelInfo* info, _Out_ size_t* out); + + /** \brief Get the number of outputs from ::OrtKernelInfo. + * + * Used in the CreateKernel callback of an OrtCustomOp to query the number of outputs + * during kernel/session creation. + * + * \param[in] info Instance of ::OrtKernelInfo. + * \param[out] out Pointer to variable assigned with the result on success. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(KernelInfo_GetOutputCount, _In_ const OrtKernelInfo* info, _Out_ size_t* out); + + /** \brief Get the name of a ::OrtKernelInfo's input. + * + * Used in the CreateKernel callback of an OrtCustomOp to query an input's name + * during kernel/session creation. + * + * If `out` is nullptr, the value of `size` is set to the size of the name + * string (including null-terminator), and a success status is returned. + * + * If the `size` parameter is greater than or equal to the name string's size, + * the value of `size` is set to the true size of the string (including null-terminator), + * the provided memory is filled with the string's contents, and a success status is returned. + * + * If the `size` parameter is less than the actual string's size and `out` + * is not nullptr, the value of `size` is set to the true size of the string + * and a failure status is returned. + * + * \param[in] info An instance of ::OrtKernelInfo. + * \param[in] index The index of the input name to get. Returns a failure status if out-of-bounds. + * \param[out] out Memory location into which to write the UTF-8 null-terminated string representing the input's name. + * \param[in,out] size Pointer to the size of the `out` buffer. See above comments for details. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(KernelInfo_GetInputName, _In_ const OrtKernelInfo* info, size_t index, _Out_ char* out, + _Inout_ size_t* size); + + /** \brief Get the name of a ::OrtKernelInfo's output. + * + * Used in the CreateKernel callback of an OrtCustomOp to query an output's name + * during kernel/session creation. + * + * If `out` is nullptr, the value of `size` is set to the size of the name + * string (including null-terminator), and a success status is returned. + * + * If the `size` parameter is greater than or equal to the name string's size, + * the value of `size` is set to the true size of the string (including null-terminator), + * the provided memory is filled with the string's contents, and a success status is returned. + * + * If the `size` parameter is less than the actual string's size and `out` + * is not nullptr, the value of `size` is set to the true size of the string + * and a failure status is returned. + * + * \param[in] info An instance of ::OrtKernelInfo. + * \param[in] index The index of the output name to get. Returns a failure status if out-of-bounds. + * \param[out] out Memory location into which to write the UTF-8 null-terminated string representing the output's + * name. + * \param[in,out] size Pointer to the size of the `out` buffer. See above comments for details. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(KernelInfo_GetOutputName, _In_ const OrtKernelInfo* info, size_t index, _Out_ char* out, + _Inout_ size_t* size); + + /** \brief Get the type information for a ::OrtKernelInfo's input. + * + * Used in the CreateKernel callback of an OrtCustomOp to query the shape and type information + * of an input during kernel/session creation. + * + * \param[in] info An instance of ::OrtKernelInfo. + * \param[in] index Which input to get the type information for + * \param[out] type_info Pointer set to the resulting ::OrtTypeInfo. Must be freed with OrtApi::ReleaseTypeInfo. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(KernelInfo_GetInputTypeInfo, _In_ const OrtKernelInfo* info, size_t index, + _Outptr_ OrtTypeInfo** type_info); + + /** \brief Get the type information for a ::OrtKernelInfo's output. + * + * Used in the CreateKernel callback of an OrtCustomOp to query the shape and type information + * of an output during kernel/session creation. + * + * \param[in] info An instance of ::OrtKernelInfo. + * \param[in] index Which input to get the type information for + * \param[out] type_info Pointer set to the resulting ::OrtTypeInfo. Must be freed with OrtApi::ReleaseTypeInfo. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(KernelInfo_GetOutputTypeInfo, _In_ const OrtKernelInfo* info, size_t index, + _Outptr_ OrtTypeInfo** type_info); + + /** \brief Get a ::OrtValue tensor stored as an attribute in the graph node. + * + * Used in the CreateKernel callback of an OrtCustomOp to get a tensor attribute. + * + * \param[in] info ::OrtKernelInfo instance. + * \param[in] name UTF-8 null-terminated string representing the attribute's name. + * \param[in] allocator Allocator used to allocate the internal tensor state. + * \param[out] out Returns newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue, + * which will also free internal tensor state allocated with the provided allocator. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelInfoGetAttribute_tensor, _In_ const OrtKernelInfo* info, _In_z_ const char* name, + _Inout_ OrtAllocator* allocator, _Outptr_ OrtValue** out); + + /// @} + /// \name OrtSessionOptions + /// Custom operator APIs + /// @{ + + /** \brief Checks if the given session configuration entry exists. + * + * The config_key formats are defined in onnxruntime_session_options_config_keys.h + * + * Can be used in a custom operator library to check for session configuration entries + * that target one or more custom operators in the library. Example: The config entry + * custom_op.myop.some_key targets a custom op named "myop". + * + * \param[in] options The ::OrtSessionOptions instance. + * \param[in] config_key A null-terminated UTF-8 string representation of the configuration key. + * \param[out] out Pointer set to 1 if the entry exists and 0 otherwise. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(HasSessionConfigEntry, _In_ const OrtSessionOptions* options, + _In_z_ const char* config_key, _Out_ int* out); + + /** \brief Get a session configuration value. + * + * Returns a failure status if the configuration key does not exist. + * The config_key and the format of config_value are defined in onnxruntime_session_options_config_keys.h + * + * If `config_value` is nullptr, the value of `size` is set to the true size of the string + * value (including null-terminator), and a success status is returned. + * + * If the `size` parameter is greater than or equal to the actual string value's size, + * the value of `size` is set to the true size of the string value, the provided memory + * is filled with the value's contents, and a success status is returned. + * + * If the `size` parameter is less than the actual string value's size and `config_value` + * is not nullptr, the value of `size` is set to the true size of the string value + * and a failure status is returned. + * + * Can be used in a custom operator library to get session configuration entries + * that target one or more custom operators in the library. Example: The config entry + * custom_op.myop.some_key targets a custom op named "myop". + * + * \param[in] options The session options. + * \param[in] config_key A null-terminated UTF-8 string representation of the config key. + * \param[in] config_value Pointer to memory where the null-terminated UTF-8 string value will be stored. + * \param[in,out] size Pointer to the size of the `config_value` buffer. See above comments for details. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(GetSessionConfigEntry, _In_ const OrtSessionOptions* options, + _In_z_ const char* config_key, _Out_ char* config_value, _Inout_ size_t* size); + + /// @} + + /** \brief Append dnnl provider to session options + * + * If oneDNN is not available, this function will return failure. + * + * \param[in] options + * \param[in] dnnl_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.15. + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_Dnnl, + _In_ OrtSessionOptions* options, _In_ const OrtDnnlProviderOptions* dnnl_options); + + /** \brief Create an OrtDnnlProviderOptions + * + * \param[out] out Newly created ::OrtDnnlProviderOptions. Must be released with OrtApi::ReleaseDnnlProviderOptions + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.15. + */ + ORT_API2_STATUS(CreateDnnlProviderOptions, _Outptr_ OrtDnnlProviderOptions** out); + + /** \brief Set options in a oneDNN Execution Provider. + * + * Key should be in null terminated string format of the member of ::OrtDnnlProviderOptions + * and value should be its related range. + * + * For example, key="use_arena" and value="1" + * + * \param[in] dnnl_options + * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys + * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values + * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.15. + */ + ORT_API2_STATUS(UpdateDnnlProviderOptions, _Inout_ OrtDnnlProviderOptions* dnnl_options, + _In_reads_(num_keys) const char* const* provider_options_keys, + _In_reads_(num_keys) const char* const* provider_options_values, + _In_ size_t num_keys); + + /** + * Get serialized oneDNN provider options string. + * + * For example, "use_arena=1;......" + * + * \param dnnl_options - OrtDnnlProviderOptions instance + * \param allocator - a ptr to an instance of OrtAllocator obtained with CreateAllocator() or GetAllocatorWithDefaultOptions() + * the specified allocator will be used to allocate continuous buffers for output strings and lengths. + * \param ptr - is a UTF-8 null terminated string allocated using 'allocator'. The caller is responsible for using the same allocator to free it. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.15. + */ + ORT_API2_STATUS(GetDnnlProviderOptionsAsString, _In_ const OrtDnnlProviderOptions* dnnl_options, _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); + + /** \brief Release an ::OrtDnnlProviderOptions + * + * \since Version 1.15. + */ + void(ORT_API_CALL* ReleaseDnnlProviderOptions)(_Frees_ptr_opt_ OrtDnnlProviderOptions* input); + + /// \name OrtKernelInfo + /// Custom operator APIs. + /// @{ + + /** \brief Get the graph node name from ::OrtKernelInfo. + * + * If `out` is nullptr, the value of `size` is set to the size of the name + * string (including null-terminator), and a success status is returned. + * + * If the `size` parameter is greater than or equal to the name string's size, + * the value of `size` is set to the true size of the string (including null-terminator), + * the provided memory is filled with the string's contents, and a success status is returned. + * + * If the `size` parameter is less than the actual string's size and `out` + * is not nullptr, the value of `size` is set to the true size of the string + * and a failure status is returned. + * + * Can be used in a custom operator's CreateKernel callback to get the name of the operator's node name in the graph. + * + * \param[in] info An instance of ::OrtKernelInfo. + * \param[out] out Memory location into which to write the UTF-8 null-terminated string representing the name. + * \param[in,out] size Pointer to the size of the `out` buffer. See above comments for details. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.15 + */ + ORT_API2_STATUS(KernelInfo_GetNodeName, _In_ const OrtKernelInfo* info, _Out_ char* out, _Inout_ size_t* size); + + /** \brief Get the session logger from ::OrtKernelInfo. + * + * Used in the CreateKernel callback of an OrtCustomOp to get a logger that can be used to log + * messages. + * + * \param[in] info An instance of ::OrtKernelInfo. + * \param[out] logger Pointer set to the session's ::OrtLogger. Owned by ONNX Runtime, so do not free. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.15 + */ + ORT_API2_STATUS(KernelInfo_GetLogger, _In_ const OrtKernelInfo* info, _Outptr_ const OrtLogger** logger); + + /// @} + /// \name OrtKernelContext + /// Custom operator APIs. + /// @{ + + /** \brief Get the runtime logger from ::OrtKernelContext. + * + * Used in the KernelCompute callback of an OrtCustomOp to get a logger that can be used to log + * messages during inference. + * + * \param[in] context An instance of ::OrtKernelContext. + * \param[out] logger Pointer set to the kernel context's ::OrtLogger. Owned by ONNX Runtime, so do not free. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.15 + */ + ORT_API2_STATUS(KernelContext_GetLogger, _In_ const OrtKernelContext* context, _Outptr_ const OrtLogger** logger); + + /// @} + /// \name OrtLogger + /// Custom operator APIs. + /// @{ + + /** \brief Logs a message at the given severity level using the provided ::OrtLogger. + * + * Only messages with a severity level equal or greater than the ::OrtLogger's logging severity level + * are logged. Use OrtApi::Logger_GetLoggingSeverityLevel to get the ::OrtLogger's logging severity + * level. + * + * Can be used in custom operators to log messages with the logger retrieved via OrtApi::KernelInfo_GetLogger. + * + * \param[in] logger The ::OrtLogger instance. + * \param[in] log_severity_level The message's severity level. + * \param[in] message The message to log. + * \param[in] file_path The filepath of the file in which the message is logged. Usually the value of ORT_FILE. + * \param[in] line_number The file line number in which the message is logged. Usually the value of __LINE__. + * \param[in] func_name The name of the function in which the message is logged. Usually the value of __FUNCTION__. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.15 + */ + ORT_API2_STATUS(Logger_LogMessage, _In_ const OrtLogger* logger, OrtLoggingLevel log_severity_level, + _In_z_ const char* message, _In_z_ const ORTCHAR_T* file_path, int line_number, + _In_z_ const char* func_name); + + /** \brief Get the logging severity level of the ::OrtLogger. + * + * Can be used in a custom operator to get the logging serverity level of the ::OrtLogger associated with + * the ::OrtKernelInfo. + * + * \param[in] logger The ::OrtLogger instance. + * \param[out] out Pointer to variable assigned with the logging severity level on success. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.15 + */ + ORT_API2_STATUS(Logger_GetLoggingSeverityLevel, _In_ const OrtLogger* logger, _Out_ OrtLoggingLevel* out); + + /// @} + + /** \brief Get a ::OrtValue tensor stored as a constant initializer in the graph node. + * + * Used in the CreateKernel callback of an OrtCustomOp to get a tensor value. + * + * \param[in] info ::OrtKernelInfo instance. + * \param[in] index The node index. + * \param[out] is_constant Is it a constant node input or not. + * \param[out] out The OrtValue tensor value. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.15. + */ + ORT_API2_STATUS(KernelInfoGetConstantInput_tensor, _In_ const OrtKernelInfo* info, size_t index, _Out_ int* is_constant, _Outptr_ const OrtValue** out); + + /** \brief Get Optional Type information from an ::OrtTypeInfo + * + * This augments ::OrtTypeInfo to return an ::OrtOptionalTypeInfo when the type is optional. + * The OrtOptionalTypeInfo also has a nested ::OrtTypeInfo that describes the type of the optional value. + * ::OrtOptionalTypeInfo type can only appear within model metadata to describe inputs/outputs. + * The actual OrtValues that are supplied in place of optional type inputs should contain + * specific type that is described by ::OrtOptionalTypeInfo. + * + * So the picture: ::OrtTypeInfo -> ::OrtOptionalTypeInfo -> ::OrtTypeInfo (describes the type that can be supplied + * in place of the optional type when creating the actual ::OrtValue). + * + * \param[in] type_info + * \param[out] out A pointer to the ::OrtOptionalTypeInfo. Do not free this value, + * it is owned by OrtTypeInfo instance. When the type_info does not represent + * optional type, nullptr is returned in out. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.15. + */ + ORT_API2_STATUS(CastTypeInfoToOptionalTypeInfo, _In_ const OrtTypeInfo* type_info, + _Outptr_result_maybenull_ const OrtOptionalTypeInfo** out); + + /** \brief Get OrtTypeInfo for the allowed contained type from an ::OrtOptionalTypeInfo. + * + * This augments ::OrtOptionalTypeInfo to return an ::OrtTypeInfo for the contained type. + * The OrtOptionalTypeInfo has a nested ::OrtTypeInfo that describes the type of the optional value. + * ::OrtOptionalTypeInfo type can only appear within model metadata to describe inputs/outputs. + * The actual OrtValues that are supplied in place of optional type inputs should contain + * specific type that is described by the returned ::OrtTypeInfo. + * + * \param[in] optional_type_info + * \param[out] out A copy of ::OrtTypeInfo for what the optional value could be. + * The user must free this value with ReleaseTypeInfo. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.15. + */ + ORT_API2_STATUS(GetOptionalContainedTypeInfo, _In_ const OrtOptionalTypeInfo* optional_type_info, + _Outptr_ OrtTypeInfo** out); + + /** \brief Set a single string in a string tensor + * Do not zero terminate the string data. + * + * \param[in] value A string tensor + * \param[in] index - flat index of the element + * \param[in] length_in_bytes length of the buffer in utf-8 bytes (without the null terminator) + * \param[inout] buffer - address of return value + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetResizedStringTensorElementBuffer, _Inout_ OrtValue* value, _In_ size_t index, _In_ size_t length_in_bytes, _Inout_ char** buffer); + + /** \brief Get Allocator from KernelContext for a specific memoryInfo. Please use C API ReleaseAllocator to release out object + * + * \param[in] context OrtKernelContext instance + * \param[in] mem_info OrtMemoryInfo instance + * \param[out] out A pointer to OrtAllocator. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.15. + */ + ORT_API2_STATUS(KernelContext_GetAllocator, _In_ const OrtKernelContext* context, _In_ const OrtMemoryInfo* mem_info, _Outptr_ OrtAllocator** out); + + /** \brief Returns a null terminated string of the build info including git info and cxx flags + * + * \return UTF-8 encoded version string. Do not deallocate the returned buffer. + * + * \since Version 1.15. + */ + const char*(ORT_API_CALL* GetBuildInfoString)(void); + + /// \name OrtROCMProviderOptions + /// @{ + + /** \brief Create an OrtROCMProviderOptions + * + * \param[out] out Newly created ::OrtROCMProviderOptions. Must be released with OrtApi::ReleaseROCMProviderOptions + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.16. + */ + ORT_API2_STATUS(CreateROCMProviderOptions, _Outptr_ OrtROCMProviderOptions** out); + + /** \brief Set options in a ROCm Execution Provider. + * + * Please refer to https://onnxruntime.ai/docs/execution-providers/ROCm-ExecutionProvider.html + * to know the available keys and values. Key should be in null terminated string format of the member of + * ::OrtROCMProviderOptions and value should be its related range. + * + * For example, key="device_id" and value="0" + * + * \param[in] rocm_options + * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys + * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values + * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.16. + */ + ORT_API2_STATUS(UpdateROCMProviderOptions, _Inout_ OrtROCMProviderOptions* rocm_options, + _In_reads_(num_keys) const char* const* provider_options_keys, + _In_reads_(num_keys) const char* const* provider_options_values, + _In_ size_t num_keys); + + /** + * Get serialized ROCm provider options string. + * + * For example, "device_id=0;arena_extend_strategy=0;......" + * + * \param rocm_options - OrtROCMProviderOptions instance + * \param allocator - a ptr to an instance of OrtAllocator obtained with CreateAllocator() or GetAllocatorWithDefaultOptions() + * the specified allocator will be used to allocate continuous buffers for output strings and lengths. + * \param ptr - is a UTF-8 null terminated string allocated using 'allocator'. The caller is responsible for using the same allocator to free it. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.16. + */ + ORT_API2_STATUS(GetROCMProviderOptionsAsString, _In_ const OrtROCMProviderOptions* rocm_options, _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); + + /** \brief Release an ::OrtROCMProviderOptions + * + * \note This is an exception in the naming convention of other Release* functions, as the name of the method does not have the V2 suffix, but the type does + * + * \since Version 1.16. + */ + void(ORT_API_CALL* ReleaseROCMProviderOptions)(_Frees_ptr_opt_ OrtROCMProviderOptions* input); + + /** \brief Create an allocator with specific type and register it with the ::OrtEnv + * This API enhance CreateAndRegisterAllocator that it can create an allocator with specific type, not just CPU allocator + * Enables sharing the allocator between multiple sessions that use the same env instance. + * Lifetime of the created allocator will be valid for the duration of the environment. + * Returns an error if an allocator with the same ::OrtMemoryInfo is already registered. + * \param[in] env OrtEnv instance + * \param[in] provider_type ExecutionProvider type + * \param[in] mem_info OrtMemoryInfo instance + * \param[in] arena_cfg Arena configuration + * \param[in] provider_options_keys key of the provider options map + * \param[in] provider_options_values value of the provider options map + * \param[in] num_keys Length of the provider options map + */ + ORT_API2_STATUS(CreateAndRegisterAllocatorV2, _Inout_ OrtEnv* env, _In_ const char* provider_type, _In_ const OrtMemoryInfo* mem_info, _In_ const OrtArenaCfg* arena_cfg, + _In_reads_(num_keys) const char* const* provider_options_keys, _In_reads_(num_keys) const char* const* provider_options_values, _In_ size_t num_keys); + + /** \brief Run the model asynchronously in a thread owned by intra op thread pool + * + * \param[in] session + * \param[in] run_options If nullptr, will use a default ::OrtRunOptions + * \param[in] input_names Array of null terminated UTF8 encoded strings of the input names + * \param[in] input Array of ::OrtValue%s of the input values + * \param[in] input_len Number of elements in the input_names and inputs arrays + * \param[in] output_names Array of null terminated UTF8 encoded strings of the output names + * \param[in] output_names_len Number of elements in the output_names and outputs array + * \param[out] output OrtValue* array of size output_names_len. + * On calling RunAsync, output[i] could either be a null or a pointer to a preallocated OrtValue. + * Later, the output array will be passed to run_async_callback with all null(s) filled with valid + * OrtValue pointer(s) allocated by onnxruntime. + * NOTE: it is customer's duty to finally release the output array and each of its member, + * regardless of whether the member (OrtValue*) is allocated by onnxruntime or preallocated by the customer. + * \param[in] run_async_callback Callback function on model run completion + * \param[in] user_data User data that pass back to run_async_callback + */ + ORT_API2_STATUS(RunAsync, _Inout_ OrtSession* session, _In_opt_ const OrtRunOptions* run_options, + _In_reads_(input_len) const char* const* input_names, + _In_reads_(input_len) const OrtValue* const* input, size_t input_len, + _In_reads_(output_names_len) const char* const* output_names, size_t output_names_len, + _Inout_updates_all_(output_names_len) OrtValue** output, + _In_ RunAsyncCallbackFn run_async_callback, _In_opt_ void* user_data); + + /** + * Update TensorRT EP provider option where its data type is pointer, for example 'user_compute_stream'. + * If the data type of the provider option can be represented by string please use UpdateTensorRTProviderOptions. + * + * Note: It's caller's responsibility to properly manage the lifetime of the instance pointed by this pointer. + * + * \param tensorrt_options - OrtTensorRTProviderOptionsV2 instance + * \param key - Name of the provider option + * \param value - A pointer to the instance that will be assigned to this provider option + * + * \since Version 1.16. + */ + ORT_API2_STATUS(UpdateTensorRTProviderOptionsWithValue, _Inout_ OrtTensorRTProviderOptionsV2* tensorrt_options, _In_ const char* key, _In_ void* value); + + /** + * Get TensorRT EP provider option where its data type is pointer. + * If the data type of the provider option can be represented by string please use GetTensorRTProviderOptionsAsString. + * + * \param tensorrt_options - OrtTensorRTProviderOptionsV2 instance + * \param key - Name of the provider option + * \param ptr - A pointer to the instance that is kept by the provider option + * + * \since Version 1.16. + */ + ORT_API2_STATUS(GetTensorRTProviderOptionsByName, _In_ const OrtTensorRTProviderOptionsV2* tensorrt_options, _In_ const char* key, _Outptr_ void** ptr); + + /** + * Update CUDA EP provider option where its data type is pointer, for example 'user_compute_stream'. + * If the data type of the provider option can be represented by string please use UpdateCUDAProviderOptions. + * + * Note: It's caller's responsibility to properly manage the lifetime of the instance pointed by this pointer. + * + * \param cuda_options - OrtCUDAProviderOptionsV2 instance + * \param key - Name of the provider option + * \param value - A pointer to the instance that will be assigned to this provider option + * + * \since Version 1.16. + */ + ORT_API2_STATUS(UpdateCUDAProviderOptionsWithValue, _Inout_ OrtCUDAProviderOptionsV2* cuda_options, _In_ const char* key, _In_ void* value); + + /** + * Get CUDA EP provider option where its data type is pointer. + * If the data type of the provider option can be represented by string please use GetCUDAProviderOptionsAsString. + * + * \param cuda_options - OrtCUDAProviderOptionsV2 instance + * \param key - Name of the provider option + * \param ptr - A pointer to the instance that is kept by the provider option + * + * \since Version 1.16. + */ + ORT_API2_STATUS(GetCUDAProviderOptionsByName, _In_ const OrtCUDAProviderOptionsV2* cuda_options, _In_ const char* key, _Outptr_ void** ptr); + + /** + * Get a EP resource. + * E.g. a cuda stream or a cublas handle + * + * \param context - Kernel context + * \param resource_version - Version of the resource + * \param resource_id - Type of resource + * \param resource - A pointer to returned resource + * + * \since Version 1.16. + */ + ORT_API2_STATUS(KernelContext_GetResource, _In_ const OrtKernelContext* context, _In_ int resource_version, + _In_ int resource_id, _Outptr_ void** resource); + + /** \brief Set user logging function + * + * By default the logger created by the CreateEnv* functions is used to create the session logger as well. + * This function allows a user to override this default session logger with a logger of their own choosing. This way + * the user doesn't have to create a separate environment with a custom logger. This addresses the problem when + * the user already created an env but now wants to use a different logger for a specific session (for debugging or + * other reasons). + * + * \param[in] options + * \param[in] user_logging_function A pointer to a logging function. + * \param[in] user_logging_param A pointer to arbitrary data passed as the ::OrtLoggingFunction `param` parameter to + * `user_logging_function`. This parameter is optional. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.17. + */ + ORT_API2_STATUS(SetUserLoggingFunction, _Inout_ OrtSessionOptions* options, + _In_ OrtLoggingFunction user_logging_function, _In_opt_ void* user_logging_param); + + /** + * Get number of input from OrtShapeInferContext + * + * \param[in] context + * \param[out] out The number of inputs + * + * \since Version 1.17. + */ + ORT_API2_STATUS(ShapeInferContext_GetInputCount, _In_ const OrtShapeInferContext* context, _Out_ size_t* out); + + /** + * Get type and shape info of an input + * + * \param[in] context + * \param[in] index The index of the input + * \param[out] info Type shape info of the input + * + * \since Version 1.17. + */ + ORT_API2_STATUS(ShapeInferContext_GetInputTypeShape, _In_ const OrtShapeInferContext* context, _In_ size_t index, _Outptr_ OrtTensorTypeAndShapeInfo** info); + + /** + * Get attribute from OrtShapeInferContext. Note that OrtShapeInferContext is a per-node context, one could only read attribute from current node. + * + * \param[in] context + * \param[in] attr_name Name of the attribute + * \param[out] attr Handle of the attribute fetched + * + * \since Version 1.17. + */ + ORT_API2_STATUS(ShapeInferContext_GetAttribute, _In_ const OrtShapeInferContext* context, _In_ const char* attr_name, _Outptr_ const OrtOpAttr** attr); + + /** + * Set type and shape info of an output + * + * \param[in] context + * \param[in] index The index of the output + * \param[out] info Type shape info of the output + * + * \since Version 1.17. + */ + ORT_API2_STATUS(ShapeInferContext_SetOutputTypeShape, _In_ const OrtShapeInferContext* context, _In_ size_t index, _In_ const OrtTensorTypeAndShapeInfo* info); + + /** + * Set symbolic shape to type shape info + * + * \param[in] info Type shape info + * \param[in] dim_params Symbolic strings + * \param[in] dim_params_length Number of strings + * + * \since Version 1.17. + */ + ORT_API2_STATUS(SetSymbolicDimensions, _In_ OrtTensorTypeAndShapeInfo* info, _In_ const char* dim_params[], _In_ size_t dim_params_length); + + /** + * Read contents of an attribute to data + * + * \param[in] op_attr + * \param[in] type Attribute type + * \param[out] data Memory address to save raw content of the attribute + * \param[in] len Number of bytes allowed to store in data + * \param[out] out Number of bytes required to save the data when the call failed, or the real number of bytes saved to data on success + * + * \since Version 1.17. + */ + ORT_API2_STATUS(ReadOpAttr, _In_ const OrtOpAttr* op_attr, _In_ OrtOpAttrType type, _Inout_ void* data, _In_ size_t len, _Out_ size_t* out); + + /** \brief Set whether to use deterministic compute. + * + * Default is false. If set to true, this will enable deterministic compute for GPU kernels where possible. + * Note that this most likely will have a performance cost. + * + * \param[in] options + * \param[in] value + * + * \since Version 1.17. + */ + ORT_API2_STATUS(SetDeterministicCompute, _Inout_ OrtSessionOptions* options, bool value); + + /** + * Run fn in parallel + * + * \param[in] context + * \param[in] fn Function accepting usr_data and an integer as iterator + * \param[in] total The number of times fn is to be invoked + * \param[in] num_batch Number of batches by which the "total" is to be divided in maximum. When zero, there is no limit + * \param[in] usr_data User data to be passed back to fn + * + * \since Version 1.17. + */ + ORT_API2_STATUS(KernelContext_ParallelFor, _In_ const OrtKernelContext* context, _In_ void (*fn)(void*, size_t), _In_ size_t total, _In_ size_t num_batch, _In_ void* usr_data); + + /** \brief Append OpenVINO execution provider to the session options + * + * If OpenVINO is not available (due to a non OpenVINO enabled build, or if OpenVINO is not installed on the system), this function will fail. + * + * \param[in] options + * \param[in] provider_options_keys + * \param[in] provider_options_values + * \param[in] num_keys + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.17. + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_OpenVINO_V2, + _In_ OrtSessionOptions* options, + _In_reads_(num_keys) const char* const* provider_options_keys, + _In_reads_(num_keys) const char* const* provider_options_values, + _In_ size_t num_keys); + + /** \brief Append VitisAI provider to session options + * + * If VitisAI is not available (due to a non VitisAI enabled build, or if VitisAI is not installed on the system), this function will return failure. + * + * \param[in] options + * \param[in] provider_options_keys + * \param[in] provider_options_values + * \param[in] num_keys + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.18. + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_VitisAI, + _In_ OrtSessionOptions* options, + _In_reads_(num_keys) const char* const* provider_options_keys, + _In_reads_(num_keys) const char* const* provider_options_values, + _In_ size_t num_keys); + + /** \brief Get scratch buffer from the corresponding allocator under the sepcific OrtMemoryInfo object. + * NOTE: callers are responsible to release this scratch buffer from the corresponding allocator + * \param[in] context OrtKernelContext instance + * \param[in] mem_info OrtMemoryInfo instance + * \param[in] count_or_bytes How many bytes is this scratch buffer + * \param[out] out A pointer to the scrach buffer + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.18. + */ + ORT_API2_STATUS(KernelContext_GetScratchBuffer, _In_ const OrtKernelContext* context, _In_ const OrtMemoryInfo* mem_info, _In_ size_t count_or_bytes, _Outptr_ void** out); + + /** \brief Get allocator from KernelInfo for a specific memory type. Please use C API ReleaseAllocator to release out object + * + * \param[in] info OrtKernelInfo instance + * \param[in] mem_type OrtMemType object + * \param[out] out A pointer to OrtAllocator + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.18. + */ + ORT_API2_STATUS(KernelInfoGetAllocator, _In_ const OrtKernelInfo* info, _In_ OrtMemType mem_type, _Outptr_ OrtAllocator** out); + + /** \brief Replace initialized Tensors with external data with the provided files in memory + * + * The function will find the initialized TensorProtos with external data in the graph with the provided + * external file names and the file content in memory. The API gets the external file name, offset, data length + * from TensorProto, and locate the tensor data from the file in memory buffer. + * It creates a Tensor to replace the existing Tensor in graph. The replacement + * will occur before any of the optimizations take place. The data will be copied into the graph + * since TensorProto can't refer to the user provided buffers. + * + * \param[in] options + * \param[in] external_initializer_file_names Array of null terminated UTF-8 encoded strings of the file names + * which holds the external initializers. + * \param[in] external_initializer_file_buffer_array Array of pointers to the buffer of the file content. + * The buffer can be freed after session creation. + * \param[in] external_initializer_file_lengths Array of size_t to indicate the length of file content + * \param[in] num_external_initializer_files Number of external files + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.18. + */ + ORT_API2_STATUS(AddExternalInitializersFromFilesInMemory, _In_ OrtSessionOptions* options, + _In_reads_(num_external_initializer_files) const ORTCHAR_T* const* external_initializer_file_names, + _In_reads_(num_external_initializer_files) char* const* external_initializer_file_buffer_array, + _In_reads_(num_external_initializer_files) const size_t* external_initializer_file_lengths, + size_t num_external_initializer_files); + + /** \brief Create an OrtLoraAdapter + * + * The function attempts to locate file specified by adapter_file_path, read it and create an OrtLoraAdapter + * instance. The adapter_file_path should be a valid path to a file that contains a valid Lora Adapter + * format. The function attempts to validate the format at load time. The file will always be memory mapped, unless + * the platform does not support memory mapping, in which case the file will be read into memory. + * + * \param[in] adapter_file_path adapter file path. + * \param[in] allocator optional pointer to a device allocator. If specified + * data is copied to the device at some point before Run() is invoked. If nullptr, data stays on CPU. + * The data would still be copied to device if required by the model at inference time. + * \param[out] out A pointer to a newly created OrtLoraAdapter instance. Must be released with + * OrtApi::ReleaseLoraAdapter. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.20. + */ + ORT_API2_STATUS(CreateLoraAdapter, const ORTCHAR_T* adapter_file_path, _In_ OrtAllocator* allocator, + _Outptr_ OrtLoraAdapter** out); + + /** \brief Create an OrtLoraAdapter + * + * The function copies the bytes from the array and creates an OrtLoraAdapter instance. + * + * + * \param[in] bytes pointer to a valid Lora Adapter format buffer. + * \param[in] num_bytes length of bytes buffer. + * \param[in] allocator optional pointer to a device allocator. If specified + * data is copied to the device at some point before Run() is invoked. If nullptr, data stays on CPU. + * The data would still be copied to device if required by the model at inference time. + * \param[out] out A pointer to a newly created OrtLoraAdapter instance. Must be released with + * OrtApi::ReleaseLoraAdapter. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.20. + */ + ORT_API2_STATUS(CreateLoraAdapterFromArray, _In_ const void* bytes, size_t num_bytes, _In_ OrtAllocator* allocator, + _Outptr_ OrtLoraAdapter** out); + + /** \brief Release an ::OrtLoraAdapter obtained from OrtApi::CreateLoraAdapter + */ + ORT_CLASS_RELEASE(LoraAdapter); + + /** \brief Add the Lora Adapter to the list of active adapters. + * + * The function adds the Lora Adapter to the list of active adapters. The Lora Adapter must be created with + * OrtApi::CreateLoraAdapter or FromArray. The Lora Adapter will be used by the session to run the model. + * The instance of the OrtRunOptions can then be used to customize the Run() calls. + * More than one OrtLoraAdapter can be active at the same time. Lora Parameters that belong to different + * Lora adapters that will be active at the same time must not overlap. + * This setting does not affect RunWithBinding. + * + * \param[in] options OrtRunOptions instance + * \param[in] adapter OrtLoraAdapter instance + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.20. + */ + ORT_API2_STATUS(RunOptionsAddActiveLoraAdapter, _Inout_ OrtRunOptions* options, _In_ const OrtLoraAdapter* adapter); + + /// @} + /// \name OrtEpDynamicOptions + /// @{ + + /** \brief Set DynamicOptions for EPs (Execution Providers) + * + * Valid options can be found in `include\onnxruntime\core\session\onnxruntime_session_options_config_keys.h` + * Look for `kOrtEpDynamicOptions` + * + * \param[in] sess OrtSession + * \param[in] keys Array of null terminated UTF8 encoded strings of EP dynamic option keys + * \param[in] values Array of null terminated UTF8 encoded string of EP dynamic option values + * \param[in] kv_len Number of elements in the keys and values arrays + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.20. + */ + ORT_API2_STATUS(SetEpDynamicOptions, _Inout_ OrtSession* sess, _In_reads_(kv_len) const char* const* keys, + _In_reads_(kv_len) const char* const* values, _In_ size_t kv_len); + + /** \brief Release an OrtValueInfo instance if it was not added to an OrtGraph. + * \since Version 1.22. + */ + ORT_CLASS_RELEASE(ValueInfo); + + /** \brief Release an OrtNode if it was not added to an OrtGraph. + * \since Version 1.22. + */ + ORT_CLASS_RELEASE(Node); + + /** \brief Release an OrtGraph. + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.22. + */ + ORT_CLASS_RELEASE(Graph); + + /** \brief Release an OrtModel. + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.22. + */ + ORT_CLASS_RELEASE(Model); + + /** \brief Get the value name from an OrtValueInfo instance. + * \param[in] value_info The OrtValueInfo instance. + * \param[out] name The name of the OrtValueInfo + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.22. + */ + ORT_API2_STATUS(GetValueInfoName, _In_ const OrtValueInfo* value_info, _Out_ const char** name); + + /** \brief Get the type information from an OrtValueInfo instance. + * \param[in] value_info The OrtValueInfo instance. + * \param[out] type_info The type info of the OrtValueInfo + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.22. + */ + ORT_API2_STATUS(GetValueInfoTypeInfo, _In_ const OrtValueInfo* value_info, _Outptr_ const OrtTypeInfo** type_info); + + /** \brief Get the Model Editor API instance + * + * Get the Model Editor API instance to create a new model or augment an existing model. + * + * \return Model Editor API struct + * + * \since Version 1.22. + */ + const OrtModelEditorApi*(ORT_API_CALL* GetModelEditorApi)(); + + /** \brief Create an OrtValue for a Tensor that uses pre-existing memory. + * + * ORT will take ownership of the memory and free it using the provided deleter when no longer in use. + * + * \param[in] deleter OrtAllocator instance that will be used to free the memory. + * Only the OrtAllocator:Info and OrtAllocator::Release functions are required. + * The OrtMemoryInfo returned by OrtAllocator::Info must match the location of p_data. + * \param[in] p_data Pointer to the memory that will be used by the Tensor. ORT will take ownership of the memory. + * \param[in] p_data_len Length of the memory in bytes. + * \param[in] shape Dimensions of the Tensor. All values should be > 0. + * \param[in] shape_len Number of dimensions in the shape array. + * \param[in] type Data type of the Tensor. + * \param[out] out Newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateTensorWithDataAndDeleterAsOrtValue, _In_ OrtAllocator* deleter, + _In_ void* p_data, size_t p_data_len, + _In_ const int64_t* shape, size_t shape_len, + ONNXTensorElementDataType type, + _Outptr_ OrtValue** out); + + /** \brief sets load cancellation flag to abort session loading process. + * + * \param[in] options instance that was passed to the session at creation time. + * \param[in] cancel setting this to true after model loading process was initiated will + * attempt to cancel the loading process. If cancellation is successful, CreateSession() + * CreateSessionFromArray() or any other session creation API that take session options as an + * argument will return an OrtStatus indicating that session loading was canceled at user request, + * error code ORT_MODEL_LOAD_CANCELED. + * The APIs above would not return any valid Session instance. This is the best case effort and the result + * is not guaranteed. The session may have already been created and initialized + * before the cancellation request was issued. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(SessionOptionsSetLoadCancellationFlag, _Inout_ OrtSessionOptions* options, + _In_ bool cancel); + + /** \brief Get the Compile API instance. + * + * Get the Compile API instance to compile ONNX models. Execution providers that support compilation fuse a subgraph + * into an EPContext node that wraps a provider-specific binary representation of the subgraph. + * For more details about the EPContext design, refer to: + * \htmlonly + * EPContext design document. + * \endhtmlonly + * + * \return Compile API struct instance. + * + * \since Version 1.22. + */ + const OrtCompileApi*(ORT_API_CALL* GetCompileApi)(); + + // + // OrtKeyValuePairs + // + + /** \brief Create an OrtKeyValuePairs instance. + * + * \param[out] out A pointer to a newly created OrtKeyValuePairs instance. + * + * \note Must be released by calling ReleaseKeyValuePairs. + * + * \since Version 1.22. + */ + void(ORT_API_CALL* CreateKeyValuePairs)(_Outptr_ OrtKeyValuePairs** out); + + /** \brief Add a key-value pair to the OrtKeyValuePairs instance. + * + * \param[in] kvps OrtKeyValuePairs instance. + * \param[in] key Key to be added. + * \param[in] value Value to be added. + * + * \note The `key` and `value` are copied internally. + * + * \since Version 1.22. + */ + + void(ORT_API_CALL* AddKeyValuePair)(_In_ OrtKeyValuePairs* kvps, _In_ const char* key, _In_ const char* value); + + /** \brief Get the value associated with a key in the OrtKeyValuePairs instance. + * + * \param[in] kvps OrtKeyValuePairs instance. + * \param[in] key Key to be searched. + * + * \return The value associated with the key, or nullptr if the key does not exist. + * + * \since Version 1.22. + */ + const char*(ORT_API_CALL* GetKeyValue)(_In_ const OrtKeyValuePairs* kvps, _In_ const char* key); + + /** \brief Get all the key-value pairs from the OrtKeyValuePairs instance. + * + * \param[in] kvps OrtKeyValuePairs instance. + * \param[out] keys Array of keys from `kvps`. + * \param[out] values Array of values from `kvps`. + * \param[out] num_entries Number of entries in `keys` and `values`. + * + * \since Version 1.22. + */ + void(ORT_API_CALL* GetKeyValuePairs)(_In_ const OrtKeyValuePairs* kvps, + _Outptr_ const char* const** keys, _Outptr_ const char* const** values, + _Out_ size_t* num_entries); + + /** \brief Remove a key-value pair from the OrtKeyValuePairs instance. + * + * \param[in] kvps OrtKeyValuePairs instance. + * \param[in] key Key to be removed. No error if not found. + * + * \since Version 1.22. + */ + void(ORT_API_CALL* RemoveKeyValuePair)(_In_ OrtKeyValuePairs* kvps, _In_ const char* key); + + /** \brief Release an OrtKeyValuePairs instance. + * + * \param[in] input OrtKeyValuePairs instance to be released. + * + * \since Version 1.22. + */ + ORT_CLASS_RELEASE(KeyValuePairs); + + /** \brief Register an execution provider library with ORT. + * + * The library must export 'CreateEpFactories' and 'ReleaseEpFactory' functions. + * See OrtEpApi for more details. + * + * \param[in] env The OrtEnv instance to register the library in. + * \param[in] registration_name The name to register the execution provider library under. + * \param[in] path The path to the execution provider library. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(RegisterExecutionProviderLibrary, _In_ OrtEnv* env, _In_ const char* registration_name, + _In_ const ORTCHAR_T* path); + + /** \brief Unregister an execution provider library with ORT. + * + * ORT will call ReleaseEpFactory for all factories created by the library, and unload the library. + * + * You MUST ensure there are no Session instances using execution providers created by the library + * before calling this function. + * + * \param[in] env The OrtEnv instance to unregister the library from. + * \param[in] registration_name The name the execution provider library was registered under. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(UnregisterExecutionProviderLibrary, _In_ OrtEnv* env, _In_ const char* registration_name); + + /** \brief Get the list of available OrtEpDevice instances. + * + * Each OrtEpDevice instance contains details of the execution provider and the device it will use. + * + * \param[in] env The OrtEnv instance to query. + * \param[out] ep_devices The OrtEpDevice instances that the execution provider will use. + * \param[out] num_ep_devices The number of OrtEpDevice instances returned. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(GetEpDevices, _In_ const OrtEnv* env, + _Outptr_ const OrtEpDevice* const** ep_devices, _Out_ size_t* num_ep_devices); + + /** \brief Append the execution provider that is responsible for the selected OrtEpDevice instances + * to the session options. + * + * \param[in] session_options Session options to add execution provider to. + * \param[in] env Environment that execution providers were registered with. + * \param[in] ep_devices One or more OrtEpDevice instances to create an execution provider for. + * Obtain from GetEpDevices. All OrtEpDevice instances must be from the same execution + * provider. It is only necessary to provide multiple OrtEpDevices if you want to use the + * same execution provider for multiple devices. + * e.g. the EP is capable of running on GPU and NPU. + * \param[in] num_ep_devices Number of OrtEpDevice instances. + * \param[in] ep_option_keys Optional keys to configure the execution provider. + * \param[in] ep_option_vals Optional values to configure the execution provider. + * \param[in] num_ep_options Number of execution provide options to add. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_V2, _In_ OrtSessionOptions* session_options, + _In_ OrtEnv* env, + _In_reads_(num_ep_devices) const OrtEpDevice* const* ep_devices, _In_ size_t num_ep_devices, + _In_reads_(num_op_options) const char* const* ep_option_keys, + _In_reads_(num_op_options) const char* const* ep_option_vals, + size_t num_ep_options); + + /** \brief Set the execution provider selection policy for the session. + * + * Allows users to specify a device selection policy for automatic execution provider (EP) selection. + * If custom selection is required please use SessionOptionsSetEpSelectionPolicyDelegate instead. + * + * \param[in] session_options The OrtSessionOptions instance. + * \param[in] policy The device selection policy to use (see OrtExecutionProviderDevicePolicy). + * + * \since Version 1.22 + */ + ORT_API2_STATUS(SessionOptionsSetEpSelectionPolicy, _In_ OrtSessionOptions* session_options, + _In_ OrtExecutionProviderDevicePolicy policy); + + /** \brief Set the execution provider selection policy delegate for the session. + * + * Allows users to provide a custom device selection policy for automatic execution provider (EP) selection. + * + * \param[in] session_options The OrtSessionOptions instance. + * \param[in] delegate Delegate callback for custom selection. + * \param[in] delegate_state Optional state that will be passed to the delegate callback. nullptr if not required. + * + * \since Version 1.22 + */ + ORT_API2_STATUS(SessionOptionsSetEpSelectionPolicyDelegate, _In_ OrtSessionOptions* session_options, + _In_ EpSelectionDelegate delegate, + _In_opt_ void* delegate_state); + + /** \brief Get the hardware device type. + * + * \param[in] device The OrtHardwareDevice instance to query. + * \return The hardware device type. + * + * \since Version 1.22. + */ + OrtHardwareDeviceType(ORT_API_CALL* HardwareDevice_Type)(_In_ const OrtHardwareDevice* device); + + /** \brief Get the hardware device's vendor identifier. + * + * \param[in] device The OrtHardwareDevice instance to query. + * \return The hardware device vendor identifier. + * + * \since Version 1.22. + */ + uint32_t(ORT_API_CALL* HardwareDevice_VendorId)(_In_ const OrtHardwareDevice* device); + + /** \brief Get the hardware device's vendor name. + * + * \param[in] device The OrtHardwareDevice instance to query. + * \return The hardware device's vendor name. + * + * \since Version 1.22. + */ + const char*(ORT_API_CALL* HardwareDevice_Vendor)(_In_ const OrtHardwareDevice* device); + + /** \brief Get the hardware device's unique identifier. + * + * \param[in] device The OrtHardwareDevice instance to query. + * \return The device id. + * + * \note This is not a unique identifier. It identifies the hardware type when combined with vendor id. + * \since Version 1.22. + */ + uint32_t(ORT_API_CALL* HardwareDevice_DeviceId)(_In_ const OrtHardwareDevice* device); + + /** \brief Get hardware device metadata. + * + * \param[in] device The OrtHardwareDevice instance to query. + * \return An OrtKeyValuePairs instance containing the metadata for the device. + * Note: ORT owns the instance so the user must not call ReleaseKeyValuePairs with it. + * + * \since Version 1.22. + */ + const OrtKeyValuePairs*(ORT_API_CALL* HardwareDevice_Metadata)(_In_ const OrtHardwareDevice* device); + + /** \brief Get the execution provider name. + * + * \param[in] ep_device The OrtEpDevice instance to query. + * \return The execution provider name. + * + * \since Version 1.22. + */ + const char*(ORT_API_CALL* EpDevice_EpName)(_In_ const OrtEpDevice* ep_device); + + /** \brief Get the execution provider's vendor name. + * + * \param[in] ep_device The OrtEpDevice instance to query. + * \return The execution provider's vendor name. + * + * \since Version 1.22. + */ + const char*(ORT_API_CALL* EpDevice_EpVendor)(_In_ const OrtEpDevice* ep_device); + + /** \brief Get the metadata for the OrtEpDevice. + * + * \param[in] ep_device The OrtEpDevice instance to query. + * \return An OrtKeyValuePairs instance containing the metadata for the device. + * + * \since Version 1.22. + */ + const OrtKeyValuePairs*(ORT_API_CALL* EpDevice_EpMetadata)(_In_ const OrtEpDevice* ep_device); + + /** \brief Get the execution provider options for the OrtEpDevice. + * + * \param[in] ep_device The OrtEpDevice instance to query. + * \return An OrtKeyValuePairs instance containing the execution provider options for the device. + * + * \since Version 1.22. + */ + const OrtKeyValuePairs*(ORT_API_CALL* EpDevice_EpOptions)(_In_ const OrtEpDevice* ep_device); + + /** \brief Get the OrtHardwareDevice instance for the OrtEpDevice. + * + * \param[in] ep_device The OrtEpDevice instance to query. + * \return The OrtHardwareDevice instance for the device. + * + * \since Version 1.22. + */ + const OrtHardwareDevice*(ORT_API_CALL* EpDevice_Device)(_In_ const OrtEpDevice* ep_device); + + /** \brief Get the OrtEpApi instance for implementing an execution provider. + * + * \since Version 1.22. + */ + const OrtEpApi*(ORT_API_CALL* GetEpApi)(); +}; + +/* + * Steps to use a custom op: + * 1 Create an OrtCustomOpDomain with the domain name used by the custom ops + * 2 Create an OrtCustomOp structure for each op and add them to the domain + * 3 Call OrtAddCustomOpDomain to add the custom domain of ops to the session options + */ + +// Specifies some characteristics of inputs/outputs of custom ops: +// Specify if the inputs/outputs are one of: +// 1) Non-optional (input/output must be present in the node) +// 2) Optional (input/output may be absent in the node) +// 3) Variadic: A variadic input or output specifies N (i.e., the minimum arity) or more operands. +// Only the last input or output of a custom op may be marked as variadic. +// The homogeneity of the variadic input or output determines whether all operands must be of the same +// tensor element type. +typedef enum OrtCustomOpInputOutputCharacteristic { + INPUT_OUTPUT_REQUIRED = 0, + INPUT_OUTPUT_OPTIONAL, + INPUT_OUTPUT_VARIADIC, +} OrtCustomOpInputOutputCharacteristic; + +/* + * The OrtCustomOp structure defines a custom op's schema and its kernel callbacks. The callbacks are filled in by + * the implementor of the custom op. + */ +struct OrtCustomOp { + uint32_t version; // Must be initialized to ORT_API_VERSION + + // This callback creates the kernel, which is a user defined + // parameter that is passed to the Kernel* callbacks below. It is + // recommended to use CreateKernelV2 which allows for a safe error + // propagation by returning an OrtStatusPtr. + void*(ORT_API_CALL* CreateKernel)(_In_ const struct OrtCustomOp* op, _In_ const OrtApi* api, + _In_ const OrtKernelInfo* info); + + // Returns the name of the op + const char*(ORT_API_CALL* GetName)(_In_ const struct OrtCustomOp* op); + + // Returns the type of the execution provider, return nullptr to use CPU execution provider + const char*(ORT_API_CALL* GetExecutionProviderType)(_In_ const struct OrtCustomOp* op); + + // Returns the count and types of the input & output tensors + ONNXTensorElementDataType(ORT_API_CALL* GetInputType)(_In_ const struct OrtCustomOp* op, _In_ size_t index); + size_t(ORT_API_CALL* GetInputTypeCount)(_In_ const struct OrtCustomOp* op); + ONNXTensorElementDataType(ORT_API_CALL* GetOutputType)(_In_ const struct OrtCustomOp* op, _In_ size_t index); + size_t(ORT_API_CALL* GetOutputTypeCount)(_In_ const struct OrtCustomOp* op); + + // Perform a computation step. It is recommended to use + // KernelComputeV2 which allows for a safe error propagation by + // returning an OrtStatusPtr. + void(ORT_API_CALL* KernelCompute)(_In_ void* op_kernel, _In_ OrtKernelContext* context); + void(ORT_API_CALL* KernelDestroy)(_In_ void* op_kernel); + + // Returns the characteristics of the input & output tensors + OrtCustomOpInputOutputCharacteristic(ORT_API_CALL* GetInputCharacteristic)(_In_ const struct OrtCustomOp* op, _In_ size_t index); + OrtCustomOpInputOutputCharacteristic(ORT_API_CALL* GetOutputCharacteristic)(_In_ const struct OrtCustomOp* op, _In_ size_t index); + + // Returns the memory type of the input tensors. This API allows the custom op + // to place the inputs on specific devices. By default, it returns + // OrtMemTypeDefault, which means the input is placed on the default device for + // the execution provider. If the inputs need to be with different memory tyeps, + // this function can be overridden to return the specific memory types. + OrtMemType(ORT_API_CALL* GetInputMemoryType)(_In_ const struct OrtCustomOp* op, _In_ size_t index); + + // Returns the minimum number of input arguments expected for the variadic input. + // Applicable only for custom ops that have a variadic input. + int(ORT_API_CALL* GetVariadicInputMinArity)(_In_ const struct OrtCustomOp* op); + + // Returns true (non-zero) if all arguments of a variadic input have to be of the same type (homogeneous), + // and false (zero) otherwise. + // Applicable only for custom ops that have a variadic input. + int(ORT_API_CALL* GetVariadicInputHomogeneity)(_In_ const struct OrtCustomOp* op); + + // Returns the minimum number of output values expected for the variadic output. + // Applicable only for custom ops that have a variadic output. + int(ORT_API_CALL* GetVariadicOutputMinArity)(_In_ const struct OrtCustomOp* op); + + // Returns true (non-zero) if all outputs values of a variadic output have to be of the same type (homogeneous), + // and false (zero) otherwise. + // Applicable only for custom ops that have a variadic output. + int(ORT_API_CALL* GetVariadicOutputHomogeneity)(_In_ const struct OrtCustomOp* op); + + // Create the kernel state which is passed to each compute call. + OrtStatusPtr(ORT_API_CALL* CreateKernelV2)(_In_ const struct OrtCustomOp* op, _In_ const OrtApi* api, + _In_ const OrtKernelInfo* info, + _Out_ void** kernel); + + // Perform the computation step. + OrtStatusPtr(ORT_API_CALL* KernelComputeV2)(_In_ void* op_kernel, _In_ OrtKernelContext* context); + + OrtStatusPtr(ORT_API_CALL* InferOutputShapeFn)(_In_ const struct OrtCustomOp* op, _In_ OrtShapeInferContext*); + + // Get start range + int(ORT_API_CALL* GetStartVersion)(_In_ const struct OrtCustomOp* op); + int(ORT_API_CALL* GetEndVersion)(_In_ const struct OrtCustomOp* op); + + // Get the inplace_map that defines which output can reuse which input + // Callers will provide 2 raw int* and pass in their address, this function will fill these 2 arrays + // when return, output (*output_index)[i] may reuse the input (*input_index[i]). + // The return value is the size of these 2 arrays. + // Callers are responsible to delete these 2 arrays after use by calling OrtCustomOp::ReleaseMayInplace(). + size_t(ORT_API_CALL* GetMayInplace)(_Out_ int** input_index, _Out_ int** output_index); + + // Release the pointer input_index and output_index allocated from GetMayInplace() function. + // If GetMayInplace() is defined, this function MUST be defined as well. + void(ORT_API_CALL* ReleaseMayInplace)(_Frees_ptr_opt_ int* input_index, _Frees_ptr_opt_ int* output_index); + + // Same as GetMayInplace() and ReleaseMayInplace() + size_t(ORT_API_CALL* GetAliasMap)(_Out_ int** input_index, _Out_ int** output_index); + void(ORT_API_CALL* ReleaseAliasMap)(_Frees_ptr_opt_ int* input_index, _Frees_ptr_opt_ int* output_index); +}; + +/** + * ORT Model Editor API + */ + +/** + * \brief The OrtModelEditorApi struct provides functions to create or edit an ONNX model. + * + * See onnxruntime/test/shared_lib/test_model_editor_api.cc for example usage. + * + * \since Version 1.22. + */ +struct OrtModelEditorApi { + // Model building/editing requires a full build. We return nullptr from GetModelEditorApi if this is a minimal + // build, so it doesn't matter if there are no function pointers in this struct as a user will never get an + // OrtModelEditorApi instance. We do however need a dummy field to avoid empty struct warning. +#if defined(ORT_MINIMAL_BUILD) + const bool not_defined_in_this_build; +#else + /** \brief Create an OrtTypeInfo instance for a Tensor. + * + * Create an OrtTypeInfo instance for a Tensor to use as graph inputs/outputs with the Model Editor API. + * + * User can release `tensor_info` after creating the OrtTypeInfo. + * + * \param[in] tensor_info Tensor type and shape information. + * \param[out] type_info TypeInfo instance for the tensor. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateTensorTypeInfo, _In_ const OrtTensorTypeAndShapeInfo* tensor_info, + _Outptr_ OrtTypeInfo** type_info); + + /** \brief Create an OrtTypeInfo instance for a SparseTensor. + * + * Create an OrtTypeInfo instance for a SparseTensor to use as graph inputs/outputs with the Model Editor API. + * + * User can release `tensor_info` after creating the OrtTypeInfo. + * + * \param[in] tensor_info SparseTensor type and shape information. + * \param[out] type_info TypeInfo instance for the tensor. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateSparseTensorTypeInfo, _In_ const OrtTensorTypeAndShapeInfo* tensor_info, + _Outptr_ OrtTypeInfo** type_info); + + /** \brief Create an OrtTypeInfo instance for a Map. + * + * Create an OrtTypeInfo instance for a Map to use as graph inputs/outputs with the Model Editor API. + * + * User can release `map_value_type` after creating the OrtTypeInfo. + * + * \param[in] map_key_type Key type for the map. + * \param[in] map_value_type Value type for the map. + * \param[out] type_info TypeInfo instance for the map. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateMapTypeInfo, ONNXTensorElementDataType map_key_type, _In_ const OrtTypeInfo* map_value_type, + _Outptr_ OrtTypeInfo** type_info); + + /** \brief Create an OrtTypeInfo instance for a Sequence. + * + * Create an OrtTypeInfo instance for a Sequence to use as graph inputs/outputs with the Model Editor API. + * + * User can release `sequence_type` after creating the OrtTypeInfo. + * + * \param[in] sequence_type Sequence type and shape information. + * \param[out] type_info TypeInfo instance for the sequence. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateSequenceTypeInfo, _In_ const OrtTypeInfo* sequence_type, _Outptr_ OrtTypeInfo** type_info); + + /** \brief Create an OrtTypeInfo instance for an Optional. + * + * Create an OrtTypeInfo instance for an Optional to use as graph inputs/outputs with the Model Editor API. + * + * User can release `contained_type` after creating the OrtTypeInfo. + * + * \param[in] contained_type Tensor type and shape information. + * \param[out] type_info TypeInfo instance for the tensor. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateOptionalTypeInfo, _In_ const OrtTypeInfo* contained_type, _Outptr_ OrtTypeInfo** type_info); + + /** \brief Create an OrtValueInfo for use as an OrtGraph input or output. + * + * \param[in] name The name of the input or output. + * \param[in] type_info The type information for the input or output. The provided value is copied. + * \param[out] value_info The OrtValueInfo instance. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateValueInfo, _In_ const char* name, _In_ const OrtTypeInfo* type_info, + _Outptr_ OrtValueInfo** value_info); + + /** \brief Create an OrtNode to add to an OrtGraph. + * + * Create an OrtNode. + * + * Create attributes with CreateOpAttr. OrtOpAttr instances are copied. + * + * \param[in] operator_name The name of the operator. + * \param[in] domain_name The domain of the operator. Use an empty string for ONNX operators. + * \param[in] node_name The name of the node. + * \param[in] input_names The names of the inputs. + * \param[in] input_names_len The number of input names. + * \param[in] output_names The names of the outputs. + * \param[in] output_names_len The number of output names. + * \param[in] attributes The optional attributes of the node. + * \param[in] attribs_len The number of attributes. May be zero. + * \param[out] node The OrtNode instance. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateNode, _In_ const char* operator_name, _In_ const char* domain_name, _In_ const char* node_name, + _In_reads_(input_names_len) const char* const* input_names, size_t input_names_len, + _In_reads_(output_names_len) const char* const* output_names, size_t output_names_len, + _In_reads_(attribs_len) _In_opt_ OrtOpAttr** attributes, _In_ size_t attribs_len, + _Outptr_ OrtNode** node); + + /** \brief Create an OrtGraph + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateGraph, _Outptr_ OrtGraph** graph); + + /** \brief Set the inputs for the OrtGraph. + * + * Set the graph inputs. This will replace any existing inputs with the new values. + * The OrtGraph takes ownership of the OrtValueInfo instances and you should NOT call ReleaseOrtValueInfo. + * + * \param[in] graph The OrtGraph instance to update. + * \param[in] inputs The input OrtValueInfo instances. + * \param[in] inputs_len The number of input OrtValueInfo instances. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(SetGraphInputs, _Inout_ OrtGraph* graph, + _In_reads_(inputs_len) _In_ OrtValueInfo** inputs, _In_ size_t inputs_len); + + /** \brief Set the outputs for the OrtGraph. + * + * Set the graph outputs. This will replace any existing outputs with the new values. + * The OrtGraph takes ownership of the OrtValueInfo instances provided and you should NOT call ReleaseOrtValueInfo. + * + * \param[in] graph The OrtGraph instance to update. + * \param[in] outputs The output OrtValueInfo instances. + * \param[in] outputs_len The number of output OrtValueInfo instances. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(SetGraphOutputs, _Inout_ OrtGraph* graph, + _In_reads_(outputs_len) _In_ OrtValueInfo** outputs, _In_ size_t outputs_len); + + /** \brief Add an initializer to the OrtGraph + * + * ORT will take ownership of the OrtValue and you should NOT call ReleaseOrtValue. + * + * Two options: + * + * Allocated memory: + * Use CreateTensorAsOrtValue (allocates memory) and populate the tensor with the data. + * Set `data_is_external` to false. + * + * Pre-existing memory: + * Use CreateTensorWithDataAsOrtValue or CreateTensorWithDataAndDeleterAsOrtValue to create an OrtValue + * with a tensor that contains a pointer to the existing data. + * Set `data_is_external` to true. + * + * The pointer must remain valid for the duration of the inference session. + * If using CreateTensorWithDataAsOrtValue you are responsible for freeing the memory after the inference session + * is released. + * If using CreateTensorWithDataAndDeleterAsOrtValue, ORT will free the memory using the provided deleter as + * soon as the OrtValue is no longer in use. + * + * NOTE: A tensor containing pre-existing memory MUST have 128 bytes of data or more. + * For smaller tensors use CreateTensorAsOrtValue. + * + * ONNX shape inferencing does not support external data. An initializer involved in shape inferencing is + * typically small (a single value or limited by the rank of a tensor) and uses less than 128 bytes of + * memory, so this limit acts as a simple catch-all rule to avoid issues. + * e.g. Reshape's `shape`, Clip's `min` and `max`, various ops `axes`. + * + * \param[in] graph The OrtGraph instance to update. + * \param[in] name The value name for the initializer. + * \param[in] tensor The OrtValue instance containing the tensor data. + * \param[in] data_is_external Set to true if the data is external and should not be copied. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(AddInitializerToGraph, _Inout_ OrtGraph* graph, _In_ const char* name, _In_ OrtValue* tensor, + bool data_is_external); + + /** \brief Add an OrtNode to an OrtGraph + * + * Add the node to the graph. The OrtGraph will take ownership of OrtNode and you should NOT call ReleaseOrtNode. + * + * \param[in] graph The OrtGraph instance to update. + * \param[in] node The OrtNode instance to add to the graph. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(AddNodeToGraph, _Inout_ OrtGraph* graph, _In_ OrtNode* node); + + /** \brief Create an OrtModel. + * + * Create an OrtModel. + * + * This can be used to build a new model, or to augment an existing model. + * + * \param[in] domain_names The domain names for the model. + * If augmenting an existing model add additional domains if needed. + * \param[in] opset_versions The opset versions for the model. + * If augmenting an existing model add additional opset versions if needed. + * \param[in] opset_entries_len The number of domain_names and opset_versions entries. + * Domain and opset entries should be 1:1 + * \param[out] model The OrtModel instance. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateModel, + _In_reads_(opset_entries_len) const char* const* domain_names, + _In_reads_(opset_entries_len) const int* opset_versions, + size_t opset_entries_len, + _Outptr_ OrtModel** model); + + /** \brief Add an OrtGraph to an OrtModel. + * + * Add the graph to a model. This should be called once when creating a new model. + * + * The OrtModel takes ownership of the OrtGraph and you should NOT call ReleaseOrtGraph. + * + * \param[in] model The OrtModel instance to update. + * \param[in] graph The OrtGraph instance to add to the model. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(AddGraphToModel, _Inout_ OrtModel* model, _In_ OrtGraph* graph); + + /** \brief Create an OrtSession using the OrtModel. + * + * Create an inference session using the OrtModel instance. + * The OrtModel should have been populated with an OrtGraph containing nodes and initializers, and SetGraphInputs + * and SetGraphOutputs must have been called. + * This will validate the model, run optimizers, and prepare the session for inferencing. + * + * ReleaseOrtModel must be called to free the OrtModel after session creation. + * + * \param[in] env The OrtEnv instance. + * \param[in] model The OrtModel instance. + * \param[in] options The OrtSessionOptions instance. + * \param[out] out The OrtSession instance. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateSessionFromModel, _In_ const OrtEnv* env, _In_ const OrtModel* model, + _In_ const OrtSessionOptions* options, _Outptr_ OrtSession** out); + + /** \brief Create an OrtSession to augment an existing model. + * + * Create an OrtSession with an existing model that will be augmented with additional nodes and initializers. + * Nodes can be added before or after the existing nodes in the model. ONNX Runtime will connect the nodes when the + * model is finalized. + * + * To add nodes and initializers to the existing model, first create an OrtModel using CreateModel. + * Add nodes and initializers to the OrtModel using AddNodeToGraph and AddInitializerToGraph. + * Graph inputs/outputs should be updated with SetGraphInputs and SetGraphOutputs as needed to reflect changes made + * by the new nodes. The list of graph inputs/outputs should be for the overall model and not just the new nodes. + * + * Add the new information from the OrtModel to the original model using ApplyModelToSession, and prepare the + * session for inferencing by calling FinalizeModelEditorSession. + * + * \param{in} env The OrtEnv instance. + * \param{in} model_path The path to the existing ONNX model to augment. + * \param{in} options The OrtSessionOptions instance. + * \param{out} out The created OrtSession instance. + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateModelEditorSession, _In_ const OrtEnv* env, _In_ const ORTCHAR_T* model_path, + _In_ const OrtSessionOptions* options, + _Outptr_ OrtSession** out); + + /** \brief Create an OrtSession to augment an existing model. + * + * Create an OrtSession with an existing model that will be augmented with additional nodes and initializers. + * Nodes can be added before or after the existing nodes in the model. ONNX Runtime will connect the nodes when the + * model is finalized. + * + * To add nodes and initializers to the existing model, first create an OrtModel using CreateModel. + * Add nodes and initializers to the OrtModel using AddNodeToGraph and AddInitializerToGraph. + * Graph inputs/outputs should be updated with SetGraphInputs and SetGraphOutputs as needed to reflect changes made + * by the new nodes. The list of graph inputs/outputs should be for the overall model and not just the new nodes. + * + * Add the new information from the OrtModel to the original model using ApplyModelToSession, and prepare the + * session for inferencing by calling FinalizeModelEditorSession. + * + * \param{in} env The OrtEnv instance. + * \param{in} model_data The model data for the existing model to augment. + * \param{in} model_data_length The length of the model data. + * \param{in} options The OrtSessionOptions instance. + * \param{out} out The created OrtSession instance. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateModelEditorSessionFromArray, _In_ const OrtEnv* env, + _In_ const void* model_data, size_t model_data_length, + _In_ const OrtSessionOptions* options, + _Outptr_ OrtSession** out); + + /** \brief Query the session for the opset version of a domain. + * + * When using the Model Editor API to augment a model, any new nodes must conform to the opset version of the + * original model. To do that the user must be able to discover that opset version. + * Returns an error if the domain is not used in the model. + * + * \param[in] session OrtSession to query + * \param[in] domain Domain to query. The ONNX domain is an empty string. + * \param[out] opset The opset version of the domain. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(SessionGetOpsetForDomain, _In_ const OrtSession* session, _In_ const char* domain, _Out_ int* opset); + + /** \brief Apply changes to augment the ONNX model in a session created using CreateModelEditorSession[FromArray] + * + * Adds new nodes and updates graph inputs/outputs using `model` to augment the original ONNX model in the session. + * All changes will be validated. + * Call FinalizeModelEditorSession to prepare the session for inferencing. + * + * Existing input/outputs will only be updated if the OrtGraph inputs/outputs are set in the OrtModel. + * i.e. you don't need to call SetGraphInputs/SetGraphOutputs if they are unchanged. + * + * ReleaseOrtModel must be called to free the OrtModel after it is applied to the session. + * + * \param[in] session OrtSession to update. Session must have been created using CreateModelEditorSession[FromArray]. + * \param[in] model OrtModel containing new nodes, new initializers, and updated graph input and/or output info. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(ApplyModelToModelEditorSession, _Inout_ OrtSession* session, _In_ OrtModel* model); + + /** \brief Finalize the Model Editor session that was created using CreateModelEditorSession[FromArray]. + * + * Finalize the Model Editor session that augmented an ONNX model by adding new nodes. + * This will run optimizers and prepare the session for inferencing. + * + * \param[in] session OrtSession to finalize. Session must have been created using CreateModelEditorSession[FromArray]. + * \param[in] options OrtSessionOptions to use for the session. + * \param[in] prepacked_weights_container Optional OrtPrepackedWeightsContainer to use for the session. + Set to nullptr if not used. + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(FinalizeModelEditorSession, _Inout_ OrtSession* session, _In_ const OrtSessionOptions* options, + _In_opt_ OrtPrepackedWeightsContainer* prepacked_weights_container); +#endif // !defined(ORT_MINIMAL_BUILD) +}; + +/** + * ORT Compile API + */ + +/** + * \brief The OrtCompileApi struct provides functions to compile ONNX models. + * + * Execution providers that support compilation fuse a subgraph into an EPContext node that wraps a provider-specific + * binary representation of the subgraph. + * For more details about the EPContext design, refer to: + * \htmlonly + * EPContext design document. + * \endhtmlonly + * + * Example (error handling not shown): + * OrtStatus* status = NULL; + * OrtCompileApi* compile_api = ort_api->GetCompileApi(); + * OrtModelCompilationOptions* compile_options = NULL; + * + * status = compile_api->CreateModelCompilationOptionsFromSessionOptions(env, session_options, &compile_options); + * status = compile_api->ModelCompilationOptions_SetInputModelPath(compile_options, ORT_TSTR("model.onnx")); + * status = compile_api->ModelCompilationOptions_SetOutputModelPath(compile_options, ORT_TSTR("model.compiled.onnx")); + * status = compile_api->CompileModel(env, compile_options); + * compile_api->ReleaseModelCompilationOptions(compile_options); + * + * \since Version 1.22. + */ +struct OrtCompileApi { + /// @} + /// \name OrtModelCompilationOptions + /// @{ + ORT_CLASS_RELEASE(ModelCompilationOptions); + + /** \brief Creates an OrtModelCompilationOptions object from an existing OrtSessionOptions object. + * + * An OrtModelCompilationOptions object contains the settings used to generate a compiled ONNX model. + * The OrtSessionOptions object has the execution providers with which the model will be compiled. + * + * ReleaseOrtModelCompilationsOptions must be called to free the OrtModelCompilationOptions after calling + * CompileModel. + * + * \param[in] env OrtEnv object. + * \param[in] session_options The OrtSessionOptions instance from which to create the OrtModelCompilationOptions. + * \param[out] out The created OrtModelCompilationOptions instance. + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateModelCompilationOptionsFromSessionOptions, _In_ const OrtEnv* env, + _In_ const OrtSessionOptions* session_options, _Outptr_ OrtModelCompilationOptions** out); + + /** \brief Sets the file path to the input ONNX model to compile. + * + * The input model's location (e.g., file path or memory buffer) must be set with either + * ModelCompilationOptions_SetInputModelPath or ModelCompilationOptions_SetInputModelFromBuffer. + * + * \param[in] model_compile_options The OrtModelCompilationOptions instance. + * \param[in] input_model_path Null terminated string of the path (wchar on Windows, char otherwise). + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(ModelCompilationOptions_SetInputModelPath, _In_ OrtModelCompilationOptions* model_compile_options, + _In_ const ORTCHAR_T* input_model_path); + + /** \brief Sets the buffer that stores the bytes of the loaded ONNX model to compile. + * + * The input model's location (e.g., file path or memory buffer) must be set with either + * ModelCompilationOptions_SetInputModelPath or ModelCompilationOptions_SetInputModelFromBuffer. + * + * \param[in] model_compile_options The OrtModelCompilationOptions instance. + * \param[in] input_model_data Buffer containing the loaded ONNX model bytes. + * \param[in] input_model_data_size The number of bytes in the `input_model_data` buffer. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(ModelCompilationOptions_SetInputModelFromBuffer, + _In_ OrtModelCompilationOptions* model_compile_options, + _In_ const void* input_model_data, + size_t input_model_data_size); + + /** \brief Sets the file path for the output ONNX model generated by CompileModel. + * + * The output model's location (e.g., file path or memory buffer) can be set with either + * ModelCompilationOptions_SetOutputModelPath or ModelCompilationOptions_SetOutputModelBuffer. + * + * If the output model's location is not set, ONNX Runtime will generate an output file with a path based on + * the input model's file path. Examples: + * /Path/my_model.onnx -> /Path/my_model_ctx.onnx + * /Path/my_model -> /Path/my_model_ctx.onnx + * + * \param[in] model_compile_options The OrtModelCompilationOptions instance. + * \param[in] output_model_path Null terminated string of the path (wchar on Windows, char otherwise). + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(ModelCompilationOptions_SetOutputModelPath, _In_ OrtModelCompilationOptions* model_compile_options, + _In_ const ORTCHAR_T* output_model_path); + + /** \brief Optionally sets the file that should store external initializers for the compiled ONNX model. + * If not set, initializers are stored within the model. + * + * Only initializers for nodes that were not compiled are stored in the external initializers file. + * Compiled nodes contain their initializer data within the `ep_cache_context` attribute of EPContext nodes. + * Refer to ModelCompilationOptions_SetEpContextEmbedMode. + * + * \param[in] model_compile_options The OrtModelCompilationOptions instance. + * \param[in] external_initializers_file_path Null terminated string of the path to the file. + * \param[in] external_initializers_size_threshold Initializers larger than this threshold are stored in the file. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(ModelCompilationOptions_SetOutputModelExternalInitializersFile, + _In_ OrtModelCompilationOptions* model_compile_options, + _In_ const ORTCHAR_T* external_initializers_file_path, + size_t external_initializers_size_threshold); + + /** \brief Configures model compilation to store the output compiled ONNX model in a buffer. + * + * The caller passes an OrtAllocator that ONNX Runtime uses to allocate memory for the buffer. + * + * The output model's location (e.g., file path or memory buffer) can be set with either + * ModelCompilationOptions_SetOutputModelPath or ModelCompilationOptions_SetOutputModelBuffer. + * + * If the output model's location is not set, ONNX Runtime will generate an output file with a path based on + * the input model's file path. Examples: + * /Path/my_model.onnx -> /Path/my_model_ctx.onnx + * /Path/my_model -> /Path/my_model_ctx.onnx + * + * \param[in] model_compile_options The OrtModelCompilationOptions instance. + * \param[in] allocator The allocator used to allocate the buffer for the compiled model. + * \param[out] output_model_buffer_ptr Pointer to the buffer that stores the compiled model. + * \param[out] output_model_buffer_size_ptr Pointer set to the size of output model in bytes. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(ModelCompilationOptions_SetOutputModelBuffer, + _In_ OrtModelCompilationOptions* model_compile_options, + _Inout_ OrtAllocator* allocator, + _Outptr_ void** output_model_buffer_ptr, + _Out_ size_t* output_model_buffer_size_ptr); + + /** \brief Enables or disables the embedding of EPContext binary data into the `ep_cache_context` attribute + * of EPContext nodes. Defaults to false. + * + * If enabled, the `ep_cache_context` attribute of EPContext nodes will store the context binary data, which may + * include weights for compiled subgraphs. + * + * If disabled, the `ep_cache_context` attribute of EPContext nodes will contain the path to the file containing the + * context binary data. The path is set by the execution provider creating the EPContext node. + * + * More details relate to EPContext design refers to: + * \htmlonly + * EPContext design document. + * \endhtmlonly + * + * \param[in] model_compile_options The OrtModelCompilationOptions instance. + * \param[in] embed_ep_context_in_model True to embed EPContext binary data into the EPContext node + * `ep_cache_context` attributes. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(ModelCompilationOptions_SetEpContextEmbedMode, _In_ OrtModelCompilationOptions* model_compile_options, + bool embed_ep_context_in_model); + + /** \brief Compiles an input ONNX model with the given compilation options. + * + * \param[in] env OrtEnv object. + * \param[in] model_options The compilation options that defines compilation options for a model. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CompileModel, _In_ const OrtEnv* env, _In_ const OrtModelCompilationOptions* model_options); +}; + +ORT_RUNTIME_CLASS(Ep); +ORT_RUNTIME_CLASS(EpFactory); + +struct OrtEpApi { + /** \brief Create an OrtEpDevice for the EP and an OrtHardwareDevice. + * \param[in] ep_factory Execution provider factory that is creating the instance. + * \param[in] hardware_device Hardware device that the EP can utilize. + * \param[in] ep_metadata Optional OrtKeyValuePairs instance for execution provider metadata that may be used + * during execution provider selection and passed to CreateEp. + * ep_device will copy this instance and the user should call ReleaseKeyValuePairs. + * \param[in] ep_options Optional OrtKeyValuePairs instance for execution provider options that will be added + * to the Session configuration options if the execution provider is selected. + * ep_device will copy this instance and the user should call ReleaseKeyValuePairs. + * \param ep_device OrtExecutionDevice that is created. + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateEpDevice, _In_ OrtEpFactory* ep_factory, + _In_ const OrtHardwareDevice* hardware_device, + _In_opt_ const OrtKeyValuePairs* ep_metadata, + _In_opt_ const OrtKeyValuePairs* ep_options, + _Out_ OrtEpDevice** ep_device); + + ORT_CLASS_RELEASE(EpDevice); +}; + +/** + * \brief The OrtEp struct provides functions to implement for an execution provider. + * \since Version 1.22. + */ +struct OrtEp { + /** \brief The ONNX Runtime version the execution provider was compiled with. + * + * Implementation should set to ORT_API_VERSION. + * ORT will use this to ensure it does not call functions that were not available when the library was compiled. + * + * \since Version 1.22. + */ + uint32_t ort_version_supported; + + /** \brief Get the execution provider name. + * + * \param[in] this_ptr The OrtEp instance. + * \return The execution provider name. + * + * \note Returned string is owned by ORT and valid until UnregisterExecutionProviderLibrary is called. + * + * \since Version 1.22. + */ + const char*(ORT_API_CALL* GetName)(const OrtEp* this_ptr); + + // OrtStatus* GetCapability(OrtEp* ep, const OrtGraph* graph, + // size_t* num_supported_subgraphs, + // OrtIndexedSubgraph** supported_subgraphs, OrtAllocator* allocator); + + // OrtStatus* Compile(OrtEp* ep, const OrtGraph** graphs, OrtNode** fused_graph_nodes, + // size_t count, OrtNodeComputeInfo* node_compute_infos); + + // TODO: Implement OrtEpApi and the complete OrtEp interface as the next step. +}; + +/** \brief The function signature that ORT will call to create OrtEpFactory instances. + * + * This must be available in a function called 'CreateEpFactories' in the execution provider library. + * + * \param[in] registered_name The name the execution library is registered with by RegisterExecutionProviderLibrary + * \param[in] ort_api_base The OrtApiBase instance that is used by the factory to get the OrtApi instance for the + * version of ORT that the library was compiled against. + * \param[in,out] factories The implementation should create and add OrtEpFactory instances to this + * pre-allocated array. + * i.e. usage is `factories[0] = new MyEpFactory();` + * \param[in] max_factories The maximum number of OrtEpFactory instances that can be added to `factories`. + * Current default is to allow 4 factories. This can be increased in the future if needed. + * \param[out] num_factories The number of OrtEpFactory instances created by the factory and added to `factories`. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ +typedef OrtStatus* (*CreateEpApiFactoriesFn)(_In_ const char* registered_name, _In_ const OrtApiBase* ort_api_base, + _Inout_ OrtEpFactory** factories, _In_ size_t max_factories, + _Out_ size_t* num_factories); + +/** \brief The function signature that ORT will call to release an OrtEpFactory instance. + * + * This must be available in a function called 'ReleaseEpFactory' in the execution provider library. + * + * \param[in] factory The OrtEpFactory instance to release. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ +typedef OrtStatus* (*ReleaseEpApiFactoryFn)(_In_ OrtEpFactory* factory); + +/** + * \brief The OrtEpFactory provides functions to create and manage execution providers. + * \since Version 1.22. + */ +struct OrtEpFactory { + /** \brief The ONNX Runtime version the execution provider was compiled with. + * + * Implementation should set to ORT_API_VERSION. + * ORT will use this to ensure it does not call functions that were not available when the library was compiled. + * + * \since Version 1.22. + */ + uint32_t ort_version_supported; + + /** \brief Get the name the of the execution provider that the factory creates. + * + * \param[in] this_ptr The OrtEpFactory instance. + * \return The name of the execution provider the factory creates. + * + * \since Version 1.22. + */ + const char*(ORT_API_CALL* GetName)(const OrtEpFactory* this_ptr); + + /** \brief Get the name of vendor who owns the execution provider that the factory creates. + * + * \param[in] this_ptr The OrtEpFactory instance. + * \return vendor The vendor name of the execution provider the factory creates. + * + * \since Version 1.22. + */ + const char*(ORT_API_CALL* GetVendor)(const OrtEpFactory* this_ptr); // return EP vendor + + /** \brief Get information from the execution provider if it supports the OrtHardwareDevice. + * + * \param[in] this_ptr The OrtEpFactory instance. + * Non-const as the factory is passed through to the CreateEp call via the OrtEpDevice. + * \param[in] devices The OrtHardwareDevice instances that are available. + * \param[in] num_devices The number of OrtHardwareDevice instances. + * \param[out] ep_devices OrtEpDevice instances for each OrtHardwareDevice that the EP can use. + * The implementation should call OrtEpApi::CreateEpDevice to create, and add the OrtEpDevice + * instances to this pre-allocated array. ORT will take ownership of the values returned. + * i.e. usage is `ep_devices[0] = ;` + * \param[in] max_ep_devices The maximum number of OrtEpDevices that can be added to ep_devices. + * Current default is 8. This can be increased if needed. + * \param[out] num_ep_devices The number of EP devices added to ep_devices. + * \return true if the factory can create an execution provider that uses `device`. + * + * \note ORT will take ownership or ep_metadata and/or ep_options if they are not null. + * + * \since Version 1.22. + */ + OrtStatus*(ORT_API_CALL* GetSupportedDevices)(_In_ OrtEpFactory* this_ptr, + _In_reads_(num_devices) const OrtHardwareDevice* const* devices, + _In_ size_t num_devices, + _Inout_ OrtEpDevice** ep_devices, + _In_ size_t max_ep_devices, + _Out_ size_t* num_ep_devices); + + /** \brief Function to create an OrtEp instance for use in a Session. + * + * ORT will call ReleaseEp to release the instance when it is no longer needed. + * + * \param[in] this_ptr The OrtEpFactory instance. + * \param[in] devices The OrtHardwareDevice instances that the execution provider was selected to use. + * \param[in] ep_metadata_pairs Execution provider metadata that was provided to OrtEpApi::CreateEpDevice, for each + * device. + * \param[in] num_devices The number of devices the execution provider was selected for. + * \param[in] session_options The OrtSessionOptions instance that contains the configuration options for the + * session. This will include ep_options from GetSupportedDevices as well as any + * user provided overrides. + * Execution provider options will have been added with a prefix of 'ep..'. + * The OrtSessionOptions instance will NOT be valid after this call and should not be + * stored for later use. + * \param[in] logger The OrtLogger instance for the session that the execution provider should use for logging. + * \param[out] ep The OrtEp instance created by the factory. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version . This is a placeholder. + */ + OrtStatus*(ORT_API_CALL* CreateEp)(_In_ OrtEpFactory* this_ptr, + _In_reads_(num_devices) const OrtHardwareDevice* const* devices, + _In_reads_(num_devices) const OrtKeyValuePairs* const* ep_metadata_pairs, + _In_ size_t num_devices, + _In_ const OrtSessionOptions* session_options, + _In_ const OrtLogger* logger, _Outptr_ OrtEp** ep); + + /** \brief Release the OrtEp instance. + * + * \param[in] this_ptr The OrtEpFactory instance. + * \param[in] ep The OrtEp instance to release. + * + * \since Version . This is a placeholder. + */ + void(ORT_API_CALL* ReleaseEp)(OrtEpFactory* this_ptr, struct OrtEp* ep); +}; + +/* + * This is the old way to add the CUDA provider to the session, please use SessionOptionsAppendExecutionProvider_CUDA above to access the latest functionality + * This function always exists, but will only succeed if Onnxruntime was built with CUDA support and the CUDA provider shared library exists + * + * \param device_id CUDA device id, starts from zero. + */ +ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_CUDA, _In_ OrtSessionOptions* options, int device_id); + +/* + * This is the old way to add the ROCm provider to the session, please use + * SessionOptionsAppendExecutionProvider_ROCM above to access the latest functionality + * This function always exists, but will only succeed if Onnxruntime was built with + * HIP support and the ROCm provider shared library exists + * + * \param device_id HIP device id, starts from zero. + */ +ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_ROCM, _In_ OrtSessionOptions* options, int device_id); + +/* + * This is the old way to add the MIGraphX provider to the session, please use + * SessionOptionsAppendExecutionProvider_MIGraphX above to access the latest functionality + * This function always exists, but will only succeed if Onnxruntime was built with + * HIP support and the MIGraphX provider shared library exists + * + * \param device_id HIP device id, starts from zero. + */ +ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_MIGraphX, _In_ OrtSessionOptions* options, int device_id); + +/* + * This is the old way to add the oneDNN provider to the session, please use + * SessionOptionsAppendExecutionProvider_oneDNN above to access the latest functionality + * This function always exists, but will only succeed if Onnxruntime was built with + * oneDNN support and the oneDNN provider shared library exists + * + * \param use_arena zero: false. non-zero: true. + */ +ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_Dnnl, _In_ OrtSessionOptions* options, int use_arena); + +/* + * This is the old way to add the TensorRT provider to the session, please use SessionOptionsAppendExecutionProvider_TensorRT_V2 above to access the latest functionality + * This function always exists, but will only succeed if Onnxruntime was built with TensorRT support and the TensorRT provider shared library exists + * + * \param device_id CUDA device id, starts from zero. + */ +ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_Tensorrt, _In_ OrtSessionOptions* options, int device_id); + +#ifdef __cplusplus +} +#endif +/// @} diff --git a/3rdParty/ONNX/onnxruntime_cxx_api.h b/3rdParty/ONNX/onnxruntime_cxx_api.h index bc6f381bb8..1bf2e2f104 100644 --- a/3rdParty/ONNX/onnxruntime_cxx_api.h +++ b/3rdParty/ONNX/onnxruntime_cxx_api.h @@ -1,2865 +1,2865 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// Summary: The Ort C++ API is a header only wrapper around the Ort C API. -// -// The C++ API simplifies usage by returning values directly instead of error codes, throwing exceptions on errors -// and automatically releasing resources in the destructors. The primary purpose of C++ API is exception safety so -// all the resources follow RAII and do not leak memory. -// -// Each of the C++ wrapper classes holds only a pointer to the C internal object. Treat them like smart pointers. -// To create an empty object, pass 'nullptr' to the constructor (for example, Env e{nullptr};). However, you can't use them -// until you assign an instance that actually holds an underlying object. -// -// For Ort objects only move assignment between objects is allowed, there are no copy constructors. -// Some objects have explicit 'Clone' methods for this purpose. -// -// ConstXXXX types are copyable since they do not own the underlying C object, so you can pass them to functions as arguments -// by value or by reference. ConstXXXX types are restricted to const only interfaces. -// -// UnownedXXXX are similar to ConstXXXX but also allow non-const interfaces. -// -// The lifetime of the corresponding owning object must eclipse the lifetimes of the ConstXXXX/UnownedXXXX types. They exists so you do not -// have to fallback to C types and the API with the usual pitfalls. In general, do not use C API from your C++ code. - -#pragma once -#include "onnxruntime_c_api.h" -#include "onnxruntime_float16.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef ORT_NO_EXCEPTIONS -#include -#endif - -/** \brief All C++ Onnxruntime APIs are defined inside this namespace - * - */ -namespace Ort { - -/** \brief All C++ methods that can fail will throw an exception of this type - * - * If ORT_NO_EXCEPTIONS is defined, then any error will result in a call to abort() - */ -struct Exception : std::exception { - Exception(std::string&& string, OrtErrorCode code) : message_{std::move(string)}, code_{code} {} - - OrtErrorCode GetOrtErrorCode() const { return code_; } - const char* what() const noexcept override { return message_.c_str(); } - - private: - std::string message_; - OrtErrorCode code_; -}; - -#ifdef ORT_NO_EXCEPTIONS -// The #ifndef is for the very special case where the user of this library wants to define their own way of handling errors. -// NOTE: This header expects control flow to not continue after calling ORT_CXX_API_THROW -#ifndef ORT_CXX_API_THROW -#define ORT_CXX_API_THROW(string, code) \ - do { \ - std::cerr << Ort::Exception(string, code) \ - .what() \ - << std::endl; \ - abort(); \ - } while (false) -#endif -#else -#define ORT_CXX_API_THROW(string, code) \ - throw Ort::Exception(string, code) -#endif - -// This is used internally by the C++ API. This class holds the global variable that points to the OrtApi, -// it's in a template so that we can define a global variable in a header and make -// it transparent to the users of the API. -template -struct Global { - static const OrtApi* api_; -}; - -// If macro ORT_API_MANUAL_INIT is defined, no static initialization will be performed. Instead, user must call InitApi() before using it. -template -#ifdef ORT_API_MANUAL_INIT -const OrtApi* Global::api_{}; -inline void InitApi() noexcept { Global::api_ = OrtGetApiBase()->GetApi(ORT_API_VERSION); } - -// Used by custom operator libraries that are not linked to onnxruntime. Sets the global API object, which is -// required by C++ APIs. -// -// Example mycustomop.cc: -// -// #define ORT_API_MANUAL_INIT -// #include -// #undef ORT_API_MANUAL_INIT -// -// OrtStatus* ORT_API_CALL RegisterCustomOps(OrtSessionOptions* options, const OrtApiBase* api_base) { -// Ort::InitApi(api_base->GetApi(ORT_API_VERSION)); -// // ... -// } -// -inline void InitApi(const OrtApi* api) noexcept { Global::api_ = api; } -#else -#if defined(_MSC_VER) && !defined(__clang__) -#pragma warning(push) -// "Global initializer calls a non-constexpr function." Therefore you can't use ORT APIs in the other global initializers. -// Please define ORT_API_MANUAL_INIT if it conerns you. -#pragma warning(disable : 26426) -#endif -const OrtApi* Global::api_ = OrtGetApiBase()->GetApi(ORT_API_VERSION); -#if defined(_MSC_VER) && !defined(__clang__) -#pragma warning(pop) -#endif -#endif - -/// This returns a reference to the ORT C API. -inline const OrtApi& GetApi() noexcept { return *Global::api_; } - -/// -/// This function returns the onnxruntime version string -/// -/// version string major.minor.rev -std::string GetVersionString(); - -/// -/// This function returns the onnxruntime build information: including git branch, -/// git commit id, build type(Debug/Release/RelWithDebInfo) and cmake cpp flags. -/// -/// string -std::string GetBuildInfoString(); - -/// -/// This is a C++ wrapper for OrtApi::GetAvailableProviders() and -/// returns a vector of strings representing the available execution providers. -/// -/// vector of strings -std::vector GetAvailableProviders(); - -/// -/// This returns a reference to the ORT C Model Editor API. Used if building or augmenting a model at runtime. -/// -/// ORT C Model Editor API reference -inline const OrtModelEditorApi& GetModelEditorApi() { - auto* api = GetApi().GetModelEditorApi(); - if (api == nullptr) { - // minimal build - ORT_CXX_API_THROW("Model Editor API is not available in this build", ORT_FAIL); - } - - return *api; -} - -/// -/// This returns a reference to the ORT C Compile API. Used if compiling a model at runtime. -/// -/// ORT C Compile API reference -inline const OrtCompileApi& GetCompileApi() { - auto* api = GetApi().GetCompileApi(); - if (api == nullptr) { - // minimal build - ORT_CXX_API_THROW("Compile API is not available in this build", ORT_FAIL); - } - - return *api; -} - -/// -/// This returns a reference to the ORT C EP API. Used if authoring a plugin execution provider. -/// -/// ORT C EP API reference -inline const OrtEpApi& GetEpApi() { - auto* api = GetApi().GetEpApi(); - if (api == nullptr) { - // minimal build - ORT_CXX_API_THROW("EP API is not available in this build", ORT_FAIL); - } - - return *api; -} - -/** \brief IEEE 754 half-precision floating point data type - * - * \details This struct is used for converting float to float16 and back - * so the user could feed inputs and fetch outputs using these type. - * - * The size of the structure should align with uint16_t and one can freely cast - * uint16_t buffers to/from Ort::Float16_t to feed and retrieve data. - * - * \code{.unparsed} - * // This example demonstrates converion from float to float16 - * constexpr float values[] = {1.f, 2.f, 3.f, 4.f, 5.f}; - * std::vector fp16_values; - * fp16_values.reserve(std::size(values)); - * std::transform(std::begin(values), std::end(values), std::back_inserter(fp16_values), - * [](float value) { return Ort::Float16_t(value); }); - * - * \endcode - */ -struct Float16_t : onnxruntime_float16::Float16Impl { - private: - /// - /// Constructor from a 16-bit representation of a float16 value - /// No conversion is done here. - /// - /// 16-bit representation - constexpr explicit Float16_t(uint16_t v) noexcept { val = v; } - - public: - using Base = onnxruntime_float16::Float16Impl; - - /// - /// Default constructor - /// - Float16_t() = default; - - /// - /// Explicit conversion to uint16_t representation of float16. - /// - /// uint16_t bit representation of float16 - /// new instance of Float16_t - constexpr static Float16_t FromBits(uint16_t v) noexcept { return Float16_t(v); } - - /// - /// __ctor from float. Float is converted into float16 16-bit representation. - /// - /// float value - explicit Float16_t(float v) noexcept { val = Base::ToUint16Impl(v); } - - /// - /// Converts float16 to float - /// - /// float representation of float16 value - float ToFloat() const noexcept { return Base::ToFloatImpl(); } - - /// - /// Checks if the value is negative - /// - /// true if negative - using Base::IsNegative; - - /// - /// Tests if the value is NaN - /// - /// true if NaN - using Base::IsNaN; - - /// - /// Tests if the value is finite - /// - /// true if finite - using Base::IsFinite; - - /// - /// Tests if the value represents positive infinity. - /// - /// true if positive infinity - using Base::IsPositiveInfinity; - - /// - /// Tests if the value represents negative infinity - /// - /// true if negative infinity - using Base::IsNegativeInfinity; - - /// - /// Tests if the value is either positive or negative infinity. - /// - /// True if absolute value is infinity - using Base::IsInfinity; - - /// - /// Tests if the value is NaN or zero. Useful for comparisons. - /// - /// True if NaN or zero. - using Base::IsNaNOrZero; - - /// - /// Tests if the value is normal (not zero, subnormal, infinite, or NaN). - /// - /// True if so - using Base::IsNormal; - - /// - /// Tests if the value is subnormal (denormal). - /// - /// True if so - using Base::IsSubnormal; - - /// - /// Creates an instance that represents absolute value. - /// - /// Absolute value - using Base::Abs; - - /// - /// Creates a new instance with the sign flipped. - /// - /// Flipped sign instance - using Base::Negate; - - /// - /// IEEE defines that positive and negative zero are equal, this gives us a quick equality check - /// for two values by or'ing the private bits together and stripping the sign. They are both zero, - /// and therefore equivalent, if the resulting value is still zero. - /// - /// first value - /// second value - /// True if both arguments represent zero - using Base::AreZero; - - /// - /// User defined conversion operator. Converts Float16_t to float. - /// - explicit operator float() const noexcept { return ToFloat(); } - - using Base::operator==; - using Base::operator!=; - using Base::operator<; -}; - -static_assert(sizeof(Float16_t) == sizeof(uint16_t), "Sizes must match"); - -/** \brief bfloat16 (Brain Floating Point) data type - * - * \details This struct is used for converting float to bfloat16 and back - * so the user could feed inputs and fetch outputs using these type. - * - * The size of the structure should align with uint16_t and one can freely cast - * uint16_t buffers to/from Ort::BFloat16_t to feed and retrieve data. - * - * \code{.unparsed} - * // This example demonstrates converion from float to float16 - * constexpr float values[] = {1.f, 2.f, 3.f, 4.f, 5.f}; - * std::vector bfp16_values; - * bfp16_values.reserve(std::size(values)); - * std::transform(std::begin(values), std::end(values), std::back_inserter(bfp16_values), - * [](float value) { return Ort::BFloat16_t(value); }); - * - * \endcode - */ -struct BFloat16_t : onnxruntime_float16::BFloat16Impl { - private: - /// - /// Constructor from a uint16_t representation of bfloat16 - /// used in FromBits() to escape overload resolution issue with - /// constructor from float. - /// No conversion is done. - /// - /// 16-bit bfloat16 value - constexpr explicit BFloat16_t(uint16_t v) noexcept { val = v; } - - public: - using Base = onnxruntime_float16::BFloat16Impl; - - BFloat16_t() = default; - - /// - /// Explicit conversion to uint16_t representation of bfloat16. - /// - /// uint16_t bit representation of bfloat16 - /// new instance of BFloat16_t - static constexpr BFloat16_t FromBits(uint16_t v) noexcept { return BFloat16_t(v); } - - /// - /// __ctor from float. Float is converted into bfloat16 16-bit representation. - /// - /// float value - explicit BFloat16_t(float v) noexcept { val = Base::ToUint16Impl(v); } - - /// - /// Converts bfloat16 to float - /// - /// float representation of bfloat16 value - float ToFloat() const noexcept { return Base::ToFloatImpl(); } - - /// - /// Checks if the value is negative - /// - /// true if negative - using Base::IsNegative; - - /// - /// Tests if the value is NaN - /// - /// true if NaN - using Base::IsNaN; - - /// - /// Tests if the value is finite - /// - /// true if finite - using Base::IsFinite; - - /// - /// Tests if the value represents positive infinity. - /// - /// true if positive infinity - using Base::IsPositiveInfinity; - - /// - /// Tests if the value represents negative infinity - /// - /// true if negative infinity - using Base::IsNegativeInfinity; - - /// - /// Tests if the value is either positive or negative infinity. - /// - /// True if absolute value is infinity - using Base::IsInfinity; - - /// - /// Tests if the value is NaN or zero. Useful for comparisons. - /// - /// True if NaN or zero. - using Base::IsNaNOrZero; - - /// - /// Tests if the value is normal (not zero, subnormal, infinite, or NaN). - /// - /// True if so - using Base::IsNormal; - - /// - /// Tests if the value is subnormal (denormal). - /// - /// True if so - using Base::IsSubnormal; - - /// - /// Creates an instance that represents absolute value. - /// - /// Absolute value - using Base::Abs; - - /// - /// Creates a new instance with the sign flipped. - /// - /// Flipped sign instance - using Base::Negate; - - /// - /// IEEE defines that positive and negative zero are equal, this gives us a quick equality check - /// for two values by or'ing the private bits together and stripping the sign. They are both zero, - /// and therefore equivalent, if the resulting value is still zero. - /// - /// first value - /// second value - /// True if both arguments represent zero - using Base::AreZero; - - /// - /// User defined conversion operator. Converts BFloat16_t to float. - /// - explicit operator float() const noexcept { return ToFloat(); } - - // We do not have an inherited impl for the below operators - // as the internal class implements them a little differently - bool operator==(const BFloat16_t& rhs) const noexcept; - bool operator!=(const BFloat16_t& rhs) const noexcept { return !(*this == rhs); } - bool operator<(const BFloat16_t& rhs) const noexcept; -}; - -static_assert(sizeof(BFloat16_t) == sizeof(uint16_t), "Sizes must match"); - -/** \brief float8e4m3fn (Float8 Floating Point) data type - * \details It is necessary for type dispatching to make use of C++ API - * The type is implicitly convertible to/from uint8_t. - * See https://onnx.ai/onnx/technical/float8.html for further details. - */ -struct Float8E4M3FN_t { - uint8_t value; - constexpr Float8E4M3FN_t() noexcept : value(0) {} - constexpr Float8E4M3FN_t(uint8_t v) noexcept : value(v) {} - constexpr operator uint8_t() const noexcept { return value; } - // nan values are treated like any other value for operator ==, != - constexpr bool operator==(const Float8E4M3FN_t& rhs) const noexcept { return value == rhs.value; }; - constexpr bool operator!=(const Float8E4M3FN_t& rhs) const noexcept { return value != rhs.value; }; -}; - -static_assert(sizeof(Float8E4M3FN_t) == sizeof(uint8_t), "Sizes must match"); - -/** \brief float8e4m3fnuz (Float8 Floating Point) data type - * \details It is necessary for type dispatching to make use of C++ API - * The type is implicitly convertible to/from uint8_t. - * See https://onnx.ai/onnx/technical/float8.html for further details. - */ -struct Float8E4M3FNUZ_t { - uint8_t value; - constexpr Float8E4M3FNUZ_t() noexcept : value(0) {} - constexpr Float8E4M3FNUZ_t(uint8_t v) noexcept : value(v) {} - constexpr operator uint8_t() const noexcept { return value; } - // nan values are treated like any other value for operator ==, != - constexpr bool operator==(const Float8E4M3FNUZ_t& rhs) const noexcept { return value == rhs.value; }; - constexpr bool operator!=(const Float8E4M3FNUZ_t& rhs) const noexcept { return value != rhs.value; }; -}; - -static_assert(sizeof(Float8E4M3FNUZ_t) == sizeof(uint8_t), "Sizes must match"); - -/** \brief float8e5m2 (Float8 Floating Point) data type - * \details It is necessary for type dispatching to make use of C++ API - * The type is implicitly convertible to/from uint8_t. - * See https://onnx.ai/onnx/technical/float8.html for further details. - */ -struct Float8E5M2_t { - uint8_t value; - constexpr Float8E5M2_t() noexcept : value(0) {} - constexpr Float8E5M2_t(uint8_t v) noexcept : value(v) {} - constexpr operator uint8_t() const noexcept { return value; } - // nan values are treated like any other value for operator ==, != - constexpr bool operator==(const Float8E5M2_t& rhs) const noexcept { return value == rhs.value; }; - constexpr bool operator!=(const Float8E5M2_t& rhs) const noexcept { return value != rhs.value; }; -}; - -static_assert(sizeof(Float8E5M2_t) == sizeof(uint8_t), "Sizes must match"); - -/** \brief float8e5m2fnuz (Float8 Floating Point) data type - * \details It is necessary for type dispatching to make use of C++ API - * The type is implicitly convertible to/from uint8_t. - * See https://onnx.ai/onnx/technical/float8.html for further details. - */ -struct Float8E5M2FNUZ_t { - uint8_t value; - constexpr Float8E5M2FNUZ_t() noexcept : value(0) {} - constexpr Float8E5M2FNUZ_t(uint8_t v) noexcept : value(v) {} - constexpr operator uint8_t() const noexcept { return value; } - // nan values are treated like any other value for operator ==, != - constexpr bool operator==(const Float8E5M2FNUZ_t& rhs) const noexcept { return value == rhs.value; }; - constexpr bool operator!=(const Float8E5M2FNUZ_t& rhs) const noexcept { return value != rhs.value; }; -}; - -static_assert(sizeof(Float8E5M2FNUZ_t) == sizeof(uint8_t), "Sizes must match"); - -namespace detail { -// This is used internally by the C++ API. This macro is to make it easy to generate overloaded methods for all of the various OrtRelease* functions for every Ort* type -// This can't be done in the C API since C doesn't have function overloading. -#define ORT_DEFINE_RELEASE(NAME) \ - inline void OrtRelease(Ort##NAME* ptr) { GetApi().Release##NAME(ptr); } - -#define ORT_DEFINE_RELEASE_FROM_API_STRUCT(NAME, API_GETTER) \ - inline void OrtRelease(Ort##NAME* ptr) { API_GETTER().Release##NAME(ptr); } - -ORT_DEFINE_RELEASE(Allocator); -ORT_DEFINE_RELEASE(MemoryInfo); -ORT_DEFINE_RELEASE(CustomOpDomain); -ORT_DEFINE_RELEASE(ThreadingOptions); -ORT_DEFINE_RELEASE(Env); -ORT_DEFINE_RELEASE(RunOptions); -ORT_DEFINE_RELEASE(LoraAdapter); -ORT_DEFINE_RELEASE(Session); -ORT_DEFINE_RELEASE(SessionOptions); -ORT_DEFINE_RELEASE(TensorTypeAndShapeInfo); -ORT_DEFINE_RELEASE(SequenceTypeInfo); -ORT_DEFINE_RELEASE(MapTypeInfo); -ORT_DEFINE_RELEASE(TypeInfo); -ORT_DEFINE_RELEASE(Value); -ORT_DEFINE_RELEASE(ModelMetadata); -ORT_DEFINE_RELEASE(IoBinding); -ORT_DEFINE_RELEASE(ArenaCfg); -ORT_DEFINE_RELEASE(Status); -ORT_DEFINE_RELEASE(OpAttr); -ORT_DEFINE_RELEASE(Op); -ORT_DEFINE_RELEASE(KernelInfo); -ORT_DEFINE_RELEASE(ValueInfo); -ORT_DEFINE_RELEASE(Node); -ORT_DEFINE_RELEASE(Graph); -ORT_DEFINE_RELEASE(Model); -ORT_DEFINE_RELEASE(KeyValuePairs) -ORT_DEFINE_RELEASE_FROM_API_STRUCT(ModelCompilationOptions, GetCompileApi); -ORT_DEFINE_RELEASE_FROM_API_STRUCT(EpDevice, GetEpApi); - -#undef ORT_DEFINE_RELEASE -#undef ORT_DEFINE_RELEASE_FROM_API_STRUCT - -/** \brief This is a tagging template type. Use it with Base to indicate that the C++ interface object - * has no ownership of the underlying C object. - */ -template -struct Unowned { - using Type = T; -}; - -/** \brief Used internally by the C++ API. C++ wrapper types inherit from this. - * This is a zero cost abstraction to wrap the C API objects and delete them on destruction. - * - * All of the C++ classes - * a) serve as containers for pointers to objects that are created by the underlying C API. - * Their size is just a pointer size, no need to dynamically allocate them. Use them by value. - * b) Each of struct XXXX, XXX instances function as smart pointers to the underlying C API objects. - * they would release objects owned automatically when going out of scope, they are move-only. - * c) ConstXXXX and UnownedXXX structs function as non-owning, copyable containers for the above pointers. - * ConstXXXX allow calling const interfaces only. They give access to objects that are owned by somebody else - * such as Onnxruntime or instances of XXXX classes. - * d) serve convenient interfaces that return C++ objects and further enhance exception and type safety so they can be used - * in C++ code. - * - */ - -/// -/// This is a non-const pointer holder that is move-only. Disposes of the pointer on destruction. -/// -template -struct Base { - using contained_type = T; - - constexpr Base() = default; - constexpr explicit Base(contained_type* p) noexcept : p_{p} {} - ~Base() { - OrtRelease(p_); - } - - Base(const Base&) = delete; - Base& operator=(const Base&) = delete; - - Base(Base&& v) noexcept : p_{v.p_} { v.p_ = nullptr; } - Base& operator=(Base&& v) noexcept { - OrtRelease(p_); - p_ = v.release(); - return *this; - } - - constexpr operator contained_type*() const noexcept { return p_; } - - /// \brief Relinquishes ownership of the contained C object pointer - /// The underlying object is not destroyed - contained_type* release() { - T* p = p_; - p_ = nullptr; - return p; - } - - protected: - contained_type* p_{}; -}; - -// Undefined. For const types use Base> -template -struct Base; - -/// -/// Covers unowned pointers owned by either the ORT -/// or some other instance of CPP wrappers. -/// Used for ConstXXX and UnownedXXXX types that are copyable. -/// Also convenient to wrap raw OrtXX pointers . -/// -/// -template -struct Base> { - using contained_type = typename Unowned::Type; - - constexpr Base() = default; - constexpr explicit Base(contained_type* p) noexcept : p_{p} {} - - ~Base() = default; - - Base(const Base&) = default; - Base& operator=(const Base&) = default; - - Base(Base&& v) noexcept : p_{v.p_} { v.p_ = nullptr; } - Base& operator=(Base&& v) noexcept { - p_ = nullptr; - std::swap(p_, v.p_); - return *this; - } - - constexpr operator contained_type*() const noexcept { return p_; } - - protected: - contained_type* p_{}; -}; - -// Light functor to release memory with OrtAllocator -struct AllocatedFree { - OrtAllocator* allocator_; - explicit AllocatedFree(OrtAllocator* allocator) - : allocator_(allocator) {} - void operator()(void* ptr) const { - if (ptr) allocator_->Free(allocator_, ptr); - } -}; - -} // namespace detail - -struct AllocatorWithDefaultOptions; -struct Env; -struct EpDevice; -struct Graph; -struct Model; -struct Node; -struct ModelMetadata; -struct TypeInfo; -struct Value; -struct ValueInfo; - -/** \brief unique_ptr typedef used to own strings allocated by OrtAllocators - * and release them at the end of the scope. The lifespan of the given allocator - * must eclipse the lifespan of AllocatedStringPtr instance - */ -using AllocatedStringPtr = std::unique_ptr; - -/** \brief The Status that holds ownership of OrtStatus received from C API - * Use it to safely destroy OrtStatus* returned from the C API. Use appropriate - * constructors to construct an instance of a Status object from exceptions. - */ -struct Status : detail::Base { - using Base = detail::Base; - using Base::Base; - - explicit Status(std::nullptr_t) noexcept {} ///< Create an empty object, must be assigned a valid one to be used - explicit Status(OrtStatus* status) noexcept; ///< Takes ownership of OrtStatus instance returned from the C API. - explicit Status(const Exception&) noexcept; ///< Creates status instance out of exception - explicit Status(const std::exception&) noexcept; ///< Creates status instance out of exception - Status(const char* message, OrtErrorCode code) noexcept; ///< Creates status instance out of null-terminated string message. - std::string GetErrorMessage() const; - OrtErrorCode GetErrorCode() const; - bool IsOK() const noexcept; ///< Returns true if instance represents an OK (non-error) status. -}; - -/** \brief The ThreadingOptions - * - * The ThreadingOptions used for set global threadpools' options of The Env. - */ -struct ThreadingOptions : detail::Base { - /// \brief Wraps OrtApi::CreateThreadingOptions - ThreadingOptions(); - - /// \brief Wraps OrtApi::SetGlobalIntraOpNumThreads - ThreadingOptions& SetGlobalIntraOpNumThreads(int intra_op_num_threads); - - /// \brief Wraps OrtApi::SetGlobalInterOpNumThreads - ThreadingOptions& SetGlobalInterOpNumThreads(int inter_op_num_threads); - - /// \brief Wraps OrtApi::SetGlobalSpinControl - ThreadingOptions& SetGlobalSpinControl(int allow_spinning); - - /// \brief Wraps OrtApi::SetGlobalDenormalAsZero - ThreadingOptions& SetGlobalDenormalAsZero(); - - /// \brief Wraps OrtApi::SetGlobalCustomCreateThreadFn - ThreadingOptions& SetGlobalCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn); - - /// \brief Wraps OrtApi::SetGlobalCustomThreadCreationOptions - ThreadingOptions& SetGlobalCustomThreadCreationOptions(void* ort_custom_thread_creation_options); - - /// \brief Wraps OrtApi::SetGlobalCustomJoinThreadFn - ThreadingOptions& SetGlobalCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn); -}; - -namespace detail { -template -struct KeyValuePairsImpl : Ort::detail::Base { - using B = Ort::detail::Base; - using B::B; - - const char* GetValue(const char* key) const; - - // get the pairs in unordered_map. needs to copy to std::string so the hash works as expected - std::unordered_map GetKeyValuePairs() const; - // get the pairs in two vectors. entries will be 1:1 between keys and values. avoids copying to std::string - void GetKeyValuePairs(std::vector& keys, std::vector& values) const; -}; -} // namespace detail - -// Const object holder that does not own the underlying object -using ConstKeyValuePairs = detail::KeyValuePairsImpl>; - -/** \brief Wrapper around ::OrtKeyValuePair */ -struct KeyValuePairs : detail::KeyValuePairsImpl { - explicit KeyValuePairs(std::nullptr_t) {} ///< No instance is created - /// Take ownership of a pointer created by C API - explicit KeyValuePairs(OrtKeyValuePairs* p) : KeyValuePairsImpl{p} {} - - /// \brief Wraps OrtApi::CreateKeyValuePairs - explicit KeyValuePairs(); - - /// \brief Wraps OrtApi::CreateKeyValuePairs and OrtApi::AddKeyValuePair - explicit KeyValuePairs(const std::unordered_map& kv_pairs); - - /// \brief Wraps OrtApi::AddKeyValuePair - void Add(const char* key, const char* value); - - /// \brief Wraps OrtApi::RemoveKeyValuePair - void Remove(const char* key); - - ConstKeyValuePairs GetConst() const { return ConstKeyValuePairs{this->p_}; } -}; - -namespace detail { -template -struct HardwareDeviceImpl : Ort::detail::Base { - using B = Ort::detail::Base; - using B::B; - - OrtHardwareDeviceType Type() const; - uint32_t VendorId() const; - uint32_t DeviceId() const; - const char* Vendor() const; - ConstKeyValuePairs Metadata() const; -}; -} // namespace detail - -/** \brief Wrapper around ::OrtHardwareDevice - * \remarks HardwareDevice is always read-only for API users. - */ -using ConstHardwareDevice = detail::HardwareDeviceImpl>; - -namespace detail { -template -struct EpDeviceImpl : Ort::detail::Base { - using B = Ort::detail::Base; - using B::B; - - const char* EpName() const; - const char* EpVendor() const; - ConstKeyValuePairs EpMetadata() const; - ConstKeyValuePairs EpOptions() const; - ConstHardwareDevice Device() const; -}; -} // namespace detail - -/** \brief Wrapper around ::OrtEpDevice - * \remarks EpDevice is always read-only for ORT API users. - */ -using ConstEpDevice = detail::EpDeviceImpl>; - -/** \brief Mutable EpDevice that is created by EpApi users. - */ -struct EpDevice : detail::EpDeviceImpl { - explicit EpDevice(std::nullptr_t) {} ///< No instance is created - explicit EpDevice(OrtEpDevice* p) : EpDeviceImpl{p} {} ///< Take ownership of a pointer created by C API - - /// \brief Wraps OrtEpApi::CreateEpDevice - EpDevice(OrtEpFactory& ep_factory, ConstHardwareDevice& hardware_device, - ConstKeyValuePairs ep_metadata = {}, ConstKeyValuePairs ep_options = {}); -}; - -/** \brief The Env (Environment) - * - * The Env holds the logging state used by all other objects. - * Note: One Env must be created before using any other Onnxruntime functionality - */ -struct Env : detail::Base { - explicit Env(std::nullptr_t) {} ///< Create an empty Env object, must be assigned a valid one to be used - - /// \brief Wraps OrtApi::CreateEnv - Env(OrtLoggingLevel logging_level = ORT_LOGGING_LEVEL_WARNING, _In_ const char* logid = ""); - - /// \brief Wraps OrtApi::CreateEnvWithCustomLogger - Env(OrtLoggingLevel logging_level, const char* logid, OrtLoggingFunction logging_function, void* logger_param); - - /// \brief Wraps OrtApi::CreateEnvWithGlobalThreadPools - Env(const OrtThreadingOptions* tp_options, OrtLoggingLevel logging_level = ORT_LOGGING_LEVEL_WARNING, _In_ const char* logid = ""); - - /// \brief Wraps OrtApi::CreateEnvWithCustomLoggerAndGlobalThreadPools - Env(const OrtThreadingOptions* tp_options, OrtLoggingFunction logging_function, void* logger_param, - OrtLoggingLevel logging_level = ORT_LOGGING_LEVEL_WARNING, _In_ const char* logid = ""); - - /// \brief C Interop Helper - explicit Env(OrtEnv* p) : Base{p} {} - - Env& EnableTelemetryEvents(); ///< Wraps OrtApi::EnableTelemetryEvents - Env& DisableTelemetryEvents(); ///< Wraps OrtApi::DisableTelemetryEvents - - Env& UpdateEnvWithCustomLogLevel(OrtLoggingLevel log_severity_level); ///< Wraps OrtApi::UpdateEnvWithCustomLogLevel - - Env& CreateAndRegisterAllocator(const OrtMemoryInfo* mem_info, const OrtArenaCfg* arena_cfg); ///< Wraps OrtApi::CreateAndRegisterAllocator - - Env& CreateAndRegisterAllocatorV2(const std::string& provider_type, const OrtMemoryInfo* mem_info, - const std::unordered_map& options, - const OrtArenaCfg* arena_cfg); ///< Wraps OrtApi::CreateAndRegisterAllocatorV2 - - Env& RegisterExecutionProviderLibrary(const char* registration_name, const std::basic_string& path); ///< Wraps OrtApi::RegisterExecutionProviderLibrary - Env& UnregisterExecutionProviderLibrary(const char* registration_name); ///< Wraps OrtApi::UnregisterExecutionProviderLibrary - - std::vector GetEpDevices() const; -}; - -/** \brief Custom Op Domain - * - */ -struct CustomOpDomain : detail::Base { - using Base = detail::Base; - using Base::Base; - - explicit CustomOpDomain(std::nullptr_t) {} ///< Create an empty CustomOpDomain object, must be assigned a valid one to be used - - /// \brief Wraps OrtApi::CreateCustomOpDomain - explicit CustomOpDomain(const char* domain); - - // This does not take ownership of the op, simply registers it. - void Add(const OrtCustomOp* op); ///< Wraps CustomOpDomain_Add -}; - -/// \brief LoraAdapter holds a set of Lora Parameters loaded from a single file -struct LoraAdapter : detail::Base { - using Base = detail::Base; - using Base::Base; - - explicit LoraAdapter(std::nullptr_t) {} ///< Create an empty LoraAdapter object, must be assigned a valid one to be used - /// \brief Wraps OrtApi::CreateLoraAdapter - /// - /// The function attempts to load the adapter from the specified file - /// \param adapter_path The path to the Lora adapter - /// \param allocator optional pointer to a device allocator. If nullptr, the data stays on CPU. It would still - /// be copied to device if required by the model at inference time. - static LoraAdapter CreateLoraAdapter(const std::basic_string& adapter_path, - OrtAllocator* allocator); - - /// \brief Wraps OrtApi::CreateLoraAdapterFromArray - /// - /// The function attempts to load the adapter from the specified byte array. - /// \param bytes The byte array containing file LoraAdapter format - /// \param num_bytes The number of bytes in the byte array - /// \param allocator optional pointer to a device allocator. If nullptr, the data stays on CPU. It would still - /// be copied to device if required by the model at inference time. - static LoraAdapter CreateLoraAdapterFromArray(const void* bytes, size_t num_bytes, - OrtAllocator* allocator); -}; - -/** \brief RunOptions - * - */ -struct RunOptions : detail::Base { - explicit RunOptions(std::nullptr_t) {} ///< Create an empty RunOptions object, must be assigned a valid one to be used - RunOptions(); ///< Wraps OrtApi::CreateRunOptions - - RunOptions& SetRunLogVerbosityLevel(int); ///< Wraps OrtApi::RunOptionsSetRunLogVerbosityLevel - int GetRunLogVerbosityLevel() const; ///< Wraps OrtApi::RunOptionsGetRunLogVerbosityLevel - - RunOptions& SetRunLogSeverityLevel(int); ///< Wraps OrtApi::RunOptionsSetRunLogSeverityLevel - int GetRunLogSeverityLevel() const; ///< Wraps OrtApi::RunOptionsGetRunLogSeverityLevel - - RunOptions& SetRunTag(const char* run_tag); ///< wraps OrtApi::RunOptionsSetRunTag - const char* GetRunTag() const; ///< Wraps OrtApi::RunOptionsGetRunTag - - RunOptions& AddConfigEntry(const char* config_key, const char* config_value); ///< Wraps OrtApi::AddRunConfigEntry - - /** \brief Terminates all currently executing Session::Run calls that were made using this RunOptions instance - * - * If a currently executing session needs to be force terminated, this can be called from another thread to force it to fail with an error - * Wraps OrtApi::RunOptionsSetTerminate - */ - RunOptions& SetTerminate(); - - /** \brief Clears the terminate flag so this RunOptions instance can be used in a new Session::Run call without it instantly terminating - * - * Wraps OrtApi::RunOptionsUnsetTerminate - */ - RunOptions& UnsetTerminate(); - - /** \brief Add the LoraAdapter to the list of active adapters. - * The setting does not affect RunWithBinding() calls. - * - * Wraps OrtApi::RunOptionsAddActiveLoraAdapter - * \param adapter The LoraAdapter to be used as the active adapter - */ - RunOptions& AddActiveLoraAdapter(const LoraAdapter& adapter); -}; - -namespace detail { -// Utility function that returns a SessionOption config entry key for a specific custom operator. -// Ex: custom_op.[custom_op_name].[config] -std::string MakeCustomOpConfigEntryKey(const char* custom_op_name, const char* config); -} // namespace detail - -/// -/// Class that represents session configuration entries for one or more custom operators. -/// -/// Example: -/// Ort::CustomOpConfigs op_configs; -/// op_configs.AddConfig("my_custom_op", "device_type", "CPU"); -/// -/// Passed to Ort::SessionOptions::RegisterCustomOpsLibrary. -/// -struct CustomOpConfigs { - CustomOpConfigs() = default; - ~CustomOpConfigs() = default; - CustomOpConfigs(const CustomOpConfigs&) = default; - CustomOpConfigs& operator=(const CustomOpConfigs&) = default; - CustomOpConfigs(CustomOpConfigs&& o) = default; - CustomOpConfigs& operator=(CustomOpConfigs&& o) = default; - - /** \brief Adds a session configuration entry/value for a specific custom operator. - * - * \param custom_op_name The name of the custom operator for which to add a configuration entry. - * Must match the name returned by the CustomOp's GetName() method. - * \param config_key The name of the configuration entry. - * \param config_value The value of the configuration entry. - * \return A reference to this object to enable call chaining. - */ - CustomOpConfigs& AddConfig(const char* custom_op_name, const char* config_key, const char* config_value); - - /** \brief Returns a flattened map of custom operator configuration entries and their values. - * - * The keys has been flattened to include both the custom operator name and the configuration entry key name. - * For example, a prior call to AddConfig("my_op", "key", "value") corresponds to the flattened key/value pair - * {"my_op.key", "value"}. - * - * \return An unordered map of flattened configurations. - */ - const std::unordered_map& GetFlattenedConfigs() const; - - private: - std::unordered_map flat_configs_; -}; - -/** \brief Options object used when creating a new Session object - * - * Wraps ::OrtSessionOptions object and methods - */ - -struct SessionOptions; - -namespace detail { -// we separate const-only methods because passing const ptr to non-const methods -// is only discovered when inline methods are compiled which is counter-intuitive -template -struct ConstSessionOptionsImpl : Base { - using B = Base; - using B::B; - - SessionOptions Clone() const; ///< Creates and returns a copy of this SessionOptions object. Wraps OrtApi::CloneSessionOptions - - std::string GetConfigEntry(const char* config_key) const; ///< Wraps OrtApi::GetSessionConfigEntry - bool HasConfigEntry(const char* config_key) const; ///< Wraps OrtApi::HasSessionConfigEntry - std::string GetConfigEntryOrDefault(const char* config_key, const std::string& def) const; -}; - -template -struct SessionOptionsImpl : ConstSessionOptionsImpl { - using B = ConstSessionOptionsImpl; - using B::B; - - SessionOptionsImpl& SetIntraOpNumThreads(int intra_op_num_threads); ///< Wraps OrtApi::SetIntraOpNumThreads - SessionOptionsImpl& SetInterOpNumThreads(int inter_op_num_threads); ///< Wraps OrtApi::SetInterOpNumThreads - SessionOptionsImpl& SetGraphOptimizationLevel(GraphOptimizationLevel graph_optimization_level); ///< Wraps OrtApi::SetSessionGraphOptimizationLevel - SessionOptionsImpl& SetDeterministicCompute(bool value); ///< Wraps OrtApi::SetDeterministicCompute - - SessionOptionsImpl& EnableCpuMemArena(); ///< Wraps OrtApi::EnableCpuMemArena - SessionOptionsImpl& DisableCpuMemArena(); ///< Wraps OrtApi::DisableCpuMemArena - - SessionOptionsImpl& SetOptimizedModelFilePath(const ORTCHAR_T* optimized_model_file); ///< Wraps OrtApi::SetOptimizedModelFilePath - - SessionOptionsImpl& EnableProfiling(const ORTCHAR_T* profile_file_prefix); ///< Wraps OrtApi::EnableProfiling - SessionOptionsImpl& DisableProfiling(); ///< Wraps OrtApi::DisableProfiling - - SessionOptionsImpl& EnableOrtCustomOps(); ///< Wraps OrtApi::EnableOrtCustomOps - - SessionOptionsImpl& EnableMemPattern(); ///< Wraps OrtApi::EnableMemPattern - SessionOptionsImpl& DisableMemPattern(); ///< Wraps OrtApi::DisableMemPattern - - SessionOptionsImpl& SetExecutionMode(ExecutionMode execution_mode); ///< Wraps OrtApi::SetSessionExecutionMode - - SessionOptionsImpl& SetLoadCancellationFlag(bool value); ///< Wraps OrtApi::SessionOptionsSetLoadCancellationFlag - - SessionOptionsImpl& SetLogId(const char* logid); ///< Wraps OrtApi::SetSessionLogId - SessionOptionsImpl& SetLogSeverityLevel(int level); ///< Wraps OrtApi::SetSessionLogSeverityLevel - - SessionOptionsImpl& Add(OrtCustomOpDomain* custom_op_domain); ///< Wraps OrtApi::AddCustomOpDomain - - SessionOptionsImpl& DisablePerSessionThreads(); ///< Wraps OrtApi::DisablePerSessionThreads - - SessionOptionsImpl& AddConfigEntry(const char* config_key, const char* config_value); ///< Wraps OrtApi::AddSessionConfigEntry - - SessionOptionsImpl& AddInitializer(const char* name, const OrtValue* ort_val); ///< Wraps OrtApi::AddInitializer - SessionOptionsImpl& AddExternalInitializers(const std::vector& names, const std::vector& ort_values); ///< Wraps OrtApi::AddExternalInitializers - SessionOptionsImpl& AddExternalInitializersFromFilesInMemory(const std::vector>& external_initializer_file_names, - const std::vector& external_initializer_file_buffer_array, - const std::vector& external_initializer_file_lengths); ///< Wraps OrtApi::AddExternalInitializersFromFilesInMemory - - SessionOptionsImpl& AppendExecutionProvider_CUDA(const OrtCUDAProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_CUDA - SessionOptionsImpl& AppendExecutionProvider_CUDA_V2(const OrtCUDAProviderOptionsV2& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_CUDA_V2 - SessionOptionsImpl& AppendExecutionProvider_ROCM(const OrtROCMProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_ROCM - SessionOptionsImpl& AppendExecutionProvider_OpenVINO(const OrtOpenVINOProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_OpenVINO - ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_OpenVINO_V2 - SessionOptionsImpl& AppendExecutionProvider_OpenVINO_V2(const std::unordered_map& provider_options = {}); - SessionOptionsImpl& AppendExecutionProvider_TensorRT(const OrtTensorRTProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_TensorRT - SessionOptionsImpl& AppendExecutionProvider_TensorRT_V2(const OrtTensorRTProviderOptionsV2& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_TensorRT - SessionOptionsImpl& AppendExecutionProvider_MIGraphX(const OrtMIGraphXProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_MIGraphX - /// Wraps OrtApi::SessionOptionsAppendExecutionProvider_CANN - SessionOptionsImpl& AppendExecutionProvider_CANN(const OrtCANNProviderOptions& provider_options); - /// Wraps OrtApi::SessionOptionsAppendExecutionProvider_Dnnl - SessionOptionsImpl& AppendExecutionProvider_Dnnl(const OrtDnnlProviderOptions& provider_options); - /// Wraps OrtApi::SessionOptionsAppendExecutionProvider. Currently supports QNN, SNPE and XNNPACK. - SessionOptionsImpl& AppendExecutionProvider(const std::string& provider_name, - const std::unordered_map& provider_options = {}); - - /// Append EPs that have been registered previously with the OrtEnv. - /// Wraps OrtApi::SessionOptionsAppendExecutionProvider_V2 - SessionOptionsImpl& AppendExecutionProvider_V2(Env& env, const std::vector& ep_devices, - const KeyValuePairs& ep_options); - /// Append EPs that have been registered previously with the OrtEnv. - /// Wraps OrtApi::SessionOptionsAppendExecutionProvider_V2 - SessionOptionsImpl& AppendExecutionProvider_V2(Env& env, const std::vector& ep_devices, - const std::unordered_map& ep_options); - - /// Wraps OrtApi::SessionOptionsSetEpSelectionPolicy - SessionOptionsImpl& SetEpSelectionPolicy(OrtExecutionProviderDevicePolicy policy); - - /// Wraps OrtApi::SessionOptionsSetEpSelectionPolicyDelegate - SessionOptionsImpl& SetEpSelectionPolicy(EpSelectionDelegate delegate, void* state = nullptr); - - SessionOptionsImpl& SetCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn); ///< Wraps OrtApi::SessionOptionsSetCustomCreateThreadFn - SessionOptionsImpl& SetCustomThreadCreationOptions(void* ort_custom_thread_creation_options); ///< Wraps OrtApi::SessionOptionsSetCustomThreadCreationOptions - SessionOptionsImpl& SetCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn); ///< Wraps OrtApi::SessionOptionsSetCustomJoinThreadFn - - ///< Registers the custom operator from the specified shared library via OrtApi::RegisterCustomOpsLibrary_V2. - ///< The custom operator configurations are optional. If provided, custom operator configs are set via - ///< OrtApi::AddSessionConfigEntry. - SessionOptionsImpl& RegisterCustomOpsLibrary(const ORTCHAR_T* library_name, const CustomOpConfigs& custom_op_configs = {}); - - SessionOptionsImpl& RegisterCustomOpsUsingFunction(const char* function_name); ///< Wraps OrtApi::RegisterCustomOpsUsingFunction - - ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_VitisAI - SessionOptionsImpl& AppendExecutionProvider_VitisAI(const std::unordered_map& provider_options = {}); -}; -} // namespace detail - -using UnownedSessionOptions = detail::SessionOptionsImpl>; -using ConstSessionOptions = detail::ConstSessionOptionsImpl>; - -/** \brief Wrapper around ::OrtSessionOptions - * - */ -struct SessionOptions : detail::SessionOptionsImpl { - explicit SessionOptions(std::nullptr_t) {} ///< Create an empty SessionOptions object, must be assigned a valid one to be used - SessionOptions(); ///< Wraps OrtApi::CreateSessionOptions - explicit SessionOptions(OrtSessionOptions* p) : SessionOptionsImpl{p} {} ///< Used for interop with the C API - UnownedSessionOptions GetUnowned() const { return UnownedSessionOptions{this->p_}; } - ConstSessionOptions GetConst() const { return ConstSessionOptions{this->p_}; } -}; - -/** \brief Options object used when compiling a model. - * - * Wraps ::OrtModelCompilationOptions object and methods - */ -struct ModelCompilationOptions : detail::Base { - using Base = detail::Base; - using Base::Base; - - explicit ModelCompilationOptions(std::nullptr_t) {} ///< Create an empty ModelCompilationOptions object, must be assigned a valid one to be used. - - ModelCompilationOptions(const Env& env, const SessionOptions& session_options); ///< Wraps OrtApi::CreateModelCompilationOptionsFromSessionOptions - ModelCompilationOptions(const Env& env, ConstSessionOptions session_options); ///< Wraps OrtApi::CreateModelCompilationOptionsFromSessionOptions - - ModelCompilationOptions& SetInputModelPath(const ORTCHAR_T* input_model_path); ///< Wraps OrtApi::ModelCompilationOptions_SetInputModelPath - ModelCompilationOptions& SetInputModelFromBuffer(const void* input_model_data, - size_t input_model_data_size); ///< Wraps OrtApi::ModelCompilationOptions_SetInputModelFromBuffer - ModelCompilationOptions& SetEpContextEmbedMode(bool embed_ep_context_in_model); ///< Wraps OrtApi::ModelCompilationOptions_SetEpContextEmbedMode - ModelCompilationOptions& SetOutputModelPath(const ORTCHAR_T* output_model_path); ///< Wraps OrtApi::ModelCompilationOptions_SetOutputModelPath - ModelCompilationOptions& SetOutputModelExternalInitializersFile(const ORTCHAR_T* file_path, - size_t initializer_size_threshold); ///< Wraps OrtApi::ModelCompilationOptions_SetOutputModelExternalInitializersFile - ModelCompilationOptions& SetOutputModelBuffer(OrtAllocator* allocator, void** output_model_buffer_ptr, - size_t* output_model_buffer_size_ptr); ///< Wraps OrtApi::ModelCompilationOptions_SetOutputModelBuffer -}; - -/** \brief Compiles an input model to generate a model with EPContext nodes that execute EP-specific kernels. Wraps OrtApi::CompileModels. - * - * \param env: ORT environment object. - * \param model_compilation_options: Compilation options for a model. - * \return A Status indicating success or failure. - */ -Status CompileModel(const Env& env, const ModelCompilationOptions& model_compilation_options); - -/** \brief Wrapper around ::OrtModelMetadata - * - */ -struct ModelMetadata : detail::Base { - using Base = detail::Base; - using Base::Base; - - explicit ModelMetadata(std::nullptr_t) {} ///< Create an empty ModelMetadata object, must be assigned a valid one to be used - - /** \brief Returns a copy of the producer name. - * - * \param allocator to allocate memory for the copy of the name returned - * \return a instance of smart pointer that would deallocate the buffer when out of scope. - * The OrtAllocator instances must be valid at the point of memory release. - */ - AllocatedStringPtr GetProducerNameAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetProducerName - - /** \brief Returns a copy of the graph name. - * - * \param allocator to allocate memory for the copy of the name returned - * \return a instance of smart pointer that would deallocate the buffer when out of scope. - * The OrtAllocator instances must be valid at the point of memory release. - */ - AllocatedStringPtr GetGraphNameAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetGraphName - - /** \brief Returns a copy of the domain name. - * - * \param allocator to allocate memory for the copy of the name returned - * \return a instance of smart pointer that would deallocate the buffer when out of scope. - * The OrtAllocator instances must be valid at the point of memory release. - */ - AllocatedStringPtr GetDomainAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetDomain - - /** \brief Returns a copy of the description. - * - * \param allocator to allocate memory for the copy of the string returned - * \return a instance of smart pointer that would deallocate the buffer when out of scope. - * The OrtAllocator instances must be valid at the point of memory release. - */ - AllocatedStringPtr GetDescriptionAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetDescription - - /** \brief Returns a copy of the graph description. - * - * \param allocator to allocate memory for the copy of the string returned - * \return a instance of smart pointer that would deallocate the buffer when out of scope. - * The OrtAllocator instances must be valid at the point of memory release. - */ - AllocatedStringPtr GetGraphDescriptionAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetGraphDescription - - /** \brief Returns a vector of copies of the custom metadata keys. - * - * \param allocator to allocate memory for the copy of the string returned - * \return a instance std::vector of smart pointers that would deallocate the buffers when out of scope. - * The OrtAllocator instance must be valid at the point of memory release. - */ - std::vector GetCustomMetadataMapKeysAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetCustomMetadataMapKeys - - /** \brief Looks up a value by a key in the Custom Metadata map - * - * \param key zero terminated string key to lookup - * \param allocator to allocate memory for the copy of the string returned - * \return a instance of smart pointer that would deallocate the buffer when out of scope. - * maybe nullptr if key is not found. - * - * The OrtAllocator instances must be valid at the point of memory release. - */ - AllocatedStringPtr LookupCustomMetadataMapAllocated(const char* key, OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataLookupCustomMetadataMap - - int64_t GetVersion() const; ///< Wraps OrtApi::ModelMetadataGetVersion -}; - -struct IoBinding; - -namespace detail { - -// we separate const-only methods because passing const ptr to non-const methods -// is only discovered when inline methods are compiled which is counter-intuitive -template -struct ConstSessionImpl : Base { - using B = Base; - using B::B; - - size_t GetInputCount() const; ///< Returns the number of model inputs - size_t GetOutputCount() const; ///< Returns the number of model outputs - size_t GetOverridableInitializerCount() const; ///< Returns the number of inputs that have defaults that can be overridden - - std::vector GetInputNames() const; - std::vector GetOutputNames() const; - std::vector GetOverridableInitializerNames() const; - - /** \brief Returns a copy of input name at the specified index. - * - * \param index must less than the value returned by GetInputCount() - * \param allocator to allocate memory for the copy of the name returned - * \return a instance of smart pointer that would deallocate the buffer when out of scope. - * The OrtAllocator instances must be valid at the point of memory release. - */ - AllocatedStringPtr GetInputNameAllocated(size_t index, OrtAllocator* allocator) const; - - /** \brief Returns a copy of output name at then specified index. - * - * \param index must less than the value returned by GetOutputCount() - * \param allocator to allocate memory for the copy of the name returned - * \return a instance of smart pointer that would deallocate the buffer when out of scope. - * The OrtAllocator instances must be valid at the point of memory release. - */ - AllocatedStringPtr GetOutputNameAllocated(size_t index, OrtAllocator* allocator) const; - - /** \brief Returns a copy of the overridable initializer name at then specified index. - * - * \param index must less than the value returned by GetOverridableInitializerCount() - * \param allocator to allocate memory for the copy of the name returned - * \return a instance of smart pointer that would deallocate the buffer when out of scope. - * The OrtAllocator instances must be valid at the point of memory release. - */ - AllocatedStringPtr GetOverridableInitializerNameAllocated(size_t index, OrtAllocator* allocator) const; ///< Wraps OrtApi::SessionGetOverridableInitializerName - - uint64_t GetProfilingStartTimeNs() const; ///< Wraps OrtApi::SessionGetProfilingStartTimeNs - ModelMetadata GetModelMetadata() const; ///< Wraps OrtApi::SessionGetModelMetadata - - TypeInfo GetInputTypeInfo(size_t index) const; ///< Wraps OrtApi::SessionGetInputTypeInfo - TypeInfo GetOutputTypeInfo(size_t index) const; ///< Wraps OrtApi::SessionGetOutputTypeInfo - TypeInfo GetOverridableInitializerTypeInfo(size_t index) const; ///< Wraps OrtApi::SessionGetOverridableInitializerTypeInfo - - int GetOpset(const std::string& domain) const; ///< Wraps OrtApi::SessionGetOpsetForDomain - - // Will move before checkin if that's the case. - std::vector GetInputs() const; - std::vector GetOutputs() const; -}; - -template -struct SessionImpl : ConstSessionImpl { - using B = ConstSessionImpl; - using B::B; - - /** \brief Run the model returning results in an Ort allocated vector. - * - * Wraps OrtApi::Run - * - * The caller provides a list of inputs and a list of the desired outputs to return. - * - * See the output logs for more information on warnings/errors that occur while processing the model. - * Common errors are.. (TODO) - * - * \param[in] run_options - * \param[in] input_names Array of null terminated strings of length input_count that is the list of input names - * \param[in] input_values Array of Value objects of length input_count that is the list of input values - * \param[in] input_count Number of inputs (the size of the input_names & input_values arrays) - * \param[in] output_names Array of C style strings of length output_count that is the list of output names - * \param[in] output_count Number of outputs (the size of the output_names array) - * \return A std::vector of Value objects that directly maps to the output_names array (eg. output_name[0] is the first entry of the returned vector) - */ - std::vector Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, - const char* const* output_names, size_t output_count); - - /** \brief Run the model returning results in user provided outputs - * Same as Run(const RunOptions&, const char* const*, const Value*, size_t,const char* const*, size_t) - */ - void Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, - const char* const* output_names, Value* output_values, size_t output_count); - - void Run(const RunOptions& run_options, const IoBinding&); ///< Wraps OrtApi::RunWithBinding - - /** \brief Run the model asynchronously in a thread owned by intra op thread pool - * - * Wraps OrtApi::RunAsync - * - * \param[in] run_options - * \param[in] input_names Array of null terminated UTF8 encoded strings of the input names - * \param[in] input_values Array of Value objects of length input_count - * \param[in] input_count Number of elements in the input_names and inputs arrays - * \param[in] output_names Array of null terminated UTF8 encoded strings of the output names - * \param[out] output_values Array of provided Values to be filled with outputs. - * On calling RunAsync, output_values[i] could either be initialized by a null pointer or a preallocated OrtValue*. - * Later, on invoking the callback, each output_values[i] of null will be filled with an OrtValue* allocated by onnxruntime. - * Then, an OrtValue** pointer will be casted from output_values, and pass to the callback. - * NOTE: it is customer's duty to finally release output_values and each of its member, - * regardless of whether the member (Ort::Value) is allocated by onnxruntime or preallocated by the customer. - * \param[in] output_count Number of elements in the output_names and outputs array - * \param[in] callback Callback function on model run completion - * \param[in] user_data User data that pass back to the callback - */ - void RunAsync(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, - const char* const* output_names, Value* output_values, size_t output_count, RunAsyncCallbackFn callback, void* user_data); - - /** \brief End profiling and return a copy of the profiling file name. - * - * \param allocator to allocate memory for the copy of the string returned - * \return a instance of smart pointer that would deallocate the buffer when out of scope. - * The OrtAllocator instances must be valid at the point of memory release. - */ - AllocatedStringPtr EndProfilingAllocated(OrtAllocator* allocator); ///< Wraps OrtApi::SessionEndProfiling - - /** \brief Set DynamicOptions for EPs (Execution Providers) - * - * Wraps OrtApi::SetEpDynamicOptions - * - * Valid options can be found in `include\onnxruntime\core\session\onnxruntime_session_options_config_keys.h` - * Look for `kOrtEpDynamicOptions` - * - * \param[in] keys Array of null terminated UTF8 encoded strings of EP dynamic option keys - * \param[in] values Array of null terminated UTF8 encoded string of EP dynamic option values - * \param[in] kv_len Number of elements in the keys and values arrays - */ - void SetEpDynamicOptions(const char* const* keys, const char* const* values, size_t kv_len); - - void FinalizeModelEditorSession(const Model& model, const SessionOptions& options, - OrtPrepackedWeightsContainer* prepacked_weights_container = nullptr); -}; - -} // namespace detail - -using ConstSession = detail::ConstSessionImpl>; -using UnownedSession = detail::SessionImpl>; - -/** \brief Wrapper around ::OrtSession - * - */ -struct Session : detail::SessionImpl { - /// Create an empty Session object, must be assigned a valid one to be used. Wraps OrtApi::CreateSession - explicit Session(std::nullptr_t) {} - explicit Session(OrtSession* p) : SessionImpl{p} {} ///< C API Interop - - Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options); - - /// Wraps OrtApi::CreateSessionWithPrepackedWeightsContainer - Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options, - OrtPrepackedWeightsContainer* prepacked_weights_container); - - /// Wraps OrtApi::CreateSessionFromArray - Session(const Env& env, const void* model_data, size_t model_data_length, const SessionOptions& options); - - /// Wraps OrtApi::CreateSessionFromArrayWithPrepackedWeightsContainer - Session(const Env& env, const void* model_data, size_t model_data_length, const SessionOptions& options, - OrtPrepackedWeightsContainer* prepacked_weights_container); - -#if !defined(ORT_MINIMAL_BUILD) - /// Wraps OrtModelEditorApi::CreateSessionFromModel - Session(const Env& env, const Model& model, const SessionOptions& options); - - /// Wraps OrtModelEditorApi::CreateModelEditorSession - static Session CreateModelEditorSession(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options); - - /// Wraps OrtModelEditorApi::CreateModelEditorSession - static Session CreateModelEditorSession(const Env& env, const void* model_data, size_t model_data_length, - const SessionOptions& options); -#endif // !defined(ORT_MINIMAL_BUILD) - - ConstSession GetConst() const { return ConstSession{this->p_}; } - UnownedSession GetUnowned() const { return UnownedSession{this->p_}; } -}; - -namespace detail { -template -struct MemoryInfoImpl : Base { - using B = Base; - using B::B; - - std::string GetAllocatorName() const; - OrtAllocatorType GetAllocatorType() const; - int GetDeviceId() const; - OrtMemoryInfoDeviceType GetDeviceType() const; - OrtMemType GetMemoryType() const; - - template - bool operator==(const MemoryInfoImpl& o) const; -}; -} // namespace detail - -// Const object holder that does not own the underlying object -using ConstMemoryInfo = detail::MemoryInfoImpl>; - -/** \brief Wrapper around ::OrtMemoryInfo - * - */ -struct MemoryInfo : detail::MemoryInfoImpl { - static MemoryInfo CreateCpu(OrtAllocatorType type, OrtMemType mem_type1); - explicit MemoryInfo(std::nullptr_t) {} ///< No instance is created - explicit MemoryInfo(OrtMemoryInfo* p) : MemoryInfoImpl{p} {} ///< Take ownership of a pointer created by C API - MemoryInfo(const char* name, OrtAllocatorType type, int id, OrtMemType mem_type); - ConstMemoryInfo GetConst() const { return ConstMemoryInfo{this->p_}; } -}; - -namespace detail { -template -struct TensorTypeAndShapeInfoImpl : Base { - using B = Base; - using B::B; - - ONNXTensorElementDataType GetElementType() const; ///< Wraps OrtApi::GetTensorElementType - size_t GetElementCount() const; ///< Wraps OrtApi::GetTensorShapeElementCount - - size_t GetDimensionsCount() const; ///< Wraps OrtApi::GetDimensionsCount - - /** \deprecated use GetShape() returning std::vector - * [[deprecated]] - * This interface is unsafe to use - */ - [[deprecated("use GetShape()")]] void GetDimensions(int64_t* values, size_t values_count) const; ///< Wraps OrtApi::GetDimensions - - void GetSymbolicDimensions(const char** values, size_t values_count) const; ///< Wraps OrtApi::GetSymbolicDimensions - std::vector GetSymbolicDimensions() const; - - std::vector GetShape() const; ///< Uses GetDimensionsCount & GetDimensions to return a std::vector of the shape -}; - -} // namespace detail - -using ConstTensorTypeAndShapeInfo = detail::TensorTypeAndShapeInfoImpl>; - -/** \brief Wrapper around ::OrtTensorTypeAndShapeInfo - * - */ -struct TensorTypeAndShapeInfo : detail::TensorTypeAndShapeInfoImpl { - using Base = detail::TensorTypeAndShapeInfoImpl; - using Base::Base; - - /// Create an empty TensorTypeAndShapeInfo object, must be assigned a valid one to be used - explicit TensorTypeAndShapeInfo(std::nullptr_t) {} - /// Used for interop with the C API - explicit TensorTypeAndShapeInfo(OrtTensorTypeAndShapeInfo* p) : TensorTypeAndShapeInfoImpl{p} {} - - // Create a TensorTypeAndShapeInfo object with the specified element type and dimensions - // symbolic_dims are optional, but should be 1:1 with dims. - // The value in symbolic_dims will be used for all entries in dims that are -1. - explicit TensorTypeAndShapeInfo(ONNXTensorElementDataType element_type, - const std::vector& dims, - const std::vector* symbolic_dims = nullptr); - - ConstTensorTypeAndShapeInfo GetConst() const { return ConstTensorTypeAndShapeInfo{this->p_}; } -}; - -namespace detail { -template -struct SequenceTypeInfoImpl : Base { - using B = Base; - using B::B; - TypeInfo GetSequenceElementType() const; ///< Wraps OrtApi::GetSequenceElementType -}; - -} // namespace detail - -using ConstSequenceTypeInfo = detail::SequenceTypeInfoImpl>; - -/** \brief Wrapper around ::OrtSequenceTypeInfo - * - */ -struct SequenceTypeInfo : detail::SequenceTypeInfoImpl { - using Base = detail::SequenceTypeInfoImpl; - using Base::Base; - - explicit SequenceTypeInfo(std::nullptr_t) {} ///< Create an empty SequenceTypeInfo object, must be assigned a valid one to be used - explicit SequenceTypeInfo(OrtSequenceTypeInfo* p) : SequenceTypeInfoImpl{p} {} ///< Used for interop with the C API - ConstSequenceTypeInfo GetConst() const { return ConstSequenceTypeInfo{this->p_}; } -}; - -namespace detail { -template -struct OptionalTypeInfoImpl : Base { - using B = Base; - using B::B; - TypeInfo GetOptionalElementType() const; ///< Wraps OrtApi::CastOptionalTypeToContainedTypeInfo -}; - -} // namespace detail - -// This is always owned by the TypeInfo and can only be obtained from it. -using ConstOptionalTypeInfo = detail::OptionalTypeInfoImpl>; - -namespace detail { -template -struct MapTypeInfoImpl : detail::Base { - using B = Base; - using B::B; - ONNXTensorElementDataType GetMapKeyType() const; ///< Wraps OrtApi::GetMapKeyType - TypeInfo GetMapValueType() const; ///< Wraps OrtApi::GetMapValueType -}; - -} // namespace detail - -using ConstMapTypeInfo = detail::MapTypeInfoImpl>; - -/** \brief Wrapper around ::OrtMapTypeInfo - * - */ -struct MapTypeInfo : detail::MapTypeInfoImpl { - using Base = detail::MapTypeInfoImpl; - using Base::Base; - - explicit MapTypeInfo(std::nullptr_t) {} ///< Create an empty MapTypeInfo object, must be assigned a valid one to be used - explicit MapTypeInfo(OrtMapTypeInfo* p) : MapTypeInfoImpl{p} {} ///< Used for interop with the C API - ConstMapTypeInfo GetConst() const { return ConstMapTypeInfo{this->p_}; } -}; - -namespace detail { -template -struct TypeInfoImpl : detail::Base { - using B = Base; - using B::B; - - ConstTensorTypeAndShapeInfo GetTensorTypeAndShapeInfo() const; ///< Wraps OrtApi::CastTypeInfoToTensorInfo - ConstSequenceTypeInfo GetSequenceTypeInfo() const; ///< Wraps OrtApi::CastTypeInfoToSequenceTypeInfo - ConstMapTypeInfo GetMapTypeInfo() const; ///< Wraps OrtApi::CastTypeInfoToMapTypeInfo - ConstOptionalTypeInfo GetOptionalTypeInfo() const; ///< wraps OrtApi::CastTypeInfoToOptionalTypeInfo - - ONNXType GetONNXType() const; -}; -} // namespace detail - -/// -/// Contains a constant, unowned OrtTypeInfo that can be copied and passed around by value. -/// Provides access to const OrtTypeInfo APIs. -/// -using ConstTypeInfo = detail::TypeInfoImpl>; - -/// -/// Type information that may contain either TensorTypeAndShapeInfo or -/// the information about contained sequence or map depending on the ONNXType. -/// -struct TypeInfo : detail::TypeInfoImpl { - using Base = detail::TypeInfoImpl; - using Base::Base; - - /// Create an empty TypeInfo object, must be assigned a valid one to be used - explicit TypeInfo(std::nullptr_t) {} - explicit TypeInfo(OrtTypeInfo* p) : TypeInfoImpl{p} {} ///< C API Interop - -#if !defined(ORT_MINIMAL_BUILD) - static TypeInfo CreateTensorInfo(ConstTensorTypeAndShapeInfo tensor_info); - static TypeInfo CreateSparseTensorInfo(ConstTensorTypeAndShapeInfo sparse_tensor_info); - static TypeInfo CreateSequenceTypeInfo(ConstTypeInfo sequence_type); - static TypeInfo CreateMapTypeInfo(ONNXTensorElementDataType key_type, ConstTypeInfo value_type); - static TypeInfo CreateOptionalTypeInfo(ConstTypeInfo contained_type); -#endif // !defined(ORT_MINIMAL_BUILD) - - ConstTypeInfo GetConst() const { return ConstTypeInfo{this->p_}; } -}; - -namespace detail { -// This structure is used to feed sparse tensor values -// information for use with FillSparseTensor() API -// if the data type for the sparse tensor values is numeric -// use data.p_data, otherwise, use data.str pointer to feed -// values. data.str is an array of const char* that are zero terminated. -// number of strings in the array must match shape size. -// For fully sparse tensors use shape {0} and set p_data/str -// to nullptr. -struct OrtSparseValuesParam { - const int64_t* values_shape; - size_t values_shape_len; - union { - const void* p_data; - const char** str; - } data; -}; - -// Provides a way to pass shape in a single -// argument -struct Shape { - const int64_t* shape; - size_t shape_len; -}; - -template -struct ConstValueImpl : Base { - using B = Base; - using B::B; - - /// - /// Obtains a pointer to a user defined data for experimental purposes - /// - template - void GetOpaqueData(const char* domain, const char* type_name, R&) const; ///< Wraps OrtApi::GetOpaqueValue - - bool IsTensor() const; ///< Returns true if Value is a tensor, false for other types like map/sequence/etc - bool HasValue() const; /// < Return true if OrtValue contains data and returns false if the OrtValue is a None - - size_t GetCount() const; // If a non tensor, returns 2 for map and N for sequence, where N is the number of elements - Value GetValue(int index, OrtAllocator* allocator) const; - - /// - /// This API returns a full length of string data contained within either a tensor or a sparse Tensor. - /// For sparse tensor it returns a full length of stored non-empty strings (values). The API is useful - /// for allocating necessary memory and calling GetStringTensorContent(). - /// - /// total length of UTF-8 encoded bytes contained. No zero terminators counted. - size_t GetStringTensorDataLength() const; - - /// - /// The API copies all of the UTF-8 encoded string data contained within a tensor or a sparse tensor - /// into a supplied buffer. Use GetStringTensorDataLength() to find out the length of the buffer to allocate. - /// The user must also allocate offsets buffer with the number of entries equal to that of the contained - /// strings. - /// - /// Strings are always assumed to be on CPU, no X-device copy. - /// - /// user allocated buffer - /// length in bytes of the allocated buffer - /// a pointer to the offsets user allocated buffer - /// count of offsets, must be equal to the number of strings contained. - /// that can be obtained from the shape of the tensor or from GetSparseTensorValuesTypeAndShapeInfo() - /// for sparse tensors - void GetStringTensorContent(void* buffer, size_t buffer_length, size_t* offsets, size_t offsets_count) const; - - /// - /// Returns a const typed pointer to the tensor contained data. - /// No type checking is performed, the caller must ensure the type matches the tensor type. - /// - /// - /// const pointer to data, no copies made - template - const R* GetTensorData() const; ///< Wraps OrtApi::GetTensorMutableData /// - - /// - /// Returns a non-typed pointer to a tensor contained data. - /// - /// const pointer to data, no copies made - const void* GetTensorRawData() const; - - /// - /// The API returns type information for data contained in a tensor. For sparse - /// tensors it returns type information for contained non-zero values. - /// It returns dense shape for sparse tensors. - /// - /// TypeInfo - TypeInfo GetTypeInfo() const; - - /// - /// The API returns type information for data contained in a tensor. For sparse - /// tensors it returns type information for contained non-zero values. - /// It returns dense shape for sparse tensors. - /// - /// TensorTypeAndShapeInfo - TensorTypeAndShapeInfo GetTensorTypeAndShapeInfo() const; - - /// - /// This API returns information about the memory allocation used to hold data. - /// - /// Non owning instance of MemoryInfo - ConstMemoryInfo GetTensorMemoryInfo() const; - - /// - /// The API copies UTF-8 encoded bytes for the requested string element - /// contained within a tensor or a sparse tensor into a provided buffer. - /// Use GetStringTensorElementLength() to obtain the length of the buffer to allocate. - /// - /// - /// - /// - void GetStringTensorElement(size_t buffer_length, size_t element_index, void* buffer) const; - - /// - /// Returns string tensor UTF-8 encoded string element. - /// Use of this API is recommended over GetStringTensorElement() that takes void* buffer pointer. - /// - /// - /// std::string - std::string GetStringTensorElement(size_t element_index) const; - - /// - /// The API returns a byte length of UTF-8 encoded string element - /// contained in either a tensor or a spare tensor values. - /// - /// - /// byte length for the specified string element - size_t GetStringTensorElementLength(size_t element_index) const; - -#if !defined(DISABLE_SPARSE_TENSORS) - /// - /// The API returns the sparse data format this OrtValue holds in a sparse tensor. - /// If the sparse tensor was not fully constructed, i.e. Use*() or Fill*() API were not used - /// the value returned is ORT_SPARSE_UNDEFINED. - /// - /// Format enum - OrtSparseFormat GetSparseFormat() const; - - /// - /// The API returns type and shape information for stored non-zero values of the - /// sparse tensor. Use GetSparseTensorValues() to obtain values buffer pointer. - /// - /// TensorTypeAndShapeInfo values information - TensorTypeAndShapeInfo GetSparseTensorValuesTypeAndShapeInfo() const; - - /// - /// The API returns type and shape information for the specified indices. Each supported - /// indices have their own enum values even if a give format has more than one kind of indices. - /// Use GetSparseTensorIndicesData() to obtain pointer to indices buffer. - /// - /// enum requested - /// type and shape information - TensorTypeAndShapeInfo GetSparseTensorIndicesTypeShapeInfo(OrtSparseIndicesFormat format) const; - - /// - /// The API retrieves a pointer to the internal indices buffer. The API merely performs - /// a convenience data type casting on the return type pointer. Make sure you are requesting - /// the right type, use GetSparseTensorIndicesTypeShapeInfo(); - /// - /// type to cast to - /// requested indices kind - /// number of indices entries - /// Pinter to the internal sparse tensor buffer containing indices. Do not free this pointer. - template - const R* GetSparseTensorIndicesData(OrtSparseIndicesFormat indices_format, size_t& num_indices) const; - - /// - /// Returns true if the OrtValue contains a sparse tensor - /// - /// - bool IsSparseTensor() const; - - /// - /// The API returns a pointer to an internal buffer of the sparse tensor - /// containing non-zero values. The API merely does casting. Make sure you - /// are requesting the right data type by calling GetSparseTensorValuesTypeAndShapeInfo() - /// first. - /// - /// numeric data types only. Use GetStringTensor*() to retrieve strings. - /// a pointer to the internal values buffer. Do not free this pointer. - template - const R* GetSparseTensorValues() const; - -#endif -}; - -template -struct ValueImpl : ConstValueImpl { - using B = ConstValueImpl; - using B::B; - - /// - /// Returns a non-const typed pointer to an OrtValue/Tensor contained buffer - /// No type checking is performed, the caller must ensure the type matches the tensor type. - /// - /// non-const pointer to data, no copies made - template - R* GetTensorMutableData(); - - /// - /// Returns a non-typed non-const pointer to a tensor contained data. - /// - /// pointer to data, no copies made - void* GetTensorMutableRawData(); - - /// - // Obtain a reference to an element of data at the location specified - /// by the vector of dims. - /// - /// - /// [in] expressed by a vecotr of dimensions offsets - /// - template - R& At(const std::vector& location); - - /// - /// Set all strings at once in a string tensor - /// - /// [in] An array of strings. Each string in this array must be null terminated. - /// [in] Count of strings in s (Must match the size of \p value's tensor shape) - void FillStringTensor(const char* const* s, size_t s_len); - - /// - /// Set a single string in a string tensor - /// - /// [in] A null terminated UTF-8 encoded string - /// [in] Index of the string in the tensor to set - void FillStringTensorElement(const char* s, size_t index); - - /// - /// Allocate if necessary and obtain a pointer to a UTF-8 - /// encoded string element buffer indexed by the flat element index, - /// of the specified length. - /// - /// This API is for advanced usage. It avoids a need to construct - /// an auxiliary array of string pointers, and allows to write data directly - /// (do not zero terminate). - /// - /// - /// - /// a pointer to a writable buffer - char* GetResizedStringTensorElementBuffer(size_t index, size_t buffer_length); - -#if !defined(DISABLE_SPARSE_TENSORS) - /// - /// Supplies COO format specific indices and marks the contained sparse tensor as being a COO format tensor. - /// Values are supplied with a CreateSparseTensor() API. The supplied indices are not copied and the user - /// allocated buffers lifespan must eclipse that of the OrtValue. - /// The location of the indices is assumed to be the same as specified by OrtMemoryInfo argument at the creation time. - /// - /// pointer to the user allocated buffer with indices. Use nullptr for fully sparse tensors. - /// number of indices entries. Use 0 for fully sparse tensors - void UseCooIndices(int64_t* indices_data, size_t indices_num); - - /// - /// Supplies CSR format specific indices and marks the contained sparse tensor as being a CSR format tensor. - /// Values are supplied with a CreateSparseTensor() API. The supplied indices are not copied and the user - /// allocated buffers lifespan must eclipse that of the OrtValue. - /// The location of the indices is assumed to be the same as specified by OrtMemoryInfo argument at the creation time. - /// - /// pointer to the user allocated buffer with inner indices or nullptr for fully sparse tensors - /// number of csr inner indices or 0 for fully sparse tensors - /// pointer to the user allocated buffer with outer indices or nullptr for fully sparse tensors - /// number of csr outer indices or 0 for fully sparse tensors - void UseCsrIndices(int64_t* inner_data, size_t inner_num, int64_t* outer_data, size_t outer_num); - - /// - /// Supplies BlockSparse format specific indices and marks the contained sparse tensor as being a BlockSparse format tensor. - /// Values are supplied with a CreateSparseTensor() API. The supplied indices are not copied and the user - /// allocated buffers lifespan must eclipse that of the OrtValue. - /// The location of the indices is assumed to be the same as specified by OrtMemoryInfo argument at the creation time. - /// - /// indices shape or a {0} for fully sparse - /// user allocated buffer with indices or nullptr for fully spare tensors - void UseBlockSparseIndices(const Shape& indices_shape, int32_t* indices_data); - - /// - /// The API will allocate memory using the allocator instance supplied to the CreateSparseTensor() API - /// and copy the values and COO indices into it. If data_mem_info specifies that the data is located - /// at difference device than the allocator, a X-device copy will be performed if possible. - /// - /// specified buffer memory description - /// values buffer information. - /// coo indices buffer or nullptr for fully sparse data - /// number of COO indices or 0 for fully sparse data - void FillSparseTensorCoo(const OrtMemoryInfo* data_mem_info, const OrtSparseValuesParam& values_param, - const int64_t* indices_data, size_t indices_num); - - /// - /// The API will allocate memory using the allocator instance supplied to the CreateSparseTensor() API - /// and copy the values and CSR indices into it. If data_mem_info specifies that the data is located - /// at difference device than the allocator, a X-device copy will be performed if possible. - /// - /// specified buffer memory description - /// values buffer information - /// csr inner indices pointer or nullptr for fully sparse tensors - /// number of csr inner indices or 0 for fully sparse tensors - /// pointer to csr indices data or nullptr for fully sparse tensors - /// number of csr outer indices or 0 - void FillSparseTensorCsr(const OrtMemoryInfo* data_mem_info, - const OrtSparseValuesParam& values, - const int64_t* inner_indices_data, size_t inner_indices_num, - const int64_t* outer_indices_data, size_t outer_indices_num); - - /// - /// The API will allocate memory using the allocator instance supplied to the CreateSparseTensor() API - /// and copy the values and BlockSparse indices into it. If data_mem_info specifies that the data is located - /// at difference device than the allocator, a X-device copy will be performed if possible. - /// - /// specified buffer memory description - /// values buffer information - /// indices shape. use {0} for fully sparse tensors - /// pointer to indices data or nullptr for fully sparse tensors - void FillSparseTensorBlockSparse(const OrtMemoryInfo* data_mem_info, - const OrtSparseValuesParam& values, - const Shape& indices_shape, - const int32_t* indices_data); - -#endif -}; - -} // namespace detail - -using ConstValue = detail::ConstValueImpl>; -using UnownedValue = detail::ValueImpl>; - -/** \brief Wrapper around ::OrtValue - * - */ -struct Value : detail::ValueImpl { - using Base = detail::ValueImpl; - using Base::Base; - using OrtSparseValuesParam = detail::OrtSparseValuesParam; - using Shape = detail::Shape; - - explicit Value(std::nullptr_t) {} ///< Create an empty Value object, must be assigned a valid one to be used - Value(Value&&) = default; - Value& operator=(Value&&) = default; - - ConstValue GetConst() const { return ConstValue{this->p_}; } - UnownedValue GetUnowned() const { return UnownedValue{this->p_}; } - - /** \brief Creates a tensor with a user supplied buffer. Wraps OrtApi::CreateTensorWithDataAsOrtValue. - * \tparam T The numeric datatype. This API is not suitable for strings. - * \param info Memory description of where the p_data buffer resides (CPU vs GPU etc). - * \param p_data Pointer to the data buffer. - * \param p_data_element_count The number of elements in the data buffer. - * \param shape Pointer to the tensor shape dimensions. - * \param shape_len The number of tensor shape dimensions. - */ - template - static Value CreateTensor(const OrtMemoryInfo* info, T* p_data, size_t p_data_element_count, - const int64_t* shape, size_t shape_len); - - /** \brief Creates a tensor with a user supplied buffer. Wraps OrtApi::CreateTensorWithDataAsOrtValue. - * - * \param info Memory description of where the p_data buffer resides (CPU vs GPU etc). - * \param p_data Pointer to the data buffer. - * \param p_data_byte_count The number of bytes in the data buffer. - * \param shape Pointer to the tensor shape dimensions. - * \param shape_len The number of tensor shape dimensions. - * \param type The data type. - */ - static Value CreateTensor(const OrtMemoryInfo* info, void* p_data, size_t p_data_byte_count, - const int64_t* shape, size_t shape_len, - ONNXTensorElementDataType type); - - /** \brief Creates a tensor with a user supplied buffer. Wraps OrtApi::CreateTensorWithDataAndDeleterAsOrtValue. - * - * \param deleter OrtAllocator that will be used to free the buffer when no longer required. - * \param p_data Pointer to the data buffer. - * \param p_data_byte_count The number of bytes in the data buffer. - * \param shape Pointer to the tensor shape dimensions. - * \param shape_len The number of tensor shape dimensions. - * \param type The data type. - */ - static Value CreateTensor(OrtAllocator* deleter, void* p_data, size_t p_data_byte_count, - const int64_t* shape, size_t shape_len, - ONNXTensorElementDataType type); - - /** \brief Creates an OrtValue with a tensor using a supplied OrtAllocator. Wraps OrtApi::CreateTensorAsOrtValue. - * This overload will allocate the buffer for the tensor according to the supplied shape and data type. - * The allocated buffer will be owned by the returned OrtValue and will be freed when the OrtValue is released. - * The input data would need to be copied into the allocated buffer. - * This API is not suitable for strings. - * - * \tparam T The numeric datatype. This API is not suitable for strings. - * \param allocator The allocator to use. - * \param shape Pointer to the tensor shape dimensions. - * \param shape_len The number of tensor shape dimensions. - */ - template - static Value CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len); - - /** \brief Creates an OrtValue with a tensor using the supplied OrtAllocator. - * Wraps OrtApi::CreateTensorAsOrtValue. - * The allocated buffer will be owned by the returned OrtValue and will be freed when the OrtValue is released. - * The input data would need to be copied into the allocated buffer. - * This API is not suitable for strings. - * - * \param allocator The allocator to use. - * \param shape Pointer to the tensor shape dimensions. - * \param shape_len The number of tensor shape dimensions. - * \param type The data type. - */ - static Value CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len, - ONNXTensorElementDataType type); - - /** \brief Creates an OrtValue with a Map Onnx type representation. - * The API would ref-count the supplied OrtValues and they will be released - * when the returned OrtValue is released. The caller may release keys and values after the call - * returns. - * - * \param keys an OrtValue containing a tensor with primitive data type keys. - * \param values an OrtValue that may contain a tensor. Ort currently supports only primitive data type values. - */ - static Value CreateMap(const Value& keys, const Value& values); ///< Wraps OrtApi::CreateValue - - /** \brief Creates an OrtValue with a Sequence Onnx type representation. - * The API would ref-count the supplied OrtValues and they will be released - * when the returned OrtValue is released. The caller may release the values after the call - * returns. - * - * \param values a vector of OrtValues that must have the same Onnx value type. - */ - static Value CreateSequence(const std::vector& values); ///< Wraps OrtApi::CreateValue - - /** \brief Creates an OrtValue wrapping an Opaque type. - * This is used for experimental support of non-tensor types. - * - * \tparam T - the type of the value. - * \param domain - zero terminated utf-8 string. Domain of the type. - * \param type_name - zero terminated utf-8 string. Name of the type. - * \param value - the value to be wrapped. - */ - template - static Value CreateOpaque(const char* domain, const char* type_name, const T& value); ///< Wraps OrtApi::CreateOpaqueValue - -#if !defined(DISABLE_SPARSE_TENSORS) - /// - /// This is a simple forwarding method to the other overload that helps deducing - /// data type enum value from the type of the buffer. - /// - /// numeric datatype. This API is not suitable for strings. - /// Memory description where the user buffers reside (CPU vs GPU etc) - /// pointer to the user supplied buffer, use nullptr for fully sparse tensors - /// a would be dense shape of the tensor - /// non zero values shape. Use a single 0 shape for fully sparse tensors. - /// - template - static Value CreateSparseTensor(const OrtMemoryInfo* info, T* p_data, const Shape& dense_shape, - const Shape& values_shape); - - /// - /// Creates an OrtValue instance containing SparseTensor. This constructs - /// a sparse tensor that makes use of user allocated buffers. It does not make copies - /// of the user provided data and does not modify it. The lifespan of user provided buffers should - /// eclipse the life span of the resulting OrtValue. This call constructs an instance that only contain - /// a pointer to non-zero values. To fully populate the sparse tensor call UseIndices() API below - /// to supply a sparse format specific indices. - /// This API is not suitable for string data. Use CreateSparseTensor() with allocator specified so strings - /// can be properly copied into the allocated buffer. - /// - /// Memory description where the user buffers reside (CPU vs GPU etc) - /// pointer to the user supplied buffer, use nullptr for fully sparse tensors - /// a would be dense shape of the tensor - /// non zero values shape. Use a single 0 shape for fully sparse tensors. - /// data type - /// Ort::Value instance containing SparseTensor - static Value CreateSparseTensor(const OrtMemoryInfo* info, void* p_data, const Shape& dense_shape, - const Shape& values_shape, ONNXTensorElementDataType type); - - /// - /// This is a simple forwarding method to the below CreateSparseTensor. - /// This helps to specify data type enum in terms of C++ data type. - /// Use CreateSparseTensor - /// - /// numeric data type only. String data enum must be specified explicitly. - /// allocator to use - /// a would be dense shape of the tensor - /// Ort::Value - template - static Value CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape); - - /// - /// Creates an instance of OrtValue containing sparse tensor. The created instance has no data. - /// The data must be supplied by on of the FillSparseTensor() methods that take both non-zero values - /// and indices. The data will be copied into a buffer that would be allocated using the supplied allocator. - /// Use this API to create OrtValues that contain sparse tensors with all supported data types including - /// strings. - /// - /// allocator to use. The allocator lifespan must eclipse that of the resulting OrtValue - /// a would be dense shape of the tensor - /// data type - /// an instance of Ort::Value - static Value CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape, ONNXTensorElementDataType type); - -#endif // !defined(DISABLE_SPARSE_TENSORS) -}; - -/// -/// Represents native memory allocation coming from one of the -/// OrtAllocators registered with OnnxRuntime. -/// Use it to wrap an allocation made by an allocator -/// so it can be automatically released when no longer needed. -/// -struct MemoryAllocation { - MemoryAllocation(OrtAllocator* allocator, void* p, size_t size); - ~MemoryAllocation(); - MemoryAllocation(const MemoryAllocation&) = delete; - MemoryAllocation& operator=(const MemoryAllocation&) = delete; - MemoryAllocation(MemoryAllocation&&) noexcept; - MemoryAllocation& operator=(MemoryAllocation&&) noexcept; - - void* get() { return p_; } - size_t size() const { return size_; } - - private: - OrtAllocator* allocator_; - void* p_; - size_t size_; -}; - -namespace detail { -template -struct AllocatorImpl : Base { - using B = Base; - using B::B; - - void* Alloc(size_t size); - MemoryAllocation GetAllocation(size_t size); - void Free(void* p); - ConstMemoryInfo GetInfo() const; -}; - -} // namespace detail - -/** \brief Wrapper around ::OrtAllocator default instance that is owned by Onnxruntime - * - */ -struct AllocatorWithDefaultOptions : detail::AllocatorImpl> { - explicit AllocatorWithDefaultOptions(std::nullptr_t) {} ///< Convenience to create a class member and then replace with an instance - AllocatorWithDefaultOptions(); -}; - -/** \brief Wrapper around ::OrtAllocator - * - */ -struct Allocator : detail::AllocatorImpl { - explicit Allocator(std::nullptr_t) {} ///< Convenience to create a class member and then replace with an instance - Allocator(const Session& session, const OrtMemoryInfo*); -}; - -using UnownedAllocator = detail::AllocatorImpl>; - -namespace detail { -namespace binding_utils { -// Bring these out of template -std::vector GetOutputNamesHelper(const OrtIoBinding* binding, OrtAllocator*); -std::vector GetOutputValuesHelper(const OrtIoBinding* binding, OrtAllocator*); -} // namespace binding_utils - -template -struct ConstIoBindingImpl : Base { - using B = Base; - using B::B; - - std::vector GetOutputNames() const; - std::vector GetOutputNames(OrtAllocator*) const; - std::vector GetOutputValues() const; - std::vector GetOutputValues(OrtAllocator*) const; -}; - -template -struct IoBindingImpl : ConstIoBindingImpl { - using B = ConstIoBindingImpl; - using B::B; - - void BindInput(const char* name, const Value&); - void BindOutput(const char* name, const Value&); - void BindOutput(const char* name, const OrtMemoryInfo*); - void ClearBoundInputs(); - void ClearBoundOutputs(); - void SynchronizeInputs(); - void SynchronizeOutputs(); -}; - -} // namespace detail - -using ConstIoBinding = detail::ConstIoBindingImpl>; -using UnownedIoBinding = detail::IoBindingImpl>; - -/** \brief Wrapper around ::OrtIoBinding - * - */ -struct IoBinding : detail::IoBindingImpl { - explicit IoBinding(std::nullptr_t) {} ///< Create an empty object for convenience. Sometimes, we want to initialize members later. - explicit IoBinding(Session& session); - ConstIoBinding GetConst() const { return ConstIoBinding{this->p_}; } - UnownedIoBinding GetUnowned() const { return UnownedIoBinding{this->p_}; } -}; - -/*! \struct Ort::ArenaCfg - * \brief it is a structure that represents the configuration of an arena based allocator - * \details Please see docs/C_API.md for details - */ -struct ArenaCfg : detail::Base { - explicit ArenaCfg(std::nullptr_t) {} ///< Create an empty ArenaCfg object, must be assigned a valid one to be used - /** - * Wraps OrtApi::CreateArenaCfg - * \param max_mem - use 0 to allow ORT to choose the default - * \param arena_extend_strategy - use -1 to allow ORT to choose the default, 0 = kNextPowerOfTwo, 1 = kSameAsRequested - * \param initial_chunk_size_bytes - use -1 to allow ORT to choose the default - * \param max_dead_bytes_per_chunk - use -1 to allow ORT to choose the default - * See docs/C_API.md for details on what the following parameters mean and how to choose these values - */ - ArenaCfg(size_t max_mem, int arena_extend_strategy, int initial_chunk_size_bytes, int max_dead_bytes_per_chunk); -}; - -// -// Custom OPs (only needed to implement custom OPs) -// - -/// -/// This struct provides life time management for custom op attribute -/// -struct OpAttr : detail::Base { - using Base = detail::Base; - using Base::Base; - - explicit OpAttr(std::nullptr_t) {} - OpAttr(const char* name, const void* data, int len, OrtOpAttrType type); -}; - -/** - * Macro that logs a message using the provided logger. Throws an exception if OrtApi::Logger_LogMessage fails. - * Example: ORT_CXX_LOG(logger, ORT_LOGGING_LEVEL_INFO, "Log a message"); - * - * \param logger The Ort::Logger instance to use. Must be a value or reference. - * \param message_severity The logging severity level of the message. - * \param message A null-terminated UTF-8 message to log. - */ -#define ORT_CXX_LOG(logger, message_severity, message) \ - do { \ - if (message_severity >= logger.GetLoggingSeverityLevel()) { \ - Ort::ThrowOnError(logger.LogMessage(message_severity, ORT_FILE, __LINE__, \ - static_cast(__FUNCTION__), message)); \ - } \ - } while (false) - -/** - * Macro that logs a message using the provided logger. Can be used in noexcept code since errors are silently ignored. - * Example: ORT_CXX_LOG_NOEXCEPT(logger, ORT_LOGGING_LEVEL_INFO, "Log a message"); - * - * \param logger The Ort::Logger instance to use. Must be a value or reference. - * \param message_severity The logging severity level of the message. - * \param message A null-terminated UTF-8 message to log. - */ -#define ORT_CXX_LOG_NOEXCEPT(logger, message_severity, message) \ - do { \ - if (message_severity >= logger.GetLoggingSeverityLevel()) { \ - static_cast(logger.LogMessage(message_severity, ORT_FILE, __LINE__, \ - static_cast(__FUNCTION__), message)); \ - } \ - } while (false) - -/** - * Macro that logs a printf-like formatted message using the provided logger. Throws an exception if - * OrtApi::Logger_LogMessage fails or if a formatting error occurs. - * Example: ORT_CXX_LOGF(logger, ORT_LOGGING_LEVEL_INFO, "Log an int: %d", 12); - * - * \param logger The Ort::Logger instance to use. Must be a value or reference. - * \param message_severity The logging severity level of the message. - * \param format A null-terminated UTF-8 format string forwarded to a printf-like function. - * Refer to https://en.cppreference.com/w/cpp/io/c/fprintf for information on valid formats. - * \param ... Zero or more variadic arguments referenced by the format string. - */ -#define ORT_CXX_LOGF(logger, message_severity, /*format,*/...) \ - do { \ - if (message_severity >= logger.GetLoggingSeverityLevel()) { \ - Ort::ThrowOnError(logger.LogFormattedMessage(message_severity, ORT_FILE, __LINE__, \ - static_cast(__FUNCTION__), __VA_ARGS__)); \ - } \ - } while (false) - -/** - * Macro that logs a printf-like formatted message using the provided logger. Can be used in noexcept code since errors - * are silently ignored. - * Example: ORT_CXX_LOGF_NOEXCEPT(logger, ORT_LOGGING_LEVEL_INFO, "Log an int: %d", 12); - * - * \param logger The Ort::Logger instance to use. Must be a value or reference. - * \param message_severity The logging severity level of the message. - * \param format A null-terminated UTF-8 format string forwarded to a printf-like function. - * Refer to https://en.cppreference.com/w/cpp/io/c/fprintf for information on valid formats. - * \param ... Zero or more variadic arguments referenced by the format string. - */ -#define ORT_CXX_LOGF_NOEXCEPT(logger, message_severity, /*format,*/...) \ - do { \ - if (message_severity >= logger.GetLoggingSeverityLevel()) { \ - static_cast(logger.LogFormattedMessage(message_severity, ORT_FILE, __LINE__, \ - static_cast(__FUNCTION__), __VA_ARGS__)); \ - } \ - } while (false) - -/// -/// This class represents an ONNX Runtime logger that can be used to log information with an -/// associated severity level and source code location (file path, line number, function name). -/// -/// A Logger can be obtained from within custom operators by calling Ort::KernelInfo::GetLogger(). -/// Instances of Ort::Logger are the size of two pointers and can be passed by value. -/// -/// Use the ORT_CXX_LOG macros to ensure the source code location is set properly from the callsite -/// and to take advantage of a cached logging severity level that can bypass calls to the underlying C API. -/// -struct Logger { - /** - * Creates an empty Ort::Logger. Must be initialized from a valid Ort::Logger before use. - */ - Logger() = default; - - /** - * Creates an empty Ort::Logger. Must be initialized from a valid Ort::Logger before use. - */ - explicit Logger(std::nullptr_t) {} - - /** - * Creates a logger from an ::OrtLogger instance. Caches the logger's current severity level by calling - * OrtApi::Logger_GetLoggingSeverityLevel. Throws an exception if OrtApi::Logger_GetLoggingSeverityLevel fails. - * - * \param logger The ::OrtLogger to wrap. - */ - explicit Logger(const OrtLogger* logger); - - ~Logger() = default; - - Logger(const Logger&) = default; - Logger& operator=(const Logger&) = default; - - Logger(Logger&& v) noexcept = default; - Logger& operator=(Logger&& v) noexcept = default; - - /** - * Returns the logger's current severity level from the cached member. - * - * \return The current ::OrtLoggingLevel. - */ - OrtLoggingLevel GetLoggingSeverityLevel() const noexcept; - - /** - * Logs the provided message via OrtApi::Logger_LogMessage. Use the ORT_CXX_LOG or ORT_CXX_LOG_NOEXCEPT - * macros to properly set the source code location and to use the cached severity level to potentially bypass - * calls to the underlying C API. - * - * \param log_severity_level The message's logging severity level. - * \param file_path The filepath of the file in which the message is logged. Usually the value of ORT_FILE. - * \param line_number The file line number in which the message is logged. Usually the value of __LINE__. - * \param func_name The name of the function in which the message is logged. Usually the value of __FUNCTION__. - * \param message The message to log. - * \return A Ort::Status value to indicate error or success. - */ - Status LogMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path, int line_number, - const char* func_name, const char* message) const noexcept; - - /** - * Logs a printf-like formatted message via OrtApi::Logger_LogMessage. Use the ORT_CXX_LOGF or ORT_CXX_LOGF_NOEXCEPT - * macros to properly set the source code location and to use the cached severity level to potentially bypass - * calls to the underlying C API. Returns an error status if a formatting error occurs. - * - * \param log_severity_level The message's logging severity level. - * \param file_path The filepath of the file in which the message is logged. Usually the value of ORT_FILE. - * \param line_number The file line number in which the message is logged. Usually the value of __LINE__. - * \param func_name The name of the function in which the message is logged. Usually the value of __FUNCTION__. - * \param format A null-terminated UTF-8 format string forwarded to a printf-like function. - * Refer to https://en.cppreference.com/w/cpp/io/c/fprintf for information on valid formats. - * \param args Zero or more variadic arguments referenced by the format string. - * \return A Ort::Status value to indicate error or success. - */ - template - Status LogFormattedMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path, int line_number, - const char* func_name, const char* format, Args&&... args) const noexcept; - - private: - const OrtLogger* logger_{}; - OrtLoggingLevel cached_severity_level_{}; -}; - -/// -/// This class wraps a raw pointer OrtKernelContext* that is being passed -/// to the custom kernel Compute() method. Use it to safely access context -/// attributes, input and output parameters with exception safety guarantees. -/// See usage example in onnxruntime/test/testdata/custom_op_library/custom_op_library.cc -/// -struct KernelContext { - explicit KernelContext(OrtKernelContext* context); - size_t GetInputCount() const; - size_t GetOutputCount() const; - // If input is optional and is not present, the method returns an empty ConstValue - // which can be compared to nullptr. - ConstValue GetInput(size_t index) const; - // If output is optional and is not present, the method returns an empty UnownedValue - // which can be compared to nullptr. - UnownedValue GetOutput(size_t index, const int64_t* dim_values, size_t dim_count) const; - UnownedValue GetOutput(size_t index, const std::vector& dims) const; - void* GetGPUComputeStream() const; - Logger GetLogger() const; - OrtAllocator* GetAllocator(const OrtMemoryInfo& memory_info) const; - OrtKernelContext* GetOrtKernelContext() const { return ctx_; } - void ParallelFor(void (*fn)(void*, size_t), size_t total, size_t num_batch, void* usr_data) const; - - private: - OrtKernelContext* ctx_; -}; - -struct KernelInfo; - -namespace detail { -namespace attr_utils { -void GetAttr(const OrtKernelInfo* p, const char* name, float&); -void GetAttr(const OrtKernelInfo* p, const char* name, int64_t&); -void GetAttr(const OrtKernelInfo* p, const char* name, std::string&); -void GetAttrs(const OrtKernelInfo* p, const char* name, std::vector&); -void GetAttrs(const OrtKernelInfo* p, const char* name, std::vector&); -} // namespace attr_utils - -template -struct KernelInfoImpl : Base { - using B = Base; - using B::B; - - KernelInfo Copy() const; - - template // R is only implemented for float, int64_t, and string - R GetAttribute(const char* name) const { - R val; - attr_utils::GetAttr(this->p_, name, val); - return val; - } - - template // R is only implemented for std::vector, std::vector - std::vector GetAttributes(const char* name) const { - std::vector result; - attr_utils::GetAttrs(this->p_, name, result); - return result; - } - - Value GetTensorAttribute(const char* name, OrtAllocator* allocator) const; - - size_t GetInputCount() const; - size_t GetOutputCount() const; - - std::string GetInputName(size_t index) const; - std::string GetOutputName(size_t index) const; - - TypeInfo GetInputTypeInfo(size_t index) const; - TypeInfo GetOutputTypeInfo(size_t index) const; - - ConstValue GetTensorConstantInput(size_t index, int* is_constant) const; - - std::string GetNodeName() const; - Logger GetLogger() const; -}; - -} // namespace detail - -using ConstKernelInfo = detail::KernelInfoImpl>; - -/// -/// This struct owns the OrtKernInfo* pointer when a copy is made. -/// For convenient wrapping of OrtKernelInfo* passed to kernel constructor -/// and query attributes, warp the pointer with Ort::Unowned instance -/// so it does not destroy the pointer the kernel does not own. -/// -struct KernelInfo : detail::KernelInfoImpl { - using Base = detail::KernelInfoImpl; - using Base::Base; - explicit KernelInfo(std::nullptr_t) {} ///< Create an empty instance to initialize later - explicit KernelInfo(OrtKernelInfo* info); ///< Take ownership of the instance - ConstKernelInfo GetConst() const { return ConstKernelInfo{this->p_}; } -}; - -/// -/// Create and own custom defined operation. -/// -struct Op : detail::Base { - using Base = detail::Base; - using Base::Base; - - explicit Op(std::nullptr_t) {} ///< Create an empty Operator object, must be assigned a valid one to be used - - explicit Op(OrtOp*); ///< Take ownership of the OrtOp - - static Op Create(const OrtKernelInfo* info, const char* op_name, const char* domain, - int version, const char** type_constraint_names, - const ONNXTensorElementDataType* type_constraint_values, - size_t type_constraint_count, - const OpAttr* attr_values, - size_t attr_count, - size_t input_count, size_t output_count); - - void Invoke(const OrtKernelContext* context, - const Value* input_values, - size_t input_count, - Value* output_values, - size_t output_count); - - // For easier refactoring - void Invoke(const OrtKernelContext* context, - const OrtValue* const* input_values, - size_t input_count, - OrtValue* const* output_values, - size_t output_count); -}; - -/// -/// Provide access to per-node attributes and input shapes, so one could compute and set output shapes. -/// -struct ShapeInferContext { - struct SymbolicInteger { - SymbolicInteger(int64_t i) : i_(i), is_int_(true) {}; - SymbolicInteger(const char* s) : s_(s), is_int_(false) {}; - SymbolicInteger(const SymbolicInteger&) = default; - SymbolicInteger(SymbolicInteger&&) = default; - - SymbolicInteger& operator=(const SymbolicInteger&) = default; - SymbolicInteger& operator=(SymbolicInteger&&) = default; - - bool operator==(const SymbolicInteger& dim) const { - if (is_int_ == dim.is_int_) { - if (is_int_) { - return i_ == dim.i_; - } else { - return std::string{s_} == std::string{dim.s_}; - } - } - return false; - } - - bool IsInt() const { return is_int_; } - int64_t AsInt() const { return i_; } - const char* AsSym() const { return s_; } - - static constexpr int INVALID_INT_DIM = -2; - - private: - union { - int64_t i_; - const char* s_; - }; - bool is_int_; - }; - - using Shape = std::vector; - - ShapeInferContext(const OrtApi* ort_api, OrtShapeInferContext* ctx); - - const Shape& GetInputShape(size_t indice) const { return input_shapes_.at(indice); } - - size_t GetInputCount() const { return input_shapes_.size(); } - - Status SetOutputShape(size_t indice, const Shape& shape, ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT); - - int64_t GetAttrInt(const char* attr_name); - - using Ints = std::vector; - Ints GetAttrInts(const char* attr_name); - - float GetAttrFloat(const char* attr_name); - - using Floats = std::vector; - Floats GetAttrFloats(const char* attr_name); - - std::string GetAttrString(const char* attr_name); - - using Strings = std::vector; - Strings GetAttrStrings(const char* attr_name); - - private: - const OrtOpAttr* GetAttrHdl(const char* attr_name) const; - const OrtApi* ort_api_; - OrtShapeInferContext* ctx_; - std::vector input_shapes_; -}; - -using ShapeInferFn = Ort::Status (*)(Ort::ShapeInferContext&); - -#define MAX_CUSTOM_OP_END_VER (1UL << 31) - 1 - -template -struct CustomOpBase : OrtCustomOp { - CustomOpBase() { - OrtCustomOp::version = ORT_API_VERSION; - OrtCustomOp::GetName = [](const OrtCustomOp* this_) { return static_cast(this_)->GetName(); }; - - OrtCustomOp::GetExecutionProviderType = [](const OrtCustomOp* this_) { return static_cast(this_)->GetExecutionProviderType(); }; - - OrtCustomOp::GetInputTypeCount = [](const OrtCustomOp* this_) { return static_cast(this_)->GetInputTypeCount(); }; - OrtCustomOp::GetInputType = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetInputType(index); }; - OrtCustomOp::GetInputMemoryType = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetInputMemoryType(index); }; - - OrtCustomOp::GetOutputTypeCount = [](const OrtCustomOp* this_) { return static_cast(this_)->GetOutputTypeCount(); }; - OrtCustomOp::GetOutputType = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetOutputType(index); }; - -#if defined(_MSC_VER) && !defined(__clang__) -#pragma warning(push) -#pragma warning(disable : 26409) -#endif - OrtCustomOp::KernelDestroy = [](void* op_kernel) { delete static_cast(op_kernel); }; -#if defined(_MSC_VER) && !defined(__clang__) -#pragma warning(pop) -#endif - OrtCustomOp::GetInputCharacteristic = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetInputCharacteristic(index); }; - OrtCustomOp::GetOutputCharacteristic = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetOutputCharacteristic(index); }; - - OrtCustomOp::GetVariadicInputMinArity = [](const OrtCustomOp* this_) { return static_cast(this_)->GetVariadicInputMinArity(); }; - OrtCustomOp::GetVariadicInputHomogeneity = [](const OrtCustomOp* this_) { return static_cast(static_cast(this_)->GetVariadicInputHomogeneity()); }; - OrtCustomOp::GetVariadicOutputMinArity = [](const OrtCustomOp* this_) { return static_cast(this_)->GetVariadicOutputMinArity(); }; - OrtCustomOp::GetVariadicOutputHomogeneity = [](const OrtCustomOp* this_) { return static_cast(static_cast(this_)->GetVariadicOutputHomogeneity()); }; -#ifdef __cpp_if_constexpr - if constexpr (WithStatus) { -#else - if (WithStatus) { -#endif - OrtCustomOp::CreateKernelV2 = [](const OrtCustomOp* this_, const OrtApi* api, const OrtKernelInfo* info, void** op_kernel) -> OrtStatusPtr { - return static_cast(this_)->CreateKernelV2(*api, info, op_kernel); - }; - OrtCustomOp::KernelComputeV2 = [](void* op_kernel, OrtKernelContext* context) -> OrtStatusPtr { - return static_cast(op_kernel)->ComputeV2(context); - }; - } else { - OrtCustomOp::CreateKernelV2 = nullptr; - OrtCustomOp::KernelComputeV2 = nullptr; - - OrtCustomOp::CreateKernel = [](const OrtCustomOp* this_, const OrtApi* api, const OrtKernelInfo* info) { return static_cast(this_)->CreateKernel(*api, info); }; - OrtCustomOp::KernelCompute = [](void* op_kernel, OrtKernelContext* context) { - static_cast(op_kernel)->Compute(context); - }; - } - - SetShapeInferFn(0); - - OrtCustomOp::GetStartVersion = [](const OrtCustomOp* this_) { - return static_cast(this_)->start_ver_; - }; - - OrtCustomOp::GetEndVersion = [](const OrtCustomOp* this_) { - return static_cast(this_)->end_ver_; - }; - - OrtCustomOp::GetMayInplace = nullptr; - OrtCustomOp::ReleaseMayInplace = nullptr; - OrtCustomOp::GetAliasMap = nullptr; - OrtCustomOp::ReleaseAliasMap = nullptr; - } - - // Default implementation of GetExecutionProviderType that returns nullptr to default to the CPU provider - const char* GetExecutionProviderType() const { return nullptr; } - - // Default implementations of GetInputCharacteristic() and GetOutputCharacteristic() below - // (inputs and outputs are required by default) - OrtCustomOpInputOutputCharacteristic GetInputCharacteristic(size_t /*index*/) const { - return OrtCustomOpInputOutputCharacteristic::INPUT_OUTPUT_REQUIRED; - } - - OrtCustomOpInputOutputCharacteristic GetOutputCharacteristic(size_t /*index*/) const { - return OrtCustomOpInputOutputCharacteristic::INPUT_OUTPUT_REQUIRED; - } - - // Default implemention of GetInputMemoryType() that returns OrtMemTypeDefault - OrtMemType GetInputMemoryType(size_t /*index*/) const { - return OrtMemTypeDefault; - } - - // Default implementation of GetVariadicInputMinArity() returns 1 to specify that a variadic input - // should expect at least 1 argument. - int GetVariadicInputMinArity() const { - return 1; - } - - // Default implementation of GetVariadicInputHomegeneity() returns true to specify that all arguments - // to a variadic input should be of the same type. - bool GetVariadicInputHomogeneity() const { - return true; - } - - // Default implementation of GetVariadicOutputMinArity() returns 1 to specify that a variadic output - // should produce at least 1 output value. - int GetVariadicOutputMinArity() const { - return 1; - } - - // Default implementation of GetVariadicOutputHomegeneity() returns true to specify that all output values - // produced by a variadic output should be of the same type. - bool GetVariadicOutputHomogeneity() const { - return true; - } - - // Declare list of session config entries used by this Custom Op. - // Implement this function in order to get configs from CustomOpBase::GetSessionConfigs(). - // This default implementation returns an empty vector of config entries. - std::vector GetSessionConfigKeys() const { - return std::vector{}; - } - - // Ort::CustomOpBase derived class should provide the following static method with the type/shape inferencing - // implementation if needed: - // static OrtStatusPtr InferOutputShape(Ort::ShapeInferContext& context) - template - decltype(&C::InferOutputShape) SetShapeInferFn(decltype(&C::InferOutputShape)) { - OrtCustomOp::InferOutputShapeFn = [](const OrtCustomOp*, OrtShapeInferContext* ort_ctx) -> OrtStatusPtr { - ShapeInferContext ctx(&GetApi(), ort_ctx); - return C::InferOutputShape(ctx); - }; - return {}; - } - - template - void SetShapeInferFn(...) { - OrtCustomOp::InferOutputShapeFn = {}; - } - - protected: - // Helper function that returns a map of session config entries specified by CustomOpBase::GetSessionConfigKeys. - void GetSessionConfigs(std::unordered_map& out, ConstSessionOptions options) const; - - int start_ver_ = 1; - int end_ver_ = MAX_CUSTOM_OP_END_VER; -}; - -namespace detail { -template -struct ValueInfoImpl : Ort::detail::Base { - using B = Ort::detail::Base; - using B::B; - - std::string Name() const; - ConstTypeInfo TypeInfo() const; -}; -} // namespace detail - -// Const object holder that does not own the underlying object -using ConstValueInfo = detail::ValueInfoImpl>; - -/** \brief Wrapper around ::OrtValueInfo - * - */ -struct ValueInfo : detail::ValueInfoImpl { - explicit ValueInfo(std::nullptr_t) {} ///< No instance is created - /// Take ownership of a pointer created by C API - explicit ValueInfo(OrtValueInfo* p) : ValueInfoImpl{p} {} - - // Create ValueInfo for a tensor - explicit ValueInfo(const std::string& name, const ConstTypeInfo& type_info); - - ConstValueInfo GetConst() const { return ConstValueInfo{this->p_}; } -}; - -namespace detail { -template -struct NodeImpl : Ort::detail::Base { - using B = Ort::detail::Base; - using B::B; -}; -} // namespace detail - -/** \brief Wrapper around ::OrtNode - * - */ -struct Node : detail::NodeImpl { - explicit Node(std::nullptr_t) {} ///< No instance is created - explicit Node(OrtNode* p) : NodeImpl{p} {} ///< Take ownership of a pointer created by C API - -#if !defined(ORT_MINIMAL_BUILD) - Node(const std::string& operator_name, const std::string& operator_domain, - const std::string& node_name, - const std::vector& input_names, - const std::vector& output_names); - - /// - /// Wraps CreateNode. Node takes ownership of attributes on success and updates the OpAttr in `attributes` to do so. - /// - Node(const std::string& operator_name, const std::string& operator_domain, - const std::string& node_name, - const std::vector& input_names, - const std::vector& output_names, - std::vector& attributes); - - private: - static void Init(const std::string& operator_name, const std::string& operator_domain, - const std::string& node_name, - const std::vector& input_names, - const std::vector& output_names, - std::vector& attributes, - OrtNode*& node); -#endif // !defined(ORT_MINIMAL_BUILD) -}; - -namespace detail { -template -struct GraphImpl : Ort::detail::Base { - using B = Ort::detail::Base; - using B::B; - -#if !defined(ORT_MINIMAL_BUILD) - void SetInputs(std::vector& inputs); - void SetOutputs(std::vector& outputs); - void AddInitializer(const std::string& name, Value& initializer, bool data_is_external); // Graph takes ownership of Value - void AddNode(Node& node); // Graph takes ownership of Node -#endif // !defined(ORT_MINIMAL_BUILD) -}; -} // namespace detail - -/** \brief Wrapper around ::OrtGraph - * - */ -struct Graph : detail::GraphImpl { - explicit Graph(std::nullptr_t) {} ///< No instance is created - explicit Graph(OrtGraph* p) : GraphImpl{p} {} ///< Take ownership of a pointer created by C API -#if !defined(ORT_MINIMAL_BUILD) - Graph(); -#endif -}; - -namespace detail { -template -struct ModelImpl : Ort::detail::Base { - using B = Ort::detail::Base; - using B::B; - -#if !defined(ORT_MINIMAL_BUILD) - void AddGraph(Graph& graph); -#endif -}; -} // namespace detail - -// Const object holder that does not own the underlying object -using ConstModel = detail::ModelImpl>; - -/** \brief Wrapper around ::OrtModel - * - */ -struct Model : detail::ModelImpl { - using DomainOpsetPair = std::pair; - - explicit Model(std::nullptr_t) {} ///< No instance is created - explicit Model(OrtModel* p) : ModelImpl{p} {} ///< Take ownership of a pointer created by C API - -#if !defined(ORT_MINIMAL_BUILD) - explicit Model(const std::vector& opsets); -#endif - - ConstModel GetConst() const { return ConstModel{this->p_}; } -}; -} // namespace Ort -#include "onnxruntime_cxx_inline.h" +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// Summary: The Ort C++ API is a header only wrapper around the Ort C API. +// +// The C++ API simplifies usage by returning values directly instead of error codes, throwing exceptions on errors +// and automatically releasing resources in the destructors. The primary purpose of C++ API is exception safety so +// all the resources follow RAII and do not leak memory. +// +// Each of the C++ wrapper classes holds only a pointer to the C internal object. Treat them like smart pointers. +// To create an empty object, pass 'nullptr' to the constructor (for example, Env e{nullptr};). However, you can't use them +// until you assign an instance that actually holds an underlying object. +// +// For Ort objects only move assignment between objects is allowed, there are no copy constructors. +// Some objects have explicit 'Clone' methods for this purpose. +// +// ConstXXXX types are copyable since they do not own the underlying C object, so you can pass them to functions as arguments +// by value or by reference. ConstXXXX types are restricted to const only interfaces. +// +// UnownedXXXX are similar to ConstXXXX but also allow non-const interfaces. +// +// The lifetime of the corresponding owning object must eclipse the lifetimes of the ConstXXXX/UnownedXXXX types. They exists so you do not +// have to fallback to C types and the API with the usual pitfalls. In general, do not use C API from your C++ code. + +#pragma once +#include "onnxruntime_c_api.h" +#include "onnxruntime_float16.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef ORT_NO_EXCEPTIONS +#include +#endif + +/** \brief All C++ Onnxruntime APIs are defined inside this namespace + * + */ +namespace Ort { + +/** \brief All C++ methods that can fail will throw an exception of this type + * + * If ORT_NO_EXCEPTIONS is defined, then any error will result in a call to abort() + */ +struct Exception : std::exception { + Exception(std::string&& string, OrtErrorCode code) : message_{std::move(string)}, code_{code} {} + + OrtErrorCode GetOrtErrorCode() const { return code_; } + const char* what() const noexcept override { return message_.c_str(); } + + private: + std::string message_; + OrtErrorCode code_; +}; + +#ifdef ORT_NO_EXCEPTIONS +// The #ifndef is for the very special case where the user of this library wants to define their own way of handling errors. +// NOTE: This header expects control flow to not continue after calling ORT_CXX_API_THROW +#ifndef ORT_CXX_API_THROW +#define ORT_CXX_API_THROW(string, code) \ + do { \ + std::cerr << Ort::Exception(string, code) \ + .what() \ + << std::endl; \ + abort(); \ + } while (false) +#endif +#else +#define ORT_CXX_API_THROW(string, code) \ + throw Ort::Exception(string, code) +#endif + +// This is used internally by the C++ API. This class holds the global variable that points to the OrtApi, +// it's in a template so that we can define a global variable in a header and make +// it transparent to the users of the API. +template +struct Global { + static const OrtApi* api_; +}; + +// If macro ORT_API_MANUAL_INIT is defined, no static initialization will be performed. Instead, user must call InitApi() before using it. +template +#ifdef ORT_API_MANUAL_INIT +const OrtApi* Global::api_{}; +inline void InitApi() noexcept { Global::api_ = OrtGetApiBase()->GetApi(ORT_API_VERSION); } + +// Used by custom operator libraries that are not linked to onnxruntime. Sets the global API object, which is +// required by C++ APIs. +// +// Example mycustomop.cc: +// +// #define ORT_API_MANUAL_INIT +// #include +// #undef ORT_API_MANUAL_INIT +// +// OrtStatus* ORT_API_CALL RegisterCustomOps(OrtSessionOptions* options, const OrtApiBase* api_base) { +// Ort::InitApi(api_base->GetApi(ORT_API_VERSION)); +// // ... +// } +// +inline void InitApi(const OrtApi* api) noexcept { Global::api_ = api; } +#else +#if defined(_MSC_VER) && !defined(__clang__) +#pragma warning(push) +// "Global initializer calls a non-constexpr function." Therefore you can't use ORT APIs in the other global initializers. +// Please define ORT_API_MANUAL_INIT if it conerns you. +#pragma warning(disable : 26426) +#endif +const OrtApi* Global::api_ = OrtGetApiBase()->GetApi(ORT_API_VERSION); +#if defined(_MSC_VER) && !defined(__clang__) +#pragma warning(pop) +#endif +#endif + +/// This returns a reference to the ORT C API. +inline const OrtApi& GetApi() noexcept { return *Global::api_; } + +/// +/// This function returns the onnxruntime version string +/// +/// version string major.minor.rev +std::string GetVersionString(); + +/// +/// This function returns the onnxruntime build information: including git branch, +/// git commit id, build type(Debug/Release/RelWithDebInfo) and cmake cpp flags. +/// +/// string +std::string GetBuildInfoString(); + +/// +/// This is a C++ wrapper for OrtApi::GetAvailableProviders() and +/// returns a vector of strings representing the available execution providers. +/// +/// vector of strings +std::vector GetAvailableProviders(); + +/// +/// This returns a reference to the ORT C Model Editor API. Used if building or augmenting a model at runtime. +/// +/// ORT C Model Editor API reference +inline const OrtModelEditorApi& GetModelEditorApi() { + auto* api = GetApi().GetModelEditorApi(); + if (api == nullptr) { + // minimal build + ORT_CXX_API_THROW("Model Editor API is not available in this build", ORT_FAIL); + } + + return *api; +} + +/// +/// This returns a reference to the ORT C Compile API. Used if compiling a model at runtime. +/// +/// ORT C Compile API reference +inline const OrtCompileApi& GetCompileApi() { + auto* api = GetApi().GetCompileApi(); + if (api == nullptr) { + // minimal build + ORT_CXX_API_THROW("Compile API is not available in this build", ORT_FAIL); + } + + return *api; +} + +/// +/// This returns a reference to the ORT C EP API. Used if authoring a plugin execution provider. +/// +/// ORT C EP API reference +inline const OrtEpApi& GetEpApi() { + auto* api = GetApi().GetEpApi(); + if (api == nullptr) { + // minimal build + ORT_CXX_API_THROW("EP API is not available in this build", ORT_FAIL); + } + + return *api; +} + +/** \brief IEEE 754 half-precision floating point data type + * + * \details This struct is used for converting float to float16 and back + * so the user could feed inputs and fetch outputs using these type. + * + * The size of the structure should align with uint16_t and one can freely cast + * uint16_t buffers to/from Ort::Float16_t to feed and retrieve data. + * + * \code{.unparsed} + * // This example demonstrates converion from float to float16 + * constexpr float values[] = {1.f, 2.f, 3.f, 4.f, 5.f}; + * std::vector fp16_values; + * fp16_values.reserve(std::size(values)); + * std::transform(std::begin(values), std::end(values), std::back_inserter(fp16_values), + * [](float value) { return Ort::Float16_t(value); }); + * + * \endcode + */ +struct Float16_t : onnxruntime_float16::Float16Impl { + private: + /// + /// Constructor from a 16-bit representation of a float16 value + /// No conversion is done here. + /// + /// 16-bit representation + constexpr explicit Float16_t(uint16_t v) noexcept { val = v; } + + public: + using Base = onnxruntime_float16::Float16Impl; + + /// + /// Default constructor + /// + Float16_t() = default; + + /// + /// Explicit conversion to uint16_t representation of float16. + /// + /// uint16_t bit representation of float16 + /// new instance of Float16_t + constexpr static Float16_t FromBits(uint16_t v) noexcept { return Float16_t(v); } + + /// + /// __ctor from float. Float is converted into float16 16-bit representation. + /// + /// float value + explicit Float16_t(float v) noexcept { val = Base::ToUint16Impl(v); } + + /// + /// Converts float16 to float + /// + /// float representation of float16 value + float ToFloat() const noexcept { return Base::ToFloatImpl(); } + + /// + /// Checks if the value is negative + /// + /// true if negative + using Base::IsNegative; + + /// + /// Tests if the value is NaN + /// + /// true if NaN + using Base::IsNaN; + + /// + /// Tests if the value is finite + /// + /// true if finite + using Base::IsFinite; + + /// + /// Tests if the value represents positive infinity. + /// + /// true if positive infinity + using Base::IsPositiveInfinity; + + /// + /// Tests if the value represents negative infinity + /// + /// true if negative infinity + using Base::IsNegativeInfinity; + + /// + /// Tests if the value is either positive or negative infinity. + /// + /// True if absolute value is infinity + using Base::IsInfinity; + + /// + /// Tests if the value is NaN or zero. Useful for comparisons. + /// + /// True if NaN or zero. + using Base::IsNaNOrZero; + + /// + /// Tests if the value is normal (not zero, subnormal, infinite, or NaN). + /// + /// True if so + using Base::IsNormal; + + /// + /// Tests if the value is subnormal (denormal). + /// + /// True if so + using Base::IsSubnormal; + + /// + /// Creates an instance that represents absolute value. + /// + /// Absolute value + using Base::Abs; + + /// + /// Creates a new instance with the sign flipped. + /// + /// Flipped sign instance + using Base::Negate; + + /// + /// IEEE defines that positive and negative zero are equal, this gives us a quick equality check + /// for two values by or'ing the private bits together and stripping the sign. They are both zero, + /// and therefore equivalent, if the resulting value is still zero. + /// + /// first value + /// second value + /// True if both arguments represent zero + using Base::AreZero; + + /// + /// User defined conversion operator. Converts Float16_t to float. + /// + explicit operator float() const noexcept { return ToFloat(); } + + using Base::operator==; + using Base::operator!=; + using Base::operator<; +}; + +static_assert(sizeof(Float16_t) == sizeof(uint16_t), "Sizes must match"); + +/** \brief bfloat16 (Brain Floating Point) data type + * + * \details This struct is used for converting float to bfloat16 and back + * so the user could feed inputs and fetch outputs using these type. + * + * The size of the structure should align with uint16_t and one can freely cast + * uint16_t buffers to/from Ort::BFloat16_t to feed and retrieve data. + * + * \code{.unparsed} + * // This example demonstrates converion from float to float16 + * constexpr float values[] = {1.f, 2.f, 3.f, 4.f, 5.f}; + * std::vector bfp16_values; + * bfp16_values.reserve(std::size(values)); + * std::transform(std::begin(values), std::end(values), std::back_inserter(bfp16_values), + * [](float value) { return Ort::BFloat16_t(value); }); + * + * \endcode + */ +struct BFloat16_t : onnxruntime_float16::BFloat16Impl { + private: + /// + /// Constructor from a uint16_t representation of bfloat16 + /// used in FromBits() to escape overload resolution issue with + /// constructor from float. + /// No conversion is done. + /// + /// 16-bit bfloat16 value + constexpr explicit BFloat16_t(uint16_t v) noexcept { val = v; } + + public: + using Base = onnxruntime_float16::BFloat16Impl; + + BFloat16_t() = default; + + /// + /// Explicit conversion to uint16_t representation of bfloat16. + /// + /// uint16_t bit representation of bfloat16 + /// new instance of BFloat16_t + static constexpr BFloat16_t FromBits(uint16_t v) noexcept { return BFloat16_t(v); } + + /// + /// __ctor from float. Float is converted into bfloat16 16-bit representation. + /// + /// float value + explicit BFloat16_t(float v) noexcept { val = Base::ToUint16Impl(v); } + + /// + /// Converts bfloat16 to float + /// + /// float representation of bfloat16 value + float ToFloat() const noexcept { return Base::ToFloatImpl(); } + + /// + /// Checks if the value is negative + /// + /// true if negative + using Base::IsNegative; + + /// + /// Tests if the value is NaN + /// + /// true if NaN + using Base::IsNaN; + + /// + /// Tests if the value is finite + /// + /// true if finite + using Base::IsFinite; + + /// + /// Tests if the value represents positive infinity. + /// + /// true if positive infinity + using Base::IsPositiveInfinity; + + /// + /// Tests if the value represents negative infinity + /// + /// true if negative infinity + using Base::IsNegativeInfinity; + + /// + /// Tests if the value is either positive or negative infinity. + /// + /// True if absolute value is infinity + using Base::IsInfinity; + + /// + /// Tests if the value is NaN or zero. Useful for comparisons. + /// + /// True if NaN or zero. + using Base::IsNaNOrZero; + + /// + /// Tests if the value is normal (not zero, subnormal, infinite, or NaN). + /// + /// True if so + using Base::IsNormal; + + /// + /// Tests if the value is subnormal (denormal). + /// + /// True if so + using Base::IsSubnormal; + + /// + /// Creates an instance that represents absolute value. + /// + /// Absolute value + using Base::Abs; + + /// + /// Creates a new instance with the sign flipped. + /// + /// Flipped sign instance + using Base::Negate; + + /// + /// IEEE defines that positive and negative zero are equal, this gives us a quick equality check + /// for two values by or'ing the private bits together and stripping the sign. They are both zero, + /// and therefore equivalent, if the resulting value is still zero. + /// + /// first value + /// second value + /// True if both arguments represent zero + using Base::AreZero; + + /// + /// User defined conversion operator. Converts BFloat16_t to float. + /// + explicit operator float() const noexcept { return ToFloat(); } + + // We do not have an inherited impl for the below operators + // as the internal class implements them a little differently + bool operator==(const BFloat16_t& rhs) const noexcept; + bool operator!=(const BFloat16_t& rhs) const noexcept { return !(*this == rhs); } + bool operator<(const BFloat16_t& rhs) const noexcept; +}; + +static_assert(sizeof(BFloat16_t) == sizeof(uint16_t), "Sizes must match"); + +/** \brief float8e4m3fn (Float8 Floating Point) data type + * \details It is necessary for type dispatching to make use of C++ API + * The type is implicitly convertible to/from uint8_t. + * See https://onnx.ai/onnx/technical/float8.html for further details. + */ +struct Float8E4M3FN_t { + uint8_t value; + constexpr Float8E4M3FN_t() noexcept : value(0) {} + constexpr Float8E4M3FN_t(uint8_t v) noexcept : value(v) {} + constexpr operator uint8_t() const noexcept { return value; } + // nan values are treated like any other value for operator ==, != + constexpr bool operator==(const Float8E4M3FN_t& rhs) const noexcept { return value == rhs.value; }; + constexpr bool operator!=(const Float8E4M3FN_t& rhs) const noexcept { return value != rhs.value; }; +}; + +static_assert(sizeof(Float8E4M3FN_t) == sizeof(uint8_t), "Sizes must match"); + +/** \brief float8e4m3fnuz (Float8 Floating Point) data type + * \details It is necessary for type dispatching to make use of C++ API + * The type is implicitly convertible to/from uint8_t. + * See https://onnx.ai/onnx/technical/float8.html for further details. + */ +struct Float8E4M3FNUZ_t { + uint8_t value; + constexpr Float8E4M3FNUZ_t() noexcept : value(0) {} + constexpr Float8E4M3FNUZ_t(uint8_t v) noexcept : value(v) {} + constexpr operator uint8_t() const noexcept { return value; } + // nan values are treated like any other value for operator ==, != + constexpr bool operator==(const Float8E4M3FNUZ_t& rhs) const noexcept { return value == rhs.value; }; + constexpr bool operator!=(const Float8E4M3FNUZ_t& rhs) const noexcept { return value != rhs.value; }; +}; + +static_assert(sizeof(Float8E4M3FNUZ_t) == sizeof(uint8_t), "Sizes must match"); + +/** \brief float8e5m2 (Float8 Floating Point) data type + * \details It is necessary for type dispatching to make use of C++ API + * The type is implicitly convertible to/from uint8_t. + * See https://onnx.ai/onnx/technical/float8.html for further details. + */ +struct Float8E5M2_t { + uint8_t value; + constexpr Float8E5M2_t() noexcept : value(0) {} + constexpr Float8E5M2_t(uint8_t v) noexcept : value(v) {} + constexpr operator uint8_t() const noexcept { return value; } + // nan values are treated like any other value for operator ==, != + constexpr bool operator==(const Float8E5M2_t& rhs) const noexcept { return value == rhs.value; }; + constexpr bool operator!=(const Float8E5M2_t& rhs) const noexcept { return value != rhs.value; }; +}; + +static_assert(sizeof(Float8E5M2_t) == sizeof(uint8_t), "Sizes must match"); + +/** \brief float8e5m2fnuz (Float8 Floating Point) data type + * \details It is necessary for type dispatching to make use of C++ API + * The type is implicitly convertible to/from uint8_t. + * See https://onnx.ai/onnx/technical/float8.html for further details. + */ +struct Float8E5M2FNUZ_t { + uint8_t value; + constexpr Float8E5M2FNUZ_t() noexcept : value(0) {} + constexpr Float8E5M2FNUZ_t(uint8_t v) noexcept : value(v) {} + constexpr operator uint8_t() const noexcept { return value; } + // nan values are treated like any other value for operator ==, != + constexpr bool operator==(const Float8E5M2FNUZ_t& rhs) const noexcept { return value == rhs.value; }; + constexpr bool operator!=(const Float8E5M2FNUZ_t& rhs) const noexcept { return value != rhs.value; }; +}; + +static_assert(sizeof(Float8E5M2FNUZ_t) == sizeof(uint8_t), "Sizes must match"); + +namespace detail { +// This is used internally by the C++ API. This macro is to make it easy to generate overloaded methods for all of the various OrtRelease* functions for every Ort* type +// This can't be done in the C API since C doesn't have function overloading. +#define ORT_DEFINE_RELEASE(NAME) \ + inline void OrtRelease(Ort##NAME* ptr) { GetApi().Release##NAME(ptr); } + +#define ORT_DEFINE_RELEASE_FROM_API_STRUCT(NAME, API_GETTER) \ + inline void OrtRelease(Ort##NAME* ptr) { API_GETTER().Release##NAME(ptr); } + +ORT_DEFINE_RELEASE(Allocator); +ORT_DEFINE_RELEASE(MemoryInfo); +ORT_DEFINE_RELEASE(CustomOpDomain); +ORT_DEFINE_RELEASE(ThreadingOptions); +ORT_DEFINE_RELEASE(Env); +ORT_DEFINE_RELEASE(RunOptions); +ORT_DEFINE_RELEASE(LoraAdapter); +ORT_DEFINE_RELEASE(Session); +ORT_DEFINE_RELEASE(SessionOptions); +ORT_DEFINE_RELEASE(TensorTypeAndShapeInfo); +ORT_DEFINE_RELEASE(SequenceTypeInfo); +ORT_DEFINE_RELEASE(MapTypeInfo); +ORT_DEFINE_RELEASE(TypeInfo); +ORT_DEFINE_RELEASE(Value); +ORT_DEFINE_RELEASE(ModelMetadata); +ORT_DEFINE_RELEASE(IoBinding); +ORT_DEFINE_RELEASE(ArenaCfg); +ORT_DEFINE_RELEASE(Status); +ORT_DEFINE_RELEASE(OpAttr); +ORT_DEFINE_RELEASE(Op); +ORT_DEFINE_RELEASE(KernelInfo); +ORT_DEFINE_RELEASE(ValueInfo); +ORT_DEFINE_RELEASE(Node); +ORT_DEFINE_RELEASE(Graph); +ORT_DEFINE_RELEASE(Model); +ORT_DEFINE_RELEASE(KeyValuePairs) +ORT_DEFINE_RELEASE_FROM_API_STRUCT(ModelCompilationOptions, GetCompileApi); +ORT_DEFINE_RELEASE_FROM_API_STRUCT(EpDevice, GetEpApi); + +#undef ORT_DEFINE_RELEASE +#undef ORT_DEFINE_RELEASE_FROM_API_STRUCT + +/** \brief This is a tagging template type. Use it with Base to indicate that the C++ interface object + * has no ownership of the underlying C object. + */ +template +struct Unowned { + using Type = T; +}; + +/** \brief Used internally by the C++ API. C++ wrapper types inherit from this. + * This is a zero cost abstraction to wrap the C API objects and delete them on destruction. + * + * All of the C++ classes + * a) serve as containers for pointers to objects that are created by the underlying C API. + * Their size is just a pointer size, no need to dynamically allocate them. Use them by value. + * b) Each of struct XXXX, XXX instances function as smart pointers to the underlying C API objects. + * they would release objects owned automatically when going out of scope, they are move-only. + * c) ConstXXXX and UnownedXXX structs function as non-owning, copyable containers for the above pointers. + * ConstXXXX allow calling const interfaces only. They give access to objects that are owned by somebody else + * such as Onnxruntime or instances of XXXX classes. + * d) serve convenient interfaces that return C++ objects and further enhance exception and type safety so they can be used + * in C++ code. + * + */ + +/// +/// This is a non-const pointer holder that is move-only. Disposes of the pointer on destruction. +/// +template +struct Base { + using contained_type = T; + + constexpr Base() = default; + constexpr explicit Base(contained_type* p) noexcept : p_{p} {} + ~Base() { + OrtRelease(p_); + } + + Base(const Base&) = delete; + Base& operator=(const Base&) = delete; + + Base(Base&& v) noexcept : p_{v.p_} { v.p_ = nullptr; } + Base& operator=(Base&& v) noexcept { + OrtRelease(p_); + p_ = v.release(); + return *this; + } + + constexpr operator contained_type*() const noexcept { return p_; } + + /// \brief Relinquishes ownership of the contained C object pointer + /// The underlying object is not destroyed + contained_type* release() { + T* p = p_; + p_ = nullptr; + return p; + } + + protected: + contained_type* p_{}; +}; + +// Undefined. For const types use Base> +template +struct Base; + +/// +/// Covers unowned pointers owned by either the ORT +/// or some other instance of CPP wrappers. +/// Used for ConstXXX and UnownedXXXX types that are copyable. +/// Also convenient to wrap raw OrtXX pointers . +/// +/// +template +struct Base> { + using contained_type = typename Unowned::Type; + + constexpr Base() = default; + constexpr explicit Base(contained_type* p) noexcept : p_{p} {} + + ~Base() = default; + + Base(const Base&) = default; + Base& operator=(const Base&) = default; + + Base(Base&& v) noexcept : p_{v.p_} { v.p_ = nullptr; } + Base& operator=(Base&& v) noexcept { + p_ = nullptr; + std::swap(p_, v.p_); + return *this; + } + + constexpr operator contained_type*() const noexcept { return p_; } + + protected: + contained_type* p_{}; +}; + +// Light functor to release memory with OrtAllocator +struct AllocatedFree { + OrtAllocator* allocator_; + explicit AllocatedFree(OrtAllocator* allocator) + : allocator_(allocator) {} + void operator()(void* ptr) const { + if (ptr) allocator_->Free(allocator_, ptr); + } +}; + +} // namespace detail + +struct AllocatorWithDefaultOptions; +struct Env; +struct EpDevice; +struct Graph; +struct Model; +struct Node; +struct ModelMetadata; +struct TypeInfo; +struct Value; +struct ValueInfo; + +/** \brief unique_ptr typedef used to own strings allocated by OrtAllocators + * and release them at the end of the scope. The lifespan of the given allocator + * must eclipse the lifespan of AllocatedStringPtr instance + */ +using AllocatedStringPtr = std::unique_ptr; + +/** \brief The Status that holds ownership of OrtStatus received from C API + * Use it to safely destroy OrtStatus* returned from the C API. Use appropriate + * constructors to construct an instance of a Status object from exceptions. + */ +struct Status : detail::Base { + using Base = detail::Base; + using Base::Base; + + explicit Status(std::nullptr_t) noexcept {} ///< Create an empty object, must be assigned a valid one to be used + explicit Status(OrtStatus* status) noexcept; ///< Takes ownership of OrtStatus instance returned from the C API. + explicit Status(const Exception&) noexcept; ///< Creates status instance out of exception + explicit Status(const std::exception&) noexcept; ///< Creates status instance out of exception + Status(const char* message, OrtErrorCode code) noexcept; ///< Creates status instance out of null-terminated string message. + std::string GetErrorMessage() const; + OrtErrorCode GetErrorCode() const; + bool IsOK() const noexcept; ///< Returns true if instance represents an OK (non-error) status. +}; + +/** \brief The ThreadingOptions + * + * The ThreadingOptions used for set global threadpools' options of The Env. + */ +struct ThreadingOptions : detail::Base { + /// \brief Wraps OrtApi::CreateThreadingOptions + ThreadingOptions(); + + /// \brief Wraps OrtApi::SetGlobalIntraOpNumThreads + ThreadingOptions& SetGlobalIntraOpNumThreads(int intra_op_num_threads); + + /// \brief Wraps OrtApi::SetGlobalInterOpNumThreads + ThreadingOptions& SetGlobalInterOpNumThreads(int inter_op_num_threads); + + /// \brief Wraps OrtApi::SetGlobalSpinControl + ThreadingOptions& SetGlobalSpinControl(int allow_spinning); + + /// \brief Wraps OrtApi::SetGlobalDenormalAsZero + ThreadingOptions& SetGlobalDenormalAsZero(); + + /// \brief Wraps OrtApi::SetGlobalCustomCreateThreadFn + ThreadingOptions& SetGlobalCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn); + + /// \brief Wraps OrtApi::SetGlobalCustomThreadCreationOptions + ThreadingOptions& SetGlobalCustomThreadCreationOptions(void* ort_custom_thread_creation_options); + + /// \brief Wraps OrtApi::SetGlobalCustomJoinThreadFn + ThreadingOptions& SetGlobalCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn); +}; + +namespace detail { +template +struct KeyValuePairsImpl : Ort::detail::Base { + using B = Ort::detail::Base; + using B::B; + + const char* GetValue(const char* key) const; + + // get the pairs in unordered_map. needs to copy to std::string so the hash works as expected + std::unordered_map GetKeyValuePairs() const; + // get the pairs in two vectors. entries will be 1:1 between keys and values. avoids copying to std::string + void GetKeyValuePairs(std::vector& keys, std::vector& values) const; +}; +} // namespace detail + +// Const object holder that does not own the underlying object +using ConstKeyValuePairs = detail::KeyValuePairsImpl>; + +/** \brief Wrapper around ::OrtKeyValuePair */ +struct KeyValuePairs : detail::KeyValuePairsImpl { + explicit KeyValuePairs(std::nullptr_t) {} ///< No instance is created + /// Take ownership of a pointer created by C API + explicit KeyValuePairs(OrtKeyValuePairs* p) : KeyValuePairsImpl{p} {} + + /// \brief Wraps OrtApi::CreateKeyValuePairs + explicit KeyValuePairs(); + + /// \brief Wraps OrtApi::CreateKeyValuePairs and OrtApi::AddKeyValuePair + explicit KeyValuePairs(const std::unordered_map& kv_pairs); + + /// \brief Wraps OrtApi::AddKeyValuePair + void Add(const char* key, const char* value); + + /// \brief Wraps OrtApi::RemoveKeyValuePair + void Remove(const char* key); + + ConstKeyValuePairs GetConst() const { return ConstKeyValuePairs{this->p_}; } +}; + +namespace detail { +template +struct HardwareDeviceImpl : Ort::detail::Base { + using B = Ort::detail::Base; + using B::B; + + OrtHardwareDeviceType Type() const; + uint32_t VendorId() const; + uint32_t DeviceId() const; + const char* Vendor() const; + ConstKeyValuePairs Metadata() const; +}; +} // namespace detail + +/** \brief Wrapper around ::OrtHardwareDevice + * \remarks HardwareDevice is always read-only for API users. + */ +using ConstHardwareDevice = detail::HardwareDeviceImpl>; + +namespace detail { +template +struct EpDeviceImpl : Ort::detail::Base { + using B = Ort::detail::Base; + using B::B; + + const char* EpName() const; + const char* EpVendor() const; + ConstKeyValuePairs EpMetadata() const; + ConstKeyValuePairs EpOptions() const; + ConstHardwareDevice Device() const; +}; +} // namespace detail + +/** \brief Wrapper around ::OrtEpDevice + * \remarks EpDevice is always read-only for ORT API users. + */ +using ConstEpDevice = detail::EpDeviceImpl>; + +/** \brief Mutable EpDevice that is created by EpApi users. + */ +struct EpDevice : detail::EpDeviceImpl { + explicit EpDevice(std::nullptr_t) {} ///< No instance is created + explicit EpDevice(OrtEpDevice* p) : EpDeviceImpl{p} {} ///< Take ownership of a pointer created by C API + + /// \brief Wraps OrtEpApi::CreateEpDevice + EpDevice(OrtEpFactory& ep_factory, ConstHardwareDevice& hardware_device, + ConstKeyValuePairs ep_metadata = {}, ConstKeyValuePairs ep_options = {}); +}; + +/** \brief The Env (Environment) + * + * The Env holds the logging state used by all other objects. + * Note: One Env must be created before using any other Onnxruntime functionality + */ +struct Env : detail::Base { + explicit Env(std::nullptr_t) {} ///< Create an empty Env object, must be assigned a valid one to be used + + /// \brief Wraps OrtApi::CreateEnv + Env(OrtLoggingLevel logging_level = ORT_LOGGING_LEVEL_WARNING, _In_ const char* logid = ""); + + /// \brief Wraps OrtApi::CreateEnvWithCustomLogger + Env(OrtLoggingLevel logging_level, const char* logid, OrtLoggingFunction logging_function, void* logger_param); + + /// \brief Wraps OrtApi::CreateEnvWithGlobalThreadPools + Env(const OrtThreadingOptions* tp_options, OrtLoggingLevel logging_level = ORT_LOGGING_LEVEL_WARNING, _In_ const char* logid = ""); + + /// \brief Wraps OrtApi::CreateEnvWithCustomLoggerAndGlobalThreadPools + Env(const OrtThreadingOptions* tp_options, OrtLoggingFunction logging_function, void* logger_param, + OrtLoggingLevel logging_level = ORT_LOGGING_LEVEL_WARNING, _In_ const char* logid = ""); + + /// \brief C Interop Helper + explicit Env(OrtEnv* p) : Base{p} {} + + Env& EnableTelemetryEvents(); ///< Wraps OrtApi::EnableTelemetryEvents + Env& DisableTelemetryEvents(); ///< Wraps OrtApi::DisableTelemetryEvents + + Env& UpdateEnvWithCustomLogLevel(OrtLoggingLevel log_severity_level); ///< Wraps OrtApi::UpdateEnvWithCustomLogLevel + + Env& CreateAndRegisterAllocator(const OrtMemoryInfo* mem_info, const OrtArenaCfg* arena_cfg); ///< Wraps OrtApi::CreateAndRegisterAllocator + + Env& CreateAndRegisterAllocatorV2(const std::string& provider_type, const OrtMemoryInfo* mem_info, + const std::unordered_map& options, + const OrtArenaCfg* arena_cfg); ///< Wraps OrtApi::CreateAndRegisterAllocatorV2 + + Env& RegisterExecutionProviderLibrary(const char* registration_name, const std::basic_string& path); ///< Wraps OrtApi::RegisterExecutionProviderLibrary + Env& UnregisterExecutionProviderLibrary(const char* registration_name); ///< Wraps OrtApi::UnregisterExecutionProviderLibrary + + std::vector GetEpDevices() const; +}; + +/** \brief Custom Op Domain + * + */ +struct CustomOpDomain : detail::Base { + using Base = detail::Base; + using Base::Base; + + explicit CustomOpDomain(std::nullptr_t) {} ///< Create an empty CustomOpDomain object, must be assigned a valid one to be used + + /// \brief Wraps OrtApi::CreateCustomOpDomain + explicit CustomOpDomain(const char* domain); + + // This does not take ownership of the op, simply registers it. + void Add(const OrtCustomOp* op); ///< Wraps CustomOpDomain_Add +}; + +/// \brief LoraAdapter holds a set of Lora Parameters loaded from a single file +struct LoraAdapter : detail::Base { + using Base = detail::Base; + using Base::Base; + + explicit LoraAdapter(std::nullptr_t) {} ///< Create an empty LoraAdapter object, must be assigned a valid one to be used + /// \brief Wraps OrtApi::CreateLoraAdapter + /// + /// The function attempts to load the adapter from the specified file + /// \param adapter_path The path to the Lora adapter + /// \param allocator optional pointer to a device allocator. If nullptr, the data stays on CPU. It would still + /// be copied to device if required by the model at inference time. + static LoraAdapter CreateLoraAdapter(const std::basic_string& adapter_path, + OrtAllocator* allocator); + + /// \brief Wraps OrtApi::CreateLoraAdapterFromArray + /// + /// The function attempts to load the adapter from the specified byte array. + /// \param bytes The byte array containing file LoraAdapter format + /// \param num_bytes The number of bytes in the byte array + /// \param allocator optional pointer to a device allocator. If nullptr, the data stays on CPU. It would still + /// be copied to device if required by the model at inference time. + static LoraAdapter CreateLoraAdapterFromArray(const void* bytes, size_t num_bytes, + OrtAllocator* allocator); +}; + +/** \brief RunOptions + * + */ +struct RunOptions : detail::Base { + explicit RunOptions(std::nullptr_t) {} ///< Create an empty RunOptions object, must be assigned a valid one to be used + RunOptions(); ///< Wraps OrtApi::CreateRunOptions + + RunOptions& SetRunLogVerbosityLevel(int); ///< Wraps OrtApi::RunOptionsSetRunLogVerbosityLevel + int GetRunLogVerbosityLevel() const; ///< Wraps OrtApi::RunOptionsGetRunLogVerbosityLevel + + RunOptions& SetRunLogSeverityLevel(int); ///< Wraps OrtApi::RunOptionsSetRunLogSeverityLevel + int GetRunLogSeverityLevel() const; ///< Wraps OrtApi::RunOptionsGetRunLogSeverityLevel + + RunOptions& SetRunTag(const char* run_tag); ///< wraps OrtApi::RunOptionsSetRunTag + const char* GetRunTag() const; ///< Wraps OrtApi::RunOptionsGetRunTag + + RunOptions& AddConfigEntry(const char* config_key, const char* config_value); ///< Wraps OrtApi::AddRunConfigEntry + + /** \brief Terminates all currently executing Session::Run calls that were made using this RunOptions instance + * + * If a currently executing session needs to be force terminated, this can be called from another thread to force it to fail with an error + * Wraps OrtApi::RunOptionsSetTerminate + */ + RunOptions& SetTerminate(); + + /** \brief Clears the terminate flag so this RunOptions instance can be used in a new Session::Run call without it instantly terminating + * + * Wraps OrtApi::RunOptionsUnsetTerminate + */ + RunOptions& UnsetTerminate(); + + /** \brief Add the LoraAdapter to the list of active adapters. + * The setting does not affect RunWithBinding() calls. + * + * Wraps OrtApi::RunOptionsAddActiveLoraAdapter + * \param adapter The LoraAdapter to be used as the active adapter + */ + RunOptions& AddActiveLoraAdapter(const LoraAdapter& adapter); +}; + +namespace detail { +// Utility function that returns a SessionOption config entry key for a specific custom operator. +// Ex: custom_op.[custom_op_name].[config] +std::string MakeCustomOpConfigEntryKey(const char* custom_op_name, const char* config); +} // namespace detail + +/// +/// Class that represents session configuration entries for one or more custom operators. +/// +/// Example: +/// Ort::CustomOpConfigs op_configs; +/// op_configs.AddConfig("my_custom_op", "device_type", "CPU"); +/// +/// Passed to Ort::SessionOptions::RegisterCustomOpsLibrary. +/// +struct CustomOpConfigs { + CustomOpConfigs() = default; + ~CustomOpConfigs() = default; + CustomOpConfigs(const CustomOpConfigs&) = default; + CustomOpConfigs& operator=(const CustomOpConfigs&) = default; + CustomOpConfigs(CustomOpConfigs&& o) = default; + CustomOpConfigs& operator=(CustomOpConfigs&& o) = default; + + /** \brief Adds a session configuration entry/value for a specific custom operator. + * + * \param custom_op_name The name of the custom operator for which to add a configuration entry. + * Must match the name returned by the CustomOp's GetName() method. + * \param config_key The name of the configuration entry. + * \param config_value The value of the configuration entry. + * \return A reference to this object to enable call chaining. + */ + CustomOpConfigs& AddConfig(const char* custom_op_name, const char* config_key, const char* config_value); + + /** \brief Returns a flattened map of custom operator configuration entries and their values. + * + * The keys has been flattened to include both the custom operator name and the configuration entry key name. + * For example, a prior call to AddConfig("my_op", "key", "value") corresponds to the flattened key/value pair + * {"my_op.key", "value"}. + * + * \return An unordered map of flattened configurations. + */ + const std::unordered_map& GetFlattenedConfigs() const; + + private: + std::unordered_map flat_configs_; +}; + +/** \brief Options object used when creating a new Session object + * + * Wraps ::OrtSessionOptions object and methods + */ + +struct SessionOptions; + +namespace detail { +// we separate const-only methods because passing const ptr to non-const methods +// is only discovered when inline methods are compiled which is counter-intuitive +template +struct ConstSessionOptionsImpl : Base { + using B = Base; + using B::B; + + SessionOptions Clone() const; ///< Creates and returns a copy of this SessionOptions object. Wraps OrtApi::CloneSessionOptions + + std::string GetConfigEntry(const char* config_key) const; ///< Wraps OrtApi::GetSessionConfigEntry + bool HasConfigEntry(const char* config_key) const; ///< Wraps OrtApi::HasSessionConfigEntry + std::string GetConfigEntryOrDefault(const char* config_key, const std::string& def) const; +}; + +template +struct SessionOptionsImpl : ConstSessionOptionsImpl { + using B = ConstSessionOptionsImpl; + using B::B; + + SessionOptionsImpl& SetIntraOpNumThreads(int intra_op_num_threads); ///< Wraps OrtApi::SetIntraOpNumThreads + SessionOptionsImpl& SetInterOpNumThreads(int inter_op_num_threads); ///< Wraps OrtApi::SetInterOpNumThreads + SessionOptionsImpl& SetGraphOptimizationLevel(GraphOptimizationLevel graph_optimization_level); ///< Wraps OrtApi::SetSessionGraphOptimizationLevel + SessionOptionsImpl& SetDeterministicCompute(bool value); ///< Wraps OrtApi::SetDeterministicCompute + + SessionOptionsImpl& EnableCpuMemArena(); ///< Wraps OrtApi::EnableCpuMemArena + SessionOptionsImpl& DisableCpuMemArena(); ///< Wraps OrtApi::DisableCpuMemArena + + SessionOptionsImpl& SetOptimizedModelFilePath(const ORTCHAR_T* optimized_model_file); ///< Wraps OrtApi::SetOptimizedModelFilePath + + SessionOptionsImpl& EnableProfiling(const ORTCHAR_T* profile_file_prefix); ///< Wraps OrtApi::EnableProfiling + SessionOptionsImpl& DisableProfiling(); ///< Wraps OrtApi::DisableProfiling + + SessionOptionsImpl& EnableOrtCustomOps(); ///< Wraps OrtApi::EnableOrtCustomOps + + SessionOptionsImpl& EnableMemPattern(); ///< Wraps OrtApi::EnableMemPattern + SessionOptionsImpl& DisableMemPattern(); ///< Wraps OrtApi::DisableMemPattern + + SessionOptionsImpl& SetExecutionMode(ExecutionMode execution_mode); ///< Wraps OrtApi::SetSessionExecutionMode + + SessionOptionsImpl& SetLoadCancellationFlag(bool value); ///< Wraps OrtApi::SessionOptionsSetLoadCancellationFlag + + SessionOptionsImpl& SetLogId(const char* logid); ///< Wraps OrtApi::SetSessionLogId + SessionOptionsImpl& SetLogSeverityLevel(int level); ///< Wraps OrtApi::SetSessionLogSeverityLevel + + SessionOptionsImpl& Add(OrtCustomOpDomain* custom_op_domain); ///< Wraps OrtApi::AddCustomOpDomain + + SessionOptionsImpl& DisablePerSessionThreads(); ///< Wraps OrtApi::DisablePerSessionThreads + + SessionOptionsImpl& AddConfigEntry(const char* config_key, const char* config_value); ///< Wraps OrtApi::AddSessionConfigEntry + + SessionOptionsImpl& AddInitializer(const char* name, const OrtValue* ort_val); ///< Wraps OrtApi::AddInitializer + SessionOptionsImpl& AddExternalInitializers(const std::vector& names, const std::vector& ort_values); ///< Wraps OrtApi::AddExternalInitializers + SessionOptionsImpl& AddExternalInitializersFromFilesInMemory(const std::vector>& external_initializer_file_names, + const std::vector& external_initializer_file_buffer_array, + const std::vector& external_initializer_file_lengths); ///< Wraps OrtApi::AddExternalInitializersFromFilesInMemory + + SessionOptionsImpl& AppendExecutionProvider_CUDA(const OrtCUDAProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_CUDA + SessionOptionsImpl& AppendExecutionProvider_CUDA_V2(const OrtCUDAProviderOptionsV2& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_CUDA_V2 + SessionOptionsImpl& AppendExecutionProvider_ROCM(const OrtROCMProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_ROCM + SessionOptionsImpl& AppendExecutionProvider_OpenVINO(const OrtOpenVINOProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_OpenVINO + ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_OpenVINO_V2 + SessionOptionsImpl& AppendExecutionProvider_OpenVINO_V2(const std::unordered_map& provider_options = {}); + SessionOptionsImpl& AppendExecutionProvider_TensorRT(const OrtTensorRTProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_TensorRT + SessionOptionsImpl& AppendExecutionProvider_TensorRT_V2(const OrtTensorRTProviderOptionsV2& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_TensorRT + SessionOptionsImpl& AppendExecutionProvider_MIGraphX(const OrtMIGraphXProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_MIGraphX + /// Wraps OrtApi::SessionOptionsAppendExecutionProvider_CANN + SessionOptionsImpl& AppendExecutionProvider_CANN(const OrtCANNProviderOptions& provider_options); + /// Wraps OrtApi::SessionOptionsAppendExecutionProvider_Dnnl + SessionOptionsImpl& AppendExecutionProvider_Dnnl(const OrtDnnlProviderOptions& provider_options); + /// Wraps OrtApi::SessionOptionsAppendExecutionProvider. Currently supports QNN, SNPE and XNNPACK. + SessionOptionsImpl& AppendExecutionProvider(const std::string& provider_name, + const std::unordered_map& provider_options = {}); + + /// Append EPs that have been registered previously with the OrtEnv. + /// Wraps OrtApi::SessionOptionsAppendExecutionProvider_V2 + SessionOptionsImpl& AppendExecutionProvider_V2(Env& env, const std::vector& ep_devices, + const KeyValuePairs& ep_options); + /// Append EPs that have been registered previously with the OrtEnv. + /// Wraps OrtApi::SessionOptionsAppendExecutionProvider_V2 + SessionOptionsImpl& AppendExecutionProvider_V2(Env& env, const std::vector& ep_devices, + const std::unordered_map& ep_options); + + /// Wraps OrtApi::SessionOptionsSetEpSelectionPolicy + SessionOptionsImpl& SetEpSelectionPolicy(OrtExecutionProviderDevicePolicy policy); + + /// Wraps OrtApi::SessionOptionsSetEpSelectionPolicyDelegate + SessionOptionsImpl& SetEpSelectionPolicy(EpSelectionDelegate delegate, void* state = nullptr); + + SessionOptionsImpl& SetCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn); ///< Wraps OrtApi::SessionOptionsSetCustomCreateThreadFn + SessionOptionsImpl& SetCustomThreadCreationOptions(void* ort_custom_thread_creation_options); ///< Wraps OrtApi::SessionOptionsSetCustomThreadCreationOptions + SessionOptionsImpl& SetCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn); ///< Wraps OrtApi::SessionOptionsSetCustomJoinThreadFn + + ///< Registers the custom operator from the specified shared library via OrtApi::RegisterCustomOpsLibrary_V2. + ///< The custom operator configurations are optional. If provided, custom operator configs are set via + ///< OrtApi::AddSessionConfigEntry. + SessionOptionsImpl& RegisterCustomOpsLibrary(const ORTCHAR_T* library_name, const CustomOpConfigs& custom_op_configs = {}); + + SessionOptionsImpl& RegisterCustomOpsUsingFunction(const char* function_name); ///< Wraps OrtApi::RegisterCustomOpsUsingFunction + + ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_VitisAI + SessionOptionsImpl& AppendExecutionProvider_VitisAI(const std::unordered_map& provider_options = {}); +}; +} // namespace detail + +using UnownedSessionOptions = detail::SessionOptionsImpl>; +using ConstSessionOptions = detail::ConstSessionOptionsImpl>; + +/** \brief Wrapper around ::OrtSessionOptions + * + */ +struct SessionOptions : detail::SessionOptionsImpl { + explicit SessionOptions(std::nullptr_t) {} ///< Create an empty SessionOptions object, must be assigned a valid one to be used + SessionOptions(); ///< Wraps OrtApi::CreateSessionOptions + explicit SessionOptions(OrtSessionOptions* p) : SessionOptionsImpl{p} {} ///< Used for interop with the C API + UnownedSessionOptions GetUnowned() const { return UnownedSessionOptions{this->p_}; } + ConstSessionOptions GetConst() const { return ConstSessionOptions{this->p_}; } +}; + +/** \brief Options object used when compiling a model. + * + * Wraps ::OrtModelCompilationOptions object and methods + */ +struct ModelCompilationOptions : detail::Base { + using Base = detail::Base; + using Base::Base; + + explicit ModelCompilationOptions(std::nullptr_t) {} ///< Create an empty ModelCompilationOptions object, must be assigned a valid one to be used. + + ModelCompilationOptions(const Env& env, const SessionOptions& session_options); ///< Wraps OrtApi::CreateModelCompilationOptionsFromSessionOptions + ModelCompilationOptions(const Env& env, ConstSessionOptions session_options); ///< Wraps OrtApi::CreateModelCompilationOptionsFromSessionOptions + + ModelCompilationOptions& SetInputModelPath(const ORTCHAR_T* input_model_path); ///< Wraps OrtApi::ModelCompilationOptions_SetInputModelPath + ModelCompilationOptions& SetInputModelFromBuffer(const void* input_model_data, + size_t input_model_data_size); ///< Wraps OrtApi::ModelCompilationOptions_SetInputModelFromBuffer + ModelCompilationOptions& SetEpContextEmbedMode(bool embed_ep_context_in_model); ///< Wraps OrtApi::ModelCompilationOptions_SetEpContextEmbedMode + ModelCompilationOptions& SetOutputModelPath(const ORTCHAR_T* output_model_path); ///< Wraps OrtApi::ModelCompilationOptions_SetOutputModelPath + ModelCompilationOptions& SetOutputModelExternalInitializersFile(const ORTCHAR_T* file_path, + size_t initializer_size_threshold); ///< Wraps OrtApi::ModelCompilationOptions_SetOutputModelExternalInitializersFile + ModelCompilationOptions& SetOutputModelBuffer(OrtAllocator* allocator, void** output_model_buffer_ptr, + size_t* output_model_buffer_size_ptr); ///< Wraps OrtApi::ModelCompilationOptions_SetOutputModelBuffer +}; + +/** \brief Compiles an input model to generate a model with EPContext nodes that execute EP-specific kernels. Wraps OrtApi::CompileModels. + * + * \param env: ORT environment object. + * \param model_compilation_options: Compilation options for a model. + * \return A Status indicating success or failure. + */ +Status CompileModel(const Env& env, const ModelCompilationOptions& model_compilation_options); + +/** \brief Wrapper around ::OrtModelMetadata + * + */ +struct ModelMetadata : detail::Base { + using Base = detail::Base; + using Base::Base; + + explicit ModelMetadata(std::nullptr_t) {} ///< Create an empty ModelMetadata object, must be assigned a valid one to be used + + /** \brief Returns a copy of the producer name. + * + * \param allocator to allocate memory for the copy of the name returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr GetProducerNameAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetProducerName + + /** \brief Returns a copy of the graph name. + * + * \param allocator to allocate memory for the copy of the name returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr GetGraphNameAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetGraphName + + /** \brief Returns a copy of the domain name. + * + * \param allocator to allocate memory for the copy of the name returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr GetDomainAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetDomain + + /** \brief Returns a copy of the description. + * + * \param allocator to allocate memory for the copy of the string returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr GetDescriptionAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetDescription + + /** \brief Returns a copy of the graph description. + * + * \param allocator to allocate memory for the copy of the string returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr GetGraphDescriptionAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetGraphDescription + + /** \brief Returns a vector of copies of the custom metadata keys. + * + * \param allocator to allocate memory for the copy of the string returned + * \return a instance std::vector of smart pointers that would deallocate the buffers when out of scope. + * The OrtAllocator instance must be valid at the point of memory release. + */ + std::vector GetCustomMetadataMapKeysAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetCustomMetadataMapKeys + + /** \brief Looks up a value by a key in the Custom Metadata map + * + * \param key zero terminated string key to lookup + * \param allocator to allocate memory for the copy of the string returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * maybe nullptr if key is not found. + * + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr LookupCustomMetadataMapAllocated(const char* key, OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataLookupCustomMetadataMap + + int64_t GetVersion() const; ///< Wraps OrtApi::ModelMetadataGetVersion +}; + +struct IoBinding; + +namespace detail { + +// we separate const-only methods because passing const ptr to non-const methods +// is only discovered when inline methods are compiled which is counter-intuitive +template +struct ConstSessionImpl : Base { + using B = Base; + using B::B; + + size_t GetInputCount() const; ///< Returns the number of model inputs + size_t GetOutputCount() const; ///< Returns the number of model outputs + size_t GetOverridableInitializerCount() const; ///< Returns the number of inputs that have defaults that can be overridden + + std::vector GetInputNames() const; + std::vector GetOutputNames() const; + std::vector GetOverridableInitializerNames() const; + + /** \brief Returns a copy of input name at the specified index. + * + * \param index must less than the value returned by GetInputCount() + * \param allocator to allocate memory for the copy of the name returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr GetInputNameAllocated(size_t index, OrtAllocator* allocator) const; + + /** \brief Returns a copy of output name at then specified index. + * + * \param index must less than the value returned by GetOutputCount() + * \param allocator to allocate memory for the copy of the name returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr GetOutputNameAllocated(size_t index, OrtAllocator* allocator) const; + + /** \brief Returns a copy of the overridable initializer name at then specified index. + * + * \param index must less than the value returned by GetOverridableInitializerCount() + * \param allocator to allocate memory for the copy of the name returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr GetOverridableInitializerNameAllocated(size_t index, OrtAllocator* allocator) const; ///< Wraps OrtApi::SessionGetOverridableInitializerName + + uint64_t GetProfilingStartTimeNs() const; ///< Wraps OrtApi::SessionGetProfilingStartTimeNs + ModelMetadata GetModelMetadata() const; ///< Wraps OrtApi::SessionGetModelMetadata + + TypeInfo GetInputTypeInfo(size_t index) const; ///< Wraps OrtApi::SessionGetInputTypeInfo + TypeInfo GetOutputTypeInfo(size_t index) const; ///< Wraps OrtApi::SessionGetOutputTypeInfo + TypeInfo GetOverridableInitializerTypeInfo(size_t index) const; ///< Wraps OrtApi::SessionGetOverridableInitializerTypeInfo + + int GetOpset(const std::string& domain) const; ///< Wraps OrtApi::SessionGetOpsetForDomain + + // Will move before checkin if that's the case. + std::vector GetInputs() const; + std::vector GetOutputs() const; +}; + +template +struct SessionImpl : ConstSessionImpl { + using B = ConstSessionImpl; + using B::B; + + /** \brief Run the model returning results in an Ort allocated vector. + * + * Wraps OrtApi::Run + * + * The caller provides a list of inputs and a list of the desired outputs to return. + * + * See the output logs for more information on warnings/errors that occur while processing the model. + * Common errors are.. (TODO) + * + * \param[in] run_options + * \param[in] input_names Array of null terminated strings of length input_count that is the list of input names + * \param[in] input_values Array of Value objects of length input_count that is the list of input values + * \param[in] input_count Number of inputs (the size of the input_names & input_values arrays) + * \param[in] output_names Array of C style strings of length output_count that is the list of output names + * \param[in] output_count Number of outputs (the size of the output_names array) + * \return A std::vector of Value objects that directly maps to the output_names array (eg. output_name[0] is the first entry of the returned vector) + */ + std::vector Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, + const char* const* output_names, size_t output_count); + + /** \brief Run the model returning results in user provided outputs + * Same as Run(const RunOptions&, const char* const*, const Value*, size_t,const char* const*, size_t) + */ + void Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, + const char* const* output_names, Value* output_values, size_t output_count); + + void Run(const RunOptions& run_options, const IoBinding&); ///< Wraps OrtApi::RunWithBinding + + /** \brief Run the model asynchronously in a thread owned by intra op thread pool + * + * Wraps OrtApi::RunAsync + * + * \param[in] run_options + * \param[in] input_names Array of null terminated UTF8 encoded strings of the input names + * \param[in] input_values Array of Value objects of length input_count + * \param[in] input_count Number of elements in the input_names and inputs arrays + * \param[in] output_names Array of null terminated UTF8 encoded strings of the output names + * \param[out] output_values Array of provided Values to be filled with outputs. + * On calling RunAsync, output_values[i] could either be initialized by a null pointer or a preallocated OrtValue*. + * Later, on invoking the callback, each output_values[i] of null will be filled with an OrtValue* allocated by onnxruntime. + * Then, an OrtValue** pointer will be casted from output_values, and pass to the callback. + * NOTE: it is customer's duty to finally release output_values and each of its member, + * regardless of whether the member (Ort::Value) is allocated by onnxruntime or preallocated by the customer. + * \param[in] output_count Number of elements in the output_names and outputs array + * \param[in] callback Callback function on model run completion + * \param[in] user_data User data that pass back to the callback + */ + void RunAsync(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, + const char* const* output_names, Value* output_values, size_t output_count, RunAsyncCallbackFn callback, void* user_data); + + /** \brief End profiling and return a copy of the profiling file name. + * + * \param allocator to allocate memory for the copy of the string returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr EndProfilingAllocated(OrtAllocator* allocator); ///< Wraps OrtApi::SessionEndProfiling + + /** \brief Set DynamicOptions for EPs (Execution Providers) + * + * Wraps OrtApi::SetEpDynamicOptions + * + * Valid options can be found in `include\onnxruntime\core\session\onnxruntime_session_options_config_keys.h` + * Look for `kOrtEpDynamicOptions` + * + * \param[in] keys Array of null terminated UTF8 encoded strings of EP dynamic option keys + * \param[in] values Array of null terminated UTF8 encoded string of EP dynamic option values + * \param[in] kv_len Number of elements in the keys and values arrays + */ + void SetEpDynamicOptions(const char* const* keys, const char* const* values, size_t kv_len); + + void FinalizeModelEditorSession(const Model& model, const SessionOptions& options, + OrtPrepackedWeightsContainer* prepacked_weights_container = nullptr); +}; + +} // namespace detail + +using ConstSession = detail::ConstSessionImpl>; +using UnownedSession = detail::SessionImpl>; + +/** \brief Wrapper around ::OrtSession + * + */ +struct Session : detail::SessionImpl { + /// Create an empty Session object, must be assigned a valid one to be used. Wraps OrtApi::CreateSession + explicit Session(std::nullptr_t) {} + explicit Session(OrtSession* p) : SessionImpl{p} {} ///< C API Interop + + Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options); + + /// Wraps OrtApi::CreateSessionWithPrepackedWeightsContainer + Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options, + OrtPrepackedWeightsContainer* prepacked_weights_container); + + /// Wraps OrtApi::CreateSessionFromArray + Session(const Env& env, const void* model_data, size_t model_data_length, const SessionOptions& options); + + /// Wraps OrtApi::CreateSessionFromArrayWithPrepackedWeightsContainer + Session(const Env& env, const void* model_data, size_t model_data_length, const SessionOptions& options, + OrtPrepackedWeightsContainer* prepacked_weights_container); + +#if !defined(ORT_MINIMAL_BUILD) + /// Wraps OrtModelEditorApi::CreateSessionFromModel + Session(const Env& env, const Model& model, const SessionOptions& options); + + /// Wraps OrtModelEditorApi::CreateModelEditorSession + static Session CreateModelEditorSession(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options); + + /// Wraps OrtModelEditorApi::CreateModelEditorSession + static Session CreateModelEditorSession(const Env& env, const void* model_data, size_t model_data_length, + const SessionOptions& options); +#endif // !defined(ORT_MINIMAL_BUILD) + + ConstSession GetConst() const { return ConstSession{this->p_}; } + UnownedSession GetUnowned() const { return UnownedSession{this->p_}; } +}; + +namespace detail { +template +struct MemoryInfoImpl : Base { + using B = Base; + using B::B; + + std::string GetAllocatorName() const; + OrtAllocatorType GetAllocatorType() const; + int GetDeviceId() const; + OrtMemoryInfoDeviceType GetDeviceType() const; + OrtMemType GetMemoryType() const; + + template + bool operator==(const MemoryInfoImpl& o) const; +}; +} // namespace detail + +// Const object holder that does not own the underlying object +using ConstMemoryInfo = detail::MemoryInfoImpl>; + +/** \brief Wrapper around ::OrtMemoryInfo + * + */ +struct MemoryInfo : detail::MemoryInfoImpl { + static MemoryInfo CreateCpu(OrtAllocatorType type, OrtMemType mem_type1); + explicit MemoryInfo(std::nullptr_t) {} ///< No instance is created + explicit MemoryInfo(OrtMemoryInfo* p) : MemoryInfoImpl{p} {} ///< Take ownership of a pointer created by C API + MemoryInfo(const char* name, OrtAllocatorType type, int id, OrtMemType mem_type); + ConstMemoryInfo GetConst() const { return ConstMemoryInfo{this->p_}; } +}; + +namespace detail { +template +struct TensorTypeAndShapeInfoImpl : Base { + using B = Base; + using B::B; + + ONNXTensorElementDataType GetElementType() const; ///< Wraps OrtApi::GetTensorElementType + size_t GetElementCount() const; ///< Wraps OrtApi::GetTensorShapeElementCount + + size_t GetDimensionsCount() const; ///< Wraps OrtApi::GetDimensionsCount + + /** \deprecated use GetShape() returning std::vector + * [[deprecated]] + * This interface is unsafe to use + */ + [[deprecated("use GetShape()")]] void GetDimensions(int64_t* values, size_t values_count) const; ///< Wraps OrtApi::GetDimensions + + void GetSymbolicDimensions(const char** values, size_t values_count) const; ///< Wraps OrtApi::GetSymbolicDimensions + std::vector GetSymbolicDimensions() const; + + std::vector GetShape() const; ///< Uses GetDimensionsCount & GetDimensions to return a std::vector of the shape +}; + +} // namespace detail + +using ConstTensorTypeAndShapeInfo = detail::TensorTypeAndShapeInfoImpl>; + +/** \brief Wrapper around ::OrtTensorTypeAndShapeInfo + * + */ +struct TensorTypeAndShapeInfo : detail::TensorTypeAndShapeInfoImpl { + using Base = detail::TensorTypeAndShapeInfoImpl; + using Base::Base; + + /// Create an empty TensorTypeAndShapeInfo object, must be assigned a valid one to be used + explicit TensorTypeAndShapeInfo(std::nullptr_t) {} + /// Used for interop with the C API + explicit TensorTypeAndShapeInfo(OrtTensorTypeAndShapeInfo* p) : TensorTypeAndShapeInfoImpl{p} {} + + // Create a TensorTypeAndShapeInfo object with the specified element type and dimensions + // symbolic_dims are optional, but should be 1:1 with dims. + // The value in symbolic_dims will be used for all entries in dims that are -1. + explicit TensorTypeAndShapeInfo(ONNXTensorElementDataType element_type, + const std::vector& dims, + const std::vector* symbolic_dims = nullptr); + + ConstTensorTypeAndShapeInfo GetConst() const { return ConstTensorTypeAndShapeInfo{this->p_}; } +}; + +namespace detail { +template +struct SequenceTypeInfoImpl : Base { + using B = Base; + using B::B; + TypeInfo GetSequenceElementType() const; ///< Wraps OrtApi::GetSequenceElementType +}; + +} // namespace detail + +using ConstSequenceTypeInfo = detail::SequenceTypeInfoImpl>; + +/** \brief Wrapper around ::OrtSequenceTypeInfo + * + */ +struct SequenceTypeInfo : detail::SequenceTypeInfoImpl { + using Base = detail::SequenceTypeInfoImpl; + using Base::Base; + + explicit SequenceTypeInfo(std::nullptr_t) {} ///< Create an empty SequenceTypeInfo object, must be assigned a valid one to be used + explicit SequenceTypeInfo(OrtSequenceTypeInfo* p) : SequenceTypeInfoImpl{p} {} ///< Used for interop with the C API + ConstSequenceTypeInfo GetConst() const { return ConstSequenceTypeInfo{this->p_}; } +}; + +namespace detail { +template +struct OptionalTypeInfoImpl : Base { + using B = Base; + using B::B; + TypeInfo GetOptionalElementType() const; ///< Wraps OrtApi::CastOptionalTypeToContainedTypeInfo +}; + +} // namespace detail + +// This is always owned by the TypeInfo and can only be obtained from it. +using ConstOptionalTypeInfo = detail::OptionalTypeInfoImpl>; + +namespace detail { +template +struct MapTypeInfoImpl : detail::Base { + using B = Base; + using B::B; + ONNXTensorElementDataType GetMapKeyType() const; ///< Wraps OrtApi::GetMapKeyType + TypeInfo GetMapValueType() const; ///< Wraps OrtApi::GetMapValueType +}; + +} // namespace detail + +using ConstMapTypeInfo = detail::MapTypeInfoImpl>; + +/** \brief Wrapper around ::OrtMapTypeInfo + * + */ +struct MapTypeInfo : detail::MapTypeInfoImpl { + using Base = detail::MapTypeInfoImpl; + using Base::Base; + + explicit MapTypeInfo(std::nullptr_t) {} ///< Create an empty MapTypeInfo object, must be assigned a valid one to be used + explicit MapTypeInfo(OrtMapTypeInfo* p) : MapTypeInfoImpl{p} {} ///< Used for interop with the C API + ConstMapTypeInfo GetConst() const { return ConstMapTypeInfo{this->p_}; } +}; + +namespace detail { +template +struct TypeInfoImpl : detail::Base { + using B = Base; + using B::B; + + ConstTensorTypeAndShapeInfo GetTensorTypeAndShapeInfo() const; ///< Wraps OrtApi::CastTypeInfoToTensorInfo + ConstSequenceTypeInfo GetSequenceTypeInfo() const; ///< Wraps OrtApi::CastTypeInfoToSequenceTypeInfo + ConstMapTypeInfo GetMapTypeInfo() const; ///< Wraps OrtApi::CastTypeInfoToMapTypeInfo + ConstOptionalTypeInfo GetOptionalTypeInfo() const; ///< wraps OrtApi::CastTypeInfoToOptionalTypeInfo + + ONNXType GetONNXType() const; +}; +} // namespace detail + +/// +/// Contains a constant, unowned OrtTypeInfo that can be copied and passed around by value. +/// Provides access to const OrtTypeInfo APIs. +/// +using ConstTypeInfo = detail::TypeInfoImpl>; + +/// +/// Type information that may contain either TensorTypeAndShapeInfo or +/// the information about contained sequence or map depending on the ONNXType. +/// +struct TypeInfo : detail::TypeInfoImpl { + using Base = detail::TypeInfoImpl; + using Base::Base; + + /// Create an empty TypeInfo object, must be assigned a valid one to be used + explicit TypeInfo(std::nullptr_t) {} + explicit TypeInfo(OrtTypeInfo* p) : TypeInfoImpl{p} {} ///< C API Interop + +#if !defined(ORT_MINIMAL_BUILD) + static TypeInfo CreateTensorInfo(ConstTensorTypeAndShapeInfo tensor_info); + static TypeInfo CreateSparseTensorInfo(ConstTensorTypeAndShapeInfo sparse_tensor_info); + static TypeInfo CreateSequenceTypeInfo(ConstTypeInfo sequence_type); + static TypeInfo CreateMapTypeInfo(ONNXTensorElementDataType key_type, ConstTypeInfo value_type); + static TypeInfo CreateOptionalTypeInfo(ConstTypeInfo contained_type); +#endif // !defined(ORT_MINIMAL_BUILD) + + ConstTypeInfo GetConst() const { return ConstTypeInfo{this->p_}; } +}; + +namespace detail { +// This structure is used to feed sparse tensor values +// information for use with FillSparseTensor() API +// if the data type for the sparse tensor values is numeric +// use data.p_data, otherwise, use data.str pointer to feed +// values. data.str is an array of const char* that are zero terminated. +// number of strings in the array must match shape size. +// For fully sparse tensors use shape {0} and set p_data/str +// to nullptr. +struct OrtSparseValuesParam { + const int64_t* values_shape; + size_t values_shape_len; + union { + const void* p_data; + const char** str; + } data; +}; + +// Provides a way to pass shape in a single +// argument +struct Shape { + const int64_t* shape; + size_t shape_len; +}; + +template +struct ConstValueImpl : Base { + using B = Base; + using B::B; + + /// + /// Obtains a pointer to a user defined data for experimental purposes + /// + template + void GetOpaqueData(const char* domain, const char* type_name, R&) const; ///< Wraps OrtApi::GetOpaqueValue + + bool IsTensor() const; ///< Returns true if Value is a tensor, false for other types like map/sequence/etc + bool HasValue() const; /// < Return true if OrtValue contains data and returns false if the OrtValue is a None + + size_t GetCount() const; // If a non tensor, returns 2 for map and N for sequence, where N is the number of elements + Value GetValue(int index, OrtAllocator* allocator) const; + + /// + /// This API returns a full length of string data contained within either a tensor or a sparse Tensor. + /// For sparse tensor it returns a full length of stored non-empty strings (values). The API is useful + /// for allocating necessary memory and calling GetStringTensorContent(). + /// + /// total length of UTF-8 encoded bytes contained. No zero terminators counted. + size_t GetStringTensorDataLength() const; + + /// + /// The API copies all of the UTF-8 encoded string data contained within a tensor or a sparse tensor + /// into a supplied buffer. Use GetStringTensorDataLength() to find out the length of the buffer to allocate. + /// The user must also allocate offsets buffer with the number of entries equal to that of the contained + /// strings. + /// + /// Strings are always assumed to be on CPU, no X-device copy. + /// + /// user allocated buffer + /// length in bytes of the allocated buffer + /// a pointer to the offsets user allocated buffer + /// count of offsets, must be equal to the number of strings contained. + /// that can be obtained from the shape of the tensor or from GetSparseTensorValuesTypeAndShapeInfo() + /// for sparse tensors + void GetStringTensorContent(void* buffer, size_t buffer_length, size_t* offsets, size_t offsets_count) const; + + /// + /// Returns a const typed pointer to the tensor contained data. + /// No type checking is performed, the caller must ensure the type matches the tensor type. + /// + /// + /// const pointer to data, no copies made + template + const R* GetTensorData() const; ///< Wraps OrtApi::GetTensorMutableData /// + + /// + /// Returns a non-typed pointer to a tensor contained data. + /// + /// const pointer to data, no copies made + const void* GetTensorRawData() const; + + /// + /// The API returns type information for data contained in a tensor. For sparse + /// tensors it returns type information for contained non-zero values. + /// It returns dense shape for sparse tensors. + /// + /// TypeInfo + TypeInfo GetTypeInfo() const; + + /// + /// The API returns type information for data contained in a tensor. For sparse + /// tensors it returns type information for contained non-zero values. + /// It returns dense shape for sparse tensors. + /// + /// TensorTypeAndShapeInfo + TensorTypeAndShapeInfo GetTensorTypeAndShapeInfo() const; + + /// + /// This API returns information about the memory allocation used to hold data. + /// + /// Non owning instance of MemoryInfo + ConstMemoryInfo GetTensorMemoryInfo() const; + + /// + /// The API copies UTF-8 encoded bytes for the requested string element + /// contained within a tensor or a sparse tensor into a provided buffer. + /// Use GetStringTensorElementLength() to obtain the length of the buffer to allocate. + /// + /// + /// + /// + void GetStringTensorElement(size_t buffer_length, size_t element_index, void* buffer) const; + + /// + /// Returns string tensor UTF-8 encoded string element. + /// Use of this API is recommended over GetStringTensorElement() that takes void* buffer pointer. + /// + /// + /// std::string + std::string GetStringTensorElement(size_t element_index) const; + + /// + /// The API returns a byte length of UTF-8 encoded string element + /// contained in either a tensor or a spare tensor values. + /// + /// + /// byte length for the specified string element + size_t GetStringTensorElementLength(size_t element_index) const; + +#if !defined(DISABLE_SPARSE_TENSORS) + /// + /// The API returns the sparse data format this OrtValue holds in a sparse tensor. + /// If the sparse tensor was not fully constructed, i.e. Use*() or Fill*() API were not used + /// the value returned is ORT_SPARSE_UNDEFINED. + /// + /// Format enum + OrtSparseFormat GetSparseFormat() const; + + /// + /// The API returns type and shape information for stored non-zero values of the + /// sparse tensor. Use GetSparseTensorValues() to obtain values buffer pointer. + /// + /// TensorTypeAndShapeInfo values information + TensorTypeAndShapeInfo GetSparseTensorValuesTypeAndShapeInfo() const; + + /// + /// The API returns type and shape information for the specified indices. Each supported + /// indices have their own enum values even if a give format has more than one kind of indices. + /// Use GetSparseTensorIndicesData() to obtain pointer to indices buffer. + /// + /// enum requested + /// type and shape information + TensorTypeAndShapeInfo GetSparseTensorIndicesTypeShapeInfo(OrtSparseIndicesFormat format) const; + + /// + /// The API retrieves a pointer to the internal indices buffer. The API merely performs + /// a convenience data type casting on the return type pointer. Make sure you are requesting + /// the right type, use GetSparseTensorIndicesTypeShapeInfo(); + /// + /// type to cast to + /// requested indices kind + /// number of indices entries + /// Pinter to the internal sparse tensor buffer containing indices. Do not free this pointer. + template + const R* GetSparseTensorIndicesData(OrtSparseIndicesFormat indices_format, size_t& num_indices) const; + + /// + /// Returns true if the OrtValue contains a sparse tensor + /// + /// + bool IsSparseTensor() const; + + /// + /// The API returns a pointer to an internal buffer of the sparse tensor + /// containing non-zero values. The API merely does casting. Make sure you + /// are requesting the right data type by calling GetSparseTensorValuesTypeAndShapeInfo() + /// first. + /// + /// numeric data types only. Use GetStringTensor*() to retrieve strings. + /// a pointer to the internal values buffer. Do not free this pointer. + template + const R* GetSparseTensorValues() const; + +#endif +}; + +template +struct ValueImpl : ConstValueImpl { + using B = ConstValueImpl; + using B::B; + + /// + /// Returns a non-const typed pointer to an OrtValue/Tensor contained buffer + /// No type checking is performed, the caller must ensure the type matches the tensor type. + /// + /// non-const pointer to data, no copies made + template + R* GetTensorMutableData(); + + /// + /// Returns a non-typed non-const pointer to a tensor contained data. + /// + /// pointer to data, no copies made + void* GetTensorMutableRawData(); + + /// + // Obtain a reference to an element of data at the location specified + /// by the vector of dims. + /// + /// + /// [in] expressed by a vecotr of dimensions offsets + /// + template + R& At(const std::vector& location); + + /// + /// Set all strings at once in a string tensor + /// + /// [in] An array of strings. Each string in this array must be null terminated. + /// [in] Count of strings in s (Must match the size of \p value's tensor shape) + void FillStringTensor(const char* const* s, size_t s_len); + + /// + /// Set a single string in a string tensor + /// + /// [in] A null terminated UTF-8 encoded string + /// [in] Index of the string in the tensor to set + void FillStringTensorElement(const char* s, size_t index); + + /// + /// Allocate if necessary and obtain a pointer to a UTF-8 + /// encoded string element buffer indexed by the flat element index, + /// of the specified length. + /// + /// This API is for advanced usage. It avoids a need to construct + /// an auxiliary array of string pointers, and allows to write data directly + /// (do not zero terminate). + /// + /// + /// + /// a pointer to a writable buffer + char* GetResizedStringTensorElementBuffer(size_t index, size_t buffer_length); + +#if !defined(DISABLE_SPARSE_TENSORS) + /// + /// Supplies COO format specific indices and marks the contained sparse tensor as being a COO format tensor. + /// Values are supplied with a CreateSparseTensor() API. The supplied indices are not copied and the user + /// allocated buffers lifespan must eclipse that of the OrtValue. + /// The location of the indices is assumed to be the same as specified by OrtMemoryInfo argument at the creation time. + /// + /// pointer to the user allocated buffer with indices. Use nullptr for fully sparse tensors. + /// number of indices entries. Use 0 for fully sparse tensors + void UseCooIndices(int64_t* indices_data, size_t indices_num); + + /// + /// Supplies CSR format specific indices and marks the contained sparse tensor as being a CSR format tensor. + /// Values are supplied with a CreateSparseTensor() API. The supplied indices are not copied and the user + /// allocated buffers lifespan must eclipse that of the OrtValue. + /// The location of the indices is assumed to be the same as specified by OrtMemoryInfo argument at the creation time. + /// + /// pointer to the user allocated buffer with inner indices or nullptr for fully sparse tensors + /// number of csr inner indices or 0 for fully sparse tensors + /// pointer to the user allocated buffer with outer indices or nullptr for fully sparse tensors + /// number of csr outer indices or 0 for fully sparse tensors + void UseCsrIndices(int64_t* inner_data, size_t inner_num, int64_t* outer_data, size_t outer_num); + + /// + /// Supplies BlockSparse format specific indices and marks the contained sparse tensor as being a BlockSparse format tensor. + /// Values are supplied with a CreateSparseTensor() API. The supplied indices are not copied and the user + /// allocated buffers lifespan must eclipse that of the OrtValue. + /// The location of the indices is assumed to be the same as specified by OrtMemoryInfo argument at the creation time. + /// + /// indices shape or a {0} for fully sparse + /// user allocated buffer with indices or nullptr for fully spare tensors + void UseBlockSparseIndices(const Shape& indices_shape, int32_t* indices_data); + + /// + /// The API will allocate memory using the allocator instance supplied to the CreateSparseTensor() API + /// and copy the values and COO indices into it. If data_mem_info specifies that the data is located + /// at difference device than the allocator, a X-device copy will be performed if possible. + /// + /// specified buffer memory description + /// values buffer information. + /// coo indices buffer or nullptr for fully sparse data + /// number of COO indices or 0 for fully sparse data + void FillSparseTensorCoo(const OrtMemoryInfo* data_mem_info, const OrtSparseValuesParam& values_param, + const int64_t* indices_data, size_t indices_num); + + /// + /// The API will allocate memory using the allocator instance supplied to the CreateSparseTensor() API + /// and copy the values and CSR indices into it. If data_mem_info specifies that the data is located + /// at difference device than the allocator, a X-device copy will be performed if possible. + /// + /// specified buffer memory description + /// values buffer information + /// csr inner indices pointer or nullptr for fully sparse tensors + /// number of csr inner indices or 0 for fully sparse tensors + /// pointer to csr indices data or nullptr for fully sparse tensors + /// number of csr outer indices or 0 + void FillSparseTensorCsr(const OrtMemoryInfo* data_mem_info, + const OrtSparseValuesParam& values, + const int64_t* inner_indices_data, size_t inner_indices_num, + const int64_t* outer_indices_data, size_t outer_indices_num); + + /// + /// The API will allocate memory using the allocator instance supplied to the CreateSparseTensor() API + /// and copy the values and BlockSparse indices into it. If data_mem_info specifies that the data is located + /// at difference device than the allocator, a X-device copy will be performed if possible. + /// + /// specified buffer memory description + /// values buffer information + /// indices shape. use {0} for fully sparse tensors + /// pointer to indices data or nullptr for fully sparse tensors + void FillSparseTensorBlockSparse(const OrtMemoryInfo* data_mem_info, + const OrtSparseValuesParam& values, + const Shape& indices_shape, + const int32_t* indices_data); + +#endif +}; + +} // namespace detail + +using ConstValue = detail::ConstValueImpl>; +using UnownedValue = detail::ValueImpl>; + +/** \brief Wrapper around ::OrtValue + * + */ +struct Value : detail::ValueImpl { + using Base = detail::ValueImpl; + using Base::Base; + using OrtSparseValuesParam = detail::OrtSparseValuesParam; + using Shape = detail::Shape; + + explicit Value(std::nullptr_t) {} ///< Create an empty Value object, must be assigned a valid one to be used + Value(Value&&) = default; + Value& operator=(Value&&) = default; + + ConstValue GetConst() const { return ConstValue{this->p_}; } + UnownedValue GetUnowned() const { return UnownedValue{this->p_}; } + + /** \brief Creates a tensor with a user supplied buffer. Wraps OrtApi::CreateTensorWithDataAsOrtValue. + * \tparam T The numeric datatype. This API is not suitable for strings. + * \param info Memory description of where the p_data buffer resides (CPU vs GPU etc). + * \param p_data Pointer to the data buffer. + * \param p_data_element_count The number of elements in the data buffer. + * \param shape Pointer to the tensor shape dimensions. + * \param shape_len The number of tensor shape dimensions. + */ + template + static Value CreateTensor(const OrtMemoryInfo* info, T* p_data, size_t p_data_element_count, + const int64_t* shape, size_t shape_len); + + /** \brief Creates a tensor with a user supplied buffer. Wraps OrtApi::CreateTensorWithDataAsOrtValue. + * + * \param info Memory description of where the p_data buffer resides (CPU vs GPU etc). + * \param p_data Pointer to the data buffer. + * \param p_data_byte_count The number of bytes in the data buffer. + * \param shape Pointer to the tensor shape dimensions. + * \param shape_len The number of tensor shape dimensions. + * \param type The data type. + */ + static Value CreateTensor(const OrtMemoryInfo* info, void* p_data, size_t p_data_byte_count, + const int64_t* shape, size_t shape_len, + ONNXTensorElementDataType type); + + /** \brief Creates a tensor with a user supplied buffer. Wraps OrtApi::CreateTensorWithDataAndDeleterAsOrtValue. + * + * \param deleter OrtAllocator that will be used to free the buffer when no longer required. + * \param p_data Pointer to the data buffer. + * \param p_data_byte_count The number of bytes in the data buffer. + * \param shape Pointer to the tensor shape dimensions. + * \param shape_len The number of tensor shape dimensions. + * \param type The data type. + */ + static Value CreateTensor(OrtAllocator* deleter, void* p_data, size_t p_data_byte_count, + const int64_t* shape, size_t shape_len, + ONNXTensorElementDataType type); + + /** \brief Creates an OrtValue with a tensor using a supplied OrtAllocator. Wraps OrtApi::CreateTensorAsOrtValue. + * This overload will allocate the buffer for the tensor according to the supplied shape and data type. + * The allocated buffer will be owned by the returned OrtValue and will be freed when the OrtValue is released. + * The input data would need to be copied into the allocated buffer. + * This API is not suitable for strings. + * + * \tparam T The numeric datatype. This API is not suitable for strings. + * \param allocator The allocator to use. + * \param shape Pointer to the tensor shape dimensions. + * \param shape_len The number of tensor shape dimensions. + */ + template + static Value CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len); + + /** \brief Creates an OrtValue with a tensor using the supplied OrtAllocator. + * Wraps OrtApi::CreateTensorAsOrtValue. + * The allocated buffer will be owned by the returned OrtValue and will be freed when the OrtValue is released. + * The input data would need to be copied into the allocated buffer. + * This API is not suitable for strings. + * + * \param allocator The allocator to use. + * \param shape Pointer to the tensor shape dimensions. + * \param shape_len The number of tensor shape dimensions. + * \param type The data type. + */ + static Value CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len, + ONNXTensorElementDataType type); + + /** \brief Creates an OrtValue with a Map Onnx type representation. + * The API would ref-count the supplied OrtValues and they will be released + * when the returned OrtValue is released. The caller may release keys and values after the call + * returns. + * + * \param keys an OrtValue containing a tensor with primitive data type keys. + * \param values an OrtValue that may contain a tensor. Ort currently supports only primitive data type values. + */ + static Value CreateMap(const Value& keys, const Value& values); ///< Wraps OrtApi::CreateValue + + /** \brief Creates an OrtValue with a Sequence Onnx type representation. + * The API would ref-count the supplied OrtValues and they will be released + * when the returned OrtValue is released. The caller may release the values after the call + * returns. + * + * \param values a vector of OrtValues that must have the same Onnx value type. + */ + static Value CreateSequence(const std::vector& values); ///< Wraps OrtApi::CreateValue + + /** \brief Creates an OrtValue wrapping an Opaque type. + * This is used for experimental support of non-tensor types. + * + * \tparam T - the type of the value. + * \param domain - zero terminated utf-8 string. Domain of the type. + * \param type_name - zero terminated utf-8 string. Name of the type. + * \param value - the value to be wrapped. + */ + template + static Value CreateOpaque(const char* domain, const char* type_name, const T& value); ///< Wraps OrtApi::CreateOpaqueValue + +#if !defined(DISABLE_SPARSE_TENSORS) + /// + /// This is a simple forwarding method to the other overload that helps deducing + /// data type enum value from the type of the buffer. + /// + /// numeric datatype. This API is not suitable for strings. + /// Memory description where the user buffers reside (CPU vs GPU etc) + /// pointer to the user supplied buffer, use nullptr for fully sparse tensors + /// a would be dense shape of the tensor + /// non zero values shape. Use a single 0 shape for fully sparse tensors. + /// + template + static Value CreateSparseTensor(const OrtMemoryInfo* info, T* p_data, const Shape& dense_shape, + const Shape& values_shape); + + /// + /// Creates an OrtValue instance containing SparseTensor. This constructs + /// a sparse tensor that makes use of user allocated buffers. It does not make copies + /// of the user provided data and does not modify it. The lifespan of user provided buffers should + /// eclipse the life span of the resulting OrtValue. This call constructs an instance that only contain + /// a pointer to non-zero values. To fully populate the sparse tensor call UseIndices() API below + /// to supply a sparse format specific indices. + /// This API is not suitable for string data. Use CreateSparseTensor() with allocator specified so strings + /// can be properly copied into the allocated buffer. + /// + /// Memory description where the user buffers reside (CPU vs GPU etc) + /// pointer to the user supplied buffer, use nullptr for fully sparse tensors + /// a would be dense shape of the tensor + /// non zero values shape. Use a single 0 shape for fully sparse tensors. + /// data type + /// Ort::Value instance containing SparseTensor + static Value CreateSparseTensor(const OrtMemoryInfo* info, void* p_data, const Shape& dense_shape, + const Shape& values_shape, ONNXTensorElementDataType type); + + /// + /// This is a simple forwarding method to the below CreateSparseTensor. + /// This helps to specify data type enum in terms of C++ data type. + /// Use CreateSparseTensor + /// + /// numeric data type only. String data enum must be specified explicitly. + /// allocator to use + /// a would be dense shape of the tensor + /// Ort::Value + template + static Value CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape); + + /// + /// Creates an instance of OrtValue containing sparse tensor. The created instance has no data. + /// The data must be supplied by on of the FillSparseTensor() methods that take both non-zero values + /// and indices. The data will be copied into a buffer that would be allocated using the supplied allocator. + /// Use this API to create OrtValues that contain sparse tensors with all supported data types including + /// strings. + /// + /// allocator to use. The allocator lifespan must eclipse that of the resulting OrtValue + /// a would be dense shape of the tensor + /// data type + /// an instance of Ort::Value + static Value CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape, ONNXTensorElementDataType type); + +#endif // !defined(DISABLE_SPARSE_TENSORS) +}; + +/// +/// Represents native memory allocation coming from one of the +/// OrtAllocators registered with OnnxRuntime. +/// Use it to wrap an allocation made by an allocator +/// so it can be automatically released when no longer needed. +/// +struct MemoryAllocation { + MemoryAllocation(OrtAllocator* allocator, void* p, size_t size); + ~MemoryAllocation(); + MemoryAllocation(const MemoryAllocation&) = delete; + MemoryAllocation& operator=(const MemoryAllocation&) = delete; + MemoryAllocation(MemoryAllocation&&) noexcept; + MemoryAllocation& operator=(MemoryAllocation&&) noexcept; + + void* get() { return p_; } + size_t size() const { return size_; } + + private: + OrtAllocator* allocator_; + void* p_; + size_t size_; +}; + +namespace detail { +template +struct AllocatorImpl : Base { + using B = Base; + using B::B; + + void* Alloc(size_t size); + MemoryAllocation GetAllocation(size_t size); + void Free(void* p); + ConstMemoryInfo GetInfo() const; +}; + +} // namespace detail + +/** \brief Wrapper around ::OrtAllocator default instance that is owned by Onnxruntime + * + */ +struct AllocatorWithDefaultOptions : detail::AllocatorImpl> { + explicit AllocatorWithDefaultOptions(std::nullptr_t) {} ///< Convenience to create a class member and then replace with an instance + AllocatorWithDefaultOptions(); +}; + +/** \brief Wrapper around ::OrtAllocator + * + */ +struct Allocator : detail::AllocatorImpl { + explicit Allocator(std::nullptr_t) {} ///< Convenience to create a class member and then replace with an instance + Allocator(const Session& session, const OrtMemoryInfo*); +}; + +using UnownedAllocator = detail::AllocatorImpl>; + +namespace detail { +namespace binding_utils { +// Bring these out of template +std::vector GetOutputNamesHelper(const OrtIoBinding* binding, OrtAllocator*); +std::vector GetOutputValuesHelper(const OrtIoBinding* binding, OrtAllocator*); +} // namespace binding_utils + +template +struct ConstIoBindingImpl : Base { + using B = Base; + using B::B; + + std::vector GetOutputNames() const; + std::vector GetOutputNames(OrtAllocator*) const; + std::vector GetOutputValues() const; + std::vector GetOutputValues(OrtAllocator*) const; +}; + +template +struct IoBindingImpl : ConstIoBindingImpl { + using B = ConstIoBindingImpl; + using B::B; + + void BindInput(const char* name, const Value&); + void BindOutput(const char* name, const Value&); + void BindOutput(const char* name, const OrtMemoryInfo*); + void ClearBoundInputs(); + void ClearBoundOutputs(); + void SynchronizeInputs(); + void SynchronizeOutputs(); +}; + +} // namespace detail + +using ConstIoBinding = detail::ConstIoBindingImpl>; +using UnownedIoBinding = detail::IoBindingImpl>; + +/** \brief Wrapper around ::OrtIoBinding + * + */ +struct IoBinding : detail::IoBindingImpl { + explicit IoBinding(std::nullptr_t) {} ///< Create an empty object for convenience. Sometimes, we want to initialize members later. + explicit IoBinding(Session& session); + ConstIoBinding GetConst() const { return ConstIoBinding{this->p_}; } + UnownedIoBinding GetUnowned() const { return UnownedIoBinding{this->p_}; } +}; + +/*! \struct Ort::ArenaCfg + * \brief it is a structure that represents the configuration of an arena based allocator + * \details Please see docs/C_API.md for details + */ +struct ArenaCfg : detail::Base { + explicit ArenaCfg(std::nullptr_t) {} ///< Create an empty ArenaCfg object, must be assigned a valid one to be used + /** + * Wraps OrtApi::CreateArenaCfg + * \param max_mem - use 0 to allow ORT to choose the default + * \param arena_extend_strategy - use -1 to allow ORT to choose the default, 0 = kNextPowerOfTwo, 1 = kSameAsRequested + * \param initial_chunk_size_bytes - use -1 to allow ORT to choose the default + * \param max_dead_bytes_per_chunk - use -1 to allow ORT to choose the default + * See docs/C_API.md for details on what the following parameters mean and how to choose these values + */ + ArenaCfg(size_t max_mem, int arena_extend_strategy, int initial_chunk_size_bytes, int max_dead_bytes_per_chunk); +}; + +// +// Custom OPs (only needed to implement custom OPs) +// + +/// +/// This struct provides life time management for custom op attribute +/// +struct OpAttr : detail::Base { + using Base = detail::Base; + using Base::Base; + + explicit OpAttr(std::nullptr_t) {} + OpAttr(const char* name, const void* data, int len, OrtOpAttrType type); +}; + +/** + * Macro that logs a message using the provided logger. Throws an exception if OrtApi::Logger_LogMessage fails. + * Example: ORT_CXX_LOG(logger, ORT_LOGGING_LEVEL_INFO, "Log a message"); + * + * \param logger The Ort::Logger instance to use. Must be a value or reference. + * \param message_severity The logging severity level of the message. + * \param message A null-terminated UTF-8 message to log. + */ +#define ORT_CXX_LOG(logger, message_severity, message) \ + do { \ + if (message_severity >= logger.GetLoggingSeverityLevel()) { \ + Ort::ThrowOnError(logger.LogMessage(message_severity, ORT_FILE, __LINE__, \ + static_cast(__FUNCTION__), message)); \ + } \ + } while (false) + +/** + * Macro that logs a message using the provided logger. Can be used in noexcept code since errors are silently ignored. + * Example: ORT_CXX_LOG_NOEXCEPT(logger, ORT_LOGGING_LEVEL_INFO, "Log a message"); + * + * \param logger The Ort::Logger instance to use. Must be a value or reference. + * \param message_severity The logging severity level of the message. + * \param message A null-terminated UTF-8 message to log. + */ +#define ORT_CXX_LOG_NOEXCEPT(logger, message_severity, message) \ + do { \ + if (message_severity >= logger.GetLoggingSeverityLevel()) { \ + static_cast(logger.LogMessage(message_severity, ORT_FILE, __LINE__, \ + static_cast(__FUNCTION__), message)); \ + } \ + } while (false) + +/** + * Macro that logs a printf-like formatted message using the provided logger. Throws an exception if + * OrtApi::Logger_LogMessage fails or if a formatting error occurs. + * Example: ORT_CXX_LOGF(logger, ORT_LOGGING_LEVEL_INFO, "Log an int: %d", 12); + * + * \param logger The Ort::Logger instance to use. Must be a value or reference. + * \param message_severity The logging severity level of the message. + * \param format A null-terminated UTF-8 format string forwarded to a printf-like function. + * Refer to https://en.cppreference.com/w/cpp/io/c/fprintf for information on valid formats. + * \param ... Zero or more variadic arguments referenced by the format string. + */ +#define ORT_CXX_LOGF(logger, message_severity, /*format,*/...) \ + do { \ + if (message_severity >= logger.GetLoggingSeverityLevel()) { \ + Ort::ThrowOnError(logger.LogFormattedMessage(message_severity, ORT_FILE, __LINE__, \ + static_cast(__FUNCTION__), __VA_ARGS__)); \ + } \ + } while (false) + +/** + * Macro that logs a printf-like formatted message using the provided logger. Can be used in noexcept code since errors + * are silently ignored. + * Example: ORT_CXX_LOGF_NOEXCEPT(logger, ORT_LOGGING_LEVEL_INFO, "Log an int: %d", 12); + * + * \param logger The Ort::Logger instance to use. Must be a value or reference. + * \param message_severity The logging severity level of the message. + * \param format A null-terminated UTF-8 format string forwarded to a printf-like function. + * Refer to https://en.cppreference.com/w/cpp/io/c/fprintf for information on valid formats. + * \param ... Zero or more variadic arguments referenced by the format string. + */ +#define ORT_CXX_LOGF_NOEXCEPT(logger, message_severity, /*format,*/...) \ + do { \ + if (message_severity >= logger.GetLoggingSeverityLevel()) { \ + static_cast(logger.LogFormattedMessage(message_severity, ORT_FILE, __LINE__, \ + static_cast(__FUNCTION__), __VA_ARGS__)); \ + } \ + } while (false) + +/// +/// This class represents an ONNX Runtime logger that can be used to log information with an +/// associated severity level and source code location (file path, line number, function name). +/// +/// A Logger can be obtained from within custom operators by calling Ort::KernelInfo::GetLogger(). +/// Instances of Ort::Logger are the size of two pointers and can be passed by value. +/// +/// Use the ORT_CXX_LOG macros to ensure the source code location is set properly from the callsite +/// and to take advantage of a cached logging severity level that can bypass calls to the underlying C API. +/// +struct Logger { + /** + * Creates an empty Ort::Logger. Must be initialized from a valid Ort::Logger before use. + */ + Logger() = default; + + /** + * Creates an empty Ort::Logger. Must be initialized from a valid Ort::Logger before use. + */ + explicit Logger(std::nullptr_t) {} + + /** + * Creates a logger from an ::OrtLogger instance. Caches the logger's current severity level by calling + * OrtApi::Logger_GetLoggingSeverityLevel. Throws an exception if OrtApi::Logger_GetLoggingSeverityLevel fails. + * + * \param logger The ::OrtLogger to wrap. + */ + explicit Logger(const OrtLogger* logger); + + ~Logger() = default; + + Logger(const Logger&) = default; + Logger& operator=(const Logger&) = default; + + Logger(Logger&& v) noexcept = default; + Logger& operator=(Logger&& v) noexcept = default; + + /** + * Returns the logger's current severity level from the cached member. + * + * \return The current ::OrtLoggingLevel. + */ + OrtLoggingLevel GetLoggingSeverityLevel() const noexcept; + + /** + * Logs the provided message via OrtApi::Logger_LogMessage. Use the ORT_CXX_LOG or ORT_CXX_LOG_NOEXCEPT + * macros to properly set the source code location and to use the cached severity level to potentially bypass + * calls to the underlying C API. + * + * \param log_severity_level The message's logging severity level. + * \param file_path The filepath of the file in which the message is logged. Usually the value of ORT_FILE. + * \param line_number The file line number in which the message is logged. Usually the value of __LINE__. + * \param func_name The name of the function in which the message is logged. Usually the value of __FUNCTION__. + * \param message The message to log. + * \return A Ort::Status value to indicate error or success. + */ + Status LogMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path, int line_number, + const char* func_name, const char* message) const noexcept; + + /** + * Logs a printf-like formatted message via OrtApi::Logger_LogMessage. Use the ORT_CXX_LOGF or ORT_CXX_LOGF_NOEXCEPT + * macros to properly set the source code location and to use the cached severity level to potentially bypass + * calls to the underlying C API. Returns an error status if a formatting error occurs. + * + * \param log_severity_level The message's logging severity level. + * \param file_path The filepath of the file in which the message is logged. Usually the value of ORT_FILE. + * \param line_number The file line number in which the message is logged. Usually the value of __LINE__. + * \param func_name The name of the function in which the message is logged. Usually the value of __FUNCTION__. + * \param format A null-terminated UTF-8 format string forwarded to a printf-like function. + * Refer to https://en.cppreference.com/w/cpp/io/c/fprintf for information on valid formats. + * \param args Zero or more variadic arguments referenced by the format string. + * \return A Ort::Status value to indicate error or success. + */ + template + Status LogFormattedMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path, int line_number, + const char* func_name, const char* format, Args&&... args) const noexcept; + + private: + const OrtLogger* logger_{}; + OrtLoggingLevel cached_severity_level_{}; +}; + +/// +/// This class wraps a raw pointer OrtKernelContext* that is being passed +/// to the custom kernel Compute() method. Use it to safely access context +/// attributes, input and output parameters with exception safety guarantees. +/// See usage example in onnxruntime/test/testdata/custom_op_library/custom_op_library.cc +/// +struct KernelContext { + explicit KernelContext(OrtKernelContext* context); + size_t GetInputCount() const; + size_t GetOutputCount() const; + // If input is optional and is not present, the method returns an empty ConstValue + // which can be compared to nullptr. + ConstValue GetInput(size_t index) const; + // If output is optional and is not present, the method returns an empty UnownedValue + // which can be compared to nullptr. + UnownedValue GetOutput(size_t index, const int64_t* dim_values, size_t dim_count) const; + UnownedValue GetOutput(size_t index, const std::vector& dims) const; + void* GetGPUComputeStream() const; + Logger GetLogger() const; + OrtAllocator* GetAllocator(const OrtMemoryInfo& memory_info) const; + OrtKernelContext* GetOrtKernelContext() const { return ctx_; } + void ParallelFor(void (*fn)(void*, size_t), size_t total, size_t num_batch, void* usr_data) const; + + private: + OrtKernelContext* ctx_; +}; + +struct KernelInfo; + +namespace detail { +namespace attr_utils { +void GetAttr(const OrtKernelInfo* p, const char* name, float&); +void GetAttr(const OrtKernelInfo* p, const char* name, int64_t&); +void GetAttr(const OrtKernelInfo* p, const char* name, std::string&); +void GetAttrs(const OrtKernelInfo* p, const char* name, std::vector&); +void GetAttrs(const OrtKernelInfo* p, const char* name, std::vector&); +} // namespace attr_utils + +template +struct KernelInfoImpl : Base { + using B = Base; + using B::B; + + KernelInfo Copy() const; + + template // R is only implemented for float, int64_t, and string + R GetAttribute(const char* name) const { + R val; + attr_utils::GetAttr(this->p_, name, val); + return val; + } + + template // R is only implemented for std::vector, std::vector + std::vector GetAttributes(const char* name) const { + std::vector result; + attr_utils::GetAttrs(this->p_, name, result); + return result; + } + + Value GetTensorAttribute(const char* name, OrtAllocator* allocator) const; + + size_t GetInputCount() const; + size_t GetOutputCount() const; + + std::string GetInputName(size_t index) const; + std::string GetOutputName(size_t index) const; + + TypeInfo GetInputTypeInfo(size_t index) const; + TypeInfo GetOutputTypeInfo(size_t index) const; + + ConstValue GetTensorConstantInput(size_t index, int* is_constant) const; + + std::string GetNodeName() const; + Logger GetLogger() const; +}; + +} // namespace detail + +using ConstKernelInfo = detail::KernelInfoImpl>; + +/// +/// This struct owns the OrtKernInfo* pointer when a copy is made. +/// For convenient wrapping of OrtKernelInfo* passed to kernel constructor +/// and query attributes, warp the pointer with Ort::Unowned instance +/// so it does not destroy the pointer the kernel does not own. +/// +struct KernelInfo : detail::KernelInfoImpl { + using Base = detail::KernelInfoImpl; + using Base::Base; + explicit KernelInfo(std::nullptr_t) {} ///< Create an empty instance to initialize later + explicit KernelInfo(OrtKernelInfo* info); ///< Take ownership of the instance + ConstKernelInfo GetConst() const { return ConstKernelInfo{this->p_}; } +}; + +/// +/// Create and own custom defined operation. +/// +struct Op : detail::Base { + using Base = detail::Base; + using Base::Base; + + explicit Op(std::nullptr_t) {} ///< Create an empty Operator object, must be assigned a valid one to be used + + explicit Op(OrtOp*); ///< Take ownership of the OrtOp + + static Op Create(const OrtKernelInfo* info, const char* op_name, const char* domain, + int version, const char** type_constraint_names, + const ONNXTensorElementDataType* type_constraint_values, + size_t type_constraint_count, + const OpAttr* attr_values, + size_t attr_count, + size_t input_count, size_t output_count); + + void Invoke(const OrtKernelContext* context, + const Value* input_values, + size_t input_count, + Value* output_values, + size_t output_count); + + // For easier refactoring + void Invoke(const OrtKernelContext* context, + const OrtValue* const* input_values, + size_t input_count, + OrtValue* const* output_values, + size_t output_count); +}; + +/// +/// Provide access to per-node attributes and input shapes, so one could compute and set output shapes. +/// +struct ShapeInferContext { + struct SymbolicInteger { + SymbolicInteger(int64_t i) : i_(i), is_int_(true) {}; + SymbolicInteger(const char* s) : s_(s), is_int_(false) {}; + SymbolicInteger(const SymbolicInteger&) = default; + SymbolicInteger(SymbolicInteger&&) = default; + + SymbolicInteger& operator=(const SymbolicInteger&) = default; + SymbolicInteger& operator=(SymbolicInteger&&) = default; + + bool operator==(const SymbolicInteger& dim) const { + if (is_int_ == dim.is_int_) { + if (is_int_) { + return i_ == dim.i_; + } else { + return std::string{s_} == std::string{dim.s_}; + } + } + return false; + } + + bool IsInt() const { return is_int_; } + int64_t AsInt() const { return i_; } + const char* AsSym() const { return s_; } + + static constexpr int INVALID_INT_DIM = -2; + + private: + union { + int64_t i_; + const char* s_; + }; + bool is_int_; + }; + + using Shape = std::vector; + + ShapeInferContext(const OrtApi* ort_api, OrtShapeInferContext* ctx); + + const Shape& GetInputShape(size_t indice) const { return input_shapes_.at(indice); } + + size_t GetInputCount() const { return input_shapes_.size(); } + + Status SetOutputShape(size_t indice, const Shape& shape, ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT); + + int64_t GetAttrInt(const char* attr_name); + + using Ints = std::vector; + Ints GetAttrInts(const char* attr_name); + + float GetAttrFloat(const char* attr_name); + + using Floats = std::vector; + Floats GetAttrFloats(const char* attr_name); + + std::string GetAttrString(const char* attr_name); + + using Strings = std::vector; + Strings GetAttrStrings(const char* attr_name); + + private: + const OrtOpAttr* GetAttrHdl(const char* attr_name) const; + const OrtApi* ort_api_; + OrtShapeInferContext* ctx_; + std::vector input_shapes_; +}; + +using ShapeInferFn = Ort::Status (*)(Ort::ShapeInferContext&); + +#define MAX_CUSTOM_OP_END_VER (1UL << 31) - 1 + +template +struct CustomOpBase : OrtCustomOp { + CustomOpBase() { + OrtCustomOp::version = ORT_API_VERSION; + OrtCustomOp::GetName = [](const OrtCustomOp* this_) { return static_cast(this_)->GetName(); }; + + OrtCustomOp::GetExecutionProviderType = [](const OrtCustomOp* this_) { return static_cast(this_)->GetExecutionProviderType(); }; + + OrtCustomOp::GetInputTypeCount = [](const OrtCustomOp* this_) { return static_cast(this_)->GetInputTypeCount(); }; + OrtCustomOp::GetInputType = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetInputType(index); }; + OrtCustomOp::GetInputMemoryType = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetInputMemoryType(index); }; + + OrtCustomOp::GetOutputTypeCount = [](const OrtCustomOp* this_) { return static_cast(this_)->GetOutputTypeCount(); }; + OrtCustomOp::GetOutputType = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetOutputType(index); }; + +#if defined(_MSC_VER) && !defined(__clang__) +#pragma warning(push) +#pragma warning(disable : 26409) +#endif + OrtCustomOp::KernelDestroy = [](void* op_kernel) { delete static_cast(op_kernel); }; +#if defined(_MSC_VER) && !defined(__clang__) +#pragma warning(pop) +#endif + OrtCustomOp::GetInputCharacteristic = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetInputCharacteristic(index); }; + OrtCustomOp::GetOutputCharacteristic = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetOutputCharacteristic(index); }; + + OrtCustomOp::GetVariadicInputMinArity = [](const OrtCustomOp* this_) { return static_cast(this_)->GetVariadicInputMinArity(); }; + OrtCustomOp::GetVariadicInputHomogeneity = [](const OrtCustomOp* this_) { return static_cast(static_cast(this_)->GetVariadicInputHomogeneity()); }; + OrtCustomOp::GetVariadicOutputMinArity = [](const OrtCustomOp* this_) { return static_cast(this_)->GetVariadicOutputMinArity(); }; + OrtCustomOp::GetVariadicOutputHomogeneity = [](const OrtCustomOp* this_) { return static_cast(static_cast(this_)->GetVariadicOutputHomogeneity()); }; +#ifdef __cpp_if_constexpr + if constexpr (WithStatus) { +#else + if (WithStatus) { +#endif + OrtCustomOp::CreateKernelV2 = [](const OrtCustomOp* this_, const OrtApi* api, const OrtKernelInfo* info, void** op_kernel) -> OrtStatusPtr { + return static_cast(this_)->CreateKernelV2(*api, info, op_kernel); + }; + OrtCustomOp::KernelComputeV2 = [](void* op_kernel, OrtKernelContext* context) -> OrtStatusPtr { + return static_cast(op_kernel)->ComputeV2(context); + }; + } else { + OrtCustomOp::CreateKernelV2 = nullptr; + OrtCustomOp::KernelComputeV2 = nullptr; + + OrtCustomOp::CreateKernel = [](const OrtCustomOp* this_, const OrtApi* api, const OrtKernelInfo* info) { return static_cast(this_)->CreateKernel(*api, info); }; + OrtCustomOp::KernelCompute = [](void* op_kernel, OrtKernelContext* context) { + static_cast(op_kernel)->Compute(context); + }; + } + + SetShapeInferFn(0); + + OrtCustomOp::GetStartVersion = [](const OrtCustomOp* this_) { + return static_cast(this_)->start_ver_; + }; + + OrtCustomOp::GetEndVersion = [](const OrtCustomOp* this_) { + return static_cast(this_)->end_ver_; + }; + + OrtCustomOp::GetMayInplace = nullptr; + OrtCustomOp::ReleaseMayInplace = nullptr; + OrtCustomOp::GetAliasMap = nullptr; + OrtCustomOp::ReleaseAliasMap = nullptr; + } + + // Default implementation of GetExecutionProviderType that returns nullptr to default to the CPU provider + const char* GetExecutionProviderType() const { return nullptr; } + + // Default implementations of GetInputCharacteristic() and GetOutputCharacteristic() below + // (inputs and outputs are required by default) + OrtCustomOpInputOutputCharacteristic GetInputCharacteristic(size_t /*index*/) const { + return OrtCustomOpInputOutputCharacteristic::INPUT_OUTPUT_REQUIRED; + } + + OrtCustomOpInputOutputCharacteristic GetOutputCharacteristic(size_t /*index*/) const { + return OrtCustomOpInputOutputCharacteristic::INPUT_OUTPUT_REQUIRED; + } + + // Default implemention of GetInputMemoryType() that returns OrtMemTypeDefault + OrtMemType GetInputMemoryType(size_t /*index*/) const { + return OrtMemTypeDefault; + } + + // Default implementation of GetVariadicInputMinArity() returns 1 to specify that a variadic input + // should expect at least 1 argument. + int GetVariadicInputMinArity() const { + return 1; + } + + // Default implementation of GetVariadicInputHomegeneity() returns true to specify that all arguments + // to a variadic input should be of the same type. + bool GetVariadicInputHomogeneity() const { + return true; + } + + // Default implementation of GetVariadicOutputMinArity() returns 1 to specify that a variadic output + // should produce at least 1 output value. + int GetVariadicOutputMinArity() const { + return 1; + } + + // Default implementation of GetVariadicOutputHomegeneity() returns true to specify that all output values + // produced by a variadic output should be of the same type. + bool GetVariadicOutputHomogeneity() const { + return true; + } + + // Declare list of session config entries used by this Custom Op. + // Implement this function in order to get configs from CustomOpBase::GetSessionConfigs(). + // This default implementation returns an empty vector of config entries. + std::vector GetSessionConfigKeys() const { + return std::vector{}; + } + + // Ort::CustomOpBase derived class should provide the following static method with the type/shape inferencing + // implementation if needed: + // static OrtStatusPtr InferOutputShape(Ort::ShapeInferContext& context) + template + decltype(&C::InferOutputShape) SetShapeInferFn(decltype(&C::InferOutputShape)) { + OrtCustomOp::InferOutputShapeFn = [](const OrtCustomOp*, OrtShapeInferContext* ort_ctx) -> OrtStatusPtr { + ShapeInferContext ctx(&GetApi(), ort_ctx); + return C::InferOutputShape(ctx); + }; + return {}; + } + + template + void SetShapeInferFn(...) { + OrtCustomOp::InferOutputShapeFn = {}; + } + + protected: + // Helper function that returns a map of session config entries specified by CustomOpBase::GetSessionConfigKeys. + void GetSessionConfigs(std::unordered_map& out, ConstSessionOptions options) const; + + int start_ver_ = 1; + int end_ver_ = MAX_CUSTOM_OP_END_VER; +}; + +namespace detail { +template +struct ValueInfoImpl : Ort::detail::Base { + using B = Ort::detail::Base; + using B::B; + + std::string Name() const; + ConstTypeInfo TypeInfo() const; +}; +} // namespace detail + +// Const object holder that does not own the underlying object +using ConstValueInfo = detail::ValueInfoImpl>; + +/** \brief Wrapper around ::OrtValueInfo + * + */ +struct ValueInfo : detail::ValueInfoImpl { + explicit ValueInfo(std::nullptr_t) {} ///< No instance is created + /// Take ownership of a pointer created by C API + explicit ValueInfo(OrtValueInfo* p) : ValueInfoImpl{p} {} + + // Create ValueInfo for a tensor + explicit ValueInfo(const std::string& name, const ConstTypeInfo& type_info); + + ConstValueInfo GetConst() const { return ConstValueInfo{this->p_}; } +}; + +namespace detail { +template +struct NodeImpl : Ort::detail::Base { + using B = Ort::detail::Base; + using B::B; +}; +} // namespace detail + +/** \brief Wrapper around ::OrtNode + * + */ +struct Node : detail::NodeImpl { + explicit Node(std::nullptr_t) {} ///< No instance is created + explicit Node(OrtNode* p) : NodeImpl{p} {} ///< Take ownership of a pointer created by C API + +#if !defined(ORT_MINIMAL_BUILD) + Node(const std::string& operator_name, const std::string& operator_domain, + const std::string& node_name, + const std::vector& input_names, + const std::vector& output_names); + + /// + /// Wraps CreateNode. Node takes ownership of attributes on success and updates the OpAttr in `attributes` to do so. + /// + Node(const std::string& operator_name, const std::string& operator_domain, + const std::string& node_name, + const std::vector& input_names, + const std::vector& output_names, + std::vector& attributes); + + private: + static void Init(const std::string& operator_name, const std::string& operator_domain, + const std::string& node_name, + const std::vector& input_names, + const std::vector& output_names, + std::vector& attributes, + OrtNode*& node); +#endif // !defined(ORT_MINIMAL_BUILD) +}; + +namespace detail { +template +struct GraphImpl : Ort::detail::Base { + using B = Ort::detail::Base; + using B::B; + +#if !defined(ORT_MINIMAL_BUILD) + void SetInputs(std::vector& inputs); + void SetOutputs(std::vector& outputs); + void AddInitializer(const std::string& name, Value& initializer, bool data_is_external); // Graph takes ownership of Value + void AddNode(Node& node); // Graph takes ownership of Node +#endif // !defined(ORT_MINIMAL_BUILD) +}; +} // namespace detail + +/** \brief Wrapper around ::OrtGraph + * + */ +struct Graph : detail::GraphImpl { + explicit Graph(std::nullptr_t) {} ///< No instance is created + explicit Graph(OrtGraph* p) : GraphImpl{p} {} ///< Take ownership of a pointer created by C API +#if !defined(ORT_MINIMAL_BUILD) + Graph(); +#endif +}; + +namespace detail { +template +struct ModelImpl : Ort::detail::Base { + using B = Ort::detail::Base; + using B::B; + +#if !defined(ORT_MINIMAL_BUILD) + void AddGraph(Graph& graph); +#endif +}; +} // namespace detail + +// Const object holder that does not own the underlying object +using ConstModel = detail::ModelImpl>; + +/** \brief Wrapper around ::OrtModel + * + */ +struct Model : detail::ModelImpl { + using DomainOpsetPair = std::pair; + + explicit Model(std::nullptr_t) {} ///< No instance is created + explicit Model(OrtModel* p) : ModelImpl{p} {} ///< Take ownership of a pointer created by C API + +#if !defined(ORT_MINIMAL_BUILD) + explicit Model(const std::vector& opsets); +#endif + + ConstModel GetConst() const { return ConstModel{this->p_}; } +}; +} // namespace Ort +#include "onnxruntime_cxx_inline.h" diff --git a/3rdParty/ONNX/onnxruntime_cxx_inline.h b/3rdParty/ONNX/onnxruntime_cxx_inline.h index 94ad2118fa..64cd09f93d 100644 --- a/3rdParty/ONNX/onnxruntime_cxx_inline.h +++ b/3rdParty/ONNX/onnxruntime_cxx_inline.h @@ -1,2778 +1,2778 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// Do not include this file directly. Please include "onnxruntime_cxx_api.h" instead. -// If interested in trying out features of the new experimental C++ API, include "experimental_onnxruntime_cxx_api.h" instead. -// -// These are the inline implementations of the C++ header APIs. They're in this separate file as to not clutter -// the main C++ file with implementation details. - -#include -#include -#include -#include -#include -#include - -// Convert OrtStatus to Ort::Status and return -// instead of throwing -#define ORT_CXX_RETURN_ON_API_FAIL(expression) \ - { \ - auto ort_status = (expression); \ - if (ort_status) { \ - return Ort::Status(ort_status); \ - } \ - } - -#ifdef __cpp_if_constexpr -#define ORT_CXX_IF_CONSTEXPR if constexpr -#else -#define ORT_CXX_IF_CONSTEXPR if -#endif - -namespace Ort { - -namespace detail { -inline void ThrowStatus(const Status& st) { - std::string error_message = st.GetErrorMessage(); - OrtErrorCode error_code = st.GetErrorCode(); - ORT_CXX_API_THROW(std::move(error_message), error_code); -} -} // namespace detail - -inline void ThrowOnError(OrtStatus* ort_status) { - if (ort_status) { - Ort::Status st(ort_status); - detail::ThrowStatus(st); - } -} - -inline void ThrowOnError(const Status& st) { - if (st) { - detail::ThrowStatus(st); - } -} - -inline Status::Status(OrtStatus* status) noexcept : detail::Base{status} { -} - -inline Status::Status(const std::exception& e) noexcept { - p_ = GetApi().CreateStatus(ORT_FAIL, e.what()); -} - -inline Status::Status(const Exception& e) noexcept { - p_ = GetApi().CreateStatus(e.GetOrtErrorCode(), e.what()); -} - -inline Status::Status(const char* message, OrtErrorCode code) noexcept { - p_ = GetApi().CreateStatus(code, message); -} - -inline std::string Status::GetErrorMessage() const { - std::string message(GetApi().GetErrorMessage(p_)); - return message; -} - -inline OrtErrorCode Status::GetErrorCode() const { - return GetApi().GetErrorCode(p_); -} - -inline bool Status::IsOK() const noexcept { - return (p_ == nullptr); -} - -// This template converts a C++ type into it's ONNXTensorElementDataType -template -struct TypeToTensorType; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_BFLOAT16; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL; -}; - -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FN; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FNUZ; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2FNUZ; -}; - -inline bool BFloat16_t::operator==(const BFloat16_t& rhs) const noexcept { - if (IsNaN() || rhs.IsNaN()) { - // IEEE defines that NaN is not equal to anything, including itself. - return false; - } - return val == rhs.val; -} - -inline bool BFloat16_t::operator<(const BFloat16_t& rhs) const noexcept { - if (IsNaN() || rhs.IsNaN()) { - // IEEE defines that NaN is unordered with respect to everything, including itself. - return false; - } - - const bool left_is_negative = IsNegative(); - if (left_is_negative != rhs.IsNegative()) { - // When the signs of left and right differ, we know that left is less than right if it is - // the negative value. The exception to this is if both values are zero, in which case IEEE - // says they should be equal, even if the signs differ. - return left_is_negative && !AreZero(*this, rhs); - } - return (val != rhs.val) && ((val < rhs.val) ^ left_is_negative); -} - -inline MemoryAllocation::MemoryAllocation(OrtAllocator* allocator, void* p, size_t size) - : allocator_(allocator), p_(p), size_(size) { -} - -inline MemoryAllocation::~MemoryAllocation() { - if (p_ != nullptr) { - // We do not throw out of destructor - auto ret = GetApi().AllocatorFree(allocator_, p_); - static_cast(ret); - } -} - -inline MemoryAllocation::MemoryAllocation(MemoryAllocation&& o) noexcept : allocator_(nullptr), p_(nullptr), size_(0) { - *this = std::move(o); -} - -inline MemoryAllocation& MemoryAllocation::operator=(MemoryAllocation&& o) noexcept { - OrtAllocator* alloc = nullptr; - void* p = nullptr; - size_t sz = 0; - - // Swap out this - std::swap(alloc, allocator_); - std::swap(p, p_); - std::swap(sz, size_); - - // Swap with incoming - std::swap(allocator_, o.allocator_); - std::swap(p_, o.p_); - std::swap(size_, o.size_); - - // Destroy this instance if needed - MemoryAllocation this_alloc(alloc, p, sz); - return *this; -} - -namespace detail { - -template -inline void* AllocatorImpl::Alloc(size_t size) { - void* out; - ThrowOnError(GetApi().AllocatorAlloc(this->p_, size, &out)); - return out; -} - -template -inline MemoryAllocation AllocatorImpl::GetAllocation(size_t size) { - void* out; - ThrowOnError(GetApi().AllocatorAlloc(this->p_, size, &out)); - MemoryAllocation result(this->p_, out, size); - return result; -} - -template -inline void AllocatorImpl::Free(void* p) { - ThrowOnError(GetApi().AllocatorFree(this->p_, p)); -} - -template -inline ConstMemoryInfo AllocatorImpl::GetInfo() const { - const OrtMemoryInfo* out; - ThrowOnError(GetApi().AllocatorGetInfo(this->p_, &out)); - return ConstMemoryInfo{out}; -} - -} // namespace detail - -inline AllocatorWithDefaultOptions::AllocatorWithDefaultOptions() { - ThrowOnError(GetApi().GetAllocatorWithDefaultOptions(&this->p_)); -} - -inline Allocator::Allocator(const Session& sess, const OrtMemoryInfo* mem_info) { - ThrowOnError(GetApi().CreateAllocator(sess, mem_info, &this->p_)); -} - -namespace detail { - -template -inline std::string MemoryInfoImpl::GetAllocatorName() const { - const char* name = nullptr; - ThrowOnError(GetApi().MemoryInfoGetName(this->p_, &name)); - return std::string(name); -} - -template -inline OrtAllocatorType MemoryInfoImpl::GetAllocatorType() const { - OrtAllocatorType type; - ThrowOnError(GetApi().MemoryInfoGetType(this->p_, &type)); - return type; -} - -template -inline int MemoryInfoImpl::GetDeviceId() const { - int id = 0; - ThrowOnError(GetApi().MemoryInfoGetId(this->p_, &id)); - return id; -} - -template -inline OrtMemoryInfoDeviceType MemoryInfoImpl::GetDeviceType() const { - OrtMemoryInfoDeviceType type; - GetApi().MemoryInfoGetDeviceType(this->p_, &type); - return type; -} - -template -inline OrtMemType MemoryInfoImpl::GetMemoryType() const { - OrtMemType type; - ThrowOnError(GetApi().MemoryInfoGetMemType(this->p_, &type)); - return type; -} - -template -template -inline bool MemoryInfoImpl::operator==(const MemoryInfoImpl& o) const { - int comp_result = 0; - ThrowOnError(Ort::GetApi().CompareMemoryInfo(this->p_, o, &comp_result)); - return comp_result == 0; -} - -} // namespace detail - -inline MemoryInfo MemoryInfo::CreateCpu(OrtAllocatorType type, OrtMemType mem_type) { - OrtMemoryInfo* p; - ThrowOnError(GetApi().CreateCpuMemoryInfo(type, mem_type, &p)); - return MemoryInfo(p); -} - -inline MemoryInfo::MemoryInfo(const char* name, OrtAllocatorType type, int id, OrtMemType mem_type) { - ThrowOnError(GetApi().CreateMemoryInfo(name, type, id, mem_type, &this->p_)); -} - -namespace detail { -template -inline std::vector ConstIoBindingImpl::GetOutputNames() const { - AllocatorWithDefaultOptions allocator; - return binding_utils::GetOutputNamesHelper(this->p_, allocator); -} - -template -inline std::vector ConstIoBindingImpl::GetOutputNames(OrtAllocator* allocator) const { - return binding_utils::GetOutputNamesHelper(this->p_, allocator); -} - -template -inline std::vector ConstIoBindingImpl::GetOutputValues() const { - AllocatorWithDefaultOptions allocator; - return binding_utils::GetOutputValuesHelper(this->p_, allocator); -} - -template -inline std::vector ConstIoBindingImpl::GetOutputValues(OrtAllocator* allocator) const { - return binding_utils::GetOutputValuesHelper(this->p_, allocator); -} - -template -inline void IoBindingImpl::BindInput(const char* name, const Value& value) { - ThrowOnError(GetApi().BindInput(this->p_, name, value)); -} - -template -inline void IoBindingImpl::BindOutput(const char* name, const Value& value) { - ThrowOnError(GetApi().BindOutput(this->p_, name, value)); -} - -template -inline void IoBindingImpl::BindOutput(const char* name, const OrtMemoryInfo* mem_info) { - ThrowOnError(GetApi().BindOutputToDevice(this->p_, name, mem_info)); -} - -template -inline void IoBindingImpl::ClearBoundInputs() { - GetApi().ClearBoundInputs(this->p_); -} - -template -inline void IoBindingImpl::ClearBoundOutputs() { - GetApi().ClearBoundOutputs(this->p_); -} - -template -inline void IoBindingImpl::SynchronizeInputs() { - ThrowOnError(GetApi().SynchronizeBoundInputs(this->p_)); -} - -template -inline void IoBindingImpl::SynchronizeOutputs() { - ThrowOnError(GetApi().SynchronizeBoundOutputs(this->p_)); -} - -namespace binding_utils { -inline std::vector GetOutputNamesHelper(const OrtIoBinding* binding, OrtAllocator* allocator) { - std::vector result; - auto free_fn = detail::AllocatedFree(allocator); - using Ptr = std::unique_ptr; - - char* buffer = nullptr; - size_t* lengths = nullptr; - size_t count = 0; - ThrowOnError(GetApi().GetBoundOutputNames(binding, allocator, &buffer, &lengths, &count)); - - if (count == 0) { - return result; - } - - Ptr buffer_g(buffer, free_fn); - Ptr lengths_g(lengths, free_fn); - - result.reserve(count); - for (size_t i = 0; i < count; ++i) { - auto sz = *lengths; - result.emplace_back(buffer, sz); - buffer += sz; - ++lengths; - } - return result; -} - -inline std::vector GetOutputValuesHelper(const OrtIoBinding* binding, OrtAllocator* allocator) { - std::vector result; - size_t owned = 0; - size_t output_count = 0; - // Lambda to release the buffer when no longer needed and - // make sure that we destroy all instances on exception - auto free_fn = [&owned, &output_count, allocator](OrtValue** buffer) { - if (buffer) { - while (owned < output_count) { - auto* p = buffer + owned++; - GetApi().ReleaseValue(*p); - } - allocator->Free(allocator, buffer); - } - }; - using Ptr = std::unique_ptr; - - OrtValue** output_buffer = nullptr; - ThrowOnError(GetApi().GetBoundOutputValues(binding, allocator, &output_buffer, &output_count)); - if (output_count == 0) { - return result; - } - - Ptr buffer_g(output_buffer, free_fn); - - result.reserve(output_count); - for (size_t i = 0; i < output_count; ++i) { - result.emplace_back(output_buffer[i]); - ++owned; - } - return result; -} - -} // namespace binding_utils -} // namespace detail - -inline IoBinding::IoBinding(Session& session) { - ThrowOnError(GetApi().CreateIoBinding(session, &this->p_)); -} - -inline ArenaCfg::ArenaCfg(size_t max_mem, int arena_extend_strategy, int initial_chunk_size_bytes, int max_dead_bytes_per_chunk) { - ThrowOnError(GetApi().CreateArenaCfg(max_mem, arena_extend_strategy, initial_chunk_size_bytes, max_dead_bytes_per_chunk, &p_)); -} - -inline ThreadingOptions::ThreadingOptions() { - ThrowOnError(GetApi().CreateThreadingOptions(&p_)); -} - -inline ThreadingOptions& ThreadingOptions::SetGlobalIntraOpNumThreads(int intra_op_num_threads) { - ThrowOnError(GetApi().SetGlobalIntraOpNumThreads(p_, intra_op_num_threads)); - return *this; -} - -inline ThreadingOptions& ThreadingOptions::SetGlobalInterOpNumThreads(int inter_op_num_threads) { - ThrowOnError(GetApi().SetGlobalInterOpNumThreads(p_, inter_op_num_threads)); - return *this; -} - -inline ThreadingOptions& ThreadingOptions::SetGlobalSpinControl(int allow_spinning) { - ThrowOnError(GetApi().SetGlobalSpinControl(p_, allow_spinning)); - return *this; -} - -inline ThreadingOptions& ThreadingOptions::SetGlobalDenormalAsZero() { - ThrowOnError(GetApi().SetGlobalDenormalAsZero(p_)); - return *this; -} - -inline ThreadingOptions& ThreadingOptions::SetGlobalCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn) { - ThrowOnError(GetApi().SetGlobalCustomCreateThreadFn(p_, ort_custom_create_thread_fn)); - return *this; -} - -inline ThreadingOptions& ThreadingOptions::SetGlobalCustomThreadCreationOptions(void* ort_custom_thread_creation_options) { - ThrowOnError(GetApi().SetGlobalCustomThreadCreationOptions(p_, ort_custom_thread_creation_options)); - return *this; -} - -inline ThreadingOptions& ThreadingOptions::SetGlobalCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn) { - ThrowOnError(GetApi().SetGlobalCustomJoinThreadFn(p_, ort_custom_join_thread_fn)); - return *this; -} - -namespace detail { -template -inline const char* KeyValuePairsImpl::GetValue(const char* key) const { - return GetApi().GetKeyValue(this->p_, key); -} - -template -inline std::unordered_map KeyValuePairsImpl::GetKeyValuePairs() const { - std::unordered_map out; - - size_t num_pairs = 0; - const char* const* keys = nullptr; - const char* const* values = nullptr; - GetApi().GetKeyValuePairs(this->p_, &keys, &values, &num_pairs); - if (num_pairs > 0) { - out.reserve(num_pairs); - for (size_t i = 0; i < num_pairs; ++i) { - out.emplace(keys[i], values[i]); - } - } - - return out; -} - -template -inline void KeyValuePairsImpl::GetKeyValuePairs(std::vector& keys, - std::vector& values) const { - keys.clear(); - values.clear(); - - size_t num_pairs = 0; - const char* const* keys_ptr = nullptr; - const char* const* values_ptr = nullptr; - GetApi().GetKeyValuePairs(this->p_, &keys_ptr, &values_ptr, &num_pairs); - if (num_pairs > 0) { - keys.resize(num_pairs); - values.resize(num_pairs); - std::copy(keys_ptr, keys_ptr + num_pairs, keys.begin()); - std::copy(values_ptr, values_ptr + num_pairs, values.begin()); - } -} -} // namespace detail - -inline KeyValuePairs::KeyValuePairs() { - GetApi().CreateKeyValuePairs(&p_); -} - -inline KeyValuePairs::KeyValuePairs(const std::unordered_map& kv_pairs) { - GetApi().CreateKeyValuePairs(&p_); - for (const auto& kv : kv_pairs) { - GetApi().AddKeyValuePair(this->p_, kv.first.c_str(), kv.second.c_str()); - } -} - -inline void KeyValuePairs::Add(const char* key, const char* value) { - GetApi().AddKeyValuePair(this->p_, key, value); -} - -inline void KeyValuePairs::Remove(const char* key) { - GetApi().RemoveKeyValuePair(this->p_, key); -} - -namespace detail { -template -inline OrtHardwareDeviceType HardwareDeviceImpl::Type() const { - return GetApi().HardwareDevice_Type(this->p_); -} - -template -inline uint32_t HardwareDeviceImpl::VendorId() const { - return GetApi().HardwareDevice_VendorId(this->p_); -} - -template -inline uint32_t HardwareDeviceImpl::DeviceId() const { - return GetApi().HardwareDevice_DeviceId(this->p_); -} - -template -inline const char* HardwareDeviceImpl::Vendor() const { - return GetApi().HardwareDevice_Vendor(this->p_); -} - -template -inline ConstKeyValuePairs HardwareDeviceImpl::Metadata() const { - return ConstKeyValuePairs{GetApi().HardwareDevice_Metadata(this->p_)}; -} - -template -inline const char* EpDeviceImpl::EpName() const { - return GetApi().EpDevice_EpName(this->p_); -} - -template -inline const char* EpDeviceImpl::EpVendor() const { - return GetApi().EpDevice_EpVendor(this->p_); -} - -template -inline ConstKeyValuePairs EpDeviceImpl::EpMetadata() const { - return ConstKeyValuePairs(GetApi().EpDevice_EpMetadata(this->p_)); -} - -template -inline ConstKeyValuePairs EpDeviceImpl::EpOptions() const { - return ConstKeyValuePairs(GetApi().EpDevice_EpOptions(this->p_)); -} - -template -inline ConstHardwareDevice EpDeviceImpl::Device() const { - return ConstHardwareDevice(GetApi().EpDevice_Device(this->p_)); -} -} // namespace detail - -inline EpDevice::EpDevice(OrtEpFactory& ep_factory, ConstHardwareDevice& hardware_device, - ConstKeyValuePairs ep_metadata, ConstKeyValuePairs ep_options) { - ThrowOnError(GetEpApi().CreateEpDevice(&ep_factory, hardware_device, ep_metadata, ep_options, &p_)); -} - -inline Env::Env(OrtLoggingLevel logging_level, _In_ const char* logid) { - ThrowOnError(GetApi().CreateEnv(logging_level, logid, &p_)); - if (strcmp(logid, "onnxruntime-node") == 0) { - ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS)); - } else { - ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS)); - } -} - -inline Env::Env(OrtLoggingLevel logging_level, const char* logid, OrtLoggingFunction logging_function, void* logger_param) { - ThrowOnError(GetApi().CreateEnvWithCustomLogger(logging_function, logger_param, logging_level, logid, &p_)); - if (strcmp(logid, "onnxruntime-node") == 0) { - ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS)); - } else { - ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS)); - } -} - -inline Env::Env(const OrtThreadingOptions* tp_options, OrtLoggingLevel logging_level, _In_ const char* logid) { - ThrowOnError(GetApi().CreateEnvWithGlobalThreadPools(logging_level, logid, tp_options, &p_)); - if (strcmp(logid, "onnxruntime-node") == 0) { - ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS)); - } else { - ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS)); - } -} - -inline Env::Env(const OrtThreadingOptions* tp_options, OrtLoggingFunction logging_function, void* logger_param, - OrtLoggingLevel logging_level, _In_ const char* logid) { - ThrowOnError(GetApi().CreateEnvWithCustomLoggerAndGlobalThreadPools(logging_function, logger_param, logging_level, logid, tp_options, &p_)); - if (strcmp(logid, "onnxruntime-node") == 0) { - ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS)); - } else { - ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS)); - } -} - -inline Env& Env::EnableTelemetryEvents() { - ThrowOnError(GetApi().EnableTelemetryEvents(p_)); - return *this; -} - -inline Env& Env::DisableTelemetryEvents() { - ThrowOnError(GetApi().DisableTelemetryEvents(p_)); - return *this; -} - -inline Env& Env::UpdateEnvWithCustomLogLevel(OrtLoggingLevel log_severity_level) { - ThrowOnError(GetApi().UpdateEnvWithCustomLogLevel(p_, log_severity_level)); - return *this; -} - -inline Env& Env::CreateAndRegisterAllocator(const OrtMemoryInfo* mem_info, const OrtArenaCfg* arena_cfg) { - ThrowOnError(GetApi().CreateAndRegisterAllocator(p_, mem_info, arena_cfg)); - return *this; -} - -inline Env& Env::CreateAndRegisterAllocatorV2(const std::string& provider_type, const OrtMemoryInfo* mem_info, const std::unordered_map& options, const OrtArenaCfg* arena_cfg) { - std::vector keys, values; - auto num_entries = options.size(); - if (num_entries > 0) { - keys.reserve(num_entries); - values.reserve(num_entries); - for (const auto& entry : options) { - keys.push_back(entry.first.c_str()); - values.push_back(entry.second.c_str()); - } - } - ThrowOnError(GetApi().CreateAndRegisterAllocatorV2(p_, provider_type.c_str(), mem_info, arena_cfg, keys.data(), values.data(), num_entries)); - return *this; -} - -inline Env& Env::RegisterExecutionProviderLibrary(const char* registration_name, - const std::basic_string& path) { - ThrowOnError(GetApi().RegisterExecutionProviderLibrary(p_, registration_name, path.c_str())); - return *this; -} - -inline Env& Env::UnregisterExecutionProviderLibrary(const char* registration_name) { - ThrowOnError(GetApi().UnregisterExecutionProviderLibrary(p_, registration_name)); - return *this; -} - -inline std::vector Env::GetEpDevices() const { - size_t num_devices = 0; - const OrtEpDevice* const* device_ptrs = nullptr; - ThrowOnError(GetApi().GetEpDevices(p_, &device_ptrs, &num_devices)); - - std::vector devices; - if (num_devices > 0) { - devices.reserve(num_devices); - for (size_t i = 0; i < num_devices; ++i) { - devices.emplace_back(device_ptrs[i]); - } - } - - return devices; -} - -inline CustomOpDomain::CustomOpDomain(const char* domain) { - ThrowOnError(GetApi().CreateCustomOpDomain(domain, &p_)); -} - -inline void CustomOpDomain::Add(const OrtCustomOp* op) { - ThrowOnError(GetApi().CustomOpDomain_Add(p_, op)); -} - -inline LoraAdapter LoraAdapter::CreateLoraAdapter(const std::basic_string& adapter_path, - OrtAllocator* allocator) { - OrtLoraAdapter* p; - ThrowOnError(GetApi().CreateLoraAdapter(adapter_path.c_str(), allocator, &p)); - return LoraAdapter{p}; -} - -inline LoraAdapter LoraAdapter::CreateLoraAdapterFromArray(const void* bytes, size_t num_bytes, - OrtAllocator* allocator) { - OrtLoraAdapter* p; - ThrowOnError(GetApi().CreateLoraAdapterFromArray(bytes, num_bytes, allocator, &p)); - return LoraAdapter{p}; -} - -inline RunOptions::RunOptions() { - ThrowOnError(GetApi().CreateRunOptions(&p_)); -} - -inline RunOptions& RunOptions::SetRunLogVerbosityLevel(int level) { - ThrowOnError(GetApi().RunOptionsSetRunLogVerbosityLevel(p_, level)); - return *this; -} - -inline RunOptions& RunOptions::SetRunLogSeverityLevel(int level) { - ThrowOnError(GetApi().RunOptionsSetRunLogSeverityLevel(p_, level)); - return *this; -} - -inline int RunOptions::GetRunLogVerbosityLevel() const { - int out; - ThrowOnError(GetApi().RunOptionsGetRunLogVerbosityLevel(p_, &out)); - return out; -} - -inline int RunOptions::GetRunLogSeverityLevel() const { - int out; - ThrowOnError(GetApi().RunOptionsGetRunLogSeverityLevel(p_, &out)); - return out; -} - -inline RunOptions& RunOptions::SetRunTag(const char* run_tag) { - ThrowOnError(GetApi().RunOptionsSetRunTag(p_, run_tag)); - return *this; -} - -inline const char* RunOptions::GetRunTag() const { - const char* out; - ThrowOnError(GetApi().RunOptionsGetRunTag(p_, &out)); - return out; -} - -inline RunOptions& RunOptions::AddConfigEntry(const char* config_key, const char* config_value) { - ThrowOnError(GetApi().AddRunConfigEntry(p_, config_key, config_value)); - return *this; -} - -inline RunOptions& RunOptions::SetTerminate() { - ThrowOnError(GetApi().RunOptionsSetTerminate(p_)); - return *this; -} - -inline RunOptions& RunOptions::UnsetTerminate() { - ThrowOnError(GetApi().RunOptionsUnsetTerminate(p_)); - return *this; -} - -inline RunOptions& RunOptions::AddActiveLoraAdapter(const LoraAdapter& adapter) { - ThrowOnError(GetApi().RunOptionsAddActiveLoraAdapter(p_, adapter)); - return *this; -} - -inline ModelCompilationOptions::ModelCompilationOptions(const Env& env, const SessionOptions& session_options) { - ThrowOnError(GetCompileApi().CreateModelCompilationOptionsFromSessionOptions(env, session_options, &this->p_)); -} - -inline ModelCompilationOptions::ModelCompilationOptions(const Env& env, ConstSessionOptions session_options) { - ThrowOnError(GetCompileApi().CreateModelCompilationOptionsFromSessionOptions(env, session_options, &this->p_)); -} - -inline Status CompileModel(const Env& env, const ModelCompilationOptions& model_compilation_options) { - return Ort::Status(GetCompileApi().CompileModel(env, model_compilation_options)); -} - -inline ModelCompilationOptions& ModelCompilationOptions::SetInputModelPath( - const ORTCHAR_T* input_model_path) { - Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetInputModelPath(this->p_, input_model_path)); - return *this; -} - -inline ModelCompilationOptions& ModelCompilationOptions::SetInputModelFromBuffer( - const void* input_model_data, size_t input_model_data_size) { - Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetInputModelFromBuffer(this->p_, input_model_data, - input_model_data_size)); - return *this; -} - -inline ModelCompilationOptions& ModelCompilationOptions::SetOutputModelPath( - const ORTCHAR_T* output_model_path) { - Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetOutputModelPath(this->p_, output_model_path)); - return *this; -} - -inline ModelCompilationOptions& ModelCompilationOptions::SetOutputModelExternalInitializersFile( - const ORTCHAR_T* file_path, size_t initializer_size_threshold) { - Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetOutputModelExternalInitializersFile( - this->p_, - file_path, - initializer_size_threshold)); - return *this; -} - -inline ModelCompilationOptions& ModelCompilationOptions::SetOutputModelBuffer( - OrtAllocator* allocator, void** output_model_buffer_ptr, size_t* output_model_buffer_size_ptr) { - Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetOutputModelBuffer(this->p_, allocator, - output_model_buffer_ptr, - output_model_buffer_size_ptr)); - return *this; -} - -inline ModelCompilationOptions& ModelCompilationOptions::SetEpContextEmbedMode( - bool embed_ep_context_in_model) { - Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetEpContextEmbedMode( - this->p_, - embed_ep_context_in_model)); - return *this; -} - -namespace detail { - -template -inline Ort::SessionOptions ConstSessionOptionsImpl::Clone() const { - OrtSessionOptions* out; - ThrowOnError(GetApi().CloneSessionOptions(this->p_, &out)); - return SessionOptions{out}; -} - -template -inline std::string ConstSessionOptionsImpl::GetConfigEntry(const char* config_key) const { - size_t size = 0; - // Feed nullptr for the data buffer to query the true size of the string value - Ort::ThrowOnError(GetApi().GetSessionConfigEntry(this->p_, config_key, nullptr, &size)); - - std::string out; - out.resize(size); - Ort::ThrowOnError(GetApi().GetSessionConfigEntry(this->p_, config_key, &out[0], &size)); - out.resize(size - 1); // remove the terminating character '\0' - - return out; -} - -template -inline bool ConstSessionOptionsImpl::HasConfigEntry(const char* config_key) const { - int out = 0; - Ort::ThrowOnError(GetApi().HasSessionConfigEntry(this->p_, config_key, &out)); - return static_cast(out); -} - -template -inline std::string ConstSessionOptionsImpl::GetConfigEntryOrDefault(const char* config_key, - const std::string& def) const { - if (!this->HasConfigEntry(config_key)) { - return def; - } - - return this->GetConfigEntry(config_key); -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetIntraOpNumThreads(int intra_op_num_threads) { - ThrowOnError(GetApi().SetIntraOpNumThreads(this->p_, intra_op_num_threads)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetInterOpNumThreads(int inter_op_num_threads) { - ThrowOnError(GetApi().SetInterOpNumThreads(this->p_, inter_op_num_threads)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetGraphOptimizationLevel(GraphOptimizationLevel graph_optimization_level) { - ThrowOnError(GetApi().SetSessionGraphOptimizationLevel(this->p_, graph_optimization_level)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetDeterministicCompute(bool value) { - ThrowOnError(GetApi().SetDeterministicCompute(this->p_, value)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetOptimizedModelFilePath(const ORTCHAR_T* optimized_model_filepath) { - ThrowOnError(GetApi().SetOptimizedModelFilePath(this->p_, optimized_model_filepath)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::EnableProfiling(const ORTCHAR_T* profile_file_prefix) { - ThrowOnError(GetApi().EnableProfiling(this->p_, profile_file_prefix)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::DisableProfiling() { - ThrowOnError(GetApi().DisableProfiling(this->p_)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::EnableOrtCustomOps() { - ThrowOnError(GetApi().EnableOrtCustomOps(this->p_)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::EnableMemPattern() { - ThrowOnError(GetApi().EnableMemPattern(this->p_)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::DisableMemPattern() { - ThrowOnError(GetApi().DisableMemPattern(this->p_)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::EnableCpuMemArena() { - ThrowOnError(GetApi().EnableCpuMemArena(this->p_)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::DisableCpuMemArena() { - ThrowOnError(GetApi().DisableCpuMemArena(this->p_)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetExecutionMode(ExecutionMode execution_mode) { - ThrowOnError(GetApi().SetSessionExecutionMode(this->p_, execution_mode)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetLoadCancellationFlag(bool value) { - ThrowOnError(GetApi().SessionOptionsSetLoadCancellationFlag(this->p_, value)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetLogId(const char* logid) { - ThrowOnError(GetApi().SetSessionLogId(this->p_, logid)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetLogSeverityLevel(int level) { - ThrowOnError(GetApi().SetSessionLogSeverityLevel(this->p_, level)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::Add(OrtCustomOpDomain* custom_op_domain) { - ThrowOnError(GetApi().AddCustomOpDomain(this->p_, custom_op_domain)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AddConfigEntry(const char* config_key, const char* config_value) { - ThrowOnError(GetApi().AddSessionConfigEntry(this->p_, config_key, config_value)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AddInitializer(const char* name, const OrtValue* ort_val) { - ThrowOnError(GetApi().AddInitializer(this->p_, name, ort_val)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::DisablePerSessionThreads() { - ThrowOnError(GetApi().DisablePerSessionThreads(this->p_)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AddExternalInitializers(const std::vector& names, - const std::vector& ort_values) { - const size_t inputs_num = names.size(); - if (inputs_num != ort_values.size()) { - ORT_CXX_API_THROW("Expecting names and ort_values to have the same length", ORT_INVALID_ARGUMENT); - } - std::vector names_ptr; - std::vector ort_values_ptrs; - names_ptr.reserve(inputs_num); - ort_values_ptrs.reserve(inputs_num); - for (size_t i = 0; i < inputs_num; ++i) { - names_ptr.push_back(names[i].c_str()); - ort_values_ptrs.push_back(ort_values[i]); - } - ThrowOnError(GetApi().AddExternalInitializers(this->p_, names_ptr.data(), ort_values_ptrs.data(), inputs_num)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AddExternalInitializersFromFilesInMemory(const std::vector>& file_names, - const std::vector& buffer_array, - const std::vector& file_lengths) { - const size_t inputs_num = file_names.size(); - if (inputs_num != buffer_array.size()) { - ORT_CXX_API_THROW("Expecting names and buffer_array to have the same length", ORT_INVALID_ARGUMENT); - } - if (inputs_num != file_lengths.size()) { - ORT_CXX_API_THROW("Expecting names and file_lengths to have the same length", ORT_INVALID_ARGUMENT); - } - std::vector names_ptr; - names_ptr.reserve(inputs_num); - for (size_t i = 0; i < inputs_num; ++i) { - names_ptr.push_back(file_names[i].c_str()); - } - ThrowOnError(GetApi().AddExternalInitializersFromFilesInMemory(this->p_, names_ptr.data(), buffer_array.data(), - file_lengths.data(), inputs_num)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_CUDA(const OrtCUDAProviderOptions& provider_options) { - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CUDA(this->p_, &provider_options)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_CUDA_V2(const OrtCUDAProviderOptionsV2& provider_options) { - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CUDA_V2(this->p_, &provider_options)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_ROCM(const OrtROCMProviderOptions& provider_options) { - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_ROCM(this->p_, &provider_options)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_TensorRT(const OrtTensorRTProviderOptions& provider_options) { - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_TensorRT(this->p_, &provider_options)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_TensorRT_V2(const OrtTensorRTProviderOptionsV2& provider_options) { - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_TensorRT_V2(this->p_, &provider_options)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_MIGraphX(const OrtMIGraphXProviderOptions& provider_options) { - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_MIGraphX(this->p_, &provider_options)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_CANN(const OrtCANNProviderOptions& provider_options) { - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CANN(this->p_, &provider_options)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_Dnnl(const OrtDnnlProviderOptions& provider_options) { - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_Dnnl(this->p_, &provider_options)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider( - const std::string& provider_name, - const std::unordered_map& provider_options) { - auto num_entries = provider_options.size(); - std::vector keys, values; - if (num_entries > 0) { - keys.reserve(num_entries); - values.reserve(num_entries); - - for (const auto& entry : provider_options) { - keys.push_back(entry.first.c_str()); - values.push_back(entry.second.c_str()); - } - } - - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider(this->p_, provider_name.c_str(), - keys.data(), values.data(), num_entries)); - - return *this; -} - -namespace { -template -void SessionOptionsAppendEP(detail::SessionOptionsImpl& session_options, - Env& env, const std::vector& ep_devices, - const std::vector& ep_options_keys, - const std::vector& ep_options_values) { - std::vector ep_devices_ptrs; - ep_devices_ptrs.reserve(ep_devices.size()); - for (const auto& ep_device : ep_devices) { - ep_devices_ptrs.push_back(ep_device); - } - - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_V2( - session_options, env, ep_devices_ptrs.data(), ep_devices_ptrs.size(), - ep_options_keys.data(), ep_options_values.data(), ep_options_keys.size())); -} -} // namespace - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_V2( - Env& env, const std::vector& ep_devices, const KeyValuePairs& ep_options) { - std::vector ep_options_keys, ep_options_values; - ep_options.GetKeyValuePairs(ep_options_keys, ep_options_values); - - SessionOptionsAppendEP(*this, env, ep_devices, ep_options_keys, ep_options_values); - - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_V2( - Env& env, const std::vector& ep_devices, - const std::unordered_map& ep_options) { - std::vector ep_options_keys, ep_options_values; - ep_options_keys.reserve(ep_options.size()); - ep_options_values.reserve(ep_options.size()); - - for (const auto& [key, value] : ep_options) { - ep_options_keys.push_back(key.c_str()); - ep_options_values.push_back(value.c_str()); - } - - SessionOptionsAppendEP(*this, env, ep_devices, ep_options_keys, ep_options_values); - - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetEpSelectionPolicy(OrtExecutionProviderDevicePolicy policy) { - ThrowOnError(GetApi().SessionOptionsSetEpSelectionPolicy(this->p_, policy)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetEpSelectionPolicy(EpSelectionDelegate delegate, void* state) { - ThrowOnError(GetApi().SessionOptionsSetEpSelectionPolicyDelegate(this->p_, delegate, state)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn) { - ThrowOnError(GetApi().SessionOptionsSetCustomCreateThreadFn(this->p_, ort_custom_create_thread_fn)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetCustomThreadCreationOptions(void* ort_custom_thread_creation_options) { - ThrowOnError(GetApi().SessionOptionsSetCustomThreadCreationOptions(this->p_, ort_custom_thread_creation_options)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn) { - ThrowOnError(GetApi().SessionOptionsSetCustomJoinThreadFn(this->p_, ort_custom_join_thread_fn)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_OpenVINO(const OrtOpenVINOProviderOptions& provider_options) { - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_OpenVINO(this->p_, &provider_options)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_OpenVINO_V2(const std::unordered_map& provider_options) { - auto num_entries = provider_options.size(); - std::vector keys, values; - if (num_entries > 0) { - keys.reserve(num_entries); - values.reserve(num_entries); - - for (const auto& entry : provider_options) { - keys.push_back(entry.first.c_str()); - values.push_back(entry.second.c_str()); - } - } - - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_OpenVINO_V2(this->p_, - keys.data(), values.data(), num_entries)); - - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_VitisAI(const std::unordered_map& provider_options) { - auto num_entries = provider_options.size(); - std::vector keys, values; - if (num_entries > 0) { - keys.reserve(num_entries); - values.reserve(num_entries); - - for (const auto& entry : provider_options) { - keys.push_back(entry.first.c_str()); - values.push_back(entry.second.c_str()); - } - } - - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_VitisAI(this->p_, keys.data(), values.data(), num_entries)); - - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::RegisterCustomOpsLibrary(const ORTCHAR_T* library_name, - const CustomOpConfigs& custom_op_configs) { - // Add custom op config entries before registering the custom op library. Otherwise, the config entries _may_ be ignored by - // the custom op library. - for (const auto& config_iter : custom_op_configs.GetFlattenedConfigs()) { - AddConfigEntry(config_iter.first.c_str(), config_iter.second.c_str()); - } - - ThrowOnError(GetApi().RegisterCustomOpsLibrary_V2(this->p_, library_name)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::RegisterCustomOpsUsingFunction(const char* registration_function_name) { - ThrowOnError(GetApi().RegisterCustomOpsUsingFunction(this->p_, registration_function_name)); - return *this; -} - -/// Session -template -inline size_t ConstSessionImpl::GetInputCount() const { - size_t out; - ThrowOnError(GetApi().SessionGetInputCount(this->p_, &out)); - return out; -} - -template -inline size_t ConstSessionImpl::GetOutputCount() const { - size_t out; - ThrowOnError(GetApi().SessionGetOutputCount(this->p_, &out)); - return out; -} - -template -inline size_t ConstSessionImpl::GetOverridableInitializerCount() const { - size_t out; - ThrowOnError(GetApi().SessionGetOverridableInitializerCount(this->p_, &out)); - return out; -} - -template -inline std::vector ConstSessionImpl::GetInputNames() const { - AllocatorWithDefaultOptions allocator; - - auto num_inputs = GetInputCount(); - std::vector input_names; - input_names.reserve(num_inputs); - - for (size_t i = 0; i < num_inputs; ++i) { - char* name = nullptr; - ThrowOnError(GetApi().SessionGetInputName(this->p_, i, allocator, &name)); - input_names.push_back(name); - allocator.Free(name); - } - - return input_names; -} - -template -inline std::vector ConstSessionImpl::GetOutputNames() const { - AllocatorWithDefaultOptions allocator; - - auto num_inputs = GetOutputCount(); - std::vector output_names; - output_names.reserve(num_inputs); - - for (size_t i = 0; i < num_inputs; ++i) { - char* name = nullptr; - ThrowOnError(GetApi().SessionGetOutputName(this->p_, i, allocator, &name)); - output_names.push_back(name); - allocator.Free(name); - } - - return output_names; -} - -template -inline std::vector ConstSessionImpl::GetOverridableInitializerNames() const { - AllocatorWithDefaultOptions allocator; - - auto num_initializers = GetOverridableInitializerCount(); - std::vector initializer_names; - initializer_names.reserve(num_initializers); - - for (size_t i = 0; i < num_initializers; ++i) { - char* name = nullptr; - ThrowOnError(GetApi().SessionGetOverridableInitializerName(this->p_, i, allocator, &name)); - initializer_names.push_back(name); - } - - return initializer_names; -} - -template -inline AllocatedStringPtr ConstSessionImpl::GetInputNameAllocated(size_t index, OrtAllocator* allocator) const { - char* out; - ThrowOnError(GetApi().SessionGetInputName(this->p_, index, allocator, &out)); - return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); -} - -template -inline AllocatedStringPtr ConstSessionImpl::GetOutputNameAllocated(size_t index, OrtAllocator* allocator) const { - char* out; - ThrowOnError(GetApi().SessionGetOutputName(this->p_, index, allocator, &out)); - return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); -} - -template -inline AllocatedStringPtr ConstSessionImpl::GetOverridableInitializerNameAllocated(size_t index, OrtAllocator* allocator) const { - char* out; - ThrowOnError(GetApi().SessionGetOverridableInitializerName(this->p_, index, allocator, &out)); - return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); -} - -template -inline uint64_t ConstSessionImpl::GetProfilingStartTimeNs() const { - uint64_t out; - ThrowOnError(GetApi().SessionGetProfilingStartTimeNs(this->p_, &out)); - return out; -} - -template -inline ModelMetadata ConstSessionImpl::GetModelMetadata() const { - OrtModelMetadata* out; - ThrowOnError(GetApi().SessionGetModelMetadata(this->p_, &out)); - return ModelMetadata{out}; -} - -template -inline TypeInfo ConstSessionImpl::GetInputTypeInfo(size_t index) const { - OrtTypeInfo* out; - ThrowOnError(GetApi().SessionGetInputTypeInfo(this->p_, index, &out)); - return TypeInfo{out}; -} - -template -inline TypeInfo ConstSessionImpl::GetOutputTypeInfo(size_t index) const { - OrtTypeInfo* out; - ThrowOnError(GetApi().SessionGetOutputTypeInfo(this->p_, index, &out)); - return TypeInfo{out}; -} - -template -inline TypeInfo ConstSessionImpl::GetOverridableInitializerTypeInfo(size_t index) const { - OrtTypeInfo* out; - ThrowOnError(GetApi().SessionGetOverridableInitializerTypeInfo(this->p_, index, &out)); - return TypeInfo{out}; -} - -#if !defined(ORT_MINIMAL_BUILD) -template -inline int ConstSessionImpl::GetOpset(const std::string& domain) const { - int opset; - ThrowOnError(GetModelEditorApi().SessionGetOpsetForDomain(this->p_, domain.c_str(), &opset)); - return opset; -} -#endif // !defined(ORT_MINIMAL_BUILD) - -template -std::vector ConstSessionImpl::GetInputs() const { - const std::vector input_names = GetInputNames(); - - std::vector inputs; - inputs.reserve(input_names.size()); - - for (size_t i = 0; i < input_names.size(); ++i) { - auto type_info = GetInputTypeInfo(i); - inputs.emplace_back(ValueInfo{input_names[i], type_info.GetConst()}); - } - - return inputs; -} - -template -std::vector ConstSessionImpl::GetOutputs() const { - const std::vector output_names = GetOutputNames(); - - std::vector outputs; - outputs.reserve(output_names.size()); - - for (size_t i = 0; i < output_names.size(); ++i) { - auto type_info = GetOutputTypeInfo(i); - outputs.emplace_back(ValueInfo{output_names[i], type_info.GetConst()}); - } - - return outputs; -} - -template -inline std::vector SessionImpl::Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, - const char* const* output_names, size_t output_count) { - std::vector output_values; - output_values.reserve(output_count); - for (size_t i = 0; i < output_count; i++) - output_values.emplace_back(nullptr); - Run(run_options, input_names, input_values, input_count, output_names, output_values.data(), output_count); - return output_values; -} - -template -inline void SessionImpl::Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, - const char* const* output_names, Value* output_values, size_t output_count) { - static_assert(sizeof(Value) == sizeof(OrtValue*), "Value is really just an array of OrtValue* in memory, so we can reinterpret_cast safely"); - auto ort_input_values = reinterpret_cast(input_values); - auto ort_output_values = reinterpret_cast(output_values); - ThrowOnError(GetApi().Run(this->p_, run_options, input_names, ort_input_values, input_count, output_names, output_count, ort_output_values)); -} - -template -inline void SessionImpl::Run(const RunOptions& run_options, const IoBinding& io_binding) { - ThrowOnError(GetApi().RunWithBinding(this->p_, run_options, io_binding)); -} - -template -inline void SessionImpl::RunAsync(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, - const char* const* output_names, Value* output_values, size_t output_count, RunAsyncCallbackFn callback, void* user_data) { - auto ort_input_values = reinterpret_cast(input_values); - auto ort_output_values = reinterpret_cast(output_values); - ThrowOnError(GetApi().RunAsync(this->p_, run_options, input_names, - ort_input_values, input_count, output_names, output_count, - ort_output_values, callback, user_data)); -} - -template -inline AllocatedStringPtr SessionImpl::EndProfilingAllocated(OrtAllocator* allocator) { - char* out = nullptr; - ThrowOnError(GetApi().SessionEndProfiling(this->p_, allocator, &out)); - return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); -} - -template -inline void SessionImpl::SetEpDynamicOptions(const char* const* keys, const char* const* values, size_t kv_len) { - ThrowOnError(GetApi().SetEpDynamicOptions(this->p_, keys, values, kv_len)); -} - -#if !defined(ORT_MINIMAL_BUILD) -template -inline void SessionImpl::FinalizeModelEditorSession(const Model& model, const SessionOptions& options, - OrtPrepackedWeightsContainer* prepacked_weights_container) { - ThrowOnError(GetModelEditorApi().ApplyModelToModelEditorSession(this->p_, model)); - ThrowOnError(GetModelEditorApi().FinalizeModelEditorSession(this->p_, options, prepacked_weights_container)); -} -#endif // #if !defined(ORT_MINIMAL_BUILD) - -} // namespace detail - -inline SessionOptions::SessionOptions() { - ThrowOnError(GetApi().CreateSessionOptions(&this->p_)); -} - -/// CustomOpConfigs -inline std::string detail::MakeCustomOpConfigEntryKey(const char* custom_op_name, const char* config) { - std::string config_key = "custom_op."; - - config_key += custom_op_name; - config_key += "."; - config_key += config; - - return config_key; -} - -inline CustomOpConfigs& CustomOpConfigs::AddConfig(const char* custom_op_name, const char* config_key, const char* config_value) { - const std::string full_flat_key = detail::MakeCustomOpConfigEntryKey(custom_op_name, config_key); - flat_configs_[full_flat_key] = config_value; - return *this; -} - -inline const std::unordered_map& CustomOpConfigs::GetFlattenedConfigs() const { - return flat_configs_; -} - -inline Session::Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options) { - ThrowOnError(GetApi().CreateSession(env, model_path, options, &this->p_)); -} - -inline Session::Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options, - OrtPrepackedWeightsContainer* prepacked_weights_container) { - ThrowOnError(GetApi().CreateSessionWithPrepackedWeightsContainer(env, model_path, options, prepacked_weights_container, &this->p_)); -} - -inline Session::Session(const Env& env, const void* model_data, size_t model_data_length, const SessionOptions& options) { - ThrowOnError(GetApi().CreateSessionFromArray(env, model_data, model_data_length, options, &this->p_)); -} - -inline Session::Session(const Env& env, const void* model_data, size_t model_data_length, - const SessionOptions& options, OrtPrepackedWeightsContainer* prepacked_weights_container) { - ThrowOnError(GetApi().CreateSessionFromArrayWithPrepackedWeightsContainer(env, model_data, model_data_length, options, - prepacked_weights_container, &this->p_)); -} - -#if !defined(ORT_MINIMAL_BUILD) -inline Session::Session(const Env& env, const Model& model, const SessionOptions& options) { - ThrowOnError(GetModelEditorApi().CreateSessionFromModel(env, model.GetConst(), options, &this->p_)); -} - -// static -inline Session Session::CreateModelEditorSession(const Env& env, const ORTCHAR_T* model_path, - const SessionOptions& options) { - OrtSession* session = nullptr; - ThrowOnError(GetModelEditorApi().CreateModelEditorSession(env, model_path, options, &session)); - return Session(session); -} - -// static -inline Session Session::CreateModelEditorSession(const Env& env, const void* model_data, size_t model_data_length, - const SessionOptions& options) { - OrtSession* session = nullptr; - ThrowOnError(GetModelEditorApi().CreateModelEditorSessionFromArray(env, model_data, model_data_length, options, - &session)); - return Session(session); -} - -void FinalizeModelEditorSession(const Model& model, const SessionOptions& options, - OrtPrepackedWeightsContainer* prepacked_weights_container); -#endif // #if !defined(ORT_MINIMAL_BUILD) - -inline AllocatedStringPtr ModelMetadata::GetProducerNameAllocated(OrtAllocator* allocator) const { - char* out; - ThrowOnError(GetApi().ModelMetadataGetProducerName(p_, allocator, &out)); - return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); -} - -inline AllocatedStringPtr ModelMetadata::GetGraphNameAllocated(OrtAllocator* allocator) const { - char* out; - ThrowOnError(GetApi().ModelMetadataGetGraphName(p_, allocator, &out)); - return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); -} - -inline AllocatedStringPtr ModelMetadata::GetDomainAllocated(OrtAllocator* allocator) const { - char* out; - ThrowOnError(GetApi().ModelMetadataGetDomain(p_, allocator, &out)); - return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); -} - -inline AllocatedStringPtr Ort::ModelMetadata::GetDescriptionAllocated(OrtAllocator* allocator) const { - char* out; - ThrowOnError(GetApi().ModelMetadataGetDescription(p_, allocator, &out)); - return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); -} - -inline AllocatedStringPtr ModelMetadata::GetGraphDescriptionAllocated(OrtAllocator* allocator) const { - char* out; - ThrowOnError(GetApi().ModelMetadataGetGraphDescription(p_, allocator, &out)); - return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); -} - -inline AllocatedStringPtr ModelMetadata::LookupCustomMetadataMapAllocated(const char* key, OrtAllocator* allocator) const { - char* out; - ThrowOnError(GetApi().ModelMetadataLookupCustomMetadataMap(p_, allocator, key, &out)); - return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); -} - -inline std::vector ModelMetadata::GetCustomMetadataMapKeysAllocated(OrtAllocator* allocator) const { - auto deletor = detail::AllocatedFree(allocator); - std::vector result; - - char** out = nullptr; - int64_t num_keys = 0; - ThrowOnError(GetApi().ModelMetadataGetCustomMetadataMapKeys(p_, allocator, &out, &num_keys)); - if (num_keys <= 0) { - return result; - } - - // array of pointers will be freed - std::unique_ptr array_guard(out, deletor); - // reserve may throw - auto strings_deletor = [&deletor, num_keys](char** out) { for(int64_t i = 0; i < num_keys; ++i) deletor(out[i]); }; - std::unique_ptr strings_guard(out, strings_deletor); - result.reserve(static_cast(num_keys)); - strings_guard.release(); - for (int64_t i = 0; i < num_keys; ++i) { - result.push_back(AllocatedStringPtr(out[i], deletor)); - } - - return result; -} - -inline int64_t ModelMetadata::GetVersion() const { - int64_t out; - ThrowOnError(GetApi().ModelMetadataGetVersion(p_, &out)); - return out; -} - -inline TensorTypeAndShapeInfo::TensorTypeAndShapeInfo(ONNXTensorElementDataType element_type, - const std::vector& dims, - const std::vector* symbolic_dims) { - ThrowOnError(GetApi().CreateTensorTypeAndShapeInfo(&p_)); - ThrowOnError(GetApi().SetTensorElementType(p_, element_type)); - ThrowOnError(GetApi().SetDimensions(p_, dims.data(), dims.size())); - - if (symbolic_dims) { - std::vector symbolic_dims_cstr; - symbolic_dims_cstr.reserve(symbolic_dims->size()); - std::transform(symbolic_dims->begin(), symbolic_dims->end(), std::back_inserter(symbolic_dims_cstr), - [](const std::string& s) { return s.c_str(); }); - ThrowOnError(GetApi().SetSymbolicDimensions(p_, symbolic_dims_cstr.data(), symbolic_dims_cstr.size())); - } -} - -#if !defined(ORT_MINIMAL_BUILD) -// static -inline TypeInfo TypeInfo::CreateTensorInfo(ConstTensorTypeAndShapeInfo tensor_type_and_shape_info) { - OrtTypeInfo* output = nullptr; - ThrowOnError(GetModelEditorApi().CreateTensorTypeInfo(tensor_type_and_shape_info, &output)); - return TypeInfo{output}; -} - -// static -inline TypeInfo TypeInfo::CreateSparseTensorInfo(ConstTensorTypeAndShapeInfo sparse_tensor_type_and_shape_info) { - OrtTypeInfo* output = nullptr; - ThrowOnError(GetModelEditorApi().CreateSparseTensorTypeInfo(sparse_tensor_type_and_shape_info, &output)); - return TypeInfo{output}; -} - -// static -inline TypeInfo TypeInfo::CreateSequenceTypeInfo(ConstTypeInfo sequence_type) { - OrtTypeInfo* output; - ThrowOnError(GetModelEditorApi().CreateSequenceTypeInfo(sequence_type, &output)); - return TypeInfo{output}; -} - -// static -inline TypeInfo TypeInfo::CreateMapTypeInfo(ONNXTensorElementDataType key_type, ConstTypeInfo value_type) { - OrtTypeInfo* output; - ThrowOnError(GetModelEditorApi().CreateMapTypeInfo(key_type, value_type, &output)); - return TypeInfo{output}; -} - -// static -inline TypeInfo TypeInfo::CreateOptionalTypeInfo(ConstTypeInfo contained_type) { - OrtTypeInfo* output; - ThrowOnError(GetModelEditorApi().CreateOptionalTypeInfo(contained_type, &output)); - return TypeInfo{output}; -} -#endif // #if !defined(ORT_MINIMAL_BUILD) - -namespace detail { - -template -inline ONNXTensorElementDataType TensorTypeAndShapeInfoImpl::GetElementType() const { - ONNXTensorElementDataType out; - ThrowOnError(GetApi().GetTensorElementType(this->p_, &out)); - return out; -} - -template -inline size_t TensorTypeAndShapeInfoImpl::GetElementCount() const { - size_t out; - ThrowOnError(GetApi().GetTensorShapeElementCount(this->p_, &out)); - return static_cast(out); -} - -template -inline size_t TensorTypeAndShapeInfoImpl::GetDimensionsCount() const { - size_t out; - ThrowOnError(GetApi().GetDimensionsCount(this->p_, &out)); - return out; -} - -template -inline void TensorTypeAndShapeInfoImpl::GetDimensions(int64_t* values, size_t values_count) const { - ThrowOnError(GetApi().GetDimensions(this->p_, values, values_count)); -} - -template -inline void TensorTypeAndShapeInfoImpl::GetSymbolicDimensions(const char** values, size_t values_count) const { - ThrowOnError(GetApi().GetSymbolicDimensions(this->p_, values, values_count)); -} - -template -inline std::vector TensorTypeAndShapeInfoImpl::GetSymbolicDimensions() const { - std::vector out(GetDimensionsCount(), nullptr); - ThrowOnError(GetApi().GetSymbolicDimensions(this->p_, out.data(), out.size())); - return out; -} - -template -inline std::vector TensorTypeAndShapeInfoImpl::GetShape() const { - std::vector out(GetDimensionsCount(), -1); - ThrowOnError(GetApi().GetDimensions(this->p_, out.data(), out.size())); - return out; -} - -template -inline ConstTensorTypeAndShapeInfo TypeInfoImpl::GetTensorTypeAndShapeInfo() const { - const OrtTensorTypeAndShapeInfo* out; - ThrowOnError(GetApi().CastTypeInfoToTensorInfo(this->p_, &out)); - return ConstTensorTypeAndShapeInfo{out}; -} - -template -inline ConstSequenceTypeInfo TypeInfoImpl::GetSequenceTypeInfo() const { - const OrtSequenceTypeInfo* out; - ThrowOnError(GetApi().CastTypeInfoToSequenceTypeInfo(this->p_, &out)); - return ConstSequenceTypeInfo{out}; -} - -template -inline ConstMapTypeInfo TypeInfoImpl::GetMapTypeInfo() const { - const OrtMapTypeInfo* out; - ThrowOnError(GetApi().CastTypeInfoToMapTypeInfo(this->p_, &out)); - return ConstMapTypeInfo{out}; -} - -template -inline ONNXType TypeInfoImpl::GetONNXType() const { - ONNXType out; - ThrowOnError(GetApi().GetOnnxTypeFromTypeInfo(this->p_, &out)); - return out; -} - -template -inline TypeInfo SequenceTypeInfoImpl::GetSequenceElementType() const { - OrtTypeInfo* output; - ThrowOnError(GetApi().GetSequenceElementType(this->p_, &output)); - return TypeInfo{output}; -} - -template -inline TypeInfo OptionalTypeInfoImpl::GetOptionalElementType() const { - OrtTypeInfo* info; - ThrowOnError(GetApi().GetOptionalContainedTypeInfo(this->p_, &info)); - return TypeInfo{info}; -} - -template -inline ONNXTensorElementDataType MapTypeInfoImpl::GetMapKeyType() const { - ONNXTensorElementDataType out; - ThrowOnError(GetApi().GetMapKeyType(this->p_, &out)); - return out; -} - -template -inline TypeInfo MapTypeInfoImpl::GetMapValueType() const { - OrtTypeInfo* output; - ThrowOnError(GetApi().GetMapValueType(this->p_, &output)); - return TypeInfo{output}; -} - -template -inline ConstOptionalTypeInfo TypeInfoImpl::GetOptionalTypeInfo() const { - const OrtOptionalTypeInfo* info; - ThrowOnError(GetApi().CastTypeInfoToOptionalTypeInfo(this->p_, &info)); - return ConstOptionalTypeInfo{info}; -} - -} // namespace detail - -namespace detail { - -template -template -inline void ConstValueImpl::GetOpaqueData(const char* domain, const char* type_name, R& out) const { - ThrowOnError(GetApi().GetOpaqueValue(domain, type_name, this->p_, &out, sizeof(R))); -} - -template -inline bool ConstValueImpl::IsTensor() const { - int out; - ThrowOnError(GetApi().IsTensor(this->p_, &out)); - return out != 0; -} - -template -inline bool ConstValueImpl::HasValue() const { - int out; - ThrowOnError(GetApi().HasValue(this->p_, &out)); - return out != 0; -} - -template -inline size_t ConstValueImpl::GetCount() const { - size_t out; - ThrowOnError(GetApi().GetValueCount(this->p_, &out)); - return out; -} - -template -inline Value ConstValueImpl::GetValue(int index, OrtAllocator* allocator) const { - OrtValue* out; - ThrowOnError(GetApi().GetValue(this->p_, index, allocator, &out)); - return Value{out}; -} - -template -inline size_t ConstValueImpl::GetStringTensorDataLength() const { - size_t out; - ThrowOnError(GetApi().GetStringTensorDataLength(this->p_, &out)); - return out; -} - -template -inline size_t ConstValueImpl::GetStringTensorElementLength(size_t element_index) const { - size_t out; - ThrowOnError(GetApi().GetStringTensorElementLength(this->p_, element_index, &out)); - return out; -} - -template -template -inline const R* ConstValueImpl::GetTensorData() const { - R* out; - ThrowOnError(GetApi().GetTensorMutableData(const_cast(this->p_), (void**)&out)); - return out; -} - -template -inline const void* ConstValueImpl::GetTensorRawData() const { - void* out; - ThrowOnError(GetApi().GetTensorMutableData(const_cast(this->p_), &out)); - return out; -} - -template -inline TypeInfo ConstValueImpl::GetTypeInfo() const { - OrtTypeInfo* output; - ThrowOnError(GetApi().GetTypeInfo(this->p_, &output)); - return TypeInfo{output}; -} - -template -inline TensorTypeAndShapeInfo ConstValueImpl::GetTensorTypeAndShapeInfo() const { - OrtTensorTypeAndShapeInfo* output; - ThrowOnError(GetApi().GetTensorTypeAndShape(this->p_, &output)); - return TensorTypeAndShapeInfo{output}; -} - -template -inline ConstMemoryInfo ConstValueImpl::GetTensorMemoryInfo() const { - const OrtMemoryInfo* mem_info; - ThrowOnError(GetApi().GetTensorMemoryInfo(this->p_, &mem_info)); - return ConstMemoryInfo(mem_info); -} - -template -inline void ConstValueImpl::GetStringTensorElement(size_t buffer_length, size_t element_index, void* buffer) const { - ThrowOnError(GetApi().GetStringTensorElement(this->p_, buffer_length, element_index, buffer)); -} - -template -inline std::string ConstValueImpl::GetStringTensorElement(size_t element_index) const { - size_t buffer_length; - ThrowOnError(GetApi().GetStringTensorElementLength(this->p_, element_index, &buffer_length)); - - std::string s; - s.resize(buffer_length); - ThrowOnError(GetApi().GetStringTensorElement(this->p_, buffer_length, element_index, &s[0])); - return s; -} - -template -inline void ConstValueImpl::GetStringTensorContent(void* buffer, size_t buffer_length, size_t* offsets, size_t offsets_count) const { - ThrowOnError(GetApi().GetStringTensorContent(this->p_, buffer, buffer_length, offsets, offsets_count)); -} - -#if !defined(DISABLE_SPARSE_TENSORS) -template -inline OrtSparseFormat ConstValueImpl::GetSparseFormat() const { - OrtSparseFormat format; - ThrowOnError(GetApi().GetSparseTensorFormat(this->p_, &format)); - return format; -} - -template -inline TensorTypeAndShapeInfo ConstValueImpl::GetSparseTensorValuesTypeAndShapeInfo() const { - OrtTensorTypeAndShapeInfo* output; - ThrowOnError(GetApi().GetSparseTensorValuesTypeAndShape(this->p_, &output)); - return TensorTypeAndShapeInfo{output}; -} - -template -inline TensorTypeAndShapeInfo ConstValueImpl::GetSparseTensorIndicesTypeShapeInfo(OrtSparseIndicesFormat indices_format) const { - OrtTensorTypeAndShapeInfo* output; - ThrowOnError(GetApi().GetSparseTensorIndicesTypeShape(this->p_, indices_format, &output)); - return TensorTypeAndShapeInfo{output}; -} - -template -template -inline const R* ConstValueImpl::GetSparseTensorIndicesData(OrtSparseIndicesFormat indices_format, size_t& num_indices) const { - const void* out; - ThrowOnError(GetApi().GetSparseTensorIndices(this->p_, indices_format, &num_indices, &out)); - return reinterpret_cast(out); -} - -template -inline bool ConstValueImpl::IsSparseTensor() const { - int out; - ThrowOnError(GetApi().IsSparseTensor(this->p_, &out)); - return out != 0; -} - -template -template -inline const R* ConstValueImpl::GetSparseTensorValues() const { - const void* out; - ThrowOnError(GetApi().GetSparseTensorValues(this->p_, &out)); - return reinterpret_cast(out); -} - -#endif - -template -void ValueImpl::FillStringTensor(const char* const* s, size_t s_len) { - ThrowOnError(GetApi().FillStringTensor(this->p_, s, s_len)); -} - -template -void ValueImpl::FillStringTensorElement(const char* s, size_t index) { - ThrowOnError(GetApi().FillStringTensorElement(this->p_, s, index)); -} - -template -inline char* ValueImpl::GetResizedStringTensorElementBuffer(size_t index, size_t buffer_length) { - char* result; - ThrowOnError(GetApi().GetResizedStringTensorElementBuffer(this->p_, index, buffer_length, &result)); - return result; -} - -template -void* ValueImpl::GetTensorMutableRawData() { - void* out; - ThrowOnError(GetApi().GetTensorMutableData(this->p_, &out)); - return out; -} - -template -template -R* ValueImpl::GetTensorMutableData() { - R* out; - ThrowOnError(GetApi().GetTensorMutableData(this->p_, (void**)&out)); - return out; -} - -template -template -R& ValueImpl::At(const std::vector& location) { - static_assert(!std::is_same::value, "this api does not support std::string"); - R* out; - ThrowOnError(GetApi().TensorAt(this->p_, location.data(), location.size(), (void**)&out)); - return *out; -} - -#if !defined(DISABLE_SPARSE_TENSORS) -template -void ValueImpl::UseCooIndices(int64_t* indices_data, size_t indices_num) { - ThrowOnError(GetApi().UseCooIndices(this->p_, indices_data, indices_num)); -} - -template -void ValueImpl::UseCsrIndices(int64_t* inner_data, size_t inner_num, int64_t* outer_data, size_t outer_num) { - ThrowOnError(GetApi().UseCsrIndices(this->p_, inner_data, inner_num, outer_data, outer_num)); -} - -template -void ValueImpl::UseBlockSparseIndices(const Shape& indices_shape, int32_t* indices_data) { - ThrowOnError(GetApi().UseBlockSparseIndices(this->p_, indices_shape.shape, indices_shape.shape_len, indices_data)); -} - -template -void ValueImpl::FillSparseTensorCoo(const OrtMemoryInfo* mem_info, const OrtSparseValuesParam& values_param, - const int64_t* indices_data, size_t indices_num) { - ThrowOnError(GetApi().FillSparseTensorCoo(this->p_, mem_info, values_param.values_shape, - values_param.values_shape_len, values_param.data.p_data, - indices_data, indices_num)); -} - -template -void ValueImpl::FillSparseTensorCsr(const OrtMemoryInfo* data_mem_info, - const OrtSparseValuesParam& values, - const int64_t* inner_indices_data, size_t inner_indices_num, - const int64_t* outer_indices_data, size_t outer_indices_num) { - ThrowOnError(GetApi().FillSparseTensorCsr(this->p_, data_mem_info, values.values_shape, values.values_shape_len, values.data.p_data, - inner_indices_data, inner_indices_num, - outer_indices_data, outer_indices_num)); -} - -template -void ValueImpl::FillSparseTensorBlockSparse(const OrtMemoryInfo* data_mem_info, - const OrtSparseValuesParam& values, - const Shape& indices_shape, - const int32_t* indices_data) { - ThrowOnError(GetApi().FillSparseTensorBlockSparse(this->p_, data_mem_info, values.values_shape, values.values_shape_len, values.data.p_data, - indices_shape.shape, indices_shape.shape_len, - indices_data)); -} - -#endif // !defined(DISABLE_SPARSE_TENSORS) - -} // namespace detail - -template -inline Value Value::CreateTensor(const OrtMemoryInfo* info, T* p_data, size_t p_data_element_count, - const int64_t* shape, size_t shape_len) { - return CreateTensor(info, p_data, p_data_element_count * sizeof(T), shape, shape_len, TypeToTensorType::type); -} - -inline Value Value::CreateTensor(const OrtMemoryInfo* info, void* p_data, size_t p_data_byte_count, - const int64_t* shape, size_t shape_len, - ONNXTensorElementDataType type) { - OrtValue* out; - ThrowOnError(GetApi().CreateTensorWithDataAsOrtValue(info, p_data, p_data_byte_count, shape, shape_len, type, &out)); - return Value{out}; -} - -inline Value Value::CreateTensor(OrtAllocator* deleter, void* p_data, size_t p_data_byte_count, - const int64_t* shape, size_t shape_len, - ONNXTensorElementDataType type) { - OrtValue* out; - ThrowOnError(GetApi().CreateTensorWithDataAndDeleterAsOrtValue(deleter, p_data, p_data_byte_count, - shape, shape_len, type, &out)); - return Value{out}; -} - -template -inline Value Value::CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len) { - return CreateTensor(allocator, shape, shape_len, TypeToTensorType::type); -} - -inline Value Value::CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len, - ONNXTensorElementDataType type) { - OrtValue* out; - ThrowOnError(GetApi().CreateTensorAsOrtValue(allocator, shape, shape_len, type, &out)); - return Value{out}; -} - -#if !defined(DISABLE_SPARSE_TENSORS) - -template -inline Value Value::CreateSparseTensor(const OrtMemoryInfo* info, T* p_data, const Shape& dense_shape, - const Shape& values_shape) { - return CreateSparseTensor(info, p_data, dense_shape, values_shape, TypeToTensorType::type); -} - -inline Value Value::CreateSparseTensor(const OrtMemoryInfo* info, void* p_data, const Shape& dense_shape, - const Shape& values_shape, ONNXTensorElementDataType type) { - OrtValue* out; - ThrowOnError(GetApi().CreateSparseTensorWithValuesAsOrtValue(info, p_data, dense_shape.shape, dense_shape.shape_len, - values_shape.shape, values_shape.shape_len, type, - &out)); - return Value{out}; -} - -template -inline Value Value::CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape) { - return CreateSparseTensor(allocator, dense_shape, TypeToTensorType::type); -} - -inline Value Value::CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape, - ONNXTensorElementDataType type) { - OrtValue* out; - ThrowOnError(GetApi().CreateSparseTensorAsOrtValue(allocator, dense_shape.shape, dense_shape.shape_len, type, &out)); - return Value{out}; -} -#endif // !defined(DISABLE_SPARSE_TENSORS) - -inline Value Value::CreateMap(const Value& keys, const Value& values) { - OrtValue* out; - const OrtValue* inputs[2] = {keys, values}; - ThrowOnError(GetApi().CreateValue(inputs, 2, ONNX_TYPE_MAP, &out)); - return Value{out}; -} - -inline Value Value::CreateSequence(const std::vector& values) { - OrtValue* out; - std::vector values_ort{values.data(), values.data() + values.size()}; - ThrowOnError(GetApi().CreateValue(values_ort.data(), values_ort.size(), ONNX_TYPE_SEQUENCE, &out)); - return Value{out}; -} - -template -inline Value Value::CreateOpaque(const char* domain, const char* type_name, const T& data_container) { - OrtValue* out; - ThrowOnError(GetApi().CreateOpaqueValue(domain, type_name, &data_container, sizeof(T), &out)); - return Value{out}; -} - -// -// Custom OP Inlines -// -inline Logger::Logger(const OrtLogger* logger) : logger_(logger) { - Ort::ThrowOnError(GetApi().Logger_GetLoggingSeverityLevel(this->logger_, &this->cached_severity_level_)); -} - -inline OrtLoggingLevel Logger::GetLoggingSeverityLevel() const noexcept { - return cached_severity_level_; -} - -inline Status Logger::LogMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path, int line_number, - const char* func_name, const char* message) const noexcept { - OrtStatus* status = GetApi().Logger_LogMessage(logger_, log_severity_level, message, file_path, line_number, - func_name); - return Status{status}; -} - -// Disable warnings about the format string not being a literal (-Wformat-nonliteral and -Wformat-security) -// for gcc and clang. The alternative is to use actual C-style variadic parameters and apply -// __attribute__(format(printf...)), which does not work with variadic templates. -#if defined(__GNUC__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wformat-nonliteral" -#pragma GCC diagnostic ignored "-Wformat-security" -#elif defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wformat-nonliteral" -#pragma clang diagnostic ignored "-Wformat-security" -#endif -template -inline Status Logger::LogFormattedMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path, - int line_number, const char* func_name, const char* format, - Args&&... args) const noexcept { - int msg_len = std::snprintf(nullptr, 0U, format, std::forward(args)...); - - if (msg_len < 0) { // Formatting error - return Status("Failed to log message due to formatting error", OrtErrorCode::ORT_FAIL); - } - - OrtStatus* status = nullptr; - const size_t buffer_size = static_cast(msg_len) + 1U; - - constexpr size_t kStackBufferSize = 1024; - - if (buffer_size < kStackBufferSize) { - char buffer[kStackBufferSize]; - snprintf(buffer, kStackBufferSize, format, std::forward(args)...); - status = GetApi().Logger_LogMessage(logger_, log_severity_level, buffer, file_path, line_number, func_name); - } else { - // std::make_unique is only supported starting at C++14. -#if (__cplusplus >= 201402L) || (_MSC_VER >= 1900) - auto buffer = std::make_unique(buffer_size); -#else - std::unique_ptr buffer(new char[buffer_size]); -#endif - std::snprintf(buffer.get(), buffer_size, format, std::forward(args)...); - status = GetApi().Logger_LogMessage(logger_, log_severity_level, buffer.get(), file_path, line_number, func_name); - } - - return Status{status}; -} -// Re-enable -Wformat-nonliteral and -Wformat-security -#if defined(__GNUC__) -#pragma GCC diagnostic pop -#elif defined(__clang__) -#pragma clang diagnostic pop -#endif - -inline KernelContext::KernelContext(OrtKernelContext* context) : ctx_(context) { -} - -inline size_t KernelContext::GetInputCount() const { - size_t out = 0; - Ort::ThrowOnError(GetApi().KernelContext_GetInputCount(ctx_, &out)); - return out; -} - -inline size_t KernelContext::GetOutputCount() const { - size_t out = 0; - Ort::ThrowOnError(GetApi().KernelContext_GetOutputCount(ctx_, &out)); - return out; -} - -inline ConstValue KernelContext::GetInput(size_t index) const { - const OrtValue* out = nullptr; - Ort::ThrowOnError(GetApi().KernelContext_GetInput(ctx_, index, &out)); - return ConstValue{out}; -} - -inline UnownedValue KernelContext::GetOutput(size_t index, const int64_t* dim_values, size_t dim_count) const { - OrtValue* out = nullptr; - Ort::ThrowOnError(GetApi().KernelContext_GetOutput(ctx_, index, dim_values, dim_count, &out)); - return UnownedValue(out); -} - -inline UnownedValue KernelContext::GetOutput(size_t index, const std::vector& dims) const { - OrtValue* out = nullptr; - Ort::ThrowOnError(GetApi().KernelContext_GetOutput(ctx_, index, dims.data(), dims.size(), &out)); - return UnownedValue(out); -} - -inline void* KernelContext::GetGPUComputeStream() const { - void* out = nullptr; - Ort::ThrowOnError(GetApi().KernelContext_GetGPUComputeStream(ctx_, &out)); - return out; -} - -inline OrtAllocator* KernelContext::GetAllocator(const OrtMemoryInfo& memory_info) const { - OrtAllocator* out = nullptr; - Ort::ThrowOnError(GetApi().KernelContext_GetAllocator(ctx_, &memory_info, &out)); - return out; -} - -inline Logger KernelContext::GetLogger() const { - const OrtLogger* out = nullptr; - ThrowOnError(GetApi().KernelContext_GetLogger(this->ctx_, &out)); - return Logger{out}; -} - -inline void KernelContext::ParallelFor(void (*fn)(void*, size_t), size_t total, size_t num_batch, void* usr_data) const { - ThrowOnError(GetApi().KernelContext_ParallelFor(ctx_, fn, total, num_batch, usr_data)); -} - -inline OpAttr::OpAttr(const char* name, const void* data, int len, OrtOpAttrType type) { - Ort::ThrowOnError(GetApi().CreateOpAttr(name, data, len, type, &p_)); -} - -namespace detail { -template -inline KernelInfo KernelInfoImpl::Copy() const { - OrtKernelInfo* info_copy = nullptr; - Ort::ThrowOnError(GetApi().CopyKernelInfo(this->p_, &info_copy)); - return KernelInfo{info_copy}; -} - -template -inline size_t KernelInfoImpl::GetInputCount() const { - size_t out = 0; - ThrowOnError(GetApi().KernelInfo_GetInputCount(this->p_, &out)); - return out; -} - -template -inline size_t KernelInfoImpl::GetOutputCount() const { - size_t out = 0; - ThrowOnError(GetApi().KernelInfo_GetOutputCount(this->p_, &out)); - return out; -} - -template -inline std::string KernelInfoImpl::GetInputName(size_t index) const { - size_t size = 0; - - // Feed nullptr for the data buffer to query the true size of the string value - Ort::ThrowOnError(GetApi().KernelInfo_GetInputName(this->p_, index, nullptr, &size)); - - std::string out; - out.resize(size); - Ort::ThrowOnError(GetApi().KernelInfo_GetInputName(this->p_, index, &out[0], &size)); - out.resize(size - 1); // remove the terminating character '\0' - - return out; -} - -template -inline std::string KernelInfoImpl::GetOutputName(size_t index) const { - size_t size = 0; - - // Feed nullptr for the data buffer to query the true size of the string value - Ort::ThrowOnError(GetApi().KernelInfo_GetOutputName(this->p_, index, nullptr, &size)); - - std::string out; - out.resize(size); - Ort::ThrowOnError(GetApi().KernelInfo_GetOutputName(this->p_, index, &out[0], &size)); - out.resize(size - 1); // remove the terminating character '\0' - - return out; -} - -template -inline TypeInfo KernelInfoImpl::GetInputTypeInfo(size_t index) const { - OrtTypeInfo* out = nullptr; - ThrowOnError(GetApi().KernelInfo_GetInputTypeInfo(this->p_, index, &out)); - return TypeInfo{out}; -} - -template -inline TypeInfo KernelInfoImpl::GetOutputTypeInfo(size_t index) const { - OrtTypeInfo* out = nullptr; - ThrowOnError(GetApi().KernelInfo_GetOutputTypeInfo(this->p_, index, &out)); - return TypeInfo{out}; -} - -template -inline Value KernelInfoImpl::GetTensorAttribute(const char* name, OrtAllocator* allocator) const { - OrtValue* out = nullptr; - ThrowOnError(GetApi().KernelInfoGetAttribute_tensor(this->p_, name, allocator, &out)); - return Value{out}; -} - -template -inline ConstValue KernelInfoImpl::GetTensorConstantInput(size_t index, int* is_constant) const { - const OrtValue* out = nullptr; - ThrowOnError(GetApi().KernelInfoGetConstantInput_tensor(this->p_, index, is_constant, &out)); - return ConstValue{out}; -} - -template -inline std::string KernelInfoImpl::GetNodeName() const { - size_t size = 0; - - // Feed nullptr for the data buffer to query the true size of the string value - Ort::ThrowOnError(GetApi().KernelInfo_GetNodeName(this->p_, nullptr, &size)); - - std::string out; - out.resize(size); - Ort::ThrowOnError(GetApi().KernelInfo_GetNodeName(this->p_, &out[0], &size)); - out.resize(size - 1); // remove the terminating character '\0' - - return out; -} - -template -inline Logger KernelInfoImpl::GetLogger() const { - const OrtLogger* out = nullptr; - ThrowOnError(GetApi().KernelInfo_GetLogger(this->p_, &out)); - return Logger{out}; -} - -inline void attr_utils::GetAttr(const OrtKernelInfo* p, const char* name, float& out) { - Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_float(p, name, &out)); -} - -inline void attr_utils::GetAttr(const OrtKernelInfo* p, const char* name, int64_t& out) { - Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_int64(p, name, &out)); -} - -inline void attr_utils::GetAttr(const OrtKernelInfo* p, const char* name, std::string& result) { - size_t size = 0; - // Feed nullptr for the data buffer to query the true size of the string attribute - Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_string(p, name, nullptr, &size)); - - std::string out; - out.resize(size); - Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_string(p, name, &out[0], &size)); - out.resize(size - 1); // remove the terminating character '\0' - out.swap(result); -} - -inline void attr_utils::GetAttrs(const OrtKernelInfo* p, const char* name, std::vector& result) { - size_t size = 0; - // Feed nullptr for the data buffer to query the true size of the attribute - Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_float(p, name, nullptr, &size)); - - std::vector out; - out.resize(size); - Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_float(p, name, out.data(), &size)); - out.swap(result); -} - -inline void attr_utils::GetAttrs(const OrtKernelInfo* p, const char* name, std::vector& result) { - size_t size = 0; - - // Feed nullptr for the data buffer to query the true size of the attribute - Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_int64(p, name, nullptr, &size)); - - std::vector out; - out.resize(size); - Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_int64(p, name, out.data(), &size)); - out.swap(result); -} -} // namespace detail - -inline KernelInfo::KernelInfo(OrtKernelInfo* info) : detail::KernelInfoImpl{info} {} - -inline Op::Op(OrtOp* p) : detail::Base(p) {} - -inline Op Op::Create(const OrtKernelInfo* info, const char* op_name, const char* domain, int version, - const char** type_constraint_names, - const ONNXTensorElementDataType* type_constraint_values, - size_t type_constraint_count, - const OpAttr* attr_values, size_t attr_count, - size_t input_count, size_t output_count) { - static_assert(sizeof(OpAttr) == sizeof(OrtOpAttr*), - "OpAttr's is expected to be just an array of OrtOpAttr in memory so we can reinterpret safely"); - auto attr_input_values = reinterpret_cast(attr_values); - OrtOp* op; - Ort::ThrowOnError(GetApi().CreateOp(info, op_name, domain, version, type_constraint_names, type_constraint_values, - static_cast(type_constraint_count), - attr_input_values, - static_cast(attr_count), - static_cast(input_count), - static_cast(output_count), &op)); - return Op{op}; -} - -inline void Op::Invoke(const OrtKernelContext* context, - const Value* input_values, - size_t input_count, - Value* output_values, - size_t output_count) { - static_assert(sizeof(Value) == sizeof(OrtValue*), - "Value is really just an array of OrtValue* in memory, so we can reinterpret_cast safely"); - auto ort_input_values = reinterpret_cast(input_values); - auto ort_output_values = reinterpret_cast(output_values); - Ort::ThrowOnError(GetApi().InvokeOp(context, p_, ort_input_values, static_cast(input_count), - ort_output_values, static_cast(output_count))); -} - -inline void Op::Invoke(const OrtKernelContext* context, - const OrtValue* const* input_values, - size_t input_count, - OrtValue* const* output_values, - size_t output_count) { - Ort::ThrowOnError(GetApi().InvokeOp(context, p_, input_values, static_cast(input_count), - output_values, static_cast(output_count))); -} - -inline std::string GetVersionString() { - return OrtGetApiBase()->GetVersionString(); -} - -inline std::string GetBuildInfoString() { - return GetApi().GetBuildInfoString(); -} - -inline std::vector GetAvailableProviders() { - char** providers; - int len; - - auto release_fn = [&len](char** providers) { - // This should always return nullptr. - ThrowOnError(GetApi().ReleaseAvailableProviders(providers, len)); - }; - - ThrowOnError(GetApi().GetAvailableProviders(&providers, &len)); - std::unique_ptr guard(providers, release_fn); - std::vector available_providers; - available_providers.reserve(static_cast(len)); - for (int i = 0; i < len; ++i) { - available_providers.emplace_back(providers[i]); - } - return available_providers; -} - -template -void CustomOpBase::GetSessionConfigs(std::unordered_map& out, - ConstSessionOptions options) const { - const TOp* derived = static_cast(this); - std::vector keys = derived->GetSessionConfigKeys(); - - out.reserve(keys.size()); - - std::string config_entry_key = detail::MakeCustomOpConfigEntryKey(derived->GetName(), ""); - const size_t prefix_size = config_entry_key.length(); - - for (const auto& key : keys) { - config_entry_key.resize(prefix_size); - config_entry_key.append(key); - out[key] = options.GetConfigEntryOrDefault(config_entry_key.c_str(), ""); - } -} - -inline ShapeInferContext::ShapeInferContext(const OrtApi* ort_api, - OrtShapeInferContext* ctx) : ort_api_(ort_api), ctx_(ctx) { - size_t input_count = 0; - Ort::ThrowOnError(ort_api_->ShapeInferContext_GetInputCount(ctx_, &input_count)); - for (size_t ith_input = 0; ith_input < input_count; ++ith_input) { - OrtTensorTypeAndShapeInfo* info{}; - Ort::ThrowOnError(ort_api_->ShapeInferContext_GetInputTypeShape(ctx, ith_input, &info)); - TensorTypeAndShapeInfo type_shape_info(info); - auto integer_shape = type_shape_info.GetShape(); - std::vector symbolic_shape(integer_shape.size(), {}); - if (!integer_shape.empty()) { - type_shape_info.GetSymbolicDimensions(&symbolic_shape[0], integer_shape.size()); - } - Shape shape; - for (size_t ith = 0; ith < integer_shape.size(); ++ith) { - if (symbolic_shape[ith] && std::string{symbolic_shape[ith]}.size() > 0) { - shape.emplace_back(symbolic_shape[ith]); - } else { - shape.emplace_back(integer_shape[ith]); - } - } - input_shapes_.push_back(std::move(shape)); - type_shape_info.release(); - } -} - -inline Status ShapeInferContext::SetOutputShape(size_t indice, const Shape& shape, ONNXTensorElementDataType type) { - OrtTensorTypeAndShapeInfo* info = {}; - ORT_CXX_RETURN_ON_API_FAIL(ort_api_->CreateTensorTypeAndShapeInfo(&info)); - ORT_CXX_RETURN_ON_API_FAIL(ort_api_->SetTensorElementType(info, type)); - - using InfoPtr = std::unique_ptr>; - - InfoPtr info_ptr(info, [this](OrtTensorTypeAndShapeInfo* obj) { - ort_api_->ReleaseTensorTypeAndShapeInfo(obj); - }); - - std::vector integer_dims; - std::vector symbolic_dims; - - for (const auto dim : shape) { - if (dim.IsInt()) { - integer_dims.push_back(dim.AsInt()); - symbolic_dims.push_back(""); - } else { - if (!dim.AsSym() || std::string{dim.AsSym()}.empty()) { - ORT_CXX_API_THROW("Symbolic dim must not be an empty string", ORT_INVALID_ARGUMENT); - } - integer_dims.push_back(SymbolicInteger::INVALID_INT_DIM); - symbolic_dims.push_back(dim.AsSym()); - } - } - - ORT_CXX_RETURN_ON_API_FAIL(ort_api_->SetDimensions(info, integer_dims.data(), integer_dims.size())); - ORT_CXX_RETURN_ON_API_FAIL(ort_api_->SetSymbolicDimensions(info, symbolic_dims.data(), symbolic_dims.size())); - ORT_CXX_RETURN_ON_API_FAIL(ort_api_->ShapeInferContext_SetOutputTypeShape(ctx_, indice, info)); - return Status{nullptr}; -} - -inline int64_t ShapeInferContext::GetAttrInt(const char* attr_name) { - const auto* attr = GetAttrHdl(attr_name); - int64_t i = {}; - size_t out = {}; - Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_INT, &i, sizeof(i), &out)); - return i; -} - -inline ShapeInferContext::Ints ShapeInferContext::GetAttrInts(const char* attr_name) { - const auto* attr = GetAttrHdl(attr_name); - int64_t i = {}; - size_t out = {}; - // first call to get the bytes needed - // 1. A status == nullptr means that ReadOpAttr was successful. A status != nullptr means failure. - // 2. The ReadOpAttr function should normally be called twice: once to get the needed buffer size (returns a status != nullptr), and a second time to actually read the ints (returns status == null on success). - // 3. This code tries a subtle optimization in the first call to ReadOpAttr. It passes in a buffer (&i) of size 1 just in case there is only 1 int. In this case, status == nullptr and we need to return {i}. - auto status = ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_INTS, &i, sizeof(i), &out); - if (status) { - size_t num_i = out / sizeof(int64_t); - ShapeInferContext::Ints ints(num_i, 0); - Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_INTS, ints.data(), out, &out)); - return ints; - } else { - if (out == 0u) { - return {}; - } - return {i}; - } -} - -inline float ShapeInferContext::GetAttrFloat(const char* attr_name) { - const auto* attr = GetAttrHdl(attr_name); - float f = {}; - size_t out = {}; - Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_FLOAT, &f, sizeof(f), &out)); - return f; -} - -inline ShapeInferContext::Floats ShapeInferContext::GetAttrFloats(const char* attr_name) { - const auto* attr = GetAttrHdl(attr_name); - float f = {}; - size_t out = {}; - // first call to get the bytes needed - // 1. A status == nullptr means that ReadOpAttr was successful. A status != nullptr means failure. - // 2. The ReadOpAttr function should normally be called twice: once to get the needed buffer size (returns a status != nullptr), and a second time to actually read the ints (returns status == null on success). - // 3. This code tries a subtle optimization in the first call to ReadOpAttr. It passes in a buffer (&i) of size 1 just in case there is only 1 int. In this case, status == nullptr and we need to return {i}. - auto status = ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_FLOATS, &f, sizeof(f), &out); - if (status) { - size_t num_f = out / sizeof(float); - ShapeInferContext::Floats floats(num_f, 0); - Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_FLOATS, floats.data(), out, &out)); - return floats; - } else { - if (out == 0u) { - return {}; - } - return {f}; - } -} - -inline std::string ShapeInferContext::GetAttrString(const char* attr_name) { - const auto* attr = GetAttrHdl(attr_name); - char c = {}; - size_t out = {}; - // first call to get the bytes needed - auto status = ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_STRING, &c, sizeof(char), &out); - if (status) { - std::vector chars(out, '\0'); - Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_STRING, chars.data(), out, &out)); - return {chars.data()}; - } else { - return {c}; - } -} - -inline ShapeInferContext::Strings ShapeInferContext::GetAttrStrings(const char* attr_name) { - const auto* attr = GetAttrHdl(attr_name); - char c = {}; - size_t out = {}; - // first call to get the bytes needed - // 1. A status == nullptr means that ReadOpAttr was successful. A status != nullptr means failure. - // 2. The ReadOpAttr function should normally be called twice: once to get the needed buffer size (returns a status != nullptr), and a second time to actually read the ints (returns status == null on success). - // 3. This code tries a subtle optimization in the first call to ReadOpAttr. It passes in a buffer (&i) of size 1 just in case there is only 1 int. In this case, status == nullptr and we need to return {i}. - auto status = ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_STRINGS, &c, sizeof(char), &out); - if (status) { - std::vector chars(out, '\0'); - Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_STRINGS, chars.data(), out, &out)); - ShapeInferContext::Strings strings; - char* char_st = chars.data(); - char* char_ed = char_st + out; - while (char_st < char_ed) { - strings.emplace_back(char_st); - while (*char_st != '\0') { - char_st++; - } - char_st++; - } - return strings; - } else { - if (out == 0u) { - return {}; - } - return {std::string{c}}; - } -} - -inline const OrtOpAttr* ShapeInferContext::GetAttrHdl(const char* attr_name) const { - const OrtOpAttr* attr_hdl = {}; - Ort::ThrowOnError(ort_api_->ShapeInferContext_GetAttribute(ctx_, attr_name, &attr_hdl)); - return attr_hdl; -} - -namespace detail { -inline std::vector StringsToCharPtrs(const std::vector& strings) { - std::vector ptrs; - ptrs.reserve(strings.size()); - std::transform(strings.begin(), strings.end(), std::back_inserter(ptrs), - [](const std::string& s) { return s.c_str(); }); - - return ptrs; -} -} // namespace detail - -#if !defined(ORT_MINIMAL_BUILD) -// static -inline void Node::Init(const std::string& operator_name, const std::string& operator_domain, - const std::string& node_name, - const std::vector& input_names, - const std::vector& output_names, - std::vector& attributes, - OrtNode*& node) { - auto inputs = detail::StringsToCharPtrs(input_names); - auto outputs = detail::StringsToCharPtrs(output_names); - - std::vector attributes_ptrs; - attributes_ptrs.reserve(attributes.size()); - std::transform(attributes.begin(), attributes.end(), std::back_inserter(attributes_ptrs), - [](OpAttr& attr) -> OrtOpAttr* { return attr; }); - - ThrowOnError(GetModelEditorApi().CreateNode(operator_name.c_str(), operator_domain.c_str(), node_name.c_str(), - inputs.data(), inputs.size(), - outputs.data(), outputs.size(), - attributes_ptrs.data(), attributes_ptrs.size(), - &node)); - - // Node now owns the attributes - std::for_each(attributes.begin(), attributes.end(), [](OpAttr& attr) { attr.release(); }); -} - -inline Node::Node(const std::string& operator_name, const std::string& operator_domain, - const std::string& node_name, - const std::vector& input_names, - const std::vector& output_names, - std::vector& attributes) { - Init(operator_name, operator_domain, node_name, input_names, output_names, attributes, p_); -} - -inline Node::Node(const std::string& operator_name, const std::string& operator_domain, - const std::string& node_name, - const std::vector& input_names, - const std::vector& output_names) { - std::vector empty_attributes; - Init(operator_name, operator_domain, node_name, input_names, output_names, empty_attributes, p_); -} - -inline Graph::Graph() { - ThrowOnError(GetModelEditorApi().CreateGraph(&p_)); -} - -inline Model::Model(const std::vector& opsets) { - std::vector domains; - std::vector versions; - domains.reserve(opsets.size()); - versions.reserve(opsets.size()); - - for (const auto& pair : opsets) { - domains.push_back(pair.first.c_str()); - versions.push_back(pair.second); - } - - ThrowOnError(GetModelEditorApi().CreateModel(domains.data(), versions.data(), opsets.size(), &p_)); -} - -inline ValueInfo::ValueInfo(const std::string& name, const ConstTypeInfo& type_info) { - ThrowOnError(GetModelEditorApi().CreateValueInfo(name.c_str(), type_info, &p_)); -} -#endif // !defined(ORT_MINIMAL_BUILD) - -namespace detail { -template <> -inline std::string ValueInfoImpl::Name() const { - const char* name = nullptr; - ThrowOnError(GetApi().GetValueInfoName(this->p_, &name)); - return name; -} - -template <> -inline ConstTypeInfo ValueInfoImpl::TypeInfo() const { - const OrtTypeInfo* type_info = nullptr; - ThrowOnError(GetApi().GetValueInfoTypeInfo(this->p_, &type_info)); - return ConstTypeInfo{type_info}; -} - -#if !defined(ORT_MINIMAL_BUILD) -template <> -inline void GraphImpl::SetInputs(std::vector& inputs) { - std::vector inputs_ptrs; - inputs_ptrs.reserve(inputs.size()); - std::transform(inputs.begin(), inputs.end(), std::back_inserter(inputs_ptrs), - [](ValueInfo& vi) -> OrtValueInfo* { return vi; }); - - ThrowOnError(GetModelEditorApi().SetGraphInputs(p_, inputs_ptrs.data(), inputs_ptrs.size())); - - // Graph now owns the inputs - std::for_each(inputs.begin(), inputs.end(), [](ValueInfo& vi) { vi.release(); }); -} - -template <> -inline void GraphImpl::SetOutputs(std::vector& outputs) { - std::vector outputs_ptrs; - outputs_ptrs.reserve(outputs.size()); - std::transform(outputs.begin(), outputs.end(), std::back_inserter(outputs_ptrs), - [](ValueInfo& vi) -> OrtValueInfo* { return vi; }); - - ThrowOnError(GetModelEditorApi().SetGraphOutputs(p_, outputs_ptrs.data(), outputs_ptrs.size())); - - // Graph now owns the outputs - std::for_each(outputs.begin(), outputs.end(), [](ValueInfo& vi) { vi.release(); }); -} - -template <> -inline void GraphImpl::AddInitializer(const std::string& name, Value& initializer, bool data_is_external) { - // Graph takes ownership of `initializer` - ThrowOnError(GetModelEditorApi().AddInitializerToGraph(p_, name.c_str(), initializer.release(), data_is_external)); -} - -template <> -inline void GraphImpl::AddNode(Node& node) { - // Graph takes ownership of `node` - ThrowOnError(GetModelEditorApi().AddNodeToGraph(p_, node.release())); -} - -template <> -inline void ModelImpl::AddGraph(Graph& graph) { - // Model takes ownership of `graph` - ThrowOnError(GetModelEditorApi().AddGraphToModel(p_, graph.release())); -} -#endif // !defined(ORT_MINIMAL_BUILD) - -} // namespace detail -} // namespace Ort +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// Do not include this file directly. Please include "onnxruntime_cxx_api.h" instead. +// If interested in trying out features of the new experimental C++ API, include "experimental_onnxruntime_cxx_api.h" instead. +// +// These are the inline implementations of the C++ header APIs. They're in this separate file as to not clutter +// the main C++ file with implementation details. + +#include +#include +#include +#include +#include +#include + +// Convert OrtStatus to Ort::Status and return +// instead of throwing +#define ORT_CXX_RETURN_ON_API_FAIL(expression) \ + { \ + auto ort_status = (expression); \ + if (ort_status) { \ + return Ort::Status(ort_status); \ + } \ + } + +#ifdef __cpp_if_constexpr +#define ORT_CXX_IF_CONSTEXPR if constexpr +#else +#define ORT_CXX_IF_CONSTEXPR if +#endif + +namespace Ort { + +namespace detail { +inline void ThrowStatus(const Status& st) { + std::string error_message = st.GetErrorMessage(); + OrtErrorCode error_code = st.GetErrorCode(); + ORT_CXX_API_THROW(std::move(error_message), error_code); +} +} // namespace detail + +inline void ThrowOnError(OrtStatus* ort_status) { + if (ort_status) { + Ort::Status st(ort_status); + detail::ThrowStatus(st); + } +} + +inline void ThrowOnError(const Status& st) { + if (st) { + detail::ThrowStatus(st); + } +} + +inline Status::Status(OrtStatus* status) noexcept : detail::Base{status} { +} + +inline Status::Status(const std::exception& e) noexcept { + p_ = GetApi().CreateStatus(ORT_FAIL, e.what()); +} + +inline Status::Status(const Exception& e) noexcept { + p_ = GetApi().CreateStatus(e.GetOrtErrorCode(), e.what()); +} + +inline Status::Status(const char* message, OrtErrorCode code) noexcept { + p_ = GetApi().CreateStatus(code, message); +} + +inline std::string Status::GetErrorMessage() const { + std::string message(GetApi().GetErrorMessage(p_)); + return message; +} + +inline OrtErrorCode Status::GetErrorCode() const { + return GetApi().GetErrorCode(p_); +} + +inline bool Status::IsOK() const noexcept { + return (p_ == nullptr); +} + +// This template converts a C++ type into it's ONNXTensorElementDataType +template +struct TypeToTensorType; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_BFLOAT16; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL; +}; + +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FN; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FNUZ; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2FNUZ; +}; + +inline bool BFloat16_t::operator==(const BFloat16_t& rhs) const noexcept { + if (IsNaN() || rhs.IsNaN()) { + // IEEE defines that NaN is not equal to anything, including itself. + return false; + } + return val == rhs.val; +} + +inline bool BFloat16_t::operator<(const BFloat16_t& rhs) const noexcept { + if (IsNaN() || rhs.IsNaN()) { + // IEEE defines that NaN is unordered with respect to everything, including itself. + return false; + } + + const bool left_is_negative = IsNegative(); + if (left_is_negative != rhs.IsNegative()) { + // When the signs of left and right differ, we know that left is less than right if it is + // the negative value. The exception to this is if both values are zero, in which case IEEE + // says they should be equal, even if the signs differ. + return left_is_negative && !AreZero(*this, rhs); + } + return (val != rhs.val) && ((val < rhs.val) ^ left_is_negative); +} + +inline MemoryAllocation::MemoryAllocation(OrtAllocator* allocator, void* p, size_t size) + : allocator_(allocator), p_(p), size_(size) { +} + +inline MemoryAllocation::~MemoryAllocation() { + if (p_ != nullptr) { + // We do not throw out of destructor + auto ret = GetApi().AllocatorFree(allocator_, p_); + static_cast(ret); + } +} + +inline MemoryAllocation::MemoryAllocation(MemoryAllocation&& o) noexcept : allocator_(nullptr), p_(nullptr), size_(0) { + *this = std::move(o); +} + +inline MemoryAllocation& MemoryAllocation::operator=(MemoryAllocation&& o) noexcept { + OrtAllocator* alloc = nullptr; + void* p = nullptr; + size_t sz = 0; + + // Swap out this + std::swap(alloc, allocator_); + std::swap(p, p_); + std::swap(sz, size_); + + // Swap with incoming + std::swap(allocator_, o.allocator_); + std::swap(p_, o.p_); + std::swap(size_, o.size_); + + // Destroy this instance if needed + MemoryAllocation this_alloc(alloc, p, sz); + return *this; +} + +namespace detail { + +template +inline void* AllocatorImpl::Alloc(size_t size) { + void* out; + ThrowOnError(GetApi().AllocatorAlloc(this->p_, size, &out)); + return out; +} + +template +inline MemoryAllocation AllocatorImpl::GetAllocation(size_t size) { + void* out; + ThrowOnError(GetApi().AllocatorAlloc(this->p_, size, &out)); + MemoryAllocation result(this->p_, out, size); + return result; +} + +template +inline void AllocatorImpl::Free(void* p) { + ThrowOnError(GetApi().AllocatorFree(this->p_, p)); +} + +template +inline ConstMemoryInfo AllocatorImpl::GetInfo() const { + const OrtMemoryInfo* out; + ThrowOnError(GetApi().AllocatorGetInfo(this->p_, &out)); + return ConstMemoryInfo{out}; +} + +} // namespace detail + +inline AllocatorWithDefaultOptions::AllocatorWithDefaultOptions() { + ThrowOnError(GetApi().GetAllocatorWithDefaultOptions(&this->p_)); +} + +inline Allocator::Allocator(const Session& sess, const OrtMemoryInfo* mem_info) { + ThrowOnError(GetApi().CreateAllocator(sess, mem_info, &this->p_)); +} + +namespace detail { + +template +inline std::string MemoryInfoImpl::GetAllocatorName() const { + const char* name = nullptr; + ThrowOnError(GetApi().MemoryInfoGetName(this->p_, &name)); + return std::string(name); +} + +template +inline OrtAllocatorType MemoryInfoImpl::GetAllocatorType() const { + OrtAllocatorType type; + ThrowOnError(GetApi().MemoryInfoGetType(this->p_, &type)); + return type; +} + +template +inline int MemoryInfoImpl::GetDeviceId() const { + int id = 0; + ThrowOnError(GetApi().MemoryInfoGetId(this->p_, &id)); + return id; +} + +template +inline OrtMemoryInfoDeviceType MemoryInfoImpl::GetDeviceType() const { + OrtMemoryInfoDeviceType type; + GetApi().MemoryInfoGetDeviceType(this->p_, &type); + return type; +} + +template +inline OrtMemType MemoryInfoImpl::GetMemoryType() const { + OrtMemType type; + ThrowOnError(GetApi().MemoryInfoGetMemType(this->p_, &type)); + return type; +} + +template +template +inline bool MemoryInfoImpl::operator==(const MemoryInfoImpl& o) const { + int comp_result = 0; + ThrowOnError(Ort::GetApi().CompareMemoryInfo(this->p_, o, &comp_result)); + return comp_result == 0; +} + +} // namespace detail + +inline MemoryInfo MemoryInfo::CreateCpu(OrtAllocatorType type, OrtMemType mem_type) { + OrtMemoryInfo* p; + ThrowOnError(GetApi().CreateCpuMemoryInfo(type, mem_type, &p)); + return MemoryInfo(p); +} + +inline MemoryInfo::MemoryInfo(const char* name, OrtAllocatorType type, int id, OrtMemType mem_type) { + ThrowOnError(GetApi().CreateMemoryInfo(name, type, id, mem_type, &this->p_)); +} + +namespace detail { +template +inline std::vector ConstIoBindingImpl::GetOutputNames() const { + AllocatorWithDefaultOptions allocator; + return binding_utils::GetOutputNamesHelper(this->p_, allocator); +} + +template +inline std::vector ConstIoBindingImpl::GetOutputNames(OrtAllocator* allocator) const { + return binding_utils::GetOutputNamesHelper(this->p_, allocator); +} + +template +inline std::vector ConstIoBindingImpl::GetOutputValues() const { + AllocatorWithDefaultOptions allocator; + return binding_utils::GetOutputValuesHelper(this->p_, allocator); +} + +template +inline std::vector ConstIoBindingImpl::GetOutputValues(OrtAllocator* allocator) const { + return binding_utils::GetOutputValuesHelper(this->p_, allocator); +} + +template +inline void IoBindingImpl::BindInput(const char* name, const Value& value) { + ThrowOnError(GetApi().BindInput(this->p_, name, value)); +} + +template +inline void IoBindingImpl::BindOutput(const char* name, const Value& value) { + ThrowOnError(GetApi().BindOutput(this->p_, name, value)); +} + +template +inline void IoBindingImpl::BindOutput(const char* name, const OrtMemoryInfo* mem_info) { + ThrowOnError(GetApi().BindOutputToDevice(this->p_, name, mem_info)); +} + +template +inline void IoBindingImpl::ClearBoundInputs() { + GetApi().ClearBoundInputs(this->p_); +} + +template +inline void IoBindingImpl::ClearBoundOutputs() { + GetApi().ClearBoundOutputs(this->p_); +} + +template +inline void IoBindingImpl::SynchronizeInputs() { + ThrowOnError(GetApi().SynchronizeBoundInputs(this->p_)); +} + +template +inline void IoBindingImpl::SynchronizeOutputs() { + ThrowOnError(GetApi().SynchronizeBoundOutputs(this->p_)); +} + +namespace binding_utils { +inline std::vector GetOutputNamesHelper(const OrtIoBinding* binding, OrtAllocator* allocator) { + std::vector result; + auto free_fn = detail::AllocatedFree(allocator); + using Ptr = std::unique_ptr; + + char* buffer = nullptr; + size_t* lengths = nullptr; + size_t count = 0; + ThrowOnError(GetApi().GetBoundOutputNames(binding, allocator, &buffer, &lengths, &count)); + + if (count == 0) { + return result; + } + + Ptr buffer_g(buffer, free_fn); + Ptr lengths_g(lengths, free_fn); + + result.reserve(count); + for (size_t i = 0; i < count; ++i) { + auto sz = *lengths; + result.emplace_back(buffer, sz); + buffer += sz; + ++lengths; + } + return result; +} + +inline std::vector GetOutputValuesHelper(const OrtIoBinding* binding, OrtAllocator* allocator) { + std::vector result; + size_t owned = 0; + size_t output_count = 0; + // Lambda to release the buffer when no longer needed and + // make sure that we destroy all instances on exception + auto free_fn = [&owned, &output_count, allocator](OrtValue** buffer) { + if (buffer) { + while (owned < output_count) { + auto* p = buffer + owned++; + GetApi().ReleaseValue(*p); + } + allocator->Free(allocator, buffer); + } + }; + using Ptr = std::unique_ptr; + + OrtValue** output_buffer = nullptr; + ThrowOnError(GetApi().GetBoundOutputValues(binding, allocator, &output_buffer, &output_count)); + if (output_count == 0) { + return result; + } + + Ptr buffer_g(output_buffer, free_fn); + + result.reserve(output_count); + for (size_t i = 0; i < output_count; ++i) { + result.emplace_back(output_buffer[i]); + ++owned; + } + return result; +} + +} // namespace binding_utils +} // namespace detail + +inline IoBinding::IoBinding(Session& session) { + ThrowOnError(GetApi().CreateIoBinding(session, &this->p_)); +} + +inline ArenaCfg::ArenaCfg(size_t max_mem, int arena_extend_strategy, int initial_chunk_size_bytes, int max_dead_bytes_per_chunk) { + ThrowOnError(GetApi().CreateArenaCfg(max_mem, arena_extend_strategy, initial_chunk_size_bytes, max_dead_bytes_per_chunk, &p_)); +} + +inline ThreadingOptions::ThreadingOptions() { + ThrowOnError(GetApi().CreateThreadingOptions(&p_)); +} + +inline ThreadingOptions& ThreadingOptions::SetGlobalIntraOpNumThreads(int intra_op_num_threads) { + ThrowOnError(GetApi().SetGlobalIntraOpNumThreads(p_, intra_op_num_threads)); + return *this; +} + +inline ThreadingOptions& ThreadingOptions::SetGlobalInterOpNumThreads(int inter_op_num_threads) { + ThrowOnError(GetApi().SetGlobalInterOpNumThreads(p_, inter_op_num_threads)); + return *this; +} + +inline ThreadingOptions& ThreadingOptions::SetGlobalSpinControl(int allow_spinning) { + ThrowOnError(GetApi().SetGlobalSpinControl(p_, allow_spinning)); + return *this; +} + +inline ThreadingOptions& ThreadingOptions::SetGlobalDenormalAsZero() { + ThrowOnError(GetApi().SetGlobalDenormalAsZero(p_)); + return *this; +} + +inline ThreadingOptions& ThreadingOptions::SetGlobalCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn) { + ThrowOnError(GetApi().SetGlobalCustomCreateThreadFn(p_, ort_custom_create_thread_fn)); + return *this; +} + +inline ThreadingOptions& ThreadingOptions::SetGlobalCustomThreadCreationOptions(void* ort_custom_thread_creation_options) { + ThrowOnError(GetApi().SetGlobalCustomThreadCreationOptions(p_, ort_custom_thread_creation_options)); + return *this; +} + +inline ThreadingOptions& ThreadingOptions::SetGlobalCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn) { + ThrowOnError(GetApi().SetGlobalCustomJoinThreadFn(p_, ort_custom_join_thread_fn)); + return *this; +} + +namespace detail { +template +inline const char* KeyValuePairsImpl::GetValue(const char* key) const { + return GetApi().GetKeyValue(this->p_, key); +} + +template +inline std::unordered_map KeyValuePairsImpl::GetKeyValuePairs() const { + std::unordered_map out; + + size_t num_pairs = 0; + const char* const* keys = nullptr; + const char* const* values = nullptr; + GetApi().GetKeyValuePairs(this->p_, &keys, &values, &num_pairs); + if (num_pairs > 0) { + out.reserve(num_pairs); + for (size_t i = 0; i < num_pairs; ++i) { + out.emplace(keys[i], values[i]); + } + } + + return out; +} + +template +inline void KeyValuePairsImpl::GetKeyValuePairs(std::vector& keys, + std::vector& values) const { + keys.clear(); + values.clear(); + + size_t num_pairs = 0; + const char* const* keys_ptr = nullptr; + const char* const* values_ptr = nullptr; + GetApi().GetKeyValuePairs(this->p_, &keys_ptr, &values_ptr, &num_pairs); + if (num_pairs > 0) { + keys.resize(num_pairs); + values.resize(num_pairs); + std::copy(keys_ptr, keys_ptr + num_pairs, keys.begin()); + std::copy(values_ptr, values_ptr + num_pairs, values.begin()); + } +} +} // namespace detail + +inline KeyValuePairs::KeyValuePairs() { + GetApi().CreateKeyValuePairs(&p_); +} + +inline KeyValuePairs::KeyValuePairs(const std::unordered_map& kv_pairs) { + GetApi().CreateKeyValuePairs(&p_); + for (const auto& kv : kv_pairs) { + GetApi().AddKeyValuePair(this->p_, kv.first.c_str(), kv.second.c_str()); + } +} + +inline void KeyValuePairs::Add(const char* key, const char* value) { + GetApi().AddKeyValuePair(this->p_, key, value); +} + +inline void KeyValuePairs::Remove(const char* key) { + GetApi().RemoveKeyValuePair(this->p_, key); +} + +namespace detail { +template +inline OrtHardwareDeviceType HardwareDeviceImpl::Type() const { + return GetApi().HardwareDevice_Type(this->p_); +} + +template +inline uint32_t HardwareDeviceImpl::VendorId() const { + return GetApi().HardwareDevice_VendorId(this->p_); +} + +template +inline uint32_t HardwareDeviceImpl::DeviceId() const { + return GetApi().HardwareDevice_DeviceId(this->p_); +} + +template +inline const char* HardwareDeviceImpl::Vendor() const { + return GetApi().HardwareDevice_Vendor(this->p_); +} + +template +inline ConstKeyValuePairs HardwareDeviceImpl::Metadata() const { + return ConstKeyValuePairs{GetApi().HardwareDevice_Metadata(this->p_)}; +} + +template +inline const char* EpDeviceImpl::EpName() const { + return GetApi().EpDevice_EpName(this->p_); +} + +template +inline const char* EpDeviceImpl::EpVendor() const { + return GetApi().EpDevice_EpVendor(this->p_); +} + +template +inline ConstKeyValuePairs EpDeviceImpl::EpMetadata() const { + return ConstKeyValuePairs(GetApi().EpDevice_EpMetadata(this->p_)); +} + +template +inline ConstKeyValuePairs EpDeviceImpl::EpOptions() const { + return ConstKeyValuePairs(GetApi().EpDevice_EpOptions(this->p_)); +} + +template +inline ConstHardwareDevice EpDeviceImpl::Device() const { + return ConstHardwareDevice(GetApi().EpDevice_Device(this->p_)); +} +} // namespace detail + +inline EpDevice::EpDevice(OrtEpFactory& ep_factory, ConstHardwareDevice& hardware_device, + ConstKeyValuePairs ep_metadata, ConstKeyValuePairs ep_options) { + ThrowOnError(GetEpApi().CreateEpDevice(&ep_factory, hardware_device, ep_metadata, ep_options, &p_)); +} + +inline Env::Env(OrtLoggingLevel logging_level, _In_ const char* logid) { + ThrowOnError(GetApi().CreateEnv(logging_level, logid, &p_)); + if (strcmp(logid, "onnxruntime-node") == 0) { + ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS)); + } else { + ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS)); + } +} + +inline Env::Env(OrtLoggingLevel logging_level, const char* logid, OrtLoggingFunction logging_function, void* logger_param) { + ThrowOnError(GetApi().CreateEnvWithCustomLogger(logging_function, logger_param, logging_level, logid, &p_)); + if (strcmp(logid, "onnxruntime-node") == 0) { + ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS)); + } else { + ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS)); + } +} + +inline Env::Env(const OrtThreadingOptions* tp_options, OrtLoggingLevel logging_level, _In_ const char* logid) { + ThrowOnError(GetApi().CreateEnvWithGlobalThreadPools(logging_level, logid, tp_options, &p_)); + if (strcmp(logid, "onnxruntime-node") == 0) { + ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS)); + } else { + ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS)); + } +} + +inline Env::Env(const OrtThreadingOptions* tp_options, OrtLoggingFunction logging_function, void* logger_param, + OrtLoggingLevel logging_level, _In_ const char* logid) { + ThrowOnError(GetApi().CreateEnvWithCustomLoggerAndGlobalThreadPools(logging_function, logger_param, logging_level, logid, tp_options, &p_)); + if (strcmp(logid, "onnxruntime-node") == 0) { + ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS)); + } else { + ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS)); + } +} + +inline Env& Env::EnableTelemetryEvents() { + ThrowOnError(GetApi().EnableTelemetryEvents(p_)); + return *this; +} + +inline Env& Env::DisableTelemetryEvents() { + ThrowOnError(GetApi().DisableTelemetryEvents(p_)); + return *this; +} + +inline Env& Env::UpdateEnvWithCustomLogLevel(OrtLoggingLevel log_severity_level) { + ThrowOnError(GetApi().UpdateEnvWithCustomLogLevel(p_, log_severity_level)); + return *this; +} + +inline Env& Env::CreateAndRegisterAllocator(const OrtMemoryInfo* mem_info, const OrtArenaCfg* arena_cfg) { + ThrowOnError(GetApi().CreateAndRegisterAllocator(p_, mem_info, arena_cfg)); + return *this; +} + +inline Env& Env::CreateAndRegisterAllocatorV2(const std::string& provider_type, const OrtMemoryInfo* mem_info, const std::unordered_map& options, const OrtArenaCfg* arena_cfg) { + std::vector keys, values; + auto num_entries = options.size(); + if (num_entries > 0) { + keys.reserve(num_entries); + values.reserve(num_entries); + for (const auto& entry : options) { + keys.push_back(entry.first.c_str()); + values.push_back(entry.second.c_str()); + } + } + ThrowOnError(GetApi().CreateAndRegisterAllocatorV2(p_, provider_type.c_str(), mem_info, arena_cfg, keys.data(), values.data(), num_entries)); + return *this; +} + +inline Env& Env::RegisterExecutionProviderLibrary(const char* registration_name, + const std::basic_string& path) { + ThrowOnError(GetApi().RegisterExecutionProviderLibrary(p_, registration_name, path.c_str())); + return *this; +} + +inline Env& Env::UnregisterExecutionProviderLibrary(const char* registration_name) { + ThrowOnError(GetApi().UnregisterExecutionProviderLibrary(p_, registration_name)); + return *this; +} + +inline std::vector Env::GetEpDevices() const { + size_t num_devices = 0; + const OrtEpDevice* const* device_ptrs = nullptr; + ThrowOnError(GetApi().GetEpDevices(p_, &device_ptrs, &num_devices)); + + std::vector devices; + if (num_devices > 0) { + devices.reserve(num_devices); + for (size_t i = 0; i < num_devices; ++i) { + devices.emplace_back(device_ptrs[i]); + } + } + + return devices; +} + +inline CustomOpDomain::CustomOpDomain(const char* domain) { + ThrowOnError(GetApi().CreateCustomOpDomain(domain, &p_)); +} + +inline void CustomOpDomain::Add(const OrtCustomOp* op) { + ThrowOnError(GetApi().CustomOpDomain_Add(p_, op)); +} + +inline LoraAdapter LoraAdapter::CreateLoraAdapter(const std::basic_string& adapter_path, + OrtAllocator* allocator) { + OrtLoraAdapter* p; + ThrowOnError(GetApi().CreateLoraAdapter(adapter_path.c_str(), allocator, &p)); + return LoraAdapter{p}; +} + +inline LoraAdapter LoraAdapter::CreateLoraAdapterFromArray(const void* bytes, size_t num_bytes, + OrtAllocator* allocator) { + OrtLoraAdapter* p; + ThrowOnError(GetApi().CreateLoraAdapterFromArray(bytes, num_bytes, allocator, &p)); + return LoraAdapter{p}; +} + +inline RunOptions::RunOptions() { + ThrowOnError(GetApi().CreateRunOptions(&p_)); +} + +inline RunOptions& RunOptions::SetRunLogVerbosityLevel(int level) { + ThrowOnError(GetApi().RunOptionsSetRunLogVerbosityLevel(p_, level)); + return *this; +} + +inline RunOptions& RunOptions::SetRunLogSeverityLevel(int level) { + ThrowOnError(GetApi().RunOptionsSetRunLogSeverityLevel(p_, level)); + return *this; +} + +inline int RunOptions::GetRunLogVerbosityLevel() const { + int out; + ThrowOnError(GetApi().RunOptionsGetRunLogVerbosityLevel(p_, &out)); + return out; +} + +inline int RunOptions::GetRunLogSeverityLevel() const { + int out; + ThrowOnError(GetApi().RunOptionsGetRunLogSeverityLevel(p_, &out)); + return out; +} + +inline RunOptions& RunOptions::SetRunTag(const char* run_tag) { + ThrowOnError(GetApi().RunOptionsSetRunTag(p_, run_tag)); + return *this; +} + +inline const char* RunOptions::GetRunTag() const { + const char* out; + ThrowOnError(GetApi().RunOptionsGetRunTag(p_, &out)); + return out; +} + +inline RunOptions& RunOptions::AddConfigEntry(const char* config_key, const char* config_value) { + ThrowOnError(GetApi().AddRunConfigEntry(p_, config_key, config_value)); + return *this; +} + +inline RunOptions& RunOptions::SetTerminate() { + ThrowOnError(GetApi().RunOptionsSetTerminate(p_)); + return *this; +} + +inline RunOptions& RunOptions::UnsetTerminate() { + ThrowOnError(GetApi().RunOptionsUnsetTerminate(p_)); + return *this; +} + +inline RunOptions& RunOptions::AddActiveLoraAdapter(const LoraAdapter& adapter) { + ThrowOnError(GetApi().RunOptionsAddActiveLoraAdapter(p_, adapter)); + return *this; +} + +inline ModelCompilationOptions::ModelCompilationOptions(const Env& env, const SessionOptions& session_options) { + ThrowOnError(GetCompileApi().CreateModelCompilationOptionsFromSessionOptions(env, session_options, &this->p_)); +} + +inline ModelCompilationOptions::ModelCompilationOptions(const Env& env, ConstSessionOptions session_options) { + ThrowOnError(GetCompileApi().CreateModelCompilationOptionsFromSessionOptions(env, session_options, &this->p_)); +} + +inline Status CompileModel(const Env& env, const ModelCompilationOptions& model_compilation_options) { + return Ort::Status(GetCompileApi().CompileModel(env, model_compilation_options)); +} + +inline ModelCompilationOptions& ModelCompilationOptions::SetInputModelPath( + const ORTCHAR_T* input_model_path) { + Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetInputModelPath(this->p_, input_model_path)); + return *this; +} + +inline ModelCompilationOptions& ModelCompilationOptions::SetInputModelFromBuffer( + const void* input_model_data, size_t input_model_data_size) { + Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetInputModelFromBuffer(this->p_, input_model_data, + input_model_data_size)); + return *this; +} + +inline ModelCompilationOptions& ModelCompilationOptions::SetOutputModelPath( + const ORTCHAR_T* output_model_path) { + Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetOutputModelPath(this->p_, output_model_path)); + return *this; +} + +inline ModelCompilationOptions& ModelCompilationOptions::SetOutputModelExternalInitializersFile( + const ORTCHAR_T* file_path, size_t initializer_size_threshold) { + Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetOutputModelExternalInitializersFile( + this->p_, + file_path, + initializer_size_threshold)); + return *this; +} + +inline ModelCompilationOptions& ModelCompilationOptions::SetOutputModelBuffer( + OrtAllocator* allocator, void** output_model_buffer_ptr, size_t* output_model_buffer_size_ptr) { + Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetOutputModelBuffer(this->p_, allocator, + output_model_buffer_ptr, + output_model_buffer_size_ptr)); + return *this; +} + +inline ModelCompilationOptions& ModelCompilationOptions::SetEpContextEmbedMode( + bool embed_ep_context_in_model) { + Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetEpContextEmbedMode( + this->p_, + embed_ep_context_in_model)); + return *this; +} + +namespace detail { + +template +inline Ort::SessionOptions ConstSessionOptionsImpl::Clone() const { + OrtSessionOptions* out; + ThrowOnError(GetApi().CloneSessionOptions(this->p_, &out)); + return SessionOptions{out}; +} + +template +inline std::string ConstSessionOptionsImpl::GetConfigEntry(const char* config_key) const { + size_t size = 0; + // Feed nullptr for the data buffer to query the true size of the string value + Ort::ThrowOnError(GetApi().GetSessionConfigEntry(this->p_, config_key, nullptr, &size)); + + std::string out; + out.resize(size); + Ort::ThrowOnError(GetApi().GetSessionConfigEntry(this->p_, config_key, &out[0], &size)); + out.resize(size - 1); // remove the terminating character '\0' + + return out; +} + +template +inline bool ConstSessionOptionsImpl::HasConfigEntry(const char* config_key) const { + int out = 0; + Ort::ThrowOnError(GetApi().HasSessionConfigEntry(this->p_, config_key, &out)); + return static_cast(out); +} + +template +inline std::string ConstSessionOptionsImpl::GetConfigEntryOrDefault(const char* config_key, + const std::string& def) const { + if (!this->HasConfigEntry(config_key)) { + return def; + } + + return this->GetConfigEntry(config_key); +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetIntraOpNumThreads(int intra_op_num_threads) { + ThrowOnError(GetApi().SetIntraOpNumThreads(this->p_, intra_op_num_threads)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetInterOpNumThreads(int inter_op_num_threads) { + ThrowOnError(GetApi().SetInterOpNumThreads(this->p_, inter_op_num_threads)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetGraphOptimizationLevel(GraphOptimizationLevel graph_optimization_level) { + ThrowOnError(GetApi().SetSessionGraphOptimizationLevel(this->p_, graph_optimization_level)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetDeterministicCompute(bool value) { + ThrowOnError(GetApi().SetDeterministicCompute(this->p_, value)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetOptimizedModelFilePath(const ORTCHAR_T* optimized_model_filepath) { + ThrowOnError(GetApi().SetOptimizedModelFilePath(this->p_, optimized_model_filepath)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::EnableProfiling(const ORTCHAR_T* profile_file_prefix) { + ThrowOnError(GetApi().EnableProfiling(this->p_, profile_file_prefix)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::DisableProfiling() { + ThrowOnError(GetApi().DisableProfiling(this->p_)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::EnableOrtCustomOps() { + ThrowOnError(GetApi().EnableOrtCustomOps(this->p_)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::EnableMemPattern() { + ThrowOnError(GetApi().EnableMemPattern(this->p_)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::DisableMemPattern() { + ThrowOnError(GetApi().DisableMemPattern(this->p_)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::EnableCpuMemArena() { + ThrowOnError(GetApi().EnableCpuMemArena(this->p_)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::DisableCpuMemArena() { + ThrowOnError(GetApi().DisableCpuMemArena(this->p_)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetExecutionMode(ExecutionMode execution_mode) { + ThrowOnError(GetApi().SetSessionExecutionMode(this->p_, execution_mode)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetLoadCancellationFlag(bool value) { + ThrowOnError(GetApi().SessionOptionsSetLoadCancellationFlag(this->p_, value)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetLogId(const char* logid) { + ThrowOnError(GetApi().SetSessionLogId(this->p_, logid)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetLogSeverityLevel(int level) { + ThrowOnError(GetApi().SetSessionLogSeverityLevel(this->p_, level)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::Add(OrtCustomOpDomain* custom_op_domain) { + ThrowOnError(GetApi().AddCustomOpDomain(this->p_, custom_op_domain)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AddConfigEntry(const char* config_key, const char* config_value) { + ThrowOnError(GetApi().AddSessionConfigEntry(this->p_, config_key, config_value)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AddInitializer(const char* name, const OrtValue* ort_val) { + ThrowOnError(GetApi().AddInitializer(this->p_, name, ort_val)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::DisablePerSessionThreads() { + ThrowOnError(GetApi().DisablePerSessionThreads(this->p_)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AddExternalInitializers(const std::vector& names, + const std::vector& ort_values) { + const size_t inputs_num = names.size(); + if (inputs_num != ort_values.size()) { + ORT_CXX_API_THROW("Expecting names and ort_values to have the same length", ORT_INVALID_ARGUMENT); + } + std::vector names_ptr; + std::vector ort_values_ptrs; + names_ptr.reserve(inputs_num); + ort_values_ptrs.reserve(inputs_num); + for (size_t i = 0; i < inputs_num; ++i) { + names_ptr.push_back(names[i].c_str()); + ort_values_ptrs.push_back(ort_values[i]); + } + ThrowOnError(GetApi().AddExternalInitializers(this->p_, names_ptr.data(), ort_values_ptrs.data(), inputs_num)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AddExternalInitializersFromFilesInMemory(const std::vector>& file_names, + const std::vector& buffer_array, + const std::vector& file_lengths) { + const size_t inputs_num = file_names.size(); + if (inputs_num != buffer_array.size()) { + ORT_CXX_API_THROW("Expecting names and buffer_array to have the same length", ORT_INVALID_ARGUMENT); + } + if (inputs_num != file_lengths.size()) { + ORT_CXX_API_THROW("Expecting names and file_lengths to have the same length", ORT_INVALID_ARGUMENT); + } + std::vector names_ptr; + names_ptr.reserve(inputs_num); + for (size_t i = 0; i < inputs_num; ++i) { + names_ptr.push_back(file_names[i].c_str()); + } + ThrowOnError(GetApi().AddExternalInitializersFromFilesInMemory(this->p_, names_ptr.data(), buffer_array.data(), + file_lengths.data(), inputs_num)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_CUDA(const OrtCUDAProviderOptions& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CUDA(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_CUDA_V2(const OrtCUDAProviderOptionsV2& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CUDA_V2(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_ROCM(const OrtROCMProviderOptions& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_ROCM(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_TensorRT(const OrtTensorRTProviderOptions& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_TensorRT(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_TensorRT_V2(const OrtTensorRTProviderOptionsV2& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_TensorRT_V2(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_MIGraphX(const OrtMIGraphXProviderOptions& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_MIGraphX(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_CANN(const OrtCANNProviderOptions& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CANN(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_Dnnl(const OrtDnnlProviderOptions& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_Dnnl(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider( + const std::string& provider_name, + const std::unordered_map& provider_options) { + auto num_entries = provider_options.size(); + std::vector keys, values; + if (num_entries > 0) { + keys.reserve(num_entries); + values.reserve(num_entries); + + for (const auto& entry : provider_options) { + keys.push_back(entry.first.c_str()); + values.push_back(entry.second.c_str()); + } + } + + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider(this->p_, provider_name.c_str(), + keys.data(), values.data(), num_entries)); + + return *this; +} + +namespace { +template +void SessionOptionsAppendEP(detail::SessionOptionsImpl& session_options, + Env& env, const std::vector& ep_devices, + const std::vector& ep_options_keys, + const std::vector& ep_options_values) { + std::vector ep_devices_ptrs; + ep_devices_ptrs.reserve(ep_devices.size()); + for (const auto& ep_device : ep_devices) { + ep_devices_ptrs.push_back(ep_device); + } + + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_V2( + session_options, env, ep_devices_ptrs.data(), ep_devices_ptrs.size(), + ep_options_keys.data(), ep_options_values.data(), ep_options_keys.size())); +} +} // namespace + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_V2( + Env& env, const std::vector& ep_devices, const KeyValuePairs& ep_options) { + std::vector ep_options_keys, ep_options_values; + ep_options.GetKeyValuePairs(ep_options_keys, ep_options_values); + + SessionOptionsAppendEP(*this, env, ep_devices, ep_options_keys, ep_options_values); + + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_V2( + Env& env, const std::vector& ep_devices, + const std::unordered_map& ep_options) { + std::vector ep_options_keys, ep_options_values; + ep_options_keys.reserve(ep_options.size()); + ep_options_values.reserve(ep_options.size()); + + for (const auto& [key, value] : ep_options) { + ep_options_keys.push_back(key.c_str()); + ep_options_values.push_back(value.c_str()); + } + + SessionOptionsAppendEP(*this, env, ep_devices, ep_options_keys, ep_options_values); + + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetEpSelectionPolicy(OrtExecutionProviderDevicePolicy policy) { + ThrowOnError(GetApi().SessionOptionsSetEpSelectionPolicy(this->p_, policy)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetEpSelectionPolicy(EpSelectionDelegate delegate, void* state) { + ThrowOnError(GetApi().SessionOptionsSetEpSelectionPolicyDelegate(this->p_, delegate, state)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn) { + ThrowOnError(GetApi().SessionOptionsSetCustomCreateThreadFn(this->p_, ort_custom_create_thread_fn)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetCustomThreadCreationOptions(void* ort_custom_thread_creation_options) { + ThrowOnError(GetApi().SessionOptionsSetCustomThreadCreationOptions(this->p_, ort_custom_thread_creation_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn) { + ThrowOnError(GetApi().SessionOptionsSetCustomJoinThreadFn(this->p_, ort_custom_join_thread_fn)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_OpenVINO(const OrtOpenVINOProviderOptions& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_OpenVINO(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_OpenVINO_V2(const std::unordered_map& provider_options) { + auto num_entries = provider_options.size(); + std::vector keys, values; + if (num_entries > 0) { + keys.reserve(num_entries); + values.reserve(num_entries); + + for (const auto& entry : provider_options) { + keys.push_back(entry.first.c_str()); + values.push_back(entry.second.c_str()); + } + } + + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_OpenVINO_V2(this->p_, + keys.data(), values.data(), num_entries)); + + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_VitisAI(const std::unordered_map& provider_options) { + auto num_entries = provider_options.size(); + std::vector keys, values; + if (num_entries > 0) { + keys.reserve(num_entries); + values.reserve(num_entries); + + for (const auto& entry : provider_options) { + keys.push_back(entry.first.c_str()); + values.push_back(entry.second.c_str()); + } + } + + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_VitisAI(this->p_, keys.data(), values.data(), num_entries)); + + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::RegisterCustomOpsLibrary(const ORTCHAR_T* library_name, + const CustomOpConfigs& custom_op_configs) { + // Add custom op config entries before registering the custom op library. Otherwise, the config entries _may_ be ignored by + // the custom op library. + for (const auto& config_iter : custom_op_configs.GetFlattenedConfigs()) { + AddConfigEntry(config_iter.first.c_str(), config_iter.second.c_str()); + } + + ThrowOnError(GetApi().RegisterCustomOpsLibrary_V2(this->p_, library_name)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::RegisterCustomOpsUsingFunction(const char* registration_function_name) { + ThrowOnError(GetApi().RegisterCustomOpsUsingFunction(this->p_, registration_function_name)); + return *this; +} + +/// Session +template +inline size_t ConstSessionImpl::GetInputCount() const { + size_t out; + ThrowOnError(GetApi().SessionGetInputCount(this->p_, &out)); + return out; +} + +template +inline size_t ConstSessionImpl::GetOutputCount() const { + size_t out; + ThrowOnError(GetApi().SessionGetOutputCount(this->p_, &out)); + return out; +} + +template +inline size_t ConstSessionImpl::GetOverridableInitializerCount() const { + size_t out; + ThrowOnError(GetApi().SessionGetOverridableInitializerCount(this->p_, &out)); + return out; +} + +template +inline std::vector ConstSessionImpl::GetInputNames() const { + AllocatorWithDefaultOptions allocator; + + auto num_inputs = GetInputCount(); + std::vector input_names; + input_names.reserve(num_inputs); + + for (size_t i = 0; i < num_inputs; ++i) { + char* name = nullptr; + ThrowOnError(GetApi().SessionGetInputName(this->p_, i, allocator, &name)); + input_names.push_back(name); + allocator.Free(name); + } + + return input_names; +} + +template +inline std::vector ConstSessionImpl::GetOutputNames() const { + AllocatorWithDefaultOptions allocator; + + auto num_inputs = GetOutputCount(); + std::vector output_names; + output_names.reserve(num_inputs); + + for (size_t i = 0; i < num_inputs; ++i) { + char* name = nullptr; + ThrowOnError(GetApi().SessionGetOutputName(this->p_, i, allocator, &name)); + output_names.push_back(name); + allocator.Free(name); + } + + return output_names; +} + +template +inline std::vector ConstSessionImpl::GetOverridableInitializerNames() const { + AllocatorWithDefaultOptions allocator; + + auto num_initializers = GetOverridableInitializerCount(); + std::vector initializer_names; + initializer_names.reserve(num_initializers); + + for (size_t i = 0; i < num_initializers; ++i) { + char* name = nullptr; + ThrowOnError(GetApi().SessionGetOverridableInitializerName(this->p_, i, allocator, &name)); + initializer_names.push_back(name); + } + + return initializer_names; +} + +template +inline AllocatedStringPtr ConstSessionImpl::GetInputNameAllocated(size_t index, OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().SessionGetInputName(this->p_, index, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +template +inline AllocatedStringPtr ConstSessionImpl::GetOutputNameAllocated(size_t index, OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().SessionGetOutputName(this->p_, index, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +template +inline AllocatedStringPtr ConstSessionImpl::GetOverridableInitializerNameAllocated(size_t index, OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().SessionGetOverridableInitializerName(this->p_, index, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +template +inline uint64_t ConstSessionImpl::GetProfilingStartTimeNs() const { + uint64_t out; + ThrowOnError(GetApi().SessionGetProfilingStartTimeNs(this->p_, &out)); + return out; +} + +template +inline ModelMetadata ConstSessionImpl::GetModelMetadata() const { + OrtModelMetadata* out; + ThrowOnError(GetApi().SessionGetModelMetadata(this->p_, &out)); + return ModelMetadata{out}; +} + +template +inline TypeInfo ConstSessionImpl::GetInputTypeInfo(size_t index) const { + OrtTypeInfo* out; + ThrowOnError(GetApi().SessionGetInputTypeInfo(this->p_, index, &out)); + return TypeInfo{out}; +} + +template +inline TypeInfo ConstSessionImpl::GetOutputTypeInfo(size_t index) const { + OrtTypeInfo* out; + ThrowOnError(GetApi().SessionGetOutputTypeInfo(this->p_, index, &out)); + return TypeInfo{out}; +} + +template +inline TypeInfo ConstSessionImpl::GetOverridableInitializerTypeInfo(size_t index) const { + OrtTypeInfo* out; + ThrowOnError(GetApi().SessionGetOverridableInitializerTypeInfo(this->p_, index, &out)); + return TypeInfo{out}; +} + +#if !defined(ORT_MINIMAL_BUILD) +template +inline int ConstSessionImpl::GetOpset(const std::string& domain) const { + int opset; + ThrowOnError(GetModelEditorApi().SessionGetOpsetForDomain(this->p_, domain.c_str(), &opset)); + return opset; +} +#endif // !defined(ORT_MINIMAL_BUILD) + +template +std::vector ConstSessionImpl::GetInputs() const { + const std::vector input_names = GetInputNames(); + + std::vector inputs; + inputs.reserve(input_names.size()); + + for (size_t i = 0; i < input_names.size(); ++i) { + auto type_info = GetInputTypeInfo(i); + inputs.emplace_back(ValueInfo{input_names[i], type_info.GetConst()}); + } + + return inputs; +} + +template +std::vector ConstSessionImpl::GetOutputs() const { + const std::vector output_names = GetOutputNames(); + + std::vector outputs; + outputs.reserve(output_names.size()); + + for (size_t i = 0; i < output_names.size(); ++i) { + auto type_info = GetOutputTypeInfo(i); + outputs.emplace_back(ValueInfo{output_names[i], type_info.GetConst()}); + } + + return outputs; +} + +template +inline std::vector SessionImpl::Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, + const char* const* output_names, size_t output_count) { + std::vector output_values; + output_values.reserve(output_count); + for (size_t i = 0; i < output_count; i++) + output_values.emplace_back(nullptr); + Run(run_options, input_names, input_values, input_count, output_names, output_values.data(), output_count); + return output_values; +} + +template +inline void SessionImpl::Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, + const char* const* output_names, Value* output_values, size_t output_count) { + static_assert(sizeof(Value) == sizeof(OrtValue*), "Value is really just an array of OrtValue* in memory, so we can reinterpret_cast safely"); + auto ort_input_values = reinterpret_cast(input_values); + auto ort_output_values = reinterpret_cast(output_values); + ThrowOnError(GetApi().Run(this->p_, run_options, input_names, ort_input_values, input_count, output_names, output_count, ort_output_values)); +} + +template +inline void SessionImpl::Run(const RunOptions& run_options, const IoBinding& io_binding) { + ThrowOnError(GetApi().RunWithBinding(this->p_, run_options, io_binding)); +} + +template +inline void SessionImpl::RunAsync(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, + const char* const* output_names, Value* output_values, size_t output_count, RunAsyncCallbackFn callback, void* user_data) { + auto ort_input_values = reinterpret_cast(input_values); + auto ort_output_values = reinterpret_cast(output_values); + ThrowOnError(GetApi().RunAsync(this->p_, run_options, input_names, + ort_input_values, input_count, output_names, output_count, + ort_output_values, callback, user_data)); +} + +template +inline AllocatedStringPtr SessionImpl::EndProfilingAllocated(OrtAllocator* allocator) { + char* out = nullptr; + ThrowOnError(GetApi().SessionEndProfiling(this->p_, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +template +inline void SessionImpl::SetEpDynamicOptions(const char* const* keys, const char* const* values, size_t kv_len) { + ThrowOnError(GetApi().SetEpDynamicOptions(this->p_, keys, values, kv_len)); +} + +#if !defined(ORT_MINIMAL_BUILD) +template +inline void SessionImpl::FinalizeModelEditorSession(const Model& model, const SessionOptions& options, + OrtPrepackedWeightsContainer* prepacked_weights_container) { + ThrowOnError(GetModelEditorApi().ApplyModelToModelEditorSession(this->p_, model)); + ThrowOnError(GetModelEditorApi().FinalizeModelEditorSession(this->p_, options, prepacked_weights_container)); +} +#endif // #if !defined(ORT_MINIMAL_BUILD) + +} // namespace detail + +inline SessionOptions::SessionOptions() { + ThrowOnError(GetApi().CreateSessionOptions(&this->p_)); +} + +/// CustomOpConfigs +inline std::string detail::MakeCustomOpConfigEntryKey(const char* custom_op_name, const char* config) { + std::string config_key = "custom_op."; + + config_key += custom_op_name; + config_key += "."; + config_key += config; + + return config_key; +} + +inline CustomOpConfigs& CustomOpConfigs::AddConfig(const char* custom_op_name, const char* config_key, const char* config_value) { + const std::string full_flat_key = detail::MakeCustomOpConfigEntryKey(custom_op_name, config_key); + flat_configs_[full_flat_key] = config_value; + return *this; +} + +inline const std::unordered_map& CustomOpConfigs::GetFlattenedConfigs() const { + return flat_configs_; +} + +inline Session::Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options) { + ThrowOnError(GetApi().CreateSession(env, model_path, options, &this->p_)); +} + +inline Session::Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options, + OrtPrepackedWeightsContainer* prepacked_weights_container) { + ThrowOnError(GetApi().CreateSessionWithPrepackedWeightsContainer(env, model_path, options, prepacked_weights_container, &this->p_)); +} + +inline Session::Session(const Env& env, const void* model_data, size_t model_data_length, const SessionOptions& options) { + ThrowOnError(GetApi().CreateSessionFromArray(env, model_data, model_data_length, options, &this->p_)); +} + +inline Session::Session(const Env& env, const void* model_data, size_t model_data_length, + const SessionOptions& options, OrtPrepackedWeightsContainer* prepacked_weights_container) { + ThrowOnError(GetApi().CreateSessionFromArrayWithPrepackedWeightsContainer(env, model_data, model_data_length, options, + prepacked_weights_container, &this->p_)); +} + +#if !defined(ORT_MINIMAL_BUILD) +inline Session::Session(const Env& env, const Model& model, const SessionOptions& options) { + ThrowOnError(GetModelEditorApi().CreateSessionFromModel(env, model.GetConst(), options, &this->p_)); +} + +// static +inline Session Session::CreateModelEditorSession(const Env& env, const ORTCHAR_T* model_path, + const SessionOptions& options) { + OrtSession* session = nullptr; + ThrowOnError(GetModelEditorApi().CreateModelEditorSession(env, model_path, options, &session)); + return Session(session); +} + +// static +inline Session Session::CreateModelEditorSession(const Env& env, const void* model_data, size_t model_data_length, + const SessionOptions& options) { + OrtSession* session = nullptr; + ThrowOnError(GetModelEditorApi().CreateModelEditorSessionFromArray(env, model_data, model_data_length, options, + &session)); + return Session(session); +} + +void FinalizeModelEditorSession(const Model& model, const SessionOptions& options, + OrtPrepackedWeightsContainer* prepacked_weights_container); +#endif // #if !defined(ORT_MINIMAL_BUILD) + +inline AllocatedStringPtr ModelMetadata::GetProducerNameAllocated(OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().ModelMetadataGetProducerName(p_, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +inline AllocatedStringPtr ModelMetadata::GetGraphNameAllocated(OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().ModelMetadataGetGraphName(p_, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +inline AllocatedStringPtr ModelMetadata::GetDomainAllocated(OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().ModelMetadataGetDomain(p_, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +inline AllocatedStringPtr Ort::ModelMetadata::GetDescriptionAllocated(OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().ModelMetadataGetDescription(p_, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +inline AllocatedStringPtr ModelMetadata::GetGraphDescriptionAllocated(OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().ModelMetadataGetGraphDescription(p_, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +inline AllocatedStringPtr ModelMetadata::LookupCustomMetadataMapAllocated(const char* key, OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().ModelMetadataLookupCustomMetadataMap(p_, allocator, key, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +inline std::vector ModelMetadata::GetCustomMetadataMapKeysAllocated(OrtAllocator* allocator) const { + auto deletor = detail::AllocatedFree(allocator); + std::vector result; + + char** out = nullptr; + int64_t num_keys = 0; + ThrowOnError(GetApi().ModelMetadataGetCustomMetadataMapKeys(p_, allocator, &out, &num_keys)); + if (num_keys <= 0) { + return result; + } + + // array of pointers will be freed + std::unique_ptr array_guard(out, deletor); + // reserve may throw + auto strings_deletor = [&deletor, num_keys](char** out) { for(int64_t i = 0; i < num_keys; ++i) deletor(out[i]); }; + std::unique_ptr strings_guard(out, strings_deletor); + result.reserve(static_cast(num_keys)); + strings_guard.release(); + for (int64_t i = 0; i < num_keys; ++i) { + result.push_back(AllocatedStringPtr(out[i], deletor)); + } + + return result; +} + +inline int64_t ModelMetadata::GetVersion() const { + int64_t out; + ThrowOnError(GetApi().ModelMetadataGetVersion(p_, &out)); + return out; +} + +inline TensorTypeAndShapeInfo::TensorTypeAndShapeInfo(ONNXTensorElementDataType element_type, + const std::vector& dims, + const std::vector* symbolic_dims) { + ThrowOnError(GetApi().CreateTensorTypeAndShapeInfo(&p_)); + ThrowOnError(GetApi().SetTensorElementType(p_, element_type)); + ThrowOnError(GetApi().SetDimensions(p_, dims.data(), dims.size())); + + if (symbolic_dims) { + std::vector symbolic_dims_cstr; + symbolic_dims_cstr.reserve(symbolic_dims->size()); + std::transform(symbolic_dims->begin(), symbolic_dims->end(), std::back_inserter(symbolic_dims_cstr), + [](const std::string& s) { return s.c_str(); }); + ThrowOnError(GetApi().SetSymbolicDimensions(p_, symbolic_dims_cstr.data(), symbolic_dims_cstr.size())); + } +} + +#if !defined(ORT_MINIMAL_BUILD) +// static +inline TypeInfo TypeInfo::CreateTensorInfo(ConstTensorTypeAndShapeInfo tensor_type_and_shape_info) { + OrtTypeInfo* output = nullptr; + ThrowOnError(GetModelEditorApi().CreateTensorTypeInfo(tensor_type_and_shape_info, &output)); + return TypeInfo{output}; +} + +// static +inline TypeInfo TypeInfo::CreateSparseTensorInfo(ConstTensorTypeAndShapeInfo sparse_tensor_type_and_shape_info) { + OrtTypeInfo* output = nullptr; + ThrowOnError(GetModelEditorApi().CreateSparseTensorTypeInfo(sparse_tensor_type_and_shape_info, &output)); + return TypeInfo{output}; +} + +// static +inline TypeInfo TypeInfo::CreateSequenceTypeInfo(ConstTypeInfo sequence_type) { + OrtTypeInfo* output; + ThrowOnError(GetModelEditorApi().CreateSequenceTypeInfo(sequence_type, &output)); + return TypeInfo{output}; +} + +// static +inline TypeInfo TypeInfo::CreateMapTypeInfo(ONNXTensorElementDataType key_type, ConstTypeInfo value_type) { + OrtTypeInfo* output; + ThrowOnError(GetModelEditorApi().CreateMapTypeInfo(key_type, value_type, &output)); + return TypeInfo{output}; +} + +// static +inline TypeInfo TypeInfo::CreateOptionalTypeInfo(ConstTypeInfo contained_type) { + OrtTypeInfo* output; + ThrowOnError(GetModelEditorApi().CreateOptionalTypeInfo(contained_type, &output)); + return TypeInfo{output}; +} +#endif // #if !defined(ORT_MINIMAL_BUILD) + +namespace detail { + +template +inline ONNXTensorElementDataType TensorTypeAndShapeInfoImpl::GetElementType() const { + ONNXTensorElementDataType out; + ThrowOnError(GetApi().GetTensorElementType(this->p_, &out)); + return out; +} + +template +inline size_t TensorTypeAndShapeInfoImpl::GetElementCount() const { + size_t out; + ThrowOnError(GetApi().GetTensorShapeElementCount(this->p_, &out)); + return static_cast(out); +} + +template +inline size_t TensorTypeAndShapeInfoImpl::GetDimensionsCount() const { + size_t out; + ThrowOnError(GetApi().GetDimensionsCount(this->p_, &out)); + return out; +} + +template +inline void TensorTypeAndShapeInfoImpl::GetDimensions(int64_t* values, size_t values_count) const { + ThrowOnError(GetApi().GetDimensions(this->p_, values, values_count)); +} + +template +inline void TensorTypeAndShapeInfoImpl::GetSymbolicDimensions(const char** values, size_t values_count) const { + ThrowOnError(GetApi().GetSymbolicDimensions(this->p_, values, values_count)); +} + +template +inline std::vector TensorTypeAndShapeInfoImpl::GetSymbolicDimensions() const { + std::vector out(GetDimensionsCount(), nullptr); + ThrowOnError(GetApi().GetSymbolicDimensions(this->p_, out.data(), out.size())); + return out; +} + +template +inline std::vector TensorTypeAndShapeInfoImpl::GetShape() const { + std::vector out(GetDimensionsCount(), -1); + ThrowOnError(GetApi().GetDimensions(this->p_, out.data(), out.size())); + return out; +} + +template +inline ConstTensorTypeAndShapeInfo TypeInfoImpl::GetTensorTypeAndShapeInfo() const { + const OrtTensorTypeAndShapeInfo* out; + ThrowOnError(GetApi().CastTypeInfoToTensorInfo(this->p_, &out)); + return ConstTensorTypeAndShapeInfo{out}; +} + +template +inline ConstSequenceTypeInfo TypeInfoImpl::GetSequenceTypeInfo() const { + const OrtSequenceTypeInfo* out; + ThrowOnError(GetApi().CastTypeInfoToSequenceTypeInfo(this->p_, &out)); + return ConstSequenceTypeInfo{out}; +} + +template +inline ConstMapTypeInfo TypeInfoImpl::GetMapTypeInfo() const { + const OrtMapTypeInfo* out; + ThrowOnError(GetApi().CastTypeInfoToMapTypeInfo(this->p_, &out)); + return ConstMapTypeInfo{out}; +} + +template +inline ONNXType TypeInfoImpl::GetONNXType() const { + ONNXType out; + ThrowOnError(GetApi().GetOnnxTypeFromTypeInfo(this->p_, &out)); + return out; +} + +template +inline TypeInfo SequenceTypeInfoImpl::GetSequenceElementType() const { + OrtTypeInfo* output; + ThrowOnError(GetApi().GetSequenceElementType(this->p_, &output)); + return TypeInfo{output}; +} + +template +inline TypeInfo OptionalTypeInfoImpl::GetOptionalElementType() const { + OrtTypeInfo* info; + ThrowOnError(GetApi().GetOptionalContainedTypeInfo(this->p_, &info)); + return TypeInfo{info}; +} + +template +inline ONNXTensorElementDataType MapTypeInfoImpl::GetMapKeyType() const { + ONNXTensorElementDataType out; + ThrowOnError(GetApi().GetMapKeyType(this->p_, &out)); + return out; +} + +template +inline TypeInfo MapTypeInfoImpl::GetMapValueType() const { + OrtTypeInfo* output; + ThrowOnError(GetApi().GetMapValueType(this->p_, &output)); + return TypeInfo{output}; +} + +template +inline ConstOptionalTypeInfo TypeInfoImpl::GetOptionalTypeInfo() const { + const OrtOptionalTypeInfo* info; + ThrowOnError(GetApi().CastTypeInfoToOptionalTypeInfo(this->p_, &info)); + return ConstOptionalTypeInfo{info}; +} + +} // namespace detail + +namespace detail { + +template +template +inline void ConstValueImpl::GetOpaqueData(const char* domain, const char* type_name, R& out) const { + ThrowOnError(GetApi().GetOpaqueValue(domain, type_name, this->p_, &out, sizeof(R))); +} + +template +inline bool ConstValueImpl::IsTensor() const { + int out; + ThrowOnError(GetApi().IsTensor(this->p_, &out)); + return out != 0; +} + +template +inline bool ConstValueImpl::HasValue() const { + int out; + ThrowOnError(GetApi().HasValue(this->p_, &out)); + return out != 0; +} + +template +inline size_t ConstValueImpl::GetCount() const { + size_t out; + ThrowOnError(GetApi().GetValueCount(this->p_, &out)); + return out; +} + +template +inline Value ConstValueImpl::GetValue(int index, OrtAllocator* allocator) const { + OrtValue* out; + ThrowOnError(GetApi().GetValue(this->p_, index, allocator, &out)); + return Value{out}; +} + +template +inline size_t ConstValueImpl::GetStringTensorDataLength() const { + size_t out; + ThrowOnError(GetApi().GetStringTensorDataLength(this->p_, &out)); + return out; +} + +template +inline size_t ConstValueImpl::GetStringTensorElementLength(size_t element_index) const { + size_t out; + ThrowOnError(GetApi().GetStringTensorElementLength(this->p_, element_index, &out)); + return out; +} + +template +template +inline const R* ConstValueImpl::GetTensorData() const { + R* out; + ThrowOnError(GetApi().GetTensorMutableData(const_cast(this->p_), (void**)&out)); + return out; +} + +template +inline const void* ConstValueImpl::GetTensorRawData() const { + void* out; + ThrowOnError(GetApi().GetTensorMutableData(const_cast(this->p_), &out)); + return out; +} + +template +inline TypeInfo ConstValueImpl::GetTypeInfo() const { + OrtTypeInfo* output; + ThrowOnError(GetApi().GetTypeInfo(this->p_, &output)); + return TypeInfo{output}; +} + +template +inline TensorTypeAndShapeInfo ConstValueImpl::GetTensorTypeAndShapeInfo() const { + OrtTensorTypeAndShapeInfo* output; + ThrowOnError(GetApi().GetTensorTypeAndShape(this->p_, &output)); + return TensorTypeAndShapeInfo{output}; +} + +template +inline ConstMemoryInfo ConstValueImpl::GetTensorMemoryInfo() const { + const OrtMemoryInfo* mem_info; + ThrowOnError(GetApi().GetTensorMemoryInfo(this->p_, &mem_info)); + return ConstMemoryInfo(mem_info); +} + +template +inline void ConstValueImpl::GetStringTensorElement(size_t buffer_length, size_t element_index, void* buffer) const { + ThrowOnError(GetApi().GetStringTensorElement(this->p_, buffer_length, element_index, buffer)); +} + +template +inline std::string ConstValueImpl::GetStringTensorElement(size_t element_index) const { + size_t buffer_length; + ThrowOnError(GetApi().GetStringTensorElementLength(this->p_, element_index, &buffer_length)); + + std::string s; + s.resize(buffer_length); + ThrowOnError(GetApi().GetStringTensorElement(this->p_, buffer_length, element_index, &s[0])); + return s; +} + +template +inline void ConstValueImpl::GetStringTensorContent(void* buffer, size_t buffer_length, size_t* offsets, size_t offsets_count) const { + ThrowOnError(GetApi().GetStringTensorContent(this->p_, buffer, buffer_length, offsets, offsets_count)); +} + +#if !defined(DISABLE_SPARSE_TENSORS) +template +inline OrtSparseFormat ConstValueImpl::GetSparseFormat() const { + OrtSparseFormat format; + ThrowOnError(GetApi().GetSparseTensorFormat(this->p_, &format)); + return format; +} + +template +inline TensorTypeAndShapeInfo ConstValueImpl::GetSparseTensorValuesTypeAndShapeInfo() const { + OrtTensorTypeAndShapeInfo* output; + ThrowOnError(GetApi().GetSparseTensorValuesTypeAndShape(this->p_, &output)); + return TensorTypeAndShapeInfo{output}; +} + +template +inline TensorTypeAndShapeInfo ConstValueImpl::GetSparseTensorIndicesTypeShapeInfo(OrtSparseIndicesFormat indices_format) const { + OrtTensorTypeAndShapeInfo* output; + ThrowOnError(GetApi().GetSparseTensorIndicesTypeShape(this->p_, indices_format, &output)); + return TensorTypeAndShapeInfo{output}; +} + +template +template +inline const R* ConstValueImpl::GetSparseTensorIndicesData(OrtSparseIndicesFormat indices_format, size_t& num_indices) const { + const void* out; + ThrowOnError(GetApi().GetSparseTensorIndices(this->p_, indices_format, &num_indices, &out)); + return reinterpret_cast(out); +} + +template +inline bool ConstValueImpl::IsSparseTensor() const { + int out; + ThrowOnError(GetApi().IsSparseTensor(this->p_, &out)); + return out != 0; +} + +template +template +inline const R* ConstValueImpl::GetSparseTensorValues() const { + const void* out; + ThrowOnError(GetApi().GetSparseTensorValues(this->p_, &out)); + return reinterpret_cast(out); +} + +#endif + +template +void ValueImpl::FillStringTensor(const char* const* s, size_t s_len) { + ThrowOnError(GetApi().FillStringTensor(this->p_, s, s_len)); +} + +template +void ValueImpl::FillStringTensorElement(const char* s, size_t index) { + ThrowOnError(GetApi().FillStringTensorElement(this->p_, s, index)); +} + +template +inline char* ValueImpl::GetResizedStringTensorElementBuffer(size_t index, size_t buffer_length) { + char* result; + ThrowOnError(GetApi().GetResizedStringTensorElementBuffer(this->p_, index, buffer_length, &result)); + return result; +} + +template +void* ValueImpl::GetTensorMutableRawData() { + void* out; + ThrowOnError(GetApi().GetTensorMutableData(this->p_, &out)); + return out; +} + +template +template +R* ValueImpl::GetTensorMutableData() { + R* out; + ThrowOnError(GetApi().GetTensorMutableData(this->p_, (void**)&out)); + return out; +} + +template +template +R& ValueImpl::At(const std::vector& location) { + static_assert(!std::is_same::value, "this api does not support std::string"); + R* out; + ThrowOnError(GetApi().TensorAt(this->p_, location.data(), location.size(), (void**)&out)); + return *out; +} + +#if !defined(DISABLE_SPARSE_TENSORS) +template +void ValueImpl::UseCooIndices(int64_t* indices_data, size_t indices_num) { + ThrowOnError(GetApi().UseCooIndices(this->p_, indices_data, indices_num)); +} + +template +void ValueImpl::UseCsrIndices(int64_t* inner_data, size_t inner_num, int64_t* outer_data, size_t outer_num) { + ThrowOnError(GetApi().UseCsrIndices(this->p_, inner_data, inner_num, outer_data, outer_num)); +} + +template +void ValueImpl::UseBlockSparseIndices(const Shape& indices_shape, int32_t* indices_data) { + ThrowOnError(GetApi().UseBlockSparseIndices(this->p_, indices_shape.shape, indices_shape.shape_len, indices_data)); +} + +template +void ValueImpl::FillSparseTensorCoo(const OrtMemoryInfo* mem_info, const OrtSparseValuesParam& values_param, + const int64_t* indices_data, size_t indices_num) { + ThrowOnError(GetApi().FillSparseTensorCoo(this->p_, mem_info, values_param.values_shape, + values_param.values_shape_len, values_param.data.p_data, + indices_data, indices_num)); +} + +template +void ValueImpl::FillSparseTensorCsr(const OrtMemoryInfo* data_mem_info, + const OrtSparseValuesParam& values, + const int64_t* inner_indices_data, size_t inner_indices_num, + const int64_t* outer_indices_data, size_t outer_indices_num) { + ThrowOnError(GetApi().FillSparseTensorCsr(this->p_, data_mem_info, values.values_shape, values.values_shape_len, values.data.p_data, + inner_indices_data, inner_indices_num, + outer_indices_data, outer_indices_num)); +} + +template +void ValueImpl::FillSparseTensorBlockSparse(const OrtMemoryInfo* data_mem_info, + const OrtSparseValuesParam& values, + const Shape& indices_shape, + const int32_t* indices_data) { + ThrowOnError(GetApi().FillSparseTensorBlockSparse(this->p_, data_mem_info, values.values_shape, values.values_shape_len, values.data.p_data, + indices_shape.shape, indices_shape.shape_len, + indices_data)); +} + +#endif // !defined(DISABLE_SPARSE_TENSORS) + +} // namespace detail + +template +inline Value Value::CreateTensor(const OrtMemoryInfo* info, T* p_data, size_t p_data_element_count, + const int64_t* shape, size_t shape_len) { + return CreateTensor(info, p_data, p_data_element_count * sizeof(T), shape, shape_len, TypeToTensorType::type); +} + +inline Value Value::CreateTensor(const OrtMemoryInfo* info, void* p_data, size_t p_data_byte_count, + const int64_t* shape, size_t shape_len, + ONNXTensorElementDataType type) { + OrtValue* out; + ThrowOnError(GetApi().CreateTensorWithDataAsOrtValue(info, p_data, p_data_byte_count, shape, shape_len, type, &out)); + return Value{out}; +} + +inline Value Value::CreateTensor(OrtAllocator* deleter, void* p_data, size_t p_data_byte_count, + const int64_t* shape, size_t shape_len, + ONNXTensorElementDataType type) { + OrtValue* out; + ThrowOnError(GetApi().CreateTensorWithDataAndDeleterAsOrtValue(deleter, p_data, p_data_byte_count, + shape, shape_len, type, &out)); + return Value{out}; +} + +template +inline Value Value::CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len) { + return CreateTensor(allocator, shape, shape_len, TypeToTensorType::type); +} + +inline Value Value::CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len, + ONNXTensorElementDataType type) { + OrtValue* out; + ThrowOnError(GetApi().CreateTensorAsOrtValue(allocator, shape, shape_len, type, &out)); + return Value{out}; +} + +#if !defined(DISABLE_SPARSE_TENSORS) + +template +inline Value Value::CreateSparseTensor(const OrtMemoryInfo* info, T* p_data, const Shape& dense_shape, + const Shape& values_shape) { + return CreateSparseTensor(info, p_data, dense_shape, values_shape, TypeToTensorType::type); +} + +inline Value Value::CreateSparseTensor(const OrtMemoryInfo* info, void* p_data, const Shape& dense_shape, + const Shape& values_shape, ONNXTensorElementDataType type) { + OrtValue* out; + ThrowOnError(GetApi().CreateSparseTensorWithValuesAsOrtValue(info, p_data, dense_shape.shape, dense_shape.shape_len, + values_shape.shape, values_shape.shape_len, type, + &out)); + return Value{out}; +} + +template +inline Value Value::CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape) { + return CreateSparseTensor(allocator, dense_shape, TypeToTensorType::type); +} + +inline Value Value::CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape, + ONNXTensorElementDataType type) { + OrtValue* out; + ThrowOnError(GetApi().CreateSparseTensorAsOrtValue(allocator, dense_shape.shape, dense_shape.shape_len, type, &out)); + return Value{out}; +} +#endif // !defined(DISABLE_SPARSE_TENSORS) + +inline Value Value::CreateMap(const Value& keys, const Value& values) { + OrtValue* out; + const OrtValue* inputs[2] = {keys, values}; + ThrowOnError(GetApi().CreateValue(inputs, 2, ONNX_TYPE_MAP, &out)); + return Value{out}; +} + +inline Value Value::CreateSequence(const std::vector& values) { + OrtValue* out; + std::vector values_ort{values.data(), values.data() + values.size()}; + ThrowOnError(GetApi().CreateValue(values_ort.data(), values_ort.size(), ONNX_TYPE_SEQUENCE, &out)); + return Value{out}; +} + +template +inline Value Value::CreateOpaque(const char* domain, const char* type_name, const T& data_container) { + OrtValue* out; + ThrowOnError(GetApi().CreateOpaqueValue(domain, type_name, &data_container, sizeof(T), &out)); + return Value{out}; +} + +// +// Custom OP Inlines +// +inline Logger::Logger(const OrtLogger* logger) : logger_(logger) { + Ort::ThrowOnError(GetApi().Logger_GetLoggingSeverityLevel(this->logger_, &this->cached_severity_level_)); +} + +inline OrtLoggingLevel Logger::GetLoggingSeverityLevel() const noexcept { + return cached_severity_level_; +} + +inline Status Logger::LogMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path, int line_number, + const char* func_name, const char* message) const noexcept { + OrtStatus* status = GetApi().Logger_LogMessage(logger_, log_severity_level, message, file_path, line_number, + func_name); + return Status{status}; +} + +// Disable warnings about the format string not being a literal (-Wformat-nonliteral and -Wformat-security) +// for gcc and clang. The alternative is to use actual C-style variadic parameters and apply +// __attribute__(format(printf...)), which does not work with variadic templates. +#if defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wformat-nonliteral" +#pragma GCC diagnostic ignored "-Wformat-security" +#elif defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wformat-nonliteral" +#pragma clang diagnostic ignored "-Wformat-security" +#endif +template +inline Status Logger::LogFormattedMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path, + int line_number, const char* func_name, const char* format, + Args&&... args) const noexcept { + int msg_len = std::snprintf(nullptr, 0U, format, std::forward(args)...); + + if (msg_len < 0) { // Formatting error + return Status("Failed to log message due to formatting error", OrtErrorCode::ORT_FAIL); + } + + OrtStatus* status = nullptr; + const size_t buffer_size = static_cast(msg_len) + 1U; + + constexpr size_t kStackBufferSize = 1024; + + if (buffer_size < kStackBufferSize) { + char buffer[kStackBufferSize]; + snprintf(buffer, kStackBufferSize, format, std::forward(args)...); + status = GetApi().Logger_LogMessage(logger_, log_severity_level, buffer, file_path, line_number, func_name); + } else { + // std::make_unique is only supported starting at C++14. +#if (__cplusplus >= 201402L) || (_MSC_VER >= 1900) + auto buffer = std::make_unique(buffer_size); +#else + std::unique_ptr buffer(new char[buffer_size]); +#endif + std::snprintf(buffer.get(), buffer_size, format, std::forward(args)...); + status = GetApi().Logger_LogMessage(logger_, log_severity_level, buffer.get(), file_path, line_number, func_name); + } + + return Status{status}; +} +// Re-enable -Wformat-nonliteral and -Wformat-security +#if defined(__GNUC__) +#pragma GCC diagnostic pop +#elif defined(__clang__) +#pragma clang diagnostic pop +#endif + +inline KernelContext::KernelContext(OrtKernelContext* context) : ctx_(context) { +} + +inline size_t KernelContext::GetInputCount() const { + size_t out = 0; + Ort::ThrowOnError(GetApi().KernelContext_GetInputCount(ctx_, &out)); + return out; +} + +inline size_t KernelContext::GetOutputCount() const { + size_t out = 0; + Ort::ThrowOnError(GetApi().KernelContext_GetOutputCount(ctx_, &out)); + return out; +} + +inline ConstValue KernelContext::GetInput(size_t index) const { + const OrtValue* out = nullptr; + Ort::ThrowOnError(GetApi().KernelContext_GetInput(ctx_, index, &out)); + return ConstValue{out}; +} + +inline UnownedValue KernelContext::GetOutput(size_t index, const int64_t* dim_values, size_t dim_count) const { + OrtValue* out = nullptr; + Ort::ThrowOnError(GetApi().KernelContext_GetOutput(ctx_, index, dim_values, dim_count, &out)); + return UnownedValue(out); +} + +inline UnownedValue KernelContext::GetOutput(size_t index, const std::vector& dims) const { + OrtValue* out = nullptr; + Ort::ThrowOnError(GetApi().KernelContext_GetOutput(ctx_, index, dims.data(), dims.size(), &out)); + return UnownedValue(out); +} + +inline void* KernelContext::GetGPUComputeStream() const { + void* out = nullptr; + Ort::ThrowOnError(GetApi().KernelContext_GetGPUComputeStream(ctx_, &out)); + return out; +} + +inline OrtAllocator* KernelContext::GetAllocator(const OrtMemoryInfo& memory_info) const { + OrtAllocator* out = nullptr; + Ort::ThrowOnError(GetApi().KernelContext_GetAllocator(ctx_, &memory_info, &out)); + return out; +} + +inline Logger KernelContext::GetLogger() const { + const OrtLogger* out = nullptr; + ThrowOnError(GetApi().KernelContext_GetLogger(this->ctx_, &out)); + return Logger{out}; +} + +inline void KernelContext::ParallelFor(void (*fn)(void*, size_t), size_t total, size_t num_batch, void* usr_data) const { + ThrowOnError(GetApi().KernelContext_ParallelFor(ctx_, fn, total, num_batch, usr_data)); +} + +inline OpAttr::OpAttr(const char* name, const void* data, int len, OrtOpAttrType type) { + Ort::ThrowOnError(GetApi().CreateOpAttr(name, data, len, type, &p_)); +} + +namespace detail { +template +inline KernelInfo KernelInfoImpl::Copy() const { + OrtKernelInfo* info_copy = nullptr; + Ort::ThrowOnError(GetApi().CopyKernelInfo(this->p_, &info_copy)); + return KernelInfo{info_copy}; +} + +template +inline size_t KernelInfoImpl::GetInputCount() const { + size_t out = 0; + ThrowOnError(GetApi().KernelInfo_GetInputCount(this->p_, &out)); + return out; +} + +template +inline size_t KernelInfoImpl::GetOutputCount() const { + size_t out = 0; + ThrowOnError(GetApi().KernelInfo_GetOutputCount(this->p_, &out)); + return out; +} + +template +inline std::string KernelInfoImpl::GetInputName(size_t index) const { + size_t size = 0; + + // Feed nullptr for the data buffer to query the true size of the string value + Ort::ThrowOnError(GetApi().KernelInfo_GetInputName(this->p_, index, nullptr, &size)); + + std::string out; + out.resize(size); + Ort::ThrowOnError(GetApi().KernelInfo_GetInputName(this->p_, index, &out[0], &size)); + out.resize(size - 1); // remove the terminating character '\0' + + return out; +} + +template +inline std::string KernelInfoImpl::GetOutputName(size_t index) const { + size_t size = 0; + + // Feed nullptr for the data buffer to query the true size of the string value + Ort::ThrowOnError(GetApi().KernelInfo_GetOutputName(this->p_, index, nullptr, &size)); + + std::string out; + out.resize(size); + Ort::ThrowOnError(GetApi().KernelInfo_GetOutputName(this->p_, index, &out[0], &size)); + out.resize(size - 1); // remove the terminating character '\0' + + return out; +} + +template +inline TypeInfo KernelInfoImpl::GetInputTypeInfo(size_t index) const { + OrtTypeInfo* out = nullptr; + ThrowOnError(GetApi().KernelInfo_GetInputTypeInfo(this->p_, index, &out)); + return TypeInfo{out}; +} + +template +inline TypeInfo KernelInfoImpl::GetOutputTypeInfo(size_t index) const { + OrtTypeInfo* out = nullptr; + ThrowOnError(GetApi().KernelInfo_GetOutputTypeInfo(this->p_, index, &out)); + return TypeInfo{out}; +} + +template +inline Value KernelInfoImpl::GetTensorAttribute(const char* name, OrtAllocator* allocator) const { + OrtValue* out = nullptr; + ThrowOnError(GetApi().KernelInfoGetAttribute_tensor(this->p_, name, allocator, &out)); + return Value{out}; +} + +template +inline ConstValue KernelInfoImpl::GetTensorConstantInput(size_t index, int* is_constant) const { + const OrtValue* out = nullptr; + ThrowOnError(GetApi().KernelInfoGetConstantInput_tensor(this->p_, index, is_constant, &out)); + return ConstValue{out}; +} + +template +inline std::string KernelInfoImpl::GetNodeName() const { + size_t size = 0; + + // Feed nullptr for the data buffer to query the true size of the string value + Ort::ThrowOnError(GetApi().KernelInfo_GetNodeName(this->p_, nullptr, &size)); + + std::string out; + out.resize(size); + Ort::ThrowOnError(GetApi().KernelInfo_GetNodeName(this->p_, &out[0], &size)); + out.resize(size - 1); // remove the terminating character '\0' + + return out; +} + +template +inline Logger KernelInfoImpl::GetLogger() const { + const OrtLogger* out = nullptr; + ThrowOnError(GetApi().KernelInfo_GetLogger(this->p_, &out)); + return Logger{out}; +} + +inline void attr_utils::GetAttr(const OrtKernelInfo* p, const char* name, float& out) { + Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_float(p, name, &out)); +} + +inline void attr_utils::GetAttr(const OrtKernelInfo* p, const char* name, int64_t& out) { + Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_int64(p, name, &out)); +} + +inline void attr_utils::GetAttr(const OrtKernelInfo* p, const char* name, std::string& result) { + size_t size = 0; + // Feed nullptr for the data buffer to query the true size of the string attribute + Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_string(p, name, nullptr, &size)); + + std::string out; + out.resize(size); + Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_string(p, name, &out[0], &size)); + out.resize(size - 1); // remove the terminating character '\0' + out.swap(result); +} + +inline void attr_utils::GetAttrs(const OrtKernelInfo* p, const char* name, std::vector& result) { + size_t size = 0; + // Feed nullptr for the data buffer to query the true size of the attribute + Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_float(p, name, nullptr, &size)); + + std::vector out; + out.resize(size); + Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_float(p, name, out.data(), &size)); + out.swap(result); +} + +inline void attr_utils::GetAttrs(const OrtKernelInfo* p, const char* name, std::vector& result) { + size_t size = 0; + + // Feed nullptr for the data buffer to query the true size of the attribute + Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_int64(p, name, nullptr, &size)); + + std::vector out; + out.resize(size); + Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_int64(p, name, out.data(), &size)); + out.swap(result); +} +} // namespace detail + +inline KernelInfo::KernelInfo(OrtKernelInfo* info) : detail::KernelInfoImpl{info} {} + +inline Op::Op(OrtOp* p) : detail::Base(p) {} + +inline Op Op::Create(const OrtKernelInfo* info, const char* op_name, const char* domain, int version, + const char** type_constraint_names, + const ONNXTensorElementDataType* type_constraint_values, + size_t type_constraint_count, + const OpAttr* attr_values, size_t attr_count, + size_t input_count, size_t output_count) { + static_assert(sizeof(OpAttr) == sizeof(OrtOpAttr*), + "OpAttr's is expected to be just an array of OrtOpAttr in memory so we can reinterpret safely"); + auto attr_input_values = reinterpret_cast(attr_values); + OrtOp* op; + Ort::ThrowOnError(GetApi().CreateOp(info, op_name, domain, version, type_constraint_names, type_constraint_values, + static_cast(type_constraint_count), + attr_input_values, + static_cast(attr_count), + static_cast(input_count), + static_cast(output_count), &op)); + return Op{op}; +} + +inline void Op::Invoke(const OrtKernelContext* context, + const Value* input_values, + size_t input_count, + Value* output_values, + size_t output_count) { + static_assert(sizeof(Value) == sizeof(OrtValue*), + "Value is really just an array of OrtValue* in memory, so we can reinterpret_cast safely"); + auto ort_input_values = reinterpret_cast(input_values); + auto ort_output_values = reinterpret_cast(output_values); + Ort::ThrowOnError(GetApi().InvokeOp(context, p_, ort_input_values, static_cast(input_count), + ort_output_values, static_cast(output_count))); +} + +inline void Op::Invoke(const OrtKernelContext* context, + const OrtValue* const* input_values, + size_t input_count, + OrtValue* const* output_values, + size_t output_count) { + Ort::ThrowOnError(GetApi().InvokeOp(context, p_, input_values, static_cast(input_count), + output_values, static_cast(output_count))); +} + +inline std::string GetVersionString() { + return OrtGetApiBase()->GetVersionString(); +} + +inline std::string GetBuildInfoString() { + return GetApi().GetBuildInfoString(); +} + +inline std::vector GetAvailableProviders() { + char** providers; + int len; + + auto release_fn = [&len](char** providers) { + // This should always return nullptr. + ThrowOnError(GetApi().ReleaseAvailableProviders(providers, len)); + }; + + ThrowOnError(GetApi().GetAvailableProviders(&providers, &len)); + std::unique_ptr guard(providers, release_fn); + std::vector available_providers; + available_providers.reserve(static_cast(len)); + for (int i = 0; i < len; ++i) { + available_providers.emplace_back(providers[i]); + } + return available_providers; +} + +template +void CustomOpBase::GetSessionConfigs(std::unordered_map& out, + ConstSessionOptions options) const { + const TOp* derived = static_cast(this); + std::vector keys = derived->GetSessionConfigKeys(); + + out.reserve(keys.size()); + + std::string config_entry_key = detail::MakeCustomOpConfigEntryKey(derived->GetName(), ""); + const size_t prefix_size = config_entry_key.length(); + + for (const auto& key : keys) { + config_entry_key.resize(prefix_size); + config_entry_key.append(key); + out[key] = options.GetConfigEntryOrDefault(config_entry_key.c_str(), ""); + } +} + +inline ShapeInferContext::ShapeInferContext(const OrtApi* ort_api, + OrtShapeInferContext* ctx) : ort_api_(ort_api), ctx_(ctx) { + size_t input_count = 0; + Ort::ThrowOnError(ort_api_->ShapeInferContext_GetInputCount(ctx_, &input_count)); + for (size_t ith_input = 0; ith_input < input_count; ++ith_input) { + OrtTensorTypeAndShapeInfo* info{}; + Ort::ThrowOnError(ort_api_->ShapeInferContext_GetInputTypeShape(ctx, ith_input, &info)); + TensorTypeAndShapeInfo type_shape_info(info); + auto integer_shape = type_shape_info.GetShape(); + std::vector symbolic_shape(integer_shape.size(), {}); + if (!integer_shape.empty()) { + type_shape_info.GetSymbolicDimensions(&symbolic_shape[0], integer_shape.size()); + } + Shape shape; + for (size_t ith = 0; ith < integer_shape.size(); ++ith) { + if (symbolic_shape[ith] && std::string{symbolic_shape[ith]}.size() > 0) { + shape.emplace_back(symbolic_shape[ith]); + } else { + shape.emplace_back(integer_shape[ith]); + } + } + input_shapes_.push_back(std::move(shape)); + type_shape_info.release(); + } +} + +inline Status ShapeInferContext::SetOutputShape(size_t indice, const Shape& shape, ONNXTensorElementDataType type) { + OrtTensorTypeAndShapeInfo* info = {}; + ORT_CXX_RETURN_ON_API_FAIL(ort_api_->CreateTensorTypeAndShapeInfo(&info)); + ORT_CXX_RETURN_ON_API_FAIL(ort_api_->SetTensorElementType(info, type)); + + using InfoPtr = std::unique_ptr>; + + InfoPtr info_ptr(info, [this](OrtTensorTypeAndShapeInfo* obj) { + ort_api_->ReleaseTensorTypeAndShapeInfo(obj); + }); + + std::vector integer_dims; + std::vector symbolic_dims; + + for (const auto dim : shape) { + if (dim.IsInt()) { + integer_dims.push_back(dim.AsInt()); + symbolic_dims.push_back(""); + } else { + if (!dim.AsSym() || std::string{dim.AsSym()}.empty()) { + ORT_CXX_API_THROW("Symbolic dim must not be an empty string", ORT_INVALID_ARGUMENT); + } + integer_dims.push_back(SymbolicInteger::INVALID_INT_DIM); + symbolic_dims.push_back(dim.AsSym()); + } + } + + ORT_CXX_RETURN_ON_API_FAIL(ort_api_->SetDimensions(info, integer_dims.data(), integer_dims.size())); + ORT_CXX_RETURN_ON_API_FAIL(ort_api_->SetSymbolicDimensions(info, symbolic_dims.data(), symbolic_dims.size())); + ORT_CXX_RETURN_ON_API_FAIL(ort_api_->ShapeInferContext_SetOutputTypeShape(ctx_, indice, info)); + return Status{nullptr}; +} + +inline int64_t ShapeInferContext::GetAttrInt(const char* attr_name) { + const auto* attr = GetAttrHdl(attr_name); + int64_t i = {}; + size_t out = {}; + Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_INT, &i, sizeof(i), &out)); + return i; +} + +inline ShapeInferContext::Ints ShapeInferContext::GetAttrInts(const char* attr_name) { + const auto* attr = GetAttrHdl(attr_name); + int64_t i = {}; + size_t out = {}; + // first call to get the bytes needed + // 1. A status == nullptr means that ReadOpAttr was successful. A status != nullptr means failure. + // 2. The ReadOpAttr function should normally be called twice: once to get the needed buffer size (returns a status != nullptr), and a second time to actually read the ints (returns status == null on success). + // 3. This code tries a subtle optimization in the first call to ReadOpAttr. It passes in a buffer (&i) of size 1 just in case there is only 1 int. In this case, status == nullptr and we need to return {i}. + auto status = ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_INTS, &i, sizeof(i), &out); + if (status) { + size_t num_i = out / sizeof(int64_t); + ShapeInferContext::Ints ints(num_i, 0); + Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_INTS, ints.data(), out, &out)); + return ints; + } else { + if (out == 0u) { + return {}; + } + return {i}; + } +} + +inline float ShapeInferContext::GetAttrFloat(const char* attr_name) { + const auto* attr = GetAttrHdl(attr_name); + float f = {}; + size_t out = {}; + Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_FLOAT, &f, sizeof(f), &out)); + return f; +} + +inline ShapeInferContext::Floats ShapeInferContext::GetAttrFloats(const char* attr_name) { + const auto* attr = GetAttrHdl(attr_name); + float f = {}; + size_t out = {}; + // first call to get the bytes needed + // 1. A status == nullptr means that ReadOpAttr was successful. A status != nullptr means failure. + // 2. The ReadOpAttr function should normally be called twice: once to get the needed buffer size (returns a status != nullptr), and a second time to actually read the ints (returns status == null on success). + // 3. This code tries a subtle optimization in the first call to ReadOpAttr. It passes in a buffer (&i) of size 1 just in case there is only 1 int. In this case, status == nullptr and we need to return {i}. + auto status = ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_FLOATS, &f, sizeof(f), &out); + if (status) { + size_t num_f = out / sizeof(float); + ShapeInferContext::Floats floats(num_f, 0); + Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_FLOATS, floats.data(), out, &out)); + return floats; + } else { + if (out == 0u) { + return {}; + } + return {f}; + } +} + +inline std::string ShapeInferContext::GetAttrString(const char* attr_name) { + const auto* attr = GetAttrHdl(attr_name); + char c = {}; + size_t out = {}; + // first call to get the bytes needed + auto status = ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_STRING, &c, sizeof(char), &out); + if (status) { + std::vector chars(out, '\0'); + Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_STRING, chars.data(), out, &out)); + return {chars.data()}; + } else { + return {c}; + } +} + +inline ShapeInferContext::Strings ShapeInferContext::GetAttrStrings(const char* attr_name) { + const auto* attr = GetAttrHdl(attr_name); + char c = {}; + size_t out = {}; + // first call to get the bytes needed + // 1. A status == nullptr means that ReadOpAttr was successful. A status != nullptr means failure. + // 2. The ReadOpAttr function should normally be called twice: once to get the needed buffer size (returns a status != nullptr), and a second time to actually read the ints (returns status == null on success). + // 3. This code tries a subtle optimization in the first call to ReadOpAttr. It passes in a buffer (&i) of size 1 just in case there is only 1 int. In this case, status == nullptr and we need to return {i}. + auto status = ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_STRINGS, &c, sizeof(char), &out); + if (status) { + std::vector chars(out, '\0'); + Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_STRINGS, chars.data(), out, &out)); + ShapeInferContext::Strings strings; + char* char_st = chars.data(); + char* char_ed = char_st + out; + while (char_st < char_ed) { + strings.emplace_back(char_st); + while (*char_st != '\0') { + char_st++; + } + char_st++; + } + return strings; + } else { + if (out == 0u) { + return {}; + } + return {std::string{c}}; + } +} + +inline const OrtOpAttr* ShapeInferContext::GetAttrHdl(const char* attr_name) const { + const OrtOpAttr* attr_hdl = {}; + Ort::ThrowOnError(ort_api_->ShapeInferContext_GetAttribute(ctx_, attr_name, &attr_hdl)); + return attr_hdl; +} + +namespace detail { +inline std::vector StringsToCharPtrs(const std::vector& strings) { + std::vector ptrs; + ptrs.reserve(strings.size()); + std::transform(strings.begin(), strings.end(), std::back_inserter(ptrs), + [](const std::string& s) { return s.c_str(); }); + + return ptrs; +} +} // namespace detail + +#if !defined(ORT_MINIMAL_BUILD) +// static +inline void Node::Init(const std::string& operator_name, const std::string& operator_domain, + const std::string& node_name, + const std::vector& input_names, + const std::vector& output_names, + std::vector& attributes, + OrtNode*& node) { + auto inputs = detail::StringsToCharPtrs(input_names); + auto outputs = detail::StringsToCharPtrs(output_names); + + std::vector attributes_ptrs; + attributes_ptrs.reserve(attributes.size()); + std::transform(attributes.begin(), attributes.end(), std::back_inserter(attributes_ptrs), + [](OpAttr& attr) -> OrtOpAttr* { return attr; }); + + ThrowOnError(GetModelEditorApi().CreateNode(operator_name.c_str(), operator_domain.c_str(), node_name.c_str(), + inputs.data(), inputs.size(), + outputs.data(), outputs.size(), + attributes_ptrs.data(), attributes_ptrs.size(), + &node)); + + // Node now owns the attributes + std::for_each(attributes.begin(), attributes.end(), [](OpAttr& attr) { attr.release(); }); +} + +inline Node::Node(const std::string& operator_name, const std::string& operator_domain, + const std::string& node_name, + const std::vector& input_names, + const std::vector& output_names, + std::vector& attributes) { + Init(operator_name, operator_domain, node_name, input_names, output_names, attributes, p_); +} + +inline Node::Node(const std::string& operator_name, const std::string& operator_domain, + const std::string& node_name, + const std::vector& input_names, + const std::vector& output_names) { + std::vector empty_attributes; + Init(operator_name, operator_domain, node_name, input_names, output_names, empty_attributes, p_); +} + +inline Graph::Graph() { + ThrowOnError(GetModelEditorApi().CreateGraph(&p_)); +} + +inline Model::Model(const std::vector& opsets) { + std::vector domains; + std::vector versions; + domains.reserve(opsets.size()); + versions.reserve(opsets.size()); + + for (const auto& pair : opsets) { + domains.push_back(pair.first.c_str()); + versions.push_back(pair.second); + } + + ThrowOnError(GetModelEditorApi().CreateModel(domains.data(), versions.data(), opsets.size(), &p_)); +} + +inline ValueInfo::ValueInfo(const std::string& name, const ConstTypeInfo& type_info) { + ThrowOnError(GetModelEditorApi().CreateValueInfo(name.c_str(), type_info, &p_)); +} +#endif // !defined(ORT_MINIMAL_BUILD) + +namespace detail { +template <> +inline std::string ValueInfoImpl::Name() const { + const char* name = nullptr; + ThrowOnError(GetApi().GetValueInfoName(this->p_, &name)); + return name; +} + +template <> +inline ConstTypeInfo ValueInfoImpl::TypeInfo() const { + const OrtTypeInfo* type_info = nullptr; + ThrowOnError(GetApi().GetValueInfoTypeInfo(this->p_, &type_info)); + return ConstTypeInfo{type_info}; +} + +#if !defined(ORT_MINIMAL_BUILD) +template <> +inline void GraphImpl::SetInputs(std::vector& inputs) { + std::vector inputs_ptrs; + inputs_ptrs.reserve(inputs.size()); + std::transform(inputs.begin(), inputs.end(), std::back_inserter(inputs_ptrs), + [](ValueInfo& vi) -> OrtValueInfo* { return vi; }); + + ThrowOnError(GetModelEditorApi().SetGraphInputs(p_, inputs_ptrs.data(), inputs_ptrs.size())); + + // Graph now owns the inputs + std::for_each(inputs.begin(), inputs.end(), [](ValueInfo& vi) { vi.release(); }); +} + +template <> +inline void GraphImpl::SetOutputs(std::vector& outputs) { + std::vector outputs_ptrs; + outputs_ptrs.reserve(outputs.size()); + std::transform(outputs.begin(), outputs.end(), std::back_inserter(outputs_ptrs), + [](ValueInfo& vi) -> OrtValueInfo* { return vi; }); + + ThrowOnError(GetModelEditorApi().SetGraphOutputs(p_, outputs_ptrs.data(), outputs_ptrs.size())); + + // Graph now owns the outputs + std::for_each(outputs.begin(), outputs.end(), [](ValueInfo& vi) { vi.release(); }); +} + +template <> +inline void GraphImpl::AddInitializer(const std::string& name, Value& initializer, bool data_is_external) { + // Graph takes ownership of `initializer` + ThrowOnError(GetModelEditorApi().AddInitializerToGraph(p_, name.c_str(), initializer.release(), data_is_external)); +} + +template <> +inline void GraphImpl::AddNode(Node& node) { + // Graph takes ownership of `node` + ThrowOnError(GetModelEditorApi().AddNodeToGraph(p_, node.release())); +} + +template <> +inline void ModelImpl::AddGraph(Graph& graph) { + // Model takes ownership of `graph` + ThrowOnError(GetModelEditorApi().AddGraphToModel(p_, graph.release())); +} +#endif // !defined(ORT_MINIMAL_BUILD) + +} // namespace detail +} // namespace Ort diff --git a/3rdParty/ONNX/onnxruntime_float16.h b/3rdParty/ONNX/onnxruntime_float16.h index 408d3ccfb2..a6923ddd43 100644 --- a/3rdParty/ONNX/onnxruntime_float16.h +++ b/3rdParty/ONNX/onnxruntime_float16.h @@ -1,535 +1,535 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include -#include -#include -#include - -namespace onnxruntime_float16 { - -namespace detail { - -enum class endian { -#if defined(_WIN32) - little = 0, - big = 1, - native = little, -#elif defined(__GNUC__) || defined(__clang__) - little = __ORDER_LITTLE_ENDIAN__, - big = __ORDER_BIG_ENDIAN__, - native = __BYTE_ORDER__, -#else -#error onnxruntime_float16::detail::endian is not implemented in this environment. -#endif -}; - -static_assert( - endian::native == endian::little || endian::native == endian::big, - "Only little-endian or big-endian native byte orders are supported."); - -} // namespace detail - -/// -/// Shared implementation between public and internal classes. CRTP pattern. -/// -template -struct Float16Impl { - protected: - /// - /// Converts from float to uint16_t float16 representation - /// - /// - /// - constexpr static uint16_t ToUint16Impl(float v) noexcept; - - /// - /// Converts float16 to float - /// - /// float representation of float16 value - float ToFloatImpl() const noexcept; - - /// - /// Creates an instance that represents absolute value. - /// - /// Absolute value - uint16_t AbsImpl() const noexcept { - return static_cast(val & ~kSignMask); - } - - /// - /// Creates a new instance with the sign flipped. - /// - /// Flipped sign instance - uint16_t NegateImpl() const noexcept { - return IsNaN() ? val : static_cast(val ^ kSignMask); - } - - public: - // uint16_t special values - static constexpr uint16_t kSignMask = 0x8000U; - static constexpr uint16_t kBiasedExponentMask = 0x7C00U; - static constexpr uint16_t kPositiveInfinityBits = 0x7C00U; - static constexpr uint16_t kNegativeInfinityBits = 0xFC00U; - static constexpr uint16_t kPositiveQNaNBits = 0x7E00U; - static constexpr uint16_t kNegativeQNaNBits = 0xFE00U; - static constexpr uint16_t kMaxValueBits = 0x7BFFU; // Largest normal number - static constexpr uint16_t kOneBits = 0x3C00U; - static constexpr uint16_t kMinusOneBits = 0xBC00U; - - uint16_t val{0}; - - Float16Impl() = default; - - /// - /// Checks if the value is negative - /// - /// true if negative - bool IsNegative() const noexcept { - return static_cast(val) < 0; - } - - /// - /// Tests if the value is NaN - /// - /// true if NaN - bool IsNaN() const noexcept { - return AbsImpl() > kPositiveInfinityBits; - } - - /// - /// Tests if the value is finite - /// - /// true if finite - bool IsFinite() const noexcept { - return AbsImpl() < kPositiveInfinityBits; - } - - /// - /// Tests if the value represents positive infinity. - /// - /// true if positive infinity - bool IsPositiveInfinity() const noexcept { - return val == kPositiveInfinityBits; - } - - /// - /// Tests if the value represents negative infinity - /// - /// true if negative infinity - bool IsNegativeInfinity() const noexcept { - return val == kNegativeInfinityBits; - } - - /// - /// Tests if the value is either positive or negative infinity. - /// - /// True if absolute value is infinity - bool IsInfinity() const noexcept { - return AbsImpl() == kPositiveInfinityBits; - } - - /// - /// Tests if the value is NaN or zero. Useful for comparisons. - /// - /// True if NaN or zero. - bool IsNaNOrZero() const noexcept { - auto abs = AbsImpl(); - return (abs == 0 || abs > kPositiveInfinityBits); - } - - /// - /// Tests if the value is normal (not zero, subnormal, infinite, or NaN). - /// - /// True if so - bool IsNormal() const noexcept { - auto abs = AbsImpl(); - return (abs < kPositiveInfinityBits) // is finite - && (abs != 0) // is not zero - && ((abs & kBiasedExponentMask) != 0); // is not subnormal (has a non-zero exponent) - } - - /// - /// Tests if the value is subnormal (denormal). - /// - /// True if so - bool IsSubnormal() const noexcept { - auto abs = AbsImpl(); - return (abs < kPositiveInfinityBits) // is finite - && (abs != 0) // is not zero - && ((abs & kBiasedExponentMask) == 0); // is subnormal (has a zero exponent) - } - - /// - /// Creates an instance that represents absolute value. - /// - /// Absolute value - Derived Abs() const noexcept { return Derived::FromBits(AbsImpl()); } - - /// - /// Creates a new instance with the sign flipped. - /// - /// Flipped sign instance - Derived Negate() const noexcept { return Derived::FromBits(NegateImpl()); } - - /// - /// IEEE defines that positive and negative zero are equal, this gives us a quick equality check - /// for two values by or'ing the private bits together and stripping the sign. They are both zero, - /// and therefore equivalent, if the resulting value is still zero. - /// - /// first value - /// second value - /// True if both arguments represent zero - static bool AreZero(const Float16Impl& lhs, const Float16Impl& rhs) noexcept { - return static_cast((lhs.val | rhs.val) & ~kSignMask) == 0; - } - - bool operator==(const Float16Impl& rhs) const noexcept { - if (IsNaN() || rhs.IsNaN()) { - // IEEE defines that NaN is not equal to anything, including itself. - return false; - } - return val == rhs.val; - } - - bool operator!=(const Float16Impl& rhs) const noexcept { return !(*this == rhs); } - - bool operator<(const Float16Impl& rhs) const noexcept { - if (IsNaN() || rhs.IsNaN()) { - // IEEE defines that NaN is unordered with respect to everything, including itself. - return false; - } - - const bool left_is_negative = IsNegative(); - if (left_is_negative != rhs.IsNegative()) { - // When the signs of left and right differ, we know that left is less than right if it is - // the negative value. The exception to this is if both values are zero, in which case IEEE - // says they should be equal, even if the signs differ. - return left_is_negative && !AreZero(*this, rhs); - } - return (val != rhs.val) && ((val < rhs.val) ^ left_is_negative); - } -}; - -// The following Float16_t conversions are based on the code from -// Eigen library. - -// The conversion routines are Copyright (c) Fabian Giesen, 2016. -// The original license follows: -// -// Copyright (c) Fabian Giesen, 2016 -// All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted. -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT -// HOLDER 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. - -namespace detail { -union float32_bits { - unsigned int u; - float f; -}; -} // namespace detail - -template -inline constexpr uint16_t Float16Impl::ToUint16Impl(float v) noexcept { - detail::float32_bits f{}; - f.f = v; - - constexpr detail::float32_bits f32infty = {255 << 23}; - constexpr detail::float32_bits f16max = {(127 + 16) << 23}; - constexpr detail::float32_bits denorm_magic = {((127 - 15) + (23 - 10) + 1) << 23}; - constexpr unsigned int sign_mask = 0x80000000u; - uint16_t val = static_cast(0x0u); - - unsigned int sign = f.u & sign_mask; - f.u ^= sign; - - // NOTE all the integer compares in this function can be safely - // compiled into signed compares since all operands are below - // 0x80000000. Important if you want fast straight SSE2 code - // (since there's no unsigned PCMPGTD). - - if (f.u >= f16max.u) { // result is Inf or NaN (all exponent bits set) - val = (f.u > f32infty.u) ? 0x7e00 : 0x7c00; // NaN->qNaN and Inf->Inf - } else { // (De)normalized number or zero - if (f.u < (113 << 23)) { // resulting FP16 is subnormal or zero - // use a magic value to align our 10 mantissa bits at the bottom of - // the float. as long as FP addition is round-to-nearest-even this - // just works. - f.f += denorm_magic.f; - - // and one integer subtract of the bias later, we have our final float! - val = static_cast(f.u - denorm_magic.u); - } else { - unsigned int mant_odd = (f.u >> 13) & 1; // resulting mantissa is odd - - // update exponent, rounding bias part 1 - // Equivalent to `f.u += ((unsigned int)(15 - 127) << 23) + 0xfff`, but - // without arithmetic overflow. - f.u += 0xc8000fffU; - // rounding bias part 2 - f.u += mant_odd; - // take the bits! - val = static_cast(f.u >> 13); - } - } - - val |= static_cast(sign >> 16); - return val; -} - -template -inline float Float16Impl::ToFloatImpl() const noexcept { - constexpr detail::float32_bits magic = {113 << 23}; - constexpr unsigned int shifted_exp = 0x7c00 << 13; // exponent mask after shift - detail::float32_bits o{}; - - o.u = (val & 0x7fff) << 13; // exponent/mantissa bits - unsigned int exp = shifted_exp & o.u; // just the exponent - o.u += (127 - 15) << 23; // exponent adjust - - // handle exponent special cases - if (exp == shifted_exp) { // Inf/NaN? - o.u += (128 - 16) << 23; // extra exp adjust - } else if (exp == 0) { // Zero/Denormal? - o.u += 1 << 23; // extra exp adjust - o.f -= magic.f; // re-normalize - } - - // Attempt to workaround the Internal Compiler Error on ARM64 - // for bitwise | operator, including std::bitset -#if (defined _MSC_VER) && (defined _M_ARM || defined _M_ARM64 || defined _M_ARM64EC) - if (IsNegative()) { - return -o.f; - } -#else - // original code: - o.u |= (val & 0x8000U) << 16U; // sign bit -#endif - return o.f; -} - -/// Shared implementation between public and internal classes. CRTP pattern. -template -struct BFloat16Impl { - protected: - /// - /// Converts from float to uint16_t float16 representation - /// - /// - /// - static uint16_t ToUint16Impl(float v) noexcept; - - /// - /// Converts bfloat16 to float - /// - /// float representation of bfloat16 value - float ToFloatImpl() const noexcept; - - /// - /// Creates an instance that represents absolute value. - /// - /// Absolute value - uint16_t AbsImpl() const noexcept { - return static_cast(val & ~kSignMask); - } - - /// - /// Creates a new instance with the sign flipped. - /// - /// Flipped sign instance - uint16_t NegateImpl() const noexcept { - return IsNaN() ? val : static_cast(val ^ kSignMask); - } - - public: - // uint16_t special values - static constexpr uint16_t kSignMask = 0x8000U; - static constexpr uint16_t kBiasedExponentMask = 0x7F80U; - static constexpr uint16_t kPositiveInfinityBits = 0x7F80U; - static constexpr uint16_t kNegativeInfinityBits = 0xFF80U; - static constexpr uint16_t kPositiveQNaNBits = 0x7FC1U; - static constexpr uint16_t kNegativeQNaNBits = 0xFFC1U; - static constexpr uint16_t kMaxValueBits = 0x7F7FU; - static constexpr uint16_t kRoundToNearest = 0x7FFFU; - static constexpr uint16_t kOneBits = 0x3F80U; - static constexpr uint16_t kMinusOneBits = 0xBF80U; - - uint16_t val{0}; - - BFloat16Impl() = default; - - /// - /// Checks if the value is negative - /// - /// true if negative - bool IsNegative() const noexcept { - return static_cast(val) < 0; - } - - /// - /// Tests if the value is NaN - /// - /// true if NaN - bool IsNaN() const noexcept { - return AbsImpl() > kPositiveInfinityBits; - } - - /// - /// Tests if the value is finite - /// - /// true if finite - bool IsFinite() const noexcept { - return AbsImpl() < kPositiveInfinityBits; - } - - /// - /// Tests if the value represents positive infinity. - /// - /// true if positive infinity - bool IsPositiveInfinity() const noexcept { - return val == kPositiveInfinityBits; - } - - /// - /// Tests if the value represents negative infinity - /// - /// true if negative infinity - bool IsNegativeInfinity() const noexcept { - return val == kNegativeInfinityBits; - } - - /// - /// Tests if the value is either positive or negative infinity. - /// - /// True if absolute value is infinity - bool IsInfinity() const noexcept { - return AbsImpl() == kPositiveInfinityBits; - } - - /// - /// Tests if the value is NaN or zero. Useful for comparisons. - /// - /// True if NaN or zero. - bool IsNaNOrZero() const noexcept { - auto abs = AbsImpl(); - return (abs == 0 || abs > kPositiveInfinityBits); - } - - /// - /// Tests if the value is normal (not zero, subnormal, infinite, or NaN). - /// - /// True if so - bool IsNormal() const noexcept { - auto abs = AbsImpl(); - return (abs < kPositiveInfinityBits) // is finite - && (abs != 0) // is not zero - && ((abs & kBiasedExponentMask) != 0); // is not subnormal (has a non-zero exponent) - } - - /// - /// Tests if the value is subnormal (denormal). - /// - /// True if so - bool IsSubnormal() const noexcept { - auto abs = AbsImpl(); - return (abs < kPositiveInfinityBits) // is finite - && (abs != 0) // is not zero - && ((abs & kBiasedExponentMask) == 0); // is subnormal (has a zero exponent) - } - - /// - /// Creates an instance that represents absolute value. - /// - /// Absolute value - Derived Abs() const noexcept { return Derived::FromBits(AbsImpl()); } - - /// - /// Creates a new instance with the sign flipped. - /// - /// Flipped sign instance - Derived Negate() const noexcept { return Derived::FromBits(NegateImpl()); } - - /// - /// IEEE defines that positive and negative zero are equal, this gives us a quick equality check - /// for two values by or'ing the private bits together and stripping the sign. They are both zero, - /// and therefore equivalent, if the resulting value is still zero. - /// - /// first value - /// second value - /// True if both arguments represent zero - static bool AreZero(const BFloat16Impl& lhs, const BFloat16Impl& rhs) noexcept { - // IEEE defines that positive and negative zero are equal, this gives us a quick equality check - // for two values by or'ing the private bits together and stripping the sign. They are both zero, - // and therefore equivalent, if the resulting value is still zero. - return static_cast((lhs.val | rhs.val) & ~kSignMask) == 0; - } -}; - -template -inline uint16_t BFloat16Impl::ToUint16Impl(float v) noexcept { - uint16_t result; - if (std::isnan(v)) { - result = kPositiveQNaNBits; - } else { - auto get_msb_half = [](float fl) { - uint16_t result; -#ifdef __cpp_if_constexpr - if constexpr (detail::endian::native == detail::endian::little) { -#else - if (detail::endian::native == detail::endian::little) { -#endif - std::memcpy(&result, reinterpret_cast(&fl) + sizeof(uint16_t), sizeof(uint16_t)); - } else { - std::memcpy(&result, &fl, sizeof(uint16_t)); - } - return result; - }; - - uint16_t upper_bits = get_msb_half(v); - union { - uint32_t U32; - float F32; - }; - F32 = v; - U32 += (upper_bits & 1) + kRoundToNearest; - result = get_msb_half(F32); - } - return result; -} - -template -inline float BFloat16Impl::ToFloatImpl() const noexcept { - if (IsNaN()) { - return std::numeric_limits::quiet_NaN(); - } - float result; - char* const first = reinterpret_cast(&result); - char* const second = first + sizeof(uint16_t); -#ifdef __cpp_if_constexpr - if constexpr (detail::endian::native == detail::endian::little) { -#else - if (detail::endian::native == detail::endian::little) { -#endif - std::memset(first, 0, sizeof(uint16_t)); - std::memcpy(second, &val, sizeof(uint16_t)); - } else { - std::memcpy(first, &val, sizeof(uint16_t)); - std::memset(second, 0, sizeof(uint16_t)); - } - return result; -} - -} // namespace onnxruntime_float16 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#pragma once + +#include +#include +#include +#include + +namespace onnxruntime_float16 { + +namespace detail { + +enum class endian { +#if defined(_WIN32) + little = 0, + big = 1, + native = little, +#elif defined(__GNUC__) || defined(__clang__) + little = __ORDER_LITTLE_ENDIAN__, + big = __ORDER_BIG_ENDIAN__, + native = __BYTE_ORDER__, +#else +#error onnxruntime_float16::detail::endian is not implemented in this environment. +#endif +}; + +static_assert( + endian::native == endian::little || endian::native == endian::big, + "Only little-endian or big-endian native byte orders are supported."); + +} // namespace detail + +/// +/// Shared implementation between public and internal classes. CRTP pattern. +/// +template +struct Float16Impl { + protected: + /// + /// Converts from float to uint16_t float16 representation + /// + /// + /// + constexpr static uint16_t ToUint16Impl(float v) noexcept; + + /// + /// Converts float16 to float + /// + /// float representation of float16 value + float ToFloatImpl() const noexcept; + + /// + /// Creates an instance that represents absolute value. + /// + /// Absolute value + uint16_t AbsImpl() const noexcept { + return static_cast(val & ~kSignMask); + } + + /// + /// Creates a new instance with the sign flipped. + /// + /// Flipped sign instance + uint16_t NegateImpl() const noexcept { + return IsNaN() ? val : static_cast(val ^ kSignMask); + } + + public: + // uint16_t special values + static constexpr uint16_t kSignMask = 0x8000U; + static constexpr uint16_t kBiasedExponentMask = 0x7C00U; + static constexpr uint16_t kPositiveInfinityBits = 0x7C00U; + static constexpr uint16_t kNegativeInfinityBits = 0xFC00U; + static constexpr uint16_t kPositiveQNaNBits = 0x7E00U; + static constexpr uint16_t kNegativeQNaNBits = 0xFE00U; + static constexpr uint16_t kMaxValueBits = 0x7BFFU; // Largest normal number + static constexpr uint16_t kOneBits = 0x3C00U; + static constexpr uint16_t kMinusOneBits = 0xBC00U; + + uint16_t val{0}; + + Float16Impl() = default; + + /// + /// Checks if the value is negative + /// + /// true if negative + bool IsNegative() const noexcept { + return static_cast(val) < 0; + } + + /// + /// Tests if the value is NaN + /// + /// true if NaN + bool IsNaN() const noexcept { + return AbsImpl() > kPositiveInfinityBits; + } + + /// + /// Tests if the value is finite + /// + /// true if finite + bool IsFinite() const noexcept { + return AbsImpl() < kPositiveInfinityBits; + } + + /// + /// Tests if the value represents positive infinity. + /// + /// true if positive infinity + bool IsPositiveInfinity() const noexcept { + return val == kPositiveInfinityBits; + } + + /// + /// Tests if the value represents negative infinity + /// + /// true if negative infinity + bool IsNegativeInfinity() const noexcept { + return val == kNegativeInfinityBits; + } + + /// + /// Tests if the value is either positive or negative infinity. + /// + /// True if absolute value is infinity + bool IsInfinity() const noexcept { + return AbsImpl() == kPositiveInfinityBits; + } + + /// + /// Tests if the value is NaN or zero. Useful for comparisons. + /// + /// True if NaN or zero. + bool IsNaNOrZero() const noexcept { + auto abs = AbsImpl(); + return (abs == 0 || abs > kPositiveInfinityBits); + } + + /// + /// Tests if the value is normal (not zero, subnormal, infinite, or NaN). + /// + /// True if so + bool IsNormal() const noexcept { + auto abs = AbsImpl(); + return (abs < kPositiveInfinityBits) // is finite + && (abs != 0) // is not zero + && ((abs & kBiasedExponentMask) != 0); // is not subnormal (has a non-zero exponent) + } + + /// + /// Tests if the value is subnormal (denormal). + /// + /// True if so + bool IsSubnormal() const noexcept { + auto abs = AbsImpl(); + return (abs < kPositiveInfinityBits) // is finite + && (abs != 0) // is not zero + && ((abs & kBiasedExponentMask) == 0); // is subnormal (has a zero exponent) + } + + /// + /// Creates an instance that represents absolute value. + /// + /// Absolute value + Derived Abs() const noexcept { return Derived::FromBits(AbsImpl()); } + + /// + /// Creates a new instance with the sign flipped. + /// + /// Flipped sign instance + Derived Negate() const noexcept { return Derived::FromBits(NegateImpl()); } + + /// + /// IEEE defines that positive and negative zero are equal, this gives us a quick equality check + /// for two values by or'ing the private bits together and stripping the sign. They are both zero, + /// and therefore equivalent, if the resulting value is still zero. + /// + /// first value + /// second value + /// True if both arguments represent zero + static bool AreZero(const Float16Impl& lhs, const Float16Impl& rhs) noexcept { + return static_cast((lhs.val | rhs.val) & ~kSignMask) == 0; + } + + bool operator==(const Float16Impl& rhs) const noexcept { + if (IsNaN() || rhs.IsNaN()) { + // IEEE defines that NaN is not equal to anything, including itself. + return false; + } + return val == rhs.val; + } + + bool operator!=(const Float16Impl& rhs) const noexcept { return !(*this == rhs); } + + bool operator<(const Float16Impl& rhs) const noexcept { + if (IsNaN() || rhs.IsNaN()) { + // IEEE defines that NaN is unordered with respect to everything, including itself. + return false; + } + + const bool left_is_negative = IsNegative(); + if (left_is_negative != rhs.IsNegative()) { + // When the signs of left and right differ, we know that left is less than right if it is + // the negative value. The exception to this is if both values are zero, in which case IEEE + // says they should be equal, even if the signs differ. + return left_is_negative && !AreZero(*this, rhs); + } + return (val != rhs.val) && ((val < rhs.val) ^ left_is_negative); + } +}; + +// The following Float16_t conversions are based on the code from +// Eigen library. + +// The conversion routines are Copyright (c) Fabian Giesen, 2016. +// The original license follows: +// +// Copyright (c) Fabian Giesen, 2016 +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted. +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT +// HOLDER 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. + +namespace detail { +union float32_bits { + unsigned int u; + float f; +}; +} // namespace detail + +template +inline constexpr uint16_t Float16Impl::ToUint16Impl(float v) noexcept { + detail::float32_bits f{}; + f.f = v; + + constexpr detail::float32_bits f32infty = {255 << 23}; + constexpr detail::float32_bits f16max = {(127 + 16) << 23}; + constexpr detail::float32_bits denorm_magic = {((127 - 15) + (23 - 10) + 1) << 23}; + constexpr unsigned int sign_mask = 0x80000000u; + uint16_t val = static_cast(0x0u); + + unsigned int sign = f.u & sign_mask; + f.u ^= sign; + + // NOTE all the integer compares in this function can be safely + // compiled into signed compares since all operands are below + // 0x80000000. Important if you want fast straight SSE2 code + // (since there's no unsigned PCMPGTD). + + if (f.u >= f16max.u) { // result is Inf or NaN (all exponent bits set) + val = (f.u > f32infty.u) ? 0x7e00 : 0x7c00; // NaN->qNaN and Inf->Inf + } else { // (De)normalized number or zero + if (f.u < (113 << 23)) { // resulting FP16 is subnormal or zero + // use a magic value to align our 10 mantissa bits at the bottom of + // the float. as long as FP addition is round-to-nearest-even this + // just works. + f.f += denorm_magic.f; + + // and one integer subtract of the bias later, we have our final float! + val = static_cast(f.u - denorm_magic.u); + } else { + unsigned int mant_odd = (f.u >> 13) & 1; // resulting mantissa is odd + + // update exponent, rounding bias part 1 + // Equivalent to `f.u += ((unsigned int)(15 - 127) << 23) + 0xfff`, but + // without arithmetic overflow. + f.u += 0xc8000fffU; + // rounding bias part 2 + f.u += mant_odd; + // take the bits! + val = static_cast(f.u >> 13); + } + } + + val |= static_cast(sign >> 16); + return val; +} + +template +inline float Float16Impl::ToFloatImpl() const noexcept { + constexpr detail::float32_bits magic = {113 << 23}; + constexpr unsigned int shifted_exp = 0x7c00 << 13; // exponent mask after shift + detail::float32_bits o{}; + + o.u = (val & 0x7fff) << 13; // exponent/mantissa bits + unsigned int exp = shifted_exp & o.u; // just the exponent + o.u += (127 - 15) << 23; // exponent adjust + + // handle exponent special cases + if (exp == shifted_exp) { // Inf/NaN? + o.u += (128 - 16) << 23; // extra exp adjust + } else if (exp == 0) { // Zero/Denormal? + o.u += 1 << 23; // extra exp adjust + o.f -= magic.f; // re-normalize + } + + // Attempt to workaround the Internal Compiler Error on ARM64 + // for bitwise | operator, including std::bitset +#if (defined _MSC_VER) && (defined _M_ARM || defined _M_ARM64 || defined _M_ARM64EC) + if (IsNegative()) { + return -o.f; + } +#else + // original code: + o.u |= (val & 0x8000U) << 16U; // sign bit +#endif + return o.f; +} + +/// Shared implementation between public and internal classes. CRTP pattern. +template +struct BFloat16Impl { + protected: + /// + /// Converts from float to uint16_t float16 representation + /// + /// + /// + static uint16_t ToUint16Impl(float v) noexcept; + + /// + /// Converts bfloat16 to float + /// + /// float representation of bfloat16 value + float ToFloatImpl() const noexcept; + + /// + /// Creates an instance that represents absolute value. + /// + /// Absolute value + uint16_t AbsImpl() const noexcept { + return static_cast(val & ~kSignMask); + } + + /// + /// Creates a new instance with the sign flipped. + /// + /// Flipped sign instance + uint16_t NegateImpl() const noexcept { + return IsNaN() ? val : static_cast(val ^ kSignMask); + } + + public: + // uint16_t special values + static constexpr uint16_t kSignMask = 0x8000U; + static constexpr uint16_t kBiasedExponentMask = 0x7F80U; + static constexpr uint16_t kPositiveInfinityBits = 0x7F80U; + static constexpr uint16_t kNegativeInfinityBits = 0xFF80U; + static constexpr uint16_t kPositiveQNaNBits = 0x7FC1U; + static constexpr uint16_t kNegativeQNaNBits = 0xFFC1U; + static constexpr uint16_t kMaxValueBits = 0x7F7FU; + static constexpr uint16_t kRoundToNearest = 0x7FFFU; + static constexpr uint16_t kOneBits = 0x3F80U; + static constexpr uint16_t kMinusOneBits = 0xBF80U; + + uint16_t val{0}; + + BFloat16Impl() = default; + + /// + /// Checks if the value is negative + /// + /// true if negative + bool IsNegative() const noexcept { + return static_cast(val) < 0; + } + + /// + /// Tests if the value is NaN + /// + /// true if NaN + bool IsNaN() const noexcept { + return AbsImpl() > kPositiveInfinityBits; + } + + /// + /// Tests if the value is finite + /// + /// true if finite + bool IsFinite() const noexcept { + return AbsImpl() < kPositiveInfinityBits; + } + + /// + /// Tests if the value represents positive infinity. + /// + /// true if positive infinity + bool IsPositiveInfinity() const noexcept { + return val == kPositiveInfinityBits; + } + + /// + /// Tests if the value represents negative infinity + /// + /// true if negative infinity + bool IsNegativeInfinity() const noexcept { + return val == kNegativeInfinityBits; + } + + /// + /// Tests if the value is either positive or negative infinity. + /// + /// True if absolute value is infinity + bool IsInfinity() const noexcept { + return AbsImpl() == kPositiveInfinityBits; + } + + /// + /// Tests if the value is NaN or zero. Useful for comparisons. + /// + /// True if NaN or zero. + bool IsNaNOrZero() const noexcept { + auto abs = AbsImpl(); + return (abs == 0 || abs > kPositiveInfinityBits); + } + + /// + /// Tests if the value is normal (not zero, subnormal, infinite, or NaN). + /// + /// True if so + bool IsNormal() const noexcept { + auto abs = AbsImpl(); + return (abs < kPositiveInfinityBits) // is finite + && (abs != 0) // is not zero + && ((abs & kBiasedExponentMask) != 0); // is not subnormal (has a non-zero exponent) + } + + /// + /// Tests if the value is subnormal (denormal). + /// + /// True if so + bool IsSubnormal() const noexcept { + auto abs = AbsImpl(); + return (abs < kPositiveInfinityBits) // is finite + && (abs != 0) // is not zero + && ((abs & kBiasedExponentMask) == 0); // is subnormal (has a zero exponent) + } + + /// + /// Creates an instance that represents absolute value. + /// + /// Absolute value + Derived Abs() const noexcept { return Derived::FromBits(AbsImpl()); } + + /// + /// Creates a new instance with the sign flipped. + /// + /// Flipped sign instance + Derived Negate() const noexcept { return Derived::FromBits(NegateImpl()); } + + /// + /// IEEE defines that positive and negative zero are equal, this gives us a quick equality check + /// for two values by or'ing the private bits together and stripping the sign. They are both zero, + /// and therefore equivalent, if the resulting value is still zero. + /// + /// first value + /// second value + /// True if both arguments represent zero + static bool AreZero(const BFloat16Impl& lhs, const BFloat16Impl& rhs) noexcept { + // IEEE defines that positive and negative zero are equal, this gives us a quick equality check + // for two values by or'ing the private bits together and stripping the sign. They are both zero, + // and therefore equivalent, if the resulting value is still zero. + return static_cast((lhs.val | rhs.val) & ~kSignMask) == 0; + } +}; + +template +inline uint16_t BFloat16Impl::ToUint16Impl(float v) noexcept { + uint16_t result; + if (std::isnan(v)) { + result = kPositiveQNaNBits; + } else { + auto get_msb_half = [](float fl) { + uint16_t result; +#ifdef __cpp_if_constexpr + if constexpr (detail::endian::native == detail::endian::little) { +#else + if (detail::endian::native == detail::endian::little) { +#endif + std::memcpy(&result, reinterpret_cast(&fl) + sizeof(uint16_t), sizeof(uint16_t)); + } else { + std::memcpy(&result, &fl, sizeof(uint16_t)); + } + return result; + }; + + uint16_t upper_bits = get_msb_half(v); + union { + uint32_t U32; + float F32; + }; + F32 = v; + U32 += (upper_bits & 1) + kRoundToNearest; + result = get_msb_half(F32); + } + return result; +} + +template +inline float BFloat16Impl::ToFloatImpl() const noexcept { + if (IsNaN()) { + return std::numeric_limits::quiet_NaN(); + } + float result; + char* const first = reinterpret_cast(&result); + char* const second = first + sizeof(uint16_t); +#ifdef __cpp_if_constexpr + if constexpr (detail::endian::native == detail::endian::little) { +#else + if (detail::endian::native == detail::endian::little) { +#endif + std::memset(first, 0, sizeof(uint16_t)); + std::memcpy(second, &val, sizeof(uint16_t)); + } else { + std::memcpy(first, &val, sizeof(uint16_t)); + std::memset(second, 0, sizeof(uint16_t)); + } + return result; +} + +} // namespace onnxruntime_float16 diff --git a/3rdParty/ONNX/onnxruntime_lite_custom_op.h b/3rdParty/ONNX/onnxruntime_lite_custom_op.h index ce87d8c56d..e8aa0342d6 100644 --- a/3rdParty/ONNX/onnxruntime_lite_custom_op.h +++ b/3rdParty/ONNX/onnxruntime_lite_custom_op.h @@ -1,1119 +1,1119 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// Summary -// The header has APIs to save custom op authors the trouble of defining schemas, -// which will be inferred by functions' signature, as long as their argument list has types supported here. -// Input could be: -// 1. Tensor of onnx data types. -// 2. Span of onnx data types. -// 3. Scalar of onnx data types. -// A input could be optional if indicated as std::optional<...>. -// For an output, it must be a tensor of onnx data types. -// Further, the header also has utility for a simple custom struct, where resources could be kept, to be registered as a custom op. -// For concrete examples, please search keyword "LiteCustomOpTest" under "/onnxruntime/test/". -// Note - all APIs in this header are ABI. - -#pragma once -#include "onnxruntime_cxx_api.h" -#include -#include -#include -#include - -namespace Ort { -namespace Custom { - -class ArgBase { - public: - ArgBase(OrtKernelContext* ctx, - size_t indice, - bool is_input) : ctx_(ctx), indice_(indice), is_input_(is_input) {} - virtual ~ArgBase() {}; - - protected: - struct KernelContext ctx_; - size_t indice_; - bool is_input_; -}; - -using ArgPtr = std::unique_ptr; -using ArgPtrs = std::vector; - -class TensorBase : public ArgBase { - public: - TensorBase(OrtKernelContext* ctx, - size_t indice, - bool is_input) : ArgBase(ctx, indice, is_input) {} - - operator bool() const { - return shape_.has_value(); - } - - const std::vector& Shape() const { - if (!shape_.has_value()) { - ORT_CXX_API_THROW("tensor shape is not yet initialized", OrtErrorCode::ORT_RUNTIME_EXCEPTION); - } - return shape_.value(); - } - - ONNXTensorElementDataType Type() const { - return type_; - } - - int64_t NumberOfElement() const { - if (shape_.has_value()) { - return std::accumulate(shape_->begin(), shape_->end(), 1LL, std::multiplies()); - } else { - return 0; - } - } - - std::string Shape2Str() const { - if (shape_.has_value()) { - std::string shape_str; - for (const auto& dim : *shape_) { - shape_str.append(std::to_string(dim)); - shape_str.append(", "); - } - return shape_str; - } else { - return "empty"; - } - } - - bool IsCpuTensor() const { - return strcmp("Cpu", mem_type_) == 0; - } - - virtual const void* DataRaw() const = 0; - virtual size_t SizeInBytes() const = 0; - - protected: - std::optional> shape_; - ONNXTensorElementDataType type_ = ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED; - const char* mem_type_ = "Cpu"; -}; - -template -struct Span { - const T* data_ = {}; - size_t size_ = {}; - void Assign(const T* data, size_t size) { - data_ = data; - size_ = size; - } - size_t size() const { return size_; } - T operator[](size_t indice) const { - return data_[indice]; - } - const T* data() const { return data_; } -}; - -template -class Tensor : public TensorBase { - public: - using TT = typename std::remove_reference::type; - Tensor(OrtKernelContext* ctx, size_t indice, bool is_input) : TensorBase(ctx, indice, is_input) { - if (is_input_) { - if (indice >= ctx_.GetInputCount()) { - ORT_CXX_API_THROW("invalid indice for Ort::Custom::Tensor", OrtErrorCode::ORT_INVALID_ARGUMENT); - } - const_value_ = ctx_.GetInput(indice); - auto type_shape_info = const_value_.GetTensorTypeAndShapeInfo(); - shape_ = type_shape_info.GetShape(); - } - } - const TT* Data() const { - return reinterpret_cast(const_value_.GetTensorRawData()); - } - TT* Allocate(const std::vector& shape) { - shape_ = shape; - if (!data_) { - shape_ = shape; - data_ = ctx_.GetOutput(indice_, shape).template GetTensorMutableData(); - } - return data_; - } - static TT GetT() { return (TT)0; } - const Span& AsSpan() { - if (!shape_.has_value() || shape_->size() != 1) { - ORT_CXX_API_THROW("invalid shape while trying to get a span out of Ort::Custom::Tensor", - OrtErrorCode::ORT_RUNTIME_EXCEPTION); - } - span_.Assign(Data(), static_cast((*shape_)[0])); - return span_; - } - const T& AsScalar() { - if (!shape_.has_value() || shape_->size() != 1 || (*shape_)[0] != 1) { - ORT_CXX_API_THROW("invalid shape while trying to get a scalar from Ort::Custom::Tensor", - OrtErrorCode::ORT_RUNTIME_EXCEPTION); - } - return *Data(); - } - const void* DataRaw() const override { - return reinterpret_cast(Data()); - } - - size_t SizeInBytes() const override { - return sizeof(TT) * static_cast(NumberOfElement()); - } - - private: - ConstValue const_value_; // for input - TT* data_{}; // for output - Span span_; -}; - -template <> -class Tensor : public TensorBase { - public: - using strings = std::vector; - - Tensor(OrtKernelContext* ctx, size_t indice, bool is_input) : TensorBase(ctx, indice, is_input) { - if (is_input_) { - if (indice >= ctx_.GetInputCount()) { - ORT_CXX_API_THROW("invalid indice for Ort::Custom::Tensor", OrtErrorCode::ORT_INVALID_ARGUMENT); - } - auto const_value = ctx_.GetInput(indice); - auto type_shape_info = const_value.GetTensorTypeAndShapeInfo(); - shape_ = type_shape_info.GetShape(); - auto num_chars = const_value.GetStringTensorDataLength(); - // note - there will be copy ... - auto num_strings = static_cast(NumberOfElement()); - if (num_strings) { - std::vector chars(num_chars + 1, '\0'); - std::vector offsets(num_strings); - const_value.GetStringTensorContent(static_cast(chars.data()), num_chars, offsets.data(), offsets.size()); - auto upper_bound = num_strings - 1; - input_strings_.resize(num_strings); - for (size_t i = upper_bound;; --i) { - if (i < upper_bound) { - chars[offsets[i + 1]] = '\0'; - } - input_strings_[i] = chars.data() + offsets[i]; - if (0 == i) { - break; - } - } - } - } - } - const strings& Data() const { - return input_strings_; - } - const void* DataRaw() const override { - if (input_strings_.size() != 1) { - ORT_CXX_API_THROW("DataRaw() only applies to string scalar", ORT_RUNTIME_EXCEPTION); - } - return reinterpret_cast(input_strings_[0].c_str()); - } - size_t SizeInBytes() const override { - if (input_strings_.size() != 1) { - ORT_CXX_API_THROW("SizeInBytes() only applies to string scalar", ORT_RUNTIME_EXCEPTION); - } - return input_strings_[0].size(); - } - void SetStringOutput(const strings& ss, const std::vector& dims) { - shape_ = dims; - std::vector raw; - for (const auto& s : ss) { - raw.push_back(s.data()); - } - auto output = ctx_.GetOutput(indice_, dims.data(), dims.size()); - // note - there will be copy ... - output.FillStringTensor(raw.data(), raw.size()); - } - const Span& AsSpan() { - ORT_CXX_API_THROW("span for TensorT of string not implemented", OrtErrorCode::ORT_RUNTIME_EXCEPTION); - } - const std::string& AsScalar() { - if (input_strings_.size() != 1) { - ORT_CXX_API_THROW("invalid shape while trying to get a scalar string from Ort::Custom::Tensor", - OrtErrorCode::ORT_RUNTIME_EXCEPTION); - } - return input_strings_[0]; - } - - private: - std::vector input_strings_; // for input -}; - -template <> -class Tensor : public TensorBase { - public: - using strings = std::vector; - using string_views = std::vector; - - Tensor(OrtKernelContext* ctx, size_t indice, bool is_input) : TensorBase(ctx, indice, is_input) { - if (is_input_) { - if (indice >= ctx_.GetInputCount()) { - ORT_CXX_API_THROW("invalid indice for Ort::Custom::Tensor", OrtErrorCode::ORT_INVALID_ARGUMENT); - } - auto const_value = ctx_.GetInput(indice); - auto type_shape_info = const_value.GetTensorTypeAndShapeInfo(); - shape_ = type_shape_info.GetShape(); - auto num_chars = const_value.GetStringTensorDataLength(); - chars_.resize(num_chars + 1, '\0'); - auto num_strings = static_cast(NumberOfElement()); - if (num_strings) { - std::vector offsets(num_strings); - const_value.GetStringTensorContent(static_cast(chars_.data()), num_chars, offsets.data(), offsets.size()); - offsets.push_back(num_chars); - for (size_t i = 0; i < num_strings; ++i) { - input_string_views_.emplace_back(chars_.data() + offsets[i], offsets[i + 1] - offsets[i]); - } - } - } - } - const string_views& Data() const { - return input_string_views_; - } - const void* DataRaw() const override { - if (input_string_views_.size() != 1) { - ORT_CXX_API_THROW("DataRaw() only applies to string scalar", ORT_RUNTIME_EXCEPTION); - } - return reinterpret_cast(input_string_views_[0].data()); - } - size_t SizeInBytes() const override { - if (input_string_views_.size() != 1) { - ORT_CXX_API_THROW("SizeInBytes() only applies to string scalar", ORT_RUNTIME_EXCEPTION); - } - return input_string_views_[0].size(); - } - void SetStringOutput(const strings& ss, const std::vector& dims) { - shape_ = dims; - std::vector raw; - for (const auto& s : ss) { - raw.push_back(s.data()); - } - auto output = ctx_.GetOutput(indice_, dims.data(), dims.size()); - // note - there will be copy ... - output.FillStringTensor(raw.data(), raw.size()); - } - const Span& AsSpan() { - ORT_CXX_API_THROW("span for TensorT of string view not implemented", OrtErrorCode::ORT_RUNTIME_EXCEPTION); - } - std::string_view AsScalar() { - if (input_string_views_.size() != 1) { - ORT_CXX_API_THROW("invalid shape while trying to get a scalar string view from Ort::Custom::Tensor", - OrtErrorCode::ORT_RUNTIME_EXCEPTION); - } - return input_string_views_[0]; - } - - private: - std::vector chars_; // for input - std::vector input_string_views_; // for input -}; - -using TensorPtr = std::unique_ptr; -using TensorPtrs = std::vector; - -struct TensorArray : public ArgBase { - TensorArray(OrtKernelContext* ctx, - size_t start_indice, - bool is_input) : ArgBase(ctx, - start_indice, - is_input) { - if (is_input) { - auto input_count = ctx_.GetInputCount(); - for (size_t ith_input = start_indice; ith_input < input_count; ++ith_input) { - auto const_value = ctx_.GetInput(start_indice); - auto type_shape_info = const_value.GetTensorTypeAndShapeInfo(); - auto type = type_shape_info.GetElementType(); - TensorPtr tensor; - switch (type) { - case ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL: - tensor = std::make_unique>(ctx, ith_input, true); - break; - case ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT: - tensor = std::make_unique>(ctx, ith_input, true); - break; - case ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE: - tensor = std::make_unique>(ctx, ith_input, true); - break; - case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8: - tensor = std::make_unique>(ctx, ith_input, true); - break; - case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8: - tensor = std::make_unique>(ctx, ith_input, true); - break; - case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16: - tensor = std::make_unique>(ctx, ith_input, true); - break; - case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16: - tensor = std::make_unique>(ctx, ith_input, true); - break; - case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32: - tensor = std::make_unique>(ctx, ith_input, true); - break; - case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32: - tensor = std::make_unique>(ctx, ith_input, true); - break; - case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64: - tensor = std::make_unique>(ctx, ith_input, true); - break; - case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64: - tensor = std::make_unique>(ctx, ith_input, true); - break; - case ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING: - tensor = std::make_unique>(ctx, ith_input, true); - break; - default: - ORT_CXX_API_THROW("unknow input type", ORT_RUNTIME_EXCEPTION); - break; - } - tensors_.emplace_back(tensor.release()); - } // for - } - } - template - T* AllocateOutput(size_t ith_output, const std::vector& shape) { - // ith_output is the indice of output relative to the tensor array - // indice_ + ith_output is the indice relative to context - auto tensor = std::make_unique>(ctx_.GetOrtKernelContext(), indice_ + ith_output, false); - auto raw_output = tensor.get()->Allocate(shape); - tensors_.emplace_back(tensor.release()); - return raw_output; - } - Tensor& AllocateStringTensor(size_t ith_output) { - // ith_output is the indice of output relative to the tensor array - // indice_ + ith_output is the indice relative to context - auto tensor = std::make_unique>(ctx_.GetOrtKernelContext(), indice_ + ith_output, false); - Tensor& output = *tensor; - tensors_.emplace_back(tensor.release()); - return output; - } - size_t Size() const { - return tensors_.size(); - } - const TensorPtr& operator[](size_t ith_input) const { - // ith_input is the indice of output relative to the tensor array - return tensors_.at(ith_input); - } - - private: - TensorPtrs tensors_; -}; - -using Variadic = TensorArray; - -/* -Note: -OrtLiteCustomOp inherits from OrtCustomOp to bridge tween a custom func/struct and ort core. -The lifetime of an OrtLiteCustomOp instance is managed by customer code, not ort, so: -1. DO NOT cast OrtLiteCustomOp to OrtCustomOp and release since there is no virtual destructor in the hierarchy. -2. OrtLiteCustomFunc and OrtLiteCustomStruct, as two sub-structs, can be released in form of OrtLiteCustomOp since all members are kept in the OrtLiteCustomOp, - hence memory could still be recycled properly. -Further, OrtCustomOp is a c struct bearing no v-table, so offspring structs are by design to be of zero virtual functions to maintain cast safety. -*/ -struct OrtLiteCustomOp : public OrtCustomOp { - using ConstOptionalFloatTensor = std::optional&>; - using OptionalFloatTensor = std::optional>; - - // CreateTuple - template - static typename std::enable_if>::type - CreateTuple(OrtKernelContext*, ArgPtrs&, size_t, size_t, const std::string&) { - return std::make_tuple(); - } - - template - static typename std::enable_if::value, std::tuple>::type - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { - std::tuple current = std::tuple{context}; - auto next = CreateTuple(context, args, num_input, num_output, ep); - return std::tuple_cat(current, next); - } - - template - static typename std::enable_if::value, std::tuple>::type - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { - std::tuple current = std::tuple{*context}; - auto next = CreateTuple(context, args, num_input, num_output, ep); - return std::tuple_cat(current, next); - } - -#ifdef ORT_CUDA_CTX - template - static typename std::enable_if::value, std::tuple>::type - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { - thread_local CudaContext cuda_context; - cuda_context.Init(*context); - std::tuple current = std::tuple{cuda_context}; - auto next = CreateTuple(context, args, num_input, num_output, ep); - return std::tuple_cat(current, next); - } -#endif - -#ifdef ORT_ROCM_CTX - template - static typename std::enable_if::value, std::tuple>::type - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { - thread_local RocmContext rocm_context; - rocm_context.Init(*context); - std::tuple current = std::tuple{rocm_context}; - auto next = CreateTuple(context, args, num_input, num_output, ep); - return std::tuple_cat(current, next); - } -#endif - - template - static typename std::enable_if::value, std::tuple>::type - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { - args.push_back(std::make_unique(context, ith_input, true)); - std::tuple current = std::tuple{reinterpret_cast(args.back().get())}; - auto next = CreateTuple(context, args, num_input, num_output, ep); - return std::tuple_cat(current, next); - } - - template - static typename std::enable_if::value, std::tuple>::type - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { - args.push_back(std::make_unique(context, ith_input, true)); - std::tuple current = std::tuple{reinterpret_cast(*args.back().get())}; - auto next = CreateTuple(context, args, num_input, num_output, ep); - return std::tuple_cat(current, next); - } - - template - static typename std::enable_if::value, std::tuple>::type - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { - args.push_back(std::make_unique(context, ith_output, false)); - std::tuple current = std::tuple{reinterpret_cast(args.back().get())}; - auto next = CreateTuple(context, args, num_input, num_output, ep); - return std::tuple_cat(current, next); - } - - template - static typename std::enable_if::value, std::tuple>::type - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { - args.push_back(std::make_unique(context, ith_output, false)); - std::tuple current = std::tuple{reinterpret_cast(*args.back().get())}; - auto next = CreateTuple(context, args, num_input, num_output, ep); - return std::tuple_cat(current, next); - } - -#define CREATE_TUPLE_INPUT(data_type) \ - template \ - static typename std::enable_if*>::value, std::tuple>::type \ - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ - args.push_back(std::make_unique>(context, ith_input, true)); \ - std::tuple current = std::tuple{reinterpret_cast(args.back().get())}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } \ - template \ - static typename std::enable_if&>::value, std::tuple>::type \ - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ - args.push_back(std::make_unique>(context, ith_input, true)); \ - std::tuple current = std::tuple{reinterpret_cast(*args.back().get())}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } \ - template \ - static typename std::enable_if*>>::value, std::tuple>::type \ - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ - if (ith_input < num_input) { \ - args.push_back(std::make_unique>(context, ith_input, true)); \ - std::tuple current = std::tuple{reinterpret_cast*>(args.back().get())}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } else { \ - std::tuple current = std::tuple{}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } \ - } \ - template \ - static typename std::enable_if*>::value, std::tuple>::type \ - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ - if ("CPUExecutionProvider" != ep) { \ - ORT_CXX_API_THROW("span input could only be applied to CPU EP", OrtErrorCode::ORT_RUNTIME_EXCEPTION); \ - } \ - args.push_back(std::make_unique>(context, ith_input, true)); \ - std::tuple current = std::tuple{&reinterpret_cast*>(args.back().get())->AsSpan()}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } \ - template \ - static typename std::enable_if&>::value, std::tuple>::type \ - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ - if ("CPUExecutionProvider" != ep) { \ - ORT_CXX_API_THROW("span input could only be applied to CPU EP", OrtErrorCode::ORT_RUNTIME_EXCEPTION); \ - } \ - args.push_back(std::make_unique>(context, ith_input, true)); \ - std::tuple current = std::tuple{reinterpret_cast*>(args.back().get())->AsSpan()}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } \ - template \ - static typename std::enable_if*>>::value, std::tuple>::type \ - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ - if (ith_input < num_input) { \ - if ("CPUExecutionProvider" != ep) { \ - ORT_CXX_API_THROW("span input could only be applied to CPU EP", OrtErrorCode::ORT_RUNTIME_EXCEPTION); \ - } \ - args.push_back(std::make_unique>(context, ith_input, true)); \ - std::tuple current = std::tuple{&reinterpret_cast*>(args.back().get())->AsSpan()}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } else { \ - std::tuple current = std::tuple{}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } \ - } \ - template \ - static typename std::enable_if::value, std::tuple>::type \ - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ - if ("CPUExecutionProvider" != ep) { \ - ORT_CXX_API_THROW("scalar input could only be applied to CPU EP", OrtErrorCode::ORT_RUNTIME_EXCEPTION); \ - } \ - args.push_back(std::make_unique>(context, ith_input, true)); \ - std::tuple current = std::tuple{reinterpret_cast*>(args.back().get())->AsScalar()}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } \ - template \ - static typename std::enable_if>::value, std::tuple>::type \ - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ - if (ith_input < num_input) { \ - if ("CPUExecutionProvider" != ep) { \ - ORT_CXX_API_THROW("scalar input could only be applied to CPU EP", OrtErrorCode::ORT_RUNTIME_EXCEPTION); \ - } \ - args.push_back(std::make_unique>(context, ith_input, true)); \ - std::tuple current = std::tuple{reinterpret_cast*>(args.back().get())->AsScalar()}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } else { \ - std::tuple current = std::tuple{}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } \ - } -#define CREATE_TUPLE_OUTPUT(data_type) \ - template \ - static typename std::enable_if*>::value, std::tuple>::type \ - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ - args.push_back(std::make_unique>(context, ith_output, false)); \ - std::tuple current = std::tuple{reinterpret_cast(args.back().get())}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } \ - template \ - static typename std::enable_if&>::value, std::tuple>::type \ - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ - args.push_back(std::make_unique>(context, ith_output, false)); \ - std::tuple current = std::tuple{reinterpret_cast(*args.back().get())}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } \ - template \ - static typename std::enable_if*>>::value, std::tuple>::type \ - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ - if (ith_output < num_output) { \ - args.push_back(std::make_unique>(context, ith_output, false)); \ - std::tuple current = std::tuple{reinterpret_cast*>(args.back().get())}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } else { \ - std::tuple current = std::tuple{}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } \ - } -#define CREATE_TUPLE(data_type) \ - CREATE_TUPLE_INPUT(data_type) \ - CREATE_TUPLE_OUTPUT(data_type) - - CREATE_TUPLE(bool) - CREATE_TUPLE(float) - CREATE_TUPLE(Ort::Float16_t) - CREATE_TUPLE(Ort::BFloat16_t) - CREATE_TUPLE(double) - CREATE_TUPLE(int8_t) - CREATE_TUPLE(int16_t) - CREATE_TUPLE(int32_t) - CREATE_TUPLE(int64_t) - CREATE_TUPLE(uint8_t) - CREATE_TUPLE(uint16_t) - CREATE_TUPLE(uint32_t) - CREATE_TUPLE(uint64_t) - CREATE_TUPLE(std::string) - CREATE_TUPLE_INPUT(std::string_view) - CREATE_TUPLE(Ort::Float8E4M3FN_t) - CREATE_TUPLE(Ort::Float8E4M3FNUZ_t) - CREATE_TUPLE(Ort::Float8E5M2_t) - CREATE_TUPLE(Ort::Float8E5M2FNUZ_t) - - // ParseArgs ... - template - static typename std::enable_if<0 == sizeof...(Ts)>::type - ParseArgs(std::vector&, std::vector&) { - } - - template - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type - ParseArgs(std::vector& input_types, std::vector& output_types) { - ParseArgs(input_types, output_types); - } - - template - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type - ParseArgs(std::vector& input_types, std::vector& output_types) { - ParseArgs(input_types, output_types); - } - -#ifdef ORT_CUDA_CTX - template - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type - ParseArgs(std::vector& input_types, std::vector& output_types) { - ParseArgs(input_types, output_types); - } -#endif - -#ifdef ORT_ROCM_CTX - template - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type - ParseArgs(std::vector& input_types, std::vector& output_types) { - ParseArgs(input_types, output_types); - } -#endif - - template - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type - ParseArgs(std::vector& input_types, std::vector& output_types) { - input_types.push_back(ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED); - ParseArgs(input_types, output_types); - } - - template - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type - ParseArgs(std::vector& input_types, std::vector& output_types) { - input_types.push_back(ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED); - ParseArgs(input_types, output_types); - } - - template - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type - ParseArgs(std::vector& input_types, std::vector& output_types) { - output_types.push_back(ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED); - ParseArgs(input_types, output_types); - } - - template - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type - ParseArgs(std::vector& input_types, std::vector& output_types) { - output_types.push_back(ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED); - ParseArgs(input_types, output_types); - } - -#define PARSE_INPUT_BASE(pack_type, onnx_type) \ - template \ - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type \ - ParseArgs(std::vector& input_types, std::vector& output_types) { \ - input_types.push_back(onnx_type); \ - ParseArgs(input_types, output_types); \ - } \ - template \ - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same>::value>::type \ - ParseArgs(std::vector& input_types, std::vector& output_types) { \ - input_types.push_back(onnx_type); \ - ParseArgs(input_types, output_types); \ - } \ - template \ - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same>::value>::type \ - ParseArgs(std::vector& input_types, std::vector& output_types) { \ - input_types.push_back(onnx_type); \ - ParseArgs(input_types, output_types); \ - } - -#define PARSE_INPUT(data_type, onnx_type) \ - PARSE_INPUT_BASE(const Custom::Tensor*, onnx_type) \ - PARSE_INPUT_BASE(const Custom::Tensor&, onnx_type) \ - PARSE_INPUT_BASE(const Custom::Span*, onnx_type) \ - PARSE_INPUT_BASE(const Custom::Span&, onnx_type) \ - PARSE_INPUT_BASE(data_type, onnx_type) - -#define PARSE_OUTPUT(data_type, onnx_type) \ - template \ - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same*>::value>::type \ - ParseArgs(std::vector& input_types, std::vector& output_types) { \ - output_types.push_back(onnx_type); \ - ParseArgs(input_types, output_types); \ - } \ - template \ - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same&>::value>::type \ - ParseArgs(std::vector& input_types, std::vector& output_types) { \ - output_types.push_back(onnx_type); \ - ParseArgs(input_types, output_types); \ - } \ - template \ - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same*>>::value>::type \ - ParseArgs(std::vector& input_types, std::vector& output_types) { \ - output_types.push_back(onnx_type); \ - ParseArgs(input_types, output_types); \ - } - -#define PARSE_ARGS(data_type, onnx_type) \ - PARSE_INPUT(data_type, onnx_type) \ - PARSE_OUTPUT(data_type, onnx_type) - - PARSE_ARGS(bool, ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL) - PARSE_ARGS(float, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT) - PARSE_ARGS(Ort::Float16_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16) - PARSE_ARGS(Ort::BFloat16_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_BFLOAT16) - PARSE_ARGS(double, ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE) - PARSE_ARGS(int8_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8) - PARSE_ARGS(int16_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16) - PARSE_ARGS(int32_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32) - PARSE_ARGS(int64_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64) - PARSE_ARGS(uint8_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8) - PARSE_ARGS(uint16_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16) - PARSE_ARGS(uint32_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32) - PARSE_ARGS(uint64_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64) - PARSE_ARGS(std::string, ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING) - PARSE_ARGS(std::string_view, ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING) // todo - remove string_view output - PARSE_ARGS(Ort::Float8E4M3FN_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FN) - PARSE_ARGS(Ort::Float8E4M3FNUZ_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FNUZ) - PARSE_ARGS(Ort::Float8E5M2_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2) - PARSE_ARGS(Ort::Float8E5M2FNUZ_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2FNUZ) - - OrtLiteCustomOp(const char* op_name, - const char* execution_provider, - ShapeInferFn shape_infer_fn, - int start_ver = 1, - int end_ver = MAX_CUSTOM_OP_END_VER) : op_name_(op_name), - execution_provider_(execution_provider), - shape_infer_fn_(shape_infer_fn), - start_ver_(start_ver), - end_ver_(end_ver) { - OrtCustomOp::version = ORT_API_VERSION; - - OrtCustomOp::GetName = [](const OrtCustomOp* op) { return static_cast(op)->op_name_.c_str(); }; - OrtCustomOp::GetExecutionProviderType = [](const OrtCustomOp* op) { return ((OrtLiteCustomOp*)op)->execution_provider_.c_str(); }; - OrtCustomOp::GetInputMemoryType = [](const OrtCustomOp*, size_t) { return OrtMemTypeDefault; }; - - OrtCustomOp::GetInputTypeCount = [](const OrtCustomOp* op) { - auto self = reinterpret_cast(op); - return self->input_types_.size(); - }; - - OrtCustomOp::GetInputType = [](const OrtCustomOp* op, size_t indice) { - auto self = reinterpret_cast(op); - return self->input_types_[indice]; - }; - - OrtCustomOp::GetOutputTypeCount = [](const OrtCustomOp* op) { - auto self = reinterpret_cast(op); - return self->output_types_.size(); - }; - - OrtCustomOp::GetOutputType = [](const OrtCustomOp* op, size_t indice) { - auto self = reinterpret_cast(op); - return self->output_types_[indice]; - }; - - OrtCustomOp::GetInputCharacteristic = [](const OrtCustomOp* op, size_t indice) { - auto self = reinterpret_cast(op); - return self->input_types_[indice] == ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED ? INPUT_OUTPUT_VARIADIC : INPUT_OUTPUT_OPTIONAL; - }; - - OrtCustomOp::GetOutputCharacteristic = [](const OrtCustomOp* op, size_t indice) { - auto self = reinterpret_cast(op); - return self->output_types_[indice] == ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED ? INPUT_OUTPUT_VARIADIC : INPUT_OUTPUT_OPTIONAL; - }; - - OrtCustomOp::GetVariadicInputMinArity = [](const OrtCustomOp*) { - return 1; - }; - - OrtCustomOp::GetVariadicInputHomogeneity = [](const OrtCustomOp*) { - return 0; - }; - - OrtCustomOp::GetVariadicOutputMinArity = [](const OrtCustomOp*) { - return 1; - }; - - OrtCustomOp::GetVariadicOutputHomogeneity = [](const OrtCustomOp*) { - return 0; - }; - - OrtCustomOp::GetVariadicInputMinArity = [](const OrtCustomOp*) { return 0; }; - OrtCustomOp::GetVariadicInputHomogeneity = [](const OrtCustomOp*) { return 0; }; - OrtCustomOp::GetVariadicOutputMinArity = [](const OrtCustomOp*) { return 0; }; - OrtCustomOp::GetVariadicOutputHomogeneity = [](const OrtCustomOp*) { return 0; }; - - OrtCustomOp::CreateKernelV2 = {}; - OrtCustomOp::KernelComputeV2 = {}; - OrtCustomOp::KernelCompute = {}; - - OrtCustomOp::InferOutputShapeFn = {}; - - OrtCustomOp::GetStartVersion = [](const OrtCustomOp* op) { - auto self = reinterpret_cast(op); - return self->start_ver_; - }; - - OrtCustomOp::GetEndVersion = [](const OrtCustomOp* op) { - auto self = reinterpret_cast(op); - return self->end_ver_; - }; - - OrtCustomOp::GetMayInplace = {}; - OrtCustomOp::ReleaseMayInplace = {}; - OrtCustomOp::GetAliasMap = {}; - OrtCustomOp::ReleaseAliasMap = {}; - } - - const std::string op_name_; - const std::string execution_provider_; - - std::vector input_types_; - std::vector output_types_; - - ShapeInferFn shape_infer_fn_ = {}; - - int start_ver_ = 1; - int end_ver_ = MAX_CUSTOM_OP_END_VER; - - void* compute_fn_ = {}; - void* compute_fn_return_status_ = {}; -}; - -//////////////////////////// OrtLiteCustomFunc //////////////////////////////// -// The struct is to implement function-as-op. -// E.g. a function might be defined as: -// void Filter(const Ort::Custom::Tensor& floats_in, Ort::Custom::Tensor& floats_out) { ... } -// It could be registered this way: -// Ort::CustomOpDomain v2_domain{"v2"}; -// std::unique_ptr fil_op_ptr{Ort::Custom::CreateLiteCustomOp("Filter", "CPUExecutionProvider", Filter)}; -// v2_domain.Add(fil_op_ptr.get()); -// session_options.Add(v2_domain); -// For the complete example, please search keyword "LiteCustomOpTest" under "/onnxruntime/test/". -template -struct OrtLiteCustomFunc : public OrtLiteCustomOp { - using ComputeFn = void (*)(Args...); - using ComputeFnReturnStatus = Status (*)(Args...); - using MyType = OrtLiteCustomFunc; - - struct Kernel { - size_t num_input_{}; - size_t num_output_{}; - ComputeFn compute_fn_{}; - ComputeFnReturnStatus compute_fn_return_status_{}; - std::string ep_{}; - }; - - OrtLiteCustomFunc(const char* op_name, - const char* execution_provider, - ComputeFn compute_fn, - ShapeInferFn shape_infer_fn = {}, - int start_ver = 1, - int end_ver = MAX_CUSTOM_OP_END_VER) : OrtLiteCustomOp(op_name, execution_provider, shape_infer_fn, start_ver, end_ver) { - compute_fn_ = reinterpret_cast(compute_fn); - ParseArgs(input_types_, output_types_); - - OrtCustomOp::KernelCompute = [](void* op_kernel, OrtKernelContext* context) { - auto kernel = reinterpret_cast(op_kernel); - std::vector args; - auto t = CreateTuple<0, 0, Args...>(context, args, kernel->num_input_, kernel->num_output_, kernel->ep_); - std::apply([kernel](Args const&... t_args) { kernel->compute_fn_(t_args...); }, t); - }; - - OrtCustomOp::CreateKernel = [](const OrtCustomOp* this_, const OrtApi* ort_api, const OrtKernelInfo* info) { - auto kernel = std::make_unique(); - auto me = static_cast(this_); - kernel->compute_fn_ = reinterpret_cast(me->compute_fn_); - Ort::ThrowOnError(ort_api->KernelInfo_GetInputCount(info, &kernel->num_input_)); - Ort::ThrowOnError(ort_api->KernelInfo_GetOutputCount(info, &kernel->num_output_)); - auto self = static_cast(this_); - kernel->ep_ = self->execution_provider_; - return reinterpret_cast(kernel.release()); - }; - - OrtCustomOp::KernelDestroy = [](void* op_kernel) { - delete reinterpret_cast(op_kernel); - }; - - if (shape_infer_fn_) { - OrtCustomOp::InferOutputShapeFn = [](const OrtCustomOp* op, OrtShapeInferContext* ort_ctx) -> OrtStatusPtr { - auto shape_info_fn = static_cast(op)->shape_infer_fn_; - ShapeInferContext ctx(&GetApi(), ort_ctx); - return shape_info_fn(ctx); - }; - } - } - - OrtLiteCustomFunc(const char* op_name, - const char* execution_provider, - ComputeFnReturnStatus compute_fn_return_status, - ShapeInferFn shape_infer_fn = {}, - int start_ver = 1, - int end_ver = MAX_CUSTOM_OP_END_VER) : OrtLiteCustomOp(op_name, execution_provider, shape_infer_fn, start_ver, end_ver) { - compute_fn_return_status_ = reinterpret_cast(compute_fn_return_status); - ParseArgs(input_types_, output_types_); - - OrtCustomOp::KernelComputeV2 = [](void* op_kernel, OrtKernelContext* context) -> OrtStatusPtr { - auto kernel = reinterpret_cast(op_kernel); - std::vector args; - auto t = CreateTuple<0, 0, Args...>(context, args, kernel->num_input_, kernel->num_output_, kernel->ep_); - return std::apply([kernel](Args const&... t_args) { Status status = kernel->compute_fn_return_status_(t_args...); return status.release(); }, t); - }; - - OrtCustomOp::CreateKernel = [](const OrtCustomOp* this_, const OrtApi* ort_api, const OrtKernelInfo* info) { - auto kernel = std::make_unique(); - auto me = static_cast(this_); - kernel->compute_fn_return_status_ = reinterpret_cast(me->compute_fn_return_status_); - Ort::ThrowOnError(ort_api->KernelInfo_GetInputCount(info, &kernel->num_input_)); - Ort::ThrowOnError(ort_api->KernelInfo_GetOutputCount(info, &kernel->num_output_)); - auto self = static_cast(this_); - kernel->ep_ = self->execution_provider_; - return reinterpret_cast(kernel.release()); - }; - - OrtCustomOp::KernelDestroy = [](void* op_kernel) { - delete reinterpret_cast(op_kernel); - }; - - if (shape_infer_fn_) { - OrtCustomOp::InferOutputShapeFn = [](const OrtCustomOp* op, OrtShapeInferContext* ort_ctx) -> OrtStatusPtr { - auto shape_info_fn = static_cast(op)->shape_infer_fn_; - ShapeInferContext ctx(&GetApi(), ort_ctx); - return shape_info_fn(ctx); - }; - } - } -}; // struct OrtLiteCustomFunc - -/////////////////////////// OrtLiteCustomStruct /////////////////////////// -// The struct is to implement struct-as-op. -// E.g. a struct might be defined as: -// struct Merge { -// Merge(const OrtApi* ort_api, const OrtKernelInfo* info) {...} -// void Compute(const Ort::Custom::Tensor& strings_in, -// std::string_view string_in, -// Ort::Custom::Tensor* strings_out) {...} -// bool reverse_ = false; -// }; -// It could be registered this way: -// Ort::CustomOpDomain v2_domain{"v2"}; -// std::unique_ptr mrg_op_ptr{Ort::Custom::CreateLiteCustomOp("Merge", "CPUExecutionProvider")}; -// v2_domain.Add(mrg_op_ptr.get()); -// session_options.Add(v2_domain); -// For the complete example, please search keyword "LiteCustomOpTest" under "/onnxruntime/test/". -template -struct OrtLiteCustomStruct : public OrtLiteCustomOp { - template - using CustomComputeFn = void (CustomOp::*)(Args...); - - template - using CustomComputeFnReturnStatus = Status (CustomOp::*)(Args...); - - using MyType = OrtLiteCustomStruct; - - struct Kernel { - size_t num_input_{}; - size_t num_output_{}; - std::unique_ptr custom_op_; - std::string ep_{}; - }; - - OrtLiteCustomStruct(const char* op_name, - const char* execution_provider, - int start_ver = 1, - int end_ver = MAX_CUSTOM_OP_END_VER) : OrtLiteCustomOp(op_name, execution_provider, {}, start_ver, end_ver) { - SetCompute(&CustomOp::Compute); - - OrtCustomOp::CreateKernel = [](const OrtCustomOp* this_, const OrtApi* ort_api, const OrtKernelInfo* info) { - auto kernel = std::make_unique(); - Ort::ThrowOnError(ort_api->KernelInfo_GetInputCount(info, &kernel->num_input_)); - Ort::ThrowOnError(ort_api->KernelInfo_GetOutputCount(info, &kernel->num_output_)); - kernel->custom_op_ = std::make_unique(ort_api, info); - auto self = static_cast(this_); - kernel->ep_ = self->execution_provider_; - return reinterpret_cast(kernel.release()); - }; - - OrtCustomOp::KernelDestroy = [](void* op_kernel) { - delete reinterpret_cast(op_kernel); - }; - - SetShapeInfer(0); - } - - template - void SetCompute(CustomComputeFn) { - ParseArgs(input_types_, output_types_); - OrtCustomOp::KernelCompute = [](void* op_kernel, OrtKernelContext* context) { - auto kernel = reinterpret_cast(op_kernel); - ArgPtrs args; - auto t = CreateTuple<0, 0, Args...>(context, args, kernel->num_input_, kernel->num_output_, kernel->ep_); - std::apply([kernel](Args const&... t_args) { kernel->custom_op_->Compute(t_args...); }, t); - }; - } - - template - void SetCompute(CustomComputeFnReturnStatus) { - ParseArgs(input_types_, output_types_); - OrtCustomOp::KernelComputeV2 = [](void* op_kernel, OrtKernelContext* context) -> OrtStatusPtr { - auto kernel = reinterpret_cast(op_kernel); - ArgPtrs args; - auto t = CreateTuple<0, 0, Args...>(context, args, kernel->num_input_, kernel->num_output_, kernel->ep_); - return std::apply([kernel](Args const&... t_args) { Status status = kernel->custom_op_->Compute(t_args...); return status.release(); }, t); - }; - } - - template - decltype(&C::InferOutputShape) SetShapeInfer(decltype(&C::InferOutputShape)) { - OrtCustomOp::InferOutputShapeFn = [](const OrtCustomOp*, OrtShapeInferContext* ort_ctx) -> OrtStatusPtr { - ShapeInferContext ctx(&GetApi(), ort_ctx); - return C::InferOutputShape(ctx); - }; - return {}; - } - - template - void SetShapeInfer(...) { - OrtCustomOp::InferOutputShapeFn = {}; - } -}; // struct OrtLiteCustomStruct - -/////////////////////////// CreateLiteCustomOp //////////////////////////// - -template -OrtLiteCustomOp* CreateLiteCustomOp(const char* op_name, - const char* execution_provider, - void (*custom_compute_fn)(Args...), - Status (*shape_infer_fn)(ShapeInferContext&) = {}, - int start_ver = 1, - int end_ver = MAX_CUSTOM_OP_END_VER) { - using LiteOp = OrtLiteCustomFunc; - return std::make_unique(op_name, execution_provider, custom_compute_fn, shape_infer_fn, start_ver, end_ver).release(); -} - -template -OrtLiteCustomOp* CreateLiteCustomOp(const char* op_name, - const char* execution_provider, - Status (*custom_compute_fn_v2)(Args...), - Status (*shape_infer_fn)(ShapeInferContext&) = {}, - int start_ver = 1, - int end_ver = MAX_CUSTOM_OP_END_VER) { - using LiteOp = OrtLiteCustomFunc; - return std::make_unique(op_name, execution_provider, custom_compute_fn_v2, shape_infer_fn, start_ver, end_ver).release(); -} - -template -OrtLiteCustomOp* CreateLiteCustomOp(const char* op_name, - const char* execution_provider, - int start_ver = 1, - int end_ver = MAX_CUSTOM_OP_END_VER) { - using LiteOp = OrtLiteCustomStruct; - return std::make_unique(op_name, execution_provider, start_ver, end_ver).release(); -} - -} // namespace Custom -} // namespace Ort +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// Summary +// The header has APIs to save custom op authors the trouble of defining schemas, +// which will be inferred by functions' signature, as long as their argument list has types supported here. +// Input could be: +// 1. Tensor of onnx data types. +// 2. Span of onnx data types. +// 3. Scalar of onnx data types. +// A input could be optional if indicated as std::optional<...>. +// For an output, it must be a tensor of onnx data types. +// Further, the header also has utility for a simple custom struct, where resources could be kept, to be registered as a custom op. +// For concrete examples, please search keyword "LiteCustomOpTest" under "/onnxruntime/test/". +// Note - all APIs in this header are ABI. + +#pragma once +#include "onnxruntime_cxx_api.h" +#include +#include +#include +#include + +namespace Ort { +namespace Custom { + +class ArgBase { + public: + ArgBase(OrtKernelContext* ctx, + size_t indice, + bool is_input) : ctx_(ctx), indice_(indice), is_input_(is_input) {} + virtual ~ArgBase() {}; + + protected: + struct KernelContext ctx_; + size_t indice_; + bool is_input_; +}; + +using ArgPtr = std::unique_ptr; +using ArgPtrs = std::vector; + +class TensorBase : public ArgBase { + public: + TensorBase(OrtKernelContext* ctx, + size_t indice, + bool is_input) : ArgBase(ctx, indice, is_input) {} + + operator bool() const { + return shape_.has_value(); + } + + const std::vector& Shape() const { + if (!shape_.has_value()) { + ORT_CXX_API_THROW("tensor shape is not yet initialized", OrtErrorCode::ORT_RUNTIME_EXCEPTION); + } + return shape_.value(); + } + + ONNXTensorElementDataType Type() const { + return type_; + } + + int64_t NumberOfElement() const { + if (shape_.has_value()) { + return std::accumulate(shape_->begin(), shape_->end(), 1LL, std::multiplies()); + } else { + return 0; + } + } + + std::string Shape2Str() const { + if (shape_.has_value()) { + std::string shape_str; + for (const auto& dim : *shape_) { + shape_str.append(std::to_string(dim)); + shape_str.append(", "); + } + return shape_str; + } else { + return "empty"; + } + } + + bool IsCpuTensor() const { + return strcmp("Cpu", mem_type_) == 0; + } + + virtual const void* DataRaw() const = 0; + virtual size_t SizeInBytes() const = 0; + + protected: + std::optional> shape_; + ONNXTensorElementDataType type_ = ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED; + const char* mem_type_ = "Cpu"; +}; + +template +struct Span { + const T* data_ = {}; + size_t size_ = {}; + void Assign(const T* data, size_t size) { + data_ = data; + size_ = size; + } + size_t size() const { return size_; } + T operator[](size_t indice) const { + return data_[indice]; + } + const T* data() const { return data_; } +}; + +template +class Tensor : public TensorBase { + public: + using TT = typename std::remove_reference::type; + Tensor(OrtKernelContext* ctx, size_t indice, bool is_input) : TensorBase(ctx, indice, is_input) { + if (is_input_) { + if (indice >= ctx_.GetInputCount()) { + ORT_CXX_API_THROW("invalid indice for Ort::Custom::Tensor", OrtErrorCode::ORT_INVALID_ARGUMENT); + } + const_value_ = ctx_.GetInput(indice); + auto type_shape_info = const_value_.GetTensorTypeAndShapeInfo(); + shape_ = type_shape_info.GetShape(); + } + } + const TT* Data() const { + return reinterpret_cast(const_value_.GetTensorRawData()); + } + TT* Allocate(const std::vector& shape) { + shape_ = shape; + if (!data_) { + shape_ = shape; + data_ = ctx_.GetOutput(indice_, shape).template GetTensorMutableData(); + } + return data_; + } + static TT GetT() { return (TT)0; } + const Span& AsSpan() { + if (!shape_.has_value() || shape_->size() != 1) { + ORT_CXX_API_THROW("invalid shape while trying to get a span out of Ort::Custom::Tensor", + OrtErrorCode::ORT_RUNTIME_EXCEPTION); + } + span_.Assign(Data(), static_cast((*shape_)[0])); + return span_; + } + const T& AsScalar() { + if (!shape_.has_value() || shape_->size() != 1 || (*shape_)[0] != 1) { + ORT_CXX_API_THROW("invalid shape while trying to get a scalar from Ort::Custom::Tensor", + OrtErrorCode::ORT_RUNTIME_EXCEPTION); + } + return *Data(); + } + const void* DataRaw() const override { + return reinterpret_cast(Data()); + } + + size_t SizeInBytes() const override { + return sizeof(TT) * static_cast(NumberOfElement()); + } + + private: + ConstValue const_value_; // for input + TT* data_{}; // for output + Span span_; +}; + +template <> +class Tensor : public TensorBase { + public: + using strings = std::vector; + + Tensor(OrtKernelContext* ctx, size_t indice, bool is_input) : TensorBase(ctx, indice, is_input) { + if (is_input_) { + if (indice >= ctx_.GetInputCount()) { + ORT_CXX_API_THROW("invalid indice for Ort::Custom::Tensor", OrtErrorCode::ORT_INVALID_ARGUMENT); + } + auto const_value = ctx_.GetInput(indice); + auto type_shape_info = const_value.GetTensorTypeAndShapeInfo(); + shape_ = type_shape_info.GetShape(); + auto num_chars = const_value.GetStringTensorDataLength(); + // note - there will be copy ... + auto num_strings = static_cast(NumberOfElement()); + if (num_strings) { + std::vector chars(num_chars + 1, '\0'); + std::vector offsets(num_strings); + const_value.GetStringTensorContent(static_cast(chars.data()), num_chars, offsets.data(), offsets.size()); + auto upper_bound = num_strings - 1; + input_strings_.resize(num_strings); + for (size_t i = upper_bound;; --i) { + if (i < upper_bound) { + chars[offsets[i + 1]] = '\0'; + } + input_strings_[i] = chars.data() + offsets[i]; + if (0 == i) { + break; + } + } + } + } + } + const strings& Data() const { + return input_strings_; + } + const void* DataRaw() const override { + if (input_strings_.size() != 1) { + ORT_CXX_API_THROW("DataRaw() only applies to string scalar", ORT_RUNTIME_EXCEPTION); + } + return reinterpret_cast(input_strings_[0].c_str()); + } + size_t SizeInBytes() const override { + if (input_strings_.size() != 1) { + ORT_CXX_API_THROW("SizeInBytes() only applies to string scalar", ORT_RUNTIME_EXCEPTION); + } + return input_strings_[0].size(); + } + void SetStringOutput(const strings& ss, const std::vector& dims) { + shape_ = dims; + std::vector raw; + for (const auto& s : ss) { + raw.push_back(s.data()); + } + auto output = ctx_.GetOutput(indice_, dims.data(), dims.size()); + // note - there will be copy ... + output.FillStringTensor(raw.data(), raw.size()); + } + const Span& AsSpan() { + ORT_CXX_API_THROW("span for TensorT of string not implemented", OrtErrorCode::ORT_RUNTIME_EXCEPTION); + } + const std::string& AsScalar() { + if (input_strings_.size() != 1) { + ORT_CXX_API_THROW("invalid shape while trying to get a scalar string from Ort::Custom::Tensor", + OrtErrorCode::ORT_RUNTIME_EXCEPTION); + } + return input_strings_[0]; + } + + private: + std::vector input_strings_; // for input +}; + +template <> +class Tensor : public TensorBase { + public: + using strings = std::vector; + using string_views = std::vector; + + Tensor(OrtKernelContext* ctx, size_t indice, bool is_input) : TensorBase(ctx, indice, is_input) { + if (is_input_) { + if (indice >= ctx_.GetInputCount()) { + ORT_CXX_API_THROW("invalid indice for Ort::Custom::Tensor", OrtErrorCode::ORT_INVALID_ARGUMENT); + } + auto const_value = ctx_.GetInput(indice); + auto type_shape_info = const_value.GetTensorTypeAndShapeInfo(); + shape_ = type_shape_info.GetShape(); + auto num_chars = const_value.GetStringTensorDataLength(); + chars_.resize(num_chars + 1, '\0'); + auto num_strings = static_cast(NumberOfElement()); + if (num_strings) { + std::vector offsets(num_strings); + const_value.GetStringTensorContent(static_cast(chars_.data()), num_chars, offsets.data(), offsets.size()); + offsets.push_back(num_chars); + for (size_t i = 0; i < num_strings; ++i) { + input_string_views_.emplace_back(chars_.data() + offsets[i], offsets[i + 1] - offsets[i]); + } + } + } + } + const string_views& Data() const { + return input_string_views_; + } + const void* DataRaw() const override { + if (input_string_views_.size() != 1) { + ORT_CXX_API_THROW("DataRaw() only applies to string scalar", ORT_RUNTIME_EXCEPTION); + } + return reinterpret_cast(input_string_views_[0].data()); + } + size_t SizeInBytes() const override { + if (input_string_views_.size() != 1) { + ORT_CXX_API_THROW("SizeInBytes() only applies to string scalar", ORT_RUNTIME_EXCEPTION); + } + return input_string_views_[0].size(); + } + void SetStringOutput(const strings& ss, const std::vector& dims) { + shape_ = dims; + std::vector raw; + for (const auto& s : ss) { + raw.push_back(s.data()); + } + auto output = ctx_.GetOutput(indice_, dims.data(), dims.size()); + // note - there will be copy ... + output.FillStringTensor(raw.data(), raw.size()); + } + const Span& AsSpan() { + ORT_CXX_API_THROW("span for TensorT of string view not implemented", OrtErrorCode::ORT_RUNTIME_EXCEPTION); + } + std::string_view AsScalar() { + if (input_string_views_.size() != 1) { + ORT_CXX_API_THROW("invalid shape while trying to get a scalar string view from Ort::Custom::Tensor", + OrtErrorCode::ORT_RUNTIME_EXCEPTION); + } + return input_string_views_[0]; + } + + private: + std::vector chars_; // for input + std::vector input_string_views_; // for input +}; + +using TensorPtr = std::unique_ptr; +using TensorPtrs = std::vector; + +struct TensorArray : public ArgBase { + TensorArray(OrtKernelContext* ctx, + size_t start_indice, + bool is_input) : ArgBase(ctx, + start_indice, + is_input) { + if (is_input) { + auto input_count = ctx_.GetInputCount(); + for (size_t ith_input = start_indice; ith_input < input_count; ++ith_input) { + auto const_value = ctx_.GetInput(start_indice); + auto type_shape_info = const_value.GetTensorTypeAndShapeInfo(); + auto type = type_shape_info.GetElementType(); + TensorPtr tensor; + switch (type) { + case ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL: + tensor = std::make_unique>(ctx, ith_input, true); + break; + case ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT: + tensor = std::make_unique>(ctx, ith_input, true); + break; + case ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE: + tensor = std::make_unique>(ctx, ith_input, true); + break; + case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8: + tensor = std::make_unique>(ctx, ith_input, true); + break; + case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8: + tensor = std::make_unique>(ctx, ith_input, true); + break; + case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16: + tensor = std::make_unique>(ctx, ith_input, true); + break; + case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16: + tensor = std::make_unique>(ctx, ith_input, true); + break; + case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32: + tensor = std::make_unique>(ctx, ith_input, true); + break; + case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32: + tensor = std::make_unique>(ctx, ith_input, true); + break; + case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64: + tensor = std::make_unique>(ctx, ith_input, true); + break; + case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64: + tensor = std::make_unique>(ctx, ith_input, true); + break; + case ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING: + tensor = std::make_unique>(ctx, ith_input, true); + break; + default: + ORT_CXX_API_THROW("unknow input type", ORT_RUNTIME_EXCEPTION); + break; + } + tensors_.emplace_back(tensor.release()); + } // for + } + } + template + T* AllocateOutput(size_t ith_output, const std::vector& shape) { + // ith_output is the indice of output relative to the tensor array + // indice_ + ith_output is the indice relative to context + auto tensor = std::make_unique>(ctx_.GetOrtKernelContext(), indice_ + ith_output, false); + auto raw_output = tensor.get()->Allocate(shape); + tensors_.emplace_back(tensor.release()); + return raw_output; + } + Tensor& AllocateStringTensor(size_t ith_output) { + // ith_output is the indice of output relative to the tensor array + // indice_ + ith_output is the indice relative to context + auto tensor = std::make_unique>(ctx_.GetOrtKernelContext(), indice_ + ith_output, false); + Tensor& output = *tensor; + tensors_.emplace_back(tensor.release()); + return output; + } + size_t Size() const { + return tensors_.size(); + } + const TensorPtr& operator[](size_t ith_input) const { + // ith_input is the indice of output relative to the tensor array + return tensors_.at(ith_input); + } + + private: + TensorPtrs tensors_; +}; + +using Variadic = TensorArray; + +/* +Note: +OrtLiteCustomOp inherits from OrtCustomOp to bridge tween a custom func/struct and ort core. +The lifetime of an OrtLiteCustomOp instance is managed by customer code, not ort, so: +1. DO NOT cast OrtLiteCustomOp to OrtCustomOp and release since there is no virtual destructor in the hierarchy. +2. OrtLiteCustomFunc and OrtLiteCustomStruct, as two sub-structs, can be released in form of OrtLiteCustomOp since all members are kept in the OrtLiteCustomOp, + hence memory could still be recycled properly. +Further, OrtCustomOp is a c struct bearing no v-table, so offspring structs are by design to be of zero virtual functions to maintain cast safety. +*/ +struct OrtLiteCustomOp : public OrtCustomOp { + using ConstOptionalFloatTensor = std::optional&>; + using OptionalFloatTensor = std::optional>; + + // CreateTuple + template + static typename std::enable_if>::type + CreateTuple(OrtKernelContext*, ArgPtrs&, size_t, size_t, const std::string&) { + return std::make_tuple(); + } + + template + static typename std::enable_if::value, std::tuple>::type + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { + std::tuple current = std::tuple{context}; + auto next = CreateTuple(context, args, num_input, num_output, ep); + return std::tuple_cat(current, next); + } + + template + static typename std::enable_if::value, std::tuple>::type + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { + std::tuple current = std::tuple{*context}; + auto next = CreateTuple(context, args, num_input, num_output, ep); + return std::tuple_cat(current, next); + } + +#ifdef ORT_CUDA_CTX + template + static typename std::enable_if::value, std::tuple>::type + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { + thread_local CudaContext cuda_context; + cuda_context.Init(*context); + std::tuple current = std::tuple{cuda_context}; + auto next = CreateTuple(context, args, num_input, num_output, ep); + return std::tuple_cat(current, next); + } +#endif + +#ifdef ORT_ROCM_CTX + template + static typename std::enable_if::value, std::tuple>::type + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { + thread_local RocmContext rocm_context; + rocm_context.Init(*context); + std::tuple current = std::tuple{rocm_context}; + auto next = CreateTuple(context, args, num_input, num_output, ep); + return std::tuple_cat(current, next); + } +#endif + + template + static typename std::enable_if::value, std::tuple>::type + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { + args.push_back(std::make_unique(context, ith_input, true)); + std::tuple current = std::tuple{reinterpret_cast(args.back().get())}; + auto next = CreateTuple(context, args, num_input, num_output, ep); + return std::tuple_cat(current, next); + } + + template + static typename std::enable_if::value, std::tuple>::type + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { + args.push_back(std::make_unique(context, ith_input, true)); + std::tuple current = std::tuple{reinterpret_cast(*args.back().get())}; + auto next = CreateTuple(context, args, num_input, num_output, ep); + return std::tuple_cat(current, next); + } + + template + static typename std::enable_if::value, std::tuple>::type + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { + args.push_back(std::make_unique(context, ith_output, false)); + std::tuple current = std::tuple{reinterpret_cast(args.back().get())}; + auto next = CreateTuple(context, args, num_input, num_output, ep); + return std::tuple_cat(current, next); + } + + template + static typename std::enable_if::value, std::tuple>::type + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { + args.push_back(std::make_unique(context, ith_output, false)); + std::tuple current = std::tuple{reinterpret_cast(*args.back().get())}; + auto next = CreateTuple(context, args, num_input, num_output, ep); + return std::tuple_cat(current, next); + } + +#define CREATE_TUPLE_INPUT(data_type) \ + template \ + static typename std::enable_if*>::value, std::tuple>::type \ + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ + args.push_back(std::make_unique>(context, ith_input, true)); \ + std::tuple current = std::tuple{reinterpret_cast(args.back().get())}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } \ + template \ + static typename std::enable_if&>::value, std::tuple>::type \ + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ + args.push_back(std::make_unique>(context, ith_input, true)); \ + std::tuple current = std::tuple{reinterpret_cast(*args.back().get())}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } \ + template \ + static typename std::enable_if*>>::value, std::tuple>::type \ + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ + if (ith_input < num_input) { \ + args.push_back(std::make_unique>(context, ith_input, true)); \ + std::tuple current = std::tuple{reinterpret_cast*>(args.back().get())}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } else { \ + std::tuple current = std::tuple{}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } \ + } \ + template \ + static typename std::enable_if*>::value, std::tuple>::type \ + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ + if ("CPUExecutionProvider" != ep) { \ + ORT_CXX_API_THROW("span input could only be applied to CPU EP", OrtErrorCode::ORT_RUNTIME_EXCEPTION); \ + } \ + args.push_back(std::make_unique>(context, ith_input, true)); \ + std::tuple current = std::tuple{&reinterpret_cast*>(args.back().get())->AsSpan()}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } \ + template \ + static typename std::enable_if&>::value, std::tuple>::type \ + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ + if ("CPUExecutionProvider" != ep) { \ + ORT_CXX_API_THROW("span input could only be applied to CPU EP", OrtErrorCode::ORT_RUNTIME_EXCEPTION); \ + } \ + args.push_back(std::make_unique>(context, ith_input, true)); \ + std::tuple current = std::tuple{reinterpret_cast*>(args.back().get())->AsSpan()}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } \ + template \ + static typename std::enable_if*>>::value, std::tuple>::type \ + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ + if (ith_input < num_input) { \ + if ("CPUExecutionProvider" != ep) { \ + ORT_CXX_API_THROW("span input could only be applied to CPU EP", OrtErrorCode::ORT_RUNTIME_EXCEPTION); \ + } \ + args.push_back(std::make_unique>(context, ith_input, true)); \ + std::tuple current = std::tuple{&reinterpret_cast*>(args.back().get())->AsSpan()}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } else { \ + std::tuple current = std::tuple{}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } \ + } \ + template \ + static typename std::enable_if::value, std::tuple>::type \ + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ + if ("CPUExecutionProvider" != ep) { \ + ORT_CXX_API_THROW("scalar input could only be applied to CPU EP", OrtErrorCode::ORT_RUNTIME_EXCEPTION); \ + } \ + args.push_back(std::make_unique>(context, ith_input, true)); \ + std::tuple current = std::tuple{reinterpret_cast*>(args.back().get())->AsScalar()}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } \ + template \ + static typename std::enable_if>::value, std::tuple>::type \ + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ + if (ith_input < num_input) { \ + if ("CPUExecutionProvider" != ep) { \ + ORT_CXX_API_THROW("scalar input could only be applied to CPU EP", OrtErrorCode::ORT_RUNTIME_EXCEPTION); \ + } \ + args.push_back(std::make_unique>(context, ith_input, true)); \ + std::tuple current = std::tuple{reinterpret_cast*>(args.back().get())->AsScalar()}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } else { \ + std::tuple current = std::tuple{}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } \ + } +#define CREATE_TUPLE_OUTPUT(data_type) \ + template \ + static typename std::enable_if*>::value, std::tuple>::type \ + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ + args.push_back(std::make_unique>(context, ith_output, false)); \ + std::tuple current = std::tuple{reinterpret_cast(args.back().get())}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } \ + template \ + static typename std::enable_if&>::value, std::tuple>::type \ + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ + args.push_back(std::make_unique>(context, ith_output, false)); \ + std::tuple current = std::tuple{reinterpret_cast(*args.back().get())}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } \ + template \ + static typename std::enable_if*>>::value, std::tuple>::type \ + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ + if (ith_output < num_output) { \ + args.push_back(std::make_unique>(context, ith_output, false)); \ + std::tuple current = std::tuple{reinterpret_cast*>(args.back().get())}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } else { \ + std::tuple current = std::tuple{}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } \ + } +#define CREATE_TUPLE(data_type) \ + CREATE_TUPLE_INPUT(data_type) \ + CREATE_TUPLE_OUTPUT(data_type) + + CREATE_TUPLE(bool) + CREATE_TUPLE(float) + CREATE_TUPLE(Ort::Float16_t) + CREATE_TUPLE(Ort::BFloat16_t) + CREATE_TUPLE(double) + CREATE_TUPLE(int8_t) + CREATE_TUPLE(int16_t) + CREATE_TUPLE(int32_t) + CREATE_TUPLE(int64_t) + CREATE_TUPLE(uint8_t) + CREATE_TUPLE(uint16_t) + CREATE_TUPLE(uint32_t) + CREATE_TUPLE(uint64_t) + CREATE_TUPLE(std::string) + CREATE_TUPLE_INPUT(std::string_view) + CREATE_TUPLE(Ort::Float8E4M3FN_t) + CREATE_TUPLE(Ort::Float8E4M3FNUZ_t) + CREATE_TUPLE(Ort::Float8E5M2_t) + CREATE_TUPLE(Ort::Float8E5M2FNUZ_t) + + // ParseArgs ... + template + static typename std::enable_if<0 == sizeof...(Ts)>::type + ParseArgs(std::vector&, std::vector&) { + } + + template + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type + ParseArgs(std::vector& input_types, std::vector& output_types) { + ParseArgs(input_types, output_types); + } + + template + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type + ParseArgs(std::vector& input_types, std::vector& output_types) { + ParseArgs(input_types, output_types); + } + +#ifdef ORT_CUDA_CTX + template + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type + ParseArgs(std::vector& input_types, std::vector& output_types) { + ParseArgs(input_types, output_types); + } +#endif + +#ifdef ORT_ROCM_CTX + template + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type + ParseArgs(std::vector& input_types, std::vector& output_types) { + ParseArgs(input_types, output_types); + } +#endif + + template + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type + ParseArgs(std::vector& input_types, std::vector& output_types) { + input_types.push_back(ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED); + ParseArgs(input_types, output_types); + } + + template + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type + ParseArgs(std::vector& input_types, std::vector& output_types) { + input_types.push_back(ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED); + ParseArgs(input_types, output_types); + } + + template + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type + ParseArgs(std::vector& input_types, std::vector& output_types) { + output_types.push_back(ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED); + ParseArgs(input_types, output_types); + } + + template + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type + ParseArgs(std::vector& input_types, std::vector& output_types) { + output_types.push_back(ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED); + ParseArgs(input_types, output_types); + } + +#define PARSE_INPUT_BASE(pack_type, onnx_type) \ + template \ + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type \ + ParseArgs(std::vector& input_types, std::vector& output_types) { \ + input_types.push_back(onnx_type); \ + ParseArgs(input_types, output_types); \ + } \ + template \ + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same>::value>::type \ + ParseArgs(std::vector& input_types, std::vector& output_types) { \ + input_types.push_back(onnx_type); \ + ParseArgs(input_types, output_types); \ + } \ + template \ + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same>::value>::type \ + ParseArgs(std::vector& input_types, std::vector& output_types) { \ + input_types.push_back(onnx_type); \ + ParseArgs(input_types, output_types); \ + } + +#define PARSE_INPUT(data_type, onnx_type) \ + PARSE_INPUT_BASE(const Custom::Tensor*, onnx_type) \ + PARSE_INPUT_BASE(const Custom::Tensor&, onnx_type) \ + PARSE_INPUT_BASE(const Custom::Span*, onnx_type) \ + PARSE_INPUT_BASE(const Custom::Span&, onnx_type) \ + PARSE_INPUT_BASE(data_type, onnx_type) + +#define PARSE_OUTPUT(data_type, onnx_type) \ + template \ + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same*>::value>::type \ + ParseArgs(std::vector& input_types, std::vector& output_types) { \ + output_types.push_back(onnx_type); \ + ParseArgs(input_types, output_types); \ + } \ + template \ + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same&>::value>::type \ + ParseArgs(std::vector& input_types, std::vector& output_types) { \ + output_types.push_back(onnx_type); \ + ParseArgs(input_types, output_types); \ + } \ + template \ + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same*>>::value>::type \ + ParseArgs(std::vector& input_types, std::vector& output_types) { \ + output_types.push_back(onnx_type); \ + ParseArgs(input_types, output_types); \ + } + +#define PARSE_ARGS(data_type, onnx_type) \ + PARSE_INPUT(data_type, onnx_type) \ + PARSE_OUTPUT(data_type, onnx_type) + + PARSE_ARGS(bool, ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL) + PARSE_ARGS(float, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT) + PARSE_ARGS(Ort::Float16_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16) + PARSE_ARGS(Ort::BFloat16_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_BFLOAT16) + PARSE_ARGS(double, ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE) + PARSE_ARGS(int8_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8) + PARSE_ARGS(int16_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16) + PARSE_ARGS(int32_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32) + PARSE_ARGS(int64_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64) + PARSE_ARGS(uint8_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8) + PARSE_ARGS(uint16_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16) + PARSE_ARGS(uint32_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32) + PARSE_ARGS(uint64_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64) + PARSE_ARGS(std::string, ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING) + PARSE_ARGS(std::string_view, ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING) // todo - remove string_view output + PARSE_ARGS(Ort::Float8E4M3FN_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FN) + PARSE_ARGS(Ort::Float8E4M3FNUZ_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FNUZ) + PARSE_ARGS(Ort::Float8E5M2_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2) + PARSE_ARGS(Ort::Float8E5M2FNUZ_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2FNUZ) + + OrtLiteCustomOp(const char* op_name, + const char* execution_provider, + ShapeInferFn shape_infer_fn, + int start_ver = 1, + int end_ver = MAX_CUSTOM_OP_END_VER) : op_name_(op_name), + execution_provider_(execution_provider), + shape_infer_fn_(shape_infer_fn), + start_ver_(start_ver), + end_ver_(end_ver) { + OrtCustomOp::version = ORT_API_VERSION; + + OrtCustomOp::GetName = [](const OrtCustomOp* op) { return static_cast(op)->op_name_.c_str(); }; + OrtCustomOp::GetExecutionProviderType = [](const OrtCustomOp* op) { return ((OrtLiteCustomOp*)op)->execution_provider_.c_str(); }; + OrtCustomOp::GetInputMemoryType = [](const OrtCustomOp*, size_t) { return OrtMemTypeDefault; }; + + OrtCustomOp::GetInputTypeCount = [](const OrtCustomOp* op) { + auto self = reinterpret_cast(op); + return self->input_types_.size(); + }; + + OrtCustomOp::GetInputType = [](const OrtCustomOp* op, size_t indice) { + auto self = reinterpret_cast(op); + return self->input_types_[indice]; + }; + + OrtCustomOp::GetOutputTypeCount = [](const OrtCustomOp* op) { + auto self = reinterpret_cast(op); + return self->output_types_.size(); + }; + + OrtCustomOp::GetOutputType = [](const OrtCustomOp* op, size_t indice) { + auto self = reinterpret_cast(op); + return self->output_types_[indice]; + }; + + OrtCustomOp::GetInputCharacteristic = [](const OrtCustomOp* op, size_t indice) { + auto self = reinterpret_cast(op); + return self->input_types_[indice] == ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED ? INPUT_OUTPUT_VARIADIC : INPUT_OUTPUT_OPTIONAL; + }; + + OrtCustomOp::GetOutputCharacteristic = [](const OrtCustomOp* op, size_t indice) { + auto self = reinterpret_cast(op); + return self->output_types_[indice] == ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED ? INPUT_OUTPUT_VARIADIC : INPUT_OUTPUT_OPTIONAL; + }; + + OrtCustomOp::GetVariadicInputMinArity = [](const OrtCustomOp*) { + return 1; + }; + + OrtCustomOp::GetVariadicInputHomogeneity = [](const OrtCustomOp*) { + return 0; + }; + + OrtCustomOp::GetVariadicOutputMinArity = [](const OrtCustomOp*) { + return 1; + }; + + OrtCustomOp::GetVariadicOutputHomogeneity = [](const OrtCustomOp*) { + return 0; + }; + + OrtCustomOp::GetVariadicInputMinArity = [](const OrtCustomOp*) { return 0; }; + OrtCustomOp::GetVariadicInputHomogeneity = [](const OrtCustomOp*) { return 0; }; + OrtCustomOp::GetVariadicOutputMinArity = [](const OrtCustomOp*) { return 0; }; + OrtCustomOp::GetVariadicOutputHomogeneity = [](const OrtCustomOp*) { return 0; }; + + OrtCustomOp::CreateKernelV2 = {}; + OrtCustomOp::KernelComputeV2 = {}; + OrtCustomOp::KernelCompute = {}; + + OrtCustomOp::InferOutputShapeFn = {}; + + OrtCustomOp::GetStartVersion = [](const OrtCustomOp* op) { + auto self = reinterpret_cast(op); + return self->start_ver_; + }; + + OrtCustomOp::GetEndVersion = [](const OrtCustomOp* op) { + auto self = reinterpret_cast(op); + return self->end_ver_; + }; + + OrtCustomOp::GetMayInplace = {}; + OrtCustomOp::ReleaseMayInplace = {}; + OrtCustomOp::GetAliasMap = {}; + OrtCustomOp::ReleaseAliasMap = {}; + } + + const std::string op_name_; + const std::string execution_provider_; + + std::vector input_types_; + std::vector output_types_; + + ShapeInferFn shape_infer_fn_ = {}; + + int start_ver_ = 1; + int end_ver_ = MAX_CUSTOM_OP_END_VER; + + void* compute_fn_ = {}; + void* compute_fn_return_status_ = {}; +}; + +//////////////////////////// OrtLiteCustomFunc //////////////////////////////// +// The struct is to implement function-as-op. +// E.g. a function might be defined as: +// void Filter(const Ort::Custom::Tensor& floats_in, Ort::Custom::Tensor& floats_out) { ... } +// It could be registered this way: +// Ort::CustomOpDomain v2_domain{"v2"}; +// std::unique_ptr fil_op_ptr{Ort::Custom::CreateLiteCustomOp("Filter", "CPUExecutionProvider", Filter)}; +// v2_domain.Add(fil_op_ptr.get()); +// session_options.Add(v2_domain); +// For the complete example, please search keyword "LiteCustomOpTest" under "/onnxruntime/test/". +template +struct OrtLiteCustomFunc : public OrtLiteCustomOp { + using ComputeFn = void (*)(Args...); + using ComputeFnReturnStatus = Status (*)(Args...); + using MyType = OrtLiteCustomFunc; + + struct Kernel { + size_t num_input_{}; + size_t num_output_{}; + ComputeFn compute_fn_{}; + ComputeFnReturnStatus compute_fn_return_status_{}; + std::string ep_{}; + }; + + OrtLiteCustomFunc(const char* op_name, + const char* execution_provider, + ComputeFn compute_fn, + ShapeInferFn shape_infer_fn = {}, + int start_ver = 1, + int end_ver = MAX_CUSTOM_OP_END_VER) : OrtLiteCustomOp(op_name, execution_provider, shape_infer_fn, start_ver, end_ver) { + compute_fn_ = reinterpret_cast(compute_fn); + ParseArgs(input_types_, output_types_); + + OrtCustomOp::KernelCompute = [](void* op_kernel, OrtKernelContext* context) { + auto kernel = reinterpret_cast(op_kernel); + std::vector args; + auto t = CreateTuple<0, 0, Args...>(context, args, kernel->num_input_, kernel->num_output_, kernel->ep_); + std::apply([kernel](Args const&... t_args) { kernel->compute_fn_(t_args...); }, t); + }; + + OrtCustomOp::CreateKernel = [](const OrtCustomOp* this_, const OrtApi* ort_api, const OrtKernelInfo* info) { + auto kernel = std::make_unique(); + auto me = static_cast(this_); + kernel->compute_fn_ = reinterpret_cast(me->compute_fn_); + Ort::ThrowOnError(ort_api->KernelInfo_GetInputCount(info, &kernel->num_input_)); + Ort::ThrowOnError(ort_api->KernelInfo_GetOutputCount(info, &kernel->num_output_)); + auto self = static_cast(this_); + kernel->ep_ = self->execution_provider_; + return reinterpret_cast(kernel.release()); + }; + + OrtCustomOp::KernelDestroy = [](void* op_kernel) { + delete reinterpret_cast(op_kernel); + }; + + if (shape_infer_fn_) { + OrtCustomOp::InferOutputShapeFn = [](const OrtCustomOp* op, OrtShapeInferContext* ort_ctx) -> OrtStatusPtr { + auto shape_info_fn = static_cast(op)->shape_infer_fn_; + ShapeInferContext ctx(&GetApi(), ort_ctx); + return shape_info_fn(ctx); + }; + } + } + + OrtLiteCustomFunc(const char* op_name, + const char* execution_provider, + ComputeFnReturnStatus compute_fn_return_status, + ShapeInferFn shape_infer_fn = {}, + int start_ver = 1, + int end_ver = MAX_CUSTOM_OP_END_VER) : OrtLiteCustomOp(op_name, execution_provider, shape_infer_fn, start_ver, end_ver) { + compute_fn_return_status_ = reinterpret_cast(compute_fn_return_status); + ParseArgs(input_types_, output_types_); + + OrtCustomOp::KernelComputeV2 = [](void* op_kernel, OrtKernelContext* context) -> OrtStatusPtr { + auto kernel = reinterpret_cast(op_kernel); + std::vector args; + auto t = CreateTuple<0, 0, Args...>(context, args, kernel->num_input_, kernel->num_output_, kernel->ep_); + return std::apply([kernel](Args const&... t_args) { Status status = kernel->compute_fn_return_status_(t_args...); return status.release(); }, t); + }; + + OrtCustomOp::CreateKernel = [](const OrtCustomOp* this_, const OrtApi* ort_api, const OrtKernelInfo* info) { + auto kernel = std::make_unique(); + auto me = static_cast(this_); + kernel->compute_fn_return_status_ = reinterpret_cast(me->compute_fn_return_status_); + Ort::ThrowOnError(ort_api->KernelInfo_GetInputCount(info, &kernel->num_input_)); + Ort::ThrowOnError(ort_api->KernelInfo_GetOutputCount(info, &kernel->num_output_)); + auto self = static_cast(this_); + kernel->ep_ = self->execution_provider_; + return reinterpret_cast(kernel.release()); + }; + + OrtCustomOp::KernelDestroy = [](void* op_kernel) { + delete reinterpret_cast(op_kernel); + }; + + if (shape_infer_fn_) { + OrtCustomOp::InferOutputShapeFn = [](const OrtCustomOp* op, OrtShapeInferContext* ort_ctx) -> OrtStatusPtr { + auto shape_info_fn = static_cast(op)->shape_infer_fn_; + ShapeInferContext ctx(&GetApi(), ort_ctx); + return shape_info_fn(ctx); + }; + } + } +}; // struct OrtLiteCustomFunc + +/////////////////////////// OrtLiteCustomStruct /////////////////////////// +// The struct is to implement struct-as-op. +// E.g. a struct might be defined as: +// struct Merge { +// Merge(const OrtApi* ort_api, const OrtKernelInfo* info) {...} +// void Compute(const Ort::Custom::Tensor& strings_in, +// std::string_view string_in, +// Ort::Custom::Tensor* strings_out) {...} +// bool reverse_ = false; +// }; +// It could be registered this way: +// Ort::CustomOpDomain v2_domain{"v2"}; +// std::unique_ptr mrg_op_ptr{Ort::Custom::CreateLiteCustomOp("Merge", "CPUExecutionProvider")}; +// v2_domain.Add(mrg_op_ptr.get()); +// session_options.Add(v2_domain); +// For the complete example, please search keyword "LiteCustomOpTest" under "/onnxruntime/test/". +template +struct OrtLiteCustomStruct : public OrtLiteCustomOp { + template + using CustomComputeFn = void (CustomOp::*)(Args...); + + template + using CustomComputeFnReturnStatus = Status (CustomOp::*)(Args...); + + using MyType = OrtLiteCustomStruct; + + struct Kernel { + size_t num_input_{}; + size_t num_output_{}; + std::unique_ptr custom_op_; + std::string ep_{}; + }; + + OrtLiteCustomStruct(const char* op_name, + const char* execution_provider, + int start_ver = 1, + int end_ver = MAX_CUSTOM_OP_END_VER) : OrtLiteCustomOp(op_name, execution_provider, {}, start_ver, end_ver) { + SetCompute(&CustomOp::Compute); + + OrtCustomOp::CreateKernel = [](const OrtCustomOp* this_, const OrtApi* ort_api, const OrtKernelInfo* info) { + auto kernel = std::make_unique(); + Ort::ThrowOnError(ort_api->KernelInfo_GetInputCount(info, &kernel->num_input_)); + Ort::ThrowOnError(ort_api->KernelInfo_GetOutputCount(info, &kernel->num_output_)); + kernel->custom_op_ = std::make_unique(ort_api, info); + auto self = static_cast(this_); + kernel->ep_ = self->execution_provider_; + return reinterpret_cast(kernel.release()); + }; + + OrtCustomOp::KernelDestroy = [](void* op_kernel) { + delete reinterpret_cast(op_kernel); + }; + + SetShapeInfer(0); + } + + template + void SetCompute(CustomComputeFn) { + ParseArgs(input_types_, output_types_); + OrtCustomOp::KernelCompute = [](void* op_kernel, OrtKernelContext* context) { + auto kernel = reinterpret_cast(op_kernel); + ArgPtrs args; + auto t = CreateTuple<0, 0, Args...>(context, args, kernel->num_input_, kernel->num_output_, kernel->ep_); + std::apply([kernel](Args const&... t_args) { kernel->custom_op_->Compute(t_args...); }, t); + }; + } + + template + void SetCompute(CustomComputeFnReturnStatus) { + ParseArgs(input_types_, output_types_); + OrtCustomOp::KernelComputeV2 = [](void* op_kernel, OrtKernelContext* context) -> OrtStatusPtr { + auto kernel = reinterpret_cast(op_kernel); + ArgPtrs args; + auto t = CreateTuple<0, 0, Args...>(context, args, kernel->num_input_, kernel->num_output_, kernel->ep_); + return std::apply([kernel](Args const&... t_args) { Status status = kernel->custom_op_->Compute(t_args...); return status.release(); }, t); + }; + } + + template + decltype(&C::InferOutputShape) SetShapeInfer(decltype(&C::InferOutputShape)) { + OrtCustomOp::InferOutputShapeFn = [](const OrtCustomOp*, OrtShapeInferContext* ort_ctx) -> OrtStatusPtr { + ShapeInferContext ctx(&GetApi(), ort_ctx); + return C::InferOutputShape(ctx); + }; + return {}; + } + + template + void SetShapeInfer(...) { + OrtCustomOp::InferOutputShapeFn = {}; + } +}; // struct OrtLiteCustomStruct + +/////////////////////////// CreateLiteCustomOp //////////////////////////// + +template +OrtLiteCustomOp* CreateLiteCustomOp(const char* op_name, + const char* execution_provider, + void (*custom_compute_fn)(Args...), + Status (*shape_infer_fn)(ShapeInferContext&) = {}, + int start_ver = 1, + int end_ver = MAX_CUSTOM_OP_END_VER) { + using LiteOp = OrtLiteCustomFunc; + return std::make_unique(op_name, execution_provider, custom_compute_fn, shape_infer_fn, start_ver, end_ver).release(); +} + +template +OrtLiteCustomOp* CreateLiteCustomOp(const char* op_name, + const char* execution_provider, + Status (*custom_compute_fn_v2)(Args...), + Status (*shape_infer_fn)(ShapeInferContext&) = {}, + int start_ver = 1, + int end_ver = MAX_CUSTOM_OP_END_VER) { + using LiteOp = OrtLiteCustomFunc; + return std::make_unique(op_name, execution_provider, custom_compute_fn_v2, shape_infer_fn, start_ver, end_ver).release(); +} + +template +OrtLiteCustomOp* CreateLiteCustomOp(const char* op_name, + const char* execution_provider, + int start_ver = 1, + int end_ver = MAX_CUSTOM_OP_END_VER) { + using LiteOp = OrtLiteCustomStruct; + return std::make_unique(op_name, execution_provider, start_ver, end_ver).release(); +} + +} // namespace Custom +} // namespace Ort diff --git a/3rdParty/ONNX/onnxruntime_run_options_config_keys.h b/3rdParty/ONNX/onnxruntime_run_options_config_keys.h index f40ea65910..bb4ce8d3fa 100644 --- a/3rdParty/ONNX/onnxruntime_run_options_config_keys.h +++ b/3rdParty/ONNX/onnxruntime_run_options_config_keys.h @@ -1,54 +1,54 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -/* - * This file defines RunOptions Config Keys and format of the Config Values. - * - * The Naming Convention for a RunOptions Config Key, - * "[Area][.[SubArea1].[SubArea2]...].[Keyname]" - * Such as "ep.cuda.use_arena" - * The Config Key cannot be empty - * The maximum length of the Config Key is 128 - * - * The string format of a RunOptions Config Value is defined individually for each Config. - * The maximum length of the Config Value is 1024 - */ - -// Key for enabling shrinkages of user listed device memory arenas. -// Expects a list of semi-colon separated key value pairs separated by colon in the following format: -// "device_0:device_id_0;device_1:device_id_1" -// No white-spaces allowed in the provided list string. -// Currently, the only supported devices are : "cpu", "gpu" (case sensitive). -// If "cpu" is included in the list, DisableCpuMemArena() API must not be called (i.e.) arena for cpu should be enabled. -// Example usage: "cpu:0;gpu:0" (or) "gpu:0" -// By default, the value for this key is empty (i.e.) no memory arenas are shrunk -static const char* const kOrtRunOptionsConfigEnableMemoryArenaShrinkage = "memory.enable_memory_arena_shrinkage"; - -// Set to '1' to not synchronize execution providers with CPU at the end of session run. -// Per default it will be set to '0' -// Taking CUDA EP as an example, it omit triggering cudaStreamSynchronize on the compute stream. -static const char* const kOrtRunOptionsConfigDisableSynchronizeExecutionProviders = "disable_synchronize_execution_providers"; - -// Set HTP performance mode for QNN HTP backend before session run. -// options for HTP performance mode: "burst", "balanced", "default", "high_performance", -// "high_power_saver", "low_balanced", "extreme_power_saver", "low_power_saver", "power_saver", -// "sustained_high_performance". Default to "default". -static const char* const kOrtRunOptionsConfigQnnPerfMode = "qnn.htp_perf_mode"; - -// Set HTP performance mode for QNN HTP backend post session run. -static const char* const kOrtRunOptionsConfigQnnPerfModePostRun = "qnn.htp_perf_mode_post_run"; - -// Set RPC control latency for QNN HTP backend -static const char* const kOrtRunOptionsConfigQnnRpcControlLatency = "qnn.rpc_control_latency"; - -// Set QNN Lora Config File for apply Lora in QNN context binary -static const char* const kOrtRunOptionsConfigQnnLoraConfig = "qnn.lora_config"; - -// Set graph annotation id for CUDA EP. Use with enable_cuda_graph=true. -// The value should be an integer. If the value is not set, the default value is 0 and -// ORT session only captures one cuda graph before another capture is requested. -// If the value is set to -1, cuda graph capture/replay is disabled in that run. -// User are not expected to set the value to 0 as it is reserved for internal use. -static const char* const kOrtRunOptionsConfigCudaGraphAnnotation = "gpu_graph_id"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#pragma once + +/* + * This file defines RunOptions Config Keys and format of the Config Values. + * + * The Naming Convention for a RunOptions Config Key, + * "[Area][.[SubArea1].[SubArea2]...].[Keyname]" + * Such as "ep.cuda.use_arena" + * The Config Key cannot be empty + * The maximum length of the Config Key is 128 + * + * The string format of a RunOptions Config Value is defined individually for each Config. + * The maximum length of the Config Value is 1024 + */ + +// Key for enabling shrinkages of user listed device memory arenas. +// Expects a list of semi-colon separated key value pairs separated by colon in the following format: +// "device_0:device_id_0;device_1:device_id_1" +// No white-spaces allowed in the provided list string. +// Currently, the only supported devices are : "cpu", "gpu" (case sensitive). +// If "cpu" is included in the list, DisableCpuMemArena() API must not be called (i.e.) arena for cpu should be enabled. +// Example usage: "cpu:0;gpu:0" (or) "gpu:0" +// By default, the value for this key is empty (i.e.) no memory arenas are shrunk +static const char* const kOrtRunOptionsConfigEnableMemoryArenaShrinkage = "memory.enable_memory_arena_shrinkage"; + +// Set to '1' to not synchronize execution providers with CPU at the end of session run. +// Per default it will be set to '0' +// Taking CUDA EP as an example, it omit triggering cudaStreamSynchronize on the compute stream. +static const char* const kOrtRunOptionsConfigDisableSynchronizeExecutionProviders = "disable_synchronize_execution_providers"; + +// Set HTP performance mode for QNN HTP backend before session run. +// options for HTP performance mode: "burst", "balanced", "default", "high_performance", +// "high_power_saver", "low_balanced", "extreme_power_saver", "low_power_saver", "power_saver", +// "sustained_high_performance". Default to "default". +static const char* const kOrtRunOptionsConfigQnnPerfMode = "qnn.htp_perf_mode"; + +// Set HTP performance mode for QNN HTP backend post session run. +static const char* const kOrtRunOptionsConfigQnnPerfModePostRun = "qnn.htp_perf_mode_post_run"; + +// Set RPC control latency for QNN HTP backend +static const char* const kOrtRunOptionsConfigQnnRpcControlLatency = "qnn.rpc_control_latency"; + +// Set QNN Lora Config File for apply Lora in QNN context binary +static const char* const kOrtRunOptionsConfigQnnLoraConfig = "qnn.lora_config"; + +// Set graph annotation id for CUDA EP. Use with enable_cuda_graph=true. +// The value should be an integer. If the value is not set, the default value is 0 and +// ORT session only captures one cuda graph before another capture is requested. +// If the value is set to -1, cuda graph capture/replay is disabled in that run. +// User are not expected to set the value to 0 as it is reserved for internal use. +static const char* const kOrtRunOptionsConfigCudaGraphAnnotation = "gpu_graph_id"; diff --git a/3rdParty/ONNX/onnxruntime_session_options_config_keys.h b/3rdParty/ONNX/onnxruntime_session_options_config_keys.h index 5497d7c71a..dec8e2b84d 100644 --- a/3rdParty/ONNX/onnxruntime_session_options_config_keys.h +++ b/3rdParty/ONNX/onnxruntime_session_options_config_keys.h @@ -1,366 +1,366 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -/* - * This file defines SessionOptions Config Keys and format of the Config Values. - * - * The Naming Convention for a SessionOptions Config Key, - * "[Area][.[SubArea1].[SubArea2]...].[Keyname]" - * Such as "ep.cuda.use_arena" - * The Config Key cannot be empty - * The maximum length of the Config Key is 1024 - * - * The string format of a SessionOptions Config Value is defined individually for each Config. - * The maximum length of the Config Value is 2048 - */ - -// Key for disable PrePacking, -// If the config value is set to "1" then the prepacking is disabled, otherwise prepacking is enabled (default value) -static const char* const kOrtSessionOptionsConfigDisablePrepacking = "session.disable_prepacking"; - -// A value of "1" means allocators registered in the env will be used. "0" means the allocators created in the session -// will be used. Use this to override the usage of env allocators on a per session level. -static const char* const kOrtSessionOptionsConfigUseEnvAllocators = "session.use_env_allocators"; - -// Set to 'ORT' (case sensitive) to load an ORT format model. -// If unset, model type will default to ONNX unless inferred from filename ('.ort' == ORT format) or bytes to be ORT -static const char* const kOrtSessionOptionsConfigLoadModelFormat = "session.load_model_format"; - -// Set to 'ORT' (case sensitive) to save optimized model in ORT format when SessionOptions.optimized_model_path is set. -// If unset, format will default to ONNX unless optimized_model_filepath ends in '.ort'. -static const char* const kOrtSessionOptionsConfigSaveModelFormat = "session.save_model_format"; - -// If a value is "1", flush-to-zero and denormal-as-zero are applied. The default is "0". -// When multiple sessions are created, a main thread doesn't override changes from succeeding session options, -// but threads in session thread pools follow option changes. -// When ORT runs with OpenMP, the same rule is applied, i.e. the first session option to flush-to-zero and -// denormal-as-zero is only applied to global OpenMP thread pool, which doesn't support per-session thread pool. -// Note that an alternative way not using this option at runtime is to train and export a model without denormals -// and that's recommended because turning this option on may hurt model accuracy. -static const char* const kOrtSessionOptionsConfigSetDenormalAsZero = "session.set_denormal_as_zero"; - -// It controls to run quantization model in QDQ (QuantizelinearDeQuantizelinear) format or not. -// "0": enable. ORT does fusion logic for QDQ format. -// "1": disable. ORT doesn't do fusion logic for QDQ format. -// Its default value is "0" unless the DirectML execution provider is registered, in which case it defaults to "1". -static const char* const kOrtSessionOptionsDisableQuantQDQ = "session.disable_quant_qdq"; - -// It controls whether to enable Double QDQ remover and Identical Children Consolidation -// "0": not to disable. ORT does remove the middle 2 Nodes from a Q->(QD->Q)->QD pairs -// "1": disable. ORT doesn't remove the middle 2 Nodes from a Q->(QD->Q)->QD pairs -// Its default value is "0" -static const char* const kOrtSessionOptionsDisableDoubleQDQRemover = "session.disable_double_qdq_remover"; - -// If set to "1", enables the removal of QuantizeLinear/DequantizeLinear node pairs once all QDQ handling has been -// completed. e.g. If after all QDQ handling has completed and we have -> FloatOp -> Q -> DQ -> FloatOp -> the -// Q -> DQ could potentially be removed. This will provide a performance benefit by avoiding going from float to -// 8-bit and back to float, but could impact accuracy. The impact on accuracy will be model specific and depend on -// other factors like whether the model was created using Quantization Aware Training or Post Training Quantization. -// As such, it's best to test to determine if enabling this works well for your scenario. -// The default value is "0" -// Available since version 1.11. -static const char* const kOrtSessionOptionsEnableQuantQDQCleanup = "session.enable_quant_qdq_cleanup"; - -// Enable or disable gelu approximation in graph optimization. "0": disable; "1": enable. The default is "0". -// GeluApproximation has side effects which may change the inference results. It is disabled by default due to this. -static const char* const kOrtSessionOptionsEnableGeluApproximation = "optimization.enable_gelu_approximation"; - -// This setting controls whether to enable AheadOfTime function inlining. -// AOT function inlining examines the graph and attempts to inline as many locally defined functions in the model -// as possible with the help of enabled execution providers. -// This can reduce the number of function calls and improve performance because it is done before -// Level1 optimizers and constant folding. However, under some circumstances, when the EPs are not available, -// one can disable the AOT inlining, produce an optimized model and postpone AOT until run time. -// "0": enable; "1": disable. -// Its default value is "0". -static const char* const kOrtSessionOptionsDisableAheadOfTimeFunctionInlining = "session.disable_aot_function_inlining"; - -#ifdef ENABLE_TRAINING -// Specifies a path of the file containing a list of memory optimization configurations. -// The value should be a string indicating the file path of the config file. -// The content of the config file is a JSON struct like this: -// [ -// "Gelu+Cast+:1:0", -// "Dropout+:1:1" -// ] -// Taking the example of "Gelu+Cast+:1:0", -// > "Gelu+Cast+" is the subgraph string, a valid "subgraph string" should be one subgraph representation -// output by ORT graph transformations. -// > "1" is "optimization strategy", valid values: 0 - disabled, 1 - recompute. -// > "0" is "number of subgraph to apply" which is used to control how many subgraphs to apply optimization, -// to avoid "oversaving" the memory. -static const char* const kOrtSessionOptionsMemoryOptimizerApplyConfig = "optimization.memory_optimizer_config"; - -// Specifies the config for detecting subgraphs for memory footprint reduction. -// The value should be a string contains int separated using commas. The default value is "0:0". -static const char* const kOrtSessionOptionsMemoryOptimizerProbeConfig = "optimization.enable_memory_probe_recompute_config"; -#endif - -// This setting if set should contain a comma separated list of optimizers names that should be disabled. -// Optimizers may take time to execute and affect model loading time. If you feel that a specific optimizer -// does not provider runtime benefits, but affects your model loading time you may disable it using this config -// entry. This option is not enabled in ORT_MINIMAL_BUILD build. -// A list of optimizes is available in onnxruntime/core/optimizer/graph_transformer_utils.cc -// -// Default is an empty string which means no optimizers are disabled. -static const char* const kOrtSessionOptionsDisableSpecifiedOptimizers = "optimization.disable_specified_optimizers"; - -// Enable or disable using device allocator for allocating initialized tensor memory. "1": enable; "0": disable. The default is "0". -// Using device allocators means the memory allocation is made using malloc/new. -static const char* const kOrtSessionOptionsUseDeviceAllocatorForInitializers = "session.use_device_allocator_for_initializers"; - -// Configure whether to allow the inter_op/intra_op threads spinning a number of times before blocking -// "0": thread will block if found no job to run -// "1": default, thread will spin a number of times before blocking -static const char* const kOrtSessionOptionsConfigAllowInterOpSpinning = "session.inter_op.allow_spinning"; -static const char* const kOrtSessionOptionsConfigAllowIntraOpSpinning = "session.intra_op.allow_spinning"; - -// Key for using model bytes directly for ORT format -// If a session is created using an input byte array contains the ORT format model data, -// By default we will copy the model bytes at the time of session creation to ensure the model bytes -// buffer is valid. -// Setting this option to "1" will disable copy the model bytes, and use the model bytes directly. The caller -// has to guarantee that the model bytes are valid until the ORT session using the model bytes is destroyed. -static const char* const kOrtSessionOptionsConfigUseORTModelBytesDirectly = "session.use_ort_model_bytes_directly"; - -/// -/// Key for using the ORT format model flatbuffer bytes directly for initializers. -/// This avoids copying the bytes and reduces peak memory usage during model loading and initialization. -/// Requires `session.use_ort_model_bytes_directly` to be true. -/// If set, the flatbuffer bytes provided when creating the InferenceSession MUST remain valid for the entire -/// duration of the InferenceSession. -/// -static const char* const kOrtSessionOptionsConfigUseORTModelBytesForInitializers = - "session.use_ort_model_bytes_for_initializers"; - -// This should only be specified when exporting an ORT format model for use on a different platform. -// If the ORT format model will be used on ARM platforms set to "1". For other platforms set to "0" -// Available since version 1.11. -static const char* const kOrtSessionOptionsQDQIsInt8Allowed = "session.qdqisint8allowed"; - -// x64 SSE4.1/AVX2/AVX512(with no VNNI) has overflow problem with quantizied matrix multiplication with U8S8. -// To avoid this we need to use slower U8U8 matrix multiplication instead. This option, if -// turned on, use slower U8U8 matrix multiplications. Only effective with AVX2 or AVX512 -// platforms. -static const char* const kOrtSessionOptionsAvx2PrecisionMode = "session.x64quantprecision"; - -// Specifies how minimal build graph optimizations are handled in a full build. -// These optimizations are at the extended level or higher. -// Possible values and their effects are: -// "save": Save runtime optimizations when saving an ORT format model. -// "apply": Only apply optimizations available in a minimal build. -// ""/: Apply optimizations available in a full build. -// Available since version 1.11. -static const char* const kOrtSessionOptionsConfigMinimalBuildOptimizations = - "optimization.minimal_build_optimizations"; - -// Note: The options specific to an EP should be specified prior to appending that EP to the session options object in -// order for them to take effect. - -// Specifies a list of stop op types. Nodes of a type in the stop op types and nodes downstream from them will not be -// run by the NNAPI EP. -// The value should be a ","-delimited list of op types. For example, "Add,Sub". -// If not specified, the default set of stop ops is used. To specify an empty stop ops types list and disable stop op -// exclusion, set the value to "". -static const char* const kOrtSessionOptionsConfigNnapiEpPartitioningStopOps = "ep.nnapi.partitioning_stop_ops"; - -// Enabling dynamic block-sizing for multithreading. -// With a positive value, thread pool will split a task of N iterations to blocks of size starting from: -// N / (num_of_threads * dynamic_block_base) -// As execution progresses, the size will decrease according to the diminishing residual of N, -// meaning the task will be distributed in smaller granularity for better parallelism. -// For some models, it helps to reduce the variance of E2E inference latency and boost performance. -// The feature will not function by default, specify any positive integer, e.g. "4", to enable it. -// Available since version 1.11. -static const char* const kOrtSessionOptionsConfigDynamicBlockBase = "session.dynamic_block_base"; - -// This option allows to decrease CPU usage between infrequent -// requests and forces any TP threads spinning stop immediately when the last of -// concurrent Run() call returns. -// Spinning is restarted on the next Run() call. -// Applies only to internal thread-pools -static const char* const kOrtSessionOptionsConfigForceSpinningStop = "session.force_spinning_stop"; - -// "1": all inconsistencies encountered during shape and type inference -// will result in failures. -// "0": in some cases warnings will be logged but processing will continue. The default. -// May be useful to expose bugs in models. -static const char* const kOrtSessionOptionsConfigStrictShapeTypeInference = "session.strict_shape_type_inference"; - -// "1": every model using a more recent opset than the latest released one will fail -// "0": the model may or may not work if onnxruntime cannot find an implementation, this option -// is used for development purpose. -static const char* const kOrtSessionOptionsConfigStrictAllowReleasedOpsetsOnly = "session.allow_released_opsets_only"; - -// The file saves configuration for partitioning node among logic streams -static const char* const kNodePartitionConfigFile = "session.node_partition_config_file"; - -// This Option allows setting affinities for intra op threads. -// Affinity string follows format: -// logical_processor_id,logical_processor_id;logical_processor_id,logical_processor_id -// Semicolon isolates configurations among threads, while comma split processors where ith thread expected to attach to. -// e.g.1,2,3;4,5 -// specifies affinities for two threads, with the 1st thread attach to the 1st, 2nd, and 3rd processor, and 2nd thread to the 4th and 5th. -// To ease the configuration, an "interval" is also allowed: -// e.g. 1-8;8-16;17-24 -// orders that the 1st thread runs on first eight processors, 2nd thread runs on next eight processors, and so forth. -// Note: -// 1. Once set, the number of thread affinities must equal to intra_op_num_threads - 1, since ort does not set affinity on the main thread which -// is started and managed by the calling app; -// 2. For windows, ort will infer the group id from a logical processor id, for example, assuming there are two groups with each has 64 logical processors, -// an id of 64 will be inferred as the last processor of the 1st group, while 65 will be interpreted as the 1st processor of the second group. -// Hence 64-65 is an invalid configuration, because a windows thread cannot be attached to processors across group boundary. -static const char* const kOrtSessionOptionsConfigIntraOpThreadAffinities = "session.intra_op_thread_affinities"; - -// This option will dump out the model to assist debugging any issues with layout transformation, -// and is primarily intended for developer usage. It is only relevant if an execution provider that requests -// NHWC layout is enabled such as NNAPI, XNNPACK or QNN. -// -// Default is off. Set to "1" to enable. -// -// If modified by layout transformation the model will be dumped after these steps: -// 1) insertion of the layout transformation Transpose nodes -// 2) after those are optimized using the transpose optimizer, -// 3) after the L1 transformers are applied to the updated graph. -// The model will be saved to filename post_layout_transform_step_.onnx. -static const char* const kDebugLayoutTransformation = "session.debug_layout_transformation"; - -// Graph nodes that are not supported by the execution providers (EPs) explicitly added to the session are -// assigned (i.e., "fallback") to the CPU EP by default. -// -// This option allows the user to disable the fallback of unsupported graph nodes to the CPU EP. -// If this option is set to "1", session creation will fail if the execution providers other than the CPU EP cannot -// fully support all of the nodes in the graph. -// -// It is invalid to set this option and explicitly add the CPU EP to the session. In this case, session creation -// will also fail with an error. -// -// Option values: -// - "0": CPU EP fallback is not disabled. [DEFAULT] -// - "1": CPU EP fallback is disabled. -static const char* const kOrtSessionOptionsDisableCPUEPFallback = "session.disable_cpu_ep_fallback"; - -// Use this config when serializing a large model after optimization to specify an external initializers file -static const char* const kOrtSessionOptionsOptimizedModelExternalInitializersFileName = - "session.optimized_model_external_initializers_file_name"; - -// Use this config to control the minimum size of the initializer when externalizing it during serialization -static const char* const kOrtSessionOptionsOptimizedModelExternalInitializersMinSizeInBytes = - "session.optimized_model_external_initializers_min_size_in_bytes"; - -// When loading model from memory buffer and the model has external initializers -// Use this config to set the external data file folder path -// All external data files should be in the same folder -static const char* const kOrtSessionOptionsModelExternalInitializersFileFolderPath = - "session.model_external_initializers_file_folder_path"; - -// Use this config when saving pre-packed constant initializers to an external data file. -// This allows you to memory map pre-packed initializers on model load and leave it to -// to the OS the amount of memory consumed by the pre-packed initializers. Otherwise, -// pre-packed data resides on the heap. -// -// - "0": Default is not save pre-packed initializers to a data file. -// - "1": Save pre-packed constant initializers to an external data file. -// Sample usage: sess_options.add_session_config_entry(kOrtSessionOptionsSavePrePackedConstantInitializers, "1") -static const char* const kOrtSessionOptionsSavePrePackedConstantInitializers = - "session.save_external_prepacked_constant_initializers"; - -// Use this config when you want to collect memory stats for each node in the graph. -// The file format is a CSV file with the following columns: -// The file will be created if it does not exist, and will be overwritten if it does. -// -// The content of the file can be used to estimate memory requirements at run time including -// the temporary allocations. This operation is preferably done on a CPU device, as the model may exceed -// device memory limits in constrained environments. When enabling this option, it is important to disable -// memory patterns, as they tend to allocate large blocks to avoid fragmentation and accommodate needs of multiple -// kernels. Memory patterns may make it difficult to allocate on a device with limited memory. -// -// The collected stats then can be used to partition the graph among the devices in a way that only the -// required memory is allocated on each device. -// -// node_name, initializers_memory, dynamic_outputs_sizes, temp_allocations_size -// -// - "full path to file": there is not a default for this option. If the file can not be opened for writing, an error will be returned. -static const char* const kOrtSessionOptionsCollectNodeMemoryStatsToFile = "session.collect_node_memory_stats_to_file"; - -/// This is a composite CSV setting formatted as "memory limit in kb,file name for collected stats" -/// "limit > 0": enables Capacity Aware Partitioning for Cuda EP. `limit` is optional and when absent -/// the provider may attempt to figure out the memory available automatically. -/// The setting with no limit is expected to look like: ",file name for collected stats" -/// The EP will place nodes on device "file name" : -/// this file is expected to be found at the same folder with the model. The file contains -/// pre-recorded stats collected when running with kOrtSessionOptionsCollectNodeMemoryStatsToFile enforce (see above) -static const char* const kOrtSessionOptionsResourceCudaPartitioningSettings = - "session.resource_cuda_partitioning_settings"; - -// Enable EP context feature to dump the partitioned graph which includes the EP context into Onnx file. -// The dumped Onnx model with EP context can be used for future inference to avoid the EP graph partitioning/compile overhead. -// "0": disable. (default) -// "1": enable. -static const char* const kOrtSessionOptionEpContextEnable = "ep.context_enable"; - -// Specify the file path for the Onnx model which has EP context. -// Default to original_file_name_ctx.onnx if not specified -// Folder is not a valid option -static const char* const kOrtSessionOptionEpContextFilePath = "ep.context_file_path"; - -// Flag to specify whether to dump the EP context into the Onnx model. -// "0": dump the EP context into separate file, keep the file name in the Onnx model. (default). -// "1": dump the EP context into the Onnx model. -static const char* const kOrtSessionOptionEpContextEmbedMode = "ep.context_embed_mode"; - -// Specify the EPContext node name prefix to make it unique -// in case user need to merge/connect multiple EPContext nodes in one model -static const char* const kOrtSessionOptionEpContextNodeNamePrefix = "ep.context_node_name_prefix"; - -// Share EP related resources across sessions -static const char* const kOrtSessionOptionShareEpContexts = "ep.share_ep_contexts"; - -// Stop to share EP related resources across sessions from then on -static const char* const kOrtSessionOptionStopShareEpContexts = "ep.stop_share_ep_contexts"; - -// Used only for context model generation. -// This configuration is used when some nodes are partitioned on the CPU EP and those nodes have external initializers. -// When generating the EP context model, the new model should not rely on the old external data file used by the source ONNX model. -// Use this setting when dumping the EP context model with an external initializers file. -// If specified, all initializers will be placed inside the external data file. -// Otherwise, all initializers will be embedded inside the generated ONNX file. -// By default, this option is not set, meaning all initializers will be included within the ONNX file. -static const char* const kOrtSessionOptionsEpContextModelExternalInitializersFileName = - "ep.context_model_external_initializers_file_name"; - -// Gemm fastmath mode provides fp32 gemm acceleration with bfloat16 based matmul. -// Option values: -// - "0": Gemm FastMath mode is not enabled. [DEFAULT] -// - "1": Gemm FastMath mode is enabled. -static const char* const kOrtSessionOptionsMlasGemmFastMathArm64Bfloat16 = "mlas.enable_gemm_fastmath_arm64_bfloat16"; - -// When converting DQ + MatMul -> MatMulNBits, the accuracy level of the MatMulNBits is controlled by this option. -// Refer to MatMulNBits op schema for more details. -// If not provided, default is 4. -static const char* const kOrtSessionOptionsQDQMatMulNBitsAccuracyLevel = "session.qdq_matmulnbits_accuracy_level"; - -// THIS OPTION IS NOT A REGULAR SESSION OPTION SINCE IT CAN BE MODIFIED AT ANY TIME -// Meant to be used with SetEpDynamicOptions -// Specify the type of workload for this session. -// “Default”: OS determines the scheduling priority and processor performance to service this workload. [Default] -// “Efficient”: OS treats this workload is efficiency oriented with low scheduling priority and efficient processor performance. -static const char* const kOrtEpDynamicOptionsWorkloadType = "ep.dynamic.workload_type"; - -// Disables model compilation during session initialization. -// -// If this option is set to "1", inference session creation will fail with error code ORT_MODEL_REQUIRES_COMPILATION -// if compilation is required to run the model on any Execution Provider added to the session. -// Only the following kinds of models are valid when this option is set to "1": -// - Pre-compiled models that have EPContext nodes for the compiling Execution Providers in the session. -// - Non-compiled models that run only on non-compiling Execution Providers, like CPU EP. -// -// See \href https://onnxruntime.ai/docs/execution-providers/EP-Context-Design.html for details about -// compiled models with EPContext nodes. -// -// Option values: -// - "0": EP compile is not disabled. [DEFAULT] -// - "1": EP compile is disabled. -static const char* const kOrtSessionOptionsDisableModelCompile = "session.disable_model_compile"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#pragma once + +/* + * This file defines SessionOptions Config Keys and format of the Config Values. + * + * The Naming Convention for a SessionOptions Config Key, + * "[Area][.[SubArea1].[SubArea2]...].[Keyname]" + * Such as "ep.cuda.use_arena" + * The Config Key cannot be empty + * The maximum length of the Config Key is 1024 + * + * The string format of a SessionOptions Config Value is defined individually for each Config. + * The maximum length of the Config Value is 2048 + */ + +// Key for disable PrePacking, +// If the config value is set to "1" then the prepacking is disabled, otherwise prepacking is enabled (default value) +static const char* const kOrtSessionOptionsConfigDisablePrepacking = "session.disable_prepacking"; + +// A value of "1" means allocators registered in the env will be used. "0" means the allocators created in the session +// will be used. Use this to override the usage of env allocators on a per session level. +static const char* const kOrtSessionOptionsConfigUseEnvAllocators = "session.use_env_allocators"; + +// Set to 'ORT' (case sensitive) to load an ORT format model. +// If unset, model type will default to ONNX unless inferred from filename ('.ort' == ORT format) or bytes to be ORT +static const char* const kOrtSessionOptionsConfigLoadModelFormat = "session.load_model_format"; + +// Set to 'ORT' (case sensitive) to save optimized model in ORT format when SessionOptions.optimized_model_path is set. +// If unset, format will default to ONNX unless optimized_model_filepath ends in '.ort'. +static const char* const kOrtSessionOptionsConfigSaveModelFormat = "session.save_model_format"; + +// If a value is "1", flush-to-zero and denormal-as-zero are applied. The default is "0". +// When multiple sessions are created, a main thread doesn't override changes from succeeding session options, +// but threads in session thread pools follow option changes. +// When ORT runs with OpenMP, the same rule is applied, i.e. the first session option to flush-to-zero and +// denormal-as-zero is only applied to global OpenMP thread pool, which doesn't support per-session thread pool. +// Note that an alternative way not using this option at runtime is to train and export a model without denormals +// and that's recommended because turning this option on may hurt model accuracy. +static const char* const kOrtSessionOptionsConfigSetDenormalAsZero = "session.set_denormal_as_zero"; + +// It controls to run quantization model in QDQ (QuantizelinearDeQuantizelinear) format or not. +// "0": enable. ORT does fusion logic for QDQ format. +// "1": disable. ORT doesn't do fusion logic for QDQ format. +// Its default value is "0" unless the DirectML execution provider is registered, in which case it defaults to "1". +static const char* const kOrtSessionOptionsDisableQuantQDQ = "session.disable_quant_qdq"; + +// It controls whether to enable Double QDQ remover and Identical Children Consolidation +// "0": not to disable. ORT does remove the middle 2 Nodes from a Q->(QD->Q)->QD pairs +// "1": disable. ORT doesn't remove the middle 2 Nodes from a Q->(QD->Q)->QD pairs +// Its default value is "0" +static const char* const kOrtSessionOptionsDisableDoubleQDQRemover = "session.disable_double_qdq_remover"; + +// If set to "1", enables the removal of QuantizeLinear/DequantizeLinear node pairs once all QDQ handling has been +// completed. e.g. If after all QDQ handling has completed and we have -> FloatOp -> Q -> DQ -> FloatOp -> the +// Q -> DQ could potentially be removed. This will provide a performance benefit by avoiding going from float to +// 8-bit and back to float, but could impact accuracy. The impact on accuracy will be model specific and depend on +// other factors like whether the model was created using Quantization Aware Training or Post Training Quantization. +// As such, it's best to test to determine if enabling this works well for your scenario. +// The default value is "0" +// Available since version 1.11. +static const char* const kOrtSessionOptionsEnableQuantQDQCleanup = "session.enable_quant_qdq_cleanup"; + +// Enable or disable gelu approximation in graph optimization. "0": disable; "1": enable. The default is "0". +// GeluApproximation has side effects which may change the inference results. It is disabled by default due to this. +static const char* const kOrtSessionOptionsEnableGeluApproximation = "optimization.enable_gelu_approximation"; + +// This setting controls whether to enable AheadOfTime function inlining. +// AOT function inlining examines the graph and attempts to inline as many locally defined functions in the model +// as possible with the help of enabled execution providers. +// This can reduce the number of function calls and improve performance because it is done before +// Level1 optimizers and constant folding. However, under some circumstances, when the EPs are not available, +// one can disable the AOT inlining, produce an optimized model and postpone AOT until run time. +// "0": enable; "1": disable. +// Its default value is "0". +static const char* const kOrtSessionOptionsDisableAheadOfTimeFunctionInlining = "session.disable_aot_function_inlining"; + +#ifdef ENABLE_TRAINING +// Specifies a path of the file containing a list of memory optimization configurations. +// The value should be a string indicating the file path of the config file. +// The content of the config file is a JSON struct like this: +// [ +// "Gelu+Cast+:1:0", +// "Dropout+:1:1" +// ] +// Taking the example of "Gelu+Cast+:1:0", +// > "Gelu+Cast+" is the subgraph string, a valid "subgraph string" should be one subgraph representation +// output by ORT graph transformations. +// > "1" is "optimization strategy", valid values: 0 - disabled, 1 - recompute. +// > "0" is "number of subgraph to apply" which is used to control how many subgraphs to apply optimization, +// to avoid "oversaving" the memory. +static const char* const kOrtSessionOptionsMemoryOptimizerApplyConfig = "optimization.memory_optimizer_config"; + +// Specifies the config for detecting subgraphs for memory footprint reduction. +// The value should be a string contains int separated using commas. The default value is "0:0". +static const char* const kOrtSessionOptionsMemoryOptimizerProbeConfig = "optimization.enable_memory_probe_recompute_config"; +#endif + +// This setting if set should contain a comma separated list of optimizers names that should be disabled. +// Optimizers may take time to execute and affect model loading time. If you feel that a specific optimizer +// does not provider runtime benefits, but affects your model loading time you may disable it using this config +// entry. This option is not enabled in ORT_MINIMAL_BUILD build. +// A list of optimizes is available in onnxruntime/core/optimizer/graph_transformer_utils.cc +// +// Default is an empty string which means no optimizers are disabled. +static const char* const kOrtSessionOptionsDisableSpecifiedOptimizers = "optimization.disable_specified_optimizers"; + +// Enable or disable using device allocator for allocating initialized tensor memory. "1": enable; "0": disable. The default is "0". +// Using device allocators means the memory allocation is made using malloc/new. +static const char* const kOrtSessionOptionsUseDeviceAllocatorForInitializers = "session.use_device_allocator_for_initializers"; + +// Configure whether to allow the inter_op/intra_op threads spinning a number of times before blocking +// "0": thread will block if found no job to run +// "1": default, thread will spin a number of times before blocking +static const char* const kOrtSessionOptionsConfigAllowInterOpSpinning = "session.inter_op.allow_spinning"; +static const char* const kOrtSessionOptionsConfigAllowIntraOpSpinning = "session.intra_op.allow_spinning"; + +// Key for using model bytes directly for ORT format +// If a session is created using an input byte array contains the ORT format model data, +// By default we will copy the model bytes at the time of session creation to ensure the model bytes +// buffer is valid. +// Setting this option to "1" will disable copy the model bytes, and use the model bytes directly. The caller +// has to guarantee that the model bytes are valid until the ORT session using the model bytes is destroyed. +static const char* const kOrtSessionOptionsConfigUseORTModelBytesDirectly = "session.use_ort_model_bytes_directly"; + +/// +/// Key for using the ORT format model flatbuffer bytes directly for initializers. +/// This avoids copying the bytes and reduces peak memory usage during model loading and initialization. +/// Requires `session.use_ort_model_bytes_directly` to be true. +/// If set, the flatbuffer bytes provided when creating the InferenceSession MUST remain valid for the entire +/// duration of the InferenceSession. +/// +static const char* const kOrtSessionOptionsConfigUseORTModelBytesForInitializers = + "session.use_ort_model_bytes_for_initializers"; + +// This should only be specified when exporting an ORT format model for use on a different platform. +// If the ORT format model will be used on ARM platforms set to "1". For other platforms set to "0" +// Available since version 1.11. +static const char* const kOrtSessionOptionsQDQIsInt8Allowed = "session.qdqisint8allowed"; + +// x64 SSE4.1/AVX2/AVX512(with no VNNI) has overflow problem with quantizied matrix multiplication with U8S8. +// To avoid this we need to use slower U8U8 matrix multiplication instead. This option, if +// turned on, use slower U8U8 matrix multiplications. Only effective with AVX2 or AVX512 +// platforms. +static const char* const kOrtSessionOptionsAvx2PrecisionMode = "session.x64quantprecision"; + +// Specifies how minimal build graph optimizations are handled in a full build. +// These optimizations are at the extended level or higher. +// Possible values and their effects are: +// "save": Save runtime optimizations when saving an ORT format model. +// "apply": Only apply optimizations available in a minimal build. +// ""/: Apply optimizations available in a full build. +// Available since version 1.11. +static const char* const kOrtSessionOptionsConfigMinimalBuildOptimizations = + "optimization.minimal_build_optimizations"; + +// Note: The options specific to an EP should be specified prior to appending that EP to the session options object in +// order for them to take effect. + +// Specifies a list of stop op types. Nodes of a type in the stop op types and nodes downstream from them will not be +// run by the NNAPI EP. +// The value should be a ","-delimited list of op types. For example, "Add,Sub". +// If not specified, the default set of stop ops is used. To specify an empty stop ops types list and disable stop op +// exclusion, set the value to "". +static const char* const kOrtSessionOptionsConfigNnapiEpPartitioningStopOps = "ep.nnapi.partitioning_stop_ops"; + +// Enabling dynamic block-sizing for multithreading. +// With a positive value, thread pool will split a task of N iterations to blocks of size starting from: +// N / (num_of_threads * dynamic_block_base) +// As execution progresses, the size will decrease according to the diminishing residual of N, +// meaning the task will be distributed in smaller granularity for better parallelism. +// For some models, it helps to reduce the variance of E2E inference latency and boost performance. +// The feature will not function by default, specify any positive integer, e.g. "4", to enable it. +// Available since version 1.11. +static const char* const kOrtSessionOptionsConfigDynamicBlockBase = "session.dynamic_block_base"; + +// This option allows to decrease CPU usage between infrequent +// requests and forces any TP threads spinning stop immediately when the last of +// concurrent Run() call returns. +// Spinning is restarted on the next Run() call. +// Applies only to internal thread-pools +static const char* const kOrtSessionOptionsConfigForceSpinningStop = "session.force_spinning_stop"; + +// "1": all inconsistencies encountered during shape and type inference +// will result in failures. +// "0": in some cases warnings will be logged but processing will continue. The default. +// May be useful to expose bugs in models. +static const char* const kOrtSessionOptionsConfigStrictShapeTypeInference = "session.strict_shape_type_inference"; + +// "1": every model using a more recent opset than the latest released one will fail +// "0": the model may or may not work if onnxruntime cannot find an implementation, this option +// is used for development purpose. +static const char* const kOrtSessionOptionsConfigStrictAllowReleasedOpsetsOnly = "session.allow_released_opsets_only"; + +// The file saves configuration for partitioning node among logic streams +static const char* const kNodePartitionConfigFile = "session.node_partition_config_file"; + +// This Option allows setting affinities for intra op threads. +// Affinity string follows format: +// logical_processor_id,logical_processor_id;logical_processor_id,logical_processor_id +// Semicolon isolates configurations among threads, while comma split processors where ith thread expected to attach to. +// e.g.1,2,3;4,5 +// specifies affinities for two threads, with the 1st thread attach to the 1st, 2nd, and 3rd processor, and 2nd thread to the 4th and 5th. +// To ease the configuration, an "interval" is also allowed: +// e.g. 1-8;8-16;17-24 +// orders that the 1st thread runs on first eight processors, 2nd thread runs on next eight processors, and so forth. +// Note: +// 1. Once set, the number of thread affinities must equal to intra_op_num_threads - 1, since ort does not set affinity on the main thread which +// is started and managed by the calling app; +// 2. For windows, ort will infer the group id from a logical processor id, for example, assuming there are two groups with each has 64 logical processors, +// an id of 64 will be inferred as the last processor of the 1st group, while 65 will be interpreted as the 1st processor of the second group. +// Hence 64-65 is an invalid configuration, because a windows thread cannot be attached to processors across group boundary. +static const char* const kOrtSessionOptionsConfigIntraOpThreadAffinities = "session.intra_op_thread_affinities"; + +// This option will dump out the model to assist debugging any issues with layout transformation, +// and is primarily intended for developer usage. It is only relevant if an execution provider that requests +// NHWC layout is enabled such as NNAPI, XNNPACK or QNN. +// +// Default is off. Set to "1" to enable. +// +// If modified by layout transformation the model will be dumped after these steps: +// 1) insertion of the layout transformation Transpose nodes +// 2) after those are optimized using the transpose optimizer, +// 3) after the L1 transformers are applied to the updated graph. +// The model will be saved to filename post_layout_transform_step_.onnx. +static const char* const kDebugLayoutTransformation = "session.debug_layout_transformation"; + +// Graph nodes that are not supported by the execution providers (EPs) explicitly added to the session are +// assigned (i.e., "fallback") to the CPU EP by default. +// +// This option allows the user to disable the fallback of unsupported graph nodes to the CPU EP. +// If this option is set to "1", session creation will fail if the execution providers other than the CPU EP cannot +// fully support all of the nodes in the graph. +// +// It is invalid to set this option and explicitly add the CPU EP to the session. In this case, session creation +// will also fail with an error. +// +// Option values: +// - "0": CPU EP fallback is not disabled. [DEFAULT] +// - "1": CPU EP fallback is disabled. +static const char* const kOrtSessionOptionsDisableCPUEPFallback = "session.disable_cpu_ep_fallback"; + +// Use this config when serializing a large model after optimization to specify an external initializers file +static const char* const kOrtSessionOptionsOptimizedModelExternalInitializersFileName = + "session.optimized_model_external_initializers_file_name"; + +// Use this config to control the minimum size of the initializer when externalizing it during serialization +static const char* const kOrtSessionOptionsOptimizedModelExternalInitializersMinSizeInBytes = + "session.optimized_model_external_initializers_min_size_in_bytes"; + +// When loading model from memory buffer and the model has external initializers +// Use this config to set the external data file folder path +// All external data files should be in the same folder +static const char* const kOrtSessionOptionsModelExternalInitializersFileFolderPath = + "session.model_external_initializers_file_folder_path"; + +// Use this config when saving pre-packed constant initializers to an external data file. +// This allows you to memory map pre-packed initializers on model load and leave it to +// to the OS the amount of memory consumed by the pre-packed initializers. Otherwise, +// pre-packed data resides on the heap. +// +// - "0": Default is not save pre-packed initializers to a data file. +// - "1": Save pre-packed constant initializers to an external data file. +// Sample usage: sess_options.add_session_config_entry(kOrtSessionOptionsSavePrePackedConstantInitializers, "1") +static const char* const kOrtSessionOptionsSavePrePackedConstantInitializers = + "session.save_external_prepacked_constant_initializers"; + +// Use this config when you want to collect memory stats for each node in the graph. +// The file format is a CSV file with the following columns: +// The file will be created if it does not exist, and will be overwritten if it does. +// +// The content of the file can be used to estimate memory requirements at run time including +// the temporary allocations. This operation is preferably done on a CPU device, as the model may exceed +// device memory limits in constrained environments. When enabling this option, it is important to disable +// memory patterns, as they tend to allocate large blocks to avoid fragmentation and accommodate needs of multiple +// kernels. Memory patterns may make it difficult to allocate on a device with limited memory. +// +// The collected stats then can be used to partition the graph among the devices in a way that only the +// required memory is allocated on each device. +// +// node_name, initializers_memory, dynamic_outputs_sizes, temp_allocations_size +// +// - "full path to file": there is not a default for this option. If the file can not be opened for writing, an error will be returned. +static const char* const kOrtSessionOptionsCollectNodeMemoryStatsToFile = "session.collect_node_memory_stats_to_file"; + +/// This is a composite CSV setting formatted as "memory limit in kb,file name for collected stats" +/// "limit > 0": enables Capacity Aware Partitioning for Cuda EP. `limit` is optional and when absent +/// the provider may attempt to figure out the memory available automatically. +/// The setting with no limit is expected to look like: ",file name for collected stats" +/// The EP will place nodes on device "file name" : +/// this file is expected to be found at the same folder with the model. The file contains +/// pre-recorded stats collected when running with kOrtSessionOptionsCollectNodeMemoryStatsToFile enforce (see above) +static const char* const kOrtSessionOptionsResourceCudaPartitioningSettings = + "session.resource_cuda_partitioning_settings"; + +// Enable EP context feature to dump the partitioned graph which includes the EP context into Onnx file. +// The dumped Onnx model with EP context can be used for future inference to avoid the EP graph partitioning/compile overhead. +// "0": disable. (default) +// "1": enable. +static const char* const kOrtSessionOptionEpContextEnable = "ep.context_enable"; + +// Specify the file path for the Onnx model which has EP context. +// Default to original_file_name_ctx.onnx if not specified +// Folder is not a valid option +static const char* const kOrtSessionOptionEpContextFilePath = "ep.context_file_path"; + +// Flag to specify whether to dump the EP context into the Onnx model. +// "0": dump the EP context into separate file, keep the file name in the Onnx model. (default). +// "1": dump the EP context into the Onnx model. +static const char* const kOrtSessionOptionEpContextEmbedMode = "ep.context_embed_mode"; + +// Specify the EPContext node name prefix to make it unique +// in case user need to merge/connect multiple EPContext nodes in one model +static const char* const kOrtSessionOptionEpContextNodeNamePrefix = "ep.context_node_name_prefix"; + +// Share EP related resources across sessions +static const char* const kOrtSessionOptionShareEpContexts = "ep.share_ep_contexts"; + +// Stop to share EP related resources across sessions from then on +static const char* const kOrtSessionOptionStopShareEpContexts = "ep.stop_share_ep_contexts"; + +// Used only for context model generation. +// This configuration is used when some nodes are partitioned on the CPU EP and those nodes have external initializers. +// When generating the EP context model, the new model should not rely on the old external data file used by the source ONNX model. +// Use this setting when dumping the EP context model with an external initializers file. +// If specified, all initializers will be placed inside the external data file. +// Otherwise, all initializers will be embedded inside the generated ONNX file. +// By default, this option is not set, meaning all initializers will be included within the ONNX file. +static const char* const kOrtSessionOptionsEpContextModelExternalInitializersFileName = + "ep.context_model_external_initializers_file_name"; + +// Gemm fastmath mode provides fp32 gemm acceleration with bfloat16 based matmul. +// Option values: +// - "0": Gemm FastMath mode is not enabled. [DEFAULT] +// - "1": Gemm FastMath mode is enabled. +static const char* const kOrtSessionOptionsMlasGemmFastMathArm64Bfloat16 = "mlas.enable_gemm_fastmath_arm64_bfloat16"; + +// When converting DQ + MatMul -> MatMulNBits, the accuracy level of the MatMulNBits is controlled by this option. +// Refer to MatMulNBits op schema for more details. +// If not provided, default is 4. +static const char* const kOrtSessionOptionsQDQMatMulNBitsAccuracyLevel = "session.qdq_matmulnbits_accuracy_level"; + +// THIS OPTION IS NOT A REGULAR SESSION OPTION SINCE IT CAN BE MODIFIED AT ANY TIME +// Meant to be used with SetEpDynamicOptions +// Specify the type of workload for this session. +// “Default”: OS determines the scheduling priority and processor performance to service this workload. [Default] +// “Efficient”: OS treats this workload is efficiency oriented with low scheduling priority and efficient processor performance. +static const char* const kOrtEpDynamicOptionsWorkloadType = "ep.dynamic.workload_type"; + +// Disables model compilation during session initialization. +// +// If this option is set to "1", inference session creation will fail with error code ORT_MODEL_REQUIRES_COMPILATION +// if compilation is required to run the model on any Execution Provider added to the session. +// Only the following kinds of models are valid when this option is set to "1": +// - Pre-compiled models that have EPContext nodes for the compiling Execution Providers in the session. +// - Non-compiled models that run only on non-compiling Execution Providers, like CPU EP. +// +// See \href https://onnxruntime.ai/docs/execution-providers/EP-Context-Design.html for details about +// compiled models with EPContext nodes. +// +// Option values: +// - "0": EP compile is not disabled. [DEFAULT] +// - "1": EP compile is disabled. +static const char* const kOrtSessionOptionsDisableModelCompile = "session.disable_model_compile"; diff --git a/3rdParty/ONNX/onnxruntime_training_c_api.h b/3rdParty/ONNX/onnxruntime_training_c_api.h index ed6d151a59..f5897d535c 100644 --- a/3rdParty/ONNX/onnxruntime_training_c_api.h +++ b/3rdParty/ONNX/onnxruntime_training_c_api.h @@ -1,731 +1,731 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// This file contains the training c apis. - -#pragma once -#include -#include "onnxruntime_c_api.h" - -/** \page training_c_cpp_api Training C & C++ APIs - * - * Training C and C++ APIs are an extension of the \ref c_cpp_api "onnxruntime core C and C++ APIs" and should be used in conjunction with them. - * - * In order to train a model with onnxruntime, the following training artifacts must be generated: - * - The training onnx model - * - The checkpoint file - * - The optimizer onnx model - * - The eval onnx model model (optional) - * - * These training artifacts can be generated as part of an offline step using the python [utilities](https://github.com/microsoft/onnxruntime/blob/main/orttraining/orttraining/python/training/onnxblock/README.md) made available in the `onnxruntime-training` python package. - * - * After these artifacts have been generated, the C and C++ utilities listed in this documentation can be leveraged to perform training. - * - * If any problem is encountered, please create an [issue](https://github.com/microsoft/onnxruntime/issues/new) with your scenario and requirements, and we will be sure to respond and follow up on the request. - * - *

Training C API

- * - * ::OrtTrainingApi - Training C API functions. - * - * This C structure contains functions that enable users to perform training with onnxruntime. - * - * _Sample Code_: - * - * ```c - * #include - * - * OrtApi* g_ort_api = OrtGetApiBase()->GetApi(ORT_API_VERSION); - * OrtTrainingApi* g_ort_training_api = g_ort_api->GetTrainingApi(ORT_API_VERSION); - * - * OrtEnv* env = NULL; - * g_ort_api->CreateEnv(logging_level, logid, &env); - * OrtSessionOptions* session_options = NULL; - * g_ort_api->CreateSessionOptions(&session_options); - * - * OrtCheckpointState* state = NULL; - * g_ort_training_api->LoadCheckpoint(path_to_checkpoint, &state); - * - * OrtTrainingSession* training_session = NULL; - * g_ort_training_api->CreateTrainingSession(env, session_options, training_model_path, - * state, eval_model_path, optimizer_model_path, - * &training_session); - * // Training loop - * { - * g_ort_training_api->TrainStep(...); - * g_ort_training_api->OptimizerStep(...); - * g_ort_training_api->LazyResetGrad(...); - * } - * - * g_ort_training_api->ExportModelForInferencing(training_session, inference_model_path, ...); - * g_ort_training_api->SaveCheckpoint(state, path_to_checkpoint, false); - * - * g_ort_training_api->ReleaseTrainingSession(training_session); - * g_ort_training_api->ReleaseCheckpointState(state); - * ``` - * - * > **Note** - * > The ::OrtCheckpointState contains the entire training state that the ::OrtTrainingSession uses. As a result, the training session must always have access to the state. That is to say, the ::OrtCheckpointState instance must outlive the lifetime of the ::OrtTrainingSession instance. - * - *

Training C++ API

- * - * @ref TrainingCpp - Training C++ API classes and functions. - * - * These C++ classes and functions enable users to perform training with onnxruntime. - * - * _Sample Code_: - * - * ```cc - * #include - * - * Ort::Env env; - * Ort::SessionOptions session_options; - * - * auto state = Ort::CheckpointState::LoadCheckpoint(path_to_checkpoint); - * auto training_session = Ort::TrainingSession(env, session_options, state, training_model_path, - * eval_model_path, optimizer_model_path); - * - * // Training Loop - * { - * training_session.TrainStep(...); - * training_session.OptimizerStep(...); - * training_session.LazyResetGrad(...); - * } - * - * training_session->ExportModelForInferencing(inference_model_path, ...); - * Ort::CheckpointState::SaveCheckpoint(state, path_to_checkpoint, false); - * ``` - * > **Note** - * > The ::Ort::CheckpointState contains the entire training state that the ::Ort::TrainingSession uses. As a result, the training session must always have access to the state. That is to say, the ::Ort::CheckpointState instance must outlive the lifetime of the ::Ort::TrainingSession instance. - */ - -/** @defgroup TrainingC Ort Training C API - * @{ - */ -ORT_RUNTIME_CLASS(TrainingSession); // Type that enables performing training for the given user models. -ORT_RUNTIME_CLASS(CheckpointState); // Type that holds the training states for the training session. - -/** \brief Type of property to be added to or returned from the ::OrtCheckpointState. - */ -typedef enum OrtPropertyType { - OrtIntProperty = 0, - OrtFloatProperty = 1, - OrtStringProperty = 2, -} OrtPropertyType; - -/** \brief The Training C API that holds onnxruntime training function pointers - * - * All the Training C API functions are defined inside this structure as pointers to functions. - * Call OrtApi::GetTrainingApi to get a pointer to this struct. - * - * \nosubgrouping - */ -struct OrtTrainingApi { - /// \name Accessing The Training Session State - /// @{ - - /** \brief Load a checkpoint state from a file on disk into checkpoint_state. - * - * This function will parse a checkpoint file, pull relevant data and load the training - * state into the checkpoint_state. This checkpoint state can then be used to create the - * training session by invoking OrtTrainingApi::CreateTrainingSession. By doing so, the training - * session will resume training from the given checkpoint state. - * \note Note that the training session created with a checkpoint state uses this state to store the entire - * training state (including model parameters, its gradients, the optimizer states and the properties). - * As a result, it is required that the checkpoint state outlive the lifetime of the training session. - * \note Note that the checkpoint file can be either the complete checkpoint or the nominal checkpoint. - * - * \param[in] checkpoint_path Path to the checkpoint file - * \param[out] checkpoint_state Checkpoint state that contains the states of the training session. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(LoadCheckpoint, _In_ const ORTCHAR_T* checkpoint_path, - _Outptr_ OrtCheckpointState** checkpoint_state); - - /** \brief Save the given state to a checkpoint file on disk. - * - * This function serializes the provided checkpoint state to a file on disk. - * This checkpoint can later be loaded by invoking OrtTrainingApi::LoadCheckpoint to resume - * training from this snapshot of the state. - * - * \param[in] checkpoint_state The checkpoint state to save. - * \param[in] checkpoint_path Path to the checkpoint file. - * \param[in] include_optimizer_state Flag to indicate whether to save the optimizer state or not. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(SaveCheckpoint, _In_ OrtCheckpointState* checkpoint_state, _In_ const ORTCHAR_T* checkpoint_path, - const bool include_optimizer_state); - - /// @} - - /// \name Implementing The Training Loop - /// @{ - /** \brief Create a training session that can be used to begin or resume training. - * - * This function creates a training session based on the env and session options provided that can - * begin or resume training from a given checkpoint state for the given onnx models. - * The checkpoint state represents the parameters of the training session which will be moved - * to the device specified by the user through the session options (if necessary). - * The training session requires four training artifacts - * - The training onnx model - * - The evaluation onnx model (optional) - * - The optimizer onnx model - * - The checkpoint file - * - * These artifacts can be generated using the `onnxruntime-training` python [utility](https://github.com/microsoft/onnxruntime/blob/main/orttraining/orttraining/python/training/onnxblock/README.md). - * - * \param[in] env Environment to be used for the training session. - * \param[in] options Session options that the user can customize for this training session. - * \param[in] checkpoint_state Training states that the training session uses as a starting point for training. - * \param[in] train_model_path Model to be used to perform training. - * \param[in] eval_model_path Model to be used to perform evaluation. - * \param[in] optimizer_model_path Model to be used to perform gradient descent. - * \param[out] out Created training session. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(CreateTrainingSession, _In_ const OrtEnv* env, _In_ const OrtSessionOptions* options, - _Inout_ OrtCheckpointState* checkpoint_state, _In_ const ORTCHAR_T* train_model_path, - _In_ const ORTCHAR_T* eval_model_path, _In_ const ORTCHAR_T* optimizer_model_path, - _Outptr_result_maybenull_ OrtTrainingSession** out); - - /** \brief Create a training session that can be used to begin or resume training. - * This api provides a way to load all the training artifacts from buffers instead of files. - * - * \param[in] env Environment to be used for the training session. - * \param[in] options Session options that the user can customize for this training session. - * \param[in] checkpoint_state Training states that the training session uses as a starting point for training. - * \param[in] train_model_data Buffer containing the model data to be used to perform training - * \param[in] train_data_length Length of the buffer containing train_model_data - * \param[in] eval_model_data Buffer containing the model data to be used to perform evaluation - * \param[in] eval_data_length Length of the buffer containing eval_model_data - * \param[in] optim_model_data Buffer containing the model data to be used to perform weight update - * \param[in] optim_data_length Length of the buffer containing optim_model_data - * \param[out] out Created training session. - * - */ - ORT_API2_STATUS(CreateTrainingSessionFromBuffer, _In_ const OrtEnv* env, - _In_ const OrtSessionOptions* options, _Inout_ OrtCheckpointState* checkpoint_state, - _In_ const void* train_model_data, size_t train_data_length, - _In_ const void* eval_model_data, size_t eval_data_length, - _In_ const void* optim_model_data, size_t optim_data_length, - _Outptr_result_maybenull_ OrtTrainingSession** out); - - /// @} - - /// \name Model IO Information - /// @{ - - /** \brief Retrieves the number of user outputs in the training model. - * - * This function returns the number of outputs of the training model so that the user can - * allocate space for the number of outputs when OrtTrainingApi::TrainStep is invoked. - * - * \param[in] sess The `this` pointer to the training session. - * \param[out] out Number of user outputs in the training model. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(TrainingSessionGetTrainingModelOutputCount, _In_ const OrtTrainingSession* sess, _Out_ size_t* out); - - /** \brief Retrieves the number of user outputs in the eval model. - * - * This function returns the number of outputs of the eval model so that the user can - * allocate space for the number of outputs when OrtTrainingApi::EvalStep is invoked. - * - * \param[in] sess The `this` pointer to the training session. - * \param[out] out Number of user outputs in the eval model. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(TrainingSessionGetEvalModelOutputCount, _In_ const OrtTrainingSession* sess, _Out_ size_t* out); - - /** \brief Retrieves the names of user outputs in the training model. - * - * This function returns the names of outputs of the training model that can be associated with the OrtValue(s) - * returned by the OrtTrainingApi::TrainStep function. - * - * \param[in] sess The `this` pointer to the training session. - * \param[in] index Index of the output name requested. - * \param[in] allocator Allocator to use to allocate the memory for the name. - * \param[out] output Name of the training model output at the given index. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(TrainingSessionGetTrainingModelOutputName, _In_ const OrtTrainingSession* sess, size_t index, _Inout_ OrtAllocator* allocator, _Outptr_ char** output); - - /** \brief Retrieves the names of user outputs in the eval model. - * - * This function returns the names of outputs of the eval model that can be associated with the OrtValue(s) returned - * by the OrtTrainingApi::EvalStep function. - * - * \param[in] sess The `this` pointer to the training session. - * \param[in] index Index of the output name requested. - * \param[in] allocator Allocator to use to allocate the memory for the name. - * \param[out] output Name of the eval model output at the given index. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(TrainingSessionGetEvalModelOutputName, _In_ const OrtTrainingSession* sess, size_t index, _Inout_ OrtAllocator* allocator, _Outptr_ char** output); - - /// @} - - /// \name Implementing The Training Loop - /// @{ - - /** \brief Reset the gradients of all trainable parameters to zero lazily. - * - * This function sets the internal state of the training session such that the gradients of the trainable - * parameters in the OrtCheckpointState will be scheduled to be reset just before the new gradients are - * computed on the next invocation of the next OrtTrainingApi::TrainStep. - * - * \param[in] session The `this` pointer to the training session. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(LazyResetGrad, _Inout_ OrtTrainingSession* session); - - /** \brief Computes the outputs of the training model and the gradients of the trainable parameters for the given inputs - * - * This function performs a training step that computes the outputs of the training model and the gradients - * of the trainable parameters for the given inputs. The train step is performed based on the training model - * that was provided to the training session. - * The OrtTrainingApi::TrainStep is equivalent of running forward propagation and backward propagation in a single - * step. - * The gradients computed are stored inside the training session state so they can be later consumed - * by the OrtTrainingApi::OptimizerStep function. - * The gradients can be lazily reset by invoking the OrtTrainingApi::LazyResetGrad function. - * - * \param[in] sess The `this` pointer to the training session. - * \param[in] run_options Run options for this training step. - * \param[in] inputs_len Number of user inputs to the training model. - * \param[in] inputs The user inputs to the training model. - * \param[in] outputs_len Number of user outputs expected from this training step. - * \param[out] outputs User outputs computed by train step. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(TrainStep, _Inout_ OrtTrainingSession* sess, _In_opt_ const OrtRunOptions* run_options, - _In_ size_t inputs_len, _In_reads_(inputs_len) const OrtValue* const* inputs, - _In_ size_t outputs_len, _Inout_updates_all_(outputs_len) OrtValue** outputs); - - /** \brief Computes the outputs for the eval model for the given inputs - * - * This function performs an eval step that computes the outputs of the eval model for the given inputs. - * The eval step is performed based on the eval model that was provided to the training session. - * - * \param[in] sess The `this` pointer to the training session. - * \param[in] run_options Run options for this eval step. - * \param[in] inputs_len Number of user inputs to the eval model. - * \param[in] inputs The user inputs to the eval model. - * \param[in] outputs_len Number of user outputs expected from this eval step. - * \param[out] outputs User outputs computed by eval step. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(EvalStep, _In_ const OrtTrainingSession* sess, _In_opt_ const OrtRunOptions* run_options, - _In_ size_t inputs_len, _In_reads_(inputs_len) const OrtValue* const* inputs, - _In_ size_t outputs_len, _Inout_updates_all_(outputs_len) OrtValue** outputs); - - /** \brief Sets the learning rate for this training session. - * - * This function allows users to set the learning rate for the training session. The current - * learning rate is maintained by the training session and can be overwritten by invoking - * this function with the desired learning rate. This function should not be used when a valid - * learning rate scheduler is registered. It should be used either to set the learning rate - * derived from a custom learning rate scheduler or to set a constant learning rate to be used - * throughout the training session. - * \note Please note that this function does not set the initial learning rate that may be needed - * by the predefined learning rate schedulers. To set the initial learning rate for learning - * rate schedulers, please look at the function OrtTrainingApi::RegisterLinearLRScheduler. - * - * \param[in] sess The `this` pointer to the training session. - * \param[in] learning_rate Desired learning rate to be set. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(SetLearningRate, _Inout_ OrtTrainingSession* sess, _In_ float learning_rate); - - /** \brief Gets the current learning rate for this training session. - * - * This function allows users to get the learning rate for the training session. The current - * learning rate is maintained by the training session, and users can query it for the purpose - * of implementing their own learning rate schedulers. - * - * \param[in] sess The `this` pointer to the training session. - * \param[out] learning_rate Learning rate currently in use by the training session. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(GetLearningRate, _Inout_ OrtTrainingSession* sess, _Out_ float* learning_rate); - - /** \brief Performs the weight updates for the trainable parameters using the optimizer model. - * - * This function performs the weight update step that updates the trainable parameters such that they - * take a step in the direction of their gradients (gradient descent). The optimizer step is performed - * based on the optimizer model that was provided to the training session. - * The updated parameters are stored inside the training state so that they can be used by the next - * OrtTrainingApi::TrainStep function call. - * - * \param[in] sess The `this` pointer to the training session. - * \param[in] run_options Run options for this optimizer step. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(OptimizerStep, _Inout_ OrtTrainingSession* sess, - _In_opt_ const OrtRunOptions* run_options); - - /** \brief Registers a linear learning rate scheduler for the training session. - * - * Register a linear learning rate scheduler that decays the learning rate by linearly updated - * multiplicative factor from the initial learning rate set on the training session to 0. The decay - * is performed after the initial warm up phase where the learning rate is linearly incremented - * from 0 to the initial learning rate provided. - * - * \param[in] sess The `this` pointer to the training session. - * \param[in] warmup_step_count Warmup steps for LR warmup. - * \param[in] total_step_count Total step count. - * \param[in] initial_lr The initial learning rate to be used by the training session. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(RegisterLinearLRScheduler, _Inout_ OrtTrainingSession* sess, _In_ const int64_t warmup_step_count, - _In_ const int64_t total_step_count, _In_ const float initial_lr); - - /** \brief Update the learning rate based on the registered learing rate scheduler. - * - * Takes a scheduler step that updates the learning rate that is being used by the training session. - * This function should typically be called before invoking the optimizer step for each round, - * or as determined necessary to update the learning rate being used by the training session. - * \note Please note that a valid predefined learning rate scheduler must be first registered to invoke this - * function. - * - * \param[in] sess The `this` pointer to the training session. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(SchedulerStep, _Inout_ OrtTrainingSession* sess); - - /// @} - - /// \name Accessing The Training Session State - /// @{ - /** \brief Retrieves the size of all the parameters. - * - * Calculates the total number of primitive (datatype of the parameters) elements of all the parameters in the - * training state. - * When trainable_only argument is true, the size is calculated for trainable params only. - * - * \param[in] sess The `this` pointer to the training session. - * \param[out] out Size of all parameter elements. - * \param[in] trainable_only Whether to skip non-trainable parameters - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(GetParametersSize, _Inout_ OrtTrainingSession* sess, _Out_ size_t* out, bool trainable_only); - - /** \brief Copy all parameters to a contiguous buffer held by the argument parameters_buffer - * - * The parameters_buffer has to be of the size given by GetParametersSize api call, - * with matching setting for the argument trainable_only. All the target parameters must be of the same - * datatype. The OrtValue must be pre-allocated onto - * the desired device. This is a complementary function to OrtTrainingApi::CopyBufferToParameters. - * Parameter ordering is preserved. - * User is responsible for allocating and freeing the resources used by the parameters_buffer. - * - * \param[in] sess The `this` pointer to the training session. - * \param[in] trainable_only Whether to skip non-trainable parameters - * \param[out] parameters_buffer The pre-allocated OrtValue buffer to copy onto. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(CopyParametersToBuffer, _Inout_ OrtTrainingSession* sess, - _Inout_ OrtValue* parameters_buffer, bool trainable_only); - - /** \brief Copy parameter values from the given contiguous buffer held by parameters_buffer to the training state - * - * The parameters_buffer argument has to be of the size given by OrtTrainingApi::GetParametersSize api call, - * with matching setting for trainable_only argument. All the target parameters must be of the same - * datatype. This is a complementary function to OrtTrainingApi::CopyParametersToBuffer - * and can be used to load updated buffer values onto the training state. - * Parameter ordering is preserved. - * User is responsible for allocating and freeing the resources used by the parameters_buffer. - * In case the training session was created with a nominal checkpoint, invoking this function is required - * to load the updated parameters onto the checkpoint to complete it. - * - * \param[in] sess The `this` pointer to the training session. - * \param[in] trainable_only Whether to skip non-trainable parameters - * \param[out] parameters_buffer The pre-allocated OrtValue buffer to copy from. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(CopyBufferToParameters, _Inout_ OrtTrainingSession* sess, - _Inout_ OrtValue* parameters_buffer, bool trainable_only); - - /// @} - - /// \name Release Training Resources - /// @{ - - /** \brief Frees up the memory used up by the training session. - * - * This function frees up any memory that was allocated in the training session. The training - * session can no longer be used after this call. - * - */ - ORT_CLASS_RELEASE(TrainingSession); - - /** \brief Frees up the memory used up by the checkpoint state. - * - * This function frees up any memory that was allocated in the checkpoint state. The checkpoint - * state can no longer be used after this call. - * \note Note that the checkpoint state must be released only after the training session has been released. - * - */ - ORT_CLASS_RELEASE(CheckpointState); - - /// @} - - /// \name Prepare For Inferencing - /// @{ - /** \brief Export a model that can be used for inferencing. - * - * If the training session was provided with an eval model, the training session can generate - * an inference model if it knows the inference graph outputs. The input inference graph outputs - * are used to prune the eval model so that the inference model's outputs align with the provided outputs. - * The exported model is saved at the path provided and can be used for inferencing with InferenceSession. - * \note Note that the function re-loads the eval model from the path provided to OrtTrainingApi::CreateTrainingSession - * and expects that this path still be valid. - * - * \param[in] sess The `this` pointer to the training session. - * \param[in] inference_model_path Path where the inference model should be serialized to. - * \param[in] graph_outputs_len Size of the graph output names array. - * \param[in] graph_output_names Names of the outputs that are needed in the inference model. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(ExportModelForInferencing, _Inout_ OrtTrainingSession* sess, - _In_ const ORTCHAR_T* inference_model_path, size_t graph_outputs_len, - _In_reads_(graph_outputs_len) const char* const* graph_output_names); - - /// @} - - /// \name Training Utilities - /// @{ - /** \brief Sets the seed used for random number generation in Onnxruntime. - * - * Use this function to generate reproducible results. It should be noted that completely reproducible - * results are not guaranteed. - * - * \param[in] seed The seed to be set. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(SetSeed, _In_ const int64_t seed); - - /// @} - - /// \name Model IO Information - /// @{ - /** \brief Retrieves the number of user inputs in the training model. - * - * This function returns the number of inputs of the training model so that the user can accordingly - * allocate the OrtValue(s) provided to the OrtTrainingApi::TrainStep function. - * - * \param[in] sess The `this` pointer to the training session. - * \param[out] out Number of user inputs in the training model. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(TrainingSessionGetTrainingModelInputCount, _In_ const OrtTrainingSession* sess, _Out_ size_t* out); - - /** \brief Retrieves the number of user inputs in the eval model. - * - * This function returns the number of inputs of the eval model so that the user can accordingly - * allocate the OrtValue(s) provided to the OrtTrainingApi::EvalStep function. - * - * \param[in] sess The `this` pointer to the training session. - * \param[out] out Number of user inputs in the eval model. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(TrainingSessionGetEvalModelInputCount, _In_ const OrtTrainingSession* sess, _Out_ size_t* out); - - /** \brief Retrieves the name of the user input at given index in the training model. - * - * This function returns the names of inputs of the training model that can be associated with the - * OrtValue(s) provided to the OrtTrainingApi::TrainStep function. - * - * \param[in] sess The `this` pointer to the training session. - * \param[in] index The index of the training model input name requested. - * \param[in] allocator The allocator to use to allocate the memory for the requested name. - * \param[out] output Name of the user input for the training model at the given index. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(TrainingSessionGetTrainingModelInputName, _In_ const OrtTrainingSession* sess, size_t index, - _In_ OrtAllocator* allocator, _Outptr_ char** output); - - /** \brief Retrieves the name of the user input at given index in the eval model. - * - * This function returns the names of inputs of the eval model that can be associated with the OrtValue(s) provided - * to the OrtTrainingApi::EvalStep function. - * - * \param[in] sess The `this` pointer to the training session. - * \param[in] index The index of the eval model input name requested. - * \param[in] allocator The allocator to use to allocate the memory for the requested name. - * \param[out] output Name of the user input for the eval model at the given index. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(TrainingSessionGetEvalModelInputName, _In_ const OrtTrainingSession* sess, size_t index, - _In_ OrtAllocator* allocator, _Outptr_ char** output); - - /// @} - - /// \name Accessing The Training Session State - /// @{ - - /** \brief Adds or updates the given property to/in the checkpoint state. - * - * Runtime properties such as epoch, training step, best score, and others can be added to the checkpoint - * state by the user by calling this function with the corresponding property name and value. - * The given property name must be unique to be able to successfully add the property. - * - * \param[in] checkpoint_state The checkpoint state which should hold the property. - * \param[in] property_name Name of the property being added or updated. - * \param[in] property_type Type of the property associated with the given name. - * \param[in] property_value Property value associated with the given name. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(AddProperty, _Inout_ OrtCheckpointState* checkpoint_state, - _In_ const char* property_name, _In_ enum OrtPropertyType property_type, - _In_ void* property_value); - - /** \brief Gets the property value associated with the given name from the checkpoint state. - * - * Gets the property value from an existing entry in the checkpoint state. The property must - * exist in the checkpoint state to be able to retrieve it successfully. - * - * \param[in] checkpoint_state The checkpoint state that is currently holding the property. - * \param[in] property_name Name of the property being retrieved. - * \param[in] allocator Allocator used to allocate the memory for the property_value. - * \param[out] property_type Type of the property associated with the given name. - * \param[out] property_value Property value associated with the given name. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(GetProperty, _In_ const OrtCheckpointState* checkpoint_state, - _In_ const char* property_name, _Inout_ OrtAllocator* allocator, - _Out_ enum OrtPropertyType* property_type, _Outptr_ void** property_value); - - /// @} - - /// \name Accessing The Training Session State - /// @{ - - /** \brief Load a checkpoint state from a buffer into checkpoint_state. - * - * This function will parse a checkpoint bytes buffer, pull relevant data and load the training - * state into the checkpoint_state. This checkpoint state can then be used to create the - * training session by invoking OrtTrainingApi::CreateTrainingSession. By doing so, the training - * session will resume training from the given checkpoint state. - * \note Note that the training session created with a checkpoint state uses this state to store the entire - * training state (including model parameters, its gradients, the optimizer states and the properties). - * As a result, it is required that the checkpoint state outlive the lifetime of the training session. - * - * \param[in] checkpoint_buffer Path to the checkpoint bytes buffer. - * \param[in] num_bytes Number of bytes in the checkpoint buffer. - * \param[out] checkpoint_state Checkpoint state that contains the states of the training session. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(LoadCheckpointFromBuffer, _In_ const void* checkpoint_buffer, - _In_ const size_t num_bytes, _Outptr_ OrtCheckpointState** checkpoint_state); - - /** \brief Retrieves the type and shape information of the parameter associated with the given parameter name. - * - * This function retrieves the type and shape of the parameter associated with the given parameter name. - * The parameter must exist in the checkpoint state to be able to retrieve its type and shape information successfully. - * - * \param[in] checkpoint_state The checkpoint state. - * \param[in] parameter_name Name of the parameter being retrieved. - * \param[out] parameter_type_and_shape The type and shape of the parameter being retrieved. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(GetParameterTypeAndShape, _In_ const OrtCheckpointState* checkpoint_state, - _In_ const char* parameter_name, _Outptr_ OrtTensorTypeAndShapeInfo** parameter_type_and_shape); - - /** \brief Updates the data associated with the model parameter in the checkpoint state for the given parameter name. - * - * This function updates a model parameter in the checkpoint state with the given parameter data. - * The training session must be already created with the checkpoint state that contains the parameter - * being updated. The given parameter is copied over to the registered device for the training session. - * The parameter must exist in the checkpoint state to be able to update it successfully. - * - * \param[in] checkpoint_state The checkpoint state. - * \param[in] parameter_name Name of the parameter being updated. - * \param[in] parameter The parameter data that should replace the existing parameter data. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(UpdateParameter, _Inout_ OrtCheckpointState* checkpoint_state, - _In_ const char* parameter_name, _In_ OrtValue* parameter); - - /** \brief Gets the data associated with the model parameter from the checkpoint state for the given parameter name. - * - * This function retrieves the model parameter data from the checkpoint state for the given parameter name. - * The parameter is copied over and returned as an OrtValue. The training session must be already created - * with the checkpoint state that contains the parameter being retrieved. - * The parameter must exist in the checkpoint state to be able to retrieve it successfully. - * - * \param[in] checkpoint_state The checkpoint state. - * \param[in] parameter_name Name of the parameter being retrieved. - * \param[in] allocator Allocator used to allocate the memory for the parameter. - * \param[out] parameter The parameter data that is retrieved from the checkpoint state. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(GetParameter, _In_ const OrtCheckpointState* checkpoint_state, - _In_ const char* parameter_name, _Inout_ OrtAllocator* allocator, - _Outptr_ OrtValue** parameter); - - /// @} -}; - -typedef struct OrtTrainingApi OrtTrainingApi; - -/// @} +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// This file contains the training c apis. + +#pragma once +#include +#include "onnxruntime_c_api.h" + +/** \page training_c_cpp_api Training C & C++ APIs + * + * Training C and C++ APIs are an extension of the \ref c_cpp_api "onnxruntime core C and C++ APIs" and should be used in conjunction with them. + * + * In order to train a model with onnxruntime, the following training artifacts must be generated: + * - The training onnx model + * - The checkpoint file + * - The optimizer onnx model + * - The eval onnx model model (optional) + * + * These training artifacts can be generated as part of an offline step using the python [utilities](https://github.com/microsoft/onnxruntime/blob/main/orttraining/orttraining/python/training/onnxblock/README.md) made available in the `onnxruntime-training` python package. + * + * After these artifacts have been generated, the C and C++ utilities listed in this documentation can be leveraged to perform training. + * + * If any problem is encountered, please create an [issue](https://github.com/microsoft/onnxruntime/issues/new) with your scenario and requirements, and we will be sure to respond and follow up on the request. + * + *

Training C API

+ * + * ::OrtTrainingApi - Training C API functions. + * + * This C structure contains functions that enable users to perform training with onnxruntime. + * + * _Sample Code_: + * + * ```c + * #include + * + * OrtApi* g_ort_api = OrtGetApiBase()->GetApi(ORT_API_VERSION); + * OrtTrainingApi* g_ort_training_api = g_ort_api->GetTrainingApi(ORT_API_VERSION); + * + * OrtEnv* env = NULL; + * g_ort_api->CreateEnv(logging_level, logid, &env); + * OrtSessionOptions* session_options = NULL; + * g_ort_api->CreateSessionOptions(&session_options); + * + * OrtCheckpointState* state = NULL; + * g_ort_training_api->LoadCheckpoint(path_to_checkpoint, &state); + * + * OrtTrainingSession* training_session = NULL; + * g_ort_training_api->CreateTrainingSession(env, session_options, training_model_path, + * state, eval_model_path, optimizer_model_path, + * &training_session); + * // Training loop + * { + * g_ort_training_api->TrainStep(...); + * g_ort_training_api->OptimizerStep(...); + * g_ort_training_api->LazyResetGrad(...); + * } + * + * g_ort_training_api->ExportModelForInferencing(training_session, inference_model_path, ...); + * g_ort_training_api->SaveCheckpoint(state, path_to_checkpoint, false); + * + * g_ort_training_api->ReleaseTrainingSession(training_session); + * g_ort_training_api->ReleaseCheckpointState(state); + * ``` + * + * > **Note** + * > The ::OrtCheckpointState contains the entire training state that the ::OrtTrainingSession uses. As a result, the training session must always have access to the state. That is to say, the ::OrtCheckpointState instance must outlive the lifetime of the ::OrtTrainingSession instance. + * + *

Training C++ API

+ * + * @ref TrainingCpp - Training C++ API classes and functions. + * + * These C++ classes and functions enable users to perform training with onnxruntime. + * + * _Sample Code_: + * + * ```cc + * #include + * + * Ort::Env env; + * Ort::SessionOptions session_options; + * + * auto state = Ort::CheckpointState::LoadCheckpoint(path_to_checkpoint); + * auto training_session = Ort::TrainingSession(env, session_options, state, training_model_path, + * eval_model_path, optimizer_model_path); + * + * // Training Loop + * { + * training_session.TrainStep(...); + * training_session.OptimizerStep(...); + * training_session.LazyResetGrad(...); + * } + * + * training_session->ExportModelForInferencing(inference_model_path, ...); + * Ort::CheckpointState::SaveCheckpoint(state, path_to_checkpoint, false); + * ``` + * > **Note** + * > The ::Ort::CheckpointState contains the entire training state that the ::Ort::TrainingSession uses. As a result, the training session must always have access to the state. That is to say, the ::Ort::CheckpointState instance must outlive the lifetime of the ::Ort::TrainingSession instance. + */ + +/** @defgroup TrainingC Ort Training C API + * @{ + */ +ORT_RUNTIME_CLASS(TrainingSession); // Type that enables performing training for the given user models. +ORT_RUNTIME_CLASS(CheckpointState); // Type that holds the training states for the training session. + +/** \brief Type of property to be added to or returned from the ::OrtCheckpointState. + */ +typedef enum OrtPropertyType { + OrtIntProperty = 0, + OrtFloatProperty = 1, + OrtStringProperty = 2, +} OrtPropertyType; + +/** \brief The Training C API that holds onnxruntime training function pointers + * + * All the Training C API functions are defined inside this structure as pointers to functions. + * Call OrtApi::GetTrainingApi to get a pointer to this struct. + * + * \nosubgrouping + */ +struct OrtTrainingApi { + /// \name Accessing The Training Session State + /// @{ + + /** \brief Load a checkpoint state from a file on disk into checkpoint_state. + * + * This function will parse a checkpoint file, pull relevant data and load the training + * state into the checkpoint_state. This checkpoint state can then be used to create the + * training session by invoking OrtTrainingApi::CreateTrainingSession. By doing so, the training + * session will resume training from the given checkpoint state. + * \note Note that the training session created with a checkpoint state uses this state to store the entire + * training state (including model parameters, its gradients, the optimizer states and the properties). + * As a result, it is required that the checkpoint state outlive the lifetime of the training session. + * \note Note that the checkpoint file can be either the complete checkpoint or the nominal checkpoint. + * + * \param[in] checkpoint_path Path to the checkpoint file + * \param[out] checkpoint_state Checkpoint state that contains the states of the training session. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(LoadCheckpoint, _In_ const ORTCHAR_T* checkpoint_path, + _Outptr_ OrtCheckpointState** checkpoint_state); + + /** \brief Save the given state to a checkpoint file on disk. + * + * This function serializes the provided checkpoint state to a file on disk. + * This checkpoint can later be loaded by invoking OrtTrainingApi::LoadCheckpoint to resume + * training from this snapshot of the state. + * + * \param[in] checkpoint_state The checkpoint state to save. + * \param[in] checkpoint_path Path to the checkpoint file. + * \param[in] include_optimizer_state Flag to indicate whether to save the optimizer state or not. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(SaveCheckpoint, _In_ OrtCheckpointState* checkpoint_state, _In_ const ORTCHAR_T* checkpoint_path, + const bool include_optimizer_state); + + /// @} + + /// \name Implementing The Training Loop + /// @{ + /** \brief Create a training session that can be used to begin or resume training. + * + * This function creates a training session based on the env and session options provided that can + * begin or resume training from a given checkpoint state for the given onnx models. + * The checkpoint state represents the parameters of the training session which will be moved + * to the device specified by the user through the session options (if necessary). + * The training session requires four training artifacts + * - The training onnx model + * - The evaluation onnx model (optional) + * - The optimizer onnx model + * - The checkpoint file + * + * These artifacts can be generated using the `onnxruntime-training` python [utility](https://github.com/microsoft/onnxruntime/blob/main/orttraining/orttraining/python/training/onnxblock/README.md). + * + * \param[in] env Environment to be used for the training session. + * \param[in] options Session options that the user can customize for this training session. + * \param[in] checkpoint_state Training states that the training session uses as a starting point for training. + * \param[in] train_model_path Model to be used to perform training. + * \param[in] eval_model_path Model to be used to perform evaluation. + * \param[in] optimizer_model_path Model to be used to perform gradient descent. + * \param[out] out Created training session. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(CreateTrainingSession, _In_ const OrtEnv* env, _In_ const OrtSessionOptions* options, + _Inout_ OrtCheckpointState* checkpoint_state, _In_ const ORTCHAR_T* train_model_path, + _In_ const ORTCHAR_T* eval_model_path, _In_ const ORTCHAR_T* optimizer_model_path, + _Outptr_result_maybenull_ OrtTrainingSession** out); + + /** \brief Create a training session that can be used to begin or resume training. + * This api provides a way to load all the training artifacts from buffers instead of files. + * + * \param[in] env Environment to be used for the training session. + * \param[in] options Session options that the user can customize for this training session. + * \param[in] checkpoint_state Training states that the training session uses as a starting point for training. + * \param[in] train_model_data Buffer containing the model data to be used to perform training + * \param[in] train_data_length Length of the buffer containing train_model_data + * \param[in] eval_model_data Buffer containing the model data to be used to perform evaluation + * \param[in] eval_data_length Length of the buffer containing eval_model_data + * \param[in] optim_model_data Buffer containing the model data to be used to perform weight update + * \param[in] optim_data_length Length of the buffer containing optim_model_data + * \param[out] out Created training session. + * + */ + ORT_API2_STATUS(CreateTrainingSessionFromBuffer, _In_ const OrtEnv* env, + _In_ const OrtSessionOptions* options, _Inout_ OrtCheckpointState* checkpoint_state, + _In_ const void* train_model_data, size_t train_data_length, + _In_ const void* eval_model_data, size_t eval_data_length, + _In_ const void* optim_model_data, size_t optim_data_length, + _Outptr_result_maybenull_ OrtTrainingSession** out); + + /// @} + + /// \name Model IO Information + /// @{ + + /** \brief Retrieves the number of user outputs in the training model. + * + * This function returns the number of outputs of the training model so that the user can + * allocate space for the number of outputs when OrtTrainingApi::TrainStep is invoked. + * + * \param[in] sess The `this` pointer to the training session. + * \param[out] out Number of user outputs in the training model. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainingSessionGetTrainingModelOutputCount, _In_ const OrtTrainingSession* sess, _Out_ size_t* out); + + /** \brief Retrieves the number of user outputs in the eval model. + * + * This function returns the number of outputs of the eval model so that the user can + * allocate space for the number of outputs when OrtTrainingApi::EvalStep is invoked. + * + * \param[in] sess The `this` pointer to the training session. + * \param[out] out Number of user outputs in the eval model. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainingSessionGetEvalModelOutputCount, _In_ const OrtTrainingSession* sess, _Out_ size_t* out); + + /** \brief Retrieves the names of user outputs in the training model. + * + * This function returns the names of outputs of the training model that can be associated with the OrtValue(s) + * returned by the OrtTrainingApi::TrainStep function. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] index Index of the output name requested. + * \param[in] allocator Allocator to use to allocate the memory for the name. + * \param[out] output Name of the training model output at the given index. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainingSessionGetTrainingModelOutputName, _In_ const OrtTrainingSession* sess, size_t index, _Inout_ OrtAllocator* allocator, _Outptr_ char** output); + + /** \brief Retrieves the names of user outputs in the eval model. + * + * This function returns the names of outputs of the eval model that can be associated with the OrtValue(s) returned + * by the OrtTrainingApi::EvalStep function. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] index Index of the output name requested. + * \param[in] allocator Allocator to use to allocate the memory for the name. + * \param[out] output Name of the eval model output at the given index. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainingSessionGetEvalModelOutputName, _In_ const OrtTrainingSession* sess, size_t index, _Inout_ OrtAllocator* allocator, _Outptr_ char** output); + + /// @} + + /// \name Implementing The Training Loop + /// @{ + + /** \brief Reset the gradients of all trainable parameters to zero lazily. + * + * This function sets the internal state of the training session such that the gradients of the trainable + * parameters in the OrtCheckpointState will be scheduled to be reset just before the new gradients are + * computed on the next invocation of the next OrtTrainingApi::TrainStep. + * + * \param[in] session The `this` pointer to the training session. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(LazyResetGrad, _Inout_ OrtTrainingSession* session); + + /** \brief Computes the outputs of the training model and the gradients of the trainable parameters for the given inputs + * + * This function performs a training step that computes the outputs of the training model and the gradients + * of the trainable parameters for the given inputs. The train step is performed based on the training model + * that was provided to the training session. + * The OrtTrainingApi::TrainStep is equivalent of running forward propagation and backward propagation in a single + * step. + * The gradients computed are stored inside the training session state so they can be later consumed + * by the OrtTrainingApi::OptimizerStep function. + * The gradients can be lazily reset by invoking the OrtTrainingApi::LazyResetGrad function. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] run_options Run options for this training step. + * \param[in] inputs_len Number of user inputs to the training model. + * \param[in] inputs The user inputs to the training model. + * \param[in] outputs_len Number of user outputs expected from this training step. + * \param[out] outputs User outputs computed by train step. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainStep, _Inout_ OrtTrainingSession* sess, _In_opt_ const OrtRunOptions* run_options, + _In_ size_t inputs_len, _In_reads_(inputs_len) const OrtValue* const* inputs, + _In_ size_t outputs_len, _Inout_updates_all_(outputs_len) OrtValue** outputs); + + /** \brief Computes the outputs for the eval model for the given inputs + * + * This function performs an eval step that computes the outputs of the eval model for the given inputs. + * The eval step is performed based on the eval model that was provided to the training session. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] run_options Run options for this eval step. + * \param[in] inputs_len Number of user inputs to the eval model. + * \param[in] inputs The user inputs to the eval model. + * \param[in] outputs_len Number of user outputs expected from this eval step. + * \param[out] outputs User outputs computed by eval step. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(EvalStep, _In_ const OrtTrainingSession* sess, _In_opt_ const OrtRunOptions* run_options, + _In_ size_t inputs_len, _In_reads_(inputs_len) const OrtValue* const* inputs, + _In_ size_t outputs_len, _Inout_updates_all_(outputs_len) OrtValue** outputs); + + /** \brief Sets the learning rate for this training session. + * + * This function allows users to set the learning rate for the training session. The current + * learning rate is maintained by the training session and can be overwritten by invoking + * this function with the desired learning rate. This function should not be used when a valid + * learning rate scheduler is registered. It should be used either to set the learning rate + * derived from a custom learning rate scheduler or to set a constant learning rate to be used + * throughout the training session. + * \note Please note that this function does not set the initial learning rate that may be needed + * by the predefined learning rate schedulers. To set the initial learning rate for learning + * rate schedulers, please look at the function OrtTrainingApi::RegisterLinearLRScheduler. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] learning_rate Desired learning rate to be set. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(SetLearningRate, _Inout_ OrtTrainingSession* sess, _In_ float learning_rate); + + /** \brief Gets the current learning rate for this training session. + * + * This function allows users to get the learning rate for the training session. The current + * learning rate is maintained by the training session, and users can query it for the purpose + * of implementing their own learning rate schedulers. + * + * \param[in] sess The `this` pointer to the training session. + * \param[out] learning_rate Learning rate currently in use by the training session. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(GetLearningRate, _Inout_ OrtTrainingSession* sess, _Out_ float* learning_rate); + + /** \brief Performs the weight updates for the trainable parameters using the optimizer model. + * + * This function performs the weight update step that updates the trainable parameters such that they + * take a step in the direction of their gradients (gradient descent). The optimizer step is performed + * based on the optimizer model that was provided to the training session. + * The updated parameters are stored inside the training state so that they can be used by the next + * OrtTrainingApi::TrainStep function call. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] run_options Run options for this optimizer step. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(OptimizerStep, _Inout_ OrtTrainingSession* sess, + _In_opt_ const OrtRunOptions* run_options); + + /** \brief Registers a linear learning rate scheduler for the training session. + * + * Register a linear learning rate scheduler that decays the learning rate by linearly updated + * multiplicative factor from the initial learning rate set on the training session to 0. The decay + * is performed after the initial warm up phase where the learning rate is linearly incremented + * from 0 to the initial learning rate provided. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] warmup_step_count Warmup steps for LR warmup. + * \param[in] total_step_count Total step count. + * \param[in] initial_lr The initial learning rate to be used by the training session. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(RegisterLinearLRScheduler, _Inout_ OrtTrainingSession* sess, _In_ const int64_t warmup_step_count, + _In_ const int64_t total_step_count, _In_ const float initial_lr); + + /** \brief Update the learning rate based on the registered learing rate scheduler. + * + * Takes a scheduler step that updates the learning rate that is being used by the training session. + * This function should typically be called before invoking the optimizer step for each round, + * or as determined necessary to update the learning rate being used by the training session. + * \note Please note that a valid predefined learning rate scheduler must be first registered to invoke this + * function. + * + * \param[in] sess The `this` pointer to the training session. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(SchedulerStep, _Inout_ OrtTrainingSession* sess); + + /// @} + + /// \name Accessing The Training Session State + /// @{ + /** \brief Retrieves the size of all the parameters. + * + * Calculates the total number of primitive (datatype of the parameters) elements of all the parameters in the + * training state. + * When trainable_only argument is true, the size is calculated for trainable params only. + * + * \param[in] sess The `this` pointer to the training session. + * \param[out] out Size of all parameter elements. + * \param[in] trainable_only Whether to skip non-trainable parameters + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(GetParametersSize, _Inout_ OrtTrainingSession* sess, _Out_ size_t* out, bool trainable_only); + + /** \brief Copy all parameters to a contiguous buffer held by the argument parameters_buffer + * + * The parameters_buffer has to be of the size given by GetParametersSize api call, + * with matching setting for the argument trainable_only. All the target parameters must be of the same + * datatype. The OrtValue must be pre-allocated onto + * the desired device. This is a complementary function to OrtTrainingApi::CopyBufferToParameters. + * Parameter ordering is preserved. + * User is responsible for allocating and freeing the resources used by the parameters_buffer. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] trainable_only Whether to skip non-trainable parameters + * \param[out] parameters_buffer The pre-allocated OrtValue buffer to copy onto. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(CopyParametersToBuffer, _Inout_ OrtTrainingSession* sess, + _Inout_ OrtValue* parameters_buffer, bool trainable_only); + + /** \brief Copy parameter values from the given contiguous buffer held by parameters_buffer to the training state + * + * The parameters_buffer argument has to be of the size given by OrtTrainingApi::GetParametersSize api call, + * with matching setting for trainable_only argument. All the target parameters must be of the same + * datatype. This is a complementary function to OrtTrainingApi::CopyParametersToBuffer + * and can be used to load updated buffer values onto the training state. + * Parameter ordering is preserved. + * User is responsible for allocating and freeing the resources used by the parameters_buffer. + * In case the training session was created with a nominal checkpoint, invoking this function is required + * to load the updated parameters onto the checkpoint to complete it. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] trainable_only Whether to skip non-trainable parameters + * \param[out] parameters_buffer The pre-allocated OrtValue buffer to copy from. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(CopyBufferToParameters, _Inout_ OrtTrainingSession* sess, + _Inout_ OrtValue* parameters_buffer, bool trainable_only); + + /// @} + + /// \name Release Training Resources + /// @{ + + /** \brief Frees up the memory used up by the training session. + * + * This function frees up any memory that was allocated in the training session. The training + * session can no longer be used after this call. + * + */ + ORT_CLASS_RELEASE(TrainingSession); + + /** \brief Frees up the memory used up by the checkpoint state. + * + * This function frees up any memory that was allocated in the checkpoint state. The checkpoint + * state can no longer be used after this call. + * \note Note that the checkpoint state must be released only after the training session has been released. + * + */ + ORT_CLASS_RELEASE(CheckpointState); + + /// @} + + /// \name Prepare For Inferencing + /// @{ + /** \brief Export a model that can be used for inferencing. + * + * If the training session was provided with an eval model, the training session can generate + * an inference model if it knows the inference graph outputs. The input inference graph outputs + * are used to prune the eval model so that the inference model's outputs align with the provided outputs. + * The exported model is saved at the path provided and can be used for inferencing with InferenceSession. + * \note Note that the function re-loads the eval model from the path provided to OrtTrainingApi::CreateTrainingSession + * and expects that this path still be valid. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] inference_model_path Path where the inference model should be serialized to. + * \param[in] graph_outputs_len Size of the graph output names array. + * \param[in] graph_output_names Names of the outputs that are needed in the inference model. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(ExportModelForInferencing, _Inout_ OrtTrainingSession* sess, + _In_ const ORTCHAR_T* inference_model_path, size_t graph_outputs_len, + _In_reads_(graph_outputs_len) const char* const* graph_output_names); + + /// @} + + /// \name Training Utilities + /// @{ + /** \brief Sets the seed used for random number generation in Onnxruntime. + * + * Use this function to generate reproducible results. It should be noted that completely reproducible + * results are not guaranteed. + * + * \param[in] seed The seed to be set. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(SetSeed, _In_ const int64_t seed); + + /// @} + + /// \name Model IO Information + /// @{ + /** \brief Retrieves the number of user inputs in the training model. + * + * This function returns the number of inputs of the training model so that the user can accordingly + * allocate the OrtValue(s) provided to the OrtTrainingApi::TrainStep function. + * + * \param[in] sess The `this` pointer to the training session. + * \param[out] out Number of user inputs in the training model. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainingSessionGetTrainingModelInputCount, _In_ const OrtTrainingSession* sess, _Out_ size_t* out); + + /** \brief Retrieves the number of user inputs in the eval model. + * + * This function returns the number of inputs of the eval model so that the user can accordingly + * allocate the OrtValue(s) provided to the OrtTrainingApi::EvalStep function. + * + * \param[in] sess The `this` pointer to the training session. + * \param[out] out Number of user inputs in the eval model. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainingSessionGetEvalModelInputCount, _In_ const OrtTrainingSession* sess, _Out_ size_t* out); + + /** \brief Retrieves the name of the user input at given index in the training model. + * + * This function returns the names of inputs of the training model that can be associated with the + * OrtValue(s) provided to the OrtTrainingApi::TrainStep function. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] index The index of the training model input name requested. + * \param[in] allocator The allocator to use to allocate the memory for the requested name. + * \param[out] output Name of the user input for the training model at the given index. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainingSessionGetTrainingModelInputName, _In_ const OrtTrainingSession* sess, size_t index, + _In_ OrtAllocator* allocator, _Outptr_ char** output); + + /** \brief Retrieves the name of the user input at given index in the eval model. + * + * This function returns the names of inputs of the eval model that can be associated with the OrtValue(s) provided + * to the OrtTrainingApi::EvalStep function. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] index The index of the eval model input name requested. + * \param[in] allocator The allocator to use to allocate the memory for the requested name. + * \param[out] output Name of the user input for the eval model at the given index. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainingSessionGetEvalModelInputName, _In_ const OrtTrainingSession* sess, size_t index, + _In_ OrtAllocator* allocator, _Outptr_ char** output); + + /// @} + + /// \name Accessing The Training Session State + /// @{ + + /** \brief Adds or updates the given property to/in the checkpoint state. + * + * Runtime properties such as epoch, training step, best score, and others can be added to the checkpoint + * state by the user by calling this function with the corresponding property name and value. + * The given property name must be unique to be able to successfully add the property. + * + * \param[in] checkpoint_state The checkpoint state which should hold the property. + * \param[in] property_name Name of the property being added or updated. + * \param[in] property_type Type of the property associated with the given name. + * \param[in] property_value Property value associated with the given name. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(AddProperty, _Inout_ OrtCheckpointState* checkpoint_state, + _In_ const char* property_name, _In_ enum OrtPropertyType property_type, + _In_ void* property_value); + + /** \brief Gets the property value associated with the given name from the checkpoint state. + * + * Gets the property value from an existing entry in the checkpoint state. The property must + * exist in the checkpoint state to be able to retrieve it successfully. + * + * \param[in] checkpoint_state The checkpoint state that is currently holding the property. + * \param[in] property_name Name of the property being retrieved. + * \param[in] allocator Allocator used to allocate the memory for the property_value. + * \param[out] property_type Type of the property associated with the given name. + * \param[out] property_value Property value associated with the given name. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(GetProperty, _In_ const OrtCheckpointState* checkpoint_state, + _In_ const char* property_name, _Inout_ OrtAllocator* allocator, + _Out_ enum OrtPropertyType* property_type, _Outptr_ void** property_value); + + /// @} + + /// \name Accessing The Training Session State + /// @{ + + /** \brief Load a checkpoint state from a buffer into checkpoint_state. + * + * This function will parse a checkpoint bytes buffer, pull relevant data and load the training + * state into the checkpoint_state. This checkpoint state can then be used to create the + * training session by invoking OrtTrainingApi::CreateTrainingSession. By doing so, the training + * session will resume training from the given checkpoint state. + * \note Note that the training session created with a checkpoint state uses this state to store the entire + * training state (including model parameters, its gradients, the optimizer states and the properties). + * As a result, it is required that the checkpoint state outlive the lifetime of the training session. + * + * \param[in] checkpoint_buffer Path to the checkpoint bytes buffer. + * \param[in] num_bytes Number of bytes in the checkpoint buffer. + * \param[out] checkpoint_state Checkpoint state that contains the states of the training session. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(LoadCheckpointFromBuffer, _In_ const void* checkpoint_buffer, + _In_ const size_t num_bytes, _Outptr_ OrtCheckpointState** checkpoint_state); + + /** \brief Retrieves the type and shape information of the parameter associated with the given parameter name. + * + * This function retrieves the type and shape of the parameter associated with the given parameter name. + * The parameter must exist in the checkpoint state to be able to retrieve its type and shape information successfully. + * + * \param[in] checkpoint_state The checkpoint state. + * \param[in] parameter_name Name of the parameter being retrieved. + * \param[out] parameter_type_and_shape The type and shape of the parameter being retrieved. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(GetParameterTypeAndShape, _In_ const OrtCheckpointState* checkpoint_state, + _In_ const char* parameter_name, _Outptr_ OrtTensorTypeAndShapeInfo** parameter_type_and_shape); + + /** \brief Updates the data associated with the model parameter in the checkpoint state for the given parameter name. + * + * This function updates a model parameter in the checkpoint state with the given parameter data. + * The training session must be already created with the checkpoint state that contains the parameter + * being updated. The given parameter is copied over to the registered device for the training session. + * The parameter must exist in the checkpoint state to be able to update it successfully. + * + * \param[in] checkpoint_state The checkpoint state. + * \param[in] parameter_name Name of the parameter being updated. + * \param[in] parameter The parameter data that should replace the existing parameter data. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(UpdateParameter, _Inout_ OrtCheckpointState* checkpoint_state, + _In_ const char* parameter_name, _In_ OrtValue* parameter); + + /** \brief Gets the data associated with the model parameter from the checkpoint state for the given parameter name. + * + * This function retrieves the model parameter data from the checkpoint state for the given parameter name. + * The parameter is copied over and returned as an OrtValue. The training session must be already created + * with the checkpoint state that contains the parameter being retrieved. + * The parameter must exist in the checkpoint state to be able to retrieve it successfully. + * + * \param[in] checkpoint_state The checkpoint state. + * \param[in] parameter_name Name of the parameter being retrieved. + * \param[in] allocator Allocator used to allocate the memory for the parameter. + * \param[out] parameter The parameter data that is retrieved from the checkpoint state. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(GetParameter, _In_ const OrtCheckpointState* checkpoint_state, + _In_ const char* parameter_name, _Inout_ OrtAllocator* allocator, + _Outptr_ OrtValue** parameter); + + /// @} +}; + +typedef struct OrtTrainingApi OrtTrainingApi; + +/// @} diff --git a/3rdParty/ONNX/onnxruntime_training_cxx_api.h b/3rdParty/ONNX/onnxruntime_training_cxx_api.h index e78c16136a..2697db5c21 100644 --- a/3rdParty/ONNX/onnxruntime_training_cxx_api.h +++ b/3rdParty/ONNX/onnxruntime_training_cxx_api.h @@ -1,418 +1,418 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once -#include "onnxruntime_training_c_api.h" -#include -#include - -namespace Ort::detail { - -#define ORT_DECLARE_TRAINING_RELEASE(NAME) \ - void OrtRelease(Ort##NAME* ptr); - -// These release methods must be forward declared before including onnxruntime_cxx_api.h -// otherwise class Base won't be aware of them -ORT_DECLARE_TRAINING_RELEASE(CheckpointState); -ORT_DECLARE_TRAINING_RELEASE(TrainingSession); - -} // namespace Ort::detail - -#include "onnxruntime_cxx_api.h" - -namespace Ort { - -/// -/// This function returns the C training api struct with the pointers to the ort training C functions. -/// If using C++, please use the class instances instead of invoking the C functions directly. -/// -/// OrtTrainingApi struct with ort training C function pointers. -inline const OrtTrainingApi& GetTrainingApi() { return *GetApi().GetTrainingApi(ORT_API_VERSION); } - -namespace detail { - -#define ORT_DEFINE_TRAINING_RELEASE(NAME) \ - inline void OrtRelease(Ort##NAME* ptr) { GetTrainingApi().Release##NAME(ptr); } - -ORT_DEFINE_TRAINING_RELEASE(CheckpointState); -ORT_DEFINE_TRAINING_RELEASE(TrainingSession); - -#undef ORT_DECLARE_TRAINING_RELEASE -#undef ORT_DEFINE_TRAINING_RELEASE - -} // namespace detail - -using Property = std::variant; - -/** - * \defgroup TrainingCpp Ort Training C++ API - * @{ - */ - -/** \brief Holds the state of the training session. - * - * This class holds the entire training session state that includes model parameters, their gradients, - * optimizer parameters, and user properties. The Ort::TrainingSession leverages the Ort::CheckpointState - * by accessing and updating the contained training state. - * \note Note that the training session created with a checkpoint state uses this state to store the entire - * training state (including model parameters, its gradients, the optimizer states and the properties). - * The Ort::TrainingSession does not hold a copy of the Ort::CheckpointState and as a result, it is required - * that the checkpoint state outlive the lifetime of the training session. - * \note Note that the checkpoint state can be either the complete checkpoint state or the nominal checkpoint - * state depending on the version provided while loading the checkpoint. - * - */ -class CheckpointState : public detail::Base { - private: - CheckpointState(OrtCheckpointState* checkpoint_state) { p_ = checkpoint_state; } - - public: - // Construct the checkpoint state by loading the checkpoint by calling LoadCheckpoint - CheckpointState() = delete; - - /// \name Accessing The Training Session State - /// @{ - - /** \brief Load a checkpoint state from a file on disk into checkpoint_state. - * - * This function will parse a checkpoint file, pull relevant data and load the training - * state and return an instance of Ort::CheckpointState. This checkpoint state can then be used to create the - * training session by instantiating Ort::TrainingSession. By doing so, the training session will resume - * training from the given checkpoint state. - * - * \param[in] path_to_checkpoint Path to the checkpoint file - * \return Ort::CheckpointState object which holds the state of the training session parameters. - * - */ - static CheckpointState LoadCheckpoint(const std::basic_string& path_to_checkpoint); - - /** \brief Load a checkpoint state from a buffer. - * - * This function will parse a checkpoint buffer, pull relevant data and load the training - * state and return an instance of Ort::CheckpointState. This checkpoint state can then be used to create the - * training session by instantiating Ort::TrainingSession. By doing so, the training session will resume - * training from the given checkpoint state. - * - * \param[in] buffer Buffer containing the checkpoint data. - * \return Ort::CheckpointState object which holds the state of the training session parameters. - * - */ - static CheckpointState LoadCheckpointFromBuffer(const std::vector& buffer); - - /** \brief Save the given state to a checkpoint file on disk. - * - * This function serializes the provided checkpoint state to a file on disk. - * This checkpoint can later be loaded by invoking Ort::CheckpointState::LoadCheckpoint to resume - * training from this snapshot of the state. - * - * \param[in] checkpoint_state The checkpoint state to save. - * \param[in] path_to_checkpoint Path to the checkpoint file. - * \param[in] include_optimizer_state Flag to indicate whether to save the optimizer state or not. - * - */ - static void SaveCheckpoint(const CheckpointState& checkpoint_state, - const std::basic_string& path_to_checkpoint, - const bool include_optimizer_state = false); - - /** \brief Adds or updates the given property to/in the checkpoint state. - * - * Runtime properties such as epoch, training step, best score, and others can be added to the checkpoint - * state by the user by calling this function with the corresponding property name and value. - * The given property name must be unique to be able to successfully add the property. - * - * \param[in] property_name Name of the property being added or updated. - * \param[in] property_value Property value associated with the given name. - * - */ - void AddProperty(const std::string& property_name, const Property& property_value); - - /** \brief Gets the property value associated with the given name from the checkpoint state. - * - * Gets the property value from an existing entry in the checkpoint state. The property must - * exist in the checkpoint state to be able to retrieve it successfully. - * - * \param[in] property_name Name of the property being retrieved. - * \return Property value associated with the given property name. - * - */ - Property GetProperty(const std::string& property_name); - - /** \brief Updates the data associated with the model parameter in the checkpoint state for the given parameter name. - * - * This function updates a model parameter in the checkpoint state with the given parameter data. - * The training session must be already created with the checkpoint state that contains the parameter - * being updated. The given parameter is copied over to the registered device for the training session. - * The parameter must exist in the checkpoint state to be able to update it successfully. - * - * \param[in] parameter_name Name of the parameter being updated. - * \param[in] parameter The parameter data that should replace the existing parameter data. - * - */ - void UpdateParameter(const std::string& parameter_name, const Value& parameter); - - /** \brief Gets the data associated with the model parameter from the checkpoint state for the given parameter name. - * - * This function retrieves the model parameter data from the checkpoint state for the given parameter name. - * The parameter is copied over to the provided OrtValue. The training session must be already created - * with the checkpoint state that contains the parameter being retrieved. - * The parameter must exist in the checkpoint state to be able to retrieve it successfully. - * - * \param[in] parameter_name Name of the parameter being retrieved. - * \return The parameter data that is retrieved from the checkpoint state. - * - */ - Value GetParameter(const std::string& parameter_name); - - /// @} -}; - -/** \brief Trainer class that provides training, evaluation and optimizer methods for training an ONNX models. - * - * The training session requires four training artifacts - * - The training onnx model - * - The evaluation onnx model (optional) - * - The optimizer onnx model - * - The checkpoint file - * - * These artifacts can be generated using the `onnxruntime-training` python [utility](https://github.com/microsoft/onnxruntime/blob/main/orttraining/orttraining/python/training/onnxblock/README.md). - * - */ -class TrainingSession : public detail::Base { - private: - size_t training_model_output_count_, eval_model_output_count_; - - public: - /// \name Constructing the Training Session - /// @{ - /** \brief Create a training session that can be used to begin or resume training. - * - * This constructor instantiates the training session based on the env and session options provided that can - * begin or resume training from a given checkpoint state for the given onnx models. - * The checkpoint state represents the parameters of the training session which will be moved - * to the device specified by the user through the session options (if necessary). - * - * \param[in] env Env to be used for the training session. - * \param[in] session_options SessionOptions that the user can customize for this training session. - * \param[in] checkpoint_state Training states that the training session uses as a starting point for training. - * \param[in] train_model_path Model to be used to perform training. - * \param[in] eval_model_path Model to be used to perform evaluation. - * \param[in] optimizer_model_path Model to be used to perform gradient descent. - * - */ - TrainingSession(const Env& env, const SessionOptions& session_options, CheckpointState& checkpoint_state, - const std::basic_string& train_model_path, - const std::optional>& eval_model_path = std::nullopt, - const std::optional>& optimizer_model_path = std::nullopt); - - /** \brief Create a training session that can be used to begin or resume training. - * This constructor allows the users to load the models from buffers instead of files. - * - * \param[in] env Env to be used for the training session. - * \param[in] session_options SessionOptions that the user can customize for this training session. - * \param[in] checkpoint_state Training states that the training session uses as a starting point for training. - * \param[in] train_model_data Buffer containing training model data. - * \param[in] eval_model_data Buffer containing evaluation model data. - * \param[in] optim_model_data Buffer containing optimizer model (used for performing weight/parameter update). - * - */ - TrainingSession(const Env& env, const SessionOptions& session_options, CheckpointState& checkpoint_state, - const std::vector& train_model_data, const std::vector& eval_model_data = {}, - const std::vector& optim_model_data = {}); - /// @} - - /// \name Implementing The Training Loop - /// @{ - /** \brief Computes the outputs of the training model and the gradients of the trainable parameters for the given inputs - * - * This function performs a training step that computes the outputs of the training model and the gradients - * of the trainable parameters for the given inputs. The train step is performed based on the training model - * that was provided to the training session. - * The Ort::TrainingSession::TrainStep is equivalent of running forward propagation and backward propagation in a single - * step. - * The gradients computed are stored inside the training session state so they can be later consumed - * by the Ort::TrainingSession::OptimizerStep function. - * The gradients can be lazily reset by invoking the Ort::TrainingSession::LazyResetGrad function. - * - * \param[in] input_values The user inputs to the training model. - * \return A std::vector of Ort::Value objects that represents the output of the forward pass of the training model. - * - * - */ - std::vector TrainStep(const std::vector& input_values); - - /** \brief Reset the gradients of all trainable parameters to zero lazily. - * - * This function sets the internal state of the training session such that the gradients of the trainable - * parameters in the OrtCheckpointState will be scheduled to be reset just before the new gradients are - * computed on the next invocation of the next Ort::TrainingSession::TrainStep. - * - */ - void LazyResetGrad(); - - /** \brief Computes the outputs for the eval model for the given inputs - * - * This function performs an eval step that computes the outputs of the eval model for the given inputs. - * The eval step is performed based on the eval model that was provided to the training session. - * - * \param[in] input_values The user inputs to the eval model. - * \return A std::vector of Ort::Value objects that represents the output of the eval pass. - * - */ - std::vector EvalStep(const std::vector& input_values); - - /** \brief Sets the learning rate for this training session. - * - * This function allows users to set the learning rate for the training session. The current - * learning rate is maintained by the training session and can be overwritten by invoking - * this function with the desired learning rate. This function should not be used when a valid - * learning rate scheduler is registered. It should be used either to set the learning rate - * derived from a custom learning rate scheduler or to set a constant learning rate to be used - * throughout the training session. - * \note Please note that this function does not set the initial learning rate that may be needed - * by the predefined learning rate schedulers. To set the initial learning rate for learning - * rate schedulers, please look at the function Ort::TrainingSession::RegisterLinearLRScheduler. - * - * \param[in] learning_rate Desired learning rate to be set. - * - */ - void SetLearningRate(float learning_rate); - - /** \brief Gets the current learning rate for this training session. - * - * This function allows users to get the learning rate for the training session. The current - * learning rate is maintained by the training session, and users can query it for the purpose - * of implementing their own learning rate schedulers. - * - * \return float representing the current learning rate. - * - */ - float GetLearningRate() const; - - /** \brief Registers a linear learning rate scheduler for the training session. - * - * Register a linear learning rate scheduler that decays the learning rate by linearly updated - * multiplicative factor from the initial learning rate set on the training session to 0. The decay - * is performed after the initial warm up phase where the learning rate is linearly incremented - * from 0 to the initial learning rate provided. - * - * \param[in] warmup_step_count Warmup steps for LR warmup. - * \param[in] total_step_count Total step count. - * \param[in] initial_lr The initial learning rate to be used by the training session. - * - */ - void RegisterLinearLRScheduler(int64_t warmup_step_count, int64_t total_step_count, - float initial_lr); - - /** \brief Update the learning rate based on the registered learing rate scheduler. - * - * Takes a scheduler step that updates the learning rate that is being used by the training session. - * This function should typically be called before invoking the optimizer step for each round, - * or as determined necessary to update the learning rate being used by the training session. - * \note Please note that a valid predefined learning rate scheduler must be first registered to invoke this - * function. - * - */ - void SchedulerStep(); - - /** \brief Performs the weight updates for the trainable parameters using the optimizer model. - * - * This function performs the weight update step that updates the trainable parameters such that they - * take a step in the direction of their gradients (gradient descent). The optimizer step is performed - * based on the optimizer model that was provided to the training session. - * The updated parameters are stored inside the training state so that they can be used by the next - * Ort::TrainingSession::TrainStep function call. - * - */ - void OptimizerStep(); - - /// @} - - /// \name Prepare For Inferencing - /// @{ - - /** \brief Export a model that can be used for inferencing. - * - * If the training session was provided with an eval model, the training session can generate - * an inference model if it knows the inference graph outputs. The input inference graph outputs - * are used to prune the eval model so that the inference model's outputs align with the provided outputs. - * The exported model is saved at the path provided and can be used for inferencing with Ort::Session. - * \note Note that the function re-loads the eval model from the path provided to Ort::TrainingSession - * and expects that this path still be valid. - * - * \param[in] inference_model_path Path where the inference model should be serialized to. - * \param[in] graph_output_names Names of the outputs that are needed in the inference model. - * - */ - void ExportModelForInferencing(const std::basic_string& inference_model_path, - const std::vector& graph_output_names); - - /// @} - - /// \name Model IO Information - /// @{ - /** \brief Retrieves the names of the user inputs for the training and eval models. - * - * This function returns the names of inputs of the training or eval model that can be associated - * with the Ort::Value(s) provided to the Ort::TrainingSession::TrainStep or Ort::TrainingSession::EvalStep - * function. - * - * \param[in] training Whether the training model input names are requested or eval model input names. - * \return Graph input names for either the training model or the eval model. - * - */ - std::vector InputNames(const bool training); - - /** \brief Retrieves the names of the user outputs for the training and eval models. - * - * This function returns the names of outputs of the training or eval model that can be associated - * with the Ort::Value(s) returned by the Ort::TrainingSession::TrainStep or Ort::TrainingSession::EvalStep - * function. - * - * \param[in] training Whether the training model output names are requested or eval model output names. - * \return Graph output names for either the training model or the eval model. - * - */ - std::vector OutputNames(const bool training); - - /// @} - - /// \name Accessing The Training Session State - /// @{ - - /** \brief Returns a contiguous buffer that holds a copy of all training state parameters - * - * \param[in] only_trainable Whether to only copy trainable parameters or to copy all parameters. - * \return Contiguous buffer to the model parameters. - * - */ - Value ToBuffer(const bool only_trainable); - - /** \brief Loads the training session model parameters from a contiguous buffer - * - * In case the training session was created with a nominal checkpoint, invoking this function is required - * to load the updated parameters onto the checkpoint to complete it. - * - * \param[in] buffer Contiguous buffer to load the parameters from. - */ - void FromBuffer(Value& buffer); - - /// @} -}; - -/// \name Training Utilities -/// @{ -/** \brief This function sets the seed for generating random numbers. - * - * Use this function to generate reproducible results. It should be noted that completely - * reproducible results are not guaranteed. - * - * \param[in] seed Manual seed to use for random number generation. - */ -void SetSeed(const int64_t seed); -/// @} - -/// @} - -} // namespace Ort - -#include "onnxruntime_training_cxx_inline.h" +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#pragma once +#include "onnxruntime_training_c_api.h" +#include +#include + +namespace Ort::detail { + +#define ORT_DECLARE_TRAINING_RELEASE(NAME) \ + void OrtRelease(Ort##NAME* ptr); + +// These release methods must be forward declared before including onnxruntime_cxx_api.h +// otherwise class Base won't be aware of them +ORT_DECLARE_TRAINING_RELEASE(CheckpointState); +ORT_DECLARE_TRAINING_RELEASE(TrainingSession); + +} // namespace Ort::detail + +#include "onnxruntime_cxx_api.h" + +namespace Ort { + +/// +/// This function returns the C training api struct with the pointers to the ort training C functions. +/// If using C++, please use the class instances instead of invoking the C functions directly. +/// +/// OrtTrainingApi struct with ort training C function pointers. +inline const OrtTrainingApi& GetTrainingApi() { return *GetApi().GetTrainingApi(ORT_API_VERSION); } + +namespace detail { + +#define ORT_DEFINE_TRAINING_RELEASE(NAME) \ + inline void OrtRelease(Ort##NAME* ptr) { GetTrainingApi().Release##NAME(ptr); } + +ORT_DEFINE_TRAINING_RELEASE(CheckpointState); +ORT_DEFINE_TRAINING_RELEASE(TrainingSession); + +#undef ORT_DECLARE_TRAINING_RELEASE +#undef ORT_DEFINE_TRAINING_RELEASE + +} // namespace detail + +using Property = std::variant; + +/** + * \defgroup TrainingCpp Ort Training C++ API + * @{ + */ + +/** \brief Holds the state of the training session. + * + * This class holds the entire training session state that includes model parameters, their gradients, + * optimizer parameters, and user properties. The Ort::TrainingSession leverages the Ort::CheckpointState + * by accessing and updating the contained training state. + * \note Note that the training session created with a checkpoint state uses this state to store the entire + * training state (including model parameters, its gradients, the optimizer states and the properties). + * The Ort::TrainingSession does not hold a copy of the Ort::CheckpointState and as a result, it is required + * that the checkpoint state outlive the lifetime of the training session. + * \note Note that the checkpoint state can be either the complete checkpoint state or the nominal checkpoint + * state depending on the version provided while loading the checkpoint. + * + */ +class CheckpointState : public detail::Base { + private: + CheckpointState(OrtCheckpointState* checkpoint_state) { p_ = checkpoint_state; } + + public: + // Construct the checkpoint state by loading the checkpoint by calling LoadCheckpoint + CheckpointState() = delete; + + /// \name Accessing The Training Session State + /// @{ + + /** \brief Load a checkpoint state from a file on disk into checkpoint_state. + * + * This function will parse a checkpoint file, pull relevant data and load the training + * state and return an instance of Ort::CheckpointState. This checkpoint state can then be used to create the + * training session by instantiating Ort::TrainingSession. By doing so, the training session will resume + * training from the given checkpoint state. + * + * \param[in] path_to_checkpoint Path to the checkpoint file + * \return Ort::CheckpointState object which holds the state of the training session parameters. + * + */ + static CheckpointState LoadCheckpoint(const std::basic_string& path_to_checkpoint); + + /** \brief Load a checkpoint state from a buffer. + * + * This function will parse a checkpoint buffer, pull relevant data and load the training + * state and return an instance of Ort::CheckpointState. This checkpoint state can then be used to create the + * training session by instantiating Ort::TrainingSession. By doing so, the training session will resume + * training from the given checkpoint state. + * + * \param[in] buffer Buffer containing the checkpoint data. + * \return Ort::CheckpointState object which holds the state of the training session parameters. + * + */ + static CheckpointState LoadCheckpointFromBuffer(const std::vector& buffer); + + /** \brief Save the given state to a checkpoint file on disk. + * + * This function serializes the provided checkpoint state to a file on disk. + * This checkpoint can later be loaded by invoking Ort::CheckpointState::LoadCheckpoint to resume + * training from this snapshot of the state. + * + * \param[in] checkpoint_state The checkpoint state to save. + * \param[in] path_to_checkpoint Path to the checkpoint file. + * \param[in] include_optimizer_state Flag to indicate whether to save the optimizer state or not. + * + */ + static void SaveCheckpoint(const CheckpointState& checkpoint_state, + const std::basic_string& path_to_checkpoint, + const bool include_optimizer_state = false); + + /** \brief Adds or updates the given property to/in the checkpoint state. + * + * Runtime properties such as epoch, training step, best score, and others can be added to the checkpoint + * state by the user by calling this function with the corresponding property name and value. + * The given property name must be unique to be able to successfully add the property. + * + * \param[in] property_name Name of the property being added or updated. + * \param[in] property_value Property value associated with the given name. + * + */ + void AddProperty(const std::string& property_name, const Property& property_value); + + /** \brief Gets the property value associated with the given name from the checkpoint state. + * + * Gets the property value from an existing entry in the checkpoint state. The property must + * exist in the checkpoint state to be able to retrieve it successfully. + * + * \param[in] property_name Name of the property being retrieved. + * \return Property value associated with the given property name. + * + */ + Property GetProperty(const std::string& property_name); + + /** \brief Updates the data associated with the model parameter in the checkpoint state for the given parameter name. + * + * This function updates a model parameter in the checkpoint state with the given parameter data. + * The training session must be already created with the checkpoint state that contains the parameter + * being updated. The given parameter is copied over to the registered device for the training session. + * The parameter must exist in the checkpoint state to be able to update it successfully. + * + * \param[in] parameter_name Name of the parameter being updated. + * \param[in] parameter The parameter data that should replace the existing parameter data. + * + */ + void UpdateParameter(const std::string& parameter_name, const Value& parameter); + + /** \brief Gets the data associated with the model parameter from the checkpoint state for the given parameter name. + * + * This function retrieves the model parameter data from the checkpoint state for the given parameter name. + * The parameter is copied over to the provided OrtValue. The training session must be already created + * with the checkpoint state that contains the parameter being retrieved. + * The parameter must exist in the checkpoint state to be able to retrieve it successfully. + * + * \param[in] parameter_name Name of the parameter being retrieved. + * \return The parameter data that is retrieved from the checkpoint state. + * + */ + Value GetParameter(const std::string& parameter_name); + + /// @} +}; + +/** \brief Trainer class that provides training, evaluation and optimizer methods for training an ONNX models. + * + * The training session requires four training artifacts + * - The training onnx model + * - The evaluation onnx model (optional) + * - The optimizer onnx model + * - The checkpoint file + * + * These artifacts can be generated using the `onnxruntime-training` python [utility](https://github.com/microsoft/onnxruntime/blob/main/orttraining/orttraining/python/training/onnxblock/README.md). + * + */ +class TrainingSession : public detail::Base { + private: + size_t training_model_output_count_, eval_model_output_count_; + + public: + /// \name Constructing the Training Session + /// @{ + /** \brief Create a training session that can be used to begin or resume training. + * + * This constructor instantiates the training session based on the env and session options provided that can + * begin or resume training from a given checkpoint state for the given onnx models. + * The checkpoint state represents the parameters of the training session which will be moved + * to the device specified by the user through the session options (if necessary). + * + * \param[in] env Env to be used for the training session. + * \param[in] session_options SessionOptions that the user can customize for this training session. + * \param[in] checkpoint_state Training states that the training session uses as a starting point for training. + * \param[in] train_model_path Model to be used to perform training. + * \param[in] eval_model_path Model to be used to perform evaluation. + * \param[in] optimizer_model_path Model to be used to perform gradient descent. + * + */ + TrainingSession(const Env& env, const SessionOptions& session_options, CheckpointState& checkpoint_state, + const std::basic_string& train_model_path, + const std::optional>& eval_model_path = std::nullopt, + const std::optional>& optimizer_model_path = std::nullopt); + + /** \brief Create a training session that can be used to begin or resume training. + * This constructor allows the users to load the models from buffers instead of files. + * + * \param[in] env Env to be used for the training session. + * \param[in] session_options SessionOptions that the user can customize for this training session. + * \param[in] checkpoint_state Training states that the training session uses as a starting point for training. + * \param[in] train_model_data Buffer containing training model data. + * \param[in] eval_model_data Buffer containing evaluation model data. + * \param[in] optim_model_data Buffer containing optimizer model (used for performing weight/parameter update). + * + */ + TrainingSession(const Env& env, const SessionOptions& session_options, CheckpointState& checkpoint_state, + const std::vector& train_model_data, const std::vector& eval_model_data = {}, + const std::vector& optim_model_data = {}); + /// @} + + /// \name Implementing The Training Loop + /// @{ + /** \brief Computes the outputs of the training model and the gradients of the trainable parameters for the given inputs + * + * This function performs a training step that computes the outputs of the training model and the gradients + * of the trainable parameters for the given inputs. The train step is performed based on the training model + * that was provided to the training session. + * The Ort::TrainingSession::TrainStep is equivalent of running forward propagation and backward propagation in a single + * step. + * The gradients computed are stored inside the training session state so they can be later consumed + * by the Ort::TrainingSession::OptimizerStep function. + * The gradients can be lazily reset by invoking the Ort::TrainingSession::LazyResetGrad function. + * + * \param[in] input_values The user inputs to the training model. + * \return A std::vector of Ort::Value objects that represents the output of the forward pass of the training model. + * + * + */ + std::vector TrainStep(const std::vector& input_values); + + /** \brief Reset the gradients of all trainable parameters to zero lazily. + * + * This function sets the internal state of the training session such that the gradients of the trainable + * parameters in the OrtCheckpointState will be scheduled to be reset just before the new gradients are + * computed on the next invocation of the next Ort::TrainingSession::TrainStep. + * + */ + void LazyResetGrad(); + + /** \brief Computes the outputs for the eval model for the given inputs + * + * This function performs an eval step that computes the outputs of the eval model for the given inputs. + * The eval step is performed based on the eval model that was provided to the training session. + * + * \param[in] input_values The user inputs to the eval model. + * \return A std::vector of Ort::Value objects that represents the output of the eval pass. + * + */ + std::vector EvalStep(const std::vector& input_values); + + /** \brief Sets the learning rate for this training session. + * + * This function allows users to set the learning rate for the training session. The current + * learning rate is maintained by the training session and can be overwritten by invoking + * this function with the desired learning rate. This function should not be used when a valid + * learning rate scheduler is registered. It should be used either to set the learning rate + * derived from a custom learning rate scheduler or to set a constant learning rate to be used + * throughout the training session. + * \note Please note that this function does not set the initial learning rate that may be needed + * by the predefined learning rate schedulers. To set the initial learning rate for learning + * rate schedulers, please look at the function Ort::TrainingSession::RegisterLinearLRScheduler. + * + * \param[in] learning_rate Desired learning rate to be set. + * + */ + void SetLearningRate(float learning_rate); + + /** \brief Gets the current learning rate for this training session. + * + * This function allows users to get the learning rate for the training session. The current + * learning rate is maintained by the training session, and users can query it for the purpose + * of implementing their own learning rate schedulers. + * + * \return float representing the current learning rate. + * + */ + float GetLearningRate() const; + + /** \brief Registers a linear learning rate scheduler for the training session. + * + * Register a linear learning rate scheduler that decays the learning rate by linearly updated + * multiplicative factor from the initial learning rate set on the training session to 0. The decay + * is performed after the initial warm up phase where the learning rate is linearly incremented + * from 0 to the initial learning rate provided. + * + * \param[in] warmup_step_count Warmup steps for LR warmup. + * \param[in] total_step_count Total step count. + * \param[in] initial_lr The initial learning rate to be used by the training session. + * + */ + void RegisterLinearLRScheduler(int64_t warmup_step_count, int64_t total_step_count, + float initial_lr); + + /** \brief Update the learning rate based on the registered learing rate scheduler. + * + * Takes a scheduler step that updates the learning rate that is being used by the training session. + * This function should typically be called before invoking the optimizer step for each round, + * or as determined necessary to update the learning rate being used by the training session. + * \note Please note that a valid predefined learning rate scheduler must be first registered to invoke this + * function. + * + */ + void SchedulerStep(); + + /** \brief Performs the weight updates for the trainable parameters using the optimizer model. + * + * This function performs the weight update step that updates the trainable parameters such that they + * take a step in the direction of their gradients (gradient descent). The optimizer step is performed + * based on the optimizer model that was provided to the training session. + * The updated parameters are stored inside the training state so that they can be used by the next + * Ort::TrainingSession::TrainStep function call. + * + */ + void OptimizerStep(); + + /// @} + + /// \name Prepare For Inferencing + /// @{ + + /** \brief Export a model that can be used for inferencing. + * + * If the training session was provided with an eval model, the training session can generate + * an inference model if it knows the inference graph outputs. The input inference graph outputs + * are used to prune the eval model so that the inference model's outputs align with the provided outputs. + * The exported model is saved at the path provided and can be used for inferencing with Ort::Session. + * \note Note that the function re-loads the eval model from the path provided to Ort::TrainingSession + * and expects that this path still be valid. + * + * \param[in] inference_model_path Path where the inference model should be serialized to. + * \param[in] graph_output_names Names of the outputs that are needed in the inference model. + * + */ + void ExportModelForInferencing(const std::basic_string& inference_model_path, + const std::vector& graph_output_names); + + /// @} + + /// \name Model IO Information + /// @{ + /** \brief Retrieves the names of the user inputs for the training and eval models. + * + * This function returns the names of inputs of the training or eval model that can be associated + * with the Ort::Value(s) provided to the Ort::TrainingSession::TrainStep or Ort::TrainingSession::EvalStep + * function. + * + * \param[in] training Whether the training model input names are requested or eval model input names. + * \return Graph input names for either the training model or the eval model. + * + */ + std::vector InputNames(const bool training); + + /** \brief Retrieves the names of the user outputs for the training and eval models. + * + * This function returns the names of outputs of the training or eval model that can be associated + * with the Ort::Value(s) returned by the Ort::TrainingSession::TrainStep or Ort::TrainingSession::EvalStep + * function. + * + * \param[in] training Whether the training model output names are requested or eval model output names. + * \return Graph output names for either the training model or the eval model. + * + */ + std::vector OutputNames(const bool training); + + /// @} + + /// \name Accessing The Training Session State + /// @{ + + /** \brief Returns a contiguous buffer that holds a copy of all training state parameters + * + * \param[in] only_trainable Whether to only copy trainable parameters or to copy all parameters. + * \return Contiguous buffer to the model parameters. + * + */ + Value ToBuffer(const bool only_trainable); + + /** \brief Loads the training session model parameters from a contiguous buffer + * + * In case the training session was created with a nominal checkpoint, invoking this function is required + * to load the updated parameters onto the checkpoint to complete it. + * + * \param[in] buffer Contiguous buffer to load the parameters from. + */ + void FromBuffer(Value& buffer); + + /// @} +}; + +/// \name Training Utilities +/// @{ +/** \brief This function sets the seed for generating random numbers. + * + * Use this function to generate reproducible results. It should be noted that completely + * reproducible results are not guaranteed. + * + * \param[in] seed Manual seed to use for random number generation. + */ +void SetSeed(const int64_t seed); +/// @} + +/// @} + +} // namespace Ort + +#include "onnxruntime_training_cxx_inline.h" diff --git a/3rdParty/ONNX/onnxruntime_training_cxx_inline.h b/3rdParty/ONNX/onnxruntime_training_cxx_inline.h index 397cba0b0f..f9961317da 100644 --- a/3rdParty/ONNX/onnxruntime_training_cxx_inline.h +++ b/3rdParty/ONNX/onnxruntime_training_cxx_inline.h @@ -1,295 +1,295 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once -#include "onnxruntime_training_c_api.h" -#include "onnxruntime_cxx_api.h" - -namespace Ort { - -inline TrainingSession::TrainingSession(const Env& env, const SessionOptions& session_options, - CheckpointState& checkpoint_state, - const std::basic_string& train_model_path, - const std::optional>& eval_model_path, - const std::optional>& optimizer_model_path) { - ThrowOnError(GetTrainingApi().CreateTrainingSession( - env, session_options, checkpoint_state, - train_model_path.c_str(), - eval_model_path.has_value() ? eval_model_path.value().c_str() : nullptr, - optimizer_model_path.has_value() ? optimizer_model_path.value().c_str() : nullptr, - &p_)); - - ThrowOnError(GetTrainingApi().TrainingSessionGetTrainingModelOutputCount(p_, &training_model_output_count_)); - - ThrowOnError(GetTrainingApi().TrainingSessionGetEvalModelOutputCount(p_, &eval_model_output_count_)); -} - -inline TrainingSession::TrainingSession(const Env& env, const SessionOptions& session_options, - CheckpointState& checkpoint_state, - const std::vector& train_model_data, - const std::vector& eval_model_data, - const std::vector& optim_model_data) { - ThrowOnError(GetTrainingApi().CreateTrainingSessionFromBuffer( - env, session_options, checkpoint_state, - train_model_data.data(), train_model_data.size(), - eval_model_data.data(), eval_model_data.size(), - optim_model_data.data(), optim_model_data.size(), - &p_)); - - ThrowOnError(GetTrainingApi().TrainingSessionGetTrainingModelOutputCount(p_, &training_model_output_count_)); - - ThrowOnError(GetTrainingApi().TrainingSessionGetEvalModelOutputCount(p_, &eval_model_output_count_)); -} - -inline std::vector TrainingSession::TrainStep(const std::vector& input_values) { - std::vector output_values; - output_values.reserve(training_model_output_count_); - for (size_t i = 0; i < training_model_output_count_; i++) output_values.emplace_back(nullptr); - auto ort_input_values = reinterpret_cast(input_values.data()); - auto ort_output_values = reinterpret_cast(output_values.data()); - RunOptions run_options; - ThrowOnError(GetTrainingApi().TrainStep( - p_, run_options, input_values.size(), ort_input_values, - training_model_output_count_, ort_output_values)); - - return output_values; -} - -inline void TrainingSession::LazyResetGrad() { - ThrowOnError(GetTrainingApi().LazyResetGrad(p_)); -} - -inline std::vector TrainingSession::EvalStep(const std::vector& input_values) { - std::vector output_values; - output_values.reserve(eval_model_output_count_); - for (size_t i = 0; i < eval_model_output_count_; i++) output_values.emplace_back(nullptr); - auto ort_input_values = reinterpret_cast(input_values.data()); - auto ort_output_values = reinterpret_cast(output_values.data()); - RunOptions run_options; - ThrowOnError(GetTrainingApi().EvalStep( - p_, run_options, input_values.size(), ort_input_values, - eval_model_output_count_, ort_output_values)); - - return output_values; -} - -inline void TrainingSession::SetLearningRate(float learning_rate) { - ThrowOnError(GetTrainingApi().SetLearningRate(p_, learning_rate)); -} - -inline float TrainingSession::GetLearningRate() const { - float learning_rate = 0; - ThrowOnError(GetTrainingApi().GetLearningRate(p_, &learning_rate)); - return learning_rate; -} - -inline void TrainingSession::RegisterLinearLRScheduler(int64_t warmup_step_count, int64_t total_step_count, - float initial_lr) { - ThrowOnError(GetTrainingApi().RegisterLinearLRScheduler(p_, warmup_step_count, total_step_count, - initial_lr)); -} - -inline void TrainingSession::SchedulerStep() { - ThrowOnError(GetTrainingApi().SchedulerStep(p_)); -} - -inline void TrainingSession::OptimizerStep() { - RunOptions run_options; - ThrowOnError(GetTrainingApi().OptimizerStep(p_, run_options)); -} - -inline std::vector TrainingSession::InputNames(const bool training) { - auto& input_count_function = training ? GetTrainingApi().TrainingSessionGetTrainingModelInputCount - : GetTrainingApi().TrainingSessionGetEvalModelInputCount; - auto& input_name_function = training ? GetTrainingApi().TrainingSessionGetTrainingModelInputName - : GetTrainingApi().TrainingSessionGetEvalModelInputName; - - size_t input_count = 0; - ThrowOnError(input_count_function(p_, &input_count)); - std::vector input_names(input_count); - AllocatorWithDefaultOptions allocator; - for (size_t index = 0; index < input_count; ++index) { - char* input_name; - ThrowOnError(input_name_function(p_, index, allocator, &input_name)); - input_names[index] = std::string(input_name); - allocator.Free(input_name); - } - - return input_names; -} - -inline std::vector TrainingSession::OutputNames(const bool training) { - auto& output_count_function = training ? GetTrainingApi().TrainingSessionGetTrainingModelOutputCount - : GetTrainingApi().TrainingSessionGetEvalModelOutputCount; - auto& output_name_function = training ? GetTrainingApi().TrainingSessionGetTrainingModelOutputName - : GetTrainingApi().TrainingSessionGetEvalModelOutputName; - - size_t output_count = 0; - ThrowOnError(output_count_function(p_, &output_count)); - std::vector output_names(output_count); - AllocatorWithDefaultOptions allocator; - for (size_t index = 0; index < output_count; ++index) { - char* output_name; - ThrowOnError(output_name_function(p_, index, allocator, &output_name)); - output_names[index] = std::string(output_name); - allocator.Free(output_name); - } - - return output_names; -} - -inline Value TrainingSession::ToBuffer(const bool only_trainable) { - size_t buffer_size = 0U; - ThrowOnError(GetTrainingApi().GetParametersSize(p_, &buffer_size, only_trainable)); - - std::array buffer_shape{static_cast(buffer_size)}; - - AllocatorWithDefaultOptions allocator; - Value buffer = Value::CreateTensor(allocator, buffer_shape.data(), 1U, - ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT); - - ThrowOnError(GetTrainingApi().CopyParametersToBuffer(p_, buffer, only_trainable)); - - return buffer; -} - -inline void TrainingSession::FromBuffer(Value& buffer) { - if (!buffer.IsTensor()) { - ThrowStatus(Status("Incorrect buffer received. Expected a tensor buffer.", OrtErrorCode::ORT_INVALID_ARGUMENT)); - } - - auto tensor_info = buffer.GetTensorTypeAndShapeInfo(); - auto buffer_shape = tensor_info.GetShape(); - - if (buffer_shape.size() != 1U) { - ThrowStatus(Status("Incorrect buffer received. Expected a contiguous tensor buffer.", - OrtErrorCode::ORT_INVALID_ARGUMENT)); - } - - auto buffer_size = buffer_shape.front(); - - size_t session_buffer_size = 0U; - ThrowOnError(GetTrainingApi().GetParametersSize(p_, &session_buffer_size, false)); - - if (buffer_size == static_cast(session_buffer_size)) { - ThrowOnError(GetTrainingApi().CopyBufferToParameters(p_, buffer, false)); - return; - } - - size_t session_buffer_size_trainable_only = 0U; - ThrowOnError(GetTrainingApi().GetParametersSize(p_, &session_buffer_size_trainable_only, true)); - - if (buffer_size == static_cast(session_buffer_size_trainable_only)) { - ThrowOnError(GetTrainingApi().CopyBufferToParameters(p_, buffer, true)); - return; - } else { - ThrowStatus(Status("Incorrect buffer size received.", OrtErrorCode::ORT_INVALID_ARGUMENT)); - } -} - -inline CheckpointState CheckpointState::LoadCheckpoint(const std::basic_string& path_to_checkpoint) { - OrtCheckpointState* checkpoint_state; - ThrowOnError(GetTrainingApi().LoadCheckpoint(path_to_checkpoint.c_str(), &checkpoint_state)); - return CheckpointState(checkpoint_state); -} - -inline CheckpointState CheckpointState::LoadCheckpointFromBuffer(const std::vector& buffer) { - OrtCheckpointState* checkpoint_state; - ThrowOnError(GetTrainingApi().LoadCheckpointFromBuffer(buffer.data(), buffer.size(), &checkpoint_state)); - return CheckpointState(checkpoint_state); -} - -inline void CheckpointState::SaveCheckpoint(const CheckpointState& checkpoint_states, - const std::basic_string& path_to_checkpoint, - const bool include_optimizer_state) { - ThrowOnError(GetTrainingApi().SaveCheckpoint(checkpoint_states, path_to_checkpoint.c_str(), - include_optimizer_state)); -} - -inline void TrainingSession::ExportModelForInferencing(const std::basic_string& inference_model_path, - const std::vector& graph_output_names) { - std::vector output_names; - output_names.reserve(graph_output_names.size()); - for (const auto& output_name : graph_output_names) { - output_names.push_back(output_name.c_str()); - } - ThrowOnError(GetTrainingApi().ExportModelForInferencing( - p_, inference_model_path.c_str(), graph_output_names.size(), output_names.data())); -} - -inline void SetSeed(const int64_t seed) { - ThrowOnError(GetTrainingApi().SetSeed(seed)); -} - -inline void CheckpointState::AddProperty(const std::string& property_name, const Property& property_value) { - if (std::holds_alternative(property_value)) { - int64_t value = std::get(property_value); - void* value_p = &value; - ThrowOnError(GetTrainingApi().AddProperty(p_, property_name.c_str(), OrtPropertyType::OrtIntProperty, value_p)); - } else if (std::holds_alternative(property_value)) { - float value = std::get(property_value); - void* value_p = &value; - ThrowOnError(GetTrainingApi().AddProperty(p_, property_name.c_str(), OrtPropertyType::OrtFloatProperty, value_p)); - } else if (std::holds_alternative(property_value)) { - std::string value = std::get(property_value); - auto buffer = std::make_unique(value.length() + 1); - memcpy(buffer.get(), value.c_str(), value.length()); - // AddProperty takes a char* and calls PropertyBag::AddProperty which takes a std::string. The data will be - // copied at that point so buffer can free the local allocation once the call is made. - ThrowOnError(GetTrainingApi().AddProperty(p_, property_name.c_str(), OrtPropertyType::OrtStringProperty, - buffer.get())); - } else { - ThrowStatus(Status("Unknown property type received.", OrtErrorCode::ORT_INVALID_ARGUMENT)); - } -} - -inline Property CheckpointState::GetProperty(const std::string& property_name) { - void* property_value = nullptr; - OrtPropertyType property_type; - - AllocatorWithDefaultOptions allocator; - ThrowOnError(GetTrainingApi().GetProperty(p_, property_name.c_str(), allocator, &property_type, &property_value)); - - Property property; - - switch (property_type) { - case OrtPropertyType::OrtIntProperty: { - auto value_p = reinterpret_cast(property_value); - property = *value_p; - allocator.Free(property_value); - break; - } - case OrtPropertyType::OrtFloatProperty: { - auto value_p = reinterpret_cast(property_value); - property = *value_p; - allocator.Free(property_value); - break; - } - case OrtPropertyType::OrtStringProperty: { - auto value_p = reinterpret_cast(property_value); - property = std::string(value_p); - allocator.Free(property_value); - break; - } - default: { - ThrowStatus(Status("Unknown property type received.", OrtErrorCode::ORT_INVALID_ARGUMENT)); - break; - } - } - - return property; -} - -inline void CheckpointState::UpdateParameter(const std::string& parameter_name, const Value& parameter) { - ThrowOnError(GetTrainingApi().UpdateParameter(p_, parameter_name.c_str(), parameter)); -} - -inline Value CheckpointState::GetParameter(const std::string& parameter_name) { - AllocatorWithDefaultOptions allocator; - OrtValue* parameter; - ThrowOnError(GetTrainingApi().GetParameter(p_, parameter_name.c_str(), allocator, ¶meter)); - - return Value{parameter}; -} - -} // namespace Ort +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#pragma once +#include "onnxruntime_training_c_api.h" +#include "onnxruntime_cxx_api.h" + +namespace Ort { + +inline TrainingSession::TrainingSession(const Env& env, const SessionOptions& session_options, + CheckpointState& checkpoint_state, + const std::basic_string& train_model_path, + const std::optional>& eval_model_path, + const std::optional>& optimizer_model_path) { + ThrowOnError(GetTrainingApi().CreateTrainingSession( + env, session_options, checkpoint_state, + train_model_path.c_str(), + eval_model_path.has_value() ? eval_model_path.value().c_str() : nullptr, + optimizer_model_path.has_value() ? optimizer_model_path.value().c_str() : nullptr, + &p_)); + + ThrowOnError(GetTrainingApi().TrainingSessionGetTrainingModelOutputCount(p_, &training_model_output_count_)); + + ThrowOnError(GetTrainingApi().TrainingSessionGetEvalModelOutputCount(p_, &eval_model_output_count_)); +} + +inline TrainingSession::TrainingSession(const Env& env, const SessionOptions& session_options, + CheckpointState& checkpoint_state, + const std::vector& train_model_data, + const std::vector& eval_model_data, + const std::vector& optim_model_data) { + ThrowOnError(GetTrainingApi().CreateTrainingSessionFromBuffer( + env, session_options, checkpoint_state, + train_model_data.data(), train_model_data.size(), + eval_model_data.data(), eval_model_data.size(), + optim_model_data.data(), optim_model_data.size(), + &p_)); + + ThrowOnError(GetTrainingApi().TrainingSessionGetTrainingModelOutputCount(p_, &training_model_output_count_)); + + ThrowOnError(GetTrainingApi().TrainingSessionGetEvalModelOutputCount(p_, &eval_model_output_count_)); +} + +inline std::vector TrainingSession::TrainStep(const std::vector& input_values) { + std::vector output_values; + output_values.reserve(training_model_output_count_); + for (size_t i = 0; i < training_model_output_count_; i++) output_values.emplace_back(nullptr); + auto ort_input_values = reinterpret_cast(input_values.data()); + auto ort_output_values = reinterpret_cast(output_values.data()); + RunOptions run_options; + ThrowOnError(GetTrainingApi().TrainStep( + p_, run_options, input_values.size(), ort_input_values, + training_model_output_count_, ort_output_values)); + + return output_values; +} + +inline void TrainingSession::LazyResetGrad() { + ThrowOnError(GetTrainingApi().LazyResetGrad(p_)); +} + +inline std::vector TrainingSession::EvalStep(const std::vector& input_values) { + std::vector output_values; + output_values.reserve(eval_model_output_count_); + for (size_t i = 0; i < eval_model_output_count_; i++) output_values.emplace_back(nullptr); + auto ort_input_values = reinterpret_cast(input_values.data()); + auto ort_output_values = reinterpret_cast(output_values.data()); + RunOptions run_options; + ThrowOnError(GetTrainingApi().EvalStep( + p_, run_options, input_values.size(), ort_input_values, + eval_model_output_count_, ort_output_values)); + + return output_values; +} + +inline void TrainingSession::SetLearningRate(float learning_rate) { + ThrowOnError(GetTrainingApi().SetLearningRate(p_, learning_rate)); +} + +inline float TrainingSession::GetLearningRate() const { + float learning_rate = 0; + ThrowOnError(GetTrainingApi().GetLearningRate(p_, &learning_rate)); + return learning_rate; +} + +inline void TrainingSession::RegisterLinearLRScheduler(int64_t warmup_step_count, int64_t total_step_count, + float initial_lr) { + ThrowOnError(GetTrainingApi().RegisterLinearLRScheduler(p_, warmup_step_count, total_step_count, + initial_lr)); +} + +inline void TrainingSession::SchedulerStep() { + ThrowOnError(GetTrainingApi().SchedulerStep(p_)); +} + +inline void TrainingSession::OptimizerStep() { + RunOptions run_options; + ThrowOnError(GetTrainingApi().OptimizerStep(p_, run_options)); +} + +inline std::vector TrainingSession::InputNames(const bool training) { + auto& input_count_function = training ? GetTrainingApi().TrainingSessionGetTrainingModelInputCount + : GetTrainingApi().TrainingSessionGetEvalModelInputCount; + auto& input_name_function = training ? GetTrainingApi().TrainingSessionGetTrainingModelInputName + : GetTrainingApi().TrainingSessionGetEvalModelInputName; + + size_t input_count = 0; + ThrowOnError(input_count_function(p_, &input_count)); + std::vector input_names(input_count); + AllocatorWithDefaultOptions allocator; + for (size_t index = 0; index < input_count; ++index) { + char* input_name; + ThrowOnError(input_name_function(p_, index, allocator, &input_name)); + input_names[index] = std::string(input_name); + allocator.Free(input_name); + } + + return input_names; +} + +inline std::vector TrainingSession::OutputNames(const bool training) { + auto& output_count_function = training ? GetTrainingApi().TrainingSessionGetTrainingModelOutputCount + : GetTrainingApi().TrainingSessionGetEvalModelOutputCount; + auto& output_name_function = training ? GetTrainingApi().TrainingSessionGetTrainingModelOutputName + : GetTrainingApi().TrainingSessionGetEvalModelOutputName; + + size_t output_count = 0; + ThrowOnError(output_count_function(p_, &output_count)); + std::vector output_names(output_count); + AllocatorWithDefaultOptions allocator; + for (size_t index = 0; index < output_count; ++index) { + char* output_name; + ThrowOnError(output_name_function(p_, index, allocator, &output_name)); + output_names[index] = std::string(output_name); + allocator.Free(output_name); + } + + return output_names; +} + +inline Value TrainingSession::ToBuffer(const bool only_trainable) { + size_t buffer_size = 0U; + ThrowOnError(GetTrainingApi().GetParametersSize(p_, &buffer_size, only_trainable)); + + std::array buffer_shape{static_cast(buffer_size)}; + + AllocatorWithDefaultOptions allocator; + Value buffer = Value::CreateTensor(allocator, buffer_shape.data(), 1U, + ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT); + + ThrowOnError(GetTrainingApi().CopyParametersToBuffer(p_, buffer, only_trainable)); + + return buffer; +} + +inline void TrainingSession::FromBuffer(Value& buffer) { + if (!buffer.IsTensor()) { + ThrowStatus(Status("Incorrect buffer received. Expected a tensor buffer.", OrtErrorCode::ORT_INVALID_ARGUMENT)); + } + + auto tensor_info = buffer.GetTensorTypeAndShapeInfo(); + auto buffer_shape = tensor_info.GetShape(); + + if (buffer_shape.size() != 1U) { + ThrowStatus(Status("Incorrect buffer received. Expected a contiguous tensor buffer.", + OrtErrorCode::ORT_INVALID_ARGUMENT)); + } + + auto buffer_size = buffer_shape.front(); + + size_t session_buffer_size = 0U; + ThrowOnError(GetTrainingApi().GetParametersSize(p_, &session_buffer_size, false)); + + if (buffer_size == static_cast(session_buffer_size)) { + ThrowOnError(GetTrainingApi().CopyBufferToParameters(p_, buffer, false)); + return; + } + + size_t session_buffer_size_trainable_only = 0U; + ThrowOnError(GetTrainingApi().GetParametersSize(p_, &session_buffer_size_trainable_only, true)); + + if (buffer_size == static_cast(session_buffer_size_trainable_only)) { + ThrowOnError(GetTrainingApi().CopyBufferToParameters(p_, buffer, true)); + return; + } else { + ThrowStatus(Status("Incorrect buffer size received.", OrtErrorCode::ORT_INVALID_ARGUMENT)); + } +} + +inline CheckpointState CheckpointState::LoadCheckpoint(const std::basic_string& path_to_checkpoint) { + OrtCheckpointState* checkpoint_state; + ThrowOnError(GetTrainingApi().LoadCheckpoint(path_to_checkpoint.c_str(), &checkpoint_state)); + return CheckpointState(checkpoint_state); +} + +inline CheckpointState CheckpointState::LoadCheckpointFromBuffer(const std::vector& buffer) { + OrtCheckpointState* checkpoint_state; + ThrowOnError(GetTrainingApi().LoadCheckpointFromBuffer(buffer.data(), buffer.size(), &checkpoint_state)); + return CheckpointState(checkpoint_state); +} + +inline void CheckpointState::SaveCheckpoint(const CheckpointState& checkpoint_states, + const std::basic_string& path_to_checkpoint, + const bool include_optimizer_state) { + ThrowOnError(GetTrainingApi().SaveCheckpoint(checkpoint_states, path_to_checkpoint.c_str(), + include_optimizer_state)); +} + +inline void TrainingSession::ExportModelForInferencing(const std::basic_string& inference_model_path, + const std::vector& graph_output_names) { + std::vector output_names; + output_names.reserve(graph_output_names.size()); + for (const auto& output_name : graph_output_names) { + output_names.push_back(output_name.c_str()); + } + ThrowOnError(GetTrainingApi().ExportModelForInferencing( + p_, inference_model_path.c_str(), graph_output_names.size(), output_names.data())); +} + +inline void SetSeed(const int64_t seed) { + ThrowOnError(GetTrainingApi().SetSeed(seed)); +} + +inline void CheckpointState::AddProperty(const std::string& property_name, const Property& property_value) { + if (std::holds_alternative(property_value)) { + int64_t value = std::get(property_value); + void* value_p = &value; + ThrowOnError(GetTrainingApi().AddProperty(p_, property_name.c_str(), OrtPropertyType::OrtIntProperty, value_p)); + } else if (std::holds_alternative(property_value)) { + float value = std::get(property_value); + void* value_p = &value; + ThrowOnError(GetTrainingApi().AddProperty(p_, property_name.c_str(), OrtPropertyType::OrtFloatProperty, value_p)); + } else if (std::holds_alternative(property_value)) { + std::string value = std::get(property_value); + auto buffer = std::make_unique(value.length() + 1); + memcpy(buffer.get(), value.c_str(), value.length()); + // AddProperty takes a char* and calls PropertyBag::AddProperty which takes a std::string. The data will be + // copied at that point so buffer can free the local allocation once the call is made. + ThrowOnError(GetTrainingApi().AddProperty(p_, property_name.c_str(), OrtPropertyType::OrtStringProperty, + buffer.get())); + } else { + ThrowStatus(Status("Unknown property type received.", OrtErrorCode::ORT_INVALID_ARGUMENT)); + } +} + +inline Property CheckpointState::GetProperty(const std::string& property_name) { + void* property_value = nullptr; + OrtPropertyType property_type; + + AllocatorWithDefaultOptions allocator; + ThrowOnError(GetTrainingApi().GetProperty(p_, property_name.c_str(), allocator, &property_type, &property_value)); + + Property property; + + switch (property_type) { + case OrtPropertyType::OrtIntProperty: { + auto value_p = reinterpret_cast(property_value); + property = *value_p; + allocator.Free(property_value); + break; + } + case OrtPropertyType::OrtFloatProperty: { + auto value_p = reinterpret_cast(property_value); + property = *value_p; + allocator.Free(property_value); + break; + } + case OrtPropertyType::OrtStringProperty: { + auto value_p = reinterpret_cast(property_value); + property = std::string(value_p); + allocator.Free(property_value); + break; + } + default: { + ThrowStatus(Status("Unknown property type received.", OrtErrorCode::ORT_INVALID_ARGUMENT)); + break; + } + } + + return property; +} + +inline void CheckpointState::UpdateParameter(const std::string& parameter_name, const Value& parameter) { + ThrowOnError(GetTrainingApi().UpdateParameter(p_, parameter_name.c_str(), parameter)); +} + +inline Value CheckpointState::GetParameter(const std::string& parameter_name) { + AllocatorWithDefaultOptions allocator; + OrtValue* parameter; + ThrowOnError(GetTrainingApi().GetParameter(p_, parameter_name.c_str(), allocator, ¶meter)); + + return Value{parameter}; +} + +} // namespace Ort diff --git a/3rdParty/ONNX/provider_options.h b/3rdParty/ONNX/provider_options.h index aab13e808e..0e084c009a 100644 --- a/3rdParty/ONNX/provider_options.h +++ b/3rdParty/ONNX/provider_options.h @@ -1,18 +1,18 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include -#include -#include - -namespace onnxruntime { - -// data types for execution provider options - -using ProviderOptions = std::unordered_map; -using ProviderOptionsVector = std::vector; -using ProviderOptionsMap = std::unordered_map; - -} // namespace onnxruntime +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#pragma once + +#include +#include +#include + +namespace onnxruntime { + +// data types for execution provider options + +using ProviderOptions = std::unordered_map; +using ProviderOptionsVector = std::vector; +using ProviderOptionsMap = std::unordered_map; + +} // namespace onnxruntime diff --git a/3rdParty/dpp/appcommand.h b/3rdParty/dpp/appcommand.h index efe11c196c..0409980e3d 100644 --- a/3rdParty/dpp/appcommand.h +++ b/3rdParty/dpp/appcommand.h @@ -1,1222 +1,1222 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Discord limits the maximum number of replies to an autocomplete interaction to 25. - * This value represents that maximum. interaction_response::add_autocomplete_choice does not allow - * adding more than this number of elements to the vector. - */ -#ifndef AUTOCOMPLETE_MAX_CHOICES - #define AUTOCOMPLETE_MAX_CHOICES 25 -#endif - -/** - * @brief Represents command option types. - * These are the possible parameter value types. - */ -enum command_option_type : uint8_t { - /** A sub-command */ - co_sub_command = 1, - /** A sub-command group */ - co_sub_command_group = 2, - /** A string value */ - co_string = 3, - /** An integer value */ - co_integer = 4, - /** A boolean value */ - co_boolean = 5, - /** A user snowflake id */ - co_user = 6, - /** A channel snowflake id. Includes all channel types and categories */ - co_channel = 7, - /** A role snowflake id */ - co_role = 8, - /** A mentionable. Includes users and roles */ - co_mentionable = 9, - /** Any double between -2^53 and 2^53 */ - co_number = 10, - /** File attachment type */ - co_attachment = 11, -}; - -/** - * @brief This type is a variant that can hold any of the potential - * native data types represented by the enum dpp::command_option_type. - * It is used in interactions. - * - * std::monostate indicates an invalid parameter value, e.g. an unfilled optional parameter. - * std::int64_t will be for all integer options, double for decimal numbers and dpp::snowflake for anything ID related. - * - * You can retrieve them with std::get(). - */ -typedef std::variant command_value; - -/** - * @brief This struct represents choices in a multiple choice option - * for a command parameter. - * It has both a string name, and a value parameter which is a variant, - * meaning it can hold different potential types (see dpp::command_value) - * that you can retrieve with std::get(). - */ -struct DPP_EXPORT command_option_choice : public json_interface { - std::string name; //!< Option name (1-32 chars) - command_value value; //!< Option value - std::map name_localizations; //!< Localisations of command option name - - /** - * @brief Construct a new command option choice object - */ - command_option_choice() = default; - - virtual ~command_option_choice() = default; - - /** - * @brief Add a localisation for this command option choice - * @see https://discord.com/developers/docs/reference#locales - * @param language Name of language, see the list of locales linked to above. - * @param _name name of command option choice in the specified language - * @return command_option_choice& reference to self for fluent chaining - */ - command_option_choice& add_localization(const std::string& language, const std::string& _name); - - /** - * @brief Construct a new command option choice object - * - * @param n name to initialise with - * @param v value to initialise with - */ - command_option_choice(const std::string &n, command_value v); - - /** - * @brief Fill object properties from JSON - * - * @param j JSON to fill from - * @return command_option_choice& Reference to self - */ - command_option_choice& fill_from_json(nlohmann::json* j); -}; - -/** - * @brief helper function to serialize a command_option_choice to json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param choice command_option_choice to be serialized - */ -void to_json(nlohmann::json& j, const command_option_choice& choice); - -/** - * @brief A minimum or maximum value for co_number and co_integer dpp::command_option types - */ -typedef std::variant command_option_range; - -/** - * @brief Each command option is a command line parameter. - * It can have a type (see dpp::command_option_type), a name, - * a description, can be required or optional, and can have - * zero or more choices (for multiple choice), plus options. - * Adding options acts like sub-commands and can contain more - * options. - */ -struct DPP_EXPORT command_option : public json_interface { - command_option_type type; //!< Option type (what type of value is accepted) - std::string name; //!< Option name (1-32 chars) - std::string description; //!< Option description (1-100 chars) - bool required; //!< True if this is a mandatory parameter - bool focused; //!< True if the user is typing in this field, when sent via autocomplete - command_value value; //!< Set only by autocomplete went sent as part of an interaction - std::vector choices; //!< List of choices for multiple choice command - bool autocomplete; //!< True if this option supports auto completion - std::vector options; //!< Sub-commands - std::vector channel_types; //!< Allowed channel types for channel snowflake id options - command_option_range min_value; //!< Minimum value allowed, for co_number and co_integer types only - command_option_range max_value; //!< Maximum value allowed, for co_number and co_integer types only - std::map name_localizations; //!< Localisations of command name - std::map description_localizations; //!< Localisations of command description - - - /** - * @brief Construct a new command option object - */ - command_option() = default; - - /** - * @brief Destroy the command option object - */ - virtual ~command_option() = default; - - /** - * @brief Add a localisation for this slash command option - * @see https://discord.com/developers/docs/reference#locales - * @param language Name of language, see the list of locales linked to above. - * @param _name name of slash command option in the specified language - * @param _description description of slash command option in the specified language - * @return command_option& reference to self for fluent chaining - */ - command_option& add_localization(const std::string& language, const std::string& _name, const std::string& _description); - - /** - * @brief Construct a new command option object - * - * @param t Option type - * @param name Option name - * @param description Option description - * @param required True if this is a mandatory parameter - */ - command_option(command_option_type t, const std::string &name, const std::string &description, bool required = false); - - /** - * @brief Add a multiple choice option - * - * @param o choice to add - * @return command_option& returns a reference to self for chaining of calls - * @throw dpp::exception command_option is an autocomplete, so choices cannot be added - */ - command_option& add_choice(const command_option_choice &o); - - /** - * @brief Set the minimum numeric value of the option. - * Only valid if the type is co_number or co_integer. - * @param min_v Minimum value - * @return command_option& return a reference to sef for chaining of calls - */ - command_option& set_min_value(command_option_range min_v); - - /** - * @brief Set the maximum numeric value of the option. - * Only valid if the type is co_number or co_integer. - * @param max_v Maximum value - * @return command_option& return a reference to sef for chaining of calls - */ - command_option& set_max_value(command_option_range max_v); - - /** - * @brief Set the minimum string length of the option. - * Only valid if the type is co_string - * @param min_v Minimum value - * @return command_option& return a reference to sef for chaining of calls - */ - command_option& set_min_length(command_option_range min_v); - - /** - * @brief Set the maximum string length of the option. - * Only valid if the type is co_string - * @param max_v Maximum value - * @return command_option& return a reference to sef for chaining of calls - */ - command_option& set_max_length(command_option_range max_v); - - /** - * @brief Add a sub-command option - * - * @param o Sub-command option to add - * @return command_option& return a reference to self for chaining of calls - */ - command_option& add_option(const command_option &o); - - /** - * @brief Add channel type for option (only for co_channel type options) - * - * @param ch type to set - * @return command_option& return a reference to self for chaining of calls - */ - command_option& add_channel_type(const channel_type ch); - - /** - * @brief Set the auto complete state - * - * @param autocomp True to enable auto completion for this option - * @return command_option& return a reference to self for chaining of calls - * @throw dpp::exception You attempted to enable auto complete on a command_option that has choices added to it - */ - command_option& set_auto_complete(bool autocomp); - - /** - * @brief Fill object properties from JSON. Fills options recursively. - * - * @param j JSON to fill from - * @return command_option& Reference to self - */ - command_option& fill_from_json(nlohmann::json* j); -}; - -/** - * @brief helper function to serialize a command_option to json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param opt command_option to be serialized - */ -void to_json(nlohmann::json& j, const command_option& opt); - -/** - * @brief Response types when responding to an interaction within on_interaction_create. - */ -enum interaction_response_type { - ir_pong = 1, //!< Acknowledge a Ping - ir_channel_message_with_source = 4, //!< respond to an interaction with a message - ir_deferred_channel_message_with_source = 5, //!< Acknowledge an interaction and edit a response later, the user sees a loading state - ir_deferred_update_message = 6, //!< for components, acknowledge an interaction and edit the original message later; the user does not see a loading state - ir_update_message = 7, //!< for components, edit the message the component was attached to - ir_autocomplete_reply = 8, //!< Reply to autocomplete interaction. Be sure to do this within 500ms of the interaction! - ir_modal_dialog = 9, //!< A modal dialog box -}; - -/** - * @brief A response to an interaction, used to reply to a command and initiate - * a message, which can be hidden from others (ephemeral) or visible to all. - * - * The dpp::interaction_response object wraps a dpp::message object. To set the - * message as 'ephemeral' (e.g. only the command issuer can see it) you should - * add the dpp::m_ephemeral flag to the dpp::message::flags field. e.g.: - * - * `mymessage.flags |= dpp::m_ephemeral;` - */ -struct DPP_EXPORT interaction_response : public json_interface { - - /** - * @brief Response type from dpp::interaction_response_type. - * Should be one of ir_pong, ir_channel_message_with_source, - * or ir_deferred_channel_message_with_source. - */ - interaction_response_type type; - - /** - * @brief A message object. This pointer is always valid - * while the containing interaction_response exists. - */ - struct message* msg; - - /** - * @brief Array of up to 25 autocomplete choices - */ - std::vector autocomplete_choices; - - /** - * @brief Construct a new interaction response object - */ - interaction_response(); - - /** - * @brief Construct a new interaction response object - * - * @param t Type of reply - * @param m Message to reply with - */ - interaction_response(interaction_response_type t, const struct message& m); - - /** - * @brief Construct a new interaction response object - * - * @param t Type of reply - */ - interaction_response(interaction_response_type t); - - /** - * @brief Fill object properties from JSON - * - * @param j JSON to fill from - * @return interaction_response& Reference to self - */ - interaction_response& fill_from_json(nlohmann::json* j); - - /** - * @brief Build a json string for this object - * - * @return std::string JSON string - */ - virtual std::string build_json(bool with_id = false) const; - - /** - * @brief Add a command option choice - * - * @param achoice command option choice to add - * @return interaction_response& Reference to self - */ - interaction_response& add_autocomplete_choice(const command_option_choice& achoice); - - /** - * @brief Destroy the interaction response object - */ - virtual ~interaction_response(); - -}; - -/** - * @brief Represents a modal dialog box response to an interaction. - * - * A dialog box is a modal popup which appears to the user instead of a message. One or more - * components are displayed on a form (the same component structure as within a dpp::message). - * When the user submits the form an on_form_submit event is dispatched to any listeners. - */ -struct DPP_EXPORT interaction_modal_response : public interaction_response, public json_interface { -private: - size_t current_row; -public: - /** - * @brief Custom ID for the modal form - */ - std::string custom_id; - - /** - * @brief Title of the modal form box - */ - std::string title; - - /** - * @brief List of components. All components must be placed within - * an action row, each outer vector is the action row. - */ - std::vector> components; - - /** - * @brief Construct a new interaction modal response object - */ - interaction_modal_response(); - - /** - * @brief Construct a new interaction modal response object - * - * @param _custom_id Custom ID of the modal form - * @param _title Title of the modal form. It will be truncated to the maximum length of 45 UTF-8 characters. - * @param _components Components to add to the modal form - */ - interaction_modal_response(const std::string& _custom_id, const std::string& _title, const std::vector _components = {}); - - /** - * @brief Set the custom id - * - * @param _custom_id custom id to set - * @return interaction_modal_response& Reference to self - */ - interaction_modal_response& set_custom_id(const std::string& _custom_id); - - /** - * @brief Set the title - * - * @param _title title to set - * @return interaction_modal_response& Reference to self - */ - interaction_modal_response& set_title(const std::string& _title); - - /** - * @brief Add a component to an interaction modal response - * - * @param c component to add - * @return interaction_modal_response& Reference to self - */ - interaction_modal_response& add_component(const component& c); - - /** - * @brief Add a new row to the interaction modal response. - * @note A modal response can have a maximum of five rows. - * @throw dpp::logic_exception if more than five rows are attempted to be added - * @return interaction_modal_response& Reference to self - */ - interaction_modal_response& add_row(); - - /** - * @brief Fill object properties from JSON - * - * @param j JSON to fill from - * @return interaction_response& Reference to self - */ - interaction_modal_response& fill_from_json(nlohmann::json* j); - - /** - * @brief Build a json string for this object - * @param with_id include id in json output - * - * @return std::string JSON string - */ - std::string build_json(bool with_id = false) const; - - /** - * @brief Destroy the interaction modal response object - */ - virtual ~interaction_modal_response() = default; -}; - -/** - * @brief Resolved snowflake ids to users, guild members, roles and channels. - */ -struct DPP_EXPORT command_resolved { - /** - * @brief Resolved users - */ - std::map users; - /** - * @brief Resolved guild members - */ - std::map members; - /** - * @brief Resolved total guild member permissions in the channel, including overwrites - */ - std::map member_permissions; - /** - * @brief Resolved roles - */ - std::map roles; - /** - * @brief Resolved channels - */ - std::map channels; - /** - * @brief Resolved messages - */ - std::map messages; - /** - * @brief Resolved attachments - */ - std::map attachments; -}; - -/** - * @brief Values in the command interaction. - * These are the values specified by the user when actually issuing - * the command on a channel or in DM. - */ -struct DPP_EXPORT command_data_option { - std::string name; //!< the name of the parameter - command_option_type type; //!< value of ApplicationCommandOptionType - command_value value; //!< Optional: the value of the pair - std::vector options; //!< Optional: present if this option is a group or subcommand - bool focused; //!< Optional: true if this option is the currently focused option for autocomplete - - /** - * @brief Check if the value variant holds std::monostate and options vector is empty (i.e. the option wasn't supplied) - * @return bool true, if value variant holds std::monostate and options vector is empty - */ - bool empty() { - return std::holds_alternative(value) && options.empty(); - } - - /** - * @brief Get an option value by index - * - * @tparam Type to get from the parameter - * @param index index number of parameter - * @return T returned type - */ - template T& get_value(size_t index) { - return std::get(options.at(index).value); - } -}; - -/** - * @brief helper function to deserialize a command_data_option from json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param cdo command_data_option to be deserialized - */ -void from_json(const nlohmann::json& j, command_data_option& cdo); - -/** Types of interaction in the dpp::interaction class - */ -enum interaction_type { - it_ping = 1, //!< ping - it_application_command = 2, //!< application command (slash command) - it_component_button = 3, //!< button click or select menu chosen (component interaction) - it_autocomplete = 4, //!< Autocomplete interaction - it_modal_submit = 5, //!< Modal form submission -}; - -/** - * @brief Right-click context menu types - */ -enum slashcommand_contextmenu_type { - ctxm_none = 0, //!< Undefined context menu type - ctxm_chat_input = 1, //!< DEFAULT, these are the slash commands you're used to - ctxm_user = 2, //!< Add command to user context menu - ctxm_message = 3 //!< Add command to message context menu -}; - -/** - * @brief Details of a command within an interaction. - * This subobject represents the application command associated - * with the interaction. - */ -struct DPP_EXPORT command_interaction { - snowflake id; //!< the ID of the invoked command - std::string name; //!< the name of the invoked command - std::vector options; //!< Optional: the params + values from the user - slashcommand_contextmenu_type type; //!< type of the command interaction - dpp::snowflake target_id; //!< Non-zero target ID for context menu actions. e.g. user id or message id whom clicked or tapped with the context menu https://discord.com/developers/docs/interactions/application-commands#user-commands - - /** - * @brief Get an option value by index - * - * @tparam Type to get from the parameter - * @param index index number of parameter - * @return T returned type - */ - template T& get_value(size_t index) { - return std::get(options.at(index).value); - } - - /** - * @brief Return a ping/mention for the slash command - * - * @return std::string mention. e.g. `` - * @note If you want a mention for a subcommand or subcommand group, you can use dpp::utility::slashcommand_mention - */ - std::string get_mention() const; -}; - -/** - * @brief helper function to deserialize a command_interaction from json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param ci command_interaction to be deserialized - */ -void from_json(const nlohmann::json& j, command_interaction& ci); - -/** - * @brief A button click for a button component - */ -struct DPP_EXPORT component_interaction { - /** - * @brief Component type (dpp::component_type) - */ - uint8_t component_type; - /** - * @brief Custom ID set when created - */ - std::string custom_id; - /** - * @brief Possible values for a drop down list - */ - std::vector values; -}; - -/** - * @brief An auto complete interaction - */ -struct DPP_EXPORT autocomplete_interaction : public command_interaction { -}; - -/** - * @brief helper function to deserialize a component_interaction from json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param bi button_interaction to be deserialized - */ -void from_json(const nlohmann::json& j, component_interaction& bi); - -/** - * @brief helper function to deserialize an autocomplete_interaction from json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param ai autocomplete_interaction to be deserialized - */ -void from_json(const nlohmann::json& j, autocomplete_interaction& ai); - -/** - * @brief An interaction represents a user running a command and arrives - * via the dpp::cluster::on_interaction_create event. This is further split - * into the events on_form_submit, on_slashcommand, on_user_context_menu, - * on_button_click, on_select_menu, etc. - */ -class DPP_EXPORT interaction : public managed, public json_interface { - - /** - * @brief Get a resolved object from the resolved set - * - * @tparam T type of object to retrieve - * @tparam C container defintion for resolved container - * @param id Snowflake ID - * @param resolved_set container for the type - * @return const T& retrieved type - * @throws dpp::logic_exception on object not found in resolved set - */ - template const T& get_resolved(snowflake id, const C& resolved_set) const { - auto i = resolved_set.find(id); - if (i == resolved_set.end()) { - throw dpp::logic_exception("ID not found in resolved properties of application command"); - } - return i->second; - } - -public: - snowflake application_id; //!< id of the application this interaction is for - uint8_t type; //!< the type of interaction (dpp::interaction_type) - std::variant data; //!< Optional: the command data payload - snowflake guild_id; //!< Optional: the guild it was sent from - snowflake channel_id; //!< Optional: the channel it was sent from - snowflake message_id; //!< Originating message id for context menu actions - permission app_permissions; //!< Permissions of the bot in the channel/guild where this command was issued - message msg; //!< Originating message for context menu actions - guild_member member; //!< Optional: guild member data for the invoking user, including permissions - user usr; //!< User object for the invoking user - std::string token; //!< a continuation token for responding to the interaction - uint8_t version; //!< read-only property, always 1 - command_resolved resolved; //!< Resolved user/role etc - std::string locale; //!< User's locale (language) - std::string guild_locale; //!< Guild's locale (language) - for guild interactions only - cache_policy_t cache_policy; //!< Cache policy from cluster - - /** - * @brief Construct a new interaction object - */ - interaction(); - - /** - * @brief Destroy the interaction object - */ - virtual ~interaction() = default; - - /** - * @brief Get a user associated with the slash command from the resolved list. - * The resolved list contains associated structures for this command and does not - * use the cache or require any extra API calls. - * - * @param id User snowflake ID to find - * @return const dpp::user& user - * @throws dpp::logic_exception on object not found in resolved set - */ - const dpp::user& get_resolved_user(snowflake id) const; - - /** - * @brief Get the channel this command originated on - * - * @return const dpp::channel& channel - * @throws dpp::logic_exception Command originated from a DM or channel not in cache - */ - const dpp::channel& get_channel() const; - - /** - * @brief Get the guild this command originated on - * - * @return const dpp::guild& guild - * @throws dpp::logic_exception Command originated from a DM or guild not in cache - */ - const dpp::guild& get_guild() const; - - /** - * @brief Get the user who issued this command - * - * @return const dpp::user& user - */ - const dpp::user& get_issuing_user() const; - - /** - * @brief Get the message this action refers to if it is a context menu command - * - * @return const dpp::message& context menu message - */ - const dpp::message& get_context_message() const; - - /** - * @brief Get a role associated with the slash command from the resolved list. - * The resolved list contains associated structures for this command and does not - * use the cache or require any extra API calls. - * - * @param id Role snowflake ID to find - * @return const dpp::role& role - * @throws dpp::logic_exception on object not found in resolved set - */ - const dpp::role& get_resolved_role(snowflake id) const; - - /** - * @brief Get a channel associated with the slash command from the resolved list. - * The resolved list contains associated structures for this command and does not - * use the cache or require any extra API calls. - * - * @param id Channel snowflake ID to find - * @return const dpp::channel& channel - * @throws dpp::logic_exception on object not found in resolved set - */ - const dpp::channel& get_resolved_channel(snowflake id) const; - - /** - * @brief Get a guild member associated with the slash command from the resolved list. - * The resolved list contains associated structures for this command and does not - * use the cache or require any extra API calls. - * - * @param id User snowflake ID to find - * @return const dpp::guild_member& guild member - * @throws dpp::logic_exception on object not found in resolved set - */ - const dpp::guild_member& get_resolved_member(snowflake id) const; - - /** - * @brief Get a permission associated with the slash command from the resolved list. - * The resolved list contains associated structures for this command and does not - * use the cache or require any extra API calls. - * - * @param id User snowflake ID to find - * @return const dpp::permission& permissions for the user including overrides on - * the channel where the command was issued. - * @throws dpp::logic_exception on object not found in resolved set - */ - const dpp::permission& get_resolved_permission(snowflake id) const; - - /** - * @brief Get a message associated with the slash command from the resolved list. - * The resolved list contains associated structures for this command and does not - * use the cache or require any extra API calls. - * - * @param id Message snowflake ID to find - * @return const dpp::message& message - * @throws dpp::logic_exception on object not found in resolved set - */ - const dpp::message& get_resolved_message(snowflake id) const; - - /** - * @brief Get an uploaded attachment associated with the slash command from the resolved list. - * The resolved list contains associated structures for this command and does not - * use the cache or require any extra API calls. - * - * @param id Attachment snowflake ID to find - * @return const dpp::attachment& file attachment - * @throws dpp::logic_exception on object not found in resolved set - */ - const dpp::attachment& get_resolved_attachment(snowflake id) const; - - /** - * @brief Get the command interaction object - * - * @throw dpp::logic_exception if the interaction is not for a command - * - * @return command_interaction object - */ - command_interaction get_command_interaction() const; - - /** - * @brief Get the component interaction object - * - * @throw dpp::logic_exception if the interaction is not for a component - * - * @return component_interaction object - */ - component_interaction get_component_interaction() const; - - /** - * @brief Get the autocomplete interaction object - * - * @throw dpp::logic_exception if the interaction is not for an autocomplete - * - * @return autocomplete_interaction object - */ - autocomplete_interaction get_autocomplete_interaction() const; - - /** - * @brief Get the command name for a command interaction - * - * @return std::string command interaction, or empty string if the interaction - * is not for a command. - */ - std::string get_command_name() const; - - /** - * @brief Fill object properties from JSON - * - * @param j JSON to fill from - * @return interaction& Reference to self - */ - interaction& fill_from_json(nlohmann::json* j); - - /** - * @brief Build a json string for this object - * - * @param with_id True if to include the ID in the JSON - * @return std::string JSON string - */ - std::string build_json(bool with_id = false) const; -}; - -/** - * @brief helper function to deserialize an interaction from json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param i interaction to be deserialized - */ -void from_json(const nlohmann::json& j, interaction& i); - -/** - * @brief type of permission in the dpp::command_permission class - */ -enum command_permission_type { - /** - * @brief Role permission - * - */ - cpt_role = 1, - /** - * @brief User permission - * - */ - cpt_user = 2, -}; - -/** - * @brief Application command permissions allow you to enable or - * disable commands for specific users or roles within a guild - */ -class DPP_EXPORT command_permission : public json_interface { -public: - snowflake id; //!< the ID of the role or user - command_permission_type type; //!< the type of permission - bool permission; //!< true to allow, false, to disallow - - /** - * @brief Construct a new command permission object - */ - command_permission() = default; - - virtual ~command_permission() = default; - - /** - * @brief Construct a new command permission object - * - * @param id The ID of the role or user - * @param t The permission type - * @param permission True to allow, false, to disallow - */ - command_permission(snowflake id, const command_permission_type t, bool permission); - - /** - * @brief Fill object properties from JSON - * - * @param j JSON to fill from - * @return command_permission& Reference to self - */ - command_permission &fill_from_json(nlohmann::json *j); -}; - -/** - * @brief helper function to serialize a command_permission to json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param cp command_permission to be serialized - */ -void to_json(nlohmann::json& j, const command_permission& cp); - -/** - * @brief Returned when fetching the permissions for a command in a guild. - */ -class DPP_EXPORT guild_command_permissions : public json_interface { -public: - snowflake id; //!< the id of the command - snowflake application_id; //!< the id of the application the command belongs to - snowflake guild_id; //!< the id of the guild - std::vector permissions; //!< the permissions for the command in the guild - - /** - * @brief Construct a new guild command permissions object - */ - guild_command_permissions(); - - virtual ~guild_command_permissions() = default; - - /** - * @brief Fill object properties from JSON - * - * @param j JSON to fill from - * @return guild_command_permissions& Reference to self - */ - guild_command_permissions &fill_from_json(nlohmann::json *j); - -}; - -/** - * @brief helper function to serialize a guild_command_permissions to json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param gcp guild_command_permissions to be serialized - */ -void to_json(nlohmann::json& j, const guild_command_permissions& gcp); - -/** - * @brief Represents an application command, created by your bot - * either globally, or on a guild. - */ -class DPP_EXPORT slashcommand : public managed, public json_interface { -public: - /** - * @brief Application id (usually matches your bots id) - */ - snowflake application_id; - - /** - * @brief Context menu type, defaults to dpp::ctxm_chat_input - */ - slashcommand_contextmenu_type type; - - /** - * @brief Command name (1-32 chars) - */ - std::string name; - - /** - * @brief Command description (1-100 chars) - */ - std::string description; - - /** - * @brief Command options (parameters) - */ - std::vector options; - - /** - * @brief Whether the command is enabled by default when the app is added to a guild. - * This has no effect as the default_member_permissions value is used instead. - * @deprecated Discord discourage use of this value and instead you should use slashcommand::default_member_permissions. - */ - bool default_permission; - - /** - * @brief command permissions - * @deprecated Discord discourage use of this value and instead you should use default_member_permissions. - */ - std::vector permissions; - - /** - * @brief autoincrementing version identifier updated during substantial record changes - */ - snowflake version; - - /** - * @brief Localisations of command name - */ - std::map name_localizations; - - /** - * @brief Localisations of command description - */ - std::map description_localizations; - - /** - * @brief The default permissions of this command on a guild. - * D++ defaults this to dpp::p_use_application_commands. - * @note You can set it to 0 to disable the command for everyone except admins by default - */ - permission default_member_permissions; - - /** - * @brief True if this command should be allowed in a DM - * D++ defaults this to false. Cannot be set to true in a guild - * command, only a global command. - */ - bool dm_permission; - - /** - * @brief Indicates whether the command is [age-restricted](https://discord.com/developers/docs/interactions/application-commands#agerestricted-commands). - * Defaults to false - */ - bool nsfw; - - /** - * @brief Construct a new slashcommand object - */ - slashcommand(); - - /** - * @brief Construct a new slashcommand object - * - * @param _name Command name - * @param _description Command description - * @param _application_id Application id (usually the bot's user id) - */ - slashcommand(const std::string &_name, const std::string &_description, const dpp::snowflake _application_id); - - /** - * @brief Destroy the slashcommand object - */ - virtual ~slashcommand(); - - /** - * @brief Add a localisation for this slash command - * @see https://discord.com/developers/docs/reference#locales - * @param language Name of language, see the list of locales linked to above. - * @param _name name of slash command in the specified language - * @param _description description of slash command in the specified language - * @return slashcommand& reference to self for fluent chaining - */ - slashcommand& add_localization(const std::string& language, const std::string& _name, const std::string& _description); - - /** - * @brief Set the dm permission for the command - * - * @param dm true to allow this command in dms - * @return slashcommand& reference to self for chaining of calls - */ - slashcommand& set_dm_permission(bool dm); - - /** - * @brief Set whether the command should be age-restricted or not - * - * @param is_nsfw true if the command should be age-restricted - * @return slashcommand& reference to self for chaining of calls - */ - slashcommand& set_nsfw(bool is_nsfw); - - /** - * @brief Set the default permissions of the slash command - * - * @param defaults default permissions to set. This is a permission bitmask of bits from dpp::permissions - * @note You can set it to 0 to disable the command for everyone except admins by default - * - * @return slashcommand& reference to self for chaining of calls - */ - slashcommand& set_default_permissions(uint64_t defaults); - - /** - * @brief Add an option (parameter) - * - * @param o option (parameter) to add - * @return slashcommand& reference to self for chaining of calls - */ - slashcommand& add_option(const command_option &o); - - /** - * @brief Set the type of the slash command (only for context menu entries) - * - * @param _type Type of context menu entry this command represents - * @note If the type is dpp::ctxm_chat_input, the command name will be set to lowercase. - * @return slashcommand& reference to self for chaining of calls - */ - slashcommand& set_type(slashcommand_contextmenu_type _type); - - /** - * @brief Set the name of the command - * - * @param n name of command - * @note The maximum length of a command name is 32 UTF-8 codepoints. - * If your command name is longer than this, it will be truncated. - * The command name will be set to lowercase when the type is the default dpp::ctxm_chat_input. - * @return slashcommand& reference to self for chaining of calls - */ - slashcommand& set_name(const std::string &n); - - /** - * @brief Set the description of the command - * - * @param d description - * @note The maximum length of a command description is 100 UTF-8 codepoints. - * If your command description is longer than this, it will be truncated. - * @return slashcommand& reference to self for chaining of calls - */ - slashcommand& set_description(const std::string &d); - - /** - * @brief Set the application id of the command - * - * @param i application id - * @return slashcommand& reference to self for chaining of calls - */ - slashcommand& set_application_id(snowflake i); - - /** - * @brief Adds a permission to the command - * - * @param p permission to add - * @return slashcommand& reference to self for chaining of calls - * @deprecated Discord discourage use of this value and instead you should use default_member_permissions. - */ - slashcommand& add_permission(const command_permission& p); - - /** - * @brief Disable default permissions, command will be unusable unless - * permissions are overridden with add_permission and - * dpp::guild_command_edit_permissions - * - * @return slashcommand& reference to self for chaining of calls - * @deprecated Discord discourage use of this value and instead you should use default_member_permissions. - */ - slashcommand& disable_default_permissions(); - - /** - * @brief Return a ping/mention for the slash command - * - * @return std::string mention. e.g. `` - * @note If you want a mention for a subcommand or subcommand group, you can use dpp::utility::slashcommand_mention - */ - std::string get_mention() const; - - /** - * @brief Fill object properties from JSON - * - * @param j JSON to fill from - * @return slashcommand& Reference to self - */ - slashcommand& fill_from_json(nlohmann::json* j); - - /** - * @brief Build a json string for this object - * - * @param with_id True if to include the ID in the JSON - * @return std::string JSON string - */ - std::string build_json(bool with_id = false) const; -}; - -/** - * @brief helper function to serialize a slashcommand to json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param cmd slashcommand to be serialized - */ -void to_json(nlohmann::json& j, const slashcommand& cmd); - -/** - * @brief A group of application slash commands - */ -typedef std::unordered_map slashcommand_map; - -/** - * @brief A group of guild command permissions - */ -typedef std::unordered_map guild_command_permissions_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Discord limits the maximum number of replies to an autocomplete interaction to 25. + * This value represents that maximum. interaction_response::add_autocomplete_choice does not allow + * adding more than this number of elements to the vector. + */ +#ifndef AUTOCOMPLETE_MAX_CHOICES + #define AUTOCOMPLETE_MAX_CHOICES 25 +#endif + +/** + * @brief Represents command option types. + * These are the possible parameter value types. + */ +enum command_option_type : uint8_t { + /** A sub-command */ + co_sub_command = 1, + /** A sub-command group */ + co_sub_command_group = 2, + /** A string value */ + co_string = 3, + /** An integer value */ + co_integer = 4, + /** A boolean value */ + co_boolean = 5, + /** A user snowflake id */ + co_user = 6, + /** A channel snowflake id. Includes all channel types and categories */ + co_channel = 7, + /** A role snowflake id */ + co_role = 8, + /** A mentionable. Includes users and roles */ + co_mentionable = 9, + /** Any double between -2^53 and 2^53 */ + co_number = 10, + /** File attachment type */ + co_attachment = 11, +}; + +/** + * @brief This type is a variant that can hold any of the potential + * native data types represented by the enum dpp::command_option_type. + * It is used in interactions. + * + * std::monostate indicates an invalid parameter value, e.g. an unfilled optional parameter. + * std::int64_t will be for all integer options, double for decimal numbers and dpp::snowflake for anything ID related. + * + * You can retrieve them with std::get(). + */ +typedef std::variant command_value; + +/** + * @brief This struct represents choices in a multiple choice option + * for a command parameter. + * It has both a string name, and a value parameter which is a variant, + * meaning it can hold different potential types (see dpp::command_value) + * that you can retrieve with std::get(). + */ +struct DPP_EXPORT command_option_choice : public json_interface { + std::string name; //!< Option name (1-32 chars) + command_value value; //!< Option value + std::map name_localizations; //!< Localisations of command option name + + /** + * @brief Construct a new command option choice object + */ + command_option_choice() = default; + + virtual ~command_option_choice() = default; + + /** + * @brief Add a localisation for this command option choice + * @see https://discord.com/developers/docs/reference#locales + * @param language Name of language, see the list of locales linked to above. + * @param _name name of command option choice in the specified language + * @return command_option_choice& reference to self for fluent chaining + */ + command_option_choice& add_localization(const std::string& language, const std::string& _name); + + /** + * @brief Construct a new command option choice object + * + * @param n name to initialise with + * @param v value to initialise with + */ + command_option_choice(const std::string &n, command_value v); + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return command_option_choice& Reference to self + */ + command_option_choice& fill_from_json(nlohmann::json* j); +}; + +/** + * @brief helper function to serialize a command_option_choice to json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param choice command_option_choice to be serialized + */ +void to_json(nlohmann::json& j, const command_option_choice& choice); + +/** + * @brief A minimum or maximum value for co_number and co_integer dpp::command_option types + */ +typedef std::variant command_option_range; + +/** + * @brief Each command option is a command line parameter. + * It can have a type (see dpp::command_option_type), a name, + * a description, can be required or optional, and can have + * zero or more choices (for multiple choice), plus options. + * Adding options acts like sub-commands and can contain more + * options. + */ +struct DPP_EXPORT command_option : public json_interface { + command_option_type type; //!< Option type (what type of value is accepted) + std::string name; //!< Option name (1-32 chars) + std::string description; //!< Option description (1-100 chars) + bool required; //!< True if this is a mandatory parameter + bool focused; //!< True if the user is typing in this field, when sent via autocomplete + command_value value; //!< Set only by autocomplete went sent as part of an interaction + std::vector choices; //!< List of choices for multiple choice command + bool autocomplete; //!< True if this option supports auto completion + std::vector options; //!< Sub-commands + std::vector channel_types; //!< Allowed channel types for channel snowflake id options + command_option_range min_value; //!< Minimum value allowed, for co_number and co_integer types only + command_option_range max_value; //!< Maximum value allowed, for co_number and co_integer types only + std::map name_localizations; //!< Localisations of command name + std::map description_localizations; //!< Localisations of command description + + + /** + * @brief Construct a new command option object + */ + command_option() = default; + + /** + * @brief Destroy the command option object + */ + virtual ~command_option() = default; + + /** + * @brief Add a localisation for this slash command option + * @see https://discord.com/developers/docs/reference#locales + * @param language Name of language, see the list of locales linked to above. + * @param _name name of slash command option in the specified language + * @param _description description of slash command option in the specified language + * @return command_option& reference to self for fluent chaining + */ + command_option& add_localization(const std::string& language, const std::string& _name, const std::string& _description); + + /** + * @brief Construct a new command option object + * + * @param t Option type + * @param name Option name + * @param description Option description + * @param required True if this is a mandatory parameter + */ + command_option(command_option_type t, const std::string &name, const std::string &description, bool required = false); + + /** + * @brief Add a multiple choice option + * + * @param o choice to add + * @return command_option& returns a reference to self for chaining of calls + * @throw dpp::exception command_option is an autocomplete, so choices cannot be added + */ + command_option& add_choice(const command_option_choice &o); + + /** + * @brief Set the minimum numeric value of the option. + * Only valid if the type is co_number or co_integer. + * @param min_v Minimum value + * @return command_option& return a reference to sef for chaining of calls + */ + command_option& set_min_value(command_option_range min_v); + + /** + * @brief Set the maximum numeric value of the option. + * Only valid if the type is co_number or co_integer. + * @param max_v Maximum value + * @return command_option& return a reference to sef for chaining of calls + */ + command_option& set_max_value(command_option_range max_v); + + /** + * @brief Set the minimum string length of the option. + * Only valid if the type is co_string + * @param min_v Minimum value + * @return command_option& return a reference to sef for chaining of calls + */ + command_option& set_min_length(command_option_range min_v); + + /** + * @brief Set the maximum string length of the option. + * Only valid if the type is co_string + * @param max_v Maximum value + * @return command_option& return a reference to sef for chaining of calls + */ + command_option& set_max_length(command_option_range max_v); + + /** + * @brief Add a sub-command option + * + * @param o Sub-command option to add + * @return command_option& return a reference to self for chaining of calls + */ + command_option& add_option(const command_option &o); + + /** + * @brief Add channel type for option (only for co_channel type options) + * + * @param ch type to set + * @return command_option& return a reference to self for chaining of calls + */ + command_option& add_channel_type(const channel_type ch); + + /** + * @brief Set the auto complete state + * + * @param autocomp True to enable auto completion for this option + * @return command_option& return a reference to self for chaining of calls + * @throw dpp::exception You attempted to enable auto complete on a command_option that has choices added to it + */ + command_option& set_auto_complete(bool autocomp); + + /** + * @brief Fill object properties from JSON. Fills options recursively. + * + * @param j JSON to fill from + * @return command_option& Reference to self + */ + command_option& fill_from_json(nlohmann::json* j); +}; + +/** + * @brief helper function to serialize a command_option to json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param opt command_option to be serialized + */ +void to_json(nlohmann::json& j, const command_option& opt); + +/** + * @brief Response types when responding to an interaction within on_interaction_create. + */ +enum interaction_response_type { + ir_pong = 1, //!< Acknowledge a Ping + ir_channel_message_with_source = 4, //!< respond to an interaction with a message + ir_deferred_channel_message_with_source = 5, //!< Acknowledge an interaction and edit a response later, the user sees a loading state + ir_deferred_update_message = 6, //!< for components, acknowledge an interaction and edit the original message later; the user does not see a loading state + ir_update_message = 7, //!< for components, edit the message the component was attached to + ir_autocomplete_reply = 8, //!< Reply to autocomplete interaction. Be sure to do this within 500ms of the interaction! + ir_modal_dialog = 9, //!< A modal dialog box +}; + +/** + * @brief A response to an interaction, used to reply to a command and initiate + * a message, which can be hidden from others (ephemeral) or visible to all. + * + * The dpp::interaction_response object wraps a dpp::message object. To set the + * message as 'ephemeral' (e.g. only the command issuer can see it) you should + * add the dpp::m_ephemeral flag to the dpp::message::flags field. e.g.: + * + * `mymessage.flags |= dpp::m_ephemeral;` + */ +struct DPP_EXPORT interaction_response : public json_interface { + + /** + * @brief Response type from dpp::interaction_response_type. + * Should be one of ir_pong, ir_channel_message_with_source, + * or ir_deferred_channel_message_with_source. + */ + interaction_response_type type; + + /** + * @brief A message object. This pointer is always valid + * while the containing interaction_response exists. + */ + struct message* msg; + + /** + * @brief Array of up to 25 autocomplete choices + */ + std::vector autocomplete_choices; + + /** + * @brief Construct a new interaction response object + */ + interaction_response(); + + /** + * @brief Construct a new interaction response object + * + * @param t Type of reply + * @param m Message to reply with + */ + interaction_response(interaction_response_type t, const struct message& m); + + /** + * @brief Construct a new interaction response object + * + * @param t Type of reply + */ + interaction_response(interaction_response_type t); + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return interaction_response& Reference to self + */ + interaction_response& fill_from_json(nlohmann::json* j); + + /** + * @brief Build a json string for this object + * + * @return std::string JSON string + */ + virtual std::string build_json(bool with_id = false) const; + + /** + * @brief Add a command option choice + * + * @param achoice command option choice to add + * @return interaction_response& Reference to self + */ + interaction_response& add_autocomplete_choice(const command_option_choice& achoice); + + /** + * @brief Destroy the interaction response object + */ + virtual ~interaction_response(); + +}; + +/** + * @brief Represents a modal dialog box response to an interaction. + * + * A dialog box is a modal popup which appears to the user instead of a message. One or more + * components are displayed on a form (the same component structure as within a dpp::message). + * When the user submits the form an on_form_submit event is dispatched to any listeners. + */ +struct DPP_EXPORT interaction_modal_response : public interaction_response, public json_interface { +private: + size_t current_row; +public: + /** + * @brief Custom ID for the modal form + */ + std::string custom_id; + + /** + * @brief Title of the modal form box + */ + std::string title; + + /** + * @brief List of components. All components must be placed within + * an action row, each outer vector is the action row. + */ + std::vector> components; + + /** + * @brief Construct a new interaction modal response object + */ + interaction_modal_response(); + + /** + * @brief Construct a new interaction modal response object + * + * @param _custom_id Custom ID of the modal form + * @param _title Title of the modal form. It will be truncated to the maximum length of 45 UTF-8 characters. + * @param _components Components to add to the modal form + */ + interaction_modal_response(const std::string& _custom_id, const std::string& _title, const std::vector _components = {}); + + /** + * @brief Set the custom id + * + * @param _custom_id custom id to set + * @return interaction_modal_response& Reference to self + */ + interaction_modal_response& set_custom_id(const std::string& _custom_id); + + /** + * @brief Set the title + * + * @param _title title to set + * @return interaction_modal_response& Reference to self + */ + interaction_modal_response& set_title(const std::string& _title); + + /** + * @brief Add a component to an interaction modal response + * + * @param c component to add + * @return interaction_modal_response& Reference to self + */ + interaction_modal_response& add_component(const component& c); + + /** + * @brief Add a new row to the interaction modal response. + * @note A modal response can have a maximum of five rows. + * @throw dpp::logic_exception if more than five rows are attempted to be added + * @return interaction_modal_response& Reference to self + */ + interaction_modal_response& add_row(); + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return interaction_response& Reference to self + */ + interaction_modal_response& fill_from_json(nlohmann::json* j); + + /** + * @brief Build a json string for this object + * @param with_id include id in json output + * + * @return std::string JSON string + */ + std::string build_json(bool with_id = false) const; + + /** + * @brief Destroy the interaction modal response object + */ + virtual ~interaction_modal_response() = default; +}; + +/** + * @brief Resolved snowflake ids to users, guild members, roles and channels. + */ +struct DPP_EXPORT command_resolved { + /** + * @brief Resolved users + */ + std::map users; + /** + * @brief Resolved guild members + */ + std::map members; + /** + * @brief Resolved total guild member permissions in the channel, including overwrites + */ + std::map member_permissions; + /** + * @brief Resolved roles + */ + std::map roles; + /** + * @brief Resolved channels + */ + std::map channels; + /** + * @brief Resolved messages + */ + std::map messages; + /** + * @brief Resolved attachments + */ + std::map attachments; +}; + +/** + * @brief Values in the command interaction. + * These are the values specified by the user when actually issuing + * the command on a channel or in DM. + */ +struct DPP_EXPORT command_data_option { + std::string name; //!< the name of the parameter + command_option_type type; //!< value of ApplicationCommandOptionType + command_value value; //!< Optional: the value of the pair + std::vector options; //!< Optional: present if this option is a group or subcommand + bool focused; //!< Optional: true if this option is the currently focused option for autocomplete + + /** + * @brief Check if the value variant holds std::monostate and options vector is empty (i.e. the option wasn't supplied) + * @return bool true, if value variant holds std::monostate and options vector is empty + */ + bool empty() { + return std::holds_alternative(value) && options.empty(); + } + + /** + * @brief Get an option value by index + * + * @tparam Type to get from the parameter + * @param index index number of parameter + * @return T returned type + */ + template T& get_value(size_t index) { + return std::get(options.at(index).value); + } +}; + +/** + * @brief helper function to deserialize a command_data_option from json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param cdo command_data_option to be deserialized + */ +void from_json(const nlohmann::json& j, command_data_option& cdo); + +/** Types of interaction in the dpp::interaction class + */ +enum interaction_type { + it_ping = 1, //!< ping + it_application_command = 2, //!< application command (slash command) + it_component_button = 3, //!< button click or select menu chosen (component interaction) + it_autocomplete = 4, //!< Autocomplete interaction + it_modal_submit = 5, //!< Modal form submission +}; + +/** + * @brief Right-click context menu types + */ +enum slashcommand_contextmenu_type { + ctxm_none = 0, //!< Undefined context menu type + ctxm_chat_input = 1, //!< DEFAULT, these are the slash commands you're used to + ctxm_user = 2, //!< Add command to user context menu + ctxm_message = 3 //!< Add command to message context menu +}; + +/** + * @brief Details of a command within an interaction. + * This subobject represents the application command associated + * with the interaction. + */ +struct DPP_EXPORT command_interaction { + snowflake id; //!< the ID of the invoked command + std::string name; //!< the name of the invoked command + std::vector options; //!< Optional: the params + values from the user + slashcommand_contextmenu_type type; //!< type of the command interaction + dpp::snowflake target_id; //!< Non-zero target ID for context menu actions. e.g. user id or message id whom clicked or tapped with the context menu https://discord.com/developers/docs/interactions/application-commands#user-commands + + /** + * @brief Get an option value by index + * + * @tparam Type to get from the parameter + * @param index index number of parameter + * @return T returned type + */ + template T& get_value(size_t index) { + return std::get(options.at(index).value); + } + + /** + * @brief Return a ping/mention for the slash command + * + * @return std::string mention. e.g. `` + * @note If you want a mention for a subcommand or subcommand group, you can use dpp::utility::slashcommand_mention + */ + std::string get_mention() const; +}; + +/** + * @brief helper function to deserialize a command_interaction from json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param ci command_interaction to be deserialized + */ +void from_json(const nlohmann::json& j, command_interaction& ci); + +/** + * @brief A button click for a button component + */ +struct DPP_EXPORT component_interaction { + /** + * @brief Component type (dpp::component_type) + */ + uint8_t component_type; + /** + * @brief Custom ID set when created + */ + std::string custom_id; + /** + * @brief Possible values for a drop down list + */ + std::vector values; +}; + +/** + * @brief An auto complete interaction + */ +struct DPP_EXPORT autocomplete_interaction : public command_interaction { +}; + +/** + * @brief helper function to deserialize a component_interaction from json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param bi button_interaction to be deserialized + */ +void from_json(const nlohmann::json& j, component_interaction& bi); + +/** + * @brief helper function to deserialize an autocomplete_interaction from json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param ai autocomplete_interaction to be deserialized + */ +void from_json(const nlohmann::json& j, autocomplete_interaction& ai); + +/** + * @brief An interaction represents a user running a command and arrives + * via the dpp::cluster::on_interaction_create event. This is further split + * into the events on_form_submit, on_slashcommand, on_user_context_menu, + * on_button_click, on_select_menu, etc. + */ +class DPP_EXPORT interaction : public managed, public json_interface { + + /** + * @brief Get a resolved object from the resolved set + * + * @tparam T type of object to retrieve + * @tparam C container defintion for resolved container + * @param id Snowflake ID + * @param resolved_set container for the type + * @return const T& retrieved type + * @throws dpp::logic_exception on object not found in resolved set + */ + template const T& get_resolved(snowflake id, const C& resolved_set) const { + auto i = resolved_set.find(id); + if (i == resolved_set.end()) { + throw dpp::logic_exception("ID not found in resolved properties of application command"); + } + return i->second; + } + +public: + snowflake application_id; //!< id of the application this interaction is for + uint8_t type; //!< the type of interaction (dpp::interaction_type) + std::variant data; //!< Optional: the command data payload + snowflake guild_id; //!< Optional: the guild it was sent from + snowflake channel_id; //!< Optional: the channel it was sent from + snowflake message_id; //!< Originating message id for context menu actions + permission app_permissions; //!< Permissions of the bot in the channel/guild where this command was issued + message msg; //!< Originating message for context menu actions + guild_member member; //!< Optional: guild member data for the invoking user, including permissions + user usr; //!< User object for the invoking user + std::string token; //!< a continuation token for responding to the interaction + uint8_t version; //!< read-only property, always 1 + command_resolved resolved; //!< Resolved user/role etc + std::string locale; //!< User's locale (language) + std::string guild_locale; //!< Guild's locale (language) - for guild interactions only + cache_policy_t cache_policy; //!< Cache policy from cluster + + /** + * @brief Construct a new interaction object + */ + interaction(); + + /** + * @brief Destroy the interaction object + */ + virtual ~interaction() = default; + + /** + * @brief Get a user associated with the slash command from the resolved list. + * The resolved list contains associated structures for this command and does not + * use the cache or require any extra API calls. + * + * @param id User snowflake ID to find + * @return const dpp::user& user + * @throws dpp::logic_exception on object not found in resolved set + */ + const dpp::user& get_resolved_user(snowflake id) const; + + /** + * @brief Get the channel this command originated on + * + * @return const dpp::channel& channel + * @throws dpp::logic_exception Command originated from a DM or channel not in cache + */ + const dpp::channel& get_channel() const; + + /** + * @brief Get the guild this command originated on + * + * @return const dpp::guild& guild + * @throws dpp::logic_exception Command originated from a DM or guild not in cache + */ + const dpp::guild& get_guild() const; + + /** + * @brief Get the user who issued this command + * + * @return const dpp::user& user + */ + const dpp::user& get_issuing_user() const; + + /** + * @brief Get the message this action refers to if it is a context menu command + * + * @return const dpp::message& context menu message + */ + const dpp::message& get_context_message() const; + + /** + * @brief Get a role associated with the slash command from the resolved list. + * The resolved list contains associated structures for this command and does not + * use the cache or require any extra API calls. + * + * @param id Role snowflake ID to find + * @return const dpp::role& role + * @throws dpp::logic_exception on object not found in resolved set + */ + const dpp::role& get_resolved_role(snowflake id) const; + + /** + * @brief Get a channel associated with the slash command from the resolved list. + * The resolved list contains associated structures for this command and does not + * use the cache or require any extra API calls. + * + * @param id Channel snowflake ID to find + * @return const dpp::channel& channel + * @throws dpp::logic_exception on object not found in resolved set + */ + const dpp::channel& get_resolved_channel(snowflake id) const; + + /** + * @brief Get a guild member associated with the slash command from the resolved list. + * The resolved list contains associated structures for this command and does not + * use the cache or require any extra API calls. + * + * @param id User snowflake ID to find + * @return const dpp::guild_member& guild member + * @throws dpp::logic_exception on object not found in resolved set + */ + const dpp::guild_member& get_resolved_member(snowflake id) const; + + /** + * @brief Get a permission associated with the slash command from the resolved list. + * The resolved list contains associated structures for this command and does not + * use the cache or require any extra API calls. + * + * @param id User snowflake ID to find + * @return const dpp::permission& permissions for the user including overrides on + * the channel where the command was issued. + * @throws dpp::logic_exception on object not found in resolved set + */ + const dpp::permission& get_resolved_permission(snowflake id) const; + + /** + * @brief Get a message associated with the slash command from the resolved list. + * The resolved list contains associated structures for this command and does not + * use the cache or require any extra API calls. + * + * @param id Message snowflake ID to find + * @return const dpp::message& message + * @throws dpp::logic_exception on object not found in resolved set + */ + const dpp::message& get_resolved_message(snowflake id) const; + + /** + * @brief Get an uploaded attachment associated with the slash command from the resolved list. + * The resolved list contains associated structures for this command and does not + * use the cache or require any extra API calls. + * + * @param id Attachment snowflake ID to find + * @return const dpp::attachment& file attachment + * @throws dpp::logic_exception on object not found in resolved set + */ + const dpp::attachment& get_resolved_attachment(snowflake id) const; + + /** + * @brief Get the command interaction object + * + * @throw dpp::logic_exception if the interaction is not for a command + * + * @return command_interaction object + */ + command_interaction get_command_interaction() const; + + /** + * @brief Get the component interaction object + * + * @throw dpp::logic_exception if the interaction is not for a component + * + * @return component_interaction object + */ + component_interaction get_component_interaction() const; + + /** + * @brief Get the autocomplete interaction object + * + * @throw dpp::logic_exception if the interaction is not for an autocomplete + * + * @return autocomplete_interaction object + */ + autocomplete_interaction get_autocomplete_interaction() const; + + /** + * @brief Get the command name for a command interaction + * + * @return std::string command interaction, or empty string if the interaction + * is not for a command. + */ + std::string get_command_name() const; + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return interaction& Reference to self + */ + interaction& fill_from_json(nlohmann::json* j); + + /** + * @brief Build a json string for this object + * + * @param with_id True if to include the ID in the JSON + * @return std::string JSON string + */ + std::string build_json(bool with_id = false) const; +}; + +/** + * @brief helper function to deserialize an interaction from json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param i interaction to be deserialized + */ +void from_json(const nlohmann::json& j, interaction& i); + +/** + * @brief type of permission in the dpp::command_permission class + */ +enum command_permission_type { + /** + * @brief Role permission + * + */ + cpt_role = 1, + /** + * @brief User permission + * + */ + cpt_user = 2, +}; + +/** + * @brief Application command permissions allow you to enable or + * disable commands for specific users or roles within a guild + */ +class DPP_EXPORT command_permission : public json_interface { +public: + snowflake id; //!< the ID of the role or user + command_permission_type type; //!< the type of permission + bool permission; //!< true to allow, false, to disallow + + /** + * @brief Construct a new command permission object + */ + command_permission() = default; + + virtual ~command_permission() = default; + + /** + * @brief Construct a new command permission object + * + * @param id The ID of the role or user + * @param t The permission type + * @param permission True to allow, false, to disallow + */ + command_permission(snowflake id, const command_permission_type t, bool permission); + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return command_permission& Reference to self + */ + command_permission &fill_from_json(nlohmann::json *j); +}; + +/** + * @brief helper function to serialize a command_permission to json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param cp command_permission to be serialized + */ +void to_json(nlohmann::json& j, const command_permission& cp); + +/** + * @brief Returned when fetching the permissions for a command in a guild. + */ +class DPP_EXPORT guild_command_permissions : public json_interface { +public: + snowflake id; //!< the id of the command + snowflake application_id; //!< the id of the application the command belongs to + snowflake guild_id; //!< the id of the guild + std::vector permissions; //!< the permissions for the command in the guild + + /** + * @brief Construct a new guild command permissions object + */ + guild_command_permissions(); + + virtual ~guild_command_permissions() = default; + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return guild_command_permissions& Reference to self + */ + guild_command_permissions &fill_from_json(nlohmann::json *j); + +}; + +/** + * @brief helper function to serialize a guild_command_permissions to json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param gcp guild_command_permissions to be serialized + */ +void to_json(nlohmann::json& j, const guild_command_permissions& gcp); + +/** + * @brief Represents an application command, created by your bot + * either globally, or on a guild. + */ +class DPP_EXPORT slashcommand : public managed, public json_interface { +public: + /** + * @brief Application id (usually matches your bots id) + */ + snowflake application_id; + + /** + * @brief Context menu type, defaults to dpp::ctxm_chat_input + */ + slashcommand_contextmenu_type type; + + /** + * @brief Command name (1-32 chars) + */ + std::string name; + + /** + * @brief Command description (1-100 chars) + */ + std::string description; + + /** + * @brief Command options (parameters) + */ + std::vector options; + + /** + * @brief Whether the command is enabled by default when the app is added to a guild. + * This has no effect as the default_member_permissions value is used instead. + * @deprecated Discord discourage use of this value and instead you should use slashcommand::default_member_permissions. + */ + bool default_permission; + + /** + * @brief command permissions + * @deprecated Discord discourage use of this value and instead you should use default_member_permissions. + */ + std::vector permissions; + + /** + * @brief autoincrementing version identifier updated during substantial record changes + */ + snowflake version; + + /** + * @brief Localisations of command name + */ + std::map name_localizations; + + /** + * @brief Localisations of command description + */ + std::map description_localizations; + + /** + * @brief The default permissions of this command on a guild. + * D++ defaults this to dpp::p_use_application_commands. + * @note You can set it to 0 to disable the command for everyone except admins by default + */ + permission default_member_permissions; + + /** + * @brief True if this command should be allowed in a DM + * D++ defaults this to false. Cannot be set to true in a guild + * command, only a global command. + */ + bool dm_permission; + + /** + * @brief Indicates whether the command is [age-restricted](https://discord.com/developers/docs/interactions/application-commands#agerestricted-commands). + * Defaults to false + */ + bool nsfw; + + /** + * @brief Construct a new slashcommand object + */ + slashcommand(); + + /** + * @brief Construct a new slashcommand object + * + * @param _name Command name + * @param _description Command description + * @param _application_id Application id (usually the bot's user id) + */ + slashcommand(const std::string &_name, const std::string &_description, const dpp::snowflake _application_id); + + /** + * @brief Destroy the slashcommand object + */ + virtual ~slashcommand(); + + /** + * @brief Add a localisation for this slash command + * @see https://discord.com/developers/docs/reference#locales + * @param language Name of language, see the list of locales linked to above. + * @param _name name of slash command in the specified language + * @param _description description of slash command in the specified language + * @return slashcommand& reference to self for fluent chaining + */ + slashcommand& add_localization(const std::string& language, const std::string& _name, const std::string& _description); + + /** + * @brief Set the dm permission for the command + * + * @param dm true to allow this command in dms + * @return slashcommand& reference to self for chaining of calls + */ + slashcommand& set_dm_permission(bool dm); + + /** + * @brief Set whether the command should be age-restricted or not + * + * @param is_nsfw true if the command should be age-restricted + * @return slashcommand& reference to self for chaining of calls + */ + slashcommand& set_nsfw(bool is_nsfw); + + /** + * @brief Set the default permissions of the slash command + * + * @param defaults default permissions to set. This is a permission bitmask of bits from dpp::permissions + * @note You can set it to 0 to disable the command for everyone except admins by default + * + * @return slashcommand& reference to self for chaining of calls + */ + slashcommand& set_default_permissions(uint64_t defaults); + + /** + * @brief Add an option (parameter) + * + * @param o option (parameter) to add + * @return slashcommand& reference to self for chaining of calls + */ + slashcommand& add_option(const command_option &o); + + /** + * @brief Set the type of the slash command (only for context menu entries) + * + * @param _type Type of context menu entry this command represents + * @note If the type is dpp::ctxm_chat_input, the command name will be set to lowercase. + * @return slashcommand& reference to self for chaining of calls + */ + slashcommand& set_type(slashcommand_contextmenu_type _type); + + /** + * @brief Set the name of the command + * + * @param n name of command + * @note The maximum length of a command name is 32 UTF-8 codepoints. + * If your command name is longer than this, it will be truncated. + * The command name will be set to lowercase when the type is the default dpp::ctxm_chat_input. + * @return slashcommand& reference to self for chaining of calls + */ + slashcommand& set_name(const std::string &n); + + /** + * @brief Set the description of the command + * + * @param d description + * @note The maximum length of a command description is 100 UTF-8 codepoints. + * If your command description is longer than this, it will be truncated. + * @return slashcommand& reference to self for chaining of calls + */ + slashcommand& set_description(const std::string &d); + + /** + * @brief Set the application id of the command + * + * @param i application id + * @return slashcommand& reference to self for chaining of calls + */ + slashcommand& set_application_id(snowflake i); + + /** + * @brief Adds a permission to the command + * + * @param p permission to add + * @return slashcommand& reference to self for chaining of calls + * @deprecated Discord discourage use of this value and instead you should use default_member_permissions. + */ + slashcommand& add_permission(const command_permission& p); + + /** + * @brief Disable default permissions, command will be unusable unless + * permissions are overridden with add_permission and + * dpp::guild_command_edit_permissions + * + * @return slashcommand& reference to self for chaining of calls + * @deprecated Discord discourage use of this value and instead you should use default_member_permissions. + */ + slashcommand& disable_default_permissions(); + + /** + * @brief Return a ping/mention for the slash command + * + * @return std::string mention. e.g. `` + * @note If you want a mention for a subcommand or subcommand group, you can use dpp::utility::slashcommand_mention + */ + std::string get_mention() const; + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return slashcommand& Reference to self + */ + slashcommand& fill_from_json(nlohmann::json* j); + + /** + * @brief Build a json string for this object + * + * @param with_id True if to include the ID in the JSON + * @return std::string JSON string + */ + std::string build_json(bool with_id = false) const; +}; + +/** + * @brief helper function to serialize a slashcommand to json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param cmd slashcommand to be serialized + */ +void to_json(nlohmann::json& j, const slashcommand& cmd); + +/** + * @brief A group of application slash commands + */ +typedef std::unordered_map slashcommand_map; + +/** + * @brief A group of guild command permissions + */ +typedef std::unordered_map guild_command_permissions_map; + +}; diff --git a/3rdParty/dpp/application.h b/3rdParty/dpp/application.h index 3d23c8a8d2..f84ff4be0d 100644 --- a/3rdParty/dpp/application.h +++ b/3rdParty/dpp/application.h @@ -1,162 +1,162 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief status of a member of a team who maintain a bot/application - */ -enum team_member_status : uint8_t { - /// User was invited to the team - tms_invited = 1, - /// User has accepted membership onto the team - tms_accepted = 2 -}; - -/** - * @brief Flags for a bot or application - */ -enum application_flags : uint32_t { - /// Has gateway presence intent - apf_gateway_presence = (1 << 12), - /// Has gateway presence intent for <100 guilds - apf_gateway_presence_limited = (1 << 13), - /// Has guild members intent - apf_gateway_guild_members = (1 << 14), - /// Has guild members intent for <100 guilds - apf_gateway_guild_members_limited = (1 << 15), - /// Verification is pending - apf_verification_pending_guild_limit = (1 << 16), - /// Embedded - apf_embedded = (1 << 17), - /// Has approval for message content - apf_gateway_message_content = (1 << 18), - /// Has message content, but <100 guilds - apf_gateway_message_content_limited = (1 << 19), - /// Indicates if the app has registered global application commands - apf_application_command_badge = (1 << 23) -}; - -/** - * @brief Represents the settings for the bot/application's in-app authorization link - */ -struct DPP_EXPORT application_install_params { - permission permissions; //!< A bitmask of dpp::permissions to request for the bot role - std::vector scopes; //!< The [scopes](https://discord.com/developers/docs/topics/oauth2#shared-resources-oauth2-scopes) as strings to add the application to the server with -}; - -/** - * @brief Represents a team member on a team who maintain a bot/application - */ -class DPP_EXPORT team_member { -public: - team_member_status membership_state; //!< the user's membership state on the team - std::string permissions; //!< will always be [""] - snowflake team_id; //!< the id of the parent team of which they are a member - user member_user; //!< the avatar, discriminator, id, and username of the user -}; - -/** - * @brief Represents a team of users who maintain a bot/application - */ -class DPP_EXPORT app_team { -public: - utility::iconhash icon; //!< a hash of the image of the team's icon (may be empty) - snowflake id; //!< the unique id of the team - std::vector members; //!< the members of the team - std::string name; //!< the name of the team - snowflake owner_user_id; //!< the user id of the current team owner -}; - -/** - * @brief The application class represents details of a bot application - */ -class DPP_EXPORT application : public managed, public json_interface { -public: - std::string name; //!< the name of the app - utility::iconhash icon; //!< the icon hash of the app (may be empty) - std::string description; //!< the description of the app - std::string rpc_origins; //!< Optional: an array of rpc origin urls, if rpc is enabled - bool bot_public; //!< when false only app owner can join the app's bot to guilds - bool bot_require_code_grant; //!< when true the app's bot will only join upon completion of the full oauth2 code grant flow - std::string terms_of_service_url; //!< Optional: the url of the app's terms of service - std::string privacy_policy_url; //!< Optional: the url of the app's privacy policy - user owner; //!< Optional: partial user object containing info on the owner of the application - std::string summary; //!< if this application is a game sold on Discord, this field will be the summary field for the store page of its primary sku @deprecated Will be removed in v11 - std::string verify_key; //!< the hex encoded key for verification in interactions and the GameSDK's GetTicket - app_team team; //!< if the application belongs to a team, this will be a list of the members of that team (may be empty) - snowflake guild_id; //!< Optional: if this application is a game sold on Discord, this field will be the guild to which it has been linked - snowflake primary_sku_id; //!< Optional: if this application is a game sold on Discord, this field will be the id of the "Game SKU" that is created, if exists - std::string slug; //!< Optional: if this application is a game sold on Discord, this field will be the URL slug that links to the store page - utility::iconhash cover_image; //!< Optional: the application's default rich presence invite cover image hash - uint32_t flags; //!< Optional: the application's public flags - std::vector tags; //!< Up to 5 tags describing the content and functionality of the application - application_install_params install_params; //!< Settings for the application's default in-app authorization link, if enabled - std::string custom_install_url; //!< The application's default custom authorization link, if enabled - std::string role_connections_verification_url; //!< The application's role connection verification entry point, which when configured will render the app as a verification method in the guild role verification configuration - - /** Constructor */ - application(); - - /** Destructor */ - ~application(); - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - application& fill_from_json(nlohmann::json* j); - - /** - * @brief Get the applications cover image url if they have one, otherwise returns an empty string - * - * @param size The size of the cover image in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized cover image is returned. - * @return std::string cover image url or empty string - */ - std::string get_cover_image_url(uint16_t size = 0) const; - - /** - * @brief Get the applications icon url if they have one, otherwise returns an empty string - * - * @param size The size of the icon in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized icon is returned. - * @return std::string icon url or empty string - */ - std::string get_icon_url(uint16_t size = 0) const; -}; - -/** A group of applications. - * This is not currently ever sent by Discord API but the DPP standard setup for - * objects that can be received by REST has the possibility for this, so this exists. - * Don't ever expect to see one at present. - */ -typedef std::unordered_map application_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief status of a member of a team who maintain a bot/application + */ +enum team_member_status : uint8_t { + /// User was invited to the team + tms_invited = 1, + /// User has accepted membership onto the team + tms_accepted = 2 +}; + +/** + * @brief Flags for a bot or application + */ +enum application_flags : uint32_t { + /// Has gateway presence intent + apf_gateway_presence = (1 << 12), + /// Has gateway presence intent for <100 guilds + apf_gateway_presence_limited = (1 << 13), + /// Has guild members intent + apf_gateway_guild_members = (1 << 14), + /// Has guild members intent for <100 guilds + apf_gateway_guild_members_limited = (1 << 15), + /// Verification is pending + apf_verification_pending_guild_limit = (1 << 16), + /// Embedded + apf_embedded = (1 << 17), + /// Has approval for message content + apf_gateway_message_content = (1 << 18), + /// Has message content, but <100 guilds + apf_gateway_message_content_limited = (1 << 19), + /// Indicates if the app has registered global application commands + apf_application_command_badge = (1 << 23) +}; + +/** + * @brief Represents the settings for the bot/application's in-app authorization link + */ +struct DPP_EXPORT application_install_params { + permission permissions; //!< A bitmask of dpp::permissions to request for the bot role + std::vector scopes; //!< The [scopes](https://discord.com/developers/docs/topics/oauth2#shared-resources-oauth2-scopes) as strings to add the application to the server with +}; + +/** + * @brief Represents a team member on a team who maintain a bot/application + */ +class DPP_EXPORT team_member { +public: + team_member_status membership_state; //!< the user's membership state on the team + std::string permissions; //!< will always be [""] + snowflake team_id; //!< the id of the parent team of which they are a member + user member_user; //!< the avatar, discriminator, id, and username of the user +}; + +/** + * @brief Represents a team of users who maintain a bot/application + */ +class DPP_EXPORT app_team { +public: + utility::iconhash icon; //!< a hash of the image of the team's icon (may be empty) + snowflake id; //!< the unique id of the team + std::vector members; //!< the members of the team + std::string name; //!< the name of the team + snowflake owner_user_id; //!< the user id of the current team owner +}; + +/** + * @brief The application class represents details of a bot application + */ +class DPP_EXPORT application : public managed, public json_interface { +public: + std::string name; //!< the name of the app + utility::iconhash icon; //!< the icon hash of the app (may be empty) + std::string description; //!< the description of the app + std::string rpc_origins; //!< Optional: an array of rpc origin urls, if rpc is enabled + bool bot_public; //!< when false only app owner can join the app's bot to guilds + bool bot_require_code_grant; //!< when true the app's bot will only join upon completion of the full oauth2 code grant flow + std::string terms_of_service_url; //!< Optional: the url of the app's terms of service + std::string privacy_policy_url; //!< Optional: the url of the app's privacy policy + user owner; //!< Optional: partial user object containing info on the owner of the application + std::string summary; //!< if this application is a game sold on Discord, this field will be the summary field for the store page of its primary sku @deprecated Will be removed in v11 + std::string verify_key; //!< the hex encoded key for verification in interactions and the GameSDK's GetTicket + app_team team; //!< if the application belongs to a team, this will be a list of the members of that team (may be empty) + snowflake guild_id; //!< Optional: if this application is a game sold on Discord, this field will be the guild to which it has been linked + snowflake primary_sku_id; //!< Optional: if this application is a game sold on Discord, this field will be the id of the "Game SKU" that is created, if exists + std::string slug; //!< Optional: if this application is a game sold on Discord, this field will be the URL slug that links to the store page + utility::iconhash cover_image; //!< Optional: the application's default rich presence invite cover image hash + uint32_t flags; //!< Optional: the application's public flags + std::vector tags; //!< Up to 5 tags describing the content and functionality of the application + application_install_params install_params; //!< Settings for the application's default in-app authorization link, if enabled + std::string custom_install_url; //!< The application's default custom authorization link, if enabled + std::string role_connections_verification_url; //!< The application's role connection verification entry point, which when configured will render the app as a verification method in the guild role verification configuration + + /** Constructor */ + application(); + + /** Destructor */ + ~application(); + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + application& fill_from_json(nlohmann::json* j); + + /** + * @brief Get the applications cover image url if they have one, otherwise returns an empty string + * + * @param size The size of the cover image in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized cover image is returned. + * @return std::string cover image url or empty string + */ + std::string get_cover_image_url(uint16_t size = 0) const; + + /** + * @brief Get the applications icon url if they have one, otherwise returns an empty string + * + * @param size The size of the icon in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized icon is returned. + * @return std::string icon url or empty string + */ + std::string get_icon_url(uint16_t size = 0) const; +}; + +/** A group of applications. + * This is not currently ever sent by Discord API but the DPP standard setup for + * objects that can be received by REST has the possibility for this, so this exists. + * Don't ever expect to see one at present. + */ +typedef std::unordered_map application_map; + +}; diff --git a/3rdParty/dpp/auditlog.h b/3rdParty/dpp/auditlog.h index abcde0a54f..49ecbedfba 100644 --- a/3rdParty/dpp/auditlog.h +++ b/3rdParty/dpp/auditlog.h @@ -1,214 +1,214 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Defines types of audit log entry - */ -enum audit_type { - /// Guild update - aut_guild_update = 1, - /// Channel create - aut_channel_create = 10, - /// Channel update - aut_channel_update = 11, - /// Channel delete - aut_channel_delete = 12, - /// Channel overwrite create - aut_channel_overwrite_create = 13, - /// Channel overwrite update - aut_channel_overwrite_update = 14, - /// Channel overwrite delete - aut_channel_overwrite_delete = 15, - /// Channel member kick - aut_member_kick = 20, - /// Channel member prune - aut_member_prune = 21, - /// Channel member ban add - aut_member_ban_add = 22, - /// Channel member ban remove - aut_member_ban_remove = 23, - /// Guild member update - aut_member_update = 24, - /// Guild member role update - aut_member_role_update = 25, - /// Guild member move - aut_member_move = 26, - /// Guild member voice disconnect - aut_member_disconnect = 27, - /// Guild bot add - aut_bot_add = 28, - /// Guild role create - aut_role_create = 30, - /// Guild role update - aut_role_update = 31, - /// Guild role delete - aut_role_delete = 32, - /// Guild invite create - aut_invite_create = 40, - /// Guild invite update - aut_invite_update = 41, - /// Guild invite delete - aut_invite_delete = 42, - /// Guild webhook create - aut_webhook_create = 50, - /// Guild webhook update - aut_webhook_update = 51, - /// Guild webhook delete - aut_webhook_delete = 52, - /// Guild emoji create - aut_emoji_create = 60, - /// Guild emoji update - aut_emoji_update = 61, - /// Guild emoji delete - aut_emoji_delete = 62, - /// Guild message delete - aut_message_delete = 72, - /// Guild message bulk delete - aut_message_bulk_delete = 73, - /// Guild message pin - aut_message_pin = 74, - /// Guild message unpin - aut_message_unpin = 75, - /// Guild integration create - aut_integration_create = 80, - /// Guild integration update - aut_integration_update = 81, - /// Guild integration delete - aut_integration_delete = 82, - /// Stage instance create - aut_stage_instance_create = 83, - /// Stage instance update - aut_stage_instance_update = 84, - /// stage instance delete - aut_stage_instance_delete = 85, - /// Sticker create - aut_sticker_create = 90, - /// Sticker update - aut_sticker_update = 91, - /// Sticker delete - aut_sticker_delete = 92, - /// Scheduled event creation - aut_guild_scheduled_event_create = 100, - /// Scheduled event update - aut_guild_scheduled_event_update = 101, - /// Scheduled event deletion - aut_guild_scheduled_event_delete = 102, - /// Thread create - aut_thread_create = 110, - /// Thread update - aut_thread_update = 111, - /// Thread delete - aut_thread_delete = 112, - /// Application command permissions update - aut_appcommand_permission_update = 121, - /// Auto moderation rule creation - aut_automod_rule_create = 140, - /// Auto moderation rule update - aut_automod_rule_update = 141, - /// Auto moderation rule deletion - aut_automod_rule_delete = 142, - /// Message was blocked by Auto Moderation - aut_automod_block_message = 143, - /// Message was flagged by Auto Moderation - aut_automod_flag_to_channel = 144, - /// Member was timed out by Auto Moderation - aut_automod_user_communication_disabled = 145, -}; - -/** - * @brief Defines audit log changes - */ -struct DPP_EXPORT audit_change { - /// Optional: Serialised new value of the change, e.g. for nicknames, the new nickname - std::string new_value; - /// Optional: Serialised old value of the change, e.g. for nicknames, the old nickname - std::string old_value; - /** - * The property name that was changed, e.g. `nick` for nickname changes - * @note For dpp::aut_appcommand_permission_update updates the key is the id of the user, channel, role, or a permission constant that was updated instead of an actual property name - */ - std::string key; -}; - -/** - * @brief Extra information for an audit log entry - */ -struct DPP_EXPORT audit_extra { - std::string automod_rule_name; //!< Name of the Auto Moderation rule that was triggered - std::string automod_rule_trigger_type; //!< Trigger type of the Auto Moderation rule that was triggered - std::string delete_member_days; //!< number of days after which inactive members were kicked - std::string members_removed; //!< number of members removed by the prune - snowflake channel_id; //!< channel in which the entities were targeted - snowflake message_id; //!< id of the message that was targeted - std::string count; //!< number of entities that were targeted - snowflake id; //!< id of the overwritten entity - std::string type; //!< type of overwritten entity - "0" for "role" or "1" for "member" - std::string role_name; //!< name of the role if type is "0" (not present if type is "1") - snowflake application_id; //!< ID of the app whose permissions were targeted -}; - -/** - * @brief An individual audit log entry - */ -struct DPP_EXPORT audit_entry { - snowflake id; //!< id of the entry - /** - * ID of the affected entity (webhook, user, role, etc.) (may be empty) - * @note For dpp::audit_type::aut_appcommand_permission_update updates, it's the command ID or the app ID - */ - snowflake target_id; - std::vector changes; //!< Optional: changes made to the target_id - snowflake user_id; //!< the user or app that made the changes (may be empty) - audit_type type; //!< type of action that occurred - std::optional extra; //!< Optional: additional info for certain action types - std::string reason; //!< Optional: the reason for the change (1-512 characters) -}; - -/** - * @brief The auditlog class represents the audit log entries of a guild. - */ -class DPP_EXPORT auditlog : public json_interface { -public: - std::vector entries; //!< Audit log entries - - /** Constructor */ - auditlog() = default; - - /** Destructor */ - virtual ~auditlog() = default; - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - auditlog& fill_from_json(nlohmann::json* j); -}; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Defines types of audit log entry + */ +enum audit_type { + /// Guild update + aut_guild_update = 1, + /// Channel create + aut_channel_create = 10, + /// Channel update + aut_channel_update = 11, + /// Channel delete + aut_channel_delete = 12, + /// Channel overwrite create + aut_channel_overwrite_create = 13, + /// Channel overwrite update + aut_channel_overwrite_update = 14, + /// Channel overwrite delete + aut_channel_overwrite_delete = 15, + /// Channel member kick + aut_member_kick = 20, + /// Channel member prune + aut_member_prune = 21, + /// Channel member ban add + aut_member_ban_add = 22, + /// Channel member ban remove + aut_member_ban_remove = 23, + /// Guild member update + aut_member_update = 24, + /// Guild member role update + aut_member_role_update = 25, + /// Guild member move + aut_member_move = 26, + /// Guild member voice disconnect + aut_member_disconnect = 27, + /// Guild bot add + aut_bot_add = 28, + /// Guild role create + aut_role_create = 30, + /// Guild role update + aut_role_update = 31, + /// Guild role delete + aut_role_delete = 32, + /// Guild invite create + aut_invite_create = 40, + /// Guild invite update + aut_invite_update = 41, + /// Guild invite delete + aut_invite_delete = 42, + /// Guild webhook create + aut_webhook_create = 50, + /// Guild webhook update + aut_webhook_update = 51, + /// Guild webhook delete + aut_webhook_delete = 52, + /// Guild emoji create + aut_emoji_create = 60, + /// Guild emoji update + aut_emoji_update = 61, + /// Guild emoji delete + aut_emoji_delete = 62, + /// Guild message delete + aut_message_delete = 72, + /// Guild message bulk delete + aut_message_bulk_delete = 73, + /// Guild message pin + aut_message_pin = 74, + /// Guild message unpin + aut_message_unpin = 75, + /// Guild integration create + aut_integration_create = 80, + /// Guild integration update + aut_integration_update = 81, + /// Guild integration delete + aut_integration_delete = 82, + /// Stage instance create + aut_stage_instance_create = 83, + /// Stage instance update + aut_stage_instance_update = 84, + /// stage instance delete + aut_stage_instance_delete = 85, + /// Sticker create + aut_sticker_create = 90, + /// Sticker update + aut_sticker_update = 91, + /// Sticker delete + aut_sticker_delete = 92, + /// Scheduled event creation + aut_guild_scheduled_event_create = 100, + /// Scheduled event update + aut_guild_scheduled_event_update = 101, + /// Scheduled event deletion + aut_guild_scheduled_event_delete = 102, + /// Thread create + aut_thread_create = 110, + /// Thread update + aut_thread_update = 111, + /// Thread delete + aut_thread_delete = 112, + /// Application command permissions update + aut_appcommand_permission_update = 121, + /// Auto moderation rule creation + aut_automod_rule_create = 140, + /// Auto moderation rule update + aut_automod_rule_update = 141, + /// Auto moderation rule deletion + aut_automod_rule_delete = 142, + /// Message was blocked by Auto Moderation + aut_automod_block_message = 143, + /// Message was flagged by Auto Moderation + aut_automod_flag_to_channel = 144, + /// Member was timed out by Auto Moderation + aut_automod_user_communication_disabled = 145, +}; + +/** + * @brief Defines audit log changes + */ +struct DPP_EXPORT audit_change { + /// Optional: Serialised new value of the change, e.g. for nicknames, the new nickname + std::string new_value; + /// Optional: Serialised old value of the change, e.g. for nicknames, the old nickname + std::string old_value; + /** + * The property name that was changed, e.g. `nick` for nickname changes + * @note For dpp::aut_appcommand_permission_update updates the key is the id of the user, channel, role, or a permission constant that was updated instead of an actual property name + */ + std::string key; +}; + +/** + * @brief Extra information for an audit log entry + */ +struct DPP_EXPORT audit_extra { + std::string automod_rule_name; //!< Name of the Auto Moderation rule that was triggered + std::string automod_rule_trigger_type; //!< Trigger type of the Auto Moderation rule that was triggered + std::string delete_member_days; //!< number of days after which inactive members were kicked + std::string members_removed; //!< number of members removed by the prune + snowflake channel_id; //!< channel in which the entities were targeted + snowflake message_id; //!< id of the message that was targeted + std::string count; //!< number of entities that were targeted + snowflake id; //!< id of the overwritten entity + std::string type; //!< type of overwritten entity - "0" for "role" or "1" for "member" + std::string role_name; //!< name of the role if type is "0" (not present if type is "1") + snowflake application_id; //!< ID of the app whose permissions were targeted +}; + +/** + * @brief An individual audit log entry + */ +struct DPP_EXPORT audit_entry { + snowflake id; //!< id of the entry + /** + * ID of the affected entity (webhook, user, role, etc.) (may be empty) + * @note For dpp::audit_type::aut_appcommand_permission_update updates, it's the command ID or the app ID + */ + snowflake target_id; + std::vector changes; //!< Optional: changes made to the target_id + snowflake user_id; //!< the user or app that made the changes (may be empty) + audit_type type; //!< type of action that occurred + std::optional extra; //!< Optional: additional info for certain action types + std::string reason; //!< Optional: the reason for the change (1-512 characters) +}; + +/** + * @brief The auditlog class represents the audit log entries of a guild. + */ +class DPP_EXPORT auditlog : public json_interface { +public: + std::vector entries; //!< Audit log entries + + /** Constructor */ + auditlog() = default; + + /** Destructor */ + virtual ~auditlog() = default; + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + auditlog& fill_from_json(nlohmann::json* j); +}; + +}; diff --git a/3rdParty/dpp/automod.h b/3rdParty/dpp/automod.h index 12a4afcdc3..f04dba4230 100644 --- a/3rdParty/dpp/automod.h +++ b/3rdParty/dpp/automod.h @@ -1,363 +1,363 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Possible types of preset filter lists - */ -enum automod_preset_type : uint8_t { - /** - * @brief Strong swearing - */ - amod_preset_profanity = 1, - /** - * @brief Sexual phrases and words - */ - amod_preset_sexual_content = 2, - /** - * @brief Racial and other slurs, hate speech - */ - amod_preset_slurs = 3, -}; - -/** - * @brief Action types to perform on filtering - */ -enum automod_action_type : uint8_t { - /** - * @brief Block the message - */ - amod_action_block_message = 1, - /** - * @brief Send an alert to a given channel - */ - amod_action_send_alert = 2, - /** - * @brief time out the user - */ - amod_action_timeout = 3, -}; - -/** - * @brief Event types, only message send is currently supported - */ -enum automod_event_type : uint8_t { - /** - * @brief Trigger on message send or edit - */ - amod_message_send = 1, -}; - -/** - * @brief Types of moderation to trigger - */ -enum automod_trigger_type : uint8_t { - /** - * @brief Check if content contains words from a user defined list of keywords - */ - amod_type_keyword = 1, - /** - * @brief Harmful/malware links - * @deprecated Removed by Discord - */ - amod_type_harmful_link = 2, - /** - * @brief Check if content represents generic spam - */ - amod_type_spam = 3, - /** - * @brief Check if content contains words from discord pre-defined wordsets - */ - amod_type_keyword_preset = 4, - /** - * @brief Check if content contains more mentions than allowed - */ - amod_type_mention_spam = 5, -}; - -/** - * @brief Metadata associated with an automod action - */ -struct DPP_EXPORT automod_metadata : public json_interface { - /** - * @brief @brief Substrings which will be searched for in content (Maximum of 1000). - * - * Each keyword can be a phrase which contains multiple words. - * All keywords are case insensitive and can be up to 30 characters. - * - * Wildcard symbols (`*`) can be used to customize how each keyword will be matched. - * - * **Examples for the `*` wildcard symbol:** - * - * Prefix - word must start with the keyword - * - * | keyword | matches | - * |----------|-------------------------------------| - * | cat* | catch, Catapult, CAttLE | - * | the mat* | the matrix | - * - * Suffix - word must end with the keyword - * - * | keyword | matches | - * |----------|--------------------------| - * | *cat | wildcat, copyCat | - * | *the mat | breathe mat | - * - * Anywhere - keyword can appear anywhere in the content - * - * | keyword | matches | - * |-----------|-----------------------------| - * | \*cat* | location, eduCation | - * | \*the mat* | breathe matter | - * - * Whole Word - keyword is a full word or phrase and must be surrounded by whitespace at the beginning and end - * - * | keyword | matches | - * |---------|-------------| - * | cat | Cat | - * | the mat | the mat | - * - */ - std::vector keywords; - - /** - * @brief Regular expression patterns which will be matched against content (Maximum of 10). - * - * Only Rust flavored regex is currently supported, which can be tested in online editors such as [Rustexp](https://rustexp.lpil.uk/). - * Each regex pattern can be up to 260 characters. - */ - std::vector regex_patterns; - - /** - * @brief Preset keyword list types to moderate - * @see automod_preset_type - */ - std::vector presets; - - /** - * @brief Substrings which should not trigger the rule. - * - * Each keyword can be a phrase which contains multiple words. - * All keywords are case insensitive and can be up to 30 characters. - * - * Wildcard symbols (`*`) can be used to customize how each keyword will be matched. - * - * **Examples for the `*` wildcard symbol:** - * - * Prefix - word must start with the keyword - * - * | keyword | matches | - * |----------|-------------------------------------| - * | cat* | catch, Catapult, CAttLE | - * | the mat* | the matrix | - * - * Suffix - word must end with the keyword - * - * | keyword | matches | - * |----------|--------------------------| - * | *cat | wildcat, copyCat | - * | *the mat | breathe mat | - * - * Anywhere - keyword can appear anywhere in the content - * - * | keyword | matches | - * |-----------|-----------------------------| - * | \*cat* | location, eduCation | - * | \*the mat* | breathe matter | - * - * Whole Word - keyword is a full word or phrase and must be surrounded by whitespace at the beginning and end - * - * | keyword | matches | - * |---------|-------------| - * | cat | Cat | - * | the mat | the mat | - * - */ - std::vector allow_list; - - /** - * @brief Total number of unique role and user mentions allowed per message (Maximum of 50) - */ - uint8_t mention_total_limit; - - /** - * @brief Construct a new automod metadata object - */ - automod_metadata(); - - /** - * @brief Destroy the automod metadata object - */ - virtual ~automod_metadata(); - - /** - * @brief Fill object properties from JSON - * - * @param j JSON to fill from - * @return automod_metadata& Reference to self - */ - automod_metadata& fill_from_json(nlohmann::json* j); - - /** - * @brief Build a json string for this object - * - * @return std::string JSON string - */ - virtual std::string build_json(bool with_id = false) const; - -}; - -/** - * @brief Represents an automod action - */ -struct DPP_EXPORT automod_action : public json_interface { - /** - * @brief Type of action to take - */ - automod_action_type type; - - /** - * @brief Channel ID, for type dpp::amod_action_send_alert - */ - snowflake channel_id; - - /** - * @brief Timeout duration in seconds (Maximum of 2419200), for dpp::amod_action_timeout - * - */ - int32_t duration_seconds; - - /** - * @brief Construct a new automod action object - */ - automod_action(); - - /** - * @brief Destroy the automod action object - */ - virtual ~automod_action(); - - /** - * @brief Fill object properties from JSON - * - * @param j JSON to fill from - * @return automod_action& Reference to self - */ - automod_action& fill_from_json(nlohmann::json* j); - - /** - * @brief Build a json string for this object - * - * @return std::string JSON string - */ - virtual std::string build_json(bool with_id = false) const; -}; - -/** - * @brief Represents an automod rule - */ -class DPP_EXPORT automod_rule : public managed, public json_interface { -public: - /** - * @brief the id of this rule - */ - snowflake id; - /** - * @brief the guild which this rule belongs to - */ - snowflake guild_id; - /** - * @brief the rule name - */ - std::string name; - /** - * @brief The user which first created this rule - */ - snowflake creator_id; - /** - * @brief The rule event type - */ - automod_event_type event_type; - /** - * @brief The rule trigger type - */ - automod_trigger_type trigger_type; - /** - * @brief The rule trigger metadata - */ - automod_metadata trigger_metadata; - /** - * @brief the actions which will execute when the rule is triggered - */ - std::vector actions; - /** - * @brief Whether the rule is enabled - */ - bool enabled; - /** - * @brief the role ids that should not be affected by the rule (Maximum of 20) - */ - std::vector exempt_roles; - /** - * @brief the channel ids that should not be affected by the rule (Maximum of 50) - */ - std::vector exempt_channels; - - /** - * @brief Construct a new automod rule object - */ - automod_rule(); - - /** - * @brief Destroy the automod rule object - */ - virtual ~automod_rule(); - - /** - * @brief Fill object properties from JSON - * - * @param j JSON to fill from - * @return automod_rule& Reference to self - */ - automod_rule& fill_from_json(nlohmann::json* j); - - /** - * @brief Build a json string for this object - * - * @return std::string JSON string - */ - virtual std::string build_json(bool with_id = false) const; -}; - -/** A group of automod rules. - */ -typedef std::unordered_map automod_rule_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Possible types of preset filter lists + */ +enum automod_preset_type : uint8_t { + /** + * @brief Strong swearing + */ + amod_preset_profanity = 1, + /** + * @brief Sexual phrases and words + */ + amod_preset_sexual_content = 2, + /** + * @brief Racial and other slurs, hate speech + */ + amod_preset_slurs = 3, +}; + +/** + * @brief Action types to perform on filtering + */ +enum automod_action_type : uint8_t { + /** + * @brief Block the message + */ + amod_action_block_message = 1, + /** + * @brief Send an alert to a given channel + */ + amod_action_send_alert = 2, + /** + * @brief time out the user + */ + amod_action_timeout = 3, +}; + +/** + * @brief Event types, only message send is currently supported + */ +enum automod_event_type : uint8_t { + /** + * @brief Trigger on message send or edit + */ + amod_message_send = 1, +}; + +/** + * @brief Types of moderation to trigger + */ +enum automod_trigger_type : uint8_t { + /** + * @brief Check if content contains words from a user defined list of keywords + */ + amod_type_keyword = 1, + /** + * @brief Harmful/malware links + * @deprecated Removed by Discord + */ + amod_type_harmful_link = 2, + /** + * @brief Check if content represents generic spam + */ + amod_type_spam = 3, + /** + * @brief Check if content contains words from discord pre-defined wordsets + */ + amod_type_keyword_preset = 4, + /** + * @brief Check if content contains more mentions than allowed + */ + amod_type_mention_spam = 5, +}; + +/** + * @brief Metadata associated with an automod action + */ +struct DPP_EXPORT automod_metadata : public json_interface { + /** + * @brief @brief Substrings which will be searched for in content (Maximum of 1000). + * + * Each keyword can be a phrase which contains multiple words. + * All keywords are case insensitive and can be up to 30 characters. + * + * Wildcard symbols (`*`) can be used to customize how each keyword will be matched. + * + * **Examples for the `*` wildcard symbol:** + * + * Prefix - word must start with the keyword + * + * | keyword | matches | + * |----------|-------------------------------------| + * | cat* | catch, Catapult, CAttLE | + * | the mat* | the matrix | + * + * Suffix - word must end with the keyword + * + * | keyword | matches | + * |----------|--------------------------| + * | *cat | wildcat, copyCat | + * | *the mat | breathe mat | + * + * Anywhere - keyword can appear anywhere in the content + * + * | keyword | matches | + * |-----------|-----------------------------| + * | \*cat* | location, eduCation | + * | \*the mat* | breathe matter | + * + * Whole Word - keyword is a full word or phrase and must be surrounded by whitespace at the beginning and end + * + * | keyword | matches | + * |---------|-------------| + * | cat | Cat | + * | the mat | the mat | + * + */ + std::vector keywords; + + /** + * @brief Regular expression patterns which will be matched against content (Maximum of 10). + * + * Only Rust flavored regex is currently supported, which can be tested in online editors such as [Rustexp](https://rustexp.lpil.uk/). + * Each regex pattern can be up to 260 characters. + */ + std::vector regex_patterns; + + /** + * @brief Preset keyword list types to moderate + * @see automod_preset_type + */ + std::vector presets; + + /** + * @brief Substrings which should not trigger the rule. + * + * Each keyword can be a phrase which contains multiple words. + * All keywords are case insensitive and can be up to 30 characters. + * + * Wildcard symbols (`*`) can be used to customize how each keyword will be matched. + * + * **Examples for the `*` wildcard symbol:** + * + * Prefix - word must start with the keyword + * + * | keyword | matches | + * |----------|-------------------------------------| + * | cat* | catch, Catapult, CAttLE | + * | the mat* | the matrix | + * + * Suffix - word must end with the keyword + * + * | keyword | matches | + * |----------|--------------------------| + * | *cat | wildcat, copyCat | + * | *the mat | breathe mat | + * + * Anywhere - keyword can appear anywhere in the content + * + * | keyword | matches | + * |-----------|-----------------------------| + * | \*cat* | location, eduCation | + * | \*the mat* | breathe matter | + * + * Whole Word - keyword is a full word or phrase and must be surrounded by whitespace at the beginning and end + * + * | keyword | matches | + * |---------|-------------| + * | cat | Cat | + * | the mat | the mat | + * + */ + std::vector allow_list; + + /** + * @brief Total number of unique role and user mentions allowed per message (Maximum of 50) + */ + uint8_t mention_total_limit; + + /** + * @brief Construct a new automod metadata object + */ + automod_metadata(); + + /** + * @brief Destroy the automod metadata object + */ + virtual ~automod_metadata(); + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return automod_metadata& Reference to self + */ + automod_metadata& fill_from_json(nlohmann::json* j); + + /** + * @brief Build a json string for this object + * + * @return std::string JSON string + */ + virtual std::string build_json(bool with_id = false) const; + +}; + +/** + * @brief Represents an automod action + */ +struct DPP_EXPORT automod_action : public json_interface { + /** + * @brief Type of action to take + */ + automod_action_type type; + + /** + * @brief Channel ID, for type dpp::amod_action_send_alert + */ + snowflake channel_id; + + /** + * @brief Timeout duration in seconds (Maximum of 2419200), for dpp::amod_action_timeout + * + */ + int32_t duration_seconds; + + /** + * @brief Construct a new automod action object + */ + automod_action(); + + /** + * @brief Destroy the automod action object + */ + virtual ~automod_action(); + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return automod_action& Reference to self + */ + automod_action& fill_from_json(nlohmann::json* j); + + /** + * @brief Build a json string for this object + * + * @return std::string JSON string + */ + virtual std::string build_json(bool with_id = false) const; +}; + +/** + * @brief Represents an automod rule + */ +class DPP_EXPORT automod_rule : public managed, public json_interface { +public: + /** + * @brief the id of this rule + */ + snowflake id; + /** + * @brief the guild which this rule belongs to + */ + snowflake guild_id; + /** + * @brief the rule name + */ + std::string name; + /** + * @brief The user which first created this rule + */ + snowflake creator_id; + /** + * @brief The rule event type + */ + automod_event_type event_type; + /** + * @brief The rule trigger type + */ + automod_trigger_type trigger_type; + /** + * @brief The rule trigger metadata + */ + automod_metadata trigger_metadata; + /** + * @brief the actions which will execute when the rule is triggered + */ + std::vector actions; + /** + * @brief Whether the rule is enabled + */ + bool enabled; + /** + * @brief the role ids that should not be affected by the rule (Maximum of 20) + */ + std::vector exempt_roles; + /** + * @brief the channel ids that should not be affected by the rule (Maximum of 50) + */ + std::vector exempt_channels; + + /** + * @brief Construct a new automod rule object + */ + automod_rule(); + + /** + * @brief Destroy the automod rule object + */ + virtual ~automod_rule(); + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return automod_rule& Reference to self + */ + automod_rule& fill_from_json(nlohmann::json* j); + + /** + * @brief Build a json string for this object + * + * @return std::string JSON string + */ + virtual std::string build_json(bool with_id = false) const; +}; + +/** A group of automod rules. + */ +typedef std::unordered_map automod_rule_map; + +}; diff --git a/3rdParty/dpp/ban.h b/3rdParty/dpp/ban.h index ea35ca4782..5695bc74a6 100644 --- a/3rdParty/dpp/ban.h +++ b/3rdParty/dpp/ban.h @@ -1,67 +1,67 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief The ban class represents a ban on a guild. - * - */ -class DPP_EXPORT ban : public json_interface { -public: - /** The ban reason */ - std::string reason; - /** User ID the ban applies to */ - snowflake user_id; - - /** Constructor */ - ban(); - - /** Destructor */ - virtual ~ban() = default; - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - ban& fill_from_json(nlohmann::json* j); - - /** - * @brief Build json representation of a ban - * @param with_id Include ID in json - * - * @return std::string stringified json - */ - std::string build_json(bool with_id = false) const; -}; - -/** A group of bans - */ -typedef std::unordered_map ban_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief The ban class represents a ban on a guild. + * + */ +class DPP_EXPORT ban : public json_interface { +public: + /** The ban reason */ + std::string reason; + /** User ID the ban applies to */ + snowflake user_id; + + /** Constructor */ + ban(); + + /** Destructor */ + virtual ~ban() = default; + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + ban& fill_from_json(nlohmann::json* j); + + /** + * @brief Build json representation of a ban + * @param with_id Include ID in json + * + * @return std::string stringified json + */ + std::string build_json(bool with_id = false) const; +}; + +/** A group of bans + */ +typedef std::unordered_map ban_map; + +}; diff --git a/3rdParty/dpp/cache.h b/3rdParty/dpp/cache.h index 7997e8d75a..59b3b4e77d 100644 --- a/3rdParty/dpp/cache.h +++ b/3rdParty/dpp/cache.h @@ -1,272 +1,272 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once -#include -#include -#include -#include -#include -#include - -namespace dpp { - -extern DPP_EXPORT std::unordered_map deletion_queue; -extern DPP_EXPORT std::mutex deletion_mutex; - -/** forward declaration */ -class guild_member; - -/** - * @brief A cache object maintains a cache of dpp::managed objects. - * - * This is for example users, channels or guilds. You may instantiate - * your own caches, to contain any type derived from dpp::managed including - * your own types. - * - * @note This class is critical to the operation of the library and therefore - * designed with thread safety in mind. - * @tparam T class type to store, which should be derived from dpp::managed. - */ -template class cache { -private: - /** - * @brief Mutex to protect the cache - * - * This is a shared mutex so reading is cheap. - */ - std::shared_mutex cache_mutex; - - /** - * @brief Container of pointers to cached items - */ - std::unordered_map* cache_map; -public: - - /** - * @brief Construct a new cache object. - * - * Caches must contain classes derived from dpp::managed. - */ - cache() { - cache_map = new std::unordered_map; - } - - /** - * @brief Destroy the cache object - * - * @note This does not delete objects stored in the cache. - */ - ~cache() { - std::unique_lock l(cache_mutex); - delete cache_map; - } - - /** - * @brief Store an object in the cache. Passing a nullptr will have no effect. - * - * The object must be derived from dpp::managed and should be allocated on the heap. - * Generally this is done via `new`. Once stored in the cache the lifetime of the stored - * object is managed by the cache class unless the cache is deleted (at which point responsibility - * for deleting the object returns to its allocator). Objects stored are removed when the - * cache::remove() method is called by placing them into a garbage collection queue for deletion - * within the next 60 seconds, which are then deleted in bulk for efficiency and to aid thread - * safety. - * - * @note Adding an object to the cache with an ID which already exists replaces that entry. - * The previously entered cache item is inserted into the garbage collection queue for deletion - * similarly to if cache::remove() was called first. - * - * @param object object to store. Storing a pointer to the cache relinquishes ownership to the cache object. - */ - void store(T* object) { - if (!object) { - return; - } - std::unique_lock l(cache_mutex); - auto existing = cache_map->find(object->id); - if (existing == cache_map->end()) { - (*cache_map)[object->id] = object; - } else if (object != existing->second) { - /* Flag old pointer for deletion and replace */ - std::lock_guard delete_lock(deletion_mutex); - deletion_queue[existing->second] = time(NULL); - (*cache_map)[object->id] = object; - } - } - - /** - * @brief Remove an object from the cache. - * - * @note The cache class takes ownership of the pointer, and calling this method will - * cause deletion of the object within the next 60 seconds by means of a garbage - * collection queue. This queue aids in efficiency by freeing memory in bulk, and - * assists in thread safety by ensuring that all deletions can be locked and freed - * at the same time. - * - * @param object object to remove. Passing a nullptr will have no effect. - */ - void remove(T* object) { - if (!object) { - return; - } - std::unique_lock l(cache_mutex); - std::lock_guard delete_lock(deletion_mutex); - auto existing = cache_map->find(object->id); - if (existing != cache_map->end()) { - cache_map->erase(existing); - deletion_queue[object] = time(NULL); - } - } - - /** - * @brief Find an object in the cache by id. - * - * The cache is searched for the object. All dpp::managed objects have a snowflake id - * (this is the only field dpp::managed actually has). - * - * @warning Do not hang onto objects returned by cache::find() indefinitely. They may be - * deleted at a later date if cache::remove() is called. If persistence is required, - * take a copy of the object after checking its pointer is non-null. - * - * @param id Object snowflake id to find - * @return Found object or nullptr if the object with this id does not exist. - */ - T* find(snowflake id) { - std::shared_lock l(cache_mutex); - auto r = cache_map->find(id); - if (r != cache_map->end()) { - return r->second; - } - return nullptr; - } - - /** - * @brief Return a count of the number of items in the cache. - * - * This is used by the library e.g. to count guilds, users, and roles - * stored within caches. - * get - * @return uint64_t count of items in the cache - */ - uint64_t count() { - std::shared_lock l(cache_mutex); - return cache_map->size(); - } - - /** - * @brief Return the cache's locking mutex. - * - * Use this whenever you manipulate or iterate raw elements in the cache! - * - * @note If you are only reading from the cache's container, wrap this - * mutex in `std::shared_lock`, else wrap it in a `std::unique_lock`. - * Shared locks will allow for multiple readers whilst blocking writers, - * and unique locks will allow only one writer whilst blocking readers - * and writers. - * - * **Example:** - * - * ```cpp - * dpp::cache* c = dpp::get_guild_cache(); - * std::unordered_map& gc = c->get_container(); - * std::shared_lock l(c->get_mutex()); // MUST LOCK HERE - * for (auto g = gc.begin(); g != gc.end(); ++g) { - * dpp::guild* gp = (dpp::guild*)g->second; - * // Do something here with the guild* in 'gp' - * } - * ``` - * - * @return The mutex used to protect the container - */ - std::shared_mutex& get_mutex() { - return this->cache_mutex; - } - - /** - * @brief Get the container unordered map - * - * @warning Be sure to use cache::get_mutex() correctly if you - * manipulate or iterate the map returned by this method! If you do - * not, this is not thread safe and will cause crashes! - * - * @see cache::get_mutex - * - * @return A reference to the cache's container map - */ - auto & get_container() { - return *(this->cache_map); - } - - /** - * @brief "Rehash" a cache by reallocating the map and copying - * all elements into the new one. - * - * Over a long running timeframe, unordered maps can grow in size - * due to bucket allocation, this function frees that unused memory - * to keep the maps in control over time. If this is an issue which - * is apparent with your use of dpp::cache objects, you should periodically - * call this method. - * - * @warning May be time consuming! This function is O(n) in relation to the - * number of cached entries. - */ - void rehash() { - std::unique_lock l(cache_mutex); - std::unordered_map* n = new std::unordered_map; - n->reserve(cache_map->size()); - for (auto t = cache_map->begin(); t != cache_map->end(); ++t) { - n->insert(*t); - } - delete cache_map; - cache_map = n; - } - - /** - * @brief Get "real" size in RAM of the cached objects - * - * This does not include metadata used to maintain the unordered map itself. - * - * @return size_t size of cache in bytes - */ - size_t bytes() { - std::shared_lock l(cache_mutex); - return sizeof(this) + (cache_map->bucket_count() * sizeof(size_t)); - } - -}; - -/** Run garbage collection across all caches removing deleted items - * that have been deleted over 60 seconds ago. - */ -void DPP_EXPORT garbage_collection(); - -#define cache_decl(type, setter, getter, counter) DPP_EXPORT class type * setter (snowflake id); DPP_EXPORT cache * getter (); DPP_EXPORT uint64_t counter (); - -/* Declare major caches */ -cache_decl(user, find_user, get_user_cache, get_user_count); -cache_decl(guild, find_guild, get_guild_cache, get_guild_count); -cache_decl(role, find_role, get_role_cache, get_role_count); -cache_decl(channel, find_channel, get_channel_cache, get_channel_count); -cache_decl(emoji, find_emoji, get_emoji_cache, get_emoji_count); - -}; - +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include +#include +#include + +namespace dpp { + +extern DPP_EXPORT std::unordered_map deletion_queue; +extern DPP_EXPORT std::mutex deletion_mutex; + +/** forward declaration */ +class guild_member; + +/** + * @brief A cache object maintains a cache of dpp::managed objects. + * + * This is for example users, channels or guilds. You may instantiate + * your own caches, to contain any type derived from dpp::managed including + * your own types. + * + * @note This class is critical to the operation of the library and therefore + * designed with thread safety in mind. + * @tparam T class type to store, which should be derived from dpp::managed. + */ +template class cache { +private: + /** + * @brief Mutex to protect the cache + * + * This is a shared mutex so reading is cheap. + */ + std::shared_mutex cache_mutex; + + /** + * @brief Container of pointers to cached items + */ + std::unordered_map* cache_map; +public: + + /** + * @brief Construct a new cache object. + * + * Caches must contain classes derived from dpp::managed. + */ + cache() { + cache_map = new std::unordered_map; + } + + /** + * @brief Destroy the cache object + * + * @note This does not delete objects stored in the cache. + */ + ~cache() { + std::unique_lock l(cache_mutex); + delete cache_map; + } + + /** + * @brief Store an object in the cache. Passing a nullptr will have no effect. + * + * The object must be derived from dpp::managed and should be allocated on the heap. + * Generally this is done via `new`. Once stored in the cache the lifetime of the stored + * object is managed by the cache class unless the cache is deleted (at which point responsibility + * for deleting the object returns to its allocator). Objects stored are removed when the + * cache::remove() method is called by placing them into a garbage collection queue for deletion + * within the next 60 seconds, which are then deleted in bulk for efficiency and to aid thread + * safety. + * + * @note Adding an object to the cache with an ID which already exists replaces that entry. + * The previously entered cache item is inserted into the garbage collection queue for deletion + * similarly to if cache::remove() was called first. + * + * @param object object to store. Storing a pointer to the cache relinquishes ownership to the cache object. + */ + void store(T* object) { + if (!object) { + return; + } + std::unique_lock l(cache_mutex); + auto existing = cache_map->find(object->id); + if (existing == cache_map->end()) { + (*cache_map)[object->id] = object; + } else if (object != existing->second) { + /* Flag old pointer for deletion and replace */ + std::lock_guard delete_lock(deletion_mutex); + deletion_queue[existing->second] = time(NULL); + (*cache_map)[object->id] = object; + } + } + + /** + * @brief Remove an object from the cache. + * + * @note The cache class takes ownership of the pointer, and calling this method will + * cause deletion of the object within the next 60 seconds by means of a garbage + * collection queue. This queue aids in efficiency by freeing memory in bulk, and + * assists in thread safety by ensuring that all deletions can be locked and freed + * at the same time. + * + * @param object object to remove. Passing a nullptr will have no effect. + */ + void remove(T* object) { + if (!object) { + return; + } + std::unique_lock l(cache_mutex); + std::lock_guard delete_lock(deletion_mutex); + auto existing = cache_map->find(object->id); + if (existing != cache_map->end()) { + cache_map->erase(existing); + deletion_queue[object] = time(NULL); + } + } + + /** + * @brief Find an object in the cache by id. + * + * The cache is searched for the object. All dpp::managed objects have a snowflake id + * (this is the only field dpp::managed actually has). + * + * @warning Do not hang onto objects returned by cache::find() indefinitely. They may be + * deleted at a later date if cache::remove() is called. If persistence is required, + * take a copy of the object after checking its pointer is non-null. + * + * @param id Object snowflake id to find + * @return Found object or nullptr if the object with this id does not exist. + */ + T* find(snowflake id) { + std::shared_lock l(cache_mutex); + auto r = cache_map->find(id); + if (r != cache_map->end()) { + return r->second; + } + return nullptr; + } + + /** + * @brief Return a count of the number of items in the cache. + * + * This is used by the library e.g. to count guilds, users, and roles + * stored within caches. + * get + * @return uint64_t count of items in the cache + */ + uint64_t count() { + std::shared_lock l(cache_mutex); + return cache_map->size(); + } + + /** + * @brief Return the cache's locking mutex. + * + * Use this whenever you manipulate or iterate raw elements in the cache! + * + * @note If you are only reading from the cache's container, wrap this + * mutex in `std::shared_lock`, else wrap it in a `std::unique_lock`. + * Shared locks will allow for multiple readers whilst blocking writers, + * and unique locks will allow only one writer whilst blocking readers + * and writers. + * + * **Example:** + * + * ```cpp + * dpp::cache* c = dpp::get_guild_cache(); + * std::unordered_map& gc = c->get_container(); + * std::shared_lock l(c->get_mutex()); // MUST LOCK HERE + * for (auto g = gc.begin(); g != gc.end(); ++g) { + * dpp::guild* gp = (dpp::guild*)g->second; + * // Do something here with the guild* in 'gp' + * } + * ``` + * + * @return The mutex used to protect the container + */ + std::shared_mutex& get_mutex() { + return this->cache_mutex; + } + + /** + * @brief Get the container unordered map + * + * @warning Be sure to use cache::get_mutex() correctly if you + * manipulate or iterate the map returned by this method! If you do + * not, this is not thread safe and will cause crashes! + * + * @see cache::get_mutex + * + * @return A reference to the cache's container map + */ + auto & get_container() { + return *(this->cache_map); + } + + /** + * @brief "Rehash" a cache by reallocating the map and copying + * all elements into the new one. + * + * Over a long running timeframe, unordered maps can grow in size + * due to bucket allocation, this function frees that unused memory + * to keep the maps in control over time. If this is an issue which + * is apparent with your use of dpp::cache objects, you should periodically + * call this method. + * + * @warning May be time consuming! This function is O(n) in relation to the + * number of cached entries. + */ + void rehash() { + std::unique_lock l(cache_mutex); + std::unordered_map* n = new std::unordered_map; + n->reserve(cache_map->size()); + for (auto t = cache_map->begin(); t != cache_map->end(); ++t) { + n->insert(*t); + } + delete cache_map; + cache_map = n; + } + + /** + * @brief Get "real" size in RAM of the cached objects + * + * This does not include metadata used to maintain the unordered map itself. + * + * @return size_t size of cache in bytes + */ + size_t bytes() { + std::shared_lock l(cache_mutex); + return sizeof(this) + (cache_map->bucket_count() * sizeof(size_t)); + } + +}; + +/** Run garbage collection across all caches removing deleted items + * that have been deleted over 60 seconds ago. + */ +void DPP_EXPORT garbage_collection(); + +#define cache_decl(type, setter, getter, counter) DPP_EXPORT class type * setter (snowflake id); DPP_EXPORT cache * getter (); DPP_EXPORT uint64_t counter (); + +/* Declare major caches */ +cache_decl(user, find_user, get_user_cache, get_user_count); +cache_decl(guild, find_guild, get_guild_cache, get_guild_count); +cache_decl(role, find_role, get_role_cache, get_role_count); +cache_decl(channel, find_channel, get_channel_cache, get_channel_count); +cache_decl(emoji, find_emoji, get_emoji_cache, get_emoji_count); + +}; + diff --git a/3rdParty/dpp/channel.h b/3rdParty/dpp/channel.h index 4ce396261e..8c72dcaed9 100644 --- a/3rdParty/dpp/channel.h +++ b/3rdParty/dpp/channel.h @@ -1,803 +1,803 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** @brief Flag integers as received from and sent to discord */ -enum channel_type : uint8_t { - CHANNEL_TEXT = 0, //!< a text channel within a server - DM = 1, //!< a direct message between users - CHANNEL_VOICE = 2, //!< a voice channel within a server - /** - * @brief a direct message between multiple users - * @deprecated this channel type was intended to be used with the now deprecated GameBridge SDK. Existing group dms with bots will continue to function, but newly created channels will be unusable - */ - GROUP_DM = 3, - CHANNEL_CATEGORY = 4, //!< an organizational category that contains up to 50 channels - CHANNEL_ANNOUNCEMENT = 5, //!< a channel that users can follow and crosspost into their own server - /** - * @brief a channel in which game developers can sell their game on Discord - * @deprecated store channels are deprecated by Discord - */ - CHANNEL_STORE = 6, - CHANNEL_ANNOUNCEMENT_THREAD = 10, //!< a temporary sub-channel within a GUILD_ANNOUNCEMENT channel - CHANNEL_PUBLIC_THREAD = 11, //!< a temporary sub-channel within a GUILD_TEXT or GUILD_FORUM channel - CHANNEL_PRIVATE_THREAD = 12, //!< a temporary sub-channel within a GUILD_TEXT channel that is only viewable by those invited and those with the MANAGE_THREADS permission - CHANNEL_STAGE = 13, //!< a "stage" channel, like a voice channel with one authorised speaker - CHANNEL_DIRECTORY = 14, //!< the channel in a [hub](https://support.discord.com/hc/en-us/articles/4406046651927-Discord-Student-Hubs-FAQ) containing the listed servers - CHANNEL_FORUM = 15 //!< forum channel that can only contain threads -}; - -/** @brief Our flags as stored in the object - * @note The bottom four bits of this flag are reserved to contain the channel_type values - * listed above as provided by Discord. If discord add another value > 15, we will have to - * shuffle these values upwards by one bit. - */ -enum channel_flags : uint16_t { - /// NSFW Gated Channel - c_nsfw = 0b0000000000010000, - /// Video quality forced to 720p - c_video_quality_720p = 0b0000000000100000, - /// Lock permissions (only used when updating channel positions) - c_lock_permissions = 0b0000000001000000, - /// Thread is pinned to the top of its parent forum channel - c_pinned_thread = 0b0000000010000000, - /// Whether a tag is required to be specified when creating a thread in a forum channel. Tags are specified in the thread::applied_tags field. - c_require_tag = 0b0000000100000000, - /* Note that the 9th and 10th bit are used for the forum layout type */ -}; - -/** - * @brief The flags in discord channel's raw "flags" field. We use these for serialisation only, right now. Might be better to create a new field than to make the existing channel::flags from uint8_t to uint16_t, if discord adds more flags in future. - */ -enum discord_channel_flags : uint8_t { - /// Thread is pinned to the top of its parent forum channel - dc_pinned_thread = 1 << 1, - /// Whether a tag is required to be specified when creating a thread in a forum channel. Tags are specified in the thread::applied_tags field. - dc_require_tag = 1 << 4, -}; - -/** - * @brief Types for sort posts in a forum channel - */ -enum default_forum_sort_order_t : uint8_t { - /// Sort forum posts by activity (default) - so_latest_activity = 0, - /// Sort forum posts by creation time (from most recent to oldest) - so_creation_date = 1, -}; - -/** - * @brief Types of forum layout views that indicates how the threads in a forum channel will be displayed for users by default - */ -enum forum_layout_type : uint8_t { - fl_not_set = 0, //!< No default has been set for the forum channel - fl_list_view = 1, //!< Display posts as a list - fl_gallery_view = 2, //!< Display posts as a collection of tiles -}; - -/** - * @brief channel permission overwrite types - */ -enum overwrite_type : uint8_t { - /// Role - ot_role = 0, - /// Member - ot_member = 1 -}; - -/** - * @brief Channel permission overwrites - */ -struct DPP_EXPORT permission_overwrite { - /// ID of the role or the member - snowflake id; - /// Bitmask of allowed permissions - permission allow; - /// Bitmask of denied permissions - permission deny; - /// Type of overwrite. See dpp::overwrite_type - uint8_t type; - - /** - * @brief Construct a new permission_overwrite object - */ - permission_overwrite(); - - /** - * @brief Construct a new permission_overwrite object - * @param id ID of the role or the member to create the overwrite for - * @param allow Bitmask of allowed permissions (refer to enum dpp::permissions) for this user/role in this channel - * @param deny Bitmask of denied permissions (refer to enum dpp::permissions) for this user/role in this channel - * @param type Type of overwrite - */ - permission_overwrite(snowflake id, uint64_t allow, uint64_t deny, overwrite_type type); -}; - - -/** - * @brief metadata for threads - */ -struct DPP_EXPORT thread_metadata { - /// Timestamp when the thread's archive status was last changed, used for calculating recent activity - time_t archive_timestamp; - /// The duration in minutes to automatically archive the thread after recent activity, can be set to: 60, 1440, 4320, 10080 - uint16_t auto_archive_duration; - /// Whether a thread is archived - bool archived; - /// Whether a thread is locked. When a thread is locked, only users with `MANAGE_THREADS` can unarchive it - bool locked; - /// Whether non-moderators can add other non-moderators. Only for private threads - bool invitable; -}; - -/** - * @brief Auto archive duration of threads which will stop showing in the channel list after the specified period of inactivity. - * Defined as an enum to fit into 1 byte. Internally it'll be translated to minutes to match the API - */ -enum auto_archive_duration_t : uint8_t { - /// Auto archive duration of 1 hour. (60 minutes) - arc_1_hour = 1, - /// Auto archive duration of 1 day. (1440 minutes) - arc_1_day = 2, - /// Auto archive duration of 3 days. (4320 minutes) - arc_3_days = 3, - /// Auto archive duration of 1 week. (10080 minutes) - arc_1_week = 4, -}; - -/** - * @brief represents membership of a user with a thread - */ -struct DPP_EXPORT thread_member -{ - /// ID of the thread member is part of - snowflake thread_id; - /// ID of the member - snowflake user_id; - /// The time when user last joined the thread - time_t joined; - /// Any user-thread settings, currently only used for notifications - uint32_t flags; - - /** - * @brief Read struct values from a json object - * @param j json to read values from - * @return A reference to self - */ - thread_member& fill_from_json(nlohmann::json* j); -}; - -/** - * @brief Represents a tag that is able to be applied to a thread in a forum channel - */ -struct DPP_EXPORT forum_tag : public managed { - /** The name of the tag (0-20 characters) */ - std::string name; - /** The emoji of the tag. Contains either nothing, the id of a guild's custom emoji or the unicode character of the emoji */ - std::variant emoji; - /** Whether this tag can only be added to or removed from threads by a member with the `MANAGE_THREADS` permission */ - bool moderated; - - /** Constructor */ - forum_tag(); - - /** - * @brief Constructor - * - * @param name The name of the tag. It will be truncated to the maximum length of 20 UTF-8 characters. - */ - forum_tag(const std::string& name); - - /** Destructor */ - virtual ~forum_tag(); - - /** - * @brief Read struct values from a json object - * @param j json to read values from - * @return A reference to self - */ - forum_tag& fill_from_json(nlohmann::json* j); - - /** - * @brief Build json for this forum_tag object - * - * @param with_id include the ID in the json - * @return std::string JSON string - */ - std::string build_json(bool with_id = false) const; - - /** - * @brief Set name of this forum_tag object - * - * @param name Name to set - * @return Reference to self, so these method calls may be chained - * - * @note name will be truncated to 20 chars, if longer - */ - forum_tag& set_name(const std::string& name); -}; - -/** @brief A group of thread member objects*/ -typedef std::unordered_map thread_member_map; - -/** - * @brief A definition of a discord channel. - * There are one of these for every channel type except threads. Threads are - * special snowflakes. Get it? A Discord pun. Hahaha. .... I'll get my coat. - */ -class DPP_EXPORT channel : public managed, public json_interface { -public: - /** Channel name (1-100 characters) */ - std::string name; - - /** Channel topic (0-4096 characters for forum channels, 0-1024 characters for all others) */ - std::string topic; - - /** - * @brief Voice region if set for voice channel, otherwise empty string - */ - std::string rtc_region; - - /** DM recipients */ - std::vector recipients; - - /** Permission overwrites to apply to base permissions */ - std::vector permission_overwrites; - - /** A set of tags that can be used in a forum channel */ - std::vector available_tags; - - /** - * @brief The emoji to show as the default reaction button on a forum post. - * Contains either nothing, the id of a guild's custom emoji or the unicode character of the emoji - */ - std::variant default_reaction; - - /** - * @brief Channel icon (for group DMs) - */ - utility::iconhash icon; - - /** User ID of the creator for group DMs or threads */ - snowflake owner_id; - - /** Parent ID (for guild channels: id of the parent category, for threads: id of the text channel this thread was created) */ - snowflake parent_id; - - /** Guild id of the guild that owns the channel */ - snowflake guild_id; - - /** ID of last message to be sent to the channel (may not point to an existing or valid message or thread) */ - snowflake last_message_id; - - /** Timestamp of last pinned message */ - time_t last_pin_timestamp; - - /** - * @brief This is only filled when the channel is part of the `resolved` set - * sent within an interaction. Any other time it contains zero. When filled, - * it contains the calculated permission bitmask of the user issuing the command - * within this channel. - */ - permission permissions; - - /** Sorting position, lower number means higher up the list */ - uint16_t position; - - /** the bitrate (in kilobits) of the voice channel */ - uint16_t bitrate; - - /** amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages or manage_channel, are unaffected*/ - uint16_t rate_limit_per_user; - - /** The initial `rate_limit_per_user` to set on newly created threads in a channel. This field is copied to the thread at creation time and does not live update */ - uint16_t default_thread_rate_limit_per_user; - - /** - * @brief Default duration, copied onto newly created threads. Used by the clients, not the API. - * Threads will stop showing in the channel list after the specified period of inactivity. Defaults to dpp::arc_1_day - */ - auto_archive_duration_t default_auto_archive_duration; - - /** the default sort order type used to order posts in forum channels */ - default_forum_sort_order_t default_sort_order; - - /** Flags bitmap (dpp::channel_flags) */ - uint16_t flags; - - /** Maximum user limit for voice channels (0-99) */ - uint8_t user_limit; - - /** Constructor */ - channel(); - - /** Destructor */ - virtual ~channel(); - - /** - * @brief Create a mentionable channel. - * @param id The ID of the channel. - * @return std::string The formatted mention of the channel. - */ - static std::string get_mention(const snowflake& id); - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - channel& fill_from_json(nlohmann::json* j); - - /** - * @brief Build json for this channel object - * - * @param with_id include the ID in the json - * @return std::string JSON string - */ - virtual std::string build_json(bool with_id = false) const; - - /** - * @brief Set name of this channel object - * - * @param name Name to set - * @return Reference to self, so these method calls may be chained - * - * @note name will be truncated to 100 chars, if longer - * @throw dpp::length_exception if length < 1 - */ - channel& set_name(const std::string& name); - - /** - * @brief Set topic of this channel object - * - * @param topic Topic to set - * @return Reference to self, so these method calls may be chained - * - * @note topic will be truncated to 1024 chars, if longer - */ - channel& set_topic(const std::string& topic); - - /** - * @brief Set type of this channel object - * - * @param type Channel type to set - * @return Reference to self, so these method calls may be chained - */ - channel& set_type(channel_type type); - - /** - * @brief Set the default forum layout type for the forum channel - * - * @param layout_type The layout type - * @return Reference to self, so these method calls may be chained - */ - channel& set_default_forum_layout(forum_layout_type layout_type); - - /** - * @brief Set flags for this channel object - * - * @param flags Flag bitmask to set from dpp::channel_flags - * @return Reference to self, so these method calls may be chained - */ - channel& set_flags(const uint16_t flags); - - /** - * @brief Add (bitwise OR) a flag to this channel object - * - * @param flag Flag bit to add from dpp::channel_flags - * @return Reference to self, so these method calls may be chained - */ - channel& add_flag(const channel_flags flag); - - /** - * @brief Remove (bitwise NOT AND) a flag from this channel object - * - * @param flag Flag bit to remove from dpp::channel_flags - * @return Reference to self, so these method calls may be chained - */ - channel& remove_flag(const channel_flags flag); - - /** - * @brief Set position of this channel object - * - * @param position Position to set - * @return Reference to self, so these method calls may be chained - */ - channel& set_position(const uint16_t position); - - /** - * @brief Set guild_id of this channel object - * - * @param guild_id Guild ID to set - * @return Reference to self, so these method calls may be chained - */ - channel& set_guild_id(const snowflake guild_id); - - /** - * @brief Set parent_id of this channel object - * - * @param parent_id Parent ID to set - * @return Reference to self, so these method calls may be chained - */ - channel& set_parent_id(const snowflake parent_id); - - /** - * @brief Set user_limit of this channel object - * - * @param user_limit Limit to set - * @return Reference to self, so these method calls may be chained - */ - channel& set_user_limit(const uint8_t user_limit); - - /** - * @brief Set bitrate of this channel object - * - * @param bitrate Bitrate to set (in kilobits) - * @return Reference to self, so these method calls may be chained - */ - channel& set_bitrate(const uint16_t bitrate); - - /** - * @brief Set nsfw property of this channel object - * - * @param is_nsfw true, if channel is nsfw - * @return Reference to self, so these method calls may be chained - */ - channel& set_nsfw(const bool is_nsfw); - - /** - * @brief Set lock permissions property of this channel object - * Used only with the reorder channels method - * - * @param is_lock_permissions true, if we are to inherit permissions from the category - * @return Reference to self, so these method calls may be chained - */ - channel& set_lock_permissions(const bool is_lock_permissions); - - /** - * @brief Set rate_limit_per_user of this channel object - * - * @param rate_limit_per_user rate_limit_per_user (slowmode in sec) to set - * @return Reference to self, so these method calls may be chained - */ - channel& set_rate_limit_per_user(const uint16_t rate_limit_per_user); - - /** - * @brief Add a permission_overwrite to this channel object - * - * @param id ID of the role or the member you want to add overwrite for - * @param type type of overwrite - * @param allowed_permissions bitmask of allowed permissions (refer to enum dpp::permissions) for this user/role in this channel - * @param denied_permissions bitmask of denied permissions (refer to enum dpp::permissions) for this user/role in this channel - * - * @return Reference to self, so these method calls may be chained - */ - channel& add_permission_overwrite(const snowflake id, const overwrite_type type, const uint64_t allowed_permissions, const uint64_t denied_permissions); - - /** - * @brief Get the channel type - * - * @return channel_type Channel type - */ - channel_type get_type() const; - - /** - * @brief Get the default forum layout type used to display posts in forum channels - * - * @return forum_layout_types Forum layout type - */ - forum_layout_type get_default_forum_layout() const; - - /** - * @brief Get the mention ping for the channel - * - * @return std::string mention - */ - std::string get_mention() const; - - /** - * @brief Get the overall permissions for a member in this channel, including channel overwrites, role permissions and admin privileges. - * - * @param user The user to resolve the permissions for - * @return permission Permission overwrites for the member. Made of bits in dpp::permissions. - * @note Requires role cache to be enabled (it's enabled by default). - * - * @note This is an alias for guild::permission_overwrites and searches for the guild in the cache, - * so consider using guild::permission_overwrites if you already have the guild object. - * - * @warning The method will search for the guild member in the cache by the users id. - * If the guild member is not in cache, the method will always return 0. - */ - permission get_user_permissions(const class user* user) const; - - /** - * @brief Get the overall permissions for a member in this channel, including channel overwrites, role permissions and admin privileges. - * - * @param member The member to resolve the permissions for - * @return permission Permission overwrites for the member. Made of bits in dpp::permissions. - * @note Requires role cache to be enabled (it's enabled by default). - * - * @note This is an alias for guild::permission_overwrites and searches for the guild in the cache, - * so consider using guild::permission_overwrites if you already have the guild object. - */ - permission get_user_permissions(const class guild_member &member) const; - - /** - * @brief Return a map of members on the channel, built from the guild's - * member list based on which members have the VIEW_CHANNEL permission. - * Does not return reliable information for voice channels, use - * dpp::channel::get_voice_members() instead for this. - * @return A map of guild members keyed by user id. - * @note If the guild this channel belongs to is not in the cache, the function will always return 0. - */ - std::map get_members(); - - /** - * @brief Get a map of members in this channel, if it is a voice channel. - * The map is keyed by snowflake id of the user. - * - * @return std::map The voice members of the channel - */ - std::map get_voice_members(); - - /** - * @brief Get the channel's icon url (if its a group DM), otherwise returns an empty string - * - * @param size The size of the icon in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized icon is returned. - * @return std::string icon url or empty string - */ - std::string get_icon_url(uint16_t size = 0) const; - - /** - * @brief Returns true if the channel is NSFW gated - * - * @return true if NSFW - */ - bool is_nsfw() const; - - /** - * @brief Returns true if the permissions are to be synced with the category it is in. - * Used only and set manually when using the reorder channels method. - * - * @return true if keeping permissions - */ - bool is_locked_permissions() const; - - /** - * @brief Returns true if the channel is a text channel - * - * @return true if text channel - */ - bool is_text_channel() const; - - /** - * @brief Returns true if the channel is a DM - * - * @return true if is a DM - */ - bool is_dm() const; - - /** - * @brief Returns true if the channel is a voice channel - * - * @return true if voice channel - */ - bool is_voice_channel() const; - - /** - * @brief Returns true if the channel is a group DM channel - * - * @return true if group DM - */ - bool is_group_dm() const; - - /** - * @brief Returns true if the channel is a category - * - * @return true if a category - */ - bool is_category() const; - - /** - * @brief Returns true if the channel is a forum - * - * @return true if a forum - */ - bool is_forum() const; - - /** - * @brief Returns true if the channel is an announcement channel - * - * @return true if announcement channel - */ - bool is_news_channel() const; - - /** - * @brief Returns true if the channel is a store channel - * @deprecated store channels are deprecated by Discord - * - * @return true if store channel - */ - bool is_store_channel() const; - - /** - * @brief Returns true if the channel is a stage channel - * - * @return true if stage channel - */ - bool is_stage_channel() const; - - /** - * @brief Returns true if video quality is auto - * - * @return true if video quality is auto - */ - bool is_video_auto() const; - - /** - * @brief Returns true if video quality is 720p - * - * @return true if video quality is 720p - */ - bool is_video_720p() const; - - /** - * @brief Returns true if channel is a pinned thread in forum - * - * @return true, if channel is a pinned thread in forum - */ - bool is_pinned_thread() const; - - /** - * @brief Returns true if a tag is required to be specified when creating a thread in a forum channel - * - * @return true, if a tag is required to be specified when creating a thread in a forum channel - */ - bool is_tag_required() const; - -}; - -/** @brief A definition of a discord thread. - * A thread is a superset of a channel. Not to be confused with `std::thread`! - */ -class DPP_EXPORT thread : public channel { -public: - /** - * @brief Thread member of current user if joined to the thread. - * Note this is only set by certain api calls otherwise contains default data - */ - thread_member member; - - /** Thread metadata (threads) */ - thread_metadata metadata; - - /** Created message. Only filled within the cluster::thread_create_in_forum() method */ - message msg; - - /** - * A list of dpp::forum_tag IDs that have been applied to a thread in a forum channel - */ - std::vector applied_tags; - - /** - * @brief Number of messages ever sent in the thread. - * It's similar to thread::message_count on message creation, but will not decrement the number when a message is deleted - */ - uint32_t total_messages_sent; - - /** - * @brief Number of messages (not including the initial message or deleted messages) of the thread. - * For threads created before July 1, 2022, the message count is inaccurate when it's greater than 50. - */ - uint8_t message_count; - - /** Approximate count of members in a thread (threads) */ - uint8_t member_count; - - /** - * @brief Construct a new thread object - */ - thread(); - - /** - * @brief Returns true if the thread is within an announcement channel - * - * @return true if announcement thread - */ - bool is_news_thread() const; - - /** - * @brief Returns true if the channel is a public thread - * - * @return true if public thread - */ - bool is_public_thread() const; - - /** - * @brief Returns true if the channel is a private thread - * - * @return true if private thread - */ - bool is_private_thread() const; - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - thread& fill_from_json(nlohmann::json* j); - - /** - * @brief Destroy the thread object - */ - virtual ~thread(); - - /** - * @brief Build json for this thread object - * - * @param with_id include the ID in the json - * @return std::string JSON string - */ - std::string build_json(bool with_id = false) const; - -}; - - -/** - * @brief Serialize a thread_metadata object to json - * - * @param j JSON object to serialize to - * @param tmdata object to serialize - */ -void to_json(nlohmann::json& j, const thread_metadata& tmdata); - -/** - * @brief Serialize a permission_overwrite object to json - * - * @param j JSON object to serialize to - * @param po object to serialize - */ -void to_json(nlohmann::json& j, const permission_overwrite& po); - -/** - * @brief A group of channels - */ -typedef std::unordered_map channel_map; - -/** - * @brief A group of threads - */ -typedef std::unordered_map thread_map; - -}; - +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** @brief Flag integers as received from and sent to discord */ +enum channel_type : uint8_t { + CHANNEL_TEXT = 0, //!< a text channel within a server + DM = 1, //!< a direct message between users + CHANNEL_VOICE = 2, //!< a voice channel within a server + /** + * @brief a direct message between multiple users + * @deprecated this channel type was intended to be used with the now deprecated GameBridge SDK. Existing group dms with bots will continue to function, but newly created channels will be unusable + */ + GROUP_DM = 3, + CHANNEL_CATEGORY = 4, //!< an organizational category that contains up to 50 channels + CHANNEL_ANNOUNCEMENT = 5, //!< a channel that users can follow and crosspost into their own server + /** + * @brief a channel in which game developers can sell their game on Discord + * @deprecated store channels are deprecated by Discord + */ + CHANNEL_STORE = 6, + CHANNEL_ANNOUNCEMENT_THREAD = 10, //!< a temporary sub-channel within a GUILD_ANNOUNCEMENT channel + CHANNEL_PUBLIC_THREAD = 11, //!< a temporary sub-channel within a GUILD_TEXT or GUILD_FORUM channel + CHANNEL_PRIVATE_THREAD = 12, //!< a temporary sub-channel within a GUILD_TEXT channel that is only viewable by those invited and those with the MANAGE_THREADS permission + CHANNEL_STAGE = 13, //!< a "stage" channel, like a voice channel with one authorised speaker + CHANNEL_DIRECTORY = 14, //!< the channel in a [hub](https://support.discord.com/hc/en-us/articles/4406046651927-Discord-Student-Hubs-FAQ) containing the listed servers + CHANNEL_FORUM = 15 //!< forum channel that can only contain threads +}; + +/** @brief Our flags as stored in the object + * @note The bottom four bits of this flag are reserved to contain the channel_type values + * listed above as provided by Discord. If discord add another value > 15, we will have to + * shuffle these values upwards by one bit. + */ +enum channel_flags : uint16_t { + /// NSFW Gated Channel + c_nsfw = 0b0000000000010000, + /// Video quality forced to 720p + c_video_quality_720p = 0b0000000000100000, + /// Lock permissions (only used when updating channel positions) + c_lock_permissions = 0b0000000001000000, + /// Thread is pinned to the top of its parent forum channel + c_pinned_thread = 0b0000000010000000, + /// Whether a tag is required to be specified when creating a thread in a forum channel. Tags are specified in the thread::applied_tags field. + c_require_tag = 0b0000000100000000, + /* Note that the 9th and 10th bit are used for the forum layout type */ +}; + +/** + * @brief The flags in discord channel's raw "flags" field. We use these for serialisation only, right now. Might be better to create a new field than to make the existing channel::flags from uint8_t to uint16_t, if discord adds more flags in future. + */ +enum discord_channel_flags : uint8_t { + /// Thread is pinned to the top of its parent forum channel + dc_pinned_thread = 1 << 1, + /// Whether a tag is required to be specified when creating a thread in a forum channel. Tags are specified in the thread::applied_tags field. + dc_require_tag = 1 << 4, +}; + +/** + * @brief Types for sort posts in a forum channel + */ +enum default_forum_sort_order_t : uint8_t { + /// Sort forum posts by activity (default) + so_latest_activity = 0, + /// Sort forum posts by creation time (from most recent to oldest) + so_creation_date = 1, +}; + +/** + * @brief Types of forum layout views that indicates how the threads in a forum channel will be displayed for users by default + */ +enum forum_layout_type : uint8_t { + fl_not_set = 0, //!< No default has been set for the forum channel + fl_list_view = 1, //!< Display posts as a list + fl_gallery_view = 2, //!< Display posts as a collection of tiles +}; + +/** + * @brief channel permission overwrite types + */ +enum overwrite_type : uint8_t { + /// Role + ot_role = 0, + /// Member + ot_member = 1 +}; + +/** + * @brief Channel permission overwrites + */ +struct DPP_EXPORT permission_overwrite { + /// ID of the role or the member + snowflake id; + /// Bitmask of allowed permissions + permission allow; + /// Bitmask of denied permissions + permission deny; + /// Type of overwrite. See dpp::overwrite_type + uint8_t type; + + /** + * @brief Construct a new permission_overwrite object + */ + permission_overwrite(); + + /** + * @brief Construct a new permission_overwrite object + * @param id ID of the role or the member to create the overwrite for + * @param allow Bitmask of allowed permissions (refer to enum dpp::permissions) for this user/role in this channel + * @param deny Bitmask of denied permissions (refer to enum dpp::permissions) for this user/role in this channel + * @param type Type of overwrite + */ + permission_overwrite(snowflake id, uint64_t allow, uint64_t deny, overwrite_type type); +}; + + +/** + * @brief metadata for threads + */ +struct DPP_EXPORT thread_metadata { + /// Timestamp when the thread's archive status was last changed, used for calculating recent activity + time_t archive_timestamp; + /// The duration in minutes to automatically archive the thread after recent activity, can be set to: 60, 1440, 4320, 10080 + uint16_t auto_archive_duration; + /// Whether a thread is archived + bool archived; + /// Whether a thread is locked. When a thread is locked, only users with `MANAGE_THREADS` can unarchive it + bool locked; + /// Whether non-moderators can add other non-moderators. Only for private threads + bool invitable; +}; + +/** + * @brief Auto archive duration of threads which will stop showing in the channel list after the specified period of inactivity. + * Defined as an enum to fit into 1 byte. Internally it'll be translated to minutes to match the API + */ +enum auto_archive_duration_t : uint8_t { + /// Auto archive duration of 1 hour. (60 minutes) + arc_1_hour = 1, + /// Auto archive duration of 1 day. (1440 minutes) + arc_1_day = 2, + /// Auto archive duration of 3 days. (4320 minutes) + arc_3_days = 3, + /// Auto archive duration of 1 week. (10080 minutes) + arc_1_week = 4, +}; + +/** + * @brief represents membership of a user with a thread + */ +struct DPP_EXPORT thread_member +{ + /// ID of the thread member is part of + snowflake thread_id; + /// ID of the member + snowflake user_id; + /// The time when user last joined the thread + time_t joined; + /// Any user-thread settings, currently only used for notifications + uint32_t flags; + + /** + * @brief Read struct values from a json object + * @param j json to read values from + * @return A reference to self + */ + thread_member& fill_from_json(nlohmann::json* j); +}; + +/** + * @brief Represents a tag that is able to be applied to a thread in a forum channel + */ +struct DPP_EXPORT forum_tag : public managed { + /** The name of the tag (0-20 characters) */ + std::string name; + /** The emoji of the tag. Contains either nothing, the id of a guild's custom emoji or the unicode character of the emoji */ + std::variant emoji; + /** Whether this tag can only be added to or removed from threads by a member with the `MANAGE_THREADS` permission */ + bool moderated; + + /** Constructor */ + forum_tag(); + + /** + * @brief Constructor + * + * @param name The name of the tag. It will be truncated to the maximum length of 20 UTF-8 characters. + */ + forum_tag(const std::string& name); + + /** Destructor */ + virtual ~forum_tag(); + + /** + * @brief Read struct values from a json object + * @param j json to read values from + * @return A reference to self + */ + forum_tag& fill_from_json(nlohmann::json* j); + + /** + * @brief Build json for this forum_tag object + * + * @param with_id include the ID in the json + * @return std::string JSON string + */ + std::string build_json(bool with_id = false) const; + + /** + * @brief Set name of this forum_tag object + * + * @param name Name to set + * @return Reference to self, so these method calls may be chained + * + * @note name will be truncated to 20 chars, if longer + */ + forum_tag& set_name(const std::string& name); +}; + +/** @brief A group of thread member objects*/ +typedef std::unordered_map thread_member_map; + +/** + * @brief A definition of a discord channel. + * There are one of these for every channel type except threads. Threads are + * special snowflakes. Get it? A Discord pun. Hahaha. .... I'll get my coat. + */ +class DPP_EXPORT channel : public managed, public json_interface { +public: + /** Channel name (1-100 characters) */ + std::string name; + + /** Channel topic (0-4096 characters for forum channels, 0-1024 characters for all others) */ + std::string topic; + + /** + * @brief Voice region if set for voice channel, otherwise empty string + */ + std::string rtc_region; + + /** DM recipients */ + std::vector recipients; + + /** Permission overwrites to apply to base permissions */ + std::vector permission_overwrites; + + /** A set of tags that can be used in a forum channel */ + std::vector available_tags; + + /** + * @brief The emoji to show as the default reaction button on a forum post. + * Contains either nothing, the id of a guild's custom emoji or the unicode character of the emoji + */ + std::variant default_reaction; + + /** + * @brief Channel icon (for group DMs) + */ + utility::iconhash icon; + + /** User ID of the creator for group DMs or threads */ + snowflake owner_id; + + /** Parent ID (for guild channels: id of the parent category, for threads: id of the text channel this thread was created) */ + snowflake parent_id; + + /** Guild id of the guild that owns the channel */ + snowflake guild_id; + + /** ID of last message to be sent to the channel (may not point to an existing or valid message or thread) */ + snowflake last_message_id; + + /** Timestamp of last pinned message */ + time_t last_pin_timestamp; + + /** + * @brief This is only filled when the channel is part of the `resolved` set + * sent within an interaction. Any other time it contains zero. When filled, + * it contains the calculated permission bitmask of the user issuing the command + * within this channel. + */ + permission permissions; + + /** Sorting position, lower number means higher up the list */ + uint16_t position; + + /** the bitrate (in kilobits) of the voice channel */ + uint16_t bitrate; + + /** amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages or manage_channel, are unaffected*/ + uint16_t rate_limit_per_user; + + /** The initial `rate_limit_per_user` to set on newly created threads in a channel. This field is copied to the thread at creation time and does not live update */ + uint16_t default_thread_rate_limit_per_user; + + /** + * @brief Default duration, copied onto newly created threads. Used by the clients, not the API. + * Threads will stop showing in the channel list after the specified period of inactivity. Defaults to dpp::arc_1_day + */ + auto_archive_duration_t default_auto_archive_duration; + + /** the default sort order type used to order posts in forum channels */ + default_forum_sort_order_t default_sort_order; + + /** Flags bitmap (dpp::channel_flags) */ + uint16_t flags; + + /** Maximum user limit for voice channels (0-99) */ + uint8_t user_limit; + + /** Constructor */ + channel(); + + /** Destructor */ + virtual ~channel(); + + /** + * @brief Create a mentionable channel. + * @param id The ID of the channel. + * @return std::string The formatted mention of the channel. + */ + static std::string get_mention(const snowflake& id); + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + channel& fill_from_json(nlohmann::json* j); + + /** + * @brief Build json for this channel object + * + * @param with_id include the ID in the json + * @return std::string JSON string + */ + virtual std::string build_json(bool with_id = false) const; + + /** + * @brief Set name of this channel object + * + * @param name Name to set + * @return Reference to self, so these method calls may be chained + * + * @note name will be truncated to 100 chars, if longer + * @throw dpp::length_exception if length < 1 + */ + channel& set_name(const std::string& name); + + /** + * @brief Set topic of this channel object + * + * @param topic Topic to set + * @return Reference to self, so these method calls may be chained + * + * @note topic will be truncated to 1024 chars, if longer + */ + channel& set_topic(const std::string& topic); + + /** + * @brief Set type of this channel object + * + * @param type Channel type to set + * @return Reference to self, so these method calls may be chained + */ + channel& set_type(channel_type type); + + /** + * @brief Set the default forum layout type for the forum channel + * + * @param layout_type The layout type + * @return Reference to self, so these method calls may be chained + */ + channel& set_default_forum_layout(forum_layout_type layout_type); + + /** + * @brief Set flags for this channel object + * + * @param flags Flag bitmask to set from dpp::channel_flags + * @return Reference to self, so these method calls may be chained + */ + channel& set_flags(const uint16_t flags); + + /** + * @brief Add (bitwise OR) a flag to this channel object + * + * @param flag Flag bit to add from dpp::channel_flags + * @return Reference to self, so these method calls may be chained + */ + channel& add_flag(const channel_flags flag); + + /** + * @brief Remove (bitwise NOT AND) a flag from this channel object + * + * @param flag Flag bit to remove from dpp::channel_flags + * @return Reference to self, so these method calls may be chained + */ + channel& remove_flag(const channel_flags flag); + + /** + * @brief Set position of this channel object + * + * @param position Position to set + * @return Reference to self, so these method calls may be chained + */ + channel& set_position(const uint16_t position); + + /** + * @brief Set guild_id of this channel object + * + * @param guild_id Guild ID to set + * @return Reference to self, so these method calls may be chained + */ + channel& set_guild_id(const snowflake guild_id); + + /** + * @brief Set parent_id of this channel object + * + * @param parent_id Parent ID to set + * @return Reference to self, so these method calls may be chained + */ + channel& set_parent_id(const snowflake parent_id); + + /** + * @brief Set user_limit of this channel object + * + * @param user_limit Limit to set + * @return Reference to self, so these method calls may be chained + */ + channel& set_user_limit(const uint8_t user_limit); + + /** + * @brief Set bitrate of this channel object + * + * @param bitrate Bitrate to set (in kilobits) + * @return Reference to self, so these method calls may be chained + */ + channel& set_bitrate(const uint16_t bitrate); + + /** + * @brief Set nsfw property of this channel object + * + * @param is_nsfw true, if channel is nsfw + * @return Reference to self, so these method calls may be chained + */ + channel& set_nsfw(const bool is_nsfw); + + /** + * @brief Set lock permissions property of this channel object + * Used only with the reorder channels method + * + * @param is_lock_permissions true, if we are to inherit permissions from the category + * @return Reference to self, so these method calls may be chained + */ + channel& set_lock_permissions(const bool is_lock_permissions); + + /** + * @brief Set rate_limit_per_user of this channel object + * + * @param rate_limit_per_user rate_limit_per_user (slowmode in sec) to set + * @return Reference to self, so these method calls may be chained + */ + channel& set_rate_limit_per_user(const uint16_t rate_limit_per_user); + + /** + * @brief Add a permission_overwrite to this channel object + * + * @param id ID of the role or the member you want to add overwrite for + * @param type type of overwrite + * @param allowed_permissions bitmask of allowed permissions (refer to enum dpp::permissions) for this user/role in this channel + * @param denied_permissions bitmask of denied permissions (refer to enum dpp::permissions) for this user/role in this channel + * + * @return Reference to self, so these method calls may be chained + */ + channel& add_permission_overwrite(const snowflake id, const overwrite_type type, const uint64_t allowed_permissions, const uint64_t denied_permissions); + + /** + * @brief Get the channel type + * + * @return channel_type Channel type + */ + channel_type get_type() const; + + /** + * @brief Get the default forum layout type used to display posts in forum channels + * + * @return forum_layout_types Forum layout type + */ + forum_layout_type get_default_forum_layout() const; + + /** + * @brief Get the mention ping for the channel + * + * @return std::string mention + */ + std::string get_mention() const; + + /** + * @brief Get the overall permissions for a member in this channel, including channel overwrites, role permissions and admin privileges. + * + * @param user The user to resolve the permissions for + * @return permission Permission overwrites for the member. Made of bits in dpp::permissions. + * @note Requires role cache to be enabled (it's enabled by default). + * + * @note This is an alias for guild::permission_overwrites and searches for the guild in the cache, + * so consider using guild::permission_overwrites if you already have the guild object. + * + * @warning The method will search for the guild member in the cache by the users id. + * If the guild member is not in cache, the method will always return 0. + */ + permission get_user_permissions(const class user* user) const; + + /** + * @brief Get the overall permissions for a member in this channel, including channel overwrites, role permissions and admin privileges. + * + * @param member The member to resolve the permissions for + * @return permission Permission overwrites for the member. Made of bits in dpp::permissions. + * @note Requires role cache to be enabled (it's enabled by default). + * + * @note This is an alias for guild::permission_overwrites and searches for the guild in the cache, + * so consider using guild::permission_overwrites if you already have the guild object. + */ + permission get_user_permissions(const class guild_member &member) const; + + /** + * @brief Return a map of members on the channel, built from the guild's + * member list based on which members have the VIEW_CHANNEL permission. + * Does not return reliable information for voice channels, use + * dpp::channel::get_voice_members() instead for this. + * @return A map of guild members keyed by user id. + * @note If the guild this channel belongs to is not in the cache, the function will always return 0. + */ + std::map get_members(); + + /** + * @brief Get a map of members in this channel, if it is a voice channel. + * The map is keyed by snowflake id of the user. + * + * @return std::map The voice members of the channel + */ + std::map get_voice_members(); + + /** + * @brief Get the channel's icon url (if its a group DM), otherwise returns an empty string + * + * @param size The size of the icon in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized icon is returned. + * @return std::string icon url or empty string + */ + std::string get_icon_url(uint16_t size = 0) const; + + /** + * @brief Returns true if the channel is NSFW gated + * + * @return true if NSFW + */ + bool is_nsfw() const; + + /** + * @brief Returns true if the permissions are to be synced with the category it is in. + * Used only and set manually when using the reorder channels method. + * + * @return true if keeping permissions + */ + bool is_locked_permissions() const; + + /** + * @brief Returns true if the channel is a text channel + * + * @return true if text channel + */ + bool is_text_channel() const; + + /** + * @brief Returns true if the channel is a DM + * + * @return true if is a DM + */ + bool is_dm() const; + + /** + * @brief Returns true if the channel is a voice channel + * + * @return true if voice channel + */ + bool is_voice_channel() const; + + /** + * @brief Returns true if the channel is a group DM channel + * + * @return true if group DM + */ + bool is_group_dm() const; + + /** + * @brief Returns true if the channel is a category + * + * @return true if a category + */ + bool is_category() const; + + /** + * @brief Returns true if the channel is a forum + * + * @return true if a forum + */ + bool is_forum() const; + + /** + * @brief Returns true if the channel is an announcement channel + * + * @return true if announcement channel + */ + bool is_news_channel() const; + + /** + * @brief Returns true if the channel is a store channel + * @deprecated store channels are deprecated by Discord + * + * @return true if store channel + */ + bool is_store_channel() const; + + /** + * @brief Returns true if the channel is a stage channel + * + * @return true if stage channel + */ + bool is_stage_channel() const; + + /** + * @brief Returns true if video quality is auto + * + * @return true if video quality is auto + */ + bool is_video_auto() const; + + /** + * @brief Returns true if video quality is 720p + * + * @return true if video quality is 720p + */ + bool is_video_720p() const; + + /** + * @brief Returns true if channel is a pinned thread in forum + * + * @return true, if channel is a pinned thread in forum + */ + bool is_pinned_thread() const; + + /** + * @brief Returns true if a tag is required to be specified when creating a thread in a forum channel + * + * @return true, if a tag is required to be specified when creating a thread in a forum channel + */ + bool is_tag_required() const; + +}; + +/** @brief A definition of a discord thread. + * A thread is a superset of a channel. Not to be confused with `std::thread`! + */ +class DPP_EXPORT thread : public channel { +public: + /** + * @brief Thread member of current user if joined to the thread. + * Note this is only set by certain api calls otherwise contains default data + */ + thread_member member; + + /** Thread metadata (threads) */ + thread_metadata metadata; + + /** Created message. Only filled within the cluster::thread_create_in_forum() method */ + message msg; + + /** + * A list of dpp::forum_tag IDs that have been applied to a thread in a forum channel + */ + std::vector applied_tags; + + /** + * @brief Number of messages ever sent in the thread. + * It's similar to thread::message_count on message creation, but will not decrement the number when a message is deleted + */ + uint32_t total_messages_sent; + + /** + * @brief Number of messages (not including the initial message or deleted messages) of the thread. + * For threads created before July 1, 2022, the message count is inaccurate when it's greater than 50. + */ + uint8_t message_count; + + /** Approximate count of members in a thread (threads) */ + uint8_t member_count; + + /** + * @brief Construct a new thread object + */ + thread(); + + /** + * @brief Returns true if the thread is within an announcement channel + * + * @return true if announcement thread + */ + bool is_news_thread() const; + + /** + * @brief Returns true if the channel is a public thread + * + * @return true if public thread + */ + bool is_public_thread() const; + + /** + * @brief Returns true if the channel is a private thread + * + * @return true if private thread + */ + bool is_private_thread() const; + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + thread& fill_from_json(nlohmann::json* j); + + /** + * @brief Destroy the thread object + */ + virtual ~thread(); + + /** + * @brief Build json for this thread object + * + * @param with_id include the ID in the json + * @return std::string JSON string + */ + std::string build_json(bool with_id = false) const; + +}; + + +/** + * @brief Serialize a thread_metadata object to json + * + * @param j JSON object to serialize to + * @param tmdata object to serialize + */ +void to_json(nlohmann::json& j, const thread_metadata& tmdata); + +/** + * @brief Serialize a permission_overwrite object to json + * + * @param j JSON object to serialize to + * @param po object to serialize + */ +void to_json(nlohmann::json& j, const permission_overwrite& po); + +/** + * @brief A group of channels + */ +typedef std::unordered_map channel_map; + +/** + * @brief A group of threads + */ +typedef std::unordered_map thread_map; + +}; + diff --git a/3rdParty/dpp/cluster.h b/3rdParty/dpp/cluster.h index bb1a8cbab0..c52898962e 100644 --- a/3rdParty/dpp/cluster.h +++ b/3rdParty/dpp/cluster.h @@ -1,3341 +1,3341 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using json = nlohmann::json; - -namespace dpp { - -/** - * @brief Types of startup for cluster::start() - */ -enum start_type : bool { - /** - * @brief Wait forever on a condition variable. - * The cluster will spawn threads for each shard - * and start() will not return in normal operation. - */ - st_wait = false, - - /** - * @brief Return immediately after starting shard threads. - * If you set the parameter of cluster::start() to - * this value, you will have to manage the lifetime - * and scope of your cluster object yourself. Taking it - * out of scope or deleting its pointer will terminate - * the bot. - */ - st_return = true, -}; - -/** @brief The cluster class represents a group of shards and a command queue for sending and - * receiving commands from discord via HTTP. You should usually instantiate a cluster object - * at the very least to make use of the library. - */ -class DPP_EXPORT cluster { - - friend class discord_client; - friend class discord_voice_client; - - /** - * @brief default gateway for connecting the websocket. - */ - std::string default_gateway; - - /** - * @brief queue system for commands sent to Discord, and any replies - */ - request_queue* rest; - - /** - * @brief queue system for arbitrary HTTP requests sent by the user to sites other than Discord - */ - request_queue* raw_rest; - - /** - * @brief True if to use compression on shards - */ - bool compressed; - - /** - * @brief Lock to prevent concurrent access to dm_channels - */ - std::mutex dm_list_lock; - - /** - * @brief Start time of cluster - */ - time_t start_time; - - /** - * @brief Active DM channels for the bot - */ - std::unordered_map dm_channels; - - /** - * @brief Active shards on this cluster. Shard IDs may have gaps between if there - * are multiple clusters. - */ - shard_list shards; - - /** - * @brief List of all active registered timers - */ - timer_reg_t timer_list; - - /** - * @brief List of timers by time - */ - timer_next_t next_timer; - - /** - * @brief Tick active timers - */ - void tick_timers(); - - /** - * @brief Reschedule a timer for its next tick - * - * @param t Timer to reschedule - */ - void timer_reschedule(timer_t* t); -public: - /** - * @brief Current bot token for all shards on this cluster and all commands sent via HTTP - */ - std::string token; - - /** - * @brief Last time the bot sent an IDENTIFY - */ - time_t last_identify; - - /** - * @brief Current bitmask of gateway intents - */ - uint32_t intents; - - /** - * @brief Total number of shards across all clusters - */ - uint32_t numshards; - - /** - * @brief ID of this cluster, between 0 and MAXCLUSTERS-1 inclusive - */ - uint32_t cluster_id; - - /** - * @brief Total number of clusters that are active - */ - uint32_t maxclusters; - - /** - * @brief REST latency (HTTPS ping) in seconds - */ - double rest_ping; - - /** - * @brief The details of the bot user. This is assumed to be identical across all shards - * in the cluster. Each connecting shard updates this information. - */ - dpp::user me; - - /** - * @brief Current cache policy for the cluster - */ - cache_policy_t cache_policy; - - /** - * @brief Websocket mode for all shards in the cluster, either ws_json or ws_etf. - * Production bots should use ETF, while development bots should use JSON. - */ - websocket_protocol_t ws_mode; - - /** - * @brief Condition variable notified when the cluster is terminating. - */ - std::condition_variable terminating; - - /** - * @brief Constructor for creating a cluster. All but the token are optional. - * @param token The bot token to use for all HTTP commands and websocket connections - * @param intents A bitmask of dpd::intents values for all shards on this cluster. This is required to be sent for all bots with over 100 servers. - * @param shards The total number of shards on this bot. If there are multiple clusters, then (shards / clusters) actual shards will run on this cluster. - * If you omit this value, the library will attempt to query the Discord API for the correct number of shards to start. - * @param cluster_id The ID of this cluster, should be between 0 and MAXCLUSTERS-1 - * @param maxclusters The total number of clusters that are active, which may be on separate processes or even separate machines. - * @param compressed Whether or not to use compression for shards on this cluster. Saves a ton of bandwidth at the cost of some CPU - * @param policy Set the user caching policy for the cluster, either lazy (only cache users/members when they message the bot) or aggressive (request whole member lists on seeing new guilds too) - * @param request_threads The number of threads to allocate for making HTTP requests to Discord. This defaults to 12. You can increase this at runtime via the object returned from get_rest(). - * @param request_threads_raw The number of threads to allocate for making HTTP requests to sites outside of Discord. This defaults to 1. You can increase this at runtime via the object returned from get_raw_rest(). - * @throw dpp::exception Thrown on windows, if WinSock fails to initialise, or on any other system if a dpp::request_queue fails to construct - */ - cluster(const std::string& token, uint32_t intents = i_default_intents, uint32_t shards = 0, uint32_t cluster_id = 0, uint32_t maxclusters = 1, bool compressed = true, cache_policy_t policy = { cp_aggressive, cp_aggressive, cp_aggressive }, uint32_t request_threads = 12, uint32_t request_threads_raw = 1); - - /** - * @brief dpp::cluster is non-copyable - */ - cluster(const cluster&) = delete; - - /** - * @brief dpp::cluster is non-moveable - */ - cluster(const cluster&&) = delete; - - /** - * @brief Destroy the cluster object - */ - virtual ~cluster(); - - /** - * @brief End cluster execution without destructing it. - * To restart the cluster, call cluster::start() again. - */ - void shutdown(); - - /** - * @brief Get the rest_queue object which handles HTTPS requests to Discord - * @return request_queue* pointer to request_queue object - */ - request_queue* get_rest(); - - /** - * @brief Get the raw rest_queue object which handles all HTTP(S) requests that are not directed at Discord - * @return request_queue* pointer to request_queue object - */ - request_queue* get_raw_rest(); - - /** - * @brief Set the websocket protocol for all shards on this cluster. - * You should call this method before cluster::start. - * Generally ws_etf is faster, but provides less facilities for debugging should something - * go wrong. It is recommended to use ETF in production and JSON in development. - * - * @param mode websocket protocol to use, either ws_json or ws_etf. - * @return cluster& Reference to self for chaining. - */ - cluster& set_websocket_protocol(websocket_protocol_t mode); - - /** - * @brief Set the audit log reason for the next REST call to be made. - * This is set per-thread, so you must ensure that if you call this method, your request that - * is associated with the reason happens on the same thread where you set the reason. - * Once the next call is made, the audit log reason is cleared for this thread automatically. - * - * Example: - * ``` - * bot.set_audit_reason("Too much abusive content") - * .channel_delete(my_channel_id); - * ``` - * - * @param reason The reason to set for the next REST call on this thread - * @return cluster& Reference to self for chaining. - */ - cluster& set_audit_reason(const std::string &reason); - - /** - * @brief Clear the audit log reason for the next REST call to be made. - * This is set per-thread, so you must ensure that if you call this method, your request that - * is associated with the reason happens on the same thread where you set the reason. - * Once the next call is made, the audit log reason is cleared for this thread automatically. - * - * Example: - * ``` - * bot.set_audit_reason("Won't be sent") - * .clear_audit_reason() - * .channel_delete(my_channel_id); - * ``` - * - * @return cluster& Reference to self for chaining. - */ - cluster& clear_audit_reason(); - - /** - * @brief Get the audit reason set for the next REST call to be made on this thread. - * This is set per-thread, so you must ensure that if you call this method, your request that - * is associated with the reason happens on the same thread where you set the reason. - * Once the next call is made, the audit log reason is cleared for this thread automatically. - * - * @note This method call clears the audit reason when it returns it. - * - * @return std::string The audit reason to be used. - * - */ - std::string get_audit_reason(); - - /** - * @brief Sets the address of the default gateway, for connecting the websockets. - * - * @return cluster& Reference to self for chaining. - */ - cluster& set_default_gateway(std::string& default_gateway); - - /** - * @brief Log a message to whatever log the user is using. - * The logged message is passed up the chain to the on_log event in user code which can then do whatever - * it wants to do with it. - * @param severity The log level from dpp::loglevel - * @param msg The log message to output - */ - void log(dpp::loglevel severity, const std::string &msg) const; - - /** - * @brief Start a timer. Every `frequency` seconds, the callback is called. - * - * @param on_tick The callback lambda to call for this timer when ticked - * @param on_stop The callback lambda to call for this timer when it is stopped - * @param frequency How often to tick the timer in seconds - * @return timer A handle to the timer, used to remove that timer later - */ - timer start_timer(timer_callback_t on_tick, uint64_t frequency, timer_callback_t on_stop = {}); - - /** - * @brief Stop a ticking timer - * - * @param t Timer handle received from cluster::start_timer - * @return bool True if the timer was stopped, false if it did not exist - * @note If the timer has an on_stop lambda, the on_stop lambda will be called. - */ - bool stop_timer(timer t); - - /** - * @brief Get the dm channel for a user id - * - * @param user_id the user id to get the dm channel for - * @return Returns 0 on failure - */ - snowflake get_dm_channel(snowflake user_id); - - /** - * @brief Set the dm channel id for a user id - * - * @param user_id user id to set the dm channel for - * @param channel_id dm channel to set - */ - void set_dm_channel(snowflake user_id, snowflake channel_id); - - /** - * @brief Returns the uptime of the cluster - * - * @return dpp::utility::uptime The uptime of the cluster - */ - dpp::utility::uptime uptime(); - - /** - * @brief Start the cluster, connecting all its shards. - * - * Returns once all shards are connected if return_after is true, - * otherwise enters an infinite loop while the shards run. - * - * @param return_after If true the bot will return to your program after starting shards, if false this function will never return. - */ - void start(bool return_after = true); - - /** - * @brief Set the presence for all shards on the cluster - * - * @param p The presence to set. Only the online status and the first activity are sent. - */ - void set_presence(const class dpp::presence &p); - - /** - * @brief Get a shard by id, returning the discord_client - * - * @param id Shard ID - * @return discord_client* shard, or null - */ - discord_client* get_shard(uint32_t id); - - /** - * @brief Get the list of shards - * - * @return shard_list& Reference to map of shards for this cluster - */ - const shard_list& get_shards(); - - /* Functions for attaching to event handlers */ - - /** - * @brief on voice state update event - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type voice_state_update_t&, and returns void. - */ - event_router_t on_voice_state_update; - - - /** - * @brief on voice client disconnect event - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type voice_client_disconnect_t&, and returns void. - */ - event_router_t on_voice_client_disconnect; - - - /** - * @brief on voice client speaking event - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type voice_client_speaking_t&, and returns void. - */ - event_router_t on_voice_client_speaking; - - - /** - * @brief Called when a log message is to be written to the log. - * You can attach any logging system here you wish, e.g. spdlog, or even just a simple - * use of std::cout or printf. If nothing attaches this log event, then the - * library will be silent. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type log_t&, and returns void. - */ - event_router_t on_log; - - /** - * @brief on guild join request delete. - * Triggered when a user declines the membership screening questionnaire for a guild. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_join_request_delete_t&, and returns void. - */ - event_router_t on_guild_join_request_delete; - - - /** - * @brief Called when a new interaction is created. - * Interactions are created by discord when commands you have registered are issued - * by a user. For an example of this in action please see \ref slashcommands - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type interaction_create_t&, and returns void. - * - * @note There are dedicated events to handle slashcommands (See dpp::cluster::on_slashcommand), - * user context menus (See dpp::cluster::on_user_context_menu) and message context menus (See dpp::cluster::on_message_context_menu) - */ - event_router_t on_interaction_create; - - /** - * @brief Called when a slash command is issued. - * Only dpp::ctxm_chat_input types of interaction are routed to this event. - * For an example of this in action please see \ref slashcommands - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type slashcommand_t&, and returns void. - */ - event_router_t on_slashcommand; - - /** - * @brief Called when a button is clicked attached to a message. - * Button clicks are triggered by discord when buttons are clicked which you have - * associated with a message using dpp::component. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type button_click_t&, and returns void. - */ - event_router_t on_button_click; - - /** - * @brief Called when an auto completed field needs suggestions to present to the user - * This is triggered by discord when option choices have auto completion enabled which you have - * associated with a dpp::slashcommand. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type autocomplete_t&, and returns void. - */ - event_router_t on_autocomplete; - - - /** - * @brief Called when a select menu is clicked attached to a message. - * Select menu clicks are triggered by discord when select menus are clicked which you have - * associated with a message using dpp::component. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type select_click_t&, and returns void. - */ - event_router_t on_select_click; - - /** - * @brief Called when a user right-clicks or long-presses on a message, - * where a slash command is bound to the dpp::ctxm_message command type. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type message_context_menu_t&, and returns void. - */ - event_router_t on_message_context_menu; - - /** - * @brief Called when a user right-clicks or long-presses on a user, - * where a slash command is bound to the dpp::ctxm_user command type. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type user_context_menu_t&, and returns void. - */ - event_router_t on_user_context_menu; - - /** - * @brief Called when a modal dialog is submitted. - * Form submits are triggered by discord when modal dialogs are submitted which you have - * associated with a slash command using dpp::interaction_modal_response. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type form_submit_t&, and returns void. - */ - event_router_t on_form_submit; - - - /** - * @brief Called when a guild is deleted. - * A guild can be deleted via the bot being kicked, the bot leaving the guild - * explicitly with dpp::cluster::guild_delete, or via the guild being unavailable due to - * an outage. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_delete_t&, and returns void. - */ - event_router_t on_guild_delete; - - - /** - * @brief Called when a channel is deleted from a guild. - * The channel will still be temporarily available in the cache. Pointers to the - * channel should not be retained long-term as they will be deleted by the garbage - * collector. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type channel_delete_t&, and returns void. - */ - event_router_t on_channel_delete; - - - /** - * @brief Called when a channel is edited on a guild. - * The new channel details have already been applied to the guild when you - * receive this event. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type channel_update_t&, and returns void. - */ - event_router_t on_channel_update; - - - /** - * @brief Called when a shard is connected and ready. - * A set of cluster::on_guild_create events will follow this event. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type ready_t&, and returns void. - */ - event_router_t on_ready; - - - /** - * @brief Called when a message is deleted. - * The message has already been deleted from Discord when you - * receive this event. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type message_delete_t&, and returns void. - */ - event_router_t on_message_delete; - - - /** - * @brief Called when a user leaves a guild (either through being kicked, or choosing to leave) - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_member_remove_t&, and returns void. - */ - event_router_t on_guild_member_remove; - - - /** - * @brief Called when a connection to a shard successfully resumes. - * A resumed session does not need to re-synchronise guilds, members, etc. - * This is generally non-fatal and informational only. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type resumed_t&, and returns void. - */ - event_router_t on_resumed; - - - /** - * @brief Called when a new role is created on a guild. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_role_create_t&, and returns void. - */ - event_router_t on_guild_role_create; - - - /** - * @brief Called when a user is typing on a channel. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type typing_start_t&, and returns void. - */ - event_router_t on_typing_start; - - - /** - * @brief Called when a new reaction is added to a message. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type message_reaction_add_t&, and returns void. - */ - event_router_t on_message_reaction_add; - - - /** - * @brief Called when a set of members is received for a guild. - * D++ will request these for all new guilds if needed, after the cluster::on_guild_create - * events. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_members_chunk_t&, and returns void. - */ - event_router_t on_guild_members_chunk; - - - /** - * @brief Called when a single reaction is removed from a message. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type message_reaction_remove_t&, and returns void. - */ - event_router_t on_message_reaction_remove; - - - /** - * @brief Called when a new guild is created. - * D++ will request members for the guild for its cache using guild_members_chunk. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_create_t&, and returns void. - */ - event_router_t on_guild_create; - - - /** - * @brief Called when a new channel is created on a guild. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type channel_create_t&, and returns void. - */ - event_router_t on_channel_create; - - - /** - * @brief Called when all reactions for a particular emoji are removed from a message. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type message_reaction_remove_emoji_t&, and returns void. - */ - event_router_t on_message_reaction_remove_emoji; - - - /** - * @brief Called when multiple messages are deleted from a channel or DM. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type message_delete_bulk_t&, and returns void. - */ - event_router_t on_message_delete_bulk; - - - /** - * @brief Called when an existing role is updated on a guild. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_role_update_t&, and returns void. - */ - event_router_t on_guild_role_update; - - - /** - * @brief Called when a role is deleted in a guild. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_role_delete_t&, and returns void. - */ - event_router_t on_guild_role_delete; - - - /** - * @brief Called when a message is pinned. - * Note that the pinned message is not returned to this event, just the timestamp - * of the last pinned message. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type channel_pins_update_t&, and returns void. - */ - event_router_t on_channel_pins_update; - - - /** - * @brief Called when all reactions are removed from a message. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type message_reaction_remove_all_t&, and returns void. - */ - event_router_t on_message_reaction_remove_all; - - - /** - * @brief Called when we are told which voice server we can use. - * This will be sent either when we establish a new voice channel connection, - * or as discord rearrange their infrastructure. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type voice_server_update_t&, and returns void. - */ - event_router_t on_voice_server_update; - - - /** - * @brief Called when new emojis are added to a guild. - * The complete set of emojis is sent every time. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_emojis_update_t&, and returns void. - */ - event_router_t on_guild_emojis_update; - - - /** - * @brief Called when new stickers are added to a guild. - * The complete set of stickers is sent every time. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_stickers_update_t&, and returns void. - */ - event_router_t on_guild_stickers_update; - - - /** - * @brief Called when a user's presence is updated. - * To receive these you will need the GUILD_PRESENCES privileged intent. - * You will receive many of these, very often, and receiving them will significantly - * increase your bot's CPU usage. If you don't need them it is recommended to not ask - * for them. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type presence_update_t&, and returns void. - */ - event_router_t on_presence_update; - - - /** - * @brief Called when the webhooks for a guild are updated. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type webhooks_update_t&, and returns void. - */ - event_router_t on_webhooks_update; - - /** - * @brief Called when a new automod rule is created. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type automod_rule_create_t&, and returns void. - */ - event_router_t on_automod_rule_create; - - - /** - * @brief Called when an automod rule is updated. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type automod_rule_update_t&, and returns void. - */ - event_router_t on_automod_rule_update; - - /** - * @brief Called when an automod rule is deleted. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type automod_rule_delete_t&, and returns void. - */ - event_router_t on_automod_rule_delete; - - /** - * @brief Called when an automod rule is triggered/executed. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type automod_rule_execute_t&, and returns void. - */ - event_router_t on_automod_rule_execute; - - /** - * @brief Called when a new member joins a guild. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_member_add_t&, and returns void. - */ - event_router_t on_guild_member_add; - - - /** - * @brief Called when an invite is deleted from a guild. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type invite_delete_t&, and returns void. - */ - event_router_t on_invite_delete; - - - /** - * @brief Called when details of a guild are updated. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_update_t&, and returns void. - */ - event_router_t on_guild_update; - - - /** - * @brief Called when an integration is updated for a guild. - * This returns the complete list. - * An integration is a connection to a guild of a user's associated accounts, - * e.g. youtube or twitch, for automatic assignment of roles etc. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_integrations_update_t&, and returns void. - */ - event_router_t on_guild_integrations_update; - - - /** - * @brief Called when details of a guild member (e.g. their roles or nickname) are updated. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_member_update_t&, and returns void. - */ - event_router_t on_guild_member_update; - - - /** - * @brief Called when a new invite is created for a guild. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type invite_create_t&, and returns void. - */ - event_router_t on_invite_create; - - - /** - * @brief Called when a message is updated (edited). - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type message_update_t&, and returns void. - */ - event_router_t on_message_update; - - - /** - * @brief Called when a user is updated. - * This is separate to cluster::on_guild_member_update and includes things such as an avatar change, - * username change, discriminator change or change in subscription status for nitro. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type user_update_t&, and returns void. - */ - event_router_t on_user_update; - - - /** - * @brief Called when a new message arrives from discord. - * Note that D++ does not cache messages. If you want to cache these objects you - * should create something yourself within your bot. Caching of messages is not on - * the roadmap to be supported as it consumes excessive amounts of RAM. - * For an example for caching of messages, please see \ref caching-messages - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type message_create_t&, and returns void. - */ - event_router_t on_message_create; - - - /** - * @brief Called when a ban is added to a guild. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_ban_add_t&, and returns void. - */ - event_router_t on_guild_ban_add; - - - /** - * @brief Called when a ban is removed from a guild. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_ban_remove_t&, and returns void. - */ - event_router_t on_guild_ban_remove; - - - /** - * @brief Called when a new integration is attached to a guild by a user. - * An integration is a connection to a guild of a user's associated accounts, - * e.g. youtube or twitch, for automatic assignment of roles etc. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type integration_create_t&, and returns void. - */ - event_router_t on_integration_create; - - - /** - * @brief Called when an integration is updated by a user. - * This returns details of just the single integration that has changed. - * An integration is a connection to a guild of a user's associated accounts, - * e.g. youtube or twitch, for automatic assignment of roles etc. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type integration_update_t&, and returns void. - */ - event_router_t on_integration_update; - - - /** - * @brief Called when an integration is removed by a user. - * An integration is a connection to a guild of a user's associated accounts, - * e.g. youtube or twitch, for automatic assignment of roles etc. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type integration_delete_t&, and returns void. - */ - event_router_t on_integration_delete; - - - /** - * @brief Called when a thread is created. - * Note that threads are not cached by D++, but a list of thread IDs is accessible in a guild object - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type thread_create_t&, and returns void. - */ - event_router_t on_thread_create; - - - /** - * @brief Called when a thread is updated - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type thread_update_t&, and returns void. - */ - event_router_t on_thread_update; - - - /** - * @brief Called when a thread is deleted - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type thread_delete_t&, and returns void. - */ - event_router_t on_thread_delete; - - - /** - * @brief Called when thread list is synced (upon gaining access to a channel). - * Note that threads are not cached by D++, but a list of thread IDs is accessible in a guild object - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type thread_list_sync_t&, and returns void. - */ - event_router_t on_thread_list_sync; - - - /** - * @brief Called when current user's thread member object is updated - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type thread_member_update_t&, and returns void. - */ - event_router_t on_thread_member_update; - - - /** - * @brief Called when a thread's member list is updated (without GUILD_MEMBERS intent, is only called for current user) - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type thread_members_update_t&, and returns void. - */ - event_router_t on_thread_members_update; - - - /** - * @brief Called when a new scheduled event is created - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_scheduled_event_create_t&, and returns void. - */ - event_router_t on_guild_scheduled_event_create; - - - /** - * @brief Called when a new scheduled event is updated - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_scheduled_event_update_t&, and returns void. - */ - event_router_t on_guild_scheduled_event_update; - - - /** - * @brief Called when a new scheduled event is deleted - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_scheduled_event_delete_t&, and returns void. - */ - event_router_t on_guild_scheduled_event_delete; - - - /** - * @brief Called when a user is added to a scheduled event - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_scheduled_event_user_add_t&, and returns void. - */ - event_router_t on_guild_scheduled_event_user_add; - - - /** - * @brief Called when a user is removed to a scheduled event - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_scheduled_event_user_remove_t&, and returns void. - */ - event_router_t on_guild_scheduled_event_user_remove; - - - /** - * @brief Called when packets are sent from the voice buffer. - * The voice buffer contains packets that are already encoded with Opus and encrypted - * with Sodium, and merged into packets by the repacketizer, which is done in the - * dpp::discord_voice_client::send_audio method. You should use the buffer size properties - * of dpp::voice_buffer_send_t to determine if you should fill the buffer with more - * content. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type voice_buffer_send_t&, and returns void. - */ - event_router_t on_voice_buffer_send; - - - /** - * @brief Called when a user is talking on a voice channel. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type voice_user_talking_t&, and returns void. - */ - event_router_t on_voice_user_talking; - - - /** - * @brief Called when a voice channel is connected and ready to send audio. - * Note that this is not directly attached to the READY event of the websocket, - * as there is further connection that needs to be done before audio is ready to send. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type voice_ready_t&, and returns void. - */ - event_router_t on_voice_ready; - - - /** - * @brief Called when new audio data is received. - * Each separate user's audio from the voice channel will arrive tagged with - * their user id in the event, if a user can be attributed to the received audio. - * - * @note Receiving audio for bots is not officially supported by discord. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type voice_receive_t&, and returns void. - */ - event_router_t on_voice_receive; - - /** - * @brief Called when new audio data is received, combined and mixed for all speaking users. - * - * @note Receiving audio for bots is not officially supported by discord. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type voice_receive_t&, and returns void. - */ - event_router_t on_voice_receive_combined; - - /** - * @brief Called when sending of audio passes over a track marker. - * Track markers are arbitrarily placed "bookmarks" in the audio buffer, placed - * by the bot developer. Each track marker can have a string value associated with it - * which is specified in dpp::discord_voice_client::insert_marker and returned to this - * event. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type voice_track_marker_t&, and returns void. - */ - event_router_t on_voice_track_marker; - - - /** - * @brief Called when a new stage instance is created on a stage channel. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * - */ - event_router_t on_stage_instance_create; - - - /** - * @brief Called when a stage instance is updated. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type stage_instance_update_t&, and returns void. - */ - event_router_t on_stage_instance_update; - - - /** - * @brief Called when an existing stage instance is deleted from a stage channel. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type stage_instance_delete_t&, and returns void. - */ - event_router_t on_stage_instance_delete; - - - /** - * @brief Post a REST request. Where possible use a helper method instead like message_create - * - * @param endpoint Endpoint to post to, e.g. /api/guilds - * @param major_parameters Major parameters for the endpoint e.g. a guild id - * @param parameters Minor parameters for the API request - * @param method Method, e.g. GET, POST - * @param postdata Post data (usually JSON encoded) - * @param callback Function to call when the HTTP call completes. The callback parameter will contain amongst other things, the decoded json. - * @param filename Filename to post for POST requests (for uploading files) - * @param filecontent File content to post for POST requests (for uploading files) - */ - void post_rest(const std::string &endpoint, const std::string &major_parameters, const std::string ¶meters, http_method method, const std::string &postdata, json_encode_t callback, const std::string &filename = "", const std::string &filecontent = ""); - - /** - * @brief Post a multipart REST request. Where possible use a helper method instead like message_create - * - * @param endpoint Endpoint to post to, e.g. /api/guilds - * @param major_parameters Major parameters for the endpoint e.g. a guild id - * @param parameters Minor parameters for the API request - * @param method Method, e.g. GET, POST - * @param postdata Post data (usually JSON encoded) - * @param callback Function to call when the HTTP call completes. The callback parameter will contain amongst other things, the decoded json. - * @param filename List of filenames to post for POST requests (for uploading files) - * @param filecontent List of file content to post for POST requests (for uploading files) - */ - void post_rest_multipart(const std::string &endpoint, const std::string &major_parameters, const std::string ¶meters, http_method method, const std::string &postdata, json_encode_t callback, const std::vector &filename = {}, const std::vector &filecontent = {}); - - /** - * @brief Make a HTTP(S) request. For use when wanting asynchronous access to HTTP APIs outside of Discord. - * - * @param url Full URL to post to, e.g. https://api.somewhere.com/v1/foo/ - * @param method Method, e.g. GET, POST - * @param callback Function to call when the HTTP call completes. No processing is done on the returned data. - * @param postdata POST data - * @param mimetype MIME type of POST data - * @param headers Headers to send with the request - */ - void request(const std::string &url, http_method method, http_completion_event callback, const std::string &postdata = "", const std::string &mimetype = "text/plain", const std::multimap &headers = {}); - - /** - * @brief Respond to a slash command - * - * @see https://discord.com/developers/docs/interactions/receiving-and-responding#create-interaction-response - * @param interaction_id Interaction id to respond to - * @param token Token for the interaction webhook - * @param r Response to send - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void interaction_response_create(snowflake interaction_id, const std::string &token, const interaction_response &r, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit response to a slash command - * - * @see https://discord.com/developers/docs/interactions/receiving-and-responding#edit-original-interaction-response - * @param token Token for the interaction webhook - * @param m Message to send - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void interaction_response_edit(const std::string &token, const message &m, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Create a followup message to a slash command - * - * @param token Token for the interaction webhook - * @param m followup message to create - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void interaction_followup_create(const std::string &token, const message &m, command_completion_event_t callback); - - /** - * @brief Edit original followup message to a slash command - * This is an alias for cluster::interaction_response_edit - * @see cluster::interaction_response_edit - * - * @param token Token for the interaction webhook - * @param m message to edit, the ID should be set - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void interaction_followup_edit_original(const std::string &token, const message &m, command_completion_event_t callback = utility::log_error()); - - /** - * @brief - * - * @param token Token for the interaction webhook - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void interaction_followup_delete(const std::string &token, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit followup message to a slash command - * The message ID in the message you pass should be correctly set to that of a followup message you previously sent - * @param token Token for the interaction webhook - * @param m message to edit, the ID should be set - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void interaction_followup_edit(const std::string &token, const message &m, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get the followup message to a slash command - * @param token Token for the interaction webhook - * @param message_id message to retrieve - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void interaction_followup_get(const std::string &token, snowflake message_id, command_completion_event_t callback); - - /** - * @brief Create a global slash command (a bot can have a maximum of 100 of these). - * - * @see https://discord.com/developers/docs/interactions/application-commands#create-global-application-command - * @param s Slash command to create - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::slashcommand object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void global_command_create(const slashcommand &s, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get a global slash command - * - * @see https://discord.com/developers/docs/interactions/application-commands#get-global-application-command - * @param id The ID of the slash command - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::slashcommand object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void global_command_get(snowflake id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get the audit log for a guild - * - * @see https://discord.com/developers/docs/resources/audit-log#get-guild-audit-log - * @param guild_id Guild to get the audit log of - * @param user_id Entries from a specific user ID. Set this to `0` will fetch any user - * @param action_type Entries for a specific dpp::audit_type. Set this to `0` will fetch any type - * @param before Entries that preceded a specific audit log entry ID. Used for paginating - * @param limit Maximum number of entries (between 1-100) to return - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::auditlog object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_auditlog_get(snowflake guild_id, snowflake user_id, uint32_t action_type, snowflake before, uint32_t limit, command_completion_event_t callback); - - /** - * @brief Create a slash command local to a guild - * - * @see https://discord.com/developers/docs/interactions/application-commands#create-guild-application-command - * @note Creating a command with the same name as an existing command for your application will overwrite the old command. - * @param s Slash command to create - * @param guild_id Guild ID to create the slash command in - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::slashcommand object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_command_create(const slashcommand &s, snowflake guild_id, command_completion_event_t callback = utility::log_error()); - - - /** - * @brief Create/overwrite guild slash commands. - * Any existing guild slash commands on this guild will be deleted and replaced with these. - * - * @see https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-guild-application-commands - * @param commands Vector of slash commands to create/update. - * New guild commands will be available in the guild immediately. If the command did not already exist, it will count toward daily application command create limits. - * @param guild_id Guild ID to create/update the slash commands in - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::slashcommand_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_bulk_command_create(const std::vector &commands, snowflake guild_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Create/overwrite global slash commands. - * Any existing global slash commands will be deleted and replaced with these. - * - * @see https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-global-application-commands - * @param commands Vector of slash commands to create/update. - * overwriting existing commands that are registered globally for this application. Updates will be available in all guilds after 1 hour. - * Commands that do not already exist will count toward daily application command create limits. - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::slashcommand_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void global_bulk_command_create(const std::vector &commands, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit a global slash command (a bot can have a maximum of 100 of these) - * - * @see https://discord.com/developers/docs/interactions/application-commands#edit-global-application-command - * @param s Slash command to change - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void global_command_edit(const slashcommand &s, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get a slash command of a guild - * - * @see https://discord.com/developers/docs/interactions/application-commands#get-guild-application-command - * @note The returned slash commands will not have permissions set, you need to use a permissions getter e.g. dpp::guild_commands_get_permissions to get the guild command permissions - * @param id The ID of the slash command - * @param guild_id Guild ID to get the slash command from - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::slashcommand object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_command_get(snowflake id, snowflake guild_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit a slash command local to a guild - * - * @see https://discord.com/developers/docs/interactions/application-commands#edit-guild-application-command - * @param s Slash command to edit - * @param guild_id Guild ID to edit the slash command in - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_command_edit(const slashcommand &s, snowflake guild_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit slash command permissions of a guild - * - * @see https://discord.com/developers/docs/interactions/application-commands#edit-application-command-permissions - * @note You can only add up to 10 permission overwrites for a command - * @param s Slash command to edit the permissions for - * @param guild_id Guild ID to edit the slash command in - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_command_edit_permissions(const slashcommand &s, snowflake guild_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get the permissions for a slash command of a guild - * - * @see https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions - * @param id The ID of the slash command to get the permissions for - * @param guild_id Guild ID to get the permissions of - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild_command_permissions object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_command_get_permissions(snowflake id, snowflake guild_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit/Overwrite the permissions of all existing slash commands in a guild - * - * @note You can only add up to 10 permission overwrites for a command - * - * @see https://discord.com/developers/docs/interactions/application-commands#batch-edit-application-command-permissions - * @warning The endpoint will overwrite all existing permissions for all commands of the application in a guild, including slash commands, user commands, and message commands. Meaning that if you forgot to pass a slash command, the permissions of it might be removed. - * @param commands A vector of slash commands to edit/overwrite the permissions for - * @param guild_id Guild ID to edit permissions of the slash commands in - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild_command_permissions_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - * @deprecated This has been disabled with updates to Permissions v2. You can use guild_command_edit_permissions instead - */ - void guild_bulk_command_edit_permissions(const std::vector &commands, snowflake guild_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a global slash command (a bot can have a maximum of 100 of these) - * - * @see https://discord.com/developers/docs/interactions/application-commands#delete-global-application-command - * @param id Slash command to delete - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void global_command_delete(snowflake id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a slash command local to a guild - * - * @see https://discord.com/developers/docs/interactions/application-commands#delete-guild-application-command - * @param id Slash command to delete - * @param guild_id Guild ID to delete the slash command in - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_command_delete(snowflake id, snowflake guild_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get the application's slash commands for a guild - * - * @see https://discord.com/developers/docs/interactions/application-commands#get-guild-application-commands - * @note The returned slash commands will not have permissions set, you need to use a permissions getter e.g. dpp::guild_commands_get_permissions to get the guild command permissions - * @param guild_id Guild ID to get the slash commands for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::slashcommand_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_commands_get(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Get all slash command permissions of a guild - * - * @see https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions - * @param guild_id Guild ID to get the slash commands permissions for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild_command_permissions_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_commands_get_permissions(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Get the application's global slash commands - * - * @see https://discord.com/developers/docs/interactions/application-commands#get-global-application-commands - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::slashcommand_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void global_commands_get(command_completion_event_t callback); - - /** - * @brief Create a direct message, also create the channel for the direct message if needed - * - * @see https://discord.com/developers/docs/resources/user#create-dm - * @see https://discord.com/developers/docs/resources/channel#create-message - * @param user_id User ID of user to send message to - * @param m Message object - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void direct_message_create(snowflake user_id, const message &m, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get a message - * - * @see https://discord.com/developers/docs/resources/channel#get-channel-message - * @param message_id Message ID - * @param channel_id Channel ID - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_get(snowflake message_id, snowflake channel_id, command_completion_event_t callback); - - /** - * @brief Get multiple messages. - * - * This function will attempt to fetch as many messages as possible using multiple API calls if needed. - * - * @see https://discord.com/developers/docs/resources/channel#get-channel-messages - * @param channel_id Channel ID to retrieve messages for - * @param around Messages should be retrieved around this ID if this is set to non-zero - * @param before Messages before this ID should be retrieved if this is set to non-zero - * @param after Messages after this ID should be retrieved if this is set to non-zero - * @param limit This number of messages maximum should be returned, up to a maximum of 100. - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::message_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void messages_get(snowflake channel_id, snowflake around, snowflake before, snowflake after, uint64_t limit, command_completion_event_t callback); - - /** - * @brief Send a message to a channel. The callback function is called when the message has been sent - * - * @see https://discord.com/developers/docs/resources/channel#create-message - * @param m Message to send - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_create(const struct message &m, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Crosspost a message. The callback function is called when the message has been sent - * - * @see https://discord.com/developers/docs/resources/channel#crosspost-message - * @param message_id Message to crosspost - * @param channel_id Channel ID to crosspost from - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_crosspost(snowflake message_id, snowflake channel_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit a message on a channel. The callback function is called when the message has been edited - * - * @see https://discord.com/developers/docs/resources/channel#edit-message - * @param m Message to edit - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_edit(const struct message &m, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Add a reaction to a message. The reaction string must be either an `emojiname:id` or a unicode character. - * - * @see https://discord.com/developers/docs/resources/channel#create-reaction - * @param m Message to add a reaction to - * @param reaction Reaction to add. Emojis should be in the form emojiname:id - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_add_reaction(const struct message &m, const std::string &reaction, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete own reaction from a message. The reaction string must be either an `emojiname:id` or a unicode character. - * - * @see https://discord.com/developers/docs/resources/channel#delete-own-reaction - * @param m Message to delete own reaction from - * @param reaction Reaction to delete. The reaction should be in the form emojiname:id - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_delete_own_reaction(const struct message &m, const std::string &reaction, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a user's reaction from a message. The reaction string must be either an `emojiname:id` or a unicode character - * - * @see https://discord.com/developers/docs/resources/channel#delete-user-reaction - * @param m Message to delete a user's reaction from - * @param user_id User ID who's reaction you want to remove - * @param reaction Reaction to remove. Reactions should be in the form emojiname:id - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_delete_reaction(const struct message &m, snowflake user_id, const std::string &reaction, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get reactions on a message for a particular emoji. The reaction string must be either an `emojiname:id` or a unicode character - * - * @see https://discord.com/developers/docs/resources/channel#get-reactions - * @param m Message to get reactions for - * @param reaction Reaction should be in the form emojiname:id or a unicode character - * @param before Reactions before this ID should be retrieved if this is set to non-zero - * @param after Reactions before this ID should be retrieved if this is set to non-zero - * @param limit This number of reactions maximum should be returned - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::user_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_get_reactions(const struct message &m, const std::string &reaction, snowflake before, snowflake after, snowflake limit, command_completion_event_t callback); - - /** - * @brief Delete all reactions on a message - * - * @see https://discord.com/developers/docs/resources/channel#delete-all-reactions - * @param m Message to delete reactions from - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_delete_all_reactions(const struct message &m, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete all reactions on a message using a particular emoji. The reaction string must be either an `emojiname:id` or a unicode character - * - * @see https://discord.com/developers/docs/resources/channel#delete-all-reactions-for-emoji - * @param m Message to delete reactions from - * @param reaction Reaction to delete, in the form emojiname:id or a unicode character - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_delete_reaction_emoji(const struct message &m, const std::string &reaction, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Add a reaction to a message by id. The reaction string must be either an `emojiname:id` or a unicode character. - * - * @see https://discord.com/developers/docs/topics/gateway#message-reaction-add - * @param message_id Message to add reactions to - * @param channel_id Channel to add reactions to - * @param reaction Reaction to add. Emojis should be in the form emojiname:id - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_add_reaction(snowflake message_id, snowflake channel_id, const std::string &reaction, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete own reaction from a message by id. The reaction string must be either an `emojiname:id` or a unicode character. - * - * @see https://discord.com/developers/docs/resources/channel#delete-own-reaction - * @param message_id Message to delete reactions from - * @param channel_id Channel to delete reactions from - * @param reaction Reaction to delete. The reaction should be in the form emojiname:id - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_delete_own_reaction(snowflake message_id, snowflake channel_id, const std::string &reaction, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a user's reaction from a message by id. The reaction string must be either an `emojiname:id` or a unicode character - * - * @see https://discord.com/developers/docs/resources/channel#delete-user-reaction - * @param message_id Message to delete reactions from - * @param channel_id Channel to delete reactions from - * @param user_id User ID who's reaction you want to remove - * @param reaction Reaction to remove. Reactions should be in the form emojiname:id - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_delete_reaction(snowflake message_id, snowflake channel_id, snowflake user_id, const std::string &reaction, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get reactions on a message for a particular emoji by id. The reaction string must be either an `emojiname:id` or a unicode character - * - * @see https://discord.com/developers/docs/resources/channel#get-reactions - * @param message_id Message to get reactions for - * @param channel_id Channel to get reactions for - * @param reaction Reaction should be in the form emojiname:id or a unicode character - * @param before Reactions before this ID should be retrieved if this is set to non-zero - * @param after Reactions before this ID should be retrieved if this is set to non-zero - * @param limit This number of reactions maximum should be returned - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::user_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_get_reactions(snowflake message_id, snowflake channel_id, const std::string &reaction, snowflake before, snowflake after, snowflake limit, command_completion_event_t callback); - - /** - * @brief Delete all reactions on a message by id - * - * @see https://discord.com/developers/docs/resources/channel#delete-all-reactions - * @param message_id Message to delete reactions from - * @param channel_id Channel to delete reactions from - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_delete_all_reactions(snowflake message_id, snowflake channel_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete all reactions on a message using a particular emoji by id. The reaction string must be either an `emojiname:id` or a unicode character - * - * @see https://discord.com/developers/docs/resources/channel#delete-all-reactions-for-emoji - * @param message_id Message to delete reactions from - * @param channel_id Channel to delete reactions from - * @param reaction Reaction to delete, in the form emojiname:id or a unicode character - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_delete_reaction_emoji(snowflake message_id, snowflake channel_id, const std::string &reaction, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a message from a channel. The callback function is called when the message has been edited - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see https://discord.com/developers/docs/resources/channel#delete-message - * @param message_id Message ID to delete - * @param channel_id Channel to delete from - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_delete(snowflake message_id, snowflake channel_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Bulk delete messages from a channel. The callback function is called when the message has been edited - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @note If any message provided older than 2 weeks or any duplicate message ID, it will fail. - * - * @see https://discord.com/developers/docs/resources/channel#bulk-delete-messages - * @param message_ids List of message IDs to delete (at least 2 and at most 100 message IDs) - * @param channel_id Channel to delete from - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_delete_bulk(const std::vector &message_ids, snowflake channel_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get a channel - * - * @see https://discord.com/developers/docs/resources/channel#get-channel - * @param c Channel ID to retrieve - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::channel object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_get(snowflake c, command_completion_event_t callback); - - /** - * @brief Get all channels for a guild - * - * @see https://discord.com/developers/docs/resources/channel#get-channels - * @param guild_id Guild ID to retrieve channels for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::channel_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channels_get(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Create a channel - * - * Create a new channel object for the guild. Requires the `MANAGE_CHANNELS` permission. If setting permission overwrites, - * only permissions your bot has in the guild can be allowed/denied. Setting `MANAGE_ROLES` permission in channels is only possible - * for guild administrators. Returns the new channel object on success. Fires a `Channel Create Gateway` event. - * - * All parameters to this endpoint are optional excluding `name` - * - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/channel#create-channel - * @param c Channel to create - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::channel object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_create(const class channel &c, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit a channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/channel#modify-channel - * @param c Channel to edit/update - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::channel object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_edit(const class channel &c, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit multiple channels positions - * - * Modify the positions of a set of channel objects for the guild. - * Requires `MANAGE_CHANNELS` permission. Fires multiple `Channel Update Gateway` events. - * Only channels to be modified are required. - * - * @see https://discord.com/developers/docs/resources/guild#modify-guild-channel-positions - * @param c Channel to change the position for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_edit_positions(const std::vector &c, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit a channel's permissions - * - * @see https://discord.com/developers/docs/resources/channel#edit-channel-permissions - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param c Channel to set permissions for - * @param overwrite_id Overwrite to change (a user or role ID) - * @param allow allow permissions bitmask - * @param deny deny permissions bitmask - * @param member true if the overwrite_id is a user id, false if it is a channel id - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_edit_permissions(const class channel &c, const snowflake overwrite_id, const uint64_t allow, const uint64_t deny, const bool member, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit a channel's permissions - * - * @see https://discord.com/developers/docs/resources/channel#edit-channel-permissions - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param channel_id ID of the channel to set permissions for - * @param overwrite_id Overwrite to change (a user or role ID) - * @param allow allow permissions bitmask - * @param deny deny permissions bitmask - * @param member true if the overwrite_id is a user id, false if it is a channel id - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_edit_permissions(const snowflake channel_id, const snowflake overwrite_id, const uint64_t allow, const uint64_t deny, const bool member, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/channel#deleteclose-channel - * @param channel_id Channel id to delete - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_delete(snowflake channel_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get details about an invite - * - * @see https://discord.com/developers/docs/resources/invite#get-invite - * @param invite Invite code to get information on - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::invite object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void invite_get(const std::string &invite, command_completion_event_t callback); - - /** - * @brief Delete an invite - * - * @see https://discord.com/developers/docs/resources/invite#delete-invite - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param invite Invite code to delete - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::invite object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void invite_delete(const std::string &invite, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get invites for a channel - * - * @see https://discord.com/developers/docs/resources/invite#get-invites - * @param c Channel to get invites for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::invite_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_invites_get(const class channel &c, command_completion_event_t callback); - - /** - * @brief Create invite for a channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/channel#create-channel-invite - * @param c Channel to create an invite on - * @param i Invite to create - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::invite object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_invite_create(const class channel &c, const class invite &i, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get a channel's pins - * @see https://discord.com/developers/docs/resources/channel#get-pinned-messages - * @param channel_id Channel ID to get pins for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::message_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_pins_get(snowflake channel_id, command_completion_event_t callback); - - /** - * @brief Adds a recipient to a Group DM using their access token - * @see https://discord.com/developers/docs/resources/channel#group-dm-add-recipient - * @param channel_id Channel id to add group DM recipients to - * @param user_id User ID to add - * @param access_token Access token from OAuth2 - * @param nick Nickname of user to apply to the chat - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void gdm_add(snowflake channel_id, snowflake user_id, const std::string &access_token, const std::string &nick, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Removes a recipient from a Group DM - * @see https://discord.com/developers/docs/resources/channel#group-dm-remove-recipient - * @param channel_id Channel ID of group DM - * @param user_id User ID to remove from group DM - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void gdm_remove(snowflake channel_id, snowflake user_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Remove a permission from a channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/channel#delete-channel-permission - * @param c Channel to remove permission from - * @param overwrite_id Overwrite to remove, user or channel ID - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_delete_permission(const class channel &c, snowflake overwrite_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Follow an announcement (news) channel - * @see https://discord.com/developers/docs/resources/channel#follow-news-channel - * @param c Channel id to follow - * @param target_channel_id Channel to subscribe the channel to - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_follow_news(const class channel &c, snowflake target_channel_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Trigger channel typing indicator - * @see https://discord.com/developers/docs/resources/channel#trigger-typing-indicator - * @param c Channel to set as typing on - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_typing(const class channel &c, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Trigger channel typing indicator - * @see https://discord.com/developers/docs/resources/channel#trigger-typing-indicator - * @param cid Channel ID to set as typing on - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_typing(snowflake cid, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Pin a message - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/channel#pin-message - * @param channel_id Channel id to pin message on - * @param message_id Message id to pin message on - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_pin(snowflake channel_id, snowflake message_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Unpin a message - * @see https://discord.com/developers/docs/resources/channel#unpin-message - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param channel_id Channel id to unpin message on - * @param message_id Message id to unpin message on - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_unpin(snowflake channel_id, snowflake message_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get a guild - * - * Returns the guild object for the given id. This endpoint will also return approximate_member_count and approximate_presence_count - * for the guild. - * @see https://discord.com/developers/docs/resources/guild#get-guild - * @param g Guild ID to retrieve - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_get(snowflake g, command_completion_event_t callback); - - /** - * @brief Get a guild preview. Returns a guild object but only a subset of the fields will be populated. - * - * Returns the guild preview object for the given id `g`. If the user is not in the guild, then the guild - * must be lurkable (it must be Discoverable or have a live public stage). - * @see https://discord.com/developers/docs/resources/guild#get-guild-preview - * @param g Guild ID to retrieve - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_get_preview(snowflake g, command_completion_event_t callback); - - /** - * @brief Get a guild member - * @see https://discord.com/developers/docs/resources/guild#get-guild-member - * @param guild_id Guild ID to get member for - * @param user_id User ID of member to get - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild_member object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_get_member(snowflake guild_id, snowflake user_id, command_completion_event_t callback); - - /** - * @brief Search for guild members based on whether their username or nickname starts with the given string. - * - * @note This endpoint is restricted according to whether the `GUILD_MEMBERS` Privileged Intent is enabled for your application. - * @see https://discord.com/developers/docs/resources/guild#search-guild-members - * @param guild_id Guild ID to search in - * @param query Query string to match username(s) and nickname(s) against - * @param limit max number of members to return (1-1000) - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild_member_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_search_members(snowflake guild_id, const std::string& query, uint16_t limit, command_completion_event_t callback); - - /** - * @brief Get all guild members - * - * @note This endpoint is restricted according to whether the `GUILD_MEMBERS` Privileged Intent is enabled for your application. - * @see https://discord.com/developers/docs/resources/guild#get-guild-members - * @param guild_id Guild ID to get all members for - * @param limit max number of members to return (1-1000) - * @param after the highest user id in the previous page - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild_member_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_get_members(snowflake guild_id, uint16_t limit, snowflake after, command_completion_event_t callback); - - /** - * @brief Add guild member. Needs a specific oauth2 scope, from which you get the access_token. - * - * Adds a user to the guild, provided you have a valid oauth2 access token for the user with the guilds.join scope. - * Returns the guild_member, which is defaulted if the user is already a member of the guild. Fires a `Guild Member Add` Gateway event. - * - * For guilds with Membership Screening enabled, this endpoint will default to adding new members as pending in the guild member object. - * Members that are pending will have to complete membership screening before they become full members that can talk. - * - * @note All parameters to this endpoint except for access_token are optional. - * The bot must be a member of the guild with `CREATE_INSTANT_INVITE` permission. - * @see https://discord.com/developers/docs/resources/guild#add-guild-member - * @param gm Guild member to add - * @param access_token Access token from Oauth2 scope - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild_member object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_add_member(const guild_member& gm, const std::string &access_token, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit the properties of an existing guild member - * - * Modify attributes of a guild member. Returns the guild_member. Fires a `Guild Member Update` Gateway event. - * To remove a timeout, set the `communication_disabled_until` to a non-zero time in the past, e.g. 1. - * When moving members to channels, the API user must have permissions to both connect to the channel and have the `MOVE_MEMBERS` permission. - * For moving and disconnecting users from voice, use dpp::cluster::guild_member_move. - * @see https://discord.com/developers/docs/resources/guild#modify-guild-member - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param gm Guild member to edit - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild_member object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_edit_member(const guild_member& gm, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Moves the guild member to a other voice channel, if member is connected to one. - * Set the `channel_id` to `0` to disconnect the user. - * - * Fires a `Guild Member Update` Gateway event. - * @note When moving members to channels, the API user __must__ have permissions to both connect to the channel and have the `MOVE_MEMBERS` permission. - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/guild#modify-guild-member - * @param channel_id Id of the channel to which the user is used. Set to `0` to disconnect the user - * @param guild_id Guild id to which the user is connected - * @param user_id User id, who should be moved - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild_member object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_member_move(const snowflake channel_id, const snowflake guild_id, const snowflake user_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Change current user nickname - * - * Modifies the nickname of the current user in a guild. - * Fires a `Guild Member Update` Gateway event. - * - * @deprecated Deprecated in favor of Modify Current Member. Will be replaced by dpp::cluster::guild_current_member_edit - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/guild#modify-current-user-nick - * @param guild_id Guild ID to change nickname on - * @param nickname New nickname, or empty string to clear nickname - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_set_nickname(snowflake guild_id, const std::string &nickname, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Add role to guild member - * - * Adds a role to a guild member. Requires the `MANAGE_ROLES` permission. - * Fires a `Guild Member Update` Gateway event. - * @see https://discord.com/developers/docs/resources/guild#add-guild-member-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to add a role to - * @param user_id User ID to add role to - * @param role_id Role ID to add to the user - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_member_add_role(snowflake guild_id, snowflake user_id, snowflake role_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Remove role from guild member - * - * Removes a role from a guild member. Requires the `MANAGE_ROLES` permission. - * Fires a `Guild Member Update` Gateway event. - * @see https://discord.com/developers/docs/resources/guild#remove-guild-member-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to remove role from user on - * @param user_id User ID to remove role from - * @param role_id Role to remove - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - * @deprecated Use dpp::cluster::guild_member_remove_role instead - */ - void guild_member_delete_role(snowflake guild_id, snowflake user_id, snowflake role_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Remove role from guild member - * - * Removes a role from a guild member. Requires the `MANAGE_ROLES` permission. - * Fires a `Guild Member Update` Gateway event. - * @see https://discord.com/developers/docs/resources/guild#remove-guild-member-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to remove role from user on - * @param user_id User ID to remove role from - * @param role_id Role to remove - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_member_remove_role(snowflake guild_id, snowflake user_id, snowflake role_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Remove (kick) a guild member - * - * Remove a member from a guild. Requires `KICK_MEMBERS` permission. - * Fires a `Guild Member Remove` Gateway event. - * @see https://discord.com/developers/docs/resources/guild#remove-guild-member - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @deprecated Replaced by dpp::cluster::guild_member_kick - * @param guild_id Guild ID to kick member from - * @param user_id User ID to kick - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_member_delete(snowflake guild_id, snowflake user_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Remove (kick) a guild member - * - * Remove a member from a guild. Requires `KICK_MEMBERS` permission. - * Fires a `Guild Member Remove` Gateway event. - * @see https://discord.com/developers/docs/resources/guild#remove-guild-member - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to kick member from - * @param user_id User ID to kick - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_member_kick(snowflake guild_id, snowflake user_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Set the timeout of a guild member - * - * Fires a `Guild Member Update` Gateway event. - * @see https://discord.com/developers/docs/resources/guild#modify-guild-member - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to timeout the member in - * @param user_id User ID to set the timeout for - * @param communication_disabled_until The timestamp when the user's timeout will expire (up to 28 days in the future). Set to 0 to remove the timeout - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_member_timeout(snowflake guild_id, snowflake user_id, time_t communication_disabled_until, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Add guild ban - * - * Create a guild ban, and optionally delete previous messages sent by the banned user. - * Requires the `BAN_MEMBERS` permission. Fires a `Guild Ban Add` Gateway event. - * @see https://discord.com/developers/docs/resources/guild#create-guild-ban - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to add ban to - * @param user_id User ID to ban - * @param delete_message_seconds How many seconds to delete messages for, between 0 and 604800 (7 days). Defaults to 0 - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_ban_add(snowflake guild_id, snowflake user_id, uint32_t delete_message_seconds = 0, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete guild ban - * - * Remove the ban for a user. Requires the `BAN_MEMBERS` permissions. - * Fires a Guild Ban Remove Gateway event. - * @see https://discord.com/developers/docs/resources/guild#remove-guild-ban - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild to delete ban from - * @param user_id User ID to delete ban for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_ban_delete(snowflake guild_id, snowflake user_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get guild ban list - * - * Requires the `BAN_MEMBERS` permission. - * @see https://discord.com/developers/docs/resources/guild#get-guild-bans - * @note Provide a user ID to `before` and `after` for pagination. Users will always be returned in ascending order by the user ID. If both before and after are provided, only before is respected. - * @param guild_id Guild ID to get bans for - * @param before If non-zero, all bans for user ids before this user id will be returned up to the limit - * @param after if non-zero, all bans for user ids after this user id will be returned up to the limit - * @param limit the maximum number of bans to retrieve in this call up to a maximum of 1000 - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::ban_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_get_bans(snowflake guild_id, snowflake before, snowflake after, snowflake limit, command_completion_event_t callback); - - /** - * @brief Get single guild ban - * - * Requires the `BAN_MEMBERS` permission. - * @see https://discord.com/developers/docs/resources/guild#get-guild-ban - * @param guild_id Guild ID to get ban for - * @param user_id User ID of ban to retrieve - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::ban object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_get_ban(snowflake guild_id, snowflake user_id, command_completion_event_t callback); - - /** - * @brief Get a template - * @see https://discord.com/developers/docs/resources/guild-template#get-guild-template - * @param code Template code - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::dtemplate object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void template_get(const std::string &code, command_completion_event_t callback); - - /** - * @brief Create a new guild based on a template. - * @note This endpoint can be used only by bots in less than 10 guilds. - * @see https://discord.com/developers/docs/resources/guild-template#create-guild-from-guild-template - * @param code Template code to create guild from - * @param name Guild name to create - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_create_from_template(const std::string &code, const std::string &name, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get guild templates - * - * @see https://discord.com/developers/docs/resources/guild-template#get-guild-templates - * @param guild_id Guild ID to get templates for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::dtemplate_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_templates_get(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Creates a template for the guild - * - * @see https://discord.com/developers/docs/resources/guild-template#create-guild-template - * @param guild_id Guild to create template from - * @param name Template name to create - * @param description Description of template to create - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::dtemplate object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_template_create(snowflake guild_id, const std::string &name, const std::string &description, command_completion_event_t callback); - - /** - * @brief Syncs the template to the guild's current state. - * - * @see https://discord.com/developers/docs/resources/guild-template#sync-guild-template - * @param guild_id Guild to synchronise template for - * @param code Code of template to synchronise - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::dtemplate object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_template_sync(snowflake guild_id, const std::string &code, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Modifies the template's metadata. - * - * @see https://discord.com/developers/docs/resources/guild-template#modify-guild-template - * @param guild_id Guild ID of template to modify - * @param code Template code to modify - * @param name New name of template - * @param description New description of template - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::dtemplate object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_template_modify(snowflake guild_id, const std::string &code, const std::string &name, const std::string &description, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Deletes the template - * - * @see https://discord.com/developers/docs/resources/guild-template#delete-guild-template - * @param guild_id Guild ID of template to delete - * @param code Template code to delete - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_template_delete(snowflake guild_id, const std::string &code, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Create a guild - * - * Create a new guild. Returns a guild object on success. `Fires a Guild Create Gateway` event. - * - * When using the roles parameter, the first member of the array is used to change properties of the guild's everyone role. - * If you are trying to bootstrap a guild with additional roles, keep this in mind. The required id field within each role object is an - * integer placeholder, and will be replaced by the API upon consumption. Its purpose is to allow you to overwrite a role's permissions - * in a channel when also passing in channels with the channels array. - * When using the channels parameter, the position field is ignored, and none of the default channels are created. The id field within - * each channel object may be set to an integer placeholder, and will be replaced by the API upon consumption. Its purpose is to - * allow you to create `GUILD_CATEGORY` channels by setting the `parent_id` field on any children to the category's id field. - * Category channels must be listed before any children. - * - * @see https://discord.com/developers/docs/resources/guild#create-guild - * @note The region field is deprecated and is replaced by channel.rtc_region. This endpoint can be used only by bots in less than 10 guilds. - * @param g Guild to create - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_create(const class guild &g, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit a guild - * - * Modify a guild's settings. Requires the `MANAGE_GUILD` permission. Returns the updated guild object on success. - * Fires a `Guild Update Gateway` event. - * - * @see https://discord.com/developers/docs/resources/guild#modify-guild - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param g Guild to edit - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_edit(const class guild &g, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a guild - * - * Delete a guild permanently. User must be owner. Fires a `Guild Delete Gateway` event. - * - * @see https://discord.com/developers/docs/resources/guild#delete-guild - * @param guild_id Guild ID to delete - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_delete(snowflake guild_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get all emojis for a guild - * - * @see https://discord.com/developers/docs/resources/emoji#get-guild-emojis - * @param guild_id Guild ID to get emojis for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::emoji_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_emojis_get(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Get a single emoji - * - * @see https://discord.com/developers/docs/resources/emoji#get-guild-emoji - * @param guild_id Guild ID to get emoji for - * @param emoji_id Emoji ID to get - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::emoji object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_emoji_get(snowflake guild_id, snowflake emoji_id, command_completion_event_t callback); - - /** - * @brief Create single emoji. - * You must ensure that the emoji passed contained image data using the emoji::load_image() method. - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see https://discord.com/developers/docs/resources/emoji#create-guild-emoji - * @param guild_id Guild ID to create emoji om - * @param newemoji Emoji to create - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::emoji object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_emoji_create(snowflake guild_id, const class emoji& newemoji, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit a single emoji. - * - * You must ensure that the emoji passed contained image data using the emoji::load_image() method. - * @see https://discord.com/developers/docs/resources/emoji#get-guild-emoji - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to edit emoji on - * @param newemoji Emoji to edit - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::emoji object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_emoji_edit(snowflake guild_id, const class emoji& newemoji, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a guild emoji - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see https://discord.com/developers/docs/resources/emoji#delete-guild-emoji - * @param guild_id Guild ID to delete emoji on - * @param emoji_id Emoji ID to delete - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_emoji_delete(snowflake guild_id, snowflake emoji_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get prune counts - * - * Returns a prune object indicating the number of members that would be removed in a prune operation. Requires the `KICK_MEMBERS` - * permission. By default, prune will not remove users with roles. You can optionally include specific roles in your prune by providing the - * include_roles parameter. Any inactive user that has a subset of the provided role(s) will be counted in the prune and users with additional - * roles will not. - * - * @see https://discord.com/developers/docs/resources/guild#get-guild-prune-count - * @param guild_id Guild ID to count for pruning - * @param pruneinfo Pruning info - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::prune object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_get_prune_counts(snowflake guild_id, const struct prune& pruneinfo, command_completion_event_t callback); - - /** - * @brief Begin guild prune - * - * Begin a prune operation. Requires the `KICK_MEMBERS` permission. Returns a prune object indicating the number of members - * that were removed in the prune operation. For large guilds it's recommended to set the `compute_prune_count` option to false, forcing - * 'pruned' to 0. Fires multiple `Guild Member Remove` Gateway events. - * By default, prune will not remove users with roles. You can optionally include specific roles in your prune by providing the `include_roles` - * parameter. Any inactive user that has a subset of the provided role(s) will be included in the prune and users with additional roles will not. - * - * @see https://discord.com/developers/docs/resources/guild#begin-guild-prune - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to prune - * @param pruneinfo Pruning info - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::prune object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_begin_prune(snowflake guild_id, const struct prune& pruneinfo, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get guild voice regions. - * - * Voice regions per guild are somewhat deprecated in preference of per-channel voice regions. - * Returns a list of voice region objects for the guild. Unlike the similar /voice route, this returns VIP servers when - * the guild is VIP-enabled. - * - * @see https://discord.com/developers/docs/resources/guild#get-guild-voice-regions - * @param guild_id Guild ID to get voice regions for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::voiceregion_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_get_voice_regions(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Get guild invites - * - * Returns a list of invite objects (with invite metadata) for the guild. Requires the `MANAGE_GUILD` permission. - * - * @see https://discord.com/developers/docs/resources/guild#get-guild-invites - * @param guild_id Guild ID to get invites for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::invite_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_get_invites(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Get guild integrations - * - * Requires the `MANAGE_GUILD` permission. - * - * @see https://discord.com/developers/docs/resources/guild#get-guild-integrations - * @param guild_id Guild ID to get integrations for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::integration_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_get_integrations(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Modify guild integration - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see https://discord.com/developers/docs/resources/guild#modify-guild-integration - * @param guild_id Guild ID to modify integration for - * @param i Integration to modify - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::integration object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_modify_integration(snowflake guild_id, const class integration &i, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete guild integration - * - * Delete the attached integration object for the guild. Deletes any associated webhooks and kicks the associated bot if there is one. - * Requires the `MANAGE_GUILD` permission. Fires a Guild Integrations Update Gateway event. - * - * @see https://discord.com/developers/docs/resources/guild#delete-guild-integration - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to delete integration for - * @param integration_id Integration ID to delete - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_delete_integration(snowflake guild_id, snowflake integration_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Sync guild integration - * - * @see https://discord.com/developers/docs/resources/guild#sync-guild-integration - * @param guild_id Guild ID to sync integration on - * @param integration_id Integration ID to synchronise - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_sync_integration(snowflake guild_id, snowflake integration_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get guild widget - * - * Requires the `MANAGE_GUILD` permission. - * - * @see https://discord.com/developers/docs/resources/guild#get-guild-widget - * @param guild_id Guild ID to get widget for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild_widget object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_get_widget(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Edit guild widget - * - * Requires the `MANAGE_GUILD` permission. - * - * @see https://discord.com/developers/docs/resources/guild#modify-guild-widget - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to edit widget for - * @param gw New guild widget information - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild_widget object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_edit_widget(snowflake guild_id, const class guild_widget &gw, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get guild vanity url, if enabled - * - * Returns a partial dpp::invite object for guilds with that feature enabled. Requires the `MANAGE_GUILD` permission. code will be null if a vanity url for the guild is not set. - * @see https://discord.com/developers/docs/resources/guild#get-guild-vanity-url - * @param guild_id Guild to get vanity URL for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::invite object in confirmation_callback_t::value filled to match the vanity url. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_get_vanity(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Create a webhook - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/webhook#create-webhook - * @param w Webhook to create - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::webhook object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void create_webhook(const class webhook &w, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get guild webhooks - * @see https://discord.com/developers/docs/resources/webhook#get-guild-webhooks - * @param guild_id Guild ID to get webhooks for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::webhook_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void get_guild_webhooks(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Get channel webhooks - * @see https://discord.com/developers/docs/resources/webhook#get-guild-webhooks - * @param channel_id Channel ID to get webhooks for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::webhook_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void get_channel_webhooks(snowflake channel_id, command_completion_event_t callback); - - /** - * @brief Get webhook - * @see https://discord.com/developers/docs/resources/webhook#get-webhook - * @param webhook_id Webhook ID to get - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::webhook object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void get_webhook(snowflake webhook_id, command_completion_event_t callback); - - /** - * @brief Get webhook using token - * @see https://discord.com/developers/docs/resources/webhook#get-webhook-with-token - * @param webhook_id Webhook ID to retrieve - * @param token Token of webhook - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::webhook object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void get_webhook_with_token(snowflake webhook_id, const std::string &token, command_completion_event_t callback); - - /** - * @brief Edit webhook - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/webhook#modify-webhook - * @param wh Webhook to edit - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::webhook object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void edit_webhook(const class webhook& wh, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit webhook with token (token is encapsulated in the webhook object) - * @see https://discord.com/developers/docs/resources/webhook#modify-webhook-with-token - * @param wh Webhook to edit (should include token) - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::webhook object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void edit_webhook_with_token(const class webhook& wh, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a webhook - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/webhook#delete-webhook - * @param webhook_id Webhook ID to delete - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void delete_webhook(snowflake webhook_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete webhook with token - * @see https://discord.com/developers/docs/resources/webhook#delete-webhook-with-token - * @param webhook_id Webhook ID to delete - * @param token Token of webhook to delete - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void delete_webhook_with_token(snowflake webhook_id, const std::string &token, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Execute webhook - * - * @see https://discord.com/developers/docs/resources/webhook#execute-webhook - * @param wh Webhook to execute - * @param m Message to send - * @param wait waits for server confirmation of message send before response, and returns the created message body - * @param thread_id Send a message to the specified thread within a webhook's channel. The thread will automatically be unarchived - * @param thread_name Name of thread to create (requires the webhook channel to be a forum channel) - * @param callback Function to call when the API call completes. - * @note If the webhook channel is a forum channel, you must provide either `thread_id` or `thread_name`. If `thread_id` is provided, the message will send in that thread. If `thread_name` is provided, a thread with that name will be created in the forum channel. - * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void execute_webhook(const class webhook &wh, const struct message &m, bool wait = false, snowflake thread_id = 0, const std::string& thread_name = "", command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get webhook message - * - * @see https://discord.com/developers/docs/resources/webhook#get-webhook-message - * @param wh Webhook to get the original message for - * @param message_id The message ID - * @param thread_id ID of the thread the message is in - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void get_webhook_message(const class webhook &wh, snowflake message_id, snowflake thread_id = 0, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit webhook message - * - * When the content field is edited, the mentions array in the message object will be reconstructed from scratch based on - * the new content. The allowed_mentions field of the edit request controls how this happens. If there is no explicit - * allowed_mentions in the edit request, the content will be parsed with default allowances, that is, without regard to - * whether or not an allowed_mentions was present in the request that originally created the message. - * - * @see https://discord.com/developers/docs/resources/webhook#edit-webhook-message - * @note the attachments array must contain all attachments that should be present after edit, including retained and new attachments provided in the request body. - * @param wh Webhook to edit message for - * @param m New message - * @param thread_id ID of the thread the message is in - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void edit_webhook_message(const class webhook &wh, const struct message &m, snowflake thread_id = 0, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete webhook message - * - * @see https://discord.com/developers/docs/resources/webhook#delete-webhook-message - * @param wh Webhook to delete message for - * @param message_id Message ID to delete - * @param thread_id ID of the thread the message is in - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void delete_webhook_message(const class webhook &wh, snowflake message_id, snowflake thread_id = 0, command_completion_event_t callback = utility::log_error()); - - - /** - * @brief Get a role for a guild - * - * @see https://discord.com/developers/docs/resources/guild#get-guild-roles - * @param guild_id Guild ID to get role for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::role_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void roles_get(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Create a role on a guild - * - * Create a new role for the guild. Requires the `MANAGE_ROLES` permission. Returns the new role object on success. - * Fires a `Guild Role Create` Gateway event. - * - * @see https://discord.com/developers/docs/resources/guild#create-guild-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param r Role to create (guild ID is encapsulated in the role object) - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::role object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void role_create(const class role &r, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit a role on a guild - * - * Requires the `MANAGE_ROLES` permission. Returns the updated role on success. Fires a `Guild Role Update` Gateway event. - * - * @see https://discord.com/developers/docs/resources/guild#modify-guild-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param r Role to edit - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::role object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void role_edit(const class role &r, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit multiple role's position in a guild. Returns a list of all roles of the guild on success. - * - * Modify the positions of a set of role objects for the guild. Requires the `MANAGE_ROLES` permission. - * Fires multiple `Guild Role Update` Gateway events. - * - * @see https://discord.com/developers/docs/resources/guild#modify-guild-role-positions - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to change the roles position on - * @param roles Vector of roles to change the positions of - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::role_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void roles_edit_position(snowflake guild_id, const std::vector &roles, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a role - * - * Requires the `MANAGE_ROLES` permission. Fires a `Guild Role Delete` Gateway event. - * - * @see https://discord.com/developers/docs/resources/guild#delete-guild-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to delete the role on - * @param role_id Role ID to delete - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void role_delete(snowflake guild_id, snowflake role_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get the application's role connection metadata records - * - * @see https://discord.com/developers/docs/resources/application-role-connection-metadata#get-application-role-connection-metadata-records - * @param application_id The application ID - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::application_role_connection_metadata_list object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void application_role_connection_get(snowflake application_id, command_completion_event_t callback); - - /** - * @brief Update the application's role connection metadata records - * - * @see https://discord.com/developers/docs/resources/application-role-connection-metadata#update-application-role-connection-metadata-records - * @param application_id The application ID - * @param connection_metadata The application role connection metadata to update - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::application_role_connection_metadata_list object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - * @note An application can have a maximum of 5 metadata records. - */ - void application_role_connection_update(snowflake application_id, const std::vector &connection_metadata, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get user application role connection - * - * @see https://discord.com/developers/docs/resources/user#get-user-application-role-connection - * @param application_id The application ID - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::application_role_connection object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void user_application_role_connection_get(snowflake application_id, command_completion_event_t callback); - - /** - * @brief Update user application role connection - * - * @see https://discord.com/developers/docs/resources/user#update-user-application-role-connection - * @param application_id The application ID - * @param connection The application role connection to update - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::application_role_connection object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void user_application_role_connection_update(snowflake application_id, const application_role_connection &connection, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get a user by id - * - * @see https://discord.com/developers/docs/resources/user#get-user - * @param user_id User ID to retrieve - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::user_identified object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - * @note The user_identified object is a subclass of dpp::user which contains further details if you have the oauth2 identify or email scopes. - * If you do not have these scopes, these fields are empty. You can safely convert a user_identified to user with `dynamic_cast`. - * @note unless you want something special from `dpp::user_identified` or you've turned off caching, you have no need to call this. - * Call `dpp::find_user` instead that looks up the user in the cache rather than a REST call. - */ - void user_get(snowflake user_id, command_completion_event_t callback); - - /** - * @brief Get current (bot) user - * - * @see https://discord.com/developers/docs/resources/user#get-current-user - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::user_identified object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - * @note The user_identified object is a subclass of dpp::user which contains further details if you have the oauth2 identify or email scopes. - * If you do not have these scopes, these fields are empty. You can safely convert a user_identified to user with `dynamic_cast`. - */ - void current_user_get(command_completion_event_t callback); - - /** - * @brief Get current (bot) application - * - * @see https://discord.com/developers/docs/topics/oauth2#get-current-bot-application-information - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::application object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void current_application_get(command_completion_event_t callback); - - /** - * @brief Modify current member - * - * Modifies the current member in a guild. - * Fires a `Guild Member Update` Gateway event. - * - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/guild#modify-current-member - * @param guild_id Guild ID to change on - * @param nickname New nickname, or empty string to clear nickname - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_current_member_edit(snowflake guild_id, const std::string &nickname, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get current user's connections (linked accounts, e.g. steam, xbox). - * This call requires the oauth2 `connections` scope and cannot be executed - * against a bot token. - * @see https://discord.com/developers/docs/resources/user#get-user-connections - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::connection_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void current_user_connections_get(command_completion_event_t callback); - - /** - * @brief Get current (bot) user guilds - * @see https://discord.com/developers/docs/resources/user#get-current-user-guilds - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void current_user_get_guilds(command_completion_event_t callback); - - /** - * @brief Edit current (bot) user - * - * Modifies the current member in a guild. Returns the updated guild_member object on success. - * Fires a `Guild Member Update` Gateway event. - * @see https://discord.com/developers/docs/resources/user#modify-current-user - * @param nickname Nickname to set - * @param image_blob Avatar data to upload (NOTE: Very heavily rate limited!) - * @param type Type of image for avatar - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::user object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - * @throw dpp::exception Image data is larger than the maximum size of 256 kilobytes - */ - void current_user_edit(const std::string &nickname, const std::string& image_blob = "", const image_type type = i_png, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get current user DM channels - * - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::channel_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void current_user_get_dms(command_completion_event_t callback); - - /** - * @brief Create a dm channel - * @see https://discord.com/developers/docs/resources/user#create-dm - * @param user_id User ID to create DM channel with - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::channel object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void create_dm_channel(snowflake user_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Leave a guild - * @see https://discord.com/developers/docs/resources/user#leave-guild - * @param guild_id Guild ID to leave - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void current_user_leave_guild(snowflake guild_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Create a thread in forum channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see https://discord.com/developers/docs/resources/channel#start-thread-in-forum-channel - * @param thread_name Name of the forum thread - * @param channel_id Forum channel in which thread to create - * @param msg The message to start the thread with - * @param auto_archive_duration Duration to automatically archive the thread after recent activity - * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected - * @param applied_tags List of IDs of forum tags (dpp::forum_tag) to apply to this thread - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::thread object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void thread_create_in_forum(const std::string& thread_name, snowflake channel_id, const message& msg, auto_archive_duration_t auto_archive_duration, uint16_t rate_limit_per_user, std::vector applied_tags = {}, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Create a thread - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see https://discord.com/developers/docs/resources/guild#create-guild-channel - * @param thread_name Name of the thread - * @param channel_id Channel in which thread to create - * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) - * @param thread_type Type of thread - CHANNEL_PUBLIC_THREAD, CHANNEL_ANNOUNCEMENT_THREAD, CHANNEL_PRIVATE_THREAD - * @param invitable whether non-moderators can add other non-moderators to a thread; only available when creating a private thread - * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::thread object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void thread_create(const std::string& thread_name, snowflake channel_id, uint16_t auto_archive_duration, channel_type thread_type, bool invitable, uint16_t rate_limit_per_user, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Create a thread with a message (Discord: ID of a thread is same as message ID) - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/topics/threads - * @param thread_name Name of the thread - * @param channel_id Channel in which thread to create - * @param message_id message to start thread with - * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) - * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::thread object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void thread_create_with_message(const std::string& thread_name, snowflake channel_id, snowflake message_id, uint16_t auto_archive_duration, uint16_t rate_limit_per_user, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Join a thread - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread ID to join - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void current_user_join_thread(snowflake thread_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Leave a thread - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread ID to leave - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void current_user_leave_thread(snowflake thread_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Add a member to a thread - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread ID to add to - * @param user_id Member ID to add - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void thread_member_add(snowflake thread_id, snowflake user_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Remove a member from a thread - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread ID to remove from - * @param user_id Member ID to remove - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void thread_member_remove(snowflake thread_id, snowflake user_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get a thread member - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread to get member for - * @param user_id ID of the user to get - * @param callback Function to call when the API call completes - * On success the callback will contain a dpp::thread_member object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void thread_member_get(const snowflake thread_id, const snowflake user_id, command_completion_event_t callback); - - /** - * @brief Get members of a thread - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread to get members for - * @param callback Function to call when the API call completes - * On success the callback will contain a dpp::thread_member_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void thread_members_get(snowflake thread_id, command_completion_event_t callback); - - /** - * @brief Get active threads in a guild (Sorted by ID in descending order) - * @see https://discord.com/developers/docs/topics/threads - * @param guild_id Guild to get active threads for - * @param callback Function to call when the API call completes - * On success the callback will contain a dpp::thread_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void threads_get_active(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Get public archived threads in a channel (Sorted by archive_timestamp in descending order) - * @see https://discord.com/developers/docs/topics/threads - * @param channel_id Channel to get public archived threads for - * @param before_timestamp Get threads before this timestamp - * @param limit Number of threads to get - * @param callback Function to call when the API call completes - * On success the callback will contain a dpp::thread_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void threads_get_public_archived(snowflake channel_id, time_t before_timestamp, uint16_t limit, command_completion_event_t callback); - - /** - * @brief Get private archived threads in a channel (Sorted by archive_timestamp in descending order) - * @see https://discord.com/developers/docs/topics/threads - * @param channel_id Channel to get public archived threads for - * @param before_timestamp Get threads before this timestamp - * @param limit Number of threads to get - * @param callback Function to call when the API call completes - * On success the callback will contain a dpp::thread_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void threads_get_private_archived(snowflake channel_id, time_t before_timestamp, uint16_t limit, command_completion_event_t callback); - - /** - * @brief Get private archived threads in a channel which current user has joined (Sorted by ID in descending order) - - * @see https://discord.com/developers/docs/topics/threads - * @param channel_id Channel to get public archived threads for - * @param before_id Get threads before this id - * @param limit Number of threads to get - * @param callback Function to call when the API call completes - * On success the callback will contain a dpp::thread_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void threads_get_joined_private_archived(snowflake channel_id, snowflake before_id, uint16_t limit, command_completion_event_t callback); - - /** - * @brief Create a sticker in a guild - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/sticker#create-guild-sticker - * @param s Sticker to create. Must have its guild ID set. - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_sticker_create(sticker &s, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Modify a sticker in a guild - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/sticker#modify-guild-sticker - * @param s Sticker to modify. Must have its guild ID and sticker ID set. - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_sticker_modify(sticker &s, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a sticker from a guild - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/sticker#delete-guild-sticker - * @param sticker_id sticker ID to delete - * @param guild_id guild ID to delete from - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_sticker_delete(snowflake sticker_id, snowflake guild_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get a nitro sticker - * @see https://discord.com/developers/docs/resources/sticker#get-sticker - * @param id Id of sticker to get. - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void nitro_sticker_get(snowflake id, command_completion_event_t callback); - - /** - * @brief Get a guild sticker - * @see https://discord.com/developers/docs/resources/sticker#get-guild-sticker - * @param id Id of sticker to get. - * @param guild_id Guild ID of the guild where the sticker is - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_sticker_get(snowflake id, snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Get all guild stickers - * @see https://discord.com/developers/docs/resources/sticker#get-guild-stickers - * @param guild_id Guild ID of the guild where the sticker is - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::sticker_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_stickers_get(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Get sticker packs - * @see https://discord.com/developers/docs/resources/sticker#list-nitro-sticker-packs - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::sticker_pack_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void sticker_packs_get(command_completion_event_t callback); - - /** - * @brief Create a stage instance on a stage channel. - * @see https://discord.com/developers/docs/resources/stage-instance#create-stage-instance - * @param instance Stage instance to create - * @param callback User function to execute when the api call completes - * On success the callback will contain a dpp::stage_instance object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - */ - void stage_instance_create(const stage_instance& instance, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get the stage instance associated with the channel id, if it exists. - * @see https://discord.com/developers/docs/resources/stage-instance#get-stage-instance - * @param channel_id ID of the associated channel - * @param callback User function to execute when the api call completes - * On success the callback will contain a dpp::stage_instance object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void stage_instance_get(const snowflake channel_id, command_completion_event_t callback); - - /** - * @brief Edit a stage instance. - * @see https://discord.com/developers/docs/resources/stage-instance#modify-stage-instance - * @param instance Stage instance to edit - * @param callback User function to execute when the api call completes - * On success the callback will contain a dpp::stage_instance object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - */ - void stage_instance_edit(const stage_instance& instance, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a stage instance. - * @see https://discord.com/developers/docs/resources/stage-instance#delete-stage-instance - * @param channel_id ID of the associated channel - * @param callback User function to execute when the api call completes - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - */ - void stage_instance_delete(const snowflake channel_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get all voice regions - * @see https://discord.com/developers/docs/resources/voice#list-voice-regions - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::voiceregion_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void get_voice_regions(command_completion_event_t callback); - - /** - * @brief Get the gateway information for the bot using the token - * @see https://discord.com/developers/docs/topics/gateway#get-gateway-bot - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::gateway object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void get_gateway_bot(command_completion_event_t callback); - - /** - * @brief Get all scheduled events for a guild - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#list-scheduled-events-for-guild - * @param guild_id Guild to get events for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::scheduled_event_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_events_get(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Get users RSVP'd to an event - * - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#get-guild-scheduled-event-users - * @param guild_id Guild to get user list for - * @param event_id Guild to get user list for - * @param limit Maximum number of results to return - * @param before Return user IDs that fall before this ID, if provided - * @param after Return user IDs that fall after this ID, if provided - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::event_member_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_event_users_get(snowflake guild_id, snowflake event_id, command_completion_event_t callback, uint8_t limit = 100, snowflake before = 0, snowflake after = 0); - - /** - * @brief Create a scheduled event on a guild - * - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#create-guild-scheduled-event - * @param event Event to create (guild ID must be populated) - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::scheduled_event_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_event_create(const scheduled_event& event, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a scheduled event from a guild - * - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#delete-guild-scheduled-event - * @param event_id Event ID to delete - * @param guild_id Guild ID of event to delete - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_event_delete(snowflake event_id, snowflake guild_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit/modify a scheduled event on a guild - * - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#modify-guild-scheduled-event - * @param event Event to create (event ID and guild ID must be populated) - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::scheduled_event_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_event_edit(const scheduled_event& event, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get a scheduled event for a guild - * - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#get-guild-scheduled-event - * @param guild_id Guild to get event for - * @param event_id Event ID to get - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::scheduled_event object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_event_get(snowflake guild_id, snowflake event_id, command_completion_event_t callback); - - /** - * @brief Set the bot's voice state on a stage channel - * - * **Caveats** - * - * There are currently several caveats for this endpoint: - * - * - `channel_id` must currently point to a stage channel. - * - current user must already have joined `channel_id`. - * - You must have the `MUTE_MEMBERS` permission to unsuppress yourself. You can always suppress yourself. - * - You must have the `REQUEST_TO_SPEAK` permission to request to speak. You can always clear your own request to speak. - * - You are able to set `request_to_speak_timestamp` to any present or future time. - * - * @see https://discord.com/developers/docs/resources/guild#modify-current-user-voice-state - * @param guild_id Guild to set voice state on - * @param channel_id Stage channel to set voice state on - * @param callback Function to call when the API call completes. - * @param suppress True if the user's audio should be suppressed, false if it should not - * @param request_to_speak_timestamp The time at which we requested to speak, or 0 to clear the request. The time set here must be the current time or in the future. - * On success the callback will contain a dpp::scheduled_event object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - * @throw std::logic_exception You attempted to set a request_to_speak_timestamp in the past which is not the value of 0. - */ - void current_user_set_voice_state(snowflake guild_id, snowflake channel_id, bool suppress = false, time_t request_to_speak_timestamp = 0, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Set a user's voice state on a stage channel - * - * **Caveats** - * - * There are currently several caveats for this endpoint: - * - * - `channel_id` must currently point to a stage channel. - * - User must already have joined `channel_id`. - * - You must have the `MUTE_MEMBERS` permission. (Since suppression is the only thing that is available currently) - * - When unsuppressed, non-bot users will have their `request_to_speak_timestamp` set to the current time. Bot users will not. - * - When suppressed, the user will have their `request_to_speak_timestamp` removed. - * - * @see https://discord.com/developers/docs/resources/guild#modify-user-voice-state - * @param user_id The user to set the voice state of - * @param guild_id Guild to set voice state on - * @param channel_id Stage channel to set voice state on - * @param callback Function to call when the API call completes. - * @param suppress True if the user's audio should be suppressed, false if it should not - * On success the callback will contain a dpp::scheduled_event object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void user_set_voice_state(snowflake user_id, snowflake guild_id, snowflake channel_id, bool suppress = false, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get all auto moderation rules for a guild - * - * @param guild_id Guild id of the auto moderation rule - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::automod_rule_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void automod_rules_get(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Get a single auto moderation rule - * - * @param guild_id Guild id of the auto moderation rule - * @param rule_id Rule id to retrieve - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::automod_rule object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void automod_rule_get(snowflake guild_id, snowflake rule_id, command_completion_event_t callback); - - /** - * @brief Create an auto moderation rule - * - * @param guild_id Guild id of the auto moderation rule - * @param r Auto moderation rule to create - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::automod_rule object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void automod_rule_create(snowflake guild_id, const automod_rule& r, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit an auto moderation rule - * - * @param guild_id Guild id of the auto moderation rule - * @param r Auto moderation rule to edit. The rule's id must be set. - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::automod_rule object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void automod_rule_edit(snowflake guild_id, const automod_rule& r, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete an auto moderation rule - * - * @param guild_id Guild id of the auto moderation rule - * @param rule_id Auto moderation rule id to delete - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void automod_rule_delete(snowflake guild_id, snowflake rule_id, command_completion_event_t callback = utility::log_error()); - -#include -#ifdef DPP_CORO -#include -#endif - -}; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { + +/** + * @brief Types of startup for cluster::start() + */ +enum start_type : bool { + /** + * @brief Wait forever on a condition variable. + * The cluster will spawn threads for each shard + * and start() will not return in normal operation. + */ + st_wait = false, + + /** + * @brief Return immediately after starting shard threads. + * If you set the parameter of cluster::start() to + * this value, you will have to manage the lifetime + * and scope of your cluster object yourself. Taking it + * out of scope or deleting its pointer will terminate + * the bot. + */ + st_return = true, +}; + +/** @brief The cluster class represents a group of shards and a command queue for sending and + * receiving commands from discord via HTTP. You should usually instantiate a cluster object + * at the very least to make use of the library. + */ +class DPP_EXPORT cluster { + + friend class discord_client; + friend class discord_voice_client; + + /** + * @brief default gateway for connecting the websocket. + */ + std::string default_gateway; + + /** + * @brief queue system for commands sent to Discord, and any replies + */ + request_queue* rest; + + /** + * @brief queue system for arbitrary HTTP requests sent by the user to sites other than Discord + */ + request_queue* raw_rest; + + /** + * @brief True if to use compression on shards + */ + bool compressed; + + /** + * @brief Lock to prevent concurrent access to dm_channels + */ + std::mutex dm_list_lock; + + /** + * @brief Start time of cluster + */ + time_t start_time; + + /** + * @brief Active DM channels for the bot + */ + std::unordered_map dm_channels; + + /** + * @brief Active shards on this cluster. Shard IDs may have gaps between if there + * are multiple clusters. + */ + shard_list shards; + + /** + * @brief List of all active registered timers + */ + timer_reg_t timer_list; + + /** + * @brief List of timers by time + */ + timer_next_t next_timer; + + /** + * @brief Tick active timers + */ + void tick_timers(); + + /** + * @brief Reschedule a timer for its next tick + * + * @param t Timer to reschedule + */ + void timer_reschedule(timer_t* t); +public: + /** + * @brief Current bot token for all shards on this cluster and all commands sent via HTTP + */ + std::string token; + + /** + * @brief Last time the bot sent an IDENTIFY + */ + time_t last_identify; + + /** + * @brief Current bitmask of gateway intents + */ + uint32_t intents; + + /** + * @brief Total number of shards across all clusters + */ + uint32_t numshards; + + /** + * @brief ID of this cluster, between 0 and MAXCLUSTERS-1 inclusive + */ + uint32_t cluster_id; + + /** + * @brief Total number of clusters that are active + */ + uint32_t maxclusters; + + /** + * @brief REST latency (HTTPS ping) in seconds + */ + double rest_ping; + + /** + * @brief The details of the bot user. This is assumed to be identical across all shards + * in the cluster. Each connecting shard updates this information. + */ + dpp::user me; + + /** + * @brief Current cache policy for the cluster + */ + cache_policy_t cache_policy; + + /** + * @brief Websocket mode for all shards in the cluster, either ws_json or ws_etf. + * Production bots should use ETF, while development bots should use JSON. + */ + websocket_protocol_t ws_mode; + + /** + * @brief Condition variable notified when the cluster is terminating. + */ + std::condition_variable terminating; + + /** + * @brief Constructor for creating a cluster. All but the token are optional. + * @param token The bot token to use for all HTTP commands and websocket connections + * @param intents A bitmask of dpd::intents values for all shards on this cluster. This is required to be sent for all bots with over 100 servers. + * @param shards The total number of shards on this bot. If there are multiple clusters, then (shards / clusters) actual shards will run on this cluster. + * If you omit this value, the library will attempt to query the Discord API for the correct number of shards to start. + * @param cluster_id The ID of this cluster, should be between 0 and MAXCLUSTERS-1 + * @param maxclusters The total number of clusters that are active, which may be on separate processes or even separate machines. + * @param compressed Whether or not to use compression for shards on this cluster. Saves a ton of bandwidth at the cost of some CPU + * @param policy Set the user caching policy for the cluster, either lazy (only cache users/members when they message the bot) or aggressive (request whole member lists on seeing new guilds too) + * @param request_threads The number of threads to allocate for making HTTP requests to Discord. This defaults to 12. You can increase this at runtime via the object returned from get_rest(). + * @param request_threads_raw The number of threads to allocate for making HTTP requests to sites outside of Discord. This defaults to 1. You can increase this at runtime via the object returned from get_raw_rest(). + * @throw dpp::exception Thrown on windows, if WinSock fails to initialise, or on any other system if a dpp::request_queue fails to construct + */ + cluster(const std::string& token, uint32_t intents = i_default_intents, uint32_t shards = 0, uint32_t cluster_id = 0, uint32_t maxclusters = 1, bool compressed = true, cache_policy_t policy = { cp_aggressive, cp_aggressive, cp_aggressive }, uint32_t request_threads = 12, uint32_t request_threads_raw = 1); + + /** + * @brief dpp::cluster is non-copyable + */ + cluster(const cluster&) = delete; + + /** + * @brief dpp::cluster is non-moveable + */ + cluster(const cluster&&) = delete; + + /** + * @brief Destroy the cluster object + */ + virtual ~cluster(); + + /** + * @brief End cluster execution without destructing it. + * To restart the cluster, call cluster::start() again. + */ + void shutdown(); + + /** + * @brief Get the rest_queue object which handles HTTPS requests to Discord + * @return request_queue* pointer to request_queue object + */ + request_queue* get_rest(); + + /** + * @brief Get the raw rest_queue object which handles all HTTP(S) requests that are not directed at Discord + * @return request_queue* pointer to request_queue object + */ + request_queue* get_raw_rest(); + + /** + * @brief Set the websocket protocol for all shards on this cluster. + * You should call this method before cluster::start. + * Generally ws_etf is faster, but provides less facilities for debugging should something + * go wrong. It is recommended to use ETF in production and JSON in development. + * + * @param mode websocket protocol to use, either ws_json or ws_etf. + * @return cluster& Reference to self for chaining. + */ + cluster& set_websocket_protocol(websocket_protocol_t mode); + + /** + * @brief Set the audit log reason for the next REST call to be made. + * This is set per-thread, so you must ensure that if you call this method, your request that + * is associated with the reason happens on the same thread where you set the reason. + * Once the next call is made, the audit log reason is cleared for this thread automatically. + * + * Example: + * ``` + * bot.set_audit_reason("Too much abusive content") + * .channel_delete(my_channel_id); + * ``` + * + * @param reason The reason to set for the next REST call on this thread + * @return cluster& Reference to self for chaining. + */ + cluster& set_audit_reason(const std::string &reason); + + /** + * @brief Clear the audit log reason for the next REST call to be made. + * This is set per-thread, so you must ensure that if you call this method, your request that + * is associated with the reason happens on the same thread where you set the reason. + * Once the next call is made, the audit log reason is cleared for this thread automatically. + * + * Example: + * ``` + * bot.set_audit_reason("Won't be sent") + * .clear_audit_reason() + * .channel_delete(my_channel_id); + * ``` + * + * @return cluster& Reference to self for chaining. + */ + cluster& clear_audit_reason(); + + /** + * @brief Get the audit reason set for the next REST call to be made on this thread. + * This is set per-thread, so you must ensure that if you call this method, your request that + * is associated with the reason happens on the same thread where you set the reason. + * Once the next call is made, the audit log reason is cleared for this thread automatically. + * + * @note This method call clears the audit reason when it returns it. + * + * @return std::string The audit reason to be used. + * + */ + std::string get_audit_reason(); + + /** + * @brief Sets the address of the default gateway, for connecting the websockets. + * + * @return cluster& Reference to self for chaining. + */ + cluster& set_default_gateway(std::string& default_gateway); + + /** + * @brief Log a message to whatever log the user is using. + * The logged message is passed up the chain to the on_log event in user code which can then do whatever + * it wants to do with it. + * @param severity The log level from dpp::loglevel + * @param msg The log message to output + */ + void log(dpp::loglevel severity, const std::string &msg) const; + + /** + * @brief Start a timer. Every `frequency` seconds, the callback is called. + * + * @param on_tick The callback lambda to call for this timer when ticked + * @param on_stop The callback lambda to call for this timer when it is stopped + * @param frequency How often to tick the timer in seconds + * @return timer A handle to the timer, used to remove that timer later + */ + timer start_timer(timer_callback_t on_tick, uint64_t frequency, timer_callback_t on_stop = {}); + + /** + * @brief Stop a ticking timer + * + * @param t Timer handle received from cluster::start_timer + * @return bool True if the timer was stopped, false if it did not exist + * @note If the timer has an on_stop lambda, the on_stop lambda will be called. + */ + bool stop_timer(timer t); + + /** + * @brief Get the dm channel for a user id + * + * @param user_id the user id to get the dm channel for + * @return Returns 0 on failure + */ + snowflake get_dm_channel(snowflake user_id); + + /** + * @brief Set the dm channel id for a user id + * + * @param user_id user id to set the dm channel for + * @param channel_id dm channel to set + */ + void set_dm_channel(snowflake user_id, snowflake channel_id); + + /** + * @brief Returns the uptime of the cluster + * + * @return dpp::utility::uptime The uptime of the cluster + */ + dpp::utility::uptime uptime(); + + /** + * @brief Start the cluster, connecting all its shards. + * + * Returns once all shards are connected if return_after is true, + * otherwise enters an infinite loop while the shards run. + * + * @param return_after If true the bot will return to your program after starting shards, if false this function will never return. + */ + void start(bool return_after = true); + + /** + * @brief Set the presence for all shards on the cluster + * + * @param p The presence to set. Only the online status and the first activity are sent. + */ + void set_presence(const class dpp::presence &p); + + /** + * @brief Get a shard by id, returning the discord_client + * + * @param id Shard ID + * @return discord_client* shard, or null + */ + discord_client* get_shard(uint32_t id); + + /** + * @brief Get the list of shards + * + * @return shard_list& Reference to map of shards for this cluster + */ + const shard_list& get_shards(); + + /* Functions for attaching to event handlers */ + + /** + * @brief on voice state update event + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type voice_state_update_t&, and returns void. + */ + event_router_t on_voice_state_update; + + + /** + * @brief on voice client disconnect event + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type voice_client_disconnect_t&, and returns void. + */ + event_router_t on_voice_client_disconnect; + + + /** + * @brief on voice client speaking event + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type voice_client_speaking_t&, and returns void. + */ + event_router_t on_voice_client_speaking; + + + /** + * @brief Called when a log message is to be written to the log. + * You can attach any logging system here you wish, e.g. spdlog, or even just a simple + * use of std::cout or printf. If nothing attaches this log event, then the + * library will be silent. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type log_t&, and returns void. + */ + event_router_t on_log; + + /** + * @brief on guild join request delete. + * Triggered when a user declines the membership screening questionnaire for a guild. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_join_request_delete_t&, and returns void. + */ + event_router_t on_guild_join_request_delete; + + + /** + * @brief Called when a new interaction is created. + * Interactions are created by discord when commands you have registered are issued + * by a user. For an example of this in action please see \ref slashcommands + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type interaction_create_t&, and returns void. + * + * @note There are dedicated events to handle slashcommands (See dpp::cluster::on_slashcommand), + * user context menus (See dpp::cluster::on_user_context_menu) and message context menus (See dpp::cluster::on_message_context_menu) + */ + event_router_t on_interaction_create; + + /** + * @brief Called when a slash command is issued. + * Only dpp::ctxm_chat_input types of interaction are routed to this event. + * For an example of this in action please see \ref slashcommands + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type slashcommand_t&, and returns void. + */ + event_router_t on_slashcommand; + + /** + * @brief Called when a button is clicked attached to a message. + * Button clicks are triggered by discord when buttons are clicked which you have + * associated with a message using dpp::component. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type button_click_t&, and returns void. + */ + event_router_t on_button_click; + + /** + * @brief Called when an auto completed field needs suggestions to present to the user + * This is triggered by discord when option choices have auto completion enabled which you have + * associated with a dpp::slashcommand. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type autocomplete_t&, and returns void. + */ + event_router_t on_autocomplete; + + + /** + * @brief Called when a select menu is clicked attached to a message. + * Select menu clicks are triggered by discord when select menus are clicked which you have + * associated with a message using dpp::component. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type select_click_t&, and returns void. + */ + event_router_t on_select_click; + + /** + * @brief Called when a user right-clicks or long-presses on a message, + * where a slash command is bound to the dpp::ctxm_message command type. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type message_context_menu_t&, and returns void. + */ + event_router_t on_message_context_menu; + + /** + * @brief Called when a user right-clicks or long-presses on a user, + * where a slash command is bound to the dpp::ctxm_user command type. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type user_context_menu_t&, and returns void. + */ + event_router_t on_user_context_menu; + + /** + * @brief Called when a modal dialog is submitted. + * Form submits are triggered by discord when modal dialogs are submitted which you have + * associated with a slash command using dpp::interaction_modal_response. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type form_submit_t&, and returns void. + */ + event_router_t on_form_submit; + + + /** + * @brief Called when a guild is deleted. + * A guild can be deleted via the bot being kicked, the bot leaving the guild + * explicitly with dpp::cluster::guild_delete, or via the guild being unavailable due to + * an outage. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_delete_t&, and returns void. + */ + event_router_t on_guild_delete; + + + /** + * @brief Called when a channel is deleted from a guild. + * The channel will still be temporarily available in the cache. Pointers to the + * channel should not be retained long-term as they will be deleted by the garbage + * collector. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type channel_delete_t&, and returns void. + */ + event_router_t on_channel_delete; + + + /** + * @brief Called when a channel is edited on a guild. + * The new channel details have already been applied to the guild when you + * receive this event. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type channel_update_t&, and returns void. + */ + event_router_t on_channel_update; + + + /** + * @brief Called when a shard is connected and ready. + * A set of cluster::on_guild_create events will follow this event. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type ready_t&, and returns void. + */ + event_router_t on_ready; + + + /** + * @brief Called when a message is deleted. + * The message has already been deleted from Discord when you + * receive this event. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type message_delete_t&, and returns void. + */ + event_router_t on_message_delete; + + + /** + * @brief Called when a user leaves a guild (either through being kicked, or choosing to leave) + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_member_remove_t&, and returns void. + */ + event_router_t on_guild_member_remove; + + + /** + * @brief Called when a connection to a shard successfully resumes. + * A resumed session does not need to re-synchronise guilds, members, etc. + * This is generally non-fatal and informational only. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type resumed_t&, and returns void. + */ + event_router_t on_resumed; + + + /** + * @brief Called when a new role is created on a guild. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_role_create_t&, and returns void. + */ + event_router_t on_guild_role_create; + + + /** + * @brief Called when a user is typing on a channel. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type typing_start_t&, and returns void. + */ + event_router_t on_typing_start; + + + /** + * @brief Called when a new reaction is added to a message. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type message_reaction_add_t&, and returns void. + */ + event_router_t on_message_reaction_add; + + + /** + * @brief Called when a set of members is received for a guild. + * D++ will request these for all new guilds if needed, after the cluster::on_guild_create + * events. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_members_chunk_t&, and returns void. + */ + event_router_t on_guild_members_chunk; + + + /** + * @brief Called when a single reaction is removed from a message. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type message_reaction_remove_t&, and returns void. + */ + event_router_t on_message_reaction_remove; + + + /** + * @brief Called when a new guild is created. + * D++ will request members for the guild for its cache using guild_members_chunk. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_create_t&, and returns void. + */ + event_router_t on_guild_create; + + + /** + * @brief Called when a new channel is created on a guild. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type channel_create_t&, and returns void. + */ + event_router_t on_channel_create; + + + /** + * @brief Called when all reactions for a particular emoji are removed from a message. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type message_reaction_remove_emoji_t&, and returns void. + */ + event_router_t on_message_reaction_remove_emoji; + + + /** + * @brief Called when multiple messages are deleted from a channel or DM. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type message_delete_bulk_t&, and returns void. + */ + event_router_t on_message_delete_bulk; + + + /** + * @brief Called when an existing role is updated on a guild. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_role_update_t&, and returns void. + */ + event_router_t on_guild_role_update; + + + /** + * @brief Called when a role is deleted in a guild. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_role_delete_t&, and returns void. + */ + event_router_t on_guild_role_delete; + + + /** + * @brief Called when a message is pinned. + * Note that the pinned message is not returned to this event, just the timestamp + * of the last pinned message. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type channel_pins_update_t&, and returns void. + */ + event_router_t on_channel_pins_update; + + + /** + * @brief Called when all reactions are removed from a message. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type message_reaction_remove_all_t&, and returns void. + */ + event_router_t on_message_reaction_remove_all; + + + /** + * @brief Called when we are told which voice server we can use. + * This will be sent either when we establish a new voice channel connection, + * or as discord rearrange their infrastructure. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type voice_server_update_t&, and returns void. + */ + event_router_t on_voice_server_update; + + + /** + * @brief Called when new emojis are added to a guild. + * The complete set of emojis is sent every time. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_emojis_update_t&, and returns void. + */ + event_router_t on_guild_emojis_update; + + + /** + * @brief Called when new stickers are added to a guild. + * The complete set of stickers is sent every time. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_stickers_update_t&, and returns void. + */ + event_router_t on_guild_stickers_update; + + + /** + * @brief Called when a user's presence is updated. + * To receive these you will need the GUILD_PRESENCES privileged intent. + * You will receive many of these, very often, and receiving them will significantly + * increase your bot's CPU usage. If you don't need them it is recommended to not ask + * for them. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type presence_update_t&, and returns void. + */ + event_router_t on_presence_update; + + + /** + * @brief Called when the webhooks for a guild are updated. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type webhooks_update_t&, and returns void. + */ + event_router_t on_webhooks_update; + + /** + * @brief Called when a new automod rule is created. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type automod_rule_create_t&, and returns void. + */ + event_router_t on_automod_rule_create; + + + /** + * @brief Called when an automod rule is updated. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type automod_rule_update_t&, and returns void. + */ + event_router_t on_automod_rule_update; + + /** + * @brief Called when an automod rule is deleted. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type automod_rule_delete_t&, and returns void. + */ + event_router_t on_automod_rule_delete; + + /** + * @brief Called when an automod rule is triggered/executed. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type automod_rule_execute_t&, and returns void. + */ + event_router_t on_automod_rule_execute; + + /** + * @brief Called when a new member joins a guild. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_member_add_t&, and returns void. + */ + event_router_t on_guild_member_add; + + + /** + * @brief Called when an invite is deleted from a guild. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type invite_delete_t&, and returns void. + */ + event_router_t on_invite_delete; + + + /** + * @brief Called when details of a guild are updated. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_update_t&, and returns void. + */ + event_router_t on_guild_update; + + + /** + * @brief Called when an integration is updated for a guild. + * This returns the complete list. + * An integration is a connection to a guild of a user's associated accounts, + * e.g. youtube or twitch, for automatic assignment of roles etc. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_integrations_update_t&, and returns void. + */ + event_router_t on_guild_integrations_update; + + + /** + * @brief Called when details of a guild member (e.g. their roles or nickname) are updated. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_member_update_t&, and returns void. + */ + event_router_t on_guild_member_update; + + + /** + * @brief Called when a new invite is created for a guild. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type invite_create_t&, and returns void. + */ + event_router_t on_invite_create; + + + /** + * @brief Called when a message is updated (edited). + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type message_update_t&, and returns void. + */ + event_router_t on_message_update; + + + /** + * @brief Called when a user is updated. + * This is separate to cluster::on_guild_member_update and includes things such as an avatar change, + * username change, discriminator change or change in subscription status for nitro. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type user_update_t&, and returns void. + */ + event_router_t on_user_update; + + + /** + * @brief Called when a new message arrives from discord. + * Note that D++ does not cache messages. If you want to cache these objects you + * should create something yourself within your bot. Caching of messages is not on + * the roadmap to be supported as it consumes excessive amounts of RAM. + * For an example for caching of messages, please see \ref caching-messages + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type message_create_t&, and returns void. + */ + event_router_t on_message_create; + + + /** + * @brief Called when a ban is added to a guild. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_ban_add_t&, and returns void. + */ + event_router_t on_guild_ban_add; + + + /** + * @brief Called when a ban is removed from a guild. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_ban_remove_t&, and returns void. + */ + event_router_t on_guild_ban_remove; + + + /** + * @brief Called when a new integration is attached to a guild by a user. + * An integration is a connection to a guild of a user's associated accounts, + * e.g. youtube or twitch, for automatic assignment of roles etc. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type integration_create_t&, and returns void. + */ + event_router_t on_integration_create; + + + /** + * @brief Called when an integration is updated by a user. + * This returns details of just the single integration that has changed. + * An integration is a connection to a guild of a user's associated accounts, + * e.g. youtube or twitch, for automatic assignment of roles etc. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type integration_update_t&, and returns void. + */ + event_router_t on_integration_update; + + + /** + * @brief Called when an integration is removed by a user. + * An integration is a connection to a guild of a user's associated accounts, + * e.g. youtube or twitch, for automatic assignment of roles etc. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type integration_delete_t&, and returns void. + */ + event_router_t on_integration_delete; + + + /** + * @brief Called when a thread is created. + * Note that threads are not cached by D++, but a list of thread IDs is accessible in a guild object + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type thread_create_t&, and returns void. + */ + event_router_t on_thread_create; + + + /** + * @brief Called when a thread is updated + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type thread_update_t&, and returns void. + */ + event_router_t on_thread_update; + + + /** + * @brief Called when a thread is deleted + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type thread_delete_t&, and returns void. + */ + event_router_t on_thread_delete; + + + /** + * @brief Called when thread list is synced (upon gaining access to a channel). + * Note that threads are not cached by D++, but a list of thread IDs is accessible in a guild object + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type thread_list_sync_t&, and returns void. + */ + event_router_t on_thread_list_sync; + + + /** + * @brief Called when current user's thread member object is updated + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type thread_member_update_t&, and returns void. + */ + event_router_t on_thread_member_update; + + + /** + * @brief Called when a thread's member list is updated (without GUILD_MEMBERS intent, is only called for current user) + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type thread_members_update_t&, and returns void. + */ + event_router_t on_thread_members_update; + + + /** + * @brief Called when a new scheduled event is created + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_scheduled_event_create_t&, and returns void. + */ + event_router_t on_guild_scheduled_event_create; + + + /** + * @brief Called when a new scheduled event is updated + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_scheduled_event_update_t&, and returns void. + */ + event_router_t on_guild_scheduled_event_update; + + + /** + * @brief Called when a new scheduled event is deleted + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_scheduled_event_delete_t&, and returns void. + */ + event_router_t on_guild_scheduled_event_delete; + + + /** + * @brief Called when a user is added to a scheduled event + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_scheduled_event_user_add_t&, and returns void. + */ + event_router_t on_guild_scheduled_event_user_add; + + + /** + * @brief Called when a user is removed to a scheduled event + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_scheduled_event_user_remove_t&, and returns void. + */ + event_router_t on_guild_scheduled_event_user_remove; + + + /** + * @brief Called when packets are sent from the voice buffer. + * The voice buffer contains packets that are already encoded with Opus and encrypted + * with Sodium, and merged into packets by the repacketizer, which is done in the + * dpp::discord_voice_client::send_audio method. You should use the buffer size properties + * of dpp::voice_buffer_send_t to determine if you should fill the buffer with more + * content. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type voice_buffer_send_t&, and returns void. + */ + event_router_t on_voice_buffer_send; + + + /** + * @brief Called when a user is talking on a voice channel. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type voice_user_talking_t&, and returns void. + */ + event_router_t on_voice_user_talking; + + + /** + * @brief Called when a voice channel is connected and ready to send audio. + * Note that this is not directly attached to the READY event of the websocket, + * as there is further connection that needs to be done before audio is ready to send. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type voice_ready_t&, and returns void. + */ + event_router_t on_voice_ready; + + + /** + * @brief Called when new audio data is received. + * Each separate user's audio from the voice channel will arrive tagged with + * their user id in the event, if a user can be attributed to the received audio. + * + * @note Receiving audio for bots is not officially supported by discord. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type voice_receive_t&, and returns void. + */ + event_router_t on_voice_receive; + + /** + * @brief Called when new audio data is received, combined and mixed for all speaking users. + * + * @note Receiving audio for bots is not officially supported by discord. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type voice_receive_t&, and returns void. + */ + event_router_t on_voice_receive_combined; + + /** + * @brief Called when sending of audio passes over a track marker. + * Track markers are arbitrarily placed "bookmarks" in the audio buffer, placed + * by the bot developer. Each track marker can have a string value associated with it + * which is specified in dpp::discord_voice_client::insert_marker and returned to this + * event. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type voice_track_marker_t&, and returns void. + */ + event_router_t on_voice_track_marker; + + + /** + * @brief Called when a new stage instance is created on a stage channel. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * + */ + event_router_t on_stage_instance_create; + + + /** + * @brief Called when a stage instance is updated. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type stage_instance_update_t&, and returns void. + */ + event_router_t on_stage_instance_update; + + + /** + * @brief Called when an existing stage instance is deleted from a stage channel. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type stage_instance_delete_t&, and returns void. + */ + event_router_t on_stage_instance_delete; + + + /** + * @brief Post a REST request. Where possible use a helper method instead like message_create + * + * @param endpoint Endpoint to post to, e.g. /api/guilds + * @param major_parameters Major parameters for the endpoint e.g. a guild id + * @param parameters Minor parameters for the API request + * @param method Method, e.g. GET, POST + * @param postdata Post data (usually JSON encoded) + * @param callback Function to call when the HTTP call completes. The callback parameter will contain amongst other things, the decoded json. + * @param filename Filename to post for POST requests (for uploading files) + * @param filecontent File content to post for POST requests (for uploading files) + */ + void post_rest(const std::string &endpoint, const std::string &major_parameters, const std::string ¶meters, http_method method, const std::string &postdata, json_encode_t callback, const std::string &filename = "", const std::string &filecontent = ""); + + /** + * @brief Post a multipart REST request. Where possible use a helper method instead like message_create + * + * @param endpoint Endpoint to post to, e.g. /api/guilds + * @param major_parameters Major parameters for the endpoint e.g. a guild id + * @param parameters Minor parameters for the API request + * @param method Method, e.g. GET, POST + * @param postdata Post data (usually JSON encoded) + * @param callback Function to call when the HTTP call completes. The callback parameter will contain amongst other things, the decoded json. + * @param filename List of filenames to post for POST requests (for uploading files) + * @param filecontent List of file content to post for POST requests (for uploading files) + */ + void post_rest_multipart(const std::string &endpoint, const std::string &major_parameters, const std::string ¶meters, http_method method, const std::string &postdata, json_encode_t callback, const std::vector &filename = {}, const std::vector &filecontent = {}); + + /** + * @brief Make a HTTP(S) request. For use when wanting asynchronous access to HTTP APIs outside of Discord. + * + * @param url Full URL to post to, e.g. https://api.somewhere.com/v1/foo/ + * @param method Method, e.g. GET, POST + * @param callback Function to call when the HTTP call completes. No processing is done on the returned data. + * @param postdata POST data + * @param mimetype MIME type of POST data + * @param headers Headers to send with the request + */ + void request(const std::string &url, http_method method, http_completion_event callback, const std::string &postdata = "", const std::string &mimetype = "text/plain", const std::multimap &headers = {}); + + /** + * @brief Respond to a slash command + * + * @see https://discord.com/developers/docs/interactions/receiving-and-responding#create-interaction-response + * @param interaction_id Interaction id to respond to + * @param token Token for the interaction webhook + * @param r Response to send + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void interaction_response_create(snowflake interaction_id, const std::string &token, const interaction_response &r, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit response to a slash command + * + * @see https://discord.com/developers/docs/interactions/receiving-and-responding#edit-original-interaction-response + * @param token Token for the interaction webhook + * @param m Message to send + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void interaction_response_edit(const std::string &token, const message &m, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Create a followup message to a slash command + * + * @param token Token for the interaction webhook + * @param m followup message to create + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void interaction_followup_create(const std::string &token, const message &m, command_completion_event_t callback); + + /** + * @brief Edit original followup message to a slash command + * This is an alias for cluster::interaction_response_edit + * @see cluster::interaction_response_edit + * + * @param token Token for the interaction webhook + * @param m message to edit, the ID should be set + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void interaction_followup_edit_original(const std::string &token, const message &m, command_completion_event_t callback = utility::log_error()); + + /** + * @brief + * + * @param token Token for the interaction webhook + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void interaction_followup_delete(const std::string &token, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit followup message to a slash command + * The message ID in the message you pass should be correctly set to that of a followup message you previously sent + * @param token Token for the interaction webhook + * @param m message to edit, the ID should be set + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void interaction_followup_edit(const std::string &token, const message &m, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get the followup message to a slash command + * @param token Token for the interaction webhook + * @param message_id message to retrieve + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void interaction_followup_get(const std::string &token, snowflake message_id, command_completion_event_t callback); + + /** + * @brief Create a global slash command (a bot can have a maximum of 100 of these). + * + * @see https://discord.com/developers/docs/interactions/application-commands#create-global-application-command + * @param s Slash command to create + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::slashcommand object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void global_command_create(const slashcommand &s, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get a global slash command + * + * @see https://discord.com/developers/docs/interactions/application-commands#get-global-application-command + * @param id The ID of the slash command + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::slashcommand object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void global_command_get(snowflake id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get the audit log for a guild + * + * @see https://discord.com/developers/docs/resources/audit-log#get-guild-audit-log + * @param guild_id Guild to get the audit log of + * @param user_id Entries from a specific user ID. Set this to `0` will fetch any user + * @param action_type Entries for a specific dpp::audit_type. Set this to `0` will fetch any type + * @param before Entries that preceded a specific audit log entry ID. Used for paginating + * @param limit Maximum number of entries (between 1-100) to return + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::auditlog object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_auditlog_get(snowflake guild_id, snowflake user_id, uint32_t action_type, snowflake before, uint32_t limit, command_completion_event_t callback); + + /** + * @brief Create a slash command local to a guild + * + * @see https://discord.com/developers/docs/interactions/application-commands#create-guild-application-command + * @note Creating a command with the same name as an existing command for your application will overwrite the old command. + * @param s Slash command to create + * @param guild_id Guild ID to create the slash command in + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::slashcommand object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_command_create(const slashcommand &s, snowflake guild_id, command_completion_event_t callback = utility::log_error()); + + + /** + * @brief Create/overwrite guild slash commands. + * Any existing guild slash commands on this guild will be deleted and replaced with these. + * + * @see https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-guild-application-commands + * @param commands Vector of slash commands to create/update. + * New guild commands will be available in the guild immediately. If the command did not already exist, it will count toward daily application command create limits. + * @param guild_id Guild ID to create/update the slash commands in + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::slashcommand_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_bulk_command_create(const std::vector &commands, snowflake guild_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Create/overwrite global slash commands. + * Any existing global slash commands will be deleted and replaced with these. + * + * @see https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-global-application-commands + * @param commands Vector of slash commands to create/update. + * overwriting existing commands that are registered globally for this application. Updates will be available in all guilds after 1 hour. + * Commands that do not already exist will count toward daily application command create limits. + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::slashcommand_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void global_bulk_command_create(const std::vector &commands, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit a global slash command (a bot can have a maximum of 100 of these) + * + * @see https://discord.com/developers/docs/interactions/application-commands#edit-global-application-command + * @param s Slash command to change + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void global_command_edit(const slashcommand &s, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get a slash command of a guild + * + * @see https://discord.com/developers/docs/interactions/application-commands#get-guild-application-command + * @note The returned slash commands will not have permissions set, you need to use a permissions getter e.g. dpp::guild_commands_get_permissions to get the guild command permissions + * @param id The ID of the slash command + * @param guild_id Guild ID to get the slash command from + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::slashcommand object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_command_get(snowflake id, snowflake guild_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit a slash command local to a guild + * + * @see https://discord.com/developers/docs/interactions/application-commands#edit-guild-application-command + * @param s Slash command to edit + * @param guild_id Guild ID to edit the slash command in + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_command_edit(const slashcommand &s, snowflake guild_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit slash command permissions of a guild + * + * @see https://discord.com/developers/docs/interactions/application-commands#edit-application-command-permissions + * @note You can only add up to 10 permission overwrites for a command + * @param s Slash command to edit the permissions for + * @param guild_id Guild ID to edit the slash command in + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_command_edit_permissions(const slashcommand &s, snowflake guild_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get the permissions for a slash command of a guild + * + * @see https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions + * @param id The ID of the slash command to get the permissions for + * @param guild_id Guild ID to get the permissions of + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild_command_permissions object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_command_get_permissions(snowflake id, snowflake guild_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit/Overwrite the permissions of all existing slash commands in a guild + * + * @note You can only add up to 10 permission overwrites for a command + * + * @see https://discord.com/developers/docs/interactions/application-commands#batch-edit-application-command-permissions + * @warning The endpoint will overwrite all existing permissions for all commands of the application in a guild, including slash commands, user commands, and message commands. Meaning that if you forgot to pass a slash command, the permissions of it might be removed. + * @param commands A vector of slash commands to edit/overwrite the permissions for + * @param guild_id Guild ID to edit permissions of the slash commands in + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild_command_permissions_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + * @deprecated This has been disabled with updates to Permissions v2. You can use guild_command_edit_permissions instead + */ + void guild_bulk_command_edit_permissions(const std::vector &commands, snowflake guild_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a global slash command (a bot can have a maximum of 100 of these) + * + * @see https://discord.com/developers/docs/interactions/application-commands#delete-global-application-command + * @param id Slash command to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void global_command_delete(snowflake id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a slash command local to a guild + * + * @see https://discord.com/developers/docs/interactions/application-commands#delete-guild-application-command + * @param id Slash command to delete + * @param guild_id Guild ID to delete the slash command in + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_command_delete(snowflake id, snowflake guild_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get the application's slash commands for a guild + * + * @see https://discord.com/developers/docs/interactions/application-commands#get-guild-application-commands + * @note The returned slash commands will not have permissions set, you need to use a permissions getter e.g. dpp::guild_commands_get_permissions to get the guild command permissions + * @param guild_id Guild ID to get the slash commands for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::slashcommand_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_commands_get(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get all slash command permissions of a guild + * + * @see https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions + * @param guild_id Guild ID to get the slash commands permissions for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild_command_permissions_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_commands_get_permissions(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get the application's global slash commands + * + * @see https://discord.com/developers/docs/interactions/application-commands#get-global-application-commands + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::slashcommand_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void global_commands_get(command_completion_event_t callback); + + /** + * @brief Create a direct message, also create the channel for the direct message if needed + * + * @see https://discord.com/developers/docs/resources/user#create-dm + * @see https://discord.com/developers/docs/resources/channel#create-message + * @param user_id User ID of user to send message to + * @param m Message object + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void direct_message_create(snowflake user_id, const message &m, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get a message + * + * @see https://discord.com/developers/docs/resources/channel#get-channel-message + * @param message_id Message ID + * @param channel_id Channel ID + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_get(snowflake message_id, snowflake channel_id, command_completion_event_t callback); + + /** + * @brief Get multiple messages. + * + * This function will attempt to fetch as many messages as possible using multiple API calls if needed. + * + * @see https://discord.com/developers/docs/resources/channel#get-channel-messages + * @param channel_id Channel ID to retrieve messages for + * @param around Messages should be retrieved around this ID if this is set to non-zero + * @param before Messages before this ID should be retrieved if this is set to non-zero + * @param after Messages after this ID should be retrieved if this is set to non-zero + * @param limit This number of messages maximum should be returned, up to a maximum of 100. + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void messages_get(snowflake channel_id, snowflake around, snowflake before, snowflake after, uint64_t limit, command_completion_event_t callback); + + /** + * @brief Send a message to a channel. The callback function is called when the message has been sent + * + * @see https://discord.com/developers/docs/resources/channel#create-message + * @param m Message to send + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_create(const struct message &m, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Crosspost a message. The callback function is called when the message has been sent + * + * @see https://discord.com/developers/docs/resources/channel#crosspost-message + * @param message_id Message to crosspost + * @param channel_id Channel ID to crosspost from + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_crosspost(snowflake message_id, snowflake channel_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit a message on a channel. The callback function is called when the message has been edited + * + * @see https://discord.com/developers/docs/resources/channel#edit-message + * @param m Message to edit + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_edit(const struct message &m, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Add a reaction to a message. The reaction string must be either an `emojiname:id` or a unicode character. + * + * @see https://discord.com/developers/docs/resources/channel#create-reaction + * @param m Message to add a reaction to + * @param reaction Reaction to add. Emojis should be in the form emojiname:id + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_add_reaction(const struct message &m, const std::string &reaction, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete own reaction from a message. The reaction string must be either an `emojiname:id` or a unicode character. + * + * @see https://discord.com/developers/docs/resources/channel#delete-own-reaction + * @param m Message to delete own reaction from + * @param reaction Reaction to delete. The reaction should be in the form emojiname:id + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_delete_own_reaction(const struct message &m, const std::string &reaction, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a user's reaction from a message. The reaction string must be either an `emojiname:id` or a unicode character + * + * @see https://discord.com/developers/docs/resources/channel#delete-user-reaction + * @param m Message to delete a user's reaction from + * @param user_id User ID who's reaction you want to remove + * @param reaction Reaction to remove. Reactions should be in the form emojiname:id + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_delete_reaction(const struct message &m, snowflake user_id, const std::string &reaction, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get reactions on a message for a particular emoji. The reaction string must be either an `emojiname:id` or a unicode character + * + * @see https://discord.com/developers/docs/resources/channel#get-reactions + * @param m Message to get reactions for + * @param reaction Reaction should be in the form emojiname:id or a unicode character + * @param before Reactions before this ID should be retrieved if this is set to non-zero + * @param after Reactions before this ID should be retrieved if this is set to non-zero + * @param limit This number of reactions maximum should be returned + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::user_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_get_reactions(const struct message &m, const std::string &reaction, snowflake before, snowflake after, snowflake limit, command_completion_event_t callback); + + /** + * @brief Delete all reactions on a message + * + * @see https://discord.com/developers/docs/resources/channel#delete-all-reactions + * @param m Message to delete reactions from + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_delete_all_reactions(const struct message &m, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete all reactions on a message using a particular emoji. The reaction string must be either an `emojiname:id` or a unicode character + * + * @see https://discord.com/developers/docs/resources/channel#delete-all-reactions-for-emoji + * @param m Message to delete reactions from + * @param reaction Reaction to delete, in the form emojiname:id or a unicode character + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_delete_reaction_emoji(const struct message &m, const std::string &reaction, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Add a reaction to a message by id. The reaction string must be either an `emojiname:id` or a unicode character. + * + * @see https://discord.com/developers/docs/topics/gateway#message-reaction-add + * @param message_id Message to add reactions to + * @param channel_id Channel to add reactions to + * @param reaction Reaction to add. Emojis should be in the form emojiname:id + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_add_reaction(snowflake message_id, snowflake channel_id, const std::string &reaction, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete own reaction from a message by id. The reaction string must be either an `emojiname:id` or a unicode character. + * + * @see https://discord.com/developers/docs/resources/channel#delete-own-reaction + * @param message_id Message to delete reactions from + * @param channel_id Channel to delete reactions from + * @param reaction Reaction to delete. The reaction should be in the form emojiname:id + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_delete_own_reaction(snowflake message_id, snowflake channel_id, const std::string &reaction, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a user's reaction from a message by id. The reaction string must be either an `emojiname:id` or a unicode character + * + * @see https://discord.com/developers/docs/resources/channel#delete-user-reaction + * @param message_id Message to delete reactions from + * @param channel_id Channel to delete reactions from + * @param user_id User ID who's reaction you want to remove + * @param reaction Reaction to remove. Reactions should be in the form emojiname:id + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_delete_reaction(snowflake message_id, snowflake channel_id, snowflake user_id, const std::string &reaction, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get reactions on a message for a particular emoji by id. The reaction string must be either an `emojiname:id` or a unicode character + * + * @see https://discord.com/developers/docs/resources/channel#get-reactions + * @param message_id Message to get reactions for + * @param channel_id Channel to get reactions for + * @param reaction Reaction should be in the form emojiname:id or a unicode character + * @param before Reactions before this ID should be retrieved if this is set to non-zero + * @param after Reactions before this ID should be retrieved if this is set to non-zero + * @param limit This number of reactions maximum should be returned + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::user_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_get_reactions(snowflake message_id, snowflake channel_id, const std::string &reaction, snowflake before, snowflake after, snowflake limit, command_completion_event_t callback); + + /** + * @brief Delete all reactions on a message by id + * + * @see https://discord.com/developers/docs/resources/channel#delete-all-reactions + * @param message_id Message to delete reactions from + * @param channel_id Channel to delete reactions from + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_delete_all_reactions(snowflake message_id, snowflake channel_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete all reactions on a message using a particular emoji by id. The reaction string must be either an `emojiname:id` or a unicode character + * + * @see https://discord.com/developers/docs/resources/channel#delete-all-reactions-for-emoji + * @param message_id Message to delete reactions from + * @param channel_id Channel to delete reactions from + * @param reaction Reaction to delete, in the form emojiname:id or a unicode character + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_delete_reaction_emoji(snowflake message_id, snowflake channel_id, const std::string &reaction, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a message from a channel. The callback function is called when the message has been edited + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see https://discord.com/developers/docs/resources/channel#delete-message + * @param message_id Message ID to delete + * @param channel_id Channel to delete from + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_delete(snowflake message_id, snowflake channel_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Bulk delete messages from a channel. The callback function is called when the message has been edited + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @note If any message provided older than 2 weeks or any duplicate message ID, it will fail. + * + * @see https://discord.com/developers/docs/resources/channel#bulk-delete-messages + * @param message_ids List of message IDs to delete (at least 2 and at most 100 message IDs) + * @param channel_id Channel to delete from + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_delete_bulk(const std::vector &message_ids, snowflake channel_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get a channel + * + * @see https://discord.com/developers/docs/resources/channel#get-channel + * @param c Channel ID to retrieve + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::channel object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_get(snowflake c, command_completion_event_t callback); + + /** + * @brief Get all channels for a guild + * + * @see https://discord.com/developers/docs/resources/channel#get-channels + * @param guild_id Guild ID to retrieve channels for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::channel_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channels_get(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Create a channel + * + * Create a new channel object for the guild. Requires the `MANAGE_CHANNELS` permission. If setting permission overwrites, + * only permissions your bot has in the guild can be allowed/denied. Setting `MANAGE_ROLES` permission in channels is only possible + * for guild administrators. Returns the new channel object on success. Fires a `Channel Create Gateway` event. + * + * All parameters to this endpoint are optional excluding `name` + * + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/channel#create-channel + * @param c Channel to create + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::channel object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_create(const class channel &c, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit a channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/channel#modify-channel + * @param c Channel to edit/update + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::channel object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_edit(const class channel &c, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit multiple channels positions + * + * Modify the positions of a set of channel objects for the guild. + * Requires `MANAGE_CHANNELS` permission. Fires multiple `Channel Update Gateway` events. + * Only channels to be modified are required. + * + * @see https://discord.com/developers/docs/resources/guild#modify-guild-channel-positions + * @param c Channel to change the position for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_edit_positions(const std::vector &c, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit a channel's permissions + * + * @see https://discord.com/developers/docs/resources/channel#edit-channel-permissions + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param c Channel to set permissions for + * @param overwrite_id Overwrite to change (a user or role ID) + * @param allow allow permissions bitmask + * @param deny deny permissions bitmask + * @param member true if the overwrite_id is a user id, false if it is a channel id + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_edit_permissions(const class channel &c, const snowflake overwrite_id, const uint64_t allow, const uint64_t deny, const bool member, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit a channel's permissions + * + * @see https://discord.com/developers/docs/resources/channel#edit-channel-permissions + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param channel_id ID of the channel to set permissions for + * @param overwrite_id Overwrite to change (a user or role ID) + * @param allow allow permissions bitmask + * @param deny deny permissions bitmask + * @param member true if the overwrite_id is a user id, false if it is a channel id + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_edit_permissions(const snowflake channel_id, const snowflake overwrite_id, const uint64_t allow, const uint64_t deny, const bool member, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/channel#deleteclose-channel + * @param channel_id Channel id to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_delete(snowflake channel_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get details about an invite + * + * @see https://discord.com/developers/docs/resources/invite#get-invite + * @param invite Invite code to get information on + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::invite object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void invite_get(const std::string &invite, command_completion_event_t callback); + + /** + * @brief Delete an invite + * + * @see https://discord.com/developers/docs/resources/invite#delete-invite + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param invite Invite code to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::invite object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void invite_delete(const std::string &invite, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get invites for a channel + * + * @see https://discord.com/developers/docs/resources/invite#get-invites + * @param c Channel to get invites for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::invite_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_invites_get(const class channel &c, command_completion_event_t callback); + + /** + * @brief Create invite for a channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/channel#create-channel-invite + * @param c Channel to create an invite on + * @param i Invite to create + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::invite object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_invite_create(const class channel &c, const class invite &i, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get a channel's pins + * @see https://discord.com/developers/docs/resources/channel#get-pinned-messages + * @param channel_id Channel ID to get pins for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_pins_get(snowflake channel_id, command_completion_event_t callback); + + /** + * @brief Adds a recipient to a Group DM using their access token + * @see https://discord.com/developers/docs/resources/channel#group-dm-add-recipient + * @param channel_id Channel id to add group DM recipients to + * @param user_id User ID to add + * @param access_token Access token from OAuth2 + * @param nick Nickname of user to apply to the chat + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void gdm_add(snowflake channel_id, snowflake user_id, const std::string &access_token, const std::string &nick, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Removes a recipient from a Group DM + * @see https://discord.com/developers/docs/resources/channel#group-dm-remove-recipient + * @param channel_id Channel ID of group DM + * @param user_id User ID to remove from group DM + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void gdm_remove(snowflake channel_id, snowflake user_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Remove a permission from a channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/channel#delete-channel-permission + * @param c Channel to remove permission from + * @param overwrite_id Overwrite to remove, user or channel ID + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_delete_permission(const class channel &c, snowflake overwrite_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Follow an announcement (news) channel + * @see https://discord.com/developers/docs/resources/channel#follow-news-channel + * @param c Channel id to follow + * @param target_channel_id Channel to subscribe the channel to + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_follow_news(const class channel &c, snowflake target_channel_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Trigger channel typing indicator + * @see https://discord.com/developers/docs/resources/channel#trigger-typing-indicator + * @param c Channel to set as typing on + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_typing(const class channel &c, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Trigger channel typing indicator + * @see https://discord.com/developers/docs/resources/channel#trigger-typing-indicator + * @param cid Channel ID to set as typing on + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_typing(snowflake cid, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Pin a message + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/channel#pin-message + * @param channel_id Channel id to pin message on + * @param message_id Message id to pin message on + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_pin(snowflake channel_id, snowflake message_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Unpin a message + * @see https://discord.com/developers/docs/resources/channel#unpin-message + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param channel_id Channel id to unpin message on + * @param message_id Message id to unpin message on + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_unpin(snowflake channel_id, snowflake message_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get a guild + * + * Returns the guild object for the given id. This endpoint will also return approximate_member_count and approximate_presence_count + * for the guild. + * @see https://discord.com/developers/docs/resources/guild#get-guild + * @param g Guild ID to retrieve + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_get(snowflake g, command_completion_event_t callback); + + /** + * @brief Get a guild preview. Returns a guild object but only a subset of the fields will be populated. + * + * Returns the guild preview object for the given id `g`. If the user is not in the guild, then the guild + * must be lurkable (it must be Discoverable or have a live public stage). + * @see https://discord.com/developers/docs/resources/guild#get-guild-preview + * @param g Guild ID to retrieve + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_get_preview(snowflake g, command_completion_event_t callback); + + /** + * @brief Get a guild member + * @see https://discord.com/developers/docs/resources/guild#get-guild-member + * @param guild_id Guild ID to get member for + * @param user_id User ID of member to get + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild_member object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_get_member(snowflake guild_id, snowflake user_id, command_completion_event_t callback); + + /** + * @brief Search for guild members based on whether their username or nickname starts with the given string. + * + * @note This endpoint is restricted according to whether the `GUILD_MEMBERS` Privileged Intent is enabled for your application. + * @see https://discord.com/developers/docs/resources/guild#search-guild-members + * @param guild_id Guild ID to search in + * @param query Query string to match username(s) and nickname(s) against + * @param limit max number of members to return (1-1000) + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild_member_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_search_members(snowflake guild_id, const std::string& query, uint16_t limit, command_completion_event_t callback); + + /** + * @brief Get all guild members + * + * @note This endpoint is restricted according to whether the `GUILD_MEMBERS` Privileged Intent is enabled for your application. + * @see https://discord.com/developers/docs/resources/guild#get-guild-members + * @param guild_id Guild ID to get all members for + * @param limit max number of members to return (1-1000) + * @param after the highest user id in the previous page + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild_member_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_get_members(snowflake guild_id, uint16_t limit, snowflake after, command_completion_event_t callback); + + /** + * @brief Add guild member. Needs a specific oauth2 scope, from which you get the access_token. + * + * Adds a user to the guild, provided you have a valid oauth2 access token for the user with the guilds.join scope. + * Returns the guild_member, which is defaulted if the user is already a member of the guild. Fires a `Guild Member Add` Gateway event. + * + * For guilds with Membership Screening enabled, this endpoint will default to adding new members as pending in the guild member object. + * Members that are pending will have to complete membership screening before they become full members that can talk. + * + * @note All parameters to this endpoint except for access_token are optional. + * The bot must be a member of the guild with `CREATE_INSTANT_INVITE` permission. + * @see https://discord.com/developers/docs/resources/guild#add-guild-member + * @param gm Guild member to add + * @param access_token Access token from Oauth2 scope + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild_member object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_add_member(const guild_member& gm, const std::string &access_token, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit the properties of an existing guild member + * + * Modify attributes of a guild member. Returns the guild_member. Fires a `Guild Member Update` Gateway event. + * To remove a timeout, set the `communication_disabled_until` to a non-zero time in the past, e.g. 1. + * When moving members to channels, the API user must have permissions to both connect to the channel and have the `MOVE_MEMBERS` permission. + * For moving and disconnecting users from voice, use dpp::cluster::guild_member_move. + * @see https://discord.com/developers/docs/resources/guild#modify-guild-member + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param gm Guild member to edit + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild_member object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_edit_member(const guild_member& gm, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Moves the guild member to a other voice channel, if member is connected to one. + * Set the `channel_id` to `0` to disconnect the user. + * + * Fires a `Guild Member Update` Gateway event. + * @note When moving members to channels, the API user __must__ have permissions to both connect to the channel and have the `MOVE_MEMBERS` permission. + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/guild#modify-guild-member + * @param channel_id Id of the channel to which the user is used. Set to `0` to disconnect the user + * @param guild_id Guild id to which the user is connected + * @param user_id User id, who should be moved + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild_member object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_member_move(const snowflake channel_id, const snowflake guild_id, const snowflake user_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Change current user nickname + * + * Modifies the nickname of the current user in a guild. + * Fires a `Guild Member Update` Gateway event. + * + * @deprecated Deprecated in favor of Modify Current Member. Will be replaced by dpp::cluster::guild_current_member_edit + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/guild#modify-current-user-nick + * @param guild_id Guild ID to change nickname on + * @param nickname New nickname, or empty string to clear nickname + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_set_nickname(snowflake guild_id, const std::string &nickname, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Add role to guild member + * + * Adds a role to a guild member. Requires the `MANAGE_ROLES` permission. + * Fires a `Guild Member Update` Gateway event. + * @see https://discord.com/developers/docs/resources/guild#add-guild-member-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to add a role to + * @param user_id User ID to add role to + * @param role_id Role ID to add to the user + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_member_add_role(snowflake guild_id, snowflake user_id, snowflake role_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Remove role from guild member + * + * Removes a role from a guild member. Requires the `MANAGE_ROLES` permission. + * Fires a `Guild Member Update` Gateway event. + * @see https://discord.com/developers/docs/resources/guild#remove-guild-member-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to remove role from user on + * @param user_id User ID to remove role from + * @param role_id Role to remove + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + * @deprecated Use dpp::cluster::guild_member_remove_role instead + */ + void guild_member_delete_role(snowflake guild_id, snowflake user_id, snowflake role_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Remove role from guild member + * + * Removes a role from a guild member. Requires the `MANAGE_ROLES` permission. + * Fires a `Guild Member Update` Gateway event. + * @see https://discord.com/developers/docs/resources/guild#remove-guild-member-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to remove role from user on + * @param user_id User ID to remove role from + * @param role_id Role to remove + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_member_remove_role(snowflake guild_id, snowflake user_id, snowflake role_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Remove (kick) a guild member + * + * Remove a member from a guild. Requires `KICK_MEMBERS` permission. + * Fires a `Guild Member Remove` Gateway event. + * @see https://discord.com/developers/docs/resources/guild#remove-guild-member + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @deprecated Replaced by dpp::cluster::guild_member_kick + * @param guild_id Guild ID to kick member from + * @param user_id User ID to kick + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_member_delete(snowflake guild_id, snowflake user_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Remove (kick) a guild member + * + * Remove a member from a guild. Requires `KICK_MEMBERS` permission. + * Fires a `Guild Member Remove` Gateway event. + * @see https://discord.com/developers/docs/resources/guild#remove-guild-member + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to kick member from + * @param user_id User ID to kick + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_member_kick(snowflake guild_id, snowflake user_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Set the timeout of a guild member + * + * Fires a `Guild Member Update` Gateway event. + * @see https://discord.com/developers/docs/resources/guild#modify-guild-member + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to timeout the member in + * @param user_id User ID to set the timeout for + * @param communication_disabled_until The timestamp when the user's timeout will expire (up to 28 days in the future). Set to 0 to remove the timeout + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_member_timeout(snowflake guild_id, snowflake user_id, time_t communication_disabled_until, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Add guild ban + * + * Create a guild ban, and optionally delete previous messages sent by the banned user. + * Requires the `BAN_MEMBERS` permission. Fires a `Guild Ban Add` Gateway event. + * @see https://discord.com/developers/docs/resources/guild#create-guild-ban + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to add ban to + * @param user_id User ID to ban + * @param delete_message_seconds How many seconds to delete messages for, between 0 and 604800 (7 days). Defaults to 0 + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_ban_add(snowflake guild_id, snowflake user_id, uint32_t delete_message_seconds = 0, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete guild ban + * + * Remove the ban for a user. Requires the `BAN_MEMBERS` permissions. + * Fires a Guild Ban Remove Gateway event. + * @see https://discord.com/developers/docs/resources/guild#remove-guild-ban + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild to delete ban from + * @param user_id User ID to delete ban for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_ban_delete(snowflake guild_id, snowflake user_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get guild ban list + * + * Requires the `BAN_MEMBERS` permission. + * @see https://discord.com/developers/docs/resources/guild#get-guild-bans + * @note Provide a user ID to `before` and `after` for pagination. Users will always be returned in ascending order by the user ID. If both before and after are provided, only before is respected. + * @param guild_id Guild ID to get bans for + * @param before If non-zero, all bans for user ids before this user id will be returned up to the limit + * @param after if non-zero, all bans for user ids after this user id will be returned up to the limit + * @param limit the maximum number of bans to retrieve in this call up to a maximum of 1000 + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::ban_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_get_bans(snowflake guild_id, snowflake before, snowflake after, snowflake limit, command_completion_event_t callback); + + /** + * @brief Get single guild ban + * + * Requires the `BAN_MEMBERS` permission. + * @see https://discord.com/developers/docs/resources/guild#get-guild-ban + * @param guild_id Guild ID to get ban for + * @param user_id User ID of ban to retrieve + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::ban object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_get_ban(snowflake guild_id, snowflake user_id, command_completion_event_t callback); + + /** + * @brief Get a template + * @see https://discord.com/developers/docs/resources/guild-template#get-guild-template + * @param code Template code + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::dtemplate object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void template_get(const std::string &code, command_completion_event_t callback); + + /** + * @brief Create a new guild based on a template. + * @note This endpoint can be used only by bots in less than 10 guilds. + * @see https://discord.com/developers/docs/resources/guild-template#create-guild-from-guild-template + * @param code Template code to create guild from + * @param name Guild name to create + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_create_from_template(const std::string &code, const std::string &name, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get guild templates + * + * @see https://discord.com/developers/docs/resources/guild-template#get-guild-templates + * @param guild_id Guild ID to get templates for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::dtemplate_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_templates_get(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Creates a template for the guild + * + * @see https://discord.com/developers/docs/resources/guild-template#create-guild-template + * @param guild_id Guild to create template from + * @param name Template name to create + * @param description Description of template to create + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::dtemplate object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_template_create(snowflake guild_id, const std::string &name, const std::string &description, command_completion_event_t callback); + + /** + * @brief Syncs the template to the guild's current state. + * + * @see https://discord.com/developers/docs/resources/guild-template#sync-guild-template + * @param guild_id Guild to synchronise template for + * @param code Code of template to synchronise + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::dtemplate object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_template_sync(snowflake guild_id, const std::string &code, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Modifies the template's metadata. + * + * @see https://discord.com/developers/docs/resources/guild-template#modify-guild-template + * @param guild_id Guild ID of template to modify + * @param code Template code to modify + * @param name New name of template + * @param description New description of template + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::dtemplate object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_template_modify(snowflake guild_id, const std::string &code, const std::string &name, const std::string &description, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Deletes the template + * + * @see https://discord.com/developers/docs/resources/guild-template#delete-guild-template + * @param guild_id Guild ID of template to delete + * @param code Template code to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_template_delete(snowflake guild_id, const std::string &code, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Create a guild + * + * Create a new guild. Returns a guild object on success. `Fires a Guild Create Gateway` event. + * + * When using the roles parameter, the first member of the array is used to change properties of the guild's everyone role. + * If you are trying to bootstrap a guild with additional roles, keep this in mind. The required id field within each role object is an + * integer placeholder, and will be replaced by the API upon consumption. Its purpose is to allow you to overwrite a role's permissions + * in a channel when also passing in channels with the channels array. + * When using the channels parameter, the position field is ignored, and none of the default channels are created. The id field within + * each channel object may be set to an integer placeholder, and will be replaced by the API upon consumption. Its purpose is to + * allow you to create `GUILD_CATEGORY` channels by setting the `parent_id` field on any children to the category's id field. + * Category channels must be listed before any children. + * + * @see https://discord.com/developers/docs/resources/guild#create-guild + * @note The region field is deprecated and is replaced by channel.rtc_region. This endpoint can be used only by bots in less than 10 guilds. + * @param g Guild to create + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_create(const class guild &g, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit a guild + * + * Modify a guild's settings. Requires the `MANAGE_GUILD` permission. Returns the updated guild object on success. + * Fires a `Guild Update Gateway` event. + * + * @see https://discord.com/developers/docs/resources/guild#modify-guild + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param g Guild to edit + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_edit(const class guild &g, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a guild + * + * Delete a guild permanently. User must be owner. Fires a `Guild Delete Gateway` event. + * + * @see https://discord.com/developers/docs/resources/guild#delete-guild + * @param guild_id Guild ID to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_delete(snowflake guild_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get all emojis for a guild + * + * @see https://discord.com/developers/docs/resources/emoji#get-guild-emojis + * @param guild_id Guild ID to get emojis for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::emoji_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_emojis_get(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get a single emoji + * + * @see https://discord.com/developers/docs/resources/emoji#get-guild-emoji + * @param guild_id Guild ID to get emoji for + * @param emoji_id Emoji ID to get + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::emoji object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_emoji_get(snowflake guild_id, snowflake emoji_id, command_completion_event_t callback); + + /** + * @brief Create single emoji. + * You must ensure that the emoji passed contained image data using the emoji::load_image() method. + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see https://discord.com/developers/docs/resources/emoji#create-guild-emoji + * @param guild_id Guild ID to create emoji om + * @param newemoji Emoji to create + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::emoji object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_emoji_create(snowflake guild_id, const class emoji& newemoji, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit a single emoji. + * + * You must ensure that the emoji passed contained image data using the emoji::load_image() method. + * @see https://discord.com/developers/docs/resources/emoji#get-guild-emoji + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to edit emoji on + * @param newemoji Emoji to edit + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::emoji object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_emoji_edit(snowflake guild_id, const class emoji& newemoji, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a guild emoji + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see https://discord.com/developers/docs/resources/emoji#delete-guild-emoji + * @param guild_id Guild ID to delete emoji on + * @param emoji_id Emoji ID to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_emoji_delete(snowflake guild_id, snowflake emoji_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get prune counts + * + * Returns a prune object indicating the number of members that would be removed in a prune operation. Requires the `KICK_MEMBERS` + * permission. By default, prune will not remove users with roles. You can optionally include specific roles in your prune by providing the + * include_roles parameter. Any inactive user that has a subset of the provided role(s) will be counted in the prune and users with additional + * roles will not. + * + * @see https://discord.com/developers/docs/resources/guild#get-guild-prune-count + * @param guild_id Guild ID to count for pruning + * @param pruneinfo Pruning info + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::prune object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_get_prune_counts(snowflake guild_id, const struct prune& pruneinfo, command_completion_event_t callback); + + /** + * @brief Begin guild prune + * + * Begin a prune operation. Requires the `KICK_MEMBERS` permission. Returns a prune object indicating the number of members + * that were removed in the prune operation. For large guilds it's recommended to set the `compute_prune_count` option to false, forcing + * 'pruned' to 0. Fires multiple `Guild Member Remove` Gateway events. + * By default, prune will not remove users with roles. You can optionally include specific roles in your prune by providing the `include_roles` + * parameter. Any inactive user that has a subset of the provided role(s) will be included in the prune and users with additional roles will not. + * + * @see https://discord.com/developers/docs/resources/guild#begin-guild-prune + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to prune + * @param pruneinfo Pruning info + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::prune object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_begin_prune(snowflake guild_id, const struct prune& pruneinfo, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get guild voice regions. + * + * Voice regions per guild are somewhat deprecated in preference of per-channel voice regions. + * Returns a list of voice region objects for the guild. Unlike the similar /voice route, this returns VIP servers when + * the guild is VIP-enabled. + * + * @see https://discord.com/developers/docs/resources/guild#get-guild-voice-regions + * @param guild_id Guild ID to get voice regions for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::voiceregion_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_get_voice_regions(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get guild invites + * + * Returns a list of invite objects (with invite metadata) for the guild. Requires the `MANAGE_GUILD` permission. + * + * @see https://discord.com/developers/docs/resources/guild#get-guild-invites + * @param guild_id Guild ID to get invites for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::invite_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_get_invites(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get guild integrations + * + * Requires the `MANAGE_GUILD` permission. + * + * @see https://discord.com/developers/docs/resources/guild#get-guild-integrations + * @param guild_id Guild ID to get integrations for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::integration_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_get_integrations(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Modify guild integration + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see https://discord.com/developers/docs/resources/guild#modify-guild-integration + * @param guild_id Guild ID to modify integration for + * @param i Integration to modify + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::integration object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_modify_integration(snowflake guild_id, const class integration &i, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete guild integration + * + * Delete the attached integration object for the guild. Deletes any associated webhooks and kicks the associated bot if there is one. + * Requires the `MANAGE_GUILD` permission. Fires a Guild Integrations Update Gateway event. + * + * @see https://discord.com/developers/docs/resources/guild#delete-guild-integration + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to delete integration for + * @param integration_id Integration ID to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_delete_integration(snowflake guild_id, snowflake integration_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Sync guild integration + * + * @see https://discord.com/developers/docs/resources/guild#sync-guild-integration + * @param guild_id Guild ID to sync integration on + * @param integration_id Integration ID to synchronise + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_sync_integration(snowflake guild_id, snowflake integration_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get guild widget + * + * Requires the `MANAGE_GUILD` permission. + * + * @see https://discord.com/developers/docs/resources/guild#get-guild-widget + * @param guild_id Guild ID to get widget for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild_widget object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_get_widget(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Edit guild widget + * + * Requires the `MANAGE_GUILD` permission. + * + * @see https://discord.com/developers/docs/resources/guild#modify-guild-widget + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to edit widget for + * @param gw New guild widget information + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild_widget object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_edit_widget(snowflake guild_id, const class guild_widget &gw, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get guild vanity url, if enabled + * + * Returns a partial dpp::invite object for guilds with that feature enabled. Requires the `MANAGE_GUILD` permission. code will be null if a vanity url for the guild is not set. + * @see https://discord.com/developers/docs/resources/guild#get-guild-vanity-url + * @param guild_id Guild to get vanity URL for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::invite object in confirmation_callback_t::value filled to match the vanity url. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_get_vanity(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Create a webhook + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/webhook#create-webhook + * @param w Webhook to create + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::webhook object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void create_webhook(const class webhook &w, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get guild webhooks + * @see https://discord.com/developers/docs/resources/webhook#get-guild-webhooks + * @param guild_id Guild ID to get webhooks for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::webhook_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void get_guild_webhooks(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get channel webhooks + * @see https://discord.com/developers/docs/resources/webhook#get-guild-webhooks + * @param channel_id Channel ID to get webhooks for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::webhook_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void get_channel_webhooks(snowflake channel_id, command_completion_event_t callback); + + /** + * @brief Get webhook + * @see https://discord.com/developers/docs/resources/webhook#get-webhook + * @param webhook_id Webhook ID to get + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::webhook object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void get_webhook(snowflake webhook_id, command_completion_event_t callback); + + /** + * @brief Get webhook using token + * @see https://discord.com/developers/docs/resources/webhook#get-webhook-with-token + * @param webhook_id Webhook ID to retrieve + * @param token Token of webhook + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::webhook object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void get_webhook_with_token(snowflake webhook_id, const std::string &token, command_completion_event_t callback); + + /** + * @brief Edit webhook + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/webhook#modify-webhook + * @param wh Webhook to edit + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::webhook object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void edit_webhook(const class webhook& wh, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit webhook with token (token is encapsulated in the webhook object) + * @see https://discord.com/developers/docs/resources/webhook#modify-webhook-with-token + * @param wh Webhook to edit (should include token) + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::webhook object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void edit_webhook_with_token(const class webhook& wh, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a webhook + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/webhook#delete-webhook + * @param webhook_id Webhook ID to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void delete_webhook(snowflake webhook_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete webhook with token + * @see https://discord.com/developers/docs/resources/webhook#delete-webhook-with-token + * @param webhook_id Webhook ID to delete + * @param token Token of webhook to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void delete_webhook_with_token(snowflake webhook_id, const std::string &token, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Execute webhook + * + * @see https://discord.com/developers/docs/resources/webhook#execute-webhook + * @param wh Webhook to execute + * @param m Message to send + * @param wait waits for server confirmation of message send before response, and returns the created message body + * @param thread_id Send a message to the specified thread within a webhook's channel. The thread will automatically be unarchived + * @param thread_name Name of thread to create (requires the webhook channel to be a forum channel) + * @param callback Function to call when the API call completes. + * @note If the webhook channel is a forum channel, you must provide either `thread_id` or `thread_name`. If `thread_id` is provided, the message will send in that thread. If `thread_name` is provided, a thread with that name will be created in the forum channel. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void execute_webhook(const class webhook &wh, const struct message &m, bool wait = false, snowflake thread_id = 0, const std::string& thread_name = "", command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get webhook message + * + * @see https://discord.com/developers/docs/resources/webhook#get-webhook-message + * @param wh Webhook to get the original message for + * @param message_id The message ID + * @param thread_id ID of the thread the message is in + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void get_webhook_message(const class webhook &wh, snowflake message_id, snowflake thread_id = 0, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit webhook message + * + * When the content field is edited, the mentions array in the message object will be reconstructed from scratch based on + * the new content. The allowed_mentions field of the edit request controls how this happens. If there is no explicit + * allowed_mentions in the edit request, the content will be parsed with default allowances, that is, without regard to + * whether or not an allowed_mentions was present in the request that originally created the message. + * + * @see https://discord.com/developers/docs/resources/webhook#edit-webhook-message + * @note the attachments array must contain all attachments that should be present after edit, including retained and new attachments provided in the request body. + * @param wh Webhook to edit message for + * @param m New message + * @param thread_id ID of the thread the message is in + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void edit_webhook_message(const class webhook &wh, const struct message &m, snowflake thread_id = 0, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete webhook message + * + * @see https://discord.com/developers/docs/resources/webhook#delete-webhook-message + * @param wh Webhook to delete message for + * @param message_id Message ID to delete + * @param thread_id ID of the thread the message is in + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void delete_webhook_message(const class webhook &wh, snowflake message_id, snowflake thread_id = 0, command_completion_event_t callback = utility::log_error()); + + + /** + * @brief Get a role for a guild + * + * @see https://discord.com/developers/docs/resources/guild#get-guild-roles + * @param guild_id Guild ID to get role for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::role_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void roles_get(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Create a role on a guild + * + * Create a new role for the guild. Requires the `MANAGE_ROLES` permission. Returns the new role object on success. + * Fires a `Guild Role Create` Gateway event. + * + * @see https://discord.com/developers/docs/resources/guild#create-guild-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param r Role to create (guild ID is encapsulated in the role object) + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::role object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void role_create(const class role &r, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit a role on a guild + * + * Requires the `MANAGE_ROLES` permission. Returns the updated role on success. Fires a `Guild Role Update` Gateway event. + * + * @see https://discord.com/developers/docs/resources/guild#modify-guild-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param r Role to edit + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::role object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void role_edit(const class role &r, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit multiple role's position in a guild. Returns a list of all roles of the guild on success. + * + * Modify the positions of a set of role objects for the guild. Requires the `MANAGE_ROLES` permission. + * Fires multiple `Guild Role Update` Gateway events. + * + * @see https://discord.com/developers/docs/resources/guild#modify-guild-role-positions + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to change the roles position on + * @param roles Vector of roles to change the positions of + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::role_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void roles_edit_position(snowflake guild_id, const std::vector &roles, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a role + * + * Requires the `MANAGE_ROLES` permission. Fires a `Guild Role Delete` Gateway event. + * + * @see https://discord.com/developers/docs/resources/guild#delete-guild-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to delete the role on + * @param role_id Role ID to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void role_delete(snowflake guild_id, snowflake role_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get the application's role connection metadata records + * + * @see https://discord.com/developers/docs/resources/application-role-connection-metadata#get-application-role-connection-metadata-records + * @param application_id The application ID + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::application_role_connection_metadata_list object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void application_role_connection_get(snowflake application_id, command_completion_event_t callback); + + /** + * @brief Update the application's role connection metadata records + * + * @see https://discord.com/developers/docs/resources/application-role-connection-metadata#update-application-role-connection-metadata-records + * @param application_id The application ID + * @param connection_metadata The application role connection metadata to update + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::application_role_connection_metadata_list object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + * @note An application can have a maximum of 5 metadata records. + */ + void application_role_connection_update(snowflake application_id, const std::vector &connection_metadata, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get user application role connection + * + * @see https://discord.com/developers/docs/resources/user#get-user-application-role-connection + * @param application_id The application ID + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::application_role_connection object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void user_application_role_connection_get(snowflake application_id, command_completion_event_t callback); + + /** + * @brief Update user application role connection + * + * @see https://discord.com/developers/docs/resources/user#update-user-application-role-connection + * @param application_id The application ID + * @param connection The application role connection to update + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::application_role_connection object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void user_application_role_connection_update(snowflake application_id, const application_role_connection &connection, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get a user by id + * + * @see https://discord.com/developers/docs/resources/user#get-user + * @param user_id User ID to retrieve + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::user_identified object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + * @note The user_identified object is a subclass of dpp::user which contains further details if you have the oauth2 identify or email scopes. + * If you do not have these scopes, these fields are empty. You can safely convert a user_identified to user with `dynamic_cast`. + * @note unless you want something special from `dpp::user_identified` or you've turned off caching, you have no need to call this. + * Call `dpp::find_user` instead that looks up the user in the cache rather than a REST call. + */ + void user_get(snowflake user_id, command_completion_event_t callback); + + /** + * @brief Get current (bot) user + * + * @see https://discord.com/developers/docs/resources/user#get-current-user + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::user_identified object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + * @note The user_identified object is a subclass of dpp::user which contains further details if you have the oauth2 identify or email scopes. + * If you do not have these scopes, these fields are empty. You can safely convert a user_identified to user with `dynamic_cast`. + */ + void current_user_get(command_completion_event_t callback); + + /** + * @brief Get current (bot) application + * + * @see https://discord.com/developers/docs/topics/oauth2#get-current-bot-application-information + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::application object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void current_application_get(command_completion_event_t callback); + + /** + * @brief Modify current member + * + * Modifies the current member in a guild. + * Fires a `Guild Member Update` Gateway event. + * + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/guild#modify-current-member + * @param guild_id Guild ID to change on + * @param nickname New nickname, or empty string to clear nickname + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_current_member_edit(snowflake guild_id, const std::string &nickname, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get current user's connections (linked accounts, e.g. steam, xbox). + * This call requires the oauth2 `connections` scope and cannot be executed + * against a bot token. + * @see https://discord.com/developers/docs/resources/user#get-user-connections + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::connection_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void current_user_connections_get(command_completion_event_t callback); + + /** + * @brief Get current (bot) user guilds + * @see https://discord.com/developers/docs/resources/user#get-current-user-guilds + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void current_user_get_guilds(command_completion_event_t callback); + + /** + * @brief Edit current (bot) user + * + * Modifies the current member in a guild. Returns the updated guild_member object on success. + * Fires a `Guild Member Update` Gateway event. + * @see https://discord.com/developers/docs/resources/user#modify-current-user + * @param nickname Nickname to set + * @param image_blob Avatar data to upload (NOTE: Very heavily rate limited!) + * @param type Type of image for avatar + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::user object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + * @throw dpp::exception Image data is larger than the maximum size of 256 kilobytes + */ + void current_user_edit(const std::string &nickname, const std::string& image_blob = "", const image_type type = i_png, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get current user DM channels + * + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::channel_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void current_user_get_dms(command_completion_event_t callback); + + /** + * @brief Create a dm channel + * @see https://discord.com/developers/docs/resources/user#create-dm + * @param user_id User ID to create DM channel with + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::channel object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void create_dm_channel(snowflake user_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Leave a guild + * @see https://discord.com/developers/docs/resources/user#leave-guild + * @param guild_id Guild ID to leave + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void current_user_leave_guild(snowflake guild_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Create a thread in forum channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see https://discord.com/developers/docs/resources/channel#start-thread-in-forum-channel + * @param thread_name Name of the forum thread + * @param channel_id Forum channel in which thread to create + * @param msg The message to start the thread with + * @param auto_archive_duration Duration to automatically archive the thread after recent activity + * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected + * @param applied_tags List of IDs of forum tags (dpp::forum_tag) to apply to this thread + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::thread object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void thread_create_in_forum(const std::string& thread_name, snowflake channel_id, const message& msg, auto_archive_duration_t auto_archive_duration, uint16_t rate_limit_per_user, std::vector applied_tags = {}, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Create a thread + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see https://discord.com/developers/docs/resources/guild#create-guild-channel + * @param thread_name Name of the thread + * @param channel_id Channel in which thread to create + * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) + * @param thread_type Type of thread - CHANNEL_PUBLIC_THREAD, CHANNEL_ANNOUNCEMENT_THREAD, CHANNEL_PRIVATE_THREAD + * @param invitable whether non-moderators can add other non-moderators to a thread; only available when creating a private thread + * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::thread object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void thread_create(const std::string& thread_name, snowflake channel_id, uint16_t auto_archive_duration, channel_type thread_type, bool invitable, uint16_t rate_limit_per_user, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Create a thread with a message (Discord: ID of a thread is same as message ID) + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/topics/threads + * @param thread_name Name of the thread + * @param channel_id Channel in which thread to create + * @param message_id message to start thread with + * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) + * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::thread object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void thread_create_with_message(const std::string& thread_name, snowflake channel_id, snowflake message_id, uint16_t auto_archive_duration, uint16_t rate_limit_per_user, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Join a thread + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread ID to join + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void current_user_join_thread(snowflake thread_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Leave a thread + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread ID to leave + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void current_user_leave_thread(snowflake thread_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Add a member to a thread + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread ID to add to + * @param user_id Member ID to add + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void thread_member_add(snowflake thread_id, snowflake user_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Remove a member from a thread + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread ID to remove from + * @param user_id Member ID to remove + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void thread_member_remove(snowflake thread_id, snowflake user_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get a thread member + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread to get member for + * @param user_id ID of the user to get + * @param callback Function to call when the API call completes + * On success the callback will contain a dpp::thread_member object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void thread_member_get(const snowflake thread_id, const snowflake user_id, command_completion_event_t callback); + + /** + * @brief Get members of a thread + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread to get members for + * @param callback Function to call when the API call completes + * On success the callback will contain a dpp::thread_member_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void thread_members_get(snowflake thread_id, command_completion_event_t callback); + + /** + * @brief Get active threads in a guild (Sorted by ID in descending order) + * @see https://discord.com/developers/docs/topics/threads + * @param guild_id Guild to get active threads for + * @param callback Function to call when the API call completes + * On success the callback will contain a dpp::thread_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void threads_get_active(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get public archived threads in a channel (Sorted by archive_timestamp in descending order) + * @see https://discord.com/developers/docs/topics/threads + * @param channel_id Channel to get public archived threads for + * @param before_timestamp Get threads before this timestamp + * @param limit Number of threads to get + * @param callback Function to call when the API call completes + * On success the callback will contain a dpp::thread_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void threads_get_public_archived(snowflake channel_id, time_t before_timestamp, uint16_t limit, command_completion_event_t callback); + + /** + * @brief Get private archived threads in a channel (Sorted by archive_timestamp in descending order) + * @see https://discord.com/developers/docs/topics/threads + * @param channel_id Channel to get public archived threads for + * @param before_timestamp Get threads before this timestamp + * @param limit Number of threads to get + * @param callback Function to call when the API call completes + * On success the callback will contain a dpp::thread_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void threads_get_private_archived(snowflake channel_id, time_t before_timestamp, uint16_t limit, command_completion_event_t callback); + + /** + * @brief Get private archived threads in a channel which current user has joined (Sorted by ID in descending order) + + * @see https://discord.com/developers/docs/topics/threads + * @param channel_id Channel to get public archived threads for + * @param before_id Get threads before this id + * @param limit Number of threads to get + * @param callback Function to call when the API call completes + * On success the callback will contain a dpp::thread_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void threads_get_joined_private_archived(snowflake channel_id, snowflake before_id, uint16_t limit, command_completion_event_t callback); + + /** + * @brief Create a sticker in a guild + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/sticker#create-guild-sticker + * @param s Sticker to create. Must have its guild ID set. + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_sticker_create(sticker &s, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Modify a sticker in a guild + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/sticker#modify-guild-sticker + * @param s Sticker to modify. Must have its guild ID and sticker ID set. + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_sticker_modify(sticker &s, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a sticker from a guild + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/sticker#delete-guild-sticker + * @param sticker_id sticker ID to delete + * @param guild_id guild ID to delete from + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_sticker_delete(snowflake sticker_id, snowflake guild_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get a nitro sticker + * @see https://discord.com/developers/docs/resources/sticker#get-sticker + * @param id Id of sticker to get. + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void nitro_sticker_get(snowflake id, command_completion_event_t callback); + + /** + * @brief Get a guild sticker + * @see https://discord.com/developers/docs/resources/sticker#get-guild-sticker + * @param id Id of sticker to get. + * @param guild_id Guild ID of the guild where the sticker is + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_sticker_get(snowflake id, snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get all guild stickers + * @see https://discord.com/developers/docs/resources/sticker#get-guild-stickers + * @param guild_id Guild ID of the guild where the sticker is + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::sticker_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_stickers_get(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get sticker packs + * @see https://discord.com/developers/docs/resources/sticker#list-nitro-sticker-packs + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::sticker_pack_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void sticker_packs_get(command_completion_event_t callback); + + /** + * @brief Create a stage instance on a stage channel. + * @see https://discord.com/developers/docs/resources/stage-instance#create-stage-instance + * @param instance Stage instance to create + * @param callback User function to execute when the api call completes + * On success the callback will contain a dpp::stage_instance object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + */ + void stage_instance_create(const stage_instance& instance, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get the stage instance associated with the channel id, if it exists. + * @see https://discord.com/developers/docs/resources/stage-instance#get-stage-instance + * @param channel_id ID of the associated channel + * @param callback User function to execute when the api call completes + * On success the callback will contain a dpp::stage_instance object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void stage_instance_get(const snowflake channel_id, command_completion_event_t callback); + + /** + * @brief Edit a stage instance. + * @see https://discord.com/developers/docs/resources/stage-instance#modify-stage-instance + * @param instance Stage instance to edit + * @param callback User function to execute when the api call completes + * On success the callback will contain a dpp::stage_instance object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + */ + void stage_instance_edit(const stage_instance& instance, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a stage instance. + * @see https://discord.com/developers/docs/resources/stage-instance#delete-stage-instance + * @param channel_id ID of the associated channel + * @param callback User function to execute when the api call completes + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + */ + void stage_instance_delete(const snowflake channel_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get all voice regions + * @see https://discord.com/developers/docs/resources/voice#list-voice-regions + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::voiceregion_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void get_voice_regions(command_completion_event_t callback); + + /** + * @brief Get the gateway information for the bot using the token + * @see https://discord.com/developers/docs/topics/gateway#get-gateway-bot + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::gateway object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void get_gateway_bot(command_completion_event_t callback); + + /** + * @brief Get all scheduled events for a guild + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#list-scheduled-events-for-guild + * @param guild_id Guild to get events for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::scheduled_event_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_events_get(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get users RSVP'd to an event + * + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#get-guild-scheduled-event-users + * @param guild_id Guild to get user list for + * @param event_id Guild to get user list for + * @param limit Maximum number of results to return + * @param before Return user IDs that fall before this ID, if provided + * @param after Return user IDs that fall after this ID, if provided + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::event_member_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_event_users_get(snowflake guild_id, snowflake event_id, command_completion_event_t callback, uint8_t limit = 100, snowflake before = 0, snowflake after = 0); + + /** + * @brief Create a scheduled event on a guild + * + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#create-guild-scheduled-event + * @param event Event to create (guild ID must be populated) + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::scheduled_event_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_event_create(const scheduled_event& event, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a scheduled event from a guild + * + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#delete-guild-scheduled-event + * @param event_id Event ID to delete + * @param guild_id Guild ID of event to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_event_delete(snowflake event_id, snowflake guild_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit/modify a scheduled event on a guild + * + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#modify-guild-scheduled-event + * @param event Event to create (event ID and guild ID must be populated) + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::scheduled_event_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_event_edit(const scheduled_event& event, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get a scheduled event for a guild + * + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#get-guild-scheduled-event + * @param guild_id Guild to get event for + * @param event_id Event ID to get + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::scheduled_event object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_event_get(snowflake guild_id, snowflake event_id, command_completion_event_t callback); + + /** + * @brief Set the bot's voice state on a stage channel + * + * **Caveats** + * + * There are currently several caveats for this endpoint: + * + * - `channel_id` must currently point to a stage channel. + * - current user must already have joined `channel_id`. + * - You must have the `MUTE_MEMBERS` permission to unsuppress yourself. You can always suppress yourself. + * - You must have the `REQUEST_TO_SPEAK` permission to request to speak. You can always clear your own request to speak. + * - You are able to set `request_to_speak_timestamp` to any present or future time. + * + * @see https://discord.com/developers/docs/resources/guild#modify-current-user-voice-state + * @param guild_id Guild to set voice state on + * @param channel_id Stage channel to set voice state on + * @param callback Function to call when the API call completes. + * @param suppress True if the user's audio should be suppressed, false if it should not + * @param request_to_speak_timestamp The time at which we requested to speak, or 0 to clear the request. The time set here must be the current time or in the future. + * On success the callback will contain a dpp::scheduled_event object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + * @throw std::logic_exception You attempted to set a request_to_speak_timestamp in the past which is not the value of 0. + */ + void current_user_set_voice_state(snowflake guild_id, snowflake channel_id, bool suppress = false, time_t request_to_speak_timestamp = 0, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Set a user's voice state on a stage channel + * + * **Caveats** + * + * There are currently several caveats for this endpoint: + * + * - `channel_id` must currently point to a stage channel. + * - User must already have joined `channel_id`. + * - You must have the `MUTE_MEMBERS` permission. (Since suppression is the only thing that is available currently) + * - When unsuppressed, non-bot users will have their `request_to_speak_timestamp` set to the current time. Bot users will not. + * - When suppressed, the user will have their `request_to_speak_timestamp` removed. + * + * @see https://discord.com/developers/docs/resources/guild#modify-user-voice-state + * @param user_id The user to set the voice state of + * @param guild_id Guild to set voice state on + * @param channel_id Stage channel to set voice state on + * @param callback Function to call when the API call completes. + * @param suppress True if the user's audio should be suppressed, false if it should not + * On success the callback will contain a dpp::scheduled_event object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void user_set_voice_state(snowflake user_id, snowflake guild_id, snowflake channel_id, bool suppress = false, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get all auto moderation rules for a guild + * + * @param guild_id Guild id of the auto moderation rule + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::automod_rule_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void automod_rules_get(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get a single auto moderation rule + * + * @param guild_id Guild id of the auto moderation rule + * @param rule_id Rule id to retrieve + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::automod_rule object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void automod_rule_get(snowflake guild_id, snowflake rule_id, command_completion_event_t callback); + + /** + * @brief Create an auto moderation rule + * + * @param guild_id Guild id of the auto moderation rule + * @param r Auto moderation rule to create + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::automod_rule object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void automod_rule_create(snowflake guild_id, const automod_rule& r, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit an auto moderation rule + * + * @param guild_id Guild id of the auto moderation rule + * @param r Auto moderation rule to edit. The rule's id must be set. + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::automod_rule object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void automod_rule_edit(snowflake guild_id, const automod_rule& r, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete an auto moderation rule + * + * @param guild_id Guild id of the auto moderation rule + * @param rule_id Auto moderation rule id to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void automod_rule_delete(snowflake guild_id, snowflake rule_id, command_completion_event_t callback = utility::log_error()); + +#include +#ifdef DPP_CORO +#include +#endif + +}; + +}; diff --git a/3rdParty/dpp/cluster_coro_calls.h b/3rdParty/dpp/cluster_coro_calls.h index aaf4afa6f7..46b305a519 100644 --- a/3rdParty/dpp/cluster_coro_calls.h +++ b/3rdParty/dpp/cluster_coro_calls.h @@ -1,2316 +1,2316 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2022 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - - -/* Auto @generated by buildtools/make_coro_struct.php. - * - * DO NOT EDIT BY HAND! - * - * To re-generate this header file re-run the script! - */ -/** - * @brief Create/overwrite global slash commands. - * Any existing global slash commands will be deleted and replaced with these. - * - * @see dpp::cluster::global_bulk_command_create - * @see https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-global-application-commands - * @param commands Vector of slash commands to create/update. - * overwriting existing commands that are registered globally for this application. Updates will be available in all guilds after 1 hour. - * Commands that do not already exist will count toward daily application command create limits. - * @return slashcommand_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_global_bulk_command_create(const std::vector &commands) { - return dpp::awaitable(this, [&] (auto cc) { this->global_bulk_command_create(commands, cc); }); -} - -/** - * @brief Create a global slash command (a bot can have a maximum of 100 of these). - * - * @see dpp::cluster::global_command_create - * @see https://discord.com/developers/docs/interactions/application-commands#create-global-application-command - * @param s Slash command to create - * @return slashcommand returned object on completion - * \memberof dpp::cluster - */ -auto inline co_global_command_create(const slashcommand &s) { - return dpp::awaitable(this, [&] (auto cc) { this->global_command_create(s, cc); }); -} - -/** - * @brief Get a global slash command - * - * @see dpp::cluster::global_command_get - * @see https://discord.com/developers/docs/interactions/application-commands#get-global-application-command - * @param id The ID of the slash command - * @return slashcommand returned object on completion - * \memberof dpp::cluster - */ -auto inline co_global_command_get(snowflake id) { - return dpp::awaitable(this, [&] (auto cc) { this->global_command_get(id, cc); }); -} - -/** - * @brief Delete a global slash command (a bot can have a maximum of 100 of these) - * - * @see dpp::cluster::global_command_delete - * @see https://discord.com/developers/docs/interactions/application-commands#delete-global-application-command - * @param id Slash command to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_global_command_delete(snowflake id) { - return dpp::awaitable(this, [&] (auto cc) { this->global_command_delete(id, cc); }); -} - -/** - * @brief Edit a global slash command (a bot can have a maximum of 100 of these) - * - * @see dpp::cluster::global_command_edit - * @see https://discord.com/developers/docs/interactions/application-commands#edit-global-application-command - * @param s Slash command to change - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_global_command_edit(const slashcommand &s) { - return dpp::awaitable(this, [&] (auto cc) { this->global_command_edit(s, cc); }); -} - -/** - * @brief Get the application's global slash commands - * - * @see dpp::cluster::global_commands_get - * @see https://discord.com/developers/docs/interactions/application-commands#get-global-application-commands - * @return slashcommand_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_global_commands_get() { - return dpp::awaitable(this, [&] (auto cc) { this->global_commands_get(cc); }); -} - -/** - * @brief Create/overwrite guild slash commands. - * Any existing guild slash commands on this guild will be deleted and replaced with these. - * - * @see dpp::cluster::guild_bulk_command_create - * @see https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-guild-application-commands - * @param commands Vector of slash commands to create/update. - * New guild commands will be available in the guild immediately. If the command did not already exist, it will count toward daily application command create limits. - * @param guild_id Guild ID to create/update the slash commands in - * @return slashcommand_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_bulk_command_create(const std::vector &commands, snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_bulk_command_create(commands, guild_id, cc); }); -} - -/** - * @brief Get all slash command permissions of a guild - * - * @see dpp::cluster::guild_commands_get_permissions - * @see https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions - * @param guild_id Guild ID to get the slash commands permissions for - * @return guild_command_permissions_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_commands_get_permissions(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_commands_get_permissions(guild_id, cc); }); -} - -/** - * @brief Edit/Overwrite the permissions of all existing slash commands in a guild - * - * @note You can only add up to 10 permission overwrites for a command - * - * @see dpp::cluster::guild_bulk_command_edit_permissions - * @see https://discord.com/developers/docs/interactions/application-commands#batch-edit-application-command-permissions - * @warning The endpoint will overwrite all existing permissions for all commands of the application in a guild, including slash commands, user commands, and message commands. Meaning that if you forgot to pass a slash command, the permissions of it might be removed. - * @param commands A vector of slash commands to edit/overwrite the permissions for - * @param guild_id Guild ID to edit permissions of the slash commands in - * @return guild_command_permissions_map returned object on completion - * @deprecated This has been disabled with updates to Permissions v2. You can use guild_command_edit_permissions instead - * \memberof dpp::cluster - */ -auto inline co_guild_bulk_command_edit_permissions(const std::vector &commands, snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_bulk_command_edit_permissions(commands, guild_id, cc); }); -} - -/** - * @brief Create a slash command local to a guild - * - * @see dpp::cluster::guild_command_create - * @see https://discord.com/developers/docs/interactions/application-commands#create-guild-application-command - * @note Creating a command with the same name as an existing command for your application will overwrite the old command. - * @param s Slash command to create - * @param guild_id Guild ID to create the slash command in - * @return slashcommand returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_command_create(const slashcommand &s, snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_command_create(s, guild_id, cc); }); -} - -/** - * @brief Delete a slash command local to a guild - * - * @see dpp::cluster::guild_command_delete - * @see https://discord.com/developers/docs/interactions/application-commands#delete-guild-application-command - * @param id Slash command to delete - * @param guild_id Guild ID to delete the slash command in - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_command_delete(snowflake id, snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_command_delete(id, guild_id, cc); }); -} - -/** - * @brief Edit slash command permissions of a guild - * - * @see dpp::cluster::guild_command_edit_permissions - * @see https://discord.com/developers/docs/interactions/application-commands#edit-application-command-permissions - * @note You can only add up to 10 permission overwrites for a command - * @param s Slash command to edit the permissions for - * @param guild_id Guild ID to edit the slash command in - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_command_edit_permissions(const slashcommand &s, snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_command_edit_permissions(s, guild_id, cc); }); -} - -/** - * @brief Get a slash command of a guild - * - * @see dpp::cluster::guild_command_get - * @see https://discord.com/developers/docs/interactions/application-commands#get-guild-application-command - * @note The returned slash commands will not have permissions set, you need to use a permissions getter e.g. dpp::guild_commands_get_permissions to get the guild command permissions - * @param id The ID of the slash command - * @param guild_id Guild ID to get the slash command from - * @return slashcommand returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_command_get(snowflake id, snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_command_get(id, guild_id, cc); }); -} - -/** - * @brief Get the permissions for a slash command of a guild - * - * @see dpp::cluster::guild_command_get_permissions - * @see https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions - * @param id The ID of the slash command to get the permissions for - * @param guild_id Guild ID to get the permissions of - * @return guild_command_permissions returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_command_get_permissions(snowflake id, snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_command_get_permissions(id, guild_id, cc); }); -} - -/** - * @brief Edit a slash command local to a guild - * - * @see dpp::cluster::guild_command_edit - * @see https://discord.com/developers/docs/interactions/application-commands#edit-guild-application-command - * @param s Slash command to edit - * @param guild_id Guild ID to edit the slash command in - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_command_edit(const slashcommand &s, snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_command_edit(s, guild_id, cc); }); -} - -/** - * @brief Get the application's slash commands for a guild - * - * @see dpp::cluster::guild_commands_get - * @see https://discord.com/developers/docs/interactions/application-commands#get-guild-application-commands - * @note The returned slash commands will not have permissions set, you need to use a permissions getter e.g. dpp::guild_commands_get_permissions to get the guild command permissions - * @param guild_id Guild ID to get the slash commands for - * @return slashcommand_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_commands_get(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_commands_get(guild_id, cc); }); -} - -/** - * @brief Respond to a slash command - * - * @see dpp::cluster::interaction_response_create - * @see https://discord.com/developers/docs/interactions/receiving-and-responding#create-interaction-response - * @param interaction_id Interaction id to respond to - * @param token Token for the interaction webhook - * @param r Response to send - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_interaction_response_create(snowflake interaction_id, const std::string &token, const interaction_response &r) { - return dpp::awaitable(this, [&] (auto cc) { this->interaction_response_create(interaction_id, token, r, cc); }); -} - -/** - * @brief Edit response to a slash command - * - * @see dpp::cluster::interaction_response_edit - * @see https://discord.com/developers/docs/interactions/receiving-and-responding#edit-original-interaction-response - * @param token Token for the interaction webhook - * @param m Message to send - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_interaction_response_edit(const std::string &token, const message &m) { - return dpp::awaitable(this, [&] (auto cc) { this->interaction_response_edit(token, m, cc); }); -} - -/** - * @brief Create a followup message to a slash command - * - * @param token Token for the interaction webhook - * @param m followup message to create - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_interaction_followup_create(const std::string &token, const message &m) { - return dpp::awaitable(this, [&] (auto cc) { this->interaction_followup_create(token, m, cc); }); -} - -/** - * @brief Edit original followup message to a slash command - * This is an alias for cluster::interaction_response_edit - * @see dpp::cluster::interaction_followup_edit_original - * @see cluster::interaction_response_edit - * - * @param token Token for the interaction webhook - * @param m message to edit, the ID should be set - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_interaction_followup_edit_original(const std::string &token, const message &m) { - return dpp::awaitable(this, [&] (auto cc) { this->interaction_followup_edit_original(token, m, cc); }); -} - -/** - * @brief - * - * @param token Token for the interaction webhook - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_interaction_followup_delete(const std::string &token) { - return dpp::awaitable(this, [&] (auto cc) { this->interaction_followup_delete(token, cc); }); -} - -/** - * @brief Edit followup message to a slash command - * The message ID in the message you pass should be correctly set to that of a followup message you previously sent - * @param token Token for the interaction webhook - * @param m message to edit, the ID should be set - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_interaction_followup_edit(const std::string &token, const message &m) { - return dpp::awaitable(this, [&] (auto cc) { this->interaction_followup_edit(token, m, cc); }); -} - -/** - * @brief Get the followup message to a slash command - * @param token Token for the interaction webhook - * @param message_id message to retrieve - * @return message returned object on completion - * \memberof dpp::cluster - */ -auto inline co_interaction_followup_get(const std::string &token, snowflake message_id) { - return dpp::awaitable(this, [&] (auto cc) { this->interaction_followup_get(token, message_id, cc); }); -} - -/** - * @brief Get all auto moderation rules for a guild - * - * @param guild_id Guild id of the auto moderation rule - * @return automod_rule_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_automod_rules_get(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->automod_rules_get(guild_id, cc); }); -} - -/** - * @brief Get a single auto moderation rule - * - * @param guild_id Guild id of the auto moderation rule - * @param rule_id Rule id to retrieve - * @return automod_rule returned object on completion - * \memberof dpp::cluster - */ -auto inline co_automod_rule_get(snowflake guild_id, snowflake rule_id) { - return dpp::awaitable(this, [&] (auto cc) { this->automod_rule_get(guild_id, rule_id, cc); }); -} - -/** - * @brief Create an auto moderation rule - * - * @param guild_id Guild id of the auto moderation rule - * @param r Auto moderation rule to create - * @return automod_rule returned object on completion - * \memberof dpp::cluster - */ -auto inline co_automod_rule_create(snowflake guild_id, const automod_rule& r) { - return dpp::awaitable(this, [&] (auto cc) { this->automod_rule_create(guild_id, r, cc); }); -} - -/** - * @brief Edit an auto moderation rule - * - * @param guild_id Guild id of the auto moderation rule - * @param r Auto moderation rule to edit. The rule's id must be set. - * @return automod_rule returned object on completion - * \memberof dpp::cluster - */ -auto inline co_automod_rule_edit(snowflake guild_id, const automod_rule& r) { - return dpp::awaitable(this, [&] (auto cc) { this->automod_rule_edit(guild_id, r, cc); }); -} - -/** - * @brief Delete an auto moderation rule - * - * @param guild_id Guild id of the auto moderation rule - * @param rule_id Auto moderation rule id to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_automod_rule_delete(snowflake guild_id, snowflake rule_id) { - return dpp::awaitable(this, [&] (auto cc) { this->automod_rule_delete(guild_id, rule_id, cc); }); -} - -/** - * @brief Create a channel - * - * Create a new channel object for the guild. Requires the `MANAGE_CHANNELS` permission. If setting permission overwrites, - * only permissions your bot has in the guild can be allowed/denied. Setting `MANAGE_ROLES` permission in channels is only possible - * for guild administrators. Returns the new channel object on success. Fires a `Channel Create Gateway` event. - * - * All parameters to this endpoint are optional excluding `name` - * - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::channel_create - * @see https://discord.com/developers/docs/resources/channel#create-channel - * @param c Channel to create - * @return channel returned object on completion - * \memberof dpp::cluster - */ -auto inline co_channel_create(const class channel &c) { - return dpp::awaitable(this, [&] (auto cc) { this->channel_create(c, cc); }); -} - -/** - * @brief Remove a permission from a channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::channel_delete_permission - * @see https://discord.com/developers/docs/resources/channel#delete-channel-permission - * @param c Channel to remove permission from - * @param overwrite_id Overwrite to remove, user or channel ID - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_channel_delete_permission(const class channel &c, snowflake overwrite_id) { - return dpp::awaitable(this, [&] (auto cc) { this->channel_delete_permission(c, overwrite_id, cc); }); -} - -/** - * @brief Delete a channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::channel_delete - * @see https://discord.com/developers/docs/resources/channel#deleteclose-channel - * @param channel_id Channel id to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_channel_delete(snowflake channel_id) { - return dpp::awaitable(this, [&] (auto cc) { this->channel_delete(channel_id, cc); }); -} - -/** - * @brief Edit multiple channels positions - * - * Modify the positions of a set of channel objects for the guild. - * Requires `MANAGE_CHANNELS` permission. Fires multiple `Channel Update Gateway` events. - * Only channels to be modified are required. - * - * @see dpp::cluster::channel_edit_positions - * @see https://discord.com/developers/docs/resources/guild#modify-guild-channel-positions - * @param c Channel to change the position for - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_channel_edit_positions(const std::vector &c) { - return dpp::awaitable(this, [&] (auto cc) { this->channel_edit_positions(c, cc); }); -} - -/** - * @brief Edit a channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::channel_edit - * @see https://discord.com/developers/docs/resources/channel#modify-channel - * @param c Channel to edit/update - * @return channel returned object on completion - * \memberof dpp::cluster - */ -auto inline co_channel_edit(const class channel &c) { - return dpp::awaitable(this, [&] (auto cc) { this->channel_edit(c, cc); }); -} - -/** - * @brief Follow an announcement (news) channel - * @see dpp::cluster::channel_follow_news - * @see https://discord.com/developers/docs/resources/channel#follow-news-channel - * @param c Channel id to follow - * @param target_channel_id Channel to subscribe the channel to - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_channel_follow_news(const class channel &c, snowflake target_channel_id) { - return dpp::awaitable(this, [&] (auto cc) { this->channel_follow_news(c, target_channel_id, cc); }); -} - -/** - * @brief Get a channel - * - * @see dpp::cluster::channel_get - * @see https://discord.com/developers/docs/resources/channel#get-channel - * @param c Channel ID to retrieve - * @return channel returned object on completion - * \memberof dpp::cluster - */ -auto inline co_channel_get(snowflake c) { - return dpp::awaitable(this, [&] (auto cc) { this->channel_get(c, cc); }); -} - -/** - * @brief Create invite for a channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::channel_invite_create - * @see https://discord.com/developers/docs/resources/channel#create-channel-invite - * @param c Channel to create an invite on - * @param i Invite to create - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_channel_invite_create(const class channel &c, const class invite &i) { - return dpp::awaitable(this, [&] (auto cc) { this->channel_invite_create(c, i, cc); }); -} - -/** - * @brief Get invites for a channel - * - * @see dpp::cluster::channel_invites_get - * @see https://discord.com/developers/docs/resources/invite#get-invites - * @param c Channel to get invites for - * @return invite_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_channel_invites_get(const class channel &c) { - return dpp::awaitable(this, [&] (auto cc) { this->channel_invites_get(c, cc); }); -} - -/** - * @brief Get all channels for a guild - * - * @see dpp::cluster::channels_get - * @see https://discord.com/developers/docs/resources/channel#get-channels - * @param guild_id Guild ID to retrieve channels for - * @return channel_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_channels_get(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->channels_get(guild_id, cc); }); -} - -/** - * @brief Create a dm channel - * @see dpp::cluster::create_dm_channel - * @see https://discord.com/developers/docs/resources/user#create-dm - * @param user_id User ID to create DM channel with - * @return channel returned object on completion - * \memberof dpp::cluster - */ -auto inline co_create_dm_channel(snowflake user_id) { - return dpp::awaitable(this, [&] (auto cc) { this->create_dm_channel(user_id, cc); }); -} - -/** - * @brief Get current user DM channels - * - * @return channel_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_current_user_get_dms() { - return dpp::awaitable(this, [&] (auto cc) { this->current_user_get_dms(cc); }); -} - -/** - * @brief Create a direct message, also create the channel for the direct message if needed - * - * @see dpp::cluster::direct_message_create - * @see https://discord.com/developers/docs/resources/user#create-dm - * @see dpp::cluster::direct_message_create - * @see https://discord.com/developers/docs/resources/channel#create-message - * @param user_id User ID of user to send message to - * @param m Message object - * @return message returned object on completion - * \memberof dpp::cluster - */ -auto inline co_direct_message_create(snowflake user_id, const message &m) { - return dpp::awaitable(this, [&] (auto cc) { this->direct_message_create(user_id, m, cc); }); -} - -/** - * @brief Adds a recipient to a Group DM using their access token - * @see dpp::cluster::gdm_add - * @see https://discord.com/developers/docs/resources/channel#group-dm-add-recipient - * @param channel_id Channel id to add group DM recipients to - * @param user_id User ID to add - * @param access_token Access token from OAuth2 - * @param nick Nickname of user to apply to the chat - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_gdm_add(snowflake channel_id, snowflake user_id, const std::string &access_token, const std::string &nick) { - return dpp::awaitable(this, [&] (auto cc) { this->gdm_add(channel_id, user_id, access_token, nick, cc); }); -} - -/** - * @brief Removes a recipient from a Group DM - * @see dpp::cluster::gdm_remove - * @see https://discord.com/developers/docs/resources/channel#group-dm-remove-recipient - * @param channel_id Channel ID of group DM - * @param user_id User ID to remove from group DM - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_gdm_remove(snowflake channel_id, snowflake user_id) { - return dpp::awaitable(this, [&] (auto cc) { this->gdm_remove(channel_id, user_id, cc); }); -} - -/** - * @brief Create single emoji. - * You must ensure that the emoji passed contained image data using the emoji::load_image() method. - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see dpp::cluster::guild_emoji_create - * @see https://discord.com/developers/docs/resources/emoji#create-guild-emoji - * @param guild_id Guild ID to create emoji om - * @param newemoji Emoji to create - * @return emoji returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_emoji_create(snowflake guild_id, const class emoji& newemoji) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_emoji_create(guild_id, newemoji, cc); }); -} - -/** - * @brief Delete a guild emoji - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see dpp::cluster::guild_emoji_delete - * @see https://discord.com/developers/docs/resources/emoji#delete-guild-emoji - * @param guild_id Guild ID to delete emoji on - * @param emoji_id Emoji ID to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_emoji_delete(snowflake guild_id, snowflake emoji_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_emoji_delete(guild_id, emoji_id, cc); }); -} - -/** - * @brief Edit a single emoji. - * - * You must ensure that the emoji passed contained image data using the emoji::load_image() method. - * @see dpp::cluster::guild_emoji_edit - * @see https://discord.com/developers/docs/resources/emoji#get-guild-emoji - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to edit emoji on - * @param newemoji Emoji to edit - * @return emoji returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_emoji_edit(snowflake guild_id, const class emoji& newemoji) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_emoji_edit(guild_id, newemoji, cc); }); -} - -/** - * @brief Get a single emoji - * - * @see dpp::cluster::guild_emoji_get - * @see https://discord.com/developers/docs/resources/emoji#get-guild-emoji - * @param guild_id Guild ID to get emoji for - * @param emoji_id Emoji ID to get - * @return emoji returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_emoji_get(snowflake guild_id, snowflake emoji_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_emoji_get(guild_id, emoji_id, cc); }); -} - -/** - * @brief Get all emojis for a guild - * - * @see dpp::cluster::guild_emojis_get - * @see https://discord.com/developers/docs/resources/emoji#get-guild-emojis - * @param guild_id Guild ID to get emojis for - * @return emoji_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_emojis_get(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_emojis_get(guild_id, cc); }); -} - -/** - * @brief Get the gateway information for the bot using the token - * @see dpp::cluster::get_gateway_bot - * @see https://discord.com/developers/docs/topics/gateway#get-gateway-bot - * @return gateway returned object on completion - * \memberof dpp::cluster - */ -auto inline co_get_gateway_bot() { - return dpp::awaitable(this, [&] (auto cc) { this->get_gateway_bot(cc); }); -} - -/** - * @brief Modify current member - * - * Modifies the current member in a guild. - * Fires a `Guild Member Update` Gateway event. - * - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::guild_current_member_edit - * @see https://discord.com/developers/docs/resources/guild#modify-current-member - * @param guild_id Guild ID to change on - * @param nickname New nickname, or empty string to clear nickname - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_current_member_edit(snowflake guild_id, const std::string &nickname) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_current_member_edit(guild_id, nickname, cc); }); -} - -/** - * @brief Get the audit log for a guild - * - * @see dpp::cluster::guild_auditlog_get - * @see https://discord.com/developers/docs/resources/audit-log#get-guild-audit-log - * @param guild_id Guild to get the audit log of - * @param user_id Entries from a specific user ID. Set this to `0` will fetch any user - * @param action_type Entries for a specific dpp::audit_type. Set this to `0` will fetch any type - * @param before Entries that preceded a specific audit log entry ID. Used for paginating - * @param limit Maximum number of entries (between 1-100) to return - * @return auditlog returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_auditlog_get(snowflake guild_id, snowflake user_id, uint32_t action_type, snowflake before, uint32_t limit) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_auditlog_get(guild_id, user_id, action_type, before, limit, cc); }); -} - -/** - * @brief Add guild ban - * - * Create a guild ban, and optionally delete previous messages sent by the banned user. - * Requires the `BAN_MEMBERS` permission. Fires a `Guild Ban Add` Gateway event. - * @see dpp::cluster::guild_ban_add - * @see https://discord.com/developers/docs/resources/guild#create-guild-ban - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to add ban to - * @param user_id User ID to ban - * @param delete_message_seconds How many seconds to delete messages for, between 0 and 604800 (7 days). Defaults to 0 - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_ban_add(snowflake guild_id, snowflake user_id, uint32_t delete_message_seconds) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_ban_add(guild_id, user_id, delete_message_seconds, cc); }); -} - -/** - * @brief Delete guild ban - * - * Remove the ban for a user. Requires the `BAN_MEMBERS` permissions. - * Fires a Guild Ban Remove Gateway event. - * @see dpp::cluster::guild_ban_delete - * @see https://discord.com/developers/docs/resources/guild#remove-guild-ban - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild to delete ban from - * @param user_id User ID to delete ban for - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_ban_delete(snowflake guild_id, snowflake user_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_ban_delete(guild_id, user_id, cc); }); -} - -/** - * @brief Create a guild - * - * Create a new guild. Returns a guild object on success. `Fires a Guild Create Gateway` event. - * - * When using the roles parameter, the first member of the array is used to change properties of the guild's everyone role. - * If you are trying to bootstrap a guild with additional roles, keep this in mind. The required id field within each role object is an - * integer placeholder, and will be replaced by the API upon consumption. Its purpose is to allow you to overwrite a role's permissions - * in a channel when also passing in channels with the channels array. - * When using the channels parameter, the position field is ignored, and none of the default channels are created. The id field within - * each channel object may be set to an integer placeholder, and will be replaced by the API upon consumption. Its purpose is to - * allow you to create `GUILD_CATEGORY` channels by setting the `parent_id` field on any children to the category's id field. - * Category channels must be listed before any children. - * - * @see dpp::cluster::guild_create - * @see https://discord.com/developers/docs/resources/guild#create-guild - * @note The region field is deprecated and is replaced by channel.rtc_region. This endpoint can be used only by bots in less than 10 guilds. - * @param g Guild to create - * @return guild returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_create(const class guild &g) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_create(g, cc); }); -} - -/** - * @brief Delete a guild - * - * Delete a guild permanently. User must be owner. Fires a `Guild Delete Gateway` event. - * - * @see dpp::cluster::guild_delete - * @see https://discord.com/developers/docs/resources/guild#delete-guild - * @param guild_id Guild ID to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_delete(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_delete(guild_id, cc); }); -} - -/** - * @brief Delete guild integration - * - * Delete the attached integration object for the guild. Deletes any associated webhooks and kicks the associated bot if there is one. - * Requires the `MANAGE_GUILD` permission. Fires a Guild Integrations Update Gateway event. - * - * @see dpp::cluster::guild_delete_integration - * @see https://discord.com/developers/docs/resources/guild#delete-guild-integration - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to delete integration for - * @param integration_id Integration ID to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_delete_integration(snowflake guild_id, snowflake integration_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_delete_integration(guild_id, integration_id, cc); }); -} - -/** - * @brief Edit a guild - * - * Modify a guild's settings. Requires the `MANAGE_GUILD` permission. Returns the updated guild object on success. - * Fires a `Guild Update Gateway` event. - * - * @see dpp::cluster::guild_edit - * @see https://discord.com/developers/docs/resources/guild#modify-guild - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param g Guild to edit - * @return guild returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_edit(const class guild &g) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_edit(g, cc); }); -} - -/** - * @brief Edit guild widget - * - * Requires the `MANAGE_GUILD` permission. - * - * @see dpp::cluster::guild_edit_widget - * @see https://discord.com/developers/docs/resources/guild#modify-guild-widget - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to edit widget for - * @param gw New guild widget information - * @return guild_widget returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_edit_widget(snowflake guild_id, const class guild_widget &gw) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_edit_widget(guild_id, gw, cc); }); -} - -/** - * @brief Get single guild ban - * - * Requires the `BAN_MEMBERS` permission. - * @see dpp::cluster::guild_get_ban - * @see https://discord.com/developers/docs/resources/guild#get-guild-ban - * @param guild_id Guild ID to get ban for - * @param user_id User ID of ban to retrieve - * @return ban returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_get_ban(snowflake guild_id, snowflake user_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_get_ban(guild_id, user_id, cc); }); -} - -/** - * @brief Get guild ban list - * - * Requires the `BAN_MEMBERS` permission. - * @see dpp::cluster::guild_get_bans - * @see https://discord.com/developers/docs/resources/guild#get-guild-bans - * @note Provide a user ID to `before` and `after` for pagination. Users will always be returned in ascending order by the user ID. If both before and after are provided, only before is respected. - * @param guild_id Guild ID to get bans for - * @param before If non-zero, all bans for user ids before this user id will be returned up to the limit - * @param after if non-zero, all bans for user ids after this user id will be returned up to the limit - * @param limit the maximum number of bans to retrieve in this call up to a maximum of 1000 - * @return ban_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_get_bans(snowflake guild_id, snowflake before, snowflake after, snowflake limit) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_get_bans(guild_id, before, after, limit, cc); }); -} - - -auto inline co_guild_get(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_get(guild_id, cc); }); -} - -/** - * @brief Get guild integrations - * - * Requires the `MANAGE_GUILD` permission. - * - * @see dpp::cluster::guild_get_integrations - * @see https://discord.com/developers/docs/resources/guild#get-guild-integrations - * @param guild_id Guild ID to get integrations for - * @return integration_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_get_integrations(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_get_integrations(guild_id, cc); }); -} - - -auto inline co_guild_get_preview(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_get_preview(guild_id, cc); }); -} - -/** - * @brief Get guild vanity url, if enabled - * - * Returns a partial dpp::invite object for guilds with that feature enabled. Requires the `MANAGE_GUILD` permission. code will be null if a vanity url for the guild is not set. - * @see dpp::cluster::guild_get_vanity - * @see https://discord.com/developers/docs/resources/guild#get-guild-vanity-url - * @param guild_id Guild to get vanity URL for - * @return invite returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_get_vanity(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_get_vanity(guild_id, cc); }); -} - -/** - * @brief Get guild widget - * - * Requires the `MANAGE_GUILD` permission. - * - * @see dpp::cluster::guild_get_widget - * @see https://discord.com/developers/docs/resources/guild#get-guild-widget - * @param guild_id Guild ID to get widget for - * @return guild_widget returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_get_widget(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_get_widget(guild_id, cc); }); -} - -/** - * @brief Modify guild integration - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see dpp::cluster::guild_modify_integration - * @see https://discord.com/developers/docs/resources/guild#modify-guild-integration - * @param guild_id Guild ID to modify integration for - * @param i Integration to modify - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_modify_integration(snowflake guild_id, const class integration &i) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_modify_integration(guild_id, i, cc); }); -} - -/** - * @brief Get prune counts - * - * Returns a prune object indicating the number of members that would be removed in a prune operation. Requires the `KICK_MEMBERS` - * permission. By default, prune will not remove users with roles. You can optionally include specific roles in your prune by providing the - * include_roles parameter. Any inactive user that has a subset of the provided role(s) will be counted in the prune and users with additional - * roles will not. - * - * @see dpp::cluster::guild_get_prune_counts - * @see https://discord.com/developers/docs/resources/guild#get-guild-prune-count - * @param guild_id Guild ID to count for pruning - * @param pruneinfo Pruning info - * @return prune returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_get_prune_counts(snowflake guild_id, const struct prune& pruneinfo) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_get_prune_counts(guild_id, pruneinfo, cc); }); -} - -/** - * @brief Begin guild prune - * - * Begin a prune operation. Requires the `KICK_MEMBERS` permission. Returns a prune object indicating the number of members - * that were removed in the prune operation. For large guilds it's recommended to set the `compute_prune_count` option to false, forcing - * 'pruned' to 0. Fires multiple `Guild Member Remove` Gateway events. - * By default, prune will not remove users with roles. You can optionally include specific roles in your prune by providing the `include_roles` - * parameter. Any inactive user that has a subset of the provided role(s) will be included in the prune and users with additional roles will not. - * - * @see dpp::cluster::guild_begin_prune - * @see https://discord.com/developers/docs/resources/guild#begin-guild-prune - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to prune - * @param pruneinfo Pruning info - * @return prune returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_begin_prune(snowflake guild_id, const struct prune& pruneinfo) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_begin_prune(guild_id, pruneinfo, cc); }); -} - -/** - * @brief Change current user nickname - * - * Modifies the nickname of the current user in a guild. - * Fires a `Guild Member Update` Gateway event. - * - * @deprecated Deprecated in favor of Modify Current Member. Will be replaced by dpp::cluster::guild_current_member_edit - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::guild_set_nickname - * @see https://discord.com/developers/docs/resources/guild#modify-current-user-nick - * @param guild_id Guild ID to change nickname on - * @param nickname New nickname, or empty string to clear nickname - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_set_nickname(snowflake guild_id, const std::string &nickname) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_set_nickname(guild_id, nickname, cc); }); -} - -/** - * @brief Sync guild integration - * - * @see dpp::cluster::guild_sync_integration - * @see https://discord.com/developers/docs/resources/guild#sync-guild-integration - * @param guild_id Guild ID to sync integration on - * @param integration_id Integration ID to synchronise - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_sync_integration(snowflake guild_id, snowflake integration_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_sync_integration(guild_id, integration_id, cc); }); -} - -/** - * @brief Add guild member. Needs a specific oauth2 scope, from which you get the access_token. - * - * Adds a user to the guild, provided you have a valid oauth2 access token for the user with the guilds.join scope. - * Returns the guild_member, which is defaulted if the user is already a member of the guild. Fires a `Guild Member Add` Gateway event. - * - * For guilds with Membership Screening enabled, this endpoint will default to adding new members as pending in the guild member object. - * Members that are pending will have to complete membership screening before they become full members that can talk. - * - * @note All parameters to this endpoint except for access_token are optional. - * The bot must be a member of the guild with `CREATE_INSTANT_INVITE` permission. - * @see dpp::cluster::guild_add_member - * @see https://discord.com/developers/docs/resources/guild#add-guild-member - * @param gm Guild member to add - * @param access_token Access token from Oauth2 scope - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_add_member(const guild_member& gm, const std::string &access_token) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_add_member(gm, access_token, cc); }); -} - -/** - * @brief Edit the properties of an existing guild member - * - * Modify attributes of a guild member. Returns the guild_member. Fires a `Guild Member Update` Gateway event. - * To remove a timeout, set the `communication_disabled_until` to a non-zero time in the past, e.g. 1. - * When moving members to channels, the API user must have permissions to both connect to the channel and have the `MOVE_MEMBERS` permission. - * For moving and disconnecting users from voice, use dpp::cluster::guild_member_move. - * @see dpp::cluster::guild_edit_member - * @see https://discord.com/developers/docs/resources/guild#modify-guild-member - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param gm Guild member to edit - * @return guild_member returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_edit_member(const guild_member& gm) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_edit_member(gm, cc); }); -} - -/** - * @brief Get a guild member - * @see dpp::cluster::guild_get_member - * @see https://discord.com/developers/docs/resources/guild#get-guild-member - * @param guild_id Guild ID to get member for - * @param user_id User ID of member to get - * @return guild_member returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_get_member(snowflake guild_id, snowflake user_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_get_member(guild_id, user_id, cc); }); -} - -/** - * @brief Get all guild members - * - * @note This endpoint is restricted according to whether the `GUILD_MEMBERS` Privileged Intent is enabled for your application. - * @see dpp::cluster::guild_get_members - * @see https://discord.com/developers/docs/resources/guild#get-guild-members - * @param guild_id Guild ID to get all members for - * @param limit max number of members to return (1-1000) - * @param after the highest user id in the previous page - * @return guild_member_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_get_members(snowflake guild_id, uint16_t limit, snowflake after) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_get_members(guild_id, limit, after, cc); }); -} - -/** - * @brief Add role to guild member - * - * Adds a role to a guild member. Requires the `MANAGE_ROLES` permission. - * Fires a `Guild Member Update` Gateway event. - * @see dpp::cluster::guild_member_add_role - * @see https://discord.com/developers/docs/resources/guild#add-guild-member-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to add a role to - * @param user_id User ID to add role to - * @param role_id Role ID to add to the user - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_member_add_role(snowflake guild_id, snowflake user_id, snowflake role_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_member_add_role(guild_id, user_id, role_id, cc); }); -} - -/** - * @brief Remove (kick) a guild member - * - * Remove a member from a guild. Requires `KICK_MEMBERS` permission. - * Fires a `Guild Member Remove` Gateway event. - * @see dpp::cluster::guild_member_delete - * @see https://discord.com/developers/docs/resources/guild#remove-guild-member - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @deprecated Replaced by dpp::cluster::guild_member_kick - * @param guild_id Guild ID to kick member from - * @param user_id User ID to kick - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_member_delete(snowflake guild_id, snowflake user_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_member_delete(guild_id, user_id, cc); }); -} - -/** - * @brief Remove (kick) a guild member - * - * Remove a member from a guild. Requires `KICK_MEMBERS` permission. - * Fires a `Guild Member Remove` Gateway event. - * @see dpp::cluster::guild_member_kick - * @see https://discord.com/developers/docs/resources/guild#remove-guild-member - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to kick member from - * @param user_id User ID to kick - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_member_kick(snowflake guild_id, snowflake user_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_member_kick(guild_id, user_id, cc); }); -} - -/** - * @brief Set the timeout of a guild member - * - * Fires a `Guild Member Update` Gateway event. - * @see dpp::cluster::guild_member_timeout - * @see https://discord.com/developers/docs/resources/guild#modify-guild-member - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to timeout the member in - * @param user_id User ID to set the timeout for - * @param communication_disabled_until The timestamp when the user's timeout will expire (up to 28 days in the future). Set to 0 to remove the timeout - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_member_timeout(snowflake guild_id, snowflake user_id, time_t communication_disabled_until) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_member_timeout(guild_id, user_id, communication_disabled_until, cc); }); -} - -/** - * @brief Remove role from guild member - * - * Removes a role from a guild member. Requires the `MANAGE_ROLES` permission. - * Fires a `Guild Member Update` Gateway event. - * @see dpp::cluster::guild_member_delete_role - * @see https://discord.com/developers/docs/resources/guild#remove-guild-member-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to remove role from user on - * @param user_id User ID to remove role from - * @param role_id Role to remove - * @return confirmation returned object on completion - * @deprecated Use dpp::cluster::guild_member_remove_role instead - * \memberof dpp::cluster - */ -auto inline co_guild_member_delete_role(snowflake guild_id, snowflake user_id, snowflake role_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_member_delete_role(guild_id, user_id, role_id, cc); }); -} - -/** - * @brief Remove role from guild member - * - * Removes a role from a guild member. Requires the `MANAGE_ROLES` permission. - * Fires a `Guild Member Update` Gateway event. - * @see dpp::cluster::guild_member_remove_role - * @see https://discord.com/developers/docs/resources/guild#remove-guild-member-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to remove role from user on - * @param user_id User ID to remove role from - * @param role_id Role to remove - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_member_remove_role(snowflake guild_id, snowflake user_id, snowflake role_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_member_remove_role(guild_id, user_id, role_id, cc); }); -} - -/** - * @brief Moves the guild member to a other voice channel, if member is connected to one. - * Set the `channel_id` to `0` to disconnect the user. - * - * Fires a `Guild Member Update` Gateway event. - * @note When moving members to channels, the API user __must__ have permissions to both connect to the channel and have the `MOVE_MEMBERS` permission. - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::guild_member_move - * @see https://discord.com/developers/docs/resources/guild#modify-guild-member - * @param channel_id Id of the channel to which the user is used. Set to `0` to disconnect the user - * @param guild_id Guild id to which the user is connected - * @param user_id User id, who should be moved - * @return guild_member returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_member_move(const snowflake channel_id, const snowflake guild_id, const snowflake user_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_member_move(channel_id, guild_id, user_id, cc); }); -} - -/** - * @brief Search for guild members based on whether their username or nickname starts with the given string. - * - * @note This endpoint is restricted according to whether the `GUILD_MEMBERS` Privileged Intent is enabled for your application. - * @see dpp::cluster::guild_search_members - * @see https://discord.com/developers/docs/resources/guild#search-guild-members - * @param guild_id Guild ID to search in - * @param query Query string to match username(s) and nickname(s) against - * @param limit max number of members to return (1-1000) - * @return guild_member_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_search_members(snowflake guild_id, const std::string& query, uint16_t limit) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_search_members(guild_id, query, limit, cc); }); -} - -/** - * @brief Get guild invites - * - * Returns a list of invite objects (with invite metadata) for the guild. Requires the `MANAGE_GUILD` permission. - * - * @see dpp::cluster::guild_get_invites - * @see https://discord.com/developers/docs/resources/guild#get-guild-invites - * @param guild_id Guild ID to get invites for - * @return invite_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_get_invites(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_get_invites(guild_id, cc); }); -} - - -auto inline co_invite_delete(const std::string &invitecode) { - return dpp::awaitable(this, [&] (auto cc) { this->invite_delete(invitecode, cc); }); -} - - -auto inline co_invite_get(const std::string &invitecode) { - return dpp::awaitable(this, [&] (auto cc) { this->invite_get(invitecode, cc); }); -} - -/** - * @brief Send a message to a channel. The callback function is called when the message has been sent - * - * @see dpp::cluster::message_create - * @see https://discord.com/developers/docs/resources/channel#create-message - * @param m Message to send - * @return message returned object on completion - * \memberof dpp::cluster - */ -auto inline co_message_create(const message &m) { - return dpp::awaitable(this, [&] (auto cc) { this->message_create(m, cc); }); -} - -/** - * @brief Crosspost a message. The callback function is called when the message has been sent - * - * @see dpp::cluster::message_crosspost - * @see https://discord.com/developers/docs/resources/channel#crosspost-message - * @param message_id Message to crosspost - * @param channel_id Channel ID to crosspost from - * @return message returned object on completion - * \memberof dpp::cluster - */ -auto inline co_message_crosspost(snowflake message_id, snowflake channel_id) { - return dpp::awaitable(this, [&] (auto cc) { this->message_crosspost(message_id, channel_id, cc); }); -} - -/** - * @brief Bulk delete messages from a channel. The callback function is called when the message has been edited - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @note If any message provided older than 2 weeks or any duplicate message ID, it will fail. - * - * @see dpp::cluster::message_delete_bulk - * @see https://discord.com/developers/docs/resources/channel#bulk-delete-messages - * @param message_ids List of message IDs to delete (at least 2 and at most 100 message IDs) - * @param channel_id Channel to delete from - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_message_delete_bulk(const std::vector& message_ids, snowflake channel_id) { - return dpp::awaitable(this, [&] (auto cc) { this->message_delete_bulk(message_ids, channel_id, cc); }); -} - -/** - * @brief Delete a message from a channel. The callback function is called when the message has been edited - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see dpp::cluster::message_delete - * @see https://discord.com/developers/docs/resources/channel#delete-message - * @param message_id Message ID to delete - * @param channel_id Channel to delete from - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_message_delete(snowflake message_id, snowflake channel_id) { - return dpp::awaitable(this, [&] (auto cc) { this->message_delete(message_id, channel_id, cc); }); -} - -/** - * @brief Edit a message on a channel. The callback function is called when the message has been edited - * - * @see dpp::cluster::message_edit - * @see https://discord.com/developers/docs/resources/channel#edit-message - * @param m Message to edit - * @return message returned object on completion - * \memberof dpp::cluster - */ -auto inline co_message_edit(const message &m) { - return dpp::awaitable(this, [&] (auto cc) { this->message_edit(m, cc); }); -} - -/** - * @brief Get a message - * - * @see dpp::cluster::message_get - * @see https://discord.com/developers/docs/resources/channel#get-channel-message - * @param message_id Message ID - * @param channel_id Channel ID - * @return message returned object on completion - * \memberof dpp::cluster - */ -auto inline co_message_get(snowflake message_id, snowflake channel_id) { - return dpp::awaitable(this, [&] (auto cc) { this->message_get(message_id, channel_id, cc); }); -} - -/** - * @brief Pin a message - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::message_pin - * @see https://discord.com/developers/docs/resources/channel#pin-message - * @param channel_id Channel id to pin message on - * @param message_id Message id to pin message on - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_message_pin(snowflake channel_id, snowflake message_id) { - return dpp::awaitable(this, [&] (auto cc) { this->message_pin(channel_id, message_id, cc); }); -} - -/** - * @brief Get multiple messages. - * - * This function will attempt to fetch as many messages as possible using multiple API calls if needed. - * - * @see dpp::cluster::messages_get - * @see https://discord.com/developers/docs/resources/channel#get-channel-messages - * @param channel_id Channel ID to retrieve messages for - * @param around Messages should be retrieved around this ID if this is set to non-zero - * @param before Messages before this ID should be retrieved if this is set to non-zero - * @param after Messages after this ID should be retrieved if this is set to non-zero - * @param limit This number of messages maximum should be returned, up to a maximum of 100. - * @return message_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_messages_get(snowflake channel_id, snowflake around, snowflake before, snowflake after, uint64_t limit) { - return dpp::awaitable(this, [&] (auto cc) { this->messages_get(channel_id, around, before, after, limit, cc); }); -} - -/** - * @brief Unpin a message - * @see dpp::cluster::message_unpin - * @see https://discord.com/developers/docs/resources/channel#unpin-message - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param channel_id Channel id to unpin message on - * @param message_id Message id to unpin message on - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_message_unpin(snowflake channel_id, snowflake message_id) { - return dpp::awaitable(this, [&] (auto cc) { this->message_unpin(channel_id, message_id, cc); }); -} - -/** - * @brief Get a channel's pins - * @see dpp::cluster::channel_pins_get - * @see https://discord.com/developers/docs/resources/channel#get-pinned-messages - * @param channel_id Channel ID to get pins for - * @return message_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_channel_pins_get(snowflake channel_id) { - return dpp::awaitable(this, [&] (auto cc) { this->channel_pins_get(channel_id, cc); }); -} - -/** - * @brief Create a role on a guild - * - * Create a new role for the guild. Requires the `MANAGE_ROLES` permission. Returns the new role object on success. - * Fires a `Guild Role Create` Gateway event. - * - * @see dpp::cluster::role_create - * @see https://discord.com/developers/docs/resources/guild#create-guild-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param r Role to create (guild ID is encapsulated in the role object) - * @return role returned object on completion - * \memberof dpp::cluster - */ -auto inline co_role_create(const class role &r) { - return dpp::awaitable(this, [&] (auto cc) { this->role_create(r, cc); }); -} - -/** - * @brief Delete a role - * - * Requires the `MANAGE_ROLES` permission. Fires a `Guild Role Delete` Gateway event. - * - * @see dpp::cluster::role_delete - * @see https://discord.com/developers/docs/resources/guild#delete-guild-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to delete the role on - * @param role_id Role ID to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_role_delete(snowflake guild_id, snowflake role_id) { - return dpp::awaitable(this, [&] (auto cc) { this->role_delete(guild_id, role_id, cc); }); -} - -/** - * @brief Edit a role on a guild - * - * Requires the `MANAGE_ROLES` permission. Returns the updated role on success. Fires a `Guild Role Update` Gateway event. - * - * @see dpp::cluster::role_edit - * @see https://discord.com/developers/docs/resources/guild#modify-guild-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param r Role to edit - * @return role returned object on completion - * \memberof dpp::cluster - */ -auto inline co_role_edit(const class role &r) { - return dpp::awaitable(this, [&] (auto cc) { this->role_edit(r, cc); }); -} - -/** - * @brief Edit multiple role's position in a guild. Returns a list of all roles of the guild on success. - * - * Modify the positions of a set of role objects for the guild. Requires the `MANAGE_ROLES` permission. - * Fires multiple `Guild Role Update` Gateway events. - * - * @see dpp::cluster::roles_edit_position - * @see https://discord.com/developers/docs/resources/guild#modify-guild-role-positions - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to change the roles position on - * @param roles Vector of roles to change the positions of - * @return role_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_roles_edit_position(snowflake guild_id, const std::vector &roles) { - return dpp::awaitable(this, [&] (auto cc) { this->roles_edit_position(guild_id, roles, cc); }); -} - -/** - * @brief Get a role for a guild - * - * @see dpp::cluster::roles_get - * @see https://discord.com/developers/docs/resources/guild#get-guild-roles - * @param guild_id Guild ID to get role for - * @return role_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_roles_get(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->roles_get(guild_id, cc); }); -} - -/** - * @brief Get all scheduled events for a guild - * @see dpp::cluster::guild_events_get - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#list-scheduled-events-for-guild - * @param guild_id Guild to get events for - * @return scheduled_event_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_events_get(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_events_get(guild_id, cc); }); -} - -/** - * @brief Create a scheduled event on a guild - * - * @see dpp::cluster::guild_event_create - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#create-guild-scheduled-event - * @param event Event to create (guild ID must be populated) - * @return scheduled_event returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_event_create(const scheduled_event& event) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_event_create(event, cc); }); -} - -/** - * @brief Delete a scheduled event from a guild - * - * @see dpp::cluster::guild_event_delete - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#delete-guild-scheduled-event - * @param event_id Event ID to delete - * @param guild_id Guild ID of event to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_event_delete(snowflake event_id, snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_event_delete(event_id, guild_id, cc); }); -} - -/** - * @brief Edit/modify a scheduled event on a guild - * - * @see dpp::cluster::guild_event_edit - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#modify-guild-scheduled-event - * @param event Event to create (event ID and guild ID must be populated) - * @return scheduled_event returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_event_edit(const scheduled_event& event) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_event_edit(event, cc); }); -} - -/** - * @brief Get a scheduled event for a guild - * - * @see dpp::cluster::guild_event_get - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#get-guild-scheduled-event - * @param guild_id Guild to get event for - * @param event_id Event ID to get - * @return scheduled_event returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_event_get(snowflake guild_id, snowflake event_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_event_get(guild_id, event_id, cc); }); -} - - -auto inline co_stage_instance_create(const stage_instance& si) { - return dpp::awaitable(this, [&] (auto cc) { this->stage_instance_create(si, cc); }); -} - -/** - * @brief Get the stage instance associated with the channel id, if it exists. - * @see dpp::cluster::stage_instance_get - * @see https://discord.com/developers/docs/resources/stage-instance#get-stage-instance - * @param channel_id ID of the associated channel - * @return stage_instance returned object on completion - * \memberof dpp::cluster - */ -auto inline co_stage_instance_get(const snowflake channel_id) { - return dpp::awaitable(this, [&] (auto cc) { this->stage_instance_get(channel_id, cc); }); -} - - -auto inline co_stage_instance_edit(const stage_instance& si) { - return dpp::awaitable(this, [&] (auto cc) { this->stage_instance_edit(si, cc); }); -} - -/** - * @brief Delete a stage instance. - * @see dpp::cluster::stage_instance_delete - * @see https://discord.com/developers/docs/resources/stage-instance#delete-stage-instance - * @param channel_id ID of the associated channel - * @return confirmation returned object on completion - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * \memberof dpp::cluster - */ -auto inline co_stage_instance_delete(const snowflake channel_id) { - return dpp::awaitable(this, [&] (auto cc) { this->stage_instance_delete(channel_id, cc); }); -} - -/** - * @brief Create a sticker in a guild - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::guild_sticker_create - * @see https://discord.com/developers/docs/resources/sticker#create-guild-sticker - * @param s Sticker to create. Must have its guild ID set. - * @return sticker returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_sticker_create(sticker &s) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_sticker_create(s, cc); }); -} - -/** - * @brief Delete a sticker from a guild - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::guild_sticker_delete - * @see https://discord.com/developers/docs/resources/sticker#delete-guild-sticker - * @param sticker_id sticker ID to delete - * @param guild_id guild ID to delete from - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_sticker_delete(snowflake sticker_id, snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_sticker_delete(sticker_id, guild_id, cc); }); -} - -/** - * @brief Get a guild sticker - * @see dpp::cluster::guild_sticker_get - * @see https://discord.com/developers/docs/resources/sticker#get-guild-sticker - * @param id Id of sticker to get. - * @param guild_id Guild ID of the guild where the sticker is - * @return sticker returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_sticker_get(snowflake id, snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_sticker_get(id, guild_id, cc); }); -} - -/** - * @brief Modify a sticker in a guild - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::guild_sticker_modify - * @see https://discord.com/developers/docs/resources/sticker#modify-guild-sticker - * @param s Sticker to modify. Must have its guild ID and sticker ID set. - * @return sticker returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_sticker_modify(sticker &s) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_sticker_modify(s, cc); }); -} - -/** - * @brief Get all guild stickers - * @see dpp::cluster::guild_stickers_get - * @see https://discord.com/developers/docs/resources/sticker#get-guild-stickers - * @param guild_id Guild ID of the guild where the sticker is - * @return sticker_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_stickers_get(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_stickers_get(guild_id, cc); }); -} - -/** - * @brief Get a nitro sticker - * @see dpp::cluster::nitro_sticker_get - * @see https://discord.com/developers/docs/resources/sticker#get-sticker - * @param id Id of sticker to get. - * @return sticker returned object on completion - * \memberof dpp::cluster - */ -auto inline co_nitro_sticker_get(snowflake id) { - return dpp::awaitable(this, [&] (auto cc) { this->nitro_sticker_get(id, cc); }); -} - -/** - * @brief Get sticker packs - * @see dpp::cluster::sticker_packs_get - * @see https://discord.com/developers/docs/resources/sticker#list-nitro-sticker-packs - * @return sticker_pack_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_sticker_packs_get() { - return dpp::awaitable(this, [&] (auto cc) { this->sticker_packs_get(cc); }); -} - -/** - * @brief Create a new guild based on a template. - * @note This endpoint can be used only by bots in less than 10 guilds. - * @see dpp::cluster::guild_create_from_template - * @see https://discord.com/developers/docs/resources/guild-template#create-guild-from-guild-template - * @param code Template code to create guild from - * @param name Guild name to create - * @return guild returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_create_from_template(const std::string &code, const std::string &name) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_create_from_template(code, name, cc); }); -} - -/** - * @brief Creates a template for the guild - * - * @see dpp::cluster::guild_template_create - * @see https://discord.com/developers/docs/resources/guild-template#create-guild-template - * @param guild_id Guild to create template from - * @param name Template name to create - * @param description Description of template to create - * @return dtemplate returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_template_create(snowflake guild_id, const std::string &name, const std::string &description) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_template_create(guild_id, name, description, cc); }); -} - -/** - * @brief Deletes the template - * - * @see dpp::cluster::guild_template_delete - * @see https://discord.com/developers/docs/resources/guild-template#delete-guild-template - * @param guild_id Guild ID of template to delete - * @param code Template code to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_template_delete(snowflake guild_id, const std::string &code) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_template_delete(guild_id, code, cc); }); -} - -/** - * @brief Modifies the template's metadata. - * - * @see dpp::cluster::guild_template_modify - * @see https://discord.com/developers/docs/resources/guild-template#modify-guild-template - * @param guild_id Guild ID of template to modify - * @param code Template code to modify - * @param name New name of template - * @param description New description of template - * @return dtemplate returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_template_modify(snowflake guild_id, const std::string &code, const std::string &name, const std::string &description) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_template_modify(guild_id, code, name, description, cc); }); -} - -/** - * @brief Get guild templates - * - * @see dpp::cluster::guild_templates_get - * @see https://discord.com/developers/docs/resources/guild-template#get-guild-templates - * @param guild_id Guild ID to get templates for - * @return dtemplate_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_templates_get(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_templates_get(guild_id, cc); }); -} - -/** - * @brief Syncs the template to the guild's current state. - * - * @see dpp::cluster::guild_template_sync - * @see https://discord.com/developers/docs/resources/guild-template#sync-guild-template - * @param guild_id Guild to synchronise template for - * @param code Code of template to synchronise - * @return dtemplate returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_template_sync(snowflake guild_id, const std::string &code) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_template_sync(guild_id, code, cc); }); -} - -/** - * @brief Get a template - * @see dpp::cluster::template_get - * @see https://discord.com/developers/docs/resources/guild-template#get-guild-template - * @param code Template code - * @return dtemplate returned object on completion - * \memberof dpp::cluster - */ -auto inline co_template_get(const std::string &code) { - return dpp::awaitable(this, [&] (auto cc) { this->template_get(code, cc); }); -} - -/** - * @brief Join a thread - * @see dpp::cluster::current_user_join_thread - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread ID to join - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_current_user_join_thread(snowflake thread_id) { - return dpp::awaitable(this, [&] (auto cc) { this->current_user_join_thread(thread_id, cc); }); -} - -/** - * @brief Leave a thread - * @see dpp::cluster::current_user_leave_thread - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread ID to leave - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_current_user_leave_thread(snowflake thread_id) { - return dpp::awaitable(this, [&] (auto cc) { this->current_user_leave_thread(thread_id, cc); }); -} - -/** - * @brief Get active threads in a channel (Sorted by ID in descending order) - * @see dpp::cluster::threads_get_active - * @see https://discord.com/developers/docs/topics/threads - * @param channel_id Channel to get active threads for - * @return thread_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_threads_get_active(snowflake channel_id) { - return dpp::awaitable(this, [&] (auto cc) { this->threads_get_active(channel_id, cc); }); -} - -/** - * @brief Get private archived threads in a channel which current user has joined (Sorted by ID in descending order) - * @see dpp::cluster::threads_get_joined_private_archived - * @see https://discord.com/developers/docs/topics/threads - * @param channel_id Channel to get public archived threads for - * @param before_id Get threads before this id - * @param limit Number of threads to get - * @return thread_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_threads_get_joined_private_archived(snowflake channel_id, snowflake before_id, uint16_t limit) { - return dpp::awaitable(this, [&] (auto cc) { this->threads_get_joined_private_archived(channel_id, before_id, limit, cc); }); -} - -/** - * @brief Get private archived threads in a channel (Sorted by archive_timestamp in descending order) - * @see dpp::cluster::threads_get_private_archived - * @see https://discord.com/developers/docs/topics/threads - * @param channel_id Channel to get public archived threads for - * @param before_timestamp Get threads before this timestamp - * @param limit Number of threads to get - * @return thread_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_threads_get_private_archived(snowflake channel_id, time_t before_timestamp, uint16_t limit) { - return dpp::awaitable(this, [&] (auto cc) { this->threads_get_private_archived(channel_id, before_timestamp, limit, cc); }); -} - -/** - * @brief Get public archived threads in a channel (Sorted by archive_timestamp in descending order) - * @see dpp::cluster::threads_get_public_archived - * @see https://discord.com/developers/docs/topics/threads - * @param channel_id Channel to get public archived threads for - * @param before_timestamp Get threads before this timestamp - * @param limit Number of threads to get - * @return thread_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_threads_get_public_archived(snowflake channel_id, time_t before_timestamp, uint16_t limit) { - return dpp::awaitable(this, [&] (auto cc) { this->threads_get_public_archived(channel_id, before_timestamp, limit, cc); }); -} - -/** - * @brief Get a thread member - * @see dpp::cluster::thread_member_get - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread to get member for - * @param user_id ID of the user to get - * @return thread_member returned object on completion - * \memberof dpp::cluster - */ -auto inline co_thread_member_get(const snowflake thread_id, const snowflake user_id) { - return dpp::awaitable(this, [&] (auto cc) { this->thread_member_get(thread_id, user_id, cc); }); -} - -/** - * @brief Get members of a thread - * @see dpp::cluster::thread_members_get - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread to get members for - * @return thread_member_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_thread_members_get(snowflake thread_id) { - return dpp::awaitable(this, [&] (auto cc) { this->thread_members_get(thread_id, cc); }); -} - -/** - * @brief Create a thread - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see dpp::cluster::thread_create - * @see https://discord.com/developers/docs/resources/guild#create-guild-channel - * @param thread_name Name of the thread - * @param channel_id Channel in which thread to create - * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) - * @param thread_type Type of thread - CHANNEL_PUBLIC_THREAD, CHANNEL_ANNOUNCEMENT_THREAD, CHANNEL_PRIVATE_THREAD - * @param invitable whether non-moderators can add other non-moderators to a thread; only available when creating a private thread - * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected - * @return thread returned object on completion - * \memberof dpp::cluster - */ -auto inline co_thread_create(const std::string& thread_name, snowflake channel_id, uint16_t auto_archive_duration, channel_type thread_type, bool invitable, uint16_t rate_limit_per_user) { - return dpp::awaitable(this, [&] (auto cc) { this->thread_create(thread_name, channel_id, auto_archive_duration, thread_type, invitable, rate_limit_per_user, cc); }); -} - -/** - * @brief Create a thread with a message (Discord: ID of a thread is same as message ID) - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::thread_create_with_message - * @see https://discord.com/developers/docs/topics/threads - * @param thread_name Name of the thread - * @param channel_id Channel in which thread to create - * @param message_id message to start thread with - * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) - * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected - * @return thread returned object on completion - * \memberof dpp::cluster - */ -auto inline co_thread_create_with_message(const std::string& thread_name, snowflake channel_id, snowflake message_id, uint16_t auto_archive_duration, uint16_t rate_limit_per_user) { - return dpp::awaitable(this, [&] (auto cc) { this->thread_create_with_message(thread_name, channel_id, message_id, auto_archive_duration, rate_limit_per_user, cc); }); -} - -/** - * @brief Add a member to a thread - * @see dpp::cluster::thread_member_add - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread ID to add to - * @param user_id Member ID to add - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_thread_member_add(snowflake thread_id, snowflake user_id) { - return dpp::awaitable(this, [&] (auto cc) { this->thread_member_add(thread_id, user_id, cc); }); -} - -/** - * @brief Remove a member from a thread - * @see dpp::cluster::thread_member_remove - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread ID to remove from - * @param user_id Member ID to remove - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_thread_member_remove(snowflake thread_id, snowflake user_id) { - return dpp::awaitable(this, [&] (auto cc) { this->thread_member_remove(thread_id, user_id, cc); }); -} - -/** - * @brief Edit current (bot) user - * - * Modifies the current member in a guild. Returns the updated guild_member object on success. - * Fires a `Guild Member Update` Gateway event. - * @see dpp::cluster::current_user_edit - * @see https://discord.com/developers/docs/resources/user#modify-current-user - * @param nickname Nickname to set - * @param image_blob Avatar data to upload (NOTE: Very heavily rate limited!) - * @param type Type of image for avatar - * @return user returned object on completion - * @throw dpp::exception Image data is larger than the maximum size of 256 kilobytes - * \memberof dpp::cluster - */ -auto inline co_current_user_edit(const std::string &nickname, const std::string& image_blob, const image_type type) { - return dpp::awaitable(this, [&] (auto cc) { this->current_user_edit(nickname, image_blob, type, cc); }); -} - -/** - * @brief Get current (bot) application - * - * @see dpp::cluster::current_application_get - * @see https://discord.com/developers/docs/topics/oauth2#get-current-bot-application-information - * @return application returned object on completion - * \memberof dpp::cluster - */ -auto inline co_current_application_get() { - return dpp::awaitable(this, [&] (auto cc) { this->current_application_get(cc); }); -} - -/** - * @brief Get current (bot) user - * - * @see dpp::cluster::current_user_get - * @see https://discord.com/developers/docs/resources/user#get-current-user - * @return user_identified returned object on completion - * @note The user_identified object is a subclass of dpp::user which contains further details if you have the oauth2 identify or email scopes. - * If you do not have these scopes, these fields are empty. You can safely convert a user_identified to user with `dynamic_cast`. - * \memberof dpp::cluster - */ -auto inline co_current_user_get() { - return dpp::awaitable(this, [&] (auto cc) { this->current_user_get(cc); }); -} - -/** - * @brief Set the bot's voice state on a stage channel - * - * **Caveats** - * - * There are currently several caveats for this endpoint: - * - * - `channel_id` must currently point to a stage channel. - * - current user must already have joined `channel_id`. - * - You must have the `MUTE_MEMBERS` permission to unsuppress yourself. You can always suppress yourself. - * - You must have the `REQUEST_TO_SPEAK` permission to request to speak. You can always clear your own request to speak. - * - You are able to set `request_to_speak_timestamp` to any present or future time. - * - * @see dpp::cluster::current_user_set_voice_state - * @see https://discord.com/developers/docs/resources/guild#modify-current-user-voice-state - * @param guild_id Guild to set voice state on - * @param channel_id Stage channel to set voice state on - * @return confirmation returned object on completion - * @param suppress True if the user's audio should be suppressed, false if it should not - * @param request_to_speak_timestamp The time at which we requested to speak, or 0 to clear the request. The time set here must be the current time or in the future. - * @throw std::logic_exception You attempted to set a request_to_speak_timestamp in the past which is not the value of 0. - * \memberof dpp::cluster - */ -auto inline co_current_user_set_voice_state(snowflake guild_id, snowflake channel_id, bool suppress, time_t request_to_speak_timestamp) { - return dpp::awaitable(this, [&] (auto cc) { this->current_user_set_voice_state(guild_id, channel_id, suppress, request_to_speak_timestamp, cc); }); -} - -/** - * @brief Set a user's voice state on a stage channel - * - * **Caveats** - * - * There are currently several caveats for this endpoint: - * - * - `channel_id` must currently point to a stage channel. - * - User must already have joined `channel_id`. - * - You must have the `MUTE_MEMBERS` permission. (Since suppression is the only thing that is available currently) - * - When unsuppressed, non-bot users will have their `request_to_speak_timestamp` set to the current time. Bot users will not. - * - When suppressed, the user will have their `request_to_speak_timestamp` removed. - * - * @see dpp::cluster::user_set_voice_state - * @see https://discord.com/developers/docs/resources/guild#modify-user-voice-state - * @param user_id The user to set the voice state of - * @param guild_id Guild to set voice state on - * @param channel_id Stage channel to set voice state on - * @return confirmation returned object on completion - * @param suppress True if the user's audio should be suppressed, false if it should not - * \memberof dpp::cluster - */ -auto inline co_user_set_voice_state(snowflake user_id, snowflake guild_id, snowflake channel_id, bool suppress) { - return dpp::awaitable(this, [&] (auto cc) { this->user_set_voice_state(user_id, guild_id, channel_id, suppress, cc); }); -} - -/** - * @brief Get current user's connections (linked accounts, e.g. steam, xbox). - * This call requires the oauth2 `connections` scope and cannot be executed - * against a bot token. - * @see dpp::cluster::current_user_connections_get - * @see https://discord.com/developers/docs/resources/user#get-user-connections - * @return connection_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_current_user_connections_get() { - return dpp::awaitable(this, [&] (auto cc) { this->current_user_connections_get(cc); }); -} - -/** - * @brief Get current (bot) user guilds - * @see dpp::cluster::current_user_get_guilds - * @see https://discord.com/developers/docs/resources/user#get-current-user-guilds - * @return guild_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_current_user_get_guilds() { - return dpp::awaitable(this, [&] (auto cc) { this->current_user_get_guilds(cc); }); -} - -/** - * @brief Leave a guild - * @see dpp::cluster::current_user_leave_guild - * @see https://discord.com/developers/docs/resources/user#leave-guild - * @param guild_id Guild ID to leave - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_current_user_leave_guild(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->current_user_leave_guild(guild_id, cc); }); -} - -/** - * @brief Get a user by id - * - * @see dpp::cluster::user_get - * @see https://discord.com/developers/docs/resources/user#get-user - * @param user_id User ID to retrieve - * @return user_identified returned object on completion - * @note The user_identified object is a subclass of dpp::user which contains further details if you have the oauth2 identify or email scopes. - * If you do not have these scopes, these fields are empty. You can safely convert a user_identified to user with `dynamic_cast`. - * @note unless you want something special from `dpp::user_identified` or you've turned off caching, you have no need to call this. - * Call `dpp::find_user` instead that looks up the user in the cache rather than a REST call. - * \memberof dpp::cluster - */ -auto inline co_user_get(snowflake user_id) { - return dpp::awaitable(this, [&] (auto cc) { this->user_get(user_id, cc); }); -} - -/** - * @brief Get all voice regions - * @see dpp::cluster::get_voice_regions - * @see https://discord.com/developers/docs/resources/voice#list-voice-regions - * @return voiceregion_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_get_voice_regions() { - return dpp::awaitable(this, [&] (auto cc) { this->get_voice_regions(cc); }); -} - -/** - * @brief Get guild voice regions. - * - * Voice regions per guild are somewhat deprecated in preference of per-channel voice regions. - * Returns a list of voice region objects for the guild. Unlike the similar /voice route, this returns VIP servers when - * the guild is VIP-enabled. - * - * @see dpp::cluster::guild_get_voice_regions - * @see https://discord.com/developers/docs/resources/guild#get-guild-voice-regions - * @param guild_id Guild ID to get voice regions for - * @return voiceregion_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_get_voice_regions(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_get_voice_regions(guild_id, cc); }); -} - -/** - * @brief Create a webhook - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::create_webhook - * @see https://discord.com/developers/docs/resources/webhook#create-webhook - * @param w Webhook to create - * @return webhook returned object on completion - * \memberof dpp::cluster - */ -auto inline co_create_webhook(const class webhook &w) { - return dpp::awaitable(this, [&] (auto cc) { this->create_webhook(w, cc); }); -} - -/** - * @brief Delete a webhook - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::delete_webhook - * @see https://discord.com/developers/docs/resources/webhook#delete-webhook - * @param webhook_id Webhook ID to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_delete_webhook(snowflake webhook_id) { - return dpp::awaitable(this, [&] (auto cc) { this->delete_webhook(webhook_id, cc); }); -} - -/** - * @brief Delete webhook message - * - * @see dpp::cluster::delete_webhook_message - * @see https://discord.com/developers/docs/resources/webhook#delete-webhook-message - * @param wh Webhook to delete message for - * @param message_id Message ID to delete - * @param thread_id ID of the thread the message is in - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_delete_webhook_message(const class webhook &wh, snowflake message_id, snowflake thread_id) { - return dpp::awaitable(this, [&] (auto cc) { this->delete_webhook_message(wh, message_id, thread_id, cc); }); -} - -/** - * @brief Delete webhook with token - * @see dpp::cluster::delete_webhook_with_token - * @see https://discord.com/developers/docs/resources/webhook#delete-webhook-with-token - * @param webhook_id Webhook ID to delete - * @param token Token of webhook to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_delete_webhook_with_token(snowflake webhook_id, const std::string &token) { - return dpp::awaitable(this, [&] (auto cc) { this->delete_webhook_with_token(webhook_id, token, cc); }); -} - -/** - * @brief Edit webhook - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::edit_webhook - * @see https://discord.com/developers/docs/resources/webhook#modify-webhook - * @param wh Webhook to edit - * @return webhook returned object on completion - * \memberof dpp::cluster - */ -auto inline co_edit_webhook(const class webhook& wh) { - return dpp::awaitable(this, [&] (auto cc) { this->edit_webhook(wh, cc); }); -} - -/** - * @brief Edit webhook message - * - * When the content field is edited, the mentions array in the message object will be reconstructed from scratch based on - * the new content. The allowed_mentions field of the edit request controls how this happens. If there is no explicit - * allowed_mentions in the edit request, the content will be parsed with default allowances, that is, without regard to - * whether or not an allowed_mentions was present in the request that originally created the message. - * - * @see dpp::cluster::edit_webhook_message - * @see https://discord.com/developers/docs/resources/webhook#edit-webhook-message - * @note the attachments array must contain all attachments that should be present after edit, including retained and new attachments provided in the request body. - * @param wh Webhook to edit message for - * @param m New message - * @param thread_id ID of the thread the message is in - * @return message returned object on completion - * \memberof dpp::cluster - */ -auto inline co_edit_webhook_message(const class webhook &wh, const struct message& m, snowflake thread_id) { - return dpp::awaitable(this, [&] (auto cc) { this->edit_webhook_message(wh, m, thread_id, cc); }); -} - -/** - * @brief Edit webhook with token (token is encapsulated in the webhook object) - * @see dpp::cluster::edit_webhook_with_token - * @see https://discord.com/developers/docs/resources/webhook#modify-webhook-with-token - * @param wh Webhook to edit (should include token) - * @return webhook returned object on completion - * \memberof dpp::cluster - */ -auto inline co_edit_webhook_with_token(const class webhook& wh) { - return dpp::awaitable(this, [&] (auto cc) { this->edit_webhook_with_token(wh, cc); }); -} - -/** - * @brief Execute webhook - * - * @see dpp::cluster::execute_webhook - * @see https://discord.com/developers/docs/resources/webhook#execute-webhook - * @param wh Webhook to execute - * @param m Message to send - * @param wait waits for server confirmation of message send before response, and returns the created message body - * @param thread_id Send a message to the specified thread within a webhook's channel. The thread will automatically be unarchived - * @param thread_name Name of thread to create (requires the webhook channel to be a forum channel) - * @return message returned object on completion - * @note If the webhook channel is a forum channel, you must provide either `thread_id` or `thread_name`. If `thread_id` is provided, the message will send in that thread. If `thread_name` is provided, a thread with that name will be created in the forum channel. - * \memberof dpp::cluster - */ -auto inline co_execute_webhook(const class webhook &wh, const struct message& m, bool wait, snowflake thread_id, const std::string& thread_name) { - return dpp::awaitable(this, [&] (auto cc) { this->execute_webhook(wh, m, wait, thread_id, thread_name, cc); }); -} - -/** - * @brief Get channel webhooks - * @see dpp::cluster::get_channel_webhooks - * @see https://discord.com/developers/docs/resources/webhook#get-guild-webhooks - * @param channel_id Channel ID to get webhooks for - * @return webhook_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_get_channel_webhooks(snowflake channel_id) { - return dpp::awaitable(this, [&] (auto cc) { this->get_channel_webhooks(channel_id, cc); }); -} - -/** - * @brief Get guild webhooks - * @see dpp::cluster::get_guild_webhooks - * @see https://discord.com/developers/docs/resources/webhook#get-guild-webhooks - * @param guild_id Guild ID to get webhooks for - * @return webhook_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_get_guild_webhooks(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->get_guild_webhooks(guild_id, cc); }); -} - -/** - * @brief Get webhook - * @see dpp::cluster::get_webhook - * @see https://discord.com/developers/docs/resources/webhook#get-webhook - * @param webhook_id Webhook ID to get - * @return webhook returned object on completion - * \memberof dpp::cluster - */ -auto inline co_get_webhook(snowflake webhook_id) { - return dpp::awaitable(this, [&] (auto cc) { this->get_webhook(webhook_id, cc); }); -} - -/** - * @brief Get webhook message - * - * @see dpp::cluster::get_webhook_message - * @see https://discord.com/developers/docs/resources/webhook#get-webhook-message - * @param wh Webhook to get the original message for - * @param message_id The message ID - * @param thread_id ID of the thread the message is in - * @return message returned object on completion - * \memberof dpp::cluster - */ -auto inline co_get_webhook_message(const class webhook &wh, snowflake message_id, snowflake thread_id) { - return dpp::awaitable(this, [&] (auto cc) { this->get_webhook_message(wh, message_id, thread_id, cc); }); -} - -/** - * @brief Get webhook using token - * @see dpp::cluster::get_webhook_with_token - * @see https://discord.com/developers/docs/resources/webhook#get-webhook-with-token - * @param webhook_id Webhook ID to retrieve - * @param token Token of webhook - * @return webhook returned object on completion - * \memberof dpp::cluster - */ -auto inline co_get_webhook_with_token(snowflake webhook_id, const std::string &token) { - return dpp::awaitable(this, [&] (auto cc) { this->get_webhook_with_token(webhook_id, token, cc); }); -} - - -/* End of auto-generated definitions */ -auto inline co_request(const std::string &url, http_method method, const std::string &postdata = "", const std::string &mimetype = "text/plain", const std::multimap &headers = {}) { - return dpp::awaitable(this, [&] (auto cc) { this->request(url, method, cc, mimetype, headers); }); -} - +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2022 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + + +/* Auto @generated by buildtools/make_coro_struct.php. + * + * DO NOT EDIT BY HAND! + * + * To re-generate this header file re-run the script! + */ +/** + * @brief Create/overwrite global slash commands. + * Any existing global slash commands will be deleted and replaced with these. + * + * @see dpp::cluster::global_bulk_command_create + * @see https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-global-application-commands + * @param commands Vector of slash commands to create/update. + * overwriting existing commands that are registered globally for this application. Updates will be available in all guilds after 1 hour. + * Commands that do not already exist will count toward daily application command create limits. + * @return slashcommand_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_global_bulk_command_create(const std::vector &commands) { + return dpp::awaitable(this, [&] (auto cc) { this->global_bulk_command_create(commands, cc); }); +} + +/** + * @brief Create a global slash command (a bot can have a maximum of 100 of these). + * + * @see dpp::cluster::global_command_create + * @see https://discord.com/developers/docs/interactions/application-commands#create-global-application-command + * @param s Slash command to create + * @return slashcommand returned object on completion + * \memberof dpp::cluster + */ +auto inline co_global_command_create(const slashcommand &s) { + return dpp::awaitable(this, [&] (auto cc) { this->global_command_create(s, cc); }); +} + +/** + * @brief Get a global slash command + * + * @see dpp::cluster::global_command_get + * @see https://discord.com/developers/docs/interactions/application-commands#get-global-application-command + * @param id The ID of the slash command + * @return slashcommand returned object on completion + * \memberof dpp::cluster + */ +auto inline co_global_command_get(snowflake id) { + return dpp::awaitable(this, [&] (auto cc) { this->global_command_get(id, cc); }); +} + +/** + * @brief Delete a global slash command (a bot can have a maximum of 100 of these) + * + * @see dpp::cluster::global_command_delete + * @see https://discord.com/developers/docs/interactions/application-commands#delete-global-application-command + * @param id Slash command to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_global_command_delete(snowflake id) { + return dpp::awaitable(this, [&] (auto cc) { this->global_command_delete(id, cc); }); +} + +/** + * @brief Edit a global slash command (a bot can have a maximum of 100 of these) + * + * @see dpp::cluster::global_command_edit + * @see https://discord.com/developers/docs/interactions/application-commands#edit-global-application-command + * @param s Slash command to change + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_global_command_edit(const slashcommand &s) { + return dpp::awaitable(this, [&] (auto cc) { this->global_command_edit(s, cc); }); +} + +/** + * @brief Get the application's global slash commands + * + * @see dpp::cluster::global_commands_get + * @see https://discord.com/developers/docs/interactions/application-commands#get-global-application-commands + * @return slashcommand_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_global_commands_get() { + return dpp::awaitable(this, [&] (auto cc) { this->global_commands_get(cc); }); +} + +/** + * @brief Create/overwrite guild slash commands. + * Any existing guild slash commands on this guild will be deleted and replaced with these. + * + * @see dpp::cluster::guild_bulk_command_create + * @see https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-guild-application-commands + * @param commands Vector of slash commands to create/update. + * New guild commands will be available in the guild immediately. If the command did not already exist, it will count toward daily application command create limits. + * @param guild_id Guild ID to create/update the slash commands in + * @return slashcommand_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_bulk_command_create(const std::vector &commands, snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_bulk_command_create(commands, guild_id, cc); }); +} + +/** + * @brief Get all slash command permissions of a guild + * + * @see dpp::cluster::guild_commands_get_permissions + * @see https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions + * @param guild_id Guild ID to get the slash commands permissions for + * @return guild_command_permissions_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_commands_get_permissions(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_commands_get_permissions(guild_id, cc); }); +} + +/** + * @brief Edit/Overwrite the permissions of all existing slash commands in a guild + * + * @note You can only add up to 10 permission overwrites for a command + * + * @see dpp::cluster::guild_bulk_command_edit_permissions + * @see https://discord.com/developers/docs/interactions/application-commands#batch-edit-application-command-permissions + * @warning The endpoint will overwrite all existing permissions for all commands of the application in a guild, including slash commands, user commands, and message commands. Meaning that if you forgot to pass a slash command, the permissions of it might be removed. + * @param commands A vector of slash commands to edit/overwrite the permissions for + * @param guild_id Guild ID to edit permissions of the slash commands in + * @return guild_command_permissions_map returned object on completion + * @deprecated This has been disabled with updates to Permissions v2. You can use guild_command_edit_permissions instead + * \memberof dpp::cluster + */ +auto inline co_guild_bulk_command_edit_permissions(const std::vector &commands, snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_bulk_command_edit_permissions(commands, guild_id, cc); }); +} + +/** + * @brief Create a slash command local to a guild + * + * @see dpp::cluster::guild_command_create + * @see https://discord.com/developers/docs/interactions/application-commands#create-guild-application-command + * @note Creating a command with the same name as an existing command for your application will overwrite the old command. + * @param s Slash command to create + * @param guild_id Guild ID to create the slash command in + * @return slashcommand returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_command_create(const slashcommand &s, snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_command_create(s, guild_id, cc); }); +} + +/** + * @brief Delete a slash command local to a guild + * + * @see dpp::cluster::guild_command_delete + * @see https://discord.com/developers/docs/interactions/application-commands#delete-guild-application-command + * @param id Slash command to delete + * @param guild_id Guild ID to delete the slash command in + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_command_delete(snowflake id, snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_command_delete(id, guild_id, cc); }); +} + +/** + * @brief Edit slash command permissions of a guild + * + * @see dpp::cluster::guild_command_edit_permissions + * @see https://discord.com/developers/docs/interactions/application-commands#edit-application-command-permissions + * @note You can only add up to 10 permission overwrites for a command + * @param s Slash command to edit the permissions for + * @param guild_id Guild ID to edit the slash command in + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_command_edit_permissions(const slashcommand &s, snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_command_edit_permissions(s, guild_id, cc); }); +} + +/** + * @brief Get a slash command of a guild + * + * @see dpp::cluster::guild_command_get + * @see https://discord.com/developers/docs/interactions/application-commands#get-guild-application-command + * @note The returned slash commands will not have permissions set, you need to use a permissions getter e.g. dpp::guild_commands_get_permissions to get the guild command permissions + * @param id The ID of the slash command + * @param guild_id Guild ID to get the slash command from + * @return slashcommand returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_command_get(snowflake id, snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_command_get(id, guild_id, cc); }); +} + +/** + * @brief Get the permissions for a slash command of a guild + * + * @see dpp::cluster::guild_command_get_permissions + * @see https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions + * @param id The ID of the slash command to get the permissions for + * @param guild_id Guild ID to get the permissions of + * @return guild_command_permissions returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_command_get_permissions(snowflake id, snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_command_get_permissions(id, guild_id, cc); }); +} + +/** + * @brief Edit a slash command local to a guild + * + * @see dpp::cluster::guild_command_edit + * @see https://discord.com/developers/docs/interactions/application-commands#edit-guild-application-command + * @param s Slash command to edit + * @param guild_id Guild ID to edit the slash command in + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_command_edit(const slashcommand &s, snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_command_edit(s, guild_id, cc); }); +} + +/** + * @brief Get the application's slash commands for a guild + * + * @see dpp::cluster::guild_commands_get + * @see https://discord.com/developers/docs/interactions/application-commands#get-guild-application-commands + * @note The returned slash commands will not have permissions set, you need to use a permissions getter e.g. dpp::guild_commands_get_permissions to get the guild command permissions + * @param guild_id Guild ID to get the slash commands for + * @return slashcommand_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_commands_get(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_commands_get(guild_id, cc); }); +} + +/** + * @brief Respond to a slash command + * + * @see dpp::cluster::interaction_response_create + * @see https://discord.com/developers/docs/interactions/receiving-and-responding#create-interaction-response + * @param interaction_id Interaction id to respond to + * @param token Token for the interaction webhook + * @param r Response to send + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_interaction_response_create(snowflake interaction_id, const std::string &token, const interaction_response &r) { + return dpp::awaitable(this, [&] (auto cc) { this->interaction_response_create(interaction_id, token, r, cc); }); +} + +/** + * @brief Edit response to a slash command + * + * @see dpp::cluster::interaction_response_edit + * @see https://discord.com/developers/docs/interactions/receiving-and-responding#edit-original-interaction-response + * @param token Token for the interaction webhook + * @param m Message to send + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_interaction_response_edit(const std::string &token, const message &m) { + return dpp::awaitable(this, [&] (auto cc) { this->interaction_response_edit(token, m, cc); }); +} + +/** + * @brief Create a followup message to a slash command + * + * @param token Token for the interaction webhook + * @param m followup message to create + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_interaction_followup_create(const std::string &token, const message &m) { + return dpp::awaitable(this, [&] (auto cc) { this->interaction_followup_create(token, m, cc); }); +} + +/** + * @brief Edit original followup message to a slash command + * This is an alias for cluster::interaction_response_edit + * @see dpp::cluster::interaction_followup_edit_original + * @see cluster::interaction_response_edit + * + * @param token Token for the interaction webhook + * @param m message to edit, the ID should be set + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_interaction_followup_edit_original(const std::string &token, const message &m) { + return dpp::awaitable(this, [&] (auto cc) { this->interaction_followup_edit_original(token, m, cc); }); +} + +/** + * @brief + * + * @param token Token for the interaction webhook + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_interaction_followup_delete(const std::string &token) { + return dpp::awaitable(this, [&] (auto cc) { this->interaction_followup_delete(token, cc); }); +} + +/** + * @brief Edit followup message to a slash command + * The message ID in the message you pass should be correctly set to that of a followup message you previously sent + * @param token Token for the interaction webhook + * @param m message to edit, the ID should be set + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_interaction_followup_edit(const std::string &token, const message &m) { + return dpp::awaitable(this, [&] (auto cc) { this->interaction_followup_edit(token, m, cc); }); +} + +/** + * @brief Get the followup message to a slash command + * @param token Token for the interaction webhook + * @param message_id message to retrieve + * @return message returned object on completion + * \memberof dpp::cluster + */ +auto inline co_interaction_followup_get(const std::string &token, snowflake message_id) { + return dpp::awaitable(this, [&] (auto cc) { this->interaction_followup_get(token, message_id, cc); }); +} + +/** + * @brief Get all auto moderation rules for a guild + * + * @param guild_id Guild id of the auto moderation rule + * @return automod_rule_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_automod_rules_get(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->automod_rules_get(guild_id, cc); }); +} + +/** + * @brief Get a single auto moderation rule + * + * @param guild_id Guild id of the auto moderation rule + * @param rule_id Rule id to retrieve + * @return automod_rule returned object on completion + * \memberof dpp::cluster + */ +auto inline co_automod_rule_get(snowflake guild_id, snowflake rule_id) { + return dpp::awaitable(this, [&] (auto cc) { this->automod_rule_get(guild_id, rule_id, cc); }); +} + +/** + * @brief Create an auto moderation rule + * + * @param guild_id Guild id of the auto moderation rule + * @param r Auto moderation rule to create + * @return automod_rule returned object on completion + * \memberof dpp::cluster + */ +auto inline co_automod_rule_create(snowflake guild_id, const automod_rule& r) { + return dpp::awaitable(this, [&] (auto cc) { this->automod_rule_create(guild_id, r, cc); }); +} + +/** + * @brief Edit an auto moderation rule + * + * @param guild_id Guild id of the auto moderation rule + * @param r Auto moderation rule to edit. The rule's id must be set. + * @return automod_rule returned object on completion + * \memberof dpp::cluster + */ +auto inline co_automod_rule_edit(snowflake guild_id, const automod_rule& r) { + return dpp::awaitable(this, [&] (auto cc) { this->automod_rule_edit(guild_id, r, cc); }); +} + +/** + * @brief Delete an auto moderation rule + * + * @param guild_id Guild id of the auto moderation rule + * @param rule_id Auto moderation rule id to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_automod_rule_delete(snowflake guild_id, snowflake rule_id) { + return dpp::awaitable(this, [&] (auto cc) { this->automod_rule_delete(guild_id, rule_id, cc); }); +} + +/** + * @brief Create a channel + * + * Create a new channel object for the guild. Requires the `MANAGE_CHANNELS` permission. If setting permission overwrites, + * only permissions your bot has in the guild can be allowed/denied. Setting `MANAGE_ROLES` permission in channels is only possible + * for guild administrators. Returns the new channel object on success. Fires a `Channel Create Gateway` event. + * + * All parameters to this endpoint are optional excluding `name` + * + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::channel_create + * @see https://discord.com/developers/docs/resources/channel#create-channel + * @param c Channel to create + * @return channel returned object on completion + * \memberof dpp::cluster + */ +auto inline co_channel_create(const class channel &c) { + return dpp::awaitable(this, [&] (auto cc) { this->channel_create(c, cc); }); +} + +/** + * @brief Remove a permission from a channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::channel_delete_permission + * @see https://discord.com/developers/docs/resources/channel#delete-channel-permission + * @param c Channel to remove permission from + * @param overwrite_id Overwrite to remove, user or channel ID + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_channel_delete_permission(const class channel &c, snowflake overwrite_id) { + return dpp::awaitable(this, [&] (auto cc) { this->channel_delete_permission(c, overwrite_id, cc); }); +} + +/** + * @brief Delete a channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::channel_delete + * @see https://discord.com/developers/docs/resources/channel#deleteclose-channel + * @param channel_id Channel id to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_channel_delete(snowflake channel_id) { + return dpp::awaitable(this, [&] (auto cc) { this->channel_delete(channel_id, cc); }); +} + +/** + * @brief Edit multiple channels positions + * + * Modify the positions of a set of channel objects for the guild. + * Requires `MANAGE_CHANNELS` permission. Fires multiple `Channel Update Gateway` events. + * Only channels to be modified are required. + * + * @see dpp::cluster::channel_edit_positions + * @see https://discord.com/developers/docs/resources/guild#modify-guild-channel-positions + * @param c Channel to change the position for + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_channel_edit_positions(const std::vector &c) { + return dpp::awaitable(this, [&] (auto cc) { this->channel_edit_positions(c, cc); }); +} + +/** + * @brief Edit a channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::channel_edit + * @see https://discord.com/developers/docs/resources/channel#modify-channel + * @param c Channel to edit/update + * @return channel returned object on completion + * \memberof dpp::cluster + */ +auto inline co_channel_edit(const class channel &c) { + return dpp::awaitable(this, [&] (auto cc) { this->channel_edit(c, cc); }); +} + +/** + * @brief Follow an announcement (news) channel + * @see dpp::cluster::channel_follow_news + * @see https://discord.com/developers/docs/resources/channel#follow-news-channel + * @param c Channel id to follow + * @param target_channel_id Channel to subscribe the channel to + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_channel_follow_news(const class channel &c, snowflake target_channel_id) { + return dpp::awaitable(this, [&] (auto cc) { this->channel_follow_news(c, target_channel_id, cc); }); +} + +/** + * @brief Get a channel + * + * @see dpp::cluster::channel_get + * @see https://discord.com/developers/docs/resources/channel#get-channel + * @param c Channel ID to retrieve + * @return channel returned object on completion + * \memberof dpp::cluster + */ +auto inline co_channel_get(snowflake c) { + return dpp::awaitable(this, [&] (auto cc) { this->channel_get(c, cc); }); +} + +/** + * @brief Create invite for a channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::channel_invite_create + * @see https://discord.com/developers/docs/resources/channel#create-channel-invite + * @param c Channel to create an invite on + * @param i Invite to create + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_channel_invite_create(const class channel &c, const class invite &i) { + return dpp::awaitable(this, [&] (auto cc) { this->channel_invite_create(c, i, cc); }); +} + +/** + * @brief Get invites for a channel + * + * @see dpp::cluster::channel_invites_get + * @see https://discord.com/developers/docs/resources/invite#get-invites + * @param c Channel to get invites for + * @return invite_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_channel_invites_get(const class channel &c) { + return dpp::awaitable(this, [&] (auto cc) { this->channel_invites_get(c, cc); }); +} + +/** + * @brief Get all channels for a guild + * + * @see dpp::cluster::channels_get + * @see https://discord.com/developers/docs/resources/channel#get-channels + * @param guild_id Guild ID to retrieve channels for + * @return channel_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_channels_get(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->channels_get(guild_id, cc); }); +} + +/** + * @brief Create a dm channel + * @see dpp::cluster::create_dm_channel + * @see https://discord.com/developers/docs/resources/user#create-dm + * @param user_id User ID to create DM channel with + * @return channel returned object on completion + * \memberof dpp::cluster + */ +auto inline co_create_dm_channel(snowflake user_id) { + return dpp::awaitable(this, [&] (auto cc) { this->create_dm_channel(user_id, cc); }); +} + +/** + * @brief Get current user DM channels + * + * @return channel_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_current_user_get_dms() { + return dpp::awaitable(this, [&] (auto cc) { this->current_user_get_dms(cc); }); +} + +/** + * @brief Create a direct message, also create the channel for the direct message if needed + * + * @see dpp::cluster::direct_message_create + * @see https://discord.com/developers/docs/resources/user#create-dm + * @see dpp::cluster::direct_message_create + * @see https://discord.com/developers/docs/resources/channel#create-message + * @param user_id User ID of user to send message to + * @param m Message object + * @return message returned object on completion + * \memberof dpp::cluster + */ +auto inline co_direct_message_create(snowflake user_id, const message &m) { + return dpp::awaitable(this, [&] (auto cc) { this->direct_message_create(user_id, m, cc); }); +} + +/** + * @brief Adds a recipient to a Group DM using their access token + * @see dpp::cluster::gdm_add + * @see https://discord.com/developers/docs/resources/channel#group-dm-add-recipient + * @param channel_id Channel id to add group DM recipients to + * @param user_id User ID to add + * @param access_token Access token from OAuth2 + * @param nick Nickname of user to apply to the chat + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_gdm_add(snowflake channel_id, snowflake user_id, const std::string &access_token, const std::string &nick) { + return dpp::awaitable(this, [&] (auto cc) { this->gdm_add(channel_id, user_id, access_token, nick, cc); }); +} + +/** + * @brief Removes a recipient from a Group DM + * @see dpp::cluster::gdm_remove + * @see https://discord.com/developers/docs/resources/channel#group-dm-remove-recipient + * @param channel_id Channel ID of group DM + * @param user_id User ID to remove from group DM + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_gdm_remove(snowflake channel_id, snowflake user_id) { + return dpp::awaitable(this, [&] (auto cc) { this->gdm_remove(channel_id, user_id, cc); }); +} + +/** + * @brief Create single emoji. + * You must ensure that the emoji passed contained image data using the emoji::load_image() method. + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see dpp::cluster::guild_emoji_create + * @see https://discord.com/developers/docs/resources/emoji#create-guild-emoji + * @param guild_id Guild ID to create emoji om + * @param newemoji Emoji to create + * @return emoji returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_emoji_create(snowflake guild_id, const class emoji& newemoji) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_emoji_create(guild_id, newemoji, cc); }); +} + +/** + * @brief Delete a guild emoji + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see dpp::cluster::guild_emoji_delete + * @see https://discord.com/developers/docs/resources/emoji#delete-guild-emoji + * @param guild_id Guild ID to delete emoji on + * @param emoji_id Emoji ID to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_emoji_delete(snowflake guild_id, snowflake emoji_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_emoji_delete(guild_id, emoji_id, cc); }); +} + +/** + * @brief Edit a single emoji. + * + * You must ensure that the emoji passed contained image data using the emoji::load_image() method. + * @see dpp::cluster::guild_emoji_edit + * @see https://discord.com/developers/docs/resources/emoji#get-guild-emoji + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to edit emoji on + * @param newemoji Emoji to edit + * @return emoji returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_emoji_edit(snowflake guild_id, const class emoji& newemoji) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_emoji_edit(guild_id, newemoji, cc); }); +} + +/** + * @brief Get a single emoji + * + * @see dpp::cluster::guild_emoji_get + * @see https://discord.com/developers/docs/resources/emoji#get-guild-emoji + * @param guild_id Guild ID to get emoji for + * @param emoji_id Emoji ID to get + * @return emoji returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_emoji_get(snowflake guild_id, snowflake emoji_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_emoji_get(guild_id, emoji_id, cc); }); +} + +/** + * @brief Get all emojis for a guild + * + * @see dpp::cluster::guild_emojis_get + * @see https://discord.com/developers/docs/resources/emoji#get-guild-emojis + * @param guild_id Guild ID to get emojis for + * @return emoji_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_emojis_get(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_emojis_get(guild_id, cc); }); +} + +/** + * @brief Get the gateway information for the bot using the token + * @see dpp::cluster::get_gateway_bot + * @see https://discord.com/developers/docs/topics/gateway#get-gateway-bot + * @return gateway returned object on completion + * \memberof dpp::cluster + */ +auto inline co_get_gateway_bot() { + return dpp::awaitable(this, [&] (auto cc) { this->get_gateway_bot(cc); }); +} + +/** + * @brief Modify current member + * + * Modifies the current member in a guild. + * Fires a `Guild Member Update` Gateway event. + * + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::guild_current_member_edit + * @see https://discord.com/developers/docs/resources/guild#modify-current-member + * @param guild_id Guild ID to change on + * @param nickname New nickname, or empty string to clear nickname + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_current_member_edit(snowflake guild_id, const std::string &nickname) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_current_member_edit(guild_id, nickname, cc); }); +} + +/** + * @brief Get the audit log for a guild + * + * @see dpp::cluster::guild_auditlog_get + * @see https://discord.com/developers/docs/resources/audit-log#get-guild-audit-log + * @param guild_id Guild to get the audit log of + * @param user_id Entries from a specific user ID. Set this to `0` will fetch any user + * @param action_type Entries for a specific dpp::audit_type. Set this to `0` will fetch any type + * @param before Entries that preceded a specific audit log entry ID. Used for paginating + * @param limit Maximum number of entries (between 1-100) to return + * @return auditlog returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_auditlog_get(snowflake guild_id, snowflake user_id, uint32_t action_type, snowflake before, uint32_t limit) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_auditlog_get(guild_id, user_id, action_type, before, limit, cc); }); +} + +/** + * @brief Add guild ban + * + * Create a guild ban, and optionally delete previous messages sent by the banned user. + * Requires the `BAN_MEMBERS` permission. Fires a `Guild Ban Add` Gateway event. + * @see dpp::cluster::guild_ban_add + * @see https://discord.com/developers/docs/resources/guild#create-guild-ban + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to add ban to + * @param user_id User ID to ban + * @param delete_message_seconds How many seconds to delete messages for, between 0 and 604800 (7 days). Defaults to 0 + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_ban_add(snowflake guild_id, snowflake user_id, uint32_t delete_message_seconds) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_ban_add(guild_id, user_id, delete_message_seconds, cc); }); +} + +/** + * @brief Delete guild ban + * + * Remove the ban for a user. Requires the `BAN_MEMBERS` permissions. + * Fires a Guild Ban Remove Gateway event. + * @see dpp::cluster::guild_ban_delete + * @see https://discord.com/developers/docs/resources/guild#remove-guild-ban + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild to delete ban from + * @param user_id User ID to delete ban for + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_ban_delete(snowflake guild_id, snowflake user_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_ban_delete(guild_id, user_id, cc); }); +} + +/** + * @brief Create a guild + * + * Create a new guild. Returns a guild object on success. `Fires a Guild Create Gateway` event. + * + * When using the roles parameter, the first member of the array is used to change properties of the guild's everyone role. + * If you are trying to bootstrap a guild with additional roles, keep this in mind. The required id field within each role object is an + * integer placeholder, and will be replaced by the API upon consumption. Its purpose is to allow you to overwrite a role's permissions + * in a channel when also passing in channels with the channels array. + * When using the channels parameter, the position field is ignored, and none of the default channels are created. The id field within + * each channel object may be set to an integer placeholder, and will be replaced by the API upon consumption. Its purpose is to + * allow you to create `GUILD_CATEGORY` channels by setting the `parent_id` field on any children to the category's id field. + * Category channels must be listed before any children. + * + * @see dpp::cluster::guild_create + * @see https://discord.com/developers/docs/resources/guild#create-guild + * @note The region field is deprecated and is replaced by channel.rtc_region. This endpoint can be used only by bots in less than 10 guilds. + * @param g Guild to create + * @return guild returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_create(const class guild &g) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_create(g, cc); }); +} + +/** + * @brief Delete a guild + * + * Delete a guild permanently. User must be owner. Fires a `Guild Delete Gateway` event. + * + * @see dpp::cluster::guild_delete + * @see https://discord.com/developers/docs/resources/guild#delete-guild + * @param guild_id Guild ID to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_delete(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_delete(guild_id, cc); }); +} + +/** + * @brief Delete guild integration + * + * Delete the attached integration object for the guild. Deletes any associated webhooks and kicks the associated bot if there is one. + * Requires the `MANAGE_GUILD` permission. Fires a Guild Integrations Update Gateway event. + * + * @see dpp::cluster::guild_delete_integration + * @see https://discord.com/developers/docs/resources/guild#delete-guild-integration + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to delete integration for + * @param integration_id Integration ID to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_delete_integration(snowflake guild_id, snowflake integration_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_delete_integration(guild_id, integration_id, cc); }); +} + +/** + * @brief Edit a guild + * + * Modify a guild's settings. Requires the `MANAGE_GUILD` permission. Returns the updated guild object on success. + * Fires a `Guild Update Gateway` event. + * + * @see dpp::cluster::guild_edit + * @see https://discord.com/developers/docs/resources/guild#modify-guild + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param g Guild to edit + * @return guild returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_edit(const class guild &g) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_edit(g, cc); }); +} + +/** + * @brief Edit guild widget + * + * Requires the `MANAGE_GUILD` permission. + * + * @see dpp::cluster::guild_edit_widget + * @see https://discord.com/developers/docs/resources/guild#modify-guild-widget + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to edit widget for + * @param gw New guild widget information + * @return guild_widget returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_edit_widget(snowflake guild_id, const class guild_widget &gw) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_edit_widget(guild_id, gw, cc); }); +} + +/** + * @brief Get single guild ban + * + * Requires the `BAN_MEMBERS` permission. + * @see dpp::cluster::guild_get_ban + * @see https://discord.com/developers/docs/resources/guild#get-guild-ban + * @param guild_id Guild ID to get ban for + * @param user_id User ID of ban to retrieve + * @return ban returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_get_ban(snowflake guild_id, snowflake user_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_get_ban(guild_id, user_id, cc); }); +} + +/** + * @brief Get guild ban list + * + * Requires the `BAN_MEMBERS` permission. + * @see dpp::cluster::guild_get_bans + * @see https://discord.com/developers/docs/resources/guild#get-guild-bans + * @note Provide a user ID to `before` and `after` for pagination. Users will always be returned in ascending order by the user ID. If both before and after are provided, only before is respected. + * @param guild_id Guild ID to get bans for + * @param before If non-zero, all bans for user ids before this user id will be returned up to the limit + * @param after if non-zero, all bans for user ids after this user id will be returned up to the limit + * @param limit the maximum number of bans to retrieve in this call up to a maximum of 1000 + * @return ban_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_get_bans(snowflake guild_id, snowflake before, snowflake after, snowflake limit) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_get_bans(guild_id, before, after, limit, cc); }); +} + + +auto inline co_guild_get(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_get(guild_id, cc); }); +} + +/** + * @brief Get guild integrations + * + * Requires the `MANAGE_GUILD` permission. + * + * @see dpp::cluster::guild_get_integrations + * @see https://discord.com/developers/docs/resources/guild#get-guild-integrations + * @param guild_id Guild ID to get integrations for + * @return integration_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_get_integrations(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_get_integrations(guild_id, cc); }); +} + + +auto inline co_guild_get_preview(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_get_preview(guild_id, cc); }); +} + +/** + * @brief Get guild vanity url, if enabled + * + * Returns a partial dpp::invite object for guilds with that feature enabled. Requires the `MANAGE_GUILD` permission. code will be null if a vanity url for the guild is not set. + * @see dpp::cluster::guild_get_vanity + * @see https://discord.com/developers/docs/resources/guild#get-guild-vanity-url + * @param guild_id Guild to get vanity URL for + * @return invite returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_get_vanity(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_get_vanity(guild_id, cc); }); +} + +/** + * @brief Get guild widget + * + * Requires the `MANAGE_GUILD` permission. + * + * @see dpp::cluster::guild_get_widget + * @see https://discord.com/developers/docs/resources/guild#get-guild-widget + * @param guild_id Guild ID to get widget for + * @return guild_widget returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_get_widget(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_get_widget(guild_id, cc); }); +} + +/** + * @brief Modify guild integration + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see dpp::cluster::guild_modify_integration + * @see https://discord.com/developers/docs/resources/guild#modify-guild-integration + * @param guild_id Guild ID to modify integration for + * @param i Integration to modify + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_modify_integration(snowflake guild_id, const class integration &i) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_modify_integration(guild_id, i, cc); }); +} + +/** + * @brief Get prune counts + * + * Returns a prune object indicating the number of members that would be removed in a prune operation. Requires the `KICK_MEMBERS` + * permission. By default, prune will not remove users with roles. You can optionally include specific roles in your prune by providing the + * include_roles parameter. Any inactive user that has a subset of the provided role(s) will be counted in the prune and users with additional + * roles will not. + * + * @see dpp::cluster::guild_get_prune_counts + * @see https://discord.com/developers/docs/resources/guild#get-guild-prune-count + * @param guild_id Guild ID to count for pruning + * @param pruneinfo Pruning info + * @return prune returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_get_prune_counts(snowflake guild_id, const struct prune& pruneinfo) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_get_prune_counts(guild_id, pruneinfo, cc); }); +} + +/** + * @brief Begin guild prune + * + * Begin a prune operation. Requires the `KICK_MEMBERS` permission. Returns a prune object indicating the number of members + * that were removed in the prune operation. For large guilds it's recommended to set the `compute_prune_count` option to false, forcing + * 'pruned' to 0. Fires multiple `Guild Member Remove` Gateway events. + * By default, prune will not remove users with roles. You can optionally include specific roles in your prune by providing the `include_roles` + * parameter. Any inactive user that has a subset of the provided role(s) will be included in the prune and users with additional roles will not. + * + * @see dpp::cluster::guild_begin_prune + * @see https://discord.com/developers/docs/resources/guild#begin-guild-prune + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to prune + * @param pruneinfo Pruning info + * @return prune returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_begin_prune(snowflake guild_id, const struct prune& pruneinfo) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_begin_prune(guild_id, pruneinfo, cc); }); +} + +/** + * @brief Change current user nickname + * + * Modifies the nickname of the current user in a guild. + * Fires a `Guild Member Update` Gateway event. + * + * @deprecated Deprecated in favor of Modify Current Member. Will be replaced by dpp::cluster::guild_current_member_edit + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::guild_set_nickname + * @see https://discord.com/developers/docs/resources/guild#modify-current-user-nick + * @param guild_id Guild ID to change nickname on + * @param nickname New nickname, or empty string to clear nickname + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_set_nickname(snowflake guild_id, const std::string &nickname) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_set_nickname(guild_id, nickname, cc); }); +} + +/** + * @brief Sync guild integration + * + * @see dpp::cluster::guild_sync_integration + * @see https://discord.com/developers/docs/resources/guild#sync-guild-integration + * @param guild_id Guild ID to sync integration on + * @param integration_id Integration ID to synchronise + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_sync_integration(snowflake guild_id, snowflake integration_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_sync_integration(guild_id, integration_id, cc); }); +} + +/** + * @brief Add guild member. Needs a specific oauth2 scope, from which you get the access_token. + * + * Adds a user to the guild, provided you have a valid oauth2 access token for the user with the guilds.join scope. + * Returns the guild_member, which is defaulted if the user is already a member of the guild. Fires a `Guild Member Add` Gateway event. + * + * For guilds with Membership Screening enabled, this endpoint will default to adding new members as pending in the guild member object. + * Members that are pending will have to complete membership screening before they become full members that can talk. + * + * @note All parameters to this endpoint except for access_token are optional. + * The bot must be a member of the guild with `CREATE_INSTANT_INVITE` permission. + * @see dpp::cluster::guild_add_member + * @see https://discord.com/developers/docs/resources/guild#add-guild-member + * @param gm Guild member to add + * @param access_token Access token from Oauth2 scope + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_add_member(const guild_member& gm, const std::string &access_token) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_add_member(gm, access_token, cc); }); +} + +/** + * @brief Edit the properties of an existing guild member + * + * Modify attributes of a guild member. Returns the guild_member. Fires a `Guild Member Update` Gateway event. + * To remove a timeout, set the `communication_disabled_until` to a non-zero time in the past, e.g. 1. + * When moving members to channels, the API user must have permissions to both connect to the channel and have the `MOVE_MEMBERS` permission. + * For moving and disconnecting users from voice, use dpp::cluster::guild_member_move. + * @see dpp::cluster::guild_edit_member + * @see https://discord.com/developers/docs/resources/guild#modify-guild-member + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param gm Guild member to edit + * @return guild_member returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_edit_member(const guild_member& gm) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_edit_member(gm, cc); }); +} + +/** + * @brief Get a guild member + * @see dpp::cluster::guild_get_member + * @see https://discord.com/developers/docs/resources/guild#get-guild-member + * @param guild_id Guild ID to get member for + * @param user_id User ID of member to get + * @return guild_member returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_get_member(snowflake guild_id, snowflake user_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_get_member(guild_id, user_id, cc); }); +} + +/** + * @brief Get all guild members + * + * @note This endpoint is restricted according to whether the `GUILD_MEMBERS` Privileged Intent is enabled for your application. + * @see dpp::cluster::guild_get_members + * @see https://discord.com/developers/docs/resources/guild#get-guild-members + * @param guild_id Guild ID to get all members for + * @param limit max number of members to return (1-1000) + * @param after the highest user id in the previous page + * @return guild_member_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_get_members(snowflake guild_id, uint16_t limit, snowflake after) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_get_members(guild_id, limit, after, cc); }); +} + +/** + * @brief Add role to guild member + * + * Adds a role to a guild member. Requires the `MANAGE_ROLES` permission. + * Fires a `Guild Member Update` Gateway event. + * @see dpp::cluster::guild_member_add_role + * @see https://discord.com/developers/docs/resources/guild#add-guild-member-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to add a role to + * @param user_id User ID to add role to + * @param role_id Role ID to add to the user + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_member_add_role(snowflake guild_id, snowflake user_id, snowflake role_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_member_add_role(guild_id, user_id, role_id, cc); }); +} + +/** + * @brief Remove (kick) a guild member + * + * Remove a member from a guild. Requires `KICK_MEMBERS` permission. + * Fires a `Guild Member Remove` Gateway event. + * @see dpp::cluster::guild_member_delete + * @see https://discord.com/developers/docs/resources/guild#remove-guild-member + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @deprecated Replaced by dpp::cluster::guild_member_kick + * @param guild_id Guild ID to kick member from + * @param user_id User ID to kick + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_member_delete(snowflake guild_id, snowflake user_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_member_delete(guild_id, user_id, cc); }); +} + +/** + * @brief Remove (kick) a guild member + * + * Remove a member from a guild. Requires `KICK_MEMBERS` permission. + * Fires a `Guild Member Remove` Gateway event. + * @see dpp::cluster::guild_member_kick + * @see https://discord.com/developers/docs/resources/guild#remove-guild-member + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to kick member from + * @param user_id User ID to kick + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_member_kick(snowflake guild_id, snowflake user_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_member_kick(guild_id, user_id, cc); }); +} + +/** + * @brief Set the timeout of a guild member + * + * Fires a `Guild Member Update` Gateway event. + * @see dpp::cluster::guild_member_timeout + * @see https://discord.com/developers/docs/resources/guild#modify-guild-member + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to timeout the member in + * @param user_id User ID to set the timeout for + * @param communication_disabled_until The timestamp when the user's timeout will expire (up to 28 days in the future). Set to 0 to remove the timeout + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_member_timeout(snowflake guild_id, snowflake user_id, time_t communication_disabled_until) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_member_timeout(guild_id, user_id, communication_disabled_until, cc); }); +} + +/** + * @brief Remove role from guild member + * + * Removes a role from a guild member. Requires the `MANAGE_ROLES` permission. + * Fires a `Guild Member Update` Gateway event. + * @see dpp::cluster::guild_member_delete_role + * @see https://discord.com/developers/docs/resources/guild#remove-guild-member-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to remove role from user on + * @param user_id User ID to remove role from + * @param role_id Role to remove + * @return confirmation returned object on completion + * @deprecated Use dpp::cluster::guild_member_remove_role instead + * \memberof dpp::cluster + */ +auto inline co_guild_member_delete_role(snowflake guild_id, snowflake user_id, snowflake role_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_member_delete_role(guild_id, user_id, role_id, cc); }); +} + +/** + * @brief Remove role from guild member + * + * Removes a role from a guild member. Requires the `MANAGE_ROLES` permission. + * Fires a `Guild Member Update` Gateway event. + * @see dpp::cluster::guild_member_remove_role + * @see https://discord.com/developers/docs/resources/guild#remove-guild-member-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to remove role from user on + * @param user_id User ID to remove role from + * @param role_id Role to remove + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_member_remove_role(snowflake guild_id, snowflake user_id, snowflake role_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_member_remove_role(guild_id, user_id, role_id, cc); }); +} + +/** + * @brief Moves the guild member to a other voice channel, if member is connected to one. + * Set the `channel_id` to `0` to disconnect the user. + * + * Fires a `Guild Member Update` Gateway event. + * @note When moving members to channels, the API user __must__ have permissions to both connect to the channel and have the `MOVE_MEMBERS` permission. + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::guild_member_move + * @see https://discord.com/developers/docs/resources/guild#modify-guild-member + * @param channel_id Id of the channel to which the user is used. Set to `0` to disconnect the user + * @param guild_id Guild id to which the user is connected + * @param user_id User id, who should be moved + * @return guild_member returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_member_move(const snowflake channel_id, const snowflake guild_id, const snowflake user_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_member_move(channel_id, guild_id, user_id, cc); }); +} + +/** + * @brief Search for guild members based on whether their username or nickname starts with the given string. + * + * @note This endpoint is restricted according to whether the `GUILD_MEMBERS` Privileged Intent is enabled for your application. + * @see dpp::cluster::guild_search_members + * @see https://discord.com/developers/docs/resources/guild#search-guild-members + * @param guild_id Guild ID to search in + * @param query Query string to match username(s) and nickname(s) against + * @param limit max number of members to return (1-1000) + * @return guild_member_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_search_members(snowflake guild_id, const std::string& query, uint16_t limit) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_search_members(guild_id, query, limit, cc); }); +} + +/** + * @brief Get guild invites + * + * Returns a list of invite objects (with invite metadata) for the guild. Requires the `MANAGE_GUILD` permission. + * + * @see dpp::cluster::guild_get_invites + * @see https://discord.com/developers/docs/resources/guild#get-guild-invites + * @param guild_id Guild ID to get invites for + * @return invite_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_get_invites(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_get_invites(guild_id, cc); }); +} + + +auto inline co_invite_delete(const std::string &invitecode) { + return dpp::awaitable(this, [&] (auto cc) { this->invite_delete(invitecode, cc); }); +} + + +auto inline co_invite_get(const std::string &invitecode) { + return dpp::awaitable(this, [&] (auto cc) { this->invite_get(invitecode, cc); }); +} + +/** + * @brief Send a message to a channel. The callback function is called when the message has been sent + * + * @see dpp::cluster::message_create + * @see https://discord.com/developers/docs/resources/channel#create-message + * @param m Message to send + * @return message returned object on completion + * \memberof dpp::cluster + */ +auto inline co_message_create(const message &m) { + return dpp::awaitable(this, [&] (auto cc) { this->message_create(m, cc); }); +} + +/** + * @brief Crosspost a message. The callback function is called when the message has been sent + * + * @see dpp::cluster::message_crosspost + * @see https://discord.com/developers/docs/resources/channel#crosspost-message + * @param message_id Message to crosspost + * @param channel_id Channel ID to crosspost from + * @return message returned object on completion + * \memberof dpp::cluster + */ +auto inline co_message_crosspost(snowflake message_id, snowflake channel_id) { + return dpp::awaitable(this, [&] (auto cc) { this->message_crosspost(message_id, channel_id, cc); }); +} + +/** + * @brief Bulk delete messages from a channel. The callback function is called when the message has been edited + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @note If any message provided older than 2 weeks or any duplicate message ID, it will fail. + * + * @see dpp::cluster::message_delete_bulk + * @see https://discord.com/developers/docs/resources/channel#bulk-delete-messages + * @param message_ids List of message IDs to delete (at least 2 and at most 100 message IDs) + * @param channel_id Channel to delete from + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_message_delete_bulk(const std::vector& message_ids, snowflake channel_id) { + return dpp::awaitable(this, [&] (auto cc) { this->message_delete_bulk(message_ids, channel_id, cc); }); +} + +/** + * @brief Delete a message from a channel. The callback function is called when the message has been edited + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see dpp::cluster::message_delete + * @see https://discord.com/developers/docs/resources/channel#delete-message + * @param message_id Message ID to delete + * @param channel_id Channel to delete from + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_message_delete(snowflake message_id, snowflake channel_id) { + return dpp::awaitable(this, [&] (auto cc) { this->message_delete(message_id, channel_id, cc); }); +} + +/** + * @brief Edit a message on a channel. The callback function is called when the message has been edited + * + * @see dpp::cluster::message_edit + * @see https://discord.com/developers/docs/resources/channel#edit-message + * @param m Message to edit + * @return message returned object on completion + * \memberof dpp::cluster + */ +auto inline co_message_edit(const message &m) { + return dpp::awaitable(this, [&] (auto cc) { this->message_edit(m, cc); }); +} + +/** + * @brief Get a message + * + * @see dpp::cluster::message_get + * @see https://discord.com/developers/docs/resources/channel#get-channel-message + * @param message_id Message ID + * @param channel_id Channel ID + * @return message returned object on completion + * \memberof dpp::cluster + */ +auto inline co_message_get(snowflake message_id, snowflake channel_id) { + return dpp::awaitable(this, [&] (auto cc) { this->message_get(message_id, channel_id, cc); }); +} + +/** + * @brief Pin a message + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::message_pin + * @see https://discord.com/developers/docs/resources/channel#pin-message + * @param channel_id Channel id to pin message on + * @param message_id Message id to pin message on + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_message_pin(snowflake channel_id, snowflake message_id) { + return dpp::awaitable(this, [&] (auto cc) { this->message_pin(channel_id, message_id, cc); }); +} + +/** + * @brief Get multiple messages. + * + * This function will attempt to fetch as many messages as possible using multiple API calls if needed. + * + * @see dpp::cluster::messages_get + * @see https://discord.com/developers/docs/resources/channel#get-channel-messages + * @param channel_id Channel ID to retrieve messages for + * @param around Messages should be retrieved around this ID if this is set to non-zero + * @param before Messages before this ID should be retrieved if this is set to non-zero + * @param after Messages after this ID should be retrieved if this is set to non-zero + * @param limit This number of messages maximum should be returned, up to a maximum of 100. + * @return message_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_messages_get(snowflake channel_id, snowflake around, snowflake before, snowflake after, uint64_t limit) { + return dpp::awaitable(this, [&] (auto cc) { this->messages_get(channel_id, around, before, after, limit, cc); }); +} + +/** + * @brief Unpin a message + * @see dpp::cluster::message_unpin + * @see https://discord.com/developers/docs/resources/channel#unpin-message + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param channel_id Channel id to unpin message on + * @param message_id Message id to unpin message on + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_message_unpin(snowflake channel_id, snowflake message_id) { + return dpp::awaitable(this, [&] (auto cc) { this->message_unpin(channel_id, message_id, cc); }); +} + +/** + * @brief Get a channel's pins + * @see dpp::cluster::channel_pins_get + * @see https://discord.com/developers/docs/resources/channel#get-pinned-messages + * @param channel_id Channel ID to get pins for + * @return message_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_channel_pins_get(snowflake channel_id) { + return dpp::awaitable(this, [&] (auto cc) { this->channel_pins_get(channel_id, cc); }); +} + +/** + * @brief Create a role on a guild + * + * Create a new role for the guild. Requires the `MANAGE_ROLES` permission. Returns the new role object on success. + * Fires a `Guild Role Create` Gateway event. + * + * @see dpp::cluster::role_create + * @see https://discord.com/developers/docs/resources/guild#create-guild-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param r Role to create (guild ID is encapsulated in the role object) + * @return role returned object on completion + * \memberof dpp::cluster + */ +auto inline co_role_create(const class role &r) { + return dpp::awaitable(this, [&] (auto cc) { this->role_create(r, cc); }); +} + +/** + * @brief Delete a role + * + * Requires the `MANAGE_ROLES` permission. Fires a `Guild Role Delete` Gateway event. + * + * @see dpp::cluster::role_delete + * @see https://discord.com/developers/docs/resources/guild#delete-guild-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to delete the role on + * @param role_id Role ID to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_role_delete(snowflake guild_id, snowflake role_id) { + return dpp::awaitable(this, [&] (auto cc) { this->role_delete(guild_id, role_id, cc); }); +} + +/** + * @brief Edit a role on a guild + * + * Requires the `MANAGE_ROLES` permission. Returns the updated role on success. Fires a `Guild Role Update` Gateway event. + * + * @see dpp::cluster::role_edit + * @see https://discord.com/developers/docs/resources/guild#modify-guild-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param r Role to edit + * @return role returned object on completion + * \memberof dpp::cluster + */ +auto inline co_role_edit(const class role &r) { + return dpp::awaitable(this, [&] (auto cc) { this->role_edit(r, cc); }); +} + +/** + * @brief Edit multiple role's position in a guild. Returns a list of all roles of the guild on success. + * + * Modify the positions of a set of role objects for the guild. Requires the `MANAGE_ROLES` permission. + * Fires multiple `Guild Role Update` Gateway events. + * + * @see dpp::cluster::roles_edit_position + * @see https://discord.com/developers/docs/resources/guild#modify-guild-role-positions + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to change the roles position on + * @param roles Vector of roles to change the positions of + * @return role_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_roles_edit_position(snowflake guild_id, const std::vector &roles) { + return dpp::awaitable(this, [&] (auto cc) { this->roles_edit_position(guild_id, roles, cc); }); +} + +/** + * @brief Get a role for a guild + * + * @see dpp::cluster::roles_get + * @see https://discord.com/developers/docs/resources/guild#get-guild-roles + * @param guild_id Guild ID to get role for + * @return role_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_roles_get(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->roles_get(guild_id, cc); }); +} + +/** + * @brief Get all scheduled events for a guild + * @see dpp::cluster::guild_events_get + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#list-scheduled-events-for-guild + * @param guild_id Guild to get events for + * @return scheduled_event_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_events_get(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_events_get(guild_id, cc); }); +} + +/** + * @brief Create a scheduled event on a guild + * + * @see dpp::cluster::guild_event_create + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#create-guild-scheduled-event + * @param event Event to create (guild ID must be populated) + * @return scheduled_event returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_event_create(const scheduled_event& event) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_event_create(event, cc); }); +} + +/** + * @brief Delete a scheduled event from a guild + * + * @see dpp::cluster::guild_event_delete + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#delete-guild-scheduled-event + * @param event_id Event ID to delete + * @param guild_id Guild ID of event to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_event_delete(snowflake event_id, snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_event_delete(event_id, guild_id, cc); }); +} + +/** + * @brief Edit/modify a scheduled event on a guild + * + * @see dpp::cluster::guild_event_edit + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#modify-guild-scheduled-event + * @param event Event to create (event ID and guild ID must be populated) + * @return scheduled_event returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_event_edit(const scheduled_event& event) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_event_edit(event, cc); }); +} + +/** + * @brief Get a scheduled event for a guild + * + * @see dpp::cluster::guild_event_get + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#get-guild-scheduled-event + * @param guild_id Guild to get event for + * @param event_id Event ID to get + * @return scheduled_event returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_event_get(snowflake guild_id, snowflake event_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_event_get(guild_id, event_id, cc); }); +} + + +auto inline co_stage_instance_create(const stage_instance& si) { + return dpp::awaitable(this, [&] (auto cc) { this->stage_instance_create(si, cc); }); +} + +/** + * @brief Get the stage instance associated with the channel id, if it exists. + * @see dpp::cluster::stage_instance_get + * @see https://discord.com/developers/docs/resources/stage-instance#get-stage-instance + * @param channel_id ID of the associated channel + * @return stage_instance returned object on completion + * \memberof dpp::cluster + */ +auto inline co_stage_instance_get(const snowflake channel_id) { + return dpp::awaitable(this, [&] (auto cc) { this->stage_instance_get(channel_id, cc); }); +} + + +auto inline co_stage_instance_edit(const stage_instance& si) { + return dpp::awaitable(this, [&] (auto cc) { this->stage_instance_edit(si, cc); }); +} + +/** + * @brief Delete a stage instance. + * @see dpp::cluster::stage_instance_delete + * @see https://discord.com/developers/docs/resources/stage-instance#delete-stage-instance + * @param channel_id ID of the associated channel + * @return confirmation returned object on completion + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * \memberof dpp::cluster + */ +auto inline co_stage_instance_delete(const snowflake channel_id) { + return dpp::awaitable(this, [&] (auto cc) { this->stage_instance_delete(channel_id, cc); }); +} + +/** + * @brief Create a sticker in a guild + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::guild_sticker_create + * @see https://discord.com/developers/docs/resources/sticker#create-guild-sticker + * @param s Sticker to create. Must have its guild ID set. + * @return sticker returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_sticker_create(sticker &s) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_sticker_create(s, cc); }); +} + +/** + * @brief Delete a sticker from a guild + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::guild_sticker_delete + * @see https://discord.com/developers/docs/resources/sticker#delete-guild-sticker + * @param sticker_id sticker ID to delete + * @param guild_id guild ID to delete from + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_sticker_delete(snowflake sticker_id, snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_sticker_delete(sticker_id, guild_id, cc); }); +} + +/** + * @brief Get a guild sticker + * @see dpp::cluster::guild_sticker_get + * @see https://discord.com/developers/docs/resources/sticker#get-guild-sticker + * @param id Id of sticker to get. + * @param guild_id Guild ID of the guild where the sticker is + * @return sticker returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_sticker_get(snowflake id, snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_sticker_get(id, guild_id, cc); }); +} + +/** + * @brief Modify a sticker in a guild + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::guild_sticker_modify + * @see https://discord.com/developers/docs/resources/sticker#modify-guild-sticker + * @param s Sticker to modify. Must have its guild ID and sticker ID set. + * @return sticker returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_sticker_modify(sticker &s) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_sticker_modify(s, cc); }); +} + +/** + * @brief Get all guild stickers + * @see dpp::cluster::guild_stickers_get + * @see https://discord.com/developers/docs/resources/sticker#get-guild-stickers + * @param guild_id Guild ID of the guild where the sticker is + * @return sticker_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_stickers_get(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_stickers_get(guild_id, cc); }); +} + +/** + * @brief Get a nitro sticker + * @see dpp::cluster::nitro_sticker_get + * @see https://discord.com/developers/docs/resources/sticker#get-sticker + * @param id Id of sticker to get. + * @return sticker returned object on completion + * \memberof dpp::cluster + */ +auto inline co_nitro_sticker_get(snowflake id) { + return dpp::awaitable(this, [&] (auto cc) { this->nitro_sticker_get(id, cc); }); +} + +/** + * @brief Get sticker packs + * @see dpp::cluster::sticker_packs_get + * @see https://discord.com/developers/docs/resources/sticker#list-nitro-sticker-packs + * @return sticker_pack_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_sticker_packs_get() { + return dpp::awaitable(this, [&] (auto cc) { this->sticker_packs_get(cc); }); +} + +/** + * @brief Create a new guild based on a template. + * @note This endpoint can be used only by bots in less than 10 guilds. + * @see dpp::cluster::guild_create_from_template + * @see https://discord.com/developers/docs/resources/guild-template#create-guild-from-guild-template + * @param code Template code to create guild from + * @param name Guild name to create + * @return guild returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_create_from_template(const std::string &code, const std::string &name) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_create_from_template(code, name, cc); }); +} + +/** + * @brief Creates a template for the guild + * + * @see dpp::cluster::guild_template_create + * @see https://discord.com/developers/docs/resources/guild-template#create-guild-template + * @param guild_id Guild to create template from + * @param name Template name to create + * @param description Description of template to create + * @return dtemplate returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_template_create(snowflake guild_id, const std::string &name, const std::string &description) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_template_create(guild_id, name, description, cc); }); +} + +/** + * @brief Deletes the template + * + * @see dpp::cluster::guild_template_delete + * @see https://discord.com/developers/docs/resources/guild-template#delete-guild-template + * @param guild_id Guild ID of template to delete + * @param code Template code to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_template_delete(snowflake guild_id, const std::string &code) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_template_delete(guild_id, code, cc); }); +} + +/** + * @brief Modifies the template's metadata. + * + * @see dpp::cluster::guild_template_modify + * @see https://discord.com/developers/docs/resources/guild-template#modify-guild-template + * @param guild_id Guild ID of template to modify + * @param code Template code to modify + * @param name New name of template + * @param description New description of template + * @return dtemplate returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_template_modify(snowflake guild_id, const std::string &code, const std::string &name, const std::string &description) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_template_modify(guild_id, code, name, description, cc); }); +} + +/** + * @brief Get guild templates + * + * @see dpp::cluster::guild_templates_get + * @see https://discord.com/developers/docs/resources/guild-template#get-guild-templates + * @param guild_id Guild ID to get templates for + * @return dtemplate_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_templates_get(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_templates_get(guild_id, cc); }); +} + +/** + * @brief Syncs the template to the guild's current state. + * + * @see dpp::cluster::guild_template_sync + * @see https://discord.com/developers/docs/resources/guild-template#sync-guild-template + * @param guild_id Guild to synchronise template for + * @param code Code of template to synchronise + * @return dtemplate returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_template_sync(snowflake guild_id, const std::string &code) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_template_sync(guild_id, code, cc); }); +} + +/** + * @brief Get a template + * @see dpp::cluster::template_get + * @see https://discord.com/developers/docs/resources/guild-template#get-guild-template + * @param code Template code + * @return dtemplate returned object on completion + * \memberof dpp::cluster + */ +auto inline co_template_get(const std::string &code) { + return dpp::awaitable(this, [&] (auto cc) { this->template_get(code, cc); }); +} + +/** + * @brief Join a thread + * @see dpp::cluster::current_user_join_thread + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread ID to join + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_current_user_join_thread(snowflake thread_id) { + return dpp::awaitable(this, [&] (auto cc) { this->current_user_join_thread(thread_id, cc); }); +} + +/** + * @brief Leave a thread + * @see dpp::cluster::current_user_leave_thread + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread ID to leave + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_current_user_leave_thread(snowflake thread_id) { + return dpp::awaitable(this, [&] (auto cc) { this->current_user_leave_thread(thread_id, cc); }); +} + +/** + * @brief Get active threads in a channel (Sorted by ID in descending order) + * @see dpp::cluster::threads_get_active + * @see https://discord.com/developers/docs/topics/threads + * @param channel_id Channel to get active threads for + * @return thread_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_threads_get_active(snowflake channel_id) { + return dpp::awaitable(this, [&] (auto cc) { this->threads_get_active(channel_id, cc); }); +} + +/** + * @brief Get private archived threads in a channel which current user has joined (Sorted by ID in descending order) + * @see dpp::cluster::threads_get_joined_private_archived + * @see https://discord.com/developers/docs/topics/threads + * @param channel_id Channel to get public archived threads for + * @param before_id Get threads before this id + * @param limit Number of threads to get + * @return thread_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_threads_get_joined_private_archived(snowflake channel_id, snowflake before_id, uint16_t limit) { + return dpp::awaitable(this, [&] (auto cc) { this->threads_get_joined_private_archived(channel_id, before_id, limit, cc); }); +} + +/** + * @brief Get private archived threads in a channel (Sorted by archive_timestamp in descending order) + * @see dpp::cluster::threads_get_private_archived + * @see https://discord.com/developers/docs/topics/threads + * @param channel_id Channel to get public archived threads for + * @param before_timestamp Get threads before this timestamp + * @param limit Number of threads to get + * @return thread_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_threads_get_private_archived(snowflake channel_id, time_t before_timestamp, uint16_t limit) { + return dpp::awaitable(this, [&] (auto cc) { this->threads_get_private_archived(channel_id, before_timestamp, limit, cc); }); +} + +/** + * @brief Get public archived threads in a channel (Sorted by archive_timestamp in descending order) + * @see dpp::cluster::threads_get_public_archived + * @see https://discord.com/developers/docs/topics/threads + * @param channel_id Channel to get public archived threads for + * @param before_timestamp Get threads before this timestamp + * @param limit Number of threads to get + * @return thread_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_threads_get_public_archived(snowflake channel_id, time_t before_timestamp, uint16_t limit) { + return dpp::awaitable(this, [&] (auto cc) { this->threads_get_public_archived(channel_id, before_timestamp, limit, cc); }); +} + +/** + * @brief Get a thread member + * @see dpp::cluster::thread_member_get + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread to get member for + * @param user_id ID of the user to get + * @return thread_member returned object on completion + * \memberof dpp::cluster + */ +auto inline co_thread_member_get(const snowflake thread_id, const snowflake user_id) { + return dpp::awaitable(this, [&] (auto cc) { this->thread_member_get(thread_id, user_id, cc); }); +} + +/** + * @brief Get members of a thread + * @see dpp::cluster::thread_members_get + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread to get members for + * @return thread_member_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_thread_members_get(snowflake thread_id) { + return dpp::awaitable(this, [&] (auto cc) { this->thread_members_get(thread_id, cc); }); +} + +/** + * @brief Create a thread + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see dpp::cluster::thread_create + * @see https://discord.com/developers/docs/resources/guild#create-guild-channel + * @param thread_name Name of the thread + * @param channel_id Channel in which thread to create + * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) + * @param thread_type Type of thread - CHANNEL_PUBLIC_THREAD, CHANNEL_ANNOUNCEMENT_THREAD, CHANNEL_PRIVATE_THREAD + * @param invitable whether non-moderators can add other non-moderators to a thread; only available when creating a private thread + * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected + * @return thread returned object on completion + * \memberof dpp::cluster + */ +auto inline co_thread_create(const std::string& thread_name, snowflake channel_id, uint16_t auto_archive_duration, channel_type thread_type, bool invitable, uint16_t rate_limit_per_user) { + return dpp::awaitable(this, [&] (auto cc) { this->thread_create(thread_name, channel_id, auto_archive_duration, thread_type, invitable, rate_limit_per_user, cc); }); +} + +/** + * @brief Create a thread with a message (Discord: ID of a thread is same as message ID) + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::thread_create_with_message + * @see https://discord.com/developers/docs/topics/threads + * @param thread_name Name of the thread + * @param channel_id Channel in which thread to create + * @param message_id message to start thread with + * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) + * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected + * @return thread returned object on completion + * \memberof dpp::cluster + */ +auto inline co_thread_create_with_message(const std::string& thread_name, snowflake channel_id, snowflake message_id, uint16_t auto_archive_duration, uint16_t rate_limit_per_user) { + return dpp::awaitable(this, [&] (auto cc) { this->thread_create_with_message(thread_name, channel_id, message_id, auto_archive_duration, rate_limit_per_user, cc); }); +} + +/** + * @brief Add a member to a thread + * @see dpp::cluster::thread_member_add + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread ID to add to + * @param user_id Member ID to add + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_thread_member_add(snowflake thread_id, snowflake user_id) { + return dpp::awaitable(this, [&] (auto cc) { this->thread_member_add(thread_id, user_id, cc); }); +} + +/** + * @brief Remove a member from a thread + * @see dpp::cluster::thread_member_remove + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread ID to remove from + * @param user_id Member ID to remove + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_thread_member_remove(snowflake thread_id, snowflake user_id) { + return dpp::awaitable(this, [&] (auto cc) { this->thread_member_remove(thread_id, user_id, cc); }); +} + +/** + * @brief Edit current (bot) user + * + * Modifies the current member in a guild. Returns the updated guild_member object on success. + * Fires a `Guild Member Update` Gateway event. + * @see dpp::cluster::current_user_edit + * @see https://discord.com/developers/docs/resources/user#modify-current-user + * @param nickname Nickname to set + * @param image_blob Avatar data to upload (NOTE: Very heavily rate limited!) + * @param type Type of image for avatar + * @return user returned object on completion + * @throw dpp::exception Image data is larger than the maximum size of 256 kilobytes + * \memberof dpp::cluster + */ +auto inline co_current_user_edit(const std::string &nickname, const std::string& image_blob, const image_type type) { + return dpp::awaitable(this, [&] (auto cc) { this->current_user_edit(nickname, image_blob, type, cc); }); +} + +/** + * @brief Get current (bot) application + * + * @see dpp::cluster::current_application_get + * @see https://discord.com/developers/docs/topics/oauth2#get-current-bot-application-information + * @return application returned object on completion + * \memberof dpp::cluster + */ +auto inline co_current_application_get() { + return dpp::awaitable(this, [&] (auto cc) { this->current_application_get(cc); }); +} + +/** + * @brief Get current (bot) user + * + * @see dpp::cluster::current_user_get + * @see https://discord.com/developers/docs/resources/user#get-current-user + * @return user_identified returned object on completion + * @note The user_identified object is a subclass of dpp::user which contains further details if you have the oauth2 identify or email scopes. + * If you do not have these scopes, these fields are empty. You can safely convert a user_identified to user with `dynamic_cast`. + * \memberof dpp::cluster + */ +auto inline co_current_user_get() { + return dpp::awaitable(this, [&] (auto cc) { this->current_user_get(cc); }); +} + +/** + * @brief Set the bot's voice state on a stage channel + * + * **Caveats** + * + * There are currently several caveats for this endpoint: + * + * - `channel_id` must currently point to a stage channel. + * - current user must already have joined `channel_id`. + * - You must have the `MUTE_MEMBERS` permission to unsuppress yourself. You can always suppress yourself. + * - You must have the `REQUEST_TO_SPEAK` permission to request to speak. You can always clear your own request to speak. + * - You are able to set `request_to_speak_timestamp` to any present or future time. + * + * @see dpp::cluster::current_user_set_voice_state + * @see https://discord.com/developers/docs/resources/guild#modify-current-user-voice-state + * @param guild_id Guild to set voice state on + * @param channel_id Stage channel to set voice state on + * @return confirmation returned object on completion + * @param suppress True if the user's audio should be suppressed, false if it should not + * @param request_to_speak_timestamp The time at which we requested to speak, or 0 to clear the request. The time set here must be the current time or in the future. + * @throw std::logic_exception You attempted to set a request_to_speak_timestamp in the past which is not the value of 0. + * \memberof dpp::cluster + */ +auto inline co_current_user_set_voice_state(snowflake guild_id, snowflake channel_id, bool suppress, time_t request_to_speak_timestamp) { + return dpp::awaitable(this, [&] (auto cc) { this->current_user_set_voice_state(guild_id, channel_id, suppress, request_to_speak_timestamp, cc); }); +} + +/** + * @brief Set a user's voice state on a stage channel + * + * **Caveats** + * + * There are currently several caveats for this endpoint: + * + * - `channel_id` must currently point to a stage channel. + * - User must already have joined `channel_id`. + * - You must have the `MUTE_MEMBERS` permission. (Since suppression is the only thing that is available currently) + * - When unsuppressed, non-bot users will have their `request_to_speak_timestamp` set to the current time. Bot users will not. + * - When suppressed, the user will have their `request_to_speak_timestamp` removed. + * + * @see dpp::cluster::user_set_voice_state + * @see https://discord.com/developers/docs/resources/guild#modify-user-voice-state + * @param user_id The user to set the voice state of + * @param guild_id Guild to set voice state on + * @param channel_id Stage channel to set voice state on + * @return confirmation returned object on completion + * @param suppress True if the user's audio should be suppressed, false if it should not + * \memberof dpp::cluster + */ +auto inline co_user_set_voice_state(snowflake user_id, snowflake guild_id, snowflake channel_id, bool suppress) { + return dpp::awaitable(this, [&] (auto cc) { this->user_set_voice_state(user_id, guild_id, channel_id, suppress, cc); }); +} + +/** + * @brief Get current user's connections (linked accounts, e.g. steam, xbox). + * This call requires the oauth2 `connections` scope and cannot be executed + * against a bot token. + * @see dpp::cluster::current_user_connections_get + * @see https://discord.com/developers/docs/resources/user#get-user-connections + * @return connection_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_current_user_connections_get() { + return dpp::awaitable(this, [&] (auto cc) { this->current_user_connections_get(cc); }); +} + +/** + * @brief Get current (bot) user guilds + * @see dpp::cluster::current_user_get_guilds + * @see https://discord.com/developers/docs/resources/user#get-current-user-guilds + * @return guild_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_current_user_get_guilds() { + return dpp::awaitable(this, [&] (auto cc) { this->current_user_get_guilds(cc); }); +} + +/** + * @brief Leave a guild + * @see dpp::cluster::current_user_leave_guild + * @see https://discord.com/developers/docs/resources/user#leave-guild + * @param guild_id Guild ID to leave + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_current_user_leave_guild(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->current_user_leave_guild(guild_id, cc); }); +} + +/** + * @brief Get a user by id + * + * @see dpp::cluster::user_get + * @see https://discord.com/developers/docs/resources/user#get-user + * @param user_id User ID to retrieve + * @return user_identified returned object on completion + * @note The user_identified object is a subclass of dpp::user which contains further details if you have the oauth2 identify or email scopes. + * If you do not have these scopes, these fields are empty. You can safely convert a user_identified to user with `dynamic_cast`. + * @note unless you want something special from `dpp::user_identified` or you've turned off caching, you have no need to call this. + * Call `dpp::find_user` instead that looks up the user in the cache rather than a REST call. + * \memberof dpp::cluster + */ +auto inline co_user_get(snowflake user_id) { + return dpp::awaitable(this, [&] (auto cc) { this->user_get(user_id, cc); }); +} + +/** + * @brief Get all voice regions + * @see dpp::cluster::get_voice_regions + * @see https://discord.com/developers/docs/resources/voice#list-voice-regions + * @return voiceregion_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_get_voice_regions() { + return dpp::awaitable(this, [&] (auto cc) { this->get_voice_regions(cc); }); +} + +/** + * @brief Get guild voice regions. + * + * Voice regions per guild are somewhat deprecated in preference of per-channel voice regions. + * Returns a list of voice region objects for the guild. Unlike the similar /voice route, this returns VIP servers when + * the guild is VIP-enabled. + * + * @see dpp::cluster::guild_get_voice_regions + * @see https://discord.com/developers/docs/resources/guild#get-guild-voice-regions + * @param guild_id Guild ID to get voice regions for + * @return voiceregion_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_get_voice_regions(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_get_voice_regions(guild_id, cc); }); +} + +/** + * @brief Create a webhook + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::create_webhook + * @see https://discord.com/developers/docs/resources/webhook#create-webhook + * @param w Webhook to create + * @return webhook returned object on completion + * \memberof dpp::cluster + */ +auto inline co_create_webhook(const class webhook &w) { + return dpp::awaitable(this, [&] (auto cc) { this->create_webhook(w, cc); }); +} + +/** + * @brief Delete a webhook + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::delete_webhook + * @see https://discord.com/developers/docs/resources/webhook#delete-webhook + * @param webhook_id Webhook ID to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_delete_webhook(snowflake webhook_id) { + return dpp::awaitable(this, [&] (auto cc) { this->delete_webhook(webhook_id, cc); }); +} + +/** + * @brief Delete webhook message + * + * @see dpp::cluster::delete_webhook_message + * @see https://discord.com/developers/docs/resources/webhook#delete-webhook-message + * @param wh Webhook to delete message for + * @param message_id Message ID to delete + * @param thread_id ID of the thread the message is in + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_delete_webhook_message(const class webhook &wh, snowflake message_id, snowflake thread_id) { + return dpp::awaitable(this, [&] (auto cc) { this->delete_webhook_message(wh, message_id, thread_id, cc); }); +} + +/** + * @brief Delete webhook with token + * @see dpp::cluster::delete_webhook_with_token + * @see https://discord.com/developers/docs/resources/webhook#delete-webhook-with-token + * @param webhook_id Webhook ID to delete + * @param token Token of webhook to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_delete_webhook_with_token(snowflake webhook_id, const std::string &token) { + return dpp::awaitable(this, [&] (auto cc) { this->delete_webhook_with_token(webhook_id, token, cc); }); +} + +/** + * @brief Edit webhook + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::edit_webhook + * @see https://discord.com/developers/docs/resources/webhook#modify-webhook + * @param wh Webhook to edit + * @return webhook returned object on completion + * \memberof dpp::cluster + */ +auto inline co_edit_webhook(const class webhook& wh) { + return dpp::awaitable(this, [&] (auto cc) { this->edit_webhook(wh, cc); }); +} + +/** + * @brief Edit webhook message + * + * When the content field is edited, the mentions array in the message object will be reconstructed from scratch based on + * the new content. The allowed_mentions field of the edit request controls how this happens. If there is no explicit + * allowed_mentions in the edit request, the content will be parsed with default allowances, that is, without regard to + * whether or not an allowed_mentions was present in the request that originally created the message. + * + * @see dpp::cluster::edit_webhook_message + * @see https://discord.com/developers/docs/resources/webhook#edit-webhook-message + * @note the attachments array must contain all attachments that should be present after edit, including retained and new attachments provided in the request body. + * @param wh Webhook to edit message for + * @param m New message + * @param thread_id ID of the thread the message is in + * @return message returned object on completion + * \memberof dpp::cluster + */ +auto inline co_edit_webhook_message(const class webhook &wh, const struct message& m, snowflake thread_id) { + return dpp::awaitable(this, [&] (auto cc) { this->edit_webhook_message(wh, m, thread_id, cc); }); +} + +/** + * @brief Edit webhook with token (token is encapsulated in the webhook object) + * @see dpp::cluster::edit_webhook_with_token + * @see https://discord.com/developers/docs/resources/webhook#modify-webhook-with-token + * @param wh Webhook to edit (should include token) + * @return webhook returned object on completion + * \memberof dpp::cluster + */ +auto inline co_edit_webhook_with_token(const class webhook& wh) { + return dpp::awaitable(this, [&] (auto cc) { this->edit_webhook_with_token(wh, cc); }); +} + +/** + * @brief Execute webhook + * + * @see dpp::cluster::execute_webhook + * @see https://discord.com/developers/docs/resources/webhook#execute-webhook + * @param wh Webhook to execute + * @param m Message to send + * @param wait waits for server confirmation of message send before response, and returns the created message body + * @param thread_id Send a message to the specified thread within a webhook's channel. The thread will automatically be unarchived + * @param thread_name Name of thread to create (requires the webhook channel to be a forum channel) + * @return message returned object on completion + * @note If the webhook channel is a forum channel, you must provide either `thread_id` or `thread_name`. If `thread_id` is provided, the message will send in that thread. If `thread_name` is provided, a thread with that name will be created in the forum channel. + * \memberof dpp::cluster + */ +auto inline co_execute_webhook(const class webhook &wh, const struct message& m, bool wait, snowflake thread_id, const std::string& thread_name) { + return dpp::awaitable(this, [&] (auto cc) { this->execute_webhook(wh, m, wait, thread_id, thread_name, cc); }); +} + +/** + * @brief Get channel webhooks + * @see dpp::cluster::get_channel_webhooks + * @see https://discord.com/developers/docs/resources/webhook#get-guild-webhooks + * @param channel_id Channel ID to get webhooks for + * @return webhook_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_get_channel_webhooks(snowflake channel_id) { + return dpp::awaitable(this, [&] (auto cc) { this->get_channel_webhooks(channel_id, cc); }); +} + +/** + * @brief Get guild webhooks + * @see dpp::cluster::get_guild_webhooks + * @see https://discord.com/developers/docs/resources/webhook#get-guild-webhooks + * @param guild_id Guild ID to get webhooks for + * @return webhook_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_get_guild_webhooks(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->get_guild_webhooks(guild_id, cc); }); +} + +/** + * @brief Get webhook + * @see dpp::cluster::get_webhook + * @see https://discord.com/developers/docs/resources/webhook#get-webhook + * @param webhook_id Webhook ID to get + * @return webhook returned object on completion + * \memberof dpp::cluster + */ +auto inline co_get_webhook(snowflake webhook_id) { + return dpp::awaitable(this, [&] (auto cc) { this->get_webhook(webhook_id, cc); }); +} + +/** + * @brief Get webhook message + * + * @see dpp::cluster::get_webhook_message + * @see https://discord.com/developers/docs/resources/webhook#get-webhook-message + * @param wh Webhook to get the original message for + * @param message_id The message ID + * @param thread_id ID of the thread the message is in + * @return message returned object on completion + * \memberof dpp::cluster + */ +auto inline co_get_webhook_message(const class webhook &wh, snowflake message_id, snowflake thread_id) { + return dpp::awaitable(this, [&] (auto cc) { this->get_webhook_message(wh, message_id, thread_id, cc); }); +} + +/** + * @brief Get webhook using token + * @see dpp::cluster::get_webhook_with_token + * @see https://discord.com/developers/docs/resources/webhook#get-webhook-with-token + * @param webhook_id Webhook ID to retrieve + * @param token Token of webhook + * @return webhook returned object on completion + * \memberof dpp::cluster + */ +auto inline co_get_webhook_with_token(snowflake webhook_id, const std::string &token) { + return dpp::awaitable(this, [&] (auto cc) { this->get_webhook_with_token(webhook_id, token, cc); }); +} + + +/* End of auto-generated definitions */ +auto inline co_request(const std::string &url, http_method method, const std::string &postdata = "", const std::string &mimetype = "text/plain", const std::multimap &headers = {}) { + return dpp::awaitable(this, [&] (auto cc) { this->request(url, method, cc, mimetype, headers); }); +} + diff --git a/3rdParty/dpp/cluster_sync_calls.h b/3rdParty/dpp/cluster_sync_calls.h index 44dd073ecb..51adeed1e5 100644 --- a/3rdParty/dpp/cluster_sync_calls.h +++ b/3rdParty/dpp/cluster_sync_calls.h @@ -1,2502 +1,2502 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2022 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - - -/* Auto @generated by buildtools/make_sync_struct.php. - * - * DO NOT EDIT BY HAND! - * - * To re-generate this header file re-run the script! - */ -/** - * @brief Create/overwrite global slash commands. - * Any existing global slash commands will be deleted and replaced with these. - * - * @see dpp::cluster::global_bulk_command_create - * @see https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-global-application-commands - * @param commands Vector of slash commands to create/update. - * overwriting existing commands that are registered globally for this application. Updates will be available in all guilds after 1 hour. - * Commands that do not already exist will count toward daily application command create limits. - * @return slashcommand_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -slashcommand_map global_bulk_command_create_sync(const std::vector &commands); - -/** - * @brief Create a global slash command (a bot can have a maximum of 100 of these). - * - * @see dpp::cluster::global_command_create - * @see https://discord.com/developers/docs/interactions/application-commands#create-global-application-command - * @param s Slash command to create - * @return slashcommand returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -slashcommand global_command_create_sync(const slashcommand &s); - -/** - * @brief Get a global slash command - * - * @see dpp::cluster::global_command_get - * @see https://discord.com/developers/docs/interactions/application-commands#get-global-application-command - * @param id The ID of the slash command - * @return slashcommand returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -slashcommand global_command_get_sync(snowflake id); - -/** - * @brief Delete a global slash command (a bot can have a maximum of 100 of these) - * - * @see dpp::cluster::global_command_delete - * @see https://discord.com/developers/docs/interactions/application-commands#delete-global-application-command - * @param id Slash command to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation global_command_delete_sync(snowflake id); - -/** - * @brief Edit a global slash command (a bot can have a maximum of 100 of these) - * - * @see dpp::cluster::global_command_edit - * @see https://discord.com/developers/docs/interactions/application-commands#edit-global-application-command - * @param s Slash command to change - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation global_command_edit_sync(const slashcommand &s); - -/** - * @brief Get the application's global slash commands - * - * @see dpp::cluster::global_commands_get - * @see https://discord.com/developers/docs/interactions/application-commands#get-global-application-commands - * @return slashcommand_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -slashcommand_map global_commands_get_sync(); - -/** - * @brief Create/overwrite guild slash commands. - * Any existing guild slash commands on this guild will be deleted and replaced with these. - * - * @see dpp::cluster::guild_bulk_command_create - * @see https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-guild-application-commands - * @param commands Vector of slash commands to create/update. - * New guild commands will be available in the guild immediately. If the command did not already exist, it will count toward daily application command create limits. - * @param guild_id Guild ID to create/update the slash commands in - * @return slashcommand_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -slashcommand_map guild_bulk_command_create_sync(const std::vector &commands, snowflake guild_id); - -/** - * @brief Get all slash command permissions of a guild - * - * @see dpp::cluster::guild_commands_get_permissions - * @see https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions - * @param guild_id Guild ID to get the slash commands permissions for - * @return guild_command_permissions_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild_command_permissions_map guild_commands_get_permissions_sync(snowflake guild_id); - -/** - * @brief Edit/Overwrite the permissions of all existing slash commands in a guild - * - * @note You can only add up to 10 permission overwrites for a command - * - * @see dpp::cluster::guild_bulk_command_edit_permissions - * @see https://discord.com/developers/docs/interactions/application-commands#batch-edit-application-command-permissions - * @warning The endpoint will overwrite all existing permissions for all commands of the application in a guild, including slash commands, user commands, and message commands. Meaning that if you forgot to pass a slash command, the permissions of it might be removed. - * @param commands A vector of slash commands to edit/overwrite the permissions for - * @param guild_id Guild ID to edit permissions of the slash commands in - * @return guild_command_permissions_map returned object on completion - * @deprecated This has been disabled with updates to Permissions v2. You can use guild_command_edit_permissions instead - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild_command_permissions_map guild_bulk_command_edit_permissions_sync(const std::vector &commands, snowflake guild_id); - -/** - * @brief Create a slash command local to a guild - * - * @see dpp::cluster::guild_command_create - * @see https://discord.com/developers/docs/interactions/application-commands#create-guild-application-command - * @note Creating a command with the same name as an existing command for your application will overwrite the old command. - * @param s Slash command to create - * @param guild_id Guild ID to create the slash command in - * @return slashcommand returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -slashcommand guild_command_create_sync(const slashcommand &s, snowflake guild_id); - -/** - * @brief Delete a slash command local to a guild - * - * @see dpp::cluster::guild_command_delete - * @see https://discord.com/developers/docs/interactions/application-commands#delete-guild-application-command - * @param id Slash command to delete - * @param guild_id Guild ID to delete the slash command in - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_command_delete_sync(snowflake id, snowflake guild_id); - -/** - * @brief Edit slash command permissions of a guild - * - * @see dpp::cluster::guild_command_edit_permissions - * @see https://discord.com/developers/docs/interactions/application-commands#edit-application-command-permissions - * @note You can only add up to 10 permission overwrites for a command - * @param s Slash command to edit the permissions for - * @param guild_id Guild ID to edit the slash command in - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_command_edit_permissions_sync(const slashcommand &s, snowflake guild_id); - -/** - * @brief Get a slash command of a guild - * - * @see dpp::cluster::guild_command_get - * @see https://discord.com/developers/docs/interactions/application-commands#get-guild-application-command - * @note The returned slash commands will not have permissions set, you need to use a permissions getter e.g. dpp::guild_commands_get_permissions to get the guild command permissions - * @param id The ID of the slash command - * @param guild_id Guild ID to get the slash command from - * @return slashcommand returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -slashcommand guild_command_get_sync(snowflake id, snowflake guild_id); - -/** - * @brief Get the permissions for a slash command of a guild - * - * @see dpp::cluster::guild_command_get_permissions - * @see https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions - * @param id The ID of the slash command to get the permissions for - * @param guild_id Guild ID to get the permissions of - * @return guild_command_permissions returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild_command_permissions guild_command_get_permissions_sync(snowflake id, snowflake guild_id); - -/** - * @brief Edit a slash command local to a guild - * - * @see dpp::cluster::guild_command_edit - * @see https://discord.com/developers/docs/interactions/application-commands#edit-guild-application-command - * @param s Slash command to edit - * @param guild_id Guild ID to edit the slash command in - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_command_edit_sync(const slashcommand &s, snowflake guild_id); - -/** - * @brief Get the application's slash commands for a guild - * - * @see dpp::cluster::guild_commands_get - * @see https://discord.com/developers/docs/interactions/application-commands#get-guild-application-commands - * @note The returned slash commands will not have permissions set, you need to use a permissions getter e.g. dpp::guild_commands_get_permissions to get the guild command permissions - * @param guild_id Guild ID to get the slash commands for - * @return slashcommand_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -slashcommand_map guild_commands_get_sync(snowflake guild_id); - -/** - * @brief Respond to a slash command - * - * @see dpp::cluster::interaction_response_create - * @see https://discord.com/developers/docs/interactions/receiving-and-responding#create-interaction-response - * @param interaction_id Interaction id to respond to - * @param token Token for the interaction webhook - * @param r Response to send - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation interaction_response_create_sync(snowflake interaction_id, const std::string &token, const interaction_response &r); - -/** - * @brief Edit response to a slash command - * - * @see dpp::cluster::interaction_response_edit - * @see https://discord.com/developers/docs/interactions/receiving-and-responding#edit-original-interaction-response - * @param token Token for the interaction webhook - * @param m Message to send - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation interaction_response_edit_sync(const std::string &token, const message &m); - -/** - * @brief Create a followup message to a slash command - * - * @param token Token for the interaction webhook - * @param m followup message to create - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation interaction_followup_create_sync(const std::string &token, const message &m); - -/** - * @brief Edit original followup message to a slash command - * This is an alias for cluster::interaction_response_edit - * @see dpp::cluster::interaction_followup_edit_original - * @see cluster::interaction_response_edit - * - * @param token Token for the interaction webhook - * @param m message to edit, the ID should be set - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation interaction_followup_edit_original_sync(const std::string &token, const message &m); - -/** - * @brief - * - * @param token Token for the interaction webhook - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation interaction_followup_delete_sync(const std::string &token); - -/** - * @brief Edit followup message to a slash command - * The message ID in the message you pass should be correctly set to that of a followup message you previously sent - * @param token Token for the interaction webhook - * @param m message to edit, the ID should be set - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation interaction_followup_edit_sync(const std::string &token, const message &m); - -/** - * @brief Get the followup message to a slash command - * @param token Token for the interaction webhook - * @param message_id message to retrieve - * @return message returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -message interaction_followup_get_sync(const std::string &token, snowflake message_id); - -/** - * @brief Get all auto moderation rules for a guild - * - * @param guild_id Guild id of the auto moderation rule - * @return automod_rule_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -automod_rule_map automod_rules_get_sync(snowflake guild_id); - -/** - * @brief Get a single auto moderation rule - * - * @param guild_id Guild id of the auto moderation rule - * @param rule_id Rule id to retrieve - * @return automod_rule returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -automod_rule automod_rule_get_sync(snowflake guild_id, snowflake rule_id); - -/** - * @brief Create an auto moderation rule - * - * @param guild_id Guild id of the auto moderation rule - * @param r Auto moderation rule to create - * @return automod_rule returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -automod_rule automod_rule_create_sync(snowflake guild_id, const automod_rule& r); - -/** - * @brief Edit an auto moderation rule - * - * @param guild_id Guild id of the auto moderation rule - * @param r Auto moderation rule to edit. The rule's id must be set. - * @return automod_rule returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -automod_rule automod_rule_edit_sync(snowflake guild_id, const automod_rule& r); - -/** - * @brief Delete an auto moderation rule - * - * @param guild_id Guild id of the auto moderation rule - * @param rule_id Auto moderation rule id to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation automod_rule_delete_sync(snowflake guild_id, snowflake rule_id); - -/** - * @brief Create a channel - * - * Create a new channel object for the guild. Requires the `MANAGE_CHANNELS` permission. If setting permission overwrites, - * only permissions your bot has in the guild can be allowed/denied. Setting `MANAGE_ROLES` permission in channels is only possible - * for guild administrators. Returns the new channel object on success. Fires a `Channel Create Gateway` event. - * - * All parameters to this endpoint are optional excluding `name` - * - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::channel_create - * @see https://discord.com/developers/docs/resources/channel#create-channel - * @param c Channel to create - * @return channel returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -channel channel_create_sync(const class channel &c); - -/** - * @brief Remove a permission from a channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::channel_delete_permission - * @see https://discord.com/developers/docs/resources/channel#delete-channel-permission - * @param c Channel to remove permission from - * @param overwrite_id Overwrite to remove, user or channel ID - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation channel_delete_permission_sync(const class channel &c, snowflake overwrite_id); - -/** - * @brief Delete a channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::channel_delete - * @see https://discord.com/developers/docs/resources/channel#deleteclose-channel - * @param channel_id Channel id to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation channel_delete_sync(snowflake channel_id); - -/** - * @brief Edit multiple channels positions - * - * Modify the positions of a set of channel objects for the guild. - * Requires `MANAGE_CHANNELS` permission. Fires multiple `Channel Update Gateway` events. - * Only channels to be modified are required. - * - * @see dpp::cluster::channel_edit_positions - * @see https://discord.com/developers/docs/resources/guild#modify-guild-channel-positions - * @param c Channel to change the position for - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation channel_edit_positions_sync(const std::vector &c); - -/** - * @brief Edit a channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::channel_edit - * @see https://discord.com/developers/docs/resources/channel#modify-channel - * @param c Channel to edit/update - * @return channel returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -channel channel_edit_sync(const class channel &c); - -/** - * @brief Follow an announcement (news) channel - * @see dpp::cluster::channel_follow_news - * @see https://discord.com/developers/docs/resources/channel#follow-news-channel - * @param c Channel id to follow - * @param target_channel_id Channel to subscribe the channel to - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation channel_follow_news_sync(const class channel &c, snowflake target_channel_id); - -/** - * @brief Get a channel - * - * @see dpp::cluster::channel_get - * @see https://discord.com/developers/docs/resources/channel#get-channel - * @param c Channel ID to retrieve - * @return channel returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -channel channel_get_sync(snowflake c); - -/** - * @brief Create invite for a channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::channel_invite_create - * @see https://discord.com/developers/docs/resources/channel#create-channel-invite - * @param c Channel to create an invite on - * @param i Invite to create - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation channel_invite_create_sync(const class channel &c, const class invite &i); - -/** - * @brief Get invites for a channel - * - * @see dpp::cluster::channel_invites_get - * @see https://discord.com/developers/docs/resources/invite#get-invites - * @param c Channel to get invites for - * @return invite_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -invite_map channel_invites_get_sync(const class channel &c); - -/** - * @brief Get all channels for a guild - * - * @see dpp::cluster::channels_get - * @see https://discord.com/developers/docs/resources/channel#get-channels - * @param guild_id Guild ID to retrieve channels for - * @return channel_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -channel_map channels_get_sync(snowflake guild_id); - -/** - * @brief Create a dm channel - * @see dpp::cluster::create_dm_channel - * @see https://discord.com/developers/docs/resources/user#create-dm - * @param user_id User ID to create DM channel with - * @return channel returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -channel create_dm_channel_sync(snowflake user_id); - -/** - * @brief Get current user DM channels - * - * @return channel_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -channel_map current_user_get_dms_sync(); - -/** - * @brief Create a direct message, also create the channel for the direct message if needed - * - * @see dpp::cluster::direct_message_create - * @see https://discord.com/developers/docs/resources/user#create-dm - * @see dpp::cluster::direct_message_create - * @see https://discord.com/developers/docs/resources/channel#create-message - * @param user_id User ID of user to send message to - * @param m Message object - * @return message returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -message direct_message_create_sync(snowflake user_id, const message &m); - -/** - * @brief Adds a recipient to a Group DM using their access token - * @see dpp::cluster::gdm_add - * @see https://discord.com/developers/docs/resources/channel#group-dm-add-recipient - * @param channel_id Channel id to add group DM recipients to - * @param user_id User ID to add - * @param access_token Access token from OAuth2 - * @param nick Nickname of user to apply to the chat - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation gdm_add_sync(snowflake channel_id, snowflake user_id, const std::string &access_token, const std::string &nick); - -/** - * @brief Removes a recipient from a Group DM - * @see dpp::cluster::gdm_remove - * @see https://discord.com/developers/docs/resources/channel#group-dm-remove-recipient - * @param channel_id Channel ID of group DM - * @param user_id User ID to remove from group DM - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation gdm_remove_sync(snowflake channel_id, snowflake user_id); - -/** - * @brief Create single emoji. - * You must ensure that the emoji passed contained image data using the emoji::load_image() method. - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see dpp::cluster::guild_emoji_create - * @see https://discord.com/developers/docs/resources/emoji#create-guild-emoji - * @param guild_id Guild ID to create emoji om - * @param newemoji Emoji to create - * @return emoji returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -emoji guild_emoji_create_sync(snowflake guild_id, const class emoji& newemoji); - -/** - * @brief Delete a guild emoji - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see dpp::cluster::guild_emoji_delete - * @see https://discord.com/developers/docs/resources/emoji#delete-guild-emoji - * @param guild_id Guild ID to delete emoji on - * @param emoji_id Emoji ID to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_emoji_delete_sync(snowflake guild_id, snowflake emoji_id); - -/** - * @brief Edit a single emoji. - * - * You must ensure that the emoji passed contained image data using the emoji::load_image() method. - * @see dpp::cluster::guild_emoji_edit - * @see https://discord.com/developers/docs/resources/emoji#get-guild-emoji - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to edit emoji on - * @param newemoji Emoji to edit - * @return emoji returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -emoji guild_emoji_edit_sync(snowflake guild_id, const class emoji& newemoji); - -/** - * @brief Get a single emoji - * - * @see dpp::cluster::guild_emoji_get - * @see https://discord.com/developers/docs/resources/emoji#get-guild-emoji - * @param guild_id Guild ID to get emoji for - * @param emoji_id Emoji ID to get - * @return emoji returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -emoji guild_emoji_get_sync(snowflake guild_id, snowflake emoji_id); - -/** - * @brief Get all emojis for a guild - * - * @see dpp::cluster::guild_emojis_get - * @see https://discord.com/developers/docs/resources/emoji#get-guild-emojis - * @param guild_id Guild ID to get emojis for - * @return emoji_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -emoji_map guild_emojis_get_sync(snowflake guild_id); - -/** - * @brief Get the gateway information for the bot using the token - * @see dpp::cluster::get_gateway_bot - * @see https://discord.com/developers/docs/topics/gateway#get-gateway-bot - * @return gateway returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -gateway get_gateway_bot_sync(); - -/** - * @brief Modify current member - * - * Modifies the current member in a guild. - * Fires a `Guild Member Update` Gateway event. - * - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::guild_current_member_edit - * @see https://discord.com/developers/docs/resources/guild#modify-current-member - * @param guild_id Guild ID to change on - * @param nickname New nickname, or empty string to clear nickname - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_current_member_edit_sync(snowflake guild_id, const std::string &nickname); - -/** - * @brief Get the audit log for a guild - * - * @see dpp::cluster::guild_auditlog_get - * @see https://discord.com/developers/docs/resources/audit-log#get-guild-audit-log - * @param guild_id Guild to get the audit log of - * @param user_id Entries from a specific user ID. Set this to `0` will fetch any user - * @param action_type Entries for a specific dpp::audit_type. Set this to `0` will fetch any type - * @param before Entries that preceded a specific audit log entry ID. Used for paginating - * @param limit Maximum number of entries (between 1-100) to return - * @return auditlog returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -auditlog guild_auditlog_get_sync(snowflake guild_id, snowflake user_id, uint32_t action_type, snowflake before, uint32_t limit); - -/** - * @brief Add guild ban - * - * Create a guild ban, and optionally delete previous messages sent by the banned user. - * Requires the `BAN_MEMBERS` permission. Fires a `Guild Ban Add` Gateway event. - * @see dpp::cluster::guild_ban_add - * @see https://discord.com/developers/docs/resources/guild#create-guild-ban - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to add ban to - * @param user_id User ID to ban - * @param delete_message_seconds How many seconds to delete messages for, between 0 and 604800 (7 days). Defaults to 0 - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_ban_add_sync(snowflake guild_id, snowflake user_id, uint32_t delete_message_seconds = 0); - -/** - * @brief Delete guild ban - * - * Remove the ban for a user. Requires the `BAN_MEMBERS` permissions. - * Fires a Guild Ban Remove Gateway event. - * @see dpp::cluster::guild_ban_delete - * @see https://discord.com/developers/docs/resources/guild#remove-guild-ban - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild to delete ban from - * @param user_id User ID to delete ban for - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_ban_delete_sync(snowflake guild_id, snowflake user_id); - -/** - * @brief Create a guild - * - * Create a new guild. Returns a guild object on success. `Fires a Guild Create Gateway` event. - * - * When using the roles parameter, the first member of the array is used to change properties of the guild's everyone role. - * If you are trying to bootstrap a guild with additional roles, keep this in mind. The required id field within each role object is an - * integer placeholder, and will be replaced by the API upon consumption. Its purpose is to allow you to overwrite a role's permissions - * in a channel when also passing in channels with the channels array. - * When using the channels parameter, the position field is ignored, and none of the default channels are created. The id field within - * each channel object may be set to an integer placeholder, and will be replaced by the API upon consumption. Its purpose is to - * allow you to create `GUILD_CATEGORY` channels by setting the `parent_id` field on any children to the category's id field. - * Category channels must be listed before any children. - * - * @see dpp::cluster::guild_create - * @see https://discord.com/developers/docs/resources/guild#create-guild - * @note The region field is deprecated and is replaced by channel.rtc_region. This endpoint can be used only by bots in less than 10 guilds. - * @param g Guild to create - * @return guild returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild guild_create_sync(const class guild &g); - -/** - * @brief Delete a guild - * - * Delete a guild permanently. User must be owner. Fires a `Guild Delete Gateway` event. - * - * @see dpp::cluster::guild_delete - * @see https://discord.com/developers/docs/resources/guild#delete-guild - * @param guild_id Guild ID to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_delete_sync(snowflake guild_id); - -/** - * @brief Delete guild integration - * - * Delete the attached integration object for the guild. Deletes any associated webhooks and kicks the associated bot if there is one. - * Requires the `MANAGE_GUILD` permission. Fires a Guild Integrations Update Gateway event. - * - * @see dpp::cluster::guild_delete_integration - * @see https://discord.com/developers/docs/resources/guild#delete-guild-integration - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to delete integration for - * @param integration_id Integration ID to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_delete_integration_sync(snowflake guild_id, snowflake integration_id); - -/** - * @brief Edit a guild - * - * Modify a guild's settings. Requires the `MANAGE_GUILD` permission. Returns the updated guild object on success. - * Fires a `Guild Update Gateway` event. - * - * @see dpp::cluster::guild_edit - * @see https://discord.com/developers/docs/resources/guild#modify-guild - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param g Guild to edit - * @return guild returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild guild_edit_sync(const class guild &g); - -/** - * @brief Edit guild widget - * - * Requires the `MANAGE_GUILD` permission. - * - * @see dpp::cluster::guild_edit_widget - * @see https://discord.com/developers/docs/resources/guild#modify-guild-widget - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to edit widget for - * @param gw New guild widget information - * @return guild_widget returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild_widget guild_edit_widget_sync(snowflake guild_id, const class guild_widget &gw); - -/** - * @brief Get single guild ban - * - * Requires the `BAN_MEMBERS` permission. - * @see dpp::cluster::guild_get_ban - * @see https://discord.com/developers/docs/resources/guild#get-guild-ban - * @param guild_id Guild ID to get ban for - * @param user_id User ID of ban to retrieve - * @return ban returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -ban guild_get_ban_sync(snowflake guild_id, snowflake user_id); - -/** - * @brief Get guild ban list - * - * Requires the `BAN_MEMBERS` permission. - * @see dpp::cluster::guild_get_bans - * @see https://discord.com/developers/docs/resources/guild#get-guild-bans - * @note Provide a user ID to `before` and `after` for pagination. Users will always be returned in ascending order by the user ID. If both before and after are provided, only before is respected. - * @param guild_id Guild ID to get bans for - * @param before If non-zero, all bans for user ids before this user id will be returned up to the limit - * @param after if non-zero, all bans for user ids after this user id will be returned up to the limit - * @param limit the maximum number of bans to retrieve in this call up to a maximum of 1000 - * @return ban_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -ban_map guild_get_bans_sync(snowflake guild_id, snowflake before, snowflake after, snowflake limit); - - -guild guild_get_sync(snowflake guild_id); - -/** - * @brief Get guild integrations - * - * Requires the `MANAGE_GUILD` permission. - * - * @see dpp::cluster::guild_get_integrations - * @see https://discord.com/developers/docs/resources/guild#get-guild-integrations - * @param guild_id Guild ID to get integrations for - * @return integration_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -integration_map guild_get_integrations_sync(snowflake guild_id); - - -guild guild_get_preview_sync(snowflake guild_id); - -/** - * @brief Get guild vanity url, if enabled - * - * Returns a partial dpp::invite object for guilds with that feature enabled. Requires the `MANAGE_GUILD` permission. code will be null if a vanity url for the guild is not set. - * @see dpp::cluster::guild_get_vanity - * @see https://discord.com/developers/docs/resources/guild#get-guild-vanity-url - * @param guild_id Guild to get vanity URL for - * @return invite returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -invite guild_get_vanity_sync(snowflake guild_id); - -/** - * @brief Get guild widget - * - * Requires the `MANAGE_GUILD` permission. - * - * @see dpp::cluster::guild_get_widget - * @see https://discord.com/developers/docs/resources/guild#get-guild-widget - * @param guild_id Guild ID to get widget for - * @return guild_widget returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild_widget guild_get_widget_sync(snowflake guild_id); - -/** - * @brief Modify guild integration - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see dpp::cluster::guild_modify_integration - * @see https://discord.com/developers/docs/resources/guild#modify-guild-integration - * @param guild_id Guild ID to modify integration for - * @param i Integration to modify - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_modify_integration_sync(snowflake guild_id, const class integration &i); - -/** - * @brief Get prune counts - * - * Returns a prune object indicating the number of members that would be removed in a prune operation. Requires the `KICK_MEMBERS` - * permission. By default, prune will not remove users with roles. You can optionally include specific roles in your prune by providing the - * include_roles parameter. Any inactive user that has a subset of the provided role(s) will be counted in the prune and users with additional - * roles will not. - * - * @see dpp::cluster::guild_get_prune_counts - * @see https://discord.com/developers/docs/resources/guild#get-guild-prune-count - * @param guild_id Guild ID to count for pruning - * @param pruneinfo Pruning info - * @return prune returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -prune guild_get_prune_counts_sync(snowflake guild_id, const struct prune& pruneinfo); - -/** - * @brief Begin guild prune - * - * Begin a prune operation. Requires the `KICK_MEMBERS` permission. Returns a prune object indicating the number of members - * that were removed in the prune operation. For large guilds it's recommended to set the `compute_prune_count` option to false, forcing - * 'pruned' to 0. Fires multiple `Guild Member Remove` Gateway events. - * By default, prune will not remove users with roles. You can optionally include specific roles in your prune by providing the `include_roles` - * parameter. Any inactive user that has a subset of the provided role(s) will be included in the prune and users with additional roles will not. - * - * @see dpp::cluster::guild_begin_prune - * @see https://discord.com/developers/docs/resources/guild#begin-guild-prune - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to prune - * @param pruneinfo Pruning info - * @return prune returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -prune guild_begin_prune_sync(snowflake guild_id, const struct prune& pruneinfo); - -/** - * @brief Change current user nickname - * - * Modifies the nickname of the current user in a guild. - * Fires a `Guild Member Update` Gateway event. - * - * @deprecated Deprecated in favor of Modify Current Member. Will be replaced by dpp::cluster::guild_current_member_edit - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::guild_set_nickname - * @see https://discord.com/developers/docs/resources/guild#modify-current-user-nick - * @param guild_id Guild ID to change nickname on - * @param nickname New nickname, or empty string to clear nickname - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_set_nickname_sync(snowflake guild_id, const std::string &nickname); - -/** - * @brief Sync guild integration - * - * @see dpp::cluster::guild_sync_integration - * @see https://discord.com/developers/docs/resources/guild#sync-guild-integration - * @param guild_id Guild ID to sync integration on - * @param integration_id Integration ID to synchronise - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_sync_integration_sync(snowflake guild_id, snowflake integration_id); - -/** - * @brief Add guild member. Needs a specific oauth2 scope, from which you get the access_token. - * - * Adds a user to the guild, provided you have a valid oauth2 access token for the user with the guilds.join scope. - * Returns the guild_member, which is defaulted if the user is already a member of the guild. Fires a `Guild Member Add` Gateway event. - * - * For guilds with Membership Screening enabled, this endpoint will default to adding new members as pending in the guild member object. - * Members that are pending will have to complete membership screening before they become full members that can talk. - * - * @note All parameters to this endpoint except for access_token are optional. - * The bot must be a member of the guild with `CREATE_INSTANT_INVITE` permission. - * @see dpp::cluster::guild_add_member - * @see https://discord.com/developers/docs/resources/guild#add-guild-member - * @param gm Guild member to add - * @param access_token Access token from Oauth2 scope - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_add_member_sync(const guild_member& gm, const std::string &access_token); - -/** - * @brief Edit the properties of an existing guild member - * - * Modify attributes of a guild member. Returns the guild_member. Fires a `Guild Member Update` Gateway event. - * To remove a timeout, set the `communication_disabled_until` to a non-zero time in the past, e.g. 1. - * When moving members to channels, the API user must have permissions to both connect to the channel and have the `MOVE_MEMBERS` permission. - * For moving and disconnecting users from voice, use dpp::cluster::guild_member_move. - * @see dpp::cluster::guild_edit_member - * @see https://discord.com/developers/docs/resources/guild#modify-guild-member - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param gm Guild member to edit - * @return guild_member returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild_member guild_edit_member_sync(const guild_member& gm); - -/** - * @brief Get a guild member - * @see dpp::cluster::guild_get_member - * @see https://discord.com/developers/docs/resources/guild#get-guild-member - * @param guild_id Guild ID to get member for - * @param user_id User ID of member to get - * @return guild_member returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild_member guild_get_member_sync(snowflake guild_id, snowflake user_id); - -/** - * @brief Get all guild members - * - * @note This endpoint is restricted according to whether the `GUILD_MEMBERS` Privileged Intent is enabled for your application. - * @see dpp::cluster::guild_get_members - * @see https://discord.com/developers/docs/resources/guild#get-guild-members - * @param guild_id Guild ID to get all members for - * @param limit max number of members to return (1-1000) - * @param after the highest user id in the previous page - * @return guild_member_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild_member_map guild_get_members_sync(snowflake guild_id, uint16_t limit, snowflake after); - -/** - * @brief Add role to guild member - * - * Adds a role to a guild member. Requires the `MANAGE_ROLES` permission. - * Fires a `Guild Member Update` Gateway event. - * @see dpp::cluster::guild_member_add_role - * @see https://discord.com/developers/docs/resources/guild#add-guild-member-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to add a role to - * @param user_id User ID to add role to - * @param role_id Role ID to add to the user - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_member_add_role_sync(snowflake guild_id, snowflake user_id, snowflake role_id); - -/** - * @brief Remove (kick) a guild member - * - * Remove a member from a guild. Requires `KICK_MEMBERS` permission. - * Fires a `Guild Member Remove` Gateway event. - * @see dpp::cluster::guild_member_delete - * @see https://discord.com/developers/docs/resources/guild#remove-guild-member - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @deprecated Replaced by dpp::cluster::guild_member_kick - * @param guild_id Guild ID to kick member from - * @param user_id User ID to kick - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_member_delete_sync(snowflake guild_id, snowflake user_id); - -/** - * @brief Remove (kick) a guild member - * - * Remove a member from a guild. Requires `KICK_MEMBERS` permission. - * Fires a `Guild Member Remove` Gateway event. - * @see dpp::cluster::guild_member_kick - * @see https://discord.com/developers/docs/resources/guild#remove-guild-member - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to kick member from - * @param user_id User ID to kick - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_member_kick_sync(snowflake guild_id, snowflake user_id); - -/** - * @brief Set the timeout of a guild member - * - * Fires a `Guild Member Update` Gateway event. - * @see dpp::cluster::guild_member_timeout - * @see https://discord.com/developers/docs/resources/guild#modify-guild-member - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to timeout the member in - * @param user_id User ID to set the timeout for - * @param communication_disabled_until The timestamp when the user's timeout will expire (up to 28 days in the future). Set to 0 to remove the timeout - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_member_timeout_sync(snowflake guild_id, snowflake user_id, time_t communication_disabled_until); - -/** - * @brief Remove role from guild member - * - * Removes a role from a guild member. Requires the `MANAGE_ROLES` permission. - * Fires a `Guild Member Update` Gateway event. - * @see dpp::cluster::guild_member_delete_role - * @see https://discord.com/developers/docs/resources/guild#remove-guild-member-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to remove role from user on - * @param user_id User ID to remove role from - * @param role_id Role to remove - * @return confirmation returned object on completion - * @deprecated Use dpp::cluster::guild_member_remove_role instead - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_member_delete_role_sync(snowflake guild_id, snowflake user_id, snowflake role_id); - -/** - * @brief Remove role from guild member - * - * Removes a role from a guild member. Requires the `MANAGE_ROLES` permission. - * Fires a `Guild Member Update` Gateway event. - * @see dpp::cluster::guild_member_remove_role - * @see https://discord.com/developers/docs/resources/guild#remove-guild-member-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to remove role from user on - * @param user_id User ID to remove role from - * @param role_id Role to remove - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_member_remove_role_sync(snowflake guild_id, snowflake user_id, snowflake role_id); - -/** - * @brief Moves the guild member to a other voice channel, if member is connected to one. - * Set the `channel_id` to `0` to disconnect the user. - * - * Fires a `Guild Member Update` Gateway event. - * @note When moving members to channels, the API user __must__ have permissions to both connect to the channel and have the `MOVE_MEMBERS` permission. - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::guild_member_move - * @see https://discord.com/developers/docs/resources/guild#modify-guild-member - * @param channel_id Id of the channel to which the user is used. Set to `0` to disconnect the user - * @param guild_id Guild id to which the user is connected - * @param user_id User id, who should be moved - * @return guild_member returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild_member guild_member_move_sync(const snowflake channel_id, const snowflake guild_id, const snowflake user_id); - -/** - * @brief Search for guild members based on whether their username or nickname starts with the given string. - * - * @note This endpoint is restricted according to whether the `GUILD_MEMBERS` Privileged Intent is enabled for your application. - * @see dpp::cluster::guild_search_members - * @see https://discord.com/developers/docs/resources/guild#search-guild-members - * @param guild_id Guild ID to search in - * @param query Query string to match username(s) and nickname(s) against - * @param limit max number of members to return (1-1000) - * @return guild_member_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild_member_map guild_search_members_sync(snowflake guild_id, const std::string& query, uint16_t limit); - -/** - * @brief Get guild invites - * - * Returns a list of invite objects (with invite metadata) for the guild. Requires the `MANAGE_GUILD` permission. - * - * @see dpp::cluster::guild_get_invites - * @see https://discord.com/developers/docs/resources/guild#get-guild-invites - * @param guild_id Guild ID to get invites for - * @return invite_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -invite_map guild_get_invites_sync(snowflake guild_id); - - -invite invite_delete_sync(const std::string &invitecode); - - -invite invite_get_sync(const std::string &invitecode); - -/** - * @brief Send a message to a channel. The callback function is called when the message has been sent - * - * @see dpp::cluster::message_create - * @see https://discord.com/developers/docs/resources/channel#create-message - * @param m Message to send - * @return message returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -message message_create_sync(const struct message &m); - -/** - * @brief Crosspost a message. The callback function is called when the message has been sent - * - * @see dpp::cluster::message_crosspost - * @see https://discord.com/developers/docs/resources/channel#crosspost-message - * @param message_id Message to crosspost - * @param channel_id Channel ID to crosspost from - * @return message returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -message message_crosspost_sync(snowflake message_id, snowflake channel_id); - -/** - * @brief Bulk delete messages from a channel. The callback function is called when the message has been edited - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @note If any message provided older than 2 weeks or any duplicate message ID, it will fail. - * - * @see dpp::cluster::message_delete_bulk - * @see https://discord.com/developers/docs/resources/channel#bulk-delete-messages - * @param message_ids List of message IDs to delete (at least 2 and at most 100 message IDs) - * @param channel_id Channel to delete from - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation message_delete_bulk_sync(const std::vector &message_ids, snowflake channel_id); - -/** - * @brief Delete a message from a channel. The callback function is called when the message has been edited - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see dpp::cluster::message_delete - * @see https://discord.com/developers/docs/resources/channel#delete-message - * @param message_id Message ID to delete - * @param channel_id Channel to delete from - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation message_delete_sync(snowflake message_id, snowflake channel_id); - -/** - * @brief Edit a message on a channel. The callback function is called when the message has been edited - * - * @see dpp::cluster::message_edit - * @see https://discord.com/developers/docs/resources/channel#edit-message - * @param m Message to edit - * @return message returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -message message_edit_sync(const struct message &m); - -/** - * @brief Get a message - * - * @see dpp::cluster::message_get - * @see https://discord.com/developers/docs/resources/channel#get-channel-message - * @param message_id Message ID - * @param channel_id Channel ID - * @return message returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -message message_get_sync(snowflake message_id, snowflake channel_id); - -/** - * @brief Pin a message - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::message_pin - * @see https://discord.com/developers/docs/resources/channel#pin-message - * @param channel_id Channel id to pin message on - * @param message_id Message id to pin message on - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation message_pin_sync(snowflake channel_id, snowflake message_id); - -/** - * @brief Get multiple messages. - * - * This function will attempt to fetch as many messages as possible using multiple API calls if needed. - * - * @see dpp::cluster::messages_get - * @see https://discord.com/developers/docs/resources/channel#get-channel-messages - * @param channel_id Channel ID to retrieve messages for - * @param around Messages should be retrieved around this ID if this is set to non-zero - * @param before Messages before this ID should be retrieved if this is set to non-zero - * @param after Messages after this ID should be retrieved if this is set to non-zero - * @param limit This number of messages maximum should be returned, up to a maximum of 100. - * @return message_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -message_map messages_get_sync(snowflake channel_id, snowflake around, snowflake before, snowflake after, uint64_t limit); - -/** - * @brief Unpin a message - * @see dpp::cluster::message_unpin - * @see https://discord.com/developers/docs/resources/channel#unpin-message - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param channel_id Channel id to unpin message on - * @param message_id Message id to unpin message on - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation message_unpin_sync(snowflake channel_id, snowflake message_id); - -/** - * @brief Get a channel's pins - * @see dpp::cluster::channel_pins_get - * @see https://discord.com/developers/docs/resources/channel#get-pinned-messages - * @param channel_id Channel ID to get pins for - * @return message_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -message_map channel_pins_get_sync(snowflake channel_id); - -/** - * @brief Create a role on a guild - * - * Create a new role for the guild. Requires the `MANAGE_ROLES` permission. Returns the new role object on success. - * Fires a `Guild Role Create` Gateway event. - * - * @see dpp::cluster::role_create - * @see https://discord.com/developers/docs/resources/guild#create-guild-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param r Role to create (guild ID is encapsulated in the role object) - * @return role returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -role role_create_sync(const class role &r); - -/** - * @brief Delete a role - * - * Requires the `MANAGE_ROLES` permission. Fires a `Guild Role Delete` Gateway event. - * - * @see dpp::cluster::role_delete - * @see https://discord.com/developers/docs/resources/guild#delete-guild-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to delete the role on - * @param role_id Role ID to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation role_delete_sync(snowflake guild_id, snowflake role_id); - -/** - * @brief Edit a role on a guild - * - * Requires the `MANAGE_ROLES` permission. Returns the updated role on success. Fires a `Guild Role Update` Gateway event. - * - * @see dpp::cluster::role_edit - * @see https://discord.com/developers/docs/resources/guild#modify-guild-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param r Role to edit - * @return role returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -role role_edit_sync(const class role &r); - -/** - * @brief Edit multiple role's position in a guild. Returns a list of all roles of the guild on success. - * - * Modify the positions of a set of role objects for the guild. Requires the `MANAGE_ROLES` permission. - * Fires multiple `Guild Role Update` Gateway events. - * - * @see dpp::cluster::roles_edit_position - * @see https://discord.com/developers/docs/resources/guild#modify-guild-role-positions - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to change the roles position on - * @param roles Vector of roles to change the positions of - * @return role_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -role_map roles_edit_position_sync(snowflake guild_id, const std::vector &roles); - -/** - * @brief Get a role for a guild - * - * @see dpp::cluster::roles_get - * @see https://discord.com/developers/docs/resources/guild#get-guild-roles - * @param guild_id Guild ID to get role for - * @return role_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -role_map roles_get_sync(snowflake guild_id); - -/** - * @brief Get user application role connection - * - * @see dpp::cluster::user_application_role_connection_get - * @see https://discord.com/developers/docs/resources/user#get-user-application-role-connection - * @param application_id The application ID - * @return application_role_connection returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -application_role_connection user_application_role_connection_get_sync(snowflake application_id); - -/** - * @brief Update user application role connection - * - * @see dpp::cluster::user_application_role_connection_update - * @see https://discord.com/developers/docs/resources/user#update-user-application-role-connection - * @param application_id The application ID - * @param connection The application role connection to update - * @return application_role_connection returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -application_role_connection user_application_role_connection_update_sync(snowflake application_id, const application_role_connection &connection); - -/** - * @brief Get all scheduled events for a guild - * @see dpp::cluster::guild_events_get - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#list-scheduled-events-for-guild - * @param guild_id Guild to get events for - * @return scheduled_event_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -scheduled_event_map guild_events_get_sync(snowflake guild_id); - -/** - * @brief Create a scheduled event on a guild - * - * @see dpp::cluster::guild_event_create - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#create-guild-scheduled-event - * @param event Event to create (guild ID must be populated) - * @return scheduled_event returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -scheduled_event guild_event_create_sync(const scheduled_event& event); - -/** - * @brief Delete a scheduled event from a guild - * - * @see dpp::cluster::guild_event_delete - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#delete-guild-scheduled-event - * @param event_id Event ID to delete - * @param guild_id Guild ID of event to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_event_delete_sync(snowflake event_id, snowflake guild_id); - -/** - * @brief Edit/modify a scheduled event on a guild - * - * @see dpp::cluster::guild_event_edit - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#modify-guild-scheduled-event - * @param event Event to create (event ID and guild ID must be populated) - * @return scheduled_event returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -scheduled_event guild_event_edit_sync(const scheduled_event& event); - -/** - * @brief Get a scheduled event for a guild - * - * @see dpp::cluster::guild_event_get - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#get-guild-scheduled-event - * @param guild_id Guild to get event for - * @param event_id Event ID to get - * @return scheduled_event returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -scheduled_event guild_event_get_sync(snowflake guild_id, snowflake event_id); - - -stage_instance stage_instance_create_sync(const stage_instance& si); - -/** - * @brief Get the stage instance associated with the channel id, if it exists. - * @see dpp::cluster::stage_instance_get - * @see https://discord.com/developers/docs/resources/stage-instance#get-stage-instance - * @param channel_id ID of the associated channel - * @return stage_instance returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -stage_instance stage_instance_get_sync(const snowflake channel_id); - - -stage_instance stage_instance_edit_sync(const stage_instance& si); - -/** - * @brief Delete a stage instance. - * @see dpp::cluster::stage_instance_delete - * @see https://discord.com/developers/docs/resources/stage-instance#delete-stage-instance - * @param channel_id ID of the associated channel - * @return confirmation returned object on completion - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation stage_instance_delete_sync(const snowflake channel_id); - -/** - * @brief Create a sticker in a guild - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::guild_sticker_create - * @see https://discord.com/developers/docs/resources/sticker#create-guild-sticker - * @param s Sticker to create. Must have its guild ID set. - * @return sticker returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -sticker guild_sticker_create_sync(sticker &s); - -/** - * @brief Delete a sticker from a guild - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::guild_sticker_delete - * @see https://discord.com/developers/docs/resources/sticker#delete-guild-sticker - * @param sticker_id sticker ID to delete - * @param guild_id guild ID to delete from - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_sticker_delete_sync(snowflake sticker_id, snowflake guild_id); - -/** - * @brief Get a guild sticker - * @see dpp::cluster::guild_sticker_get - * @see https://discord.com/developers/docs/resources/sticker#get-guild-sticker - * @param id Id of sticker to get. - * @param guild_id Guild ID of the guild where the sticker is - * @return sticker returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -sticker guild_sticker_get_sync(snowflake id, snowflake guild_id); - -/** - * @brief Modify a sticker in a guild - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::guild_sticker_modify - * @see https://discord.com/developers/docs/resources/sticker#modify-guild-sticker - * @param s Sticker to modify. Must have its guild ID and sticker ID set. - * @return sticker returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -sticker guild_sticker_modify_sync(sticker &s); - -/** - * @brief Get all guild stickers - * @see dpp::cluster::guild_stickers_get - * @see https://discord.com/developers/docs/resources/sticker#get-guild-stickers - * @param guild_id Guild ID of the guild where the sticker is - * @return sticker_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -sticker_map guild_stickers_get_sync(snowflake guild_id); - -/** - * @brief Get a nitro sticker - * @see dpp::cluster::nitro_sticker_get - * @see https://discord.com/developers/docs/resources/sticker#get-sticker - * @param id Id of sticker to get. - * @return sticker returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -sticker nitro_sticker_get_sync(snowflake id); - -/** - * @brief Get sticker packs - * @see dpp::cluster::sticker_packs_get - * @see https://discord.com/developers/docs/resources/sticker#list-nitro-sticker-packs - * @return sticker_pack_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -sticker_pack_map sticker_packs_get_sync(); - -/** - * @brief Create a new guild based on a template. - * @note This endpoint can be used only by bots in less than 10 guilds. - * @see dpp::cluster::guild_create_from_template - * @see https://discord.com/developers/docs/resources/guild-template#create-guild-from-guild-template - * @param code Template code to create guild from - * @param name Guild name to create - * @return guild returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild guild_create_from_template_sync(const std::string &code, const std::string &name); - -/** - * @brief Creates a template for the guild - * - * @see dpp::cluster::guild_template_create - * @see https://discord.com/developers/docs/resources/guild-template#create-guild-template - * @param guild_id Guild to create template from - * @param name Template name to create - * @param description Description of template to create - * @return dtemplate returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -dtemplate guild_template_create_sync(snowflake guild_id, const std::string &name, const std::string &description); - -/** - * @brief Deletes the template - * - * @see dpp::cluster::guild_template_delete - * @see https://discord.com/developers/docs/resources/guild-template#delete-guild-template - * @param guild_id Guild ID of template to delete - * @param code Template code to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_template_delete_sync(snowflake guild_id, const std::string &code); - -/** - * @brief Modifies the template's metadata. - * - * @see dpp::cluster::guild_template_modify - * @see https://discord.com/developers/docs/resources/guild-template#modify-guild-template - * @param guild_id Guild ID of template to modify - * @param code Template code to modify - * @param name New name of template - * @param description New description of template - * @return dtemplate returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -dtemplate guild_template_modify_sync(snowflake guild_id, const std::string &code, const std::string &name, const std::string &description); - -/** - * @brief Get guild templates - * - * @see dpp::cluster::guild_templates_get - * @see https://discord.com/developers/docs/resources/guild-template#get-guild-templates - * @param guild_id Guild ID to get templates for - * @return dtemplate_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -dtemplate_map guild_templates_get_sync(snowflake guild_id); - -/** - * @brief Syncs the template to the guild's current state. - * - * @see dpp::cluster::guild_template_sync - * @see https://discord.com/developers/docs/resources/guild-template#sync-guild-template - * @param guild_id Guild to synchronise template for - * @param code Code of template to synchronise - * @return dtemplate returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -dtemplate guild_template_sync_sync(snowflake guild_id, const std::string &code); - -/** - * @brief Get a template - * @see dpp::cluster::template_get - * @see https://discord.com/developers/docs/resources/guild-template#get-guild-template - * @param code Template code - * @return dtemplate returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -dtemplate template_get_sync(const std::string &code); - -/** - * @brief Join a thread - * @see dpp::cluster::current_user_join_thread - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread ID to join - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation current_user_join_thread_sync(snowflake thread_id); - -/** - * @brief Leave a thread - * @see dpp::cluster::current_user_leave_thread - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread ID to leave - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation current_user_leave_thread_sync(snowflake thread_id); - -/** - * @brief Get active threads in a guild (Sorted by ID in descending order) - * @see dpp::cluster::threads_get_active - * @see https://discord.com/developers/docs/topics/threads - * @param guild_id Guild to get active threads for - * @return thread_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -thread_map threads_get_active_sync(snowflake guild_id); - -/** - * @brief Get private archived threads in a channel which current user has joined (Sorted by ID in descending order) - * @see dpp::cluster::threads_get_joined_private_archived - * @see https://discord.com/developers/docs/topics/threads - * @param channel_id Channel to get public archived threads for - * @param before_id Get threads before this id - * @param limit Number of threads to get - * @return thread_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -thread_map threads_get_joined_private_archived_sync(snowflake channel_id, snowflake before_id, uint16_t limit); - -/** - * @brief Get private archived threads in a channel (Sorted by archive_timestamp in descending order) - * @see dpp::cluster::threads_get_private_archived - * @see https://discord.com/developers/docs/topics/threads - * @param channel_id Channel to get public archived threads for - * @param before_timestamp Get threads before this timestamp - * @param limit Number of threads to get - * @return thread_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -thread_map threads_get_private_archived_sync(snowflake channel_id, time_t before_timestamp, uint16_t limit); - -/** - * @brief Get public archived threads in a channel (Sorted by archive_timestamp in descending order) - * @see dpp::cluster::threads_get_public_archived - * @see https://discord.com/developers/docs/topics/threads - * @param channel_id Channel to get public archived threads for - * @param before_timestamp Get threads before this timestamp - * @param limit Number of threads to get - * @return thread_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -thread_map threads_get_public_archived_sync(snowflake channel_id, time_t before_timestamp, uint16_t limit); - -/** - * @brief Get a thread member - * @see dpp::cluster::thread_member_get - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread to get member for - * @param user_id ID of the user to get - * @return thread_member returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -thread_member thread_member_get_sync(const snowflake thread_id, const snowflake user_id); - -/** - * @brief Get members of a thread - * @see dpp::cluster::thread_members_get - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread to get members for - * @return thread_member_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -thread_member_map thread_members_get_sync(snowflake thread_id); - -/** - * @brief Create a thread in forum channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see dpp::cluster::thread_create_in_forum - * @see https://discord.com/developers/docs/resources/channel#start-thread-in-forum-channel - * @param thread_name Name of the forum thread - * @param channel_id Forum channel in which thread to create - * @param msg The message to start the thread with - * @param auto_archive_duration Duration to automatically archive the thread after recent activity - * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected - * @param applied_tags List of IDs of forum tags (dpp::forum_tag) to apply to this thread - * @return thread returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -thread thread_create_in_forum_sync(const std::string& thread_name, snowflake channel_id, const message& msg, auto_archive_duration_t auto_archive_duration, uint16_t rate_limit_per_user, std::vector applied_tags = {}); - -/** - * @brief Create a thread - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see dpp::cluster::thread_create - * @see https://discord.com/developers/docs/resources/guild#create-guild-channel - * @param thread_name Name of the thread - * @param channel_id Channel in which thread to create - * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) - * @param thread_type Type of thread - CHANNEL_PUBLIC_THREAD, CHANNEL_ANNOUNCEMENT_THREAD, CHANNEL_PRIVATE_THREAD - * @param invitable whether non-moderators can add other non-moderators to a thread; only available when creating a private thread - * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected - * @return thread returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -thread thread_create_sync(const std::string& thread_name, snowflake channel_id, uint16_t auto_archive_duration, channel_type thread_type, bool invitable, uint16_t rate_limit_per_user); - -/** - * @brief Create a thread with a message (Discord: ID of a thread is same as message ID) - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::thread_create_with_message - * @see https://discord.com/developers/docs/topics/threads - * @param thread_name Name of the thread - * @param channel_id Channel in which thread to create - * @param message_id message to start thread with - * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) - * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected - * @return thread returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -thread thread_create_with_message_sync(const std::string& thread_name, snowflake channel_id, snowflake message_id, uint16_t auto_archive_duration, uint16_t rate_limit_per_user); - -/** - * @brief Add a member to a thread - * @see dpp::cluster::thread_member_add - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread ID to add to - * @param user_id Member ID to add - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation thread_member_add_sync(snowflake thread_id, snowflake user_id); - -/** - * @brief Remove a member from a thread - * @see dpp::cluster::thread_member_remove - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread ID to remove from - * @param user_id Member ID to remove - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation thread_member_remove_sync(snowflake thread_id, snowflake user_id); - -/** - * @brief Edit current (bot) user - * - * Modifies the current member in a guild. Returns the updated guild_member object on success. - * Fires a `Guild Member Update` Gateway event. - * @see dpp::cluster::current_user_edit - * @see https://discord.com/developers/docs/resources/user#modify-current-user - * @param nickname Nickname to set - * @param image_blob Avatar data to upload (NOTE: Very heavily rate limited!) - * @param type Type of image for avatar - * @return user returned object on completion - * @throw dpp::exception Image data is larger than the maximum size of 256 kilobytes - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -user current_user_edit_sync(const std::string &nickname, const std::string& image_blob = "", const image_type type = i_png); - -/** - * @brief Get current (bot) application - * - * @see dpp::cluster::current_application_get - * @see https://discord.com/developers/docs/topics/oauth2#get-current-bot-application-information - * @return application returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -application current_application_get_sync(); - -/** - * @brief Get current (bot) user - * - * @see dpp::cluster::current_user_get - * @see https://discord.com/developers/docs/resources/user#get-current-user - * @return user_identified returned object on completion - * @note The user_identified object is a subclass of dpp::user which contains further details if you have the oauth2 identify or email scopes. - * If you do not have these scopes, these fields are empty. You can safely convert a user_identified to user with `dynamic_cast`. - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -user_identified current_user_get_sync(); - -/** - * @brief Set the bot's voice state on a stage channel - * - * **Caveats** - * - * There are currently several caveats for this endpoint: - * - * - `channel_id` must currently point to a stage channel. - * - current user must already have joined `channel_id`. - * - You must have the `MUTE_MEMBERS` permission to unsuppress yourself. You can always suppress yourself. - * - You must have the `REQUEST_TO_SPEAK` permission to request to speak. You can always clear your own request to speak. - * - You are able to set `request_to_speak_timestamp` to any present or future time. - * - * @see dpp::cluster::current_user_set_voice_state - * @see https://discord.com/developers/docs/resources/guild#modify-current-user-voice-state - * @param guild_id Guild to set voice state on - * @param channel_id Stage channel to set voice state on - * @return confirmation returned object on completion - * @param suppress True if the user's audio should be suppressed, false if it should not - * @param request_to_speak_timestamp The time at which we requested to speak, or 0 to clear the request. The time set here must be the current time or in the future. - * @throw std::logic_exception You attempted to set a request_to_speak_timestamp in the past which is not the value of 0. - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation current_user_set_voice_state_sync(snowflake guild_id, snowflake channel_id, bool suppress = false, time_t request_to_speak_timestamp = 0); - -/** - * @brief Set a user's voice state on a stage channel - * - * **Caveats** - * - * There are currently several caveats for this endpoint: - * - * - `channel_id` must currently point to a stage channel. - * - User must already have joined `channel_id`. - * - You must have the `MUTE_MEMBERS` permission. (Since suppression is the only thing that is available currently) - * - When unsuppressed, non-bot users will have their `request_to_speak_timestamp` set to the current time. Bot users will not. - * - When suppressed, the user will have their `request_to_speak_timestamp` removed. - * - * @see dpp::cluster::user_set_voice_state - * @see https://discord.com/developers/docs/resources/guild#modify-user-voice-state - * @param user_id The user to set the voice state of - * @param guild_id Guild to set voice state on - * @param channel_id Stage channel to set voice state on - * @return confirmation returned object on completion - * @param suppress True if the user's audio should be suppressed, false if it should not - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation user_set_voice_state_sync(snowflake user_id, snowflake guild_id, snowflake channel_id, bool suppress = false); - -/** - * @brief Get current user's connections (linked accounts, e.g. steam, xbox). - * This call requires the oauth2 `connections` scope and cannot be executed - * against a bot token. - * @see dpp::cluster::current_user_connections_get - * @see https://discord.com/developers/docs/resources/user#get-user-connections - * @return connection_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -connection_map current_user_connections_get_sync(); - -/** - * @brief Get current (bot) user guilds - * @see dpp::cluster::current_user_get_guilds - * @see https://discord.com/developers/docs/resources/user#get-current-user-guilds - * @return guild_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild_map current_user_get_guilds_sync(); - -/** - * @brief Leave a guild - * @see dpp::cluster::current_user_leave_guild - * @see https://discord.com/developers/docs/resources/user#leave-guild - * @param guild_id Guild ID to leave - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation current_user_leave_guild_sync(snowflake guild_id); - -/** - * @brief Get a user by id - * - * @see dpp::cluster::user_get - * @see https://discord.com/developers/docs/resources/user#get-user - * @param user_id User ID to retrieve - * @return user_identified returned object on completion - * @note The user_identified object is a subclass of dpp::user which contains further details if you have the oauth2 identify or email scopes. - * If you do not have these scopes, these fields are empty. You can safely convert a user_identified to user with `dynamic_cast`. - * @note unless you want something special from `dpp::user_identified` or you've turned off caching, you have no need to call this. - * Call `dpp::find_user` instead that looks up the user in the cache rather than a REST call. - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -user_identified user_get_sync(snowflake user_id); - -/** - * @brief Get all voice regions - * @see dpp::cluster::get_voice_regions - * @see https://discord.com/developers/docs/resources/voice#list-voice-regions - * @return voiceregion_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -voiceregion_map get_voice_regions_sync(); - -/** - * @brief Get guild voice regions. - * - * Voice regions per guild are somewhat deprecated in preference of per-channel voice regions. - * Returns a list of voice region objects for the guild. Unlike the similar /voice route, this returns VIP servers when - * the guild is VIP-enabled. - * - * @see dpp::cluster::guild_get_voice_regions - * @see https://discord.com/developers/docs/resources/guild#get-guild-voice-regions - * @param guild_id Guild ID to get voice regions for - * @return voiceregion_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -voiceregion_map guild_get_voice_regions_sync(snowflake guild_id); - -/** - * @brief Create a webhook - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::create_webhook - * @see https://discord.com/developers/docs/resources/webhook#create-webhook - * @param w Webhook to create - * @return webhook returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -webhook create_webhook_sync(const class webhook &w); - -/** - * @brief Delete a webhook - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::delete_webhook - * @see https://discord.com/developers/docs/resources/webhook#delete-webhook - * @param webhook_id Webhook ID to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation delete_webhook_sync(snowflake webhook_id); - -/** - * @brief Delete webhook message - * - * @see dpp::cluster::delete_webhook_message - * @see https://discord.com/developers/docs/resources/webhook#delete-webhook-message - * @param wh Webhook to delete message for - * @param message_id Message ID to delete - * @param thread_id ID of the thread the message is in - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation delete_webhook_message_sync(const class webhook &wh, snowflake message_id, snowflake thread_id = 0); - -/** - * @brief Delete webhook with token - * @see dpp::cluster::delete_webhook_with_token - * @see https://discord.com/developers/docs/resources/webhook#delete-webhook-with-token - * @param webhook_id Webhook ID to delete - * @param token Token of webhook to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation delete_webhook_with_token_sync(snowflake webhook_id, const std::string &token); - -/** - * @brief Edit webhook - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::edit_webhook - * @see https://discord.com/developers/docs/resources/webhook#modify-webhook - * @param wh Webhook to edit - * @return webhook returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -webhook edit_webhook_sync(const class webhook& wh); - -/** - * @brief Edit webhook message - * - * When the content field is edited, the mentions array in the message object will be reconstructed from scratch based on - * the new content. The allowed_mentions field of the edit request controls how this happens. If there is no explicit - * allowed_mentions in the edit request, the content will be parsed with default allowances, that is, without regard to - * whether or not an allowed_mentions was present in the request that originally created the message. - * - * @see dpp::cluster::edit_webhook_message - * @see https://discord.com/developers/docs/resources/webhook#edit-webhook-message - * @note the attachments array must contain all attachments that should be present after edit, including retained and new attachments provided in the request body. - * @param wh Webhook to edit message for - * @param m New message - * @param thread_id ID of the thread the message is in - * @return message returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -message edit_webhook_message_sync(const class webhook &wh, const struct message &m, snowflake thread_id = 0); - -/** - * @brief Edit webhook with token (token is encapsulated in the webhook object) - * @see dpp::cluster::edit_webhook_with_token - * @see https://discord.com/developers/docs/resources/webhook#modify-webhook-with-token - * @param wh Webhook to edit (should include token) - * @return webhook returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -webhook edit_webhook_with_token_sync(const class webhook& wh); - -/** - * @brief Execute webhook - * - * @see dpp::cluster::execute_webhook - * @see https://discord.com/developers/docs/resources/webhook#execute-webhook - * @param wh Webhook to execute - * @param m Message to send - * @param wait waits for server confirmation of message send before response, and returns the created message body - * @param thread_id Send a message to the specified thread within a webhook's channel. The thread will automatically be unarchived - * @param thread_name Name of thread to create (requires the webhook channel to be a forum channel) - * @return message returned object on completion - * @note If the webhook channel is a forum channel, you must provide either `thread_id` or `thread_name`. If `thread_id` is provided, the message will send in that thread. If `thread_name` is provided, a thread with that name will be created in the forum channel. - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -message execute_webhook_sync(const class webhook &wh, const struct message &m, bool wait = false, snowflake thread_id = 0, const std::string& thread_name = ""); - -/** - * @brief Get channel webhooks - * @see dpp::cluster::get_channel_webhooks - * @see https://discord.com/developers/docs/resources/webhook#get-guild-webhooks - * @param channel_id Channel ID to get webhooks for - * @return webhook_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -webhook_map get_channel_webhooks_sync(snowflake channel_id); - -/** - * @brief Get guild webhooks - * @see dpp::cluster::get_guild_webhooks - * @see https://discord.com/developers/docs/resources/webhook#get-guild-webhooks - * @param guild_id Guild ID to get webhooks for - * @return webhook_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -webhook_map get_guild_webhooks_sync(snowflake guild_id); - -/** - * @brief Get webhook - * @see dpp::cluster::get_webhook - * @see https://discord.com/developers/docs/resources/webhook#get-webhook - * @param webhook_id Webhook ID to get - * @return webhook returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -webhook get_webhook_sync(snowflake webhook_id); - -/** - * @brief Get webhook message - * - * @see dpp::cluster::get_webhook_message - * @see https://discord.com/developers/docs/resources/webhook#get-webhook-message - * @param wh Webhook to get the original message for - * @param message_id The message ID - * @param thread_id ID of the thread the message is in - * @return message returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -message get_webhook_message_sync(const class webhook &wh, snowflake message_id, snowflake thread_id = 0); - -/** - * @brief Get webhook using token - * @see dpp::cluster::get_webhook_with_token - * @see https://discord.com/developers/docs/resources/webhook#get-webhook-with-token - * @param webhook_id Webhook ID to retrieve - * @param token Token of webhook - * @return webhook returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -webhook get_webhook_with_token_sync(snowflake webhook_id, const std::string &token); - - -/* End of auto-generated definitions */ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2022 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + + +/* Auto @generated by buildtools/make_sync_struct.php. + * + * DO NOT EDIT BY HAND! + * + * To re-generate this header file re-run the script! + */ +/** + * @brief Create/overwrite global slash commands. + * Any existing global slash commands will be deleted and replaced with these. + * + * @see dpp::cluster::global_bulk_command_create + * @see https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-global-application-commands + * @param commands Vector of slash commands to create/update. + * overwriting existing commands that are registered globally for this application. Updates will be available in all guilds after 1 hour. + * Commands that do not already exist will count toward daily application command create limits. + * @return slashcommand_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +slashcommand_map global_bulk_command_create_sync(const std::vector &commands); + +/** + * @brief Create a global slash command (a bot can have a maximum of 100 of these). + * + * @see dpp::cluster::global_command_create + * @see https://discord.com/developers/docs/interactions/application-commands#create-global-application-command + * @param s Slash command to create + * @return slashcommand returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +slashcommand global_command_create_sync(const slashcommand &s); + +/** + * @brief Get a global slash command + * + * @see dpp::cluster::global_command_get + * @see https://discord.com/developers/docs/interactions/application-commands#get-global-application-command + * @param id The ID of the slash command + * @return slashcommand returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +slashcommand global_command_get_sync(snowflake id); + +/** + * @brief Delete a global slash command (a bot can have a maximum of 100 of these) + * + * @see dpp::cluster::global_command_delete + * @see https://discord.com/developers/docs/interactions/application-commands#delete-global-application-command + * @param id Slash command to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation global_command_delete_sync(snowflake id); + +/** + * @brief Edit a global slash command (a bot can have a maximum of 100 of these) + * + * @see dpp::cluster::global_command_edit + * @see https://discord.com/developers/docs/interactions/application-commands#edit-global-application-command + * @param s Slash command to change + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation global_command_edit_sync(const slashcommand &s); + +/** + * @brief Get the application's global slash commands + * + * @see dpp::cluster::global_commands_get + * @see https://discord.com/developers/docs/interactions/application-commands#get-global-application-commands + * @return slashcommand_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +slashcommand_map global_commands_get_sync(); + +/** + * @brief Create/overwrite guild slash commands. + * Any existing guild slash commands on this guild will be deleted and replaced with these. + * + * @see dpp::cluster::guild_bulk_command_create + * @see https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-guild-application-commands + * @param commands Vector of slash commands to create/update. + * New guild commands will be available in the guild immediately. If the command did not already exist, it will count toward daily application command create limits. + * @param guild_id Guild ID to create/update the slash commands in + * @return slashcommand_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +slashcommand_map guild_bulk_command_create_sync(const std::vector &commands, snowflake guild_id); + +/** + * @brief Get all slash command permissions of a guild + * + * @see dpp::cluster::guild_commands_get_permissions + * @see https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions + * @param guild_id Guild ID to get the slash commands permissions for + * @return guild_command_permissions_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild_command_permissions_map guild_commands_get_permissions_sync(snowflake guild_id); + +/** + * @brief Edit/Overwrite the permissions of all existing slash commands in a guild + * + * @note You can only add up to 10 permission overwrites for a command + * + * @see dpp::cluster::guild_bulk_command_edit_permissions + * @see https://discord.com/developers/docs/interactions/application-commands#batch-edit-application-command-permissions + * @warning The endpoint will overwrite all existing permissions for all commands of the application in a guild, including slash commands, user commands, and message commands. Meaning that if you forgot to pass a slash command, the permissions of it might be removed. + * @param commands A vector of slash commands to edit/overwrite the permissions for + * @param guild_id Guild ID to edit permissions of the slash commands in + * @return guild_command_permissions_map returned object on completion + * @deprecated This has been disabled with updates to Permissions v2. You can use guild_command_edit_permissions instead + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild_command_permissions_map guild_bulk_command_edit_permissions_sync(const std::vector &commands, snowflake guild_id); + +/** + * @brief Create a slash command local to a guild + * + * @see dpp::cluster::guild_command_create + * @see https://discord.com/developers/docs/interactions/application-commands#create-guild-application-command + * @note Creating a command with the same name as an existing command for your application will overwrite the old command. + * @param s Slash command to create + * @param guild_id Guild ID to create the slash command in + * @return slashcommand returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +slashcommand guild_command_create_sync(const slashcommand &s, snowflake guild_id); + +/** + * @brief Delete a slash command local to a guild + * + * @see dpp::cluster::guild_command_delete + * @see https://discord.com/developers/docs/interactions/application-commands#delete-guild-application-command + * @param id Slash command to delete + * @param guild_id Guild ID to delete the slash command in + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_command_delete_sync(snowflake id, snowflake guild_id); + +/** + * @brief Edit slash command permissions of a guild + * + * @see dpp::cluster::guild_command_edit_permissions + * @see https://discord.com/developers/docs/interactions/application-commands#edit-application-command-permissions + * @note You can only add up to 10 permission overwrites for a command + * @param s Slash command to edit the permissions for + * @param guild_id Guild ID to edit the slash command in + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_command_edit_permissions_sync(const slashcommand &s, snowflake guild_id); + +/** + * @brief Get a slash command of a guild + * + * @see dpp::cluster::guild_command_get + * @see https://discord.com/developers/docs/interactions/application-commands#get-guild-application-command + * @note The returned slash commands will not have permissions set, you need to use a permissions getter e.g. dpp::guild_commands_get_permissions to get the guild command permissions + * @param id The ID of the slash command + * @param guild_id Guild ID to get the slash command from + * @return slashcommand returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +slashcommand guild_command_get_sync(snowflake id, snowflake guild_id); + +/** + * @brief Get the permissions for a slash command of a guild + * + * @see dpp::cluster::guild_command_get_permissions + * @see https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions + * @param id The ID of the slash command to get the permissions for + * @param guild_id Guild ID to get the permissions of + * @return guild_command_permissions returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild_command_permissions guild_command_get_permissions_sync(snowflake id, snowflake guild_id); + +/** + * @brief Edit a slash command local to a guild + * + * @see dpp::cluster::guild_command_edit + * @see https://discord.com/developers/docs/interactions/application-commands#edit-guild-application-command + * @param s Slash command to edit + * @param guild_id Guild ID to edit the slash command in + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_command_edit_sync(const slashcommand &s, snowflake guild_id); + +/** + * @brief Get the application's slash commands for a guild + * + * @see dpp::cluster::guild_commands_get + * @see https://discord.com/developers/docs/interactions/application-commands#get-guild-application-commands + * @note The returned slash commands will not have permissions set, you need to use a permissions getter e.g. dpp::guild_commands_get_permissions to get the guild command permissions + * @param guild_id Guild ID to get the slash commands for + * @return slashcommand_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +slashcommand_map guild_commands_get_sync(snowflake guild_id); + +/** + * @brief Respond to a slash command + * + * @see dpp::cluster::interaction_response_create + * @see https://discord.com/developers/docs/interactions/receiving-and-responding#create-interaction-response + * @param interaction_id Interaction id to respond to + * @param token Token for the interaction webhook + * @param r Response to send + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation interaction_response_create_sync(snowflake interaction_id, const std::string &token, const interaction_response &r); + +/** + * @brief Edit response to a slash command + * + * @see dpp::cluster::interaction_response_edit + * @see https://discord.com/developers/docs/interactions/receiving-and-responding#edit-original-interaction-response + * @param token Token for the interaction webhook + * @param m Message to send + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation interaction_response_edit_sync(const std::string &token, const message &m); + +/** + * @brief Create a followup message to a slash command + * + * @param token Token for the interaction webhook + * @param m followup message to create + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation interaction_followup_create_sync(const std::string &token, const message &m); + +/** + * @brief Edit original followup message to a slash command + * This is an alias for cluster::interaction_response_edit + * @see dpp::cluster::interaction_followup_edit_original + * @see cluster::interaction_response_edit + * + * @param token Token for the interaction webhook + * @param m message to edit, the ID should be set + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation interaction_followup_edit_original_sync(const std::string &token, const message &m); + +/** + * @brief + * + * @param token Token for the interaction webhook + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation interaction_followup_delete_sync(const std::string &token); + +/** + * @brief Edit followup message to a slash command + * The message ID in the message you pass should be correctly set to that of a followup message you previously sent + * @param token Token for the interaction webhook + * @param m message to edit, the ID should be set + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation interaction_followup_edit_sync(const std::string &token, const message &m); + +/** + * @brief Get the followup message to a slash command + * @param token Token for the interaction webhook + * @param message_id message to retrieve + * @return message returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +message interaction_followup_get_sync(const std::string &token, snowflake message_id); + +/** + * @brief Get all auto moderation rules for a guild + * + * @param guild_id Guild id of the auto moderation rule + * @return automod_rule_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +automod_rule_map automod_rules_get_sync(snowflake guild_id); + +/** + * @brief Get a single auto moderation rule + * + * @param guild_id Guild id of the auto moderation rule + * @param rule_id Rule id to retrieve + * @return automod_rule returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +automod_rule automod_rule_get_sync(snowflake guild_id, snowflake rule_id); + +/** + * @brief Create an auto moderation rule + * + * @param guild_id Guild id of the auto moderation rule + * @param r Auto moderation rule to create + * @return automod_rule returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +automod_rule automod_rule_create_sync(snowflake guild_id, const automod_rule& r); + +/** + * @brief Edit an auto moderation rule + * + * @param guild_id Guild id of the auto moderation rule + * @param r Auto moderation rule to edit. The rule's id must be set. + * @return automod_rule returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +automod_rule automod_rule_edit_sync(snowflake guild_id, const automod_rule& r); + +/** + * @brief Delete an auto moderation rule + * + * @param guild_id Guild id of the auto moderation rule + * @param rule_id Auto moderation rule id to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation automod_rule_delete_sync(snowflake guild_id, snowflake rule_id); + +/** + * @brief Create a channel + * + * Create a new channel object for the guild. Requires the `MANAGE_CHANNELS` permission. If setting permission overwrites, + * only permissions your bot has in the guild can be allowed/denied. Setting `MANAGE_ROLES` permission in channels is only possible + * for guild administrators. Returns the new channel object on success. Fires a `Channel Create Gateway` event. + * + * All parameters to this endpoint are optional excluding `name` + * + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::channel_create + * @see https://discord.com/developers/docs/resources/channel#create-channel + * @param c Channel to create + * @return channel returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +channel channel_create_sync(const class channel &c); + +/** + * @brief Remove a permission from a channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::channel_delete_permission + * @see https://discord.com/developers/docs/resources/channel#delete-channel-permission + * @param c Channel to remove permission from + * @param overwrite_id Overwrite to remove, user or channel ID + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation channel_delete_permission_sync(const class channel &c, snowflake overwrite_id); + +/** + * @brief Delete a channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::channel_delete + * @see https://discord.com/developers/docs/resources/channel#deleteclose-channel + * @param channel_id Channel id to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation channel_delete_sync(snowflake channel_id); + +/** + * @brief Edit multiple channels positions + * + * Modify the positions of a set of channel objects for the guild. + * Requires `MANAGE_CHANNELS` permission. Fires multiple `Channel Update Gateway` events. + * Only channels to be modified are required. + * + * @see dpp::cluster::channel_edit_positions + * @see https://discord.com/developers/docs/resources/guild#modify-guild-channel-positions + * @param c Channel to change the position for + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation channel_edit_positions_sync(const std::vector &c); + +/** + * @brief Edit a channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::channel_edit + * @see https://discord.com/developers/docs/resources/channel#modify-channel + * @param c Channel to edit/update + * @return channel returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +channel channel_edit_sync(const class channel &c); + +/** + * @brief Follow an announcement (news) channel + * @see dpp::cluster::channel_follow_news + * @see https://discord.com/developers/docs/resources/channel#follow-news-channel + * @param c Channel id to follow + * @param target_channel_id Channel to subscribe the channel to + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation channel_follow_news_sync(const class channel &c, snowflake target_channel_id); + +/** + * @brief Get a channel + * + * @see dpp::cluster::channel_get + * @see https://discord.com/developers/docs/resources/channel#get-channel + * @param c Channel ID to retrieve + * @return channel returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +channel channel_get_sync(snowflake c); + +/** + * @brief Create invite for a channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::channel_invite_create + * @see https://discord.com/developers/docs/resources/channel#create-channel-invite + * @param c Channel to create an invite on + * @param i Invite to create + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation channel_invite_create_sync(const class channel &c, const class invite &i); + +/** + * @brief Get invites for a channel + * + * @see dpp::cluster::channel_invites_get + * @see https://discord.com/developers/docs/resources/invite#get-invites + * @param c Channel to get invites for + * @return invite_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +invite_map channel_invites_get_sync(const class channel &c); + +/** + * @brief Get all channels for a guild + * + * @see dpp::cluster::channels_get + * @see https://discord.com/developers/docs/resources/channel#get-channels + * @param guild_id Guild ID to retrieve channels for + * @return channel_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +channel_map channels_get_sync(snowflake guild_id); + +/** + * @brief Create a dm channel + * @see dpp::cluster::create_dm_channel + * @see https://discord.com/developers/docs/resources/user#create-dm + * @param user_id User ID to create DM channel with + * @return channel returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +channel create_dm_channel_sync(snowflake user_id); + +/** + * @brief Get current user DM channels + * + * @return channel_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +channel_map current_user_get_dms_sync(); + +/** + * @brief Create a direct message, also create the channel for the direct message if needed + * + * @see dpp::cluster::direct_message_create + * @see https://discord.com/developers/docs/resources/user#create-dm + * @see dpp::cluster::direct_message_create + * @see https://discord.com/developers/docs/resources/channel#create-message + * @param user_id User ID of user to send message to + * @param m Message object + * @return message returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +message direct_message_create_sync(snowflake user_id, const message &m); + +/** + * @brief Adds a recipient to a Group DM using their access token + * @see dpp::cluster::gdm_add + * @see https://discord.com/developers/docs/resources/channel#group-dm-add-recipient + * @param channel_id Channel id to add group DM recipients to + * @param user_id User ID to add + * @param access_token Access token from OAuth2 + * @param nick Nickname of user to apply to the chat + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation gdm_add_sync(snowflake channel_id, snowflake user_id, const std::string &access_token, const std::string &nick); + +/** + * @brief Removes a recipient from a Group DM + * @see dpp::cluster::gdm_remove + * @see https://discord.com/developers/docs/resources/channel#group-dm-remove-recipient + * @param channel_id Channel ID of group DM + * @param user_id User ID to remove from group DM + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation gdm_remove_sync(snowflake channel_id, snowflake user_id); + +/** + * @brief Create single emoji. + * You must ensure that the emoji passed contained image data using the emoji::load_image() method. + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see dpp::cluster::guild_emoji_create + * @see https://discord.com/developers/docs/resources/emoji#create-guild-emoji + * @param guild_id Guild ID to create emoji om + * @param newemoji Emoji to create + * @return emoji returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +emoji guild_emoji_create_sync(snowflake guild_id, const class emoji& newemoji); + +/** + * @brief Delete a guild emoji + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see dpp::cluster::guild_emoji_delete + * @see https://discord.com/developers/docs/resources/emoji#delete-guild-emoji + * @param guild_id Guild ID to delete emoji on + * @param emoji_id Emoji ID to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_emoji_delete_sync(snowflake guild_id, snowflake emoji_id); + +/** + * @brief Edit a single emoji. + * + * You must ensure that the emoji passed contained image data using the emoji::load_image() method. + * @see dpp::cluster::guild_emoji_edit + * @see https://discord.com/developers/docs/resources/emoji#get-guild-emoji + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to edit emoji on + * @param newemoji Emoji to edit + * @return emoji returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +emoji guild_emoji_edit_sync(snowflake guild_id, const class emoji& newemoji); + +/** + * @brief Get a single emoji + * + * @see dpp::cluster::guild_emoji_get + * @see https://discord.com/developers/docs/resources/emoji#get-guild-emoji + * @param guild_id Guild ID to get emoji for + * @param emoji_id Emoji ID to get + * @return emoji returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +emoji guild_emoji_get_sync(snowflake guild_id, snowflake emoji_id); + +/** + * @brief Get all emojis for a guild + * + * @see dpp::cluster::guild_emojis_get + * @see https://discord.com/developers/docs/resources/emoji#get-guild-emojis + * @param guild_id Guild ID to get emojis for + * @return emoji_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +emoji_map guild_emojis_get_sync(snowflake guild_id); + +/** + * @brief Get the gateway information for the bot using the token + * @see dpp::cluster::get_gateway_bot + * @see https://discord.com/developers/docs/topics/gateway#get-gateway-bot + * @return gateway returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +gateway get_gateway_bot_sync(); + +/** + * @brief Modify current member + * + * Modifies the current member in a guild. + * Fires a `Guild Member Update` Gateway event. + * + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::guild_current_member_edit + * @see https://discord.com/developers/docs/resources/guild#modify-current-member + * @param guild_id Guild ID to change on + * @param nickname New nickname, or empty string to clear nickname + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_current_member_edit_sync(snowflake guild_id, const std::string &nickname); + +/** + * @brief Get the audit log for a guild + * + * @see dpp::cluster::guild_auditlog_get + * @see https://discord.com/developers/docs/resources/audit-log#get-guild-audit-log + * @param guild_id Guild to get the audit log of + * @param user_id Entries from a specific user ID. Set this to `0` will fetch any user + * @param action_type Entries for a specific dpp::audit_type. Set this to `0` will fetch any type + * @param before Entries that preceded a specific audit log entry ID. Used for paginating + * @param limit Maximum number of entries (between 1-100) to return + * @return auditlog returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +auditlog guild_auditlog_get_sync(snowflake guild_id, snowflake user_id, uint32_t action_type, snowflake before, uint32_t limit); + +/** + * @brief Add guild ban + * + * Create a guild ban, and optionally delete previous messages sent by the banned user. + * Requires the `BAN_MEMBERS` permission. Fires a `Guild Ban Add` Gateway event. + * @see dpp::cluster::guild_ban_add + * @see https://discord.com/developers/docs/resources/guild#create-guild-ban + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to add ban to + * @param user_id User ID to ban + * @param delete_message_seconds How many seconds to delete messages for, between 0 and 604800 (7 days). Defaults to 0 + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_ban_add_sync(snowflake guild_id, snowflake user_id, uint32_t delete_message_seconds = 0); + +/** + * @brief Delete guild ban + * + * Remove the ban for a user. Requires the `BAN_MEMBERS` permissions. + * Fires a Guild Ban Remove Gateway event. + * @see dpp::cluster::guild_ban_delete + * @see https://discord.com/developers/docs/resources/guild#remove-guild-ban + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild to delete ban from + * @param user_id User ID to delete ban for + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_ban_delete_sync(snowflake guild_id, snowflake user_id); + +/** + * @brief Create a guild + * + * Create a new guild. Returns a guild object on success. `Fires a Guild Create Gateway` event. + * + * When using the roles parameter, the first member of the array is used to change properties of the guild's everyone role. + * If you are trying to bootstrap a guild with additional roles, keep this in mind. The required id field within each role object is an + * integer placeholder, and will be replaced by the API upon consumption. Its purpose is to allow you to overwrite a role's permissions + * in a channel when also passing in channels with the channels array. + * When using the channels parameter, the position field is ignored, and none of the default channels are created. The id field within + * each channel object may be set to an integer placeholder, and will be replaced by the API upon consumption. Its purpose is to + * allow you to create `GUILD_CATEGORY` channels by setting the `parent_id` field on any children to the category's id field. + * Category channels must be listed before any children. + * + * @see dpp::cluster::guild_create + * @see https://discord.com/developers/docs/resources/guild#create-guild + * @note The region field is deprecated and is replaced by channel.rtc_region. This endpoint can be used only by bots in less than 10 guilds. + * @param g Guild to create + * @return guild returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild guild_create_sync(const class guild &g); + +/** + * @brief Delete a guild + * + * Delete a guild permanently. User must be owner. Fires a `Guild Delete Gateway` event. + * + * @see dpp::cluster::guild_delete + * @see https://discord.com/developers/docs/resources/guild#delete-guild + * @param guild_id Guild ID to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_delete_sync(snowflake guild_id); + +/** + * @brief Delete guild integration + * + * Delete the attached integration object for the guild. Deletes any associated webhooks and kicks the associated bot if there is one. + * Requires the `MANAGE_GUILD` permission. Fires a Guild Integrations Update Gateway event. + * + * @see dpp::cluster::guild_delete_integration + * @see https://discord.com/developers/docs/resources/guild#delete-guild-integration + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to delete integration for + * @param integration_id Integration ID to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_delete_integration_sync(snowflake guild_id, snowflake integration_id); + +/** + * @brief Edit a guild + * + * Modify a guild's settings. Requires the `MANAGE_GUILD` permission. Returns the updated guild object on success. + * Fires a `Guild Update Gateway` event. + * + * @see dpp::cluster::guild_edit + * @see https://discord.com/developers/docs/resources/guild#modify-guild + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param g Guild to edit + * @return guild returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild guild_edit_sync(const class guild &g); + +/** + * @brief Edit guild widget + * + * Requires the `MANAGE_GUILD` permission. + * + * @see dpp::cluster::guild_edit_widget + * @see https://discord.com/developers/docs/resources/guild#modify-guild-widget + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to edit widget for + * @param gw New guild widget information + * @return guild_widget returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild_widget guild_edit_widget_sync(snowflake guild_id, const class guild_widget &gw); + +/** + * @brief Get single guild ban + * + * Requires the `BAN_MEMBERS` permission. + * @see dpp::cluster::guild_get_ban + * @see https://discord.com/developers/docs/resources/guild#get-guild-ban + * @param guild_id Guild ID to get ban for + * @param user_id User ID of ban to retrieve + * @return ban returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +ban guild_get_ban_sync(snowflake guild_id, snowflake user_id); + +/** + * @brief Get guild ban list + * + * Requires the `BAN_MEMBERS` permission. + * @see dpp::cluster::guild_get_bans + * @see https://discord.com/developers/docs/resources/guild#get-guild-bans + * @note Provide a user ID to `before` and `after` for pagination. Users will always be returned in ascending order by the user ID. If both before and after are provided, only before is respected. + * @param guild_id Guild ID to get bans for + * @param before If non-zero, all bans for user ids before this user id will be returned up to the limit + * @param after if non-zero, all bans for user ids after this user id will be returned up to the limit + * @param limit the maximum number of bans to retrieve in this call up to a maximum of 1000 + * @return ban_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +ban_map guild_get_bans_sync(snowflake guild_id, snowflake before, snowflake after, snowflake limit); + + +guild guild_get_sync(snowflake guild_id); + +/** + * @brief Get guild integrations + * + * Requires the `MANAGE_GUILD` permission. + * + * @see dpp::cluster::guild_get_integrations + * @see https://discord.com/developers/docs/resources/guild#get-guild-integrations + * @param guild_id Guild ID to get integrations for + * @return integration_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +integration_map guild_get_integrations_sync(snowflake guild_id); + + +guild guild_get_preview_sync(snowflake guild_id); + +/** + * @brief Get guild vanity url, if enabled + * + * Returns a partial dpp::invite object for guilds with that feature enabled. Requires the `MANAGE_GUILD` permission. code will be null if a vanity url for the guild is not set. + * @see dpp::cluster::guild_get_vanity + * @see https://discord.com/developers/docs/resources/guild#get-guild-vanity-url + * @param guild_id Guild to get vanity URL for + * @return invite returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +invite guild_get_vanity_sync(snowflake guild_id); + +/** + * @brief Get guild widget + * + * Requires the `MANAGE_GUILD` permission. + * + * @see dpp::cluster::guild_get_widget + * @see https://discord.com/developers/docs/resources/guild#get-guild-widget + * @param guild_id Guild ID to get widget for + * @return guild_widget returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild_widget guild_get_widget_sync(snowflake guild_id); + +/** + * @brief Modify guild integration + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see dpp::cluster::guild_modify_integration + * @see https://discord.com/developers/docs/resources/guild#modify-guild-integration + * @param guild_id Guild ID to modify integration for + * @param i Integration to modify + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_modify_integration_sync(snowflake guild_id, const class integration &i); + +/** + * @brief Get prune counts + * + * Returns a prune object indicating the number of members that would be removed in a prune operation. Requires the `KICK_MEMBERS` + * permission. By default, prune will not remove users with roles. You can optionally include specific roles in your prune by providing the + * include_roles parameter. Any inactive user that has a subset of the provided role(s) will be counted in the prune and users with additional + * roles will not. + * + * @see dpp::cluster::guild_get_prune_counts + * @see https://discord.com/developers/docs/resources/guild#get-guild-prune-count + * @param guild_id Guild ID to count for pruning + * @param pruneinfo Pruning info + * @return prune returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +prune guild_get_prune_counts_sync(snowflake guild_id, const struct prune& pruneinfo); + +/** + * @brief Begin guild prune + * + * Begin a prune operation. Requires the `KICK_MEMBERS` permission. Returns a prune object indicating the number of members + * that were removed in the prune operation. For large guilds it's recommended to set the `compute_prune_count` option to false, forcing + * 'pruned' to 0. Fires multiple `Guild Member Remove` Gateway events. + * By default, prune will not remove users with roles. You can optionally include specific roles in your prune by providing the `include_roles` + * parameter. Any inactive user that has a subset of the provided role(s) will be included in the prune and users with additional roles will not. + * + * @see dpp::cluster::guild_begin_prune + * @see https://discord.com/developers/docs/resources/guild#begin-guild-prune + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to prune + * @param pruneinfo Pruning info + * @return prune returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +prune guild_begin_prune_sync(snowflake guild_id, const struct prune& pruneinfo); + +/** + * @brief Change current user nickname + * + * Modifies the nickname of the current user in a guild. + * Fires a `Guild Member Update` Gateway event. + * + * @deprecated Deprecated in favor of Modify Current Member. Will be replaced by dpp::cluster::guild_current_member_edit + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::guild_set_nickname + * @see https://discord.com/developers/docs/resources/guild#modify-current-user-nick + * @param guild_id Guild ID to change nickname on + * @param nickname New nickname, or empty string to clear nickname + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_set_nickname_sync(snowflake guild_id, const std::string &nickname); + +/** + * @brief Sync guild integration + * + * @see dpp::cluster::guild_sync_integration + * @see https://discord.com/developers/docs/resources/guild#sync-guild-integration + * @param guild_id Guild ID to sync integration on + * @param integration_id Integration ID to synchronise + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_sync_integration_sync(snowflake guild_id, snowflake integration_id); + +/** + * @brief Add guild member. Needs a specific oauth2 scope, from which you get the access_token. + * + * Adds a user to the guild, provided you have a valid oauth2 access token for the user with the guilds.join scope. + * Returns the guild_member, which is defaulted if the user is already a member of the guild. Fires a `Guild Member Add` Gateway event. + * + * For guilds with Membership Screening enabled, this endpoint will default to adding new members as pending in the guild member object. + * Members that are pending will have to complete membership screening before they become full members that can talk. + * + * @note All parameters to this endpoint except for access_token are optional. + * The bot must be a member of the guild with `CREATE_INSTANT_INVITE` permission. + * @see dpp::cluster::guild_add_member + * @see https://discord.com/developers/docs/resources/guild#add-guild-member + * @param gm Guild member to add + * @param access_token Access token from Oauth2 scope + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_add_member_sync(const guild_member& gm, const std::string &access_token); + +/** + * @brief Edit the properties of an existing guild member + * + * Modify attributes of a guild member. Returns the guild_member. Fires a `Guild Member Update` Gateway event. + * To remove a timeout, set the `communication_disabled_until` to a non-zero time in the past, e.g. 1. + * When moving members to channels, the API user must have permissions to both connect to the channel and have the `MOVE_MEMBERS` permission. + * For moving and disconnecting users from voice, use dpp::cluster::guild_member_move. + * @see dpp::cluster::guild_edit_member + * @see https://discord.com/developers/docs/resources/guild#modify-guild-member + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param gm Guild member to edit + * @return guild_member returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild_member guild_edit_member_sync(const guild_member& gm); + +/** + * @brief Get a guild member + * @see dpp::cluster::guild_get_member + * @see https://discord.com/developers/docs/resources/guild#get-guild-member + * @param guild_id Guild ID to get member for + * @param user_id User ID of member to get + * @return guild_member returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild_member guild_get_member_sync(snowflake guild_id, snowflake user_id); + +/** + * @brief Get all guild members + * + * @note This endpoint is restricted according to whether the `GUILD_MEMBERS` Privileged Intent is enabled for your application. + * @see dpp::cluster::guild_get_members + * @see https://discord.com/developers/docs/resources/guild#get-guild-members + * @param guild_id Guild ID to get all members for + * @param limit max number of members to return (1-1000) + * @param after the highest user id in the previous page + * @return guild_member_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild_member_map guild_get_members_sync(snowflake guild_id, uint16_t limit, snowflake after); + +/** + * @brief Add role to guild member + * + * Adds a role to a guild member. Requires the `MANAGE_ROLES` permission. + * Fires a `Guild Member Update` Gateway event. + * @see dpp::cluster::guild_member_add_role + * @see https://discord.com/developers/docs/resources/guild#add-guild-member-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to add a role to + * @param user_id User ID to add role to + * @param role_id Role ID to add to the user + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_member_add_role_sync(snowflake guild_id, snowflake user_id, snowflake role_id); + +/** + * @brief Remove (kick) a guild member + * + * Remove a member from a guild. Requires `KICK_MEMBERS` permission. + * Fires a `Guild Member Remove` Gateway event. + * @see dpp::cluster::guild_member_delete + * @see https://discord.com/developers/docs/resources/guild#remove-guild-member + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @deprecated Replaced by dpp::cluster::guild_member_kick + * @param guild_id Guild ID to kick member from + * @param user_id User ID to kick + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_member_delete_sync(snowflake guild_id, snowflake user_id); + +/** + * @brief Remove (kick) a guild member + * + * Remove a member from a guild. Requires `KICK_MEMBERS` permission. + * Fires a `Guild Member Remove` Gateway event. + * @see dpp::cluster::guild_member_kick + * @see https://discord.com/developers/docs/resources/guild#remove-guild-member + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to kick member from + * @param user_id User ID to kick + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_member_kick_sync(snowflake guild_id, snowflake user_id); + +/** + * @brief Set the timeout of a guild member + * + * Fires a `Guild Member Update` Gateway event. + * @see dpp::cluster::guild_member_timeout + * @see https://discord.com/developers/docs/resources/guild#modify-guild-member + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to timeout the member in + * @param user_id User ID to set the timeout for + * @param communication_disabled_until The timestamp when the user's timeout will expire (up to 28 days in the future). Set to 0 to remove the timeout + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_member_timeout_sync(snowflake guild_id, snowflake user_id, time_t communication_disabled_until); + +/** + * @brief Remove role from guild member + * + * Removes a role from a guild member. Requires the `MANAGE_ROLES` permission. + * Fires a `Guild Member Update` Gateway event. + * @see dpp::cluster::guild_member_delete_role + * @see https://discord.com/developers/docs/resources/guild#remove-guild-member-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to remove role from user on + * @param user_id User ID to remove role from + * @param role_id Role to remove + * @return confirmation returned object on completion + * @deprecated Use dpp::cluster::guild_member_remove_role instead + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_member_delete_role_sync(snowflake guild_id, snowflake user_id, snowflake role_id); + +/** + * @brief Remove role from guild member + * + * Removes a role from a guild member. Requires the `MANAGE_ROLES` permission. + * Fires a `Guild Member Update` Gateway event. + * @see dpp::cluster::guild_member_remove_role + * @see https://discord.com/developers/docs/resources/guild#remove-guild-member-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to remove role from user on + * @param user_id User ID to remove role from + * @param role_id Role to remove + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_member_remove_role_sync(snowflake guild_id, snowflake user_id, snowflake role_id); + +/** + * @brief Moves the guild member to a other voice channel, if member is connected to one. + * Set the `channel_id` to `0` to disconnect the user. + * + * Fires a `Guild Member Update` Gateway event. + * @note When moving members to channels, the API user __must__ have permissions to both connect to the channel and have the `MOVE_MEMBERS` permission. + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::guild_member_move + * @see https://discord.com/developers/docs/resources/guild#modify-guild-member + * @param channel_id Id of the channel to which the user is used. Set to `0` to disconnect the user + * @param guild_id Guild id to which the user is connected + * @param user_id User id, who should be moved + * @return guild_member returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild_member guild_member_move_sync(const snowflake channel_id, const snowflake guild_id, const snowflake user_id); + +/** + * @brief Search for guild members based on whether their username or nickname starts with the given string. + * + * @note This endpoint is restricted according to whether the `GUILD_MEMBERS` Privileged Intent is enabled for your application. + * @see dpp::cluster::guild_search_members + * @see https://discord.com/developers/docs/resources/guild#search-guild-members + * @param guild_id Guild ID to search in + * @param query Query string to match username(s) and nickname(s) against + * @param limit max number of members to return (1-1000) + * @return guild_member_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild_member_map guild_search_members_sync(snowflake guild_id, const std::string& query, uint16_t limit); + +/** + * @brief Get guild invites + * + * Returns a list of invite objects (with invite metadata) for the guild. Requires the `MANAGE_GUILD` permission. + * + * @see dpp::cluster::guild_get_invites + * @see https://discord.com/developers/docs/resources/guild#get-guild-invites + * @param guild_id Guild ID to get invites for + * @return invite_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +invite_map guild_get_invites_sync(snowflake guild_id); + + +invite invite_delete_sync(const std::string &invitecode); + + +invite invite_get_sync(const std::string &invitecode); + +/** + * @brief Send a message to a channel. The callback function is called when the message has been sent + * + * @see dpp::cluster::message_create + * @see https://discord.com/developers/docs/resources/channel#create-message + * @param m Message to send + * @return message returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +message message_create_sync(const struct message &m); + +/** + * @brief Crosspost a message. The callback function is called when the message has been sent + * + * @see dpp::cluster::message_crosspost + * @see https://discord.com/developers/docs/resources/channel#crosspost-message + * @param message_id Message to crosspost + * @param channel_id Channel ID to crosspost from + * @return message returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +message message_crosspost_sync(snowflake message_id, snowflake channel_id); + +/** + * @brief Bulk delete messages from a channel. The callback function is called when the message has been edited + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @note If any message provided older than 2 weeks or any duplicate message ID, it will fail. + * + * @see dpp::cluster::message_delete_bulk + * @see https://discord.com/developers/docs/resources/channel#bulk-delete-messages + * @param message_ids List of message IDs to delete (at least 2 and at most 100 message IDs) + * @param channel_id Channel to delete from + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation message_delete_bulk_sync(const std::vector &message_ids, snowflake channel_id); + +/** + * @brief Delete a message from a channel. The callback function is called when the message has been edited + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see dpp::cluster::message_delete + * @see https://discord.com/developers/docs/resources/channel#delete-message + * @param message_id Message ID to delete + * @param channel_id Channel to delete from + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation message_delete_sync(snowflake message_id, snowflake channel_id); + +/** + * @brief Edit a message on a channel. The callback function is called when the message has been edited + * + * @see dpp::cluster::message_edit + * @see https://discord.com/developers/docs/resources/channel#edit-message + * @param m Message to edit + * @return message returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +message message_edit_sync(const struct message &m); + +/** + * @brief Get a message + * + * @see dpp::cluster::message_get + * @see https://discord.com/developers/docs/resources/channel#get-channel-message + * @param message_id Message ID + * @param channel_id Channel ID + * @return message returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +message message_get_sync(snowflake message_id, snowflake channel_id); + +/** + * @brief Pin a message + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::message_pin + * @see https://discord.com/developers/docs/resources/channel#pin-message + * @param channel_id Channel id to pin message on + * @param message_id Message id to pin message on + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation message_pin_sync(snowflake channel_id, snowflake message_id); + +/** + * @brief Get multiple messages. + * + * This function will attempt to fetch as many messages as possible using multiple API calls if needed. + * + * @see dpp::cluster::messages_get + * @see https://discord.com/developers/docs/resources/channel#get-channel-messages + * @param channel_id Channel ID to retrieve messages for + * @param around Messages should be retrieved around this ID if this is set to non-zero + * @param before Messages before this ID should be retrieved if this is set to non-zero + * @param after Messages after this ID should be retrieved if this is set to non-zero + * @param limit This number of messages maximum should be returned, up to a maximum of 100. + * @return message_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +message_map messages_get_sync(snowflake channel_id, snowflake around, snowflake before, snowflake after, uint64_t limit); + +/** + * @brief Unpin a message + * @see dpp::cluster::message_unpin + * @see https://discord.com/developers/docs/resources/channel#unpin-message + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param channel_id Channel id to unpin message on + * @param message_id Message id to unpin message on + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation message_unpin_sync(snowflake channel_id, snowflake message_id); + +/** + * @brief Get a channel's pins + * @see dpp::cluster::channel_pins_get + * @see https://discord.com/developers/docs/resources/channel#get-pinned-messages + * @param channel_id Channel ID to get pins for + * @return message_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +message_map channel_pins_get_sync(snowflake channel_id); + +/** + * @brief Create a role on a guild + * + * Create a new role for the guild. Requires the `MANAGE_ROLES` permission. Returns the new role object on success. + * Fires a `Guild Role Create` Gateway event. + * + * @see dpp::cluster::role_create + * @see https://discord.com/developers/docs/resources/guild#create-guild-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param r Role to create (guild ID is encapsulated in the role object) + * @return role returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +role role_create_sync(const class role &r); + +/** + * @brief Delete a role + * + * Requires the `MANAGE_ROLES` permission. Fires a `Guild Role Delete` Gateway event. + * + * @see dpp::cluster::role_delete + * @see https://discord.com/developers/docs/resources/guild#delete-guild-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to delete the role on + * @param role_id Role ID to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation role_delete_sync(snowflake guild_id, snowflake role_id); + +/** + * @brief Edit a role on a guild + * + * Requires the `MANAGE_ROLES` permission. Returns the updated role on success. Fires a `Guild Role Update` Gateway event. + * + * @see dpp::cluster::role_edit + * @see https://discord.com/developers/docs/resources/guild#modify-guild-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param r Role to edit + * @return role returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +role role_edit_sync(const class role &r); + +/** + * @brief Edit multiple role's position in a guild. Returns a list of all roles of the guild on success. + * + * Modify the positions of a set of role objects for the guild. Requires the `MANAGE_ROLES` permission. + * Fires multiple `Guild Role Update` Gateway events. + * + * @see dpp::cluster::roles_edit_position + * @see https://discord.com/developers/docs/resources/guild#modify-guild-role-positions + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to change the roles position on + * @param roles Vector of roles to change the positions of + * @return role_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +role_map roles_edit_position_sync(snowflake guild_id, const std::vector &roles); + +/** + * @brief Get a role for a guild + * + * @see dpp::cluster::roles_get + * @see https://discord.com/developers/docs/resources/guild#get-guild-roles + * @param guild_id Guild ID to get role for + * @return role_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +role_map roles_get_sync(snowflake guild_id); + +/** + * @brief Get user application role connection + * + * @see dpp::cluster::user_application_role_connection_get + * @see https://discord.com/developers/docs/resources/user#get-user-application-role-connection + * @param application_id The application ID + * @return application_role_connection returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +application_role_connection user_application_role_connection_get_sync(snowflake application_id); + +/** + * @brief Update user application role connection + * + * @see dpp::cluster::user_application_role_connection_update + * @see https://discord.com/developers/docs/resources/user#update-user-application-role-connection + * @param application_id The application ID + * @param connection The application role connection to update + * @return application_role_connection returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +application_role_connection user_application_role_connection_update_sync(snowflake application_id, const application_role_connection &connection); + +/** + * @brief Get all scheduled events for a guild + * @see dpp::cluster::guild_events_get + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#list-scheduled-events-for-guild + * @param guild_id Guild to get events for + * @return scheduled_event_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +scheduled_event_map guild_events_get_sync(snowflake guild_id); + +/** + * @brief Create a scheduled event on a guild + * + * @see dpp::cluster::guild_event_create + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#create-guild-scheduled-event + * @param event Event to create (guild ID must be populated) + * @return scheduled_event returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +scheduled_event guild_event_create_sync(const scheduled_event& event); + +/** + * @brief Delete a scheduled event from a guild + * + * @see dpp::cluster::guild_event_delete + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#delete-guild-scheduled-event + * @param event_id Event ID to delete + * @param guild_id Guild ID of event to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_event_delete_sync(snowflake event_id, snowflake guild_id); + +/** + * @brief Edit/modify a scheduled event on a guild + * + * @see dpp::cluster::guild_event_edit + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#modify-guild-scheduled-event + * @param event Event to create (event ID and guild ID must be populated) + * @return scheduled_event returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +scheduled_event guild_event_edit_sync(const scheduled_event& event); + +/** + * @brief Get a scheduled event for a guild + * + * @see dpp::cluster::guild_event_get + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#get-guild-scheduled-event + * @param guild_id Guild to get event for + * @param event_id Event ID to get + * @return scheduled_event returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +scheduled_event guild_event_get_sync(snowflake guild_id, snowflake event_id); + + +stage_instance stage_instance_create_sync(const stage_instance& si); + +/** + * @brief Get the stage instance associated with the channel id, if it exists. + * @see dpp::cluster::stage_instance_get + * @see https://discord.com/developers/docs/resources/stage-instance#get-stage-instance + * @param channel_id ID of the associated channel + * @return stage_instance returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +stage_instance stage_instance_get_sync(const snowflake channel_id); + + +stage_instance stage_instance_edit_sync(const stage_instance& si); + +/** + * @brief Delete a stage instance. + * @see dpp::cluster::stage_instance_delete + * @see https://discord.com/developers/docs/resources/stage-instance#delete-stage-instance + * @param channel_id ID of the associated channel + * @return confirmation returned object on completion + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation stage_instance_delete_sync(const snowflake channel_id); + +/** + * @brief Create a sticker in a guild + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::guild_sticker_create + * @see https://discord.com/developers/docs/resources/sticker#create-guild-sticker + * @param s Sticker to create. Must have its guild ID set. + * @return sticker returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +sticker guild_sticker_create_sync(sticker &s); + +/** + * @brief Delete a sticker from a guild + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::guild_sticker_delete + * @see https://discord.com/developers/docs/resources/sticker#delete-guild-sticker + * @param sticker_id sticker ID to delete + * @param guild_id guild ID to delete from + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_sticker_delete_sync(snowflake sticker_id, snowflake guild_id); + +/** + * @brief Get a guild sticker + * @see dpp::cluster::guild_sticker_get + * @see https://discord.com/developers/docs/resources/sticker#get-guild-sticker + * @param id Id of sticker to get. + * @param guild_id Guild ID of the guild where the sticker is + * @return sticker returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +sticker guild_sticker_get_sync(snowflake id, snowflake guild_id); + +/** + * @brief Modify a sticker in a guild + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::guild_sticker_modify + * @see https://discord.com/developers/docs/resources/sticker#modify-guild-sticker + * @param s Sticker to modify. Must have its guild ID and sticker ID set. + * @return sticker returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +sticker guild_sticker_modify_sync(sticker &s); + +/** + * @brief Get all guild stickers + * @see dpp::cluster::guild_stickers_get + * @see https://discord.com/developers/docs/resources/sticker#get-guild-stickers + * @param guild_id Guild ID of the guild where the sticker is + * @return sticker_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +sticker_map guild_stickers_get_sync(snowflake guild_id); + +/** + * @brief Get a nitro sticker + * @see dpp::cluster::nitro_sticker_get + * @see https://discord.com/developers/docs/resources/sticker#get-sticker + * @param id Id of sticker to get. + * @return sticker returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +sticker nitro_sticker_get_sync(snowflake id); + +/** + * @brief Get sticker packs + * @see dpp::cluster::sticker_packs_get + * @see https://discord.com/developers/docs/resources/sticker#list-nitro-sticker-packs + * @return sticker_pack_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +sticker_pack_map sticker_packs_get_sync(); + +/** + * @brief Create a new guild based on a template. + * @note This endpoint can be used only by bots in less than 10 guilds. + * @see dpp::cluster::guild_create_from_template + * @see https://discord.com/developers/docs/resources/guild-template#create-guild-from-guild-template + * @param code Template code to create guild from + * @param name Guild name to create + * @return guild returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild guild_create_from_template_sync(const std::string &code, const std::string &name); + +/** + * @brief Creates a template for the guild + * + * @see dpp::cluster::guild_template_create + * @see https://discord.com/developers/docs/resources/guild-template#create-guild-template + * @param guild_id Guild to create template from + * @param name Template name to create + * @param description Description of template to create + * @return dtemplate returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +dtemplate guild_template_create_sync(snowflake guild_id, const std::string &name, const std::string &description); + +/** + * @brief Deletes the template + * + * @see dpp::cluster::guild_template_delete + * @see https://discord.com/developers/docs/resources/guild-template#delete-guild-template + * @param guild_id Guild ID of template to delete + * @param code Template code to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_template_delete_sync(snowflake guild_id, const std::string &code); + +/** + * @brief Modifies the template's metadata. + * + * @see dpp::cluster::guild_template_modify + * @see https://discord.com/developers/docs/resources/guild-template#modify-guild-template + * @param guild_id Guild ID of template to modify + * @param code Template code to modify + * @param name New name of template + * @param description New description of template + * @return dtemplate returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +dtemplate guild_template_modify_sync(snowflake guild_id, const std::string &code, const std::string &name, const std::string &description); + +/** + * @brief Get guild templates + * + * @see dpp::cluster::guild_templates_get + * @see https://discord.com/developers/docs/resources/guild-template#get-guild-templates + * @param guild_id Guild ID to get templates for + * @return dtemplate_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +dtemplate_map guild_templates_get_sync(snowflake guild_id); + +/** + * @brief Syncs the template to the guild's current state. + * + * @see dpp::cluster::guild_template_sync + * @see https://discord.com/developers/docs/resources/guild-template#sync-guild-template + * @param guild_id Guild to synchronise template for + * @param code Code of template to synchronise + * @return dtemplate returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +dtemplate guild_template_sync_sync(snowflake guild_id, const std::string &code); + +/** + * @brief Get a template + * @see dpp::cluster::template_get + * @see https://discord.com/developers/docs/resources/guild-template#get-guild-template + * @param code Template code + * @return dtemplate returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +dtemplate template_get_sync(const std::string &code); + +/** + * @brief Join a thread + * @see dpp::cluster::current_user_join_thread + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread ID to join + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation current_user_join_thread_sync(snowflake thread_id); + +/** + * @brief Leave a thread + * @see dpp::cluster::current_user_leave_thread + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread ID to leave + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation current_user_leave_thread_sync(snowflake thread_id); + +/** + * @brief Get active threads in a guild (Sorted by ID in descending order) + * @see dpp::cluster::threads_get_active + * @see https://discord.com/developers/docs/topics/threads + * @param guild_id Guild to get active threads for + * @return thread_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +thread_map threads_get_active_sync(snowflake guild_id); + +/** + * @brief Get private archived threads in a channel which current user has joined (Sorted by ID in descending order) + * @see dpp::cluster::threads_get_joined_private_archived + * @see https://discord.com/developers/docs/topics/threads + * @param channel_id Channel to get public archived threads for + * @param before_id Get threads before this id + * @param limit Number of threads to get + * @return thread_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +thread_map threads_get_joined_private_archived_sync(snowflake channel_id, snowflake before_id, uint16_t limit); + +/** + * @brief Get private archived threads in a channel (Sorted by archive_timestamp in descending order) + * @see dpp::cluster::threads_get_private_archived + * @see https://discord.com/developers/docs/topics/threads + * @param channel_id Channel to get public archived threads for + * @param before_timestamp Get threads before this timestamp + * @param limit Number of threads to get + * @return thread_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +thread_map threads_get_private_archived_sync(snowflake channel_id, time_t before_timestamp, uint16_t limit); + +/** + * @brief Get public archived threads in a channel (Sorted by archive_timestamp in descending order) + * @see dpp::cluster::threads_get_public_archived + * @see https://discord.com/developers/docs/topics/threads + * @param channel_id Channel to get public archived threads for + * @param before_timestamp Get threads before this timestamp + * @param limit Number of threads to get + * @return thread_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +thread_map threads_get_public_archived_sync(snowflake channel_id, time_t before_timestamp, uint16_t limit); + +/** + * @brief Get a thread member + * @see dpp::cluster::thread_member_get + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread to get member for + * @param user_id ID of the user to get + * @return thread_member returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +thread_member thread_member_get_sync(const snowflake thread_id, const snowflake user_id); + +/** + * @brief Get members of a thread + * @see dpp::cluster::thread_members_get + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread to get members for + * @return thread_member_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +thread_member_map thread_members_get_sync(snowflake thread_id); + +/** + * @brief Create a thread in forum channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see dpp::cluster::thread_create_in_forum + * @see https://discord.com/developers/docs/resources/channel#start-thread-in-forum-channel + * @param thread_name Name of the forum thread + * @param channel_id Forum channel in which thread to create + * @param msg The message to start the thread with + * @param auto_archive_duration Duration to automatically archive the thread after recent activity + * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected + * @param applied_tags List of IDs of forum tags (dpp::forum_tag) to apply to this thread + * @return thread returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +thread thread_create_in_forum_sync(const std::string& thread_name, snowflake channel_id, const message& msg, auto_archive_duration_t auto_archive_duration, uint16_t rate_limit_per_user, std::vector applied_tags = {}); + +/** + * @brief Create a thread + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see dpp::cluster::thread_create + * @see https://discord.com/developers/docs/resources/guild#create-guild-channel + * @param thread_name Name of the thread + * @param channel_id Channel in which thread to create + * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) + * @param thread_type Type of thread - CHANNEL_PUBLIC_THREAD, CHANNEL_ANNOUNCEMENT_THREAD, CHANNEL_PRIVATE_THREAD + * @param invitable whether non-moderators can add other non-moderators to a thread; only available when creating a private thread + * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected + * @return thread returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +thread thread_create_sync(const std::string& thread_name, snowflake channel_id, uint16_t auto_archive_duration, channel_type thread_type, bool invitable, uint16_t rate_limit_per_user); + +/** + * @brief Create a thread with a message (Discord: ID of a thread is same as message ID) + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::thread_create_with_message + * @see https://discord.com/developers/docs/topics/threads + * @param thread_name Name of the thread + * @param channel_id Channel in which thread to create + * @param message_id message to start thread with + * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) + * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected + * @return thread returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +thread thread_create_with_message_sync(const std::string& thread_name, snowflake channel_id, snowflake message_id, uint16_t auto_archive_duration, uint16_t rate_limit_per_user); + +/** + * @brief Add a member to a thread + * @see dpp::cluster::thread_member_add + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread ID to add to + * @param user_id Member ID to add + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation thread_member_add_sync(snowflake thread_id, snowflake user_id); + +/** + * @brief Remove a member from a thread + * @see dpp::cluster::thread_member_remove + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread ID to remove from + * @param user_id Member ID to remove + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation thread_member_remove_sync(snowflake thread_id, snowflake user_id); + +/** + * @brief Edit current (bot) user + * + * Modifies the current member in a guild. Returns the updated guild_member object on success. + * Fires a `Guild Member Update` Gateway event. + * @see dpp::cluster::current_user_edit + * @see https://discord.com/developers/docs/resources/user#modify-current-user + * @param nickname Nickname to set + * @param image_blob Avatar data to upload (NOTE: Very heavily rate limited!) + * @param type Type of image for avatar + * @return user returned object on completion + * @throw dpp::exception Image data is larger than the maximum size of 256 kilobytes + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +user current_user_edit_sync(const std::string &nickname, const std::string& image_blob = "", const image_type type = i_png); + +/** + * @brief Get current (bot) application + * + * @see dpp::cluster::current_application_get + * @see https://discord.com/developers/docs/topics/oauth2#get-current-bot-application-information + * @return application returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +application current_application_get_sync(); + +/** + * @brief Get current (bot) user + * + * @see dpp::cluster::current_user_get + * @see https://discord.com/developers/docs/resources/user#get-current-user + * @return user_identified returned object on completion + * @note The user_identified object is a subclass of dpp::user which contains further details if you have the oauth2 identify or email scopes. + * If you do not have these scopes, these fields are empty. You can safely convert a user_identified to user with `dynamic_cast`. + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +user_identified current_user_get_sync(); + +/** + * @brief Set the bot's voice state on a stage channel + * + * **Caveats** + * + * There are currently several caveats for this endpoint: + * + * - `channel_id` must currently point to a stage channel. + * - current user must already have joined `channel_id`. + * - You must have the `MUTE_MEMBERS` permission to unsuppress yourself. You can always suppress yourself. + * - You must have the `REQUEST_TO_SPEAK` permission to request to speak. You can always clear your own request to speak. + * - You are able to set `request_to_speak_timestamp` to any present or future time. + * + * @see dpp::cluster::current_user_set_voice_state + * @see https://discord.com/developers/docs/resources/guild#modify-current-user-voice-state + * @param guild_id Guild to set voice state on + * @param channel_id Stage channel to set voice state on + * @return confirmation returned object on completion + * @param suppress True if the user's audio should be suppressed, false if it should not + * @param request_to_speak_timestamp The time at which we requested to speak, or 0 to clear the request. The time set here must be the current time or in the future. + * @throw std::logic_exception You attempted to set a request_to_speak_timestamp in the past which is not the value of 0. + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation current_user_set_voice_state_sync(snowflake guild_id, snowflake channel_id, bool suppress = false, time_t request_to_speak_timestamp = 0); + +/** + * @brief Set a user's voice state on a stage channel + * + * **Caveats** + * + * There are currently several caveats for this endpoint: + * + * - `channel_id` must currently point to a stage channel. + * - User must already have joined `channel_id`. + * - You must have the `MUTE_MEMBERS` permission. (Since suppression is the only thing that is available currently) + * - When unsuppressed, non-bot users will have their `request_to_speak_timestamp` set to the current time. Bot users will not. + * - When suppressed, the user will have their `request_to_speak_timestamp` removed. + * + * @see dpp::cluster::user_set_voice_state + * @see https://discord.com/developers/docs/resources/guild#modify-user-voice-state + * @param user_id The user to set the voice state of + * @param guild_id Guild to set voice state on + * @param channel_id Stage channel to set voice state on + * @return confirmation returned object on completion + * @param suppress True if the user's audio should be suppressed, false if it should not + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation user_set_voice_state_sync(snowflake user_id, snowflake guild_id, snowflake channel_id, bool suppress = false); + +/** + * @brief Get current user's connections (linked accounts, e.g. steam, xbox). + * This call requires the oauth2 `connections` scope and cannot be executed + * against a bot token. + * @see dpp::cluster::current_user_connections_get + * @see https://discord.com/developers/docs/resources/user#get-user-connections + * @return connection_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +connection_map current_user_connections_get_sync(); + +/** + * @brief Get current (bot) user guilds + * @see dpp::cluster::current_user_get_guilds + * @see https://discord.com/developers/docs/resources/user#get-current-user-guilds + * @return guild_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild_map current_user_get_guilds_sync(); + +/** + * @brief Leave a guild + * @see dpp::cluster::current_user_leave_guild + * @see https://discord.com/developers/docs/resources/user#leave-guild + * @param guild_id Guild ID to leave + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation current_user_leave_guild_sync(snowflake guild_id); + +/** + * @brief Get a user by id + * + * @see dpp::cluster::user_get + * @see https://discord.com/developers/docs/resources/user#get-user + * @param user_id User ID to retrieve + * @return user_identified returned object on completion + * @note The user_identified object is a subclass of dpp::user which contains further details if you have the oauth2 identify or email scopes. + * If you do not have these scopes, these fields are empty. You can safely convert a user_identified to user with `dynamic_cast`. + * @note unless you want something special from `dpp::user_identified` or you've turned off caching, you have no need to call this. + * Call `dpp::find_user` instead that looks up the user in the cache rather than a REST call. + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +user_identified user_get_sync(snowflake user_id); + +/** + * @brief Get all voice regions + * @see dpp::cluster::get_voice_regions + * @see https://discord.com/developers/docs/resources/voice#list-voice-regions + * @return voiceregion_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +voiceregion_map get_voice_regions_sync(); + +/** + * @brief Get guild voice regions. + * + * Voice regions per guild are somewhat deprecated in preference of per-channel voice regions. + * Returns a list of voice region objects for the guild. Unlike the similar /voice route, this returns VIP servers when + * the guild is VIP-enabled. + * + * @see dpp::cluster::guild_get_voice_regions + * @see https://discord.com/developers/docs/resources/guild#get-guild-voice-regions + * @param guild_id Guild ID to get voice regions for + * @return voiceregion_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +voiceregion_map guild_get_voice_regions_sync(snowflake guild_id); + +/** + * @brief Create a webhook + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::create_webhook + * @see https://discord.com/developers/docs/resources/webhook#create-webhook + * @param w Webhook to create + * @return webhook returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +webhook create_webhook_sync(const class webhook &w); + +/** + * @brief Delete a webhook + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::delete_webhook + * @see https://discord.com/developers/docs/resources/webhook#delete-webhook + * @param webhook_id Webhook ID to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation delete_webhook_sync(snowflake webhook_id); + +/** + * @brief Delete webhook message + * + * @see dpp::cluster::delete_webhook_message + * @see https://discord.com/developers/docs/resources/webhook#delete-webhook-message + * @param wh Webhook to delete message for + * @param message_id Message ID to delete + * @param thread_id ID of the thread the message is in + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation delete_webhook_message_sync(const class webhook &wh, snowflake message_id, snowflake thread_id = 0); + +/** + * @brief Delete webhook with token + * @see dpp::cluster::delete_webhook_with_token + * @see https://discord.com/developers/docs/resources/webhook#delete-webhook-with-token + * @param webhook_id Webhook ID to delete + * @param token Token of webhook to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation delete_webhook_with_token_sync(snowflake webhook_id, const std::string &token); + +/** + * @brief Edit webhook + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::edit_webhook + * @see https://discord.com/developers/docs/resources/webhook#modify-webhook + * @param wh Webhook to edit + * @return webhook returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +webhook edit_webhook_sync(const class webhook& wh); + +/** + * @brief Edit webhook message + * + * When the content field is edited, the mentions array in the message object will be reconstructed from scratch based on + * the new content. The allowed_mentions field of the edit request controls how this happens. If there is no explicit + * allowed_mentions in the edit request, the content will be parsed with default allowances, that is, without regard to + * whether or not an allowed_mentions was present in the request that originally created the message. + * + * @see dpp::cluster::edit_webhook_message + * @see https://discord.com/developers/docs/resources/webhook#edit-webhook-message + * @note the attachments array must contain all attachments that should be present after edit, including retained and new attachments provided in the request body. + * @param wh Webhook to edit message for + * @param m New message + * @param thread_id ID of the thread the message is in + * @return message returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +message edit_webhook_message_sync(const class webhook &wh, const struct message &m, snowflake thread_id = 0); + +/** + * @brief Edit webhook with token (token is encapsulated in the webhook object) + * @see dpp::cluster::edit_webhook_with_token + * @see https://discord.com/developers/docs/resources/webhook#modify-webhook-with-token + * @param wh Webhook to edit (should include token) + * @return webhook returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +webhook edit_webhook_with_token_sync(const class webhook& wh); + +/** + * @brief Execute webhook + * + * @see dpp::cluster::execute_webhook + * @see https://discord.com/developers/docs/resources/webhook#execute-webhook + * @param wh Webhook to execute + * @param m Message to send + * @param wait waits for server confirmation of message send before response, and returns the created message body + * @param thread_id Send a message to the specified thread within a webhook's channel. The thread will automatically be unarchived + * @param thread_name Name of thread to create (requires the webhook channel to be a forum channel) + * @return message returned object on completion + * @note If the webhook channel is a forum channel, you must provide either `thread_id` or `thread_name`. If `thread_id` is provided, the message will send in that thread. If `thread_name` is provided, a thread with that name will be created in the forum channel. + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +message execute_webhook_sync(const class webhook &wh, const struct message &m, bool wait = false, snowflake thread_id = 0, const std::string& thread_name = ""); + +/** + * @brief Get channel webhooks + * @see dpp::cluster::get_channel_webhooks + * @see https://discord.com/developers/docs/resources/webhook#get-guild-webhooks + * @param channel_id Channel ID to get webhooks for + * @return webhook_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +webhook_map get_channel_webhooks_sync(snowflake channel_id); + +/** + * @brief Get guild webhooks + * @see dpp::cluster::get_guild_webhooks + * @see https://discord.com/developers/docs/resources/webhook#get-guild-webhooks + * @param guild_id Guild ID to get webhooks for + * @return webhook_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +webhook_map get_guild_webhooks_sync(snowflake guild_id); + +/** + * @brief Get webhook + * @see dpp::cluster::get_webhook + * @see https://discord.com/developers/docs/resources/webhook#get-webhook + * @param webhook_id Webhook ID to get + * @return webhook returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +webhook get_webhook_sync(snowflake webhook_id); + +/** + * @brief Get webhook message + * + * @see dpp::cluster::get_webhook_message + * @see https://discord.com/developers/docs/resources/webhook#get-webhook-message + * @param wh Webhook to get the original message for + * @param message_id The message ID + * @param thread_id ID of the thread the message is in + * @return message returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +message get_webhook_message_sync(const class webhook &wh, snowflake message_id, snowflake thread_id = 0); + +/** + * @brief Get webhook using token + * @see dpp::cluster::get_webhook_with_token + * @see https://discord.com/developers/docs/resources/webhook#get-webhook-with-token + * @param webhook_id Webhook ID to retrieve + * @param token Token of webhook + * @return webhook returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +webhook get_webhook_with_token_sync(snowflake webhook_id, const std::string &token); + + +/* End of auto-generated definitions */ diff --git a/3rdParty/dpp/collector.h b/3rdParty/dpp/collector.h index a27d0a2d7a..72ddd89a4e 100644 --- a/3rdParty/dpp/collector.h +++ b/3rdParty/dpp/collector.h @@ -1,435 +1,435 @@ -/* - * Discord erlpack - tidied up for D++, Craig Edwards 2021. - * - * MessagePack system dependencies modified for erlpack. - * - * Copyright (C) 2008-2010 FURUHASHI Sadayuki - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Collects objects from events during a specified time period. - * - * This template must be specialised. There are premade specialisations which you can use - * such as dpp::reaction_collector and dpp::message_collector. For these specialised instances - * all you need to do is derive a simple class from them which implements collector::completed(). - * - * A collector will run for the specified number of seconds, attaching itself to the - * given event. During this time any events pass through the collector and collector::filter(). - * This function can return a pointer to an object to allow a copy of that object to be stored - * to a vector, or it can return nullptr to do nothing with that object. For example a collector - * attached to on_message_create would receive an event with the type message_create_t, and from - * this may decide to extract the message_create_t::msg structure, returning a pointer to it, or - * instead may choose to return a nullptr. - * - * When either the predetermined timeout is reached, or the collector::cancel() method is called, - * or the collector is destroyed, the collector::completed() method is called, which will be - * passed a list of collected objects in the order they were collected. - * - * @tparam T parameter type of the event this collector will monitor - * @tparam C object type this collector will store - */ -template class collector -{ -protected: - /// Owning cluster - class cluster* owner; -private: - /// Timed listener - timed_listener, std::function>* tl; - /// stored list - std::vector stored; - /// Trigger flag - bool triggered; -public: - /** - * @brief Construct a new collector object. - * - * The timer for the collector begins immediately on construction of the object. - * - * @param cl Pointer to cluster which manages this collector - * @param duration Duration in seconds to run the collector for - * @param event Event to attach to, e.g. cluster::on_message_create - */ - collector(class cluster* cl, uint64_t duration, event_router_t & event) : owner(cl), triggered(false) { - std::function f = [this](const T& event) { - const C* v = filter(event); - if (v) { - stored.push_back(*v); - } - }; - tl = new dpp::timed_listener, std::function>(cl, duration, event, f, [this](dpp::timer timer_handle) { - if (!triggered) { - triggered = true; - completed(stored); - } - }); - } - - /** - * @brief You must implement this function to receive the completed list of - * captured objects. - * @param list The list of captured objects in captured order - */ - virtual void completed(const std::vector& list) = 0; - - /** - * @brief Filter the list of elements. - * - * Every time an event is fired on the collector, this method wil be called - * to determine if we should add an object to the list or not. This function - * can then process the `element` value, extract the parts which are to be - * saved to a list (e.g. a dpp::message out of a dpp::message_create_t) and - * return it as the return value. Returning a value of nullptr causes no - * object to be stored. - * - * Here is an example of how to filter messages which have specific text in them. - * This should be used with the specialised type dpp::message_collector - * - * ```cpp - * virtual const dpp::message* filter(const dpp::message_create_t& m) { - * if (m.msg.content.find("something i want") != std::string::npos) { - * return &m.msg; - * } else { - * return nullptr; - * } - * } - * ``` - * - * @param element The event data to filter - * @return const C* Returned object or nullptr - */ - virtual const C* filter(const T& element) = 0; - - /** - * @brief Immediately cancels the collector. - * - * Use this if you have met the conditions for which you are collecting objects - * early, e.g. you were watching for a message containing 'yes' or 'no' and have - * received it before the time is up. - * - * @note Causes calling of the completed() method if it has not yet been called. - */ - virtual void cancel() { - delete tl; - tl = nullptr; - } - - /** - * @brief Destroy the collector object. - * @note Causes calling of the completed() method if it has not yet been called. - */ - virtual ~collector() { - delete tl; - } -}; - -/** - * @brief Represents a reaction. - * Can be filled for use in a collector - */ -class collected_reaction : public managed { -public: - /// Reacting user - user react_user; - /// Reacting guild - guild* react_guild{}; - /// Reacting guild member - guild_member react_member; - /// Reacting channel - channel* react_channel{}; - /// Reacted emoji - emoji react_emoji; -}; - -/** - * @brief Template type for base class of channel collector - */ -typedef dpp::collector channel_collector_t; - -/** - * @brief Template type for base class of thread collector - */ -typedef dpp::collector thread_collector_t; - -/** - * @brief Template type for base class of role collector - */ -typedef dpp::collector role_collector_t; - -/** - * @brief Template type for base class of scheduled event collector - */ -typedef dpp::collector scheduled_event_collector_t; - -/** - * @brief Template type for base class of message collector - */ -typedef dpp::collector message_collector_t; - -/** - * @brief Template type for base class of message reaction collector - */ -typedef dpp::collector reaction_collector_t; - -/** - * @brief Message collector. - * Collects messages during a set timeframe and returns them in a list via the completed() method. - */ -class message_collector : public message_collector_t { -public: - /** - * @brief Construct a new message collector object - * - * @param cl cluster to associate the collector with - * @param duration Duration of time to run the collector for in seconds - */ - message_collector(cluster* cl, uint64_t duration) : message_collector_t::collector(cl, duration, cl->on_message_create) { } - - /** - * @brief Return the completed collection - * - * @param list items collected during the timeframe specified - */ - virtual void completed(const std::vector& list) = 0; - - /** - * @brief Select and filter the items which are to appear in the list - * This is called every time a new event is fired, to filter the event and determine which - * of the items is sent to the list. Returning nullptr excludes the item from the list. - * - * @param element element to filter - * @return Returned item to add to the list, or nullptr to skip adding this element - */ - virtual const dpp::message* filter(const dpp::message_create_t& element) { return &element.msg; } - - /** - * @brief Destroy the message collector object - */ - virtual ~message_collector() = default; -}; - -/** - * @brief Reaction collector. - * Collects message reactions during a set timeframe and returns them in a list via the completed() method. - */ -class reaction_collector : public reaction_collector_t { - snowflake message_id; - collected_reaction react; -public: - /** - * @brief Construct a new reaction collector object - * - * @param cl cluster to associate the collector with - * @param duration Duration of time to run the collector for in seconds - * @param msg_id Optional message ID. If specified, only collects reactions for the given message - */ - reaction_collector(cluster* cl, uint64_t duration, snowflake msg_id = 0) : reaction_collector_t::collector(cl, duration, cl->on_message_reaction_add), message_id(msg_id) { } - - /** - * @brief Return the completed collection - * - * @param list items collected during the timeframe specified - */ - virtual void completed(const std::vector& list) = 0; - - /** - * @brief Select and filter the items which are to appear in the list - * This is called every time a new event is fired, to filter the event and determine which - * of the items is sent to the list. Returning nullptr excludes the item from the list. - * - * @param element element to filter - * @return Returned item to add to the list, or nullptr to skip adding this element - */ - virtual const dpp::collected_reaction* filter(const dpp::message_reaction_add_t& element) { - /* Capture reactions for given message ID only */ - if (message_id.empty() || element.message_id == message_id) { - react.id = element.message_id; - react.react_user = element.reacting_user; - react.react_guild = element.reacting_guild; - react.react_member = element.reacting_member; - react.react_channel = element.reacting_channel; - react.react_emoji = element.reacting_emoji; - return &react; - } else { - return nullptr; - } - } - - /** - * @brief Destroy the reaction collector object - */ - virtual ~reaction_collector() = default; -}; - -/** - * @brief Channel collector. - * Collects channels during a set timeframe and returns them in a list via the completed() method. - */ -class channel_collector : public channel_collector_t { -public: - /** - * @brief Construct a new channel collector object - * - * @param cl cluster to associate the collector with - * @param duration Duration of time to run the collector for in seconds - */ - channel_collector(cluster* cl, uint64_t duration) : channel_collector_t::collector(cl, duration, cl->on_channel_create) { } - - /** - * @brief Return the completed collection - * - * @param list items collected during the timeframe specified - */ - virtual void completed(const std::vector& list) = 0; - - /** - * @brief Select and filter the items which are to appear in the list - * This is called every time a new event is fired, to filter the event and determine which - * of the items is sent to the list. Returning nullptr excludes the item from the list. - * - * @param element element to filter - * @return Returned item to add to the list, or nullptr to skip adding this element - */ - virtual const dpp::channel* filter(const dpp::channel_create_t& element) { return element.created; } - - /** - * @brief Destroy the channel collector object - */ - virtual ~channel_collector() = default; -}; - -/** - * @brief Thread collector. - * Collects threads during a set timeframe and returns them in a list via the completed() method. - */ -class thread_collector : public thread_collector_t { -public: - /** - * @brief Construct a new thread collector object - * - * @param cl cluster to associate the collector with - * @param duration Duration of time to run the collector for in seconds - */ - thread_collector(cluster* cl, uint64_t duration) : thread_collector_t::collector(cl, duration, cl->on_thread_create) { } - - /** - * @brief Return the completed collection - * - * @param list items collected during the timeframe specified - */ - virtual void completed(const std::vector& list) = 0; - - /** - * @brief Select and filter the items which are to appear in the list - * This is called every time a new event is fired, to filter the event and determine which - * of the items is sent to the list. Returning nullptr excludes the item from the list. - * - * @param element element to filter - * @return Returned item to add to the list, or nullptr to skip adding this element - */ - virtual const dpp::thread* filter(const dpp::thread_create_t& element) { return &element.created; } - - /** - * @brief Destroy the thread collector object - */ - virtual ~thread_collector() = default; -}; - -/** - * @brief Role collector. - * Collects guild roles during a set timeframe and returns them in a list via the completed() method. - */ -class role_collector : public role_collector_t { -public: - /** - * @brief Construct a new role collector object - * - * @param cl cluster to associate the collector with - * @param duration Duration of time to run the collector for in seconds - */ - role_collector(cluster* cl, uint64_t duration) : role_collector_t::collector(cl, duration, cl->on_guild_role_create) { } - - /** - * @brief Return the completed collection - * - * @param list items collected during the timeframe specified - */ - virtual void completed(const std::vector& list) = 0; - - /** - * @brief Select and filter the items which are to appear in the list - * This is called every time a new event is fired, to filter the event and determine which - * of the items is sent to the list. Returning nullptr excludes the item from the list. - * - * @param element element to filter - * @return Returned item to add to the list, or nullptr to skip adding this element - */ - virtual const dpp::role* filter(const dpp::guild_role_create_t& element) { return element.created; } - - /** - * @brief Destroy the role collector object - */ - virtual ~role_collector() = default; -}; - -/** - * @brief Scheduled event collector. - * Collects messages during a set timeframe and returns them in a list via the completed() method. - */ -class scheduled_event_collector : public scheduled_event_collector_t { -public: - /** - * @brief Construct a new scheduled event collector object - * - * @param cl cluster to associate the collector with - * @param duration Duration of time to run the collector for in seconds - */ - scheduled_event_collector(cluster* cl, uint64_t duration) : scheduled_event_collector_t::collector(cl, duration, cl->on_guild_scheduled_event_create) { } - - /** - * @brief Return the completed collection - * - * @param list items collected during the timeframe specified - */ - virtual void completed(const std::vector& list) = 0; - - /** - * @brief Select and filter the items which are to appear in the list - * This is called every time a new event is fired, to filter the event and determine which - * of the items is sent to the list. Returning nullptr excludes the item from the list. - * - * @param element element to filter - * @return Returned item to add to the list, or nullptr to skip adding this element - */ - virtual const dpp::scheduled_event* filter(const dpp::guild_scheduled_event_create_t& element) { return &element.created; } - - /** - * @brief Destroy the scheduled event collector object - */ - virtual ~scheduled_event_collector() = default; -}; - +/* + * Discord erlpack - tidied up for D++, Craig Edwards 2021. + * + * MessagePack system dependencies modified for erlpack. + * + * Copyright (C) 2008-2010 FURUHASHI Sadayuki + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Collects objects from events during a specified time period. + * + * This template must be specialised. There are premade specialisations which you can use + * such as dpp::reaction_collector and dpp::message_collector. For these specialised instances + * all you need to do is derive a simple class from them which implements collector::completed(). + * + * A collector will run for the specified number of seconds, attaching itself to the + * given event. During this time any events pass through the collector and collector::filter(). + * This function can return a pointer to an object to allow a copy of that object to be stored + * to a vector, or it can return nullptr to do nothing with that object. For example a collector + * attached to on_message_create would receive an event with the type message_create_t, and from + * this may decide to extract the message_create_t::msg structure, returning a pointer to it, or + * instead may choose to return a nullptr. + * + * When either the predetermined timeout is reached, or the collector::cancel() method is called, + * or the collector is destroyed, the collector::completed() method is called, which will be + * passed a list of collected objects in the order they were collected. + * + * @tparam T parameter type of the event this collector will monitor + * @tparam C object type this collector will store + */ +template class collector +{ +protected: + /// Owning cluster + class cluster* owner; +private: + /// Timed listener + timed_listener, std::function>* tl; + /// stored list + std::vector stored; + /// Trigger flag + bool triggered; +public: + /** + * @brief Construct a new collector object. + * + * The timer for the collector begins immediately on construction of the object. + * + * @param cl Pointer to cluster which manages this collector + * @param duration Duration in seconds to run the collector for + * @param event Event to attach to, e.g. cluster::on_message_create + */ + collector(class cluster* cl, uint64_t duration, event_router_t & event) : owner(cl), triggered(false) { + std::function f = [this](const T& event) { + const C* v = filter(event); + if (v) { + stored.push_back(*v); + } + }; + tl = new dpp::timed_listener, std::function>(cl, duration, event, f, [this](dpp::timer timer_handle) { + if (!triggered) { + triggered = true; + completed(stored); + } + }); + } + + /** + * @brief You must implement this function to receive the completed list of + * captured objects. + * @param list The list of captured objects in captured order + */ + virtual void completed(const std::vector& list) = 0; + + /** + * @brief Filter the list of elements. + * + * Every time an event is fired on the collector, this method wil be called + * to determine if we should add an object to the list or not. This function + * can then process the `element` value, extract the parts which are to be + * saved to a list (e.g. a dpp::message out of a dpp::message_create_t) and + * return it as the return value. Returning a value of nullptr causes no + * object to be stored. + * + * Here is an example of how to filter messages which have specific text in them. + * This should be used with the specialised type dpp::message_collector + * + * ```cpp + * virtual const dpp::message* filter(const dpp::message_create_t& m) { + * if (m.msg.content.find("something i want") != std::string::npos) { + * return &m.msg; + * } else { + * return nullptr; + * } + * } + * ``` + * + * @param element The event data to filter + * @return const C* Returned object or nullptr + */ + virtual const C* filter(const T& element) = 0; + + /** + * @brief Immediately cancels the collector. + * + * Use this if you have met the conditions for which you are collecting objects + * early, e.g. you were watching for a message containing 'yes' or 'no' and have + * received it before the time is up. + * + * @note Causes calling of the completed() method if it has not yet been called. + */ + virtual void cancel() { + delete tl; + tl = nullptr; + } + + /** + * @brief Destroy the collector object. + * @note Causes calling of the completed() method if it has not yet been called. + */ + virtual ~collector() { + delete tl; + } +}; + +/** + * @brief Represents a reaction. + * Can be filled for use in a collector + */ +class collected_reaction : public managed { +public: + /// Reacting user + user react_user; + /// Reacting guild + guild* react_guild{}; + /// Reacting guild member + guild_member react_member; + /// Reacting channel + channel* react_channel{}; + /// Reacted emoji + emoji react_emoji; +}; + +/** + * @brief Template type for base class of channel collector + */ +typedef dpp::collector channel_collector_t; + +/** + * @brief Template type for base class of thread collector + */ +typedef dpp::collector thread_collector_t; + +/** + * @brief Template type for base class of role collector + */ +typedef dpp::collector role_collector_t; + +/** + * @brief Template type for base class of scheduled event collector + */ +typedef dpp::collector scheduled_event_collector_t; + +/** + * @brief Template type for base class of message collector + */ +typedef dpp::collector message_collector_t; + +/** + * @brief Template type for base class of message reaction collector + */ +typedef dpp::collector reaction_collector_t; + +/** + * @brief Message collector. + * Collects messages during a set timeframe and returns them in a list via the completed() method. + */ +class message_collector : public message_collector_t { +public: + /** + * @brief Construct a new message collector object + * + * @param cl cluster to associate the collector with + * @param duration Duration of time to run the collector for in seconds + */ + message_collector(cluster* cl, uint64_t duration) : message_collector_t::collector(cl, duration, cl->on_message_create) { } + + /** + * @brief Return the completed collection + * + * @param list items collected during the timeframe specified + */ + virtual void completed(const std::vector& list) = 0; + + /** + * @brief Select and filter the items which are to appear in the list + * This is called every time a new event is fired, to filter the event and determine which + * of the items is sent to the list. Returning nullptr excludes the item from the list. + * + * @param element element to filter + * @return Returned item to add to the list, or nullptr to skip adding this element + */ + virtual const dpp::message* filter(const dpp::message_create_t& element) { return &element.msg; } + + /** + * @brief Destroy the message collector object + */ + virtual ~message_collector() = default; +}; + +/** + * @brief Reaction collector. + * Collects message reactions during a set timeframe and returns them in a list via the completed() method. + */ +class reaction_collector : public reaction_collector_t { + snowflake message_id; + collected_reaction react; +public: + /** + * @brief Construct a new reaction collector object + * + * @param cl cluster to associate the collector with + * @param duration Duration of time to run the collector for in seconds + * @param msg_id Optional message ID. If specified, only collects reactions for the given message + */ + reaction_collector(cluster* cl, uint64_t duration, snowflake msg_id = 0) : reaction_collector_t::collector(cl, duration, cl->on_message_reaction_add), message_id(msg_id) { } + + /** + * @brief Return the completed collection + * + * @param list items collected during the timeframe specified + */ + virtual void completed(const std::vector& list) = 0; + + /** + * @brief Select and filter the items which are to appear in the list + * This is called every time a new event is fired, to filter the event and determine which + * of the items is sent to the list. Returning nullptr excludes the item from the list. + * + * @param element element to filter + * @return Returned item to add to the list, or nullptr to skip adding this element + */ + virtual const dpp::collected_reaction* filter(const dpp::message_reaction_add_t& element) { + /* Capture reactions for given message ID only */ + if (message_id.empty() || element.message_id == message_id) { + react.id = element.message_id; + react.react_user = element.reacting_user; + react.react_guild = element.reacting_guild; + react.react_member = element.reacting_member; + react.react_channel = element.reacting_channel; + react.react_emoji = element.reacting_emoji; + return &react; + } else { + return nullptr; + } + } + + /** + * @brief Destroy the reaction collector object + */ + virtual ~reaction_collector() = default; +}; + +/** + * @brief Channel collector. + * Collects channels during a set timeframe and returns them in a list via the completed() method. + */ +class channel_collector : public channel_collector_t { +public: + /** + * @brief Construct a new channel collector object + * + * @param cl cluster to associate the collector with + * @param duration Duration of time to run the collector for in seconds + */ + channel_collector(cluster* cl, uint64_t duration) : channel_collector_t::collector(cl, duration, cl->on_channel_create) { } + + /** + * @brief Return the completed collection + * + * @param list items collected during the timeframe specified + */ + virtual void completed(const std::vector& list) = 0; + + /** + * @brief Select and filter the items which are to appear in the list + * This is called every time a new event is fired, to filter the event and determine which + * of the items is sent to the list. Returning nullptr excludes the item from the list. + * + * @param element element to filter + * @return Returned item to add to the list, or nullptr to skip adding this element + */ + virtual const dpp::channel* filter(const dpp::channel_create_t& element) { return element.created; } + + /** + * @brief Destroy the channel collector object + */ + virtual ~channel_collector() = default; +}; + +/** + * @brief Thread collector. + * Collects threads during a set timeframe and returns them in a list via the completed() method. + */ +class thread_collector : public thread_collector_t { +public: + /** + * @brief Construct a new thread collector object + * + * @param cl cluster to associate the collector with + * @param duration Duration of time to run the collector for in seconds + */ + thread_collector(cluster* cl, uint64_t duration) : thread_collector_t::collector(cl, duration, cl->on_thread_create) { } + + /** + * @brief Return the completed collection + * + * @param list items collected during the timeframe specified + */ + virtual void completed(const std::vector& list) = 0; + + /** + * @brief Select and filter the items which are to appear in the list + * This is called every time a new event is fired, to filter the event and determine which + * of the items is sent to the list. Returning nullptr excludes the item from the list. + * + * @param element element to filter + * @return Returned item to add to the list, or nullptr to skip adding this element + */ + virtual const dpp::thread* filter(const dpp::thread_create_t& element) { return &element.created; } + + /** + * @brief Destroy the thread collector object + */ + virtual ~thread_collector() = default; +}; + +/** + * @brief Role collector. + * Collects guild roles during a set timeframe and returns them in a list via the completed() method. + */ +class role_collector : public role_collector_t { +public: + /** + * @brief Construct a new role collector object + * + * @param cl cluster to associate the collector with + * @param duration Duration of time to run the collector for in seconds + */ + role_collector(cluster* cl, uint64_t duration) : role_collector_t::collector(cl, duration, cl->on_guild_role_create) { } + + /** + * @brief Return the completed collection + * + * @param list items collected during the timeframe specified + */ + virtual void completed(const std::vector& list) = 0; + + /** + * @brief Select and filter the items which are to appear in the list + * This is called every time a new event is fired, to filter the event and determine which + * of the items is sent to the list. Returning nullptr excludes the item from the list. + * + * @param element element to filter + * @return Returned item to add to the list, or nullptr to skip adding this element + */ + virtual const dpp::role* filter(const dpp::guild_role_create_t& element) { return element.created; } + + /** + * @brief Destroy the role collector object + */ + virtual ~role_collector() = default; +}; + +/** + * @brief Scheduled event collector. + * Collects messages during a set timeframe and returns them in a list via the completed() method. + */ +class scheduled_event_collector : public scheduled_event_collector_t { +public: + /** + * @brief Construct a new scheduled event collector object + * + * @param cl cluster to associate the collector with + * @param duration Duration of time to run the collector for in seconds + */ + scheduled_event_collector(cluster* cl, uint64_t duration) : scheduled_event_collector_t::collector(cl, duration, cl->on_guild_scheduled_event_create) { } + + /** + * @brief Return the completed collection + * + * @param list items collected during the timeframe specified + */ + virtual void completed(const std::vector& list) = 0; + + /** + * @brief Select and filter the items which are to appear in the list + * This is called every time a new event is fired, to filter the event and determine which + * of the items is sent to the list. Returning nullptr excludes the item from the list. + * + * @param element element to filter + * @return Returned item to add to the list, or nullptr to skip adding this element + */ + virtual const dpp::scheduled_event* filter(const dpp::guild_scheduled_event_create_t& element) { return &element.created; } + + /** + * @brief Destroy the scheduled event collector object + */ + virtual ~scheduled_event_collector() = default; +}; + }; \ No newline at end of file diff --git a/3rdParty/dpp/colors.h b/3rdParty/dpp/colors.h index 664a11cd33..a57e08a273 100644 --- a/3rdParty/dpp/colors.h +++ b/3rdParty/dpp/colors.h @@ -1,80 +1,80 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once - -#include - - /** - * @brief The main namespace for D++ functions. classes and types - */ -namespace dpp { - /** - * @brief predefined color constants - */ - namespace colors { - const uint32_t - white = 0xFFFFFF, - discord_white = 0xFFFFFE, - light_gray = 0xC0C0C0, - gray = 0x808080, - dark_gray = 0x404040, - black = 0x000000, - discord_black = 0x000001, - red = 0xFF0000, - pink = 0xFFAFAF, - orange = 0xFFC800, - yellow = 0xFFFF00, - green = 0x00FF00, - magenta = 0xFF00FF, - cyan = 0x00FFFF, - blue = 0x0000FF, - light_sea_green = 0x1ABC9C, - medium_sea_green = 0x2ECC71, - summer_sky = 0x3498DB, - deep_lilac = 0x9B59B6, - ruby = 0xE91E63, - moon_yellow = 0xF1C40F, - tahiti_gold = 0xE67E22, - cinnabar = 0xE74C3C, - submarine = 0x95A5A6, - blue_aquamarine = 0x607D8B, - deep_sea = 0x11806A, - sea_green = 0x1F8B4C, - endeavour = 0x206694, - vivid_violet = 0x71368A, - jazzberry_jam = 0xAD1457, - dark_goldenrod = 0xC27C0E, - rust = 0xA84300, - brown = 0x992D22, - gray_chateau = 0x979C9F, - bismark = 0x546E7A, - sti_blue = 0x0E4BEF, - wrx_blue = 0x00247D, - rallyart_crimson = 0xE60012, - lime = 0x00FF00, - forest_green = 0x228B22, - cadmium_green = 0x097969, - aquamarine = 0x7FFFD4, - blue_green = 0x088F8F, - raspberry = 0xE30B5C, - scarlet_red = 0xFF2400; - }; -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once + +#include + + /** + * @brief The main namespace for D++ functions. classes and types + */ +namespace dpp { + /** + * @brief predefined color constants + */ + namespace colors { + const uint32_t + white = 0xFFFFFF, + discord_white = 0xFFFFFE, + light_gray = 0xC0C0C0, + gray = 0x808080, + dark_gray = 0x404040, + black = 0x000000, + discord_black = 0x000001, + red = 0xFF0000, + pink = 0xFFAFAF, + orange = 0xFFC800, + yellow = 0xFFFF00, + green = 0x00FF00, + magenta = 0xFF00FF, + cyan = 0x00FFFF, + blue = 0x0000FF, + light_sea_green = 0x1ABC9C, + medium_sea_green = 0x2ECC71, + summer_sky = 0x3498DB, + deep_lilac = 0x9B59B6, + ruby = 0xE91E63, + moon_yellow = 0xF1C40F, + tahiti_gold = 0xE67E22, + cinnabar = 0xE74C3C, + submarine = 0x95A5A6, + blue_aquamarine = 0x607D8B, + deep_sea = 0x11806A, + sea_green = 0x1F8B4C, + endeavour = 0x206694, + vivid_violet = 0x71368A, + jazzberry_jam = 0xAD1457, + dark_goldenrod = 0xC27C0E, + rust = 0xA84300, + brown = 0x992D22, + gray_chateau = 0x979C9F, + bismark = 0x546E7A, + sti_blue = 0x0E4BEF, + wrx_blue = 0x00247D, + rallyart_crimson = 0xE60012, + lime = 0x00FF00, + forest_green = 0x228B22, + cadmium_green = 0x097969, + aquamarine = 0x7FFFD4, + blue_green = 0x088F8F, + raspberry = 0xE30B5C, + scarlet_red = 0xFF2400; + }; +}; diff --git a/3rdParty/dpp/commandhandler.h b/3rdParty/dpp/commandhandler.h index 1e4b12fa96..1bebc899f5 100644 --- a/3rdParty/dpp/commandhandler.h +++ b/3rdParty/dpp/commandhandler.h @@ -1,392 +1,392 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief dpp::resolved_user contains both a dpp::guild_member and a dpp::user. - * The user can be used to obtain in-depth user details such as if they are nitro, - * and the guild member information to check their roles on a guild etc. - * The Discord API provides both if a parameter is a user ping, - * so we offer both in a combined structure. - */ -struct DPP_EXPORT resolved_user { - /** - * @brief Holds user information - */ - dpp::user user; - /** - * @brief Holds member information - */ - dpp::guild_member member; -}; - -/** - * @brief Represents a received parameter. - * We use variant so that multiple non-related types can be contained within. - */ -typedef std::variant command_parameter; - -/** - * @brief Parameter types when registering a command. - * We don't pass these in when triggering the command in the handler, because it is - * expected the developer added the command so they know what types to expect for each named - * parameter. - */ -enum parameter_type { - pt_string, //!< String value - pt_role, //!< Role object - pt_channel, //!< Channel object - pt_user, //!< User object - pt_integer, //!< 64 bit signed integer - pt_double, //!< double floating point - pt_boolean //!< boolean -}; - -/** - * @brief Details of a command parameter used in registration. - * Note that for non-slash commands optional parameters can only be at the end of - * the list of parameters. - */ -struct DPP_EXPORT param_info { - - /** - * @brief Type of parameter - */ - parameter_type type; - - /** - * @brief True if the parameter is optional. - * For non-slash commands optional parameters may only be on the end of the list. - */ - bool optional; - - /** - * @brief Description of command. Displayed only for slash commands - */ - std::string description; - - /** - * @brief Allowed multiple choice options. - * The key name is the string passed to the command handler - * and the key value is its description displayed to the user. - */ - std::map choices; - - /** - * @brief Construct a new param_info object - * - * @param t Type of parameter - * @param o True if parameter is optional - * @param description The parameter description - * @param opts The options for a multiple choice parameter - */ - param_info(parameter_type t, bool o, const std::string &description, const std::map &opts = {}); -}; - -/** - * @brief Parameter list used during registration. - * Note that use of vector/pair is important here to preserve parameter order, - * as opposed to unordered_map (which doesn't guarantee any order at all) and - * std::map, which reorders keys alphabetically. - */ -typedef std::vector> parameter_registration_t; - -/** - * @brief Parameter list for a called command. - * See dpp::parameter_registration_t for an explanation as to why vector is used. - */ -typedef std::vector> parameter_list_t; - -/** - * @brief Represents the sending source of a command. - * This is passed to any command handler and should be passed back to - * commandhandler::reply(), allowing the reply method to route any replies back - * to the origin, which may be a slash command or a message. Both require different - * response facilities but we want this to be transparent if you use the command - * handler class. - * @deprecated commandhandler and message commands are deprecated and dpp::slashcommand is encouraged as a replacement. - */ -struct DPP_EXPORT command_source { - /** - * @brief Sending guild id - */ - snowflake guild_id; - /** - * @brief Source channel id - */ - snowflake channel_id; - /** - * @brief Command ID of a slash command - */ - snowflake command_id; - /** - * @brief Token for sending a slash command reply - */ - std::string command_token; - /** - * @brief The user who issued the command - */ - user issuer; - - /** - * @brief Copy of the underlying message_create_t event, if it was a message create event - */ - std::optional message_event; - - /** - * @brief Copy of the underlying interaction_create_t event, if it was an interaction create event - */ - std::optional interaction_event; - - /** - * @brief Construct a command_source object from a message_create_t event - */ - command_source(const struct message_create_t& event); - - /** - * @brief Construct a command_source object from an interaction_create_t event - */ - command_source(const struct interaction_create_t& event); -}; - -/** - * @brief The function definition for a command handler. Expects a command name string, - * and a list of command parameters. - * @deprecated commandhandler and message commands are deprecated and dpp::slashcommand is encouraged as a replacement. - */ -typedef std::function command_handler; - -/** - * @brief Represents the details of a command added to the command handler class. - * @deprecated commandhandler and message commands are deprecated and dpp::slashcommand is encouraged as a replacement. - */ -struct DPP_EXPORT command_info_t { - /** - * @brief Function reference for the handler. This is std::function so it can represent - * a class member, a lambda or a raw C function pointer. - */ - command_handler func; - /** - * @brief Parameters requested for the command, with their types - */ - parameter_registration_t parameters; - /** - * @brief Guild ID the command exists on, or 0 to be present on all guilds - */ - snowflake guild_id; -}; - - -/** - * @brief The commandhandler class represents a group of commands, prefixed or slash commands with handling functions. - * - * It can automatically register slash commands, and handle routing of messages and interactions to separated command handler - * functions. - * @deprecated commandhandler and message commands are deprecated and dpp::slashcommand is encouraged as a replacement. - */ -class DPP_EXPORT commandhandler { -private: - /** - * @brief List of guild commands to bulk register - */ - std::map> bulk_registration_list_guild; - /** - * @brief List of global commands to bulk register - */ - std::vector bulk_registration_list_global; -public: - /** - * @brief Commands in the handler - */ - std::unordered_map commands; - - /** - * @brief Valid prefixes - */ - std::vector prefixes; - - /** - * @brief Set to true automatically if one of the prefixes added is "/" - */ - bool slash_commands_enabled; - - /** - * @brief Cluster we are attached to for issuing REST calls - */ - class cluster* owner; - - /** - * @brief Application ID - */ - snowflake app_id; - - /** - * @brief Interaction event handle - */ - event_handle interactions; - - /** - * @brief Message event handle - */ - event_handle messages; - - /** - * @brief Returns true if the string has a known prefix on the start. - * Modifies string to remove prefix if it returns true. - * - * @param str String to check and modify - * @return true string contained a prefix, prefix removed from string - * @return false string did not contain a prefix - */ - bool string_has_prefix(std::string &str); - -public: - - /** - * @brief Construct a new commandhandler object - * - * @param o Owning cluster to attach to - * @param auto_hook_events Set to true to automatically hook the on_slashcommand - * and on_message events. You should not need to set this to false unless you have a specific - * use case, as D++ supports multiple listeners to an event, so will allow the commandhandler - * to hook to your command events without disrupting other uses for the events you may have. - * @param application_id The application id of the bot. If not specified, the class will - * look within the cluster object and use cluster::me::id instead. - */ - commandhandler(class cluster* o, bool auto_hook_events = true, snowflake application_id = 0); - - /** - * @brief Destroy the commandhandler object - */ - ~commandhandler(); - - /** - * @brief Set the application id after construction - * - * @param o Owning cluster to attach to - */ - commandhandler& set_owner(class cluster* o); - - /** - * @brief Add a prefix to the command handler - * - * @param prefix Prefix to be handled by the command handler - * @return commandhandler& reference to self - */ - commandhandler& add_prefix(const std::string &prefix); - - /** - * @brief Add a command to the command handler - * - * @param command Command to be handled. - * Note that if any one of your prefixes is "/" this will attempt to register - * a global command using the API and you will receive notification of this command - * via an interaction event. - * @param handler Handler function - * @param parameters Parameters to use for the command - * @param description The description of the command, shown for slash commands - * @param guild_id The guild ID to restrict the command to. For slash commands causes registration of a guild command as opposed to a global command. - * @return commandhandler& reference to self - * @throw dpp::logic_exception if application ID cannot be determined - */ - commandhandler& add_command(const std::string &command, const parameter_registration_t ¶meters, command_handler handler, const std::string &description = "", snowflake guild_id = 0); - - /** - * @brief Register all slash commands with Discord - * This method must be called at least once if you are using the "/" prefix to mark the - * end of commands being added to the handler. Note that this uses bulk registration and will replace any - * existing slash commands. - * - * Note that if you have previously registered your commands and they have not changed, you do - * not need to call this again. Discord retains a cache of previously added commands. - * - * @return commandhandler& Reference to self for chaining method calls - */ - commandhandler& register_commands(); - - /** - * @brief Route a command from the on_message_create function. - * Call this method from within your on_message_create with the received - * dpp::message object if you have disabled automatic registration of events. - * - * @param event message create event to parse - */ - void route(const struct dpp::message_create_t& event); - - /** - * @brief Route a command from the on_slashcommand function. - * Call this method from your on_slashcommand with the received - * dpp::interaction_create_t object if you have disabled automatic registration of events. - * - * @param event command interaction event to parse - */ - void route(const struct slashcommand_t & event); - - /** - * @brief Reply to a command. - * You should use this method rather than cluster::message_create as - * the way you reply varies between slash commands and message commands. - * Note you should ALWAYS reply. Slash commands will emit an ugly error - * to the user if you do not emit some form of reply within 3 seconds. - * - * @param m message to reply with. - * @param source source of the command - * @param callback User function to execute when the api call completes. - */ - void reply(const dpp::message &m, command_source source, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Reply to a command without a message, causing the discord client - * to display "Bot name is thinking...". - * The "thinking" message will persist for a maximum of 15 minutes. - * This counts as a reply for a slash command. Slash commands will emit an - * ugly error to the user if you do not emit some form of reply within 3 - * seconds. - * - * @param source source of the command - * @param callback User function to execute when the api call completes. - */ - void thinking(command_source source, command_completion_event_t callback = utility::log_error()); - - /* Easter egg */ - void thonk(command_source source, command_completion_event_t callback = utility::log_error()); - -}; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief dpp::resolved_user contains both a dpp::guild_member and a dpp::user. + * The user can be used to obtain in-depth user details such as if they are nitro, + * and the guild member information to check their roles on a guild etc. + * The Discord API provides both if a parameter is a user ping, + * so we offer both in a combined structure. + */ +struct DPP_EXPORT resolved_user { + /** + * @brief Holds user information + */ + dpp::user user; + /** + * @brief Holds member information + */ + dpp::guild_member member; +}; + +/** + * @brief Represents a received parameter. + * We use variant so that multiple non-related types can be contained within. + */ +typedef std::variant command_parameter; + +/** + * @brief Parameter types when registering a command. + * We don't pass these in when triggering the command in the handler, because it is + * expected the developer added the command so they know what types to expect for each named + * parameter. + */ +enum parameter_type { + pt_string, //!< String value + pt_role, //!< Role object + pt_channel, //!< Channel object + pt_user, //!< User object + pt_integer, //!< 64 bit signed integer + pt_double, //!< double floating point + pt_boolean //!< boolean +}; + +/** + * @brief Details of a command parameter used in registration. + * Note that for non-slash commands optional parameters can only be at the end of + * the list of parameters. + */ +struct DPP_EXPORT param_info { + + /** + * @brief Type of parameter + */ + parameter_type type; + + /** + * @brief True if the parameter is optional. + * For non-slash commands optional parameters may only be on the end of the list. + */ + bool optional; + + /** + * @brief Description of command. Displayed only for slash commands + */ + std::string description; + + /** + * @brief Allowed multiple choice options. + * The key name is the string passed to the command handler + * and the key value is its description displayed to the user. + */ + std::map choices; + + /** + * @brief Construct a new param_info object + * + * @param t Type of parameter + * @param o True if parameter is optional + * @param description The parameter description + * @param opts The options for a multiple choice parameter + */ + param_info(parameter_type t, bool o, const std::string &description, const std::map &opts = {}); +}; + +/** + * @brief Parameter list used during registration. + * Note that use of vector/pair is important here to preserve parameter order, + * as opposed to unordered_map (which doesn't guarantee any order at all) and + * std::map, which reorders keys alphabetically. + */ +typedef std::vector> parameter_registration_t; + +/** + * @brief Parameter list for a called command. + * See dpp::parameter_registration_t for an explanation as to why vector is used. + */ +typedef std::vector> parameter_list_t; + +/** + * @brief Represents the sending source of a command. + * This is passed to any command handler and should be passed back to + * commandhandler::reply(), allowing the reply method to route any replies back + * to the origin, which may be a slash command or a message. Both require different + * response facilities but we want this to be transparent if you use the command + * handler class. + * @deprecated commandhandler and message commands are deprecated and dpp::slashcommand is encouraged as a replacement. + */ +struct DPP_EXPORT command_source { + /** + * @brief Sending guild id + */ + snowflake guild_id; + /** + * @brief Source channel id + */ + snowflake channel_id; + /** + * @brief Command ID of a slash command + */ + snowflake command_id; + /** + * @brief Token for sending a slash command reply + */ + std::string command_token; + /** + * @brief The user who issued the command + */ + user issuer; + + /** + * @brief Copy of the underlying message_create_t event, if it was a message create event + */ + std::optional message_event; + + /** + * @brief Copy of the underlying interaction_create_t event, if it was an interaction create event + */ + std::optional interaction_event; + + /** + * @brief Construct a command_source object from a message_create_t event + */ + command_source(const struct message_create_t& event); + + /** + * @brief Construct a command_source object from an interaction_create_t event + */ + command_source(const struct interaction_create_t& event); +}; + +/** + * @brief The function definition for a command handler. Expects a command name string, + * and a list of command parameters. + * @deprecated commandhandler and message commands are deprecated and dpp::slashcommand is encouraged as a replacement. + */ +typedef std::function command_handler; + +/** + * @brief Represents the details of a command added to the command handler class. + * @deprecated commandhandler and message commands are deprecated and dpp::slashcommand is encouraged as a replacement. + */ +struct DPP_EXPORT command_info_t { + /** + * @brief Function reference for the handler. This is std::function so it can represent + * a class member, a lambda or a raw C function pointer. + */ + command_handler func; + /** + * @brief Parameters requested for the command, with their types + */ + parameter_registration_t parameters; + /** + * @brief Guild ID the command exists on, or 0 to be present on all guilds + */ + snowflake guild_id; +}; + + +/** + * @brief The commandhandler class represents a group of commands, prefixed or slash commands with handling functions. + * + * It can automatically register slash commands, and handle routing of messages and interactions to separated command handler + * functions. + * @deprecated commandhandler and message commands are deprecated and dpp::slashcommand is encouraged as a replacement. + */ +class DPP_EXPORT commandhandler { +private: + /** + * @brief List of guild commands to bulk register + */ + std::map> bulk_registration_list_guild; + /** + * @brief List of global commands to bulk register + */ + std::vector bulk_registration_list_global; +public: + /** + * @brief Commands in the handler + */ + std::unordered_map commands; + + /** + * @brief Valid prefixes + */ + std::vector prefixes; + + /** + * @brief Set to true automatically if one of the prefixes added is "/" + */ + bool slash_commands_enabled; + + /** + * @brief Cluster we are attached to for issuing REST calls + */ + class cluster* owner; + + /** + * @brief Application ID + */ + snowflake app_id; + + /** + * @brief Interaction event handle + */ + event_handle interactions; + + /** + * @brief Message event handle + */ + event_handle messages; + + /** + * @brief Returns true if the string has a known prefix on the start. + * Modifies string to remove prefix if it returns true. + * + * @param str String to check and modify + * @return true string contained a prefix, prefix removed from string + * @return false string did not contain a prefix + */ + bool string_has_prefix(std::string &str); + +public: + + /** + * @brief Construct a new commandhandler object + * + * @param o Owning cluster to attach to + * @param auto_hook_events Set to true to automatically hook the on_slashcommand + * and on_message events. You should not need to set this to false unless you have a specific + * use case, as D++ supports multiple listeners to an event, so will allow the commandhandler + * to hook to your command events without disrupting other uses for the events you may have. + * @param application_id The application id of the bot. If not specified, the class will + * look within the cluster object and use cluster::me::id instead. + */ + commandhandler(class cluster* o, bool auto_hook_events = true, snowflake application_id = 0); + + /** + * @brief Destroy the commandhandler object + */ + ~commandhandler(); + + /** + * @brief Set the application id after construction + * + * @param o Owning cluster to attach to + */ + commandhandler& set_owner(class cluster* o); + + /** + * @brief Add a prefix to the command handler + * + * @param prefix Prefix to be handled by the command handler + * @return commandhandler& reference to self + */ + commandhandler& add_prefix(const std::string &prefix); + + /** + * @brief Add a command to the command handler + * + * @param command Command to be handled. + * Note that if any one of your prefixes is "/" this will attempt to register + * a global command using the API and you will receive notification of this command + * via an interaction event. + * @param handler Handler function + * @param parameters Parameters to use for the command + * @param description The description of the command, shown for slash commands + * @param guild_id The guild ID to restrict the command to. For slash commands causes registration of a guild command as opposed to a global command. + * @return commandhandler& reference to self + * @throw dpp::logic_exception if application ID cannot be determined + */ + commandhandler& add_command(const std::string &command, const parameter_registration_t ¶meters, command_handler handler, const std::string &description = "", snowflake guild_id = 0); + + /** + * @brief Register all slash commands with Discord + * This method must be called at least once if you are using the "/" prefix to mark the + * end of commands being added to the handler. Note that this uses bulk registration and will replace any + * existing slash commands. + * + * Note that if you have previously registered your commands and they have not changed, you do + * not need to call this again. Discord retains a cache of previously added commands. + * + * @return commandhandler& Reference to self for chaining method calls + */ + commandhandler& register_commands(); + + /** + * @brief Route a command from the on_message_create function. + * Call this method from within your on_message_create with the received + * dpp::message object if you have disabled automatic registration of events. + * + * @param event message create event to parse + */ + void route(const struct dpp::message_create_t& event); + + /** + * @brief Route a command from the on_slashcommand function. + * Call this method from your on_slashcommand with the received + * dpp::interaction_create_t object if you have disabled automatic registration of events. + * + * @param event command interaction event to parse + */ + void route(const struct slashcommand_t & event); + + /** + * @brief Reply to a command. + * You should use this method rather than cluster::message_create as + * the way you reply varies between slash commands and message commands. + * Note you should ALWAYS reply. Slash commands will emit an ugly error + * to the user if you do not emit some form of reply within 3 seconds. + * + * @param m message to reply with. + * @param source source of the command + * @param callback User function to execute when the api call completes. + */ + void reply(const dpp::message &m, command_source source, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Reply to a command without a message, causing the discord client + * to display "Bot name is thinking...". + * The "thinking" message will persist for a maximum of 15 minutes. + * This counts as a reply for a slash command. Slash commands will emit an + * ugly error to the user if you do not emit some form of reply within 3 + * seconds. + * + * @param source source of the command + * @param callback User function to execute when the api call completes. + */ + void thinking(command_source source, command_completion_event_t callback = utility::log_error()); + + /* Easter egg */ + void thonk(command_source source, command_completion_event_t callback = utility::log_error()); + +}; + +}; diff --git a/3rdParty/dpp/coro.h b/3rdParty/dpp/coro.h index 900a67e43b..43f4d4fe96 100644 --- a/3rdParty/dpp/coro.h +++ b/3rdParty/dpp/coro.h @@ -1,158 +1,158 @@ -#ifdef DPP_CORO -#pragma once -#include -#include - -namespace dpp { - - /** - * @brief Shorthand for the coroutine handle's type - */ - using handle_type = std::coroutine_handle; - - class cluster; - - /** - * @brief Return type for coroutines - */ - struct task { - /** - * @brief Required nested promise_type for coroutines - */ - using promise_type = dpp::promise; - }; - - /** - * @brief Implementation of promise_type for dpp's coroutines - */ - struct promise { - /** - * @brief A pointer to the cluster making the requests in the coroutine - */ - cluster* bot = nullptr; - - /** - * @brief The result of the last co_await-ed function - */ - confirmation_callback_t callback; - - /** - * @brief Construct a new promise object - */ - promise() = default; - - /** - * @brief Construct a new promise object - * - * @param ev Base type of all events, only used to get the dpp::cluster pointer - */ - promise(const dpp::event_dispatch_t& ev) : bot(ev.from->creator) { } - - /** - * @brief Get the return object - * - * @return task dpp::task type - */ - task get_return_object() { - return {}; - } - - /** - * @brief Function called when the coroutine is first suspended, never suspends - * - * @return std::suspend_never Never suspend this coroutine at the first suspend point - */ - std::suspend_never initial_suspend() noexcept { - return {}; - } - - /** - * @brief Function called when the coroutine reaches its last suspension point - * - * @return std::suspend_never Never suspend this coroutine at the final suspend point - */ - std::suspend_never final_suspend() noexcept { - return {}; - } - - /** - * @brief Function called when the coroutine returns nothing - */ - void return_void() noexcept {} - - /** - * @brief Function called when coroutine throws a un-catch-ed exception. Does nothing - */ - void unhandled_exception() { - /* try { std::rethrow_exception(std::current_exception()); } */ - /* catch (const std::exception& e) { std::cout << e.what() << '\n'; } */ - } - }; - - /** - * @brief A co_await-able struct which returns the result of stored api call when co_await-ed. Meant to be opaque to the user - * - * @tparam T The type of the function (lambda if auto-generated by the php script) handling the making of api call - */ - template - struct awaitable { - /** - * @brief Pointer to the nested promise object of the coroutine, used for storing and retrieving the result of an api call - */ - promise* p; - - /** - * @brief Pointer to the cluster making the api request - */ - cluster* bot; - - /** - * @brief The function handling the making of request, using the cluster pointer - */ - T api_req; - - /** - * @brief Construct a new awaitable object - * - * @param cl pointer to the cluster making the api request - * @param api_call a function to invoke with the cluster pointer, handles the making of request - */ - awaitable(cluster* cl, T api_call) : bot{cl}, api_req{api_call} {} - - /** - * @brief First function called when this object is co_await-ed, its return type tells if the coroutine should be immediately suspended - * - * @return bool false, signifying immediate suspension - */ - bool await_ready() noexcept { - return false; - } - - /** - * @brief Function called when the coroutine is suspended, makes the api request and queues the resumption of the suspended coroutine, storing the result in promise object - * - * @param handle the handle to the suspended coroutine - */ - void await_suspend(handle_type handle) { - /* p = &handle.promise(); */ - /* if (!p->bot) p->bot = bot; */ - api_req([handle](const confirmation_callback_t& cback) { handle.promise().callback = cback; handle.resume(); }); - } - - /** - * @brief Function called when the coroutine is resumed by its handle, handles the retrieval and return of result from promise object - * - * @return confirmation_callback_t the result of the api call - */ - confirmation_callback_t await_resume() { - return p->callback; - } - }; - -}; - -/* template<> */ -/* struct std::coroutine_traits { */ -/* using promise_type = dpp::promise; */ -/* }; */ -#endif +#ifdef DPP_CORO +#pragma once +#include +#include + +namespace dpp { + + /** + * @brief Shorthand for the coroutine handle's type + */ + using handle_type = std::coroutine_handle; + + class cluster; + + /** + * @brief Return type for coroutines + */ + struct task { + /** + * @brief Required nested promise_type for coroutines + */ + using promise_type = dpp::promise; + }; + + /** + * @brief Implementation of promise_type for dpp's coroutines + */ + struct promise { + /** + * @brief A pointer to the cluster making the requests in the coroutine + */ + cluster* bot = nullptr; + + /** + * @brief The result of the last co_await-ed function + */ + confirmation_callback_t callback; + + /** + * @brief Construct a new promise object + */ + promise() = default; + + /** + * @brief Construct a new promise object + * + * @param ev Base type of all events, only used to get the dpp::cluster pointer + */ + promise(const dpp::event_dispatch_t& ev) : bot(ev.from->creator) { } + + /** + * @brief Get the return object + * + * @return task dpp::task type + */ + task get_return_object() { + return {}; + } + + /** + * @brief Function called when the coroutine is first suspended, never suspends + * + * @return std::suspend_never Never suspend this coroutine at the first suspend point + */ + std::suspend_never initial_suspend() noexcept { + return {}; + } + + /** + * @brief Function called when the coroutine reaches its last suspension point + * + * @return std::suspend_never Never suspend this coroutine at the final suspend point + */ + std::suspend_never final_suspend() noexcept { + return {}; + } + + /** + * @brief Function called when the coroutine returns nothing + */ + void return_void() noexcept {} + + /** + * @brief Function called when coroutine throws a un-catch-ed exception. Does nothing + */ + void unhandled_exception() { + /* try { std::rethrow_exception(std::current_exception()); } */ + /* catch (const std::exception& e) { std::cout << e.what() << '\n'; } */ + } + }; + + /** + * @brief A co_await-able struct which returns the result of stored api call when co_await-ed. Meant to be opaque to the user + * + * @tparam T The type of the function (lambda if auto-generated by the php script) handling the making of api call + */ + template + struct awaitable { + /** + * @brief Pointer to the nested promise object of the coroutine, used for storing and retrieving the result of an api call + */ + promise* p; + + /** + * @brief Pointer to the cluster making the api request + */ + cluster* bot; + + /** + * @brief The function handling the making of request, using the cluster pointer + */ + T api_req; + + /** + * @brief Construct a new awaitable object + * + * @param cl pointer to the cluster making the api request + * @param api_call a function to invoke with the cluster pointer, handles the making of request + */ + awaitable(cluster* cl, T api_call) : bot{cl}, api_req{api_call} {} + + /** + * @brief First function called when this object is co_await-ed, its return type tells if the coroutine should be immediately suspended + * + * @return bool false, signifying immediate suspension + */ + bool await_ready() noexcept { + return false; + } + + /** + * @brief Function called when the coroutine is suspended, makes the api request and queues the resumption of the suspended coroutine, storing the result in promise object + * + * @param handle the handle to the suspended coroutine + */ + void await_suspend(handle_type handle) { + /* p = &handle.promise(); */ + /* if (!p->bot) p->bot = bot; */ + api_req([handle](const confirmation_callback_t& cback) { handle.promise().callback = cback; handle.resume(); }); + } + + /** + * @brief Function called when the coroutine is resumed by its handle, handles the retrieval and return of result from promise object + * + * @return confirmation_callback_t the result of the api call + */ + confirmation_callback_t await_resume() { + return p->callback; + } + }; + +}; + +/* template<> */ +/* struct std::coroutine_traits { */ +/* using promise_type = dpp::promise; */ +/* }; */ +#endif diff --git a/3rdParty/dpp/discordclient.h b/3rdParty/dpp/discordclient.h index 50c080c52e..745b705848 100644 --- a/3rdParty/dpp/discordclient.h +++ b/3rdParty/dpp/discordclient.h @@ -1,519 +1,519 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using json = nlohmann::json; - -#define DISCORD_API_VERSION "10" -#define API_PATH "/api/v" DISCORD_API_VERSION -namespace dpp { - -// Forward declarations -class cluster; - -/** - * @brief This is an opaque class containing zlib library specific structures. - * We define it this way so that the public facing D++ library doesn't require - * the zlib headers be available to build against it. - */ -class zlibcontext; - -/** - * @brief Represents a connection to a voice channel. - * A client can only connect to one voice channel per guild at a time, so these are stored in a map - * in the dpp::discord_client keyed by guild_id. - */ -class DPP_EXPORT voiceconn { - /** - * @brief Owning dpp::discord_client instance - */ - class discord_client* creator; -public: - /** - * @brief Voice Channel ID - */ - snowflake channel_id; - - /** - * @brief Websocket hostname for status - */ - std::string websocket_hostname; - - /** - * @brief Voice Voice session ID - */ - std::string session_id; - - /** - * @brief Voice websocket token - */ - std::string token; - - /** - * @brief voice websocket client - */ - class discord_voice_client* voiceclient; - - /** - * @brief Construct a new voiceconn object - */ - voiceconn() = default; - - /** - * @brief Construct a new voiceconn object - * - * @param o owner - * @param _channel_id voice channel id - */ - voiceconn(class discord_client* o, snowflake _channel_id); - - /** - * @brief Destroy the voiceconn object - */ - ~voiceconn(); - - /** - * @brief return true if the connection is ready to connect - * (has hostname, token and session id) - * - * @return true if ready to connect - */ - bool is_ready(); - - /** - * @brief return true if the connection is active (websocket exists) - * - * @return true if has an active websocket - */ - bool is_active(); - - /** - * @brief Create websocket object and connect it. - * Needs hostname, token and session_id to be set or does nothing. - * - * @param guild_id Guild to connect to the voice channel on - * @return reference to self - * @note It can spawn a thread to establish the connection, so this is NOT a synchronous blocking call! - * You shouldn't call this directly. Use a wrapper function instead. e.g. dpp::guild::connect_member_voice - */ - voiceconn& connect(snowflake guild_id); - - /** - * @brief Disconnect from the currently connected voice channel - * @return reference to self - */ - voiceconn& disconnect(); -}; - -/** @brief Implements a discord client. Each discord_client connects to one shard and derives from a websocket client. */ -class DPP_EXPORT discord_client : public websocket_client -{ -protected: - /** - * @brief Needed so that voice_state_update can call dpp::discord_client::disconnect_voice_internal - */ - friend class dpp::events::voice_state_update; - - /** - * @brief Needed so that guild_create can request member chunks if you have the correct intents - */ - friend class dpp::events::guild_create; - - /** - * @brief Needed to allow cluster::set_presence to use the ETF functions - */ - friend class dpp::cluster; - - /** - * @brief True if the shard is terminating - */ - bool terminating; - - /** - * @brief Disconnect from the connected voice channel on a guild - * - * @param guild_id The guild who's voice channel you wish to disconnect from - * @param send_json True if we should send a json message confirming we are leaving the VC - * Should be set to false if we already receive this message in an event. - */ - void disconnect_voice_internal(snowflake guild_id, bool send_json = true); - -private: - - /** - * @brief Mutex for message queue - */ - std::shared_mutex queue_mutex; - - /** - * @brief Queue of outbound messages - */ - std::deque message_queue; - - /** - * @brief Thread this shard is executing on - */ - std::thread* runner; - - /** - * @brief Run shard loop under a thread. - * Calls discord_client::run() from within a std::thread. - */ - void thread_run(); - - /** - * @brief If true, stream compression is enabled - */ - bool compressed; - - /** - * @brief ZLib decompression buffer - */ - unsigned char* decomp_buffer; - - /** - * @brief Decompressed string - */ - std::string decompressed; - - /** - * @brief This object contains the various zlib structs which - * are not usable by the user of the library directly. They - * are wrapped within this opaque object so that this header - * file does not bring in a dependency on zlib.h. - */ - zlibcontext* zlib; - - /** - * @brief Total decompressed received bytes - */ - uint64_t decompressed_total; - - /** - * @brief Last connect time of cluster - */ - time_t connect_time; - - /** - * @brief Time last ping sent to websocket, in fractional seconds - */ - double ping_start; - - /** - * @brief ETF parser for when in ws_etf mode - */ - class etf_parser* etf; - - /** - * @brief Convert a JSON object to string. - * In JSON protocol mode, call json.dump(), and in ETF mode, - * call etf::build(). - * - * @param json nlohmann::json object to convert - * @return std::string string output in the correct format - */ - std::string jsonobj_to_string(const nlohmann::json& json); - - /** - * @brief Initialise ZLib (websocket compression) - * @throw dpp::exception if ZLib cannot be initialised - */ - void setup_zlib(); - - /** - * @brief Shut down ZLib (websocket compression) - */ - void end_zlib(); - - /** - * @brief Update the websocket hostname with the resume url - * from the last READY event - */ - void set_resume_hostname(); - -public: - /** - * @brief Owning cluster - */ - class dpp::cluster* creator; - - /** - * @brief Heartbeat interval for sending heartbeat keepalive - * @note value in milliseconds - */ - uint32_t heartbeat_interval; - - /** - * @brief Last heartbeat - */ - time_t last_heartbeat; - - /** - * @brief Shard ID of this client - */ - uint32_t shard_id; - - /** - * @brief Total number of shards - */ - uint32_t max_shards; - - /** - * @brief Thread ID - */ - std::thread::native_handle_type thread_id; - - /** - * @brief Last sequence number received, for resumes and pings - */ - uint64_t last_seq; - - /** - * @brief Discord bot token - */ - std::string token; - - /** - * @brief Privileged gateway intents - * @see dpp::intents - */ - uint32_t intents; - - /** - * @brief Discord session id - */ - std::string sessionid; - - /** - * @brief Mutex for voice connections map - */ - std::shared_mutex voice_mutex; - - /** - * @brief Resume count - */ - uint32_t resumes; - - /** - * @brief Reconnection count - */ - uint32_t reconnects; - - /** - * @brief Websocket latency in fractional seconds - */ - double websocket_ping; - - /** - * @brief True if READY or RESUMED has been received - */ - bool ready; - - /** - * @brief Last heartbeat ACK (opcode 11) - */ - time_t last_heartbeat_ack; - - /** - * @brief Current websocket protocol, currently either ETF or JSON - */ - websocket_protocol_t protocol; - - /** - * @brief List of voice channels we are connecting to keyed by guild id - */ - std::unordered_map connecting_voice_channels; - - /** - * @brief The gateway address we reconnect to when we resume a session - */ - std::string resume_gateway_url; - - /** - * @brief Log a message to whatever log the user is using. - * The logged message is passed up the chain to the on_log event in user code which can then do whatever - * it wants to do with it. - * @param severity The log level from dpp::loglevel - * @param msg The log message to output - */ - virtual void log(dpp::loglevel severity, const std::string &msg) const; - - /** - * @brief Handle an event (opcode 0) - * @param event Event name, e.g. MESSAGE_CREATE - * @param j JSON object for the event content - * @param raw Raw JSON event string - */ - virtual void handle_event(const std::string &event, json &j, const std::string &raw); - - /** - * @brief Get the Guild Count for this shard - * - * @return uint64_t guild count - */ - uint64_t get_guild_count(); - - /** - * @brief Get the Member Count for this shard - * - * @return uint64_t member count - */ - uint64_t get_member_count(); - - /** - * @brief Get the Channel Count for this shard - * - * @return uint64_t channel count - */ - uint64_t get_channel_count(); - - /** Fires every second from the underlying socket I/O loop, used for sending heartbeats */ - virtual void one_second_timer(); - - /** - * @brief Queue a message to be sent via the websocket - * - * @param j The JSON data of the message to be sent - * @param to_front If set to true, will place the message at the front of the queue not the back - * (this is for urgent messages such as heartbeat, presence, so they can take precedence over - * chunk requests etc) - */ - void queue_message(const std::string &j, bool to_front = false); - - /** - * @brief Clear the outbound message queue - * @return reference to self - */ - discord_client& clear_queue(); - - /** - * @brief Get the size of the outbound message queue - * - * @return The size of the queue - */ - size_t get_queue_size(); - - /** - * @brief Returns true if the shard is connected - * - * @return True if connected - */ - bool is_connected(); - - /** - * @brief Returns the connection time of the shard - * - * @return dpp::utility::uptime Detail of how long the shard has been connected for - */ - dpp::utility::uptime get_uptime(); - - /** - * @brief Construct a new discord_client object - * - * @param _cluster The owning cluster for this shard - * @param _shard_id The ID of the shard to start - * @param _max_shards The total number of shards across all clusters - * @param _token The bot token to use for identifying to the websocket - * @param intents Privileged intents to use, a bitmask of values from dpp::intents - * @param compressed True if the received data will be gzip compressed - * @param ws_protocol Websocket protocol to use for the connection, JSON or ETF - */ - discord_client(dpp::cluster* _cluster, uint32_t _shard_id, uint32_t _max_shards, const std::string &_token, uint32_t intents = 0, bool compressed = true, websocket_protocol_t ws_protocol = ws_json); - - /** - * @brief Destroy the discord client object - */ - virtual ~discord_client(); - - /** - * @brief Get the decompressed bytes in objectGet decompressed total bytes received - * @return uint64_t bytes received - */ - uint64_t get_decompressed_bytes_in(); - - /** - * @brief Handle JSON from the websocket. - * @param buffer The entire buffer content from the websocket client - * @returns True if a frame has been handled - */ - virtual bool handle_frame(const std::string &buffer); - - /** - * @brief Handle a websocket error. - * @param errorcode The error returned from the websocket - */ - virtual void error(uint32_t errorcode); - - /** - * @brief Start and monitor I/O loop. - * @note this is a blocking call and is usually executed within a - * thread by whatever creates the object. - */ - void run(); - - /** - * @brief Connect to a voice channel - * - * @param guild_id Guild where the voice channel is - * @param channel_id Channel ID of the voice channel - * @param self_mute True if the bot should mute itself - * @param self_deaf True if the bot should deafen itself - * @return reference to self - * @note This is NOT a synchronous blocking call! The bot isn't instantly ready to send or listen for audio, - * as we have to wait for the connection to the voice server to be established! - * e.g. wait for dpp::cluster::on_voice_ready event, and then send the audio within that event. - */ - discord_client& connect_voice(snowflake guild_id, snowflake channel_id, bool self_mute = false, bool self_deaf = false); - - /** - * @brief Disconnect from the connected voice channel on a guild - * - * @param guild_id The guild who's voice channel you wish to disconnect from - * @return reference to self - * @note This is NOT a synchronous blocking call! The bot isn't instantly disconnected. - */ - discord_client& disconnect_voice(snowflake guild_id); - - /** - * @brief Get the dpp::voiceconn object for a specific guild on this shard. - * - * @param guild_id The guild ID to retrieve the voice connection for - * @return voiceconn* The voice connection for the guild, or nullptr if there is no - * voice connection to this guild. - */ - voiceconn* get_voice(snowflake guild_id); -}; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +#define DISCORD_API_VERSION "10" +#define API_PATH "/api/v" DISCORD_API_VERSION +namespace dpp { + +// Forward declarations +class cluster; + +/** + * @brief This is an opaque class containing zlib library specific structures. + * We define it this way so that the public facing D++ library doesn't require + * the zlib headers be available to build against it. + */ +class zlibcontext; + +/** + * @brief Represents a connection to a voice channel. + * A client can only connect to one voice channel per guild at a time, so these are stored in a map + * in the dpp::discord_client keyed by guild_id. + */ +class DPP_EXPORT voiceconn { + /** + * @brief Owning dpp::discord_client instance + */ + class discord_client* creator; +public: + /** + * @brief Voice Channel ID + */ + snowflake channel_id; + + /** + * @brief Websocket hostname for status + */ + std::string websocket_hostname; + + /** + * @brief Voice Voice session ID + */ + std::string session_id; + + /** + * @brief Voice websocket token + */ + std::string token; + + /** + * @brief voice websocket client + */ + class discord_voice_client* voiceclient; + + /** + * @brief Construct a new voiceconn object + */ + voiceconn() = default; + + /** + * @brief Construct a new voiceconn object + * + * @param o owner + * @param _channel_id voice channel id + */ + voiceconn(class discord_client* o, snowflake _channel_id); + + /** + * @brief Destroy the voiceconn object + */ + ~voiceconn(); + + /** + * @brief return true if the connection is ready to connect + * (has hostname, token and session id) + * + * @return true if ready to connect + */ + bool is_ready(); + + /** + * @brief return true if the connection is active (websocket exists) + * + * @return true if has an active websocket + */ + bool is_active(); + + /** + * @brief Create websocket object and connect it. + * Needs hostname, token and session_id to be set or does nothing. + * + * @param guild_id Guild to connect to the voice channel on + * @return reference to self + * @note It can spawn a thread to establish the connection, so this is NOT a synchronous blocking call! + * You shouldn't call this directly. Use a wrapper function instead. e.g. dpp::guild::connect_member_voice + */ + voiceconn& connect(snowflake guild_id); + + /** + * @brief Disconnect from the currently connected voice channel + * @return reference to self + */ + voiceconn& disconnect(); +}; + +/** @brief Implements a discord client. Each discord_client connects to one shard and derives from a websocket client. */ +class DPP_EXPORT discord_client : public websocket_client +{ +protected: + /** + * @brief Needed so that voice_state_update can call dpp::discord_client::disconnect_voice_internal + */ + friend class dpp::events::voice_state_update; + + /** + * @brief Needed so that guild_create can request member chunks if you have the correct intents + */ + friend class dpp::events::guild_create; + + /** + * @brief Needed to allow cluster::set_presence to use the ETF functions + */ + friend class dpp::cluster; + + /** + * @brief True if the shard is terminating + */ + bool terminating; + + /** + * @brief Disconnect from the connected voice channel on a guild + * + * @param guild_id The guild who's voice channel you wish to disconnect from + * @param send_json True if we should send a json message confirming we are leaving the VC + * Should be set to false if we already receive this message in an event. + */ + void disconnect_voice_internal(snowflake guild_id, bool send_json = true); + +private: + + /** + * @brief Mutex for message queue + */ + std::shared_mutex queue_mutex; + + /** + * @brief Queue of outbound messages + */ + std::deque message_queue; + + /** + * @brief Thread this shard is executing on + */ + std::thread* runner; + + /** + * @brief Run shard loop under a thread. + * Calls discord_client::run() from within a std::thread. + */ + void thread_run(); + + /** + * @brief If true, stream compression is enabled + */ + bool compressed; + + /** + * @brief ZLib decompression buffer + */ + unsigned char* decomp_buffer; + + /** + * @brief Decompressed string + */ + std::string decompressed; + + /** + * @brief This object contains the various zlib structs which + * are not usable by the user of the library directly. They + * are wrapped within this opaque object so that this header + * file does not bring in a dependency on zlib.h. + */ + zlibcontext* zlib; + + /** + * @brief Total decompressed received bytes + */ + uint64_t decompressed_total; + + /** + * @brief Last connect time of cluster + */ + time_t connect_time; + + /** + * @brief Time last ping sent to websocket, in fractional seconds + */ + double ping_start; + + /** + * @brief ETF parser for when in ws_etf mode + */ + class etf_parser* etf; + + /** + * @brief Convert a JSON object to string. + * In JSON protocol mode, call json.dump(), and in ETF mode, + * call etf::build(). + * + * @param json nlohmann::json object to convert + * @return std::string string output in the correct format + */ + std::string jsonobj_to_string(const nlohmann::json& json); + + /** + * @brief Initialise ZLib (websocket compression) + * @throw dpp::exception if ZLib cannot be initialised + */ + void setup_zlib(); + + /** + * @brief Shut down ZLib (websocket compression) + */ + void end_zlib(); + + /** + * @brief Update the websocket hostname with the resume url + * from the last READY event + */ + void set_resume_hostname(); + +public: + /** + * @brief Owning cluster + */ + class dpp::cluster* creator; + + /** + * @brief Heartbeat interval for sending heartbeat keepalive + * @note value in milliseconds + */ + uint32_t heartbeat_interval; + + /** + * @brief Last heartbeat + */ + time_t last_heartbeat; + + /** + * @brief Shard ID of this client + */ + uint32_t shard_id; + + /** + * @brief Total number of shards + */ + uint32_t max_shards; + + /** + * @brief Thread ID + */ + std::thread::native_handle_type thread_id; + + /** + * @brief Last sequence number received, for resumes and pings + */ + uint64_t last_seq; + + /** + * @brief Discord bot token + */ + std::string token; + + /** + * @brief Privileged gateway intents + * @see dpp::intents + */ + uint32_t intents; + + /** + * @brief Discord session id + */ + std::string sessionid; + + /** + * @brief Mutex for voice connections map + */ + std::shared_mutex voice_mutex; + + /** + * @brief Resume count + */ + uint32_t resumes; + + /** + * @brief Reconnection count + */ + uint32_t reconnects; + + /** + * @brief Websocket latency in fractional seconds + */ + double websocket_ping; + + /** + * @brief True if READY or RESUMED has been received + */ + bool ready; + + /** + * @brief Last heartbeat ACK (opcode 11) + */ + time_t last_heartbeat_ack; + + /** + * @brief Current websocket protocol, currently either ETF or JSON + */ + websocket_protocol_t protocol; + + /** + * @brief List of voice channels we are connecting to keyed by guild id + */ + std::unordered_map connecting_voice_channels; + + /** + * @brief The gateway address we reconnect to when we resume a session + */ + std::string resume_gateway_url; + + /** + * @brief Log a message to whatever log the user is using. + * The logged message is passed up the chain to the on_log event in user code which can then do whatever + * it wants to do with it. + * @param severity The log level from dpp::loglevel + * @param msg The log message to output + */ + virtual void log(dpp::loglevel severity, const std::string &msg) const; + + /** + * @brief Handle an event (opcode 0) + * @param event Event name, e.g. MESSAGE_CREATE + * @param j JSON object for the event content + * @param raw Raw JSON event string + */ + virtual void handle_event(const std::string &event, json &j, const std::string &raw); + + /** + * @brief Get the Guild Count for this shard + * + * @return uint64_t guild count + */ + uint64_t get_guild_count(); + + /** + * @brief Get the Member Count for this shard + * + * @return uint64_t member count + */ + uint64_t get_member_count(); + + /** + * @brief Get the Channel Count for this shard + * + * @return uint64_t channel count + */ + uint64_t get_channel_count(); + + /** Fires every second from the underlying socket I/O loop, used for sending heartbeats */ + virtual void one_second_timer(); + + /** + * @brief Queue a message to be sent via the websocket + * + * @param j The JSON data of the message to be sent + * @param to_front If set to true, will place the message at the front of the queue not the back + * (this is for urgent messages such as heartbeat, presence, so they can take precedence over + * chunk requests etc) + */ + void queue_message(const std::string &j, bool to_front = false); + + /** + * @brief Clear the outbound message queue + * @return reference to self + */ + discord_client& clear_queue(); + + /** + * @brief Get the size of the outbound message queue + * + * @return The size of the queue + */ + size_t get_queue_size(); + + /** + * @brief Returns true if the shard is connected + * + * @return True if connected + */ + bool is_connected(); + + /** + * @brief Returns the connection time of the shard + * + * @return dpp::utility::uptime Detail of how long the shard has been connected for + */ + dpp::utility::uptime get_uptime(); + + /** + * @brief Construct a new discord_client object + * + * @param _cluster The owning cluster for this shard + * @param _shard_id The ID of the shard to start + * @param _max_shards The total number of shards across all clusters + * @param _token The bot token to use for identifying to the websocket + * @param intents Privileged intents to use, a bitmask of values from dpp::intents + * @param compressed True if the received data will be gzip compressed + * @param ws_protocol Websocket protocol to use for the connection, JSON or ETF + */ + discord_client(dpp::cluster* _cluster, uint32_t _shard_id, uint32_t _max_shards, const std::string &_token, uint32_t intents = 0, bool compressed = true, websocket_protocol_t ws_protocol = ws_json); + + /** + * @brief Destroy the discord client object + */ + virtual ~discord_client(); + + /** + * @brief Get the decompressed bytes in objectGet decompressed total bytes received + * @return uint64_t bytes received + */ + uint64_t get_decompressed_bytes_in(); + + /** + * @brief Handle JSON from the websocket. + * @param buffer The entire buffer content from the websocket client + * @returns True if a frame has been handled + */ + virtual bool handle_frame(const std::string &buffer); + + /** + * @brief Handle a websocket error. + * @param errorcode The error returned from the websocket + */ + virtual void error(uint32_t errorcode); + + /** + * @brief Start and monitor I/O loop. + * @note this is a blocking call and is usually executed within a + * thread by whatever creates the object. + */ + void run(); + + /** + * @brief Connect to a voice channel + * + * @param guild_id Guild where the voice channel is + * @param channel_id Channel ID of the voice channel + * @param self_mute True if the bot should mute itself + * @param self_deaf True if the bot should deafen itself + * @return reference to self + * @note This is NOT a synchronous blocking call! The bot isn't instantly ready to send or listen for audio, + * as we have to wait for the connection to the voice server to be established! + * e.g. wait for dpp::cluster::on_voice_ready event, and then send the audio within that event. + */ + discord_client& connect_voice(snowflake guild_id, snowflake channel_id, bool self_mute = false, bool self_deaf = false); + + /** + * @brief Disconnect from the connected voice channel on a guild + * + * @param guild_id The guild who's voice channel you wish to disconnect from + * @return reference to self + * @note This is NOT a synchronous blocking call! The bot isn't instantly disconnected. + */ + discord_client& disconnect_voice(snowflake guild_id); + + /** + * @brief Get the dpp::voiceconn object for a specific guild on this shard. + * + * @param guild_id The guild ID to retrieve the voice connection for + * @return voiceconn* The voice connection for the guild, or nullptr if there is no + * voice connection to this guild. + */ + voiceconn* get_voice(snowflake guild_id); +}; + +}; diff --git a/3rdParty/dpp/discordevents.h b/3rdParty/dpp/discordevents.h index c6474a45c0..62f88c33ee 100644 --- a/3rdParty/dpp/discordevents.h +++ b/3rdParty/dpp/discordevents.h @@ -1,171 +1,171 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once - -#include -#include - -namespace dpp { - -/** @brief Returns a snowflake id from a json field value, if defined, else returns 0 - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @return found value - */ -uint64_t DPP_EXPORT snowflake_not_null(const nlohmann::json* j, const char *keyname); - -/** @brief Sets a snowflake id from a json field value, if defined, else does nothing - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @param v Value to change - */ -void DPP_EXPORT set_snowflake_not_null(const nlohmann::json* j, const char *keyname, uint64_t &v); - -/** @brief Returns a string from a json field value, if defined, else returns an empty string. - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @return found value - */ -std::string DPP_EXPORT string_not_null(const nlohmann::json* j, const char *keyname); - -/** @brief Sets a string from a json field value, if defined, else does nothing - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @param v Value to change - */ -void DPP_EXPORT set_string_not_null(const nlohmann::json* j, const char *keyname, std::string &v); - -/** @brief Returns a double from a json field value, if defined, else returns 0. - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @return found value - */ -double DPP_EXPORT double_not_null(const nlohmann::json* j, const char *keyname); - -/** @brief Sets a double from a json field value, if defined, else does nothing - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @param v Value to change - */ -void DPP_EXPORT set_double_not_null(const nlohmann::json* j, const char *keyname, double &v); - -/** @brief Returns a 64 bit unsigned integer from a json field value, if defined, else returns 0. - * DO NOT use this for snowflakes, as usually snowflakes are wrapped in a string! - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @return found value - */ -uint64_t DPP_EXPORT int64_not_null(const nlohmann::json* j, const char *keyname); - -/** @brief Sets an unsigned 64 bit integer from a json field value, if defined, else does nothing - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @param v Value to change - */ -void DPP_EXPORT set_int64_not_null(const nlohmann::json* j, const char *keyname, uint64_t &v); - -/** @brief Returns a 32 bit unsigned integer from a json field value, if defined, else returns 0 - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @return found value - */ -uint32_t DPP_EXPORT int32_not_null(const nlohmann::json* j, const char *keyname); - -/** @brief Sets an unsigned 32 bit integer from a json field value, if defined, else does nothing - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @param v Value to change - */ -void DPP_EXPORT set_int32_not_null(const nlohmann::json* j, const char *keyname, uint32_t &v); - -/** @brief Returns a 16 bit unsigned integer from a json field value, if defined, else returns 0 - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @return found value - */ -uint16_t DPP_EXPORT int16_not_null(const nlohmann::json* j, const char *keyname); - -/** @brief Sets an unsigned 16 bit integer from a json field value, if defined, else does nothing - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @param v Value to change - */ -void DPP_EXPORT set_int16_not_null(const nlohmann::json* j, const char *keyname, uint16_t &v); - -/** @brief Returns an 8 bit unsigned integer from a json field value, if defined, else returns 0 - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @return found value - */ -uint8_t DPP_EXPORT int8_not_null(const nlohmann::json* j, const char *keyname); - -/** @brief Sets an unsigned 8 bit integer from a json field value, if defined, else does nothing - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @param v Value to change - */ -void DPP_EXPORT set_int8_not_null(const nlohmann::json* j, const char *keyname, uint8_t &v); - -/** @brief Returns a boolean value from a json field value, if defined, else returns false - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @return found value - */ -bool DPP_EXPORT bool_not_null(const nlohmann::json* j, const char *keyname); - -/** @brief Sets a boolean from a json field value, if defined, else does nothing - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @param v Value to change - */ -void DPP_EXPORT set_bool_not_null(const nlohmann::json* j, const char *keyname, bool &v); - -/** @brief Returns a time_t from an ISO8601 timestamp field in a json value, if defined, else returns - * epoch value of 0. - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @return found value - */ -time_t DPP_EXPORT ts_not_null(const nlohmann::json* j, const char *keyname); - -/** @brief Sets an timestamp from a json field value containing an ISO8601 string, if defined, else does nothing - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @param v Value to change - */ -void DPP_EXPORT set_ts_not_null(const nlohmann::json* j, const char *keyname, time_t &v); - -/** @brief Base64 encode data into a string. - * @param buf Raw binary buffer - * @param buffer_length Buffer length to encode - * @return The base64 encoded string - */ -std::string DPP_EXPORT base64_encode(unsigned char const* buf, unsigned int buffer_length); - -/** - * @brief Convert time_t unix epoch to std::string ISO date/time - * - * @param ts Timestamp to convert - * @return std::string Converted time/date string - */ -std::string DPP_EXPORT ts_to_string(time_t ts); - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once + +#include +#include + +namespace dpp { + +/** @brief Returns a snowflake id from a json field value, if defined, else returns 0 + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +uint64_t DPP_EXPORT snowflake_not_null(const nlohmann::json* j, const char *keyname); + +/** @brief Sets a snowflake id from a json field value, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void DPP_EXPORT set_snowflake_not_null(const nlohmann::json* j, const char *keyname, uint64_t &v); + +/** @brief Returns a string from a json field value, if defined, else returns an empty string. + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +std::string DPP_EXPORT string_not_null(const nlohmann::json* j, const char *keyname); + +/** @brief Sets a string from a json field value, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void DPP_EXPORT set_string_not_null(const nlohmann::json* j, const char *keyname, std::string &v); + +/** @brief Returns a double from a json field value, if defined, else returns 0. + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +double DPP_EXPORT double_not_null(const nlohmann::json* j, const char *keyname); + +/** @brief Sets a double from a json field value, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void DPP_EXPORT set_double_not_null(const nlohmann::json* j, const char *keyname, double &v); + +/** @brief Returns a 64 bit unsigned integer from a json field value, if defined, else returns 0. + * DO NOT use this for snowflakes, as usually snowflakes are wrapped in a string! + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +uint64_t DPP_EXPORT int64_not_null(const nlohmann::json* j, const char *keyname); + +/** @brief Sets an unsigned 64 bit integer from a json field value, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void DPP_EXPORT set_int64_not_null(const nlohmann::json* j, const char *keyname, uint64_t &v); + +/** @brief Returns a 32 bit unsigned integer from a json field value, if defined, else returns 0 + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +uint32_t DPP_EXPORT int32_not_null(const nlohmann::json* j, const char *keyname); + +/** @brief Sets an unsigned 32 bit integer from a json field value, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void DPP_EXPORT set_int32_not_null(const nlohmann::json* j, const char *keyname, uint32_t &v); + +/** @brief Returns a 16 bit unsigned integer from a json field value, if defined, else returns 0 + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +uint16_t DPP_EXPORT int16_not_null(const nlohmann::json* j, const char *keyname); + +/** @brief Sets an unsigned 16 bit integer from a json field value, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void DPP_EXPORT set_int16_not_null(const nlohmann::json* j, const char *keyname, uint16_t &v); + +/** @brief Returns an 8 bit unsigned integer from a json field value, if defined, else returns 0 + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +uint8_t DPP_EXPORT int8_not_null(const nlohmann::json* j, const char *keyname); + +/** @brief Sets an unsigned 8 bit integer from a json field value, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void DPP_EXPORT set_int8_not_null(const nlohmann::json* j, const char *keyname, uint8_t &v); + +/** @brief Returns a boolean value from a json field value, if defined, else returns false + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +bool DPP_EXPORT bool_not_null(const nlohmann::json* j, const char *keyname); + +/** @brief Sets a boolean from a json field value, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void DPP_EXPORT set_bool_not_null(const nlohmann::json* j, const char *keyname, bool &v); + +/** @brief Returns a time_t from an ISO8601 timestamp field in a json value, if defined, else returns + * epoch value of 0. + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +time_t DPP_EXPORT ts_not_null(const nlohmann::json* j, const char *keyname); + +/** @brief Sets an timestamp from a json field value containing an ISO8601 string, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void DPP_EXPORT set_ts_not_null(const nlohmann::json* j, const char *keyname, time_t &v); + +/** @brief Base64 encode data into a string. + * @param buf Raw binary buffer + * @param buffer_length Buffer length to encode + * @return The base64 encoded string + */ +std::string DPP_EXPORT base64_encode(unsigned char const* buf, unsigned int buffer_length); + +/** + * @brief Convert time_t unix epoch to std::string ISO date/time + * + * @param ts Timestamp to convert + * @return std::string Converted time/date string + */ +std::string DPP_EXPORT ts_to_string(time_t ts); + +}; diff --git a/3rdParty/dpp/discordvoiceclient.h b/3rdParty/dpp/discordvoiceclient.h index a98fd84f8d..9ecd3840d5 100644 --- a/3rdParty/dpp/discordvoiceclient.h +++ b/3rdParty/dpp/discordvoiceclient.h @@ -1,868 +1,868 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using json = nlohmann::json; - -struct OpusDecoder; -struct OpusEncoder; -struct OpusRepacketizer; - -namespace dpp { - -// Forward declaration -class cluster; - -/** - * @brief An opus-encoded RTP packet to be sent out to a voice channel - */ -struct DPP_EXPORT voice_out_packet { - /** - * @brief Each string is a UDP packet. - * Generally these will be RTP. - */ - std::string packet; - /** - * @brief Duration of packet - */ - uint64_t duration; -}; - -#define AUDIO_TRACK_MARKER (uint16_t)0xFFFF - -#define AUDIO_OVERLAP_SLEEP_SAMPLES 30 - -/** @brief Implements a discord voice connection. - * Each discord_voice_client connects to one voice channel and derives from a websocket client. - */ -class DPP_EXPORT discord_voice_client : public websocket_client -{ - /** - * @brief Mutex for outbound packet stream - */ - std::mutex stream_mutex; - - /** - * @brief Mutex for message queue - */ - std::shared_mutex queue_mutex; - - /** - * @brief Queue of outbound messages - */ - std::deque message_queue; - - /** - * @brief Thread this connection is executing on - */ - std::thread* runner; - - /** - * @brief Run shard loop under a thread - */ - void thread_run(); - - /** - * @brief Last connect time of voice session - */ - time_t connect_time; - - /** - * @brief IP of UDP/RTP endpoint - */ - std::string ip; - - /** - * @brief Port number of UDP/RTP endpoint - */ - uint16_t port; - - /** - * @brief SSRC value - */ - uint64_t ssrc; - - /** - * @brief List of supported audio encoding modes - */ - std::vector modes; - - /** - * @brief Timescale in nanoseconds - */ - uint64_t timescale; - - /** - * @brief Output buffer - */ - std::vector outbuf; - - /** - * @brief Data type of RTP packet sequence number field. - */ - using rtp_seq_t = uint16_t; - using rtp_timestamp_t = uint32_t; - - /** - * @brief Keeps track of the voice payload to deliver to voice handlers. - */ - struct voice_payload { - /** - * @brief The sequence number of the RTP packet that generated this - * voice payload. - */ - rtp_seq_t seq; - /** - * @brief The timestamp of the RTP packet that generated this voice - * payload. - * - * The timestamp is used to detect the order around where sequence - * number wraps around. - */ - rtp_timestamp_t timestamp; - /** - * @brief The event payload that voice handlers receive. - */ - std::unique_ptr vr; - - /** - * @brief For priority_queue sorting. - * @return true if "this" has lower priority that "other", - * i.e. appears later in the queue; false otherwise. - */ - bool operator<(const voice_payload& other) const; - }; - - struct voice_payload_parking_lot { - /** - * @brief The range of RTP packet sequence number and timestamp in the lot. - * - * The minimum is used to drop packets that arrive too late. Packets - * less than the minimum have been delivered to voice handlers and - * there is no going back. Unfortunately we just have to drop them. - * - * The maximum is used, at flush time, to calculate the minimum for - * the next batch. The maximum is also updated every time we receive an - * RTP packet with a larger value. - */ - struct seq_range_t { - rtp_seq_t min_seq, max_seq; - rtp_timestamp_t min_timestamp, max_timestamp; - } range; - /** - * @brief The queue of parked voice payloads. - * - * We group payloads and deliver them to handlers periodically as the - * handling of out-of-order RTP packets. Payloads in between flushes - * are parked and sorted in this queue. - */ - std::priority_queue parked_payloads; - /** - * @brief The decoder ctls to be set on the decoder. - */ - std::vector> pending_decoder_ctls; - /** - * @brief libopus decoder - * - * Shared with the voice courier thread that does the decoding. - * This is not protected by a mutex because only the courier thread - * uses the decoder. - */ - std::shared_ptr decoder; - }; - /** - * @brief Thread used to deliver incoming voice data to handlers. - */ - std::thread voice_courier; - /** - * @brief Shared state between this voice client and the courier thread. - */ - struct courier_shared_state_t { - /** - * @brief Protects all following members. - */ - std::mutex mtx; - /** - * @brief Signaled when there is a new payload to deliver or terminating state has changed. - */ - std::condition_variable signal_iteration; - /** - * @brief Voice buffers to be reported to handler, grouped by speaker. - * - * Buffers are parked here and flushed every 500ms. - */ - std::map parked_voice_payloads; - /** - * @brief Used to signal termination. - * - * @note Pending payloads are delivered first before termination. - */ - bool terminating = false; - } voice_courier_shared_state; - /** - * @brief The run loop of the voice courier thread. - */ - static void voice_courier_loop(discord_voice_client&, courier_shared_state_t&); - - /** - * @brief If true, audio packet sending is paused - */ - bool paused; - -#ifdef HAVE_VOICE - /** - * @brief libopus encoder - */ - OpusEncoder* encoder; - - /** - * @brief libopus repacketizer - * (merges frames into one packet) - */ - OpusRepacketizer* repacketizer; -#else - /** - * @brief libopus encoder - */ - void* encoder; - - /** - * @brief libopus repacketizer - * (merges frames into one packet) - */ - void* repacketizer; -#endif - - /** - * @brief File descriptor for UDP connection - */ - dpp::socket fd; - - /** - * @brief Secret key for encrypting voice. - * If it has been sent, this is non-null and points to a - * sequence of exactly 32 bytes. - */ - uint8_t* secret_key; - - /** - * @brief Sequence number of outbound audio. This is incremented - * once per frame sent. - */ - uint16_t sequence; - - /** - * @brief Timestamp value used in outbound audio. Each packet - * has the timestamp value which is incremented to match - * how many frames are sent. - */ - uint32_t timestamp; - - /** - * @brief Last sent packet high-resolution timestamp - */ - std::chrono::high_resolution_clock::time_point last_timestamp; - - /** - * @brief Fraction of the sleep that was not executed after the last audio packet was sent - */ - std::chrono::nanoseconds last_sleep_remainder; - - /** - * @brief Maps receiving ssrc to user id - */ - std::unordered_map ssrc_map; - - /** - * @brief This is set to true if we have started sending audio. - * When this moves from false to true, this causes the - * client to send the 'talking' notification to the websocket. - */ - bool sending; - - /** - * @brief Number of track markers in the buffer. For example if there - * are two track markers in the buffer there are 3 tracks. - * - * **Special case:** - * - * If the buffer is empty, there are zero tracks in the - * buffer. - */ - uint32_t tracks; - - /** - * @brief Meta data associated with each track. - * Arbitrary string that the user can set via - * dpp::discord_voice_client::add_marker - */ - std::vector track_meta; - - /** - * @brief Encoding buffer for opus repacketizer and encode - */ - uint8_t encode_buffer[65536]; - - /** - * @brief Send data to UDP socket immediately. - * - * @param data data to send - * @param length length of data to send - * @return int bytes sent. Will return -1 if we cannot send - */ - int udp_send(const char* data, size_t length); - - /** - * @brief Receive data from UDP socket immediately. - * - * @param data data to receive - * @param max_length size of data receiving buffer - * @return int bytes received. -1 if there is an error - * (e.g. EAGAIN) - */ - int udp_recv(char* data, size_t max_length); - - /** - * @brief This hooks the ssl_client, returning the file - * descriptor if we want to send buffered data, or - * -1 if there is nothing to send - * - * @return int file descriptor or -1 - */ - dpp::socket want_write(); - - /** - * @brief This hooks the ssl_client, returning the file - * descriptor if we want to receive buffered data, or - * -1 if we are not wanting to receive - * - * @return int file descriptor or -1 - */ - dpp::socket want_read(); - - /** - * @brief Called by ssl_client when the socket is ready - * for writing, at this point we pick the head item off - * the buffer and send it. So long as it doesn't error - * completely, we pop it off the head of the queue. - */ - void write_ready(); - - /** - * @brief Called by ssl_client when there is data to be - * read. At this point we insert that data into the - * input queue. - */ - void read_ready(); - - /** - * @brief Send data to the UDP socket, using the buffer. - * - * @param packet packet data - * @param len length of packet - * @param duration duration of opus packet - */ - void send(const char* packet, size_t len, uint64_t duration); - - /** - * @brief Queue a message to be sent via the websocket - * - * @param j The JSON data of the message to be sent - * @param to_front If set to true, will place the message at the front of the queue not the back - * (this is for urgent messages such as heartbeat, presence, so they can take precedence over - * chunk requests etc) - */ - void queue_message(const std::string &j, bool to_front = false); - - /** - * @brief Clear the outbound message queue - * - */ - void clear_queue(); - - /** - * @brief Get the size of the outbound message queue - * - * @return The size of the queue - */ - size_t get_queue_size(); - - /** - * @brief Encode a byte buffer using opus codec. - * Multiple opus frames (2880 bytes each) will be encoded into one packet for sending. - * - * @param input Input data as raw bytes of PCM data - * @param inDataSize Input data length - * @param output Output data as an opus encoded packet - * @param outDataSize Output data length, should be at least equal to the input size. - * Will be adjusted on return to the actual compressed data size. - * @return size_t The compressed data size that was encoded. - * @throw dpp::voice_exception If data length to encode is invalid or voice support not compiled into D++ - */ - size_t encode(uint8_t *input, size_t inDataSize, uint8_t *output, size_t &outDataSize); - -public: - - /** - * @brief Owning cluster - */ - class dpp::cluster* creator; - - /** - * @brief This needs to be static, we only initialise libsodium once per program start, - * so initialising it on first use in a voice connection is best. - */ - static bool sodium_initialised; - - /** - * @brief True when the thread is shutting down - */ - bool terminating; - - /** - * @brief Heartbeat interval for sending heartbeat keepalive - */ - uint32_t heartbeat_interval; - - /** - * @brief Last voice channel websocket heartbeat - */ - time_t last_heartbeat; - - /** - * @brief Thread ID - */ - std::thread::native_handle_type thread_id; - - /** - * @brief Discord voice session token - */ - std::string token; - - /** - * @brief Discord voice session id - */ - std::string sessionid; - - /** - * @brief Server ID - */ - snowflake server_id; - - /** - * @brief Channel ID - */ - snowflake channel_id; - - /** - * @brief The audio type to be sent. The default type is recorded audio. - * - * If the audio is recorded, the sending of audio packets is throttled. - * Otherwise, if the audio is live, the sending is not throttled. - * - * Discord voice engine is expecting audio data as if they were from - * some audio device, e.g. microphone, where the data become available - * as they get captured from the audio device. - * - * In case of recorded audio, unlike from a device, the audio data are - * usually instantly available in large chunks. Throttling is needed to - * simulate audio data coming from an audio device. In case of live audio, - * the throttling is by nature, so no extra throttling is needed. - * - * Using live audio mode for recorded audio can cause Discord to skip - * audio data because Discord does not expect to receive, say, 3 minutes' - * worth of audio data in 1 second. - * - * There are some inaccuracies in the throttling method used by the recorded - * audio mode on some systems (mainly Windows) which causes gaps and stutters - * in the resulting audio stream. The overlap audio mode provides a different - * implementation that fixes the issue. This method is slightly more CPU - * intensive, and should only be used if you encounter issues with recorded audio - * on your system. - * - * Use discord_voice_client::set_send_audio_type to change this value as - * it ensures thread safety. - */ - enum send_audio_type_t - { - satype_recorded_audio, - satype_live_audio, - satype_overlap_audio - } send_audio_type = satype_recorded_audio; - - /** - * @brief Sets the gain for the specified user. - * - * Similar to the User Volume slider, controls the listening volume per user. - * Uses native Opus gain control, so clients don't have to perform extra - * audio processing. - * - * The gain setting will affect the both individual and combined voice audio. - * - * The gain value can also be set even before the user connects to the voice - * channel. - * - * @param user_id The ID of the user where the gain is to be controlled. - * @param factor Nonnegative factor to scale the amplitude by, where 1.f reverts - * to the default volume. - */ - void set_user_gain(snowflake user_id, float factor); - - /** - * @brief Log a message to whatever log the user is using. - * The logged message is passed up the chain to the on_log event in user code which can then do whatever - * it wants to do with it. - * @param severity The log level from dpp::loglevel - * @param msg The log message to output - */ - virtual void log(dpp::loglevel severity, const std::string &msg) const; - - /** - * @brief Fires every second from the underlying socket I/O loop, used for sending heartbeats - * @throw dpp::exception if the socket needs to disconnect - */ - virtual void one_second_timer(); - - /** - * @brief voice client is ready to stream audio. - * The voice client is considered ready if it has a secret key. - * - * @return true if ready to stream audio - */ - bool is_ready(); - - /** - * @brief Returns true if the voice client is connected to the websocket - * - * @return True if connected - */ - bool is_connected(); - - /** - * @brief Returns the connection time of the voice client - * - * @return dpp::utility::uptime Detail of how long the voice client has been connected for - */ - dpp::utility::uptime get_uptime(); - - /** Constructor takes shard id, max shards and token. - * @param _cluster The cluster which owns this voice connection, for related logging, REST requests etc - * @param _channel_id The channel id to identify the voice connection as - * @param _server_id The server id (guild id) to identify the voice connection as - * @param _token The voice session token to use for identifying to the websocket - * @param _session_id The voice session id to identify with - * @param _host The voice server hostname to connect to (hostname:port format) - * @throw dpp::voice_exception Sodium or Opus failed to initialise, or D++ is not compiled with voice support - */ - discord_voice_client(dpp::cluster* _cluster, snowflake _channel_id, snowflake _server_id, const std::string &_token, const std::string &_session_id, const std::string &_host); - - /** - * @brief Destroy the discord voice client object - */ - virtual ~discord_voice_client(); - - /** - * @brief Handle JSON from the websocket. - * @param buffer The entire buffer content from the websocket client - * @return bool True if a frame has been handled - * @throw dpp::exception If there was an error processing the frame, or connection to UDP socket failed - */ - virtual bool handle_frame(const std::string &buffer); - - /** - * @brief Handle a websocket error. - * @param errorcode The error returned from the websocket - */ - virtual void error(uint32_t errorcode); - - /** - * @brief Start and monitor I/O loop - */ - void run(); - - /** - * @brief Send raw audio to the voice channel. - * - * You should send an audio packet of 11520 bytes. - * Note that this function can be costly as it has to opus encode - * the PCM audio on the fly, and also encrypt it with libsodium. - * - * @note Because this function encrypts and encodes packets before - * pushing them onto the output queue, if you have a complete stream - * ready to send and know its length it is advisable to call this - * method multiple times to enqueue the entire stream audio so that - * it is all encoded at once (unless you have set use_opus to false). - * Constantly calling this from the dpp::on_voice_buffer_send callback - * can and will eat a TON of cpu! - * - * @param audio_data Raw PCM audio data. Channels are interleaved, - * with each channel's amplitude being a 16 bit value. - * - * The audio data should be 48000Hz signed 16 bit audio. - * - * @param length The length of the audio data. The length should - * be a multiple of 4 (2x 16 bit stereo channels) with a maximum - * length of 11520, which is a complete opus frame at highest - * quality. - * - * @return discord_voice_client& Reference to self - * - * @throw dpp::voice_exception If data length is invalid or voice support not compiled into D++ - */ - discord_voice_client& send_audio_raw(uint16_t* audio_data, const size_t length); - - /** - * @brief Send opus packets to the voice channel - * - * Some containers such as .ogg may contain OPUS - * encoded data already. In this case, we don't need to encode the - * frames using opus here. We can bypass the codec, only applying - * libsodium to the stream. - * - * @param opus_packet Opus packets. Discord expects opus frames - * to be encoded at 48000Hz - * - * @param length The length of the audio data. - * - * @param duration Generally duration is 2.5, 5, 10, 20, 40 or 60 - * if the timescale is 1000000 (1ms) - * - * @return discord_voice_client& Reference to self - * - * @note It is your responsibility to ensure that packets of data - * sent to send_audio are correctly repacketized for streaming, - * e.g. that audio frames are not too large or contain - * an incorrect format. Discord will still expect the same frequency - * and bit width of audio and the same signedness. - * - * @throw dpp::voice_exception If data length is invalid or voice support not compiled into D++ - */ - discord_voice_client& send_audio_opus(uint8_t* opus_packet, const size_t length, uint64_t duration); - - /** - * @brief Send opus packets to the voice channel - * - * Some containers such as .ogg may contain OPUS - * encoded data already. In this case, we don't need to encode the - * frames using opus here. We can bypass the codec, only applying - * libsodium to the stream. - * - * Duration is calculated internally - * - * @param opus_packet Opus packets. Discord expects opus frames - * to be encoded at 48000Hz - * - * @param length The length of the audio data. - * - * @return discord_voice_client& Reference to self - * - * @note It is your responsibility to ensure that packets of data - * sent to send_audio are correctly repacketized for streaming, - * e.g. that audio frames are not too large or contain - * an incorrect format. Discord will still expect the same frequency - * and bit width of audio and the same signedness. - * - * @throw dpp::voice_exception If data length is invalid or voice support not compiled into D++ - */ - discord_voice_client& send_audio_opus(uint8_t* opus_packet, const size_t length); - - /** - * @brief Send silence to the voice channel - * - * @param duration How long to send silence for. With the standard - * timescale this is in milliseconds. Allowed values are 2.5, - * 5, 10, 20, 40 or 60 milliseconds. - * @return discord_voice_client& Reference to self - * @throw dpp::voice_exception if voice support is not compiled into D++ - */ - discord_voice_client& send_silence(const uint64_t duration); - - /** - * @brief Sets the audio type that will be sent with send_audio_* methods. - * - * @see send_audio_type_t - */ - discord_voice_client& set_send_audio_type(send_audio_type_t type); - - /** - * @brief Set the timescale in nanoseconds. - * - * @param new_timescale Timescale to set. This defaults to 1000000, - * which means 1 millisecond. - * @return discord_voice_client& Reference to self - * @throw dpp::voice_exception If data length is invalid or voice support not compiled into D++ - */ - discord_voice_client& set_timescale(uint64_t new_timescale); - - /** - * @brief Get the current timescale, this will default to 1000000 - * which means 1 millisecond. - * - * @return uint64_t timescale in nanoseconds - */ - uint64_t get_timescale(); - - /** - * @brief Mark the voice connection as 'speaking'. - * This sends a JSON message to the voice websocket which tells discord - * that the user is speaking. The library automatically calls this for you - * whenever you send audio. - * - * @return discord_voice_client& Reference to self - */ - discord_voice_client& speak(); - - /** - * @brief Pause sending of audio - * - * @param pause True to pause, false to resume - * @return reference to self - */ - discord_voice_client& pause_audio(bool pause); - - /** - * @brief Immediately stop all audio. - * Clears the packet queue. - * @return reference to self - */ - discord_voice_client& stop_audio(); - - /** - * @brief Returns true if we are playing audio - * - * @return true if audio is playing - */ - bool is_playing(); - - /** - * @brief Get the number of seconds remaining - * of the audio output buffer - * - * @return float number of seconds remaining - */ - float get_secs_remaining(); - - /** - * @brief Get the number of tracks remaining - * in the output buffer. - * This is calculated by the number of track - * markers plus one. - * @return uint32_t Number of tracks in the - * buffer - */ - uint32_t get_tracks_remaining(); - - /** - * @brief Get the time remaining to send the - * audio output buffer in hours:minutes:seconds - * - * @return dpp::utility::uptime length of buffer - */ - dpp::utility::uptime get_remaining(); - - /** - * @brief Insert a track marker into the audio - * output buffer. - * A track marker is an arbitrary flag in the - * buffer contents that indicates the end of some - * block of audio of significance to the sender. - * This may be a song from a streaming site, or - * some voice audio/speech, a sound effect, or - * whatever you choose. You can later skip - * to the next marker using the - * dpp::discord_voice_client::skip_to_next_marker - * function. - * @param metadata Arbitrary information related to this - * track - * @return reference to self - */ - discord_voice_client& insert_marker(const std::string& metadata = ""); - - /** - * @brief Skip tp the next track marker, - * previously inserted by using the - * dpp::discord_voice_client::insert_marker - * function. If there are no markers in the - * output buffer, then this skips to the end - * of the buffer and is equivalent to the - * dpp::discord_voice_client::stop_audio - * function. - * @note It is possible to use this function - * while the output stream is paused. - * @return reference to self - */ - discord_voice_client& skip_to_next_marker(); - - /** - * @brief Get the metadata string associated with each inserted marker. - * - * @return const std::vector& list of metadata strings - */ - const std::vector get_marker_metadata(); - - /** - * @brief Returns true if the audio is paused. - * You can unpause with - * dpp::discord_voice_client::pause_audio. - * - * @return true if paused - */ - bool is_paused(); - - /** - * @brief Discord external IP detection. - * @return std::string Your external IP address - * @note This is a blocking operation that waits - * for a single packet from Discord's voice servers. - */ - std::string discover_ip(); -}; - -}; - +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +struct OpusDecoder; +struct OpusEncoder; +struct OpusRepacketizer; + +namespace dpp { + +// Forward declaration +class cluster; + +/** + * @brief An opus-encoded RTP packet to be sent out to a voice channel + */ +struct DPP_EXPORT voice_out_packet { + /** + * @brief Each string is a UDP packet. + * Generally these will be RTP. + */ + std::string packet; + /** + * @brief Duration of packet + */ + uint64_t duration; +}; + +#define AUDIO_TRACK_MARKER (uint16_t)0xFFFF + +#define AUDIO_OVERLAP_SLEEP_SAMPLES 30 + +/** @brief Implements a discord voice connection. + * Each discord_voice_client connects to one voice channel and derives from a websocket client. + */ +class DPP_EXPORT discord_voice_client : public websocket_client +{ + /** + * @brief Mutex for outbound packet stream + */ + std::mutex stream_mutex; + + /** + * @brief Mutex for message queue + */ + std::shared_mutex queue_mutex; + + /** + * @brief Queue of outbound messages + */ + std::deque message_queue; + + /** + * @brief Thread this connection is executing on + */ + std::thread* runner; + + /** + * @brief Run shard loop under a thread + */ + void thread_run(); + + /** + * @brief Last connect time of voice session + */ + time_t connect_time; + + /** + * @brief IP of UDP/RTP endpoint + */ + std::string ip; + + /** + * @brief Port number of UDP/RTP endpoint + */ + uint16_t port; + + /** + * @brief SSRC value + */ + uint64_t ssrc; + + /** + * @brief List of supported audio encoding modes + */ + std::vector modes; + + /** + * @brief Timescale in nanoseconds + */ + uint64_t timescale; + + /** + * @brief Output buffer + */ + std::vector outbuf; + + /** + * @brief Data type of RTP packet sequence number field. + */ + using rtp_seq_t = uint16_t; + using rtp_timestamp_t = uint32_t; + + /** + * @brief Keeps track of the voice payload to deliver to voice handlers. + */ + struct voice_payload { + /** + * @brief The sequence number of the RTP packet that generated this + * voice payload. + */ + rtp_seq_t seq; + /** + * @brief The timestamp of the RTP packet that generated this voice + * payload. + * + * The timestamp is used to detect the order around where sequence + * number wraps around. + */ + rtp_timestamp_t timestamp; + /** + * @brief The event payload that voice handlers receive. + */ + std::unique_ptr vr; + + /** + * @brief For priority_queue sorting. + * @return true if "this" has lower priority that "other", + * i.e. appears later in the queue; false otherwise. + */ + bool operator<(const voice_payload& other) const; + }; + + struct voice_payload_parking_lot { + /** + * @brief The range of RTP packet sequence number and timestamp in the lot. + * + * The minimum is used to drop packets that arrive too late. Packets + * less than the minimum have been delivered to voice handlers and + * there is no going back. Unfortunately we just have to drop them. + * + * The maximum is used, at flush time, to calculate the minimum for + * the next batch. The maximum is also updated every time we receive an + * RTP packet with a larger value. + */ + struct seq_range_t { + rtp_seq_t min_seq, max_seq; + rtp_timestamp_t min_timestamp, max_timestamp; + } range; + /** + * @brief The queue of parked voice payloads. + * + * We group payloads and deliver them to handlers periodically as the + * handling of out-of-order RTP packets. Payloads in between flushes + * are parked and sorted in this queue. + */ + std::priority_queue parked_payloads; + /** + * @brief The decoder ctls to be set on the decoder. + */ + std::vector> pending_decoder_ctls; + /** + * @brief libopus decoder + * + * Shared with the voice courier thread that does the decoding. + * This is not protected by a mutex because only the courier thread + * uses the decoder. + */ + std::shared_ptr decoder; + }; + /** + * @brief Thread used to deliver incoming voice data to handlers. + */ + std::thread voice_courier; + /** + * @brief Shared state between this voice client and the courier thread. + */ + struct courier_shared_state_t { + /** + * @brief Protects all following members. + */ + std::mutex mtx; + /** + * @brief Signaled when there is a new payload to deliver or terminating state has changed. + */ + std::condition_variable signal_iteration; + /** + * @brief Voice buffers to be reported to handler, grouped by speaker. + * + * Buffers are parked here and flushed every 500ms. + */ + std::map parked_voice_payloads; + /** + * @brief Used to signal termination. + * + * @note Pending payloads are delivered first before termination. + */ + bool terminating = false; + } voice_courier_shared_state; + /** + * @brief The run loop of the voice courier thread. + */ + static void voice_courier_loop(discord_voice_client&, courier_shared_state_t&); + + /** + * @brief If true, audio packet sending is paused + */ + bool paused; + +#ifdef HAVE_VOICE + /** + * @brief libopus encoder + */ + OpusEncoder* encoder; + + /** + * @brief libopus repacketizer + * (merges frames into one packet) + */ + OpusRepacketizer* repacketizer; +#else + /** + * @brief libopus encoder + */ + void* encoder; + + /** + * @brief libopus repacketizer + * (merges frames into one packet) + */ + void* repacketizer; +#endif + + /** + * @brief File descriptor for UDP connection + */ + dpp::socket fd; + + /** + * @brief Secret key for encrypting voice. + * If it has been sent, this is non-null and points to a + * sequence of exactly 32 bytes. + */ + uint8_t* secret_key; + + /** + * @brief Sequence number of outbound audio. This is incremented + * once per frame sent. + */ + uint16_t sequence; + + /** + * @brief Timestamp value used in outbound audio. Each packet + * has the timestamp value which is incremented to match + * how many frames are sent. + */ + uint32_t timestamp; + + /** + * @brief Last sent packet high-resolution timestamp + */ + std::chrono::high_resolution_clock::time_point last_timestamp; + + /** + * @brief Fraction of the sleep that was not executed after the last audio packet was sent + */ + std::chrono::nanoseconds last_sleep_remainder; + + /** + * @brief Maps receiving ssrc to user id + */ + std::unordered_map ssrc_map; + + /** + * @brief This is set to true if we have started sending audio. + * When this moves from false to true, this causes the + * client to send the 'talking' notification to the websocket. + */ + bool sending; + + /** + * @brief Number of track markers in the buffer. For example if there + * are two track markers in the buffer there are 3 tracks. + * + * **Special case:** + * + * If the buffer is empty, there are zero tracks in the + * buffer. + */ + uint32_t tracks; + + /** + * @brief Meta data associated with each track. + * Arbitrary string that the user can set via + * dpp::discord_voice_client::add_marker + */ + std::vector track_meta; + + /** + * @brief Encoding buffer for opus repacketizer and encode + */ + uint8_t encode_buffer[65536]; + + /** + * @brief Send data to UDP socket immediately. + * + * @param data data to send + * @param length length of data to send + * @return int bytes sent. Will return -1 if we cannot send + */ + int udp_send(const char* data, size_t length); + + /** + * @brief Receive data from UDP socket immediately. + * + * @param data data to receive + * @param max_length size of data receiving buffer + * @return int bytes received. -1 if there is an error + * (e.g. EAGAIN) + */ + int udp_recv(char* data, size_t max_length); + + /** + * @brief This hooks the ssl_client, returning the file + * descriptor if we want to send buffered data, or + * -1 if there is nothing to send + * + * @return int file descriptor or -1 + */ + dpp::socket want_write(); + + /** + * @brief This hooks the ssl_client, returning the file + * descriptor if we want to receive buffered data, or + * -1 if we are not wanting to receive + * + * @return int file descriptor or -1 + */ + dpp::socket want_read(); + + /** + * @brief Called by ssl_client when the socket is ready + * for writing, at this point we pick the head item off + * the buffer and send it. So long as it doesn't error + * completely, we pop it off the head of the queue. + */ + void write_ready(); + + /** + * @brief Called by ssl_client when there is data to be + * read. At this point we insert that data into the + * input queue. + */ + void read_ready(); + + /** + * @brief Send data to the UDP socket, using the buffer. + * + * @param packet packet data + * @param len length of packet + * @param duration duration of opus packet + */ + void send(const char* packet, size_t len, uint64_t duration); + + /** + * @brief Queue a message to be sent via the websocket + * + * @param j The JSON data of the message to be sent + * @param to_front If set to true, will place the message at the front of the queue not the back + * (this is for urgent messages such as heartbeat, presence, so they can take precedence over + * chunk requests etc) + */ + void queue_message(const std::string &j, bool to_front = false); + + /** + * @brief Clear the outbound message queue + * + */ + void clear_queue(); + + /** + * @brief Get the size of the outbound message queue + * + * @return The size of the queue + */ + size_t get_queue_size(); + + /** + * @brief Encode a byte buffer using opus codec. + * Multiple opus frames (2880 bytes each) will be encoded into one packet for sending. + * + * @param input Input data as raw bytes of PCM data + * @param inDataSize Input data length + * @param output Output data as an opus encoded packet + * @param outDataSize Output data length, should be at least equal to the input size. + * Will be adjusted on return to the actual compressed data size. + * @return size_t The compressed data size that was encoded. + * @throw dpp::voice_exception If data length to encode is invalid or voice support not compiled into D++ + */ + size_t encode(uint8_t *input, size_t inDataSize, uint8_t *output, size_t &outDataSize); + +public: + + /** + * @brief Owning cluster + */ + class dpp::cluster* creator; + + /** + * @brief This needs to be static, we only initialise libsodium once per program start, + * so initialising it on first use in a voice connection is best. + */ + static bool sodium_initialised; + + /** + * @brief True when the thread is shutting down + */ + bool terminating; + + /** + * @brief Heartbeat interval for sending heartbeat keepalive + */ + uint32_t heartbeat_interval; + + /** + * @brief Last voice channel websocket heartbeat + */ + time_t last_heartbeat; + + /** + * @brief Thread ID + */ + std::thread::native_handle_type thread_id; + + /** + * @brief Discord voice session token + */ + std::string token; + + /** + * @brief Discord voice session id + */ + std::string sessionid; + + /** + * @brief Server ID + */ + snowflake server_id; + + /** + * @brief Channel ID + */ + snowflake channel_id; + + /** + * @brief The audio type to be sent. The default type is recorded audio. + * + * If the audio is recorded, the sending of audio packets is throttled. + * Otherwise, if the audio is live, the sending is not throttled. + * + * Discord voice engine is expecting audio data as if they were from + * some audio device, e.g. microphone, where the data become available + * as they get captured from the audio device. + * + * In case of recorded audio, unlike from a device, the audio data are + * usually instantly available in large chunks. Throttling is needed to + * simulate audio data coming from an audio device. In case of live audio, + * the throttling is by nature, so no extra throttling is needed. + * + * Using live audio mode for recorded audio can cause Discord to skip + * audio data because Discord does not expect to receive, say, 3 minutes' + * worth of audio data in 1 second. + * + * There are some inaccuracies in the throttling method used by the recorded + * audio mode on some systems (mainly Windows) which causes gaps and stutters + * in the resulting audio stream. The overlap audio mode provides a different + * implementation that fixes the issue. This method is slightly more CPU + * intensive, and should only be used if you encounter issues with recorded audio + * on your system. + * + * Use discord_voice_client::set_send_audio_type to change this value as + * it ensures thread safety. + */ + enum send_audio_type_t + { + satype_recorded_audio, + satype_live_audio, + satype_overlap_audio + } send_audio_type = satype_recorded_audio; + + /** + * @brief Sets the gain for the specified user. + * + * Similar to the User Volume slider, controls the listening volume per user. + * Uses native Opus gain control, so clients don't have to perform extra + * audio processing. + * + * The gain setting will affect the both individual and combined voice audio. + * + * The gain value can also be set even before the user connects to the voice + * channel. + * + * @param user_id The ID of the user where the gain is to be controlled. + * @param factor Nonnegative factor to scale the amplitude by, where 1.f reverts + * to the default volume. + */ + void set_user_gain(snowflake user_id, float factor); + + /** + * @brief Log a message to whatever log the user is using. + * The logged message is passed up the chain to the on_log event in user code which can then do whatever + * it wants to do with it. + * @param severity The log level from dpp::loglevel + * @param msg The log message to output + */ + virtual void log(dpp::loglevel severity, const std::string &msg) const; + + /** + * @brief Fires every second from the underlying socket I/O loop, used for sending heartbeats + * @throw dpp::exception if the socket needs to disconnect + */ + virtual void one_second_timer(); + + /** + * @brief voice client is ready to stream audio. + * The voice client is considered ready if it has a secret key. + * + * @return true if ready to stream audio + */ + bool is_ready(); + + /** + * @brief Returns true if the voice client is connected to the websocket + * + * @return True if connected + */ + bool is_connected(); + + /** + * @brief Returns the connection time of the voice client + * + * @return dpp::utility::uptime Detail of how long the voice client has been connected for + */ + dpp::utility::uptime get_uptime(); + + /** Constructor takes shard id, max shards and token. + * @param _cluster The cluster which owns this voice connection, for related logging, REST requests etc + * @param _channel_id The channel id to identify the voice connection as + * @param _server_id The server id (guild id) to identify the voice connection as + * @param _token The voice session token to use for identifying to the websocket + * @param _session_id The voice session id to identify with + * @param _host The voice server hostname to connect to (hostname:port format) + * @throw dpp::voice_exception Sodium or Opus failed to initialise, or D++ is not compiled with voice support + */ + discord_voice_client(dpp::cluster* _cluster, snowflake _channel_id, snowflake _server_id, const std::string &_token, const std::string &_session_id, const std::string &_host); + + /** + * @brief Destroy the discord voice client object + */ + virtual ~discord_voice_client(); + + /** + * @brief Handle JSON from the websocket. + * @param buffer The entire buffer content from the websocket client + * @return bool True if a frame has been handled + * @throw dpp::exception If there was an error processing the frame, or connection to UDP socket failed + */ + virtual bool handle_frame(const std::string &buffer); + + /** + * @brief Handle a websocket error. + * @param errorcode The error returned from the websocket + */ + virtual void error(uint32_t errorcode); + + /** + * @brief Start and monitor I/O loop + */ + void run(); + + /** + * @brief Send raw audio to the voice channel. + * + * You should send an audio packet of 11520 bytes. + * Note that this function can be costly as it has to opus encode + * the PCM audio on the fly, and also encrypt it with libsodium. + * + * @note Because this function encrypts and encodes packets before + * pushing them onto the output queue, if you have a complete stream + * ready to send and know its length it is advisable to call this + * method multiple times to enqueue the entire stream audio so that + * it is all encoded at once (unless you have set use_opus to false). + * Constantly calling this from the dpp::on_voice_buffer_send callback + * can and will eat a TON of cpu! + * + * @param audio_data Raw PCM audio data. Channels are interleaved, + * with each channel's amplitude being a 16 bit value. + * + * The audio data should be 48000Hz signed 16 bit audio. + * + * @param length The length of the audio data. The length should + * be a multiple of 4 (2x 16 bit stereo channels) with a maximum + * length of 11520, which is a complete opus frame at highest + * quality. + * + * @return discord_voice_client& Reference to self + * + * @throw dpp::voice_exception If data length is invalid or voice support not compiled into D++ + */ + discord_voice_client& send_audio_raw(uint16_t* audio_data, const size_t length); + + /** + * @brief Send opus packets to the voice channel + * + * Some containers such as .ogg may contain OPUS + * encoded data already. In this case, we don't need to encode the + * frames using opus here. We can bypass the codec, only applying + * libsodium to the stream. + * + * @param opus_packet Opus packets. Discord expects opus frames + * to be encoded at 48000Hz + * + * @param length The length of the audio data. + * + * @param duration Generally duration is 2.5, 5, 10, 20, 40 or 60 + * if the timescale is 1000000 (1ms) + * + * @return discord_voice_client& Reference to self + * + * @note It is your responsibility to ensure that packets of data + * sent to send_audio are correctly repacketized for streaming, + * e.g. that audio frames are not too large or contain + * an incorrect format. Discord will still expect the same frequency + * and bit width of audio and the same signedness. + * + * @throw dpp::voice_exception If data length is invalid or voice support not compiled into D++ + */ + discord_voice_client& send_audio_opus(uint8_t* opus_packet, const size_t length, uint64_t duration); + + /** + * @brief Send opus packets to the voice channel + * + * Some containers such as .ogg may contain OPUS + * encoded data already. In this case, we don't need to encode the + * frames using opus here. We can bypass the codec, only applying + * libsodium to the stream. + * + * Duration is calculated internally + * + * @param opus_packet Opus packets. Discord expects opus frames + * to be encoded at 48000Hz + * + * @param length The length of the audio data. + * + * @return discord_voice_client& Reference to self + * + * @note It is your responsibility to ensure that packets of data + * sent to send_audio are correctly repacketized for streaming, + * e.g. that audio frames are not too large or contain + * an incorrect format. Discord will still expect the same frequency + * and bit width of audio and the same signedness. + * + * @throw dpp::voice_exception If data length is invalid or voice support not compiled into D++ + */ + discord_voice_client& send_audio_opus(uint8_t* opus_packet, const size_t length); + + /** + * @brief Send silence to the voice channel + * + * @param duration How long to send silence for. With the standard + * timescale this is in milliseconds. Allowed values are 2.5, + * 5, 10, 20, 40 or 60 milliseconds. + * @return discord_voice_client& Reference to self + * @throw dpp::voice_exception if voice support is not compiled into D++ + */ + discord_voice_client& send_silence(const uint64_t duration); + + /** + * @brief Sets the audio type that will be sent with send_audio_* methods. + * + * @see send_audio_type_t + */ + discord_voice_client& set_send_audio_type(send_audio_type_t type); + + /** + * @brief Set the timescale in nanoseconds. + * + * @param new_timescale Timescale to set. This defaults to 1000000, + * which means 1 millisecond. + * @return discord_voice_client& Reference to self + * @throw dpp::voice_exception If data length is invalid or voice support not compiled into D++ + */ + discord_voice_client& set_timescale(uint64_t new_timescale); + + /** + * @brief Get the current timescale, this will default to 1000000 + * which means 1 millisecond. + * + * @return uint64_t timescale in nanoseconds + */ + uint64_t get_timescale(); + + /** + * @brief Mark the voice connection as 'speaking'. + * This sends a JSON message to the voice websocket which tells discord + * that the user is speaking. The library automatically calls this for you + * whenever you send audio. + * + * @return discord_voice_client& Reference to self + */ + discord_voice_client& speak(); + + /** + * @brief Pause sending of audio + * + * @param pause True to pause, false to resume + * @return reference to self + */ + discord_voice_client& pause_audio(bool pause); + + /** + * @brief Immediately stop all audio. + * Clears the packet queue. + * @return reference to self + */ + discord_voice_client& stop_audio(); + + /** + * @brief Returns true if we are playing audio + * + * @return true if audio is playing + */ + bool is_playing(); + + /** + * @brief Get the number of seconds remaining + * of the audio output buffer + * + * @return float number of seconds remaining + */ + float get_secs_remaining(); + + /** + * @brief Get the number of tracks remaining + * in the output buffer. + * This is calculated by the number of track + * markers plus one. + * @return uint32_t Number of tracks in the + * buffer + */ + uint32_t get_tracks_remaining(); + + /** + * @brief Get the time remaining to send the + * audio output buffer in hours:minutes:seconds + * + * @return dpp::utility::uptime length of buffer + */ + dpp::utility::uptime get_remaining(); + + /** + * @brief Insert a track marker into the audio + * output buffer. + * A track marker is an arbitrary flag in the + * buffer contents that indicates the end of some + * block of audio of significance to the sender. + * This may be a song from a streaming site, or + * some voice audio/speech, a sound effect, or + * whatever you choose. You can later skip + * to the next marker using the + * dpp::discord_voice_client::skip_to_next_marker + * function. + * @param metadata Arbitrary information related to this + * track + * @return reference to self + */ + discord_voice_client& insert_marker(const std::string& metadata = ""); + + /** + * @brief Skip tp the next track marker, + * previously inserted by using the + * dpp::discord_voice_client::insert_marker + * function. If there are no markers in the + * output buffer, then this skips to the end + * of the buffer and is equivalent to the + * dpp::discord_voice_client::stop_audio + * function. + * @note It is possible to use this function + * while the output stream is paused. + * @return reference to self + */ + discord_voice_client& skip_to_next_marker(); + + /** + * @brief Get the metadata string associated with each inserted marker. + * + * @return const std::vector& list of metadata strings + */ + const std::vector get_marker_metadata(); + + /** + * @brief Returns true if the audio is paused. + * You can unpause with + * dpp::discord_voice_client::pause_audio. + * + * @return true if paused + */ + bool is_paused(); + + /** + * @brief Discord external IP detection. + * @return std::string Your external IP address + * @note This is a blocking operation that waits + * for a single packet from Discord's voice servers. + */ + std::string discover_ip(); +}; + +}; + diff --git a/3rdParty/dpp/dispatcher.h b/3rdParty/dpp/dispatcher.h index ed3a135ee7..7f595dcd38 100644 --- a/3rdParty/dpp/dispatcher.h +++ b/3rdParty/dpp/dispatcher.h @@ -1,1779 +1,1779 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/* Forward declaration */ -struct confirmation_callback_t; - -/** - * @brief A function used as a callback for any REST based command - */ -typedef std::function command_completion_event_t; - -/** @brief Base event parameter struct. - * Each event you receive from the library will have its parameter derived from this class. - * The class contains the raw event data, and a pointer to the current shard's dpp::discord_client object. - * You can also use this object to cancel the current event, meaning that any listeners after yours do - * not get notified of the current event if you call it. - */ -struct DPP_EXPORT event_dispatch_t { - /** - * @brief Raw event data. - * If you are using json on your websocket, this will contain json, and if you are using - * ETF as your websocket protocol, it will contain raw ETF data. - */ - const std::string raw_event; - - /** - * @brief Shard the event came from. - * Note that for some events, notably voice events, this may be nullptr. - */ - class discord_client* from; - - /** - * @brief Construct a new event_dispatch_t object - * - * @param client The shard the event originated on. May be a nullptr, e.g. for voice events - * @param raw Raw event data as JSON or ETF - */ - event_dispatch_t(class discord_client* client, const std::string& raw); - - /** - * @brief Cancels the event in progress. Any other attached lambdas for this event after this one are not called. - * Note that event cancellation is a thread local state, and not stored in the object (because object which can - * be cancelled is `const` during the event, and cannot itself contain the changeable state). - * @return const event_dispatch_t& reference to self for chaining - */ - const event_dispatch_t& cancel_event() const; - - /** - * @brief Returns true if the event is cancelled. - * Note that event cancellation is a thread local state, and not stored in the object (because object which can - * be cancelled is `const` during the event, and cannot itself contain the changeable state). - * @return true if the event is cancelled - */ - bool is_cancelled() const; -}; - -/** @brief Log messages */ -struct DPP_EXPORT log_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - log_t(class discord_client* client, const std::string& raw); - /** Severity */ - loglevel severity; - /** Log Message */ - std::string message; - - log_t(const log_t&) = default; -}; - -namespace utility { - /** - * @brief Get a default logger that outputs to std::cout. - * e.g. - * ``` - * bot.on_log(dpp::utility::cout_logger()); - * ``` - * - * @return A logger for attaching to on_log - */ - std::function DPP_EXPORT cout_logger(); - - /** - * @brief The default callback handler for API calls. - * on error, sends the error to the logger. - * - * @return A lambda for attaching to an API callback - */ - std::function DPP_EXPORT log_error(); -}; - -/** @brief Add user to scheduled event */ -struct DPP_EXPORT guild_scheduled_event_user_add_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - guild_scheduled_event_user_add_t(class discord_client* client, const std::string& raw); - /** - * @brief event user added to - */ - snowflake event_id; - - /** - * @brief User being added - * - */ - snowflake user_id; - - /** - * @brief Guild being added to - * - */ - snowflake guild_id; -}; - -/** @brief Delete user from scheduled event */ -struct DPP_EXPORT guild_scheduled_event_user_remove_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - guild_scheduled_event_user_remove_t(class discord_client* client, const std::string& raw); - /** - * @brief event user removed from - */ - snowflake event_id; - - /** - * @brief User being removed - * - */ - snowflake user_id; - - /** - * @brief Guild being removed from - * - */ - snowflake guild_id; -}; - -/** @brief Create scheduled event */ -struct DPP_EXPORT guild_scheduled_event_create_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - guild_scheduled_event_create_t(class discord_client* client, const std::string& raw); - /** - * @brief created event - */ - scheduled_event created; -}; - -/** @brief Create scheduled event */ -struct DPP_EXPORT guild_scheduled_event_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - guild_scheduled_event_update_t(class discord_client* client, const std::string& raw); - /** - * @brief updated event - */ - scheduled_event updated; -}; - -/** @brief Delete scheduled event */ -struct DPP_EXPORT guild_scheduled_event_delete_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - guild_scheduled_event_delete_t(class discord_client* client, const std::string& raw); - /** - * @brief deleted event - */ - scheduled_event deleted; -}; - -/** @brief Create automod rule */ -struct DPP_EXPORT automod_rule_create_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - automod_rule_create_t(class discord_client* client, const std::string& raw); - /** - * @brief updated event - */ - automod_rule created; -}; - -/** @brief Update automod rule */ -struct DPP_EXPORT automod_rule_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - automod_rule_update_t(class discord_client* client, const std::string& raw); - /** - * @brief updated event - */ - automod_rule updated; -}; - -/** @brief Delete automod rule */ -struct DPP_EXPORT automod_rule_delete_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - automod_rule_delete_t(class discord_client* client, const std::string& raw); - /** - * @brief updated event - */ - automod_rule deleted; -}; - -/** @brief Execute/trigger automod rule */ -struct DPP_EXPORT automod_rule_execute_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - automod_rule_execute_t(class discord_client* client, const std::string& raw); - - snowflake guild_id; //!< the id of the guild in which action was executed - automod_action action; //!< the action which was executed - snowflake rule_id; //!< the id of the rule which action belongs to - automod_trigger_type rule_trigger_type; //!< the trigger type of rule which was triggered - snowflake user_id; //!< the id of the user which generated the content which triggered the rule - snowflake channel_id; //!< Optional: the id of the channel in which user content was posted - snowflake message_id; //!< Optional: the id of any user message which content belongs to - snowflake alert_system_message_id; //!< Optional: the id of any system auto moderation messages posted as a result of this action - std::string content; //!< the user generated text content - std::string matched_keyword; //!< the word or phrase configured in the rule that triggered the rule (may be empty) - std::string matched_content; //!< the substring in content that triggered the rule (may be empty) -}; - - - -/** @brief Create stage instance */ -struct DPP_EXPORT stage_instance_create_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - stage_instance_create_t(class discord_client* client, const std::string& raw); - /** - * @brief created stage instance - */ - stage_instance created; -}; - -/** @brief Update stage instance */ -struct DPP_EXPORT stage_instance_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - stage_instance_update_t(class discord_client* client, const std::string& raw); - /** - * @brief updated stage instance - */ - stage_instance updated; -}; - -/** @brief Delete stage instance */ -struct DPP_EXPORT stage_instance_delete_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - stage_instance_delete_t(class discord_client* client, const std::string& raw); - /** - * @brief deleted stage instance - */ - stage_instance deleted; -}; - -/** @brief Voice state update */ -struct DPP_EXPORT voice_state_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - voice_state_update_t(class discord_client* client, const std::string& raw); - /** Voice state */ - voicestate state; -}; - -/** - * @brief Create interaction - */ -struct DPP_EXPORT interaction_create_t : public event_dispatch_t { - - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - interaction_create_t(class discord_client* client, const std::string& raw); - - - /** - * @brief Acknowledge interaction without displaying a message to the user, - * for use with button and select menu components. - * - * @param callback User function to execute when the api call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void reply(command_completion_event_t callback = utility::log_error()) const; - - /** - * @brief Send a reply for this interaction - * - * @param t Type of reply to send - * @param m Message object to send. Not all fields are supported by Discord. - * @param callback User function to execute when the api call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void reply(interaction_response_type t, const message & m, command_completion_event_t callback = utility::log_error()) const; - - /** - * @brief Send a reply for this interaction - * - * @param t Type of reply to send - * @param mt The string value to send, for simple text only messages - * @param callback User function to execute when the api call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void reply(interaction_response_type t, const std::string & mt, command_completion_event_t callback = utility::log_error()) const; - - /** - * @brief Send a reply for this interaction. - * Uses the default type of dpp::ir_channel_message_with_source, a simple message reply. - * - * @param m Message object to send. Not all fields are supported by Discord. - * @param callback User function to execute when the api call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void reply(const message & m, command_completion_event_t callback = utility::log_error()) const; - - /** - * @brief Send a reply for this interaction. - * Uses the default type of dpp::ir_channel_message_with_source, a simple message reply. - * - * @param mt The string value to send, for simple text only messages - * @param callback User function to execute when the api call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void reply(const std::string & mt, command_completion_event_t callback = utility::log_error()) const; - - /** - * @brief Reply to interaction with a dialog box - * - * @param mr Dialog box response to send - * @param callback User function to execute when the api call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void dialog(const interaction_modal_response& mr, command_completion_event_t callback = utility::log_error()) const; - - /** - * @brief Edit the response for this interaction - * - * @param m Message object to send. Not all fields are supported by Discord. - * @param callback User function to execute when the api call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void edit_response(const message & m, command_completion_event_t callback = utility::log_error()) const; - - /** - * @brief Edit the response for this interaction - * - * @param mt The string value to send, for simple text only messages - * @param callback User function to execute when the api call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void edit_response(const std::string & mt, command_completion_event_t callback = utility::log_error()) const; - - /** - * @brief Set the bot to 'thinking' state - * - * @param ephemeral True if the thinking state should be ephemeral - * @param callback User function to execute when the api call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void thinking(bool ephemeral = false, command_completion_event_t callback = utility::log_error()) const; - - /** - * @brief Get original response message for this interaction - * - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void get_original_response(command_completion_event_t callback) const; - - /** - * @brief Edit original response message for this interaction - * - * @param m Message object to send. Not all fields are supported by Discord. - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void edit_original_response(const message & m, command_completion_event_t callback = utility::log_error()) const; - - /** - * @brief Delete original response message for this interaction. This cannot be used on an ephemeral interaction response. - * - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void delete_original_response(command_completion_event_t callback = utility::log_error()) const; - - /** - * @brief Get a command line parameter - * - * @param name The command line parameter to retrieve - * @return const command_value& If the command line parameter does not - * exist, an empty variant is returned. - */ - const virtual command_value& get_parameter(const std::string& name) const; - - /** - * @brief command interaction - */ - interaction command; - - /** - * @brief Destroy this object - */ - virtual ~interaction_create_t() = default; -}; - -/** - * @brief User has issued a slash command - */ -struct DPP_EXPORT slashcommand_t : public interaction_create_t { -public: - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - slashcommand_t(class discord_client* client, const std::string& raw); -}; - -/** - * @brief Click on button - */ -struct DPP_EXPORT button_click_t : public interaction_create_t { - - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - button_click_t(class discord_client* client, const std::string& raw); - - /** - * @brief Get a command line parameter - * - * @param name The command line parameter to retrieve - * @return Always returns an empty parameter as buttons dont have parameters! - */ - const virtual command_value& get_parameter(const std::string& name) const; - /** - * @brief button custom id - */ - std::string custom_id; - /** - * @brief component type - */ - uint8_t component_type; -}; - -struct DPP_EXPORT form_submit_t : public interaction_create_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - form_submit_t(class discord_client* client, const std::string& raw); - - /** - * @brief Get a command line parameter - * - * @param name The command line parameter to retrieve - * @return Always returns an empty parameter as buttons dont have parameters! - */ - const virtual command_value& get_parameter(const std::string& name) const; - /** - * @brief button custom id - */ - std::string custom_id; - /** - * @brief Message components for form reply - */ - std::vector components; -}; - -/** - * @brief Discord requests that we fill a list of auto completion choices for a command option - */ -struct DPP_EXPORT autocomplete_t : public interaction_create_t { - - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - autocomplete_t(class discord_client* client, const std::string& raw); - - /** - * @brief Get a command line parameter - * - * @param name The command line parameter to retrieve - * @return Always returns an empty parameter as auto complete requests dont have parameters! - */ - const virtual command_value& get_parameter(const std::string& name) const; - - /** - * @brief Command ID - */ - dpp::snowflake id; - - /** - * @brief Command name - */ - std::string name; - - /** - * @brief auto completion options - */ - std::vector options; -}; - -/** - * @brief Base class for context menu interactions, e.g. right click on - * user or message. - */ -struct DPP_EXPORT context_menu_t : public interaction_create_t { -public: - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - context_menu_t(class discord_client* client, const std::string& raw); -}; - -/** - * @brief Event parameter for context menu interactions for messages - */ -struct DPP_EXPORT message_context_menu_t : public context_menu_t { - - /** - * @brief Related message - */ - message ctx_message; -public: - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - message_context_menu_t(class discord_client* client, const std::string& raw); - - /** - * @brief Get the message which was right-clicked on - * - * @return message right-clicked on - */ - message get_message() const; - - /** - * @brief Set the message object for this event - * - * @param m message to set - * @return message_context_menu_t& reference to self for fluent chaining - */ - message_context_menu_t& set_message(const message& m); -}; - -/** - * @brief Event parameter for context menu interactions for users - */ -struct DPP_EXPORT user_context_menu_t : public context_menu_t { - - /** - * @brief Related user - */ - user ctx_user; -public: - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - user_context_menu_t(class discord_client* client, const std::string& raw); - - /** - * @brief Get the user which was right-clicked on - * - * @return user right clicked on - */ - user get_user() const; - - /** - * @brief Set the user object for this event - * - * @param u user to set - * @return user_context_menu_t& reference to self for fluent chaining - */ - user_context_menu_t& set_user(const user& u); - -}; - -/** - * @brief Click on select - */ -struct DPP_EXPORT select_click_t : public interaction_create_t { - - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - select_click_t(class discord_client* client, const std::string& raw); - - /** - * @brief Get a command line parameter - * - * @param name The command line parameter to retrieve - * @return Always returns an empty parameter as buttons dont have parameters! - */ - const virtual command_value& get_parameter(const std::string& name) const; - - /** - * @brief select menu custom id - */ - std::string custom_id; - /** - * @brief select menu values - */ - std::vector values; - /** - * @brief select menu component type (dpp::component_type) - */ - uint8_t component_type; -}; - - -/** @brief Delete guild */ -struct DPP_EXPORT guild_delete_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_delete_t(class discord_client* client, const std::string& raw); - /** Deleted guild */ - guild* deleted; -}; - -/** @brief Update guild stickers */ -struct DPP_EXPORT guild_stickers_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_stickers_update_t(class discord_client* client, const std::string& raw); - /** Updating guild */ - guild* updating_guild; - /** - * @brief stickers being updated - */ - std::vector stickers; -}; - -/** @brief Guild join request delete (user declined membership screening) */ -struct DPP_EXPORT guild_join_request_delete_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_join_request_delete_t(class discord_client* client, const std::string& raw); - /** Deleted guild */ - snowflake guild_id; - /** - * @brief user id - */ - snowflake user_id; -}; - -/** @brief Delete channel */ -struct DPP_EXPORT channel_delete_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - channel_delete_t(class discord_client* client, const std::string& raw); - /** - * @brief guild channel is being deleted from - */ - guild* deleting_guild; - /** - * @brief channel being deleted - */ - channel* deleted; -}; - -/** @brief Update channel */ -struct DPP_EXPORT channel_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - channel_update_t(class discord_client* client, const std::string& raw); - /** - * @brief guild channel is being updated on - */ - guild* updating_guild; - /** - * @brief channel being updated - */ - channel* updated; -}; - -/** @brief Session ready */ -struct DPP_EXPORT ready_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - ready_t(class discord_client* client, const std::string& raw); - /** - * @brief websocket session id - */ - std::string session_id; - /** - * @brief shard id - */ - uint32_t shard_id; -}; - -/** @brief Message Deleted */ -struct DPP_EXPORT message_delete_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - message_delete_t(class discord_client* client, const std::string& raw); - /** - * @brief message being deleted - */ - message* deleted; -}; - -/** @brief Guild member remove */ -struct DPP_EXPORT guild_member_remove_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_member_remove_t(class discord_client* client, const std::string& raw); - /** - * @brief guild user is being removed from - */ - guild* removing_guild; - /** - * @brief user being removed - */ - user* removed; -}; - -/** @brief Session resumed */ -struct DPP_EXPORT resumed_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - resumed_t(class discord_client* client, const std::string& raw); - /** - * @brief websocket session id - */ - std::string session_id; - /** - * @brief shard id - */ - uint32_t shard_id; -}; - -/** @brief Guild role create */ -struct DPP_EXPORT guild_role_create_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_role_create_t(class discord_client* client, const std::string& raw); - /** - * @brief guild role is being created on - */ - guild* creating_guild; - /** - * @brief role being created - */ - role* created; -}; - -/** @brief Typing start */ -struct DPP_EXPORT typing_start_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - typing_start_t(class discord_client* client, const std::string& raw); - /** - * @brief guild user is typing on - */ - guild* typing_guild; - /** - * @brief channel user is typing on - */ - channel* typing_channel; - /** - * @brief user who is typing. - * Can be nullptr if user is not cached - */ - user* typing_user; - /** - * @brief User id of user typing. - * Always set regardless of caching - */ - snowflake user_id; - /** - * @brief Time of typing event - */ - time_t timestamp; -}; - -/** @brief Voice state update */ -struct DPP_EXPORT voice_track_marker_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. - * Will always be null. - * @param raw Raw event text as JSON. - * Will always be empty. - */ - voice_track_marker_t(class discord_client* client, const std::string& raw); - /** Voice client */ - class discord_voice_client* voice_client; - /** Track metadata */ - std::string track_meta; -}; - - -/** @brief Message reaction add */ -struct DPP_EXPORT message_reaction_add_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - message_reaction_add_t(class discord_client* client, const std::string& raw); - /** - * @brief Guild reaction occurred on - */ - guild* reacting_guild; - /** - * @brief User who reacted - */ - user reacting_user; - /** - * @brief member data of user who reacted - */ - guild_member reacting_member; - /** - * @brief channel the reaction happened on - */ - channel* reacting_channel; - /** - * @brief emoji of reaction - */ - emoji reacting_emoji; - /** - * @brief message id of the message reacted upon - */ - snowflake message_id; -}; - -/** @brief Guild members chunk */ -struct DPP_EXPORT guild_members_chunk_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_members_chunk_t(class discord_client* client, const std::string& raw); - /** - * @brief guild the members chunk is for - */ - guild* adding; - /** - * @brief list of members in the chunk - */ - guild_member_map* members; -}; - -/** @brief Message reaction remove */ -struct DPP_EXPORT message_reaction_remove_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - message_reaction_remove_t(class discord_client* client, const std::string& raw); - /** - * @brief Guild reaction occurred on - */ - guild* reacting_guild; - /** - * @brief User who reacted - */ - dpp::snowflake reacting_user_id; - /** - * @brief channel the reaction happened on - */ - channel* reacting_channel; - /** - * @brief emoji of reaction - */ - emoji reacting_emoji; - /** - * @brief message id of the message reacted upon - */ - snowflake message_id; -}; - -/** @brief Create guild */ -struct DPP_EXPORT guild_create_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_create_t(class discord_client* client, const std::string& raw); - /** - * @brief guild that was created - */ - guild* created; - /** - * @brief List of presences of all users on the guild. - * - * This is only filled if you have the GUILD_PRESENCES - * privileged intent. - */ - presence_map presences; - /** - * @brief List of scheduled events in the guild - */ - scheduled_event_map scheduled_events; - /** - * @brief List of stage instances in the guild - */ - stage_instance_map stage_instances; - /** - * @brief List of threads in the guild - */ - thread_map threads; - /** - * @brief List of stickers in the guild - */ - sticker_map stickers; -}; - -/** @brief Create channel */ -struct DPP_EXPORT channel_create_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - channel_create_t(class discord_client* client, const std::string& raw); - /** - * @brief guild channel was created on - */ - guild* creating_guild; - /** - * @brief channel that was created - */ - channel* created; -}; - -/** @brief Message remove emoji */ -struct DPP_EXPORT message_reaction_remove_emoji_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - message_reaction_remove_emoji_t(class discord_client* client, const std::string& raw); - /** - * @brief Guild reaction occurred on - */ - guild* reacting_guild; - /** - * @brief channel the reaction happened on - */ - channel* reacting_channel; - /** - * @brief emoji of reaction - */ - emoji reacting_emoji; - /** - * @brief message id of the message reacted upon - */ - snowflake message_id; -}; - -/** @brief Message delete bulk */ -struct DPP_EXPORT message_delete_bulk_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - message_delete_bulk_t(class discord_client* client, const std::string& raw); - /** - * @brief guild messages are being deleted upon - */ - guild* deleting_guild; - /** - * @brief user who is deleting the messages - */ - user* deleting_user; - /** - * @brief channel messages are being deleted from - */ - channel* deleting_channel; - /** - * @brief list of message ids of deleted messages - */ - std::vector deleted; -}; - -/** @brief Guild role update */ -struct DPP_EXPORT guild_role_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_role_update_t(class discord_client* client, const std::string& raw); - /** - * @brief guild where roles are being updated - */ - guild* updating_guild; - /** - * @brief the role being updated - */ - role* updated; -}; - -/** @brief Guild role delete */ -struct DPP_EXPORT guild_role_delete_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_role_delete_t(class discord_client* client, const std::string& raw); - /** - * @brief guild where role is being deleted - */ - guild* deleting_guild; - /** - * @brief role being deleted - */ - role* deleted; - /** - * @brief ID of the deleted role - */ - snowflake role_id; -}; - -/** @brief Channel pins update */ -struct DPP_EXPORT channel_pins_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - channel_pins_update_t(class discord_client* client, const std::string& raw); - /** - * @brief guild where message is being pinned - */ - guild* pin_guild; - /** - * @brief channel where message is being pinned - */ - channel* pin_channel; - /** - * @brief timestamp of pin - */ - time_t timestamp; -}; - -/** @brief Message remove all reactions */ -struct DPP_EXPORT message_reaction_remove_all_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - message_reaction_remove_all_t(class discord_client* client, const std::string& raw); - /** - * @brief Guild reaction occurred on - */ - guild* reacting_guild; - /** - * @brief channel the reaction happened on - */ - channel* reacting_channel; - /** - * @brief message id of the message reacted upon - */ - snowflake message_id; - -}; - -/** @brief Voice server update */ -struct DPP_EXPORT voice_server_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - voice_server_update_t(class discord_client* client, const std::string& raw); - /** - * @brief guild id where voice server updated - */ - snowflake guild_id; - /** - * @brief voice server token, used to connect to vc - */ - std::string token; - /** - * @brief voice server endpoint wss:// address - * - */ - std::string endpoint; -}; - -/** @brief Guild emojis update */ -struct DPP_EXPORT guild_emojis_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_emojis_update_t(class discord_client* client, const std::string& raw); - /** - * @brief snowflake ids of list of emojis - */ - std::vector emojis; - /** - * @brief guild where emojis are being updated - */ - guild* updating_guild; -}; - -/** - * @brief Presence update - * - */ -struct DPP_EXPORT presence_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - presence_update_t(class discord_client* client, const std::string& raw); - /** - * @brief rich presence being updated - */ - presence rich_presence; -}; - -/** @brief Webhooks update */ -struct DPP_EXPORT webhooks_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - webhooks_update_t(class discord_client* client, const std::string& raw); - /** - * @brief guild where webhooks are being updated - */ - guild* webhook_guild; - /** - * @brief channel where webhooks are being updated - */ - channel* webhook_channel; -}; - -/** @brief Guild member add */ -struct DPP_EXPORT guild_member_add_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_member_add_t(class discord_client* client, const std::string& raw); - /** - * @brief guild which gained new member - */ - guild* adding_guild; - /** - * @brief member which was added - */ - guild_member added; -}; - -/** @brief Invite delete */ -struct DPP_EXPORT invite_delete_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - invite_delete_t(class discord_client* client, const std::string& raw); - /** - * @brief the deleted invite - */ - invite deleted_invite; -}; - -/** @brief Guild update */ -struct DPP_EXPORT guild_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_update_t(class discord_client* client, const std::string& raw); - /** - * @brief guild being updated - */ - guild* updated; -}; - -/** @brief Guild integrations update */ -struct DPP_EXPORT guild_integrations_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_integrations_update_t(class discord_client* client, const std::string& raw); - /** - * @brief guild where integrations are being updated - */ - guild* updating_guild; -}; - -/** @brief Guild member update */ -struct DPP_EXPORT guild_member_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_member_update_t(class discord_client* client, const std::string& raw); - /** - * @brief guild where member is being updated - */ - guild* updating_guild; - /** - * @brief member being updated - */ - guild_member updated; -}; - -/** @brief Invite create */ -struct DPP_EXPORT invite_create_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - invite_create_t(class discord_client* client, const std::string& raw); - /** - * @brief created invite - */ - invite created_invite; -}; - -/** @brief Message update */ -struct DPP_EXPORT message_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - message_update_t(class discord_client* client, const std::string& raw); - /** - * @brief message being updated - */ - message msg; -}; - -/** @brief User update */ -struct DPP_EXPORT user_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - user_update_t(class discord_client* client, const std::string& raw); - /** - * @brief user being updated - */ - user updated; -}; - -/** @brief Create message */ -struct DPP_EXPORT message_create_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - message_create_t(class discord_client* client, const std::string& raw); - /** - * @brief message that was created (sent). - */ - message msg; - /** - * @brief Send a text to the same channel as the channel_id in received event. - * @param m Text to send - * @param callback User function to execute once the API call completes. - * @note confirmation_callback_t::value contains a message object on success. On failure, value is undefined and confirmation_callback_t::is_error() is true. - */ - void send(const std::string& m, command_completion_event_t callback = utility::log_error()) const; - /** - * @brief Send a message to the same channel as the channel_id in received event. - * @param msg Message to send - * @param callback User function to execute once the API call completes. - * @note confirmation_callback_t::value contains a message object on success. On failure, value is undefined and confirmation_callback_t::is_error() is true. - */ - void send(message& msg, command_completion_event_t callback = utility::log_error()) const; - /** - * @brief Send a message to the same channel as the channel_id in received event. - * @param msg Message to send - * @param callback User function to execute once the API call completes. - * @note confirmation_callback_t::value contains a message object on success. On failure, value is undefined and confirmation_callback_t::is_error() is true. - */ - void send(message&& msg, command_completion_event_t callback = utility::log_error()) const; - /** - * @brief Reply to the message received in the event. - * @param m Text to send - * @param mention_replied_user mentions (pings) the author of message replied to, if true - * @param callback User function to execute once the API call completes. - * @note confirmation_callback_t::value contains a message object on success. On failure, value is undefined and confirmation_callback_t::is_error() is true. - */ - void reply(const std::string& m, bool mention_replied_user = false, command_completion_event_t callback = utility::log_error()) const; - /** - * @brief Reply to the message received in the event. - * @param msg Message to send as a reply. - * @param mention_replied_user mentions (pings) the author of message replied to, if true - * @param callback User function to execute once the API call completes. - * @note confirmation_callback_t::value contains a message object on success. On failure, value is undefined and confirmation_callback_t::is_error() is true. - */ - void reply(message& msg, bool mention_replied_user = false, command_completion_event_t callback = utility::log_error()) const; - /** - * @brief Reply to the message received in the event. - * @param msg Message to send as a reply. - * @param mention_replied_user mentions (pings) the author of message replied to, if true - * @param callback User function to execute once the API call completes. - * @note confirmation_callback_t::value contains a message object on success. On failure, value is undefined and confirmation_callback_t::is_error() is true. - */ - void reply(message&& msg, bool mention_replied_user = false, command_completion_event_t callback = utility::log_error()) const; -}; - -/** @brief Guild ban add */ -struct DPP_EXPORT guild_ban_add_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_ban_add_t(class discord_client* client, const std::string& raw); - /** - * @brief guild where ban was added - */ - guild* banning_guild; - /** - * @brief user being banned - */ - user banned; -}; - -/** @brief Guild ban remove */ -struct DPP_EXPORT guild_ban_remove_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_ban_remove_t(class discord_client* client, const std::string& raw); - /** - * @brief guild where ban is being removed - */ - guild* unbanning_guild; - /** - * @brief user being unbanned - */ - user unbanned; -}; - -/** @brief Integration create */ -struct DPP_EXPORT integration_create_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - integration_create_t(class discord_client* client, const std::string& raw); - /** - * @brief created integration - */ - integration created_integration; -}; - -/** @brief Integration update */ -struct DPP_EXPORT integration_update_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - integration_update_t(class discord_client* client, const std::string& raw); - /** - * @brief updated integration - */ - integration updated_integration; -}; - -/** @brief Integration delete */ -struct DPP_EXPORT integration_delete_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - integration_delete_t(class discord_client* client, const std::string& raw); - /** - * @brief deleted integration - */ - integration deleted_integration; -}; - -/** @brief Thread Create*/ -struct DPP_EXPORT thread_create_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - thread_create_t(class discord_client* client, const std::string& raw); - /** - * @brief guild where thread was created - */ - guild* creating_guild; - /** - * @brief thread created - */ - thread created; -}; - -/** @brief Thread Update -*/ -struct DPP_EXPORT thread_update_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - thread_update_t(class discord_client* client, const std::string& raw); - /** - * @brief guild where thread was updated - */ - guild* updating_guild; - /** - * @brief thread updated - */ - thread updated; -}; - -/** @brief Thread Delete - */ -struct DPP_EXPORT thread_delete_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - thread_delete_t(class discord_client* client, const std::string& raw); - /** - * @brief guild where thread was deleted - */ - guild* deleting_guild; - /** - * @brief thread deleted - */ - thread deleted; -}; - -/** @brief Thread List Sync - */ -struct DPP_EXPORT thread_list_sync_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - thread_list_sync_t(class discord_client* client, const std::string& raw); - /** - * @brief guild where thread list was synchronised - */ - guild* updating_guild; - /** - * @brief list of threads (channels) synchronised - */ - std::vector threads; - /** - * @brief list of thread members for the channels (threads) - */ - std::vector members; -}; - -/** @brief Thread Member Update - */ -struct DPP_EXPORT thread_member_update_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - thread_member_update_t(class discord_client* client, const std::string& raw); - /** - * @brief updated thread member - */ - thread_member updated; -}; - -/** @brief Thread Members Update - */ -struct DPP_EXPORT thread_members_update_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - thread_members_update_t(class discord_client* client, const std::string& raw); - /** - * @brief thread (channel) id - */ - snowflake thread_id; - /** - * @brief guild thread members updated on - */ - guild* updating_guild; - /** - * @brief new approximate member count - */ - uint8_t member_count; - /** - * @brief added members - */ - std::vector added; - /** - * @brief ids only of removed members - */ - std::vector removed_ids; -}; - -/** @brief voice buffer send - */ -struct DPP_EXPORT voice_buffer_send_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on - * WILL ALWAYS be NULL. - * @param raw Raw event text as JSON - */ - voice_buffer_send_t(class discord_client* client, const std::string &raw); - /** - * @brief voice client where buffer was sent - */ - class discord_voice_client* voice_client; - /** - * @brief encoded size of sent buffer - */ - int buffer_size; -}; - -/** @brief voice user talking */ -struct DPP_EXPORT voice_user_talking_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on - * WILL ALWAYS be NULL. - * @param raw Raw event text as JSON - */ - voice_user_talking_t(class discord_client* client, const std::string &raw); - /** - * @brief voice client where user is talking - */ - class discord_voice_client* voice_client; - /** - * @brief talking user id - */ - snowflake user_id; - /** - * @brief flags for talking user - */ - uint8_t talking_flags; -}; - -/** @brief voice user talking */ -struct DPP_EXPORT voice_ready_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on - * WILL ALWAYS be NULL. - * @param raw Raw event text as JSON - */ - voice_ready_t(class discord_client* client, const std::string &raw); - /** - * @brief voice client which is ready - */ - class discord_voice_client* voice_client; - /** - * @brief id of voice channel - */ - snowflake voice_channel_id; -}; - -/** @brief voice receive packet */ -struct DPP_EXPORT voice_receive_t : public event_dispatch_t { - -friend class discord_voice_client; - - /** - * @brief Constructor - * @param client The shard the event originated on. - * WILL ALWAYS be NULL. - * @param raw Raw event text as UDP packet. - */ - voice_receive_t(class discord_client* client, const std::string &raw); - /** - * @brief Construct a new voice receive t object - * - * @param client The shard the event originated on. - * WILL ALWAYS be NULL. - * @param raw Raw event text as UDP packet. - * @param vc owning voice client pointer - * @param _user_id user id who is speaking, 0 for a mix of all user audio - * @param pcm user audio to set - * @param length length of user audio in bytes - */ - voice_receive_t(class discord_client* client, const std::string &raw, class discord_voice_client* vc, snowflake _user_id, uint8_t* pcm, size_t length); - /** - * @brief Voice client - */ - class discord_voice_client* voice_client; - /** - * @brief Audio data, encoded as 48kHz stereo PCM or Opus, - * @deprecated Please switch to using audio_data. - */ - uint8_t* audio = nullptr; - /** - * @brief Size of audio buffer - * @deprecated Please switch to using audio_data. - */ - size_t audio_size = 0; - /** - * @brief Audio data, encoded as 48kHz stereo PCM or Opus, - */ - std::basic_string audio_data; - /** - * @brief User ID of speaker (zero if unknown) - */ - snowflake user_id; -protected: - /** - * @brief Reassign values outside of the constructor for use within discord_voice_client - * - * @param vc owning voice client pointer - * @param _user_id user id who is speaking, 0 for a mix of all user audio - * @param pcm user audio to set - * @param length length of user audio in bytes - */ - void reassign(class discord_voice_client* vc, snowflake _user_id, uint8_t* pcm, size_t length); -}; - -/** @brief voice client speaking event */ -struct DPP_EXPORT voice_client_speaking_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on. - * WILL ALWAYS be NULL. - * @param raw Raw event text as JSON - */ - voice_client_speaking_t(class discord_client* client, const std::string &raw); - /** - * @brief voice client where user is speaking - */ - class discord_voice_client* voice_client; - /** - * @brief speaking user id - * - */ - snowflake user_id; - /** - * @brief ssrc value of speaking user - */ - uint32_t ssrc; -}; - -/** @brief voice client disconnect event */ -struct DPP_EXPORT voice_client_disconnect_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on. - * WILL ALWAYS be NULL. - * @param raw Raw event text as JSON - */ - voice_client_disconnect_t(class discord_client* client, const std::string &raw); - /** - * @brief voice client where user disconnected - */ - class discord_voice_client* voice_client; - /** - * @brief user id of user who left vc - */ - snowflake user_id; -}; - -}; - +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/* Forward declaration */ +struct confirmation_callback_t; + +/** + * @brief A function used as a callback for any REST based command + */ +typedef std::function command_completion_event_t; + +/** @brief Base event parameter struct. + * Each event you receive from the library will have its parameter derived from this class. + * The class contains the raw event data, and a pointer to the current shard's dpp::discord_client object. + * You can also use this object to cancel the current event, meaning that any listeners after yours do + * not get notified of the current event if you call it. + */ +struct DPP_EXPORT event_dispatch_t { + /** + * @brief Raw event data. + * If you are using json on your websocket, this will contain json, and if you are using + * ETF as your websocket protocol, it will contain raw ETF data. + */ + const std::string raw_event; + + /** + * @brief Shard the event came from. + * Note that for some events, notably voice events, this may be nullptr. + */ + class discord_client* from; + + /** + * @brief Construct a new event_dispatch_t object + * + * @param client The shard the event originated on. May be a nullptr, e.g. for voice events + * @param raw Raw event data as JSON or ETF + */ + event_dispatch_t(class discord_client* client, const std::string& raw); + + /** + * @brief Cancels the event in progress. Any other attached lambdas for this event after this one are not called. + * Note that event cancellation is a thread local state, and not stored in the object (because object which can + * be cancelled is `const` during the event, and cannot itself contain the changeable state). + * @return const event_dispatch_t& reference to self for chaining + */ + const event_dispatch_t& cancel_event() const; + + /** + * @brief Returns true if the event is cancelled. + * Note that event cancellation is a thread local state, and not stored in the object (because object which can + * be cancelled is `const` during the event, and cannot itself contain the changeable state). + * @return true if the event is cancelled + */ + bool is_cancelled() const; +}; + +/** @brief Log messages */ +struct DPP_EXPORT log_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + log_t(class discord_client* client, const std::string& raw); + /** Severity */ + loglevel severity; + /** Log Message */ + std::string message; + + log_t(const log_t&) = default; +}; + +namespace utility { + /** + * @brief Get a default logger that outputs to std::cout. + * e.g. + * ``` + * bot.on_log(dpp::utility::cout_logger()); + * ``` + * + * @return A logger for attaching to on_log + */ + std::function DPP_EXPORT cout_logger(); + + /** + * @brief The default callback handler for API calls. + * on error, sends the error to the logger. + * + * @return A lambda for attaching to an API callback + */ + std::function DPP_EXPORT log_error(); +}; + +/** @brief Add user to scheduled event */ +struct DPP_EXPORT guild_scheduled_event_user_add_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + guild_scheduled_event_user_add_t(class discord_client* client, const std::string& raw); + /** + * @brief event user added to + */ + snowflake event_id; + + /** + * @brief User being added + * + */ + snowflake user_id; + + /** + * @brief Guild being added to + * + */ + snowflake guild_id; +}; + +/** @brief Delete user from scheduled event */ +struct DPP_EXPORT guild_scheduled_event_user_remove_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + guild_scheduled_event_user_remove_t(class discord_client* client, const std::string& raw); + /** + * @brief event user removed from + */ + snowflake event_id; + + /** + * @brief User being removed + * + */ + snowflake user_id; + + /** + * @brief Guild being removed from + * + */ + snowflake guild_id; +}; + +/** @brief Create scheduled event */ +struct DPP_EXPORT guild_scheduled_event_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + guild_scheduled_event_create_t(class discord_client* client, const std::string& raw); + /** + * @brief created event + */ + scheduled_event created; +}; + +/** @brief Create scheduled event */ +struct DPP_EXPORT guild_scheduled_event_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + guild_scheduled_event_update_t(class discord_client* client, const std::string& raw); + /** + * @brief updated event + */ + scheduled_event updated; +}; + +/** @brief Delete scheduled event */ +struct DPP_EXPORT guild_scheduled_event_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + guild_scheduled_event_delete_t(class discord_client* client, const std::string& raw); + /** + * @brief deleted event + */ + scheduled_event deleted; +}; + +/** @brief Create automod rule */ +struct DPP_EXPORT automod_rule_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + automod_rule_create_t(class discord_client* client, const std::string& raw); + /** + * @brief updated event + */ + automod_rule created; +}; + +/** @brief Update automod rule */ +struct DPP_EXPORT automod_rule_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + automod_rule_update_t(class discord_client* client, const std::string& raw); + /** + * @brief updated event + */ + automod_rule updated; +}; + +/** @brief Delete automod rule */ +struct DPP_EXPORT automod_rule_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + automod_rule_delete_t(class discord_client* client, const std::string& raw); + /** + * @brief updated event + */ + automod_rule deleted; +}; + +/** @brief Execute/trigger automod rule */ +struct DPP_EXPORT automod_rule_execute_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + automod_rule_execute_t(class discord_client* client, const std::string& raw); + + snowflake guild_id; //!< the id of the guild in which action was executed + automod_action action; //!< the action which was executed + snowflake rule_id; //!< the id of the rule which action belongs to + automod_trigger_type rule_trigger_type; //!< the trigger type of rule which was triggered + snowflake user_id; //!< the id of the user which generated the content which triggered the rule + snowflake channel_id; //!< Optional: the id of the channel in which user content was posted + snowflake message_id; //!< Optional: the id of any user message which content belongs to + snowflake alert_system_message_id; //!< Optional: the id of any system auto moderation messages posted as a result of this action + std::string content; //!< the user generated text content + std::string matched_keyword; //!< the word or phrase configured in the rule that triggered the rule (may be empty) + std::string matched_content; //!< the substring in content that triggered the rule (may be empty) +}; + + + +/** @brief Create stage instance */ +struct DPP_EXPORT stage_instance_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + stage_instance_create_t(class discord_client* client, const std::string& raw); + /** + * @brief created stage instance + */ + stage_instance created; +}; + +/** @brief Update stage instance */ +struct DPP_EXPORT stage_instance_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + stage_instance_update_t(class discord_client* client, const std::string& raw); + /** + * @brief updated stage instance + */ + stage_instance updated; +}; + +/** @brief Delete stage instance */ +struct DPP_EXPORT stage_instance_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + stage_instance_delete_t(class discord_client* client, const std::string& raw); + /** + * @brief deleted stage instance + */ + stage_instance deleted; +}; + +/** @brief Voice state update */ +struct DPP_EXPORT voice_state_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + voice_state_update_t(class discord_client* client, const std::string& raw); + /** Voice state */ + voicestate state; +}; + +/** + * @brief Create interaction + */ +struct DPP_EXPORT interaction_create_t : public event_dispatch_t { + + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + interaction_create_t(class discord_client* client, const std::string& raw); + + + /** + * @brief Acknowledge interaction without displaying a message to the user, + * for use with button and select menu components. + * + * @param callback User function to execute when the api call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void reply(command_completion_event_t callback = utility::log_error()) const; + + /** + * @brief Send a reply for this interaction + * + * @param t Type of reply to send + * @param m Message object to send. Not all fields are supported by Discord. + * @param callback User function to execute when the api call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void reply(interaction_response_type t, const message & m, command_completion_event_t callback = utility::log_error()) const; + + /** + * @brief Send a reply for this interaction + * + * @param t Type of reply to send + * @param mt The string value to send, for simple text only messages + * @param callback User function to execute when the api call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void reply(interaction_response_type t, const std::string & mt, command_completion_event_t callback = utility::log_error()) const; + + /** + * @brief Send a reply for this interaction. + * Uses the default type of dpp::ir_channel_message_with_source, a simple message reply. + * + * @param m Message object to send. Not all fields are supported by Discord. + * @param callback User function to execute when the api call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void reply(const message & m, command_completion_event_t callback = utility::log_error()) const; + + /** + * @brief Send a reply for this interaction. + * Uses the default type of dpp::ir_channel_message_with_source, a simple message reply. + * + * @param mt The string value to send, for simple text only messages + * @param callback User function to execute when the api call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void reply(const std::string & mt, command_completion_event_t callback = utility::log_error()) const; + + /** + * @brief Reply to interaction with a dialog box + * + * @param mr Dialog box response to send + * @param callback User function to execute when the api call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void dialog(const interaction_modal_response& mr, command_completion_event_t callback = utility::log_error()) const; + + /** + * @brief Edit the response for this interaction + * + * @param m Message object to send. Not all fields are supported by Discord. + * @param callback User function to execute when the api call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void edit_response(const message & m, command_completion_event_t callback = utility::log_error()) const; + + /** + * @brief Edit the response for this interaction + * + * @param mt The string value to send, for simple text only messages + * @param callback User function to execute when the api call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void edit_response(const std::string & mt, command_completion_event_t callback = utility::log_error()) const; + + /** + * @brief Set the bot to 'thinking' state + * + * @param ephemeral True if the thinking state should be ephemeral + * @param callback User function to execute when the api call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void thinking(bool ephemeral = false, command_completion_event_t callback = utility::log_error()) const; + + /** + * @brief Get original response message for this interaction + * + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void get_original_response(command_completion_event_t callback) const; + + /** + * @brief Edit original response message for this interaction + * + * @param m Message object to send. Not all fields are supported by Discord. + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void edit_original_response(const message & m, command_completion_event_t callback = utility::log_error()) const; + + /** + * @brief Delete original response message for this interaction. This cannot be used on an ephemeral interaction response. + * + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void delete_original_response(command_completion_event_t callback = utility::log_error()) const; + + /** + * @brief Get a command line parameter + * + * @param name The command line parameter to retrieve + * @return const command_value& If the command line parameter does not + * exist, an empty variant is returned. + */ + const virtual command_value& get_parameter(const std::string& name) const; + + /** + * @brief command interaction + */ + interaction command; + + /** + * @brief Destroy this object + */ + virtual ~interaction_create_t() = default; +}; + +/** + * @brief User has issued a slash command + */ +struct DPP_EXPORT slashcommand_t : public interaction_create_t { +public: + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + slashcommand_t(class discord_client* client, const std::string& raw); +}; + +/** + * @brief Click on button + */ +struct DPP_EXPORT button_click_t : public interaction_create_t { + + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + button_click_t(class discord_client* client, const std::string& raw); + + /** + * @brief Get a command line parameter + * + * @param name The command line parameter to retrieve + * @return Always returns an empty parameter as buttons dont have parameters! + */ + const virtual command_value& get_parameter(const std::string& name) const; + /** + * @brief button custom id + */ + std::string custom_id; + /** + * @brief component type + */ + uint8_t component_type; +}; + +struct DPP_EXPORT form_submit_t : public interaction_create_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + form_submit_t(class discord_client* client, const std::string& raw); + + /** + * @brief Get a command line parameter + * + * @param name The command line parameter to retrieve + * @return Always returns an empty parameter as buttons dont have parameters! + */ + const virtual command_value& get_parameter(const std::string& name) const; + /** + * @brief button custom id + */ + std::string custom_id; + /** + * @brief Message components for form reply + */ + std::vector components; +}; + +/** + * @brief Discord requests that we fill a list of auto completion choices for a command option + */ +struct DPP_EXPORT autocomplete_t : public interaction_create_t { + + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + autocomplete_t(class discord_client* client, const std::string& raw); + + /** + * @brief Get a command line parameter + * + * @param name The command line parameter to retrieve + * @return Always returns an empty parameter as auto complete requests dont have parameters! + */ + const virtual command_value& get_parameter(const std::string& name) const; + + /** + * @brief Command ID + */ + dpp::snowflake id; + + /** + * @brief Command name + */ + std::string name; + + /** + * @brief auto completion options + */ + std::vector options; +}; + +/** + * @brief Base class for context menu interactions, e.g. right click on + * user or message. + */ +struct DPP_EXPORT context_menu_t : public interaction_create_t { +public: + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + context_menu_t(class discord_client* client, const std::string& raw); +}; + +/** + * @brief Event parameter for context menu interactions for messages + */ +struct DPP_EXPORT message_context_menu_t : public context_menu_t { + + /** + * @brief Related message + */ + message ctx_message; +public: + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_context_menu_t(class discord_client* client, const std::string& raw); + + /** + * @brief Get the message which was right-clicked on + * + * @return message right-clicked on + */ + message get_message() const; + + /** + * @brief Set the message object for this event + * + * @param m message to set + * @return message_context_menu_t& reference to self for fluent chaining + */ + message_context_menu_t& set_message(const message& m); +}; + +/** + * @brief Event parameter for context menu interactions for users + */ +struct DPP_EXPORT user_context_menu_t : public context_menu_t { + + /** + * @brief Related user + */ + user ctx_user; +public: + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + user_context_menu_t(class discord_client* client, const std::string& raw); + + /** + * @brief Get the user which was right-clicked on + * + * @return user right clicked on + */ + user get_user() const; + + /** + * @brief Set the user object for this event + * + * @param u user to set + * @return user_context_menu_t& reference to self for fluent chaining + */ + user_context_menu_t& set_user(const user& u); + +}; + +/** + * @brief Click on select + */ +struct DPP_EXPORT select_click_t : public interaction_create_t { + + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + select_click_t(class discord_client* client, const std::string& raw); + + /** + * @brief Get a command line parameter + * + * @param name The command line parameter to retrieve + * @return Always returns an empty parameter as buttons dont have parameters! + */ + const virtual command_value& get_parameter(const std::string& name) const; + + /** + * @brief select menu custom id + */ + std::string custom_id; + /** + * @brief select menu values + */ + std::vector values; + /** + * @brief select menu component type (dpp::component_type) + */ + uint8_t component_type; +}; + + +/** @brief Delete guild */ +struct DPP_EXPORT guild_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_delete_t(class discord_client* client, const std::string& raw); + /** Deleted guild */ + guild* deleted; +}; + +/** @brief Update guild stickers */ +struct DPP_EXPORT guild_stickers_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_stickers_update_t(class discord_client* client, const std::string& raw); + /** Updating guild */ + guild* updating_guild; + /** + * @brief stickers being updated + */ + std::vector stickers; +}; + +/** @brief Guild join request delete (user declined membership screening) */ +struct DPP_EXPORT guild_join_request_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_join_request_delete_t(class discord_client* client, const std::string& raw); + /** Deleted guild */ + snowflake guild_id; + /** + * @brief user id + */ + snowflake user_id; +}; + +/** @brief Delete channel */ +struct DPP_EXPORT channel_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + channel_delete_t(class discord_client* client, const std::string& raw); + /** + * @brief guild channel is being deleted from + */ + guild* deleting_guild; + /** + * @brief channel being deleted + */ + channel* deleted; +}; + +/** @brief Update channel */ +struct DPP_EXPORT channel_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + channel_update_t(class discord_client* client, const std::string& raw); + /** + * @brief guild channel is being updated on + */ + guild* updating_guild; + /** + * @brief channel being updated + */ + channel* updated; +}; + +/** @brief Session ready */ +struct DPP_EXPORT ready_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + ready_t(class discord_client* client, const std::string& raw); + /** + * @brief websocket session id + */ + std::string session_id; + /** + * @brief shard id + */ + uint32_t shard_id; +}; + +/** @brief Message Deleted */ +struct DPP_EXPORT message_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_delete_t(class discord_client* client, const std::string& raw); + /** + * @brief message being deleted + */ + message* deleted; +}; + +/** @brief Guild member remove */ +struct DPP_EXPORT guild_member_remove_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_member_remove_t(class discord_client* client, const std::string& raw); + /** + * @brief guild user is being removed from + */ + guild* removing_guild; + /** + * @brief user being removed + */ + user* removed; +}; + +/** @brief Session resumed */ +struct DPP_EXPORT resumed_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + resumed_t(class discord_client* client, const std::string& raw); + /** + * @brief websocket session id + */ + std::string session_id; + /** + * @brief shard id + */ + uint32_t shard_id; +}; + +/** @brief Guild role create */ +struct DPP_EXPORT guild_role_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_role_create_t(class discord_client* client, const std::string& raw); + /** + * @brief guild role is being created on + */ + guild* creating_guild; + /** + * @brief role being created + */ + role* created; +}; + +/** @brief Typing start */ +struct DPP_EXPORT typing_start_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + typing_start_t(class discord_client* client, const std::string& raw); + /** + * @brief guild user is typing on + */ + guild* typing_guild; + /** + * @brief channel user is typing on + */ + channel* typing_channel; + /** + * @brief user who is typing. + * Can be nullptr if user is not cached + */ + user* typing_user; + /** + * @brief User id of user typing. + * Always set regardless of caching + */ + snowflake user_id; + /** + * @brief Time of typing event + */ + time_t timestamp; +}; + +/** @brief Voice state update */ +struct DPP_EXPORT voice_track_marker_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. + * Will always be null. + * @param raw Raw event text as JSON. + * Will always be empty. + */ + voice_track_marker_t(class discord_client* client, const std::string& raw); + /** Voice client */ + class discord_voice_client* voice_client; + /** Track metadata */ + std::string track_meta; +}; + + +/** @brief Message reaction add */ +struct DPP_EXPORT message_reaction_add_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_reaction_add_t(class discord_client* client, const std::string& raw); + /** + * @brief Guild reaction occurred on + */ + guild* reacting_guild; + /** + * @brief User who reacted + */ + user reacting_user; + /** + * @brief member data of user who reacted + */ + guild_member reacting_member; + /** + * @brief channel the reaction happened on + */ + channel* reacting_channel; + /** + * @brief emoji of reaction + */ + emoji reacting_emoji; + /** + * @brief message id of the message reacted upon + */ + snowflake message_id; +}; + +/** @brief Guild members chunk */ +struct DPP_EXPORT guild_members_chunk_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_members_chunk_t(class discord_client* client, const std::string& raw); + /** + * @brief guild the members chunk is for + */ + guild* adding; + /** + * @brief list of members in the chunk + */ + guild_member_map* members; +}; + +/** @brief Message reaction remove */ +struct DPP_EXPORT message_reaction_remove_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_reaction_remove_t(class discord_client* client, const std::string& raw); + /** + * @brief Guild reaction occurred on + */ + guild* reacting_guild; + /** + * @brief User who reacted + */ + dpp::snowflake reacting_user_id; + /** + * @brief channel the reaction happened on + */ + channel* reacting_channel; + /** + * @brief emoji of reaction + */ + emoji reacting_emoji; + /** + * @brief message id of the message reacted upon + */ + snowflake message_id; +}; + +/** @brief Create guild */ +struct DPP_EXPORT guild_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_create_t(class discord_client* client, const std::string& raw); + /** + * @brief guild that was created + */ + guild* created; + /** + * @brief List of presences of all users on the guild. + * + * This is only filled if you have the GUILD_PRESENCES + * privileged intent. + */ + presence_map presences; + /** + * @brief List of scheduled events in the guild + */ + scheduled_event_map scheduled_events; + /** + * @brief List of stage instances in the guild + */ + stage_instance_map stage_instances; + /** + * @brief List of threads in the guild + */ + thread_map threads; + /** + * @brief List of stickers in the guild + */ + sticker_map stickers; +}; + +/** @brief Create channel */ +struct DPP_EXPORT channel_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + channel_create_t(class discord_client* client, const std::string& raw); + /** + * @brief guild channel was created on + */ + guild* creating_guild; + /** + * @brief channel that was created + */ + channel* created; +}; + +/** @brief Message remove emoji */ +struct DPP_EXPORT message_reaction_remove_emoji_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_reaction_remove_emoji_t(class discord_client* client, const std::string& raw); + /** + * @brief Guild reaction occurred on + */ + guild* reacting_guild; + /** + * @brief channel the reaction happened on + */ + channel* reacting_channel; + /** + * @brief emoji of reaction + */ + emoji reacting_emoji; + /** + * @brief message id of the message reacted upon + */ + snowflake message_id; +}; + +/** @brief Message delete bulk */ +struct DPP_EXPORT message_delete_bulk_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_delete_bulk_t(class discord_client* client, const std::string& raw); + /** + * @brief guild messages are being deleted upon + */ + guild* deleting_guild; + /** + * @brief user who is deleting the messages + */ + user* deleting_user; + /** + * @brief channel messages are being deleted from + */ + channel* deleting_channel; + /** + * @brief list of message ids of deleted messages + */ + std::vector deleted; +}; + +/** @brief Guild role update */ +struct DPP_EXPORT guild_role_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_role_update_t(class discord_client* client, const std::string& raw); + /** + * @brief guild where roles are being updated + */ + guild* updating_guild; + /** + * @brief the role being updated + */ + role* updated; +}; + +/** @brief Guild role delete */ +struct DPP_EXPORT guild_role_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_role_delete_t(class discord_client* client, const std::string& raw); + /** + * @brief guild where role is being deleted + */ + guild* deleting_guild; + /** + * @brief role being deleted + */ + role* deleted; + /** + * @brief ID of the deleted role + */ + snowflake role_id; +}; + +/** @brief Channel pins update */ +struct DPP_EXPORT channel_pins_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + channel_pins_update_t(class discord_client* client, const std::string& raw); + /** + * @brief guild where message is being pinned + */ + guild* pin_guild; + /** + * @brief channel where message is being pinned + */ + channel* pin_channel; + /** + * @brief timestamp of pin + */ + time_t timestamp; +}; + +/** @brief Message remove all reactions */ +struct DPP_EXPORT message_reaction_remove_all_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_reaction_remove_all_t(class discord_client* client, const std::string& raw); + /** + * @brief Guild reaction occurred on + */ + guild* reacting_guild; + /** + * @brief channel the reaction happened on + */ + channel* reacting_channel; + /** + * @brief message id of the message reacted upon + */ + snowflake message_id; + +}; + +/** @brief Voice server update */ +struct DPP_EXPORT voice_server_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + voice_server_update_t(class discord_client* client, const std::string& raw); + /** + * @brief guild id where voice server updated + */ + snowflake guild_id; + /** + * @brief voice server token, used to connect to vc + */ + std::string token; + /** + * @brief voice server endpoint wss:// address + * + */ + std::string endpoint; +}; + +/** @brief Guild emojis update */ +struct DPP_EXPORT guild_emojis_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_emojis_update_t(class discord_client* client, const std::string& raw); + /** + * @brief snowflake ids of list of emojis + */ + std::vector emojis; + /** + * @brief guild where emojis are being updated + */ + guild* updating_guild; +}; + +/** + * @brief Presence update + * + */ +struct DPP_EXPORT presence_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + presence_update_t(class discord_client* client, const std::string& raw); + /** + * @brief rich presence being updated + */ + presence rich_presence; +}; + +/** @brief Webhooks update */ +struct DPP_EXPORT webhooks_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + webhooks_update_t(class discord_client* client, const std::string& raw); + /** + * @brief guild where webhooks are being updated + */ + guild* webhook_guild; + /** + * @brief channel where webhooks are being updated + */ + channel* webhook_channel; +}; + +/** @brief Guild member add */ +struct DPP_EXPORT guild_member_add_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_member_add_t(class discord_client* client, const std::string& raw); + /** + * @brief guild which gained new member + */ + guild* adding_guild; + /** + * @brief member which was added + */ + guild_member added; +}; + +/** @brief Invite delete */ +struct DPP_EXPORT invite_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + invite_delete_t(class discord_client* client, const std::string& raw); + /** + * @brief the deleted invite + */ + invite deleted_invite; +}; + +/** @brief Guild update */ +struct DPP_EXPORT guild_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_update_t(class discord_client* client, const std::string& raw); + /** + * @brief guild being updated + */ + guild* updated; +}; + +/** @brief Guild integrations update */ +struct DPP_EXPORT guild_integrations_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_integrations_update_t(class discord_client* client, const std::string& raw); + /** + * @brief guild where integrations are being updated + */ + guild* updating_guild; +}; + +/** @brief Guild member update */ +struct DPP_EXPORT guild_member_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_member_update_t(class discord_client* client, const std::string& raw); + /** + * @brief guild where member is being updated + */ + guild* updating_guild; + /** + * @brief member being updated + */ + guild_member updated; +}; + +/** @brief Invite create */ +struct DPP_EXPORT invite_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + invite_create_t(class discord_client* client, const std::string& raw); + /** + * @brief created invite + */ + invite created_invite; +}; + +/** @brief Message update */ +struct DPP_EXPORT message_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_update_t(class discord_client* client, const std::string& raw); + /** + * @brief message being updated + */ + message msg; +}; + +/** @brief User update */ +struct DPP_EXPORT user_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + user_update_t(class discord_client* client, const std::string& raw); + /** + * @brief user being updated + */ + user updated; +}; + +/** @brief Create message */ +struct DPP_EXPORT message_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_create_t(class discord_client* client, const std::string& raw); + /** + * @brief message that was created (sent). + */ + message msg; + /** + * @brief Send a text to the same channel as the channel_id in received event. + * @param m Text to send + * @param callback User function to execute once the API call completes. + * @note confirmation_callback_t::value contains a message object on success. On failure, value is undefined and confirmation_callback_t::is_error() is true. + */ + void send(const std::string& m, command_completion_event_t callback = utility::log_error()) const; + /** + * @brief Send a message to the same channel as the channel_id in received event. + * @param msg Message to send + * @param callback User function to execute once the API call completes. + * @note confirmation_callback_t::value contains a message object on success. On failure, value is undefined and confirmation_callback_t::is_error() is true. + */ + void send(message& msg, command_completion_event_t callback = utility::log_error()) const; + /** + * @brief Send a message to the same channel as the channel_id in received event. + * @param msg Message to send + * @param callback User function to execute once the API call completes. + * @note confirmation_callback_t::value contains a message object on success. On failure, value is undefined and confirmation_callback_t::is_error() is true. + */ + void send(message&& msg, command_completion_event_t callback = utility::log_error()) const; + /** + * @brief Reply to the message received in the event. + * @param m Text to send + * @param mention_replied_user mentions (pings) the author of message replied to, if true + * @param callback User function to execute once the API call completes. + * @note confirmation_callback_t::value contains a message object on success. On failure, value is undefined and confirmation_callback_t::is_error() is true. + */ + void reply(const std::string& m, bool mention_replied_user = false, command_completion_event_t callback = utility::log_error()) const; + /** + * @brief Reply to the message received in the event. + * @param msg Message to send as a reply. + * @param mention_replied_user mentions (pings) the author of message replied to, if true + * @param callback User function to execute once the API call completes. + * @note confirmation_callback_t::value contains a message object on success. On failure, value is undefined and confirmation_callback_t::is_error() is true. + */ + void reply(message& msg, bool mention_replied_user = false, command_completion_event_t callback = utility::log_error()) const; + /** + * @brief Reply to the message received in the event. + * @param msg Message to send as a reply. + * @param mention_replied_user mentions (pings) the author of message replied to, if true + * @param callback User function to execute once the API call completes. + * @note confirmation_callback_t::value contains a message object on success. On failure, value is undefined and confirmation_callback_t::is_error() is true. + */ + void reply(message&& msg, bool mention_replied_user = false, command_completion_event_t callback = utility::log_error()) const; +}; + +/** @brief Guild ban add */ +struct DPP_EXPORT guild_ban_add_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_ban_add_t(class discord_client* client, const std::string& raw); + /** + * @brief guild where ban was added + */ + guild* banning_guild; + /** + * @brief user being banned + */ + user banned; +}; + +/** @brief Guild ban remove */ +struct DPP_EXPORT guild_ban_remove_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_ban_remove_t(class discord_client* client, const std::string& raw); + /** + * @brief guild where ban is being removed + */ + guild* unbanning_guild; + /** + * @brief user being unbanned + */ + user unbanned; +}; + +/** @brief Integration create */ +struct DPP_EXPORT integration_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + integration_create_t(class discord_client* client, const std::string& raw); + /** + * @brief created integration + */ + integration created_integration; +}; + +/** @brief Integration update */ +struct DPP_EXPORT integration_update_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + integration_update_t(class discord_client* client, const std::string& raw); + /** + * @brief updated integration + */ + integration updated_integration; +}; + +/** @brief Integration delete */ +struct DPP_EXPORT integration_delete_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + integration_delete_t(class discord_client* client, const std::string& raw); + /** + * @brief deleted integration + */ + integration deleted_integration; +}; + +/** @brief Thread Create*/ +struct DPP_EXPORT thread_create_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + thread_create_t(class discord_client* client, const std::string& raw); + /** + * @brief guild where thread was created + */ + guild* creating_guild; + /** + * @brief thread created + */ + thread created; +}; + +/** @brief Thread Update +*/ +struct DPP_EXPORT thread_update_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + thread_update_t(class discord_client* client, const std::string& raw); + /** + * @brief guild where thread was updated + */ + guild* updating_guild; + /** + * @brief thread updated + */ + thread updated; +}; + +/** @brief Thread Delete + */ +struct DPP_EXPORT thread_delete_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + thread_delete_t(class discord_client* client, const std::string& raw); + /** + * @brief guild where thread was deleted + */ + guild* deleting_guild; + /** + * @brief thread deleted + */ + thread deleted; +}; + +/** @brief Thread List Sync + */ +struct DPP_EXPORT thread_list_sync_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + thread_list_sync_t(class discord_client* client, const std::string& raw); + /** + * @brief guild where thread list was synchronised + */ + guild* updating_guild; + /** + * @brief list of threads (channels) synchronised + */ + std::vector threads; + /** + * @brief list of thread members for the channels (threads) + */ + std::vector members; +}; + +/** @brief Thread Member Update + */ +struct DPP_EXPORT thread_member_update_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + thread_member_update_t(class discord_client* client, const std::string& raw); + /** + * @brief updated thread member + */ + thread_member updated; +}; + +/** @brief Thread Members Update + */ +struct DPP_EXPORT thread_members_update_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + thread_members_update_t(class discord_client* client, const std::string& raw); + /** + * @brief thread (channel) id + */ + snowflake thread_id; + /** + * @brief guild thread members updated on + */ + guild* updating_guild; + /** + * @brief new approximate member count + */ + uint8_t member_count; + /** + * @brief added members + */ + std::vector added; + /** + * @brief ids only of removed members + */ + std::vector removed_ids; +}; + +/** @brief voice buffer send + */ +struct DPP_EXPORT voice_buffer_send_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * WILL ALWAYS be NULL. + * @param raw Raw event text as JSON + */ + voice_buffer_send_t(class discord_client* client, const std::string &raw); + /** + * @brief voice client where buffer was sent + */ + class discord_voice_client* voice_client; + /** + * @brief encoded size of sent buffer + */ + int buffer_size; +}; + +/** @brief voice user talking */ +struct DPP_EXPORT voice_user_talking_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * WILL ALWAYS be NULL. + * @param raw Raw event text as JSON + */ + voice_user_talking_t(class discord_client* client, const std::string &raw); + /** + * @brief voice client where user is talking + */ + class discord_voice_client* voice_client; + /** + * @brief talking user id + */ + snowflake user_id; + /** + * @brief flags for talking user + */ + uint8_t talking_flags; +}; + +/** @brief voice user talking */ +struct DPP_EXPORT voice_ready_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * WILL ALWAYS be NULL. + * @param raw Raw event text as JSON + */ + voice_ready_t(class discord_client* client, const std::string &raw); + /** + * @brief voice client which is ready + */ + class discord_voice_client* voice_client; + /** + * @brief id of voice channel + */ + snowflake voice_channel_id; +}; + +/** @brief voice receive packet */ +struct DPP_EXPORT voice_receive_t : public event_dispatch_t { + +friend class discord_voice_client; + + /** + * @brief Constructor + * @param client The shard the event originated on. + * WILL ALWAYS be NULL. + * @param raw Raw event text as UDP packet. + */ + voice_receive_t(class discord_client* client, const std::string &raw); + /** + * @brief Construct a new voice receive t object + * + * @param client The shard the event originated on. + * WILL ALWAYS be NULL. + * @param raw Raw event text as UDP packet. + * @param vc owning voice client pointer + * @param _user_id user id who is speaking, 0 for a mix of all user audio + * @param pcm user audio to set + * @param length length of user audio in bytes + */ + voice_receive_t(class discord_client* client, const std::string &raw, class discord_voice_client* vc, snowflake _user_id, uint8_t* pcm, size_t length); + /** + * @brief Voice client + */ + class discord_voice_client* voice_client; + /** + * @brief Audio data, encoded as 48kHz stereo PCM or Opus, + * @deprecated Please switch to using audio_data. + */ + uint8_t* audio = nullptr; + /** + * @brief Size of audio buffer + * @deprecated Please switch to using audio_data. + */ + size_t audio_size = 0; + /** + * @brief Audio data, encoded as 48kHz stereo PCM or Opus, + */ + std::basic_string audio_data; + /** + * @brief User ID of speaker (zero if unknown) + */ + snowflake user_id; +protected: + /** + * @brief Reassign values outside of the constructor for use within discord_voice_client + * + * @param vc owning voice client pointer + * @param _user_id user id who is speaking, 0 for a mix of all user audio + * @param pcm user audio to set + * @param length length of user audio in bytes + */ + void reassign(class discord_voice_client* vc, snowflake _user_id, uint8_t* pcm, size_t length); +}; + +/** @brief voice client speaking event */ +struct DPP_EXPORT voice_client_speaking_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on. + * WILL ALWAYS be NULL. + * @param raw Raw event text as JSON + */ + voice_client_speaking_t(class discord_client* client, const std::string &raw); + /** + * @brief voice client where user is speaking + */ + class discord_voice_client* voice_client; + /** + * @brief speaking user id + * + */ + snowflake user_id; + /** + * @brief ssrc value of speaking user + */ + uint32_t ssrc; +}; + +/** @brief voice client disconnect event */ +struct DPP_EXPORT voice_client_disconnect_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on. + * WILL ALWAYS be NULL. + * @param raw Raw event text as JSON + */ + voice_client_disconnect_t(class discord_client* client, const std::string &raw); + /** + * @brief voice client where user disconnected + */ + class discord_voice_client* voice_client; + /** + * @brief user id of user who left vc + */ + snowflake user_id; +}; + +}; + diff --git a/3rdParty/dpp/dns.h b/3rdParty/dpp/dns.h index 23d5b1ba99..33265e979c 100644 --- a/3rdParty/dpp/dns.h +++ b/3rdParty/dpp/dns.h @@ -1,76 +1,76 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#ifdef _WIN32 -#include -#include -#else -#include -#include -#include -#endif -#include -#include -#include - -namespace dpp { - - /** - * @brief Represents a cached DNS result. - * Used by the ssl_client class to store cached copies of dns lookups. - */ - struct dns_cache_entry { - /** - * @brief Resolved address information - */ - addrinfo addr; - - /** - * @brief Socket address. - * Discord only supports ipv4, but sockaddr_in6 is larger - * than sockaddr_in, sockaddr_storage will hold either. This - * means that if discord ever do support ipv6 we just flip - * one value in dns.cpp and that should be all that is needed. - */ - sockaddr_storage ai_addr; - - /** - * @brief Time at which this cache entry is invalidated - */ - time_t expire_timestamp; - }; - - /** - * @brief Cache container type - */ - using dns_cache_t = std::unordered_map; - - /** - * @brief Resolve a hostname to an addrinfo - * - * @param hostname Hostname to resolve - * @param port A port number or named service, e.g. "80" - * @return dns_cache_entry* First IP address associated with the hostname DNS record - * @throw dpp::connection_exception On failure to resolve hostname - */ - const dns_cache_entry* resolve_hostname(const std::string& hostname, const std::string& port); -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#ifdef _WIN32 +#include +#include +#else +#include +#include +#include +#endif +#include +#include +#include + +namespace dpp { + + /** + * @brief Represents a cached DNS result. + * Used by the ssl_client class to store cached copies of dns lookups. + */ + struct dns_cache_entry { + /** + * @brief Resolved address information + */ + addrinfo addr; + + /** + * @brief Socket address. + * Discord only supports ipv4, but sockaddr_in6 is larger + * than sockaddr_in, sockaddr_storage will hold either. This + * means that if discord ever do support ipv6 we just flip + * one value in dns.cpp and that should be all that is needed. + */ + sockaddr_storage ai_addr; + + /** + * @brief Time at which this cache entry is invalidated + */ + time_t expire_timestamp; + }; + + /** + * @brief Cache container type + */ + using dns_cache_t = std::unordered_map; + + /** + * @brief Resolve a hostname to an addrinfo + * + * @param hostname Hostname to resolve + * @param port A port number or named service, e.g. "80" + * @return dns_cache_entry* First IP address associated with the hostname DNS record + * @throw dpp::connection_exception On failure to resolve hostname + */ + const dns_cache_entry* resolve_hostname(const std::string& hostname, const std::string& port); +}; diff --git a/3rdParty/dpp/dpp.h b/3rdParty/dpp/dpp.h index 3e3d0b52fb..297c94c272 100644 --- a/3rdParty/dpp/dpp.h +++ b/3rdParty/dpp/dpp.h @@ -1,74 +1,74 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include diff --git a/3rdParty/dpp/dtemplate.h b/3rdParty/dpp/dtemplate.h index f9ecb3a406..7569c5f786 100644 --- a/3rdParty/dpp/dtemplate.h +++ b/3rdParty/dpp/dtemplate.h @@ -1,103 +1,103 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Represents a guild template - */ -class DPP_EXPORT dtemplate : public json_interface { -public: - /** - * @brief Template code - */ - std::string code; - /** - * @brief Template name - */ - std::string name; - /** - * @brief Template description - */ - std::string description; - /** - * @brief Usage counter - */ - uint32_t usage_count; - /** - * @brief User ID of creator - */ - snowflake creator_id; - /** - * @brief Creation date/time - * - */ - time_t created_at; - /** - * @brief Last update date/time - */ - time_t updated_at; - /** - * @brief Guild id the template is created from - */ - snowflake source_guild_id; - /** - * @brief True if needs synchronising - */ - bool is_dirty; - - /** - * @brief Construct a new dtemplate object - */ - dtemplate(); - - /** - * @brief Destroy the dtemplate object - */ - virtual ~dtemplate() = default; - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - dtemplate& fill_from_json(nlohmann::json* j); - - /** - * @brief Build the JSON for this object - * - * @param with_id Add ID to output - * @return std::string JSON content - */ - std::string build_json(bool with_id = false) const; - -}; - -/** A container of invites */ -typedef std::unordered_map dtemplate_map; - - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Represents a guild template + */ +class DPP_EXPORT dtemplate : public json_interface { +public: + /** + * @brief Template code + */ + std::string code; + /** + * @brief Template name + */ + std::string name; + /** + * @brief Template description + */ + std::string description; + /** + * @brief Usage counter + */ + uint32_t usage_count; + /** + * @brief User ID of creator + */ + snowflake creator_id; + /** + * @brief Creation date/time + * + */ + time_t created_at; + /** + * @brief Last update date/time + */ + time_t updated_at; + /** + * @brief Guild id the template is created from + */ + snowflake source_guild_id; + /** + * @brief True if needs synchronising + */ + bool is_dirty; + + /** + * @brief Construct a new dtemplate object + */ + dtemplate(); + + /** + * @brief Destroy the dtemplate object + */ + virtual ~dtemplate() = default; + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + dtemplate& fill_from_json(nlohmann::json* j); + + /** + * @brief Build the JSON for this object + * + * @param with_id Add ID to output + * @return std::string JSON content + */ + std::string build_json(bool with_id = false) const; + +}; + +/** A container of invites */ +typedef std::unordered_map dtemplate_map; + + +}; diff --git a/3rdParty/dpp/emoji.h b/3rdParty/dpp/emoji.h index 05e841317f..7c47fe5eba 100644 --- a/3rdParty/dpp/emoji.h +++ b/3rdParty/dpp/emoji.h @@ -1,177 +1,177 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -#define MAX_EMOJI_SIZE 256 * 1024 - -/** - * @brief Flags for dpp::emoji - */ -enum emoji_flags : uint8_t { - /// Emoji requires colons - e_require_colons = 0b00000001, - /// Managed (introduced by application) - e_managed = 0b00000010, - /// Animated - e_animated = 0b00000100, - /// Available (false if the guild doesn't meet boosting criteria, etc) - e_available = 0b00001000, -}; - -/** - * @brief Represents an emoji for a dpp::guild - */ -class DPP_EXPORT emoji : public managed, public json_interface { -public: - /** - * @brief Emoji name - */ - std::string name; - /** - * @brief User id who uploaded the emoji - */ - snowflake user_id; - /** - * @brief Flags for the emoji from dpp::emoji_flags - */ - uint8_t flags; - /** - * @brief Image data for the emoji if uploading - */ - std::string* image_data; - - /** - * @brief Construct a new emoji object - */ - emoji(); - - /** - * @brief Construct a new emoji object with name, ID and flags - * - * @param n The emoji's name - * @param i ID, if it has one (unicode does not) - * @param f Emoji flags (emoji_flags) - */ - emoji(const std::string n, const snowflake i = 0, const uint8_t f = 0); - - /** - * @brief Destroy the emoji object - */ - virtual ~emoji(); - - /** - * @brief Create a mentionable emoji - * @param name The name of the emoji. - * @param id The ID of the emoji. - * @param is_animated is emoji animated. - * @return std::string The formatted mention of the emoji. - */ - static std::string get_mention(const std::string& name, const snowflake& id, bool is_animated = false); - - /** - * @brief Read class values from json object - * - * @param j A json object to read from - * @return A reference to self - */ - emoji& fill_from_json(nlohmann::json* j); - - /** - * @brief Build the json for this object - * - * @param with_id include the id in the JSON - * @return std::string json data - */ - std::string build_json(bool with_id = false) const; - - /** - * @brief Emoji requires colons - * - * @return true Requires colons - * @return false Does not require colons - */ - bool requires_colons() const; - - /** - * @brief Emoji is managed - * - * @return true Is managed - * @return false Is not managed - */ - bool is_managed() const; - - /** - * @brief Emoji is animated - * - * @return true Is animated - * @return false Is noy animated - */ - bool is_animated() const; - - /** - * @brief Is available - * - * @return true Is available - * @return false Is unavailable - */ - bool is_available() const; - - /** - * @brief Load an image into the object as base64 - * - * @param image_blob Image binary data - * @param type Type of image - * @return emoji& Reference to self - * @throw dpp::exception Image content exceeds discord maximum of 256 kilobytes - */ - emoji& load_image(const std::string &image_blob, const image_type type); - - /** - * @brief Format to name if unicode, name:id if has id or a:name:id if animated - * - * @return Formatted name for reactions - */ - std::string format() const; - - /** - * @brief Get the mention/ping for the emoji - * - * @return std::string mention - */ - std::string get_mention() const; -}; - -/** - * @brief Group of emojis - */ -typedef std::unordered_map emoji_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +#define MAX_EMOJI_SIZE 256 * 1024 + +/** + * @brief Flags for dpp::emoji + */ +enum emoji_flags : uint8_t { + /// Emoji requires colons + e_require_colons = 0b00000001, + /// Managed (introduced by application) + e_managed = 0b00000010, + /// Animated + e_animated = 0b00000100, + /// Available (false if the guild doesn't meet boosting criteria, etc) + e_available = 0b00001000, +}; + +/** + * @brief Represents an emoji for a dpp::guild + */ +class DPP_EXPORT emoji : public managed, public json_interface { +public: + /** + * @brief Emoji name + */ + std::string name; + /** + * @brief User id who uploaded the emoji + */ + snowflake user_id; + /** + * @brief Flags for the emoji from dpp::emoji_flags + */ + uint8_t flags; + /** + * @brief Image data for the emoji if uploading + */ + std::string* image_data; + + /** + * @brief Construct a new emoji object + */ + emoji(); + + /** + * @brief Construct a new emoji object with name, ID and flags + * + * @param n The emoji's name + * @param i ID, if it has one (unicode does not) + * @param f Emoji flags (emoji_flags) + */ + emoji(const std::string n, const snowflake i = 0, const uint8_t f = 0); + + /** + * @brief Destroy the emoji object + */ + virtual ~emoji(); + + /** + * @brief Create a mentionable emoji + * @param name The name of the emoji. + * @param id The ID of the emoji. + * @param is_animated is emoji animated. + * @return std::string The formatted mention of the emoji. + */ + static std::string get_mention(const std::string& name, const snowflake& id, bool is_animated = false); + + /** + * @brief Read class values from json object + * + * @param j A json object to read from + * @return A reference to self + */ + emoji& fill_from_json(nlohmann::json* j); + + /** + * @brief Build the json for this object + * + * @param with_id include the id in the JSON + * @return std::string json data + */ + std::string build_json(bool with_id = false) const; + + /** + * @brief Emoji requires colons + * + * @return true Requires colons + * @return false Does not require colons + */ + bool requires_colons() const; + + /** + * @brief Emoji is managed + * + * @return true Is managed + * @return false Is not managed + */ + bool is_managed() const; + + /** + * @brief Emoji is animated + * + * @return true Is animated + * @return false Is noy animated + */ + bool is_animated() const; + + /** + * @brief Is available + * + * @return true Is available + * @return false Is unavailable + */ + bool is_available() const; + + /** + * @brief Load an image into the object as base64 + * + * @param image_blob Image binary data + * @param type Type of image + * @return emoji& Reference to self + * @throw dpp::exception Image content exceeds discord maximum of 256 kilobytes + */ + emoji& load_image(const std::string &image_blob, const image_type type); + + /** + * @brief Format to name if unicode, name:id if has id or a:name:id if animated + * + * @return Formatted name for reactions + */ + std::string format() const; + + /** + * @brief Get the mention/ping for the emoji + * + * @return std::string mention + */ + std::string get_mention() const; +}; + +/** + * @brief Group of emojis + */ +typedef std::unordered_map emoji_map; + +}; diff --git a/3rdParty/dpp/etf.h b/3rdParty/dpp/etf.h index 79b18d9338..5b07b6c961 100644 --- a/3rdParty/dpp/etf.h +++ b/3rdParty/dpp/etf.h @@ -1,642 +1,642 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Parts of this file inspired by, or outright copied from erlpack: - * https://github.com/discord/erlpack/ - * - * Acknowledgements: - * - * sysdep.h: - * Based on work by FURUHASHI Sadayuki in msgpack-python - * (https://github.com/msgpack/msgpack-python) - * - * Copyright (C) 2008-2010 FURUHASHI Sadayuki - * Licensed under the Apache License, Version 2.0 (the "License"). - * - ************************************************************************************/ - -#pragma once -#include -#include -#include - -namespace dpp { - -/** Current ETF format version in use */ -const uint8_t FORMAT_VERSION = 131; - -/** - * @brief Represents a token which identifies the type of value which follows it - * in the ETF binary structure. - */ -enum etf_token_type : uint8_t { - /// 68 [Distribution header] - ett_distribution = 'D', - /// 70 [Float64:IEEE float] - ett_new_float = 'F', - /// 77 [UInt32:Len, UInt8:Bits, Len:Data] - ett_bit_binary = 'M', - /// 80 [UInt4:UncompressedSize, N:ZlibCompressedData] - ett_compressed = 'P', - /// 97 [UInt8:Int] - ett_smallint = 'a', - /// 98 [Int32:Int] - ett_integer = 'b', - /// 99 [31:Float String] Float in string format (formatted "%.20e", sscanf "%lf"). Superseded by ett_new_float - ett_float = 'c', - /// 100 [UInt16:Len, Len:AtomName] max Len is 255 - ett_atom = 'd', - /// 101 [atom:Node, UInt32:ID, UInt8:Creation] - ett_reference = 'e', - /// 102 [atom:Node, UInt32:ID, UInt8:Creation] - ett_port = 'f', - /// 103 [atom:Node, UInt32:ID, UInt32:Serial, UInt8:Creation] - ett_pid = 'g', - /// 104 [UInt8:Arity, N:Elements] - ett_small_tuple = 'h', - /// 105 [UInt32:Arity, N:Elements] - ett_large_tuple = 'i', - /// 106 empty list - ett_nil = 'j', - /// 107 [UInt16:Len, Len:Characters] - ett_string = 'k', - /// 108 [UInt32:Len, Elements, Tail] - ett_list = 'l', - /// 109 [UInt32:Len, Len:Data] - ett_binary = 'm', - /// 110 [UInt8:n, UInt8:Sign, n:nums] - ett_bigint_small = 'n', - /// 111 [UInt32:n, UInt8:Sign, n:nums] - ett_bigint_large = 'o', - /// 112 [UInt32:Size, UInt8:Arity, 16*Uint6-MD5:Uniq, UInt32:Index, UInt32:NumFree, atom:Module, int:OldIndex, int:OldUniq, pid:Pid, NunFree*ext:FreeVars] - ett_new_function = 'p', - /// 113 [atom:Module, atom:Function, smallint:Arity] - ett_export = 'q', - /// 114 [UInt16:Len, atom:Node, UInt8:Creation, Len*UInt32:ID] - ett_new_reference = 'r', - /// 115 [UInt8:Len, Len:AtomName] - ett_atom_small = 's', - /// 116 [UInt32:Airty, N:Pairs] - ett_map = 't', - /// 117 [UInt4:NumFree, pid:Pid, atom:Module, int:Index, int:Uniq, NumFree*ext:FreeVars] - ett_function = 'u', - /// 118 [UInt16:Len, Len:AtomName] max Len is 255 characters (up to 4 bytes per) - ett_atom_utf8 = 'v', - /// 119 [UInt8:Len, Len:AtomName] - ett_atom_utf8_small = 'w' -}; - -/** - * @brief A horrible structure used within the ETF parser to convert uint64_t to double and back. - * This is horrible, but it is the official way erlang term format does this, so we can't really - * mess with it much. - */ -union type_punner { - /** - * @brief binary integer value - */ - uint64_t ui64; - /** - * @brief double floating point value - */ - double df; -}; - -/** - * @brief Represents a buffer of bytes being encoded into ETF - */ -struct DPP_EXPORT etf_buffer { - /** - * @brief Raw buffer - */ - std::vector buf; - /** - * @brief Current used length of buffer - * (this is different from buf.size() as it is pre-allocated - * using resize and may not all be in use) - */ - size_t length; - - /** - * @brief Construct a new etf buffer object - * - * @param initial initial buffer size to allocate - */ - etf_buffer(size_t initial); - - /** - * @brief Destroy the etf buffer object - */ - ~etf_buffer(); -}; - -/** - * @brief The etf_parser class can serialise and deserialise ETF (Erlang Term Format) - * into and out of an nlohmann::json object, so that layers above the websocket don't - * have to be any different for handling ETF. - */ -class DPP_EXPORT etf_parser { - - /** - * @brief Current size of binary data - */ - size_t size; - - /** - * @brief Current offset into binary data - */ - size_t offset; - - /** - * @brief Pointer to binary ETF data to be decoded - */ - uint8_t* data; - - /** - * @brief Parse a single value, and if that value contains other - * values (e.g. an array or map) then call itself recursively. - * - * @return nlohmann::json JSON value from the ETF - */ - nlohmann::json inner_parse(); - - /** - * @brief Read 8 bits of data from the buffer - * - * @return uint8_t data retrieved - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - uint8_t read_8_bits(); - - /** - * @brief Read 16 bits of data from the buffer - * - * @return uint16_t data retrieved - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - uint16_t read_16_bits(); - - /** - * @brief Read 32 bits of data from the buffer - * - * @return uint32_t data retrieved - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - uint32_t read_32_bits(); - - /** - * @brief Read 64 bits of data from the buffer - * - * @return uint64_t data retrieved - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - uint64_t read_64_bits(); - - /** - * @brief Read string data from the buffer - * - * @param length Length of string to retrieve - * @return const char* data retrieved - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - const char* read_string(uint32_t length); - - /** - * @brief Process an 'atom' value. - * An atom is a "label" or constant value within the data, - * such as a key name, nullptr, or false. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json process_atom(const char* atom, uint16_t length); - - /** - * @brief Decode an 'atom' value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_atom(); - - /** - * @brief Decode a small 'atom' value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_small_atom(); - - /** - * @brief Decode a small integer value (0-255). - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_small_integer(); - - /** - * @brief Decode an integer value (-MAXINT -> MAXINT-1). - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_integer(); - - /** - * @brief Decode an array of values. - * - * @return nlohmann::json values converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_array(uint32_t length); - - /** - * @brief Decode a list of values. - * - * @return nlohmann::json values converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_list(); - - /** - * @brief Decode a 'tuple' value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_tuple(uint32_t length); - - /** - * @brief Decode a nil 'atom' value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_nil(); - - /** - * @brief Decode a map (object) value. - * Will recurse to evaluate each member variable. - * - * @return nlohmann::json values converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_map(); - - /** - * @brief Decode a floating point numeric value. - * (depreciated in erlang but still expected to be supported) - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_float(); - - /** - * @brief Decode a floating type numeric value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_new_float(); - - /** - * @brief Decode a 'bigint' value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_bigint(uint32_t digits); - - /** - * @brief Decode a small 'bigint' value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_bigint_small(); - - /** - * @brief Decode a large 'bigint' value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_bigint_large(); - - /** - * @brief Decode a binary value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_binary(); - - /** - * @brief Decode a string value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_string(); - - /** - * @brief Decode a string list value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_string_as_list(); - - /** - * @brief Decode a 'small tuple' value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_tuple_small(); - - /** - * @brief Decode a 'large tuple' value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_tuple_large(); - - /** - * @brief Decode a compressed value. - * This is a zlib-compressed binary blob which contains another - * ETF object. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_compressed(); - - /** - * @brief Decode a 'reference' value. - * Erlang expects this to be supported, in practice Discord doesn't send these right now. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_reference(); - - /** - * @brief Decode a 'new reference' value. - * Erlang expects this to be supported, in practice Discord doesn't send these right now. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_new_reference(); - - /** - * @brief Decode a 'port' value. - * Erlang expects this to be supported, in practice Discord doesn't send these right now. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_port(); - - /** - * @brief Decode a 'PID' value. - * Erlang expects this to be supported, in practice Discord doesn't send these right now. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_pid(); - - /** - * @brief Decode an 'export' value. - * Erlang expects this to be supported, in practice Discord doesn't send these right now. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_export(); - - /** - * @brief Write to output buffer for creation of ETF from JSON - * - * @param pk buffer struct - * @param bytes byte buffer to write - * @param l number of bytes to write - * @throw std::exception Buffer cannot be extended - */ - void buffer_write(etf_buffer *pk, const char *bytes, size_t l); - - /** - * @brief Append version number to ETF buffer - * - * @param b buffer to append to - * @throw std::exception Buffer cannot be extended - */ - void append_version(etf_buffer *b); - - /** - * @brief Append nil value to ETF buffer - * - * @param b buffer to append to - * @throw std::exception Buffer cannot be extended - */ - void append_nil(etf_buffer *b); - - /** - * @brief Append false value to ETF buffer - * - * @param b buffer to append to - * @throw std::exception Buffer cannot be extended - */ - void append_false(etf_buffer *b); - - /** - * @brief Append true value to ETF buffer - * - * @param b buffer to append to - * @throw std::exception Buffer cannot be extended - */ - void append_true(etf_buffer *b); - - /** - * @brief Append small integer value to ETF buffer - * - * @param b buffer to append to - * @param d double to append - * @throw std::exception Buffer cannot be extended - */ - void append_small_integer(etf_buffer *b, unsigned char d); - - /** - * @brief Append integer value to ETF buffer - * - * @param b buffer to append to - * @param d integer to append - * @throw std::exception Buffer cannot be extended - */ - void append_integer(etf_buffer *b, int32_t d); - - /** - * @brief Append 64 bit integer value to ETF buffer - * - * @param b buffer to append to - * @param d integer to append - * @throw std::exception Buffer cannot be extended - */ - void append_unsigned_long_long(etf_buffer *b, unsigned long long d); - - /** - * @brief Append 64 bit integer value to ETF buffer - * - * @param b buffer to append to - * @param d integer to append - * @throw std::exception Buffer cannot be extended - */ - void append_long_long(etf_buffer *b, long long d); - - /** - * @brief Append double value to ETF buffer - * - * @param b buffer to append to - * @param f double to append - * @throw std::exception Buffer cannot be extended - */ - void append_double(etf_buffer *b, double f); - - /** - * @brief Append atom value to ETF buffer - * - * @param b buffer to append to - * @param bytes pointer to string to append - * @param size size of string to append - * @throw std::exception Buffer cannot be extended - */ - void append_atom(etf_buffer *b, const char *bytes, size_t size); - - /** - * @brief Append utf8 atom value to ETF buffer - * - * @param b buffer to append to - * @param bytes pointer to string to append - * @param size size of string to append - * @throw std::exception Buffer cannot be extended - */ - void append_atom_utf8(etf_buffer *b, const char *bytes, size_t size); - - /** - * @brief Append binary value to ETF buffer - * - * @param b buffer to append to - * @param bytes pointer to string to append - * @param size size of string to append - * @throw std::exception Buffer cannot be extended - */ - void append_binary(etf_buffer *b, const char *bytes, size_t size); - - /** - * @brief Append string value to ETF buffer - * - * @param b buffer to append to - * @param bytes pointer to string to append - * @param size size of string to append - * @throw std::exception Buffer cannot be extended - */ - void append_string(etf_buffer *b, const char *bytes, size_t size); - - /** - * @brief Append tuple value to ETF buffer - * - * @param b buffer to append to - * @param size size of value to append - * @throw std::exception Buffer cannot be extended - */ - void append_tuple_header(etf_buffer *b, size_t size); - - /** - * @brief Append list terminator to ETF buffer - * - * @param b buffer to append to - * @throw std::exception Buffer cannot be extended - */ - void append_nil_ext(etf_buffer *b); - - /** - * @brief Append a list header value to ETF buffer - * - * @param b buffer to append to - * @param size size of values to append - * @throw std::exception Buffer cannot be extended - */ - void append_list_header(etf_buffer *b, size_t size); - - /** - * @brief Append a map header value to ETF buffer - * - * @param b buffer to append to - * @param size size of values to append - * @throw std::exception Buffer cannot be extended - */ - void append_map_header(etf_buffer *b, size_t size); - - /** - * @brief Build ETF buffer - * - * @param j JSON object to build from - * @param b Buffer to append to - * @throw std::exception Buffer cannot be extended - */ - void inner_build(const nlohmann::json* j, etf_buffer* b); - -public: - /** - * @brief Construct a new etf parser object - */ - etf_parser(); - - /** - * @brief Destroy the etf parser object - */ - ~etf_parser(); - - /** - * @brief Convert ETF binary content to nlohmann::json - * - * @param in Raw binary ETF data (generally from a websocket) - * @return nlohmann::json JSON data for use in the library - * @throw dpp::exception Malformed or otherwise invalid ETF content - */ - nlohmann::json parse(const std::string& in); - - /** - * @brief Create ETF binary data from nlohmann::json - * - * @param j JSON value to encode to ETF - * @return std::string raw ETF data. Note that this can - * and probably will contain null values, use std::string::data() - * and std::string::size() to manipulate or send it. - * @throw std::exception Not enough memory, or invalid data types/values - */ - std::string build(const nlohmann::json& j); -}; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Parts of this file inspired by, or outright copied from erlpack: + * https://github.com/discord/erlpack/ + * + * Acknowledgements: + * + * sysdep.h: + * Based on work by FURUHASHI Sadayuki in msgpack-python + * (https://github.com/msgpack/msgpack-python) + * + * Copyright (C) 2008-2010 FURUHASHI Sadayuki + * Licensed under the Apache License, Version 2.0 (the "License"). + * + ************************************************************************************/ + +#pragma once +#include +#include +#include + +namespace dpp { + +/** Current ETF format version in use */ +const uint8_t FORMAT_VERSION = 131; + +/** + * @brief Represents a token which identifies the type of value which follows it + * in the ETF binary structure. + */ +enum etf_token_type : uint8_t { + /// 68 [Distribution header] + ett_distribution = 'D', + /// 70 [Float64:IEEE float] + ett_new_float = 'F', + /// 77 [UInt32:Len, UInt8:Bits, Len:Data] + ett_bit_binary = 'M', + /// 80 [UInt4:UncompressedSize, N:ZlibCompressedData] + ett_compressed = 'P', + /// 97 [UInt8:Int] + ett_smallint = 'a', + /// 98 [Int32:Int] + ett_integer = 'b', + /// 99 [31:Float String] Float in string format (formatted "%.20e", sscanf "%lf"). Superseded by ett_new_float + ett_float = 'c', + /// 100 [UInt16:Len, Len:AtomName] max Len is 255 + ett_atom = 'd', + /// 101 [atom:Node, UInt32:ID, UInt8:Creation] + ett_reference = 'e', + /// 102 [atom:Node, UInt32:ID, UInt8:Creation] + ett_port = 'f', + /// 103 [atom:Node, UInt32:ID, UInt32:Serial, UInt8:Creation] + ett_pid = 'g', + /// 104 [UInt8:Arity, N:Elements] + ett_small_tuple = 'h', + /// 105 [UInt32:Arity, N:Elements] + ett_large_tuple = 'i', + /// 106 empty list + ett_nil = 'j', + /// 107 [UInt16:Len, Len:Characters] + ett_string = 'k', + /// 108 [UInt32:Len, Elements, Tail] + ett_list = 'l', + /// 109 [UInt32:Len, Len:Data] + ett_binary = 'm', + /// 110 [UInt8:n, UInt8:Sign, n:nums] + ett_bigint_small = 'n', + /// 111 [UInt32:n, UInt8:Sign, n:nums] + ett_bigint_large = 'o', + /// 112 [UInt32:Size, UInt8:Arity, 16*Uint6-MD5:Uniq, UInt32:Index, UInt32:NumFree, atom:Module, int:OldIndex, int:OldUniq, pid:Pid, NunFree*ext:FreeVars] + ett_new_function = 'p', + /// 113 [atom:Module, atom:Function, smallint:Arity] + ett_export = 'q', + /// 114 [UInt16:Len, atom:Node, UInt8:Creation, Len*UInt32:ID] + ett_new_reference = 'r', + /// 115 [UInt8:Len, Len:AtomName] + ett_atom_small = 's', + /// 116 [UInt32:Airty, N:Pairs] + ett_map = 't', + /// 117 [UInt4:NumFree, pid:Pid, atom:Module, int:Index, int:Uniq, NumFree*ext:FreeVars] + ett_function = 'u', + /// 118 [UInt16:Len, Len:AtomName] max Len is 255 characters (up to 4 bytes per) + ett_atom_utf8 = 'v', + /// 119 [UInt8:Len, Len:AtomName] + ett_atom_utf8_small = 'w' +}; + +/** + * @brief A horrible structure used within the ETF parser to convert uint64_t to double and back. + * This is horrible, but it is the official way erlang term format does this, so we can't really + * mess with it much. + */ +union type_punner { + /** + * @brief binary integer value + */ + uint64_t ui64; + /** + * @brief double floating point value + */ + double df; +}; + +/** + * @brief Represents a buffer of bytes being encoded into ETF + */ +struct DPP_EXPORT etf_buffer { + /** + * @brief Raw buffer + */ + std::vector buf; + /** + * @brief Current used length of buffer + * (this is different from buf.size() as it is pre-allocated + * using resize and may not all be in use) + */ + size_t length; + + /** + * @brief Construct a new etf buffer object + * + * @param initial initial buffer size to allocate + */ + etf_buffer(size_t initial); + + /** + * @brief Destroy the etf buffer object + */ + ~etf_buffer(); +}; + +/** + * @brief The etf_parser class can serialise and deserialise ETF (Erlang Term Format) + * into and out of an nlohmann::json object, so that layers above the websocket don't + * have to be any different for handling ETF. + */ +class DPP_EXPORT etf_parser { + + /** + * @brief Current size of binary data + */ + size_t size; + + /** + * @brief Current offset into binary data + */ + size_t offset; + + /** + * @brief Pointer to binary ETF data to be decoded + */ + uint8_t* data; + + /** + * @brief Parse a single value, and if that value contains other + * values (e.g. an array or map) then call itself recursively. + * + * @return nlohmann::json JSON value from the ETF + */ + nlohmann::json inner_parse(); + + /** + * @brief Read 8 bits of data from the buffer + * + * @return uint8_t data retrieved + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + uint8_t read_8_bits(); + + /** + * @brief Read 16 bits of data from the buffer + * + * @return uint16_t data retrieved + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + uint16_t read_16_bits(); + + /** + * @brief Read 32 bits of data from the buffer + * + * @return uint32_t data retrieved + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + uint32_t read_32_bits(); + + /** + * @brief Read 64 bits of data from the buffer + * + * @return uint64_t data retrieved + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + uint64_t read_64_bits(); + + /** + * @brief Read string data from the buffer + * + * @param length Length of string to retrieve + * @return const char* data retrieved + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + const char* read_string(uint32_t length); + + /** + * @brief Process an 'atom' value. + * An atom is a "label" or constant value within the data, + * such as a key name, nullptr, or false. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json process_atom(const char* atom, uint16_t length); + + /** + * @brief Decode an 'atom' value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_atom(); + + /** + * @brief Decode a small 'atom' value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_small_atom(); + + /** + * @brief Decode a small integer value (0-255). + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_small_integer(); + + /** + * @brief Decode an integer value (-MAXINT -> MAXINT-1). + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_integer(); + + /** + * @brief Decode an array of values. + * + * @return nlohmann::json values converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_array(uint32_t length); + + /** + * @brief Decode a list of values. + * + * @return nlohmann::json values converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_list(); + + /** + * @brief Decode a 'tuple' value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_tuple(uint32_t length); + + /** + * @brief Decode a nil 'atom' value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_nil(); + + /** + * @brief Decode a map (object) value. + * Will recurse to evaluate each member variable. + * + * @return nlohmann::json values converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_map(); + + /** + * @brief Decode a floating point numeric value. + * (depreciated in erlang but still expected to be supported) + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_float(); + + /** + * @brief Decode a floating type numeric value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_new_float(); + + /** + * @brief Decode a 'bigint' value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_bigint(uint32_t digits); + + /** + * @brief Decode a small 'bigint' value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_bigint_small(); + + /** + * @brief Decode a large 'bigint' value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_bigint_large(); + + /** + * @brief Decode a binary value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_binary(); + + /** + * @brief Decode a string value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_string(); + + /** + * @brief Decode a string list value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_string_as_list(); + + /** + * @brief Decode a 'small tuple' value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_tuple_small(); + + /** + * @brief Decode a 'large tuple' value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_tuple_large(); + + /** + * @brief Decode a compressed value. + * This is a zlib-compressed binary blob which contains another + * ETF object. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_compressed(); + + /** + * @brief Decode a 'reference' value. + * Erlang expects this to be supported, in practice Discord doesn't send these right now. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_reference(); + + /** + * @brief Decode a 'new reference' value. + * Erlang expects this to be supported, in practice Discord doesn't send these right now. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_new_reference(); + + /** + * @brief Decode a 'port' value. + * Erlang expects this to be supported, in practice Discord doesn't send these right now. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_port(); + + /** + * @brief Decode a 'PID' value. + * Erlang expects this to be supported, in practice Discord doesn't send these right now. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_pid(); + + /** + * @brief Decode an 'export' value. + * Erlang expects this to be supported, in practice Discord doesn't send these right now. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_export(); + + /** + * @brief Write to output buffer for creation of ETF from JSON + * + * @param pk buffer struct + * @param bytes byte buffer to write + * @param l number of bytes to write + * @throw std::exception Buffer cannot be extended + */ + void buffer_write(etf_buffer *pk, const char *bytes, size_t l); + + /** + * @brief Append version number to ETF buffer + * + * @param b buffer to append to + * @throw std::exception Buffer cannot be extended + */ + void append_version(etf_buffer *b); + + /** + * @brief Append nil value to ETF buffer + * + * @param b buffer to append to + * @throw std::exception Buffer cannot be extended + */ + void append_nil(etf_buffer *b); + + /** + * @brief Append false value to ETF buffer + * + * @param b buffer to append to + * @throw std::exception Buffer cannot be extended + */ + void append_false(etf_buffer *b); + + /** + * @brief Append true value to ETF buffer + * + * @param b buffer to append to + * @throw std::exception Buffer cannot be extended + */ + void append_true(etf_buffer *b); + + /** + * @brief Append small integer value to ETF buffer + * + * @param b buffer to append to + * @param d double to append + * @throw std::exception Buffer cannot be extended + */ + void append_small_integer(etf_buffer *b, unsigned char d); + + /** + * @brief Append integer value to ETF buffer + * + * @param b buffer to append to + * @param d integer to append + * @throw std::exception Buffer cannot be extended + */ + void append_integer(etf_buffer *b, int32_t d); + + /** + * @brief Append 64 bit integer value to ETF buffer + * + * @param b buffer to append to + * @param d integer to append + * @throw std::exception Buffer cannot be extended + */ + void append_unsigned_long_long(etf_buffer *b, unsigned long long d); + + /** + * @brief Append 64 bit integer value to ETF buffer + * + * @param b buffer to append to + * @param d integer to append + * @throw std::exception Buffer cannot be extended + */ + void append_long_long(etf_buffer *b, long long d); + + /** + * @brief Append double value to ETF buffer + * + * @param b buffer to append to + * @param f double to append + * @throw std::exception Buffer cannot be extended + */ + void append_double(etf_buffer *b, double f); + + /** + * @brief Append atom value to ETF buffer + * + * @param b buffer to append to + * @param bytes pointer to string to append + * @param size size of string to append + * @throw std::exception Buffer cannot be extended + */ + void append_atom(etf_buffer *b, const char *bytes, size_t size); + + /** + * @brief Append utf8 atom value to ETF buffer + * + * @param b buffer to append to + * @param bytes pointer to string to append + * @param size size of string to append + * @throw std::exception Buffer cannot be extended + */ + void append_atom_utf8(etf_buffer *b, const char *bytes, size_t size); + + /** + * @brief Append binary value to ETF buffer + * + * @param b buffer to append to + * @param bytes pointer to string to append + * @param size size of string to append + * @throw std::exception Buffer cannot be extended + */ + void append_binary(etf_buffer *b, const char *bytes, size_t size); + + /** + * @brief Append string value to ETF buffer + * + * @param b buffer to append to + * @param bytes pointer to string to append + * @param size size of string to append + * @throw std::exception Buffer cannot be extended + */ + void append_string(etf_buffer *b, const char *bytes, size_t size); + + /** + * @brief Append tuple value to ETF buffer + * + * @param b buffer to append to + * @param size size of value to append + * @throw std::exception Buffer cannot be extended + */ + void append_tuple_header(etf_buffer *b, size_t size); + + /** + * @brief Append list terminator to ETF buffer + * + * @param b buffer to append to + * @throw std::exception Buffer cannot be extended + */ + void append_nil_ext(etf_buffer *b); + + /** + * @brief Append a list header value to ETF buffer + * + * @param b buffer to append to + * @param size size of values to append + * @throw std::exception Buffer cannot be extended + */ + void append_list_header(etf_buffer *b, size_t size); + + /** + * @brief Append a map header value to ETF buffer + * + * @param b buffer to append to + * @param size size of values to append + * @throw std::exception Buffer cannot be extended + */ + void append_map_header(etf_buffer *b, size_t size); + + /** + * @brief Build ETF buffer + * + * @param j JSON object to build from + * @param b Buffer to append to + * @throw std::exception Buffer cannot be extended + */ + void inner_build(const nlohmann::json* j, etf_buffer* b); + +public: + /** + * @brief Construct a new etf parser object + */ + etf_parser(); + + /** + * @brief Destroy the etf parser object + */ + ~etf_parser(); + + /** + * @brief Convert ETF binary content to nlohmann::json + * + * @param in Raw binary ETF data (generally from a websocket) + * @return nlohmann::json JSON data for use in the library + * @throw dpp::exception Malformed or otherwise invalid ETF content + */ + nlohmann::json parse(const std::string& in); + + /** + * @brief Create ETF binary data from nlohmann::json + * + * @param j JSON value to encode to ETF + * @return std::string raw ETF data. Note that this can + * and probably will contain null values, use std::string::data() + * and std::string::size() to manipulate or send it. + * @throw std::exception Not enough memory, or invalid data types/values + */ + std::string build(const nlohmann::json& j); +}; + +}; diff --git a/3rdParty/dpp/event.h b/3rdParty/dpp/event.h index b82f982eae..8f50f1d0b1 100644 --- a/3rdParty/dpp/event.h +++ b/3rdParty/dpp/event.h @@ -1,151 +1,151 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include - -#define event_decl(x,wstype) /** @brief Internal event handler for wstype websocket events. Called for each websocket message of this type. @internal */ \ - class x : public event { public: virtual void handle(dpp::discord_client* client, nlohmann::json &j, const std::string &raw); }; - -namespace dpp { - -class discord_client; - -/** - * @brief The events namespace holds the internal event handlers for each websocket event. - * These are handled internally and also dispatched to the user code if the event is hooked. - */ -namespace events { - -/** - * @brief An event object represents an event handled internally, passed from the websocket e.g. MESSAGE_CREATE. - */ -class DPP_EXPORT event { -public: - /** Pure virtual method for event handler code - * @param client The creating shard - * @param j The json data of the event - * @param raw The raw event json - */ - virtual void handle(class discord_client* client, nlohmann::json &j, const std::string &raw) = 0; -}; - -/* Internal logger */ -event_decl(logger,LOG); - -/* Guilds */ -event_decl(guild_create,GUILD_CREATE); -event_decl(guild_update,GUILD_UPDATE); -event_decl(guild_delete,GUILD_DELETE); -event_decl(guild_ban_add,GUILD_BAN_ADD); -event_decl(guild_ban_remove,GUILD_BAN_REMOVE); -event_decl(guild_emojis_update,GUILD_EMOJIS_UPDATE); -event_decl(guild_integrations_update,GUILD_INTEGRATIONS_UPDATE); -event_decl(guild_join_request_delete,GUILD_JOIN_REQUEST_DELETE); -event_decl(guild_stickers_update,GUILD_STICKERS_UPDATE); - -/* Stage channels */ -event_decl(stage_instance_create,STAGE_INSTANCE_CREATE); -event_decl(stage_instance_update,STAGE_INSTANCE_UPDATE); -event_decl(stage_instance_delete,STAGE_INSTANCE_DELETE); - -/* Guild members */ -event_decl(guild_member_add,GUILD_MEMBER_ADD); -event_decl(guild_member_remove,GUILD_MEMBER_REMOVE); -event_decl(guild_members_chunk,GUILD_MEMBERS_CHUNK); -event_decl(guild_member_update,GUILD_MEMBERS_UPDATE); - -/* Guild roles */ -event_decl(guild_role_create,GUILD_ROLE_CREATE); -event_decl(guild_role_update,GUILD_ROLE_UPDATE); -event_decl(guild_role_delete,GUILD_ROLE_DELETE); - -/* Session state */ -event_decl(resumed,RESUMED); -event_decl(ready,READY); - -/* Channels */ -event_decl(channel_create,CHANNEL_CREATE); -event_decl(channel_update,CHANNEL_UPDATE); -event_decl(channel_delete,CHANNEL_DELETE); -event_decl(channel_pins_update,CHANNEL_PINS_UPDATE); - -/* Threads */ -event_decl(thread_create,THREAD_CREATE); -event_decl(thread_update,THREAD_UPDATE); -event_decl(thread_delete,THREAD_DELETE); -event_decl(thread_list_sync,THREAD_LIST_SYNC); -event_decl(thread_member_update,THREAD_MEMBER_UPDATE); -event_decl(thread_members_update,THREAD_MEMBERS_UPDATE); - -/* Messages */ -event_decl(message_create,MESSAGE_CREATE); -event_decl(message_update,MESSAGE_UPDATE); -event_decl(message_delete,MESSAGE_DELETE); -event_decl(message_delete_bulk,MESSAGE_DELETE_BULK); - -/* Presence/typing */ -event_decl(presence_update,PRESENCE_UPDATE); -event_decl(typing_start,TYPING_START); - -/* Users (outside of guild) */ -event_decl(user_update,USER_UPDATE); - -/* Message reactions */ -event_decl(message_reaction_add,MESSAGE_REACTION_ADD); -event_decl(message_reaction_remove,MESSAGE_REACTION_REMOVE); -event_decl(message_reaction_remove_all,MESSAGE_REACTION_REMOVE_ALL); -event_decl(message_reaction_remove_emoji,MESSAGE_REACTION_REMOVE_EMOJI); - -/* Invites */ -event_decl(invite_create,INVITE_CREATE); -event_decl(invite_delete,INVITE_DELETE); - -/* Voice */ -event_decl(voice_state_update,VOICE_STATE_UPDATE); -event_decl(voice_server_update,VOICE_SERVER_UPDATE); - -/* Webhooks */ -event_decl(webhooks_update,WEBHOOKS_UPDATE); - -/* Application commands */ -event_decl(interaction_create,INTERACTION_CREATE); - -/* Integrations */ -event_decl(integration_create,INTEGRATION_CREATE); -event_decl(integration_update,INTEGRATION_UPDATE); -event_decl(integration_delete,INTEGRATION_DELETE); - -/* Scheduled events */ -event_decl(guild_scheduled_event_create,GUILD_SCHEDULED_EVENT_CREATE); -event_decl(guild_scheduled_event_update,GUILD_SCHEDULED_EVENT_UPDATE); -event_decl(guild_scheduled_event_delete,GUILD_SCHEDULED_EVENT_DELETE); -event_decl(guild_scheduled_event_user_add,GUILD_SCHEDULED_EVENT_USER_ADD); -event_decl(guild_scheduled_event_user_remove,GUILD_SCHEDULED_EVENT_USER_REMOVE); - -/* Auto moderation */ -event_decl(automod_rule_create, AUTO_MODERATION_RULE_CREATE); -event_decl(automod_rule_update, AUTO_MODERATION_RULE_UPDATE); -event_decl(automod_rule_delete, AUTO_MODERATION_RULE_DELETE); -event_decl(automod_rule_execute, AUTO_MODERATION_ACTION_EXECUTION); - -}}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include + +#define event_decl(x,wstype) /** @brief Internal event handler for wstype websocket events. Called for each websocket message of this type. @internal */ \ + class x : public event { public: virtual void handle(dpp::discord_client* client, nlohmann::json &j, const std::string &raw); }; + +namespace dpp { + +class discord_client; + +/** + * @brief The events namespace holds the internal event handlers for each websocket event. + * These are handled internally and also dispatched to the user code if the event is hooked. + */ +namespace events { + +/** + * @brief An event object represents an event handled internally, passed from the websocket e.g. MESSAGE_CREATE. + */ +class DPP_EXPORT event { +public: + /** Pure virtual method for event handler code + * @param client The creating shard + * @param j The json data of the event + * @param raw The raw event json + */ + virtual void handle(class discord_client* client, nlohmann::json &j, const std::string &raw) = 0; +}; + +/* Internal logger */ +event_decl(logger,LOG); + +/* Guilds */ +event_decl(guild_create,GUILD_CREATE); +event_decl(guild_update,GUILD_UPDATE); +event_decl(guild_delete,GUILD_DELETE); +event_decl(guild_ban_add,GUILD_BAN_ADD); +event_decl(guild_ban_remove,GUILD_BAN_REMOVE); +event_decl(guild_emojis_update,GUILD_EMOJIS_UPDATE); +event_decl(guild_integrations_update,GUILD_INTEGRATIONS_UPDATE); +event_decl(guild_join_request_delete,GUILD_JOIN_REQUEST_DELETE); +event_decl(guild_stickers_update,GUILD_STICKERS_UPDATE); + +/* Stage channels */ +event_decl(stage_instance_create,STAGE_INSTANCE_CREATE); +event_decl(stage_instance_update,STAGE_INSTANCE_UPDATE); +event_decl(stage_instance_delete,STAGE_INSTANCE_DELETE); + +/* Guild members */ +event_decl(guild_member_add,GUILD_MEMBER_ADD); +event_decl(guild_member_remove,GUILD_MEMBER_REMOVE); +event_decl(guild_members_chunk,GUILD_MEMBERS_CHUNK); +event_decl(guild_member_update,GUILD_MEMBERS_UPDATE); + +/* Guild roles */ +event_decl(guild_role_create,GUILD_ROLE_CREATE); +event_decl(guild_role_update,GUILD_ROLE_UPDATE); +event_decl(guild_role_delete,GUILD_ROLE_DELETE); + +/* Session state */ +event_decl(resumed,RESUMED); +event_decl(ready,READY); + +/* Channels */ +event_decl(channel_create,CHANNEL_CREATE); +event_decl(channel_update,CHANNEL_UPDATE); +event_decl(channel_delete,CHANNEL_DELETE); +event_decl(channel_pins_update,CHANNEL_PINS_UPDATE); + +/* Threads */ +event_decl(thread_create,THREAD_CREATE); +event_decl(thread_update,THREAD_UPDATE); +event_decl(thread_delete,THREAD_DELETE); +event_decl(thread_list_sync,THREAD_LIST_SYNC); +event_decl(thread_member_update,THREAD_MEMBER_UPDATE); +event_decl(thread_members_update,THREAD_MEMBERS_UPDATE); + +/* Messages */ +event_decl(message_create,MESSAGE_CREATE); +event_decl(message_update,MESSAGE_UPDATE); +event_decl(message_delete,MESSAGE_DELETE); +event_decl(message_delete_bulk,MESSAGE_DELETE_BULK); + +/* Presence/typing */ +event_decl(presence_update,PRESENCE_UPDATE); +event_decl(typing_start,TYPING_START); + +/* Users (outside of guild) */ +event_decl(user_update,USER_UPDATE); + +/* Message reactions */ +event_decl(message_reaction_add,MESSAGE_REACTION_ADD); +event_decl(message_reaction_remove,MESSAGE_REACTION_REMOVE); +event_decl(message_reaction_remove_all,MESSAGE_REACTION_REMOVE_ALL); +event_decl(message_reaction_remove_emoji,MESSAGE_REACTION_REMOVE_EMOJI); + +/* Invites */ +event_decl(invite_create,INVITE_CREATE); +event_decl(invite_delete,INVITE_DELETE); + +/* Voice */ +event_decl(voice_state_update,VOICE_STATE_UPDATE); +event_decl(voice_server_update,VOICE_SERVER_UPDATE); + +/* Webhooks */ +event_decl(webhooks_update,WEBHOOKS_UPDATE); + +/* Application commands */ +event_decl(interaction_create,INTERACTION_CREATE); + +/* Integrations */ +event_decl(integration_create,INTEGRATION_CREATE); +event_decl(integration_update,INTEGRATION_UPDATE); +event_decl(integration_delete,INTEGRATION_DELETE); + +/* Scheduled events */ +event_decl(guild_scheduled_event_create,GUILD_SCHEDULED_EVENT_CREATE); +event_decl(guild_scheduled_event_update,GUILD_SCHEDULED_EVENT_UPDATE); +event_decl(guild_scheduled_event_delete,GUILD_SCHEDULED_EVENT_DELETE); +event_decl(guild_scheduled_event_user_add,GUILD_SCHEDULED_EVENT_USER_ADD); +event_decl(guild_scheduled_event_user_remove,GUILD_SCHEDULED_EVENT_USER_REMOVE); + +/* Auto moderation */ +event_decl(automod_rule_create, AUTO_MODERATION_RULE_CREATE); +event_decl(automod_rule_update, AUTO_MODERATION_RULE_UPDATE); +event_decl(automod_rule_delete, AUTO_MODERATION_RULE_DELETE); +event_decl(automod_rule_execute, AUTO_MODERATION_ACTION_EXECUTION); + +}}; diff --git a/3rdParty/dpp/event_router.h b/3rdParty/dpp/event_router.h index fa8bef7816..6532ed8823 100644 --- a/3rdParty/dpp/event_router.h +++ b/3rdParty/dpp/event_router.h @@ -1,246 +1,246 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using json = nlohmann::json; - -namespace dpp { - -/** - * @brief A returned event handle for an event which was attached - */ -typedef size_t event_handle; - -/** - * @brief Handles routing of an event to multiple listeners. - * - * Multiple listeners may attach to the event_router_t by means of operator(). Passing a - * lambda into operator() attaches to the event. - * - * Dispatchers of the event may call the event_router_t::call() method to cause all listeners - * to receive the event. - * - * The event_router_t::empty() method will return true if there are no listeners attached - * to the event_router_t (this can be used to save time by not constructing objects that - * nobody will ever see). - * - * The event_router_t::detach() method removes an existing listener from the event, - * using the event_handle ID returned by operator(). - * - * This class is used by the library to route all websocket events to listening code. - * - * Example: - * - * ```cpp - * // Declare an event that takes log_t as its parameter - * event_router_t my_event; - * - * // Attach a listener to the event - * event_handle id = my_event([&](const log_t& cc) { - * std::cout << cc.message << "\n"; - * }); - * - * // Construct a log_t and call the event (listeners will receive the log_t object) - * log_t lt; - * lt.message = "foo"; - * my_event.call(lt); - * - * // Detach from an event using the handle returned by operator() - * my_event.detach(id); - * ``` - * - * @tparam T type of single parameter passed to event lambda derived from event_dispatch_t - */ -template class event_router_t { -private: - friend class cluster; - - event_handle next_handle = 1; - - /** - * @brief Thread safety mutex - */ - mutable std::shared_mutex lock; - /** - * @brief Container of event listeners keyed by handle, - * as handles are handed out sequentially they will always - * be called in they order they are bound to the event - * as std::map is an ordered container. - */ - std::map> dispatch_container; - - -#ifdef DPP_CORO - /** - * @brief Container for event listeners (coroutines only) - */ - std::map> coroutine_container; -#else - /** - * @brief Dummy container to keep the struct size same - */ - std::map> dummy_container; -#endif - - - /** - * @brief A function to be called whenever the method is called, to check - * some condition that is required for this event to trigger correctly. - */ - std::function warning; - - /** - * @brief Next handle to be given out by the event router - */ - -protected: - - /** - * @brief Set the warning callback object used to check that this - * event is capable of running properly - * - * @param warning_function A checking function to call - */ - void set_warning_callback(std::function warning_function) { - warning = warning_function; - } - -public: - /** - * @brief Construct a new event_router_t object. - */ - event_router_t() = default; - - /** - * @brief Call all attached listeners. - * Listeners may cancel, by calling the event.cancel method. - * - * @param event Class to pass as parameter to all listeners. - */ - void call(const T& event) const { - if (warning) { - warning(event); - } - std::shared_lock l(lock); - std::for_each(dispatch_container.begin(), dispatch_container.end(), [&](auto &ev) { - if (!event.is_cancelled()) { - ev.second(event); - } - }); -#ifdef DPP_CORO - std::for_each(coroutine_container.begin(), coroutine_container.end(), [&](auto &ev) { - if (!event.is_cancelled()) { - ev.second(event); - } - }); -#endif - }; - - /** - * @brief Returns true if the container of listeners is empty, - * i.e. there is nothing listening for this event right now. - * - * @return true if there are no listeners - * @return false if there are some listeners - */ - bool empty() const { - std::shared_lock l(lock); - return dispatch_container.empty(); - } - - /** - * @brief Returns true if any listeners are attached. - * - * This is the boolean opposite of event_router_t::empty(). - * @return true if listeners are attached - * @return false if no listeners are attached - */ - operator bool() const { - return !empty(); - } - - /** - * @brief Attach a lambda to the event, adding a listener. - * The lambda should follow the signature specified when declaring - * the event object and should take exactly one parameter derived - * from event_dispatch_t. - * - * @param func Function lambda to attach to event - * @return event_handle An event handle unique to this event, used to - * detach the listener from the event later if necessary. - */ - event_handle operator()(std::function func) { - return this->attach(func); - } - - /** - * @brief Attach a lambda to the event, adding a listener. - * The lambda should follow the signature specified when declaring - * the event object and should take exactly one parameter derived - * from event_dispatch_t. - * - * @param func Function lambda to attach to event - * @return event_handle An event handle unique to this event, used to - * detach the listener from the event later if necessary. - */ - event_handle attach(std::function func) { - std::unique_lock l(lock); - event_handle h = next_handle++; - dispatch_container.emplace(h, func); - return h; - } - -#ifdef DPP_CORO - event_handle co_attach(std::function func) { - std::unique_lock l(lock); - event_handle h = next_handle++; - coroutine_container.emplace(h, func); - return h; - } -#endif - /** - * @brief Detach a listener from the event using a previously obtained ID. - * - * @param handle An ID obtained from event_router_t::operator() - * @return true The event was successfully detached - * @return false The ID is invalid (possibly already detached, or does not exist) - */ - bool detach(const event_handle& handle) { - std::unique_lock l(lock); - return this->dispatch_container.erase(handle); - } -}; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { + +/** + * @brief A returned event handle for an event which was attached + */ +typedef size_t event_handle; + +/** + * @brief Handles routing of an event to multiple listeners. + * + * Multiple listeners may attach to the event_router_t by means of operator(). Passing a + * lambda into operator() attaches to the event. + * + * Dispatchers of the event may call the event_router_t::call() method to cause all listeners + * to receive the event. + * + * The event_router_t::empty() method will return true if there are no listeners attached + * to the event_router_t (this can be used to save time by not constructing objects that + * nobody will ever see). + * + * The event_router_t::detach() method removes an existing listener from the event, + * using the event_handle ID returned by operator(). + * + * This class is used by the library to route all websocket events to listening code. + * + * Example: + * + * ```cpp + * // Declare an event that takes log_t as its parameter + * event_router_t my_event; + * + * // Attach a listener to the event + * event_handle id = my_event([&](const log_t& cc) { + * std::cout << cc.message << "\n"; + * }); + * + * // Construct a log_t and call the event (listeners will receive the log_t object) + * log_t lt; + * lt.message = "foo"; + * my_event.call(lt); + * + * // Detach from an event using the handle returned by operator() + * my_event.detach(id); + * ``` + * + * @tparam T type of single parameter passed to event lambda derived from event_dispatch_t + */ +template class event_router_t { +private: + friend class cluster; + + event_handle next_handle = 1; + + /** + * @brief Thread safety mutex + */ + mutable std::shared_mutex lock; + /** + * @brief Container of event listeners keyed by handle, + * as handles are handed out sequentially they will always + * be called in they order they are bound to the event + * as std::map is an ordered container. + */ + std::map> dispatch_container; + + +#ifdef DPP_CORO + /** + * @brief Container for event listeners (coroutines only) + */ + std::map> coroutine_container; +#else + /** + * @brief Dummy container to keep the struct size same + */ + std::map> dummy_container; +#endif + + + /** + * @brief A function to be called whenever the method is called, to check + * some condition that is required for this event to trigger correctly. + */ + std::function warning; + + /** + * @brief Next handle to be given out by the event router + */ + +protected: + + /** + * @brief Set the warning callback object used to check that this + * event is capable of running properly + * + * @param warning_function A checking function to call + */ + void set_warning_callback(std::function warning_function) { + warning = warning_function; + } + +public: + /** + * @brief Construct a new event_router_t object. + */ + event_router_t() = default; + + /** + * @brief Call all attached listeners. + * Listeners may cancel, by calling the event.cancel method. + * + * @param event Class to pass as parameter to all listeners. + */ + void call(const T& event) const { + if (warning) { + warning(event); + } + std::shared_lock l(lock); + std::for_each(dispatch_container.begin(), dispatch_container.end(), [&](auto &ev) { + if (!event.is_cancelled()) { + ev.second(event); + } + }); +#ifdef DPP_CORO + std::for_each(coroutine_container.begin(), coroutine_container.end(), [&](auto &ev) { + if (!event.is_cancelled()) { + ev.second(event); + } + }); +#endif + }; + + /** + * @brief Returns true if the container of listeners is empty, + * i.e. there is nothing listening for this event right now. + * + * @return true if there are no listeners + * @return false if there are some listeners + */ + bool empty() const { + std::shared_lock l(lock); + return dispatch_container.empty(); + } + + /** + * @brief Returns true if any listeners are attached. + * + * This is the boolean opposite of event_router_t::empty(). + * @return true if listeners are attached + * @return false if no listeners are attached + */ + operator bool() const { + return !empty(); + } + + /** + * @brief Attach a lambda to the event, adding a listener. + * The lambda should follow the signature specified when declaring + * the event object and should take exactly one parameter derived + * from event_dispatch_t. + * + * @param func Function lambda to attach to event + * @return event_handle An event handle unique to this event, used to + * detach the listener from the event later if necessary. + */ + event_handle operator()(std::function func) { + return this->attach(func); + } + + /** + * @brief Attach a lambda to the event, adding a listener. + * The lambda should follow the signature specified when declaring + * the event object and should take exactly one parameter derived + * from event_dispatch_t. + * + * @param func Function lambda to attach to event + * @return event_handle An event handle unique to this event, used to + * detach the listener from the event later if necessary. + */ + event_handle attach(std::function func) { + std::unique_lock l(lock); + event_handle h = next_handle++; + dispatch_container.emplace(h, func); + return h; + } + +#ifdef DPP_CORO + event_handle co_attach(std::function func) { + std::unique_lock l(lock); + event_handle h = next_handle++; + coroutine_container.emplace(h, func); + return h; + } +#endif + /** + * @brief Detach a listener from the event using a previously obtained ID. + * + * @param handle An ID obtained from event_router_t::operator() + * @return true The event was successfully detached + * @return false The ID is invalid (possibly already detached, or does not exist) + */ + bool detach(const event_handle& handle) { + std::unique_lock l(lock); + return this->dispatch_container.erase(handle); + } +}; + +}; diff --git a/3rdParty/dpp/exception.h b/3rdParty/dpp/exception.h index 576e67a812..ffdc1bdb83 100644 --- a/3rdParty/dpp/exception.h +++ b/3rdParty/dpp/exception.h @@ -1,201 +1,201 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief The dpp::exception class derives from std::exception and supports some other - * ways of passing in error details such as via std::string. - */ -class exception : public std::exception -{ -protected: - /** - * @brief Exception message - */ - std::string msg; - -public: - - using std::exception::exception; - - /** - * @brief Construct a new exception object - */ - exception() = default; - - /** - * @brief Construct a new exception object - * - * @param what reason message - */ - explicit exception(const char* what) : msg(what) { } - - /** - * @brief Construct a new exception object - * - * @param what reason message - * @param len length of reason message - */ - exception(const char* what, size_t len) : msg(what, len) { } - - /** - * @brief Construct a new exception object - * - * @param what reason message - */ - explicit exception(const std::string& what) : msg(what) { } - - /** - * @brief Construct a new exception object - * - * @param what reason message - */ - explicit exception(std::string&& what) : msg(std::move(what)) { } - - /** - * @brief Construct a new exception object (copy constructor) - */ - exception(const exception&) = default; - - /** - * @brief Construct a new exception object (move constructor) - */ - exception(exception&&) = default; - - /** - * @brief Destroy the exception object - */ - ~exception() override = default; - - /** - * @brief Copy assignment operator - * - * @return exception& reference to self - */ - exception & operator = (const exception &) = default; - - /** - * @brief Move assignment operator - * - * @return exception& reference to self - */ - exception & operator = (exception&&) = default; - - /** - * @brief Get exception message - * - * @return const char* error message - */ - [[nodiscard]] const char* what() const noexcept override { return msg.c_str(); }; - -}; - -#ifndef _DOXYGEN_ - #define derived_exception(name, ancestor) class name : public dpp::ancestor { \ - public: \ - using dpp::ancestor::ancestor; \ - name() = default; \ - explicit name(const char* what) : ancestor(what) { } \ - name(const char* what, size_t len) : ancestor(what, len) { } \ - explicit name(const std::string& what) : ancestor(what) { } \ - explicit name(std::string&& what) : ancestor(what) { } \ - name(const name&) = default; \ - name(name&&) = default; \ - ~name() override = default; \ - name & operator = (const name &) = default; \ - name & operator = (name&&) = default; \ - [[nodiscard]] const char* what() const noexcept override { return msg.c_str(); }; \ - }; -#endif - -#ifdef _DOXYGEN_ - /* - * THESE DEFINITIONS ARE NOT THE REAL DEFINITIONS USED BY PROGRAM CODE. - * - * They exist only to cause Doxygen to emit proper documentation for the derived exception types. - * Proper definitions are emitted by the `derived_exception` macro in the "else" section. - */ - - /** - * @brief Represents an error in logic, e.g. you asked the library to do something the Discord API does not support - * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. - */ - class logic_exception : public dpp::exception { }; - /** - * @brief Represents an error reading or writing to a file - * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. - */ - class file_exception : public dpp::exception { }; - /** - * @brief Represents an error establishing or maintaining a connection - * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. - */ - class connection_exception : public dpp::exception { }; - /** - * @brief Represents an error with voice processing - * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. - */ - class voice_exception : public dpp::exception { }; - /** - * @brief Represents an error on a REST API call, e.g. a HTTPS request - * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. - */ - class rest_exception : public dpp::exception { }; - /** - * @brief Represents invalid length of argument being passed to a function - * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. - */ - class length_exception : public dpp::exception { }; - /** - * @brief Represents inability to parse data, usually caused by malformed JSON or ETF - * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. - */ - class parse_exception : public dpp::exception { }; - /** - * @brief Represents invalid access to dpp's cache or its members, which may or may not exist. - * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. - */ - class cache_exception : public dpp::exception { }; - /** - * @brief Represents an attempt to construct a cluster with an invalid bot token. - * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. - */ - class invalid_token_exception : public dpp::rest_exception { }; -#else - derived_exception(logic_exception, exception); - derived_exception(file_exception, exception); - derived_exception(connection_exception, exception); - derived_exception(voice_exception, exception); - derived_exception(rest_exception, exception); - derived_exception(invalid_token_exception, rest_exception); - derived_exception(length_exception, exception); - derived_exception(parse_exception, exception); - derived_exception(cache_exception, exception); -#endif - -}; - +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief The dpp::exception class derives from std::exception and supports some other + * ways of passing in error details such as via std::string. + */ +class exception : public std::exception +{ +protected: + /** + * @brief Exception message + */ + std::string msg; + +public: + + using std::exception::exception; + + /** + * @brief Construct a new exception object + */ + exception() = default; + + /** + * @brief Construct a new exception object + * + * @param what reason message + */ + explicit exception(const char* what) : msg(what) { } + + /** + * @brief Construct a new exception object + * + * @param what reason message + * @param len length of reason message + */ + exception(const char* what, size_t len) : msg(what, len) { } + + /** + * @brief Construct a new exception object + * + * @param what reason message + */ + explicit exception(const std::string& what) : msg(what) { } + + /** + * @brief Construct a new exception object + * + * @param what reason message + */ + explicit exception(std::string&& what) : msg(std::move(what)) { } + + /** + * @brief Construct a new exception object (copy constructor) + */ + exception(const exception&) = default; + + /** + * @brief Construct a new exception object (move constructor) + */ + exception(exception&&) = default; + + /** + * @brief Destroy the exception object + */ + ~exception() override = default; + + /** + * @brief Copy assignment operator + * + * @return exception& reference to self + */ + exception & operator = (const exception &) = default; + + /** + * @brief Move assignment operator + * + * @return exception& reference to self + */ + exception & operator = (exception&&) = default; + + /** + * @brief Get exception message + * + * @return const char* error message + */ + [[nodiscard]] const char* what() const noexcept override { return msg.c_str(); }; + +}; + +#ifndef _DOXYGEN_ + #define derived_exception(name, ancestor) class name : public dpp::ancestor { \ + public: \ + using dpp::ancestor::ancestor; \ + name() = default; \ + explicit name(const char* what) : ancestor(what) { } \ + name(const char* what, size_t len) : ancestor(what, len) { } \ + explicit name(const std::string& what) : ancestor(what) { } \ + explicit name(std::string&& what) : ancestor(what) { } \ + name(const name&) = default; \ + name(name&&) = default; \ + ~name() override = default; \ + name & operator = (const name &) = default; \ + name & operator = (name&&) = default; \ + [[nodiscard]] const char* what() const noexcept override { return msg.c_str(); }; \ + }; +#endif + +#ifdef _DOXYGEN_ + /* + * THESE DEFINITIONS ARE NOT THE REAL DEFINITIONS USED BY PROGRAM CODE. + * + * They exist only to cause Doxygen to emit proper documentation for the derived exception types. + * Proper definitions are emitted by the `derived_exception` macro in the "else" section. + */ + + /** + * @brief Represents an error in logic, e.g. you asked the library to do something the Discord API does not support + * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. + */ + class logic_exception : public dpp::exception { }; + /** + * @brief Represents an error reading or writing to a file + * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. + */ + class file_exception : public dpp::exception { }; + /** + * @brief Represents an error establishing or maintaining a connection + * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. + */ + class connection_exception : public dpp::exception { }; + /** + * @brief Represents an error with voice processing + * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. + */ + class voice_exception : public dpp::exception { }; + /** + * @brief Represents an error on a REST API call, e.g. a HTTPS request + * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. + */ + class rest_exception : public dpp::exception { }; + /** + * @brief Represents invalid length of argument being passed to a function + * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. + */ + class length_exception : public dpp::exception { }; + /** + * @brief Represents inability to parse data, usually caused by malformed JSON or ETF + * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. + */ + class parse_exception : public dpp::exception { }; + /** + * @brief Represents invalid access to dpp's cache or its members, which may or may not exist. + * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. + */ + class cache_exception : public dpp::exception { }; + /** + * @brief Represents an attempt to construct a cluster with an invalid bot token. + * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. + */ + class invalid_token_exception : public dpp::rest_exception { }; +#else + derived_exception(logic_exception, exception); + derived_exception(file_exception, exception); + derived_exception(connection_exception, exception); + derived_exception(voice_exception, exception); + derived_exception(rest_exception, exception); + derived_exception(invalid_token_exception, rest_exception); + derived_exception(length_exception, exception); + derived_exception(parse_exception, exception); + derived_exception(cache_exception, exception); +#endif + +}; + diff --git a/3rdParty/dpp/export.h b/3rdParty/dpp/export.h index 423729c98d..5fc9ac465b 100644 --- a/3rdParty/dpp/export.h +++ b/3rdParty/dpp/export.h @@ -1,66 +1,66 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once - -/* Compile-time check for C++17. - * Either one of the following causes a compile time error: - * __cplusplus not defined at all (this means we are being compiled on a C compiler) - * MSVC defined and _MSVC_LANG < 201703L (Visual Studio, but not C++17 or newer) - * MSVC not defined and __cplusplus < 201703L (Non-visual studio, but not C++17 or newer) - * The additional checks are required because MSVC doesn't correctly set __cplusplus to 201703L, - * which is hugely non-standard, but apparently "it broke stuff" so they dont ever change it - * from C++98. Ugh. - */ -#if (!defined(__cplusplus) || (defined(_MSC_VER) && (!defined(_MSVC_LANG) || _MSVC_LANG < 201703L)) || (!defined(_MSC_VER) && __cplusplus < 201703L)) - #error "D++ Requires a C++17 compatible C++ compiler. Please ensure that you have enabled C++17 in your compiler flags." -#endif - -#ifndef DPP_STATIC - /* Dynamic linked build as shared object or dll */ - #ifdef DPP_BUILD - /* Building the library */ - #ifdef _WIN32 - #include - #define DPP_EXPORT __declspec(dllexport) - #else - #define DPP_EXPORT - #endif - #else - /* Including the library */ - #ifdef _WIN32 - #define DPP_EXPORT __declspec(dllimport) - #else - #define DPP_EXPORT - #endif - #endif -#else - /* Static linked build */ - #if defined(_WIN32) && defined(DPP_BUILD) - #include - #endif - #define DPP_EXPORT -#endif - -#ifndef _WIN32 - #define SOCKET int -#else - #include +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once + +/* Compile-time check for C++17. + * Either one of the following causes a compile time error: + * __cplusplus not defined at all (this means we are being compiled on a C compiler) + * MSVC defined and _MSVC_LANG < 201703L (Visual Studio, but not C++17 or newer) + * MSVC not defined and __cplusplus < 201703L (Non-visual studio, but not C++17 or newer) + * The additional checks are required because MSVC doesn't correctly set __cplusplus to 201703L, + * which is hugely non-standard, but apparently "it broke stuff" so they dont ever change it + * from C++98. Ugh. + */ +#if (!defined(__cplusplus) || (defined(_MSC_VER) && (!defined(_MSVC_LANG) || _MSVC_LANG < 201703L)) || (!defined(_MSC_VER) && __cplusplus < 201703L)) + #error "D++ Requires a C++17 compatible C++ compiler. Please ensure that you have enabled C++17 in your compiler flags." +#endif + +#ifndef DPP_STATIC + /* Dynamic linked build as shared object or dll */ + #ifdef DPP_BUILD + /* Building the library */ + #ifdef _WIN32 + #include + #define DPP_EXPORT __declspec(dllexport) + #else + #define DPP_EXPORT + #endif + #else + /* Including the library */ + #ifdef _WIN32 + #define DPP_EXPORT __declspec(dllimport) + #else + #define DPP_EXPORT + #endif + #endif +#else + /* Static linked build */ + #if defined(_WIN32) && defined(DPP_BUILD) + #include + #endif + #define DPP_EXPORT +#endif + +#ifndef _WIN32 + #define SOCKET int +#else + #include #endif \ No newline at end of file diff --git a/3rdParty/dpp/guild.h b/3rdParty/dpp/guild.h index 0684705c65..48f7e3fbd6 100644 --- a/3rdParty/dpp/guild.h +++ b/3rdParty/dpp/guild.h @@ -1,980 +1,980 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -class channel; - -/** - * @brief Represents voice regions for guilds and channels. - * @deprecated Deprecated in favour of per-channel regions. - * Please use channel::rtc_region instead. - */ -enum region : uint8_t { - r_brazil, //!< Brazil - r_central_europe, //!< Central Europe - r_hong_kong, //!< Hong Kong - r_india, //!< India - r_japan, //!< Japan - r_russia, //!< Russia - r_singapore, //!< Singapore - r_south_africa, //!< South Africa - r_sydney, //!< Sydney - r_us_central, //!< US Central - r_us_east, //!< US East Coast - r_us_south, //!< US South - r_us_west, //!< US West Coast - r_western_europe //!< Western Europe -}; - -/** - * @brief The various flags that represent the status of a dpp::guild object - */ -enum guild_flags : uint32_t { - /** Large guild */ - g_large = 0b00000000000000000000000000000001, - /** Unavailable guild (inaccessible due to an outage) */ - g_unavailable = 0b00000000000000000000000000000010, - /** Guild has widget enabled */ - g_widget_enabled = 0b00000000000000000000000000000100, - /** Guild can have an invite splash image */ - g_invite_splash = 0b00000000000000000000000000001000, - /** Guild can have VIP regions */ - g_vip_regions = 0b00000000000000000000000000010000, - /** Guild can have a vanity url */ - g_vanity_url = 0b00000000000000000000000000100000, - /** Guild is verified */ - g_verified = 0b00000000000000000000000001000000, - /** Guild is partnered */ - g_partnered = 0b00000000000000000000000010000000, - /** Community features enabled */ - g_community = 0b00000000000000000000000100000000, - /** Guild has commerce features enabled - * @deprecated Removed by Discord - */ - g_commerce = 0b00000000000000000000001000000000, - /** Guild has access to create announcement channels */ - g_news = 0b00000000000000000000010000000000, - /** Guild is discoverable in discovery */ - g_discoverable = 0b00000000000000000000100000000000, - /** Guild is featureable */ - g_featureable = 0b00000000000000000001000000000000, - /** Guild can have an animated icon (doesn't mean it actually has one though) */ - g_animated_icon = 0b00000000000000000010000000000000, - /** Guild can have a banner image */ - g_banner = 0b00000000000000000100000000000000, - /** Guild has a welcome screen */ - g_welcome_screen_enabled = 0b00000000000000001000000000000000, - /** Guild has a member verification gate */ - g_member_verification_gate = 0b00000000000000010000000000000000, - /** Guild has a preview */ - g_preview_enabled = 0b00000000000000100000000000000000, - /** Guild join notifications are off */ - g_no_join_notifications = 0b00000000000001000000000000000000, - /** Guild boost notifications are off */ - g_no_boost_notifications = 0b00000000000010000000000000000000, - /** Guild has an actual animated icon (set by the icon hash starting with 'a_') */ - g_has_animated_icon = 0b00000000000100000000000000000000, - /** Guild has an actual animated banner (set by the icon hash starting with 'a_') */ - g_has_animated_banner = 0b00000000001000000000000000000000, - /** Guild setup tips are off */ - g_no_setup_tips = 0b00000000010000000000000000000000, - /** "Wave to say hi" sticker prompt buttons are off */ - g_no_sticker_greeting = 0b00000000100000000000000000000000, - /** guild has enabled monetization */ - g_monetization_enabled = 0b00000001000000000000000000000000, - /** guild has increased custom sticker slots */ - g_more_stickers = 0b00000010000000000000000000000000, - /** guild has access to create private threads - * @deprecated Removed by Discord - * */ - g_private_threads = 0b00000100000000000000000000000000, - /** guild is able to set role icons */ - g_role_icons = 0b00001000000000000000000000000000, - /** guild has access to the seven day archive time for threads */ - g_seven_day_thread_archive = 0b00010000000000000000000000000000, - /** guild has access to the three day archive time for threads */ - g_three_day_thread_archive = 0b00100000000000000000000000000000, - /** guild has enabled ticketed events */ - g_ticketed_events = 0b01000000000000000000000000000000, - /** guild can have channel banners */ - g_channel_banners = 0b10000000000000000000000000000000, -}; - -/** - * @brief Additional boolean flag values for guild, as guild_flags is full - */ -enum guild_flags_extra : uint8_t { - /** Guild has premium progress bar enabled */ - g_premium_progress_bar_enabled = 0b00000001, - /** Guild can have an animated banner (doesn't mean it actually has one though) */ - g_animated_banner = 0b00000010, - /** Guild has auto moderation */ - g_auto_moderation = 0b00000100, - /** Guild has paused invites, preventing new users from joining */ - g_invites_disabled = 0b00001000, - /** Guild has been set as support server of an app in the App Directory */ - g_developer_support_server = 0b00010000, -}; - -/** - * @brief Various flags that can be used to indicate the status of a guild member. - * @note Use set_mute and set_deaf member functions and do not toggle the bits yourself. - */ -enum guild_member_flags : uint8_t { - /** Member deafened in voice channels */ - gm_deaf = 0b00000001, - /** Member muted in voice channels */ - gm_mute = 0b00000010, - /** Member pending verification by membership screening */ - gm_pending = 0b00000100, - /** Member has animated guild-specific avatar */ - gm_animated_avatar = 0b00001000, - /** gm_deaf or gm_mute has been toggled */ - gm_voice_action = 0b00010000, -}; - -/** - * @brief Represents dpp::user membership upon a dpp::guild. - * This contains the user's nickname, guild roles, and any other guild-specific flags. - */ -class DPP_EXPORT guild_member { -public: - /** Nickname, or empty string if they don't have a nickname on this guild */ - std::string nickname; - /** List of roles this user has on this guild */ - std::vector roles; - /** Guild id */ - snowflake guild_id; - /** User id */ - snowflake user_id; - /** User avatar (per-server avatar is a nitro only feature) */ - utility::iconhash avatar; - /** timestamp of when the time out will be removed; until then, they cannot interact with the guild */ - time_t communication_disabled_until; - /** Date and time the user joined the guild */ - time_t joined_at; - /** Boosting since */ - time_t premium_since; - /** A set of flags built from the bitmask defined by dpp::guild_member_flags */ - uint8_t flags; - - /** Default constructor */ - guild_member(); - - /** Fill this object from a json object. - * @param j The json object to get data from - * @param g_id The guild id to associate the member with - * @param u_id The user id to associate the member with - * @return Reference to self for call chaining - */ - guild_member& fill_from_json(nlohmann::json* j, snowflake g_id, snowflake u_id); - - /** - * @brief Build json string for the member object - * - * @param with_id Add ID to output - * @return std::string json string - */ - std::string build_json(bool with_id = false) const; - - /** - * @brief Returns true if the user is in time-out (communication disabled) - * - * @return true user is in time-out - * @return false user is not in time-out - */ - bool is_communication_disabled() const; - - /** - * @brief Returns true if the user is deafened - * - * @return true user is deafened - * @return false user is not deafened - */ - bool is_deaf() const; - - /** - * @brief Returns true if the user is muted - * - * @return true user muted - * @return false user not muted - */ - bool is_muted() const; - - /** - * @brief Returns true if pending verification by membership screening - * - * @return true user has completed membership screening - * @return false user has not completed membership screening - */ - bool is_pending() const; - - /** - * @brief Returns true if the user's per-guild custom avatar is animated - * - * @return true user's custom avatar is animated - * @return false user's custom avatar is not animated - */ - bool has_animated_guild_avatar() const; - - /** - * @brief Returns the members per guild avatar if they have one, otherwise returns an empty string - * - * @note per-server avatar is a nitro only feature so it might be not set. If you need the real user avatar, use user::get_avatar_url. - * - * @param size The size of the avatar in pixels. It can be any power of two between 16 and 4096. If not specified, the default sized avatar is returned. - * @return std::string avatar url or empty string - */ - std::string get_avatar_url(uint16_t size = 0) const; - - /** - * @brief Set the nickname - * - * @param nick Nickname to set - * - * @return guild_member& reference to self - */ - guild_member& set_nickname(const std::string& nick); - - /** - * @brief Get the dpp::user object for this member - * @return dpp::user user object. If not in cache, it returns nullptr - * - * - */ - dpp::user* get_user() const; - - /** - * @brief Set whether the user is muted in voice channels - * - * @param is_muted value to set, true if mute in voice channels - * - * @return guild_member& reference to self - */ - guild_member& set_mute(const bool is_muted); - - /** - * @brief Set whether the user is deafened in voice channels - * - * @param is_deafened value to set, true if deaf in voice channels - * - * @return guild_member& reference to self - */ - guild_member& set_deaf(const bool is_deafened); - - /** - * @brief Set communication_disabled_until - * - * @param timestamp timestamp until communication is disabled - * - * @return guild_member& reference to self - */ - guild_member& set_communication_disabled_until(const time_t timestamp); - - /** - * @brief Return a ping/mention for the user by nickname - * - * @return std::string mention - */ - std::string get_mention() const; -}; - -/** - * @brief Defines a channel on a server's welcome screen - */ -struct welcome_channel_t { - /// the description shown for the channel - std::string description; - /// the emoji name if custom, the unicode character if standard, or null if no emoji is set - std::string emoji_name; - /// the channel's id - snowflake channel_id = 0; - /// the emoji id, if the emoji is custom - snowflake emoji_id = 0; -}; - - -/** - * @brief Defines a server's welcome screen - */ -struct welcome_screen_t { - /// the server description shown in the welcome screen - std::string description; - /// the channels shown in the welcome screen, up to 5 - std::vector welcome_channels; -}; - -/** - * @brief Guild NSFW level. - * Used to represent just how naughty this guild is. Naughty guild, go sit in the corner. - * @note This is set by Discord, and cannot be set by any bot or user on the guild. - */ -enum guild_nsfw_level_t : uint8_t { - /// Default setting, not configured - nsfw_default = 0, - /// Explicit content may be in this guild - nsfw_explicit = 1, - /// Safe for work content only - nsfw_safe = 2, - /// Age restricted, 18+ - nsfw_age_restricted = 3 -}; - -/** - * @brief explicit content filter level. - * This is set by a guild admin, but can be forced to a setting if the server is verified, - * partnered, official etc. - */ -enum guild_explicit_content_t : uint8_t { - /// media content will not be scanned - expl_disabled = 0, - /// media content sent by members without roles will be scanned - expl_members_without_roles = 1, - /// media content sent by all members will be scanned - expl_all_members = 2 -}; - -/** - * @brief MFA level for server. If set to elevated all moderators need MFA to perform specific - * actions such as kick or ban. - */ -enum mfa_level_t : uint8_t { - /// MFA not elevated - mfa_none = 0, - /// MFA elevated - mfa_elevated = 1 -}; - -/** - * @brief Guild verification level - */ -enum verification_level_t : uint8_t { - /// unrestricted - ver_none = 0, - /// must have verified email on account - ver_low = 1, - /// must be registered on Discord for longer than 5 minutes - ver_medium = 2, - /// must be a member of the server for longer than 10 minutes - ver_high = 3, - /// must have a verified phone number - ver_very_high = 4, -}; - -/** - * @brief Default message notification level - */ -enum default_message_notification_t: uint8_t { - /// members will receive notifications for all messages by default - dmn_all = 0, - /// members will receive notifications only for messages that \@mention them by default - dmn_only_mentions = 1, -}; - -/** - * @brief Premium tier - */ -enum guild_premium_tier_t: uint8_t { - /// guild has not unlocked any Server Boost perks - tier_none = 0, - /// guild has unlocked Server Boost level 1 perks - tier_1 = 1, - /// guild has unlocked Server Boost level 2 perks - tier_2 = 2, - /// guild has unlocked Server Boost level 3 perks - tier_3 = 3, -}; - -/** - * @brief Voice AFK timeout values for guild::afk_timeout - */ -enum guild_afk_timeout_t: uint8_t { - /// AFK timeout disabled - afk_off, - /// AFK timeout of 1 Minute - afk_60, - /// AFK timeout of 5 Minutes - afk_300, - /// AFK timeout of 15 Minutes - afk_900, - /// AFK timeout of 30 Minutes - afk_1800, - /// AFK timeout of 1 Hour - afk_3600, -}; - -/** @brief Guild members container - */ -typedef std::unordered_map members_container; - -/** - * @brief Represents a guild on Discord (AKA a server) - */ -class DPP_EXPORT guild : public managed, public json_interface { -public: - /** Guild name */ - std::string name; - - /** Server description */ - std::string description; - - /** - * @brief Vanity url code for verified or partnered servers and boost level 3 - * @note This field cannot be set from the API. Attempts to change this value will be - * silently ignored even if the correct number of boosts or verified/partnered status exist. - * See: https://github.com/discord/discord-api-docs/issues/519 - */ - std::string vanity_url_code; - - /** Roles defined on this server */ - std::vector roles; - - /** List of channels on this server */ - std::vector channels; - - /** List of threads on this server */ - std::vector threads; - - /** List of emojis - */ - std::vector emojis; - - /** List of members in voice channels in the guild. - */ - std::map voice_members; - - /** List of guild members. Note that when you first receive the - * guild create event, this may be empty or near empty. - * This depends upon your dpp::intents and the size of your bot. - * It will be filled by guild member chunk requests. - */ - members_container members; - - /** Welcome screen - */ - welcome_screen_t welcome_screen; - - /** Guild icon hash */ - utility::iconhash icon; - - /** Guild splash hash */ - utility::iconhash splash; - - /** Guild discovery splash hash */ - utility::iconhash discovery_splash; - - /** Server banner hash */ - utility::iconhash banner; - - /** Snowflake id of guild owner */ - snowflake owner_id; - - /** Snowflake ID of AFK voice channel or 0 */ - snowflake afk_channel_id; - - /** ID of creating application, if any, or 0 */ - snowflake application_id; - - /** ID of system channel where discord update messages are sent */ - snowflake system_channel_id; - - /** ID of rules channel for communities */ - snowflake rules_channel_id; - - /** Public updates channel id or 0 */ - snowflake public_updates_channel_id; - - /** Snowflake ID of widget channel, or 0 */ - snowflake widget_channel_id; - - /** Approximate member count. May be sent as zero */ - uint32_t member_count; - - /** Flags bitmask as defined by values within dpp::guild_flags */ - uint32_t flags; - - /** - * @brief the maximum number of presences for the guild. - * @note Generally Discord always fills this with 0, apart from for the largest of guilds - */ - uint32_t max_presences; - - /** - * @brief the maximum number of members for the guild - */ - uint32_t max_members; - - /** Shard ID of the guild */ - uint16_t shard_id; - - /** Number of boosters */ - uint16_t premium_subscription_count; - - /** Voice AFK timeout before moving users to AFK channel */ - guild_afk_timeout_t afk_timeout; - - /** Maximum users in a video channel, or 0 */ - uint8_t max_video_channel_users; - - /** Setting for how notifications are to be delivered to users */ - default_message_notification_t default_message_notifications; - - /** Boost level */ - guild_premium_tier_t premium_tier; - - /** Verification level of server */ - verification_level_t verification_level; - - /** Whether or not explicit content filtering is enable and what setting it is */ - guild_explicit_content_t explicit_content_filter; - - /** If multi factor authentication is required for moderators or not */ - mfa_level_t mfa_level; - - /** - * @brief Guild NSFW level - */ - guild_nsfw_level_t nsfw_level; - - /** - * @brief Additional flags - */ - uint8_t flags_extra; - - /** Default constructor, zeroes all values */ - guild(); - - /** - * @brief Destroy the guild object - */ - virtual ~guild() = default; - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - guild& fill_from_json(nlohmann::json* j); - - /** Read class values from json object - * @param shard originating shard - * @param j A json object to read from - * @return A reference to self - */ - guild& fill_from_json(class discord_client* shard, nlohmann::json* j); - - /** Build a JSON string from this object. - * @param with_id True if an ID is to be included in the JSON - * @return JSON string - */ - std::string build_json(bool with_id = false) const; - - /** - * @brief Compute the base permissions for a member on this guild, - * before channel overwrites are applied. - * This method takes into consideration the following cases: - * - Guild owner - * - Guild roles including \@everyone - * - * @param user User to get permissions for - * @return permission permissions bitmask - * @note Requires role cache to be enabled (it's enabled by default). - * - * @warning The method will search for the guild member in the cache by the users id. - * If the guild member is not in cache, the method will always return 0. - */ - permission base_permissions(const class user* user) const; - - /** - * @brief Compute the base permissions for a member on this guild, - * before channel overwrites are applied. - * This method takes into consideration the following cases: - * - Guild owner - * - Guild roles including \@everyone - * - * @param member member to get permissions for - * @return permission permissions bitmask - * @note Requires role cache to be enabled (it's enabled by default). - */ - permission base_permissions(const guild_member &member) const; - - /** - * @brief Get the overall permissions for a member in this channel, including channel overwrites, role permissions and admin privileges. - * - * @param base_permissions base permissions before overwrites, - * from guild::base_permissions - * @param user The user to resolve the permissions for - * @param channel Channel to compute permission overwrites for - * @return permission Permission overwrites for the member. Made of bits in dpp::permissions. - * @note Requires role cache to be enabled (it's enabled by default). - * - * @warning The method will search for the guild member in the cache by the users id. - * If the guild member is not in cache, the method will always return 0. - */ - permission permission_overwrites(const uint64_t base_permissions, const user* user, const channel* channel) const; - - /** - * @brief Get the overall permissions for a member in this channel, including channel overwrites, role permissions and admin privileges. - * - * @param member The member to resolve the permissions for - * @param channel Channel to compute permission overwrites for - * @return permission Permission overwrites for the member. Made of bits in dpp::permissions. - * @note Requires role cache to be enabled (it's enabled by default). - */ - permission permission_overwrites(const guild_member &member, const channel &channel) const; - - /** - * @brief Rehash members map - */ - void rehash_members(); - - /** - * @brief Connect to a voice channel another guild member is in - * - * @param user_id User id to join - * @param self_mute True if the bot should mute itself - * @param self_deaf True if the bot should deafen itself - * @return True if the user specified is in a vc, false if they aren't - * @note This is NOT a synchronous blocking call! The bot isn't instantly ready to send or listen for audio, - * as we have to wait for the connection to the voice server to be established! - * e.g. wait for dpp::cluster::on_voice_ready event, and then send the audio within that event. - */ - bool connect_member_voice(snowflake user_id, bool self_mute = false, bool self_deaf = false); - - /** - * @brief Get the banner url of the guild if it have one, otherwise returns an empty string - * - * @param size The size of the banner in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized banner is returned. - * @return std::string banner url or empty string - */ - std::string get_banner_url(uint16_t size = 0) const; - - /** - * @brief Get the discovery splash url of the guild if it have one, otherwise returns an empty string - * - * @param size The size of the discovery splash in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized discovery splash is returned. - * @return std::string discovery splash url or empty string - */ - std::string get_discovery_splash_url(uint16_t size = 0) const; - - /** - * @brief Get the icon url of the guild if it have one, otherwise returns an empty string - * - * @param size The size of the icon in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized icon is returned. - * @return std::string icon url or empty string - */ - std::string get_icon_url(uint16_t size = 0) const; - - /** - * @brief Get the splash url of the guild if it have one, otherwise returns an empty string - * - * @param size The size of the splash in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized splash is returned. - * @return std::string splash url or empty string - */ - std::string get_splash_url(uint16_t size = 0) const; - - /** - * @brief Set the name of the guild in the object - * Min length: 2, Max length: 100 (not including leading/trailing spaces) - * @param n Guild name - * @return guild& reference to self - * @throw dpp::length_exception if guild name is too short - */ - guild& set_name(const std::string& n); - - /** - * @brief Is a large server (>250 users) - * @return bool is a large guild - */ - bool is_large() const; - - /** - * @brief Is unavailable due to outage (most other fields will be blank or outdated - * @return bool is unavailable - */ - bool is_unavailable() const; - - /** - * @brief Widget is enabled for this server - * @return bool widget enabled - */ - bool widget_enabled() const; - - /** - * @brief Guild has access to set an invite splash background - * @return bool can have an invite splash - */ - bool has_invite_splash() const; - - /** - * @brief Guild has access to set 384kbps bitrate in voice - * @return bool can have VIP voice regions - */ - bool has_vip_regions() const; - - /** - * @brief Guild has access to set a vanity URL - * @return bool can have vanity url - */ - bool has_vanity_url() const; - - /** - * @brief Guild is a verified server - * @return bool is verified - */ - bool is_verified() const; - - /** - * @brief Guild is a discord partnered server - * @return bool is discord partnered - */ - bool is_partnered() const; - - /** - * @brief Has enabled community - * @return bool has enabled community - */ - bool is_community() const; - - /** - * @brief Guild has access to use commerce features - * @return bool has commerce features enabled - * @deprecated Removed by Discord - */ - bool has_commerce() const; - - /** - * @brief Guild has access to create announcement channels - * @return bool has announcement channels features enabled - */ - bool has_news() const; - - /** - * @brief Guild is discoverable - * @return bool is discoverable - */ - bool is_discoverable() const; - - /** - * @brief Guild is featurable - * @return bool is featurable - */ - bool is_featureable() const; - - /** - * @brief Guild has access to set an animated guild banner image - * @return bool can have animated banner image - */ - bool has_animated_banner() const; - - /** - * @brief Guild has auto moderation features - * @return bool has auto moderation features - */ - bool has_auto_moderation() const; - - /** - * @brief Guild has been set as a support server on the App Directory - * @return bool has been set as a support server of an app in the app directory - */ - bool has_support_server() const; - - /** - * @brief Guild has access to set an animated guild icon - * @return bool can have animated icon - */ - bool has_animated_icon() const; - - /** - * @brief Guild has access to set a guild banner image - * @return bool can have banner image - */ - bool has_banner() const; - - /** - * @brief Guild has enabled the welcome screen - * @return bool enabled welcome screen - */ - bool is_welcome_screen_enabled() const; - - /** - * @brief Guild has enabled membership screening - * @return bool has membership screening - */ - bool has_member_verification_gate() const; - - /** - * @brief Guild has preview enabled - * @return bool has preview - */ - bool is_preview_enabled() const; - - /** - * @brief Guild icon is actually an animated gif - * @return bool is animated gif - */ - bool has_animated_icon_hash() const; - - /** - * @brief Guild banner is actually an animated gif - * @return bool is animated gif - */ - bool has_animated_banner_hash() const; - - - /** - * @brief guild has access to monetization features - * @return bool - */ - bool has_monetization_enabled() const; - - /** - * @brief guild has increased custom sticker slots - * @return bool has more stickers - */ - bool has_more_stickers() const; - - /** - * @brief guild has access to create private threads - * @return bool has private threads - * @deprecated Removed by Discord - */ - bool has_private_threads() const; - - /** - * @brief guild is able to set role icons - * @return bool has role icons - */ - bool has_role_icons() const; - - /** - * @brief guild has access to the seven day archive time for threads - * @return bool has seven day thread archive - */ - bool has_seven_day_thread_archive() const; - - /** - * @brief guild has access to the three day archive time for threads - * @return bool has three day thread archive - */ - bool has_three_day_thread_archive() const; - - /** - * @brief guild has enabled ticketed events - * @return bool has ticketed events - */ - bool has_ticketed_events() const; - - /** - * @brief guild has access to channel banners feature - * @return bool has channel banners - */ - bool has_channel_banners() const; - - /** - * @brief True if the premium progress bar is enabled - * @return bool has progress bar enabled - */ - bool has_premium_progress_bar_enabled() const; - - /** - * @brief True if has paused invites, preventing new users from joining - * @return bool has paused invites - */ - bool has_invites_disabled() const; -}; - -/** A container of guilds */ -typedef std::unordered_map guild_map; - -/** - * @brief Represents a guild widget, simple web widget of member list - */ -class DPP_EXPORT guild_widget { -public: - /** - * @brief Channel widget points to - */ - snowflake channel_id; - - /** - * @brief True if enabled - */ - bool enabled; - - /** - * @brief Construct a new guild widget object - */ - guild_widget(); - - /** - * @brief Build a guild widget from json - * - * @param j json to build from - * @return guild_widget& reference to self - */ - guild_widget& fill_from_json(nlohmann::json* j); - - /** - * @brief Build json for a guild widget - * - * @param with_id Add ID to output - * @return std::string guild widget stringified json - */ - std::string build_json(bool with_id = false) const; -}; - -/** - * @brief helper function to deserialize a guild_member from json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param gm guild_member to be deserialized - */ -void from_json(const nlohmann::json& j, guild_member& gm); - -/** A container of guild members */ -typedef std::unordered_map guild_member_map; - -/** - * @brief Get the guild_member from cache of given IDs - * - * @param guild_id ID of the guild to find guild_member for - * @param user_id ID of the user to find guild_member for - * - * @throw dpp::cache_exception if the guild or guild_member is not found in the cache - * @return guild_member the cached object, if found - */ -guild_member DPP_EXPORT find_guild_member(const snowflake guild_id, const snowflake user_id); - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +class channel; + +/** + * @brief Represents voice regions for guilds and channels. + * @deprecated Deprecated in favour of per-channel regions. + * Please use channel::rtc_region instead. + */ +enum region : uint8_t { + r_brazil, //!< Brazil + r_central_europe, //!< Central Europe + r_hong_kong, //!< Hong Kong + r_india, //!< India + r_japan, //!< Japan + r_russia, //!< Russia + r_singapore, //!< Singapore + r_south_africa, //!< South Africa + r_sydney, //!< Sydney + r_us_central, //!< US Central + r_us_east, //!< US East Coast + r_us_south, //!< US South + r_us_west, //!< US West Coast + r_western_europe //!< Western Europe +}; + +/** + * @brief The various flags that represent the status of a dpp::guild object + */ +enum guild_flags : uint32_t { + /** Large guild */ + g_large = 0b00000000000000000000000000000001, + /** Unavailable guild (inaccessible due to an outage) */ + g_unavailable = 0b00000000000000000000000000000010, + /** Guild has widget enabled */ + g_widget_enabled = 0b00000000000000000000000000000100, + /** Guild can have an invite splash image */ + g_invite_splash = 0b00000000000000000000000000001000, + /** Guild can have VIP regions */ + g_vip_regions = 0b00000000000000000000000000010000, + /** Guild can have a vanity url */ + g_vanity_url = 0b00000000000000000000000000100000, + /** Guild is verified */ + g_verified = 0b00000000000000000000000001000000, + /** Guild is partnered */ + g_partnered = 0b00000000000000000000000010000000, + /** Community features enabled */ + g_community = 0b00000000000000000000000100000000, + /** Guild has commerce features enabled + * @deprecated Removed by Discord + */ + g_commerce = 0b00000000000000000000001000000000, + /** Guild has access to create announcement channels */ + g_news = 0b00000000000000000000010000000000, + /** Guild is discoverable in discovery */ + g_discoverable = 0b00000000000000000000100000000000, + /** Guild is featureable */ + g_featureable = 0b00000000000000000001000000000000, + /** Guild can have an animated icon (doesn't mean it actually has one though) */ + g_animated_icon = 0b00000000000000000010000000000000, + /** Guild can have a banner image */ + g_banner = 0b00000000000000000100000000000000, + /** Guild has a welcome screen */ + g_welcome_screen_enabled = 0b00000000000000001000000000000000, + /** Guild has a member verification gate */ + g_member_verification_gate = 0b00000000000000010000000000000000, + /** Guild has a preview */ + g_preview_enabled = 0b00000000000000100000000000000000, + /** Guild join notifications are off */ + g_no_join_notifications = 0b00000000000001000000000000000000, + /** Guild boost notifications are off */ + g_no_boost_notifications = 0b00000000000010000000000000000000, + /** Guild has an actual animated icon (set by the icon hash starting with 'a_') */ + g_has_animated_icon = 0b00000000000100000000000000000000, + /** Guild has an actual animated banner (set by the icon hash starting with 'a_') */ + g_has_animated_banner = 0b00000000001000000000000000000000, + /** Guild setup tips are off */ + g_no_setup_tips = 0b00000000010000000000000000000000, + /** "Wave to say hi" sticker prompt buttons are off */ + g_no_sticker_greeting = 0b00000000100000000000000000000000, + /** guild has enabled monetization */ + g_monetization_enabled = 0b00000001000000000000000000000000, + /** guild has increased custom sticker slots */ + g_more_stickers = 0b00000010000000000000000000000000, + /** guild has access to create private threads + * @deprecated Removed by Discord + * */ + g_private_threads = 0b00000100000000000000000000000000, + /** guild is able to set role icons */ + g_role_icons = 0b00001000000000000000000000000000, + /** guild has access to the seven day archive time for threads */ + g_seven_day_thread_archive = 0b00010000000000000000000000000000, + /** guild has access to the three day archive time for threads */ + g_three_day_thread_archive = 0b00100000000000000000000000000000, + /** guild has enabled ticketed events */ + g_ticketed_events = 0b01000000000000000000000000000000, + /** guild can have channel banners */ + g_channel_banners = 0b10000000000000000000000000000000, +}; + +/** + * @brief Additional boolean flag values for guild, as guild_flags is full + */ +enum guild_flags_extra : uint8_t { + /** Guild has premium progress bar enabled */ + g_premium_progress_bar_enabled = 0b00000001, + /** Guild can have an animated banner (doesn't mean it actually has one though) */ + g_animated_banner = 0b00000010, + /** Guild has auto moderation */ + g_auto_moderation = 0b00000100, + /** Guild has paused invites, preventing new users from joining */ + g_invites_disabled = 0b00001000, + /** Guild has been set as support server of an app in the App Directory */ + g_developer_support_server = 0b00010000, +}; + +/** + * @brief Various flags that can be used to indicate the status of a guild member. + * @note Use set_mute and set_deaf member functions and do not toggle the bits yourself. + */ +enum guild_member_flags : uint8_t { + /** Member deafened in voice channels */ + gm_deaf = 0b00000001, + /** Member muted in voice channels */ + gm_mute = 0b00000010, + /** Member pending verification by membership screening */ + gm_pending = 0b00000100, + /** Member has animated guild-specific avatar */ + gm_animated_avatar = 0b00001000, + /** gm_deaf or gm_mute has been toggled */ + gm_voice_action = 0b00010000, +}; + +/** + * @brief Represents dpp::user membership upon a dpp::guild. + * This contains the user's nickname, guild roles, and any other guild-specific flags. + */ +class DPP_EXPORT guild_member { +public: + /** Nickname, or empty string if they don't have a nickname on this guild */ + std::string nickname; + /** List of roles this user has on this guild */ + std::vector roles; + /** Guild id */ + snowflake guild_id; + /** User id */ + snowflake user_id; + /** User avatar (per-server avatar is a nitro only feature) */ + utility::iconhash avatar; + /** timestamp of when the time out will be removed; until then, they cannot interact with the guild */ + time_t communication_disabled_until; + /** Date and time the user joined the guild */ + time_t joined_at; + /** Boosting since */ + time_t premium_since; + /** A set of flags built from the bitmask defined by dpp::guild_member_flags */ + uint8_t flags; + + /** Default constructor */ + guild_member(); + + /** Fill this object from a json object. + * @param j The json object to get data from + * @param g_id The guild id to associate the member with + * @param u_id The user id to associate the member with + * @return Reference to self for call chaining + */ + guild_member& fill_from_json(nlohmann::json* j, snowflake g_id, snowflake u_id); + + /** + * @brief Build json string for the member object + * + * @param with_id Add ID to output + * @return std::string json string + */ + std::string build_json(bool with_id = false) const; + + /** + * @brief Returns true if the user is in time-out (communication disabled) + * + * @return true user is in time-out + * @return false user is not in time-out + */ + bool is_communication_disabled() const; + + /** + * @brief Returns true if the user is deafened + * + * @return true user is deafened + * @return false user is not deafened + */ + bool is_deaf() const; + + /** + * @brief Returns true if the user is muted + * + * @return true user muted + * @return false user not muted + */ + bool is_muted() const; + + /** + * @brief Returns true if pending verification by membership screening + * + * @return true user has completed membership screening + * @return false user has not completed membership screening + */ + bool is_pending() const; + + /** + * @brief Returns true if the user's per-guild custom avatar is animated + * + * @return true user's custom avatar is animated + * @return false user's custom avatar is not animated + */ + bool has_animated_guild_avatar() const; + + /** + * @brief Returns the members per guild avatar if they have one, otherwise returns an empty string + * + * @note per-server avatar is a nitro only feature so it might be not set. If you need the real user avatar, use user::get_avatar_url. + * + * @param size The size of the avatar in pixels. It can be any power of two between 16 and 4096. If not specified, the default sized avatar is returned. + * @return std::string avatar url or empty string + */ + std::string get_avatar_url(uint16_t size = 0) const; + + /** + * @brief Set the nickname + * + * @param nick Nickname to set + * + * @return guild_member& reference to self + */ + guild_member& set_nickname(const std::string& nick); + + /** + * @brief Get the dpp::user object for this member + * @return dpp::user user object. If not in cache, it returns nullptr + * + * + */ + dpp::user* get_user() const; + + /** + * @brief Set whether the user is muted in voice channels + * + * @param is_muted value to set, true if mute in voice channels + * + * @return guild_member& reference to self + */ + guild_member& set_mute(const bool is_muted); + + /** + * @brief Set whether the user is deafened in voice channels + * + * @param is_deafened value to set, true if deaf in voice channels + * + * @return guild_member& reference to self + */ + guild_member& set_deaf(const bool is_deafened); + + /** + * @brief Set communication_disabled_until + * + * @param timestamp timestamp until communication is disabled + * + * @return guild_member& reference to self + */ + guild_member& set_communication_disabled_until(const time_t timestamp); + + /** + * @brief Return a ping/mention for the user by nickname + * + * @return std::string mention + */ + std::string get_mention() const; +}; + +/** + * @brief Defines a channel on a server's welcome screen + */ +struct welcome_channel_t { + /// the description shown for the channel + std::string description; + /// the emoji name if custom, the unicode character if standard, or null if no emoji is set + std::string emoji_name; + /// the channel's id + snowflake channel_id = 0; + /// the emoji id, if the emoji is custom + snowflake emoji_id = 0; +}; + + +/** + * @brief Defines a server's welcome screen + */ +struct welcome_screen_t { + /// the server description shown in the welcome screen + std::string description; + /// the channels shown in the welcome screen, up to 5 + std::vector welcome_channels; +}; + +/** + * @brief Guild NSFW level. + * Used to represent just how naughty this guild is. Naughty guild, go sit in the corner. + * @note This is set by Discord, and cannot be set by any bot or user on the guild. + */ +enum guild_nsfw_level_t : uint8_t { + /// Default setting, not configured + nsfw_default = 0, + /// Explicit content may be in this guild + nsfw_explicit = 1, + /// Safe for work content only + nsfw_safe = 2, + /// Age restricted, 18+ + nsfw_age_restricted = 3 +}; + +/** + * @brief explicit content filter level. + * This is set by a guild admin, but can be forced to a setting if the server is verified, + * partnered, official etc. + */ +enum guild_explicit_content_t : uint8_t { + /// media content will not be scanned + expl_disabled = 0, + /// media content sent by members without roles will be scanned + expl_members_without_roles = 1, + /// media content sent by all members will be scanned + expl_all_members = 2 +}; + +/** + * @brief MFA level for server. If set to elevated all moderators need MFA to perform specific + * actions such as kick or ban. + */ +enum mfa_level_t : uint8_t { + /// MFA not elevated + mfa_none = 0, + /// MFA elevated + mfa_elevated = 1 +}; + +/** + * @brief Guild verification level + */ +enum verification_level_t : uint8_t { + /// unrestricted + ver_none = 0, + /// must have verified email on account + ver_low = 1, + /// must be registered on Discord for longer than 5 minutes + ver_medium = 2, + /// must be a member of the server for longer than 10 minutes + ver_high = 3, + /// must have a verified phone number + ver_very_high = 4, +}; + +/** + * @brief Default message notification level + */ +enum default_message_notification_t: uint8_t { + /// members will receive notifications for all messages by default + dmn_all = 0, + /// members will receive notifications only for messages that \@mention them by default + dmn_only_mentions = 1, +}; + +/** + * @brief Premium tier + */ +enum guild_premium_tier_t: uint8_t { + /// guild has not unlocked any Server Boost perks + tier_none = 0, + /// guild has unlocked Server Boost level 1 perks + tier_1 = 1, + /// guild has unlocked Server Boost level 2 perks + tier_2 = 2, + /// guild has unlocked Server Boost level 3 perks + tier_3 = 3, +}; + +/** + * @brief Voice AFK timeout values for guild::afk_timeout + */ +enum guild_afk_timeout_t: uint8_t { + /// AFK timeout disabled + afk_off, + /// AFK timeout of 1 Minute + afk_60, + /// AFK timeout of 5 Minutes + afk_300, + /// AFK timeout of 15 Minutes + afk_900, + /// AFK timeout of 30 Minutes + afk_1800, + /// AFK timeout of 1 Hour + afk_3600, +}; + +/** @brief Guild members container + */ +typedef std::unordered_map members_container; + +/** + * @brief Represents a guild on Discord (AKA a server) + */ +class DPP_EXPORT guild : public managed, public json_interface { +public: + /** Guild name */ + std::string name; + + /** Server description */ + std::string description; + + /** + * @brief Vanity url code for verified or partnered servers and boost level 3 + * @note This field cannot be set from the API. Attempts to change this value will be + * silently ignored even if the correct number of boosts or verified/partnered status exist. + * See: https://github.com/discord/discord-api-docs/issues/519 + */ + std::string vanity_url_code; + + /** Roles defined on this server */ + std::vector roles; + + /** List of channels on this server */ + std::vector channels; + + /** List of threads on this server */ + std::vector threads; + + /** List of emojis + */ + std::vector emojis; + + /** List of members in voice channels in the guild. + */ + std::map voice_members; + + /** List of guild members. Note that when you first receive the + * guild create event, this may be empty or near empty. + * This depends upon your dpp::intents and the size of your bot. + * It will be filled by guild member chunk requests. + */ + members_container members; + + /** Welcome screen + */ + welcome_screen_t welcome_screen; + + /** Guild icon hash */ + utility::iconhash icon; + + /** Guild splash hash */ + utility::iconhash splash; + + /** Guild discovery splash hash */ + utility::iconhash discovery_splash; + + /** Server banner hash */ + utility::iconhash banner; + + /** Snowflake id of guild owner */ + snowflake owner_id; + + /** Snowflake ID of AFK voice channel or 0 */ + snowflake afk_channel_id; + + /** ID of creating application, if any, or 0 */ + snowflake application_id; + + /** ID of system channel where discord update messages are sent */ + snowflake system_channel_id; + + /** ID of rules channel for communities */ + snowflake rules_channel_id; + + /** Public updates channel id or 0 */ + snowflake public_updates_channel_id; + + /** Snowflake ID of widget channel, or 0 */ + snowflake widget_channel_id; + + /** Approximate member count. May be sent as zero */ + uint32_t member_count; + + /** Flags bitmask as defined by values within dpp::guild_flags */ + uint32_t flags; + + /** + * @brief the maximum number of presences for the guild. + * @note Generally Discord always fills this with 0, apart from for the largest of guilds + */ + uint32_t max_presences; + + /** + * @brief the maximum number of members for the guild + */ + uint32_t max_members; + + /** Shard ID of the guild */ + uint16_t shard_id; + + /** Number of boosters */ + uint16_t premium_subscription_count; + + /** Voice AFK timeout before moving users to AFK channel */ + guild_afk_timeout_t afk_timeout; + + /** Maximum users in a video channel, or 0 */ + uint8_t max_video_channel_users; + + /** Setting for how notifications are to be delivered to users */ + default_message_notification_t default_message_notifications; + + /** Boost level */ + guild_premium_tier_t premium_tier; + + /** Verification level of server */ + verification_level_t verification_level; + + /** Whether or not explicit content filtering is enable and what setting it is */ + guild_explicit_content_t explicit_content_filter; + + /** If multi factor authentication is required for moderators or not */ + mfa_level_t mfa_level; + + /** + * @brief Guild NSFW level + */ + guild_nsfw_level_t nsfw_level; + + /** + * @brief Additional flags + */ + uint8_t flags_extra; + + /** Default constructor, zeroes all values */ + guild(); + + /** + * @brief Destroy the guild object + */ + virtual ~guild() = default; + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + guild& fill_from_json(nlohmann::json* j); + + /** Read class values from json object + * @param shard originating shard + * @param j A json object to read from + * @return A reference to self + */ + guild& fill_from_json(class discord_client* shard, nlohmann::json* j); + + /** Build a JSON string from this object. + * @param with_id True if an ID is to be included in the JSON + * @return JSON string + */ + std::string build_json(bool with_id = false) const; + + /** + * @brief Compute the base permissions for a member on this guild, + * before channel overwrites are applied. + * This method takes into consideration the following cases: + * - Guild owner + * - Guild roles including \@everyone + * + * @param user User to get permissions for + * @return permission permissions bitmask + * @note Requires role cache to be enabled (it's enabled by default). + * + * @warning The method will search for the guild member in the cache by the users id. + * If the guild member is not in cache, the method will always return 0. + */ + permission base_permissions(const class user* user) const; + + /** + * @brief Compute the base permissions for a member on this guild, + * before channel overwrites are applied. + * This method takes into consideration the following cases: + * - Guild owner + * - Guild roles including \@everyone + * + * @param member member to get permissions for + * @return permission permissions bitmask + * @note Requires role cache to be enabled (it's enabled by default). + */ + permission base_permissions(const guild_member &member) const; + + /** + * @brief Get the overall permissions for a member in this channel, including channel overwrites, role permissions and admin privileges. + * + * @param base_permissions base permissions before overwrites, + * from guild::base_permissions + * @param user The user to resolve the permissions for + * @param channel Channel to compute permission overwrites for + * @return permission Permission overwrites for the member. Made of bits in dpp::permissions. + * @note Requires role cache to be enabled (it's enabled by default). + * + * @warning The method will search for the guild member in the cache by the users id. + * If the guild member is not in cache, the method will always return 0. + */ + permission permission_overwrites(const uint64_t base_permissions, const user* user, const channel* channel) const; + + /** + * @brief Get the overall permissions for a member in this channel, including channel overwrites, role permissions and admin privileges. + * + * @param member The member to resolve the permissions for + * @param channel Channel to compute permission overwrites for + * @return permission Permission overwrites for the member. Made of bits in dpp::permissions. + * @note Requires role cache to be enabled (it's enabled by default). + */ + permission permission_overwrites(const guild_member &member, const channel &channel) const; + + /** + * @brief Rehash members map + */ + void rehash_members(); + + /** + * @brief Connect to a voice channel another guild member is in + * + * @param user_id User id to join + * @param self_mute True if the bot should mute itself + * @param self_deaf True if the bot should deafen itself + * @return True if the user specified is in a vc, false if they aren't + * @note This is NOT a synchronous blocking call! The bot isn't instantly ready to send or listen for audio, + * as we have to wait for the connection to the voice server to be established! + * e.g. wait for dpp::cluster::on_voice_ready event, and then send the audio within that event. + */ + bool connect_member_voice(snowflake user_id, bool self_mute = false, bool self_deaf = false); + + /** + * @brief Get the banner url of the guild if it have one, otherwise returns an empty string + * + * @param size The size of the banner in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized banner is returned. + * @return std::string banner url or empty string + */ + std::string get_banner_url(uint16_t size = 0) const; + + /** + * @brief Get the discovery splash url of the guild if it have one, otherwise returns an empty string + * + * @param size The size of the discovery splash in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized discovery splash is returned. + * @return std::string discovery splash url or empty string + */ + std::string get_discovery_splash_url(uint16_t size = 0) const; + + /** + * @brief Get the icon url of the guild if it have one, otherwise returns an empty string + * + * @param size The size of the icon in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized icon is returned. + * @return std::string icon url or empty string + */ + std::string get_icon_url(uint16_t size = 0) const; + + /** + * @brief Get the splash url of the guild if it have one, otherwise returns an empty string + * + * @param size The size of the splash in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized splash is returned. + * @return std::string splash url or empty string + */ + std::string get_splash_url(uint16_t size = 0) const; + + /** + * @brief Set the name of the guild in the object + * Min length: 2, Max length: 100 (not including leading/trailing spaces) + * @param n Guild name + * @return guild& reference to self + * @throw dpp::length_exception if guild name is too short + */ + guild& set_name(const std::string& n); + + /** + * @brief Is a large server (>250 users) + * @return bool is a large guild + */ + bool is_large() const; + + /** + * @brief Is unavailable due to outage (most other fields will be blank or outdated + * @return bool is unavailable + */ + bool is_unavailable() const; + + /** + * @brief Widget is enabled for this server + * @return bool widget enabled + */ + bool widget_enabled() const; + + /** + * @brief Guild has access to set an invite splash background + * @return bool can have an invite splash + */ + bool has_invite_splash() const; + + /** + * @brief Guild has access to set 384kbps bitrate in voice + * @return bool can have VIP voice regions + */ + bool has_vip_regions() const; + + /** + * @brief Guild has access to set a vanity URL + * @return bool can have vanity url + */ + bool has_vanity_url() const; + + /** + * @brief Guild is a verified server + * @return bool is verified + */ + bool is_verified() const; + + /** + * @brief Guild is a discord partnered server + * @return bool is discord partnered + */ + bool is_partnered() const; + + /** + * @brief Has enabled community + * @return bool has enabled community + */ + bool is_community() const; + + /** + * @brief Guild has access to use commerce features + * @return bool has commerce features enabled + * @deprecated Removed by Discord + */ + bool has_commerce() const; + + /** + * @brief Guild has access to create announcement channels + * @return bool has announcement channels features enabled + */ + bool has_news() const; + + /** + * @brief Guild is discoverable + * @return bool is discoverable + */ + bool is_discoverable() const; + + /** + * @brief Guild is featurable + * @return bool is featurable + */ + bool is_featureable() const; + + /** + * @brief Guild has access to set an animated guild banner image + * @return bool can have animated banner image + */ + bool has_animated_banner() const; + + /** + * @brief Guild has auto moderation features + * @return bool has auto moderation features + */ + bool has_auto_moderation() const; + + /** + * @brief Guild has been set as a support server on the App Directory + * @return bool has been set as a support server of an app in the app directory + */ + bool has_support_server() const; + + /** + * @brief Guild has access to set an animated guild icon + * @return bool can have animated icon + */ + bool has_animated_icon() const; + + /** + * @brief Guild has access to set a guild banner image + * @return bool can have banner image + */ + bool has_banner() const; + + /** + * @brief Guild has enabled the welcome screen + * @return bool enabled welcome screen + */ + bool is_welcome_screen_enabled() const; + + /** + * @brief Guild has enabled membership screening + * @return bool has membership screening + */ + bool has_member_verification_gate() const; + + /** + * @brief Guild has preview enabled + * @return bool has preview + */ + bool is_preview_enabled() const; + + /** + * @brief Guild icon is actually an animated gif + * @return bool is animated gif + */ + bool has_animated_icon_hash() const; + + /** + * @brief Guild banner is actually an animated gif + * @return bool is animated gif + */ + bool has_animated_banner_hash() const; + + + /** + * @brief guild has access to monetization features + * @return bool + */ + bool has_monetization_enabled() const; + + /** + * @brief guild has increased custom sticker slots + * @return bool has more stickers + */ + bool has_more_stickers() const; + + /** + * @brief guild has access to create private threads + * @return bool has private threads + * @deprecated Removed by Discord + */ + bool has_private_threads() const; + + /** + * @brief guild is able to set role icons + * @return bool has role icons + */ + bool has_role_icons() const; + + /** + * @brief guild has access to the seven day archive time for threads + * @return bool has seven day thread archive + */ + bool has_seven_day_thread_archive() const; + + /** + * @brief guild has access to the three day archive time for threads + * @return bool has three day thread archive + */ + bool has_three_day_thread_archive() const; + + /** + * @brief guild has enabled ticketed events + * @return bool has ticketed events + */ + bool has_ticketed_events() const; + + /** + * @brief guild has access to channel banners feature + * @return bool has channel banners + */ + bool has_channel_banners() const; + + /** + * @brief True if the premium progress bar is enabled + * @return bool has progress bar enabled + */ + bool has_premium_progress_bar_enabled() const; + + /** + * @brief True if has paused invites, preventing new users from joining + * @return bool has paused invites + */ + bool has_invites_disabled() const; +}; + +/** A container of guilds */ +typedef std::unordered_map guild_map; + +/** + * @brief Represents a guild widget, simple web widget of member list + */ +class DPP_EXPORT guild_widget { +public: + /** + * @brief Channel widget points to + */ + snowflake channel_id; + + /** + * @brief True if enabled + */ + bool enabled; + + /** + * @brief Construct a new guild widget object + */ + guild_widget(); + + /** + * @brief Build a guild widget from json + * + * @param j json to build from + * @return guild_widget& reference to self + */ + guild_widget& fill_from_json(nlohmann::json* j); + + /** + * @brief Build json for a guild widget + * + * @param with_id Add ID to output + * @return std::string guild widget stringified json + */ + std::string build_json(bool with_id = false) const; +}; + +/** + * @brief helper function to deserialize a guild_member from json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param gm guild_member to be deserialized + */ +void from_json(const nlohmann::json& j, guild_member& gm); + +/** A container of guild members */ +typedef std::unordered_map guild_member_map; + +/** + * @brief Get the guild_member from cache of given IDs + * + * @param guild_id ID of the guild to find guild_member for + * @param user_id ID of the user to find guild_member for + * + * @throw dpp::cache_exception if the guild or guild_member is not found in the cache + * @return guild_member the cached object, if found + */ +guild_member DPP_EXPORT find_guild_member(const snowflake guild_id, const snowflake user_id); + +}; diff --git a/3rdParty/dpp/httpsclient.h b/3rdParty/dpp/httpsclient.h index 20e766afd4..d0a51edf2c 100644 --- a/3rdParty/dpp/httpsclient.h +++ b/3rdParty/dpp/httpsclient.h @@ -1,316 +1,316 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include - -namespace dpp { - - -/** - * @brief HTTP connection status - */ -enum http_state : uint8_t { - /** - * @brief Sending/receiving HTTP headers and request body - */ - HTTPS_HEADERS, - - /** - * @brief Receiving body content. - */ - HTTPS_CONTENT, - - /** - * @brief Completed connection, as it was closed or the body is >= Content-Length - * - */ - HTTPS_DONE, - - /** - * @brief Received chunk length - * - */ - HTTPS_CHUNK_LEN, - - /** - * @brief Received chunk trailing CRLF - */ - HTTPS_CHUNK_TRAILER, - - /** - * @brief The last received chunk is the final chunk - */ - HTTPS_CHUNK_LAST, - - /** - * @brief Receiving contents of a chunk - */ - HTTPS_CHUNK_CONTENT -}; - -/** - * @brief Request headers - */ -typedef std::multimap http_headers; - -/** - * @brief Represents a multipart mime body and the correct top-level mime type - * If a non-multipart request is passed in, this is represented as a plain body - * and the application/json mime type. - */ -struct multipart_content { - /** - * @brief Multipart body - */ - std::string body; - /** - * @brief MIME type - */ - std::string mimetype; -}; - -/** - * @brief Represents a HTTP scheme, hostname and port - * split into parts for easy use in https_client. - */ -struct http_connect_info { - /** - * @brief True if the connection should be SSL - */ - bool is_ssl; - /** - * @brief The request scheme, e.g. 'https' or 'http' - */ - std::string scheme; - /** - * @brief The request hostname part, e.g. 'discord.com' - */ - std::string hostname; - /** - * @brief The port number, either determined from the scheme, - * or from the part of the hostname after a colon ":" character - */ - uint16_t port; -}; - -/** - * @brief Implements a HTTPS socket client based on the SSL client. - * @note plaintext HTTP without SSL is also supported via a "downgrade" setting - */ -class DPP_EXPORT https_client : public ssl_client -{ - /** - * @brief Current connection state - */ - http_state state; - - /** - * @brief The type of the request, e.g. GET, POST - */ - std::string request_type; - - /** - * @brief Path part of URL for HTTPS connection - */ - std::string path; - - /** - * @brief The request body, e.g. form data - */ - std::string request_body; - - /** - * @brief The response body, e.g. file content or JSON - */ - std::string body; - - /** - * @brief The reported length of the content. If this is - * UULONG_MAX, then no length was reported by the server. - */ - uint64_t content_length; - - /** - * @brief Headers for the request, e.g. Authorization, etc. - */ - http_headers request_headers; - - /** - * @brief The status of the HTTP request from the server, - * e.g. 200 for OK, 404 for not found. A value of 0 means - * no request has been completed. - */ - uint16_t status; - - /** - * @brief Time at which the request should be abandoned - */ - time_t timeout; - - /** - * @brief If true the content is chunked encoding - */ - bool chunked; - - /** - * @brief Size of current chunk - */ - size_t chunk_size; - - /** - * @brief Number of bytes received in current chunk - */ - size_t chunk_receive; - - /** - * @brief Headers from the server's response, e.g. RateLimit - * headers, cookies, etc. - */ - std::map response_headers; - - /** - * @brief Handle input buffer - * - * @param buffer Buffer to read - * @return returns true if the connection should remain open - */ - bool do_buffer(std::string& buffer); - -protected: - - /** - * @brief Start the connection - */ - virtual void connect(); - - /** - * @brief Get request state - * @return request state - */ - http_state get_state(); - -public: - - /** - * @brief Connect to a specific HTTP(S) server and complete a request. - * - * The constructor will attempt the connection, and return the content. - * By the time the constructor completes, the HTTP request will be stored - * in the object. - * - * @note This is a blocking call. It starts a loop which runs non-blocking - * functions within it, but does not return until the request completes. - * See queues.cpp for how to make this asynchronous. - * - * @param hostname Hostname to connect to - * @param port Port number to connect to, usually 443 for SSL and 80 for plaintext - * @param urlpath path part of URL, e.g. "/api" - * @param verb Request verb, e.g. GET or POST - * @param req_body Request body, use dpp::https_client::build_multipart() to build a multipart MIME body (e.g. for multiple file upload) - * @param extra_headers Additional request headers, e.g. user-agent, authorization, etc - * @param plaintext_connection Set to true to make the connection plaintext (turns off SSL) - * @param request_timeout How many seconds before the connection is considered failed if not finished - */ - https_client(const std::string &hostname, uint16_t port = 443, const std::string &urlpath = "/", const std::string &verb = "GET", const std::string &req_body = "", const http_headers& extra_headers = {}, bool plaintext_connection = false, uint16_t request_timeout = 5); - - /** - * @brief Destroy the https client object - */ - virtual ~https_client(); - - /** - * @brief Build a multipart content from a set of files and some json - * - * @param json The json content - * @param filenames File names of files to send - * @param contents Contents of each of the files to send - * @return multipart mime content and headers - */ - static multipart_content build_multipart(const std::string &json, const std::vector& filenames = {}, const std::vector& contents = {}); - - /** - * @brief Processes incoming data from the SSL socket input buffer. - * - * @param buffer The buffer contents. Can modify this value removing the head elements when processed. - */ - virtual bool handle_buffer(std::string &buffer); - - /** - * @brief Close HTTPS socket - */ - virtual void close(); - - /** - * @brief Fires every second from the underlying socket I/O loop, used for timeouts - */ - virtual void one_second_timer(); - - /** - * @brief Get a HTTP response header - * - * @param header_name Header name to find, case insensitive - * @return Header content or empty string if not found - */ - const std::string get_header(std::string header_name) const; - - /** - * @brief Get all HTTP response headers - * - * @return headers as a map - */ - const std::map get_headers() const; - - /** - * @brief Get the response content - * - * @return response content - */ - const std::string get_content() const; - - /** - * @brief Get the response HTTP status, e.g. - * 200 for OK, 404 for not found, 429 for rate limited. - * A value of 0 indicates the request was not completed. - * - * @return uint16_t HTTP status - */ - uint16_t get_status() const; - - /** - * @brief Break down a scheme, hostname and port into - * a http_connect_info. - * - * All but the hostname portion are optional. The path component - * should not be passed to this function. - * - * @param url URL to break down - * @return Split URL - */ - static http_connect_info get_host_info(std::string url); - -}; - +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace dpp { + + +/** + * @brief HTTP connection status + */ +enum http_state : uint8_t { + /** + * @brief Sending/receiving HTTP headers and request body + */ + HTTPS_HEADERS, + + /** + * @brief Receiving body content. + */ + HTTPS_CONTENT, + + /** + * @brief Completed connection, as it was closed or the body is >= Content-Length + * + */ + HTTPS_DONE, + + /** + * @brief Received chunk length + * + */ + HTTPS_CHUNK_LEN, + + /** + * @brief Received chunk trailing CRLF + */ + HTTPS_CHUNK_TRAILER, + + /** + * @brief The last received chunk is the final chunk + */ + HTTPS_CHUNK_LAST, + + /** + * @brief Receiving contents of a chunk + */ + HTTPS_CHUNK_CONTENT +}; + +/** + * @brief Request headers + */ +typedef std::multimap http_headers; + +/** + * @brief Represents a multipart mime body and the correct top-level mime type + * If a non-multipart request is passed in, this is represented as a plain body + * and the application/json mime type. + */ +struct multipart_content { + /** + * @brief Multipart body + */ + std::string body; + /** + * @brief MIME type + */ + std::string mimetype; +}; + +/** + * @brief Represents a HTTP scheme, hostname and port + * split into parts for easy use in https_client. + */ +struct http_connect_info { + /** + * @brief True if the connection should be SSL + */ + bool is_ssl; + /** + * @brief The request scheme, e.g. 'https' or 'http' + */ + std::string scheme; + /** + * @brief The request hostname part, e.g. 'discord.com' + */ + std::string hostname; + /** + * @brief The port number, either determined from the scheme, + * or from the part of the hostname after a colon ":" character + */ + uint16_t port; +}; + +/** + * @brief Implements a HTTPS socket client based on the SSL client. + * @note plaintext HTTP without SSL is also supported via a "downgrade" setting + */ +class DPP_EXPORT https_client : public ssl_client +{ + /** + * @brief Current connection state + */ + http_state state; + + /** + * @brief The type of the request, e.g. GET, POST + */ + std::string request_type; + + /** + * @brief Path part of URL for HTTPS connection + */ + std::string path; + + /** + * @brief The request body, e.g. form data + */ + std::string request_body; + + /** + * @brief The response body, e.g. file content or JSON + */ + std::string body; + + /** + * @brief The reported length of the content. If this is + * UULONG_MAX, then no length was reported by the server. + */ + uint64_t content_length; + + /** + * @brief Headers for the request, e.g. Authorization, etc. + */ + http_headers request_headers; + + /** + * @brief The status of the HTTP request from the server, + * e.g. 200 for OK, 404 for not found. A value of 0 means + * no request has been completed. + */ + uint16_t status; + + /** + * @brief Time at which the request should be abandoned + */ + time_t timeout; + + /** + * @brief If true the content is chunked encoding + */ + bool chunked; + + /** + * @brief Size of current chunk + */ + size_t chunk_size; + + /** + * @brief Number of bytes received in current chunk + */ + size_t chunk_receive; + + /** + * @brief Headers from the server's response, e.g. RateLimit + * headers, cookies, etc. + */ + std::map response_headers; + + /** + * @brief Handle input buffer + * + * @param buffer Buffer to read + * @return returns true if the connection should remain open + */ + bool do_buffer(std::string& buffer); + +protected: + + /** + * @brief Start the connection + */ + virtual void connect(); + + /** + * @brief Get request state + * @return request state + */ + http_state get_state(); + +public: + + /** + * @brief Connect to a specific HTTP(S) server and complete a request. + * + * The constructor will attempt the connection, and return the content. + * By the time the constructor completes, the HTTP request will be stored + * in the object. + * + * @note This is a blocking call. It starts a loop which runs non-blocking + * functions within it, but does not return until the request completes. + * See queues.cpp for how to make this asynchronous. + * + * @param hostname Hostname to connect to + * @param port Port number to connect to, usually 443 for SSL and 80 for plaintext + * @param urlpath path part of URL, e.g. "/api" + * @param verb Request verb, e.g. GET or POST + * @param req_body Request body, use dpp::https_client::build_multipart() to build a multipart MIME body (e.g. for multiple file upload) + * @param extra_headers Additional request headers, e.g. user-agent, authorization, etc + * @param plaintext_connection Set to true to make the connection plaintext (turns off SSL) + * @param request_timeout How many seconds before the connection is considered failed if not finished + */ + https_client(const std::string &hostname, uint16_t port = 443, const std::string &urlpath = "/", const std::string &verb = "GET", const std::string &req_body = "", const http_headers& extra_headers = {}, bool plaintext_connection = false, uint16_t request_timeout = 5); + + /** + * @brief Destroy the https client object + */ + virtual ~https_client(); + + /** + * @brief Build a multipart content from a set of files and some json + * + * @param json The json content + * @param filenames File names of files to send + * @param contents Contents of each of the files to send + * @return multipart mime content and headers + */ + static multipart_content build_multipart(const std::string &json, const std::vector& filenames = {}, const std::vector& contents = {}); + + /** + * @brief Processes incoming data from the SSL socket input buffer. + * + * @param buffer The buffer contents. Can modify this value removing the head elements when processed. + */ + virtual bool handle_buffer(std::string &buffer); + + /** + * @brief Close HTTPS socket + */ + virtual void close(); + + /** + * @brief Fires every second from the underlying socket I/O loop, used for timeouts + */ + virtual void one_second_timer(); + + /** + * @brief Get a HTTP response header + * + * @param header_name Header name to find, case insensitive + * @return Header content or empty string if not found + */ + const std::string get_header(std::string header_name) const; + + /** + * @brief Get all HTTP response headers + * + * @return headers as a map + */ + const std::map get_headers() const; + + /** + * @brief Get the response content + * + * @return response content + */ + const std::string get_content() const; + + /** + * @brief Get the response HTTP status, e.g. + * 200 for OK, 404 for not found, 429 for rate limited. + * A value of 0 indicates the request was not completed. + * + * @return uint16_t HTTP status + */ + uint16_t get_status() const; + + /** + * @brief Break down a scheme, hostname and port into + * a http_connect_info. + * + * All but the hostname portion are optional. The path component + * should not be passed to this function. + * + * @param url URL to break down + * @return Split URL + */ + static http_connect_info get_host_info(std::string url); + +}; + }; \ No newline at end of file diff --git a/3rdParty/dpp/integration.h b/3rdParty/dpp/integration.h index a1de296193..6205b36635 100644 --- a/3rdParty/dpp/integration.h +++ b/3rdParty/dpp/integration.h @@ -1,171 +1,171 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Integration types - */ -enum integration_type { - /// Twitch integration - i_twitch, - /// YouTube integration - i_youtube, - /// Discord integration - i_discord -}; - -/** - * @brief Integration flags - */ -enum integration_flags { - /// Integration enabled - if_enabled = 0b00000001, - /// Integration syncing - if_syncing = 0b00000010, - /// Emoji integration - if_emoticons = 0b00000100, - /// Integration revoked - if_revoked = 0b00001000, - /// Kick users when their subscription expires - if_expire_kick = 0b00010000, -}; - -/** - * @brief An application that has been integrated - */ -struct DPP_EXPORT integration_app { - /// Integration id - snowflake id; - /// Name - std::string name; - /// Icon - std::string icon; - /// Description - std::string description; - /// Integration summary @deprecated Removed by Discord - std::string summary; - /// Pointer to bot user - class user* bot; -}; - -/** - * @brief Represents an integration on a guild, e.g. a connection to twitch. - */ -class DPP_EXPORT integration : public managed, public json_interface { -public: - /** Integration name */ - std::string name; - /** Integration type */ - integration_type type; - /** Integration flags from dpp::integration_flags */ - uint8_t flags; - /** Role id */ - snowflake role_id; - /** User id */ - snowflake user_id; - /** The grace period (in days) before expiring subscribers */ - uint32_t expire_grace_period; - /** Sync time */ - time_t synced_at; - /** Subscriber count */ - uint32_t subscriber_count; - /** Account id */ - std::string account_id; - /** Account name */ - std::string account_name; - /** The bot/OAuth2 application for discord integrations */ - integration_app app; - - /** Default constructor */ - integration(); - - /** Default destructor */ - ~integration(); - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - integration& fill_from_json(nlohmann::json* j); - - /** Build a json string from this object. - * @param with_id Add ID to output - * @return JSON string of the object - */ - virtual std::string build_json(bool with_id = false) const; - - /** True if emoticons are enabled */ - bool emoticons_enabled() const; - /** True if integration is enabled */ - bool is_enabled() const; - /** True if is syncing */ - bool is_syncing() const; - /** True if has been revoked */ - bool is_revoked() const; - /** True if expiring kicks the user */ - bool expiry_kicks_user() const; -}; - -/** - * @brief The connection object that the user has attached. - */ -class DPP_EXPORT connection { -public: - std::string id; //!< id of the connection account - std::string name; //!< the username of the connection account - std::string type; //!< the service of the connection (twitch, youtube) - bool revoked; //!< Optional: whether the connection is revoked - std::vector integrations; //!< Optional: an array of partial server integrations - bool verified; //!< whether the connection is verified - bool friend_sync; //!< whether friend sync is enabled for this connection - bool show_activity; //!< whether activities related to this connection will be shown in presence updates - bool two_way_link; //!< Whether this connection has a corresponding third party OAuth2 token - bool visible; //!< visibility of this connection - - /** - * @brief Construct a new connection object - */ - connection(); - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - connection& fill_from_json(nlohmann::json* j); - -}; - -/** A group of integrations */ -typedef std::unordered_map integration_map; - -/** A group of connections */ -typedef std::unordered_map connection_map; - -}; - +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Integration types + */ +enum integration_type { + /// Twitch integration + i_twitch, + /// YouTube integration + i_youtube, + /// Discord integration + i_discord +}; + +/** + * @brief Integration flags + */ +enum integration_flags { + /// Integration enabled + if_enabled = 0b00000001, + /// Integration syncing + if_syncing = 0b00000010, + /// Emoji integration + if_emoticons = 0b00000100, + /// Integration revoked + if_revoked = 0b00001000, + /// Kick users when their subscription expires + if_expire_kick = 0b00010000, +}; + +/** + * @brief An application that has been integrated + */ +struct DPP_EXPORT integration_app { + /// Integration id + snowflake id; + /// Name + std::string name; + /// Icon + std::string icon; + /// Description + std::string description; + /// Integration summary @deprecated Removed by Discord + std::string summary; + /// Pointer to bot user + class user* bot; +}; + +/** + * @brief Represents an integration on a guild, e.g. a connection to twitch. + */ +class DPP_EXPORT integration : public managed, public json_interface { +public: + /** Integration name */ + std::string name; + /** Integration type */ + integration_type type; + /** Integration flags from dpp::integration_flags */ + uint8_t flags; + /** Role id */ + snowflake role_id; + /** User id */ + snowflake user_id; + /** The grace period (in days) before expiring subscribers */ + uint32_t expire_grace_period; + /** Sync time */ + time_t synced_at; + /** Subscriber count */ + uint32_t subscriber_count; + /** Account id */ + std::string account_id; + /** Account name */ + std::string account_name; + /** The bot/OAuth2 application for discord integrations */ + integration_app app; + + /** Default constructor */ + integration(); + + /** Default destructor */ + ~integration(); + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + integration& fill_from_json(nlohmann::json* j); + + /** Build a json string from this object. + * @param with_id Add ID to output + * @return JSON string of the object + */ + virtual std::string build_json(bool with_id = false) const; + + /** True if emoticons are enabled */ + bool emoticons_enabled() const; + /** True if integration is enabled */ + bool is_enabled() const; + /** True if is syncing */ + bool is_syncing() const; + /** True if has been revoked */ + bool is_revoked() const; + /** True if expiring kicks the user */ + bool expiry_kicks_user() const; +}; + +/** + * @brief The connection object that the user has attached. + */ +class DPP_EXPORT connection { +public: + std::string id; //!< id of the connection account + std::string name; //!< the username of the connection account + std::string type; //!< the service of the connection (twitch, youtube) + bool revoked; //!< Optional: whether the connection is revoked + std::vector integrations; //!< Optional: an array of partial server integrations + bool verified; //!< whether the connection is verified + bool friend_sync; //!< whether friend sync is enabled for this connection + bool show_activity; //!< whether activities related to this connection will be shown in presence updates + bool two_way_link; //!< Whether this connection has a corresponding third party OAuth2 token + bool visible; //!< visibility of this connection + + /** + * @brief Construct a new connection object + */ + connection(); + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + connection& fill_from_json(nlohmann::json* j); + +}; + +/** A group of integrations */ +typedef std::unordered_map integration_map; + +/** A group of connections */ +typedef std::unordered_map connection_map; + +}; + diff --git a/3rdParty/dpp/intents.h b/3rdParty/dpp/intents.h index 1e5932198d..3cb84fb693 100644 --- a/3rdParty/dpp/intents.h +++ b/3rdParty/dpp/intents.h @@ -1,86 +1,86 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once - -namespace dpp { - -/** - * @brief intents are a bitmask of allowed events on your websocket. - * - * Some of these are known as Privileged intents (GUILD_MEMBERS and GUILD_PRESENCES) - * and require verification of a bot over 100 servers by discord via submission of - * your real life ID. - */ -enum intents { - /// Intent for receipt of guild information - i_guilds = (1 << 0), - /// Intent for receipt of guild members - i_guild_members = (1 << 1), - /// Intent for receipt of guild bans - i_guild_bans = (1 << 2), - /// Intent for receipt of guild emojis - i_guild_emojis = (1 << 3), - /// Intent for receipt of guild integrations - i_guild_integrations = (1 << 4), - /// Intent for receipt of guild webhooks - i_guild_webhooks = (1 << 5), - /// Intent for receipt of guild invites - i_guild_invites = (1 << 6), - /// Intent for receipt of guild voice states - i_guild_voice_states = (1 << 7), - /// Intent for receipt of guild presences - i_guild_presences = (1 << 8), - /// Intent for receipt of guild messages - i_guild_messages = (1 << 9), - /// Intent for receipt of guild message reactions - i_guild_message_reactions = (1 << 10), - /// Intent for receipt of guild message typing notifications - i_guild_message_typing = (1 << 11), - /// Intent for receipt of direct messages (DMs) - i_direct_messages = (1 << 12), - /// Intent for receipt of direct message reactions - i_direct_message_reactions = (1 << 13), - /// Intent for receipt of direct message typing notifications - i_direct_message_typing = (1 << 14), - /// Intent for receipt of message content - i_message_content = (1 << 15), - /// Scheduled events - i_guild_scheduled_events = (1 << 16), - /// Auto moderation configuration - i_auto_moderation_configuration = (1 << 20), - /// Auto moderation configuration - i_auto_moderation_execution = (1 << 21), - /// Default D++ intents (all non-privileged intents) - i_default_intents = dpp::i_guilds | dpp::i_guild_bans | dpp::i_guild_emojis | dpp::i_guild_integrations | - dpp::i_guild_webhooks | dpp::i_guild_invites | dpp::i_guild_voice_states | - dpp::i_guild_messages | dpp::i_guild_message_reactions | dpp::i_guild_message_typing | - dpp::i_direct_messages | dpp::i_direct_message_typing | dpp::i_direct_message_reactions | - dpp::i_guild_scheduled_events | dpp::i_auto_moderation_configuration | - dpp::i_auto_moderation_execution, - /// Privileged intents requiring ID - i_privileged_intents = dpp::i_guild_members | dpp::i_guild_presences | dpp::i_message_content, - /// Every single intent - i_all_intents = dpp::i_default_intents | dpp::i_privileged_intents, - /// Unverified bots default intents - i_unverified_default_intents = dpp::i_default_intents | dpp::i_message_content -}; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once + +namespace dpp { + +/** + * @brief intents are a bitmask of allowed events on your websocket. + * + * Some of these are known as Privileged intents (GUILD_MEMBERS and GUILD_PRESENCES) + * and require verification of a bot over 100 servers by discord via submission of + * your real life ID. + */ +enum intents { + /// Intent for receipt of guild information + i_guilds = (1 << 0), + /// Intent for receipt of guild members + i_guild_members = (1 << 1), + /// Intent for receipt of guild bans + i_guild_bans = (1 << 2), + /// Intent for receipt of guild emojis + i_guild_emojis = (1 << 3), + /// Intent for receipt of guild integrations + i_guild_integrations = (1 << 4), + /// Intent for receipt of guild webhooks + i_guild_webhooks = (1 << 5), + /// Intent for receipt of guild invites + i_guild_invites = (1 << 6), + /// Intent for receipt of guild voice states + i_guild_voice_states = (1 << 7), + /// Intent for receipt of guild presences + i_guild_presences = (1 << 8), + /// Intent for receipt of guild messages + i_guild_messages = (1 << 9), + /// Intent for receipt of guild message reactions + i_guild_message_reactions = (1 << 10), + /// Intent for receipt of guild message typing notifications + i_guild_message_typing = (1 << 11), + /// Intent for receipt of direct messages (DMs) + i_direct_messages = (1 << 12), + /// Intent for receipt of direct message reactions + i_direct_message_reactions = (1 << 13), + /// Intent for receipt of direct message typing notifications + i_direct_message_typing = (1 << 14), + /// Intent for receipt of message content + i_message_content = (1 << 15), + /// Scheduled events + i_guild_scheduled_events = (1 << 16), + /// Auto moderation configuration + i_auto_moderation_configuration = (1 << 20), + /// Auto moderation configuration + i_auto_moderation_execution = (1 << 21), + /// Default D++ intents (all non-privileged intents) + i_default_intents = dpp::i_guilds | dpp::i_guild_bans | dpp::i_guild_emojis | dpp::i_guild_integrations | + dpp::i_guild_webhooks | dpp::i_guild_invites | dpp::i_guild_voice_states | + dpp::i_guild_messages | dpp::i_guild_message_reactions | dpp::i_guild_message_typing | + dpp::i_direct_messages | dpp::i_direct_message_typing | dpp::i_direct_message_reactions | + dpp::i_guild_scheduled_events | dpp::i_auto_moderation_configuration | + dpp::i_auto_moderation_execution, + /// Privileged intents requiring ID + i_privileged_intents = dpp::i_guild_members | dpp::i_guild_presences | dpp::i_message_content, + /// Every single intent + i_all_intents = dpp::i_default_intents | dpp::i_privileged_intents, + /// Unverified bots default intents + i_unverified_default_intents = dpp::i_default_intents | dpp::i_message_content +}; + +}; diff --git a/3rdParty/dpp/invite.h b/3rdParty/dpp/invite.h index fe61b67e14..26ac50ddc1 100644 --- a/3rdParty/dpp/invite.h +++ b/3rdParty/dpp/invite.h @@ -1,110 +1,110 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Represents an invite to a discord guild or channel - */ -class DPP_EXPORT invite : public json_interface { -public: - /** Invite code - */ - std::string code; - /** Readonly expiration timestamp of this invite or 0 if the invite doesn't expire - */ - time_t expires_at; - /** Guild for the invite - */ - snowflake guild_id; - /** Channel id for invite - */ - snowflake channel_id; - /** User ID of invite creator - */ - snowflake inviter_id; - /** Target user ID of invite, for invites sent via DM - */ - snowflake target_user_id; - /** Target user type (generally this is always 1, "stream") - */ - uint8_t target_user_type; - /** Approximate number of online users - */ - uint32_t approximate_presence_count; - /** Approximate total users online and offline - */ - uint32_t approximate_member_count; - /** Maximum age (in seconds) of invite - */ - uint32_t max_age; - /** Maximum number of uses - */ - uint32_t max_uses; - /** True if a temporary invite which grants access for a limited time - */ - bool temporary; - /** True if this invite should not replace or "attach to" similar invites - */ - bool unique; - /** How many times this invite has been used - * - * @note Only set when using cluster::channel_invites_get - */ - uint32_t uses; - /** The stage instance data if there is a public stage instance in the stage channel this invite is for - * @deprecated Deprecated - */ - stage_instance stage; - - /** Constructor - */ - invite(); - - /** Destructor - */ - virtual ~invite() = default; - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - invite& fill_from_json(nlohmann::json* j); - - /** Build JSON from this object. - * @param with_id Include ID in JSON - * @return The JSON text of the invite - */ - virtual std::string build_json(bool with_id = false) const; - -}; - -/** A container of invites */ -typedef std::unordered_map invite_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Represents an invite to a discord guild or channel + */ +class DPP_EXPORT invite : public json_interface { +public: + /** Invite code + */ + std::string code; + /** Readonly expiration timestamp of this invite or 0 if the invite doesn't expire + */ + time_t expires_at; + /** Guild for the invite + */ + snowflake guild_id; + /** Channel id for invite + */ + snowflake channel_id; + /** User ID of invite creator + */ + snowflake inviter_id; + /** Target user ID of invite, for invites sent via DM + */ + snowflake target_user_id; + /** Target user type (generally this is always 1, "stream") + */ + uint8_t target_user_type; + /** Approximate number of online users + */ + uint32_t approximate_presence_count; + /** Approximate total users online and offline + */ + uint32_t approximate_member_count; + /** Maximum age (in seconds) of invite + */ + uint32_t max_age; + /** Maximum number of uses + */ + uint32_t max_uses; + /** True if a temporary invite which grants access for a limited time + */ + bool temporary; + /** True if this invite should not replace or "attach to" similar invites + */ + bool unique; + /** How many times this invite has been used + * + * @note Only set when using cluster::channel_invites_get + */ + uint32_t uses; + /** The stage instance data if there is a public stage instance in the stage channel this invite is for + * @deprecated Deprecated + */ + stage_instance stage; + + /** Constructor + */ + invite(); + + /** Destructor + */ + virtual ~invite() = default; + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + invite& fill_from_json(nlohmann::json* j); + + /** Build JSON from this object. + * @param with_id Include ID in JSON + * @return The JSON text of the invite + */ + virtual std::string build_json(bool with_id = false) const; + +}; + +/** A container of invites */ +typedef std::unordered_map invite_map; + +}; diff --git a/3rdParty/dpp/json_interface.h b/3rdParty/dpp/json_interface.h index 302642db12..5097b9b333 100644 --- a/3rdParty/dpp/json_interface.h +++ b/3rdParty/dpp/json_interface.h @@ -1,61 +1,61 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2022 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once -#include -#include -#include - -namespace dpp { - /** - * @brief Represents an interface for an object that can optionally implement functions - * for converting to and from nlohmann::json. In the event either parse_from_json() or - * build_json() are not implemented and are called, they will throw at runtime. - * - * @tparam T Type of class that implements the interface - */ - template struct DPP_EXPORT json_interface { - protected: - /* Must not destruct through pointer to json_interface. */ - ~json_interface() = default; - - public: - /** - * @brief Convert object from nlohmann::json - * - * @param j nlohmann::json object - * @return T& Reference to self for fluent calling - */ - T& fill_from_json(nlohmann::json* j) { - throw dpp::logic_exception("JSON interface doesn't implement parse_from_json"); - } - - /** - * @brief Build JSON string from the object - * - * @param with_id Include the ID in the JSON - * @return std::string JSON string version of object - */ - virtual std::string build_json(bool with_id = false) const { - throw dpp::logic_exception("JSON interface doesn't implement build_json"); - } - }; -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2022 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include + +namespace dpp { + /** + * @brief Represents an interface for an object that can optionally implement functions + * for converting to and from nlohmann::json. In the event either parse_from_json() or + * build_json() are not implemented and are called, they will throw at runtime. + * + * @tparam T Type of class that implements the interface + */ + template struct DPP_EXPORT json_interface { + protected: + /* Must not destruct through pointer to json_interface. */ + ~json_interface() = default; + + public: + /** + * @brief Convert object from nlohmann::json + * + * @param j nlohmann::json object + * @return T& Reference to self for fluent calling + */ + T& fill_from_json(nlohmann::json* j) { + throw dpp::logic_exception("JSON interface doesn't implement parse_from_json"); + } + + /** + * @brief Build JSON string from the object + * + * @param with_id Include the ID in the JSON + * @return std::string JSON string version of object + */ + virtual std::string build_json(bool with_id = false) const { + throw dpp::logic_exception("JSON interface doesn't implement build_json"); + } + }; +}; diff --git a/3rdParty/dpp/managed.h b/3rdParty/dpp/managed.h index 3939b8994d..4d4cb0fc3b 100644 --- a/3rdParty/dpp/managed.h +++ b/3rdParty/dpp/managed.h @@ -1,76 +1,76 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include - -namespace dpp { - - /** @brief The managed class is the base class for various types that can - * be stored in a cache that are identified by a dpp::snowflake id. - */ - class DPP_EXPORT managed { - public: - /** - * @brief Unique ID of object set by Discord. - * This value contains a timestamp, worker ID, internal server ID, and an incrementing value. - * Only the timestamp is relevant to us as useful metadata. - */ - snowflake id; - /** - * @brief Constructor, initialises ID - * @param nid ID to set - */ - managed(const snowflake nid = 0); - /** - * @brief Destroy the managed object - */ - virtual ~managed() = default; - - /** - * @brief Get the creation time of this object according to Discord. - * - * @return double creation time inferred from the snowflake ID. - * The minimum possible value is the first second of 2015. - */ - double get_creation_time() const; - - /** - * @brief Comparison operator for comparing two managed objects by id - * - * @param other Other object to compare against - * @return true objects are the same id - * @return false objects are not the same id - */ - bool operator==(const managed& other) const noexcept; - - /** - * @brief Comparison operator for comparing two managed objects by id - * - * @param other Other object to compare against - * @return true objects are not the same id - * @return false objects are the same id - */ - bool operator!=(const managed& other) const noexcept; - }; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include + +namespace dpp { + + /** @brief The managed class is the base class for various types that can + * be stored in a cache that are identified by a dpp::snowflake id. + */ + class DPP_EXPORT managed { + public: + /** + * @brief Unique ID of object set by Discord. + * This value contains a timestamp, worker ID, internal server ID, and an incrementing value. + * Only the timestamp is relevant to us as useful metadata. + */ + snowflake id; + /** + * @brief Constructor, initialises ID + * @param nid ID to set + */ + managed(const snowflake nid = 0); + /** + * @brief Destroy the managed object + */ + virtual ~managed() = default; + + /** + * @brief Get the creation time of this object according to Discord. + * + * @return double creation time inferred from the snowflake ID. + * The minimum possible value is the first second of 2015. + */ + double get_creation_time() const; + + /** + * @brief Comparison operator for comparing two managed objects by id + * + * @param other Other object to compare against + * @return true objects are the same id + * @return false objects are not the same id + */ + bool operator==(const managed& other) const noexcept; + + /** + * @brief Comparison operator for comparing two managed objects by id + * + * @param other Other object to compare against + * @return true objects are not the same id + * @return false objects are the same id + */ + bool operator!=(const managed& other) const noexcept; + }; + +}; diff --git a/3rdParty/dpp/message.h b/3rdParty/dpp/message.h index fb65d8824e..61dd046a3b 100644 --- a/3rdParty/dpp/message.h +++ b/3rdParty/dpp/message.h @@ -1,1491 +1,1491 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Represents the type of a component - */ -enum component_type : uint8_t { - /// Action row, a container for other components - cot_action_row = 1, - /// Clickable button - cot_button = 2, - /// Select menu for picking from defined text options - cot_selectmenu = 3, - /// Text input - cot_text = 4, - /// Select menu for users - cot_user_selectmenu = 5, - /// Select menu for roles - cot_role_selectmenu = 6, - /// Select menu for mentionables (users and roles) - cot_mentionable_selectmenu = 7, - /// Select menu for channels - cot_channel_selectmenu = 8, -}; - -/** - * @brief Types of text input - */ -enum text_style_type : uint8_t { - /// Intended for short single-line text. - text_short = 1, - /// Intended for much longer inputs. - text_paragraph = 2, -}; - -/** - * @brief Represents the style of a button - */ -enum component_style : uint8_t { - /// Blurple - cos_primary = 1, - /// Grey - cos_secondary, - /// Green - cos_success, - /// Red - cos_danger, - /// An external hyperlink to a website - cos_link -}; - -/** - * @brief An option for a select component - */ -struct DPP_EXPORT select_option : public json_interface { - /** - * @brief Label for option - */ - std::string label; - /** - * @brief Value for option - */ - std::string value; - /** - * @brief Description of option - */ - std::string description; - /** - * @brief True if option is the default option - */ - bool is_default; - /** - * @brief Emoji definition. To set an emoji on your button - * you must set one of either the name or id fields. - * The easiest way is to use the component::set_emoji - * method. - */ - struct inner_select_emoji { - /** - * @brief Set the name field to the name of the emoji. - * For built in unicode emojis, set this to the - * actual unicode value of the emoji e.g. "😄" - * and not for example ":smile:" - */ - std::string name; - /** - * @brief The emoji ID value for emojis that are custom - * ones belonging to a guild. The same rules apply - * as with other emojis, that the bot must be on - * the guild where the emoji resides and it must - * be available for use (e.g. not disabled due to - * lack of boosts etc) - */ - dpp::snowflake id = 0; - /** - * @brief True if the emoji is animated. Only applies to - * custom emojis. - */ - bool animated = false; - } emoji; - - /** - * @brief Construct a new select option object - */ - select_option(); - - /** - * @brief Destructs the select option object. - */ - virtual ~select_option() = default; - - /** - * @brief Construct a new select option object - * - * @param label Label of option - * @param value Value of option - * @param description Description of option - */ - select_option(const std::string &label, const std::string &value, const std::string &description = ""); - - /** - * @brief Set the label - * - * @param l the user-facing name of the option. It will be truncated to the maximum length of 100 UTF-8 characters. - * @return select_option& reference to self for chaining - */ - select_option& set_label(const std::string &l); - - /** - * @brief Set the value - * - * @param v value to set. It will be truncated to the maximum length of 100 UTF-8 characters. - * @return select_option& reference to self for chaining - */ - select_option& set_value(const std::string &v); - - /** - * @brief Set the description - * - * @param d description to set. It will be truncated to the maximum length of 100 UTF-8 characters. - * @return select_option& reference to self for chaining - */ - select_option& set_description(const std::string &d); - - /** - * @brief Set the emoji - * - * @param n emoji name - * @param id emoji id for custom emojis - * @param animated true if animated emoji - * @return select_option& reference to self for chaining - */ - select_option& set_emoji(const std::string &n, dpp::snowflake id = 0, bool animated = false); - - /** - * @brief Set the option as default - * - * @param def true to set the option as default - * @return select_option& reference to self for chaining - */ - select_option& set_default(bool def); - - /** - * @brief Set the emoji as animated - * - * @param anim true if animated - * @return select_option& reference to self for chaining - */ - select_option& set_animated(bool anim); - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - select_option& fill_from_json(nlohmann::json* j); -}; - -/** - * @brief Represents the component object. - * A component is a clickable button or drop down list - * within a discord message, where the buttons emit - * on_button_click events when the user interacts with - * them. - * - * You should generally define one component object and - * then insert one or more additional components into it - * using component::add_component(), so that the parent - * object is an action row and the child objects are buttons. - */ -class DPP_EXPORT component : public json_interface { -public: - /** Component type, either a button or action row - */ - component_type type; - - /** Sub components, buttons on an action row - */ - std::vector components; - - /** Component label (for buttons, text inputs). - * Maximum of 80 characters. - */ - std::string label; - - /** Component style (for buttons) - */ - component_style style; - - /** - * @brief Text style (for text inputs) - */ - text_style_type text_style; - - /** Component id (for buttons, menus, text inputs). - * Maximum of 100 characters. - */ - std::string custom_id; - - /** URL for link types (dpp::cos_link). - * Maximum of 512 characters. - */ - std::string url; - - /** Placeholder text for select menus and text inputs (max 150 characters) - */ - std::string placeholder; - - /** Minimum number of items that must be chosen for a select menu. - * Default is -1 to not set this - */ - int32_t min_values; - - /** Maximum number of items that can be chosen for a select menu. - * Default is -1 to not set this - */ - int32_t max_values; - - /** Minimum length for text input (0-4000) - */ - int32_t min_length; - - /** Maximum length for text input (1-4000) - */ - int32_t max_length; - - /** Select options for select menus. Only required and available for select menus of type dpp::cot_selectmenu - */ - std::vector options; - - /** List of channel types (dpp::channel_type) to include in the channel select component (dpp::cot_channel_selectmenu) - */ - std::vector channel_types; - - /** Disabled flag (for buttons) - */ - bool disabled; - - /** Whether the text input is required to be filled - */ - bool required; - - /** Value of the modal (filled or valid when populated from an - * on_form_submit event, or from the set_value function) - */ - std::variant value; - - /** Emoji definition. To set an emoji on your button - * you must set one of either the name or id fields. - * The easiest way is to use the component::set_emoji - * method. - */ - struct inner_emoji { - /** Set the name field to the name of the emoji. - * For built in unicode emojis, set this to the - * actual unicode value of the emoji e.g. "😄" - * and not for example ":smile:" - */ - std::string name; - /** The emoji ID value for emojis that are custom - * ones belonging to a guild. The same rules apply - * as with other emojis, that the bot must be on - * the guild where the emoji resides and it must - * be available for use (e.g. not disabled due to - * lack of boosts etc) - */ - dpp::snowflake id; - /** True if the emoji is animated. Only applies to - * custom emojis. - */ - bool animated; - } emoji; - - /** Constructor - */ - component(); - - /** Destructor - */ - virtual ~component() = default; - - /** - * @brief Add a channel type to include in the channel select component (dpp::cot_channel_selectmenu) - * - * @param ct The dpp::channel_type - * @return component& reference to self - */ - component& add_channel_type(uint8_t ct); - - /** - * @brief Set the type of the component. Button components - * (type dpp::cot_button) should always be contained within - * an action row (type dpp::cot_action_row). As described - * below, many of the other methods automatically set this - * to the correct type so usually you should not need to - * manually call component::set_type(). - * - * @param ct The component type - * @return component& reference to self - */ - component& set_type(component_type ct); - - /** - * @brief Set the text style of a text component - * @note Sets type to `cot_text` - * - * @param ts Text style type to set - * @return component& reference to self - */ - component& set_text_style(text_style_type ts); - - /** - * @brief Set the label of the component, e.g. button text. - * For action rows, this field is ignored. Setting the - * label will auto-set the type to dpp::cot_button. - * - * @param label Label text to set. It will be truncated to the maximum length of 80 UTF-8 characters. - * @return component& Reference to self - */ - component& set_label(const std::string &label); - - /** - * @brief Set the default value of the text input component. - * For action rows, this field is ignored. Setting the - * value will auto-set the type to dpp::cot_text. - * - * @param val Value text to set. It will be truncated to the maximum length of 4000 UTF-8 characters. - * @return component& Reference to self - */ - component& set_default_value(const std::string &val); - - /** - * @brief Set the url for dpp::cos_link types. - * Calling this function sets the style to dpp::cos_link - * and the type to dpp::cot_button. - * - * @param url URL to set. It will be truncated to the maximum length of 512 UTF-8 characters. - * @return component& reference to self. - */ - component& set_url(const std::string &url); - - /** - * @brief Set the style of the component, e.g. button colour. - * For action rows, this field is ignored. Setting the - * style will auto-set the type to dpp::cot_button. - * - * @param cs Component style to set - * @return component& reference to self - */ - component& set_style(component_style cs); - - /** - * @brief Set the id of the component. - * For action rows, this field is ignored. Setting the - * id will auto-set the type to dpp::cot_button. - * - * @param id Custom ID string to set. This ID will be sent - * for any on_button_click events related to the button. - * @note The maximum length of the Custom ID is 100 UTF-8 codepoints. - * If your Custom ID is longer than this, it will be truncated. - * @return component& Reference to self - */ - component& set_id(const std::string &id); - - /** - * @brief Set the component to disabled. - * Defaults to false on all created components. - * - * @param disable True to disable, false to disable. - * @return component& Reference to self - */ - component& set_disabled(bool disable); - - /** - * @brief Set if this component is required. - * Defaults to false on all created components. - * - * @param require True to require this, false to make it optional. - * @return component& Reference to self - */ - component& set_required(bool require); - - /** - * @brief Set the placeholder - * - * @param placeholder placeholder string. It will be truncated to the - * maximum length of 150 UTF-8 characters for select menus, and 100 UTF-8 - * characters for modals. - * @return component& Reference to self - */ - component& set_placeholder(const std::string &placeholder); - - /** - * @brief Set the min value - * - * @param min_values min value to set - * @return component& Reference to self - */ - component& set_min_values(uint32_t min_values); - - /** - * @brief Set the max value - * - * @param max_values max value to set (0 - 25) - * @return component& Reference to self - */ - component& set_max_values(uint32_t max_values); - - /** - * @brief Set the min length of text input - * - * @param min_l min value to set (0 - 25) - * @return component& Reference to self - */ - component& set_min_length(uint32_t min_l); - - /** - * @brief Set the max length of text input - * - * @param max_l max value to set - * @return component& Reference to self - */ - component& set_max_length(uint32_t max_l); - - /** - * @brief Add a select option - * - * @param option option to add - * @return component& Reference to self - */ - component& add_select_option(const select_option &option); - - /** - * @brief Add a sub-component, only valid for action rows. - * Adding subcomponents to a component will automatically - * set this component's type to dpp::cot_action_row. - * - * @param c The sub-component to add - * @return component& reference to self - */ - component& add_component(const component& c); - - /** - * @brief Set the emoji of the current sub-component. - * Only valid for buttons. Adding an emoji to a component - * will automatically set this components type to - * dpp::cot_button. One or both of name and id must be set. - * For a built in unicode emoji, you only need set name, - * and should set it to a unicode character e.g. "😄". - * For custom emojis, set the name to the name of the emoji - * on the guild, and the id to the emoji's ID. - * Setting the animated boolean is only valid for custom - * emojis. - * - * @param name Emoji name, or unicode character to use - * @param id Emoji id, for custom emojis only. - * @param animated True if the custom emoji is animated. - * @return component& Reference to self - */ - component& set_emoji(const std::string& name, dpp::snowflake id = 0, bool animated = false); - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - component& fill_from_json(nlohmann::json* j); - -}; - -/** - * @brief A footer in a dpp::embed - */ -struct DPP_EXPORT embed_footer { - /** Footer text */ - std::string text; - /** Footer icon url */ - std::string icon_url; - /** Proxied icon url */ - std::string proxy_url; - - /** Set footer's text. Returns footer itself so these methods may be "chained" - * @param t string to set as footer text. It will be truncated to the maximum length of 2048 UTF-8 characters. - * @return A reference to self - */ - embed_footer& set_text(const std::string& t); - - /** Set footer's icon url. Returns footer itself so these methods may be "chained" - * @param i url to set as footer icon url - * @return A reference to self - */ - embed_footer& set_icon(const std::string& i); - - /** Set footer's proxied icon url. Returns footer itself so these methods may be "chained" - * @param p url to set as footer proxied icon url - * @return A reference to self - */ - embed_footer& set_proxy(const std::string& p); -}; - -/** - * @brief An video, image or thumbnail in a dpp::embed - */ -struct DPP_EXPORT embed_image { - /** URL to image or video */ - std::string url; - /** Proxied image url */ - std::string proxy_url; - /** Height (calculated by discord) */ - std::string height; - /** Width (calculated by discord) */ - std::string width; -}; - -/** - * @brief Embed provider in a dpp::embed. Received from discord but cannot be sent - */ -struct DPP_EXPORT embed_provider { - /** Provider name */ - std::string name; - /** Provider URL */ - std::string url; -}; - -/** - * @brief Author within a dpp::embed object - */ -struct DPP_EXPORT embed_author { - /** Author name */ - std::string name; - /** Author url */ - std::string url; - /** Author icon url */ - std::string icon_url; - /** Proxied icon url */ - std::string proxy_icon_url; -}; - -/** - * @brief A dpp::embed may contain zero or more fields - */ -struct DPP_EXPORT embed_field { - /** Name of field */ - std::string name; - /** Value of field (max length 1000) */ - std::string value; - /** True if the field is to be displayed inline */ - bool is_inline; -}; - -/** - * @brief A rich embed for display within a dpp::message - */ -struct DPP_EXPORT embed { - /** Optional: title of embed */ - std::string title; - /** Optional: type of embed (always "rich" for webhook embeds) */ - std::string type; - /** Optional: description of embed */ - std::string description; - /** Optional: url of embed */ - std::string url; - /** Optional: timestamp of embed content */ - time_t timestamp; - /** Optional: color code of the embed */ - uint32_t color; - /** Optional: footer information */ - std::optional footer; - /** Optional: image information */ - std::optional image; - /** Optional: thumbnail information */ - std::optional thumbnail; - /** Optional: video information (can't send these) */ - std::optional video; - /** Optional: provider information (can't send these) */ - std::optional provider; - /** Optional: author information */ - std::optional author; - /** Optional: fields information */ - std::vector fields; - - /** Constructor */ - embed(); - - /** Constructor to build embed from json object - * @param j JSON to read content from - */ - embed(nlohmann::json* j); - - /** Destructor */ - ~embed(); - - /** Set embed title. Returns the embed itself so these method calls may be "chained" - * @param text The text of the title. It will be truncated to the maximum length of 256 UTF-8 characters. - * @return A reference to self - */ - embed& set_title(const std::string &text); - - /** Set embed description. Returns the embed itself so these method calls may be "chained" - * @param text The text of the title. It will be truncated to the maximum length of 4096 UTF-8 characters. - * @return A reference to self - */ - embed& set_description(const std::string &text); - - /** Set the footer of the embed. Returns the embed itself so these method calls may be "chained" - * @param f the footer to set - * @return A reference to self - */ - embed& set_footer(const embed_footer& f); - - /** Set the footer of the embed. Returns the embed itself so these method calls may be "chained" - * @param text string to set as footer text. It will be truncated to the maximum length of 2048 UTF-8 characters. - * @param icon_url an url to set as footer icon url - * @return A reference to self - */ - embed& set_footer(const std::string& text, const std::string& icon_url); - - /** Set embed colour. Returns the embed itself so these method calls may be "chained" - * @param col The colour of the embed - * @return A reference to self - */ - embed& set_color(uint32_t col); - - /** Set embed timestamp. Returns the embed itself so these method calls may be "chained" - * @param tstamp The timestamp to show in the footer, should be in UTC - * @return A reference to self - */ - embed& set_timestamp(time_t tstamp); - - /** Set embed url. Returns the embed itself so these method calls may be "chained" - * @param url the url of the embed - * @return A reference to self - */ - embed& set_url(const std::string &url); - - /** Add an embed field. Returns the embed itself so these method calls may be "chained" - * @param name The name of the field. It will be truncated to the maximum length of 256 UTF-8 characters. - * @param value The value of the field. It will be truncated to the maximum length of 1024 UTF-8 characters. - * @param is_inline Whether or not to display the field 'inline' or on its own line - * @return A reference to self - */ - embed& add_field(const std::string& name, const std::string &value, bool is_inline = false); - - /** Set embed author. Returns the embed itself so these method calls may be "chained" - * @param a The author to set - * @return A reference to self - */ - embed& set_author(const dpp::embed_author& a); - - /** Set embed author. Returns the embed itself so these method calls may be "chained" - * @param name The name of the author. It will be truncated to the maximum length of 256 UTF-8 characters. - * @param url The url of the author - * @param icon_url The icon URL of the author - * @return A reference to self - */ - embed& set_author(const std::string& name, const std::string& url, const std::string& icon_url); - - /** Set embed provider. Returns the embed itself so these method calls may be "chained" - * @param name The provider name. It will be truncated to the maximum length of 256 UTF-8 characters. - * @param url The provider url - * @return A reference to self - */ - embed& set_provider(const std::string& name, const std::string& url); - - /** Set embed image. Returns the embed itself so these method calls may be "chained" - * @param url The embed image URL - * @return A reference to self - */ - embed& set_image(const std::string& url); - - /** Set embed video. Returns the embed itself so these method calls may be "chained" - * @param url The embed video url - * @return A reference to self - */ - embed& set_video(const std::string& url); - - /** Set embed thumbnail. Returns the embed itself so these method calls may be "chained" - * @param url The embed thumbnail url - * @return A reference to self - */ - embed& set_thumbnail(const std::string& url); -}; - -/** - * @brief Represents a reaction to a dpp::message - */ -struct DPP_EXPORT reaction { - /** Number of times this reaction has been added */ - uint32_t count; - /** Reaction was from the bot's id */ - bool me; - /** ID of emoji for reaction */ - snowflake emoji_id; - /** Name of emoji, if applicable */ - std::string emoji_name; - - /** - * @brief Constructs a new reaction object. - */ - reaction(); - - /** - * @brief Constructs a new reaction object from a JSON object. - * @param j The JSON to read data from - */ - reaction(nlohmann::json* j); - - /** - * @brief Destructs the reaction object. - */ - ~reaction() = default; -}; - -/** - * @brief Represents an attachment in a dpp::message - */ -struct DPP_EXPORT attachment { - /** ID of attachment */ - snowflake id; - /** Size of the attachment in bytes */ - uint32_t size; - /** File name of the attachment */ - std::string filename; - /** Optional: Description of the attachment (max 1024 characters) */ - std::string description; - /** URL which points to the attachment */ - std::string url; - /** Proxied URL which points to the attachment */ - std::string proxy_url; - /** Width of the attachment, if applicable */ - uint32_t width; - /** Height of the attachment, if applicable */ - uint32_t height; - /** MIME type of the attachment, if applicable */ - std::string content_type; - /** Whether this attachment is ephemeral, if applicable */ - bool ephemeral; - /** Owning message */ - struct message* owner; - - /** - * @brief Constructs a new attachment object. - * @param o Owning dpp::message object - */ - attachment(struct message* o); - - /** - * @brief Constructs a new attachment object from a JSON object. - * @param o Owning dpp::message object - * @param j JSON to read information from - */ - attachment(struct message* o, nlohmann::json* j); - - /** - * @brief Destructs the attachment object. - */ - ~attachment() = default; - - /** - * @brief Download this attachment - * @param callback A callback which is called when the download completes. - * @note The content of the file will be in the http_info.body parameter of the - * callback parameter. - * @throw dpp::logic_exception If there is no owner associated with this attachment that - * itself has an owning cluster, this method will throw a dpp::logic_exception when called. - */ - void download(http_completion_event callback) const; -}; - -/** - * @brief Represents the type of a sticker - */ -enum sticker_type : uint8_t { - /// Nitro pack sticker - st_standard = 1, - /// Guild sticker - st_guild = 2 -}; - -/** - * @brief The file format (png, apng, lottie) of a sticker - */ -enum sticker_format : uint8_t { - sf_png = 1, - sf_apng = 2, - sf_lottie = 3 -}; - -/** - * @brief Represents stickers received in messages - */ -struct DPP_EXPORT sticker : public managed, public json_interface { - /** Optional: for standard stickers, id of the pack the sticker is from - */ - snowflake pack_id; - /** The name of the sticker */ - std::string name; - /// description of the sticker (may be empty) - std::string description; - /** for guild stickers, the Discord name of a unicode emoji representing the sticker's expression. - * for standard stickers, a comma-separated list of related expressions. - */ - std::string tags; - /** - * @brief Asset ID - * @deprecated now an empty string but still sent by discord. - * While discord still send this empty string value we will still have a field - * here in the library. - */ - std::string asset; - /** The type of sticker */ - sticker_type type; - /// type of sticker format - sticker_format format_type; - /// Optional: whether this guild sticker can be used, may be false due to loss of Server Boosts - bool available; - /// Optional: id of the guild that owns this sticker - snowflake guild_id; - /// Optional: the user that uploaded the guild sticker - user sticker_user; - /// Optional: the standard sticker's sort order within its pack - uint8_t sort_value; - /** Name of file to upload (when adding or editing a sticker) */ - std::string filename; - /** File content to upload (raw binary) */ - std::string filecontent; - - /** - * @brief Construct a new sticker object - */ - sticker(); - - virtual ~sticker() = default; - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - sticker& fill_from_json(nlohmann::json* j); - - /** Build JSON from this object. - * @param with_id True if the ID is to be set in the JSON structure - * @return The JSON text of the invite - */ - virtual std::string build_json(bool with_id = true) const; - - /** - * @brief Get the sticker url - * - * @param accept_lottie Whether to allow that [lottie](https://airbnb.io/lottie/#/) (json format) can be returned or not - * @return std::string The sticker url or an empty string when its a lottie and accept_lottie is false - */ - std::string get_url(bool accept_lottie = true) const; - - /** - * @brief Set the filename - * - * @param fn filename - * @return message& reference to self - */ - sticker& set_filename(const std::string &fn); - - /** - * @brief Set the file content - * - * @param fc raw file content contained in std::string - * @return message& reference to self - */ - sticker& set_file_content(const std::string &fc); - -}; - -/** - * @brief Represents a sticker pack (the built in groups of stickers that all nitro users get to use) - */ -struct DPP_EXPORT sticker_pack : public managed, public json_interface { - /// the stickers in the pack - std::map stickers; - /// name of the sticker pack - std::string name; - /// id of the pack's SKU - snowflake sku_id; - /// Optional: id of a sticker in the pack which is shown as the pack's icon - snowflake cover_sticker_id; - /// description of the sticker pack - std::string description; - /// id of the sticker pack's banner image - snowflake banner_asset_id; - - /** - * @brief Construct a new sticker pack object - */ - sticker_pack(); - - virtual ~sticker_pack() = default; - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - sticker_pack& fill_from_json(nlohmann::json* j); - - /** Build JSON from this object. - * @param with_id True if the ID is to be set in the JSON structure - * @return The JSON text of the invite - */ - virtual std::string build_json(bool with_id = true) const; - -}; - -/** - * @brief Bitmask flags for a dpp::message - */ -enum message_flags : uint16_t { - /// this message has been published to subscribed channels (via Channel Following) - m_crossposted = 1 << 0, - /// this message originated from a message in another channel (via Channel Following) - m_is_crosspost = 1 << 1, - /// do not include any embeds when serializing this message - m_suppress_embeds = 1 << 2, - /// the source message for this crosspost has been deleted (via Channel Following) - m_source_message_deleted = 1 << 3, - /// this message came from the urgent message system - m_urgent = 1 << 4, - /// this message has an associated thread, with the same id as the message - m_has_thread = 1 << 5, - /// this message is only visible to the user who invoked the Interaction - m_ephemeral = 1 << 6, - /// this message is an Interaction Response and the bot is "thinking" - m_loading = 1 << 7, - /// this message failed to mention some roles and add their members to the thread - m_thread_mention_failed = 1 << 8, -}; - -/** - * @brief Represents possible values for the dpp::embed type field. - * These are loosely defined by the API docs and do not influence how the client renders embeds. - * The only type a bot can send is dpp::embed_type::emt_rich. - */ -namespace embed_type { - /** - * @brief Rich text - */ - const std::string emt_rich = "rich"; - /** - * @brief Image - */ - const std::string emt_image = "image"; - /** - * @brief Video link - */ - const std::string emt_video = "video"; - /** - * @brief Animated gif - */ - const std::string emt_gifv = "gifv"; - /** - * @brief Article - */ - const std::string emt_article = "article"; - /** - * @brief Link URL - */ - const std::string emt_link = "link"; - /** - * @brief Auto moderation filter - */ - const std::string emt_automod = "auto_moderation_message"; -}; - -/** - * @brief Message types for dpp::message::type - */ -enum message_type { - /// Default - mt_default = 0, - /// Add recipient - mt_recipient_add = 1, - /// Remove recipient - mt_recipient_remove = 2, - /// Call - mt_call = 3, - /// Channel name change - mt_channel_name_change = 4, - /// Channel icon change - mt_channel_icon_change = 5, - /// Message pinned - mt_channel_pinned_message = 6, - /// Member joined - mt_guild_member_join = 7, - /// Boost - mt_user_premium_guild_subscription = 8, - /// Boost level 1 - mt_user_premium_guild_subscription_tier_1 = 9, - /// Boost level 2 - mt_user_premium_guild_subscription_tier_2 = 10, - /// Boost level 3 - mt_user_premium_guild_subscription_tier_3 = 11, - /// Follow channel - mt_channel_follow_add = 12, - /// Disqualified from discovery - mt_guild_discovery_disqualified = 14, - /// Re-qualified for discovery - mt_guild_discovery_requalified = 15, - /// Discovery grace period warning 1 - mt_guild_discovery_grace_period_initial_warning = 16, - /// Discovery grace period warning 2 - mt_guild_discovery_grace_period_final_warning = 17, - /// Thread Created - mt_thread_created = 18, - /// Reply - mt_reply = 19, - /// Application command - mt_application_command = 20, - /// Thread starter message - mt_thread_starter_message = 21, - /// Invite reminder - mt_guild_invite_reminder = 22, - /// Context Menu Command - mt_context_menu_command = 23, - /// Auto moderation action - mt_auto_moderation_action = 24, -}; - -/** - * @brief Represents the caching policy of a cache in the library. - */ -enum cache_policy_setting_t { - /** - * @brief request aggressively on seeing new guilds, and also store missing data from messages. - * This is the default behaviour and the least memory-efficient option. Memory usage will increase - * over time, initially quite rapidly, and then linearly over time. It is the least cpu-intensive - * setting. - */ - cp_aggressive = 0, - /** - * @brief only cache when there is relevant activity, e.g. a message to the bot. - * This is a good middle-ground, memory usage will increase linearly over time. - */ - cp_lazy = 1, - /** - * @brief Don't cache anything. Fill details when we see them. - * This is the most memory-efficient option but consumes more CPU time - */ - cp_none = 2 -}; - -/** - * @brief Represents the caching policy of the cluster. - * - * Channels and guilds are always cached as these caches are used - * internally by the library. The memory usage of these is minimal. - * - * All default to 'aggressive' which means to actively attempt to cache, - * going out of the way to fill the caches completely. On large bots this - * can take a LOT of RAM. - */ -struct DPP_EXPORT cache_policy_t { - /** - * @brief Caching policy for users and guild members - */ - cache_policy_setting_t user_policy = cp_aggressive; - - /** - * @brief Caching policy for emojis - */ - cache_policy_setting_t emoji_policy = cp_aggressive; - - /** - * @brief Caching policy for roles - */ - cache_policy_setting_t role_policy = cp_aggressive; -}; - -/** - * @brief Represents messages sent and received on Discord - */ -struct DPP_EXPORT message : public managed { - /** id of the channel the message was sent in */ - snowflake channel_id; - /** Optional: id of the guild the message was sent in */ - snowflake guild_id; - /** the author of this message (not guaranteed to be a valid user) */ - user author; - /** Optional: member properties for this message's author */ - guild_member member; - /** contents of the message */ - std::string content; - /** message components */ - std::vector components; - /** when this message was sent */ - time_t sent; - /** when this message was edited (may be 0 if never edited) */ - time_t edited; - /** users specifically mentioned in the message */ - std::vector> mentions; - /** roles specifically mentioned in this message (only IDs currently)*/ - std::vector mention_roles; - /** Channels mentioned in the message. (Discord: not all types supported) - * Discord: Only textual channels that are visible to everyone in a lurkable guild will ever be included. Only crossposted messages (via Channel Following) currently include mention_channels at all. (includes ID, Guild ID, Type, Name)*/ - std::vector mention_channels; - /** any attached files */ - std::vector attachments; - /** zero or more dpp::embed objects */ - std::vector embeds; - /** Optional: reactions to the message */ - std::vector reactions; - /** Optional: used for validating a message was sent */ - std::string nonce; - /** Optional: if the message is generated by a webhook, its id will be here otherwise the field will be 0 */ - snowflake webhook_id; - /** Stickers */ - std::vector stickers; - - /** Name of file to upload (for use server-side in discord's url) */ - std::vector filename; - - /** File content to upload (raw binary) */ - std::vector filecontent; - - /** - * @brief Reference to another message, e.g. a reply - */ - struct message_ref { - /// id of the originating message - snowflake message_id; - /// id of the originating message's channel - snowflake channel_id; - /// id of the originating message's guild - snowflake guild_id; - /// when sending, whether to error if the referenced message doesn't exist instead of sending as a normal (non-reply) message, default true - bool fail_if_not_exists; - } message_reference; - - /** - * @brief Reference to an interaction - */ - struct message_interaction_struct{ - /// id of the interaction - snowflake id; - /// type of interaction - uint8_t type; - /// name of the application command - std::string name; - /// the user who invoked the interaction - user usr; - } interaction; - - /** - * @brief Allowed mentions details - */ - struct allowed_ref { - /** - * @brief Set to true to parse user mentions in the text. Default is false - */ - bool parse_users; - /** - * @brief Set to true to at-everyone and at-here mentions in the text. Default is false - */ - bool parse_everyone; - /** - * @brief Set to true to parse role mentions in the text. Default is false - */ - bool parse_roles; - /** - * @brief Set to true to mention the user who sent the message this one is replying to. Default is false - */ - bool replied_user; - /** - * @brief List of users to allow pings for - */ - std::vector users; - /** - * @brief List of roles to allow pings for - */ - std::vector roles; - } allowed_mentions; - - /** - * @brief The cluster which created this message object - */ - class cluster* owner; - - /** Message type */ - message_type type; - - /** Flags. Made of bits in dpp::message_flags */ - uint16_t flags; - - /** whether this message is pinned */ - bool pinned; - /** whether this was a TTS message */ - bool tts; - /** whether this message mentions everyone */ - bool mention_everyone; - - /** - * @brief Construct a new message object - */ - message(); - - /** - * @brief Construct a new message object - * @param o Owning cluster, passed down to various things such as dpp::attachment. - * Owning cluster is optional (can be nullptr) and if nulled, will prevent some functions - * such as attachment::download from functioning (they will throw, if used) - */ - message(class cluster* o); - - /** - * @brief Destroy the message object - */ - virtual ~message(); - - /** - * @brief Construct a new message object with a channel and content - * - * @param channel_id The channel to send the message to - * @param content The content of the message. It will be truncated to the maximum length of 4000 UTF-8 characters. - * @param type The message type to create - */ - message(snowflake channel_id, const std::string &content, message_type type = mt_default); - - /** - * @brief Construct a new message object with a channel and content - * - * @param channel_id The channel to send the message to - * @param _embed An embed to send - */ - message(snowflake channel_id, const embed & _embed); - - /** - * @brief Construct a new message object with content - * - * @param content The content of the message. It will be truncated to the maximum length of 4000 UTF-8 characters. - * @param type The message type to create - */ - message(const std::string &content, message_type type = mt_default); - - /** - * @brief Set the original message reference for replies/crossposts - * - * @param _message_id message id to reply to - * @param _guild_id guild id to reply to (optional) - * @param _channel_id channel id to reply to (optional) - * @param fail_if_not_exists true if the message send should fail if these values are invalid (optional) - * @return message& reference to self - */ - message& set_reference(snowflake _message_id, snowflake _guild_id = 0, snowflake _channel_id = 0, bool fail_if_not_exists = false); - - /** - * @brief Set the allowed mentions object for pings on the message - * - * @param _parse_users whether or not to parse users in the message content or embeds - * @param _parse_roles whether or not to parse roles in the message content or embeds - * @param _parse_everyone whether or not to parse everyone/here in the message content or embeds - * @param _replied_user if set to true and this is a reply, then ping the user we reply to - * @param users list of user ids to allow pings for - * @param roles list of role ids to allow pings for - * @return message& reference to self - */ - message& set_allowed_mentions(bool _parse_users, bool _parse_roles, bool _parse_everyone, bool _replied_user, const std::vector &users, const std::vector &roles); - - /** Fill this object from json. - * @param j JSON object to fill from - * @param cp Cache policy for user records, whether or not we cache users when a message is received - * @return A reference to self - */ - message& fill_from_json(nlohmann::json* j, cache_policy_t cp = {cp_aggressive, cp_aggressive, cp_aggressive}); - - /** Build JSON from this object. - * @param with_id True if the ID is to be included in the built JSON - * @param is_interaction_response Set to true if this message is intended to be included in an interaction response. - * This will exclude some fields that are not valid in interactions at this time. - * @return The JSON text of the message - */ - virtual std::string build_json(bool with_id = false, bool is_interaction_response = false) const; - - /** - * @brief Returns true if the message was crossposted to other servers - * - * @return true if crossposted - */ - bool is_crossposted() const; - - /** - * @brief Returns true if posted from other servers announcement channel via webhook - * - * @return true if posted from other server - */ - bool is_crosspost() const; - - /** - * @brief True if embeds have been removed - * - * @return true if embeds removed - */ - bool suppress_embeds() const; - - /** - * @brief True if source message was deleted - * - * @return true if source message deleted - */ - bool is_source_message_deleted() const; - - /** - * @brief True if urgent - * - * @return true if urgent - */ - bool is_urgent() const; - - /** - * @brief True if has thread attached - * - * @return true if has thread attached - */ - bool has_thread() const; - - /** - * @brief True if ephemeral (visible only to issuer of a slash command) - * - * @return true if ephemeral - */ - bool is_ephemeral() const; - - /** - * @brief True if loading - * - * @return true if loading - */ - bool is_loading() const; - - /** - * @brief Returns true if this message failed to mention some roles and add their members to the thread - * - * @return true if this message failed to mention some roles and add their members to the thread - */ - bool is_thread_mention_failed() const; - - /** - * @brief Add a component (button) to message - * - * @param c component to add - * @return message& reference to self - */ - message& add_component(const component& c); - - /** - * @brief Add an embed to message - * - * @param e embed to add - * @return message& reference to self - */ - message& add_embed(const embed& e); - - /** - * @brief Set the flags - * - * @param f flags to set from dpp::message_flags - * @return message& reference to self - */ - message& set_flags(uint16_t f); - - /** - * @brief Set the message type - * - * @param t type to set - * @return message& reference to self - */ - message& set_type(message_type t); - - /** - * @brief Set the filename of the last file in list - * - * @param fn filename - * @return message& reference to self - * @deprecated Use message::add_file instead - */ - message& set_filename(const std::string &fn); - - /** - * @brief Set the file content of the last file in list - * - * @param fc raw file content contained in std::string - * @return message& reference to self - * @deprecated Use message::add_file instead - */ - message& set_file_content(const std::string &fc); - - /** - * @brief Add a file to the message - * - * @param filename filename - * @param filecontent raw file content contained in std::string - * @return message& reference to self - */ - message& add_file(const std::string &filename, const std::string &filecontent); - - /** - * @brief Set the message content - * - * @param c message content. It will be truncated to the maximum length of 4000 UTF-8 characters. - * @return message& reference to self - */ - message& set_content(const std::string &c); - - /** - * @brief Set the channel id - * - * @param _channel_id channel id - * @return message& reference to self - */ - message& set_channel_id(snowflake _channel_id); - - /** - * @brief Set the channel id - * - * @param _guild_id channel id - * @return message& reference to self - */ - message& set_guild_id(snowflake _guild_id); - - /** - * @brief Returns true if the message is from a DM - * - * @return true if message is a DM - */ - bool is_dm() const; -}; - -/** A group of messages */ -typedef std::unordered_map message_map; - -/** A group of stickers */ -typedef std::unordered_map sticker_map; - -/** A group of sticker packs */ -typedef std::unordered_map sticker_pack_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Represents the type of a component + */ +enum component_type : uint8_t { + /// Action row, a container for other components + cot_action_row = 1, + /// Clickable button + cot_button = 2, + /// Select menu for picking from defined text options + cot_selectmenu = 3, + /// Text input + cot_text = 4, + /// Select menu for users + cot_user_selectmenu = 5, + /// Select menu for roles + cot_role_selectmenu = 6, + /// Select menu for mentionables (users and roles) + cot_mentionable_selectmenu = 7, + /// Select menu for channels + cot_channel_selectmenu = 8, +}; + +/** + * @brief Types of text input + */ +enum text_style_type : uint8_t { + /// Intended for short single-line text. + text_short = 1, + /// Intended for much longer inputs. + text_paragraph = 2, +}; + +/** + * @brief Represents the style of a button + */ +enum component_style : uint8_t { + /// Blurple + cos_primary = 1, + /// Grey + cos_secondary, + /// Green + cos_success, + /// Red + cos_danger, + /// An external hyperlink to a website + cos_link +}; + +/** + * @brief An option for a select component + */ +struct DPP_EXPORT select_option : public json_interface { + /** + * @brief Label for option + */ + std::string label; + /** + * @brief Value for option + */ + std::string value; + /** + * @brief Description of option + */ + std::string description; + /** + * @brief True if option is the default option + */ + bool is_default; + /** + * @brief Emoji definition. To set an emoji on your button + * you must set one of either the name or id fields. + * The easiest way is to use the component::set_emoji + * method. + */ + struct inner_select_emoji { + /** + * @brief Set the name field to the name of the emoji. + * For built in unicode emojis, set this to the + * actual unicode value of the emoji e.g. "😄" + * and not for example ":smile:" + */ + std::string name; + /** + * @brief The emoji ID value for emojis that are custom + * ones belonging to a guild. The same rules apply + * as with other emojis, that the bot must be on + * the guild where the emoji resides and it must + * be available for use (e.g. not disabled due to + * lack of boosts etc) + */ + dpp::snowflake id = 0; + /** + * @brief True if the emoji is animated. Only applies to + * custom emojis. + */ + bool animated = false; + } emoji; + + /** + * @brief Construct a new select option object + */ + select_option(); + + /** + * @brief Destructs the select option object. + */ + virtual ~select_option() = default; + + /** + * @brief Construct a new select option object + * + * @param label Label of option + * @param value Value of option + * @param description Description of option + */ + select_option(const std::string &label, const std::string &value, const std::string &description = ""); + + /** + * @brief Set the label + * + * @param l the user-facing name of the option. It will be truncated to the maximum length of 100 UTF-8 characters. + * @return select_option& reference to self for chaining + */ + select_option& set_label(const std::string &l); + + /** + * @brief Set the value + * + * @param v value to set. It will be truncated to the maximum length of 100 UTF-8 characters. + * @return select_option& reference to self for chaining + */ + select_option& set_value(const std::string &v); + + /** + * @brief Set the description + * + * @param d description to set. It will be truncated to the maximum length of 100 UTF-8 characters. + * @return select_option& reference to self for chaining + */ + select_option& set_description(const std::string &d); + + /** + * @brief Set the emoji + * + * @param n emoji name + * @param id emoji id for custom emojis + * @param animated true if animated emoji + * @return select_option& reference to self for chaining + */ + select_option& set_emoji(const std::string &n, dpp::snowflake id = 0, bool animated = false); + + /** + * @brief Set the option as default + * + * @param def true to set the option as default + * @return select_option& reference to self for chaining + */ + select_option& set_default(bool def); + + /** + * @brief Set the emoji as animated + * + * @param anim true if animated + * @return select_option& reference to self for chaining + */ + select_option& set_animated(bool anim); + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + select_option& fill_from_json(nlohmann::json* j); +}; + +/** + * @brief Represents the component object. + * A component is a clickable button or drop down list + * within a discord message, where the buttons emit + * on_button_click events when the user interacts with + * them. + * + * You should generally define one component object and + * then insert one or more additional components into it + * using component::add_component(), so that the parent + * object is an action row and the child objects are buttons. + */ +class DPP_EXPORT component : public json_interface { +public: + /** Component type, either a button or action row + */ + component_type type; + + /** Sub components, buttons on an action row + */ + std::vector components; + + /** Component label (for buttons, text inputs). + * Maximum of 80 characters. + */ + std::string label; + + /** Component style (for buttons) + */ + component_style style; + + /** + * @brief Text style (for text inputs) + */ + text_style_type text_style; + + /** Component id (for buttons, menus, text inputs). + * Maximum of 100 characters. + */ + std::string custom_id; + + /** URL for link types (dpp::cos_link). + * Maximum of 512 characters. + */ + std::string url; + + /** Placeholder text for select menus and text inputs (max 150 characters) + */ + std::string placeholder; + + /** Minimum number of items that must be chosen for a select menu. + * Default is -1 to not set this + */ + int32_t min_values; + + /** Maximum number of items that can be chosen for a select menu. + * Default is -1 to not set this + */ + int32_t max_values; + + /** Minimum length for text input (0-4000) + */ + int32_t min_length; + + /** Maximum length for text input (1-4000) + */ + int32_t max_length; + + /** Select options for select menus. Only required and available for select menus of type dpp::cot_selectmenu + */ + std::vector options; + + /** List of channel types (dpp::channel_type) to include in the channel select component (dpp::cot_channel_selectmenu) + */ + std::vector channel_types; + + /** Disabled flag (for buttons) + */ + bool disabled; + + /** Whether the text input is required to be filled + */ + bool required; + + /** Value of the modal (filled or valid when populated from an + * on_form_submit event, or from the set_value function) + */ + std::variant value; + + /** Emoji definition. To set an emoji on your button + * you must set one of either the name or id fields. + * The easiest way is to use the component::set_emoji + * method. + */ + struct inner_emoji { + /** Set the name field to the name of the emoji. + * For built in unicode emojis, set this to the + * actual unicode value of the emoji e.g. "😄" + * and not for example ":smile:" + */ + std::string name; + /** The emoji ID value for emojis that are custom + * ones belonging to a guild. The same rules apply + * as with other emojis, that the bot must be on + * the guild where the emoji resides and it must + * be available for use (e.g. not disabled due to + * lack of boosts etc) + */ + dpp::snowflake id; + /** True if the emoji is animated. Only applies to + * custom emojis. + */ + bool animated; + } emoji; + + /** Constructor + */ + component(); + + /** Destructor + */ + virtual ~component() = default; + + /** + * @brief Add a channel type to include in the channel select component (dpp::cot_channel_selectmenu) + * + * @param ct The dpp::channel_type + * @return component& reference to self + */ + component& add_channel_type(uint8_t ct); + + /** + * @brief Set the type of the component. Button components + * (type dpp::cot_button) should always be contained within + * an action row (type dpp::cot_action_row). As described + * below, many of the other methods automatically set this + * to the correct type so usually you should not need to + * manually call component::set_type(). + * + * @param ct The component type + * @return component& reference to self + */ + component& set_type(component_type ct); + + /** + * @brief Set the text style of a text component + * @note Sets type to `cot_text` + * + * @param ts Text style type to set + * @return component& reference to self + */ + component& set_text_style(text_style_type ts); + + /** + * @brief Set the label of the component, e.g. button text. + * For action rows, this field is ignored. Setting the + * label will auto-set the type to dpp::cot_button. + * + * @param label Label text to set. It will be truncated to the maximum length of 80 UTF-8 characters. + * @return component& Reference to self + */ + component& set_label(const std::string &label); + + /** + * @brief Set the default value of the text input component. + * For action rows, this field is ignored. Setting the + * value will auto-set the type to dpp::cot_text. + * + * @param val Value text to set. It will be truncated to the maximum length of 4000 UTF-8 characters. + * @return component& Reference to self + */ + component& set_default_value(const std::string &val); + + /** + * @brief Set the url for dpp::cos_link types. + * Calling this function sets the style to dpp::cos_link + * and the type to dpp::cot_button. + * + * @param url URL to set. It will be truncated to the maximum length of 512 UTF-8 characters. + * @return component& reference to self. + */ + component& set_url(const std::string &url); + + /** + * @brief Set the style of the component, e.g. button colour. + * For action rows, this field is ignored. Setting the + * style will auto-set the type to dpp::cot_button. + * + * @param cs Component style to set + * @return component& reference to self + */ + component& set_style(component_style cs); + + /** + * @brief Set the id of the component. + * For action rows, this field is ignored. Setting the + * id will auto-set the type to dpp::cot_button. + * + * @param id Custom ID string to set. This ID will be sent + * for any on_button_click events related to the button. + * @note The maximum length of the Custom ID is 100 UTF-8 codepoints. + * If your Custom ID is longer than this, it will be truncated. + * @return component& Reference to self + */ + component& set_id(const std::string &id); + + /** + * @brief Set the component to disabled. + * Defaults to false on all created components. + * + * @param disable True to disable, false to disable. + * @return component& Reference to self + */ + component& set_disabled(bool disable); + + /** + * @brief Set if this component is required. + * Defaults to false on all created components. + * + * @param require True to require this, false to make it optional. + * @return component& Reference to self + */ + component& set_required(bool require); + + /** + * @brief Set the placeholder + * + * @param placeholder placeholder string. It will be truncated to the + * maximum length of 150 UTF-8 characters for select menus, and 100 UTF-8 + * characters for modals. + * @return component& Reference to self + */ + component& set_placeholder(const std::string &placeholder); + + /** + * @brief Set the min value + * + * @param min_values min value to set + * @return component& Reference to self + */ + component& set_min_values(uint32_t min_values); + + /** + * @brief Set the max value + * + * @param max_values max value to set (0 - 25) + * @return component& Reference to self + */ + component& set_max_values(uint32_t max_values); + + /** + * @brief Set the min length of text input + * + * @param min_l min value to set (0 - 25) + * @return component& Reference to self + */ + component& set_min_length(uint32_t min_l); + + /** + * @brief Set the max length of text input + * + * @param max_l max value to set + * @return component& Reference to self + */ + component& set_max_length(uint32_t max_l); + + /** + * @brief Add a select option + * + * @param option option to add + * @return component& Reference to self + */ + component& add_select_option(const select_option &option); + + /** + * @brief Add a sub-component, only valid for action rows. + * Adding subcomponents to a component will automatically + * set this component's type to dpp::cot_action_row. + * + * @param c The sub-component to add + * @return component& reference to self + */ + component& add_component(const component& c); + + /** + * @brief Set the emoji of the current sub-component. + * Only valid for buttons. Adding an emoji to a component + * will automatically set this components type to + * dpp::cot_button. One or both of name and id must be set. + * For a built in unicode emoji, you only need set name, + * and should set it to a unicode character e.g. "😄". + * For custom emojis, set the name to the name of the emoji + * on the guild, and the id to the emoji's ID. + * Setting the animated boolean is only valid for custom + * emojis. + * + * @param name Emoji name, or unicode character to use + * @param id Emoji id, for custom emojis only. + * @param animated True if the custom emoji is animated. + * @return component& Reference to self + */ + component& set_emoji(const std::string& name, dpp::snowflake id = 0, bool animated = false); + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + component& fill_from_json(nlohmann::json* j); + +}; + +/** + * @brief A footer in a dpp::embed + */ +struct DPP_EXPORT embed_footer { + /** Footer text */ + std::string text; + /** Footer icon url */ + std::string icon_url; + /** Proxied icon url */ + std::string proxy_url; + + /** Set footer's text. Returns footer itself so these methods may be "chained" + * @param t string to set as footer text. It will be truncated to the maximum length of 2048 UTF-8 characters. + * @return A reference to self + */ + embed_footer& set_text(const std::string& t); + + /** Set footer's icon url. Returns footer itself so these methods may be "chained" + * @param i url to set as footer icon url + * @return A reference to self + */ + embed_footer& set_icon(const std::string& i); + + /** Set footer's proxied icon url. Returns footer itself so these methods may be "chained" + * @param p url to set as footer proxied icon url + * @return A reference to self + */ + embed_footer& set_proxy(const std::string& p); +}; + +/** + * @brief An video, image or thumbnail in a dpp::embed + */ +struct DPP_EXPORT embed_image { + /** URL to image or video */ + std::string url; + /** Proxied image url */ + std::string proxy_url; + /** Height (calculated by discord) */ + std::string height; + /** Width (calculated by discord) */ + std::string width; +}; + +/** + * @brief Embed provider in a dpp::embed. Received from discord but cannot be sent + */ +struct DPP_EXPORT embed_provider { + /** Provider name */ + std::string name; + /** Provider URL */ + std::string url; +}; + +/** + * @brief Author within a dpp::embed object + */ +struct DPP_EXPORT embed_author { + /** Author name */ + std::string name; + /** Author url */ + std::string url; + /** Author icon url */ + std::string icon_url; + /** Proxied icon url */ + std::string proxy_icon_url; +}; + +/** + * @brief A dpp::embed may contain zero or more fields + */ +struct DPP_EXPORT embed_field { + /** Name of field */ + std::string name; + /** Value of field (max length 1000) */ + std::string value; + /** True if the field is to be displayed inline */ + bool is_inline; +}; + +/** + * @brief A rich embed for display within a dpp::message + */ +struct DPP_EXPORT embed { + /** Optional: title of embed */ + std::string title; + /** Optional: type of embed (always "rich" for webhook embeds) */ + std::string type; + /** Optional: description of embed */ + std::string description; + /** Optional: url of embed */ + std::string url; + /** Optional: timestamp of embed content */ + time_t timestamp; + /** Optional: color code of the embed */ + uint32_t color; + /** Optional: footer information */ + std::optional footer; + /** Optional: image information */ + std::optional image; + /** Optional: thumbnail information */ + std::optional thumbnail; + /** Optional: video information (can't send these) */ + std::optional video; + /** Optional: provider information (can't send these) */ + std::optional provider; + /** Optional: author information */ + std::optional author; + /** Optional: fields information */ + std::vector fields; + + /** Constructor */ + embed(); + + /** Constructor to build embed from json object + * @param j JSON to read content from + */ + embed(nlohmann::json* j); + + /** Destructor */ + ~embed(); + + /** Set embed title. Returns the embed itself so these method calls may be "chained" + * @param text The text of the title. It will be truncated to the maximum length of 256 UTF-8 characters. + * @return A reference to self + */ + embed& set_title(const std::string &text); + + /** Set embed description. Returns the embed itself so these method calls may be "chained" + * @param text The text of the title. It will be truncated to the maximum length of 4096 UTF-8 characters. + * @return A reference to self + */ + embed& set_description(const std::string &text); + + /** Set the footer of the embed. Returns the embed itself so these method calls may be "chained" + * @param f the footer to set + * @return A reference to self + */ + embed& set_footer(const embed_footer& f); + + /** Set the footer of the embed. Returns the embed itself so these method calls may be "chained" + * @param text string to set as footer text. It will be truncated to the maximum length of 2048 UTF-8 characters. + * @param icon_url an url to set as footer icon url + * @return A reference to self + */ + embed& set_footer(const std::string& text, const std::string& icon_url); + + /** Set embed colour. Returns the embed itself so these method calls may be "chained" + * @param col The colour of the embed + * @return A reference to self + */ + embed& set_color(uint32_t col); + + /** Set embed timestamp. Returns the embed itself so these method calls may be "chained" + * @param tstamp The timestamp to show in the footer, should be in UTC + * @return A reference to self + */ + embed& set_timestamp(time_t tstamp); + + /** Set embed url. Returns the embed itself so these method calls may be "chained" + * @param url the url of the embed + * @return A reference to self + */ + embed& set_url(const std::string &url); + + /** Add an embed field. Returns the embed itself so these method calls may be "chained" + * @param name The name of the field. It will be truncated to the maximum length of 256 UTF-8 characters. + * @param value The value of the field. It will be truncated to the maximum length of 1024 UTF-8 characters. + * @param is_inline Whether or not to display the field 'inline' or on its own line + * @return A reference to self + */ + embed& add_field(const std::string& name, const std::string &value, bool is_inline = false); + + /** Set embed author. Returns the embed itself so these method calls may be "chained" + * @param a The author to set + * @return A reference to self + */ + embed& set_author(const dpp::embed_author& a); + + /** Set embed author. Returns the embed itself so these method calls may be "chained" + * @param name The name of the author. It will be truncated to the maximum length of 256 UTF-8 characters. + * @param url The url of the author + * @param icon_url The icon URL of the author + * @return A reference to self + */ + embed& set_author(const std::string& name, const std::string& url, const std::string& icon_url); + + /** Set embed provider. Returns the embed itself so these method calls may be "chained" + * @param name The provider name. It will be truncated to the maximum length of 256 UTF-8 characters. + * @param url The provider url + * @return A reference to self + */ + embed& set_provider(const std::string& name, const std::string& url); + + /** Set embed image. Returns the embed itself so these method calls may be "chained" + * @param url The embed image URL + * @return A reference to self + */ + embed& set_image(const std::string& url); + + /** Set embed video. Returns the embed itself so these method calls may be "chained" + * @param url The embed video url + * @return A reference to self + */ + embed& set_video(const std::string& url); + + /** Set embed thumbnail. Returns the embed itself so these method calls may be "chained" + * @param url The embed thumbnail url + * @return A reference to self + */ + embed& set_thumbnail(const std::string& url); +}; + +/** + * @brief Represents a reaction to a dpp::message + */ +struct DPP_EXPORT reaction { + /** Number of times this reaction has been added */ + uint32_t count; + /** Reaction was from the bot's id */ + bool me; + /** ID of emoji for reaction */ + snowflake emoji_id; + /** Name of emoji, if applicable */ + std::string emoji_name; + + /** + * @brief Constructs a new reaction object. + */ + reaction(); + + /** + * @brief Constructs a new reaction object from a JSON object. + * @param j The JSON to read data from + */ + reaction(nlohmann::json* j); + + /** + * @brief Destructs the reaction object. + */ + ~reaction() = default; +}; + +/** + * @brief Represents an attachment in a dpp::message + */ +struct DPP_EXPORT attachment { + /** ID of attachment */ + snowflake id; + /** Size of the attachment in bytes */ + uint32_t size; + /** File name of the attachment */ + std::string filename; + /** Optional: Description of the attachment (max 1024 characters) */ + std::string description; + /** URL which points to the attachment */ + std::string url; + /** Proxied URL which points to the attachment */ + std::string proxy_url; + /** Width of the attachment, if applicable */ + uint32_t width; + /** Height of the attachment, if applicable */ + uint32_t height; + /** MIME type of the attachment, if applicable */ + std::string content_type; + /** Whether this attachment is ephemeral, if applicable */ + bool ephemeral; + /** Owning message */ + struct message* owner; + + /** + * @brief Constructs a new attachment object. + * @param o Owning dpp::message object + */ + attachment(struct message* o); + + /** + * @brief Constructs a new attachment object from a JSON object. + * @param o Owning dpp::message object + * @param j JSON to read information from + */ + attachment(struct message* o, nlohmann::json* j); + + /** + * @brief Destructs the attachment object. + */ + ~attachment() = default; + + /** + * @brief Download this attachment + * @param callback A callback which is called when the download completes. + * @note The content of the file will be in the http_info.body parameter of the + * callback parameter. + * @throw dpp::logic_exception If there is no owner associated with this attachment that + * itself has an owning cluster, this method will throw a dpp::logic_exception when called. + */ + void download(http_completion_event callback) const; +}; + +/** + * @brief Represents the type of a sticker + */ +enum sticker_type : uint8_t { + /// Nitro pack sticker + st_standard = 1, + /// Guild sticker + st_guild = 2 +}; + +/** + * @brief The file format (png, apng, lottie) of a sticker + */ +enum sticker_format : uint8_t { + sf_png = 1, + sf_apng = 2, + sf_lottie = 3 +}; + +/** + * @brief Represents stickers received in messages + */ +struct DPP_EXPORT sticker : public managed, public json_interface { + /** Optional: for standard stickers, id of the pack the sticker is from + */ + snowflake pack_id; + /** The name of the sticker */ + std::string name; + /// description of the sticker (may be empty) + std::string description; + /** for guild stickers, the Discord name of a unicode emoji representing the sticker's expression. + * for standard stickers, a comma-separated list of related expressions. + */ + std::string tags; + /** + * @brief Asset ID + * @deprecated now an empty string but still sent by discord. + * While discord still send this empty string value we will still have a field + * here in the library. + */ + std::string asset; + /** The type of sticker */ + sticker_type type; + /// type of sticker format + sticker_format format_type; + /// Optional: whether this guild sticker can be used, may be false due to loss of Server Boosts + bool available; + /// Optional: id of the guild that owns this sticker + snowflake guild_id; + /// Optional: the user that uploaded the guild sticker + user sticker_user; + /// Optional: the standard sticker's sort order within its pack + uint8_t sort_value; + /** Name of file to upload (when adding or editing a sticker) */ + std::string filename; + /** File content to upload (raw binary) */ + std::string filecontent; + + /** + * @brief Construct a new sticker object + */ + sticker(); + + virtual ~sticker() = default; + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + sticker& fill_from_json(nlohmann::json* j); + + /** Build JSON from this object. + * @param with_id True if the ID is to be set in the JSON structure + * @return The JSON text of the invite + */ + virtual std::string build_json(bool with_id = true) const; + + /** + * @brief Get the sticker url + * + * @param accept_lottie Whether to allow that [lottie](https://airbnb.io/lottie/#/) (json format) can be returned or not + * @return std::string The sticker url or an empty string when its a lottie and accept_lottie is false + */ + std::string get_url(bool accept_lottie = true) const; + + /** + * @brief Set the filename + * + * @param fn filename + * @return message& reference to self + */ + sticker& set_filename(const std::string &fn); + + /** + * @brief Set the file content + * + * @param fc raw file content contained in std::string + * @return message& reference to self + */ + sticker& set_file_content(const std::string &fc); + +}; + +/** + * @brief Represents a sticker pack (the built in groups of stickers that all nitro users get to use) + */ +struct DPP_EXPORT sticker_pack : public managed, public json_interface { + /// the stickers in the pack + std::map stickers; + /// name of the sticker pack + std::string name; + /// id of the pack's SKU + snowflake sku_id; + /// Optional: id of a sticker in the pack which is shown as the pack's icon + snowflake cover_sticker_id; + /// description of the sticker pack + std::string description; + /// id of the sticker pack's banner image + snowflake banner_asset_id; + + /** + * @brief Construct a new sticker pack object + */ + sticker_pack(); + + virtual ~sticker_pack() = default; + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + sticker_pack& fill_from_json(nlohmann::json* j); + + /** Build JSON from this object. + * @param with_id True if the ID is to be set in the JSON structure + * @return The JSON text of the invite + */ + virtual std::string build_json(bool with_id = true) const; + +}; + +/** + * @brief Bitmask flags for a dpp::message + */ +enum message_flags : uint16_t { + /// this message has been published to subscribed channels (via Channel Following) + m_crossposted = 1 << 0, + /// this message originated from a message in another channel (via Channel Following) + m_is_crosspost = 1 << 1, + /// do not include any embeds when serializing this message + m_suppress_embeds = 1 << 2, + /// the source message for this crosspost has been deleted (via Channel Following) + m_source_message_deleted = 1 << 3, + /// this message came from the urgent message system + m_urgent = 1 << 4, + /// this message has an associated thread, with the same id as the message + m_has_thread = 1 << 5, + /// this message is only visible to the user who invoked the Interaction + m_ephemeral = 1 << 6, + /// this message is an Interaction Response and the bot is "thinking" + m_loading = 1 << 7, + /// this message failed to mention some roles and add their members to the thread + m_thread_mention_failed = 1 << 8, +}; + +/** + * @brief Represents possible values for the dpp::embed type field. + * These are loosely defined by the API docs and do not influence how the client renders embeds. + * The only type a bot can send is dpp::embed_type::emt_rich. + */ +namespace embed_type { + /** + * @brief Rich text + */ + const std::string emt_rich = "rich"; + /** + * @brief Image + */ + const std::string emt_image = "image"; + /** + * @brief Video link + */ + const std::string emt_video = "video"; + /** + * @brief Animated gif + */ + const std::string emt_gifv = "gifv"; + /** + * @brief Article + */ + const std::string emt_article = "article"; + /** + * @brief Link URL + */ + const std::string emt_link = "link"; + /** + * @brief Auto moderation filter + */ + const std::string emt_automod = "auto_moderation_message"; +}; + +/** + * @brief Message types for dpp::message::type + */ +enum message_type { + /// Default + mt_default = 0, + /// Add recipient + mt_recipient_add = 1, + /// Remove recipient + mt_recipient_remove = 2, + /// Call + mt_call = 3, + /// Channel name change + mt_channel_name_change = 4, + /// Channel icon change + mt_channel_icon_change = 5, + /// Message pinned + mt_channel_pinned_message = 6, + /// Member joined + mt_guild_member_join = 7, + /// Boost + mt_user_premium_guild_subscription = 8, + /// Boost level 1 + mt_user_premium_guild_subscription_tier_1 = 9, + /// Boost level 2 + mt_user_premium_guild_subscription_tier_2 = 10, + /// Boost level 3 + mt_user_premium_guild_subscription_tier_3 = 11, + /// Follow channel + mt_channel_follow_add = 12, + /// Disqualified from discovery + mt_guild_discovery_disqualified = 14, + /// Re-qualified for discovery + mt_guild_discovery_requalified = 15, + /// Discovery grace period warning 1 + mt_guild_discovery_grace_period_initial_warning = 16, + /// Discovery grace period warning 2 + mt_guild_discovery_grace_period_final_warning = 17, + /// Thread Created + mt_thread_created = 18, + /// Reply + mt_reply = 19, + /// Application command + mt_application_command = 20, + /// Thread starter message + mt_thread_starter_message = 21, + /// Invite reminder + mt_guild_invite_reminder = 22, + /// Context Menu Command + mt_context_menu_command = 23, + /// Auto moderation action + mt_auto_moderation_action = 24, +}; + +/** + * @brief Represents the caching policy of a cache in the library. + */ +enum cache_policy_setting_t { + /** + * @brief request aggressively on seeing new guilds, and also store missing data from messages. + * This is the default behaviour and the least memory-efficient option. Memory usage will increase + * over time, initially quite rapidly, and then linearly over time. It is the least cpu-intensive + * setting. + */ + cp_aggressive = 0, + /** + * @brief only cache when there is relevant activity, e.g. a message to the bot. + * This is a good middle-ground, memory usage will increase linearly over time. + */ + cp_lazy = 1, + /** + * @brief Don't cache anything. Fill details when we see them. + * This is the most memory-efficient option but consumes more CPU time + */ + cp_none = 2 +}; + +/** + * @brief Represents the caching policy of the cluster. + * + * Channels and guilds are always cached as these caches are used + * internally by the library. The memory usage of these is minimal. + * + * All default to 'aggressive' which means to actively attempt to cache, + * going out of the way to fill the caches completely. On large bots this + * can take a LOT of RAM. + */ +struct DPP_EXPORT cache_policy_t { + /** + * @brief Caching policy for users and guild members + */ + cache_policy_setting_t user_policy = cp_aggressive; + + /** + * @brief Caching policy for emojis + */ + cache_policy_setting_t emoji_policy = cp_aggressive; + + /** + * @brief Caching policy for roles + */ + cache_policy_setting_t role_policy = cp_aggressive; +}; + +/** + * @brief Represents messages sent and received on Discord + */ +struct DPP_EXPORT message : public managed { + /** id of the channel the message was sent in */ + snowflake channel_id; + /** Optional: id of the guild the message was sent in */ + snowflake guild_id; + /** the author of this message (not guaranteed to be a valid user) */ + user author; + /** Optional: member properties for this message's author */ + guild_member member; + /** contents of the message */ + std::string content; + /** message components */ + std::vector components; + /** when this message was sent */ + time_t sent; + /** when this message was edited (may be 0 if never edited) */ + time_t edited; + /** users specifically mentioned in the message */ + std::vector> mentions; + /** roles specifically mentioned in this message (only IDs currently)*/ + std::vector mention_roles; + /** Channels mentioned in the message. (Discord: not all types supported) + * Discord: Only textual channels that are visible to everyone in a lurkable guild will ever be included. Only crossposted messages (via Channel Following) currently include mention_channels at all. (includes ID, Guild ID, Type, Name)*/ + std::vector mention_channels; + /** any attached files */ + std::vector attachments; + /** zero or more dpp::embed objects */ + std::vector embeds; + /** Optional: reactions to the message */ + std::vector reactions; + /** Optional: used for validating a message was sent */ + std::string nonce; + /** Optional: if the message is generated by a webhook, its id will be here otherwise the field will be 0 */ + snowflake webhook_id; + /** Stickers */ + std::vector stickers; + + /** Name of file to upload (for use server-side in discord's url) */ + std::vector filename; + + /** File content to upload (raw binary) */ + std::vector filecontent; + + /** + * @brief Reference to another message, e.g. a reply + */ + struct message_ref { + /// id of the originating message + snowflake message_id; + /// id of the originating message's channel + snowflake channel_id; + /// id of the originating message's guild + snowflake guild_id; + /// when sending, whether to error if the referenced message doesn't exist instead of sending as a normal (non-reply) message, default true + bool fail_if_not_exists; + } message_reference; + + /** + * @brief Reference to an interaction + */ + struct message_interaction_struct{ + /// id of the interaction + snowflake id; + /// type of interaction + uint8_t type; + /// name of the application command + std::string name; + /// the user who invoked the interaction + user usr; + } interaction; + + /** + * @brief Allowed mentions details + */ + struct allowed_ref { + /** + * @brief Set to true to parse user mentions in the text. Default is false + */ + bool parse_users; + /** + * @brief Set to true to at-everyone and at-here mentions in the text. Default is false + */ + bool parse_everyone; + /** + * @brief Set to true to parse role mentions in the text. Default is false + */ + bool parse_roles; + /** + * @brief Set to true to mention the user who sent the message this one is replying to. Default is false + */ + bool replied_user; + /** + * @brief List of users to allow pings for + */ + std::vector users; + /** + * @brief List of roles to allow pings for + */ + std::vector roles; + } allowed_mentions; + + /** + * @brief The cluster which created this message object + */ + class cluster* owner; + + /** Message type */ + message_type type; + + /** Flags. Made of bits in dpp::message_flags */ + uint16_t flags; + + /** whether this message is pinned */ + bool pinned; + /** whether this was a TTS message */ + bool tts; + /** whether this message mentions everyone */ + bool mention_everyone; + + /** + * @brief Construct a new message object + */ + message(); + + /** + * @brief Construct a new message object + * @param o Owning cluster, passed down to various things such as dpp::attachment. + * Owning cluster is optional (can be nullptr) and if nulled, will prevent some functions + * such as attachment::download from functioning (they will throw, if used) + */ + message(class cluster* o); + + /** + * @brief Destroy the message object + */ + virtual ~message(); + + /** + * @brief Construct a new message object with a channel and content + * + * @param channel_id The channel to send the message to + * @param content The content of the message. It will be truncated to the maximum length of 4000 UTF-8 characters. + * @param type The message type to create + */ + message(snowflake channel_id, const std::string &content, message_type type = mt_default); + + /** + * @brief Construct a new message object with a channel and content + * + * @param channel_id The channel to send the message to + * @param _embed An embed to send + */ + message(snowflake channel_id, const embed & _embed); + + /** + * @brief Construct a new message object with content + * + * @param content The content of the message. It will be truncated to the maximum length of 4000 UTF-8 characters. + * @param type The message type to create + */ + message(const std::string &content, message_type type = mt_default); + + /** + * @brief Set the original message reference for replies/crossposts + * + * @param _message_id message id to reply to + * @param _guild_id guild id to reply to (optional) + * @param _channel_id channel id to reply to (optional) + * @param fail_if_not_exists true if the message send should fail if these values are invalid (optional) + * @return message& reference to self + */ + message& set_reference(snowflake _message_id, snowflake _guild_id = 0, snowflake _channel_id = 0, bool fail_if_not_exists = false); + + /** + * @brief Set the allowed mentions object for pings on the message + * + * @param _parse_users whether or not to parse users in the message content or embeds + * @param _parse_roles whether or not to parse roles in the message content or embeds + * @param _parse_everyone whether or not to parse everyone/here in the message content or embeds + * @param _replied_user if set to true and this is a reply, then ping the user we reply to + * @param users list of user ids to allow pings for + * @param roles list of role ids to allow pings for + * @return message& reference to self + */ + message& set_allowed_mentions(bool _parse_users, bool _parse_roles, bool _parse_everyone, bool _replied_user, const std::vector &users, const std::vector &roles); + + /** Fill this object from json. + * @param j JSON object to fill from + * @param cp Cache policy for user records, whether or not we cache users when a message is received + * @return A reference to self + */ + message& fill_from_json(nlohmann::json* j, cache_policy_t cp = {cp_aggressive, cp_aggressive, cp_aggressive}); + + /** Build JSON from this object. + * @param with_id True if the ID is to be included in the built JSON + * @param is_interaction_response Set to true if this message is intended to be included in an interaction response. + * This will exclude some fields that are not valid in interactions at this time. + * @return The JSON text of the message + */ + virtual std::string build_json(bool with_id = false, bool is_interaction_response = false) const; + + /** + * @brief Returns true if the message was crossposted to other servers + * + * @return true if crossposted + */ + bool is_crossposted() const; + + /** + * @brief Returns true if posted from other servers announcement channel via webhook + * + * @return true if posted from other server + */ + bool is_crosspost() const; + + /** + * @brief True if embeds have been removed + * + * @return true if embeds removed + */ + bool suppress_embeds() const; + + /** + * @brief True if source message was deleted + * + * @return true if source message deleted + */ + bool is_source_message_deleted() const; + + /** + * @brief True if urgent + * + * @return true if urgent + */ + bool is_urgent() const; + + /** + * @brief True if has thread attached + * + * @return true if has thread attached + */ + bool has_thread() const; + + /** + * @brief True if ephemeral (visible only to issuer of a slash command) + * + * @return true if ephemeral + */ + bool is_ephemeral() const; + + /** + * @brief True if loading + * + * @return true if loading + */ + bool is_loading() const; + + /** + * @brief Returns true if this message failed to mention some roles and add their members to the thread + * + * @return true if this message failed to mention some roles and add their members to the thread + */ + bool is_thread_mention_failed() const; + + /** + * @brief Add a component (button) to message + * + * @param c component to add + * @return message& reference to self + */ + message& add_component(const component& c); + + /** + * @brief Add an embed to message + * + * @param e embed to add + * @return message& reference to self + */ + message& add_embed(const embed& e); + + /** + * @brief Set the flags + * + * @param f flags to set from dpp::message_flags + * @return message& reference to self + */ + message& set_flags(uint16_t f); + + /** + * @brief Set the message type + * + * @param t type to set + * @return message& reference to self + */ + message& set_type(message_type t); + + /** + * @brief Set the filename of the last file in list + * + * @param fn filename + * @return message& reference to self + * @deprecated Use message::add_file instead + */ + message& set_filename(const std::string &fn); + + /** + * @brief Set the file content of the last file in list + * + * @param fc raw file content contained in std::string + * @return message& reference to self + * @deprecated Use message::add_file instead + */ + message& set_file_content(const std::string &fc); + + /** + * @brief Add a file to the message + * + * @param filename filename + * @param filecontent raw file content contained in std::string + * @return message& reference to self + */ + message& add_file(const std::string &filename, const std::string &filecontent); + + /** + * @brief Set the message content + * + * @param c message content. It will be truncated to the maximum length of 4000 UTF-8 characters. + * @return message& reference to self + */ + message& set_content(const std::string &c); + + /** + * @brief Set the channel id + * + * @param _channel_id channel id + * @return message& reference to self + */ + message& set_channel_id(snowflake _channel_id); + + /** + * @brief Set the channel id + * + * @param _guild_id channel id + * @return message& reference to self + */ + message& set_guild_id(snowflake _guild_id); + + /** + * @brief Returns true if the message is from a DM + * + * @return true if message is a DM + */ + bool is_dm() const; +}; + +/** A group of messages */ +typedef std::unordered_map message_map; + +/** A group of stickers */ +typedef std::unordered_map sticker_map; + +/** A group of sticker packs */ +typedef std::unordered_map sticker_pack_map; + +}; diff --git a/3rdParty/dpp/misc-enum.h b/3rdParty/dpp/misc-enum.h index 0e488470bb..19ef2a1edf 100644 --- a/3rdParty/dpp/misc-enum.h +++ b/3rdParty/dpp/misc-enum.h @@ -1,53 +1,53 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include - -namespace dpp { - - /** @brief Supported image types for profile pictures */ - enum image_type { - /// image/png - i_png, - /// image/jpeg - i_jpg, - /// image/gif - i_gif - }; - - /** @brief Log levels */ - enum loglevel { - /// Trace - ll_trace = 0, - /// Debug - ll_debug, - /// Information - ll_info, - /// Warning - ll_warning, - /// Error - ll_error, - /// Critical - ll_critical - }; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include + +namespace dpp { + + /** @brief Supported image types for profile pictures */ + enum image_type { + /// image/png + i_png, + /// image/jpeg + i_jpg, + /// image/gif + i_gif + }; + + /** @brief Log levels */ + enum loglevel { + /// Trace + ll_trace = 0, + /// Debug + ll_debug, + /// Information + ll_info, + /// Warning + ll_warning, + /// Error + ll_error, + /// Critical + ll_critical + }; + +}; diff --git a/3rdParty/dpp/nlohmann/json.hpp b/3rdParty/dpp/nlohmann/json.hpp index 6f74deae67..9b6728a2bc 100644 --- a/3rdParty/dpp/nlohmann/json.hpp +++ b/3rdParty/dpp/nlohmann/json.hpp @@ -1 +1 @@ -#include "3rdParty/nlohmann/json.hpp" +#include "3rdParty/nlohmann/json.hpp" diff --git a/3rdParty/dpp/nlohmann/json_fwd.hpp b/3rdParty/dpp/nlohmann/json_fwd.hpp index d34c8afd10..9163963745 100644 --- a/3rdParty/dpp/nlohmann/json_fwd.hpp +++ b/3rdParty/dpp/nlohmann/json_fwd.hpp @@ -1 +1 @@ -#include "3rdParty/nlohmann/json_fwd.hpp" +#include "3rdParty/nlohmann/json_fwd.hpp" diff --git a/3rdParty/dpp/once.h b/3rdParty/dpp/once.h index 0c1a8ce670..f77339673f 100644 --- a/3rdParty/dpp/once.h +++ b/3rdParty/dpp/once.h @@ -1,46 +1,46 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2022 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include - -namespace dpp { - - /** - * @brief Run some code within an if() statement only once. - * - * Use this template like this: - * - * ``` - * if (dpp::run_once()) { - * // Your code here - * } - * ``` - * - * @tparam T any unique 'tag' identifier name - * @return auto a true/false return to say if we should execute or not - */ - template auto run_once() { - static auto called = false; - return !std::exchange(called, true); - }; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2022 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include + +namespace dpp { + + /** + * @brief Run some code within an if() statement only once. + * + * Use this template like this: + * + * ``` + * if (dpp::run_once()) { + * // Your code here + * } + * ``` + * + * @tparam T any unique 'tag' identifier name + * @return auto a true/false return to say if we should execute or not + */ + template auto run_once() { + static auto called = false; + return !std::exchange(called, true); + }; + +}; diff --git a/3rdParty/dpp/permissions.h b/3rdParty/dpp/permissions.h index caf248fc76..2f8b1fe310 100644 --- a/3rdParty/dpp/permissions.h +++ b/3rdParty/dpp/permissions.h @@ -1,204 +1,204 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Represents the various discord permissions - */ -enum permissions : uint64_t { - p_create_instant_invite = 0x00000000001, //!< allows creation of instant invites - p_kick_members = 0x00000000002, //!< allows kicking members - p_ban_members = 0x00000000004, //!< allows banning members - p_administrator = 0x00000000008, //!< allows all permissions and bypasses channel permission overwrites - p_manage_channels = 0x00000000010, //!< allows management and editing of channels - p_manage_guild = 0x00000000020, //!< allows management and editing of the guild - p_add_reactions = 0x00000000040, //!< allows for the addition of reactions to messages - p_view_audit_log = 0x00000000080, //!< allows for viewing of audit logs - p_priority_speaker = 0x00000000100, //!< allows for using priority speaker in a voice channel - p_stream = 0x00000000200, //!< allows the user to go live - p_view_channel = 0x00000000400, //!< allows guild members to view a channel, which includes reading messages in text channels and joining voice channels - p_send_messages = 0x00000000800, //!< allows for sending messages in a channel - p_send_tts_messages = 0x00000001000, //!< allows for sending of /tts messages - p_manage_messages = 0x00000002000, //!< allows for deletion of other users messages - p_embed_links = 0x00000004000, //!< links sent by users with this permission will be auto-embedded - p_attach_files = 0x00000008000, //!< allows for uploading images and files - p_read_message_history = 0x00000010000, //!< allows for reading of message history - p_mention_everyone = 0x00000020000, //!< allows for using the everyone and the here tag to notify users in a channel - p_use_external_emojis = 0x00000040000, //!< allows the usage of custom emojis from other servers - p_view_guild_insights = 0x00000080000, //!< allows for viewing guild insights - p_connect = 0x00000100000, //!< allows for joining of a voice channel - p_speak = 0x00000200000, //!< allows for speaking in a voice channel - p_mute_members = 0x00000400000, //!< allows for muting members in a voice channel - p_deafen_members = 0x00000800000, //!< allows for deafening of members in a voice channel - p_move_members = 0x00001000000, //!< allows for moving of members between voice channels - p_use_vad = 0x00002000000, //!< allows for using voice-activity-detection in a voice channel - p_change_nickname = 0x00004000000, //!< allows for modification of own nickname - p_manage_nicknames = 0x00008000000, //!< allows for modification of other users nicknames - p_manage_roles = 0x00010000000, //!< allows management and editing of roles - p_manage_webhooks = 0x00020000000, //!< allows management and editing of webhooks - p_manage_emojis_and_stickers = 0x00040000000, //!< allows management and editing of emojis and stickers - p_use_application_commands = 0x00080000000, //!< allows members to use application commands, including slash commands and context menus - p_request_to_speak = 0x00100000000, //!< allows for requesting to speak in stage channels. (Discord: This permission is under active development and may be changed or removed.) - p_manage_events = 0x00200000000, //!< allows for management (creation, updating, deleting, starting) of scheduled events - p_manage_threads = 0x00400000000, //!< allows for deleting and archiving threads, and viewing all private threads - p_create_public_threads = 0x00800000000, //!< allows for creating public and announcement threads - p_create_private_threads = 0x01000000000, //!< allows for creating private threads - p_use_external_stickers = 0x02000000000, //!< allows the usage of custom stickers from other servers - p_send_messages_in_threads = 0x04000000000, //!< allows for sending messages in threads - p_use_embedded_activities = 0x08000000000, //!< allows for using activities (applications with the EMBEDDED flag) in a voice channel - p_moderate_members = 0x10000000000, //!< allows for timing out users to prevent them from sending or reacting to messages in chat and threads, and from speaking in voice and stage channels -}; - -/** - * @brief Represents the various discord permissions - * @deprecated Use dpp::permissions instead. - */ -using role_permissions = permissions; - -/** - * @brief Represents a permission bitmask (refer to enum dpp::permissions) which are hold in an uint64_t - */ -class DPP_EXPORT permission { -protected: - /** - * @brief The permission bitmask value - */ - uint64_t value; - -public: - /** - * @brief Construct a permission object - * @param value A permission bitmask - */ - permission(const uint64_t& value); - - /** - * @brief Construct a permission object - */ - permission(); - - /** - * @brief For acting like an integer - * @return The permission bitmask value - */ - operator uint64_t() const; - - /** - * @brief For acting like an integer - * @return A reference to the permission bitmask value - */ - operator uint64_t &(); - - /** - * @brief For building json - * @return The permission bitmask value as a string - */ - operator nlohmann::json() const; - - /** - * @brief Check for permission flags set. It uses the Bitwise AND operator - * @tparam T one or more uint64_t permission bits - * @param values The permissions (from dpp::permissions) to check for - * - * **Example:** - * - * ```cpp - * bool is_mod = permission.has(dpp::p_kick_members, dpp::p_ban_members); - * // Returns true if the permission bitmask contains p_kick_members and p_ban_members - * ``` - * - * @return bool True if it has all the given permissions - */ - template - bool has(T... values) const { - return (value & (0 | ... | values)) == (0 | ... | values); - } - - /** - * @brief Add a permission with the Bitwise OR operation - * @tparam T one or more uint64_t permission bits - * @param values The permissions (from dpp::permissions) to add - * - * **Example:** - * - * ```cpp - * permission.add(dpp::p_view_channel, dpp::p_send_messages); - * // Adds p_view_channel and p_send_messages to the permission bitmask - * ``` - * - * @return permission& reference to self for chaining - */ - template - typename std::enable_if<(std::is_convertible::value && ...), permission&>::type - add(T... values) { - value |= (0 | ... | values); - return *this; - } - - /** - * @brief Assign a permission. This will reset the bitmask to the new value. - * @tparam T one or more uint64_t permission bits - * @param values The permissions (from dpp::permissions) to set - * - * **Example:** - * - * ```cpp - * permission.set(dpp::p_view_channel, dpp::p_send_messages); - * ``` - * - * @return permission& reference to self for chaining - */ - template - typename std::enable_if<(std::is_convertible::value && ...), permission&>::type - set(T... values) { - value = (0 | ... | values); - return *this; - } - - /** - * @brief Remove a permission with the Bitwise NOT operation - * @tparam T one or more uint64_t permission bits - * @param values The permissions (from dpp::permissions) to remove - * - * **Example:** - * - * ```cpp - * permission.remove(dpp::p_view_channel, dpp::p_send_messages); - * // Removes p_view_channel and p_send_messages permission - * ``` - * - * @return permission& reference to self for chaining - */ - template - typename std::enable_if<(std::is_convertible::value && ...), permission&>::type - remove(T... values) { - value &= ~(0 | ... | values); - return *this; - } -}; - -} +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Represents the various discord permissions + */ +enum permissions : uint64_t { + p_create_instant_invite = 0x00000000001, //!< allows creation of instant invites + p_kick_members = 0x00000000002, //!< allows kicking members + p_ban_members = 0x00000000004, //!< allows banning members + p_administrator = 0x00000000008, //!< allows all permissions and bypasses channel permission overwrites + p_manage_channels = 0x00000000010, //!< allows management and editing of channels + p_manage_guild = 0x00000000020, //!< allows management and editing of the guild + p_add_reactions = 0x00000000040, //!< allows for the addition of reactions to messages + p_view_audit_log = 0x00000000080, //!< allows for viewing of audit logs + p_priority_speaker = 0x00000000100, //!< allows for using priority speaker in a voice channel + p_stream = 0x00000000200, //!< allows the user to go live + p_view_channel = 0x00000000400, //!< allows guild members to view a channel, which includes reading messages in text channels and joining voice channels + p_send_messages = 0x00000000800, //!< allows for sending messages in a channel + p_send_tts_messages = 0x00000001000, //!< allows for sending of /tts messages + p_manage_messages = 0x00000002000, //!< allows for deletion of other users messages + p_embed_links = 0x00000004000, //!< links sent by users with this permission will be auto-embedded + p_attach_files = 0x00000008000, //!< allows for uploading images and files + p_read_message_history = 0x00000010000, //!< allows for reading of message history + p_mention_everyone = 0x00000020000, //!< allows for using the everyone and the here tag to notify users in a channel + p_use_external_emojis = 0x00000040000, //!< allows the usage of custom emojis from other servers + p_view_guild_insights = 0x00000080000, //!< allows for viewing guild insights + p_connect = 0x00000100000, //!< allows for joining of a voice channel + p_speak = 0x00000200000, //!< allows for speaking in a voice channel + p_mute_members = 0x00000400000, //!< allows for muting members in a voice channel + p_deafen_members = 0x00000800000, //!< allows for deafening of members in a voice channel + p_move_members = 0x00001000000, //!< allows for moving of members between voice channels + p_use_vad = 0x00002000000, //!< allows for using voice-activity-detection in a voice channel + p_change_nickname = 0x00004000000, //!< allows for modification of own nickname + p_manage_nicknames = 0x00008000000, //!< allows for modification of other users nicknames + p_manage_roles = 0x00010000000, //!< allows management and editing of roles + p_manage_webhooks = 0x00020000000, //!< allows management and editing of webhooks + p_manage_emojis_and_stickers = 0x00040000000, //!< allows management and editing of emojis and stickers + p_use_application_commands = 0x00080000000, //!< allows members to use application commands, including slash commands and context menus + p_request_to_speak = 0x00100000000, //!< allows for requesting to speak in stage channels. (Discord: This permission is under active development and may be changed or removed.) + p_manage_events = 0x00200000000, //!< allows for management (creation, updating, deleting, starting) of scheduled events + p_manage_threads = 0x00400000000, //!< allows for deleting and archiving threads, and viewing all private threads + p_create_public_threads = 0x00800000000, //!< allows for creating public and announcement threads + p_create_private_threads = 0x01000000000, //!< allows for creating private threads + p_use_external_stickers = 0x02000000000, //!< allows the usage of custom stickers from other servers + p_send_messages_in_threads = 0x04000000000, //!< allows for sending messages in threads + p_use_embedded_activities = 0x08000000000, //!< allows for using activities (applications with the EMBEDDED flag) in a voice channel + p_moderate_members = 0x10000000000, //!< allows for timing out users to prevent them from sending or reacting to messages in chat and threads, and from speaking in voice and stage channels +}; + +/** + * @brief Represents the various discord permissions + * @deprecated Use dpp::permissions instead. + */ +using role_permissions = permissions; + +/** + * @brief Represents a permission bitmask (refer to enum dpp::permissions) which are hold in an uint64_t + */ +class DPP_EXPORT permission { +protected: + /** + * @brief The permission bitmask value + */ + uint64_t value; + +public: + /** + * @brief Construct a permission object + * @param value A permission bitmask + */ + permission(const uint64_t& value); + + /** + * @brief Construct a permission object + */ + permission(); + + /** + * @brief For acting like an integer + * @return The permission bitmask value + */ + operator uint64_t() const; + + /** + * @brief For acting like an integer + * @return A reference to the permission bitmask value + */ + operator uint64_t &(); + + /** + * @brief For building json + * @return The permission bitmask value as a string + */ + operator nlohmann::json() const; + + /** + * @brief Check for permission flags set. It uses the Bitwise AND operator + * @tparam T one or more uint64_t permission bits + * @param values The permissions (from dpp::permissions) to check for + * + * **Example:** + * + * ```cpp + * bool is_mod = permission.has(dpp::p_kick_members, dpp::p_ban_members); + * // Returns true if the permission bitmask contains p_kick_members and p_ban_members + * ``` + * + * @return bool True if it has all the given permissions + */ + template + bool has(T... values) const { + return (value & (0 | ... | values)) == (0 | ... | values); + } + + /** + * @brief Add a permission with the Bitwise OR operation + * @tparam T one or more uint64_t permission bits + * @param values The permissions (from dpp::permissions) to add + * + * **Example:** + * + * ```cpp + * permission.add(dpp::p_view_channel, dpp::p_send_messages); + * // Adds p_view_channel and p_send_messages to the permission bitmask + * ``` + * + * @return permission& reference to self for chaining + */ + template + typename std::enable_if<(std::is_convertible::value && ...), permission&>::type + add(T... values) { + value |= (0 | ... | values); + return *this; + } + + /** + * @brief Assign a permission. This will reset the bitmask to the new value. + * @tparam T one or more uint64_t permission bits + * @param values The permissions (from dpp::permissions) to set + * + * **Example:** + * + * ```cpp + * permission.set(dpp::p_view_channel, dpp::p_send_messages); + * ``` + * + * @return permission& reference to self for chaining + */ + template + typename std::enable_if<(std::is_convertible::value && ...), permission&>::type + set(T... values) { + value = (0 | ... | values); + return *this; + } + + /** + * @brief Remove a permission with the Bitwise NOT operation + * @tparam T one or more uint64_t permission bits + * @param values The permissions (from dpp::permissions) to remove + * + * **Example:** + * + * ```cpp + * permission.remove(dpp::p_view_channel, dpp::p_send_messages); + * // Removes p_view_channel and p_send_messages permission + * ``` + * + * @return permission& reference to self for chaining + */ + template + typename std::enable_if<(std::is_convertible::value && ...), permission&>::type + remove(T... values) { + value &= ~(0 | ... | values); + return *this; + } +}; + +} diff --git a/3rdParty/dpp/presence.h b/3rdParty/dpp/presence.h index e018f92ecb..23c389420f 100644 --- a/3rdParty/dpp/presence.h +++ b/3rdParty/dpp/presence.h @@ -1,384 +1,384 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Presence flags bitmask - */ -enum presence_flags { - /// Desktop: Online - p_desktop_online = 0b00000001, - /// Desktop: DND - p_desktop_dnd = 0b00000010, - /// Desktop: Idle - p_desktop_idle = 0b00000011, - /// Web: Online - p_web_online = 0b00000100, - /// Web: DND - p_web_dnd = 0b00001000, - /// Web: Idle - p_web_idle = 0b00001100, - /// Mobile: Online - p_mobile_online = 0b00010000, - /// Mobile: DND - p_mobile_dnd = 0b00100000, - /// Mobile: Idle - p_mobile_idle = 0b00110000, - /// General: Online - p_status_online = 0b01000000, - /// General: DND - p_status_dnd = 0b10000000, - /// General: Idle - p_status_idle = 0b11000000 -}; - -/** - * @brief Online presence status values - */ -enum presence_status : uint8_t { - /// Offline - ps_offline = 0, - /// Online - ps_online = 1, - /// DND - ps_dnd = 2, - /// Idle - ps_idle = 3 -}; - -/** - * @brief Bit shift for desktop status - */ -#define PF_SHIFT_DESKTOP 0 -/** Bit shift for web status */ -#define PF_SHIFT_WEB 2 -/** Bit shift for mobile status */ -#define PF_SHIFT_MOBILE 4 -/** Bit shift for main status */ -#define PF_SHIFT_MAIN 6 -/** Bit mask for status */ -#define PF_STATUS_MASK 0b00000011 -/** Bit mask for clearing desktop status */ -#define PF_CLEAR_DESKTOP 0b11111100 -/** Bit mask for clearing web status */ -#define PF_CLEAR_WEB 0b11110011 -/** Bit mask for clearing mobile status */ -#define PF_CLEAR_MOBILE 0b11001111 -/** Bit mask for clearing main status */ -#define PF_CLEAR_STATUS 0b00111111 - -/** - * @brief Game types - */ -enum activity_type : uint8_t { - /// "Playing ..." - at_game = 0, - /// "Streaming ..." - at_streaming = 1, - /// "Listening to..." - at_listening = 2, - /// "Watching..." - at_watching = 3, - /// "Emoji..." - at_custom = 4, - /// "Competing in..." - at_competing = 5 -}; - -/** - * @brief Activity types for rich presence - */ -enum activity_flags { - /// In an instance - af_instance = 0b000000001, - /// Joining - af_join = 0b000000010, - /// Spectating - af_spectate = 0b000000100, - /// Sending join request - af_join_request = 0b000001000, - /// Synchronising - af_sync = 0b000010000, - /// Playing - af_play = 0b000100000, - /// Party privacy friends - af_party_privacy_friends = 0b001000000, - /// Party privacy voice channel - af_party_privacy_voice_channel = 0b010000000, - /// Embedded - af_embedded = 0b100000000 -}; - -/** - * @brief An activity button is a custom button shown in the rich presence. Can be to join a game or whatever - */ -struct DPP_EXPORT activity_button { -public: - /** The text shown on the button (1-32 characters) - */ - std::string label; - /** The url opened when clicking the button (1-512 characters). It's may be empty - * - * @note Bots cannot access the activity button URLs. - */ - std::string url; - - /** Constructor */ - activity_button() = default; -}; - -/** - * @brief An activity asset are the images and the hover text displayed in the rich presence - */ -struct DPP_EXPORT activity_assets { -public: - /** The large asset image which usually contain snowflake ID or prefixed image ID - */ - std::string large_image; - /** Text displayed when hovering over the large image of the activity - */ - std::string large_text; - /** The small asset image which usually contain snowflake ID or prefixed image ID - */ - std::string small_image; - /** Text displayed when hovering over the small image of the activity - */ - std::string small_text; - - /** Constructor */ - activity_assets() = default; -}; - -/** - * @brief Secrets for Rich Presence joining and spectating - */ -struct DPP_EXPORT activity_secrets { -public: - /** The secret for joining a party - */ - std::string join; - /** The secret for spectating a game - */ - std::string spectate; - /** The secret for a specific instanced match - */ - std::string match; - - /** Constructor */ - activity_secrets() = default; -}; - -/** - * @brief Information for the current party of the player - */ -struct DPP_EXPORT activity_party { -public: - /** The ID of the party - */ - snowflake id; - /** The party's current size. Used to show the party's current size - */ - int32_t current_size; - /** The party's maximum size. Used to show the party's maximum size - */ - int32_t maximum_size; - - /** Constructor */ - activity_party(); -}; - -/** - * @brief An activity is a representation of what a user is doing. It might be a game, or a website, or a movie. Whatever. - */ -class DPP_EXPORT activity { -public: - /** Name of activity - * e.g. "Fortnite" - */ - std::string name; - /** State of activity or the custom user status. - * e.g. "Waiting in lobby" - */ - std::string state; - /** What the player is currently doing - */ - std::string details; - /** Images for the presence and their hover texts - */ - activity_assets assets; - /** URL. - * Only applicable for certain sites such a YouTube - * Alias: details - */ - std::string url; - /** The custom buttons shown in the Rich Presence (max 2) - */ - std::vector buttons; - /** The emoji used for the custom status - */ - dpp::emoji emoji; - /** Information of the current party if there is one - */ - activity_party party; - /** Secrets for rich presence joining and spectating - */ - activity_secrets secrets; - /** Activity type - */ - activity_type type; - /** Time activity was created - */ - time_t created_at; - /** Start time. e.g. when game was started - */ - time_t start; - /** End time, e.g. for songs on spotify - */ - time_t end; - /** Creating application (e.g. a linked account on the user's client) - */ - snowflake application_id; - /** Flags bitmask from dpp::activity_flags - */ - uint8_t flags; - /** Whether or not the activity is an instanced game session - */ - bool is_instance; - - /** - * @brief Get the assets large image url if they have one, otherwise returns an empty string. In case of prefixed image IDs (mp:{image_id}) it returns an empty string. - * - * @param size The size of the image in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized image is returned. - * @return image url or empty string - */ - std::string get_large_asset_url(uint16_t size = 0) const; - - /** - * @brief Get the assets small image url if they have one, otherwise returns an empty string. In case of prefixed image IDs (mp:{image_id}) it returns an empty string. - * - * @param size The size of the image in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized image is returned. - * @return image url or empty string - */ - std::string get_small_asset_url(uint16_t size = 0) const; - - activity(); - - /** - * @brief Construct a new activity - * - * @param typ activity type - * @param nam Name of the activity - * @param stat State of the activity - * @param url_ url of the activity, only works for certain sites, such as YouTube - */ - activity(const activity_type typ, const std::string& nam, const std::string& stat, const std::string& url_); -}; - -/** - * @brief Represents user presence, e.g. what game they are playing and if they are online - */ -class DPP_EXPORT presence : public json_interface { -public: - /** The user the presence applies to */ - snowflake user_id; - - /** Guild ID. Apparently, Discord supports this internally but the client doesn't... */ - snowflake guild_id; - - /** Flags bitmask containing dpp::presence_flags */ - uint8_t flags; - - /** List of activities */ - std::vector activities; - - /** Constructor */ - presence(); - - /** - * @brief Construct a new presence object with some parameters for sending to a websocket - * - * @param status Status of the activity - * @param type Type of activity - * @param activity_description Description of the activity - */ - presence(presence_status status, activity_type type, const std::string& activity_description); - - /** - * @brief Construct a new presence object with some parameters for sending to a websocket. - * - * @param status Status of the activity - * @param a Activity itself - */ - presence(presence_status status, const activity& a); - - /** Destructor */ - ~presence(); - - /** Fill this object from json. - * @param j JSON object to fill from - * @return A reference to self - */ - presence& fill_from_json(nlohmann::json* j); - - /** Build JSON from this object. - * - * Note: This excludes any part of the presence object that are not valid for websockets and bots, - * and includes websocket opcode 3. You will not get what you expect if you call this on a user's - * presence received from on_presence_update or on_guild_create! - * - * @param with_id Add ID to output - * @return The JSON text of the presence - */ - virtual std::string build_json(bool with_id = false) const; - - /** The users status on desktop - * @return The user's status on desktop - */ - presence_status desktop_status() const; - - /** The user's status on web - * @return The user's status on web - */ - presence_status web_status() const; - - /** The user's status on mobile - * @return The user's status on mobile - */ - presence_status mobile_status() const; - - /** The user's status as shown to other users - * @return The user's status as shown to other users - */ - presence_status status() const; -}; - -/** A container of presences */ -typedef std::unordered_map presence_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Presence flags bitmask + */ +enum presence_flags { + /// Desktop: Online + p_desktop_online = 0b00000001, + /// Desktop: DND + p_desktop_dnd = 0b00000010, + /// Desktop: Idle + p_desktop_idle = 0b00000011, + /// Web: Online + p_web_online = 0b00000100, + /// Web: DND + p_web_dnd = 0b00001000, + /// Web: Idle + p_web_idle = 0b00001100, + /// Mobile: Online + p_mobile_online = 0b00010000, + /// Mobile: DND + p_mobile_dnd = 0b00100000, + /// Mobile: Idle + p_mobile_idle = 0b00110000, + /// General: Online + p_status_online = 0b01000000, + /// General: DND + p_status_dnd = 0b10000000, + /// General: Idle + p_status_idle = 0b11000000 +}; + +/** + * @brief Online presence status values + */ +enum presence_status : uint8_t { + /// Offline + ps_offline = 0, + /// Online + ps_online = 1, + /// DND + ps_dnd = 2, + /// Idle + ps_idle = 3 +}; + +/** + * @brief Bit shift for desktop status + */ +#define PF_SHIFT_DESKTOP 0 +/** Bit shift for web status */ +#define PF_SHIFT_WEB 2 +/** Bit shift for mobile status */ +#define PF_SHIFT_MOBILE 4 +/** Bit shift for main status */ +#define PF_SHIFT_MAIN 6 +/** Bit mask for status */ +#define PF_STATUS_MASK 0b00000011 +/** Bit mask for clearing desktop status */ +#define PF_CLEAR_DESKTOP 0b11111100 +/** Bit mask for clearing web status */ +#define PF_CLEAR_WEB 0b11110011 +/** Bit mask for clearing mobile status */ +#define PF_CLEAR_MOBILE 0b11001111 +/** Bit mask for clearing main status */ +#define PF_CLEAR_STATUS 0b00111111 + +/** + * @brief Game types + */ +enum activity_type : uint8_t { + /// "Playing ..." + at_game = 0, + /// "Streaming ..." + at_streaming = 1, + /// "Listening to..." + at_listening = 2, + /// "Watching..." + at_watching = 3, + /// "Emoji..." + at_custom = 4, + /// "Competing in..." + at_competing = 5 +}; + +/** + * @brief Activity types for rich presence + */ +enum activity_flags { + /// In an instance + af_instance = 0b000000001, + /// Joining + af_join = 0b000000010, + /// Spectating + af_spectate = 0b000000100, + /// Sending join request + af_join_request = 0b000001000, + /// Synchronising + af_sync = 0b000010000, + /// Playing + af_play = 0b000100000, + /// Party privacy friends + af_party_privacy_friends = 0b001000000, + /// Party privacy voice channel + af_party_privacy_voice_channel = 0b010000000, + /// Embedded + af_embedded = 0b100000000 +}; + +/** + * @brief An activity button is a custom button shown in the rich presence. Can be to join a game or whatever + */ +struct DPP_EXPORT activity_button { +public: + /** The text shown on the button (1-32 characters) + */ + std::string label; + /** The url opened when clicking the button (1-512 characters). It's may be empty + * + * @note Bots cannot access the activity button URLs. + */ + std::string url; + + /** Constructor */ + activity_button() = default; +}; + +/** + * @brief An activity asset are the images and the hover text displayed in the rich presence + */ +struct DPP_EXPORT activity_assets { +public: + /** The large asset image which usually contain snowflake ID or prefixed image ID + */ + std::string large_image; + /** Text displayed when hovering over the large image of the activity + */ + std::string large_text; + /** The small asset image which usually contain snowflake ID or prefixed image ID + */ + std::string small_image; + /** Text displayed when hovering over the small image of the activity + */ + std::string small_text; + + /** Constructor */ + activity_assets() = default; +}; + +/** + * @brief Secrets for Rich Presence joining and spectating + */ +struct DPP_EXPORT activity_secrets { +public: + /** The secret for joining a party + */ + std::string join; + /** The secret for spectating a game + */ + std::string spectate; + /** The secret for a specific instanced match + */ + std::string match; + + /** Constructor */ + activity_secrets() = default; +}; + +/** + * @brief Information for the current party of the player + */ +struct DPP_EXPORT activity_party { +public: + /** The ID of the party + */ + snowflake id; + /** The party's current size. Used to show the party's current size + */ + int32_t current_size; + /** The party's maximum size. Used to show the party's maximum size + */ + int32_t maximum_size; + + /** Constructor */ + activity_party(); +}; + +/** + * @brief An activity is a representation of what a user is doing. It might be a game, or a website, or a movie. Whatever. + */ +class DPP_EXPORT activity { +public: + /** Name of activity + * e.g. "Fortnite" + */ + std::string name; + /** State of activity or the custom user status. + * e.g. "Waiting in lobby" + */ + std::string state; + /** What the player is currently doing + */ + std::string details; + /** Images for the presence and their hover texts + */ + activity_assets assets; + /** URL. + * Only applicable for certain sites such a YouTube + * Alias: details + */ + std::string url; + /** The custom buttons shown in the Rich Presence (max 2) + */ + std::vector buttons; + /** The emoji used for the custom status + */ + dpp::emoji emoji; + /** Information of the current party if there is one + */ + activity_party party; + /** Secrets for rich presence joining and spectating + */ + activity_secrets secrets; + /** Activity type + */ + activity_type type; + /** Time activity was created + */ + time_t created_at; + /** Start time. e.g. when game was started + */ + time_t start; + /** End time, e.g. for songs on spotify + */ + time_t end; + /** Creating application (e.g. a linked account on the user's client) + */ + snowflake application_id; + /** Flags bitmask from dpp::activity_flags + */ + uint8_t flags; + /** Whether or not the activity is an instanced game session + */ + bool is_instance; + + /** + * @brief Get the assets large image url if they have one, otherwise returns an empty string. In case of prefixed image IDs (mp:{image_id}) it returns an empty string. + * + * @param size The size of the image in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized image is returned. + * @return image url or empty string + */ + std::string get_large_asset_url(uint16_t size = 0) const; + + /** + * @brief Get the assets small image url if they have one, otherwise returns an empty string. In case of prefixed image IDs (mp:{image_id}) it returns an empty string. + * + * @param size The size of the image in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized image is returned. + * @return image url or empty string + */ + std::string get_small_asset_url(uint16_t size = 0) const; + + activity(); + + /** + * @brief Construct a new activity + * + * @param typ activity type + * @param nam Name of the activity + * @param stat State of the activity + * @param url_ url of the activity, only works for certain sites, such as YouTube + */ + activity(const activity_type typ, const std::string& nam, const std::string& stat, const std::string& url_); +}; + +/** + * @brief Represents user presence, e.g. what game they are playing and if they are online + */ +class DPP_EXPORT presence : public json_interface { +public: + /** The user the presence applies to */ + snowflake user_id; + + /** Guild ID. Apparently, Discord supports this internally but the client doesn't... */ + snowflake guild_id; + + /** Flags bitmask containing dpp::presence_flags */ + uint8_t flags; + + /** List of activities */ + std::vector activities; + + /** Constructor */ + presence(); + + /** + * @brief Construct a new presence object with some parameters for sending to a websocket + * + * @param status Status of the activity + * @param type Type of activity + * @param activity_description Description of the activity + */ + presence(presence_status status, activity_type type, const std::string& activity_description); + + /** + * @brief Construct a new presence object with some parameters for sending to a websocket. + * + * @param status Status of the activity + * @param a Activity itself + */ + presence(presence_status status, const activity& a); + + /** Destructor */ + ~presence(); + + /** Fill this object from json. + * @param j JSON object to fill from + * @return A reference to self + */ + presence& fill_from_json(nlohmann::json* j); + + /** Build JSON from this object. + * + * Note: This excludes any part of the presence object that are not valid for websockets and bots, + * and includes websocket opcode 3. You will not get what you expect if you call this on a user's + * presence received from on_presence_update or on_guild_create! + * + * @param with_id Add ID to output + * @return The JSON text of the presence + */ + virtual std::string build_json(bool with_id = false) const; + + /** The users status on desktop + * @return The user's status on desktop + */ + presence_status desktop_status() const; + + /** The user's status on web + * @return The user's status on web + */ + presence_status web_status() const; + + /** The user's status on mobile + * @return The user's status on mobile + */ + presence_status mobile_status() const; + + /** The user's status as shown to other users + * @return The user's status as shown to other users + */ + presence_status status() const; +}; + +/** A container of presences */ +typedef std::unordered_map presence_map; + +}; diff --git a/3rdParty/dpp/prune.h b/3rdParty/dpp/prune.h index fe3d843908..23f335fc25 100644 --- a/3rdParty/dpp/prune.h +++ b/3rdParty/dpp/prune.h @@ -1,63 +1,63 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Defines a request to count prunable users, or start a prune operation - */ -struct DPP_EXPORT prune : public json_interface { - /** - * Destroy this prune object - */ - virtual ~prune() = default; - - /** Number of days to include in the prune - */ - uint32_t days = 0; - /** Roles to include in the prune (empty to include everyone) - */ - std::vector include_roles; - /** True if the count of pruneable users should be returned - * (discord recommend not using this on big guilds) - */ - bool compute_prune_count; - - /** Fill this object from json. - * @param j JSON object to fill from - * @return A reference to self - */ - prune& fill_from_json(nlohmann::json* j); - - /** Build JSON from this object. - * @param with_prune_count True if the prune count boolean is to be set in the built JSON - * @return The JSON text of the prune object - */ - virtual std::string build_json(bool with_prune_count = false) const; - -}; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Defines a request to count prunable users, or start a prune operation + */ +struct DPP_EXPORT prune : public json_interface { + /** + * Destroy this prune object + */ + virtual ~prune() = default; + + /** Number of days to include in the prune + */ + uint32_t days = 0; + /** Roles to include in the prune (empty to include everyone) + */ + std::vector include_roles; + /** True if the count of pruneable users should be returned + * (discord recommend not using this on big guilds) + */ + bool compute_prune_count; + + /** Fill this object from json. + * @param j JSON object to fill from + * @return A reference to self + */ + prune& fill_from_json(nlohmann::json* j); + + /** Build JSON from this object. + * @param with_prune_count True if the prune count boolean is to be set in the built JSON + * @return The JSON text of the prune object + */ + virtual std::string build_json(bool with_prune_count = false) const; + +}; + +}; diff --git a/3rdParty/dpp/queues.h b/3rdParty/dpp/queues.h index e3e5a650a4..ae5ee6e4c3 100644 --- a/3rdParty/dpp/queues.h +++ b/3rdParty/dpp/queues.h @@ -1,457 +1,457 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Error values. Most of these are currently unused in https_client. - */ -enum http_error { - /// Request successful - h_success = 0, - /// Status unknown - h_unknown, - /// Connect failed - h_connection, - /// Invalid local ip address - h_bind_ip_address, - /// Read error - h_read, - /// Write error - h_write, - /// Too many 30x redirects - h_exceed_redirect_count, - /// Request cancelled - h_canceled, - /// SSL connection error - h_ssl_connection, - /// SSL cert loading error - h_ssl_loading_certs, - /// SSL server verification error - h_ssl_server_verification, - /// Unsupported multipart boundary characters - h_unsupported_multipart_boundary_chars, - /// Compression error - h_compression, -}; - -/** - * @brief The result of any HTTP request. Contains the headers, vital - * rate limit figures, and returned request body. - */ -struct DPP_EXPORT http_request_completion_t { - /** @brief HTTP headers of response */ - std::map headers; - /** @brief HTTP status, e.g. 200 = OK, 404 = Not found, 429 = Rate limited */ - uint16_t status = 0; - /** @brief Error status (e.g. if the request could not connect at all) */ - http_error error = h_success; - /** @brief Ratelimit bucket */ - std::string ratelimit_bucket; - /** @brief Ratelimit limit of requests */ - uint64_t ratelimit_limit = 0; - /** @brief Ratelimit remaining requests */ - uint64_t ratelimit_remaining = 0; - /** @brief Ratelimit reset after (seconds) */ - uint64_t ratelimit_reset_after = 0; - /** @brief Ratelimit retry after (seconds) */ - uint64_t ratelimit_retry_after = 0; - /** @brief True if this request has caused us to be globally rate limited */ - bool ratelimit_global = false; - /** @brief Reply body */ - std::string body; - /** @brief Ping latency */ - double latency; -}; - -/** - * @brief Results of HTTP requests are called back to these std::function types. - * @note Returned http_completion_events are called ASYNCHRONOUSLY in your - * code which means they execute in a separate thread. The completion events - * arrive in order. - */ -typedef std::function http_completion_event; - -/** - * @brief Various types of http method supported by the Discord API - */ -enum http_method { - /// GET - m_get, - /// POST - m_post, - /// PUT - m_put, - /// PATCH - m_patch, - /// DELETE - m_delete -}; - -/** - * @brief A HTTP request. - * - * You should instantiate one of these objects via its constructor, - * and pass a pointer to it into an instance of request_queue. Although you can - * directly call the run() method of the object and it will make a HTTP call, be - * aware that if you do this, it will be a **BLOCKING call** (not asynchronous) and - * will not respect rate limits, as both of these functions are managed by the - * request_queue class. - */ -class DPP_EXPORT http_request { - /** @brief Completion callback */ - http_completion_event complete_handler; - /** @brief True if request has been made */ - bool completed; - /** @brief True for requests that are not going to discord (rate limits code skipped) */ - bool non_discord; -public: - /** @brief Endpoint name e.g. /api/users */ - std::string endpoint; - /** @brief Major and minor parameters */ - std::string parameters; - /** @brief Postdata for POST and PUT */ - std::string postdata; - /** @brief HTTP method for request */ - http_method method; - /** @brief Audit log reason for Discord requests, if non-empty */ - std::string reason; - /** @brief Upload file name (server side) */ - std::vector file_name; - /** @brief Upload file contents (binary) */ - std::vector file_content; - /** @brief Request mime type */ - std::string mimetype; - /** @brief Request headers (non-discord requests only) */ - std::multimap req_headers; - /** @brief Waiting for rate limit to expire */ - bool waiting; - - /** - * @brief Constructor. When constructing one of these objects it should be passed to request_queue::post_request(). - * @param _endpoint The API endpoint, e.g. /api/guilds - * @param _parameters Major and minor parameters for the endpoint e.g. a user id or guild id - * @param completion completion event to call when done - * @param _postdata Data to send in POST and PUT requests - * @param method The HTTP method to use from dpp::http_method - * @param audit_reason Audit log reason to send, empty to send none - * @param filename The filename (server side) of any uploaded file - * @param filecontent The binary content of any uploaded file for the request - */ - http_request(const std::string &_endpoint, const std::string &_parameters, http_completion_event completion, const std::string &_postdata = "", http_method method = m_get, const std::string &audit_reason = "", const std::string &filename = "", const std::string &filecontent = ""); - - /** - * @brief Constructor. When constructing one of these objects it should be passed to request_queue::post_request(). - * @param _endpoint The API endpoint, e.g. /api/guilds - * @param _parameters Major and minor parameters for the endpoint e.g. a user id or guild id - * @param completion completion event to call when done - * @param _postdata Data to send in POST and PUT requests - * @param method The HTTP method to use from dpp::http_method - * @param audit_reason Audit log reason to send, empty to send none - * @param filename The filename (server side) of any uploaded file - * @param filecontent The binary content of any uploaded file for the request - */ - http_request(const std::string &_endpoint, const std::string &_parameters, http_completion_event completion, const std::string &_postdata = "", http_method method = m_get, const std::string &audit_reason = "", const std::vector &filename = {}, const std::vector &filecontent = {}); - - /** - * @brief Constructor. When constructing one of these objects it should be passed to request_queue::post_request(). - * @param _url Raw HTTP url - * @param completion completion event to call when done - * @param method The HTTP method to use from dpp::http_method - * @param _postdata Data to send in POST and PUT requests - * @param _mimetype POST data mime type - * @param _headers HTTP headers to send - */ - http_request(const std::string &_url, http_completion_event completion, http_method method = m_get, const std::string &_postdata = "", const std::string &_mimetype = "text/plain", const std::multimap &_headers = {}); - - /** - * @brief Destroy the http request object - */ - ~http_request(); - - /** - * @brief Call the completion callback, if the request is complete. - * @param c callback to call - */ - void complete(const http_request_completion_t &c); - - /** - * @brief Execute the HTTP request and mark the request complete. - * @param owner creating cluster - */ - http_request_completion_t run(class cluster* owner); - - /** @brief Returns true if the request is complete */ - bool is_completed(); -}; - -/** - * @brief A rate limit bucket. The library builds one of these for - * each endpoint. - */ -struct DPP_EXPORT bucket_t { - /** @brief Request limit */ - uint64_t limit; - /** @brief Requests remaining */ - uint64_t remaining; - /** @brief Ratelimit of this bucket resets after this many seconds */ - uint64_t reset_after; - /** @brief Ratelimit of this bucket can be retried after this many seconds */ - uint64_t retry_after; - /** @brief Timestamp this buckets counters were updated */ - time_t timestamp; -}; - - -/** - * @brief Represents a thread in the thread pool handling requests to HTTP(S) servers. - * There are several of these, the total defined by a constant in queues.cpp, and each - * one will always receive requests for the same rate limit bucket based on its endpoint - * portion of the url. This makes rate limit handling reliable and easy to manage. - * Each of these also has its own mutex, so that requests are less likely to block while - * waiting for internal containers to be usable. - */ -class DPP_EXPORT in_thread { -private: - /** - * @brief True if ending - */ - bool terminating; - - /** - * @brief Request queue that owns this in_thread - */ - class request_queue* requests; - - /** - * @brief The cluster that owns this in_thread - */ - class cluster* creator; - - /** - * @brief Inbound queue mutex thread safety - */ - std::shared_mutex in_mutex; - - /** - * @brief Inbound queue thread - */ - std::thread* in_thr; - - /** - * @brief Inbound queue condition, signalled when there are requests to fulfill - */ - std::condition_variable in_ready; - - /** - * @brief Ratelimit bucket counters - */ - std::map buckets; - - /** - * @brief Queue of requests to be made - */ - std::map> requests_in; - - /** - * @brief Inbound queue thread loop - * @param index Thread index - */ - void in_loop(uint32_t index); -public: - /** - * @brief Construct a new in thread object - * - * @param owner Owning cluster - * @param req_q Owning request queue - * @param index Thread index number - */ - in_thread(class cluster* owner, class request_queue* req_q, uint32_t index); - - /** - * @brief Destroy the in thread object - * This will end the thread that is owned by this object by joining it. - */ - ~in_thread(); - - /** - * @brief Post a http_request to this thread. - * - * @param req http_request to post. The pointer will be freed when it has - * been executed. - */ - void post_request(http_request* req); -}; - -/** - * @brief The request_queue class manages rate limits and marshalls HTTP requests that have - * been built as http_request objects. - * - * It ensures asynchronous delivery of events and queueing of requests. - * - * It will spawn two threads, one to make outbound HTTP requests and push the returned - * results into a queue, and the second to call the callback methods with these results. - * They are separated so that if the user decides to take a long time processing a reply - * in their callback it won't affect when other requests are sent, and if a HTTP request - * takes a long time due to latency, it won't hold up user processing. - * - * There are usually two request_queue objects in each dpp::cluster, one of which is used - * internally for the various REST methods to Discord such as sending messages, and the other - * used to support user REST calls via dpp::cluster::request(). - */ -class DPP_EXPORT request_queue { -protected: - /** - * @brief Required so in_thread can access these member variables - */ - friend class in_thread; - - /** - * @brief The cluster that owns this request_queue - */ - class cluster* creator; - - /** - * @brief Outbound queue mutex thread safety - */ - std::shared_mutex out_mutex; - - /** - * @brief Outbound queue thread - * Note that although there are many 'in queues', which handle the HTTP requests, - * there is only ever one 'out queue' which dispatches the results to the caller. - * This is to simplify thread management in bots that use the library, as less mutexing - * and thread safety boilerplate is required. - */ - std::thread* out_thread; - - /** - * @brief Outbound queue condition, signalled when there are requests completed to call callbacks for - */ - std::condition_variable out_ready; - - /** - * @brief Completed requests queue - */ - std::queue> responses_out; - - /** - * @brief A vector of inbound request threads forming a pool. - * There are a set number of these defined by a constant in queues.cpp. A request is always placed - * on the same element in this vector, based upon its url, so that two conditions are satisfied: - * 1) Any requests for the same ratelimit bucket are handled by the same thread in the pool so that - * they do not create unnecessary 429 errors, - * 2) Requests for different endpoints go into different buckets, so that they may be requested in parallel - * A global ratelimit event pauses all threads in the pool. These are few and far between. - */ - std::vector requests_in; - - /** - * @brief Completed requests to delete - */ - std::multimap> responses_to_delete; - - /** - * @brief Set to true if the threads should terminate - */ - bool terminating; - - /** - * @brief True if globally rate limited - makes the entire request thread wait - */ - bool globally_ratelimited; - - /** - * @brief How many seconds we are globally rate limited for, if globally_ratelimited is true - */ - uint64_t globally_limited_for; - - /** - * @brief Number of request threads in the thread pool - */ - uint32_t in_thread_pool_size; - - /** - * @brief Outbound queue thread loop - */ - void out_loop(); -public: - - /** - * @brief constructor - * @param owner The creating cluster. - * @param request_threads The number of http request threads to allocate to the threadpool. - * By default eight threads are allocated. - * Side effects: Creates threads for the queue - */ - request_queue(class cluster* owner, uint32_t request_threads = 8); - - /** - * @brief Add more request threads to the library at runtime. - * @note You should do this at a quiet time when there are few requests happening. - * This will reorganise the hashing used to place requests into the thread pool so if you do - * this while the bot is busy there is a small chance of receiving "429 rate limited" errors. - * @param request_threads Number of threads to add. It is not possible to scale down at runtime. - * @return reference to self - */ - request_queue& add_request_threads(uint32_t request_threads); - - /** - * @brief Get the request thread count - * @return uint32_t number of request threads that are active - */ - uint32_t get_request_thread_count() const; - - /** - * @brief Destroy the request queue object. - * Side effects: Joins and deletes queue threads - */ - ~request_queue(); - - /** - * @brief Put a http_request into the request queue. You should ALWAYS "new" an object - * to pass to here -- don't submit an object that's on the stack! - * @note Will use a simple hash function to determine which of the 'in queues' to place - * this request onto. - * @param req request to add - * @return reference to self - */ - request_queue& post_request(http_request *req); - - /** - * @brief Returns true if the bot is currently globally rate limited - * @return true if globally rate limited - */ - bool is_globally_ratelimited() const; -}; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Error values. Most of these are currently unused in https_client. + */ +enum http_error { + /// Request successful + h_success = 0, + /// Status unknown + h_unknown, + /// Connect failed + h_connection, + /// Invalid local ip address + h_bind_ip_address, + /// Read error + h_read, + /// Write error + h_write, + /// Too many 30x redirects + h_exceed_redirect_count, + /// Request cancelled + h_canceled, + /// SSL connection error + h_ssl_connection, + /// SSL cert loading error + h_ssl_loading_certs, + /// SSL server verification error + h_ssl_server_verification, + /// Unsupported multipart boundary characters + h_unsupported_multipart_boundary_chars, + /// Compression error + h_compression, +}; + +/** + * @brief The result of any HTTP request. Contains the headers, vital + * rate limit figures, and returned request body. + */ +struct DPP_EXPORT http_request_completion_t { + /** @brief HTTP headers of response */ + std::map headers; + /** @brief HTTP status, e.g. 200 = OK, 404 = Not found, 429 = Rate limited */ + uint16_t status = 0; + /** @brief Error status (e.g. if the request could not connect at all) */ + http_error error = h_success; + /** @brief Ratelimit bucket */ + std::string ratelimit_bucket; + /** @brief Ratelimit limit of requests */ + uint64_t ratelimit_limit = 0; + /** @brief Ratelimit remaining requests */ + uint64_t ratelimit_remaining = 0; + /** @brief Ratelimit reset after (seconds) */ + uint64_t ratelimit_reset_after = 0; + /** @brief Ratelimit retry after (seconds) */ + uint64_t ratelimit_retry_after = 0; + /** @brief True if this request has caused us to be globally rate limited */ + bool ratelimit_global = false; + /** @brief Reply body */ + std::string body; + /** @brief Ping latency */ + double latency; +}; + +/** + * @brief Results of HTTP requests are called back to these std::function types. + * @note Returned http_completion_events are called ASYNCHRONOUSLY in your + * code which means they execute in a separate thread. The completion events + * arrive in order. + */ +typedef std::function http_completion_event; + +/** + * @brief Various types of http method supported by the Discord API + */ +enum http_method { + /// GET + m_get, + /// POST + m_post, + /// PUT + m_put, + /// PATCH + m_patch, + /// DELETE + m_delete +}; + +/** + * @brief A HTTP request. + * + * You should instantiate one of these objects via its constructor, + * and pass a pointer to it into an instance of request_queue. Although you can + * directly call the run() method of the object and it will make a HTTP call, be + * aware that if you do this, it will be a **BLOCKING call** (not asynchronous) and + * will not respect rate limits, as both of these functions are managed by the + * request_queue class. + */ +class DPP_EXPORT http_request { + /** @brief Completion callback */ + http_completion_event complete_handler; + /** @brief True if request has been made */ + bool completed; + /** @brief True for requests that are not going to discord (rate limits code skipped) */ + bool non_discord; +public: + /** @brief Endpoint name e.g. /api/users */ + std::string endpoint; + /** @brief Major and minor parameters */ + std::string parameters; + /** @brief Postdata for POST and PUT */ + std::string postdata; + /** @brief HTTP method for request */ + http_method method; + /** @brief Audit log reason for Discord requests, if non-empty */ + std::string reason; + /** @brief Upload file name (server side) */ + std::vector file_name; + /** @brief Upload file contents (binary) */ + std::vector file_content; + /** @brief Request mime type */ + std::string mimetype; + /** @brief Request headers (non-discord requests only) */ + std::multimap req_headers; + /** @brief Waiting for rate limit to expire */ + bool waiting; + + /** + * @brief Constructor. When constructing one of these objects it should be passed to request_queue::post_request(). + * @param _endpoint The API endpoint, e.g. /api/guilds + * @param _parameters Major and minor parameters for the endpoint e.g. a user id or guild id + * @param completion completion event to call when done + * @param _postdata Data to send in POST and PUT requests + * @param method The HTTP method to use from dpp::http_method + * @param audit_reason Audit log reason to send, empty to send none + * @param filename The filename (server side) of any uploaded file + * @param filecontent The binary content of any uploaded file for the request + */ + http_request(const std::string &_endpoint, const std::string &_parameters, http_completion_event completion, const std::string &_postdata = "", http_method method = m_get, const std::string &audit_reason = "", const std::string &filename = "", const std::string &filecontent = ""); + + /** + * @brief Constructor. When constructing one of these objects it should be passed to request_queue::post_request(). + * @param _endpoint The API endpoint, e.g. /api/guilds + * @param _parameters Major and minor parameters for the endpoint e.g. a user id or guild id + * @param completion completion event to call when done + * @param _postdata Data to send in POST and PUT requests + * @param method The HTTP method to use from dpp::http_method + * @param audit_reason Audit log reason to send, empty to send none + * @param filename The filename (server side) of any uploaded file + * @param filecontent The binary content of any uploaded file for the request + */ + http_request(const std::string &_endpoint, const std::string &_parameters, http_completion_event completion, const std::string &_postdata = "", http_method method = m_get, const std::string &audit_reason = "", const std::vector &filename = {}, const std::vector &filecontent = {}); + + /** + * @brief Constructor. When constructing one of these objects it should be passed to request_queue::post_request(). + * @param _url Raw HTTP url + * @param completion completion event to call when done + * @param method The HTTP method to use from dpp::http_method + * @param _postdata Data to send in POST and PUT requests + * @param _mimetype POST data mime type + * @param _headers HTTP headers to send + */ + http_request(const std::string &_url, http_completion_event completion, http_method method = m_get, const std::string &_postdata = "", const std::string &_mimetype = "text/plain", const std::multimap &_headers = {}); + + /** + * @brief Destroy the http request object + */ + ~http_request(); + + /** + * @brief Call the completion callback, if the request is complete. + * @param c callback to call + */ + void complete(const http_request_completion_t &c); + + /** + * @brief Execute the HTTP request and mark the request complete. + * @param owner creating cluster + */ + http_request_completion_t run(class cluster* owner); + + /** @brief Returns true if the request is complete */ + bool is_completed(); +}; + +/** + * @brief A rate limit bucket. The library builds one of these for + * each endpoint. + */ +struct DPP_EXPORT bucket_t { + /** @brief Request limit */ + uint64_t limit; + /** @brief Requests remaining */ + uint64_t remaining; + /** @brief Ratelimit of this bucket resets after this many seconds */ + uint64_t reset_after; + /** @brief Ratelimit of this bucket can be retried after this many seconds */ + uint64_t retry_after; + /** @brief Timestamp this buckets counters were updated */ + time_t timestamp; +}; + + +/** + * @brief Represents a thread in the thread pool handling requests to HTTP(S) servers. + * There are several of these, the total defined by a constant in queues.cpp, and each + * one will always receive requests for the same rate limit bucket based on its endpoint + * portion of the url. This makes rate limit handling reliable and easy to manage. + * Each of these also has its own mutex, so that requests are less likely to block while + * waiting for internal containers to be usable. + */ +class DPP_EXPORT in_thread { +private: + /** + * @brief True if ending + */ + bool terminating; + + /** + * @brief Request queue that owns this in_thread + */ + class request_queue* requests; + + /** + * @brief The cluster that owns this in_thread + */ + class cluster* creator; + + /** + * @brief Inbound queue mutex thread safety + */ + std::shared_mutex in_mutex; + + /** + * @brief Inbound queue thread + */ + std::thread* in_thr; + + /** + * @brief Inbound queue condition, signalled when there are requests to fulfill + */ + std::condition_variable in_ready; + + /** + * @brief Ratelimit bucket counters + */ + std::map buckets; + + /** + * @brief Queue of requests to be made + */ + std::map> requests_in; + + /** + * @brief Inbound queue thread loop + * @param index Thread index + */ + void in_loop(uint32_t index); +public: + /** + * @brief Construct a new in thread object + * + * @param owner Owning cluster + * @param req_q Owning request queue + * @param index Thread index number + */ + in_thread(class cluster* owner, class request_queue* req_q, uint32_t index); + + /** + * @brief Destroy the in thread object + * This will end the thread that is owned by this object by joining it. + */ + ~in_thread(); + + /** + * @brief Post a http_request to this thread. + * + * @param req http_request to post. The pointer will be freed when it has + * been executed. + */ + void post_request(http_request* req); +}; + +/** + * @brief The request_queue class manages rate limits and marshalls HTTP requests that have + * been built as http_request objects. + * + * It ensures asynchronous delivery of events and queueing of requests. + * + * It will spawn two threads, one to make outbound HTTP requests and push the returned + * results into a queue, and the second to call the callback methods with these results. + * They are separated so that if the user decides to take a long time processing a reply + * in their callback it won't affect when other requests are sent, and if a HTTP request + * takes a long time due to latency, it won't hold up user processing. + * + * There are usually two request_queue objects in each dpp::cluster, one of which is used + * internally for the various REST methods to Discord such as sending messages, and the other + * used to support user REST calls via dpp::cluster::request(). + */ +class DPP_EXPORT request_queue { +protected: + /** + * @brief Required so in_thread can access these member variables + */ + friend class in_thread; + + /** + * @brief The cluster that owns this request_queue + */ + class cluster* creator; + + /** + * @brief Outbound queue mutex thread safety + */ + std::shared_mutex out_mutex; + + /** + * @brief Outbound queue thread + * Note that although there are many 'in queues', which handle the HTTP requests, + * there is only ever one 'out queue' which dispatches the results to the caller. + * This is to simplify thread management in bots that use the library, as less mutexing + * and thread safety boilerplate is required. + */ + std::thread* out_thread; + + /** + * @brief Outbound queue condition, signalled when there are requests completed to call callbacks for + */ + std::condition_variable out_ready; + + /** + * @brief Completed requests queue + */ + std::queue> responses_out; + + /** + * @brief A vector of inbound request threads forming a pool. + * There are a set number of these defined by a constant in queues.cpp. A request is always placed + * on the same element in this vector, based upon its url, so that two conditions are satisfied: + * 1) Any requests for the same ratelimit bucket are handled by the same thread in the pool so that + * they do not create unnecessary 429 errors, + * 2) Requests for different endpoints go into different buckets, so that they may be requested in parallel + * A global ratelimit event pauses all threads in the pool. These are few and far between. + */ + std::vector requests_in; + + /** + * @brief Completed requests to delete + */ + std::multimap> responses_to_delete; + + /** + * @brief Set to true if the threads should terminate + */ + bool terminating; + + /** + * @brief True if globally rate limited - makes the entire request thread wait + */ + bool globally_ratelimited; + + /** + * @brief How many seconds we are globally rate limited for, if globally_ratelimited is true + */ + uint64_t globally_limited_for; + + /** + * @brief Number of request threads in the thread pool + */ + uint32_t in_thread_pool_size; + + /** + * @brief Outbound queue thread loop + */ + void out_loop(); +public: + + /** + * @brief constructor + * @param owner The creating cluster. + * @param request_threads The number of http request threads to allocate to the threadpool. + * By default eight threads are allocated. + * Side effects: Creates threads for the queue + */ + request_queue(class cluster* owner, uint32_t request_threads = 8); + + /** + * @brief Add more request threads to the library at runtime. + * @note You should do this at a quiet time when there are few requests happening. + * This will reorganise the hashing used to place requests into the thread pool so if you do + * this while the bot is busy there is a small chance of receiving "429 rate limited" errors. + * @param request_threads Number of threads to add. It is not possible to scale down at runtime. + * @return reference to self + */ + request_queue& add_request_threads(uint32_t request_threads); + + /** + * @brief Get the request thread count + * @return uint32_t number of request threads that are active + */ + uint32_t get_request_thread_count() const; + + /** + * @brief Destroy the request queue object. + * Side effects: Joins and deletes queue threads + */ + ~request_queue(); + + /** + * @brief Put a http_request into the request queue. You should ALWAYS "new" an object + * to pass to here -- don't submit an object that's on the stack! + * @note Will use a simple hash function to determine which of the 'in queues' to place + * this request onto. + * @param req request to add + * @return reference to self + */ + request_queue& post_request(http_request *req); + + /** + * @brief Returns true if the bot is currently globally rate limited + * @return true if globally rate limited + */ + bool is_globally_ratelimited() const; +}; + +}; diff --git a/3rdParty/dpp/restrequest.h b/3rdParty/dpp/restrequest.h index f97f070684..74ca431f6e 100644 --- a/3rdParty/dpp/restrequest.h +++ b/3rdParty/dpp/restrequest.h @@ -1,205 +1,205 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2022 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Templated REST request helper to save on typing - * - * @tparam T type to return in lambda callback - * @param c calling cluster - * @param basepath base path for API call - * @param major major API function - * @param minor minor API function - * @param method HTTP method - * @param postdata Post data or empty string - * @param callback Callback lambda - */ -template inline void rest_request(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback) { - c->post_rest(basepath, major, minor, method, postdata, [c, callback](json &j, const http_request_completion_t& http) { - if (callback) { - callback(confirmation_callback_t(c, T().fill_from_json(&j), http)); - } - }); -}; - -/** - * @brief Templated REST request helper to save on typing (specialised for message) - * - * @tparam T type to return in lambda callback - * @param c calling cluster - * @param basepath base path for API call - * @param major major API function - * @param minor minor API function - * @param method HTTP method - * @param postdata Post data or empty string - * @param callback Callback lambda - */ -template<> inline void rest_request(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback) { - c->post_rest(basepath, major, minor, method, postdata, [c, callback](json &j, const http_request_completion_t& http) { - if (callback) { - callback(confirmation_callback_t(c, message(c).fill_from_json(&j), http)); - } - }); -}; - -/** - * @brief Templated REST request helper to save on typing (specialised for confirmation) - * - * @tparam T type to return in lambda callback - * @param c calling cluster - * @param basepath base path for API call - * @param major major API function - * @param minor minor API function - * @param method HTTP method - * @param postdata Post data or empty string - * @param callback Callback lambda - */ -template<> inline void rest_request(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback) { - c->post_rest(basepath, major, minor, method, postdata, [c, callback](json &j, const http_request_completion_t& http) { - if (callback) { - callback(confirmation_callback_t(c, confirmation(), http)); - } - }); -}; - -/** - * @brief Templated REST request helper to save on typing (for returned lists) - * - * @tparam T singular type to return in lambda callback - * @tparam T map type to return in lambda callback - * @param c calling cluster - * @param basepath base path for API call - * @param major major API function - * @param minor minor API function - * @param method HTTP method - * @param postdata Post data or empty string - * @param key Key name of elements in the json list - * @param callback Callback lambda - */ -template inline void rest_request_list(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback, const std::string& key = "id") { - c->post_rest(basepath, major, minor, method, postdata, [c, key, callback](json &j, const http_request_completion_t& http) { - std::unordered_map list; - confirmation_callback_t e(c, confirmation(), http); - if (!e.is_error()) { - for (auto & curr_item : j) { - list[snowflake_not_null(&curr_item, key.c_str())] = T().fill_from_json(&curr_item); - } - } - if (callback) { - callback(confirmation_callback_t(c, list, http)); - } - }); -} - -/** - * @brief Templated REST request helper to save on typing (for returned lists, specialised for invites) - * - * @tparam T singular type to return in lambda callback - * @tparam T map type to return in lambda callback - * @param c calling cluster - * @param basepath base path for API call - * @param major major API function - * @param minor minor API function - * @param method HTTP method - * @param postdata Post data or empty string - * @param key Key name of elements in the json list - * @param callback Callback lambda - */ -template<> inline void rest_request_list(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback, const std::string& key) { - c->post_rest(basepath, major, minor, method, postdata, [c, callback](json &j, const http_request_completion_t& http) { - std::unordered_map list; - confirmation_callback_t e(c, confirmation(), http); - if (!e.is_error()) { - for (auto & curr_item : j) { - list[string_not_null(&curr_item, "code")] = invite().fill_from_json(&curr_item); - } - } - if (callback) { - callback(confirmation_callback_t(c, list, http)); - } - }); -} -/** - * @brief Templated REST request helper to save on typing (for returned lists, specialised for voiceregions) - * - * @tparam T singular type to return in lambda callback - * @tparam T map type to return in lambda callback - * @param c calling cluster - * @param basepath base path for API call - * @param major major API function - * @param minor minor API function - * @param method HTTP method - * @param postdata Post data or empty string - * @param key Key name of elements in the json list - * @param callback Callback lambda - */ -template<> inline void rest_request_list(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback, const std::string& key) { - c->post_rest(basepath, major, minor, method, postdata, [c, callback](json &j, const http_request_completion_t& http) { - std::unordered_map list; - confirmation_callback_t e(c, confirmation(), http); - if (!e.is_error()) { - for (auto & curr_item : j) { - list[string_not_null(&curr_item, "id")] = voiceregion().fill_from_json(&curr_item); - } - } - if (callback) { - callback(confirmation_callback_t(c, list, http)); - } - }); -} - -/** - * @brief Templated REST request helper to save on typing (for returned vectors) - * - * @tparam T singular type to return in lambda callback - * @tparam T vector type to return in lambda callback - * @param c calling cluster - * @param basepath base path for API call - * @param major major API function - * @param minor minor API function - * @param method HTTP method - * @param postdata Post data or empty string - * @param callback Callback lambda - */ -template inline void rest_request_vector(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback) { - c->post_rest(basepath, major, minor, method, postdata, [c, callback](json &j, const http_request_completion_t& http) { - std::vector list; - confirmation_callback_t e(c, confirmation(), http); - if (!e.is_error()) { - for (auto & curr_item : j) { - list.push_back(T().fill_from_json(&curr_item)); - } - } - if (callback) { - callback(confirmation_callback_t(c, list, http)); - } - }); -} - - +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2022 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Templated REST request helper to save on typing + * + * @tparam T type to return in lambda callback + * @param c calling cluster + * @param basepath base path for API call + * @param major major API function + * @param minor minor API function + * @param method HTTP method + * @param postdata Post data or empty string + * @param callback Callback lambda + */ +template inline void rest_request(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback) { + c->post_rest(basepath, major, minor, method, postdata, [c, callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t(c, T().fill_from_json(&j), http)); + } + }); +}; + +/** + * @brief Templated REST request helper to save on typing (specialised for message) + * + * @tparam T type to return in lambda callback + * @param c calling cluster + * @param basepath base path for API call + * @param major major API function + * @param minor minor API function + * @param method HTTP method + * @param postdata Post data or empty string + * @param callback Callback lambda + */ +template<> inline void rest_request(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback) { + c->post_rest(basepath, major, minor, method, postdata, [c, callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t(c, message(c).fill_from_json(&j), http)); + } + }); +}; + +/** + * @brief Templated REST request helper to save on typing (specialised for confirmation) + * + * @tparam T type to return in lambda callback + * @param c calling cluster + * @param basepath base path for API call + * @param major major API function + * @param minor minor API function + * @param method HTTP method + * @param postdata Post data or empty string + * @param callback Callback lambda + */ +template<> inline void rest_request(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback) { + c->post_rest(basepath, major, minor, method, postdata, [c, callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t(c, confirmation(), http)); + } + }); +}; + +/** + * @brief Templated REST request helper to save on typing (for returned lists) + * + * @tparam T singular type to return in lambda callback + * @tparam T map type to return in lambda callback + * @param c calling cluster + * @param basepath base path for API call + * @param major major API function + * @param minor minor API function + * @param method HTTP method + * @param postdata Post data or empty string + * @param key Key name of elements in the json list + * @param callback Callback lambda + */ +template inline void rest_request_list(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback, const std::string& key = "id") { + c->post_rest(basepath, major, minor, method, postdata, [c, key, callback](json &j, const http_request_completion_t& http) { + std::unordered_map list; + confirmation_callback_t e(c, confirmation(), http); + if (!e.is_error()) { + for (auto & curr_item : j) { + list[snowflake_not_null(&curr_item, key.c_str())] = T().fill_from_json(&curr_item); + } + } + if (callback) { + callback(confirmation_callback_t(c, list, http)); + } + }); +} + +/** + * @brief Templated REST request helper to save on typing (for returned lists, specialised for invites) + * + * @tparam T singular type to return in lambda callback + * @tparam T map type to return in lambda callback + * @param c calling cluster + * @param basepath base path for API call + * @param major major API function + * @param minor minor API function + * @param method HTTP method + * @param postdata Post data or empty string + * @param key Key name of elements in the json list + * @param callback Callback lambda + */ +template<> inline void rest_request_list(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback, const std::string& key) { + c->post_rest(basepath, major, minor, method, postdata, [c, callback](json &j, const http_request_completion_t& http) { + std::unordered_map list; + confirmation_callback_t e(c, confirmation(), http); + if (!e.is_error()) { + for (auto & curr_item : j) { + list[string_not_null(&curr_item, "code")] = invite().fill_from_json(&curr_item); + } + } + if (callback) { + callback(confirmation_callback_t(c, list, http)); + } + }); +} +/** + * @brief Templated REST request helper to save on typing (for returned lists, specialised for voiceregions) + * + * @tparam T singular type to return in lambda callback + * @tparam T map type to return in lambda callback + * @param c calling cluster + * @param basepath base path for API call + * @param major major API function + * @param minor minor API function + * @param method HTTP method + * @param postdata Post data or empty string + * @param key Key name of elements in the json list + * @param callback Callback lambda + */ +template<> inline void rest_request_list(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback, const std::string& key) { + c->post_rest(basepath, major, minor, method, postdata, [c, callback](json &j, const http_request_completion_t& http) { + std::unordered_map list; + confirmation_callback_t e(c, confirmation(), http); + if (!e.is_error()) { + for (auto & curr_item : j) { + list[string_not_null(&curr_item, "id")] = voiceregion().fill_from_json(&curr_item); + } + } + if (callback) { + callback(confirmation_callback_t(c, list, http)); + } + }); +} + +/** + * @brief Templated REST request helper to save on typing (for returned vectors) + * + * @tparam T singular type to return in lambda callback + * @tparam T vector type to return in lambda callback + * @param c calling cluster + * @param basepath base path for API call + * @param major major API function + * @param minor minor API function + * @param method HTTP method + * @param postdata Post data or empty string + * @param callback Callback lambda + */ +template inline void rest_request_vector(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback) { + c->post_rest(basepath, major, minor, method, postdata, [c, callback](json &j, const http_request_completion_t& http) { + std::vector list; + confirmation_callback_t e(c, confirmation(), http); + if (!e.is_error()) { + for (auto & curr_item : j) { + list.push_back(T().fill_from_json(&curr_item)); + } + } + if (callback) { + callback(confirmation_callback_t(c, list, http)); + } + }); +} + + }; \ No newline at end of file diff --git a/3rdParty/dpp/restresults.h b/3rdParty/dpp/restresults.h index 58c2e926ed..8a5afb4c59 100644 --- a/3rdParty/dpp/restresults.h +++ b/3rdParty/dpp/restresults.h @@ -1,316 +1,316 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using json = nlohmann::json; - -namespace dpp { - -#ifdef _WIN32 - #ifdef _DEBUG - extern "C" DPP_EXPORT void you_are_using_a_debug_build_of_dpp_on_a_release_project(); - #else - extern "C" DPP_EXPORT void you_are_using_a_release_build_of_dpp_on_a_debug_project(); - #endif -#endif - -struct DPP_EXPORT version_checker { - version_checker() { - #ifdef _WIN32 - #ifdef _DEBUG - you_are_using_a_debug_build_of_dpp_on_a_release_project(); - #else - you_are_using_a_release_build_of_dpp_on_a_debug_project(); - #endif - #endif - } -}; - -static version_checker dpp_vc; - - -/** - * @brief A list of shards - */ -typedef std::map shard_list; - -/** - * @brief Represents the various information from the 'get gateway bot' api call - */ -struct DPP_EXPORT gateway { - /// Gateway websocket url - std::string url; - - /// Number of suggested shards to start - uint32_t shards; - - /// Total number of sessions that can be started - uint32_t session_start_total; - - /// How many sessions are left - uint32_t session_start_remaining; - - /// How many seconds until the session start quota resets - uint32_t session_start_reset_after; - - /// How many sessions can be started at the same time - uint32_t session_start_max_concurrency; - - /** - * @brief Construct a new gateway object - * - * @param j JSON data to construct from - */ - gateway(nlohmann::json* j); - - /** - * @brief Construct a new gateway object - */ - gateway(); - - /** - * @brief Fill this object from json - * - * @param j json to fill from - * @return gateway& reference to self - */ - gateway& fill_from_json(nlohmann::json* j); -}; - -/** - * @brief Confirmation object represents any true or false simple REST request - * - */ -struct DPP_EXPORT confirmation { - bool success; -}; - -/** - * @brief A container for types that can be returned for a REST API call - * - */ -typedef std::variant< - application_role_connection, - application_role_connection_metadata_list, - confirmation, - message, - message_map, - user, - user_identified, - user_map, - guild_member, - guild_member_map, - channel, - channel_map, - thread_member, - thread_member_map, - guild, - guild_map, - guild_command_permissions, - guild_command_permissions_map, - role, - role_map, - invite, - invite_map, - dtemplate, - dtemplate_map, - emoji, - emoji_map, - ban, - ban_map, - voiceregion, - voiceregion_map, - integration, - integration_map, - webhook, - webhook_map, - prune, - guild_widget, - gateway, - interaction, - interaction_response, - auditlog, - slashcommand, - slashcommand_map, - stage_instance, - sticker, - sticker_map, - sticker_pack, - sticker_pack_map, - application, - application_map, - connection, - connection_map, - thread, - thread_map, - scheduled_event, - scheduled_event_map, - event_member, - event_member_map, - automod_rule, - automod_rule_map - > confirmable_t; - -/** - * @brief The details of a field in an error response - */ -struct DPP_EXPORT error_detail { - /** - * @brief Object name which is in error - */ - std::string object; - /** - * @brief Field name which is in error - */ - std::string field; - /** - * @brief Error code - */ - std::string code; - /** - * @brief Error reason (full message) - */ - std::string reason; -}; - -/** - * @brief The full details of an error from a REST response - */ -struct DPP_EXPORT error_info { - /** - * @brief Error code - */ - uint32_t code = 0; - /** - * @brief Error message - * - */ - std::string message; - /** - * @brief Field specific error descriptions - */ - std::vector errors; -}; - -/** - * @brief The results of a REST call wrapped in a convenient struct - */ -struct DPP_EXPORT confirmation_callback_t { - /** Information about the HTTP call used to make the request */ - http_request_completion_t http_info; - - /** Value returned, wrapped in variant */ - confirmable_t value; - - /** Owner/creator of the callback object */ - const class cluster* bot; - - /** - * @brief Construct a new confirmation callback t object - */ - confirmation_callback_t() = default; - - /** - * @brief Construct a new confirmation callback t object - * - * @param creator owning cluster object - */ - confirmation_callback_t(cluster* creator); - - /** - * @brief Construct a new confirmation callback object - * - * @param _http The HTTP metadata from the REST call - */ - confirmation_callback_t(const http_request_completion_t& _http); - - /** - * @brief Construct a new confirmation callback object - * - * @param creator owning cluster object - * @param _value The value to encapsulate in the confirmable_t - * @param _http The HTTP metadata from the REST call - */ - confirmation_callback_t(cluster* creator, const confirmable_t& _value, const http_request_completion_t& _http); - - /** - * @brief Returns true if the call resulted in an error rather than a legitimate value in the - * confirmation_callback_t::value member. - * - * @return true There was an error who's details can be obtained by get_error() - * @return false There was no error - */ - bool is_error() const; - - /** - * @brief Get the error_info object. - * The error_info object contains the details of any REST error, if there is an error - * (to find out if there is an error check confirmation_callback_t::is_error()) - * - * @return error_info The details of the error message - */ - error_info get_error() const; - - /** - * @brief Get the stored value via std::get - * @tparam T type to get - * @return stored value as type T - */ - template - T get() const { - return std::get(value); - } -}; - -/** - * @brief A callback upon command completion - */ -typedef std::function command_completion_event_t; - -/** - * @brief Automatically JSON encoded HTTP result - */ -typedef std::function json_encode_t; -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { + +#ifdef _WIN32 + #ifdef _DEBUG + extern "C" DPP_EXPORT void you_are_using_a_debug_build_of_dpp_on_a_release_project(); + #else + extern "C" DPP_EXPORT void you_are_using_a_release_build_of_dpp_on_a_debug_project(); + #endif +#endif + +struct DPP_EXPORT version_checker { + version_checker() { + #ifdef _WIN32 + #ifdef _DEBUG + you_are_using_a_debug_build_of_dpp_on_a_release_project(); + #else + you_are_using_a_release_build_of_dpp_on_a_debug_project(); + #endif + #endif + } +}; + +static version_checker dpp_vc; + + +/** + * @brief A list of shards + */ +typedef std::map shard_list; + +/** + * @brief Represents the various information from the 'get gateway bot' api call + */ +struct DPP_EXPORT gateway { + /// Gateway websocket url + std::string url; + + /// Number of suggested shards to start + uint32_t shards; + + /// Total number of sessions that can be started + uint32_t session_start_total; + + /// How many sessions are left + uint32_t session_start_remaining; + + /// How many seconds until the session start quota resets + uint32_t session_start_reset_after; + + /// How many sessions can be started at the same time + uint32_t session_start_max_concurrency; + + /** + * @brief Construct a new gateway object + * + * @param j JSON data to construct from + */ + gateway(nlohmann::json* j); + + /** + * @brief Construct a new gateway object + */ + gateway(); + + /** + * @brief Fill this object from json + * + * @param j json to fill from + * @return gateway& reference to self + */ + gateway& fill_from_json(nlohmann::json* j); +}; + +/** + * @brief Confirmation object represents any true or false simple REST request + * + */ +struct DPP_EXPORT confirmation { + bool success; +}; + +/** + * @brief A container for types that can be returned for a REST API call + * + */ +typedef std::variant< + application_role_connection, + application_role_connection_metadata_list, + confirmation, + message, + message_map, + user, + user_identified, + user_map, + guild_member, + guild_member_map, + channel, + channel_map, + thread_member, + thread_member_map, + guild, + guild_map, + guild_command_permissions, + guild_command_permissions_map, + role, + role_map, + invite, + invite_map, + dtemplate, + dtemplate_map, + emoji, + emoji_map, + ban, + ban_map, + voiceregion, + voiceregion_map, + integration, + integration_map, + webhook, + webhook_map, + prune, + guild_widget, + gateway, + interaction, + interaction_response, + auditlog, + slashcommand, + slashcommand_map, + stage_instance, + sticker, + sticker_map, + sticker_pack, + sticker_pack_map, + application, + application_map, + connection, + connection_map, + thread, + thread_map, + scheduled_event, + scheduled_event_map, + event_member, + event_member_map, + automod_rule, + automod_rule_map + > confirmable_t; + +/** + * @brief The details of a field in an error response + */ +struct DPP_EXPORT error_detail { + /** + * @brief Object name which is in error + */ + std::string object; + /** + * @brief Field name which is in error + */ + std::string field; + /** + * @brief Error code + */ + std::string code; + /** + * @brief Error reason (full message) + */ + std::string reason; +}; + +/** + * @brief The full details of an error from a REST response + */ +struct DPP_EXPORT error_info { + /** + * @brief Error code + */ + uint32_t code = 0; + /** + * @brief Error message + * + */ + std::string message; + /** + * @brief Field specific error descriptions + */ + std::vector errors; +}; + +/** + * @brief The results of a REST call wrapped in a convenient struct + */ +struct DPP_EXPORT confirmation_callback_t { + /** Information about the HTTP call used to make the request */ + http_request_completion_t http_info; + + /** Value returned, wrapped in variant */ + confirmable_t value; + + /** Owner/creator of the callback object */ + const class cluster* bot; + + /** + * @brief Construct a new confirmation callback t object + */ + confirmation_callback_t() = default; + + /** + * @brief Construct a new confirmation callback t object + * + * @param creator owning cluster object + */ + confirmation_callback_t(cluster* creator); + + /** + * @brief Construct a new confirmation callback object + * + * @param _http The HTTP metadata from the REST call + */ + confirmation_callback_t(const http_request_completion_t& _http); + + /** + * @brief Construct a new confirmation callback object + * + * @param creator owning cluster object + * @param _value The value to encapsulate in the confirmable_t + * @param _http The HTTP metadata from the REST call + */ + confirmation_callback_t(cluster* creator, const confirmable_t& _value, const http_request_completion_t& _http); + + /** + * @brief Returns true if the call resulted in an error rather than a legitimate value in the + * confirmation_callback_t::value member. + * + * @return true There was an error who's details can be obtained by get_error() + * @return false There was no error + */ + bool is_error() const; + + /** + * @brief Get the error_info object. + * The error_info object contains the details of any REST error, if there is an error + * (to find out if there is an error check confirmation_callback_t::is_error()) + * + * @return error_info The details of the error message + */ + error_info get_error() const; + + /** + * @brief Get the stored value via std::get + * @tparam T type to get + * @return stored value as type T + */ + template + T get() const { + return std::get(value); + } +}; + +/** + * @brief A callback upon command completion + */ +typedef std::function command_completion_event_t; + +/** + * @brief Automatically JSON encoded HTTP result + */ +typedef std::function json_encode_t; +}; diff --git a/3rdParty/dpp/role.h b/3rdParty/dpp/role.h index bfd1ab951c..1508c8d913 100644 --- a/3rdParty/dpp/role.h +++ b/3rdParty/dpp/role.h @@ -1,648 +1,648 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** Various flags related to dpp::role */ -enum role_flags : uint8_t { - r_hoist = 0b00000001, //!< Hoisted role - r_managed = 0b00000010, //!< Managed role (introduced by a bot or application) - r_mentionable = 0b00000100, //!< Mentionable with a ping - r_premium_subscriber = 0b00001000, //!< This is set for the role given to nitro -}; - -/** - * @brief Represents a role within a dpp::guild. - * Roles are combined via logical OR of the permission bitmasks, then channel-specific overrides - * can be applied on top, deny types apply a logic NOT to the bit mask, and allows apply a logical OR. - * @note Every guild has at least one role, called the 'everyone' role, which always has the same role - * ID as the guild's ID. This is the base permission set applied to all users where no other role or override - * applies, and is the starting value of the bit mask looped through to calculate channel permissions. - */ -class DPP_EXPORT role : public managed, public json_interface { -public: - /** - * @brief Role name - * Between 1 and 100 characters. - */ - std::string name; - /** - * @brief Guild ID - */ - snowflake guild_id; - /** - * @brief Role colour. - * A colour of 0 means no colour. If you want a black role, - * you must use the value 0x000001. - */ - uint32_t colour; - /** Role position */ - uint8_t position; - /** Role permissions bitmask values from dpp::permissions */ - permission permissions; - /** Role flags from dpp::role_flags */ - uint8_t flags; - /** Integration id if any (e.g. role is a bot's role created when it was invited) */ - snowflake integration_id; - /** Bot id if any (e.g. role is a bot's role created when it was invited) */ - snowflake bot_id; - /** The unicode emoji used for the role's icon, can be an empty string */ - std::string unicode_emoji; - /** The role icon hash, can be an empty string */ - utility::iconhash icon; - /** Image data for the role icon (if any) */ - std::string* image_data; - - /** - * @brief Construct a new role object - */ - role(); - - /** - * @brief Destroy the role object - */ - virtual ~role(); - - /** - * @brief Create a mentionable role. - * @param id The ID of the role. - * @return std::string The formatted mention of the role. - */ - static std::string get_mention(const snowflake& id); - - /** - * @brief Set the name of the role - * Maximum length: 100 - * Minimum length: 1 - * @param n Name to set - * @return role& reference to self - * @throw dpp::exception thrown if role length is less than 1 character - */ - role& set_name(const std::string& n); - - /** - * @brief Set the colour - * - * @param c Colour to set - * @note There is an americanised version of this method, role::set_color(). - * @return role& reference to self - */ - role& set_colour(uint32_t c); - - /** - * @brief Set the color - * - * @param c Colour to set - * @note This is an alias of role::set_colour for American spelling. - * @return role& reference to self - */ - role& set_color(uint32_t c); - - /** - * @brief Set the flags - * - * @param f Flags to set from dpp::role_flags - * @return role& reference to self - */ - role& set_flags(uint8_t f); - - /** - * @brief Set the integration id - * - * @param i Integration ID to set - * @return role& reference to self - */ - role& set_integration_id(snowflake i); - - /** - * @brief Set the bot id - * - * @param b Bot ID to set - * @return role& reference to self - */ - role& set_bot_id(snowflake b); - - /** - * @brief Set the guild id - * - * @param gid Guild ID to set - * @return role& reference to self - */ - role& set_guild_id(snowflake gid); - - /** - * @brief Fill this role from json. - * - * @param j The json data - * @return A reference to self - */ - role& fill_from_json(nlohmann::json* j); - - /** - * @brief Fill this role from json. - * - * @param guild_id the guild id to place in the json - * @param j The json data - * @return A reference to self - */ - role& fill_from_json(snowflake guild_id, nlohmann::json* j); - - /** - * @brief Build a json string from this object. - * - * @param with_id true if the ID is to be included in the json text - * @return The json of the role - */ - virtual std::string build_json(bool with_id = false) const; - - /** - * @brief Get the mention/ping for the role - * - * @return std::string mention - */ - std::string get_mention() const; - - /** - * @brief Returns the role's icon if they have one, otherwise returns an empty string - * - * @param size The size of the icon in pixels. It can be any power of two between 16 and 4096. If not specified, the default sized icon is returned. - * @return std::string icon url or empty string - */ - std::string get_icon_url(uint16_t size = 0) const; - - /** - * @brief Load an image into the object as base64 - * - * @param image_blob Image binary data - * @param type Type of image - * @return emoji& Reference to self - */ - role& load_image(const std::string &image_blob, const image_type type); - - /** - * @brief Operator less than, used for checking if a role is below another. - * - * @param lhs first role to compare - * @param rhs second role to compare - * @return true if lhs is less than rhs - */ - friend inline bool operator< (const role& lhs, const role& rhs) - { - return lhs.position < rhs.position; - } - - /** - * @brief Operator greater than, used for checking if a role is above another. - * - * @param lhs first role to compare - * @param rhs second role to compare - * @return true if lhs is greater than rhs - */ - friend inline bool operator> (const role& lhs, const role& rhs) - { - return lhs.position > rhs.position; - } - - /** - * @brief Operator equals, used for checking if a role is ranked equal to another. - * - * @param other role to compare - * @return true if is equal to other - */ - inline bool operator== (const role& other) const - { - return this->position == other.position; - } - - /** - * @brief Operator not equals, used for checking if a role is ranked equal to another. - * - * @param other role to compare - * @return true if is not equal to other - */ - inline bool operator!= (const role& other) const - { - return this->position != other.position; - } - - /** - * @brief True if the role is hoisted - * @return bool Role appears separated from others in the member list - */ - bool is_hoisted() const; - /** - * @brief True if the role is mentionable - * @return bool Role is mentionable - */ - bool is_mentionable() const; - /** - * @brief True if the role is managed (belongs to a bot or application) - * @return bool True if the role is managed (introduced for a bot or other application by Discord) - */ - bool is_managed() const; - /** - * @brief True if has create instant invite permission - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the instant invite permission or is administrator. - */ - bool has_create_instant_invite() const; - /** - * @brief True if has the kick members permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the kick members permission or is administrator. - */ - bool has_kick_members() const; - /** - * @brief True if has the ban members permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the ban members permission or is administrator. - */ - bool has_ban_members() const; - /** - * @brief True if has the administrator permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the administrator permission or is administrator. - */ - bool has_administrator() const; - /** - * @brief True if has the manage channels permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the manage channels permission or is administrator. - */ - bool has_manage_channels() const; - /** - * @brief True if has the manage guild permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the manage guild permission or is administrator. - */ - bool has_manage_guild() const; - /** - * @brief True if has the add reactions permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the add reactions permission or is administrator. - */ - bool has_add_reactions() const; - /** - * @brief True if has the view audit log permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the view audit log permission or is administrator. - */ - bool has_view_audit_log() const; - /** - * @brief True if has the priority speaker permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the priority speaker permission or is administrator. - */ - bool has_priority_speaker() const; - /** - * @brief True if has the stream permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the stream permission or is administrator. - */ - bool has_stream() const; - /** - * @brief True if has the view channel permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the view channel permission or is administrator. - */ - bool has_view_channel() const; - /** - * @brief True if has the send messages permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the send messages permission or is administrator. - */ - bool has_send_messages() const; - /** - * @brief True if has the send TTS messages permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the send TTS messages permission or is administrator. - */ - bool has_send_tts_messages() const; - /** - * @brief True if has the manage messages permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the manage messages permission or is administrator. - */ - bool has_manage_messages() const; - /** - * @brief True if has the embed links permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the embed links permission or is administrator. - */ - bool has_embed_links() const; - /** - * @brief True if has the attach files permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the attach files permission or is administrator. - */ - bool has_attach_files() const; - /** - * @brief True if has the read message history permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the read message history permission or is administrator. - */ - bool has_read_message_history() const; - /** - * @brief True if has the mention \@everyone and \@here permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the mention \@everyone and \@here permission or is administrator. - */ - bool has_mention_everyone() const; - /** - * @brief True if has the use external emojis permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the use external emojis permission or is administrator. - */ - bool has_use_external_emojis() const; - /** - * @brief True if has the view guild insights permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the view guild insights permission or is administrator. - */ - bool has_view_guild_insights() const; - /** - * @brief True if has the connect voice permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the connect voice permission or is administrator. - */ - bool has_connect() const; - /** - * @brief True if has the speak permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the speak permission or is administrator. - */ - bool has_speak() const; - /** - * @brief True if has the mute members permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the mute members permission or is administrator. - */ - bool has_mute_members() const; - /** - * @brief True if has the deafen members permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the deafen members permission or is administrator. - */ - bool has_deafen_members() const; - /** - * @brief True if has the move members permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the move members permission or is administrator. - */ - bool has_move_members() const; - /** True if has use voice activity detection permission */ - bool has_use_vad() const; - /** - * @brief True if has the change nickname permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the change nickname permission or is administrator. - */ - bool has_change_nickname() const; - /** - * @brief True if has the manage nicknames permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the manage nicknames permission or is administrator. - */ - bool has_manage_nicknames() const; - /** - * @brief True if has the manage roles permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the manage roles permission or is administrator. - */ - bool has_manage_roles() const; - /** - * @brief True if has the manage webhooks permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the manage webhooks permission or is administrator. - */ - bool has_manage_webhooks() const; - /** - * @brief True if has the manage emojis and stickers permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the manage emojis and stickers permission or is administrator. - */ - bool has_manage_emojis_and_stickers() const; - /** - * @brief True if has the use application commands permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the use application commands permission or is administrator. - */ - bool has_use_application_commands() const; - /** - * @brief True if has the request to speak permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the request to speak permission or is administrator. - */ - bool has_request_to_speak() const; - /** - * @brief True if has the manage threads permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the manage threads permission or is administrator. - */ - bool has_manage_threads() const; - /** - * @brief True if has the create public threads permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the create public threads permission or is administrator. - */ - bool has_create_public_threads() const; - /** - * @brief True if has the create private threads permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the create private threads permission or is administrator. - */ - bool has_create_private_threads() const; - /** - * @brief True if has the use external stickers permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the use external stickers permission or is administrator. - */ - bool has_use_external_stickers() const; - /** - * @brief True if has the send messages in threads permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the send messages in threads permission or is administrator. - */ - bool has_send_messages_in_threads() const; - /** - * @brief True if has the start embedded activities permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the start embedded activities permission or is administrator. - */ - bool has_use_embedded_activities() const; - /** - * @brief True if has the manage events permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the manage events permission or is administrator. - */ - bool has_manage_events() const; - /** - * @brief True if has the moderate users permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the moderate users permission or is administrator. - */ - bool has_moderate_members() const; - - /** - * @brief Get guild members who have this role - * @note This method requires user/members cache to be active - * @return members_container List of members who have this role - */ - members_container get_members() const; -}; - -/** - * @brief Application Role Connection Metadata Type - * - * @note Each metadata type offers a comparison operation that allows guilds to configure role requirements based on metadata values stored by the bot. Bots specify a `metadata value` for each user and guilds specify the required `guild's configured value` within the guild role settings. - */ -enum application_role_connection_metadata_type : uint8_t { - rc_integer_less_than_or_equal = 1, //!< The metadata value (integer) is less than or equal to the guild's configured value (integer) - rc_integer_greater_than_or_equal = 2, //!< The metadata value (integer) is greater than or equal to the guild's configured value (integer) - rc_integer_equal = 3, //!< The metadata value (integer) is equal to the guild's configured value (integer) - rc_integer_not_equal = 4, //!< The metadata value (integer) is not equal to the guild's configured value (integer) - rc_datetime_less_than_or_equal = 5, //!< The metadata value (ISO8601 string) is less than or equal to the guild's configured value (integer; days before current date) - rc_datetime_greater_than_or_equal = 6, //!< The metadata value (ISO8601 string) is greater than or equal to the guild's configured value (integer; days before current date) - rc_boolean_equal = 7, //!< The metadata value (integer) is equal to the guild's configured value (integer; 1) - rc_boolean_not_equal = 8, //!< The metadata value (integer) is not equal to the guild's configured value (integer; 1) -}; - -/** - * @brief Application Role Connection Metadata. Represents a role connection metadata for an dpp::application - */ -class DPP_EXPORT application_role_connection_metadata : public json_interface { -public: - application_role_connection_metadata_type type; //!< Type of metadata value - std::string key; //!< Dictionary key for the metadata field (must be `a-z`, `0-9`, or `_` characters; max 50 characters) - std::string name; //!< Name of the metadata field (max 100 characters) - std::map name_localizations; //!< Translations of the name - std::string description; //!< Description of the metadata field (max 200 characters) - std::map description_localizations; //!< Translations of the description - - /** - * Constructor - */ - application_role_connection_metadata(); - - virtual ~application_role_connection_metadata() = default; - - /** Fill this record from json. - * @param j The json to fill this record from - * @return Reference to self - */ - application_role_connection_metadata& fill_from_json(nlohmann::json* j); - - /** - * @brief Convert to JSON string - * - * @param with_id include ID in output - * @return std::string JSON output - */ - virtual std::string build_json(bool with_id = false) const; -}; - -/** - * @brief The application role connection that an application has attached to a user. - */ -class DPP_EXPORT application_role_connection : public json_interface { -public: - std::string platform_name; //!< Optional: The vanity name of the platform a bot has connected (max 50 characters) - std::string platform_username; //!< Optional: The username on the platform a bot has connected (max 100 characters) - std::variant metadata; //!< Optional: Object mapping application role connection metadata keys to their stringified value (max 100 characters) for the user on the platform a bot has connected - - /** - * Constructor - */ - application_role_connection(); - - virtual ~application_role_connection() = default; - - /** Fill this record from json. - * @param j The json to fill this record from - * @return Reference to self - */ - application_role_connection& fill_from_json(nlohmann::json* j); - - /** - * @brief Convert to JSON string - * - * @param with_id include ID in output - * @return std::string JSON output - */ - virtual std::string build_json(bool with_id = false) const; -}; - -/** A group of roles */ -typedef std::unordered_map role_map; - -/** A group of application_role_connection_metadata objects */ -typedef std::vector application_role_connection_metadata_list; - -}; - +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** Various flags related to dpp::role */ +enum role_flags : uint8_t { + r_hoist = 0b00000001, //!< Hoisted role + r_managed = 0b00000010, //!< Managed role (introduced by a bot or application) + r_mentionable = 0b00000100, //!< Mentionable with a ping + r_premium_subscriber = 0b00001000, //!< This is set for the role given to nitro +}; + +/** + * @brief Represents a role within a dpp::guild. + * Roles are combined via logical OR of the permission bitmasks, then channel-specific overrides + * can be applied on top, deny types apply a logic NOT to the bit mask, and allows apply a logical OR. + * @note Every guild has at least one role, called the 'everyone' role, which always has the same role + * ID as the guild's ID. This is the base permission set applied to all users where no other role or override + * applies, and is the starting value of the bit mask looped through to calculate channel permissions. + */ +class DPP_EXPORT role : public managed, public json_interface { +public: + /** + * @brief Role name + * Between 1 and 100 characters. + */ + std::string name; + /** + * @brief Guild ID + */ + snowflake guild_id; + /** + * @brief Role colour. + * A colour of 0 means no colour. If you want a black role, + * you must use the value 0x000001. + */ + uint32_t colour; + /** Role position */ + uint8_t position; + /** Role permissions bitmask values from dpp::permissions */ + permission permissions; + /** Role flags from dpp::role_flags */ + uint8_t flags; + /** Integration id if any (e.g. role is a bot's role created when it was invited) */ + snowflake integration_id; + /** Bot id if any (e.g. role is a bot's role created when it was invited) */ + snowflake bot_id; + /** The unicode emoji used for the role's icon, can be an empty string */ + std::string unicode_emoji; + /** The role icon hash, can be an empty string */ + utility::iconhash icon; + /** Image data for the role icon (if any) */ + std::string* image_data; + + /** + * @brief Construct a new role object + */ + role(); + + /** + * @brief Destroy the role object + */ + virtual ~role(); + + /** + * @brief Create a mentionable role. + * @param id The ID of the role. + * @return std::string The formatted mention of the role. + */ + static std::string get_mention(const snowflake& id); + + /** + * @brief Set the name of the role + * Maximum length: 100 + * Minimum length: 1 + * @param n Name to set + * @return role& reference to self + * @throw dpp::exception thrown if role length is less than 1 character + */ + role& set_name(const std::string& n); + + /** + * @brief Set the colour + * + * @param c Colour to set + * @note There is an americanised version of this method, role::set_color(). + * @return role& reference to self + */ + role& set_colour(uint32_t c); + + /** + * @brief Set the color + * + * @param c Colour to set + * @note This is an alias of role::set_colour for American spelling. + * @return role& reference to self + */ + role& set_color(uint32_t c); + + /** + * @brief Set the flags + * + * @param f Flags to set from dpp::role_flags + * @return role& reference to self + */ + role& set_flags(uint8_t f); + + /** + * @brief Set the integration id + * + * @param i Integration ID to set + * @return role& reference to self + */ + role& set_integration_id(snowflake i); + + /** + * @brief Set the bot id + * + * @param b Bot ID to set + * @return role& reference to self + */ + role& set_bot_id(snowflake b); + + /** + * @brief Set the guild id + * + * @param gid Guild ID to set + * @return role& reference to self + */ + role& set_guild_id(snowflake gid); + + /** + * @brief Fill this role from json. + * + * @param j The json data + * @return A reference to self + */ + role& fill_from_json(nlohmann::json* j); + + /** + * @brief Fill this role from json. + * + * @param guild_id the guild id to place in the json + * @param j The json data + * @return A reference to self + */ + role& fill_from_json(snowflake guild_id, nlohmann::json* j); + + /** + * @brief Build a json string from this object. + * + * @param with_id true if the ID is to be included in the json text + * @return The json of the role + */ + virtual std::string build_json(bool with_id = false) const; + + /** + * @brief Get the mention/ping for the role + * + * @return std::string mention + */ + std::string get_mention() const; + + /** + * @brief Returns the role's icon if they have one, otherwise returns an empty string + * + * @param size The size of the icon in pixels. It can be any power of two between 16 and 4096. If not specified, the default sized icon is returned. + * @return std::string icon url or empty string + */ + std::string get_icon_url(uint16_t size = 0) const; + + /** + * @brief Load an image into the object as base64 + * + * @param image_blob Image binary data + * @param type Type of image + * @return emoji& Reference to self + */ + role& load_image(const std::string &image_blob, const image_type type); + + /** + * @brief Operator less than, used for checking if a role is below another. + * + * @param lhs first role to compare + * @param rhs second role to compare + * @return true if lhs is less than rhs + */ + friend inline bool operator< (const role& lhs, const role& rhs) + { + return lhs.position < rhs.position; + } + + /** + * @brief Operator greater than, used for checking if a role is above another. + * + * @param lhs first role to compare + * @param rhs second role to compare + * @return true if lhs is greater than rhs + */ + friend inline bool operator> (const role& lhs, const role& rhs) + { + return lhs.position > rhs.position; + } + + /** + * @brief Operator equals, used for checking if a role is ranked equal to another. + * + * @param other role to compare + * @return true if is equal to other + */ + inline bool operator== (const role& other) const + { + return this->position == other.position; + } + + /** + * @brief Operator not equals, used for checking if a role is ranked equal to another. + * + * @param other role to compare + * @return true if is not equal to other + */ + inline bool operator!= (const role& other) const + { + return this->position != other.position; + } + + /** + * @brief True if the role is hoisted + * @return bool Role appears separated from others in the member list + */ + bool is_hoisted() const; + /** + * @brief True if the role is mentionable + * @return bool Role is mentionable + */ + bool is_mentionable() const; + /** + * @brief True if the role is managed (belongs to a bot or application) + * @return bool True if the role is managed (introduced for a bot or other application by Discord) + */ + bool is_managed() const; + /** + * @brief True if has create instant invite permission + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the instant invite permission or is administrator. + */ + bool has_create_instant_invite() const; + /** + * @brief True if has the kick members permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the kick members permission or is administrator. + */ + bool has_kick_members() const; + /** + * @brief True if has the ban members permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the ban members permission or is administrator. + */ + bool has_ban_members() const; + /** + * @brief True if has the administrator permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the administrator permission or is administrator. + */ + bool has_administrator() const; + /** + * @brief True if has the manage channels permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the manage channels permission or is administrator. + */ + bool has_manage_channels() const; + /** + * @brief True if has the manage guild permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the manage guild permission or is administrator. + */ + bool has_manage_guild() const; + /** + * @brief True if has the add reactions permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the add reactions permission or is administrator. + */ + bool has_add_reactions() const; + /** + * @brief True if has the view audit log permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the view audit log permission or is administrator. + */ + bool has_view_audit_log() const; + /** + * @brief True if has the priority speaker permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the priority speaker permission or is administrator. + */ + bool has_priority_speaker() const; + /** + * @brief True if has the stream permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the stream permission or is administrator. + */ + bool has_stream() const; + /** + * @brief True if has the view channel permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the view channel permission or is administrator. + */ + bool has_view_channel() const; + /** + * @brief True if has the send messages permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the send messages permission or is administrator. + */ + bool has_send_messages() const; + /** + * @brief True if has the send TTS messages permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the send TTS messages permission or is administrator. + */ + bool has_send_tts_messages() const; + /** + * @brief True if has the manage messages permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the manage messages permission or is administrator. + */ + bool has_manage_messages() const; + /** + * @brief True if has the embed links permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the embed links permission or is administrator. + */ + bool has_embed_links() const; + /** + * @brief True if has the attach files permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the attach files permission or is administrator. + */ + bool has_attach_files() const; + /** + * @brief True if has the read message history permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the read message history permission or is administrator. + */ + bool has_read_message_history() const; + /** + * @brief True if has the mention \@everyone and \@here permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the mention \@everyone and \@here permission or is administrator. + */ + bool has_mention_everyone() const; + /** + * @brief True if has the use external emojis permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the use external emojis permission or is administrator. + */ + bool has_use_external_emojis() const; + /** + * @brief True if has the view guild insights permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the view guild insights permission or is administrator. + */ + bool has_view_guild_insights() const; + /** + * @brief True if has the connect voice permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the connect voice permission or is administrator. + */ + bool has_connect() const; + /** + * @brief True if has the speak permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the speak permission or is administrator. + */ + bool has_speak() const; + /** + * @brief True if has the mute members permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the mute members permission or is administrator. + */ + bool has_mute_members() const; + /** + * @brief True if has the deafen members permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the deafen members permission or is administrator. + */ + bool has_deafen_members() const; + /** + * @brief True if has the move members permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the move members permission or is administrator. + */ + bool has_move_members() const; + /** True if has use voice activity detection permission */ + bool has_use_vad() const; + /** + * @brief True if has the change nickname permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the change nickname permission or is administrator. + */ + bool has_change_nickname() const; + /** + * @brief True if has the manage nicknames permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the manage nicknames permission or is administrator. + */ + bool has_manage_nicknames() const; + /** + * @brief True if has the manage roles permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the manage roles permission or is administrator. + */ + bool has_manage_roles() const; + /** + * @brief True if has the manage webhooks permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the manage webhooks permission or is administrator. + */ + bool has_manage_webhooks() const; + /** + * @brief True if has the manage emojis and stickers permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the manage emojis and stickers permission or is administrator. + */ + bool has_manage_emojis_and_stickers() const; + /** + * @brief True if has the use application commands permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the use application commands permission or is administrator. + */ + bool has_use_application_commands() const; + /** + * @brief True if has the request to speak permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the request to speak permission or is administrator. + */ + bool has_request_to_speak() const; + /** + * @brief True if has the manage threads permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the manage threads permission or is administrator. + */ + bool has_manage_threads() const; + /** + * @brief True if has the create public threads permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the create public threads permission or is administrator. + */ + bool has_create_public_threads() const; + /** + * @brief True if has the create private threads permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the create private threads permission or is administrator. + */ + bool has_create_private_threads() const; + /** + * @brief True if has the use external stickers permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the use external stickers permission or is administrator. + */ + bool has_use_external_stickers() const; + /** + * @brief True if has the send messages in threads permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the send messages in threads permission or is administrator. + */ + bool has_send_messages_in_threads() const; + /** + * @brief True if has the start embedded activities permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the start embedded activities permission or is administrator. + */ + bool has_use_embedded_activities() const; + /** + * @brief True if has the manage events permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the manage events permission or is administrator. + */ + bool has_manage_events() const; + /** + * @brief True if has the moderate users permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the moderate users permission or is administrator. + */ + bool has_moderate_members() const; + + /** + * @brief Get guild members who have this role + * @note This method requires user/members cache to be active + * @return members_container List of members who have this role + */ + members_container get_members() const; +}; + +/** + * @brief Application Role Connection Metadata Type + * + * @note Each metadata type offers a comparison operation that allows guilds to configure role requirements based on metadata values stored by the bot. Bots specify a `metadata value` for each user and guilds specify the required `guild's configured value` within the guild role settings. + */ +enum application_role_connection_metadata_type : uint8_t { + rc_integer_less_than_or_equal = 1, //!< The metadata value (integer) is less than or equal to the guild's configured value (integer) + rc_integer_greater_than_or_equal = 2, //!< The metadata value (integer) is greater than or equal to the guild's configured value (integer) + rc_integer_equal = 3, //!< The metadata value (integer) is equal to the guild's configured value (integer) + rc_integer_not_equal = 4, //!< The metadata value (integer) is not equal to the guild's configured value (integer) + rc_datetime_less_than_or_equal = 5, //!< The metadata value (ISO8601 string) is less than or equal to the guild's configured value (integer; days before current date) + rc_datetime_greater_than_or_equal = 6, //!< The metadata value (ISO8601 string) is greater than or equal to the guild's configured value (integer; days before current date) + rc_boolean_equal = 7, //!< The metadata value (integer) is equal to the guild's configured value (integer; 1) + rc_boolean_not_equal = 8, //!< The metadata value (integer) is not equal to the guild's configured value (integer; 1) +}; + +/** + * @brief Application Role Connection Metadata. Represents a role connection metadata for an dpp::application + */ +class DPP_EXPORT application_role_connection_metadata : public json_interface { +public: + application_role_connection_metadata_type type; //!< Type of metadata value + std::string key; //!< Dictionary key for the metadata field (must be `a-z`, `0-9`, or `_` characters; max 50 characters) + std::string name; //!< Name of the metadata field (max 100 characters) + std::map name_localizations; //!< Translations of the name + std::string description; //!< Description of the metadata field (max 200 characters) + std::map description_localizations; //!< Translations of the description + + /** + * Constructor + */ + application_role_connection_metadata(); + + virtual ~application_role_connection_metadata() = default; + + /** Fill this record from json. + * @param j The json to fill this record from + * @return Reference to self + */ + application_role_connection_metadata& fill_from_json(nlohmann::json* j); + + /** + * @brief Convert to JSON string + * + * @param with_id include ID in output + * @return std::string JSON output + */ + virtual std::string build_json(bool with_id = false) const; +}; + +/** + * @brief The application role connection that an application has attached to a user. + */ +class DPP_EXPORT application_role_connection : public json_interface { +public: + std::string platform_name; //!< Optional: The vanity name of the platform a bot has connected (max 50 characters) + std::string platform_username; //!< Optional: The username on the platform a bot has connected (max 100 characters) + std::variant metadata; //!< Optional: Object mapping application role connection metadata keys to their stringified value (max 100 characters) for the user on the platform a bot has connected + + /** + * Constructor + */ + application_role_connection(); + + virtual ~application_role_connection() = default; + + /** Fill this record from json. + * @param j The json to fill this record from + * @return Reference to self + */ + application_role_connection& fill_from_json(nlohmann::json* j); + + /** + * @brief Convert to JSON string + * + * @param with_id include ID in output + * @return std::string JSON output + */ + virtual std::string build_json(bool with_id = false) const; +}; + +/** A group of roles */ +typedef std::unordered_map role_map; + +/** A group of application_role_connection_metadata objects */ +typedef std::vector application_role_connection_metadata_list; + +}; + diff --git a/3rdParty/dpp/scheduled_event.h b/3rdParty/dpp/scheduled_event.h index 5e8a63ec97..ceec00d79f 100644 --- a/3rdParty/dpp/scheduled_event.h +++ b/3rdParty/dpp/scheduled_event.h @@ -1,224 +1,224 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Represents the privacy of an event - */ -enum event_privacy_level : uint8_t { - /// The event is visible to only guild members. - ep_guild_only = 2 -}; - -/** - * @brief Event entity types - */ -enum event_entity_type : uint8_t { - /// A stage instance - eet_stage_instance = 1, - /// A voice channel - eet_voice = 2, - /// External to discord, or a text channel etc - eet_external = 3 -}; - -/** - * @brief Event status types - */ -enum event_status : uint8_t { - /// Scheduled - es_scheduled = 1, - /// Active now - es_active = 2, - /// Completed - es_completed = 3, - /// Cancelled - es_cancelled = 4 -}; - -/** - * @brief Entities for the event - */ -struct DPP_EXPORT event_entities { - /// location of the event - std::string location; -}; - -/** - * @brief Represents a guild member/user who has registered interest in an event - * - */ -struct DPP_EXPORT event_member { - /** - * @brief Event ID associated with - */ - snowflake guild_scheduled_event_id; - /** - * @brief User details of associated user - * - */ - dpp::user user; - /** - * @brief Member details of user on the associated guild - */ - dpp::guild_member member; -}; - -/** - * @brief A scheduled event - */ -struct DPP_EXPORT scheduled_event : public managed, public json_interface { - snowflake guild_id; //!< the guild id which the scheduled event belongs to - snowflake channel_id; //!< the channel id in which the scheduled event will be hosted, or null if scheduled entity type is EXTERNAL (may be empty) - snowflake creator_id; //!< Optional: the id of the user that created the scheduled event - std::string name; //!< the name of the scheduled event - std::string description; //!< Optional: the description of the scheduled event (1-1000 characters) - std::string image; //!< the image of the scheduled event (may be empty) - time_t scheduled_start_time; //!< the time the scheduled event will start - time_t scheduled_end_time; //!< the time the scheduled event will end, or null if the event does not have a scheduled time to end (may be empty) - event_privacy_level privacy_level; //!< the privacy level of the scheduled event - event_status status; //!< the status of the scheduled event - event_entity_type entity_type; //!< the type of hosting entity associated with a scheduled event, e.g. voice channel or stage channel - snowflake entity_id; //!< any additional id of the hosting entity associated with event, e.g. stage instance id) (may be empty) - event_entities entity_metadata; //!< the entity metadata for the scheduled event (may be empty) - user creator; //!< Optional: the creator of the scheduled event - uint32_t user_count; //!< Optional: the number of users subscribed to the scheduled event - - /** - * @brief Create a scheduled_event object - */ - scheduled_event(); - - /** - * @brief Destroy the scheduled_event object - */ - ~scheduled_event() = default; - - /** - * @brief Set the name of the event - * Minimum length: 1, Maximum length: 100 - * @param n event name - * @return scheduled_event& reference to self - * @throw dpp::length_error if length < 1 - */ - scheduled_event& set_name(const std::string& n); - - /** - * @brief Set the description of the event - * Minimum length: 1 (if set), Maximum length: 100 - * @param d event description - * @return scheduled_event& reference to self - * @throw dpp::length_error if length < 1 - */ - scheduled_event& set_description(const std::string& d); - - /** - * @brief Clear the description of the event - * @return scheduled_event& reference to self - */ - scheduled_event& clear_description(); - - /** - * @brief Set the location of the event. - * Minimum length: 1, Maximum length: 1000 - * @note Clears channel_id - * @param l event location - * @return scheduled_event& reference to self - * @throw dpp::length_error if length < 1 - */ - scheduled_event& set_location(const std::string& l); - - /** - * @brief Set the voice channel id of the event - * @note clears location - * @param c channel ID - * @return scheduled_event& reference to self - */ - scheduled_event& set_channel_id(snowflake c); - - /** - * @brief Set the creator id of the event - * @param c creator user ID - * @return scheduled_event& reference to self - */ - scheduled_event& set_creator_id(snowflake c); - - /** - * @brief Set the status of the event - * @param s status to set - * @return scheduled_event& reference to self - * @throw dpp::logic_exception if status change is not valid - */ - scheduled_event& set_status(event_status s); - - /** - * @brief Set the start time of the event - * @param t starting time - * @return scheduled_event& reference to self - * @throw dpp::length_error if time is before now - */ - scheduled_event& set_start_time(time_t t); - - /** - * @brief Set the end time of the event - * @param t ending time - * @return scheduled_event& reference to self - * @throw dpp::length_error if time is before now - */ - scheduled_event& set_end_time(time_t t); - - /** - * @brief Serialise a scheduled_event object from json - * - * @return scheduled_event& a reference to self - */ - scheduled_event& fill_from_json(const nlohmann::json* j); - - /** - * @brief Build json for this object - * @param with_id Include id field in json - * - * @return std::string Dumped json of this object - */ - virtual std::string build_json(bool with_id = false) const; -}; - -/** - * @brief A group of scheduled events - */ -typedef std::unordered_map scheduled_event_map; - -/** - * @brief A group of scheduled event members - */ -typedef std::unordered_map event_member_map; - - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Represents the privacy of an event + */ +enum event_privacy_level : uint8_t { + /// The event is visible to only guild members. + ep_guild_only = 2 +}; + +/** + * @brief Event entity types + */ +enum event_entity_type : uint8_t { + /// A stage instance + eet_stage_instance = 1, + /// A voice channel + eet_voice = 2, + /// External to discord, or a text channel etc + eet_external = 3 +}; + +/** + * @brief Event status types + */ +enum event_status : uint8_t { + /// Scheduled + es_scheduled = 1, + /// Active now + es_active = 2, + /// Completed + es_completed = 3, + /// Cancelled + es_cancelled = 4 +}; + +/** + * @brief Entities for the event + */ +struct DPP_EXPORT event_entities { + /// location of the event + std::string location; +}; + +/** + * @brief Represents a guild member/user who has registered interest in an event + * + */ +struct DPP_EXPORT event_member { + /** + * @brief Event ID associated with + */ + snowflake guild_scheduled_event_id; + /** + * @brief User details of associated user + * + */ + dpp::user user; + /** + * @brief Member details of user on the associated guild + */ + dpp::guild_member member; +}; + +/** + * @brief A scheduled event + */ +struct DPP_EXPORT scheduled_event : public managed, public json_interface { + snowflake guild_id; //!< the guild id which the scheduled event belongs to + snowflake channel_id; //!< the channel id in which the scheduled event will be hosted, or null if scheduled entity type is EXTERNAL (may be empty) + snowflake creator_id; //!< Optional: the id of the user that created the scheduled event + std::string name; //!< the name of the scheduled event + std::string description; //!< Optional: the description of the scheduled event (1-1000 characters) + std::string image; //!< the image of the scheduled event (may be empty) + time_t scheduled_start_time; //!< the time the scheduled event will start + time_t scheduled_end_time; //!< the time the scheduled event will end, or null if the event does not have a scheduled time to end (may be empty) + event_privacy_level privacy_level; //!< the privacy level of the scheduled event + event_status status; //!< the status of the scheduled event + event_entity_type entity_type; //!< the type of hosting entity associated with a scheduled event, e.g. voice channel or stage channel + snowflake entity_id; //!< any additional id of the hosting entity associated with event, e.g. stage instance id) (may be empty) + event_entities entity_metadata; //!< the entity metadata for the scheduled event (may be empty) + user creator; //!< Optional: the creator of the scheduled event + uint32_t user_count; //!< Optional: the number of users subscribed to the scheduled event + + /** + * @brief Create a scheduled_event object + */ + scheduled_event(); + + /** + * @brief Destroy the scheduled_event object + */ + ~scheduled_event() = default; + + /** + * @brief Set the name of the event + * Minimum length: 1, Maximum length: 100 + * @param n event name + * @return scheduled_event& reference to self + * @throw dpp::length_error if length < 1 + */ + scheduled_event& set_name(const std::string& n); + + /** + * @brief Set the description of the event + * Minimum length: 1 (if set), Maximum length: 100 + * @param d event description + * @return scheduled_event& reference to self + * @throw dpp::length_error if length < 1 + */ + scheduled_event& set_description(const std::string& d); + + /** + * @brief Clear the description of the event + * @return scheduled_event& reference to self + */ + scheduled_event& clear_description(); + + /** + * @brief Set the location of the event. + * Minimum length: 1, Maximum length: 1000 + * @note Clears channel_id + * @param l event location + * @return scheduled_event& reference to self + * @throw dpp::length_error if length < 1 + */ + scheduled_event& set_location(const std::string& l); + + /** + * @brief Set the voice channel id of the event + * @note clears location + * @param c channel ID + * @return scheduled_event& reference to self + */ + scheduled_event& set_channel_id(snowflake c); + + /** + * @brief Set the creator id of the event + * @param c creator user ID + * @return scheduled_event& reference to self + */ + scheduled_event& set_creator_id(snowflake c); + + /** + * @brief Set the status of the event + * @param s status to set + * @return scheduled_event& reference to self + * @throw dpp::logic_exception if status change is not valid + */ + scheduled_event& set_status(event_status s); + + /** + * @brief Set the start time of the event + * @param t starting time + * @return scheduled_event& reference to self + * @throw dpp::length_error if time is before now + */ + scheduled_event& set_start_time(time_t t); + + /** + * @brief Set the end time of the event + * @param t ending time + * @return scheduled_event& reference to self + * @throw dpp::length_error if time is before now + */ + scheduled_event& set_end_time(time_t t); + + /** + * @brief Serialise a scheduled_event object from json + * + * @return scheduled_event& a reference to self + */ + scheduled_event& fill_from_json(const nlohmann::json* j); + + /** + * @brief Build json for this object + * @param with_id Include id field in json + * + * @return std::string Dumped json of this object + */ + virtual std::string build_json(bool with_id = false) const; +}; + +/** + * @brief A group of scheduled events + */ +typedef std::unordered_map scheduled_event_map; + +/** + * @brief A group of scheduled event members + */ +typedef std::unordered_map event_member_map; + + +}; diff --git a/3rdParty/dpp/snowflake.h b/3rdParty/dpp/snowflake.h index 2eb0205d1c..033b1d10f5 100644 --- a/3rdParty/dpp/snowflake.h +++ b/3rdParty/dpp/snowflake.h @@ -1,196 +1,196 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include - -/** - * @brief The main namespace for D++ functions. classes and types - */ -namespace dpp { - -/** @brief A container for a 64 bit unsigned value representing many things on discord. - * This value is known in distributed computing as a snowflake value. - * - * Snowflakes are: - * - * - Performant (very fast to generate at source and to compare in code) - * - Uncoordinated (allowing high availability across clusters, data centres etc) - * - Time ordered (newer snowflakes have higher IDs) - * - Directly Sortable (due to time ordering) - * - Compact (64 bit numbers, not 128 bit, or string) - * - * An identical format of snowflake is used by Twitter, Instagram and several other platforms. - * - * @see https://en.wikipedia.org/wiki/Snowflake_ID - * @see https://github.com/twitter-archive/snowflake/tree/b3f6a3c6ca8e1b6847baa6ff42bf72201e2c2231 - */ -class DPP_EXPORT snowflake final { - friend struct std::hash; -protected: - /** - * @brief The snowflake value - */ - uint64_t value; - -public: - /** - * @brief Construct a snowflake object - * @param value A snowflake value - */ - snowflake(const uint64_t& value); - - /** - * @brief Construct a snowflake object - * @param value A snowflake value - */ - snowflake(const std::string& string_value); - - /** - * @brief Construct a snowflake object - */ - snowflake(); - - /** - * @brief Destroy the snowflake object - */ - ~snowflake() = default; - - /** - * @brief For acting like an integer - * @return The snowflake value - */ - operator uint64_t() const; - - /** - * @brief Returns true if the snowflake holds an empty value (is 0) - * - * @return true if empty (zero) - */ - inline bool empty() const - { - return value == 0; - } - - /** - * @brief Operator less than, used for maps/unordered maps - * when the snowflake is a key value. - * - * @param lhs fist snowflake to compare - * @param rhs second snowflake to compare - * @return true if lhs is less than rhs - */ - friend inline bool operator< (const snowflake& lhs, const snowflake& rhs) - { - return lhs.value < rhs.value; - } - - /** - * @brief Assign from std::string - * - * @param snowflake_val string to assign from. - */ - snowflake& operator=(const std::string &snowflake_val); - - /** - * @brief Assign from std::string - * - * @param snowflake_val value to assign from. - */ - snowflake& operator=(const uint64_t &snowflake_val); - - /** - * @brief Check if one snowflake value is equal to another - * - * @param other other snowflake to compare - * @return True if the snowflake objects match - */ - bool operator==(const snowflake& other) const; - - /** - * @brief Check if one snowflake value is equal to a uint64_t - * - * @param other other snowflake to compare - * @return True if the snowflake objects match - */ - bool operator==(const uint64_t& other) const; - - /** - * @brief For acting like an integer - * @return A reference to the snowflake value - */ - operator uint64_t &(); - - /** - * @brief For building json - * @return The snowflake value as a string - */ - operator nlohmann::json() const; - - /** - * @brief Get the creation time of this snowflake according to Discord. - * - * @return double creation time inferred from the snowflake ID. - * The minimum possible value is the first second of 2015. - */ - double get_creation_time() const; - - /** - * @brief Get the worker id that produced this snowflake value - * - * @return uint8_t worker id - */ - uint8_t get_worker_id() const; - - /** - * @brief Get the process id that produced this snowflake value - * - * @return uint8_t process id - */ - uint8_t get_process_id() const; - - /** - * @brief Get the increment, which is incremented for every snowflake - * created over the one millisecond resolution in the timestamp. - * - * @return uint64_t millisecond increment - */ - uint16_t get_increment() const; -}; - -}; - -template<> -struct std::hash -{ - /** - * @brief Hashing function for dpp::slowflake - * Used by std::unordered_map. This just calls std::hash. - * - * @param s Snowflake value to hash - * @return std::size_t hash value - */ - std::size_t operator()(dpp::snowflake const& s) const noexcept { - return std::hash{}(s.value); - } -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include + +/** + * @brief The main namespace for D++ functions. classes and types + */ +namespace dpp { + +/** @brief A container for a 64 bit unsigned value representing many things on discord. + * This value is known in distributed computing as a snowflake value. + * + * Snowflakes are: + * + * - Performant (very fast to generate at source and to compare in code) + * - Uncoordinated (allowing high availability across clusters, data centres etc) + * - Time ordered (newer snowflakes have higher IDs) + * - Directly Sortable (due to time ordering) + * - Compact (64 bit numbers, not 128 bit, or string) + * + * An identical format of snowflake is used by Twitter, Instagram and several other platforms. + * + * @see https://en.wikipedia.org/wiki/Snowflake_ID + * @see https://github.com/twitter-archive/snowflake/tree/b3f6a3c6ca8e1b6847baa6ff42bf72201e2c2231 + */ +class DPP_EXPORT snowflake final { + friend struct std::hash; +protected: + /** + * @brief The snowflake value + */ + uint64_t value; + +public: + /** + * @brief Construct a snowflake object + * @param value A snowflake value + */ + snowflake(const uint64_t& value); + + /** + * @brief Construct a snowflake object + * @param value A snowflake value + */ + snowflake(const std::string& string_value); + + /** + * @brief Construct a snowflake object + */ + snowflake(); + + /** + * @brief Destroy the snowflake object + */ + ~snowflake() = default; + + /** + * @brief For acting like an integer + * @return The snowflake value + */ + operator uint64_t() const; + + /** + * @brief Returns true if the snowflake holds an empty value (is 0) + * + * @return true if empty (zero) + */ + inline bool empty() const + { + return value == 0; + } + + /** + * @brief Operator less than, used for maps/unordered maps + * when the snowflake is a key value. + * + * @param lhs fist snowflake to compare + * @param rhs second snowflake to compare + * @return true if lhs is less than rhs + */ + friend inline bool operator< (const snowflake& lhs, const snowflake& rhs) + { + return lhs.value < rhs.value; + } + + /** + * @brief Assign from std::string + * + * @param snowflake_val string to assign from. + */ + snowflake& operator=(const std::string &snowflake_val); + + /** + * @brief Assign from std::string + * + * @param snowflake_val value to assign from. + */ + snowflake& operator=(const uint64_t &snowflake_val); + + /** + * @brief Check if one snowflake value is equal to another + * + * @param other other snowflake to compare + * @return True if the snowflake objects match + */ + bool operator==(const snowflake& other) const; + + /** + * @brief Check if one snowflake value is equal to a uint64_t + * + * @param other other snowflake to compare + * @return True if the snowflake objects match + */ + bool operator==(const uint64_t& other) const; + + /** + * @brief For acting like an integer + * @return A reference to the snowflake value + */ + operator uint64_t &(); + + /** + * @brief For building json + * @return The snowflake value as a string + */ + operator nlohmann::json() const; + + /** + * @brief Get the creation time of this snowflake according to Discord. + * + * @return double creation time inferred from the snowflake ID. + * The minimum possible value is the first second of 2015. + */ + double get_creation_time() const; + + /** + * @brief Get the worker id that produced this snowflake value + * + * @return uint8_t worker id + */ + uint8_t get_worker_id() const; + + /** + * @brief Get the process id that produced this snowflake value + * + * @return uint8_t process id + */ + uint8_t get_process_id() const; + + /** + * @brief Get the increment, which is incremented for every snowflake + * created over the one millisecond resolution in the timestamp. + * + * @return uint64_t millisecond increment + */ + uint16_t get_increment() const; +}; + +}; + +template<> +struct std::hash +{ + /** + * @brief Hashing function for dpp::slowflake + * Used by std::unordered_map. This just calls std::hash. + * + * @param s Snowflake value to hash + * @return std::size_t hash value + */ + std::size_t operator()(dpp::snowflake const& s) const noexcept { + return std::hash{}(s.value); + } +}; diff --git a/3rdParty/dpp/socket.h b/3rdParty/dpp/socket.h index 7f1ccc3fc1..21be6da1b7 100644 --- a/3rdParty/dpp/socket.h +++ b/3rdParty/dpp/socket.h @@ -1,30 +1,30 @@ -#pragma once - -#ifndef _WIN32 -#ifndef SOCKET -#define SOCKET int -#endif -#endif - -namespace dpp -{ - /** - * @brief Represents a socket file descriptor. - * This is used to ensure parity between windows and unix-like systems. - */ - typedef SOCKET socket; -} - -#ifndef SOCKET_ERROR -/** - * @brief Represents a socket in error state - */ -#define SOCKET_ERROR -1 -#endif - -#ifndef INVALID_SOCKET -/** - * @brief Represents a socket which is not yet assigned - */ -#define INVALID_SOCKET ~0 +#pragma once + +#ifndef _WIN32 +#ifndef SOCKET +#define SOCKET int +#endif +#endif + +namespace dpp +{ + /** + * @brief Represents a socket file descriptor. + * This is used to ensure parity between windows and unix-like systems. + */ + typedef SOCKET socket; +} + +#ifndef SOCKET_ERROR +/** + * @brief Represents a socket in error state + */ +#define SOCKET_ERROR -1 +#endif + +#ifndef INVALID_SOCKET +/** + * @brief Represents a socket which is not yet assigned + */ +#define INVALID_SOCKET ~0 #endif \ No newline at end of file diff --git a/3rdParty/dpp/sslclient.h b/3rdParty/dpp/sslclient.h index daf4a2b1dc..8d07048a5f 100644 --- a/3rdParty/dpp/sslclient.h +++ b/3rdParty/dpp/sslclient.h @@ -1,252 +1,252 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief This is an opaque class containing openssl library specific structures. - * We define it this way so that the public facing D++ library doesn't require - * the openssl headers be available to build against it. - */ -class openssl_connection; - -/** - * @brief A callback for socket status - */ -typedef std::function socket_callback_t; - -/** - * @brief A socket notification callback - */ -typedef std::function socket_notification_t; - -/** - * @brief Close a socket - * - * @param sfd Socket to close - * @return false on error, true on success - */ -bool close_socket(dpp::socket sfd); - -/** - * @brief Set a socket to blocking or non-blocking IO - * - * @param sockfd socket to act upon - * @return false on error, true on success - */ -bool set_nonblocking(dpp::socket sockfd, bool non_blocking); - -/** - * @brief Implements a simple non-blocking SSL stream client. - * - * @note although the design is non-blocking the run() method will - * execute in an infinite loop until the socket disconnects. This is intended - * to be run within a std::thread. - */ -class DPP_EXPORT ssl_client -{ -protected: - /** - * @brief Input buffer received from socket - */ - std::string buffer; - - /** - * @brief Output buffer for sending to socket - */ - std::string obuffer; - - /** - * @brief True if in nonblocking mode. The socket switches to nonblocking mode - * once ReadLoop is called. - */ - bool nonblocking; - - /** - * @brief Raw file descriptor of connection - */ - dpp::socket sfd; - - /** - * @brief Openssl opaque contexts - */ - openssl_connection* ssl; - - /** - * @brief SSL cipher in use - */ - std::string cipher; - - /** - * @brief For timers - */ - time_t last_tick; - - /** - * @brief Hostname connected to - */ - std::string hostname; - - /** - * @brief Port connected to - */ - std::string port; - - /** - * @brief Bytes out - */ - uint64_t bytes_out; - - /** - * @brief Bytes in - */ - uint64_t bytes_in; - - /** - * @brief True for a plain text connection - */ - bool plaintext; - - /** - * @brief True if we are establishing a new connection, false if otherwise. - */ - bool make_new; - - - /** - * @brief Called every second - */ - virtual void one_second_timer(); - - /** - * @brief Start SSL connection and connect to TCP endpoint - * @throw dpp::exception Failed to initialise connection - */ - virtual void connect(); -public: - /** - * @brief Get the bytes out objectGet total bytes sent - * @return uint64_t bytes sent - */ - uint64_t get_bytes_out(); - - /** - * @brief Get total bytes received - * @return uint64_t bytes received - */ - uint64_t get_bytes_in(); - - /** - * @brief Get SSL cipher name - * @return std::string ssl cipher name - */ - std::string get_cipher(); - - /** - * @brief Attaching an additional file descriptor to this function will send notifications when there is data to read. - * - * NOTE: Only hook this if you NEED it as it can increase CPU usage of the thread! - * Returning -1 means that you don't want to be notified. - */ - socket_callback_t custom_readable_fd; - - /** - * @brief Attaching an additional file descriptor to this function will send notifications when you are able to write - * to the socket. - * - * NOTE: Only hook this if you NEED it as it can increase CPU usage of the thread! You should toggle this - * to -1 when you do not have anything to write otherwise it'll keep triggering repeatedly (it is level triggered). - */ - socket_callback_t custom_writeable_fd; - - /** - * @brief This event will be called when you can read from the custom fd - */ - socket_notification_t custom_readable_ready; - - /** - * @brief This event will be called when you can write to a custom fd - */ - socket_notification_t custom_writeable_ready; - - /** - * @brief True if we are keeping the connection alive after it has finished - */ - bool keepalive; - - /** - * @brief Connect to a specified host and port. Throws std::runtime_error on fatal error. - * @param _hostname The hostname to connect to - * @param _port the Port number to connect to - * @param plaintext_downgrade Set to true to connect using plaintext only, without initialising SSL. - * @param reuse Attempt to reuse previous connections for this hostname and port, if available - * Note that no Discord endpoints will function when downgraded. This option is provided only for - * connection to non-Discord addresses such as within dpp::cluster::request(). - * @throw dpp::exception Failed to initialise connection - */ - ssl_client(const std::string &_hostname, const std::string &_port = "443", bool plaintext_downgrade = false, bool reuse = false); - - /** - * @brief Nonblocking I/O loop - * @throw std::exception Any std::exception (or derivative) thrown from read_loop() causes reconnection of the shard - */ - void read_loop(); - - /** - * @brief Destroy the ssl_client object - */ - virtual ~ssl_client(); - - /** - * @brief Handle input from the input buffer. This function will be called until - * all data in the buffer has been processed and the buffer is empty. - * @param buffer the buffer content. Will be modified removing any processed front elements - * @return bool True if the socket should remain connected - */ - virtual bool handle_buffer(std::string &buffer); - - /** - * @brief Write to the output buffer. - * @param data Data to be written to the buffer - * @note The data may not be written immediately and may be written at a later time to the socket. - */ - virtual void write(const std::string &data); - - /** - * @brief Close socket connection - */ - virtual void close(); - - /** - * @brief Log a message - * @param severity severity of log message - * @param msg Log message to send - */ - virtual void log(dpp::loglevel severity, const std::string &msg) const; -}; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief This is an opaque class containing openssl library specific structures. + * We define it this way so that the public facing D++ library doesn't require + * the openssl headers be available to build against it. + */ +class openssl_connection; + +/** + * @brief A callback for socket status + */ +typedef std::function socket_callback_t; + +/** + * @brief A socket notification callback + */ +typedef std::function socket_notification_t; + +/** + * @brief Close a socket + * + * @param sfd Socket to close + * @return false on error, true on success + */ +bool close_socket(dpp::socket sfd); + +/** + * @brief Set a socket to blocking or non-blocking IO + * + * @param sockfd socket to act upon + * @return false on error, true on success + */ +bool set_nonblocking(dpp::socket sockfd, bool non_blocking); + +/** + * @brief Implements a simple non-blocking SSL stream client. + * + * @note although the design is non-blocking the run() method will + * execute in an infinite loop until the socket disconnects. This is intended + * to be run within a std::thread. + */ +class DPP_EXPORT ssl_client +{ +protected: + /** + * @brief Input buffer received from socket + */ + std::string buffer; + + /** + * @brief Output buffer for sending to socket + */ + std::string obuffer; + + /** + * @brief True if in nonblocking mode. The socket switches to nonblocking mode + * once ReadLoop is called. + */ + bool nonblocking; + + /** + * @brief Raw file descriptor of connection + */ + dpp::socket sfd; + + /** + * @brief Openssl opaque contexts + */ + openssl_connection* ssl; + + /** + * @brief SSL cipher in use + */ + std::string cipher; + + /** + * @brief For timers + */ + time_t last_tick; + + /** + * @brief Hostname connected to + */ + std::string hostname; + + /** + * @brief Port connected to + */ + std::string port; + + /** + * @brief Bytes out + */ + uint64_t bytes_out; + + /** + * @brief Bytes in + */ + uint64_t bytes_in; + + /** + * @brief True for a plain text connection + */ + bool plaintext; + + /** + * @brief True if we are establishing a new connection, false if otherwise. + */ + bool make_new; + + + /** + * @brief Called every second + */ + virtual void one_second_timer(); + + /** + * @brief Start SSL connection and connect to TCP endpoint + * @throw dpp::exception Failed to initialise connection + */ + virtual void connect(); +public: + /** + * @brief Get the bytes out objectGet total bytes sent + * @return uint64_t bytes sent + */ + uint64_t get_bytes_out(); + + /** + * @brief Get total bytes received + * @return uint64_t bytes received + */ + uint64_t get_bytes_in(); + + /** + * @brief Get SSL cipher name + * @return std::string ssl cipher name + */ + std::string get_cipher(); + + /** + * @brief Attaching an additional file descriptor to this function will send notifications when there is data to read. + * + * NOTE: Only hook this if you NEED it as it can increase CPU usage of the thread! + * Returning -1 means that you don't want to be notified. + */ + socket_callback_t custom_readable_fd; + + /** + * @brief Attaching an additional file descriptor to this function will send notifications when you are able to write + * to the socket. + * + * NOTE: Only hook this if you NEED it as it can increase CPU usage of the thread! You should toggle this + * to -1 when you do not have anything to write otherwise it'll keep triggering repeatedly (it is level triggered). + */ + socket_callback_t custom_writeable_fd; + + /** + * @brief This event will be called when you can read from the custom fd + */ + socket_notification_t custom_readable_ready; + + /** + * @brief This event will be called when you can write to a custom fd + */ + socket_notification_t custom_writeable_ready; + + /** + * @brief True if we are keeping the connection alive after it has finished + */ + bool keepalive; + + /** + * @brief Connect to a specified host and port. Throws std::runtime_error on fatal error. + * @param _hostname The hostname to connect to + * @param _port the Port number to connect to + * @param plaintext_downgrade Set to true to connect using plaintext only, without initialising SSL. + * @param reuse Attempt to reuse previous connections for this hostname and port, if available + * Note that no Discord endpoints will function when downgraded. This option is provided only for + * connection to non-Discord addresses such as within dpp::cluster::request(). + * @throw dpp::exception Failed to initialise connection + */ + ssl_client(const std::string &_hostname, const std::string &_port = "443", bool plaintext_downgrade = false, bool reuse = false); + + /** + * @brief Nonblocking I/O loop + * @throw std::exception Any std::exception (or derivative) thrown from read_loop() causes reconnection of the shard + */ + void read_loop(); + + /** + * @brief Destroy the ssl_client object + */ + virtual ~ssl_client(); + + /** + * @brief Handle input from the input buffer. This function will be called until + * all data in the buffer has been processed and the buffer is empty. + * @param buffer the buffer content. Will be modified removing any processed front elements + * @return bool True if the socket should remain connected + */ + virtual bool handle_buffer(std::string &buffer); + + /** + * @brief Write to the output buffer. + * @param data Data to be written to the buffer + * @note The data may not be written immediately and may be written at a later time to the socket. + */ + virtual void write(const std::string &data); + + /** + * @brief Close socket connection + */ + virtual void close(); + + /** + * @brief Log a message + * @param severity severity of log message + * @param msg Log message to send + */ + virtual void log(dpp::loglevel severity, const std::string &msg) const; +}; + +}; diff --git a/3rdParty/dpp/stage_instance.h b/3rdParty/dpp/stage_instance.h index 90a134f9eb..6137320348 100644 --- a/3rdParty/dpp/stage_instance.h +++ b/3rdParty/dpp/stage_instance.h @@ -1,86 +1,86 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Represents the privacy of a stage instance - */ -enum stage_privacy_level : uint8_t { - /// The Stage instance is visible publicly, such as on Stage Discovery. - sp_public = 1, - /// The Stage instance is visible to only guild members. - sp_guild_only = 2 -}; - -/** - * @brief A stage instance. - * Stage instances are like a conference facility, with moderators/speakers and listeners. - */ -struct DPP_EXPORT stage_instance : public managed, public json_interface { - /// The guild id of the associated Stage channel - snowflake guild_id; - /// The id of the associated Stage channel - snowflake channel_id; - /// The topic of the Stage instance (1-120 characters) - std::string topic; - /// The privacy level of the Stage instance - stage_privacy_level privacy_level; - /// Whether or not Stage Discovery is disabled - bool discoverable_disabled; - - /** - * @brief Create a stage_instance object - */ - stage_instance(); - - /** - * @brief Destroy the stage_instance object - */ - ~stage_instance() = default; - - /** - * @brief Serialise a stage_instance object rom json - * - * @return stage_instance& a reference to self - */ - stage_instance& fill_from_json(const nlohmann::json* j); - - /** - * @brief Build json for this object - * - * @param with_id include ID - * @return std::string Dumped json of this object - */ - virtual std::string build_json(bool with_id = false) const; -}; - -/** A group of stage instances */ -typedef std::unordered_map stage_instance_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Represents the privacy of a stage instance + */ +enum stage_privacy_level : uint8_t { + /// The Stage instance is visible publicly, such as on Stage Discovery. + sp_public = 1, + /// The Stage instance is visible to only guild members. + sp_guild_only = 2 +}; + +/** + * @brief A stage instance. + * Stage instances are like a conference facility, with moderators/speakers and listeners. + */ +struct DPP_EXPORT stage_instance : public managed, public json_interface { + /// The guild id of the associated Stage channel + snowflake guild_id; + /// The id of the associated Stage channel + snowflake channel_id; + /// The topic of the Stage instance (1-120 characters) + std::string topic; + /// The privacy level of the Stage instance + stage_privacy_level privacy_level; + /// Whether or not Stage Discovery is disabled + bool discoverable_disabled; + + /** + * @brief Create a stage_instance object + */ + stage_instance(); + + /** + * @brief Destroy the stage_instance object + */ + ~stage_instance() = default; + + /** + * @brief Serialise a stage_instance object rom json + * + * @return stage_instance& a reference to self + */ + stage_instance& fill_from_json(const nlohmann::json* j); + + /** + * @brief Build json for this object + * + * @param with_id include ID + * @return std::string Dumped json of this object + */ + virtual std::string build_json(bool with_id = false) const; +}; + +/** A group of stage instances */ +typedef std::unordered_map stage_instance_map; + +}; diff --git a/3rdParty/dpp/stringops.h b/3rdParty/dpp/stringops.h index 856ff30103..c749f1f370 100644 --- a/3rdParty/dpp/stringops.h +++ b/3rdParty/dpp/stringops.h @@ -1,212 +1,212 @@ -/************************************************************************************ - * - * D++ - A Lightweight C++ Library for Discord - * - * stringops.h taken from TriviaBot - * - * Copyright 2004 Craig Edwards - * - * Core based on Sporks, the Learning Discord Bot, Craig Edwards (c) 2019. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once -#include -#include -#include -#include -#include -#include - -namespace dpp { -/** - * @brief Convert a string to lowercase using tolower() - * - * @tparam T type of string - * @param s String to lowercase - * @return std::basic_string lowercased string - */ -template std::basic_string lowercase(const std::basic_string& s) -{ - std::basic_string s2 = s; - std::transform(s2.begin(), s2.end(), s2.begin(), tolower); - return s2; -} - -/** - * @brief Convert a string to uppercase using toupper() - * - * @tparam T type of string - * @param s String to uppercase - * @return std::basic_string uppercased string - */ -template std::basic_string uppercase(const std::basic_string& s) -{ - std::basic_string s2 = s; - std::transform(s2.begin(), s2.end(), s2.begin(), toupper); - return s2; -} - -/** - * @brief trim from end of string (right) - * - * @param s String to trim - * @return std::string trimmed string - */ -inline std::string rtrim(std::string s) -{ - s.erase(s.find_last_not_of(" \t\n\r\f\v") + 1); - return s; -} - -/** - * @brief trim from beginning of string (left) - * - * @param s string to trim - * @return std::string trimmed string - */ -inline std::string ltrim(std::string s) -{ - s.erase(0, s.find_first_not_of(" \t\n\r\f\v")); - return s; -} - -/** - * @brief Trim from both ends of string (right then left) - * - * @param s string to trim - * @return std::string trimmed string - */ -inline std::string trim(std::string s) -{ - return ltrim(rtrim(s)); -} - -/** - * @brief Add commas to a string (or dots) based on current locale server-side - * - * @tparam T type of numeric value - * @param value Value - * @return std::string number with commas added - */ -template std::string comma(T value) -{ - std::stringstream ss; - ss.imbue(std::locale("")); - ss << std::fixed << value; - return ss.str(); -} - -/** - * @brief Convert any value from a string to another type using stringstream. - * The optional second parameter indicates the format of the input string, - * e.g. std::dec for decimal, std::hex for hex, std::oct for octal. - * - * @tparam T Type to convert to - * @param s String to convert from - * @param f Numeric base, e.g. `std::dec` or `std::hex` - * @return T Returned numeric value - */ -template T from_string(const std::string &s, std::ios_base & (*f)(std::ios_base&)) -{ - T t; - std::istringstream iss(s); - iss >> f, iss >> t; - return t; -} - -/** - * @brief Convert any value from a string to another type using stringstream. - * - * @tparam T Type to convert to - * @param s String to convert from - * @return T Returned numeric value - * - * @note Base 10 for numeric conversions. - */ -template T from_string(const std::string &s) -{ - T t; - std::istringstream iss(s); - iss >> t; - return t; -} - -/** - * @brief Specialised conversion of uint64_t from string - * - * @tparam int64_t - * @param s string to convert - * @return uint64_t return value - */ -template uint64_t from_string(const std::string &s) -{ - return std::stoull(s, 0, 10); -} - -/** - * @brief Specialised conversion of uint32_t from string - * - * @tparam uint32_t - * @param s string to convert - * @return uint32_t return value - */ -template uint32_t from_string(const std::string &s) -{ - return std::stoul(s, 0, 10); -} - -/** - * @brief Specialised conversion of int from string - * - * @tparam int - * @param s string to convert - * @return int return value - */ -template int from_string(const std::string &s) -{ - return std::stoi(s, 0, 10); -} - -/** - * @brief Convert a numeric value to hex - * - * @tparam T numeric type - * @param i numeric value - * @return std::string value in hex, the length will be 2* the raw size of the type - */ -template std::string to_hex(T i) -{ - std::stringstream stream; - stream << std::setfill('0') << std::setw(sizeof(T)*2) << std::hex << i; - return stream.str(); -} - -/** - * @brief Format a numeric type as a string with leading zeroes - * - * @tparam T numeric type - * @param i numeric value - * @param width width of type including the leading zeroes - * @return std::string resultant string with leading zeroes - */ -template std::string leading_zeroes(T i, size_t width) -{ - std::stringstream stream; - stream << std::setfill('0') << std::setw(width) << std::dec << i; - return stream.str(); -} - -}; +/************************************************************************************ + * + * D++ - A Lightweight C++ Library for Discord + * + * stringops.h taken from TriviaBot + * + * Copyright 2004 Craig Edwards + * + * Core based on Sporks, the Learning Discord Bot, Craig Edwards (c) 2019. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include +#include +#include + +namespace dpp { +/** + * @brief Convert a string to lowercase using tolower() + * + * @tparam T type of string + * @param s String to lowercase + * @return std::basic_string lowercased string + */ +template std::basic_string lowercase(const std::basic_string& s) +{ + std::basic_string s2 = s; + std::transform(s2.begin(), s2.end(), s2.begin(), tolower); + return s2; +} + +/** + * @brief Convert a string to uppercase using toupper() + * + * @tparam T type of string + * @param s String to uppercase + * @return std::basic_string uppercased string + */ +template std::basic_string uppercase(const std::basic_string& s) +{ + std::basic_string s2 = s; + std::transform(s2.begin(), s2.end(), s2.begin(), toupper); + return s2; +} + +/** + * @brief trim from end of string (right) + * + * @param s String to trim + * @return std::string trimmed string + */ +inline std::string rtrim(std::string s) +{ + s.erase(s.find_last_not_of(" \t\n\r\f\v") + 1); + return s; +} + +/** + * @brief trim from beginning of string (left) + * + * @param s string to trim + * @return std::string trimmed string + */ +inline std::string ltrim(std::string s) +{ + s.erase(0, s.find_first_not_of(" \t\n\r\f\v")); + return s; +} + +/** + * @brief Trim from both ends of string (right then left) + * + * @param s string to trim + * @return std::string trimmed string + */ +inline std::string trim(std::string s) +{ + return ltrim(rtrim(s)); +} + +/** + * @brief Add commas to a string (or dots) based on current locale server-side + * + * @tparam T type of numeric value + * @param value Value + * @return std::string number with commas added + */ +template std::string comma(T value) +{ + std::stringstream ss; + ss.imbue(std::locale("")); + ss << std::fixed << value; + return ss.str(); +} + +/** + * @brief Convert any value from a string to another type using stringstream. + * The optional second parameter indicates the format of the input string, + * e.g. std::dec for decimal, std::hex for hex, std::oct for octal. + * + * @tparam T Type to convert to + * @param s String to convert from + * @param f Numeric base, e.g. `std::dec` or `std::hex` + * @return T Returned numeric value + */ +template T from_string(const std::string &s, std::ios_base & (*f)(std::ios_base&)) +{ + T t; + std::istringstream iss(s); + iss >> f, iss >> t; + return t; +} + +/** + * @brief Convert any value from a string to another type using stringstream. + * + * @tparam T Type to convert to + * @param s String to convert from + * @return T Returned numeric value + * + * @note Base 10 for numeric conversions. + */ +template T from_string(const std::string &s) +{ + T t; + std::istringstream iss(s); + iss >> t; + return t; +} + +/** + * @brief Specialised conversion of uint64_t from string + * + * @tparam int64_t + * @param s string to convert + * @return uint64_t return value + */ +template uint64_t from_string(const std::string &s) +{ + return std::stoull(s, 0, 10); +} + +/** + * @brief Specialised conversion of uint32_t from string + * + * @tparam uint32_t + * @param s string to convert + * @return uint32_t return value + */ +template uint32_t from_string(const std::string &s) +{ + return std::stoul(s, 0, 10); +} + +/** + * @brief Specialised conversion of int from string + * + * @tparam int + * @param s string to convert + * @return int return value + */ +template int from_string(const std::string &s) +{ + return std::stoi(s, 0, 10); +} + +/** + * @brief Convert a numeric value to hex + * + * @tparam T numeric type + * @param i numeric value + * @return std::string value in hex, the length will be 2* the raw size of the type + */ +template std::string to_hex(T i) +{ + std::stringstream stream; + stream << std::setfill('0') << std::setw(sizeof(T)*2) << std::hex << i; + return stream.str(); +} + +/** + * @brief Format a numeric type as a string with leading zeroes + * + * @tparam T numeric type + * @param i numeric value + * @param width width of type including the leading zeroes + * @return std::string resultant string with leading zeroes + */ +template std::string leading_zeroes(T i, size_t width) +{ + std::stringstream stream; + stream << std::setfill('0') << std::setw(width) << std::dec << i; + return stream.str(); +} + +}; diff --git a/3rdParty/dpp/sync.h b/3rdParty/dpp/sync.h index a837103782..e4d278fb5b 100644 --- a/3rdParty/dpp/sync.h +++ b/3rdParty/dpp/sync.h @@ -1,80 +1,80 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2022 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include - -namespace dpp { - - /** - * @brief Call a D++ REST function synchronously. - * - * Synchronously calling a REST function means *IT WILL BLOCK* - This is a Bad Thing™ and strongly discouraged. - * There are very few circumstances you actually need this. If you do need to use this, you'll know it. - * - * Example: - * - * ```cpp - * dpp::message m = dpp::sync(&bot, &dpp::cluster::message_create, dpp::message(channel_id, "moo.")); - * ``` - * - * @warning As previously mentioned, this template will block. It is ill-advised to call this outside of - * a separate thread and this should never be directly used in any event such as dpp::cluster::on_interaction_create! - * @tparam T type of expected return value, should match up with the method called - * @tparam F Type of class method in dpp::cluster to call. - * @tparam Ts Function parameters in method call - * @param c A pointer to dpp::cluster object - * @param func pointer to class method in dpp::cluster to call. This can call any - * dpp::cluster member function who's last parameter is a dpp::command_completion_event_t callback type. - * @param args Zero or more arguments for the method call - * @return An instantiated object of type T - * @throw dpp::rest_exception On failure of the method call, an exception is thrown - */ - template T sync(class cluster* c, F func, Ts&&... args) { - std::promise _p; - std::future _f = _p.get_future(); - /* (obj ->* func) is the obscure syntax for calling a method pointer on an object instance */ - (c ->* func)(std::forward(args)..., [&_p](const auto& cc) { - try { - if (cc.is_error()) { - throw dpp::rest_exception(cc.get_error().message); - } else { - try { - _p.set_value(std::get(cc.value)); - } catch (const std::exception& e) { - throw dpp::rest_exception(e.what()); - } - } - } catch (const dpp::rest_exception&) { - _p.set_exception(std::current_exception()); - } - }); - - /* Blocking calling thread until rest request is completed. - * Exceptions encountered on the other thread are re-thrown. - */ - return _f.get(); - } - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2022 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include + +namespace dpp { + + /** + * @brief Call a D++ REST function synchronously. + * + * Synchronously calling a REST function means *IT WILL BLOCK* - This is a Bad Thing™ and strongly discouraged. + * There are very few circumstances you actually need this. If you do need to use this, you'll know it. + * + * Example: + * + * ```cpp + * dpp::message m = dpp::sync(&bot, &dpp::cluster::message_create, dpp::message(channel_id, "moo.")); + * ``` + * + * @warning As previously mentioned, this template will block. It is ill-advised to call this outside of + * a separate thread and this should never be directly used in any event such as dpp::cluster::on_interaction_create! + * @tparam T type of expected return value, should match up with the method called + * @tparam F Type of class method in dpp::cluster to call. + * @tparam Ts Function parameters in method call + * @param c A pointer to dpp::cluster object + * @param func pointer to class method in dpp::cluster to call. This can call any + * dpp::cluster member function who's last parameter is a dpp::command_completion_event_t callback type. + * @param args Zero or more arguments for the method call + * @return An instantiated object of type T + * @throw dpp::rest_exception On failure of the method call, an exception is thrown + */ + template T sync(class cluster* c, F func, Ts&&... args) { + std::promise _p; + std::future _f = _p.get_future(); + /* (obj ->* func) is the obscure syntax for calling a method pointer on an object instance */ + (c ->* func)(std::forward(args)..., [&_p](const auto& cc) { + try { + if (cc.is_error()) { + throw dpp::rest_exception(cc.get_error().message); + } else { + try { + _p.set_value(std::get(cc.value)); + } catch (const std::exception& e) { + throw dpp::rest_exception(e.what()); + } + } + } catch (const dpp::rest_exception&) { + _p.set_exception(std::current_exception()); + } + }); + + /* Blocking calling thread until rest request is completed. + * Exceptions encountered on the other thread are re-thrown. + */ + return _f.get(); + } + +}; diff --git a/3rdParty/dpp/sysdep.h b/3rdParty/dpp/sysdep.h index 8971c30870..d706d7b8f5 100644 --- a/3rdParty/dpp/sysdep.h +++ b/3rdParty/dpp/sysdep.h @@ -1,120 +1,120 @@ -/* - * Discord erlpack - tidied up for D++, Craig Edwards 2021. - * - * MessagePack system dependencies modified for erlpack. - * - * Copyright (C) 2008-2010 FURUHASHI Sadayuki - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#pragma once - -#include -#include -#include -#include -#if defined(__linux__) -#include -#endif - -#ifdef _WIN32 - -#ifdef __cplusplus -/* numeric_limits::min,max */ -#ifdef max -#undef max -#endif -#ifdef min -#undef min -#endif -#endif - -#else -#include /* __BYTE_ORDER */ -#endif - -#if !defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__) -#if __BYTE_ORDER == __LITTLE_ENDIAN -#define __LITTLE_ENDIAN__ -#elif __BYTE_ORDER == __BIG_ENDIAN -#define __BIG_ENDIAN__ -#elif _WIN32 -#define __LITTLE_ENDIAN__ -#endif -#endif - - -#ifdef __LITTLE_ENDIAN__ - -#ifdef _WIN32 -# if defined(ntohs) -# define etf_byte_order_16(x) ntohs(x) -# elif defined(_byteswap_ushort) || (defined(_MSC_VER) && _MSC_VER >= 1400) -# define etf_byte_order_16(x) ((uint16_t)_byteswap_ushort((unsigned short)x)) -# else -# define etf_byte_order_16(x) ( \ - ((((uint16_t)x) << 8) ) | \ - ((((uint16_t)x) >> 8) ) ) -# endif -#else -# define etf_byte_order_16(x) ntohs(x) -#endif - -#ifdef _WIN32 -# if defined(ntohl) -# define etf_byte_order_32(x) ntohl(x) -# elif defined(_byteswap_ulong) || (defined(_MSC_VER) && _MSC_VER >= 1400) -# define etf_byte_order_32(x) ((uint32_t)_byteswap_ulong((unsigned long)x)) -# else -# define etf_byte_order_32(x) \ - ( ((((uint32_t)x) << 24) ) | \ - ((((uint32_t)x) << 8) & 0x00ff0000U ) | \ - ((((uint32_t)x) >> 8) & 0x0000ff00U ) | \ - ((((uint32_t)x) >> 24) ) ) -# endif -#else -# define etf_byte_order_32(x) ntohl(x) -#endif - -#if defined(_byteswap_uint64) || (defined(_MSC_VER) && _MSC_VER >= 1400) -# define etf_byte_order_64(x) (_byteswap_uint64(x)) -#elif defined(bswap_64) -# define etf_byte_order_64(x) bswap_64(x) -#elif defined(__DARWIN_OSSwapInt64) -# define etf_byte_order_64(x) __DARWIN_OSSwapInt64(x) -#elif defined(__linux__) -# define etf_byte_order_64(x) be64toh(x) -#else -# define etf_byte_order_64(x) \ - ( ((((uint64_t)x) << 56) ) | \ - ((((uint64_t)x) << 40) & 0x00ff000000000000ULL ) | \ - ((((uint64_t)x) << 24) & 0x0000ff0000000000ULL ) | \ - ((((uint64_t)x) << 8) & 0x000000ff00000000ULL ) | \ - ((((uint64_t)x) >> 8) & 0x00000000ff000000ULL ) | \ - ((((uint64_t)x) >> 24) & 0x0000000000ff0000ULL ) | \ - ((((uint64_t)x) >> 40) & 0x000000000000ff00ULL ) | \ - ((((uint64_t)x) >> 56) ) ) -#endif - -#else -#define etf_byte_order_16(x) (x) -#define etf_byte_order_32(x) (x) -#define etf_byte_order_64(x) (x) -#endif - -#define store_16_bits(to, num) \ - do { uint16_t val = etf_byte_order_16(num); memcpy(to, &val, 2); } while(0) -#define store_32_bits(to, num) \ - do { uint32_t val = etf_byte_order_32(num); memcpy(to, &val, 4); } while(0) -#define store_64_bits(to, num) \ - do { uint64_t val = etf_byte_order_64(num); memcpy(to, &val, 8); } while(0) +/* + * Discord erlpack - tidied up for D++, Craig Edwards 2021. + * + * MessagePack system dependencies modified for erlpack. + * + * Copyright (C) 2008-2010 FURUHASHI Sadayuki + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#pragma once + +#include +#include +#include +#include +#if defined(__linux__) +#include +#endif + +#ifdef _WIN32 + +#ifdef __cplusplus +/* numeric_limits::min,max */ +#ifdef max +#undef max +#endif +#ifdef min +#undef min +#endif +#endif + +#else +#include /* __BYTE_ORDER */ +#endif + +#if !defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__) +#if __BYTE_ORDER == __LITTLE_ENDIAN +#define __LITTLE_ENDIAN__ +#elif __BYTE_ORDER == __BIG_ENDIAN +#define __BIG_ENDIAN__ +#elif _WIN32 +#define __LITTLE_ENDIAN__ +#endif +#endif + + +#ifdef __LITTLE_ENDIAN__ + +#ifdef _WIN32 +# if defined(ntohs) +# define etf_byte_order_16(x) ntohs(x) +# elif defined(_byteswap_ushort) || (defined(_MSC_VER) && _MSC_VER >= 1400) +# define etf_byte_order_16(x) ((uint16_t)_byteswap_ushort((unsigned short)x)) +# else +# define etf_byte_order_16(x) ( \ + ((((uint16_t)x) << 8) ) | \ + ((((uint16_t)x) >> 8) ) ) +# endif +#else +# define etf_byte_order_16(x) ntohs(x) +#endif + +#ifdef _WIN32 +# if defined(ntohl) +# define etf_byte_order_32(x) ntohl(x) +# elif defined(_byteswap_ulong) || (defined(_MSC_VER) && _MSC_VER >= 1400) +# define etf_byte_order_32(x) ((uint32_t)_byteswap_ulong((unsigned long)x)) +# else +# define etf_byte_order_32(x) \ + ( ((((uint32_t)x) << 24) ) | \ + ((((uint32_t)x) << 8) & 0x00ff0000U ) | \ + ((((uint32_t)x) >> 8) & 0x0000ff00U ) | \ + ((((uint32_t)x) >> 24) ) ) +# endif +#else +# define etf_byte_order_32(x) ntohl(x) +#endif + +#if defined(_byteswap_uint64) || (defined(_MSC_VER) && _MSC_VER >= 1400) +# define etf_byte_order_64(x) (_byteswap_uint64(x)) +#elif defined(bswap_64) +# define etf_byte_order_64(x) bswap_64(x) +#elif defined(__DARWIN_OSSwapInt64) +# define etf_byte_order_64(x) __DARWIN_OSSwapInt64(x) +#elif defined(__linux__) +# define etf_byte_order_64(x) be64toh(x) +#else +# define etf_byte_order_64(x) \ + ( ((((uint64_t)x) << 56) ) | \ + ((((uint64_t)x) << 40) & 0x00ff000000000000ULL ) | \ + ((((uint64_t)x) << 24) & 0x0000ff0000000000ULL ) | \ + ((((uint64_t)x) << 8) & 0x000000ff00000000ULL ) | \ + ((((uint64_t)x) >> 8) & 0x00000000ff000000ULL ) | \ + ((((uint64_t)x) >> 24) & 0x0000000000ff0000ULL ) | \ + ((((uint64_t)x) >> 40) & 0x000000000000ff00ULL ) | \ + ((((uint64_t)x) >> 56) ) ) +#endif + +#else +#define etf_byte_order_16(x) (x) +#define etf_byte_order_32(x) (x) +#define etf_byte_order_64(x) (x) +#endif + +#define store_16_bits(to, num) \ + do { uint16_t val = etf_byte_order_16(num); memcpy(to, &val, 2); } while(0) +#define store_32_bits(to, num) \ + do { uint32_t val = etf_byte_order_32(num); memcpy(to, &val, 4); } while(0) +#define store_64_bits(to, num) \ + do { uint64_t val = etf_byte_order_64(num); memcpy(to, &val, 8); } while(0) diff --git a/3rdParty/dpp/timed_listener.h b/3rdParty/dpp/timed_listener.h index 467f0046e0..2316a7797a 100644 --- a/3rdParty/dpp/timed_listener.h +++ b/3rdParty/dpp/timed_listener.h @@ -1,95 +1,95 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief A timed_listener is a way to temporarily attach to an event for a specific timeframe, then detach when complete. - * A lambda may also be optionally called when the timeout is reached. Destructing the timed_listener detaches any attached - * event listeners, and cancels any created timers, but does not call any timeout lambda. - * - * @tparam attached_event Event within cluster to attach to within the cluster::dispatch member (dpp::dispatcher object) - * @tparam listening_function Definition of lambda function that matches up with the attached_event. - */ -template class timed_listener -{ -private: - /// Owning cluster - cluster* owner; - - /// Duration of listen - time_t duration; - - /// Reference to attached event in cluster - //event_router_t on_thread_member_update; - attached_event& ev; - - /// Timer handle - timer th; - - /// Event handle - event_handle listener_handle; - -public: - /** - * @brief Construct a new timed listener object - * - * @param cl Owning cluster - * @param _duration Duration of timed event in seconds - * @param event Event to hook, e.g. cluster.on_message_create - * @param on_end An optional void() lambda to trigger when the timed_listener times out. - * Calling the destructor before the timeout is reached does not call this lambda. - * @param listener Lambda to receive events. Type must match up properly with that passed into the 'event' parameter. - */ - timed_listener(cluster* cl, uint64_t _duration, attached_event& event, listening_function listener, timer_callback_t on_end = {}) - : owner(cl), duration(_duration), ev(event) - { - /* Attach event */ - listener_handle = ev(listener); - /* Create timer */ - th = cl->start_timer([this](dpp::timer timer_handle) { - /* Timer has finished, detach it from event. - * Only allowed to tick once. - */ - ev.detach(listener_handle); - owner->stop_timer(th); - }, duration, on_end); - } - - /** - * @brief Destroy the timed listener object - */ - ~timed_listener() { - /* Stop timer and detach event, but do not call on_end */ - ev.detach(listener_handle); - owner->stop_timer(th); - } -}; - +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief A timed_listener is a way to temporarily attach to an event for a specific timeframe, then detach when complete. + * A lambda may also be optionally called when the timeout is reached. Destructing the timed_listener detaches any attached + * event listeners, and cancels any created timers, but does not call any timeout lambda. + * + * @tparam attached_event Event within cluster to attach to within the cluster::dispatch member (dpp::dispatcher object) + * @tparam listening_function Definition of lambda function that matches up with the attached_event. + */ +template class timed_listener +{ +private: + /// Owning cluster + cluster* owner; + + /// Duration of listen + time_t duration; + + /// Reference to attached event in cluster + //event_router_t on_thread_member_update; + attached_event& ev; + + /// Timer handle + timer th; + + /// Event handle + event_handle listener_handle; + +public: + /** + * @brief Construct a new timed listener object + * + * @param cl Owning cluster + * @param _duration Duration of timed event in seconds + * @param event Event to hook, e.g. cluster.on_message_create + * @param on_end An optional void() lambda to trigger when the timed_listener times out. + * Calling the destructor before the timeout is reached does not call this lambda. + * @param listener Lambda to receive events. Type must match up properly with that passed into the 'event' parameter. + */ + timed_listener(cluster* cl, uint64_t _duration, attached_event& event, listening_function listener, timer_callback_t on_end = {}) + : owner(cl), duration(_duration), ev(event) + { + /* Attach event */ + listener_handle = ev(listener); + /* Create timer */ + th = cl->start_timer([this](dpp::timer timer_handle) { + /* Timer has finished, detach it from event. + * Only allowed to tick once. + */ + ev.detach(listener_handle); + owner->stop_timer(th); + }, duration, on_end); + } + + /** + * @brief Destroy the timed listener object + */ + ~timed_listener() { + /* Stop timer and detach event, but do not call on_end */ + ev.detach(listener_handle); + owner->stop_timer(th); + } +}; + }; \ No newline at end of file diff --git a/3rdParty/dpp/timer.h b/3rdParty/dpp/timer.h index 92c5a05db1..fdc8b536b6 100644 --- a/3rdParty/dpp/timer.h +++ b/3rdParty/dpp/timer.h @@ -1,124 +1,124 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Represents a timer handle. - * Returned from cluster::start_timer and used by cluster::stop_timer. - * This is obtained from a simple incrementing value, internally. - */ -typedef size_t timer; - -/** - * @brief The type for a timer callback - */ -typedef std::function timer_callback_t; - -/** - * @brief Used internally to store state of active timers - */ -struct DPP_EXPORT timer_t { - /** - * @brief Timer handle - */ - timer handle; - /** - * @brief Next timer tick as unix epoch - */ - time_t next_tick; - /** - * @brief Frequency between ticks - */ - uint64_t frequency; - /** - * @brief Lambda to call on tick - */ - timer_callback_t on_tick; - /** - * @brief Lambda to call on stop (optional) - */ - timer_callback_t on_stop; -}; - -/** - * @brief A map of timers, ordered by earliest first so that map::begin() is always the - * soonest to be due. - */ -typedef std::multimap timer_next_t; - -/** - * @brief A map of timers stored by handle - */ -typedef std::unordered_map timer_reg_t; - -/** - * @brief Trigger a timed event once. - * The provided callback is called only once. - */ -class DPP_EXPORT oneshot_timer -{ -private: - /// Owning cluster - class cluster* owner; - /// Timer handle - timer th; -public: - /** - * @brief Construct a new oneshot timer object - * - * @param cl cluster owner - * @param duration duration before firing - * @param callback callback to call on firing - */ - oneshot_timer(class cluster* cl, uint64_t duration, timer_callback_t callback); - - /** - * @brief Get the handle for the created one-shot timer - * - * @return timer handle for use with stop_timer - */ - timer get_handle(); - - /** - * @brief Cancel the one shot timer immediately. - * Callback function is not called. - */ - void cancel(); - - /** - * @brief Destroy the oneshot timer object - */ - ~oneshot_timer(); -}; - - - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Represents a timer handle. + * Returned from cluster::start_timer and used by cluster::stop_timer. + * This is obtained from a simple incrementing value, internally. + */ +typedef size_t timer; + +/** + * @brief The type for a timer callback + */ +typedef std::function timer_callback_t; + +/** + * @brief Used internally to store state of active timers + */ +struct DPP_EXPORT timer_t { + /** + * @brief Timer handle + */ + timer handle; + /** + * @brief Next timer tick as unix epoch + */ + time_t next_tick; + /** + * @brief Frequency between ticks + */ + uint64_t frequency; + /** + * @brief Lambda to call on tick + */ + timer_callback_t on_tick; + /** + * @brief Lambda to call on stop (optional) + */ + timer_callback_t on_stop; +}; + +/** + * @brief A map of timers, ordered by earliest first so that map::begin() is always the + * soonest to be due. + */ +typedef std::multimap timer_next_t; + +/** + * @brief A map of timers stored by handle + */ +typedef std::unordered_map timer_reg_t; + +/** + * @brief Trigger a timed event once. + * The provided callback is called only once. + */ +class DPP_EXPORT oneshot_timer +{ +private: + /// Owning cluster + class cluster* owner; + /// Timer handle + timer th; +public: + /** + * @brief Construct a new oneshot timer object + * + * @param cl cluster owner + * @param duration duration before firing + * @param callback callback to call on firing + */ + oneshot_timer(class cluster* cl, uint64_t duration, timer_callback_t callback); + + /** + * @brief Get the handle for the created one-shot timer + * + * @return timer handle for use with stop_timer + */ + timer get_handle(); + + /** + * @brief Cancel the one shot timer immediately. + * Callback function is not called. + */ + void cancel(); + + /** + * @brief Destroy the oneshot timer object + */ + ~oneshot_timer(); +}; + + + +}; diff --git a/3rdParty/dpp/user.h b/3rdParty/dpp/user.h index 4ff03664cd..c582f443c3 100644 --- a/3rdParty/dpp/user.h +++ b/3rdParty/dpp/user.h @@ -1,371 +1,371 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Various bitmask flags used to represent information about a dpp::user - */ -enum user_flags : uint32_t { - /// User is a bot - u_bot = 0b00000000000000000000001, - /// User is a system user (Clyde!) - u_system = 0b00000000000000000000010, - /// User has multi-factor authentication enabled - u_mfa_enabled = 0b00000000000000000000100, - /// User is verified (verified email address) - u_verified = 0b00000000000000000001000, - /// User has full nitro - u_nitro_full = 0b00000000000000000010000, - /// User has nitro classic - u_nitro_classic = 0b00000000000000000100000, - /// User is discord staff - u_discord_employee = 0b00000000000000001000000, - /// User owns a partnered server - u_partnered_owner = 0b00000000000000010000000, - /// User is a member of hypesquad events - u_hypesquad_events = 0b00000000000000100000000, - /// User has BugHunter level 1 - u_bughunter_1 = 0b00000000000001000000000, - /// User is a member of House Bravery - u_house_bravery = 0b00000000000010000000000, - /// User is a member of House Brilliance - u_house_brilliance = 0b00000000000100000000000, - /// User is a member of House Balance - u_house_balance = 0b00000000001000000000000, - /// User is an early supporter - u_early_supporter = 0b00000000010000000000000, - /// User is a team user - u_team_user = 0b00000000100000000000000, - /// User is has Bug Hunter level 2 - u_bughunter_2 = 0b00000001000000000000000, - /// User is a verified bot - u_verified_bot = 0b00000010000000000000000, - /// User has the Early Verified Bot Developer badge - u_verified_bot_dev = 0b00000100000000000000000, - /// User's icon is animated - u_animated_icon = 0b00001000000000000000000, - /// User is a certified moderator - u_certified_moderator = 0b00010000000000000000000, - /// User is a bot using HTTP interactions (shows online even when not connected to a websocket) - u_bot_http_interactions = 0b00100000000000000000000, - /// User has nitro basic - u_nitro_basic = 0b01000000000000000000000, - /// User has the active developer badge - u_active_developer = 0b10000000000000000000000, -}; - -/** - * @brief Represents a user on discord. May or may not be a member of a dpp::guild. - */ -class DPP_EXPORT user : public managed, public json_interface { -public: - /** Discord username */ - std::string username; - /** Avatar hash */ - utility::iconhash avatar; - /** Flags built from a bitmask of values in dpp::user_flags */ - uint32_t flags; - /** Discriminator (aka tag), 4 digits usually displayed with leading zeroes. - * - * @note To print the discriminator with leading zeroes, use format_username() - */ - uint16_t discriminator; - /** Reference count of how many guilds this user is in */ - uint8_t refcount; - - /** - * @brief Construct a new user object - */ - user(); - - /** - * @brief Destroy the user object - */ - virtual ~user(); - - /** - * @brief Create a mentionable user. - * @param id The ID of the user. - * @return std::string The formatted mention of the user. - */ - static std::string get_mention(const snowflake& id); - - /** Fill this record from json. - * @param j The json to fill this record from - * @return Reference to self - */ - user& fill_from_json(nlohmann::json* j); - - /** - * @brief Convert to JSON string - * - * @param with_id include ID in output - * @return std::string JSON output - */ - virtual std::string build_json(bool with_id = true) const; - - /** - * @brief Get the avatar url of the user object - * - * @param size The size of the avatar in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized avatar is returned. - * @return std::string avatar url. If the user doesn't have an avatar, the default user avatar url is returned - */ - std::string get_avatar_url(uint16_t size = 0) const; - - /** - * @brief Return a ping/mention for the user - * - * @return std::string mention - */ - std::string get_mention() const; - - /** - * @brief Return true if user has the active Developer badge - * - * @return true if has active developer - */ - bool is_active_developer() const; - /** - * @brief User is a bot - * - * @return True if the user is a bot - */ - bool is_bot() const; - /** - * @brief User is a system user (Clyde) - * - * @return true if user is a system user - */ - bool is_system() const; - /** - * @brief User has multi-factor authentication enabled - * - * @return true if multi-factor is enabled - */ - bool is_mfa_enabled() const; - /** - * @brief Return true if user has verified account - * - * @return true if verified - */ - bool is_verified() const; - /** - * @brief Return true if user has full nitro. - * This is mutually exclusive with full nitro. - * - * @return true if user has full nitro - */ - bool has_nitro_full() const; - /** - * @brief Return true if user has nitro classic. - * This is mutually exclusive with nitro classic. - * - * @return true if user has nitro classic - */ - bool has_nitro_classic() const; - /** - * @brief Return true if user has nitro basic. - * This is mutually exclusive with nitro basic. - * - * @return true if user has nitro basic - */ - bool has_nitro_basic() const; - /** - * @brief Return true if user is a discord employee - * - * @return true if user is discord staff - */ - bool is_discord_employee() const; - /** - * @brief Return true if user owns a partnered server - * - * @return true if user has partnered server - */ - bool is_partnered_owner() const; - /** - * @brief Return true if user has hypesquad events - * - * @return true if has hypesquad events - */ - bool has_hypesquad_events() const; - /** - * @brief Return true if user has the bughunter level 1 badge - * - * @return true if has bughunter level 1 - */ - bool is_bughunter_1() const; - /** - * @brief Return true if user is in house bravery - * - * @return true if in house bravery - */ - bool is_house_bravery() const; - /** - * @brief Return true if user is in house brilliance - * - * @return true if in house brilliance - */ - bool is_house_brilliance() const; - /** - * @brief Return true if user is in house balance - * - * @return true if in house brilliance - */ - bool is_house_balance() const; - /** - * @brief Return true if user is an early supporter - * - * @return true if early supporter - */ - bool is_early_supporter() const; - /** - * @brief Return true if user is a team user - * - * @return true if a team user - */ - bool is_team_user() const; - /** - * @brief Return true if user has the bughunter level 2 badge - * - * @return true if has bughunter level 2 - */ - bool is_bughunter_2() const; - /** - * @brief Return true if user has the verified bot badge - * - * @return true if verified bot - */ - bool is_verified_bot() const; - /** - * @brief Return true if user is an early verified bot developer - * - * @return true if verified bot developer - */ - bool is_verified_bot_dev() const; - /** - * @brief Return true if user is a certified moderator - * - * @return true if certified moderator - */ - bool is_certified_moderator() const; - /** - * @brief Return true if user is a bot which exclusively uses HTTP interactions. - * Bots using HTTP interactions are always considered online even when not connected to a websocket. - * - * @return true if is a http interactions only bot - */ - bool is_bot_http_interactions() const; - /** - * @brief Return true if user has an animated icon - * - * @return true if icon is animated (gif) - */ - bool has_animated_icon() const; - - /** - * @brief Format a username into user#discriminator - * - * For example Brain#0001 - * - * @return Formatted username and discriminator - */ - std::string format_username() const; -}; - -/** - * @brief A user with additional fields only available via the oauth2 identify scope. - * These are not included in dpp::user as additional scopes are needed to fetch them - * which bots do not normally have. - */ -class DPP_EXPORT user_identified : public user, public json_interface { -public: - std::string locale; //!< Optional: the user's chosen language option identify - std::string email; //!< Optional: the user's email email (may be empty) - utility::iconhash banner; //!< Optional: the user's banner hash identify (may be empty) - uint32_t accent_color; //!< Optional: the user's banner color encoded as an integer representation of hexadecimal color code identify (may be empty) - bool verified; //!< Optional: whether the email on this account has been verified email - - /** Fill this record from json. - * @param j The json to fill this record from - * @return Reference to self - */ - user_identified& fill_from_json(nlohmann::json* j); - - /** - * @brief Convert to JSON string - * - * @param with_id include ID in output - * @return std::string JSON output - */ - virtual std::string build_json(bool with_id = true) const; - - /** - * @brief Construct a new user identified object - */ - user_identified(); - - /** - * @brief Destroy the user identified object - */ - virtual ~user_identified(); - - /** - * @brief Get the user identified's banner url if they have one, otherwise returns an empty string - * - * @param size The size of the banner in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized banner is returned. - * @return std::string banner url or empty string - */ - std::string get_banner_url(uint16_t size = 0) const; - -}; - -/** - * @brief helper function to deserialize a user from json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param u user to be deserialized - */ -void from_json(const nlohmann::json& j, user& u); - -/** - * @brief helper function to deserialize a user_identified from json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param u user to be deserialized - */ -void from_json(const nlohmann::json& j, user_identified& u); - -/** A group of users */ -typedef std::unordered_map user_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Various bitmask flags used to represent information about a dpp::user + */ +enum user_flags : uint32_t { + /// User is a bot + u_bot = 0b00000000000000000000001, + /// User is a system user (Clyde!) + u_system = 0b00000000000000000000010, + /// User has multi-factor authentication enabled + u_mfa_enabled = 0b00000000000000000000100, + /// User is verified (verified email address) + u_verified = 0b00000000000000000001000, + /// User has full nitro + u_nitro_full = 0b00000000000000000010000, + /// User has nitro classic + u_nitro_classic = 0b00000000000000000100000, + /// User is discord staff + u_discord_employee = 0b00000000000000001000000, + /// User owns a partnered server + u_partnered_owner = 0b00000000000000010000000, + /// User is a member of hypesquad events + u_hypesquad_events = 0b00000000000000100000000, + /// User has BugHunter level 1 + u_bughunter_1 = 0b00000000000001000000000, + /// User is a member of House Bravery + u_house_bravery = 0b00000000000010000000000, + /// User is a member of House Brilliance + u_house_brilliance = 0b00000000000100000000000, + /// User is a member of House Balance + u_house_balance = 0b00000000001000000000000, + /// User is an early supporter + u_early_supporter = 0b00000000010000000000000, + /// User is a team user + u_team_user = 0b00000000100000000000000, + /// User is has Bug Hunter level 2 + u_bughunter_2 = 0b00000001000000000000000, + /// User is a verified bot + u_verified_bot = 0b00000010000000000000000, + /// User has the Early Verified Bot Developer badge + u_verified_bot_dev = 0b00000100000000000000000, + /// User's icon is animated + u_animated_icon = 0b00001000000000000000000, + /// User is a certified moderator + u_certified_moderator = 0b00010000000000000000000, + /// User is a bot using HTTP interactions (shows online even when not connected to a websocket) + u_bot_http_interactions = 0b00100000000000000000000, + /// User has nitro basic + u_nitro_basic = 0b01000000000000000000000, + /// User has the active developer badge + u_active_developer = 0b10000000000000000000000, +}; + +/** + * @brief Represents a user on discord. May or may not be a member of a dpp::guild. + */ +class DPP_EXPORT user : public managed, public json_interface { +public: + /** Discord username */ + std::string username; + /** Avatar hash */ + utility::iconhash avatar; + /** Flags built from a bitmask of values in dpp::user_flags */ + uint32_t flags; + /** Discriminator (aka tag), 4 digits usually displayed with leading zeroes. + * + * @note To print the discriminator with leading zeroes, use format_username() + */ + uint16_t discriminator; + /** Reference count of how many guilds this user is in */ + uint8_t refcount; + + /** + * @brief Construct a new user object + */ + user(); + + /** + * @brief Destroy the user object + */ + virtual ~user(); + + /** + * @brief Create a mentionable user. + * @param id The ID of the user. + * @return std::string The formatted mention of the user. + */ + static std::string get_mention(const snowflake& id); + + /** Fill this record from json. + * @param j The json to fill this record from + * @return Reference to self + */ + user& fill_from_json(nlohmann::json* j); + + /** + * @brief Convert to JSON string + * + * @param with_id include ID in output + * @return std::string JSON output + */ + virtual std::string build_json(bool with_id = true) const; + + /** + * @brief Get the avatar url of the user object + * + * @param size The size of the avatar in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized avatar is returned. + * @return std::string avatar url. If the user doesn't have an avatar, the default user avatar url is returned + */ + std::string get_avatar_url(uint16_t size = 0) const; + + /** + * @brief Return a ping/mention for the user + * + * @return std::string mention + */ + std::string get_mention() const; + + /** + * @brief Return true if user has the active Developer badge + * + * @return true if has active developer + */ + bool is_active_developer() const; + /** + * @brief User is a bot + * + * @return True if the user is a bot + */ + bool is_bot() const; + /** + * @brief User is a system user (Clyde) + * + * @return true if user is a system user + */ + bool is_system() const; + /** + * @brief User has multi-factor authentication enabled + * + * @return true if multi-factor is enabled + */ + bool is_mfa_enabled() const; + /** + * @brief Return true if user has verified account + * + * @return true if verified + */ + bool is_verified() const; + /** + * @brief Return true if user has full nitro. + * This is mutually exclusive with full nitro. + * + * @return true if user has full nitro + */ + bool has_nitro_full() const; + /** + * @brief Return true if user has nitro classic. + * This is mutually exclusive with nitro classic. + * + * @return true if user has nitro classic + */ + bool has_nitro_classic() const; + /** + * @brief Return true if user has nitro basic. + * This is mutually exclusive with nitro basic. + * + * @return true if user has nitro basic + */ + bool has_nitro_basic() const; + /** + * @brief Return true if user is a discord employee + * + * @return true if user is discord staff + */ + bool is_discord_employee() const; + /** + * @brief Return true if user owns a partnered server + * + * @return true if user has partnered server + */ + bool is_partnered_owner() const; + /** + * @brief Return true if user has hypesquad events + * + * @return true if has hypesquad events + */ + bool has_hypesquad_events() const; + /** + * @brief Return true if user has the bughunter level 1 badge + * + * @return true if has bughunter level 1 + */ + bool is_bughunter_1() const; + /** + * @brief Return true if user is in house bravery + * + * @return true if in house bravery + */ + bool is_house_bravery() const; + /** + * @brief Return true if user is in house brilliance + * + * @return true if in house brilliance + */ + bool is_house_brilliance() const; + /** + * @brief Return true if user is in house balance + * + * @return true if in house brilliance + */ + bool is_house_balance() const; + /** + * @brief Return true if user is an early supporter + * + * @return true if early supporter + */ + bool is_early_supporter() const; + /** + * @brief Return true if user is a team user + * + * @return true if a team user + */ + bool is_team_user() const; + /** + * @brief Return true if user has the bughunter level 2 badge + * + * @return true if has bughunter level 2 + */ + bool is_bughunter_2() const; + /** + * @brief Return true if user has the verified bot badge + * + * @return true if verified bot + */ + bool is_verified_bot() const; + /** + * @brief Return true if user is an early verified bot developer + * + * @return true if verified bot developer + */ + bool is_verified_bot_dev() const; + /** + * @brief Return true if user is a certified moderator + * + * @return true if certified moderator + */ + bool is_certified_moderator() const; + /** + * @brief Return true if user is a bot which exclusively uses HTTP interactions. + * Bots using HTTP interactions are always considered online even when not connected to a websocket. + * + * @return true if is a http interactions only bot + */ + bool is_bot_http_interactions() const; + /** + * @brief Return true if user has an animated icon + * + * @return true if icon is animated (gif) + */ + bool has_animated_icon() const; + + /** + * @brief Format a username into user#discriminator + * + * For example Brain#0001 + * + * @return Formatted username and discriminator + */ + std::string format_username() const; +}; + +/** + * @brief A user with additional fields only available via the oauth2 identify scope. + * These are not included in dpp::user as additional scopes are needed to fetch them + * which bots do not normally have. + */ +class DPP_EXPORT user_identified : public user, public json_interface { +public: + std::string locale; //!< Optional: the user's chosen language option identify + std::string email; //!< Optional: the user's email email (may be empty) + utility::iconhash banner; //!< Optional: the user's banner hash identify (may be empty) + uint32_t accent_color; //!< Optional: the user's banner color encoded as an integer representation of hexadecimal color code identify (may be empty) + bool verified; //!< Optional: whether the email on this account has been verified email + + /** Fill this record from json. + * @param j The json to fill this record from + * @return Reference to self + */ + user_identified& fill_from_json(nlohmann::json* j); + + /** + * @brief Convert to JSON string + * + * @param with_id include ID in output + * @return std::string JSON output + */ + virtual std::string build_json(bool with_id = true) const; + + /** + * @brief Construct a new user identified object + */ + user_identified(); + + /** + * @brief Destroy the user identified object + */ + virtual ~user_identified(); + + /** + * @brief Get the user identified's banner url if they have one, otherwise returns an empty string + * + * @param size The size of the banner in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized banner is returned. + * @return std::string banner url or empty string + */ + std::string get_banner_url(uint16_t size = 0) const; + +}; + +/** + * @brief helper function to deserialize a user from json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param u user to be deserialized + */ +void from_json(const nlohmann::json& j, user& u); + +/** + * @brief helper function to deserialize a user_identified from json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param u user to be deserialized + */ +void from_json(const nlohmann::json& j, user_identified& u); + +/** A group of users */ +typedef std::unordered_map user_map; + +}; diff --git a/3rdParty/dpp/utility.h b/3rdParty/dpp/utility.h index 963e9d0161..a4c17f6051 100644 --- a/3rdParty/dpp/utility.h +++ b/3rdParty/dpp/utility.h @@ -1,487 +1,487 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include - -/** - * @brief The main namespace for D++ functions, classes and types - */ -namespace dpp { - /** - * @brief Utility helper functions, generally for logging, running programs, time/date manipulation, etc - */ - namespace utility { - - /** - * @brief Timestamp formats for dpp::utility::timestamp() - * - * @note These values are the actual character values specified by the Discord API - * and should not be changed unless the Discord API changes the specification! - * They have been sorted into numerical order of their ASCII value to keep C++ happy. - */ - enum time_format : uint8_t { - /// "20 April 2021" - Long Date - tf_long_date = 'D', - /// "Tuesday, 20 April 2021 16:20" - Long Date/Time - tf_long_datetime = 'F', - /// "2 months ago" - Relative Time - tf_relative_time = 'R', - /// "16:20:30" - Long Time - tf_long_time = 'T', - /// "20/04/2021" - Short Date - tf_short_date = 'd', - /// "20 April 2021 16:20" - Short Date/Time - tf_short_datetime = 'f', - /// "16:20" - Short Time - tf_short_time = 't', - }; - - /** - * @brief The base URL for CDN content such as profile pictures and guild icons. - */ - const std::string cdn_host = "https://cdn.discordapp.com"; - - /** - * @brief Callback for the results of a command executed via dpp::utility::exec - */ - typedef std::function cmd_result_t; - - /** - * @brief Run a commandline program asynchronously. The command line program - * is spawned in a separate std::thread, and when complete, its output from - * stdout is passed to the callback function in its string parameter. For example - * ``` - * dpp::utility::exec("/bin/ls", {"-al"}, [](const std::string& output) { - * std::cout << "Output of 'ls -al': " << output << "\n"; - * }); - * ``` - * - * @param cmd The command to run. - * @param parameters Command line parameters. Each will be escaped using `std::quoted`. - * @param callback The callback to call on completion. - */ - void DPP_EXPORT exec(const std::string& cmd, std::vector parameters = {}, cmd_result_t callback = {}); - - /** - * @brief Return a mentionable timestamp (used in a message). These timestamps will display the given timestamp in the user's timezone and locale. - * - * @param ts Time stamp to convert - * @param tf Format of timestamp using dpp::utility::time_format - * @return std::string The formatted timestamp - */ - std::string DPP_EXPORT timestamp(time_t ts, time_format tf = tf_short_datetime); - - /** - * @brief Returns current date and time - * - * @return std::string Current date and time in "Y-m-d H:M:S" format - */ - std::string DPP_EXPORT current_date_time(); - /** - * @brief Convert a dpp::loglevel enum value to a string - * - * @param in log level to convert - * @return std::string string form of log level - */ - std::string DPP_EXPORT loglevel(dpp::loglevel in); - - /** - * @brief Store a 128 bit icon hash (profile picture, server icon etc) - * as a 128 bit binary value made of two uint64_t. - * Has a constructor to build one from a string, and a method to fetch - * the value back in string form. - */ - struct DPP_EXPORT iconhash { - - uint64_t first; //!< High 64 bits - uint64_t second; //!< Low 64 bits - - /** - * @brief Construct a new iconhash object - * @param _first Leftmost portion of the hash value - * @param _second Rightmost portion of the hash value - */ - iconhash(uint64_t _first = 0, uint64_t _second = 0); - - /** - * @brief Construct a new iconhash object - */ - iconhash(const iconhash&); - - /** - * @brief Destroy the iconhash object - */ - ~iconhash(); - - /** - * @brief Construct a new iconhash object - * - * @param hash String hash to construct from. - * Must contain a 32 character hex string. - * - * @throws std::length_error if the provided - * string is not exactly 32 characters long. - */ - iconhash(const std::string &hash); - - /** - * @brief Assign from std::string - * - * @param assignment string to assign from. - * - * @throws std::length_error if the provided - * string is not exactly 32 characters long. - */ - iconhash& operator=(const std::string &assignment); - - /** - * @brief Check if one iconhash is equal to another - * - * @param other other iconhash to compare - * @return True if the iconhash objects match - */ - bool operator==(const iconhash& other) const; - - /** - * @brief Change value of iconhash object - * - * @param hash String hash to change to. - * Must contain a 32 character hex string. - * - * @throws std::length_error if the provided - * string is not exactly 32 characters long. - */ - void set(const std::string &hash); - - /** - * @brief Convert iconhash back to 32 character - * string value. - * - * @return std::string Hash value - */ - std::string to_string() const; - }; - - /** - * @brief Return the current time with fractions of seconds. - * This is a unix epoch time with the fractional seconds part - * after the decimal place. - * - * @return double time with fractional seconds - */ - double DPP_EXPORT time_f(); - - /** - * @brief Returns true if D++ was built with voice support - * - * @return bool True if voice support is compiled in (libsodium/libopus) - */ - bool DPP_EXPORT has_voice(); - - /** - * @brief Convert a byte count to display value - * - * @param c number of bytes - * @return std::string display value suffixed with M, G, T where necessary - */ - std::string DPP_EXPORT bytes(uint64_t c); - - /** - * @brief A class used to represent an uptime in hours, minutes, - * seconds and days, with helper functions to convert from time_t - * and display as a string. - */ - struct DPP_EXPORT uptime { - uint16_t days; //!< Number of days - uint8_t hours; //!< Number of hours - uint8_t mins; //!< Number of minutes - uint8_t secs; //!< Number of seconds - - /** - * @brief Construct a new uptime object - */ - uptime(); - - /** - * @brief Construct a new uptime object - * - * @param diff A time_t to initialise the object from - */ - uptime(time_t diff); - - /** - * @brief Construct a new uptime object - * - * @param diff A time_t to initialise the object from - */ - uptime(double diff); - - /** - * @brief Get uptime as string - * - * @return std::string Uptime as string - */ - std::string to_string() const; - - /** - * @brief Get uptime as seconds - * - * @return uint64_t Uptime as seconds - */ - uint64_t to_secs() const; - - /** - * @brief Get uptime as milliseconds - * - * @return uint64_t Uptime as milliseconds - */ - uint64_t to_msecs() const; - }; - - /** - * @brief Convert doubles to RGB for sending in embeds - * - * @param red red value, between 0 and 1 inclusive - * @param green green value, between 0 and 1 inclusive - * @param blue blue value, between 0 and 1 inclusive - * @return uint32_t returned integer colour value - */ - uint32_t DPP_EXPORT rgb(double red, double green, double blue); - - /** - * @brief Convert ints to RGB for sending in embeds - * - * @param red red value, between 0 and 255 inclusive - * @param green green value, between 0 and 255 inclusive - * @param blue blue value, between 0 and 255 inclusive - * @return uint32_t returned integer colour value - */ - uint32_t DPP_EXPORT rgb(int red, int green, int blue); - - /** - * @brief Convert doubles to CMYK for sending in embeds - * - * @param c cyan value, between 0 and 1 inclusive - * @param m magenta value, between 0 and 1 inclusive - * @param y yellow value, between 0 and 1 inclusive - * @param k key (black) value, between 0 and 1 inclusive - * @return uint32_t returned integer colour value - */ - uint32_t DPP_EXPORT cmyk(double c, double m, double y, double k); - - /** - * @brief Convert ints to CMYK for sending in embeds - * - * @param c cyan value, between 0 and 255 inclusive - * @param m magenta value, between 0 and 255 inclusive - * @param y yellow value, between 0 and 255 inclusive - * @param k key (black) value, between 0 and 255 inclusive - * @return uint32_t returned integer colour value - */ - uint32_t DPP_EXPORT cmyk(int c, int m, int y, int k); - - /** - * @brief Output hex values of a section of memory for debugging - * - * @param data The start of the data to display - * @param length The length of data to display - */ - std::string DPP_EXPORT debug_dump(uint8_t* data, size_t length); - - /** - * @brief Returns the length of a UTF-8 string in codepoints - * - * @param str string to count length of - * @return size_t length of string (0 for invalid utf8) - */ - size_t DPP_EXPORT utf8len(const std::string &str); - - /** - * @brief Return substring of a UTF-8 encoded string in codepoints - * - * @param str string to return substring from - * @param start start codepoint offset - * @param length length in codepoints - * @return std::string Substring in UTF-8 or empty string if invalid UTF-8 passed in - */ - std::string DPP_EXPORT utf8substr(const std::string& str, std::string::size_type start, std::string::size_type length); - - /** - * @brief Read a whole file into a std::string. - * Be sure you have enough memory to read the file, if you are reading a large file. - * @note Be aware this function can block! If you are regularly reading large files, consider caching them. - * @param filename The path to the file to read - * @return std::string The file contents - * @throw dpp::exception on failure to read the entire file - */ - std::string DPP_EXPORT read_file(const std::string& filename); - - /** - * @brief Validate a string value - * In the event the length of the string is less than _min, then an exception of type dpp:length_exception - * will be thrown. If the string is longer than _max UTF8 codepoints it will be truncated to fit. - * - * @param value The value to validate - * @param _min Minimum length - * @param _max Maximum length - * @param exception_message Exception message to throw if value length < _min - * @return std::string Validated string, truncated if necessary. - * @throw dpp::length_exception if value UTF8 length < _min - */ - std::string DPP_EXPORT validate(const std::string& value, size_t _min, size_t _max, const std::string& exception_message); - - /** - * @brief Return the url parameter for an avatar size, or empty if the size is 0 - * - * @param size size to generate url parameter for - * @return std::string url parameter - */ - std::string DPP_EXPORT avatar_size(uint32_t size); - - /** - * @brief Split (tokenize) a string into a vector, using the given separators - * - * @param in Input string - * @param sep Separator characters - * @return std::vector Tokenized strings - */ - std::vector DPP_EXPORT tokenize(std::string const &in, const char* sep = "\r\n"); - - /** - * @brief Create a bot invite - * - * @param bot_id Bot ID - * @param permissions Permission bitmask of the bot to invite - * @param scopes Scopes to use - * @return Invite URL - */ - std::string DPP_EXPORT bot_invite_url(const snowflake bot_id, const uint64_t permissions = 0, const std::vector& scopes = {"bot", "applications.commands"}); - - /** - * @brief Escapes Discord's markdown sequences in a string - * - * @param text Text to escape - * @param escape_code_blocks If set to false, then code blocks are not escaped. - * This means that you can still use a code block, and the text within will be left as-is. - * If set to true, code blocks will also be escaped so that ` symbol may be used as a normal - * character. - * @return std::string The text with the markdown special characters escaped with a backslash - */ - std::string DPP_EXPORT markdown_escape(const std::string& text, bool escape_code_blocks = false); - - /** - * @brief Encodes a url parameter similar to [php urlencode()](https://www.php.net/manual/en/function.urlencode.php) - * - * @param value String to encode - * @return std::string URL encoded string - */ - std::string DPP_EXPORT url_encode(const std::string &value); - - /** - * @brief Create a mentionable slashcommand (used in a message). - * @param command_id The ID of the slashcommand - * @param command_name The command name - * @param subcommand Optional: The subcommand name (for mentioning a subcommand) - * @return std::string The formatted mention - */ - std::string DPP_EXPORT slashcommand_mention(snowflake command_id, const std::string &command_name, const std::string &subcommand = ""); - - /** - * @brief Create a mentionable slashcommand (used in a message). - * @param command_id The ID of the slashcommand - * @param command_name The command name - * @param subcommand_group The subcommand group name - * @param subcommand The subcommand name - * @return std::string The formatted mention of the slashcommand with its subcommand - */ - std::string DPP_EXPORT slashcommand_mention(snowflake command_id, const std::string &command_name, const std::string &subcommand_group, const std::string &subcommand); - - /** - * @brief Create a mentionable user. - * @param id The ID of the user. - * @return std::string The formatted mention of the user. - */ - std::string DPP_EXPORT user_mention(const snowflake& id); - - /** - * @brief Create a mentionable channel. - * @param id The ID of the channel. - * @return std::string The formatted mention of the channel. - */ - std::string DPP_EXPORT channel_mention(const snowflake& id); - - /** - * @brief Create a mentionable emoji - * @param name The name of the emoji. - * @param id The ID of the emoji. - * @param is_animated is emoji animated. - * @return std::string The formatted mention of the emoji. - */ - std::string DPP_EXPORT emoji_mention(const std::string& name, const snowflake& id, bool is_animated = false); - - /** - * @brief Create a mentionable role. - * @param id The ID of the role. - * @return std::string The formatted mention of the role. - */ - std::string DPP_EXPORT role_mention(const snowflake& id); - - /** - * @brief Returns the library's version string - * - * @return std::string version - */ - std::string DPP_EXPORT version(); - - /** - * @brief Build a URL parameter string e.g. "?a=b&c=d&e=f" from a map of key/value pairs. - * Entries with empty key names or values are omitted. - * - * @param parameters parameters to create a url query string for - * @return std::string A correctly encoded url query string - */ - std::string DPP_EXPORT make_url_parameters(const std::map& parameters); - - /** - * @brief Build a URL parameter string e.g. "?a=b&c=d&e=f" from a map of key/value pairs. - * Entries with empty key names or zero values are omitted. - * - * @param parameters parameters to create a url query string for - * @return std::string A correctly encoded url query string - */ - std::string DPP_EXPORT make_url_parameters(const std::map& parameters); - - /** - * @brief Set the name of the current thread for debugging and statistical reporting - * - * @param name New name to set - */ - void DPP_EXPORT set_thread_name(const std::string& name); - - }; -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include + +/** + * @brief The main namespace for D++ functions, classes and types + */ +namespace dpp { + /** + * @brief Utility helper functions, generally for logging, running programs, time/date manipulation, etc + */ + namespace utility { + + /** + * @brief Timestamp formats for dpp::utility::timestamp() + * + * @note These values are the actual character values specified by the Discord API + * and should not be changed unless the Discord API changes the specification! + * They have been sorted into numerical order of their ASCII value to keep C++ happy. + */ + enum time_format : uint8_t { + /// "20 April 2021" - Long Date + tf_long_date = 'D', + /// "Tuesday, 20 April 2021 16:20" - Long Date/Time + tf_long_datetime = 'F', + /// "2 months ago" - Relative Time + tf_relative_time = 'R', + /// "16:20:30" - Long Time + tf_long_time = 'T', + /// "20/04/2021" - Short Date + tf_short_date = 'd', + /// "20 April 2021 16:20" - Short Date/Time + tf_short_datetime = 'f', + /// "16:20" - Short Time + tf_short_time = 't', + }; + + /** + * @brief The base URL for CDN content such as profile pictures and guild icons. + */ + const std::string cdn_host = "https://cdn.discordapp.com"; + + /** + * @brief Callback for the results of a command executed via dpp::utility::exec + */ + typedef std::function cmd_result_t; + + /** + * @brief Run a commandline program asynchronously. The command line program + * is spawned in a separate std::thread, and when complete, its output from + * stdout is passed to the callback function in its string parameter. For example + * ``` + * dpp::utility::exec("/bin/ls", {"-al"}, [](const std::string& output) { + * std::cout << "Output of 'ls -al': " << output << "\n"; + * }); + * ``` + * + * @param cmd The command to run. + * @param parameters Command line parameters. Each will be escaped using `std::quoted`. + * @param callback The callback to call on completion. + */ + void DPP_EXPORT exec(const std::string& cmd, std::vector parameters = {}, cmd_result_t callback = {}); + + /** + * @brief Return a mentionable timestamp (used in a message). These timestamps will display the given timestamp in the user's timezone and locale. + * + * @param ts Time stamp to convert + * @param tf Format of timestamp using dpp::utility::time_format + * @return std::string The formatted timestamp + */ + std::string DPP_EXPORT timestamp(time_t ts, time_format tf = tf_short_datetime); + + /** + * @brief Returns current date and time + * + * @return std::string Current date and time in "Y-m-d H:M:S" format + */ + std::string DPP_EXPORT current_date_time(); + /** + * @brief Convert a dpp::loglevel enum value to a string + * + * @param in log level to convert + * @return std::string string form of log level + */ + std::string DPP_EXPORT loglevel(dpp::loglevel in); + + /** + * @brief Store a 128 bit icon hash (profile picture, server icon etc) + * as a 128 bit binary value made of two uint64_t. + * Has a constructor to build one from a string, and a method to fetch + * the value back in string form. + */ + struct DPP_EXPORT iconhash { + + uint64_t first; //!< High 64 bits + uint64_t second; //!< Low 64 bits + + /** + * @brief Construct a new iconhash object + * @param _first Leftmost portion of the hash value + * @param _second Rightmost portion of the hash value + */ + iconhash(uint64_t _first = 0, uint64_t _second = 0); + + /** + * @brief Construct a new iconhash object + */ + iconhash(const iconhash&); + + /** + * @brief Destroy the iconhash object + */ + ~iconhash(); + + /** + * @brief Construct a new iconhash object + * + * @param hash String hash to construct from. + * Must contain a 32 character hex string. + * + * @throws std::length_error if the provided + * string is not exactly 32 characters long. + */ + iconhash(const std::string &hash); + + /** + * @brief Assign from std::string + * + * @param assignment string to assign from. + * + * @throws std::length_error if the provided + * string is not exactly 32 characters long. + */ + iconhash& operator=(const std::string &assignment); + + /** + * @brief Check if one iconhash is equal to another + * + * @param other other iconhash to compare + * @return True if the iconhash objects match + */ + bool operator==(const iconhash& other) const; + + /** + * @brief Change value of iconhash object + * + * @param hash String hash to change to. + * Must contain a 32 character hex string. + * + * @throws std::length_error if the provided + * string is not exactly 32 characters long. + */ + void set(const std::string &hash); + + /** + * @brief Convert iconhash back to 32 character + * string value. + * + * @return std::string Hash value + */ + std::string to_string() const; + }; + + /** + * @brief Return the current time with fractions of seconds. + * This is a unix epoch time with the fractional seconds part + * after the decimal place. + * + * @return double time with fractional seconds + */ + double DPP_EXPORT time_f(); + + /** + * @brief Returns true if D++ was built with voice support + * + * @return bool True if voice support is compiled in (libsodium/libopus) + */ + bool DPP_EXPORT has_voice(); + + /** + * @brief Convert a byte count to display value + * + * @param c number of bytes + * @return std::string display value suffixed with M, G, T where necessary + */ + std::string DPP_EXPORT bytes(uint64_t c); + + /** + * @brief A class used to represent an uptime in hours, minutes, + * seconds and days, with helper functions to convert from time_t + * and display as a string. + */ + struct DPP_EXPORT uptime { + uint16_t days; //!< Number of days + uint8_t hours; //!< Number of hours + uint8_t mins; //!< Number of minutes + uint8_t secs; //!< Number of seconds + + /** + * @brief Construct a new uptime object + */ + uptime(); + + /** + * @brief Construct a new uptime object + * + * @param diff A time_t to initialise the object from + */ + uptime(time_t diff); + + /** + * @brief Construct a new uptime object + * + * @param diff A time_t to initialise the object from + */ + uptime(double diff); + + /** + * @brief Get uptime as string + * + * @return std::string Uptime as string + */ + std::string to_string() const; + + /** + * @brief Get uptime as seconds + * + * @return uint64_t Uptime as seconds + */ + uint64_t to_secs() const; + + /** + * @brief Get uptime as milliseconds + * + * @return uint64_t Uptime as milliseconds + */ + uint64_t to_msecs() const; + }; + + /** + * @brief Convert doubles to RGB for sending in embeds + * + * @param red red value, between 0 and 1 inclusive + * @param green green value, between 0 and 1 inclusive + * @param blue blue value, between 0 and 1 inclusive + * @return uint32_t returned integer colour value + */ + uint32_t DPP_EXPORT rgb(double red, double green, double blue); + + /** + * @brief Convert ints to RGB for sending in embeds + * + * @param red red value, between 0 and 255 inclusive + * @param green green value, between 0 and 255 inclusive + * @param blue blue value, between 0 and 255 inclusive + * @return uint32_t returned integer colour value + */ + uint32_t DPP_EXPORT rgb(int red, int green, int blue); + + /** + * @brief Convert doubles to CMYK for sending in embeds + * + * @param c cyan value, between 0 and 1 inclusive + * @param m magenta value, between 0 and 1 inclusive + * @param y yellow value, between 0 and 1 inclusive + * @param k key (black) value, between 0 and 1 inclusive + * @return uint32_t returned integer colour value + */ + uint32_t DPP_EXPORT cmyk(double c, double m, double y, double k); + + /** + * @brief Convert ints to CMYK for sending in embeds + * + * @param c cyan value, between 0 and 255 inclusive + * @param m magenta value, between 0 and 255 inclusive + * @param y yellow value, between 0 and 255 inclusive + * @param k key (black) value, between 0 and 255 inclusive + * @return uint32_t returned integer colour value + */ + uint32_t DPP_EXPORT cmyk(int c, int m, int y, int k); + + /** + * @brief Output hex values of a section of memory for debugging + * + * @param data The start of the data to display + * @param length The length of data to display + */ + std::string DPP_EXPORT debug_dump(uint8_t* data, size_t length); + + /** + * @brief Returns the length of a UTF-8 string in codepoints + * + * @param str string to count length of + * @return size_t length of string (0 for invalid utf8) + */ + size_t DPP_EXPORT utf8len(const std::string &str); + + /** + * @brief Return substring of a UTF-8 encoded string in codepoints + * + * @param str string to return substring from + * @param start start codepoint offset + * @param length length in codepoints + * @return std::string Substring in UTF-8 or empty string if invalid UTF-8 passed in + */ + std::string DPP_EXPORT utf8substr(const std::string& str, std::string::size_type start, std::string::size_type length); + + /** + * @brief Read a whole file into a std::string. + * Be sure you have enough memory to read the file, if you are reading a large file. + * @note Be aware this function can block! If you are regularly reading large files, consider caching them. + * @param filename The path to the file to read + * @return std::string The file contents + * @throw dpp::exception on failure to read the entire file + */ + std::string DPP_EXPORT read_file(const std::string& filename); + + /** + * @brief Validate a string value + * In the event the length of the string is less than _min, then an exception of type dpp:length_exception + * will be thrown. If the string is longer than _max UTF8 codepoints it will be truncated to fit. + * + * @param value The value to validate + * @param _min Minimum length + * @param _max Maximum length + * @param exception_message Exception message to throw if value length < _min + * @return std::string Validated string, truncated if necessary. + * @throw dpp::length_exception if value UTF8 length < _min + */ + std::string DPP_EXPORT validate(const std::string& value, size_t _min, size_t _max, const std::string& exception_message); + + /** + * @brief Return the url parameter for an avatar size, or empty if the size is 0 + * + * @param size size to generate url parameter for + * @return std::string url parameter + */ + std::string DPP_EXPORT avatar_size(uint32_t size); + + /** + * @brief Split (tokenize) a string into a vector, using the given separators + * + * @param in Input string + * @param sep Separator characters + * @return std::vector Tokenized strings + */ + std::vector DPP_EXPORT tokenize(std::string const &in, const char* sep = "\r\n"); + + /** + * @brief Create a bot invite + * + * @param bot_id Bot ID + * @param permissions Permission bitmask of the bot to invite + * @param scopes Scopes to use + * @return Invite URL + */ + std::string DPP_EXPORT bot_invite_url(const snowflake bot_id, const uint64_t permissions = 0, const std::vector& scopes = {"bot", "applications.commands"}); + + /** + * @brief Escapes Discord's markdown sequences in a string + * + * @param text Text to escape + * @param escape_code_blocks If set to false, then code blocks are not escaped. + * This means that you can still use a code block, and the text within will be left as-is. + * If set to true, code blocks will also be escaped so that ` symbol may be used as a normal + * character. + * @return std::string The text with the markdown special characters escaped with a backslash + */ + std::string DPP_EXPORT markdown_escape(const std::string& text, bool escape_code_blocks = false); + + /** + * @brief Encodes a url parameter similar to [php urlencode()](https://www.php.net/manual/en/function.urlencode.php) + * + * @param value String to encode + * @return std::string URL encoded string + */ + std::string DPP_EXPORT url_encode(const std::string &value); + + /** + * @brief Create a mentionable slashcommand (used in a message). + * @param command_id The ID of the slashcommand + * @param command_name The command name + * @param subcommand Optional: The subcommand name (for mentioning a subcommand) + * @return std::string The formatted mention + */ + std::string DPP_EXPORT slashcommand_mention(snowflake command_id, const std::string &command_name, const std::string &subcommand = ""); + + /** + * @brief Create a mentionable slashcommand (used in a message). + * @param command_id The ID of the slashcommand + * @param command_name The command name + * @param subcommand_group The subcommand group name + * @param subcommand The subcommand name + * @return std::string The formatted mention of the slashcommand with its subcommand + */ + std::string DPP_EXPORT slashcommand_mention(snowflake command_id, const std::string &command_name, const std::string &subcommand_group, const std::string &subcommand); + + /** + * @brief Create a mentionable user. + * @param id The ID of the user. + * @return std::string The formatted mention of the user. + */ + std::string DPP_EXPORT user_mention(const snowflake& id); + + /** + * @brief Create a mentionable channel. + * @param id The ID of the channel. + * @return std::string The formatted mention of the channel. + */ + std::string DPP_EXPORT channel_mention(const snowflake& id); + + /** + * @brief Create a mentionable emoji + * @param name The name of the emoji. + * @param id The ID of the emoji. + * @param is_animated is emoji animated. + * @return std::string The formatted mention of the emoji. + */ + std::string DPP_EXPORT emoji_mention(const std::string& name, const snowflake& id, bool is_animated = false); + + /** + * @brief Create a mentionable role. + * @param id The ID of the role. + * @return std::string The formatted mention of the role. + */ + std::string DPP_EXPORT role_mention(const snowflake& id); + + /** + * @brief Returns the library's version string + * + * @return std::string version + */ + std::string DPP_EXPORT version(); + + /** + * @brief Build a URL parameter string e.g. "?a=b&c=d&e=f" from a map of key/value pairs. + * Entries with empty key names or values are omitted. + * + * @param parameters parameters to create a url query string for + * @return std::string A correctly encoded url query string + */ + std::string DPP_EXPORT make_url_parameters(const std::map& parameters); + + /** + * @brief Build a URL parameter string e.g. "?a=b&c=d&e=f" from a map of key/value pairs. + * Entries with empty key names or zero values are omitted. + * + * @param parameters parameters to create a url query string for + * @return std::string A correctly encoded url query string + */ + std::string DPP_EXPORT make_url_parameters(const std::map& parameters); + + /** + * @brief Set the name of the current thread for debugging and statistical reporting + * + * @param name New name to set + */ + void DPP_EXPORT set_thread_name(const std::string& name); + + }; +}; diff --git a/3rdParty/dpp/version.h b/3rdParty/dpp/version.h index bb8d69338a..dbc615b2f7 100644 --- a/3rdParty/dpp/version.h +++ b/3rdParty/dpp/version.h @@ -1,31 +1,31 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once - -#if !defined(DPP_VERSION_LONG) -#define DPP_VERSION_LONG 0x00100022 -#define DPP_VERSION_SHORT 100022 -#define DPP_VERSION_TEXT "D++ 10.0.22 (01-Nov-2022)" - -#define DPP_VERSION_MAJOR ((DPP_VERSION_LONG & 0x00ff0000) >> 16) -#define DPP_VERSION_MINOR ((DPP_VERSION_LONG & 0x0000ff00) >> 8) -#define DPP_VERSION_PATCH (DPP_VERSION_LONG & 0x000000ff) -#endif +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once + +#if !defined(DPP_VERSION_LONG) +#define DPP_VERSION_LONG 0x00100022 +#define DPP_VERSION_SHORT 100022 +#define DPP_VERSION_TEXT "D++ 10.0.22 (01-Nov-2022)" + +#define DPP_VERSION_MAJOR ((DPP_VERSION_LONG & 0x00ff0000) >> 16) +#define DPP_VERSION_MINOR ((DPP_VERSION_LONG & 0x0000ff00) >> 8) +#define DPP_VERSION_PATCH (DPP_VERSION_LONG & 0x000000ff) +#endif diff --git a/3rdParty/dpp/voiceregion.h b/3rdParty/dpp/voiceregion.h index 1ca805b06a..39c88057aa 100644 --- a/3rdParty/dpp/voiceregion.h +++ b/3rdParty/dpp/voiceregion.h @@ -1,119 +1,119 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Flags related to a voice region - */ -enum voiceregion_flags { - v_optimal = 0x00000001, - v_deprecated = 0x00000010, - v_custom = 0x00000100, - v_vip = 0x00001000 -}; - -/** - * @brief Represents a voice region on discord - */ -class DPP_EXPORT voiceregion : public json_interface { -public: - /** - * @brief Voice server ID - */ - std::string id; - - /** - * @brief Voice server name - */ - std::string name; - - /** - * @brief Flags bitmap - */ - uint8_t flags; - - /** - * @brief Construct a new voiceregion object - */ - voiceregion(); - - /** - * @brief Destroy the voiceregion object - */ - virtual ~voiceregion() = default; - - /** - * @brief Fill object properties from JSON - * - * @param j JSON to fill from - * @return voiceregion& Reference to self - */ - voiceregion& fill_from_json(nlohmann::json* j); - - /** - * @brief Build a json string for this object - * - * @param with_id Add ID to output - * @return std::string JSON string - */ - virtual std::string build_json(bool with_id = false) const; - - /** - * @brief True if is the optimal voice server - * - * @return true if optimal - */ - bool is_optimal() const; - - /** - * @brief True if is a deprecated voice server - * - * @return true if deprecated - */ - bool is_deprecated() const; - - /** - * @brief True if is a custom voice server - * - * @return true if custom - */ - bool is_custom() const; - - /** - * @brief True if is a VIP voice server - * - * @return true if VIP - */ - bool is_vip() const; -}; - -/** - * @brief A group of voice regions - */ -typedef std::unordered_map voiceregion_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Flags related to a voice region + */ +enum voiceregion_flags { + v_optimal = 0x00000001, + v_deprecated = 0x00000010, + v_custom = 0x00000100, + v_vip = 0x00001000 +}; + +/** + * @brief Represents a voice region on discord + */ +class DPP_EXPORT voiceregion : public json_interface { +public: + /** + * @brief Voice server ID + */ + std::string id; + + /** + * @brief Voice server name + */ + std::string name; + + /** + * @brief Flags bitmap + */ + uint8_t flags; + + /** + * @brief Construct a new voiceregion object + */ + voiceregion(); + + /** + * @brief Destroy the voiceregion object + */ + virtual ~voiceregion() = default; + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return voiceregion& Reference to self + */ + voiceregion& fill_from_json(nlohmann::json* j); + + /** + * @brief Build a json string for this object + * + * @param with_id Add ID to output + * @return std::string JSON string + */ + virtual std::string build_json(bool with_id = false) const; + + /** + * @brief True if is the optimal voice server + * + * @return true if optimal + */ + bool is_optimal() const; + + /** + * @brief True if is a deprecated voice server + * + * @return true if deprecated + */ + bool is_deprecated() const; + + /** + * @brief True if is a custom voice server + * + * @return true if custom + */ + bool is_custom() const; + + /** + * @brief True if is a VIP voice server + * + * @return true if VIP + */ + bool is_vip() const; +}; + +/** + * @brief A group of voice regions + */ +typedef std::unordered_map voiceregion_map; + +}; diff --git a/3rdParty/dpp/voicestate.h b/3rdParty/dpp/voicestate.h index 6edabe6307..82eebbe378 100644 --- a/3rdParty/dpp/voicestate.h +++ b/3rdParty/dpp/voicestate.h @@ -1,110 +1,110 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Bit mask flags relating to voice states - */ -enum voicestate_flags { - vs_deaf = 0b00000001, //!< Deafened by the server - vs_mute = 0b00000010, //!< Muted by the server - vs_self_mute = 0b00000100, //!< Locally Muted - vs_self_deaf = 0b00001000, //!< Locally deafened - vs_self_stream = 0b00010000, //!< Whether this user is streaming using "Go Live" - vs_self_video = 0b00100000, //!< Whether this user's camera is enabled - vs_suppress = 0b01000000 //!< Whether this user's permission to speak is denied -}; - -/** - * @brief Represents the voice state of a user on a guild - * These are stored in the dpp::guild object, and accessible there, - * or via dpp::channel::get_voice_members - */ -class DPP_EXPORT voicestate : public json_interface { -public: - class discord_client* shard; //!< Owning shard - snowflake guild_id; //!< Optional: the guild id this voice state is for - snowflake channel_id; //!< the channel id this user is connected to (may be empty) - snowflake user_id; //!< the user id this voice state is for - std::string session_id; //!< the session id for this voice state - uint8_t flags; //!< Voice state flags (see dpp::voicestate_flags) - time_t request_to_speak; //!< The time at which the user requested to speak, or 0 - - /** - * @brief Construct a new voicestate object - */ - voicestate(); - - /** - * @brief Destroy the voicestate object - */ - virtual ~voicestate() = default; - - /** - * @brief Fill voicestate object from json data - * - * @param j JSON data to fill from - * @return voicestate& Reference to self - */ - voicestate& fill_from_json(nlohmann::json* j); - - /** - * @brief Build json representation of the object - * - * @param with_id Add ID to output - * @return std::string JSON string - */ - virtual std::string build_json(bool with_id = false) const; - - /// Return true if the user is deafened by the server - bool is_deaf() const; - - /// Return true if the user is muted by the server - bool is_mute() const; - - /// Return true if user muted themselves - bool is_self_mute() const; - - /// Return true if user deafened themselves - bool is_self_deaf() const; - - /// Return true if the user is streaming using "Go Live" - bool self_stream() const; - - /// Return true if the user's camera is enabled - bool self_video() const; - - /// Return true if user is suppressed. - /// "HELP HELP I'M BEING SUPPRESSED!" - bool is_suppressed() const; -}; - -/** A container of voicestates */ -typedef std::unordered_map voicestate_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Bit mask flags relating to voice states + */ +enum voicestate_flags { + vs_deaf = 0b00000001, //!< Deafened by the server + vs_mute = 0b00000010, //!< Muted by the server + vs_self_mute = 0b00000100, //!< Locally Muted + vs_self_deaf = 0b00001000, //!< Locally deafened + vs_self_stream = 0b00010000, //!< Whether this user is streaming using "Go Live" + vs_self_video = 0b00100000, //!< Whether this user's camera is enabled + vs_suppress = 0b01000000 //!< Whether this user's permission to speak is denied +}; + +/** + * @brief Represents the voice state of a user on a guild + * These are stored in the dpp::guild object, and accessible there, + * or via dpp::channel::get_voice_members + */ +class DPP_EXPORT voicestate : public json_interface { +public: + class discord_client* shard; //!< Owning shard + snowflake guild_id; //!< Optional: the guild id this voice state is for + snowflake channel_id; //!< the channel id this user is connected to (may be empty) + snowflake user_id; //!< the user id this voice state is for + std::string session_id; //!< the session id for this voice state + uint8_t flags; //!< Voice state flags (see dpp::voicestate_flags) + time_t request_to_speak; //!< The time at which the user requested to speak, or 0 + + /** + * @brief Construct a new voicestate object + */ + voicestate(); + + /** + * @brief Destroy the voicestate object + */ + virtual ~voicestate() = default; + + /** + * @brief Fill voicestate object from json data + * + * @param j JSON data to fill from + * @return voicestate& Reference to self + */ + voicestate& fill_from_json(nlohmann::json* j); + + /** + * @brief Build json representation of the object + * + * @param with_id Add ID to output + * @return std::string JSON string + */ + virtual std::string build_json(bool with_id = false) const; + + /// Return true if the user is deafened by the server + bool is_deaf() const; + + /// Return true if the user is muted by the server + bool is_mute() const; + + /// Return true if user muted themselves + bool is_self_mute() const; + + /// Return true if user deafened themselves + bool is_self_deaf() const; + + /// Return true if the user is streaming using "Go Live" + bool self_stream() const; + + /// Return true if the user's camera is enabled + bool self_video() const; + + /// Return true if user is suppressed. + /// "HELP HELP I'M BEING SUPPRESSED!" + bool is_suppressed() const; +}; + +/** A container of voicestates */ +typedef std::unordered_map voicestate_map; + +}; diff --git a/3rdParty/dpp/webhook.h b/3rdParty/dpp/webhook.h index 98fa1767fc..003f0b6cf8 100644 --- a/3rdParty/dpp/webhook.h +++ b/3rdParty/dpp/webhook.h @@ -1,113 +1,113 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Defines types of webhook - */ -enum webhook_type { - w_incoming = 1, //!< Incoming webhook - w_channel_follower = 2 //!< Channel following webhook -}; - -/** - * @brief Represents a discord webhook - */ -class DPP_EXPORT webhook : public managed, public json_interface { -public: - uint8_t type; //!< the type of the webhook - snowflake guild_id; //!< Optional: the guild id this webhook is for - snowflake channel_id; //!< the channel id this webhook is for - snowflake user_id; //!< Optional: the user this webhook was created by (not returned when getting a webhook with its token) - std::string name; //!< the default name of the webhook (may be empty) - std::string avatar; //!< the default avatar of the webhook (may be empty) - std::string token; //!< Optional: the secure token of the webhook (returned for Incoming Webhooks) - snowflake application_id; //!< the bot/OAuth2 application that created this webhook (may be empty) - std::string* image_data; //!< base64 encoded image data if uploading a new image - - /** - * @brief Construct a new webhook object - */ - webhook(); - - /** - * @brief Construct a new webhook object using the Webhook URL provided by Discord - * - * @param webhook_url a fully qualified web address of an existing webhook - */ - webhook(const std::string& webhook_url); - - /** - * @brief Construct a new webhook object using the webhook ID and the webhook token - * - * @param webhook_id id taken from a link of an existing webhook - * @param webhook_token token taken from a link of an existing webhook - */ - webhook(const snowflake webhook_id, const std::string& webhook_token); - - /** - * @brief Destroy the webhook object - */ - ~webhook(); - - /** - * @brief Fill in object from json data - * - * @param j JSON data - * @return webhook& Reference to self - */ - webhook& fill_from_json(nlohmann::json* j); - - /** - * @brief Build JSON string from object - * - * @param with_id Include the ID of the webhook in the json - * @return std::string JSON encoded object - */ - virtual std::string build_json(bool with_id = false) const; - - /** - * @brief Base64 encode image data and allocate it to image_data - * - * @param image_blob Binary image data - * @param type Image type - * @param is_base64_encoded True if the image data is already base64 encoded - * @return webhook& Reference to self - * @throw dpp::exception Image data is larger than the maximum size of 256 kilobytes - */ - webhook& load_image(const std::string &image_blob, const image_type type, bool is_base64_encoded = false); -}; - -/** - * @brief A group of webhooks - */ -typedef std::unordered_map webhook_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Defines types of webhook + */ +enum webhook_type { + w_incoming = 1, //!< Incoming webhook + w_channel_follower = 2 //!< Channel following webhook +}; + +/** + * @brief Represents a discord webhook + */ +class DPP_EXPORT webhook : public managed, public json_interface { +public: + uint8_t type; //!< the type of the webhook + snowflake guild_id; //!< Optional: the guild id this webhook is for + snowflake channel_id; //!< the channel id this webhook is for + snowflake user_id; //!< Optional: the user this webhook was created by (not returned when getting a webhook with its token) + std::string name; //!< the default name of the webhook (may be empty) + std::string avatar; //!< the default avatar of the webhook (may be empty) + std::string token; //!< Optional: the secure token of the webhook (returned for Incoming Webhooks) + snowflake application_id; //!< the bot/OAuth2 application that created this webhook (may be empty) + std::string* image_data; //!< base64 encoded image data if uploading a new image + + /** + * @brief Construct a new webhook object + */ + webhook(); + + /** + * @brief Construct a new webhook object using the Webhook URL provided by Discord + * + * @param webhook_url a fully qualified web address of an existing webhook + */ + webhook(const std::string& webhook_url); + + /** + * @brief Construct a new webhook object using the webhook ID and the webhook token + * + * @param webhook_id id taken from a link of an existing webhook + * @param webhook_token token taken from a link of an existing webhook + */ + webhook(const snowflake webhook_id, const std::string& webhook_token); + + /** + * @brief Destroy the webhook object + */ + ~webhook(); + + /** + * @brief Fill in object from json data + * + * @param j JSON data + * @return webhook& Reference to self + */ + webhook& fill_from_json(nlohmann::json* j); + + /** + * @brief Build JSON string from object + * + * @param with_id Include the ID of the webhook in the json + * @return std::string JSON encoded object + */ + virtual std::string build_json(bool with_id = false) const; + + /** + * @brief Base64 encode image data and allocate it to image_data + * + * @param image_blob Binary image data + * @param type Image type + * @param is_base64_encoded True if the image data is already base64 encoded + * @return webhook& Reference to self + * @throw dpp::exception Image data is larger than the maximum size of 256 kilobytes + */ + webhook& load_image(const std::string &image_blob, const image_type type, bool is_base64_encoded = false); +}; + +/** + * @brief A group of webhooks + */ +typedef std::unordered_map webhook_map; + +}; diff --git a/3rdParty/dpp/win32_safe_warnings.h b/3rdParty/dpp/win32_safe_warnings.h index 104b6660bb..c4a09d21ea 100644 --- a/3rdParty/dpp/win32_safe_warnings.h +++ b/3rdParty/dpp/win32_safe_warnings.h @@ -1,32 +1,32 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once - -/* This file contains pragmas to disable warnings on win32 builds with msvc only. - * It is only included during build of D++ itself, and not when including the headers - * into a user's project. - * - * Before adding a warning here please be ABSOLUTELY SURE it is one we cannot easily fix - * and is to be silenced, thrown into the sarlacc pit to be eaten for 1000 years... - */ - -_Pragma("warning( disable : 4251 )"); // 4251 warns when we export classes or structures with stl member variables -_Pragma("warning( disable : 5105 )"); // 5105 is to do with macro warnings +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once + +/* This file contains pragmas to disable warnings on win32 builds with msvc only. + * It is only included during build of D++ itself, and not when including the headers + * into a user's project. + * + * Before adding a warning here please be ABSOLUTELY SURE it is one we cannot easily fix + * and is to be silenced, thrown into the sarlacc pit to be eaten for 1000 years... + */ + +_Pragma("warning( disable : 4251 )"); // 4251 warns when we export classes or structures with stl member variables +_Pragma("warning( disable : 5105 )"); // 5105 is to do with macro warnings diff --git a/3rdParty/dpp/wsclient.h b/3rdParty/dpp/wsclient.h index 6f05840f5c..6c1b919046 100644 --- a/3rdParty/dpp/wsclient.h +++ b/3rdParty/dpp/wsclient.h @@ -1,212 +1,212 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Websocket protocol types available on Discord - */ -enum websocket_protocol_t : uint8_t { - /** - * @brief JSON data, text, UTF-8 character set - */ - ws_json = 0, - /** - * @brief Erlang Term Format (ETF) binary protocol - */ - ws_etf = 1 -}; - -/** - * @brief Websocket connection status - */ -enum ws_state : uint8_t { - /** - * @brief Sending/receiving HTTP headers, acting as a standard HTTP connection. - * This is the state prior to receiving "HTTP/1.1 101 Switching Protocols" from the - * server side. - */ - HTTP_HEADERS, - - /** - * @brief Connected as a websocket, and "upgraded". Now talking using binary frames. - */ - CONNECTED -}; - -/** - * @brief Low-level websocket opcodes for frames - */ -enum ws_opcode : uint8_t -{ - OP_CONTINUATION = 0x00, //!< Continuation - OP_TEXT = 0x01, //!< Text frame - OP_BINARY = 0x02, //!< Binary frame - OP_CLOSE = 0x08, //!< Close notification with close code - OP_PING = 0x09, //!< Low level ping - OP_PONG = 0x0a //!< Low level pong -}; - -/** - * @brief Implements a websocket client based on the SSL client - */ -class DPP_EXPORT websocket_client : public ssl_client -{ - /** - * @brief Connection key used in the HTTP headers - */ - std::string key; - - /** - * @brief Current websocket state - */ - ws_state state; - - /** - * @brief Path part of URL for websocket - */ - std::string path; - - /** - * @brief Data opcode, represents the type of frames we send - */ - ws_opcode data_opcode; - - /** - * @brief HTTP headers received on connecting/upgrading - */ - std::map http_headers; - - /** - * @brief Parse headers for a websocket frame from the buffer. - * @param buffer The buffer to operate on. Will modify the string removing completed items from the head of the queue - * @return true if a complete header has been received - */ - bool parseheader(std::string &buffer); - - /** - * @brief Unpack a frame and pass completed frames up the stack. - * @param buffer The buffer to operate on. Gets modified to remove completed frames on the head of the buffer - * @param offset The offset to start at (reserved for future use) - * @param first True if is the first element (reserved for future use) - * @return true if a complete frame has been received - */ - bool unpack(std::string &buffer, uint32_t offset, bool first = true); - - /** - * @brief Fill a header for outbound messages - * @param outbuf The raw frame to fill - * @param sendlength The size of the data to encapsulate - * @param opcode the ws_opcode to send in the header - * @return size of filled header - */ - size_t fill_header(unsigned char* outbuf, size_t sendlength, ws_opcode opcode); - - /** - * @brief Handle ping and pong requests. - * @param ping True if this is a ping, false if it is a pong - * @param payload The ping payload, to be returned as-is for a ping - */ - void handle_ping_pong(bool ping, const std::string &payload); - -protected: - - /** - * @brief (Re)connect - */ - virtual void connect(); - - /** - * @brief Get websocket state - * @return websocket state - */ - ws_state get_state(); - -public: - - /** - * @brief Connect to a specific websocket server. - * @param hostname Hostname to connect to - * @param port Port to connect to - * @param urlpath The URL path components of the HTTP request to send - * @param opcode The encoding type to use, either OP_BINARY or OP_TEXT - * @note Voice websockets only support OP_TEXT, and other websockets must be - * OP_BINARY if you are going to send ETF. - */ - websocket_client(const std::string &hostname, const std::string &port = "443", const std::string &urlpath = "", ws_opcode opcode = OP_BINARY); - - /** - * @brief Destroy the websocket client object - */ - virtual ~websocket_client(); - - /** - * @brief Write to websocket. Encapsulates data in frames if the status is CONNECTED. - * @param data The data to send. - */ - virtual void write(const std::string &data); - - /** - * @brief Processes incoming frames from the SSL socket input buffer. - * @param buffer The buffer contents. Can modify this value removing the head elements when processed. - */ - virtual bool handle_buffer(std::string &buffer); - - /** - * @brief Close websocket - */ - virtual void close(); - - /** - * @brief Receives raw frame content only without headers - * - * @param buffer The buffer contents - * @return True if the frame was successfully handled. False if no valid frame is in the buffer. - */ - virtual bool handle_frame(const std::string &buffer); - - /** - * @brief Called upon error frame. - * - * @param errorcode The error code from the websocket server - */ - virtual void error(uint32_t errorcode); - - /** - * @brief Fires every second from the underlying socket I/O loop, used for sending websocket pings - */ - virtual void one_second_timer(); - - /** - * @brief Send OP_CLOSE error code 1000 to the other side of the connection. - * This indicates graceful close. - */ - void send_close_packet(); -}; - +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Websocket protocol types available on Discord + */ +enum websocket_protocol_t : uint8_t { + /** + * @brief JSON data, text, UTF-8 character set + */ + ws_json = 0, + /** + * @brief Erlang Term Format (ETF) binary protocol + */ + ws_etf = 1 +}; + +/** + * @brief Websocket connection status + */ +enum ws_state : uint8_t { + /** + * @brief Sending/receiving HTTP headers, acting as a standard HTTP connection. + * This is the state prior to receiving "HTTP/1.1 101 Switching Protocols" from the + * server side. + */ + HTTP_HEADERS, + + /** + * @brief Connected as a websocket, and "upgraded". Now talking using binary frames. + */ + CONNECTED +}; + +/** + * @brief Low-level websocket opcodes for frames + */ +enum ws_opcode : uint8_t +{ + OP_CONTINUATION = 0x00, //!< Continuation + OP_TEXT = 0x01, //!< Text frame + OP_BINARY = 0x02, //!< Binary frame + OP_CLOSE = 0x08, //!< Close notification with close code + OP_PING = 0x09, //!< Low level ping + OP_PONG = 0x0a //!< Low level pong +}; + +/** + * @brief Implements a websocket client based on the SSL client + */ +class DPP_EXPORT websocket_client : public ssl_client +{ + /** + * @brief Connection key used in the HTTP headers + */ + std::string key; + + /** + * @brief Current websocket state + */ + ws_state state; + + /** + * @brief Path part of URL for websocket + */ + std::string path; + + /** + * @brief Data opcode, represents the type of frames we send + */ + ws_opcode data_opcode; + + /** + * @brief HTTP headers received on connecting/upgrading + */ + std::map http_headers; + + /** + * @brief Parse headers for a websocket frame from the buffer. + * @param buffer The buffer to operate on. Will modify the string removing completed items from the head of the queue + * @return true if a complete header has been received + */ + bool parseheader(std::string &buffer); + + /** + * @brief Unpack a frame and pass completed frames up the stack. + * @param buffer The buffer to operate on. Gets modified to remove completed frames on the head of the buffer + * @param offset The offset to start at (reserved for future use) + * @param first True if is the first element (reserved for future use) + * @return true if a complete frame has been received + */ + bool unpack(std::string &buffer, uint32_t offset, bool first = true); + + /** + * @brief Fill a header for outbound messages + * @param outbuf The raw frame to fill + * @param sendlength The size of the data to encapsulate + * @param opcode the ws_opcode to send in the header + * @return size of filled header + */ + size_t fill_header(unsigned char* outbuf, size_t sendlength, ws_opcode opcode); + + /** + * @brief Handle ping and pong requests. + * @param ping True if this is a ping, false if it is a pong + * @param payload The ping payload, to be returned as-is for a ping + */ + void handle_ping_pong(bool ping, const std::string &payload); + +protected: + + /** + * @brief (Re)connect + */ + virtual void connect(); + + /** + * @brief Get websocket state + * @return websocket state + */ + ws_state get_state(); + +public: + + /** + * @brief Connect to a specific websocket server. + * @param hostname Hostname to connect to + * @param port Port to connect to + * @param urlpath The URL path components of the HTTP request to send + * @param opcode The encoding type to use, either OP_BINARY or OP_TEXT + * @note Voice websockets only support OP_TEXT, and other websockets must be + * OP_BINARY if you are going to send ETF. + */ + websocket_client(const std::string &hostname, const std::string &port = "443", const std::string &urlpath = "", ws_opcode opcode = OP_BINARY); + + /** + * @brief Destroy the websocket client object + */ + virtual ~websocket_client(); + + /** + * @brief Write to websocket. Encapsulates data in frames if the status is CONNECTED. + * @param data The data to send. + */ + virtual void write(const std::string &data); + + /** + * @brief Processes incoming frames from the SSL socket input buffer. + * @param buffer The buffer contents. Can modify this value removing the head elements when processed. + */ + virtual bool handle_buffer(std::string &buffer); + + /** + * @brief Close websocket + */ + virtual void close(); + + /** + * @brief Receives raw frame content only without headers + * + * @param buffer The buffer contents + * @return True if the frame was successfully handled. False if no valid frame is in the buffer. + */ + virtual bool handle_frame(const std::string &buffer); + + /** + * @brief Called upon error frame. + * + * @param errorcode The error code from the websocket server + */ + virtual void error(uint32_t errorcode); + + /** + * @brief Fires every second from the underlying socket I/O loop, used for sending websocket pings + */ + virtual void one_second_timer(); + + /** + * @brief Send OP_CLOSE error code 1000 to the other side of the connection. + * This indicates graceful close. + */ + void send_close_packet(); +}; + }; \ No newline at end of file diff --git a/3rdParty/nlohmann/json.hpp b/3rdParty/nlohmann/json.hpp index cb27e05811..880d7d9d45 100644 --- a/3rdParty/nlohmann/json.hpp +++ b/3rdParty/nlohmann/json.hpp @@ -1,22091 +1,22091 @@ -/* - __ _____ _____ _____ - __| | __| | | | JSON for Modern C++ -| | |__ | | | | | | version 3.10.5 -|_____|_____|_____|_|___| https://github.com/nlohmann/json - -Licensed under the MIT License . -SPDX-License-Identifier: MIT -Copyright (c) 2013-2022 Niels Lohmann . - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -/****************************************************************************\ - * Note on documentation: The source files contain links to the online * - * documentation of the public API at https://json.nlohmann.me. This URL * - * contains the most recent documentation and should also be applicable to * - * previous versions; documentation for deprecated functions is not * - * removed, but marked deprecated. See "Generate documentation" section in * - * file doc/README.md. * -\****************************************************************************/ - -#ifndef INCLUDE_NLOHMANN_JSON_HPP_ -#define INCLUDE_NLOHMANN_JSON_HPP_ - -#define NLOHMANN_JSON_VERSION_MAJOR 3 -#define NLOHMANN_JSON_VERSION_MINOR 10 -#define NLOHMANN_JSON_VERSION_PATCH 5 - -#include // all_of, find, for_each -#include // nullptr_t, ptrdiff_t, size_t -#include // hash, less -#include // initializer_list -#ifndef JSON_NO_IO - #include // istream, ostream -#endif // JSON_NO_IO -#include // random_access_iterator_tag -#include // unique_ptr -#include // accumulate -#include // string, stoi, to_string -#include // declval, forward, move, pair, swap -#include // vector - -// #include - - -#include -#include - -// #include - - -#include // transform -#include // array -#include // forward_list -#include // inserter, front_inserter, end -#include // map -#include // string -#include // tuple, make_tuple -#include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible -#include // unordered_map -#include // pair, declval -#include // valarray - -// #include - - -#include // exception -#include // runtime_error -#include // to_string -#include // vector - -// #include - - -#include // array -#include // size_t -#include // uint8_t -#include // string - -namespace nlohmann -{ -namespace detail -{ -/////////////////////////// -// JSON type enumeration // -/////////////////////////// - -/*! -@brief the JSON type enumeration - -This enumeration collects the different JSON types. It is internally used to -distinguish the stored values, and the functions @ref basic_json::is_null(), -@ref basic_json::is_object(), @ref basic_json::is_array(), -@ref basic_json::is_string(), @ref basic_json::is_boolean(), -@ref basic_json::is_number() (with @ref basic_json::is_number_integer(), -@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), -@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and -@ref basic_json::is_structured() rely on it. - -@note There are three enumeration entries (number_integer, number_unsigned, and -number_float), because the library distinguishes these three types for numbers: -@ref basic_json::number_unsigned_t is used for unsigned integers, -@ref basic_json::number_integer_t is used for signed integers, and -@ref basic_json::number_float_t is used for floating-point numbers or to -approximate integers which do not fit in the limits of their respective type. - -@sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON -value with the default value for a given type - -@since version 1.0.0 -*/ -enum class value_t : std::uint8_t -{ - null, ///< null value - object, ///< object (unordered set of name/value pairs) - array, ///< array (ordered collection of values) - string, ///< string value - boolean, ///< boolean value - number_integer, ///< number value (signed integer) - number_unsigned, ///< number value (unsigned integer) - number_float, ///< number value (floating-point) - binary, ///< binary array (ordered collection of bytes) - discarded ///< discarded by the parser callback function -}; - -/*! -@brief comparison operator for JSON types - -Returns an ordering that is similar to Python: -- order: null < boolean < number < object < array < string < binary -- furthermore, each type is not smaller than itself -- discarded values are not comparable -- binary is represented as a b"" string in python and directly comparable to a - string; however, making a binary array directly comparable with a string would - be surprising behavior in a JSON file. - -@since version 1.0.0 -*/ -inline bool operator<(const value_t lhs, const value_t rhs) noexcept -{ - static constexpr std::array order = {{ - 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */, - 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */, - 6 /* binary */ - } - }; - - const auto l_index = static_cast(lhs); - const auto r_index = static_cast(rhs); - return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index]; -} -} // namespace detail -} // namespace nlohmann - -// #include - - -#include -// #include - - -#include // declval, pair -// #include - - -/* Hedley - https://nemequ.github.io/hedley - * Created by Evan Nemerson - * - * To the extent possible under law, the author(s) have dedicated all - * copyright and related and neighboring rights to this software to - * the public domain worldwide. This software is distributed without - * any warranty. - * - * For details, see . - * SPDX-License-Identifier: CC0-1.0 - */ - -#if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 15) -#if defined(JSON_HEDLEY_VERSION) - #undef JSON_HEDLEY_VERSION -#endif -#define JSON_HEDLEY_VERSION 15 - -#if defined(JSON_HEDLEY_STRINGIFY_EX) - #undef JSON_HEDLEY_STRINGIFY_EX -#endif -#define JSON_HEDLEY_STRINGIFY_EX(x) #x - -#if defined(JSON_HEDLEY_STRINGIFY) - #undef JSON_HEDLEY_STRINGIFY -#endif -#define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x) - -#if defined(JSON_HEDLEY_CONCAT_EX) - #undef JSON_HEDLEY_CONCAT_EX -#endif -#define JSON_HEDLEY_CONCAT_EX(a,b) a##b - -#if defined(JSON_HEDLEY_CONCAT) - #undef JSON_HEDLEY_CONCAT -#endif -#define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b) - -#if defined(JSON_HEDLEY_CONCAT3_EX) - #undef JSON_HEDLEY_CONCAT3_EX -#endif -#define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c - -#if defined(JSON_HEDLEY_CONCAT3) - #undef JSON_HEDLEY_CONCAT3 -#endif -#define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c) - -#if defined(JSON_HEDLEY_VERSION_ENCODE) - #undef JSON_HEDLEY_VERSION_ENCODE -#endif -#define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision)) - -#if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR) - #undef JSON_HEDLEY_VERSION_DECODE_MAJOR -#endif -#define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000) - -#if defined(JSON_HEDLEY_VERSION_DECODE_MINOR) - #undef JSON_HEDLEY_VERSION_DECODE_MINOR -#endif -#define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000) - -#if defined(JSON_HEDLEY_VERSION_DECODE_REVISION) - #undef JSON_HEDLEY_VERSION_DECODE_REVISION -#endif -#define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000) - -#if defined(JSON_HEDLEY_GNUC_VERSION) - #undef JSON_HEDLEY_GNUC_VERSION -#endif -#if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__) - #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) -#elif defined(__GNUC__) - #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0) -#endif - -#if defined(JSON_HEDLEY_GNUC_VERSION_CHECK) - #undef JSON_HEDLEY_GNUC_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_GNUC_VERSION) - #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_MSVC_VERSION) - #undef JSON_HEDLEY_MSVC_VERSION -#endif -#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) && !defined(__ICL) - #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100) -#elif defined(_MSC_FULL_VER) && !defined(__ICL) - #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10) -#elif defined(_MSC_VER) && !defined(__ICL) - #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0) -#endif - -#if defined(JSON_HEDLEY_MSVC_VERSION_CHECK) - #undef JSON_HEDLEY_MSVC_VERSION_CHECK -#endif -#if !defined(JSON_HEDLEY_MSVC_VERSION) - #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0) -#elif defined(_MSC_VER) && (_MSC_VER >= 1400) - #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch))) -#elif defined(_MSC_VER) && (_MSC_VER >= 1200) - #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch))) -#else - #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor))) -#endif - -#if defined(JSON_HEDLEY_INTEL_VERSION) - #undef JSON_HEDLEY_INTEL_VERSION -#endif -#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && !defined(__ICL) - #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE) -#elif defined(__INTEL_COMPILER) && !defined(__ICL) - #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0) -#endif - -#if defined(JSON_HEDLEY_INTEL_VERSION_CHECK) - #undef JSON_HEDLEY_INTEL_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_INTEL_VERSION) - #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_INTEL_CL_VERSION) - #undef JSON_HEDLEY_INTEL_CL_VERSION -#endif -#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && defined(__ICL) - #define JSON_HEDLEY_INTEL_CL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER, __INTEL_COMPILER_UPDATE, 0) -#endif - -#if defined(JSON_HEDLEY_INTEL_CL_VERSION_CHECK) - #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_INTEL_CL_VERSION) - #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_CL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_PGI_VERSION) - #undef JSON_HEDLEY_PGI_VERSION -#endif -#if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__) - #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__) -#endif - -#if defined(JSON_HEDLEY_PGI_VERSION_CHECK) - #undef JSON_HEDLEY_PGI_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_PGI_VERSION) - #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_SUNPRO_VERSION) - #undef JSON_HEDLEY_SUNPRO_VERSION -#endif -#if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000) - #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10) -#elif defined(__SUNPRO_C) - #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf) -#elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000) - #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10) -#elif defined(__SUNPRO_CC) - #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf) -#endif - -#if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK) - #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_SUNPRO_VERSION) - #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) - #undef JSON_HEDLEY_EMSCRIPTEN_VERSION -#endif -#if defined(__EMSCRIPTEN__) - #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__) -#endif - -#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK) - #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) - #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_ARM_VERSION) - #undef JSON_HEDLEY_ARM_VERSION -#endif -#if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION) - #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100) -#elif defined(__CC_ARM) && defined(__ARMCC_VERSION) - #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100) -#endif - -#if defined(JSON_HEDLEY_ARM_VERSION_CHECK) - #undef JSON_HEDLEY_ARM_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_ARM_VERSION) - #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_IBM_VERSION) - #undef JSON_HEDLEY_IBM_VERSION -#endif -#if defined(__ibmxl__) - #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__) -#elif defined(__xlC__) && defined(__xlC_ver__) - #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff) -#elif defined(__xlC__) - #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0) -#endif - -#if defined(JSON_HEDLEY_IBM_VERSION_CHECK) - #undef JSON_HEDLEY_IBM_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_IBM_VERSION) - #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_TI_VERSION) - #undef JSON_HEDLEY_TI_VERSION -#endif -#if \ - defined(__TI_COMPILER_VERSION__) && \ - ( \ - defined(__TMS470__) || defined(__TI_ARM__) || \ - defined(__MSP430__) || \ - defined(__TMS320C2000__) \ - ) -#if (__TI_COMPILER_VERSION__ >= 16000000) - #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) -#endif -#endif - -#if defined(JSON_HEDLEY_TI_VERSION_CHECK) - #undef JSON_HEDLEY_TI_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_TI_VERSION) - #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_TI_CL2000_VERSION) - #undef JSON_HEDLEY_TI_CL2000_VERSION -#endif -#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__) - #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) -#endif - -#if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK) - #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_TI_CL2000_VERSION) - #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_TI_CL430_VERSION) - #undef JSON_HEDLEY_TI_CL430_VERSION -#endif -#if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__) - #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) -#endif - -#if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK) - #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_TI_CL430_VERSION) - #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) - #undef JSON_HEDLEY_TI_ARMCL_VERSION -#endif -#if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__)) - #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) -#endif - -#if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK) - #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) - #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_TI_CL6X_VERSION) - #undef JSON_HEDLEY_TI_CL6X_VERSION -#endif -#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__) - #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) -#endif - -#if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK) - #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_TI_CL6X_VERSION) - #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_TI_CL7X_VERSION) - #undef JSON_HEDLEY_TI_CL7X_VERSION -#endif -#if defined(__TI_COMPILER_VERSION__) && defined(__C7000__) - #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) -#endif - -#if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK) - #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_TI_CL7X_VERSION) - #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) - #undef JSON_HEDLEY_TI_CLPRU_VERSION -#endif -#if defined(__TI_COMPILER_VERSION__) && defined(__PRU__) - #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) -#endif - -#if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK) - #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) - #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_CRAY_VERSION) - #undef JSON_HEDLEY_CRAY_VERSION -#endif -#if defined(_CRAYC) - #if defined(_RELEASE_PATCHLEVEL) - #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL) - #else - #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0) - #endif -#endif - -#if defined(JSON_HEDLEY_CRAY_VERSION_CHECK) - #undef JSON_HEDLEY_CRAY_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_CRAY_VERSION) - #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_IAR_VERSION) - #undef JSON_HEDLEY_IAR_VERSION -#endif -#if defined(__IAR_SYSTEMS_ICC__) - #if __VER__ > 1000 - #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000)) - #else - #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(__VER__ / 100, __VER__ % 100, 0) - #endif -#endif - -#if defined(JSON_HEDLEY_IAR_VERSION_CHECK) - #undef JSON_HEDLEY_IAR_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_IAR_VERSION) - #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_TINYC_VERSION) - #undef JSON_HEDLEY_TINYC_VERSION -#endif -#if defined(__TINYC__) - #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100) -#endif - -#if defined(JSON_HEDLEY_TINYC_VERSION_CHECK) - #undef JSON_HEDLEY_TINYC_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_TINYC_VERSION) - #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_DMC_VERSION) - #undef JSON_HEDLEY_DMC_VERSION -#endif -#if defined(__DMC__) - #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf) -#endif - -#if defined(JSON_HEDLEY_DMC_VERSION_CHECK) - #undef JSON_HEDLEY_DMC_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_DMC_VERSION) - #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_COMPCERT_VERSION) - #undef JSON_HEDLEY_COMPCERT_VERSION -#endif -#if defined(__COMPCERT_VERSION__) - #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100) -#endif - -#if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK) - #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_COMPCERT_VERSION) - #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_PELLES_VERSION) - #undef JSON_HEDLEY_PELLES_VERSION -#endif -#if defined(__POCC__) - #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0) -#endif - -#if defined(JSON_HEDLEY_PELLES_VERSION_CHECK) - #undef JSON_HEDLEY_PELLES_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_PELLES_VERSION) - #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_MCST_LCC_VERSION) - #undef JSON_HEDLEY_MCST_LCC_VERSION -#endif -#if defined(__LCC__) && defined(__LCC_MINOR__) - #define JSON_HEDLEY_MCST_LCC_VERSION JSON_HEDLEY_VERSION_ENCODE(__LCC__ / 100, __LCC__ % 100, __LCC_MINOR__) -#endif - -#if defined(JSON_HEDLEY_MCST_LCC_VERSION_CHECK) - #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_MCST_LCC_VERSION) - #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_MCST_LCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_GCC_VERSION) - #undef JSON_HEDLEY_GCC_VERSION -#endif -#if \ - defined(JSON_HEDLEY_GNUC_VERSION) && \ - !defined(__clang__) && \ - !defined(JSON_HEDLEY_INTEL_VERSION) && \ - !defined(JSON_HEDLEY_PGI_VERSION) && \ - !defined(JSON_HEDLEY_ARM_VERSION) && \ - !defined(JSON_HEDLEY_CRAY_VERSION) && \ - !defined(JSON_HEDLEY_TI_VERSION) && \ - !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \ - !defined(JSON_HEDLEY_TI_CL430_VERSION) && \ - !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \ - !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \ - !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \ - !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \ - !defined(__COMPCERT__) && \ - !defined(JSON_HEDLEY_MCST_LCC_VERSION) - #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION -#endif - -#if defined(JSON_HEDLEY_GCC_VERSION_CHECK) - #undef JSON_HEDLEY_GCC_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_GCC_VERSION) - #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_HAS_ATTRIBUTE) - #undef JSON_HEDLEY_HAS_ATTRIBUTE -#endif -#if \ - defined(__has_attribute) && \ - ( \ - (!defined(JSON_HEDLEY_IAR_VERSION) || JSON_HEDLEY_IAR_VERSION_CHECK(8,5,9)) \ - ) -# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute) -#else -# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0) -#endif - -#if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE) - #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE -#endif -#if defined(__has_attribute) - #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) -#else - #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE) - #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE -#endif -#if defined(__has_attribute) - #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) -#else - #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE) - #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE -#endif -#if \ - defined(__has_cpp_attribute) && \ - defined(__cplusplus) && \ - (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) - #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute) -#else - #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0) -#endif - -#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS) - #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS -#endif -#if !defined(__cplusplus) || !defined(__has_cpp_attribute) - #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) -#elif \ - !defined(JSON_HEDLEY_PGI_VERSION) && \ - !defined(JSON_HEDLEY_IAR_VERSION) && \ - (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \ - (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0)) - #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute) -#else - #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) -#endif - -#if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE) - #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE -#endif -#if defined(__has_cpp_attribute) && defined(__cplusplus) - #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) -#else - #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE) - #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE -#endif -#if defined(__has_cpp_attribute) && defined(__cplusplus) - #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) -#else - #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_HAS_BUILTIN) - #undef JSON_HEDLEY_HAS_BUILTIN -#endif -#if defined(__has_builtin) - #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin) -#else - #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0) -#endif - -#if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN) - #undef JSON_HEDLEY_GNUC_HAS_BUILTIN -#endif -#if defined(__has_builtin) - #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) -#else - #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_GCC_HAS_BUILTIN) - #undef JSON_HEDLEY_GCC_HAS_BUILTIN -#endif -#if defined(__has_builtin) - #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) -#else - #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_HAS_FEATURE) - #undef JSON_HEDLEY_HAS_FEATURE -#endif -#if defined(__has_feature) - #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature) -#else - #define JSON_HEDLEY_HAS_FEATURE(feature) (0) -#endif - -#if defined(JSON_HEDLEY_GNUC_HAS_FEATURE) - #undef JSON_HEDLEY_GNUC_HAS_FEATURE -#endif -#if defined(__has_feature) - #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) -#else - #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_GCC_HAS_FEATURE) - #undef JSON_HEDLEY_GCC_HAS_FEATURE -#endif -#if defined(__has_feature) - #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) -#else - #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_HAS_EXTENSION) - #undef JSON_HEDLEY_HAS_EXTENSION -#endif -#if defined(__has_extension) - #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension) -#else - #define JSON_HEDLEY_HAS_EXTENSION(extension) (0) -#endif - -#if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION) - #undef JSON_HEDLEY_GNUC_HAS_EXTENSION -#endif -#if defined(__has_extension) - #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) -#else - #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_GCC_HAS_EXTENSION) - #undef JSON_HEDLEY_GCC_HAS_EXTENSION -#endif -#if defined(__has_extension) - #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) -#else - #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE) - #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE -#endif -#if defined(__has_declspec_attribute) - #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute) -#else - #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0) -#endif - -#if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE) - #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE -#endif -#if defined(__has_declspec_attribute) - #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) -#else - #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE) - #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE -#endif -#if defined(__has_declspec_attribute) - #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) -#else - #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_HAS_WARNING) - #undef JSON_HEDLEY_HAS_WARNING -#endif -#if defined(__has_warning) - #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning) -#else - #define JSON_HEDLEY_HAS_WARNING(warning) (0) -#endif - -#if defined(JSON_HEDLEY_GNUC_HAS_WARNING) - #undef JSON_HEDLEY_GNUC_HAS_WARNING -#endif -#if defined(__has_warning) - #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) -#else - #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_GCC_HAS_WARNING) - #undef JSON_HEDLEY_GCC_HAS_WARNING -#endif -#if defined(__has_warning) - #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) -#else - #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) -#endif - -#if \ - (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ - defined(__clang__) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ - JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \ - JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \ - (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR)) - #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value) -#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) - #define JSON_HEDLEY_PRAGMA(value) __pragma(value) -#else - #define JSON_HEDLEY_PRAGMA(value) -#endif - -#if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH) - #undef JSON_HEDLEY_DIAGNOSTIC_PUSH -#endif -#if defined(JSON_HEDLEY_DIAGNOSTIC_POP) - #undef JSON_HEDLEY_DIAGNOSTIC_POP -#endif -#if defined(__clang__) - #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push") - #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop") -#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") - #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") -#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) - #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push") - #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop") -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push)) - #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop)) -#elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) - #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push") - #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop") -#elif \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) - #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push") - #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop") -#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) - #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") - #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") -#else - #define JSON_HEDLEY_DIAGNOSTIC_PUSH - #define JSON_HEDLEY_DIAGNOSTIC_POP -#endif - -/* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for - HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ -#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) - #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ -#endif -#if defined(__cplusplus) -# if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat") -# if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions") -# if JSON_HEDLEY_HAS_WARNING("-Wc++1z-extensions") -# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ - _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ - _Pragma("clang diagnostic ignored \"-Wc++1z-extensions\"") \ - xpr \ - JSON_HEDLEY_DIAGNOSTIC_POP -# else -# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ - _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ - xpr \ - JSON_HEDLEY_DIAGNOSTIC_POP -# endif -# else -# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ - xpr \ - JSON_HEDLEY_DIAGNOSTIC_POP -# endif -# endif -#endif -#if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x -#endif - -#if defined(JSON_HEDLEY_CONST_CAST) - #undef JSON_HEDLEY_CONST_CAST -#endif -#if defined(__cplusplus) -# define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast(expr)) -#elif \ - JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) -# define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \ - ((T) (expr)); \ - JSON_HEDLEY_DIAGNOSTIC_POP \ - })) -#else -# define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr)) -#endif - -#if defined(JSON_HEDLEY_REINTERPRET_CAST) - #undef JSON_HEDLEY_REINTERPRET_CAST -#endif -#if defined(__cplusplus) - #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast(expr)) -#else - #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr)) -#endif - -#if defined(JSON_HEDLEY_STATIC_CAST) - #undef JSON_HEDLEY_STATIC_CAST -#endif -#if defined(__cplusplus) - #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast(expr)) -#else - #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr)) -#endif - -#if defined(JSON_HEDLEY_CPP_CAST) - #undef JSON_HEDLEY_CPP_CAST -#endif -#if defined(__cplusplus) -# if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast") -# define JSON_HEDLEY_CPP_CAST(T, expr) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \ - ((T) (expr)) \ - JSON_HEDLEY_DIAGNOSTIC_POP -# elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0) -# define JSON_HEDLEY_CPP_CAST(T, expr) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - _Pragma("diag_suppress=Pe137") \ - JSON_HEDLEY_DIAGNOSTIC_POP -# else -# define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr)) -# endif -#else -# define JSON_HEDLEY_CPP_CAST(T, expr) (expr) -#endif - -#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED) - #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED -#endif -#if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations") - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") -#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)") -#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:1478 1786)) -#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1216,1444,1445") -#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") -#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") -#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996)) -#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") -#elif \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718") -#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)") -#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)") -#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215") -#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)") -#else - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED -#endif - -#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS) - #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS -#endif -#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"") -#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)") -#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:161)) -#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675") -#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"") -#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068)) -#elif \ - JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") -#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") -#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161") -#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 161") -#else - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS -#endif - -#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES) - #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES -#endif -#if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes") - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"") -#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") -#elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)") -#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:1292)) -#elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030)) -#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097,1098") -#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") -#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)") -#elif \ - JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173") -#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097") -#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") -#else - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES -#endif - -#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL) - #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL -#endif -#if JSON_HEDLEY_HAS_WARNING("-Wcast-qual") - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"") -#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)") -#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"") -#else - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL -#endif - -#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION) - #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION -#endif -#if JSON_HEDLEY_HAS_WARNING("-Wunused-function") - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("clang diagnostic ignored \"-Wunused-function\"") -#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("GCC diagnostic ignored \"-Wunused-function\"") -#elif JSON_HEDLEY_MSVC_VERSION_CHECK(1,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION __pragma(warning(disable:4505)) -#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("diag_suppress 3142") -#else - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION -#endif - -#if defined(JSON_HEDLEY_DEPRECATED) - #undef JSON_HEDLEY_DEPRECATED -#endif -#if defined(JSON_HEDLEY_DEPRECATED_FOR) - #undef JSON_HEDLEY_DEPRECATED_FOR -#endif -#if \ - JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since)) - #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement)) -#elif \ - (JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \ - JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since))) - #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement))) -#elif defined(__cplusplus) && (__cplusplus >= 201402L) - #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]]) - #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]]) -#elif \ - JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ - JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) - #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__)) - #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__)) -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ - JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated) - #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated) -#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) - #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated") - #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated") -#else - #define JSON_HEDLEY_DEPRECATED(since) - #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) -#endif - -#if defined(JSON_HEDLEY_UNAVAILABLE) - #undef JSON_HEDLEY_UNAVAILABLE -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since))) -#else - #define JSON_HEDLEY_UNAVAILABLE(available_since) -#endif - -#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT) - #undef JSON_HEDLEY_WARN_UNUSED_RESULT -#endif -#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG) - #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ - JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__)) - #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__)) -#elif (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L) - #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) - #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]]) -#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) - #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) - #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) -#elif defined(_Check_return_) /* SAL */ - #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_ - #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_ -#else - #define JSON_HEDLEY_WARN_UNUSED_RESULT - #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) -#endif - -#if defined(JSON_HEDLEY_SENTINEL) - #undef JSON_HEDLEY_SENTINEL -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position))) -#else - #define JSON_HEDLEY_SENTINEL(position) -#endif - -#if defined(JSON_HEDLEY_NO_RETURN) - #undef JSON_HEDLEY_NO_RETURN -#endif -#if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) - #define JSON_HEDLEY_NO_RETURN __noreturn -#elif \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) -#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L - #define JSON_HEDLEY_NO_RETURN _Noreturn -#elif defined(__cplusplus) && (__cplusplus >= 201103L) - #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]]) -#elif \ - JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) - #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) -#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) - #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return") -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) -#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) - #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;") -#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) - #define JSON_HEDLEY_NO_RETURN __attribute((noreturn)) -#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) - #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) -#else - #define JSON_HEDLEY_NO_RETURN -#endif - -#if defined(JSON_HEDLEY_NO_ESCAPE) - #undef JSON_HEDLEY_NO_ESCAPE -#endif -#if JSON_HEDLEY_HAS_ATTRIBUTE(noescape) - #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__)) -#else - #define JSON_HEDLEY_NO_ESCAPE -#endif - -#if defined(JSON_HEDLEY_UNREACHABLE) - #undef JSON_HEDLEY_UNREACHABLE -#endif -#if defined(JSON_HEDLEY_UNREACHABLE_RETURN) - #undef JSON_HEDLEY_UNREACHABLE_RETURN -#endif -#if defined(JSON_HEDLEY_ASSUME) - #undef JSON_HEDLEY_ASSUME -#endif -#if \ - JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_ASSUME(expr) __assume(expr) -#elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume) - #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr) -#elif \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) - #if defined(__cplusplus) - #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr) - #else - #define JSON_HEDLEY_ASSUME(expr) _nassert(expr) - #endif -#endif -#if \ - (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ - JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5) || \ - JSON_HEDLEY_CRAY_VERSION_CHECK(10,0,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable() -#elif defined(JSON_HEDLEY_ASSUME) - #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) -#endif -#if !defined(JSON_HEDLEY_ASSUME) - #if defined(JSON_HEDLEY_UNREACHABLE) - #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1))) - #else - #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr) - #endif -#endif -#if defined(JSON_HEDLEY_UNREACHABLE) - #if \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) - #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value)) - #else - #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE() - #endif -#else - #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value) -#endif -#if !defined(JSON_HEDLEY_UNREACHABLE) - #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) -#endif - -JSON_HEDLEY_DIAGNOSTIC_PUSH -#if JSON_HEDLEY_HAS_WARNING("-Wpedantic") - #pragma clang diagnostic ignored "-Wpedantic" -#endif -#if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus) - #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" -#endif -#if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0) - #if defined(__clang__) - #pragma clang diagnostic ignored "-Wvariadic-macros" - #elif defined(JSON_HEDLEY_GCC_VERSION) - #pragma GCC diagnostic ignored "-Wvariadic-macros" - #endif -#endif -#if defined(JSON_HEDLEY_NON_NULL) - #undef JSON_HEDLEY_NON_NULL -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) - #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__))) -#else - #define JSON_HEDLEY_NON_NULL(...) -#endif -JSON_HEDLEY_DIAGNOSTIC_POP - -#if defined(JSON_HEDLEY_PRINTF_FORMAT) - #undef JSON_HEDLEY_PRINTF_FORMAT -#endif -#if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO) - #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check))) -#elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO) - #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check))) -#elif \ - JSON_HEDLEY_HAS_ATTRIBUTE(format) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check))) -#elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0) - #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check)) -#else - #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) -#endif - -#if defined(JSON_HEDLEY_CONSTEXPR) - #undef JSON_HEDLEY_CONSTEXPR -#endif -#if defined(__cplusplus) - #if __cplusplus >= 201103L - #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr) - #endif -#endif -#if !defined(JSON_HEDLEY_CONSTEXPR) - #define JSON_HEDLEY_CONSTEXPR -#endif - -#if defined(JSON_HEDLEY_PREDICT) - #undef JSON_HEDLEY_PREDICT -#endif -#if defined(JSON_HEDLEY_LIKELY) - #undef JSON_HEDLEY_LIKELY -#endif -#if defined(JSON_HEDLEY_UNLIKELY) - #undef JSON_HEDLEY_UNLIKELY -#endif -#if defined(JSON_HEDLEY_UNPREDICTABLE) - #undef JSON_HEDLEY_UNPREDICTABLE -#endif -#if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable) - #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr)) -#endif -#if \ - (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) && !defined(JSON_HEDLEY_PGI_VERSION)) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) -# define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability)) -# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability)) -# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability)) -# define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 ) -# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 ) -#elif \ - (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \ - JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) -# define JSON_HEDLEY_PREDICT(expr, expected, probability) \ - (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))) -# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \ - (__extension__ ({ \ - double hedley_probability_ = (probability); \ - ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \ - })) -# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \ - (__extension__ ({ \ - double hedley_probability_ = (probability); \ - ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \ - })) -# define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1) -# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0) -#else -# define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)) -# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr)) -# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr)) -# define JSON_HEDLEY_LIKELY(expr) (!!(expr)) -# define JSON_HEDLEY_UNLIKELY(expr) (!!(expr)) -#endif -#if !defined(JSON_HEDLEY_UNPREDICTABLE) - #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5) -#endif - -#if defined(JSON_HEDLEY_MALLOC) - #undef JSON_HEDLEY_MALLOC -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_MALLOC __attribute__((__malloc__)) -#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) - #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory") -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_MALLOC __declspec(restrict) -#else - #define JSON_HEDLEY_MALLOC -#endif - -#if defined(JSON_HEDLEY_PURE) - #undef JSON_HEDLEY_PURE -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) -# define JSON_HEDLEY_PURE __attribute__((__pure__)) -#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) -# define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data") -#elif defined(__cplusplus) && \ - ( \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \ - ) -# define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;") -#else -# define JSON_HEDLEY_PURE -#endif - -#if defined(JSON_HEDLEY_CONST) - #undef JSON_HEDLEY_CONST -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(const) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_CONST __attribute__((__const__)) -#elif \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) - #define JSON_HEDLEY_CONST _Pragma("no_side_effect") -#else - #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE -#endif - -#if defined(JSON_HEDLEY_RESTRICT) - #undef JSON_HEDLEY_RESTRICT -#endif -#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus) - #define JSON_HEDLEY_RESTRICT restrict -#elif \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ - JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ - JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \ - JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ - defined(__clang__) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_RESTRICT __restrict -#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus) - #define JSON_HEDLEY_RESTRICT _Restrict -#else - #define JSON_HEDLEY_RESTRICT -#endif - -#if defined(JSON_HEDLEY_INLINE) - #undef JSON_HEDLEY_INLINE -#endif -#if \ - (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ - (defined(__cplusplus) && (__cplusplus >= 199711L)) - #define JSON_HEDLEY_INLINE inline -#elif \ - defined(JSON_HEDLEY_GCC_VERSION) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0) - #define JSON_HEDLEY_INLINE __inline__ -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_INLINE __inline -#else - #define JSON_HEDLEY_INLINE -#endif - -#if defined(JSON_HEDLEY_ALWAYS_INLINE) - #undef JSON_HEDLEY_ALWAYS_INLINE -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ - JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) -# define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) -# define JSON_HEDLEY_ALWAYS_INLINE __forceinline -#elif defined(__cplusplus) && \ - ( \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \ - ) -# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;") -#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) -# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced") -#else -# define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE -#endif - -#if defined(JSON_HEDLEY_NEVER_INLINE) - #undef JSON_HEDLEY_NEVER_INLINE -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ - JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) - #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__)) -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) -#elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0) - #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline") -#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) - #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;") -#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) - #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never") -#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) - #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline)) -#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) - #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) -#else - #define JSON_HEDLEY_NEVER_INLINE -#endif - -#if defined(JSON_HEDLEY_PRIVATE) - #undef JSON_HEDLEY_PRIVATE -#endif -#if defined(JSON_HEDLEY_PUBLIC) - #undef JSON_HEDLEY_PUBLIC -#endif -#if defined(JSON_HEDLEY_IMPORT) - #undef JSON_HEDLEY_IMPORT -#endif -#if defined(_WIN32) || defined(__CYGWIN__) -# define JSON_HEDLEY_PRIVATE -# define JSON_HEDLEY_PUBLIC __declspec(dllexport) -# define JSON_HEDLEY_IMPORT __declspec(dllimport) -#else -# if \ - JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ - ( \ - defined(__TI_EABI__) && \ - ( \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \ - ) \ - ) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) -# define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden"))) -# define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default"))) -# else -# define JSON_HEDLEY_PRIVATE -# define JSON_HEDLEY_PUBLIC -# endif -# define JSON_HEDLEY_IMPORT extern -#endif - -#if defined(JSON_HEDLEY_NO_THROW) - #undef JSON_HEDLEY_NO_THROW -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__)) -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) - #define JSON_HEDLEY_NO_THROW __declspec(nothrow) -#else - #define JSON_HEDLEY_NO_THROW -#endif - -#if defined(JSON_HEDLEY_FALL_THROUGH) - #undef JSON_HEDLEY_FALL_THROUGH -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__)) -#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough) - #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]]) -#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough) - #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]]) -#elif defined(__fallthrough) /* SAL */ - #define JSON_HEDLEY_FALL_THROUGH __fallthrough -#else - #define JSON_HEDLEY_FALL_THROUGH -#endif - -#if defined(JSON_HEDLEY_RETURNS_NON_NULL) - #undef JSON_HEDLEY_RETURNS_NON_NULL -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__)) -#elif defined(_Ret_notnull_) /* SAL */ - #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_ -#else - #define JSON_HEDLEY_RETURNS_NON_NULL -#endif - -#if defined(JSON_HEDLEY_ARRAY_PARAM) - #undef JSON_HEDLEY_ARRAY_PARAM -#endif -#if \ - defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ - !defined(__STDC_NO_VLA__) && \ - !defined(__cplusplus) && \ - !defined(JSON_HEDLEY_PGI_VERSION) && \ - !defined(JSON_HEDLEY_TINYC_VERSION) - #define JSON_HEDLEY_ARRAY_PARAM(name) (name) -#else - #define JSON_HEDLEY_ARRAY_PARAM(name) -#endif - -#if defined(JSON_HEDLEY_IS_CONSTANT) - #undef JSON_HEDLEY_IS_CONSTANT -#endif -#if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR) - #undef JSON_HEDLEY_REQUIRE_CONSTEXPR -#endif -/* JSON_HEDLEY_IS_CONSTEXPR_ is for - HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ -#if defined(JSON_HEDLEY_IS_CONSTEXPR_) - #undef JSON_HEDLEY_IS_CONSTEXPR_ -#endif -#if \ - JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ - (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \ - JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr) -#endif -#if !defined(__cplusplus) -# if \ - JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ - JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ - JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24) -#if defined(__INTPTR_TYPE__) - #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*) -#else - #include - #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*) -#endif -# elif \ - ( \ - defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \ - !defined(JSON_HEDLEY_SUNPRO_VERSION) && \ - !defined(JSON_HEDLEY_PGI_VERSION) && \ - !defined(JSON_HEDLEY_IAR_VERSION)) || \ - (JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0) -#if defined(__INTPTR_TYPE__) - #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0) -#else - #include - #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0) -#endif -# elif \ - defined(JSON_HEDLEY_GCC_VERSION) || \ - defined(JSON_HEDLEY_INTEL_VERSION) || \ - defined(JSON_HEDLEY_TINYC_VERSION) || \ - defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \ - defined(JSON_HEDLEY_TI_CL2000_VERSION) || \ - defined(JSON_HEDLEY_TI_CL6X_VERSION) || \ - defined(JSON_HEDLEY_TI_CL7X_VERSION) || \ - defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \ - defined(__clang__) -# define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \ - sizeof(void) != \ - sizeof(*( \ - 1 ? \ - ((void*) ((expr) * 0L) ) : \ -((struct { char v[sizeof(void) * 2]; } *) 1) \ - ) \ - ) \ - ) -# endif -#endif -#if defined(JSON_HEDLEY_IS_CONSTEXPR_) - #if !defined(JSON_HEDLEY_IS_CONSTANT) - #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr) - #endif - #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1)) -#else - #if !defined(JSON_HEDLEY_IS_CONSTANT) - #define JSON_HEDLEY_IS_CONSTANT(expr) (0) - #endif - #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr) -#endif - -#if defined(JSON_HEDLEY_BEGIN_C_DECLS) - #undef JSON_HEDLEY_BEGIN_C_DECLS -#endif -#if defined(JSON_HEDLEY_END_C_DECLS) - #undef JSON_HEDLEY_END_C_DECLS -#endif -#if defined(JSON_HEDLEY_C_DECL) - #undef JSON_HEDLEY_C_DECL -#endif -#if defined(__cplusplus) - #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" { - #define JSON_HEDLEY_END_C_DECLS } - #define JSON_HEDLEY_C_DECL extern "C" -#else - #define JSON_HEDLEY_BEGIN_C_DECLS - #define JSON_HEDLEY_END_C_DECLS - #define JSON_HEDLEY_C_DECL -#endif - -#if defined(JSON_HEDLEY_STATIC_ASSERT) - #undef JSON_HEDLEY_STATIC_ASSERT -#endif -#if \ - !defined(__cplusplus) && ( \ - (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \ - (JSON_HEDLEY_HAS_FEATURE(c_static_assert) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - defined(_Static_assert) \ - ) -# define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message) -#elif \ - (defined(__cplusplus) && (__cplusplus >= 201103L)) || \ - JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) -# define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message)) -#else -# define JSON_HEDLEY_STATIC_ASSERT(expr, message) -#endif - -#if defined(JSON_HEDLEY_NULL) - #undef JSON_HEDLEY_NULL -#endif -#if defined(__cplusplus) - #if __cplusplus >= 201103L - #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr) - #elif defined(NULL) - #define JSON_HEDLEY_NULL NULL - #else - #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0) - #endif -#elif defined(NULL) - #define JSON_HEDLEY_NULL NULL -#else - #define JSON_HEDLEY_NULL ((void*) 0) -#endif - -#if defined(JSON_HEDLEY_MESSAGE) - #undef JSON_HEDLEY_MESSAGE -#endif -#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") -# define JSON_HEDLEY_MESSAGE(msg) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ - JSON_HEDLEY_PRAGMA(message msg) \ - JSON_HEDLEY_DIAGNOSTIC_POP -#elif \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) -# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg) -#elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) -# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg) -#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) -# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) -#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0) -# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) -#else -# define JSON_HEDLEY_MESSAGE(msg) -#endif - -#if defined(JSON_HEDLEY_WARNING) - #undef JSON_HEDLEY_WARNING -#endif -#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") -# define JSON_HEDLEY_WARNING(msg) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ - JSON_HEDLEY_PRAGMA(clang warning msg) \ - JSON_HEDLEY_DIAGNOSTIC_POP -#elif \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \ - JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) -# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg) -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) -# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg)) -#else -# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg) -#endif - -#if defined(JSON_HEDLEY_REQUIRE) - #undef JSON_HEDLEY_REQUIRE -#endif -#if defined(JSON_HEDLEY_REQUIRE_MSG) - #undef JSON_HEDLEY_REQUIRE_MSG -#endif -#if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if) -# if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat") -# define JSON_HEDLEY_REQUIRE(expr) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ - __attribute__((diagnose_if(!(expr), #expr, "error"))) \ - JSON_HEDLEY_DIAGNOSTIC_POP -# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ - __attribute__((diagnose_if(!(expr), msg, "error"))) \ - JSON_HEDLEY_DIAGNOSTIC_POP -# else -# define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error"))) -# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error"))) -# endif -#else -# define JSON_HEDLEY_REQUIRE(expr) -# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) -#endif - -#if defined(JSON_HEDLEY_FLAGS) - #undef JSON_HEDLEY_FLAGS -#endif -#if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum) && (!defined(__cplusplus) || JSON_HEDLEY_HAS_WARNING("-Wbitfield-enum-conversion")) - #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__)) -#else - #define JSON_HEDLEY_FLAGS -#endif - -#if defined(JSON_HEDLEY_FLAGS_CAST) - #undef JSON_HEDLEY_FLAGS_CAST -#endif -#if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0) -# define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - _Pragma("warning(disable:188)") \ - ((T) (expr)); \ - JSON_HEDLEY_DIAGNOSTIC_POP \ - })) -#else -# define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr) -#endif - -#if defined(JSON_HEDLEY_EMPTY_BASES) - #undef JSON_HEDLEY_EMPTY_BASES -#endif -#if \ - (JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases) -#else - #define JSON_HEDLEY_EMPTY_BASES -#endif - -/* Remaining macros are deprecated. */ - -#if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK) - #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK -#endif -#if defined(__clang__) - #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0) -#else - #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE) - #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE -#endif -#define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) - -#if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE) - #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE -#endif -#define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) - -#if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN) - #undef JSON_HEDLEY_CLANG_HAS_BUILTIN -#endif -#define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin) - -#if defined(JSON_HEDLEY_CLANG_HAS_FEATURE) - #undef JSON_HEDLEY_CLANG_HAS_FEATURE -#endif -#define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature) - -#if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION) - #undef JSON_HEDLEY_CLANG_HAS_EXTENSION -#endif -#define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension) - -#if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE) - #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE -#endif -#define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) - -#if defined(JSON_HEDLEY_CLANG_HAS_WARNING) - #undef JSON_HEDLEY_CLANG_HAS_WARNING -#endif -#define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning) - -#endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */ - -// #include - - -#include - -// #include - - -namespace nlohmann -{ -namespace detail -{ -template struct make_void -{ - using type = void; -}; -template using void_t = typename make_void::type; -} // namespace detail -} // namespace nlohmann - - -// https://en.cppreference.com/w/cpp/experimental/is_detected -namespace nlohmann -{ -namespace detail -{ -struct nonesuch -{ - nonesuch() = delete; - ~nonesuch() = delete; - nonesuch(nonesuch const&) = delete; - nonesuch(nonesuch const&&) = delete; - void operator=(nonesuch const&) = delete; - void operator=(nonesuch&&) = delete; -}; - -template class Op, - class... Args> -struct detector -{ - using value_t = std::false_type; - using type = Default; -}; - -template class Op, class... Args> -struct detector>, Op, Args...> -{ - using value_t = std::true_type; - using type = Op; -}; - -template class Op, class... Args> -using is_detected = typename detector::value_t; - -template class Op, class... Args> -struct is_detected_lazy : is_detected { }; - -template class Op, class... Args> -using detected_t = typename detector::type; - -template class Op, class... Args> -using detected_or = detector; - -template class Op, class... Args> -using detected_or_t = typename detected_or::type; - -template class Op, class... Args> -using is_detected_exact = std::is_same>; - -template class Op, class... Args> -using is_detected_convertible = - std::is_convertible, To>; -} // namespace detail -} // namespace nlohmann - - -// This file contains all internal macro definitions -// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them - -// exclude unsupported compilers -#if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) - #if defined(__clang__) - #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 - #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" - #endif - #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) - #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 - #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" - #endif - #endif -#endif - -// C++ language standard detection -// if the user manually specified the used c++ version this is skipped -#if !defined(JSON_HAS_CPP_20) && !defined(JSON_HAS_CPP_17) && !defined(JSON_HAS_CPP_14) && !defined(JSON_HAS_CPP_11) - #if (defined(__cplusplus) && __cplusplus >= 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L) - #define JSON_HAS_CPP_20 - #define JSON_HAS_CPP_17 - #define JSON_HAS_CPP_14 - #elif (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 - #define JSON_HAS_CPP_17 - #define JSON_HAS_CPP_14 - #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) - #define JSON_HAS_CPP_14 - #endif - // the cpp 11 flag is always specified because it is the minimal required version - #define JSON_HAS_CPP_11 -#endif - -#if !defined(JSON_HAS_FILESYSTEM) && !defined(JSON_HAS_EXPERIMENTAL_FILESYSTEM) - #ifdef JSON_HAS_CPP_17 - #if defined(__cpp_lib_filesystem) - #define JSON_HAS_FILESYSTEM 1 - #elif defined(__cpp_lib_experimental_filesystem) - #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 - #elif !defined(__has_include) - #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 - #elif __has_include() - #define JSON_HAS_FILESYSTEM 1 - #elif __has_include() - #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 - #endif - - // std::filesystem does not work on MinGW GCC 8: https://sourceforge.net/p/mingw-w64/bugs/737/ - #if defined(__MINGW32__) && defined(__GNUC__) && __GNUC__ == 8 - #undef JSON_HAS_FILESYSTEM - #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM - #endif - - // no filesystem support before GCC 8: https://en.cppreference.com/w/cpp/compiler_support - #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 8 - #undef JSON_HAS_FILESYSTEM - #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM - #endif - - // no filesystem support before Clang 7: https://en.cppreference.com/w/cpp/compiler_support - #if defined(__clang_major__) && __clang_major__ < 7 - #undef JSON_HAS_FILESYSTEM - #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM - #endif - - // no filesystem support before MSVC 19.14: https://en.cppreference.com/w/cpp/compiler_support - #if defined(_MSC_VER) && _MSC_VER < 1940 - #undef JSON_HAS_FILESYSTEM - #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM - #endif - - // no filesystem support before iOS 13 - #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED < 130000 - #undef JSON_HAS_FILESYSTEM - #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM - #endif - - // no filesystem support before macOS Catalina - #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500 - #undef JSON_HAS_FILESYSTEM - #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM - #endif - #endif -#endif - -#ifndef JSON_HAS_EXPERIMENTAL_FILESYSTEM - #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 0 -#endif - -#ifndef JSON_HAS_FILESYSTEM - #define JSON_HAS_FILESYSTEM 0 -#endif - -// disable documentation warnings on clang -#if defined(__clang__) - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wdocumentation" - #pragma clang diagnostic ignored "-Wdocumentation-unknown-command" -#endif - -// allow disabling exceptions -#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) - #define JSON_THROW(exception) throw exception - #define JSON_TRY try - #define JSON_CATCH(exception) catch(exception) - #define JSON_INTERNAL_CATCH(exception) catch(exception) -#else - #include - #define JSON_THROW(exception) std::abort() - #define JSON_TRY if(true) - #define JSON_CATCH(exception) if(false) - #define JSON_INTERNAL_CATCH(exception) if(false) -#endif - -// override exception macros -#if defined(JSON_THROW_USER) - #undef JSON_THROW - #define JSON_THROW JSON_THROW_USER -#endif -#if defined(JSON_TRY_USER) - #undef JSON_TRY - #define JSON_TRY JSON_TRY_USER -#endif -#if defined(JSON_CATCH_USER) - #undef JSON_CATCH - #define JSON_CATCH JSON_CATCH_USER - #undef JSON_INTERNAL_CATCH - #define JSON_INTERNAL_CATCH JSON_CATCH_USER -#endif -#if defined(JSON_INTERNAL_CATCH_USER) - #undef JSON_INTERNAL_CATCH - #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER -#endif - -// allow overriding assert -#if !defined(JSON_ASSERT) - #include // assert - #define JSON_ASSERT(x) assert(x) -#endif - -// allow to access some private functions (needed by the test suite) -#if defined(JSON_TESTS_PRIVATE) - #define JSON_PRIVATE_UNLESS_TESTED public -#else - #define JSON_PRIVATE_UNLESS_TESTED private -#endif - -/*! -@brief macro to briefly define a mapping between an enum and JSON -@def NLOHMANN_JSON_SERIALIZE_ENUM -@since version 3.4.0 -*/ -#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ - template \ - inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ - { \ - static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ - static const std::pair m[] = __VA_ARGS__; \ - auto it = std::find_if(std::begin(m), std::end(m), \ - [e](const std::pair& ej_pair) -> bool \ - { \ - return ej_pair.first == e; \ - }); \ - j = ((it != std::end(m)) ? it : std::begin(m))->second; \ - } \ - template \ - inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ - { \ - static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ - static const std::pair m[] = __VA_ARGS__; \ - auto it = std::find_if(std::begin(m), std::end(m), \ - [&j](const std::pair& ej_pair) -> bool \ - { \ - return ej_pair.second == j; \ - }); \ - e = ((it != std::end(m)) ? it : std::begin(m))->first; \ - } - -// Ugly macros to avoid uglier copy-paste when specializing basic_json. They -// may be removed in the future once the class is split. - -#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ - template class ObjectType, \ - template class ArrayType, \ - class StringType, class BooleanType, class NumberIntegerType, \ - class NumberUnsignedType, class NumberFloatType, \ - template class AllocatorType, \ - template class JSONSerializer, \ - class BinaryType> - -#define NLOHMANN_BASIC_JSON_TPL \ - basic_json - -// Macros to simplify conversion from/to types - -#define NLOHMANN_JSON_EXPAND( x ) x -#define NLOHMANN_JSON_GET_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, NAME,...) NAME -#define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \ - NLOHMANN_JSON_PASTE64, \ - NLOHMANN_JSON_PASTE63, \ - NLOHMANN_JSON_PASTE62, \ - NLOHMANN_JSON_PASTE61, \ - NLOHMANN_JSON_PASTE60, \ - NLOHMANN_JSON_PASTE59, \ - NLOHMANN_JSON_PASTE58, \ - NLOHMANN_JSON_PASTE57, \ - NLOHMANN_JSON_PASTE56, \ - NLOHMANN_JSON_PASTE55, \ - NLOHMANN_JSON_PASTE54, \ - NLOHMANN_JSON_PASTE53, \ - NLOHMANN_JSON_PASTE52, \ - NLOHMANN_JSON_PASTE51, \ - NLOHMANN_JSON_PASTE50, \ - NLOHMANN_JSON_PASTE49, \ - NLOHMANN_JSON_PASTE48, \ - NLOHMANN_JSON_PASTE47, \ - NLOHMANN_JSON_PASTE46, \ - NLOHMANN_JSON_PASTE45, \ - NLOHMANN_JSON_PASTE44, \ - NLOHMANN_JSON_PASTE43, \ - NLOHMANN_JSON_PASTE42, \ - NLOHMANN_JSON_PASTE41, \ - NLOHMANN_JSON_PASTE40, \ - NLOHMANN_JSON_PASTE39, \ - NLOHMANN_JSON_PASTE38, \ - NLOHMANN_JSON_PASTE37, \ - NLOHMANN_JSON_PASTE36, \ - NLOHMANN_JSON_PASTE35, \ - NLOHMANN_JSON_PASTE34, \ - NLOHMANN_JSON_PASTE33, \ - NLOHMANN_JSON_PASTE32, \ - NLOHMANN_JSON_PASTE31, \ - NLOHMANN_JSON_PASTE30, \ - NLOHMANN_JSON_PASTE29, \ - NLOHMANN_JSON_PASTE28, \ - NLOHMANN_JSON_PASTE27, \ - NLOHMANN_JSON_PASTE26, \ - NLOHMANN_JSON_PASTE25, \ - NLOHMANN_JSON_PASTE24, \ - NLOHMANN_JSON_PASTE23, \ - NLOHMANN_JSON_PASTE22, \ - NLOHMANN_JSON_PASTE21, \ - NLOHMANN_JSON_PASTE20, \ - NLOHMANN_JSON_PASTE19, \ - NLOHMANN_JSON_PASTE18, \ - NLOHMANN_JSON_PASTE17, \ - NLOHMANN_JSON_PASTE16, \ - NLOHMANN_JSON_PASTE15, \ - NLOHMANN_JSON_PASTE14, \ - NLOHMANN_JSON_PASTE13, \ - NLOHMANN_JSON_PASTE12, \ - NLOHMANN_JSON_PASTE11, \ - NLOHMANN_JSON_PASTE10, \ - NLOHMANN_JSON_PASTE9, \ - NLOHMANN_JSON_PASTE8, \ - NLOHMANN_JSON_PASTE7, \ - NLOHMANN_JSON_PASTE6, \ - NLOHMANN_JSON_PASTE5, \ - NLOHMANN_JSON_PASTE4, \ - NLOHMANN_JSON_PASTE3, \ - NLOHMANN_JSON_PASTE2, \ - NLOHMANN_JSON_PASTE1)(__VA_ARGS__)) -#define NLOHMANN_JSON_PASTE2(func, v1) func(v1) -#define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2) -#define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3) -#define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4) -#define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5) -#define NLOHMANN_JSON_PASTE7(func, v1, v2, v3, v4, v5, v6) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE6(func, v2, v3, v4, v5, v6) -#define NLOHMANN_JSON_PASTE8(func, v1, v2, v3, v4, v5, v6, v7) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE7(func, v2, v3, v4, v5, v6, v7) -#define NLOHMANN_JSON_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8) -#define NLOHMANN_JSON_PASTE10(func, v1, v2, v3, v4, v5, v6, v7, v8, v9) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE9(func, v2, v3, v4, v5, v6, v7, v8, v9) -#define NLOHMANN_JSON_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE10(func, v2, v3, v4, v5, v6, v7, v8, v9, v10) -#define NLOHMANN_JSON_PASTE12(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE11(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) -#define NLOHMANN_JSON_PASTE13(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE12(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) -#define NLOHMANN_JSON_PASTE14(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE13(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) -#define NLOHMANN_JSON_PASTE15(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE14(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) -#define NLOHMANN_JSON_PASTE16(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE15(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) -#define NLOHMANN_JSON_PASTE17(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE16(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) -#define NLOHMANN_JSON_PASTE18(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE17(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) -#define NLOHMANN_JSON_PASTE19(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE18(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) -#define NLOHMANN_JSON_PASTE20(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE19(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) -#define NLOHMANN_JSON_PASTE21(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE20(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) -#define NLOHMANN_JSON_PASTE22(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE21(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) -#define NLOHMANN_JSON_PASTE23(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE22(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) -#define NLOHMANN_JSON_PASTE24(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE23(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) -#define NLOHMANN_JSON_PASTE25(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE24(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) -#define NLOHMANN_JSON_PASTE26(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE25(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) -#define NLOHMANN_JSON_PASTE27(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE26(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) -#define NLOHMANN_JSON_PASTE28(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE27(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) -#define NLOHMANN_JSON_PASTE29(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE28(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) -#define NLOHMANN_JSON_PASTE30(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE29(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) -#define NLOHMANN_JSON_PASTE31(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE30(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) -#define NLOHMANN_JSON_PASTE32(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE31(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) -#define NLOHMANN_JSON_PASTE33(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE32(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) -#define NLOHMANN_JSON_PASTE34(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE33(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) -#define NLOHMANN_JSON_PASTE35(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE34(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) -#define NLOHMANN_JSON_PASTE36(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE35(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) -#define NLOHMANN_JSON_PASTE37(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE36(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) -#define NLOHMANN_JSON_PASTE38(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE37(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) -#define NLOHMANN_JSON_PASTE39(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE38(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) -#define NLOHMANN_JSON_PASTE40(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE39(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) -#define NLOHMANN_JSON_PASTE41(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE40(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) -#define NLOHMANN_JSON_PASTE42(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE41(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) -#define NLOHMANN_JSON_PASTE43(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE42(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) -#define NLOHMANN_JSON_PASTE44(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE43(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) -#define NLOHMANN_JSON_PASTE45(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE44(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) -#define NLOHMANN_JSON_PASTE46(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE45(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) -#define NLOHMANN_JSON_PASTE47(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE46(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) -#define NLOHMANN_JSON_PASTE48(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE47(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) -#define NLOHMANN_JSON_PASTE49(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE48(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) -#define NLOHMANN_JSON_PASTE50(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE49(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) -#define NLOHMANN_JSON_PASTE51(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE50(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) -#define NLOHMANN_JSON_PASTE52(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE51(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) -#define NLOHMANN_JSON_PASTE53(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE52(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) -#define NLOHMANN_JSON_PASTE54(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE53(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) -#define NLOHMANN_JSON_PASTE55(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE54(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) -#define NLOHMANN_JSON_PASTE56(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE55(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) -#define NLOHMANN_JSON_PASTE57(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE56(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) -#define NLOHMANN_JSON_PASTE58(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE57(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) -#define NLOHMANN_JSON_PASTE59(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE58(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) -#define NLOHMANN_JSON_PASTE60(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE59(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) -#define NLOHMANN_JSON_PASTE61(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE60(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) -#define NLOHMANN_JSON_PASTE62(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE61(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) -#define NLOHMANN_JSON_PASTE63(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE62(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) -#define NLOHMANN_JSON_PASTE64(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE63(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) - -#define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1; -#define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1); - -/*! -@brief macro -@def NLOHMANN_DEFINE_TYPE_INTRUSIVE -@since version 3.9.0 -*/ -#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \ - friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ - friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } - -/*! -@brief macro -@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE -@since version 3.9.0 -*/ -#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \ - inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ - inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } - - -// inspired from https://stackoverflow.com/a/26745591 -// allows to call any std function as if (e.g. with begin): -// using std::begin; begin(x); -// -// it allows using the detected idiom to retrieve the return type -// of such an expression -#define NLOHMANN_CAN_CALL_STD_FUNC_IMPL(std_name) \ - namespace detail { \ - using std::std_name; \ - \ - template \ - using result_of_##std_name = decltype(std_name(std::declval()...)); \ - } \ - \ - namespace detail2 { \ - struct std_name##_tag \ - { \ - }; \ - \ - template \ - std_name##_tag std_name(T&&...); \ - \ - template \ - using result_of_##std_name = decltype(std_name(std::declval()...)); \ - \ - template \ - struct would_call_std_##std_name \ - { \ - static constexpr auto const value = ::nlohmann::detail:: \ - is_detected_exact::value; \ - }; \ - } /* namespace detail2 */ \ - \ - template \ - struct would_call_std_##std_name : detail2::would_call_std_##std_name \ - { \ - } - -#ifndef JSON_USE_IMPLICIT_CONVERSIONS - #define JSON_USE_IMPLICIT_CONVERSIONS 1 -#endif - -#if JSON_USE_IMPLICIT_CONVERSIONS - #define JSON_EXPLICIT -#else - #define JSON_EXPLICIT explicit -#endif - -#ifndef JSON_DIAGNOSTICS - #define JSON_DIAGNOSTICS 0 -#endif - - -namespace nlohmann -{ -namespace detail -{ - -/*! -@brief replace all occurrences of a substring by another string - -@param[in,out] s the string to manipulate; changed so that all - occurrences of @a f are replaced with @a t -@param[in] f the substring to replace with @a t -@param[in] t the string to replace @a f - -@pre The search string @a f must not be empty. **This precondition is -enforced with an assertion.** - -@since version 2.0.0 -*/ -inline void replace_substring(std::string& s, const std::string& f, - const std::string& t) -{ - JSON_ASSERT(!f.empty()); - for (auto pos = s.find(f); // find first occurrence of f - pos != std::string::npos; // make sure f was found - s.replace(pos, f.size(), t), // replace with t, and - pos = s.find(f, pos + t.size())) // find next occurrence of f - {} -} - -/*! - * @brief string escaping as described in RFC 6901 (Sect. 4) - * @param[in] s string to escape - * @return escaped string - * - * Note the order of escaping "~" to "~0" and "/" to "~1" is important. - */ -inline std::string escape(std::string s) -{ - replace_substring(s, "~", "~0"); - replace_substring(s, "/", "~1"); - return s; -} - -/*! - * @brief string unescaping as described in RFC 6901 (Sect. 4) - * @param[in] s string to unescape - * @return unescaped string - * - * Note the order of escaping "~1" to "/" and "~0" to "~" is important. - */ -static void unescape(std::string& s) -{ - replace_substring(s, "~1", "/"); - replace_substring(s, "~0", "~"); -} - -} // namespace detail -} // namespace nlohmann - -// #include - - -#include // size_t - -namespace nlohmann -{ -namespace detail -{ -/// struct to capture the start position of the current token -struct position_t -{ - /// the total number of characters read - std::size_t chars_read_total = 0; - /// the number of characters read in the current line - std::size_t chars_read_current_line = 0; - /// the number of lines read - std::size_t lines_read = 0; - - /// conversion to size_t to preserve SAX interface - constexpr operator size_t() const - { - return chars_read_total; - } -}; - -} // namespace detail -} // namespace nlohmann - -// #include - - -namespace nlohmann -{ -namespace detail -{ -//////////////// -// exceptions // -//////////////// - -/// @brief general exception of the @ref basic_json class -/// @sa https://json.nlohmann.me/api/basic_json/exception/ -class exception : public std::exception -{ - public: - /// returns the explanatory string - const char* what() const noexcept override - { - return m.what(); - } - - /// the id of the exception - const int id; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) - - protected: - JSON_HEDLEY_NON_NULL(3) - exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} // NOLINT(bugprone-throw-keyword-missing) - - static std::string name(const std::string& ename, int id_) - { - return "[json.exception." + ename + "." + std::to_string(id_) + "] "; - } - - template - static std::string diagnostics(const BasicJsonType& leaf_element) - { -#if JSON_DIAGNOSTICS - std::vector tokens; - for (const auto* current = &leaf_element; current->m_parent != nullptr; current = current->m_parent) - { - switch (current->m_parent->type()) - { - case value_t::array: - { - for (std::size_t i = 0; i < current->m_parent->m_value.array->size(); ++i) - { - if (¤t->m_parent->m_value.array->operator[](i) == current) - { - tokens.emplace_back(std::to_string(i)); - break; - } - } - break; - } - - case value_t::object: - { - for (const auto& element : *current->m_parent->m_value.object) - { - if (&element.second == current) - { - tokens.emplace_back(element.first.c_str()); - break; - } - } - break; - } - - case value_t::null: // LCOV_EXCL_LINE - case value_t::string: // LCOV_EXCL_LINE - case value_t::boolean: // LCOV_EXCL_LINE - case value_t::number_integer: // LCOV_EXCL_LINE - case value_t::number_unsigned: // LCOV_EXCL_LINE - case value_t::number_float: // LCOV_EXCL_LINE - case value_t::binary: // LCOV_EXCL_LINE - case value_t::discarded: // LCOV_EXCL_LINE - default: // LCOV_EXCL_LINE - break; // LCOV_EXCL_LINE - } - } - - if (tokens.empty()) - { - return ""; - } - - return "(" + std::accumulate(tokens.rbegin(), tokens.rend(), std::string{}, - [](const std::string & a, const std::string & b) - { - return a + "/" + detail::escape(b); - }) + ") "; -#else - static_cast(leaf_element); - return ""; -#endif - } - - private: - /// an exception object as storage for error messages - std::runtime_error m; -}; - -/// @brief exception indicating a parse error -/// @sa https://json.nlohmann.me/api/basic_json/parse_error/ -class parse_error : public exception -{ - public: - /*! - @brief create a parse error exception - @param[in] id_ the id of the exception - @param[in] pos the position where the error occurred (or with - chars_read_total=0 if the position cannot be - determined) - @param[in] what_arg the explanatory string - @return parse_error object - */ - template - static parse_error create(int id_, const position_t& pos, const std::string& what_arg, const BasicJsonType& context) - { - std::string w = exception::name("parse_error", id_) + "parse error" + - position_string(pos) + ": " + exception::diagnostics(context) + what_arg; - return {id_, pos.chars_read_total, w.c_str()}; - } - - template - static parse_error create(int id_, std::size_t byte_, const std::string& what_arg, const BasicJsonType& context) - { - std::string w = exception::name("parse_error", id_) + "parse error" + - (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") + - ": " + exception::diagnostics(context) + what_arg; - return {id_, byte_, w.c_str()}; - } - - /*! - @brief byte index of the parse error - - The byte index of the last read character in the input file. - - @note For an input with n bytes, 1 is the index of the first character and - n+1 is the index of the terminating null byte or the end of file. - This also holds true when reading a byte vector (CBOR or MessagePack). - */ - const std::size_t byte; - - private: - parse_error(int id_, std::size_t byte_, const char* what_arg) - : exception(id_, what_arg), byte(byte_) {} - - static std::string position_string(const position_t& pos) - { - return " at line " + std::to_string(pos.lines_read + 1) + - ", column " + std::to_string(pos.chars_read_current_line); - } -}; - -/// @brief exception indicating errors with iterators -/// @sa https://json.nlohmann.me/api/basic_json/invalid_iterator/ -class invalid_iterator : public exception -{ - public: - template - static invalid_iterator create(int id_, const std::string& what_arg, const BasicJsonType& context) - { - std::string w = exception::name("invalid_iterator", id_) + exception::diagnostics(context) + what_arg; - return {id_, w.c_str()}; - } - - private: - JSON_HEDLEY_NON_NULL(3) - invalid_iterator(int id_, const char* what_arg) - : exception(id_, what_arg) {} -}; - -/// @brief exception indicating executing a member function with a wrong type -/// @sa https://json.nlohmann.me/api/basic_json/type_error/ -class type_error : public exception -{ - public: - template - static type_error create(int id_, const std::string& what_arg, const BasicJsonType& context) - { - std::string w = exception::name("type_error", id_) + exception::diagnostics(context) + what_arg; - return {id_, w.c_str()}; - } - - private: - JSON_HEDLEY_NON_NULL(3) - type_error(int id_, const char* what_arg) : exception(id_, what_arg) {} -}; - -/// @brief exception indicating access out of the defined range -/// @sa https://json.nlohmann.me/api/basic_json/out_of_range/ -class out_of_range : public exception -{ - public: - template - static out_of_range create(int id_, const std::string& what_arg, const BasicJsonType& context) - { - std::string w = exception::name("out_of_range", id_) + exception::diagnostics(context) + what_arg; - return {id_, w.c_str()}; - } - - private: - JSON_HEDLEY_NON_NULL(3) - out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {} -}; - -/// @brief exception indicating other library errors -/// @sa https://json.nlohmann.me/api/basic_json/other_error/ -class other_error : public exception -{ - public: - template - static other_error create(int id_, const std::string& what_arg, const BasicJsonType& context) - { - std::string w = exception::name("other_error", id_) + exception::diagnostics(context) + what_arg; - return {id_, w.c_str()}; - } - - private: - JSON_HEDLEY_NON_NULL(3) - other_error(int id_, const char* what_arg) : exception(id_, what_arg) {} -}; - -} // namespace detail -} // namespace nlohmann - -// #include - -// #include - - -#include // size_t -#include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type -#include // index_sequence, make_index_sequence, index_sequence_for - -// #include - - -namespace nlohmann -{ -namespace detail -{ - -template -using uncvref_t = typename std::remove_cv::type>::type; - -#ifdef JSON_HAS_CPP_14 - -// the following utilities are natively available in C++14 -using std::enable_if_t; -using std::index_sequence; -using std::make_index_sequence; -using std::index_sequence_for; - -#else - -// alias templates to reduce boilerplate -template -using enable_if_t = typename std::enable_if::type; - -// The following code is taken from https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h -// which is part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0. - -//// START OF CODE FROM GOOGLE ABSEIL - -// integer_sequence -// -// Class template representing a compile-time integer sequence. An instantiation -// of `integer_sequence` has a sequence of integers encoded in its -// type through its template arguments (which is a common need when -// working with C++11 variadic templates). `absl::integer_sequence` is designed -// to be a drop-in replacement for C++14's `std::integer_sequence`. -// -// Example: -// -// template< class T, T... Ints > -// void user_function(integer_sequence); -// -// int main() -// { -// // user_function's `T` will be deduced to `int` and `Ints...` -// // will be deduced to `0, 1, 2, 3, 4`. -// user_function(make_integer_sequence()); -// } -template -struct integer_sequence -{ - using value_type = T; - static constexpr std::size_t size() noexcept - { - return sizeof...(Ints); - } -}; - -// index_sequence -// -// A helper template for an `integer_sequence` of `size_t`, -// `absl::index_sequence` is designed to be a drop-in replacement for C++14's -// `std::index_sequence`. -template -using index_sequence = integer_sequence; - -namespace utility_internal -{ - -template -struct Extend; - -// Note that SeqSize == sizeof...(Ints). It's passed explicitly for efficiency. -template -struct Extend, SeqSize, 0> -{ - using type = integer_sequence < T, Ints..., (Ints + SeqSize)... >; -}; - -template -struct Extend, SeqSize, 1> -{ - using type = integer_sequence < T, Ints..., (Ints + SeqSize)..., 2 * SeqSize >; -}; - -// Recursion helper for 'make_integer_sequence'. -// 'Gen::type' is an alias for 'integer_sequence'. -template -struct Gen -{ - using type = - typename Extend < typename Gen < T, N / 2 >::type, N / 2, N % 2 >::type; -}; - -template -struct Gen -{ - using type = integer_sequence; -}; - -} // namespace utility_internal - -// Compile-time sequences of integers - -// make_integer_sequence -// -// This template alias is equivalent to -// `integer_sequence`, and is designed to be a drop-in -// replacement for C++14's `std::make_integer_sequence`. -template -using make_integer_sequence = typename utility_internal::Gen::type; - -// make_index_sequence -// -// This template alias is equivalent to `index_sequence<0, 1, ..., N-1>`, -// and is designed to be a drop-in replacement for C++14's -// `std::make_index_sequence`. -template -using make_index_sequence = make_integer_sequence; - -// index_sequence_for -// -// Converts a typename pack into an index sequence of the same length, and -// is designed to be a drop-in replacement for C++14's -// `std::index_sequence_for()` -template -using index_sequence_for = make_index_sequence; - -//// END OF CODE FROM GOOGLE ABSEIL - -#endif - -// dispatch utility (taken from ranges-v3) -template struct priority_tag : priority_tag < N - 1 > {}; -template<> struct priority_tag<0> {}; - -// taken from ranges-v3 -template -struct static_const -{ - static constexpr T value{}; -}; - -template -constexpr T static_const::value; // NOLINT(readability-redundant-declaration) - -} // namespace detail -} // namespace nlohmann - -// #include - - -namespace nlohmann -{ -namespace detail -{ -// dispatching helper struct -template struct identity_tag {}; -} // namespace detail -} // namespace nlohmann - -// #include - - -#include // numeric_limits -#include // false_type, is_constructible, is_integral, is_same, true_type -#include // declval -#include // tuple - -// #include - - -// #include - - -#include // random_access_iterator_tag - -// #include - -// #include - - -namespace nlohmann -{ -namespace detail -{ -template -struct iterator_types {}; - -template -struct iterator_types < - It, - void_t> -{ - using difference_type = typename It::difference_type; - using value_type = typename It::value_type; - using pointer = typename It::pointer; - using reference = typename It::reference; - using iterator_category = typename It::iterator_category; -}; - -// This is required as some compilers implement std::iterator_traits in a way that -// doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. -template -struct iterator_traits -{ -}; - -template -struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> - : iterator_types -{ -}; - -template -struct iterator_traits::value>> -{ - using iterator_category = std::random_access_iterator_tag; - using value_type = T; - using difference_type = ptrdiff_t; - using pointer = T*; - using reference = T&; -}; -} // namespace detail -} // namespace nlohmann - -// #include - - -// #include - - -namespace nlohmann -{ -NLOHMANN_CAN_CALL_STD_FUNC_IMPL(begin); -} // namespace nlohmann - -// #include - - -// #include - - -namespace nlohmann -{ -NLOHMANN_CAN_CALL_STD_FUNC_IMPL(end); -} // namespace nlohmann - -// #include - -// #include - -// #include -#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ -#define INCLUDE_NLOHMANN_JSON_FWD_HPP_ - -#include // int64_t, uint64_t -#include // map -#include // allocator -#include // string -#include // vector - -/*! -@brief namespace for Niels Lohmann -@see https://github.com/nlohmann -@since version 1.0.0 -*/ -namespace nlohmann -{ -/*! -@brief default JSONSerializer template argument - -This serializer ignores the template arguments and uses ADL -([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) -for serialization. -*/ -template -struct adl_serializer; - -/// a class to store JSON values -/// @sa https://json.nlohmann.me/api/basic_json/ -template class ObjectType = - std::map, - template class ArrayType = std::vector, - class StringType = std::string, class BooleanType = bool, - class NumberIntegerType = std::int64_t, - class NumberUnsignedType = std::uint64_t, - class NumberFloatType = double, - template class AllocatorType = std::allocator, - template class JSONSerializer = - adl_serializer, - class BinaryType = std::vector> -class basic_json; - -/// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document -/// @sa https://json.nlohmann.me/api/json_pointer/ -template -class json_pointer; - -/*! -@brief default specialization -@sa https://json.nlohmann.me/api/json/ -*/ -using json = basic_json<>; - -/// @brief a minimal map-like container that preserves insertion order -/// @sa https://json.nlohmann.me/api/ordered_map/ -template -struct ordered_map; - -/// @brief specialization that maintains the insertion order of object keys -/// @sa https://json.nlohmann.me/api/ordered_json/ -using ordered_json = basic_json; - -} // namespace nlohmann - -#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ - - -namespace nlohmann -{ -/*! -@brief detail namespace with internal helper functions - -This namespace collects functions that should not be exposed, -implementations of some @ref basic_json methods, and meta-programming helpers. - -@since version 2.1.0 -*/ -namespace detail -{ -///////////// -// helpers // -///////////// - -// Note to maintainers: -// -// Every trait in this file expects a non CV-qualified type. -// The only exceptions are in the 'aliases for detected' section -// (i.e. those of the form: decltype(T::member_function(std::declval()))) -// -// In this case, T has to be properly CV-qualified to constraint the function arguments -// (e.g. to_json(BasicJsonType&, const T&)) - -template struct is_basic_json : std::false_type {}; - -NLOHMANN_BASIC_JSON_TPL_DECLARATION -struct is_basic_json : std::true_type {}; - -////////////////////// -// json_ref helpers // -////////////////////// - -template -class json_ref; - -template -struct is_json_ref : std::false_type {}; - -template -struct is_json_ref> : std::true_type {}; - -////////////////////////// -// aliases for detected // -////////////////////////// - -template -using mapped_type_t = typename T::mapped_type; - -template -using key_type_t = typename T::key_type; - -template -using value_type_t = typename T::value_type; - -template -using difference_type_t = typename T::difference_type; - -template -using pointer_t = typename T::pointer; - -template -using reference_t = typename T::reference; - -template -using iterator_category_t = typename T::iterator_category; - -template -using to_json_function = decltype(T::to_json(std::declval()...)); - -template -using from_json_function = decltype(T::from_json(std::declval()...)); - -template -using get_template_function = decltype(std::declval().template get()); - -// trait checking if JSONSerializer::from_json(json const&, udt&) exists -template -struct has_from_json : std::false_type {}; - -// trait checking if j.get is valid -// use this trait instead of std::is_constructible or std::is_convertible, -// both rely on, or make use of implicit conversions, and thus fail when T -// has several constructors/operator= (see https://github.com/nlohmann/json/issues/958) -template -struct is_getable -{ - static constexpr bool value = is_detected::value; -}; - -template -struct has_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> -{ - using serializer = typename BasicJsonType::template json_serializer; - - static constexpr bool value = - is_detected_exact::value; -}; - -// This trait checks if JSONSerializer::from_json(json const&) exists -// this overload is used for non-default-constructible user-defined-types -template -struct has_non_default_from_json : std::false_type {}; - -template -struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> -{ - using serializer = typename BasicJsonType::template json_serializer; - - static constexpr bool value = - is_detected_exact::value; -}; - -// This trait checks if BasicJsonType::json_serializer::to_json exists -// Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion. -template -struct has_to_json : std::false_type {}; - -template -struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> -{ - using serializer = typename BasicJsonType::template json_serializer; - - static constexpr bool value = - is_detected_exact::value; -}; - - -/////////////////// -// is_ functions // -/////////////////// - -// https://en.cppreference.com/w/cpp/types/conjunction -template struct conjunction : std::true_type { }; -template struct conjunction : B1 { }; -template -struct conjunction -: std::conditional, B1>::type {}; - -// https://en.cppreference.com/w/cpp/types/negation -template struct negation : std::integral_constant < bool, !B::value > { }; - -// Reimplementation of is_constructible and is_default_constructible, due to them being broken for -// std::pair and std::tuple until LWG 2367 fix (see https://cplusplus.github.io/LWG/lwg-defects.html#2367). -// This causes compile errors in e.g. clang 3.5 or gcc 4.9. -template -struct is_default_constructible : std::is_default_constructible {}; - -template -struct is_default_constructible> - : conjunction, is_default_constructible> {}; - -template -struct is_default_constructible> - : conjunction, is_default_constructible> {}; - -template -struct is_default_constructible> - : conjunction...> {}; - -template -struct is_default_constructible> - : conjunction...> {}; - - -template -struct is_constructible : std::is_constructible {}; - -template -struct is_constructible> : is_default_constructible> {}; - -template -struct is_constructible> : is_default_constructible> {}; - -template -struct is_constructible> : is_default_constructible> {}; - -template -struct is_constructible> : is_default_constructible> {}; - - -template -struct is_iterator_traits : std::false_type {}; - -template -struct is_iterator_traits> -{ - private: - using traits = iterator_traits; - - public: - static constexpr auto value = - is_detected::value && - is_detected::value && - is_detected::value && - is_detected::value && - is_detected::value; -}; - -template -struct is_range -{ - private: - using t_ref = typename std::add_lvalue_reference::type; - - using iterator = detected_t; - using sentinel = detected_t; - - // to be 100% correct, it should use https://en.cppreference.com/w/cpp/iterator/input_or_output_iterator - // and https://en.cppreference.com/w/cpp/iterator/sentinel_for - // but reimplementing these would be too much work, as a lot of other concepts are used underneath - static constexpr auto is_iterator_begin = - is_iterator_traits>::value; - - public: - static constexpr bool value = !std::is_same::value && !std::is_same::value && is_iterator_begin; -}; - -template -using iterator_t = enable_if_t::value, result_of_begin())>>; - -template -using range_value_t = value_type_t>>; - -// The following implementation of is_complete_type is taken from -// https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/ -// and is written by Xiang Fan who agreed to using it in this library. - -template -struct is_complete_type : std::false_type {}; - -template -struct is_complete_type : std::true_type {}; - -template -struct is_compatible_object_type_impl : std::false_type {}; - -template -struct is_compatible_object_type_impl < - BasicJsonType, CompatibleObjectType, - enable_if_t < is_detected::value&& - is_detected::value >> -{ - using object_t = typename BasicJsonType::object_t; - - // macOS's is_constructible does not play well with nonesuch... - static constexpr bool value = - is_constructible::value && - is_constructible::value; -}; - -template -struct is_compatible_object_type - : is_compatible_object_type_impl {}; - -template -struct is_constructible_object_type_impl : std::false_type {}; - -template -struct is_constructible_object_type_impl < - BasicJsonType, ConstructibleObjectType, - enable_if_t < is_detected::value&& - is_detected::value >> -{ - using object_t = typename BasicJsonType::object_t; - - static constexpr bool value = - (is_default_constructible::value && - (std::is_move_assignable::value || - std::is_copy_assignable::value) && - (is_constructible::value && - std::is_same < - typename object_t::mapped_type, - typename ConstructibleObjectType::mapped_type >::value)) || - (has_from_json::value || - has_non_default_from_json < - BasicJsonType, - typename ConstructibleObjectType::mapped_type >::value); -}; - -template -struct is_constructible_object_type - : is_constructible_object_type_impl {}; - -template -struct is_compatible_string_type -{ - static constexpr auto value = - is_constructible::value; -}; - -template -struct is_constructible_string_type -{ - static constexpr auto value = - is_constructible::value; -}; - -template -struct is_compatible_array_type_impl : std::false_type {}; - -template -struct is_compatible_array_type_impl < - BasicJsonType, CompatibleArrayType, - enable_if_t < - is_detected::value&& - is_iterator_traits>>::value&& -// special case for types like std::filesystem::path whose iterator's value_type are themselves -// c.f. https://github.com/nlohmann/json/pull/3073 - !std::is_same>::value >> -{ - static constexpr bool value = - is_constructible>::value; -}; - -template -struct is_compatible_array_type - : is_compatible_array_type_impl {}; - -template -struct is_constructible_array_type_impl : std::false_type {}; - -template -struct is_constructible_array_type_impl < - BasicJsonType, ConstructibleArrayType, - enable_if_t::value >> - : std::true_type {}; - -template -struct is_constructible_array_type_impl < - BasicJsonType, ConstructibleArrayType, - enable_if_t < !std::is_same::value&& - !is_compatible_string_type::value&& - is_default_constructible::value&& -(std::is_move_assignable::value || - std::is_copy_assignable::value)&& -is_detected::value&& -is_iterator_traits>>::value&& -is_detected::value&& -// special case for types like std::filesystem::path whose iterator's value_type are themselves -// c.f. https://github.com/nlohmann/json/pull/3073 -!std::is_same>::value&& - is_complete_type < - detected_t>::value >> -{ - using value_type = range_value_t; - - static constexpr bool value = - std::is_same::value || - has_from_json::value || - has_non_default_from_json < - BasicJsonType, - value_type >::value; -}; - -template -struct is_constructible_array_type - : is_constructible_array_type_impl {}; - -template -struct is_compatible_integer_type_impl : std::false_type {}; - -template -struct is_compatible_integer_type_impl < - RealIntegerType, CompatibleNumberIntegerType, - enable_if_t < std::is_integral::value&& - std::is_integral::value&& - !std::is_same::value >> -{ - // is there an assert somewhere on overflows? - using RealLimits = std::numeric_limits; - using CompatibleLimits = std::numeric_limits; - - static constexpr auto value = - is_constructible::value && - CompatibleLimits::is_integer && - RealLimits::is_signed == CompatibleLimits::is_signed; -}; - -template -struct is_compatible_integer_type - : is_compatible_integer_type_impl {}; - -template -struct is_compatible_type_impl: std::false_type {}; - -template -struct is_compatible_type_impl < - BasicJsonType, CompatibleType, - enable_if_t::value >> -{ - static constexpr bool value = - has_to_json::value; -}; - -template -struct is_compatible_type - : is_compatible_type_impl {}; - -template -struct is_constructible_tuple : std::false_type {}; - -template -struct is_constructible_tuple> : conjunction...> {}; - -// a naive helper to check if a type is an ordered_map (exploits the fact that -// ordered_map inherits capacity() from std::vector) -template -struct is_ordered_map -{ - using one = char; - - struct two - { - char x[2]; // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) - }; - - template static one test( decltype(&C::capacity) ) ; - template static two test(...); - - enum { value = sizeof(test(nullptr)) == sizeof(char) }; // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) -}; - -// to avoid useless casts (see https://github.com/nlohmann/json/issues/2893#issuecomment-889152324) -template < typename T, typename U, enable_if_t < !std::is_same::value, int > = 0 > -T conditional_static_cast(U value) -{ - return static_cast(value); -} - -template::value, int> = 0> -T conditional_static_cast(U value) -{ - return value; -} - -} // namespace detail -} // namespace nlohmann - -// #include - - -#if JSON_HAS_EXPERIMENTAL_FILESYSTEM -#include -namespace nlohmann::detail -{ -namespace std_fs = std::experimental::filesystem; -} // namespace nlohmann::detail -#elif JSON_HAS_FILESYSTEM -#include -namespace nlohmann::detail -{ -namespace std_fs = std::filesystem; -} // namespace nlohmann::detail -#endif - -namespace nlohmann -{ -namespace detail -{ -template -void from_json(const BasicJsonType& j, typename std::nullptr_t& n) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_null())) - { - JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name()), j)); - } - n = nullptr; -} - -// overloads for basic_json template parameters -template < typename BasicJsonType, typename ArithmeticType, - enable_if_t < std::is_arithmetic::value&& - !std::is_same::value, - int > = 0 > -void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val) -{ - switch (static_cast(j)) - { - case value_t::number_unsigned: - { - val = static_cast(*j.template get_ptr()); - break; - } - case value_t::number_integer: - { - val = static_cast(*j.template get_ptr()); - break; - } - case value_t::number_float: - { - val = static_cast(*j.template get_ptr()); - break; - } - - case value_t::null: - case value_t::object: - case value_t::array: - case value_t::string: - case value_t::boolean: - case value_t::binary: - case value_t::discarded: - default: - JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j)); - } -} - -template -void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_boolean())) - { - JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name()), j)); - } - b = *j.template get_ptr(); -} - -template -void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_string())) - { - JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j)); - } - s = *j.template get_ptr(); -} - -template < - typename BasicJsonType, typename ConstructibleStringType, - enable_if_t < - is_constructible_string_type::value&& - !std::is_same::value, - int > = 0 > -void from_json(const BasicJsonType& j, ConstructibleStringType& s) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_string())) - { - JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j)); - } - - s = *j.template get_ptr(); -} - -template -void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val) -{ - get_arithmetic_value(j, val); -} - -template -void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val) -{ - get_arithmetic_value(j, val); -} - -template -void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val) -{ - get_arithmetic_value(j, val); -} - -template::value, int> = 0> -void from_json(const BasicJsonType& j, EnumType& e) -{ - typename std::underlying_type::type val; - get_arithmetic_value(j, val); - e = static_cast(val); -} - -// forward_list doesn't have an insert method -template::value, int> = 0> -void from_json(const BasicJsonType& j, std::forward_list& l) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); - } - l.clear(); - std::transform(j.rbegin(), j.rend(), - std::front_inserter(l), [](const BasicJsonType & i) - { - return i.template get(); - }); -} - -// valarray doesn't have an insert method -template::value, int> = 0> -void from_json(const BasicJsonType& j, std::valarray& l) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); - } - l.resize(j.size()); - std::transform(j.begin(), j.end(), std::begin(l), - [](const BasicJsonType & elem) - { - return elem.template get(); - }); -} - -template -auto from_json(const BasicJsonType& j, T (&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) --> decltype(j.template get(), void()) -{ - for (std::size_t i = 0; i < N; ++i) - { - arr[i] = j.at(i).template get(); - } -} - -template -void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/) -{ - arr = *j.template get_ptr(); -} - -template -auto from_json_array_impl(const BasicJsonType& j, std::array& arr, - priority_tag<2> /*unused*/) --> decltype(j.template get(), void()) -{ - for (std::size_t i = 0; i < N; ++i) - { - arr[i] = j.at(i).template get(); - } -} - -template::value, - int> = 0> -auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/) --> decltype( - arr.reserve(std::declval()), - j.template get(), - void()) -{ - using std::end; - - ConstructibleArrayType ret; - ret.reserve(j.size()); - std::transform(j.begin(), j.end(), - std::inserter(ret, end(ret)), [](const BasicJsonType & i) - { - // get() returns *this, this won't call a from_json - // method when value_type is BasicJsonType - return i.template get(); - }); - arr = std::move(ret); -} - -template::value, - int> = 0> -void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, - priority_tag<0> /*unused*/) -{ - using std::end; - - ConstructibleArrayType ret; - std::transform( - j.begin(), j.end(), std::inserter(ret, end(ret)), - [](const BasicJsonType & i) - { - // get() returns *this, this won't call a from_json - // method when value_type is BasicJsonType - return i.template get(); - }); - arr = std::move(ret); -} - -template < typename BasicJsonType, typename ConstructibleArrayType, - enable_if_t < - is_constructible_array_type::value&& - !is_constructible_object_type::value&& - !is_constructible_string_type::value&& - !std::is_same::value&& - !is_basic_json::value, - int > = 0 > -auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr) --> decltype(from_json_array_impl(j, arr, priority_tag<3> {}), -j.template get(), -void()) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); - } - - from_json_array_impl(j, arr, priority_tag<3> {}); -} - -template < typename BasicJsonType, typename T, std::size_t... Idx > -std::array from_json_inplace_array_impl(BasicJsonType&& j, - identity_tag> /*unused*/, index_sequence /*unused*/) -{ - return { { std::forward(j).at(Idx).template get()... } }; -} - -template < typename BasicJsonType, typename T, std::size_t N > -auto from_json(BasicJsonType&& j, identity_tag> tag) --> decltype(from_json_inplace_array_impl(std::forward(j), tag, make_index_sequence {})) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); - } - - return from_json_inplace_array_impl(std::forward(j), tag, make_index_sequence {}); -} - -template -void from_json(const BasicJsonType& j, typename BasicJsonType::binary_t& bin) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_binary())) - { - JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(j.type_name()), j)); - } - - bin = *j.template get_ptr(); -} - -template::value, int> = 0> -void from_json(const BasicJsonType& j, ConstructibleObjectType& obj) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_object())) - { - JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name()), j)); - } - - ConstructibleObjectType ret; - const auto* inner_object = j.template get_ptr(); - using value_type = typename ConstructibleObjectType::value_type; - std::transform( - inner_object->begin(), inner_object->end(), - std::inserter(ret, ret.begin()), - [](typename BasicJsonType::object_t::value_type const & p) - { - return value_type(p.first, p.second.template get()); - }); - obj = std::move(ret); -} - -// overload for arithmetic types, not chosen for basic_json template arguments -// (BooleanType, etc..); note: Is it really necessary to provide explicit -// overloads for boolean_t etc. in case of a custom BooleanType which is not -// an arithmetic type? -template < typename BasicJsonType, typename ArithmeticType, - enable_if_t < - std::is_arithmetic::value&& - !std::is_same::value&& - !std::is_same::value&& - !std::is_same::value&& - !std::is_same::value, - int > = 0 > -void from_json(const BasicJsonType& j, ArithmeticType& val) -{ - switch (static_cast(j)) - { - case value_t::number_unsigned: - { - val = static_cast(*j.template get_ptr()); - break; - } - case value_t::number_integer: - { - val = static_cast(*j.template get_ptr()); - break; - } - case value_t::number_float: - { - val = static_cast(*j.template get_ptr()); - break; - } - case value_t::boolean: - { - val = static_cast(*j.template get_ptr()); - break; - } - - case value_t::null: - case value_t::object: - case value_t::array: - case value_t::string: - case value_t::binary: - case value_t::discarded: - default: - JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j)); - } -} - -template -std::tuple from_json_tuple_impl_base(BasicJsonType&& j, index_sequence /*unused*/) -{ - return std::make_tuple(std::forward(j).at(Idx).template get()...); -} - -template < typename BasicJsonType, class A1, class A2 > -std::pair from_json_tuple_impl(BasicJsonType&& j, identity_tag> /*unused*/, priority_tag<0> /*unused*/) -{ - return {std::forward(j).at(0).template get(), - std::forward(j).at(1).template get()}; -} - -template -void from_json_tuple_impl(BasicJsonType&& j, std::pair& p, priority_tag<1> /*unused*/) -{ - p = from_json_tuple_impl(std::forward(j), identity_tag> {}, priority_tag<0> {}); -} - -template -std::tuple from_json_tuple_impl(BasicJsonType&& j, identity_tag> /*unused*/, priority_tag<2> /*unused*/) -{ - return from_json_tuple_impl_base(std::forward(j), index_sequence_for {}); -} - -template -void from_json_tuple_impl(BasicJsonType&& j, std::tuple& t, priority_tag<3> /*unused*/) -{ - t = from_json_tuple_impl_base(std::forward(j), index_sequence_for {}); -} - -template -auto from_json(BasicJsonType&& j, TupleRelated&& t) --> decltype(from_json_tuple_impl(std::forward(j), std::forward(t), priority_tag<3> {})) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); - } - - return from_json_tuple_impl(std::forward(j), std::forward(t), priority_tag<3> {}); -} - -template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator, - typename = enable_if_t < !std::is_constructible < - typename BasicJsonType::string_t, Key >::value >> -void from_json(const BasicJsonType& j, std::map& m) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); - } - m.clear(); - for (const auto& p : j) - { - if (JSON_HEDLEY_UNLIKELY(!p.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j)); - } - m.emplace(p.at(0).template get(), p.at(1).template get()); - } -} - -template < typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator, - typename = enable_if_t < !std::is_constructible < - typename BasicJsonType::string_t, Key >::value >> -void from_json(const BasicJsonType& j, std::unordered_map& m) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); - } - m.clear(); - for (const auto& p : j) - { - if (JSON_HEDLEY_UNLIKELY(!p.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j)); - } - m.emplace(p.at(0).template get(), p.at(1).template get()); - } -} - -#if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM -template -void from_json(const BasicJsonType& j, std_fs::path& p) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_string())) - { - JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j)); - } - p = *j.template get_ptr(); -} -#endif - -struct from_json_fn -{ - template - auto operator()(const BasicJsonType& j, T&& val) const - noexcept(noexcept(from_json(j, std::forward(val)))) - -> decltype(from_json(j, std::forward(val))) - { - return from_json(j, std::forward(val)); - } -}; -} // namespace detail - -/// namespace to hold default `from_json` function -/// to see why this is required: -/// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html -namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces) -{ -constexpr const auto& from_json = detail::static_const::value; // NOLINT(misc-definitions-in-headers) -} // namespace -} // namespace nlohmann - -// #include - - -#include // copy -#include // begin, end -#include // string -#include // tuple, get -#include // is_same, is_constructible, is_floating_point, is_enum, underlying_type -#include // move, forward, declval, pair -#include // valarray -#include // vector - -// #include - -// #include - - -#include // size_t -#include // input_iterator_tag -#include // string, to_string -#include // tuple_size, get, tuple_element -#include // move - -// #include - -// #include - - -namespace nlohmann -{ -namespace detail -{ -template -void int_to_string( string_type& target, std::size_t value ) -{ - // For ADL - using std::to_string; - target = to_string(value); -} -template class iteration_proxy_value -{ - public: - using difference_type = std::ptrdiff_t; - using value_type = iteration_proxy_value; - using pointer = value_type * ; - using reference = value_type & ; - using iterator_category = std::input_iterator_tag; - using string_type = typename std::remove_cv< typename std::remove_reference().key() ) >::type >::type; - - private: - /// the iterator - IteratorType anchor; - /// an index for arrays (used to create key names) - std::size_t array_index = 0; - /// last stringified array index - mutable std::size_t array_index_last = 0; - /// a string representation of the array index - mutable string_type array_index_str = "0"; - /// an empty string (to return a reference for primitive values) - const string_type empty_str{}; - - public: - explicit iteration_proxy_value(IteratorType it) noexcept - : anchor(std::move(it)) - {} - - /// dereference operator (needed for range-based for) - iteration_proxy_value& operator*() - { - return *this; - } - - /// increment operator (needed for range-based for) - iteration_proxy_value& operator++() - { - ++anchor; - ++array_index; - - return *this; - } - - /// equality operator (needed for InputIterator) - bool operator==(const iteration_proxy_value& o) const - { - return anchor == o.anchor; - } - - /// inequality operator (needed for range-based for) - bool operator!=(const iteration_proxy_value& o) const - { - return anchor != o.anchor; - } - - /// return key of the iterator - const string_type& key() const - { - JSON_ASSERT(anchor.m_object != nullptr); - - switch (anchor.m_object->type()) - { - // use integer array index as key - case value_t::array: - { - if (array_index != array_index_last) - { - int_to_string( array_index_str, array_index ); - array_index_last = array_index; - } - return array_index_str; - } - - // use key from the object - case value_t::object: - return anchor.key(); - - // use an empty key for all primitive types - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - return empty_str; - } - } - - /// return value of the iterator - typename IteratorType::reference value() const - { - return anchor.value(); - } -}; - -/// proxy class for the items() function -template class iteration_proxy -{ - private: - /// the container to iterate - typename IteratorType::reference container; - - public: - /// construct iteration proxy from a container - explicit iteration_proxy(typename IteratorType::reference cont) noexcept - : container(cont) {} - - /// return iterator begin (needed for range-based for) - iteration_proxy_value begin() noexcept - { - return iteration_proxy_value(container.begin()); - } - - /// return iterator end (needed for range-based for) - iteration_proxy_value end() noexcept - { - return iteration_proxy_value(container.end()); - } -}; -// Structured Bindings Support -// For further reference see https://blog.tartanllama.xyz/structured-bindings/ -// And see https://github.com/nlohmann/json/pull/1391 -template = 0> -auto get(const nlohmann::detail::iteration_proxy_value& i) -> decltype(i.key()) -{ - return i.key(); -} -// Structured Bindings Support -// For further reference see https://blog.tartanllama.xyz/structured-bindings/ -// And see https://github.com/nlohmann/json/pull/1391 -template = 0> -auto get(const nlohmann::detail::iteration_proxy_value& i) -> decltype(i.value()) -{ - return i.value(); -} -} // namespace detail -} // namespace nlohmann - -// The Addition to the STD Namespace is required to add -// Structured Bindings Support to the iteration_proxy_value class -// For further reference see https://blog.tartanllama.xyz/structured-bindings/ -// And see https://github.com/nlohmann/json/pull/1391 -namespace std -{ -#if defined(__clang__) - // Fix: https://github.com/nlohmann/json/issues/1401 - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wmismatched-tags" -#endif -template -class tuple_size<::nlohmann::detail::iteration_proxy_value> - : public std::integral_constant {}; - -template -class tuple_element> -{ - public: - using type = decltype( - get(std::declval < - ::nlohmann::detail::iteration_proxy_value> ())); -}; -#if defined(__clang__) - #pragma clang diagnostic pop -#endif -} // namespace std - -// #include - -// #include - -// #include - - -#if JSON_HAS_EXPERIMENTAL_FILESYSTEM -#include -namespace nlohmann::detail -{ -namespace std_fs = std::experimental::filesystem; -} // namespace nlohmann::detail -#elif JSON_HAS_FILESYSTEM -#include -namespace nlohmann::detail -{ -namespace std_fs = std::filesystem; -} // namespace nlohmann::detail -#endif - -namespace nlohmann -{ -namespace detail -{ -////////////////// -// constructors // -////////////////// - -/* - * Note all external_constructor<>::construct functions need to call - * j.m_value.destroy(j.m_type) to avoid a memory leak in case j contains an - * allocated value (e.g., a string). See bug issue - * https://github.com/nlohmann/json/issues/2865 for more information. - */ - -template struct external_constructor; - -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::boolean; - j.m_value = b; - j.assert_invariant(); - } -}; - -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s) - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::string; - j.m_value = s; - j.assert_invariant(); - } - - template - static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s) - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::string; - j.m_value = std::move(s); - j.assert_invariant(); - } - - template < typename BasicJsonType, typename CompatibleStringType, - enable_if_t < !std::is_same::value, - int > = 0 > - static void construct(BasicJsonType& j, const CompatibleStringType& str) - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::string; - j.m_value.string = j.template create(str); - j.assert_invariant(); - } -}; - -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, const typename BasicJsonType::binary_t& b) - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::binary; - j.m_value = typename BasicJsonType::binary_t(b); - j.assert_invariant(); - } - - template - static void construct(BasicJsonType& j, typename BasicJsonType::binary_t&& b) - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::binary; - j.m_value = typename BasicJsonType::binary_t(std::move(b)); - j.assert_invariant(); - } -}; - -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::number_float; - j.m_value = val; - j.assert_invariant(); - } -}; - -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::number_unsigned; - j.m_value = val; - j.assert_invariant(); - } -}; - -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::number_integer; - j.m_value = val; - j.assert_invariant(); - } -}; - -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr) - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::array; - j.m_value = arr; - j.set_parents(); - j.assert_invariant(); - } - - template - static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr) - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::array; - j.m_value = std::move(arr); - j.set_parents(); - j.assert_invariant(); - } - - template < typename BasicJsonType, typename CompatibleArrayType, - enable_if_t < !std::is_same::value, - int > = 0 > - static void construct(BasicJsonType& j, const CompatibleArrayType& arr) - { - using std::begin; - using std::end; - - j.m_value.destroy(j.m_type); - j.m_type = value_t::array; - j.m_value.array = j.template create(begin(arr), end(arr)); - j.set_parents(); - j.assert_invariant(); - } - - template - static void construct(BasicJsonType& j, const std::vector& arr) - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::array; - j.m_value = value_t::array; - j.m_value.array->reserve(arr.size()); - for (const bool x : arr) - { - j.m_value.array->push_back(x); - j.set_parent(j.m_value.array->back()); - } - j.assert_invariant(); - } - - template::value, int> = 0> - static void construct(BasicJsonType& j, const std::valarray& arr) - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::array; - j.m_value = value_t::array; - j.m_value.array->resize(arr.size()); - if (arr.size() > 0) - { - std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin()); - } - j.set_parents(); - j.assert_invariant(); - } -}; - -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj) - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::object; - j.m_value = obj; - j.set_parents(); - j.assert_invariant(); - } - - template - static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj) - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::object; - j.m_value = std::move(obj); - j.set_parents(); - j.assert_invariant(); - } - - template < typename BasicJsonType, typename CompatibleObjectType, - enable_if_t < !std::is_same::value, int > = 0 > - static void construct(BasicJsonType& j, const CompatibleObjectType& obj) - { - using std::begin; - using std::end; - - j.m_value.destroy(j.m_type); - j.m_type = value_t::object; - j.m_value.object = j.template create(begin(obj), end(obj)); - j.set_parents(); - j.assert_invariant(); - } -}; - -///////////// -// to_json // -///////////// - -template::value, int> = 0> -void to_json(BasicJsonType& j, T b) noexcept -{ - external_constructor::construct(j, b); -} - -template::value, int> = 0> -void to_json(BasicJsonType& j, const CompatibleString& s) -{ - external_constructor::construct(j, s); -} - -template -void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s) -{ - external_constructor::construct(j, std::move(s)); -} - -template::value, int> = 0> -void to_json(BasicJsonType& j, FloatType val) noexcept -{ - external_constructor::construct(j, static_cast(val)); -} - -template::value, int> = 0> -void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept -{ - external_constructor::construct(j, static_cast(val)); -} - -template::value, int> = 0> -void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept -{ - external_constructor::construct(j, static_cast(val)); -} - -template::value, int> = 0> -void to_json(BasicJsonType& j, EnumType e) noexcept -{ - using underlying_type = typename std::underlying_type::type; - external_constructor::construct(j, static_cast(e)); -} - -template -void to_json(BasicJsonType& j, const std::vector& e) -{ - external_constructor::construct(j, e); -} - -template < typename BasicJsonType, typename CompatibleArrayType, - enable_if_t < is_compatible_array_type::value&& - !is_compatible_object_type::value&& - !is_compatible_string_type::value&& - !std::is_same::value&& - !is_basic_json::value, - int > = 0 > -void to_json(BasicJsonType& j, const CompatibleArrayType& arr) -{ - external_constructor::construct(j, arr); -} - -template -void to_json(BasicJsonType& j, const typename BasicJsonType::binary_t& bin) -{ - external_constructor::construct(j, bin); -} - -template::value, int> = 0> -void to_json(BasicJsonType& j, const std::valarray& arr) -{ - external_constructor::construct(j, std::move(arr)); -} - -template -void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr) -{ - external_constructor::construct(j, std::move(arr)); -} - -template < typename BasicJsonType, typename CompatibleObjectType, - enable_if_t < is_compatible_object_type::value&& !is_basic_json::value, int > = 0 > -void to_json(BasicJsonType& j, const CompatibleObjectType& obj) -{ - external_constructor::construct(j, obj); -} - -template -void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj) -{ - external_constructor::construct(j, std::move(obj)); -} - -template < - typename BasicJsonType, typename T, std::size_t N, - enable_if_t < !std::is_constructible::value, // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) - int > = 0 > -void to_json(BasicJsonType& j, const T(&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) -{ - external_constructor::construct(j, arr); -} - -template < typename BasicJsonType, typename T1, typename T2, enable_if_t < std::is_constructible::value&& std::is_constructible::value, int > = 0 > -void to_json(BasicJsonType& j, const std::pair& p) -{ - j = { p.first, p.second }; -} - -// for https://github.com/nlohmann/json/pull/1134 -template>::value, int> = 0> -void to_json(BasicJsonType& j, const T& b) -{ - j = { {b.key(), b.value()} }; -} - -template -void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence /*unused*/) -{ - j = { std::get(t)... }; -} - -template::value, int > = 0> -void to_json(BasicJsonType& j, const T& t) -{ - to_json_tuple_impl(j, t, make_index_sequence::value> {}); -} - -#if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM -template -void to_json(BasicJsonType& j, const std_fs::path& p) -{ - j = p.string(); -} -#endif - -struct to_json_fn -{ - template - auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward(val)))) - -> decltype(to_json(j, std::forward(val)), void()) - { - return to_json(j, std::forward(val)); - } -}; -} // namespace detail - -/// namespace to hold default `to_json` function -/// to see why this is required: -/// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html -namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces) -{ -constexpr const auto& to_json = detail::static_const::value; // NOLINT(misc-definitions-in-headers) -} // namespace -} // namespace nlohmann - -// #include - -// #include - - -namespace nlohmann -{ - -/// @sa https://json.nlohmann.me/api/adl_serializer/ -template -struct adl_serializer -{ - /// @brief convert a JSON value to any value type - /// @sa https://json.nlohmann.me/api/adl_serializer/from_json/ - template - static auto from_json(BasicJsonType && j, TargetType& val) noexcept( - noexcept(::nlohmann::from_json(std::forward(j), val))) - -> decltype(::nlohmann::from_json(std::forward(j), val), void()) - { - ::nlohmann::from_json(std::forward(j), val); - } - - /// @brief convert a JSON value to any value type - /// @sa https://json.nlohmann.me/api/adl_serializer/from_json/ - template - static auto from_json(BasicJsonType && j) noexcept( - noexcept(::nlohmann::from_json(std::forward(j), detail::identity_tag {}))) - -> decltype(::nlohmann::from_json(std::forward(j), detail::identity_tag {})) - { - return ::nlohmann::from_json(std::forward(j), detail::identity_tag {}); - } - - /// @brief convert any value type to a JSON value - /// @sa https://json.nlohmann.me/api/adl_serializer/to_json/ - template - static auto to_json(BasicJsonType& j, TargetType && val) noexcept( - noexcept(::nlohmann::to_json(j, std::forward(val)))) - -> decltype(::nlohmann::to_json(j, std::forward(val)), void()) - { - ::nlohmann::to_json(j, std::forward(val)); - } -}; -} // namespace nlohmann - -// #include - - -#include // uint8_t, uint64_t -#include // tie -#include // move - -namespace nlohmann -{ - -/// @brief an internal type for a backed binary type -/// @sa https://json.nlohmann.me/api/byte_container_with_subtype/ -template -class byte_container_with_subtype : public BinaryType -{ - public: - using container_type = BinaryType; - using subtype_type = std::uint64_t; - - /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ - byte_container_with_subtype() noexcept(noexcept(container_type())) - : container_type() - {} - - /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ - byte_container_with_subtype(const container_type& b) noexcept(noexcept(container_type(b))) - : container_type(b) - {} - - /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ - byte_container_with_subtype(container_type&& b) noexcept(noexcept(container_type(std::move(b)))) - : container_type(std::move(b)) - {} - - /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ - byte_container_with_subtype(const container_type& b, subtype_type subtype_) noexcept(noexcept(container_type(b))) - : container_type(b) - , m_subtype(subtype_) - , m_has_subtype(true) - {} - - /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ - byte_container_with_subtype(container_type&& b, subtype_type subtype_) noexcept(noexcept(container_type(std::move(b)))) - : container_type(std::move(b)) - , m_subtype(subtype_) - , m_has_subtype(true) - {} - - bool operator==(const byte_container_with_subtype& rhs) const - { - return std::tie(static_cast(*this), m_subtype, m_has_subtype) == - std::tie(static_cast(rhs), rhs.m_subtype, rhs.m_has_subtype); - } - - bool operator!=(const byte_container_with_subtype& rhs) const - { - return !(rhs == *this); - } - - /// @brief sets the binary subtype - /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/set_subtype/ - void set_subtype(subtype_type subtype_) noexcept - { - m_subtype = subtype_; - m_has_subtype = true; - } - - /// @brief return the binary subtype - /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/subtype/ - constexpr subtype_type subtype() const noexcept - { - return m_has_subtype ? m_subtype : static_cast(-1); - } - - /// @brief return whether the value has a subtype - /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/has_subtype/ - constexpr bool has_subtype() const noexcept - { - return m_has_subtype; - } - - /// @brief clears the binary subtype - /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/clear_subtype/ - void clear_subtype() noexcept - { - m_subtype = 0; - m_has_subtype = false; - } - - private: - subtype_type m_subtype = 0; - bool m_has_subtype = false; -}; - -} // namespace nlohmann - -// #include - -// #include - -// #include - -// #include - - -#include // uint8_t -#include // size_t -#include // hash - -// #include - -// #include - - -namespace nlohmann -{ -namespace detail -{ - -// boost::hash_combine -inline std::size_t combine(std::size_t seed, std::size_t h) noexcept -{ - seed ^= h + 0x9e3779b9 + (seed << 6U) + (seed >> 2U); - return seed; -} - -/*! -@brief hash a JSON value - -The hash function tries to rely on std::hash where possible. Furthermore, the -type of the JSON value is taken into account to have different hash values for -null, 0, 0U, and false, etc. - -@tparam BasicJsonType basic_json specialization -@param j JSON value to hash -@return hash value of j -*/ -template -std::size_t hash(const BasicJsonType& j) -{ - using string_t = typename BasicJsonType::string_t; - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - - const auto type = static_cast(j.type()); - switch (j.type()) - { - case BasicJsonType::value_t::null: - case BasicJsonType::value_t::discarded: - { - return combine(type, 0); - } - - case BasicJsonType::value_t::object: - { - auto seed = combine(type, j.size()); - for (const auto& element : j.items()) - { - const auto h = std::hash {}(element.key()); - seed = combine(seed, h); - seed = combine(seed, hash(element.value())); - } - return seed; - } - - case BasicJsonType::value_t::array: - { - auto seed = combine(type, j.size()); - for (const auto& element : j) - { - seed = combine(seed, hash(element)); - } - return seed; - } - - case BasicJsonType::value_t::string: - { - const auto h = std::hash {}(j.template get_ref()); - return combine(type, h); - } - - case BasicJsonType::value_t::boolean: - { - const auto h = std::hash {}(j.template get()); - return combine(type, h); - } - - case BasicJsonType::value_t::number_integer: - { - const auto h = std::hash {}(j.template get()); - return combine(type, h); - } - - case BasicJsonType::value_t::number_unsigned: - { - const auto h = std::hash {}(j.template get()); - return combine(type, h); - } - - case BasicJsonType::value_t::number_float: - { - const auto h = std::hash {}(j.template get()); - return combine(type, h); - } - - case BasicJsonType::value_t::binary: - { - auto seed = combine(type, j.get_binary().size()); - const auto h = std::hash {}(j.get_binary().has_subtype()); - seed = combine(seed, h); - seed = combine(seed, static_cast(j.get_binary().subtype())); - for (const auto byte : j.get_binary()) - { - seed = combine(seed, std::hash {}(byte)); - } - return seed; - } - - default: // LCOV_EXCL_LINE - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE - return 0; // LCOV_EXCL_LINE - } -} - -} // namespace detail -} // namespace nlohmann - -// #include - - -#include // generate_n -#include // array -#include // ldexp -#include // size_t -#include // uint8_t, uint16_t, uint32_t, uint64_t -#include // snprintf -#include // memcpy -#include // back_inserter -#include // numeric_limits -#include // char_traits, string -#include // make_pair, move -#include // vector - -// #include - -// #include - - -#include // array -#include // size_t -#include // strlen -#include // begin, end, iterator_traits, random_access_iterator_tag, distance, next -#include // shared_ptr, make_shared, addressof -#include // accumulate -#include // string, char_traits -#include // enable_if, is_base_of, is_pointer, is_integral, remove_pointer -#include // pair, declval - -#ifndef JSON_NO_IO - #include // FILE * - #include // istream -#endif // JSON_NO_IO - -// #include - -// #include - - -namespace nlohmann -{ -namespace detail -{ -/// the supported input formats -enum class input_format_t { json, cbor, msgpack, ubjson, bson }; - -//////////////////// -// input adapters // -//////////////////// - -#ifndef JSON_NO_IO -/*! -Input adapter for stdio file access. This adapter read only 1 byte and do not use any - buffer. This adapter is a very low level adapter. -*/ -class file_input_adapter -{ - public: - using char_type = char; - - JSON_HEDLEY_NON_NULL(2) - explicit file_input_adapter(std::FILE* f) noexcept - : m_file(f) - {} - - // make class move-only - file_input_adapter(const file_input_adapter&) = delete; - file_input_adapter(file_input_adapter&&) noexcept = default; - file_input_adapter& operator=(const file_input_adapter&) = delete; - file_input_adapter& operator=(file_input_adapter&&) = delete; - ~file_input_adapter() = default; - - std::char_traits::int_type get_character() noexcept - { - return std::fgetc(m_file); - } - - private: - /// the file pointer to read from - std::FILE* m_file; -}; - - -/*! -Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at -beginning of input. Does not support changing the underlying std::streambuf -in mid-input. Maintains underlying std::istream and std::streambuf to support -subsequent use of standard std::istream operations to process any input -characters following those used in parsing the JSON input. Clears the -std::istream flags; any input errors (e.g., EOF) will be detected by the first -subsequent call for input from the std::istream. -*/ -class input_stream_adapter -{ - public: - using char_type = char; - - ~input_stream_adapter() - { - // clear stream flags; we use underlying streambuf I/O, do not - // maintain ifstream flags, except eof - if (is != nullptr) - { - is->clear(is->rdstate() & std::ios::eofbit); - } - } - - explicit input_stream_adapter(std::istream& i) - : is(&i), sb(i.rdbuf()) - {} - - // delete because of pointer members - input_stream_adapter(const input_stream_adapter&) = delete; - input_stream_adapter& operator=(input_stream_adapter&) = delete; - input_stream_adapter& operator=(input_stream_adapter&&) = delete; - - input_stream_adapter(input_stream_adapter&& rhs) noexcept - : is(rhs.is), sb(rhs.sb) - { - rhs.is = nullptr; - rhs.sb = nullptr; - } - - // std::istream/std::streambuf use std::char_traits::to_int_type, to - // ensure that std::char_traits::eof() and the character 0xFF do not - // end up as the same value, e.g. 0xFFFFFFFF. - std::char_traits::int_type get_character() - { - auto res = sb->sbumpc(); - // set eof manually, as we don't use the istream interface. - if (JSON_HEDLEY_UNLIKELY(res == std::char_traits::eof())) - { - is->clear(is->rdstate() | std::ios::eofbit); - } - return res; - } - - private: - /// the associated input stream - std::istream* is = nullptr; - std::streambuf* sb = nullptr; -}; -#endif // JSON_NO_IO - -// General-purpose iterator-based adapter. It might not be as fast as -// theoretically possible for some containers, but it is extremely versatile. -template -class iterator_input_adapter -{ - public: - using char_type = typename std::iterator_traits::value_type; - - iterator_input_adapter(IteratorType first, IteratorType last) - : current(std::move(first)), end(std::move(last)) - {} - - typename std::char_traits::int_type get_character() - { - if (JSON_HEDLEY_LIKELY(current != end)) - { - auto result = std::char_traits::to_int_type(*current); - std::advance(current, 1); - return result; - } - - return std::char_traits::eof(); - } - - private: - IteratorType current; - IteratorType end; - - template - friend struct wide_string_input_helper; - - bool empty() const - { - return current == end; - } -}; - - -template -struct wide_string_input_helper; - -template -struct wide_string_input_helper -{ - // UTF-32 - static void fill_buffer(BaseInputAdapter& input, - std::array::int_type, 4>& utf8_bytes, - size_t& utf8_bytes_index, - size_t& utf8_bytes_filled) - { - utf8_bytes_index = 0; - - if (JSON_HEDLEY_UNLIKELY(input.empty())) - { - utf8_bytes[0] = std::char_traits::eof(); - utf8_bytes_filled = 1; - } - else - { - // get the current character - const auto wc = input.get_character(); - - // UTF-32 to UTF-8 encoding - if (wc < 0x80) - { - utf8_bytes[0] = static_cast::int_type>(wc); - utf8_bytes_filled = 1; - } - else if (wc <= 0x7FF) - { - utf8_bytes[0] = static_cast::int_type>(0xC0u | ((static_cast(wc) >> 6u) & 0x1Fu)); - utf8_bytes[1] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); - utf8_bytes_filled = 2; - } - else if (wc <= 0xFFFF) - { - utf8_bytes[0] = static_cast::int_type>(0xE0u | ((static_cast(wc) >> 12u) & 0x0Fu)); - utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); - utf8_bytes[2] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); - utf8_bytes_filled = 3; - } - else if (wc <= 0x10FFFF) - { - utf8_bytes[0] = static_cast::int_type>(0xF0u | ((static_cast(wc) >> 18u) & 0x07u)); - utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 12u) & 0x3Fu)); - utf8_bytes[2] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); - utf8_bytes[3] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); - utf8_bytes_filled = 4; - } - else - { - // unknown character - utf8_bytes[0] = static_cast::int_type>(wc); - utf8_bytes_filled = 1; - } - } - } -}; - -template -struct wide_string_input_helper -{ - // UTF-16 - static void fill_buffer(BaseInputAdapter& input, - std::array::int_type, 4>& utf8_bytes, - size_t& utf8_bytes_index, - size_t& utf8_bytes_filled) - { - utf8_bytes_index = 0; - - if (JSON_HEDLEY_UNLIKELY(input.empty())) - { - utf8_bytes[0] = std::char_traits::eof(); - utf8_bytes_filled = 1; - } - else - { - // get the current character - const auto wc = input.get_character(); - - // UTF-16 to UTF-8 encoding - if (wc < 0x80) - { - utf8_bytes[0] = static_cast::int_type>(wc); - utf8_bytes_filled = 1; - } - else if (wc <= 0x7FF) - { - utf8_bytes[0] = static_cast::int_type>(0xC0u | ((static_cast(wc) >> 6u))); - utf8_bytes[1] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); - utf8_bytes_filled = 2; - } - else if (0xD800 > wc || wc >= 0xE000) - { - utf8_bytes[0] = static_cast::int_type>(0xE0u | ((static_cast(wc) >> 12u))); - utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); - utf8_bytes[2] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); - utf8_bytes_filled = 3; - } - else - { - if (JSON_HEDLEY_UNLIKELY(!input.empty())) - { - const auto wc2 = static_cast(input.get_character()); - const auto charcode = 0x10000u + (((static_cast(wc) & 0x3FFu) << 10u) | (wc2 & 0x3FFu)); - utf8_bytes[0] = static_cast::int_type>(0xF0u | (charcode >> 18u)); - utf8_bytes[1] = static_cast::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu)); - utf8_bytes[2] = static_cast::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu)); - utf8_bytes[3] = static_cast::int_type>(0x80u | (charcode & 0x3Fu)); - utf8_bytes_filled = 4; - } - else - { - utf8_bytes[0] = static_cast::int_type>(wc); - utf8_bytes_filled = 1; - } - } - } - } -}; - -// Wraps another input apdater to convert wide character types into individual bytes. -template -class wide_string_input_adapter -{ - public: - using char_type = char; - - wide_string_input_adapter(BaseInputAdapter base) - : base_adapter(base) {} - - typename std::char_traits::int_type get_character() noexcept - { - // check if buffer needs to be filled - if (utf8_bytes_index == utf8_bytes_filled) - { - fill_buffer(); - - JSON_ASSERT(utf8_bytes_filled > 0); - JSON_ASSERT(utf8_bytes_index == 0); - } - - // use buffer - JSON_ASSERT(utf8_bytes_filled > 0); - JSON_ASSERT(utf8_bytes_index < utf8_bytes_filled); - return utf8_bytes[utf8_bytes_index++]; - } - - private: - BaseInputAdapter base_adapter; - - template - void fill_buffer() - { - wide_string_input_helper::fill_buffer(base_adapter, utf8_bytes, utf8_bytes_index, utf8_bytes_filled); - } - - /// a buffer for UTF-8 bytes - std::array::int_type, 4> utf8_bytes = {{0, 0, 0, 0}}; - - /// index to the utf8_codes array for the next valid byte - std::size_t utf8_bytes_index = 0; - /// number of valid bytes in the utf8_codes array - std::size_t utf8_bytes_filled = 0; -}; - - -template -struct iterator_input_adapter_factory -{ - using iterator_type = IteratorType; - using char_type = typename std::iterator_traits::value_type; - using adapter_type = iterator_input_adapter; - - static adapter_type create(IteratorType first, IteratorType last) - { - return adapter_type(std::move(first), std::move(last)); - } -}; - -template -struct is_iterator_of_multibyte -{ - using value_type = typename std::iterator_traits::value_type; - enum - { - value = sizeof(value_type) > 1 - }; -}; - -template -struct iterator_input_adapter_factory::value>> -{ - using iterator_type = IteratorType; - using char_type = typename std::iterator_traits::value_type; - using base_adapter_type = iterator_input_adapter; - using adapter_type = wide_string_input_adapter; - - static adapter_type create(IteratorType first, IteratorType last) - { - return adapter_type(base_adapter_type(std::move(first), std::move(last))); - } -}; - -// General purpose iterator-based input -template -typename iterator_input_adapter_factory::adapter_type input_adapter(IteratorType first, IteratorType last) -{ - using factory_type = iterator_input_adapter_factory; - return factory_type::create(first, last); -} - -// Convenience shorthand from container to iterator -// Enables ADL on begin(container) and end(container) -// Encloses the using declarations in namespace for not to leak them to outside scope - -namespace container_input_adapter_factory_impl -{ - -using std::begin; -using std::end; - -template -struct container_input_adapter_factory {}; - -template -struct container_input_adapter_factory< ContainerType, - void_t()), end(std::declval()))>> - { - using adapter_type = decltype(input_adapter(begin(std::declval()), end(std::declval()))); - - static adapter_type create(const ContainerType& container) -{ - return input_adapter(begin(container), end(container)); -} - }; - -} // namespace container_input_adapter_factory_impl - -template -typename container_input_adapter_factory_impl::container_input_adapter_factory::adapter_type input_adapter(const ContainerType& container) -{ - return container_input_adapter_factory_impl::container_input_adapter_factory::create(container); -} - -#ifndef JSON_NO_IO -// Special cases with fast paths -inline file_input_adapter input_adapter(std::FILE* file) -{ - return file_input_adapter(file); -} - -inline input_stream_adapter input_adapter(std::istream& stream) -{ - return input_stream_adapter(stream); -} - -inline input_stream_adapter input_adapter(std::istream&& stream) -{ - return input_stream_adapter(stream); -} -#endif // JSON_NO_IO - -using contiguous_bytes_input_adapter = decltype(input_adapter(std::declval(), std::declval())); - -// Null-delimited strings, and the like. -template < typename CharT, - typename std::enable_if < - std::is_pointer::value&& - !std::is_array::value&& - std::is_integral::type>::value&& - sizeof(typename std::remove_pointer::type) == 1, - int >::type = 0 > -contiguous_bytes_input_adapter input_adapter(CharT b) -{ - auto length = std::strlen(reinterpret_cast(b)); - const auto* ptr = reinterpret_cast(b); - return input_adapter(ptr, ptr + length); -} - -template -auto input_adapter(T (&array)[N]) -> decltype(input_adapter(array, array + N)) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) -{ - return input_adapter(array, array + N); -} - -// This class only handles inputs of input_buffer_adapter type. -// It's required so that expressions like {ptr, len} can be implicitly cast -// to the correct adapter. -class span_input_adapter -{ - public: - template < typename CharT, - typename std::enable_if < - std::is_pointer::value&& - std::is_integral::type>::value&& - sizeof(typename std::remove_pointer::type) == 1, - int >::type = 0 > - span_input_adapter(CharT b, std::size_t l) - : ia(reinterpret_cast(b), reinterpret_cast(b) + l) {} - - template::iterator_category, std::random_access_iterator_tag>::value, - int>::type = 0> - span_input_adapter(IteratorType first, IteratorType last) - : ia(input_adapter(first, last)) {} - - contiguous_bytes_input_adapter&& get() - { - return std::move(ia); // NOLINT(hicpp-move-const-arg,performance-move-const-arg) - } - - private: - contiguous_bytes_input_adapter ia; -}; -} // namespace detail -} // namespace nlohmann - -// #include - - -#include -#include // string -#include // move -#include // vector - -// #include - -// #include - - -namespace nlohmann -{ - -/*! -@brief SAX interface - -This class describes the SAX interface used by @ref nlohmann::json::sax_parse. -Each function is called in different situations while the input is parsed. The -boolean return value informs the parser whether to continue processing the -input. -*/ -template -struct json_sax -{ - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - using string_t = typename BasicJsonType::string_t; - using binary_t = typename BasicJsonType::binary_t; - - /*! - @brief a null value was read - @return whether parsing should proceed - */ - virtual bool null() = 0; - - /*! - @brief a boolean value was read - @param[in] val boolean value - @return whether parsing should proceed - */ - virtual bool boolean(bool val) = 0; - - /*! - @brief an integer number was read - @param[in] val integer value - @return whether parsing should proceed - */ - virtual bool number_integer(number_integer_t val) = 0; - - /*! - @brief an unsigned integer number was read - @param[in] val unsigned integer value - @return whether parsing should proceed - */ - virtual bool number_unsigned(number_unsigned_t val) = 0; - - /*! - @brief a floating-point number was read - @param[in] val floating-point value - @param[in] s raw token value - @return whether parsing should proceed - */ - virtual bool number_float(number_float_t val, const string_t& s) = 0; - - /*! - @brief a string value was read - @param[in] val string value - @return whether parsing should proceed - @note It is safe to move the passed string value. - */ - virtual bool string(string_t& val) = 0; - - /*! - @brief a binary value was read - @param[in] val binary value - @return whether parsing should proceed - @note It is safe to move the passed binary value. - */ - virtual bool binary(binary_t& val) = 0; - - /*! - @brief the beginning of an object was read - @param[in] elements number of object elements or -1 if unknown - @return whether parsing should proceed - @note binary formats may report the number of elements - */ - virtual bool start_object(std::size_t elements) = 0; - - /*! - @brief an object key was read - @param[in] val object key - @return whether parsing should proceed - @note It is safe to move the passed string. - */ - virtual bool key(string_t& val) = 0; - - /*! - @brief the end of an object was read - @return whether parsing should proceed - */ - virtual bool end_object() = 0; - - /*! - @brief the beginning of an array was read - @param[in] elements number of array elements or -1 if unknown - @return whether parsing should proceed - @note binary formats may report the number of elements - */ - virtual bool start_array(std::size_t elements) = 0; - - /*! - @brief the end of an array was read - @return whether parsing should proceed - */ - virtual bool end_array() = 0; - - /*! - @brief a parse error occurred - @param[in] position the position in the input where the error occurs - @param[in] last_token the last read token - @param[in] ex an exception object describing the error - @return whether parsing should proceed (must return false) - */ - virtual bool parse_error(std::size_t position, - const std::string& last_token, - const detail::exception& ex) = 0; - - json_sax() = default; - json_sax(const json_sax&) = default; - json_sax(json_sax&&) noexcept = default; - json_sax& operator=(const json_sax&) = default; - json_sax& operator=(json_sax&&) noexcept = default; - virtual ~json_sax() = default; -}; - - -namespace detail -{ -/*! -@brief SAX implementation to create a JSON value from SAX events - -This class implements the @ref json_sax interface and processes the SAX events -to create a JSON value which makes it basically a DOM parser. The structure or -hierarchy of the JSON value is managed by the stack `ref_stack` which contains -a pointer to the respective array or object for each recursion depth. - -After successful parsing, the value that is passed by reference to the -constructor contains the parsed value. - -@tparam BasicJsonType the JSON type -*/ -template -class json_sax_dom_parser -{ - public: - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - using string_t = typename BasicJsonType::string_t; - using binary_t = typename BasicJsonType::binary_t; - - /*! - @param[in,out] r reference to a JSON value that is manipulated while - parsing - @param[in] allow_exceptions_ whether parse errors yield exceptions - */ - explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true) - : root(r), allow_exceptions(allow_exceptions_) - {} - - // make class move-only - json_sax_dom_parser(const json_sax_dom_parser&) = delete; - json_sax_dom_parser(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) - json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete; - json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) - ~json_sax_dom_parser() = default; - - bool null() - { - handle_value(nullptr); - return true; - } - - bool boolean(bool val) - { - handle_value(val); - return true; - } - - bool number_integer(number_integer_t val) - { - handle_value(val); - return true; - } - - bool number_unsigned(number_unsigned_t val) - { - handle_value(val); - return true; - } - - bool number_float(number_float_t val, const string_t& /*unused*/) - { - handle_value(val); - return true; - } - - bool string(string_t& val) - { - handle_value(val); - return true; - } - - bool binary(binary_t& val) - { - handle_value(std::move(val)); - return true; - } - - bool start_object(std::size_t len) - { - ref_stack.push_back(handle_value(BasicJsonType::value_t::object)); - - if (JSON_HEDLEY_UNLIKELY(len != static_cast(-1) && len > ref_stack.back()->max_size())) - { - JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len), *ref_stack.back())); - } - - return true; - } - - bool key(string_t& val) - { - // add null at given key and store the reference for later - object_element = &(ref_stack.back()->m_value.object->operator[](val)); - return true; - } - - bool end_object() - { - ref_stack.back()->set_parents(); - ref_stack.pop_back(); - return true; - } - - bool start_array(std::size_t len) - { - ref_stack.push_back(handle_value(BasicJsonType::value_t::array)); - - if (JSON_HEDLEY_UNLIKELY(len != static_cast(-1) && len > ref_stack.back()->max_size())) - { - JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len), *ref_stack.back())); - } - - return true; - } - - bool end_array() - { - ref_stack.back()->set_parents(); - ref_stack.pop_back(); - return true; - } - - template - bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, - const Exception& ex) - { - errored = true; - static_cast(ex); - if (allow_exceptions) - { - JSON_THROW(ex); - } - return false; - } - - constexpr bool is_errored() const - { - return errored; - } - - private: - /*! - @invariant If the ref stack is empty, then the passed value will be the new - root. - @invariant If the ref stack contains a value, then it is an array or an - object to which we can add elements - */ - template - JSON_HEDLEY_RETURNS_NON_NULL - BasicJsonType* handle_value(Value&& v) - { - if (ref_stack.empty()) - { - root = BasicJsonType(std::forward(v)); - return &root; - } - - JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object()); - - if (ref_stack.back()->is_array()) - { - ref_stack.back()->m_value.array->emplace_back(std::forward(v)); - return &(ref_stack.back()->m_value.array->back()); - } - - JSON_ASSERT(ref_stack.back()->is_object()); - JSON_ASSERT(object_element); - *object_element = BasicJsonType(std::forward(v)); - return object_element; - } - - /// the parsed JSON value - BasicJsonType& root; - /// stack to model hierarchy of values - std::vector ref_stack {}; - /// helper to hold the reference for the next object element - BasicJsonType* object_element = nullptr; - /// whether a syntax error occurred - bool errored = false; - /// whether to throw exceptions in case of errors - const bool allow_exceptions = true; -}; - -template -class json_sax_dom_callback_parser -{ - public: - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - using string_t = typename BasicJsonType::string_t; - using binary_t = typename BasicJsonType::binary_t; - using parser_callback_t = typename BasicJsonType::parser_callback_t; - using parse_event_t = typename BasicJsonType::parse_event_t; - - json_sax_dom_callback_parser(BasicJsonType& r, - const parser_callback_t cb, - const bool allow_exceptions_ = true) - : root(r), callback(cb), allow_exceptions(allow_exceptions_) - { - keep_stack.push_back(true); - } - - // make class move-only - json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete; - json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) - json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete; - json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) - ~json_sax_dom_callback_parser() = default; - - bool null() - { - handle_value(nullptr); - return true; - } - - bool boolean(bool val) - { - handle_value(val); - return true; - } - - bool number_integer(number_integer_t val) - { - handle_value(val); - return true; - } - - bool number_unsigned(number_unsigned_t val) - { - handle_value(val); - return true; - } - - bool number_float(number_float_t val, const string_t& /*unused*/) - { - handle_value(val); - return true; - } - - bool string(string_t& val) - { - handle_value(val); - return true; - } - - bool binary(binary_t& val) - { - handle_value(std::move(val)); - return true; - } - - bool start_object(std::size_t len) - { - // check callback for object start - const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::object_start, discarded); - keep_stack.push_back(keep); - - auto val = handle_value(BasicJsonType::value_t::object, true); - ref_stack.push_back(val.second); - - // check object limit - if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != static_cast(-1) && len > ref_stack.back()->max_size())) - { - JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len), *ref_stack.back())); - } - - return true; - } - - bool key(string_t& val) - { - BasicJsonType k = BasicJsonType(val); - - // check callback for key - const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::key, k); - key_keep_stack.push_back(keep); - - // add discarded value at given key and store the reference for later - if (keep && ref_stack.back()) - { - object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded); - } - - return true; - } - - bool end_object() - { - if (ref_stack.back()) - { - if (!callback(static_cast(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back())) - { - // discard object - *ref_stack.back() = discarded; - } - else - { - ref_stack.back()->set_parents(); - } - } - - JSON_ASSERT(!ref_stack.empty()); - JSON_ASSERT(!keep_stack.empty()); - ref_stack.pop_back(); - keep_stack.pop_back(); - - if (!ref_stack.empty() && ref_stack.back() && ref_stack.back()->is_structured()) - { - // remove discarded value - for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it) - { - if (it->is_discarded()) - { - ref_stack.back()->erase(it); - break; - } - } - } - - return true; - } - - bool start_array(std::size_t len) - { - const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::array_start, discarded); - keep_stack.push_back(keep); - - auto val = handle_value(BasicJsonType::value_t::array, true); - ref_stack.push_back(val.second); - - // check array limit - if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != static_cast(-1) && len > ref_stack.back()->max_size())) - { - JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len), *ref_stack.back())); - } - - return true; - } - - bool end_array() - { - bool keep = true; - - if (ref_stack.back()) - { - keep = callback(static_cast(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back()); - if (keep) - { - ref_stack.back()->set_parents(); - } - else - { - // discard array - *ref_stack.back() = discarded; - } - } - - JSON_ASSERT(!ref_stack.empty()); - JSON_ASSERT(!keep_stack.empty()); - ref_stack.pop_back(); - keep_stack.pop_back(); - - // remove discarded value - if (!keep && !ref_stack.empty() && ref_stack.back()->is_array()) - { - ref_stack.back()->m_value.array->pop_back(); - } - - return true; - } - - template - bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, - const Exception& ex) - { - errored = true; - static_cast(ex); - if (allow_exceptions) - { - JSON_THROW(ex); - } - return false; - } - - constexpr bool is_errored() const - { - return errored; - } - - private: - /*! - @param[in] v value to add to the JSON value we build during parsing - @param[in] skip_callback whether we should skip calling the callback - function; this is required after start_array() and - start_object() SAX events, because otherwise we would call the - callback function with an empty array or object, respectively. - - @invariant If the ref stack is empty, then the passed value will be the new - root. - @invariant If the ref stack contains a value, then it is an array or an - object to which we can add elements - - @return pair of boolean (whether value should be kept) and pointer (to the - passed value in the ref_stack hierarchy; nullptr if not kept) - */ - template - std::pair handle_value(Value&& v, const bool skip_callback = false) - { - JSON_ASSERT(!keep_stack.empty()); - - // do not handle this value if we know it would be added to a discarded - // container - if (!keep_stack.back()) - { - return {false, nullptr}; - } - - // create value - auto value = BasicJsonType(std::forward(v)); - - // check callback - const bool keep = skip_callback || callback(static_cast(ref_stack.size()), parse_event_t::value, value); - - // do not handle this value if we just learnt it shall be discarded - if (!keep) - { - return {false, nullptr}; - } - - if (ref_stack.empty()) - { - root = std::move(value); - return {true, &root}; - } - - // skip this value if we already decided to skip the parent - // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360) - if (!ref_stack.back()) - { - return {false, nullptr}; - } - - // we now only expect arrays and objects - JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object()); - - // array - if (ref_stack.back()->is_array()) - { - ref_stack.back()->m_value.array->emplace_back(std::move(value)); - return {true, &(ref_stack.back()->m_value.array->back())}; - } - - // object - JSON_ASSERT(ref_stack.back()->is_object()); - // check if we should store an element for the current key - JSON_ASSERT(!key_keep_stack.empty()); - const bool store_element = key_keep_stack.back(); - key_keep_stack.pop_back(); - - if (!store_element) - { - return {false, nullptr}; - } - - JSON_ASSERT(object_element); - *object_element = std::move(value); - return {true, object_element}; - } - - /// the parsed JSON value - BasicJsonType& root; - /// stack to model hierarchy of values - std::vector ref_stack {}; - /// stack to manage which values to keep - std::vector keep_stack {}; - /// stack to manage which object keys to keep - std::vector key_keep_stack {}; - /// helper to hold the reference for the next object element - BasicJsonType* object_element = nullptr; - /// whether a syntax error occurred - bool errored = false; - /// callback function - const parser_callback_t callback = nullptr; - /// whether to throw exceptions in case of errors - const bool allow_exceptions = true; - /// a discarded value for the callback - BasicJsonType discarded = BasicJsonType::value_t::discarded; -}; - -template -class json_sax_acceptor -{ - public: - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - using string_t = typename BasicJsonType::string_t; - using binary_t = typename BasicJsonType::binary_t; - - bool null() - { - return true; - } - - bool boolean(bool /*unused*/) - { - return true; - } - - bool number_integer(number_integer_t /*unused*/) - { - return true; - } - - bool number_unsigned(number_unsigned_t /*unused*/) - { - return true; - } - - bool number_float(number_float_t /*unused*/, const string_t& /*unused*/) - { - return true; - } - - bool string(string_t& /*unused*/) - { - return true; - } - - bool binary(binary_t& /*unused*/) - { - return true; - } - - bool start_object(std::size_t /*unused*/ = static_cast(-1)) - { - return true; - } - - bool key(string_t& /*unused*/) - { - return true; - } - - bool end_object() - { - return true; - } - - bool start_array(std::size_t /*unused*/ = static_cast(-1)) - { - return true; - } - - bool end_array() - { - return true; - } - - bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/) - { - return false; - } -}; -} // namespace detail - -} // namespace nlohmann - -// #include - - -#include // array -#include // localeconv -#include // size_t -#include // snprintf -#include // strtof, strtod, strtold, strtoll, strtoull -#include // initializer_list -#include // char_traits, string -#include // move -#include // vector - -// #include - -// #include - -// #include - - -namespace nlohmann -{ -namespace detail -{ -/////////// -// lexer // -/////////// - -template -class lexer_base -{ - public: - /// token types for the parser - enum class token_type - { - uninitialized, ///< indicating the scanner is uninitialized - literal_true, ///< the `true` literal - literal_false, ///< the `false` literal - literal_null, ///< the `null` literal - value_string, ///< a string -- use get_string() for actual value - value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value - value_integer, ///< a signed integer -- use get_number_integer() for actual value - value_float, ///< an floating point number -- use get_number_float() for actual value - begin_array, ///< the character for array begin `[` - begin_object, ///< the character for object begin `{` - end_array, ///< the character for array end `]` - end_object, ///< the character for object end `}` - name_separator, ///< the name separator `:` - value_separator, ///< the value separator `,` - parse_error, ///< indicating a parse error - end_of_input, ///< indicating the end of the input buffer - literal_or_value ///< a literal or the begin of a value (only for diagnostics) - }; - - /// return name of values of type token_type (only used for errors) - JSON_HEDLEY_RETURNS_NON_NULL - JSON_HEDLEY_CONST - static const char* token_type_name(const token_type t) noexcept - { - switch (t) - { - case token_type::uninitialized: - return ""; - case token_type::literal_true: - return "true literal"; - case token_type::literal_false: - return "false literal"; - case token_type::literal_null: - return "null literal"; - case token_type::value_string: - return "string literal"; - case token_type::value_unsigned: - case token_type::value_integer: - case token_type::value_float: - return "number literal"; - case token_type::begin_array: - return "'['"; - case token_type::begin_object: - return "'{'"; - case token_type::end_array: - return "']'"; - case token_type::end_object: - return "'}'"; - case token_type::name_separator: - return "':'"; - case token_type::value_separator: - return "','"; - case token_type::parse_error: - return ""; - case token_type::end_of_input: - return "end of input"; - case token_type::literal_or_value: - return "'[', '{', or a literal"; - // LCOV_EXCL_START - default: // catch non-enum values - return "unknown token"; - // LCOV_EXCL_STOP - } - } -}; -/*! -@brief lexical analysis - -This class organizes the lexical analysis during JSON deserialization. -*/ -template -class lexer : public lexer_base -{ - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - using string_t = typename BasicJsonType::string_t; - using char_type = typename InputAdapterType::char_type; - using char_int_type = typename std::char_traits::int_type; - - public: - using token_type = typename lexer_base::token_type; - - explicit lexer(InputAdapterType&& adapter, bool ignore_comments_ = false) noexcept - : ia(std::move(adapter)) - , ignore_comments(ignore_comments_) - , decimal_point_char(static_cast(get_decimal_point())) - {} - - // delete because of pointer members - lexer(const lexer&) = delete; - lexer(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) - lexer& operator=(lexer&) = delete; - lexer& operator=(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) - ~lexer() = default; - - private: - ///////////////////// - // locales - ///////////////////// - - /// return the locale-dependent decimal point - JSON_HEDLEY_PURE - static char get_decimal_point() noexcept - { - const auto* loc = localeconv(); - JSON_ASSERT(loc != nullptr); - return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point); - } - - ///////////////////// - // scan functions - ///////////////////// - - /*! - @brief get codepoint from 4 hex characters following `\u` - - For input "\u c1 c2 c3 c4" the codepoint is: - (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4 - = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0) - - Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f' - must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The - conversion is done by subtracting the offset (0x30, 0x37, and 0x57) - between the ASCII value of the character and the desired integer value. - - @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or - non-hex character) - */ - int get_codepoint() - { - // this function only makes sense after reading `\u` - JSON_ASSERT(current == 'u'); - int codepoint = 0; - - const auto factors = { 12u, 8u, 4u, 0u }; - for (const auto factor : factors) - { - get(); - - if (current >= '0' && current <= '9') - { - codepoint += static_cast((static_cast(current) - 0x30u) << factor); - } - else if (current >= 'A' && current <= 'F') - { - codepoint += static_cast((static_cast(current) - 0x37u) << factor); - } - else if (current >= 'a' && current <= 'f') - { - codepoint += static_cast((static_cast(current) - 0x57u) << factor); - } - else - { - return -1; - } - } - - JSON_ASSERT(0x0000 <= codepoint && codepoint <= 0xFFFF); - return codepoint; - } - - /*! - @brief check if the next byte(s) are inside a given range - - Adds the current byte and, for each passed range, reads a new byte and - checks if it is inside the range. If a violation was detected, set up an - error message and return false. Otherwise, return true. - - @param[in] ranges list of integers; interpreted as list of pairs of - inclusive lower and upper bound, respectively - - @pre The passed list @a ranges must have 2, 4, or 6 elements; that is, - 1, 2, or 3 pairs. This precondition is enforced by an assertion. - - @return true if and only if no range violation was detected - */ - bool next_byte_in_range(std::initializer_list ranges) - { - JSON_ASSERT(ranges.size() == 2 || ranges.size() == 4 || ranges.size() == 6); - add(current); - - for (auto range = ranges.begin(); range != ranges.end(); ++range) - { - get(); - if (JSON_HEDLEY_LIKELY(*range <= current && current <= *(++range))) - { - add(current); - } - else - { - error_message = "invalid string: ill-formed UTF-8 byte"; - return false; - } - } - - return true; - } - - /*! - @brief scan a string literal - - This function scans a string according to Sect. 7 of RFC 8259. While - scanning, bytes are escaped and copied into buffer token_buffer. Then the - function returns successfully, token_buffer is *not* null-terminated (as it - may contain \0 bytes), and token_buffer.size() is the number of bytes in the - string. - - @return token_type::value_string if string could be successfully scanned, - token_type::parse_error otherwise - - @note In case of errors, variable error_message contains a textual - description. - */ - token_type scan_string() - { - // reset token_buffer (ignore opening quote) - reset(); - - // we entered the function by reading an open quote - JSON_ASSERT(current == '\"'); - - while (true) - { - // get next character - switch (get()) - { - // end of file while parsing string - case std::char_traits::eof(): - { - error_message = "invalid string: missing closing quote"; - return token_type::parse_error; - } - - // closing quote - case '\"': - { - return token_type::value_string; - } - - // escapes - case '\\': - { - switch (get()) - { - // quotation mark - case '\"': - add('\"'); - break; - // reverse solidus - case '\\': - add('\\'); - break; - // solidus - case '/': - add('/'); - break; - // backspace - case 'b': - add('\b'); - break; - // form feed - case 'f': - add('\f'); - break; - // line feed - case 'n': - add('\n'); - break; - // carriage return - case 'r': - add('\r'); - break; - // tab - case 't': - add('\t'); - break; - - // unicode escapes - case 'u': - { - const int codepoint1 = get_codepoint(); - int codepoint = codepoint1; // start with codepoint1 - - if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1)) - { - error_message = "invalid string: '\\u' must be followed by 4 hex digits"; - return token_type::parse_error; - } - - // check if code point is a high surrogate - if (0xD800 <= codepoint1 && codepoint1 <= 0xDBFF) - { - // expect next \uxxxx entry - if (JSON_HEDLEY_LIKELY(get() == '\\' && get() == 'u')) - { - const int codepoint2 = get_codepoint(); - - if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1)) - { - error_message = "invalid string: '\\u' must be followed by 4 hex digits"; - return token_type::parse_error; - } - - // check if codepoint2 is a low surrogate - if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 && codepoint2 <= 0xDFFF)) - { - // overwrite codepoint - codepoint = static_cast( - // high surrogate occupies the most significant 22 bits - (static_cast(codepoint1) << 10u) - // low surrogate occupies the least significant 15 bits - + static_cast(codepoint2) - // there is still the 0xD800, 0xDC00 and 0x10000 noise - // in the result, so we have to subtract with: - // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00 - - 0x35FDC00u); - } - else - { - error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF"; - return token_type::parse_error; - } - } - else - { - error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF"; - return token_type::parse_error; - } - } - else - { - if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 && codepoint1 <= 0xDFFF)) - { - error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF"; - return token_type::parse_error; - } - } - - // result of the above calculation yields a proper codepoint - JSON_ASSERT(0x00 <= codepoint && codepoint <= 0x10FFFF); - - // translate codepoint into bytes - if (codepoint < 0x80) - { - // 1-byte characters: 0xxxxxxx (ASCII) - add(static_cast(codepoint)); - } - else if (codepoint <= 0x7FF) - { - // 2-byte characters: 110xxxxx 10xxxxxx - add(static_cast(0xC0u | (static_cast(codepoint) >> 6u))); - add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); - } - else if (codepoint <= 0xFFFF) - { - // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx - add(static_cast(0xE0u | (static_cast(codepoint) >> 12u))); - add(static_cast(0x80u | ((static_cast(codepoint) >> 6u) & 0x3Fu))); - add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); - } - else - { - // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - add(static_cast(0xF0u | (static_cast(codepoint) >> 18u))); - add(static_cast(0x80u | ((static_cast(codepoint) >> 12u) & 0x3Fu))); - add(static_cast(0x80u | ((static_cast(codepoint) >> 6u) & 0x3Fu))); - add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); - } - - break; - } - - // other characters after escape - default: - error_message = "invalid string: forbidden character after backslash"; - return token_type::parse_error; - } - - break; - } - - // invalid control characters - case 0x00: - { - error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000"; - return token_type::parse_error; - } - - case 0x01: - { - error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001"; - return token_type::parse_error; - } - - case 0x02: - { - error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002"; - return token_type::parse_error; - } - - case 0x03: - { - error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003"; - return token_type::parse_error; - } - - case 0x04: - { - error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004"; - return token_type::parse_error; - } - - case 0x05: - { - error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005"; - return token_type::parse_error; - } - - case 0x06: - { - error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006"; - return token_type::parse_error; - } - - case 0x07: - { - error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007"; - return token_type::parse_error; - } - - case 0x08: - { - error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b"; - return token_type::parse_error; - } - - case 0x09: - { - error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t"; - return token_type::parse_error; - } - - case 0x0A: - { - error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n"; - return token_type::parse_error; - } - - case 0x0B: - { - error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B"; - return token_type::parse_error; - } - - case 0x0C: - { - error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f"; - return token_type::parse_error; - } - - case 0x0D: - { - error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r"; - return token_type::parse_error; - } - - case 0x0E: - { - error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E"; - return token_type::parse_error; - } - - case 0x0F: - { - error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F"; - return token_type::parse_error; - } - - case 0x10: - { - error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010"; - return token_type::parse_error; - } - - case 0x11: - { - error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011"; - return token_type::parse_error; - } - - case 0x12: - { - error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012"; - return token_type::parse_error; - } - - case 0x13: - { - error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013"; - return token_type::parse_error; - } - - case 0x14: - { - error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014"; - return token_type::parse_error; - } - - case 0x15: - { - error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015"; - return token_type::parse_error; - } - - case 0x16: - { - error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016"; - return token_type::parse_error; - } - - case 0x17: - { - error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017"; - return token_type::parse_error; - } - - case 0x18: - { - error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018"; - return token_type::parse_error; - } - - case 0x19: - { - error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019"; - return token_type::parse_error; - } - - case 0x1A: - { - error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A"; - return token_type::parse_error; - } - - case 0x1B: - { - error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B"; - return token_type::parse_error; - } - - case 0x1C: - { - error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C"; - return token_type::parse_error; - } - - case 0x1D: - { - error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D"; - return token_type::parse_error; - } - - case 0x1E: - { - error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E"; - return token_type::parse_error; - } - - case 0x1F: - { - error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F"; - return token_type::parse_error; - } - - // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace)) - case 0x20: - case 0x21: - case 0x23: - case 0x24: - case 0x25: - case 0x26: - case 0x27: - case 0x28: - case 0x29: - case 0x2A: - case 0x2B: - case 0x2C: - case 0x2D: - case 0x2E: - case 0x2F: - case 0x30: - case 0x31: - case 0x32: - case 0x33: - case 0x34: - case 0x35: - case 0x36: - case 0x37: - case 0x38: - case 0x39: - case 0x3A: - case 0x3B: - case 0x3C: - case 0x3D: - case 0x3E: - case 0x3F: - case 0x40: - case 0x41: - case 0x42: - case 0x43: - case 0x44: - case 0x45: - case 0x46: - case 0x47: - case 0x48: - case 0x49: - case 0x4A: - case 0x4B: - case 0x4C: - case 0x4D: - case 0x4E: - case 0x4F: - case 0x50: - case 0x51: - case 0x52: - case 0x53: - case 0x54: - case 0x55: - case 0x56: - case 0x57: - case 0x58: - case 0x59: - case 0x5A: - case 0x5B: - case 0x5D: - case 0x5E: - case 0x5F: - case 0x60: - case 0x61: - case 0x62: - case 0x63: - case 0x64: - case 0x65: - case 0x66: - case 0x67: - case 0x68: - case 0x69: - case 0x6A: - case 0x6B: - case 0x6C: - case 0x6D: - case 0x6E: - case 0x6F: - case 0x70: - case 0x71: - case 0x72: - case 0x73: - case 0x74: - case 0x75: - case 0x76: - case 0x77: - case 0x78: - case 0x79: - case 0x7A: - case 0x7B: - case 0x7C: - case 0x7D: - case 0x7E: - case 0x7F: - { - add(current); - break; - } - - // U+0080..U+07FF: bytes C2..DF 80..BF - case 0xC2: - case 0xC3: - case 0xC4: - case 0xC5: - case 0xC6: - case 0xC7: - case 0xC8: - case 0xC9: - case 0xCA: - case 0xCB: - case 0xCC: - case 0xCD: - case 0xCE: - case 0xCF: - case 0xD0: - case 0xD1: - case 0xD2: - case 0xD3: - case 0xD4: - case 0xD5: - case 0xD6: - case 0xD7: - case 0xD8: - case 0xD9: - case 0xDA: - case 0xDB: - case 0xDC: - case 0xDD: - case 0xDE: - case 0xDF: - { - if (JSON_HEDLEY_UNLIKELY(!next_byte_in_range({0x80, 0xBF}))) - { - return token_type::parse_error; - } - break; - } - - // U+0800..U+0FFF: bytes E0 A0..BF 80..BF - case 0xE0: - { - if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF})))) - { - return token_type::parse_error; - } - break; - } - - // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF - // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF - case 0xE1: - case 0xE2: - case 0xE3: - case 0xE4: - case 0xE5: - case 0xE6: - case 0xE7: - case 0xE8: - case 0xE9: - case 0xEA: - case 0xEB: - case 0xEC: - case 0xEE: - case 0xEF: - { - if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF})))) - { - return token_type::parse_error; - } - break; - } - - // U+D000..U+D7FF: bytes ED 80..9F 80..BF - case 0xED: - { - if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x9F, 0x80, 0xBF})))) - { - return token_type::parse_error; - } - break; - } - - // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF - case 0xF0: - { - if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) - { - return token_type::parse_error; - } - break; - } - - // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF - case 0xF1: - case 0xF2: - case 0xF3: - { - if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) - { - return token_type::parse_error; - } - break; - } - - // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF - case 0xF4: - { - if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF})))) - { - return token_type::parse_error; - } - break; - } - - // remaining bytes (80..C1 and F5..FF) are ill-formed - default: - { - error_message = "invalid string: ill-formed UTF-8 byte"; - return token_type::parse_error; - } - } - } - } - - /*! - * @brief scan a comment - * @return whether comment could be scanned successfully - */ - bool scan_comment() - { - switch (get()) - { - // single-line comments skip input until a newline or EOF is read - case '/': - { - while (true) - { - switch (get()) - { - case '\n': - case '\r': - case std::char_traits::eof(): - case '\0': - return true; - - default: - break; - } - } - } - - // multi-line comments skip input until */ is read - case '*': - { - while (true) - { - switch (get()) - { - case std::char_traits::eof(): - case '\0': - { - error_message = "invalid comment; missing closing '*/'"; - return false; - } - - case '*': - { - switch (get()) - { - case '/': - return true; - - default: - { - unget(); - continue; - } - } - } - - default: - continue; - } - } - } - - // unexpected character after reading '/' - default: - { - error_message = "invalid comment; expecting '/' or '*' after '/'"; - return false; - } - } - } - - JSON_HEDLEY_NON_NULL(2) - static void strtof(float& f, const char* str, char** endptr) noexcept - { - f = std::strtof(str, endptr); - } - - JSON_HEDLEY_NON_NULL(2) - static void strtof(double& f, const char* str, char** endptr) noexcept - { - f = std::strtod(str, endptr); - } - - JSON_HEDLEY_NON_NULL(2) - static void strtof(long double& f, const char* str, char** endptr) noexcept - { - f = std::strtold(str, endptr); - } - - /*! - @brief scan a number literal - - This function scans a string according to Sect. 6 of RFC 8259. - - The function is realized with a deterministic finite state machine derived - from the grammar described in RFC 8259. Starting in state "init", the - input is read and used to determined the next state. Only state "done" - accepts the number. State "error" is a trap state to model errors. In the - table below, "anything" means any character but the ones listed before. - - state | 0 | 1-9 | e E | + | - | . | anything - ---------|----------|----------|----------|---------|---------|----------|----------- - init | zero | any1 | [error] | [error] | minus | [error] | [error] - minus | zero | any1 | [error] | [error] | [error] | [error] | [error] - zero | done | done | exponent | done | done | decimal1 | done - any1 | any1 | any1 | exponent | done | done | decimal1 | done - decimal1 | decimal2 | decimal2 | [error] | [error] | [error] | [error] | [error] - decimal2 | decimal2 | decimal2 | exponent | done | done | done | done - exponent | any2 | any2 | [error] | sign | sign | [error] | [error] - sign | any2 | any2 | [error] | [error] | [error] | [error] | [error] - any2 | any2 | any2 | done | done | done | done | done - - The state machine is realized with one label per state (prefixed with - "scan_number_") and `goto` statements between them. The state machine - contains cycles, but any cycle can be left when EOF is read. Therefore, - the function is guaranteed to terminate. - - During scanning, the read bytes are stored in token_buffer. This string is - then converted to a signed integer, an unsigned integer, or a - floating-point number. - - @return token_type::value_unsigned, token_type::value_integer, or - token_type::value_float if number could be successfully scanned, - token_type::parse_error otherwise - - @note The scanner is independent of the current locale. Internally, the - locale's decimal point is used instead of `.` to work with the - locale-dependent converters. - */ - token_type scan_number() // lgtm [cpp/use-of-goto] - { - // reset token_buffer to store the number's bytes - reset(); - - // the type of the parsed number; initially set to unsigned; will be - // changed if minus sign, decimal point or exponent is read - token_type number_type = token_type::value_unsigned; - - // state (init): we just found out we need to scan a number - switch (current) - { - case '-': - { - add(current); - goto scan_number_minus; - } - - case '0': - { - add(current); - goto scan_number_zero; - } - - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - add(current); - goto scan_number_any1; - } - - // all other characters are rejected outside scan_number() - default: // LCOV_EXCL_LINE - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE - } - -scan_number_minus: - // state: we just parsed a leading minus sign - number_type = token_type::value_integer; - switch (get()) - { - case '0': - { - add(current); - goto scan_number_zero; - } - - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - add(current); - goto scan_number_any1; - } - - default: - { - error_message = "invalid number; expected digit after '-'"; - return token_type::parse_error; - } - } - -scan_number_zero: - // state: we just parse a zero (maybe with a leading minus sign) - switch (get()) - { - case '.': - { - add(decimal_point_char); - goto scan_number_decimal1; - } - - case 'e': - case 'E': - { - add(current); - goto scan_number_exponent; - } - - default: - goto scan_number_done; - } - -scan_number_any1: - // state: we just parsed a number 0-9 (maybe with a leading minus sign) - switch (get()) - { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - add(current); - goto scan_number_any1; - } - - case '.': - { - add(decimal_point_char); - goto scan_number_decimal1; - } - - case 'e': - case 'E': - { - add(current); - goto scan_number_exponent; - } - - default: - goto scan_number_done; - } - -scan_number_decimal1: - // state: we just parsed a decimal point - number_type = token_type::value_float; - switch (get()) - { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - add(current); - goto scan_number_decimal2; - } - - default: - { - error_message = "invalid number; expected digit after '.'"; - return token_type::parse_error; - } - } - -scan_number_decimal2: - // we just parsed at least one number after a decimal point - switch (get()) - { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - add(current); - goto scan_number_decimal2; - } - - case 'e': - case 'E': - { - add(current); - goto scan_number_exponent; - } - - default: - goto scan_number_done; - } - -scan_number_exponent: - // we just parsed an exponent - number_type = token_type::value_float; - switch (get()) - { - case '+': - case '-': - { - add(current); - goto scan_number_sign; - } - - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - add(current); - goto scan_number_any2; - } - - default: - { - error_message = - "invalid number; expected '+', '-', or digit after exponent"; - return token_type::parse_error; - } - } - -scan_number_sign: - // we just parsed an exponent sign - switch (get()) - { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - add(current); - goto scan_number_any2; - } - - default: - { - error_message = "invalid number; expected digit after exponent sign"; - return token_type::parse_error; - } - } - -scan_number_any2: - // we just parsed a number after the exponent or exponent sign - switch (get()) - { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - add(current); - goto scan_number_any2; - } - - default: - goto scan_number_done; - } - -scan_number_done: - // unget the character after the number (we only read it to know that - // we are done scanning a number) - unget(); - - char* endptr = nullptr; // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) - errno = 0; - - // try to parse integers first and fall back to floats - if (number_type == token_type::value_unsigned) - { - const auto x = std::strtoull(token_buffer.data(), &endptr, 10); - - // we checked the number format before - JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); - - if (errno == 0) - { - value_unsigned = static_cast(x); - if (value_unsigned == x) - { - return token_type::value_unsigned; - } - } - } - else if (number_type == token_type::value_integer) - { - const auto x = std::strtoll(token_buffer.data(), &endptr, 10); - - // we checked the number format before - JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); - - if (errno == 0) - { - value_integer = static_cast(x); - if (value_integer == x) - { - return token_type::value_integer; - } - } - } - - // this code is reached if we parse a floating-point number or if an - // integer conversion above failed - strtof(value_float, token_buffer.data(), &endptr); - - // we checked the number format before - JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); - - return token_type::value_float; - } - - /*! - @param[in] literal_text the literal text to expect - @param[in] length the length of the passed literal text - @param[in] return_type the token type to return on success - */ - JSON_HEDLEY_NON_NULL(2) - token_type scan_literal(const char_type* literal_text, const std::size_t length, - token_type return_type) - { - JSON_ASSERT(std::char_traits::to_char_type(current) == literal_text[0]); - for (std::size_t i = 1; i < length; ++i) - { - if (JSON_HEDLEY_UNLIKELY(std::char_traits::to_char_type(get()) != literal_text[i])) - { - error_message = "invalid literal"; - return token_type::parse_error; - } - } - return return_type; - } - - ///////////////////// - // input management - ///////////////////// - - /// reset token_buffer; current character is beginning of token - void reset() noexcept - { - token_buffer.clear(); - token_string.clear(); - token_string.push_back(std::char_traits::to_char_type(current)); - } - - /* - @brief get next character from the input - - This function provides the interface to the used input adapter. It does - not throw in case the input reached EOF, but returns a - `std::char_traits::eof()` in that case. Stores the scanned characters - for use in error messages. - - @return character read from the input - */ - char_int_type get() - { - ++position.chars_read_total; - ++position.chars_read_current_line; - - if (next_unget) - { - // just reset the next_unget variable and work with current - next_unget = false; - } - else - { - current = ia.get_character(); - } - - if (JSON_HEDLEY_LIKELY(current != std::char_traits::eof())) - { - token_string.push_back(std::char_traits::to_char_type(current)); - } - - if (current == '\n') - { - ++position.lines_read; - position.chars_read_current_line = 0; - } - - return current; - } - - /*! - @brief unget current character (read it again on next get) - - We implement unget by setting variable next_unget to true. The input is not - changed - we just simulate ungetting by modifying chars_read_total, - chars_read_current_line, and token_string. The next call to get() will - behave as if the unget character is read again. - */ - void unget() - { - next_unget = true; - - --position.chars_read_total; - - // in case we "unget" a newline, we have to also decrement the lines_read - if (position.chars_read_current_line == 0) - { - if (position.lines_read > 0) - { - --position.lines_read; - } - } - else - { - --position.chars_read_current_line; - } - - if (JSON_HEDLEY_LIKELY(current != std::char_traits::eof())) - { - JSON_ASSERT(!token_string.empty()); - token_string.pop_back(); - } - } - - /// add a character to token_buffer - void add(char_int_type c) - { - token_buffer.push_back(static_cast(c)); - } - - public: - ///////////////////// - // value getters - ///////////////////// - - /// return integer value - constexpr number_integer_t get_number_integer() const noexcept - { - return value_integer; - } - - /// return unsigned integer value - constexpr number_unsigned_t get_number_unsigned() const noexcept - { - return value_unsigned; - } - - /// return floating-point value - constexpr number_float_t get_number_float() const noexcept - { - return value_float; - } - - /// return current string value (implicitly resets the token; useful only once) - string_t& get_string() - { - return token_buffer; - } - - ///////////////////// - // diagnostics - ///////////////////// - - /// return position of last read token - constexpr position_t get_position() const noexcept - { - return position; - } - - /// return the last read token (for errors only). Will never contain EOF - /// (an arbitrary value that is not a valid char value, often -1), because - /// 255 may legitimately occur. May contain NUL, which should be escaped. - std::string get_token_string() const - { - // escape control characters - std::string result; - for (const auto c : token_string) - { - if (static_cast(c) <= '\x1F') - { - // escape control characters - std::array cs{{}}; - static_cast((std::snprintf)(cs.data(), cs.size(), "", static_cast(c))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) - result += cs.data(); - } - else - { - // add character as is - result.push_back(static_cast(c)); - } - } - - return result; - } - - /// return syntax error message - JSON_HEDLEY_RETURNS_NON_NULL - constexpr const char* get_error_message() const noexcept - { - return error_message; - } - - ///////////////////// - // actual scanner - ///////////////////// - - /*! - @brief skip the UTF-8 byte order mark - @return true iff there is no BOM or the correct BOM has been skipped - */ - bool skip_bom() - { - if (get() == 0xEF) - { - // check if we completely parse the BOM - return get() == 0xBB && get() == 0xBF; - } - - // the first character is not the beginning of the BOM; unget it to - // process is later - unget(); - return true; - } - - void skip_whitespace() - { - do - { - get(); - } - while (current == ' ' || current == '\t' || current == '\n' || current == '\r'); - } - - token_type scan() - { - // initially, skip the BOM - if (position.chars_read_total == 0 && !skip_bom()) - { - error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given"; - return token_type::parse_error; - } - - // read next character and ignore whitespace - skip_whitespace(); - - // ignore comments - while (ignore_comments && current == '/') - { - if (!scan_comment()) - { - return token_type::parse_error; - } - - // skip following whitespace - skip_whitespace(); - } - - switch (current) - { - // structural characters - case '[': - return token_type::begin_array; - case ']': - return token_type::end_array; - case '{': - return token_type::begin_object; - case '}': - return token_type::end_object; - case ':': - return token_type::name_separator; - case ',': - return token_type::value_separator; - - // literals - case 't': - { - std::array true_literal = {{static_cast('t'), static_cast('r'), static_cast('u'), static_cast('e')}}; - return scan_literal(true_literal.data(), true_literal.size(), token_type::literal_true); - } - case 'f': - { - std::array false_literal = {{static_cast('f'), static_cast('a'), static_cast('l'), static_cast('s'), static_cast('e')}}; - return scan_literal(false_literal.data(), false_literal.size(), token_type::literal_false); - } - case 'n': - { - std::array null_literal = {{static_cast('n'), static_cast('u'), static_cast('l'), static_cast('l')}}; - return scan_literal(null_literal.data(), null_literal.size(), token_type::literal_null); - } - - // string - case '\"': - return scan_string(); - - // number - case '-': - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - return scan_number(); - - // end of input (the null byte is needed when parsing from - // string literals) - case '\0': - case std::char_traits::eof(): - return token_type::end_of_input; - - // error - default: - error_message = "invalid literal"; - return token_type::parse_error; - } - } - - private: - /// input adapter - InputAdapterType ia; - - /// whether comments should be ignored (true) or signaled as errors (false) - const bool ignore_comments = false; - - /// the current character - char_int_type current = std::char_traits::eof(); - - /// whether the next get() call should just return current - bool next_unget = false; - - /// the start position of the current token - position_t position {}; - - /// raw input token string (for error messages) - std::vector token_string {}; - - /// buffer for variable-length tokens (numbers, strings) - string_t token_buffer {}; - - /// a description of occurred lexer errors - const char* error_message = ""; - - // number values - number_integer_t value_integer = 0; - number_unsigned_t value_unsigned = 0; - number_float_t value_float = 0; - - /// the decimal point - const char_int_type decimal_point_char = '.'; -}; -} // namespace detail -} // namespace nlohmann - -// #include - -// #include - - -#include // size_t -#include // declval -#include // string - -// #include - -// #include - - -namespace nlohmann -{ -namespace detail -{ -template -using null_function_t = decltype(std::declval().null()); - -template -using boolean_function_t = - decltype(std::declval().boolean(std::declval())); - -template -using number_integer_function_t = - decltype(std::declval().number_integer(std::declval())); - -template -using number_unsigned_function_t = - decltype(std::declval().number_unsigned(std::declval())); - -template -using number_float_function_t = decltype(std::declval().number_float( - std::declval(), std::declval())); - -template -using string_function_t = - decltype(std::declval().string(std::declval())); - -template -using binary_function_t = - decltype(std::declval().binary(std::declval())); - -template -using start_object_function_t = - decltype(std::declval().start_object(std::declval())); - -template -using key_function_t = - decltype(std::declval().key(std::declval())); - -template -using end_object_function_t = decltype(std::declval().end_object()); - -template -using start_array_function_t = - decltype(std::declval().start_array(std::declval())); - -template -using end_array_function_t = decltype(std::declval().end_array()); - -template -using parse_error_function_t = decltype(std::declval().parse_error( - std::declval(), std::declval(), - std::declval())); - -template -struct is_sax -{ - private: - static_assert(is_basic_json::value, - "BasicJsonType must be of type basic_json<...>"); - - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - using string_t = typename BasicJsonType::string_t; - using binary_t = typename BasicJsonType::binary_t; - using exception_t = typename BasicJsonType::exception; - - public: - static constexpr bool value = - is_detected_exact::value && - is_detected_exact::value && - is_detected_exact::value && - is_detected_exact::value && - is_detected_exact::value && - is_detected_exact::value && - is_detected_exact::value && - is_detected_exact::value && - is_detected_exact::value && - is_detected_exact::value && - is_detected_exact::value && - is_detected_exact::value && - is_detected_exact::value; -}; - -template -struct is_sax_static_asserts -{ - private: - static_assert(is_basic_json::value, - "BasicJsonType must be of type basic_json<...>"); - - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - using string_t = typename BasicJsonType::string_t; - using binary_t = typename BasicJsonType::binary_t; - using exception_t = typename BasicJsonType::exception; - - public: - static_assert(is_detected_exact::value, - "Missing/invalid function: bool null()"); - static_assert(is_detected_exact::value, - "Missing/invalid function: bool boolean(bool)"); - static_assert(is_detected_exact::value, - "Missing/invalid function: bool boolean(bool)"); - static_assert( - is_detected_exact::value, - "Missing/invalid function: bool number_integer(number_integer_t)"); - static_assert( - is_detected_exact::value, - "Missing/invalid function: bool number_unsigned(number_unsigned_t)"); - static_assert(is_detected_exact::value, - "Missing/invalid function: bool number_float(number_float_t, const string_t&)"); - static_assert( - is_detected_exact::value, - "Missing/invalid function: bool string(string_t&)"); - static_assert( - is_detected_exact::value, - "Missing/invalid function: bool binary(binary_t&)"); - static_assert(is_detected_exact::value, - "Missing/invalid function: bool start_object(std::size_t)"); - static_assert(is_detected_exact::value, - "Missing/invalid function: bool key(string_t&)"); - static_assert(is_detected_exact::value, - "Missing/invalid function: bool end_object()"); - static_assert(is_detected_exact::value, - "Missing/invalid function: bool start_array(std::size_t)"); - static_assert(is_detected_exact::value, - "Missing/invalid function: bool end_array()"); - static_assert( - is_detected_exact::value, - "Missing/invalid function: bool parse_error(std::size_t, const " - "std::string&, const exception&)"); -}; -} // namespace detail -} // namespace nlohmann - -// #include - -// #include - - -namespace nlohmann -{ -namespace detail -{ - -/// how to treat CBOR tags -enum class cbor_tag_handler_t -{ - error, ///< throw a parse_error exception in case of a tag - ignore, ///< ignore tags - store ///< store tags as binary type -}; - -/*! -@brief determine system byte order - -@return true if and only if system's byte order is little endian - -@note from https://stackoverflow.com/a/1001328/266378 -*/ -static inline bool little_endianness(int num = 1) noexcept -{ - return *reinterpret_cast(&num) == 1; -} - - -/////////////////// -// binary reader // -/////////////////// - -/*! -@brief deserialization of CBOR, MessagePack, and UBJSON values -*/ -template> -class binary_reader -{ - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - using string_t = typename BasicJsonType::string_t; - using binary_t = typename BasicJsonType::binary_t; - using json_sax_t = SAX; - using char_type = typename InputAdapterType::char_type; - using char_int_type = typename std::char_traits::int_type; - - public: - /*! - @brief create a binary reader - - @param[in] adapter input adapter to read from - */ - explicit binary_reader(InputAdapterType&& adapter) noexcept : ia(std::move(adapter)) - { - (void)detail::is_sax_static_asserts {}; - } - - // make class move-only - binary_reader(const binary_reader&) = delete; - binary_reader(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) - binary_reader& operator=(const binary_reader&) = delete; - binary_reader& operator=(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) - ~binary_reader() = default; - - /*! - @param[in] format the binary format to parse - @param[in] sax_ a SAX event processor - @param[in] strict whether to expect the input to be consumed completed - @param[in] tag_handler how to treat CBOR tags - - @return whether parsing was successful - */ - JSON_HEDLEY_NON_NULL(3) - bool sax_parse(const input_format_t format, - json_sax_t* sax_, - const bool strict = true, - const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) - { - sax = sax_; - bool result = false; - - switch (format) - { - case input_format_t::bson: - result = parse_bson_internal(); - break; - - case input_format_t::cbor: - result = parse_cbor_internal(true, tag_handler); - break; - - case input_format_t::msgpack: - result = parse_msgpack_internal(); - break; - - case input_format_t::ubjson: - result = parse_ubjson_internal(); - break; - - case input_format_t::json: // LCOV_EXCL_LINE - default: // LCOV_EXCL_LINE - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE - } - - // strict mode: next byte must be EOF - if (result && strict) - { - if (format == input_format_t::ubjson) - { - get_ignore_noop(); - } - else - { - get(); - } - - if (JSON_HEDLEY_UNLIKELY(current != std::char_traits::eof())) - { - return sax->parse_error(chars_read, get_token_string(), - parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value"), BasicJsonType())); - } - } - - return result; - } - - private: - ////////// - // BSON // - ////////// - - /*! - @brief Reads in a BSON-object and passes it to the SAX-parser. - @return whether a valid BSON-value was passed to the SAX parser - */ - bool parse_bson_internal() - { - std::int32_t document_size{}; - get_number(input_format_t::bson, document_size); - - if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast(-1)))) - { - return false; - } - - if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/false))) - { - return false; - } - - return sax->end_object(); - } - - /*! - @brief Parses a C-style string from the BSON input. - @param[in,out] result A reference to the string variable where the read - string is to be stored. - @return `true` if the \x00-byte indicating the end of the string was - encountered before the EOF; false` indicates an unexpected EOF. - */ - bool get_bson_cstr(string_t& result) - { - auto out = std::back_inserter(result); - while (true) - { - get(); - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "cstring"))) - { - return false; - } - if (current == 0x00) - { - return true; - } - *out++ = static_cast(current); - } - } - - /*! - @brief Parses a zero-terminated string of length @a len from the BSON - input. - @param[in] len The length (including the zero-byte at the end) of the - string to be read. - @param[in,out] result A reference to the string variable where the read - string is to be stored. - @tparam NumberType The type of the length @a len - @pre len >= 1 - @return `true` if the string was successfully parsed - */ - template - bool get_bson_string(const NumberType len, string_t& result) - { - if (JSON_HEDLEY_UNLIKELY(len < 1)) - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "string length must be at least 1, is " + std::to_string(len), "string"), BasicJsonType())); - } - - return get_string(input_format_t::bson, len - static_cast(1), result) && get() != std::char_traits::eof(); - } - - /*! - @brief Parses a byte array input of length @a len from the BSON input. - @param[in] len The length of the byte array to be read. - @param[in,out] result A reference to the binary variable where the read - array is to be stored. - @tparam NumberType The type of the length @a len - @pre len >= 0 - @return `true` if the byte array was successfully parsed - */ - template - bool get_bson_binary(const NumberType len, binary_t& result) - { - if (JSON_HEDLEY_UNLIKELY(len < 0)) - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "byte array length cannot be negative, is " + std::to_string(len), "binary"), BasicJsonType())); - } - - // All BSON binary values have a subtype - std::uint8_t subtype{}; - get_number(input_format_t::bson, subtype); - result.set_subtype(subtype); - - return get_binary(input_format_t::bson, len, result); - } - - /*! - @brief Read a BSON document element of the given @a element_type. - @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html - @param[in] element_type_parse_position The position in the input stream, - where the `element_type` was read. - @warning Not all BSON element types are supported yet. An unsupported - @a element_type will give rise to a parse_error.114: - Unsupported BSON record type 0x... - @return whether a valid BSON-object/array was passed to the SAX parser - */ - bool parse_bson_element_internal(const char_int_type element_type, - const std::size_t element_type_parse_position) - { - switch (element_type) - { - case 0x01: // double - { - double number{}; - return get_number(input_format_t::bson, number) && sax->number_float(static_cast(number), ""); - } - - case 0x02: // string - { - std::int32_t len{}; - string_t value; - return get_number(input_format_t::bson, len) && get_bson_string(len, value) && sax->string(value); - } - - case 0x03: // object - { - return parse_bson_internal(); - } - - case 0x04: // array - { - return parse_bson_array(); - } - - case 0x05: // binary - { - std::int32_t len{}; - binary_t value; - return get_number(input_format_t::bson, len) && get_bson_binary(len, value) && sax->binary(value); - } - - case 0x08: // boolean - { - return sax->boolean(get() != 0); - } - - case 0x0A: // null - { - return sax->null(); - } - - case 0x10: // int32 - { - std::int32_t value{}; - return get_number(input_format_t::bson, value) && sax->number_integer(value); - } - - case 0x12: // int64 - { - std::int64_t value{}; - return get_number(input_format_t::bson, value) && sax->number_integer(value); - } - - default: // anything else not supported (yet) - { - std::array cr{{}}; - static_cast((std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast(element_type))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) - return sax->parse_error(element_type_parse_position, std::string(cr.data()), parse_error::create(114, element_type_parse_position, "Unsupported BSON record type 0x" + std::string(cr.data()), BasicJsonType())); - } - } - } - - /*! - @brief Read a BSON element list (as specified in the BSON-spec) - - The same binary layout is used for objects and arrays, hence it must be - indicated with the argument @a is_array which one is expected - (true --> array, false --> object). - - @param[in] is_array Determines if the element list being read is to be - treated as an object (@a is_array == false), or as an - array (@a is_array == true). - @return whether a valid BSON-object/array was passed to the SAX parser - */ - bool parse_bson_element_list(const bool is_array) - { - string_t key; - - while (auto element_type = get()) - { - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "element list"))) - { - return false; - } - - const std::size_t element_type_parse_position = chars_read; - if (JSON_HEDLEY_UNLIKELY(!get_bson_cstr(key))) - { - return false; - } - - if (!is_array && !sax->key(key)) - { - return false; - } - - if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_internal(element_type, element_type_parse_position))) - { - return false; - } - - // get_bson_cstr only appends - key.clear(); - } - - return true; - } - - /*! - @brief Reads an array from the BSON input and passes it to the SAX-parser. - @return whether a valid BSON-array was passed to the SAX parser - */ - bool parse_bson_array() - { - std::int32_t document_size{}; - get_number(input_format_t::bson, document_size); - - if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast(-1)))) - { - return false; - } - - if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/true))) - { - return false; - } - - return sax->end_array(); - } - - ////////// - // CBOR // - ////////// - - /*! - @param[in] get_char whether a new character should be retrieved from the - input (true) or whether the last read character should - be considered instead (false) - @param[in] tag_handler how CBOR tags should be treated - - @return whether a valid CBOR value was passed to the SAX parser - */ - bool parse_cbor_internal(const bool get_char, - const cbor_tag_handler_t tag_handler) - { - switch (get_char ? get() : current) - { - // EOF - case std::char_traits::eof(): - return unexpect_eof(input_format_t::cbor, "value"); - - // Integer 0x00..0x17 (0..23) - case 0x00: - case 0x01: - case 0x02: - case 0x03: - case 0x04: - case 0x05: - case 0x06: - case 0x07: - case 0x08: - case 0x09: - case 0x0A: - case 0x0B: - case 0x0C: - case 0x0D: - case 0x0E: - case 0x0F: - case 0x10: - case 0x11: - case 0x12: - case 0x13: - case 0x14: - case 0x15: - case 0x16: - case 0x17: - return sax->number_unsigned(static_cast(current)); - - case 0x18: // Unsigned integer (one-byte uint8_t follows) - { - std::uint8_t number{}; - return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); - } - - case 0x19: // Unsigned integer (two-byte uint16_t follows) - { - std::uint16_t number{}; - return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); - } - - case 0x1A: // Unsigned integer (four-byte uint32_t follows) - { - std::uint32_t number{}; - return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); - } - - case 0x1B: // Unsigned integer (eight-byte uint64_t follows) - { - std::uint64_t number{}; - return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); - } - - // Negative integer -1-0x00..-1-0x17 (-1..-24) - case 0x20: - case 0x21: - case 0x22: - case 0x23: - case 0x24: - case 0x25: - case 0x26: - case 0x27: - case 0x28: - case 0x29: - case 0x2A: - case 0x2B: - case 0x2C: - case 0x2D: - case 0x2E: - case 0x2F: - case 0x30: - case 0x31: - case 0x32: - case 0x33: - case 0x34: - case 0x35: - case 0x36: - case 0x37: - return sax->number_integer(static_cast(0x20 - 1 - current)); - - case 0x38: // Negative integer (one-byte uint8_t follows) - { - std::uint8_t number{}; - return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); - } - - case 0x39: // Negative integer -1-n (two-byte uint16_t follows) - { - std::uint16_t number{}; - return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); - } - - case 0x3A: // Negative integer -1-n (four-byte uint32_t follows) - { - std::uint32_t number{}; - return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); - } - - case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows) - { - std::uint64_t number{}; - return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - - static_cast(number)); - } - - // Binary data (0x00..0x17 bytes follow) - case 0x40: - case 0x41: - case 0x42: - case 0x43: - case 0x44: - case 0x45: - case 0x46: - case 0x47: - case 0x48: - case 0x49: - case 0x4A: - case 0x4B: - case 0x4C: - case 0x4D: - case 0x4E: - case 0x4F: - case 0x50: - case 0x51: - case 0x52: - case 0x53: - case 0x54: - case 0x55: - case 0x56: - case 0x57: - case 0x58: // Binary data (one-byte uint8_t for n follows) - case 0x59: // Binary data (two-byte uint16_t for n follow) - case 0x5A: // Binary data (four-byte uint32_t for n follow) - case 0x5B: // Binary data (eight-byte uint64_t for n follow) - case 0x5F: // Binary data (indefinite length) - { - binary_t b; - return get_cbor_binary(b) && sax->binary(b); - } - - // UTF-8 string (0x00..0x17 bytes follow) - case 0x60: - case 0x61: - case 0x62: - case 0x63: - case 0x64: - case 0x65: - case 0x66: - case 0x67: - case 0x68: - case 0x69: - case 0x6A: - case 0x6B: - case 0x6C: - case 0x6D: - case 0x6E: - case 0x6F: - case 0x70: - case 0x71: - case 0x72: - case 0x73: - case 0x74: - case 0x75: - case 0x76: - case 0x77: - case 0x78: // UTF-8 string (one-byte uint8_t for n follows) - case 0x79: // UTF-8 string (two-byte uint16_t for n follow) - case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) - case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) - case 0x7F: // UTF-8 string (indefinite length) - { - string_t s; - return get_cbor_string(s) && sax->string(s); - } - - // array (0x00..0x17 data items follow) - case 0x80: - case 0x81: - case 0x82: - case 0x83: - case 0x84: - case 0x85: - case 0x86: - case 0x87: - case 0x88: - case 0x89: - case 0x8A: - case 0x8B: - case 0x8C: - case 0x8D: - case 0x8E: - case 0x8F: - case 0x90: - case 0x91: - case 0x92: - case 0x93: - case 0x94: - case 0x95: - case 0x96: - case 0x97: - return get_cbor_array(static_cast(static_cast(current) & 0x1Fu), tag_handler); - - case 0x98: // array (one-byte uint8_t for n follows) - { - std::uint8_t len{}; - return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); - } - - case 0x99: // array (two-byte uint16_t for n follow) - { - std::uint16_t len{}; - return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); - } - - case 0x9A: // array (four-byte uint32_t for n follow) - { - std::uint32_t len{}; - return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); - } - - case 0x9B: // array (eight-byte uint64_t for n follow) - { - std::uint64_t len{}; - return get_number(input_format_t::cbor, len) && get_cbor_array(detail::conditional_static_cast(len), tag_handler); - } - - case 0x9F: // array (indefinite length) - return get_cbor_array(static_cast(-1), tag_handler); - - // map (0x00..0x17 pairs of data items follow) - case 0xA0: - case 0xA1: - case 0xA2: - case 0xA3: - case 0xA4: - case 0xA5: - case 0xA6: - case 0xA7: - case 0xA8: - case 0xA9: - case 0xAA: - case 0xAB: - case 0xAC: - case 0xAD: - case 0xAE: - case 0xAF: - case 0xB0: - case 0xB1: - case 0xB2: - case 0xB3: - case 0xB4: - case 0xB5: - case 0xB6: - case 0xB7: - return get_cbor_object(static_cast(static_cast(current) & 0x1Fu), tag_handler); - - case 0xB8: // map (one-byte uint8_t for n follows) - { - std::uint8_t len{}; - return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); - } - - case 0xB9: // map (two-byte uint16_t for n follow) - { - std::uint16_t len{}; - return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); - } - - case 0xBA: // map (four-byte uint32_t for n follow) - { - std::uint32_t len{}; - return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); - } - - case 0xBB: // map (eight-byte uint64_t for n follow) - { - std::uint64_t len{}; - return get_number(input_format_t::cbor, len) && get_cbor_object(detail::conditional_static_cast(len), tag_handler); - } - - case 0xBF: // map (indefinite length) - return get_cbor_object(static_cast(-1), tag_handler); - - case 0xC6: // tagged item - case 0xC7: - case 0xC8: - case 0xC9: - case 0xCA: - case 0xCB: - case 0xCC: - case 0xCD: - case 0xCE: - case 0xCF: - case 0xD0: - case 0xD1: - case 0xD2: - case 0xD3: - case 0xD4: - case 0xD8: // tagged item (1 bytes follow) - case 0xD9: // tagged item (2 bytes follow) - case 0xDA: // tagged item (4 bytes follow) - case 0xDB: // tagged item (8 bytes follow) - { - switch (tag_handler) - { - case cbor_tag_handler_t::error: - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); - } - - case cbor_tag_handler_t::ignore: - { - // ignore binary subtype - switch (current) - { - case 0xD8: - { - std::uint8_t subtype_to_ignore{}; - get_number(input_format_t::cbor, subtype_to_ignore); - break; - } - case 0xD9: - { - std::uint16_t subtype_to_ignore{}; - get_number(input_format_t::cbor, subtype_to_ignore); - break; - } - case 0xDA: - { - std::uint32_t subtype_to_ignore{}; - get_number(input_format_t::cbor, subtype_to_ignore); - break; - } - case 0xDB: - { - std::uint64_t subtype_to_ignore{}; - get_number(input_format_t::cbor, subtype_to_ignore); - break; - } - default: - break; - } - return parse_cbor_internal(true, tag_handler); - } - - case cbor_tag_handler_t::store: - { - binary_t b; - // use binary subtype and store in binary container - switch (current) - { - case 0xD8: - { - std::uint8_t subtype{}; - get_number(input_format_t::cbor, subtype); - b.set_subtype(detail::conditional_static_cast(subtype)); - break; - } - case 0xD9: - { - std::uint16_t subtype{}; - get_number(input_format_t::cbor, subtype); - b.set_subtype(detail::conditional_static_cast(subtype)); - break; - } - case 0xDA: - { - std::uint32_t subtype{}; - get_number(input_format_t::cbor, subtype); - b.set_subtype(detail::conditional_static_cast(subtype)); - break; - } - case 0xDB: - { - std::uint64_t subtype{}; - get_number(input_format_t::cbor, subtype); - b.set_subtype(detail::conditional_static_cast(subtype)); - break; - } - default: - return parse_cbor_internal(true, tag_handler); - } - get(); - return get_cbor_binary(b) && sax->binary(b); - } - - default: // LCOV_EXCL_LINE - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE - return false; // LCOV_EXCL_LINE - } - } - - case 0xF4: // false - return sax->boolean(false); - - case 0xF5: // true - return sax->boolean(true); - - case 0xF6: // null - return sax->null(); - - case 0xF9: // Half-Precision Float (two-byte IEEE 754) - { - const auto byte1_raw = get(); - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number"))) - { - return false; - } - const auto byte2_raw = get(); - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number"))) - { - return false; - } - - const auto byte1 = static_cast(byte1_raw); - const auto byte2 = static_cast(byte2_raw); - - // code from RFC 7049, Appendix D, Figure 3: - // As half-precision floating-point numbers were only added - // to IEEE 754 in 2008, today's programming platforms often - // still only have limited support for them. It is very - // easy to include at least decoding support for them even - // without such support. An example of a small decoder for - // half-precision floating-point numbers in the C language - // is shown in Fig. 3. - const auto half = static_cast((byte1 << 8u) + byte2); - const double val = [&half] - { - const int exp = (half >> 10u) & 0x1Fu; - const unsigned int mant = half & 0x3FFu; - JSON_ASSERT(0 <= exp&& exp <= 32); - JSON_ASSERT(mant <= 1024); - switch (exp) - { - case 0: - return std::ldexp(mant, -24); - case 31: - return (mant == 0) - ? std::numeric_limits::infinity() - : std::numeric_limits::quiet_NaN(); - default: - return std::ldexp(mant + 1024, exp - 25); - } - }(); - return sax->number_float((half & 0x8000u) != 0 - ? static_cast(-val) - : static_cast(val), ""); - } - - case 0xFA: // Single-Precision Float (four-byte IEEE 754) - { - float number{}; - return get_number(input_format_t::cbor, number) && sax->number_float(static_cast(number), ""); - } - - case 0xFB: // Double-Precision Float (eight-byte IEEE 754) - { - double number{}; - return get_number(input_format_t::cbor, number) && sax->number_float(static_cast(number), ""); - } - - default: // anything else (0xFF is handled inside the other types) - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); - } - } - } - - /*! - @brief reads a CBOR string - - This function first reads starting bytes to determine the expected - string length and then copies this number of bytes into a string. - Additionally, CBOR's strings with indefinite lengths are supported. - - @param[out] result created string - - @return whether string creation completed - */ - bool get_cbor_string(string_t& result) - { - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "string"))) - { - return false; - } - - switch (current) - { - // UTF-8 string (0x00..0x17 bytes follow) - case 0x60: - case 0x61: - case 0x62: - case 0x63: - case 0x64: - case 0x65: - case 0x66: - case 0x67: - case 0x68: - case 0x69: - case 0x6A: - case 0x6B: - case 0x6C: - case 0x6D: - case 0x6E: - case 0x6F: - case 0x70: - case 0x71: - case 0x72: - case 0x73: - case 0x74: - case 0x75: - case 0x76: - case 0x77: - { - return get_string(input_format_t::cbor, static_cast(current) & 0x1Fu, result); - } - - case 0x78: // UTF-8 string (one-byte uint8_t for n follows) - { - std::uint8_t len{}; - return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); - } - - case 0x79: // UTF-8 string (two-byte uint16_t for n follow) - { - std::uint16_t len{}; - return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); - } - - case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) - { - std::uint32_t len{}; - return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); - } - - case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) - { - std::uint64_t len{}; - return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); - } - - case 0x7F: // UTF-8 string (indefinite length) - { - while (get() != 0xFF) - { - string_t chunk; - if (!get_cbor_string(chunk)) - { - return false; - } - result.append(chunk); - } - return true; - } - - default: - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0x" + last_token, "string"), BasicJsonType())); - } - } - } - - /*! - @brief reads a CBOR byte array - - This function first reads starting bytes to determine the expected - byte array length and then copies this number of bytes into the byte array. - Additionally, CBOR's byte arrays with indefinite lengths are supported. - - @param[out] result created byte array - - @return whether byte array creation completed - */ - bool get_cbor_binary(binary_t& result) - { - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "binary"))) - { - return false; - } - - switch (current) - { - // Binary data (0x00..0x17 bytes follow) - case 0x40: - case 0x41: - case 0x42: - case 0x43: - case 0x44: - case 0x45: - case 0x46: - case 0x47: - case 0x48: - case 0x49: - case 0x4A: - case 0x4B: - case 0x4C: - case 0x4D: - case 0x4E: - case 0x4F: - case 0x50: - case 0x51: - case 0x52: - case 0x53: - case 0x54: - case 0x55: - case 0x56: - case 0x57: - { - return get_binary(input_format_t::cbor, static_cast(current) & 0x1Fu, result); - } - - case 0x58: // Binary data (one-byte uint8_t for n follows) - { - std::uint8_t len{}; - return get_number(input_format_t::cbor, len) && - get_binary(input_format_t::cbor, len, result); - } - - case 0x59: // Binary data (two-byte uint16_t for n follow) - { - std::uint16_t len{}; - return get_number(input_format_t::cbor, len) && - get_binary(input_format_t::cbor, len, result); - } - - case 0x5A: // Binary data (four-byte uint32_t for n follow) - { - std::uint32_t len{}; - return get_number(input_format_t::cbor, len) && - get_binary(input_format_t::cbor, len, result); - } - - case 0x5B: // Binary data (eight-byte uint64_t for n follow) - { - std::uint64_t len{}; - return get_number(input_format_t::cbor, len) && - get_binary(input_format_t::cbor, len, result); - } - - case 0x5F: // Binary data (indefinite length) - { - while (get() != 0xFF) - { - binary_t chunk; - if (!get_cbor_binary(chunk)) - { - return false; - } - result.insert(result.end(), chunk.begin(), chunk.end()); - } - return true; - } - - default: - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x40-0x5B) or indefinite binary array type (0x5F); last byte: 0x" + last_token, "binary"), BasicJsonType())); - } - } - } - - /*! - @param[in] len the length of the array or static_cast(-1) for an - array of indefinite size - @param[in] tag_handler how CBOR tags should be treated - @return whether array creation completed - */ - bool get_cbor_array(const std::size_t len, - const cbor_tag_handler_t tag_handler) - { - if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len))) - { - return false; - } - - if (len != static_cast(-1)) - { - for (std::size_t i = 0; i < len; ++i) - { - if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) - { - return false; - } - } - } - else - { - while (get() != 0xFF) - { - if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(false, tag_handler))) - { - return false; - } - } - } - - return sax->end_array(); - } - - /*! - @param[in] len the length of the object or static_cast(-1) for an - object of indefinite size - @param[in] tag_handler how CBOR tags should be treated - @return whether object creation completed - */ - bool get_cbor_object(const std::size_t len, - const cbor_tag_handler_t tag_handler) - { - if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len))) - { - return false; - } - - if (len != 0) - { - string_t key; - if (len != static_cast(-1)) - { - for (std::size_t i = 0; i < len; ++i) - { - get(); - if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key))) - { - return false; - } - - if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) - { - return false; - } - key.clear(); - } - } - else - { - while (get() != 0xFF) - { - if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key))) - { - return false; - } - - if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) - { - return false; - } - key.clear(); - } - } - } - - return sax->end_object(); - } - - ///////////// - // MsgPack // - ///////////// - - /*! - @return whether a valid MessagePack value was passed to the SAX parser - */ - bool parse_msgpack_internal() - { - switch (get()) - { - // EOF - case std::char_traits::eof(): - return unexpect_eof(input_format_t::msgpack, "value"); - - // positive fixint - case 0x00: - case 0x01: - case 0x02: - case 0x03: - case 0x04: - case 0x05: - case 0x06: - case 0x07: - case 0x08: - case 0x09: - case 0x0A: - case 0x0B: - case 0x0C: - case 0x0D: - case 0x0E: - case 0x0F: - case 0x10: - case 0x11: - case 0x12: - case 0x13: - case 0x14: - case 0x15: - case 0x16: - case 0x17: - case 0x18: - case 0x19: - case 0x1A: - case 0x1B: - case 0x1C: - case 0x1D: - case 0x1E: - case 0x1F: - case 0x20: - case 0x21: - case 0x22: - case 0x23: - case 0x24: - case 0x25: - case 0x26: - case 0x27: - case 0x28: - case 0x29: - case 0x2A: - case 0x2B: - case 0x2C: - case 0x2D: - case 0x2E: - case 0x2F: - case 0x30: - case 0x31: - case 0x32: - case 0x33: - case 0x34: - case 0x35: - case 0x36: - case 0x37: - case 0x38: - case 0x39: - case 0x3A: - case 0x3B: - case 0x3C: - case 0x3D: - case 0x3E: - case 0x3F: - case 0x40: - case 0x41: - case 0x42: - case 0x43: - case 0x44: - case 0x45: - case 0x46: - case 0x47: - case 0x48: - case 0x49: - case 0x4A: - case 0x4B: - case 0x4C: - case 0x4D: - case 0x4E: - case 0x4F: - case 0x50: - case 0x51: - case 0x52: - case 0x53: - case 0x54: - case 0x55: - case 0x56: - case 0x57: - case 0x58: - case 0x59: - case 0x5A: - case 0x5B: - case 0x5C: - case 0x5D: - case 0x5E: - case 0x5F: - case 0x60: - case 0x61: - case 0x62: - case 0x63: - case 0x64: - case 0x65: - case 0x66: - case 0x67: - case 0x68: - case 0x69: - case 0x6A: - case 0x6B: - case 0x6C: - case 0x6D: - case 0x6E: - case 0x6F: - case 0x70: - case 0x71: - case 0x72: - case 0x73: - case 0x74: - case 0x75: - case 0x76: - case 0x77: - case 0x78: - case 0x79: - case 0x7A: - case 0x7B: - case 0x7C: - case 0x7D: - case 0x7E: - case 0x7F: - return sax->number_unsigned(static_cast(current)); - - // fixmap - case 0x80: - case 0x81: - case 0x82: - case 0x83: - case 0x84: - case 0x85: - case 0x86: - case 0x87: - case 0x88: - case 0x89: - case 0x8A: - case 0x8B: - case 0x8C: - case 0x8D: - case 0x8E: - case 0x8F: - return get_msgpack_object(static_cast(static_cast(current) & 0x0Fu)); - - // fixarray - case 0x90: - case 0x91: - case 0x92: - case 0x93: - case 0x94: - case 0x95: - case 0x96: - case 0x97: - case 0x98: - case 0x99: - case 0x9A: - case 0x9B: - case 0x9C: - case 0x9D: - case 0x9E: - case 0x9F: - return get_msgpack_array(static_cast(static_cast(current) & 0x0Fu)); - - // fixstr - case 0xA0: - case 0xA1: - case 0xA2: - case 0xA3: - case 0xA4: - case 0xA5: - case 0xA6: - case 0xA7: - case 0xA8: - case 0xA9: - case 0xAA: - case 0xAB: - case 0xAC: - case 0xAD: - case 0xAE: - case 0xAF: - case 0xB0: - case 0xB1: - case 0xB2: - case 0xB3: - case 0xB4: - case 0xB5: - case 0xB6: - case 0xB7: - case 0xB8: - case 0xB9: - case 0xBA: - case 0xBB: - case 0xBC: - case 0xBD: - case 0xBE: - case 0xBF: - case 0xD9: // str 8 - case 0xDA: // str 16 - case 0xDB: // str 32 - { - string_t s; - return get_msgpack_string(s) && sax->string(s); - } - - case 0xC0: // nil - return sax->null(); - - case 0xC2: // false - return sax->boolean(false); - - case 0xC3: // true - return sax->boolean(true); - - case 0xC4: // bin 8 - case 0xC5: // bin 16 - case 0xC6: // bin 32 - case 0xC7: // ext 8 - case 0xC8: // ext 16 - case 0xC9: // ext 32 - case 0xD4: // fixext 1 - case 0xD5: // fixext 2 - case 0xD6: // fixext 4 - case 0xD7: // fixext 8 - case 0xD8: // fixext 16 - { - binary_t b; - return get_msgpack_binary(b) && sax->binary(b); - } - - case 0xCA: // float 32 - { - float number{}; - return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast(number), ""); - } - - case 0xCB: // float 64 - { - double number{}; - return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast(number), ""); - } - - case 0xCC: // uint 8 - { - std::uint8_t number{}; - return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); - } - - case 0xCD: // uint 16 - { - std::uint16_t number{}; - return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); - } - - case 0xCE: // uint 32 - { - std::uint32_t number{}; - return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); - } - - case 0xCF: // uint 64 - { - std::uint64_t number{}; - return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); - } - - case 0xD0: // int 8 - { - std::int8_t number{}; - return get_number(input_format_t::msgpack, number) && sax->number_integer(number); - } - - case 0xD1: // int 16 - { - std::int16_t number{}; - return get_number(input_format_t::msgpack, number) && sax->number_integer(number); - } - - case 0xD2: // int 32 - { - std::int32_t number{}; - return get_number(input_format_t::msgpack, number) && sax->number_integer(number); - } - - case 0xD3: // int 64 - { - std::int64_t number{}; - return get_number(input_format_t::msgpack, number) && sax->number_integer(number); - } - - case 0xDC: // array 16 - { - std::uint16_t len{}; - return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast(len)); - } - - case 0xDD: // array 32 - { - std::uint32_t len{}; - return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast(len)); - } - - case 0xDE: // map 16 - { - std::uint16_t len{}; - return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast(len)); - } - - case 0xDF: // map 32 - { - std::uint32_t len{}; - return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast(len)); - } - - // negative fixint - case 0xE0: - case 0xE1: - case 0xE2: - case 0xE3: - case 0xE4: - case 0xE5: - case 0xE6: - case 0xE7: - case 0xE8: - case 0xE9: - case 0xEA: - case 0xEB: - case 0xEC: - case 0xED: - case 0xEE: - case 0xEF: - case 0xF0: - case 0xF1: - case 0xF2: - case 0xF3: - case 0xF4: - case 0xF5: - case 0xF6: - case 0xF7: - case 0xF8: - case 0xF9: - case 0xFA: - case 0xFB: - case 0xFC: - case 0xFD: - case 0xFE: - case 0xFF: - return sax->number_integer(static_cast(current)); - - default: // anything else - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::msgpack, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); - } - } - } - - /*! - @brief reads a MessagePack string - - This function first reads starting bytes to determine the expected - string length and then copies this number of bytes into a string. - - @param[out] result created string - - @return whether string creation completed - */ - bool get_msgpack_string(string_t& result) - { - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::msgpack, "string"))) - { - return false; - } - - switch (current) - { - // fixstr - case 0xA0: - case 0xA1: - case 0xA2: - case 0xA3: - case 0xA4: - case 0xA5: - case 0xA6: - case 0xA7: - case 0xA8: - case 0xA9: - case 0xAA: - case 0xAB: - case 0xAC: - case 0xAD: - case 0xAE: - case 0xAF: - case 0xB0: - case 0xB1: - case 0xB2: - case 0xB3: - case 0xB4: - case 0xB5: - case 0xB6: - case 0xB7: - case 0xB8: - case 0xB9: - case 0xBA: - case 0xBB: - case 0xBC: - case 0xBD: - case 0xBE: - case 0xBF: - { - return get_string(input_format_t::msgpack, static_cast(current) & 0x1Fu, result); - } - - case 0xD9: // str 8 - { - std::uint8_t len{}; - return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); - } - - case 0xDA: // str 16 - { - std::uint16_t len{}; - return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); - } - - case 0xDB: // str 32 - { - std::uint32_t len{}; - return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); - } - - default: - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::msgpack, "expected length specification (0xA0-0xBF, 0xD9-0xDB); last byte: 0x" + last_token, "string"), BasicJsonType())); - } - } - } - - /*! - @brief reads a MessagePack byte array - - This function first reads starting bytes to determine the expected - byte array length and then copies this number of bytes into a byte array. - - @param[out] result created byte array - - @return whether byte array creation completed - */ - bool get_msgpack_binary(binary_t& result) - { - // helper function to set the subtype - auto assign_and_return_true = [&result](std::int8_t subtype) - { - result.set_subtype(static_cast(subtype)); - return true; - }; - - switch (current) - { - case 0xC4: // bin 8 - { - std::uint8_t len{}; - return get_number(input_format_t::msgpack, len) && - get_binary(input_format_t::msgpack, len, result); - } - - case 0xC5: // bin 16 - { - std::uint16_t len{}; - return get_number(input_format_t::msgpack, len) && - get_binary(input_format_t::msgpack, len, result); - } - - case 0xC6: // bin 32 - { - std::uint32_t len{}; - return get_number(input_format_t::msgpack, len) && - get_binary(input_format_t::msgpack, len, result); - } - - case 0xC7: // ext 8 - { - std::uint8_t len{}; - std::int8_t subtype{}; - return get_number(input_format_t::msgpack, len) && - get_number(input_format_t::msgpack, subtype) && - get_binary(input_format_t::msgpack, len, result) && - assign_and_return_true(subtype); - } - - case 0xC8: // ext 16 - { - std::uint16_t len{}; - std::int8_t subtype{}; - return get_number(input_format_t::msgpack, len) && - get_number(input_format_t::msgpack, subtype) && - get_binary(input_format_t::msgpack, len, result) && - assign_and_return_true(subtype); - } - - case 0xC9: // ext 32 - { - std::uint32_t len{}; - std::int8_t subtype{}; - return get_number(input_format_t::msgpack, len) && - get_number(input_format_t::msgpack, subtype) && - get_binary(input_format_t::msgpack, len, result) && - assign_and_return_true(subtype); - } - - case 0xD4: // fixext 1 - { - std::int8_t subtype{}; - return get_number(input_format_t::msgpack, subtype) && - get_binary(input_format_t::msgpack, 1, result) && - assign_and_return_true(subtype); - } - - case 0xD5: // fixext 2 - { - std::int8_t subtype{}; - return get_number(input_format_t::msgpack, subtype) && - get_binary(input_format_t::msgpack, 2, result) && - assign_and_return_true(subtype); - } - - case 0xD6: // fixext 4 - { - std::int8_t subtype{}; - return get_number(input_format_t::msgpack, subtype) && - get_binary(input_format_t::msgpack, 4, result) && - assign_and_return_true(subtype); - } - - case 0xD7: // fixext 8 - { - std::int8_t subtype{}; - return get_number(input_format_t::msgpack, subtype) && - get_binary(input_format_t::msgpack, 8, result) && - assign_and_return_true(subtype); - } - - case 0xD8: // fixext 16 - { - std::int8_t subtype{}; - return get_number(input_format_t::msgpack, subtype) && - get_binary(input_format_t::msgpack, 16, result) && - assign_and_return_true(subtype); - } - - default: // LCOV_EXCL_LINE - return false; // LCOV_EXCL_LINE - } - } - - /*! - @param[in] len the length of the array - @return whether array creation completed - */ - bool get_msgpack_array(const std::size_t len) - { - if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len))) - { - return false; - } - - for (std::size_t i = 0; i < len; ++i) - { - if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal())) - { - return false; - } - } - - return sax->end_array(); - } - - /*! - @param[in] len the length of the object - @return whether object creation completed - */ - bool get_msgpack_object(const std::size_t len) - { - if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len))) - { - return false; - } - - string_t key; - for (std::size_t i = 0; i < len; ++i) - { - get(); - if (JSON_HEDLEY_UNLIKELY(!get_msgpack_string(key) || !sax->key(key))) - { - return false; - } - - if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal())) - { - return false; - } - key.clear(); - } - - return sax->end_object(); - } - - //////////// - // UBJSON // - //////////// - - /*! - @param[in] get_char whether a new character should be retrieved from the - input (true, default) or whether the last read - character should be considered instead - - @return whether a valid UBJSON value was passed to the SAX parser - */ - bool parse_ubjson_internal(const bool get_char = true) - { - return get_ubjson_value(get_char ? get_ignore_noop() : current); - } - - /*! - @brief reads a UBJSON string - - This function is either called after reading the 'S' byte explicitly - indicating a string, or in case of an object key where the 'S' byte can be - left out. - - @param[out] result created string - @param[in] get_char whether a new character should be retrieved from the - input (true, default) or whether the last read - character should be considered instead - - @return whether string creation completed - */ - bool get_ubjson_string(string_t& result, const bool get_char = true) - { - if (get_char) - { - get(); // TODO(niels): may we ignore N here? - } - - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value"))) - { - return false; - } - - switch (current) - { - case 'U': - { - std::uint8_t len{}; - return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); - } - - case 'i': - { - std::int8_t len{}; - return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); - } - - case 'I': - { - std::int16_t len{}; - return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); - } - - case 'l': - { - std::int32_t len{}; - return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); - } - - case 'L': - { - std::int64_t len{}; - return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); - } - - default: - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L); last byte: 0x" + last_token, "string"), BasicJsonType())); - } - } - - /*! - @param[out] result determined size - @return whether size determination completed - */ - bool get_ubjson_size_value(std::size_t& result) - { - switch (get_ignore_noop()) - { - case 'U': - { - std::uint8_t number{}; - if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) - { - return false; - } - result = static_cast(number); - return true; - } - - case 'i': - { - std::int8_t number{}; - if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) - { - return false; - } - result = static_cast(number); // NOLINT(bugprone-signed-char-misuse,cert-str34-c): number is not a char - return true; - } - - case 'I': - { - std::int16_t number{}; - if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) - { - return false; - } - result = static_cast(number); - return true; - } - - case 'l': - { - std::int32_t number{}; - if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) - { - return false; - } - result = static_cast(number); - return true; - } - - case 'L': - { - std::int64_t number{}; - if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) - { - return false; - } - result = static_cast(number); - return true; - } - - default: - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L) after '#'; last byte: 0x" + last_token, "size"), BasicJsonType())); - } - } - } - - /*! - @brief determine the type and size for a container - - In the optimized UBJSON format, a type and a size can be provided to allow - for a more compact representation. - - @param[out] result pair of the size and the type - - @return whether pair creation completed - */ - bool get_ubjson_size_type(std::pair& result) - { - result.first = string_t::npos; // size - result.second = 0; // type - - get_ignore_noop(); - - if (current == '$') - { - result.second = get(); // must not ignore 'N', because 'N' maybe the type - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "type"))) - { - return false; - } - - get_ignore_noop(); - if (JSON_HEDLEY_UNLIKELY(current != '#')) - { - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value"))) - { - return false; - } - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "expected '#' after type information; last byte: 0x" + last_token, "size"), BasicJsonType())); - } - - return get_ubjson_size_value(result.first); - } - - if (current == '#') - { - return get_ubjson_size_value(result.first); - } - - return true; - } - - /*! - @param prefix the previously read or set type prefix - @return whether value creation completed - */ - bool get_ubjson_value(const char_int_type prefix) - { - switch (prefix) - { - case std::char_traits::eof(): // EOF - return unexpect_eof(input_format_t::ubjson, "value"); - - case 'T': // true - return sax->boolean(true); - case 'F': // false - return sax->boolean(false); - - case 'Z': // null - return sax->null(); - - case 'U': - { - std::uint8_t number{}; - return get_number(input_format_t::ubjson, number) && sax->number_unsigned(number); - } - - case 'i': - { - std::int8_t number{}; - return get_number(input_format_t::ubjson, number) && sax->number_integer(number); - } - - case 'I': - { - std::int16_t number{}; - return get_number(input_format_t::ubjson, number) && sax->number_integer(number); - } - - case 'l': - { - std::int32_t number{}; - return get_number(input_format_t::ubjson, number) && sax->number_integer(number); - } - - case 'L': - { - std::int64_t number{}; - return get_number(input_format_t::ubjson, number) && sax->number_integer(number); - } - - case 'd': - { - float number{}; - return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast(number), ""); - } - - case 'D': - { - double number{}; - return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast(number), ""); - } - - case 'H': - { - return get_ubjson_high_precision_number(); - } - - case 'C': // char - { - get(); - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "char"))) - { - return false; - } - if (JSON_HEDLEY_UNLIKELY(current > 127)) - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "byte after 'C' must be in range 0x00..0x7F; last byte: 0x" + last_token, "char"), BasicJsonType())); - } - string_t s(1, static_cast(current)); - return sax->string(s); - } - - case 'S': // string - { - string_t s; - return get_ubjson_string(s) && sax->string(s); - } - - case '[': // array - return get_ubjson_array(); - - case '{': // object - return get_ubjson_object(); - - default: // anything else - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); - } - } - } - - /*! - @return whether array creation completed - */ - bool get_ubjson_array() - { - std::pair size_and_type; - if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type))) - { - return false; - } - - if (size_and_type.first != string_t::npos) - { - if (JSON_HEDLEY_UNLIKELY(!sax->start_array(size_and_type.first))) - { - return false; - } - - if (size_and_type.second != 0) - { - if (size_and_type.second != 'N') - { - for (std::size_t i = 0; i < size_and_type.first; ++i) - { - if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) - { - return false; - } - } - } - } - else - { - for (std::size_t i = 0; i < size_and_type.first; ++i) - { - if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) - { - return false; - } - } - } - } - else - { - if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast(-1)))) - { - return false; - } - - while (current != ']') - { - if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal(false))) - { - return false; - } - get_ignore_noop(); - } - } - - return sax->end_array(); - } - - /*! - @return whether object creation completed - */ - bool get_ubjson_object() - { - std::pair size_and_type; - if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type))) - { - return false; - } - - string_t key; - if (size_and_type.first != string_t::npos) - { - if (JSON_HEDLEY_UNLIKELY(!sax->start_object(size_and_type.first))) - { - return false; - } - - if (size_and_type.second != 0) - { - for (std::size_t i = 0; i < size_and_type.first; ++i) - { - if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key))) - { - return false; - } - if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) - { - return false; - } - key.clear(); - } - } - else - { - for (std::size_t i = 0; i < size_and_type.first; ++i) - { - if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key))) - { - return false; - } - if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) - { - return false; - } - key.clear(); - } - } - } - else - { - if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast(-1)))) - { - return false; - } - - while (current != '}') - { - if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key, false) || !sax->key(key))) - { - return false; - } - if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) - { - return false; - } - get_ignore_noop(); - key.clear(); - } - } - - return sax->end_object(); - } - - // Note, no reader for UBJSON binary types is implemented because they do - // not exist - - bool get_ubjson_high_precision_number() - { - // get size of following number string - std::size_t size{}; - auto res = get_ubjson_size_value(size); - if (JSON_HEDLEY_UNLIKELY(!res)) - { - return res; - } - - // get number string - std::vector number_vector; - for (std::size_t i = 0; i < size; ++i) - { - get(); - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "number"))) - { - return false; - } - number_vector.push_back(static_cast(current)); - } - - // parse number string - using ia_type = decltype(detail::input_adapter(number_vector)); - auto number_lexer = detail::lexer(detail::input_adapter(number_vector), false); - const auto result_number = number_lexer.scan(); - const auto number_string = number_lexer.get_token_string(); - const auto result_remainder = number_lexer.scan(); - - using token_type = typename detail::lexer_base::token_type; - - if (JSON_HEDLEY_UNLIKELY(result_remainder != token_type::end_of_input)) - { - return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format_t::ubjson, "invalid number text: " + number_lexer.get_token_string(), "high-precision number"), BasicJsonType())); - } - - switch (result_number) - { - case token_type::value_integer: - return sax->number_integer(number_lexer.get_number_integer()); - case token_type::value_unsigned: - return sax->number_unsigned(number_lexer.get_number_unsigned()); - case token_type::value_float: - return sax->number_float(number_lexer.get_number_float(), std::move(number_string)); - case token_type::uninitialized: - case token_type::literal_true: - case token_type::literal_false: - case token_type::literal_null: - case token_type::value_string: - case token_type::begin_array: - case token_type::begin_object: - case token_type::end_array: - case token_type::end_object: - case token_type::name_separator: - case token_type::value_separator: - case token_type::parse_error: - case token_type::end_of_input: - case token_type::literal_or_value: - default: - return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format_t::ubjson, "invalid number text: " + number_lexer.get_token_string(), "high-precision number"), BasicJsonType())); - } - } - - /////////////////////// - // Utility functions // - /////////////////////// - - /*! - @brief get next character from the input - - This function provides the interface to the used input adapter. It does - not throw in case the input reached EOF, but returns a -'ve valued - `std::char_traits::eof()` in that case. - - @return character read from the input - */ - char_int_type get() - { - ++chars_read; - return current = ia.get_character(); - } - - /*! - @return character read from the input after ignoring all 'N' entries - */ - char_int_type get_ignore_noop() - { - do - { - get(); - } - while (current == 'N'); - - return current; - } - - /* - @brief read a number from the input - - @tparam NumberType the type of the number - @param[in] format the current format (for diagnostics) - @param[out] result number of type @a NumberType - - @return whether conversion completed - - @note This function needs to respect the system's endianness, because - bytes in CBOR, MessagePack, and UBJSON are stored in network order - (big endian) and therefore need reordering on little endian systems. - */ - template - bool get_number(const input_format_t format, NumberType& result) - { - // step 1: read input into array with system's byte order - std::array vec{}; - for (std::size_t i = 0; i < sizeof(NumberType); ++i) - { - get(); - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "number"))) - { - return false; - } - - // reverse byte order prior to conversion if necessary - if (is_little_endian != InputIsLittleEndian) - { - vec[sizeof(NumberType) - i - 1] = static_cast(current); - } - else - { - vec[i] = static_cast(current); // LCOV_EXCL_LINE - } - } - - // step 2: convert array into number of type T and return - std::memcpy(&result, vec.data(), sizeof(NumberType)); - return true; - } - - /*! - @brief create a string by reading characters from the input - - @tparam NumberType the type of the number - @param[in] format the current format (for diagnostics) - @param[in] len number of characters to read - @param[out] result string created by reading @a len bytes - - @return whether string creation completed - - @note We can not reserve @a len bytes for the result, because @a len - may be too large. Usually, @ref unexpect_eof() detects the end of - the input before we run out of string memory. - */ - template - bool get_string(const input_format_t format, - const NumberType len, - string_t& result) - { - bool success = true; - for (NumberType i = 0; i < len; i++) - { - get(); - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "string"))) - { - success = false; - break; - } - result.push_back(static_cast(current)); - } - return success; - } - - /*! - @brief create a byte array by reading bytes from the input - - @tparam NumberType the type of the number - @param[in] format the current format (for diagnostics) - @param[in] len number of bytes to read - @param[out] result byte array created by reading @a len bytes - - @return whether byte array creation completed - - @note We can not reserve @a len bytes for the result, because @a len - may be too large. Usually, @ref unexpect_eof() detects the end of - the input before we run out of memory. - */ - template - bool get_binary(const input_format_t format, - const NumberType len, - binary_t& result) - { - bool success = true; - for (NumberType i = 0; i < len; i++) - { - get(); - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "binary"))) - { - success = false; - break; - } - result.push_back(static_cast(current)); - } - return success; - } - - /*! - @param[in] format the current format (for diagnostics) - @param[in] context further context information (for diagnostics) - @return whether the last read character is not EOF - */ - JSON_HEDLEY_NON_NULL(3) - bool unexpect_eof(const input_format_t format, const char* context) const - { - if (JSON_HEDLEY_UNLIKELY(current == std::char_traits::eof())) - { - return sax->parse_error(chars_read, "", - parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context), BasicJsonType())); - } - return true; - } - - /*! - @return a string representation of the last read byte - */ - std::string get_token_string() const - { - std::array cr{{}}; - static_cast((std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast(current))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) - return std::string{cr.data()}; - } - - /*! - @param[in] format the current format - @param[in] detail a detailed error message - @param[in] context further context information - @return a message string to use in the parse_error exceptions - */ - std::string exception_message(const input_format_t format, - const std::string& detail, - const std::string& context) const - { - std::string error_msg = "syntax error while parsing "; - - switch (format) - { - case input_format_t::cbor: - error_msg += "CBOR"; - break; - - case input_format_t::msgpack: - error_msg += "MessagePack"; - break; - - case input_format_t::ubjson: - error_msg += "UBJSON"; - break; - - case input_format_t::bson: - error_msg += "BSON"; - break; - - case input_format_t::json: // LCOV_EXCL_LINE - default: // LCOV_EXCL_LINE - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE - } - - return error_msg + " " + context + ": " + detail; - } - - private: - /// input adapter - InputAdapterType ia; - - /// the current character - char_int_type current = std::char_traits::eof(); - - /// the number of characters read - std::size_t chars_read = 0; - - /// whether we can assume little endianness - const bool is_little_endian = little_endianness(); - - /// the SAX parser - json_sax_t* sax = nullptr; -}; -} // namespace detail -} // namespace nlohmann - -// #include - -// #include - -// #include - - -#include // isfinite -#include // uint8_t -#include // function -#include // string -#include // move -#include // vector - -// #include - -// #include - -// #include - -// #include - -// #include - -// #include - -// #include - - -namespace nlohmann -{ -namespace detail -{ -//////////// -// parser // -//////////// - -enum class parse_event_t : std::uint8_t -{ - /// the parser read `{` and started to process a JSON object - object_start, - /// the parser read `}` and finished processing a JSON object - object_end, - /// the parser read `[` and started to process a JSON array - array_start, - /// the parser read `]` and finished processing a JSON array - array_end, - /// the parser read a key of a value in an object - key, - /// the parser finished reading a JSON value - value -}; - -template -using parser_callback_t = - std::function; - -/*! -@brief syntax analysis - -This class implements a recursive descent parser. -*/ -template -class parser -{ - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - using string_t = typename BasicJsonType::string_t; - using lexer_t = lexer; - using token_type = typename lexer_t::token_type; - - public: - /// a parser reading from an input adapter - explicit parser(InputAdapterType&& adapter, - const parser_callback_t cb = nullptr, - const bool allow_exceptions_ = true, - const bool skip_comments = false) - : callback(cb) - , m_lexer(std::move(adapter), skip_comments) - , allow_exceptions(allow_exceptions_) - { - // read first token - get_token(); - } - - /*! - @brief public parser interface - - @param[in] strict whether to expect the last token to be EOF - @param[in,out] result parsed JSON value - - @throw parse_error.101 in case of an unexpected token - @throw parse_error.102 if to_unicode fails or surrogate error - @throw parse_error.103 if to_unicode fails - */ - void parse(const bool strict, BasicJsonType& result) - { - if (callback) - { - json_sax_dom_callback_parser sdp(result, callback, allow_exceptions); - sax_parse_internal(&sdp); - - // in strict mode, input must be completely read - if (strict && (get_token() != token_type::end_of_input)) - { - sdp.parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), - exception_message(token_type::end_of_input, "value"), BasicJsonType())); - } - - // in case of an error, return discarded value - if (sdp.is_errored()) - { - result = value_t::discarded; - return; - } - - // set top-level value to null if it was discarded by the callback - // function - if (result.is_discarded()) - { - result = nullptr; - } - } - else - { - json_sax_dom_parser sdp(result, allow_exceptions); - sax_parse_internal(&sdp); - - // in strict mode, input must be completely read - if (strict && (get_token() != token_type::end_of_input)) - { - sdp.parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType())); - } - - // in case of an error, return discarded value - if (sdp.is_errored()) - { - result = value_t::discarded; - return; - } - } - - result.assert_invariant(); - } - - /*! - @brief public accept interface - - @param[in] strict whether to expect the last token to be EOF - @return whether the input is a proper JSON text - */ - bool accept(const bool strict = true) - { - json_sax_acceptor sax_acceptor; - return sax_parse(&sax_acceptor, strict); - } - - template - JSON_HEDLEY_NON_NULL(2) - bool sax_parse(SAX* sax, const bool strict = true) - { - (void)detail::is_sax_static_asserts {}; - const bool result = sax_parse_internal(sax); - - // strict mode: next byte must be EOF - if (result && strict && (get_token() != token_type::end_of_input)) - { - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType())); - } - - return result; - } - - private: - template - JSON_HEDLEY_NON_NULL(2) - bool sax_parse_internal(SAX* sax) - { - // stack to remember the hierarchy of structured values we are parsing - // true = array; false = object - std::vector states; - // value to avoid a goto (see comment where set to true) - bool skip_to_state_evaluation = false; - - while (true) - { - if (!skip_to_state_evaluation) - { - // invariant: get_token() was called before each iteration - switch (last_token) - { - case token_type::begin_object: - { - if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast(-1)))) - { - return false; - } - - // closing } -> we are done - if (get_token() == token_type::end_object) - { - if (JSON_HEDLEY_UNLIKELY(!sax->end_object())) - { - return false; - } - break; - } - - // parse key - if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string)) - { - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), BasicJsonType())); - } - if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string()))) - { - return false; - } - - // parse separator (:) - if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator)) - { - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), BasicJsonType())); - } - - // remember we are now inside an object - states.push_back(false); - - // parse values - get_token(); - continue; - } - - case token_type::begin_array: - { - if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast(-1)))) - { - return false; - } - - // closing ] -> we are done - if (get_token() == token_type::end_array) - { - if (JSON_HEDLEY_UNLIKELY(!sax->end_array())) - { - return false; - } - break; - } - - // remember we are now inside an array - states.push_back(true); - - // parse values (no need to call get_token) - continue; - } - - case token_type::value_float: - { - const auto res = m_lexer.get_number_float(); - - if (JSON_HEDLEY_UNLIKELY(!std::isfinite(res))) - { - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'", BasicJsonType())); - } - - if (JSON_HEDLEY_UNLIKELY(!sax->number_float(res, m_lexer.get_string()))) - { - return false; - } - - break; - } - - case token_type::literal_false: - { - if (JSON_HEDLEY_UNLIKELY(!sax->boolean(false))) - { - return false; - } - break; - } - - case token_type::literal_null: - { - if (JSON_HEDLEY_UNLIKELY(!sax->null())) - { - return false; - } - break; - } - - case token_type::literal_true: - { - if (JSON_HEDLEY_UNLIKELY(!sax->boolean(true))) - { - return false; - } - break; - } - - case token_type::value_integer: - { - if (JSON_HEDLEY_UNLIKELY(!sax->number_integer(m_lexer.get_number_integer()))) - { - return false; - } - break; - } - - case token_type::value_string: - { - if (JSON_HEDLEY_UNLIKELY(!sax->string(m_lexer.get_string()))) - { - return false; - } - break; - } - - case token_type::value_unsigned: - { - if (JSON_HEDLEY_UNLIKELY(!sax->number_unsigned(m_lexer.get_number_unsigned()))) - { - return false; - } - break; - } - - case token_type::parse_error: - { - // using "uninitialized" to avoid "expected" message - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::uninitialized, "value"), BasicJsonType())); - } - - case token_type::uninitialized: - case token_type::end_array: - case token_type::end_object: - case token_type::name_separator: - case token_type::value_separator: - case token_type::end_of_input: - case token_type::literal_or_value: - default: // the last token was unexpected - { - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::literal_or_value, "value"), BasicJsonType())); - } - } - } - else - { - skip_to_state_evaluation = false; - } - - // we reached this line after we successfully parsed a value - if (states.empty()) - { - // empty stack: we reached the end of the hierarchy: done - return true; - } - - if (states.back()) // array - { - // comma -> next value - if (get_token() == token_type::value_separator) - { - // parse a new value - get_token(); - continue; - } - - // closing ] - if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array)) - { - if (JSON_HEDLEY_UNLIKELY(!sax->end_array())) - { - return false; - } - - // We are done with this array. Before we can parse a - // new value, we need to evaluate the new state first. - // By setting skip_to_state_evaluation to false, we - // are effectively jumping to the beginning of this if. - JSON_ASSERT(!states.empty()); - states.pop_back(); - skip_to_state_evaluation = true; - continue; - } - - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_array, "array"), BasicJsonType())); - } - - // states.back() is false -> object - - // comma -> next value - if (get_token() == token_type::value_separator) - { - // parse key - if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string)) - { - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), BasicJsonType())); - } - - if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string()))) - { - return false; - } - - // parse separator (:) - if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator)) - { - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), BasicJsonType())); - } - - // parse values - get_token(); - continue; - } - - // closing } - if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object)) - { - if (JSON_HEDLEY_UNLIKELY(!sax->end_object())) - { - return false; - } - - // We are done with this object. Before we can parse a - // new value, we need to evaluate the new state first. - // By setting skip_to_state_evaluation to false, we - // are effectively jumping to the beginning of this if. - JSON_ASSERT(!states.empty()); - states.pop_back(); - skip_to_state_evaluation = true; - continue; - } - - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_object, "object"), BasicJsonType())); - } - } - - /// get next token from lexer - token_type get_token() - { - return last_token = m_lexer.scan(); - } - - std::string exception_message(const token_type expected, const std::string& context) - { - std::string error_msg = "syntax error "; - - if (!context.empty()) - { - error_msg += "while parsing " + context + " "; - } - - error_msg += "- "; - - if (last_token == token_type::parse_error) - { - error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" + - m_lexer.get_token_string() + "'"; - } - else - { - error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token)); - } - - if (expected != token_type::uninitialized) - { - error_msg += "; expected " + std::string(lexer_t::token_type_name(expected)); - } - - return error_msg; - } - - private: - /// callback function - const parser_callback_t callback = nullptr; - /// the type of the last read token - token_type last_token = token_type::uninitialized; - /// the lexer - lexer_t m_lexer; - /// whether to throw exceptions in case of errors - const bool allow_exceptions = true; -}; - -} // namespace detail -} // namespace nlohmann - -// #include - - -// #include - - -#include // ptrdiff_t -#include // numeric_limits - -// #include - - -namespace nlohmann -{ -namespace detail -{ -/* -@brief an iterator for primitive JSON types - -This class models an iterator for primitive JSON types (boolean, number, -string). It's only purpose is to allow the iterator/const_iterator classes -to "iterate" over primitive values. Internally, the iterator is modeled by -a `difference_type` variable. Value begin_value (`0`) models the begin, -end_value (`1`) models past the end. -*/ -class primitive_iterator_t -{ - private: - using difference_type = std::ptrdiff_t; - static constexpr difference_type begin_value = 0; - static constexpr difference_type end_value = begin_value + 1; - - JSON_PRIVATE_UNLESS_TESTED: - /// iterator as signed integer type - difference_type m_it = (std::numeric_limits::min)(); - - public: - constexpr difference_type get_value() const noexcept - { - return m_it; - } - - /// set iterator to a defined beginning - void set_begin() noexcept - { - m_it = begin_value; - } - - /// set iterator to a defined past the end - void set_end() noexcept - { - m_it = end_value; - } - - /// return whether the iterator can be dereferenced - constexpr bool is_begin() const noexcept - { - return m_it == begin_value; - } - - /// return whether the iterator is at end - constexpr bool is_end() const noexcept - { - return m_it == end_value; - } - - friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept - { - return lhs.m_it == rhs.m_it; - } - - friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept - { - return lhs.m_it < rhs.m_it; - } - - primitive_iterator_t operator+(difference_type n) noexcept - { - auto result = *this; - result += n; - return result; - } - - friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept - { - return lhs.m_it - rhs.m_it; - } - - primitive_iterator_t& operator++() noexcept - { - ++m_it; - return *this; - } - - primitive_iterator_t const operator++(int) noexcept // NOLINT(readability-const-return-type) - { - auto result = *this; - ++m_it; - return result; - } - - primitive_iterator_t& operator--() noexcept - { - --m_it; - return *this; - } - - primitive_iterator_t const operator--(int) noexcept // NOLINT(readability-const-return-type) - { - auto result = *this; - --m_it; - return result; - } - - primitive_iterator_t& operator+=(difference_type n) noexcept - { - m_it += n; - return *this; - } - - primitive_iterator_t& operator-=(difference_type n) noexcept - { - m_it -= n; - return *this; - } -}; -} // namespace detail -} // namespace nlohmann - - -namespace nlohmann -{ -namespace detail -{ -/*! -@brief an iterator value - -@note This structure could easily be a union, but MSVC currently does not allow -unions members with complex constructors, see https://github.com/nlohmann/json/pull/105. -*/ -template struct internal_iterator -{ - /// iterator for JSON objects - typename BasicJsonType::object_t::iterator object_iterator {}; - /// iterator for JSON arrays - typename BasicJsonType::array_t::iterator array_iterator {}; - /// generic iterator for all other types - primitive_iterator_t primitive_iterator {}; -}; -} // namespace detail -} // namespace nlohmann - -// #include - - -#include // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next -#include // conditional, is_const, remove_const - -// #include - -// #include - -// #include - -// #include - -// #include - -// #include - -// #include - - -namespace nlohmann -{ -namespace detail -{ -// forward declare, to be able to friend it later on -template class iteration_proxy; -template class iteration_proxy_value; - -/*! -@brief a template for a bidirectional iterator for the @ref basic_json class -This class implements a both iterators (iterator and const_iterator) for the -@ref basic_json class. -@note An iterator is called *initialized* when a pointer to a JSON value has - been set (e.g., by a constructor or a copy assignment). If the iterator is - default-constructed, it is *uninitialized* and most methods are undefined. - **The library uses assertions to detect calls on uninitialized iterators.** -@requirement The class satisfies the following concept requirements: -- -[BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): - The iterator that can be moved can be moved in both directions (i.e. - incremented and decremented). -@since version 1.0.0, simplified in version 2.0.9, change to bidirectional - iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593) -*/ -template -class iter_impl // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions) -{ - /// the iterator with BasicJsonType of different const-ness - using other_iter_impl = iter_impl::value, typename std::remove_const::type, const BasicJsonType>::type>; - /// allow basic_json to access private members - friend other_iter_impl; - friend BasicJsonType; - friend iteration_proxy; - friend iteration_proxy_value; - - using object_t = typename BasicJsonType::object_t; - using array_t = typename BasicJsonType::array_t; - // make sure BasicJsonType is basic_json or const basic_json - static_assert(is_basic_json::type>::value, - "iter_impl only accepts (const) basic_json"); - - public: - - /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17. - /// The C++ Standard has never required user-defined iterators to derive from std::iterator. - /// A user-defined iterator should provide publicly accessible typedefs named - /// iterator_category, value_type, difference_type, pointer, and reference. - /// Note that value_type is required to be non-const, even for constant iterators. - using iterator_category = std::bidirectional_iterator_tag; - - /// the type of the values when the iterator is dereferenced - using value_type = typename BasicJsonType::value_type; - /// a type to represent differences between iterators - using difference_type = typename BasicJsonType::difference_type; - /// defines a pointer to the type iterated over (value_type) - using pointer = typename std::conditional::value, - typename BasicJsonType::const_pointer, - typename BasicJsonType::pointer>::type; - /// defines a reference to the type iterated over (value_type) - using reference = - typename std::conditional::value, - typename BasicJsonType::const_reference, - typename BasicJsonType::reference>::type; - - iter_impl() = default; - ~iter_impl() = default; - iter_impl(iter_impl&&) noexcept = default; - iter_impl& operator=(iter_impl&&) noexcept = default; - - /*! - @brief constructor for a given JSON instance - @param[in] object pointer to a JSON object for this iterator - @pre object != nullptr - @post The iterator is initialized; i.e. `m_object != nullptr`. - */ - explicit iter_impl(pointer object) noexcept : m_object(object) - { - JSON_ASSERT(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - { - m_it.object_iterator = typename object_t::iterator(); - break; - } - - case value_t::array: - { - m_it.array_iterator = typename array_t::iterator(); - break; - } - - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - m_it.primitive_iterator = primitive_iterator_t(); - break; - } - } - } - - /*! - @note The conventional copy constructor and copy assignment are implicitly - defined. Combined with the following converting constructor and - assignment, they support: (1) copy from iterator to iterator, (2) - copy from const iterator to const iterator, and (3) conversion from - iterator to const iterator. However conversion from const iterator - to iterator is not defined. - */ - - /*! - @brief const copy constructor - @param[in] other const iterator to copy from - @note This copy constructor had to be defined explicitly to circumvent a bug - occurring on msvc v19.0 compiler (VS 2015) debug build. For more - information refer to: https://github.com/nlohmann/json/issues/1608 - */ - iter_impl(const iter_impl& other) noexcept - : m_object(other.m_object), m_it(other.m_it) - {} - - /*! - @brief converting assignment - @param[in] other const iterator to copy from - @return const/non-const iterator - @note It is not checked whether @a other is initialized. - */ - iter_impl& operator=(const iter_impl& other) noexcept - { - if (&other != this) - { - m_object = other.m_object; - m_it = other.m_it; - } - return *this; - } - - /*! - @brief converting constructor - @param[in] other non-const iterator to copy from - @note It is not checked whether @a other is initialized. - */ - iter_impl(const iter_impl::type>& other) noexcept - : m_object(other.m_object), m_it(other.m_it) - {} - - /*! - @brief converting assignment - @param[in] other non-const iterator to copy from - @return const/non-const iterator - @note It is not checked whether @a other is initialized. - */ - iter_impl& operator=(const iter_impl::type>& other) noexcept // NOLINT(cert-oop54-cpp) - { - m_object = other.m_object; - m_it = other.m_it; - return *this; - } - - JSON_PRIVATE_UNLESS_TESTED: - /*! - @brief set the iterator to the first value - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - void set_begin() noexcept - { - JSON_ASSERT(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - { - m_it.object_iterator = m_object->m_value.object->begin(); - break; - } - - case value_t::array: - { - m_it.array_iterator = m_object->m_value.array->begin(); - break; - } - - case value_t::null: - { - // set to end so begin()==end() is true: null is empty - m_it.primitive_iterator.set_end(); - break; - } - - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - m_it.primitive_iterator.set_begin(); - break; - } - } - } - - /*! - @brief set the iterator past the last value - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - void set_end() noexcept - { - JSON_ASSERT(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - { - m_it.object_iterator = m_object->m_value.object->end(); - break; - } - - case value_t::array: - { - m_it.array_iterator = m_object->m_value.array->end(); - break; - } - - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - m_it.primitive_iterator.set_end(); - break; - } - } - } - - public: - /*! - @brief return a reference to the value pointed to by the iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - reference operator*() const - { - JSON_ASSERT(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - { - JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end()); - return m_it.object_iterator->second; - } - - case value_t::array: - { - JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end()); - return *m_it.array_iterator; - } - - case value_t::null: - JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); - - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin())) - { - return *m_object; - } - - JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); - } - } - } - - /*! - @brief dereference the iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - pointer operator->() const - { - JSON_ASSERT(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - { - JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end()); - return &(m_it.object_iterator->second); - } - - case value_t::array: - { - JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end()); - return &*m_it.array_iterator; - } - - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin())) - { - return m_object; - } - - JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); - } - } - } - - /*! - @brief post-increment (it++) - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - iter_impl const operator++(int) // NOLINT(readability-const-return-type) - { - auto result = *this; - ++(*this); - return result; - } - - /*! - @brief pre-increment (++it) - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - iter_impl& operator++() - { - JSON_ASSERT(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - { - std::advance(m_it.object_iterator, 1); - break; - } - - case value_t::array: - { - std::advance(m_it.array_iterator, 1); - break; - } - - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - ++m_it.primitive_iterator; - break; - } - } - - return *this; - } - - /*! - @brief post-decrement (it--) - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - iter_impl const operator--(int) // NOLINT(readability-const-return-type) - { - auto result = *this; - --(*this); - return result; - } - - /*! - @brief pre-decrement (--it) - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - iter_impl& operator--() - { - JSON_ASSERT(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - { - std::advance(m_it.object_iterator, -1); - break; - } - - case value_t::array: - { - std::advance(m_it.array_iterator, -1); - break; - } - - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - --m_it.primitive_iterator; - break; - } - } - - return *this; - } - - /*! - @brief comparison: equal - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - template < typename IterImpl, detail::enable_if_t < (std::is_same::value || std::is_same::value), std::nullptr_t > = nullptr > - bool operator==(const IterImpl& other) const - { - // if objects are not the same, the comparison is undefined - if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object)) - { - JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", *m_object)); - } - - JSON_ASSERT(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - return (m_it.object_iterator == other.m_it.object_iterator); - - case value_t::array: - return (m_it.array_iterator == other.m_it.array_iterator); - - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - return (m_it.primitive_iterator == other.m_it.primitive_iterator); - } - } - - /*! - @brief comparison: not equal - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - template < typename IterImpl, detail::enable_if_t < (std::is_same::value || std::is_same::value), std::nullptr_t > = nullptr > - bool operator!=(const IterImpl& other) const - { - return !operator==(other); - } - - /*! - @brief comparison: smaller - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - bool operator<(const iter_impl& other) const - { - // if objects are not the same, the comparison is undefined - if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object)) - { - JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", *m_object)); - } - - JSON_ASSERT(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators", *m_object)); - - case value_t::array: - return (m_it.array_iterator < other.m_it.array_iterator); - - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - return (m_it.primitive_iterator < other.m_it.primitive_iterator); - } - } - - /*! - @brief comparison: less than or equal - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - bool operator<=(const iter_impl& other) const - { - return !other.operator < (*this); - } - - /*! - @brief comparison: greater than - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - bool operator>(const iter_impl& other) const - { - return !operator<=(other); - } - - /*! - @brief comparison: greater than or equal - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - bool operator>=(const iter_impl& other) const - { - return !operator<(other); - } - - /*! - @brief add to iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - iter_impl& operator+=(difference_type i) - { - JSON_ASSERT(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", *m_object)); - - case value_t::array: - { - std::advance(m_it.array_iterator, i); - break; - } - - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - m_it.primitive_iterator += i; - break; - } - } - - return *this; - } - - /*! - @brief subtract from iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - iter_impl& operator-=(difference_type i) - { - return operator+=(-i); - } - - /*! - @brief add to iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - iter_impl operator+(difference_type i) const - { - auto result = *this; - result += i; - return result; - } - - /*! - @brief addition of distance and iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - friend iter_impl operator+(difference_type i, const iter_impl& it) - { - auto result = it; - result += i; - return result; - } - - /*! - @brief subtract from iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - iter_impl operator-(difference_type i) const - { - auto result = *this; - result -= i; - return result; - } - - /*! - @brief return difference - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - difference_type operator-(const iter_impl& other) const - { - JSON_ASSERT(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", *m_object)); - - case value_t::array: - return m_it.array_iterator - other.m_it.array_iterator; - - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - return m_it.primitive_iterator - other.m_it.primitive_iterator; - } - } - - /*! - @brief access to successor - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - reference operator[](difference_type n) const - { - JSON_ASSERT(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators", *m_object)); - - case value_t::array: - return *std::next(m_it.array_iterator, n); - - case value_t::null: - JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); - - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n)) - { - return *m_object; - } - - JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); - } - } - } - - /*! - @brief return the key of an object iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - const typename object_t::key_type& key() const - { - JSON_ASSERT(m_object != nullptr); - - if (JSON_HEDLEY_LIKELY(m_object->is_object())) - { - return m_it.object_iterator->first; - } - - JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators", *m_object)); - } - - /*! - @brief return the value of an iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - reference value() const - { - return operator*(); - } - - JSON_PRIVATE_UNLESS_TESTED: - /// associated JSON instance - pointer m_object = nullptr; - /// the actual iterator of the associated instance - internal_iterator::type> m_it {}; -}; -} // namespace detail -} // namespace nlohmann - -// #include - -// #include - - -#include // ptrdiff_t -#include // reverse_iterator -#include // declval - -namespace nlohmann -{ -namespace detail -{ -////////////////////// -// reverse_iterator // -////////////////////// - -/*! -@brief a template for a reverse iterator class - -@tparam Base the base iterator type to reverse. Valid types are @ref -iterator (to create @ref reverse_iterator) and @ref const_iterator (to -create @ref const_reverse_iterator). - -@requirement The class satisfies the following concept requirements: -- -[BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): - The iterator that can be moved can be moved in both directions (i.e. - incremented and decremented). -- [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator): - It is possible to write to the pointed-to element (only if @a Base is - @ref iterator). - -@since version 1.0.0 -*/ -template -class json_reverse_iterator : public std::reverse_iterator -{ - public: - using difference_type = std::ptrdiff_t; - /// shortcut to the reverse iterator adapter - using base_iterator = std::reverse_iterator; - /// the reference type for the pointed-to element - using reference = typename Base::reference; - - /// create reverse iterator from iterator - explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept - : base_iterator(it) {} - - /// create reverse iterator from base class - explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {} - - /// post-increment (it++) - json_reverse_iterator const operator++(int) // NOLINT(readability-const-return-type) - { - return static_cast(base_iterator::operator++(1)); - } - - /// pre-increment (++it) - json_reverse_iterator& operator++() - { - return static_cast(base_iterator::operator++()); - } - - /// post-decrement (it--) - json_reverse_iterator const operator--(int) // NOLINT(readability-const-return-type) - { - return static_cast(base_iterator::operator--(1)); - } - - /// pre-decrement (--it) - json_reverse_iterator& operator--() - { - return static_cast(base_iterator::operator--()); - } - - /// add to iterator - json_reverse_iterator& operator+=(difference_type i) - { - return static_cast(base_iterator::operator+=(i)); - } - - /// add to iterator - json_reverse_iterator operator+(difference_type i) const - { - return static_cast(base_iterator::operator+(i)); - } - - /// subtract from iterator - json_reverse_iterator operator-(difference_type i) const - { - return static_cast(base_iterator::operator-(i)); - } - - /// return difference - difference_type operator-(const json_reverse_iterator& other) const - { - return base_iterator(*this) - base_iterator(other); - } - - /// access to successor - reference operator[](difference_type n) const - { - return *(this->operator+(n)); - } - - /// return the key of an object iterator - auto key() const -> decltype(std::declval().key()) - { - auto it = --this->base(); - return it.key(); - } - - /// return the value of an iterator - reference value() const - { - auto it = --this->base(); - return it.operator * (); - } -}; -} // namespace detail -} // namespace nlohmann - -// #include - -// #include - - -#include // all_of -#include // isdigit -#include // max -#include // accumulate -#include // string -#include // move -#include // vector - -// #include - -// #include - -// #include - -// #include - - -namespace nlohmann -{ - -/// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document -/// @sa https://json.nlohmann.me/api/json_pointer/ -template -class json_pointer -{ - // allow basic_json to access private members - NLOHMANN_BASIC_JSON_TPL_DECLARATION - friend class basic_json; - - public: - /// @brief create JSON pointer - /// @sa https://json.nlohmann.me/api/json_pointer/json_pointer/ - explicit json_pointer(const std::string& s = "") - : reference_tokens(split(s)) - {} - - /// @brief return a string representation of the JSON pointer - /// @sa https://json.nlohmann.me/api/json_pointer/to_string/ - std::string to_string() const - { - return std::accumulate(reference_tokens.begin(), reference_tokens.end(), - std::string{}, - [](const std::string & a, const std::string & b) - { - return a + "/" + detail::escape(b); - }); - } - - /// @brief return a string representation of the JSON pointer - /// @sa https://json.nlohmann.me/api/json_pointer/operator_string/ - operator std::string() const - { - return to_string(); - } - - /// @brief append another JSON pointer at the end of this JSON pointer - /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/ - json_pointer& operator/=(const json_pointer& ptr) - { - reference_tokens.insert(reference_tokens.end(), - ptr.reference_tokens.begin(), - ptr.reference_tokens.end()); - return *this; - } - - /// @brief append an unescaped reference token at the end of this JSON pointer - /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/ - json_pointer& operator/=(std::string token) - { - push_back(std::move(token)); - return *this; - } - - /// @brief append an array index at the end of this JSON pointer - /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/ - json_pointer& operator/=(std::size_t array_idx) - { - return *this /= std::to_string(array_idx); - } - - /// @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer - /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/ - friend json_pointer operator/(const json_pointer& lhs, - const json_pointer& rhs) - { - return json_pointer(lhs) /= rhs; - } - - /// @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer - /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/ - friend json_pointer operator/(const json_pointer& lhs, std::string token) // NOLINT(performance-unnecessary-value-param) - { - return json_pointer(lhs) /= std::move(token); - } - - /// @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer - /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/ - friend json_pointer operator/(const json_pointer& lhs, std::size_t array_idx) - { - return json_pointer(lhs) /= array_idx; - } - - /// @brief returns the parent of this JSON pointer - /// @sa https://json.nlohmann.me/api/json_pointer/parent_pointer/ - json_pointer parent_pointer() const - { - if (empty()) - { - return *this; - } - - json_pointer res = *this; - res.pop_back(); - return res; - } - - /// @brief remove last reference token - /// @sa https://json.nlohmann.me/api/json_pointer/pop_back/ - void pop_back() - { - if (JSON_HEDLEY_UNLIKELY(empty())) - { - JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType())); - } - - reference_tokens.pop_back(); - } - - /// @brief return last reference token - /// @sa https://json.nlohmann.me/api/json_pointer/back/ - const std::string& back() const - { - if (JSON_HEDLEY_UNLIKELY(empty())) - { - JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType())); - } - - return reference_tokens.back(); - } - - /// @brief append an unescaped token at the end of the reference pointer - /// @sa https://json.nlohmann.me/api/json_pointer/push_back/ - void push_back(const std::string& token) - { - reference_tokens.push_back(token); - } - - /// @brief append an unescaped token at the end of the reference pointer - /// @sa https://json.nlohmann.me/api/json_pointer/push_back/ - void push_back(std::string&& token) - { - reference_tokens.push_back(std::move(token)); - } - - /// @brief return whether pointer points to the root document - /// @sa https://json.nlohmann.me/api/json_pointer/empty/ - bool empty() const noexcept - { - return reference_tokens.empty(); - } - - private: - /*! - @param[in] s reference token to be converted into an array index - - @return integer representation of @a s - - @throw parse_error.106 if an array index begins with '0' - @throw parse_error.109 if an array index begins not with a digit - @throw out_of_range.404 if string @a s could not be converted to an integer - @throw out_of_range.410 if an array index exceeds size_type - */ - static typename BasicJsonType::size_type array_index(const std::string& s) - { - using size_type = typename BasicJsonType::size_type; - - // error condition (cf. RFC 6901, Sect. 4) - if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && s[0] == '0')) - { - JSON_THROW(detail::parse_error::create(106, 0, "array index '" + s + "' must not begin with '0'", BasicJsonType())); - } - - // error condition (cf. RFC 6901, Sect. 4) - if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && !(s[0] >= '1' && s[0] <= '9'))) - { - JSON_THROW(detail::parse_error::create(109, 0, "array index '" + s + "' is not a number", BasicJsonType())); - } - - std::size_t processed_chars = 0; - unsigned long long res = 0; // NOLINT(runtime/int) - JSON_TRY - { - res = std::stoull(s, &processed_chars); - } - JSON_CATCH(std::out_of_range&) - { - JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType())); - } - - // check if the string was completely read - if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size())) - { - JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType())); - } - - // only triggered on special platforms (like 32bit), see also - // https://github.com/nlohmann/json/pull/2203 - if (res >= static_cast((std::numeric_limits::max)())) // NOLINT(runtime/int) - { - JSON_THROW(detail::out_of_range::create(410, "array index " + s + " exceeds size_type", BasicJsonType())); // LCOV_EXCL_LINE - } - - return static_cast(res); - } - - JSON_PRIVATE_UNLESS_TESTED: - json_pointer top() const - { - if (JSON_HEDLEY_UNLIKELY(empty())) - { - JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType())); - } - - json_pointer result = *this; - result.reference_tokens = {reference_tokens[0]}; - return result; - } - - private: - /*! - @brief create and return a reference to the pointed to value - - @complexity Linear in the number of reference tokens. - - @throw parse_error.109 if array index is not a number - @throw type_error.313 if value cannot be unflattened - */ - BasicJsonType& get_and_create(BasicJsonType& j) const - { - auto* result = &j; - - // in case no reference tokens exist, return a reference to the JSON value - // j which will be overwritten by a primitive value - for (const auto& reference_token : reference_tokens) - { - switch (result->type()) - { - case detail::value_t::null: - { - if (reference_token == "0") - { - // start a new array if reference token is 0 - result = &result->operator[](0); - } - else - { - // start a new object otherwise - result = &result->operator[](reference_token); - } - break; - } - - case detail::value_t::object: - { - // create an entry in the object - result = &result->operator[](reference_token); - break; - } - - case detail::value_t::array: - { - // create an entry in the array - result = &result->operator[](array_index(reference_token)); - break; - } - - /* - The following code is only reached if there exists a reference - token _and_ the current value is primitive. In this case, we have - an error situation, because primitive values may only occur as - single value; that is, with an empty list of reference tokens. - */ - case detail::value_t::string: - case detail::value_t::boolean: - case detail::value_t::number_integer: - case detail::value_t::number_unsigned: - case detail::value_t::number_float: - case detail::value_t::binary: - case detail::value_t::discarded: - default: - JSON_THROW(detail::type_error::create(313, "invalid value to unflatten", j)); - } - } - - return *result; - } - - /*! - @brief return a reference to the pointed to value - - @note This version does not throw if a value is not present, but tries to - create nested values instead. For instance, calling this function - with pointer `"/this/that"` on a null value is equivalent to calling - `operator[]("this").operator[]("that")` on that value, effectively - changing the null value to an object. - - @param[in] ptr a JSON value - - @return reference to the JSON value pointed to by the JSON pointer - - @complexity Linear in the length of the JSON pointer. - - @throw parse_error.106 if an array index begins with '0' - @throw parse_error.109 if an array index was not a number - @throw out_of_range.404 if the JSON pointer can not be resolved - */ - BasicJsonType& get_unchecked(BasicJsonType* ptr) const - { - for (const auto& reference_token : reference_tokens) - { - // convert null values to arrays or objects before continuing - if (ptr->is_null()) - { - // check if reference token is a number - const bool nums = - std::all_of(reference_token.begin(), reference_token.end(), - [](const unsigned char x) - { - return std::isdigit(x); - }); - - // change value to array for numbers or "-" or to object otherwise - *ptr = (nums || reference_token == "-") - ? detail::value_t::array - : detail::value_t::object; - } - - switch (ptr->type()) - { - case detail::value_t::object: - { - // use unchecked object access - ptr = &ptr->operator[](reference_token); - break; - } - - case detail::value_t::array: - { - if (reference_token == "-") - { - // explicitly treat "-" as index beyond the end - ptr = &ptr->operator[](ptr->m_value.array->size()); - } - else - { - // convert array index to number; unchecked access - ptr = &ptr->operator[](array_index(reference_token)); - } - break; - } - - case detail::value_t::null: - case detail::value_t::string: - case detail::value_t::boolean: - case detail::value_t::number_integer: - case detail::value_t::number_unsigned: - case detail::value_t::number_float: - case detail::value_t::binary: - case detail::value_t::discarded: - default: - JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); - } - } - - return *ptr; - } - - /*! - @throw parse_error.106 if an array index begins with '0' - @throw parse_error.109 if an array index was not a number - @throw out_of_range.402 if the array index '-' is used - @throw out_of_range.404 if the JSON pointer can not be resolved - */ - BasicJsonType& get_checked(BasicJsonType* ptr) const - { - for (const auto& reference_token : reference_tokens) - { - switch (ptr->type()) - { - case detail::value_t::object: - { - // note: at performs range check - ptr = &ptr->at(reference_token); - break; - } - - case detail::value_t::array: - { - if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) - { - // "-" always fails the range check - JSON_THROW(detail::out_of_range::create(402, - "array index '-' (" + std::to_string(ptr->m_value.array->size()) + - ") is out of range", *ptr)); - } - - // note: at performs range check - ptr = &ptr->at(array_index(reference_token)); - break; - } - - case detail::value_t::null: - case detail::value_t::string: - case detail::value_t::boolean: - case detail::value_t::number_integer: - case detail::value_t::number_unsigned: - case detail::value_t::number_float: - case detail::value_t::binary: - case detail::value_t::discarded: - default: - JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); - } - } - - return *ptr; - } - - /*! - @brief return a const reference to the pointed to value - - @param[in] ptr a JSON value - - @return const reference to the JSON value pointed to by the JSON - pointer - - @throw parse_error.106 if an array index begins with '0' - @throw parse_error.109 if an array index was not a number - @throw out_of_range.402 if the array index '-' is used - @throw out_of_range.404 if the JSON pointer can not be resolved - */ - const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const - { - for (const auto& reference_token : reference_tokens) - { - switch (ptr->type()) - { - case detail::value_t::object: - { - // use unchecked object access - ptr = &ptr->operator[](reference_token); - break; - } - - case detail::value_t::array: - { - if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) - { - // "-" cannot be used for const access - JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range", *ptr)); - } - - // use unchecked array access - ptr = &ptr->operator[](array_index(reference_token)); - break; - } - - case detail::value_t::null: - case detail::value_t::string: - case detail::value_t::boolean: - case detail::value_t::number_integer: - case detail::value_t::number_unsigned: - case detail::value_t::number_float: - case detail::value_t::binary: - case detail::value_t::discarded: - default: - JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); - } - } - - return *ptr; - } - - /*! - @throw parse_error.106 if an array index begins with '0' - @throw parse_error.109 if an array index was not a number - @throw out_of_range.402 if the array index '-' is used - @throw out_of_range.404 if the JSON pointer can not be resolved - */ - const BasicJsonType& get_checked(const BasicJsonType* ptr) const - { - for (const auto& reference_token : reference_tokens) - { - switch (ptr->type()) - { - case detail::value_t::object: - { - // note: at performs range check - ptr = &ptr->at(reference_token); - break; - } - - case detail::value_t::array: - { - if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) - { - // "-" always fails the range check - JSON_THROW(detail::out_of_range::create(402, - "array index '-' (" + std::to_string(ptr->m_value.array->size()) + - ") is out of range", *ptr)); - } - - // note: at performs range check - ptr = &ptr->at(array_index(reference_token)); - break; - } - - case detail::value_t::null: - case detail::value_t::string: - case detail::value_t::boolean: - case detail::value_t::number_integer: - case detail::value_t::number_unsigned: - case detail::value_t::number_float: - case detail::value_t::binary: - case detail::value_t::discarded: - default: - JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); - } - } - - return *ptr; - } - - /*! - @throw parse_error.106 if an array index begins with '0' - @throw parse_error.109 if an array index was not a number - */ - bool contains(const BasicJsonType* ptr) const - { - for (const auto& reference_token : reference_tokens) - { - switch (ptr->type()) - { - case detail::value_t::object: - { - if (!ptr->contains(reference_token)) - { - // we did not find the key in the object - return false; - } - - ptr = &ptr->operator[](reference_token); - break; - } - - case detail::value_t::array: - { - if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) - { - // "-" always fails the range check - return false; - } - if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 && !("0" <= reference_token && reference_token <= "9"))) - { - // invalid char - return false; - } - if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1)) - { - if (JSON_HEDLEY_UNLIKELY(!('1' <= reference_token[0] && reference_token[0] <= '9'))) - { - // first char should be between '1' and '9' - return false; - } - for (std::size_t i = 1; i < reference_token.size(); i++) - { - if (JSON_HEDLEY_UNLIKELY(!('0' <= reference_token[i] && reference_token[i] <= '9'))) - { - // other char should be between '0' and '9' - return false; - } - } - } - - const auto idx = array_index(reference_token); - if (idx >= ptr->size()) - { - // index out of range - return false; - } - - ptr = &ptr->operator[](idx); - break; - } - - case detail::value_t::null: - case detail::value_t::string: - case detail::value_t::boolean: - case detail::value_t::number_integer: - case detail::value_t::number_unsigned: - case detail::value_t::number_float: - case detail::value_t::binary: - case detail::value_t::discarded: - default: - { - // we do not expect primitive values if there is still a - // reference token to process - return false; - } - } - } - - // no reference token left means we found a primitive value - return true; - } - - /*! - @brief split the string input to reference tokens - - @note This function is only called by the json_pointer constructor. - All exceptions below are documented there. - - @throw parse_error.107 if the pointer is not empty or begins with '/' - @throw parse_error.108 if character '~' is not followed by '0' or '1' - */ - static std::vector split(const std::string& reference_string) - { - std::vector result; - - // special case: empty reference string -> no reference tokens - if (reference_string.empty()) - { - return result; - } - - // check if nonempty reference string begins with slash - if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/')) - { - JSON_THROW(detail::parse_error::create(107, 1, "JSON pointer must be empty or begin with '/' - was: '" + reference_string + "'", BasicJsonType())); - } - - // extract the reference tokens: - // - slash: position of the last read slash (or end of string) - // - start: position after the previous slash - for ( - // search for the first slash after the first character - std::size_t slash = reference_string.find_first_of('/', 1), - // set the beginning of the first reference token - start = 1; - // we can stop if start == 0 (if slash == std::string::npos) - start != 0; - // set the beginning of the next reference token - // (will eventually be 0 if slash == std::string::npos) - start = (slash == std::string::npos) ? 0 : slash + 1, - // find next slash - slash = reference_string.find_first_of('/', start)) - { - // use the text between the beginning of the reference token - // (start) and the last slash (slash). - auto reference_token = reference_string.substr(start, slash - start); - - // check reference tokens are properly escaped - for (std::size_t pos = reference_token.find_first_of('~'); - pos != std::string::npos; - pos = reference_token.find_first_of('~', pos + 1)) - { - JSON_ASSERT(reference_token[pos] == '~'); - - // ~ must be followed by 0 or 1 - if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 || - (reference_token[pos + 1] != '0' && - reference_token[pos + 1] != '1'))) - { - JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'", BasicJsonType())); - } - } - - // finally, store the reference token - detail::unescape(reference_token); - result.push_back(reference_token); - } - - return result; - } - - private: - /*! - @param[in] reference_string the reference string to the current value - @param[in] value the value to consider - @param[in,out] result the result object to insert values to - - @note Empty objects or arrays are flattened to `null`. - */ - static void flatten(const std::string& reference_string, - const BasicJsonType& value, - BasicJsonType& result) - { - switch (value.type()) - { - case detail::value_t::array: - { - if (value.m_value.array->empty()) - { - // flatten empty array as null - result[reference_string] = nullptr; - } - else - { - // iterate array and use index as reference string - for (std::size_t i = 0; i < value.m_value.array->size(); ++i) - { - flatten(reference_string + "/" + std::to_string(i), - value.m_value.array->operator[](i), result); - } - } - break; - } - - case detail::value_t::object: - { - if (value.m_value.object->empty()) - { - // flatten empty object as null - result[reference_string] = nullptr; - } - else - { - // iterate object and use keys as reference string - for (const auto& element : *value.m_value.object) - { - flatten(reference_string + "/" + detail::escape(element.first), element.second, result); - } - } - break; - } - - case detail::value_t::null: - case detail::value_t::string: - case detail::value_t::boolean: - case detail::value_t::number_integer: - case detail::value_t::number_unsigned: - case detail::value_t::number_float: - case detail::value_t::binary: - case detail::value_t::discarded: - default: - { - // add primitive value with its reference string - result[reference_string] = value; - break; - } - } - } - - /*! - @param[in] value flattened JSON - - @return unflattened JSON - - @throw parse_error.109 if array index is not a number - @throw type_error.314 if value is not an object - @throw type_error.315 if object values are not primitive - @throw type_error.313 if value cannot be unflattened - */ - static BasicJsonType - unflatten(const BasicJsonType& value) - { - if (JSON_HEDLEY_UNLIKELY(!value.is_object())) - { - JSON_THROW(detail::type_error::create(314, "only objects can be unflattened", value)); - } - - BasicJsonType result; - - // iterate the JSON object values - for (const auto& element : *value.m_value.object) - { - if (JSON_HEDLEY_UNLIKELY(!element.second.is_primitive())) - { - JSON_THROW(detail::type_error::create(315, "values in object must be primitive", element.second)); - } - - // assign value to reference pointed to by JSON pointer; Note that if - // the JSON pointer is "" (i.e., points to the whole value), function - // get_and_create returns a reference to result itself. An assignment - // will then create a primitive value. - json_pointer(element.first).get_and_create(result) = element.second; - } - - return result; - } - - /*! - @brief compares two JSON pointers for equality - - @param[in] lhs JSON pointer to compare - @param[in] rhs JSON pointer to compare - @return whether @a lhs is equal to @a rhs - - @complexity Linear in the length of the JSON pointer - - @exceptionsafety No-throw guarantee: this function never throws exceptions. - */ - friend bool operator==(json_pointer const& lhs, - json_pointer const& rhs) noexcept - { - return lhs.reference_tokens == rhs.reference_tokens; - } - - /*! - @brief compares two JSON pointers for inequality - - @param[in] lhs JSON pointer to compare - @param[in] rhs JSON pointer to compare - @return whether @a lhs is not equal @a rhs - - @complexity Linear in the length of the JSON pointer - - @exceptionsafety No-throw guarantee: this function never throws exceptions. - */ - friend bool operator!=(json_pointer const& lhs, - json_pointer const& rhs) noexcept - { - return !(lhs == rhs); - } - - /// the reference tokens - std::vector reference_tokens; -}; -} // namespace nlohmann - -// #include - - -#include -#include - -// #include - - -namespace nlohmann -{ -namespace detail -{ -template -class json_ref -{ - public: - using value_type = BasicJsonType; - - json_ref(value_type&& value) - : owned_value(std::move(value)) - {} - - json_ref(const value_type& value) - : value_ref(&value) - {} - - json_ref(std::initializer_list init) - : owned_value(init) - {} - - template < - class... Args, - enable_if_t::value, int> = 0 > - json_ref(Args && ... args) - : owned_value(std::forward(args)...) - {} - - // class should be movable only - json_ref(json_ref&&) noexcept = default; - json_ref(const json_ref&) = delete; - json_ref& operator=(const json_ref&) = delete; - json_ref& operator=(json_ref&&) = delete; - ~json_ref() = default; - - value_type moved_or_copied() const - { - if (value_ref == nullptr) - { - return std::move(owned_value); - } - return *value_ref; - } - - value_type const& operator*() const - { - return value_ref ? *value_ref : owned_value; - } - - value_type const* operator->() const - { - return &** this; - } - - private: - mutable value_type owned_value = nullptr; - value_type const* value_ref = nullptr; -}; -} // namespace detail -} // namespace nlohmann - -// #include - -// #include - -// #include - -// #include - -// #include - - -#include // reverse -#include // array -#include // isnan, isinf -#include // uint8_t, uint16_t, uint32_t, uint64_t -#include // memcpy -#include // numeric_limits -#include // string -#include // move - -// #include - -// #include - -// #include - - -#include // copy -#include // size_t -#include // back_inserter -#include // shared_ptr, make_shared -#include // basic_string -#include // vector - -#ifndef JSON_NO_IO - #include // streamsize - #include // basic_ostream -#endif // JSON_NO_IO - -// #include - - -namespace nlohmann -{ -namespace detail -{ -/// abstract output adapter interface -template struct output_adapter_protocol -{ - virtual void write_character(CharType c) = 0; - virtual void write_characters(const CharType* s, std::size_t length) = 0; - virtual ~output_adapter_protocol() = default; - - output_adapter_protocol() = default; - output_adapter_protocol(const output_adapter_protocol&) = default; - output_adapter_protocol(output_adapter_protocol&&) noexcept = default; - output_adapter_protocol& operator=(const output_adapter_protocol&) = default; - output_adapter_protocol& operator=(output_adapter_protocol&&) noexcept = default; -}; - -/// a type to simplify interfaces -template -using output_adapter_t = std::shared_ptr>; - -/// output adapter for byte vectors -template> -class output_vector_adapter : public output_adapter_protocol -{ - public: - explicit output_vector_adapter(std::vector& vec) noexcept - : v(vec) - {} - - void write_character(CharType c) override - { - v.push_back(c); - } - - JSON_HEDLEY_NON_NULL(2) - void write_characters(const CharType* s, std::size_t length) override - { - std::copy(s, s + length, std::back_inserter(v)); - } - - private: - std::vector& v; -}; - -#ifndef JSON_NO_IO -/// output adapter for output streams -template -class output_stream_adapter : public output_adapter_protocol -{ - public: - explicit output_stream_adapter(std::basic_ostream& s) noexcept - : stream(s) - {} - - void write_character(CharType c) override - { - stream.put(c); - } - - JSON_HEDLEY_NON_NULL(2) - void write_characters(const CharType* s, std::size_t length) override - { - stream.write(s, static_cast(length)); - } - - private: - std::basic_ostream& stream; -}; -#endif // JSON_NO_IO - -/// output adapter for basic_string -template> -class output_string_adapter : public output_adapter_protocol -{ - public: - explicit output_string_adapter(StringType& s) noexcept - : str(s) - {} - - void write_character(CharType c) override - { - str.push_back(c); - } - - JSON_HEDLEY_NON_NULL(2) - void write_characters(const CharType* s, std::size_t length) override - { - str.append(s, length); - } - - private: - StringType& str; -}; - -template> -class output_adapter -{ - public: - template> - output_adapter(std::vector& vec) - : oa(std::make_shared>(vec)) {} - -#ifndef JSON_NO_IO - output_adapter(std::basic_ostream& s) - : oa(std::make_shared>(s)) {} -#endif // JSON_NO_IO - - output_adapter(StringType& s) - : oa(std::make_shared>(s)) {} - - operator output_adapter_t() - { - return oa; - } - - private: - output_adapter_t oa = nullptr; -}; -} // namespace detail -} // namespace nlohmann - - -namespace nlohmann -{ -namespace detail -{ -/////////////////// -// binary writer // -/////////////////// - -/*! -@brief serialization to CBOR and MessagePack values -*/ -template -class binary_writer -{ - using string_t = typename BasicJsonType::string_t; - using binary_t = typename BasicJsonType::binary_t; - using number_float_t = typename BasicJsonType::number_float_t; - - public: - /*! - @brief create a binary writer - - @param[in] adapter output adapter to write to - */ - explicit binary_writer(output_adapter_t adapter) : oa(std::move(adapter)) - { - JSON_ASSERT(oa); - } - - /*! - @param[in] j JSON value to serialize - @pre j.type() == value_t::object - */ - void write_bson(const BasicJsonType& j) - { - switch (j.type()) - { - case value_t::object: - { - write_bson_object(*j.m_value.object); - break; - } - - case value_t::null: - case value_t::array: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name()), j)); - } - } - } - - /*! - @param[in] j JSON value to serialize - */ - void write_cbor(const BasicJsonType& j) - { - switch (j.type()) - { - case value_t::null: - { - oa->write_character(to_char_type(0xF6)); - break; - } - - case value_t::boolean: - { - oa->write_character(j.m_value.boolean - ? to_char_type(0xF5) - : to_char_type(0xF4)); - break; - } - - case value_t::number_integer: - { - if (j.m_value.number_integer >= 0) - { - // CBOR does not differentiate between positive signed - // integers and unsigned integers. Therefore, we used the - // code from the value_t::number_unsigned case here. - if (j.m_value.number_integer <= 0x17) - { - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_integer <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x18)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_integer <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x19)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_integer <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x1A)); - write_number(static_cast(j.m_value.number_integer)); - } - else - { - oa->write_character(to_char_type(0x1B)); - write_number(static_cast(j.m_value.number_integer)); - } - } - else - { - // The conversions below encode the sign in the first - // byte, and the value is converted to a positive number. - const auto positive_number = -1 - j.m_value.number_integer; - if (j.m_value.number_integer >= -24) - { - write_number(static_cast(0x20 + positive_number)); - } - else if (positive_number <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x38)); - write_number(static_cast(positive_number)); - } - else if (positive_number <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x39)); - write_number(static_cast(positive_number)); - } - else if (positive_number <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x3A)); - write_number(static_cast(positive_number)); - } - else - { - oa->write_character(to_char_type(0x3B)); - write_number(static_cast(positive_number)); - } - } - break; - } - - case value_t::number_unsigned: - { - if (j.m_value.number_unsigned <= 0x17) - { - write_number(static_cast(j.m_value.number_unsigned)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x18)); - write_number(static_cast(j.m_value.number_unsigned)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x19)); - write_number(static_cast(j.m_value.number_unsigned)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x1A)); - write_number(static_cast(j.m_value.number_unsigned)); - } - else - { - oa->write_character(to_char_type(0x1B)); - write_number(static_cast(j.m_value.number_unsigned)); - } - break; - } - - case value_t::number_float: - { - if (std::isnan(j.m_value.number_float)) - { - // NaN is 0xf97e00 in CBOR - oa->write_character(to_char_type(0xF9)); - oa->write_character(to_char_type(0x7E)); - oa->write_character(to_char_type(0x00)); - } - else if (std::isinf(j.m_value.number_float)) - { - // Infinity is 0xf97c00, -Infinity is 0xf9fc00 - oa->write_character(to_char_type(0xf9)); - oa->write_character(j.m_value.number_float > 0 ? to_char_type(0x7C) : to_char_type(0xFC)); - oa->write_character(to_char_type(0x00)); - } - else - { - write_compact_float(j.m_value.number_float, detail::input_format_t::cbor); - } - break; - } - - case value_t::string: - { - // step 1: write control byte and the string length - const auto N = j.m_value.string->size(); - if (N <= 0x17) - { - write_number(static_cast(0x60 + N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x78)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x79)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x7A)); - write_number(static_cast(N)); - } - // LCOV_EXCL_START - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x7B)); - write_number(static_cast(N)); - } - // LCOV_EXCL_STOP - - // step 2: write the string - oa->write_characters( - reinterpret_cast(j.m_value.string->c_str()), - j.m_value.string->size()); - break; - } - - case value_t::array: - { - // step 1: write control byte and the array size - const auto N = j.m_value.array->size(); - if (N <= 0x17) - { - write_number(static_cast(0x80 + N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x98)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x99)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x9A)); - write_number(static_cast(N)); - } - // LCOV_EXCL_START - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x9B)); - write_number(static_cast(N)); - } - // LCOV_EXCL_STOP - - // step 2: write each element - for (const auto& el : *j.m_value.array) - { - write_cbor(el); - } - break; - } - - case value_t::binary: - { - if (j.m_value.binary->has_subtype()) - { - if (j.m_value.binary->subtype() <= (std::numeric_limits::max)()) - { - write_number(static_cast(0xd8)); - write_number(static_cast(j.m_value.binary->subtype())); - } - else if (j.m_value.binary->subtype() <= (std::numeric_limits::max)()) - { - write_number(static_cast(0xd9)); - write_number(static_cast(j.m_value.binary->subtype())); - } - else if (j.m_value.binary->subtype() <= (std::numeric_limits::max)()) - { - write_number(static_cast(0xda)); - write_number(static_cast(j.m_value.binary->subtype())); - } - else if (j.m_value.binary->subtype() <= (std::numeric_limits::max)()) - { - write_number(static_cast(0xdb)); - write_number(static_cast(j.m_value.binary->subtype())); - } - } - - // step 1: write control byte and the binary array size - const auto N = j.m_value.binary->size(); - if (N <= 0x17) - { - write_number(static_cast(0x40 + N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x58)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x59)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x5A)); - write_number(static_cast(N)); - } - // LCOV_EXCL_START - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x5B)); - write_number(static_cast(N)); - } - // LCOV_EXCL_STOP - - // step 2: write each element - oa->write_characters( - reinterpret_cast(j.m_value.binary->data()), - N); - - break; - } - - case value_t::object: - { - // step 1: write control byte and the object size - const auto N = j.m_value.object->size(); - if (N <= 0x17) - { - write_number(static_cast(0xA0 + N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0xB8)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0xB9)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0xBA)); - write_number(static_cast(N)); - } - // LCOV_EXCL_START - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0xBB)); - write_number(static_cast(N)); - } - // LCOV_EXCL_STOP - - // step 2: write each element - for (const auto& el : *j.m_value.object) - { - write_cbor(el.first); - write_cbor(el.second); - } - break; - } - - case value_t::discarded: - default: - break; - } - } - - /*! - @param[in] j JSON value to serialize - */ - void write_msgpack(const BasicJsonType& j) - { - switch (j.type()) - { - case value_t::null: // nil - { - oa->write_character(to_char_type(0xC0)); - break; - } - - case value_t::boolean: // true and false - { - oa->write_character(j.m_value.boolean - ? to_char_type(0xC3) - : to_char_type(0xC2)); - break; - } - - case value_t::number_integer: - { - if (j.m_value.number_integer >= 0) - { - // MessagePack does not differentiate between positive - // signed integers and unsigned integers. Therefore, we used - // the code from the value_t::number_unsigned case here. - if (j.m_value.number_unsigned < 128) - { - // positive fixnum - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - // uint 8 - oa->write_character(to_char_type(0xCC)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - // uint 16 - oa->write_character(to_char_type(0xCD)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - // uint 32 - oa->write_character(to_char_type(0xCE)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - // uint 64 - oa->write_character(to_char_type(0xCF)); - write_number(static_cast(j.m_value.number_integer)); - } - } - else - { - if (j.m_value.number_integer >= -32) - { - // negative fixnum - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_integer >= (std::numeric_limits::min)() && - j.m_value.number_integer <= (std::numeric_limits::max)()) - { - // int 8 - oa->write_character(to_char_type(0xD0)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_integer >= (std::numeric_limits::min)() && - j.m_value.number_integer <= (std::numeric_limits::max)()) - { - // int 16 - oa->write_character(to_char_type(0xD1)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_integer >= (std::numeric_limits::min)() && - j.m_value.number_integer <= (std::numeric_limits::max)()) - { - // int 32 - oa->write_character(to_char_type(0xD2)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_integer >= (std::numeric_limits::min)() && - j.m_value.number_integer <= (std::numeric_limits::max)()) - { - // int 64 - oa->write_character(to_char_type(0xD3)); - write_number(static_cast(j.m_value.number_integer)); - } - } - break; - } - - case value_t::number_unsigned: - { - if (j.m_value.number_unsigned < 128) - { - // positive fixnum - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - // uint 8 - oa->write_character(to_char_type(0xCC)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - // uint 16 - oa->write_character(to_char_type(0xCD)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - // uint 32 - oa->write_character(to_char_type(0xCE)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - // uint 64 - oa->write_character(to_char_type(0xCF)); - write_number(static_cast(j.m_value.number_integer)); - } - break; - } - - case value_t::number_float: - { - write_compact_float(j.m_value.number_float, detail::input_format_t::msgpack); - break; - } - - case value_t::string: - { - // step 1: write control byte and the string length - const auto N = j.m_value.string->size(); - if (N <= 31) - { - // fixstr - write_number(static_cast(0xA0 | N)); - } - else if (N <= (std::numeric_limits::max)()) - { - // str 8 - oa->write_character(to_char_type(0xD9)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - // str 16 - oa->write_character(to_char_type(0xDA)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - // str 32 - oa->write_character(to_char_type(0xDB)); - write_number(static_cast(N)); - } - - // step 2: write the string - oa->write_characters( - reinterpret_cast(j.m_value.string->c_str()), - j.m_value.string->size()); - break; - } - - case value_t::array: - { - // step 1: write control byte and the array size - const auto N = j.m_value.array->size(); - if (N <= 15) - { - // fixarray - write_number(static_cast(0x90 | N)); - } - else if (N <= (std::numeric_limits::max)()) - { - // array 16 - oa->write_character(to_char_type(0xDC)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - // array 32 - oa->write_character(to_char_type(0xDD)); - write_number(static_cast(N)); - } - - // step 2: write each element - for (const auto& el : *j.m_value.array) - { - write_msgpack(el); - } - break; - } - - case value_t::binary: - { - // step 0: determine if the binary type has a set subtype to - // determine whether or not to use the ext or fixext types - const bool use_ext = j.m_value.binary->has_subtype(); - - // step 1: write control byte and the byte string length - const auto N = j.m_value.binary->size(); - if (N <= (std::numeric_limits::max)()) - { - std::uint8_t output_type{}; - bool fixed = true; - if (use_ext) - { - switch (N) - { - case 1: - output_type = 0xD4; // fixext 1 - break; - case 2: - output_type = 0xD5; // fixext 2 - break; - case 4: - output_type = 0xD6; // fixext 4 - break; - case 8: - output_type = 0xD7; // fixext 8 - break; - case 16: - output_type = 0xD8; // fixext 16 - break; - default: - output_type = 0xC7; // ext 8 - fixed = false; - break; - } - - } - else - { - output_type = 0xC4; // bin 8 - fixed = false; - } - - oa->write_character(to_char_type(output_type)); - if (!fixed) - { - write_number(static_cast(N)); - } - } - else if (N <= (std::numeric_limits::max)()) - { - std::uint8_t output_type = use_ext - ? 0xC8 // ext 16 - : 0xC5; // bin 16 - - oa->write_character(to_char_type(output_type)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - std::uint8_t output_type = use_ext - ? 0xC9 // ext 32 - : 0xC6; // bin 32 - - oa->write_character(to_char_type(output_type)); - write_number(static_cast(N)); - } - - // step 1.5: if this is an ext type, write the subtype - if (use_ext) - { - write_number(static_cast(j.m_value.binary->subtype())); - } - - // step 2: write the byte string - oa->write_characters( - reinterpret_cast(j.m_value.binary->data()), - N); - - break; - } - - case value_t::object: - { - // step 1: write control byte and the object size - const auto N = j.m_value.object->size(); - if (N <= 15) - { - // fixmap - write_number(static_cast(0x80 | (N & 0xF))); - } - else if (N <= (std::numeric_limits::max)()) - { - // map 16 - oa->write_character(to_char_type(0xDE)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - // map 32 - oa->write_character(to_char_type(0xDF)); - write_number(static_cast(N)); - } - - // step 2: write each element - for (const auto& el : *j.m_value.object) - { - write_msgpack(el.first); - write_msgpack(el.second); - } - break; - } - - case value_t::discarded: - default: - break; - } - } - - /*! - @param[in] j JSON value to serialize - @param[in] use_count whether to use '#' prefixes (optimized format) - @param[in] use_type whether to use '$' prefixes (optimized format) - @param[in] add_prefix whether prefixes need to be used for this value - */ - void write_ubjson(const BasicJsonType& j, const bool use_count, - const bool use_type, const bool add_prefix = true) - { - switch (j.type()) - { - case value_t::null: - { - if (add_prefix) - { - oa->write_character(to_char_type('Z')); - } - break; - } - - case value_t::boolean: - { - if (add_prefix) - { - oa->write_character(j.m_value.boolean - ? to_char_type('T') - : to_char_type('F')); - } - break; - } - - case value_t::number_integer: - { - write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix); - break; - } - - case value_t::number_unsigned: - { - write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix); - break; - } - - case value_t::number_float: - { - write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix); - break; - } - - case value_t::string: - { - if (add_prefix) - { - oa->write_character(to_char_type('S')); - } - write_number_with_ubjson_prefix(j.m_value.string->size(), true); - oa->write_characters( - reinterpret_cast(j.m_value.string->c_str()), - j.m_value.string->size()); - break; - } - - case value_t::array: - { - if (add_prefix) - { - oa->write_character(to_char_type('[')); - } - - bool prefix_required = true; - if (use_type && !j.m_value.array->empty()) - { - JSON_ASSERT(use_count); - const CharType first_prefix = ubjson_prefix(j.front()); - const bool same_prefix = std::all_of(j.begin() + 1, j.end(), - [this, first_prefix](const BasicJsonType & v) - { - return ubjson_prefix(v) == first_prefix; - }); - - if (same_prefix) - { - prefix_required = false; - oa->write_character(to_char_type('$')); - oa->write_character(first_prefix); - } - } - - if (use_count) - { - oa->write_character(to_char_type('#')); - write_number_with_ubjson_prefix(j.m_value.array->size(), true); - } - - for (const auto& el : *j.m_value.array) - { - write_ubjson(el, use_count, use_type, prefix_required); - } - - if (!use_count) - { - oa->write_character(to_char_type(']')); - } - - break; - } - - case value_t::binary: - { - if (add_prefix) - { - oa->write_character(to_char_type('[')); - } - - if (use_type && !j.m_value.binary->empty()) - { - JSON_ASSERT(use_count); - oa->write_character(to_char_type('$')); - oa->write_character('U'); - } - - if (use_count) - { - oa->write_character(to_char_type('#')); - write_number_with_ubjson_prefix(j.m_value.binary->size(), true); - } - - if (use_type) - { - oa->write_characters( - reinterpret_cast(j.m_value.binary->data()), - j.m_value.binary->size()); - } - else - { - for (size_t i = 0; i < j.m_value.binary->size(); ++i) - { - oa->write_character(to_char_type('U')); - oa->write_character(j.m_value.binary->data()[i]); - } - } - - if (!use_count) - { - oa->write_character(to_char_type(']')); - } - - break; - } - - case value_t::object: - { - if (add_prefix) - { - oa->write_character(to_char_type('{')); - } - - bool prefix_required = true; - if (use_type && !j.m_value.object->empty()) - { - JSON_ASSERT(use_count); - const CharType first_prefix = ubjson_prefix(j.front()); - const bool same_prefix = std::all_of(j.begin(), j.end(), - [this, first_prefix](const BasicJsonType & v) - { - return ubjson_prefix(v) == first_prefix; - }); - - if (same_prefix) - { - prefix_required = false; - oa->write_character(to_char_type('$')); - oa->write_character(first_prefix); - } - } - - if (use_count) - { - oa->write_character(to_char_type('#')); - write_number_with_ubjson_prefix(j.m_value.object->size(), true); - } - - for (const auto& el : *j.m_value.object) - { - write_number_with_ubjson_prefix(el.first.size(), true); - oa->write_characters( - reinterpret_cast(el.first.c_str()), - el.first.size()); - write_ubjson(el.second, use_count, use_type, prefix_required); - } - - if (!use_count) - { - oa->write_character(to_char_type('}')); - } - - break; - } - - case value_t::discarded: - default: - break; - } - } - - private: - ////////// - // BSON // - ////////// - - /*! - @return The size of a BSON document entry header, including the id marker - and the entry name size (and its null-terminator). - */ - static std::size_t calc_bson_entry_header_size(const string_t& name, const BasicJsonType& j) - { - const auto it = name.find(static_cast(0)); - if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos)) - { - JSON_THROW(out_of_range::create(409, "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")", j)); - static_cast(j); - } - - return /*id*/ 1ul + name.size() + /*zero-terminator*/1u; - } - - /*! - @brief Writes the given @a element_type and @a name to the output adapter - */ - void write_bson_entry_header(const string_t& name, - const std::uint8_t element_type) - { - oa->write_character(to_char_type(element_type)); // boolean - oa->write_characters( - reinterpret_cast(name.c_str()), - name.size() + 1u); - } - - /*! - @brief Writes a BSON element with key @a name and boolean value @a value - */ - void write_bson_boolean(const string_t& name, - const bool value) - { - write_bson_entry_header(name, 0x08); - oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00)); - } - - /*! - @brief Writes a BSON element with key @a name and double value @a value - */ - void write_bson_double(const string_t& name, - const double value) - { - write_bson_entry_header(name, 0x01); - write_number(value); - } - - /*! - @return The size of the BSON-encoded string in @a value - */ - static std::size_t calc_bson_string_size(const string_t& value) - { - return sizeof(std::int32_t) + value.size() + 1ul; - } - - /*! - @brief Writes a BSON element with key @a name and string value @a value - */ - void write_bson_string(const string_t& name, - const string_t& value) - { - write_bson_entry_header(name, 0x02); - - write_number(static_cast(value.size() + 1ul)); - oa->write_characters( - reinterpret_cast(value.c_str()), - value.size() + 1); - } - - /*! - @brief Writes a BSON element with key @a name and null value - */ - void write_bson_null(const string_t& name) - { - write_bson_entry_header(name, 0x0A); - } - - /*! - @return The size of the BSON-encoded integer @a value - */ - static std::size_t calc_bson_integer_size(const std::int64_t value) - { - return (std::numeric_limits::min)() <= value && value <= (std::numeric_limits::max)() - ? sizeof(std::int32_t) - : sizeof(std::int64_t); - } - - /*! - @brief Writes a BSON element with key @a name and integer @a value - */ - void write_bson_integer(const string_t& name, - const std::int64_t value) - { - if ((std::numeric_limits::min)() <= value && value <= (std::numeric_limits::max)()) - { - write_bson_entry_header(name, 0x10); // int32 - write_number(static_cast(value)); - } - else - { - write_bson_entry_header(name, 0x12); // int64 - write_number(static_cast(value)); - } - } - - /*! - @return The size of the BSON-encoded unsigned integer in @a j - */ - static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept - { - return (value <= static_cast((std::numeric_limits::max)())) - ? sizeof(std::int32_t) - : sizeof(std::int64_t); - } - - /*! - @brief Writes a BSON element with key @a name and unsigned @a value - */ - void write_bson_unsigned(const string_t& name, - const BasicJsonType& j) - { - if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) - { - write_bson_entry_header(name, 0x10 /* int32 */); - write_number(static_cast(j.m_value.number_unsigned)); - } - else if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) - { - write_bson_entry_header(name, 0x12 /* int64 */); - write_number(static_cast(j.m_value.number_unsigned)); - } - else - { - JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(j.m_value.number_unsigned) + " cannot be represented by BSON as it does not fit int64", j)); - } - } - - /*! - @brief Writes a BSON element with key @a name and object @a value - */ - void write_bson_object_entry(const string_t& name, - const typename BasicJsonType::object_t& value) - { - write_bson_entry_header(name, 0x03); // object - write_bson_object(value); - } - - /*! - @return The size of the BSON-encoded array @a value - */ - static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value) - { - std::size_t array_index = 0ul; - - const std::size_t embedded_document_size = std::accumulate(std::begin(value), std::end(value), static_cast(0), [&array_index](std::size_t result, const typename BasicJsonType::array_t::value_type & el) - { - return result + calc_bson_element_size(std::to_string(array_index++), el); - }); - - return sizeof(std::int32_t) + embedded_document_size + 1ul; - } - - /*! - @return The size of the BSON-encoded binary array @a value - */ - static std::size_t calc_bson_binary_size(const typename BasicJsonType::binary_t& value) - { - return sizeof(std::int32_t) + value.size() + 1ul; - } - - /*! - @brief Writes a BSON element with key @a name and array @a value - */ - void write_bson_array(const string_t& name, - const typename BasicJsonType::array_t& value) - { - write_bson_entry_header(name, 0x04); // array - write_number(static_cast(calc_bson_array_size(value))); - - std::size_t array_index = 0ul; - - for (const auto& el : value) - { - write_bson_element(std::to_string(array_index++), el); - } - - oa->write_character(to_char_type(0x00)); - } - - /*! - @brief Writes a BSON element with key @a name and binary value @a value - */ - void write_bson_binary(const string_t& name, - const binary_t& value) - { - write_bson_entry_header(name, 0x05); - - write_number(static_cast(value.size())); - write_number(value.has_subtype() ? static_cast(value.subtype()) : static_cast(0x00)); - - oa->write_characters(reinterpret_cast(value.data()), value.size()); - } - - /*! - @brief Calculates the size necessary to serialize the JSON value @a j with its @a name - @return The calculated size for the BSON document entry for @a j with the given @a name. - */ - static std::size_t calc_bson_element_size(const string_t& name, - const BasicJsonType& j) - { - const auto header_size = calc_bson_entry_header_size(name, j); - switch (j.type()) - { - case value_t::object: - return header_size + calc_bson_object_size(*j.m_value.object); - - case value_t::array: - return header_size + calc_bson_array_size(*j.m_value.array); - - case value_t::binary: - return header_size + calc_bson_binary_size(*j.m_value.binary); - - case value_t::boolean: - return header_size + 1ul; - - case value_t::number_float: - return header_size + 8ul; - - case value_t::number_integer: - return header_size + calc_bson_integer_size(j.m_value.number_integer); - - case value_t::number_unsigned: - return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned); - - case value_t::string: - return header_size + calc_bson_string_size(*j.m_value.string); - - case value_t::null: - return header_size + 0ul; - - // LCOV_EXCL_START - case value_t::discarded: - default: - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) - return 0ul; - // LCOV_EXCL_STOP - } - } - - /*! - @brief Serializes the JSON value @a j to BSON and associates it with the - key @a name. - @param name The name to associate with the JSON entity @a j within the - current BSON document - */ - void write_bson_element(const string_t& name, - const BasicJsonType& j) - { - switch (j.type()) - { - case value_t::object: - return write_bson_object_entry(name, *j.m_value.object); - - case value_t::array: - return write_bson_array(name, *j.m_value.array); - - case value_t::binary: - return write_bson_binary(name, *j.m_value.binary); - - case value_t::boolean: - return write_bson_boolean(name, j.m_value.boolean); - - case value_t::number_float: - return write_bson_double(name, j.m_value.number_float); - - case value_t::number_integer: - return write_bson_integer(name, j.m_value.number_integer); - - case value_t::number_unsigned: - return write_bson_unsigned(name, j); - - case value_t::string: - return write_bson_string(name, *j.m_value.string); - - case value_t::null: - return write_bson_null(name); - - // LCOV_EXCL_START - case value_t::discarded: - default: - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) - return; - // LCOV_EXCL_STOP - } - } - - /*! - @brief Calculates the size of the BSON serialization of the given - JSON-object @a j. - @param[in] value JSON value to serialize - @pre value.type() == value_t::object - */ - static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value) - { - std::size_t document_size = std::accumulate(value.begin(), value.end(), static_cast(0), - [](size_t result, const typename BasicJsonType::object_t::value_type & el) - { - return result += calc_bson_element_size(el.first, el.second); - }); - - return sizeof(std::int32_t) + document_size + 1ul; - } - - /*! - @param[in] value JSON value to serialize - @pre value.type() == value_t::object - */ - void write_bson_object(const typename BasicJsonType::object_t& value) - { - write_number(static_cast(calc_bson_object_size(value))); - - for (const auto& el : value) - { - write_bson_element(el.first, el.second); - } - - oa->write_character(to_char_type(0x00)); - } - - ////////// - // CBOR // - ////////// - - static constexpr CharType get_cbor_float_prefix(float /*unused*/) - { - return to_char_type(0xFA); // Single-Precision Float - } - - static constexpr CharType get_cbor_float_prefix(double /*unused*/) - { - return to_char_type(0xFB); // Double-Precision Float - } - - ///////////// - // MsgPack // - ///////////// - - static constexpr CharType get_msgpack_float_prefix(float /*unused*/) - { - return to_char_type(0xCA); // float 32 - } - - static constexpr CharType get_msgpack_float_prefix(double /*unused*/) - { - return to_char_type(0xCB); // float 64 - } - - //////////// - // UBJSON // - //////////// - - // UBJSON: write number (floating point) - template::value, int>::type = 0> - void write_number_with_ubjson_prefix(const NumberType n, - const bool add_prefix) - { - if (add_prefix) - { - oa->write_character(get_ubjson_float_prefix(n)); - } - write_number(n); - } - - // UBJSON: write number (unsigned integer) - template::value, int>::type = 0> - void write_number_with_ubjson_prefix(const NumberType n, - const bool add_prefix) - { - if (n <= static_cast((std::numeric_limits::max)())) - { - if (add_prefix) - { - oa->write_character(to_char_type('i')); // int8 - } - write_number(static_cast(n)); - } - else if (n <= (std::numeric_limits::max)()) - { - if (add_prefix) - { - oa->write_character(to_char_type('U')); // uint8 - } - write_number(static_cast(n)); - } - else if (n <= static_cast((std::numeric_limits::max)())) - { - if (add_prefix) - { - oa->write_character(to_char_type('I')); // int16 - } - write_number(static_cast(n)); - } - else if (n <= static_cast((std::numeric_limits::max)())) - { - if (add_prefix) - { - oa->write_character(to_char_type('l')); // int32 - } - write_number(static_cast(n)); - } - else if (n <= static_cast((std::numeric_limits::max)())) - { - if (add_prefix) - { - oa->write_character(to_char_type('L')); // int64 - } - write_number(static_cast(n)); - } - else - { - if (add_prefix) - { - oa->write_character(to_char_type('H')); // high-precision number - } - - const auto number = BasicJsonType(n).dump(); - write_number_with_ubjson_prefix(number.size(), true); - for (std::size_t i = 0; i < number.size(); ++i) - { - oa->write_character(to_char_type(static_cast(number[i]))); - } - } - } - - // UBJSON: write number (signed integer) - template < typename NumberType, typename std::enable_if < - std::is_signed::value&& - !std::is_floating_point::value, int >::type = 0 > - void write_number_with_ubjson_prefix(const NumberType n, - const bool add_prefix) - { - if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) - { - if (add_prefix) - { - oa->write_character(to_char_type('i')); // int8 - } - write_number(static_cast(n)); - } - else if (static_cast((std::numeric_limits::min)()) <= n && n <= static_cast((std::numeric_limits::max)())) - { - if (add_prefix) - { - oa->write_character(to_char_type('U')); // uint8 - } - write_number(static_cast(n)); - } - else if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) - { - if (add_prefix) - { - oa->write_character(to_char_type('I')); // int16 - } - write_number(static_cast(n)); - } - else if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) - { - if (add_prefix) - { - oa->write_character(to_char_type('l')); // int32 - } - write_number(static_cast(n)); - } - else if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) - { - if (add_prefix) - { - oa->write_character(to_char_type('L')); // int64 - } - write_number(static_cast(n)); - } - // LCOV_EXCL_START - else - { - if (add_prefix) - { - oa->write_character(to_char_type('H')); // high-precision number - } - - const auto number = BasicJsonType(n).dump(); - write_number_with_ubjson_prefix(number.size(), true); - for (std::size_t i = 0; i < number.size(); ++i) - { - oa->write_character(to_char_type(static_cast(number[i]))); - } - } - // LCOV_EXCL_STOP - } - - /*! - @brief determine the type prefix of container values - */ - CharType ubjson_prefix(const BasicJsonType& j) const noexcept - { - switch (j.type()) - { - case value_t::null: - return 'Z'; - - case value_t::boolean: - return j.m_value.boolean ? 'T' : 'F'; - - case value_t::number_integer: - { - if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) - { - return 'i'; - } - if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) - { - return 'U'; - } - if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) - { - return 'I'; - } - if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) - { - return 'l'; - } - if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) - { - return 'L'; - } - // anything else is treated as high-precision number - return 'H'; // LCOV_EXCL_LINE - } - - case value_t::number_unsigned: - { - if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) - { - return 'i'; - } - if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) - { - return 'U'; - } - if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) - { - return 'I'; - } - if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) - { - return 'l'; - } - if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) - { - return 'L'; - } - // anything else is treated as high-precision number - return 'H'; // LCOV_EXCL_LINE - } - - case value_t::number_float: - return get_ubjson_float_prefix(j.m_value.number_float); - - case value_t::string: - return 'S'; - - case value_t::array: // fallthrough - case value_t::binary: - return '['; - - case value_t::object: - return '{'; - - case value_t::discarded: - default: // discarded values - return 'N'; - } - } - - static constexpr CharType get_ubjson_float_prefix(float /*unused*/) - { - return 'd'; // float 32 - } - - static constexpr CharType get_ubjson_float_prefix(double /*unused*/) - { - return 'D'; // float 64 - } - - /////////////////////// - // Utility functions // - /////////////////////// - - /* - @brief write a number to output input - @param[in] n number of type @a NumberType - @tparam NumberType the type of the number - @tparam OutputIsLittleEndian Set to true if output data is - required to be little endian - - @note This function needs to respect the system's endianness, because bytes - in CBOR, MessagePack, and UBJSON are stored in network order (big - endian) and therefore need reordering on little endian systems. - */ - template - void write_number(const NumberType n) - { - // step 1: write number to array of length NumberType - std::array vec{}; - std::memcpy(vec.data(), &n, sizeof(NumberType)); - - // step 2: write array to output (with possible reordering) - if (is_little_endian != OutputIsLittleEndian) - { - // reverse byte order prior to conversion if necessary - std::reverse(vec.begin(), vec.end()); - } - - oa->write_characters(vec.data(), sizeof(NumberType)); - } - - void write_compact_float(const number_float_t n, detail::input_format_t format) - { -#ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wfloat-equal" -#endif - if (static_cast(n) >= static_cast(std::numeric_limits::lowest()) && - static_cast(n) <= static_cast((std::numeric_limits::max)()) && - static_cast(static_cast(n)) == static_cast(n)) - { - oa->write_character(format == detail::input_format_t::cbor - ? get_cbor_float_prefix(static_cast(n)) - : get_msgpack_float_prefix(static_cast(n))); - write_number(static_cast(n)); - } - else - { - oa->write_character(format == detail::input_format_t::cbor - ? get_cbor_float_prefix(n) - : get_msgpack_float_prefix(n)); - write_number(n); - } -#ifdef __GNUC__ -#pragma GCC diagnostic pop -#endif - } - - public: - // The following to_char_type functions are implement the conversion - // between uint8_t and CharType. In case CharType is not unsigned, - // such a conversion is required to allow values greater than 128. - // See for a discussion. - template < typename C = CharType, - enable_if_t < std::is_signed::value && std::is_signed::value > * = nullptr > - static constexpr CharType to_char_type(std::uint8_t x) noexcept - { - return *reinterpret_cast(&x); - } - - template < typename C = CharType, - enable_if_t < std::is_signed::value && std::is_unsigned::value > * = nullptr > - static CharType to_char_type(std::uint8_t x) noexcept - { - static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t"); - static_assert(std::is_trivial::value, "CharType must be trivial"); - CharType result; - std::memcpy(&result, &x, sizeof(x)); - return result; - } - - template::value>* = nullptr> - static constexpr CharType to_char_type(std::uint8_t x) noexcept - { - return x; - } - - template < typename InputCharType, typename C = CharType, - enable_if_t < - std::is_signed::value && - std::is_signed::value && - std::is_same::type>::value - > * = nullptr > - static constexpr CharType to_char_type(InputCharType x) noexcept - { - return x; - } - - private: - /// whether we can assume little endianness - const bool is_little_endian = little_endianness(); - - /// the output - output_adapter_t oa = nullptr; -}; -} // namespace detail -} // namespace nlohmann - -// #include - -// #include - - -#include // reverse, remove, fill, find, none_of -#include // array -#include // localeconv, lconv -#include // labs, isfinite, isnan, signbit -#include // size_t, ptrdiff_t -#include // uint8_t -#include // snprintf -#include // numeric_limits -#include // string, char_traits -#include // setfill, setw -#include // stringstream -#include // is_same -#include // move - -// #include - - -#include // array -#include // signbit, isfinite -#include // intN_t, uintN_t -#include // memcpy, memmove -#include // numeric_limits -#include // conditional - -// #include - - -namespace nlohmann -{ -namespace detail -{ - -/*! -@brief implements the Grisu2 algorithm for binary to decimal floating-point -conversion. - -This implementation is a slightly modified version of the reference -implementation which may be obtained from -http://florian.loitsch.com/publications (bench.tar.gz). - -The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch. - -For a detailed description of the algorithm see: - -[1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with - Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming - Language Design and Implementation, PLDI 2010 -[2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately", - Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language - Design and Implementation, PLDI 1996 -*/ -namespace dtoa_impl -{ - -template -Target reinterpret_bits(const Source source) -{ - static_assert(sizeof(Target) == sizeof(Source), "size mismatch"); - - Target target; - std::memcpy(&target, &source, sizeof(Source)); - return target; -} - -struct diyfp // f * 2^e -{ - static constexpr int kPrecision = 64; // = q - - std::uint64_t f = 0; - int e = 0; - - constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {} - - /*! - @brief returns x - y - @pre x.e == y.e and x.f >= y.f - */ - static diyfp sub(const diyfp& x, const diyfp& y) noexcept - { - JSON_ASSERT(x.e == y.e); - JSON_ASSERT(x.f >= y.f); - - return {x.f - y.f, x.e}; - } - - /*! - @brief returns x * y - @note The result is rounded. (Only the upper q bits are returned.) - */ - static diyfp mul(const diyfp& x, const diyfp& y) noexcept - { - static_assert(kPrecision == 64, "internal error"); - - // Computes: - // f = round((x.f * y.f) / 2^q) - // e = x.e + y.e + q - - // Emulate the 64-bit * 64-bit multiplication: - // - // p = u * v - // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi) - // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi ) - // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 ) - // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 ) - // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3) - // = (p0_lo ) + 2^32 (Q ) + 2^64 (H ) - // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H ) - // - // (Since Q might be larger than 2^32 - 1) - // - // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H) - // - // (Q_hi + H does not overflow a 64-bit int) - // - // = p_lo + 2^64 p_hi - - const std::uint64_t u_lo = x.f & 0xFFFFFFFFu; - const std::uint64_t u_hi = x.f >> 32u; - const std::uint64_t v_lo = y.f & 0xFFFFFFFFu; - const std::uint64_t v_hi = y.f >> 32u; - - const std::uint64_t p0 = u_lo * v_lo; - const std::uint64_t p1 = u_lo * v_hi; - const std::uint64_t p2 = u_hi * v_lo; - const std::uint64_t p3 = u_hi * v_hi; - - const std::uint64_t p0_hi = p0 >> 32u; - const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu; - const std::uint64_t p1_hi = p1 >> 32u; - const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu; - const std::uint64_t p2_hi = p2 >> 32u; - - std::uint64_t Q = p0_hi + p1_lo + p2_lo; - - // The full product might now be computed as - // - // p_hi = p3 + p2_hi + p1_hi + (Q >> 32) - // p_lo = p0_lo + (Q << 32) - // - // But in this particular case here, the full p_lo is not required. - // Effectively we only need to add the highest bit in p_lo to p_hi (and - // Q_hi + 1 does not overflow). - - Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up - - const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u); - - return {h, x.e + y.e + 64}; - } - - /*! - @brief normalize x such that the significand is >= 2^(q-1) - @pre x.f != 0 - */ - static diyfp normalize(diyfp x) noexcept - { - JSON_ASSERT(x.f != 0); - - while ((x.f >> 63u) == 0) - { - x.f <<= 1u; - x.e--; - } - - return x; - } - - /*! - @brief normalize x such that the result has the exponent E - @pre e >= x.e and the upper e - x.e bits of x.f must be zero. - */ - static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept - { - const int delta = x.e - target_exponent; - - JSON_ASSERT(delta >= 0); - JSON_ASSERT(((x.f << delta) >> delta) == x.f); - - return {x.f << delta, target_exponent}; - } -}; - -struct boundaries -{ - diyfp w; - diyfp minus; - diyfp plus; -}; - -/*! -Compute the (normalized) diyfp representing the input number 'value' and its -boundaries. - -@pre value must be finite and positive -*/ -template -boundaries compute_boundaries(FloatType value) -{ - JSON_ASSERT(std::isfinite(value)); - JSON_ASSERT(value > 0); - - // Convert the IEEE representation into a diyfp. - // - // If v is denormal: - // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1)) - // If v is normalized: - // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1)) - - static_assert(std::numeric_limits::is_iec559, - "internal error: dtoa_short requires an IEEE-754 floating-point implementation"); - - constexpr int kPrecision = std::numeric_limits::digits; // = p (includes the hidden bit) - constexpr int kBias = std::numeric_limits::max_exponent - 1 + (kPrecision - 1); - constexpr int kMinExp = 1 - kBias; - constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1) - - using bits_type = typename std::conditional::type; - - const auto bits = static_cast(reinterpret_bits(value)); - const std::uint64_t E = bits >> (kPrecision - 1); - const std::uint64_t F = bits & (kHiddenBit - 1); - - const bool is_denormal = E == 0; - const diyfp v = is_denormal - ? diyfp(F, kMinExp) - : diyfp(F + kHiddenBit, static_cast(E) - kBias); - - // Compute the boundaries m- and m+ of the floating-point value - // v = f * 2^e. - // - // Determine v- and v+, the floating-point predecessor and successor if v, - // respectively. - // - // v- = v - 2^e if f != 2^(p-1) or e == e_min (A) - // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B) - // - // v+ = v + 2^e - // - // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_ - // between m- and m+ round to v, regardless of how the input rounding - // algorithm breaks ties. - // - // ---+-------------+-------------+-------------+-------------+--- (A) - // v- m- v m+ v+ - // - // -----------------+------+------+-------------+-------------+--- (B) - // v- m- v m+ v+ - - const bool lower_boundary_is_closer = F == 0 && E > 1; - const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1); - const diyfp m_minus = lower_boundary_is_closer - ? diyfp(4 * v.f - 1, v.e - 2) // (B) - : diyfp(2 * v.f - 1, v.e - 1); // (A) - - // Determine the normalized w+ = m+. - const diyfp w_plus = diyfp::normalize(m_plus); - - // Determine w- = m- such that e_(w-) = e_(w+). - const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e); - - return {diyfp::normalize(v), w_minus, w_plus}; -} - -// Given normalized diyfp w, Grisu needs to find a (normalized) cached -// power-of-ten c, such that the exponent of the product c * w = f * 2^e lies -// within a certain range [alpha, gamma] (Definition 3.2 from [1]) -// -// alpha <= e = e_c + e_w + q <= gamma -// -// or -// -// f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q -// <= f_c * f_w * 2^gamma -// -// Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies -// -// 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma -// -// or -// -// 2^(q - 2 + alpha) <= c * w < 2^(q + gamma) -// -// The choice of (alpha,gamma) determines the size of the table and the form of -// the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well -// in practice: -// -// The idea is to cut the number c * w = f * 2^e into two parts, which can be -// processed independently: An integral part p1, and a fractional part p2: -// -// f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e -// = (f div 2^-e) + (f mod 2^-e) * 2^e -// = p1 + p2 * 2^e -// -// The conversion of p1 into decimal form requires a series of divisions and -// modulos by (a power of) 10. These operations are faster for 32-bit than for -// 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be -// achieved by choosing -// -// -e >= 32 or e <= -32 := gamma -// -// In order to convert the fractional part -// -// p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ... -// -// into decimal form, the fraction is repeatedly multiplied by 10 and the digits -// d[-i] are extracted in order: -// -// (10 * p2) div 2^-e = d[-1] -// (10 * p2) mod 2^-e = d[-2] / 10^1 + ... -// -// The multiplication by 10 must not overflow. It is sufficient to choose -// -// 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64. -// -// Since p2 = f mod 2^-e < 2^-e, -// -// -e <= 60 or e >= -60 := alpha - -constexpr int kAlpha = -60; -constexpr int kGamma = -32; - -struct cached_power // c = f * 2^e ~= 10^k -{ - std::uint64_t f; - int e; - int k; -}; - -/*! -For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached -power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c -satisfies (Definition 3.2 from [1]) - - alpha <= e_c + e + q <= gamma. -*/ -inline cached_power get_cached_power_for_binary_exponent(int e) -{ - // Now - // - // alpha <= e_c + e + q <= gamma (1) - // ==> f_c * 2^alpha <= c * 2^e * 2^q - // - // and since the c's are normalized, 2^(q-1) <= f_c, - // - // ==> 2^(q - 1 + alpha) <= c * 2^(e + q) - // ==> 2^(alpha - e - 1) <= c - // - // If c were an exact power of ten, i.e. c = 10^k, one may determine k as - // - // k = ceil( log_10( 2^(alpha - e - 1) ) ) - // = ceil( (alpha - e - 1) * log_10(2) ) - // - // From the paper: - // "In theory the result of the procedure could be wrong since c is rounded, - // and the computation itself is approximated [...]. In practice, however, - // this simple function is sufficient." - // - // For IEEE double precision floating-point numbers converted into - // normalized diyfp's w = f * 2^e, with q = 64, - // - // e >= -1022 (min IEEE exponent) - // -52 (p - 1) - // -52 (p - 1, possibly normalize denormal IEEE numbers) - // -11 (normalize the diyfp) - // = -1137 - // - // and - // - // e <= +1023 (max IEEE exponent) - // -52 (p - 1) - // -11 (normalize the diyfp) - // = 960 - // - // This binary exponent range [-1137,960] results in a decimal exponent - // range [-307,324]. One does not need to store a cached power for each - // k in this range. For each such k it suffices to find a cached power - // such that the exponent of the product lies in [alpha,gamma]. - // This implies that the difference of the decimal exponents of adjacent - // table entries must be less than or equal to - // - // floor( (gamma - alpha) * log_10(2) ) = 8. - // - // (A smaller distance gamma-alpha would require a larger table.) - - // NB: - // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34. - - constexpr int kCachedPowersMinDecExp = -300; - constexpr int kCachedPowersDecStep = 8; - - static constexpr std::array kCachedPowers = - { - { - { 0xAB70FE17C79AC6CA, -1060, -300 }, - { 0xFF77B1FCBEBCDC4F, -1034, -292 }, - { 0xBE5691EF416BD60C, -1007, -284 }, - { 0x8DD01FAD907FFC3C, -980, -276 }, - { 0xD3515C2831559A83, -954, -268 }, - { 0x9D71AC8FADA6C9B5, -927, -260 }, - { 0xEA9C227723EE8BCB, -901, -252 }, - { 0xAECC49914078536D, -874, -244 }, - { 0x823C12795DB6CE57, -847, -236 }, - { 0xC21094364DFB5637, -821, -228 }, - { 0x9096EA6F3848984F, -794, -220 }, - { 0xD77485CB25823AC7, -768, -212 }, - { 0xA086CFCD97BF97F4, -741, -204 }, - { 0xEF340A98172AACE5, -715, -196 }, - { 0xB23867FB2A35B28E, -688, -188 }, - { 0x84C8D4DFD2C63F3B, -661, -180 }, - { 0xC5DD44271AD3CDBA, -635, -172 }, - { 0x936B9FCEBB25C996, -608, -164 }, - { 0xDBAC6C247D62A584, -582, -156 }, - { 0xA3AB66580D5FDAF6, -555, -148 }, - { 0xF3E2F893DEC3F126, -529, -140 }, - { 0xB5B5ADA8AAFF80B8, -502, -132 }, - { 0x87625F056C7C4A8B, -475, -124 }, - { 0xC9BCFF6034C13053, -449, -116 }, - { 0x964E858C91BA2655, -422, -108 }, - { 0xDFF9772470297EBD, -396, -100 }, - { 0xA6DFBD9FB8E5B88F, -369, -92 }, - { 0xF8A95FCF88747D94, -343, -84 }, - { 0xB94470938FA89BCF, -316, -76 }, - { 0x8A08F0F8BF0F156B, -289, -68 }, - { 0xCDB02555653131B6, -263, -60 }, - { 0x993FE2C6D07B7FAC, -236, -52 }, - { 0xE45C10C42A2B3B06, -210, -44 }, - { 0xAA242499697392D3, -183, -36 }, - { 0xFD87B5F28300CA0E, -157, -28 }, - { 0xBCE5086492111AEB, -130, -20 }, - { 0x8CBCCC096F5088CC, -103, -12 }, - { 0xD1B71758E219652C, -77, -4 }, - { 0x9C40000000000000, -50, 4 }, - { 0xE8D4A51000000000, -24, 12 }, - { 0xAD78EBC5AC620000, 3, 20 }, - { 0x813F3978F8940984, 30, 28 }, - { 0xC097CE7BC90715B3, 56, 36 }, - { 0x8F7E32CE7BEA5C70, 83, 44 }, - { 0xD5D238A4ABE98068, 109, 52 }, - { 0x9F4F2726179A2245, 136, 60 }, - { 0xED63A231D4C4FB27, 162, 68 }, - { 0xB0DE65388CC8ADA8, 189, 76 }, - { 0x83C7088E1AAB65DB, 216, 84 }, - { 0xC45D1DF942711D9A, 242, 92 }, - { 0x924D692CA61BE758, 269, 100 }, - { 0xDA01EE641A708DEA, 295, 108 }, - { 0xA26DA3999AEF774A, 322, 116 }, - { 0xF209787BB47D6B85, 348, 124 }, - { 0xB454E4A179DD1877, 375, 132 }, - { 0x865B86925B9BC5C2, 402, 140 }, - { 0xC83553C5C8965D3D, 428, 148 }, - { 0x952AB45CFA97A0B3, 455, 156 }, - { 0xDE469FBD99A05FE3, 481, 164 }, - { 0xA59BC234DB398C25, 508, 172 }, - { 0xF6C69A72A3989F5C, 534, 180 }, - { 0xB7DCBF5354E9BECE, 561, 188 }, - { 0x88FCF317F22241E2, 588, 196 }, - { 0xCC20CE9BD35C78A5, 614, 204 }, - { 0x98165AF37B2153DF, 641, 212 }, - { 0xE2A0B5DC971F303A, 667, 220 }, - { 0xA8D9D1535CE3B396, 694, 228 }, - { 0xFB9B7CD9A4A7443C, 720, 236 }, - { 0xBB764C4CA7A44410, 747, 244 }, - { 0x8BAB8EEFB6409C1A, 774, 252 }, - { 0xD01FEF10A657842C, 800, 260 }, - { 0x9B10A4E5E9913129, 827, 268 }, - { 0xE7109BFBA19C0C9D, 853, 276 }, - { 0xAC2820D9623BF429, 880, 284 }, - { 0x80444B5E7AA7CF85, 907, 292 }, - { 0xBF21E44003ACDD2D, 933, 300 }, - { 0x8E679C2F5E44FF8F, 960, 308 }, - { 0xD433179D9C8CB841, 986, 316 }, - { 0x9E19DB92B4E31BA9, 1013, 324 }, - } - }; - - // This computation gives exactly the same results for k as - // k = ceil((kAlpha - e - 1) * 0.30102999566398114) - // for |e| <= 1500, but doesn't require floating-point operations. - // NB: log_10(2) ~= 78913 / 2^18 - JSON_ASSERT(e >= -1500); - JSON_ASSERT(e <= 1500); - const int f = kAlpha - e - 1; - const int k = (f * 78913) / (1 << 18) + static_cast(f > 0); - - const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep; - JSON_ASSERT(index >= 0); - JSON_ASSERT(static_cast(index) < kCachedPowers.size()); - - const cached_power cached = kCachedPowers[static_cast(index)]; - JSON_ASSERT(kAlpha <= cached.e + e + 64); - JSON_ASSERT(kGamma >= cached.e + e + 64); - - return cached; -} - -/*! -For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k. -For n == 0, returns 1 and sets pow10 := 1. -*/ -inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10) -{ - // LCOV_EXCL_START - if (n >= 1000000000) - { - pow10 = 1000000000; - return 10; - } - // LCOV_EXCL_STOP - if (n >= 100000000) - { - pow10 = 100000000; - return 9; - } - if (n >= 10000000) - { - pow10 = 10000000; - return 8; - } - if (n >= 1000000) - { - pow10 = 1000000; - return 7; - } - if (n >= 100000) - { - pow10 = 100000; - return 6; - } - if (n >= 10000) - { - pow10 = 10000; - return 5; - } - if (n >= 1000) - { - pow10 = 1000; - return 4; - } - if (n >= 100) - { - pow10 = 100; - return 3; - } - if (n >= 10) - { - pow10 = 10; - return 2; - } - - pow10 = 1; - return 1; -} - -inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta, - std::uint64_t rest, std::uint64_t ten_k) -{ - JSON_ASSERT(len >= 1); - JSON_ASSERT(dist <= delta); - JSON_ASSERT(rest <= delta); - JSON_ASSERT(ten_k > 0); - - // <--------------------------- delta ----> - // <---- dist ---------> - // --------------[------------------+-------------------]-------------- - // M- w M+ - // - // ten_k - // <------> - // <---- rest ----> - // --------------[------------------+----+--------------]-------------- - // w V - // = buf * 10^k - // - // ten_k represents a unit-in-the-last-place in the decimal representation - // stored in buf. - // Decrement buf by ten_k while this takes buf closer to w. - - // The tests are written in this order to avoid overflow in unsigned - // integer arithmetic. - - while (rest < dist - && delta - rest >= ten_k - && (rest + ten_k < dist || dist - rest > rest + ten_k - dist)) - { - JSON_ASSERT(buf[len - 1] != '0'); - buf[len - 1]--; - rest += ten_k; - } -} - -/*! -Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+. -M- and M+ must be normalized and share the same exponent -60 <= e <= -32. -*/ -inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent, - diyfp M_minus, diyfp w, diyfp M_plus) -{ - static_assert(kAlpha >= -60, "internal error"); - static_assert(kGamma <= -32, "internal error"); - - // Generates the digits (and the exponent) of a decimal floating-point - // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's - // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma. - // - // <--------------------------- delta ----> - // <---- dist ---------> - // --------------[------------------+-------------------]-------------- - // M- w M+ - // - // Grisu2 generates the digits of M+ from left to right and stops as soon as - // V is in [M-,M+]. - - JSON_ASSERT(M_plus.e >= kAlpha); - JSON_ASSERT(M_plus.e <= kGamma); - - std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e) - std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e) - - // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0): - // - // M+ = f * 2^e - // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e - // = ((p1 ) * 2^-e + (p2 )) * 2^e - // = p1 + p2 * 2^e - - const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e); - - auto p1 = static_cast(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.) - std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e - - // 1) - // - // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0] - - JSON_ASSERT(p1 > 0); - - std::uint32_t pow10{}; - const int k = find_largest_pow10(p1, pow10); - - // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1) - // - // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1)) - // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1)) - // - // M+ = p1 + p2 * 2^e - // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e - // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e - // = d[k-1] * 10^(k-1) + ( rest) * 2^e - // - // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0) - // - // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0] - // - // but stop as soon as - // - // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e - - int n = k; - while (n > 0) - { - // Invariants: - // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k) - // pow10 = 10^(n-1) <= p1 < 10^n - // - const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1) - const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1) - // - // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e - // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e) - // - JSON_ASSERT(d <= 9); - buffer[length++] = static_cast('0' + d); // buffer := buffer * 10 + d - // - // M+ = buffer * 10^(n-1) + (r + p2 * 2^e) - // - p1 = r; - n--; - // - // M+ = buffer * 10^n + (p1 + p2 * 2^e) - // pow10 = 10^n - // - - // Now check if enough digits have been generated. - // Compute - // - // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e - // - // Note: - // Since rest and delta share the same exponent e, it suffices to - // compare the significands. - const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2; - if (rest <= delta) - { - // V = buffer * 10^n, with M- <= V <= M+. - - decimal_exponent += n; - - // We may now just stop. But instead look if the buffer could be - // decremented to bring V closer to w. - // - // pow10 = 10^n is now 1 ulp in the decimal representation V. - // The rounding procedure works with diyfp's with an implicit - // exponent of e. - // - // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e - // - const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e; - grisu2_round(buffer, length, dist, delta, rest, ten_n); - - return; - } - - pow10 /= 10; - // - // pow10 = 10^(n-1) <= p1 < 10^n - // Invariants restored. - } - - // 2) - // - // The digits of the integral part have been generated: - // - // M+ = d[k-1]...d[1]d[0] + p2 * 2^e - // = buffer + p2 * 2^e - // - // Now generate the digits of the fractional part p2 * 2^e. - // - // Note: - // No decimal point is generated: the exponent is adjusted instead. - // - // p2 actually represents the fraction - // - // p2 * 2^e - // = p2 / 2^-e - // = d[-1] / 10^1 + d[-2] / 10^2 + ... - // - // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...) - // - // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m - // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...) - // - // using - // - // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e) - // = ( d) * 2^-e + ( r) - // - // or - // 10^m * p2 * 2^e = d + r * 2^e - // - // i.e. - // - // M+ = buffer + p2 * 2^e - // = buffer + 10^-m * (d + r * 2^e) - // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e - // - // and stop as soon as 10^-m * r * 2^e <= delta * 2^e - - JSON_ASSERT(p2 > delta); - - int m = 0; - for (;;) - { - // Invariant: - // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e - // = buffer * 10^-m + 10^-m * (p2 ) * 2^e - // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e - // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e - // - JSON_ASSERT(p2 <= (std::numeric_limits::max)() / 10); - p2 *= 10; - const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e - const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e - // - // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e - // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e)) - // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e - // - JSON_ASSERT(d <= 9); - buffer[length++] = static_cast('0' + d); // buffer := buffer * 10 + d - // - // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e - // - p2 = r; - m++; - // - // M+ = buffer * 10^-m + 10^-m * p2 * 2^e - // Invariant restored. - - // Check if enough digits have been generated. - // - // 10^-m * p2 * 2^e <= delta * 2^e - // p2 * 2^e <= 10^m * delta * 2^e - // p2 <= 10^m * delta - delta *= 10; - dist *= 10; - if (p2 <= delta) - { - break; - } - } - - // V = buffer * 10^-m, with M- <= V <= M+. - - decimal_exponent -= m; - - // 1 ulp in the decimal representation is now 10^-m. - // Since delta and dist are now scaled by 10^m, we need to do the - // same with ulp in order to keep the units in sync. - // - // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e - // - const std::uint64_t ten_m = one.f; - grisu2_round(buffer, length, dist, delta, p2, ten_m); - - // By construction this algorithm generates the shortest possible decimal - // number (Loitsch, Theorem 6.2) which rounds back to w. - // For an input number of precision p, at least - // - // N = 1 + ceil(p * log_10(2)) - // - // decimal digits are sufficient to identify all binary floating-point - // numbers (Matula, "In-and-Out conversions"). - // This implies that the algorithm does not produce more than N decimal - // digits. - // - // N = 17 for p = 53 (IEEE double precision) - // N = 9 for p = 24 (IEEE single precision) -} - -/*! -v = buf * 10^decimal_exponent -len is the length of the buffer (number of decimal digits) -The buffer must be large enough, i.e. >= max_digits10. -*/ -JSON_HEDLEY_NON_NULL(1) -inline void grisu2(char* buf, int& len, int& decimal_exponent, - diyfp m_minus, diyfp v, diyfp m_plus) -{ - JSON_ASSERT(m_plus.e == m_minus.e); - JSON_ASSERT(m_plus.e == v.e); - - // --------(-----------------------+-----------------------)-------- (A) - // m- v m+ - // - // --------------------(-----------+-----------------------)-------- (B) - // m- v m+ - // - // First scale v (and m- and m+) such that the exponent is in the range - // [alpha, gamma]. - - const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e); - - const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k - - // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma] - const diyfp w = diyfp::mul(v, c_minus_k); - const diyfp w_minus = diyfp::mul(m_minus, c_minus_k); - const diyfp w_plus = diyfp::mul(m_plus, c_minus_k); - - // ----(---+---)---------------(---+---)---------------(---+---)---- - // w- w w+ - // = c*m- = c*v = c*m+ - // - // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and - // w+ are now off by a small amount. - // In fact: - // - // w - v * 10^k < 1 ulp - // - // To account for this inaccuracy, add resp. subtract 1 ulp. - // - // --------+---[---------------(---+---)---------------]---+-------- - // w- M- w M+ w+ - // - // Now any number in [M-, M+] (bounds included) will round to w when input, - // regardless of how the input rounding algorithm breaks ties. - // - // And digit_gen generates the shortest possible such number in [M-, M+]. - // Note that this does not mean that Grisu2 always generates the shortest - // possible number in the interval (m-, m+). - const diyfp M_minus(w_minus.f + 1, w_minus.e); - const diyfp M_plus (w_plus.f - 1, w_plus.e ); - - decimal_exponent = -cached.k; // = -(-k) = k - - grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus); -} - -/*! -v = buf * 10^decimal_exponent -len is the length of the buffer (number of decimal digits) -The buffer must be large enough, i.e. >= max_digits10. -*/ -template -JSON_HEDLEY_NON_NULL(1) -void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value) -{ - static_assert(diyfp::kPrecision >= std::numeric_limits::digits + 3, - "internal error: not enough precision"); - - JSON_ASSERT(std::isfinite(value)); - JSON_ASSERT(value > 0); - - // If the neighbors (and boundaries) of 'value' are always computed for double-precision - // numbers, all float's can be recovered using strtod (and strtof). However, the resulting - // decimal representations are not exactly "short". - // - // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars) - // says "value is converted to a string as if by std::sprintf in the default ("C") locale" - // and since sprintf promotes floats to doubles, I think this is exactly what 'std::to_chars' - // does. - // On the other hand, the documentation for 'std::to_chars' requires that "parsing the - // representation using the corresponding std::from_chars function recovers value exactly". That - // indicates that single precision floating-point numbers should be recovered using - // 'std::strtof'. - // - // NB: If the neighbors are computed for single-precision numbers, there is a single float - // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision - // value is off by 1 ulp. -#if 0 - const boundaries w = compute_boundaries(static_cast(value)); -#else - const boundaries w = compute_boundaries(value); -#endif - - grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus); -} - -/*! -@brief appends a decimal representation of e to buf -@return a pointer to the element following the exponent. -@pre -1000 < e < 1000 -*/ -JSON_HEDLEY_NON_NULL(1) -JSON_HEDLEY_RETURNS_NON_NULL -inline char* append_exponent(char* buf, int e) -{ - JSON_ASSERT(e > -1000); - JSON_ASSERT(e < 1000); - - if (e < 0) - { - e = -e; - *buf++ = '-'; - } - else - { - *buf++ = '+'; - } - - auto k = static_cast(e); - if (k < 10) - { - // Always print at least two digits in the exponent. - // This is for compatibility with printf("%g"). - *buf++ = '0'; - *buf++ = static_cast('0' + k); - } - else if (k < 100) - { - *buf++ = static_cast('0' + k / 10); - k %= 10; - *buf++ = static_cast('0' + k); - } - else - { - *buf++ = static_cast('0' + k / 100); - k %= 100; - *buf++ = static_cast('0' + k / 10); - k %= 10; - *buf++ = static_cast('0' + k); - } - - return buf; -} - -/*! -@brief prettify v = buf * 10^decimal_exponent - -If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point -notation. Otherwise it will be printed in exponential notation. - -@pre min_exp < 0 -@pre max_exp > 0 -*/ -JSON_HEDLEY_NON_NULL(1) -JSON_HEDLEY_RETURNS_NON_NULL -inline char* format_buffer(char* buf, int len, int decimal_exponent, - int min_exp, int max_exp) -{ - JSON_ASSERT(min_exp < 0); - JSON_ASSERT(max_exp > 0); - - const int k = len; - const int n = len + decimal_exponent; - - // v = buf * 10^(n-k) - // k is the length of the buffer (number of decimal digits) - // n is the position of the decimal point relative to the start of the buffer. - - if (k <= n && n <= max_exp) - { - // digits[000] - // len <= max_exp + 2 - - std::memset(buf + k, '0', static_cast(n) - static_cast(k)); - // Make it look like a floating-point number (#362, #378) - buf[n + 0] = '.'; - buf[n + 1] = '0'; - return buf + (static_cast(n) + 2); - } - - if (0 < n && n <= max_exp) - { - // dig.its - // len <= max_digits10 + 1 - - JSON_ASSERT(k > n); - - std::memmove(buf + (static_cast(n) + 1), buf + n, static_cast(k) - static_cast(n)); - buf[n] = '.'; - return buf + (static_cast(k) + 1U); - } - - if (min_exp < n && n <= 0) - { - // 0.[000]digits - // len <= 2 + (-min_exp - 1) + max_digits10 - - std::memmove(buf + (2 + static_cast(-n)), buf, static_cast(k)); - buf[0] = '0'; - buf[1] = '.'; - std::memset(buf + 2, '0', static_cast(-n)); - return buf + (2U + static_cast(-n) + static_cast(k)); - } - - if (k == 1) - { - // dE+123 - // len <= 1 + 5 - - buf += 1; - } - else - { - // d.igitsE+123 - // len <= max_digits10 + 1 + 5 - - std::memmove(buf + 2, buf + 1, static_cast(k) - 1); - buf[1] = '.'; - buf += 1 + static_cast(k); - } - - *buf++ = 'e'; - return append_exponent(buf, n - 1); -} - -} // namespace dtoa_impl - -/*! -@brief generates a decimal representation of the floating-point number value in [first, last). - -The format of the resulting decimal representation is similar to printf's %g -format. Returns an iterator pointing past-the-end of the decimal representation. - -@note The input number must be finite, i.e. NaN's and Inf's are not supported. -@note The buffer must be large enough. -@note The result is NOT null-terminated. -*/ -template -JSON_HEDLEY_NON_NULL(1, 2) -JSON_HEDLEY_RETURNS_NON_NULL -char* to_chars(char* first, const char* last, FloatType value) -{ - static_cast(last); // maybe unused - fix warning - JSON_ASSERT(std::isfinite(value)); - - // Use signbit(value) instead of (value < 0) since signbit works for -0. - if (std::signbit(value)) - { - value = -value; - *first++ = '-'; - } - -#ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wfloat-equal" -#endif - if (value == 0) // +-0 - { - *first++ = '0'; - // Make it look like a floating-point number (#362, #378) - *first++ = '.'; - *first++ = '0'; - return first; - } -#ifdef __GNUC__ -#pragma GCC diagnostic pop -#endif - - JSON_ASSERT(last - first >= std::numeric_limits::max_digits10); - - // Compute v = buffer * 10^decimal_exponent. - // The decimal digits are stored in the buffer, which needs to be interpreted - // as an unsigned decimal integer. - // len is the length of the buffer, i.e. the number of decimal digits. - int len = 0; - int decimal_exponent = 0; - dtoa_impl::grisu2(first, len, decimal_exponent, value); - - JSON_ASSERT(len <= std::numeric_limits::max_digits10); - - // Format the buffer like printf("%.*g", prec, value) - constexpr int kMinExp = -4; - // Use digits10 here to increase compatibility with version 2. - constexpr int kMaxExp = std::numeric_limits::digits10; - - JSON_ASSERT(last - first >= kMaxExp + 2); - JSON_ASSERT(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits::max_digits10); - JSON_ASSERT(last - first >= std::numeric_limits::max_digits10 + 6); - - return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp); -} - -} // namespace detail -} // namespace nlohmann - -// #include - -// #include - -// #include - -// #include - -// #include - -// #include - - -namespace nlohmann -{ -namespace detail -{ -/////////////////// -// serialization // -/////////////////// - -/// how to treat decoding errors -enum class error_handler_t -{ - strict, ///< throw a type_error exception in case of invalid UTF-8 - replace, ///< replace invalid UTF-8 sequences with U+FFFD - ignore ///< ignore invalid UTF-8 sequences -}; - -template -class serializer -{ - using string_t = typename BasicJsonType::string_t; - using number_float_t = typename BasicJsonType::number_float_t; - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using binary_char_t = typename BasicJsonType::binary_t::value_type; - static constexpr std::uint8_t UTF8_ACCEPT = 0; - static constexpr std::uint8_t UTF8_REJECT = 1; - - public: - /*! - @param[in] s output stream to serialize to - @param[in] ichar indentation character to use - @param[in] error_handler_ how to react on decoding errors - */ - serializer(output_adapter_t s, const char ichar, - error_handler_t error_handler_ = error_handler_t::strict) - : o(std::move(s)) - , loc(std::localeconv()) - , thousands_sep(loc->thousands_sep == nullptr ? '\0' : std::char_traits::to_char_type(* (loc->thousands_sep))) - , decimal_point(loc->decimal_point == nullptr ? '\0' : std::char_traits::to_char_type(* (loc->decimal_point))) - , indent_char(ichar) - , indent_string(512, indent_char) - , error_handler(error_handler_) - {} - - // delete because of pointer members - serializer(const serializer&) = delete; - serializer& operator=(const serializer&) = delete; - serializer(serializer&&) = delete; - serializer& operator=(serializer&&) = delete; - ~serializer() = default; - - /*! - @brief internal implementation of the serialization function - - This function is called by the public member function dump and organizes - the serialization internally. The indentation level is propagated as - additional parameter. In case of arrays and objects, the function is - called recursively. - - - strings and object keys are escaped using `escape_string()` - - integer numbers are converted implicitly via `operator<<` - - floating-point numbers are converted to a string using `"%g"` format - - binary values are serialized as objects containing the subtype and the - byte array - - @param[in] val value to serialize - @param[in] pretty_print whether the output shall be pretty-printed - @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters - in the output are escaped with `\uXXXX` sequences, and the result consists - of ASCII characters only. - @param[in] indent_step the indent level - @param[in] current_indent the current indent level (only used internally) - */ - void dump(const BasicJsonType& val, - const bool pretty_print, - const bool ensure_ascii, - const unsigned int indent_step, - const unsigned int current_indent = 0) - { - switch (val.m_type) - { - case value_t::object: - { - if (val.m_value.object->empty()) - { - o->write_characters("{}", 2); - return; - } - - if (pretty_print) - { - o->write_characters("{\n", 2); - - // variable to hold indentation for recursive calls - const auto new_indent = current_indent + indent_step; - if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) - { - indent_string.resize(indent_string.size() * 2, ' '); - } - - // first n-1 elements - auto i = val.m_value.object->cbegin(); - for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) - { - o->write_characters(indent_string.c_str(), new_indent); - o->write_character('\"'); - dump_escaped(i->first, ensure_ascii); - o->write_characters("\": ", 3); - dump(i->second, true, ensure_ascii, indent_step, new_indent); - o->write_characters(",\n", 2); - } - - // last element - JSON_ASSERT(i != val.m_value.object->cend()); - JSON_ASSERT(std::next(i) == val.m_value.object->cend()); - o->write_characters(indent_string.c_str(), new_indent); - o->write_character('\"'); - dump_escaped(i->first, ensure_ascii); - o->write_characters("\": ", 3); - dump(i->second, true, ensure_ascii, indent_step, new_indent); - - o->write_character('\n'); - o->write_characters(indent_string.c_str(), current_indent); - o->write_character('}'); - } - else - { - o->write_character('{'); - - // first n-1 elements - auto i = val.m_value.object->cbegin(); - for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) - { - o->write_character('\"'); - dump_escaped(i->first, ensure_ascii); - o->write_characters("\":", 2); - dump(i->second, false, ensure_ascii, indent_step, current_indent); - o->write_character(','); - } - - // last element - JSON_ASSERT(i != val.m_value.object->cend()); - JSON_ASSERT(std::next(i) == val.m_value.object->cend()); - o->write_character('\"'); - dump_escaped(i->first, ensure_ascii); - o->write_characters("\":", 2); - dump(i->second, false, ensure_ascii, indent_step, current_indent); - - o->write_character('}'); - } - - return; - } - - case value_t::array: - { - if (val.m_value.array->empty()) - { - o->write_characters("[]", 2); - return; - } - - if (pretty_print) - { - o->write_characters("[\n", 2); - - // variable to hold indentation for recursive calls - const auto new_indent = current_indent + indent_step; - if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) - { - indent_string.resize(indent_string.size() * 2, ' '); - } - - // first n-1 elements - for (auto i = val.m_value.array->cbegin(); - i != val.m_value.array->cend() - 1; ++i) - { - o->write_characters(indent_string.c_str(), new_indent); - dump(*i, true, ensure_ascii, indent_step, new_indent); - o->write_characters(",\n", 2); - } - - // last element - JSON_ASSERT(!val.m_value.array->empty()); - o->write_characters(indent_string.c_str(), new_indent); - dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent); - - o->write_character('\n'); - o->write_characters(indent_string.c_str(), current_indent); - o->write_character(']'); - } - else - { - o->write_character('['); - - // first n-1 elements - for (auto i = val.m_value.array->cbegin(); - i != val.m_value.array->cend() - 1; ++i) - { - dump(*i, false, ensure_ascii, indent_step, current_indent); - o->write_character(','); - } - - // last element - JSON_ASSERT(!val.m_value.array->empty()); - dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent); - - o->write_character(']'); - } - - return; - } - - case value_t::string: - { - o->write_character('\"'); - dump_escaped(*val.m_value.string, ensure_ascii); - o->write_character('\"'); - return; - } - - case value_t::binary: - { - if (pretty_print) - { - o->write_characters("{\n", 2); - - // variable to hold indentation for recursive calls - const auto new_indent = current_indent + indent_step; - if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) - { - indent_string.resize(indent_string.size() * 2, ' '); - } - - o->write_characters(indent_string.c_str(), new_indent); - - o->write_characters("\"bytes\": [", 10); - - if (!val.m_value.binary->empty()) - { - for (auto i = val.m_value.binary->cbegin(); - i != val.m_value.binary->cend() - 1; ++i) - { - dump_integer(*i); - o->write_characters(", ", 2); - } - dump_integer(val.m_value.binary->back()); - } - - o->write_characters("],\n", 3); - o->write_characters(indent_string.c_str(), new_indent); - - o->write_characters("\"subtype\": ", 11); - if (val.m_value.binary->has_subtype()) - { - dump_integer(val.m_value.binary->subtype()); - } - else - { - o->write_characters("null", 4); - } - o->write_character('\n'); - o->write_characters(indent_string.c_str(), current_indent); - o->write_character('}'); - } - else - { - o->write_characters("{\"bytes\":[", 10); - - if (!val.m_value.binary->empty()) - { - for (auto i = val.m_value.binary->cbegin(); - i != val.m_value.binary->cend() - 1; ++i) - { - dump_integer(*i); - o->write_character(','); - } - dump_integer(val.m_value.binary->back()); - } - - o->write_characters("],\"subtype\":", 12); - if (val.m_value.binary->has_subtype()) - { - dump_integer(val.m_value.binary->subtype()); - o->write_character('}'); - } - else - { - o->write_characters("null}", 5); - } - } - return; - } - - case value_t::boolean: - { - if (val.m_value.boolean) - { - o->write_characters("true", 4); - } - else - { - o->write_characters("false", 5); - } - return; - } - - case value_t::number_integer: - { - dump_integer(val.m_value.number_integer); - return; - } - - case value_t::number_unsigned: - { - dump_integer(val.m_value.number_unsigned); - return; - } - - case value_t::number_float: - { - dump_float(val.m_value.number_float); - return; - } - - case value_t::discarded: - { - o->write_characters("", 11); - return; - } - - case value_t::null: - { - o->write_characters("null", 4); - return; - } - - default: // LCOV_EXCL_LINE - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE - } - } - - JSON_PRIVATE_UNLESS_TESTED: - /*! - @brief dump escaped string - - Escape a string by replacing certain special characters by a sequence of an - escape character (backslash) and another character and other control - characters by a sequence of "\u" followed by a four-digit hex - representation. The escaped string is written to output stream @a o. - - @param[in] s the string to escape - @param[in] ensure_ascii whether to escape non-ASCII characters with - \uXXXX sequences - - @complexity Linear in the length of string @a s. - */ - void dump_escaped(const string_t& s, const bool ensure_ascii) - { - std::uint32_t codepoint{}; - std::uint8_t state = UTF8_ACCEPT; - std::size_t bytes = 0; // number of bytes written to string_buffer - - // number of bytes written at the point of the last valid byte - std::size_t bytes_after_last_accept = 0; - std::size_t undumped_chars = 0; - - for (std::size_t i = 0; i < s.size(); ++i) - { - const auto byte = static_cast(s[i]); - - switch (decode(state, codepoint, byte)) - { - case UTF8_ACCEPT: // decode found a new code point - { - switch (codepoint) - { - case 0x08: // backspace - { - string_buffer[bytes++] = '\\'; - string_buffer[bytes++] = 'b'; - break; - } - - case 0x09: // horizontal tab - { - string_buffer[bytes++] = '\\'; - string_buffer[bytes++] = 't'; - break; - } - - case 0x0A: // newline - { - string_buffer[bytes++] = '\\'; - string_buffer[bytes++] = 'n'; - break; - } - - case 0x0C: // formfeed - { - string_buffer[bytes++] = '\\'; - string_buffer[bytes++] = 'f'; - break; - } - - case 0x0D: // carriage return - { - string_buffer[bytes++] = '\\'; - string_buffer[bytes++] = 'r'; - break; - } - - case 0x22: // quotation mark - { - string_buffer[bytes++] = '\\'; - string_buffer[bytes++] = '\"'; - break; - } - - case 0x5C: // reverse solidus - { - string_buffer[bytes++] = '\\'; - string_buffer[bytes++] = '\\'; - break; - } - - default: - { - // escape control characters (0x00..0x1F) or, if - // ensure_ascii parameter is used, non-ASCII characters - if ((codepoint <= 0x1F) || (ensure_ascii && (codepoint >= 0x7F))) - { - if (codepoint <= 0xFFFF) - { - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) - static_cast((std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x", - static_cast(codepoint))); - bytes += 6; - } - else - { - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) - static_cast((std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x", - static_cast(0xD7C0u + (codepoint >> 10u)), - static_cast(0xDC00u + (codepoint & 0x3FFu)))); - bytes += 12; - } - } - else - { - // copy byte to buffer (all previous bytes - // been copied have in default case above) - string_buffer[bytes++] = s[i]; - } - break; - } - } - - // write buffer and reset index; there must be 13 bytes - // left, as this is the maximal number of bytes to be - // written ("\uxxxx\uxxxx\0") for one code point - if (string_buffer.size() - bytes < 13) - { - o->write_characters(string_buffer.data(), bytes); - bytes = 0; - } - - // remember the byte position of this accept - bytes_after_last_accept = bytes; - undumped_chars = 0; - break; - } - - case UTF8_REJECT: // decode found invalid UTF-8 byte - { - switch (error_handler) - { - case error_handler_t::strict: - { - std::stringstream ss; - ss << std::uppercase << std::setfill('0') << std::setw(2) << std::hex << (byte | 0); - JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + ss.str(), BasicJsonType())); - } - - case error_handler_t::ignore: - case error_handler_t::replace: - { - // in case we saw this character the first time, we - // would like to read it again, because the byte - // may be OK for itself, but just not OK for the - // previous sequence - if (undumped_chars > 0) - { - --i; - } - - // reset length buffer to the last accepted index; - // thus removing/ignoring the invalid characters - bytes = bytes_after_last_accept; - - if (error_handler == error_handler_t::replace) - { - // add a replacement character - if (ensure_ascii) - { - string_buffer[bytes++] = '\\'; - string_buffer[bytes++] = 'u'; - string_buffer[bytes++] = 'f'; - string_buffer[bytes++] = 'f'; - string_buffer[bytes++] = 'f'; - string_buffer[bytes++] = 'd'; - } - else - { - string_buffer[bytes++] = detail::binary_writer::to_char_type('\xEF'); - string_buffer[bytes++] = detail::binary_writer::to_char_type('\xBF'); - string_buffer[bytes++] = detail::binary_writer::to_char_type('\xBD'); - } - - // write buffer and reset index; there must be 13 bytes - // left, as this is the maximal number of bytes to be - // written ("\uxxxx\uxxxx\0") for one code point - if (string_buffer.size() - bytes < 13) - { - o->write_characters(string_buffer.data(), bytes); - bytes = 0; - } - - bytes_after_last_accept = bytes; - } - - undumped_chars = 0; - - // continue processing the string - state = UTF8_ACCEPT; - break; - } - - default: // LCOV_EXCL_LINE - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE - } - break; - } - - default: // decode found yet incomplete multi-byte code point - { - if (!ensure_ascii) - { - // code point will not be escaped - copy byte to buffer - string_buffer[bytes++] = s[i]; - } - ++undumped_chars; - break; - } - } - } - - // we finished processing the string - if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT)) - { - // write buffer - if (bytes > 0) - { - o->write_characters(string_buffer.data(), bytes); - } - } - else - { - // we finish reading, but do not accept: string was incomplete - switch (error_handler) - { - case error_handler_t::strict: - { - std::stringstream ss; - ss << std::uppercase << std::setfill('0') << std::setw(2) << std::hex << (static_cast(s.back()) | 0); - JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + ss.str(), BasicJsonType())); - } - - case error_handler_t::ignore: - { - // write all accepted bytes - o->write_characters(string_buffer.data(), bytes_after_last_accept); - break; - } - - case error_handler_t::replace: - { - // write all accepted bytes - o->write_characters(string_buffer.data(), bytes_after_last_accept); - // add a replacement character - if (ensure_ascii) - { - o->write_characters("\\ufffd", 6); - } - else - { - o->write_characters("\xEF\xBF\xBD", 3); - } - break; - } - - default: // LCOV_EXCL_LINE - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE - } - } - } - - private: - /*! - @brief count digits - - Count the number of decimal (base 10) digits for an input unsigned integer. - - @param[in] x unsigned integer number to count its digits - @return number of decimal digits - */ - inline unsigned int count_digits(number_unsigned_t x) noexcept - { - unsigned int n_digits = 1; - for (;;) - { - if (x < 10) - { - return n_digits; - } - if (x < 100) - { - return n_digits + 1; - } - if (x < 1000) - { - return n_digits + 2; - } - if (x < 10000) - { - return n_digits + 3; - } - x = x / 10000u; - n_digits += 4; - } - } - - // templates to avoid warnings about useless casts - template ::value, int> = 0> - bool is_negative_number(NumberType x) - { - return x < 0; - } - - template < typename NumberType, enable_if_t ::value, int > = 0 > - bool is_negative_number(NumberType /*unused*/) - { - return false; - } - - /*! - @brief dump an integer - - Dump a given integer to output stream @a o. Works internally with - @a number_buffer. - - @param[in] x integer number (signed or unsigned) to dump - @tparam NumberType either @a number_integer_t or @a number_unsigned_t - */ - template < typename NumberType, detail::enable_if_t < - std::is_integral::value || - std::is_same::value || - std::is_same::value || - std::is_same::value, - int > = 0 > - void dump_integer(NumberType x) - { - static constexpr std::array, 100> digits_to_99 - { - { - {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}}, - {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}}, - {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}}, - {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}}, - {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}}, - {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}}, - {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}}, - {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}}, - {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}}, - {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}}, - } - }; - - // special case for "0" - if (x == 0) - { - o->write_character('0'); - return; - } - - // use a pointer to fill the buffer - auto buffer_ptr = number_buffer.begin(); // NOLINT(llvm-qualified-auto,readability-qualified-auto,cppcoreguidelines-pro-type-vararg,hicpp-vararg) - - number_unsigned_t abs_value; - - unsigned int n_chars{}; - - if (is_negative_number(x)) - { - *buffer_ptr = '-'; - abs_value = remove_sign(static_cast(x)); - - // account one more byte for the minus sign - n_chars = 1 + count_digits(abs_value); - } - else - { - abs_value = static_cast(x); - n_chars = count_digits(abs_value); - } - - // spare 1 byte for '\0' - JSON_ASSERT(n_chars < number_buffer.size() - 1); - - // jump to the end to generate the string from backward, - // so we later avoid reversing the result - buffer_ptr += n_chars; - - // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu - // See: https://www.youtube.com/watch?v=o4-CwDo2zpg - while (abs_value >= 100) - { - const auto digits_index = static_cast((abs_value % 100)); - abs_value /= 100; - *(--buffer_ptr) = digits_to_99[digits_index][1]; - *(--buffer_ptr) = digits_to_99[digits_index][0]; - } - - if (abs_value >= 10) - { - const auto digits_index = static_cast(abs_value); - *(--buffer_ptr) = digits_to_99[digits_index][1]; - *(--buffer_ptr) = digits_to_99[digits_index][0]; - } - else - { - *(--buffer_ptr) = static_cast('0' + abs_value); - } - - o->write_characters(number_buffer.data(), n_chars); - } - - /*! - @brief dump a floating-point number - - Dump a given floating-point number to output stream @a o. Works internally - with @a number_buffer. - - @param[in] x floating-point number to dump - */ - void dump_float(number_float_t x) - { - // NaN / inf - if (!std::isfinite(x)) - { - o->write_characters("null", 4); - return; - } - - // If number_float_t is an IEEE-754 single or double precision number, - // use the Grisu2 algorithm to produce short numbers which are - // guaranteed to round-trip, using strtof and strtod, resp. - // - // NB: The test below works if == . - static constexpr bool is_ieee_single_or_double - = (std::numeric_limits::is_iec559 && std::numeric_limits::digits == 24 && std::numeric_limits::max_exponent == 128) || - (std::numeric_limits::is_iec559 && std::numeric_limits::digits == 53 && std::numeric_limits::max_exponent == 1024); - - dump_float(x, std::integral_constant()); - } - - void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/) - { - auto* begin = number_buffer.data(); - auto* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x); - - o->write_characters(begin, static_cast(end - begin)); - } - - void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/) - { - // get number of digits for a float -> text -> float round-trip - static constexpr auto d = std::numeric_limits::max_digits10; - - // the actual conversion - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) - std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x); - - // negative value indicates an error - JSON_ASSERT(len > 0); - // check if buffer was large enough - JSON_ASSERT(static_cast(len) < number_buffer.size()); - - // erase thousands separator - if (thousands_sep != '\0') - { - // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::remove returns an iterator, see https://github.com/nlohmann/json/issues/3081 - const auto end = std::remove(number_buffer.begin(), number_buffer.begin() + len, thousands_sep); - std::fill(end, number_buffer.end(), '\0'); - JSON_ASSERT((end - number_buffer.begin()) <= len); - len = (end - number_buffer.begin()); - } - - // convert decimal point to '.' - if (decimal_point != '\0' && decimal_point != '.') - { - // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::find returns an iterator, see https://github.com/nlohmann/json/issues/3081 - const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point); - if (dec_pos != number_buffer.end()) - { - *dec_pos = '.'; - } - } - - o->write_characters(number_buffer.data(), static_cast(len)); - - // determine if we need to append ".0" - const bool value_is_int_like = - std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1, - [](char c) - { - return c == '.' || c == 'e'; - }); - - if (value_is_int_like) - { - o->write_characters(".0", 2); - } - } - - /*! - @brief check whether a string is UTF-8 encoded - - The function checks each byte of a string whether it is UTF-8 encoded. The - result of the check is stored in the @a state parameter. The function must - be called initially with state 0 (accept). State 1 means the string must - be rejected, because the current byte is not allowed. If the string is - completely processed, but the state is non-zero, the string ended - prematurely; that is, the last byte indicated more bytes should have - followed. - - @param[in,out] state the state of the decoding - @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT) - @param[in] byte next byte to decode - @return new state - - @note The function has been edited: a std::array is used. - - @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann - @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ - */ - static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept - { - static const std::array utf8d = - { - { - 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, // 00..1F - 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, // 20..3F - 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, // 40..5F - 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, // 60..7F - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9F - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // A0..BF - 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C0..DF - 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF - 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF - 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2 - 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4 - 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6 - 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // s7..s8 - } - }; - - JSON_ASSERT(byte < utf8d.size()); - const std::uint8_t type = utf8d[byte]; - - codep = (state != UTF8_ACCEPT) - ? (byte & 0x3fu) | (codep << 6u) - : (0xFFu >> type) & (byte); - - std::size_t index = 256u + static_cast(state) * 16u + static_cast(type); - JSON_ASSERT(index < 400); - state = utf8d[index]; - return state; - } - - /* - * Overload to make the compiler happy while it is instantiating - * dump_integer for number_unsigned_t. - * Must never be called. - */ - number_unsigned_t remove_sign(number_unsigned_t x) - { - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE - return x; // LCOV_EXCL_LINE - } - - /* - * Helper function for dump_integer - * - * This function takes a negative signed integer and returns its absolute - * value as unsigned integer. The plus/minus shuffling is necessary as we can - * not directly remove the sign of an arbitrary signed integer as the - * absolute values of INT_MIN and INT_MAX are usually not the same. See - * #1708 for details. - */ - inline number_unsigned_t remove_sign(number_integer_t x) noexcept - { - JSON_ASSERT(x < 0 && x < (std::numeric_limits::max)()); // NOLINT(misc-redundant-expression) - return static_cast(-(x + 1)) + 1; - } - - private: - /// the output of the serializer - output_adapter_t o = nullptr; - - /// a (hopefully) large enough character buffer - std::array number_buffer{{}}; - - /// the locale - const std::lconv* loc = nullptr; - /// the locale's thousand separator character - const char thousands_sep = '\0'; - /// the locale's decimal point character - const char decimal_point = '\0'; - - /// string buffer - std::array string_buffer{{}}; - - /// the indentation character - const char indent_char; - /// the indentation string - string_t indent_string; - - /// error_handler how to react on decoding errors - const error_handler_t error_handler; -}; -} // namespace detail -} // namespace nlohmann - -// #include - -// #include - -// #include - - -#include // less -#include // initializer_list -#include // input_iterator_tag, iterator_traits -#include // allocator -#include // for out_of_range -#include // enable_if, is_convertible -#include // pair -#include // vector - -// #include - - -namespace nlohmann -{ - -/// ordered_map: a minimal map-like container that preserves insertion order -/// for use within nlohmann::basic_json -template , - class Allocator = std::allocator>> - struct ordered_map : std::vector, Allocator> -{ - using key_type = Key; - using mapped_type = T; - using Container = std::vector, Allocator>; - using iterator = typename Container::iterator; - using const_iterator = typename Container::const_iterator; - using size_type = typename Container::size_type; - using value_type = typename Container::value_type; - - // Explicit constructors instead of `using Container::Container` - // otherwise older compilers choke on it (GCC <= 5.5, xcode <= 9.4) - ordered_map(const Allocator& alloc = Allocator()) : Container{alloc} {} - template - ordered_map(It first, It last, const Allocator& alloc = Allocator()) - : Container{first, last, alloc} {} - ordered_map(std::initializer_list init, const Allocator& alloc = Allocator() ) - : Container{init, alloc} {} - - std::pair emplace(const key_type& key, T&& t) - { - for (auto it = this->begin(); it != this->end(); ++it) - { - if (it->first == key) - { - return {it, false}; - } - } - Container::emplace_back(key, t); - return {--this->end(), true}; - } - - T& operator[](const Key& key) - { - return emplace(key, T{}).first->second; - } - - const T& operator[](const Key& key) const - { - return at(key); - } - - T& at(const Key& key) - { - for (auto it = this->begin(); it != this->end(); ++it) - { - if (it->first == key) - { - return it->second; - } - } - - JSON_THROW(std::out_of_range("key not found")); - } - - const T& at(const Key& key) const - { - for (auto it = this->begin(); it != this->end(); ++it) - { - if (it->first == key) - { - return it->second; - } - } - - JSON_THROW(std::out_of_range("key not found")); - } - - size_type erase(const Key& key) - { - for (auto it = this->begin(); it != this->end(); ++it) - { - if (it->first == key) - { - // Since we cannot move const Keys, re-construct them in place - for (auto next = it; ++next != this->end(); ++it) - { - it->~value_type(); // Destroy but keep allocation - new (&*it) value_type{std::move(*next)}; - } - Container::pop_back(); - return 1; - } - } - return 0; - } - - iterator erase(iterator pos) - { - return erase(pos, std::next(pos)); - } - - iterator erase(iterator first, iterator last) - { - const auto elements_affected = std::distance(first, last); - const auto offset = std::distance(Container::begin(), first); - - // This is the start situation. We need to delete elements_affected - // elements (3 in this example: e, f, g), and need to return an - // iterator past the last deleted element (h in this example). - // Note that offset is the distance from the start of the vector - // to first. We will need this later. - - // [ a, b, c, d, e, f, g, h, i, j ] - // ^ ^ - // first last - - // Since we cannot move const Keys, we re-construct them in place. - // We start at first and re-construct (viz. copy) the elements from - // the back of the vector. Example for first iteration: - - // ,--------. - // v | destroy e and re-construct with h - // [ a, b, c, d, e, f, g, h, i, j ] - // ^ ^ - // it it + elements_affected - - for (auto it = first; std::next(it, elements_affected) != Container::end(); ++it) - { - it->~value_type(); // destroy but keep allocation - new (&*it) value_type{std::move(*std::next(it, elements_affected))}; // "move" next element to it - } - - // [ a, b, c, d, h, i, j, h, i, j ] - // ^ ^ - // first last - - // remove the unneeded elements at the end of the vector - Container::resize(this->size() - static_cast(elements_affected)); - - // [ a, b, c, d, h, i, j ] - // ^ ^ - // first last - - // first is now pointing past the last deleted element, but we cannot - // use this iterator, because it may have been invalidated by the - // resize call. Instead, we can return begin() + offset. - return Container::begin() + offset; - } - - size_type count(const Key& key) const - { - for (auto it = this->begin(); it != this->end(); ++it) - { - if (it->first == key) - { - return 1; - } - } - return 0; - } - - iterator find(const Key& key) - { - for (auto it = this->begin(); it != this->end(); ++it) - { - if (it->first == key) - { - return it; - } - } - return Container::end(); - } - - const_iterator find(const Key& key) const - { - for (auto it = this->begin(); it != this->end(); ++it) - { - if (it->first == key) - { - return it; - } - } - return Container::end(); - } - - std::pair insert( value_type&& value ) - { - return emplace(value.first, std::move(value.second)); - } - - std::pair insert( const value_type& value ) - { - for (auto it = this->begin(); it != this->end(); ++it) - { - if (it->first == value.first) - { - return {it, false}; - } - } - Container::push_back(value); - return {--this->end(), true}; - } - - template - using require_input_iter = typename std::enable_if::iterator_category, - std::input_iterator_tag>::value>::type; - - template> - void insert(InputIt first, InputIt last) - { - for (auto it = first; it != last; ++it) - { - insert(*it); - } - } -}; - -} // namespace nlohmann - - -#if defined(JSON_HAS_CPP_17) - #include -#endif - -/*! -@brief namespace for Niels Lohmann -@see https://github.com/nlohmann -@since version 1.0.0 -*/ -namespace nlohmann -{ - -/*! -@brief a class to store JSON values - -@internal -@invariant The member variables @a m_value and @a m_type have the following -relationship: -- If `m_type == value_t::object`, then `m_value.object != nullptr`. -- If `m_type == value_t::array`, then `m_value.array != nullptr`. -- If `m_type == value_t::string`, then `m_value.string != nullptr`. -The invariants are checked by member function assert_invariant(). - -@note ObjectType trick from https://stackoverflow.com/a/9860911 -@endinternal - -@since version 1.0.0 - -@nosubgrouping -*/ -NLOHMANN_BASIC_JSON_TPL_DECLARATION -class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions) -{ - private: - template friend struct detail::external_constructor; - friend ::nlohmann::json_pointer; - - template - friend class ::nlohmann::detail::parser; - friend ::nlohmann::detail::serializer; - template - friend class ::nlohmann::detail::iter_impl; - template - friend class ::nlohmann::detail::binary_writer; - template - friend class ::nlohmann::detail::binary_reader; - template - friend class ::nlohmann::detail::json_sax_dom_parser; - template - friend class ::nlohmann::detail::json_sax_dom_callback_parser; - friend class ::nlohmann::detail::exception; - - /// workaround type for MSVC - using basic_json_t = NLOHMANN_BASIC_JSON_TPL; - - JSON_PRIVATE_UNLESS_TESTED: - // convenience aliases for types residing in namespace detail; - using lexer = ::nlohmann::detail::lexer_base; - - template - static ::nlohmann::detail::parser parser( - InputAdapterType adapter, - detail::parser_callback_tcb = nullptr, - const bool allow_exceptions = true, - const bool ignore_comments = false - ) - { - return ::nlohmann::detail::parser(std::move(adapter), - std::move(cb), allow_exceptions, ignore_comments); - } - - private: - using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t; - template - using internal_iterator = ::nlohmann::detail::internal_iterator; - template - using iter_impl = ::nlohmann::detail::iter_impl; - template - using iteration_proxy = ::nlohmann::detail::iteration_proxy; - template using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator; - - template - using output_adapter_t = ::nlohmann::detail::output_adapter_t; - - template - using binary_reader = ::nlohmann::detail::binary_reader; - template using binary_writer = ::nlohmann::detail::binary_writer; - - JSON_PRIVATE_UNLESS_TESTED: - using serializer = ::nlohmann::detail::serializer; - - public: - using value_t = detail::value_t; - /// JSON Pointer, see @ref nlohmann::json_pointer - using json_pointer = ::nlohmann::json_pointer; - template - using json_serializer = JSONSerializer; - /// how to treat decoding errors - using error_handler_t = detail::error_handler_t; - /// how to treat CBOR tags - using cbor_tag_handler_t = detail::cbor_tag_handler_t; - /// helper type for initializer lists of basic_json values - using initializer_list_t = std::initializer_list>; - - using input_format_t = detail::input_format_t; - /// SAX interface type, see @ref nlohmann::json_sax - using json_sax_t = json_sax; - - //////////////// - // exceptions // - //////////////// - - /// @name exceptions - /// Classes to implement user-defined exceptions. - /// @{ - - using exception = detail::exception; - using parse_error = detail::parse_error; - using invalid_iterator = detail::invalid_iterator; - using type_error = detail::type_error; - using out_of_range = detail::out_of_range; - using other_error = detail::other_error; - - /// @} - - - ///////////////////// - // container types // - ///////////////////// - - /// @name container types - /// The canonic container types to use @ref basic_json like any other STL - /// container. - /// @{ - - /// the type of elements in a basic_json container - using value_type = basic_json; - - /// the type of an element reference - using reference = value_type&; - /// the type of an element const reference - using const_reference = const value_type&; - - /// a type to represent differences between iterators - using difference_type = std::ptrdiff_t; - /// a type to represent container sizes - using size_type = std::size_t; - - /// the allocator type - using allocator_type = AllocatorType; - - /// the type of an element pointer - using pointer = typename std::allocator_traits::pointer; - /// the type of an element const pointer - using const_pointer = typename std::allocator_traits::const_pointer; - - /// an iterator for a basic_json container - using iterator = iter_impl; - /// a const iterator for a basic_json container - using const_iterator = iter_impl; - /// a reverse iterator for a basic_json container - using reverse_iterator = json_reverse_iterator; - /// a const reverse iterator for a basic_json container - using const_reverse_iterator = json_reverse_iterator; - - /// @} - - - /// @brief returns the allocator associated with the container - /// @sa https://json.nlohmann.me/api/basic_json/get_allocator/ - static allocator_type get_allocator() - { - return allocator_type(); - } - - /// @brief returns version information on the library - /// @sa https://json.nlohmann.me/api/basic_json/meta/ - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json meta() - { - basic_json result; - - result["copyright"] = "(C) 2013-2022 Niels Lohmann"; - result["name"] = "JSON for Modern C++"; - result["url"] = "https://github.com/nlohmann/json"; - result["version"]["string"] = - std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." + - std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." + - std::to_string(NLOHMANN_JSON_VERSION_PATCH); - result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR; - result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR; - result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH; - -#ifdef _WIN32 - result["platform"] = "win32"; -#elif defined __linux__ - result["platform"] = "linux"; -#elif defined __APPLE__ - result["platform"] = "apple"; -#elif defined __unix__ - result["platform"] = "unix"; -#else - result["platform"] = "unknown"; -#endif - -#if defined(__ICC) || defined(__INTEL_COMPILER) - result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}}; -#elif defined(__clang__) - result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}}; -#elif defined(__GNUC__) || defined(__GNUG__) - result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}}; -#elif defined(__HP_cc) || defined(__HP_aCC) - result["compiler"] = "hp" -#elif defined(__IBMCPP__) - result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}}; -#elif defined(_MSC_VER) - result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}}; -#elif defined(__PGI) - result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}}; -#elif defined(__SUNPRO_CC) - result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}}; -#else - result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}}; -#endif - -#ifdef __cplusplus - result["compiler"]["c++"] = std::to_string(__cplusplus); -#else - result["compiler"]["c++"] = "unknown"; -#endif - return result; - } - - - /////////////////////////// - // JSON value data types // - /////////////////////////// - - /// @name JSON value data types - /// The data types to store a JSON value. These types are derived from - /// the template arguments passed to class @ref basic_json. - /// @{ - - /// @brief object key comparator type - /// @sa https://json.nlohmann.me/api/basic_json/object_comparator_t/ -#if defined(JSON_HAS_CPP_14) - // Use transparent comparator if possible, combined with perfect forwarding - // on find() and count() calls prevents unnecessary string construction. - using object_comparator_t = std::less<>; -#else - using object_comparator_t = std::less; -#endif - - /// @brief a type for an object - /// @sa https://json.nlohmann.me/api/basic_json/object_t/ - using object_t = ObjectType>>; - - /// @brief a type for an array - /// @sa https://json.nlohmann.me/api/basic_json/array_t/ - using array_t = ArrayType>; - - /// @brief a type for a string - /// @sa https://json.nlohmann.me/api/basic_json/string_t/ - using string_t = StringType; - - /// @brief a type for a boolean - /// @sa https://json.nlohmann.me/api/basic_json/boolean_t/ - using boolean_t = BooleanType; - - /// @brief a type for a number (integer) - /// @sa https://json.nlohmann.me/api/basic_json/number_integer_t/ - using number_integer_t = NumberIntegerType; - - /// @brief a type for a number (unsigned) - /// @sa https://json.nlohmann.me/api/basic_json/number_unsigned_t/ - using number_unsigned_t = NumberUnsignedType; - - /// @brief a type for a number (floating-point) - /// @sa https://json.nlohmann.me/api/basic_json/number_float_t/ - using number_float_t = NumberFloatType; - - /// @brief a type for a packed binary type - /// @sa https://json.nlohmann.me/api/basic_json/binary_t/ - using binary_t = nlohmann::byte_container_with_subtype; - - /// @} - - private: - - /// helper for exception-safe object creation - template - JSON_HEDLEY_RETURNS_NON_NULL - static T* create(Args&& ... args) - { - AllocatorType alloc; - using AllocatorTraits = std::allocator_traits>; - - auto deleter = [&](T * obj) - { - AllocatorTraits::deallocate(alloc, obj, 1); - }; - std::unique_ptr obj(AllocatorTraits::allocate(alloc, 1), deleter); - AllocatorTraits::construct(alloc, obj.get(), std::forward(args)...); - JSON_ASSERT(obj != nullptr); - return obj.release(); - } - - //////////////////////// - // JSON value storage // - //////////////////////// - - JSON_PRIVATE_UNLESS_TESTED: - /*! - @brief a JSON value - - The actual storage for a JSON value of the @ref basic_json class. This - union combines the different storage types for the JSON value types - defined in @ref value_t. - - JSON type | value_t type | used type - --------- | --------------- | ------------------------ - object | object | pointer to @ref object_t - array | array | pointer to @ref array_t - string | string | pointer to @ref string_t - boolean | boolean | @ref boolean_t - number | number_integer | @ref number_integer_t - number | number_unsigned | @ref number_unsigned_t - number | number_float | @ref number_float_t - binary | binary | pointer to @ref binary_t - null | null | *no value is stored* - - @note Variable-length types (objects, arrays, and strings) are stored as - pointers. The size of the union should not exceed 64 bits if the default - value types are used. - - @since version 1.0.0 - */ - union json_value - { - /// object (stored with pointer to save storage) - object_t* object; - /// array (stored with pointer to save storage) - array_t* array; - /// string (stored with pointer to save storage) - string_t* string; - /// binary (stored with pointer to save storage) - binary_t* binary; - /// boolean - boolean_t boolean; - /// number (integer) - number_integer_t number_integer; - /// number (unsigned integer) - number_unsigned_t number_unsigned; - /// number (floating-point) - number_float_t number_float; - - /// default constructor (for null values) - json_value() = default; - /// constructor for booleans - json_value(boolean_t v) noexcept : boolean(v) {} - /// constructor for numbers (integer) - json_value(number_integer_t v) noexcept : number_integer(v) {} - /// constructor for numbers (unsigned) - json_value(number_unsigned_t v) noexcept : number_unsigned(v) {} - /// constructor for numbers (floating-point) - json_value(number_float_t v) noexcept : number_float(v) {} - /// constructor for empty values of a given type - json_value(value_t t) - { - switch (t) - { - case value_t::object: - { - object = create(); - break; - } - - case value_t::array: - { - array = create(); - break; - } - - case value_t::string: - { - string = create(""); - break; - } - - case value_t::binary: - { - binary = create(); - break; - } - - case value_t::boolean: - { - boolean = static_cast(false); - break; - } - - case value_t::number_integer: - { - number_integer = static_cast(0); - break; - } - - case value_t::number_unsigned: - { - number_unsigned = static_cast(0); - break; - } - - case value_t::number_float: - { - number_float = static_cast(0.0); - break; - } - - case value_t::null: - { - object = nullptr; // silence warning, see #821 - break; - } - - case value_t::discarded: - default: - { - object = nullptr; // silence warning, see #821 - if (JSON_HEDLEY_UNLIKELY(t == value_t::null)) - { - JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.10.5", basic_json())); // LCOV_EXCL_LINE - } - break; - } - } - } - - /// constructor for strings - json_value(const string_t& value) : string(create(value)) {} - - /// constructor for rvalue strings - json_value(string_t&& value) : string(create(std::move(value))) {} - - /// constructor for objects - json_value(const object_t& value) : object(create(value)) {} - - /// constructor for rvalue objects - json_value(object_t&& value) : object(create(std::move(value))) {} - - /// constructor for arrays - json_value(const array_t& value) : array(create(value)) {} - - /// constructor for rvalue arrays - json_value(array_t&& value) : array(create(std::move(value))) {} - - /// constructor for binary arrays - json_value(const typename binary_t::container_type& value) : binary(create(value)) {} - - /// constructor for rvalue binary arrays - json_value(typename binary_t::container_type&& value) : binary(create(std::move(value))) {} - - /// constructor for binary arrays (internal type) - json_value(const binary_t& value) : binary(create(value)) {} - - /// constructor for rvalue binary arrays (internal type) - json_value(binary_t&& value) : binary(create(std::move(value))) {} - - void destroy(value_t t) - { - if (t == value_t::array || t == value_t::object) - { - // flatten the current json_value to a heap-allocated stack - std::vector stack; - - // move the top-level items to stack - if (t == value_t::array) - { - stack.reserve(array->size()); - std::move(array->begin(), array->end(), std::back_inserter(stack)); - } - else - { - stack.reserve(object->size()); - for (auto&& it : *object) - { - stack.push_back(std::move(it.second)); - } - } - - while (!stack.empty()) - { - // move the last item to local variable to be processed - basic_json current_item(std::move(stack.back())); - stack.pop_back(); - - // if current_item is array/object, move - // its children to the stack to be processed later - if (current_item.is_array()) - { - std::move(current_item.m_value.array->begin(), current_item.m_value.array->end(), std::back_inserter(stack)); - - current_item.m_value.array->clear(); - } - else if (current_item.is_object()) - { - for (auto&& it : *current_item.m_value.object) - { - stack.push_back(std::move(it.second)); - } - - current_item.m_value.object->clear(); - } - - // it's now safe that current_item get destructed - // since it doesn't have any children - } - } - - switch (t) - { - case value_t::object: - { - AllocatorType alloc; - std::allocator_traits::destroy(alloc, object); - std::allocator_traits::deallocate(alloc, object, 1); - break; - } - - case value_t::array: - { - AllocatorType alloc; - std::allocator_traits::destroy(alloc, array); - std::allocator_traits::deallocate(alloc, array, 1); - break; - } - - case value_t::string: - { - AllocatorType alloc; - std::allocator_traits::destroy(alloc, string); - std::allocator_traits::deallocate(alloc, string, 1); - break; - } - - case value_t::binary: - { - AllocatorType alloc; - std::allocator_traits::destroy(alloc, binary); - std::allocator_traits::deallocate(alloc, binary, 1); - break; - } - - case value_t::null: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::discarded: - default: - { - break; - } - } - } - }; - - private: - /*! - @brief checks the class invariants - - This function asserts the class invariants. It needs to be called at the - end of every constructor to make sure that created objects respect the - invariant. Furthermore, it has to be called each time the type of a JSON - value is changed, because the invariant expresses a relationship between - @a m_type and @a m_value. - - Furthermore, the parent relation is checked for arrays and objects: If - @a check_parents true and the value is an array or object, then the - container's elements must have the current value as parent. - - @param[in] check_parents whether the parent relation should be checked. - The value is true by default and should only be set to false - during destruction of objects when the invariant does not - need to hold. - */ - void assert_invariant(bool check_parents = true) const noexcept - { - JSON_ASSERT(m_type != value_t::object || m_value.object != nullptr); - JSON_ASSERT(m_type != value_t::array || m_value.array != nullptr); - JSON_ASSERT(m_type != value_t::string || m_value.string != nullptr); - JSON_ASSERT(m_type != value_t::binary || m_value.binary != nullptr); - -#if JSON_DIAGNOSTICS - JSON_TRY - { - // cppcheck-suppress assertWithSideEffect - JSON_ASSERT(!check_parents || !is_structured() || std::all_of(begin(), end(), [this](const basic_json & j) - { - return j.m_parent == this; - })); - } - JSON_CATCH(...) {} // LCOV_EXCL_LINE -#endif - static_cast(check_parents); - } - - void set_parents() - { -#if JSON_DIAGNOSTICS - switch (m_type) - { - case value_t::array: - { - for (auto& element : *m_value.array) - { - element.m_parent = this; - } - break; - } - - case value_t::object: - { - for (auto& element : *m_value.object) - { - element.second.m_parent = this; - } - break; - } - - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - break; - } -#endif - } - - iterator set_parents(iterator it, typename iterator::difference_type count_set_parents) - { -#if JSON_DIAGNOSTICS - for (typename iterator::difference_type i = 0; i < count_set_parents; ++i) - { - (it + i)->m_parent = this; - } -#else - static_cast(count_set_parents); -#endif - return it; - } - - reference set_parent(reference j, std::size_t old_capacity = static_cast(-1)) - { -#if JSON_DIAGNOSTICS - if (old_capacity != static_cast(-1)) - { - // see https://github.com/nlohmann/json/issues/2838 - JSON_ASSERT(type() == value_t::array); - if (JSON_HEDLEY_UNLIKELY(m_value.array->capacity() != old_capacity)) - { - // capacity has changed: update all parents - set_parents(); - return j; - } - } - - // ordered_json uses a vector internally, so pointers could have - // been invalidated; see https://github.com/nlohmann/json/issues/2962 -#ifdef JSON_HEDLEY_MSVC_VERSION -#pragma warning(push ) -#pragma warning(disable : 4127) // ignore warning to replace if with if constexpr -#endif - if (detail::is_ordered_map::value) - { - set_parents(); - return j; - } -#ifdef JSON_HEDLEY_MSVC_VERSION -#pragma warning( pop ) -#endif - - j.m_parent = this; -#else - static_cast(j); - static_cast(old_capacity); -#endif - return j; - } - - public: - ////////////////////////// - // JSON parser callback // - ////////////////////////// - - /// @brief parser event types - /// @sa https://json.nlohmann.me/api/basic_json/parse_event_t/ - using parse_event_t = detail::parse_event_t; - - /// @brief per-element parser callback type - /// @sa https://json.nlohmann.me/api/basic_json/parser_callback_t/ - using parser_callback_t = detail::parser_callback_t; - - ////////////////// - // constructors // - ////////////////// - - /// @name constructors and destructors - /// Constructors of class @ref basic_json, copy/move constructor, copy - /// assignment, static functions creating objects, and the destructor. - /// @{ - - /// @brief create an empty value with a given type - /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ - basic_json(const value_t v) - : m_type(v), m_value(v) - { - assert_invariant(); - } - - /// @brief create a null object - /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ - basic_json(std::nullptr_t = nullptr) noexcept - : basic_json(value_t::null) - { - assert_invariant(); - } - - /// @brief create a JSON value from compatible types - /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ - template < typename CompatibleType, - typename U = detail::uncvref_t, - detail::enable_if_t < - !detail::is_basic_json::value && detail::is_compatible_type::value, int > = 0 > - basic_json(CompatibleType && val) noexcept(noexcept( // NOLINT(bugprone-forwarding-reference-overload,bugprone-exception-escape) - JSONSerializer::to_json(std::declval(), - std::forward(val)))) - { - JSONSerializer::to_json(*this, std::forward(val)); - set_parents(); - assert_invariant(); - } - - /// @brief create a JSON value from an existing one - /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ - template < typename BasicJsonType, - detail::enable_if_t < - detail::is_basic_json::value&& !std::is_same::value, int > = 0 > - basic_json(const BasicJsonType& val) - { - using other_boolean_t = typename BasicJsonType::boolean_t; - using other_number_float_t = typename BasicJsonType::number_float_t; - using other_number_integer_t = typename BasicJsonType::number_integer_t; - using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using other_string_t = typename BasicJsonType::string_t; - using other_object_t = typename BasicJsonType::object_t; - using other_array_t = typename BasicJsonType::array_t; - using other_binary_t = typename BasicJsonType::binary_t; - - switch (val.type()) - { - case value_t::boolean: - JSONSerializer::to_json(*this, val.template get()); - break; - case value_t::number_float: - JSONSerializer::to_json(*this, val.template get()); - break; - case value_t::number_integer: - JSONSerializer::to_json(*this, val.template get()); - break; - case value_t::number_unsigned: - JSONSerializer::to_json(*this, val.template get()); - break; - case value_t::string: - JSONSerializer::to_json(*this, val.template get_ref()); - break; - case value_t::object: - JSONSerializer::to_json(*this, val.template get_ref()); - break; - case value_t::array: - JSONSerializer::to_json(*this, val.template get_ref()); - break; - case value_t::binary: - JSONSerializer::to_json(*this, val.template get_ref()); - break; - case value_t::null: - *this = nullptr; - break; - case value_t::discarded: - m_type = value_t::discarded; - break; - default: // LCOV_EXCL_LINE - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE - } - set_parents(); - assert_invariant(); - } - - /// @brief create a container (array or object) from an initializer list - /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ - basic_json(initializer_list_t init, - bool type_deduction = true, - value_t manual_type = value_t::array) - { - // check if each element is an array with two elements whose first - // element is a string - bool is_an_object = std::all_of(init.begin(), init.end(), - [](const detail::json_ref& element_ref) - { - return element_ref->is_array() && element_ref->size() == 2 && (*element_ref)[0].is_string(); - }); - - // adjust type if type deduction is not wanted - if (!type_deduction) - { - // if array is wanted, do not create an object though possible - if (manual_type == value_t::array) - { - is_an_object = false; - } - - // if object is wanted but impossible, throw an exception - if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object && !is_an_object)) - { - JSON_THROW(type_error::create(301, "cannot create object from initializer list", basic_json())); - } - } - - if (is_an_object) - { - // the initializer list is a list of pairs -> create object - m_type = value_t::object; - m_value = value_t::object; - - for (auto& element_ref : init) - { - auto element = element_ref.moved_or_copied(); - m_value.object->emplace( - std::move(*((*element.m_value.array)[0].m_value.string)), - std::move((*element.m_value.array)[1])); - } - } - else - { - // the initializer list describes an array -> create array - m_type = value_t::array; - m_value.array = create(init.begin(), init.end()); - } - - set_parents(); - assert_invariant(); - } - - /// @brief explicitly create a binary array (without subtype) - /// @sa https://json.nlohmann.me/api/basic_json/binary/ - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json binary(const typename binary_t::container_type& init) - { - auto res = basic_json(); - res.m_type = value_t::binary; - res.m_value = init; - return res; - } - - /// @brief explicitly create a binary array (with subtype) - /// @sa https://json.nlohmann.me/api/basic_json/binary/ - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json binary(const typename binary_t::container_type& init, typename binary_t::subtype_type subtype) - { - auto res = basic_json(); - res.m_type = value_t::binary; - res.m_value = binary_t(init, subtype); - return res; - } - - /// @brief explicitly create a binary array - /// @sa https://json.nlohmann.me/api/basic_json/binary/ - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json binary(typename binary_t::container_type&& init) - { - auto res = basic_json(); - res.m_type = value_t::binary; - res.m_value = std::move(init); - return res; - } - - /// @brief explicitly create a binary array (with subtype) - /// @sa https://json.nlohmann.me/api/basic_json/binary/ - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json binary(typename binary_t::container_type&& init, typename binary_t::subtype_type subtype) - { - auto res = basic_json(); - res.m_type = value_t::binary; - res.m_value = binary_t(std::move(init), subtype); - return res; - } - - /// @brief explicitly create an array from an initializer list - /// @sa https://json.nlohmann.me/api/basic_json/array/ - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json array(initializer_list_t init = {}) - { - return basic_json(init, false, value_t::array); - } - - /// @brief explicitly create an object from an initializer list - /// @sa https://json.nlohmann.me/api/basic_json/object/ - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json object(initializer_list_t init = {}) - { - return basic_json(init, false, value_t::object); - } - - /// @brief construct an array with count copies of given value - /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ - basic_json(size_type cnt, const basic_json& val) - : m_type(value_t::array) - { - m_value.array = create(cnt, val); - set_parents(); - assert_invariant(); - } - - /// @brief construct a JSON container given an iterator range - /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ - template < class InputIT, typename std::enable_if < - std::is_same::value || - std::is_same::value, int >::type = 0 > - basic_json(InputIT first, InputIT last) - { - JSON_ASSERT(first.m_object != nullptr); - JSON_ASSERT(last.m_object != nullptr); - - // make sure iterator fits the current value - if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) - { - JSON_THROW(invalid_iterator::create(201, "iterators are not compatible", basic_json())); - } - - // copy type from first iterator - m_type = first.m_object->m_type; - - // check if iterator range is complete for primitive values - switch (m_type) - { - case value_t::boolean: - case value_t::number_float: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::string: - { - if (JSON_HEDLEY_UNLIKELY(!first.m_it.primitive_iterator.is_begin() - || !last.m_it.primitive_iterator.is_end())) - { - JSON_THROW(invalid_iterator::create(204, "iterators out of range", *first.m_object)); - } - break; - } - - case value_t::null: - case value_t::object: - case value_t::array: - case value_t::binary: - case value_t::discarded: - default: - break; - } - - switch (m_type) - { - case value_t::number_integer: - { - m_value.number_integer = first.m_object->m_value.number_integer; - break; - } - - case value_t::number_unsigned: - { - m_value.number_unsigned = first.m_object->m_value.number_unsigned; - break; - } - - case value_t::number_float: - { - m_value.number_float = first.m_object->m_value.number_float; - break; - } - - case value_t::boolean: - { - m_value.boolean = first.m_object->m_value.boolean; - break; - } - - case value_t::string: - { - m_value = *first.m_object->m_value.string; - break; - } - - case value_t::object: - { - m_value.object = create(first.m_it.object_iterator, - last.m_it.object_iterator); - break; - } - - case value_t::array: - { - m_value.array = create(first.m_it.array_iterator, - last.m_it.array_iterator); - break; - } - - case value_t::binary: - { - m_value = *first.m_object->m_value.binary; - break; - } - - case value_t::null: - case value_t::discarded: - default: - JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " + std::string(first.m_object->type_name()), *first.m_object)); - } - - set_parents(); - assert_invariant(); - } - - - /////////////////////////////////////// - // other constructors and destructor // - /////////////////////////////////////// - - template, - std::is_same>::value, int> = 0 > - basic_json(const JsonRef& ref) : basic_json(ref.moved_or_copied()) {} - - /// @brief copy constructor - /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ - basic_json(const basic_json& other) - : m_type(other.m_type) - { - // check of passed value is valid - other.assert_invariant(); - - switch (m_type) - { - case value_t::object: - { - m_value = *other.m_value.object; - break; - } - - case value_t::array: - { - m_value = *other.m_value.array; - break; - } - - case value_t::string: - { - m_value = *other.m_value.string; - break; - } - - case value_t::boolean: - { - m_value = other.m_value.boolean; - break; - } - - case value_t::number_integer: - { - m_value = other.m_value.number_integer; - break; - } - - case value_t::number_unsigned: - { - m_value = other.m_value.number_unsigned; - break; - } - - case value_t::number_float: - { - m_value = other.m_value.number_float; - break; - } - - case value_t::binary: - { - m_value = *other.m_value.binary; - break; - } - - case value_t::null: - case value_t::discarded: - default: - break; - } - - set_parents(); - assert_invariant(); - } - - /// @brief move constructor - /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ - basic_json(basic_json&& other) noexcept - : m_type(std::move(other.m_type)), - m_value(std::move(other.m_value)) - { - // check that passed value is valid - other.assert_invariant(false); - - // invalidate payload - other.m_type = value_t::null; - other.m_value = {}; - - set_parents(); - assert_invariant(); - } - - /// @brief copy assignment - /// @sa https://json.nlohmann.me/api/basic_json/operator=/ - basic_json& operator=(basic_json other) noexcept ( - std::is_nothrow_move_constructible::value&& - std::is_nothrow_move_assignable::value&& - std::is_nothrow_move_constructible::value&& - std::is_nothrow_move_assignable::value - ) - { - // check that passed value is valid - other.assert_invariant(); - - using std::swap; - swap(m_type, other.m_type); - swap(m_value, other.m_value); - - set_parents(); - assert_invariant(); - return *this; - } - - /// @brief destructor - /// @sa https://json.nlohmann.me/api/basic_json/~basic_json/ - ~basic_json() noexcept - { - assert_invariant(false); - m_value.destroy(m_type); - } - - /// @} - - public: - /////////////////////// - // object inspection // - /////////////////////// - - /// @name object inspection - /// Functions to inspect the type of a JSON value. - /// @{ - - /// @brief serialization - /// @sa https://json.nlohmann.me/api/basic_json/dump/ - string_t dump(const int indent = -1, - const char indent_char = ' ', - const bool ensure_ascii = false, - const error_handler_t error_handler = error_handler_t::strict) const - { - string_t result; - serializer s(detail::output_adapter(result), indent_char, error_handler); - - if (indent >= 0) - { - s.dump(*this, true, ensure_ascii, static_cast(indent)); - } - else - { - s.dump(*this, false, ensure_ascii, 0); - } - - return result; - } - - /// @brief return the type of the JSON value (explicit) - /// @sa https://json.nlohmann.me/api/basic_json/type/ - constexpr value_t type() const noexcept - { - return m_type; - } - - /// @brief return whether type is primitive - /// @sa https://json.nlohmann.me/api/basic_json/is_primitive/ - constexpr bool is_primitive() const noexcept - { - return is_null() || is_string() || is_boolean() || is_number() || is_binary(); - } - - /// @brief return whether type is structured - /// @sa https://json.nlohmann.me/api/basic_json/is_structured/ - constexpr bool is_structured() const noexcept - { - return is_array() || is_object(); - } - - /// @brief return whether value is null - /// @sa https://json.nlohmann.me/api/basic_json/is_null/ - constexpr bool is_null() const noexcept - { - return m_type == value_t::null; - } - - /// @brief return whether value is a boolean - /// @sa https://json.nlohmann.me/api/basic_json/is_boolean/ - constexpr bool is_boolean() const noexcept - { - return m_type == value_t::boolean; - } - - /// @brief return whether value is a number - /// @sa https://json.nlohmann.me/api/basic_json/is_number/ - constexpr bool is_number() const noexcept - { - return is_number_integer() || is_number_float(); - } - - /// @brief return whether value is an integer number - /// @sa https://json.nlohmann.me/api/basic_json/is_number_integer/ - constexpr bool is_number_integer() const noexcept - { - return m_type == value_t::number_integer || m_type == value_t::number_unsigned; - } - - /// @brief return whether value is an unsigned integer number - /// @sa https://json.nlohmann.me/api/basic_json/is_number_unsigned/ - constexpr bool is_number_unsigned() const noexcept - { - return m_type == value_t::number_unsigned; - } - - /// @brief return whether value is a floating-point number - /// @sa https://json.nlohmann.me/api/basic_json/is_number_float/ - constexpr bool is_number_float() const noexcept - { - return m_type == value_t::number_float; - } - - /// @brief return whether value is an object - /// @sa https://json.nlohmann.me/api/basic_json/is_object/ - constexpr bool is_object() const noexcept - { - return m_type == value_t::object; - } - - /// @brief return whether value is an array - /// @sa https://json.nlohmann.me/api/basic_json/is_array/ - constexpr bool is_array() const noexcept - { - return m_type == value_t::array; - } - - /// @brief return whether value is a string - /// @sa https://json.nlohmann.me/api/basic_json/is_string/ - constexpr bool is_string() const noexcept - { - return m_type == value_t::string; - } - - /// @brief return whether value is a binary array - /// @sa https://json.nlohmann.me/api/basic_json/is_binary/ - constexpr bool is_binary() const noexcept - { - return m_type == value_t::binary; - } - - /// @brief return whether value is discarded - /// @sa https://json.nlohmann.me/api/basic_json/is_discarded/ - constexpr bool is_discarded() const noexcept - { - return m_type == value_t::discarded; - } - - /// @brief return the type of the JSON value (implicit) - /// @sa https://json.nlohmann.me/api/basic_json/operator_value_t/ - constexpr operator value_t() const noexcept - { - return m_type; - } - - /// @} - - private: - ////////////////// - // value access // - ////////////////// - - /// get a boolean (explicit) - boolean_t get_impl(boolean_t* /*unused*/) const - { - if (JSON_HEDLEY_LIKELY(is_boolean())) - { - return m_value.boolean; - } - - JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name()), *this)); - } - - /// get a pointer to the value (object) - object_t* get_impl_ptr(object_t* /*unused*/) noexcept - { - return is_object() ? m_value.object : nullptr; - } - - /// get a pointer to the value (object) - constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept - { - return is_object() ? m_value.object : nullptr; - } - - /// get a pointer to the value (array) - array_t* get_impl_ptr(array_t* /*unused*/) noexcept - { - return is_array() ? m_value.array : nullptr; - } - - /// get a pointer to the value (array) - constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept - { - return is_array() ? m_value.array : nullptr; - } - - /// get a pointer to the value (string) - string_t* get_impl_ptr(string_t* /*unused*/) noexcept - { - return is_string() ? m_value.string : nullptr; - } - - /// get a pointer to the value (string) - constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept - { - return is_string() ? m_value.string : nullptr; - } - - /// get a pointer to the value (boolean) - boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept - { - return is_boolean() ? &m_value.boolean : nullptr; - } - - /// get a pointer to the value (boolean) - constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept - { - return is_boolean() ? &m_value.boolean : nullptr; - } - - /// get a pointer to the value (integer number) - number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept - { - return is_number_integer() ? &m_value.number_integer : nullptr; - } - - /// get a pointer to the value (integer number) - constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept - { - return is_number_integer() ? &m_value.number_integer : nullptr; - } - - /// get a pointer to the value (unsigned number) - number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept - { - return is_number_unsigned() ? &m_value.number_unsigned : nullptr; - } - - /// get a pointer to the value (unsigned number) - constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept - { - return is_number_unsigned() ? &m_value.number_unsigned : nullptr; - } - - /// get a pointer to the value (floating-point number) - number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept - { - return is_number_float() ? &m_value.number_float : nullptr; - } - - /// get a pointer to the value (floating-point number) - constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept - { - return is_number_float() ? &m_value.number_float : nullptr; - } - - /// get a pointer to the value (binary) - binary_t* get_impl_ptr(binary_t* /*unused*/) noexcept - { - return is_binary() ? m_value.binary : nullptr; - } - - /// get a pointer to the value (binary) - constexpr const binary_t* get_impl_ptr(const binary_t* /*unused*/) const noexcept - { - return is_binary() ? m_value.binary : nullptr; - } - - /*! - @brief helper function to implement get_ref() - - This function helps to implement get_ref() without code duplication for - const and non-const overloads - - @tparam ThisType will be deduced as `basic_json` or `const basic_json` - - @throw type_error.303 if ReferenceType does not match underlying value - type of the current JSON - */ - template - static ReferenceType get_ref_impl(ThisType& obj) - { - // delegate the call to get_ptr<>() - auto* ptr = obj.template get_ptr::type>(); - - if (JSON_HEDLEY_LIKELY(ptr != nullptr)) - { - return *ptr; - } - - JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name()), obj)); - } - - public: - /// @name value access - /// Direct access to the stored value of a JSON value. - /// @{ - - /// @brief get a pointer value (implicit) - /// @sa https://json.nlohmann.me/api/basic_json/get_ptr/ - template::value, int>::type = 0> - auto get_ptr() noexcept -> decltype(std::declval().get_impl_ptr(std::declval())) - { - // delegate the call to get_impl_ptr<>() - return get_impl_ptr(static_cast(nullptr)); - } - - /// @brief get a pointer value (implicit) - /// @sa https://json.nlohmann.me/api/basic_json/get_ptr/ - template < typename PointerType, typename std::enable_if < - std::is_pointer::value&& - std::is_const::type>::value, int >::type = 0 > - constexpr auto get_ptr() const noexcept -> decltype(std::declval().get_impl_ptr(std::declval())) - { - // delegate the call to get_impl_ptr<>() const - return get_impl_ptr(static_cast(nullptr)); - } - - private: - /*! - @brief get a value (explicit) - - Explicit type conversion between the JSON value and a compatible value - which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) - and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). - The value is converted by calling the @ref json_serializer - `from_json()` method. - - The function is equivalent to executing - @code {.cpp} - ValueType ret; - JSONSerializer::from_json(*this, ret); - return ret; - @endcode - - This overloads is chosen if: - - @a ValueType is not @ref basic_json, - - @ref json_serializer has a `from_json()` method of the form - `void from_json(const basic_json&, ValueType&)`, and - - @ref json_serializer does not have a `from_json()` method of - the form `ValueType from_json(const basic_json&)` - - @tparam ValueType the returned value type - - @return copy of the JSON value, converted to @a ValueType - - @throw what @ref json_serializer `from_json()` method throws - - @liveexample{The example below shows several conversions from JSON values - to other types. There a few things to note: (1) Floating-point numbers can - be converted to integers\, (2) A JSON array can be converted to a standard - `std::vector`\, (3) A JSON object can be converted to C++ - associative containers such as `std::unordered_map`.,get__ValueType_const} - - @since version 2.1.0 - */ - template < typename ValueType, - detail::enable_if_t < - detail::is_default_constructible::value&& - detail::has_from_json::value, - int > = 0 > - ValueType get_impl(detail::priority_tag<0> /*unused*/) const noexcept(noexcept( - JSONSerializer::from_json(std::declval(), std::declval()))) - { - auto ret = ValueType(); - JSONSerializer::from_json(*this, ret); - return ret; - } - - /*! - @brief get a value (explicit); special case - - Explicit type conversion between the JSON value and a compatible value - which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) - and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). - The value is converted by calling the @ref json_serializer - `from_json()` method. - - The function is equivalent to executing - @code {.cpp} - return JSONSerializer::from_json(*this); - @endcode - - This overloads is chosen if: - - @a ValueType is not @ref basic_json and - - @ref json_serializer has a `from_json()` method of the form - `ValueType from_json(const basic_json&)` - - @note If @ref json_serializer has both overloads of - `from_json()`, this one is chosen. - - @tparam ValueType the returned value type - - @return copy of the JSON value, converted to @a ValueType - - @throw what @ref json_serializer `from_json()` method throws - - @since version 2.1.0 - */ - template < typename ValueType, - detail::enable_if_t < - detail::has_non_default_from_json::value, - int > = 0 > - ValueType get_impl(detail::priority_tag<1> /*unused*/) const noexcept(noexcept( - JSONSerializer::from_json(std::declval()))) - { - return JSONSerializer::from_json(*this); - } - - /*! - @brief get special-case overload - - This overloads converts the current @ref basic_json in a different - @ref basic_json type - - @tparam BasicJsonType == @ref basic_json - - @return a copy of *this, converted into @a BasicJsonType - - @complexity Depending on the implementation of the called `from_json()` - method. - - @since version 3.2.0 - */ - template < typename BasicJsonType, - detail::enable_if_t < - detail::is_basic_json::value, - int > = 0 > - BasicJsonType get_impl(detail::priority_tag<2> /*unused*/) const - { - return *this; - } - - /*! - @brief get special-case overload - - This overloads avoids a lot of template boilerplate, it can be seen as the - identity method - - @tparam BasicJsonType == @ref basic_json - - @return a copy of *this - - @complexity Constant. - - @since version 2.1.0 - */ - template::value, - int> = 0> - basic_json get_impl(detail::priority_tag<3> /*unused*/) const - { - return *this; - } - - /*! - @brief get a pointer value (explicit) - @copydoc get() - */ - template::value, - int> = 0> - constexpr auto get_impl(detail::priority_tag<4> /*unused*/) const noexcept - -> decltype(std::declval().template get_ptr()) - { - // delegate the call to get_ptr - return get_ptr(); - } - - public: - /*! - @brief get a (pointer) value (explicit) - - Performs explicit type conversion between the JSON value and a compatible value if required. - - - If the requested type is a pointer to the internally stored JSON value that pointer is returned. - No copies are made. - - - If the requested type is the current @ref basic_json, or a different @ref basic_json convertible - from the current @ref basic_json. - - - Otherwise the value is converted by calling the @ref json_serializer `from_json()` - method. - - @tparam ValueTypeCV the provided value type - @tparam ValueType the returned value type - - @return copy of the JSON value, converted to @tparam ValueType if necessary - - @throw what @ref json_serializer `from_json()` method throws if conversion is required - - @since version 2.1.0 - */ - template < typename ValueTypeCV, typename ValueType = detail::uncvref_t> -#if defined(JSON_HAS_CPP_14) - constexpr -#endif - auto get() const noexcept( - noexcept(std::declval().template get_impl(detail::priority_tag<4> {}))) - -> decltype(std::declval().template get_impl(detail::priority_tag<4> {})) - { - // we cannot static_assert on ValueTypeCV being non-const, because - // there is support for get(), which is why we - // still need the uncvref - static_assert(!std::is_reference::value, - "get() cannot be used with reference types, you might want to use get_ref()"); - return get_impl(detail::priority_tag<4> {}); - } - - /*! - @brief get a pointer value (explicit) - - Explicit pointer access to the internally stored JSON value. No copies are - made. - - @warning The pointer becomes invalid if the underlying JSON object - changes. - - @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref - object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, - @ref number_unsigned_t, or @ref number_float_t. - - @return pointer to the internally stored JSON value if the requested - pointer type @a PointerType fits to the JSON value; `nullptr` otherwise - - @complexity Constant. - - @liveexample{The example below shows how pointers to internal values of a - JSON value can be requested. Note that no type conversions are made and a - `nullptr` is returned if the value and the requested pointer type does not - match.,get__PointerType} - - @sa see @ref get_ptr() for explicit pointer-member access - - @since version 1.0.0 - */ - template::value, int>::type = 0> - auto get() noexcept -> decltype(std::declval().template get_ptr()) - { - // delegate the call to get_ptr - return get_ptr(); - } - - /// @brief get a value (explicit) - /// @sa https://json.nlohmann.me/api/basic_json/get_to/ - template < typename ValueType, - detail::enable_if_t < - !detail::is_basic_json::value&& - detail::has_from_json::value, - int > = 0 > - ValueType & get_to(ValueType& v) const noexcept(noexcept( - JSONSerializer::from_json(std::declval(), v))) - { - JSONSerializer::from_json(*this, v); - return v; - } - - // specialization to allow calling get_to with a basic_json value - // see https://github.com/nlohmann/json/issues/2175 - template::value, - int> = 0> - ValueType & get_to(ValueType& v) const - { - v = *this; - return v; - } - - template < - typename T, std::size_t N, - typename Array = T (&)[N], // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) - detail::enable_if_t < - detail::has_from_json::value, int > = 0 > - Array get_to(T (&v)[N]) const // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) - noexcept(noexcept(JSONSerializer::from_json( - std::declval(), v))) - { - JSONSerializer::from_json(*this, v); - return v; - } - - /// @brief get a reference value (implicit) - /// @sa https://json.nlohmann.me/api/basic_json/get_ref/ - template::value, int>::type = 0> - ReferenceType get_ref() - { - // delegate call to get_ref_impl - return get_ref_impl(*this); - } - - /// @brief get a reference value (implicit) - /// @sa https://json.nlohmann.me/api/basic_json/get_ref/ - template < typename ReferenceType, typename std::enable_if < - std::is_reference::value&& - std::is_const::type>::value, int >::type = 0 > - ReferenceType get_ref() const - { - // delegate call to get_ref_impl - return get_ref_impl(*this); - } - - /*! - @brief get a value (implicit) - - Implicit type conversion between the JSON value and a compatible value. - The call is realized by calling @ref get() const. - - @tparam ValueType non-pointer type compatible to the JSON value, for - instance `int` for JSON integer numbers, `bool` for JSON booleans, or - `std::vector` types for JSON arrays. The character type of @ref string_t - as well as an initializer list of this type is excluded to avoid - ambiguities as these types implicitly convert to `std::string`. - - @return copy of the JSON value, converted to type @a ValueType - - @throw type_error.302 in case passed type @a ValueType is incompatible - to the JSON value type (e.g., the JSON value is of type boolean, but a - string is requested); see example below - - @complexity Linear in the size of the JSON value. - - @liveexample{The example below shows several conversions from JSON values - to other types. There a few things to note: (1) Floating-point numbers can - be converted to integers\, (2) A JSON array can be converted to a standard - `std::vector`\, (3) A JSON object can be converted to C++ - associative containers such as `std::unordered_map`.,operator__ValueType} - - @since version 1.0.0 - */ - template < typename ValueType, typename std::enable_if < - detail::conjunction < - detail::negation>, - detail::negation>>, - detail::negation>, - detail::negation>, - detail::negation>>, - -#if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1910 && _MSC_VER <= 1914)) - detail::negation>, -#endif - detail::is_detected_lazy - >::value, int >::type = 0 > - JSON_EXPLICIT operator ValueType() const - { - // delegate the call to get<>() const - return get(); - } - - /// @brief get a binary value - /// @sa https://json.nlohmann.me/api/basic_json/get_binary/ - binary_t& get_binary() - { - if (!is_binary()) - { - JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()), *this)); - } - - return *get_ptr(); - } - - /// @brief get a binary value - /// @sa https://json.nlohmann.me/api/basic_json/get_binary/ - const binary_t& get_binary() const - { - if (!is_binary()) - { - JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()), *this)); - } - - return *get_ptr(); - } - - /// @} - - - //////////////////// - // element access // - //////////////////// - - /// @name element access - /// Access to the JSON value. - /// @{ - - /// @brief access specified array element with bounds checking - /// @sa https://json.nlohmann.me/api/basic_json/at/ - reference at(size_type idx) - { - // at only works for arrays - if (JSON_HEDLEY_LIKELY(is_array())) - { - JSON_TRY - { - return set_parent(m_value.array->at(idx)); - } - JSON_CATCH (std::out_of_range&) - { - // create better exception explanation - JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this)); - } - } - else - { - JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); - } - } - - /// @brief access specified array element with bounds checking - /// @sa https://json.nlohmann.me/api/basic_json/at/ - const_reference at(size_type idx) const - { - // at only works for arrays - if (JSON_HEDLEY_LIKELY(is_array())) - { - JSON_TRY - { - return m_value.array->at(idx); - } - JSON_CATCH (std::out_of_range&) - { - // create better exception explanation - JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this)); - } - } - else - { - JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); - } - } - - /// @brief access specified object element with bounds checking - /// @sa https://json.nlohmann.me/api/basic_json/at/ - reference at(const typename object_t::key_type& key) - { - // at only works for objects - if (JSON_HEDLEY_LIKELY(is_object())) - { - JSON_TRY - { - return set_parent(m_value.object->at(key)); - } - JSON_CATCH (std::out_of_range&) - { - // create better exception explanation - JSON_THROW(out_of_range::create(403, "key '" + key + "' not found", *this)); - } - } - else - { - JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); - } - } - - /// @brief access specified object element with bounds checking - /// @sa https://json.nlohmann.me/api/basic_json/at/ - const_reference at(const typename object_t::key_type& key) const - { - // at only works for objects - if (JSON_HEDLEY_LIKELY(is_object())) - { - JSON_TRY - { - return m_value.object->at(key); - } - JSON_CATCH (std::out_of_range&) - { - // create better exception explanation - JSON_THROW(out_of_range::create(403, "key '" + key + "' not found", *this)); - } - } - else - { - JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); - } - } - - /// @brief access specified array element - /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ - reference operator[](size_type idx) - { - // implicitly convert null value to an empty array - if (is_null()) - { - m_type = value_t::array; - m_value.array = create(); - assert_invariant(); - } - - // operator[] only works for arrays - if (JSON_HEDLEY_LIKELY(is_array())) - { - // fill up array with null values if given idx is outside range - if (idx >= m_value.array->size()) - { -#if JSON_DIAGNOSTICS - // remember array size & capacity before resizing - const auto old_size = m_value.array->size(); - const auto old_capacity = m_value.array->capacity(); -#endif - m_value.array->resize(idx + 1); - -#if JSON_DIAGNOSTICS - if (JSON_HEDLEY_UNLIKELY(m_value.array->capacity() != old_capacity)) - { - // capacity has changed: update all parents - set_parents(); - } - else - { - // set parent for values added above - set_parents(begin() + static_cast(old_size), static_cast(idx + 1 - old_size)); - } -#endif - assert_invariant(); - } - - return m_value.array->operator[](idx); - } - - JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()), *this)); - } - - /// @brief access specified array element - /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ - const_reference operator[](size_type idx) const - { - // const operator[] only works for arrays - if (JSON_HEDLEY_LIKELY(is_array())) - { - return m_value.array->operator[](idx); - } - - JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()), *this)); - } - - /// @brief access specified object element - /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ - reference operator[](const typename object_t::key_type& key) - { - // implicitly convert null value to an empty object - if (is_null()) - { - m_type = value_t::object; - m_value.object = create(); - assert_invariant(); - } - - // operator[] only works for objects - if (JSON_HEDLEY_LIKELY(is_object())) - { - return set_parent(m_value.object->operator[](key)); - } - - JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); - } - - /// @brief access specified object element - /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ - const_reference operator[](const typename object_t::key_type& key) const - { - // const operator[] only works for objects - if (JSON_HEDLEY_LIKELY(is_object())) - { - JSON_ASSERT(m_value.object->find(key) != m_value.object->end()); - return m_value.object->find(key)->second; - } - - JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); - } - - /// @brief access specified object element - /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ - template - JSON_HEDLEY_NON_NULL(2) - reference operator[](T* key) - { - // implicitly convert null to object - if (is_null()) - { - m_type = value_t::object; - m_value = value_t::object; - assert_invariant(); - } - - // at only works for objects - if (JSON_HEDLEY_LIKELY(is_object())) - { - return set_parent(m_value.object->operator[](key)); - } - - JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); - } - - /// @brief access specified object element - /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ - template - JSON_HEDLEY_NON_NULL(2) - const_reference operator[](T* key) const - { - // at only works for objects - if (JSON_HEDLEY_LIKELY(is_object())) - { - JSON_ASSERT(m_value.object->find(key) != m_value.object->end()); - return m_value.object->find(key)->second; - } - - JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); - } - - /// @brief access specified object element with default value - /// @sa https://json.nlohmann.me/api/basic_json/value/ - /// using std::is_convertible in a std::enable_if will fail when using explicit conversions - template < class ValueType, typename std::enable_if < - detail::is_getable::value - && !std::is_same::value, int >::type = 0 > - ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const - { - // at only works for objects - if (JSON_HEDLEY_LIKELY(is_object())) - { - // if key is found, return value and given default value otherwise - const auto it = find(key); - if (it != end()) - { - return it->template get(); - } - - return default_value; - } - - JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()), *this)); - } - - /// @brief access specified object element with default value - /// @sa https://json.nlohmann.me/api/basic_json/value/ - /// overload for a default value of type const char* - string_t value(const typename object_t::key_type& key, const char* default_value) const - { - return value(key, string_t(default_value)); - } - - /// @brief access specified object element via JSON Pointer with default value - /// @sa https://json.nlohmann.me/api/basic_json/value/ - template::value, int>::type = 0> - ValueType value(const json_pointer& ptr, const ValueType& default_value) const - { - // at only works for objects - if (JSON_HEDLEY_LIKELY(is_object())) - { - // if pointer resolves a value, return it or use default value - JSON_TRY - { - return ptr.get_checked(this).template get(); - } - JSON_INTERNAL_CATCH (out_of_range&) - { - return default_value; - } - } - - JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()), *this)); - } - - /// @brief access specified object element via JSON Pointer with default value - /// @sa https://json.nlohmann.me/api/basic_json/value/ - /// overload for a default value of type const char* - JSON_HEDLEY_NON_NULL(3) - string_t value(const json_pointer& ptr, const char* default_value) const - { - return value(ptr, string_t(default_value)); - } - - /// @brief access the first element - /// @sa https://json.nlohmann.me/api/basic_json/front/ - reference front() - { - return *begin(); - } - - /// @brief access the first element - /// @sa https://json.nlohmann.me/api/basic_json/front/ - const_reference front() const - { - return *cbegin(); - } - - /// @brief access the last element - /// @sa https://json.nlohmann.me/api/basic_json/back/ - reference back() - { - auto tmp = end(); - --tmp; - return *tmp; - } - - /// @brief access the last element - /// @sa https://json.nlohmann.me/api/basic_json/back/ - const_reference back() const - { - auto tmp = cend(); - --tmp; - return *tmp; - } - - /// @brief remove element given an iterator - /// @sa https://json.nlohmann.me/api/basic_json/erase/ - template < class IteratorType, typename std::enable_if < - std::is_same::value || - std::is_same::value, int >::type - = 0 > - IteratorType erase(IteratorType pos) - { - // make sure iterator fits the current value - if (JSON_HEDLEY_UNLIKELY(this != pos.m_object)) - { - JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); - } - - IteratorType result = end(); - - switch (m_type) - { - case value_t::boolean: - case value_t::number_float: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::string: - case value_t::binary: - { - if (JSON_HEDLEY_UNLIKELY(!pos.m_it.primitive_iterator.is_begin())) - { - JSON_THROW(invalid_iterator::create(205, "iterator out of range", *this)); - } - - if (is_string()) - { - AllocatorType alloc; - std::allocator_traits::destroy(alloc, m_value.string); - std::allocator_traits::deallocate(alloc, m_value.string, 1); - m_value.string = nullptr; - } - else if (is_binary()) - { - AllocatorType alloc; - std::allocator_traits::destroy(alloc, m_value.binary); - std::allocator_traits::deallocate(alloc, m_value.binary, 1); - m_value.binary = nullptr; - } - - m_type = value_t::null; - assert_invariant(); - break; - } - - case value_t::object: - { - result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator); - break; - } - - case value_t::array: - { - result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator); - break; - } - - case value_t::null: - case value_t::discarded: - default: - JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); - } - - return result; - } - - /// @brief remove elements given an iterator range - /// @sa https://json.nlohmann.me/api/basic_json/erase/ - template < class IteratorType, typename std::enable_if < - std::is_same::value || - std::is_same::value, int >::type - = 0 > - IteratorType erase(IteratorType first, IteratorType last) - { - // make sure iterator fits the current value - if (JSON_HEDLEY_UNLIKELY(this != first.m_object || this != last.m_object)) - { - JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value", *this)); - } - - IteratorType result = end(); - - switch (m_type) - { - case value_t::boolean: - case value_t::number_float: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::string: - case value_t::binary: - { - if (JSON_HEDLEY_LIKELY(!first.m_it.primitive_iterator.is_begin() - || !last.m_it.primitive_iterator.is_end())) - { - JSON_THROW(invalid_iterator::create(204, "iterators out of range", *this)); - } - - if (is_string()) - { - AllocatorType alloc; - std::allocator_traits::destroy(alloc, m_value.string); - std::allocator_traits::deallocate(alloc, m_value.string, 1); - m_value.string = nullptr; - } - else if (is_binary()) - { - AllocatorType alloc; - std::allocator_traits::destroy(alloc, m_value.binary); - std::allocator_traits::deallocate(alloc, m_value.binary, 1); - m_value.binary = nullptr; - } - - m_type = value_t::null; - assert_invariant(); - break; - } - - case value_t::object: - { - result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator, - last.m_it.object_iterator); - break; - } - - case value_t::array: - { - result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator, - last.m_it.array_iterator); - break; - } - - case value_t::null: - case value_t::discarded: - default: - JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); - } - - return result; - } - - /// @brief remove element from a JSON object given a key - /// @sa https://json.nlohmann.me/api/basic_json/erase/ - size_type erase(const typename object_t::key_type& key) - { - // this erase only works for objects - if (JSON_HEDLEY_LIKELY(is_object())) - { - return m_value.object->erase(key); - } - - JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); - } - - /// @brief remove element from a JSON array given an index - /// @sa https://json.nlohmann.me/api/basic_json/erase/ - void erase(const size_type idx) - { - // this erase only works for arrays - if (JSON_HEDLEY_LIKELY(is_array())) - { - if (JSON_HEDLEY_UNLIKELY(idx >= size())) - { - JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this)); - } - - m_value.array->erase(m_value.array->begin() + static_cast(idx)); - } - else - { - JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); - } - } - - /// @} - - - //////////// - // lookup // - //////////// - - /// @name lookup - /// @{ - - /// @brief find an element in a JSON object - /// @sa https://json.nlohmann.me/api/basic_json/find/ - template - iterator find(KeyT&& key) - { - auto result = end(); - - if (is_object()) - { - result.m_it.object_iterator = m_value.object->find(std::forward(key)); - } - - return result; - } - - /// @brief find an element in a JSON object - /// @sa https://json.nlohmann.me/api/basic_json/find/ - template - const_iterator find(KeyT&& key) const - { - auto result = cend(); - - if (is_object()) - { - result.m_it.object_iterator = m_value.object->find(std::forward(key)); - } - - return result; - } - - /// @brief returns the number of occurrences of a key in a JSON object - /// @sa https://json.nlohmann.me/api/basic_json/count/ - template - size_type count(KeyT&& key) const - { - // return 0 for all nonobject types - return is_object() ? m_value.object->count(std::forward(key)) : 0; - } - - /// @brief check the existence of an element in a JSON object - /// @sa https://json.nlohmann.me/api/basic_json/contains/ - template < typename KeyT, typename std::enable_if < - !std::is_same::type, json_pointer>::value, int >::type = 0 > - bool contains(KeyT && key) const - { - return is_object() && m_value.object->find(std::forward(key)) != m_value.object->end(); - } - - /// @brief check the existence of an element in a JSON object given a JSON pointer - /// @sa https://json.nlohmann.me/api/basic_json/contains/ - bool contains(const json_pointer& ptr) const - { - return ptr.contains(this); - } - - /// @} - - - /////////////// - // iterators // - /////////////// - - /// @name iterators - /// @{ - - /// @brief returns an iterator to the first element - /// @sa https://json.nlohmann.me/api/basic_json/begin/ - iterator begin() noexcept - { - iterator result(this); - result.set_begin(); - return result; - } - - /// @brief returns an iterator to the first element - /// @sa https://json.nlohmann.me/api/basic_json/begin/ - const_iterator begin() const noexcept - { - return cbegin(); - } - - /// @brief returns a const iterator to the first element - /// @sa https://json.nlohmann.me/api/basic_json/cbegin/ - const_iterator cbegin() const noexcept - { - const_iterator result(this); - result.set_begin(); - return result; - } - - /// @brief returns an iterator to one past the last element - /// @sa https://json.nlohmann.me/api/basic_json/end/ - iterator end() noexcept - { - iterator result(this); - result.set_end(); - return result; - } - - /// @brief returns an iterator to one past the last element - /// @sa https://json.nlohmann.me/api/basic_json/end/ - const_iterator end() const noexcept - { - return cend(); - } - - /// @brief returns an iterator to one past the last element - /// @sa https://json.nlohmann.me/api/basic_json/cend/ - const_iterator cend() const noexcept - { - const_iterator result(this); - result.set_end(); - return result; - } - - /// @brief returns an iterator to the reverse-beginning - /// @sa https://json.nlohmann.me/api/basic_json/rbegin/ - reverse_iterator rbegin() noexcept - { - return reverse_iterator(end()); - } - - /// @brief returns an iterator to the reverse-beginning - /// @sa https://json.nlohmann.me/api/basic_json/rbegin/ - const_reverse_iterator rbegin() const noexcept - { - return crbegin(); - } - - /// @brief returns an iterator to the reverse-end - /// @sa https://json.nlohmann.me/api/basic_json/rend/ - reverse_iterator rend() noexcept - { - return reverse_iterator(begin()); - } - - /// @brief returns an iterator to the reverse-end - /// @sa https://json.nlohmann.me/api/basic_json/rend/ - const_reverse_iterator rend() const noexcept - { - return crend(); - } - - /// @brief returns a const reverse iterator to the last element - /// @sa https://json.nlohmann.me/api/basic_json/crbegin/ - const_reverse_iterator crbegin() const noexcept - { - return const_reverse_iterator(cend()); - } - - /// @brief returns a const reverse iterator to one before the first - /// @sa https://json.nlohmann.me/api/basic_json/crend/ - const_reverse_iterator crend() const noexcept - { - return const_reverse_iterator(cbegin()); - } - - public: - /// @brief wrapper to access iterator member functions in range-based for - /// @sa https://json.nlohmann.me/api/basic_json/items/ - /// @deprecated This function is deprecated since 3.1.0 and will be removed in - /// version 4.0.0 of the library. Please use @ref items() instead; - /// that is, replace `json::iterator_wrapper(j)` with `j.items()`. - JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items()) - static iteration_proxy iterator_wrapper(reference ref) noexcept - { - return ref.items(); - } - - /// @brief wrapper to access iterator member functions in range-based for - /// @sa https://json.nlohmann.me/api/basic_json/items/ - /// @deprecated This function is deprecated since 3.1.0 and will be removed in - /// version 4.0.0 of the library. Please use @ref items() instead; - /// that is, replace `json::iterator_wrapper(j)` with `j.items()`. - JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items()) - static iteration_proxy iterator_wrapper(const_reference ref) noexcept - { - return ref.items(); - } - - /// @brief helper to access iterator member functions in range-based for - /// @sa https://json.nlohmann.me/api/basic_json/items/ - iteration_proxy items() noexcept - { - return iteration_proxy(*this); - } - - /// @brief helper to access iterator member functions in range-based for - /// @sa https://json.nlohmann.me/api/basic_json/items/ - iteration_proxy items() const noexcept - { - return iteration_proxy(*this); - } - - /// @} - - - ////////////// - // capacity // - ////////////// - - /// @name capacity - /// @{ - - /// @brief checks whether the container is empty. - /// @sa https://json.nlohmann.me/api/basic_json/empty/ - bool empty() const noexcept - { - switch (m_type) - { - case value_t::null: - { - // null values are empty - return true; - } - - case value_t::array: - { - // delegate call to array_t::empty() - return m_value.array->empty(); - } - - case value_t::object: - { - // delegate call to object_t::empty() - return m_value.object->empty(); - } - - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - // all other types are nonempty - return false; - } - } - } - - /// @brief returns the number of elements - /// @sa https://json.nlohmann.me/api/basic_json/size/ - size_type size() const noexcept - { - switch (m_type) - { - case value_t::null: - { - // null values are empty - return 0; - } - - case value_t::array: - { - // delegate call to array_t::size() - return m_value.array->size(); - } - - case value_t::object: - { - // delegate call to object_t::size() - return m_value.object->size(); - } - - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - // all other types have size 1 - return 1; - } - } - } - - /// @brief returns the maximum possible number of elements - /// @sa https://json.nlohmann.me/api/basic_json/max_size/ - size_type max_size() const noexcept - { - switch (m_type) - { - case value_t::array: - { - // delegate call to array_t::max_size() - return m_value.array->max_size(); - } - - case value_t::object: - { - // delegate call to object_t::max_size() - return m_value.object->max_size(); - } - - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - // all other types have max_size() == size() - return size(); - } - } - } - - /// @} - - - /////////////// - // modifiers // - /////////////// - - /// @name modifiers - /// @{ - - /// @brief clears the contents - /// @sa https://json.nlohmann.me/api/basic_json/clear/ - void clear() noexcept - { - switch (m_type) - { - case value_t::number_integer: - { - m_value.number_integer = 0; - break; - } - - case value_t::number_unsigned: - { - m_value.number_unsigned = 0; - break; - } - - case value_t::number_float: - { - m_value.number_float = 0.0; - break; - } - - case value_t::boolean: - { - m_value.boolean = false; - break; - } - - case value_t::string: - { - m_value.string->clear(); - break; - } - - case value_t::binary: - { - m_value.binary->clear(); - break; - } - - case value_t::array: - { - m_value.array->clear(); - break; - } - - case value_t::object: - { - m_value.object->clear(); - break; - } - - case value_t::null: - case value_t::discarded: - default: - break; - } - } - - /// @brief add an object to an array - /// @sa https://json.nlohmann.me/api/basic_json/push_back/ - void push_back(basic_json&& val) - { - // push_back only works for null objects or arrays - if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) - { - JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this)); - } - - // transform null object into an array - if (is_null()) - { - m_type = value_t::array; - m_value = value_t::array; - assert_invariant(); - } - - // add element to array (move semantics) - const auto old_capacity = m_value.array->capacity(); - m_value.array->push_back(std::move(val)); - set_parent(m_value.array->back(), old_capacity); - // if val is moved from, basic_json move constructor marks it null, so we do not call the destructor - } - - /// @brief add an object to an array - /// @sa https://json.nlohmann.me/api/basic_json/operator+=/ - reference operator+=(basic_json&& val) - { - push_back(std::move(val)); - return *this; - } - - /// @brief add an object to an array - /// @sa https://json.nlohmann.me/api/basic_json/push_back/ - void push_back(const basic_json& val) - { - // push_back only works for null objects or arrays - if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) - { - JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this)); - } - - // transform null object into an array - if (is_null()) - { - m_type = value_t::array; - m_value = value_t::array; - assert_invariant(); - } - - // add element to array - const auto old_capacity = m_value.array->capacity(); - m_value.array->push_back(val); - set_parent(m_value.array->back(), old_capacity); - } - - /// @brief add an object to an array - /// @sa https://json.nlohmann.me/api/basic_json/operator+=/ - reference operator+=(const basic_json& val) - { - push_back(val); - return *this; - } - - /// @brief add an object to an object - /// @sa https://json.nlohmann.me/api/basic_json/push_back/ - void push_back(const typename object_t::value_type& val) - { - // push_back only works for null objects or objects - if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object()))) - { - JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this)); - } - - // transform null object into an object - if (is_null()) - { - m_type = value_t::object; - m_value = value_t::object; - assert_invariant(); - } - - // add element to object - auto res = m_value.object->insert(val); - set_parent(res.first->second); - } - - /// @brief add an object to an object - /// @sa https://json.nlohmann.me/api/basic_json/operator+=/ - reference operator+=(const typename object_t::value_type& val) - { - push_back(val); - return *this; - } - - /// @brief add an object to an object - /// @sa https://json.nlohmann.me/api/basic_json/push_back/ - void push_back(initializer_list_t init) - { - if (is_object() && init.size() == 2 && (*init.begin())->is_string()) - { - basic_json&& key = init.begin()->moved_or_copied(); - push_back(typename object_t::value_type( - std::move(key.get_ref()), (init.begin() + 1)->moved_or_copied())); - } - else - { - push_back(basic_json(init)); - } - } - - /// @brief add an object to an object - /// @sa https://json.nlohmann.me/api/basic_json/operator+=/ - reference operator+=(initializer_list_t init) - { - push_back(init); - return *this; - } - - /// @brief add an object to an array - /// @sa https://json.nlohmann.me/api/basic_json/emplace_back/ - template - reference emplace_back(Args&& ... args) - { - // emplace_back only works for null objects or arrays - if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) - { - JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name()), *this)); - } - - // transform null object into an array - if (is_null()) - { - m_type = value_t::array; - m_value = value_t::array; - assert_invariant(); - } - - // add element to array (perfect forwarding) - const auto old_capacity = m_value.array->capacity(); - m_value.array->emplace_back(std::forward(args)...); - return set_parent(m_value.array->back(), old_capacity); - } - - /// @brief add an object to an object if key does not exist - /// @sa https://json.nlohmann.me/api/basic_json/emplace/ - template - std::pair emplace(Args&& ... args) - { - // emplace only works for null objects or arrays - if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object()))) - { - JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name()), *this)); - } - - // transform null object into an object - if (is_null()) - { - m_type = value_t::object; - m_value = value_t::object; - assert_invariant(); - } - - // add element to array (perfect forwarding) - auto res = m_value.object->emplace(std::forward(args)...); - set_parent(res.first->second); - - // create result iterator and set iterator to the result of emplace - auto it = begin(); - it.m_it.object_iterator = res.first; - - // return pair of iterator and boolean - return {it, res.second}; - } - - /// Helper for insertion of an iterator - /// @note: This uses std::distance to support GCC 4.8, - /// see https://github.com/nlohmann/json/pull/1257 - template - iterator insert_iterator(const_iterator pos, Args&& ... args) - { - iterator result(this); - JSON_ASSERT(m_value.array != nullptr); - - auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator); - m_value.array->insert(pos.m_it.array_iterator, std::forward(args)...); - result.m_it.array_iterator = m_value.array->begin() + insert_pos; - - // This could have been written as: - // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val); - // but the return value of insert is missing in GCC 4.8, so it is written this way instead. - - set_parents(); - return result; - } - - /// @brief inserts element into array - /// @sa https://json.nlohmann.me/api/basic_json/insert/ - iterator insert(const_iterator pos, const basic_json& val) - { - // insert only works for arrays - if (JSON_HEDLEY_LIKELY(is_array())) - { - // check if iterator pos fits to this JSON value - if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) - { - JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); - } - - // insert to array and return iterator - return insert_iterator(pos, val); - } - - JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); - } - - /// @brief inserts element into array - /// @sa https://json.nlohmann.me/api/basic_json/insert/ - iterator insert(const_iterator pos, basic_json&& val) - { - return insert(pos, val); - } - - /// @brief inserts copies of element into array - /// @sa https://json.nlohmann.me/api/basic_json/insert/ - iterator insert(const_iterator pos, size_type cnt, const basic_json& val) - { - // insert only works for arrays - if (JSON_HEDLEY_LIKELY(is_array())) - { - // check if iterator pos fits to this JSON value - if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) - { - JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); - } - - // insert to array and return iterator - return insert_iterator(pos, cnt, val); - } - - JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); - } - - /// @brief inserts range of elements into array - /// @sa https://json.nlohmann.me/api/basic_json/insert/ - iterator insert(const_iterator pos, const_iterator first, const_iterator last) - { - // insert only works for arrays - if (JSON_HEDLEY_UNLIKELY(!is_array())) - { - JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); - } - - // check if iterator pos fits to this JSON value - if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) - { - JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); - } - - // check if range iterators belong to the same JSON object - if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) - { - JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this)); - } - - if (JSON_HEDLEY_UNLIKELY(first.m_object == this)) - { - JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container", *this)); - } - - // insert to array and return iterator - return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator); - } - - /// @brief inserts elements from initializer list into array - /// @sa https://json.nlohmann.me/api/basic_json/insert/ - iterator insert(const_iterator pos, initializer_list_t ilist) - { - // insert only works for arrays - if (JSON_HEDLEY_UNLIKELY(!is_array())) - { - JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); - } - - // check if iterator pos fits to this JSON value - if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) - { - JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); - } - - // insert to array and return iterator - return insert_iterator(pos, ilist.begin(), ilist.end()); - } - - /// @brief inserts range of elements into object - /// @sa https://json.nlohmann.me/api/basic_json/insert/ - void insert(const_iterator first, const_iterator last) - { - // insert only works for objects - if (JSON_HEDLEY_UNLIKELY(!is_object())) - { - JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); - } - - // check if range iterators belong to the same JSON object - if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) - { - JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this)); - } - - // passed iterators must belong to objects - if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object())) - { - JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects", *this)); - } - - m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator); - } - - /// @brief updates a JSON object from another object, overwriting existing keys - /// @sa https://json.nlohmann.me/api/basic_json/update/ - void update(const_reference j, bool merge_objects = false) - { - update(j.begin(), j.end(), merge_objects); - } - - /// @brief updates a JSON object from another object, overwriting existing keys - /// @sa https://json.nlohmann.me/api/basic_json/update/ - void update(const_iterator first, const_iterator last, bool merge_objects = false) - { - // implicitly convert null value to an empty object - if (is_null()) - { - m_type = value_t::object; - m_value.object = create(); - assert_invariant(); - } - - if (JSON_HEDLEY_UNLIKELY(!is_object())) - { - JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()), *this)); - } - - // check if range iterators belong to the same JSON object - if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) - { - JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this)); - } - - // passed iterators must belong to objects - if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object())) - { - JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(first.m_object->type_name()), *first.m_object)); - } - - for (auto it = first; it != last; ++it) - { - if (merge_objects && it.value().is_object()) - { - auto it2 = m_value.object->find(it.key()); - if (it2 != m_value.object->end()) - { - it2->second.update(it.value(), true); - continue; - } - } - m_value.object->operator[](it.key()) = it.value(); -#if JSON_DIAGNOSTICS - m_value.object->operator[](it.key()).m_parent = this; -#endif - } - } - - /// @brief exchanges the values - /// @sa https://json.nlohmann.me/api/basic_json/swap/ - void swap(reference other) noexcept ( - std::is_nothrow_move_constructible::value&& - std::is_nothrow_move_assignable::value&& - std::is_nothrow_move_constructible::value&& - std::is_nothrow_move_assignable::value - ) - { - std::swap(m_type, other.m_type); - std::swap(m_value, other.m_value); - - set_parents(); - other.set_parents(); - assert_invariant(); - } - - /// @brief exchanges the values - /// @sa https://json.nlohmann.me/api/basic_json/swap/ - friend void swap(reference left, reference right) noexcept ( - std::is_nothrow_move_constructible::value&& - std::is_nothrow_move_assignable::value&& - std::is_nothrow_move_constructible::value&& - std::is_nothrow_move_assignable::value - ) - { - left.swap(right); - } - - /// @brief exchanges the values - /// @sa https://json.nlohmann.me/api/basic_json/swap/ - void swap(array_t& other) // NOLINT(bugprone-exception-escape) - { - // swap only works for arrays - if (JSON_HEDLEY_LIKELY(is_array())) - { - std::swap(*(m_value.array), other); - } - else - { - JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); - } - } - - /// @brief exchanges the values - /// @sa https://json.nlohmann.me/api/basic_json/swap/ - void swap(object_t& other) // NOLINT(bugprone-exception-escape) - { - // swap only works for objects - if (JSON_HEDLEY_LIKELY(is_object())) - { - std::swap(*(m_value.object), other); - } - else - { - JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); - } - } - - /// @brief exchanges the values - /// @sa https://json.nlohmann.me/api/basic_json/swap/ - void swap(string_t& other) // NOLINT(bugprone-exception-escape) - { - // swap only works for strings - if (JSON_HEDLEY_LIKELY(is_string())) - { - std::swap(*(m_value.string), other); - } - else - { - JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); - } - } - - /// @brief exchanges the values - /// @sa https://json.nlohmann.me/api/basic_json/swap/ - void swap(binary_t& other) // NOLINT(bugprone-exception-escape) - { - // swap only works for strings - if (JSON_HEDLEY_LIKELY(is_binary())) - { - std::swap(*(m_value.binary), other); - } - else - { - JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); - } - } - - /// @brief exchanges the values - /// @sa https://json.nlohmann.me/api/basic_json/swap/ - void swap(typename binary_t::container_type& other) // NOLINT(bugprone-exception-escape) - { - // swap only works for strings - if (JSON_HEDLEY_LIKELY(is_binary())) - { - std::swap(*(m_value.binary), other); - } - else - { - JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); - } - } - - /// @} - - public: - ////////////////////////////////////////// - // lexicographical comparison operators // - ////////////////////////////////////////// - - /// @name lexicographical comparison operators - /// @{ - - /// @brief comparison: equal - /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/ - friend bool operator==(const_reference lhs, const_reference rhs) noexcept - { -#ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wfloat-equal" -#endif - const auto lhs_type = lhs.type(); - const auto rhs_type = rhs.type(); - - if (lhs_type == rhs_type) - { - switch (lhs_type) - { - case value_t::array: - return *lhs.m_value.array == *rhs.m_value.array; - - case value_t::object: - return *lhs.m_value.object == *rhs.m_value.object; - - case value_t::null: - return true; - - case value_t::string: - return *lhs.m_value.string == *rhs.m_value.string; - - case value_t::boolean: - return lhs.m_value.boolean == rhs.m_value.boolean; - - case value_t::number_integer: - return lhs.m_value.number_integer == rhs.m_value.number_integer; - - case value_t::number_unsigned: - return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned; - - case value_t::number_float: - return lhs.m_value.number_float == rhs.m_value.number_float; - - case value_t::binary: - return *lhs.m_value.binary == *rhs.m_value.binary; - - case value_t::discarded: - default: - return false; - } - } - else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float) - { - return static_cast(lhs.m_value.number_integer) == rhs.m_value.number_float; - } - else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer) - { - return lhs.m_value.number_float == static_cast(rhs.m_value.number_integer); - } - else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float) - { - return static_cast(lhs.m_value.number_unsigned) == rhs.m_value.number_float; - } - else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned) - { - return lhs.m_value.number_float == static_cast(rhs.m_value.number_unsigned); - } - else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer) - { - return static_cast(lhs.m_value.number_unsigned) == rhs.m_value.number_integer; - } - else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned) - { - return lhs.m_value.number_integer == static_cast(rhs.m_value.number_unsigned); - } - - return false; -#ifdef __GNUC__ -#pragma GCC diagnostic pop -#endif - } - - /// @brief comparison: equal - /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/ - template::value, int>::type = 0> - friend bool operator==(const_reference lhs, ScalarType rhs) noexcept - { - return lhs == basic_json(rhs); - } - - /// @brief comparison: equal - /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/ - template::value, int>::type = 0> - friend bool operator==(ScalarType lhs, const_reference rhs) noexcept - { - return basic_json(lhs) == rhs; - } - - /// @brief comparison: not equal - /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/ - friend bool operator!=(const_reference lhs, const_reference rhs) noexcept - { - return !(lhs == rhs); - } - - /// @brief comparison: not equal - /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/ - template::value, int>::type = 0> - friend bool operator!=(const_reference lhs, ScalarType rhs) noexcept - { - return lhs != basic_json(rhs); - } - - /// @brief comparison: not equal - /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/ - template::value, int>::type = 0> - friend bool operator!=(ScalarType lhs, const_reference rhs) noexcept - { - return basic_json(lhs) != rhs; - } - - /// @brief comparison: less than - /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/ - friend bool operator<(const_reference lhs, const_reference rhs) noexcept - { - const auto lhs_type = lhs.type(); - const auto rhs_type = rhs.type(); - - if (lhs_type == rhs_type) - { - switch (lhs_type) - { - case value_t::array: - // note parentheses are necessary, see - // https://github.com/nlohmann/json/issues/1530 - return (*lhs.m_value.array) < (*rhs.m_value.array); - - case value_t::object: - return (*lhs.m_value.object) < (*rhs.m_value.object); - - case value_t::null: - return false; - - case value_t::string: - return (*lhs.m_value.string) < (*rhs.m_value.string); - - case value_t::boolean: - return (lhs.m_value.boolean) < (rhs.m_value.boolean); - - case value_t::number_integer: - return (lhs.m_value.number_integer) < (rhs.m_value.number_integer); - - case value_t::number_unsigned: - return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned); - - case value_t::number_float: - return (lhs.m_value.number_float) < (rhs.m_value.number_float); - - case value_t::binary: - return (*lhs.m_value.binary) < (*rhs.m_value.binary); - - case value_t::discarded: - default: - return false; - } - } - else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float) - { - return static_cast(lhs.m_value.number_integer) < rhs.m_value.number_float; - } - else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer) - { - return lhs.m_value.number_float < static_cast(rhs.m_value.number_integer); - } - else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float) - { - return static_cast(lhs.m_value.number_unsigned) < rhs.m_value.number_float; - } - else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned) - { - return lhs.m_value.number_float < static_cast(rhs.m_value.number_unsigned); - } - else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned) - { - return lhs.m_value.number_integer < static_cast(rhs.m_value.number_unsigned); - } - else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer) - { - return static_cast(lhs.m_value.number_unsigned) < rhs.m_value.number_integer; - } - - // We only reach this line if we cannot compare values. In that case, - // we compare types. Note we have to call the operator explicitly, - // because MSVC has problems otherwise. - return operator<(lhs_type, rhs_type); - } - - /// @brief comparison: less than - /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/ - template::value, int>::type = 0> - friend bool operator<(const_reference lhs, ScalarType rhs) noexcept - { - return lhs < basic_json(rhs); - } - - /// @brief comparison: less than - /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/ - template::value, int>::type = 0> - friend bool operator<(ScalarType lhs, const_reference rhs) noexcept - { - return basic_json(lhs) < rhs; - } - - /// @brief comparison: less than or equal - /// @sa https://json.nlohmann.me/api/basic_json/operator_le/ - friend bool operator<=(const_reference lhs, const_reference rhs) noexcept - { - return !(rhs < lhs); - } - - /// @brief comparison: less than or equal - /// @sa https://json.nlohmann.me/api/basic_json/operator_le/ - template::value, int>::type = 0> - friend bool operator<=(const_reference lhs, ScalarType rhs) noexcept - { - return lhs <= basic_json(rhs); - } - - /// @brief comparison: less than or equal - /// @sa https://json.nlohmann.me/api/basic_json/operator_le/ - template::value, int>::type = 0> - friend bool operator<=(ScalarType lhs, const_reference rhs) noexcept - { - return basic_json(lhs) <= rhs; - } - - /// @brief comparison: greater than - /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/ - friend bool operator>(const_reference lhs, const_reference rhs) noexcept - { - return !(lhs <= rhs); - } - - /// @brief comparison: greater than - /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/ - template::value, int>::type = 0> - friend bool operator>(const_reference lhs, ScalarType rhs) noexcept - { - return lhs > basic_json(rhs); - } - - /// @brief comparison: greater than - /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/ - template::value, int>::type = 0> - friend bool operator>(ScalarType lhs, const_reference rhs) noexcept - { - return basic_json(lhs) > rhs; - } - - /// @brief comparison: greater than or equal - /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/ - friend bool operator>=(const_reference lhs, const_reference rhs) noexcept - { - return !(lhs < rhs); - } - - /// @brief comparison: greater than or equal - /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/ - template::value, int>::type = 0> - friend bool operator>=(const_reference lhs, ScalarType rhs) noexcept - { - return lhs >= basic_json(rhs); - } - - /// @brief comparison: greater than or equal - /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/ - template::value, int>::type = 0> - friend bool operator>=(ScalarType lhs, const_reference rhs) noexcept - { - return basic_json(lhs) >= rhs; - } - - /// @} - - /////////////////// - // serialization // - /////////////////// - - /// @name serialization - /// @{ -#ifndef JSON_NO_IO - /// @brief serialize to stream - /// @sa https://json.nlohmann.me/api/basic_json/operator_ltlt/ - friend std::ostream& operator<<(std::ostream& o, const basic_json& j) - { - // read width member and use it as indentation parameter if nonzero - const bool pretty_print = o.width() > 0; - const auto indentation = pretty_print ? o.width() : 0; - - // reset width to 0 for subsequent calls to this stream - o.width(0); - - // do the actual serialization - serializer s(detail::output_adapter(o), o.fill()); - s.dump(j, pretty_print, false, static_cast(indentation)); - return o; - } - - /// @brief serialize to stream - /// @sa https://json.nlohmann.me/api/basic_json/operator_ltlt/ - /// @deprecated This function is deprecated since 3.0.0 and will be removed in - /// version 4.0.0 of the library. Please use - /// operator<<(std::ostream&, const basic_json&) instead; that is, - /// replace calls like `j >> o;` with `o << j;`. - JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator<<(std::ostream&, const basic_json&)) - friend std::ostream& operator>>(const basic_json& j, std::ostream& o) - { - return o << j; - } -#endif // JSON_NO_IO - /// @} - - - ///////////////////// - // deserialization // - ///////////////////// - - /// @name deserialization - /// @{ - - /// @brief deserialize from a compatible input - /// @sa https://json.nlohmann.me/api/basic_json/parse/ - template - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json parse(InputType&& i, - const parser_callback_t cb = nullptr, - const bool allow_exceptions = true, - const bool ignore_comments = false) - { - basic_json result; - parser(detail::input_adapter(std::forward(i)), cb, allow_exceptions, ignore_comments).parse(true, result); - return result; - } - - /// @brief deserialize from a pair of character iterators - /// @sa https://json.nlohmann.me/api/basic_json/parse/ - template - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json parse(IteratorType first, - IteratorType last, - const parser_callback_t cb = nullptr, - const bool allow_exceptions = true, - const bool ignore_comments = false) - { - basic_json result; - parser(detail::input_adapter(std::move(first), std::move(last)), cb, allow_exceptions, ignore_comments).parse(true, result); - return result; - } - - JSON_HEDLEY_WARN_UNUSED_RESULT - JSON_HEDLEY_DEPRECATED_FOR(3.8.0, parse(ptr, ptr + len)) - static basic_json parse(detail::span_input_adapter&& i, - const parser_callback_t cb = nullptr, - const bool allow_exceptions = true, - const bool ignore_comments = false) - { - basic_json result; - parser(i.get(), cb, allow_exceptions, ignore_comments).parse(true, result); - return result; - } - - /// @brief check if the input is valid JSON - /// @sa https://json.nlohmann.me/api/basic_json/accept/ - template - static bool accept(InputType&& i, - const bool ignore_comments = false) - { - return parser(detail::input_adapter(std::forward(i)), nullptr, false, ignore_comments).accept(true); - } - - /// @brief check if the input is valid JSON - /// @sa https://json.nlohmann.me/api/basic_json/accept/ - template - static bool accept(IteratorType first, IteratorType last, - const bool ignore_comments = false) - { - return parser(detail::input_adapter(std::move(first), std::move(last)), nullptr, false, ignore_comments).accept(true); - } - - JSON_HEDLEY_WARN_UNUSED_RESULT - JSON_HEDLEY_DEPRECATED_FOR(3.8.0, accept(ptr, ptr + len)) - static bool accept(detail::span_input_adapter&& i, - const bool ignore_comments = false) - { - return parser(i.get(), nullptr, false, ignore_comments).accept(true); - } - - /// @brief generate SAX events - /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/ - template - JSON_HEDLEY_NON_NULL(2) - static bool sax_parse(InputType&& i, SAX* sax, - input_format_t format = input_format_t::json, - const bool strict = true, - const bool ignore_comments = false) - { - auto ia = detail::input_adapter(std::forward(i)); - return format == input_format_t::json - ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) - : detail::binary_reader(std::move(ia)).sax_parse(format, sax, strict); - } - - /// @brief generate SAX events - /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/ - template - JSON_HEDLEY_NON_NULL(3) - static bool sax_parse(IteratorType first, IteratorType last, SAX* sax, - input_format_t format = input_format_t::json, - const bool strict = true, - const bool ignore_comments = false) - { - auto ia = detail::input_adapter(std::move(first), std::move(last)); - return format == input_format_t::json - ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) - : detail::binary_reader(std::move(ia)).sax_parse(format, sax, strict); - } - - /// @brief generate SAX events - /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/ - /// @deprecated This function is deprecated since 3.8.0 and will be removed in - /// version 4.0.0 of the library. Please use - /// sax_parse(ptr, ptr + len) instead. - template - JSON_HEDLEY_DEPRECATED_FOR(3.8.0, sax_parse(ptr, ptr + len, ...)) - JSON_HEDLEY_NON_NULL(2) - static bool sax_parse(detail::span_input_adapter&& i, SAX* sax, - input_format_t format = input_format_t::json, - const bool strict = true, - const bool ignore_comments = false) - { - auto ia = i.get(); - return format == input_format_t::json - // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) - ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) - // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) - : detail::binary_reader(std::move(ia)).sax_parse(format, sax, strict); - } -#ifndef JSON_NO_IO - /// @brief deserialize from stream - /// @sa https://json.nlohmann.me/api/basic_json/operator_gtgt/ - /// @deprecated This stream operator is deprecated since 3.0.0 and will be removed in - /// version 4.0.0 of the library. Please use - /// operator>>(std::istream&, basic_json&) instead; that is, - /// replace calls like `j << i;` with `i >> j;`. - JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator>>(std::istream&, basic_json&)) - friend std::istream& operator<<(basic_json& j, std::istream& i) - { - return operator>>(i, j); - } - - /// @brief deserialize from stream - /// @sa https://json.nlohmann.me/api/basic_json/operator_gtgt/ - friend std::istream& operator>>(std::istream& i, basic_json& j) - { - parser(detail::input_adapter(i)).parse(false, j); - return i; - } -#endif // JSON_NO_IO - /// @} - - /////////////////////////// - // convenience functions // - /////////////////////////// - - /// @brief return the type as string - /// @sa https://json.nlohmann.me/api/basic_json/type_name/ - JSON_HEDLEY_RETURNS_NON_NULL - const char* type_name() const noexcept - { - switch (m_type) - { - case value_t::null: - return "null"; - case value_t::object: - return "object"; - case value_t::array: - return "array"; - case value_t::string: - return "string"; - case value_t::boolean: - return "boolean"; - case value_t::binary: - return "binary"; - case value_t::discarded: - return "discarded"; - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - default: - return "number"; - } - } - - - JSON_PRIVATE_UNLESS_TESTED: - ////////////////////// - // member variables // - ////////////////////// - - /// the type of the current element - value_t m_type = value_t::null; - - /// the value of the current element - json_value m_value = {}; - -#if JSON_DIAGNOSTICS - /// a pointer to a parent value (for debugging purposes) - basic_json* m_parent = nullptr; -#endif - - ////////////////////////////////////////// - // binary serialization/deserialization // - ////////////////////////////////////////// - - /// @name binary serialization/deserialization support - /// @{ - - public: - /// @brief create a CBOR serialization of a given JSON value - /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/ - static std::vector to_cbor(const basic_json& j) - { - std::vector result; - to_cbor(j, result); - return result; - } - - /// @brief create a CBOR serialization of a given JSON value - /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/ - static void to_cbor(const basic_json& j, detail::output_adapter o) - { - binary_writer(o).write_cbor(j); - } - - /// @brief create a CBOR serialization of a given JSON value - /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/ - static void to_cbor(const basic_json& j, detail::output_adapter o) - { - binary_writer(o).write_cbor(j); - } - - /// @brief create a MessagePack serialization of a given JSON value - /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/ - static std::vector to_msgpack(const basic_json& j) - { - std::vector result; - to_msgpack(j, result); - return result; - } - - /// @brief create a MessagePack serialization of a given JSON value - /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/ - static void to_msgpack(const basic_json& j, detail::output_adapter o) - { - binary_writer(o).write_msgpack(j); - } - - /// @brief create a MessagePack serialization of a given JSON value - /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/ - static void to_msgpack(const basic_json& j, detail::output_adapter o) - { - binary_writer(o).write_msgpack(j); - } - - /// @brief create a UBJSON serialization of a given JSON value - /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/ - static std::vector to_ubjson(const basic_json& j, - const bool use_size = false, - const bool use_type = false) - { - std::vector result; - to_ubjson(j, result, use_size, use_type); - return result; - } - - /// @brief create a UBJSON serialization of a given JSON value - /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/ - static void to_ubjson(const basic_json& j, detail::output_adapter o, - const bool use_size = false, const bool use_type = false) - { - binary_writer(o).write_ubjson(j, use_size, use_type); - } - - /// @brief create a UBJSON serialization of a given JSON value - /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/ - static void to_ubjson(const basic_json& j, detail::output_adapter o, - const bool use_size = false, const bool use_type = false) - { - binary_writer(o).write_ubjson(j, use_size, use_type); - } - - /// @brief create a BSON serialization of a given JSON value - /// @sa https://json.nlohmann.me/api/basic_json/to_bson/ - static std::vector to_bson(const basic_json& j) - { - std::vector result; - to_bson(j, result); - return result; - } - - /// @brief create a BSON serialization of a given JSON value - /// @sa https://json.nlohmann.me/api/basic_json/to_bson/ - static void to_bson(const basic_json& j, detail::output_adapter o) - { - binary_writer(o).write_bson(j); - } - - /// @brief create a BSON serialization of a given JSON value - /// @sa https://json.nlohmann.me/api/basic_json/to_bson/ - static void to_bson(const basic_json& j, detail::output_adapter o) - { - binary_writer(o).write_bson(j); - } - - /// @brief create a JSON value from an input in CBOR format - /// @sa https://json.nlohmann.me/api/basic_json/from_cbor/ - template - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json from_cbor(InputType&& i, - const bool strict = true, - const bool allow_exceptions = true, - const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - auto ia = detail::input_adapter(std::forward(i)); - const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); - return res ? result : basic_json(value_t::discarded); - } - - /// @brief create a JSON value from an input in CBOR format - /// @sa https://json.nlohmann.me/api/basic_json/from_cbor/ - template - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json from_cbor(IteratorType first, IteratorType last, - const bool strict = true, - const bool allow_exceptions = true, - const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - auto ia = detail::input_adapter(std::move(first), std::move(last)); - const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); - return res ? result : basic_json(value_t::discarded); - } - - template - JSON_HEDLEY_WARN_UNUSED_RESULT - JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len)) - static basic_json from_cbor(const T* ptr, std::size_t len, - const bool strict = true, - const bool allow_exceptions = true, - const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) - { - return from_cbor(ptr, ptr + len, strict, allow_exceptions, tag_handler); - } - - - JSON_HEDLEY_WARN_UNUSED_RESULT - JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len)) - static basic_json from_cbor(detail::span_input_adapter&& i, - const bool strict = true, - const bool allow_exceptions = true, - const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - auto ia = i.get(); - // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) - const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); - return res ? result : basic_json(value_t::discarded); - } - - /// @brief create a JSON value from an input in MessagePack format - /// @sa https://json.nlohmann.me/api/basic_json/from_msgpack/ - template - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json from_msgpack(InputType&& i, - const bool strict = true, - const bool allow_exceptions = true) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - auto ia = detail::input_adapter(std::forward(i)); - const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); - return res ? result : basic_json(value_t::discarded); - } - - /// @brief create a JSON value from an input in MessagePack format - /// @sa https://json.nlohmann.me/api/basic_json/from_msgpack/ - template - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json from_msgpack(IteratorType first, IteratorType last, - const bool strict = true, - const bool allow_exceptions = true) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - auto ia = detail::input_adapter(std::move(first), std::move(last)); - const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); - return res ? result : basic_json(value_t::discarded); - } - - template - JSON_HEDLEY_WARN_UNUSED_RESULT - JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len)) - static basic_json from_msgpack(const T* ptr, std::size_t len, - const bool strict = true, - const bool allow_exceptions = true) - { - return from_msgpack(ptr, ptr + len, strict, allow_exceptions); - } - - JSON_HEDLEY_WARN_UNUSED_RESULT - JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len)) - static basic_json from_msgpack(detail::span_input_adapter&& i, - const bool strict = true, - const bool allow_exceptions = true) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - auto ia = i.get(); - // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) - const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); - return res ? result : basic_json(value_t::discarded); - } - - /// @brief create a JSON value from an input in UBJSON format - /// @sa https://json.nlohmann.me/api/basic_json/from_ubjson/ - template - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json from_ubjson(InputType&& i, - const bool strict = true, - const bool allow_exceptions = true) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - auto ia = detail::input_adapter(std::forward(i)); - const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); - return res ? result : basic_json(value_t::discarded); - } - - /// @brief create a JSON value from an input in UBJSON format - /// @sa https://json.nlohmann.me/api/basic_json/from_ubjson/ - template - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json from_ubjson(IteratorType first, IteratorType last, - const bool strict = true, - const bool allow_exceptions = true) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - auto ia = detail::input_adapter(std::move(first), std::move(last)); - const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); - return res ? result : basic_json(value_t::discarded); - } - - template - JSON_HEDLEY_WARN_UNUSED_RESULT - JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len)) - static basic_json from_ubjson(const T* ptr, std::size_t len, - const bool strict = true, - const bool allow_exceptions = true) - { - return from_ubjson(ptr, ptr + len, strict, allow_exceptions); - } - - JSON_HEDLEY_WARN_UNUSED_RESULT - JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len)) - static basic_json from_ubjson(detail::span_input_adapter&& i, - const bool strict = true, - const bool allow_exceptions = true) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - auto ia = i.get(); - // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) - const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); - return res ? result : basic_json(value_t::discarded); - } - - /// @brief create a JSON value from an input in BSON format - /// @sa https://json.nlohmann.me/api/basic_json/from_bson/ - template - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json from_bson(InputType&& i, - const bool strict = true, - const bool allow_exceptions = true) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - auto ia = detail::input_adapter(std::forward(i)); - const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); - return res ? result : basic_json(value_t::discarded); - } - - /// @brief create a JSON value from an input in BSON format - /// @sa https://json.nlohmann.me/api/basic_json/from_bson/ - template - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json from_bson(IteratorType first, IteratorType last, - const bool strict = true, - const bool allow_exceptions = true) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - auto ia = detail::input_adapter(std::move(first), std::move(last)); - const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); - return res ? result : basic_json(value_t::discarded); - } - - template - JSON_HEDLEY_WARN_UNUSED_RESULT - JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len)) - static basic_json from_bson(const T* ptr, std::size_t len, - const bool strict = true, - const bool allow_exceptions = true) - { - return from_bson(ptr, ptr + len, strict, allow_exceptions); - } - - JSON_HEDLEY_WARN_UNUSED_RESULT - JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len)) - static basic_json from_bson(detail::span_input_adapter&& i, - const bool strict = true, - const bool allow_exceptions = true) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - auto ia = i.get(); - // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) - const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); - return res ? result : basic_json(value_t::discarded); - } - /// @} - - ////////////////////////// - // JSON Pointer support // - ////////////////////////// - - /// @name JSON Pointer functions - /// @{ - - /// @brief access specified element via JSON Pointer - /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ - reference operator[](const json_pointer& ptr) - { - return ptr.get_unchecked(this); - } - - /// @brief access specified element via JSON Pointer - /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ - const_reference operator[](const json_pointer& ptr) const - { - return ptr.get_unchecked(this); - } - - /// @brief access specified element via JSON Pointer - /// @sa https://json.nlohmann.me/api/basic_json/at/ - reference at(const json_pointer& ptr) - { - return ptr.get_checked(this); - } - - /// @brief access specified element via JSON Pointer - /// @sa https://json.nlohmann.me/api/basic_json/at/ - const_reference at(const json_pointer& ptr) const - { - return ptr.get_checked(this); - } - - /// @brief return flattened JSON value - /// @sa https://json.nlohmann.me/api/basic_json/flatten/ - basic_json flatten() const - { - basic_json result(value_t::object); - json_pointer::flatten("", *this, result); - return result; - } - - /// @brief unflatten a previously flattened JSON value - /// @sa https://json.nlohmann.me/api/basic_json/unflatten/ - basic_json unflatten() const - { - return json_pointer::unflatten(*this); - } - - /// @} - - ////////////////////////// - // JSON Patch functions // - ////////////////////////// - - /// @name JSON Patch functions - /// @{ - - /// @brief applies a JSON patch - /// @sa https://json.nlohmann.me/api/basic_json/patch/ - basic_json patch(const basic_json& json_patch) const - { - // make a working copy to apply the patch to - basic_json result = *this; - - // the valid JSON Patch operations - enum class patch_operations {add, remove, replace, move, copy, test, invalid}; - - const auto get_op = [](const std::string & op) - { - if (op == "add") - { - return patch_operations::add; - } - if (op == "remove") - { - return patch_operations::remove; - } - if (op == "replace") - { - return patch_operations::replace; - } - if (op == "move") - { - return patch_operations::move; - } - if (op == "copy") - { - return patch_operations::copy; - } - if (op == "test") - { - return patch_operations::test; - } - - return patch_operations::invalid; - }; - - // wrapper for "add" operation; add value at ptr - const auto operation_add = [&result](json_pointer & ptr, basic_json val) - { - // adding to the root of the target document means replacing it - if (ptr.empty()) - { - result = val; - return; - } - - // make sure the top element of the pointer exists - json_pointer top_pointer = ptr.top(); - if (top_pointer != ptr) - { - result.at(top_pointer); - } - - // get reference to parent of JSON pointer ptr - const auto last_path = ptr.back(); - ptr.pop_back(); - basic_json& parent = result[ptr]; - - switch (parent.m_type) - { - case value_t::null: - case value_t::object: - { - // use operator[] to add value - parent[last_path] = val; - break; - } - - case value_t::array: - { - if (last_path == "-") - { - // special case: append to back - parent.push_back(val); - } - else - { - const auto idx = json_pointer::array_index(last_path); - if (JSON_HEDLEY_UNLIKELY(idx > parent.size())) - { - // avoid undefined behavior - JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", parent)); - } - - // default case: insert add offset - parent.insert(parent.begin() + static_cast(idx), val); - } - break; - } - - // if there exists a parent it cannot be primitive - case value_t::string: // LCOV_EXCL_LINE - case value_t::boolean: // LCOV_EXCL_LINE - case value_t::number_integer: // LCOV_EXCL_LINE - case value_t::number_unsigned: // LCOV_EXCL_LINE - case value_t::number_float: // LCOV_EXCL_LINE - case value_t::binary: // LCOV_EXCL_LINE - case value_t::discarded: // LCOV_EXCL_LINE - default: // LCOV_EXCL_LINE - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE - } - }; - - // wrapper for "remove" operation; remove value at ptr - const auto operation_remove = [this, &result](json_pointer & ptr) - { - // get reference to parent of JSON pointer ptr - const auto last_path = ptr.back(); - ptr.pop_back(); - basic_json& parent = result.at(ptr); - - // remove child - if (parent.is_object()) - { - // perform range check - auto it = parent.find(last_path); - if (JSON_HEDLEY_LIKELY(it != parent.end())) - { - parent.erase(it); - } - else - { - JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found", *this)); - } - } - else if (parent.is_array()) - { - // note erase performs range check - parent.erase(json_pointer::array_index(last_path)); - } - }; - - // type check: top level value must be an array - if (JSON_HEDLEY_UNLIKELY(!json_patch.is_array())) - { - JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", json_patch)); - } - - // iterate and apply the operations - for (const auto& val : json_patch) - { - // wrapper to get a value for an operation - const auto get_value = [&val](const std::string & op, - const std::string & member, - bool string_type) -> basic_json & - { - // find value - auto it = val.m_value.object->find(member); - - // context-sensitive error message - const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'"; - - // check if desired value is present - if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end())) - { - // NOLINTNEXTLINE(performance-inefficient-string-concatenation) - JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'", val)); - } - - // check if result is of type string - if (JSON_HEDLEY_UNLIKELY(string_type && !it->second.is_string())) - { - // NOLINTNEXTLINE(performance-inefficient-string-concatenation) - JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'", val)); - } - - // no error: return value - return it->second; - }; - - // type check: every element of the array must be an object - if (JSON_HEDLEY_UNLIKELY(!val.is_object())) - { - JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", val)); - } - - // collect mandatory members - const auto op = get_value("op", "op", true).template get(); - const auto path = get_value(op, "path", true).template get(); - json_pointer ptr(path); - - switch (get_op(op)) - { - case patch_operations::add: - { - operation_add(ptr, get_value("add", "value", false)); - break; - } - - case patch_operations::remove: - { - operation_remove(ptr); - break; - } - - case patch_operations::replace: - { - // the "path" location must exist - use at() - result.at(ptr) = get_value("replace", "value", false); - break; - } - - case patch_operations::move: - { - const auto from_path = get_value("move", "from", true).template get(); - json_pointer from_ptr(from_path); - - // the "from" location must exist - use at() - basic_json v = result.at(from_ptr); - - // The move operation is functionally identical to a - // "remove" operation on the "from" location, followed - // immediately by an "add" operation at the target - // location with the value that was just removed. - operation_remove(from_ptr); - operation_add(ptr, v); - break; - } - - case patch_operations::copy: - { - const auto from_path = get_value("copy", "from", true).template get(); - const json_pointer from_ptr(from_path); - - // the "from" location must exist - use at() - basic_json v = result.at(from_ptr); - - // The copy is functionally identical to an "add" - // operation at the target location using the value - // specified in the "from" member. - operation_add(ptr, v); - break; - } - - case patch_operations::test: - { - bool success = false; - JSON_TRY - { - // check if "value" matches the one at "path" - // the "path" location must exist - use at() - success = (result.at(ptr) == get_value("test", "value", false)); - } - JSON_INTERNAL_CATCH (out_of_range&) - { - // ignore out of range errors: success remains false - } - - // throw an exception if test fails - if (JSON_HEDLEY_UNLIKELY(!success)) - { - JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump(), val)); - } - - break; - } - - case patch_operations::invalid: - default: - { - // op must be "add", "remove", "replace", "move", "copy", or - // "test" - JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid", val)); - } - } - } - - return result; - } - - /// @brief creates a diff as a JSON patch - /// @sa https://json.nlohmann.me/api/basic_json/diff/ - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json diff(const basic_json& source, const basic_json& target, - const std::string& path = "") - { - // the patch - basic_json result(value_t::array); - - // if the values are the same, return empty patch - if (source == target) - { - return result; - } - - if (source.type() != target.type()) - { - // different types: replace value - result.push_back( - { - {"op", "replace"}, {"path", path}, {"value", target} - }); - return result; - } - - switch (source.type()) - { - case value_t::array: - { - // first pass: traverse common elements - std::size_t i = 0; - while (i < source.size() && i < target.size()) - { - // recursive call to compare array values at index i - auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i)); - result.insert(result.end(), temp_diff.begin(), temp_diff.end()); - ++i; - } - - // We now reached the end of at least one array - // in a second pass, traverse the remaining elements - - // remove my remaining elements - const auto end_index = static_cast(result.size()); - while (i < source.size()) - { - // add operations in reverse order to avoid invalid - // indices - result.insert(result.begin() + end_index, object( - { - {"op", "remove"}, - {"path", path + "/" + std::to_string(i)} - })); - ++i; - } - - // add other remaining elements - while (i < target.size()) - { - result.push_back( - { - {"op", "add"}, - {"path", path + "/-"}, - {"value", target[i]} - }); - ++i; - } - - break; - } - - case value_t::object: - { - // first pass: traverse this object's elements - for (auto it = source.cbegin(); it != source.cend(); ++it) - { - // escape the key name to be used in a JSON patch - const auto path_key = path + "/" + detail::escape(it.key()); - - if (target.find(it.key()) != target.end()) - { - // recursive call to compare object values at key it - auto temp_diff = diff(it.value(), target[it.key()], path_key); - result.insert(result.end(), temp_diff.begin(), temp_diff.end()); - } - else - { - // found a key that is not in o -> remove it - result.push_back(object( - { - {"op", "remove"}, {"path", path_key} - })); - } - } - - // second pass: traverse other object's elements - for (auto it = target.cbegin(); it != target.cend(); ++it) - { - if (source.find(it.key()) == source.end()) - { - // found a key that is not in this -> add it - const auto path_key = path + "/" + detail::escape(it.key()); - result.push_back( - { - {"op", "add"}, {"path", path_key}, - {"value", it.value()} - }); - } - } - - break; - } - - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - // both primitive type: replace value - result.push_back( - { - {"op", "replace"}, {"path", path}, {"value", target} - }); - break; - } - } - - return result; - } - - /// @} - - //////////////////////////////// - // JSON Merge Patch functions // - //////////////////////////////// - - /// @name JSON Merge Patch functions - /// @{ - - /// @brief applies a JSON Merge Patch - /// @sa https://json.nlohmann.me/api/basic_json/merge_patch/ - void merge_patch(const basic_json& apply_patch) - { - if (apply_patch.is_object()) - { - if (!is_object()) - { - *this = object(); - } - for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it) - { - if (it.value().is_null()) - { - erase(it.key()); - } - else - { - operator[](it.key()).merge_patch(it.value()); - } - } - } - else - { - *this = apply_patch; - } - } - - /// @} -}; - -/// @brief user-defined to_string function for JSON values -/// @sa https://json.nlohmann.me/api/basic_json/to_string/ -NLOHMANN_BASIC_JSON_TPL_DECLARATION -std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j) -{ - return j.dump(); -} - -} // namespace nlohmann - -/////////////////////// -// nonmember support // -/////////////////////// - -namespace std // NOLINT(cert-dcl58-cpp) -{ - -/// @brief hash value for JSON objects -/// @sa https://json.nlohmann.me/api/basic_json/std_hash/ -NLOHMANN_BASIC_JSON_TPL_DECLARATION -struct hash -{ - std::size_t operator()(const nlohmann::NLOHMANN_BASIC_JSON_TPL& j) const - { - return nlohmann::detail::hash(j); - } -}; - -// specialization for std::less -template<> -struct less< ::nlohmann::detail::value_t> // do not remove the space after '<', see https://github.com/nlohmann/json/pull/679 -{ - /*! - @brief compare two value_t enum values - @since version 3.0.0 - */ - bool operator()(nlohmann::detail::value_t lhs, - nlohmann::detail::value_t rhs) const noexcept - { - return nlohmann::detail::operator<(lhs, rhs); - } -}; - -// C++20 prohibit function specialization in the std namespace. -#ifndef JSON_HAS_CPP_20 - -/// @brief exchanges the values of two JSON objects -/// @sa https://json.nlohmann.me/api/basic_json/std_swap/ -NLOHMANN_BASIC_JSON_TPL_DECLARATION -inline void swap(nlohmann::NLOHMANN_BASIC_JSON_TPL& j1, nlohmann::NLOHMANN_BASIC_JSON_TPL& j2) noexcept( // NOLINT(readability-inconsistent-declaration-parameter-name) - is_nothrow_move_constructible::value&& // NOLINT(misc-redundant-expression) - is_nothrow_move_assignable::value) -{ - j1.swap(j2); -} - -#endif - -} // namespace std - -/// @brief user-defined string literal for JSON values -/// @sa https://json.nlohmann.me/api/basic_json/operator_literal_json/ -JSON_HEDLEY_NON_NULL(1) -inline nlohmann::json operator "" _json(const char* s, std::size_t n) -{ - return nlohmann::json::parse(s, s + n); -} - -/// @brief user-defined string literal for JSON pointer -/// @sa https://json.nlohmann.me/api/basic_json/operator_literal_json_pointer/ -JSON_HEDLEY_NON_NULL(1) -inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n) -{ - return nlohmann::json::json_pointer(std::string(s, n)); -} - -// #include - - -// restore clang diagnostic settings -#if defined(__clang__) - #pragma clang diagnostic pop -#endif - -// clean up -#undef JSON_ASSERT -#undef JSON_INTERNAL_CATCH -#undef JSON_CATCH -#undef JSON_THROW -#undef JSON_TRY -#undef JSON_PRIVATE_UNLESS_TESTED -#undef JSON_HAS_CPP_11 -#undef JSON_HAS_CPP_14 -#undef JSON_HAS_CPP_17 -#undef JSON_HAS_CPP_20 -#undef JSON_HAS_FILESYSTEM -#undef JSON_HAS_EXPERIMENTAL_FILESYSTEM -#undef NLOHMANN_BASIC_JSON_TPL_DECLARATION -#undef NLOHMANN_BASIC_JSON_TPL -#undef JSON_EXPLICIT -#undef NLOHMANN_CAN_CALL_STD_FUNC_IMPL - -// #include - - -#undef JSON_HEDLEY_ALWAYS_INLINE -#undef JSON_HEDLEY_ARM_VERSION -#undef JSON_HEDLEY_ARM_VERSION_CHECK -#undef JSON_HEDLEY_ARRAY_PARAM -#undef JSON_HEDLEY_ASSUME -#undef JSON_HEDLEY_BEGIN_C_DECLS -#undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE -#undef JSON_HEDLEY_CLANG_HAS_BUILTIN -#undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE -#undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE -#undef JSON_HEDLEY_CLANG_HAS_EXTENSION -#undef JSON_HEDLEY_CLANG_HAS_FEATURE -#undef JSON_HEDLEY_CLANG_HAS_WARNING -#undef JSON_HEDLEY_COMPCERT_VERSION -#undef JSON_HEDLEY_COMPCERT_VERSION_CHECK -#undef JSON_HEDLEY_CONCAT -#undef JSON_HEDLEY_CONCAT3 -#undef JSON_HEDLEY_CONCAT3_EX -#undef JSON_HEDLEY_CONCAT_EX -#undef JSON_HEDLEY_CONST -#undef JSON_HEDLEY_CONSTEXPR -#undef JSON_HEDLEY_CONST_CAST -#undef JSON_HEDLEY_CPP_CAST -#undef JSON_HEDLEY_CRAY_VERSION -#undef JSON_HEDLEY_CRAY_VERSION_CHECK -#undef JSON_HEDLEY_C_DECL -#undef JSON_HEDLEY_DEPRECATED -#undef JSON_HEDLEY_DEPRECATED_FOR -#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL -#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ -#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED -#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES -#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS -#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION -#undef JSON_HEDLEY_DIAGNOSTIC_POP -#undef JSON_HEDLEY_DIAGNOSTIC_PUSH -#undef JSON_HEDLEY_DMC_VERSION -#undef JSON_HEDLEY_DMC_VERSION_CHECK -#undef JSON_HEDLEY_EMPTY_BASES -#undef JSON_HEDLEY_EMSCRIPTEN_VERSION -#undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK -#undef JSON_HEDLEY_END_C_DECLS -#undef JSON_HEDLEY_FLAGS -#undef JSON_HEDLEY_FLAGS_CAST -#undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE -#undef JSON_HEDLEY_GCC_HAS_BUILTIN -#undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE -#undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE -#undef JSON_HEDLEY_GCC_HAS_EXTENSION -#undef JSON_HEDLEY_GCC_HAS_FEATURE -#undef JSON_HEDLEY_GCC_HAS_WARNING -#undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK -#undef JSON_HEDLEY_GCC_VERSION -#undef JSON_HEDLEY_GCC_VERSION_CHECK -#undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE -#undef JSON_HEDLEY_GNUC_HAS_BUILTIN -#undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE -#undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE -#undef JSON_HEDLEY_GNUC_HAS_EXTENSION -#undef JSON_HEDLEY_GNUC_HAS_FEATURE -#undef JSON_HEDLEY_GNUC_HAS_WARNING -#undef JSON_HEDLEY_GNUC_VERSION -#undef JSON_HEDLEY_GNUC_VERSION_CHECK -#undef JSON_HEDLEY_HAS_ATTRIBUTE -#undef JSON_HEDLEY_HAS_BUILTIN -#undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE -#undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS -#undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE -#undef JSON_HEDLEY_HAS_EXTENSION -#undef JSON_HEDLEY_HAS_FEATURE -#undef JSON_HEDLEY_HAS_WARNING -#undef JSON_HEDLEY_IAR_VERSION -#undef JSON_HEDLEY_IAR_VERSION_CHECK -#undef JSON_HEDLEY_IBM_VERSION -#undef JSON_HEDLEY_IBM_VERSION_CHECK -#undef JSON_HEDLEY_IMPORT -#undef JSON_HEDLEY_INLINE -#undef JSON_HEDLEY_INTEL_CL_VERSION -#undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK -#undef JSON_HEDLEY_INTEL_VERSION -#undef JSON_HEDLEY_INTEL_VERSION_CHECK -#undef JSON_HEDLEY_IS_CONSTANT -#undef JSON_HEDLEY_IS_CONSTEXPR_ -#undef JSON_HEDLEY_LIKELY -#undef JSON_HEDLEY_MALLOC -#undef JSON_HEDLEY_MCST_LCC_VERSION -#undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK -#undef JSON_HEDLEY_MESSAGE -#undef JSON_HEDLEY_MSVC_VERSION -#undef JSON_HEDLEY_MSVC_VERSION_CHECK -#undef JSON_HEDLEY_NEVER_INLINE -#undef JSON_HEDLEY_NON_NULL -#undef JSON_HEDLEY_NO_ESCAPE -#undef JSON_HEDLEY_NO_RETURN -#undef JSON_HEDLEY_NO_THROW -#undef JSON_HEDLEY_NULL -#undef JSON_HEDLEY_PELLES_VERSION -#undef JSON_HEDLEY_PELLES_VERSION_CHECK -#undef JSON_HEDLEY_PGI_VERSION -#undef JSON_HEDLEY_PGI_VERSION_CHECK -#undef JSON_HEDLEY_PREDICT -#undef JSON_HEDLEY_PRINTF_FORMAT -#undef JSON_HEDLEY_PRIVATE -#undef JSON_HEDLEY_PUBLIC -#undef JSON_HEDLEY_PURE -#undef JSON_HEDLEY_REINTERPRET_CAST -#undef JSON_HEDLEY_REQUIRE -#undef JSON_HEDLEY_REQUIRE_CONSTEXPR -#undef JSON_HEDLEY_REQUIRE_MSG -#undef JSON_HEDLEY_RESTRICT -#undef JSON_HEDLEY_RETURNS_NON_NULL -#undef JSON_HEDLEY_SENTINEL -#undef JSON_HEDLEY_STATIC_ASSERT -#undef JSON_HEDLEY_STATIC_CAST -#undef JSON_HEDLEY_STRINGIFY -#undef JSON_HEDLEY_STRINGIFY_EX -#undef JSON_HEDLEY_SUNPRO_VERSION -#undef JSON_HEDLEY_SUNPRO_VERSION_CHECK -#undef JSON_HEDLEY_TINYC_VERSION -#undef JSON_HEDLEY_TINYC_VERSION_CHECK -#undef JSON_HEDLEY_TI_ARMCL_VERSION -#undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK -#undef JSON_HEDLEY_TI_CL2000_VERSION -#undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK -#undef JSON_HEDLEY_TI_CL430_VERSION -#undef JSON_HEDLEY_TI_CL430_VERSION_CHECK -#undef JSON_HEDLEY_TI_CL6X_VERSION -#undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK -#undef JSON_HEDLEY_TI_CL7X_VERSION -#undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK -#undef JSON_HEDLEY_TI_CLPRU_VERSION -#undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK -#undef JSON_HEDLEY_TI_VERSION -#undef JSON_HEDLEY_TI_VERSION_CHECK -#undef JSON_HEDLEY_UNAVAILABLE -#undef JSON_HEDLEY_UNLIKELY -#undef JSON_HEDLEY_UNPREDICTABLE -#undef JSON_HEDLEY_UNREACHABLE -#undef JSON_HEDLEY_UNREACHABLE_RETURN -#undef JSON_HEDLEY_VERSION -#undef JSON_HEDLEY_VERSION_DECODE_MAJOR -#undef JSON_HEDLEY_VERSION_DECODE_MINOR -#undef JSON_HEDLEY_VERSION_DECODE_REVISION -#undef JSON_HEDLEY_VERSION_ENCODE -#undef JSON_HEDLEY_WARNING -#undef JSON_HEDLEY_WARN_UNUSED_RESULT -#undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG -#undef JSON_HEDLEY_FALL_THROUGH - - - -#endif // INCLUDE_NLOHMANN_JSON_HPP_ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ +| | |__ | | | | | | version 3.10.5 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +SPDX-License-Identifier: MIT +Copyright (c) 2013-2022 Niels Lohmann . + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +/****************************************************************************\ + * Note on documentation: The source files contain links to the online * + * documentation of the public API at https://json.nlohmann.me. This URL * + * contains the most recent documentation and should also be applicable to * + * previous versions; documentation for deprecated functions is not * + * removed, but marked deprecated. See "Generate documentation" section in * + * file doc/README.md. * +\****************************************************************************/ + +#ifndef INCLUDE_NLOHMANN_JSON_HPP_ +#define INCLUDE_NLOHMANN_JSON_HPP_ + +#define NLOHMANN_JSON_VERSION_MAJOR 3 +#define NLOHMANN_JSON_VERSION_MINOR 10 +#define NLOHMANN_JSON_VERSION_PATCH 5 + +#include // all_of, find, for_each +#include // nullptr_t, ptrdiff_t, size_t +#include // hash, less +#include // initializer_list +#ifndef JSON_NO_IO + #include // istream, ostream +#endif // JSON_NO_IO +#include // random_access_iterator_tag +#include // unique_ptr +#include // accumulate +#include // string, stoi, to_string +#include // declval, forward, move, pair, swap +#include // vector + +// #include + + +#include +#include + +// #include + + +#include // transform +#include // array +#include // forward_list +#include // inserter, front_inserter, end +#include // map +#include // string +#include // tuple, make_tuple +#include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible +#include // unordered_map +#include // pair, declval +#include // valarray + +// #include + + +#include // exception +#include // runtime_error +#include // to_string +#include // vector + +// #include + + +#include // array +#include // size_t +#include // uint8_t +#include // string + +namespace nlohmann +{ +namespace detail +{ +/////////////////////////// +// JSON type enumeration // +/////////////////////////// + +/*! +@brief the JSON type enumeration + +This enumeration collects the different JSON types. It is internally used to +distinguish the stored values, and the functions @ref basic_json::is_null(), +@ref basic_json::is_object(), @ref basic_json::is_array(), +@ref basic_json::is_string(), @ref basic_json::is_boolean(), +@ref basic_json::is_number() (with @ref basic_json::is_number_integer(), +@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), +@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and +@ref basic_json::is_structured() rely on it. + +@note There are three enumeration entries (number_integer, number_unsigned, and +number_float), because the library distinguishes these three types for numbers: +@ref basic_json::number_unsigned_t is used for unsigned integers, +@ref basic_json::number_integer_t is used for signed integers, and +@ref basic_json::number_float_t is used for floating-point numbers or to +approximate integers which do not fit in the limits of their respective type. + +@sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON +value with the default value for a given type + +@since version 1.0.0 +*/ +enum class value_t : std::uint8_t +{ + null, ///< null value + object, ///< object (unordered set of name/value pairs) + array, ///< array (ordered collection of values) + string, ///< string value + boolean, ///< boolean value + number_integer, ///< number value (signed integer) + number_unsigned, ///< number value (unsigned integer) + number_float, ///< number value (floating-point) + binary, ///< binary array (ordered collection of bytes) + discarded ///< discarded by the parser callback function +}; + +/*! +@brief comparison operator for JSON types + +Returns an ordering that is similar to Python: +- order: null < boolean < number < object < array < string < binary +- furthermore, each type is not smaller than itself +- discarded values are not comparable +- binary is represented as a b"" string in python and directly comparable to a + string; however, making a binary array directly comparable with a string would + be surprising behavior in a JSON file. + +@since version 1.0.0 +*/ +inline bool operator<(const value_t lhs, const value_t rhs) noexcept +{ + static constexpr std::array order = {{ + 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */, + 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */, + 6 /* binary */ + } + }; + + const auto l_index = static_cast(lhs); + const auto r_index = static_cast(rhs); + return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index]; +} +} // namespace detail +} // namespace nlohmann + +// #include + + +#include +// #include + + +#include // declval, pair +// #include + + +/* Hedley - https://nemequ.github.io/hedley + * Created by Evan Nemerson + * + * To the extent possible under law, the author(s) have dedicated all + * copyright and related and neighboring rights to this software to + * the public domain worldwide. This software is distributed without + * any warranty. + * + * For details, see . + * SPDX-License-Identifier: CC0-1.0 + */ + +#if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 15) +#if defined(JSON_HEDLEY_VERSION) + #undef JSON_HEDLEY_VERSION +#endif +#define JSON_HEDLEY_VERSION 15 + +#if defined(JSON_HEDLEY_STRINGIFY_EX) + #undef JSON_HEDLEY_STRINGIFY_EX +#endif +#define JSON_HEDLEY_STRINGIFY_EX(x) #x + +#if defined(JSON_HEDLEY_STRINGIFY) + #undef JSON_HEDLEY_STRINGIFY +#endif +#define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x) + +#if defined(JSON_HEDLEY_CONCAT_EX) + #undef JSON_HEDLEY_CONCAT_EX +#endif +#define JSON_HEDLEY_CONCAT_EX(a,b) a##b + +#if defined(JSON_HEDLEY_CONCAT) + #undef JSON_HEDLEY_CONCAT +#endif +#define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b) + +#if defined(JSON_HEDLEY_CONCAT3_EX) + #undef JSON_HEDLEY_CONCAT3_EX +#endif +#define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c + +#if defined(JSON_HEDLEY_CONCAT3) + #undef JSON_HEDLEY_CONCAT3 +#endif +#define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c) + +#if defined(JSON_HEDLEY_VERSION_ENCODE) + #undef JSON_HEDLEY_VERSION_ENCODE +#endif +#define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision)) + +#if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR) + #undef JSON_HEDLEY_VERSION_DECODE_MAJOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000) + +#if defined(JSON_HEDLEY_VERSION_DECODE_MINOR) + #undef JSON_HEDLEY_VERSION_DECODE_MINOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000) + +#if defined(JSON_HEDLEY_VERSION_DECODE_REVISION) + #undef JSON_HEDLEY_VERSION_DECODE_REVISION +#endif +#define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000) + +#if defined(JSON_HEDLEY_GNUC_VERSION) + #undef JSON_HEDLEY_GNUC_VERSION +#endif +#if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) +#elif defined(__GNUC__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0) +#endif + +#if defined(JSON_HEDLEY_GNUC_VERSION_CHECK) + #undef JSON_HEDLEY_GNUC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GNUC_VERSION) + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_MSVC_VERSION) + #undef JSON_HEDLEY_MSVC_VERSION +#endif +#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100) +#elif defined(_MSC_FULL_VER) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10) +#elif defined(_MSC_VER) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0) +#endif + +#if defined(JSON_HEDLEY_MSVC_VERSION_CHECK) + #undef JSON_HEDLEY_MSVC_VERSION_CHECK +#endif +#if !defined(JSON_HEDLEY_MSVC_VERSION) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0) +#elif defined(_MSC_VER) && (_MSC_VER >= 1400) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch))) +#elif defined(_MSC_VER) && (_MSC_VER >= 1200) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch))) +#else + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor))) +#endif + +#if defined(JSON_HEDLEY_INTEL_VERSION) + #undef JSON_HEDLEY_INTEL_VERSION +#endif +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && !defined(__ICL) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE) +#elif defined(__INTEL_COMPILER) && !defined(__ICL) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0) +#endif + +#if defined(JSON_HEDLEY_INTEL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_INTEL_VERSION) + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_INTEL_CL_VERSION) + #undef JSON_HEDLEY_INTEL_CL_VERSION +#endif +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && defined(__ICL) + #define JSON_HEDLEY_INTEL_CL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER, __INTEL_COMPILER_UPDATE, 0) +#endif + +#if defined(JSON_HEDLEY_INTEL_CL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_INTEL_CL_VERSION) + #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_CL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_PGI_VERSION) + #undef JSON_HEDLEY_PGI_VERSION +#endif +#if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__) + #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__) +#endif + +#if defined(JSON_HEDLEY_PGI_VERSION_CHECK) + #undef JSON_HEDLEY_PGI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PGI_VERSION) + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #undef JSON_HEDLEY_SUNPRO_VERSION +#endif +#if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10) +#elif defined(__SUNPRO_C) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf) +#elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10) +#elif defined(__SUNPRO_CC) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf) +#endif + +#if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK) + #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION +#endif +#if defined(__EMSCRIPTEN__) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__) +#endif + +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_ARM_VERSION) + #undef JSON_HEDLEY_ARM_VERSION +#endif +#if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100) +#elif defined(__CC_ARM) && defined(__ARMCC_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100) +#endif + +#if defined(JSON_HEDLEY_ARM_VERSION_CHECK) + #undef JSON_HEDLEY_ARM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_ARM_VERSION) + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_IBM_VERSION) + #undef JSON_HEDLEY_IBM_VERSION +#endif +#if defined(__ibmxl__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__) +#elif defined(__xlC__) && defined(__xlC_ver__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff) +#elif defined(__xlC__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0) +#endif + +#if defined(JSON_HEDLEY_IBM_VERSION_CHECK) + #undef JSON_HEDLEY_IBM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IBM_VERSION) + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_VERSION) + #undef JSON_HEDLEY_TI_VERSION +#endif +#if \ + defined(__TI_COMPILER_VERSION__) && \ + ( \ + defined(__TMS470__) || defined(__TI_ARM__) || \ + defined(__MSP430__) || \ + defined(__TMS320C2000__) \ + ) +#if (__TI_COMPILER_VERSION__ >= 16000000) + #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif +#endif + +#if defined(JSON_HEDLEY_TI_VERSION_CHECK) + #undef JSON_HEDLEY_TI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_VERSION) + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #undef JSON_HEDLEY_TI_CL2000_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__) + #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #undef JSON_HEDLEY_TI_CL430_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__) + #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #undef JSON_HEDLEY_TI_ARMCL_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__)) + #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK) + #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #undef JSON_HEDLEY_TI_CL6X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__) + #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #undef JSON_HEDLEY_TI_CL7X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__C7000__) + #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #undef JSON_HEDLEY_TI_CLPRU_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__PRU__) + #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_CRAY_VERSION) + #undef JSON_HEDLEY_CRAY_VERSION +#endif +#if defined(_CRAYC) + #if defined(_RELEASE_PATCHLEVEL) + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL) + #else + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0) + #endif +#endif + +#if defined(JSON_HEDLEY_CRAY_VERSION_CHECK) + #undef JSON_HEDLEY_CRAY_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_CRAY_VERSION) + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_IAR_VERSION) + #undef JSON_HEDLEY_IAR_VERSION +#endif +#if defined(__IAR_SYSTEMS_ICC__) + #if __VER__ > 1000 + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000)) + #else + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(__VER__ / 100, __VER__ % 100, 0) + #endif +#endif + +#if defined(JSON_HEDLEY_IAR_VERSION_CHECK) + #undef JSON_HEDLEY_IAR_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IAR_VERSION) + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TINYC_VERSION) + #undef JSON_HEDLEY_TINYC_VERSION +#endif +#if defined(__TINYC__) + #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100) +#endif + +#if defined(JSON_HEDLEY_TINYC_VERSION_CHECK) + #undef JSON_HEDLEY_TINYC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_DMC_VERSION) + #undef JSON_HEDLEY_DMC_VERSION +#endif +#if defined(__DMC__) + #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf) +#endif + +#if defined(JSON_HEDLEY_DMC_VERSION_CHECK) + #undef JSON_HEDLEY_DMC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_DMC_VERSION) + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #undef JSON_HEDLEY_COMPCERT_VERSION +#endif +#if defined(__COMPCERT_VERSION__) + #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100) +#endif + +#if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK) + #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_PELLES_VERSION) + #undef JSON_HEDLEY_PELLES_VERSION +#endif +#if defined(__POCC__) + #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0) +#endif + +#if defined(JSON_HEDLEY_PELLES_VERSION_CHECK) + #undef JSON_HEDLEY_PELLES_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PELLES_VERSION) + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_MCST_LCC_VERSION) + #undef JSON_HEDLEY_MCST_LCC_VERSION +#endif +#if defined(__LCC__) && defined(__LCC_MINOR__) + #define JSON_HEDLEY_MCST_LCC_VERSION JSON_HEDLEY_VERSION_ENCODE(__LCC__ / 100, __LCC__ % 100, __LCC_MINOR__) +#endif + +#if defined(JSON_HEDLEY_MCST_LCC_VERSION_CHECK) + #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_MCST_LCC_VERSION) + #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_MCST_LCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_GCC_VERSION) + #undef JSON_HEDLEY_GCC_VERSION +#endif +#if \ + defined(JSON_HEDLEY_GNUC_VERSION) && \ + !defined(__clang__) && \ + !defined(JSON_HEDLEY_INTEL_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_ARM_VERSION) && \ + !defined(JSON_HEDLEY_CRAY_VERSION) && \ + !defined(JSON_HEDLEY_TI_VERSION) && \ + !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL430_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \ + !defined(__COMPCERT__) && \ + !defined(JSON_HEDLEY_MCST_LCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION +#endif + +#if defined(JSON_HEDLEY_GCC_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_ATTRIBUTE +#endif +#if \ + defined(__has_attribute) && \ + ( \ + (!defined(JSON_HEDLEY_IAR_VERSION) || JSON_HEDLEY_IAR_VERSION_CHECK(8,5,9)) \ + ) +# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute) +#else +# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE +#endif +#if \ + defined(__has_cpp_attribute) && \ + defined(__cplusplus) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS +#endif +#if !defined(__cplusplus) || !defined(__has_cpp_attribute) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#elif \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \ + (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE +#endif +#if defined(__has_cpp_attribute) && defined(__cplusplus) + #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE +#endif +#if defined(__has_cpp_attribute) && defined(__cplusplus) + #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_BUILTIN) + #undef JSON_HEDLEY_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin) +#else + #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN) + #undef JSON_HEDLEY_GNUC_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) +#else + #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_BUILTIN) + #undef JSON_HEDLEY_GCC_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) +#else + #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_FEATURE) + #undef JSON_HEDLEY_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature) +#else + #define JSON_HEDLEY_HAS_FEATURE(feature) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_FEATURE) + #undef JSON_HEDLEY_GNUC_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) +#else + #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_FEATURE) + #undef JSON_HEDLEY_GCC_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) +#else + #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_EXTENSION) + #undef JSON_HEDLEY_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension) +#else + #define JSON_HEDLEY_HAS_EXTENSION(extension) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION) + #undef JSON_HEDLEY_GNUC_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) +#else + #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_EXTENSION) + #undef JSON_HEDLEY_GCC_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) +#else + #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_WARNING) + #undef JSON_HEDLEY_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning) +#else + #define JSON_HEDLEY_HAS_WARNING(warning) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_WARNING) + #undef JSON_HEDLEY_GNUC_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) +#else + #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_WARNING) + #undef JSON_HEDLEY_GCC_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) +#else + #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ + defined(__clang__) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \ + (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR)) + #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_PRAGMA(value) __pragma(value) +#else + #define JSON_HEDLEY_PRAGMA(value) +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH) + #undef JSON_HEDLEY_DIAGNOSTIC_PUSH +#endif +#if defined(JSON_HEDLEY_DIAGNOSTIC_POP) + #undef JSON_HEDLEY_DIAGNOSTIC_POP +#endif +#if defined(__clang__) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push)) + #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop)) +#elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop") +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") +#else + #define JSON_HEDLEY_DIAGNOSTIC_PUSH + #define JSON_HEDLEY_DIAGNOSTIC_POP +#endif + +/* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for + HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ +#endif +#if defined(__cplusplus) +# if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat") +# if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions") +# if JSON_HEDLEY_HAS_WARNING("-Wc++1z-extensions") +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ + _Pragma("clang diagnostic ignored \"-Wc++1z-extensions\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# endif +# else +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# endif +# endif +#endif +#if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x +#endif + +#if defined(JSON_HEDLEY_CONST_CAST) + #undef JSON_HEDLEY_CONST_CAST +#endif +#if defined(__cplusplus) +# define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast(expr)) +#elif \ + JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \ + ((T) (expr)); \ + JSON_HEDLEY_DIAGNOSTIC_POP \ + })) +#else +# define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_REINTERPRET_CAST) + #undef JSON_HEDLEY_REINTERPRET_CAST +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast(expr)) +#else + #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_STATIC_CAST) + #undef JSON_HEDLEY_STATIC_CAST +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast(expr)) +#else + #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_CPP_CAST) + #undef JSON_HEDLEY_CPP_CAST +#endif +#if defined(__cplusplus) +# if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast") +# define JSON_HEDLEY_CPP_CAST(T, expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \ + ((T) (expr)) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0) +# define JSON_HEDLEY_CPP_CAST(T, expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("diag_suppress=Pe137") \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr)) +# endif +#else +# define JSON_HEDLEY_CPP_CAST(T, expr) (expr) +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:1478 1786)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1216,1444,1445") +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996)) +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215") +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:161)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068)) +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161") +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 161") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:1292)) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097,1098") +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097") +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wcast-qual") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunused-function") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("clang diagnostic ignored \"-Wunused-function\"") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("GCC diagnostic ignored \"-Wunused-function\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(1,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION __pragma(warning(disable:4505)) +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("diag_suppress 3142") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#endif + +#if defined(JSON_HEDLEY_DEPRECATED) + #undef JSON_HEDLEY_DEPRECATED +#endif +#if defined(JSON_HEDLEY_DEPRECATED_FOR) + #undef JSON_HEDLEY_DEPRECATED_FOR +#endif +#if \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since)) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement)) +#elif \ + (JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since))) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement))) +#elif defined(__cplusplus) && (__cplusplus >= 201402L) + #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]]) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]]) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__)) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated) +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated") + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated") +#else + #define JSON_HEDLEY_DEPRECATED(since) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) +#endif + +#if defined(JSON_HEDLEY_UNAVAILABLE) + #undef JSON_HEDLEY_UNAVAILABLE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since))) +#else + #define JSON_HEDLEY_UNAVAILABLE(available_since) +#endif + +#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT) + #undef JSON_HEDLEY_WARN_UNUSED_RESULT +#endif +#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG) + #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__)) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__)) +#elif (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L) + #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]]) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) + #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) +#elif defined(_Check_return_) /* SAL */ + #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_ + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_ +#else + #define JSON_HEDLEY_WARN_UNUSED_RESULT + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) +#endif + +#if defined(JSON_HEDLEY_SENTINEL) + #undef JSON_HEDLEY_SENTINEL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position))) +#else + #define JSON_HEDLEY_SENTINEL(position) +#endif + +#if defined(JSON_HEDLEY_NO_RETURN) + #undef JSON_HEDLEY_NO_RETURN +#endif +#if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_NO_RETURN __noreturn +#elif \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) +#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L + #define JSON_HEDLEY_NO_RETURN _Noreturn +#elif defined(__cplusplus) && (__cplusplus >= 201103L) + #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]]) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) + #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;") +#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) + #define JSON_HEDLEY_NO_RETURN __attribute((noreturn)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) + #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) +#else + #define JSON_HEDLEY_NO_RETURN +#endif + +#if defined(JSON_HEDLEY_NO_ESCAPE) + #undef JSON_HEDLEY_NO_ESCAPE +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(noescape) + #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__)) +#else + #define JSON_HEDLEY_NO_ESCAPE +#endif + +#if defined(JSON_HEDLEY_UNREACHABLE) + #undef JSON_HEDLEY_UNREACHABLE +#endif +#if defined(JSON_HEDLEY_UNREACHABLE_RETURN) + #undef JSON_HEDLEY_UNREACHABLE_RETURN +#endif +#if defined(JSON_HEDLEY_ASSUME) + #undef JSON_HEDLEY_ASSUME +#endif +#if \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_ASSUME(expr) __assume(expr) +#elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume) + #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr) +#elif \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) + #if defined(__cplusplus) + #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr) + #else + #define JSON_HEDLEY_ASSUME(expr) _nassert(expr) + #endif +#endif +#if \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(10,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable() +#elif defined(JSON_HEDLEY_ASSUME) + #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) +#endif +#if !defined(JSON_HEDLEY_ASSUME) + #if defined(JSON_HEDLEY_UNREACHABLE) + #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1))) + #else + #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr) + #endif +#endif +#if defined(JSON_HEDLEY_UNREACHABLE) + #if \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value)) + #else + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE() + #endif +#else + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value) +#endif +#if !defined(JSON_HEDLEY_UNREACHABLE) + #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) +#endif + +JSON_HEDLEY_DIAGNOSTIC_PUSH +#if JSON_HEDLEY_HAS_WARNING("-Wpedantic") + #pragma clang diagnostic ignored "-Wpedantic" +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus) + #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" +#endif +#if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0) + #if defined(__clang__) + #pragma clang diagnostic ignored "-Wvariadic-macros" + #elif defined(JSON_HEDLEY_GCC_VERSION) + #pragma GCC diagnostic ignored "-Wvariadic-macros" + #endif +#endif +#if defined(JSON_HEDLEY_NON_NULL) + #undef JSON_HEDLEY_NON_NULL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) + #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__))) +#else + #define JSON_HEDLEY_NON_NULL(...) +#endif +JSON_HEDLEY_DIAGNOSTIC_POP + +#if defined(JSON_HEDLEY_PRINTF_FORMAT) + #undef JSON_HEDLEY_PRINTF_FORMAT +#endif +#if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check))) +#elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check))) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(format) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check))) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check)) +#else + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) +#endif + +#if defined(JSON_HEDLEY_CONSTEXPR) + #undef JSON_HEDLEY_CONSTEXPR +#endif +#if defined(__cplusplus) + #if __cplusplus >= 201103L + #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr) + #endif +#endif +#if !defined(JSON_HEDLEY_CONSTEXPR) + #define JSON_HEDLEY_CONSTEXPR +#endif + +#if defined(JSON_HEDLEY_PREDICT) + #undef JSON_HEDLEY_PREDICT +#endif +#if defined(JSON_HEDLEY_LIKELY) + #undef JSON_HEDLEY_LIKELY +#endif +#if defined(JSON_HEDLEY_UNLIKELY) + #undef JSON_HEDLEY_UNLIKELY +#endif +#if defined(JSON_HEDLEY_UNPREDICTABLE) + #undef JSON_HEDLEY_UNPREDICTABLE +#endif +#if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable) + #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr)) +#endif +#if \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) && !defined(JSON_HEDLEY_PGI_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability)) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability)) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability)) +# define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 ) +# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 ) +#elif \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PREDICT(expr, expected, probability) \ + (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \ + (__extension__ ({ \ + double hedley_probability_ = (probability); \ + ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \ + })) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \ + (__extension__ ({ \ + double hedley_probability_ = (probability); \ + ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \ + })) +# define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1) +# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0) +#else +# define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr)) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr)) +# define JSON_HEDLEY_LIKELY(expr) (!!(expr)) +# define JSON_HEDLEY_UNLIKELY(expr) (!!(expr)) +#endif +#if !defined(JSON_HEDLEY_UNPREDICTABLE) + #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5) +#endif + +#if defined(JSON_HEDLEY_MALLOC) + #undef JSON_HEDLEY_MALLOC +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_MALLOC __attribute__((__malloc__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_MALLOC __declspec(restrict) +#else + #define JSON_HEDLEY_MALLOC +#endif + +#if defined(JSON_HEDLEY_PURE) + #undef JSON_HEDLEY_PURE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PURE __attribute__((__pure__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) +# define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data") +#elif defined(__cplusplus) && \ + ( \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \ + ) +# define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;") +#else +# define JSON_HEDLEY_PURE +#endif + +#if defined(JSON_HEDLEY_CONST) + #undef JSON_HEDLEY_CONST +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(const) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_CONST __attribute__((__const__)) +#elif \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_CONST _Pragma("no_side_effect") +#else + #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE +#endif + +#if defined(JSON_HEDLEY_RESTRICT) + #undef JSON_HEDLEY_RESTRICT +#endif +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus) + #define JSON_HEDLEY_RESTRICT restrict +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ + defined(__clang__) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_RESTRICT __restrict +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus) + #define JSON_HEDLEY_RESTRICT _Restrict +#else + #define JSON_HEDLEY_RESTRICT +#endif + +#if defined(JSON_HEDLEY_INLINE) + #undef JSON_HEDLEY_INLINE +#endif +#if \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ + (defined(__cplusplus) && (__cplusplus >= 199711L)) + #define JSON_HEDLEY_INLINE inline +#elif \ + defined(JSON_HEDLEY_GCC_VERSION) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0) + #define JSON_HEDLEY_INLINE __inline__ +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_INLINE __inline +#else + #define JSON_HEDLEY_INLINE +#endif + +#if defined(JSON_HEDLEY_ALWAYS_INLINE) + #undef JSON_HEDLEY_ALWAYS_INLINE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) +# define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_ALWAYS_INLINE __forceinline +#elif defined(__cplusplus) && \ + ( \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \ + ) +# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) +# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced") +#else +# define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE +#endif + +#if defined(JSON_HEDLEY_NEVER_INLINE) + #undef JSON_HEDLEY_NEVER_INLINE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline") +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never") +#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) + #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) + #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) +#else + #define JSON_HEDLEY_NEVER_INLINE +#endif + +#if defined(JSON_HEDLEY_PRIVATE) + #undef JSON_HEDLEY_PRIVATE +#endif +#if defined(JSON_HEDLEY_PUBLIC) + #undef JSON_HEDLEY_PUBLIC +#endif +#if defined(JSON_HEDLEY_IMPORT) + #undef JSON_HEDLEY_IMPORT +#endif +#if defined(_WIN32) || defined(__CYGWIN__) +# define JSON_HEDLEY_PRIVATE +# define JSON_HEDLEY_PUBLIC __declspec(dllexport) +# define JSON_HEDLEY_IMPORT __declspec(dllimport) +#else +# if \ + JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + ( \ + defined(__TI_EABI__) && \ + ( \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \ + ) \ + ) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden"))) +# define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default"))) +# else +# define JSON_HEDLEY_PRIVATE +# define JSON_HEDLEY_PUBLIC +# endif +# define JSON_HEDLEY_IMPORT extern +#endif + +#if defined(JSON_HEDLEY_NO_THROW) + #undef JSON_HEDLEY_NO_THROW +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) + #define JSON_HEDLEY_NO_THROW __declspec(nothrow) +#else + #define JSON_HEDLEY_NO_THROW +#endif + +#if defined(JSON_HEDLEY_FALL_THROUGH) + #undef JSON_HEDLEY_FALL_THROUGH +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__)) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough) + #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]]) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough) + #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]]) +#elif defined(__fallthrough) /* SAL */ + #define JSON_HEDLEY_FALL_THROUGH __fallthrough +#else + #define JSON_HEDLEY_FALL_THROUGH +#endif + +#if defined(JSON_HEDLEY_RETURNS_NON_NULL) + #undef JSON_HEDLEY_RETURNS_NON_NULL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__)) +#elif defined(_Ret_notnull_) /* SAL */ + #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_ +#else + #define JSON_HEDLEY_RETURNS_NON_NULL +#endif + +#if defined(JSON_HEDLEY_ARRAY_PARAM) + #undef JSON_HEDLEY_ARRAY_PARAM +#endif +#if \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ + !defined(__STDC_NO_VLA__) && \ + !defined(__cplusplus) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_ARRAY_PARAM(name) (name) +#else + #define JSON_HEDLEY_ARRAY_PARAM(name) +#endif + +#if defined(JSON_HEDLEY_IS_CONSTANT) + #undef JSON_HEDLEY_IS_CONSTANT +#endif +#if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR) + #undef JSON_HEDLEY_REQUIRE_CONSTEXPR +#endif +/* JSON_HEDLEY_IS_CONSTEXPR_ is for + HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ +#if defined(JSON_HEDLEY_IS_CONSTEXPR_) + #undef JSON_HEDLEY_IS_CONSTEXPR_ +#endif +#if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr) +#endif +#if !defined(__cplusplus) +# if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24) +#if defined(__INTPTR_TYPE__) + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*) +#else + #include + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*) +#endif +# elif \ + ( \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \ + !defined(JSON_HEDLEY_SUNPRO_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION)) || \ + (JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0) +#if defined(__INTPTR_TYPE__) + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0) +#else + #include + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0) +#endif +# elif \ + defined(JSON_HEDLEY_GCC_VERSION) || \ + defined(JSON_HEDLEY_INTEL_VERSION) || \ + defined(JSON_HEDLEY_TINYC_VERSION) || \ + defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \ + defined(JSON_HEDLEY_TI_CL2000_VERSION) || \ + defined(JSON_HEDLEY_TI_CL6X_VERSION) || \ + defined(JSON_HEDLEY_TI_CL7X_VERSION) || \ + defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \ + defined(__clang__) +# define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \ + sizeof(void) != \ + sizeof(*( \ + 1 ? \ + ((void*) ((expr) * 0L) ) : \ +((struct { char v[sizeof(void) * 2]; } *) 1) \ + ) \ + ) \ + ) +# endif +#endif +#if defined(JSON_HEDLEY_IS_CONSTEXPR_) + #if !defined(JSON_HEDLEY_IS_CONSTANT) + #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr) + #endif + #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1)) +#else + #if !defined(JSON_HEDLEY_IS_CONSTANT) + #define JSON_HEDLEY_IS_CONSTANT(expr) (0) + #endif + #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr) +#endif + +#if defined(JSON_HEDLEY_BEGIN_C_DECLS) + #undef JSON_HEDLEY_BEGIN_C_DECLS +#endif +#if defined(JSON_HEDLEY_END_C_DECLS) + #undef JSON_HEDLEY_END_C_DECLS +#endif +#if defined(JSON_HEDLEY_C_DECL) + #undef JSON_HEDLEY_C_DECL +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" { + #define JSON_HEDLEY_END_C_DECLS } + #define JSON_HEDLEY_C_DECL extern "C" +#else + #define JSON_HEDLEY_BEGIN_C_DECLS + #define JSON_HEDLEY_END_C_DECLS + #define JSON_HEDLEY_C_DECL +#endif + +#if defined(JSON_HEDLEY_STATIC_ASSERT) + #undef JSON_HEDLEY_STATIC_ASSERT +#endif +#if \ + !defined(__cplusplus) && ( \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \ + (JSON_HEDLEY_HAS_FEATURE(c_static_assert) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + defined(_Static_assert) \ + ) +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message) +#elif \ + (defined(__cplusplus) && (__cplusplus >= 201103L)) || \ + JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message)) +#else +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) +#endif + +#if defined(JSON_HEDLEY_NULL) + #undef JSON_HEDLEY_NULL +#endif +#if defined(__cplusplus) + #if __cplusplus >= 201103L + #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr) + #elif defined(NULL) + #define JSON_HEDLEY_NULL NULL + #else + #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0) + #endif +#elif defined(NULL) + #define JSON_HEDLEY_NULL NULL +#else + #define JSON_HEDLEY_NULL ((void*) 0) +#endif + +#if defined(JSON_HEDLEY_MESSAGE) + #undef JSON_HEDLEY_MESSAGE +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") +# define JSON_HEDLEY_MESSAGE(msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ + JSON_HEDLEY_PRAGMA(message msg) \ + JSON_HEDLEY_DIAGNOSTIC_POP +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg) +#elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg) +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#else +# define JSON_HEDLEY_MESSAGE(msg) +#endif + +#if defined(JSON_HEDLEY_WARNING) + #undef JSON_HEDLEY_WARNING +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") +# define JSON_HEDLEY_WARNING(msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ + JSON_HEDLEY_PRAGMA(clang warning msg) \ + JSON_HEDLEY_DIAGNOSTIC_POP +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#else +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg) +#endif + +#if defined(JSON_HEDLEY_REQUIRE) + #undef JSON_HEDLEY_REQUIRE +#endif +#if defined(JSON_HEDLEY_REQUIRE_MSG) + #undef JSON_HEDLEY_REQUIRE_MSG +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if) +# if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat") +# define JSON_HEDLEY_REQUIRE(expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((diagnose_if(!(expr), #expr, "error"))) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((diagnose_if(!(expr), msg, "error"))) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error"))) +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error"))) +# endif +#else +# define JSON_HEDLEY_REQUIRE(expr) +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) +#endif + +#if defined(JSON_HEDLEY_FLAGS) + #undef JSON_HEDLEY_FLAGS +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum) && (!defined(__cplusplus) || JSON_HEDLEY_HAS_WARNING("-Wbitfield-enum-conversion")) + #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__)) +#else + #define JSON_HEDLEY_FLAGS +#endif + +#if defined(JSON_HEDLEY_FLAGS_CAST) + #undef JSON_HEDLEY_FLAGS_CAST +#endif +#if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0) +# define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("warning(disable:188)") \ + ((T) (expr)); \ + JSON_HEDLEY_DIAGNOSTIC_POP \ + })) +#else +# define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr) +#endif + +#if defined(JSON_HEDLEY_EMPTY_BASES) + #undef JSON_HEDLEY_EMPTY_BASES +#endif +#if \ + (JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases) +#else + #define JSON_HEDLEY_EMPTY_BASES +#endif + +/* Remaining macros are deprecated. */ + +#if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK +#endif +#if defined(__clang__) + #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0) +#else + #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN) + #undef JSON_HEDLEY_CLANG_HAS_BUILTIN +#endif +#define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin) + +#if defined(JSON_HEDLEY_CLANG_HAS_FEATURE) + #undef JSON_HEDLEY_CLANG_HAS_FEATURE +#endif +#define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature) + +#if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION) + #undef JSON_HEDLEY_CLANG_HAS_EXTENSION +#endif +#define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension) + +#if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_WARNING) + #undef JSON_HEDLEY_CLANG_HAS_WARNING +#endif +#define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning) + +#endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */ + +// #include + + +#include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template struct make_void +{ + using type = void; +}; +template using void_t = typename make_void::type; +} // namespace detail +} // namespace nlohmann + + +// https://en.cppreference.com/w/cpp/experimental/is_detected +namespace nlohmann +{ +namespace detail +{ +struct nonesuch +{ + nonesuch() = delete; + ~nonesuch() = delete; + nonesuch(nonesuch const&) = delete; + nonesuch(nonesuch const&&) = delete; + void operator=(nonesuch const&) = delete; + void operator=(nonesuch&&) = delete; +}; + +template class Op, + class... Args> +struct detector +{ + using value_t = std::false_type; + using type = Default; +}; + +template class Op, class... Args> +struct detector>, Op, Args...> +{ + using value_t = std::true_type; + using type = Op; +}; + +template class Op, class... Args> +using is_detected = typename detector::value_t; + +template class Op, class... Args> +struct is_detected_lazy : is_detected { }; + +template class Op, class... Args> +using detected_t = typename detector::type; + +template class Op, class... Args> +using detected_or = detector; + +template class Op, class... Args> +using detected_or_t = typename detected_or::type; + +template class Op, class... Args> +using is_detected_exact = std::is_same>; + +template class Op, class... Args> +using is_detected_convertible = + std::is_convertible, To>; +} // namespace detail +} // namespace nlohmann + + +// This file contains all internal macro definitions +// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them + +// exclude unsupported compilers +#if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) + #if defined(__clang__) + #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 + #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) + #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 + #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #endif +#endif + +// C++ language standard detection +// if the user manually specified the used c++ version this is skipped +#if !defined(JSON_HAS_CPP_20) && !defined(JSON_HAS_CPP_17) && !defined(JSON_HAS_CPP_14) && !defined(JSON_HAS_CPP_11) + #if (defined(__cplusplus) && __cplusplus >= 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L) + #define JSON_HAS_CPP_20 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) + #define JSON_HAS_CPP_14 + #endif + // the cpp 11 flag is always specified because it is the minimal required version + #define JSON_HAS_CPP_11 +#endif + +#if !defined(JSON_HAS_FILESYSTEM) && !defined(JSON_HAS_EXPERIMENTAL_FILESYSTEM) + #ifdef JSON_HAS_CPP_17 + #if defined(__cpp_lib_filesystem) + #define JSON_HAS_FILESYSTEM 1 + #elif defined(__cpp_lib_experimental_filesystem) + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #elif !defined(__has_include) + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #elif __has_include() + #define JSON_HAS_FILESYSTEM 1 + #elif __has_include() + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #endif + + // std::filesystem does not work on MinGW GCC 8: https://sourceforge.net/p/mingw-w64/bugs/737/ + #if defined(__MINGW32__) && defined(__GNUC__) && __GNUC__ == 8 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before GCC 8: https://en.cppreference.com/w/cpp/compiler_support + #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 8 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before Clang 7: https://en.cppreference.com/w/cpp/compiler_support + #if defined(__clang_major__) && __clang_major__ < 7 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before MSVC 19.14: https://en.cppreference.com/w/cpp/compiler_support + #if defined(_MSC_VER) && _MSC_VER < 1940 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before iOS 13 + #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED < 130000 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before macOS Catalina + #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + #endif +#endif + +#ifndef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 0 +#endif + +#ifndef JSON_HAS_FILESYSTEM + #define JSON_HAS_FILESYSTEM 0 +#endif + +// disable documentation warnings on clang +#if defined(__clang__) + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wdocumentation" + #pragma clang diagnostic ignored "-Wdocumentation-unknown-command" +#endif + +// allow disabling exceptions +#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) + #define JSON_THROW(exception) throw exception + #define JSON_TRY try + #define JSON_CATCH(exception) catch(exception) + #define JSON_INTERNAL_CATCH(exception) catch(exception) +#else + #include + #define JSON_THROW(exception) std::abort() + #define JSON_TRY if(true) + #define JSON_CATCH(exception) if(false) + #define JSON_INTERNAL_CATCH(exception) if(false) +#endif + +// override exception macros +#if defined(JSON_THROW_USER) + #undef JSON_THROW + #define JSON_THROW JSON_THROW_USER +#endif +#if defined(JSON_TRY_USER) + #undef JSON_TRY + #define JSON_TRY JSON_TRY_USER +#endif +#if defined(JSON_CATCH_USER) + #undef JSON_CATCH + #define JSON_CATCH JSON_CATCH_USER + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_CATCH_USER +#endif +#if defined(JSON_INTERNAL_CATCH_USER) + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER +#endif + +// allow overriding assert +#if !defined(JSON_ASSERT) + #include // assert + #define JSON_ASSERT(x) assert(x) +#endif + +// allow to access some private functions (needed by the test suite) +#if defined(JSON_TESTS_PRIVATE) + #define JSON_PRIVATE_UNLESS_TESTED public +#else + #define JSON_PRIVATE_UNLESS_TESTED private +#endif + +/*! +@brief macro to briefly define a mapping between an enum and JSON +@def NLOHMANN_JSON_SERIALIZE_ENUM +@since version 3.4.0 +*/ +#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ + template \ + inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [e](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.first == e; \ + }); \ + j = ((it != std::end(m)) ? it : std::begin(m))->second; \ + } \ + template \ + inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [&j](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.second == j; \ + }); \ + e = ((it != std::end(m)) ? it : std::begin(m))->first; \ + } + +// Ugly macros to avoid uglier copy-paste when specializing basic_json. They +// may be removed in the future once the class is split. + +#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ + template class ObjectType, \ + template class ArrayType, \ + class StringType, class BooleanType, class NumberIntegerType, \ + class NumberUnsignedType, class NumberFloatType, \ + template class AllocatorType, \ + template class JSONSerializer, \ + class BinaryType> + +#define NLOHMANN_BASIC_JSON_TPL \ + basic_json + +// Macros to simplify conversion from/to types + +#define NLOHMANN_JSON_EXPAND( x ) x +#define NLOHMANN_JSON_GET_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, NAME,...) NAME +#define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \ + NLOHMANN_JSON_PASTE64, \ + NLOHMANN_JSON_PASTE63, \ + NLOHMANN_JSON_PASTE62, \ + NLOHMANN_JSON_PASTE61, \ + NLOHMANN_JSON_PASTE60, \ + NLOHMANN_JSON_PASTE59, \ + NLOHMANN_JSON_PASTE58, \ + NLOHMANN_JSON_PASTE57, \ + NLOHMANN_JSON_PASTE56, \ + NLOHMANN_JSON_PASTE55, \ + NLOHMANN_JSON_PASTE54, \ + NLOHMANN_JSON_PASTE53, \ + NLOHMANN_JSON_PASTE52, \ + NLOHMANN_JSON_PASTE51, \ + NLOHMANN_JSON_PASTE50, \ + NLOHMANN_JSON_PASTE49, \ + NLOHMANN_JSON_PASTE48, \ + NLOHMANN_JSON_PASTE47, \ + NLOHMANN_JSON_PASTE46, \ + NLOHMANN_JSON_PASTE45, \ + NLOHMANN_JSON_PASTE44, \ + NLOHMANN_JSON_PASTE43, \ + NLOHMANN_JSON_PASTE42, \ + NLOHMANN_JSON_PASTE41, \ + NLOHMANN_JSON_PASTE40, \ + NLOHMANN_JSON_PASTE39, \ + NLOHMANN_JSON_PASTE38, \ + NLOHMANN_JSON_PASTE37, \ + NLOHMANN_JSON_PASTE36, \ + NLOHMANN_JSON_PASTE35, \ + NLOHMANN_JSON_PASTE34, \ + NLOHMANN_JSON_PASTE33, \ + NLOHMANN_JSON_PASTE32, \ + NLOHMANN_JSON_PASTE31, \ + NLOHMANN_JSON_PASTE30, \ + NLOHMANN_JSON_PASTE29, \ + NLOHMANN_JSON_PASTE28, \ + NLOHMANN_JSON_PASTE27, \ + NLOHMANN_JSON_PASTE26, \ + NLOHMANN_JSON_PASTE25, \ + NLOHMANN_JSON_PASTE24, \ + NLOHMANN_JSON_PASTE23, \ + NLOHMANN_JSON_PASTE22, \ + NLOHMANN_JSON_PASTE21, \ + NLOHMANN_JSON_PASTE20, \ + NLOHMANN_JSON_PASTE19, \ + NLOHMANN_JSON_PASTE18, \ + NLOHMANN_JSON_PASTE17, \ + NLOHMANN_JSON_PASTE16, \ + NLOHMANN_JSON_PASTE15, \ + NLOHMANN_JSON_PASTE14, \ + NLOHMANN_JSON_PASTE13, \ + NLOHMANN_JSON_PASTE12, \ + NLOHMANN_JSON_PASTE11, \ + NLOHMANN_JSON_PASTE10, \ + NLOHMANN_JSON_PASTE9, \ + NLOHMANN_JSON_PASTE8, \ + NLOHMANN_JSON_PASTE7, \ + NLOHMANN_JSON_PASTE6, \ + NLOHMANN_JSON_PASTE5, \ + NLOHMANN_JSON_PASTE4, \ + NLOHMANN_JSON_PASTE3, \ + NLOHMANN_JSON_PASTE2, \ + NLOHMANN_JSON_PASTE1)(__VA_ARGS__)) +#define NLOHMANN_JSON_PASTE2(func, v1) func(v1) +#define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2) +#define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3) +#define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4) +#define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5) +#define NLOHMANN_JSON_PASTE7(func, v1, v2, v3, v4, v5, v6) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE6(func, v2, v3, v4, v5, v6) +#define NLOHMANN_JSON_PASTE8(func, v1, v2, v3, v4, v5, v6, v7) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE7(func, v2, v3, v4, v5, v6, v7) +#define NLOHMANN_JSON_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8) +#define NLOHMANN_JSON_PASTE10(func, v1, v2, v3, v4, v5, v6, v7, v8, v9) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE9(func, v2, v3, v4, v5, v6, v7, v8, v9) +#define NLOHMANN_JSON_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE10(func, v2, v3, v4, v5, v6, v7, v8, v9, v10) +#define NLOHMANN_JSON_PASTE12(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE11(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) +#define NLOHMANN_JSON_PASTE13(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE12(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) +#define NLOHMANN_JSON_PASTE14(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE13(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) +#define NLOHMANN_JSON_PASTE15(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE14(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) +#define NLOHMANN_JSON_PASTE16(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE15(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) +#define NLOHMANN_JSON_PASTE17(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE16(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) +#define NLOHMANN_JSON_PASTE18(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE17(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) +#define NLOHMANN_JSON_PASTE19(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE18(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) +#define NLOHMANN_JSON_PASTE20(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE19(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) +#define NLOHMANN_JSON_PASTE21(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE20(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) +#define NLOHMANN_JSON_PASTE22(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE21(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) +#define NLOHMANN_JSON_PASTE23(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE22(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) +#define NLOHMANN_JSON_PASTE24(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE23(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) +#define NLOHMANN_JSON_PASTE25(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE24(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) +#define NLOHMANN_JSON_PASTE26(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE25(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) +#define NLOHMANN_JSON_PASTE27(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE26(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) +#define NLOHMANN_JSON_PASTE28(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE27(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) +#define NLOHMANN_JSON_PASTE29(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE28(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) +#define NLOHMANN_JSON_PASTE30(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE29(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) +#define NLOHMANN_JSON_PASTE31(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE30(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) +#define NLOHMANN_JSON_PASTE32(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE31(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) +#define NLOHMANN_JSON_PASTE33(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE32(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) +#define NLOHMANN_JSON_PASTE34(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE33(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) +#define NLOHMANN_JSON_PASTE35(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE34(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) +#define NLOHMANN_JSON_PASTE36(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE35(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) +#define NLOHMANN_JSON_PASTE37(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE36(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) +#define NLOHMANN_JSON_PASTE38(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE37(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) +#define NLOHMANN_JSON_PASTE39(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE38(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) +#define NLOHMANN_JSON_PASTE40(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE39(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) +#define NLOHMANN_JSON_PASTE41(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE40(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) +#define NLOHMANN_JSON_PASTE42(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE41(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) +#define NLOHMANN_JSON_PASTE43(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE42(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) +#define NLOHMANN_JSON_PASTE44(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE43(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) +#define NLOHMANN_JSON_PASTE45(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE44(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) +#define NLOHMANN_JSON_PASTE46(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE45(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) +#define NLOHMANN_JSON_PASTE47(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE46(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) +#define NLOHMANN_JSON_PASTE48(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE47(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) +#define NLOHMANN_JSON_PASTE49(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE48(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) +#define NLOHMANN_JSON_PASTE50(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE49(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) +#define NLOHMANN_JSON_PASTE51(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE50(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) +#define NLOHMANN_JSON_PASTE52(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE51(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) +#define NLOHMANN_JSON_PASTE53(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE52(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) +#define NLOHMANN_JSON_PASTE54(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE53(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) +#define NLOHMANN_JSON_PASTE55(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE54(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) +#define NLOHMANN_JSON_PASTE56(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE55(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) +#define NLOHMANN_JSON_PASTE57(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE56(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) +#define NLOHMANN_JSON_PASTE58(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE57(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) +#define NLOHMANN_JSON_PASTE59(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE58(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) +#define NLOHMANN_JSON_PASTE60(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE59(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) +#define NLOHMANN_JSON_PASTE61(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE60(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) +#define NLOHMANN_JSON_PASTE62(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE61(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) +#define NLOHMANN_JSON_PASTE63(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE62(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) +#define NLOHMANN_JSON_PASTE64(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE63(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) + +#define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1; +#define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1); + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_INTRUSIVE +@since version 3.9.0 +*/ +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \ + friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE +@since version 3.9.0 +*/ +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \ + inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + + +// inspired from https://stackoverflow.com/a/26745591 +// allows to call any std function as if (e.g. with begin): +// using std::begin; begin(x); +// +// it allows using the detected idiom to retrieve the return type +// of such an expression +#define NLOHMANN_CAN_CALL_STD_FUNC_IMPL(std_name) \ + namespace detail { \ + using std::std_name; \ + \ + template \ + using result_of_##std_name = decltype(std_name(std::declval()...)); \ + } \ + \ + namespace detail2 { \ + struct std_name##_tag \ + { \ + }; \ + \ + template \ + std_name##_tag std_name(T&&...); \ + \ + template \ + using result_of_##std_name = decltype(std_name(std::declval()...)); \ + \ + template \ + struct would_call_std_##std_name \ + { \ + static constexpr auto const value = ::nlohmann::detail:: \ + is_detected_exact::value; \ + }; \ + } /* namespace detail2 */ \ + \ + template \ + struct would_call_std_##std_name : detail2::would_call_std_##std_name \ + { \ + } + +#ifndef JSON_USE_IMPLICIT_CONVERSIONS + #define JSON_USE_IMPLICIT_CONVERSIONS 1 +#endif + +#if JSON_USE_IMPLICIT_CONVERSIONS + #define JSON_EXPLICIT +#else + #define JSON_EXPLICIT explicit +#endif + +#ifndef JSON_DIAGNOSTICS + #define JSON_DIAGNOSTICS 0 +#endif + + +namespace nlohmann +{ +namespace detail +{ + +/*! +@brief replace all occurrences of a substring by another string + +@param[in,out] s the string to manipulate; changed so that all + occurrences of @a f are replaced with @a t +@param[in] f the substring to replace with @a t +@param[in] t the string to replace @a f + +@pre The search string @a f must not be empty. **This precondition is +enforced with an assertion.** + +@since version 2.0.0 +*/ +inline void replace_substring(std::string& s, const std::string& f, + const std::string& t) +{ + JSON_ASSERT(!f.empty()); + for (auto pos = s.find(f); // find first occurrence of f + pos != std::string::npos; // make sure f was found + s.replace(pos, f.size(), t), // replace with t, and + pos = s.find(f, pos + t.size())) // find next occurrence of f + {} +} + +/*! + * @brief string escaping as described in RFC 6901 (Sect. 4) + * @param[in] s string to escape + * @return escaped string + * + * Note the order of escaping "~" to "~0" and "/" to "~1" is important. + */ +inline std::string escape(std::string s) +{ + replace_substring(s, "~", "~0"); + replace_substring(s, "/", "~1"); + return s; +} + +/*! + * @brief string unescaping as described in RFC 6901 (Sect. 4) + * @param[in] s string to unescape + * @return unescaped string + * + * Note the order of escaping "~1" to "/" and "~0" to "~" is important. + */ +static void unescape(std::string& s) +{ + replace_substring(s, "~1", "/"); + replace_substring(s, "~0", "~"); +} + +} // namespace detail +} // namespace nlohmann + +// #include + + +#include // size_t + +namespace nlohmann +{ +namespace detail +{ +/// struct to capture the start position of the current token +struct position_t +{ + /// the total number of characters read + std::size_t chars_read_total = 0; + /// the number of characters read in the current line + std::size_t chars_read_current_line = 0; + /// the number of lines read + std::size_t lines_read = 0; + + /// conversion to size_t to preserve SAX interface + constexpr operator size_t() const + { + return chars_read_total; + } +}; + +} // namespace detail +} // namespace nlohmann + +// #include + + +namespace nlohmann +{ +namespace detail +{ +//////////////// +// exceptions // +//////////////// + +/// @brief general exception of the @ref basic_json class +/// @sa https://json.nlohmann.me/api/basic_json/exception/ +class exception : public std::exception +{ + public: + /// returns the explanatory string + const char* what() const noexcept override + { + return m.what(); + } + + /// the id of the exception + const int id; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) + + protected: + JSON_HEDLEY_NON_NULL(3) + exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} // NOLINT(bugprone-throw-keyword-missing) + + static std::string name(const std::string& ename, int id_) + { + return "[json.exception." + ename + "." + std::to_string(id_) + "] "; + } + + template + static std::string diagnostics(const BasicJsonType& leaf_element) + { +#if JSON_DIAGNOSTICS + std::vector tokens; + for (const auto* current = &leaf_element; current->m_parent != nullptr; current = current->m_parent) + { + switch (current->m_parent->type()) + { + case value_t::array: + { + for (std::size_t i = 0; i < current->m_parent->m_value.array->size(); ++i) + { + if (¤t->m_parent->m_value.array->operator[](i) == current) + { + tokens.emplace_back(std::to_string(i)); + break; + } + } + break; + } + + case value_t::object: + { + for (const auto& element : *current->m_parent->m_value.object) + { + if (&element.second == current) + { + tokens.emplace_back(element.first.c_str()); + break; + } + } + break; + } + + case value_t::null: // LCOV_EXCL_LINE + case value_t::string: // LCOV_EXCL_LINE + case value_t::boolean: // LCOV_EXCL_LINE + case value_t::number_integer: // LCOV_EXCL_LINE + case value_t::number_unsigned: // LCOV_EXCL_LINE + case value_t::number_float: // LCOV_EXCL_LINE + case value_t::binary: // LCOV_EXCL_LINE + case value_t::discarded: // LCOV_EXCL_LINE + default: // LCOV_EXCL_LINE + break; // LCOV_EXCL_LINE + } + } + + if (tokens.empty()) + { + return ""; + } + + return "(" + std::accumulate(tokens.rbegin(), tokens.rend(), std::string{}, + [](const std::string & a, const std::string & b) + { + return a + "/" + detail::escape(b); + }) + ") "; +#else + static_cast(leaf_element); + return ""; +#endif + } + + private: + /// an exception object as storage for error messages + std::runtime_error m; +}; + +/// @brief exception indicating a parse error +/// @sa https://json.nlohmann.me/api/basic_json/parse_error/ +class parse_error : public exception +{ + public: + /*! + @brief create a parse error exception + @param[in] id_ the id of the exception + @param[in] pos the position where the error occurred (or with + chars_read_total=0 if the position cannot be + determined) + @param[in] what_arg the explanatory string + @return parse_error object + */ + template + static parse_error create(int id_, const position_t& pos, const std::string& what_arg, const BasicJsonType& context) + { + std::string w = exception::name("parse_error", id_) + "parse error" + + position_string(pos) + ": " + exception::diagnostics(context) + what_arg; + return {id_, pos.chars_read_total, w.c_str()}; + } + + template + static parse_error create(int id_, std::size_t byte_, const std::string& what_arg, const BasicJsonType& context) + { + std::string w = exception::name("parse_error", id_) + "parse error" + + (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") + + ": " + exception::diagnostics(context) + what_arg; + return {id_, byte_, w.c_str()}; + } + + /*! + @brief byte index of the parse error + + The byte index of the last read character in the input file. + + @note For an input with n bytes, 1 is the index of the first character and + n+1 is the index of the terminating null byte or the end of file. + This also holds true when reading a byte vector (CBOR or MessagePack). + */ + const std::size_t byte; + + private: + parse_error(int id_, std::size_t byte_, const char* what_arg) + : exception(id_, what_arg), byte(byte_) {} + + static std::string position_string(const position_t& pos) + { + return " at line " + std::to_string(pos.lines_read + 1) + + ", column " + std::to_string(pos.chars_read_current_line); + } +}; + +/// @brief exception indicating errors with iterators +/// @sa https://json.nlohmann.me/api/basic_json/invalid_iterator/ +class invalid_iterator : public exception +{ + public: + template + static invalid_iterator create(int id_, const std::string& what_arg, const BasicJsonType& context) + { + std::string w = exception::name("invalid_iterator", id_) + exception::diagnostics(context) + what_arg; + return {id_, w.c_str()}; + } + + private: + JSON_HEDLEY_NON_NULL(3) + invalid_iterator(int id_, const char* what_arg) + : exception(id_, what_arg) {} +}; + +/// @brief exception indicating executing a member function with a wrong type +/// @sa https://json.nlohmann.me/api/basic_json/type_error/ +class type_error : public exception +{ + public: + template + static type_error create(int id_, const std::string& what_arg, const BasicJsonType& context) + { + std::string w = exception::name("type_error", id_) + exception::diagnostics(context) + what_arg; + return {id_, w.c_str()}; + } + + private: + JSON_HEDLEY_NON_NULL(3) + type_error(int id_, const char* what_arg) : exception(id_, what_arg) {} +}; + +/// @brief exception indicating access out of the defined range +/// @sa https://json.nlohmann.me/api/basic_json/out_of_range/ +class out_of_range : public exception +{ + public: + template + static out_of_range create(int id_, const std::string& what_arg, const BasicJsonType& context) + { + std::string w = exception::name("out_of_range", id_) + exception::diagnostics(context) + what_arg; + return {id_, w.c_str()}; + } + + private: + JSON_HEDLEY_NON_NULL(3) + out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {} +}; + +/// @brief exception indicating other library errors +/// @sa https://json.nlohmann.me/api/basic_json/other_error/ +class other_error : public exception +{ + public: + template + static other_error create(int id_, const std::string& what_arg, const BasicJsonType& context) + { + std::string w = exception::name("other_error", id_) + exception::diagnostics(context) + what_arg; + return {id_, w.c_str()}; + } + + private: + JSON_HEDLEY_NON_NULL(3) + other_error(int id_, const char* what_arg) : exception(id_, what_arg) {} +}; + +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + + +#include // size_t +#include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type +#include // index_sequence, make_index_sequence, index_sequence_for + +// #include + + +namespace nlohmann +{ +namespace detail +{ + +template +using uncvref_t = typename std::remove_cv::type>::type; + +#ifdef JSON_HAS_CPP_14 + +// the following utilities are natively available in C++14 +using std::enable_if_t; +using std::index_sequence; +using std::make_index_sequence; +using std::index_sequence_for; + +#else + +// alias templates to reduce boilerplate +template +using enable_if_t = typename std::enable_if::type; + +// The following code is taken from https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h +// which is part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0. + +//// START OF CODE FROM GOOGLE ABSEIL + +// integer_sequence +// +// Class template representing a compile-time integer sequence. An instantiation +// of `integer_sequence` has a sequence of integers encoded in its +// type through its template arguments (which is a common need when +// working with C++11 variadic templates). `absl::integer_sequence` is designed +// to be a drop-in replacement for C++14's `std::integer_sequence`. +// +// Example: +// +// template< class T, T... Ints > +// void user_function(integer_sequence); +// +// int main() +// { +// // user_function's `T` will be deduced to `int` and `Ints...` +// // will be deduced to `0, 1, 2, 3, 4`. +// user_function(make_integer_sequence()); +// } +template +struct integer_sequence +{ + using value_type = T; + static constexpr std::size_t size() noexcept + { + return sizeof...(Ints); + } +}; + +// index_sequence +// +// A helper template for an `integer_sequence` of `size_t`, +// `absl::index_sequence` is designed to be a drop-in replacement for C++14's +// `std::index_sequence`. +template +using index_sequence = integer_sequence; + +namespace utility_internal +{ + +template +struct Extend; + +// Note that SeqSize == sizeof...(Ints). It's passed explicitly for efficiency. +template +struct Extend, SeqSize, 0> +{ + using type = integer_sequence < T, Ints..., (Ints + SeqSize)... >; +}; + +template +struct Extend, SeqSize, 1> +{ + using type = integer_sequence < T, Ints..., (Ints + SeqSize)..., 2 * SeqSize >; +}; + +// Recursion helper for 'make_integer_sequence'. +// 'Gen::type' is an alias for 'integer_sequence'. +template +struct Gen +{ + using type = + typename Extend < typename Gen < T, N / 2 >::type, N / 2, N % 2 >::type; +}; + +template +struct Gen +{ + using type = integer_sequence; +}; + +} // namespace utility_internal + +// Compile-time sequences of integers + +// make_integer_sequence +// +// This template alias is equivalent to +// `integer_sequence`, and is designed to be a drop-in +// replacement for C++14's `std::make_integer_sequence`. +template +using make_integer_sequence = typename utility_internal::Gen::type; + +// make_index_sequence +// +// This template alias is equivalent to `index_sequence<0, 1, ..., N-1>`, +// and is designed to be a drop-in replacement for C++14's +// `std::make_index_sequence`. +template +using make_index_sequence = make_integer_sequence; + +// index_sequence_for +// +// Converts a typename pack into an index sequence of the same length, and +// is designed to be a drop-in replacement for C++14's +// `std::index_sequence_for()` +template +using index_sequence_for = make_index_sequence; + +//// END OF CODE FROM GOOGLE ABSEIL + +#endif + +// dispatch utility (taken from ranges-v3) +template struct priority_tag : priority_tag < N - 1 > {}; +template<> struct priority_tag<0> {}; + +// taken from ranges-v3 +template +struct static_const +{ + static constexpr T value{}; +}; + +template +constexpr T static_const::value; // NOLINT(readability-redundant-declaration) + +} // namespace detail +} // namespace nlohmann + +// #include + + +namespace nlohmann +{ +namespace detail +{ +// dispatching helper struct +template struct identity_tag {}; +} // namespace detail +} // namespace nlohmann + +// #include + + +#include // numeric_limits +#include // false_type, is_constructible, is_integral, is_same, true_type +#include // declval +#include // tuple + +// #include + + +// #include + + +#include // random_access_iterator_tag + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template +struct iterator_types {}; + +template +struct iterator_types < + It, + void_t> +{ + using difference_type = typename It::difference_type; + using value_type = typename It::value_type; + using pointer = typename It::pointer; + using reference = typename It::reference; + using iterator_category = typename It::iterator_category; +}; + +// This is required as some compilers implement std::iterator_traits in a way that +// doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. +template +struct iterator_traits +{ +}; + +template +struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> + : iterator_types +{ +}; + +template +struct iterator_traits::value>> +{ + using iterator_category = std::random_access_iterator_tag; + using value_type = T; + using difference_type = ptrdiff_t; + using pointer = T*; + using reference = T&; +}; +} // namespace detail +} // namespace nlohmann + +// #include + + +// #include + + +namespace nlohmann +{ +NLOHMANN_CAN_CALL_STD_FUNC_IMPL(begin); +} // namespace nlohmann + +// #include + + +// #include + + +namespace nlohmann +{ +NLOHMANN_CAN_CALL_STD_FUNC_IMPL(end); +} // namespace nlohmann + +// #include + +// #include + +// #include +#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ +#define INCLUDE_NLOHMANN_JSON_FWD_HPP_ + +#include // int64_t, uint64_t +#include // map +#include // allocator +#include // string +#include // vector + +/*! +@brief namespace for Niels Lohmann +@see https://github.com/nlohmann +@since version 1.0.0 +*/ +namespace nlohmann +{ +/*! +@brief default JSONSerializer template argument + +This serializer ignores the template arguments and uses ADL +([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) +for serialization. +*/ +template +struct adl_serializer; + +/// a class to store JSON values +/// @sa https://json.nlohmann.me/api/basic_json/ +template class ObjectType = + std::map, + template class ArrayType = std::vector, + class StringType = std::string, class BooleanType = bool, + class NumberIntegerType = std::int64_t, + class NumberUnsignedType = std::uint64_t, + class NumberFloatType = double, + template class AllocatorType = std::allocator, + template class JSONSerializer = + adl_serializer, + class BinaryType = std::vector> +class basic_json; + +/// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document +/// @sa https://json.nlohmann.me/api/json_pointer/ +template +class json_pointer; + +/*! +@brief default specialization +@sa https://json.nlohmann.me/api/json/ +*/ +using json = basic_json<>; + +/// @brief a minimal map-like container that preserves insertion order +/// @sa https://json.nlohmann.me/api/ordered_map/ +template +struct ordered_map; + +/// @brief specialization that maintains the insertion order of object keys +/// @sa https://json.nlohmann.me/api/ordered_json/ +using ordered_json = basic_json; + +} // namespace nlohmann + +#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ + + +namespace nlohmann +{ +/*! +@brief detail namespace with internal helper functions + +This namespace collects functions that should not be exposed, +implementations of some @ref basic_json methods, and meta-programming helpers. + +@since version 2.1.0 +*/ +namespace detail +{ +///////////// +// helpers // +///////////// + +// Note to maintainers: +// +// Every trait in this file expects a non CV-qualified type. +// The only exceptions are in the 'aliases for detected' section +// (i.e. those of the form: decltype(T::member_function(std::declval()))) +// +// In this case, T has to be properly CV-qualified to constraint the function arguments +// (e.g. to_json(BasicJsonType&, const T&)) + +template struct is_basic_json : std::false_type {}; + +NLOHMANN_BASIC_JSON_TPL_DECLARATION +struct is_basic_json : std::true_type {}; + +////////////////////// +// json_ref helpers // +////////////////////// + +template +class json_ref; + +template +struct is_json_ref : std::false_type {}; + +template +struct is_json_ref> : std::true_type {}; + +////////////////////////// +// aliases for detected // +////////////////////////// + +template +using mapped_type_t = typename T::mapped_type; + +template +using key_type_t = typename T::key_type; + +template +using value_type_t = typename T::value_type; + +template +using difference_type_t = typename T::difference_type; + +template +using pointer_t = typename T::pointer; + +template +using reference_t = typename T::reference; + +template +using iterator_category_t = typename T::iterator_category; + +template +using to_json_function = decltype(T::to_json(std::declval()...)); + +template +using from_json_function = decltype(T::from_json(std::declval()...)); + +template +using get_template_function = decltype(std::declval().template get()); + +// trait checking if JSONSerializer::from_json(json const&, udt&) exists +template +struct has_from_json : std::false_type {}; + +// trait checking if j.get is valid +// use this trait instead of std::is_constructible or std::is_convertible, +// both rely on, or make use of implicit conversions, and thus fail when T +// has several constructors/operator= (see https://github.com/nlohmann/json/issues/958) +template +struct is_getable +{ + static constexpr bool value = is_detected::value; +}; + +template +struct has_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +// This trait checks if JSONSerializer::from_json(json const&) exists +// this overload is used for non-default-constructible user-defined-types +template +struct has_non_default_from_json : std::false_type {}; + +template +struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +// This trait checks if BasicJsonType::json_serializer::to_json exists +// Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion. +template +struct has_to_json : std::false_type {}; + +template +struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + + +/////////////////// +// is_ functions // +/////////////////// + +// https://en.cppreference.com/w/cpp/types/conjunction +template struct conjunction : std::true_type { }; +template struct conjunction : B1 { }; +template +struct conjunction +: std::conditional, B1>::type {}; + +// https://en.cppreference.com/w/cpp/types/negation +template struct negation : std::integral_constant < bool, !B::value > { }; + +// Reimplementation of is_constructible and is_default_constructible, due to them being broken for +// std::pair and std::tuple until LWG 2367 fix (see https://cplusplus.github.io/LWG/lwg-defects.html#2367). +// This causes compile errors in e.g. clang 3.5 or gcc 4.9. +template +struct is_default_constructible : std::is_default_constructible {}; + +template +struct is_default_constructible> + : conjunction, is_default_constructible> {}; + +template +struct is_default_constructible> + : conjunction, is_default_constructible> {}; + +template +struct is_default_constructible> + : conjunction...> {}; + +template +struct is_default_constructible> + : conjunction...> {}; + + +template +struct is_constructible : std::is_constructible {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + + +template +struct is_iterator_traits : std::false_type {}; + +template +struct is_iterator_traits> +{ + private: + using traits = iterator_traits; + + public: + static constexpr auto value = + is_detected::value && + is_detected::value && + is_detected::value && + is_detected::value && + is_detected::value; +}; + +template +struct is_range +{ + private: + using t_ref = typename std::add_lvalue_reference::type; + + using iterator = detected_t; + using sentinel = detected_t; + + // to be 100% correct, it should use https://en.cppreference.com/w/cpp/iterator/input_or_output_iterator + // and https://en.cppreference.com/w/cpp/iterator/sentinel_for + // but reimplementing these would be too much work, as a lot of other concepts are used underneath + static constexpr auto is_iterator_begin = + is_iterator_traits>::value; + + public: + static constexpr bool value = !std::is_same::value && !std::is_same::value && is_iterator_begin; +}; + +template +using iterator_t = enable_if_t::value, result_of_begin())>>; + +template +using range_value_t = value_type_t>>; + +// The following implementation of is_complete_type is taken from +// https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/ +// and is written by Xiang Fan who agreed to using it in this library. + +template +struct is_complete_type : std::false_type {}; + +template +struct is_complete_type : std::true_type {}; + +template +struct is_compatible_object_type_impl : std::false_type {}; + +template +struct is_compatible_object_type_impl < + BasicJsonType, CompatibleObjectType, + enable_if_t < is_detected::value&& + is_detected::value >> +{ + using object_t = typename BasicJsonType::object_t; + + // macOS's is_constructible does not play well with nonesuch... + static constexpr bool value = + is_constructible::value && + is_constructible::value; +}; + +template +struct is_compatible_object_type + : is_compatible_object_type_impl {}; + +template +struct is_constructible_object_type_impl : std::false_type {}; + +template +struct is_constructible_object_type_impl < + BasicJsonType, ConstructibleObjectType, + enable_if_t < is_detected::value&& + is_detected::value >> +{ + using object_t = typename BasicJsonType::object_t; + + static constexpr bool value = + (is_default_constructible::value && + (std::is_move_assignable::value || + std::is_copy_assignable::value) && + (is_constructible::value && + std::is_same < + typename object_t::mapped_type, + typename ConstructibleObjectType::mapped_type >::value)) || + (has_from_json::value || + has_non_default_from_json < + BasicJsonType, + typename ConstructibleObjectType::mapped_type >::value); +}; + +template +struct is_constructible_object_type + : is_constructible_object_type_impl {}; + +template +struct is_compatible_string_type +{ + static constexpr auto value = + is_constructible::value; +}; + +template +struct is_constructible_string_type +{ + static constexpr auto value = + is_constructible::value; +}; + +template +struct is_compatible_array_type_impl : std::false_type {}; + +template +struct is_compatible_array_type_impl < + BasicJsonType, CompatibleArrayType, + enable_if_t < + is_detected::value&& + is_iterator_traits>>::value&& +// special case for types like std::filesystem::path whose iterator's value_type are themselves +// c.f. https://github.com/nlohmann/json/pull/3073 + !std::is_same>::value >> +{ + static constexpr bool value = + is_constructible>::value; +}; + +template +struct is_compatible_array_type + : is_compatible_array_type_impl {}; + +template +struct is_constructible_array_type_impl : std::false_type {}; + +template +struct is_constructible_array_type_impl < + BasicJsonType, ConstructibleArrayType, + enable_if_t::value >> + : std::true_type {}; + +template +struct is_constructible_array_type_impl < + BasicJsonType, ConstructibleArrayType, + enable_if_t < !std::is_same::value&& + !is_compatible_string_type::value&& + is_default_constructible::value&& +(std::is_move_assignable::value || + std::is_copy_assignable::value)&& +is_detected::value&& +is_iterator_traits>>::value&& +is_detected::value&& +// special case for types like std::filesystem::path whose iterator's value_type are themselves +// c.f. https://github.com/nlohmann/json/pull/3073 +!std::is_same>::value&& + is_complete_type < + detected_t>::value >> +{ + using value_type = range_value_t; + + static constexpr bool value = + std::is_same::value || + has_from_json::value || + has_non_default_from_json < + BasicJsonType, + value_type >::value; +}; + +template +struct is_constructible_array_type + : is_constructible_array_type_impl {}; + +template +struct is_compatible_integer_type_impl : std::false_type {}; + +template +struct is_compatible_integer_type_impl < + RealIntegerType, CompatibleNumberIntegerType, + enable_if_t < std::is_integral::value&& + std::is_integral::value&& + !std::is_same::value >> +{ + // is there an assert somewhere on overflows? + using RealLimits = std::numeric_limits; + using CompatibleLimits = std::numeric_limits; + + static constexpr auto value = + is_constructible::value && + CompatibleLimits::is_integer && + RealLimits::is_signed == CompatibleLimits::is_signed; +}; + +template +struct is_compatible_integer_type + : is_compatible_integer_type_impl {}; + +template +struct is_compatible_type_impl: std::false_type {}; + +template +struct is_compatible_type_impl < + BasicJsonType, CompatibleType, + enable_if_t::value >> +{ + static constexpr bool value = + has_to_json::value; +}; + +template +struct is_compatible_type + : is_compatible_type_impl {}; + +template +struct is_constructible_tuple : std::false_type {}; + +template +struct is_constructible_tuple> : conjunction...> {}; + +// a naive helper to check if a type is an ordered_map (exploits the fact that +// ordered_map inherits capacity() from std::vector) +template +struct is_ordered_map +{ + using one = char; + + struct two + { + char x[2]; // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) + }; + + template static one test( decltype(&C::capacity) ) ; + template static two test(...); + + enum { value = sizeof(test(nullptr)) == sizeof(char) }; // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) +}; + +// to avoid useless casts (see https://github.com/nlohmann/json/issues/2893#issuecomment-889152324) +template < typename T, typename U, enable_if_t < !std::is_same::value, int > = 0 > +T conditional_static_cast(U value) +{ + return static_cast(value); +} + +template::value, int> = 0> +T conditional_static_cast(U value) +{ + return value; +} + +} // namespace detail +} // namespace nlohmann + +// #include + + +#if JSON_HAS_EXPERIMENTAL_FILESYSTEM +#include +namespace nlohmann::detail +{ +namespace std_fs = std::experimental::filesystem; +} // namespace nlohmann::detail +#elif JSON_HAS_FILESYSTEM +#include +namespace nlohmann::detail +{ +namespace std_fs = std::filesystem; +} // namespace nlohmann::detail +#endif + +namespace nlohmann +{ +namespace detail +{ +template +void from_json(const BasicJsonType& j, typename std::nullptr_t& n) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_null())) + { + JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name()), j)); + } + n = nullptr; +} + +// overloads for basic_json template parameters +template < typename BasicJsonType, typename ArithmeticType, + enable_if_t < std::is_arithmetic::value&& + !std::is_same::value, + int > = 0 > +void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val) +{ + switch (static_cast(j)) + { + case value_t::number_unsigned: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::number_integer: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::number_float: + { + val = static_cast(*j.template get_ptr()); + break; + } + + case value_t::null: + case value_t::object: + case value_t::array: + case value_t::string: + case value_t::boolean: + case value_t::binary: + case value_t::discarded: + default: + JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j)); + } +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_boolean())) + { + JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name()), j)); + } + b = *j.template get_ptr(); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_string())) + { + JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j)); + } + s = *j.template get_ptr(); +} + +template < + typename BasicJsonType, typename ConstructibleStringType, + enable_if_t < + is_constructible_string_type::value&& + !std::is_same::value, + int > = 0 > +void from_json(const BasicJsonType& j, ConstructibleStringType& s) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_string())) + { + JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j)); + } + + s = *j.template get_ptr(); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val) +{ + get_arithmetic_value(j, val); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val) +{ + get_arithmetic_value(j, val); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val) +{ + get_arithmetic_value(j, val); +} + +template::value, int> = 0> +void from_json(const BasicJsonType& j, EnumType& e) +{ + typename std::underlying_type::type val; + get_arithmetic_value(j, val); + e = static_cast(val); +} + +// forward_list doesn't have an insert method +template::value, int> = 0> +void from_json(const BasicJsonType& j, std::forward_list& l) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); + } + l.clear(); + std::transform(j.rbegin(), j.rend(), + std::front_inserter(l), [](const BasicJsonType & i) + { + return i.template get(); + }); +} + +// valarray doesn't have an insert method +template::value, int> = 0> +void from_json(const BasicJsonType& j, std::valarray& l) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); + } + l.resize(j.size()); + std::transform(j.begin(), j.end(), std::begin(l), + [](const BasicJsonType & elem) + { + return elem.template get(); + }); +} + +template +auto from_json(const BasicJsonType& j, T (&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) +-> decltype(j.template get(), void()) +{ + for (std::size_t i = 0; i < N; ++i) + { + arr[i] = j.at(i).template get(); + } +} + +template +void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/) +{ + arr = *j.template get_ptr(); +} + +template +auto from_json_array_impl(const BasicJsonType& j, std::array& arr, + priority_tag<2> /*unused*/) +-> decltype(j.template get(), void()) +{ + for (std::size_t i = 0; i < N; ++i) + { + arr[i] = j.at(i).template get(); + } +} + +template::value, + int> = 0> +auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/) +-> decltype( + arr.reserve(std::declval()), + j.template get(), + void()) +{ + using std::end; + + ConstructibleArrayType ret; + ret.reserve(j.size()); + std::transform(j.begin(), j.end(), + std::inserter(ret, end(ret)), [](const BasicJsonType & i) + { + // get() returns *this, this won't call a from_json + // method when value_type is BasicJsonType + return i.template get(); + }); + arr = std::move(ret); +} + +template::value, + int> = 0> +void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, + priority_tag<0> /*unused*/) +{ + using std::end; + + ConstructibleArrayType ret; + std::transform( + j.begin(), j.end(), std::inserter(ret, end(ret)), + [](const BasicJsonType & i) + { + // get() returns *this, this won't call a from_json + // method when value_type is BasicJsonType + return i.template get(); + }); + arr = std::move(ret); +} + +template < typename BasicJsonType, typename ConstructibleArrayType, + enable_if_t < + is_constructible_array_type::value&& + !is_constructible_object_type::value&& + !is_constructible_string_type::value&& + !std::is_same::value&& + !is_basic_json::value, + int > = 0 > +auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr) +-> decltype(from_json_array_impl(j, arr, priority_tag<3> {}), +j.template get(), +void()) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); + } + + from_json_array_impl(j, arr, priority_tag<3> {}); +} + +template < typename BasicJsonType, typename T, std::size_t... Idx > +std::array from_json_inplace_array_impl(BasicJsonType&& j, + identity_tag> /*unused*/, index_sequence /*unused*/) +{ + return { { std::forward(j).at(Idx).template get()... } }; +} + +template < typename BasicJsonType, typename T, std::size_t N > +auto from_json(BasicJsonType&& j, identity_tag> tag) +-> decltype(from_json_inplace_array_impl(std::forward(j), tag, make_index_sequence {})) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); + } + + return from_json_inplace_array_impl(std::forward(j), tag, make_index_sequence {}); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::binary_t& bin) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_binary())) + { + JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(j.type_name()), j)); + } + + bin = *j.template get_ptr(); +} + +template::value, int> = 0> +void from_json(const BasicJsonType& j, ConstructibleObjectType& obj) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_object())) + { + JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name()), j)); + } + + ConstructibleObjectType ret; + const auto* inner_object = j.template get_ptr(); + using value_type = typename ConstructibleObjectType::value_type; + std::transform( + inner_object->begin(), inner_object->end(), + std::inserter(ret, ret.begin()), + [](typename BasicJsonType::object_t::value_type const & p) + { + return value_type(p.first, p.second.template get()); + }); + obj = std::move(ret); +} + +// overload for arithmetic types, not chosen for basic_json template arguments +// (BooleanType, etc..); note: Is it really necessary to provide explicit +// overloads for boolean_t etc. in case of a custom BooleanType which is not +// an arithmetic type? +template < typename BasicJsonType, typename ArithmeticType, + enable_if_t < + std::is_arithmetic::value&& + !std::is_same::value&& + !std::is_same::value&& + !std::is_same::value&& + !std::is_same::value, + int > = 0 > +void from_json(const BasicJsonType& j, ArithmeticType& val) +{ + switch (static_cast(j)) + { + case value_t::number_unsigned: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::number_integer: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::number_float: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::boolean: + { + val = static_cast(*j.template get_ptr()); + break; + } + + case value_t::null: + case value_t::object: + case value_t::array: + case value_t::string: + case value_t::binary: + case value_t::discarded: + default: + JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j)); + } +} + +template +std::tuple from_json_tuple_impl_base(BasicJsonType&& j, index_sequence /*unused*/) +{ + return std::make_tuple(std::forward(j).at(Idx).template get()...); +} + +template < typename BasicJsonType, class A1, class A2 > +std::pair from_json_tuple_impl(BasicJsonType&& j, identity_tag> /*unused*/, priority_tag<0> /*unused*/) +{ + return {std::forward(j).at(0).template get(), + std::forward(j).at(1).template get()}; +} + +template +void from_json_tuple_impl(BasicJsonType&& j, std::pair& p, priority_tag<1> /*unused*/) +{ + p = from_json_tuple_impl(std::forward(j), identity_tag> {}, priority_tag<0> {}); +} + +template +std::tuple from_json_tuple_impl(BasicJsonType&& j, identity_tag> /*unused*/, priority_tag<2> /*unused*/) +{ + return from_json_tuple_impl_base(std::forward(j), index_sequence_for {}); +} + +template +void from_json_tuple_impl(BasicJsonType&& j, std::tuple& t, priority_tag<3> /*unused*/) +{ + t = from_json_tuple_impl_base(std::forward(j), index_sequence_for {}); +} + +template +auto from_json(BasicJsonType&& j, TupleRelated&& t) +-> decltype(from_json_tuple_impl(std::forward(j), std::forward(t), priority_tag<3> {})) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); + } + + return from_json_tuple_impl(std::forward(j), std::forward(t), priority_tag<3> {}); +} + +template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator, + typename = enable_if_t < !std::is_constructible < + typename BasicJsonType::string_t, Key >::value >> +void from_json(const BasicJsonType& j, std::map& m) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); + } + m.clear(); + for (const auto& p : j) + { + if (JSON_HEDLEY_UNLIKELY(!p.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j)); + } + m.emplace(p.at(0).template get(), p.at(1).template get()); + } +} + +template < typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator, + typename = enable_if_t < !std::is_constructible < + typename BasicJsonType::string_t, Key >::value >> +void from_json(const BasicJsonType& j, std::unordered_map& m) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); + } + m.clear(); + for (const auto& p : j) + { + if (JSON_HEDLEY_UNLIKELY(!p.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j)); + } + m.emplace(p.at(0).template get(), p.at(1).template get()); + } +} + +#if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM +template +void from_json(const BasicJsonType& j, std_fs::path& p) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_string())) + { + JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j)); + } + p = *j.template get_ptr(); +} +#endif + +struct from_json_fn +{ + template + auto operator()(const BasicJsonType& j, T&& val) const + noexcept(noexcept(from_json(j, std::forward(val)))) + -> decltype(from_json(j, std::forward(val))) + { + return from_json(j, std::forward(val)); + } +}; +} // namespace detail + +/// namespace to hold default `from_json` function +/// to see why this is required: +/// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html +namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces) +{ +constexpr const auto& from_json = detail::static_const::value; // NOLINT(misc-definitions-in-headers) +} // namespace +} // namespace nlohmann + +// #include + + +#include // copy +#include // begin, end +#include // string +#include // tuple, get +#include // is_same, is_constructible, is_floating_point, is_enum, underlying_type +#include // move, forward, declval, pair +#include // valarray +#include // vector + +// #include + +// #include + + +#include // size_t +#include // input_iterator_tag +#include // string, to_string +#include // tuple_size, get, tuple_element +#include // move + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template +void int_to_string( string_type& target, std::size_t value ) +{ + // For ADL + using std::to_string; + target = to_string(value); +} +template class iteration_proxy_value +{ + public: + using difference_type = std::ptrdiff_t; + using value_type = iteration_proxy_value; + using pointer = value_type * ; + using reference = value_type & ; + using iterator_category = std::input_iterator_tag; + using string_type = typename std::remove_cv< typename std::remove_reference().key() ) >::type >::type; + + private: + /// the iterator + IteratorType anchor; + /// an index for arrays (used to create key names) + std::size_t array_index = 0; + /// last stringified array index + mutable std::size_t array_index_last = 0; + /// a string representation of the array index + mutable string_type array_index_str = "0"; + /// an empty string (to return a reference for primitive values) + const string_type empty_str{}; + + public: + explicit iteration_proxy_value(IteratorType it) noexcept + : anchor(std::move(it)) + {} + + /// dereference operator (needed for range-based for) + iteration_proxy_value& operator*() + { + return *this; + } + + /// increment operator (needed for range-based for) + iteration_proxy_value& operator++() + { + ++anchor; + ++array_index; + + return *this; + } + + /// equality operator (needed for InputIterator) + bool operator==(const iteration_proxy_value& o) const + { + return anchor == o.anchor; + } + + /// inequality operator (needed for range-based for) + bool operator!=(const iteration_proxy_value& o) const + { + return anchor != o.anchor; + } + + /// return key of the iterator + const string_type& key() const + { + JSON_ASSERT(anchor.m_object != nullptr); + + switch (anchor.m_object->type()) + { + // use integer array index as key + case value_t::array: + { + if (array_index != array_index_last) + { + int_to_string( array_index_str, array_index ); + array_index_last = array_index; + } + return array_index_str; + } + + // use key from the object + case value_t::object: + return anchor.key(); + + // use an empty key for all primitive types + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + return empty_str; + } + } + + /// return value of the iterator + typename IteratorType::reference value() const + { + return anchor.value(); + } +}; + +/// proxy class for the items() function +template class iteration_proxy +{ + private: + /// the container to iterate + typename IteratorType::reference container; + + public: + /// construct iteration proxy from a container + explicit iteration_proxy(typename IteratorType::reference cont) noexcept + : container(cont) {} + + /// return iterator begin (needed for range-based for) + iteration_proxy_value begin() noexcept + { + return iteration_proxy_value(container.begin()); + } + + /// return iterator end (needed for range-based for) + iteration_proxy_value end() noexcept + { + return iteration_proxy_value(container.end()); + } +}; +// Structured Bindings Support +// For further reference see https://blog.tartanllama.xyz/structured-bindings/ +// And see https://github.com/nlohmann/json/pull/1391 +template = 0> +auto get(const nlohmann::detail::iteration_proxy_value& i) -> decltype(i.key()) +{ + return i.key(); +} +// Structured Bindings Support +// For further reference see https://blog.tartanllama.xyz/structured-bindings/ +// And see https://github.com/nlohmann/json/pull/1391 +template = 0> +auto get(const nlohmann::detail::iteration_proxy_value& i) -> decltype(i.value()) +{ + return i.value(); +} +} // namespace detail +} // namespace nlohmann + +// The Addition to the STD Namespace is required to add +// Structured Bindings Support to the iteration_proxy_value class +// For further reference see https://blog.tartanllama.xyz/structured-bindings/ +// And see https://github.com/nlohmann/json/pull/1391 +namespace std +{ +#if defined(__clang__) + // Fix: https://github.com/nlohmann/json/issues/1401 + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wmismatched-tags" +#endif +template +class tuple_size<::nlohmann::detail::iteration_proxy_value> + : public std::integral_constant {}; + +template +class tuple_element> +{ + public: + using type = decltype( + get(std::declval < + ::nlohmann::detail::iteration_proxy_value> ())); +}; +#if defined(__clang__) + #pragma clang diagnostic pop +#endif +} // namespace std + +// #include + +// #include + +// #include + + +#if JSON_HAS_EXPERIMENTAL_FILESYSTEM +#include +namespace nlohmann::detail +{ +namespace std_fs = std::experimental::filesystem; +} // namespace nlohmann::detail +#elif JSON_HAS_FILESYSTEM +#include +namespace nlohmann::detail +{ +namespace std_fs = std::filesystem; +} // namespace nlohmann::detail +#endif + +namespace nlohmann +{ +namespace detail +{ +////////////////// +// constructors // +////////////////// + +/* + * Note all external_constructor<>::construct functions need to call + * j.m_value.destroy(j.m_type) to avoid a memory leak in case j contains an + * allocated value (e.g., a string). See bug issue + * https://github.com/nlohmann/json/issues/2865 for more information. + */ + +template struct external_constructor; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::boolean; + j.m_value = b; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s) + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::string; + j.m_value = s; + j.assert_invariant(); + } + + template + static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s) + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::string; + j.m_value = std::move(s); + j.assert_invariant(); + } + + template < typename BasicJsonType, typename CompatibleStringType, + enable_if_t < !std::is_same::value, + int > = 0 > + static void construct(BasicJsonType& j, const CompatibleStringType& str) + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::string; + j.m_value.string = j.template create(str); + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, const typename BasicJsonType::binary_t& b) + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::binary; + j.m_value = typename BasicJsonType::binary_t(b); + j.assert_invariant(); + } + + template + static void construct(BasicJsonType& j, typename BasicJsonType::binary_t&& b) + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::binary; + j.m_value = typename BasicJsonType::binary_t(std::move(b)); + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::number_float; + j.m_value = val; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::number_unsigned; + j.m_value = val; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::number_integer; + j.m_value = val; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr) + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::array; + j.m_value = arr; + j.set_parents(); + j.assert_invariant(); + } + + template + static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr) + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::array; + j.m_value = std::move(arr); + j.set_parents(); + j.assert_invariant(); + } + + template < typename BasicJsonType, typename CompatibleArrayType, + enable_if_t < !std::is_same::value, + int > = 0 > + static void construct(BasicJsonType& j, const CompatibleArrayType& arr) + { + using std::begin; + using std::end; + + j.m_value.destroy(j.m_type); + j.m_type = value_t::array; + j.m_value.array = j.template create(begin(arr), end(arr)); + j.set_parents(); + j.assert_invariant(); + } + + template + static void construct(BasicJsonType& j, const std::vector& arr) + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::array; + j.m_value = value_t::array; + j.m_value.array->reserve(arr.size()); + for (const bool x : arr) + { + j.m_value.array->push_back(x); + j.set_parent(j.m_value.array->back()); + } + j.assert_invariant(); + } + + template::value, int> = 0> + static void construct(BasicJsonType& j, const std::valarray& arr) + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::array; + j.m_value = value_t::array; + j.m_value.array->resize(arr.size()); + if (arr.size() > 0) + { + std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin()); + } + j.set_parents(); + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj) + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::object; + j.m_value = obj; + j.set_parents(); + j.assert_invariant(); + } + + template + static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj) + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::object; + j.m_value = std::move(obj); + j.set_parents(); + j.assert_invariant(); + } + + template < typename BasicJsonType, typename CompatibleObjectType, + enable_if_t < !std::is_same::value, int > = 0 > + static void construct(BasicJsonType& j, const CompatibleObjectType& obj) + { + using std::begin; + using std::end; + + j.m_value.destroy(j.m_type); + j.m_type = value_t::object; + j.m_value.object = j.template create(begin(obj), end(obj)); + j.set_parents(); + j.assert_invariant(); + } +}; + +///////////// +// to_json // +///////////// + +template::value, int> = 0> +void to_json(BasicJsonType& j, T b) noexcept +{ + external_constructor::construct(j, b); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, const CompatibleString& s) +{ + external_constructor::construct(j, s); +} + +template +void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s) +{ + external_constructor::construct(j, std::move(s)); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, FloatType val) noexcept +{ + external_constructor::construct(j, static_cast(val)); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept +{ + external_constructor::construct(j, static_cast(val)); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept +{ + external_constructor::construct(j, static_cast(val)); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, EnumType e) noexcept +{ + using underlying_type = typename std::underlying_type::type; + external_constructor::construct(j, static_cast(e)); +} + +template +void to_json(BasicJsonType& j, const std::vector& e) +{ + external_constructor::construct(j, e); +} + +template < typename BasicJsonType, typename CompatibleArrayType, + enable_if_t < is_compatible_array_type::value&& + !is_compatible_object_type::value&& + !is_compatible_string_type::value&& + !std::is_same::value&& + !is_basic_json::value, + int > = 0 > +void to_json(BasicJsonType& j, const CompatibleArrayType& arr) +{ + external_constructor::construct(j, arr); +} + +template +void to_json(BasicJsonType& j, const typename BasicJsonType::binary_t& bin) +{ + external_constructor::construct(j, bin); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, const std::valarray& arr) +{ + external_constructor::construct(j, std::move(arr)); +} + +template +void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr) +{ + external_constructor::construct(j, std::move(arr)); +} + +template < typename BasicJsonType, typename CompatibleObjectType, + enable_if_t < is_compatible_object_type::value&& !is_basic_json::value, int > = 0 > +void to_json(BasicJsonType& j, const CompatibleObjectType& obj) +{ + external_constructor::construct(j, obj); +} + +template +void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj) +{ + external_constructor::construct(j, std::move(obj)); +} + +template < + typename BasicJsonType, typename T, std::size_t N, + enable_if_t < !std::is_constructible::value, // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) + int > = 0 > +void to_json(BasicJsonType& j, const T(&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) +{ + external_constructor::construct(j, arr); +} + +template < typename BasicJsonType, typename T1, typename T2, enable_if_t < std::is_constructible::value&& std::is_constructible::value, int > = 0 > +void to_json(BasicJsonType& j, const std::pair& p) +{ + j = { p.first, p.second }; +} + +// for https://github.com/nlohmann/json/pull/1134 +template>::value, int> = 0> +void to_json(BasicJsonType& j, const T& b) +{ + j = { {b.key(), b.value()} }; +} + +template +void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence /*unused*/) +{ + j = { std::get(t)... }; +} + +template::value, int > = 0> +void to_json(BasicJsonType& j, const T& t) +{ + to_json_tuple_impl(j, t, make_index_sequence::value> {}); +} + +#if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM +template +void to_json(BasicJsonType& j, const std_fs::path& p) +{ + j = p.string(); +} +#endif + +struct to_json_fn +{ + template + auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward(val)))) + -> decltype(to_json(j, std::forward(val)), void()) + { + return to_json(j, std::forward(val)); + } +}; +} // namespace detail + +/// namespace to hold default `to_json` function +/// to see why this is required: +/// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html +namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces) +{ +constexpr const auto& to_json = detail::static_const::value; // NOLINT(misc-definitions-in-headers) +} // namespace +} // namespace nlohmann + +// #include + +// #include + + +namespace nlohmann +{ + +/// @sa https://json.nlohmann.me/api/adl_serializer/ +template +struct adl_serializer +{ + /// @brief convert a JSON value to any value type + /// @sa https://json.nlohmann.me/api/adl_serializer/from_json/ + template + static auto from_json(BasicJsonType && j, TargetType& val) noexcept( + noexcept(::nlohmann::from_json(std::forward(j), val))) + -> decltype(::nlohmann::from_json(std::forward(j), val), void()) + { + ::nlohmann::from_json(std::forward(j), val); + } + + /// @brief convert a JSON value to any value type + /// @sa https://json.nlohmann.me/api/adl_serializer/from_json/ + template + static auto from_json(BasicJsonType && j) noexcept( + noexcept(::nlohmann::from_json(std::forward(j), detail::identity_tag {}))) + -> decltype(::nlohmann::from_json(std::forward(j), detail::identity_tag {})) + { + return ::nlohmann::from_json(std::forward(j), detail::identity_tag {}); + } + + /// @brief convert any value type to a JSON value + /// @sa https://json.nlohmann.me/api/adl_serializer/to_json/ + template + static auto to_json(BasicJsonType& j, TargetType && val) noexcept( + noexcept(::nlohmann::to_json(j, std::forward(val)))) + -> decltype(::nlohmann::to_json(j, std::forward(val)), void()) + { + ::nlohmann::to_json(j, std::forward(val)); + } +}; +} // namespace nlohmann + +// #include + + +#include // uint8_t, uint64_t +#include // tie +#include // move + +namespace nlohmann +{ + +/// @brief an internal type for a backed binary type +/// @sa https://json.nlohmann.me/api/byte_container_with_subtype/ +template +class byte_container_with_subtype : public BinaryType +{ + public: + using container_type = BinaryType; + using subtype_type = std::uint64_t; + + /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ + byte_container_with_subtype() noexcept(noexcept(container_type())) + : container_type() + {} + + /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ + byte_container_with_subtype(const container_type& b) noexcept(noexcept(container_type(b))) + : container_type(b) + {} + + /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ + byte_container_with_subtype(container_type&& b) noexcept(noexcept(container_type(std::move(b)))) + : container_type(std::move(b)) + {} + + /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ + byte_container_with_subtype(const container_type& b, subtype_type subtype_) noexcept(noexcept(container_type(b))) + : container_type(b) + , m_subtype(subtype_) + , m_has_subtype(true) + {} + + /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ + byte_container_with_subtype(container_type&& b, subtype_type subtype_) noexcept(noexcept(container_type(std::move(b)))) + : container_type(std::move(b)) + , m_subtype(subtype_) + , m_has_subtype(true) + {} + + bool operator==(const byte_container_with_subtype& rhs) const + { + return std::tie(static_cast(*this), m_subtype, m_has_subtype) == + std::tie(static_cast(rhs), rhs.m_subtype, rhs.m_has_subtype); + } + + bool operator!=(const byte_container_with_subtype& rhs) const + { + return !(rhs == *this); + } + + /// @brief sets the binary subtype + /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/set_subtype/ + void set_subtype(subtype_type subtype_) noexcept + { + m_subtype = subtype_; + m_has_subtype = true; + } + + /// @brief return the binary subtype + /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/subtype/ + constexpr subtype_type subtype() const noexcept + { + return m_has_subtype ? m_subtype : static_cast(-1); + } + + /// @brief return whether the value has a subtype + /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/has_subtype/ + constexpr bool has_subtype() const noexcept + { + return m_has_subtype; + } + + /// @brief clears the binary subtype + /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/clear_subtype/ + void clear_subtype() noexcept + { + m_subtype = 0; + m_has_subtype = false; + } + + private: + subtype_type m_subtype = 0; + bool m_has_subtype = false; +}; + +} // namespace nlohmann + +// #include + +// #include + +// #include + +// #include + + +#include // uint8_t +#include // size_t +#include // hash + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ + +// boost::hash_combine +inline std::size_t combine(std::size_t seed, std::size_t h) noexcept +{ + seed ^= h + 0x9e3779b9 + (seed << 6U) + (seed >> 2U); + return seed; +} + +/*! +@brief hash a JSON value + +The hash function tries to rely on std::hash where possible. Furthermore, the +type of the JSON value is taken into account to have different hash values for +null, 0, 0U, and false, etc. + +@tparam BasicJsonType basic_json specialization +@param j JSON value to hash +@return hash value of j +*/ +template +std::size_t hash(const BasicJsonType& j) +{ + using string_t = typename BasicJsonType::string_t; + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + + const auto type = static_cast(j.type()); + switch (j.type()) + { + case BasicJsonType::value_t::null: + case BasicJsonType::value_t::discarded: + { + return combine(type, 0); + } + + case BasicJsonType::value_t::object: + { + auto seed = combine(type, j.size()); + for (const auto& element : j.items()) + { + const auto h = std::hash {}(element.key()); + seed = combine(seed, h); + seed = combine(seed, hash(element.value())); + } + return seed; + } + + case BasicJsonType::value_t::array: + { + auto seed = combine(type, j.size()); + for (const auto& element : j) + { + seed = combine(seed, hash(element)); + } + return seed; + } + + case BasicJsonType::value_t::string: + { + const auto h = std::hash {}(j.template get_ref()); + return combine(type, h); + } + + case BasicJsonType::value_t::boolean: + { + const auto h = std::hash {}(j.template get()); + return combine(type, h); + } + + case BasicJsonType::value_t::number_integer: + { + const auto h = std::hash {}(j.template get()); + return combine(type, h); + } + + case BasicJsonType::value_t::number_unsigned: + { + const auto h = std::hash {}(j.template get()); + return combine(type, h); + } + + case BasicJsonType::value_t::number_float: + { + const auto h = std::hash {}(j.template get()); + return combine(type, h); + } + + case BasicJsonType::value_t::binary: + { + auto seed = combine(type, j.get_binary().size()); + const auto h = std::hash {}(j.get_binary().has_subtype()); + seed = combine(seed, h); + seed = combine(seed, static_cast(j.get_binary().subtype())); + for (const auto byte : j.get_binary()) + { + seed = combine(seed, std::hash {}(byte)); + } + return seed; + } + + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + return 0; // LCOV_EXCL_LINE + } +} + +} // namespace detail +} // namespace nlohmann + +// #include + + +#include // generate_n +#include // array +#include // ldexp +#include // size_t +#include // uint8_t, uint16_t, uint32_t, uint64_t +#include // snprintf +#include // memcpy +#include // back_inserter +#include // numeric_limits +#include // char_traits, string +#include // make_pair, move +#include // vector + +// #include + +// #include + + +#include // array +#include // size_t +#include // strlen +#include // begin, end, iterator_traits, random_access_iterator_tag, distance, next +#include // shared_ptr, make_shared, addressof +#include // accumulate +#include // string, char_traits +#include // enable_if, is_base_of, is_pointer, is_integral, remove_pointer +#include // pair, declval + +#ifndef JSON_NO_IO + #include // FILE * + #include // istream +#endif // JSON_NO_IO + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +/// the supported input formats +enum class input_format_t { json, cbor, msgpack, ubjson, bson }; + +//////////////////// +// input adapters // +//////////////////// + +#ifndef JSON_NO_IO +/*! +Input adapter for stdio file access. This adapter read only 1 byte and do not use any + buffer. This adapter is a very low level adapter. +*/ +class file_input_adapter +{ + public: + using char_type = char; + + JSON_HEDLEY_NON_NULL(2) + explicit file_input_adapter(std::FILE* f) noexcept + : m_file(f) + {} + + // make class move-only + file_input_adapter(const file_input_adapter&) = delete; + file_input_adapter(file_input_adapter&&) noexcept = default; + file_input_adapter& operator=(const file_input_adapter&) = delete; + file_input_adapter& operator=(file_input_adapter&&) = delete; + ~file_input_adapter() = default; + + std::char_traits::int_type get_character() noexcept + { + return std::fgetc(m_file); + } + + private: + /// the file pointer to read from + std::FILE* m_file; +}; + + +/*! +Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at +beginning of input. Does not support changing the underlying std::streambuf +in mid-input. Maintains underlying std::istream and std::streambuf to support +subsequent use of standard std::istream operations to process any input +characters following those used in parsing the JSON input. Clears the +std::istream flags; any input errors (e.g., EOF) will be detected by the first +subsequent call for input from the std::istream. +*/ +class input_stream_adapter +{ + public: + using char_type = char; + + ~input_stream_adapter() + { + // clear stream flags; we use underlying streambuf I/O, do not + // maintain ifstream flags, except eof + if (is != nullptr) + { + is->clear(is->rdstate() & std::ios::eofbit); + } + } + + explicit input_stream_adapter(std::istream& i) + : is(&i), sb(i.rdbuf()) + {} + + // delete because of pointer members + input_stream_adapter(const input_stream_adapter&) = delete; + input_stream_adapter& operator=(input_stream_adapter&) = delete; + input_stream_adapter& operator=(input_stream_adapter&&) = delete; + + input_stream_adapter(input_stream_adapter&& rhs) noexcept + : is(rhs.is), sb(rhs.sb) + { + rhs.is = nullptr; + rhs.sb = nullptr; + } + + // std::istream/std::streambuf use std::char_traits::to_int_type, to + // ensure that std::char_traits::eof() and the character 0xFF do not + // end up as the same value, e.g. 0xFFFFFFFF. + std::char_traits::int_type get_character() + { + auto res = sb->sbumpc(); + // set eof manually, as we don't use the istream interface. + if (JSON_HEDLEY_UNLIKELY(res == std::char_traits::eof())) + { + is->clear(is->rdstate() | std::ios::eofbit); + } + return res; + } + + private: + /// the associated input stream + std::istream* is = nullptr; + std::streambuf* sb = nullptr; +}; +#endif // JSON_NO_IO + +// General-purpose iterator-based adapter. It might not be as fast as +// theoretically possible for some containers, but it is extremely versatile. +template +class iterator_input_adapter +{ + public: + using char_type = typename std::iterator_traits::value_type; + + iterator_input_adapter(IteratorType first, IteratorType last) + : current(std::move(first)), end(std::move(last)) + {} + + typename std::char_traits::int_type get_character() + { + if (JSON_HEDLEY_LIKELY(current != end)) + { + auto result = std::char_traits::to_int_type(*current); + std::advance(current, 1); + return result; + } + + return std::char_traits::eof(); + } + + private: + IteratorType current; + IteratorType end; + + template + friend struct wide_string_input_helper; + + bool empty() const + { + return current == end; + } +}; + + +template +struct wide_string_input_helper; + +template +struct wide_string_input_helper +{ + // UTF-32 + static void fill_buffer(BaseInputAdapter& input, + std::array::int_type, 4>& utf8_bytes, + size_t& utf8_bytes_index, + size_t& utf8_bytes_filled) + { + utf8_bytes_index = 0; + + if (JSON_HEDLEY_UNLIKELY(input.empty())) + { + utf8_bytes[0] = std::char_traits::eof(); + utf8_bytes_filled = 1; + } + else + { + // get the current character + const auto wc = input.get_character(); + + // UTF-32 to UTF-8 encoding + if (wc < 0x80) + { + utf8_bytes[0] = static_cast::int_type>(wc); + utf8_bytes_filled = 1; + } + else if (wc <= 0x7FF) + { + utf8_bytes[0] = static_cast::int_type>(0xC0u | ((static_cast(wc) >> 6u) & 0x1Fu)); + utf8_bytes[1] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); + utf8_bytes_filled = 2; + } + else if (wc <= 0xFFFF) + { + utf8_bytes[0] = static_cast::int_type>(0xE0u | ((static_cast(wc) >> 12u) & 0x0Fu)); + utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); + utf8_bytes[2] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); + utf8_bytes_filled = 3; + } + else if (wc <= 0x10FFFF) + { + utf8_bytes[0] = static_cast::int_type>(0xF0u | ((static_cast(wc) >> 18u) & 0x07u)); + utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 12u) & 0x3Fu)); + utf8_bytes[2] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); + utf8_bytes[3] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); + utf8_bytes_filled = 4; + } + else + { + // unknown character + utf8_bytes[0] = static_cast::int_type>(wc); + utf8_bytes_filled = 1; + } + } + } +}; + +template +struct wide_string_input_helper +{ + // UTF-16 + static void fill_buffer(BaseInputAdapter& input, + std::array::int_type, 4>& utf8_bytes, + size_t& utf8_bytes_index, + size_t& utf8_bytes_filled) + { + utf8_bytes_index = 0; + + if (JSON_HEDLEY_UNLIKELY(input.empty())) + { + utf8_bytes[0] = std::char_traits::eof(); + utf8_bytes_filled = 1; + } + else + { + // get the current character + const auto wc = input.get_character(); + + // UTF-16 to UTF-8 encoding + if (wc < 0x80) + { + utf8_bytes[0] = static_cast::int_type>(wc); + utf8_bytes_filled = 1; + } + else if (wc <= 0x7FF) + { + utf8_bytes[0] = static_cast::int_type>(0xC0u | ((static_cast(wc) >> 6u))); + utf8_bytes[1] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); + utf8_bytes_filled = 2; + } + else if (0xD800 > wc || wc >= 0xE000) + { + utf8_bytes[0] = static_cast::int_type>(0xE0u | ((static_cast(wc) >> 12u))); + utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); + utf8_bytes[2] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); + utf8_bytes_filled = 3; + } + else + { + if (JSON_HEDLEY_UNLIKELY(!input.empty())) + { + const auto wc2 = static_cast(input.get_character()); + const auto charcode = 0x10000u + (((static_cast(wc) & 0x3FFu) << 10u) | (wc2 & 0x3FFu)); + utf8_bytes[0] = static_cast::int_type>(0xF0u | (charcode >> 18u)); + utf8_bytes[1] = static_cast::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu)); + utf8_bytes[2] = static_cast::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu)); + utf8_bytes[3] = static_cast::int_type>(0x80u | (charcode & 0x3Fu)); + utf8_bytes_filled = 4; + } + else + { + utf8_bytes[0] = static_cast::int_type>(wc); + utf8_bytes_filled = 1; + } + } + } + } +}; + +// Wraps another input apdater to convert wide character types into individual bytes. +template +class wide_string_input_adapter +{ + public: + using char_type = char; + + wide_string_input_adapter(BaseInputAdapter base) + : base_adapter(base) {} + + typename std::char_traits::int_type get_character() noexcept + { + // check if buffer needs to be filled + if (utf8_bytes_index == utf8_bytes_filled) + { + fill_buffer(); + + JSON_ASSERT(utf8_bytes_filled > 0); + JSON_ASSERT(utf8_bytes_index == 0); + } + + // use buffer + JSON_ASSERT(utf8_bytes_filled > 0); + JSON_ASSERT(utf8_bytes_index < utf8_bytes_filled); + return utf8_bytes[utf8_bytes_index++]; + } + + private: + BaseInputAdapter base_adapter; + + template + void fill_buffer() + { + wide_string_input_helper::fill_buffer(base_adapter, utf8_bytes, utf8_bytes_index, utf8_bytes_filled); + } + + /// a buffer for UTF-8 bytes + std::array::int_type, 4> utf8_bytes = {{0, 0, 0, 0}}; + + /// index to the utf8_codes array for the next valid byte + std::size_t utf8_bytes_index = 0; + /// number of valid bytes in the utf8_codes array + std::size_t utf8_bytes_filled = 0; +}; + + +template +struct iterator_input_adapter_factory +{ + using iterator_type = IteratorType; + using char_type = typename std::iterator_traits::value_type; + using adapter_type = iterator_input_adapter; + + static adapter_type create(IteratorType first, IteratorType last) + { + return adapter_type(std::move(first), std::move(last)); + } +}; + +template +struct is_iterator_of_multibyte +{ + using value_type = typename std::iterator_traits::value_type; + enum + { + value = sizeof(value_type) > 1 + }; +}; + +template +struct iterator_input_adapter_factory::value>> +{ + using iterator_type = IteratorType; + using char_type = typename std::iterator_traits::value_type; + using base_adapter_type = iterator_input_adapter; + using adapter_type = wide_string_input_adapter; + + static adapter_type create(IteratorType first, IteratorType last) + { + return adapter_type(base_adapter_type(std::move(first), std::move(last))); + } +}; + +// General purpose iterator-based input +template +typename iterator_input_adapter_factory::adapter_type input_adapter(IteratorType first, IteratorType last) +{ + using factory_type = iterator_input_adapter_factory; + return factory_type::create(first, last); +} + +// Convenience shorthand from container to iterator +// Enables ADL on begin(container) and end(container) +// Encloses the using declarations in namespace for not to leak them to outside scope + +namespace container_input_adapter_factory_impl +{ + +using std::begin; +using std::end; + +template +struct container_input_adapter_factory {}; + +template +struct container_input_adapter_factory< ContainerType, + void_t()), end(std::declval()))>> + { + using adapter_type = decltype(input_adapter(begin(std::declval()), end(std::declval()))); + + static adapter_type create(const ContainerType& container) +{ + return input_adapter(begin(container), end(container)); +} + }; + +} // namespace container_input_adapter_factory_impl + +template +typename container_input_adapter_factory_impl::container_input_adapter_factory::adapter_type input_adapter(const ContainerType& container) +{ + return container_input_adapter_factory_impl::container_input_adapter_factory::create(container); +} + +#ifndef JSON_NO_IO +// Special cases with fast paths +inline file_input_adapter input_adapter(std::FILE* file) +{ + return file_input_adapter(file); +} + +inline input_stream_adapter input_adapter(std::istream& stream) +{ + return input_stream_adapter(stream); +} + +inline input_stream_adapter input_adapter(std::istream&& stream) +{ + return input_stream_adapter(stream); +} +#endif // JSON_NO_IO + +using contiguous_bytes_input_adapter = decltype(input_adapter(std::declval(), std::declval())); + +// Null-delimited strings, and the like. +template < typename CharT, + typename std::enable_if < + std::is_pointer::value&& + !std::is_array::value&& + std::is_integral::type>::value&& + sizeof(typename std::remove_pointer::type) == 1, + int >::type = 0 > +contiguous_bytes_input_adapter input_adapter(CharT b) +{ + auto length = std::strlen(reinterpret_cast(b)); + const auto* ptr = reinterpret_cast(b); + return input_adapter(ptr, ptr + length); +} + +template +auto input_adapter(T (&array)[N]) -> decltype(input_adapter(array, array + N)) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) +{ + return input_adapter(array, array + N); +} + +// This class only handles inputs of input_buffer_adapter type. +// It's required so that expressions like {ptr, len} can be implicitly cast +// to the correct adapter. +class span_input_adapter +{ + public: + template < typename CharT, + typename std::enable_if < + std::is_pointer::value&& + std::is_integral::type>::value&& + sizeof(typename std::remove_pointer::type) == 1, + int >::type = 0 > + span_input_adapter(CharT b, std::size_t l) + : ia(reinterpret_cast(b), reinterpret_cast(b) + l) {} + + template::iterator_category, std::random_access_iterator_tag>::value, + int>::type = 0> + span_input_adapter(IteratorType first, IteratorType last) + : ia(input_adapter(first, last)) {} + + contiguous_bytes_input_adapter&& get() + { + return std::move(ia); // NOLINT(hicpp-move-const-arg,performance-move-const-arg) + } + + private: + contiguous_bytes_input_adapter ia; +}; +} // namespace detail +} // namespace nlohmann + +// #include + + +#include +#include // string +#include // move +#include // vector + +// #include + +// #include + + +namespace nlohmann +{ + +/*! +@brief SAX interface + +This class describes the SAX interface used by @ref nlohmann::json::sax_parse. +Each function is called in different situations while the input is parsed. The +boolean return value informs the parser whether to continue processing the +input. +*/ +template +struct json_sax +{ + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + + /*! + @brief a null value was read + @return whether parsing should proceed + */ + virtual bool null() = 0; + + /*! + @brief a boolean value was read + @param[in] val boolean value + @return whether parsing should proceed + */ + virtual bool boolean(bool val) = 0; + + /*! + @brief an integer number was read + @param[in] val integer value + @return whether parsing should proceed + */ + virtual bool number_integer(number_integer_t val) = 0; + + /*! + @brief an unsigned integer number was read + @param[in] val unsigned integer value + @return whether parsing should proceed + */ + virtual bool number_unsigned(number_unsigned_t val) = 0; + + /*! + @brief a floating-point number was read + @param[in] val floating-point value + @param[in] s raw token value + @return whether parsing should proceed + */ + virtual bool number_float(number_float_t val, const string_t& s) = 0; + + /*! + @brief a string value was read + @param[in] val string value + @return whether parsing should proceed + @note It is safe to move the passed string value. + */ + virtual bool string(string_t& val) = 0; + + /*! + @brief a binary value was read + @param[in] val binary value + @return whether parsing should proceed + @note It is safe to move the passed binary value. + */ + virtual bool binary(binary_t& val) = 0; + + /*! + @brief the beginning of an object was read + @param[in] elements number of object elements or -1 if unknown + @return whether parsing should proceed + @note binary formats may report the number of elements + */ + virtual bool start_object(std::size_t elements) = 0; + + /*! + @brief an object key was read + @param[in] val object key + @return whether parsing should proceed + @note It is safe to move the passed string. + */ + virtual bool key(string_t& val) = 0; + + /*! + @brief the end of an object was read + @return whether parsing should proceed + */ + virtual bool end_object() = 0; + + /*! + @brief the beginning of an array was read + @param[in] elements number of array elements or -1 if unknown + @return whether parsing should proceed + @note binary formats may report the number of elements + */ + virtual bool start_array(std::size_t elements) = 0; + + /*! + @brief the end of an array was read + @return whether parsing should proceed + */ + virtual bool end_array() = 0; + + /*! + @brief a parse error occurred + @param[in] position the position in the input where the error occurs + @param[in] last_token the last read token + @param[in] ex an exception object describing the error + @return whether parsing should proceed (must return false) + */ + virtual bool parse_error(std::size_t position, + const std::string& last_token, + const detail::exception& ex) = 0; + + json_sax() = default; + json_sax(const json_sax&) = default; + json_sax(json_sax&&) noexcept = default; + json_sax& operator=(const json_sax&) = default; + json_sax& operator=(json_sax&&) noexcept = default; + virtual ~json_sax() = default; +}; + + +namespace detail +{ +/*! +@brief SAX implementation to create a JSON value from SAX events + +This class implements the @ref json_sax interface and processes the SAX events +to create a JSON value which makes it basically a DOM parser. The structure or +hierarchy of the JSON value is managed by the stack `ref_stack` which contains +a pointer to the respective array or object for each recursion depth. + +After successful parsing, the value that is passed by reference to the +constructor contains the parsed value. + +@tparam BasicJsonType the JSON type +*/ +template +class json_sax_dom_parser +{ + public: + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + + /*! + @param[in,out] r reference to a JSON value that is manipulated while + parsing + @param[in] allow_exceptions_ whether parse errors yield exceptions + */ + explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true) + : root(r), allow_exceptions(allow_exceptions_) + {} + + // make class move-only + json_sax_dom_parser(const json_sax_dom_parser&) = delete; + json_sax_dom_parser(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) + json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete; + json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) + ~json_sax_dom_parser() = default; + + bool null() + { + handle_value(nullptr); + return true; + } + + bool boolean(bool val) + { + handle_value(val); + return true; + } + + bool number_integer(number_integer_t val) + { + handle_value(val); + return true; + } + + bool number_unsigned(number_unsigned_t val) + { + handle_value(val); + return true; + } + + bool number_float(number_float_t val, const string_t& /*unused*/) + { + handle_value(val); + return true; + } + + bool string(string_t& val) + { + handle_value(val); + return true; + } + + bool binary(binary_t& val) + { + handle_value(std::move(val)); + return true; + } + + bool start_object(std::size_t len) + { + ref_stack.push_back(handle_value(BasicJsonType::value_t::object)); + + if (JSON_HEDLEY_UNLIKELY(len != static_cast(-1) && len > ref_stack.back()->max_size())) + { + JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len), *ref_stack.back())); + } + + return true; + } + + bool key(string_t& val) + { + // add null at given key and store the reference for later + object_element = &(ref_stack.back()->m_value.object->operator[](val)); + return true; + } + + bool end_object() + { + ref_stack.back()->set_parents(); + ref_stack.pop_back(); + return true; + } + + bool start_array(std::size_t len) + { + ref_stack.push_back(handle_value(BasicJsonType::value_t::array)); + + if (JSON_HEDLEY_UNLIKELY(len != static_cast(-1) && len > ref_stack.back()->max_size())) + { + JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len), *ref_stack.back())); + } + + return true; + } + + bool end_array() + { + ref_stack.back()->set_parents(); + ref_stack.pop_back(); + return true; + } + + template + bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, + const Exception& ex) + { + errored = true; + static_cast(ex); + if (allow_exceptions) + { + JSON_THROW(ex); + } + return false; + } + + constexpr bool is_errored() const + { + return errored; + } + + private: + /*! + @invariant If the ref stack is empty, then the passed value will be the new + root. + @invariant If the ref stack contains a value, then it is an array or an + object to which we can add elements + */ + template + JSON_HEDLEY_RETURNS_NON_NULL + BasicJsonType* handle_value(Value&& v) + { + if (ref_stack.empty()) + { + root = BasicJsonType(std::forward(v)); + return &root; + } + + JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object()); + + if (ref_stack.back()->is_array()) + { + ref_stack.back()->m_value.array->emplace_back(std::forward(v)); + return &(ref_stack.back()->m_value.array->back()); + } + + JSON_ASSERT(ref_stack.back()->is_object()); + JSON_ASSERT(object_element); + *object_element = BasicJsonType(std::forward(v)); + return object_element; + } + + /// the parsed JSON value + BasicJsonType& root; + /// stack to model hierarchy of values + std::vector ref_stack {}; + /// helper to hold the reference for the next object element + BasicJsonType* object_element = nullptr; + /// whether a syntax error occurred + bool errored = false; + /// whether to throw exceptions in case of errors + const bool allow_exceptions = true; +}; + +template +class json_sax_dom_callback_parser +{ + public: + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + using parser_callback_t = typename BasicJsonType::parser_callback_t; + using parse_event_t = typename BasicJsonType::parse_event_t; + + json_sax_dom_callback_parser(BasicJsonType& r, + const parser_callback_t cb, + const bool allow_exceptions_ = true) + : root(r), callback(cb), allow_exceptions(allow_exceptions_) + { + keep_stack.push_back(true); + } + + // make class move-only + json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete; + json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) + json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete; + json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) + ~json_sax_dom_callback_parser() = default; + + bool null() + { + handle_value(nullptr); + return true; + } + + bool boolean(bool val) + { + handle_value(val); + return true; + } + + bool number_integer(number_integer_t val) + { + handle_value(val); + return true; + } + + bool number_unsigned(number_unsigned_t val) + { + handle_value(val); + return true; + } + + bool number_float(number_float_t val, const string_t& /*unused*/) + { + handle_value(val); + return true; + } + + bool string(string_t& val) + { + handle_value(val); + return true; + } + + bool binary(binary_t& val) + { + handle_value(std::move(val)); + return true; + } + + bool start_object(std::size_t len) + { + // check callback for object start + const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::object_start, discarded); + keep_stack.push_back(keep); + + auto val = handle_value(BasicJsonType::value_t::object, true); + ref_stack.push_back(val.second); + + // check object limit + if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != static_cast(-1) && len > ref_stack.back()->max_size())) + { + JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len), *ref_stack.back())); + } + + return true; + } + + bool key(string_t& val) + { + BasicJsonType k = BasicJsonType(val); + + // check callback for key + const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::key, k); + key_keep_stack.push_back(keep); + + // add discarded value at given key and store the reference for later + if (keep && ref_stack.back()) + { + object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded); + } + + return true; + } + + bool end_object() + { + if (ref_stack.back()) + { + if (!callback(static_cast(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back())) + { + // discard object + *ref_stack.back() = discarded; + } + else + { + ref_stack.back()->set_parents(); + } + } + + JSON_ASSERT(!ref_stack.empty()); + JSON_ASSERT(!keep_stack.empty()); + ref_stack.pop_back(); + keep_stack.pop_back(); + + if (!ref_stack.empty() && ref_stack.back() && ref_stack.back()->is_structured()) + { + // remove discarded value + for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it) + { + if (it->is_discarded()) + { + ref_stack.back()->erase(it); + break; + } + } + } + + return true; + } + + bool start_array(std::size_t len) + { + const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::array_start, discarded); + keep_stack.push_back(keep); + + auto val = handle_value(BasicJsonType::value_t::array, true); + ref_stack.push_back(val.second); + + // check array limit + if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != static_cast(-1) && len > ref_stack.back()->max_size())) + { + JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len), *ref_stack.back())); + } + + return true; + } + + bool end_array() + { + bool keep = true; + + if (ref_stack.back()) + { + keep = callback(static_cast(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back()); + if (keep) + { + ref_stack.back()->set_parents(); + } + else + { + // discard array + *ref_stack.back() = discarded; + } + } + + JSON_ASSERT(!ref_stack.empty()); + JSON_ASSERT(!keep_stack.empty()); + ref_stack.pop_back(); + keep_stack.pop_back(); + + // remove discarded value + if (!keep && !ref_stack.empty() && ref_stack.back()->is_array()) + { + ref_stack.back()->m_value.array->pop_back(); + } + + return true; + } + + template + bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, + const Exception& ex) + { + errored = true; + static_cast(ex); + if (allow_exceptions) + { + JSON_THROW(ex); + } + return false; + } + + constexpr bool is_errored() const + { + return errored; + } + + private: + /*! + @param[in] v value to add to the JSON value we build during parsing + @param[in] skip_callback whether we should skip calling the callback + function; this is required after start_array() and + start_object() SAX events, because otherwise we would call the + callback function with an empty array or object, respectively. + + @invariant If the ref stack is empty, then the passed value will be the new + root. + @invariant If the ref stack contains a value, then it is an array or an + object to which we can add elements + + @return pair of boolean (whether value should be kept) and pointer (to the + passed value in the ref_stack hierarchy; nullptr if not kept) + */ + template + std::pair handle_value(Value&& v, const bool skip_callback = false) + { + JSON_ASSERT(!keep_stack.empty()); + + // do not handle this value if we know it would be added to a discarded + // container + if (!keep_stack.back()) + { + return {false, nullptr}; + } + + // create value + auto value = BasicJsonType(std::forward(v)); + + // check callback + const bool keep = skip_callback || callback(static_cast(ref_stack.size()), parse_event_t::value, value); + + // do not handle this value if we just learnt it shall be discarded + if (!keep) + { + return {false, nullptr}; + } + + if (ref_stack.empty()) + { + root = std::move(value); + return {true, &root}; + } + + // skip this value if we already decided to skip the parent + // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360) + if (!ref_stack.back()) + { + return {false, nullptr}; + } + + // we now only expect arrays and objects + JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object()); + + // array + if (ref_stack.back()->is_array()) + { + ref_stack.back()->m_value.array->emplace_back(std::move(value)); + return {true, &(ref_stack.back()->m_value.array->back())}; + } + + // object + JSON_ASSERT(ref_stack.back()->is_object()); + // check if we should store an element for the current key + JSON_ASSERT(!key_keep_stack.empty()); + const bool store_element = key_keep_stack.back(); + key_keep_stack.pop_back(); + + if (!store_element) + { + return {false, nullptr}; + } + + JSON_ASSERT(object_element); + *object_element = std::move(value); + return {true, object_element}; + } + + /// the parsed JSON value + BasicJsonType& root; + /// stack to model hierarchy of values + std::vector ref_stack {}; + /// stack to manage which values to keep + std::vector keep_stack {}; + /// stack to manage which object keys to keep + std::vector key_keep_stack {}; + /// helper to hold the reference for the next object element + BasicJsonType* object_element = nullptr; + /// whether a syntax error occurred + bool errored = false; + /// callback function + const parser_callback_t callback = nullptr; + /// whether to throw exceptions in case of errors + const bool allow_exceptions = true; + /// a discarded value for the callback + BasicJsonType discarded = BasicJsonType::value_t::discarded; +}; + +template +class json_sax_acceptor +{ + public: + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + + bool null() + { + return true; + } + + bool boolean(bool /*unused*/) + { + return true; + } + + bool number_integer(number_integer_t /*unused*/) + { + return true; + } + + bool number_unsigned(number_unsigned_t /*unused*/) + { + return true; + } + + bool number_float(number_float_t /*unused*/, const string_t& /*unused*/) + { + return true; + } + + bool string(string_t& /*unused*/) + { + return true; + } + + bool binary(binary_t& /*unused*/) + { + return true; + } + + bool start_object(std::size_t /*unused*/ = static_cast(-1)) + { + return true; + } + + bool key(string_t& /*unused*/) + { + return true; + } + + bool end_object() + { + return true; + } + + bool start_array(std::size_t /*unused*/ = static_cast(-1)) + { + return true; + } + + bool end_array() + { + return true; + } + + bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/) + { + return false; + } +}; +} // namespace detail + +} // namespace nlohmann + +// #include + + +#include // array +#include // localeconv +#include // size_t +#include // snprintf +#include // strtof, strtod, strtold, strtoll, strtoull +#include // initializer_list +#include // char_traits, string +#include // move +#include // vector + +// #include + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +/////////// +// lexer // +/////////// + +template +class lexer_base +{ + public: + /// token types for the parser + enum class token_type + { + uninitialized, ///< indicating the scanner is uninitialized + literal_true, ///< the `true` literal + literal_false, ///< the `false` literal + literal_null, ///< the `null` literal + value_string, ///< a string -- use get_string() for actual value + value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value + value_integer, ///< a signed integer -- use get_number_integer() for actual value + value_float, ///< an floating point number -- use get_number_float() for actual value + begin_array, ///< the character for array begin `[` + begin_object, ///< the character for object begin `{` + end_array, ///< the character for array end `]` + end_object, ///< the character for object end `}` + name_separator, ///< the name separator `:` + value_separator, ///< the value separator `,` + parse_error, ///< indicating a parse error + end_of_input, ///< indicating the end of the input buffer + literal_or_value ///< a literal or the begin of a value (only for diagnostics) + }; + + /// return name of values of type token_type (only used for errors) + JSON_HEDLEY_RETURNS_NON_NULL + JSON_HEDLEY_CONST + static const char* token_type_name(const token_type t) noexcept + { + switch (t) + { + case token_type::uninitialized: + return ""; + case token_type::literal_true: + return "true literal"; + case token_type::literal_false: + return "false literal"; + case token_type::literal_null: + return "null literal"; + case token_type::value_string: + return "string literal"; + case token_type::value_unsigned: + case token_type::value_integer: + case token_type::value_float: + return "number literal"; + case token_type::begin_array: + return "'['"; + case token_type::begin_object: + return "'{'"; + case token_type::end_array: + return "']'"; + case token_type::end_object: + return "'}'"; + case token_type::name_separator: + return "':'"; + case token_type::value_separator: + return "','"; + case token_type::parse_error: + return ""; + case token_type::end_of_input: + return "end of input"; + case token_type::literal_or_value: + return "'[', '{', or a literal"; + // LCOV_EXCL_START + default: // catch non-enum values + return "unknown token"; + // LCOV_EXCL_STOP + } + } +}; +/*! +@brief lexical analysis + +This class organizes the lexical analysis during JSON deserialization. +*/ +template +class lexer : public lexer_base +{ + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using char_type = typename InputAdapterType::char_type; + using char_int_type = typename std::char_traits::int_type; + + public: + using token_type = typename lexer_base::token_type; + + explicit lexer(InputAdapterType&& adapter, bool ignore_comments_ = false) noexcept + : ia(std::move(adapter)) + , ignore_comments(ignore_comments_) + , decimal_point_char(static_cast(get_decimal_point())) + {} + + // delete because of pointer members + lexer(const lexer&) = delete; + lexer(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) + lexer& operator=(lexer&) = delete; + lexer& operator=(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) + ~lexer() = default; + + private: + ///////////////////// + // locales + ///////////////////// + + /// return the locale-dependent decimal point + JSON_HEDLEY_PURE + static char get_decimal_point() noexcept + { + const auto* loc = localeconv(); + JSON_ASSERT(loc != nullptr); + return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point); + } + + ///////////////////// + // scan functions + ///////////////////// + + /*! + @brief get codepoint from 4 hex characters following `\u` + + For input "\u c1 c2 c3 c4" the codepoint is: + (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4 + = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0) + + Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f' + must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The + conversion is done by subtracting the offset (0x30, 0x37, and 0x57) + between the ASCII value of the character and the desired integer value. + + @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or + non-hex character) + */ + int get_codepoint() + { + // this function only makes sense after reading `\u` + JSON_ASSERT(current == 'u'); + int codepoint = 0; + + const auto factors = { 12u, 8u, 4u, 0u }; + for (const auto factor : factors) + { + get(); + + if (current >= '0' && current <= '9') + { + codepoint += static_cast((static_cast(current) - 0x30u) << factor); + } + else if (current >= 'A' && current <= 'F') + { + codepoint += static_cast((static_cast(current) - 0x37u) << factor); + } + else if (current >= 'a' && current <= 'f') + { + codepoint += static_cast((static_cast(current) - 0x57u) << factor); + } + else + { + return -1; + } + } + + JSON_ASSERT(0x0000 <= codepoint && codepoint <= 0xFFFF); + return codepoint; + } + + /*! + @brief check if the next byte(s) are inside a given range + + Adds the current byte and, for each passed range, reads a new byte and + checks if it is inside the range. If a violation was detected, set up an + error message and return false. Otherwise, return true. + + @param[in] ranges list of integers; interpreted as list of pairs of + inclusive lower and upper bound, respectively + + @pre The passed list @a ranges must have 2, 4, or 6 elements; that is, + 1, 2, or 3 pairs. This precondition is enforced by an assertion. + + @return true if and only if no range violation was detected + */ + bool next_byte_in_range(std::initializer_list ranges) + { + JSON_ASSERT(ranges.size() == 2 || ranges.size() == 4 || ranges.size() == 6); + add(current); + + for (auto range = ranges.begin(); range != ranges.end(); ++range) + { + get(); + if (JSON_HEDLEY_LIKELY(*range <= current && current <= *(++range))) + { + add(current); + } + else + { + error_message = "invalid string: ill-formed UTF-8 byte"; + return false; + } + } + + return true; + } + + /*! + @brief scan a string literal + + This function scans a string according to Sect. 7 of RFC 8259. While + scanning, bytes are escaped and copied into buffer token_buffer. Then the + function returns successfully, token_buffer is *not* null-terminated (as it + may contain \0 bytes), and token_buffer.size() is the number of bytes in the + string. + + @return token_type::value_string if string could be successfully scanned, + token_type::parse_error otherwise + + @note In case of errors, variable error_message contains a textual + description. + */ + token_type scan_string() + { + // reset token_buffer (ignore opening quote) + reset(); + + // we entered the function by reading an open quote + JSON_ASSERT(current == '\"'); + + while (true) + { + // get next character + switch (get()) + { + // end of file while parsing string + case std::char_traits::eof(): + { + error_message = "invalid string: missing closing quote"; + return token_type::parse_error; + } + + // closing quote + case '\"': + { + return token_type::value_string; + } + + // escapes + case '\\': + { + switch (get()) + { + // quotation mark + case '\"': + add('\"'); + break; + // reverse solidus + case '\\': + add('\\'); + break; + // solidus + case '/': + add('/'); + break; + // backspace + case 'b': + add('\b'); + break; + // form feed + case 'f': + add('\f'); + break; + // line feed + case 'n': + add('\n'); + break; + // carriage return + case 'r': + add('\r'); + break; + // tab + case 't': + add('\t'); + break; + + // unicode escapes + case 'u': + { + const int codepoint1 = get_codepoint(); + int codepoint = codepoint1; // start with codepoint1 + + if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1)) + { + error_message = "invalid string: '\\u' must be followed by 4 hex digits"; + return token_type::parse_error; + } + + // check if code point is a high surrogate + if (0xD800 <= codepoint1 && codepoint1 <= 0xDBFF) + { + // expect next \uxxxx entry + if (JSON_HEDLEY_LIKELY(get() == '\\' && get() == 'u')) + { + const int codepoint2 = get_codepoint(); + + if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1)) + { + error_message = "invalid string: '\\u' must be followed by 4 hex digits"; + return token_type::parse_error; + } + + // check if codepoint2 is a low surrogate + if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 && codepoint2 <= 0xDFFF)) + { + // overwrite codepoint + codepoint = static_cast( + // high surrogate occupies the most significant 22 bits + (static_cast(codepoint1) << 10u) + // low surrogate occupies the least significant 15 bits + + static_cast(codepoint2) + // there is still the 0xD800, 0xDC00 and 0x10000 noise + // in the result, so we have to subtract with: + // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00 + - 0x35FDC00u); + } + else + { + error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF"; + return token_type::parse_error; + } + } + else + { + error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF"; + return token_type::parse_error; + } + } + else + { + if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 && codepoint1 <= 0xDFFF)) + { + error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF"; + return token_type::parse_error; + } + } + + // result of the above calculation yields a proper codepoint + JSON_ASSERT(0x00 <= codepoint && codepoint <= 0x10FFFF); + + // translate codepoint into bytes + if (codepoint < 0x80) + { + // 1-byte characters: 0xxxxxxx (ASCII) + add(static_cast(codepoint)); + } + else if (codepoint <= 0x7FF) + { + // 2-byte characters: 110xxxxx 10xxxxxx + add(static_cast(0xC0u | (static_cast(codepoint) >> 6u))); + add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); + } + else if (codepoint <= 0xFFFF) + { + // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx + add(static_cast(0xE0u | (static_cast(codepoint) >> 12u))); + add(static_cast(0x80u | ((static_cast(codepoint) >> 6u) & 0x3Fu))); + add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); + } + else + { + // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + add(static_cast(0xF0u | (static_cast(codepoint) >> 18u))); + add(static_cast(0x80u | ((static_cast(codepoint) >> 12u) & 0x3Fu))); + add(static_cast(0x80u | ((static_cast(codepoint) >> 6u) & 0x3Fu))); + add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); + } + + break; + } + + // other characters after escape + default: + error_message = "invalid string: forbidden character after backslash"; + return token_type::parse_error; + } + + break; + } + + // invalid control characters + case 0x00: + { + error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000"; + return token_type::parse_error; + } + + case 0x01: + { + error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001"; + return token_type::parse_error; + } + + case 0x02: + { + error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002"; + return token_type::parse_error; + } + + case 0x03: + { + error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003"; + return token_type::parse_error; + } + + case 0x04: + { + error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004"; + return token_type::parse_error; + } + + case 0x05: + { + error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005"; + return token_type::parse_error; + } + + case 0x06: + { + error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006"; + return token_type::parse_error; + } + + case 0x07: + { + error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007"; + return token_type::parse_error; + } + + case 0x08: + { + error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b"; + return token_type::parse_error; + } + + case 0x09: + { + error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t"; + return token_type::parse_error; + } + + case 0x0A: + { + error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n"; + return token_type::parse_error; + } + + case 0x0B: + { + error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B"; + return token_type::parse_error; + } + + case 0x0C: + { + error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f"; + return token_type::parse_error; + } + + case 0x0D: + { + error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r"; + return token_type::parse_error; + } + + case 0x0E: + { + error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E"; + return token_type::parse_error; + } + + case 0x0F: + { + error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F"; + return token_type::parse_error; + } + + case 0x10: + { + error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010"; + return token_type::parse_error; + } + + case 0x11: + { + error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011"; + return token_type::parse_error; + } + + case 0x12: + { + error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012"; + return token_type::parse_error; + } + + case 0x13: + { + error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013"; + return token_type::parse_error; + } + + case 0x14: + { + error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014"; + return token_type::parse_error; + } + + case 0x15: + { + error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015"; + return token_type::parse_error; + } + + case 0x16: + { + error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016"; + return token_type::parse_error; + } + + case 0x17: + { + error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017"; + return token_type::parse_error; + } + + case 0x18: + { + error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018"; + return token_type::parse_error; + } + + case 0x19: + { + error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019"; + return token_type::parse_error; + } + + case 0x1A: + { + error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A"; + return token_type::parse_error; + } + + case 0x1B: + { + error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B"; + return token_type::parse_error; + } + + case 0x1C: + { + error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C"; + return token_type::parse_error; + } + + case 0x1D: + { + error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D"; + return token_type::parse_error; + } + + case 0x1E: + { + error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E"; + return token_type::parse_error; + } + + case 0x1F: + { + error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F"; + return token_type::parse_error; + } + + // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace)) + case 0x20: + case 0x21: + case 0x23: + case 0x24: + case 0x25: + case 0x26: + case 0x27: + case 0x28: + case 0x29: + case 0x2A: + case 0x2B: + case 0x2C: + case 0x2D: + case 0x2E: + case 0x2F: + case 0x30: + case 0x31: + case 0x32: + case 0x33: + case 0x34: + case 0x35: + case 0x36: + case 0x37: + case 0x38: + case 0x39: + case 0x3A: + case 0x3B: + case 0x3C: + case 0x3D: + case 0x3E: + case 0x3F: + case 0x40: + case 0x41: + case 0x42: + case 0x43: + case 0x44: + case 0x45: + case 0x46: + case 0x47: + case 0x48: + case 0x49: + case 0x4A: + case 0x4B: + case 0x4C: + case 0x4D: + case 0x4E: + case 0x4F: + case 0x50: + case 0x51: + case 0x52: + case 0x53: + case 0x54: + case 0x55: + case 0x56: + case 0x57: + case 0x58: + case 0x59: + case 0x5A: + case 0x5B: + case 0x5D: + case 0x5E: + case 0x5F: + case 0x60: + case 0x61: + case 0x62: + case 0x63: + case 0x64: + case 0x65: + case 0x66: + case 0x67: + case 0x68: + case 0x69: + case 0x6A: + case 0x6B: + case 0x6C: + case 0x6D: + case 0x6E: + case 0x6F: + case 0x70: + case 0x71: + case 0x72: + case 0x73: + case 0x74: + case 0x75: + case 0x76: + case 0x77: + case 0x78: + case 0x79: + case 0x7A: + case 0x7B: + case 0x7C: + case 0x7D: + case 0x7E: + case 0x7F: + { + add(current); + break; + } + + // U+0080..U+07FF: bytes C2..DF 80..BF + case 0xC2: + case 0xC3: + case 0xC4: + case 0xC5: + case 0xC6: + case 0xC7: + case 0xC8: + case 0xC9: + case 0xCA: + case 0xCB: + case 0xCC: + case 0xCD: + case 0xCE: + case 0xCF: + case 0xD0: + case 0xD1: + case 0xD2: + case 0xD3: + case 0xD4: + case 0xD5: + case 0xD6: + case 0xD7: + case 0xD8: + case 0xD9: + case 0xDA: + case 0xDB: + case 0xDC: + case 0xDD: + case 0xDE: + case 0xDF: + { + if (JSON_HEDLEY_UNLIKELY(!next_byte_in_range({0x80, 0xBF}))) + { + return token_type::parse_error; + } + break; + } + + // U+0800..U+0FFF: bytes E0 A0..BF 80..BF + case 0xE0: + { + if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF})))) + { + return token_type::parse_error; + } + break; + } + + // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF + // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF + case 0xE1: + case 0xE2: + case 0xE3: + case 0xE4: + case 0xE5: + case 0xE6: + case 0xE7: + case 0xE8: + case 0xE9: + case 0xEA: + case 0xEB: + case 0xEC: + case 0xEE: + case 0xEF: + { + if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF})))) + { + return token_type::parse_error; + } + break; + } + + // U+D000..U+D7FF: bytes ED 80..9F 80..BF + case 0xED: + { + if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x9F, 0x80, 0xBF})))) + { + return token_type::parse_error; + } + break; + } + + // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF + case 0xF0: + { + if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) + { + return token_type::parse_error; + } + break; + } + + // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF + case 0xF1: + case 0xF2: + case 0xF3: + { + if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) + { + return token_type::parse_error; + } + break; + } + + // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF + case 0xF4: + { + if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF})))) + { + return token_type::parse_error; + } + break; + } + + // remaining bytes (80..C1 and F5..FF) are ill-formed + default: + { + error_message = "invalid string: ill-formed UTF-8 byte"; + return token_type::parse_error; + } + } + } + } + + /*! + * @brief scan a comment + * @return whether comment could be scanned successfully + */ + bool scan_comment() + { + switch (get()) + { + // single-line comments skip input until a newline or EOF is read + case '/': + { + while (true) + { + switch (get()) + { + case '\n': + case '\r': + case std::char_traits::eof(): + case '\0': + return true; + + default: + break; + } + } + } + + // multi-line comments skip input until */ is read + case '*': + { + while (true) + { + switch (get()) + { + case std::char_traits::eof(): + case '\0': + { + error_message = "invalid comment; missing closing '*/'"; + return false; + } + + case '*': + { + switch (get()) + { + case '/': + return true; + + default: + { + unget(); + continue; + } + } + } + + default: + continue; + } + } + } + + // unexpected character after reading '/' + default: + { + error_message = "invalid comment; expecting '/' or '*' after '/'"; + return false; + } + } + } + + JSON_HEDLEY_NON_NULL(2) + static void strtof(float& f, const char* str, char** endptr) noexcept + { + f = std::strtof(str, endptr); + } + + JSON_HEDLEY_NON_NULL(2) + static void strtof(double& f, const char* str, char** endptr) noexcept + { + f = std::strtod(str, endptr); + } + + JSON_HEDLEY_NON_NULL(2) + static void strtof(long double& f, const char* str, char** endptr) noexcept + { + f = std::strtold(str, endptr); + } + + /*! + @brief scan a number literal + + This function scans a string according to Sect. 6 of RFC 8259. + + The function is realized with a deterministic finite state machine derived + from the grammar described in RFC 8259. Starting in state "init", the + input is read and used to determined the next state. Only state "done" + accepts the number. State "error" is a trap state to model errors. In the + table below, "anything" means any character but the ones listed before. + + state | 0 | 1-9 | e E | + | - | . | anything + ---------|----------|----------|----------|---------|---------|----------|----------- + init | zero | any1 | [error] | [error] | minus | [error] | [error] + minus | zero | any1 | [error] | [error] | [error] | [error] | [error] + zero | done | done | exponent | done | done | decimal1 | done + any1 | any1 | any1 | exponent | done | done | decimal1 | done + decimal1 | decimal2 | decimal2 | [error] | [error] | [error] | [error] | [error] + decimal2 | decimal2 | decimal2 | exponent | done | done | done | done + exponent | any2 | any2 | [error] | sign | sign | [error] | [error] + sign | any2 | any2 | [error] | [error] | [error] | [error] | [error] + any2 | any2 | any2 | done | done | done | done | done + + The state machine is realized with one label per state (prefixed with + "scan_number_") and `goto` statements between them. The state machine + contains cycles, but any cycle can be left when EOF is read. Therefore, + the function is guaranteed to terminate. + + During scanning, the read bytes are stored in token_buffer. This string is + then converted to a signed integer, an unsigned integer, or a + floating-point number. + + @return token_type::value_unsigned, token_type::value_integer, or + token_type::value_float if number could be successfully scanned, + token_type::parse_error otherwise + + @note The scanner is independent of the current locale. Internally, the + locale's decimal point is used instead of `.` to work with the + locale-dependent converters. + */ + token_type scan_number() // lgtm [cpp/use-of-goto] + { + // reset token_buffer to store the number's bytes + reset(); + + // the type of the parsed number; initially set to unsigned; will be + // changed if minus sign, decimal point or exponent is read + token_type number_type = token_type::value_unsigned; + + // state (init): we just found out we need to scan a number + switch (current) + { + case '-': + { + add(current); + goto scan_number_minus; + } + + case '0': + { + add(current); + goto scan_number_zero; + } + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any1; + } + + // all other characters are rejected outside scan_number() + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + } + +scan_number_minus: + // state: we just parsed a leading minus sign + number_type = token_type::value_integer; + switch (get()) + { + case '0': + { + add(current); + goto scan_number_zero; + } + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any1; + } + + default: + { + error_message = "invalid number; expected digit after '-'"; + return token_type::parse_error; + } + } + +scan_number_zero: + // state: we just parse a zero (maybe with a leading minus sign) + switch (get()) + { + case '.': + { + add(decimal_point_char); + goto scan_number_decimal1; + } + + case 'e': + case 'E': + { + add(current); + goto scan_number_exponent; + } + + default: + goto scan_number_done; + } + +scan_number_any1: + // state: we just parsed a number 0-9 (maybe with a leading minus sign) + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any1; + } + + case '.': + { + add(decimal_point_char); + goto scan_number_decimal1; + } + + case 'e': + case 'E': + { + add(current); + goto scan_number_exponent; + } + + default: + goto scan_number_done; + } + +scan_number_decimal1: + // state: we just parsed a decimal point + number_type = token_type::value_float; + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_decimal2; + } + + default: + { + error_message = "invalid number; expected digit after '.'"; + return token_type::parse_error; + } + } + +scan_number_decimal2: + // we just parsed at least one number after a decimal point + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_decimal2; + } + + case 'e': + case 'E': + { + add(current); + goto scan_number_exponent; + } + + default: + goto scan_number_done; + } + +scan_number_exponent: + // we just parsed an exponent + number_type = token_type::value_float; + switch (get()) + { + case '+': + case '-': + { + add(current); + goto scan_number_sign; + } + + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any2; + } + + default: + { + error_message = + "invalid number; expected '+', '-', or digit after exponent"; + return token_type::parse_error; + } + } + +scan_number_sign: + // we just parsed an exponent sign + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any2; + } + + default: + { + error_message = "invalid number; expected digit after exponent sign"; + return token_type::parse_error; + } + } + +scan_number_any2: + // we just parsed a number after the exponent or exponent sign + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any2; + } + + default: + goto scan_number_done; + } + +scan_number_done: + // unget the character after the number (we only read it to know that + // we are done scanning a number) + unget(); + + char* endptr = nullptr; // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) + errno = 0; + + // try to parse integers first and fall back to floats + if (number_type == token_type::value_unsigned) + { + const auto x = std::strtoull(token_buffer.data(), &endptr, 10); + + // we checked the number format before + JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); + + if (errno == 0) + { + value_unsigned = static_cast(x); + if (value_unsigned == x) + { + return token_type::value_unsigned; + } + } + } + else if (number_type == token_type::value_integer) + { + const auto x = std::strtoll(token_buffer.data(), &endptr, 10); + + // we checked the number format before + JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); + + if (errno == 0) + { + value_integer = static_cast(x); + if (value_integer == x) + { + return token_type::value_integer; + } + } + } + + // this code is reached if we parse a floating-point number or if an + // integer conversion above failed + strtof(value_float, token_buffer.data(), &endptr); + + // we checked the number format before + JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); + + return token_type::value_float; + } + + /*! + @param[in] literal_text the literal text to expect + @param[in] length the length of the passed literal text + @param[in] return_type the token type to return on success + */ + JSON_HEDLEY_NON_NULL(2) + token_type scan_literal(const char_type* literal_text, const std::size_t length, + token_type return_type) + { + JSON_ASSERT(std::char_traits::to_char_type(current) == literal_text[0]); + for (std::size_t i = 1; i < length; ++i) + { + if (JSON_HEDLEY_UNLIKELY(std::char_traits::to_char_type(get()) != literal_text[i])) + { + error_message = "invalid literal"; + return token_type::parse_error; + } + } + return return_type; + } + + ///////////////////// + // input management + ///////////////////// + + /// reset token_buffer; current character is beginning of token + void reset() noexcept + { + token_buffer.clear(); + token_string.clear(); + token_string.push_back(std::char_traits::to_char_type(current)); + } + + /* + @brief get next character from the input + + This function provides the interface to the used input adapter. It does + not throw in case the input reached EOF, but returns a + `std::char_traits::eof()` in that case. Stores the scanned characters + for use in error messages. + + @return character read from the input + */ + char_int_type get() + { + ++position.chars_read_total; + ++position.chars_read_current_line; + + if (next_unget) + { + // just reset the next_unget variable and work with current + next_unget = false; + } + else + { + current = ia.get_character(); + } + + if (JSON_HEDLEY_LIKELY(current != std::char_traits::eof())) + { + token_string.push_back(std::char_traits::to_char_type(current)); + } + + if (current == '\n') + { + ++position.lines_read; + position.chars_read_current_line = 0; + } + + return current; + } + + /*! + @brief unget current character (read it again on next get) + + We implement unget by setting variable next_unget to true. The input is not + changed - we just simulate ungetting by modifying chars_read_total, + chars_read_current_line, and token_string. The next call to get() will + behave as if the unget character is read again. + */ + void unget() + { + next_unget = true; + + --position.chars_read_total; + + // in case we "unget" a newline, we have to also decrement the lines_read + if (position.chars_read_current_line == 0) + { + if (position.lines_read > 0) + { + --position.lines_read; + } + } + else + { + --position.chars_read_current_line; + } + + if (JSON_HEDLEY_LIKELY(current != std::char_traits::eof())) + { + JSON_ASSERT(!token_string.empty()); + token_string.pop_back(); + } + } + + /// add a character to token_buffer + void add(char_int_type c) + { + token_buffer.push_back(static_cast(c)); + } + + public: + ///////////////////// + // value getters + ///////////////////// + + /// return integer value + constexpr number_integer_t get_number_integer() const noexcept + { + return value_integer; + } + + /// return unsigned integer value + constexpr number_unsigned_t get_number_unsigned() const noexcept + { + return value_unsigned; + } + + /// return floating-point value + constexpr number_float_t get_number_float() const noexcept + { + return value_float; + } + + /// return current string value (implicitly resets the token; useful only once) + string_t& get_string() + { + return token_buffer; + } + + ///////////////////// + // diagnostics + ///////////////////// + + /// return position of last read token + constexpr position_t get_position() const noexcept + { + return position; + } + + /// return the last read token (for errors only). Will never contain EOF + /// (an arbitrary value that is not a valid char value, often -1), because + /// 255 may legitimately occur. May contain NUL, which should be escaped. + std::string get_token_string() const + { + // escape control characters + std::string result; + for (const auto c : token_string) + { + if (static_cast(c) <= '\x1F') + { + // escape control characters + std::array cs{{}}; + static_cast((std::snprintf)(cs.data(), cs.size(), "", static_cast(c))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) + result += cs.data(); + } + else + { + // add character as is + result.push_back(static_cast(c)); + } + } + + return result; + } + + /// return syntax error message + JSON_HEDLEY_RETURNS_NON_NULL + constexpr const char* get_error_message() const noexcept + { + return error_message; + } + + ///////////////////// + // actual scanner + ///////////////////// + + /*! + @brief skip the UTF-8 byte order mark + @return true iff there is no BOM or the correct BOM has been skipped + */ + bool skip_bom() + { + if (get() == 0xEF) + { + // check if we completely parse the BOM + return get() == 0xBB && get() == 0xBF; + } + + // the first character is not the beginning of the BOM; unget it to + // process is later + unget(); + return true; + } + + void skip_whitespace() + { + do + { + get(); + } + while (current == ' ' || current == '\t' || current == '\n' || current == '\r'); + } + + token_type scan() + { + // initially, skip the BOM + if (position.chars_read_total == 0 && !skip_bom()) + { + error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given"; + return token_type::parse_error; + } + + // read next character and ignore whitespace + skip_whitespace(); + + // ignore comments + while (ignore_comments && current == '/') + { + if (!scan_comment()) + { + return token_type::parse_error; + } + + // skip following whitespace + skip_whitespace(); + } + + switch (current) + { + // structural characters + case '[': + return token_type::begin_array; + case ']': + return token_type::end_array; + case '{': + return token_type::begin_object; + case '}': + return token_type::end_object; + case ':': + return token_type::name_separator; + case ',': + return token_type::value_separator; + + // literals + case 't': + { + std::array true_literal = {{static_cast('t'), static_cast('r'), static_cast('u'), static_cast('e')}}; + return scan_literal(true_literal.data(), true_literal.size(), token_type::literal_true); + } + case 'f': + { + std::array false_literal = {{static_cast('f'), static_cast('a'), static_cast('l'), static_cast('s'), static_cast('e')}}; + return scan_literal(false_literal.data(), false_literal.size(), token_type::literal_false); + } + case 'n': + { + std::array null_literal = {{static_cast('n'), static_cast('u'), static_cast('l'), static_cast('l')}}; + return scan_literal(null_literal.data(), null_literal.size(), token_type::literal_null); + } + + // string + case '\"': + return scan_string(); + + // number + case '-': + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + return scan_number(); + + // end of input (the null byte is needed when parsing from + // string literals) + case '\0': + case std::char_traits::eof(): + return token_type::end_of_input; + + // error + default: + error_message = "invalid literal"; + return token_type::parse_error; + } + } + + private: + /// input adapter + InputAdapterType ia; + + /// whether comments should be ignored (true) or signaled as errors (false) + const bool ignore_comments = false; + + /// the current character + char_int_type current = std::char_traits::eof(); + + /// whether the next get() call should just return current + bool next_unget = false; + + /// the start position of the current token + position_t position {}; + + /// raw input token string (for error messages) + std::vector token_string {}; + + /// buffer for variable-length tokens (numbers, strings) + string_t token_buffer {}; + + /// a description of occurred lexer errors + const char* error_message = ""; + + // number values + number_integer_t value_integer = 0; + number_unsigned_t value_unsigned = 0; + number_float_t value_float = 0; + + /// the decimal point + const char_int_type decimal_point_char = '.'; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + + +#include // size_t +#include // declval +#include // string + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template +using null_function_t = decltype(std::declval().null()); + +template +using boolean_function_t = + decltype(std::declval().boolean(std::declval())); + +template +using number_integer_function_t = + decltype(std::declval().number_integer(std::declval())); + +template +using number_unsigned_function_t = + decltype(std::declval().number_unsigned(std::declval())); + +template +using number_float_function_t = decltype(std::declval().number_float( + std::declval(), std::declval())); + +template +using string_function_t = + decltype(std::declval().string(std::declval())); + +template +using binary_function_t = + decltype(std::declval().binary(std::declval())); + +template +using start_object_function_t = + decltype(std::declval().start_object(std::declval())); + +template +using key_function_t = + decltype(std::declval().key(std::declval())); + +template +using end_object_function_t = decltype(std::declval().end_object()); + +template +using start_array_function_t = + decltype(std::declval().start_array(std::declval())); + +template +using end_array_function_t = decltype(std::declval().end_array()); + +template +using parse_error_function_t = decltype(std::declval().parse_error( + std::declval(), std::declval(), + std::declval())); + +template +struct is_sax +{ + private: + static_assert(is_basic_json::value, + "BasicJsonType must be of type basic_json<...>"); + + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + using exception_t = typename BasicJsonType::exception; + + public: + static constexpr bool value = + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value; +}; + +template +struct is_sax_static_asserts +{ + private: + static_assert(is_basic_json::value, + "BasicJsonType must be of type basic_json<...>"); + + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + using exception_t = typename BasicJsonType::exception; + + public: + static_assert(is_detected_exact::value, + "Missing/invalid function: bool null()"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool boolean(bool)"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool boolean(bool)"); + static_assert( + is_detected_exact::value, + "Missing/invalid function: bool number_integer(number_integer_t)"); + static_assert( + is_detected_exact::value, + "Missing/invalid function: bool number_unsigned(number_unsigned_t)"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool number_float(number_float_t, const string_t&)"); + static_assert( + is_detected_exact::value, + "Missing/invalid function: bool string(string_t&)"); + static_assert( + is_detected_exact::value, + "Missing/invalid function: bool binary(binary_t&)"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool start_object(std::size_t)"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool key(string_t&)"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool end_object()"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool start_array(std::size_t)"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool end_array()"); + static_assert( + is_detected_exact::value, + "Missing/invalid function: bool parse_error(std::size_t, const " + "std::string&, const exception&)"); +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ + +/// how to treat CBOR tags +enum class cbor_tag_handler_t +{ + error, ///< throw a parse_error exception in case of a tag + ignore, ///< ignore tags + store ///< store tags as binary type +}; + +/*! +@brief determine system byte order + +@return true if and only if system's byte order is little endian + +@note from https://stackoverflow.com/a/1001328/266378 +*/ +static inline bool little_endianness(int num = 1) noexcept +{ + return *reinterpret_cast(&num) == 1; +} + + +/////////////////// +// binary reader // +/////////////////// + +/*! +@brief deserialization of CBOR, MessagePack, and UBJSON values +*/ +template> +class binary_reader +{ + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + using json_sax_t = SAX; + using char_type = typename InputAdapterType::char_type; + using char_int_type = typename std::char_traits::int_type; + + public: + /*! + @brief create a binary reader + + @param[in] adapter input adapter to read from + */ + explicit binary_reader(InputAdapterType&& adapter) noexcept : ia(std::move(adapter)) + { + (void)detail::is_sax_static_asserts {}; + } + + // make class move-only + binary_reader(const binary_reader&) = delete; + binary_reader(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) + binary_reader& operator=(const binary_reader&) = delete; + binary_reader& operator=(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) + ~binary_reader() = default; + + /*! + @param[in] format the binary format to parse + @param[in] sax_ a SAX event processor + @param[in] strict whether to expect the input to be consumed completed + @param[in] tag_handler how to treat CBOR tags + + @return whether parsing was successful + */ + JSON_HEDLEY_NON_NULL(3) + bool sax_parse(const input_format_t format, + json_sax_t* sax_, + const bool strict = true, + const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) + { + sax = sax_; + bool result = false; + + switch (format) + { + case input_format_t::bson: + result = parse_bson_internal(); + break; + + case input_format_t::cbor: + result = parse_cbor_internal(true, tag_handler); + break; + + case input_format_t::msgpack: + result = parse_msgpack_internal(); + break; + + case input_format_t::ubjson: + result = parse_ubjson_internal(); + break; + + case input_format_t::json: // LCOV_EXCL_LINE + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + } + + // strict mode: next byte must be EOF + if (result && strict) + { + if (format == input_format_t::ubjson) + { + get_ignore_noop(); + } + else + { + get(); + } + + if (JSON_HEDLEY_UNLIKELY(current != std::char_traits::eof())) + { + return sax->parse_error(chars_read, get_token_string(), + parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value"), BasicJsonType())); + } + } + + return result; + } + + private: + ////////// + // BSON // + ////////// + + /*! + @brief Reads in a BSON-object and passes it to the SAX-parser. + @return whether a valid BSON-value was passed to the SAX parser + */ + bool parse_bson_internal() + { + std::int32_t document_size{}; + get_number(input_format_t::bson, document_size); + + if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast(-1)))) + { + return false; + } + + if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/false))) + { + return false; + } + + return sax->end_object(); + } + + /*! + @brief Parses a C-style string from the BSON input. + @param[in,out] result A reference to the string variable where the read + string is to be stored. + @return `true` if the \x00-byte indicating the end of the string was + encountered before the EOF; false` indicates an unexpected EOF. + */ + bool get_bson_cstr(string_t& result) + { + auto out = std::back_inserter(result); + while (true) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "cstring"))) + { + return false; + } + if (current == 0x00) + { + return true; + } + *out++ = static_cast(current); + } + } + + /*! + @brief Parses a zero-terminated string of length @a len from the BSON + input. + @param[in] len The length (including the zero-byte at the end) of the + string to be read. + @param[in,out] result A reference to the string variable where the read + string is to be stored. + @tparam NumberType The type of the length @a len + @pre len >= 1 + @return `true` if the string was successfully parsed + */ + template + bool get_bson_string(const NumberType len, string_t& result) + { + if (JSON_HEDLEY_UNLIKELY(len < 1)) + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "string length must be at least 1, is " + std::to_string(len), "string"), BasicJsonType())); + } + + return get_string(input_format_t::bson, len - static_cast(1), result) && get() != std::char_traits::eof(); + } + + /*! + @brief Parses a byte array input of length @a len from the BSON input. + @param[in] len The length of the byte array to be read. + @param[in,out] result A reference to the binary variable where the read + array is to be stored. + @tparam NumberType The type of the length @a len + @pre len >= 0 + @return `true` if the byte array was successfully parsed + */ + template + bool get_bson_binary(const NumberType len, binary_t& result) + { + if (JSON_HEDLEY_UNLIKELY(len < 0)) + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "byte array length cannot be negative, is " + std::to_string(len), "binary"), BasicJsonType())); + } + + // All BSON binary values have a subtype + std::uint8_t subtype{}; + get_number(input_format_t::bson, subtype); + result.set_subtype(subtype); + + return get_binary(input_format_t::bson, len, result); + } + + /*! + @brief Read a BSON document element of the given @a element_type. + @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html + @param[in] element_type_parse_position The position in the input stream, + where the `element_type` was read. + @warning Not all BSON element types are supported yet. An unsupported + @a element_type will give rise to a parse_error.114: + Unsupported BSON record type 0x... + @return whether a valid BSON-object/array was passed to the SAX parser + */ + bool parse_bson_element_internal(const char_int_type element_type, + const std::size_t element_type_parse_position) + { + switch (element_type) + { + case 0x01: // double + { + double number{}; + return get_number(input_format_t::bson, number) && sax->number_float(static_cast(number), ""); + } + + case 0x02: // string + { + std::int32_t len{}; + string_t value; + return get_number(input_format_t::bson, len) && get_bson_string(len, value) && sax->string(value); + } + + case 0x03: // object + { + return parse_bson_internal(); + } + + case 0x04: // array + { + return parse_bson_array(); + } + + case 0x05: // binary + { + std::int32_t len{}; + binary_t value; + return get_number(input_format_t::bson, len) && get_bson_binary(len, value) && sax->binary(value); + } + + case 0x08: // boolean + { + return sax->boolean(get() != 0); + } + + case 0x0A: // null + { + return sax->null(); + } + + case 0x10: // int32 + { + std::int32_t value{}; + return get_number(input_format_t::bson, value) && sax->number_integer(value); + } + + case 0x12: // int64 + { + std::int64_t value{}; + return get_number(input_format_t::bson, value) && sax->number_integer(value); + } + + default: // anything else not supported (yet) + { + std::array cr{{}}; + static_cast((std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast(element_type))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) + return sax->parse_error(element_type_parse_position, std::string(cr.data()), parse_error::create(114, element_type_parse_position, "Unsupported BSON record type 0x" + std::string(cr.data()), BasicJsonType())); + } + } + } + + /*! + @brief Read a BSON element list (as specified in the BSON-spec) + + The same binary layout is used for objects and arrays, hence it must be + indicated with the argument @a is_array which one is expected + (true --> array, false --> object). + + @param[in] is_array Determines if the element list being read is to be + treated as an object (@a is_array == false), or as an + array (@a is_array == true). + @return whether a valid BSON-object/array was passed to the SAX parser + */ + bool parse_bson_element_list(const bool is_array) + { + string_t key; + + while (auto element_type = get()) + { + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "element list"))) + { + return false; + } + + const std::size_t element_type_parse_position = chars_read; + if (JSON_HEDLEY_UNLIKELY(!get_bson_cstr(key))) + { + return false; + } + + if (!is_array && !sax->key(key)) + { + return false; + } + + if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_internal(element_type, element_type_parse_position))) + { + return false; + } + + // get_bson_cstr only appends + key.clear(); + } + + return true; + } + + /*! + @brief Reads an array from the BSON input and passes it to the SAX-parser. + @return whether a valid BSON-array was passed to the SAX parser + */ + bool parse_bson_array() + { + std::int32_t document_size{}; + get_number(input_format_t::bson, document_size); + + if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast(-1)))) + { + return false; + } + + if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/true))) + { + return false; + } + + return sax->end_array(); + } + + ////////// + // CBOR // + ////////// + + /*! + @param[in] get_char whether a new character should be retrieved from the + input (true) or whether the last read character should + be considered instead (false) + @param[in] tag_handler how CBOR tags should be treated + + @return whether a valid CBOR value was passed to the SAX parser + */ + bool parse_cbor_internal(const bool get_char, + const cbor_tag_handler_t tag_handler) + { + switch (get_char ? get() : current) + { + // EOF + case std::char_traits::eof(): + return unexpect_eof(input_format_t::cbor, "value"); + + // Integer 0x00..0x17 (0..23) + case 0x00: + case 0x01: + case 0x02: + case 0x03: + case 0x04: + case 0x05: + case 0x06: + case 0x07: + case 0x08: + case 0x09: + case 0x0A: + case 0x0B: + case 0x0C: + case 0x0D: + case 0x0E: + case 0x0F: + case 0x10: + case 0x11: + case 0x12: + case 0x13: + case 0x14: + case 0x15: + case 0x16: + case 0x17: + return sax->number_unsigned(static_cast(current)); + + case 0x18: // Unsigned integer (one-byte uint8_t follows) + { + std::uint8_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); + } + + case 0x19: // Unsigned integer (two-byte uint16_t follows) + { + std::uint16_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); + } + + case 0x1A: // Unsigned integer (four-byte uint32_t follows) + { + std::uint32_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); + } + + case 0x1B: // Unsigned integer (eight-byte uint64_t follows) + { + std::uint64_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); + } + + // Negative integer -1-0x00..-1-0x17 (-1..-24) + case 0x20: + case 0x21: + case 0x22: + case 0x23: + case 0x24: + case 0x25: + case 0x26: + case 0x27: + case 0x28: + case 0x29: + case 0x2A: + case 0x2B: + case 0x2C: + case 0x2D: + case 0x2E: + case 0x2F: + case 0x30: + case 0x31: + case 0x32: + case 0x33: + case 0x34: + case 0x35: + case 0x36: + case 0x37: + return sax->number_integer(static_cast(0x20 - 1 - current)); + + case 0x38: // Negative integer (one-byte uint8_t follows) + { + std::uint8_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); + } + + case 0x39: // Negative integer -1-n (two-byte uint16_t follows) + { + std::uint16_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); + } + + case 0x3A: // Negative integer -1-n (four-byte uint32_t follows) + { + std::uint32_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); + } + + case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows) + { + std::uint64_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) + - static_cast(number)); + } + + // Binary data (0x00..0x17 bytes follow) + case 0x40: + case 0x41: + case 0x42: + case 0x43: + case 0x44: + case 0x45: + case 0x46: + case 0x47: + case 0x48: + case 0x49: + case 0x4A: + case 0x4B: + case 0x4C: + case 0x4D: + case 0x4E: + case 0x4F: + case 0x50: + case 0x51: + case 0x52: + case 0x53: + case 0x54: + case 0x55: + case 0x56: + case 0x57: + case 0x58: // Binary data (one-byte uint8_t for n follows) + case 0x59: // Binary data (two-byte uint16_t for n follow) + case 0x5A: // Binary data (four-byte uint32_t for n follow) + case 0x5B: // Binary data (eight-byte uint64_t for n follow) + case 0x5F: // Binary data (indefinite length) + { + binary_t b; + return get_cbor_binary(b) && sax->binary(b); + } + + // UTF-8 string (0x00..0x17 bytes follow) + case 0x60: + case 0x61: + case 0x62: + case 0x63: + case 0x64: + case 0x65: + case 0x66: + case 0x67: + case 0x68: + case 0x69: + case 0x6A: + case 0x6B: + case 0x6C: + case 0x6D: + case 0x6E: + case 0x6F: + case 0x70: + case 0x71: + case 0x72: + case 0x73: + case 0x74: + case 0x75: + case 0x76: + case 0x77: + case 0x78: // UTF-8 string (one-byte uint8_t for n follows) + case 0x79: // UTF-8 string (two-byte uint16_t for n follow) + case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) + case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) + case 0x7F: // UTF-8 string (indefinite length) + { + string_t s; + return get_cbor_string(s) && sax->string(s); + } + + // array (0x00..0x17 data items follow) + case 0x80: + case 0x81: + case 0x82: + case 0x83: + case 0x84: + case 0x85: + case 0x86: + case 0x87: + case 0x88: + case 0x89: + case 0x8A: + case 0x8B: + case 0x8C: + case 0x8D: + case 0x8E: + case 0x8F: + case 0x90: + case 0x91: + case 0x92: + case 0x93: + case 0x94: + case 0x95: + case 0x96: + case 0x97: + return get_cbor_array(static_cast(static_cast(current) & 0x1Fu), tag_handler); + + case 0x98: // array (one-byte uint8_t for n follows) + { + std::uint8_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); + } + + case 0x99: // array (two-byte uint16_t for n follow) + { + std::uint16_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); + } + + case 0x9A: // array (four-byte uint32_t for n follow) + { + std::uint32_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); + } + + case 0x9B: // array (eight-byte uint64_t for n follow) + { + std::uint64_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_array(detail::conditional_static_cast(len), tag_handler); + } + + case 0x9F: // array (indefinite length) + return get_cbor_array(static_cast(-1), tag_handler); + + // map (0x00..0x17 pairs of data items follow) + case 0xA0: + case 0xA1: + case 0xA2: + case 0xA3: + case 0xA4: + case 0xA5: + case 0xA6: + case 0xA7: + case 0xA8: + case 0xA9: + case 0xAA: + case 0xAB: + case 0xAC: + case 0xAD: + case 0xAE: + case 0xAF: + case 0xB0: + case 0xB1: + case 0xB2: + case 0xB3: + case 0xB4: + case 0xB5: + case 0xB6: + case 0xB7: + return get_cbor_object(static_cast(static_cast(current) & 0x1Fu), tag_handler); + + case 0xB8: // map (one-byte uint8_t for n follows) + { + std::uint8_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); + } + + case 0xB9: // map (two-byte uint16_t for n follow) + { + std::uint16_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); + } + + case 0xBA: // map (four-byte uint32_t for n follow) + { + std::uint32_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); + } + + case 0xBB: // map (eight-byte uint64_t for n follow) + { + std::uint64_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_object(detail::conditional_static_cast(len), tag_handler); + } + + case 0xBF: // map (indefinite length) + return get_cbor_object(static_cast(-1), tag_handler); + + case 0xC6: // tagged item + case 0xC7: + case 0xC8: + case 0xC9: + case 0xCA: + case 0xCB: + case 0xCC: + case 0xCD: + case 0xCE: + case 0xCF: + case 0xD0: + case 0xD1: + case 0xD2: + case 0xD3: + case 0xD4: + case 0xD8: // tagged item (1 bytes follow) + case 0xD9: // tagged item (2 bytes follow) + case 0xDA: // tagged item (4 bytes follow) + case 0xDB: // tagged item (8 bytes follow) + { + switch (tag_handler) + { + case cbor_tag_handler_t::error: + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); + } + + case cbor_tag_handler_t::ignore: + { + // ignore binary subtype + switch (current) + { + case 0xD8: + { + std::uint8_t subtype_to_ignore{}; + get_number(input_format_t::cbor, subtype_to_ignore); + break; + } + case 0xD9: + { + std::uint16_t subtype_to_ignore{}; + get_number(input_format_t::cbor, subtype_to_ignore); + break; + } + case 0xDA: + { + std::uint32_t subtype_to_ignore{}; + get_number(input_format_t::cbor, subtype_to_ignore); + break; + } + case 0xDB: + { + std::uint64_t subtype_to_ignore{}; + get_number(input_format_t::cbor, subtype_to_ignore); + break; + } + default: + break; + } + return parse_cbor_internal(true, tag_handler); + } + + case cbor_tag_handler_t::store: + { + binary_t b; + // use binary subtype and store in binary container + switch (current) + { + case 0xD8: + { + std::uint8_t subtype{}; + get_number(input_format_t::cbor, subtype); + b.set_subtype(detail::conditional_static_cast(subtype)); + break; + } + case 0xD9: + { + std::uint16_t subtype{}; + get_number(input_format_t::cbor, subtype); + b.set_subtype(detail::conditional_static_cast(subtype)); + break; + } + case 0xDA: + { + std::uint32_t subtype{}; + get_number(input_format_t::cbor, subtype); + b.set_subtype(detail::conditional_static_cast(subtype)); + break; + } + case 0xDB: + { + std::uint64_t subtype{}; + get_number(input_format_t::cbor, subtype); + b.set_subtype(detail::conditional_static_cast(subtype)); + break; + } + default: + return parse_cbor_internal(true, tag_handler); + } + get(); + return get_cbor_binary(b) && sax->binary(b); + } + + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + return false; // LCOV_EXCL_LINE + } + } + + case 0xF4: // false + return sax->boolean(false); + + case 0xF5: // true + return sax->boolean(true); + + case 0xF6: // null + return sax->null(); + + case 0xF9: // Half-Precision Float (two-byte IEEE 754) + { + const auto byte1_raw = get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number"))) + { + return false; + } + const auto byte2_raw = get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number"))) + { + return false; + } + + const auto byte1 = static_cast(byte1_raw); + const auto byte2 = static_cast(byte2_raw); + + // code from RFC 7049, Appendix D, Figure 3: + // As half-precision floating-point numbers were only added + // to IEEE 754 in 2008, today's programming platforms often + // still only have limited support for them. It is very + // easy to include at least decoding support for them even + // without such support. An example of a small decoder for + // half-precision floating-point numbers in the C language + // is shown in Fig. 3. + const auto half = static_cast((byte1 << 8u) + byte2); + const double val = [&half] + { + const int exp = (half >> 10u) & 0x1Fu; + const unsigned int mant = half & 0x3FFu; + JSON_ASSERT(0 <= exp&& exp <= 32); + JSON_ASSERT(mant <= 1024); + switch (exp) + { + case 0: + return std::ldexp(mant, -24); + case 31: + return (mant == 0) + ? std::numeric_limits::infinity() + : std::numeric_limits::quiet_NaN(); + default: + return std::ldexp(mant + 1024, exp - 25); + } + }(); + return sax->number_float((half & 0x8000u) != 0 + ? static_cast(-val) + : static_cast(val), ""); + } + + case 0xFA: // Single-Precision Float (four-byte IEEE 754) + { + float number{}; + return get_number(input_format_t::cbor, number) && sax->number_float(static_cast(number), ""); + } + + case 0xFB: // Double-Precision Float (eight-byte IEEE 754) + { + double number{}; + return get_number(input_format_t::cbor, number) && sax->number_float(static_cast(number), ""); + } + + default: // anything else (0xFF is handled inside the other types) + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); + } + } + } + + /*! + @brief reads a CBOR string + + This function first reads starting bytes to determine the expected + string length and then copies this number of bytes into a string. + Additionally, CBOR's strings with indefinite lengths are supported. + + @param[out] result created string + + @return whether string creation completed + */ + bool get_cbor_string(string_t& result) + { + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "string"))) + { + return false; + } + + switch (current) + { + // UTF-8 string (0x00..0x17 bytes follow) + case 0x60: + case 0x61: + case 0x62: + case 0x63: + case 0x64: + case 0x65: + case 0x66: + case 0x67: + case 0x68: + case 0x69: + case 0x6A: + case 0x6B: + case 0x6C: + case 0x6D: + case 0x6E: + case 0x6F: + case 0x70: + case 0x71: + case 0x72: + case 0x73: + case 0x74: + case 0x75: + case 0x76: + case 0x77: + { + return get_string(input_format_t::cbor, static_cast(current) & 0x1Fu, result); + } + + case 0x78: // UTF-8 string (one-byte uint8_t for n follows) + { + std::uint8_t len{}; + return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); + } + + case 0x79: // UTF-8 string (two-byte uint16_t for n follow) + { + std::uint16_t len{}; + return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); + } + + case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) + { + std::uint32_t len{}; + return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); + } + + case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) + { + std::uint64_t len{}; + return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); + } + + case 0x7F: // UTF-8 string (indefinite length) + { + while (get() != 0xFF) + { + string_t chunk; + if (!get_cbor_string(chunk)) + { + return false; + } + result.append(chunk); + } + return true; + } + + default: + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0x" + last_token, "string"), BasicJsonType())); + } + } + } + + /*! + @brief reads a CBOR byte array + + This function first reads starting bytes to determine the expected + byte array length and then copies this number of bytes into the byte array. + Additionally, CBOR's byte arrays with indefinite lengths are supported. + + @param[out] result created byte array + + @return whether byte array creation completed + */ + bool get_cbor_binary(binary_t& result) + { + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "binary"))) + { + return false; + } + + switch (current) + { + // Binary data (0x00..0x17 bytes follow) + case 0x40: + case 0x41: + case 0x42: + case 0x43: + case 0x44: + case 0x45: + case 0x46: + case 0x47: + case 0x48: + case 0x49: + case 0x4A: + case 0x4B: + case 0x4C: + case 0x4D: + case 0x4E: + case 0x4F: + case 0x50: + case 0x51: + case 0x52: + case 0x53: + case 0x54: + case 0x55: + case 0x56: + case 0x57: + { + return get_binary(input_format_t::cbor, static_cast(current) & 0x1Fu, result); + } + + case 0x58: // Binary data (one-byte uint8_t for n follows) + { + std::uint8_t len{}; + return get_number(input_format_t::cbor, len) && + get_binary(input_format_t::cbor, len, result); + } + + case 0x59: // Binary data (two-byte uint16_t for n follow) + { + std::uint16_t len{}; + return get_number(input_format_t::cbor, len) && + get_binary(input_format_t::cbor, len, result); + } + + case 0x5A: // Binary data (four-byte uint32_t for n follow) + { + std::uint32_t len{}; + return get_number(input_format_t::cbor, len) && + get_binary(input_format_t::cbor, len, result); + } + + case 0x5B: // Binary data (eight-byte uint64_t for n follow) + { + std::uint64_t len{}; + return get_number(input_format_t::cbor, len) && + get_binary(input_format_t::cbor, len, result); + } + + case 0x5F: // Binary data (indefinite length) + { + while (get() != 0xFF) + { + binary_t chunk; + if (!get_cbor_binary(chunk)) + { + return false; + } + result.insert(result.end(), chunk.begin(), chunk.end()); + } + return true; + } + + default: + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x40-0x5B) or indefinite binary array type (0x5F); last byte: 0x" + last_token, "binary"), BasicJsonType())); + } + } + } + + /*! + @param[in] len the length of the array or static_cast(-1) for an + array of indefinite size + @param[in] tag_handler how CBOR tags should be treated + @return whether array creation completed + */ + bool get_cbor_array(const std::size_t len, + const cbor_tag_handler_t tag_handler) + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len))) + { + return false; + } + + if (len != static_cast(-1)) + { + for (std::size_t i = 0; i < len; ++i) + { + if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) + { + return false; + } + } + } + else + { + while (get() != 0xFF) + { + if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(false, tag_handler))) + { + return false; + } + } + } + + return sax->end_array(); + } + + /*! + @param[in] len the length of the object or static_cast(-1) for an + object of indefinite size + @param[in] tag_handler how CBOR tags should be treated + @return whether object creation completed + */ + bool get_cbor_object(const std::size_t len, + const cbor_tag_handler_t tag_handler) + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len))) + { + return false; + } + + if (len != 0) + { + string_t key; + if (len != static_cast(-1)) + { + for (std::size_t i = 0; i < len; ++i) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key))) + { + return false; + } + + if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) + { + return false; + } + key.clear(); + } + } + else + { + while (get() != 0xFF) + { + if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key))) + { + return false; + } + + if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) + { + return false; + } + key.clear(); + } + } + } + + return sax->end_object(); + } + + ///////////// + // MsgPack // + ///////////// + + /*! + @return whether a valid MessagePack value was passed to the SAX parser + */ + bool parse_msgpack_internal() + { + switch (get()) + { + // EOF + case std::char_traits::eof(): + return unexpect_eof(input_format_t::msgpack, "value"); + + // positive fixint + case 0x00: + case 0x01: + case 0x02: + case 0x03: + case 0x04: + case 0x05: + case 0x06: + case 0x07: + case 0x08: + case 0x09: + case 0x0A: + case 0x0B: + case 0x0C: + case 0x0D: + case 0x0E: + case 0x0F: + case 0x10: + case 0x11: + case 0x12: + case 0x13: + case 0x14: + case 0x15: + case 0x16: + case 0x17: + case 0x18: + case 0x19: + case 0x1A: + case 0x1B: + case 0x1C: + case 0x1D: + case 0x1E: + case 0x1F: + case 0x20: + case 0x21: + case 0x22: + case 0x23: + case 0x24: + case 0x25: + case 0x26: + case 0x27: + case 0x28: + case 0x29: + case 0x2A: + case 0x2B: + case 0x2C: + case 0x2D: + case 0x2E: + case 0x2F: + case 0x30: + case 0x31: + case 0x32: + case 0x33: + case 0x34: + case 0x35: + case 0x36: + case 0x37: + case 0x38: + case 0x39: + case 0x3A: + case 0x3B: + case 0x3C: + case 0x3D: + case 0x3E: + case 0x3F: + case 0x40: + case 0x41: + case 0x42: + case 0x43: + case 0x44: + case 0x45: + case 0x46: + case 0x47: + case 0x48: + case 0x49: + case 0x4A: + case 0x4B: + case 0x4C: + case 0x4D: + case 0x4E: + case 0x4F: + case 0x50: + case 0x51: + case 0x52: + case 0x53: + case 0x54: + case 0x55: + case 0x56: + case 0x57: + case 0x58: + case 0x59: + case 0x5A: + case 0x5B: + case 0x5C: + case 0x5D: + case 0x5E: + case 0x5F: + case 0x60: + case 0x61: + case 0x62: + case 0x63: + case 0x64: + case 0x65: + case 0x66: + case 0x67: + case 0x68: + case 0x69: + case 0x6A: + case 0x6B: + case 0x6C: + case 0x6D: + case 0x6E: + case 0x6F: + case 0x70: + case 0x71: + case 0x72: + case 0x73: + case 0x74: + case 0x75: + case 0x76: + case 0x77: + case 0x78: + case 0x79: + case 0x7A: + case 0x7B: + case 0x7C: + case 0x7D: + case 0x7E: + case 0x7F: + return sax->number_unsigned(static_cast(current)); + + // fixmap + case 0x80: + case 0x81: + case 0x82: + case 0x83: + case 0x84: + case 0x85: + case 0x86: + case 0x87: + case 0x88: + case 0x89: + case 0x8A: + case 0x8B: + case 0x8C: + case 0x8D: + case 0x8E: + case 0x8F: + return get_msgpack_object(static_cast(static_cast(current) & 0x0Fu)); + + // fixarray + case 0x90: + case 0x91: + case 0x92: + case 0x93: + case 0x94: + case 0x95: + case 0x96: + case 0x97: + case 0x98: + case 0x99: + case 0x9A: + case 0x9B: + case 0x9C: + case 0x9D: + case 0x9E: + case 0x9F: + return get_msgpack_array(static_cast(static_cast(current) & 0x0Fu)); + + // fixstr + case 0xA0: + case 0xA1: + case 0xA2: + case 0xA3: + case 0xA4: + case 0xA5: + case 0xA6: + case 0xA7: + case 0xA8: + case 0xA9: + case 0xAA: + case 0xAB: + case 0xAC: + case 0xAD: + case 0xAE: + case 0xAF: + case 0xB0: + case 0xB1: + case 0xB2: + case 0xB3: + case 0xB4: + case 0xB5: + case 0xB6: + case 0xB7: + case 0xB8: + case 0xB9: + case 0xBA: + case 0xBB: + case 0xBC: + case 0xBD: + case 0xBE: + case 0xBF: + case 0xD9: // str 8 + case 0xDA: // str 16 + case 0xDB: // str 32 + { + string_t s; + return get_msgpack_string(s) && sax->string(s); + } + + case 0xC0: // nil + return sax->null(); + + case 0xC2: // false + return sax->boolean(false); + + case 0xC3: // true + return sax->boolean(true); + + case 0xC4: // bin 8 + case 0xC5: // bin 16 + case 0xC6: // bin 32 + case 0xC7: // ext 8 + case 0xC8: // ext 16 + case 0xC9: // ext 32 + case 0xD4: // fixext 1 + case 0xD5: // fixext 2 + case 0xD6: // fixext 4 + case 0xD7: // fixext 8 + case 0xD8: // fixext 16 + { + binary_t b; + return get_msgpack_binary(b) && sax->binary(b); + } + + case 0xCA: // float 32 + { + float number{}; + return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast(number), ""); + } + + case 0xCB: // float 64 + { + double number{}; + return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast(number), ""); + } + + case 0xCC: // uint 8 + { + std::uint8_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); + } + + case 0xCD: // uint 16 + { + std::uint16_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); + } + + case 0xCE: // uint 32 + { + std::uint32_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); + } + + case 0xCF: // uint 64 + { + std::uint64_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); + } + + case 0xD0: // int 8 + { + std::int8_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_integer(number); + } + + case 0xD1: // int 16 + { + std::int16_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_integer(number); + } + + case 0xD2: // int 32 + { + std::int32_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_integer(number); + } + + case 0xD3: // int 64 + { + std::int64_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_integer(number); + } + + case 0xDC: // array 16 + { + std::uint16_t len{}; + return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast(len)); + } + + case 0xDD: // array 32 + { + std::uint32_t len{}; + return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast(len)); + } + + case 0xDE: // map 16 + { + std::uint16_t len{}; + return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast(len)); + } + + case 0xDF: // map 32 + { + std::uint32_t len{}; + return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast(len)); + } + + // negative fixint + case 0xE0: + case 0xE1: + case 0xE2: + case 0xE3: + case 0xE4: + case 0xE5: + case 0xE6: + case 0xE7: + case 0xE8: + case 0xE9: + case 0xEA: + case 0xEB: + case 0xEC: + case 0xED: + case 0xEE: + case 0xEF: + case 0xF0: + case 0xF1: + case 0xF2: + case 0xF3: + case 0xF4: + case 0xF5: + case 0xF6: + case 0xF7: + case 0xF8: + case 0xF9: + case 0xFA: + case 0xFB: + case 0xFC: + case 0xFD: + case 0xFE: + case 0xFF: + return sax->number_integer(static_cast(current)); + + default: // anything else + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::msgpack, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); + } + } + } + + /*! + @brief reads a MessagePack string + + This function first reads starting bytes to determine the expected + string length and then copies this number of bytes into a string. + + @param[out] result created string + + @return whether string creation completed + */ + bool get_msgpack_string(string_t& result) + { + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::msgpack, "string"))) + { + return false; + } + + switch (current) + { + // fixstr + case 0xA0: + case 0xA1: + case 0xA2: + case 0xA3: + case 0xA4: + case 0xA5: + case 0xA6: + case 0xA7: + case 0xA8: + case 0xA9: + case 0xAA: + case 0xAB: + case 0xAC: + case 0xAD: + case 0xAE: + case 0xAF: + case 0xB0: + case 0xB1: + case 0xB2: + case 0xB3: + case 0xB4: + case 0xB5: + case 0xB6: + case 0xB7: + case 0xB8: + case 0xB9: + case 0xBA: + case 0xBB: + case 0xBC: + case 0xBD: + case 0xBE: + case 0xBF: + { + return get_string(input_format_t::msgpack, static_cast(current) & 0x1Fu, result); + } + + case 0xD9: // str 8 + { + std::uint8_t len{}; + return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); + } + + case 0xDA: // str 16 + { + std::uint16_t len{}; + return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); + } + + case 0xDB: // str 32 + { + std::uint32_t len{}; + return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); + } + + default: + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::msgpack, "expected length specification (0xA0-0xBF, 0xD9-0xDB); last byte: 0x" + last_token, "string"), BasicJsonType())); + } + } + } + + /*! + @brief reads a MessagePack byte array + + This function first reads starting bytes to determine the expected + byte array length and then copies this number of bytes into a byte array. + + @param[out] result created byte array + + @return whether byte array creation completed + */ + bool get_msgpack_binary(binary_t& result) + { + // helper function to set the subtype + auto assign_and_return_true = [&result](std::int8_t subtype) + { + result.set_subtype(static_cast(subtype)); + return true; + }; + + switch (current) + { + case 0xC4: // bin 8 + { + std::uint8_t len{}; + return get_number(input_format_t::msgpack, len) && + get_binary(input_format_t::msgpack, len, result); + } + + case 0xC5: // bin 16 + { + std::uint16_t len{}; + return get_number(input_format_t::msgpack, len) && + get_binary(input_format_t::msgpack, len, result); + } + + case 0xC6: // bin 32 + { + std::uint32_t len{}; + return get_number(input_format_t::msgpack, len) && + get_binary(input_format_t::msgpack, len, result); + } + + case 0xC7: // ext 8 + { + std::uint8_t len{}; + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, len) && + get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, len, result) && + assign_and_return_true(subtype); + } + + case 0xC8: // ext 16 + { + std::uint16_t len{}; + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, len) && + get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, len, result) && + assign_and_return_true(subtype); + } + + case 0xC9: // ext 32 + { + std::uint32_t len{}; + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, len) && + get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, len, result) && + assign_and_return_true(subtype); + } + + case 0xD4: // fixext 1 + { + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, 1, result) && + assign_and_return_true(subtype); + } + + case 0xD5: // fixext 2 + { + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, 2, result) && + assign_and_return_true(subtype); + } + + case 0xD6: // fixext 4 + { + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, 4, result) && + assign_and_return_true(subtype); + } + + case 0xD7: // fixext 8 + { + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, 8, result) && + assign_and_return_true(subtype); + } + + case 0xD8: // fixext 16 + { + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, 16, result) && + assign_and_return_true(subtype); + } + + default: // LCOV_EXCL_LINE + return false; // LCOV_EXCL_LINE + } + } + + /*! + @param[in] len the length of the array + @return whether array creation completed + */ + bool get_msgpack_array(const std::size_t len) + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len))) + { + return false; + } + + for (std::size_t i = 0; i < len; ++i) + { + if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal())) + { + return false; + } + } + + return sax->end_array(); + } + + /*! + @param[in] len the length of the object + @return whether object creation completed + */ + bool get_msgpack_object(const std::size_t len) + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len))) + { + return false; + } + + string_t key; + for (std::size_t i = 0; i < len; ++i) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!get_msgpack_string(key) || !sax->key(key))) + { + return false; + } + + if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal())) + { + return false; + } + key.clear(); + } + + return sax->end_object(); + } + + //////////// + // UBJSON // + //////////// + + /*! + @param[in] get_char whether a new character should be retrieved from the + input (true, default) or whether the last read + character should be considered instead + + @return whether a valid UBJSON value was passed to the SAX parser + */ + bool parse_ubjson_internal(const bool get_char = true) + { + return get_ubjson_value(get_char ? get_ignore_noop() : current); + } + + /*! + @brief reads a UBJSON string + + This function is either called after reading the 'S' byte explicitly + indicating a string, or in case of an object key where the 'S' byte can be + left out. + + @param[out] result created string + @param[in] get_char whether a new character should be retrieved from the + input (true, default) or whether the last read + character should be considered instead + + @return whether string creation completed + */ + bool get_ubjson_string(string_t& result, const bool get_char = true) + { + if (get_char) + { + get(); // TODO(niels): may we ignore N here? + } + + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value"))) + { + return false; + } + + switch (current) + { + case 'U': + { + std::uint8_t len{}; + return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); + } + + case 'i': + { + std::int8_t len{}; + return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); + } + + case 'I': + { + std::int16_t len{}; + return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); + } + + case 'l': + { + std::int32_t len{}; + return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); + } + + case 'L': + { + std::int64_t len{}; + return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); + } + + default: + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L); last byte: 0x" + last_token, "string"), BasicJsonType())); + } + } + + /*! + @param[out] result determined size + @return whether size determination completed + */ + bool get_ubjson_size_value(std::size_t& result) + { + switch (get_ignore_noop()) + { + case 'U': + { + std::uint8_t number{}; + if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) + { + return false; + } + result = static_cast(number); + return true; + } + + case 'i': + { + std::int8_t number{}; + if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) + { + return false; + } + result = static_cast(number); // NOLINT(bugprone-signed-char-misuse,cert-str34-c): number is not a char + return true; + } + + case 'I': + { + std::int16_t number{}; + if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) + { + return false; + } + result = static_cast(number); + return true; + } + + case 'l': + { + std::int32_t number{}; + if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) + { + return false; + } + result = static_cast(number); + return true; + } + + case 'L': + { + std::int64_t number{}; + if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) + { + return false; + } + result = static_cast(number); + return true; + } + + default: + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L) after '#'; last byte: 0x" + last_token, "size"), BasicJsonType())); + } + } + } + + /*! + @brief determine the type and size for a container + + In the optimized UBJSON format, a type and a size can be provided to allow + for a more compact representation. + + @param[out] result pair of the size and the type + + @return whether pair creation completed + */ + bool get_ubjson_size_type(std::pair& result) + { + result.first = string_t::npos; // size + result.second = 0; // type + + get_ignore_noop(); + + if (current == '$') + { + result.second = get(); // must not ignore 'N', because 'N' maybe the type + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "type"))) + { + return false; + } + + get_ignore_noop(); + if (JSON_HEDLEY_UNLIKELY(current != '#')) + { + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value"))) + { + return false; + } + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "expected '#' after type information; last byte: 0x" + last_token, "size"), BasicJsonType())); + } + + return get_ubjson_size_value(result.first); + } + + if (current == '#') + { + return get_ubjson_size_value(result.first); + } + + return true; + } + + /*! + @param prefix the previously read or set type prefix + @return whether value creation completed + */ + bool get_ubjson_value(const char_int_type prefix) + { + switch (prefix) + { + case std::char_traits::eof(): // EOF + return unexpect_eof(input_format_t::ubjson, "value"); + + case 'T': // true + return sax->boolean(true); + case 'F': // false + return sax->boolean(false); + + case 'Z': // null + return sax->null(); + + case 'U': + { + std::uint8_t number{}; + return get_number(input_format_t::ubjson, number) && sax->number_unsigned(number); + } + + case 'i': + { + std::int8_t number{}; + return get_number(input_format_t::ubjson, number) && sax->number_integer(number); + } + + case 'I': + { + std::int16_t number{}; + return get_number(input_format_t::ubjson, number) && sax->number_integer(number); + } + + case 'l': + { + std::int32_t number{}; + return get_number(input_format_t::ubjson, number) && sax->number_integer(number); + } + + case 'L': + { + std::int64_t number{}; + return get_number(input_format_t::ubjson, number) && sax->number_integer(number); + } + + case 'd': + { + float number{}; + return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast(number), ""); + } + + case 'D': + { + double number{}; + return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast(number), ""); + } + + case 'H': + { + return get_ubjson_high_precision_number(); + } + + case 'C': // char + { + get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "char"))) + { + return false; + } + if (JSON_HEDLEY_UNLIKELY(current > 127)) + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "byte after 'C' must be in range 0x00..0x7F; last byte: 0x" + last_token, "char"), BasicJsonType())); + } + string_t s(1, static_cast(current)); + return sax->string(s); + } + + case 'S': // string + { + string_t s; + return get_ubjson_string(s) && sax->string(s); + } + + case '[': // array + return get_ubjson_array(); + + case '{': // object + return get_ubjson_object(); + + default: // anything else + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); + } + } + } + + /*! + @return whether array creation completed + */ + bool get_ubjson_array() + { + std::pair size_and_type; + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type))) + { + return false; + } + + if (size_and_type.first != string_t::npos) + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_array(size_and_type.first))) + { + return false; + } + + if (size_and_type.second != 0) + { + if (size_and_type.second != 'N') + { + for (std::size_t i = 0; i < size_and_type.first; ++i) + { + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) + { + return false; + } + } + } + } + else + { + for (std::size_t i = 0; i < size_and_type.first; ++i) + { + if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) + { + return false; + } + } + } + } + else + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast(-1)))) + { + return false; + } + + while (current != ']') + { + if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal(false))) + { + return false; + } + get_ignore_noop(); + } + } + + return sax->end_array(); + } + + /*! + @return whether object creation completed + */ + bool get_ubjson_object() + { + std::pair size_and_type; + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type))) + { + return false; + } + + string_t key; + if (size_and_type.first != string_t::npos) + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_object(size_and_type.first))) + { + return false; + } + + if (size_and_type.second != 0) + { + for (std::size_t i = 0; i < size_and_type.first; ++i) + { + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key))) + { + return false; + } + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) + { + return false; + } + key.clear(); + } + } + else + { + for (std::size_t i = 0; i < size_and_type.first; ++i) + { + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key))) + { + return false; + } + if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) + { + return false; + } + key.clear(); + } + } + } + else + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast(-1)))) + { + return false; + } + + while (current != '}') + { + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key, false) || !sax->key(key))) + { + return false; + } + if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) + { + return false; + } + get_ignore_noop(); + key.clear(); + } + } + + return sax->end_object(); + } + + // Note, no reader for UBJSON binary types is implemented because they do + // not exist + + bool get_ubjson_high_precision_number() + { + // get size of following number string + std::size_t size{}; + auto res = get_ubjson_size_value(size); + if (JSON_HEDLEY_UNLIKELY(!res)) + { + return res; + } + + // get number string + std::vector number_vector; + for (std::size_t i = 0; i < size; ++i) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "number"))) + { + return false; + } + number_vector.push_back(static_cast(current)); + } + + // parse number string + using ia_type = decltype(detail::input_adapter(number_vector)); + auto number_lexer = detail::lexer(detail::input_adapter(number_vector), false); + const auto result_number = number_lexer.scan(); + const auto number_string = number_lexer.get_token_string(); + const auto result_remainder = number_lexer.scan(); + + using token_type = typename detail::lexer_base::token_type; + + if (JSON_HEDLEY_UNLIKELY(result_remainder != token_type::end_of_input)) + { + return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format_t::ubjson, "invalid number text: " + number_lexer.get_token_string(), "high-precision number"), BasicJsonType())); + } + + switch (result_number) + { + case token_type::value_integer: + return sax->number_integer(number_lexer.get_number_integer()); + case token_type::value_unsigned: + return sax->number_unsigned(number_lexer.get_number_unsigned()); + case token_type::value_float: + return sax->number_float(number_lexer.get_number_float(), std::move(number_string)); + case token_type::uninitialized: + case token_type::literal_true: + case token_type::literal_false: + case token_type::literal_null: + case token_type::value_string: + case token_type::begin_array: + case token_type::begin_object: + case token_type::end_array: + case token_type::end_object: + case token_type::name_separator: + case token_type::value_separator: + case token_type::parse_error: + case token_type::end_of_input: + case token_type::literal_or_value: + default: + return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format_t::ubjson, "invalid number text: " + number_lexer.get_token_string(), "high-precision number"), BasicJsonType())); + } + } + + /////////////////////// + // Utility functions // + /////////////////////// + + /*! + @brief get next character from the input + + This function provides the interface to the used input adapter. It does + not throw in case the input reached EOF, but returns a -'ve valued + `std::char_traits::eof()` in that case. + + @return character read from the input + */ + char_int_type get() + { + ++chars_read; + return current = ia.get_character(); + } + + /*! + @return character read from the input after ignoring all 'N' entries + */ + char_int_type get_ignore_noop() + { + do + { + get(); + } + while (current == 'N'); + + return current; + } + + /* + @brief read a number from the input + + @tparam NumberType the type of the number + @param[in] format the current format (for diagnostics) + @param[out] result number of type @a NumberType + + @return whether conversion completed + + @note This function needs to respect the system's endianness, because + bytes in CBOR, MessagePack, and UBJSON are stored in network order + (big endian) and therefore need reordering on little endian systems. + */ + template + bool get_number(const input_format_t format, NumberType& result) + { + // step 1: read input into array with system's byte order + std::array vec{}; + for (std::size_t i = 0; i < sizeof(NumberType); ++i) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "number"))) + { + return false; + } + + // reverse byte order prior to conversion if necessary + if (is_little_endian != InputIsLittleEndian) + { + vec[sizeof(NumberType) - i - 1] = static_cast(current); + } + else + { + vec[i] = static_cast(current); // LCOV_EXCL_LINE + } + } + + // step 2: convert array into number of type T and return + std::memcpy(&result, vec.data(), sizeof(NumberType)); + return true; + } + + /*! + @brief create a string by reading characters from the input + + @tparam NumberType the type of the number + @param[in] format the current format (for diagnostics) + @param[in] len number of characters to read + @param[out] result string created by reading @a len bytes + + @return whether string creation completed + + @note We can not reserve @a len bytes for the result, because @a len + may be too large. Usually, @ref unexpect_eof() detects the end of + the input before we run out of string memory. + */ + template + bool get_string(const input_format_t format, + const NumberType len, + string_t& result) + { + bool success = true; + for (NumberType i = 0; i < len; i++) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "string"))) + { + success = false; + break; + } + result.push_back(static_cast(current)); + } + return success; + } + + /*! + @brief create a byte array by reading bytes from the input + + @tparam NumberType the type of the number + @param[in] format the current format (for diagnostics) + @param[in] len number of bytes to read + @param[out] result byte array created by reading @a len bytes + + @return whether byte array creation completed + + @note We can not reserve @a len bytes for the result, because @a len + may be too large. Usually, @ref unexpect_eof() detects the end of + the input before we run out of memory. + */ + template + bool get_binary(const input_format_t format, + const NumberType len, + binary_t& result) + { + bool success = true; + for (NumberType i = 0; i < len; i++) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "binary"))) + { + success = false; + break; + } + result.push_back(static_cast(current)); + } + return success; + } + + /*! + @param[in] format the current format (for diagnostics) + @param[in] context further context information (for diagnostics) + @return whether the last read character is not EOF + */ + JSON_HEDLEY_NON_NULL(3) + bool unexpect_eof(const input_format_t format, const char* context) const + { + if (JSON_HEDLEY_UNLIKELY(current == std::char_traits::eof())) + { + return sax->parse_error(chars_read, "", + parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context), BasicJsonType())); + } + return true; + } + + /*! + @return a string representation of the last read byte + */ + std::string get_token_string() const + { + std::array cr{{}}; + static_cast((std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast(current))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) + return std::string{cr.data()}; + } + + /*! + @param[in] format the current format + @param[in] detail a detailed error message + @param[in] context further context information + @return a message string to use in the parse_error exceptions + */ + std::string exception_message(const input_format_t format, + const std::string& detail, + const std::string& context) const + { + std::string error_msg = "syntax error while parsing "; + + switch (format) + { + case input_format_t::cbor: + error_msg += "CBOR"; + break; + + case input_format_t::msgpack: + error_msg += "MessagePack"; + break; + + case input_format_t::ubjson: + error_msg += "UBJSON"; + break; + + case input_format_t::bson: + error_msg += "BSON"; + break; + + case input_format_t::json: // LCOV_EXCL_LINE + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + } + + return error_msg + " " + context + ": " + detail; + } + + private: + /// input adapter + InputAdapterType ia; + + /// the current character + char_int_type current = std::char_traits::eof(); + + /// the number of characters read + std::size_t chars_read = 0; + + /// whether we can assume little endianness + const bool is_little_endian = little_endianness(); + + /// the SAX parser + json_sax_t* sax = nullptr; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + +// #include + + +#include // isfinite +#include // uint8_t +#include // function +#include // string +#include // move +#include // vector + +// #include + +// #include + +// #include + +// #include + +// #include + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +//////////// +// parser // +//////////// + +enum class parse_event_t : std::uint8_t +{ + /// the parser read `{` and started to process a JSON object + object_start, + /// the parser read `}` and finished processing a JSON object + object_end, + /// the parser read `[` and started to process a JSON array + array_start, + /// the parser read `]` and finished processing a JSON array + array_end, + /// the parser read a key of a value in an object + key, + /// the parser finished reading a JSON value + value +}; + +template +using parser_callback_t = + std::function; + +/*! +@brief syntax analysis + +This class implements a recursive descent parser. +*/ +template +class parser +{ + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using lexer_t = lexer; + using token_type = typename lexer_t::token_type; + + public: + /// a parser reading from an input adapter + explicit parser(InputAdapterType&& adapter, + const parser_callback_t cb = nullptr, + const bool allow_exceptions_ = true, + const bool skip_comments = false) + : callback(cb) + , m_lexer(std::move(adapter), skip_comments) + , allow_exceptions(allow_exceptions_) + { + // read first token + get_token(); + } + + /*! + @brief public parser interface + + @param[in] strict whether to expect the last token to be EOF + @param[in,out] result parsed JSON value + + @throw parse_error.101 in case of an unexpected token + @throw parse_error.102 if to_unicode fails or surrogate error + @throw parse_error.103 if to_unicode fails + */ + void parse(const bool strict, BasicJsonType& result) + { + if (callback) + { + json_sax_dom_callback_parser sdp(result, callback, allow_exceptions); + sax_parse_internal(&sdp); + + // in strict mode, input must be completely read + if (strict && (get_token() != token_type::end_of_input)) + { + sdp.parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), + exception_message(token_type::end_of_input, "value"), BasicJsonType())); + } + + // in case of an error, return discarded value + if (sdp.is_errored()) + { + result = value_t::discarded; + return; + } + + // set top-level value to null if it was discarded by the callback + // function + if (result.is_discarded()) + { + result = nullptr; + } + } + else + { + json_sax_dom_parser sdp(result, allow_exceptions); + sax_parse_internal(&sdp); + + // in strict mode, input must be completely read + if (strict && (get_token() != token_type::end_of_input)) + { + sdp.parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType())); + } + + // in case of an error, return discarded value + if (sdp.is_errored()) + { + result = value_t::discarded; + return; + } + } + + result.assert_invariant(); + } + + /*! + @brief public accept interface + + @param[in] strict whether to expect the last token to be EOF + @return whether the input is a proper JSON text + */ + bool accept(const bool strict = true) + { + json_sax_acceptor sax_acceptor; + return sax_parse(&sax_acceptor, strict); + } + + template + JSON_HEDLEY_NON_NULL(2) + bool sax_parse(SAX* sax, const bool strict = true) + { + (void)detail::is_sax_static_asserts {}; + const bool result = sax_parse_internal(sax); + + // strict mode: next byte must be EOF + if (result && strict && (get_token() != token_type::end_of_input)) + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType())); + } + + return result; + } + + private: + template + JSON_HEDLEY_NON_NULL(2) + bool sax_parse_internal(SAX* sax) + { + // stack to remember the hierarchy of structured values we are parsing + // true = array; false = object + std::vector states; + // value to avoid a goto (see comment where set to true) + bool skip_to_state_evaluation = false; + + while (true) + { + if (!skip_to_state_evaluation) + { + // invariant: get_token() was called before each iteration + switch (last_token) + { + case token_type::begin_object: + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast(-1)))) + { + return false; + } + + // closing } -> we are done + if (get_token() == token_type::end_object) + { + if (JSON_HEDLEY_UNLIKELY(!sax->end_object())) + { + return false; + } + break; + } + + // parse key + if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string)) + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), BasicJsonType())); + } + if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string()))) + { + return false; + } + + // parse separator (:) + if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator)) + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), BasicJsonType())); + } + + // remember we are now inside an object + states.push_back(false); + + // parse values + get_token(); + continue; + } + + case token_type::begin_array: + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast(-1)))) + { + return false; + } + + // closing ] -> we are done + if (get_token() == token_type::end_array) + { + if (JSON_HEDLEY_UNLIKELY(!sax->end_array())) + { + return false; + } + break; + } + + // remember we are now inside an array + states.push_back(true); + + // parse values (no need to call get_token) + continue; + } + + case token_type::value_float: + { + const auto res = m_lexer.get_number_float(); + + if (JSON_HEDLEY_UNLIKELY(!std::isfinite(res))) + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'", BasicJsonType())); + } + + if (JSON_HEDLEY_UNLIKELY(!sax->number_float(res, m_lexer.get_string()))) + { + return false; + } + + break; + } + + case token_type::literal_false: + { + if (JSON_HEDLEY_UNLIKELY(!sax->boolean(false))) + { + return false; + } + break; + } + + case token_type::literal_null: + { + if (JSON_HEDLEY_UNLIKELY(!sax->null())) + { + return false; + } + break; + } + + case token_type::literal_true: + { + if (JSON_HEDLEY_UNLIKELY(!sax->boolean(true))) + { + return false; + } + break; + } + + case token_type::value_integer: + { + if (JSON_HEDLEY_UNLIKELY(!sax->number_integer(m_lexer.get_number_integer()))) + { + return false; + } + break; + } + + case token_type::value_string: + { + if (JSON_HEDLEY_UNLIKELY(!sax->string(m_lexer.get_string()))) + { + return false; + } + break; + } + + case token_type::value_unsigned: + { + if (JSON_HEDLEY_UNLIKELY(!sax->number_unsigned(m_lexer.get_number_unsigned()))) + { + return false; + } + break; + } + + case token_type::parse_error: + { + // using "uninitialized" to avoid "expected" message + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::uninitialized, "value"), BasicJsonType())); + } + + case token_type::uninitialized: + case token_type::end_array: + case token_type::end_object: + case token_type::name_separator: + case token_type::value_separator: + case token_type::end_of_input: + case token_type::literal_or_value: + default: // the last token was unexpected + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::literal_or_value, "value"), BasicJsonType())); + } + } + } + else + { + skip_to_state_evaluation = false; + } + + // we reached this line after we successfully parsed a value + if (states.empty()) + { + // empty stack: we reached the end of the hierarchy: done + return true; + } + + if (states.back()) // array + { + // comma -> next value + if (get_token() == token_type::value_separator) + { + // parse a new value + get_token(); + continue; + } + + // closing ] + if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array)) + { + if (JSON_HEDLEY_UNLIKELY(!sax->end_array())) + { + return false; + } + + // We are done with this array. Before we can parse a + // new value, we need to evaluate the new state first. + // By setting skip_to_state_evaluation to false, we + // are effectively jumping to the beginning of this if. + JSON_ASSERT(!states.empty()); + states.pop_back(); + skip_to_state_evaluation = true; + continue; + } + + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_array, "array"), BasicJsonType())); + } + + // states.back() is false -> object + + // comma -> next value + if (get_token() == token_type::value_separator) + { + // parse key + if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string)) + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), BasicJsonType())); + } + + if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string()))) + { + return false; + } + + // parse separator (:) + if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator)) + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), BasicJsonType())); + } + + // parse values + get_token(); + continue; + } + + // closing } + if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object)) + { + if (JSON_HEDLEY_UNLIKELY(!sax->end_object())) + { + return false; + } + + // We are done with this object. Before we can parse a + // new value, we need to evaluate the new state first. + // By setting skip_to_state_evaluation to false, we + // are effectively jumping to the beginning of this if. + JSON_ASSERT(!states.empty()); + states.pop_back(); + skip_to_state_evaluation = true; + continue; + } + + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_object, "object"), BasicJsonType())); + } + } + + /// get next token from lexer + token_type get_token() + { + return last_token = m_lexer.scan(); + } + + std::string exception_message(const token_type expected, const std::string& context) + { + std::string error_msg = "syntax error "; + + if (!context.empty()) + { + error_msg += "while parsing " + context + " "; + } + + error_msg += "- "; + + if (last_token == token_type::parse_error) + { + error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" + + m_lexer.get_token_string() + "'"; + } + else + { + error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token)); + } + + if (expected != token_type::uninitialized) + { + error_msg += "; expected " + std::string(lexer_t::token_type_name(expected)); + } + + return error_msg; + } + + private: + /// callback function + const parser_callback_t callback = nullptr; + /// the type of the last read token + token_type last_token = token_type::uninitialized; + /// the lexer + lexer_t m_lexer; + /// whether to throw exceptions in case of errors + const bool allow_exceptions = true; +}; + +} // namespace detail +} // namespace nlohmann + +// #include + + +// #include + + +#include // ptrdiff_t +#include // numeric_limits + +// #include + + +namespace nlohmann +{ +namespace detail +{ +/* +@brief an iterator for primitive JSON types + +This class models an iterator for primitive JSON types (boolean, number, +string). It's only purpose is to allow the iterator/const_iterator classes +to "iterate" over primitive values. Internally, the iterator is modeled by +a `difference_type` variable. Value begin_value (`0`) models the begin, +end_value (`1`) models past the end. +*/ +class primitive_iterator_t +{ + private: + using difference_type = std::ptrdiff_t; + static constexpr difference_type begin_value = 0; + static constexpr difference_type end_value = begin_value + 1; + + JSON_PRIVATE_UNLESS_TESTED: + /// iterator as signed integer type + difference_type m_it = (std::numeric_limits::min)(); + + public: + constexpr difference_type get_value() const noexcept + { + return m_it; + } + + /// set iterator to a defined beginning + void set_begin() noexcept + { + m_it = begin_value; + } + + /// set iterator to a defined past the end + void set_end() noexcept + { + m_it = end_value; + } + + /// return whether the iterator can be dereferenced + constexpr bool is_begin() const noexcept + { + return m_it == begin_value; + } + + /// return whether the iterator is at end + constexpr bool is_end() const noexcept + { + return m_it == end_value; + } + + friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return lhs.m_it == rhs.m_it; + } + + friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return lhs.m_it < rhs.m_it; + } + + primitive_iterator_t operator+(difference_type n) noexcept + { + auto result = *this; + result += n; + return result; + } + + friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return lhs.m_it - rhs.m_it; + } + + primitive_iterator_t& operator++() noexcept + { + ++m_it; + return *this; + } + + primitive_iterator_t const operator++(int) noexcept // NOLINT(readability-const-return-type) + { + auto result = *this; + ++m_it; + return result; + } + + primitive_iterator_t& operator--() noexcept + { + --m_it; + return *this; + } + + primitive_iterator_t const operator--(int) noexcept // NOLINT(readability-const-return-type) + { + auto result = *this; + --m_it; + return result; + } + + primitive_iterator_t& operator+=(difference_type n) noexcept + { + m_it += n; + return *this; + } + + primitive_iterator_t& operator-=(difference_type n) noexcept + { + m_it -= n; + return *this; + } +}; +} // namespace detail +} // namespace nlohmann + + +namespace nlohmann +{ +namespace detail +{ +/*! +@brief an iterator value + +@note This structure could easily be a union, but MSVC currently does not allow +unions members with complex constructors, see https://github.com/nlohmann/json/pull/105. +*/ +template struct internal_iterator +{ + /// iterator for JSON objects + typename BasicJsonType::object_t::iterator object_iterator {}; + /// iterator for JSON arrays + typename BasicJsonType::array_t::iterator array_iterator {}; + /// generic iterator for all other types + primitive_iterator_t primitive_iterator {}; +}; +} // namespace detail +} // namespace nlohmann + +// #include + + +#include // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next +#include // conditional, is_const, remove_const + +// #include + +// #include + +// #include + +// #include + +// #include + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +// forward declare, to be able to friend it later on +template class iteration_proxy; +template class iteration_proxy_value; + +/*! +@brief a template for a bidirectional iterator for the @ref basic_json class +This class implements a both iterators (iterator and const_iterator) for the +@ref basic_json class. +@note An iterator is called *initialized* when a pointer to a JSON value has + been set (e.g., by a constructor or a copy assignment). If the iterator is + default-constructed, it is *uninitialized* and most methods are undefined. + **The library uses assertions to detect calls on uninitialized iterators.** +@requirement The class satisfies the following concept requirements: +- +[BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): + The iterator that can be moved can be moved in both directions (i.e. + incremented and decremented). +@since version 1.0.0, simplified in version 2.0.9, change to bidirectional + iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593) +*/ +template +class iter_impl // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions) +{ + /// the iterator with BasicJsonType of different const-ness + using other_iter_impl = iter_impl::value, typename std::remove_const::type, const BasicJsonType>::type>; + /// allow basic_json to access private members + friend other_iter_impl; + friend BasicJsonType; + friend iteration_proxy; + friend iteration_proxy_value; + + using object_t = typename BasicJsonType::object_t; + using array_t = typename BasicJsonType::array_t; + // make sure BasicJsonType is basic_json or const basic_json + static_assert(is_basic_json::type>::value, + "iter_impl only accepts (const) basic_json"); + + public: + + /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17. + /// The C++ Standard has never required user-defined iterators to derive from std::iterator. + /// A user-defined iterator should provide publicly accessible typedefs named + /// iterator_category, value_type, difference_type, pointer, and reference. + /// Note that value_type is required to be non-const, even for constant iterators. + using iterator_category = std::bidirectional_iterator_tag; + + /// the type of the values when the iterator is dereferenced + using value_type = typename BasicJsonType::value_type; + /// a type to represent differences between iterators + using difference_type = typename BasicJsonType::difference_type; + /// defines a pointer to the type iterated over (value_type) + using pointer = typename std::conditional::value, + typename BasicJsonType::const_pointer, + typename BasicJsonType::pointer>::type; + /// defines a reference to the type iterated over (value_type) + using reference = + typename std::conditional::value, + typename BasicJsonType::const_reference, + typename BasicJsonType::reference>::type; + + iter_impl() = default; + ~iter_impl() = default; + iter_impl(iter_impl&&) noexcept = default; + iter_impl& operator=(iter_impl&&) noexcept = default; + + /*! + @brief constructor for a given JSON instance + @param[in] object pointer to a JSON object for this iterator + @pre object != nullptr + @post The iterator is initialized; i.e. `m_object != nullptr`. + */ + explicit iter_impl(pointer object) noexcept : m_object(object) + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + m_it.object_iterator = typename object_t::iterator(); + break; + } + + case value_t::array: + { + m_it.array_iterator = typename array_t::iterator(); + break; + } + + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + m_it.primitive_iterator = primitive_iterator_t(); + break; + } + } + } + + /*! + @note The conventional copy constructor and copy assignment are implicitly + defined. Combined with the following converting constructor and + assignment, they support: (1) copy from iterator to iterator, (2) + copy from const iterator to const iterator, and (3) conversion from + iterator to const iterator. However conversion from const iterator + to iterator is not defined. + */ + + /*! + @brief const copy constructor + @param[in] other const iterator to copy from + @note This copy constructor had to be defined explicitly to circumvent a bug + occurring on msvc v19.0 compiler (VS 2015) debug build. For more + information refer to: https://github.com/nlohmann/json/issues/1608 + */ + iter_impl(const iter_impl& other) noexcept + : m_object(other.m_object), m_it(other.m_it) + {} + + /*! + @brief converting assignment + @param[in] other const iterator to copy from + @return const/non-const iterator + @note It is not checked whether @a other is initialized. + */ + iter_impl& operator=(const iter_impl& other) noexcept + { + if (&other != this) + { + m_object = other.m_object; + m_it = other.m_it; + } + return *this; + } + + /*! + @brief converting constructor + @param[in] other non-const iterator to copy from + @note It is not checked whether @a other is initialized. + */ + iter_impl(const iter_impl::type>& other) noexcept + : m_object(other.m_object), m_it(other.m_it) + {} + + /*! + @brief converting assignment + @param[in] other non-const iterator to copy from + @return const/non-const iterator + @note It is not checked whether @a other is initialized. + */ + iter_impl& operator=(const iter_impl::type>& other) noexcept // NOLINT(cert-oop54-cpp) + { + m_object = other.m_object; + m_it = other.m_it; + return *this; + } + + JSON_PRIVATE_UNLESS_TESTED: + /*! + @brief set the iterator to the first value + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + void set_begin() noexcept + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + m_it.object_iterator = m_object->m_value.object->begin(); + break; + } + + case value_t::array: + { + m_it.array_iterator = m_object->m_value.array->begin(); + break; + } + + case value_t::null: + { + // set to end so begin()==end() is true: null is empty + m_it.primitive_iterator.set_end(); + break; + } + + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + m_it.primitive_iterator.set_begin(); + break; + } + } + } + + /*! + @brief set the iterator past the last value + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + void set_end() noexcept + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + m_it.object_iterator = m_object->m_value.object->end(); + break; + } + + case value_t::array: + { + m_it.array_iterator = m_object->m_value.array->end(); + break; + } + + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + m_it.primitive_iterator.set_end(); + break; + } + } + } + + public: + /*! + @brief return a reference to the value pointed to by the iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + reference operator*() const + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end()); + return m_it.object_iterator->second; + } + + case value_t::array: + { + JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end()); + return *m_it.array_iterator; + } + + case value_t::null: + JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); + + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin())) + { + return *m_object; + } + + JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); + } + } + } + + /*! + @brief dereference the iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + pointer operator->() const + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end()); + return &(m_it.object_iterator->second); + } + + case value_t::array: + { + JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end()); + return &*m_it.array_iterator; + } + + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin())) + { + return m_object; + } + + JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); + } + } + } + + /*! + @brief post-increment (it++) + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl const operator++(int) // NOLINT(readability-const-return-type) + { + auto result = *this; + ++(*this); + return result; + } + + /*! + @brief pre-increment (++it) + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl& operator++() + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + std::advance(m_it.object_iterator, 1); + break; + } + + case value_t::array: + { + std::advance(m_it.array_iterator, 1); + break; + } + + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + ++m_it.primitive_iterator; + break; + } + } + + return *this; + } + + /*! + @brief post-decrement (it--) + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl const operator--(int) // NOLINT(readability-const-return-type) + { + auto result = *this; + --(*this); + return result; + } + + /*! + @brief pre-decrement (--it) + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl& operator--() + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + std::advance(m_it.object_iterator, -1); + break; + } + + case value_t::array: + { + std::advance(m_it.array_iterator, -1); + break; + } + + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + --m_it.primitive_iterator; + break; + } + } + + return *this; + } + + /*! + @brief comparison: equal + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + template < typename IterImpl, detail::enable_if_t < (std::is_same::value || std::is_same::value), std::nullptr_t > = nullptr > + bool operator==(const IterImpl& other) const + { + // if objects are not the same, the comparison is undefined + if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object)) + { + JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", *m_object)); + } + + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + return (m_it.object_iterator == other.m_it.object_iterator); + + case value_t::array: + return (m_it.array_iterator == other.m_it.array_iterator); + + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + return (m_it.primitive_iterator == other.m_it.primitive_iterator); + } + } + + /*! + @brief comparison: not equal + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + template < typename IterImpl, detail::enable_if_t < (std::is_same::value || std::is_same::value), std::nullptr_t > = nullptr > + bool operator!=(const IterImpl& other) const + { + return !operator==(other); + } + + /*! + @brief comparison: smaller + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator<(const iter_impl& other) const + { + // if objects are not the same, the comparison is undefined + if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object)) + { + JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", *m_object)); + } + + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators", *m_object)); + + case value_t::array: + return (m_it.array_iterator < other.m_it.array_iterator); + + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + return (m_it.primitive_iterator < other.m_it.primitive_iterator); + } + } + + /*! + @brief comparison: less than or equal + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator<=(const iter_impl& other) const + { + return !other.operator < (*this); + } + + /*! + @brief comparison: greater than + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator>(const iter_impl& other) const + { + return !operator<=(other); + } + + /*! + @brief comparison: greater than or equal + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator>=(const iter_impl& other) const + { + return !operator<(other); + } + + /*! + @brief add to iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl& operator+=(difference_type i) + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", *m_object)); + + case value_t::array: + { + std::advance(m_it.array_iterator, i); + break; + } + + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + m_it.primitive_iterator += i; + break; + } + } + + return *this; + } + + /*! + @brief subtract from iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl& operator-=(difference_type i) + { + return operator+=(-i); + } + + /*! + @brief add to iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl operator+(difference_type i) const + { + auto result = *this; + result += i; + return result; + } + + /*! + @brief addition of distance and iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + friend iter_impl operator+(difference_type i, const iter_impl& it) + { + auto result = it; + result += i; + return result; + } + + /*! + @brief subtract from iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl operator-(difference_type i) const + { + auto result = *this; + result -= i; + return result; + } + + /*! + @brief return difference + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + difference_type operator-(const iter_impl& other) const + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", *m_object)); + + case value_t::array: + return m_it.array_iterator - other.m_it.array_iterator; + + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + return m_it.primitive_iterator - other.m_it.primitive_iterator; + } + } + + /*! + @brief access to successor + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + reference operator[](difference_type n) const + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators", *m_object)); + + case value_t::array: + return *std::next(m_it.array_iterator, n); + + case value_t::null: + JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); + + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n)) + { + return *m_object; + } + + JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); + } + } + } + + /*! + @brief return the key of an object iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + const typename object_t::key_type& key() const + { + JSON_ASSERT(m_object != nullptr); + + if (JSON_HEDLEY_LIKELY(m_object->is_object())) + { + return m_it.object_iterator->first; + } + + JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators", *m_object)); + } + + /*! + @brief return the value of an iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + reference value() const + { + return operator*(); + } + + JSON_PRIVATE_UNLESS_TESTED: + /// associated JSON instance + pointer m_object = nullptr; + /// the actual iterator of the associated instance + internal_iterator::type> m_it {}; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + + +#include // ptrdiff_t +#include // reverse_iterator +#include // declval + +namespace nlohmann +{ +namespace detail +{ +////////////////////// +// reverse_iterator // +////////////////////// + +/*! +@brief a template for a reverse iterator class + +@tparam Base the base iterator type to reverse. Valid types are @ref +iterator (to create @ref reverse_iterator) and @ref const_iterator (to +create @ref const_reverse_iterator). + +@requirement The class satisfies the following concept requirements: +- +[BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): + The iterator that can be moved can be moved in both directions (i.e. + incremented and decremented). +- [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator): + It is possible to write to the pointed-to element (only if @a Base is + @ref iterator). + +@since version 1.0.0 +*/ +template +class json_reverse_iterator : public std::reverse_iterator +{ + public: + using difference_type = std::ptrdiff_t; + /// shortcut to the reverse iterator adapter + using base_iterator = std::reverse_iterator; + /// the reference type for the pointed-to element + using reference = typename Base::reference; + + /// create reverse iterator from iterator + explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept + : base_iterator(it) {} + + /// create reverse iterator from base class + explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {} + + /// post-increment (it++) + json_reverse_iterator const operator++(int) // NOLINT(readability-const-return-type) + { + return static_cast(base_iterator::operator++(1)); + } + + /// pre-increment (++it) + json_reverse_iterator& operator++() + { + return static_cast(base_iterator::operator++()); + } + + /// post-decrement (it--) + json_reverse_iterator const operator--(int) // NOLINT(readability-const-return-type) + { + return static_cast(base_iterator::operator--(1)); + } + + /// pre-decrement (--it) + json_reverse_iterator& operator--() + { + return static_cast(base_iterator::operator--()); + } + + /// add to iterator + json_reverse_iterator& operator+=(difference_type i) + { + return static_cast(base_iterator::operator+=(i)); + } + + /// add to iterator + json_reverse_iterator operator+(difference_type i) const + { + return static_cast(base_iterator::operator+(i)); + } + + /// subtract from iterator + json_reverse_iterator operator-(difference_type i) const + { + return static_cast(base_iterator::operator-(i)); + } + + /// return difference + difference_type operator-(const json_reverse_iterator& other) const + { + return base_iterator(*this) - base_iterator(other); + } + + /// access to successor + reference operator[](difference_type n) const + { + return *(this->operator+(n)); + } + + /// return the key of an object iterator + auto key() const -> decltype(std::declval().key()) + { + auto it = --this->base(); + return it.key(); + } + + /// return the value of an iterator + reference value() const + { + auto it = --this->base(); + return it.operator * (); + } +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + + +#include // all_of +#include // isdigit +#include // max +#include // accumulate +#include // string +#include // move +#include // vector + +// #include + +// #include + +// #include + +// #include + + +namespace nlohmann +{ + +/// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document +/// @sa https://json.nlohmann.me/api/json_pointer/ +template +class json_pointer +{ + // allow basic_json to access private members + NLOHMANN_BASIC_JSON_TPL_DECLARATION + friend class basic_json; + + public: + /// @brief create JSON pointer + /// @sa https://json.nlohmann.me/api/json_pointer/json_pointer/ + explicit json_pointer(const std::string& s = "") + : reference_tokens(split(s)) + {} + + /// @brief return a string representation of the JSON pointer + /// @sa https://json.nlohmann.me/api/json_pointer/to_string/ + std::string to_string() const + { + return std::accumulate(reference_tokens.begin(), reference_tokens.end(), + std::string{}, + [](const std::string & a, const std::string & b) + { + return a + "/" + detail::escape(b); + }); + } + + /// @brief return a string representation of the JSON pointer + /// @sa https://json.nlohmann.me/api/json_pointer/operator_string/ + operator std::string() const + { + return to_string(); + } + + /// @brief append another JSON pointer at the end of this JSON pointer + /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/ + json_pointer& operator/=(const json_pointer& ptr) + { + reference_tokens.insert(reference_tokens.end(), + ptr.reference_tokens.begin(), + ptr.reference_tokens.end()); + return *this; + } + + /// @brief append an unescaped reference token at the end of this JSON pointer + /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/ + json_pointer& operator/=(std::string token) + { + push_back(std::move(token)); + return *this; + } + + /// @brief append an array index at the end of this JSON pointer + /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/ + json_pointer& operator/=(std::size_t array_idx) + { + return *this /= std::to_string(array_idx); + } + + /// @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer + /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/ + friend json_pointer operator/(const json_pointer& lhs, + const json_pointer& rhs) + { + return json_pointer(lhs) /= rhs; + } + + /// @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer + /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/ + friend json_pointer operator/(const json_pointer& lhs, std::string token) // NOLINT(performance-unnecessary-value-param) + { + return json_pointer(lhs) /= std::move(token); + } + + /// @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer + /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/ + friend json_pointer operator/(const json_pointer& lhs, std::size_t array_idx) + { + return json_pointer(lhs) /= array_idx; + } + + /// @brief returns the parent of this JSON pointer + /// @sa https://json.nlohmann.me/api/json_pointer/parent_pointer/ + json_pointer parent_pointer() const + { + if (empty()) + { + return *this; + } + + json_pointer res = *this; + res.pop_back(); + return res; + } + + /// @brief remove last reference token + /// @sa https://json.nlohmann.me/api/json_pointer/pop_back/ + void pop_back() + { + if (JSON_HEDLEY_UNLIKELY(empty())) + { + JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType())); + } + + reference_tokens.pop_back(); + } + + /// @brief return last reference token + /// @sa https://json.nlohmann.me/api/json_pointer/back/ + const std::string& back() const + { + if (JSON_HEDLEY_UNLIKELY(empty())) + { + JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType())); + } + + return reference_tokens.back(); + } + + /// @brief append an unescaped token at the end of the reference pointer + /// @sa https://json.nlohmann.me/api/json_pointer/push_back/ + void push_back(const std::string& token) + { + reference_tokens.push_back(token); + } + + /// @brief append an unescaped token at the end of the reference pointer + /// @sa https://json.nlohmann.me/api/json_pointer/push_back/ + void push_back(std::string&& token) + { + reference_tokens.push_back(std::move(token)); + } + + /// @brief return whether pointer points to the root document + /// @sa https://json.nlohmann.me/api/json_pointer/empty/ + bool empty() const noexcept + { + return reference_tokens.empty(); + } + + private: + /*! + @param[in] s reference token to be converted into an array index + + @return integer representation of @a s + + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index begins not with a digit + @throw out_of_range.404 if string @a s could not be converted to an integer + @throw out_of_range.410 if an array index exceeds size_type + */ + static typename BasicJsonType::size_type array_index(const std::string& s) + { + using size_type = typename BasicJsonType::size_type; + + // error condition (cf. RFC 6901, Sect. 4) + if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && s[0] == '0')) + { + JSON_THROW(detail::parse_error::create(106, 0, "array index '" + s + "' must not begin with '0'", BasicJsonType())); + } + + // error condition (cf. RFC 6901, Sect. 4) + if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && !(s[0] >= '1' && s[0] <= '9'))) + { + JSON_THROW(detail::parse_error::create(109, 0, "array index '" + s + "' is not a number", BasicJsonType())); + } + + std::size_t processed_chars = 0; + unsigned long long res = 0; // NOLINT(runtime/int) + JSON_TRY + { + res = std::stoull(s, &processed_chars); + } + JSON_CATCH(std::out_of_range&) + { + JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType())); + } + + // check if the string was completely read + if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size())) + { + JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType())); + } + + // only triggered on special platforms (like 32bit), see also + // https://github.com/nlohmann/json/pull/2203 + if (res >= static_cast((std::numeric_limits::max)())) // NOLINT(runtime/int) + { + JSON_THROW(detail::out_of_range::create(410, "array index " + s + " exceeds size_type", BasicJsonType())); // LCOV_EXCL_LINE + } + + return static_cast(res); + } + + JSON_PRIVATE_UNLESS_TESTED: + json_pointer top() const + { + if (JSON_HEDLEY_UNLIKELY(empty())) + { + JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType())); + } + + json_pointer result = *this; + result.reference_tokens = {reference_tokens[0]}; + return result; + } + + private: + /*! + @brief create and return a reference to the pointed to value + + @complexity Linear in the number of reference tokens. + + @throw parse_error.109 if array index is not a number + @throw type_error.313 if value cannot be unflattened + */ + BasicJsonType& get_and_create(BasicJsonType& j) const + { + auto* result = &j; + + // in case no reference tokens exist, return a reference to the JSON value + // j which will be overwritten by a primitive value + for (const auto& reference_token : reference_tokens) + { + switch (result->type()) + { + case detail::value_t::null: + { + if (reference_token == "0") + { + // start a new array if reference token is 0 + result = &result->operator[](0); + } + else + { + // start a new object otherwise + result = &result->operator[](reference_token); + } + break; + } + + case detail::value_t::object: + { + // create an entry in the object + result = &result->operator[](reference_token); + break; + } + + case detail::value_t::array: + { + // create an entry in the array + result = &result->operator[](array_index(reference_token)); + break; + } + + /* + The following code is only reached if there exists a reference + token _and_ the current value is primitive. In this case, we have + an error situation, because primitive values may only occur as + single value; that is, with an empty list of reference tokens. + */ + case detail::value_t::string: + case detail::value_t::boolean: + case detail::value_t::number_integer: + case detail::value_t::number_unsigned: + case detail::value_t::number_float: + case detail::value_t::binary: + case detail::value_t::discarded: + default: + JSON_THROW(detail::type_error::create(313, "invalid value to unflatten", j)); + } + } + + return *result; + } + + /*! + @brief return a reference to the pointed to value + + @note This version does not throw if a value is not present, but tries to + create nested values instead. For instance, calling this function + with pointer `"/this/that"` on a null value is equivalent to calling + `operator[]("this").operator[]("that")` on that value, effectively + changing the null value to an object. + + @param[in] ptr a JSON value + + @return reference to the JSON value pointed to by the JSON pointer + + @complexity Linear in the length of the JSON pointer. + + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.404 if the JSON pointer can not be resolved + */ + BasicJsonType& get_unchecked(BasicJsonType* ptr) const + { + for (const auto& reference_token : reference_tokens) + { + // convert null values to arrays or objects before continuing + if (ptr->is_null()) + { + // check if reference token is a number + const bool nums = + std::all_of(reference_token.begin(), reference_token.end(), + [](const unsigned char x) + { + return std::isdigit(x); + }); + + // change value to array for numbers or "-" or to object otherwise + *ptr = (nums || reference_token == "-") + ? detail::value_t::array + : detail::value_t::object; + } + + switch (ptr->type()) + { + case detail::value_t::object: + { + // use unchecked object access + ptr = &ptr->operator[](reference_token); + break; + } + + case detail::value_t::array: + { + if (reference_token == "-") + { + // explicitly treat "-" as index beyond the end + ptr = &ptr->operator[](ptr->m_value.array->size()); + } + else + { + // convert array index to number; unchecked access + ptr = &ptr->operator[](array_index(reference_token)); + } + break; + } + + case detail::value_t::null: + case detail::value_t::string: + case detail::value_t::boolean: + case detail::value_t::number_integer: + case detail::value_t::number_unsigned: + case detail::value_t::number_float: + case detail::value_t::binary: + case detail::value_t::discarded: + default: + JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); + } + } + + return *ptr; + } + + /*! + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.402 if the array index '-' is used + @throw out_of_range.404 if the JSON pointer can not be resolved + */ + BasicJsonType& get_checked(BasicJsonType* ptr) const + { + for (const auto& reference_token : reference_tokens) + { + switch (ptr->type()) + { + case detail::value_t::object: + { + // note: at performs range check + ptr = &ptr->at(reference_token); + break; + } + + case detail::value_t::array: + { + if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) + { + // "-" always fails the range check + JSON_THROW(detail::out_of_range::create(402, + "array index '-' (" + std::to_string(ptr->m_value.array->size()) + + ") is out of range", *ptr)); + } + + // note: at performs range check + ptr = &ptr->at(array_index(reference_token)); + break; + } + + case detail::value_t::null: + case detail::value_t::string: + case detail::value_t::boolean: + case detail::value_t::number_integer: + case detail::value_t::number_unsigned: + case detail::value_t::number_float: + case detail::value_t::binary: + case detail::value_t::discarded: + default: + JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); + } + } + + return *ptr; + } + + /*! + @brief return a const reference to the pointed to value + + @param[in] ptr a JSON value + + @return const reference to the JSON value pointed to by the JSON + pointer + + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.402 if the array index '-' is used + @throw out_of_range.404 if the JSON pointer can not be resolved + */ + const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const + { + for (const auto& reference_token : reference_tokens) + { + switch (ptr->type()) + { + case detail::value_t::object: + { + // use unchecked object access + ptr = &ptr->operator[](reference_token); + break; + } + + case detail::value_t::array: + { + if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) + { + // "-" cannot be used for const access + JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range", *ptr)); + } + + // use unchecked array access + ptr = &ptr->operator[](array_index(reference_token)); + break; + } + + case detail::value_t::null: + case detail::value_t::string: + case detail::value_t::boolean: + case detail::value_t::number_integer: + case detail::value_t::number_unsigned: + case detail::value_t::number_float: + case detail::value_t::binary: + case detail::value_t::discarded: + default: + JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); + } + } + + return *ptr; + } + + /*! + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.402 if the array index '-' is used + @throw out_of_range.404 if the JSON pointer can not be resolved + */ + const BasicJsonType& get_checked(const BasicJsonType* ptr) const + { + for (const auto& reference_token : reference_tokens) + { + switch (ptr->type()) + { + case detail::value_t::object: + { + // note: at performs range check + ptr = &ptr->at(reference_token); + break; + } + + case detail::value_t::array: + { + if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) + { + // "-" always fails the range check + JSON_THROW(detail::out_of_range::create(402, + "array index '-' (" + std::to_string(ptr->m_value.array->size()) + + ") is out of range", *ptr)); + } + + // note: at performs range check + ptr = &ptr->at(array_index(reference_token)); + break; + } + + case detail::value_t::null: + case detail::value_t::string: + case detail::value_t::boolean: + case detail::value_t::number_integer: + case detail::value_t::number_unsigned: + case detail::value_t::number_float: + case detail::value_t::binary: + case detail::value_t::discarded: + default: + JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); + } + } + + return *ptr; + } + + /*! + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + */ + bool contains(const BasicJsonType* ptr) const + { + for (const auto& reference_token : reference_tokens) + { + switch (ptr->type()) + { + case detail::value_t::object: + { + if (!ptr->contains(reference_token)) + { + // we did not find the key in the object + return false; + } + + ptr = &ptr->operator[](reference_token); + break; + } + + case detail::value_t::array: + { + if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) + { + // "-" always fails the range check + return false; + } + if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 && !("0" <= reference_token && reference_token <= "9"))) + { + // invalid char + return false; + } + if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1)) + { + if (JSON_HEDLEY_UNLIKELY(!('1' <= reference_token[0] && reference_token[0] <= '9'))) + { + // first char should be between '1' and '9' + return false; + } + for (std::size_t i = 1; i < reference_token.size(); i++) + { + if (JSON_HEDLEY_UNLIKELY(!('0' <= reference_token[i] && reference_token[i] <= '9'))) + { + // other char should be between '0' and '9' + return false; + } + } + } + + const auto idx = array_index(reference_token); + if (idx >= ptr->size()) + { + // index out of range + return false; + } + + ptr = &ptr->operator[](idx); + break; + } + + case detail::value_t::null: + case detail::value_t::string: + case detail::value_t::boolean: + case detail::value_t::number_integer: + case detail::value_t::number_unsigned: + case detail::value_t::number_float: + case detail::value_t::binary: + case detail::value_t::discarded: + default: + { + // we do not expect primitive values if there is still a + // reference token to process + return false; + } + } + } + + // no reference token left means we found a primitive value + return true; + } + + /*! + @brief split the string input to reference tokens + + @note This function is only called by the json_pointer constructor. + All exceptions below are documented there. + + @throw parse_error.107 if the pointer is not empty or begins with '/' + @throw parse_error.108 if character '~' is not followed by '0' or '1' + */ + static std::vector split(const std::string& reference_string) + { + std::vector result; + + // special case: empty reference string -> no reference tokens + if (reference_string.empty()) + { + return result; + } + + // check if nonempty reference string begins with slash + if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/')) + { + JSON_THROW(detail::parse_error::create(107, 1, "JSON pointer must be empty or begin with '/' - was: '" + reference_string + "'", BasicJsonType())); + } + + // extract the reference tokens: + // - slash: position of the last read slash (or end of string) + // - start: position after the previous slash + for ( + // search for the first slash after the first character + std::size_t slash = reference_string.find_first_of('/', 1), + // set the beginning of the first reference token + start = 1; + // we can stop if start == 0 (if slash == std::string::npos) + start != 0; + // set the beginning of the next reference token + // (will eventually be 0 if slash == std::string::npos) + start = (slash == std::string::npos) ? 0 : slash + 1, + // find next slash + slash = reference_string.find_first_of('/', start)) + { + // use the text between the beginning of the reference token + // (start) and the last slash (slash). + auto reference_token = reference_string.substr(start, slash - start); + + // check reference tokens are properly escaped + for (std::size_t pos = reference_token.find_first_of('~'); + pos != std::string::npos; + pos = reference_token.find_first_of('~', pos + 1)) + { + JSON_ASSERT(reference_token[pos] == '~'); + + // ~ must be followed by 0 or 1 + if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 || + (reference_token[pos + 1] != '0' && + reference_token[pos + 1] != '1'))) + { + JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'", BasicJsonType())); + } + } + + // finally, store the reference token + detail::unescape(reference_token); + result.push_back(reference_token); + } + + return result; + } + + private: + /*! + @param[in] reference_string the reference string to the current value + @param[in] value the value to consider + @param[in,out] result the result object to insert values to + + @note Empty objects or arrays are flattened to `null`. + */ + static void flatten(const std::string& reference_string, + const BasicJsonType& value, + BasicJsonType& result) + { + switch (value.type()) + { + case detail::value_t::array: + { + if (value.m_value.array->empty()) + { + // flatten empty array as null + result[reference_string] = nullptr; + } + else + { + // iterate array and use index as reference string + for (std::size_t i = 0; i < value.m_value.array->size(); ++i) + { + flatten(reference_string + "/" + std::to_string(i), + value.m_value.array->operator[](i), result); + } + } + break; + } + + case detail::value_t::object: + { + if (value.m_value.object->empty()) + { + // flatten empty object as null + result[reference_string] = nullptr; + } + else + { + // iterate object and use keys as reference string + for (const auto& element : *value.m_value.object) + { + flatten(reference_string + "/" + detail::escape(element.first), element.second, result); + } + } + break; + } + + case detail::value_t::null: + case detail::value_t::string: + case detail::value_t::boolean: + case detail::value_t::number_integer: + case detail::value_t::number_unsigned: + case detail::value_t::number_float: + case detail::value_t::binary: + case detail::value_t::discarded: + default: + { + // add primitive value with its reference string + result[reference_string] = value; + break; + } + } + } + + /*! + @param[in] value flattened JSON + + @return unflattened JSON + + @throw parse_error.109 if array index is not a number + @throw type_error.314 if value is not an object + @throw type_error.315 if object values are not primitive + @throw type_error.313 if value cannot be unflattened + */ + static BasicJsonType + unflatten(const BasicJsonType& value) + { + if (JSON_HEDLEY_UNLIKELY(!value.is_object())) + { + JSON_THROW(detail::type_error::create(314, "only objects can be unflattened", value)); + } + + BasicJsonType result; + + // iterate the JSON object values + for (const auto& element : *value.m_value.object) + { + if (JSON_HEDLEY_UNLIKELY(!element.second.is_primitive())) + { + JSON_THROW(detail::type_error::create(315, "values in object must be primitive", element.second)); + } + + // assign value to reference pointed to by JSON pointer; Note that if + // the JSON pointer is "" (i.e., points to the whole value), function + // get_and_create returns a reference to result itself. An assignment + // will then create a primitive value. + json_pointer(element.first).get_and_create(result) = element.second; + } + + return result; + } + + /*! + @brief compares two JSON pointers for equality + + @param[in] lhs JSON pointer to compare + @param[in] rhs JSON pointer to compare + @return whether @a lhs is equal to @a rhs + + @complexity Linear in the length of the JSON pointer + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + */ + friend bool operator==(json_pointer const& lhs, + json_pointer const& rhs) noexcept + { + return lhs.reference_tokens == rhs.reference_tokens; + } + + /*! + @brief compares two JSON pointers for inequality + + @param[in] lhs JSON pointer to compare + @param[in] rhs JSON pointer to compare + @return whether @a lhs is not equal @a rhs + + @complexity Linear in the length of the JSON pointer + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + */ + friend bool operator!=(json_pointer const& lhs, + json_pointer const& rhs) noexcept + { + return !(lhs == rhs); + } + + /// the reference tokens + std::vector reference_tokens; +}; +} // namespace nlohmann + +// #include + + +#include +#include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template +class json_ref +{ + public: + using value_type = BasicJsonType; + + json_ref(value_type&& value) + : owned_value(std::move(value)) + {} + + json_ref(const value_type& value) + : value_ref(&value) + {} + + json_ref(std::initializer_list init) + : owned_value(init) + {} + + template < + class... Args, + enable_if_t::value, int> = 0 > + json_ref(Args && ... args) + : owned_value(std::forward(args)...) + {} + + // class should be movable only + json_ref(json_ref&&) noexcept = default; + json_ref(const json_ref&) = delete; + json_ref& operator=(const json_ref&) = delete; + json_ref& operator=(json_ref&&) = delete; + ~json_ref() = default; + + value_type moved_or_copied() const + { + if (value_ref == nullptr) + { + return std::move(owned_value); + } + return *value_ref; + } + + value_type const& operator*() const + { + return value_ref ? *value_ref : owned_value; + } + + value_type const* operator->() const + { + return &** this; + } + + private: + mutable value_type owned_value = nullptr; + value_type const* value_ref = nullptr; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + +// #include + +// #include + +// #include + + +#include // reverse +#include // array +#include // isnan, isinf +#include // uint8_t, uint16_t, uint32_t, uint64_t +#include // memcpy +#include // numeric_limits +#include // string +#include // move + +// #include + +// #include + +// #include + + +#include // copy +#include // size_t +#include // back_inserter +#include // shared_ptr, make_shared +#include // basic_string +#include // vector + +#ifndef JSON_NO_IO + #include // streamsize + #include // basic_ostream +#endif // JSON_NO_IO + +// #include + + +namespace nlohmann +{ +namespace detail +{ +/// abstract output adapter interface +template struct output_adapter_protocol +{ + virtual void write_character(CharType c) = 0; + virtual void write_characters(const CharType* s, std::size_t length) = 0; + virtual ~output_adapter_protocol() = default; + + output_adapter_protocol() = default; + output_adapter_protocol(const output_adapter_protocol&) = default; + output_adapter_protocol(output_adapter_protocol&&) noexcept = default; + output_adapter_protocol& operator=(const output_adapter_protocol&) = default; + output_adapter_protocol& operator=(output_adapter_protocol&&) noexcept = default; +}; + +/// a type to simplify interfaces +template +using output_adapter_t = std::shared_ptr>; + +/// output adapter for byte vectors +template> +class output_vector_adapter : public output_adapter_protocol +{ + public: + explicit output_vector_adapter(std::vector& vec) noexcept + : v(vec) + {} + + void write_character(CharType c) override + { + v.push_back(c); + } + + JSON_HEDLEY_NON_NULL(2) + void write_characters(const CharType* s, std::size_t length) override + { + std::copy(s, s + length, std::back_inserter(v)); + } + + private: + std::vector& v; +}; + +#ifndef JSON_NO_IO +/// output adapter for output streams +template +class output_stream_adapter : public output_adapter_protocol +{ + public: + explicit output_stream_adapter(std::basic_ostream& s) noexcept + : stream(s) + {} + + void write_character(CharType c) override + { + stream.put(c); + } + + JSON_HEDLEY_NON_NULL(2) + void write_characters(const CharType* s, std::size_t length) override + { + stream.write(s, static_cast(length)); + } + + private: + std::basic_ostream& stream; +}; +#endif // JSON_NO_IO + +/// output adapter for basic_string +template> +class output_string_adapter : public output_adapter_protocol +{ + public: + explicit output_string_adapter(StringType& s) noexcept + : str(s) + {} + + void write_character(CharType c) override + { + str.push_back(c); + } + + JSON_HEDLEY_NON_NULL(2) + void write_characters(const CharType* s, std::size_t length) override + { + str.append(s, length); + } + + private: + StringType& str; +}; + +template> +class output_adapter +{ + public: + template> + output_adapter(std::vector& vec) + : oa(std::make_shared>(vec)) {} + +#ifndef JSON_NO_IO + output_adapter(std::basic_ostream& s) + : oa(std::make_shared>(s)) {} +#endif // JSON_NO_IO + + output_adapter(StringType& s) + : oa(std::make_shared>(s)) {} + + operator output_adapter_t() + { + return oa; + } + + private: + output_adapter_t oa = nullptr; +}; +} // namespace detail +} // namespace nlohmann + + +namespace nlohmann +{ +namespace detail +{ +/////////////////// +// binary writer // +/////////////////// + +/*! +@brief serialization to CBOR and MessagePack values +*/ +template +class binary_writer +{ + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + using number_float_t = typename BasicJsonType::number_float_t; + + public: + /*! + @brief create a binary writer + + @param[in] adapter output adapter to write to + */ + explicit binary_writer(output_adapter_t adapter) : oa(std::move(adapter)) + { + JSON_ASSERT(oa); + } + + /*! + @param[in] j JSON value to serialize + @pre j.type() == value_t::object + */ + void write_bson(const BasicJsonType& j) + { + switch (j.type()) + { + case value_t::object: + { + write_bson_object(*j.m_value.object); + break; + } + + case value_t::null: + case value_t::array: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name()), j)); + } + } + } + + /*! + @param[in] j JSON value to serialize + */ + void write_cbor(const BasicJsonType& j) + { + switch (j.type()) + { + case value_t::null: + { + oa->write_character(to_char_type(0xF6)); + break; + } + + case value_t::boolean: + { + oa->write_character(j.m_value.boolean + ? to_char_type(0xF5) + : to_char_type(0xF4)); + break; + } + + case value_t::number_integer: + { + if (j.m_value.number_integer >= 0) + { + // CBOR does not differentiate between positive signed + // integers and unsigned integers. Therefore, we used the + // code from the value_t::number_unsigned case here. + if (j.m_value.number_integer <= 0x17) + { + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x18)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x19)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x1A)); + write_number(static_cast(j.m_value.number_integer)); + } + else + { + oa->write_character(to_char_type(0x1B)); + write_number(static_cast(j.m_value.number_integer)); + } + } + else + { + // The conversions below encode the sign in the first + // byte, and the value is converted to a positive number. + const auto positive_number = -1 - j.m_value.number_integer; + if (j.m_value.number_integer >= -24) + { + write_number(static_cast(0x20 + positive_number)); + } + else if (positive_number <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x38)); + write_number(static_cast(positive_number)); + } + else if (positive_number <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x39)); + write_number(static_cast(positive_number)); + } + else if (positive_number <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x3A)); + write_number(static_cast(positive_number)); + } + else + { + oa->write_character(to_char_type(0x3B)); + write_number(static_cast(positive_number)); + } + } + break; + } + + case value_t::number_unsigned: + { + if (j.m_value.number_unsigned <= 0x17) + { + write_number(static_cast(j.m_value.number_unsigned)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x18)); + write_number(static_cast(j.m_value.number_unsigned)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x19)); + write_number(static_cast(j.m_value.number_unsigned)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x1A)); + write_number(static_cast(j.m_value.number_unsigned)); + } + else + { + oa->write_character(to_char_type(0x1B)); + write_number(static_cast(j.m_value.number_unsigned)); + } + break; + } + + case value_t::number_float: + { + if (std::isnan(j.m_value.number_float)) + { + // NaN is 0xf97e00 in CBOR + oa->write_character(to_char_type(0xF9)); + oa->write_character(to_char_type(0x7E)); + oa->write_character(to_char_type(0x00)); + } + else if (std::isinf(j.m_value.number_float)) + { + // Infinity is 0xf97c00, -Infinity is 0xf9fc00 + oa->write_character(to_char_type(0xf9)); + oa->write_character(j.m_value.number_float > 0 ? to_char_type(0x7C) : to_char_type(0xFC)); + oa->write_character(to_char_type(0x00)); + } + else + { + write_compact_float(j.m_value.number_float, detail::input_format_t::cbor); + } + break; + } + + case value_t::string: + { + // step 1: write control byte and the string length + const auto N = j.m_value.string->size(); + if (N <= 0x17) + { + write_number(static_cast(0x60 + N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x78)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x79)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x7A)); + write_number(static_cast(N)); + } + // LCOV_EXCL_START + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x7B)); + write_number(static_cast(N)); + } + // LCOV_EXCL_STOP + + // step 2: write the string + oa->write_characters( + reinterpret_cast(j.m_value.string->c_str()), + j.m_value.string->size()); + break; + } + + case value_t::array: + { + // step 1: write control byte and the array size + const auto N = j.m_value.array->size(); + if (N <= 0x17) + { + write_number(static_cast(0x80 + N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x98)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x99)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x9A)); + write_number(static_cast(N)); + } + // LCOV_EXCL_START + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x9B)); + write_number(static_cast(N)); + } + // LCOV_EXCL_STOP + + // step 2: write each element + for (const auto& el : *j.m_value.array) + { + write_cbor(el); + } + break; + } + + case value_t::binary: + { + if (j.m_value.binary->has_subtype()) + { + if (j.m_value.binary->subtype() <= (std::numeric_limits::max)()) + { + write_number(static_cast(0xd8)); + write_number(static_cast(j.m_value.binary->subtype())); + } + else if (j.m_value.binary->subtype() <= (std::numeric_limits::max)()) + { + write_number(static_cast(0xd9)); + write_number(static_cast(j.m_value.binary->subtype())); + } + else if (j.m_value.binary->subtype() <= (std::numeric_limits::max)()) + { + write_number(static_cast(0xda)); + write_number(static_cast(j.m_value.binary->subtype())); + } + else if (j.m_value.binary->subtype() <= (std::numeric_limits::max)()) + { + write_number(static_cast(0xdb)); + write_number(static_cast(j.m_value.binary->subtype())); + } + } + + // step 1: write control byte and the binary array size + const auto N = j.m_value.binary->size(); + if (N <= 0x17) + { + write_number(static_cast(0x40 + N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x58)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x59)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x5A)); + write_number(static_cast(N)); + } + // LCOV_EXCL_START + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x5B)); + write_number(static_cast(N)); + } + // LCOV_EXCL_STOP + + // step 2: write each element + oa->write_characters( + reinterpret_cast(j.m_value.binary->data()), + N); + + break; + } + + case value_t::object: + { + // step 1: write control byte and the object size + const auto N = j.m_value.object->size(); + if (N <= 0x17) + { + write_number(static_cast(0xA0 + N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0xB8)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0xB9)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0xBA)); + write_number(static_cast(N)); + } + // LCOV_EXCL_START + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0xBB)); + write_number(static_cast(N)); + } + // LCOV_EXCL_STOP + + // step 2: write each element + for (const auto& el : *j.m_value.object) + { + write_cbor(el.first); + write_cbor(el.second); + } + break; + } + + case value_t::discarded: + default: + break; + } + } + + /*! + @param[in] j JSON value to serialize + */ + void write_msgpack(const BasicJsonType& j) + { + switch (j.type()) + { + case value_t::null: // nil + { + oa->write_character(to_char_type(0xC0)); + break; + } + + case value_t::boolean: // true and false + { + oa->write_character(j.m_value.boolean + ? to_char_type(0xC3) + : to_char_type(0xC2)); + break; + } + + case value_t::number_integer: + { + if (j.m_value.number_integer >= 0) + { + // MessagePack does not differentiate between positive + // signed integers and unsigned integers. Therefore, we used + // the code from the value_t::number_unsigned case here. + if (j.m_value.number_unsigned < 128) + { + // positive fixnum + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 8 + oa->write_character(to_char_type(0xCC)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 16 + oa->write_character(to_char_type(0xCD)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 32 + oa->write_character(to_char_type(0xCE)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 64 + oa->write_character(to_char_type(0xCF)); + write_number(static_cast(j.m_value.number_integer)); + } + } + else + { + if (j.m_value.number_integer >= -32) + { + // negative fixnum + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer >= (std::numeric_limits::min)() && + j.m_value.number_integer <= (std::numeric_limits::max)()) + { + // int 8 + oa->write_character(to_char_type(0xD0)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer >= (std::numeric_limits::min)() && + j.m_value.number_integer <= (std::numeric_limits::max)()) + { + // int 16 + oa->write_character(to_char_type(0xD1)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer >= (std::numeric_limits::min)() && + j.m_value.number_integer <= (std::numeric_limits::max)()) + { + // int 32 + oa->write_character(to_char_type(0xD2)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer >= (std::numeric_limits::min)() && + j.m_value.number_integer <= (std::numeric_limits::max)()) + { + // int 64 + oa->write_character(to_char_type(0xD3)); + write_number(static_cast(j.m_value.number_integer)); + } + } + break; + } + + case value_t::number_unsigned: + { + if (j.m_value.number_unsigned < 128) + { + // positive fixnum + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 8 + oa->write_character(to_char_type(0xCC)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 16 + oa->write_character(to_char_type(0xCD)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 32 + oa->write_character(to_char_type(0xCE)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 64 + oa->write_character(to_char_type(0xCF)); + write_number(static_cast(j.m_value.number_integer)); + } + break; + } + + case value_t::number_float: + { + write_compact_float(j.m_value.number_float, detail::input_format_t::msgpack); + break; + } + + case value_t::string: + { + // step 1: write control byte and the string length + const auto N = j.m_value.string->size(); + if (N <= 31) + { + // fixstr + write_number(static_cast(0xA0 | N)); + } + else if (N <= (std::numeric_limits::max)()) + { + // str 8 + oa->write_character(to_char_type(0xD9)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + // str 16 + oa->write_character(to_char_type(0xDA)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + // str 32 + oa->write_character(to_char_type(0xDB)); + write_number(static_cast(N)); + } + + // step 2: write the string + oa->write_characters( + reinterpret_cast(j.m_value.string->c_str()), + j.m_value.string->size()); + break; + } + + case value_t::array: + { + // step 1: write control byte and the array size + const auto N = j.m_value.array->size(); + if (N <= 15) + { + // fixarray + write_number(static_cast(0x90 | N)); + } + else if (N <= (std::numeric_limits::max)()) + { + // array 16 + oa->write_character(to_char_type(0xDC)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + // array 32 + oa->write_character(to_char_type(0xDD)); + write_number(static_cast(N)); + } + + // step 2: write each element + for (const auto& el : *j.m_value.array) + { + write_msgpack(el); + } + break; + } + + case value_t::binary: + { + // step 0: determine if the binary type has a set subtype to + // determine whether or not to use the ext or fixext types + const bool use_ext = j.m_value.binary->has_subtype(); + + // step 1: write control byte and the byte string length + const auto N = j.m_value.binary->size(); + if (N <= (std::numeric_limits::max)()) + { + std::uint8_t output_type{}; + bool fixed = true; + if (use_ext) + { + switch (N) + { + case 1: + output_type = 0xD4; // fixext 1 + break; + case 2: + output_type = 0xD5; // fixext 2 + break; + case 4: + output_type = 0xD6; // fixext 4 + break; + case 8: + output_type = 0xD7; // fixext 8 + break; + case 16: + output_type = 0xD8; // fixext 16 + break; + default: + output_type = 0xC7; // ext 8 + fixed = false; + break; + } + + } + else + { + output_type = 0xC4; // bin 8 + fixed = false; + } + + oa->write_character(to_char_type(output_type)); + if (!fixed) + { + write_number(static_cast(N)); + } + } + else if (N <= (std::numeric_limits::max)()) + { + std::uint8_t output_type = use_ext + ? 0xC8 // ext 16 + : 0xC5; // bin 16 + + oa->write_character(to_char_type(output_type)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + std::uint8_t output_type = use_ext + ? 0xC9 // ext 32 + : 0xC6; // bin 32 + + oa->write_character(to_char_type(output_type)); + write_number(static_cast(N)); + } + + // step 1.5: if this is an ext type, write the subtype + if (use_ext) + { + write_number(static_cast(j.m_value.binary->subtype())); + } + + // step 2: write the byte string + oa->write_characters( + reinterpret_cast(j.m_value.binary->data()), + N); + + break; + } + + case value_t::object: + { + // step 1: write control byte and the object size + const auto N = j.m_value.object->size(); + if (N <= 15) + { + // fixmap + write_number(static_cast(0x80 | (N & 0xF))); + } + else if (N <= (std::numeric_limits::max)()) + { + // map 16 + oa->write_character(to_char_type(0xDE)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + // map 32 + oa->write_character(to_char_type(0xDF)); + write_number(static_cast(N)); + } + + // step 2: write each element + for (const auto& el : *j.m_value.object) + { + write_msgpack(el.first); + write_msgpack(el.second); + } + break; + } + + case value_t::discarded: + default: + break; + } + } + + /*! + @param[in] j JSON value to serialize + @param[in] use_count whether to use '#' prefixes (optimized format) + @param[in] use_type whether to use '$' prefixes (optimized format) + @param[in] add_prefix whether prefixes need to be used for this value + */ + void write_ubjson(const BasicJsonType& j, const bool use_count, + const bool use_type, const bool add_prefix = true) + { + switch (j.type()) + { + case value_t::null: + { + if (add_prefix) + { + oa->write_character(to_char_type('Z')); + } + break; + } + + case value_t::boolean: + { + if (add_prefix) + { + oa->write_character(j.m_value.boolean + ? to_char_type('T') + : to_char_type('F')); + } + break; + } + + case value_t::number_integer: + { + write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix); + break; + } + + case value_t::number_unsigned: + { + write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix); + break; + } + + case value_t::number_float: + { + write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix); + break; + } + + case value_t::string: + { + if (add_prefix) + { + oa->write_character(to_char_type('S')); + } + write_number_with_ubjson_prefix(j.m_value.string->size(), true); + oa->write_characters( + reinterpret_cast(j.m_value.string->c_str()), + j.m_value.string->size()); + break; + } + + case value_t::array: + { + if (add_prefix) + { + oa->write_character(to_char_type('[')); + } + + bool prefix_required = true; + if (use_type && !j.m_value.array->empty()) + { + JSON_ASSERT(use_count); + const CharType first_prefix = ubjson_prefix(j.front()); + const bool same_prefix = std::all_of(j.begin() + 1, j.end(), + [this, first_prefix](const BasicJsonType & v) + { + return ubjson_prefix(v) == first_prefix; + }); + + if (same_prefix) + { + prefix_required = false; + oa->write_character(to_char_type('$')); + oa->write_character(first_prefix); + } + } + + if (use_count) + { + oa->write_character(to_char_type('#')); + write_number_with_ubjson_prefix(j.m_value.array->size(), true); + } + + for (const auto& el : *j.m_value.array) + { + write_ubjson(el, use_count, use_type, prefix_required); + } + + if (!use_count) + { + oa->write_character(to_char_type(']')); + } + + break; + } + + case value_t::binary: + { + if (add_prefix) + { + oa->write_character(to_char_type('[')); + } + + if (use_type && !j.m_value.binary->empty()) + { + JSON_ASSERT(use_count); + oa->write_character(to_char_type('$')); + oa->write_character('U'); + } + + if (use_count) + { + oa->write_character(to_char_type('#')); + write_number_with_ubjson_prefix(j.m_value.binary->size(), true); + } + + if (use_type) + { + oa->write_characters( + reinterpret_cast(j.m_value.binary->data()), + j.m_value.binary->size()); + } + else + { + for (size_t i = 0; i < j.m_value.binary->size(); ++i) + { + oa->write_character(to_char_type('U')); + oa->write_character(j.m_value.binary->data()[i]); + } + } + + if (!use_count) + { + oa->write_character(to_char_type(']')); + } + + break; + } + + case value_t::object: + { + if (add_prefix) + { + oa->write_character(to_char_type('{')); + } + + bool prefix_required = true; + if (use_type && !j.m_value.object->empty()) + { + JSON_ASSERT(use_count); + const CharType first_prefix = ubjson_prefix(j.front()); + const bool same_prefix = std::all_of(j.begin(), j.end(), + [this, first_prefix](const BasicJsonType & v) + { + return ubjson_prefix(v) == first_prefix; + }); + + if (same_prefix) + { + prefix_required = false; + oa->write_character(to_char_type('$')); + oa->write_character(first_prefix); + } + } + + if (use_count) + { + oa->write_character(to_char_type('#')); + write_number_with_ubjson_prefix(j.m_value.object->size(), true); + } + + for (const auto& el : *j.m_value.object) + { + write_number_with_ubjson_prefix(el.first.size(), true); + oa->write_characters( + reinterpret_cast(el.first.c_str()), + el.first.size()); + write_ubjson(el.second, use_count, use_type, prefix_required); + } + + if (!use_count) + { + oa->write_character(to_char_type('}')); + } + + break; + } + + case value_t::discarded: + default: + break; + } + } + + private: + ////////// + // BSON // + ////////// + + /*! + @return The size of a BSON document entry header, including the id marker + and the entry name size (and its null-terminator). + */ + static std::size_t calc_bson_entry_header_size(const string_t& name, const BasicJsonType& j) + { + const auto it = name.find(static_cast(0)); + if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos)) + { + JSON_THROW(out_of_range::create(409, "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")", j)); + static_cast(j); + } + + return /*id*/ 1ul + name.size() + /*zero-terminator*/1u; + } + + /*! + @brief Writes the given @a element_type and @a name to the output adapter + */ + void write_bson_entry_header(const string_t& name, + const std::uint8_t element_type) + { + oa->write_character(to_char_type(element_type)); // boolean + oa->write_characters( + reinterpret_cast(name.c_str()), + name.size() + 1u); + } + + /*! + @brief Writes a BSON element with key @a name and boolean value @a value + */ + void write_bson_boolean(const string_t& name, + const bool value) + { + write_bson_entry_header(name, 0x08); + oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00)); + } + + /*! + @brief Writes a BSON element with key @a name and double value @a value + */ + void write_bson_double(const string_t& name, + const double value) + { + write_bson_entry_header(name, 0x01); + write_number(value); + } + + /*! + @return The size of the BSON-encoded string in @a value + */ + static std::size_t calc_bson_string_size(const string_t& value) + { + return sizeof(std::int32_t) + value.size() + 1ul; + } + + /*! + @brief Writes a BSON element with key @a name and string value @a value + */ + void write_bson_string(const string_t& name, + const string_t& value) + { + write_bson_entry_header(name, 0x02); + + write_number(static_cast(value.size() + 1ul)); + oa->write_characters( + reinterpret_cast(value.c_str()), + value.size() + 1); + } + + /*! + @brief Writes a BSON element with key @a name and null value + */ + void write_bson_null(const string_t& name) + { + write_bson_entry_header(name, 0x0A); + } + + /*! + @return The size of the BSON-encoded integer @a value + */ + static std::size_t calc_bson_integer_size(const std::int64_t value) + { + return (std::numeric_limits::min)() <= value && value <= (std::numeric_limits::max)() + ? sizeof(std::int32_t) + : sizeof(std::int64_t); + } + + /*! + @brief Writes a BSON element with key @a name and integer @a value + */ + void write_bson_integer(const string_t& name, + const std::int64_t value) + { + if ((std::numeric_limits::min)() <= value && value <= (std::numeric_limits::max)()) + { + write_bson_entry_header(name, 0x10); // int32 + write_number(static_cast(value)); + } + else + { + write_bson_entry_header(name, 0x12); // int64 + write_number(static_cast(value)); + } + } + + /*! + @return The size of the BSON-encoded unsigned integer in @a j + */ + static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept + { + return (value <= static_cast((std::numeric_limits::max)())) + ? sizeof(std::int32_t) + : sizeof(std::int64_t); + } + + /*! + @brief Writes a BSON element with key @a name and unsigned @a value + */ + void write_bson_unsigned(const string_t& name, + const BasicJsonType& j) + { + if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + write_bson_entry_header(name, 0x10 /* int32 */); + write_number(static_cast(j.m_value.number_unsigned)); + } + else if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + write_bson_entry_header(name, 0x12 /* int64 */); + write_number(static_cast(j.m_value.number_unsigned)); + } + else + { + JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(j.m_value.number_unsigned) + " cannot be represented by BSON as it does not fit int64", j)); + } + } + + /*! + @brief Writes a BSON element with key @a name and object @a value + */ + void write_bson_object_entry(const string_t& name, + const typename BasicJsonType::object_t& value) + { + write_bson_entry_header(name, 0x03); // object + write_bson_object(value); + } + + /*! + @return The size of the BSON-encoded array @a value + */ + static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value) + { + std::size_t array_index = 0ul; + + const std::size_t embedded_document_size = std::accumulate(std::begin(value), std::end(value), static_cast(0), [&array_index](std::size_t result, const typename BasicJsonType::array_t::value_type & el) + { + return result + calc_bson_element_size(std::to_string(array_index++), el); + }); + + return sizeof(std::int32_t) + embedded_document_size + 1ul; + } + + /*! + @return The size of the BSON-encoded binary array @a value + */ + static std::size_t calc_bson_binary_size(const typename BasicJsonType::binary_t& value) + { + return sizeof(std::int32_t) + value.size() + 1ul; + } + + /*! + @brief Writes a BSON element with key @a name and array @a value + */ + void write_bson_array(const string_t& name, + const typename BasicJsonType::array_t& value) + { + write_bson_entry_header(name, 0x04); // array + write_number(static_cast(calc_bson_array_size(value))); + + std::size_t array_index = 0ul; + + for (const auto& el : value) + { + write_bson_element(std::to_string(array_index++), el); + } + + oa->write_character(to_char_type(0x00)); + } + + /*! + @brief Writes a BSON element with key @a name and binary value @a value + */ + void write_bson_binary(const string_t& name, + const binary_t& value) + { + write_bson_entry_header(name, 0x05); + + write_number(static_cast(value.size())); + write_number(value.has_subtype() ? static_cast(value.subtype()) : static_cast(0x00)); + + oa->write_characters(reinterpret_cast(value.data()), value.size()); + } + + /*! + @brief Calculates the size necessary to serialize the JSON value @a j with its @a name + @return The calculated size for the BSON document entry for @a j with the given @a name. + */ + static std::size_t calc_bson_element_size(const string_t& name, + const BasicJsonType& j) + { + const auto header_size = calc_bson_entry_header_size(name, j); + switch (j.type()) + { + case value_t::object: + return header_size + calc_bson_object_size(*j.m_value.object); + + case value_t::array: + return header_size + calc_bson_array_size(*j.m_value.array); + + case value_t::binary: + return header_size + calc_bson_binary_size(*j.m_value.binary); + + case value_t::boolean: + return header_size + 1ul; + + case value_t::number_float: + return header_size + 8ul; + + case value_t::number_integer: + return header_size + calc_bson_integer_size(j.m_value.number_integer); + + case value_t::number_unsigned: + return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned); + + case value_t::string: + return header_size + calc_bson_string_size(*j.m_value.string); + + case value_t::null: + return header_size + 0ul; + + // LCOV_EXCL_START + case value_t::discarded: + default: + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) + return 0ul; + // LCOV_EXCL_STOP + } + } + + /*! + @brief Serializes the JSON value @a j to BSON and associates it with the + key @a name. + @param name The name to associate with the JSON entity @a j within the + current BSON document + */ + void write_bson_element(const string_t& name, + const BasicJsonType& j) + { + switch (j.type()) + { + case value_t::object: + return write_bson_object_entry(name, *j.m_value.object); + + case value_t::array: + return write_bson_array(name, *j.m_value.array); + + case value_t::binary: + return write_bson_binary(name, *j.m_value.binary); + + case value_t::boolean: + return write_bson_boolean(name, j.m_value.boolean); + + case value_t::number_float: + return write_bson_double(name, j.m_value.number_float); + + case value_t::number_integer: + return write_bson_integer(name, j.m_value.number_integer); + + case value_t::number_unsigned: + return write_bson_unsigned(name, j); + + case value_t::string: + return write_bson_string(name, *j.m_value.string); + + case value_t::null: + return write_bson_null(name); + + // LCOV_EXCL_START + case value_t::discarded: + default: + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) + return; + // LCOV_EXCL_STOP + } + } + + /*! + @brief Calculates the size of the BSON serialization of the given + JSON-object @a j. + @param[in] value JSON value to serialize + @pre value.type() == value_t::object + */ + static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value) + { + std::size_t document_size = std::accumulate(value.begin(), value.end(), static_cast(0), + [](size_t result, const typename BasicJsonType::object_t::value_type & el) + { + return result += calc_bson_element_size(el.first, el.second); + }); + + return sizeof(std::int32_t) + document_size + 1ul; + } + + /*! + @param[in] value JSON value to serialize + @pre value.type() == value_t::object + */ + void write_bson_object(const typename BasicJsonType::object_t& value) + { + write_number(static_cast(calc_bson_object_size(value))); + + for (const auto& el : value) + { + write_bson_element(el.first, el.second); + } + + oa->write_character(to_char_type(0x00)); + } + + ////////// + // CBOR // + ////////// + + static constexpr CharType get_cbor_float_prefix(float /*unused*/) + { + return to_char_type(0xFA); // Single-Precision Float + } + + static constexpr CharType get_cbor_float_prefix(double /*unused*/) + { + return to_char_type(0xFB); // Double-Precision Float + } + + ///////////// + // MsgPack // + ///////////// + + static constexpr CharType get_msgpack_float_prefix(float /*unused*/) + { + return to_char_type(0xCA); // float 32 + } + + static constexpr CharType get_msgpack_float_prefix(double /*unused*/) + { + return to_char_type(0xCB); // float 64 + } + + //////////// + // UBJSON // + //////////// + + // UBJSON: write number (floating point) + template::value, int>::type = 0> + void write_number_with_ubjson_prefix(const NumberType n, + const bool add_prefix) + { + if (add_prefix) + { + oa->write_character(get_ubjson_float_prefix(n)); + } + write_number(n); + } + + // UBJSON: write number (unsigned integer) + template::value, int>::type = 0> + void write_number_with_ubjson_prefix(const NumberType n, + const bool add_prefix) + { + if (n <= static_cast((std::numeric_limits::max)())) + { + if (add_prefix) + { + oa->write_character(to_char_type('i')); // int8 + } + write_number(static_cast(n)); + } + else if (n <= (std::numeric_limits::max)()) + { + if (add_prefix) + { + oa->write_character(to_char_type('U')); // uint8 + } + write_number(static_cast(n)); + } + else if (n <= static_cast((std::numeric_limits::max)())) + { + if (add_prefix) + { + oa->write_character(to_char_type('I')); // int16 + } + write_number(static_cast(n)); + } + else if (n <= static_cast((std::numeric_limits::max)())) + { + if (add_prefix) + { + oa->write_character(to_char_type('l')); // int32 + } + write_number(static_cast(n)); + } + else if (n <= static_cast((std::numeric_limits::max)())) + { + if (add_prefix) + { + oa->write_character(to_char_type('L')); // int64 + } + write_number(static_cast(n)); + } + else + { + if (add_prefix) + { + oa->write_character(to_char_type('H')); // high-precision number + } + + const auto number = BasicJsonType(n).dump(); + write_number_with_ubjson_prefix(number.size(), true); + for (std::size_t i = 0; i < number.size(); ++i) + { + oa->write_character(to_char_type(static_cast(number[i]))); + } + } + } + + // UBJSON: write number (signed integer) + template < typename NumberType, typename std::enable_if < + std::is_signed::value&& + !std::is_floating_point::value, int >::type = 0 > + void write_number_with_ubjson_prefix(const NumberType n, + const bool add_prefix) + { + if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) + { + if (add_prefix) + { + oa->write_character(to_char_type('i')); // int8 + } + write_number(static_cast(n)); + } + else if (static_cast((std::numeric_limits::min)()) <= n && n <= static_cast((std::numeric_limits::max)())) + { + if (add_prefix) + { + oa->write_character(to_char_type('U')); // uint8 + } + write_number(static_cast(n)); + } + else if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) + { + if (add_prefix) + { + oa->write_character(to_char_type('I')); // int16 + } + write_number(static_cast(n)); + } + else if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) + { + if (add_prefix) + { + oa->write_character(to_char_type('l')); // int32 + } + write_number(static_cast(n)); + } + else if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) + { + if (add_prefix) + { + oa->write_character(to_char_type('L')); // int64 + } + write_number(static_cast(n)); + } + // LCOV_EXCL_START + else + { + if (add_prefix) + { + oa->write_character(to_char_type('H')); // high-precision number + } + + const auto number = BasicJsonType(n).dump(); + write_number_with_ubjson_prefix(number.size(), true); + for (std::size_t i = 0; i < number.size(); ++i) + { + oa->write_character(to_char_type(static_cast(number[i]))); + } + } + // LCOV_EXCL_STOP + } + + /*! + @brief determine the type prefix of container values + */ + CharType ubjson_prefix(const BasicJsonType& j) const noexcept + { + switch (j.type()) + { + case value_t::null: + return 'Z'; + + case value_t::boolean: + return j.m_value.boolean ? 'T' : 'F'; + + case value_t::number_integer: + { + if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) + { + return 'i'; + } + if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) + { + return 'U'; + } + if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) + { + return 'I'; + } + if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) + { + return 'l'; + } + if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) + { + return 'L'; + } + // anything else is treated as high-precision number + return 'H'; // LCOV_EXCL_LINE + } + + case value_t::number_unsigned: + { + if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + return 'i'; + } + if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + return 'U'; + } + if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + return 'I'; + } + if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + return 'l'; + } + if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + return 'L'; + } + // anything else is treated as high-precision number + return 'H'; // LCOV_EXCL_LINE + } + + case value_t::number_float: + return get_ubjson_float_prefix(j.m_value.number_float); + + case value_t::string: + return 'S'; + + case value_t::array: // fallthrough + case value_t::binary: + return '['; + + case value_t::object: + return '{'; + + case value_t::discarded: + default: // discarded values + return 'N'; + } + } + + static constexpr CharType get_ubjson_float_prefix(float /*unused*/) + { + return 'd'; // float 32 + } + + static constexpr CharType get_ubjson_float_prefix(double /*unused*/) + { + return 'D'; // float 64 + } + + /////////////////////// + // Utility functions // + /////////////////////// + + /* + @brief write a number to output input + @param[in] n number of type @a NumberType + @tparam NumberType the type of the number + @tparam OutputIsLittleEndian Set to true if output data is + required to be little endian + + @note This function needs to respect the system's endianness, because bytes + in CBOR, MessagePack, and UBJSON are stored in network order (big + endian) and therefore need reordering on little endian systems. + */ + template + void write_number(const NumberType n) + { + // step 1: write number to array of length NumberType + std::array vec{}; + std::memcpy(vec.data(), &n, sizeof(NumberType)); + + // step 2: write array to output (with possible reordering) + if (is_little_endian != OutputIsLittleEndian) + { + // reverse byte order prior to conversion if necessary + std::reverse(vec.begin(), vec.end()); + } + + oa->write_characters(vec.data(), sizeof(NumberType)); + } + + void write_compact_float(const number_float_t n, detail::input_format_t format) + { +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif + if (static_cast(n) >= static_cast(std::numeric_limits::lowest()) && + static_cast(n) <= static_cast((std::numeric_limits::max)()) && + static_cast(static_cast(n)) == static_cast(n)) + { + oa->write_character(format == detail::input_format_t::cbor + ? get_cbor_float_prefix(static_cast(n)) + : get_msgpack_float_prefix(static_cast(n))); + write_number(static_cast(n)); + } + else + { + oa->write_character(format == detail::input_format_t::cbor + ? get_cbor_float_prefix(n) + : get_msgpack_float_prefix(n)); + write_number(n); + } +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif + } + + public: + // The following to_char_type functions are implement the conversion + // between uint8_t and CharType. In case CharType is not unsigned, + // such a conversion is required to allow values greater than 128. + // See for a discussion. + template < typename C = CharType, + enable_if_t < std::is_signed::value && std::is_signed::value > * = nullptr > + static constexpr CharType to_char_type(std::uint8_t x) noexcept + { + return *reinterpret_cast(&x); + } + + template < typename C = CharType, + enable_if_t < std::is_signed::value && std::is_unsigned::value > * = nullptr > + static CharType to_char_type(std::uint8_t x) noexcept + { + static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t"); + static_assert(std::is_trivial::value, "CharType must be trivial"); + CharType result; + std::memcpy(&result, &x, sizeof(x)); + return result; + } + + template::value>* = nullptr> + static constexpr CharType to_char_type(std::uint8_t x) noexcept + { + return x; + } + + template < typename InputCharType, typename C = CharType, + enable_if_t < + std::is_signed::value && + std::is_signed::value && + std::is_same::type>::value + > * = nullptr > + static constexpr CharType to_char_type(InputCharType x) noexcept + { + return x; + } + + private: + /// whether we can assume little endianness + const bool is_little_endian = little_endianness(); + + /// the output + output_adapter_t oa = nullptr; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + + +#include // reverse, remove, fill, find, none_of +#include // array +#include // localeconv, lconv +#include // labs, isfinite, isnan, signbit +#include // size_t, ptrdiff_t +#include // uint8_t +#include // snprintf +#include // numeric_limits +#include // string, char_traits +#include // setfill, setw +#include // stringstream +#include // is_same +#include // move + +// #include + + +#include // array +#include // signbit, isfinite +#include // intN_t, uintN_t +#include // memcpy, memmove +#include // numeric_limits +#include // conditional + +// #include + + +namespace nlohmann +{ +namespace detail +{ + +/*! +@brief implements the Grisu2 algorithm for binary to decimal floating-point +conversion. + +This implementation is a slightly modified version of the reference +implementation which may be obtained from +http://florian.loitsch.com/publications (bench.tar.gz). + +The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch. + +For a detailed description of the algorithm see: + +[1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with + Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming + Language Design and Implementation, PLDI 2010 +[2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately", + Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language + Design and Implementation, PLDI 1996 +*/ +namespace dtoa_impl +{ + +template +Target reinterpret_bits(const Source source) +{ + static_assert(sizeof(Target) == sizeof(Source), "size mismatch"); + + Target target; + std::memcpy(&target, &source, sizeof(Source)); + return target; +} + +struct diyfp // f * 2^e +{ + static constexpr int kPrecision = 64; // = q + + std::uint64_t f = 0; + int e = 0; + + constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {} + + /*! + @brief returns x - y + @pre x.e == y.e and x.f >= y.f + */ + static diyfp sub(const diyfp& x, const diyfp& y) noexcept + { + JSON_ASSERT(x.e == y.e); + JSON_ASSERT(x.f >= y.f); + + return {x.f - y.f, x.e}; + } + + /*! + @brief returns x * y + @note The result is rounded. (Only the upper q bits are returned.) + */ + static diyfp mul(const diyfp& x, const diyfp& y) noexcept + { + static_assert(kPrecision == 64, "internal error"); + + // Computes: + // f = round((x.f * y.f) / 2^q) + // e = x.e + y.e + q + + // Emulate the 64-bit * 64-bit multiplication: + // + // p = u * v + // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi) + // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi ) + // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 ) + // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 ) + // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3) + // = (p0_lo ) + 2^32 (Q ) + 2^64 (H ) + // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H ) + // + // (Since Q might be larger than 2^32 - 1) + // + // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H) + // + // (Q_hi + H does not overflow a 64-bit int) + // + // = p_lo + 2^64 p_hi + + const std::uint64_t u_lo = x.f & 0xFFFFFFFFu; + const std::uint64_t u_hi = x.f >> 32u; + const std::uint64_t v_lo = y.f & 0xFFFFFFFFu; + const std::uint64_t v_hi = y.f >> 32u; + + const std::uint64_t p0 = u_lo * v_lo; + const std::uint64_t p1 = u_lo * v_hi; + const std::uint64_t p2 = u_hi * v_lo; + const std::uint64_t p3 = u_hi * v_hi; + + const std::uint64_t p0_hi = p0 >> 32u; + const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu; + const std::uint64_t p1_hi = p1 >> 32u; + const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu; + const std::uint64_t p2_hi = p2 >> 32u; + + std::uint64_t Q = p0_hi + p1_lo + p2_lo; + + // The full product might now be computed as + // + // p_hi = p3 + p2_hi + p1_hi + (Q >> 32) + // p_lo = p0_lo + (Q << 32) + // + // But in this particular case here, the full p_lo is not required. + // Effectively we only need to add the highest bit in p_lo to p_hi (and + // Q_hi + 1 does not overflow). + + Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up + + const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u); + + return {h, x.e + y.e + 64}; + } + + /*! + @brief normalize x such that the significand is >= 2^(q-1) + @pre x.f != 0 + */ + static diyfp normalize(diyfp x) noexcept + { + JSON_ASSERT(x.f != 0); + + while ((x.f >> 63u) == 0) + { + x.f <<= 1u; + x.e--; + } + + return x; + } + + /*! + @brief normalize x such that the result has the exponent E + @pre e >= x.e and the upper e - x.e bits of x.f must be zero. + */ + static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept + { + const int delta = x.e - target_exponent; + + JSON_ASSERT(delta >= 0); + JSON_ASSERT(((x.f << delta) >> delta) == x.f); + + return {x.f << delta, target_exponent}; + } +}; + +struct boundaries +{ + diyfp w; + diyfp minus; + diyfp plus; +}; + +/*! +Compute the (normalized) diyfp representing the input number 'value' and its +boundaries. + +@pre value must be finite and positive +*/ +template +boundaries compute_boundaries(FloatType value) +{ + JSON_ASSERT(std::isfinite(value)); + JSON_ASSERT(value > 0); + + // Convert the IEEE representation into a diyfp. + // + // If v is denormal: + // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1)) + // If v is normalized: + // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1)) + + static_assert(std::numeric_limits::is_iec559, + "internal error: dtoa_short requires an IEEE-754 floating-point implementation"); + + constexpr int kPrecision = std::numeric_limits::digits; // = p (includes the hidden bit) + constexpr int kBias = std::numeric_limits::max_exponent - 1 + (kPrecision - 1); + constexpr int kMinExp = 1 - kBias; + constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1) + + using bits_type = typename std::conditional::type; + + const auto bits = static_cast(reinterpret_bits(value)); + const std::uint64_t E = bits >> (kPrecision - 1); + const std::uint64_t F = bits & (kHiddenBit - 1); + + const bool is_denormal = E == 0; + const diyfp v = is_denormal + ? diyfp(F, kMinExp) + : diyfp(F + kHiddenBit, static_cast(E) - kBias); + + // Compute the boundaries m- and m+ of the floating-point value + // v = f * 2^e. + // + // Determine v- and v+, the floating-point predecessor and successor if v, + // respectively. + // + // v- = v - 2^e if f != 2^(p-1) or e == e_min (A) + // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B) + // + // v+ = v + 2^e + // + // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_ + // between m- and m+ round to v, regardless of how the input rounding + // algorithm breaks ties. + // + // ---+-------------+-------------+-------------+-------------+--- (A) + // v- m- v m+ v+ + // + // -----------------+------+------+-------------+-------------+--- (B) + // v- m- v m+ v+ + + const bool lower_boundary_is_closer = F == 0 && E > 1; + const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1); + const diyfp m_minus = lower_boundary_is_closer + ? diyfp(4 * v.f - 1, v.e - 2) // (B) + : diyfp(2 * v.f - 1, v.e - 1); // (A) + + // Determine the normalized w+ = m+. + const diyfp w_plus = diyfp::normalize(m_plus); + + // Determine w- = m- such that e_(w-) = e_(w+). + const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e); + + return {diyfp::normalize(v), w_minus, w_plus}; +} + +// Given normalized diyfp w, Grisu needs to find a (normalized) cached +// power-of-ten c, such that the exponent of the product c * w = f * 2^e lies +// within a certain range [alpha, gamma] (Definition 3.2 from [1]) +// +// alpha <= e = e_c + e_w + q <= gamma +// +// or +// +// f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q +// <= f_c * f_w * 2^gamma +// +// Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies +// +// 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma +// +// or +// +// 2^(q - 2 + alpha) <= c * w < 2^(q + gamma) +// +// The choice of (alpha,gamma) determines the size of the table and the form of +// the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well +// in practice: +// +// The idea is to cut the number c * w = f * 2^e into two parts, which can be +// processed independently: An integral part p1, and a fractional part p2: +// +// f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e +// = (f div 2^-e) + (f mod 2^-e) * 2^e +// = p1 + p2 * 2^e +// +// The conversion of p1 into decimal form requires a series of divisions and +// modulos by (a power of) 10. These operations are faster for 32-bit than for +// 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be +// achieved by choosing +// +// -e >= 32 or e <= -32 := gamma +// +// In order to convert the fractional part +// +// p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ... +// +// into decimal form, the fraction is repeatedly multiplied by 10 and the digits +// d[-i] are extracted in order: +// +// (10 * p2) div 2^-e = d[-1] +// (10 * p2) mod 2^-e = d[-2] / 10^1 + ... +// +// The multiplication by 10 must not overflow. It is sufficient to choose +// +// 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64. +// +// Since p2 = f mod 2^-e < 2^-e, +// +// -e <= 60 or e >= -60 := alpha + +constexpr int kAlpha = -60; +constexpr int kGamma = -32; + +struct cached_power // c = f * 2^e ~= 10^k +{ + std::uint64_t f; + int e; + int k; +}; + +/*! +For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached +power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c +satisfies (Definition 3.2 from [1]) + + alpha <= e_c + e + q <= gamma. +*/ +inline cached_power get_cached_power_for_binary_exponent(int e) +{ + // Now + // + // alpha <= e_c + e + q <= gamma (1) + // ==> f_c * 2^alpha <= c * 2^e * 2^q + // + // and since the c's are normalized, 2^(q-1) <= f_c, + // + // ==> 2^(q - 1 + alpha) <= c * 2^(e + q) + // ==> 2^(alpha - e - 1) <= c + // + // If c were an exact power of ten, i.e. c = 10^k, one may determine k as + // + // k = ceil( log_10( 2^(alpha - e - 1) ) ) + // = ceil( (alpha - e - 1) * log_10(2) ) + // + // From the paper: + // "In theory the result of the procedure could be wrong since c is rounded, + // and the computation itself is approximated [...]. In practice, however, + // this simple function is sufficient." + // + // For IEEE double precision floating-point numbers converted into + // normalized diyfp's w = f * 2^e, with q = 64, + // + // e >= -1022 (min IEEE exponent) + // -52 (p - 1) + // -52 (p - 1, possibly normalize denormal IEEE numbers) + // -11 (normalize the diyfp) + // = -1137 + // + // and + // + // e <= +1023 (max IEEE exponent) + // -52 (p - 1) + // -11 (normalize the diyfp) + // = 960 + // + // This binary exponent range [-1137,960] results in a decimal exponent + // range [-307,324]. One does not need to store a cached power for each + // k in this range. For each such k it suffices to find a cached power + // such that the exponent of the product lies in [alpha,gamma]. + // This implies that the difference of the decimal exponents of adjacent + // table entries must be less than or equal to + // + // floor( (gamma - alpha) * log_10(2) ) = 8. + // + // (A smaller distance gamma-alpha would require a larger table.) + + // NB: + // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34. + + constexpr int kCachedPowersMinDecExp = -300; + constexpr int kCachedPowersDecStep = 8; + + static constexpr std::array kCachedPowers = + { + { + { 0xAB70FE17C79AC6CA, -1060, -300 }, + { 0xFF77B1FCBEBCDC4F, -1034, -292 }, + { 0xBE5691EF416BD60C, -1007, -284 }, + { 0x8DD01FAD907FFC3C, -980, -276 }, + { 0xD3515C2831559A83, -954, -268 }, + { 0x9D71AC8FADA6C9B5, -927, -260 }, + { 0xEA9C227723EE8BCB, -901, -252 }, + { 0xAECC49914078536D, -874, -244 }, + { 0x823C12795DB6CE57, -847, -236 }, + { 0xC21094364DFB5637, -821, -228 }, + { 0x9096EA6F3848984F, -794, -220 }, + { 0xD77485CB25823AC7, -768, -212 }, + { 0xA086CFCD97BF97F4, -741, -204 }, + { 0xEF340A98172AACE5, -715, -196 }, + { 0xB23867FB2A35B28E, -688, -188 }, + { 0x84C8D4DFD2C63F3B, -661, -180 }, + { 0xC5DD44271AD3CDBA, -635, -172 }, + { 0x936B9FCEBB25C996, -608, -164 }, + { 0xDBAC6C247D62A584, -582, -156 }, + { 0xA3AB66580D5FDAF6, -555, -148 }, + { 0xF3E2F893DEC3F126, -529, -140 }, + { 0xB5B5ADA8AAFF80B8, -502, -132 }, + { 0x87625F056C7C4A8B, -475, -124 }, + { 0xC9BCFF6034C13053, -449, -116 }, + { 0x964E858C91BA2655, -422, -108 }, + { 0xDFF9772470297EBD, -396, -100 }, + { 0xA6DFBD9FB8E5B88F, -369, -92 }, + { 0xF8A95FCF88747D94, -343, -84 }, + { 0xB94470938FA89BCF, -316, -76 }, + { 0x8A08F0F8BF0F156B, -289, -68 }, + { 0xCDB02555653131B6, -263, -60 }, + { 0x993FE2C6D07B7FAC, -236, -52 }, + { 0xE45C10C42A2B3B06, -210, -44 }, + { 0xAA242499697392D3, -183, -36 }, + { 0xFD87B5F28300CA0E, -157, -28 }, + { 0xBCE5086492111AEB, -130, -20 }, + { 0x8CBCCC096F5088CC, -103, -12 }, + { 0xD1B71758E219652C, -77, -4 }, + { 0x9C40000000000000, -50, 4 }, + { 0xE8D4A51000000000, -24, 12 }, + { 0xAD78EBC5AC620000, 3, 20 }, + { 0x813F3978F8940984, 30, 28 }, + { 0xC097CE7BC90715B3, 56, 36 }, + { 0x8F7E32CE7BEA5C70, 83, 44 }, + { 0xD5D238A4ABE98068, 109, 52 }, + { 0x9F4F2726179A2245, 136, 60 }, + { 0xED63A231D4C4FB27, 162, 68 }, + { 0xB0DE65388CC8ADA8, 189, 76 }, + { 0x83C7088E1AAB65DB, 216, 84 }, + { 0xC45D1DF942711D9A, 242, 92 }, + { 0x924D692CA61BE758, 269, 100 }, + { 0xDA01EE641A708DEA, 295, 108 }, + { 0xA26DA3999AEF774A, 322, 116 }, + { 0xF209787BB47D6B85, 348, 124 }, + { 0xB454E4A179DD1877, 375, 132 }, + { 0x865B86925B9BC5C2, 402, 140 }, + { 0xC83553C5C8965D3D, 428, 148 }, + { 0x952AB45CFA97A0B3, 455, 156 }, + { 0xDE469FBD99A05FE3, 481, 164 }, + { 0xA59BC234DB398C25, 508, 172 }, + { 0xF6C69A72A3989F5C, 534, 180 }, + { 0xB7DCBF5354E9BECE, 561, 188 }, + { 0x88FCF317F22241E2, 588, 196 }, + { 0xCC20CE9BD35C78A5, 614, 204 }, + { 0x98165AF37B2153DF, 641, 212 }, + { 0xE2A0B5DC971F303A, 667, 220 }, + { 0xA8D9D1535CE3B396, 694, 228 }, + { 0xFB9B7CD9A4A7443C, 720, 236 }, + { 0xBB764C4CA7A44410, 747, 244 }, + { 0x8BAB8EEFB6409C1A, 774, 252 }, + { 0xD01FEF10A657842C, 800, 260 }, + { 0x9B10A4E5E9913129, 827, 268 }, + { 0xE7109BFBA19C0C9D, 853, 276 }, + { 0xAC2820D9623BF429, 880, 284 }, + { 0x80444B5E7AA7CF85, 907, 292 }, + { 0xBF21E44003ACDD2D, 933, 300 }, + { 0x8E679C2F5E44FF8F, 960, 308 }, + { 0xD433179D9C8CB841, 986, 316 }, + { 0x9E19DB92B4E31BA9, 1013, 324 }, + } + }; + + // This computation gives exactly the same results for k as + // k = ceil((kAlpha - e - 1) * 0.30102999566398114) + // for |e| <= 1500, but doesn't require floating-point operations. + // NB: log_10(2) ~= 78913 / 2^18 + JSON_ASSERT(e >= -1500); + JSON_ASSERT(e <= 1500); + const int f = kAlpha - e - 1; + const int k = (f * 78913) / (1 << 18) + static_cast(f > 0); + + const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep; + JSON_ASSERT(index >= 0); + JSON_ASSERT(static_cast(index) < kCachedPowers.size()); + + const cached_power cached = kCachedPowers[static_cast(index)]; + JSON_ASSERT(kAlpha <= cached.e + e + 64); + JSON_ASSERT(kGamma >= cached.e + e + 64); + + return cached; +} + +/*! +For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k. +For n == 0, returns 1 and sets pow10 := 1. +*/ +inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10) +{ + // LCOV_EXCL_START + if (n >= 1000000000) + { + pow10 = 1000000000; + return 10; + } + // LCOV_EXCL_STOP + if (n >= 100000000) + { + pow10 = 100000000; + return 9; + } + if (n >= 10000000) + { + pow10 = 10000000; + return 8; + } + if (n >= 1000000) + { + pow10 = 1000000; + return 7; + } + if (n >= 100000) + { + pow10 = 100000; + return 6; + } + if (n >= 10000) + { + pow10 = 10000; + return 5; + } + if (n >= 1000) + { + pow10 = 1000; + return 4; + } + if (n >= 100) + { + pow10 = 100; + return 3; + } + if (n >= 10) + { + pow10 = 10; + return 2; + } + + pow10 = 1; + return 1; +} + +inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta, + std::uint64_t rest, std::uint64_t ten_k) +{ + JSON_ASSERT(len >= 1); + JSON_ASSERT(dist <= delta); + JSON_ASSERT(rest <= delta); + JSON_ASSERT(ten_k > 0); + + // <--------------------------- delta ----> + // <---- dist ---------> + // --------------[------------------+-------------------]-------------- + // M- w M+ + // + // ten_k + // <------> + // <---- rest ----> + // --------------[------------------+----+--------------]-------------- + // w V + // = buf * 10^k + // + // ten_k represents a unit-in-the-last-place in the decimal representation + // stored in buf. + // Decrement buf by ten_k while this takes buf closer to w. + + // The tests are written in this order to avoid overflow in unsigned + // integer arithmetic. + + while (rest < dist + && delta - rest >= ten_k + && (rest + ten_k < dist || dist - rest > rest + ten_k - dist)) + { + JSON_ASSERT(buf[len - 1] != '0'); + buf[len - 1]--; + rest += ten_k; + } +} + +/*! +Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+. +M- and M+ must be normalized and share the same exponent -60 <= e <= -32. +*/ +inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent, + diyfp M_minus, diyfp w, diyfp M_plus) +{ + static_assert(kAlpha >= -60, "internal error"); + static_assert(kGamma <= -32, "internal error"); + + // Generates the digits (and the exponent) of a decimal floating-point + // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's + // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma. + // + // <--------------------------- delta ----> + // <---- dist ---------> + // --------------[------------------+-------------------]-------------- + // M- w M+ + // + // Grisu2 generates the digits of M+ from left to right and stops as soon as + // V is in [M-,M+]. + + JSON_ASSERT(M_plus.e >= kAlpha); + JSON_ASSERT(M_plus.e <= kGamma); + + std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e) + std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e) + + // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0): + // + // M+ = f * 2^e + // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e + // = ((p1 ) * 2^-e + (p2 )) * 2^e + // = p1 + p2 * 2^e + + const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e); + + auto p1 = static_cast(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.) + std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e + + // 1) + // + // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0] + + JSON_ASSERT(p1 > 0); + + std::uint32_t pow10{}; + const int k = find_largest_pow10(p1, pow10); + + // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1) + // + // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1)) + // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1)) + // + // M+ = p1 + p2 * 2^e + // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e + // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e + // = d[k-1] * 10^(k-1) + ( rest) * 2^e + // + // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0) + // + // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0] + // + // but stop as soon as + // + // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e + + int n = k; + while (n > 0) + { + // Invariants: + // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k) + // pow10 = 10^(n-1) <= p1 < 10^n + // + const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1) + const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1) + // + // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e + // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e) + // + JSON_ASSERT(d <= 9); + buffer[length++] = static_cast('0' + d); // buffer := buffer * 10 + d + // + // M+ = buffer * 10^(n-1) + (r + p2 * 2^e) + // + p1 = r; + n--; + // + // M+ = buffer * 10^n + (p1 + p2 * 2^e) + // pow10 = 10^n + // + + // Now check if enough digits have been generated. + // Compute + // + // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e + // + // Note: + // Since rest and delta share the same exponent e, it suffices to + // compare the significands. + const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2; + if (rest <= delta) + { + // V = buffer * 10^n, with M- <= V <= M+. + + decimal_exponent += n; + + // We may now just stop. But instead look if the buffer could be + // decremented to bring V closer to w. + // + // pow10 = 10^n is now 1 ulp in the decimal representation V. + // The rounding procedure works with diyfp's with an implicit + // exponent of e. + // + // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e + // + const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e; + grisu2_round(buffer, length, dist, delta, rest, ten_n); + + return; + } + + pow10 /= 10; + // + // pow10 = 10^(n-1) <= p1 < 10^n + // Invariants restored. + } + + // 2) + // + // The digits of the integral part have been generated: + // + // M+ = d[k-1]...d[1]d[0] + p2 * 2^e + // = buffer + p2 * 2^e + // + // Now generate the digits of the fractional part p2 * 2^e. + // + // Note: + // No decimal point is generated: the exponent is adjusted instead. + // + // p2 actually represents the fraction + // + // p2 * 2^e + // = p2 / 2^-e + // = d[-1] / 10^1 + d[-2] / 10^2 + ... + // + // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...) + // + // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m + // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...) + // + // using + // + // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e) + // = ( d) * 2^-e + ( r) + // + // or + // 10^m * p2 * 2^e = d + r * 2^e + // + // i.e. + // + // M+ = buffer + p2 * 2^e + // = buffer + 10^-m * (d + r * 2^e) + // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e + // + // and stop as soon as 10^-m * r * 2^e <= delta * 2^e + + JSON_ASSERT(p2 > delta); + + int m = 0; + for (;;) + { + // Invariant: + // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e + // = buffer * 10^-m + 10^-m * (p2 ) * 2^e + // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e + // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e + // + JSON_ASSERT(p2 <= (std::numeric_limits::max)() / 10); + p2 *= 10; + const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e + const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e + // + // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e + // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e)) + // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e + // + JSON_ASSERT(d <= 9); + buffer[length++] = static_cast('0' + d); // buffer := buffer * 10 + d + // + // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e + // + p2 = r; + m++; + // + // M+ = buffer * 10^-m + 10^-m * p2 * 2^e + // Invariant restored. + + // Check if enough digits have been generated. + // + // 10^-m * p2 * 2^e <= delta * 2^e + // p2 * 2^e <= 10^m * delta * 2^e + // p2 <= 10^m * delta + delta *= 10; + dist *= 10; + if (p2 <= delta) + { + break; + } + } + + // V = buffer * 10^-m, with M- <= V <= M+. + + decimal_exponent -= m; + + // 1 ulp in the decimal representation is now 10^-m. + // Since delta and dist are now scaled by 10^m, we need to do the + // same with ulp in order to keep the units in sync. + // + // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e + // + const std::uint64_t ten_m = one.f; + grisu2_round(buffer, length, dist, delta, p2, ten_m); + + // By construction this algorithm generates the shortest possible decimal + // number (Loitsch, Theorem 6.2) which rounds back to w. + // For an input number of precision p, at least + // + // N = 1 + ceil(p * log_10(2)) + // + // decimal digits are sufficient to identify all binary floating-point + // numbers (Matula, "In-and-Out conversions"). + // This implies that the algorithm does not produce more than N decimal + // digits. + // + // N = 17 for p = 53 (IEEE double precision) + // N = 9 for p = 24 (IEEE single precision) +} + +/*! +v = buf * 10^decimal_exponent +len is the length of the buffer (number of decimal digits) +The buffer must be large enough, i.e. >= max_digits10. +*/ +JSON_HEDLEY_NON_NULL(1) +inline void grisu2(char* buf, int& len, int& decimal_exponent, + diyfp m_minus, diyfp v, diyfp m_plus) +{ + JSON_ASSERT(m_plus.e == m_minus.e); + JSON_ASSERT(m_plus.e == v.e); + + // --------(-----------------------+-----------------------)-------- (A) + // m- v m+ + // + // --------------------(-----------+-----------------------)-------- (B) + // m- v m+ + // + // First scale v (and m- and m+) such that the exponent is in the range + // [alpha, gamma]. + + const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e); + + const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k + + // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma] + const diyfp w = diyfp::mul(v, c_minus_k); + const diyfp w_minus = diyfp::mul(m_minus, c_minus_k); + const diyfp w_plus = diyfp::mul(m_plus, c_minus_k); + + // ----(---+---)---------------(---+---)---------------(---+---)---- + // w- w w+ + // = c*m- = c*v = c*m+ + // + // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and + // w+ are now off by a small amount. + // In fact: + // + // w - v * 10^k < 1 ulp + // + // To account for this inaccuracy, add resp. subtract 1 ulp. + // + // --------+---[---------------(---+---)---------------]---+-------- + // w- M- w M+ w+ + // + // Now any number in [M-, M+] (bounds included) will round to w when input, + // regardless of how the input rounding algorithm breaks ties. + // + // And digit_gen generates the shortest possible such number in [M-, M+]. + // Note that this does not mean that Grisu2 always generates the shortest + // possible number in the interval (m-, m+). + const diyfp M_minus(w_minus.f + 1, w_minus.e); + const diyfp M_plus (w_plus.f - 1, w_plus.e ); + + decimal_exponent = -cached.k; // = -(-k) = k + + grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus); +} + +/*! +v = buf * 10^decimal_exponent +len is the length of the buffer (number of decimal digits) +The buffer must be large enough, i.e. >= max_digits10. +*/ +template +JSON_HEDLEY_NON_NULL(1) +void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value) +{ + static_assert(diyfp::kPrecision >= std::numeric_limits::digits + 3, + "internal error: not enough precision"); + + JSON_ASSERT(std::isfinite(value)); + JSON_ASSERT(value > 0); + + // If the neighbors (and boundaries) of 'value' are always computed for double-precision + // numbers, all float's can be recovered using strtod (and strtof). However, the resulting + // decimal representations are not exactly "short". + // + // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars) + // says "value is converted to a string as if by std::sprintf in the default ("C") locale" + // and since sprintf promotes floats to doubles, I think this is exactly what 'std::to_chars' + // does. + // On the other hand, the documentation for 'std::to_chars' requires that "parsing the + // representation using the corresponding std::from_chars function recovers value exactly". That + // indicates that single precision floating-point numbers should be recovered using + // 'std::strtof'. + // + // NB: If the neighbors are computed for single-precision numbers, there is a single float + // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision + // value is off by 1 ulp. +#if 0 + const boundaries w = compute_boundaries(static_cast(value)); +#else + const boundaries w = compute_boundaries(value); +#endif + + grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus); +} + +/*! +@brief appends a decimal representation of e to buf +@return a pointer to the element following the exponent. +@pre -1000 < e < 1000 +*/ +JSON_HEDLEY_NON_NULL(1) +JSON_HEDLEY_RETURNS_NON_NULL +inline char* append_exponent(char* buf, int e) +{ + JSON_ASSERT(e > -1000); + JSON_ASSERT(e < 1000); + + if (e < 0) + { + e = -e; + *buf++ = '-'; + } + else + { + *buf++ = '+'; + } + + auto k = static_cast(e); + if (k < 10) + { + // Always print at least two digits in the exponent. + // This is for compatibility with printf("%g"). + *buf++ = '0'; + *buf++ = static_cast('0' + k); + } + else if (k < 100) + { + *buf++ = static_cast('0' + k / 10); + k %= 10; + *buf++ = static_cast('0' + k); + } + else + { + *buf++ = static_cast('0' + k / 100); + k %= 100; + *buf++ = static_cast('0' + k / 10); + k %= 10; + *buf++ = static_cast('0' + k); + } + + return buf; +} + +/*! +@brief prettify v = buf * 10^decimal_exponent + +If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point +notation. Otherwise it will be printed in exponential notation. + +@pre min_exp < 0 +@pre max_exp > 0 +*/ +JSON_HEDLEY_NON_NULL(1) +JSON_HEDLEY_RETURNS_NON_NULL +inline char* format_buffer(char* buf, int len, int decimal_exponent, + int min_exp, int max_exp) +{ + JSON_ASSERT(min_exp < 0); + JSON_ASSERT(max_exp > 0); + + const int k = len; + const int n = len + decimal_exponent; + + // v = buf * 10^(n-k) + // k is the length of the buffer (number of decimal digits) + // n is the position of the decimal point relative to the start of the buffer. + + if (k <= n && n <= max_exp) + { + // digits[000] + // len <= max_exp + 2 + + std::memset(buf + k, '0', static_cast(n) - static_cast(k)); + // Make it look like a floating-point number (#362, #378) + buf[n + 0] = '.'; + buf[n + 1] = '0'; + return buf + (static_cast(n) + 2); + } + + if (0 < n && n <= max_exp) + { + // dig.its + // len <= max_digits10 + 1 + + JSON_ASSERT(k > n); + + std::memmove(buf + (static_cast(n) + 1), buf + n, static_cast(k) - static_cast(n)); + buf[n] = '.'; + return buf + (static_cast(k) + 1U); + } + + if (min_exp < n && n <= 0) + { + // 0.[000]digits + // len <= 2 + (-min_exp - 1) + max_digits10 + + std::memmove(buf + (2 + static_cast(-n)), buf, static_cast(k)); + buf[0] = '0'; + buf[1] = '.'; + std::memset(buf + 2, '0', static_cast(-n)); + return buf + (2U + static_cast(-n) + static_cast(k)); + } + + if (k == 1) + { + // dE+123 + // len <= 1 + 5 + + buf += 1; + } + else + { + // d.igitsE+123 + // len <= max_digits10 + 1 + 5 + + std::memmove(buf + 2, buf + 1, static_cast(k) - 1); + buf[1] = '.'; + buf += 1 + static_cast(k); + } + + *buf++ = 'e'; + return append_exponent(buf, n - 1); +} + +} // namespace dtoa_impl + +/*! +@brief generates a decimal representation of the floating-point number value in [first, last). + +The format of the resulting decimal representation is similar to printf's %g +format. Returns an iterator pointing past-the-end of the decimal representation. + +@note The input number must be finite, i.e. NaN's and Inf's are not supported. +@note The buffer must be large enough. +@note The result is NOT null-terminated. +*/ +template +JSON_HEDLEY_NON_NULL(1, 2) +JSON_HEDLEY_RETURNS_NON_NULL +char* to_chars(char* first, const char* last, FloatType value) +{ + static_cast(last); // maybe unused - fix warning + JSON_ASSERT(std::isfinite(value)); + + // Use signbit(value) instead of (value < 0) since signbit works for -0. + if (std::signbit(value)) + { + value = -value; + *first++ = '-'; + } + +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif + if (value == 0) // +-0 + { + *first++ = '0'; + // Make it look like a floating-point number (#362, #378) + *first++ = '.'; + *first++ = '0'; + return first; + } +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif + + JSON_ASSERT(last - first >= std::numeric_limits::max_digits10); + + // Compute v = buffer * 10^decimal_exponent. + // The decimal digits are stored in the buffer, which needs to be interpreted + // as an unsigned decimal integer. + // len is the length of the buffer, i.e. the number of decimal digits. + int len = 0; + int decimal_exponent = 0; + dtoa_impl::grisu2(first, len, decimal_exponent, value); + + JSON_ASSERT(len <= std::numeric_limits::max_digits10); + + // Format the buffer like printf("%.*g", prec, value) + constexpr int kMinExp = -4; + // Use digits10 here to increase compatibility with version 2. + constexpr int kMaxExp = std::numeric_limits::digits10; + + JSON_ASSERT(last - first >= kMaxExp + 2); + JSON_ASSERT(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits::max_digits10); + JSON_ASSERT(last - first >= std::numeric_limits::max_digits10 + 6); + + return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp); +} + +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + +// #include + +// #include + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +/////////////////// +// serialization // +/////////////////// + +/// how to treat decoding errors +enum class error_handler_t +{ + strict, ///< throw a type_error exception in case of invalid UTF-8 + replace, ///< replace invalid UTF-8 sequences with U+FFFD + ignore ///< ignore invalid UTF-8 sequences +}; + +template +class serializer +{ + using string_t = typename BasicJsonType::string_t; + using number_float_t = typename BasicJsonType::number_float_t; + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using binary_char_t = typename BasicJsonType::binary_t::value_type; + static constexpr std::uint8_t UTF8_ACCEPT = 0; + static constexpr std::uint8_t UTF8_REJECT = 1; + + public: + /*! + @param[in] s output stream to serialize to + @param[in] ichar indentation character to use + @param[in] error_handler_ how to react on decoding errors + */ + serializer(output_adapter_t s, const char ichar, + error_handler_t error_handler_ = error_handler_t::strict) + : o(std::move(s)) + , loc(std::localeconv()) + , thousands_sep(loc->thousands_sep == nullptr ? '\0' : std::char_traits::to_char_type(* (loc->thousands_sep))) + , decimal_point(loc->decimal_point == nullptr ? '\0' : std::char_traits::to_char_type(* (loc->decimal_point))) + , indent_char(ichar) + , indent_string(512, indent_char) + , error_handler(error_handler_) + {} + + // delete because of pointer members + serializer(const serializer&) = delete; + serializer& operator=(const serializer&) = delete; + serializer(serializer&&) = delete; + serializer& operator=(serializer&&) = delete; + ~serializer() = default; + + /*! + @brief internal implementation of the serialization function + + This function is called by the public member function dump and organizes + the serialization internally. The indentation level is propagated as + additional parameter. In case of arrays and objects, the function is + called recursively. + + - strings and object keys are escaped using `escape_string()` + - integer numbers are converted implicitly via `operator<<` + - floating-point numbers are converted to a string using `"%g"` format + - binary values are serialized as objects containing the subtype and the + byte array + + @param[in] val value to serialize + @param[in] pretty_print whether the output shall be pretty-printed + @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters + in the output are escaped with `\uXXXX` sequences, and the result consists + of ASCII characters only. + @param[in] indent_step the indent level + @param[in] current_indent the current indent level (only used internally) + */ + void dump(const BasicJsonType& val, + const bool pretty_print, + const bool ensure_ascii, + const unsigned int indent_step, + const unsigned int current_indent = 0) + { + switch (val.m_type) + { + case value_t::object: + { + if (val.m_value.object->empty()) + { + o->write_characters("{}", 2); + return; + } + + if (pretty_print) + { + o->write_characters("{\n", 2); + + // variable to hold indentation for recursive calls + const auto new_indent = current_indent + indent_step; + if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) + { + indent_string.resize(indent_string.size() * 2, ' '); + } + + // first n-1 elements + auto i = val.m_value.object->cbegin(); + for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) + { + o->write_characters(indent_string.c_str(), new_indent); + o->write_character('\"'); + dump_escaped(i->first, ensure_ascii); + o->write_characters("\": ", 3); + dump(i->second, true, ensure_ascii, indent_step, new_indent); + o->write_characters(",\n", 2); + } + + // last element + JSON_ASSERT(i != val.m_value.object->cend()); + JSON_ASSERT(std::next(i) == val.m_value.object->cend()); + o->write_characters(indent_string.c_str(), new_indent); + o->write_character('\"'); + dump_escaped(i->first, ensure_ascii); + o->write_characters("\": ", 3); + dump(i->second, true, ensure_ascii, indent_step, new_indent); + + o->write_character('\n'); + o->write_characters(indent_string.c_str(), current_indent); + o->write_character('}'); + } + else + { + o->write_character('{'); + + // first n-1 elements + auto i = val.m_value.object->cbegin(); + for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) + { + o->write_character('\"'); + dump_escaped(i->first, ensure_ascii); + o->write_characters("\":", 2); + dump(i->second, false, ensure_ascii, indent_step, current_indent); + o->write_character(','); + } + + // last element + JSON_ASSERT(i != val.m_value.object->cend()); + JSON_ASSERT(std::next(i) == val.m_value.object->cend()); + o->write_character('\"'); + dump_escaped(i->first, ensure_ascii); + o->write_characters("\":", 2); + dump(i->second, false, ensure_ascii, indent_step, current_indent); + + o->write_character('}'); + } + + return; + } + + case value_t::array: + { + if (val.m_value.array->empty()) + { + o->write_characters("[]", 2); + return; + } + + if (pretty_print) + { + o->write_characters("[\n", 2); + + // variable to hold indentation for recursive calls + const auto new_indent = current_indent + indent_step; + if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) + { + indent_string.resize(indent_string.size() * 2, ' '); + } + + // first n-1 elements + for (auto i = val.m_value.array->cbegin(); + i != val.m_value.array->cend() - 1; ++i) + { + o->write_characters(indent_string.c_str(), new_indent); + dump(*i, true, ensure_ascii, indent_step, new_indent); + o->write_characters(",\n", 2); + } + + // last element + JSON_ASSERT(!val.m_value.array->empty()); + o->write_characters(indent_string.c_str(), new_indent); + dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent); + + o->write_character('\n'); + o->write_characters(indent_string.c_str(), current_indent); + o->write_character(']'); + } + else + { + o->write_character('['); + + // first n-1 elements + for (auto i = val.m_value.array->cbegin(); + i != val.m_value.array->cend() - 1; ++i) + { + dump(*i, false, ensure_ascii, indent_step, current_indent); + o->write_character(','); + } + + // last element + JSON_ASSERT(!val.m_value.array->empty()); + dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent); + + o->write_character(']'); + } + + return; + } + + case value_t::string: + { + o->write_character('\"'); + dump_escaped(*val.m_value.string, ensure_ascii); + o->write_character('\"'); + return; + } + + case value_t::binary: + { + if (pretty_print) + { + o->write_characters("{\n", 2); + + // variable to hold indentation for recursive calls + const auto new_indent = current_indent + indent_step; + if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) + { + indent_string.resize(indent_string.size() * 2, ' '); + } + + o->write_characters(indent_string.c_str(), new_indent); + + o->write_characters("\"bytes\": [", 10); + + if (!val.m_value.binary->empty()) + { + for (auto i = val.m_value.binary->cbegin(); + i != val.m_value.binary->cend() - 1; ++i) + { + dump_integer(*i); + o->write_characters(", ", 2); + } + dump_integer(val.m_value.binary->back()); + } + + o->write_characters("],\n", 3); + o->write_characters(indent_string.c_str(), new_indent); + + o->write_characters("\"subtype\": ", 11); + if (val.m_value.binary->has_subtype()) + { + dump_integer(val.m_value.binary->subtype()); + } + else + { + o->write_characters("null", 4); + } + o->write_character('\n'); + o->write_characters(indent_string.c_str(), current_indent); + o->write_character('}'); + } + else + { + o->write_characters("{\"bytes\":[", 10); + + if (!val.m_value.binary->empty()) + { + for (auto i = val.m_value.binary->cbegin(); + i != val.m_value.binary->cend() - 1; ++i) + { + dump_integer(*i); + o->write_character(','); + } + dump_integer(val.m_value.binary->back()); + } + + o->write_characters("],\"subtype\":", 12); + if (val.m_value.binary->has_subtype()) + { + dump_integer(val.m_value.binary->subtype()); + o->write_character('}'); + } + else + { + o->write_characters("null}", 5); + } + } + return; + } + + case value_t::boolean: + { + if (val.m_value.boolean) + { + o->write_characters("true", 4); + } + else + { + o->write_characters("false", 5); + } + return; + } + + case value_t::number_integer: + { + dump_integer(val.m_value.number_integer); + return; + } + + case value_t::number_unsigned: + { + dump_integer(val.m_value.number_unsigned); + return; + } + + case value_t::number_float: + { + dump_float(val.m_value.number_float); + return; + } + + case value_t::discarded: + { + o->write_characters("", 11); + return; + } + + case value_t::null: + { + o->write_characters("null", 4); + return; + } + + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + } + } + + JSON_PRIVATE_UNLESS_TESTED: + /*! + @brief dump escaped string + + Escape a string by replacing certain special characters by a sequence of an + escape character (backslash) and another character and other control + characters by a sequence of "\u" followed by a four-digit hex + representation. The escaped string is written to output stream @a o. + + @param[in] s the string to escape + @param[in] ensure_ascii whether to escape non-ASCII characters with + \uXXXX sequences + + @complexity Linear in the length of string @a s. + */ + void dump_escaped(const string_t& s, const bool ensure_ascii) + { + std::uint32_t codepoint{}; + std::uint8_t state = UTF8_ACCEPT; + std::size_t bytes = 0; // number of bytes written to string_buffer + + // number of bytes written at the point of the last valid byte + std::size_t bytes_after_last_accept = 0; + std::size_t undumped_chars = 0; + + for (std::size_t i = 0; i < s.size(); ++i) + { + const auto byte = static_cast(s[i]); + + switch (decode(state, codepoint, byte)) + { + case UTF8_ACCEPT: // decode found a new code point + { + switch (codepoint) + { + case 0x08: // backspace + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = 'b'; + break; + } + + case 0x09: // horizontal tab + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = 't'; + break; + } + + case 0x0A: // newline + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = 'n'; + break; + } + + case 0x0C: // formfeed + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = 'f'; + break; + } + + case 0x0D: // carriage return + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = 'r'; + break; + } + + case 0x22: // quotation mark + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = '\"'; + break; + } + + case 0x5C: // reverse solidus + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = '\\'; + break; + } + + default: + { + // escape control characters (0x00..0x1F) or, if + // ensure_ascii parameter is used, non-ASCII characters + if ((codepoint <= 0x1F) || (ensure_ascii && (codepoint >= 0x7F))) + { + if (codepoint <= 0xFFFF) + { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) + static_cast((std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x", + static_cast(codepoint))); + bytes += 6; + } + else + { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) + static_cast((std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x", + static_cast(0xD7C0u + (codepoint >> 10u)), + static_cast(0xDC00u + (codepoint & 0x3FFu)))); + bytes += 12; + } + } + else + { + // copy byte to buffer (all previous bytes + // been copied have in default case above) + string_buffer[bytes++] = s[i]; + } + break; + } + } + + // write buffer and reset index; there must be 13 bytes + // left, as this is the maximal number of bytes to be + // written ("\uxxxx\uxxxx\0") for one code point + if (string_buffer.size() - bytes < 13) + { + o->write_characters(string_buffer.data(), bytes); + bytes = 0; + } + + // remember the byte position of this accept + bytes_after_last_accept = bytes; + undumped_chars = 0; + break; + } + + case UTF8_REJECT: // decode found invalid UTF-8 byte + { + switch (error_handler) + { + case error_handler_t::strict: + { + std::stringstream ss; + ss << std::uppercase << std::setfill('0') << std::setw(2) << std::hex << (byte | 0); + JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + ss.str(), BasicJsonType())); + } + + case error_handler_t::ignore: + case error_handler_t::replace: + { + // in case we saw this character the first time, we + // would like to read it again, because the byte + // may be OK for itself, but just not OK for the + // previous sequence + if (undumped_chars > 0) + { + --i; + } + + // reset length buffer to the last accepted index; + // thus removing/ignoring the invalid characters + bytes = bytes_after_last_accept; + + if (error_handler == error_handler_t::replace) + { + // add a replacement character + if (ensure_ascii) + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = 'u'; + string_buffer[bytes++] = 'f'; + string_buffer[bytes++] = 'f'; + string_buffer[bytes++] = 'f'; + string_buffer[bytes++] = 'd'; + } + else + { + string_buffer[bytes++] = detail::binary_writer::to_char_type('\xEF'); + string_buffer[bytes++] = detail::binary_writer::to_char_type('\xBF'); + string_buffer[bytes++] = detail::binary_writer::to_char_type('\xBD'); + } + + // write buffer and reset index; there must be 13 bytes + // left, as this is the maximal number of bytes to be + // written ("\uxxxx\uxxxx\0") for one code point + if (string_buffer.size() - bytes < 13) + { + o->write_characters(string_buffer.data(), bytes); + bytes = 0; + } + + bytes_after_last_accept = bytes; + } + + undumped_chars = 0; + + // continue processing the string + state = UTF8_ACCEPT; + break; + } + + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + } + break; + } + + default: // decode found yet incomplete multi-byte code point + { + if (!ensure_ascii) + { + // code point will not be escaped - copy byte to buffer + string_buffer[bytes++] = s[i]; + } + ++undumped_chars; + break; + } + } + } + + // we finished processing the string + if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT)) + { + // write buffer + if (bytes > 0) + { + o->write_characters(string_buffer.data(), bytes); + } + } + else + { + // we finish reading, but do not accept: string was incomplete + switch (error_handler) + { + case error_handler_t::strict: + { + std::stringstream ss; + ss << std::uppercase << std::setfill('0') << std::setw(2) << std::hex << (static_cast(s.back()) | 0); + JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + ss.str(), BasicJsonType())); + } + + case error_handler_t::ignore: + { + // write all accepted bytes + o->write_characters(string_buffer.data(), bytes_after_last_accept); + break; + } + + case error_handler_t::replace: + { + // write all accepted bytes + o->write_characters(string_buffer.data(), bytes_after_last_accept); + // add a replacement character + if (ensure_ascii) + { + o->write_characters("\\ufffd", 6); + } + else + { + o->write_characters("\xEF\xBF\xBD", 3); + } + break; + } + + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + } + } + } + + private: + /*! + @brief count digits + + Count the number of decimal (base 10) digits for an input unsigned integer. + + @param[in] x unsigned integer number to count its digits + @return number of decimal digits + */ + inline unsigned int count_digits(number_unsigned_t x) noexcept + { + unsigned int n_digits = 1; + for (;;) + { + if (x < 10) + { + return n_digits; + } + if (x < 100) + { + return n_digits + 1; + } + if (x < 1000) + { + return n_digits + 2; + } + if (x < 10000) + { + return n_digits + 3; + } + x = x / 10000u; + n_digits += 4; + } + } + + // templates to avoid warnings about useless casts + template ::value, int> = 0> + bool is_negative_number(NumberType x) + { + return x < 0; + } + + template < typename NumberType, enable_if_t ::value, int > = 0 > + bool is_negative_number(NumberType /*unused*/) + { + return false; + } + + /*! + @brief dump an integer + + Dump a given integer to output stream @a o. Works internally with + @a number_buffer. + + @param[in] x integer number (signed or unsigned) to dump + @tparam NumberType either @a number_integer_t or @a number_unsigned_t + */ + template < typename NumberType, detail::enable_if_t < + std::is_integral::value || + std::is_same::value || + std::is_same::value || + std::is_same::value, + int > = 0 > + void dump_integer(NumberType x) + { + static constexpr std::array, 100> digits_to_99 + { + { + {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}}, + {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}}, + {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}}, + {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}}, + {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}}, + {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}}, + {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}}, + {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}}, + {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}}, + {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}}, + } + }; + + // special case for "0" + if (x == 0) + { + o->write_character('0'); + return; + } + + // use a pointer to fill the buffer + auto buffer_ptr = number_buffer.begin(); // NOLINT(llvm-qualified-auto,readability-qualified-auto,cppcoreguidelines-pro-type-vararg,hicpp-vararg) + + number_unsigned_t abs_value; + + unsigned int n_chars{}; + + if (is_negative_number(x)) + { + *buffer_ptr = '-'; + abs_value = remove_sign(static_cast(x)); + + // account one more byte for the minus sign + n_chars = 1 + count_digits(abs_value); + } + else + { + abs_value = static_cast(x); + n_chars = count_digits(abs_value); + } + + // spare 1 byte for '\0' + JSON_ASSERT(n_chars < number_buffer.size() - 1); + + // jump to the end to generate the string from backward, + // so we later avoid reversing the result + buffer_ptr += n_chars; + + // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu + // See: https://www.youtube.com/watch?v=o4-CwDo2zpg + while (abs_value >= 100) + { + const auto digits_index = static_cast((abs_value % 100)); + abs_value /= 100; + *(--buffer_ptr) = digits_to_99[digits_index][1]; + *(--buffer_ptr) = digits_to_99[digits_index][0]; + } + + if (abs_value >= 10) + { + const auto digits_index = static_cast(abs_value); + *(--buffer_ptr) = digits_to_99[digits_index][1]; + *(--buffer_ptr) = digits_to_99[digits_index][0]; + } + else + { + *(--buffer_ptr) = static_cast('0' + abs_value); + } + + o->write_characters(number_buffer.data(), n_chars); + } + + /*! + @brief dump a floating-point number + + Dump a given floating-point number to output stream @a o. Works internally + with @a number_buffer. + + @param[in] x floating-point number to dump + */ + void dump_float(number_float_t x) + { + // NaN / inf + if (!std::isfinite(x)) + { + o->write_characters("null", 4); + return; + } + + // If number_float_t is an IEEE-754 single or double precision number, + // use the Grisu2 algorithm to produce short numbers which are + // guaranteed to round-trip, using strtof and strtod, resp. + // + // NB: The test below works if == . + static constexpr bool is_ieee_single_or_double + = (std::numeric_limits::is_iec559 && std::numeric_limits::digits == 24 && std::numeric_limits::max_exponent == 128) || + (std::numeric_limits::is_iec559 && std::numeric_limits::digits == 53 && std::numeric_limits::max_exponent == 1024); + + dump_float(x, std::integral_constant()); + } + + void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/) + { + auto* begin = number_buffer.data(); + auto* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x); + + o->write_characters(begin, static_cast(end - begin)); + } + + void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/) + { + // get number of digits for a float -> text -> float round-trip + static constexpr auto d = std::numeric_limits::max_digits10; + + // the actual conversion + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) + std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x); + + // negative value indicates an error + JSON_ASSERT(len > 0); + // check if buffer was large enough + JSON_ASSERT(static_cast(len) < number_buffer.size()); + + // erase thousands separator + if (thousands_sep != '\0') + { + // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::remove returns an iterator, see https://github.com/nlohmann/json/issues/3081 + const auto end = std::remove(number_buffer.begin(), number_buffer.begin() + len, thousands_sep); + std::fill(end, number_buffer.end(), '\0'); + JSON_ASSERT((end - number_buffer.begin()) <= len); + len = (end - number_buffer.begin()); + } + + // convert decimal point to '.' + if (decimal_point != '\0' && decimal_point != '.') + { + // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::find returns an iterator, see https://github.com/nlohmann/json/issues/3081 + const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point); + if (dec_pos != number_buffer.end()) + { + *dec_pos = '.'; + } + } + + o->write_characters(number_buffer.data(), static_cast(len)); + + // determine if we need to append ".0" + const bool value_is_int_like = + std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1, + [](char c) + { + return c == '.' || c == 'e'; + }); + + if (value_is_int_like) + { + o->write_characters(".0", 2); + } + } + + /*! + @brief check whether a string is UTF-8 encoded + + The function checks each byte of a string whether it is UTF-8 encoded. The + result of the check is stored in the @a state parameter. The function must + be called initially with state 0 (accept). State 1 means the string must + be rejected, because the current byte is not allowed. If the string is + completely processed, but the state is non-zero, the string ended + prematurely; that is, the last byte indicated more bytes should have + followed. + + @param[in,out] state the state of the decoding + @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT) + @param[in] byte next byte to decode + @return new state + + @note The function has been edited: a std::array is used. + + @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann + @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ + */ + static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept + { + static const std::array utf8d = + { + { + 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, // 00..1F + 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, // 20..3F + 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, // 40..5F + 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, // 60..7F + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9F + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // A0..BF + 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C0..DF + 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF + 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF + 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2 + 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4 + 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6 + 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // s7..s8 + } + }; + + JSON_ASSERT(byte < utf8d.size()); + const std::uint8_t type = utf8d[byte]; + + codep = (state != UTF8_ACCEPT) + ? (byte & 0x3fu) | (codep << 6u) + : (0xFFu >> type) & (byte); + + std::size_t index = 256u + static_cast(state) * 16u + static_cast(type); + JSON_ASSERT(index < 400); + state = utf8d[index]; + return state; + } + + /* + * Overload to make the compiler happy while it is instantiating + * dump_integer for number_unsigned_t. + * Must never be called. + */ + number_unsigned_t remove_sign(number_unsigned_t x) + { + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + return x; // LCOV_EXCL_LINE + } + + /* + * Helper function for dump_integer + * + * This function takes a negative signed integer and returns its absolute + * value as unsigned integer. The plus/minus shuffling is necessary as we can + * not directly remove the sign of an arbitrary signed integer as the + * absolute values of INT_MIN and INT_MAX are usually not the same. See + * #1708 for details. + */ + inline number_unsigned_t remove_sign(number_integer_t x) noexcept + { + JSON_ASSERT(x < 0 && x < (std::numeric_limits::max)()); // NOLINT(misc-redundant-expression) + return static_cast(-(x + 1)) + 1; + } + + private: + /// the output of the serializer + output_adapter_t o = nullptr; + + /// a (hopefully) large enough character buffer + std::array number_buffer{{}}; + + /// the locale + const std::lconv* loc = nullptr; + /// the locale's thousand separator character + const char thousands_sep = '\0'; + /// the locale's decimal point character + const char decimal_point = '\0'; + + /// string buffer + std::array string_buffer{{}}; + + /// the indentation character + const char indent_char; + /// the indentation string + string_t indent_string; + + /// error_handler how to react on decoding errors + const error_handler_t error_handler; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + +// #include + + +#include // less +#include // initializer_list +#include // input_iterator_tag, iterator_traits +#include // allocator +#include // for out_of_range +#include // enable_if, is_convertible +#include // pair +#include // vector + +// #include + + +namespace nlohmann +{ + +/// ordered_map: a minimal map-like container that preserves insertion order +/// for use within nlohmann::basic_json +template , + class Allocator = std::allocator>> + struct ordered_map : std::vector, Allocator> +{ + using key_type = Key; + using mapped_type = T; + using Container = std::vector, Allocator>; + using iterator = typename Container::iterator; + using const_iterator = typename Container::const_iterator; + using size_type = typename Container::size_type; + using value_type = typename Container::value_type; + + // Explicit constructors instead of `using Container::Container` + // otherwise older compilers choke on it (GCC <= 5.5, xcode <= 9.4) + ordered_map(const Allocator& alloc = Allocator()) : Container{alloc} {} + template + ordered_map(It first, It last, const Allocator& alloc = Allocator()) + : Container{first, last, alloc} {} + ordered_map(std::initializer_list init, const Allocator& alloc = Allocator() ) + : Container{init, alloc} {} + + std::pair emplace(const key_type& key, T&& t) + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + return {it, false}; + } + } + Container::emplace_back(key, t); + return {--this->end(), true}; + } + + T& operator[](const Key& key) + { + return emplace(key, T{}).first->second; + } + + const T& operator[](const Key& key) const + { + return at(key); + } + + T& at(const Key& key) + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + return it->second; + } + } + + JSON_THROW(std::out_of_range("key not found")); + } + + const T& at(const Key& key) const + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + return it->second; + } + } + + JSON_THROW(std::out_of_range("key not found")); + } + + size_type erase(const Key& key) + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + // Since we cannot move const Keys, re-construct them in place + for (auto next = it; ++next != this->end(); ++it) + { + it->~value_type(); // Destroy but keep allocation + new (&*it) value_type{std::move(*next)}; + } + Container::pop_back(); + return 1; + } + } + return 0; + } + + iterator erase(iterator pos) + { + return erase(pos, std::next(pos)); + } + + iterator erase(iterator first, iterator last) + { + const auto elements_affected = std::distance(first, last); + const auto offset = std::distance(Container::begin(), first); + + // This is the start situation. We need to delete elements_affected + // elements (3 in this example: e, f, g), and need to return an + // iterator past the last deleted element (h in this example). + // Note that offset is the distance from the start of the vector + // to first. We will need this later. + + // [ a, b, c, d, e, f, g, h, i, j ] + // ^ ^ + // first last + + // Since we cannot move const Keys, we re-construct them in place. + // We start at first and re-construct (viz. copy) the elements from + // the back of the vector. Example for first iteration: + + // ,--------. + // v | destroy e and re-construct with h + // [ a, b, c, d, e, f, g, h, i, j ] + // ^ ^ + // it it + elements_affected + + for (auto it = first; std::next(it, elements_affected) != Container::end(); ++it) + { + it->~value_type(); // destroy but keep allocation + new (&*it) value_type{std::move(*std::next(it, elements_affected))}; // "move" next element to it + } + + // [ a, b, c, d, h, i, j, h, i, j ] + // ^ ^ + // first last + + // remove the unneeded elements at the end of the vector + Container::resize(this->size() - static_cast(elements_affected)); + + // [ a, b, c, d, h, i, j ] + // ^ ^ + // first last + + // first is now pointing past the last deleted element, but we cannot + // use this iterator, because it may have been invalidated by the + // resize call. Instead, we can return begin() + offset. + return Container::begin() + offset; + } + + size_type count(const Key& key) const + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + return 1; + } + } + return 0; + } + + iterator find(const Key& key) + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + return it; + } + } + return Container::end(); + } + + const_iterator find(const Key& key) const + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + return it; + } + } + return Container::end(); + } + + std::pair insert( value_type&& value ) + { + return emplace(value.first, std::move(value.second)); + } + + std::pair insert( const value_type& value ) + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == value.first) + { + return {it, false}; + } + } + Container::push_back(value); + return {--this->end(), true}; + } + + template + using require_input_iter = typename std::enable_if::iterator_category, + std::input_iterator_tag>::value>::type; + + template> + void insert(InputIt first, InputIt last) + { + for (auto it = first; it != last; ++it) + { + insert(*it); + } + } +}; + +} // namespace nlohmann + + +#if defined(JSON_HAS_CPP_17) + #include +#endif + +/*! +@brief namespace for Niels Lohmann +@see https://github.com/nlohmann +@since version 1.0.0 +*/ +namespace nlohmann +{ + +/*! +@brief a class to store JSON values + +@internal +@invariant The member variables @a m_value and @a m_type have the following +relationship: +- If `m_type == value_t::object`, then `m_value.object != nullptr`. +- If `m_type == value_t::array`, then `m_value.array != nullptr`. +- If `m_type == value_t::string`, then `m_value.string != nullptr`. +The invariants are checked by member function assert_invariant(). + +@note ObjectType trick from https://stackoverflow.com/a/9860911 +@endinternal + +@since version 1.0.0 + +@nosubgrouping +*/ +NLOHMANN_BASIC_JSON_TPL_DECLARATION +class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions) +{ + private: + template friend struct detail::external_constructor; + friend ::nlohmann::json_pointer; + + template + friend class ::nlohmann::detail::parser; + friend ::nlohmann::detail::serializer; + template + friend class ::nlohmann::detail::iter_impl; + template + friend class ::nlohmann::detail::binary_writer; + template + friend class ::nlohmann::detail::binary_reader; + template + friend class ::nlohmann::detail::json_sax_dom_parser; + template + friend class ::nlohmann::detail::json_sax_dom_callback_parser; + friend class ::nlohmann::detail::exception; + + /// workaround type for MSVC + using basic_json_t = NLOHMANN_BASIC_JSON_TPL; + + JSON_PRIVATE_UNLESS_TESTED: + // convenience aliases for types residing in namespace detail; + using lexer = ::nlohmann::detail::lexer_base; + + template + static ::nlohmann::detail::parser parser( + InputAdapterType adapter, + detail::parser_callback_tcb = nullptr, + const bool allow_exceptions = true, + const bool ignore_comments = false + ) + { + return ::nlohmann::detail::parser(std::move(adapter), + std::move(cb), allow_exceptions, ignore_comments); + } + + private: + using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t; + template + using internal_iterator = ::nlohmann::detail::internal_iterator; + template + using iter_impl = ::nlohmann::detail::iter_impl; + template + using iteration_proxy = ::nlohmann::detail::iteration_proxy; + template using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator; + + template + using output_adapter_t = ::nlohmann::detail::output_adapter_t; + + template + using binary_reader = ::nlohmann::detail::binary_reader; + template using binary_writer = ::nlohmann::detail::binary_writer; + + JSON_PRIVATE_UNLESS_TESTED: + using serializer = ::nlohmann::detail::serializer; + + public: + using value_t = detail::value_t; + /// JSON Pointer, see @ref nlohmann::json_pointer + using json_pointer = ::nlohmann::json_pointer; + template + using json_serializer = JSONSerializer; + /// how to treat decoding errors + using error_handler_t = detail::error_handler_t; + /// how to treat CBOR tags + using cbor_tag_handler_t = detail::cbor_tag_handler_t; + /// helper type for initializer lists of basic_json values + using initializer_list_t = std::initializer_list>; + + using input_format_t = detail::input_format_t; + /// SAX interface type, see @ref nlohmann::json_sax + using json_sax_t = json_sax; + + //////////////// + // exceptions // + //////////////// + + /// @name exceptions + /// Classes to implement user-defined exceptions. + /// @{ + + using exception = detail::exception; + using parse_error = detail::parse_error; + using invalid_iterator = detail::invalid_iterator; + using type_error = detail::type_error; + using out_of_range = detail::out_of_range; + using other_error = detail::other_error; + + /// @} + + + ///////////////////// + // container types // + ///////////////////// + + /// @name container types + /// The canonic container types to use @ref basic_json like any other STL + /// container. + /// @{ + + /// the type of elements in a basic_json container + using value_type = basic_json; + + /// the type of an element reference + using reference = value_type&; + /// the type of an element const reference + using const_reference = const value_type&; + + /// a type to represent differences between iterators + using difference_type = std::ptrdiff_t; + /// a type to represent container sizes + using size_type = std::size_t; + + /// the allocator type + using allocator_type = AllocatorType; + + /// the type of an element pointer + using pointer = typename std::allocator_traits::pointer; + /// the type of an element const pointer + using const_pointer = typename std::allocator_traits::const_pointer; + + /// an iterator for a basic_json container + using iterator = iter_impl; + /// a const iterator for a basic_json container + using const_iterator = iter_impl; + /// a reverse iterator for a basic_json container + using reverse_iterator = json_reverse_iterator; + /// a const reverse iterator for a basic_json container + using const_reverse_iterator = json_reverse_iterator; + + /// @} + + + /// @brief returns the allocator associated with the container + /// @sa https://json.nlohmann.me/api/basic_json/get_allocator/ + static allocator_type get_allocator() + { + return allocator_type(); + } + + /// @brief returns version information on the library + /// @sa https://json.nlohmann.me/api/basic_json/meta/ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json meta() + { + basic_json result; + + result["copyright"] = "(C) 2013-2022 Niels Lohmann"; + result["name"] = "JSON for Modern C++"; + result["url"] = "https://github.com/nlohmann/json"; + result["version"]["string"] = + std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." + + std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." + + std::to_string(NLOHMANN_JSON_VERSION_PATCH); + result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR; + result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR; + result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH; + +#ifdef _WIN32 + result["platform"] = "win32"; +#elif defined __linux__ + result["platform"] = "linux"; +#elif defined __APPLE__ + result["platform"] = "apple"; +#elif defined __unix__ + result["platform"] = "unix"; +#else + result["platform"] = "unknown"; +#endif + +#if defined(__ICC) || defined(__INTEL_COMPILER) + result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}}; +#elif defined(__clang__) + result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}}; +#elif defined(__GNUC__) || defined(__GNUG__) + result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}}; +#elif defined(__HP_cc) || defined(__HP_aCC) + result["compiler"] = "hp" +#elif defined(__IBMCPP__) + result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}}; +#elif defined(_MSC_VER) + result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}}; +#elif defined(__PGI) + result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}}; +#elif defined(__SUNPRO_CC) + result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}}; +#else + result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}}; +#endif + +#ifdef __cplusplus + result["compiler"]["c++"] = std::to_string(__cplusplus); +#else + result["compiler"]["c++"] = "unknown"; +#endif + return result; + } + + + /////////////////////////// + // JSON value data types // + /////////////////////////// + + /// @name JSON value data types + /// The data types to store a JSON value. These types are derived from + /// the template arguments passed to class @ref basic_json. + /// @{ + + /// @brief object key comparator type + /// @sa https://json.nlohmann.me/api/basic_json/object_comparator_t/ +#if defined(JSON_HAS_CPP_14) + // Use transparent comparator if possible, combined with perfect forwarding + // on find() and count() calls prevents unnecessary string construction. + using object_comparator_t = std::less<>; +#else + using object_comparator_t = std::less; +#endif + + /// @brief a type for an object + /// @sa https://json.nlohmann.me/api/basic_json/object_t/ + using object_t = ObjectType>>; + + /// @brief a type for an array + /// @sa https://json.nlohmann.me/api/basic_json/array_t/ + using array_t = ArrayType>; + + /// @brief a type for a string + /// @sa https://json.nlohmann.me/api/basic_json/string_t/ + using string_t = StringType; + + /// @brief a type for a boolean + /// @sa https://json.nlohmann.me/api/basic_json/boolean_t/ + using boolean_t = BooleanType; + + /// @brief a type for a number (integer) + /// @sa https://json.nlohmann.me/api/basic_json/number_integer_t/ + using number_integer_t = NumberIntegerType; + + /// @brief a type for a number (unsigned) + /// @sa https://json.nlohmann.me/api/basic_json/number_unsigned_t/ + using number_unsigned_t = NumberUnsignedType; + + /// @brief a type for a number (floating-point) + /// @sa https://json.nlohmann.me/api/basic_json/number_float_t/ + using number_float_t = NumberFloatType; + + /// @brief a type for a packed binary type + /// @sa https://json.nlohmann.me/api/basic_json/binary_t/ + using binary_t = nlohmann::byte_container_with_subtype; + + /// @} + + private: + + /// helper for exception-safe object creation + template + JSON_HEDLEY_RETURNS_NON_NULL + static T* create(Args&& ... args) + { + AllocatorType alloc; + using AllocatorTraits = std::allocator_traits>; + + auto deleter = [&](T * obj) + { + AllocatorTraits::deallocate(alloc, obj, 1); + }; + std::unique_ptr obj(AllocatorTraits::allocate(alloc, 1), deleter); + AllocatorTraits::construct(alloc, obj.get(), std::forward(args)...); + JSON_ASSERT(obj != nullptr); + return obj.release(); + } + + //////////////////////// + // JSON value storage // + //////////////////////// + + JSON_PRIVATE_UNLESS_TESTED: + /*! + @brief a JSON value + + The actual storage for a JSON value of the @ref basic_json class. This + union combines the different storage types for the JSON value types + defined in @ref value_t. + + JSON type | value_t type | used type + --------- | --------------- | ------------------------ + object | object | pointer to @ref object_t + array | array | pointer to @ref array_t + string | string | pointer to @ref string_t + boolean | boolean | @ref boolean_t + number | number_integer | @ref number_integer_t + number | number_unsigned | @ref number_unsigned_t + number | number_float | @ref number_float_t + binary | binary | pointer to @ref binary_t + null | null | *no value is stored* + + @note Variable-length types (objects, arrays, and strings) are stored as + pointers. The size of the union should not exceed 64 bits if the default + value types are used. + + @since version 1.0.0 + */ + union json_value + { + /// object (stored with pointer to save storage) + object_t* object; + /// array (stored with pointer to save storage) + array_t* array; + /// string (stored with pointer to save storage) + string_t* string; + /// binary (stored with pointer to save storage) + binary_t* binary; + /// boolean + boolean_t boolean; + /// number (integer) + number_integer_t number_integer; + /// number (unsigned integer) + number_unsigned_t number_unsigned; + /// number (floating-point) + number_float_t number_float; + + /// default constructor (for null values) + json_value() = default; + /// constructor for booleans + json_value(boolean_t v) noexcept : boolean(v) {} + /// constructor for numbers (integer) + json_value(number_integer_t v) noexcept : number_integer(v) {} + /// constructor for numbers (unsigned) + json_value(number_unsigned_t v) noexcept : number_unsigned(v) {} + /// constructor for numbers (floating-point) + json_value(number_float_t v) noexcept : number_float(v) {} + /// constructor for empty values of a given type + json_value(value_t t) + { + switch (t) + { + case value_t::object: + { + object = create(); + break; + } + + case value_t::array: + { + array = create(); + break; + } + + case value_t::string: + { + string = create(""); + break; + } + + case value_t::binary: + { + binary = create(); + break; + } + + case value_t::boolean: + { + boolean = static_cast(false); + break; + } + + case value_t::number_integer: + { + number_integer = static_cast(0); + break; + } + + case value_t::number_unsigned: + { + number_unsigned = static_cast(0); + break; + } + + case value_t::number_float: + { + number_float = static_cast(0.0); + break; + } + + case value_t::null: + { + object = nullptr; // silence warning, see #821 + break; + } + + case value_t::discarded: + default: + { + object = nullptr; // silence warning, see #821 + if (JSON_HEDLEY_UNLIKELY(t == value_t::null)) + { + JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.10.5", basic_json())); // LCOV_EXCL_LINE + } + break; + } + } + } + + /// constructor for strings + json_value(const string_t& value) : string(create(value)) {} + + /// constructor for rvalue strings + json_value(string_t&& value) : string(create(std::move(value))) {} + + /// constructor for objects + json_value(const object_t& value) : object(create(value)) {} + + /// constructor for rvalue objects + json_value(object_t&& value) : object(create(std::move(value))) {} + + /// constructor for arrays + json_value(const array_t& value) : array(create(value)) {} + + /// constructor for rvalue arrays + json_value(array_t&& value) : array(create(std::move(value))) {} + + /// constructor for binary arrays + json_value(const typename binary_t::container_type& value) : binary(create(value)) {} + + /// constructor for rvalue binary arrays + json_value(typename binary_t::container_type&& value) : binary(create(std::move(value))) {} + + /// constructor for binary arrays (internal type) + json_value(const binary_t& value) : binary(create(value)) {} + + /// constructor for rvalue binary arrays (internal type) + json_value(binary_t&& value) : binary(create(std::move(value))) {} + + void destroy(value_t t) + { + if (t == value_t::array || t == value_t::object) + { + // flatten the current json_value to a heap-allocated stack + std::vector stack; + + // move the top-level items to stack + if (t == value_t::array) + { + stack.reserve(array->size()); + std::move(array->begin(), array->end(), std::back_inserter(stack)); + } + else + { + stack.reserve(object->size()); + for (auto&& it : *object) + { + stack.push_back(std::move(it.second)); + } + } + + while (!stack.empty()) + { + // move the last item to local variable to be processed + basic_json current_item(std::move(stack.back())); + stack.pop_back(); + + // if current_item is array/object, move + // its children to the stack to be processed later + if (current_item.is_array()) + { + std::move(current_item.m_value.array->begin(), current_item.m_value.array->end(), std::back_inserter(stack)); + + current_item.m_value.array->clear(); + } + else if (current_item.is_object()) + { + for (auto&& it : *current_item.m_value.object) + { + stack.push_back(std::move(it.second)); + } + + current_item.m_value.object->clear(); + } + + // it's now safe that current_item get destructed + // since it doesn't have any children + } + } + + switch (t) + { + case value_t::object: + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, object); + std::allocator_traits::deallocate(alloc, object, 1); + break; + } + + case value_t::array: + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, array); + std::allocator_traits::deallocate(alloc, array, 1); + break; + } + + case value_t::string: + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, string); + std::allocator_traits::deallocate(alloc, string, 1); + break; + } + + case value_t::binary: + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, binary); + std::allocator_traits::deallocate(alloc, binary, 1); + break; + } + + case value_t::null: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::discarded: + default: + { + break; + } + } + } + }; + + private: + /*! + @brief checks the class invariants + + This function asserts the class invariants. It needs to be called at the + end of every constructor to make sure that created objects respect the + invariant. Furthermore, it has to be called each time the type of a JSON + value is changed, because the invariant expresses a relationship between + @a m_type and @a m_value. + + Furthermore, the parent relation is checked for arrays and objects: If + @a check_parents true and the value is an array or object, then the + container's elements must have the current value as parent. + + @param[in] check_parents whether the parent relation should be checked. + The value is true by default and should only be set to false + during destruction of objects when the invariant does not + need to hold. + */ + void assert_invariant(bool check_parents = true) const noexcept + { + JSON_ASSERT(m_type != value_t::object || m_value.object != nullptr); + JSON_ASSERT(m_type != value_t::array || m_value.array != nullptr); + JSON_ASSERT(m_type != value_t::string || m_value.string != nullptr); + JSON_ASSERT(m_type != value_t::binary || m_value.binary != nullptr); + +#if JSON_DIAGNOSTICS + JSON_TRY + { + // cppcheck-suppress assertWithSideEffect + JSON_ASSERT(!check_parents || !is_structured() || std::all_of(begin(), end(), [this](const basic_json & j) + { + return j.m_parent == this; + })); + } + JSON_CATCH(...) {} // LCOV_EXCL_LINE +#endif + static_cast(check_parents); + } + + void set_parents() + { +#if JSON_DIAGNOSTICS + switch (m_type) + { + case value_t::array: + { + for (auto& element : *m_value.array) + { + element.m_parent = this; + } + break; + } + + case value_t::object: + { + for (auto& element : *m_value.object) + { + element.second.m_parent = this; + } + break; + } + + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + break; + } +#endif + } + + iterator set_parents(iterator it, typename iterator::difference_type count_set_parents) + { +#if JSON_DIAGNOSTICS + for (typename iterator::difference_type i = 0; i < count_set_parents; ++i) + { + (it + i)->m_parent = this; + } +#else + static_cast(count_set_parents); +#endif + return it; + } + + reference set_parent(reference j, std::size_t old_capacity = static_cast(-1)) + { +#if JSON_DIAGNOSTICS + if (old_capacity != static_cast(-1)) + { + // see https://github.com/nlohmann/json/issues/2838 + JSON_ASSERT(type() == value_t::array); + if (JSON_HEDLEY_UNLIKELY(m_value.array->capacity() != old_capacity)) + { + // capacity has changed: update all parents + set_parents(); + return j; + } + } + + // ordered_json uses a vector internally, so pointers could have + // been invalidated; see https://github.com/nlohmann/json/issues/2962 +#ifdef JSON_HEDLEY_MSVC_VERSION +#pragma warning(push ) +#pragma warning(disable : 4127) // ignore warning to replace if with if constexpr +#endif + if (detail::is_ordered_map::value) + { + set_parents(); + return j; + } +#ifdef JSON_HEDLEY_MSVC_VERSION +#pragma warning( pop ) +#endif + + j.m_parent = this; +#else + static_cast(j); + static_cast(old_capacity); +#endif + return j; + } + + public: + ////////////////////////// + // JSON parser callback // + ////////////////////////// + + /// @brief parser event types + /// @sa https://json.nlohmann.me/api/basic_json/parse_event_t/ + using parse_event_t = detail::parse_event_t; + + /// @brief per-element parser callback type + /// @sa https://json.nlohmann.me/api/basic_json/parser_callback_t/ + using parser_callback_t = detail::parser_callback_t; + + ////////////////// + // constructors // + ////////////////// + + /// @name constructors and destructors + /// Constructors of class @ref basic_json, copy/move constructor, copy + /// assignment, static functions creating objects, and the destructor. + /// @{ + + /// @brief create an empty value with a given type + /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ + basic_json(const value_t v) + : m_type(v), m_value(v) + { + assert_invariant(); + } + + /// @brief create a null object + /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ + basic_json(std::nullptr_t = nullptr) noexcept + : basic_json(value_t::null) + { + assert_invariant(); + } + + /// @brief create a JSON value from compatible types + /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ + template < typename CompatibleType, + typename U = detail::uncvref_t, + detail::enable_if_t < + !detail::is_basic_json::value && detail::is_compatible_type::value, int > = 0 > + basic_json(CompatibleType && val) noexcept(noexcept( // NOLINT(bugprone-forwarding-reference-overload,bugprone-exception-escape) + JSONSerializer::to_json(std::declval(), + std::forward(val)))) + { + JSONSerializer::to_json(*this, std::forward(val)); + set_parents(); + assert_invariant(); + } + + /// @brief create a JSON value from an existing one + /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ + template < typename BasicJsonType, + detail::enable_if_t < + detail::is_basic_json::value&& !std::is_same::value, int > = 0 > + basic_json(const BasicJsonType& val) + { + using other_boolean_t = typename BasicJsonType::boolean_t; + using other_number_float_t = typename BasicJsonType::number_float_t; + using other_number_integer_t = typename BasicJsonType::number_integer_t; + using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using other_string_t = typename BasicJsonType::string_t; + using other_object_t = typename BasicJsonType::object_t; + using other_array_t = typename BasicJsonType::array_t; + using other_binary_t = typename BasicJsonType::binary_t; + + switch (val.type()) + { + case value_t::boolean: + JSONSerializer::to_json(*this, val.template get()); + break; + case value_t::number_float: + JSONSerializer::to_json(*this, val.template get()); + break; + case value_t::number_integer: + JSONSerializer::to_json(*this, val.template get()); + break; + case value_t::number_unsigned: + JSONSerializer::to_json(*this, val.template get()); + break; + case value_t::string: + JSONSerializer::to_json(*this, val.template get_ref()); + break; + case value_t::object: + JSONSerializer::to_json(*this, val.template get_ref()); + break; + case value_t::array: + JSONSerializer::to_json(*this, val.template get_ref()); + break; + case value_t::binary: + JSONSerializer::to_json(*this, val.template get_ref()); + break; + case value_t::null: + *this = nullptr; + break; + case value_t::discarded: + m_type = value_t::discarded; + break; + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + } + set_parents(); + assert_invariant(); + } + + /// @brief create a container (array or object) from an initializer list + /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ + basic_json(initializer_list_t init, + bool type_deduction = true, + value_t manual_type = value_t::array) + { + // check if each element is an array with two elements whose first + // element is a string + bool is_an_object = std::all_of(init.begin(), init.end(), + [](const detail::json_ref& element_ref) + { + return element_ref->is_array() && element_ref->size() == 2 && (*element_ref)[0].is_string(); + }); + + // adjust type if type deduction is not wanted + if (!type_deduction) + { + // if array is wanted, do not create an object though possible + if (manual_type == value_t::array) + { + is_an_object = false; + } + + // if object is wanted but impossible, throw an exception + if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object && !is_an_object)) + { + JSON_THROW(type_error::create(301, "cannot create object from initializer list", basic_json())); + } + } + + if (is_an_object) + { + // the initializer list is a list of pairs -> create object + m_type = value_t::object; + m_value = value_t::object; + + for (auto& element_ref : init) + { + auto element = element_ref.moved_or_copied(); + m_value.object->emplace( + std::move(*((*element.m_value.array)[0].m_value.string)), + std::move((*element.m_value.array)[1])); + } + } + else + { + // the initializer list describes an array -> create array + m_type = value_t::array; + m_value.array = create(init.begin(), init.end()); + } + + set_parents(); + assert_invariant(); + } + + /// @brief explicitly create a binary array (without subtype) + /// @sa https://json.nlohmann.me/api/basic_json/binary/ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json binary(const typename binary_t::container_type& init) + { + auto res = basic_json(); + res.m_type = value_t::binary; + res.m_value = init; + return res; + } + + /// @brief explicitly create a binary array (with subtype) + /// @sa https://json.nlohmann.me/api/basic_json/binary/ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json binary(const typename binary_t::container_type& init, typename binary_t::subtype_type subtype) + { + auto res = basic_json(); + res.m_type = value_t::binary; + res.m_value = binary_t(init, subtype); + return res; + } + + /// @brief explicitly create a binary array + /// @sa https://json.nlohmann.me/api/basic_json/binary/ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json binary(typename binary_t::container_type&& init) + { + auto res = basic_json(); + res.m_type = value_t::binary; + res.m_value = std::move(init); + return res; + } + + /// @brief explicitly create a binary array (with subtype) + /// @sa https://json.nlohmann.me/api/basic_json/binary/ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json binary(typename binary_t::container_type&& init, typename binary_t::subtype_type subtype) + { + auto res = basic_json(); + res.m_type = value_t::binary; + res.m_value = binary_t(std::move(init), subtype); + return res; + } + + /// @brief explicitly create an array from an initializer list + /// @sa https://json.nlohmann.me/api/basic_json/array/ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json array(initializer_list_t init = {}) + { + return basic_json(init, false, value_t::array); + } + + /// @brief explicitly create an object from an initializer list + /// @sa https://json.nlohmann.me/api/basic_json/object/ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json object(initializer_list_t init = {}) + { + return basic_json(init, false, value_t::object); + } + + /// @brief construct an array with count copies of given value + /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ + basic_json(size_type cnt, const basic_json& val) + : m_type(value_t::array) + { + m_value.array = create(cnt, val); + set_parents(); + assert_invariant(); + } + + /// @brief construct a JSON container given an iterator range + /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ + template < class InputIT, typename std::enable_if < + std::is_same::value || + std::is_same::value, int >::type = 0 > + basic_json(InputIT first, InputIT last) + { + JSON_ASSERT(first.m_object != nullptr); + JSON_ASSERT(last.m_object != nullptr); + + // make sure iterator fits the current value + if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) + { + JSON_THROW(invalid_iterator::create(201, "iterators are not compatible", basic_json())); + } + + // copy type from first iterator + m_type = first.m_object->m_type; + + // check if iterator range is complete for primitive values + switch (m_type) + { + case value_t::boolean: + case value_t::number_float: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::string: + { + if (JSON_HEDLEY_UNLIKELY(!first.m_it.primitive_iterator.is_begin() + || !last.m_it.primitive_iterator.is_end())) + { + JSON_THROW(invalid_iterator::create(204, "iterators out of range", *first.m_object)); + } + break; + } + + case value_t::null: + case value_t::object: + case value_t::array: + case value_t::binary: + case value_t::discarded: + default: + break; + } + + switch (m_type) + { + case value_t::number_integer: + { + m_value.number_integer = first.m_object->m_value.number_integer; + break; + } + + case value_t::number_unsigned: + { + m_value.number_unsigned = first.m_object->m_value.number_unsigned; + break; + } + + case value_t::number_float: + { + m_value.number_float = first.m_object->m_value.number_float; + break; + } + + case value_t::boolean: + { + m_value.boolean = first.m_object->m_value.boolean; + break; + } + + case value_t::string: + { + m_value = *first.m_object->m_value.string; + break; + } + + case value_t::object: + { + m_value.object = create(first.m_it.object_iterator, + last.m_it.object_iterator); + break; + } + + case value_t::array: + { + m_value.array = create(first.m_it.array_iterator, + last.m_it.array_iterator); + break; + } + + case value_t::binary: + { + m_value = *first.m_object->m_value.binary; + break; + } + + case value_t::null: + case value_t::discarded: + default: + JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " + std::string(first.m_object->type_name()), *first.m_object)); + } + + set_parents(); + assert_invariant(); + } + + + /////////////////////////////////////// + // other constructors and destructor // + /////////////////////////////////////// + + template, + std::is_same>::value, int> = 0 > + basic_json(const JsonRef& ref) : basic_json(ref.moved_or_copied()) {} + + /// @brief copy constructor + /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ + basic_json(const basic_json& other) + : m_type(other.m_type) + { + // check of passed value is valid + other.assert_invariant(); + + switch (m_type) + { + case value_t::object: + { + m_value = *other.m_value.object; + break; + } + + case value_t::array: + { + m_value = *other.m_value.array; + break; + } + + case value_t::string: + { + m_value = *other.m_value.string; + break; + } + + case value_t::boolean: + { + m_value = other.m_value.boolean; + break; + } + + case value_t::number_integer: + { + m_value = other.m_value.number_integer; + break; + } + + case value_t::number_unsigned: + { + m_value = other.m_value.number_unsigned; + break; + } + + case value_t::number_float: + { + m_value = other.m_value.number_float; + break; + } + + case value_t::binary: + { + m_value = *other.m_value.binary; + break; + } + + case value_t::null: + case value_t::discarded: + default: + break; + } + + set_parents(); + assert_invariant(); + } + + /// @brief move constructor + /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ + basic_json(basic_json&& other) noexcept + : m_type(std::move(other.m_type)), + m_value(std::move(other.m_value)) + { + // check that passed value is valid + other.assert_invariant(false); + + // invalidate payload + other.m_type = value_t::null; + other.m_value = {}; + + set_parents(); + assert_invariant(); + } + + /// @brief copy assignment + /// @sa https://json.nlohmann.me/api/basic_json/operator=/ + basic_json& operator=(basic_json other) noexcept ( + std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_assignable::value&& + std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_assignable::value + ) + { + // check that passed value is valid + other.assert_invariant(); + + using std::swap; + swap(m_type, other.m_type); + swap(m_value, other.m_value); + + set_parents(); + assert_invariant(); + return *this; + } + + /// @brief destructor + /// @sa https://json.nlohmann.me/api/basic_json/~basic_json/ + ~basic_json() noexcept + { + assert_invariant(false); + m_value.destroy(m_type); + } + + /// @} + + public: + /////////////////////// + // object inspection // + /////////////////////// + + /// @name object inspection + /// Functions to inspect the type of a JSON value. + /// @{ + + /// @brief serialization + /// @sa https://json.nlohmann.me/api/basic_json/dump/ + string_t dump(const int indent = -1, + const char indent_char = ' ', + const bool ensure_ascii = false, + const error_handler_t error_handler = error_handler_t::strict) const + { + string_t result; + serializer s(detail::output_adapter(result), indent_char, error_handler); + + if (indent >= 0) + { + s.dump(*this, true, ensure_ascii, static_cast(indent)); + } + else + { + s.dump(*this, false, ensure_ascii, 0); + } + + return result; + } + + /// @brief return the type of the JSON value (explicit) + /// @sa https://json.nlohmann.me/api/basic_json/type/ + constexpr value_t type() const noexcept + { + return m_type; + } + + /// @brief return whether type is primitive + /// @sa https://json.nlohmann.me/api/basic_json/is_primitive/ + constexpr bool is_primitive() const noexcept + { + return is_null() || is_string() || is_boolean() || is_number() || is_binary(); + } + + /// @brief return whether type is structured + /// @sa https://json.nlohmann.me/api/basic_json/is_structured/ + constexpr bool is_structured() const noexcept + { + return is_array() || is_object(); + } + + /// @brief return whether value is null + /// @sa https://json.nlohmann.me/api/basic_json/is_null/ + constexpr bool is_null() const noexcept + { + return m_type == value_t::null; + } + + /// @brief return whether value is a boolean + /// @sa https://json.nlohmann.me/api/basic_json/is_boolean/ + constexpr bool is_boolean() const noexcept + { + return m_type == value_t::boolean; + } + + /// @brief return whether value is a number + /// @sa https://json.nlohmann.me/api/basic_json/is_number/ + constexpr bool is_number() const noexcept + { + return is_number_integer() || is_number_float(); + } + + /// @brief return whether value is an integer number + /// @sa https://json.nlohmann.me/api/basic_json/is_number_integer/ + constexpr bool is_number_integer() const noexcept + { + return m_type == value_t::number_integer || m_type == value_t::number_unsigned; + } + + /// @brief return whether value is an unsigned integer number + /// @sa https://json.nlohmann.me/api/basic_json/is_number_unsigned/ + constexpr bool is_number_unsigned() const noexcept + { + return m_type == value_t::number_unsigned; + } + + /// @brief return whether value is a floating-point number + /// @sa https://json.nlohmann.me/api/basic_json/is_number_float/ + constexpr bool is_number_float() const noexcept + { + return m_type == value_t::number_float; + } + + /// @brief return whether value is an object + /// @sa https://json.nlohmann.me/api/basic_json/is_object/ + constexpr bool is_object() const noexcept + { + return m_type == value_t::object; + } + + /// @brief return whether value is an array + /// @sa https://json.nlohmann.me/api/basic_json/is_array/ + constexpr bool is_array() const noexcept + { + return m_type == value_t::array; + } + + /// @brief return whether value is a string + /// @sa https://json.nlohmann.me/api/basic_json/is_string/ + constexpr bool is_string() const noexcept + { + return m_type == value_t::string; + } + + /// @brief return whether value is a binary array + /// @sa https://json.nlohmann.me/api/basic_json/is_binary/ + constexpr bool is_binary() const noexcept + { + return m_type == value_t::binary; + } + + /// @brief return whether value is discarded + /// @sa https://json.nlohmann.me/api/basic_json/is_discarded/ + constexpr bool is_discarded() const noexcept + { + return m_type == value_t::discarded; + } + + /// @brief return the type of the JSON value (implicit) + /// @sa https://json.nlohmann.me/api/basic_json/operator_value_t/ + constexpr operator value_t() const noexcept + { + return m_type; + } + + /// @} + + private: + ////////////////// + // value access // + ////////////////// + + /// get a boolean (explicit) + boolean_t get_impl(boolean_t* /*unused*/) const + { + if (JSON_HEDLEY_LIKELY(is_boolean())) + { + return m_value.boolean; + } + + JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name()), *this)); + } + + /// get a pointer to the value (object) + object_t* get_impl_ptr(object_t* /*unused*/) noexcept + { + return is_object() ? m_value.object : nullptr; + } + + /// get a pointer to the value (object) + constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept + { + return is_object() ? m_value.object : nullptr; + } + + /// get a pointer to the value (array) + array_t* get_impl_ptr(array_t* /*unused*/) noexcept + { + return is_array() ? m_value.array : nullptr; + } + + /// get a pointer to the value (array) + constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept + { + return is_array() ? m_value.array : nullptr; + } + + /// get a pointer to the value (string) + string_t* get_impl_ptr(string_t* /*unused*/) noexcept + { + return is_string() ? m_value.string : nullptr; + } + + /// get a pointer to the value (string) + constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept + { + return is_string() ? m_value.string : nullptr; + } + + /// get a pointer to the value (boolean) + boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept + { + return is_boolean() ? &m_value.boolean : nullptr; + } + + /// get a pointer to the value (boolean) + constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept + { + return is_boolean() ? &m_value.boolean : nullptr; + } + + /// get a pointer to the value (integer number) + number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept + { + return is_number_integer() ? &m_value.number_integer : nullptr; + } + + /// get a pointer to the value (integer number) + constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept + { + return is_number_integer() ? &m_value.number_integer : nullptr; + } + + /// get a pointer to the value (unsigned number) + number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept + { + return is_number_unsigned() ? &m_value.number_unsigned : nullptr; + } + + /// get a pointer to the value (unsigned number) + constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept + { + return is_number_unsigned() ? &m_value.number_unsigned : nullptr; + } + + /// get a pointer to the value (floating-point number) + number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept + { + return is_number_float() ? &m_value.number_float : nullptr; + } + + /// get a pointer to the value (floating-point number) + constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept + { + return is_number_float() ? &m_value.number_float : nullptr; + } + + /// get a pointer to the value (binary) + binary_t* get_impl_ptr(binary_t* /*unused*/) noexcept + { + return is_binary() ? m_value.binary : nullptr; + } + + /// get a pointer to the value (binary) + constexpr const binary_t* get_impl_ptr(const binary_t* /*unused*/) const noexcept + { + return is_binary() ? m_value.binary : nullptr; + } + + /*! + @brief helper function to implement get_ref() + + This function helps to implement get_ref() without code duplication for + const and non-const overloads + + @tparam ThisType will be deduced as `basic_json` or `const basic_json` + + @throw type_error.303 if ReferenceType does not match underlying value + type of the current JSON + */ + template + static ReferenceType get_ref_impl(ThisType& obj) + { + // delegate the call to get_ptr<>() + auto* ptr = obj.template get_ptr::type>(); + + if (JSON_HEDLEY_LIKELY(ptr != nullptr)) + { + return *ptr; + } + + JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name()), obj)); + } + + public: + /// @name value access + /// Direct access to the stored value of a JSON value. + /// @{ + + /// @brief get a pointer value (implicit) + /// @sa https://json.nlohmann.me/api/basic_json/get_ptr/ + template::value, int>::type = 0> + auto get_ptr() noexcept -> decltype(std::declval().get_impl_ptr(std::declval())) + { + // delegate the call to get_impl_ptr<>() + return get_impl_ptr(static_cast(nullptr)); + } + + /// @brief get a pointer value (implicit) + /// @sa https://json.nlohmann.me/api/basic_json/get_ptr/ + template < typename PointerType, typename std::enable_if < + std::is_pointer::value&& + std::is_const::type>::value, int >::type = 0 > + constexpr auto get_ptr() const noexcept -> decltype(std::declval().get_impl_ptr(std::declval())) + { + // delegate the call to get_impl_ptr<>() const + return get_impl_ptr(static_cast(nullptr)); + } + + private: + /*! + @brief get a value (explicit) + + Explicit type conversion between the JSON value and a compatible value + which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) + and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). + The value is converted by calling the @ref json_serializer + `from_json()` method. + + The function is equivalent to executing + @code {.cpp} + ValueType ret; + JSONSerializer::from_json(*this, ret); + return ret; + @endcode + + This overloads is chosen if: + - @a ValueType is not @ref basic_json, + - @ref json_serializer has a `from_json()` method of the form + `void from_json(const basic_json&, ValueType&)`, and + - @ref json_serializer does not have a `from_json()` method of + the form `ValueType from_json(const basic_json&)` + + @tparam ValueType the returned value type + + @return copy of the JSON value, converted to @a ValueType + + @throw what @ref json_serializer `from_json()` method throws + + @liveexample{The example below shows several conversions from JSON values + to other types. There a few things to note: (1) Floating-point numbers can + be converted to integers\, (2) A JSON array can be converted to a standard + `std::vector`\, (3) A JSON object can be converted to C++ + associative containers such as `std::unordered_map`.,get__ValueType_const} + + @since version 2.1.0 + */ + template < typename ValueType, + detail::enable_if_t < + detail::is_default_constructible::value&& + detail::has_from_json::value, + int > = 0 > + ValueType get_impl(detail::priority_tag<0> /*unused*/) const noexcept(noexcept( + JSONSerializer::from_json(std::declval(), std::declval()))) + { + auto ret = ValueType(); + JSONSerializer::from_json(*this, ret); + return ret; + } + + /*! + @brief get a value (explicit); special case + + Explicit type conversion between the JSON value and a compatible value + which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) + and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). + The value is converted by calling the @ref json_serializer + `from_json()` method. + + The function is equivalent to executing + @code {.cpp} + return JSONSerializer::from_json(*this); + @endcode + + This overloads is chosen if: + - @a ValueType is not @ref basic_json and + - @ref json_serializer has a `from_json()` method of the form + `ValueType from_json(const basic_json&)` + + @note If @ref json_serializer has both overloads of + `from_json()`, this one is chosen. + + @tparam ValueType the returned value type + + @return copy of the JSON value, converted to @a ValueType + + @throw what @ref json_serializer `from_json()` method throws + + @since version 2.1.0 + */ + template < typename ValueType, + detail::enable_if_t < + detail::has_non_default_from_json::value, + int > = 0 > + ValueType get_impl(detail::priority_tag<1> /*unused*/) const noexcept(noexcept( + JSONSerializer::from_json(std::declval()))) + { + return JSONSerializer::from_json(*this); + } + + /*! + @brief get special-case overload + + This overloads converts the current @ref basic_json in a different + @ref basic_json type + + @tparam BasicJsonType == @ref basic_json + + @return a copy of *this, converted into @a BasicJsonType + + @complexity Depending on the implementation of the called `from_json()` + method. + + @since version 3.2.0 + */ + template < typename BasicJsonType, + detail::enable_if_t < + detail::is_basic_json::value, + int > = 0 > + BasicJsonType get_impl(detail::priority_tag<2> /*unused*/) const + { + return *this; + } + + /*! + @brief get special-case overload + + This overloads avoids a lot of template boilerplate, it can be seen as the + identity method + + @tparam BasicJsonType == @ref basic_json + + @return a copy of *this + + @complexity Constant. + + @since version 2.1.0 + */ + template::value, + int> = 0> + basic_json get_impl(detail::priority_tag<3> /*unused*/) const + { + return *this; + } + + /*! + @brief get a pointer value (explicit) + @copydoc get() + */ + template::value, + int> = 0> + constexpr auto get_impl(detail::priority_tag<4> /*unused*/) const noexcept + -> decltype(std::declval().template get_ptr()) + { + // delegate the call to get_ptr + return get_ptr(); + } + + public: + /*! + @brief get a (pointer) value (explicit) + + Performs explicit type conversion between the JSON value and a compatible value if required. + + - If the requested type is a pointer to the internally stored JSON value that pointer is returned. + No copies are made. + + - If the requested type is the current @ref basic_json, or a different @ref basic_json convertible + from the current @ref basic_json. + + - Otherwise the value is converted by calling the @ref json_serializer `from_json()` + method. + + @tparam ValueTypeCV the provided value type + @tparam ValueType the returned value type + + @return copy of the JSON value, converted to @tparam ValueType if necessary + + @throw what @ref json_serializer `from_json()` method throws if conversion is required + + @since version 2.1.0 + */ + template < typename ValueTypeCV, typename ValueType = detail::uncvref_t> +#if defined(JSON_HAS_CPP_14) + constexpr +#endif + auto get() const noexcept( + noexcept(std::declval().template get_impl(detail::priority_tag<4> {}))) + -> decltype(std::declval().template get_impl(detail::priority_tag<4> {})) + { + // we cannot static_assert on ValueTypeCV being non-const, because + // there is support for get(), which is why we + // still need the uncvref + static_assert(!std::is_reference::value, + "get() cannot be used with reference types, you might want to use get_ref()"); + return get_impl(detail::priority_tag<4> {}); + } + + /*! + @brief get a pointer value (explicit) + + Explicit pointer access to the internally stored JSON value. No copies are + made. + + @warning The pointer becomes invalid if the underlying JSON object + changes. + + @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref + object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, + @ref number_unsigned_t, or @ref number_float_t. + + @return pointer to the internally stored JSON value if the requested + pointer type @a PointerType fits to the JSON value; `nullptr` otherwise + + @complexity Constant. + + @liveexample{The example below shows how pointers to internal values of a + JSON value can be requested. Note that no type conversions are made and a + `nullptr` is returned if the value and the requested pointer type does not + match.,get__PointerType} + + @sa see @ref get_ptr() for explicit pointer-member access + + @since version 1.0.0 + */ + template::value, int>::type = 0> + auto get() noexcept -> decltype(std::declval().template get_ptr()) + { + // delegate the call to get_ptr + return get_ptr(); + } + + /// @brief get a value (explicit) + /// @sa https://json.nlohmann.me/api/basic_json/get_to/ + template < typename ValueType, + detail::enable_if_t < + !detail::is_basic_json::value&& + detail::has_from_json::value, + int > = 0 > + ValueType & get_to(ValueType& v) const noexcept(noexcept( + JSONSerializer::from_json(std::declval(), v))) + { + JSONSerializer::from_json(*this, v); + return v; + } + + // specialization to allow calling get_to with a basic_json value + // see https://github.com/nlohmann/json/issues/2175 + template::value, + int> = 0> + ValueType & get_to(ValueType& v) const + { + v = *this; + return v; + } + + template < + typename T, std::size_t N, + typename Array = T (&)[N], // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) + detail::enable_if_t < + detail::has_from_json::value, int > = 0 > + Array get_to(T (&v)[N]) const // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) + noexcept(noexcept(JSONSerializer::from_json( + std::declval(), v))) + { + JSONSerializer::from_json(*this, v); + return v; + } + + /// @brief get a reference value (implicit) + /// @sa https://json.nlohmann.me/api/basic_json/get_ref/ + template::value, int>::type = 0> + ReferenceType get_ref() + { + // delegate call to get_ref_impl + return get_ref_impl(*this); + } + + /// @brief get a reference value (implicit) + /// @sa https://json.nlohmann.me/api/basic_json/get_ref/ + template < typename ReferenceType, typename std::enable_if < + std::is_reference::value&& + std::is_const::type>::value, int >::type = 0 > + ReferenceType get_ref() const + { + // delegate call to get_ref_impl + return get_ref_impl(*this); + } + + /*! + @brief get a value (implicit) + + Implicit type conversion between the JSON value and a compatible value. + The call is realized by calling @ref get() const. + + @tparam ValueType non-pointer type compatible to the JSON value, for + instance `int` for JSON integer numbers, `bool` for JSON booleans, or + `std::vector` types for JSON arrays. The character type of @ref string_t + as well as an initializer list of this type is excluded to avoid + ambiguities as these types implicitly convert to `std::string`. + + @return copy of the JSON value, converted to type @a ValueType + + @throw type_error.302 in case passed type @a ValueType is incompatible + to the JSON value type (e.g., the JSON value is of type boolean, but a + string is requested); see example below + + @complexity Linear in the size of the JSON value. + + @liveexample{The example below shows several conversions from JSON values + to other types. There a few things to note: (1) Floating-point numbers can + be converted to integers\, (2) A JSON array can be converted to a standard + `std::vector`\, (3) A JSON object can be converted to C++ + associative containers such as `std::unordered_map`.,operator__ValueType} + + @since version 1.0.0 + */ + template < typename ValueType, typename std::enable_if < + detail::conjunction < + detail::negation>, + detail::negation>>, + detail::negation>, + detail::negation>, + detail::negation>>, + +#if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1910 && _MSC_VER <= 1914)) + detail::negation>, +#endif + detail::is_detected_lazy + >::value, int >::type = 0 > + JSON_EXPLICIT operator ValueType() const + { + // delegate the call to get<>() const + return get(); + } + + /// @brief get a binary value + /// @sa https://json.nlohmann.me/api/basic_json/get_binary/ + binary_t& get_binary() + { + if (!is_binary()) + { + JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()), *this)); + } + + return *get_ptr(); + } + + /// @brief get a binary value + /// @sa https://json.nlohmann.me/api/basic_json/get_binary/ + const binary_t& get_binary() const + { + if (!is_binary()) + { + JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()), *this)); + } + + return *get_ptr(); + } + + /// @} + + + //////////////////// + // element access // + //////////////////// + + /// @name element access + /// Access to the JSON value. + /// @{ + + /// @brief access specified array element with bounds checking + /// @sa https://json.nlohmann.me/api/basic_json/at/ + reference at(size_type idx) + { + // at only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + JSON_TRY + { + return set_parent(m_value.array->at(idx)); + } + JSON_CATCH (std::out_of_range&) + { + // create better exception explanation + JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this)); + } + } + else + { + JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); + } + } + + /// @brief access specified array element with bounds checking + /// @sa https://json.nlohmann.me/api/basic_json/at/ + const_reference at(size_type idx) const + { + // at only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + JSON_TRY + { + return m_value.array->at(idx); + } + JSON_CATCH (std::out_of_range&) + { + // create better exception explanation + JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this)); + } + } + else + { + JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); + } + } + + /// @brief access specified object element with bounds checking + /// @sa https://json.nlohmann.me/api/basic_json/at/ + reference at(const typename object_t::key_type& key) + { + // at only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + JSON_TRY + { + return set_parent(m_value.object->at(key)); + } + JSON_CATCH (std::out_of_range&) + { + // create better exception explanation + JSON_THROW(out_of_range::create(403, "key '" + key + "' not found", *this)); + } + } + else + { + JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); + } + } + + /// @brief access specified object element with bounds checking + /// @sa https://json.nlohmann.me/api/basic_json/at/ + const_reference at(const typename object_t::key_type& key) const + { + // at only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + JSON_TRY + { + return m_value.object->at(key); + } + JSON_CATCH (std::out_of_range&) + { + // create better exception explanation + JSON_THROW(out_of_range::create(403, "key '" + key + "' not found", *this)); + } + } + else + { + JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); + } + } + + /// @brief access specified array element + /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ + reference operator[](size_type idx) + { + // implicitly convert null value to an empty array + if (is_null()) + { + m_type = value_t::array; + m_value.array = create(); + assert_invariant(); + } + + // operator[] only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + // fill up array with null values if given idx is outside range + if (idx >= m_value.array->size()) + { +#if JSON_DIAGNOSTICS + // remember array size & capacity before resizing + const auto old_size = m_value.array->size(); + const auto old_capacity = m_value.array->capacity(); +#endif + m_value.array->resize(idx + 1); + +#if JSON_DIAGNOSTICS + if (JSON_HEDLEY_UNLIKELY(m_value.array->capacity() != old_capacity)) + { + // capacity has changed: update all parents + set_parents(); + } + else + { + // set parent for values added above + set_parents(begin() + static_cast(old_size), static_cast(idx + 1 - old_size)); + } +#endif + assert_invariant(); + } + + return m_value.array->operator[](idx); + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()), *this)); + } + + /// @brief access specified array element + /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ + const_reference operator[](size_type idx) const + { + // const operator[] only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + return m_value.array->operator[](idx); + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()), *this)); + } + + /// @brief access specified object element + /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ + reference operator[](const typename object_t::key_type& key) + { + // implicitly convert null value to an empty object + if (is_null()) + { + m_type = value_t::object; + m_value.object = create(); + assert_invariant(); + } + + // operator[] only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + return set_parent(m_value.object->operator[](key)); + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); + } + + /// @brief access specified object element + /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ + const_reference operator[](const typename object_t::key_type& key) const + { + // const operator[] only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + JSON_ASSERT(m_value.object->find(key) != m_value.object->end()); + return m_value.object->find(key)->second; + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); + } + + /// @brief access specified object element + /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ + template + JSON_HEDLEY_NON_NULL(2) + reference operator[](T* key) + { + // implicitly convert null to object + if (is_null()) + { + m_type = value_t::object; + m_value = value_t::object; + assert_invariant(); + } + + // at only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + return set_parent(m_value.object->operator[](key)); + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); + } + + /// @brief access specified object element + /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ + template + JSON_HEDLEY_NON_NULL(2) + const_reference operator[](T* key) const + { + // at only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + JSON_ASSERT(m_value.object->find(key) != m_value.object->end()); + return m_value.object->find(key)->second; + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); + } + + /// @brief access specified object element with default value + /// @sa https://json.nlohmann.me/api/basic_json/value/ + /// using std::is_convertible in a std::enable_if will fail when using explicit conversions + template < class ValueType, typename std::enable_if < + detail::is_getable::value + && !std::is_same::value, int >::type = 0 > + ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const + { + // at only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + // if key is found, return value and given default value otherwise + const auto it = find(key); + if (it != end()) + { + return it->template get(); + } + + return default_value; + } + + JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()), *this)); + } + + /// @brief access specified object element with default value + /// @sa https://json.nlohmann.me/api/basic_json/value/ + /// overload for a default value of type const char* + string_t value(const typename object_t::key_type& key, const char* default_value) const + { + return value(key, string_t(default_value)); + } + + /// @brief access specified object element via JSON Pointer with default value + /// @sa https://json.nlohmann.me/api/basic_json/value/ + template::value, int>::type = 0> + ValueType value(const json_pointer& ptr, const ValueType& default_value) const + { + // at only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + // if pointer resolves a value, return it or use default value + JSON_TRY + { + return ptr.get_checked(this).template get(); + } + JSON_INTERNAL_CATCH (out_of_range&) + { + return default_value; + } + } + + JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()), *this)); + } + + /// @brief access specified object element via JSON Pointer with default value + /// @sa https://json.nlohmann.me/api/basic_json/value/ + /// overload for a default value of type const char* + JSON_HEDLEY_NON_NULL(3) + string_t value(const json_pointer& ptr, const char* default_value) const + { + return value(ptr, string_t(default_value)); + } + + /// @brief access the first element + /// @sa https://json.nlohmann.me/api/basic_json/front/ + reference front() + { + return *begin(); + } + + /// @brief access the first element + /// @sa https://json.nlohmann.me/api/basic_json/front/ + const_reference front() const + { + return *cbegin(); + } + + /// @brief access the last element + /// @sa https://json.nlohmann.me/api/basic_json/back/ + reference back() + { + auto tmp = end(); + --tmp; + return *tmp; + } + + /// @brief access the last element + /// @sa https://json.nlohmann.me/api/basic_json/back/ + const_reference back() const + { + auto tmp = cend(); + --tmp; + return *tmp; + } + + /// @brief remove element given an iterator + /// @sa https://json.nlohmann.me/api/basic_json/erase/ + template < class IteratorType, typename std::enable_if < + std::is_same::value || + std::is_same::value, int >::type + = 0 > + IteratorType erase(IteratorType pos) + { + // make sure iterator fits the current value + if (JSON_HEDLEY_UNLIKELY(this != pos.m_object)) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); + } + + IteratorType result = end(); + + switch (m_type) + { + case value_t::boolean: + case value_t::number_float: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::string: + case value_t::binary: + { + if (JSON_HEDLEY_UNLIKELY(!pos.m_it.primitive_iterator.is_begin())) + { + JSON_THROW(invalid_iterator::create(205, "iterator out of range", *this)); + } + + if (is_string()) + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, m_value.string); + std::allocator_traits::deallocate(alloc, m_value.string, 1); + m_value.string = nullptr; + } + else if (is_binary()) + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, m_value.binary); + std::allocator_traits::deallocate(alloc, m_value.binary, 1); + m_value.binary = nullptr; + } + + m_type = value_t::null; + assert_invariant(); + break; + } + + case value_t::object: + { + result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator); + break; + } + + case value_t::array: + { + result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator); + break; + } + + case value_t::null: + case value_t::discarded: + default: + JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); + } + + return result; + } + + /// @brief remove elements given an iterator range + /// @sa https://json.nlohmann.me/api/basic_json/erase/ + template < class IteratorType, typename std::enable_if < + std::is_same::value || + std::is_same::value, int >::type + = 0 > + IteratorType erase(IteratorType first, IteratorType last) + { + // make sure iterator fits the current value + if (JSON_HEDLEY_UNLIKELY(this != first.m_object || this != last.m_object)) + { + JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value", *this)); + } + + IteratorType result = end(); + + switch (m_type) + { + case value_t::boolean: + case value_t::number_float: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::string: + case value_t::binary: + { + if (JSON_HEDLEY_LIKELY(!first.m_it.primitive_iterator.is_begin() + || !last.m_it.primitive_iterator.is_end())) + { + JSON_THROW(invalid_iterator::create(204, "iterators out of range", *this)); + } + + if (is_string()) + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, m_value.string); + std::allocator_traits::deallocate(alloc, m_value.string, 1); + m_value.string = nullptr; + } + else if (is_binary()) + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, m_value.binary); + std::allocator_traits::deallocate(alloc, m_value.binary, 1); + m_value.binary = nullptr; + } + + m_type = value_t::null; + assert_invariant(); + break; + } + + case value_t::object: + { + result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator, + last.m_it.object_iterator); + break; + } + + case value_t::array: + { + result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator, + last.m_it.array_iterator); + break; + } + + case value_t::null: + case value_t::discarded: + default: + JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); + } + + return result; + } + + /// @brief remove element from a JSON object given a key + /// @sa https://json.nlohmann.me/api/basic_json/erase/ + size_type erase(const typename object_t::key_type& key) + { + // this erase only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + return m_value.object->erase(key); + } + + JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); + } + + /// @brief remove element from a JSON array given an index + /// @sa https://json.nlohmann.me/api/basic_json/erase/ + void erase(const size_type idx) + { + // this erase only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + if (JSON_HEDLEY_UNLIKELY(idx >= size())) + { + JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this)); + } + + m_value.array->erase(m_value.array->begin() + static_cast(idx)); + } + else + { + JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); + } + } + + /// @} + + + //////////// + // lookup // + //////////// + + /// @name lookup + /// @{ + + /// @brief find an element in a JSON object + /// @sa https://json.nlohmann.me/api/basic_json/find/ + template + iterator find(KeyT&& key) + { + auto result = end(); + + if (is_object()) + { + result.m_it.object_iterator = m_value.object->find(std::forward(key)); + } + + return result; + } + + /// @brief find an element in a JSON object + /// @sa https://json.nlohmann.me/api/basic_json/find/ + template + const_iterator find(KeyT&& key) const + { + auto result = cend(); + + if (is_object()) + { + result.m_it.object_iterator = m_value.object->find(std::forward(key)); + } + + return result; + } + + /// @brief returns the number of occurrences of a key in a JSON object + /// @sa https://json.nlohmann.me/api/basic_json/count/ + template + size_type count(KeyT&& key) const + { + // return 0 for all nonobject types + return is_object() ? m_value.object->count(std::forward(key)) : 0; + } + + /// @brief check the existence of an element in a JSON object + /// @sa https://json.nlohmann.me/api/basic_json/contains/ + template < typename KeyT, typename std::enable_if < + !std::is_same::type, json_pointer>::value, int >::type = 0 > + bool contains(KeyT && key) const + { + return is_object() && m_value.object->find(std::forward(key)) != m_value.object->end(); + } + + /// @brief check the existence of an element in a JSON object given a JSON pointer + /// @sa https://json.nlohmann.me/api/basic_json/contains/ + bool contains(const json_pointer& ptr) const + { + return ptr.contains(this); + } + + /// @} + + + /////////////// + // iterators // + /////////////// + + /// @name iterators + /// @{ + + /// @brief returns an iterator to the first element + /// @sa https://json.nlohmann.me/api/basic_json/begin/ + iterator begin() noexcept + { + iterator result(this); + result.set_begin(); + return result; + } + + /// @brief returns an iterator to the first element + /// @sa https://json.nlohmann.me/api/basic_json/begin/ + const_iterator begin() const noexcept + { + return cbegin(); + } + + /// @brief returns a const iterator to the first element + /// @sa https://json.nlohmann.me/api/basic_json/cbegin/ + const_iterator cbegin() const noexcept + { + const_iterator result(this); + result.set_begin(); + return result; + } + + /// @brief returns an iterator to one past the last element + /// @sa https://json.nlohmann.me/api/basic_json/end/ + iterator end() noexcept + { + iterator result(this); + result.set_end(); + return result; + } + + /// @brief returns an iterator to one past the last element + /// @sa https://json.nlohmann.me/api/basic_json/end/ + const_iterator end() const noexcept + { + return cend(); + } + + /// @brief returns an iterator to one past the last element + /// @sa https://json.nlohmann.me/api/basic_json/cend/ + const_iterator cend() const noexcept + { + const_iterator result(this); + result.set_end(); + return result; + } + + /// @brief returns an iterator to the reverse-beginning + /// @sa https://json.nlohmann.me/api/basic_json/rbegin/ + reverse_iterator rbegin() noexcept + { + return reverse_iterator(end()); + } + + /// @brief returns an iterator to the reverse-beginning + /// @sa https://json.nlohmann.me/api/basic_json/rbegin/ + const_reverse_iterator rbegin() const noexcept + { + return crbegin(); + } + + /// @brief returns an iterator to the reverse-end + /// @sa https://json.nlohmann.me/api/basic_json/rend/ + reverse_iterator rend() noexcept + { + return reverse_iterator(begin()); + } + + /// @brief returns an iterator to the reverse-end + /// @sa https://json.nlohmann.me/api/basic_json/rend/ + const_reverse_iterator rend() const noexcept + { + return crend(); + } + + /// @brief returns a const reverse iterator to the last element + /// @sa https://json.nlohmann.me/api/basic_json/crbegin/ + const_reverse_iterator crbegin() const noexcept + { + return const_reverse_iterator(cend()); + } + + /// @brief returns a const reverse iterator to one before the first + /// @sa https://json.nlohmann.me/api/basic_json/crend/ + const_reverse_iterator crend() const noexcept + { + return const_reverse_iterator(cbegin()); + } + + public: + /// @brief wrapper to access iterator member functions in range-based for + /// @sa https://json.nlohmann.me/api/basic_json/items/ + /// @deprecated This function is deprecated since 3.1.0 and will be removed in + /// version 4.0.0 of the library. Please use @ref items() instead; + /// that is, replace `json::iterator_wrapper(j)` with `j.items()`. + JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items()) + static iteration_proxy iterator_wrapper(reference ref) noexcept + { + return ref.items(); + } + + /// @brief wrapper to access iterator member functions in range-based for + /// @sa https://json.nlohmann.me/api/basic_json/items/ + /// @deprecated This function is deprecated since 3.1.0 and will be removed in + /// version 4.0.0 of the library. Please use @ref items() instead; + /// that is, replace `json::iterator_wrapper(j)` with `j.items()`. + JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items()) + static iteration_proxy iterator_wrapper(const_reference ref) noexcept + { + return ref.items(); + } + + /// @brief helper to access iterator member functions in range-based for + /// @sa https://json.nlohmann.me/api/basic_json/items/ + iteration_proxy items() noexcept + { + return iteration_proxy(*this); + } + + /// @brief helper to access iterator member functions in range-based for + /// @sa https://json.nlohmann.me/api/basic_json/items/ + iteration_proxy items() const noexcept + { + return iteration_proxy(*this); + } + + /// @} + + + ////////////// + // capacity // + ////////////// + + /// @name capacity + /// @{ + + /// @brief checks whether the container is empty. + /// @sa https://json.nlohmann.me/api/basic_json/empty/ + bool empty() const noexcept + { + switch (m_type) + { + case value_t::null: + { + // null values are empty + return true; + } + + case value_t::array: + { + // delegate call to array_t::empty() + return m_value.array->empty(); + } + + case value_t::object: + { + // delegate call to object_t::empty() + return m_value.object->empty(); + } + + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + // all other types are nonempty + return false; + } + } + } + + /// @brief returns the number of elements + /// @sa https://json.nlohmann.me/api/basic_json/size/ + size_type size() const noexcept + { + switch (m_type) + { + case value_t::null: + { + // null values are empty + return 0; + } + + case value_t::array: + { + // delegate call to array_t::size() + return m_value.array->size(); + } + + case value_t::object: + { + // delegate call to object_t::size() + return m_value.object->size(); + } + + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + // all other types have size 1 + return 1; + } + } + } + + /// @brief returns the maximum possible number of elements + /// @sa https://json.nlohmann.me/api/basic_json/max_size/ + size_type max_size() const noexcept + { + switch (m_type) + { + case value_t::array: + { + // delegate call to array_t::max_size() + return m_value.array->max_size(); + } + + case value_t::object: + { + // delegate call to object_t::max_size() + return m_value.object->max_size(); + } + + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + // all other types have max_size() == size() + return size(); + } + } + } + + /// @} + + + /////////////// + // modifiers // + /////////////// + + /// @name modifiers + /// @{ + + /// @brief clears the contents + /// @sa https://json.nlohmann.me/api/basic_json/clear/ + void clear() noexcept + { + switch (m_type) + { + case value_t::number_integer: + { + m_value.number_integer = 0; + break; + } + + case value_t::number_unsigned: + { + m_value.number_unsigned = 0; + break; + } + + case value_t::number_float: + { + m_value.number_float = 0.0; + break; + } + + case value_t::boolean: + { + m_value.boolean = false; + break; + } + + case value_t::string: + { + m_value.string->clear(); + break; + } + + case value_t::binary: + { + m_value.binary->clear(); + break; + } + + case value_t::array: + { + m_value.array->clear(); + break; + } + + case value_t::object: + { + m_value.object->clear(); + break; + } + + case value_t::null: + case value_t::discarded: + default: + break; + } + } + + /// @brief add an object to an array + /// @sa https://json.nlohmann.me/api/basic_json/push_back/ + void push_back(basic_json&& val) + { + // push_back only works for null objects or arrays + if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) + { + JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this)); + } + + // transform null object into an array + if (is_null()) + { + m_type = value_t::array; + m_value = value_t::array; + assert_invariant(); + } + + // add element to array (move semantics) + const auto old_capacity = m_value.array->capacity(); + m_value.array->push_back(std::move(val)); + set_parent(m_value.array->back(), old_capacity); + // if val is moved from, basic_json move constructor marks it null, so we do not call the destructor + } + + /// @brief add an object to an array + /// @sa https://json.nlohmann.me/api/basic_json/operator+=/ + reference operator+=(basic_json&& val) + { + push_back(std::move(val)); + return *this; + } + + /// @brief add an object to an array + /// @sa https://json.nlohmann.me/api/basic_json/push_back/ + void push_back(const basic_json& val) + { + // push_back only works for null objects or arrays + if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) + { + JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this)); + } + + // transform null object into an array + if (is_null()) + { + m_type = value_t::array; + m_value = value_t::array; + assert_invariant(); + } + + // add element to array + const auto old_capacity = m_value.array->capacity(); + m_value.array->push_back(val); + set_parent(m_value.array->back(), old_capacity); + } + + /// @brief add an object to an array + /// @sa https://json.nlohmann.me/api/basic_json/operator+=/ + reference operator+=(const basic_json& val) + { + push_back(val); + return *this; + } + + /// @brief add an object to an object + /// @sa https://json.nlohmann.me/api/basic_json/push_back/ + void push_back(const typename object_t::value_type& val) + { + // push_back only works for null objects or objects + if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object()))) + { + JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this)); + } + + // transform null object into an object + if (is_null()) + { + m_type = value_t::object; + m_value = value_t::object; + assert_invariant(); + } + + // add element to object + auto res = m_value.object->insert(val); + set_parent(res.first->second); + } + + /// @brief add an object to an object + /// @sa https://json.nlohmann.me/api/basic_json/operator+=/ + reference operator+=(const typename object_t::value_type& val) + { + push_back(val); + return *this; + } + + /// @brief add an object to an object + /// @sa https://json.nlohmann.me/api/basic_json/push_back/ + void push_back(initializer_list_t init) + { + if (is_object() && init.size() == 2 && (*init.begin())->is_string()) + { + basic_json&& key = init.begin()->moved_or_copied(); + push_back(typename object_t::value_type( + std::move(key.get_ref()), (init.begin() + 1)->moved_or_copied())); + } + else + { + push_back(basic_json(init)); + } + } + + /// @brief add an object to an object + /// @sa https://json.nlohmann.me/api/basic_json/operator+=/ + reference operator+=(initializer_list_t init) + { + push_back(init); + return *this; + } + + /// @brief add an object to an array + /// @sa https://json.nlohmann.me/api/basic_json/emplace_back/ + template + reference emplace_back(Args&& ... args) + { + // emplace_back only works for null objects or arrays + if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) + { + JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name()), *this)); + } + + // transform null object into an array + if (is_null()) + { + m_type = value_t::array; + m_value = value_t::array; + assert_invariant(); + } + + // add element to array (perfect forwarding) + const auto old_capacity = m_value.array->capacity(); + m_value.array->emplace_back(std::forward(args)...); + return set_parent(m_value.array->back(), old_capacity); + } + + /// @brief add an object to an object if key does not exist + /// @sa https://json.nlohmann.me/api/basic_json/emplace/ + template + std::pair emplace(Args&& ... args) + { + // emplace only works for null objects or arrays + if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object()))) + { + JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name()), *this)); + } + + // transform null object into an object + if (is_null()) + { + m_type = value_t::object; + m_value = value_t::object; + assert_invariant(); + } + + // add element to array (perfect forwarding) + auto res = m_value.object->emplace(std::forward(args)...); + set_parent(res.first->second); + + // create result iterator and set iterator to the result of emplace + auto it = begin(); + it.m_it.object_iterator = res.first; + + // return pair of iterator and boolean + return {it, res.second}; + } + + /// Helper for insertion of an iterator + /// @note: This uses std::distance to support GCC 4.8, + /// see https://github.com/nlohmann/json/pull/1257 + template + iterator insert_iterator(const_iterator pos, Args&& ... args) + { + iterator result(this); + JSON_ASSERT(m_value.array != nullptr); + + auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator); + m_value.array->insert(pos.m_it.array_iterator, std::forward(args)...); + result.m_it.array_iterator = m_value.array->begin() + insert_pos; + + // This could have been written as: + // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val); + // but the return value of insert is missing in GCC 4.8, so it is written this way instead. + + set_parents(); + return result; + } + + /// @brief inserts element into array + /// @sa https://json.nlohmann.me/api/basic_json/insert/ + iterator insert(const_iterator pos, const basic_json& val) + { + // insert only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + // check if iterator pos fits to this JSON value + if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); + } + + // insert to array and return iterator + return insert_iterator(pos, val); + } + + JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); + } + + /// @brief inserts element into array + /// @sa https://json.nlohmann.me/api/basic_json/insert/ + iterator insert(const_iterator pos, basic_json&& val) + { + return insert(pos, val); + } + + /// @brief inserts copies of element into array + /// @sa https://json.nlohmann.me/api/basic_json/insert/ + iterator insert(const_iterator pos, size_type cnt, const basic_json& val) + { + // insert only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + // check if iterator pos fits to this JSON value + if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); + } + + // insert to array and return iterator + return insert_iterator(pos, cnt, val); + } + + JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); + } + + /// @brief inserts range of elements into array + /// @sa https://json.nlohmann.me/api/basic_json/insert/ + iterator insert(const_iterator pos, const_iterator first, const_iterator last) + { + // insert only works for arrays + if (JSON_HEDLEY_UNLIKELY(!is_array())) + { + JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); + } + + // check if iterator pos fits to this JSON value + if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); + } + + // check if range iterators belong to the same JSON object + if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) + { + JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this)); + } + + if (JSON_HEDLEY_UNLIKELY(first.m_object == this)) + { + JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container", *this)); + } + + // insert to array and return iterator + return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator); + } + + /// @brief inserts elements from initializer list into array + /// @sa https://json.nlohmann.me/api/basic_json/insert/ + iterator insert(const_iterator pos, initializer_list_t ilist) + { + // insert only works for arrays + if (JSON_HEDLEY_UNLIKELY(!is_array())) + { + JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); + } + + // check if iterator pos fits to this JSON value + if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); + } + + // insert to array and return iterator + return insert_iterator(pos, ilist.begin(), ilist.end()); + } + + /// @brief inserts range of elements into object + /// @sa https://json.nlohmann.me/api/basic_json/insert/ + void insert(const_iterator first, const_iterator last) + { + // insert only works for objects + if (JSON_HEDLEY_UNLIKELY(!is_object())) + { + JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); + } + + // check if range iterators belong to the same JSON object + if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) + { + JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this)); + } + + // passed iterators must belong to objects + if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object())) + { + JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects", *this)); + } + + m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator); + } + + /// @brief updates a JSON object from another object, overwriting existing keys + /// @sa https://json.nlohmann.me/api/basic_json/update/ + void update(const_reference j, bool merge_objects = false) + { + update(j.begin(), j.end(), merge_objects); + } + + /// @brief updates a JSON object from another object, overwriting existing keys + /// @sa https://json.nlohmann.me/api/basic_json/update/ + void update(const_iterator first, const_iterator last, bool merge_objects = false) + { + // implicitly convert null value to an empty object + if (is_null()) + { + m_type = value_t::object; + m_value.object = create(); + assert_invariant(); + } + + if (JSON_HEDLEY_UNLIKELY(!is_object())) + { + JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()), *this)); + } + + // check if range iterators belong to the same JSON object + if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) + { + JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this)); + } + + // passed iterators must belong to objects + if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object())) + { + JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(first.m_object->type_name()), *first.m_object)); + } + + for (auto it = first; it != last; ++it) + { + if (merge_objects && it.value().is_object()) + { + auto it2 = m_value.object->find(it.key()); + if (it2 != m_value.object->end()) + { + it2->second.update(it.value(), true); + continue; + } + } + m_value.object->operator[](it.key()) = it.value(); +#if JSON_DIAGNOSTICS + m_value.object->operator[](it.key()).m_parent = this; +#endif + } + } + + /// @brief exchanges the values + /// @sa https://json.nlohmann.me/api/basic_json/swap/ + void swap(reference other) noexcept ( + std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_assignable::value&& + std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_assignable::value + ) + { + std::swap(m_type, other.m_type); + std::swap(m_value, other.m_value); + + set_parents(); + other.set_parents(); + assert_invariant(); + } + + /// @brief exchanges the values + /// @sa https://json.nlohmann.me/api/basic_json/swap/ + friend void swap(reference left, reference right) noexcept ( + std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_assignable::value&& + std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_assignable::value + ) + { + left.swap(right); + } + + /// @brief exchanges the values + /// @sa https://json.nlohmann.me/api/basic_json/swap/ + void swap(array_t& other) // NOLINT(bugprone-exception-escape) + { + // swap only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + std::swap(*(m_value.array), other); + } + else + { + JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); + } + } + + /// @brief exchanges the values + /// @sa https://json.nlohmann.me/api/basic_json/swap/ + void swap(object_t& other) // NOLINT(bugprone-exception-escape) + { + // swap only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + std::swap(*(m_value.object), other); + } + else + { + JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); + } + } + + /// @brief exchanges the values + /// @sa https://json.nlohmann.me/api/basic_json/swap/ + void swap(string_t& other) // NOLINT(bugprone-exception-escape) + { + // swap only works for strings + if (JSON_HEDLEY_LIKELY(is_string())) + { + std::swap(*(m_value.string), other); + } + else + { + JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); + } + } + + /// @brief exchanges the values + /// @sa https://json.nlohmann.me/api/basic_json/swap/ + void swap(binary_t& other) // NOLINT(bugprone-exception-escape) + { + // swap only works for strings + if (JSON_HEDLEY_LIKELY(is_binary())) + { + std::swap(*(m_value.binary), other); + } + else + { + JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); + } + } + + /// @brief exchanges the values + /// @sa https://json.nlohmann.me/api/basic_json/swap/ + void swap(typename binary_t::container_type& other) // NOLINT(bugprone-exception-escape) + { + // swap only works for strings + if (JSON_HEDLEY_LIKELY(is_binary())) + { + std::swap(*(m_value.binary), other); + } + else + { + JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); + } + } + + /// @} + + public: + ////////////////////////////////////////// + // lexicographical comparison operators // + ////////////////////////////////////////// + + /// @name lexicographical comparison operators + /// @{ + + /// @brief comparison: equal + /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/ + friend bool operator==(const_reference lhs, const_reference rhs) noexcept + { +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif + const auto lhs_type = lhs.type(); + const auto rhs_type = rhs.type(); + + if (lhs_type == rhs_type) + { + switch (lhs_type) + { + case value_t::array: + return *lhs.m_value.array == *rhs.m_value.array; + + case value_t::object: + return *lhs.m_value.object == *rhs.m_value.object; + + case value_t::null: + return true; + + case value_t::string: + return *lhs.m_value.string == *rhs.m_value.string; + + case value_t::boolean: + return lhs.m_value.boolean == rhs.m_value.boolean; + + case value_t::number_integer: + return lhs.m_value.number_integer == rhs.m_value.number_integer; + + case value_t::number_unsigned: + return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned; + + case value_t::number_float: + return lhs.m_value.number_float == rhs.m_value.number_float; + + case value_t::binary: + return *lhs.m_value.binary == *rhs.m_value.binary; + + case value_t::discarded: + default: + return false; + } + } + else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float) + { + return static_cast(lhs.m_value.number_integer) == rhs.m_value.number_float; + } + else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer) + { + return lhs.m_value.number_float == static_cast(rhs.m_value.number_integer); + } + else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float) + { + return static_cast(lhs.m_value.number_unsigned) == rhs.m_value.number_float; + } + else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned) + { + return lhs.m_value.number_float == static_cast(rhs.m_value.number_unsigned); + } + else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer) + { + return static_cast(lhs.m_value.number_unsigned) == rhs.m_value.number_integer; + } + else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned) + { + return lhs.m_value.number_integer == static_cast(rhs.m_value.number_unsigned); + } + + return false; +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif + } + + /// @brief comparison: equal + /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/ + template::value, int>::type = 0> + friend bool operator==(const_reference lhs, ScalarType rhs) noexcept + { + return lhs == basic_json(rhs); + } + + /// @brief comparison: equal + /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/ + template::value, int>::type = 0> + friend bool operator==(ScalarType lhs, const_reference rhs) noexcept + { + return basic_json(lhs) == rhs; + } + + /// @brief comparison: not equal + /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/ + friend bool operator!=(const_reference lhs, const_reference rhs) noexcept + { + return !(lhs == rhs); + } + + /// @brief comparison: not equal + /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/ + template::value, int>::type = 0> + friend bool operator!=(const_reference lhs, ScalarType rhs) noexcept + { + return lhs != basic_json(rhs); + } + + /// @brief comparison: not equal + /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/ + template::value, int>::type = 0> + friend bool operator!=(ScalarType lhs, const_reference rhs) noexcept + { + return basic_json(lhs) != rhs; + } + + /// @brief comparison: less than + /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/ + friend bool operator<(const_reference lhs, const_reference rhs) noexcept + { + const auto lhs_type = lhs.type(); + const auto rhs_type = rhs.type(); + + if (lhs_type == rhs_type) + { + switch (lhs_type) + { + case value_t::array: + // note parentheses are necessary, see + // https://github.com/nlohmann/json/issues/1530 + return (*lhs.m_value.array) < (*rhs.m_value.array); + + case value_t::object: + return (*lhs.m_value.object) < (*rhs.m_value.object); + + case value_t::null: + return false; + + case value_t::string: + return (*lhs.m_value.string) < (*rhs.m_value.string); + + case value_t::boolean: + return (lhs.m_value.boolean) < (rhs.m_value.boolean); + + case value_t::number_integer: + return (lhs.m_value.number_integer) < (rhs.m_value.number_integer); + + case value_t::number_unsigned: + return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned); + + case value_t::number_float: + return (lhs.m_value.number_float) < (rhs.m_value.number_float); + + case value_t::binary: + return (*lhs.m_value.binary) < (*rhs.m_value.binary); + + case value_t::discarded: + default: + return false; + } + } + else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float) + { + return static_cast(lhs.m_value.number_integer) < rhs.m_value.number_float; + } + else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer) + { + return lhs.m_value.number_float < static_cast(rhs.m_value.number_integer); + } + else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float) + { + return static_cast(lhs.m_value.number_unsigned) < rhs.m_value.number_float; + } + else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned) + { + return lhs.m_value.number_float < static_cast(rhs.m_value.number_unsigned); + } + else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned) + { + return lhs.m_value.number_integer < static_cast(rhs.m_value.number_unsigned); + } + else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer) + { + return static_cast(lhs.m_value.number_unsigned) < rhs.m_value.number_integer; + } + + // We only reach this line if we cannot compare values. In that case, + // we compare types. Note we have to call the operator explicitly, + // because MSVC has problems otherwise. + return operator<(lhs_type, rhs_type); + } + + /// @brief comparison: less than + /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/ + template::value, int>::type = 0> + friend bool operator<(const_reference lhs, ScalarType rhs) noexcept + { + return lhs < basic_json(rhs); + } + + /// @brief comparison: less than + /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/ + template::value, int>::type = 0> + friend bool operator<(ScalarType lhs, const_reference rhs) noexcept + { + return basic_json(lhs) < rhs; + } + + /// @brief comparison: less than or equal + /// @sa https://json.nlohmann.me/api/basic_json/operator_le/ + friend bool operator<=(const_reference lhs, const_reference rhs) noexcept + { + return !(rhs < lhs); + } + + /// @brief comparison: less than or equal + /// @sa https://json.nlohmann.me/api/basic_json/operator_le/ + template::value, int>::type = 0> + friend bool operator<=(const_reference lhs, ScalarType rhs) noexcept + { + return lhs <= basic_json(rhs); + } + + /// @brief comparison: less than or equal + /// @sa https://json.nlohmann.me/api/basic_json/operator_le/ + template::value, int>::type = 0> + friend bool operator<=(ScalarType lhs, const_reference rhs) noexcept + { + return basic_json(lhs) <= rhs; + } + + /// @brief comparison: greater than + /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/ + friend bool operator>(const_reference lhs, const_reference rhs) noexcept + { + return !(lhs <= rhs); + } + + /// @brief comparison: greater than + /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/ + template::value, int>::type = 0> + friend bool operator>(const_reference lhs, ScalarType rhs) noexcept + { + return lhs > basic_json(rhs); + } + + /// @brief comparison: greater than + /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/ + template::value, int>::type = 0> + friend bool operator>(ScalarType lhs, const_reference rhs) noexcept + { + return basic_json(lhs) > rhs; + } + + /// @brief comparison: greater than or equal + /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/ + friend bool operator>=(const_reference lhs, const_reference rhs) noexcept + { + return !(lhs < rhs); + } + + /// @brief comparison: greater than or equal + /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/ + template::value, int>::type = 0> + friend bool operator>=(const_reference lhs, ScalarType rhs) noexcept + { + return lhs >= basic_json(rhs); + } + + /// @brief comparison: greater than or equal + /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/ + template::value, int>::type = 0> + friend bool operator>=(ScalarType lhs, const_reference rhs) noexcept + { + return basic_json(lhs) >= rhs; + } + + /// @} + + /////////////////// + // serialization // + /////////////////// + + /// @name serialization + /// @{ +#ifndef JSON_NO_IO + /// @brief serialize to stream + /// @sa https://json.nlohmann.me/api/basic_json/operator_ltlt/ + friend std::ostream& operator<<(std::ostream& o, const basic_json& j) + { + // read width member and use it as indentation parameter if nonzero + const bool pretty_print = o.width() > 0; + const auto indentation = pretty_print ? o.width() : 0; + + // reset width to 0 for subsequent calls to this stream + o.width(0); + + // do the actual serialization + serializer s(detail::output_adapter(o), o.fill()); + s.dump(j, pretty_print, false, static_cast(indentation)); + return o; + } + + /// @brief serialize to stream + /// @sa https://json.nlohmann.me/api/basic_json/operator_ltlt/ + /// @deprecated This function is deprecated since 3.0.0 and will be removed in + /// version 4.0.0 of the library. Please use + /// operator<<(std::ostream&, const basic_json&) instead; that is, + /// replace calls like `j >> o;` with `o << j;`. + JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator<<(std::ostream&, const basic_json&)) + friend std::ostream& operator>>(const basic_json& j, std::ostream& o) + { + return o << j; + } +#endif // JSON_NO_IO + /// @} + + + ///////////////////// + // deserialization // + ///////////////////// + + /// @name deserialization + /// @{ + + /// @brief deserialize from a compatible input + /// @sa https://json.nlohmann.me/api/basic_json/parse/ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json parse(InputType&& i, + const parser_callback_t cb = nullptr, + const bool allow_exceptions = true, + const bool ignore_comments = false) + { + basic_json result; + parser(detail::input_adapter(std::forward(i)), cb, allow_exceptions, ignore_comments).parse(true, result); + return result; + } + + /// @brief deserialize from a pair of character iterators + /// @sa https://json.nlohmann.me/api/basic_json/parse/ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json parse(IteratorType first, + IteratorType last, + const parser_callback_t cb = nullptr, + const bool allow_exceptions = true, + const bool ignore_comments = false) + { + basic_json result; + parser(detail::input_adapter(std::move(first), std::move(last)), cb, allow_exceptions, ignore_comments).parse(true, result); + return result; + } + + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, parse(ptr, ptr + len)) + static basic_json parse(detail::span_input_adapter&& i, + const parser_callback_t cb = nullptr, + const bool allow_exceptions = true, + const bool ignore_comments = false) + { + basic_json result; + parser(i.get(), cb, allow_exceptions, ignore_comments).parse(true, result); + return result; + } + + /// @brief check if the input is valid JSON + /// @sa https://json.nlohmann.me/api/basic_json/accept/ + template + static bool accept(InputType&& i, + const bool ignore_comments = false) + { + return parser(detail::input_adapter(std::forward(i)), nullptr, false, ignore_comments).accept(true); + } + + /// @brief check if the input is valid JSON + /// @sa https://json.nlohmann.me/api/basic_json/accept/ + template + static bool accept(IteratorType first, IteratorType last, + const bool ignore_comments = false) + { + return parser(detail::input_adapter(std::move(first), std::move(last)), nullptr, false, ignore_comments).accept(true); + } + + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, accept(ptr, ptr + len)) + static bool accept(detail::span_input_adapter&& i, + const bool ignore_comments = false) + { + return parser(i.get(), nullptr, false, ignore_comments).accept(true); + } + + /// @brief generate SAX events + /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/ + template + JSON_HEDLEY_NON_NULL(2) + static bool sax_parse(InputType&& i, SAX* sax, + input_format_t format = input_format_t::json, + const bool strict = true, + const bool ignore_comments = false) + { + auto ia = detail::input_adapter(std::forward(i)); + return format == input_format_t::json + ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) + : detail::binary_reader(std::move(ia)).sax_parse(format, sax, strict); + } + + /// @brief generate SAX events + /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/ + template + JSON_HEDLEY_NON_NULL(3) + static bool sax_parse(IteratorType first, IteratorType last, SAX* sax, + input_format_t format = input_format_t::json, + const bool strict = true, + const bool ignore_comments = false) + { + auto ia = detail::input_adapter(std::move(first), std::move(last)); + return format == input_format_t::json + ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) + : detail::binary_reader(std::move(ia)).sax_parse(format, sax, strict); + } + + /// @brief generate SAX events + /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/ + /// @deprecated This function is deprecated since 3.8.0 and will be removed in + /// version 4.0.0 of the library. Please use + /// sax_parse(ptr, ptr + len) instead. + template + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, sax_parse(ptr, ptr + len, ...)) + JSON_HEDLEY_NON_NULL(2) + static bool sax_parse(detail::span_input_adapter&& i, SAX* sax, + input_format_t format = input_format_t::json, + const bool strict = true, + const bool ignore_comments = false) + { + auto ia = i.get(); + return format == input_format_t::json + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) + ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) + : detail::binary_reader(std::move(ia)).sax_parse(format, sax, strict); + } +#ifndef JSON_NO_IO + /// @brief deserialize from stream + /// @sa https://json.nlohmann.me/api/basic_json/operator_gtgt/ + /// @deprecated This stream operator is deprecated since 3.0.0 and will be removed in + /// version 4.0.0 of the library. Please use + /// operator>>(std::istream&, basic_json&) instead; that is, + /// replace calls like `j << i;` with `i >> j;`. + JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator>>(std::istream&, basic_json&)) + friend std::istream& operator<<(basic_json& j, std::istream& i) + { + return operator>>(i, j); + } + + /// @brief deserialize from stream + /// @sa https://json.nlohmann.me/api/basic_json/operator_gtgt/ + friend std::istream& operator>>(std::istream& i, basic_json& j) + { + parser(detail::input_adapter(i)).parse(false, j); + return i; + } +#endif // JSON_NO_IO + /// @} + + /////////////////////////// + // convenience functions // + /////////////////////////// + + /// @brief return the type as string + /// @sa https://json.nlohmann.me/api/basic_json/type_name/ + JSON_HEDLEY_RETURNS_NON_NULL + const char* type_name() const noexcept + { + switch (m_type) + { + case value_t::null: + return "null"; + case value_t::object: + return "object"; + case value_t::array: + return "array"; + case value_t::string: + return "string"; + case value_t::boolean: + return "boolean"; + case value_t::binary: + return "binary"; + case value_t::discarded: + return "discarded"; + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + default: + return "number"; + } + } + + + JSON_PRIVATE_UNLESS_TESTED: + ////////////////////// + // member variables // + ////////////////////// + + /// the type of the current element + value_t m_type = value_t::null; + + /// the value of the current element + json_value m_value = {}; + +#if JSON_DIAGNOSTICS + /// a pointer to a parent value (for debugging purposes) + basic_json* m_parent = nullptr; +#endif + + ////////////////////////////////////////// + // binary serialization/deserialization // + ////////////////////////////////////////// + + /// @name binary serialization/deserialization support + /// @{ + + public: + /// @brief create a CBOR serialization of a given JSON value + /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/ + static std::vector to_cbor(const basic_json& j) + { + std::vector result; + to_cbor(j, result); + return result; + } + + /// @brief create a CBOR serialization of a given JSON value + /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/ + static void to_cbor(const basic_json& j, detail::output_adapter o) + { + binary_writer(o).write_cbor(j); + } + + /// @brief create a CBOR serialization of a given JSON value + /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/ + static void to_cbor(const basic_json& j, detail::output_adapter o) + { + binary_writer(o).write_cbor(j); + } + + /// @brief create a MessagePack serialization of a given JSON value + /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/ + static std::vector to_msgpack(const basic_json& j) + { + std::vector result; + to_msgpack(j, result); + return result; + } + + /// @brief create a MessagePack serialization of a given JSON value + /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/ + static void to_msgpack(const basic_json& j, detail::output_adapter o) + { + binary_writer(o).write_msgpack(j); + } + + /// @brief create a MessagePack serialization of a given JSON value + /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/ + static void to_msgpack(const basic_json& j, detail::output_adapter o) + { + binary_writer(o).write_msgpack(j); + } + + /// @brief create a UBJSON serialization of a given JSON value + /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/ + static std::vector to_ubjson(const basic_json& j, + const bool use_size = false, + const bool use_type = false) + { + std::vector result; + to_ubjson(j, result, use_size, use_type); + return result; + } + + /// @brief create a UBJSON serialization of a given JSON value + /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/ + static void to_ubjson(const basic_json& j, detail::output_adapter o, + const bool use_size = false, const bool use_type = false) + { + binary_writer(o).write_ubjson(j, use_size, use_type); + } + + /// @brief create a UBJSON serialization of a given JSON value + /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/ + static void to_ubjson(const basic_json& j, detail::output_adapter o, + const bool use_size = false, const bool use_type = false) + { + binary_writer(o).write_ubjson(j, use_size, use_type); + } + + /// @brief create a BSON serialization of a given JSON value + /// @sa https://json.nlohmann.me/api/basic_json/to_bson/ + static std::vector to_bson(const basic_json& j) + { + std::vector result; + to_bson(j, result); + return result; + } + + /// @brief create a BSON serialization of a given JSON value + /// @sa https://json.nlohmann.me/api/basic_json/to_bson/ + static void to_bson(const basic_json& j, detail::output_adapter o) + { + binary_writer(o).write_bson(j); + } + + /// @brief create a BSON serialization of a given JSON value + /// @sa https://json.nlohmann.me/api/basic_json/to_bson/ + static void to_bson(const basic_json& j, detail::output_adapter o) + { + binary_writer(o).write_bson(j); + } + + /// @brief create a JSON value from an input in CBOR format + /// @sa https://json.nlohmann.me/api/basic_json/from_cbor/ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_cbor(InputType&& i, + const bool strict = true, + const bool allow_exceptions = true, + const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::forward(i)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); + return res ? result : basic_json(value_t::discarded); + } + + /// @brief create a JSON value from an input in CBOR format + /// @sa https://json.nlohmann.me/api/basic_json/from_cbor/ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_cbor(IteratorType first, IteratorType last, + const bool strict = true, + const bool allow_exceptions = true, + const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::move(first), std::move(last)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); + return res ? result : basic_json(value_t::discarded); + } + + template + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len)) + static basic_json from_cbor(const T* ptr, std::size_t len, + const bool strict = true, + const bool allow_exceptions = true, + const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) + { + return from_cbor(ptr, ptr + len, strict, allow_exceptions, tag_handler); + } + + + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len)) + static basic_json from_cbor(detail::span_input_adapter&& i, + const bool strict = true, + const bool allow_exceptions = true, + const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = i.get(); + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); + return res ? result : basic_json(value_t::discarded); + } + + /// @brief create a JSON value from an input in MessagePack format + /// @sa https://json.nlohmann.me/api/basic_json/from_msgpack/ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_msgpack(InputType&& i, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::forward(i)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + /// @brief create a JSON value from an input in MessagePack format + /// @sa https://json.nlohmann.me/api/basic_json/from_msgpack/ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_msgpack(IteratorType first, IteratorType last, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::move(first), std::move(last)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + template + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len)) + static basic_json from_msgpack(const T* ptr, std::size_t len, + const bool strict = true, + const bool allow_exceptions = true) + { + return from_msgpack(ptr, ptr + len, strict, allow_exceptions); + } + + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len)) + static basic_json from_msgpack(detail::span_input_adapter&& i, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = i.get(); + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + /// @brief create a JSON value from an input in UBJSON format + /// @sa https://json.nlohmann.me/api/basic_json/from_ubjson/ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_ubjson(InputType&& i, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::forward(i)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + /// @brief create a JSON value from an input in UBJSON format + /// @sa https://json.nlohmann.me/api/basic_json/from_ubjson/ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_ubjson(IteratorType first, IteratorType last, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::move(first), std::move(last)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + template + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len)) + static basic_json from_ubjson(const T* ptr, std::size_t len, + const bool strict = true, + const bool allow_exceptions = true) + { + return from_ubjson(ptr, ptr + len, strict, allow_exceptions); + } + + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len)) + static basic_json from_ubjson(detail::span_input_adapter&& i, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = i.get(); + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + /// @brief create a JSON value from an input in BSON format + /// @sa https://json.nlohmann.me/api/basic_json/from_bson/ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_bson(InputType&& i, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::forward(i)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + /// @brief create a JSON value from an input in BSON format + /// @sa https://json.nlohmann.me/api/basic_json/from_bson/ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_bson(IteratorType first, IteratorType last, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::move(first), std::move(last)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + template + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len)) + static basic_json from_bson(const T* ptr, std::size_t len, + const bool strict = true, + const bool allow_exceptions = true) + { + return from_bson(ptr, ptr + len, strict, allow_exceptions); + } + + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len)) + static basic_json from_bson(detail::span_input_adapter&& i, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = i.get(); + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + /// @} + + ////////////////////////// + // JSON Pointer support // + ////////////////////////// + + /// @name JSON Pointer functions + /// @{ + + /// @brief access specified element via JSON Pointer + /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ + reference operator[](const json_pointer& ptr) + { + return ptr.get_unchecked(this); + } + + /// @brief access specified element via JSON Pointer + /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ + const_reference operator[](const json_pointer& ptr) const + { + return ptr.get_unchecked(this); + } + + /// @brief access specified element via JSON Pointer + /// @sa https://json.nlohmann.me/api/basic_json/at/ + reference at(const json_pointer& ptr) + { + return ptr.get_checked(this); + } + + /// @brief access specified element via JSON Pointer + /// @sa https://json.nlohmann.me/api/basic_json/at/ + const_reference at(const json_pointer& ptr) const + { + return ptr.get_checked(this); + } + + /// @brief return flattened JSON value + /// @sa https://json.nlohmann.me/api/basic_json/flatten/ + basic_json flatten() const + { + basic_json result(value_t::object); + json_pointer::flatten("", *this, result); + return result; + } + + /// @brief unflatten a previously flattened JSON value + /// @sa https://json.nlohmann.me/api/basic_json/unflatten/ + basic_json unflatten() const + { + return json_pointer::unflatten(*this); + } + + /// @} + + ////////////////////////// + // JSON Patch functions // + ////////////////////////// + + /// @name JSON Patch functions + /// @{ + + /// @brief applies a JSON patch + /// @sa https://json.nlohmann.me/api/basic_json/patch/ + basic_json patch(const basic_json& json_patch) const + { + // make a working copy to apply the patch to + basic_json result = *this; + + // the valid JSON Patch operations + enum class patch_operations {add, remove, replace, move, copy, test, invalid}; + + const auto get_op = [](const std::string & op) + { + if (op == "add") + { + return patch_operations::add; + } + if (op == "remove") + { + return patch_operations::remove; + } + if (op == "replace") + { + return patch_operations::replace; + } + if (op == "move") + { + return patch_operations::move; + } + if (op == "copy") + { + return patch_operations::copy; + } + if (op == "test") + { + return patch_operations::test; + } + + return patch_operations::invalid; + }; + + // wrapper for "add" operation; add value at ptr + const auto operation_add = [&result](json_pointer & ptr, basic_json val) + { + // adding to the root of the target document means replacing it + if (ptr.empty()) + { + result = val; + return; + } + + // make sure the top element of the pointer exists + json_pointer top_pointer = ptr.top(); + if (top_pointer != ptr) + { + result.at(top_pointer); + } + + // get reference to parent of JSON pointer ptr + const auto last_path = ptr.back(); + ptr.pop_back(); + basic_json& parent = result[ptr]; + + switch (parent.m_type) + { + case value_t::null: + case value_t::object: + { + // use operator[] to add value + parent[last_path] = val; + break; + } + + case value_t::array: + { + if (last_path == "-") + { + // special case: append to back + parent.push_back(val); + } + else + { + const auto idx = json_pointer::array_index(last_path); + if (JSON_HEDLEY_UNLIKELY(idx > parent.size())) + { + // avoid undefined behavior + JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", parent)); + } + + // default case: insert add offset + parent.insert(parent.begin() + static_cast(idx), val); + } + break; + } + + // if there exists a parent it cannot be primitive + case value_t::string: // LCOV_EXCL_LINE + case value_t::boolean: // LCOV_EXCL_LINE + case value_t::number_integer: // LCOV_EXCL_LINE + case value_t::number_unsigned: // LCOV_EXCL_LINE + case value_t::number_float: // LCOV_EXCL_LINE + case value_t::binary: // LCOV_EXCL_LINE + case value_t::discarded: // LCOV_EXCL_LINE + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + } + }; + + // wrapper for "remove" operation; remove value at ptr + const auto operation_remove = [this, &result](json_pointer & ptr) + { + // get reference to parent of JSON pointer ptr + const auto last_path = ptr.back(); + ptr.pop_back(); + basic_json& parent = result.at(ptr); + + // remove child + if (parent.is_object()) + { + // perform range check + auto it = parent.find(last_path); + if (JSON_HEDLEY_LIKELY(it != parent.end())) + { + parent.erase(it); + } + else + { + JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found", *this)); + } + } + else if (parent.is_array()) + { + // note erase performs range check + parent.erase(json_pointer::array_index(last_path)); + } + }; + + // type check: top level value must be an array + if (JSON_HEDLEY_UNLIKELY(!json_patch.is_array())) + { + JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", json_patch)); + } + + // iterate and apply the operations + for (const auto& val : json_patch) + { + // wrapper to get a value for an operation + const auto get_value = [&val](const std::string & op, + const std::string & member, + bool string_type) -> basic_json & + { + // find value + auto it = val.m_value.object->find(member); + + // context-sensitive error message + const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'"; + + // check if desired value is present + if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end())) + { + // NOLINTNEXTLINE(performance-inefficient-string-concatenation) + JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'", val)); + } + + // check if result is of type string + if (JSON_HEDLEY_UNLIKELY(string_type && !it->second.is_string())) + { + // NOLINTNEXTLINE(performance-inefficient-string-concatenation) + JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'", val)); + } + + // no error: return value + return it->second; + }; + + // type check: every element of the array must be an object + if (JSON_HEDLEY_UNLIKELY(!val.is_object())) + { + JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", val)); + } + + // collect mandatory members + const auto op = get_value("op", "op", true).template get(); + const auto path = get_value(op, "path", true).template get(); + json_pointer ptr(path); + + switch (get_op(op)) + { + case patch_operations::add: + { + operation_add(ptr, get_value("add", "value", false)); + break; + } + + case patch_operations::remove: + { + operation_remove(ptr); + break; + } + + case patch_operations::replace: + { + // the "path" location must exist - use at() + result.at(ptr) = get_value("replace", "value", false); + break; + } + + case patch_operations::move: + { + const auto from_path = get_value("move", "from", true).template get(); + json_pointer from_ptr(from_path); + + // the "from" location must exist - use at() + basic_json v = result.at(from_ptr); + + // The move operation is functionally identical to a + // "remove" operation on the "from" location, followed + // immediately by an "add" operation at the target + // location with the value that was just removed. + operation_remove(from_ptr); + operation_add(ptr, v); + break; + } + + case patch_operations::copy: + { + const auto from_path = get_value("copy", "from", true).template get(); + const json_pointer from_ptr(from_path); + + // the "from" location must exist - use at() + basic_json v = result.at(from_ptr); + + // The copy is functionally identical to an "add" + // operation at the target location using the value + // specified in the "from" member. + operation_add(ptr, v); + break; + } + + case patch_operations::test: + { + bool success = false; + JSON_TRY + { + // check if "value" matches the one at "path" + // the "path" location must exist - use at() + success = (result.at(ptr) == get_value("test", "value", false)); + } + JSON_INTERNAL_CATCH (out_of_range&) + { + // ignore out of range errors: success remains false + } + + // throw an exception if test fails + if (JSON_HEDLEY_UNLIKELY(!success)) + { + JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump(), val)); + } + + break; + } + + case patch_operations::invalid: + default: + { + // op must be "add", "remove", "replace", "move", "copy", or + // "test" + JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid", val)); + } + } + } + + return result; + } + + /// @brief creates a diff as a JSON patch + /// @sa https://json.nlohmann.me/api/basic_json/diff/ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json diff(const basic_json& source, const basic_json& target, + const std::string& path = "") + { + // the patch + basic_json result(value_t::array); + + // if the values are the same, return empty patch + if (source == target) + { + return result; + } + + if (source.type() != target.type()) + { + // different types: replace value + result.push_back( + { + {"op", "replace"}, {"path", path}, {"value", target} + }); + return result; + } + + switch (source.type()) + { + case value_t::array: + { + // first pass: traverse common elements + std::size_t i = 0; + while (i < source.size() && i < target.size()) + { + // recursive call to compare array values at index i + auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i)); + result.insert(result.end(), temp_diff.begin(), temp_diff.end()); + ++i; + } + + // We now reached the end of at least one array + // in a second pass, traverse the remaining elements + + // remove my remaining elements + const auto end_index = static_cast(result.size()); + while (i < source.size()) + { + // add operations in reverse order to avoid invalid + // indices + result.insert(result.begin() + end_index, object( + { + {"op", "remove"}, + {"path", path + "/" + std::to_string(i)} + })); + ++i; + } + + // add other remaining elements + while (i < target.size()) + { + result.push_back( + { + {"op", "add"}, + {"path", path + "/-"}, + {"value", target[i]} + }); + ++i; + } + + break; + } + + case value_t::object: + { + // first pass: traverse this object's elements + for (auto it = source.cbegin(); it != source.cend(); ++it) + { + // escape the key name to be used in a JSON patch + const auto path_key = path + "/" + detail::escape(it.key()); + + if (target.find(it.key()) != target.end()) + { + // recursive call to compare object values at key it + auto temp_diff = diff(it.value(), target[it.key()], path_key); + result.insert(result.end(), temp_diff.begin(), temp_diff.end()); + } + else + { + // found a key that is not in o -> remove it + result.push_back(object( + { + {"op", "remove"}, {"path", path_key} + })); + } + } + + // second pass: traverse other object's elements + for (auto it = target.cbegin(); it != target.cend(); ++it) + { + if (source.find(it.key()) == source.end()) + { + // found a key that is not in this -> add it + const auto path_key = path + "/" + detail::escape(it.key()); + result.push_back( + { + {"op", "add"}, {"path", path_key}, + {"value", it.value()} + }); + } + } + + break; + } + + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + // both primitive type: replace value + result.push_back( + { + {"op", "replace"}, {"path", path}, {"value", target} + }); + break; + } + } + + return result; + } + + /// @} + + //////////////////////////////// + // JSON Merge Patch functions // + //////////////////////////////// + + /// @name JSON Merge Patch functions + /// @{ + + /// @brief applies a JSON Merge Patch + /// @sa https://json.nlohmann.me/api/basic_json/merge_patch/ + void merge_patch(const basic_json& apply_patch) + { + if (apply_patch.is_object()) + { + if (!is_object()) + { + *this = object(); + } + for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it) + { + if (it.value().is_null()) + { + erase(it.key()); + } + else + { + operator[](it.key()).merge_patch(it.value()); + } + } + } + else + { + *this = apply_patch; + } + } + + /// @} +}; + +/// @brief user-defined to_string function for JSON values +/// @sa https://json.nlohmann.me/api/basic_json/to_string/ +NLOHMANN_BASIC_JSON_TPL_DECLARATION +std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j) +{ + return j.dump(); +} + +} // namespace nlohmann + +/////////////////////// +// nonmember support // +/////////////////////// + +namespace std // NOLINT(cert-dcl58-cpp) +{ + +/// @brief hash value for JSON objects +/// @sa https://json.nlohmann.me/api/basic_json/std_hash/ +NLOHMANN_BASIC_JSON_TPL_DECLARATION +struct hash +{ + std::size_t operator()(const nlohmann::NLOHMANN_BASIC_JSON_TPL& j) const + { + return nlohmann::detail::hash(j); + } +}; + +// specialization for std::less +template<> +struct less< ::nlohmann::detail::value_t> // do not remove the space after '<', see https://github.com/nlohmann/json/pull/679 +{ + /*! + @brief compare two value_t enum values + @since version 3.0.0 + */ + bool operator()(nlohmann::detail::value_t lhs, + nlohmann::detail::value_t rhs) const noexcept + { + return nlohmann::detail::operator<(lhs, rhs); + } +}; + +// C++20 prohibit function specialization in the std namespace. +#ifndef JSON_HAS_CPP_20 + +/// @brief exchanges the values of two JSON objects +/// @sa https://json.nlohmann.me/api/basic_json/std_swap/ +NLOHMANN_BASIC_JSON_TPL_DECLARATION +inline void swap(nlohmann::NLOHMANN_BASIC_JSON_TPL& j1, nlohmann::NLOHMANN_BASIC_JSON_TPL& j2) noexcept( // NOLINT(readability-inconsistent-declaration-parameter-name) + is_nothrow_move_constructible::value&& // NOLINT(misc-redundant-expression) + is_nothrow_move_assignable::value) +{ + j1.swap(j2); +} + +#endif + +} // namespace std + +/// @brief user-defined string literal for JSON values +/// @sa https://json.nlohmann.me/api/basic_json/operator_literal_json/ +JSON_HEDLEY_NON_NULL(1) +inline nlohmann::json operator "" _json(const char* s, std::size_t n) +{ + return nlohmann::json::parse(s, s + n); +} + +/// @brief user-defined string literal for JSON pointer +/// @sa https://json.nlohmann.me/api/basic_json/operator_literal_json_pointer/ +JSON_HEDLEY_NON_NULL(1) +inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n) +{ + return nlohmann::json::json_pointer(std::string(s, n)); +} + +// #include + + +// restore clang diagnostic settings +#if defined(__clang__) + #pragma clang diagnostic pop +#endif + +// clean up +#undef JSON_ASSERT +#undef JSON_INTERNAL_CATCH +#undef JSON_CATCH +#undef JSON_THROW +#undef JSON_TRY +#undef JSON_PRIVATE_UNLESS_TESTED +#undef JSON_HAS_CPP_11 +#undef JSON_HAS_CPP_14 +#undef JSON_HAS_CPP_17 +#undef JSON_HAS_CPP_20 +#undef JSON_HAS_FILESYSTEM +#undef JSON_HAS_EXPERIMENTAL_FILESYSTEM +#undef NLOHMANN_BASIC_JSON_TPL_DECLARATION +#undef NLOHMANN_BASIC_JSON_TPL +#undef JSON_EXPLICIT +#undef NLOHMANN_CAN_CALL_STD_FUNC_IMPL + +// #include + + +#undef JSON_HEDLEY_ALWAYS_INLINE +#undef JSON_HEDLEY_ARM_VERSION +#undef JSON_HEDLEY_ARM_VERSION_CHECK +#undef JSON_HEDLEY_ARRAY_PARAM +#undef JSON_HEDLEY_ASSUME +#undef JSON_HEDLEY_BEGIN_C_DECLS +#undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE +#undef JSON_HEDLEY_CLANG_HAS_BUILTIN +#undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE +#undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE +#undef JSON_HEDLEY_CLANG_HAS_EXTENSION +#undef JSON_HEDLEY_CLANG_HAS_FEATURE +#undef JSON_HEDLEY_CLANG_HAS_WARNING +#undef JSON_HEDLEY_COMPCERT_VERSION +#undef JSON_HEDLEY_COMPCERT_VERSION_CHECK +#undef JSON_HEDLEY_CONCAT +#undef JSON_HEDLEY_CONCAT3 +#undef JSON_HEDLEY_CONCAT3_EX +#undef JSON_HEDLEY_CONCAT_EX +#undef JSON_HEDLEY_CONST +#undef JSON_HEDLEY_CONSTEXPR +#undef JSON_HEDLEY_CONST_CAST +#undef JSON_HEDLEY_CPP_CAST +#undef JSON_HEDLEY_CRAY_VERSION +#undef JSON_HEDLEY_CRAY_VERSION_CHECK +#undef JSON_HEDLEY_C_DECL +#undef JSON_HEDLEY_DEPRECATED +#undef JSON_HEDLEY_DEPRECATED_FOR +#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ +#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#undef JSON_HEDLEY_DIAGNOSTIC_POP +#undef JSON_HEDLEY_DIAGNOSTIC_PUSH +#undef JSON_HEDLEY_DMC_VERSION +#undef JSON_HEDLEY_DMC_VERSION_CHECK +#undef JSON_HEDLEY_EMPTY_BASES +#undef JSON_HEDLEY_EMSCRIPTEN_VERSION +#undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK +#undef JSON_HEDLEY_END_C_DECLS +#undef JSON_HEDLEY_FLAGS +#undef JSON_HEDLEY_FLAGS_CAST +#undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE +#undef JSON_HEDLEY_GCC_HAS_BUILTIN +#undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE +#undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE +#undef JSON_HEDLEY_GCC_HAS_EXTENSION +#undef JSON_HEDLEY_GCC_HAS_FEATURE +#undef JSON_HEDLEY_GCC_HAS_WARNING +#undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK +#undef JSON_HEDLEY_GCC_VERSION +#undef JSON_HEDLEY_GCC_VERSION_CHECK +#undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE +#undef JSON_HEDLEY_GNUC_HAS_BUILTIN +#undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE +#undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE +#undef JSON_HEDLEY_GNUC_HAS_EXTENSION +#undef JSON_HEDLEY_GNUC_HAS_FEATURE +#undef JSON_HEDLEY_GNUC_HAS_WARNING +#undef JSON_HEDLEY_GNUC_VERSION +#undef JSON_HEDLEY_GNUC_VERSION_CHECK +#undef JSON_HEDLEY_HAS_ATTRIBUTE +#undef JSON_HEDLEY_HAS_BUILTIN +#undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE +#undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS +#undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE +#undef JSON_HEDLEY_HAS_EXTENSION +#undef JSON_HEDLEY_HAS_FEATURE +#undef JSON_HEDLEY_HAS_WARNING +#undef JSON_HEDLEY_IAR_VERSION +#undef JSON_HEDLEY_IAR_VERSION_CHECK +#undef JSON_HEDLEY_IBM_VERSION +#undef JSON_HEDLEY_IBM_VERSION_CHECK +#undef JSON_HEDLEY_IMPORT +#undef JSON_HEDLEY_INLINE +#undef JSON_HEDLEY_INTEL_CL_VERSION +#undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK +#undef JSON_HEDLEY_INTEL_VERSION +#undef JSON_HEDLEY_INTEL_VERSION_CHECK +#undef JSON_HEDLEY_IS_CONSTANT +#undef JSON_HEDLEY_IS_CONSTEXPR_ +#undef JSON_HEDLEY_LIKELY +#undef JSON_HEDLEY_MALLOC +#undef JSON_HEDLEY_MCST_LCC_VERSION +#undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK +#undef JSON_HEDLEY_MESSAGE +#undef JSON_HEDLEY_MSVC_VERSION +#undef JSON_HEDLEY_MSVC_VERSION_CHECK +#undef JSON_HEDLEY_NEVER_INLINE +#undef JSON_HEDLEY_NON_NULL +#undef JSON_HEDLEY_NO_ESCAPE +#undef JSON_HEDLEY_NO_RETURN +#undef JSON_HEDLEY_NO_THROW +#undef JSON_HEDLEY_NULL +#undef JSON_HEDLEY_PELLES_VERSION +#undef JSON_HEDLEY_PELLES_VERSION_CHECK +#undef JSON_HEDLEY_PGI_VERSION +#undef JSON_HEDLEY_PGI_VERSION_CHECK +#undef JSON_HEDLEY_PREDICT +#undef JSON_HEDLEY_PRINTF_FORMAT +#undef JSON_HEDLEY_PRIVATE +#undef JSON_HEDLEY_PUBLIC +#undef JSON_HEDLEY_PURE +#undef JSON_HEDLEY_REINTERPRET_CAST +#undef JSON_HEDLEY_REQUIRE +#undef JSON_HEDLEY_REQUIRE_CONSTEXPR +#undef JSON_HEDLEY_REQUIRE_MSG +#undef JSON_HEDLEY_RESTRICT +#undef JSON_HEDLEY_RETURNS_NON_NULL +#undef JSON_HEDLEY_SENTINEL +#undef JSON_HEDLEY_STATIC_ASSERT +#undef JSON_HEDLEY_STATIC_CAST +#undef JSON_HEDLEY_STRINGIFY +#undef JSON_HEDLEY_STRINGIFY_EX +#undef JSON_HEDLEY_SUNPRO_VERSION +#undef JSON_HEDLEY_SUNPRO_VERSION_CHECK +#undef JSON_HEDLEY_TINYC_VERSION +#undef JSON_HEDLEY_TINYC_VERSION_CHECK +#undef JSON_HEDLEY_TI_ARMCL_VERSION +#undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK +#undef JSON_HEDLEY_TI_CL2000_VERSION +#undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK +#undef JSON_HEDLEY_TI_CL430_VERSION +#undef JSON_HEDLEY_TI_CL430_VERSION_CHECK +#undef JSON_HEDLEY_TI_CL6X_VERSION +#undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK +#undef JSON_HEDLEY_TI_CL7X_VERSION +#undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK +#undef JSON_HEDLEY_TI_CLPRU_VERSION +#undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK +#undef JSON_HEDLEY_TI_VERSION +#undef JSON_HEDLEY_TI_VERSION_CHECK +#undef JSON_HEDLEY_UNAVAILABLE +#undef JSON_HEDLEY_UNLIKELY +#undef JSON_HEDLEY_UNPREDICTABLE +#undef JSON_HEDLEY_UNREACHABLE +#undef JSON_HEDLEY_UNREACHABLE_RETURN +#undef JSON_HEDLEY_VERSION +#undef JSON_HEDLEY_VERSION_DECODE_MAJOR +#undef JSON_HEDLEY_VERSION_DECODE_MINOR +#undef JSON_HEDLEY_VERSION_DECODE_REVISION +#undef JSON_HEDLEY_VERSION_ENCODE +#undef JSON_HEDLEY_WARNING +#undef JSON_HEDLEY_WARN_UNUSED_RESULT +#undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG +#undef JSON_HEDLEY_FALL_THROUGH + + + +#endif // INCLUDE_NLOHMANN_JSON_HPP_ diff --git a/3rdParty/nlohmann/json_fwd.hpp b/3rdParty/nlohmann/json_fwd.hpp index 2d5ba384be..bdcc45b660 100644 --- a/3rdParty/nlohmann/json_fwd.hpp +++ b/3rdParty/nlohmann/json_fwd.hpp @@ -1,64 +1,64 @@ -#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ -#define INCLUDE_NLOHMANN_JSON_FWD_HPP_ - -#include // int64_t, uint64_t -#include // map -#include // allocator -#include // string -#include // vector - -/*! -@brief namespace for Niels Lohmann -@see https://github.com/nlohmann -@since version 1.0.0 -*/ -namespace nlohmann -{ -/*! -@brief default JSONSerializer template argument - -This serializer ignores the template arguments and uses ADL -([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) -for serialization. -*/ -template -struct adl_serializer; - -/// a class to store JSON values -/// @sa https://json.nlohmann.me/api/basic_json/ -template class ObjectType = - std::map, - template class ArrayType = std::vector, - class StringType = std::string, class BooleanType = bool, - class NumberIntegerType = std::int64_t, - class NumberUnsignedType = std::uint64_t, - class NumberFloatType = double, - template class AllocatorType = std::allocator, - template class JSONSerializer = - adl_serializer, - class BinaryType = std::vector> -class basic_json; - -/// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document -/// @sa https://json.nlohmann.me/api/json_pointer/ -template -class json_pointer; - -/*! -@brief default specialization -@sa https://json.nlohmann.me/api/json/ -*/ -using json = basic_json<>; - -/// @brief a minimal map-like container that preserves insertion order -/// @sa https://json.nlohmann.me/api/ordered_map/ -template -struct ordered_map; - -/// @brief specialization that maintains the insertion order of object keys -/// @sa https://json.nlohmann.me/api/ordered_json/ -using ordered_json = basic_json; - -} // namespace nlohmann - -#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ +#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ +#define INCLUDE_NLOHMANN_JSON_FWD_HPP_ + +#include // int64_t, uint64_t +#include // map +#include // allocator +#include // string +#include // vector + +/*! +@brief namespace for Niels Lohmann +@see https://github.com/nlohmann +@since version 1.0.0 +*/ +namespace nlohmann +{ +/*! +@brief default JSONSerializer template argument + +This serializer ignores the template arguments and uses ADL +([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) +for serialization. +*/ +template +struct adl_serializer; + +/// a class to store JSON values +/// @sa https://json.nlohmann.me/api/basic_json/ +template class ObjectType = + std::map, + template class ArrayType = std::vector, + class StringType = std::string, class BooleanType = bool, + class NumberIntegerType = std::int64_t, + class NumberUnsignedType = std::uint64_t, + class NumberFloatType = double, + template class AllocatorType = std::allocator, + template class JSONSerializer = + adl_serializer, + class BinaryType = std::vector> +class basic_json; + +/// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document +/// @sa https://json.nlohmann.me/api/json_pointer/ +template +class json_pointer; + +/*! +@brief default specialization +@sa https://json.nlohmann.me/api/json/ +*/ +using json = basic_json<>; + +/// @brief a minimal map-like container that preserves insertion order +/// @sa https://json.nlohmann.me/api/ordered_map/ +template +struct ordered_map; + +/// @brief specialization that maintains the insertion order of object keys +/// @sa https://json.nlohmann.me/api/ordered_json/ +using ordered_json = basic_json; + +} // namespace nlohmann + +#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ diff --git a/3rdParty/opencv-4.11.0/opencv2/calib3d.hpp b/3rdParty/opencv-4.11.0/opencv2/calib3d.hpp index f44dacbedf..a0245b81b1 100644 --- a/3rdParty/opencv-4.11.0/opencv2/calib3d.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/calib3d.hpp @@ -1,4146 +1,4146 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CALIB3D_HPP -#define OPENCV_CALIB3D_HPP - -#include "opencv2/core.hpp" -#include "opencv2/core/types.hpp" -#include "opencv2/features2d.hpp" -#include "opencv2/core/affine.hpp" -#include "opencv2/core/utils/logger.hpp" - -/** - @defgroup calib3d Camera Calibration and 3D Reconstruction - -The functions in this section use a so-called pinhole camera model. The view of a scene -is obtained by projecting a scene's 3D point \f$P_w\f$ into the image plane using a perspective -transformation which forms the corresponding pixel \f$p\f$. Both \f$P_w\f$ and \f$p\f$ are -represented in homogeneous coordinates, i.e. as 3D and 2D homogeneous vector respectively. You will -find a brief introduction to projective geometry, homogeneous vectors and homogeneous -transformations at the end of this section's introduction. For more succinct notation, we often drop -the 'homogeneous' and say vector instead of homogeneous vector. - -The distortion-free projective transformation given by a pinhole camera model is shown below. - -\f[s \; p = A \begin{bmatrix} R|t \end{bmatrix} P_w,\f] - -where \f$P_w\f$ is a 3D point expressed with respect to the world coordinate system, -\f$p\f$ is a 2D pixel in the image plane, \f$A\f$ is the camera intrinsic matrix, -\f$R\f$ and \f$t\f$ are the rotation and translation that describe the change of coordinates from -world to camera coordinate systems (or camera frame) and \f$s\f$ is the projective transformation's -arbitrary scaling and not part of the camera model. - -The camera intrinsic matrix \f$A\f$ (notation used as in @cite Zhang2000 and also generally notated -as \f$K\f$) projects 3D points given in the camera coordinate system to 2D pixel coordinates, i.e. - -\f[p = A P_c.\f] - -The camera intrinsic matrix \f$A\f$ is composed of the focal lengths \f$f_x\f$ and \f$f_y\f$, which are -expressed in pixel units, and the principal point \f$(c_x, c_y)\f$, that is usually close to the -image center: - -\f[A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1},\f] - -and thus - -\f[s \vecthree{u}{v}{1} = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1} \vecthree{X_c}{Y_c}{Z_c}.\f] - -The matrix of intrinsic parameters does not depend on the scene viewed. So, once estimated, it can -be re-used as long as the focal length is fixed (in case of a zoom lens). Thus, if an image from the -camera is scaled by a factor, all of these parameters need to be scaled (multiplied/divided, -respectively) by the same factor. - -The joint rotation-translation matrix \f$[R|t]\f$ is the matrix product of a projective -transformation and a homogeneous transformation. The 3-by-4 projective transformation maps 3D points -represented in camera coordinates to 2D points in the image plane and represented in normalized -camera coordinates \f$x' = X_c / Z_c\f$ and \f$y' = Y_c / Z_c\f$: - -\f[Z_c \begin{bmatrix} -x' \\ -y' \\ -1 -\end{bmatrix} = \begin{bmatrix} -1 & 0 & 0 & 0 \\ -0 & 1 & 0 & 0 \\ -0 & 0 & 1 & 0 -\end{bmatrix} -\begin{bmatrix} -X_c \\ -Y_c \\ -Z_c \\ -1 -\end{bmatrix}.\f] - -The homogeneous transformation is encoded by the extrinsic parameters \f$R\f$ and \f$t\f$ and -represents the change of basis from world coordinate system \f$w\f$ to the camera coordinate sytem -\f$c\f$. Thus, given the representation of the point \f$P\f$ in world coordinates, \f$P_w\f$, we -obtain \f$P\f$'s representation in the camera coordinate system, \f$P_c\f$, by - -\f[P_c = \begin{bmatrix} -R & t \\ -0 & 1 -\end{bmatrix} P_w,\f] - -This homogeneous transformation is composed out of \f$R\f$, a 3-by-3 rotation matrix, and \f$t\f$, a -3-by-1 translation vector: - -\f[\begin{bmatrix} -R & t \\ -0 & 1 -\end{bmatrix} = \begin{bmatrix} -r_{11} & r_{12} & r_{13} & t_x \\ -r_{21} & r_{22} & r_{23} & t_y \\ -r_{31} & r_{32} & r_{33} & t_z \\ -0 & 0 & 0 & 1 -\end{bmatrix}, -\f] - -and therefore - -\f[\begin{bmatrix} -X_c \\ -Y_c \\ -Z_c \\ -1 -\end{bmatrix} = \begin{bmatrix} -r_{11} & r_{12} & r_{13} & t_x \\ -r_{21} & r_{22} & r_{23} & t_y \\ -r_{31} & r_{32} & r_{33} & t_z \\ -0 & 0 & 0 & 1 -\end{bmatrix} -\begin{bmatrix} -X_w \\ -Y_w \\ -Z_w \\ -1 -\end{bmatrix}.\f] - -Combining the projective transformation and the homogeneous transformation, we obtain the projective -transformation that maps 3D points in world coordinates into 2D points in the image plane and in -normalized camera coordinates: - -\f[Z_c \begin{bmatrix} -x' \\ -y' \\ -1 -\end{bmatrix} = \begin{bmatrix} R|t \end{bmatrix} \begin{bmatrix} -X_w \\ -Y_w \\ -Z_w \\ -1 -\end{bmatrix} = \begin{bmatrix} -r_{11} & r_{12} & r_{13} & t_x \\ -r_{21} & r_{22} & r_{23} & t_y \\ -r_{31} & r_{32} & r_{33} & t_z -\end{bmatrix} -\begin{bmatrix} -X_w \\ -Y_w \\ -Z_w \\ -1 -\end{bmatrix},\f] - -with \f$x' = X_c / Z_c\f$ and \f$y' = Y_c / Z_c\f$. Putting the equations for instrincs and extrinsics together, we can write out -\f$s \; p = A \begin{bmatrix} R|t \end{bmatrix} P_w\f$ as - -\f[s \vecthree{u}{v}{1} = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1} -\begin{bmatrix} -r_{11} & r_{12} & r_{13} & t_x \\ -r_{21} & r_{22} & r_{23} & t_y \\ -r_{31} & r_{32} & r_{33} & t_z -\end{bmatrix} -\begin{bmatrix} -X_w \\ -Y_w \\ -Z_w \\ -1 -\end{bmatrix}.\f] - -If \f$Z_c \ne 0\f$, the transformation above is equivalent to the following, - -\f[\begin{bmatrix} -u \\ -v -\end{bmatrix} = \begin{bmatrix} -f_x X_c/Z_c + c_x \\ -f_y Y_c/Z_c + c_y -\end{bmatrix}\f] - -with - -\f[\vecthree{X_c}{Y_c}{Z_c} = \begin{bmatrix} -R|t -\end{bmatrix} \begin{bmatrix} -X_w \\ -Y_w \\ -Z_w \\ -1 -\end{bmatrix}.\f] - -The following figure illustrates the pinhole camera model. - -![Pinhole camera model](pics/pinhole_camera_model.png) - -Real lenses usually have some distortion, mostly radial distortion, and slight tangential distortion. -So, the above model is extended as: - -\f[\begin{bmatrix} -u \\ -v -\end{bmatrix} = \begin{bmatrix} -f_x x'' + c_x \\ -f_y y'' + c_y -\end{bmatrix}\f] - -where - -\f[\begin{bmatrix} -x'' \\ -y'' -\end{bmatrix} = \begin{bmatrix} -x' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} + 2 p_1 x' y' + p_2(r^2 + 2 x'^2) + s_1 r^2 + s_2 r^4 \\ -y' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} + p_1 (r^2 + 2 y'^2) + 2 p_2 x' y' + s_3 r^2 + s_4 r^4 \\ -\end{bmatrix}\f] - -with - -\f[r^2 = x'^2 + y'^2\f] - -and - -\f[\begin{bmatrix} -x'\\ -y' -\end{bmatrix} = \begin{bmatrix} -X_c/Z_c \\ -Y_c/Z_c -\end{bmatrix},\f] - -if \f$Z_c \ne 0\f$. - -The distortion parameters are the radial coefficients \f$k_1\f$, \f$k_2\f$, \f$k_3\f$, \f$k_4\f$, \f$k_5\f$, and \f$k_6\f$ -,\f$p_1\f$ and \f$p_2\f$ are the tangential distortion coefficients, and \f$s_1\f$, \f$s_2\f$, \f$s_3\f$, and \f$s_4\f$, -are the thin prism distortion coefficients. Higher-order coefficients are not considered in OpenCV. - -The next figures show two common types of radial distortion: barrel distortion -(\f$ 1 + k_1 r^2 + k_2 r^4 + k_3 r^6 \f$ monotonically decreasing) -and pincushion distortion (\f$ 1 + k_1 r^2 + k_2 r^4 + k_3 r^6 \f$ monotonically increasing). -Radial distortion is always monotonic for real lenses, -and if the estimator produces a non-monotonic result, -this should be considered a calibration failure. -More generally, radial distortion must be monotonic and the distortion function must be bijective. -A failed estimation result may look deceptively good near the image center -but will work poorly in e.g. AR/SFM applications. -The optimization method used in OpenCV camera calibration does not include these constraints as -the framework does not support the required integer programming and polynomial inequalities. -See [issue #15992](https://github.com/opencv/opencv/issues/15992) for additional information. - -![](pics/distortion_examples.png) -![](pics/distortion_examples2.png) - -In some cases, the image sensor may be tilted in order to focus an oblique plane in front of the -camera (Scheimpflug principle). This can be useful for particle image velocimetry (PIV) or -triangulation with a laser fan. The tilt causes a perspective distortion of \f$x''\f$ and -\f$y''\f$. This distortion can be modeled in the following way, see e.g. @cite Louhichi07. - -\f[\begin{bmatrix} -u \\ -v -\end{bmatrix} = \begin{bmatrix} -f_x x''' + c_x \\ -f_y y''' + c_y -\end{bmatrix},\f] - -where - -\f[s\vecthree{x'''}{y'''}{1} = -\vecthreethree{R_{33}(\tau_x, \tau_y)}{0}{-R_{13}(\tau_x, \tau_y)} -{0}{R_{33}(\tau_x, \tau_y)}{-R_{23}(\tau_x, \tau_y)} -{0}{0}{1} R(\tau_x, \tau_y) \vecthree{x''}{y''}{1}\f] - -and the matrix \f$R(\tau_x, \tau_y)\f$ is defined by two rotations with angular parameter -\f$\tau_x\f$ and \f$\tau_y\f$, respectively, - -\f[ -R(\tau_x, \tau_y) = -\vecthreethree{\cos(\tau_y)}{0}{-\sin(\tau_y)}{0}{1}{0}{\sin(\tau_y)}{0}{\cos(\tau_y)} -\vecthreethree{1}{0}{0}{0}{\cos(\tau_x)}{\sin(\tau_x)}{0}{-\sin(\tau_x)}{\cos(\tau_x)} = -\vecthreethree{\cos(\tau_y)}{\sin(\tau_y)\sin(\tau_x)}{-\sin(\tau_y)\cos(\tau_x)} -{0}{\cos(\tau_x)}{\sin(\tau_x)} -{\sin(\tau_y)}{-\cos(\tau_y)\sin(\tau_x)}{\cos(\tau_y)\cos(\tau_x)}. -\f] - -In the functions below the coefficients are passed or returned as - -\f[(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f] - -vector. That is, if the vector contains four elements, it means that \f$k_3=0\f$ . The distortion -coefficients do not depend on the scene viewed. Thus, they also belong to the intrinsic camera -parameters. And they remain the same regardless of the captured image resolution. If, for example, a -camera has been calibrated on images of 320 x 240 resolution, absolutely the same distortion -coefficients can be used for 640 x 480 images from the same camera while \f$f_x\f$, \f$f_y\f$, -\f$c_x\f$, and \f$c_y\f$ need to be scaled appropriately. - -The functions below use the above model to do the following: - -- Project 3D points to the image plane given intrinsic and extrinsic parameters. -- Compute extrinsic parameters given intrinsic parameters, a few 3D points, and their -projections. -- Estimate intrinsic and extrinsic camera parameters from several views of a known calibration -pattern (every view is described by several 3D-2D point correspondences). -- Estimate the relative position and orientation of the stereo camera "heads" and compute the -*rectification* transformation that makes the camera optical axes parallel. - - Homogeneous Coordinates
-Homogeneous Coordinates are a system of coordinates that are used in projective geometry. Their use -allows to represent points at infinity by finite coordinates and simplifies formulas when compared -to the cartesian counterparts, e.g. they have the advantage that affine transformations can be -expressed as linear homogeneous transformation. - -One obtains the homogeneous vector \f$P_h\f$ by appending a 1 along an n-dimensional cartesian -vector \f$P\f$ e.g. for a 3D cartesian vector the mapping \f$P \rightarrow P_h\f$ is: - -\f[\begin{bmatrix} -X \\ -Y \\ -Z -\end{bmatrix} \rightarrow \begin{bmatrix} -X \\ -Y \\ -Z \\ -1 -\end{bmatrix}.\f] - -For the inverse mapping \f$P_h \rightarrow P\f$, one divides all elements of the homogeneous vector -by its last element, e.g. for a 3D homogeneous vector one gets its 2D cartesian counterpart by: - -\f[\begin{bmatrix} -X \\ -Y \\ -W -\end{bmatrix} \rightarrow \begin{bmatrix} -X / W \\ -Y / W -\end{bmatrix},\f] - -if \f$W \ne 0\f$. - -Due to this mapping, all multiples \f$k P_h\f$, for \f$k \ne 0\f$, of a homogeneous point represent -the same point \f$P_h\f$. An intuitive understanding of this property is that under a projective -transformation, all multiples of \f$P_h\f$ are mapped to the same point. This is the physical -observation one does for pinhole cameras, as all points along a ray through the camera's pinhole are -projected to the same image point, e.g. all points along the red ray in the image of the pinhole -camera model above would be mapped to the same image coordinate. This property is also the source -for the scale ambiguity s in the equation of the pinhole camera model. - -As mentioned, by using homogeneous coordinates we can express any change of basis parameterized by -\f$R\f$ and \f$t\f$ as a linear transformation, e.g. for the change of basis from coordinate system -0 to coordinate system 1 becomes: - -\f[P_1 = R P_0 + t \rightarrow P_{h_1} = \begin{bmatrix} -R & t \\ -0 & 1 -\end{bmatrix} P_{h_0}.\f] - -@note - - Many functions in this module take a camera intrinsic matrix as an input parameter. Although all - functions assume the same structure of this parameter, they may name it differently. The - parameter's description, however, will be clear in that a camera intrinsic matrix with the structure - shown above is required. - - A calibration sample for 3 cameras in a horizontal position can be found at - opencv_source_code/samples/cpp/3calibration.cpp - - A calibration sample based on a sequence of images can be found at - opencv_source_code/samples/cpp/calibration.cpp - - A calibration sample in order to do 3D reconstruction can be found at - opencv_source_code/samples/cpp/build3dmodel.cpp - - A calibration example on stereo calibration can be found at - opencv_source_code/samples/cpp/stereo_calib.cpp - - A calibration example on stereo matching can be found at - opencv_source_code/samples/cpp/stereo_match.cpp - - (Python) A camera calibration sample can be found at - opencv_source_code/samples/python/calibrate.py - - @{ - @defgroup calib3d_fisheye Fisheye camera model - - Definitions: Let P be a point in 3D of coordinates X in the world reference frame (stored in the - matrix X) The coordinate vector of P in the camera reference frame is: - - \f[Xc = R X + T\f] - - where R is the rotation matrix corresponding to the rotation vector om: R = rodrigues(om); call x, y - and z the 3 coordinates of Xc: - - \f[\begin{array}{l} x = Xc_1 \\ y = Xc_2 \\ z = Xc_3 \end{array} \f] - - The pinhole projection coordinates of P is [a; b] where - - \f[\begin{array}{l} a = x / z \ and \ b = y / z \\ r^2 = a^2 + b^2 \\ \theta = atan(r) \end{array} \f] - - Fisheye distortion: - - \f[\theta_d = \theta (1 + k_1 \theta^2 + k_2 \theta^4 + k_3 \theta^6 + k_4 \theta^8)\f] - - The distorted point coordinates are [x'; y'] where - - \f[\begin{array}{l} x' = (\theta_d / r) a \\ y' = (\theta_d / r) b \end{array} \f] - - Finally, conversion into pixel coordinates: The final pixel coordinates vector [u; v] where: - - \f[\begin{array}{l} u = f_x (x' + \alpha y') + c_x \\ - v = f_y y' + c_y \end{array} \f] - - Summary: - Generic camera model @cite Kannala2006 with perspective projection and without distortion correction - - @} - */ - -namespace cv -{ - -//! @addtogroup calib3d -//! @{ - -//! type of the robust estimation algorithm -enum { LMEDS = 4, //!< least-median of squares algorithm - RANSAC = 8, //!< RANSAC algorithm - RHO = 16, //!< RHO algorithm - USAC_DEFAULT = 32, //!< USAC algorithm, default settings - USAC_PARALLEL = 33, //!< USAC, parallel version - USAC_FM_8PTS = 34, //!< USAC, fundamental matrix 8 points - USAC_FAST = 35, //!< USAC, fast settings - USAC_ACCURATE = 36, //!< USAC, accurate settings - USAC_PROSAC = 37, //!< USAC, sorted points, runs PROSAC - USAC_MAGSAC = 38 //!< USAC, runs MAGSAC++ - }; - -enum SolvePnPMethod { - SOLVEPNP_ITERATIVE = 0, //!< Pose refinement using non-linear Levenberg-Marquardt minimization scheme @cite Madsen04 @cite Eade13 \n - //!< Initial solution for non-planar "objectPoints" needs at least 6 points and uses the DLT algorithm. \n - //!< Initial solution for planar "objectPoints" needs at least 4 points and uses pose from homography decomposition. - SOLVEPNP_EPNP = 1, //!< EPnP: Efficient Perspective-n-Point Camera Pose Estimation @cite lepetit2009epnp - SOLVEPNP_P3P = 2, //!< Complete Solution Classification for the Perspective-Three-Point Problem @cite gao2003complete - SOLVEPNP_DLS = 3, //!< **Broken implementation. Using this flag will fallback to EPnP.** \n - //!< A Direct Least-Squares (DLS) Method for PnP @cite hesch2011direct - SOLVEPNP_UPNP = 4, //!< **Broken implementation. Using this flag will fallback to EPnP.** \n - //!< Exhaustive Linearization for Robust Camera Pose and Focal Length Estimation @cite penate2013exhaustive - SOLVEPNP_AP3P = 5, //!< An Efficient Algebraic Solution to the Perspective-Three-Point Problem @cite Ke17 - SOLVEPNP_IPPE = 6, //!< Infinitesimal Plane-Based Pose Estimation @cite Collins14 \n - //!< Object points must be coplanar. - SOLVEPNP_IPPE_SQUARE = 7, //!< Infinitesimal Plane-Based Pose Estimation @cite Collins14 \n - //!< This is a special case suitable for marker pose estimation.\n - //!< 4 coplanar object points must be defined in the following order: - //!< - point 0: [-squareLength / 2, squareLength / 2, 0] - //!< - point 1: [ squareLength / 2, squareLength / 2, 0] - //!< - point 2: [ squareLength / 2, -squareLength / 2, 0] - //!< - point 3: [-squareLength / 2, -squareLength / 2, 0] - SOLVEPNP_SQPNP = 8, //!< SQPnP: A Consistently Fast and Globally OptimalSolution to the Perspective-n-Point Problem @cite Terzakis2020SQPnP -#ifndef CV_DOXYGEN - SOLVEPNP_MAX_COUNT //!< Used for count -#endif -}; - -enum { CALIB_CB_ADAPTIVE_THRESH = 1, - CALIB_CB_NORMALIZE_IMAGE = 2, - CALIB_CB_FILTER_QUADS = 4, - CALIB_CB_FAST_CHECK = 8, - CALIB_CB_EXHAUSTIVE = 16, - CALIB_CB_ACCURACY = 32, - CALIB_CB_LARGER = 64, - CALIB_CB_MARKER = 128, - CALIB_CB_PLAIN = 256 - }; - -enum { CALIB_CB_SYMMETRIC_GRID = 1, - CALIB_CB_ASYMMETRIC_GRID = 2, - CALIB_CB_CLUSTERING = 4 - }; - -enum { CALIB_NINTRINSIC = 18, - CALIB_USE_INTRINSIC_GUESS = 0x00001, - CALIB_FIX_ASPECT_RATIO = 0x00002, - CALIB_FIX_PRINCIPAL_POINT = 0x00004, - CALIB_ZERO_TANGENT_DIST = 0x00008, - CALIB_FIX_FOCAL_LENGTH = 0x00010, - CALIB_FIX_K1 = 0x00020, - CALIB_FIX_K2 = 0x00040, - CALIB_FIX_K3 = 0x00080, - CALIB_FIX_K4 = 0x00800, - CALIB_FIX_K5 = 0x01000, - CALIB_FIX_K6 = 0x02000, - CALIB_RATIONAL_MODEL = 0x04000, - CALIB_THIN_PRISM_MODEL = 0x08000, - CALIB_FIX_S1_S2_S3_S4 = 0x10000, - CALIB_TILTED_MODEL = 0x40000, - CALIB_FIX_TAUX_TAUY = 0x80000, - CALIB_USE_QR = 0x100000, //!< use QR instead of SVD decomposition for solving. Faster but potentially less precise - CALIB_FIX_TANGENT_DIST = 0x200000, - // only for stereo - CALIB_FIX_INTRINSIC = 0x00100, - CALIB_SAME_FOCAL_LENGTH = 0x00200, - // for stereo rectification - CALIB_ZERO_DISPARITY = 0x00400, - CALIB_USE_LU = (1 << 17), //!< use LU instead of SVD decomposition for solving. much faster but potentially less precise - CALIB_USE_EXTRINSIC_GUESS = (1 << 22) //!< for stereoCalibrate - }; - -//! the algorithm for finding fundamental matrix -enum { FM_7POINT = 1, //!< 7-point algorithm - FM_8POINT = 2, //!< 8-point algorithm - FM_LMEDS = 4, //!< least-median algorithm. 7-point algorithm is used. - FM_RANSAC = 8 //!< RANSAC algorithm. It needs at least 15 points. 7-point algorithm is used. - }; - -enum HandEyeCalibrationMethod -{ - CALIB_HAND_EYE_TSAI = 0, //!< A New Technique for Fully Autonomous and Efficient 3D Robotics Hand/Eye Calibration @cite Tsai89 - CALIB_HAND_EYE_PARK = 1, //!< Robot Sensor Calibration: Solving AX = XB on the Euclidean Group @cite Park94 - CALIB_HAND_EYE_HORAUD = 2, //!< Hand-eye Calibration @cite Horaud95 - CALIB_HAND_EYE_ANDREFF = 3, //!< On-line Hand-Eye Calibration @cite Andreff99 - CALIB_HAND_EYE_DANIILIDIS = 4 //!< Hand-Eye Calibration Using Dual Quaternions @cite Daniilidis98 -}; - -enum RobotWorldHandEyeCalibrationMethod -{ - CALIB_ROBOT_WORLD_HAND_EYE_SHAH = 0, //!< Solving the robot-world/hand-eye calibration problem using the kronecker product @cite Shah2013SolvingTR - CALIB_ROBOT_WORLD_HAND_EYE_LI = 1 //!< Simultaneous robot-world and hand-eye calibration using dual-quaternions and kronecker product @cite Li2010SimultaneousRA -}; - -enum SamplingMethod { SAMPLING_UNIFORM=0, SAMPLING_PROGRESSIVE_NAPSAC=1, SAMPLING_NAPSAC=2, - SAMPLING_PROSAC=3 }; -enum LocalOptimMethod {LOCAL_OPTIM_NULL=0, LOCAL_OPTIM_INNER_LO=1, LOCAL_OPTIM_INNER_AND_ITER_LO=2, - LOCAL_OPTIM_GC=3, LOCAL_OPTIM_SIGMA=4}; -enum ScoreMethod {SCORE_METHOD_RANSAC=0, SCORE_METHOD_MSAC=1, SCORE_METHOD_MAGSAC=2, SCORE_METHOD_LMEDS=3}; -enum NeighborSearchMethod { NEIGH_FLANN_KNN=0, NEIGH_GRID=1, NEIGH_FLANN_RADIUS=2 }; -enum PolishingMethod { NONE_POLISHER=0, LSQ_POLISHER=1, MAGSAC=2, COV_POLISHER=3 }; - -struct CV_EXPORTS_W_SIMPLE UsacParams -{ // in alphabetical order - CV_WRAP UsacParams(); - CV_PROP_RW double confidence; - CV_PROP_RW bool isParallel; - CV_PROP_RW int loIterations; - CV_PROP_RW LocalOptimMethod loMethod; - CV_PROP_RW int loSampleSize; - CV_PROP_RW int maxIterations; - CV_PROP_RW NeighborSearchMethod neighborsSearch; - CV_PROP_RW int randomGeneratorState; - CV_PROP_RW SamplingMethod sampler; - CV_PROP_RW ScoreMethod score; - CV_PROP_RW double threshold; - CV_PROP_RW PolishingMethod final_polisher; - CV_PROP_RW int final_polisher_iterations; -}; - -/** @brief Converts a rotation matrix to a rotation vector or vice versa. - -@param src Input rotation vector (3x1 or 1x3) or rotation matrix (3x3). -@param dst Output rotation matrix (3x3) or rotation vector (3x1 or 1x3), respectively. -@param jacobian Optional output Jacobian matrix, 3x9 or 9x3, which is a matrix of partial -derivatives of the output array components with respect to the input array components. - -\f[\begin{array}{l} \theta \leftarrow norm(r) \\ r \leftarrow r/ \theta \\ R = \cos(\theta) I + (1- \cos{\theta} ) r r^T + \sin(\theta) \vecthreethree{0}{-r_z}{r_y}{r_z}{0}{-r_x}{-r_y}{r_x}{0} \end{array}\f] - -Inverse transformation can be also done easily, since - -\f[\sin ( \theta ) \vecthreethree{0}{-r_z}{r_y}{r_z}{0}{-r_x}{-r_y}{r_x}{0} = \frac{R - R^T}{2}\f] - -A rotation vector is a convenient and most compact representation of a rotation matrix (since any -rotation matrix has just 3 degrees of freedom). The representation is used in the global 3D geometry -optimization procedures like @ref calibrateCamera, @ref stereoCalibrate, or @ref solvePnP . - -@note More information about the computation of the derivative of a 3D rotation matrix with respect to its exponential coordinate -can be found in: - - A Compact Formula for the Derivative of a 3-D Rotation in Exponential Coordinates, Guillermo Gallego, Anthony J. Yezzi @cite Gallego2014ACF - -@note Useful information on SE(3) and Lie Groups can be found in: - - A tutorial on SE(3) transformation parameterizations and on-manifold optimization, Jose-Luis Blanco @cite blanco2010tutorial - - Lie Groups for 2D and 3D Transformation, Ethan Eade @cite Eade17 - - A micro Lie theory for state estimation in robotics, Joan Solà, Jérémie Deray, Dinesh Atchuthan @cite Sol2018AML - */ -CV_EXPORTS_W void Rodrigues( InputArray src, OutputArray dst, OutputArray jacobian = noArray() ); - - - -/** Levenberg-Marquardt solver. Starting with the specified vector of parameters it - optimizes the target vector criteria "err" - (finds local minima of each target vector component absolute value). - - When needed, it calls user-provided callback. -*/ -class CV_EXPORTS LMSolver : public Algorithm -{ -public: - class CV_EXPORTS Callback - { - public: - virtual ~Callback() {} - /** - computes error and Jacobian for the specified vector of parameters - - @param param the current vector of parameters - @param err output vector of errors: err_i = actual_f_i - ideal_f_i - @param J output Jacobian: J_ij = d(ideal_f_i)/d(param_j) - - when J=noArray(), it means that it does not need to be computed. - Dimensionality of error vector and param vector can be different. - The callback should explicitly allocate (with "create" method) each output array - (unless it's noArray()). - */ - virtual bool compute(InputArray param, OutputArray err, OutputArray J) const = 0; - }; - - /** - Runs Levenberg-Marquardt algorithm using the passed vector of parameters as the start point. - The final vector of parameters (whether the algorithm converged or not) is stored at the same - vector. The method returns the number of iterations used. If it's equal to the previously specified - maxIters, there is a big chance the algorithm did not converge. - - @param param initial/final vector of parameters. - - Note that the dimensionality of parameter space is defined by the size of param vector, - and the dimensionality of optimized criteria is defined by the size of err vector - computed by the callback. - */ - virtual int run(InputOutputArray param) const = 0; - - /** - Sets the maximum number of iterations - @param maxIters the number of iterations - */ - virtual void setMaxIters(int maxIters) = 0; - /** - Retrieves the current maximum number of iterations - */ - virtual int getMaxIters() const = 0; - - /** - Creates Levenberg-Marquard solver - - @param cb callback - @param maxIters maximum number of iterations that can be further - modified using setMaxIters() method. - */ - static Ptr create(const Ptr& cb, int maxIters); - static Ptr create(const Ptr& cb, int maxIters, double eps); -}; - - - -/** @example samples/cpp/tutorial_code/features2D/Homography/pose_from_homography.cpp -An example program about pose estimation from coplanar points - -Check @ref tutorial_homography "the corresponding tutorial" for more details -*/ - -/** @brief Finds a perspective transformation between two planes. - -@param srcPoints Coordinates of the points in the original plane, a matrix of the type CV_32FC2 -or vector\ . -@param dstPoints Coordinates of the points in the target plane, a matrix of the type CV_32FC2 or -a vector\ . -@param method Method used to compute a homography matrix. The following methods are possible: -- **0** - a regular method using all the points, i.e., the least squares method -- @ref RANSAC - RANSAC-based robust method -- @ref LMEDS - Least-Median robust method -- @ref RHO - PROSAC-based robust method -@param ransacReprojThreshold Maximum allowed reprojection error to treat a point pair as an inlier -(used in the RANSAC and RHO methods only). That is, if -\f[\| \texttt{dstPoints} _i - \texttt{convertPointsHomogeneous} ( \texttt{H} \cdot \texttt{srcPoints} _i) \|_2 > \texttt{ransacReprojThreshold}\f] -then the point \f$i\f$ is considered as an outlier. If srcPoints and dstPoints are measured in pixels, -it usually makes sense to set this parameter somewhere in the range of 1 to 10. -@param mask Optional output mask set by a robust method ( RANSAC or LMeDS ). Note that the input -mask values are ignored. -@param maxIters The maximum number of RANSAC iterations. -@param confidence Confidence level, between 0 and 1. - -The function finds and returns the perspective transformation \f$H\f$ between the source and the -destination planes: - -\f[s_i \vecthree{x'_i}{y'_i}{1} \sim H \vecthree{x_i}{y_i}{1}\f] - -so that the back-projection error - -\f[\sum _i \left ( x'_i- \frac{h_{11} x_i + h_{12} y_i + h_{13}}{h_{31} x_i + h_{32} y_i + h_{33}} \right )^2+ \left ( y'_i- \frac{h_{21} x_i + h_{22} y_i + h_{23}}{h_{31} x_i + h_{32} y_i + h_{33}} \right )^2\f] - -is minimized. If the parameter method is set to the default value 0, the function uses all the point -pairs to compute an initial homography estimate with a simple least-squares scheme. - -However, if not all of the point pairs ( \f$srcPoints_i\f$, \f$dstPoints_i\f$ ) fit the rigid perspective -transformation (that is, there are some outliers), this initial estimate will be poor. In this case, -you can use one of the three robust methods. The methods RANSAC, LMeDS and RHO try many different -random subsets of the corresponding point pairs (of four pairs each, collinear pairs are discarded), estimate the homography matrix -using this subset and a simple least-squares algorithm, and then compute the quality/goodness of the -computed homography (which is the number of inliers for RANSAC or the least median re-projection error for -LMeDS). The best subset is then used to produce the initial estimate of the homography matrix and -the mask of inliers/outliers. - -Regardless of the method, robust or not, the computed homography matrix is refined further (using -inliers only in case of a robust method) with the Levenberg-Marquardt method to reduce the -re-projection error even more. - -The methods RANSAC and RHO can handle practically any ratio of outliers but need a threshold to -distinguish inliers from outliers. The method LMeDS does not need any threshold but it works -correctly only when there are more than 50% of inliers. Finally, if there are no outliers and the -noise is rather small, use the default method (method=0). - -The function is used to find initial intrinsic and extrinsic matrices. Homography matrix is -determined up to a scale. If \f$h_{33}\f$ is non-zero, the matrix is normalized so that \f$h_{33}=1\f$. -@note Whenever an \f$H\f$ matrix cannot be estimated, an empty one will be returned. - -@sa -getAffineTransform, estimateAffine2D, estimateAffinePartial2D, getPerspectiveTransform, warpPerspective, -perspectiveTransform - */ -CV_EXPORTS_W Mat findHomography( InputArray srcPoints, InputArray dstPoints, - int method = 0, double ransacReprojThreshold = 3, - OutputArray mask=noArray(), const int maxIters = 2000, - const double confidence = 0.995); - -/** @overload */ -CV_EXPORTS Mat findHomography( InputArray srcPoints, InputArray dstPoints, - OutputArray mask, int method = 0, double ransacReprojThreshold = 3 ); - - -CV_EXPORTS_W Mat findHomography(InputArray srcPoints, InputArray dstPoints, OutputArray mask, - const UsacParams ¶ms); - -/** @brief Computes an RQ decomposition of 3x3 matrices. - -@param src 3x3 input matrix. -@param mtxR Output 3x3 upper-triangular matrix. -@param mtxQ Output 3x3 orthogonal matrix. -@param Qx Optional output 3x3 rotation matrix around x-axis. -@param Qy Optional output 3x3 rotation matrix around y-axis. -@param Qz Optional output 3x3 rotation matrix around z-axis. - -The function computes a RQ decomposition using the given rotations. This function is used in -#decomposeProjectionMatrix to decompose the left 3x3 submatrix of a projection matrix into a camera -and a rotation matrix. - -It optionally returns three rotation matrices, one for each axis, and the three Euler angles in -degrees (as the return value) that could be used in OpenGL. Note, there is always more than one -sequence of rotations about the three principal axes that results in the same orientation of an -object, e.g. see @cite Slabaugh . Returned three rotation matrices and corresponding three Euler angles -are only one of the possible solutions. - */ -CV_EXPORTS_W Vec3d RQDecomp3x3( InputArray src, OutputArray mtxR, OutputArray mtxQ, - OutputArray Qx = noArray(), - OutputArray Qy = noArray(), - OutputArray Qz = noArray()); - -/** @brief Decomposes a projection matrix into a rotation matrix and a camera intrinsic matrix. - -@param projMatrix 3x4 input projection matrix P. -@param cameraMatrix Output 3x3 camera intrinsic matrix \f$\cameramatrix{A}\f$. -@param rotMatrix Output 3x3 external rotation matrix R. -@param transVect Output 4x1 translation vector T. -@param rotMatrixX Optional 3x3 rotation matrix around x-axis. -@param rotMatrixY Optional 3x3 rotation matrix around y-axis. -@param rotMatrixZ Optional 3x3 rotation matrix around z-axis. -@param eulerAngles Optional three-element vector containing three Euler angles of rotation in -degrees. - -The function computes a decomposition of a projection matrix into a calibration and a rotation -matrix and the position of a camera. - -It optionally returns three rotation matrices, one for each axis, and three Euler angles that could -be used in OpenGL. Note, there is always more than one sequence of rotations about the three -principal axes that results in the same orientation of an object, e.g. see @cite Slabaugh . Returned -three rotation matrices and corresponding three Euler angles are only one of the possible solutions. - -The function is based on #RQDecomp3x3 . - */ -CV_EXPORTS_W void decomposeProjectionMatrix( InputArray projMatrix, OutputArray cameraMatrix, - OutputArray rotMatrix, OutputArray transVect, - OutputArray rotMatrixX = noArray(), - OutputArray rotMatrixY = noArray(), - OutputArray rotMatrixZ = noArray(), - OutputArray eulerAngles =noArray() ); - -/** @brief Computes partial derivatives of the matrix product for each multiplied matrix. - -@param A First multiplied matrix. -@param B Second multiplied matrix. -@param dABdA First output derivative matrix d(A\*B)/dA of size -\f$\texttt{A.rows*B.cols} \times {A.rows*A.cols}\f$ . -@param dABdB Second output derivative matrix d(A\*B)/dB of size -\f$\texttt{A.rows*B.cols} \times {B.rows*B.cols}\f$ . - -The function computes partial derivatives of the elements of the matrix product \f$A*B\f$ with regard to -the elements of each of the two input matrices. The function is used to compute the Jacobian -matrices in #stereoCalibrate but can also be used in any other similar optimization function. - */ -CV_EXPORTS_W void matMulDeriv( InputArray A, InputArray B, OutputArray dABdA, OutputArray dABdB ); - -/** @brief Combines two rotation-and-shift transformations. - -@param rvec1 First rotation vector. -@param tvec1 First translation vector. -@param rvec2 Second rotation vector. -@param tvec2 Second translation vector. -@param rvec3 Output rotation vector of the superposition. -@param tvec3 Output translation vector of the superposition. -@param dr3dr1 Optional output derivative of rvec3 with regard to rvec1 -@param dr3dt1 Optional output derivative of rvec3 with regard to tvec1 -@param dr3dr2 Optional output derivative of rvec3 with regard to rvec2 -@param dr3dt2 Optional output derivative of rvec3 with regard to tvec2 -@param dt3dr1 Optional output derivative of tvec3 with regard to rvec1 -@param dt3dt1 Optional output derivative of tvec3 with regard to tvec1 -@param dt3dr2 Optional output derivative of tvec3 with regard to rvec2 -@param dt3dt2 Optional output derivative of tvec3 with regard to tvec2 - -The functions compute: - -\f[\begin{array}{l} \texttt{rvec3} = \mathrm{rodrigues} ^{-1} \left ( \mathrm{rodrigues} ( \texttt{rvec2} ) \cdot \mathrm{rodrigues} ( \texttt{rvec1} ) \right ) \\ \texttt{tvec3} = \mathrm{rodrigues} ( \texttt{rvec2} ) \cdot \texttt{tvec1} + \texttt{tvec2} \end{array} ,\f] - -where \f$\mathrm{rodrigues}\f$ denotes a rotation vector to a rotation matrix transformation, and -\f$\mathrm{rodrigues}^{-1}\f$ denotes the inverse transformation. See #Rodrigues for details. - -Also, the functions can compute the derivatives of the output vectors with regards to the input -vectors (see #matMulDeriv ). The functions are used inside #stereoCalibrate but can also be used in -your own code where Levenberg-Marquardt or another gradient-based solver is used to optimize a -function that contains a matrix multiplication. - */ -CV_EXPORTS_W void composeRT( InputArray rvec1, InputArray tvec1, - InputArray rvec2, InputArray tvec2, - OutputArray rvec3, OutputArray tvec3, - OutputArray dr3dr1 = noArray(), OutputArray dr3dt1 = noArray(), - OutputArray dr3dr2 = noArray(), OutputArray dr3dt2 = noArray(), - OutputArray dt3dr1 = noArray(), OutputArray dt3dt1 = noArray(), - OutputArray dt3dr2 = noArray(), OutputArray dt3dt2 = noArray() ); - -/** @brief Projects 3D points to an image plane. - -@param objectPoints Array of object points expressed wrt. the world coordinate frame. A 3xN/Nx3 -1-channel or 1xN/Nx1 3-channel (or vector\ ), where N is the number of points in the view. -@param rvec The rotation vector (@ref Rodrigues) that, together with tvec, performs a change of -basis from world to camera coordinate system, see @ref calibrateCamera for details. -@param tvec The translation vector, see parameter description above. -@param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ . -@param distCoeffs Input vector of distortion coefficients -\f$\distcoeffs\f$ . If the vector is empty, the zero distortion coefficients are assumed. -@param imagePoints Output array of image points, 1xN/Nx1 2-channel, or -vector\ . -@param jacobian Optional output 2Nx(10+\) jacobian matrix of derivatives of image -points with respect to components of the rotation vector, translation vector, focal lengths, -coordinates of the principal point and the distortion coefficients. In the old interface different -components of the jacobian are returned via different output parameters. -@param aspectRatio Optional "fixed aspect ratio" parameter. If the parameter is not 0, the -function assumes that the aspect ratio (\f$f_x / f_y\f$) is fixed and correspondingly adjusts the -jacobian matrix. - -The function computes the 2D projections of 3D points to the image plane, given intrinsic and -extrinsic camera parameters. Optionally, the function computes Jacobians -matrices of partial -derivatives of image points coordinates (as functions of all the input parameters) with respect to -the particular parameters, intrinsic and/or extrinsic. The Jacobians are used during the global -optimization in @ref calibrateCamera, @ref solvePnP, and @ref stereoCalibrate. The function itself -can also be used to compute a re-projection error, given the current intrinsic and extrinsic -parameters. - -@note By setting rvec = tvec = \f$[0, 0, 0]\f$, or by setting cameraMatrix to a 3x3 identity matrix, -or by passing zero distortion coefficients, one can get various useful partial cases of the -function. This means, one can compute the distorted coordinates for a sparse set of points or apply -a perspective transformation (and also compute the derivatives) in the ideal zero-distortion setup. - */ -CV_EXPORTS_W void projectPoints( InputArray objectPoints, - InputArray rvec, InputArray tvec, - InputArray cameraMatrix, InputArray distCoeffs, - OutputArray imagePoints, - OutputArray jacobian = noArray(), - double aspectRatio = 0 ); - -/** @example samples/cpp/tutorial_code/features2D/Homography/homography_from_camera_displacement.cpp -An example program about homography from the camera displacement - -Check @ref tutorial_homography "the corresponding tutorial" for more details -*/ - -/** @brief Finds an object pose from 3D-2D point correspondences. - -@see @ref calib3d_solvePnP - -This function returns the rotation and the translation vectors that transform a 3D point expressed in the object -coordinate frame to the camera coordinate frame, using different methods: -- P3P methods (@ref SOLVEPNP_P3P, @ref SOLVEPNP_AP3P): need 4 input points to return a unique solution. -- @ref SOLVEPNP_IPPE Input points must be >= 4 and object points must be coplanar. -- @ref SOLVEPNP_IPPE_SQUARE Special case suitable for marker pose estimation. -Number of input points must be 4. Object points must be defined in the following order: - - point 0: [-squareLength / 2, squareLength / 2, 0] - - point 1: [ squareLength / 2, squareLength / 2, 0] - - point 2: [ squareLength / 2, -squareLength / 2, 0] - - point 3: [-squareLength / 2, -squareLength / 2, 0] -- for all the other flags, number of input points must be >= 4 and object points can be in any configuration. - -@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or -1xN/Nx1 3-channel, where N is the number of points. vector\ can be also passed here. -@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel, -where N is the number of points. vector\ can be also passed here. -@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . -@param distCoeffs Input vector of distortion coefficients -\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are -assumed. -@param rvec Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from -the model coordinate system to the camera coordinate system. -@param tvec Output translation vector. -@param useExtrinsicGuess Parameter used for #SOLVEPNP_ITERATIVE. If true (1), the function uses -the provided rvec and tvec values as initial approximations of the rotation and translation -vectors, respectively, and further optimizes them. -@param flags Method for solving a PnP problem: see @ref calib3d_solvePnP_flags - -More information about Perspective-n-Points is described in @ref calib3d_solvePnP - -@note - - An example of how to use solvePnP for planar augmented reality can be found at - opencv_source_code/samples/python/plane_ar.py - - If you are using Python: - - Numpy array slices won't work as input because solvePnP requires contiguous - arrays (enforced by the assertion using cv::Mat::checkVector() around line 55 of - modules/calib3d/src/solvepnp.cpp version 2.4.9) - - The P3P algorithm requires image points to be in an array of shape (N,1,2) due - to its calling of #undistortPoints (around line 75 of modules/calib3d/src/solvepnp.cpp version 2.4.9) - which requires 2-channel information. - - Thus, given some data D = np.array(...) where D.shape = (N,M), in order to use a subset of - it as, e.g., imagePoints, one must effectively copy it into a new array: imagePoints = - np.ascontiguousarray(D[:,:2]).reshape((N,1,2)) - - The methods @ref SOLVEPNP_DLS and @ref SOLVEPNP_UPNP cannot be used as the current implementations are - unstable and sometimes give completely wrong results. If you pass one of these two - flags, @ref SOLVEPNP_EPNP method will be used instead. - - The minimum number of points is 4 in the general case. In the case of @ref SOLVEPNP_P3P and @ref SOLVEPNP_AP3P - methods, it is required to use exactly 4 points (the first 3 points are used to estimate all the solutions - of the P3P problem, the last one is used to retain the best solution that minimizes the reprojection error). - - With @ref SOLVEPNP_ITERATIVE method and `useExtrinsicGuess=true`, the minimum number of points is 3 (3 points - are sufficient to compute a pose but there are up to 4 solutions). The initial solution should be close to the - global solution to converge. - - With @ref SOLVEPNP_IPPE input points must be >= 4 and object points must be coplanar. - - With @ref SOLVEPNP_IPPE_SQUARE this is a special case suitable for marker pose estimation. - Number of input points must be 4. Object points must be defined in the following order: - - point 0: [-squareLength / 2, squareLength / 2, 0] - - point 1: [ squareLength / 2, squareLength / 2, 0] - - point 2: [ squareLength / 2, -squareLength / 2, 0] - - point 3: [-squareLength / 2, -squareLength / 2, 0] - - With @ref SOLVEPNP_SQPNP input points must be >= 3 - */ -CV_EXPORTS_W bool solvePnP( InputArray objectPoints, InputArray imagePoints, - InputArray cameraMatrix, InputArray distCoeffs, - OutputArray rvec, OutputArray tvec, - bool useExtrinsicGuess = false, int flags = SOLVEPNP_ITERATIVE ); - -/** @brief Finds an object pose from 3D-2D point correspondences using the RANSAC scheme. - -@see @ref calib3d_solvePnP - -@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or -1xN/Nx1 3-channel, where N is the number of points. vector\ can be also passed here. -@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel, -where N is the number of points. vector\ can be also passed here. -@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . -@param distCoeffs Input vector of distortion coefficients -\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are -assumed. -@param rvec Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from -the model coordinate system to the camera coordinate system. -@param tvec Output translation vector. -@param useExtrinsicGuess Parameter used for @ref SOLVEPNP_ITERATIVE. If true (1), the function uses -the provided rvec and tvec values as initial approximations of the rotation and translation -vectors, respectively, and further optimizes them. -@param iterationsCount Number of iterations. -@param reprojectionError Inlier threshold value used by the RANSAC procedure. The parameter value -is the maximum allowed distance between the observed and computed point projections to consider it -an inlier. -@param confidence The probability that the algorithm produces a useful result. -@param inliers Output vector that contains indices of inliers in objectPoints and imagePoints . -@param flags Method for solving a PnP problem (see @ref solvePnP ). - -The function estimates an object pose given a set of object points, their corresponding image -projections, as well as the camera intrinsic matrix and the distortion coefficients. This function finds such -a pose that minimizes reprojection error, that is, the sum of squared distances between the observed -projections imagePoints and the projected (using @ref projectPoints ) objectPoints. The use of RANSAC -makes the function resistant to outliers. - -@note - - An example of how to use solvePNPRansac for object detection can be found at - opencv_source_code/samples/cpp/tutorial_code/calib3d/real_time_pose_estimation/ - - The default method used to estimate the camera pose for the Minimal Sample Sets step - is #SOLVEPNP_EPNP. Exceptions are: - - if you choose #SOLVEPNP_P3P or #SOLVEPNP_AP3P, these methods will be used. - - if the number of input points is equal to 4, #SOLVEPNP_P3P is used. - - The method used to estimate the camera pose using all the inliers is defined by the - flags parameters unless it is equal to #SOLVEPNP_P3P or #SOLVEPNP_AP3P. In this case, - the method #SOLVEPNP_EPNP will be used instead. - */ -CV_EXPORTS_W bool solvePnPRansac( InputArray objectPoints, InputArray imagePoints, - InputArray cameraMatrix, InputArray distCoeffs, - OutputArray rvec, OutputArray tvec, - bool useExtrinsicGuess = false, int iterationsCount = 100, - float reprojectionError = 8.0, double confidence = 0.99, - OutputArray inliers = noArray(), int flags = SOLVEPNP_ITERATIVE ); - - -/* -Finds rotation and translation vector. -If cameraMatrix is given then run P3P. Otherwise run linear P6P and output cameraMatrix too. -*/ -CV_EXPORTS_W bool solvePnPRansac( InputArray objectPoints, InputArray imagePoints, - InputOutputArray cameraMatrix, InputArray distCoeffs, - OutputArray rvec, OutputArray tvec, OutputArray inliers, - const UsacParams ¶ms=UsacParams()); - -/** @brief Finds an object pose from 3 3D-2D point correspondences. - -@see @ref calib3d_solvePnP - -@param objectPoints Array of object points in the object coordinate space, 3x3 1-channel or -1x3/3x1 3-channel. vector\ can be also passed here. -@param imagePoints Array of corresponding image points, 3x2 1-channel or 1x3/3x1 2-channel. - vector\ can be also passed here. -@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . -@param distCoeffs Input vector of distortion coefficients -\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are -assumed. -@param rvecs Output rotation vectors (see @ref Rodrigues ) that, together with tvecs, brings points from -the model coordinate system to the camera coordinate system. A P3P problem has up to 4 solutions. -@param tvecs Output translation vectors. -@param flags Method for solving a P3P problem: -- @ref SOLVEPNP_P3P Method is based on the paper of X.S. Gao, X.-R. Hou, J. Tang, H.-F. Chang -"Complete Solution Classification for the Perspective-Three-Point Problem" (@cite gao2003complete). -- @ref SOLVEPNP_AP3P Method is based on the paper of T. Ke and S. Roumeliotis. -"An Efficient Algebraic Solution to the Perspective-Three-Point Problem" (@cite Ke17). - -The function estimates the object pose given 3 object points, their corresponding image -projections, as well as the camera intrinsic matrix and the distortion coefficients. - -@note -The solutions are sorted by reprojection errors (lowest to highest). - */ -CV_EXPORTS_W int solveP3P( InputArray objectPoints, InputArray imagePoints, - InputArray cameraMatrix, InputArray distCoeffs, - OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, - int flags ); - -/** @brief Refine a pose (the translation and the rotation that transform a 3D point expressed in the object coordinate frame -to the camera coordinate frame) from a 3D-2D point correspondences and starting from an initial solution. - -@see @ref calib3d_solvePnP - -@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or 1xN/Nx1 3-channel, -where N is the number of points. vector\ can also be passed here. -@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel, -where N is the number of points. vector\ can also be passed here. -@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . -@param distCoeffs Input vector of distortion coefficients -\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are -assumed. -@param rvec Input/Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from -the model coordinate system to the camera coordinate system. Input values are used as an initial solution. -@param tvec Input/Output translation vector. Input values are used as an initial solution. -@param criteria Criteria when to stop the Levenberg-Marquard iterative algorithm. - -The function refines the object pose given at least 3 object points, their corresponding image -projections, an initial solution for the rotation and translation vector, -as well as the camera intrinsic matrix and the distortion coefficients. -The function minimizes the projection error with respect to the rotation and the translation vectors, according -to a Levenberg-Marquardt iterative minimization @cite Madsen04 @cite Eade13 process. - */ -CV_EXPORTS_W void solvePnPRefineLM( InputArray objectPoints, InputArray imagePoints, - InputArray cameraMatrix, InputArray distCoeffs, - InputOutputArray rvec, InputOutputArray tvec, - TermCriteria criteria = TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 20, FLT_EPSILON)); - -/** @brief Refine a pose (the translation and the rotation that transform a 3D point expressed in the object coordinate frame -to the camera coordinate frame) from a 3D-2D point correspondences and starting from an initial solution. - -@see @ref calib3d_solvePnP - -@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or 1xN/Nx1 3-channel, -where N is the number of points. vector\ can also be passed here. -@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel, -where N is the number of points. vector\ can also be passed here. -@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . -@param distCoeffs Input vector of distortion coefficients -\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are -assumed. -@param rvec Input/Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from -the model coordinate system to the camera coordinate system. Input values are used as an initial solution. -@param tvec Input/Output translation vector. Input values are used as an initial solution. -@param criteria Criteria when to stop the Levenberg-Marquard iterative algorithm. -@param VVSlambda Gain for the virtual visual servoing control law, equivalent to the \f$\alpha\f$ -gain in the Damped Gauss-Newton formulation. - -The function refines the object pose given at least 3 object points, their corresponding image -projections, an initial solution for the rotation and translation vector, -as well as the camera intrinsic matrix and the distortion coefficients. -The function minimizes the projection error with respect to the rotation and the translation vectors, using a -virtual visual servoing (VVS) @cite Chaumette06 @cite Marchand16 scheme. - */ -CV_EXPORTS_W void solvePnPRefineVVS( InputArray objectPoints, InputArray imagePoints, - InputArray cameraMatrix, InputArray distCoeffs, - InputOutputArray rvec, InputOutputArray tvec, - TermCriteria criteria = TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 20, FLT_EPSILON), - double VVSlambda = 1); - -/** @brief Finds an object pose from 3D-2D point correspondences. - -@see @ref calib3d_solvePnP - -This function returns a list of all the possible solutions (a solution is a -couple), depending on the number of input points and the chosen method: -- P3P methods (@ref SOLVEPNP_P3P, @ref SOLVEPNP_AP3P): 3 or 4 input points. Number of returned solutions can be between 0 and 4 with 3 input points. -- @ref SOLVEPNP_IPPE Input points must be >= 4 and object points must be coplanar. Returns 2 solutions. -- @ref SOLVEPNP_IPPE_SQUARE Special case suitable for marker pose estimation. -Number of input points must be 4 and 2 solutions are returned. Object points must be defined in the following order: - - point 0: [-squareLength / 2, squareLength / 2, 0] - - point 1: [ squareLength / 2, squareLength / 2, 0] - - point 2: [ squareLength / 2, -squareLength / 2, 0] - - point 3: [-squareLength / 2, -squareLength / 2, 0] -- for all the other flags, number of input points must be >= 4 and object points can be in any configuration. -Only 1 solution is returned. - -@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or -1xN/Nx1 3-channel, where N is the number of points. vector\ can be also passed here. -@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel, -where N is the number of points. vector\ can be also passed here. -@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . -@param distCoeffs Input vector of distortion coefficients -\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are -assumed. -@param rvecs Vector of output rotation vectors (see @ref Rodrigues ) that, together with tvecs, brings points from -the model coordinate system to the camera coordinate system. -@param tvecs Vector of output translation vectors. -@param useExtrinsicGuess Parameter used for #SOLVEPNP_ITERATIVE. If true (1), the function uses -the provided rvec and tvec values as initial approximations of the rotation and translation -vectors, respectively, and further optimizes them. -@param flags Method for solving a PnP problem: see @ref calib3d_solvePnP_flags -@param rvec Rotation vector used to initialize an iterative PnP refinement algorithm, when flag is @ref SOLVEPNP_ITERATIVE -and useExtrinsicGuess is set to true. -@param tvec Translation vector used to initialize an iterative PnP refinement algorithm, when flag is @ref SOLVEPNP_ITERATIVE -and useExtrinsicGuess is set to true. -@param reprojectionError Optional vector of reprojection error, that is the RMS error -(\f$ \text{RMSE} = \sqrt{\frac{\sum_{i}^{N} \left ( \hat{y_i} - y_i \right )^2}{N}} \f$) between the input image points -and the 3D object points projected with the estimated pose. - -More information is described in @ref calib3d_solvePnP - -@note - - An example of how to use solvePnP for planar augmented reality can be found at - opencv_source_code/samples/python/plane_ar.py - - If you are using Python: - - Numpy array slices won't work as input because solvePnP requires contiguous - arrays (enforced by the assertion using cv::Mat::checkVector() around line 55 of - modules/calib3d/src/solvepnp.cpp version 2.4.9) - - The P3P algorithm requires image points to be in an array of shape (N,1,2) due - to its calling of #undistortPoints (around line 75 of modules/calib3d/src/solvepnp.cpp version 2.4.9) - which requires 2-channel information. - - Thus, given some data D = np.array(...) where D.shape = (N,M), in order to use a subset of - it as, e.g., imagePoints, one must effectively copy it into a new array: imagePoints = - np.ascontiguousarray(D[:,:2]).reshape((N,1,2)) - - The methods @ref SOLVEPNP_DLS and @ref SOLVEPNP_UPNP cannot be used as the current implementations are - unstable and sometimes give completely wrong results. If you pass one of these two - flags, @ref SOLVEPNP_EPNP method will be used instead. - - The minimum number of points is 4 in the general case. In the case of @ref SOLVEPNP_P3P and @ref SOLVEPNP_AP3P - methods, it is required to use exactly 4 points (the first 3 points are used to estimate all the solutions - of the P3P problem, the last one is used to retain the best solution that minimizes the reprojection error). - - With @ref SOLVEPNP_ITERATIVE method and `useExtrinsicGuess=true`, the minimum number of points is 3 (3 points - are sufficient to compute a pose but there are up to 4 solutions). The initial solution should be close to the - global solution to converge. - - With @ref SOLVEPNP_IPPE input points must be >= 4 and object points must be coplanar. - - With @ref SOLVEPNP_IPPE_SQUARE this is a special case suitable for marker pose estimation. - Number of input points must be 4. Object points must be defined in the following order: - - point 0: [-squareLength / 2, squareLength / 2, 0] - - point 1: [ squareLength / 2, squareLength / 2, 0] - - point 2: [ squareLength / 2, -squareLength / 2, 0] - - point 3: [-squareLength / 2, -squareLength / 2, 0] - */ -CV_EXPORTS_W int solvePnPGeneric( InputArray objectPoints, InputArray imagePoints, - InputArray cameraMatrix, InputArray distCoeffs, - OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, - bool useExtrinsicGuess = false, SolvePnPMethod flags = SOLVEPNP_ITERATIVE, - InputArray rvec = noArray(), InputArray tvec = noArray(), - OutputArray reprojectionError = noArray() ); - -/** @brief Finds an initial camera intrinsic matrix from 3D-2D point correspondences. - -@param objectPoints Vector of vectors of the calibration pattern points in the calibration pattern -coordinate space. In the old interface all the per-view vectors are concatenated. See -#calibrateCamera for details. -@param imagePoints Vector of vectors of the projections of the calibration pattern points. In the -old interface all the per-view vectors are concatenated. -@param imageSize Image size in pixels used to initialize the principal point. -@param aspectRatio If it is zero or negative, both \f$f_x\f$ and \f$f_y\f$ are estimated independently. -Otherwise, \f$f_x = f_y \cdot \texttt{aspectRatio}\f$ . - -The function estimates and returns an initial camera intrinsic matrix for the camera calibration process. -Currently, the function only supports planar calibration patterns, which are patterns where each -object point has z-coordinate =0. - */ -CV_EXPORTS_W Mat initCameraMatrix2D( InputArrayOfArrays objectPoints, - InputArrayOfArrays imagePoints, - Size imageSize, double aspectRatio = 1.0 ); - -/** @brief Finds the positions of internal corners of the chessboard. - -@param image Source chessboard view. It must be an 8-bit grayscale or color image. -@param patternSize Number of inner corners per a chessboard row and column -( patternSize = cv::Size(points_per_row,points_per_colum) = cv::Size(columns,rows) ). -@param corners Output array of detected corners. -@param flags Various operation flags that can be zero or a combination of the following values: -- @ref CALIB_CB_ADAPTIVE_THRESH Use adaptive thresholding to convert the image to black -and white, rather than a fixed threshold level (computed from the average image brightness). -- @ref CALIB_CB_NORMALIZE_IMAGE Normalize the image gamma with #equalizeHist before -applying fixed or adaptive thresholding. -- @ref CALIB_CB_FILTER_QUADS Use additional criteria (like contour area, perimeter, -square-like shape) to filter out false quads extracted at the contour retrieval stage. -- @ref CALIB_CB_FAST_CHECK Run a fast check on the image that looks for chessboard corners, -and shortcut the call if none is found. This can drastically speed up the call in the -degenerate condition when no chessboard is observed. -- @ref CALIB_CB_PLAIN All other flags are ignored. The input image is taken as is. -No image processing is done to improve to find the checkerboard. This has the effect of speeding up the -execution of the function but could lead to not recognizing the checkerboard if the image -is not previously binarized in the appropriate manner. - -The function attempts to determine whether the input image is a view of the chessboard pattern and -locate the internal chessboard corners. The function returns a non-zero value if all of the corners -are found and they are placed in a certain order (row by row, left to right in every row). -Otherwise, if the function fails to find all the corners or reorder them, it returns 0. For example, -a regular chessboard has 8 x 8 squares and 7 x 7 internal corners, that is, points where the black -squares touch each other. The detected coordinates are approximate, and to determine their positions -more accurately, the function calls #cornerSubPix. You also may use the function #cornerSubPix with -different parameters if returned coordinates are not accurate enough. - -Sample usage of detecting and drawing chessboard corners: : -@code - Size patternsize(8,6); //interior number of corners - Mat gray = ....; //source image - vector corners; //this will be filled by the detected corners - - //CALIB_CB_FAST_CHECK saves a lot of time on images - //that do not contain any chessboard corners - bool patternfound = findChessboardCorners(gray, patternsize, corners, - CALIB_CB_ADAPTIVE_THRESH + CALIB_CB_NORMALIZE_IMAGE - + CALIB_CB_FAST_CHECK); - - if(patternfound) - cornerSubPix(gray, corners, Size(11, 11), Size(-1, -1), - TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1)); - - drawChessboardCorners(img, patternsize, Mat(corners), patternfound); -@endcode -@note The function requires white space (like a square-thick border, the wider the better) around -the board to make the detection more robust in various environments. Otherwise, if there is no -border and the background is dark, the outer black squares cannot be segmented properly and so the -square grouping and ordering algorithm fails. - -Use gen_pattern.py (@ref tutorial_camera_calibration_pattern) to create checkerboard. - */ -CV_EXPORTS_W bool findChessboardCorners( InputArray image, Size patternSize, OutputArray corners, - int flags = CALIB_CB_ADAPTIVE_THRESH + CALIB_CB_NORMALIZE_IMAGE ); - -/* - Checks whether the image contains chessboard of the specific size or not. - If yes, nonzero value is returned. -*/ -CV_EXPORTS_W bool checkChessboard(InputArray img, Size size); - -/** @brief Finds the positions of internal corners of the chessboard using a sector based approach. - -@param image Source chessboard view. It must be an 8-bit grayscale or color image. -@param patternSize Number of inner corners per a chessboard row and column -( patternSize = cv::Size(points_per_row,points_per_colum) = cv::Size(columns,rows) ). -@param corners Output array of detected corners. -@param flags Various operation flags that can be zero or a combination of the following values: -- @ref CALIB_CB_NORMALIZE_IMAGE Normalize the image gamma with equalizeHist before detection. -- @ref CALIB_CB_EXHAUSTIVE Run an exhaustive search to improve detection rate. -- @ref CALIB_CB_ACCURACY Up sample input image to improve sub-pixel accuracy due to aliasing effects. -- @ref CALIB_CB_LARGER The detected pattern is allowed to be larger than patternSize (see description). -- @ref CALIB_CB_MARKER The detected pattern must have a marker (see description). -This should be used if an accurate camera calibration is required. -@param meta Optional output arrray of detected corners (CV_8UC1 and size = cv::Size(columns,rows)). -Each entry stands for one corner of the pattern and can have one of the following values: -- 0 = no meta data attached -- 1 = left-top corner of a black cell -- 2 = left-top corner of a white cell -- 3 = left-top corner of a black cell with a white marker dot -- 4 = left-top corner of a white cell with a black marker dot (pattern origin in case of markers otherwise first corner) - -The function is analog to #findChessboardCorners but uses a localized radon -transformation approximated by box filters being more robust to all sort of -noise, faster on larger images and is able to directly return the sub-pixel -position of the internal chessboard corners. The Method is based on the paper -@cite duda2018 "Accurate Detection and Localization of Checkerboard Corners for -Calibration" demonstrating that the returned sub-pixel positions are more -accurate than the one returned by cornerSubPix allowing a precise camera -calibration for demanding applications. - -In the case, the flags @ref CALIB_CB_LARGER or @ref CALIB_CB_MARKER are given, -the result can be recovered from the optional meta array. Both flags are -helpful to use calibration patterns exceeding the field of view of the camera. -These oversized patterns allow more accurate calibrations as corners can be -utilized, which are as close as possible to the image borders. For a -consistent coordinate system across all images, the optional marker (see image -below) can be used to move the origin of the board to the location where the -black circle is located. - -@note The function requires a white boarder with roughly the same width as one -of the checkerboard fields around the whole board to improve the detection in -various environments. In addition, because of the localized radon -transformation it is beneficial to use round corners for the field corners -which are located on the outside of the board. The following figure illustrates -a sample checkerboard optimized for the detection. However, any other checkerboard -can be used as well. - -Use gen_pattern.py (@ref tutorial_camera_calibration_pattern) to create checkerboard. -![Checkerboard](pics/checkerboard_radon.png) - */ -CV_EXPORTS_AS(findChessboardCornersSBWithMeta) -bool findChessboardCornersSB(InputArray image,Size patternSize, OutputArray corners, - int flags,OutputArray meta); -/** @overload */ -CV_EXPORTS_W inline -bool findChessboardCornersSB(InputArray image, Size patternSize, OutputArray corners, - int flags = 0) -{ - return findChessboardCornersSB(image, patternSize, corners, flags, noArray()); -} - -/** @brief Estimates the sharpness of a detected chessboard. - -Image sharpness, as well as brightness, are a critical parameter for accuracte -camera calibration. For accessing these parameters for filtering out -problematic calibraiton images, this method calculates edge profiles by traveling from -black to white chessboard cell centers. Based on this, the number of pixels is -calculated required to transit from black to white. This width of the -transition area is a good indication of how sharp the chessboard is imaged -and should be below ~3.0 pixels. - -@param image Gray image used to find chessboard corners -@param patternSize Size of a found chessboard pattern -@param corners Corners found by #findChessboardCornersSB -@param rise_distance Rise distance 0.8 means 10% ... 90% of the final signal strength -@param vertical By default edge responses for horizontal lines are calculated -@param sharpness Optional output array with a sharpness value for calculated edge responses (see description) - -The optional sharpness array is of type CV_32FC1 and has for each calculated -profile one row with the following five entries: -* 0 = x coordinate of the underlying edge in the image -* 1 = y coordinate of the underlying edge in the image -* 2 = width of the transition area (sharpness) -* 3 = signal strength in the black cell (min brightness) -* 4 = signal strength in the white cell (max brightness) - -@return Scalar(average sharpness, average min brightness, average max brightness,0) -*/ -CV_EXPORTS_W Scalar estimateChessboardSharpness(InputArray image, Size patternSize, InputArray corners, - float rise_distance=0.8F,bool vertical=false, - OutputArray sharpness=noArray()); - - -//! finds subpixel-accurate positions of the chessboard corners -CV_EXPORTS_W bool find4QuadCornerSubpix( InputArray img, InputOutputArray corners, Size region_size ); - -/** @brief Renders the detected chessboard corners. - -@param image Destination image. It must be an 8-bit color image. -@param patternSize Number of inner corners per a chessboard row and column -(patternSize = cv::Size(points_per_row,points_per_column)). -@param corners Array of detected corners, the output of #findChessboardCorners. -@param patternWasFound Parameter indicating whether the complete board was found or not. The -return value of #findChessboardCorners should be passed here. - -The function draws individual chessboard corners detected either as red circles if the board was not -found, or as colored corners connected with lines if the board was found. - */ -CV_EXPORTS_W void drawChessboardCorners( InputOutputArray image, Size patternSize, - InputArray corners, bool patternWasFound ); - -/** @brief Draw axes of the world/object coordinate system from pose estimation. @sa solvePnP - -@param image Input/output image. It must have 1 or 3 channels. The number of channels is not altered. -@param cameraMatrix Input 3x3 floating-point matrix of camera intrinsic parameters. -\f$\cameramatrix{A}\f$ -@param distCoeffs Input vector of distortion coefficients -\f$\distcoeffs\f$. If the vector is empty, the zero distortion coefficients are assumed. -@param rvec Rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from -the model coordinate system to the camera coordinate system. -@param tvec Translation vector. -@param length Length of the painted axes in the same unit than tvec (usually in meters). -@param thickness Line thickness of the painted axes. - -This function draws the axes of the world/object coordinate system w.r.t. to the camera frame. -OX is drawn in red, OY in green and OZ in blue. - */ -CV_EXPORTS_W void drawFrameAxes(InputOutputArray image, InputArray cameraMatrix, InputArray distCoeffs, - InputArray rvec, InputArray tvec, float length, int thickness=3); - -struct CV_EXPORTS_W_SIMPLE CirclesGridFinderParameters -{ - CV_WRAP CirclesGridFinderParameters(); - CV_PROP_RW cv::Size2f densityNeighborhoodSize; - CV_PROP_RW float minDensity; - CV_PROP_RW int kmeansAttempts; - CV_PROP_RW int minDistanceToAddKeypoint; - CV_PROP_RW int keypointScale; - CV_PROP_RW float minGraphConfidence; - CV_PROP_RW float vertexGain; - CV_PROP_RW float vertexPenalty; - CV_PROP_RW float existingVertexGain; - CV_PROP_RW float edgeGain; - CV_PROP_RW float edgePenalty; - CV_PROP_RW float convexHullFactor; - CV_PROP_RW float minRNGEdgeSwitchDist; - - enum GridType - { - SYMMETRIC_GRID, ASYMMETRIC_GRID - }; - GridType gridType; - - CV_PROP_RW float squareSize; //!< Distance between two adjacent points. Used by CALIB_CB_CLUSTERING. - CV_PROP_RW float maxRectifiedDistance; //!< Max deviation from prediction. Used by CALIB_CB_CLUSTERING. -}; - -#ifndef DISABLE_OPENCV_3_COMPATIBILITY -typedef CirclesGridFinderParameters CirclesGridFinderParameters2; -#endif - -/** @brief Finds centers in the grid of circles. - -@param image grid view of input circles; it must be an 8-bit grayscale or color image. -@param patternSize number of circles per row and column -( patternSize = Size(points_per_row, points_per_colum) ). -@param centers output array of detected centers. -@param flags various operation flags that can be one of the following values: -- @ref CALIB_CB_SYMMETRIC_GRID uses symmetric pattern of circles. -- @ref CALIB_CB_ASYMMETRIC_GRID uses asymmetric pattern of circles. -- @ref CALIB_CB_CLUSTERING uses a special algorithm for grid detection. It is more robust to -perspective distortions but much more sensitive to background clutter. -@param blobDetector feature detector that finds blobs like dark circles on light background. - If `blobDetector` is NULL then `image` represents Point2f array of candidates. -@param parameters struct for finding circles in a grid pattern. - -The function attempts to determine whether the input image contains a grid of circles. If it is, the -function locates centers of the circles. The function returns a non-zero value if all of the centers -have been found and they have been placed in a certain order (row by row, left to right in every -row). Otherwise, if the function fails to find all the corners or reorder them, it returns 0. - -Sample usage of detecting and drawing the centers of circles: : -@code - Size patternsize(7,7); //number of centers - Mat gray = ...; //source image - vector centers; //this will be filled by the detected centers - - bool patternfound = findCirclesGrid(gray, patternsize, centers); - - drawChessboardCorners(img, patternsize, Mat(centers), patternfound); -@endcode -@note The function requires white space (like a square-thick border, the wider the better) around -the board to make the detection more robust in various environments. - */ -CV_EXPORTS_W bool findCirclesGrid( InputArray image, Size patternSize, - OutputArray centers, int flags, - const Ptr &blobDetector, - const CirclesGridFinderParameters& parameters); - -/** @overload */ -CV_EXPORTS_W bool findCirclesGrid( InputArray image, Size patternSize, - OutputArray centers, int flags = CALIB_CB_SYMMETRIC_GRID, - const Ptr &blobDetector = SimpleBlobDetector::create()); - -/** @brief Finds the camera intrinsic and extrinsic parameters from several views of a calibration -pattern. - -@param objectPoints In the new interface it is a vector of vectors of calibration pattern points in -the calibration pattern coordinate space (e.g. std::vector>). The outer -vector contains as many elements as the number of pattern views. If the same calibration pattern -is shown in each view and it is fully visible, all the vectors will be the same. Although, it is -possible to use partially occluded patterns or even different patterns in different views. Then, -the vectors will be different. Although the points are 3D, they all lie in the calibration pattern's -XY coordinate plane (thus 0 in the Z-coordinate), if the used calibration pattern is a planar rig. -In the old interface all the vectors of object points from different views are concatenated -together. -@param imagePoints In the new interface it is a vector of vectors of the projections of calibration -pattern points (e.g. std::vector>). imagePoints.size() and -objectPoints.size(), and imagePoints[i].size() and objectPoints[i].size() for each i, must be equal, -respectively. In the old interface all the vectors of object points from different views are -concatenated together. -@param imageSize Size of the image used only to initialize the camera intrinsic matrix. -@param cameraMatrix Input/output 3x3 floating-point camera intrinsic matrix -\f$\cameramatrix{A}\f$ . If @ref CALIB_USE_INTRINSIC_GUESS -and/or @ref CALIB_FIX_ASPECT_RATIO, @ref CALIB_FIX_PRINCIPAL_POINT or @ref CALIB_FIX_FOCAL_LENGTH -are specified, some or all of fx, fy, cx, cy must be initialized before calling the function. -@param distCoeffs Input/output vector of distortion coefficients -\f$\distcoeffs\f$. -@param rvecs Output vector of rotation vectors (@ref Rodrigues ) estimated for each pattern view -(e.g. std::vector>). That is, each i-th rotation vector together with the corresponding -i-th translation vector (see the next output parameter description) brings the calibration pattern -from the object coordinate space (in which object points are specified) to the camera coordinate -space. In more technical terms, the tuple of the i-th rotation and translation vector performs -a change of basis from object coordinate space to camera coordinate space. Due to its duality, this -tuple is equivalent to the position of the calibration pattern with respect to the camera coordinate -space. -@param tvecs Output vector of translation vectors estimated for each pattern view, see parameter -describtion above. -@param stdDeviationsIntrinsics Output vector of standard deviations estimated for intrinsic -parameters. Order of deviations values: -\f$(f_x, f_y, c_x, c_y, k_1, k_2, p_1, p_2, k_3, k_4, k_5, k_6 , s_1, s_2, s_3, - s_4, \tau_x, \tau_y)\f$ If one of parameters is not estimated, it's deviation is equals to zero. -@param stdDeviationsExtrinsics Output vector of standard deviations estimated for extrinsic -parameters. Order of deviations values: \f$(R_0, T_0, \dotsc , R_{M - 1}, T_{M - 1})\f$ where M is -the number of pattern views. \f$R_i, T_i\f$ are concatenated 1x3 vectors. - @param perViewErrors Output vector of the RMS re-projection error estimated for each pattern view. -@param flags Different flags that may be zero or a combination of the following values: -- @ref CALIB_USE_INTRINSIC_GUESS cameraMatrix contains valid initial values of -fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image -center ( imageSize is used), and focal distances are computed in a least-squares fashion. -Note, that if intrinsic parameters are known, there is no need to use this function just to -estimate extrinsic parameters. Use @ref solvePnP instead. -- @ref CALIB_FIX_PRINCIPAL_POINT The principal point is not changed during the global -optimization. It stays at the center or at a different location specified when - @ref CALIB_USE_INTRINSIC_GUESS is set too. -- @ref CALIB_FIX_ASPECT_RATIO The functions consider only fy as a free parameter. The -ratio fx/fy stays the same as in the input cameraMatrix . When - @ref CALIB_USE_INTRINSIC_GUESS is not set, the actual input values of fx and fy are -ignored, only their ratio is computed and used further. -- @ref CALIB_ZERO_TANGENT_DIST Tangential distortion coefficients \f$(p_1, p_2)\f$ are set -to zeros and stay zero. -- @ref CALIB_FIX_FOCAL_LENGTH The focal length is not changed during the global optimization if - @ref CALIB_USE_INTRINSIC_GUESS is set. -- @ref CALIB_FIX_K1,..., @ref CALIB_FIX_K6 The corresponding radial distortion -coefficient is not changed during the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is -set, the coefficient from the supplied distCoeffs matrix is used. Otherwise, it is set to 0. -- @ref CALIB_RATIONAL_MODEL Coefficients k4, k5, and k6 are enabled. To provide the -backward compatibility, this extra flag should be explicitly specified to make the -calibration function use the rational model and return 8 coefficients or more. -- @ref CALIB_THIN_PRISM_MODEL Coefficients s1, s2, s3 and s4 are enabled. To provide the -backward compatibility, this extra flag should be explicitly specified to make the -calibration function use the thin prism model and return 12 coefficients or more. -- @ref CALIB_FIX_S1_S2_S3_S4 The thin prism distortion coefficients are not changed during -the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the -supplied distCoeffs matrix is used. Otherwise, it is set to 0. -- @ref CALIB_TILTED_MODEL Coefficients tauX and tauY are enabled. To provide the -backward compatibility, this extra flag should be explicitly specified to make the -calibration function use the tilted sensor model and return 14 coefficients. -- @ref CALIB_FIX_TAUX_TAUY The coefficients of the tilted sensor model are not changed during -the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the -supplied distCoeffs matrix is used. Otherwise, it is set to 0. -@param criteria Termination criteria for the iterative optimization algorithm. - -@return the overall RMS re-projection error. - -The function estimates the intrinsic camera parameters and extrinsic parameters for each of the -views. The algorithm is based on @cite Zhang2000 and @cite BouguetMCT . The coordinates of 3D object -points and their corresponding 2D projections in each view must be specified. That may be achieved -by using an object with known geometry and easily detectable feature points. Such an object is -called a calibration rig or calibration pattern, and OpenCV has built-in support for a chessboard as -a calibration rig (see @ref findChessboardCorners). Currently, initialization of intrinsic -parameters (when @ref CALIB_USE_INTRINSIC_GUESS is not set) is only implemented for planar calibration -patterns (where Z-coordinates of the object points must be all zeros). 3D calibration rigs can also -be used as long as initial cameraMatrix is provided. - -The algorithm performs the following steps: - -- Compute the initial intrinsic parameters (the option only available for planar calibration - patterns) or read them from the input parameters. The distortion coefficients are all set to - zeros initially unless some of CALIB_FIX_K? are specified. - -- Estimate the initial camera pose as if the intrinsic parameters have been already known. This is - done using @ref solvePnP . - -- Run the global Levenberg-Marquardt optimization algorithm to minimize the reprojection error, - that is, the total sum of squared distances between the observed feature points imagePoints and - the projected (using the current estimates for camera parameters and the poses) object points - objectPoints. See @ref projectPoints for details. - -@note - If you use a non-square (i.e. non-N-by-N) grid and @ref findChessboardCorners for calibration, - and @ref calibrateCamera returns bad values (zero distortion coefficients, \f$c_x\f$ and - \f$c_y\f$ very far from the image center, and/or large differences between \f$f_x\f$ and - \f$f_y\f$ (ratios of 10:1 or more)), then you are probably using patternSize=cvSize(rows,cols) - instead of using patternSize=cvSize(cols,rows) in @ref findChessboardCorners. - -@note - The function may throw exceptions, if unsupported combination of parameters is provided or - the system is underconstrained. - -@sa - calibrateCameraRO, findChessboardCorners, solvePnP, initCameraMatrix2D, stereoCalibrate, - undistort - */ -CV_EXPORTS_AS(calibrateCameraExtended) double calibrateCamera( InputArrayOfArrays objectPoints, - InputArrayOfArrays imagePoints, Size imageSize, - InputOutputArray cameraMatrix, InputOutputArray distCoeffs, - OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, - OutputArray stdDeviationsIntrinsics, - OutputArray stdDeviationsExtrinsics, - OutputArray perViewErrors, - int flags = 0, TermCriteria criteria = TermCriteria( - TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) ); - -/** @overload */ -CV_EXPORTS_W double calibrateCamera( InputArrayOfArrays objectPoints, - InputArrayOfArrays imagePoints, Size imageSize, - InputOutputArray cameraMatrix, InputOutputArray distCoeffs, - OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, - int flags = 0, TermCriteria criteria = TermCriteria( - TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) ); - -/** @brief Finds the camera intrinsic and extrinsic parameters from several views of a calibration pattern. - -This function is an extension of #calibrateCamera with the method of releasing object which was -proposed in @cite strobl2011iccv. In many common cases with inaccurate, unmeasured, roughly planar -targets (calibration plates), this method can dramatically improve the precision of the estimated -camera parameters. Both the object-releasing method and standard method are supported by this -function. Use the parameter **iFixedPoint** for method selection. In the internal implementation, -#calibrateCamera is a wrapper for this function. - -@param objectPoints Vector of vectors of calibration pattern points in the calibration pattern -coordinate space. See #calibrateCamera for details. If the method of releasing object to be used, -the identical calibration board must be used in each view and it must be fully visible, and all -objectPoints[i] must be the same and all points should be roughly close to a plane. **The calibration -target has to be rigid, or at least static if the camera (rather than the calibration target) is -shifted for grabbing images.** -@param imagePoints Vector of vectors of the projections of calibration pattern points. See -#calibrateCamera for details. -@param imageSize Size of the image used only to initialize the intrinsic camera matrix. -@param iFixedPoint The index of the 3D object point in objectPoints[0] to be fixed. It also acts as -a switch for calibration method selection. If object-releasing method to be used, pass in the -parameter in the range of [1, objectPoints[0].size()-2], otherwise a value out of this range will -make standard calibration method selected. Usually the top-right corner point of the calibration -board grid is recommended to be fixed when object-releasing method being utilized. According to -\cite strobl2011iccv, two other points are also fixed. In this implementation, objectPoints[0].front -and objectPoints[0].back.z are used. With object-releasing method, accurate rvecs, tvecs and -newObjPoints are only possible if coordinates of these three fixed points are accurate enough. -@param cameraMatrix Output 3x3 floating-point camera matrix. See #calibrateCamera for details. -@param distCoeffs Output vector of distortion coefficients. See #calibrateCamera for details. -@param rvecs Output vector of rotation vectors estimated for each pattern view. See #calibrateCamera -for details. -@param tvecs Output vector of translation vectors estimated for each pattern view. -@param newObjPoints The updated output vector of calibration pattern points. The coordinates might -be scaled based on three fixed points. The returned coordinates are accurate only if the above -mentioned three fixed points are accurate. If not needed, noArray() can be passed in. This parameter -is ignored with standard calibration method. -@param stdDeviationsIntrinsics Output vector of standard deviations estimated for intrinsic parameters. -See #calibrateCamera for details. -@param stdDeviationsExtrinsics Output vector of standard deviations estimated for extrinsic parameters. -See #calibrateCamera for details. -@param stdDeviationsObjPoints Output vector of standard deviations estimated for refined coordinates -of calibration pattern points. It has the same size and order as objectPoints[0] vector. This -parameter is ignored with standard calibration method. - @param perViewErrors Output vector of the RMS re-projection error estimated for each pattern view. -@param flags Different flags that may be zero or a combination of some predefined values. See -#calibrateCamera for details. If the method of releasing object is used, the calibration time may -be much longer. CALIB_USE_QR or CALIB_USE_LU could be used for faster calibration with potentially -less precise and less stable in some rare cases. -@param criteria Termination criteria for the iterative optimization algorithm. - -@return the overall RMS re-projection error. - -The function estimates the intrinsic camera parameters and extrinsic parameters for each of the -views. The algorithm is based on @cite Zhang2000, @cite BouguetMCT and @cite strobl2011iccv. See -#calibrateCamera for other detailed explanations. -@sa - calibrateCamera, findChessboardCorners, solvePnP, initCameraMatrix2D, stereoCalibrate, undistort - */ -CV_EXPORTS_AS(calibrateCameraROExtended) double calibrateCameraRO( InputArrayOfArrays objectPoints, - InputArrayOfArrays imagePoints, Size imageSize, int iFixedPoint, - InputOutputArray cameraMatrix, InputOutputArray distCoeffs, - OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, - OutputArray newObjPoints, - OutputArray stdDeviationsIntrinsics, - OutputArray stdDeviationsExtrinsics, - OutputArray stdDeviationsObjPoints, - OutputArray perViewErrors, - int flags = 0, TermCriteria criteria = TermCriteria( - TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) ); - -/** @overload */ -CV_EXPORTS_W double calibrateCameraRO( InputArrayOfArrays objectPoints, - InputArrayOfArrays imagePoints, Size imageSize, int iFixedPoint, - InputOutputArray cameraMatrix, InputOutputArray distCoeffs, - OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, - OutputArray newObjPoints, - int flags = 0, TermCriteria criteria = TermCriteria( - TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) ); - -/** @brief Computes useful camera characteristics from the camera intrinsic matrix. - -@param cameraMatrix Input camera intrinsic matrix that can be estimated by #calibrateCamera or -#stereoCalibrate . -@param imageSize Input image size in pixels. -@param apertureWidth Physical width in mm of the sensor. -@param apertureHeight Physical height in mm of the sensor. -@param fovx Output field of view in degrees along the horizontal sensor axis. -@param fovy Output field of view in degrees along the vertical sensor axis. -@param focalLength Focal length of the lens in mm. -@param principalPoint Principal point in mm. -@param aspectRatio \f$f_y/f_x\f$ - -The function computes various useful camera characteristics from the previously estimated camera -matrix. - -@note - Do keep in mind that the unity measure 'mm' stands for whatever unit of measure one chooses for - the chessboard pitch (it can thus be any value). - */ -CV_EXPORTS_W void calibrationMatrixValues( InputArray cameraMatrix, Size imageSize, - double apertureWidth, double apertureHeight, - CV_OUT double& fovx, CV_OUT double& fovy, - CV_OUT double& focalLength, CV_OUT Point2d& principalPoint, - CV_OUT double& aspectRatio ); - -/** @brief Calibrates a stereo camera set up. This function finds the intrinsic parameters -for each of the two cameras and the extrinsic parameters between the two cameras. - -@param objectPoints Vector of vectors of the calibration pattern points. The same structure as -in @ref calibrateCamera. For each pattern view, both cameras need to see the same object -points. Therefore, objectPoints.size(), imagePoints1.size(), and imagePoints2.size() need to be -equal as well as objectPoints[i].size(), imagePoints1[i].size(), and imagePoints2[i].size() need to -be equal for each i. -@param imagePoints1 Vector of vectors of the projections of the calibration pattern points, -observed by the first camera. The same structure as in @ref calibrateCamera. -@param imagePoints2 Vector of vectors of the projections of the calibration pattern points, -observed by the second camera. The same structure as in @ref calibrateCamera. -@param cameraMatrix1 Input/output camera intrinsic matrix for the first camera, the same as in -@ref calibrateCamera. Furthermore, for the stereo case, additional flags may be used, see below. -@param distCoeffs1 Input/output vector of distortion coefficients, the same as in -@ref calibrateCamera. -@param cameraMatrix2 Input/output second camera intrinsic matrix for the second camera. See description for -cameraMatrix1. -@param distCoeffs2 Input/output lens distortion coefficients for the second camera. See -description for distCoeffs1. -@param imageSize Size of the image used only to initialize the camera intrinsic matrices. -@param R Output rotation matrix. Together with the translation vector T, this matrix brings -points given in the first camera's coordinate system to points in the second camera's -coordinate system. In more technical terms, the tuple of R and T performs a change of basis -from the first camera's coordinate system to the second camera's coordinate system. Due to its -duality, this tuple is equivalent to the position of the first camera with respect to the -second camera coordinate system. -@param T Output translation vector, see description above. -@param E Output essential matrix. -@param F Output fundamental matrix. -@param rvecs Output vector of rotation vectors ( @ref Rodrigues ) estimated for each pattern view in the -coordinate system of the first camera of the stereo pair (e.g. std::vector). More in detail, each -i-th rotation vector together with the corresponding i-th translation vector (see the next output parameter -description) brings the calibration pattern from the object coordinate space (in which object points are -specified) to the camera coordinate space of the first camera of the stereo pair. In more technical terms, -the tuple of the i-th rotation and translation vector performs a change of basis from object coordinate space -to camera coordinate space of the first camera of the stereo pair. -@param tvecs Output vector of translation vectors estimated for each pattern view, see parameter description -of previous output parameter ( rvecs ). -@param perViewErrors Output vector of the RMS re-projection error estimated for each pattern view. -@param flags Different flags that may be zero or a combination of the following values: -- @ref CALIB_FIX_INTRINSIC Fix cameraMatrix? and distCoeffs? so that only R, T, E, and F -matrices are estimated. -- @ref CALIB_USE_INTRINSIC_GUESS Optimize some or all of the intrinsic parameters -according to the specified flags. Initial values are provided by the user. -- @ref CALIB_USE_EXTRINSIC_GUESS R and T contain valid initial values that are optimized further. -Otherwise R and T are initialized to the median value of the pattern views (each dimension separately). -- @ref CALIB_FIX_PRINCIPAL_POINT Fix the principal points during the optimization. -- @ref CALIB_FIX_FOCAL_LENGTH Fix \f$f^{(j)}_x\f$ and \f$f^{(j)}_y\f$ . -- @ref CALIB_FIX_ASPECT_RATIO Optimize \f$f^{(j)}_y\f$ . Fix the ratio \f$f^{(j)}_x/f^{(j)}_y\f$ -. -- @ref CALIB_SAME_FOCAL_LENGTH Enforce \f$f^{(0)}_x=f^{(1)}_x\f$ and \f$f^{(0)}_y=f^{(1)}_y\f$ . -- @ref CALIB_ZERO_TANGENT_DIST Set tangential distortion coefficients for each camera to -zeros and fix there. -- @ref CALIB_FIX_K1,..., @ref CALIB_FIX_K6 Do not change the corresponding radial -distortion coefficient during the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, -the coefficient from the supplied distCoeffs matrix is used. Otherwise, it is set to 0. -- @ref CALIB_RATIONAL_MODEL Enable coefficients k4, k5, and k6. To provide the backward -compatibility, this extra flag should be explicitly specified to make the calibration -function use the rational model and return 8 coefficients. If the flag is not set, the -function computes and returns only 5 distortion coefficients. -- @ref CALIB_THIN_PRISM_MODEL Coefficients s1, s2, s3 and s4 are enabled. To provide the -backward compatibility, this extra flag should be explicitly specified to make the -calibration function use the thin prism model and return 12 coefficients. If the flag is not -set, the function computes and returns only 5 distortion coefficients. -- @ref CALIB_FIX_S1_S2_S3_S4 The thin prism distortion coefficients are not changed during -the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the -supplied distCoeffs matrix is used. Otherwise, it is set to 0. -- @ref CALIB_TILTED_MODEL Coefficients tauX and tauY are enabled. To provide the -backward compatibility, this extra flag should be explicitly specified to make the -calibration function use the tilted sensor model and return 14 coefficients. If the flag is not -set, the function computes and returns only 5 distortion coefficients. -- @ref CALIB_FIX_TAUX_TAUY The coefficients of the tilted sensor model are not changed during -the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the -supplied distCoeffs matrix is used. Otherwise, it is set to 0. -@param criteria Termination criteria for the iterative optimization algorithm. - -The function estimates the transformation between two cameras making a stereo pair. If one computes -the poses of an object relative to the first camera and to the second camera, -( \f$R_1\f$,\f$T_1\f$ ) and (\f$R_2\f$,\f$T_2\f$), respectively, for a stereo camera where the -relative position and orientation between the two cameras are fixed, then those poses definitely -relate to each other. This means, if the relative position and orientation (\f$R\f$,\f$T\f$) of the -two cameras is known, it is possible to compute (\f$R_2\f$,\f$T_2\f$) when (\f$R_1\f$,\f$T_1\f$) is -given. This is what the described function does. It computes (\f$R\f$,\f$T\f$) such that: - -\f[R_2=R R_1\f] -\f[T_2=R T_1 + T.\f] - -Therefore, one can compute the coordinate representation of a 3D point for the second camera's -coordinate system when given the point's coordinate representation in the first camera's coordinate -system: - -\f[\begin{bmatrix} -X_2 \\ -Y_2 \\ -Z_2 \\ -1 -\end{bmatrix} = \begin{bmatrix} -R & T \\ -0 & 1 -\end{bmatrix} \begin{bmatrix} -X_1 \\ -Y_1 \\ -Z_1 \\ -1 -\end{bmatrix}.\f] - - -Optionally, it computes the essential matrix E: - -\f[E= \vecthreethree{0}{-T_2}{T_1}{T_2}{0}{-T_0}{-T_1}{T_0}{0} R\f] - -where \f$T_i\f$ are components of the translation vector \f$T\f$ : \f$T=[T_0, T_1, T_2]^T\f$ . -And the function can also compute the fundamental matrix F: - -\f[F = cameraMatrix2^{-T}\cdot E \cdot cameraMatrix1^{-1}\f] - -Besides the stereo-related information, the function can also perform a full calibration of each of -the two cameras. However, due to the high dimensionality of the parameter space and noise in the -input data, the function can diverge from the correct solution. If the intrinsic parameters can be -estimated with high accuracy for each of the cameras individually (for example, using -#calibrateCamera ), you are recommended to do so and then pass @ref CALIB_FIX_INTRINSIC flag to the -function along with the computed intrinsic parameters. Otherwise, if all the parameters are -estimated at once, it makes sense to restrict some parameters, for example, pass - @ref CALIB_SAME_FOCAL_LENGTH and @ref CALIB_ZERO_TANGENT_DIST flags, which is usually a -reasonable assumption. - -Similarly to #calibrateCamera, the function minimizes the total re-projection error for all the -points in all the available views from both cameras. The function returns the final value of the -re-projection error. - */ -CV_EXPORTS_AS(stereoCalibrateExtended) double stereoCalibrate( InputArrayOfArrays objectPoints, - InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, - InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1, - InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2, - Size imageSize, InputOutputArray R, InputOutputArray T, OutputArray E, OutputArray F, - OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, OutputArray perViewErrors, int flags = CALIB_FIX_INTRINSIC, - TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6) ); - -/// @overload -CV_EXPORTS_W double stereoCalibrate( InputArrayOfArrays objectPoints, - InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, - InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1, - InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2, - Size imageSize, OutputArray R,OutputArray T, OutputArray E, OutputArray F, - int flags = CALIB_FIX_INTRINSIC, - TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6) ); - -/// @overload -CV_EXPORTS_W double stereoCalibrate( InputArrayOfArrays objectPoints, - InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, - InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1, - InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2, - Size imageSize, InputOutputArray R, InputOutputArray T, OutputArray E, OutputArray F, - OutputArray perViewErrors, int flags = CALIB_FIX_INTRINSIC, - TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6) ); - -/** @brief Computes rectification transforms for each head of a calibrated stereo camera. - -@param cameraMatrix1 First camera intrinsic matrix. -@param distCoeffs1 First camera distortion parameters. -@param cameraMatrix2 Second camera intrinsic matrix. -@param distCoeffs2 Second camera distortion parameters. -@param imageSize Size of the image used for stereo calibration. -@param R Rotation matrix from the coordinate system of the first camera to the second camera, -see @ref stereoCalibrate. -@param T Translation vector from the coordinate system of the first camera to the second camera, -see @ref stereoCalibrate. -@param R1 Output 3x3 rectification transform (rotation matrix) for the first camera. This matrix -brings points given in the unrectified first camera's coordinate system to points in the rectified -first camera's coordinate system. In more technical terms, it performs a change of basis from the -unrectified first camera's coordinate system to the rectified first camera's coordinate system. -@param R2 Output 3x3 rectification transform (rotation matrix) for the second camera. This matrix -brings points given in the unrectified second camera's coordinate system to points in the rectified -second camera's coordinate system. In more technical terms, it performs a change of basis from the -unrectified second camera's coordinate system to the rectified second camera's coordinate system. -@param P1 Output 3x4 projection matrix in the new (rectified) coordinate systems for the first -camera, i.e. it projects points given in the rectified first camera coordinate system into the -rectified first camera's image. -@param P2 Output 3x4 projection matrix in the new (rectified) coordinate systems for the second -camera, i.e. it projects points given in the rectified first camera coordinate system into the -rectified second camera's image. -@param Q Output \f$4 \times 4\f$ disparity-to-depth mapping matrix (see @ref reprojectImageTo3D). -@param flags Operation flags that may be zero or @ref CALIB_ZERO_DISPARITY . If the flag is set, -the function makes the principal points of each camera have the same pixel coordinates in the -rectified views. And if the flag is not set, the function may still shift the images in the -horizontal or vertical direction (depending on the orientation of epipolar lines) to maximize the -useful image area. -@param alpha Free scaling parameter. If it is -1 or absent, the function performs the default -scaling. Otherwise, the parameter should be between 0 and 1. alpha=0 means that the rectified -images are zoomed and shifted so that only valid pixels are visible (no black areas after -rectification). alpha=1 means that the rectified image is decimated and shifted so that all the -pixels from the original images from the cameras are retained in the rectified images (no source -image pixels are lost). Any intermediate value yields an intermediate result between -those two extreme cases. -@param newImageSize New image resolution after rectification. The same size should be passed to -#initUndistortRectifyMap (see the stereo_calib.cpp sample in OpenCV samples directory). When (0,0) -is passed (default), it is set to the original imageSize . Setting it to a larger value can help you -preserve details in the original image, especially when there is a big radial distortion. -@param validPixROI1 Optional output rectangles inside the rectified images where all the pixels -are valid. If alpha=0 , the ROIs cover the whole images. Otherwise, they are likely to be smaller -(see the picture below). -@param validPixROI2 Optional output rectangles inside the rectified images where all the pixels -are valid. If alpha=0 , the ROIs cover the whole images. Otherwise, they are likely to be smaller -(see the picture below). - -The function computes the rotation matrices for each camera that (virtually) make both camera image -planes the same plane. Consequently, this makes all the epipolar lines parallel and thus simplifies -the dense stereo correspondence problem. The function takes the matrices computed by #stereoCalibrate -as input. As output, it provides two rotation matrices and also two projection matrices in the new -coordinates. The function distinguishes the following two cases: - -- **Horizontal stereo**: the first and the second camera views are shifted relative to each other - mainly along the x-axis (with possible small vertical shift). In the rectified images, the - corresponding epipolar lines in the left and right cameras are horizontal and have the same - y-coordinate. P1 and P2 look like: - - \f[\texttt{P1} = \begin{bmatrix} - f & 0 & cx_1 & 0 \\ - 0 & f & cy & 0 \\ - 0 & 0 & 1 & 0 - \end{bmatrix}\f] - - \f[\texttt{P2} = \begin{bmatrix} - f & 0 & cx_2 & T_x \cdot f \\ - 0 & f & cy & 0 \\ - 0 & 0 & 1 & 0 - \end{bmatrix} ,\f] - - \f[\texttt{Q} = \begin{bmatrix} - 1 & 0 & 0 & -cx_1 \\ - 0 & 1 & 0 & -cy \\ - 0 & 0 & 0 & f \\ - 0 & 0 & -\frac{1}{T_x} & \frac{cx_1 - cx_2}{T_x} - \end{bmatrix} \f] - - where \f$T_x\f$ is a horizontal shift between the cameras and \f$cx_1=cx_2\f$ if - @ref CALIB_ZERO_DISPARITY is set. - -- **Vertical stereo**: the first and the second camera views are shifted relative to each other - mainly in the vertical direction (and probably a bit in the horizontal direction too). The epipolar - lines in the rectified images are vertical and have the same x-coordinate. P1 and P2 look like: - - \f[\texttt{P1} = \begin{bmatrix} - f & 0 & cx & 0 \\ - 0 & f & cy_1 & 0 \\ - 0 & 0 & 1 & 0 - \end{bmatrix}\f] - - \f[\texttt{P2} = \begin{bmatrix} - f & 0 & cx & 0 \\ - 0 & f & cy_2 & T_y \cdot f \\ - 0 & 0 & 1 & 0 - \end{bmatrix},\f] - - \f[\texttt{Q} = \begin{bmatrix} - 1 & 0 & 0 & -cx \\ - 0 & 1 & 0 & -cy_1 \\ - 0 & 0 & 0 & f \\ - 0 & 0 & -\frac{1}{T_y} & \frac{cy_1 - cy_2}{T_y} - \end{bmatrix} \f] - - where \f$T_y\f$ is a vertical shift between the cameras and \f$cy_1=cy_2\f$ if - @ref CALIB_ZERO_DISPARITY is set. - -As you can see, the first three columns of P1 and P2 will effectively be the new "rectified" camera -matrices. The matrices, together with R1 and R2 , can then be passed to #initUndistortRectifyMap to -initialize the rectification map for each camera. - -See below the screenshot from the stereo_calib.cpp sample. Some red horizontal lines pass through -the corresponding image regions. This means that the images are well rectified, which is what most -stereo correspondence algorithms rely on. The green rectangles are roi1 and roi2 . You see that -their interiors are all valid pixels. - -![image](pics/stereo_undistort.jpg) - */ -CV_EXPORTS_W void stereoRectify( InputArray cameraMatrix1, InputArray distCoeffs1, - InputArray cameraMatrix2, InputArray distCoeffs2, - Size imageSize, InputArray R, InputArray T, - OutputArray R1, OutputArray R2, - OutputArray P1, OutputArray P2, - OutputArray Q, int flags = CALIB_ZERO_DISPARITY, - double alpha = -1, Size newImageSize = Size(), - CV_OUT Rect* validPixROI1 = 0, CV_OUT Rect* validPixROI2 = 0 ); - -/** @brief Computes a rectification transform for an uncalibrated stereo camera. - -@param points1 Array of feature points in the first image. -@param points2 The corresponding points in the second image. The same formats as in -#findFundamentalMat are supported. -@param F Input fundamental matrix. It can be computed from the same set of point pairs using -#findFundamentalMat . -@param imgSize Size of the image. -@param H1 Output rectification homography matrix for the first image. -@param H2 Output rectification homography matrix for the second image. -@param threshold Optional threshold used to filter out the outliers. If the parameter is greater -than zero, all the point pairs that do not comply with the epipolar geometry (that is, the points -for which \f$|\texttt{points2[i]}^T \cdot \texttt{F} \cdot \texttt{points1[i]}|>\texttt{threshold}\f$ ) -are rejected prior to computing the homographies. Otherwise, all the points are considered inliers. - -The function computes the rectification transformations without knowing intrinsic parameters of the -cameras and their relative position in the space, which explains the suffix "uncalibrated". Another -related difference from #stereoRectify is that the function outputs not the rectification -transformations in the object (3D) space, but the planar perspective transformations encoded by the -homography matrices H1 and H2 . The function implements the algorithm @cite Hartley99 . - -@note - While the algorithm does not need to know the intrinsic parameters of the cameras, it heavily - depends on the epipolar geometry. Therefore, if the camera lenses have a significant distortion, - it would be better to correct it before computing the fundamental matrix and calling this - function. For example, distortion coefficients can be estimated for each head of stereo camera - separately by using #calibrateCamera . Then, the images can be corrected using #undistort , or - just the point coordinates can be corrected with #undistortPoints . - */ -CV_EXPORTS_W bool stereoRectifyUncalibrated( InputArray points1, InputArray points2, - InputArray F, Size imgSize, - OutputArray H1, OutputArray H2, - double threshold = 5 ); - -//! computes the rectification transformations for 3-head camera, where all the heads are on the same line. -CV_EXPORTS_W float rectify3Collinear( InputArray cameraMatrix1, InputArray distCoeffs1, - InputArray cameraMatrix2, InputArray distCoeffs2, - InputArray cameraMatrix3, InputArray distCoeffs3, - InputArrayOfArrays imgpt1, InputArrayOfArrays imgpt3, - Size imageSize, InputArray R12, InputArray T12, - InputArray R13, InputArray T13, - OutputArray R1, OutputArray R2, OutputArray R3, - OutputArray P1, OutputArray P2, OutputArray P3, - OutputArray Q, double alpha, Size newImgSize, - CV_OUT Rect* roi1, CV_OUT Rect* roi2, int flags ); - -/** @brief Returns the new camera intrinsic matrix based on the free scaling parameter. - -@param cameraMatrix Input camera intrinsic matrix. -@param distCoeffs Input vector of distortion coefficients -\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are -assumed. -@param imageSize Original image size. -@param alpha Free scaling parameter between 0 (when all the pixels in the undistorted image are -valid) and 1 (when all the source image pixels are retained in the undistorted image). See -#stereoRectify for details. -@param newImgSize Image size after rectification. By default, it is set to imageSize . -@param validPixROI Optional output rectangle that outlines all-good-pixels region in the -undistorted image. See roi1, roi2 description in #stereoRectify . -@param centerPrincipalPoint Optional flag that indicates whether in the new camera intrinsic matrix the -principal point should be at the image center or not. By default, the principal point is chosen to -best fit a subset of the source image (determined by alpha) to the corrected image. -@return new_camera_matrix Output new camera intrinsic matrix. - -The function computes and returns the optimal new camera intrinsic matrix based on the free scaling parameter. -By varying this parameter, you may retrieve only sensible pixels alpha=0 , keep all the original -image pixels if there is valuable information in the corners alpha=1 , or get something in between. -When alpha\>0 , the undistorted result is likely to have some black pixels corresponding to -"virtual" pixels outside of the captured distorted image. The original camera intrinsic matrix, distortion -coefficients, the computed new camera intrinsic matrix, and newImageSize should be passed to -#initUndistortRectifyMap to produce the maps for #remap . - */ -CV_EXPORTS_W Mat getOptimalNewCameraMatrix( InputArray cameraMatrix, InputArray distCoeffs, - Size imageSize, double alpha, Size newImgSize = Size(), - CV_OUT Rect* validPixROI = 0, - bool centerPrincipalPoint = false); - -/** @brief Computes Hand-Eye calibration: \f$_{}^{g}\textrm{T}_c\f$ - -@param[in] R_gripper2base Rotation part extracted from the homogeneous matrix that transforms a point -expressed in the gripper frame to the robot base frame (\f$_{}^{b}\textrm{T}_g\f$). -This is a vector (`vector`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors, -for all the transformations from gripper frame to robot base frame. -@param[in] t_gripper2base Translation part extracted from the homogeneous matrix that transforms a point -expressed in the gripper frame to the robot base frame (\f$_{}^{b}\textrm{T}_g\f$). -This is a vector (`vector`) that contains the `(3x1)` translation vectors for all the transformations -from gripper frame to robot base frame. -@param[in] R_target2cam Rotation part extracted from the homogeneous matrix that transforms a point -expressed in the target frame to the camera frame (\f$_{}^{c}\textrm{T}_t\f$). -This is a vector (`vector`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors, -for all the transformations from calibration target frame to camera frame. -@param[in] t_target2cam Rotation part extracted from the homogeneous matrix that transforms a point -expressed in the target frame to the camera frame (\f$_{}^{c}\textrm{T}_t\f$). -This is a vector (`vector`) that contains the `(3x1)` translation vectors for all the transformations -from calibration target frame to camera frame. -@param[out] R_cam2gripper Estimated `(3x3)` rotation part extracted from the homogeneous matrix that transforms a point -expressed in the camera frame to the gripper frame (\f$_{}^{g}\textrm{T}_c\f$). -@param[out] t_cam2gripper Estimated `(3x1)` translation part extracted from the homogeneous matrix that transforms a point -expressed in the camera frame to the gripper frame (\f$_{}^{g}\textrm{T}_c\f$). -@param[in] method One of the implemented Hand-Eye calibration method, see cv::HandEyeCalibrationMethod - -The function performs the Hand-Eye calibration using various methods. One approach consists in estimating the -rotation then the translation (separable solutions) and the following methods are implemented: - - R. Tsai, R. Lenz A New Technique for Fully Autonomous and Efficient 3D Robotics Hand/EyeCalibration \cite Tsai89 - - F. Park, B. Martin Robot Sensor Calibration: Solving AX = XB on the Euclidean Group \cite Park94 - - R. Horaud, F. Dornaika Hand-Eye Calibration \cite Horaud95 - -Another approach consists in estimating simultaneously the rotation and the translation (simultaneous solutions), -with the following implemented methods: - - N. Andreff, R. Horaud, B. Espiau On-line Hand-Eye Calibration \cite Andreff99 - - K. Daniilidis Hand-Eye Calibration Using Dual Quaternions \cite Daniilidis98 - -The following picture describes the Hand-Eye calibration problem where the transformation between a camera ("eye") -mounted on a robot gripper ("hand") has to be estimated. This configuration is called eye-in-hand. - -The eye-to-hand configuration consists in a static camera observing a calibration pattern mounted on the robot -end-effector. The transformation from the camera to the robot base frame can then be estimated by inputting -the suitable transformations to the function, see below. - -![](pics/hand-eye_figure.png) - -The calibration procedure is the following: - - a static calibration pattern is used to estimate the transformation between the target frame - and the camera frame - - the robot gripper is moved in order to acquire several poses - - for each pose, the homogeneous transformation between the gripper frame and the robot base frame is recorded using for - instance the robot kinematics -\f[ - \begin{bmatrix} - X_b\\ - Y_b\\ - Z_b\\ - 1 - \end{bmatrix} - = - \begin{bmatrix} - _{}^{b}\textrm{R}_g & _{}^{b}\textrm{t}_g \\ - 0_{1 \times 3} & 1 - \end{bmatrix} - \begin{bmatrix} - X_g\\ - Y_g\\ - Z_g\\ - 1 - \end{bmatrix} -\f] - - for each pose, the homogeneous transformation between the calibration target frame and the camera frame is recorded using - for instance a pose estimation method (PnP) from 2D-3D point correspondences -\f[ - \begin{bmatrix} - X_c\\ - Y_c\\ - Z_c\\ - 1 - \end{bmatrix} - = - \begin{bmatrix} - _{}^{c}\textrm{R}_t & _{}^{c}\textrm{t}_t \\ - 0_{1 \times 3} & 1 - \end{bmatrix} - \begin{bmatrix} - X_t\\ - Y_t\\ - Z_t\\ - 1 - \end{bmatrix} -\f] - -The Hand-Eye calibration procedure returns the following homogeneous transformation -\f[ - \begin{bmatrix} - X_g\\ - Y_g\\ - Z_g\\ - 1 - \end{bmatrix} - = - \begin{bmatrix} - _{}^{g}\textrm{R}_c & _{}^{g}\textrm{t}_c \\ - 0_{1 \times 3} & 1 - \end{bmatrix} - \begin{bmatrix} - X_c\\ - Y_c\\ - Z_c\\ - 1 - \end{bmatrix} -\f] - -This problem is also known as solving the \f$\mathbf{A}\mathbf{X}=\mathbf{X}\mathbf{B}\f$ equation: - - for an eye-in-hand configuration -\f[ - \begin{align*} - ^{b}{\textrm{T}_g}^{(1)} \hspace{0.2em} ^{g}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(1)} &= - \hspace{0.1em} ^{b}{\textrm{T}_g}^{(2)} \hspace{0.2em} ^{g}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} \\ - - (^{b}{\textrm{T}_g}^{(2)})^{-1} \hspace{0.2em} ^{b}{\textrm{T}_g}^{(1)} \hspace{0.2em} ^{g}\textrm{T}_c &= - \hspace{0.1em} ^{g}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} (^{c}{\textrm{T}_t}^{(1)})^{-1} \\ - - \textrm{A}_i \textrm{X} &= \textrm{X} \textrm{B}_i \\ - \end{align*} -\f] - - - for an eye-to-hand configuration -\f[ - \begin{align*} - ^{g}{\textrm{T}_b}^{(1)} \hspace{0.2em} ^{b}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(1)} &= - \hspace{0.1em} ^{g}{\textrm{T}_b}^{(2)} \hspace{0.2em} ^{b}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} \\ - - (^{g}{\textrm{T}_b}^{(2)})^{-1} \hspace{0.2em} ^{g}{\textrm{T}_b}^{(1)} \hspace{0.2em} ^{b}\textrm{T}_c &= - \hspace{0.1em} ^{b}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} (^{c}{\textrm{T}_t}^{(1)})^{-1} \\ - - \textrm{A}_i \textrm{X} &= \textrm{X} \textrm{B}_i \\ - \end{align*} -\f] - -\note -Additional information can be found on this [website](http://campar.in.tum.de/Chair/HandEyeCalibration). -\note -A minimum of 2 motions with non parallel rotation axes are necessary to determine the hand-eye transformation. -So at least 3 different poses are required, but it is strongly recommended to use many more poses. - - */ -CV_EXPORTS_W void calibrateHandEye( InputArrayOfArrays R_gripper2base, InputArrayOfArrays t_gripper2base, - InputArrayOfArrays R_target2cam, InputArrayOfArrays t_target2cam, - OutputArray R_cam2gripper, OutputArray t_cam2gripper, - HandEyeCalibrationMethod method=CALIB_HAND_EYE_TSAI ); - -/** @brief Computes Robot-World/Hand-Eye calibration: \f$_{}^{w}\textrm{T}_b\f$ and \f$_{}^{c}\textrm{T}_g\f$ - -@param[in] R_world2cam Rotation part extracted from the homogeneous matrix that transforms a point -expressed in the world frame to the camera frame (\f$_{}^{c}\textrm{T}_w\f$). -This is a vector (`vector`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors, -for all the transformations from world frame to the camera frame. -@param[in] t_world2cam Translation part extracted from the homogeneous matrix that transforms a point -expressed in the world frame to the camera frame (\f$_{}^{c}\textrm{T}_w\f$). -This is a vector (`vector`) that contains the `(3x1)` translation vectors for all the transformations -from world frame to the camera frame. -@param[in] R_base2gripper Rotation part extracted from the homogeneous matrix that transforms a point -expressed in the robot base frame to the gripper frame (\f$_{}^{g}\textrm{T}_b\f$). -This is a vector (`vector`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors, -for all the transformations from robot base frame to the gripper frame. -@param[in] t_base2gripper Rotation part extracted from the homogeneous matrix that transforms a point -expressed in the robot base frame to the gripper frame (\f$_{}^{g}\textrm{T}_b\f$). -This is a vector (`vector`) that contains the `(3x1)` translation vectors for all the transformations -from robot base frame to the gripper frame. -@param[out] R_base2world Estimated `(3x3)` rotation part extracted from the homogeneous matrix that transforms a point -expressed in the robot base frame to the world frame (\f$_{}^{w}\textrm{T}_b\f$). -@param[out] t_base2world Estimated `(3x1)` translation part extracted from the homogeneous matrix that transforms a point -expressed in the robot base frame to the world frame (\f$_{}^{w}\textrm{T}_b\f$). -@param[out] R_gripper2cam Estimated `(3x3)` rotation part extracted from the homogeneous matrix that transforms a point -expressed in the gripper frame to the camera frame (\f$_{}^{c}\textrm{T}_g\f$). -@param[out] t_gripper2cam Estimated `(3x1)` translation part extracted from the homogeneous matrix that transforms a point -expressed in the gripper frame to the camera frame (\f$_{}^{c}\textrm{T}_g\f$). -@param[in] method One of the implemented Robot-World/Hand-Eye calibration method, see cv::RobotWorldHandEyeCalibrationMethod - -The function performs the Robot-World/Hand-Eye calibration using various methods. One approach consists in estimating the -rotation then the translation (separable solutions): - - M. Shah, Solving the robot-world/hand-eye calibration problem using the kronecker product \cite Shah2013SolvingTR - -Another approach consists in estimating simultaneously the rotation and the translation (simultaneous solutions), -with the following implemented method: - - A. Li, L. Wang, and D. Wu, Simultaneous robot-world and hand-eye calibration using dual-quaternions and kronecker product \cite Li2010SimultaneousRA - -The following picture describes the Robot-World/Hand-Eye calibration problem where the transformations between a robot and a world frame -and between a robot gripper ("hand") and a camera ("eye") mounted at the robot end-effector have to be estimated. - -![](pics/robot-world_hand-eye_figure.png) - -The calibration procedure is the following: - - a static calibration pattern is used to estimate the transformation between the target frame - and the camera frame - - the robot gripper is moved in order to acquire several poses - - for each pose, the homogeneous transformation between the gripper frame and the robot base frame is recorded using for - instance the robot kinematics -\f[ - \begin{bmatrix} - X_g\\ - Y_g\\ - Z_g\\ - 1 - \end{bmatrix} - = - \begin{bmatrix} - _{}^{g}\textrm{R}_b & _{}^{g}\textrm{t}_b \\ - 0_{1 \times 3} & 1 - \end{bmatrix} - \begin{bmatrix} - X_b\\ - Y_b\\ - Z_b\\ - 1 - \end{bmatrix} -\f] - - for each pose, the homogeneous transformation between the calibration target frame (the world frame) and the camera frame is recorded using - for instance a pose estimation method (PnP) from 2D-3D point correspondences -\f[ - \begin{bmatrix} - X_c\\ - Y_c\\ - Z_c\\ - 1 - \end{bmatrix} - = - \begin{bmatrix} - _{}^{c}\textrm{R}_w & _{}^{c}\textrm{t}_w \\ - 0_{1 \times 3} & 1 - \end{bmatrix} - \begin{bmatrix} - X_w\\ - Y_w\\ - Z_w\\ - 1 - \end{bmatrix} -\f] - -The Robot-World/Hand-Eye calibration procedure returns the following homogeneous transformations -\f[ - \begin{bmatrix} - X_w\\ - Y_w\\ - Z_w\\ - 1 - \end{bmatrix} - = - \begin{bmatrix} - _{}^{w}\textrm{R}_b & _{}^{w}\textrm{t}_b \\ - 0_{1 \times 3} & 1 - \end{bmatrix} - \begin{bmatrix} - X_b\\ - Y_b\\ - Z_b\\ - 1 - \end{bmatrix} -\f] -\f[ - \begin{bmatrix} - X_c\\ - Y_c\\ - Z_c\\ - 1 - \end{bmatrix} - = - \begin{bmatrix} - _{}^{c}\textrm{R}_g & _{}^{c}\textrm{t}_g \\ - 0_{1 \times 3} & 1 - \end{bmatrix} - \begin{bmatrix} - X_g\\ - Y_g\\ - Z_g\\ - 1 - \end{bmatrix} -\f] - -This problem is also known as solving the \f$\mathbf{A}\mathbf{X}=\mathbf{Z}\mathbf{B}\f$ equation, with: - - \f$\mathbf{A} \Leftrightarrow \hspace{0.1em} _{}^{c}\textrm{T}_w\f$ - - \f$\mathbf{X} \Leftrightarrow \hspace{0.1em} _{}^{w}\textrm{T}_b\f$ - - \f$\mathbf{Z} \Leftrightarrow \hspace{0.1em} _{}^{c}\textrm{T}_g\f$ - - \f$\mathbf{B} \Leftrightarrow \hspace{0.1em} _{}^{g}\textrm{T}_b\f$ - -\note -At least 3 measurements are required (input vectors size must be greater or equal to 3). - - */ -CV_EXPORTS_W void calibrateRobotWorldHandEye( InputArrayOfArrays R_world2cam, InputArrayOfArrays t_world2cam, - InputArrayOfArrays R_base2gripper, InputArrayOfArrays t_base2gripper, - OutputArray R_base2world, OutputArray t_base2world, - OutputArray R_gripper2cam, OutputArray t_gripper2cam, - RobotWorldHandEyeCalibrationMethod method=CALIB_ROBOT_WORLD_HAND_EYE_SHAH ); - -/** @brief Converts points from Euclidean to homogeneous space. - -@param src Input vector of N-dimensional points. -@param dst Output vector of N+1-dimensional points. - -The function converts points from Euclidean to homogeneous space by appending 1's to the tuple of -point coordinates. That is, each point (x1, x2, ..., xn) is converted to (x1, x2, ..., xn, 1). - */ -CV_EXPORTS_W void convertPointsToHomogeneous( InputArray src, OutputArray dst ); - -/** @brief Converts points from homogeneous to Euclidean space. - -@param src Input vector of N-dimensional points. -@param dst Output vector of N-1-dimensional points. - -The function converts points homogeneous to Euclidean space using perspective projection. That is, -each point (x1, x2, ... x(n-1), xn) is converted to (x1/xn, x2/xn, ..., x(n-1)/xn). When xn=0, the -output point coordinates will be (0,0,0,...). - */ -CV_EXPORTS_W void convertPointsFromHomogeneous( InputArray src, OutputArray dst ); - -/** @brief Converts points to/from homogeneous coordinates. - -@param src Input array or vector of 2D, 3D, or 4D points. -@param dst Output vector of 2D, 3D, or 4D points. - -The function converts 2D or 3D points from/to homogeneous coordinates by calling either -#convertPointsToHomogeneous or #convertPointsFromHomogeneous. - -@note The function is obsolete. Use one of the previous two functions instead. - */ -CV_EXPORTS void convertPointsHomogeneous( InputArray src, OutputArray dst ); - -/** @brief Calculates a fundamental matrix from the corresponding points in two images. - -@param points1 Array of N points from the first image. The point coordinates should be -floating-point (single or double precision). -@param points2 Array of the second image points of the same size and format as points1 . -@param method Method for computing a fundamental matrix. -- @ref FM_7POINT for a 7-point algorithm. \f$N = 7\f$ -- @ref FM_8POINT for an 8-point algorithm. \f$N \ge 8\f$ -- @ref FM_RANSAC for the RANSAC algorithm. \f$N \ge 8\f$ -- @ref FM_LMEDS for the LMedS algorithm. \f$N \ge 8\f$ -@param ransacReprojThreshold Parameter used only for RANSAC. It is the maximum distance from a point to an epipolar -line in pixels, beyond which the point is considered an outlier and is not used for computing the -final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the -point localization, image resolution, and the image noise. -@param confidence Parameter used for the RANSAC and LMedS methods only. It specifies a desirable level -of confidence (probability) that the estimated matrix is correct. -@param[out] mask optional output mask -@param maxIters The maximum number of robust method iterations. - -The epipolar geometry is described by the following equation: - -\f[[p_2; 1]^T F [p_1; 1] = 0\f] - -where \f$F\f$ is a fundamental matrix, \f$p_1\f$ and \f$p_2\f$ are corresponding points in the first and the -second images, respectively. - -The function calculates the fundamental matrix using one of four methods listed above and returns -the found fundamental matrix. Normally just one matrix is found. But in case of the 7-point -algorithm, the function may return up to 3 solutions ( \f$9 \times 3\f$ matrix that stores all 3 -matrices sequentially). - -The calculated fundamental matrix may be passed further to #computeCorrespondEpilines that finds the -epipolar lines corresponding to the specified points. It can also be passed to -#stereoRectifyUncalibrated to compute the rectification transformation. : -@code - // Example. Estimation of fundamental matrix using the RANSAC algorithm - int point_count = 100; - vector points1(point_count); - vector points2(point_count); - - // initialize the points here ... - for( int i = 0; i < point_count; i++ ) - { - points1[i] = ...; - points2[i] = ...; - } - - Mat fundamental_matrix = - findFundamentalMat(points1, points2, FM_RANSAC, 3, 0.99); -@endcode - */ -CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2, - int method, double ransacReprojThreshold, double confidence, - int maxIters, OutputArray mask = noArray() ); - -/** @overload */ -CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2, - int method = FM_RANSAC, - double ransacReprojThreshold = 3., double confidence = 0.99, - OutputArray mask = noArray() ); - -/** @overload */ -CV_EXPORTS Mat findFundamentalMat( InputArray points1, InputArray points2, - OutputArray mask, int method = FM_RANSAC, - double ransacReprojThreshold = 3., double confidence = 0.99 ); - - -CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2, - OutputArray mask, const UsacParams ¶ms); - -/** @brief Calculates an essential matrix from the corresponding points in two images. - -@param points1 Array of N (N \>= 5) 2D points from the first image. The point coordinates should -be floating-point (single or double precision). -@param points2 Array of the second image points of the same size and format as points1. -@param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ . -Note that this function assumes that points1 and points2 are feature points from cameras with the -same camera intrinsic matrix. If this assumption does not hold for your use case, use another -function overload or #undistortPoints with `P = cv::NoArray()` for both cameras to transform image -points to normalized image coordinates, which are valid for the identity camera intrinsic matrix. -When passing these coordinates, pass the identity matrix for this parameter. -@param method Method for computing an essential matrix. -- @ref RANSAC for the RANSAC algorithm. -- @ref LMEDS for the LMedS algorithm. -@param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of -confidence (probability) that the estimated matrix is correct. -@param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar -line in pixels, beyond which the point is considered an outlier and is not used for computing the -final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the -point localization, image resolution, and the image noise. -@param mask Output array of N elements, every element of which is set to 0 for outliers and to 1 -for the other points. The array is computed only in the RANSAC and LMedS methods. -@param maxIters The maximum number of robust method iterations. - -This function estimates essential matrix based on the five-point algorithm solver in @cite Nister03 . -@cite SteweniusCFS is also a related. The epipolar geometry is described by the following equation: - -\f[[p_2; 1]^T K^{-T} E K^{-1} [p_1; 1] = 0\f] - -where \f$E\f$ is an essential matrix, \f$p_1\f$ and \f$p_2\f$ are corresponding points in the first and the -second images, respectively. The result of this function may be passed further to -#decomposeEssentialMat or #recoverPose to recover the relative pose between cameras. - */ -CV_EXPORTS_W -Mat findEssentialMat( - InputArray points1, InputArray points2, - InputArray cameraMatrix, int method = RANSAC, - double prob = 0.999, double threshold = 1.0, - int maxIters = 1000, OutputArray mask = noArray() -); - -/** @overload */ -CV_EXPORTS -Mat findEssentialMat( - InputArray points1, InputArray points2, - InputArray cameraMatrix, int method, - double prob, double threshold, - OutputArray mask -); // TODO remove from OpenCV 5.0 - -/** @overload -@param points1 Array of N (N \>= 5) 2D points from the first image. The point coordinates should -be floating-point (single or double precision). -@param points2 Array of the second image points of the same size and format as points1 . -@param focal focal length of the camera. Note that this function assumes that points1 and points2 -are feature points from cameras with same focal length and principal point. -@param pp principal point of the camera. -@param method Method for computing a fundamental matrix. -- @ref RANSAC for the RANSAC algorithm. -- @ref LMEDS for the LMedS algorithm. -@param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar -line in pixels, beyond which the point is considered an outlier and is not used for computing the -final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the -point localization, image resolution, and the image noise. -@param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of -confidence (probability) that the estimated matrix is correct. -@param mask Output array of N elements, every element of which is set to 0 for outliers and to 1 -for the other points. The array is computed only in the RANSAC and LMedS methods. -@param maxIters The maximum number of robust method iterations. - -This function differs from the one above that it computes camera intrinsic matrix from focal length and -principal point: - -\f[A = -\begin{bmatrix} -f & 0 & x_{pp} \\ -0 & f & y_{pp} \\ -0 & 0 & 1 -\end{bmatrix}\f] - */ -CV_EXPORTS_W -Mat findEssentialMat( - InputArray points1, InputArray points2, - double focal = 1.0, Point2d pp = Point2d(0, 0), - int method = RANSAC, double prob = 0.999, - double threshold = 1.0, int maxIters = 1000, - OutputArray mask = noArray() -); - -/** @overload */ -CV_EXPORTS -Mat findEssentialMat( - InputArray points1, InputArray points2, - double focal, Point2d pp, - int method, double prob, - double threshold, OutputArray mask -); // TODO remove from OpenCV 5.0 - -/** @brief Calculates an essential matrix from the corresponding points in two images from potentially two different cameras. - -@param points1 Array of N (N \>= 5) 2D points from the first image. The point coordinates should -be floating-point (single or double precision). -@param points2 Array of the second image points of the same size and format as points1. -@param cameraMatrix1 Camera matrix for the first camera \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . -@param cameraMatrix2 Camera matrix for the second camera \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . -@param distCoeffs1 Input vector of distortion coefficients for the first camera -\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ -of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. -@param distCoeffs2 Input vector of distortion coefficients for the second camera -\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ -of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. -@param method Method for computing an essential matrix. -- @ref RANSAC for the RANSAC algorithm. -- @ref LMEDS for the LMedS algorithm. -@param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of -confidence (probability) that the estimated matrix is correct. -@param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar -line in pixels, beyond which the point is considered an outlier and is not used for computing the -final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the -point localization, image resolution, and the image noise. -@param mask Output array of N elements, every element of which is set to 0 for outliers and to 1 -for the other points. The array is computed only in the RANSAC and LMedS methods. - -This function estimates essential matrix based on the five-point algorithm solver in @cite Nister03 . -@cite SteweniusCFS is also a related. The epipolar geometry is described by the following equation: - -\f[[p_2; 1]^T K^{-T} E K^{-1} [p_1; 1] = 0\f] - -where \f$E\f$ is an essential matrix, \f$p_1\f$ and \f$p_2\f$ are corresponding points in the first and the -second images, respectively. The result of this function may be passed further to -#decomposeEssentialMat or #recoverPose to recover the relative pose between cameras. - */ -CV_EXPORTS_W Mat findEssentialMat( InputArray points1, InputArray points2, - InputArray cameraMatrix1, InputArray distCoeffs1, - InputArray cameraMatrix2, InputArray distCoeffs2, - int method = RANSAC, - double prob = 0.999, double threshold = 1.0, - OutputArray mask = noArray() ); - - -CV_EXPORTS_W Mat findEssentialMat( InputArray points1, InputArray points2, - InputArray cameraMatrix1, InputArray cameraMatrix2, - InputArray dist_coeff1, InputArray dist_coeff2, OutputArray mask, - const UsacParams ¶ms); - -/** @brief Decompose an essential matrix to possible rotations and translation. - -@param E The input essential matrix. -@param R1 One possible rotation matrix. -@param R2 Another possible rotation matrix. -@param t One possible translation. - -This function decomposes the essential matrix E using svd decomposition @cite HartleyZ00. In -general, four possible poses exist for the decomposition of E. They are \f$[R_1, t]\f$, -\f$[R_1, -t]\f$, \f$[R_2, t]\f$, \f$[R_2, -t]\f$. - -If E gives the epipolar constraint \f$[p_2; 1]^T A^{-T} E A^{-1} [p_1; 1] = 0\f$ between the image -points \f$p_1\f$ in the first image and \f$p_2\f$ in second image, then any of the tuples -\f$[R_1, t]\f$, \f$[R_1, -t]\f$, \f$[R_2, t]\f$, \f$[R_2, -t]\f$ is a change of basis from the first -camera's coordinate system to the second camera's coordinate system. However, by decomposing E, one -can only get the direction of the translation. For this reason, the translation t is returned with -unit length. - */ -CV_EXPORTS_W void decomposeEssentialMat( InputArray E, OutputArray R1, OutputArray R2, OutputArray t ); - -/** @brief Recovers the relative camera rotation and the translation from corresponding points in two images from two different cameras, using cheirality check. Returns the number of -inliers that pass the check. - -@param points1 Array of N 2D points from the first image. The point coordinates should be -floating-point (single or double precision). -@param points2 Array of the second image points of the same size and format as points1 . -@param cameraMatrix1 Input/output camera matrix for the first camera, the same as in -@ref calibrateCamera. Furthermore, for the stereo case, additional flags may be used, see below. -@param distCoeffs1 Input/output vector of distortion coefficients, the same as in -@ref calibrateCamera. -@param cameraMatrix2 Input/output camera matrix for the first camera, the same as in -@ref calibrateCamera. Furthermore, for the stereo case, additional flags may be used, see below. -@param distCoeffs2 Input/output vector of distortion coefficients, the same as in -@ref calibrateCamera. -@param E The output essential matrix. -@param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple -that performs a change of basis from the first camera's coordinate system to the second camera's -coordinate system. Note that, in general, t can not be used for this tuple, see the parameter -described below. -@param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and -therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit -length. -@param method Method for computing an essential matrix. -- @ref RANSAC for the RANSAC algorithm. -- @ref LMEDS for the LMedS algorithm. -@param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of -confidence (probability) that the estimated matrix is correct. -@param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar -line in pixels, beyond which the point is considered an outlier and is not used for computing the -final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the -point localization, image resolution, and the image noise. -@param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks -inliers in points1 and points2 for then given essential matrix E. Only these inliers will be used to -recover pose. In the output mask only inliers which pass the cheirality check. - -This function decomposes an essential matrix using @ref decomposeEssentialMat and then verifies -possible pose hypotheses by doing cheirality check. The cheirality check means that the -triangulated 3D points should have positive depth. Some details can be found in @cite Nister03. - -This function can be used to process the output E and mask from @ref findEssentialMat. In this -scenario, points1 and points2 are the same input for findEssentialMat.: -@code - // Example. Estimation of fundamental matrix using the RANSAC algorithm - int point_count = 100; - vector points1(point_count); - vector points2(point_count); - - // initialize the points here ... - for( int i = 0; i < point_count; i++ ) - { - points1[i] = ...; - points2[i] = ...; - } - - // Input: camera calibration of both cameras, for example using intrinsic chessboard calibration. - Mat cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2; - - // Output: Essential matrix, relative rotation and relative translation. - Mat E, R, t, mask; - - recoverPose(points1, points2, cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, E, R, t, mask); -@endcode - */ -CV_EXPORTS_W int recoverPose( InputArray points1, InputArray points2, - InputArray cameraMatrix1, InputArray distCoeffs1, - InputArray cameraMatrix2, InputArray distCoeffs2, - OutputArray E, OutputArray R, OutputArray t, - int method = cv::RANSAC, double prob = 0.999, double threshold = 1.0, - InputOutputArray mask = noArray()); - -/** @brief Recovers the relative camera rotation and the translation from an estimated essential -matrix and the corresponding points in two images, using chirality check. Returns the number of -inliers that pass the check. - -@param E The input essential matrix. -@param points1 Array of N 2D points from the first image. The point coordinates should be -floating-point (single or double precision). -@param points2 Array of the second image points of the same size and format as points1 . -@param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ . -Note that this function assumes that points1 and points2 are feature points from cameras with the -same camera intrinsic matrix. -@param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple -that performs a change of basis from the first camera's coordinate system to the second camera's -coordinate system. Note that, in general, t can not be used for this tuple, see the parameter -described below. -@param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and -therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit -length. -@param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks -inliers in points1 and points2 for the given essential matrix E. Only these inliers will be used to -recover pose. In the output mask only inliers which pass the chirality check. - -This function decomposes an essential matrix using @ref decomposeEssentialMat and then verifies -possible pose hypotheses by doing chirality check. The chirality check means that the -triangulated 3D points should have positive depth. Some details can be found in @cite Nister03. - -This function can be used to process the output E and mask from @ref findEssentialMat. In this -scenario, points1 and points2 are the same input for #findEssentialMat : -@code - // Example. Estimation of fundamental matrix using the RANSAC algorithm - int point_count = 100; - vector points1(point_count); - vector points2(point_count); - - // initialize the points here ... - for( int i = 0; i < point_count; i++ ) - { - points1[i] = ...; - points2[i] = ...; - } - - // cametra matrix with both focal lengths = 1, and principal point = (0, 0) - Mat cameraMatrix = Mat::eye(3, 3, CV_64F); - - Mat E, R, t, mask; - - E = findEssentialMat(points1, points2, cameraMatrix, RANSAC, 0.999, 1.0, mask); - recoverPose(E, points1, points2, cameraMatrix, R, t, mask); -@endcode - */ -CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray points2, - InputArray cameraMatrix, OutputArray R, OutputArray t, - InputOutputArray mask = noArray() ); - -/** @overload -@param E The input essential matrix. -@param points1 Array of N 2D points from the first image. The point coordinates should be -floating-point (single or double precision). -@param points2 Array of the second image points of the same size and format as points1 . -@param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple -that performs a change of basis from the first camera's coordinate system to the second camera's -coordinate system. Note that, in general, t can not be used for this tuple, see the parameter -description below. -@param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and -therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit -length. -@param focal Focal length of the camera. Note that this function assumes that points1 and points2 -are feature points from cameras with same focal length and principal point. -@param pp principal point of the camera. -@param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks -inliers in points1 and points2 for the given essential matrix E. Only these inliers will be used to -recover pose. In the output mask only inliers which pass the chirality check. - -This function differs from the one above that it computes camera intrinsic matrix from focal length and -principal point: - -\f[A = -\begin{bmatrix} -f & 0 & x_{pp} \\ -0 & f & y_{pp} \\ -0 & 0 & 1 -\end{bmatrix}\f] - */ -CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray points2, - OutputArray R, OutputArray t, - double focal = 1.0, Point2d pp = Point2d(0, 0), - InputOutputArray mask = noArray() ); - -/** @overload -@param E The input essential matrix. -@param points1 Array of N 2D points from the first image. The point coordinates should be -floating-point (single or double precision). -@param points2 Array of the second image points of the same size and format as points1. -@param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ . -Note that this function assumes that points1 and points2 are feature points from cameras with the -same camera intrinsic matrix. -@param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple -that performs a change of basis from the first camera's coordinate system to the second camera's -coordinate system. Note that, in general, t can not be used for this tuple, see the parameter -description below. -@param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and -therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit -length. -@param distanceThresh threshold distance which is used to filter out far away points (i.e. infinite -points). -@param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks -inliers in points1 and points2 for the given essential matrix E. Only these inliers will be used to -recover pose. In the output mask only inliers which pass the chirality check. -@param triangulatedPoints 3D points which were reconstructed by triangulation. - -This function differs from the one above that it outputs the triangulated 3D point that are used for -the chirality check. - */ -CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray points2, - InputArray cameraMatrix, OutputArray R, OutputArray t, double distanceThresh, InputOutputArray mask = noArray(), - OutputArray triangulatedPoints = noArray()); - -/** @brief For points in an image of a stereo pair, computes the corresponding epilines in the other image. - -@param points Input points. \f$N \times 1\f$ or \f$1 \times N\f$ matrix of type CV_32FC2 or -vector\ . -@param whichImage Index of the image (1 or 2) that contains the points . -@param F Fundamental matrix that can be estimated using #findFundamentalMat or #stereoRectify . -@param lines Output vector of the epipolar lines corresponding to the points in the other image. -Each line \f$ax + by + c=0\f$ is encoded by 3 numbers \f$(a, b, c)\f$ . - -For every point in one of the two images of a stereo pair, the function finds the equation of the -corresponding epipolar line in the other image. - -From the fundamental matrix definition (see #findFundamentalMat ), line \f$l^{(2)}_i\f$ in the second -image for the point \f$p^{(1)}_i\f$ in the first image (when whichImage=1 ) is computed as: - -\f[l^{(2)}_i = F p^{(1)}_i\f] - -And vice versa, when whichImage=2, \f$l^{(1)}_i\f$ is computed from \f$p^{(2)}_i\f$ as: - -\f[l^{(1)}_i = F^T p^{(2)}_i\f] - -Line coefficients are defined up to a scale. They are normalized so that \f$a_i^2+b_i^2=1\f$ . - */ -CV_EXPORTS_W void computeCorrespondEpilines( InputArray points, int whichImage, - InputArray F, OutputArray lines ); - -/** @brief This function reconstructs 3-dimensional points (in homogeneous coordinates) by using -their observations with a stereo camera. - -@param projMatr1 3x4 projection matrix of the first camera, i.e. this matrix projects 3D points -given in the world's coordinate system into the first image. -@param projMatr2 3x4 projection matrix of the second camera, i.e. this matrix projects 3D points -given in the world's coordinate system into the second image. -@param projPoints1 2xN array of feature points in the first image. In the case of the c++ version, -it can be also a vector of feature points or two-channel matrix of size 1xN or Nx1. -@param projPoints2 2xN array of corresponding points in the second image. In the case of the c++ -version, it can be also a vector of feature points or two-channel matrix of size 1xN or Nx1. -@param points4D 4xN array of reconstructed points in homogeneous coordinates. These points are -returned in the world's coordinate system. - -@note - Keep in mind that all input data should be of float type in order for this function to work. - -@note - If the projection matrices from @ref stereoRectify are used, then the returned points are - represented in the first camera's rectified coordinate system. - -@sa - reprojectImageTo3D - */ -CV_EXPORTS_W void triangulatePoints( InputArray projMatr1, InputArray projMatr2, - InputArray projPoints1, InputArray projPoints2, - OutputArray points4D ); - -/** @brief Refines coordinates of corresponding points. - -@param F 3x3 fundamental matrix. -@param points1 1xN array containing the first set of points. -@param points2 1xN array containing the second set of points. -@param newPoints1 The optimized points1. -@param newPoints2 The optimized points2. - -The function implements the Optimal Triangulation Method (see Multiple View Geometry @cite HartleyZ00 for details). -For each given point correspondence points1[i] \<-\> points2[i], and a fundamental matrix F, it -computes the corrected correspondences newPoints1[i] \<-\> newPoints2[i] that minimize the geometric -error \f$d(points1[i], newPoints1[i])^2 + d(points2[i],newPoints2[i])^2\f$ (where \f$d(a,b)\f$ is the -geometric distance between points \f$a\f$ and \f$b\f$ ) subject to the epipolar constraint -\f$newPoints2^T \cdot F \cdot newPoints1 = 0\f$ . - */ -CV_EXPORTS_W void correctMatches( InputArray F, InputArray points1, InputArray points2, - OutputArray newPoints1, OutputArray newPoints2 ); - -/** @brief Filters off small noise blobs (speckles) in the disparity map - -@param img The input 16-bit signed disparity image -@param newVal The disparity value used to paint-off the speckles -@param maxSpeckleSize The maximum speckle size to consider it a speckle. Larger blobs are not -affected by the algorithm -@param maxDiff Maximum difference between neighbor disparity pixels to put them into the same -blob. Note that since StereoBM, StereoSGBM and may be other algorithms return a fixed-point -disparity map, where disparity values are multiplied by 16, this scale factor should be taken into -account when specifying this parameter value. -@param buf The optional temporary buffer to avoid memory allocation within the function. - */ -CV_EXPORTS_W void filterSpeckles( InputOutputArray img, double newVal, - int maxSpeckleSize, double maxDiff, - InputOutputArray buf = noArray() ); - -//! computes valid disparity ROI from the valid ROIs of the rectified images (that are returned by #stereoRectify) -CV_EXPORTS_W Rect getValidDisparityROI( Rect roi1, Rect roi2, - int minDisparity, int numberOfDisparities, - int blockSize ); - -//! validates disparity using the left-right check. The matrix "cost" should be computed by the stereo correspondence algorithm -CV_EXPORTS_W void validateDisparity( InputOutputArray disparity, InputArray cost, - int minDisparity, int numberOfDisparities, - int disp12MaxDisp = 1 ); - -/** @brief Reprojects a disparity image to 3D space. - -@param disparity Input single-channel 8-bit unsigned, 16-bit signed, 32-bit signed or 32-bit -floating-point disparity image. The values of 8-bit / 16-bit signed formats are assumed to have no -fractional bits. If the disparity is 16-bit signed format, as computed by @ref StereoBM or -@ref StereoSGBM and maybe other algorithms, it should be divided by 16 (and scaled to float) before -being used here. -@param _3dImage Output 3-channel floating-point image of the same size as disparity. Each element of -_3dImage(x,y) contains 3D coordinates of the point (x,y) computed from the disparity map. If one -uses Q obtained by @ref stereoRectify, then the returned points are represented in the first -camera's rectified coordinate system. -@param Q \f$4 \times 4\f$ perspective transformation matrix that can be obtained with -@ref stereoRectify. -@param handleMissingValues Indicates, whether the function should handle missing values (i.e. -points where the disparity was not computed). If handleMissingValues=true, then pixels with the -minimal disparity that corresponds to the outliers (see StereoMatcher::compute ) are transformed -to 3D points with a very large Z value (currently set to 10000). -@param ddepth The optional output array depth. If it is -1, the output image will have CV_32F -depth. ddepth can also be set to CV_16S, CV_32S or CV_32F. - -The function transforms a single-channel disparity map to a 3-channel image representing a 3D -surface. That is, for each pixel (x,y) and the corresponding disparity d=disparity(x,y) , it -computes: - -\f[\begin{bmatrix} -X \\ -Y \\ -Z \\ -W -\end{bmatrix} = Q \begin{bmatrix} -x \\ -y \\ -\texttt{disparity} (x,y) \\ -1 -\end{bmatrix}.\f] - -@sa - To reproject a sparse set of points {(x,y,d),...} to 3D space, use perspectiveTransform. - */ -CV_EXPORTS_W void reprojectImageTo3D( InputArray disparity, - OutputArray _3dImage, InputArray Q, - bool handleMissingValues = false, - int ddepth = -1 ); - -/** @brief Calculates the Sampson Distance between two points. - -The function cv::sampsonDistance calculates and returns the first order approximation of the geometric error as: -\f[ -sd( \texttt{pt1} , \texttt{pt2} )= -\frac{(\texttt{pt2}^t \cdot \texttt{F} \cdot \texttt{pt1})^2} -{((\texttt{F} \cdot \texttt{pt1})(0))^2 + -((\texttt{F} \cdot \texttt{pt1})(1))^2 + -((\texttt{F}^t \cdot \texttt{pt2})(0))^2 + -((\texttt{F}^t \cdot \texttt{pt2})(1))^2} -\f] -The fundamental matrix may be calculated using the #findFundamentalMat function. See @cite HartleyZ00 11.4.3 for details. -@param pt1 first homogeneous 2d point -@param pt2 second homogeneous 2d point -@param F fundamental matrix -@return The computed Sampson distance. -*/ -CV_EXPORTS_W double sampsonDistance(InputArray pt1, InputArray pt2, InputArray F); - -/** @brief Computes an optimal affine transformation between two 3D point sets. - -It computes -\f[ -\begin{bmatrix} -x\\ -y\\ -z\\ -\end{bmatrix} -= -\begin{bmatrix} -a_{11} & a_{12} & a_{13}\\ -a_{21} & a_{22} & a_{23}\\ -a_{31} & a_{32} & a_{33}\\ -\end{bmatrix} -\begin{bmatrix} -X\\ -Y\\ -Z\\ -\end{bmatrix} -+ -\begin{bmatrix} -b_1\\ -b_2\\ -b_3\\ -\end{bmatrix} -\f] - -@param src First input 3D point set containing \f$(X,Y,Z)\f$. -@param dst Second input 3D point set containing \f$(x,y,z)\f$. -@param out Output 3D affine transformation matrix \f$3 \times 4\f$ of the form -\f[ -\begin{bmatrix} -a_{11} & a_{12} & a_{13} & b_1\\ -a_{21} & a_{22} & a_{23} & b_2\\ -a_{31} & a_{32} & a_{33} & b_3\\ -\end{bmatrix} -\f] -@param inliers Output vector indicating which points are inliers (1-inlier, 0-outlier). -@param ransacThreshold Maximum reprojection error in the RANSAC algorithm to consider a point as -an inlier. -@param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything -between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation -significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation. - -The function estimates an optimal 3D affine transformation between two 3D point sets using the -RANSAC algorithm. - */ -CV_EXPORTS_W int estimateAffine3D(InputArray src, InputArray dst, - OutputArray out, OutputArray inliers, - double ransacThreshold = 3, double confidence = 0.99); - -/** @brief Computes an optimal affine transformation between two 3D point sets. - -It computes \f$R,s,t\f$ minimizing \f$\sum{i} dst_i - c \cdot R \cdot src_i \f$ -where \f$R\f$ is a 3x3 rotation matrix, \f$t\f$ is a 3x1 translation vector and \f$s\f$ is a -scalar size value. This is an implementation of the algorithm by Umeyama \cite umeyama1991least . -The estimated affine transform has a homogeneous scale which is a subclass of affine -transformations with 7 degrees of freedom. The paired point sets need to comprise at least 3 -points each. - -@param src First input 3D point set. -@param dst Second input 3D point set. -@param scale If null is passed, the scale parameter c will be assumed to be 1.0. -Else the pointed-to variable will be set to the optimal scale. -@param force_rotation If true, the returned rotation will never be a reflection. -This might be unwanted, e.g. when optimizing a transform between a right- and a -left-handed coordinate system. -@return 3D affine transformation matrix \f$3 \times 4\f$ of the form -\f[T = -\begin{bmatrix} -R & t\\ -\end{bmatrix} -\f] - - */ -CV_EXPORTS_W cv::Mat estimateAffine3D(InputArray src, InputArray dst, - CV_OUT double* scale = nullptr, bool force_rotation = true); - -/** @brief Computes an optimal translation between two 3D point sets. - * - * It computes - * \f[ - * \begin{bmatrix} - * x\\ - * y\\ - * z\\ - * \end{bmatrix} - * = - * \begin{bmatrix} - * X\\ - * Y\\ - * Z\\ - * \end{bmatrix} - * + - * \begin{bmatrix} - * b_1\\ - * b_2\\ - * b_3\\ - * \end{bmatrix} - * \f] - * - * @param src First input 3D point set containing \f$(X,Y,Z)\f$. - * @param dst Second input 3D point set containing \f$(x,y,z)\f$. - * @param out Output 3D translation vector \f$3 \times 1\f$ of the form - * \f[ - * \begin{bmatrix} - * b_1 \\ - * b_2 \\ - * b_3 \\ - * \end{bmatrix} - * \f] - * @param inliers Output vector indicating which points are inliers (1-inlier, 0-outlier). - * @param ransacThreshold Maximum reprojection error in the RANSAC algorithm to consider a point as - * an inlier. - * @param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything - * between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation - * significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation. - * - * The function estimates an optimal 3D translation between two 3D point sets using the - * RANSAC algorithm. - * */ -CV_EXPORTS_W int estimateTranslation3D(InputArray src, InputArray dst, - OutputArray out, OutputArray inliers, - double ransacThreshold = 3, double confidence = 0.99); - -/** @brief Computes an optimal affine transformation between two 2D point sets. - -It computes -\f[ -\begin{bmatrix} -x\\ -y\\ -\end{bmatrix} -= -\begin{bmatrix} -a_{11} & a_{12}\\ -a_{21} & a_{22}\\ -\end{bmatrix} -\begin{bmatrix} -X\\ -Y\\ -\end{bmatrix} -+ -\begin{bmatrix} -b_1\\ -b_2\\ -\end{bmatrix} -\f] - -@param from First input 2D point set containing \f$(X,Y)\f$. -@param to Second input 2D point set containing \f$(x,y)\f$. -@param inliers Output vector indicating which points are inliers (1-inlier, 0-outlier). -@param method Robust method used to compute transformation. The following methods are possible: -- @ref RANSAC - RANSAC-based robust method -- @ref LMEDS - Least-Median robust method -RANSAC is the default method. -@param ransacReprojThreshold Maximum reprojection error in the RANSAC algorithm to consider -a point as an inlier. Applies only to RANSAC. -@param maxIters The maximum number of robust method iterations. -@param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything -between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation -significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation. -@param refineIters Maximum number of iterations of refining algorithm (Levenberg-Marquardt). -Passing 0 will disable refining, so the output matrix will be output of robust method. - -@return Output 2D affine transformation matrix \f$2 \times 3\f$ or empty matrix if transformation -could not be estimated. The returned matrix has the following form: -\f[ -\begin{bmatrix} -a_{11} & a_{12} & b_1\\ -a_{21} & a_{22} & b_2\\ -\end{bmatrix} -\f] - -The function estimates an optimal 2D affine transformation between two 2D point sets using the -selected robust algorithm. - -The computed transformation is then refined further (using only inliers) with the -Levenberg-Marquardt method to reduce the re-projection error even more. - -@note -The RANSAC method can handle practically any ratio of outliers but needs a threshold to -distinguish inliers from outliers. The method LMeDS does not need any threshold but it works -correctly only when there are more than 50% of inliers. - -@sa estimateAffinePartial2D, getAffineTransform -*/ -CV_EXPORTS_W cv::Mat estimateAffine2D(InputArray from, InputArray to, OutputArray inliers = noArray(), - int method = RANSAC, double ransacReprojThreshold = 3, - size_t maxIters = 2000, double confidence = 0.99, - size_t refineIters = 10); - - -CV_EXPORTS_W cv::Mat estimateAffine2D(InputArray pts1, InputArray pts2, OutputArray inliers, - const UsacParams ¶ms); - -/** @brief Computes an optimal limited affine transformation with 4 degrees of freedom between -two 2D point sets. - -@param from First input 2D point set. -@param to Second input 2D point set. -@param inliers Output vector indicating which points are inliers. -@param method Robust method used to compute transformation. The following methods are possible: -- @ref RANSAC - RANSAC-based robust method -- @ref LMEDS - Least-Median robust method -RANSAC is the default method. -@param ransacReprojThreshold Maximum reprojection error in the RANSAC algorithm to consider -a point as an inlier. Applies only to RANSAC. -@param maxIters The maximum number of robust method iterations. -@param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything -between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation -significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation. -@param refineIters Maximum number of iterations of refining algorithm (Levenberg-Marquardt). -Passing 0 will disable refining, so the output matrix will be output of robust method. - -@return Output 2D affine transformation (4 degrees of freedom) matrix \f$2 \times 3\f$ or -empty matrix if transformation could not be estimated. - -The function estimates an optimal 2D affine transformation with 4 degrees of freedom limited to -combinations of translation, rotation, and uniform scaling. Uses the selected algorithm for robust -estimation. - -The computed transformation is then refined further (using only inliers) with the -Levenberg-Marquardt method to reduce the re-projection error even more. - -Estimated transformation matrix is: -\f[ \begin{bmatrix} \cos(\theta) \cdot s & -\sin(\theta) \cdot s & t_x \\ - \sin(\theta) \cdot s & \cos(\theta) \cdot s & t_y -\end{bmatrix} \f] -Where \f$ \theta \f$ is the rotation angle, \f$ s \f$ the scaling factor and \f$ t_x, t_y \f$ are -translations in \f$ x, y \f$ axes respectively. - -@note -The RANSAC method can handle practically any ratio of outliers but need a threshold to -distinguish inliers from outliers. The method LMeDS does not need any threshold but it works -correctly only when there are more than 50% of inliers. - -@sa estimateAffine2D, getAffineTransform -*/ -CV_EXPORTS_W cv::Mat estimateAffinePartial2D(InputArray from, InputArray to, OutputArray inliers = noArray(), - int method = RANSAC, double ransacReprojThreshold = 3, - size_t maxIters = 2000, double confidence = 0.99, - size_t refineIters = 10); - -/** @example samples/cpp/tutorial_code/features2D/Homography/decompose_homography.cpp -An example program with homography decomposition. - -Check @ref tutorial_homography "the corresponding tutorial" for more details. -*/ - -/** @brief Decompose a homography matrix to rotation(s), translation(s) and plane normal(s). - -@param H The input homography matrix between two images. -@param K The input camera intrinsic matrix. -@param rotations Array of rotation matrices. -@param translations Array of translation matrices. -@param normals Array of plane normal matrices. - -This function extracts relative camera motion between two views of a planar object and returns up to -four mathematical solution tuples of rotation, translation, and plane normal. The decomposition of -the homography matrix H is described in detail in @cite Malis2007. - -If the homography H, induced by the plane, gives the constraint -\f[s_i \vecthree{x'_i}{y'_i}{1} \sim H \vecthree{x_i}{y_i}{1}\f] on the source image points -\f$p_i\f$ and the destination image points \f$p'_i\f$, then the tuple of rotations[k] and -translations[k] is a change of basis from the source camera's coordinate system to the destination -camera's coordinate system. However, by decomposing H, one can only get the translation normalized -by the (typically unknown) depth of the scene, i.e. its direction but with normalized length. - -If point correspondences are available, at least two solutions may further be invalidated, by -applying positive depth constraint, i.e. all points must be in front of the camera. - */ -CV_EXPORTS_W int decomposeHomographyMat(InputArray H, - InputArray K, - OutputArrayOfArrays rotations, - OutputArrayOfArrays translations, - OutputArrayOfArrays normals); - -/** @brief Filters homography decompositions based on additional information. - -@param rotations Vector of rotation matrices. -@param normals Vector of plane normal matrices. -@param beforePoints Vector of (rectified) visible reference points before the homography is applied -@param afterPoints Vector of (rectified) visible reference points after the homography is applied -@param possibleSolutions Vector of int indices representing the viable solution set after filtering -@param pointsMask optional Mat/Vector of 8u type representing the mask for the inliers as given by the #findHomography function - -This function is intended to filter the output of the #decomposeHomographyMat based on additional -information as described in @cite Malis2007 . The summary of the method: the #decomposeHomographyMat function -returns 2 unique solutions and their "opposites" for a total of 4 solutions. If we have access to the -sets of points visible in the camera frame before and after the homography transformation is applied, -we can determine which are the true potential solutions and which are the opposites by verifying which -homographies are consistent with all visible reference points being in front of the camera. The inputs -are left unchanged; the filtered solution set is returned as indices into the existing one. - -*/ -CV_EXPORTS_W void filterHomographyDecompByVisibleRefpoints(InputArrayOfArrays rotations, - InputArrayOfArrays normals, - InputArray beforePoints, - InputArray afterPoints, - OutputArray possibleSolutions, - InputArray pointsMask = noArray()); - -/** @brief The base class for stereo correspondence algorithms. - */ -class CV_EXPORTS_W StereoMatcher : public Algorithm -{ -public: - enum { DISP_SHIFT = 4, - DISP_SCALE = (1 << DISP_SHIFT) - }; - - /** @brief Computes disparity map for the specified stereo pair - - @param left Left 8-bit single-channel image. - @param right Right image of the same size and the same type as the left one. - @param disparity Output disparity map. It has the same size as the input images. Some algorithms, - like StereoBM or StereoSGBM compute 16-bit fixed-point disparity map (where each disparity value - has 4 fractional bits), whereas other algorithms output 32-bit floating-point disparity map. - */ - CV_WRAP virtual void compute( InputArray left, InputArray right, - OutputArray disparity ) = 0; - - CV_WRAP virtual int getMinDisparity() const = 0; - CV_WRAP virtual void setMinDisparity(int minDisparity) = 0; - - CV_WRAP virtual int getNumDisparities() const = 0; - CV_WRAP virtual void setNumDisparities(int numDisparities) = 0; - - CV_WRAP virtual int getBlockSize() const = 0; - CV_WRAP virtual void setBlockSize(int blockSize) = 0; - - CV_WRAP virtual int getSpeckleWindowSize() const = 0; - CV_WRAP virtual void setSpeckleWindowSize(int speckleWindowSize) = 0; - - CV_WRAP virtual int getSpeckleRange() const = 0; - CV_WRAP virtual void setSpeckleRange(int speckleRange) = 0; - - CV_WRAP virtual int getDisp12MaxDiff() const = 0; - CV_WRAP virtual void setDisp12MaxDiff(int disp12MaxDiff) = 0; -}; - - -/** @brief Class for computing stereo correspondence using the block matching algorithm, introduced and -contributed to OpenCV by K. Konolige. - */ -class CV_EXPORTS_W StereoBM : public StereoMatcher -{ -public: - enum { PREFILTER_NORMALIZED_RESPONSE = 0, - PREFILTER_XSOBEL = 1 - }; - - CV_WRAP virtual int getPreFilterType() const = 0; - CV_WRAP virtual void setPreFilterType(int preFilterType) = 0; - - CV_WRAP virtual int getPreFilterSize() const = 0; - CV_WRAP virtual void setPreFilterSize(int preFilterSize) = 0; - - CV_WRAP virtual int getPreFilterCap() const = 0; - CV_WRAP virtual void setPreFilterCap(int preFilterCap) = 0; - - CV_WRAP virtual int getTextureThreshold() const = 0; - CV_WRAP virtual void setTextureThreshold(int textureThreshold) = 0; - - CV_WRAP virtual int getUniquenessRatio() const = 0; - CV_WRAP virtual void setUniquenessRatio(int uniquenessRatio) = 0; - - CV_WRAP virtual int getSmallerBlockSize() const = 0; - CV_WRAP virtual void setSmallerBlockSize(int blockSize) = 0; - - CV_WRAP virtual Rect getROI1() const = 0; - CV_WRAP virtual void setROI1(Rect roi1) = 0; - - CV_WRAP virtual Rect getROI2() const = 0; - CV_WRAP virtual void setROI2(Rect roi2) = 0; - - /** @brief Creates StereoBM object - - @param numDisparities the disparity search range. For each pixel algorithm will find the best - disparity from 0 (default minimum disparity) to numDisparities. The search range can then be - shifted by changing the minimum disparity. - @param blockSize the linear size of the blocks compared by the algorithm. The size should be odd - (as the block is centered at the current pixel). Larger block size implies smoother, though less - accurate disparity map. Smaller block size gives more detailed disparity map, but there is higher - chance for algorithm to find a wrong correspondence. - - The function create StereoBM object. You can then call StereoBM::compute() to compute disparity for - a specific stereo pair. - */ - CV_WRAP static Ptr create(int numDisparities = 0, int blockSize = 21); -}; - -/** @brief The class implements the modified H. Hirschmuller algorithm @cite HH08 that differs from the original -one as follows: - -- By default, the algorithm is single-pass, which means that you consider only 5 directions -instead of 8. Set mode=StereoSGBM::MODE_HH in createStereoSGBM to run the full variant of the -algorithm but beware that it may consume a lot of memory. -- The algorithm matches blocks, not individual pixels. Though, setting blockSize=1 reduces the -blocks to single pixels. -- Mutual information cost function is not implemented. Instead, a simpler Birchfield-Tomasi -sub-pixel metric from @cite BT98 is used. Though, the color images are supported as well. -- Some pre- and post- processing steps from K. Konolige algorithm StereoBM are included, for -example: pre-filtering (StereoBM::PREFILTER_XSOBEL type) and post-filtering (uniqueness -check, quadratic interpolation and speckle filtering). - -@note - - (Python) An example illustrating the use of the StereoSGBM matching algorithm can be found - at opencv_source_code/samples/python/stereo_match.py - */ -class CV_EXPORTS_W StereoSGBM : public StereoMatcher -{ -public: - enum - { - MODE_SGBM = 0, - MODE_HH = 1, - MODE_SGBM_3WAY = 2, - MODE_HH4 = 3 - }; - - CV_WRAP virtual int getPreFilterCap() const = 0; - CV_WRAP virtual void setPreFilterCap(int preFilterCap) = 0; - - CV_WRAP virtual int getUniquenessRatio() const = 0; - CV_WRAP virtual void setUniquenessRatio(int uniquenessRatio) = 0; - - CV_WRAP virtual int getP1() const = 0; - CV_WRAP virtual void setP1(int P1) = 0; - - CV_WRAP virtual int getP2() const = 0; - CV_WRAP virtual void setP2(int P2) = 0; - - CV_WRAP virtual int getMode() const = 0; - CV_WRAP virtual void setMode(int mode) = 0; - - /** @brief Creates StereoSGBM object - - @param minDisparity Minimum possible disparity value. Normally, it is zero but sometimes - rectification algorithms can shift images, so this parameter needs to be adjusted accordingly. - @param numDisparities Maximum disparity minus minimum disparity. The value is always greater than - zero. In the current implementation, this parameter must be divisible by 16. - @param blockSize Matched block size. It must be an odd number \>=1 . Normally, it should be - somewhere in the 3..11 range. - @param P1 The first parameter controlling the disparity smoothness. See below. - @param P2 The second parameter controlling the disparity smoothness. The larger the values are, - the smoother the disparity is. P1 is the penalty on the disparity change by plus or minus 1 - between neighbor pixels. P2 is the penalty on the disparity change by more than 1 between neighbor - pixels. The algorithm requires P2 \> P1 . See stereo_match.cpp sample where some reasonably good - P1 and P2 values are shown (like 8\*number_of_image_channels\*blockSize\*blockSize and - 32\*number_of_image_channels\*blockSize\*blockSize , respectively). - @param disp12MaxDiff Maximum allowed difference (in integer pixel units) in the left-right - disparity check. Set it to a non-positive value to disable the check. - @param preFilterCap Truncation value for the prefiltered image pixels. The algorithm first - computes x-derivative at each pixel and clips its value by [-preFilterCap, preFilterCap] interval. - The result values are passed to the Birchfield-Tomasi pixel cost function. - @param uniquenessRatio Margin in percentage by which the best (minimum) computed cost function - value should "win" the second best value to consider the found match correct. Normally, a value - within the 5-15 range is good enough. - @param speckleWindowSize Maximum size of smooth disparity regions to consider their noise speckles - and invalidate. Set it to 0 to disable speckle filtering. Otherwise, set it somewhere in the - 50-200 range. - @param speckleRange Maximum disparity variation within each connected component. If you do speckle - filtering, set the parameter to a positive value, it will be implicitly multiplied by 16. - Normally, 1 or 2 is good enough. - @param mode Set it to StereoSGBM::MODE_HH to run the full-scale two-pass dynamic programming - algorithm. It will consume O(W\*H\*numDisparities) bytes, which is large for 640x480 stereo and - huge for HD-size pictures. By default, it is set to false . - - The first constructor initializes StereoSGBM with all the default parameters. So, you only have to - set StereoSGBM::numDisparities at minimum. The second constructor enables you to set each parameter - to a custom value. - */ - CV_WRAP static Ptr create(int minDisparity = 0, int numDisparities = 16, int blockSize = 3, - int P1 = 0, int P2 = 0, int disp12MaxDiff = 0, - int preFilterCap = 0, int uniquenessRatio = 0, - int speckleWindowSize = 0, int speckleRange = 0, - int mode = StereoSGBM::MODE_SGBM); -}; - - -//! cv::undistort mode -enum UndistortTypes -{ - PROJ_SPHERICAL_ORTHO = 0, - PROJ_SPHERICAL_EQRECT = 1 -}; - -/** @brief Transforms an image to compensate for lens distortion. - -The function transforms an image to compensate radial and tangential lens distortion. - -The function is simply a combination of #initUndistortRectifyMap (with unity R ) and #remap -(with bilinear interpolation). See the former function for details of the transformation being -performed. - -Those pixels in the destination image, for which there is no correspondent pixels in the source -image, are filled with zeros (black color). - -A particular subset of the source image that will be visible in the corrected image can be regulated -by newCameraMatrix. You can use #getOptimalNewCameraMatrix to compute the appropriate -newCameraMatrix depending on your requirements. - -The camera matrix and the distortion parameters can be determined using #calibrateCamera. If -the resolution of images is different from the resolution used at the calibration stage, \f$f_x, -f_y, c_x\f$ and \f$c_y\f$ need to be scaled accordingly, while the distortion coefficients remain -the same. - -@param src Input (distorted) image. -@param dst Output (corrected) image that has the same size and type as src . -@param cameraMatrix Input camera matrix \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . -@param distCoeffs Input vector of distortion coefficients -\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ -of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. -@param newCameraMatrix Camera matrix of the distorted image. By default, it is the same as -cameraMatrix but you may additionally scale and shift the result by using a different matrix. - */ -CV_EXPORTS_W void undistort( InputArray src, OutputArray dst, - InputArray cameraMatrix, - InputArray distCoeffs, - InputArray newCameraMatrix = noArray() ); - -/** @brief Computes the undistortion and rectification transformation map. - -The function computes the joint undistortion and rectification transformation and represents the -result in the form of maps for #remap. The undistorted image looks like original, as if it is -captured with a camera using the camera matrix =newCameraMatrix and zero distortion. In case of a -monocular camera, newCameraMatrix is usually equal to cameraMatrix, or it can be computed by -#getOptimalNewCameraMatrix for a better control over scaling. In case of a stereo camera, -newCameraMatrix is normally set to P1 or P2 computed by #stereoRectify . - -Also, this new camera is oriented differently in the coordinate space, according to R. That, for -example, helps to align two heads of a stereo camera so that the epipolar lines on both images -become horizontal and have the same y- coordinate (in case of a horizontally aligned stereo camera). - -The function actually builds the maps for the inverse mapping algorithm that is used by #remap. That -is, for each pixel \f$(u, v)\f$ in the destination (corrected and rectified) image, the function -computes the corresponding coordinates in the source image (that is, in the original image from -camera). The following process is applied: -\f[ -\begin{array}{l} -x \leftarrow (u - {c'}_x)/{f'}_x \\ -y \leftarrow (v - {c'}_y)/{f'}_y \\ -{[X\,Y\,W]} ^T \leftarrow R^{-1}*[x \, y \, 1]^T \\ -x' \leftarrow X/W \\ -y' \leftarrow Y/W \\ -r^2 \leftarrow x'^2 + y'^2 \\ -x'' \leftarrow x' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} -+ 2p_1 x' y' + p_2(r^2 + 2 x'^2) + s_1 r^2 + s_2 r^4\\ -y'' \leftarrow y' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} -+ p_1 (r^2 + 2 y'^2) + 2 p_2 x' y' + s_3 r^2 + s_4 r^4 \\ -s\vecthree{x'''}{y'''}{1} = -\vecthreethree{R_{33}(\tau_x, \tau_y)}{0}{-R_{13}((\tau_x, \tau_y)} -{0}{R_{33}(\tau_x, \tau_y)}{-R_{23}(\tau_x, \tau_y)} -{0}{0}{1} R(\tau_x, \tau_y) \vecthree{x''}{y''}{1}\\ -map_x(u,v) \leftarrow x''' f_x + c_x \\ -map_y(u,v) \leftarrow y''' f_y + c_y -\end{array} -\f] -where \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ -are the distortion coefficients. - -In case of a stereo camera, this function is called twice: once for each camera head, after -#stereoRectify, which in its turn is called after #stereoCalibrate. But if the stereo camera -was not calibrated, it is still possible to compute the rectification transformations directly from -the fundamental matrix using #stereoRectifyUncalibrated. For each camera, the function computes -homography H as the rectification transformation in a pixel domain, not a rotation matrix R in 3D -space. R can be computed from H as -\f[\texttt{R} = \texttt{cameraMatrix} ^{-1} \cdot \texttt{H} \cdot \texttt{cameraMatrix}\f] -where cameraMatrix can be chosen arbitrarily. - -@param cameraMatrix Input camera matrix \f$A=\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . -@param distCoeffs Input vector of distortion coefficients -\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ -of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. -@param R Optional rectification transformation in the object space (3x3 matrix). R1 or R2 , -computed by #stereoRectify can be passed here. If the matrix is empty, the identity transformation -is assumed. In #initUndistortRectifyMap R assumed to be an identity matrix. -@param newCameraMatrix New camera matrix \f$A'=\vecthreethree{f_x'}{0}{c_x'}{0}{f_y'}{c_y'}{0}{0}{1}\f$. -@param size Undistorted image size. -@param m1type Type of the first output map that can be CV_32FC1, CV_32FC2 or CV_16SC2, see #convertMaps -@param map1 The first output map. -@param map2 The second output map. - */ -CV_EXPORTS_W -void initUndistortRectifyMap(InputArray cameraMatrix, InputArray distCoeffs, - InputArray R, InputArray newCameraMatrix, - Size size, int m1type, OutputArray map1, OutputArray map2); - -/** @brief Computes the projection and inverse-rectification transformation map. In essense, this is the inverse of -#initUndistortRectifyMap to accomodate stereo-rectification of projectors ('inverse-cameras') in projector-camera pairs. - -The function computes the joint projection and inverse rectification transformation and represents the -result in the form of maps for #remap. The projected image looks like a distorted version of the original which, -once projected by a projector, should visually match the original. In case of a monocular camera, newCameraMatrix -is usually equal to cameraMatrix, or it can be computed by -#getOptimalNewCameraMatrix for a better control over scaling. In case of a projector-camera pair, -newCameraMatrix is normally set to P1 or P2 computed by #stereoRectify . - -The projector is oriented differently in the coordinate space, according to R. In case of projector-camera pairs, -this helps align the projector (in the same manner as #initUndistortRectifyMap for the camera) to create a stereo-rectified pair. This -allows epipolar lines on both images to become horizontal and have the same y-coordinate (in case of a horizontally aligned projector-camera pair). - -The function builds the maps for the inverse mapping algorithm that is used by #remap. That -is, for each pixel \f$(u, v)\f$ in the destination (projected and inverse-rectified) image, the function -computes the corresponding coordinates in the source image (that is, in the original digital image). The following process is applied: - -\f[ -\begin{array}{l} -\text{newCameraMatrix}\\ -x \leftarrow (u - {c'}_x)/{f'}_x \\ -y \leftarrow (v - {c'}_y)/{f'}_y \\ - -\\\text{Undistortion} -\\\scriptsize{\textit{though equation shown is for radial undistortion, function implements cv::undistortPoints()}}\\ -r^2 \leftarrow x^2 + y^2 \\ -\theta \leftarrow \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6}\\ -x' \leftarrow \frac{x}{\theta} \\ -y' \leftarrow \frac{y}{\theta} \\ - -\\\text{Rectification}\\ -{[X\,Y\,W]} ^T \leftarrow R*[x' \, y' \, 1]^T \\ -x'' \leftarrow X/W \\ -y'' \leftarrow Y/W \\ - -\\\text{cameraMatrix}\\ -map_x(u,v) \leftarrow x'' f_x + c_x \\ -map_y(u,v) \leftarrow y'' f_y + c_y -\end{array} -\f] -where \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ -are the distortion coefficients vector distCoeffs. - -In case of a stereo-rectified projector-camera pair, this function is called for the projector while #initUndistortRectifyMap is called for the camera head. -This is done after #stereoRectify, which in turn is called after #stereoCalibrate. If the projector-camera pair -is not calibrated, it is still possible to compute the rectification transformations directly from -the fundamental matrix using #stereoRectifyUncalibrated. For the projector and camera, the function computes -homography H as the rectification transformation in a pixel domain, not a rotation matrix R in 3D -space. R can be computed from H as -\f[\texttt{R} = \texttt{cameraMatrix} ^{-1} \cdot \texttt{H} \cdot \texttt{cameraMatrix}\f] -where cameraMatrix can be chosen arbitrarily. - -@param cameraMatrix Input camera matrix \f$A=\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . -@param distCoeffs Input vector of distortion coefficients -\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ -of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. -@param R Optional rectification transformation in the object space (3x3 matrix). R1 or R2, -computed by #stereoRectify can be passed here. If the matrix is empty, the identity transformation -is assumed. -@param newCameraMatrix New camera matrix \f$A'=\vecthreethree{f_x'}{0}{c_x'}{0}{f_y'}{c_y'}{0}{0}{1}\f$. -@param size Distorted image size. -@param m1type Type of the first output map. Can be CV_32FC1, CV_32FC2 or CV_16SC2, see #convertMaps -@param map1 The first output map for #remap. -@param map2 The second output map for #remap. - */ -CV_EXPORTS_W -void initInverseRectificationMap( InputArray cameraMatrix, InputArray distCoeffs, - InputArray R, InputArray newCameraMatrix, - const Size& size, int m1type, OutputArray map1, OutputArray map2 ); - -//! initializes maps for #remap for wide-angle -CV_EXPORTS -float initWideAngleProjMap(InputArray cameraMatrix, InputArray distCoeffs, - Size imageSize, int destImageWidth, - int m1type, OutputArray map1, OutputArray map2, - enum UndistortTypes projType = PROJ_SPHERICAL_EQRECT, double alpha = 0); -static inline -float initWideAngleProjMap(InputArray cameraMatrix, InputArray distCoeffs, - Size imageSize, int destImageWidth, - int m1type, OutputArray map1, OutputArray map2, - int projType, double alpha = 0) -{ - return initWideAngleProjMap(cameraMatrix, distCoeffs, imageSize, destImageWidth, - m1type, map1, map2, (UndistortTypes)projType, alpha); -} - -/** @brief Returns the default new camera matrix. - -The function returns the camera matrix that is either an exact copy of the input cameraMatrix (when -centerPrinicipalPoint=false ), or the modified one (when centerPrincipalPoint=true). - -In the latter case, the new camera matrix will be: - -\f[\begin{bmatrix} f_x && 0 && ( \texttt{imgSize.width} -1)*0.5 \\ 0 && f_y && ( \texttt{imgSize.height} -1)*0.5 \\ 0 && 0 && 1 \end{bmatrix} ,\f] - -where \f$f_x\f$ and \f$f_y\f$ are \f$(0,0)\f$ and \f$(1,1)\f$ elements of cameraMatrix, respectively. - -By default, the undistortion functions in OpenCV (see #initUndistortRectifyMap, #undistort) do not -move the principal point. However, when you work with stereo, it is important to move the principal -points in both views to the same y-coordinate (which is required by most of stereo correspondence -algorithms), and may be to the same x-coordinate too. So, you can form the new camera matrix for -each view where the principal points are located at the center. - -@param cameraMatrix Input camera matrix. -@param imgsize Camera view image size in pixels. -@param centerPrincipalPoint Location of the principal point in the new camera matrix. The -parameter indicates whether this location should be at the image center or not. - */ -CV_EXPORTS_W -Mat getDefaultNewCameraMatrix(InputArray cameraMatrix, Size imgsize = Size(), - bool centerPrincipalPoint = false); - -/** @brief Computes the ideal point coordinates from the observed point coordinates. - -The function is similar to #undistort and #initUndistortRectifyMap but it operates on a -sparse set of points instead of a raster image. Also the function performs a reverse transformation -to #projectPoints. In case of a 3D object, it does not reconstruct its 3D coordinates, but for a -planar object, it does, up to a translation vector, if the proper R is specified. - -For each observed point coordinate \f$(u, v)\f$ the function computes: -\f[ -\begin{array}{l} -x^{"} \leftarrow (u - c_x)/f_x \\ -y^{"} \leftarrow (v - c_y)/f_y \\ -(x',y') = undistort(x^{"},y^{"}, \texttt{distCoeffs}) \\ -{[X\,Y\,W]} ^T \leftarrow R*[x' \, y' \, 1]^T \\ -x \leftarrow X/W \\ -y \leftarrow Y/W \\ -\text{only performed if P is specified:} \\ -u' \leftarrow x {f'}_x + {c'}_x \\ -v' \leftarrow y {f'}_y + {c'}_y -\end{array} -\f] - -where *undistort* is an approximate iterative algorithm that estimates the normalized original -point coordinates out of the normalized distorted point coordinates ("normalized" means that the -coordinates do not depend on the camera matrix). - -The function can be used for both a stereo camera head or a monocular camera (when R is empty). -@param src Observed point coordinates, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel (CV_32FC2 or CV_64FC2) (or -vector\ ). -@param dst Output ideal point coordinates (1xN/Nx1 2-channel or vector\ ) after undistortion and reverse perspective -transformation. If matrix P is identity or omitted, dst will contain normalized point coordinates. -@param cameraMatrix Camera matrix \f$\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . -@param distCoeffs Input vector of distortion coefficients -\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ -of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. -@param R Rectification transformation in the object space (3x3 matrix). R1 or R2 computed by -#stereoRectify can be passed here. If the matrix is empty, the identity transformation is used. -@param P New camera matrix (3x3) or new projection matrix (3x4) \f$\begin{bmatrix} {f'}_x & 0 & {c'}_x & t_x \\ 0 & {f'}_y & {c'}_y & t_y \\ 0 & 0 & 1 & t_z \end{bmatrix}\f$. P1 or P2 computed by -#stereoRectify can be passed here. If the matrix is empty, the identity new camera matrix is used. - */ -CV_EXPORTS_W -void undistortPoints(InputArray src, OutputArray dst, - InputArray cameraMatrix, InputArray distCoeffs, - InputArray R = noArray(), InputArray P = noArray()); -/** @overload - @note Default version of #undistortPoints does 5 iterations to compute undistorted points. - */ -CV_EXPORTS_AS(undistortPointsIter) -void undistortPoints(InputArray src, OutputArray dst, - InputArray cameraMatrix, InputArray distCoeffs, - InputArray R, InputArray P, TermCriteria criteria); - -/** - * @brief Compute undistorted image points position - * - * @param src Observed points position, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel (CV_32FC2 or -CV_64FC2) (or vector\ ). - * @param dst Output undistorted points position (1xN/Nx1 2-channel or vector\ ). - * @param cameraMatrix Camera matrix \f$\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . - * @param distCoeffs Distortion coefficients - */ -CV_EXPORTS_W -void undistortImagePoints(InputArray src, OutputArray dst, InputArray cameraMatrix, - InputArray distCoeffs, - TermCriteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, - 0.01)); - -//! @} calib3d - -/** @brief The methods in this namespace use a so-called fisheye camera model. - @ingroup calib3d_fisheye -*/ -namespace fisheye -{ -//! @addtogroup calib3d_fisheye -//! @{ - - enum{ - CALIB_USE_INTRINSIC_GUESS = 1 << 0, - CALIB_RECOMPUTE_EXTRINSIC = 1 << 1, - CALIB_CHECK_COND = 1 << 2, - CALIB_FIX_SKEW = 1 << 3, - CALIB_FIX_K1 = 1 << 4, - CALIB_FIX_K2 = 1 << 5, - CALIB_FIX_K3 = 1 << 6, - CALIB_FIX_K4 = 1 << 7, - CALIB_FIX_INTRINSIC = 1 << 8, - CALIB_FIX_PRINCIPAL_POINT = 1 << 9, - CALIB_ZERO_DISPARITY = 1 << 10, - CALIB_FIX_FOCAL_LENGTH = 1 << 11 - }; - - /** @brief Projects points using fisheye model - - @param objectPoints Array of object points, 1xN/Nx1 3-channel (or vector\ ), where N is - the number of points in the view. - @param imagePoints Output array of image points, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel, or - vector\. - @param affine - @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. - @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. - @param alpha The skew coefficient. - @param jacobian Optional output 2Nx15 jacobian matrix of derivatives of image points with respect - to components of the focal lengths, coordinates of the principal point, distortion coefficients, - rotation vector, translation vector, and the skew. In the old interface different components of - the jacobian are returned via different output parameters. - - The function computes projections of 3D points to the image plane given intrinsic and extrinsic - camera parameters. Optionally, the function computes Jacobians - matrices of partial derivatives of - image points coordinates (as functions of all the input parameters) with respect to the particular - parameters, intrinsic and/or extrinsic. - */ - CV_EXPORTS void projectPoints(InputArray objectPoints, OutputArray imagePoints, const Affine3d& affine, - InputArray K, InputArray D, double alpha = 0, OutputArray jacobian = noArray()); - - /** @overload */ - CV_EXPORTS_W void projectPoints(InputArray objectPoints, OutputArray imagePoints, InputArray rvec, InputArray tvec, - InputArray K, InputArray D, double alpha = 0, OutputArray jacobian = noArray()); - - /** @brief Distorts 2D points using fisheye model. - - @param undistorted Array of object points, 1xN/Nx1 2-channel (or vector\ ), where N is - the number of points in the view. - @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. - @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. - @param alpha The skew coefficient. - @param distorted Output array of image points, 1xN/Nx1 2-channel, or vector\ . - - Note that the function assumes the camera intrinsic matrix of the undistorted points to be identity. - This means if you want to distort image points you have to multiply them with \f$K^{-1}\f$ or - use another function overload. - */ - CV_EXPORTS_W void distortPoints(InputArray undistorted, OutputArray distorted, InputArray K, InputArray D, double alpha = 0); - - /** @overload - Overload of distortPoints function to handle cases when undistorted points are obtained with non-identity - camera matrix, e.g. output of #estimateNewCameraMatrixForUndistortRectify. - @param undistorted Array of object points, 1xN/Nx1 2-channel (or vector\ ), where N is - the number of points in the view. - @param Kundistorted Camera intrinsic matrix used as new camera matrix for undistortion. - @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. - @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. - @param alpha The skew coefficient. - @param distorted Output array of image points, 1xN/Nx1 2-channel, or vector\ . - @sa estimateNewCameraMatrixForUndistortRectify - */ - CV_EXPORTS_W void distortPoints(InputArray undistorted, OutputArray distorted, InputArray Kundistorted, InputArray K, InputArray D, double alpha = 0); - - /** @brief Undistorts 2D points using fisheye model - - @param distorted Array of object points, 1xN/Nx1 2-channel (or vector\ ), where N is the - number of points in the view. - @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. - @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. - @param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3 - 1-channel or 1x1 3-channel - @param P New camera intrinsic matrix (3x3) or new projection matrix (3x4) - @param criteria Termination criteria - @param undistorted Output array of image points, 1xN/Nx1 2-channel, or vector\ . - */ - CV_EXPORTS_W void undistortPoints(InputArray distorted, OutputArray undistorted, - InputArray K, InputArray D, InputArray R = noArray(), InputArray P = noArray(), - TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 10, 1e-8)); - - /** @brief Computes undistortion and rectification maps for image transform by #remap. If D is empty zero - distortion is used, if R or P is empty identity matrixes are used. - - @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. - @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. - @param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3 - 1-channel or 1x1 3-channel - @param P New camera intrinsic matrix (3x3) or new projection matrix (3x4) - @param size Undistorted image size. - @param m1type Type of the first output map that can be CV_32FC1 or CV_16SC2 . See #convertMaps - for details. - @param map1 The first output map. - @param map2 The second output map. - */ - CV_EXPORTS_W void initUndistortRectifyMap(InputArray K, InputArray D, InputArray R, InputArray P, - const cv::Size& size, int m1type, OutputArray map1, OutputArray map2); - - /** @brief Transforms an image to compensate for fisheye lens distortion. - - @param distorted image with fisheye lens distortion. - @param undistorted Output image with compensated fisheye lens distortion. - @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. - @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. - @param Knew Camera intrinsic matrix of the distorted image. By default, it is the identity matrix but you - may additionally scale and shift the result by using a different matrix. - @param new_size the new size - - The function transforms an image to compensate radial and tangential lens distortion. - - The function is simply a combination of #fisheye::initUndistortRectifyMap (with unity R ) and #remap - (with bilinear interpolation). See the former function for details of the transformation being - performed. - - See below the results of undistortImage. - - a\) result of undistort of perspective camera model (all possible coefficients (k_1, k_2, k_3, - k_4, k_5, k_6) of distortion were optimized under calibration) - - b\) result of #fisheye::undistortImage of fisheye camera model (all possible coefficients (k_1, k_2, - k_3, k_4) of fisheye distortion were optimized under calibration) - - c\) original image was captured with fisheye lens - - Pictures a) and b) almost the same. But if we consider points of image located far from the center - of image, we can notice that on image a) these points are distorted. - - ![image](pics/fisheye_undistorted.jpg) - */ - CV_EXPORTS_W void undistortImage(InputArray distorted, OutputArray undistorted, - InputArray K, InputArray D, InputArray Knew = cv::noArray(), const Size& new_size = Size()); - - /** @brief Estimates new camera intrinsic matrix for undistortion or rectification. - - @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. - @param image_size Size of the image - @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. - @param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3 - 1-channel or 1x1 3-channel - @param P New camera intrinsic matrix (3x3) or new projection matrix (3x4) - @param balance Sets the new focal length in range between the min focal length and the max focal - length. Balance is in range of [0, 1]. - @param new_size the new size - @param fov_scale Divisor for new focal length. - */ - CV_EXPORTS_W void estimateNewCameraMatrixForUndistortRectify(InputArray K, InputArray D, const Size &image_size, InputArray R, - OutputArray P, double balance = 0.0, const Size& new_size = Size(), double fov_scale = 1.0); - - /** @brief Performs camera calibration - - @param objectPoints vector of vectors of calibration pattern points in the calibration pattern - coordinate space. - @param imagePoints vector of vectors of the projections of calibration pattern points. - imagePoints.size() and objectPoints.size() and imagePoints[i].size() must be equal to - objectPoints[i].size() for each i. - @param image_size Size of the image used only to initialize the camera intrinsic matrix. - @param K Output 3x3 floating-point camera intrinsic matrix - \f$\cameramatrix{A}\f$ . If - @ref fisheye::CALIB_USE_INTRINSIC_GUESS is specified, some or all of fx, fy, cx, cy must be - initialized before calling the function. - @param D Output vector of distortion coefficients \f$\distcoeffsfisheye\f$. - @param rvecs Output vector of rotation vectors (see @ref Rodrigues ) estimated for each pattern view. - That is, each k-th rotation vector together with the corresponding k-th translation vector (see - the next output parameter description) brings the calibration pattern from the model coordinate - space (in which object points are specified) to the world coordinate space, that is, a real - position of the calibration pattern in the k-th pattern view (k=0.. *M* -1). - @param tvecs Output vector of translation vectors estimated for each pattern view. - @param flags Different flags that may be zero or a combination of the following values: - - @ref fisheye::CALIB_USE_INTRINSIC_GUESS cameraMatrix contains valid initial values of - fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image - center ( imageSize is used), and focal distances are computed in a least-squares fashion. - - @ref fisheye::CALIB_RECOMPUTE_EXTRINSIC Extrinsic will be recomputed after each iteration - of intrinsic optimization. - - @ref fisheye::CALIB_CHECK_COND The functions will check validity of condition number. - - @ref fisheye::CALIB_FIX_SKEW Skew coefficient (alpha) is set to zero and stay zero. - - @ref fisheye::CALIB_FIX_K1,..., @ref fisheye::CALIB_FIX_K4 Selected distortion coefficients - are set to zeros and stay zero. - - @ref fisheye::CALIB_FIX_PRINCIPAL_POINT The principal point is not changed during the global -optimization. It stays at the center or at a different location specified when @ref fisheye::CALIB_USE_INTRINSIC_GUESS is set too. - - @ref fisheye::CALIB_FIX_FOCAL_LENGTH The focal length is not changed during the global -optimization. It is the \f$max(width,height)/\pi\f$ or the provided \f$f_x\f$, \f$f_y\f$ when @ref fisheye::CALIB_USE_INTRINSIC_GUESS is set too. - @param criteria Termination criteria for the iterative optimization algorithm. - */ - CV_EXPORTS_W double calibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, const Size& image_size, - InputOutputArray K, InputOutputArray D, OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, int flags = 0, - TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON)); - - /** @brief Stereo rectification for fisheye camera model - - @param K1 First camera intrinsic matrix. - @param D1 First camera distortion parameters. - @param K2 Second camera intrinsic matrix. - @param D2 Second camera distortion parameters. - @param imageSize Size of the image used for stereo calibration. - @param R Rotation matrix between the coordinate systems of the first and the second - cameras. - @param tvec Translation vector between coordinate systems of the cameras. - @param R1 Output 3x3 rectification transform (rotation matrix) for the first camera. - @param R2 Output 3x3 rectification transform (rotation matrix) for the second camera. - @param P1 Output 3x4 projection matrix in the new (rectified) coordinate systems for the first - camera. - @param P2 Output 3x4 projection matrix in the new (rectified) coordinate systems for the second - camera. - @param Q Output \f$4 \times 4\f$ disparity-to-depth mapping matrix (see #reprojectImageTo3D ). - @param flags Operation flags that may be zero or @ref fisheye::CALIB_ZERO_DISPARITY . If the flag is set, - the function makes the principal points of each camera have the same pixel coordinates in the - rectified views. And if the flag is not set, the function may still shift the images in the - horizontal or vertical direction (depending on the orientation of epipolar lines) to maximize the - useful image area. - @param newImageSize New image resolution after rectification. The same size should be passed to - #initUndistortRectifyMap (see the stereo_calib.cpp sample in OpenCV samples directory). When (0,0) - is passed (default), it is set to the original imageSize . Setting it to larger value can help you - preserve details in the original image, especially when there is a big radial distortion. - @param balance Sets the new focal length in range between the min focal length and the max focal - length. Balance is in range of [0, 1]. - @param fov_scale Divisor for new focal length. - */ - CV_EXPORTS_W void stereoRectify(InputArray K1, InputArray D1, InputArray K2, InputArray D2, const Size &imageSize, InputArray R, InputArray tvec, - OutputArray R1, OutputArray R2, OutputArray P1, OutputArray P2, OutputArray Q, int flags, const Size &newImageSize = Size(), - double balance = 0.0, double fov_scale = 1.0); - - /** @brief Performs stereo calibration - - @param objectPoints Vector of vectors of the calibration pattern points. - @param imagePoints1 Vector of vectors of the projections of the calibration pattern points, - observed by the first camera. - @param imagePoints2 Vector of vectors of the projections of the calibration pattern points, - observed by the second camera. - @param K1 Input/output first camera intrinsic matrix: - \f$\vecthreethree{f_x^{(j)}}{0}{c_x^{(j)}}{0}{f_y^{(j)}}{c_y^{(j)}}{0}{0}{1}\f$ , \f$j = 0,\, 1\f$ . If - any of @ref fisheye::CALIB_USE_INTRINSIC_GUESS , @ref fisheye::CALIB_FIX_INTRINSIC are specified, - some or all of the matrix components must be initialized. - @param D1 Input/output vector of distortion coefficients \f$\distcoeffsfisheye\f$ of 4 elements. - @param K2 Input/output second camera intrinsic matrix. The parameter is similar to K1 . - @param D2 Input/output lens distortion coefficients for the second camera. The parameter is - similar to D1 . - @param imageSize Size of the image used only to initialize camera intrinsic matrix. - @param R Output rotation matrix between the 1st and the 2nd camera coordinate systems. - @param T Output translation vector between the coordinate systems of the cameras. - @param rvecs Output vector of rotation vectors ( @ref Rodrigues ) estimated for each pattern view in the - coordinate system of the first camera of the stereo pair (e.g. std::vector). More in detail, each - i-th rotation vector together with the corresponding i-th translation vector (see the next output parameter - description) brings the calibration pattern from the object coordinate space (in which object points are - specified) to the camera coordinate space of the first camera of the stereo pair. In more technical terms, - the tuple of the i-th rotation and translation vector performs a change of basis from object coordinate space - to camera coordinate space of the first camera of the stereo pair. - @param tvecs Output vector of translation vectors estimated for each pattern view, see parameter description - of previous output parameter ( rvecs ). - @param flags Different flags that may be zero or a combination of the following values: - - @ref fisheye::CALIB_FIX_INTRINSIC Fix K1, K2? and D1, D2? so that only R, T matrices - are estimated. - - @ref fisheye::CALIB_USE_INTRINSIC_GUESS K1, K2 contains valid initial values of - fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image - center (imageSize is used), and focal distances are computed in a least-squares fashion. - - @ref fisheye::CALIB_RECOMPUTE_EXTRINSIC Extrinsic will be recomputed after each iteration - of intrinsic optimization. - - @ref fisheye::CALIB_CHECK_COND The functions will check validity of condition number. - - @ref fisheye::CALIB_FIX_SKEW Skew coefficient (alpha) is set to zero and stay zero. - - @ref fisheye::CALIB_FIX_K1,..., @ref fisheye::CALIB_FIX_K4 Selected distortion coefficients are set to zeros and stay - zero. - @param criteria Termination criteria for the iterative optimization algorithm. - */ - CV_EXPORTS_W double stereoCalibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, - InputOutputArray K1, InputOutputArray D1, InputOutputArray K2, InputOutputArray D2, Size imageSize, - OutputArray R, OutputArray T, OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, int flags = fisheye::CALIB_FIX_INTRINSIC, - TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON)); - - /// @overload - CV_EXPORTS_W double stereoCalibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, - InputOutputArray K1, InputOutputArray D1, InputOutputArray K2, InputOutputArray D2, Size imageSize, - OutputArray R, OutputArray T, int flags = fisheye::CALIB_FIX_INTRINSIC, - TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON)); - - /** - @brief Finds an object pose from 3D-2D point correspondences for fisheye camera moodel. - - @param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or - 1xN/Nx1 3-channel, where N is the number of points. vector\ can be also passed here. - @param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel, - where N is the number of points. vector\ can be also passed here. - @param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . - @param distCoeffs Input vector of distortion coefficients (4x1/1x4). - @param rvec Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from - the model coordinate system to the camera coordinate system. - @param tvec Output translation vector. - @param useExtrinsicGuess Parameter used for #SOLVEPNP_ITERATIVE. If true (1), the function uses - the provided rvec and tvec values as initial approximations of the rotation and translation - vectors, respectively, and further optimizes them. - @param flags Method for solving a PnP problem: see @ref calib3d_solvePnP_flags - This function returns the rotation and the translation vectors that transform a 3D point expressed in the object - coordinate frame to the camera coordinate frame, using different methods: - - P3P methods (@ref SOLVEPNP_P3P, @ref SOLVEPNP_AP3P): need 4 input points to return a unique solution. - - @ref SOLVEPNP_IPPE Input points must be >= 4 and object points must be coplanar. - - @ref SOLVEPNP_IPPE_SQUARE Special case suitable for marker pose estimation. - Number of input points must be 4. Object points must be defined in the following order: - - point 0: [-squareLength / 2, squareLength / 2, 0] - - point 1: [ squareLength / 2, squareLength / 2, 0] - - point 2: [ squareLength / 2, -squareLength / 2, 0] - - point 3: [-squareLength / 2, -squareLength / 2, 0] - - for all the other flags, number of input points must be >= 4 and object points can be in any configuration. - @param criteria Termination criteria for internal undistortPoints call. - The function interally undistorts points with @ref undistortPoints and call @ref cv::solvePnP, - thus the input are very similar. More information about Perspective-n-Points is described in @ref calib3d_solvePnP - for more information. - */ - CV_EXPORTS_W bool solvePnP( InputArray objectPoints, InputArray imagePoints, - InputArray cameraMatrix, InputArray distCoeffs, - OutputArray rvec, OutputArray tvec, - bool useExtrinsicGuess = false, int flags = SOLVEPNP_ITERATIVE, - TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 10, 1e-8) - ); - -//! @} calib3d_fisheye -} // end namespace fisheye - -} //end namespace cv - -#if 0 //def __cplusplus -////////////////////////////////////////////////////////////////////////////////////////// -class CV_EXPORTS CvLevMarq -{ -public: - CvLevMarq(); - CvLevMarq( int nparams, int nerrs, CvTermCriteria criteria= - cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON), - bool completeSymmFlag=false ); - ~CvLevMarq(); - void init( int nparams, int nerrs, CvTermCriteria criteria= - cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON), - bool completeSymmFlag=false ); - bool update( const CvMat*& param, CvMat*& J, CvMat*& err ); - bool updateAlt( const CvMat*& param, CvMat*& JtJ, CvMat*& JtErr, double*& errNorm ); - - void clear(); - void step(); - enum { DONE=0, STARTED=1, CALC_J=2, CHECK_ERR=3 }; - - cv::Ptr mask; - cv::Ptr prevParam; - cv::Ptr param; - cv::Ptr J; - cv::Ptr err; - cv::Ptr JtJ; - cv::Ptr JtJN; - cv::Ptr JtErr; - cv::Ptr JtJV; - cv::Ptr JtJW; - double prevErrNorm, errNorm; - int lambdaLg10; - CvTermCriteria criteria; - int state; - int iters; - bool completeSymmFlag; - int solveMethod; -}; -#endif - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CALIB3D_HPP +#define OPENCV_CALIB3D_HPP + +#include "opencv2/core.hpp" +#include "opencv2/core/types.hpp" +#include "opencv2/features2d.hpp" +#include "opencv2/core/affine.hpp" +#include "opencv2/core/utils/logger.hpp" + +/** + @defgroup calib3d Camera Calibration and 3D Reconstruction + +The functions in this section use a so-called pinhole camera model. The view of a scene +is obtained by projecting a scene's 3D point \f$P_w\f$ into the image plane using a perspective +transformation which forms the corresponding pixel \f$p\f$. Both \f$P_w\f$ and \f$p\f$ are +represented in homogeneous coordinates, i.e. as 3D and 2D homogeneous vector respectively. You will +find a brief introduction to projective geometry, homogeneous vectors and homogeneous +transformations at the end of this section's introduction. For more succinct notation, we often drop +the 'homogeneous' and say vector instead of homogeneous vector. + +The distortion-free projective transformation given by a pinhole camera model is shown below. + +\f[s \; p = A \begin{bmatrix} R|t \end{bmatrix} P_w,\f] + +where \f$P_w\f$ is a 3D point expressed with respect to the world coordinate system, +\f$p\f$ is a 2D pixel in the image plane, \f$A\f$ is the camera intrinsic matrix, +\f$R\f$ and \f$t\f$ are the rotation and translation that describe the change of coordinates from +world to camera coordinate systems (or camera frame) and \f$s\f$ is the projective transformation's +arbitrary scaling and not part of the camera model. + +The camera intrinsic matrix \f$A\f$ (notation used as in @cite Zhang2000 and also generally notated +as \f$K\f$) projects 3D points given in the camera coordinate system to 2D pixel coordinates, i.e. + +\f[p = A P_c.\f] + +The camera intrinsic matrix \f$A\f$ is composed of the focal lengths \f$f_x\f$ and \f$f_y\f$, which are +expressed in pixel units, and the principal point \f$(c_x, c_y)\f$, that is usually close to the +image center: + +\f[A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1},\f] + +and thus + +\f[s \vecthree{u}{v}{1} = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1} \vecthree{X_c}{Y_c}{Z_c}.\f] + +The matrix of intrinsic parameters does not depend on the scene viewed. So, once estimated, it can +be re-used as long as the focal length is fixed (in case of a zoom lens). Thus, if an image from the +camera is scaled by a factor, all of these parameters need to be scaled (multiplied/divided, +respectively) by the same factor. + +The joint rotation-translation matrix \f$[R|t]\f$ is the matrix product of a projective +transformation and a homogeneous transformation. The 3-by-4 projective transformation maps 3D points +represented in camera coordinates to 2D points in the image plane and represented in normalized +camera coordinates \f$x' = X_c / Z_c\f$ and \f$y' = Y_c / Z_c\f$: + +\f[Z_c \begin{bmatrix} +x' \\ +y' \\ +1 +\end{bmatrix} = \begin{bmatrix} +1 & 0 & 0 & 0 \\ +0 & 1 & 0 & 0 \\ +0 & 0 & 1 & 0 +\end{bmatrix} +\begin{bmatrix} +X_c \\ +Y_c \\ +Z_c \\ +1 +\end{bmatrix}.\f] + +The homogeneous transformation is encoded by the extrinsic parameters \f$R\f$ and \f$t\f$ and +represents the change of basis from world coordinate system \f$w\f$ to the camera coordinate sytem +\f$c\f$. Thus, given the representation of the point \f$P\f$ in world coordinates, \f$P_w\f$, we +obtain \f$P\f$'s representation in the camera coordinate system, \f$P_c\f$, by + +\f[P_c = \begin{bmatrix} +R & t \\ +0 & 1 +\end{bmatrix} P_w,\f] + +This homogeneous transformation is composed out of \f$R\f$, a 3-by-3 rotation matrix, and \f$t\f$, a +3-by-1 translation vector: + +\f[\begin{bmatrix} +R & t \\ +0 & 1 +\end{bmatrix} = \begin{bmatrix} +r_{11} & r_{12} & r_{13} & t_x \\ +r_{21} & r_{22} & r_{23} & t_y \\ +r_{31} & r_{32} & r_{33} & t_z \\ +0 & 0 & 0 & 1 +\end{bmatrix}, +\f] + +and therefore + +\f[\begin{bmatrix} +X_c \\ +Y_c \\ +Z_c \\ +1 +\end{bmatrix} = \begin{bmatrix} +r_{11} & r_{12} & r_{13} & t_x \\ +r_{21} & r_{22} & r_{23} & t_y \\ +r_{31} & r_{32} & r_{33} & t_z \\ +0 & 0 & 0 & 1 +\end{bmatrix} +\begin{bmatrix} +X_w \\ +Y_w \\ +Z_w \\ +1 +\end{bmatrix}.\f] + +Combining the projective transformation and the homogeneous transformation, we obtain the projective +transformation that maps 3D points in world coordinates into 2D points in the image plane and in +normalized camera coordinates: + +\f[Z_c \begin{bmatrix} +x' \\ +y' \\ +1 +\end{bmatrix} = \begin{bmatrix} R|t \end{bmatrix} \begin{bmatrix} +X_w \\ +Y_w \\ +Z_w \\ +1 +\end{bmatrix} = \begin{bmatrix} +r_{11} & r_{12} & r_{13} & t_x \\ +r_{21} & r_{22} & r_{23} & t_y \\ +r_{31} & r_{32} & r_{33} & t_z +\end{bmatrix} +\begin{bmatrix} +X_w \\ +Y_w \\ +Z_w \\ +1 +\end{bmatrix},\f] + +with \f$x' = X_c / Z_c\f$ and \f$y' = Y_c / Z_c\f$. Putting the equations for instrincs and extrinsics together, we can write out +\f$s \; p = A \begin{bmatrix} R|t \end{bmatrix} P_w\f$ as + +\f[s \vecthree{u}{v}{1} = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1} +\begin{bmatrix} +r_{11} & r_{12} & r_{13} & t_x \\ +r_{21} & r_{22} & r_{23} & t_y \\ +r_{31} & r_{32} & r_{33} & t_z +\end{bmatrix} +\begin{bmatrix} +X_w \\ +Y_w \\ +Z_w \\ +1 +\end{bmatrix}.\f] + +If \f$Z_c \ne 0\f$, the transformation above is equivalent to the following, + +\f[\begin{bmatrix} +u \\ +v +\end{bmatrix} = \begin{bmatrix} +f_x X_c/Z_c + c_x \\ +f_y Y_c/Z_c + c_y +\end{bmatrix}\f] + +with + +\f[\vecthree{X_c}{Y_c}{Z_c} = \begin{bmatrix} +R|t +\end{bmatrix} \begin{bmatrix} +X_w \\ +Y_w \\ +Z_w \\ +1 +\end{bmatrix}.\f] + +The following figure illustrates the pinhole camera model. + +![Pinhole camera model](pics/pinhole_camera_model.png) + +Real lenses usually have some distortion, mostly radial distortion, and slight tangential distortion. +So, the above model is extended as: + +\f[\begin{bmatrix} +u \\ +v +\end{bmatrix} = \begin{bmatrix} +f_x x'' + c_x \\ +f_y y'' + c_y +\end{bmatrix}\f] + +where + +\f[\begin{bmatrix} +x'' \\ +y'' +\end{bmatrix} = \begin{bmatrix} +x' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} + 2 p_1 x' y' + p_2(r^2 + 2 x'^2) + s_1 r^2 + s_2 r^4 \\ +y' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} + p_1 (r^2 + 2 y'^2) + 2 p_2 x' y' + s_3 r^2 + s_4 r^4 \\ +\end{bmatrix}\f] + +with + +\f[r^2 = x'^2 + y'^2\f] + +and + +\f[\begin{bmatrix} +x'\\ +y' +\end{bmatrix} = \begin{bmatrix} +X_c/Z_c \\ +Y_c/Z_c +\end{bmatrix},\f] + +if \f$Z_c \ne 0\f$. + +The distortion parameters are the radial coefficients \f$k_1\f$, \f$k_2\f$, \f$k_3\f$, \f$k_4\f$, \f$k_5\f$, and \f$k_6\f$ +,\f$p_1\f$ and \f$p_2\f$ are the tangential distortion coefficients, and \f$s_1\f$, \f$s_2\f$, \f$s_3\f$, and \f$s_4\f$, +are the thin prism distortion coefficients. Higher-order coefficients are not considered in OpenCV. + +The next figures show two common types of radial distortion: barrel distortion +(\f$ 1 + k_1 r^2 + k_2 r^4 + k_3 r^6 \f$ monotonically decreasing) +and pincushion distortion (\f$ 1 + k_1 r^2 + k_2 r^4 + k_3 r^6 \f$ monotonically increasing). +Radial distortion is always monotonic for real lenses, +and if the estimator produces a non-monotonic result, +this should be considered a calibration failure. +More generally, radial distortion must be monotonic and the distortion function must be bijective. +A failed estimation result may look deceptively good near the image center +but will work poorly in e.g. AR/SFM applications. +The optimization method used in OpenCV camera calibration does not include these constraints as +the framework does not support the required integer programming and polynomial inequalities. +See [issue #15992](https://github.com/opencv/opencv/issues/15992) for additional information. + +![](pics/distortion_examples.png) +![](pics/distortion_examples2.png) + +In some cases, the image sensor may be tilted in order to focus an oblique plane in front of the +camera (Scheimpflug principle). This can be useful for particle image velocimetry (PIV) or +triangulation with a laser fan. The tilt causes a perspective distortion of \f$x''\f$ and +\f$y''\f$. This distortion can be modeled in the following way, see e.g. @cite Louhichi07. + +\f[\begin{bmatrix} +u \\ +v +\end{bmatrix} = \begin{bmatrix} +f_x x''' + c_x \\ +f_y y''' + c_y +\end{bmatrix},\f] + +where + +\f[s\vecthree{x'''}{y'''}{1} = +\vecthreethree{R_{33}(\tau_x, \tau_y)}{0}{-R_{13}(\tau_x, \tau_y)} +{0}{R_{33}(\tau_x, \tau_y)}{-R_{23}(\tau_x, \tau_y)} +{0}{0}{1} R(\tau_x, \tau_y) \vecthree{x''}{y''}{1}\f] + +and the matrix \f$R(\tau_x, \tau_y)\f$ is defined by two rotations with angular parameter +\f$\tau_x\f$ and \f$\tau_y\f$, respectively, + +\f[ +R(\tau_x, \tau_y) = +\vecthreethree{\cos(\tau_y)}{0}{-\sin(\tau_y)}{0}{1}{0}{\sin(\tau_y)}{0}{\cos(\tau_y)} +\vecthreethree{1}{0}{0}{0}{\cos(\tau_x)}{\sin(\tau_x)}{0}{-\sin(\tau_x)}{\cos(\tau_x)} = +\vecthreethree{\cos(\tau_y)}{\sin(\tau_y)\sin(\tau_x)}{-\sin(\tau_y)\cos(\tau_x)} +{0}{\cos(\tau_x)}{\sin(\tau_x)} +{\sin(\tau_y)}{-\cos(\tau_y)\sin(\tau_x)}{\cos(\tau_y)\cos(\tau_x)}. +\f] + +In the functions below the coefficients are passed or returned as + +\f[(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f] + +vector. That is, if the vector contains four elements, it means that \f$k_3=0\f$ . The distortion +coefficients do not depend on the scene viewed. Thus, they also belong to the intrinsic camera +parameters. And they remain the same regardless of the captured image resolution. If, for example, a +camera has been calibrated on images of 320 x 240 resolution, absolutely the same distortion +coefficients can be used for 640 x 480 images from the same camera while \f$f_x\f$, \f$f_y\f$, +\f$c_x\f$, and \f$c_y\f$ need to be scaled appropriately. + +The functions below use the above model to do the following: + +- Project 3D points to the image plane given intrinsic and extrinsic parameters. +- Compute extrinsic parameters given intrinsic parameters, a few 3D points, and their +projections. +- Estimate intrinsic and extrinsic camera parameters from several views of a known calibration +pattern (every view is described by several 3D-2D point correspondences). +- Estimate the relative position and orientation of the stereo camera "heads" and compute the +*rectification* transformation that makes the camera optical axes parallel. + + Homogeneous Coordinates
+Homogeneous Coordinates are a system of coordinates that are used in projective geometry. Their use +allows to represent points at infinity by finite coordinates and simplifies formulas when compared +to the cartesian counterparts, e.g. they have the advantage that affine transformations can be +expressed as linear homogeneous transformation. + +One obtains the homogeneous vector \f$P_h\f$ by appending a 1 along an n-dimensional cartesian +vector \f$P\f$ e.g. for a 3D cartesian vector the mapping \f$P \rightarrow P_h\f$ is: + +\f[\begin{bmatrix} +X \\ +Y \\ +Z +\end{bmatrix} \rightarrow \begin{bmatrix} +X \\ +Y \\ +Z \\ +1 +\end{bmatrix}.\f] + +For the inverse mapping \f$P_h \rightarrow P\f$, one divides all elements of the homogeneous vector +by its last element, e.g. for a 3D homogeneous vector one gets its 2D cartesian counterpart by: + +\f[\begin{bmatrix} +X \\ +Y \\ +W +\end{bmatrix} \rightarrow \begin{bmatrix} +X / W \\ +Y / W +\end{bmatrix},\f] + +if \f$W \ne 0\f$. + +Due to this mapping, all multiples \f$k P_h\f$, for \f$k \ne 0\f$, of a homogeneous point represent +the same point \f$P_h\f$. An intuitive understanding of this property is that under a projective +transformation, all multiples of \f$P_h\f$ are mapped to the same point. This is the physical +observation one does for pinhole cameras, as all points along a ray through the camera's pinhole are +projected to the same image point, e.g. all points along the red ray in the image of the pinhole +camera model above would be mapped to the same image coordinate. This property is also the source +for the scale ambiguity s in the equation of the pinhole camera model. + +As mentioned, by using homogeneous coordinates we can express any change of basis parameterized by +\f$R\f$ and \f$t\f$ as a linear transformation, e.g. for the change of basis from coordinate system +0 to coordinate system 1 becomes: + +\f[P_1 = R P_0 + t \rightarrow P_{h_1} = \begin{bmatrix} +R & t \\ +0 & 1 +\end{bmatrix} P_{h_0}.\f] + +@note + - Many functions in this module take a camera intrinsic matrix as an input parameter. Although all + functions assume the same structure of this parameter, they may name it differently. The + parameter's description, however, will be clear in that a camera intrinsic matrix with the structure + shown above is required. + - A calibration sample for 3 cameras in a horizontal position can be found at + opencv_source_code/samples/cpp/3calibration.cpp + - A calibration sample based on a sequence of images can be found at + opencv_source_code/samples/cpp/calibration.cpp + - A calibration sample in order to do 3D reconstruction can be found at + opencv_source_code/samples/cpp/build3dmodel.cpp + - A calibration example on stereo calibration can be found at + opencv_source_code/samples/cpp/stereo_calib.cpp + - A calibration example on stereo matching can be found at + opencv_source_code/samples/cpp/stereo_match.cpp + - (Python) A camera calibration sample can be found at + opencv_source_code/samples/python/calibrate.py + + @{ + @defgroup calib3d_fisheye Fisheye camera model + + Definitions: Let P be a point in 3D of coordinates X in the world reference frame (stored in the + matrix X) The coordinate vector of P in the camera reference frame is: + + \f[Xc = R X + T\f] + + where R is the rotation matrix corresponding to the rotation vector om: R = rodrigues(om); call x, y + and z the 3 coordinates of Xc: + + \f[\begin{array}{l} x = Xc_1 \\ y = Xc_2 \\ z = Xc_3 \end{array} \f] + + The pinhole projection coordinates of P is [a; b] where + + \f[\begin{array}{l} a = x / z \ and \ b = y / z \\ r^2 = a^2 + b^2 \\ \theta = atan(r) \end{array} \f] + + Fisheye distortion: + + \f[\theta_d = \theta (1 + k_1 \theta^2 + k_2 \theta^4 + k_3 \theta^6 + k_4 \theta^8)\f] + + The distorted point coordinates are [x'; y'] where + + \f[\begin{array}{l} x' = (\theta_d / r) a \\ y' = (\theta_d / r) b \end{array} \f] + + Finally, conversion into pixel coordinates: The final pixel coordinates vector [u; v] where: + + \f[\begin{array}{l} u = f_x (x' + \alpha y') + c_x \\ + v = f_y y' + c_y \end{array} \f] + + Summary: + Generic camera model @cite Kannala2006 with perspective projection and without distortion correction + + @} + */ + +namespace cv +{ + +//! @addtogroup calib3d +//! @{ + +//! type of the robust estimation algorithm +enum { LMEDS = 4, //!< least-median of squares algorithm + RANSAC = 8, //!< RANSAC algorithm + RHO = 16, //!< RHO algorithm + USAC_DEFAULT = 32, //!< USAC algorithm, default settings + USAC_PARALLEL = 33, //!< USAC, parallel version + USAC_FM_8PTS = 34, //!< USAC, fundamental matrix 8 points + USAC_FAST = 35, //!< USAC, fast settings + USAC_ACCURATE = 36, //!< USAC, accurate settings + USAC_PROSAC = 37, //!< USAC, sorted points, runs PROSAC + USAC_MAGSAC = 38 //!< USAC, runs MAGSAC++ + }; + +enum SolvePnPMethod { + SOLVEPNP_ITERATIVE = 0, //!< Pose refinement using non-linear Levenberg-Marquardt minimization scheme @cite Madsen04 @cite Eade13 \n + //!< Initial solution for non-planar "objectPoints" needs at least 6 points and uses the DLT algorithm. \n + //!< Initial solution for planar "objectPoints" needs at least 4 points and uses pose from homography decomposition. + SOLVEPNP_EPNP = 1, //!< EPnP: Efficient Perspective-n-Point Camera Pose Estimation @cite lepetit2009epnp + SOLVEPNP_P3P = 2, //!< Complete Solution Classification for the Perspective-Three-Point Problem @cite gao2003complete + SOLVEPNP_DLS = 3, //!< **Broken implementation. Using this flag will fallback to EPnP.** \n + //!< A Direct Least-Squares (DLS) Method for PnP @cite hesch2011direct + SOLVEPNP_UPNP = 4, //!< **Broken implementation. Using this flag will fallback to EPnP.** \n + //!< Exhaustive Linearization for Robust Camera Pose and Focal Length Estimation @cite penate2013exhaustive + SOLVEPNP_AP3P = 5, //!< An Efficient Algebraic Solution to the Perspective-Three-Point Problem @cite Ke17 + SOLVEPNP_IPPE = 6, //!< Infinitesimal Plane-Based Pose Estimation @cite Collins14 \n + //!< Object points must be coplanar. + SOLVEPNP_IPPE_SQUARE = 7, //!< Infinitesimal Plane-Based Pose Estimation @cite Collins14 \n + //!< This is a special case suitable for marker pose estimation.\n + //!< 4 coplanar object points must be defined in the following order: + //!< - point 0: [-squareLength / 2, squareLength / 2, 0] + //!< - point 1: [ squareLength / 2, squareLength / 2, 0] + //!< - point 2: [ squareLength / 2, -squareLength / 2, 0] + //!< - point 3: [-squareLength / 2, -squareLength / 2, 0] + SOLVEPNP_SQPNP = 8, //!< SQPnP: A Consistently Fast and Globally OptimalSolution to the Perspective-n-Point Problem @cite Terzakis2020SQPnP +#ifndef CV_DOXYGEN + SOLVEPNP_MAX_COUNT //!< Used for count +#endif +}; + +enum { CALIB_CB_ADAPTIVE_THRESH = 1, + CALIB_CB_NORMALIZE_IMAGE = 2, + CALIB_CB_FILTER_QUADS = 4, + CALIB_CB_FAST_CHECK = 8, + CALIB_CB_EXHAUSTIVE = 16, + CALIB_CB_ACCURACY = 32, + CALIB_CB_LARGER = 64, + CALIB_CB_MARKER = 128, + CALIB_CB_PLAIN = 256 + }; + +enum { CALIB_CB_SYMMETRIC_GRID = 1, + CALIB_CB_ASYMMETRIC_GRID = 2, + CALIB_CB_CLUSTERING = 4 + }; + +enum { CALIB_NINTRINSIC = 18, + CALIB_USE_INTRINSIC_GUESS = 0x00001, + CALIB_FIX_ASPECT_RATIO = 0x00002, + CALIB_FIX_PRINCIPAL_POINT = 0x00004, + CALIB_ZERO_TANGENT_DIST = 0x00008, + CALIB_FIX_FOCAL_LENGTH = 0x00010, + CALIB_FIX_K1 = 0x00020, + CALIB_FIX_K2 = 0x00040, + CALIB_FIX_K3 = 0x00080, + CALIB_FIX_K4 = 0x00800, + CALIB_FIX_K5 = 0x01000, + CALIB_FIX_K6 = 0x02000, + CALIB_RATIONAL_MODEL = 0x04000, + CALIB_THIN_PRISM_MODEL = 0x08000, + CALIB_FIX_S1_S2_S3_S4 = 0x10000, + CALIB_TILTED_MODEL = 0x40000, + CALIB_FIX_TAUX_TAUY = 0x80000, + CALIB_USE_QR = 0x100000, //!< use QR instead of SVD decomposition for solving. Faster but potentially less precise + CALIB_FIX_TANGENT_DIST = 0x200000, + // only for stereo + CALIB_FIX_INTRINSIC = 0x00100, + CALIB_SAME_FOCAL_LENGTH = 0x00200, + // for stereo rectification + CALIB_ZERO_DISPARITY = 0x00400, + CALIB_USE_LU = (1 << 17), //!< use LU instead of SVD decomposition for solving. much faster but potentially less precise + CALIB_USE_EXTRINSIC_GUESS = (1 << 22) //!< for stereoCalibrate + }; + +//! the algorithm for finding fundamental matrix +enum { FM_7POINT = 1, //!< 7-point algorithm + FM_8POINT = 2, //!< 8-point algorithm + FM_LMEDS = 4, //!< least-median algorithm. 7-point algorithm is used. + FM_RANSAC = 8 //!< RANSAC algorithm. It needs at least 15 points. 7-point algorithm is used. + }; + +enum HandEyeCalibrationMethod +{ + CALIB_HAND_EYE_TSAI = 0, //!< A New Technique for Fully Autonomous and Efficient 3D Robotics Hand/Eye Calibration @cite Tsai89 + CALIB_HAND_EYE_PARK = 1, //!< Robot Sensor Calibration: Solving AX = XB on the Euclidean Group @cite Park94 + CALIB_HAND_EYE_HORAUD = 2, //!< Hand-eye Calibration @cite Horaud95 + CALIB_HAND_EYE_ANDREFF = 3, //!< On-line Hand-Eye Calibration @cite Andreff99 + CALIB_HAND_EYE_DANIILIDIS = 4 //!< Hand-Eye Calibration Using Dual Quaternions @cite Daniilidis98 +}; + +enum RobotWorldHandEyeCalibrationMethod +{ + CALIB_ROBOT_WORLD_HAND_EYE_SHAH = 0, //!< Solving the robot-world/hand-eye calibration problem using the kronecker product @cite Shah2013SolvingTR + CALIB_ROBOT_WORLD_HAND_EYE_LI = 1 //!< Simultaneous robot-world and hand-eye calibration using dual-quaternions and kronecker product @cite Li2010SimultaneousRA +}; + +enum SamplingMethod { SAMPLING_UNIFORM=0, SAMPLING_PROGRESSIVE_NAPSAC=1, SAMPLING_NAPSAC=2, + SAMPLING_PROSAC=3 }; +enum LocalOptimMethod {LOCAL_OPTIM_NULL=0, LOCAL_OPTIM_INNER_LO=1, LOCAL_OPTIM_INNER_AND_ITER_LO=2, + LOCAL_OPTIM_GC=3, LOCAL_OPTIM_SIGMA=4}; +enum ScoreMethod {SCORE_METHOD_RANSAC=0, SCORE_METHOD_MSAC=1, SCORE_METHOD_MAGSAC=2, SCORE_METHOD_LMEDS=3}; +enum NeighborSearchMethod { NEIGH_FLANN_KNN=0, NEIGH_GRID=1, NEIGH_FLANN_RADIUS=2 }; +enum PolishingMethod { NONE_POLISHER=0, LSQ_POLISHER=1, MAGSAC=2, COV_POLISHER=3 }; + +struct CV_EXPORTS_W_SIMPLE UsacParams +{ // in alphabetical order + CV_WRAP UsacParams(); + CV_PROP_RW double confidence; + CV_PROP_RW bool isParallel; + CV_PROP_RW int loIterations; + CV_PROP_RW LocalOptimMethod loMethod; + CV_PROP_RW int loSampleSize; + CV_PROP_RW int maxIterations; + CV_PROP_RW NeighborSearchMethod neighborsSearch; + CV_PROP_RW int randomGeneratorState; + CV_PROP_RW SamplingMethod sampler; + CV_PROP_RW ScoreMethod score; + CV_PROP_RW double threshold; + CV_PROP_RW PolishingMethod final_polisher; + CV_PROP_RW int final_polisher_iterations; +}; + +/** @brief Converts a rotation matrix to a rotation vector or vice versa. + +@param src Input rotation vector (3x1 or 1x3) or rotation matrix (3x3). +@param dst Output rotation matrix (3x3) or rotation vector (3x1 or 1x3), respectively. +@param jacobian Optional output Jacobian matrix, 3x9 or 9x3, which is a matrix of partial +derivatives of the output array components with respect to the input array components. + +\f[\begin{array}{l} \theta \leftarrow norm(r) \\ r \leftarrow r/ \theta \\ R = \cos(\theta) I + (1- \cos{\theta} ) r r^T + \sin(\theta) \vecthreethree{0}{-r_z}{r_y}{r_z}{0}{-r_x}{-r_y}{r_x}{0} \end{array}\f] + +Inverse transformation can be also done easily, since + +\f[\sin ( \theta ) \vecthreethree{0}{-r_z}{r_y}{r_z}{0}{-r_x}{-r_y}{r_x}{0} = \frac{R - R^T}{2}\f] + +A rotation vector is a convenient and most compact representation of a rotation matrix (since any +rotation matrix has just 3 degrees of freedom). The representation is used in the global 3D geometry +optimization procedures like @ref calibrateCamera, @ref stereoCalibrate, or @ref solvePnP . + +@note More information about the computation of the derivative of a 3D rotation matrix with respect to its exponential coordinate +can be found in: + - A Compact Formula for the Derivative of a 3-D Rotation in Exponential Coordinates, Guillermo Gallego, Anthony J. Yezzi @cite Gallego2014ACF + +@note Useful information on SE(3) and Lie Groups can be found in: + - A tutorial on SE(3) transformation parameterizations and on-manifold optimization, Jose-Luis Blanco @cite blanco2010tutorial + - Lie Groups for 2D and 3D Transformation, Ethan Eade @cite Eade17 + - A micro Lie theory for state estimation in robotics, Joan Solà, Jérémie Deray, Dinesh Atchuthan @cite Sol2018AML + */ +CV_EXPORTS_W void Rodrigues( InputArray src, OutputArray dst, OutputArray jacobian = noArray() ); + + + +/** Levenberg-Marquardt solver. Starting with the specified vector of parameters it + optimizes the target vector criteria "err" + (finds local minima of each target vector component absolute value). + + When needed, it calls user-provided callback. +*/ +class CV_EXPORTS LMSolver : public Algorithm +{ +public: + class CV_EXPORTS Callback + { + public: + virtual ~Callback() {} + /** + computes error and Jacobian for the specified vector of parameters + + @param param the current vector of parameters + @param err output vector of errors: err_i = actual_f_i - ideal_f_i + @param J output Jacobian: J_ij = d(ideal_f_i)/d(param_j) + + when J=noArray(), it means that it does not need to be computed. + Dimensionality of error vector and param vector can be different. + The callback should explicitly allocate (with "create" method) each output array + (unless it's noArray()). + */ + virtual bool compute(InputArray param, OutputArray err, OutputArray J) const = 0; + }; + + /** + Runs Levenberg-Marquardt algorithm using the passed vector of parameters as the start point. + The final vector of parameters (whether the algorithm converged or not) is stored at the same + vector. The method returns the number of iterations used. If it's equal to the previously specified + maxIters, there is a big chance the algorithm did not converge. + + @param param initial/final vector of parameters. + + Note that the dimensionality of parameter space is defined by the size of param vector, + and the dimensionality of optimized criteria is defined by the size of err vector + computed by the callback. + */ + virtual int run(InputOutputArray param) const = 0; + + /** + Sets the maximum number of iterations + @param maxIters the number of iterations + */ + virtual void setMaxIters(int maxIters) = 0; + /** + Retrieves the current maximum number of iterations + */ + virtual int getMaxIters() const = 0; + + /** + Creates Levenberg-Marquard solver + + @param cb callback + @param maxIters maximum number of iterations that can be further + modified using setMaxIters() method. + */ + static Ptr create(const Ptr& cb, int maxIters); + static Ptr create(const Ptr& cb, int maxIters, double eps); +}; + + + +/** @example samples/cpp/tutorial_code/features2D/Homography/pose_from_homography.cpp +An example program about pose estimation from coplanar points + +Check @ref tutorial_homography "the corresponding tutorial" for more details +*/ + +/** @brief Finds a perspective transformation between two planes. + +@param srcPoints Coordinates of the points in the original plane, a matrix of the type CV_32FC2 +or vector\ . +@param dstPoints Coordinates of the points in the target plane, a matrix of the type CV_32FC2 or +a vector\ . +@param method Method used to compute a homography matrix. The following methods are possible: +- **0** - a regular method using all the points, i.e., the least squares method +- @ref RANSAC - RANSAC-based robust method +- @ref LMEDS - Least-Median robust method +- @ref RHO - PROSAC-based robust method +@param ransacReprojThreshold Maximum allowed reprojection error to treat a point pair as an inlier +(used in the RANSAC and RHO methods only). That is, if +\f[\| \texttt{dstPoints} _i - \texttt{convertPointsHomogeneous} ( \texttt{H} \cdot \texttt{srcPoints} _i) \|_2 > \texttt{ransacReprojThreshold}\f] +then the point \f$i\f$ is considered as an outlier. If srcPoints and dstPoints are measured in pixels, +it usually makes sense to set this parameter somewhere in the range of 1 to 10. +@param mask Optional output mask set by a robust method ( RANSAC or LMeDS ). Note that the input +mask values are ignored. +@param maxIters The maximum number of RANSAC iterations. +@param confidence Confidence level, between 0 and 1. + +The function finds and returns the perspective transformation \f$H\f$ between the source and the +destination planes: + +\f[s_i \vecthree{x'_i}{y'_i}{1} \sim H \vecthree{x_i}{y_i}{1}\f] + +so that the back-projection error + +\f[\sum _i \left ( x'_i- \frac{h_{11} x_i + h_{12} y_i + h_{13}}{h_{31} x_i + h_{32} y_i + h_{33}} \right )^2+ \left ( y'_i- \frac{h_{21} x_i + h_{22} y_i + h_{23}}{h_{31} x_i + h_{32} y_i + h_{33}} \right )^2\f] + +is minimized. If the parameter method is set to the default value 0, the function uses all the point +pairs to compute an initial homography estimate with a simple least-squares scheme. + +However, if not all of the point pairs ( \f$srcPoints_i\f$, \f$dstPoints_i\f$ ) fit the rigid perspective +transformation (that is, there are some outliers), this initial estimate will be poor. In this case, +you can use one of the three robust methods. The methods RANSAC, LMeDS and RHO try many different +random subsets of the corresponding point pairs (of four pairs each, collinear pairs are discarded), estimate the homography matrix +using this subset and a simple least-squares algorithm, and then compute the quality/goodness of the +computed homography (which is the number of inliers for RANSAC or the least median re-projection error for +LMeDS). The best subset is then used to produce the initial estimate of the homography matrix and +the mask of inliers/outliers. + +Regardless of the method, robust or not, the computed homography matrix is refined further (using +inliers only in case of a robust method) with the Levenberg-Marquardt method to reduce the +re-projection error even more. + +The methods RANSAC and RHO can handle practically any ratio of outliers but need a threshold to +distinguish inliers from outliers. The method LMeDS does not need any threshold but it works +correctly only when there are more than 50% of inliers. Finally, if there are no outliers and the +noise is rather small, use the default method (method=0). + +The function is used to find initial intrinsic and extrinsic matrices. Homography matrix is +determined up to a scale. If \f$h_{33}\f$ is non-zero, the matrix is normalized so that \f$h_{33}=1\f$. +@note Whenever an \f$H\f$ matrix cannot be estimated, an empty one will be returned. + +@sa +getAffineTransform, estimateAffine2D, estimateAffinePartial2D, getPerspectiveTransform, warpPerspective, +perspectiveTransform + */ +CV_EXPORTS_W Mat findHomography( InputArray srcPoints, InputArray dstPoints, + int method = 0, double ransacReprojThreshold = 3, + OutputArray mask=noArray(), const int maxIters = 2000, + const double confidence = 0.995); + +/** @overload */ +CV_EXPORTS Mat findHomography( InputArray srcPoints, InputArray dstPoints, + OutputArray mask, int method = 0, double ransacReprojThreshold = 3 ); + + +CV_EXPORTS_W Mat findHomography(InputArray srcPoints, InputArray dstPoints, OutputArray mask, + const UsacParams ¶ms); + +/** @brief Computes an RQ decomposition of 3x3 matrices. + +@param src 3x3 input matrix. +@param mtxR Output 3x3 upper-triangular matrix. +@param mtxQ Output 3x3 orthogonal matrix. +@param Qx Optional output 3x3 rotation matrix around x-axis. +@param Qy Optional output 3x3 rotation matrix around y-axis. +@param Qz Optional output 3x3 rotation matrix around z-axis. + +The function computes a RQ decomposition using the given rotations. This function is used in +#decomposeProjectionMatrix to decompose the left 3x3 submatrix of a projection matrix into a camera +and a rotation matrix. + +It optionally returns three rotation matrices, one for each axis, and the three Euler angles in +degrees (as the return value) that could be used in OpenGL. Note, there is always more than one +sequence of rotations about the three principal axes that results in the same orientation of an +object, e.g. see @cite Slabaugh . Returned three rotation matrices and corresponding three Euler angles +are only one of the possible solutions. + */ +CV_EXPORTS_W Vec3d RQDecomp3x3( InputArray src, OutputArray mtxR, OutputArray mtxQ, + OutputArray Qx = noArray(), + OutputArray Qy = noArray(), + OutputArray Qz = noArray()); + +/** @brief Decomposes a projection matrix into a rotation matrix and a camera intrinsic matrix. + +@param projMatrix 3x4 input projection matrix P. +@param cameraMatrix Output 3x3 camera intrinsic matrix \f$\cameramatrix{A}\f$. +@param rotMatrix Output 3x3 external rotation matrix R. +@param transVect Output 4x1 translation vector T. +@param rotMatrixX Optional 3x3 rotation matrix around x-axis. +@param rotMatrixY Optional 3x3 rotation matrix around y-axis. +@param rotMatrixZ Optional 3x3 rotation matrix around z-axis. +@param eulerAngles Optional three-element vector containing three Euler angles of rotation in +degrees. + +The function computes a decomposition of a projection matrix into a calibration and a rotation +matrix and the position of a camera. + +It optionally returns three rotation matrices, one for each axis, and three Euler angles that could +be used in OpenGL. Note, there is always more than one sequence of rotations about the three +principal axes that results in the same orientation of an object, e.g. see @cite Slabaugh . Returned +three rotation matrices and corresponding three Euler angles are only one of the possible solutions. + +The function is based on #RQDecomp3x3 . + */ +CV_EXPORTS_W void decomposeProjectionMatrix( InputArray projMatrix, OutputArray cameraMatrix, + OutputArray rotMatrix, OutputArray transVect, + OutputArray rotMatrixX = noArray(), + OutputArray rotMatrixY = noArray(), + OutputArray rotMatrixZ = noArray(), + OutputArray eulerAngles =noArray() ); + +/** @brief Computes partial derivatives of the matrix product for each multiplied matrix. + +@param A First multiplied matrix. +@param B Second multiplied matrix. +@param dABdA First output derivative matrix d(A\*B)/dA of size +\f$\texttt{A.rows*B.cols} \times {A.rows*A.cols}\f$ . +@param dABdB Second output derivative matrix d(A\*B)/dB of size +\f$\texttt{A.rows*B.cols} \times {B.rows*B.cols}\f$ . + +The function computes partial derivatives of the elements of the matrix product \f$A*B\f$ with regard to +the elements of each of the two input matrices. The function is used to compute the Jacobian +matrices in #stereoCalibrate but can also be used in any other similar optimization function. + */ +CV_EXPORTS_W void matMulDeriv( InputArray A, InputArray B, OutputArray dABdA, OutputArray dABdB ); + +/** @brief Combines two rotation-and-shift transformations. + +@param rvec1 First rotation vector. +@param tvec1 First translation vector. +@param rvec2 Second rotation vector. +@param tvec2 Second translation vector. +@param rvec3 Output rotation vector of the superposition. +@param tvec3 Output translation vector of the superposition. +@param dr3dr1 Optional output derivative of rvec3 with regard to rvec1 +@param dr3dt1 Optional output derivative of rvec3 with regard to tvec1 +@param dr3dr2 Optional output derivative of rvec3 with regard to rvec2 +@param dr3dt2 Optional output derivative of rvec3 with regard to tvec2 +@param dt3dr1 Optional output derivative of tvec3 with regard to rvec1 +@param dt3dt1 Optional output derivative of tvec3 with regard to tvec1 +@param dt3dr2 Optional output derivative of tvec3 with regard to rvec2 +@param dt3dt2 Optional output derivative of tvec3 with regard to tvec2 + +The functions compute: + +\f[\begin{array}{l} \texttt{rvec3} = \mathrm{rodrigues} ^{-1} \left ( \mathrm{rodrigues} ( \texttt{rvec2} ) \cdot \mathrm{rodrigues} ( \texttt{rvec1} ) \right ) \\ \texttt{tvec3} = \mathrm{rodrigues} ( \texttt{rvec2} ) \cdot \texttt{tvec1} + \texttt{tvec2} \end{array} ,\f] + +where \f$\mathrm{rodrigues}\f$ denotes a rotation vector to a rotation matrix transformation, and +\f$\mathrm{rodrigues}^{-1}\f$ denotes the inverse transformation. See #Rodrigues for details. + +Also, the functions can compute the derivatives of the output vectors with regards to the input +vectors (see #matMulDeriv ). The functions are used inside #stereoCalibrate but can also be used in +your own code where Levenberg-Marquardt or another gradient-based solver is used to optimize a +function that contains a matrix multiplication. + */ +CV_EXPORTS_W void composeRT( InputArray rvec1, InputArray tvec1, + InputArray rvec2, InputArray tvec2, + OutputArray rvec3, OutputArray tvec3, + OutputArray dr3dr1 = noArray(), OutputArray dr3dt1 = noArray(), + OutputArray dr3dr2 = noArray(), OutputArray dr3dt2 = noArray(), + OutputArray dt3dr1 = noArray(), OutputArray dt3dt1 = noArray(), + OutputArray dt3dr2 = noArray(), OutputArray dt3dt2 = noArray() ); + +/** @brief Projects 3D points to an image plane. + +@param objectPoints Array of object points expressed wrt. the world coordinate frame. A 3xN/Nx3 +1-channel or 1xN/Nx1 3-channel (or vector\ ), where N is the number of points in the view. +@param rvec The rotation vector (@ref Rodrigues) that, together with tvec, performs a change of +basis from world to camera coordinate system, see @ref calibrateCamera for details. +@param tvec The translation vector, see parameter description above. +@param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ . +@param distCoeffs Input vector of distortion coefficients +\f$\distcoeffs\f$ . If the vector is empty, the zero distortion coefficients are assumed. +@param imagePoints Output array of image points, 1xN/Nx1 2-channel, or +vector\ . +@param jacobian Optional output 2Nx(10+\) jacobian matrix of derivatives of image +points with respect to components of the rotation vector, translation vector, focal lengths, +coordinates of the principal point and the distortion coefficients. In the old interface different +components of the jacobian are returned via different output parameters. +@param aspectRatio Optional "fixed aspect ratio" parameter. If the parameter is not 0, the +function assumes that the aspect ratio (\f$f_x / f_y\f$) is fixed and correspondingly adjusts the +jacobian matrix. + +The function computes the 2D projections of 3D points to the image plane, given intrinsic and +extrinsic camera parameters. Optionally, the function computes Jacobians -matrices of partial +derivatives of image points coordinates (as functions of all the input parameters) with respect to +the particular parameters, intrinsic and/or extrinsic. The Jacobians are used during the global +optimization in @ref calibrateCamera, @ref solvePnP, and @ref stereoCalibrate. The function itself +can also be used to compute a re-projection error, given the current intrinsic and extrinsic +parameters. + +@note By setting rvec = tvec = \f$[0, 0, 0]\f$, or by setting cameraMatrix to a 3x3 identity matrix, +or by passing zero distortion coefficients, one can get various useful partial cases of the +function. This means, one can compute the distorted coordinates for a sparse set of points or apply +a perspective transformation (and also compute the derivatives) in the ideal zero-distortion setup. + */ +CV_EXPORTS_W void projectPoints( InputArray objectPoints, + InputArray rvec, InputArray tvec, + InputArray cameraMatrix, InputArray distCoeffs, + OutputArray imagePoints, + OutputArray jacobian = noArray(), + double aspectRatio = 0 ); + +/** @example samples/cpp/tutorial_code/features2D/Homography/homography_from_camera_displacement.cpp +An example program about homography from the camera displacement + +Check @ref tutorial_homography "the corresponding tutorial" for more details +*/ + +/** @brief Finds an object pose from 3D-2D point correspondences. + +@see @ref calib3d_solvePnP + +This function returns the rotation and the translation vectors that transform a 3D point expressed in the object +coordinate frame to the camera coordinate frame, using different methods: +- P3P methods (@ref SOLVEPNP_P3P, @ref SOLVEPNP_AP3P): need 4 input points to return a unique solution. +- @ref SOLVEPNP_IPPE Input points must be >= 4 and object points must be coplanar. +- @ref SOLVEPNP_IPPE_SQUARE Special case suitable for marker pose estimation. +Number of input points must be 4. Object points must be defined in the following order: + - point 0: [-squareLength / 2, squareLength / 2, 0] + - point 1: [ squareLength / 2, squareLength / 2, 0] + - point 2: [ squareLength / 2, -squareLength / 2, 0] + - point 3: [-squareLength / 2, -squareLength / 2, 0] +- for all the other flags, number of input points must be >= 4 and object points can be in any configuration. + +@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or +1xN/Nx1 3-channel, where N is the number of points. vector\ can be also passed here. +@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel, +where N is the number of points. vector\ can be also passed here. +@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . +@param distCoeffs Input vector of distortion coefficients +\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are +assumed. +@param rvec Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from +the model coordinate system to the camera coordinate system. +@param tvec Output translation vector. +@param useExtrinsicGuess Parameter used for #SOLVEPNP_ITERATIVE. If true (1), the function uses +the provided rvec and tvec values as initial approximations of the rotation and translation +vectors, respectively, and further optimizes them. +@param flags Method for solving a PnP problem: see @ref calib3d_solvePnP_flags + +More information about Perspective-n-Points is described in @ref calib3d_solvePnP + +@note + - An example of how to use solvePnP for planar augmented reality can be found at + opencv_source_code/samples/python/plane_ar.py + - If you are using Python: + - Numpy array slices won't work as input because solvePnP requires contiguous + arrays (enforced by the assertion using cv::Mat::checkVector() around line 55 of + modules/calib3d/src/solvepnp.cpp version 2.4.9) + - The P3P algorithm requires image points to be in an array of shape (N,1,2) due + to its calling of #undistortPoints (around line 75 of modules/calib3d/src/solvepnp.cpp version 2.4.9) + which requires 2-channel information. + - Thus, given some data D = np.array(...) where D.shape = (N,M), in order to use a subset of + it as, e.g., imagePoints, one must effectively copy it into a new array: imagePoints = + np.ascontiguousarray(D[:,:2]).reshape((N,1,2)) + - The methods @ref SOLVEPNP_DLS and @ref SOLVEPNP_UPNP cannot be used as the current implementations are + unstable and sometimes give completely wrong results. If you pass one of these two + flags, @ref SOLVEPNP_EPNP method will be used instead. + - The minimum number of points is 4 in the general case. In the case of @ref SOLVEPNP_P3P and @ref SOLVEPNP_AP3P + methods, it is required to use exactly 4 points (the first 3 points are used to estimate all the solutions + of the P3P problem, the last one is used to retain the best solution that minimizes the reprojection error). + - With @ref SOLVEPNP_ITERATIVE method and `useExtrinsicGuess=true`, the minimum number of points is 3 (3 points + are sufficient to compute a pose but there are up to 4 solutions). The initial solution should be close to the + global solution to converge. + - With @ref SOLVEPNP_IPPE input points must be >= 4 and object points must be coplanar. + - With @ref SOLVEPNP_IPPE_SQUARE this is a special case suitable for marker pose estimation. + Number of input points must be 4. Object points must be defined in the following order: + - point 0: [-squareLength / 2, squareLength / 2, 0] + - point 1: [ squareLength / 2, squareLength / 2, 0] + - point 2: [ squareLength / 2, -squareLength / 2, 0] + - point 3: [-squareLength / 2, -squareLength / 2, 0] + - With @ref SOLVEPNP_SQPNP input points must be >= 3 + */ +CV_EXPORTS_W bool solvePnP( InputArray objectPoints, InputArray imagePoints, + InputArray cameraMatrix, InputArray distCoeffs, + OutputArray rvec, OutputArray tvec, + bool useExtrinsicGuess = false, int flags = SOLVEPNP_ITERATIVE ); + +/** @brief Finds an object pose from 3D-2D point correspondences using the RANSAC scheme. + +@see @ref calib3d_solvePnP + +@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or +1xN/Nx1 3-channel, where N is the number of points. vector\ can be also passed here. +@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel, +where N is the number of points. vector\ can be also passed here. +@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . +@param distCoeffs Input vector of distortion coefficients +\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are +assumed. +@param rvec Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from +the model coordinate system to the camera coordinate system. +@param tvec Output translation vector. +@param useExtrinsicGuess Parameter used for @ref SOLVEPNP_ITERATIVE. If true (1), the function uses +the provided rvec and tvec values as initial approximations of the rotation and translation +vectors, respectively, and further optimizes them. +@param iterationsCount Number of iterations. +@param reprojectionError Inlier threshold value used by the RANSAC procedure. The parameter value +is the maximum allowed distance between the observed and computed point projections to consider it +an inlier. +@param confidence The probability that the algorithm produces a useful result. +@param inliers Output vector that contains indices of inliers in objectPoints and imagePoints . +@param flags Method for solving a PnP problem (see @ref solvePnP ). + +The function estimates an object pose given a set of object points, their corresponding image +projections, as well as the camera intrinsic matrix and the distortion coefficients. This function finds such +a pose that minimizes reprojection error, that is, the sum of squared distances between the observed +projections imagePoints and the projected (using @ref projectPoints ) objectPoints. The use of RANSAC +makes the function resistant to outliers. + +@note + - An example of how to use solvePNPRansac for object detection can be found at + opencv_source_code/samples/cpp/tutorial_code/calib3d/real_time_pose_estimation/ + - The default method used to estimate the camera pose for the Minimal Sample Sets step + is #SOLVEPNP_EPNP. Exceptions are: + - if you choose #SOLVEPNP_P3P or #SOLVEPNP_AP3P, these methods will be used. + - if the number of input points is equal to 4, #SOLVEPNP_P3P is used. + - The method used to estimate the camera pose using all the inliers is defined by the + flags parameters unless it is equal to #SOLVEPNP_P3P or #SOLVEPNP_AP3P. In this case, + the method #SOLVEPNP_EPNP will be used instead. + */ +CV_EXPORTS_W bool solvePnPRansac( InputArray objectPoints, InputArray imagePoints, + InputArray cameraMatrix, InputArray distCoeffs, + OutputArray rvec, OutputArray tvec, + bool useExtrinsicGuess = false, int iterationsCount = 100, + float reprojectionError = 8.0, double confidence = 0.99, + OutputArray inliers = noArray(), int flags = SOLVEPNP_ITERATIVE ); + + +/* +Finds rotation and translation vector. +If cameraMatrix is given then run P3P. Otherwise run linear P6P and output cameraMatrix too. +*/ +CV_EXPORTS_W bool solvePnPRansac( InputArray objectPoints, InputArray imagePoints, + InputOutputArray cameraMatrix, InputArray distCoeffs, + OutputArray rvec, OutputArray tvec, OutputArray inliers, + const UsacParams ¶ms=UsacParams()); + +/** @brief Finds an object pose from 3 3D-2D point correspondences. + +@see @ref calib3d_solvePnP + +@param objectPoints Array of object points in the object coordinate space, 3x3 1-channel or +1x3/3x1 3-channel. vector\ can be also passed here. +@param imagePoints Array of corresponding image points, 3x2 1-channel or 1x3/3x1 2-channel. + vector\ can be also passed here. +@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . +@param distCoeffs Input vector of distortion coefficients +\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are +assumed. +@param rvecs Output rotation vectors (see @ref Rodrigues ) that, together with tvecs, brings points from +the model coordinate system to the camera coordinate system. A P3P problem has up to 4 solutions. +@param tvecs Output translation vectors. +@param flags Method for solving a P3P problem: +- @ref SOLVEPNP_P3P Method is based on the paper of X.S. Gao, X.-R. Hou, J. Tang, H.-F. Chang +"Complete Solution Classification for the Perspective-Three-Point Problem" (@cite gao2003complete). +- @ref SOLVEPNP_AP3P Method is based on the paper of T. Ke and S. Roumeliotis. +"An Efficient Algebraic Solution to the Perspective-Three-Point Problem" (@cite Ke17). + +The function estimates the object pose given 3 object points, their corresponding image +projections, as well as the camera intrinsic matrix and the distortion coefficients. + +@note +The solutions are sorted by reprojection errors (lowest to highest). + */ +CV_EXPORTS_W int solveP3P( InputArray objectPoints, InputArray imagePoints, + InputArray cameraMatrix, InputArray distCoeffs, + OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, + int flags ); + +/** @brief Refine a pose (the translation and the rotation that transform a 3D point expressed in the object coordinate frame +to the camera coordinate frame) from a 3D-2D point correspondences and starting from an initial solution. + +@see @ref calib3d_solvePnP + +@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or 1xN/Nx1 3-channel, +where N is the number of points. vector\ can also be passed here. +@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel, +where N is the number of points. vector\ can also be passed here. +@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . +@param distCoeffs Input vector of distortion coefficients +\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are +assumed. +@param rvec Input/Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from +the model coordinate system to the camera coordinate system. Input values are used as an initial solution. +@param tvec Input/Output translation vector. Input values are used as an initial solution. +@param criteria Criteria when to stop the Levenberg-Marquard iterative algorithm. + +The function refines the object pose given at least 3 object points, their corresponding image +projections, an initial solution for the rotation and translation vector, +as well as the camera intrinsic matrix and the distortion coefficients. +The function minimizes the projection error with respect to the rotation and the translation vectors, according +to a Levenberg-Marquardt iterative minimization @cite Madsen04 @cite Eade13 process. + */ +CV_EXPORTS_W void solvePnPRefineLM( InputArray objectPoints, InputArray imagePoints, + InputArray cameraMatrix, InputArray distCoeffs, + InputOutputArray rvec, InputOutputArray tvec, + TermCriteria criteria = TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 20, FLT_EPSILON)); + +/** @brief Refine a pose (the translation and the rotation that transform a 3D point expressed in the object coordinate frame +to the camera coordinate frame) from a 3D-2D point correspondences and starting from an initial solution. + +@see @ref calib3d_solvePnP + +@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or 1xN/Nx1 3-channel, +where N is the number of points. vector\ can also be passed here. +@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel, +where N is the number of points. vector\ can also be passed here. +@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . +@param distCoeffs Input vector of distortion coefficients +\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are +assumed. +@param rvec Input/Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from +the model coordinate system to the camera coordinate system. Input values are used as an initial solution. +@param tvec Input/Output translation vector. Input values are used as an initial solution. +@param criteria Criteria when to stop the Levenberg-Marquard iterative algorithm. +@param VVSlambda Gain for the virtual visual servoing control law, equivalent to the \f$\alpha\f$ +gain in the Damped Gauss-Newton formulation. + +The function refines the object pose given at least 3 object points, their corresponding image +projections, an initial solution for the rotation and translation vector, +as well as the camera intrinsic matrix and the distortion coefficients. +The function minimizes the projection error with respect to the rotation and the translation vectors, using a +virtual visual servoing (VVS) @cite Chaumette06 @cite Marchand16 scheme. + */ +CV_EXPORTS_W void solvePnPRefineVVS( InputArray objectPoints, InputArray imagePoints, + InputArray cameraMatrix, InputArray distCoeffs, + InputOutputArray rvec, InputOutputArray tvec, + TermCriteria criteria = TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 20, FLT_EPSILON), + double VVSlambda = 1); + +/** @brief Finds an object pose from 3D-2D point correspondences. + +@see @ref calib3d_solvePnP + +This function returns a list of all the possible solutions (a solution is a +couple), depending on the number of input points and the chosen method: +- P3P methods (@ref SOLVEPNP_P3P, @ref SOLVEPNP_AP3P): 3 or 4 input points. Number of returned solutions can be between 0 and 4 with 3 input points. +- @ref SOLVEPNP_IPPE Input points must be >= 4 and object points must be coplanar. Returns 2 solutions. +- @ref SOLVEPNP_IPPE_SQUARE Special case suitable for marker pose estimation. +Number of input points must be 4 and 2 solutions are returned. Object points must be defined in the following order: + - point 0: [-squareLength / 2, squareLength / 2, 0] + - point 1: [ squareLength / 2, squareLength / 2, 0] + - point 2: [ squareLength / 2, -squareLength / 2, 0] + - point 3: [-squareLength / 2, -squareLength / 2, 0] +- for all the other flags, number of input points must be >= 4 and object points can be in any configuration. +Only 1 solution is returned. + +@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or +1xN/Nx1 3-channel, where N is the number of points. vector\ can be also passed here. +@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel, +where N is the number of points. vector\ can be also passed here. +@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . +@param distCoeffs Input vector of distortion coefficients +\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are +assumed. +@param rvecs Vector of output rotation vectors (see @ref Rodrigues ) that, together with tvecs, brings points from +the model coordinate system to the camera coordinate system. +@param tvecs Vector of output translation vectors. +@param useExtrinsicGuess Parameter used for #SOLVEPNP_ITERATIVE. If true (1), the function uses +the provided rvec and tvec values as initial approximations of the rotation and translation +vectors, respectively, and further optimizes them. +@param flags Method for solving a PnP problem: see @ref calib3d_solvePnP_flags +@param rvec Rotation vector used to initialize an iterative PnP refinement algorithm, when flag is @ref SOLVEPNP_ITERATIVE +and useExtrinsicGuess is set to true. +@param tvec Translation vector used to initialize an iterative PnP refinement algorithm, when flag is @ref SOLVEPNP_ITERATIVE +and useExtrinsicGuess is set to true. +@param reprojectionError Optional vector of reprojection error, that is the RMS error +(\f$ \text{RMSE} = \sqrt{\frac{\sum_{i}^{N} \left ( \hat{y_i} - y_i \right )^2}{N}} \f$) between the input image points +and the 3D object points projected with the estimated pose. + +More information is described in @ref calib3d_solvePnP + +@note + - An example of how to use solvePnP for planar augmented reality can be found at + opencv_source_code/samples/python/plane_ar.py + - If you are using Python: + - Numpy array slices won't work as input because solvePnP requires contiguous + arrays (enforced by the assertion using cv::Mat::checkVector() around line 55 of + modules/calib3d/src/solvepnp.cpp version 2.4.9) + - The P3P algorithm requires image points to be in an array of shape (N,1,2) due + to its calling of #undistortPoints (around line 75 of modules/calib3d/src/solvepnp.cpp version 2.4.9) + which requires 2-channel information. + - Thus, given some data D = np.array(...) where D.shape = (N,M), in order to use a subset of + it as, e.g., imagePoints, one must effectively copy it into a new array: imagePoints = + np.ascontiguousarray(D[:,:2]).reshape((N,1,2)) + - The methods @ref SOLVEPNP_DLS and @ref SOLVEPNP_UPNP cannot be used as the current implementations are + unstable and sometimes give completely wrong results. If you pass one of these two + flags, @ref SOLVEPNP_EPNP method will be used instead. + - The minimum number of points is 4 in the general case. In the case of @ref SOLVEPNP_P3P and @ref SOLVEPNP_AP3P + methods, it is required to use exactly 4 points (the first 3 points are used to estimate all the solutions + of the P3P problem, the last one is used to retain the best solution that minimizes the reprojection error). + - With @ref SOLVEPNP_ITERATIVE method and `useExtrinsicGuess=true`, the minimum number of points is 3 (3 points + are sufficient to compute a pose but there are up to 4 solutions). The initial solution should be close to the + global solution to converge. + - With @ref SOLVEPNP_IPPE input points must be >= 4 and object points must be coplanar. + - With @ref SOLVEPNP_IPPE_SQUARE this is a special case suitable for marker pose estimation. + Number of input points must be 4. Object points must be defined in the following order: + - point 0: [-squareLength / 2, squareLength / 2, 0] + - point 1: [ squareLength / 2, squareLength / 2, 0] + - point 2: [ squareLength / 2, -squareLength / 2, 0] + - point 3: [-squareLength / 2, -squareLength / 2, 0] + */ +CV_EXPORTS_W int solvePnPGeneric( InputArray objectPoints, InputArray imagePoints, + InputArray cameraMatrix, InputArray distCoeffs, + OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, + bool useExtrinsicGuess = false, SolvePnPMethod flags = SOLVEPNP_ITERATIVE, + InputArray rvec = noArray(), InputArray tvec = noArray(), + OutputArray reprojectionError = noArray() ); + +/** @brief Finds an initial camera intrinsic matrix from 3D-2D point correspondences. + +@param objectPoints Vector of vectors of the calibration pattern points in the calibration pattern +coordinate space. In the old interface all the per-view vectors are concatenated. See +#calibrateCamera for details. +@param imagePoints Vector of vectors of the projections of the calibration pattern points. In the +old interface all the per-view vectors are concatenated. +@param imageSize Image size in pixels used to initialize the principal point. +@param aspectRatio If it is zero or negative, both \f$f_x\f$ and \f$f_y\f$ are estimated independently. +Otherwise, \f$f_x = f_y \cdot \texttt{aspectRatio}\f$ . + +The function estimates and returns an initial camera intrinsic matrix for the camera calibration process. +Currently, the function only supports planar calibration patterns, which are patterns where each +object point has z-coordinate =0. + */ +CV_EXPORTS_W Mat initCameraMatrix2D( InputArrayOfArrays objectPoints, + InputArrayOfArrays imagePoints, + Size imageSize, double aspectRatio = 1.0 ); + +/** @brief Finds the positions of internal corners of the chessboard. + +@param image Source chessboard view. It must be an 8-bit grayscale or color image. +@param patternSize Number of inner corners per a chessboard row and column +( patternSize = cv::Size(points_per_row,points_per_colum) = cv::Size(columns,rows) ). +@param corners Output array of detected corners. +@param flags Various operation flags that can be zero or a combination of the following values: +- @ref CALIB_CB_ADAPTIVE_THRESH Use adaptive thresholding to convert the image to black +and white, rather than a fixed threshold level (computed from the average image brightness). +- @ref CALIB_CB_NORMALIZE_IMAGE Normalize the image gamma with #equalizeHist before +applying fixed or adaptive thresholding. +- @ref CALIB_CB_FILTER_QUADS Use additional criteria (like contour area, perimeter, +square-like shape) to filter out false quads extracted at the contour retrieval stage. +- @ref CALIB_CB_FAST_CHECK Run a fast check on the image that looks for chessboard corners, +and shortcut the call if none is found. This can drastically speed up the call in the +degenerate condition when no chessboard is observed. +- @ref CALIB_CB_PLAIN All other flags are ignored. The input image is taken as is. +No image processing is done to improve to find the checkerboard. This has the effect of speeding up the +execution of the function but could lead to not recognizing the checkerboard if the image +is not previously binarized in the appropriate manner. + +The function attempts to determine whether the input image is a view of the chessboard pattern and +locate the internal chessboard corners. The function returns a non-zero value if all of the corners +are found and they are placed in a certain order (row by row, left to right in every row). +Otherwise, if the function fails to find all the corners or reorder them, it returns 0. For example, +a regular chessboard has 8 x 8 squares and 7 x 7 internal corners, that is, points where the black +squares touch each other. The detected coordinates are approximate, and to determine their positions +more accurately, the function calls #cornerSubPix. You also may use the function #cornerSubPix with +different parameters if returned coordinates are not accurate enough. + +Sample usage of detecting and drawing chessboard corners: : +@code + Size patternsize(8,6); //interior number of corners + Mat gray = ....; //source image + vector corners; //this will be filled by the detected corners + + //CALIB_CB_FAST_CHECK saves a lot of time on images + //that do not contain any chessboard corners + bool patternfound = findChessboardCorners(gray, patternsize, corners, + CALIB_CB_ADAPTIVE_THRESH + CALIB_CB_NORMALIZE_IMAGE + + CALIB_CB_FAST_CHECK); + + if(patternfound) + cornerSubPix(gray, corners, Size(11, 11), Size(-1, -1), + TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1)); + + drawChessboardCorners(img, patternsize, Mat(corners), patternfound); +@endcode +@note The function requires white space (like a square-thick border, the wider the better) around +the board to make the detection more robust in various environments. Otherwise, if there is no +border and the background is dark, the outer black squares cannot be segmented properly and so the +square grouping and ordering algorithm fails. + +Use gen_pattern.py (@ref tutorial_camera_calibration_pattern) to create checkerboard. + */ +CV_EXPORTS_W bool findChessboardCorners( InputArray image, Size patternSize, OutputArray corners, + int flags = CALIB_CB_ADAPTIVE_THRESH + CALIB_CB_NORMALIZE_IMAGE ); + +/* + Checks whether the image contains chessboard of the specific size or not. + If yes, nonzero value is returned. +*/ +CV_EXPORTS_W bool checkChessboard(InputArray img, Size size); + +/** @brief Finds the positions of internal corners of the chessboard using a sector based approach. + +@param image Source chessboard view. It must be an 8-bit grayscale or color image. +@param patternSize Number of inner corners per a chessboard row and column +( patternSize = cv::Size(points_per_row,points_per_colum) = cv::Size(columns,rows) ). +@param corners Output array of detected corners. +@param flags Various operation flags that can be zero or a combination of the following values: +- @ref CALIB_CB_NORMALIZE_IMAGE Normalize the image gamma with equalizeHist before detection. +- @ref CALIB_CB_EXHAUSTIVE Run an exhaustive search to improve detection rate. +- @ref CALIB_CB_ACCURACY Up sample input image to improve sub-pixel accuracy due to aliasing effects. +- @ref CALIB_CB_LARGER The detected pattern is allowed to be larger than patternSize (see description). +- @ref CALIB_CB_MARKER The detected pattern must have a marker (see description). +This should be used if an accurate camera calibration is required. +@param meta Optional output arrray of detected corners (CV_8UC1 and size = cv::Size(columns,rows)). +Each entry stands for one corner of the pattern and can have one of the following values: +- 0 = no meta data attached +- 1 = left-top corner of a black cell +- 2 = left-top corner of a white cell +- 3 = left-top corner of a black cell with a white marker dot +- 4 = left-top corner of a white cell with a black marker dot (pattern origin in case of markers otherwise first corner) + +The function is analog to #findChessboardCorners but uses a localized radon +transformation approximated by box filters being more robust to all sort of +noise, faster on larger images and is able to directly return the sub-pixel +position of the internal chessboard corners. The Method is based on the paper +@cite duda2018 "Accurate Detection and Localization of Checkerboard Corners for +Calibration" demonstrating that the returned sub-pixel positions are more +accurate than the one returned by cornerSubPix allowing a precise camera +calibration for demanding applications. + +In the case, the flags @ref CALIB_CB_LARGER or @ref CALIB_CB_MARKER are given, +the result can be recovered from the optional meta array. Both flags are +helpful to use calibration patterns exceeding the field of view of the camera. +These oversized patterns allow more accurate calibrations as corners can be +utilized, which are as close as possible to the image borders. For a +consistent coordinate system across all images, the optional marker (see image +below) can be used to move the origin of the board to the location where the +black circle is located. + +@note The function requires a white boarder with roughly the same width as one +of the checkerboard fields around the whole board to improve the detection in +various environments. In addition, because of the localized radon +transformation it is beneficial to use round corners for the field corners +which are located on the outside of the board. The following figure illustrates +a sample checkerboard optimized for the detection. However, any other checkerboard +can be used as well. + +Use gen_pattern.py (@ref tutorial_camera_calibration_pattern) to create checkerboard. +![Checkerboard](pics/checkerboard_radon.png) + */ +CV_EXPORTS_AS(findChessboardCornersSBWithMeta) +bool findChessboardCornersSB(InputArray image,Size patternSize, OutputArray corners, + int flags,OutputArray meta); +/** @overload */ +CV_EXPORTS_W inline +bool findChessboardCornersSB(InputArray image, Size patternSize, OutputArray corners, + int flags = 0) +{ + return findChessboardCornersSB(image, patternSize, corners, flags, noArray()); +} + +/** @brief Estimates the sharpness of a detected chessboard. + +Image sharpness, as well as brightness, are a critical parameter for accuracte +camera calibration. For accessing these parameters for filtering out +problematic calibraiton images, this method calculates edge profiles by traveling from +black to white chessboard cell centers. Based on this, the number of pixels is +calculated required to transit from black to white. This width of the +transition area is a good indication of how sharp the chessboard is imaged +and should be below ~3.0 pixels. + +@param image Gray image used to find chessboard corners +@param patternSize Size of a found chessboard pattern +@param corners Corners found by #findChessboardCornersSB +@param rise_distance Rise distance 0.8 means 10% ... 90% of the final signal strength +@param vertical By default edge responses for horizontal lines are calculated +@param sharpness Optional output array with a sharpness value for calculated edge responses (see description) + +The optional sharpness array is of type CV_32FC1 and has for each calculated +profile one row with the following five entries: +* 0 = x coordinate of the underlying edge in the image +* 1 = y coordinate of the underlying edge in the image +* 2 = width of the transition area (sharpness) +* 3 = signal strength in the black cell (min brightness) +* 4 = signal strength in the white cell (max brightness) + +@return Scalar(average sharpness, average min brightness, average max brightness,0) +*/ +CV_EXPORTS_W Scalar estimateChessboardSharpness(InputArray image, Size patternSize, InputArray corners, + float rise_distance=0.8F,bool vertical=false, + OutputArray sharpness=noArray()); + + +//! finds subpixel-accurate positions of the chessboard corners +CV_EXPORTS_W bool find4QuadCornerSubpix( InputArray img, InputOutputArray corners, Size region_size ); + +/** @brief Renders the detected chessboard corners. + +@param image Destination image. It must be an 8-bit color image. +@param patternSize Number of inner corners per a chessboard row and column +(patternSize = cv::Size(points_per_row,points_per_column)). +@param corners Array of detected corners, the output of #findChessboardCorners. +@param patternWasFound Parameter indicating whether the complete board was found or not. The +return value of #findChessboardCorners should be passed here. + +The function draws individual chessboard corners detected either as red circles if the board was not +found, or as colored corners connected with lines if the board was found. + */ +CV_EXPORTS_W void drawChessboardCorners( InputOutputArray image, Size patternSize, + InputArray corners, bool patternWasFound ); + +/** @brief Draw axes of the world/object coordinate system from pose estimation. @sa solvePnP + +@param image Input/output image. It must have 1 or 3 channels. The number of channels is not altered. +@param cameraMatrix Input 3x3 floating-point matrix of camera intrinsic parameters. +\f$\cameramatrix{A}\f$ +@param distCoeffs Input vector of distortion coefficients +\f$\distcoeffs\f$. If the vector is empty, the zero distortion coefficients are assumed. +@param rvec Rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from +the model coordinate system to the camera coordinate system. +@param tvec Translation vector. +@param length Length of the painted axes in the same unit than tvec (usually in meters). +@param thickness Line thickness of the painted axes. + +This function draws the axes of the world/object coordinate system w.r.t. to the camera frame. +OX is drawn in red, OY in green and OZ in blue. + */ +CV_EXPORTS_W void drawFrameAxes(InputOutputArray image, InputArray cameraMatrix, InputArray distCoeffs, + InputArray rvec, InputArray tvec, float length, int thickness=3); + +struct CV_EXPORTS_W_SIMPLE CirclesGridFinderParameters +{ + CV_WRAP CirclesGridFinderParameters(); + CV_PROP_RW cv::Size2f densityNeighborhoodSize; + CV_PROP_RW float minDensity; + CV_PROP_RW int kmeansAttempts; + CV_PROP_RW int minDistanceToAddKeypoint; + CV_PROP_RW int keypointScale; + CV_PROP_RW float minGraphConfidence; + CV_PROP_RW float vertexGain; + CV_PROP_RW float vertexPenalty; + CV_PROP_RW float existingVertexGain; + CV_PROP_RW float edgeGain; + CV_PROP_RW float edgePenalty; + CV_PROP_RW float convexHullFactor; + CV_PROP_RW float minRNGEdgeSwitchDist; + + enum GridType + { + SYMMETRIC_GRID, ASYMMETRIC_GRID + }; + GridType gridType; + + CV_PROP_RW float squareSize; //!< Distance between two adjacent points. Used by CALIB_CB_CLUSTERING. + CV_PROP_RW float maxRectifiedDistance; //!< Max deviation from prediction. Used by CALIB_CB_CLUSTERING. +}; + +#ifndef DISABLE_OPENCV_3_COMPATIBILITY +typedef CirclesGridFinderParameters CirclesGridFinderParameters2; +#endif + +/** @brief Finds centers in the grid of circles. + +@param image grid view of input circles; it must be an 8-bit grayscale or color image. +@param patternSize number of circles per row and column +( patternSize = Size(points_per_row, points_per_colum) ). +@param centers output array of detected centers. +@param flags various operation flags that can be one of the following values: +- @ref CALIB_CB_SYMMETRIC_GRID uses symmetric pattern of circles. +- @ref CALIB_CB_ASYMMETRIC_GRID uses asymmetric pattern of circles. +- @ref CALIB_CB_CLUSTERING uses a special algorithm for grid detection. It is more robust to +perspective distortions but much more sensitive to background clutter. +@param blobDetector feature detector that finds blobs like dark circles on light background. + If `blobDetector` is NULL then `image` represents Point2f array of candidates. +@param parameters struct for finding circles in a grid pattern. + +The function attempts to determine whether the input image contains a grid of circles. If it is, the +function locates centers of the circles. The function returns a non-zero value if all of the centers +have been found and they have been placed in a certain order (row by row, left to right in every +row). Otherwise, if the function fails to find all the corners or reorder them, it returns 0. + +Sample usage of detecting and drawing the centers of circles: : +@code + Size patternsize(7,7); //number of centers + Mat gray = ...; //source image + vector centers; //this will be filled by the detected centers + + bool patternfound = findCirclesGrid(gray, patternsize, centers); + + drawChessboardCorners(img, patternsize, Mat(centers), patternfound); +@endcode +@note The function requires white space (like a square-thick border, the wider the better) around +the board to make the detection more robust in various environments. + */ +CV_EXPORTS_W bool findCirclesGrid( InputArray image, Size patternSize, + OutputArray centers, int flags, + const Ptr &blobDetector, + const CirclesGridFinderParameters& parameters); + +/** @overload */ +CV_EXPORTS_W bool findCirclesGrid( InputArray image, Size patternSize, + OutputArray centers, int flags = CALIB_CB_SYMMETRIC_GRID, + const Ptr &blobDetector = SimpleBlobDetector::create()); + +/** @brief Finds the camera intrinsic and extrinsic parameters from several views of a calibration +pattern. + +@param objectPoints In the new interface it is a vector of vectors of calibration pattern points in +the calibration pattern coordinate space (e.g. std::vector>). The outer +vector contains as many elements as the number of pattern views. If the same calibration pattern +is shown in each view and it is fully visible, all the vectors will be the same. Although, it is +possible to use partially occluded patterns or even different patterns in different views. Then, +the vectors will be different. Although the points are 3D, they all lie in the calibration pattern's +XY coordinate plane (thus 0 in the Z-coordinate), if the used calibration pattern is a planar rig. +In the old interface all the vectors of object points from different views are concatenated +together. +@param imagePoints In the new interface it is a vector of vectors of the projections of calibration +pattern points (e.g. std::vector>). imagePoints.size() and +objectPoints.size(), and imagePoints[i].size() and objectPoints[i].size() for each i, must be equal, +respectively. In the old interface all the vectors of object points from different views are +concatenated together. +@param imageSize Size of the image used only to initialize the camera intrinsic matrix. +@param cameraMatrix Input/output 3x3 floating-point camera intrinsic matrix +\f$\cameramatrix{A}\f$ . If @ref CALIB_USE_INTRINSIC_GUESS +and/or @ref CALIB_FIX_ASPECT_RATIO, @ref CALIB_FIX_PRINCIPAL_POINT or @ref CALIB_FIX_FOCAL_LENGTH +are specified, some or all of fx, fy, cx, cy must be initialized before calling the function. +@param distCoeffs Input/output vector of distortion coefficients +\f$\distcoeffs\f$. +@param rvecs Output vector of rotation vectors (@ref Rodrigues ) estimated for each pattern view +(e.g. std::vector>). That is, each i-th rotation vector together with the corresponding +i-th translation vector (see the next output parameter description) brings the calibration pattern +from the object coordinate space (in which object points are specified) to the camera coordinate +space. In more technical terms, the tuple of the i-th rotation and translation vector performs +a change of basis from object coordinate space to camera coordinate space. Due to its duality, this +tuple is equivalent to the position of the calibration pattern with respect to the camera coordinate +space. +@param tvecs Output vector of translation vectors estimated for each pattern view, see parameter +describtion above. +@param stdDeviationsIntrinsics Output vector of standard deviations estimated for intrinsic +parameters. Order of deviations values: +\f$(f_x, f_y, c_x, c_y, k_1, k_2, p_1, p_2, k_3, k_4, k_5, k_6 , s_1, s_2, s_3, + s_4, \tau_x, \tau_y)\f$ If one of parameters is not estimated, it's deviation is equals to zero. +@param stdDeviationsExtrinsics Output vector of standard deviations estimated for extrinsic +parameters. Order of deviations values: \f$(R_0, T_0, \dotsc , R_{M - 1}, T_{M - 1})\f$ where M is +the number of pattern views. \f$R_i, T_i\f$ are concatenated 1x3 vectors. + @param perViewErrors Output vector of the RMS re-projection error estimated for each pattern view. +@param flags Different flags that may be zero or a combination of the following values: +- @ref CALIB_USE_INTRINSIC_GUESS cameraMatrix contains valid initial values of +fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image +center ( imageSize is used), and focal distances are computed in a least-squares fashion. +Note, that if intrinsic parameters are known, there is no need to use this function just to +estimate extrinsic parameters. Use @ref solvePnP instead. +- @ref CALIB_FIX_PRINCIPAL_POINT The principal point is not changed during the global +optimization. It stays at the center or at a different location specified when + @ref CALIB_USE_INTRINSIC_GUESS is set too. +- @ref CALIB_FIX_ASPECT_RATIO The functions consider only fy as a free parameter. The +ratio fx/fy stays the same as in the input cameraMatrix . When + @ref CALIB_USE_INTRINSIC_GUESS is not set, the actual input values of fx and fy are +ignored, only their ratio is computed and used further. +- @ref CALIB_ZERO_TANGENT_DIST Tangential distortion coefficients \f$(p_1, p_2)\f$ are set +to zeros and stay zero. +- @ref CALIB_FIX_FOCAL_LENGTH The focal length is not changed during the global optimization if + @ref CALIB_USE_INTRINSIC_GUESS is set. +- @ref CALIB_FIX_K1,..., @ref CALIB_FIX_K6 The corresponding radial distortion +coefficient is not changed during the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is +set, the coefficient from the supplied distCoeffs matrix is used. Otherwise, it is set to 0. +- @ref CALIB_RATIONAL_MODEL Coefficients k4, k5, and k6 are enabled. To provide the +backward compatibility, this extra flag should be explicitly specified to make the +calibration function use the rational model and return 8 coefficients or more. +- @ref CALIB_THIN_PRISM_MODEL Coefficients s1, s2, s3 and s4 are enabled. To provide the +backward compatibility, this extra flag should be explicitly specified to make the +calibration function use the thin prism model and return 12 coefficients or more. +- @ref CALIB_FIX_S1_S2_S3_S4 The thin prism distortion coefficients are not changed during +the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the +supplied distCoeffs matrix is used. Otherwise, it is set to 0. +- @ref CALIB_TILTED_MODEL Coefficients tauX and tauY are enabled. To provide the +backward compatibility, this extra flag should be explicitly specified to make the +calibration function use the tilted sensor model and return 14 coefficients. +- @ref CALIB_FIX_TAUX_TAUY The coefficients of the tilted sensor model are not changed during +the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the +supplied distCoeffs matrix is used. Otherwise, it is set to 0. +@param criteria Termination criteria for the iterative optimization algorithm. + +@return the overall RMS re-projection error. + +The function estimates the intrinsic camera parameters and extrinsic parameters for each of the +views. The algorithm is based on @cite Zhang2000 and @cite BouguetMCT . The coordinates of 3D object +points and their corresponding 2D projections in each view must be specified. That may be achieved +by using an object with known geometry and easily detectable feature points. Such an object is +called a calibration rig or calibration pattern, and OpenCV has built-in support for a chessboard as +a calibration rig (see @ref findChessboardCorners). Currently, initialization of intrinsic +parameters (when @ref CALIB_USE_INTRINSIC_GUESS is not set) is only implemented for planar calibration +patterns (where Z-coordinates of the object points must be all zeros). 3D calibration rigs can also +be used as long as initial cameraMatrix is provided. + +The algorithm performs the following steps: + +- Compute the initial intrinsic parameters (the option only available for planar calibration + patterns) or read them from the input parameters. The distortion coefficients are all set to + zeros initially unless some of CALIB_FIX_K? are specified. + +- Estimate the initial camera pose as if the intrinsic parameters have been already known. This is + done using @ref solvePnP . + +- Run the global Levenberg-Marquardt optimization algorithm to minimize the reprojection error, + that is, the total sum of squared distances between the observed feature points imagePoints and + the projected (using the current estimates for camera parameters and the poses) object points + objectPoints. See @ref projectPoints for details. + +@note + If you use a non-square (i.e. non-N-by-N) grid and @ref findChessboardCorners for calibration, + and @ref calibrateCamera returns bad values (zero distortion coefficients, \f$c_x\f$ and + \f$c_y\f$ very far from the image center, and/or large differences between \f$f_x\f$ and + \f$f_y\f$ (ratios of 10:1 or more)), then you are probably using patternSize=cvSize(rows,cols) + instead of using patternSize=cvSize(cols,rows) in @ref findChessboardCorners. + +@note + The function may throw exceptions, if unsupported combination of parameters is provided or + the system is underconstrained. + +@sa + calibrateCameraRO, findChessboardCorners, solvePnP, initCameraMatrix2D, stereoCalibrate, + undistort + */ +CV_EXPORTS_AS(calibrateCameraExtended) double calibrateCamera( InputArrayOfArrays objectPoints, + InputArrayOfArrays imagePoints, Size imageSize, + InputOutputArray cameraMatrix, InputOutputArray distCoeffs, + OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, + OutputArray stdDeviationsIntrinsics, + OutputArray stdDeviationsExtrinsics, + OutputArray perViewErrors, + int flags = 0, TermCriteria criteria = TermCriteria( + TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) ); + +/** @overload */ +CV_EXPORTS_W double calibrateCamera( InputArrayOfArrays objectPoints, + InputArrayOfArrays imagePoints, Size imageSize, + InputOutputArray cameraMatrix, InputOutputArray distCoeffs, + OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, + int flags = 0, TermCriteria criteria = TermCriteria( + TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) ); + +/** @brief Finds the camera intrinsic and extrinsic parameters from several views of a calibration pattern. + +This function is an extension of #calibrateCamera with the method of releasing object which was +proposed in @cite strobl2011iccv. In many common cases with inaccurate, unmeasured, roughly planar +targets (calibration plates), this method can dramatically improve the precision of the estimated +camera parameters. Both the object-releasing method and standard method are supported by this +function. Use the parameter **iFixedPoint** for method selection. In the internal implementation, +#calibrateCamera is a wrapper for this function. + +@param objectPoints Vector of vectors of calibration pattern points in the calibration pattern +coordinate space. See #calibrateCamera for details. If the method of releasing object to be used, +the identical calibration board must be used in each view and it must be fully visible, and all +objectPoints[i] must be the same and all points should be roughly close to a plane. **The calibration +target has to be rigid, or at least static if the camera (rather than the calibration target) is +shifted for grabbing images.** +@param imagePoints Vector of vectors of the projections of calibration pattern points. See +#calibrateCamera for details. +@param imageSize Size of the image used only to initialize the intrinsic camera matrix. +@param iFixedPoint The index of the 3D object point in objectPoints[0] to be fixed. It also acts as +a switch for calibration method selection. If object-releasing method to be used, pass in the +parameter in the range of [1, objectPoints[0].size()-2], otherwise a value out of this range will +make standard calibration method selected. Usually the top-right corner point of the calibration +board grid is recommended to be fixed when object-releasing method being utilized. According to +\cite strobl2011iccv, two other points are also fixed. In this implementation, objectPoints[0].front +and objectPoints[0].back.z are used. With object-releasing method, accurate rvecs, tvecs and +newObjPoints are only possible if coordinates of these three fixed points are accurate enough. +@param cameraMatrix Output 3x3 floating-point camera matrix. See #calibrateCamera for details. +@param distCoeffs Output vector of distortion coefficients. See #calibrateCamera for details. +@param rvecs Output vector of rotation vectors estimated for each pattern view. See #calibrateCamera +for details. +@param tvecs Output vector of translation vectors estimated for each pattern view. +@param newObjPoints The updated output vector of calibration pattern points. The coordinates might +be scaled based on three fixed points. The returned coordinates are accurate only if the above +mentioned three fixed points are accurate. If not needed, noArray() can be passed in. This parameter +is ignored with standard calibration method. +@param stdDeviationsIntrinsics Output vector of standard deviations estimated for intrinsic parameters. +See #calibrateCamera for details. +@param stdDeviationsExtrinsics Output vector of standard deviations estimated for extrinsic parameters. +See #calibrateCamera for details. +@param stdDeviationsObjPoints Output vector of standard deviations estimated for refined coordinates +of calibration pattern points. It has the same size and order as objectPoints[0] vector. This +parameter is ignored with standard calibration method. + @param perViewErrors Output vector of the RMS re-projection error estimated for each pattern view. +@param flags Different flags that may be zero or a combination of some predefined values. See +#calibrateCamera for details. If the method of releasing object is used, the calibration time may +be much longer. CALIB_USE_QR or CALIB_USE_LU could be used for faster calibration with potentially +less precise and less stable in some rare cases. +@param criteria Termination criteria for the iterative optimization algorithm. + +@return the overall RMS re-projection error. + +The function estimates the intrinsic camera parameters and extrinsic parameters for each of the +views. The algorithm is based on @cite Zhang2000, @cite BouguetMCT and @cite strobl2011iccv. See +#calibrateCamera for other detailed explanations. +@sa + calibrateCamera, findChessboardCorners, solvePnP, initCameraMatrix2D, stereoCalibrate, undistort + */ +CV_EXPORTS_AS(calibrateCameraROExtended) double calibrateCameraRO( InputArrayOfArrays objectPoints, + InputArrayOfArrays imagePoints, Size imageSize, int iFixedPoint, + InputOutputArray cameraMatrix, InputOutputArray distCoeffs, + OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, + OutputArray newObjPoints, + OutputArray stdDeviationsIntrinsics, + OutputArray stdDeviationsExtrinsics, + OutputArray stdDeviationsObjPoints, + OutputArray perViewErrors, + int flags = 0, TermCriteria criteria = TermCriteria( + TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) ); + +/** @overload */ +CV_EXPORTS_W double calibrateCameraRO( InputArrayOfArrays objectPoints, + InputArrayOfArrays imagePoints, Size imageSize, int iFixedPoint, + InputOutputArray cameraMatrix, InputOutputArray distCoeffs, + OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, + OutputArray newObjPoints, + int flags = 0, TermCriteria criteria = TermCriteria( + TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) ); + +/** @brief Computes useful camera characteristics from the camera intrinsic matrix. + +@param cameraMatrix Input camera intrinsic matrix that can be estimated by #calibrateCamera or +#stereoCalibrate . +@param imageSize Input image size in pixels. +@param apertureWidth Physical width in mm of the sensor. +@param apertureHeight Physical height in mm of the sensor. +@param fovx Output field of view in degrees along the horizontal sensor axis. +@param fovy Output field of view in degrees along the vertical sensor axis. +@param focalLength Focal length of the lens in mm. +@param principalPoint Principal point in mm. +@param aspectRatio \f$f_y/f_x\f$ + +The function computes various useful camera characteristics from the previously estimated camera +matrix. + +@note + Do keep in mind that the unity measure 'mm' stands for whatever unit of measure one chooses for + the chessboard pitch (it can thus be any value). + */ +CV_EXPORTS_W void calibrationMatrixValues( InputArray cameraMatrix, Size imageSize, + double apertureWidth, double apertureHeight, + CV_OUT double& fovx, CV_OUT double& fovy, + CV_OUT double& focalLength, CV_OUT Point2d& principalPoint, + CV_OUT double& aspectRatio ); + +/** @brief Calibrates a stereo camera set up. This function finds the intrinsic parameters +for each of the two cameras and the extrinsic parameters between the two cameras. + +@param objectPoints Vector of vectors of the calibration pattern points. The same structure as +in @ref calibrateCamera. For each pattern view, both cameras need to see the same object +points. Therefore, objectPoints.size(), imagePoints1.size(), and imagePoints2.size() need to be +equal as well as objectPoints[i].size(), imagePoints1[i].size(), and imagePoints2[i].size() need to +be equal for each i. +@param imagePoints1 Vector of vectors of the projections of the calibration pattern points, +observed by the first camera. The same structure as in @ref calibrateCamera. +@param imagePoints2 Vector of vectors of the projections of the calibration pattern points, +observed by the second camera. The same structure as in @ref calibrateCamera. +@param cameraMatrix1 Input/output camera intrinsic matrix for the first camera, the same as in +@ref calibrateCamera. Furthermore, for the stereo case, additional flags may be used, see below. +@param distCoeffs1 Input/output vector of distortion coefficients, the same as in +@ref calibrateCamera. +@param cameraMatrix2 Input/output second camera intrinsic matrix for the second camera. See description for +cameraMatrix1. +@param distCoeffs2 Input/output lens distortion coefficients for the second camera. See +description for distCoeffs1. +@param imageSize Size of the image used only to initialize the camera intrinsic matrices. +@param R Output rotation matrix. Together with the translation vector T, this matrix brings +points given in the first camera's coordinate system to points in the second camera's +coordinate system. In more technical terms, the tuple of R and T performs a change of basis +from the first camera's coordinate system to the second camera's coordinate system. Due to its +duality, this tuple is equivalent to the position of the first camera with respect to the +second camera coordinate system. +@param T Output translation vector, see description above. +@param E Output essential matrix. +@param F Output fundamental matrix. +@param rvecs Output vector of rotation vectors ( @ref Rodrigues ) estimated for each pattern view in the +coordinate system of the first camera of the stereo pair (e.g. std::vector). More in detail, each +i-th rotation vector together with the corresponding i-th translation vector (see the next output parameter +description) brings the calibration pattern from the object coordinate space (in which object points are +specified) to the camera coordinate space of the first camera of the stereo pair. In more technical terms, +the tuple of the i-th rotation and translation vector performs a change of basis from object coordinate space +to camera coordinate space of the first camera of the stereo pair. +@param tvecs Output vector of translation vectors estimated for each pattern view, see parameter description +of previous output parameter ( rvecs ). +@param perViewErrors Output vector of the RMS re-projection error estimated for each pattern view. +@param flags Different flags that may be zero or a combination of the following values: +- @ref CALIB_FIX_INTRINSIC Fix cameraMatrix? and distCoeffs? so that only R, T, E, and F +matrices are estimated. +- @ref CALIB_USE_INTRINSIC_GUESS Optimize some or all of the intrinsic parameters +according to the specified flags. Initial values are provided by the user. +- @ref CALIB_USE_EXTRINSIC_GUESS R and T contain valid initial values that are optimized further. +Otherwise R and T are initialized to the median value of the pattern views (each dimension separately). +- @ref CALIB_FIX_PRINCIPAL_POINT Fix the principal points during the optimization. +- @ref CALIB_FIX_FOCAL_LENGTH Fix \f$f^{(j)}_x\f$ and \f$f^{(j)}_y\f$ . +- @ref CALIB_FIX_ASPECT_RATIO Optimize \f$f^{(j)}_y\f$ . Fix the ratio \f$f^{(j)}_x/f^{(j)}_y\f$ +. +- @ref CALIB_SAME_FOCAL_LENGTH Enforce \f$f^{(0)}_x=f^{(1)}_x\f$ and \f$f^{(0)}_y=f^{(1)}_y\f$ . +- @ref CALIB_ZERO_TANGENT_DIST Set tangential distortion coefficients for each camera to +zeros and fix there. +- @ref CALIB_FIX_K1,..., @ref CALIB_FIX_K6 Do not change the corresponding radial +distortion coefficient during the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, +the coefficient from the supplied distCoeffs matrix is used. Otherwise, it is set to 0. +- @ref CALIB_RATIONAL_MODEL Enable coefficients k4, k5, and k6. To provide the backward +compatibility, this extra flag should be explicitly specified to make the calibration +function use the rational model and return 8 coefficients. If the flag is not set, the +function computes and returns only 5 distortion coefficients. +- @ref CALIB_THIN_PRISM_MODEL Coefficients s1, s2, s3 and s4 are enabled. To provide the +backward compatibility, this extra flag should be explicitly specified to make the +calibration function use the thin prism model and return 12 coefficients. If the flag is not +set, the function computes and returns only 5 distortion coefficients. +- @ref CALIB_FIX_S1_S2_S3_S4 The thin prism distortion coefficients are not changed during +the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the +supplied distCoeffs matrix is used. Otherwise, it is set to 0. +- @ref CALIB_TILTED_MODEL Coefficients tauX and tauY are enabled. To provide the +backward compatibility, this extra flag should be explicitly specified to make the +calibration function use the tilted sensor model and return 14 coefficients. If the flag is not +set, the function computes and returns only 5 distortion coefficients. +- @ref CALIB_FIX_TAUX_TAUY The coefficients of the tilted sensor model are not changed during +the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the +supplied distCoeffs matrix is used. Otherwise, it is set to 0. +@param criteria Termination criteria for the iterative optimization algorithm. + +The function estimates the transformation between two cameras making a stereo pair. If one computes +the poses of an object relative to the first camera and to the second camera, +( \f$R_1\f$,\f$T_1\f$ ) and (\f$R_2\f$,\f$T_2\f$), respectively, for a stereo camera where the +relative position and orientation between the two cameras are fixed, then those poses definitely +relate to each other. This means, if the relative position and orientation (\f$R\f$,\f$T\f$) of the +two cameras is known, it is possible to compute (\f$R_2\f$,\f$T_2\f$) when (\f$R_1\f$,\f$T_1\f$) is +given. This is what the described function does. It computes (\f$R\f$,\f$T\f$) such that: + +\f[R_2=R R_1\f] +\f[T_2=R T_1 + T.\f] + +Therefore, one can compute the coordinate representation of a 3D point for the second camera's +coordinate system when given the point's coordinate representation in the first camera's coordinate +system: + +\f[\begin{bmatrix} +X_2 \\ +Y_2 \\ +Z_2 \\ +1 +\end{bmatrix} = \begin{bmatrix} +R & T \\ +0 & 1 +\end{bmatrix} \begin{bmatrix} +X_1 \\ +Y_1 \\ +Z_1 \\ +1 +\end{bmatrix}.\f] + + +Optionally, it computes the essential matrix E: + +\f[E= \vecthreethree{0}{-T_2}{T_1}{T_2}{0}{-T_0}{-T_1}{T_0}{0} R\f] + +where \f$T_i\f$ are components of the translation vector \f$T\f$ : \f$T=[T_0, T_1, T_2]^T\f$ . +And the function can also compute the fundamental matrix F: + +\f[F = cameraMatrix2^{-T}\cdot E \cdot cameraMatrix1^{-1}\f] + +Besides the stereo-related information, the function can also perform a full calibration of each of +the two cameras. However, due to the high dimensionality of the parameter space and noise in the +input data, the function can diverge from the correct solution. If the intrinsic parameters can be +estimated with high accuracy for each of the cameras individually (for example, using +#calibrateCamera ), you are recommended to do so and then pass @ref CALIB_FIX_INTRINSIC flag to the +function along with the computed intrinsic parameters. Otherwise, if all the parameters are +estimated at once, it makes sense to restrict some parameters, for example, pass + @ref CALIB_SAME_FOCAL_LENGTH and @ref CALIB_ZERO_TANGENT_DIST flags, which is usually a +reasonable assumption. + +Similarly to #calibrateCamera, the function minimizes the total re-projection error for all the +points in all the available views from both cameras. The function returns the final value of the +re-projection error. + */ +CV_EXPORTS_AS(stereoCalibrateExtended) double stereoCalibrate( InputArrayOfArrays objectPoints, + InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, + InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1, + InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2, + Size imageSize, InputOutputArray R, InputOutputArray T, OutputArray E, OutputArray F, + OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, OutputArray perViewErrors, int flags = CALIB_FIX_INTRINSIC, + TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6) ); + +/// @overload +CV_EXPORTS_W double stereoCalibrate( InputArrayOfArrays objectPoints, + InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, + InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1, + InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2, + Size imageSize, OutputArray R,OutputArray T, OutputArray E, OutputArray F, + int flags = CALIB_FIX_INTRINSIC, + TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6) ); + +/// @overload +CV_EXPORTS_W double stereoCalibrate( InputArrayOfArrays objectPoints, + InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, + InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1, + InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2, + Size imageSize, InputOutputArray R, InputOutputArray T, OutputArray E, OutputArray F, + OutputArray perViewErrors, int flags = CALIB_FIX_INTRINSIC, + TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6) ); + +/** @brief Computes rectification transforms for each head of a calibrated stereo camera. + +@param cameraMatrix1 First camera intrinsic matrix. +@param distCoeffs1 First camera distortion parameters. +@param cameraMatrix2 Second camera intrinsic matrix. +@param distCoeffs2 Second camera distortion parameters. +@param imageSize Size of the image used for stereo calibration. +@param R Rotation matrix from the coordinate system of the first camera to the second camera, +see @ref stereoCalibrate. +@param T Translation vector from the coordinate system of the first camera to the second camera, +see @ref stereoCalibrate. +@param R1 Output 3x3 rectification transform (rotation matrix) for the first camera. This matrix +brings points given in the unrectified first camera's coordinate system to points in the rectified +first camera's coordinate system. In more technical terms, it performs a change of basis from the +unrectified first camera's coordinate system to the rectified first camera's coordinate system. +@param R2 Output 3x3 rectification transform (rotation matrix) for the second camera. This matrix +brings points given in the unrectified second camera's coordinate system to points in the rectified +second camera's coordinate system. In more technical terms, it performs a change of basis from the +unrectified second camera's coordinate system to the rectified second camera's coordinate system. +@param P1 Output 3x4 projection matrix in the new (rectified) coordinate systems for the first +camera, i.e. it projects points given in the rectified first camera coordinate system into the +rectified first camera's image. +@param P2 Output 3x4 projection matrix in the new (rectified) coordinate systems for the second +camera, i.e. it projects points given in the rectified first camera coordinate system into the +rectified second camera's image. +@param Q Output \f$4 \times 4\f$ disparity-to-depth mapping matrix (see @ref reprojectImageTo3D). +@param flags Operation flags that may be zero or @ref CALIB_ZERO_DISPARITY . If the flag is set, +the function makes the principal points of each camera have the same pixel coordinates in the +rectified views. And if the flag is not set, the function may still shift the images in the +horizontal or vertical direction (depending on the orientation of epipolar lines) to maximize the +useful image area. +@param alpha Free scaling parameter. If it is -1 or absent, the function performs the default +scaling. Otherwise, the parameter should be between 0 and 1. alpha=0 means that the rectified +images are zoomed and shifted so that only valid pixels are visible (no black areas after +rectification). alpha=1 means that the rectified image is decimated and shifted so that all the +pixels from the original images from the cameras are retained in the rectified images (no source +image pixels are lost). Any intermediate value yields an intermediate result between +those two extreme cases. +@param newImageSize New image resolution after rectification. The same size should be passed to +#initUndistortRectifyMap (see the stereo_calib.cpp sample in OpenCV samples directory). When (0,0) +is passed (default), it is set to the original imageSize . Setting it to a larger value can help you +preserve details in the original image, especially when there is a big radial distortion. +@param validPixROI1 Optional output rectangles inside the rectified images where all the pixels +are valid. If alpha=0 , the ROIs cover the whole images. Otherwise, they are likely to be smaller +(see the picture below). +@param validPixROI2 Optional output rectangles inside the rectified images where all the pixels +are valid. If alpha=0 , the ROIs cover the whole images. Otherwise, they are likely to be smaller +(see the picture below). + +The function computes the rotation matrices for each camera that (virtually) make both camera image +planes the same plane. Consequently, this makes all the epipolar lines parallel and thus simplifies +the dense stereo correspondence problem. The function takes the matrices computed by #stereoCalibrate +as input. As output, it provides two rotation matrices and also two projection matrices in the new +coordinates. The function distinguishes the following two cases: + +- **Horizontal stereo**: the first and the second camera views are shifted relative to each other + mainly along the x-axis (with possible small vertical shift). In the rectified images, the + corresponding epipolar lines in the left and right cameras are horizontal and have the same + y-coordinate. P1 and P2 look like: + + \f[\texttt{P1} = \begin{bmatrix} + f & 0 & cx_1 & 0 \\ + 0 & f & cy & 0 \\ + 0 & 0 & 1 & 0 + \end{bmatrix}\f] + + \f[\texttt{P2} = \begin{bmatrix} + f & 0 & cx_2 & T_x \cdot f \\ + 0 & f & cy & 0 \\ + 0 & 0 & 1 & 0 + \end{bmatrix} ,\f] + + \f[\texttt{Q} = \begin{bmatrix} + 1 & 0 & 0 & -cx_1 \\ + 0 & 1 & 0 & -cy \\ + 0 & 0 & 0 & f \\ + 0 & 0 & -\frac{1}{T_x} & \frac{cx_1 - cx_2}{T_x} + \end{bmatrix} \f] + + where \f$T_x\f$ is a horizontal shift between the cameras and \f$cx_1=cx_2\f$ if + @ref CALIB_ZERO_DISPARITY is set. + +- **Vertical stereo**: the first and the second camera views are shifted relative to each other + mainly in the vertical direction (and probably a bit in the horizontal direction too). The epipolar + lines in the rectified images are vertical and have the same x-coordinate. P1 and P2 look like: + + \f[\texttt{P1} = \begin{bmatrix} + f & 0 & cx & 0 \\ + 0 & f & cy_1 & 0 \\ + 0 & 0 & 1 & 0 + \end{bmatrix}\f] + + \f[\texttt{P2} = \begin{bmatrix} + f & 0 & cx & 0 \\ + 0 & f & cy_2 & T_y \cdot f \\ + 0 & 0 & 1 & 0 + \end{bmatrix},\f] + + \f[\texttt{Q} = \begin{bmatrix} + 1 & 0 & 0 & -cx \\ + 0 & 1 & 0 & -cy_1 \\ + 0 & 0 & 0 & f \\ + 0 & 0 & -\frac{1}{T_y} & \frac{cy_1 - cy_2}{T_y} + \end{bmatrix} \f] + + where \f$T_y\f$ is a vertical shift between the cameras and \f$cy_1=cy_2\f$ if + @ref CALIB_ZERO_DISPARITY is set. + +As you can see, the first three columns of P1 and P2 will effectively be the new "rectified" camera +matrices. The matrices, together with R1 and R2 , can then be passed to #initUndistortRectifyMap to +initialize the rectification map for each camera. + +See below the screenshot from the stereo_calib.cpp sample. Some red horizontal lines pass through +the corresponding image regions. This means that the images are well rectified, which is what most +stereo correspondence algorithms rely on. The green rectangles are roi1 and roi2 . You see that +their interiors are all valid pixels. + +![image](pics/stereo_undistort.jpg) + */ +CV_EXPORTS_W void stereoRectify( InputArray cameraMatrix1, InputArray distCoeffs1, + InputArray cameraMatrix2, InputArray distCoeffs2, + Size imageSize, InputArray R, InputArray T, + OutputArray R1, OutputArray R2, + OutputArray P1, OutputArray P2, + OutputArray Q, int flags = CALIB_ZERO_DISPARITY, + double alpha = -1, Size newImageSize = Size(), + CV_OUT Rect* validPixROI1 = 0, CV_OUT Rect* validPixROI2 = 0 ); + +/** @brief Computes a rectification transform for an uncalibrated stereo camera. + +@param points1 Array of feature points in the first image. +@param points2 The corresponding points in the second image. The same formats as in +#findFundamentalMat are supported. +@param F Input fundamental matrix. It can be computed from the same set of point pairs using +#findFundamentalMat . +@param imgSize Size of the image. +@param H1 Output rectification homography matrix for the first image. +@param H2 Output rectification homography matrix for the second image. +@param threshold Optional threshold used to filter out the outliers. If the parameter is greater +than zero, all the point pairs that do not comply with the epipolar geometry (that is, the points +for which \f$|\texttt{points2[i]}^T \cdot \texttt{F} \cdot \texttt{points1[i]}|>\texttt{threshold}\f$ ) +are rejected prior to computing the homographies. Otherwise, all the points are considered inliers. + +The function computes the rectification transformations without knowing intrinsic parameters of the +cameras and their relative position in the space, which explains the suffix "uncalibrated". Another +related difference from #stereoRectify is that the function outputs not the rectification +transformations in the object (3D) space, but the planar perspective transformations encoded by the +homography matrices H1 and H2 . The function implements the algorithm @cite Hartley99 . + +@note + While the algorithm does not need to know the intrinsic parameters of the cameras, it heavily + depends on the epipolar geometry. Therefore, if the camera lenses have a significant distortion, + it would be better to correct it before computing the fundamental matrix and calling this + function. For example, distortion coefficients can be estimated for each head of stereo camera + separately by using #calibrateCamera . Then, the images can be corrected using #undistort , or + just the point coordinates can be corrected with #undistortPoints . + */ +CV_EXPORTS_W bool stereoRectifyUncalibrated( InputArray points1, InputArray points2, + InputArray F, Size imgSize, + OutputArray H1, OutputArray H2, + double threshold = 5 ); + +//! computes the rectification transformations for 3-head camera, where all the heads are on the same line. +CV_EXPORTS_W float rectify3Collinear( InputArray cameraMatrix1, InputArray distCoeffs1, + InputArray cameraMatrix2, InputArray distCoeffs2, + InputArray cameraMatrix3, InputArray distCoeffs3, + InputArrayOfArrays imgpt1, InputArrayOfArrays imgpt3, + Size imageSize, InputArray R12, InputArray T12, + InputArray R13, InputArray T13, + OutputArray R1, OutputArray R2, OutputArray R3, + OutputArray P1, OutputArray P2, OutputArray P3, + OutputArray Q, double alpha, Size newImgSize, + CV_OUT Rect* roi1, CV_OUT Rect* roi2, int flags ); + +/** @brief Returns the new camera intrinsic matrix based on the free scaling parameter. + +@param cameraMatrix Input camera intrinsic matrix. +@param distCoeffs Input vector of distortion coefficients +\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are +assumed. +@param imageSize Original image size. +@param alpha Free scaling parameter between 0 (when all the pixels in the undistorted image are +valid) and 1 (when all the source image pixels are retained in the undistorted image). See +#stereoRectify for details. +@param newImgSize Image size after rectification. By default, it is set to imageSize . +@param validPixROI Optional output rectangle that outlines all-good-pixels region in the +undistorted image. See roi1, roi2 description in #stereoRectify . +@param centerPrincipalPoint Optional flag that indicates whether in the new camera intrinsic matrix the +principal point should be at the image center or not. By default, the principal point is chosen to +best fit a subset of the source image (determined by alpha) to the corrected image. +@return new_camera_matrix Output new camera intrinsic matrix. + +The function computes and returns the optimal new camera intrinsic matrix based on the free scaling parameter. +By varying this parameter, you may retrieve only sensible pixels alpha=0 , keep all the original +image pixels if there is valuable information in the corners alpha=1 , or get something in between. +When alpha\>0 , the undistorted result is likely to have some black pixels corresponding to +"virtual" pixels outside of the captured distorted image. The original camera intrinsic matrix, distortion +coefficients, the computed new camera intrinsic matrix, and newImageSize should be passed to +#initUndistortRectifyMap to produce the maps for #remap . + */ +CV_EXPORTS_W Mat getOptimalNewCameraMatrix( InputArray cameraMatrix, InputArray distCoeffs, + Size imageSize, double alpha, Size newImgSize = Size(), + CV_OUT Rect* validPixROI = 0, + bool centerPrincipalPoint = false); + +/** @brief Computes Hand-Eye calibration: \f$_{}^{g}\textrm{T}_c\f$ + +@param[in] R_gripper2base Rotation part extracted from the homogeneous matrix that transforms a point +expressed in the gripper frame to the robot base frame (\f$_{}^{b}\textrm{T}_g\f$). +This is a vector (`vector`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors, +for all the transformations from gripper frame to robot base frame. +@param[in] t_gripper2base Translation part extracted from the homogeneous matrix that transforms a point +expressed in the gripper frame to the robot base frame (\f$_{}^{b}\textrm{T}_g\f$). +This is a vector (`vector`) that contains the `(3x1)` translation vectors for all the transformations +from gripper frame to robot base frame. +@param[in] R_target2cam Rotation part extracted from the homogeneous matrix that transforms a point +expressed in the target frame to the camera frame (\f$_{}^{c}\textrm{T}_t\f$). +This is a vector (`vector`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors, +for all the transformations from calibration target frame to camera frame. +@param[in] t_target2cam Rotation part extracted from the homogeneous matrix that transforms a point +expressed in the target frame to the camera frame (\f$_{}^{c}\textrm{T}_t\f$). +This is a vector (`vector`) that contains the `(3x1)` translation vectors for all the transformations +from calibration target frame to camera frame. +@param[out] R_cam2gripper Estimated `(3x3)` rotation part extracted from the homogeneous matrix that transforms a point +expressed in the camera frame to the gripper frame (\f$_{}^{g}\textrm{T}_c\f$). +@param[out] t_cam2gripper Estimated `(3x1)` translation part extracted from the homogeneous matrix that transforms a point +expressed in the camera frame to the gripper frame (\f$_{}^{g}\textrm{T}_c\f$). +@param[in] method One of the implemented Hand-Eye calibration method, see cv::HandEyeCalibrationMethod + +The function performs the Hand-Eye calibration using various methods. One approach consists in estimating the +rotation then the translation (separable solutions) and the following methods are implemented: + - R. Tsai, R. Lenz A New Technique for Fully Autonomous and Efficient 3D Robotics Hand/EyeCalibration \cite Tsai89 + - F. Park, B. Martin Robot Sensor Calibration: Solving AX = XB on the Euclidean Group \cite Park94 + - R. Horaud, F. Dornaika Hand-Eye Calibration \cite Horaud95 + +Another approach consists in estimating simultaneously the rotation and the translation (simultaneous solutions), +with the following implemented methods: + - N. Andreff, R. Horaud, B. Espiau On-line Hand-Eye Calibration \cite Andreff99 + - K. Daniilidis Hand-Eye Calibration Using Dual Quaternions \cite Daniilidis98 + +The following picture describes the Hand-Eye calibration problem where the transformation between a camera ("eye") +mounted on a robot gripper ("hand") has to be estimated. This configuration is called eye-in-hand. + +The eye-to-hand configuration consists in a static camera observing a calibration pattern mounted on the robot +end-effector. The transformation from the camera to the robot base frame can then be estimated by inputting +the suitable transformations to the function, see below. + +![](pics/hand-eye_figure.png) + +The calibration procedure is the following: + - a static calibration pattern is used to estimate the transformation between the target frame + and the camera frame + - the robot gripper is moved in order to acquire several poses + - for each pose, the homogeneous transformation between the gripper frame and the robot base frame is recorded using for + instance the robot kinematics +\f[ + \begin{bmatrix} + X_b\\ + Y_b\\ + Z_b\\ + 1 + \end{bmatrix} + = + \begin{bmatrix} + _{}^{b}\textrm{R}_g & _{}^{b}\textrm{t}_g \\ + 0_{1 \times 3} & 1 + \end{bmatrix} + \begin{bmatrix} + X_g\\ + Y_g\\ + Z_g\\ + 1 + \end{bmatrix} +\f] + - for each pose, the homogeneous transformation between the calibration target frame and the camera frame is recorded using + for instance a pose estimation method (PnP) from 2D-3D point correspondences +\f[ + \begin{bmatrix} + X_c\\ + Y_c\\ + Z_c\\ + 1 + \end{bmatrix} + = + \begin{bmatrix} + _{}^{c}\textrm{R}_t & _{}^{c}\textrm{t}_t \\ + 0_{1 \times 3} & 1 + \end{bmatrix} + \begin{bmatrix} + X_t\\ + Y_t\\ + Z_t\\ + 1 + \end{bmatrix} +\f] + +The Hand-Eye calibration procedure returns the following homogeneous transformation +\f[ + \begin{bmatrix} + X_g\\ + Y_g\\ + Z_g\\ + 1 + \end{bmatrix} + = + \begin{bmatrix} + _{}^{g}\textrm{R}_c & _{}^{g}\textrm{t}_c \\ + 0_{1 \times 3} & 1 + \end{bmatrix} + \begin{bmatrix} + X_c\\ + Y_c\\ + Z_c\\ + 1 + \end{bmatrix} +\f] + +This problem is also known as solving the \f$\mathbf{A}\mathbf{X}=\mathbf{X}\mathbf{B}\f$ equation: + - for an eye-in-hand configuration +\f[ + \begin{align*} + ^{b}{\textrm{T}_g}^{(1)} \hspace{0.2em} ^{g}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(1)} &= + \hspace{0.1em} ^{b}{\textrm{T}_g}^{(2)} \hspace{0.2em} ^{g}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} \\ + + (^{b}{\textrm{T}_g}^{(2)})^{-1} \hspace{0.2em} ^{b}{\textrm{T}_g}^{(1)} \hspace{0.2em} ^{g}\textrm{T}_c &= + \hspace{0.1em} ^{g}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} (^{c}{\textrm{T}_t}^{(1)})^{-1} \\ + + \textrm{A}_i \textrm{X} &= \textrm{X} \textrm{B}_i \\ + \end{align*} +\f] + + - for an eye-to-hand configuration +\f[ + \begin{align*} + ^{g}{\textrm{T}_b}^{(1)} \hspace{0.2em} ^{b}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(1)} &= + \hspace{0.1em} ^{g}{\textrm{T}_b}^{(2)} \hspace{0.2em} ^{b}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} \\ + + (^{g}{\textrm{T}_b}^{(2)})^{-1} \hspace{0.2em} ^{g}{\textrm{T}_b}^{(1)} \hspace{0.2em} ^{b}\textrm{T}_c &= + \hspace{0.1em} ^{b}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} (^{c}{\textrm{T}_t}^{(1)})^{-1} \\ + + \textrm{A}_i \textrm{X} &= \textrm{X} \textrm{B}_i \\ + \end{align*} +\f] + +\note +Additional information can be found on this [website](http://campar.in.tum.de/Chair/HandEyeCalibration). +\note +A minimum of 2 motions with non parallel rotation axes are necessary to determine the hand-eye transformation. +So at least 3 different poses are required, but it is strongly recommended to use many more poses. + + */ +CV_EXPORTS_W void calibrateHandEye( InputArrayOfArrays R_gripper2base, InputArrayOfArrays t_gripper2base, + InputArrayOfArrays R_target2cam, InputArrayOfArrays t_target2cam, + OutputArray R_cam2gripper, OutputArray t_cam2gripper, + HandEyeCalibrationMethod method=CALIB_HAND_EYE_TSAI ); + +/** @brief Computes Robot-World/Hand-Eye calibration: \f$_{}^{w}\textrm{T}_b\f$ and \f$_{}^{c}\textrm{T}_g\f$ + +@param[in] R_world2cam Rotation part extracted from the homogeneous matrix that transforms a point +expressed in the world frame to the camera frame (\f$_{}^{c}\textrm{T}_w\f$). +This is a vector (`vector`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors, +for all the transformations from world frame to the camera frame. +@param[in] t_world2cam Translation part extracted from the homogeneous matrix that transforms a point +expressed in the world frame to the camera frame (\f$_{}^{c}\textrm{T}_w\f$). +This is a vector (`vector`) that contains the `(3x1)` translation vectors for all the transformations +from world frame to the camera frame. +@param[in] R_base2gripper Rotation part extracted from the homogeneous matrix that transforms a point +expressed in the robot base frame to the gripper frame (\f$_{}^{g}\textrm{T}_b\f$). +This is a vector (`vector`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors, +for all the transformations from robot base frame to the gripper frame. +@param[in] t_base2gripper Rotation part extracted from the homogeneous matrix that transforms a point +expressed in the robot base frame to the gripper frame (\f$_{}^{g}\textrm{T}_b\f$). +This is a vector (`vector`) that contains the `(3x1)` translation vectors for all the transformations +from robot base frame to the gripper frame. +@param[out] R_base2world Estimated `(3x3)` rotation part extracted from the homogeneous matrix that transforms a point +expressed in the robot base frame to the world frame (\f$_{}^{w}\textrm{T}_b\f$). +@param[out] t_base2world Estimated `(3x1)` translation part extracted from the homogeneous matrix that transforms a point +expressed in the robot base frame to the world frame (\f$_{}^{w}\textrm{T}_b\f$). +@param[out] R_gripper2cam Estimated `(3x3)` rotation part extracted from the homogeneous matrix that transforms a point +expressed in the gripper frame to the camera frame (\f$_{}^{c}\textrm{T}_g\f$). +@param[out] t_gripper2cam Estimated `(3x1)` translation part extracted from the homogeneous matrix that transforms a point +expressed in the gripper frame to the camera frame (\f$_{}^{c}\textrm{T}_g\f$). +@param[in] method One of the implemented Robot-World/Hand-Eye calibration method, see cv::RobotWorldHandEyeCalibrationMethod + +The function performs the Robot-World/Hand-Eye calibration using various methods. One approach consists in estimating the +rotation then the translation (separable solutions): + - M. Shah, Solving the robot-world/hand-eye calibration problem using the kronecker product \cite Shah2013SolvingTR + +Another approach consists in estimating simultaneously the rotation and the translation (simultaneous solutions), +with the following implemented method: + - A. Li, L. Wang, and D. Wu, Simultaneous robot-world and hand-eye calibration using dual-quaternions and kronecker product \cite Li2010SimultaneousRA + +The following picture describes the Robot-World/Hand-Eye calibration problem where the transformations between a robot and a world frame +and between a robot gripper ("hand") and a camera ("eye") mounted at the robot end-effector have to be estimated. + +![](pics/robot-world_hand-eye_figure.png) + +The calibration procedure is the following: + - a static calibration pattern is used to estimate the transformation between the target frame + and the camera frame + - the robot gripper is moved in order to acquire several poses + - for each pose, the homogeneous transformation between the gripper frame and the robot base frame is recorded using for + instance the robot kinematics +\f[ + \begin{bmatrix} + X_g\\ + Y_g\\ + Z_g\\ + 1 + \end{bmatrix} + = + \begin{bmatrix} + _{}^{g}\textrm{R}_b & _{}^{g}\textrm{t}_b \\ + 0_{1 \times 3} & 1 + \end{bmatrix} + \begin{bmatrix} + X_b\\ + Y_b\\ + Z_b\\ + 1 + \end{bmatrix} +\f] + - for each pose, the homogeneous transformation between the calibration target frame (the world frame) and the camera frame is recorded using + for instance a pose estimation method (PnP) from 2D-3D point correspondences +\f[ + \begin{bmatrix} + X_c\\ + Y_c\\ + Z_c\\ + 1 + \end{bmatrix} + = + \begin{bmatrix} + _{}^{c}\textrm{R}_w & _{}^{c}\textrm{t}_w \\ + 0_{1 \times 3} & 1 + \end{bmatrix} + \begin{bmatrix} + X_w\\ + Y_w\\ + Z_w\\ + 1 + \end{bmatrix} +\f] + +The Robot-World/Hand-Eye calibration procedure returns the following homogeneous transformations +\f[ + \begin{bmatrix} + X_w\\ + Y_w\\ + Z_w\\ + 1 + \end{bmatrix} + = + \begin{bmatrix} + _{}^{w}\textrm{R}_b & _{}^{w}\textrm{t}_b \\ + 0_{1 \times 3} & 1 + \end{bmatrix} + \begin{bmatrix} + X_b\\ + Y_b\\ + Z_b\\ + 1 + \end{bmatrix} +\f] +\f[ + \begin{bmatrix} + X_c\\ + Y_c\\ + Z_c\\ + 1 + \end{bmatrix} + = + \begin{bmatrix} + _{}^{c}\textrm{R}_g & _{}^{c}\textrm{t}_g \\ + 0_{1 \times 3} & 1 + \end{bmatrix} + \begin{bmatrix} + X_g\\ + Y_g\\ + Z_g\\ + 1 + \end{bmatrix} +\f] + +This problem is also known as solving the \f$\mathbf{A}\mathbf{X}=\mathbf{Z}\mathbf{B}\f$ equation, with: + - \f$\mathbf{A} \Leftrightarrow \hspace{0.1em} _{}^{c}\textrm{T}_w\f$ + - \f$\mathbf{X} \Leftrightarrow \hspace{0.1em} _{}^{w}\textrm{T}_b\f$ + - \f$\mathbf{Z} \Leftrightarrow \hspace{0.1em} _{}^{c}\textrm{T}_g\f$ + - \f$\mathbf{B} \Leftrightarrow \hspace{0.1em} _{}^{g}\textrm{T}_b\f$ + +\note +At least 3 measurements are required (input vectors size must be greater or equal to 3). + + */ +CV_EXPORTS_W void calibrateRobotWorldHandEye( InputArrayOfArrays R_world2cam, InputArrayOfArrays t_world2cam, + InputArrayOfArrays R_base2gripper, InputArrayOfArrays t_base2gripper, + OutputArray R_base2world, OutputArray t_base2world, + OutputArray R_gripper2cam, OutputArray t_gripper2cam, + RobotWorldHandEyeCalibrationMethod method=CALIB_ROBOT_WORLD_HAND_EYE_SHAH ); + +/** @brief Converts points from Euclidean to homogeneous space. + +@param src Input vector of N-dimensional points. +@param dst Output vector of N+1-dimensional points. + +The function converts points from Euclidean to homogeneous space by appending 1's to the tuple of +point coordinates. That is, each point (x1, x2, ..., xn) is converted to (x1, x2, ..., xn, 1). + */ +CV_EXPORTS_W void convertPointsToHomogeneous( InputArray src, OutputArray dst ); + +/** @brief Converts points from homogeneous to Euclidean space. + +@param src Input vector of N-dimensional points. +@param dst Output vector of N-1-dimensional points. + +The function converts points homogeneous to Euclidean space using perspective projection. That is, +each point (x1, x2, ... x(n-1), xn) is converted to (x1/xn, x2/xn, ..., x(n-1)/xn). When xn=0, the +output point coordinates will be (0,0,0,...). + */ +CV_EXPORTS_W void convertPointsFromHomogeneous( InputArray src, OutputArray dst ); + +/** @brief Converts points to/from homogeneous coordinates. + +@param src Input array or vector of 2D, 3D, or 4D points. +@param dst Output vector of 2D, 3D, or 4D points. + +The function converts 2D or 3D points from/to homogeneous coordinates by calling either +#convertPointsToHomogeneous or #convertPointsFromHomogeneous. + +@note The function is obsolete. Use one of the previous two functions instead. + */ +CV_EXPORTS void convertPointsHomogeneous( InputArray src, OutputArray dst ); + +/** @brief Calculates a fundamental matrix from the corresponding points in two images. + +@param points1 Array of N points from the first image. The point coordinates should be +floating-point (single or double precision). +@param points2 Array of the second image points of the same size and format as points1 . +@param method Method for computing a fundamental matrix. +- @ref FM_7POINT for a 7-point algorithm. \f$N = 7\f$ +- @ref FM_8POINT for an 8-point algorithm. \f$N \ge 8\f$ +- @ref FM_RANSAC for the RANSAC algorithm. \f$N \ge 8\f$ +- @ref FM_LMEDS for the LMedS algorithm. \f$N \ge 8\f$ +@param ransacReprojThreshold Parameter used only for RANSAC. It is the maximum distance from a point to an epipolar +line in pixels, beyond which the point is considered an outlier and is not used for computing the +final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the +point localization, image resolution, and the image noise. +@param confidence Parameter used for the RANSAC and LMedS methods only. It specifies a desirable level +of confidence (probability) that the estimated matrix is correct. +@param[out] mask optional output mask +@param maxIters The maximum number of robust method iterations. + +The epipolar geometry is described by the following equation: + +\f[[p_2; 1]^T F [p_1; 1] = 0\f] + +where \f$F\f$ is a fundamental matrix, \f$p_1\f$ and \f$p_2\f$ are corresponding points in the first and the +second images, respectively. + +The function calculates the fundamental matrix using one of four methods listed above and returns +the found fundamental matrix. Normally just one matrix is found. But in case of the 7-point +algorithm, the function may return up to 3 solutions ( \f$9 \times 3\f$ matrix that stores all 3 +matrices sequentially). + +The calculated fundamental matrix may be passed further to #computeCorrespondEpilines that finds the +epipolar lines corresponding to the specified points. It can also be passed to +#stereoRectifyUncalibrated to compute the rectification transformation. : +@code + // Example. Estimation of fundamental matrix using the RANSAC algorithm + int point_count = 100; + vector points1(point_count); + vector points2(point_count); + + // initialize the points here ... + for( int i = 0; i < point_count; i++ ) + { + points1[i] = ...; + points2[i] = ...; + } + + Mat fundamental_matrix = + findFundamentalMat(points1, points2, FM_RANSAC, 3, 0.99); +@endcode + */ +CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2, + int method, double ransacReprojThreshold, double confidence, + int maxIters, OutputArray mask = noArray() ); + +/** @overload */ +CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2, + int method = FM_RANSAC, + double ransacReprojThreshold = 3., double confidence = 0.99, + OutputArray mask = noArray() ); + +/** @overload */ +CV_EXPORTS Mat findFundamentalMat( InputArray points1, InputArray points2, + OutputArray mask, int method = FM_RANSAC, + double ransacReprojThreshold = 3., double confidence = 0.99 ); + + +CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2, + OutputArray mask, const UsacParams ¶ms); + +/** @brief Calculates an essential matrix from the corresponding points in two images. + +@param points1 Array of N (N \>= 5) 2D points from the first image. The point coordinates should +be floating-point (single or double precision). +@param points2 Array of the second image points of the same size and format as points1. +@param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ . +Note that this function assumes that points1 and points2 are feature points from cameras with the +same camera intrinsic matrix. If this assumption does not hold for your use case, use another +function overload or #undistortPoints with `P = cv::NoArray()` for both cameras to transform image +points to normalized image coordinates, which are valid for the identity camera intrinsic matrix. +When passing these coordinates, pass the identity matrix for this parameter. +@param method Method for computing an essential matrix. +- @ref RANSAC for the RANSAC algorithm. +- @ref LMEDS for the LMedS algorithm. +@param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of +confidence (probability) that the estimated matrix is correct. +@param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar +line in pixels, beyond which the point is considered an outlier and is not used for computing the +final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the +point localization, image resolution, and the image noise. +@param mask Output array of N elements, every element of which is set to 0 for outliers and to 1 +for the other points. The array is computed only in the RANSAC and LMedS methods. +@param maxIters The maximum number of robust method iterations. + +This function estimates essential matrix based on the five-point algorithm solver in @cite Nister03 . +@cite SteweniusCFS is also a related. The epipolar geometry is described by the following equation: + +\f[[p_2; 1]^T K^{-T} E K^{-1} [p_1; 1] = 0\f] + +where \f$E\f$ is an essential matrix, \f$p_1\f$ and \f$p_2\f$ are corresponding points in the first and the +second images, respectively. The result of this function may be passed further to +#decomposeEssentialMat or #recoverPose to recover the relative pose between cameras. + */ +CV_EXPORTS_W +Mat findEssentialMat( + InputArray points1, InputArray points2, + InputArray cameraMatrix, int method = RANSAC, + double prob = 0.999, double threshold = 1.0, + int maxIters = 1000, OutputArray mask = noArray() +); + +/** @overload */ +CV_EXPORTS +Mat findEssentialMat( + InputArray points1, InputArray points2, + InputArray cameraMatrix, int method, + double prob, double threshold, + OutputArray mask +); // TODO remove from OpenCV 5.0 + +/** @overload +@param points1 Array of N (N \>= 5) 2D points from the first image. The point coordinates should +be floating-point (single or double precision). +@param points2 Array of the second image points of the same size and format as points1 . +@param focal focal length of the camera. Note that this function assumes that points1 and points2 +are feature points from cameras with same focal length and principal point. +@param pp principal point of the camera. +@param method Method for computing a fundamental matrix. +- @ref RANSAC for the RANSAC algorithm. +- @ref LMEDS for the LMedS algorithm. +@param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar +line in pixels, beyond which the point is considered an outlier and is not used for computing the +final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the +point localization, image resolution, and the image noise. +@param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of +confidence (probability) that the estimated matrix is correct. +@param mask Output array of N elements, every element of which is set to 0 for outliers and to 1 +for the other points. The array is computed only in the RANSAC and LMedS methods. +@param maxIters The maximum number of robust method iterations. + +This function differs from the one above that it computes camera intrinsic matrix from focal length and +principal point: + +\f[A = +\begin{bmatrix} +f & 0 & x_{pp} \\ +0 & f & y_{pp} \\ +0 & 0 & 1 +\end{bmatrix}\f] + */ +CV_EXPORTS_W +Mat findEssentialMat( + InputArray points1, InputArray points2, + double focal = 1.0, Point2d pp = Point2d(0, 0), + int method = RANSAC, double prob = 0.999, + double threshold = 1.0, int maxIters = 1000, + OutputArray mask = noArray() +); + +/** @overload */ +CV_EXPORTS +Mat findEssentialMat( + InputArray points1, InputArray points2, + double focal, Point2d pp, + int method, double prob, + double threshold, OutputArray mask +); // TODO remove from OpenCV 5.0 + +/** @brief Calculates an essential matrix from the corresponding points in two images from potentially two different cameras. + +@param points1 Array of N (N \>= 5) 2D points from the first image. The point coordinates should +be floating-point (single or double precision). +@param points2 Array of the second image points of the same size and format as points1. +@param cameraMatrix1 Camera matrix for the first camera \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . +@param cameraMatrix2 Camera matrix for the second camera \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . +@param distCoeffs1 Input vector of distortion coefficients for the first camera +\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ +of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. +@param distCoeffs2 Input vector of distortion coefficients for the second camera +\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ +of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. +@param method Method for computing an essential matrix. +- @ref RANSAC for the RANSAC algorithm. +- @ref LMEDS for the LMedS algorithm. +@param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of +confidence (probability) that the estimated matrix is correct. +@param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar +line in pixels, beyond which the point is considered an outlier and is not used for computing the +final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the +point localization, image resolution, and the image noise. +@param mask Output array of N elements, every element of which is set to 0 for outliers and to 1 +for the other points. The array is computed only in the RANSAC and LMedS methods. + +This function estimates essential matrix based on the five-point algorithm solver in @cite Nister03 . +@cite SteweniusCFS is also a related. The epipolar geometry is described by the following equation: + +\f[[p_2; 1]^T K^{-T} E K^{-1} [p_1; 1] = 0\f] + +where \f$E\f$ is an essential matrix, \f$p_1\f$ and \f$p_2\f$ are corresponding points in the first and the +second images, respectively. The result of this function may be passed further to +#decomposeEssentialMat or #recoverPose to recover the relative pose between cameras. + */ +CV_EXPORTS_W Mat findEssentialMat( InputArray points1, InputArray points2, + InputArray cameraMatrix1, InputArray distCoeffs1, + InputArray cameraMatrix2, InputArray distCoeffs2, + int method = RANSAC, + double prob = 0.999, double threshold = 1.0, + OutputArray mask = noArray() ); + + +CV_EXPORTS_W Mat findEssentialMat( InputArray points1, InputArray points2, + InputArray cameraMatrix1, InputArray cameraMatrix2, + InputArray dist_coeff1, InputArray dist_coeff2, OutputArray mask, + const UsacParams ¶ms); + +/** @brief Decompose an essential matrix to possible rotations and translation. + +@param E The input essential matrix. +@param R1 One possible rotation matrix. +@param R2 Another possible rotation matrix. +@param t One possible translation. + +This function decomposes the essential matrix E using svd decomposition @cite HartleyZ00. In +general, four possible poses exist for the decomposition of E. They are \f$[R_1, t]\f$, +\f$[R_1, -t]\f$, \f$[R_2, t]\f$, \f$[R_2, -t]\f$. + +If E gives the epipolar constraint \f$[p_2; 1]^T A^{-T} E A^{-1} [p_1; 1] = 0\f$ between the image +points \f$p_1\f$ in the first image and \f$p_2\f$ in second image, then any of the tuples +\f$[R_1, t]\f$, \f$[R_1, -t]\f$, \f$[R_2, t]\f$, \f$[R_2, -t]\f$ is a change of basis from the first +camera's coordinate system to the second camera's coordinate system. However, by decomposing E, one +can only get the direction of the translation. For this reason, the translation t is returned with +unit length. + */ +CV_EXPORTS_W void decomposeEssentialMat( InputArray E, OutputArray R1, OutputArray R2, OutputArray t ); + +/** @brief Recovers the relative camera rotation and the translation from corresponding points in two images from two different cameras, using cheirality check. Returns the number of +inliers that pass the check. + +@param points1 Array of N 2D points from the first image. The point coordinates should be +floating-point (single or double precision). +@param points2 Array of the second image points of the same size and format as points1 . +@param cameraMatrix1 Input/output camera matrix for the first camera, the same as in +@ref calibrateCamera. Furthermore, for the stereo case, additional flags may be used, see below. +@param distCoeffs1 Input/output vector of distortion coefficients, the same as in +@ref calibrateCamera. +@param cameraMatrix2 Input/output camera matrix for the first camera, the same as in +@ref calibrateCamera. Furthermore, for the stereo case, additional flags may be used, see below. +@param distCoeffs2 Input/output vector of distortion coefficients, the same as in +@ref calibrateCamera. +@param E The output essential matrix. +@param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple +that performs a change of basis from the first camera's coordinate system to the second camera's +coordinate system. Note that, in general, t can not be used for this tuple, see the parameter +described below. +@param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and +therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit +length. +@param method Method for computing an essential matrix. +- @ref RANSAC for the RANSAC algorithm. +- @ref LMEDS for the LMedS algorithm. +@param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of +confidence (probability) that the estimated matrix is correct. +@param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar +line in pixels, beyond which the point is considered an outlier and is not used for computing the +final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the +point localization, image resolution, and the image noise. +@param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks +inliers in points1 and points2 for then given essential matrix E. Only these inliers will be used to +recover pose. In the output mask only inliers which pass the cheirality check. + +This function decomposes an essential matrix using @ref decomposeEssentialMat and then verifies +possible pose hypotheses by doing cheirality check. The cheirality check means that the +triangulated 3D points should have positive depth. Some details can be found in @cite Nister03. + +This function can be used to process the output E and mask from @ref findEssentialMat. In this +scenario, points1 and points2 are the same input for findEssentialMat.: +@code + // Example. Estimation of fundamental matrix using the RANSAC algorithm + int point_count = 100; + vector points1(point_count); + vector points2(point_count); + + // initialize the points here ... + for( int i = 0; i < point_count; i++ ) + { + points1[i] = ...; + points2[i] = ...; + } + + // Input: camera calibration of both cameras, for example using intrinsic chessboard calibration. + Mat cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2; + + // Output: Essential matrix, relative rotation and relative translation. + Mat E, R, t, mask; + + recoverPose(points1, points2, cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, E, R, t, mask); +@endcode + */ +CV_EXPORTS_W int recoverPose( InputArray points1, InputArray points2, + InputArray cameraMatrix1, InputArray distCoeffs1, + InputArray cameraMatrix2, InputArray distCoeffs2, + OutputArray E, OutputArray R, OutputArray t, + int method = cv::RANSAC, double prob = 0.999, double threshold = 1.0, + InputOutputArray mask = noArray()); + +/** @brief Recovers the relative camera rotation and the translation from an estimated essential +matrix and the corresponding points in two images, using chirality check. Returns the number of +inliers that pass the check. + +@param E The input essential matrix. +@param points1 Array of N 2D points from the first image. The point coordinates should be +floating-point (single or double precision). +@param points2 Array of the second image points of the same size and format as points1 . +@param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ . +Note that this function assumes that points1 and points2 are feature points from cameras with the +same camera intrinsic matrix. +@param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple +that performs a change of basis from the first camera's coordinate system to the second camera's +coordinate system. Note that, in general, t can not be used for this tuple, see the parameter +described below. +@param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and +therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit +length. +@param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks +inliers in points1 and points2 for the given essential matrix E. Only these inliers will be used to +recover pose. In the output mask only inliers which pass the chirality check. + +This function decomposes an essential matrix using @ref decomposeEssentialMat and then verifies +possible pose hypotheses by doing chirality check. The chirality check means that the +triangulated 3D points should have positive depth. Some details can be found in @cite Nister03. + +This function can be used to process the output E and mask from @ref findEssentialMat. In this +scenario, points1 and points2 are the same input for #findEssentialMat : +@code + // Example. Estimation of fundamental matrix using the RANSAC algorithm + int point_count = 100; + vector points1(point_count); + vector points2(point_count); + + // initialize the points here ... + for( int i = 0; i < point_count; i++ ) + { + points1[i] = ...; + points2[i] = ...; + } + + // cametra matrix with both focal lengths = 1, and principal point = (0, 0) + Mat cameraMatrix = Mat::eye(3, 3, CV_64F); + + Mat E, R, t, mask; + + E = findEssentialMat(points1, points2, cameraMatrix, RANSAC, 0.999, 1.0, mask); + recoverPose(E, points1, points2, cameraMatrix, R, t, mask); +@endcode + */ +CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray points2, + InputArray cameraMatrix, OutputArray R, OutputArray t, + InputOutputArray mask = noArray() ); + +/** @overload +@param E The input essential matrix. +@param points1 Array of N 2D points from the first image. The point coordinates should be +floating-point (single or double precision). +@param points2 Array of the second image points of the same size and format as points1 . +@param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple +that performs a change of basis from the first camera's coordinate system to the second camera's +coordinate system. Note that, in general, t can not be used for this tuple, see the parameter +description below. +@param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and +therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit +length. +@param focal Focal length of the camera. Note that this function assumes that points1 and points2 +are feature points from cameras with same focal length and principal point. +@param pp principal point of the camera. +@param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks +inliers in points1 and points2 for the given essential matrix E. Only these inliers will be used to +recover pose. In the output mask only inliers which pass the chirality check. + +This function differs from the one above that it computes camera intrinsic matrix from focal length and +principal point: + +\f[A = +\begin{bmatrix} +f & 0 & x_{pp} \\ +0 & f & y_{pp} \\ +0 & 0 & 1 +\end{bmatrix}\f] + */ +CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray points2, + OutputArray R, OutputArray t, + double focal = 1.0, Point2d pp = Point2d(0, 0), + InputOutputArray mask = noArray() ); + +/** @overload +@param E The input essential matrix. +@param points1 Array of N 2D points from the first image. The point coordinates should be +floating-point (single or double precision). +@param points2 Array of the second image points of the same size and format as points1. +@param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ . +Note that this function assumes that points1 and points2 are feature points from cameras with the +same camera intrinsic matrix. +@param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple +that performs a change of basis from the first camera's coordinate system to the second camera's +coordinate system. Note that, in general, t can not be used for this tuple, see the parameter +description below. +@param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and +therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit +length. +@param distanceThresh threshold distance which is used to filter out far away points (i.e. infinite +points). +@param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks +inliers in points1 and points2 for the given essential matrix E. Only these inliers will be used to +recover pose. In the output mask only inliers which pass the chirality check. +@param triangulatedPoints 3D points which were reconstructed by triangulation. + +This function differs from the one above that it outputs the triangulated 3D point that are used for +the chirality check. + */ +CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray points2, + InputArray cameraMatrix, OutputArray R, OutputArray t, double distanceThresh, InputOutputArray mask = noArray(), + OutputArray triangulatedPoints = noArray()); + +/** @brief For points in an image of a stereo pair, computes the corresponding epilines in the other image. + +@param points Input points. \f$N \times 1\f$ or \f$1 \times N\f$ matrix of type CV_32FC2 or +vector\ . +@param whichImage Index of the image (1 or 2) that contains the points . +@param F Fundamental matrix that can be estimated using #findFundamentalMat or #stereoRectify . +@param lines Output vector of the epipolar lines corresponding to the points in the other image. +Each line \f$ax + by + c=0\f$ is encoded by 3 numbers \f$(a, b, c)\f$ . + +For every point in one of the two images of a stereo pair, the function finds the equation of the +corresponding epipolar line in the other image. + +From the fundamental matrix definition (see #findFundamentalMat ), line \f$l^{(2)}_i\f$ in the second +image for the point \f$p^{(1)}_i\f$ in the first image (when whichImage=1 ) is computed as: + +\f[l^{(2)}_i = F p^{(1)}_i\f] + +And vice versa, when whichImage=2, \f$l^{(1)}_i\f$ is computed from \f$p^{(2)}_i\f$ as: + +\f[l^{(1)}_i = F^T p^{(2)}_i\f] + +Line coefficients are defined up to a scale. They are normalized so that \f$a_i^2+b_i^2=1\f$ . + */ +CV_EXPORTS_W void computeCorrespondEpilines( InputArray points, int whichImage, + InputArray F, OutputArray lines ); + +/** @brief This function reconstructs 3-dimensional points (in homogeneous coordinates) by using +their observations with a stereo camera. + +@param projMatr1 3x4 projection matrix of the first camera, i.e. this matrix projects 3D points +given in the world's coordinate system into the first image. +@param projMatr2 3x4 projection matrix of the second camera, i.e. this matrix projects 3D points +given in the world's coordinate system into the second image. +@param projPoints1 2xN array of feature points in the first image. In the case of the c++ version, +it can be also a vector of feature points or two-channel matrix of size 1xN or Nx1. +@param projPoints2 2xN array of corresponding points in the second image. In the case of the c++ +version, it can be also a vector of feature points or two-channel matrix of size 1xN or Nx1. +@param points4D 4xN array of reconstructed points in homogeneous coordinates. These points are +returned in the world's coordinate system. + +@note + Keep in mind that all input data should be of float type in order for this function to work. + +@note + If the projection matrices from @ref stereoRectify are used, then the returned points are + represented in the first camera's rectified coordinate system. + +@sa + reprojectImageTo3D + */ +CV_EXPORTS_W void triangulatePoints( InputArray projMatr1, InputArray projMatr2, + InputArray projPoints1, InputArray projPoints2, + OutputArray points4D ); + +/** @brief Refines coordinates of corresponding points. + +@param F 3x3 fundamental matrix. +@param points1 1xN array containing the first set of points. +@param points2 1xN array containing the second set of points. +@param newPoints1 The optimized points1. +@param newPoints2 The optimized points2. + +The function implements the Optimal Triangulation Method (see Multiple View Geometry @cite HartleyZ00 for details). +For each given point correspondence points1[i] \<-\> points2[i], and a fundamental matrix F, it +computes the corrected correspondences newPoints1[i] \<-\> newPoints2[i] that minimize the geometric +error \f$d(points1[i], newPoints1[i])^2 + d(points2[i],newPoints2[i])^2\f$ (where \f$d(a,b)\f$ is the +geometric distance between points \f$a\f$ and \f$b\f$ ) subject to the epipolar constraint +\f$newPoints2^T \cdot F \cdot newPoints1 = 0\f$ . + */ +CV_EXPORTS_W void correctMatches( InputArray F, InputArray points1, InputArray points2, + OutputArray newPoints1, OutputArray newPoints2 ); + +/** @brief Filters off small noise blobs (speckles) in the disparity map + +@param img The input 16-bit signed disparity image +@param newVal The disparity value used to paint-off the speckles +@param maxSpeckleSize The maximum speckle size to consider it a speckle. Larger blobs are not +affected by the algorithm +@param maxDiff Maximum difference between neighbor disparity pixels to put them into the same +blob. Note that since StereoBM, StereoSGBM and may be other algorithms return a fixed-point +disparity map, where disparity values are multiplied by 16, this scale factor should be taken into +account when specifying this parameter value. +@param buf The optional temporary buffer to avoid memory allocation within the function. + */ +CV_EXPORTS_W void filterSpeckles( InputOutputArray img, double newVal, + int maxSpeckleSize, double maxDiff, + InputOutputArray buf = noArray() ); + +//! computes valid disparity ROI from the valid ROIs of the rectified images (that are returned by #stereoRectify) +CV_EXPORTS_W Rect getValidDisparityROI( Rect roi1, Rect roi2, + int minDisparity, int numberOfDisparities, + int blockSize ); + +//! validates disparity using the left-right check. The matrix "cost" should be computed by the stereo correspondence algorithm +CV_EXPORTS_W void validateDisparity( InputOutputArray disparity, InputArray cost, + int minDisparity, int numberOfDisparities, + int disp12MaxDisp = 1 ); + +/** @brief Reprojects a disparity image to 3D space. + +@param disparity Input single-channel 8-bit unsigned, 16-bit signed, 32-bit signed or 32-bit +floating-point disparity image. The values of 8-bit / 16-bit signed formats are assumed to have no +fractional bits. If the disparity is 16-bit signed format, as computed by @ref StereoBM or +@ref StereoSGBM and maybe other algorithms, it should be divided by 16 (and scaled to float) before +being used here. +@param _3dImage Output 3-channel floating-point image of the same size as disparity. Each element of +_3dImage(x,y) contains 3D coordinates of the point (x,y) computed from the disparity map. If one +uses Q obtained by @ref stereoRectify, then the returned points are represented in the first +camera's rectified coordinate system. +@param Q \f$4 \times 4\f$ perspective transformation matrix that can be obtained with +@ref stereoRectify. +@param handleMissingValues Indicates, whether the function should handle missing values (i.e. +points where the disparity was not computed). If handleMissingValues=true, then pixels with the +minimal disparity that corresponds to the outliers (see StereoMatcher::compute ) are transformed +to 3D points with a very large Z value (currently set to 10000). +@param ddepth The optional output array depth. If it is -1, the output image will have CV_32F +depth. ddepth can also be set to CV_16S, CV_32S or CV_32F. + +The function transforms a single-channel disparity map to a 3-channel image representing a 3D +surface. That is, for each pixel (x,y) and the corresponding disparity d=disparity(x,y) , it +computes: + +\f[\begin{bmatrix} +X \\ +Y \\ +Z \\ +W +\end{bmatrix} = Q \begin{bmatrix} +x \\ +y \\ +\texttt{disparity} (x,y) \\ +1 +\end{bmatrix}.\f] + +@sa + To reproject a sparse set of points {(x,y,d),...} to 3D space, use perspectiveTransform. + */ +CV_EXPORTS_W void reprojectImageTo3D( InputArray disparity, + OutputArray _3dImage, InputArray Q, + bool handleMissingValues = false, + int ddepth = -1 ); + +/** @brief Calculates the Sampson Distance between two points. + +The function cv::sampsonDistance calculates and returns the first order approximation of the geometric error as: +\f[ +sd( \texttt{pt1} , \texttt{pt2} )= +\frac{(\texttt{pt2}^t \cdot \texttt{F} \cdot \texttt{pt1})^2} +{((\texttt{F} \cdot \texttt{pt1})(0))^2 + +((\texttt{F} \cdot \texttt{pt1})(1))^2 + +((\texttt{F}^t \cdot \texttt{pt2})(0))^2 + +((\texttt{F}^t \cdot \texttt{pt2})(1))^2} +\f] +The fundamental matrix may be calculated using the #findFundamentalMat function. See @cite HartleyZ00 11.4.3 for details. +@param pt1 first homogeneous 2d point +@param pt2 second homogeneous 2d point +@param F fundamental matrix +@return The computed Sampson distance. +*/ +CV_EXPORTS_W double sampsonDistance(InputArray pt1, InputArray pt2, InputArray F); + +/** @brief Computes an optimal affine transformation between two 3D point sets. + +It computes +\f[ +\begin{bmatrix} +x\\ +y\\ +z\\ +\end{bmatrix} += +\begin{bmatrix} +a_{11} & a_{12} & a_{13}\\ +a_{21} & a_{22} & a_{23}\\ +a_{31} & a_{32} & a_{33}\\ +\end{bmatrix} +\begin{bmatrix} +X\\ +Y\\ +Z\\ +\end{bmatrix} ++ +\begin{bmatrix} +b_1\\ +b_2\\ +b_3\\ +\end{bmatrix} +\f] + +@param src First input 3D point set containing \f$(X,Y,Z)\f$. +@param dst Second input 3D point set containing \f$(x,y,z)\f$. +@param out Output 3D affine transformation matrix \f$3 \times 4\f$ of the form +\f[ +\begin{bmatrix} +a_{11} & a_{12} & a_{13} & b_1\\ +a_{21} & a_{22} & a_{23} & b_2\\ +a_{31} & a_{32} & a_{33} & b_3\\ +\end{bmatrix} +\f] +@param inliers Output vector indicating which points are inliers (1-inlier, 0-outlier). +@param ransacThreshold Maximum reprojection error in the RANSAC algorithm to consider a point as +an inlier. +@param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything +between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation +significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation. + +The function estimates an optimal 3D affine transformation between two 3D point sets using the +RANSAC algorithm. + */ +CV_EXPORTS_W int estimateAffine3D(InputArray src, InputArray dst, + OutputArray out, OutputArray inliers, + double ransacThreshold = 3, double confidence = 0.99); + +/** @brief Computes an optimal affine transformation between two 3D point sets. + +It computes \f$R,s,t\f$ minimizing \f$\sum{i} dst_i - c \cdot R \cdot src_i \f$ +where \f$R\f$ is a 3x3 rotation matrix, \f$t\f$ is a 3x1 translation vector and \f$s\f$ is a +scalar size value. This is an implementation of the algorithm by Umeyama \cite umeyama1991least . +The estimated affine transform has a homogeneous scale which is a subclass of affine +transformations with 7 degrees of freedom. The paired point sets need to comprise at least 3 +points each. + +@param src First input 3D point set. +@param dst Second input 3D point set. +@param scale If null is passed, the scale parameter c will be assumed to be 1.0. +Else the pointed-to variable will be set to the optimal scale. +@param force_rotation If true, the returned rotation will never be a reflection. +This might be unwanted, e.g. when optimizing a transform between a right- and a +left-handed coordinate system. +@return 3D affine transformation matrix \f$3 \times 4\f$ of the form +\f[T = +\begin{bmatrix} +R & t\\ +\end{bmatrix} +\f] + + */ +CV_EXPORTS_W cv::Mat estimateAffine3D(InputArray src, InputArray dst, + CV_OUT double* scale = nullptr, bool force_rotation = true); + +/** @brief Computes an optimal translation between two 3D point sets. + * + * It computes + * \f[ + * \begin{bmatrix} + * x\\ + * y\\ + * z\\ + * \end{bmatrix} + * = + * \begin{bmatrix} + * X\\ + * Y\\ + * Z\\ + * \end{bmatrix} + * + + * \begin{bmatrix} + * b_1\\ + * b_2\\ + * b_3\\ + * \end{bmatrix} + * \f] + * + * @param src First input 3D point set containing \f$(X,Y,Z)\f$. + * @param dst Second input 3D point set containing \f$(x,y,z)\f$. + * @param out Output 3D translation vector \f$3 \times 1\f$ of the form + * \f[ + * \begin{bmatrix} + * b_1 \\ + * b_2 \\ + * b_3 \\ + * \end{bmatrix} + * \f] + * @param inliers Output vector indicating which points are inliers (1-inlier, 0-outlier). + * @param ransacThreshold Maximum reprojection error in the RANSAC algorithm to consider a point as + * an inlier. + * @param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything + * between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation + * significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation. + * + * The function estimates an optimal 3D translation between two 3D point sets using the + * RANSAC algorithm. + * */ +CV_EXPORTS_W int estimateTranslation3D(InputArray src, InputArray dst, + OutputArray out, OutputArray inliers, + double ransacThreshold = 3, double confidence = 0.99); + +/** @brief Computes an optimal affine transformation between two 2D point sets. + +It computes +\f[ +\begin{bmatrix} +x\\ +y\\ +\end{bmatrix} += +\begin{bmatrix} +a_{11} & a_{12}\\ +a_{21} & a_{22}\\ +\end{bmatrix} +\begin{bmatrix} +X\\ +Y\\ +\end{bmatrix} ++ +\begin{bmatrix} +b_1\\ +b_2\\ +\end{bmatrix} +\f] + +@param from First input 2D point set containing \f$(X,Y)\f$. +@param to Second input 2D point set containing \f$(x,y)\f$. +@param inliers Output vector indicating which points are inliers (1-inlier, 0-outlier). +@param method Robust method used to compute transformation. The following methods are possible: +- @ref RANSAC - RANSAC-based robust method +- @ref LMEDS - Least-Median robust method +RANSAC is the default method. +@param ransacReprojThreshold Maximum reprojection error in the RANSAC algorithm to consider +a point as an inlier. Applies only to RANSAC. +@param maxIters The maximum number of robust method iterations. +@param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything +between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation +significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation. +@param refineIters Maximum number of iterations of refining algorithm (Levenberg-Marquardt). +Passing 0 will disable refining, so the output matrix will be output of robust method. + +@return Output 2D affine transformation matrix \f$2 \times 3\f$ or empty matrix if transformation +could not be estimated. The returned matrix has the following form: +\f[ +\begin{bmatrix} +a_{11} & a_{12} & b_1\\ +a_{21} & a_{22} & b_2\\ +\end{bmatrix} +\f] + +The function estimates an optimal 2D affine transformation between two 2D point sets using the +selected robust algorithm. + +The computed transformation is then refined further (using only inliers) with the +Levenberg-Marquardt method to reduce the re-projection error even more. + +@note +The RANSAC method can handle practically any ratio of outliers but needs a threshold to +distinguish inliers from outliers. The method LMeDS does not need any threshold but it works +correctly only when there are more than 50% of inliers. + +@sa estimateAffinePartial2D, getAffineTransform +*/ +CV_EXPORTS_W cv::Mat estimateAffine2D(InputArray from, InputArray to, OutputArray inliers = noArray(), + int method = RANSAC, double ransacReprojThreshold = 3, + size_t maxIters = 2000, double confidence = 0.99, + size_t refineIters = 10); + + +CV_EXPORTS_W cv::Mat estimateAffine2D(InputArray pts1, InputArray pts2, OutputArray inliers, + const UsacParams ¶ms); + +/** @brief Computes an optimal limited affine transformation with 4 degrees of freedom between +two 2D point sets. + +@param from First input 2D point set. +@param to Second input 2D point set. +@param inliers Output vector indicating which points are inliers. +@param method Robust method used to compute transformation. The following methods are possible: +- @ref RANSAC - RANSAC-based robust method +- @ref LMEDS - Least-Median robust method +RANSAC is the default method. +@param ransacReprojThreshold Maximum reprojection error in the RANSAC algorithm to consider +a point as an inlier. Applies only to RANSAC. +@param maxIters The maximum number of robust method iterations. +@param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything +between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation +significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation. +@param refineIters Maximum number of iterations of refining algorithm (Levenberg-Marquardt). +Passing 0 will disable refining, so the output matrix will be output of robust method. + +@return Output 2D affine transformation (4 degrees of freedom) matrix \f$2 \times 3\f$ or +empty matrix if transformation could not be estimated. + +The function estimates an optimal 2D affine transformation with 4 degrees of freedom limited to +combinations of translation, rotation, and uniform scaling. Uses the selected algorithm for robust +estimation. + +The computed transformation is then refined further (using only inliers) with the +Levenberg-Marquardt method to reduce the re-projection error even more. + +Estimated transformation matrix is: +\f[ \begin{bmatrix} \cos(\theta) \cdot s & -\sin(\theta) \cdot s & t_x \\ + \sin(\theta) \cdot s & \cos(\theta) \cdot s & t_y +\end{bmatrix} \f] +Where \f$ \theta \f$ is the rotation angle, \f$ s \f$ the scaling factor and \f$ t_x, t_y \f$ are +translations in \f$ x, y \f$ axes respectively. + +@note +The RANSAC method can handle practically any ratio of outliers but need a threshold to +distinguish inliers from outliers. The method LMeDS does not need any threshold but it works +correctly only when there are more than 50% of inliers. + +@sa estimateAffine2D, getAffineTransform +*/ +CV_EXPORTS_W cv::Mat estimateAffinePartial2D(InputArray from, InputArray to, OutputArray inliers = noArray(), + int method = RANSAC, double ransacReprojThreshold = 3, + size_t maxIters = 2000, double confidence = 0.99, + size_t refineIters = 10); + +/** @example samples/cpp/tutorial_code/features2D/Homography/decompose_homography.cpp +An example program with homography decomposition. + +Check @ref tutorial_homography "the corresponding tutorial" for more details. +*/ + +/** @brief Decompose a homography matrix to rotation(s), translation(s) and plane normal(s). + +@param H The input homography matrix between two images. +@param K The input camera intrinsic matrix. +@param rotations Array of rotation matrices. +@param translations Array of translation matrices. +@param normals Array of plane normal matrices. + +This function extracts relative camera motion between two views of a planar object and returns up to +four mathematical solution tuples of rotation, translation, and plane normal. The decomposition of +the homography matrix H is described in detail in @cite Malis2007. + +If the homography H, induced by the plane, gives the constraint +\f[s_i \vecthree{x'_i}{y'_i}{1} \sim H \vecthree{x_i}{y_i}{1}\f] on the source image points +\f$p_i\f$ and the destination image points \f$p'_i\f$, then the tuple of rotations[k] and +translations[k] is a change of basis from the source camera's coordinate system to the destination +camera's coordinate system. However, by decomposing H, one can only get the translation normalized +by the (typically unknown) depth of the scene, i.e. its direction but with normalized length. + +If point correspondences are available, at least two solutions may further be invalidated, by +applying positive depth constraint, i.e. all points must be in front of the camera. + */ +CV_EXPORTS_W int decomposeHomographyMat(InputArray H, + InputArray K, + OutputArrayOfArrays rotations, + OutputArrayOfArrays translations, + OutputArrayOfArrays normals); + +/** @brief Filters homography decompositions based on additional information. + +@param rotations Vector of rotation matrices. +@param normals Vector of plane normal matrices. +@param beforePoints Vector of (rectified) visible reference points before the homography is applied +@param afterPoints Vector of (rectified) visible reference points after the homography is applied +@param possibleSolutions Vector of int indices representing the viable solution set after filtering +@param pointsMask optional Mat/Vector of 8u type representing the mask for the inliers as given by the #findHomography function + +This function is intended to filter the output of the #decomposeHomographyMat based on additional +information as described in @cite Malis2007 . The summary of the method: the #decomposeHomographyMat function +returns 2 unique solutions and their "opposites" for a total of 4 solutions. If we have access to the +sets of points visible in the camera frame before and after the homography transformation is applied, +we can determine which are the true potential solutions and which are the opposites by verifying which +homographies are consistent with all visible reference points being in front of the camera. The inputs +are left unchanged; the filtered solution set is returned as indices into the existing one. + +*/ +CV_EXPORTS_W void filterHomographyDecompByVisibleRefpoints(InputArrayOfArrays rotations, + InputArrayOfArrays normals, + InputArray beforePoints, + InputArray afterPoints, + OutputArray possibleSolutions, + InputArray pointsMask = noArray()); + +/** @brief The base class for stereo correspondence algorithms. + */ +class CV_EXPORTS_W StereoMatcher : public Algorithm +{ +public: + enum { DISP_SHIFT = 4, + DISP_SCALE = (1 << DISP_SHIFT) + }; + + /** @brief Computes disparity map for the specified stereo pair + + @param left Left 8-bit single-channel image. + @param right Right image of the same size and the same type as the left one. + @param disparity Output disparity map. It has the same size as the input images. Some algorithms, + like StereoBM or StereoSGBM compute 16-bit fixed-point disparity map (where each disparity value + has 4 fractional bits), whereas other algorithms output 32-bit floating-point disparity map. + */ + CV_WRAP virtual void compute( InputArray left, InputArray right, + OutputArray disparity ) = 0; + + CV_WRAP virtual int getMinDisparity() const = 0; + CV_WRAP virtual void setMinDisparity(int minDisparity) = 0; + + CV_WRAP virtual int getNumDisparities() const = 0; + CV_WRAP virtual void setNumDisparities(int numDisparities) = 0; + + CV_WRAP virtual int getBlockSize() const = 0; + CV_WRAP virtual void setBlockSize(int blockSize) = 0; + + CV_WRAP virtual int getSpeckleWindowSize() const = 0; + CV_WRAP virtual void setSpeckleWindowSize(int speckleWindowSize) = 0; + + CV_WRAP virtual int getSpeckleRange() const = 0; + CV_WRAP virtual void setSpeckleRange(int speckleRange) = 0; + + CV_WRAP virtual int getDisp12MaxDiff() const = 0; + CV_WRAP virtual void setDisp12MaxDiff(int disp12MaxDiff) = 0; +}; + + +/** @brief Class for computing stereo correspondence using the block matching algorithm, introduced and +contributed to OpenCV by K. Konolige. + */ +class CV_EXPORTS_W StereoBM : public StereoMatcher +{ +public: + enum { PREFILTER_NORMALIZED_RESPONSE = 0, + PREFILTER_XSOBEL = 1 + }; + + CV_WRAP virtual int getPreFilterType() const = 0; + CV_WRAP virtual void setPreFilterType(int preFilterType) = 0; + + CV_WRAP virtual int getPreFilterSize() const = 0; + CV_WRAP virtual void setPreFilterSize(int preFilterSize) = 0; + + CV_WRAP virtual int getPreFilterCap() const = 0; + CV_WRAP virtual void setPreFilterCap(int preFilterCap) = 0; + + CV_WRAP virtual int getTextureThreshold() const = 0; + CV_WRAP virtual void setTextureThreshold(int textureThreshold) = 0; + + CV_WRAP virtual int getUniquenessRatio() const = 0; + CV_WRAP virtual void setUniquenessRatio(int uniquenessRatio) = 0; + + CV_WRAP virtual int getSmallerBlockSize() const = 0; + CV_WRAP virtual void setSmallerBlockSize(int blockSize) = 0; + + CV_WRAP virtual Rect getROI1() const = 0; + CV_WRAP virtual void setROI1(Rect roi1) = 0; + + CV_WRAP virtual Rect getROI2() const = 0; + CV_WRAP virtual void setROI2(Rect roi2) = 0; + + /** @brief Creates StereoBM object + + @param numDisparities the disparity search range. For each pixel algorithm will find the best + disparity from 0 (default minimum disparity) to numDisparities. The search range can then be + shifted by changing the minimum disparity. + @param blockSize the linear size of the blocks compared by the algorithm. The size should be odd + (as the block is centered at the current pixel). Larger block size implies smoother, though less + accurate disparity map. Smaller block size gives more detailed disparity map, but there is higher + chance for algorithm to find a wrong correspondence. + + The function create StereoBM object. You can then call StereoBM::compute() to compute disparity for + a specific stereo pair. + */ + CV_WRAP static Ptr create(int numDisparities = 0, int blockSize = 21); +}; + +/** @brief The class implements the modified H. Hirschmuller algorithm @cite HH08 that differs from the original +one as follows: + +- By default, the algorithm is single-pass, which means that you consider only 5 directions +instead of 8. Set mode=StereoSGBM::MODE_HH in createStereoSGBM to run the full variant of the +algorithm but beware that it may consume a lot of memory. +- The algorithm matches blocks, not individual pixels. Though, setting blockSize=1 reduces the +blocks to single pixels. +- Mutual information cost function is not implemented. Instead, a simpler Birchfield-Tomasi +sub-pixel metric from @cite BT98 is used. Though, the color images are supported as well. +- Some pre- and post- processing steps from K. Konolige algorithm StereoBM are included, for +example: pre-filtering (StereoBM::PREFILTER_XSOBEL type) and post-filtering (uniqueness +check, quadratic interpolation and speckle filtering). + +@note + - (Python) An example illustrating the use of the StereoSGBM matching algorithm can be found + at opencv_source_code/samples/python/stereo_match.py + */ +class CV_EXPORTS_W StereoSGBM : public StereoMatcher +{ +public: + enum + { + MODE_SGBM = 0, + MODE_HH = 1, + MODE_SGBM_3WAY = 2, + MODE_HH4 = 3 + }; + + CV_WRAP virtual int getPreFilterCap() const = 0; + CV_WRAP virtual void setPreFilterCap(int preFilterCap) = 0; + + CV_WRAP virtual int getUniquenessRatio() const = 0; + CV_WRAP virtual void setUniquenessRatio(int uniquenessRatio) = 0; + + CV_WRAP virtual int getP1() const = 0; + CV_WRAP virtual void setP1(int P1) = 0; + + CV_WRAP virtual int getP2() const = 0; + CV_WRAP virtual void setP2(int P2) = 0; + + CV_WRAP virtual int getMode() const = 0; + CV_WRAP virtual void setMode(int mode) = 0; + + /** @brief Creates StereoSGBM object + + @param minDisparity Minimum possible disparity value. Normally, it is zero but sometimes + rectification algorithms can shift images, so this parameter needs to be adjusted accordingly. + @param numDisparities Maximum disparity minus minimum disparity. The value is always greater than + zero. In the current implementation, this parameter must be divisible by 16. + @param blockSize Matched block size. It must be an odd number \>=1 . Normally, it should be + somewhere in the 3..11 range. + @param P1 The first parameter controlling the disparity smoothness. See below. + @param P2 The second parameter controlling the disparity smoothness. The larger the values are, + the smoother the disparity is. P1 is the penalty on the disparity change by plus or minus 1 + between neighbor pixels. P2 is the penalty on the disparity change by more than 1 between neighbor + pixels. The algorithm requires P2 \> P1 . See stereo_match.cpp sample where some reasonably good + P1 and P2 values are shown (like 8\*number_of_image_channels\*blockSize\*blockSize and + 32\*number_of_image_channels\*blockSize\*blockSize , respectively). + @param disp12MaxDiff Maximum allowed difference (in integer pixel units) in the left-right + disparity check. Set it to a non-positive value to disable the check. + @param preFilterCap Truncation value for the prefiltered image pixels. The algorithm first + computes x-derivative at each pixel and clips its value by [-preFilterCap, preFilterCap] interval. + The result values are passed to the Birchfield-Tomasi pixel cost function. + @param uniquenessRatio Margin in percentage by which the best (minimum) computed cost function + value should "win" the second best value to consider the found match correct. Normally, a value + within the 5-15 range is good enough. + @param speckleWindowSize Maximum size of smooth disparity regions to consider their noise speckles + and invalidate. Set it to 0 to disable speckle filtering. Otherwise, set it somewhere in the + 50-200 range. + @param speckleRange Maximum disparity variation within each connected component. If you do speckle + filtering, set the parameter to a positive value, it will be implicitly multiplied by 16. + Normally, 1 or 2 is good enough. + @param mode Set it to StereoSGBM::MODE_HH to run the full-scale two-pass dynamic programming + algorithm. It will consume O(W\*H\*numDisparities) bytes, which is large for 640x480 stereo and + huge for HD-size pictures. By default, it is set to false . + + The first constructor initializes StereoSGBM with all the default parameters. So, you only have to + set StereoSGBM::numDisparities at minimum. The second constructor enables you to set each parameter + to a custom value. + */ + CV_WRAP static Ptr create(int minDisparity = 0, int numDisparities = 16, int blockSize = 3, + int P1 = 0, int P2 = 0, int disp12MaxDiff = 0, + int preFilterCap = 0, int uniquenessRatio = 0, + int speckleWindowSize = 0, int speckleRange = 0, + int mode = StereoSGBM::MODE_SGBM); +}; + + +//! cv::undistort mode +enum UndistortTypes +{ + PROJ_SPHERICAL_ORTHO = 0, + PROJ_SPHERICAL_EQRECT = 1 +}; + +/** @brief Transforms an image to compensate for lens distortion. + +The function transforms an image to compensate radial and tangential lens distortion. + +The function is simply a combination of #initUndistortRectifyMap (with unity R ) and #remap +(with bilinear interpolation). See the former function for details of the transformation being +performed. + +Those pixels in the destination image, for which there is no correspondent pixels in the source +image, are filled with zeros (black color). + +A particular subset of the source image that will be visible in the corrected image can be regulated +by newCameraMatrix. You can use #getOptimalNewCameraMatrix to compute the appropriate +newCameraMatrix depending on your requirements. + +The camera matrix and the distortion parameters can be determined using #calibrateCamera. If +the resolution of images is different from the resolution used at the calibration stage, \f$f_x, +f_y, c_x\f$ and \f$c_y\f$ need to be scaled accordingly, while the distortion coefficients remain +the same. + +@param src Input (distorted) image. +@param dst Output (corrected) image that has the same size and type as src . +@param cameraMatrix Input camera matrix \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . +@param distCoeffs Input vector of distortion coefficients +\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ +of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. +@param newCameraMatrix Camera matrix of the distorted image. By default, it is the same as +cameraMatrix but you may additionally scale and shift the result by using a different matrix. + */ +CV_EXPORTS_W void undistort( InputArray src, OutputArray dst, + InputArray cameraMatrix, + InputArray distCoeffs, + InputArray newCameraMatrix = noArray() ); + +/** @brief Computes the undistortion and rectification transformation map. + +The function computes the joint undistortion and rectification transformation and represents the +result in the form of maps for #remap. The undistorted image looks like original, as if it is +captured with a camera using the camera matrix =newCameraMatrix and zero distortion. In case of a +monocular camera, newCameraMatrix is usually equal to cameraMatrix, or it can be computed by +#getOptimalNewCameraMatrix for a better control over scaling. In case of a stereo camera, +newCameraMatrix is normally set to P1 or P2 computed by #stereoRectify . + +Also, this new camera is oriented differently in the coordinate space, according to R. That, for +example, helps to align two heads of a stereo camera so that the epipolar lines on both images +become horizontal and have the same y- coordinate (in case of a horizontally aligned stereo camera). + +The function actually builds the maps for the inverse mapping algorithm that is used by #remap. That +is, for each pixel \f$(u, v)\f$ in the destination (corrected and rectified) image, the function +computes the corresponding coordinates in the source image (that is, in the original image from +camera). The following process is applied: +\f[ +\begin{array}{l} +x \leftarrow (u - {c'}_x)/{f'}_x \\ +y \leftarrow (v - {c'}_y)/{f'}_y \\ +{[X\,Y\,W]} ^T \leftarrow R^{-1}*[x \, y \, 1]^T \\ +x' \leftarrow X/W \\ +y' \leftarrow Y/W \\ +r^2 \leftarrow x'^2 + y'^2 \\ +x'' \leftarrow x' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} ++ 2p_1 x' y' + p_2(r^2 + 2 x'^2) + s_1 r^2 + s_2 r^4\\ +y'' \leftarrow y' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} ++ p_1 (r^2 + 2 y'^2) + 2 p_2 x' y' + s_3 r^2 + s_4 r^4 \\ +s\vecthree{x'''}{y'''}{1} = +\vecthreethree{R_{33}(\tau_x, \tau_y)}{0}{-R_{13}((\tau_x, \tau_y)} +{0}{R_{33}(\tau_x, \tau_y)}{-R_{23}(\tau_x, \tau_y)} +{0}{0}{1} R(\tau_x, \tau_y) \vecthree{x''}{y''}{1}\\ +map_x(u,v) \leftarrow x''' f_x + c_x \\ +map_y(u,v) \leftarrow y''' f_y + c_y +\end{array} +\f] +where \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ +are the distortion coefficients. + +In case of a stereo camera, this function is called twice: once for each camera head, after +#stereoRectify, which in its turn is called after #stereoCalibrate. But if the stereo camera +was not calibrated, it is still possible to compute the rectification transformations directly from +the fundamental matrix using #stereoRectifyUncalibrated. For each camera, the function computes +homography H as the rectification transformation in a pixel domain, not a rotation matrix R in 3D +space. R can be computed from H as +\f[\texttt{R} = \texttt{cameraMatrix} ^{-1} \cdot \texttt{H} \cdot \texttt{cameraMatrix}\f] +where cameraMatrix can be chosen arbitrarily. + +@param cameraMatrix Input camera matrix \f$A=\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . +@param distCoeffs Input vector of distortion coefficients +\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ +of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. +@param R Optional rectification transformation in the object space (3x3 matrix). R1 or R2 , +computed by #stereoRectify can be passed here. If the matrix is empty, the identity transformation +is assumed. In #initUndistortRectifyMap R assumed to be an identity matrix. +@param newCameraMatrix New camera matrix \f$A'=\vecthreethree{f_x'}{0}{c_x'}{0}{f_y'}{c_y'}{0}{0}{1}\f$. +@param size Undistorted image size. +@param m1type Type of the first output map that can be CV_32FC1, CV_32FC2 or CV_16SC2, see #convertMaps +@param map1 The first output map. +@param map2 The second output map. + */ +CV_EXPORTS_W +void initUndistortRectifyMap(InputArray cameraMatrix, InputArray distCoeffs, + InputArray R, InputArray newCameraMatrix, + Size size, int m1type, OutputArray map1, OutputArray map2); + +/** @brief Computes the projection and inverse-rectification transformation map. In essense, this is the inverse of +#initUndistortRectifyMap to accomodate stereo-rectification of projectors ('inverse-cameras') in projector-camera pairs. + +The function computes the joint projection and inverse rectification transformation and represents the +result in the form of maps for #remap. The projected image looks like a distorted version of the original which, +once projected by a projector, should visually match the original. In case of a monocular camera, newCameraMatrix +is usually equal to cameraMatrix, or it can be computed by +#getOptimalNewCameraMatrix for a better control over scaling. In case of a projector-camera pair, +newCameraMatrix is normally set to P1 or P2 computed by #stereoRectify . + +The projector is oriented differently in the coordinate space, according to R. In case of projector-camera pairs, +this helps align the projector (in the same manner as #initUndistortRectifyMap for the camera) to create a stereo-rectified pair. This +allows epipolar lines on both images to become horizontal and have the same y-coordinate (in case of a horizontally aligned projector-camera pair). + +The function builds the maps for the inverse mapping algorithm that is used by #remap. That +is, for each pixel \f$(u, v)\f$ in the destination (projected and inverse-rectified) image, the function +computes the corresponding coordinates in the source image (that is, in the original digital image). The following process is applied: + +\f[ +\begin{array}{l} +\text{newCameraMatrix}\\ +x \leftarrow (u - {c'}_x)/{f'}_x \\ +y \leftarrow (v - {c'}_y)/{f'}_y \\ + +\\\text{Undistortion} +\\\scriptsize{\textit{though equation shown is for radial undistortion, function implements cv::undistortPoints()}}\\ +r^2 \leftarrow x^2 + y^2 \\ +\theta \leftarrow \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6}\\ +x' \leftarrow \frac{x}{\theta} \\ +y' \leftarrow \frac{y}{\theta} \\ + +\\\text{Rectification}\\ +{[X\,Y\,W]} ^T \leftarrow R*[x' \, y' \, 1]^T \\ +x'' \leftarrow X/W \\ +y'' \leftarrow Y/W \\ + +\\\text{cameraMatrix}\\ +map_x(u,v) \leftarrow x'' f_x + c_x \\ +map_y(u,v) \leftarrow y'' f_y + c_y +\end{array} +\f] +where \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ +are the distortion coefficients vector distCoeffs. + +In case of a stereo-rectified projector-camera pair, this function is called for the projector while #initUndistortRectifyMap is called for the camera head. +This is done after #stereoRectify, which in turn is called after #stereoCalibrate. If the projector-camera pair +is not calibrated, it is still possible to compute the rectification transformations directly from +the fundamental matrix using #stereoRectifyUncalibrated. For the projector and camera, the function computes +homography H as the rectification transformation in a pixel domain, not a rotation matrix R in 3D +space. R can be computed from H as +\f[\texttt{R} = \texttt{cameraMatrix} ^{-1} \cdot \texttt{H} \cdot \texttt{cameraMatrix}\f] +where cameraMatrix can be chosen arbitrarily. + +@param cameraMatrix Input camera matrix \f$A=\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . +@param distCoeffs Input vector of distortion coefficients +\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ +of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. +@param R Optional rectification transformation in the object space (3x3 matrix). R1 or R2, +computed by #stereoRectify can be passed here. If the matrix is empty, the identity transformation +is assumed. +@param newCameraMatrix New camera matrix \f$A'=\vecthreethree{f_x'}{0}{c_x'}{0}{f_y'}{c_y'}{0}{0}{1}\f$. +@param size Distorted image size. +@param m1type Type of the first output map. Can be CV_32FC1, CV_32FC2 or CV_16SC2, see #convertMaps +@param map1 The first output map for #remap. +@param map2 The second output map for #remap. + */ +CV_EXPORTS_W +void initInverseRectificationMap( InputArray cameraMatrix, InputArray distCoeffs, + InputArray R, InputArray newCameraMatrix, + const Size& size, int m1type, OutputArray map1, OutputArray map2 ); + +//! initializes maps for #remap for wide-angle +CV_EXPORTS +float initWideAngleProjMap(InputArray cameraMatrix, InputArray distCoeffs, + Size imageSize, int destImageWidth, + int m1type, OutputArray map1, OutputArray map2, + enum UndistortTypes projType = PROJ_SPHERICAL_EQRECT, double alpha = 0); +static inline +float initWideAngleProjMap(InputArray cameraMatrix, InputArray distCoeffs, + Size imageSize, int destImageWidth, + int m1type, OutputArray map1, OutputArray map2, + int projType, double alpha = 0) +{ + return initWideAngleProjMap(cameraMatrix, distCoeffs, imageSize, destImageWidth, + m1type, map1, map2, (UndistortTypes)projType, alpha); +} + +/** @brief Returns the default new camera matrix. + +The function returns the camera matrix that is either an exact copy of the input cameraMatrix (when +centerPrinicipalPoint=false ), or the modified one (when centerPrincipalPoint=true). + +In the latter case, the new camera matrix will be: + +\f[\begin{bmatrix} f_x && 0 && ( \texttt{imgSize.width} -1)*0.5 \\ 0 && f_y && ( \texttt{imgSize.height} -1)*0.5 \\ 0 && 0 && 1 \end{bmatrix} ,\f] + +where \f$f_x\f$ and \f$f_y\f$ are \f$(0,0)\f$ and \f$(1,1)\f$ elements of cameraMatrix, respectively. + +By default, the undistortion functions in OpenCV (see #initUndistortRectifyMap, #undistort) do not +move the principal point. However, when you work with stereo, it is important to move the principal +points in both views to the same y-coordinate (which is required by most of stereo correspondence +algorithms), and may be to the same x-coordinate too. So, you can form the new camera matrix for +each view where the principal points are located at the center. + +@param cameraMatrix Input camera matrix. +@param imgsize Camera view image size in pixels. +@param centerPrincipalPoint Location of the principal point in the new camera matrix. The +parameter indicates whether this location should be at the image center or not. + */ +CV_EXPORTS_W +Mat getDefaultNewCameraMatrix(InputArray cameraMatrix, Size imgsize = Size(), + bool centerPrincipalPoint = false); + +/** @brief Computes the ideal point coordinates from the observed point coordinates. + +The function is similar to #undistort and #initUndistortRectifyMap but it operates on a +sparse set of points instead of a raster image. Also the function performs a reverse transformation +to #projectPoints. In case of a 3D object, it does not reconstruct its 3D coordinates, but for a +planar object, it does, up to a translation vector, if the proper R is specified. + +For each observed point coordinate \f$(u, v)\f$ the function computes: +\f[ +\begin{array}{l} +x^{"} \leftarrow (u - c_x)/f_x \\ +y^{"} \leftarrow (v - c_y)/f_y \\ +(x',y') = undistort(x^{"},y^{"}, \texttt{distCoeffs}) \\ +{[X\,Y\,W]} ^T \leftarrow R*[x' \, y' \, 1]^T \\ +x \leftarrow X/W \\ +y \leftarrow Y/W \\ +\text{only performed if P is specified:} \\ +u' \leftarrow x {f'}_x + {c'}_x \\ +v' \leftarrow y {f'}_y + {c'}_y +\end{array} +\f] + +where *undistort* is an approximate iterative algorithm that estimates the normalized original +point coordinates out of the normalized distorted point coordinates ("normalized" means that the +coordinates do not depend on the camera matrix). + +The function can be used for both a stereo camera head or a monocular camera (when R is empty). +@param src Observed point coordinates, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel (CV_32FC2 or CV_64FC2) (or +vector\ ). +@param dst Output ideal point coordinates (1xN/Nx1 2-channel or vector\ ) after undistortion and reverse perspective +transformation. If matrix P is identity or omitted, dst will contain normalized point coordinates. +@param cameraMatrix Camera matrix \f$\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . +@param distCoeffs Input vector of distortion coefficients +\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ +of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. +@param R Rectification transformation in the object space (3x3 matrix). R1 or R2 computed by +#stereoRectify can be passed here. If the matrix is empty, the identity transformation is used. +@param P New camera matrix (3x3) or new projection matrix (3x4) \f$\begin{bmatrix} {f'}_x & 0 & {c'}_x & t_x \\ 0 & {f'}_y & {c'}_y & t_y \\ 0 & 0 & 1 & t_z \end{bmatrix}\f$. P1 or P2 computed by +#stereoRectify can be passed here. If the matrix is empty, the identity new camera matrix is used. + */ +CV_EXPORTS_W +void undistortPoints(InputArray src, OutputArray dst, + InputArray cameraMatrix, InputArray distCoeffs, + InputArray R = noArray(), InputArray P = noArray()); +/** @overload + @note Default version of #undistortPoints does 5 iterations to compute undistorted points. + */ +CV_EXPORTS_AS(undistortPointsIter) +void undistortPoints(InputArray src, OutputArray dst, + InputArray cameraMatrix, InputArray distCoeffs, + InputArray R, InputArray P, TermCriteria criteria); + +/** + * @brief Compute undistorted image points position + * + * @param src Observed points position, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel (CV_32FC2 or +CV_64FC2) (or vector\ ). + * @param dst Output undistorted points position (1xN/Nx1 2-channel or vector\ ). + * @param cameraMatrix Camera matrix \f$\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . + * @param distCoeffs Distortion coefficients + */ +CV_EXPORTS_W +void undistortImagePoints(InputArray src, OutputArray dst, InputArray cameraMatrix, + InputArray distCoeffs, + TermCriteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, + 0.01)); + +//! @} calib3d + +/** @brief The methods in this namespace use a so-called fisheye camera model. + @ingroup calib3d_fisheye +*/ +namespace fisheye +{ +//! @addtogroup calib3d_fisheye +//! @{ + + enum{ + CALIB_USE_INTRINSIC_GUESS = 1 << 0, + CALIB_RECOMPUTE_EXTRINSIC = 1 << 1, + CALIB_CHECK_COND = 1 << 2, + CALIB_FIX_SKEW = 1 << 3, + CALIB_FIX_K1 = 1 << 4, + CALIB_FIX_K2 = 1 << 5, + CALIB_FIX_K3 = 1 << 6, + CALIB_FIX_K4 = 1 << 7, + CALIB_FIX_INTRINSIC = 1 << 8, + CALIB_FIX_PRINCIPAL_POINT = 1 << 9, + CALIB_ZERO_DISPARITY = 1 << 10, + CALIB_FIX_FOCAL_LENGTH = 1 << 11 + }; + + /** @brief Projects points using fisheye model + + @param objectPoints Array of object points, 1xN/Nx1 3-channel (or vector\ ), where N is + the number of points in the view. + @param imagePoints Output array of image points, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel, or + vector\. + @param affine + @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. + @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. + @param alpha The skew coefficient. + @param jacobian Optional output 2Nx15 jacobian matrix of derivatives of image points with respect + to components of the focal lengths, coordinates of the principal point, distortion coefficients, + rotation vector, translation vector, and the skew. In the old interface different components of + the jacobian are returned via different output parameters. + + The function computes projections of 3D points to the image plane given intrinsic and extrinsic + camera parameters. Optionally, the function computes Jacobians - matrices of partial derivatives of + image points coordinates (as functions of all the input parameters) with respect to the particular + parameters, intrinsic and/or extrinsic. + */ + CV_EXPORTS void projectPoints(InputArray objectPoints, OutputArray imagePoints, const Affine3d& affine, + InputArray K, InputArray D, double alpha = 0, OutputArray jacobian = noArray()); + + /** @overload */ + CV_EXPORTS_W void projectPoints(InputArray objectPoints, OutputArray imagePoints, InputArray rvec, InputArray tvec, + InputArray K, InputArray D, double alpha = 0, OutputArray jacobian = noArray()); + + /** @brief Distorts 2D points using fisheye model. + + @param undistorted Array of object points, 1xN/Nx1 2-channel (or vector\ ), where N is + the number of points in the view. + @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. + @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. + @param alpha The skew coefficient. + @param distorted Output array of image points, 1xN/Nx1 2-channel, or vector\ . + + Note that the function assumes the camera intrinsic matrix of the undistorted points to be identity. + This means if you want to distort image points you have to multiply them with \f$K^{-1}\f$ or + use another function overload. + */ + CV_EXPORTS_W void distortPoints(InputArray undistorted, OutputArray distorted, InputArray K, InputArray D, double alpha = 0); + + /** @overload + Overload of distortPoints function to handle cases when undistorted points are obtained with non-identity + camera matrix, e.g. output of #estimateNewCameraMatrixForUndistortRectify. + @param undistorted Array of object points, 1xN/Nx1 2-channel (or vector\ ), where N is + the number of points in the view. + @param Kundistorted Camera intrinsic matrix used as new camera matrix for undistortion. + @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. + @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. + @param alpha The skew coefficient. + @param distorted Output array of image points, 1xN/Nx1 2-channel, or vector\ . + @sa estimateNewCameraMatrixForUndistortRectify + */ + CV_EXPORTS_W void distortPoints(InputArray undistorted, OutputArray distorted, InputArray Kundistorted, InputArray K, InputArray D, double alpha = 0); + + /** @brief Undistorts 2D points using fisheye model + + @param distorted Array of object points, 1xN/Nx1 2-channel (or vector\ ), where N is the + number of points in the view. + @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. + @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. + @param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3 + 1-channel or 1x1 3-channel + @param P New camera intrinsic matrix (3x3) or new projection matrix (3x4) + @param criteria Termination criteria + @param undistorted Output array of image points, 1xN/Nx1 2-channel, or vector\ . + */ + CV_EXPORTS_W void undistortPoints(InputArray distorted, OutputArray undistorted, + InputArray K, InputArray D, InputArray R = noArray(), InputArray P = noArray(), + TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 10, 1e-8)); + + /** @brief Computes undistortion and rectification maps for image transform by #remap. If D is empty zero + distortion is used, if R or P is empty identity matrixes are used. + + @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. + @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. + @param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3 + 1-channel or 1x1 3-channel + @param P New camera intrinsic matrix (3x3) or new projection matrix (3x4) + @param size Undistorted image size. + @param m1type Type of the first output map that can be CV_32FC1 or CV_16SC2 . See #convertMaps + for details. + @param map1 The first output map. + @param map2 The second output map. + */ + CV_EXPORTS_W void initUndistortRectifyMap(InputArray K, InputArray D, InputArray R, InputArray P, + const cv::Size& size, int m1type, OutputArray map1, OutputArray map2); + + /** @brief Transforms an image to compensate for fisheye lens distortion. + + @param distorted image with fisheye lens distortion. + @param undistorted Output image with compensated fisheye lens distortion. + @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. + @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. + @param Knew Camera intrinsic matrix of the distorted image. By default, it is the identity matrix but you + may additionally scale and shift the result by using a different matrix. + @param new_size the new size + + The function transforms an image to compensate radial and tangential lens distortion. + + The function is simply a combination of #fisheye::initUndistortRectifyMap (with unity R ) and #remap + (with bilinear interpolation). See the former function for details of the transformation being + performed. + + See below the results of undistortImage. + - a\) result of undistort of perspective camera model (all possible coefficients (k_1, k_2, k_3, + k_4, k_5, k_6) of distortion were optimized under calibration) + - b\) result of #fisheye::undistortImage of fisheye camera model (all possible coefficients (k_1, k_2, + k_3, k_4) of fisheye distortion were optimized under calibration) + - c\) original image was captured with fisheye lens + + Pictures a) and b) almost the same. But if we consider points of image located far from the center + of image, we can notice that on image a) these points are distorted. + + ![image](pics/fisheye_undistorted.jpg) + */ + CV_EXPORTS_W void undistortImage(InputArray distorted, OutputArray undistorted, + InputArray K, InputArray D, InputArray Knew = cv::noArray(), const Size& new_size = Size()); + + /** @brief Estimates new camera intrinsic matrix for undistortion or rectification. + + @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. + @param image_size Size of the image + @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. + @param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3 + 1-channel or 1x1 3-channel + @param P New camera intrinsic matrix (3x3) or new projection matrix (3x4) + @param balance Sets the new focal length in range between the min focal length and the max focal + length. Balance is in range of [0, 1]. + @param new_size the new size + @param fov_scale Divisor for new focal length. + */ + CV_EXPORTS_W void estimateNewCameraMatrixForUndistortRectify(InputArray K, InputArray D, const Size &image_size, InputArray R, + OutputArray P, double balance = 0.0, const Size& new_size = Size(), double fov_scale = 1.0); + + /** @brief Performs camera calibration + + @param objectPoints vector of vectors of calibration pattern points in the calibration pattern + coordinate space. + @param imagePoints vector of vectors of the projections of calibration pattern points. + imagePoints.size() and objectPoints.size() and imagePoints[i].size() must be equal to + objectPoints[i].size() for each i. + @param image_size Size of the image used only to initialize the camera intrinsic matrix. + @param K Output 3x3 floating-point camera intrinsic matrix + \f$\cameramatrix{A}\f$ . If + @ref fisheye::CALIB_USE_INTRINSIC_GUESS is specified, some or all of fx, fy, cx, cy must be + initialized before calling the function. + @param D Output vector of distortion coefficients \f$\distcoeffsfisheye\f$. + @param rvecs Output vector of rotation vectors (see @ref Rodrigues ) estimated for each pattern view. + That is, each k-th rotation vector together with the corresponding k-th translation vector (see + the next output parameter description) brings the calibration pattern from the model coordinate + space (in which object points are specified) to the world coordinate space, that is, a real + position of the calibration pattern in the k-th pattern view (k=0.. *M* -1). + @param tvecs Output vector of translation vectors estimated for each pattern view. + @param flags Different flags that may be zero or a combination of the following values: + - @ref fisheye::CALIB_USE_INTRINSIC_GUESS cameraMatrix contains valid initial values of + fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image + center ( imageSize is used), and focal distances are computed in a least-squares fashion. + - @ref fisheye::CALIB_RECOMPUTE_EXTRINSIC Extrinsic will be recomputed after each iteration + of intrinsic optimization. + - @ref fisheye::CALIB_CHECK_COND The functions will check validity of condition number. + - @ref fisheye::CALIB_FIX_SKEW Skew coefficient (alpha) is set to zero and stay zero. + - @ref fisheye::CALIB_FIX_K1,..., @ref fisheye::CALIB_FIX_K4 Selected distortion coefficients + are set to zeros and stay zero. + - @ref fisheye::CALIB_FIX_PRINCIPAL_POINT The principal point is not changed during the global +optimization. It stays at the center or at a different location specified when @ref fisheye::CALIB_USE_INTRINSIC_GUESS is set too. + - @ref fisheye::CALIB_FIX_FOCAL_LENGTH The focal length is not changed during the global +optimization. It is the \f$max(width,height)/\pi\f$ or the provided \f$f_x\f$, \f$f_y\f$ when @ref fisheye::CALIB_USE_INTRINSIC_GUESS is set too. + @param criteria Termination criteria for the iterative optimization algorithm. + */ + CV_EXPORTS_W double calibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, const Size& image_size, + InputOutputArray K, InputOutputArray D, OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, int flags = 0, + TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON)); + + /** @brief Stereo rectification for fisheye camera model + + @param K1 First camera intrinsic matrix. + @param D1 First camera distortion parameters. + @param K2 Second camera intrinsic matrix. + @param D2 Second camera distortion parameters. + @param imageSize Size of the image used for stereo calibration. + @param R Rotation matrix between the coordinate systems of the first and the second + cameras. + @param tvec Translation vector between coordinate systems of the cameras. + @param R1 Output 3x3 rectification transform (rotation matrix) for the first camera. + @param R2 Output 3x3 rectification transform (rotation matrix) for the second camera. + @param P1 Output 3x4 projection matrix in the new (rectified) coordinate systems for the first + camera. + @param P2 Output 3x4 projection matrix in the new (rectified) coordinate systems for the second + camera. + @param Q Output \f$4 \times 4\f$ disparity-to-depth mapping matrix (see #reprojectImageTo3D ). + @param flags Operation flags that may be zero or @ref fisheye::CALIB_ZERO_DISPARITY . If the flag is set, + the function makes the principal points of each camera have the same pixel coordinates in the + rectified views. And if the flag is not set, the function may still shift the images in the + horizontal or vertical direction (depending on the orientation of epipolar lines) to maximize the + useful image area. + @param newImageSize New image resolution after rectification. The same size should be passed to + #initUndistortRectifyMap (see the stereo_calib.cpp sample in OpenCV samples directory). When (0,0) + is passed (default), it is set to the original imageSize . Setting it to larger value can help you + preserve details in the original image, especially when there is a big radial distortion. + @param balance Sets the new focal length in range between the min focal length and the max focal + length. Balance is in range of [0, 1]. + @param fov_scale Divisor for new focal length. + */ + CV_EXPORTS_W void stereoRectify(InputArray K1, InputArray D1, InputArray K2, InputArray D2, const Size &imageSize, InputArray R, InputArray tvec, + OutputArray R1, OutputArray R2, OutputArray P1, OutputArray P2, OutputArray Q, int flags, const Size &newImageSize = Size(), + double balance = 0.0, double fov_scale = 1.0); + + /** @brief Performs stereo calibration + + @param objectPoints Vector of vectors of the calibration pattern points. + @param imagePoints1 Vector of vectors of the projections of the calibration pattern points, + observed by the first camera. + @param imagePoints2 Vector of vectors of the projections of the calibration pattern points, + observed by the second camera. + @param K1 Input/output first camera intrinsic matrix: + \f$\vecthreethree{f_x^{(j)}}{0}{c_x^{(j)}}{0}{f_y^{(j)}}{c_y^{(j)}}{0}{0}{1}\f$ , \f$j = 0,\, 1\f$ . If + any of @ref fisheye::CALIB_USE_INTRINSIC_GUESS , @ref fisheye::CALIB_FIX_INTRINSIC are specified, + some or all of the matrix components must be initialized. + @param D1 Input/output vector of distortion coefficients \f$\distcoeffsfisheye\f$ of 4 elements. + @param K2 Input/output second camera intrinsic matrix. The parameter is similar to K1 . + @param D2 Input/output lens distortion coefficients for the second camera. The parameter is + similar to D1 . + @param imageSize Size of the image used only to initialize camera intrinsic matrix. + @param R Output rotation matrix between the 1st and the 2nd camera coordinate systems. + @param T Output translation vector between the coordinate systems of the cameras. + @param rvecs Output vector of rotation vectors ( @ref Rodrigues ) estimated for each pattern view in the + coordinate system of the first camera of the stereo pair (e.g. std::vector). More in detail, each + i-th rotation vector together with the corresponding i-th translation vector (see the next output parameter + description) brings the calibration pattern from the object coordinate space (in which object points are + specified) to the camera coordinate space of the first camera of the stereo pair. In more technical terms, + the tuple of the i-th rotation and translation vector performs a change of basis from object coordinate space + to camera coordinate space of the first camera of the stereo pair. + @param tvecs Output vector of translation vectors estimated for each pattern view, see parameter description + of previous output parameter ( rvecs ). + @param flags Different flags that may be zero or a combination of the following values: + - @ref fisheye::CALIB_FIX_INTRINSIC Fix K1, K2? and D1, D2? so that only R, T matrices + are estimated. + - @ref fisheye::CALIB_USE_INTRINSIC_GUESS K1, K2 contains valid initial values of + fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image + center (imageSize is used), and focal distances are computed in a least-squares fashion. + - @ref fisheye::CALIB_RECOMPUTE_EXTRINSIC Extrinsic will be recomputed after each iteration + of intrinsic optimization. + - @ref fisheye::CALIB_CHECK_COND The functions will check validity of condition number. + - @ref fisheye::CALIB_FIX_SKEW Skew coefficient (alpha) is set to zero and stay zero. + - @ref fisheye::CALIB_FIX_K1,..., @ref fisheye::CALIB_FIX_K4 Selected distortion coefficients are set to zeros and stay + zero. + @param criteria Termination criteria for the iterative optimization algorithm. + */ + CV_EXPORTS_W double stereoCalibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, + InputOutputArray K1, InputOutputArray D1, InputOutputArray K2, InputOutputArray D2, Size imageSize, + OutputArray R, OutputArray T, OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, int flags = fisheye::CALIB_FIX_INTRINSIC, + TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON)); + + /// @overload + CV_EXPORTS_W double stereoCalibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, + InputOutputArray K1, InputOutputArray D1, InputOutputArray K2, InputOutputArray D2, Size imageSize, + OutputArray R, OutputArray T, int flags = fisheye::CALIB_FIX_INTRINSIC, + TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON)); + + /** + @brief Finds an object pose from 3D-2D point correspondences for fisheye camera moodel. + + @param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or + 1xN/Nx1 3-channel, where N is the number of points. vector\ can be also passed here. + @param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel, + where N is the number of points. vector\ can be also passed here. + @param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . + @param distCoeffs Input vector of distortion coefficients (4x1/1x4). + @param rvec Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from + the model coordinate system to the camera coordinate system. + @param tvec Output translation vector. + @param useExtrinsicGuess Parameter used for #SOLVEPNP_ITERATIVE. If true (1), the function uses + the provided rvec and tvec values as initial approximations of the rotation and translation + vectors, respectively, and further optimizes them. + @param flags Method for solving a PnP problem: see @ref calib3d_solvePnP_flags + This function returns the rotation and the translation vectors that transform a 3D point expressed in the object + coordinate frame to the camera coordinate frame, using different methods: + - P3P methods (@ref SOLVEPNP_P3P, @ref SOLVEPNP_AP3P): need 4 input points to return a unique solution. + - @ref SOLVEPNP_IPPE Input points must be >= 4 and object points must be coplanar. + - @ref SOLVEPNP_IPPE_SQUARE Special case suitable for marker pose estimation. + Number of input points must be 4. Object points must be defined in the following order: + - point 0: [-squareLength / 2, squareLength / 2, 0] + - point 1: [ squareLength / 2, squareLength / 2, 0] + - point 2: [ squareLength / 2, -squareLength / 2, 0] + - point 3: [-squareLength / 2, -squareLength / 2, 0] + - for all the other flags, number of input points must be >= 4 and object points can be in any configuration. + @param criteria Termination criteria for internal undistortPoints call. + The function interally undistorts points with @ref undistortPoints and call @ref cv::solvePnP, + thus the input are very similar. More information about Perspective-n-Points is described in @ref calib3d_solvePnP + for more information. + */ + CV_EXPORTS_W bool solvePnP( InputArray objectPoints, InputArray imagePoints, + InputArray cameraMatrix, InputArray distCoeffs, + OutputArray rvec, OutputArray tvec, + bool useExtrinsicGuess = false, int flags = SOLVEPNP_ITERATIVE, + TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 10, 1e-8) + ); + +//! @} calib3d_fisheye +} // end namespace fisheye + +} //end namespace cv + +#if 0 //def __cplusplus +////////////////////////////////////////////////////////////////////////////////////////// +class CV_EXPORTS CvLevMarq +{ +public: + CvLevMarq(); + CvLevMarq( int nparams, int nerrs, CvTermCriteria criteria= + cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON), + bool completeSymmFlag=false ); + ~CvLevMarq(); + void init( int nparams, int nerrs, CvTermCriteria criteria= + cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON), + bool completeSymmFlag=false ); + bool update( const CvMat*& param, CvMat*& J, CvMat*& err ); + bool updateAlt( const CvMat*& param, CvMat*& JtJ, CvMat*& JtErr, double*& errNorm ); + + void clear(); + void step(); + enum { DONE=0, STARTED=1, CALC_J=2, CHECK_ERR=3 }; + + cv::Ptr mask; + cv::Ptr prevParam; + cv::Ptr param; + cv::Ptr J; + cv::Ptr err; + cv::Ptr JtJ; + cv::Ptr JtJN; + cv::Ptr JtErr; + cv::Ptr JtJV; + cv::Ptr JtJW; + double prevErrNorm, errNorm; + int lambdaLg10; + CvTermCriteria criteria; + int state; + int iters; + bool completeSymmFlag; + int solveMethod; +}; +#endif + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/calib3d/calib3d.hpp b/3rdParty/opencv-4.11.0/opencv2/calib3d/calib3d.hpp index b3da45edd5..9cae7f4cdd 100644 --- a/3rdParty/opencv-4.11.0/opencv2/calib3d/calib3d.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/calib3d/calib3d.hpp @@ -1,48 +1,48 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifdef __OPENCV_BUILD -#error this is a compatibility header which should not be used inside the OpenCV library -#endif - -#include "opencv2/calib3d.hpp" +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/calib3d.hpp" diff --git a/3rdParty/opencv-4.11.0/opencv2/calib3d/calib3d_c.h b/3rdParty/opencv-4.11.0/opencv2/calib3d/calib3d_c.h index e2af07b2e2..d3072cc00c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/calib3d/calib3d_c.h +++ b/3rdParty/opencv-4.11.0/opencv2/calib3d/calib3d_c.h @@ -1,150 +1,150 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CALIB3D_C_H -#define OPENCV_CALIB3D_C_H - -#include "opencv2/core/types_c.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* Calculates fundamental matrix given a set of corresponding points */ -#define CV_FM_7POINT 1 -#define CV_FM_8POINT 2 - -#define CV_LMEDS 4 -#define CV_RANSAC 8 - -#define CV_FM_LMEDS_ONLY CV_LMEDS -#define CV_FM_RANSAC_ONLY CV_RANSAC -#define CV_FM_LMEDS CV_LMEDS -#define CV_FM_RANSAC CV_RANSAC - -enum -{ - CV_ITERATIVE = 0, - CV_EPNP = 1, // F.Moreno-Noguer, V.Lepetit and P.Fua "EPnP: Efficient Perspective-n-Point Camera Pose Estimation" - CV_P3P = 2, // X.S. Gao, X.-R. Hou, J. Tang, H.-F. Chang; "Complete Solution Classification for the Perspective-Three-Point Problem" - CV_DLS = 3 // Joel A. Hesch and Stergios I. Roumeliotis. "A Direct Least-Squares (DLS) Method for PnP" -}; - -#define CV_CALIB_CB_ADAPTIVE_THRESH 1 -#define CV_CALIB_CB_NORMALIZE_IMAGE 2 -#define CV_CALIB_CB_FILTER_QUADS 4 -#define CV_CALIB_CB_FAST_CHECK 8 - -#define CV_CALIB_USE_INTRINSIC_GUESS 1 -#define CV_CALIB_FIX_ASPECT_RATIO 2 -#define CV_CALIB_FIX_PRINCIPAL_POINT 4 -#define CV_CALIB_ZERO_TANGENT_DIST 8 -#define CV_CALIB_FIX_FOCAL_LENGTH 16 -#define CV_CALIB_FIX_K1 32 -#define CV_CALIB_FIX_K2 64 -#define CV_CALIB_FIX_K3 128 -#define CV_CALIB_FIX_K4 2048 -#define CV_CALIB_FIX_K5 4096 -#define CV_CALIB_FIX_K6 8192 -#define CV_CALIB_RATIONAL_MODEL 16384 -#define CV_CALIB_THIN_PRISM_MODEL 32768 -#define CV_CALIB_FIX_S1_S2_S3_S4 65536 -#define CV_CALIB_TILTED_MODEL 262144 -#define CV_CALIB_FIX_TAUX_TAUY 524288 -#define CV_CALIB_FIX_TANGENT_DIST 2097152 - -#define CV_CALIB_NINTRINSIC 18 - -#define CV_CALIB_FIX_INTRINSIC 256 -#define CV_CALIB_SAME_FOCAL_LENGTH 512 - -#define CV_CALIB_ZERO_DISPARITY 1024 - -/* stereo correspondence parameters and functions */ -#define CV_STEREO_BM_NORMALIZED_RESPONSE 0 -#define CV_STEREO_BM_XSOBEL 1 - -#ifdef __cplusplus -} // extern "C" - -////////////////////////////////////////////////////////////////////////////////////////// -class CV_EXPORTS CvLevMarq -{ -public: - CvLevMarq(); - CvLevMarq( int nparams, int nerrs, CvTermCriteria criteria= - cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON), - bool completeSymmFlag=false ); - ~CvLevMarq(); - void init( int nparams, int nerrs, CvTermCriteria criteria= - cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON), - bool completeSymmFlag=false ); - bool update( const CvMat*& param, CvMat*& J, CvMat*& err ); - bool updateAlt( const CvMat*& param, CvMat*& JtJ, CvMat*& JtErr, double*& errNorm ); - - void clear(); - void step(); - enum { DONE=0, STARTED=1, CALC_J=2, CHECK_ERR=3 }; - - cv::Ptr mask; - cv::Ptr prevParam; - cv::Ptr param; - cv::Ptr J; - cv::Ptr err; - cv::Ptr JtJ; - cv::Ptr JtJN; - cv::Ptr JtErr; - cv::Ptr JtJV; - cv::Ptr JtJW; - double prevErrNorm, errNorm; - int lambdaLg10; - CvTermCriteria criteria; - int state; - int iters; - bool completeSymmFlag; - int solveMethod; -}; - -#endif - -#endif /* OPENCV_CALIB3D_C_H */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CALIB3D_C_H +#define OPENCV_CALIB3D_C_H + +#include "opencv2/core/types_c.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Calculates fundamental matrix given a set of corresponding points */ +#define CV_FM_7POINT 1 +#define CV_FM_8POINT 2 + +#define CV_LMEDS 4 +#define CV_RANSAC 8 + +#define CV_FM_LMEDS_ONLY CV_LMEDS +#define CV_FM_RANSAC_ONLY CV_RANSAC +#define CV_FM_LMEDS CV_LMEDS +#define CV_FM_RANSAC CV_RANSAC + +enum +{ + CV_ITERATIVE = 0, + CV_EPNP = 1, // F.Moreno-Noguer, V.Lepetit and P.Fua "EPnP: Efficient Perspective-n-Point Camera Pose Estimation" + CV_P3P = 2, // X.S. Gao, X.-R. Hou, J. Tang, H.-F. Chang; "Complete Solution Classification for the Perspective-Three-Point Problem" + CV_DLS = 3 // Joel A. Hesch and Stergios I. Roumeliotis. "A Direct Least-Squares (DLS) Method for PnP" +}; + +#define CV_CALIB_CB_ADAPTIVE_THRESH 1 +#define CV_CALIB_CB_NORMALIZE_IMAGE 2 +#define CV_CALIB_CB_FILTER_QUADS 4 +#define CV_CALIB_CB_FAST_CHECK 8 + +#define CV_CALIB_USE_INTRINSIC_GUESS 1 +#define CV_CALIB_FIX_ASPECT_RATIO 2 +#define CV_CALIB_FIX_PRINCIPAL_POINT 4 +#define CV_CALIB_ZERO_TANGENT_DIST 8 +#define CV_CALIB_FIX_FOCAL_LENGTH 16 +#define CV_CALIB_FIX_K1 32 +#define CV_CALIB_FIX_K2 64 +#define CV_CALIB_FIX_K3 128 +#define CV_CALIB_FIX_K4 2048 +#define CV_CALIB_FIX_K5 4096 +#define CV_CALIB_FIX_K6 8192 +#define CV_CALIB_RATIONAL_MODEL 16384 +#define CV_CALIB_THIN_PRISM_MODEL 32768 +#define CV_CALIB_FIX_S1_S2_S3_S4 65536 +#define CV_CALIB_TILTED_MODEL 262144 +#define CV_CALIB_FIX_TAUX_TAUY 524288 +#define CV_CALIB_FIX_TANGENT_DIST 2097152 + +#define CV_CALIB_NINTRINSIC 18 + +#define CV_CALIB_FIX_INTRINSIC 256 +#define CV_CALIB_SAME_FOCAL_LENGTH 512 + +#define CV_CALIB_ZERO_DISPARITY 1024 + +/* stereo correspondence parameters and functions */ +#define CV_STEREO_BM_NORMALIZED_RESPONSE 0 +#define CV_STEREO_BM_XSOBEL 1 + +#ifdef __cplusplus +} // extern "C" + +////////////////////////////////////////////////////////////////////////////////////////// +class CV_EXPORTS CvLevMarq +{ +public: + CvLevMarq(); + CvLevMarq( int nparams, int nerrs, CvTermCriteria criteria= + cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON), + bool completeSymmFlag=false ); + ~CvLevMarq(); + void init( int nparams, int nerrs, CvTermCriteria criteria= + cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON), + bool completeSymmFlag=false ); + bool update( const CvMat*& param, CvMat*& J, CvMat*& err ); + bool updateAlt( const CvMat*& param, CvMat*& JtJ, CvMat*& JtErr, double*& errNorm ); + + void clear(); + void step(); + enum { DONE=0, STARTED=1, CALC_J=2, CHECK_ERR=3 }; + + cv::Ptr mask; + cv::Ptr prevParam; + cv::Ptr param; + cv::Ptr J; + cv::Ptr err; + cv::Ptr JtJ; + cv::Ptr JtJN; + cv::Ptr JtErr; + cv::Ptr JtJV; + cv::Ptr JtJW; + double prevErrNorm, errNorm; + int lambdaLg10; + CvTermCriteria criteria; + int state; + int iters; + bool completeSymmFlag; + int solveMethod; +}; + +#endif + +#endif /* OPENCV_CALIB3D_C_H */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core.hpp b/3rdParty/opencv-4.11.0/opencv2/core.hpp index d134273753..cafa7bda27 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core.hpp @@ -1,3419 +1,3419 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2015, Intel Corporation, all rights reserved. -// Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved. -// Copyright (C) 2015, OpenCV Foundation, all rights reserved. -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CORE_HPP -#define OPENCV_CORE_HPP - -#ifndef __cplusplus -# error core.hpp header must be compiled as C++ -#endif - -#include "opencv2/core/cvdef.h" -#include "opencv2/core/base.hpp" -#include "opencv2/core/cvstd.hpp" -#include "opencv2/core/traits.hpp" -#include "opencv2/core/matx.hpp" -#include "opencv2/core/types.hpp" -#include "opencv2/core/mat.hpp" -#include "opencv2/core/persistence.hpp" - -/** -@defgroup core Core functionality - -The Core module is the backbone of OpenCV, offering fundamental data structures, matrix operations, -and utility functions that other modules depend on. It’s essential for handling image data, -performing mathematical computations, and managing memory efficiently within the OpenCV ecosystem. - -@{ - @defgroup core_basic Basic structures - @defgroup core_array Operations on arrays - @defgroup core_async Asynchronous API - @defgroup core_xml XML/YAML/JSON Persistence - @defgroup core_cluster Clustering - @defgroup core_utils Utility and system functions and macros - @{ - @defgroup core_logging Logging facilities - @defgroup core_utils_sse SSE utilities - @defgroup core_utils_neon NEON utilities - @defgroup core_utils_vsx VSX utilities - @defgroup core_utils_softfloat Softfloat support - @defgroup core_utils_samples Utility functions for OpenCV samples - @} - @defgroup core_opengl OpenGL interoperability - @defgroup core_optim Optimization Algorithms - @defgroup core_directx DirectX interoperability - @defgroup core_eigen Eigen support - @defgroup core_opencl OpenCL support - @defgroup core_va_intel Intel VA-API/OpenCL (CL-VA) interoperability - @defgroup core_hal Hardware Acceleration Layer - @{ - @defgroup core_hal_functions Functions - @defgroup core_hal_interface Interface - @defgroup core_hal_intrin Universal intrinsics - @{ - @defgroup core_hal_intrin_impl Private implementation helpers - @} - @defgroup core_lowlevel_api Low-level API for external libraries / plugins - @} - @defgroup core_parallel Parallel Processing - @{ - @defgroup core_parallel_backend Parallel backends API - @} - @defgroup core_quaternion Quaternion -@} - */ - -namespace cv { - -//! @addtogroup core_utils -//! @{ - -/*! @brief Class passed to an error. - -This class encapsulates all or almost all necessary -information about the error happened in the program. The exception is -usually constructed and thrown implicitly via CV_Error and CV_Error_ macros. -@see error - */ -class CV_EXPORTS Exception : public std::exception -{ -public: - /*! - Default constructor - */ - Exception(); - /*! - Full constructor. Normally the constructor is not called explicitly. - Instead, the macros CV_Error(), CV_Error_() and CV_Assert() are used. - */ - Exception(int _code, const String& _err, const String& _func, const String& _file, int _line); - virtual ~Exception() CV_NOEXCEPT; - - /*! - \return the error description and the context as a text string. - */ - virtual const char *what() const CV_NOEXCEPT CV_OVERRIDE; - void formatMessage(); - - String msg; ///< the formatted error message - - int code; ///< error code @see CVStatus - String err; ///< error description - String func; ///< function name. Available only when the compiler supports getting it - String file; ///< source file name where the error has occurred - int line; ///< line number in the source file where the error has occurred -}; - -/*! @brief Signals an error and raises the exception. - -By default the function prints information about the error to stderr, -then it either stops if cv::setBreakOnError() had been called before or raises the exception. -It is possible to alternate error processing by using #redirectError(). -@param exc the exception raisen. -@deprecated drop this version - */ -CV_EXPORTS CV_NORETURN void error(const Exception& exc); - -enum SortFlags { SORT_EVERY_ROW = 0, //!< each matrix row is sorted independently - SORT_EVERY_COLUMN = 1, //!< each matrix column is sorted - //!< independently; this flag and the previous one are - //!< mutually exclusive. - SORT_ASCENDING = 0, //!< each matrix row is sorted in the ascending - //!< order. - SORT_DESCENDING = 16 //!< each matrix row is sorted in the - //!< descending order; this flag and the previous one are also - //!< mutually exclusive. - }; - -//! @} core_utils - -//! @addtogroup core_array -//! @{ - -//! Covariation flags -enum CovarFlags { - /** The output covariance matrix is calculated as: - \f[\texttt{scale} \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...]^T \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...],\f] - The covariance matrix will be nsamples x nsamples. Such an unusual covariance matrix is used - for fast PCA of a set of very large vectors (see, for example, the EigenFaces technique for - face recognition). Eigenvalues of this "scrambled" matrix match the eigenvalues of the true - covariance matrix. The "true" eigenvectors can be easily calculated from the eigenvectors of - the "scrambled" covariance matrix. */ - COVAR_SCRAMBLED = 0, - /**The output covariance matrix is calculated as: - \f[\texttt{scale} \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...] \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...]^T,\f] - covar will be a square matrix of the same size as the total number of elements in each input - vector. One and only one of #COVAR_SCRAMBLED and #COVAR_NORMAL must be specified.*/ - COVAR_NORMAL = 1, - /** If the flag is specified, the function does not calculate mean from - the input vectors but, instead, uses the passed mean vector. This is useful if mean has been - pre-calculated or known in advance, or if the covariance matrix is calculated by parts. In - this case, mean is not a mean vector of the input sub-set of vectors but rather the mean - vector of the whole set.*/ - COVAR_USE_AVG = 2, - /** If the flag is specified, the covariance matrix is scaled. In the - "normal" mode, scale is 1./nsamples . In the "scrambled" mode, scale is the reciprocal of the - total number of elements in each input vector. By default (if the flag is not specified), the - covariance matrix is not scaled ( scale=1 ).*/ - COVAR_SCALE = 4, - /** If the flag is - specified, all the input vectors are stored as rows of the samples matrix. mean should be a - single-row vector in this case.*/ - COVAR_ROWS = 8, - /** If the flag is - specified, all the input vectors are stored as columns of the samples matrix. mean should be a - single-column vector in this case.*/ - COVAR_COLS = 16 -}; - -enum ReduceTypes { REDUCE_SUM = 0, //!< the output is the sum of all rows/columns of the matrix. - REDUCE_AVG = 1, //!< the output is the mean vector of all rows/columns of the matrix. - REDUCE_MAX = 2, //!< the output is the maximum (column/row-wise) of all rows/columns of the matrix. - REDUCE_MIN = 3, //!< the output is the minimum (column/row-wise) of all rows/columns of the matrix. - REDUCE_SUM2 = 4 //!< the output is the sum of all squared rows/columns of the matrix. - }; - -/** @brief Swaps two matrices -*/ -CV_EXPORTS void swap(Mat& a, Mat& b); -/** @overload */ -CV_EXPORTS void swap( UMat& a, UMat& b ); - -/** @brief Computes the source location of an extrapolated pixel. - -The function computes and returns the coordinate of a donor pixel corresponding to the specified -extrapolated pixel when using the specified extrapolation border mode. For example, if you use -cv::BORDER_WRAP mode in the horizontal direction, cv::BORDER_REFLECT_101 in the vertical direction and -want to compute value of the "virtual" pixel Point(-5, 100) in a floating-point image img, it -looks like: -@code{.cpp} - float val = img.at(borderInterpolate(100, img.rows, cv::BORDER_REFLECT_101), - borderInterpolate(-5, img.cols, cv::BORDER_WRAP)); -@endcode -Normally, the function is not called directly. It is used inside filtering functions and also in -copyMakeBorder. -@param p 0-based coordinate of the extrapolated pixel along one of the axes, likely \<0 or \>= len -@param len Length of the array along the corresponding axis. -@param borderType Border type, one of the #BorderTypes, except for #BORDER_TRANSPARENT and -#BORDER_ISOLATED. When borderType==#BORDER_CONSTANT, the function always returns -1, regardless -of p and len. - -@sa copyMakeBorder -*/ -CV_EXPORTS_W int borderInterpolate(int p, int len, int borderType); - -/** @example samples/cpp/tutorial_code/ImgTrans/copyMakeBorder_demo.cpp -An example using copyMakeBorder function. -Check @ref tutorial_copyMakeBorder "the corresponding tutorial" for more details -*/ - -/** @brief Forms a border around an image. - -The function copies the source image into the middle of the destination image. The areas to the -left, to the right, above and below the copied source image will be filled with extrapolated -pixels. This is not what filtering functions based on it do (they extrapolate pixels on-fly), but -what other more complex functions, including your own, may do to simplify image boundary handling. - -The function supports the mode when src is already in the middle of dst . In this case, the -function does not copy src itself but simply constructs the border, for example: - -@code{.cpp} - // let border be the same in all directions - int border=2; - // constructs a larger image to fit both the image and the border - Mat gray_buf(rgb.rows + border*2, rgb.cols + border*2, rgb.depth()); - // select the middle part of it w/o copying data - Mat gray(gray_canvas, Rect(border, border, rgb.cols, rgb.rows)); - // convert image from RGB to grayscale - cvtColor(rgb, gray, COLOR_RGB2GRAY); - // form a border in-place - copyMakeBorder(gray, gray_buf, border, border, - border, border, BORDER_REPLICATE); - // now do some custom filtering ... - ... -@endcode -@note When the source image is a part (ROI) of a bigger image, the function will try to use the -pixels outside of the ROI to form a border. To disable this feature and always do extrapolation, as -if src was not a ROI, use borderType | #BORDER_ISOLATED. - -@param src Source image. -@param dst Destination image of the same type as src and the size Size(src.cols+left+right, -src.rows+top+bottom) . -@param top the top pixels -@param bottom the bottom pixels -@param left the left pixels -@param right Parameter specifying how many pixels in each direction from the source image rectangle -to extrapolate. For example, top=1, bottom=1, left=1, right=1 mean that 1 pixel-wide border needs -to be built. -@param borderType Border type. See borderInterpolate for details. -@param value Border value if borderType==BORDER_CONSTANT . - -@sa borderInterpolate -*/ -CV_EXPORTS_W void copyMakeBorder(InputArray src, OutputArray dst, - int top, int bottom, int left, int right, - int borderType, const Scalar& value = Scalar() ); - -/** @brief Calculates the per-element sum of two arrays or an array and a scalar. - -The function add calculates: -- Sum of two arrays when both input arrays have the same size and the same number of channels: -\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) + \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0\f] -- Sum of an array and a scalar when src2 is constructed from Scalar or has the same number of -elements as `src1.channels()`: -\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) + \texttt{src2} ) \quad \texttt{if mask}(I) \ne0\f] -- Sum of a scalar and an array when src1 is constructed from Scalar or has the same number of -elements as `src2.channels()`: -\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1} + \texttt{src2}(I) ) \quad \texttt{if mask}(I) \ne0\f] -where `I` is a multi-dimensional index of array elements. In case of multi-channel arrays, each -channel is processed independently. - -The first function in the list above can be replaced with matrix expressions: -@code{.cpp} - dst = src1 + src2; - dst += src1; // equivalent to add(dst, src1, dst); -@endcode -The input arrays and the output array can all have the same or different depths. For example, you -can add a 16-bit unsigned array to a 8-bit signed array and store the sum as a 32-bit -floating-point array. Depth of the output array is determined by the dtype parameter. In the second -and third cases above, as well as in the first case, when src1.depth() == src2.depth(), dtype can -be set to the default -1. In this case, the output array will have the same depth as the input -array, be it src1, src2 or both. -@note Saturation is not applied when the output array has the depth CV_32S. You may even get -result of an incorrect sign in the case of overflow. -@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. -`add(src,X)` means `add(src,(X,X,X,X))`. -`add(src,(X,))` means `add(src,(X,0,0,0))`. -@param src1 first input array or a scalar. -@param src2 second input array or a scalar. -@param dst output array that has the same size and number of channels as the input array(s); the -depth is defined by dtype or src1/src2. -@param mask optional operation mask - 8-bit single channel array, that specifies elements of the -output array to be changed. -@param dtype optional depth of the output array (see the discussion below). -@sa subtract, addWeighted, scaleAdd, Mat::convertTo -*/ -CV_EXPORTS_W void add(InputArray src1, InputArray src2, OutputArray dst, - InputArray mask = noArray(), int dtype = -1); - -/** @brief Calculates the per-element difference between two arrays or array and a scalar. - -The function subtract calculates: -- Difference between two arrays, when both input arrays have the same size and the same number of -channels: - \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) - \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0\f] -- Difference between an array and a scalar, when src2 is constructed from Scalar or has the same -number of elements as `src1.channels()`: - \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) - \texttt{src2} ) \quad \texttt{if mask}(I) \ne0\f] -- Difference between a scalar and an array, when src1 is constructed from Scalar or has the same -number of elements as `src2.channels()`: - \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1} - \texttt{src2}(I) ) \quad \texttt{if mask}(I) \ne0\f] -- The reverse difference between a scalar and an array in the case of `SubRS`: - \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src2} - \texttt{src1}(I) ) \quad \texttt{if mask}(I) \ne0\f] -where I is a multi-dimensional index of array elements. In case of multi-channel arrays, each -channel is processed independently. - -The first function in the list above can be replaced with matrix expressions: -@code{.cpp} - dst = src1 - src2; - dst -= src1; // equivalent to subtract(dst, src1, dst); -@endcode -The input arrays and the output array can all have the same or different depths. For example, you -can subtract to 8-bit unsigned arrays and store the difference in a 16-bit signed array. Depth of -the output array is determined by dtype parameter. In the second and third cases above, as well as -in the first case, when src1.depth() == src2.depth(), dtype can be set to the default -1. In this -case the output array will have the same depth as the input array, be it src1, src2 or both. -@note Saturation is not applied when the output array has the depth CV_32S. You may even get -result of an incorrect sign in the case of overflow. -@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. -`subtract(src,X)` means `subtract(src,(X,X,X,X))`. -`subtract(src,(X,))` means `subtract(src,(X,0,0,0))`. -@param src1 first input array or a scalar. -@param src2 second input array or a scalar. -@param dst output array of the same size and the same number of channels as the input array. -@param mask optional operation mask; this is an 8-bit single channel array that specifies elements -of the output array to be changed. -@param dtype optional depth of the output array -@sa add, addWeighted, scaleAdd, Mat::convertTo - */ -CV_EXPORTS_W void subtract(InputArray src1, InputArray src2, OutputArray dst, - InputArray mask = noArray(), int dtype = -1); - - -/** @brief Calculates the per-element scaled product of two arrays. - -The function multiply calculates the per-element product of two arrays: - -\f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{scale} \cdot \texttt{src1} (I) \cdot \texttt{src2} (I))\f] - -There is also a @ref MatrixExpressions -friendly variant of the first function. See Mat::mul . - -For a not-per-element matrix product, see gemm . - -@note Saturation is not applied when the output array has the depth -CV_32S. You may even get result of an incorrect sign in the case of -overflow. -@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. -`multiply(src,X)` means `multiply(src,(X,X,X,X))`. -`multiply(src,(X,))` means `multiply(src,(X,0,0,0))`. -@param src1 first input array. -@param src2 second input array of the same size and the same type as src1. -@param dst output array of the same size and type as src1. -@param scale optional scale factor. -@param dtype optional depth of the output array -@sa add, subtract, divide, scaleAdd, addWeighted, accumulate, accumulateProduct, accumulateSquare, -Mat::convertTo -*/ -CV_EXPORTS_W void multiply(InputArray src1, InputArray src2, - OutputArray dst, double scale = 1, int dtype = -1); - -/** @brief Performs per-element division of two arrays or a scalar by an array. - -The function cv::divide divides one array by another: -\f[\texttt{dst(I) = saturate(src1(I)*scale/src2(I))}\f] -or a scalar by an array when there is no src1 : -\f[\texttt{dst(I) = saturate(scale/src2(I))}\f] - -Different channels of multi-channel arrays are processed independently. - -For integer types when src2(I) is zero, dst(I) will also be zero. - -@note In case of floating point data there is no special defined behavior for zero src2(I) values. -Regular floating-point division is used. -Expect correct IEEE-754 behaviour for floating-point data (with NaN, Inf result values). - -@note Saturation is not applied when the output array has the depth CV_32S. You may even get -result of an incorrect sign in the case of overflow. -@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. -`divide(src,X)` means `divide(src,(X,X,X,X))`. -`divide(src,(X,))` means `divide(src,(X,0,0,0))`. -@param src1 first input array. -@param src2 second input array of the same size and type as src1. -@param scale scalar factor. -@param dst output array of the same size and type as src2. -@param dtype optional depth of the output array; if -1, dst will have depth src2.depth(), but in -case of an array-by-array division, you can only pass -1 when src1.depth()==src2.depth(). -@sa multiply, add, subtract -*/ -CV_EXPORTS_W void divide(InputArray src1, InputArray src2, OutputArray dst, - double scale = 1, int dtype = -1); - -/** @overload */ -CV_EXPORTS_W void divide(double scale, InputArray src2, - OutputArray dst, int dtype = -1); - -/** @brief Calculates the sum of a scaled array and another array. - -The function scaleAdd is one of the classical primitive linear algebra operations, known as DAXPY -or SAXPY in [BLAS](http://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms). It calculates -the sum of a scaled array and another array: -\f[\texttt{dst} (I)= \texttt{scale} \cdot \texttt{src1} (I) + \texttt{src2} (I)\f] -The function can also be emulated with a matrix expression, for example: -@code{.cpp} - Mat A(3, 3, CV_64F); - ... - A.row(0) = A.row(1)*2 + A.row(2); -@endcode -@param src1 first input array. -@param alpha scale factor for the first array. -@param src2 second input array of the same size and type as src1. -@param dst output array of the same size and type as src1. -@sa add, addWeighted, subtract, Mat::dot, Mat::convertTo -*/ -CV_EXPORTS_W void scaleAdd(InputArray src1, double alpha, InputArray src2, OutputArray dst); - -/** @brief Calculates the weighted sum of two arrays. - -The function addWeighted calculates the weighted sum of two arrays as follows: -\f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{src1} (I)* \texttt{alpha} + \texttt{src2} (I)* \texttt{beta} + \texttt{gamma} )\f] -where I is a multi-dimensional index of array elements. In case of multi-channel arrays, each -channel is processed independently. -The function can be replaced with a matrix expression: -@code{.cpp} - dst = src1*alpha + src2*beta + gamma; -@endcode -@note Saturation is not applied when the output array has the depth CV_32S. You may even get -result of an incorrect sign in the case of overflow. -@param src1 first input array. -@param alpha weight of the first array elements. -@param src2 second input array of the same size and channel number as src1. -@param beta weight of the second array elements. -@param gamma scalar added to each sum. -@param dst output array that has the same size and number of channels as the input arrays. -@param dtype optional depth of the output array; when both input arrays have the same depth, dtype -can be set to -1, which will be equivalent to src1.depth(). -@sa add, subtract, scaleAdd, Mat::convertTo -*/ -CV_EXPORTS_W void addWeighted(InputArray src1, double alpha, InputArray src2, - double beta, double gamma, OutputArray dst, int dtype = -1); - -/** @brief Scales, calculates absolute values, and converts the result to 8-bit. - -On each element of the input array, the function convertScaleAbs -performs three operations sequentially: scaling, taking an absolute -value, conversion to an unsigned 8-bit type: -\f[\texttt{dst} (I)= \texttt{saturate\_cast} (| \texttt{src} (I)* \texttt{alpha} + \texttt{beta} |)\f] -In case of multi-channel arrays, the function processes each channel -independently. When the output is not 8-bit, the operation can be -emulated by calling the Mat::convertTo method (or by using matrix -expressions) and then by calculating an absolute value of the result. -For example: -@code{.cpp} - Mat_ A(30,30); - randu(A, Scalar(-100), Scalar(100)); - Mat_ B = A*5 + 3; - B = abs(B); - // Mat_ B = abs(A*5+3) will also do the job, - // but it will allocate a temporary matrix -@endcode -@param src input array. -@param dst output array. -@param alpha optional scale factor. -@param beta optional delta added to the scaled values. -@sa Mat::convertTo, cv::abs(const Mat&) -*/ -CV_EXPORTS_W void convertScaleAbs(InputArray src, OutputArray dst, - double alpha = 1, double beta = 0); - -/** @brief Converts an array to half precision floating number. - -This function converts FP32 (single precision floating point) from/to FP16 (half precision floating point). CV_16S format is used to represent FP16 data. -There are two use modes (src -> dst): CV_32F -> CV_16S and CV_16S -> CV_32F. The input array has to have type of CV_32F or -CV_16S to represent the bit depth. If the input array is neither of them, the function will raise an error. -The format of half precision floating point is defined in IEEE 754-2008. - -@param src input array. -@param dst output array. - -@deprecated Use Mat::convertTo with CV_16F instead. -*/ -CV_EXPORTS_W void convertFp16(InputArray src, OutputArray dst); - -/** @example samples/cpp/tutorial_code/core/how_to_scan_images/how_to_scan_images.cpp -Check @ref tutorial_how_to_scan_images "the corresponding tutorial" for more details -*/ - -/** @brief Performs a look-up table transform of an array. - -The function LUT fills the output array with values from the look-up table. Indices of the entries -are taken from the input array. That is, the function processes each element of src as follows: -\f[\texttt{dst} (I) \leftarrow \texttt{lut(src(I) + d)}\f] -where -\f[d = \fork{0}{if \(\texttt{src}\) has depth \(\texttt{CV_8U}\)}{128}{if \(\texttt{src}\) has depth \(\texttt{CV_8S}\)}\f] -@param src input array of 8-bit elements. -@param lut look-up table of 256 elements; in case of multi-channel input array, the table should -either have a single channel (in this case the same table is used for all channels) or the same -number of channels as in the input array. -@param dst output array of the same size and number of channels as src, and the same depth as lut. -@sa convertScaleAbs, Mat::convertTo -*/ -CV_EXPORTS_W void LUT(InputArray src, InputArray lut, OutputArray dst); - -/** @brief Calculates the sum of array elements. - -The function cv::sum calculates and returns the sum of array elements, -independently for each channel. -@param src input array that must have from 1 to 4 channels. -@sa countNonZero, mean, meanStdDev, norm, minMaxLoc, reduce -*/ -CV_EXPORTS_AS(sumElems) Scalar sum(InputArray src); - -/** @brief Checks for the presence of at least one non-zero array element. - -The function returns whether there are non-zero elements in src - -The function do not work with multi-channel arrays. If you need to check non-zero array -elements across all the channels, use Mat::reshape first to reinterpret the array as -single-channel. Or you may extract the particular channel using either extractImageCOI, or -mixChannels, or split. - -@note -- If the location of non-zero array elements is important, @ref findNonZero is helpful. -- If the count of non-zero array elements is important, @ref countNonZero is helpful. -@param src single-channel array. -@sa mean, meanStdDev, norm, minMaxLoc, calcCovarMatrix -@sa findNonZero, countNonZero -*/ -CV_EXPORTS_W bool hasNonZero( InputArray src ); - -/** @brief Counts non-zero array elements. - -The function returns the number of non-zero elements in src : -\f[\sum _{I: \; \texttt{src} (I) \ne0 } 1\f] - -The function do not work with multi-channel arrays. If you need to count non-zero array -elements across all the channels, use Mat::reshape first to reinterpret the array as -single-channel. Or you may extract the particular channel using either extractImageCOI, or -mixChannels, or split. - -@note -- If only whether there are non-zero elements is important, @ref hasNonZero is helpful. -- If the location of non-zero array elements is important, @ref findNonZero is helpful. -@param src single-channel array. -@sa mean, meanStdDev, norm, minMaxLoc, calcCovarMatrix -@sa findNonZero, hasNonZero -*/ -CV_EXPORTS_W int countNonZero( InputArray src ); - -/** @brief Returns the list of locations of non-zero pixels - -Given a binary matrix (likely returned from an operation such -as threshold(), compare(), >, ==, etc, return all of -the non-zero indices as a cv::Mat or std::vector (x,y) -For example: -@code{.cpp} - cv::Mat binaryImage; // input, binary image - cv::Mat locations; // output, locations of non-zero pixels - cv::findNonZero(binaryImage, locations); - - // access pixel coordinates - Point pnt = locations.at(i); -@endcode -or -@code{.cpp} - cv::Mat binaryImage; // input, binary image - vector locations; // output, locations of non-zero pixels - cv::findNonZero(binaryImage, locations); - - // access pixel coordinates - Point pnt = locations[i]; -@endcode - -The function do not work with multi-channel arrays. If you need to find non-zero -elements across all the channels, use Mat::reshape first to reinterpret the array as -single-channel. Or you may extract the particular channel using either extractImageCOI, or -mixChannels, or split. - -@note -- If only count of non-zero array elements is important, @ref countNonZero is helpful. -- If only whether there are non-zero elements is important, @ref hasNonZero is helpful. -@param src single-channel array -@param idx the output array, type of cv::Mat or std::vector, corresponding to non-zero indices in the input -@sa countNonZero, hasNonZero -*/ -CV_EXPORTS_W void findNonZero( InputArray src, OutputArray idx ); - -/** @brief Calculates an average (mean) of array elements. - -The function cv::mean calculates the mean value M of array elements, -independently for each channel, and return it: -\f[\begin{array}{l} N = \sum _{I: \; \texttt{mask} (I) \ne 0} 1 \\ M_c = \left ( \sum _{I: \; \texttt{mask} (I) \ne 0}{ \texttt{mtx} (I)_c} \right )/N \end{array}\f] -When all the mask elements are 0's, the function returns Scalar::all(0) -@param src input array that should have from 1 to 4 channels so that the result can be stored in -Scalar_ . -@param mask optional operation mask. -@sa countNonZero, meanStdDev, norm, minMaxLoc -*/ -CV_EXPORTS_W Scalar mean(InputArray src, InputArray mask = noArray()); - -/** Calculates a mean and standard deviation of array elements. - -The function cv::meanStdDev calculates the mean and the standard deviation M -of array elements independently for each channel and returns it via the -output parameters: -\f[\begin{array}{l} N = \sum _{I, \texttt{mask} (I) \ne 0} 1 \\ \texttt{mean} _c = \frac{\sum_{ I: \; \texttt{mask}(I) \ne 0} \texttt{src} (I)_c}{N} \\ \texttt{stddev} _c = \sqrt{\frac{\sum_{ I: \; \texttt{mask}(I) \ne 0} \left ( \texttt{src} (I)_c - \texttt{mean} _c \right )^2}{N}} \end{array}\f] -When all the mask elements are 0's, the function returns -mean=stddev=Scalar::all(0). -@note The calculated standard deviation is only the diagonal of the -complete normalized covariance matrix. If the full matrix is needed, you -can reshape the multi-channel array M x N to the single-channel array -M\*N x mtx.channels() (only possible when the matrix is continuous) and -then pass the matrix to calcCovarMatrix . -@param src input array that should have from 1 to 4 channels so that the results can be stored in -Scalar_ 's. -@param mean output parameter: calculated mean value. -@param stddev output parameter: calculated standard deviation. -@param mask optional operation mask. -@sa countNonZero, mean, norm, minMaxLoc, calcCovarMatrix -*/ -CV_EXPORTS_W void meanStdDev(InputArray src, OutputArray mean, OutputArray stddev, - InputArray mask=noArray()); - -/** @brief Calculates the absolute norm of an array. - -This version of #norm calculates the absolute norm of src1. The type of norm to calculate is specified using #NormTypes. - -As example for one array consider the function \f$r(x)= \begin{pmatrix} x \\ 1-x \end{pmatrix}, x \in [-1;1]\f$. -The \f$ L_{1}, L_{2} \f$ and \f$ L_{\infty} \f$ norm for the sample value \f$r(-1) = \begin{pmatrix} -1 \\ 2 \end{pmatrix}\f$ -is calculated as follows -\f{align*} - \| r(-1) \|_{L_1} &= |-1| + |2| = 3 \\ - \| r(-1) \|_{L_2} &= \sqrt{(-1)^{2} + (2)^{2}} = \sqrt{5} \\ - \| r(-1) \|_{L_\infty} &= \max(|-1|,|2|) = 2 -\f} -and for \f$r(0.5) = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}\f$ the calculation is -\f{align*} - \| r(0.5) \|_{L_1} &= |0.5| + |0.5| = 1 \\ - \| r(0.5) \|_{L_2} &= \sqrt{(0.5)^{2} + (0.5)^{2}} = \sqrt{0.5} \\ - \| r(0.5) \|_{L_\infty} &= \max(|0.5|,|0.5|) = 0.5. -\f} -The following graphic shows all values for the three norm functions \f$\| r(x) \|_{L_1}, \| r(x) \|_{L_2}\f$ and \f$\| r(x) \|_{L_\infty}\f$. -It is notable that the \f$ L_{1} \f$ norm forms the upper and the \f$ L_{\infty} \f$ norm forms the lower border for the example function \f$ r(x) \f$. -![Graphs for the different norm functions from the above example](pics/NormTypes_OneArray_1-2-INF.png) - -When the mask parameter is specified and it is not empty, the norm is - -If normType is not specified, #NORM_L2 is used. -calculated only over the region specified by the mask. - -Multi-channel input arrays are treated as single-channel arrays, that is, -the results for all channels are combined. - -Hamming norms can only be calculated with CV_8U depth arrays. - -@param src1 first input array. -@param normType type of the norm (see #NormTypes). -@param mask optional operation mask; it must have the same size as src1 and CV_8UC1 type. -*/ -CV_EXPORTS_W double norm(InputArray src1, int normType = NORM_L2, InputArray mask = noArray()); - -/** @brief Calculates an absolute difference norm or a relative difference norm. - -This version of cv::norm calculates the absolute difference norm -or the relative difference norm of arrays src1 and src2. -The type of norm to calculate is specified using #NormTypes. - -@param src1 first input array. -@param src2 second input array of the same size and the same type as src1. -@param normType type of the norm (see #NormTypes). -@param mask optional operation mask; it must have the same size as src1 and CV_8UC1 type. -*/ -CV_EXPORTS_W double norm(InputArray src1, InputArray src2, - int normType = NORM_L2, InputArray mask = noArray()); -/** @overload -@param src first input array. -@param normType type of the norm (see #NormTypes). -*/ -CV_EXPORTS double norm( const SparseMat& src, int normType ); - -/** @brief Computes the Peak Signal-to-Noise Ratio (PSNR) image quality metric. - -This function calculates the Peak Signal-to-Noise Ratio (PSNR) image quality metric in decibels (dB), -between two input arrays src1 and src2. The arrays must have the same type. - -The PSNR is calculated as follows: - -\f[ -\texttt{PSNR} = 10 \cdot \log_{10}{\left( \frac{R^2}{MSE} \right) } -\f] - -where R is the maximum integer value of depth (e.g. 255 in the case of CV_8U data) -and MSE is the mean squared error between the two arrays. - -@param src1 first input array. -@param src2 second input array of the same size as src1. -@param R the maximum pixel value (255 by default) - - */ -CV_EXPORTS_W double PSNR(InputArray src1, InputArray src2, double R=255.); - -/** @brief naive nearest neighbor finder - -see http://en.wikipedia.org/wiki/Nearest_neighbor_search -@todo document - */ -CV_EXPORTS_W void batchDistance(InputArray src1, InputArray src2, - OutputArray dist, int dtype, OutputArray nidx, - int normType = NORM_L2, int K = 0, - InputArray mask = noArray(), int update = 0, - bool crosscheck = false); - -/** @brief Normalizes the norm or value range of an array. - -The function cv::normalize normalizes scale and shift the input array elements so that -\f[\| \texttt{dst} \| _{L_p}= \texttt{alpha}\f] -(where p=Inf, 1 or 2) when normType=NORM_INF, NORM_L1, or NORM_L2, respectively; or so that -\f[\min _I \texttt{dst} (I)= \texttt{alpha} , \, \, \max _I \texttt{dst} (I)= \texttt{beta}\f] - -when normType=NORM_MINMAX (for dense arrays only). The optional mask specifies a sub-array to be -normalized. This means that the norm or min-n-max are calculated over the sub-array, and then this -sub-array is modified to be normalized. If you want to only use the mask to calculate the norm or -min-max but modify the whole array, you can use norm and Mat::convertTo. - -In case of sparse matrices, only the non-zero values are analyzed and transformed. Because of this, -the range transformation for sparse matrices is not allowed since it can shift the zero level. - -Possible usage with some positive example data: -@code{.cpp} - vector positiveData = { 2.0, 8.0, 10.0 }; - vector normalizedData_l1, normalizedData_l2, normalizedData_inf, normalizedData_minmax; - - // Norm to probability (total count) - // sum(numbers) = 20.0 - // 2.0 0.1 (2.0/20.0) - // 8.0 0.4 (8.0/20.0) - // 10.0 0.5 (10.0/20.0) - normalize(positiveData, normalizedData_l1, 1.0, 0.0, NORM_L1); - - // Norm to unit vector: ||positiveData|| = 1.0 - // 2.0 0.15 - // 8.0 0.62 - // 10.0 0.77 - normalize(positiveData, normalizedData_l2, 1.0, 0.0, NORM_L2); - - // Norm to max element - // 2.0 0.2 (2.0/10.0) - // 8.0 0.8 (8.0/10.0) - // 10.0 1.0 (10.0/10.0) - normalize(positiveData, normalizedData_inf, 1.0, 0.0, NORM_INF); - - // Norm to range [0.0;1.0] - // 2.0 0.0 (shift to left border) - // 8.0 0.75 (6.0/8.0) - // 10.0 1.0 (shift to right border) - normalize(positiveData, normalizedData_minmax, 1.0, 0.0, NORM_MINMAX); -@endcode - -@param src input array. -@param dst output array of the same size as src . -@param alpha norm value to normalize to or the lower range boundary in case of the range -normalization. -@param beta upper range boundary in case of the range normalization; it is not used for the norm -normalization. -@param norm_type normalization type (see cv::NormTypes). -@param dtype when negative, the output array has the same type as src; otherwise, it has the same -number of channels as src and the depth =CV_MAT_DEPTH(dtype). -@param mask optional operation mask. -@sa norm, Mat::convertTo, SparseMat::convertTo -*/ -CV_EXPORTS_W void normalize( InputArray src, InputOutputArray dst, double alpha = 1, double beta = 0, - int norm_type = NORM_L2, int dtype = -1, InputArray mask = noArray()); - -/** @overload -@param src input array. -@param dst output array of the same size as src . -@param alpha norm value to normalize to or the lower range boundary in case of the range -normalization. -@param normType normalization type (see cv::NormTypes). -*/ -CV_EXPORTS void normalize( const SparseMat& src, SparseMat& dst, double alpha, int normType ); - -/** @brief Finds the global minimum and maximum in an array. - -The function cv::minMaxLoc finds the minimum and maximum element values and their positions. The -extrema are searched across the whole array or, if mask is not an empty array, in the specified -array region. - -In C++, if the input is multi-channel, you should omit the minLoc, maxLoc, and mask arguments -(i.e. leave them as NULL, NULL, and noArray() respectively). These arguments are not -supported for multi-channel input arrays. If working with multi-channel input and you -need the minLoc, maxLoc, or mask arguments, then use Mat::reshape first to reinterpret -the array as single-channel. Alternatively, you can extract the particular channel using either -extractImageCOI, mixChannels, or split. - -In Python, multi-channel input is not supported at all due to a limitation in the -binding generation process (there is no way to set minLoc and maxLoc to NULL). A -workaround is to operate on each channel individually or to use NumPy to achieve the same -functionality. - -@param src input single-channel array. -@param minVal pointer to the returned minimum value; NULL is used if not required. -@param maxVal pointer to the returned maximum value; NULL is used if not required. -@param minLoc pointer to the returned minimum location (in 2D case); NULL is used if not required. -@param maxLoc pointer to the returned maximum location (in 2D case); NULL is used if not required. -@param mask optional mask used to select a sub-array. -@sa max, min, reduceArgMin, reduceArgMax, compare, inRange, extractImageCOI, mixChannels, split, Mat::reshape -*/ -CV_EXPORTS_W void minMaxLoc(InputArray src, CV_OUT double* minVal, - CV_OUT double* maxVal = 0, CV_OUT Point* minLoc = 0, - CV_OUT Point* maxLoc = 0, InputArray mask = noArray()); - -/** - * @brief Finds indices of min elements along provided axis - * - * @note - * - If input or output array is not continuous, this function will create an internal copy. - * - NaN handling is left unspecified, see patchNaNs(). - * - The returned index is always in bounds of input matrix. - * - * @param src input single-channel array. - * @param dst output array of type CV_32SC1 with the same dimensionality as src, - * except for axis being reduced - it should be set to 1. - * @param lastIndex whether to get the index of first or last occurrence of min. - * @param axis axis to reduce along. - * @sa reduceArgMax, minMaxLoc, min, max, compare, reduce - */ -CV_EXPORTS_W void reduceArgMin(InputArray src, OutputArray dst, int axis, bool lastIndex = false); - -/** - * @brief Finds indices of max elements along provided axis - * - * @note - * - If input or output array is not continuous, this function will create an internal copy. - * - NaN handling is left unspecified, see patchNaNs(). - * - The returned index is always in bounds of input matrix. - * - * @param src input single-channel array. - * @param dst output array of type CV_32SC1 with the same dimensionality as src, - * except for axis being reduced - it should be set to 1. - * @param lastIndex whether to get the index of first or last occurrence of max. - * @param axis axis to reduce along. - * @sa reduceArgMin, minMaxLoc, min, max, compare, reduce - */ -CV_EXPORTS_W void reduceArgMax(InputArray src, OutputArray dst, int axis, bool lastIndex = false); - -/** @brief Finds the global minimum and maximum in an array - -The function cv::minMaxIdx finds the minimum and maximum element values and their positions. The -extremums are searched across the whole array or, if mask is not an empty array, in the specified -array region. In case of a sparse matrix, the minimum is found among non-zero elements -only. Multi-channel input is supported without mask and extremums indexes (should be nullptr). -@note When minIdx is not NULL, it must have at least 2 elements (as well as maxIdx), even if src is -a single-row or single-column matrix. In OpenCV (following MATLAB) each array has at least 2 -dimensions, i.e. single-column matrix is Mx1 matrix (and therefore minIdx/maxIdx will be -(i1,0)/(i2,0)) and single-row matrix is 1xN matrix (and therefore minIdx/maxIdx will be -(0,j1)/(0,j2)). -@param src input single-channel array. -@param minVal pointer to the returned minimum value; NULL is used if not required. -@param maxVal pointer to the returned maximum value; NULL is used if not required. -@param minIdx pointer to the returned minimum location (in nD case); NULL is used if not required; -Otherwise, it must point to an array of src.dims elements, the coordinates of the minimum element -in each dimension are stored there sequentially. -@param maxIdx pointer to the returned maximum location (in nD case). NULL is used if not required. -@param mask specified array region -*/ -CV_EXPORTS void minMaxIdx(InputArray src, double* minVal, double* maxVal = 0, - int* minIdx = 0, int* maxIdx = 0, InputArray mask = noArray()); - -/** @overload -@param a input single-channel array. -@param minVal pointer to the returned minimum value; NULL is used if not required. -@param maxVal pointer to the returned maximum value; NULL is used if not required. -@param minIdx pointer to the returned minimum location (in nD case); NULL is used if not required; -Otherwise, it must point to an array of src.dims elements, the coordinates of the minimum element -in each dimension are stored there sequentially. -@param maxIdx pointer to the returned maximum location (in nD case). NULL is used if not required. -*/ -CV_EXPORTS void minMaxLoc(const SparseMat& a, double* minVal, - double* maxVal, int* minIdx = 0, int* maxIdx = 0); - -/** @brief Reduces a matrix to a vector. - -The function #reduce reduces the matrix to a vector by treating the matrix rows/columns as a set of -1D vectors and performing the specified operation on the vectors until a single row/column is -obtained. For example, the function can be used to compute horizontal and vertical projections of a -raster image. In case of #REDUCE_MAX and #REDUCE_MIN, the output image should have the same type as the source one. -In case of #REDUCE_SUM, #REDUCE_SUM2 and #REDUCE_AVG, the output may have a larger element bit-depth to preserve accuracy. -And multi-channel arrays are also supported in these two reduction modes. - -The following code demonstrates its usage for a single channel matrix. -@snippet snippets/core_reduce.cpp example - -And the following code demonstrates its usage for a two-channel matrix. -@snippet snippets/core_reduce.cpp example2 - -@param src input 2D matrix. -@param dst output vector. Its size and type is defined by dim and dtype parameters. -@param dim dimension index along which the matrix is reduced. 0 means that the matrix is reduced to -a single row. 1 means that the matrix is reduced to a single column. -@param rtype reduction operation that could be one of #ReduceTypes -@param dtype when negative, the output vector will have the same type as the input matrix, -otherwise, its type will be CV_MAKE_TYPE(CV_MAT_DEPTH(dtype), src.channels()). -@sa repeat, reduceArgMin, reduceArgMax -*/ -CV_EXPORTS_W void reduce(InputArray src, OutputArray dst, int dim, int rtype, int dtype = -1); - -/** @brief Creates one multi-channel array out of several single-channel ones. - -The function cv::merge merges several arrays to make a single multi-channel array. That is, each -element of the output array will be a concatenation of the elements of the input arrays, where -elements of i-th input array are treated as mv[i].channels()-element vectors. - -The function cv::split does the reverse operation. If you need to shuffle channels in some other -advanced way, use cv::mixChannels. - -The following example shows how to merge 3 single channel matrices into a single 3-channel matrix. -@snippet snippets/core_merge.cpp example - -@param mv input array of matrices to be merged; all the matrices in mv must have the same -size and the same depth. -@param count number of input matrices when mv is a plain C array; it must be greater than zero. -@param dst output array of the same size and the same depth as mv[0]; The number of channels will -be equal to the parameter count. -@sa mixChannels, split, Mat::reshape -*/ -CV_EXPORTS void merge(const Mat* mv, size_t count, OutputArray dst); - -/** @overload -@param mv input vector of matrices to be merged; all the matrices in mv must have the same -size and the same depth. -@param dst output array of the same size and the same depth as mv[0]; The number of channels will -be the total number of channels in the matrix array. - */ -CV_EXPORTS_W void merge(InputArrayOfArrays mv, OutputArray dst); - -/** @brief Divides a multi-channel array into several single-channel arrays. - -The function cv::split splits a multi-channel array into separate single-channel arrays: -\f[\texttt{mv} [c](I) = \texttt{src} (I)_c\f] -If you need to extract a single channel or do some other sophisticated channel permutation, use -mixChannels. - -The following example demonstrates how to split a 3-channel matrix into 3 single channel matrices. -@snippet snippets/core_split.cpp example - -@param src input multi-channel array. -@param mvbegin output array; the number of arrays must match src.channels(); the arrays themselves are -reallocated, if needed. -@sa merge, mixChannels, cvtColor -*/ -CV_EXPORTS void split(const Mat& src, Mat* mvbegin); - -/** @overload -@param m input multi-channel array. -@param mv output vector of arrays; the arrays themselves are reallocated, if needed. -*/ -CV_EXPORTS_W void split(InputArray m, OutputArrayOfArrays mv); - -/** @brief Copies specified channels from input arrays to the specified channels of -output arrays. - -The function cv::mixChannels provides an advanced mechanism for shuffling image channels. - -cv::split,cv::merge,cv::extractChannel,cv::insertChannel and some forms of cv::cvtColor are partial cases of cv::mixChannels. - -In the example below, the code splits a 4-channel BGRA image into a 3-channel BGR (with B and R -channels swapped) and a separate alpha-channel image: -@code{.cpp} - Mat bgra( 100, 100, CV_8UC4, Scalar(255,0,0,255) ); - Mat bgr( bgra.rows, bgra.cols, CV_8UC3 ); - Mat alpha( bgra.rows, bgra.cols, CV_8UC1 ); - - // forming an array of matrices is a quite efficient operation, - // because the matrix data is not copied, only the headers - Mat out[] = { bgr, alpha }; - // bgra[0] -> bgr[2], bgra[1] -> bgr[1], - // bgra[2] -> bgr[0], bgra[3] -> alpha[0] - int from_to[] = { 0,2, 1,1, 2,0, 3,3 }; - mixChannels( &bgra, 1, out, 2, from_to, 4 ); -@endcode -@note Unlike many other new-style C++ functions in OpenCV (see the introduction section and -Mat::create ), cv::mixChannels requires the output arrays to be pre-allocated before calling the -function. -@param src input array or vector of matrices; all of the matrices must have the same size and the -same depth. -@param nsrcs number of matrices in `src`. -@param dst output array or vector of matrices; all the matrices **must be allocated**; their size and -depth must be the same as in `src[0]`. -@param ndsts number of matrices in `dst`. -@param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is -a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in -dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to -src[0].channels()-1, the second input image channels are indexed from src[0].channels() to -src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image -channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is -filled with zero . -@param npairs number of index pairs in `fromTo`. -@sa split, merge, extractChannel, insertChannel, cvtColor -*/ -CV_EXPORTS void mixChannels(const Mat* src, size_t nsrcs, Mat* dst, size_t ndsts, - const int* fromTo, size_t npairs); - -/** @overload -@param src input array or vector of matrices; all of the matrices must have the same size and the -same depth. -@param dst output array or vector of matrices; all the matrices **must be allocated**; their size and -depth must be the same as in src[0]. -@param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is -a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in -dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to -src[0].channels()-1, the second input image channels are indexed from src[0].channels() to -src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image -channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is -filled with zero . -@param npairs number of index pairs in fromTo. -*/ -CV_EXPORTS void mixChannels(InputArrayOfArrays src, InputOutputArrayOfArrays dst, - const int* fromTo, size_t npairs); - -/** @overload -@param src input array or vector of matrices; all of the matrices must have the same size and the -same depth. -@param dst output array or vector of matrices; all the matrices **must be allocated**; their size and -depth must be the same as in src[0]. -@param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is -a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in -dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to -src[0].channels()-1, the second input image channels are indexed from src[0].channels() to -src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image -channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is -filled with zero . -*/ -CV_EXPORTS_W void mixChannels(InputArrayOfArrays src, InputOutputArrayOfArrays dst, - const std::vector& fromTo); - -/** @brief Extracts a single channel from src (coi is 0-based index) -@param src input array -@param dst output array -@param coi index of channel to extract -@sa mixChannels, split -*/ -CV_EXPORTS_W void extractChannel(InputArray src, OutputArray dst, int coi); - -/** @brief Inserts a single channel to dst (coi is 0-based index) -@param src input array -@param dst output array -@param coi index of channel for insertion -@sa mixChannels, merge -*/ -CV_EXPORTS_W void insertChannel(InputArray src, InputOutputArray dst, int coi); - -/** @brief Flips a 2D array around vertical, horizontal, or both axes. - -The function cv::flip flips the array in one of three different ways (row -and column indices are 0-based): -\f[\texttt{dst} _{ij} = -\left\{ -\begin{array}{l l} -\texttt{src} _{\texttt{src.rows}-i-1,j} & if\; \texttt{flipCode} = 0 \\ -\texttt{src} _{i, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} > 0 \\ -\texttt{src} _{ \texttt{src.rows} -i-1, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} < 0 \\ -\end{array} -\right.\f] -The example scenarios of using the function are the following: -* Vertical flipping of the image (flipCode == 0) to switch between - top-left and bottom-left image origin. This is a typical operation - in video processing on Microsoft Windows\* OS. -* Horizontal flipping of the image with the subsequent horizontal - shift and absolute difference calculation to check for a - vertical-axis symmetry (flipCode \> 0). -* Simultaneous horizontal and vertical flipping of the image with - the subsequent shift and absolute difference calculation to check - for a central symmetry (flipCode \< 0). -* Reversing the order of point arrays (flipCode \> 0 or - flipCode == 0). -@param src input array. -@param dst output array of the same size and type as src. -@param flipCode a flag to specify how to flip the array; 0 means -flipping around the x-axis and positive value (for example, 1) means -flipping around y-axis. Negative value (for example, -1) means flipping -around both axes. -@sa transpose, repeat, completeSymm -*/ -CV_EXPORTS_W void flip(InputArray src, OutputArray dst, int flipCode); - -/** @brief Flips a n-dimensional at given axis - * @param src input array - * @param dst output array that has the same shape of src - * @param axis axis that performs a flip on. 0 <= axis < src.dims. - */ -CV_EXPORTS_W void flipND(InputArray src, OutputArray dst, int axis); - -/** @brief Broadcast the given Mat to the given shape. - * @param src input array - * @param shape target shape. Should be a list of CV_32S numbers. Note that negative values are not supported. - * @param dst output array that has the given shape - */ -CV_EXPORTS_W void broadcast(InputArray src, InputArray shape, OutputArray dst); - -enum RotateFlags { - ROTATE_90_CLOCKWISE = 0, //! A = (cv::Mat_(3, 2) << 1, 4, - 2, 5, - 3, 6); - cv::Mat_ B = (cv::Mat_(3, 2) << 7, 10, - 8, 11, - 9, 12); - - cv::Mat C; - cv::hconcat(A, B, C); - //C: - //[1, 4, 7, 10; - // 2, 5, 8, 11; - // 3, 6, 9, 12] - @endcode - @param src1 first input array to be considered for horizontal concatenation. - @param src2 second input array to be considered for horizontal concatenation. - @param dst output array. It has the same number of rows and depth as the src1 and src2, and the sum of cols of the src1 and src2. - */ -CV_EXPORTS void hconcat(InputArray src1, InputArray src2, OutputArray dst); -/** @overload - @code{.cpp} - std::vector matrices = { cv::Mat(4, 1, CV_8UC1, cv::Scalar(1)), - cv::Mat(4, 1, CV_8UC1, cv::Scalar(2)), - cv::Mat(4, 1, CV_8UC1, cv::Scalar(3)),}; - - cv::Mat out; - cv::hconcat( matrices, out ); - //out: - //[1, 2, 3; - // 1, 2, 3; - // 1, 2, 3; - // 1, 2, 3] - @endcode - @param src input array or vector of matrices. all of the matrices must have the same number of rows and the same depth. - @param dst output array. It has the same number of rows and depth as the src, and the sum of cols of the src. -same depth. - */ -CV_EXPORTS_W void hconcat(InputArrayOfArrays src, OutputArray dst); - -/** @brief Applies vertical concatenation to given matrices. - -The function vertically concatenates two or more cv::Mat matrices (with the same number of cols). -@code{.cpp} - cv::Mat matArray[] = { cv::Mat(1, 4, CV_8UC1, cv::Scalar(1)), - cv::Mat(1, 4, CV_8UC1, cv::Scalar(2)), - cv::Mat(1, 4, CV_8UC1, cv::Scalar(3)),}; - - cv::Mat out; - cv::vconcat( matArray, 3, out ); - //out: - //[1, 1, 1, 1; - // 2, 2, 2, 2; - // 3, 3, 3, 3] -@endcode -@param src input array or vector of matrices. all of the matrices must have the same number of cols and the same depth. -@param nsrc number of matrices in src. -@param dst output array. It has the same number of cols and depth as the src, and the sum of rows of the src. -@sa cv::hconcat(const Mat*, size_t, OutputArray), @sa cv::hconcat(InputArrayOfArrays, OutputArray) and @sa cv::hconcat(InputArray, InputArray, OutputArray) -*/ -CV_EXPORTS void vconcat(const Mat* src, size_t nsrc, OutputArray dst); -/** @overload - @code{.cpp} - cv::Mat_ A = (cv::Mat_(3, 2) << 1, 7, - 2, 8, - 3, 9); - cv::Mat_ B = (cv::Mat_(3, 2) << 4, 10, - 5, 11, - 6, 12); - - cv::Mat C; - cv::vconcat(A, B, C); - //C: - //[1, 7; - // 2, 8; - // 3, 9; - // 4, 10; - // 5, 11; - // 6, 12] - @endcode - @param src1 first input array to be considered for vertical concatenation. - @param src2 second input array to be considered for vertical concatenation. - @param dst output array. It has the same number of cols and depth as the src1 and src2, and the sum of rows of the src1 and src2. - */ -CV_EXPORTS void vconcat(InputArray src1, InputArray src2, OutputArray dst); -/** @overload - @code{.cpp} - std::vector matrices = { cv::Mat(1, 4, CV_8UC1, cv::Scalar(1)), - cv::Mat(1, 4, CV_8UC1, cv::Scalar(2)), - cv::Mat(1, 4, CV_8UC1, cv::Scalar(3)),}; - - cv::Mat out; - cv::vconcat( matrices, out ); - //out: - //[1, 1, 1, 1; - // 2, 2, 2, 2; - // 3, 3, 3, 3] - @endcode - @param src input array or vector of matrices. all of the matrices must have the same number of cols and the same depth - @param dst output array. It has the same number of cols and depth as the src, and the sum of rows of the src. -same depth. - */ -CV_EXPORTS_W void vconcat(InputArrayOfArrays src, OutputArray dst); - -/** @brief computes bitwise conjunction of the two arrays (dst = src1 & src2) -Calculates the per-element bit-wise conjunction of two arrays or an -array and a scalar. - -The function cv::bitwise_and calculates the per-element bit-wise logical conjunction for: -* Two arrays when src1 and src2 have the same size: - \f[\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] -* An array and a scalar when src2 is constructed from Scalar or has - the same number of elements as `src1.channels()`: - \f[\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} \quad \texttt{if mask} (I) \ne0\f] -* A scalar and an array when src1 is constructed from Scalar or has - the same number of elements as `src2.channels()`: - \f[\texttt{dst} (I) = \texttt{src1} \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] -In case of floating-point arrays, their machine-specific bit -representations (usually IEEE754-compliant) are used for the operation. -In case of multi-channel arrays, each channel is processed -independently. In the second and third cases above, the scalar is first -converted to the array type. -@param src1 first input array or a scalar. -@param src2 second input array or a scalar. -@param dst output array that has the same size and type as the input -arrays. -@param mask optional operation mask, 8-bit single channel array, that -specifies elements of the output array to be changed. -*/ -CV_EXPORTS_W void bitwise_and(InputArray src1, InputArray src2, - OutputArray dst, InputArray mask = noArray()); - -/** @brief Calculates the per-element bit-wise disjunction of two arrays or an -array and a scalar. - -The function cv::bitwise_or calculates the per-element bit-wise logical disjunction for: -* Two arrays when src1 and src2 have the same size: - \f[\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] -* An array and a scalar when src2 is constructed from Scalar or has - the same number of elements as `src1.channels()`: - \f[\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} \quad \texttt{if mask} (I) \ne0\f] -* A scalar and an array when src1 is constructed from Scalar or has - the same number of elements as `src2.channels()`: - \f[\texttt{dst} (I) = \texttt{src1} \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] -In case of floating-point arrays, their machine-specific bit -representations (usually IEEE754-compliant) are used for the operation. -In case of multi-channel arrays, each channel is processed -independently. In the second and third cases above, the scalar is first -converted to the array type. -@param src1 first input array or a scalar. -@param src2 second input array or a scalar. -@param dst output array that has the same size and type as the input -arrays. -@param mask optional operation mask, 8-bit single channel array, that -specifies elements of the output array to be changed. -*/ -CV_EXPORTS_W void bitwise_or(InputArray src1, InputArray src2, - OutputArray dst, InputArray mask = noArray()); - -/** @brief Calculates the per-element bit-wise "exclusive or" operation on two -arrays or an array and a scalar. - -The function cv::bitwise_xor calculates the per-element bit-wise logical "exclusive-or" -operation for: -* Two arrays when src1 and src2 have the same size: - \f[\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] -* An array and a scalar when src2 is constructed from Scalar or has - the same number of elements as `src1.channels()`: - \f[\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} \quad \texttt{if mask} (I) \ne0\f] -* A scalar and an array when src1 is constructed from Scalar or has - the same number of elements as `src2.channels()`: - \f[\texttt{dst} (I) = \texttt{src1} \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] -In case of floating-point arrays, their machine-specific bit -representations (usually IEEE754-compliant) are used for the operation. -In case of multi-channel arrays, each channel is processed -independently. In the 2nd and 3rd cases above, the scalar is first -converted to the array type. -@param src1 first input array or a scalar. -@param src2 second input array or a scalar. -@param dst output array that has the same size and type as the input -arrays. -@param mask optional operation mask, 8-bit single channel array, that -specifies elements of the output array to be changed. -*/ -CV_EXPORTS_W void bitwise_xor(InputArray src1, InputArray src2, - OutputArray dst, InputArray mask = noArray()); - -/** @brief Inverts every bit of an array. - -The function cv::bitwise_not calculates per-element bit-wise inversion of the input -array: -\f[\texttt{dst} (I) = \neg \texttt{src} (I)\f] -In case of a floating-point input array, its machine-specific bit -representation (usually IEEE754-compliant) is used for the operation. In -case of multi-channel arrays, each channel is processed independently. -@param src input array. -@param dst output array that has the same size and type as the input -array. -@param mask optional operation mask, 8-bit single channel array, that -specifies elements of the output array to be changed. -*/ -CV_EXPORTS_W void bitwise_not(InputArray src, OutputArray dst, - InputArray mask = noArray()); - -/** @brief Calculates the per-element absolute difference between two arrays or between an array and a scalar. - -The function cv::absdiff calculates: -* Absolute difference between two arrays when they have the same - size and type: - \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2}(I)|)\f] -* Absolute difference between an array and a scalar when the second - array is constructed from Scalar or has as many elements as the - number of channels in `src1`: - \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2} |)\f] -* Absolute difference between a scalar and an array when the first - array is constructed from Scalar or has as many elements as the - number of channels in `src2`: - \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1} - \texttt{src2}(I) |)\f] - where I is a multi-dimensional index of array elements. In case of - multi-channel arrays, each channel is processed independently. -@note Saturation is not applied when the arrays have the depth CV_32S. -You may even get a negative value in the case of overflow. -@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. -`absdiff(src,X)` means `absdiff(src,(X,X,X,X))`. -`absdiff(src,(X,))` means `absdiff(src,(X,0,0,0))`. -@param src1 first input array or a scalar. -@param src2 second input array or a scalar. -@param dst output array that has the same size and type as input arrays. -@sa cv::abs(const Mat&) -*/ -CV_EXPORTS_W void absdiff(InputArray src1, InputArray src2, OutputArray dst); - -/** @brief This is an overloaded member function, provided for convenience (python) -Copies the matrix to another one. -When the operation mask is specified, if the Mat::create call shown above reallocates the matrix, the newly allocated matrix is initialized with all zeros before copying the data. -@param src source matrix. -@param dst Destination matrix. If it does not have a proper size or type before the operation, it is -reallocated. -@param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix -elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels. -*/ - -void CV_EXPORTS_W copyTo(InputArray src, OutputArray dst, InputArray mask); -/** @brief Checks if array elements lie between the elements of two other arrays. - -The function checks the range as follows: -- For every element of a single-channel input array: - \f[\texttt{dst} (I)= \texttt{lowerb} (I)_0 \leq \texttt{src} (I)_0 \leq \texttt{upperb} (I)_0\f] -- For two-channel arrays: - \f[\texttt{dst} (I)= \texttt{lowerb} (I)_0 \leq \texttt{src} (I)_0 \leq \texttt{upperb} (I)_0 \land \texttt{lowerb} (I)_1 \leq \texttt{src} (I)_1 \leq \texttt{upperb} (I)_1\f] -- and so forth. - -That is, dst (I) is set to 255 (all 1 -bits) if src (I) is within the -specified 1D, 2D, 3D, ... box and 0 otherwise. - -When the lower and/or upper boundary parameters are scalars, the indexes -(I) at lowerb and upperb in the above formulas should be omitted. -@param src first input array. -@param lowerb inclusive lower boundary array or a scalar. -@param upperb inclusive upper boundary array or a scalar. -@param dst output array of the same size as src and CV_8U type. -*/ -CV_EXPORTS_W void inRange(InputArray src, InputArray lowerb, - InputArray upperb, OutputArray dst); - -/** @brief Performs the per-element comparison of two arrays or an array and scalar value. - -The function compares: -* Elements of two arrays when src1 and src2 have the same size: - \f[\texttt{dst} (I) = \texttt{src1} (I) \,\texttt{cmpop}\, \texttt{src2} (I)\f] -* Elements of src1 with a scalar src2 when src2 is constructed from - Scalar or has a single element: - \f[\texttt{dst} (I) = \texttt{src1}(I) \,\texttt{cmpop}\, \texttt{src2}\f] -* src1 with elements of src2 when src1 is constructed from Scalar or - has a single element: - \f[\texttt{dst} (I) = \texttt{src1} \,\texttt{cmpop}\, \texttt{src2} (I)\f] -When the comparison result is true, the corresponding element of output -array is set to 255. The comparison operations can be replaced with the -equivalent matrix expressions: -@code{.cpp} - Mat dst1 = src1 >= src2; - Mat dst2 = src1 < 8; - ... -@endcode -@param src1 first input array or a scalar; when it is an array, it must have a single channel. -@param src2 second input array or a scalar; when it is an array, it must have a single channel. -@param dst output array of type ref CV_8U that has the same size and the same number of channels as - the input arrays. -@param cmpop a flag, that specifies correspondence between the arrays (cv::CmpTypes) -@sa checkRange, min, max, threshold -*/ -CV_EXPORTS_W void compare(InputArray src1, InputArray src2, OutputArray dst, int cmpop); - -/** @brief Calculates per-element minimum of two arrays or an array and a scalar. - -The function cv::min calculates the per-element minimum of two arrays: -\f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{src2} (I))\f] -or array and a scalar: -\f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{value} )\f] -@param src1 first input array. -@param src2 second input array of the same size and type as src1. -@param dst output array of the same size and type as src1. -@sa max, compare, inRange, minMaxLoc -*/ -CV_EXPORTS_W void min(InputArray src1, InputArray src2, OutputArray dst); -/** @overload -needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare) -*/ -CV_EXPORTS void min(const Mat& src1, const Mat& src2, Mat& dst); -/** @overload -needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare) -*/ -CV_EXPORTS void min(const UMat& src1, const UMat& src2, UMat& dst); - -/** @brief Calculates per-element maximum of two arrays or an array and a scalar. - -The function cv::max calculates the per-element maximum of two arrays: -\f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{src2} (I))\f] -or array and a scalar: -\f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{value} )\f] -@param src1 first input array. -@param src2 second input array of the same size and type as src1 . -@param dst output array of the same size and type as src1. -@sa min, compare, inRange, minMaxLoc, @ref MatrixExpressions -*/ -CV_EXPORTS_W void max(InputArray src1, InputArray src2, OutputArray dst); -/** @overload -needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare) -*/ -CV_EXPORTS void max(const Mat& src1, const Mat& src2, Mat& dst); -/** @overload -needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare) -*/ -CV_EXPORTS void max(const UMat& src1, const UMat& src2, UMat& dst); - -/** @brief Calculates a square root of array elements. - -The function cv::sqrt calculates a square root of each input array element. -In case of multi-channel arrays, each channel is processed -independently. The accuracy is approximately the same as of the built-in -std::sqrt . -@param src input floating-point array. -@param dst output array of the same size and type as src. -*/ -CV_EXPORTS_W void sqrt(InputArray src, OutputArray dst); - -/** @brief Raises every array element to a power. - -The function cv::pow raises every element of the input array to power : -\f[\texttt{dst} (I) = \fork{\texttt{src}(I)^{power}}{if \(\texttt{power}\) is integer}{|\texttt{src}(I)|^{power}}{otherwise}\f] - -So, for a non-integer power exponent, the absolute values of input array -elements are used. However, it is possible to get true values for -negative values using some extra operations. In the example below, -computing the 5th root of array src shows: -@code{.cpp} - Mat mask = src < 0; - pow(src, 1./5, dst); - subtract(Scalar::all(0), dst, dst, mask); -@endcode -For some values of power, such as integer values, 0.5 and -0.5, -specialized faster algorithms are used. - -Special values (NaN, Inf) are not handled. -@param src input array. -@param power exponent of power. -@param dst output array of the same size and type as src. -@sa sqrt, exp, log, cartToPolar, polarToCart -*/ -CV_EXPORTS_W void pow(InputArray src, double power, OutputArray dst); - -/** @brief Calculates the exponent of every array element. - -The function cv::exp calculates the exponent of every element of the input -array: -\f[\texttt{dst} [I] = e^{ src(I) }\f] - -The maximum relative error is about 7e-6 for single-precision input and -less than 1e-10 for double-precision input. Currently, the function -converts denormalized values to zeros on output. Special values (NaN, -Inf) are not handled. -@param src input array. -@param dst output array of the same size and type as src. -@sa log, cartToPolar, polarToCart, phase, pow, sqrt, magnitude -*/ -CV_EXPORTS_W void exp(InputArray src, OutputArray dst); - -/** @brief Calculates the natural logarithm of every array element. - -The function cv::log calculates the natural logarithm of every element of the input array: -\f[\texttt{dst} (I) = \log (\texttt{src}(I)) \f] - -Output on zero, negative and special (NaN, Inf) values is undefined. - -@param src input array. -@param dst output array of the same size and type as src . -@sa exp, cartToPolar, polarToCart, phase, pow, sqrt, magnitude -*/ -CV_EXPORTS_W void log(InputArray src, OutputArray dst); - -/** @brief Calculates x and y coordinates of 2D vectors from their magnitude and angle. - -The function cv::polarToCart calculates the Cartesian coordinates of each 2D -vector represented by the corresponding elements of magnitude and angle: -\f[\begin{array}{l} \texttt{x} (I) = \texttt{magnitude} (I) \cos ( \texttt{angle} (I)) \\ \texttt{y} (I) = \texttt{magnitude} (I) \sin ( \texttt{angle} (I)) \\ \end{array}\f] - -The relative accuracy of the estimated coordinates is about 1e-6. -@param magnitude input floating-point array of magnitudes of 2D vectors; -it can be an empty matrix (=Mat()), in this case, the function assumes -that all the magnitudes are =1; if it is not empty, it must have the -same size and type as angle. -@param angle input floating-point array of angles of 2D vectors. -@param x output array of x-coordinates of 2D vectors; it has the same -size and type as angle. -@param y output array of y-coordinates of 2D vectors; it has the same -size and type as angle. -@param angleInDegrees when true, the input angles are measured in -degrees, otherwise, they are measured in radians. -@sa cartToPolar, magnitude, phase, exp, log, pow, sqrt -*/ -CV_EXPORTS_W void polarToCart(InputArray magnitude, InputArray angle, - OutputArray x, OutputArray y, bool angleInDegrees = false); - -/** @brief Calculates the magnitude and angle of 2D vectors. - -The function cv::cartToPolar calculates either the magnitude, angle, or both -for every 2D vector (x(I),y(I)): -\f[\begin{array}{l} \texttt{magnitude} (I)= \sqrt{\texttt{x}(I)^2+\texttt{y}(I)^2} , \\ \texttt{angle} (I)= \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))[ \cdot180 / \pi ] \end{array}\f] - -The angles are calculated with accuracy about 0.3 degrees. For the point -(0,0), the angle is set to 0. -@param x array of x-coordinates; this must be a single-precision or -double-precision floating-point array. -@param y array of y-coordinates, that must have the same size and same type as x. -@param magnitude output array of magnitudes of the same size and type as x. -@param angle output array of angles that has the same size and type as -x; the angles are measured in radians (from 0 to 2\*Pi) or in degrees (0 to 360 degrees). -@param angleInDegrees a flag, indicating whether the angles are measured -in radians (which is by default), or in degrees. -@sa Sobel, Scharr -*/ -CV_EXPORTS_W void cartToPolar(InputArray x, InputArray y, - OutputArray magnitude, OutputArray angle, - bool angleInDegrees = false); - -/** @brief Calculates the rotation angle of 2D vectors. - -The function cv::phase calculates the rotation angle of each 2D vector that -is formed from the corresponding elements of x and y : -\f[\texttt{angle} (I) = \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))\f] - -The angle estimation accuracy is about 0.3 degrees. When x(I)=y(I)=0 , -the corresponding angle(I) is set to 0. -@param x input floating-point array of x-coordinates of 2D vectors. -@param y input array of y-coordinates of 2D vectors; it must have the -same size and the same type as x. -@param angle output array of vector angles; it has the same size and -same type as x . -@param angleInDegrees when true, the function calculates the angle in -degrees, otherwise, they are measured in radians. -*/ -CV_EXPORTS_W void phase(InputArray x, InputArray y, OutputArray angle, - bool angleInDegrees = false); - -/** @brief Calculates the magnitude of 2D vectors. - -The function cv::magnitude calculates the magnitude of 2D vectors formed -from the corresponding elements of x and y arrays: -\f[\texttt{dst} (I) = \sqrt{\texttt{x}(I)^2 + \texttt{y}(I)^2}\f] -@param x floating-point array of x-coordinates of the vectors. -@param y floating-point array of y-coordinates of the vectors; it must -have the same size as x. -@param magnitude output array of the same size and type as x. -@sa cartToPolar, polarToCart, phase, sqrt -*/ -CV_EXPORTS_W void magnitude(InputArray x, InputArray y, OutputArray magnitude); - -/** @brief Checks every element of an input array for invalid values. - -The function cv::checkRange checks that every array element is neither NaN nor infinite. When minVal \> --DBL_MAX and maxVal \< DBL_MAX, the function also checks that each value is between minVal and -maxVal. In case of multi-channel arrays, each channel is processed independently. If some values -are out of range, position of the first outlier is stored in pos (when pos != NULL). Then, the -function either returns false (when quiet=true) or throws an exception. -@param a input array. -@param quiet a flag, indicating whether the functions quietly return false when the array elements -are out of range or they throw an exception. -@param pos optional output parameter, when not NULL, must be a pointer to array of src.dims -elements. -@param minVal inclusive lower boundary of valid values range. -@param maxVal exclusive upper boundary of valid values range. -*/ -CV_EXPORTS_W bool checkRange(InputArray a, bool quiet = true, CV_OUT Point* pos = 0, - double minVal = -DBL_MAX, double maxVal = DBL_MAX); - -/** @brief Replaces NaNs by given number -@param a input/output matrix (CV_32F type). -@param val value to convert the NaNs -*/ -CV_EXPORTS_W void patchNaNs(InputOutputArray a, double val = 0); - -/** @brief Performs generalized matrix multiplication. - -The function cv::gemm performs generalized matrix multiplication similar to the -gemm functions in BLAS level 3. For example, -`gemm(src1, src2, alpha, src3, beta, dst, GEMM_1_T + GEMM_3_T)` -corresponds to -\f[\texttt{dst} = \texttt{alpha} \cdot \texttt{src1} ^T \cdot \texttt{src2} + \texttt{beta} \cdot \texttt{src3} ^T\f] - -In case of complex (two-channel) data, performed a complex matrix -multiplication. - -The function can be replaced with a matrix expression. For example, the -above call can be replaced with: -@code{.cpp} - dst = alpha*src1.t()*src2 + beta*src3.t(); -@endcode -@param src1 first multiplied input matrix that could be real(CV_32FC1, -CV_64FC1) or complex(CV_32FC2, CV_64FC2). -@param src2 second multiplied input matrix of the same type as src1. -@param alpha weight of the matrix product. -@param src3 third optional delta matrix added to the matrix product; it -should have the same type as src1 and src2. -@param beta weight of src3. -@param dst output matrix; it has the proper size and the same type as -input matrices. -@param flags operation flags (cv::GemmFlags) -@sa mulTransposed, transform -*/ -CV_EXPORTS_W void gemm(InputArray src1, InputArray src2, double alpha, - InputArray src3, double beta, OutputArray dst, int flags = 0); - -/** @brief Calculates the product of a matrix and its transposition. - -The function cv::mulTransposed calculates the product of src and its -transposition: -\f[\texttt{dst} = \texttt{scale} ( \texttt{src} - \texttt{delta} )^T ( \texttt{src} - \texttt{delta} )\f] -if aTa=true, and -\f[\texttt{dst} = \texttt{scale} ( \texttt{src} - \texttt{delta} ) ( \texttt{src} - \texttt{delta} )^T\f] -otherwise. The function is used to calculate the covariance matrix. With -zero delta, it can be used as a faster substitute for general matrix -product A\*B when B=A' -@param src input single-channel matrix. Note that unlike gemm, the -function can multiply not only floating-point matrices. -@param dst output square matrix. -@param aTa Flag specifying the multiplication ordering. See the -description below. -@param delta Optional delta matrix subtracted from src before the -multiplication. When the matrix is empty ( delta=noArray() ), it is -assumed to be zero, that is, nothing is subtracted. If it has the same -size as src, it is simply subtracted. Otherwise, it is "repeated" (see -repeat ) to cover the full src and then subtracted. Type of the delta -matrix, when it is not empty, must be the same as the type of created -output matrix. See the dtype parameter description below. -@param scale Optional scale factor for the matrix product. -@param dtype Optional type of the output matrix. When it is negative, -the output matrix will have the same type as src . Otherwise, it will be -type=CV_MAT_DEPTH(dtype) that should be either CV_32F or CV_64F . -@sa calcCovarMatrix, gemm, repeat, reduce -*/ -CV_EXPORTS_W void mulTransposed( InputArray src, OutputArray dst, bool aTa, - InputArray delta = noArray(), - double scale = 1, int dtype = -1 ); - -/** @brief Transposes a matrix. - -The function cv::transpose transposes the matrix src : -\f[\texttt{dst} (i,j) = \texttt{src} (j,i)\f] -@note No complex conjugation is done in case of a complex matrix. It -should be done separately if needed. -@param src input array. -@param dst output array of the same type as src. -*/ -CV_EXPORTS_W void transpose(InputArray src, OutputArray dst); - -/** @brief Transpose for n-dimensional matrices. - * - * @note Input should be continuous single-channel matrix. - * @param src input array. - * @param order a permutation of [0,1,..,N-1] where N is the number of axes of src. - * The i'th axis of dst will correspond to the axis numbered order[i] of the input. - * @param dst output array of the same type as src. - */ -CV_EXPORTS_W void transposeND(InputArray src, const std::vector& order, OutputArray dst); - -/** @brief Performs the matrix transformation of every array element. - -The function cv::transform performs the matrix transformation of every -element of the array src and stores the results in dst : -\f[\texttt{dst} (I) = \texttt{m} \cdot \texttt{src} (I)\f] -(when m.cols=src.channels() ), or -\f[\texttt{dst} (I) = \texttt{m} \cdot [ \texttt{src} (I); 1]\f] -(when m.cols=src.channels()+1 ) - -Every element of the N -channel array src is interpreted as N -element -vector that is transformed using the M x N or M x (N+1) matrix m to -M-element vector - the corresponding element of the output array dst . - -The function may be used for geometrical transformation of -N -dimensional points, arbitrary linear color space transformation (such -as various kinds of RGB to YUV transforms), shuffling the image -channels, and so forth. -@param src input array that must have as many channels (1 to 4) as -m.cols or m.cols-1. -@param dst output array of the same size and depth as src; it has as -many channels as m.rows. -@param m transformation 2x2 or 2x3 floating-point matrix. -@sa perspectiveTransform, getAffineTransform, estimateAffine2D, warpAffine, warpPerspective -*/ -CV_EXPORTS_W void transform(InputArray src, OutputArray dst, InputArray m ); - -/** @brief Performs the perspective matrix transformation of vectors. - -The function cv::perspectiveTransform transforms every element of src by -treating it as a 2D or 3D vector, in the following way: -\f[(x, y, z) \rightarrow (x'/w, y'/w, z'/w)\f] -where -\f[(x', y', z', w') = \texttt{mat} \cdot \begin{bmatrix} x & y & z & 1 \end{bmatrix}\f] -and -\f[w = \fork{w'}{if \(w' \ne 0\)}{\infty}{otherwise}\f] - -Here a 3D vector transformation is shown. In case of a 2D vector -transformation, the z component is omitted. - -@note The function transforms a sparse set of 2D or 3D vectors. If you -want to transform an image using perspective transformation, use -warpPerspective . If you have an inverse problem, that is, you want to -compute the most probable perspective transformation out of several -pairs of corresponding points, you can use getPerspectiveTransform or -findHomography . -@param src input two-channel or three-channel floating-point array; each -element is a 2D/3D vector to be transformed. -@param dst output array of the same size and type as src. -@param m 3x3 or 4x4 floating-point transformation matrix. -@sa transform, warpPerspective, getPerspectiveTransform, findHomography -*/ -CV_EXPORTS_W void perspectiveTransform(InputArray src, OutputArray dst, InputArray m ); - -/** @brief Copies the lower or the upper half of a square matrix to its another half. - -The function cv::completeSymm copies the lower or the upper half of a square matrix to -its another half. The matrix diagonal remains unchanged: - - \f$\texttt{m}_{ij}=\texttt{m}_{ji}\f$ for \f$i > j\f$ if - lowerToUpper=false - - \f$\texttt{m}_{ij}=\texttt{m}_{ji}\f$ for \f$i < j\f$ if - lowerToUpper=true - -@param m input-output floating-point square matrix. -@param lowerToUpper operation flag; if true, the lower half is copied to -the upper half. Otherwise, the upper half is copied to the lower half. -@sa flip, transpose -*/ -CV_EXPORTS_W void completeSymm(InputOutputArray m, bool lowerToUpper = false); - -/** @brief Initializes a scaled identity matrix. - -The function cv::setIdentity initializes a scaled identity matrix: -\f[\texttt{mtx} (i,j)= \fork{\texttt{value}}{ if \(i=j\)}{0}{otherwise}\f] - -The function can also be emulated using the matrix initializers and the -matrix expressions: -@code - Mat A = Mat::eye(4, 3, CV_32F)*5; - // A will be set to [[5, 0, 0], [0, 5, 0], [0, 0, 5], [0, 0, 0]] -@endcode -@param mtx matrix to initialize (not necessarily square). -@param s value to assign to diagonal elements. -@sa Mat::zeros, Mat::ones, Mat::setTo, Mat::operator= -*/ -CV_EXPORTS_W void setIdentity(InputOutputArray mtx, const Scalar& s = Scalar(1)); - -/** @brief Returns the determinant of a square floating-point matrix. - -The function cv::determinant calculates and returns the determinant of the -specified matrix. For small matrices ( mtx.cols=mtx.rows\<=3 ), the -direct method is used. For larger matrices, the function uses LU -factorization with partial pivoting. - -For symmetric positively-determined matrices, it is also possible to use -eigen decomposition to calculate the determinant. -@param mtx input matrix that must have CV_32FC1 or CV_64FC1 type and -square size. -@sa trace, invert, solve, eigen, @ref MatrixExpressions -*/ -CV_EXPORTS_W double determinant(InputArray mtx); - -/** @brief Returns the trace of a matrix. - -The function cv::trace returns the sum of the diagonal elements of the -matrix mtx . -\f[\mathrm{tr} ( \texttt{mtx} ) = \sum _i \texttt{mtx} (i,i)\f] -@param mtx input matrix. -*/ -CV_EXPORTS_W Scalar trace(InputArray mtx); - -/** @brief Finds the inverse or pseudo-inverse of a matrix. - -The function cv::invert inverts the matrix src and stores the result in dst -. When the matrix src is singular or non-square, the function calculates -the pseudo-inverse matrix (the dst matrix) so that norm(src\*dst - I) is -minimal, where I is an identity matrix. - -In case of the #DECOMP_LU method, the function returns non-zero value if -the inverse has been successfully calculated and 0 if src is singular. - -In case of the #DECOMP_SVD method, the function returns the inverse -condition number of src (the ratio of the smallest singular value to the -largest singular value) and 0 if src is singular. The SVD method -calculates a pseudo-inverse matrix if src is singular. - -Similarly to #DECOMP_LU, the method #DECOMP_CHOLESKY works only with -non-singular square matrices that should also be symmetrical and -positively defined. In this case, the function stores the inverted -matrix in dst and returns non-zero. Otherwise, it returns 0. - -@param src input floating-point M x N matrix. -@param dst output matrix of N x M size and the same type as src. -@param flags inversion method (cv::DecompTypes) -@sa solve, SVD -*/ -CV_EXPORTS_W double invert(InputArray src, OutputArray dst, int flags = DECOMP_LU); - -/** @brief Solves one or more linear systems or least-squares problems. - -The function cv::solve solves a linear system or least-squares problem (the -latter is possible with SVD or QR methods, or by specifying the flag -#DECOMP_NORMAL ): -\f[\texttt{dst} = \arg \min _X \| \texttt{src1} \cdot \texttt{X} - \texttt{src2} \|\f] - -If #DECOMP_LU or #DECOMP_CHOLESKY method is used, the function returns 1 -if src1 (or \f$\texttt{src1}^T\texttt{src1}\f$ ) is non-singular. Otherwise, -it returns 0. In the latter case, dst is not valid. Other methods find a -pseudo-solution in case of a singular left-hand side part. - -@note If you want to find a unity-norm solution of an under-defined -singular system \f$\texttt{src1}\cdot\texttt{dst}=0\f$ , the function solve -will not do the work. Use SVD::solveZ instead. - -@param src1 input matrix on the left-hand side of the system. -@param src2 input matrix on the right-hand side of the system. -@param dst output solution. -@param flags solution (matrix inversion) method (#DecompTypes) -@sa invert, SVD, eigen -*/ -CV_EXPORTS_W bool solve(InputArray src1, InputArray src2, - OutputArray dst, int flags = DECOMP_LU); - -/** @brief Sorts each row or each column of a matrix. - -The function cv::sort sorts each matrix row or each matrix column in -ascending or descending order. So you should pass two operation flags to -get desired behaviour. If you want to sort matrix rows or columns -lexicographically, you can use STL std::sort generic function with the -proper comparison predicate. - -@param src input single-channel array. -@param dst output array of the same size and type as src. -@param flags operation flags, a combination of #SortFlags -@sa sortIdx, randShuffle -*/ -CV_EXPORTS_W void sort(InputArray src, OutputArray dst, int flags); - -/** @brief Sorts each row or each column of a matrix. - -The function cv::sortIdx sorts each matrix row or each matrix column in the -ascending or descending order. So you should pass two operation flags to -get desired behaviour. Instead of reordering the elements themselves, it -stores the indices of sorted elements in the output array. For example: -@code - Mat A = Mat::eye(3,3,CV_32F), B; - sortIdx(A, B, SORT_EVERY_ROW + SORT_ASCENDING); - // B will probably contain - // (because of equal elements in A some permutations are possible): - // [[1, 2, 0], [0, 2, 1], [0, 1, 2]] -@endcode -@param src input single-channel array. -@param dst output integer array of the same size as src. -@param flags operation flags that could be a combination of cv::SortFlags -@sa sort, randShuffle -*/ -CV_EXPORTS_W void sortIdx(InputArray src, OutputArray dst, int flags); - -/** @brief Finds the real roots of a cubic equation. - -The function solveCubic finds the real roots of a cubic equation: -- if coeffs is a 4-element vector: -\f[\texttt{coeffs} [0] x^3 + \texttt{coeffs} [1] x^2 + \texttt{coeffs} [2] x + \texttt{coeffs} [3] = 0\f] -- if coeffs is a 3-element vector: -\f[x^3 + \texttt{coeffs} [0] x^2 + \texttt{coeffs} [1] x + \texttt{coeffs} [2] = 0\f] - -The roots are stored in the roots array. -@param coeffs equation coefficients, an array of 3 or 4 elements. -@param roots output array of real roots that has 1 or 3 elements. -@return number of real roots. It can be 0, 1 or 2. -*/ -CV_EXPORTS_W int solveCubic(InputArray coeffs, OutputArray roots); - -/** @brief Finds the real or complex roots of a polynomial equation. - -The function cv::solvePoly finds real and complex roots of a polynomial equation: -\f[\texttt{coeffs} [n] x^{n} + \texttt{coeffs} [n-1] x^{n-1} + ... + \texttt{coeffs} [1] x + \texttt{coeffs} [0] = 0\f] -@param coeffs array of polynomial coefficients. -@param roots output (complex) array of roots. -@param maxIters maximum number of iterations the algorithm does. -*/ -CV_EXPORTS_W double solvePoly(InputArray coeffs, OutputArray roots, int maxIters = 300); - -/** @brief Calculates eigenvalues and eigenvectors of a symmetric matrix. - -The function cv::eigen calculates just eigenvalues, or eigenvalues and eigenvectors of the symmetric -matrix src: -@code - src*eigenvectors.row(i).t() = eigenvalues.at(i)*eigenvectors.row(i).t() -@endcode - -@note Use cv::eigenNonSymmetric for calculation of real eigenvalues and eigenvectors of non-symmetric matrix. - -@param src input matrix that must have CV_32FC1 or CV_64FC1 type, square size and be symmetrical -(src ^T^ == src). -@param eigenvalues output vector of eigenvalues of the same type as src; the eigenvalues are stored -in the descending order. -@param eigenvectors output matrix of eigenvectors; it has the same size and type as src; the -eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding -eigenvalues. -@sa eigenNonSymmetric, completeSymm, PCA -*/ -CV_EXPORTS_W bool eigen(InputArray src, OutputArray eigenvalues, - OutputArray eigenvectors = noArray()); - -/** @brief Calculates eigenvalues and eigenvectors of a non-symmetric matrix (real eigenvalues only). - -@note Assumes real eigenvalues. - -The function calculates eigenvalues and eigenvectors (optional) of the square matrix src: -@code - src*eigenvectors.row(i).t() = eigenvalues.at(i)*eigenvectors.row(i).t() -@endcode - -@param src input matrix (CV_32FC1 or CV_64FC1 type). -@param eigenvalues output vector of eigenvalues (type is the same type as src). -@param eigenvectors output matrix of eigenvectors (type is the same type as src). The eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding eigenvalues. -@sa eigen -*/ -CV_EXPORTS_W void eigenNonSymmetric(InputArray src, OutputArray eigenvalues, - OutputArray eigenvectors); - -/** @brief Calculates the covariance matrix of a set of vectors. - -The function cv::calcCovarMatrix calculates the covariance matrix and, optionally, the mean vector of -the set of input vectors. -@param samples samples stored as separate matrices -@param nsamples number of samples -@param covar output covariance matrix of the type ctype and square size. -@param mean input or output (depending on the flags) array as the average value of the input vectors. -@param flags operation flags as a combination of #CovarFlags -@param ctype type of the matrixl; it equals 'CV_64F' by default. -@sa PCA, mulTransposed, Mahalanobis -@todo InputArrayOfArrays -*/ -CV_EXPORTS void calcCovarMatrix( const Mat* samples, int nsamples, Mat& covar, Mat& mean, - int flags, int ctype = CV_64F); - -/** @overload -@note use #COVAR_ROWS or #COVAR_COLS flag -@param samples samples stored as rows/columns of a single matrix. -@param covar output covariance matrix of the type ctype and square size. -@param mean input or output (depending on the flags) array as the average value of the input vectors. -@param flags operation flags as a combination of #CovarFlags -@param ctype type of the matrixl; it equals 'CV_64F' by default. -*/ -CV_EXPORTS_W void calcCovarMatrix( InputArray samples, OutputArray covar, - InputOutputArray mean, int flags, int ctype = CV_64F); - -/** wrap PCA::operator() */ -CV_EXPORTS_W void PCACompute(InputArray data, InputOutputArray mean, - OutputArray eigenvectors, int maxComponents = 0); - -/** wrap PCA::operator() and add eigenvalues output parameter */ -CV_EXPORTS_AS(PCACompute2) void PCACompute(InputArray data, InputOutputArray mean, - OutputArray eigenvectors, OutputArray eigenvalues, - int maxComponents = 0); - -/** wrap PCA::operator() */ -CV_EXPORTS_W void PCACompute(InputArray data, InputOutputArray mean, - OutputArray eigenvectors, double retainedVariance); - -/** wrap PCA::operator() and add eigenvalues output parameter */ -CV_EXPORTS_AS(PCACompute2) void PCACompute(InputArray data, InputOutputArray mean, - OutputArray eigenvectors, OutputArray eigenvalues, - double retainedVariance); - -/** wrap PCA::project */ -CV_EXPORTS_W void PCAProject(InputArray data, InputArray mean, - InputArray eigenvectors, OutputArray result); - -/** wrap PCA::backProject */ -CV_EXPORTS_W void PCABackProject(InputArray data, InputArray mean, - InputArray eigenvectors, OutputArray result); - -/** wrap SVD::compute */ -CV_EXPORTS_W void SVDecomp( InputArray src, OutputArray w, OutputArray u, OutputArray vt, int flags = 0 ); - -/** wrap SVD::backSubst */ -CV_EXPORTS_W void SVBackSubst( InputArray w, InputArray u, InputArray vt, - InputArray rhs, OutputArray dst ); - -/** @brief Calculates the Mahalanobis distance between two vectors. - -The function cv::Mahalanobis calculates and returns the weighted distance between two vectors: -\f[d( \texttt{vec1} , \texttt{vec2} )= \sqrt{\sum_{i,j}{\texttt{icovar(i,j)}\cdot(\texttt{vec1}(I)-\texttt{vec2}(I))\cdot(\texttt{vec1(j)}-\texttt{vec2(j)})} }\f] -The covariance matrix may be calculated using the #calcCovarMatrix function and then inverted using -the invert function (preferably using the #DECOMP_SVD method, as the most accurate). -@param v1 first 1D input vector. -@param v2 second 1D input vector. -@param icovar inverse covariance matrix. -*/ -CV_EXPORTS_W double Mahalanobis(InputArray v1, InputArray v2, InputArray icovar); - -/** @brief Performs a forward or inverse Discrete Fourier transform of a 1D or 2D floating-point array. - -The function cv::dft performs one of the following: -- Forward the Fourier transform of a 1D vector of N elements: - \f[Y = F^{(N)} \cdot X,\f] - where \f$F^{(N)}_{jk}=\exp(-2\pi i j k/N)\f$ and \f$i=\sqrt{-1}\f$ -- Inverse the Fourier transform of a 1D vector of N elements: - \f[\begin{array}{l} X'= \left (F^{(N)} \right )^{-1} \cdot Y = \left (F^{(N)} \right )^* \cdot y \\ X = (1/N) \cdot X, \end{array}\f] - where \f$F^*=\left(\textrm{Re}(F^{(N)})-\textrm{Im}(F^{(N)})\right)^T\f$ -- Forward the 2D Fourier transform of a M x N matrix: - \f[Y = F^{(M)} \cdot X \cdot F^{(N)}\f] -- Inverse the 2D Fourier transform of a M x N matrix: - \f[\begin{array}{l} X'= \left (F^{(M)} \right )^* \cdot Y \cdot \left (F^{(N)} \right )^* \\ X = \frac{1}{M \cdot N} \cdot X' \end{array}\f] - -In case of real (single-channel) data, the output spectrum of the forward Fourier transform or input -spectrum of the inverse Fourier transform can be represented in a packed format called *CCS* -(complex-conjugate-symmetrical). It was borrowed from IPL (Intel\* Image Processing Library). Here -is how 2D *CCS* spectrum looks: -\f[\begin{bmatrix} Re Y_{0,0} & Re Y_{0,1} & Im Y_{0,1} & Re Y_{0,2} & Im Y_{0,2} & \cdots & Re Y_{0,N/2-1} & Im Y_{0,N/2-1} & Re Y_{0,N/2} \\ Re Y_{1,0} & Re Y_{1,1} & Im Y_{1,1} & Re Y_{1,2} & Im Y_{1,2} & \cdots & Re Y_{1,N/2-1} & Im Y_{1,N/2-1} & Re Y_{1,N/2} \\ Im Y_{1,0} & Re Y_{2,1} & Im Y_{2,1} & Re Y_{2,2} & Im Y_{2,2} & \cdots & Re Y_{2,N/2-1} & Im Y_{2,N/2-1} & Im Y_{1,N/2} \\ \hdotsfor{9} \\ Re Y_{M/2-1,0} & Re Y_{M-3,1} & Im Y_{M-3,1} & \hdotsfor{3} & Re Y_{M-3,N/2-1} & Im Y_{M-3,N/2-1}& Re Y_{M/2-1,N/2} \\ Im Y_{M/2-1,0} & Re Y_{M-2,1} & Im Y_{M-2,1} & \hdotsfor{3} & Re Y_{M-2,N/2-1} & Im Y_{M-2,N/2-1}& Im Y_{M/2-1,N/2} \\ Re Y_{M/2,0} & Re Y_{M-1,1} & Im Y_{M-1,1} & \hdotsfor{3} & Re Y_{M-1,N/2-1} & Im Y_{M-1,N/2-1}& Re Y_{M/2,N/2} \end{bmatrix}\f] - -In case of 1D transform of a real vector, the output looks like the first row of the matrix above. - -So, the function chooses an operation mode depending on the flags and size of the input array: -- If #DFT_ROWS is set or the input array has a single row or single column, the function - performs a 1D forward or inverse transform of each row of a matrix when #DFT_ROWS is set. - Otherwise, it performs a 2D transform. -- If the input array is real and #DFT_INVERSE is not set, the function performs a forward 1D or - 2D transform: - - When #DFT_COMPLEX_OUTPUT is set, the output is a complex matrix of the same size as - input. - - When #DFT_COMPLEX_OUTPUT is not set, the output is a real matrix of the same size as - input. In case of 2D transform, it uses the packed format as shown above. In case of a - single 1D transform, it looks like the first row of the matrix above. In case of - multiple 1D transforms (when using the #DFT_ROWS flag), each row of the output matrix - looks like the first row of the matrix above. -- If the input array is complex and either #DFT_INVERSE or #DFT_REAL_OUTPUT are not set, the - output is a complex array of the same size as input. The function performs a forward or - inverse 1D or 2D transform of the whole input array or each row of the input array - independently, depending on the flags DFT_INVERSE and DFT_ROWS. -- When #DFT_INVERSE is set and the input array is real, or it is complex but #DFT_REAL_OUTPUT - is set, the output is a real array of the same size as input. The function performs a 1D or 2D - inverse transformation of the whole input array or each individual row, depending on the flags - #DFT_INVERSE and #DFT_ROWS. - -If #DFT_SCALE is set, the scaling is done after the transformation. - -Unlike dct, the function supports arrays of arbitrary size. But only those arrays are processed -efficiently, whose sizes can be factorized in a product of small prime numbers (2, 3, and 5 in the -current implementation). Such an efficient DFT size can be calculated using the getOptimalDFTSize -method. - -The sample below illustrates how to calculate a DFT-based convolution of two 2D real arrays: -@code - void convolveDFT(InputArray A, InputArray B, OutputArray C) - { - // reallocate the output array if needed - C.create(abs(A.rows - B.rows)+1, abs(A.cols - B.cols)+1, A.type()); - Size dftSize; - // calculate the size of DFT transform - dftSize.width = getOptimalDFTSize(A.cols + B.cols - 1); - dftSize.height = getOptimalDFTSize(A.rows + B.rows - 1); - - // allocate temporary buffers and initialize them with 0's - Mat tempA(dftSize, A.type(), Scalar::all(0)); - Mat tempB(dftSize, B.type(), Scalar::all(0)); - - // copy A and B to the top-left corners of tempA and tempB, respectively - Mat roiA(tempA, Rect(0,0,A.cols,A.rows)); - A.copyTo(roiA); - Mat roiB(tempB, Rect(0,0,B.cols,B.rows)); - B.copyTo(roiB); - - // now transform the padded A & B in-place; - // use "nonzeroRows" hint for faster processing - dft(tempA, tempA, 0, A.rows); - dft(tempB, tempB, 0, B.rows); - - // multiply the spectrums; - // the function handles packed spectrum representations well - mulSpectrums(tempA, tempB, tempA); - - // transform the product back from the frequency domain. - // Even though all the result rows will be non-zero, - // you need only the first C.rows of them, and thus you - // pass nonzeroRows == C.rows - dft(tempA, tempA, DFT_INVERSE + DFT_SCALE, C.rows); - - // now copy the result back to C. - tempA(Rect(0, 0, C.cols, C.rows)).copyTo(C); - - // all the temporary buffers will be deallocated automatically - } -@endcode -To optimize this sample, consider the following approaches: -- Since nonzeroRows != 0 is passed to the forward transform calls and since A and B are copied to - the top-left corners of tempA and tempB, respectively, it is not necessary to clear the whole - tempA and tempB. It is only necessary to clear the tempA.cols - A.cols ( tempB.cols - B.cols) - rightmost columns of the matrices. -- This DFT-based convolution does not have to be applied to the whole big arrays, especially if B - is significantly smaller than A or vice versa. Instead, you can calculate convolution by parts. - To do this, you need to split the output array C into multiple tiles. For each tile, estimate - which parts of A and B are required to calculate convolution in this tile. If the tiles in C are - too small, the speed will decrease a lot because of repeated work. In the ultimate case, when - each tile in C is a single pixel, the algorithm becomes equivalent to the naive convolution - algorithm. If the tiles are too big, the temporary arrays tempA and tempB become too big and - there is also a slowdown because of bad cache locality. So, there is an optimal tile size - somewhere in the middle. -- If different tiles in C can be calculated in parallel and, thus, the convolution is done by - parts, the loop can be threaded. - -All of the above improvements have been implemented in #matchTemplate and #filter2D . Therefore, by -using them, you can get the performance even better than with the above theoretically optimal -implementation. Though, those two functions actually calculate cross-correlation, not convolution, -so you need to "flip" the second convolution operand B vertically and horizontally using flip . -@note -- An example using the discrete fourier transform can be found at - opencv_source_code/samples/cpp/dft.cpp -- (Python) An example using the dft functionality to perform Wiener deconvolution can be found - at opencv_source/samples/python/deconvolution.py -- (Python) An example rearranging the quadrants of a Fourier image can be found at - opencv_source/samples/python/dft.py -@param src input array that could be real or complex. -@param dst output array whose size and type depends on the flags . -@param flags transformation flags, representing a combination of the #DftFlags -@param nonzeroRows when the parameter is not zero, the function assumes that only the first -nonzeroRows rows of the input array (#DFT_INVERSE is not set) or only the first nonzeroRows of the -output array (#DFT_INVERSE is set) contain non-zeros, thus, the function can handle the rest of the -rows more efficiently and save some time; this technique is very useful for calculating array -cross-correlation or convolution using DFT. -@sa dct, getOptimalDFTSize, mulSpectrums, filter2D, matchTemplate, flip, cartToPolar, -magnitude, phase -*/ -CV_EXPORTS_W void dft(InputArray src, OutputArray dst, int flags = 0, int nonzeroRows = 0); - -/** @brief Calculates the inverse Discrete Fourier Transform of a 1D or 2D array. - -idft(src, dst, flags) is equivalent to dft(src, dst, flags | #DFT_INVERSE) . -@note None of dft and idft scales the result by default. So, you should pass #DFT_SCALE to one of -dft or idft explicitly to make these transforms mutually inverse. -@sa dft, dct, idct, mulSpectrums, getOptimalDFTSize -@param src input floating-point real or complex array. -@param dst output array whose size and type depend on the flags. -@param flags operation flags (see dft and #DftFlags). -@param nonzeroRows number of dst rows to process; the rest of the rows have undefined content (see -the convolution sample in dft description. -*/ -CV_EXPORTS_W void idft(InputArray src, OutputArray dst, int flags = 0, int nonzeroRows = 0); - -/** @brief Performs a forward or inverse discrete Cosine transform of 1D or 2D array. - -The function cv::dct performs a forward or inverse discrete Cosine transform (DCT) of a 1D or 2D -floating-point array: -- Forward Cosine transform of a 1D vector of N elements: - \f[Y = C^{(N)} \cdot X\f] - where - \f[C^{(N)}_{jk}= \sqrt{\alpha_j/N} \cos \left ( \frac{\pi(2k+1)j}{2N} \right )\f] - and - \f$\alpha_0=1\f$, \f$\alpha_j=2\f$ for *j \> 0*. -- Inverse Cosine transform of a 1D vector of N elements: - \f[X = \left (C^{(N)} \right )^{-1} \cdot Y = \left (C^{(N)} \right )^T \cdot Y\f] - (since \f$C^{(N)}\f$ is an orthogonal matrix, \f$C^{(N)} \cdot \left(C^{(N)}\right)^T = I\f$ ) -- Forward 2D Cosine transform of M x N matrix: - \f[Y = C^{(N)} \cdot X \cdot \left (C^{(N)} \right )^T\f] -- Inverse 2D Cosine transform of M x N matrix: - \f[X = \left (C^{(N)} \right )^T \cdot X \cdot C^{(N)}\f] - -The function chooses the mode of operation by looking at the flags and size of the input array: -- If (flags & #DCT_INVERSE) == 0, the function does a forward 1D or 2D transform. Otherwise, it - is an inverse 1D or 2D transform. -- If (flags & #DCT_ROWS) != 0, the function performs a 1D transform of each row. -- If the array is a single column or a single row, the function performs a 1D transform. -- If none of the above is true, the function performs a 2D transform. - -@note Currently dct supports even-size arrays (2, 4, 6 ...). For data analysis and approximation, you -can pad the array when necessary. -Also, the function performance depends very much, and not monotonically, on the array size (see -getOptimalDFTSize ). In the current implementation DCT of a vector of size N is calculated via DFT -of a vector of size N/2 . Thus, the optimal DCT size N1 \>= N can be calculated as: -@code - size_t getOptimalDCTSize(size_t N) { return 2*getOptimalDFTSize((N+1)/2); } - N1 = getOptimalDCTSize(N); -@endcode -@param src input floating-point array. -@param dst output array of the same size and type as src . -@param flags transformation flags as a combination of cv::DftFlags (DCT_*) -@sa dft, getOptimalDFTSize, idct -*/ -CV_EXPORTS_W void dct(InputArray src, OutputArray dst, int flags = 0); - -/** @brief Calculates the inverse Discrete Cosine Transform of a 1D or 2D array. - -idct(src, dst, flags) is equivalent to dct(src, dst, flags | DCT_INVERSE). -@param src input floating-point single-channel array. -@param dst output array of the same size and type as src. -@param flags operation flags. -@sa dct, dft, idft, getOptimalDFTSize -*/ -CV_EXPORTS_W void idct(InputArray src, OutputArray dst, int flags = 0); - -/** @brief Performs the per-element multiplication of two Fourier spectrums. - -The function cv::mulSpectrums performs the per-element multiplication of the two CCS-packed or complex -matrices that are results of a real or complex Fourier transform. - -The function, together with dft and idft, may be used to calculate convolution (pass conjB=false ) -or correlation (pass conjB=true ) of two arrays rapidly. When the arrays are complex, they are -simply multiplied (per element) with an optional conjugation of the second-array elements. When the -arrays are real, they are assumed to be CCS-packed (see dft for details). -@param a first input array. -@param b second input array of the same size and type as src1 . -@param c output array of the same size and type as src1 . -@param flags operation flags; currently, the only supported flag is cv::DFT_ROWS, which indicates that -each row of src1 and src2 is an independent 1D Fourier spectrum. If you do not want to use this flag, then simply add a `0` as value. -@param conjB optional flag that conjugates the second input array before the multiplication (true) -or not (false). -*/ -CV_EXPORTS_W void mulSpectrums(InputArray a, InputArray b, OutputArray c, - int flags, bool conjB = false); - -/** @brief Returns the optimal DFT size for a given vector size. - -DFT performance is not a monotonic function of a vector size. Therefore, when you calculate -convolution of two arrays or perform the spectral analysis of an array, it usually makes sense to -pad the input data with zeros to get a bit larger array that can be transformed much faster than the -original one. Arrays whose size is a power-of-two (2, 4, 8, 16, 32, ...) are the fastest to process. -Though, the arrays whose size is a product of 2's, 3's, and 5's (for example, 300 = 5\*5\*3\*2\*2) -are also processed quite efficiently. - -The function cv::getOptimalDFTSize returns the minimum number N that is greater than or equal to vecsize -so that the DFT of a vector of size N can be processed efficiently. In the current implementation N -= 2 ^p^ \* 3 ^q^ \* 5 ^r^ for some integer p, q, r. - -The function returns a negative number if vecsize is too large (very close to INT_MAX ). - -While the function cannot be used directly to estimate the optimal vector size for DCT transform -(since the current DCT implementation supports only even-size vectors), it can be easily processed -as getOptimalDFTSize((vecsize+1)/2)\*2. -@param vecsize vector size. -@sa dft, dct, idft, idct, mulSpectrums -*/ -CV_EXPORTS_W int getOptimalDFTSize(int vecsize); - -/** @brief Returns the default random number generator. - -The function cv::theRNG returns the default random number generator. For each thread, there is a -separate random number generator, so you can use the function safely in multi-thread environments. -If you just need to get a single random number using this generator or initialize an array, you can -use randu or randn instead. But if you are going to generate many random numbers inside a loop, it -is much faster to use this function to retrieve the generator and then use RNG::operator _Tp() . -@sa RNG, randu, randn -*/ -CV_EXPORTS RNG& theRNG(); - -/** @brief Sets state of default random number generator. - -The function cv::setRNGSeed sets state of default random number generator to custom value. -@param seed new state for default random number generator -@sa RNG, randu, randn -*/ -CV_EXPORTS_W void setRNGSeed(int seed); - -/** @brief Generates a single uniformly-distributed random number or an array of random numbers. - -Non-template variant of the function fills the matrix dst with uniformly-distributed -random numbers from the specified range: -\f[\texttt{low} _c \leq \texttt{dst} (I)_c < \texttt{high} _c\f] -@param dst output array of random numbers; the array must be pre-allocated. -@param low inclusive lower boundary of the generated random numbers. -@param high exclusive upper boundary of the generated random numbers. -@sa RNG, randn, theRNG -*/ -CV_EXPORTS_W void randu(InputOutputArray dst, InputArray low, InputArray high); - -/** @brief Fills the array with normally distributed random numbers. - -The function cv::randn fills the matrix dst with normally distributed random numbers with the specified -mean vector and the standard deviation matrix. The generated random numbers are clipped to fit the -value range of the output array data type. -@param dst output array of random numbers; the array must be pre-allocated and have 1 to 4 channels. -@param mean mean value (expectation) of the generated random numbers. -@param stddev standard deviation of the generated random numbers; it can be either a vector (in -which case a diagonal standard deviation matrix is assumed) or a square matrix. -@sa RNG, randu -*/ -CV_EXPORTS_W void randn(InputOutputArray dst, InputArray mean, InputArray stddev); - -/** @brief Shuffles the array elements randomly. - -The function cv::randShuffle shuffles the specified 1D array by randomly choosing pairs of elements and -swapping them. The number of such swap operations will be dst.rows\*dst.cols\*iterFactor . -@param dst input/output numerical 1D array. -@param iterFactor scale factor that determines the number of random swap operations (see the details -below). -@param rng optional random number generator used for shuffling; if it is zero, theRNG () is used -instead. -@sa RNG, sort -*/ -CV_EXPORTS_W void randShuffle(InputOutputArray dst, double iterFactor = 1., RNG* rng = 0); - -/** @brief Principal Component Analysis - -The class is used to calculate a special basis for a set of vectors. The -basis will consist of eigenvectors of the covariance matrix calculated -from the input set of vectors. The class %PCA can also transform -vectors to/from the new coordinate space defined by the basis. Usually, -in this new coordinate system, each vector from the original set (and -any linear combination of such vectors) can be quite accurately -approximated by taking its first few components, corresponding to the -eigenvectors of the largest eigenvalues of the covariance matrix. -Geometrically it means that you calculate a projection of the vector to -a subspace formed by a few eigenvectors corresponding to the dominant -eigenvalues of the covariance matrix. And usually such a projection is -very close to the original vector. So, you can represent the original -vector from a high-dimensional space with a much shorter vector -consisting of the projected vector's coordinates in the subspace. Such a -transformation is also known as Karhunen-Loeve Transform, or KLT. -See http://en.wikipedia.org/wiki/Principal_component_analysis - -The sample below is the function that takes two matrices. The first -function stores a set of vectors (a row per vector) that is used to -calculate PCA. The second function stores another "test" set of vectors -(a row per vector). First, these vectors are compressed with PCA, then -reconstructed back, and then the reconstruction error norm is computed -and printed for each vector. : - -@code{.cpp} -using namespace cv; - -PCA compressPCA(const Mat& pcaset, int maxComponents, - const Mat& testset, Mat& compressed) -{ - PCA pca(pcaset, // pass the data - Mat(), // we do not have a pre-computed mean vector, - // so let the PCA engine to compute it - PCA::DATA_AS_ROW, // indicate that the vectors - // are stored as matrix rows - // (use PCA::DATA_AS_COL if the vectors are - // the matrix columns) - maxComponents // specify, how many principal components to retain - ); - // if there is no test data, just return the computed basis, ready-to-use - if( !testset.data ) - return pca; - CV_Assert( testset.cols == pcaset.cols ); - - compressed.create(testset.rows, maxComponents, testset.type()); - - Mat reconstructed; - for( int i = 0; i < testset.rows; i++ ) - { - Mat vec = testset.row(i), coeffs = compressed.row(i), reconstructed; - // compress the vector, the result will be stored - // in the i-th row of the output matrix - pca.project(vec, coeffs); - // and then reconstruct it - pca.backProject(coeffs, reconstructed); - // and measure the error - printf("%d. diff = %g\n", i, norm(vec, reconstructed, NORM_L2)); - } - return pca; -} -@endcode -@sa calcCovarMatrix, mulTransposed, SVD, dft, dct -*/ -class CV_EXPORTS PCA -{ -public: - enum Flags { DATA_AS_ROW = 0, //!< indicates that the input samples are stored as matrix rows - DATA_AS_COL = 1, //!< indicates that the input samples are stored as matrix columns - USE_AVG = 2 //! - }; - - /** @brief default constructor - - The default constructor initializes an empty %PCA structure. The other - constructors initialize the structure and call PCA::operator()(). - */ - PCA(); - - /** @overload - @param data input samples stored as matrix rows or matrix columns. - @param mean optional mean value; if the matrix is empty (@c noArray()), - the mean is computed from the data. - @param flags operation flags; currently the parameter is only used to - specify the data layout (PCA::Flags) - @param maxComponents maximum number of components that %PCA should - retain; by default, all the components are retained. - */ - PCA(InputArray data, InputArray mean, int flags, int maxComponents = 0); - - /** @overload - @param data input samples stored as matrix rows or matrix columns. - @param mean optional mean value; if the matrix is empty (noArray()), - the mean is computed from the data. - @param flags operation flags; currently the parameter is only used to - specify the data layout (PCA::Flags) - @param retainedVariance Percentage of variance that PCA should retain. - Using this parameter will let the PCA decided how many components to - retain but it will always keep at least 2. - */ - PCA(InputArray data, InputArray mean, int flags, double retainedVariance); - - /** @brief performs %PCA - - The operator performs %PCA of the supplied dataset. It is safe to reuse - the same PCA structure for multiple datasets. That is, if the structure - has been previously used with another dataset, the existing internal - data is reclaimed and the new @ref eigenvalues, @ref eigenvectors and @ref - mean are allocated and computed. - - The computed @ref eigenvalues are sorted from the largest to the smallest and - the corresponding @ref eigenvectors are stored as eigenvectors rows. - - @param data input samples stored as the matrix rows or as the matrix - columns. - @param mean optional mean value; if the matrix is empty (noArray()), - the mean is computed from the data. - @param flags operation flags; currently the parameter is only used to - specify the data layout. (Flags) - @param maxComponents maximum number of components that PCA should - retain; by default, all the components are retained. - */ - PCA& operator()(InputArray data, InputArray mean, int flags, int maxComponents = 0); - - /** @overload - @param data input samples stored as the matrix rows or as the matrix - columns. - @param mean optional mean value; if the matrix is empty (noArray()), - the mean is computed from the data. - @param flags operation flags; currently the parameter is only used to - specify the data layout. (PCA::Flags) - @param retainedVariance Percentage of variance that %PCA should retain. - Using this parameter will let the %PCA decided how many components to - retain but it will always keep at least 2. - */ - PCA& operator()(InputArray data, InputArray mean, int flags, double retainedVariance); - - /** @brief Projects vector(s) to the principal component subspace. - - The methods project one or more vectors to the principal component - subspace, where each vector projection is represented by coefficients in - the principal component basis. The first form of the method returns the - matrix that the second form writes to the result. So the first form can - be used as a part of expression while the second form can be more - efficient in a processing loop. - @param vec input vector(s); must have the same dimensionality and the - same layout as the input data used at %PCA phase, that is, if - DATA_AS_ROW are specified, then `vec.cols==data.cols` - (vector dimensionality) and `vec.rows` is the number of vectors to - project, and the same is true for the PCA::DATA_AS_COL case. - */ - Mat project(InputArray vec) const; - - /** @overload - @param vec input vector(s); must have the same dimensionality and the - same layout as the input data used at PCA phase, that is, if - DATA_AS_ROW are specified, then `vec.cols==data.cols` - (vector dimensionality) and `vec.rows` is the number of vectors to - project, and the same is true for the PCA::DATA_AS_COL case. - @param result output vectors; in case of PCA::DATA_AS_COL, the - output matrix has as many columns as the number of input vectors, this - means that `result.cols==vec.cols` and the number of rows match the - number of principal components (for example, `maxComponents` parameter - passed to the constructor). - */ - void project(InputArray vec, OutputArray result) const; - - /** @brief Reconstructs vectors from their PC projections. - - The methods are inverse operations to PCA::project. They take PC - coordinates of projected vectors and reconstruct the original vectors. - Unless all the principal components have been retained, the - reconstructed vectors are different from the originals. But typically, - the difference is small if the number of components is large enough (but - still much smaller than the original vector dimensionality). As a - result, PCA is used. - @param vec coordinates of the vectors in the principal component - subspace, the layout and size are the same as of PCA::project output - vectors. - */ - Mat backProject(InputArray vec) const; - - /** @overload - @param vec coordinates of the vectors in the principal component - subspace, the layout and size are the same as of PCA::project output - vectors. - @param result reconstructed vectors; the layout and size are the same as - of PCA::project input vectors. - */ - void backProject(InputArray vec, OutputArray result) const; - - /** @brief write PCA objects - - Writes @ref eigenvalues @ref eigenvectors and @ref mean to specified FileStorage - */ - void write(FileStorage& fs) const; - - /** @brief load PCA objects - - Loads @ref eigenvalues @ref eigenvectors and @ref mean from specified FileNode - */ - void read(const FileNode& fn); - - Mat eigenvectors; //!< eigenvectors of the covariation matrix - Mat eigenvalues; //!< eigenvalues of the covariation matrix - Mat mean; //!< mean value subtracted before the projection and added after the back projection -}; - -/** @example samples/cpp/pca.cpp -An example using %PCA for dimensionality reduction while maintaining an amount of variance -*/ - -/** @example samples/cpp/tutorial_code/ml/introduction_to_pca/introduction_to_pca.cpp -Check @ref tutorial_introduction_to_pca "the corresponding tutorial" for more details -*/ - -/** -@brief Linear Discriminant Analysis -@todo document this class -*/ -class CV_EXPORTS LDA -{ -public: - /** @brief constructor - Initializes a LDA with num_components (default 0). - */ - explicit LDA(int num_components = 0); - - /** Initializes and performs a Discriminant Analysis with Fisher's - Optimization Criterion on given data in src and corresponding labels - in labels. If 0 (or less) number of components are given, they are - automatically determined for given data in computation. - */ - LDA(InputArrayOfArrays src, InputArray labels, int num_components = 0); - - /** Serializes this object to a given filename. - */ - void save(const String& filename) const; - - /** Deserializes this object from a given filename. - */ - void load(const String& filename); - - /** Serializes this object to a given cv::FileStorage. - */ - void save(FileStorage& fs) const; - - /** Deserializes this object from a given cv::FileStorage. - */ - void load(const FileStorage& node); - - /** destructor - */ - ~LDA(); - - /** Compute the discriminants for data in src (row aligned) and labels. - */ - void compute(InputArrayOfArrays src, InputArray labels); - - /** Projects samples into the LDA subspace. - src may be one or more row aligned samples. - */ - Mat project(InputArray src); - - /** Reconstructs projections from the LDA subspace. - src may be one or more row aligned projections. - */ - Mat reconstruct(InputArray src); - - /** Returns the eigenvectors of this LDA. - */ - Mat eigenvectors() const { return _eigenvectors; } - - /** Returns the eigenvalues of this LDA. - */ - Mat eigenvalues() const { return _eigenvalues; } - - static Mat subspaceProject(InputArray W, InputArray mean, InputArray src); - static Mat subspaceReconstruct(InputArray W, InputArray mean, InputArray src); - -protected: - int _num_components; - Mat _eigenvectors; - Mat _eigenvalues; - void lda(InputArrayOfArrays src, InputArray labels); -}; - -/** @brief Singular Value Decomposition - -Class for computing Singular Value Decomposition of a floating-point -matrix. The Singular Value Decomposition is used to solve least-square -problems, under-determined linear systems, invert matrices, compute -condition numbers, and so on. - -If you want to compute a condition number of a matrix or an absolute value of -its determinant, you do not need `u` and `vt`. You can pass -flags=SVD::NO_UV|... . Another flag SVD::FULL_UV indicates that full-size u -and vt must be computed, which is not necessary most of the time. - -@sa invert, solve, eigen, determinant -*/ -class CV_EXPORTS SVD -{ -public: - enum Flags { - /** allow the algorithm to modify the decomposed matrix; it can save space and speed up - processing. currently ignored. */ - MODIFY_A = 1, - /** indicates that only a vector of singular values `w` is to be processed, while u and vt - will be set to empty matrices */ - NO_UV = 2, - /** when the matrix is not square, by default the algorithm produces u and vt matrices of - sufficiently large size for the further A reconstruction; if, however, FULL_UV flag is - specified, u and vt will be full-size square orthogonal matrices.*/ - FULL_UV = 4 - }; - - /** @brief the default constructor - - initializes an empty SVD structure - */ - SVD(); - - /** @overload - initializes an empty SVD structure and then calls SVD::operator() - @param src decomposed matrix. The depth has to be CV_32F or CV_64F. - @param flags operation flags (SVD::Flags) - */ - SVD( InputArray src, int flags = 0 ); - - /** @brief the operator that performs SVD. The previously allocated u, w and vt are released. - - The operator performs the singular value decomposition of the supplied - matrix. The u,`vt` , and the vector of singular values w are stored in - the structure. The same SVD structure can be reused many times with - different matrices. Each time, if needed, the previous u,`vt` , and w - are reclaimed and the new matrices are created, which is all handled by - Mat::create. - @param src decomposed matrix. The depth has to be CV_32F or CV_64F. - @param flags operation flags (SVD::Flags) - */ - SVD& operator ()( InputArray src, int flags = 0 ); - - /** @brief decomposes matrix and stores the results to user-provided matrices - - The methods/functions perform SVD of matrix. Unlike SVD::SVD constructor - and SVD::operator(), they store the results to the user-provided - matrices: - - @code{.cpp} - Mat A, w, u, vt; - SVD::compute(A, w, u, vt); - @endcode - - @param src decomposed matrix. The depth has to be CV_32F or CV_64F. - @param w calculated singular values - @param u calculated left singular vectors - @param vt transposed matrix of right singular vectors - @param flags operation flags - see SVD::Flags. - */ - static void compute( InputArray src, OutputArray w, - OutputArray u, OutputArray vt, int flags = 0 ); - - /** @overload - computes singular values of a matrix - @param src decomposed matrix. The depth has to be CV_32F or CV_64F. - @param w calculated singular values - @param flags operation flags - see SVD::Flags. - */ - static void compute( InputArray src, OutputArray w, int flags = 0 ); - - /** @brief performs back substitution - */ - static void backSubst( InputArray w, InputArray u, - InputArray vt, InputArray rhs, - OutputArray dst ); - - /** @brief solves an under-determined singular linear system - - The method finds a unit-length solution x of a singular linear system - A\*x = 0. Depending on the rank of A, there can be no solutions, a - single solution or an infinite number of solutions. In general, the - algorithm solves the following problem: - \f[dst = \arg \min _{x: \| x \| =1} \| src \cdot x \|\f] - @param src left-hand-side matrix. - @param dst found solution. - */ - static void solveZ( InputArray src, OutputArray dst ); - - /** @brief performs a singular value back substitution. - - The method calculates a back substitution for the specified right-hand - side: - - \f[\texttt{x} = \texttt{vt} ^T \cdot diag( \texttt{w} )^{-1} \cdot \texttt{u} ^T \cdot \texttt{rhs} \sim \texttt{A} ^{-1} \cdot \texttt{rhs}\f] - - Using this technique you can either get a very accurate solution of the - convenient linear system, or the best (in the least-squares terms) - pseudo-solution of an overdetermined linear system. - - @param rhs right-hand side of a linear system (u\*w\*v')\*dst = rhs to - be solved, where A has been previously decomposed. - - @param dst found solution of the system. - - @note Explicit SVD with the further back substitution only makes sense - if you need to solve many linear systems with the same left-hand side - (for example, src ). If all you need is to solve a single system - (possibly with multiple rhs immediately available), simply call solve - add pass #DECOMP_SVD there. It does absolutely the same thing. - */ - void backSubst( InputArray rhs, OutputArray dst ) const; - - /** @todo document */ - template static - void compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt ); - - /** @todo document */ - template static - void compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w ); - - /** @todo document */ - template static - void backSubst( const Matx<_Tp, nm, 1>& w, const Matx<_Tp, m, nm>& u, const Matx<_Tp, n, nm>& vt, const Matx<_Tp, m, nb>& rhs, Matx<_Tp, n, nb>& dst ); - - Mat u, w, vt; -}; - -/** @brief Random Number Generator - -Random number generator. It encapsulates the state (currently, a 64-bit -integer) and has methods to return scalar random values and to fill -arrays with random values. Currently it supports uniform and Gaussian -(normal) distributions. The generator uses Multiply-With-Carry -algorithm, introduced by G. Marsaglia ( - ). -Gaussian-distribution random numbers are generated using the Ziggurat -algorithm ( ), -introduced by G. Marsaglia and W. W. Tsang. -*/ -class CV_EXPORTS RNG -{ -public: - enum { UNIFORM = 0, - NORMAL = 1 - }; - - /** @brief constructor - - These are the RNG constructors. The first form sets the state to some - pre-defined value, equal to 2\*\*32-1 in the current implementation. The - second form sets the state to the specified value. If you passed state=0 - , the constructor uses the above default value instead to avoid the - singular random number sequence, consisting of all zeros. - */ - RNG(); - /** @overload - @param state 64-bit value used to initialize the RNG. - */ - RNG(uint64 state); - /**The method updates the state using the MWC algorithm and returns the - next 32-bit random number.*/ - unsigned next(); - - /**Each of the methods updates the state using the MWC algorithm and - returns the next random number of the specified type. In case of integer - types, the returned number is from the available value range for the - specified type. In case of floating-point types, the returned value is - from [0,1) range. - */ - operator uchar(); - /** @overload */ - operator schar(); - /** @overload */ - operator ushort(); - /** @overload */ - operator short(); - /** @overload */ - operator unsigned(); - /** @overload */ - operator int(); - /** @overload */ - operator float(); - /** @overload */ - operator double(); - - /** @brief returns a random integer sampled uniformly from [0, N). - - The methods transform the state using the MWC algorithm and return the - next random number. The first form is equivalent to RNG::next . The - second form returns the random number modulo N, which means that the - result is in the range [0, N) . - */ - unsigned operator ()(); - /** @overload - @param N upper non-inclusive boundary of the returned random number. - */ - unsigned operator ()(unsigned N); - - /** @brief returns uniformly distributed integer random number from [a,b) range - - The methods transform the state using the MWC algorithm and return the - next uniformly-distributed random number of the specified type, deduced - from the input parameter type, from the range [a, b) . There is a nuance - illustrated by the following sample: - - @code{.cpp} - RNG rng; - - // always produces 0 - double a = rng.uniform(0, 1); - - // produces double from [0, 1) - double a1 = rng.uniform((double)0, (double)1); - - // produces float from [0, 1) - float b = rng.uniform(0.f, 1.f); - - // produces double from [0, 1) - double c = rng.uniform(0., 1.); - - // may cause compiler error because of ambiguity: - // RNG::uniform(0, (int)0.999999)? or RNG::uniform((double)0, 0.99999)? - double d = rng.uniform(0, 0.999999); - @endcode - - The compiler does not take into account the type of the variable to - which you assign the result of RNG::uniform . The only thing that - matters to the compiler is the type of a and b parameters. So, if you - want a floating-point random number, but the range boundaries are - integer numbers, either put dots in the end, if they are constants, or - use explicit type cast operators, as in the a1 initialization above. - @param a lower inclusive boundary of the returned random number. - @param b upper non-inclusive boundary of the returned random number. - */ - int uniform(int a, int b); - /** @overload */ - float uniform(float a, float b); - /** @overload */ - double uniform(double a, double b); - - /** @brief Fills arrays with random numbers. - - @param mat 2D or N-dimensional matrix; currently matrices with more than - 4 channels are not supported by the methods, use Mat::reshape as a - possible workaround. - @param distType distribution type, RNG::UNIFORM or RNG::NORMAL. - @param a first distribution parameter; in case of the uniform - distribution, this is an inclusive lower boundary, in case of the normal - distribution, this is a mean value. - @param b second distribution parameter; in case of the uniform - distribution, this is a non-inclusive upper boundary, in case of the - normal distribution, this is a standard deviation (diagonal of the - standard deviation matrix or the full standard deviation matrix). - @param saturateRange pre-saturation flag; for uniform distribution only; - if true, the method will first convert a and b to the acceptable value - range (according to the mat datatype) and then will generate uniformly - distributed random numbers within the range [saturate(a), saturate(b)), - if saturateRange=false, the method will generate uniformly distributed - random numbers in the original range [a, b) and then will saturate them, - it means, for example, that - theRNG().fill(mat_8u, RNG::UNIFORM, -DBL_MAX, DBL_MAX) will likely - produce array mostly filled with 0's and 255's, since the range (0, 255) - is significantly smaller than [-DBL_MAX, DBL_MAX). - - Each of the methods fills the matrix with the random values from the - specified distribution. As the new numbers are generated, the RNG state - is updated accordingly. In case of multiple-channel images, every - channel is filled independently, which means that RNG cannot generate - samples from the multi-dimensional Gaussian distribution with - non-diagonal covariance matrix directly. To do that, the method - generates samples from multi-dimensional standard Gaussian distribution - with zero mean and identity covariation matrix, and then transforms them - using transform to get samples from the specified Gaussian distribution. - */ - void fill( InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange = false ); - - /** @brief Returns the next random number sampled from the Gaussian distribution - @param sigma standard deviation of the distribution. - - The method transforms the state using the MWC algorithm and returns the - next random number from the Gaussian distribution N(0,sigma) . That is, - the mean value of the returned random numbers is zero and the standard - deviation is the specified sigma . - */ - double gaussian(double sigma); - - uint64 state; - - bool operator ==(const RNG& other) const; -}; - -/** @brief Mersenne Twister random number generator - -Inspired by http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c -@todo document -*/ -class CV_EXPORTS RNG_MT19937 -{ -public: - RNG_MT19937(); - RNG_MT19937(unsigned s); - void seed(unsigned s); - - unsigned next(); - - operator int(); - operator unsigned(); - operator float(); - operator double(); - - unsigned operator ()(unsigned N); - unsigned operator ()(); - - /** @brief returns uniformly distributed integer random number from [a,b) range*/ - int uniform(int a, int b); - /** @brief returns uniformly distributed floating-point random number from [a,b) range*/ - float uniform(float a, float b); - /** @brief returns uniformly distributed double-precision floating-point random number from [a,b) range*/ - double uniform(double a, double b); - -private: - enum PeriodParameters {N = 624, M = 397}; - unsigned state[N]; - int mti; -}; - -//! @} core_array - -//! @addtogroup core_cluster -//! @{ - -//! k-means flags -enum KmeansFlags { - /** Select random initial centers in each attempt.*/ - KMEANS_RANDOM_CENTERS = 0, - /** Use kmeans++ center initialization by Arthur and Vassilvitskii [Arthur2007].*/ - KMEANS_PP_CENTERS = 2, - /** During the first (and possibly the only) attempt, use the - user-supplied labels instead of computing them from the initial centers. For the second and - further attempts, use the random or semi-random centers. Use one of KMEANS_\*_CENTERS flag - to specify the exact method.*/ - KMEANS_USE_INITIAL_LABELS = 1 -}; - -/** @example samples/cpp/kmeans.cpp -An example on k-means clustering -*/ - -/** @brief Finds centers of clusters and groups input samples around the clusters. - -The function kmeans implements a k-means algorithm that finds the centers of cluster_count clusters -and groups the input samples around the clusters. As an output, \f$\texttt{bestLabels}_i\f$ contains a -0-based cluster index for the sample stored in the \f$i^{th}\f$ row of the samples matrix. - -@note -- (Python) An example on k-means clustering can be found at - opencv_source_code/samples/python/kmeans.py -@param data Data for clustering. An array of N-Dimensional points with float coordinates is needed. -Examples of this array can be: -- Mat points(count, 2, CV_32F); -- Mat points(count, 1, CV_32FC2); -- Mat points(1, count, CV_32FC2); -- std::vector\ points(sampleCount); -@param K Number of clusters to split the set by. -@param bestLabels Input/output integer array that stores the cluster indices for every sample. -@param criteria The algorithm termination criteria, that is, the maximum number of iterations and/or -the desired accuracy. The accuracy is specified as criteria.epsilon. As soon as each of the cluster -centers moves by less than criteria.epsilon on some iteration, the algorithm stops. -@param attempts Flag to specify the number of times the algorithm is executed using different -initial labellings. The algorithm returns the labels that yield the best compactness (see the last -function parameter). -@param flags Flag that can take values of cv::KmeansFlags -@param centers Output matrix of the cluster centers, one row per each cluster center. -@return The function returns the compactness measure that is computed as -\f[\sum _i \| \texttt{samples} _i - \texttt{centers} _{ \texttt{labels} _i} \| ^2\f] -after every attempt. The best (minimum) value is chosen and the corresponding labels and the -compactness value are returned by the function. Basically, you can use only the core of the -function, set the number of attempts to 1, initialize labels each time using a custom algorithm, -pass them with the ( flags = #KMEANS_USE_INITIAL_LABELS ) flag, and then choose the best -(most-compact) clustering. -*/ -CV_EXPORTS_W double kmeans( InputArray data, int K, InputOutputArray bestLabels, - TermCriteria criteria, int attempts, - int flags, OutputArray centers = noArray() ); - -//! @} core_cluster - -//! @addtogroup core_basic -//! @{ - -/////////////////////////////// Formatted output of cv::Mat /////////////////////////// - -/** @todo document */ -class CV_EXPORTS Formatted -{ -public: - virtual const char* next() = 0; - virtual void reset() = 0; - virtual ~Formatted(); -}; - -/** @todo document */ -class CV_EXPORTS Formatter -{ -public: - enum FormatType { - FMT_DEFAULT = 0, - FMT_MATLAB = 1, - FMT_CSV = 2, - FMT_PYTHON = 3, - FMT_NUMPY = 4, - FMT_C = 5 - }; - - virtual ~Formatter(); - - virtual Ptr format(const Mat& mtx) const = 0; - - virtual void set16fPrecision(int p = 4) = 0; - virtual void set32fPrecision(int p = 8) = 0; - virtual void set64fPrecision(int p = 16) = 0; - virtual void setMultiline(bool ml = true) = 0; - - static Ptr get(Formatter::FormatType fmt = FMT_DEFAULT); - -}; - -static inline -String& operator << (String& out, Ptr fmtd) -{ - fmtd->reset(); - for(const char* str = fmtd->next(); str; str = fmtd->next()) - out += cv::String(str); - return out; -} - -static inline -String& operator << (String& out, const Mat& mtx) -{ - return out << Formatter::get()->format(mtx); -} - -//////////////////////////////////////// Algorithm //////////////////////////////////// - -class CV_EXPORTS Algorithm; - -template struct ParamType {}; - - -/** @brief This is a base class for all more or less complex algorithms in OpenCV - -especially for classes of algorithms, for which there can be multiple implementations. The examples -are stereo correspondence (for which there are algorithms like block matching, semi-global block -matching, graph-cut etc.), background subtraction (which can be done using mixture-of-gaussians -models, codebook-based algorithm etc.), optical flow (block matching, Lucas-Kanade, Horn-Schunck -etc.). - -Here is example of SimpleBlobDetector use in your application via Algorithm interface: -@snippet snippets/core_various.cpp Algorithm -*/ -class CV_EXPORTS_W Algorithm -{ -public: - Algorithm(); - virtual ~Algorithm(); - - /** @brief Clears the algorithm state - */ - CV_WRAP virtual void clear() {} - - /** @brief Stores algorithm parameters in a file storage - */ - CV_WRAP virtual void write(FileStorage& fs) const { CV_UNUSED(fs); } - - /** - * @overload - */ - CV_WRAP void write(FileStorage& fs, const String& name) const; -#if CV_VERSION_MAJOR < 5 - /** @deprecated */ - void write(const Ptr& fs, const String& name = String()) const; -#endif - - /** @brief Reads algorithm parameters from a file storage - */ - CV_WRAP virtual void read(const FileNode& fn) { CV_UNUSED(fn); } - - /** @brief Returns true if the Algorithm is empty (e.g. in the very beginning or after unsuccessful read - */ - CV_WRAP virtual bool empty() const { return false; } - - /** @brief Reads algorithm from the file node - - This is static template method of Algorithm. It's usage is following (in the case of SVM): - @code - cv::FileStorage fsRead("example.xml", FileStorage::READ); - Ptr svm = Algorithm::read(fsRead.root()); - @endcode - In order to make this method work, the derived class must overwrite Algorithm::read(const - FileNode& fn) and also have static create() method without parameters - (or with all the optional parameters) - */ - template static Ptr<_Tp> read(const FileNode& fn) - { - Ptr<_Tp> obj = _Tp::create(); - obj->read(fn); - return !obj->empty() ? obj : Ptr<_Tp>(); - } - - /** @brief Loads algorithm from the file - - @param filename Name of the file to read. - @param objname The optional name of the node to read (if empty, the first top-level node will be used) - - This is static template method of Algorithm. It's usage is following (in the case of SVM): - @code - Ptr svm = Algorithm::load("my_svm_model.xml"); - @endcode - In order to make this method work, the derived class must overwrite Algorithm::read(const - FileNode& fn). - */ - template static Ptr<_Tp> load(const String& filename, const String& objname=String()) - { - FileStorage fs(filename, FileStorage::READ); - CV_Assert(fs.isOpened()); - FileNode fn = objname.empty() ? fs.getFirstTopLevelNode() : fs[objname]; - if (fn.empty()) return Ptr<_Tp>(); - Ptr<_Tp> obj = _Tp::create(); - obj->read(fn); - return !obj->empty() ? obj : Ptr<_Tp>(); - } - - /** @brief Loads algorithm from a String - - @param strModel The string variable containing the model you want to load. - @param objname The optional name of the node to read (if empty, the first top-level node will be used) - - This is static template method of Algorithm. It's usage is following (in the case of SVM): - @code - Ptr svm = Algorithm::loadFromString(myStringModel); - @endcode - */ - template static Ptr<_Tp> loadFromString(const String& strModel, const String& objname=String()) - { - FileStorage fs(strModel, FileStorage::READ + FileStorage::MEMORY); - FileNode fn = objname.empty() ? fs.getFirstTopLevelNode() : fs[objname]; - Ptr<_Tp> obj = _Tp::create(); - obj->read(fn); - return !obj->empty() ? obj : Ptr<_Tp>(); - } - - /** Saves the algorithm to a file. - In order to make this method work, the derived class must implement Algorithm::write(FileStorage& fs). */ - CV_WRAP virtual void save(const String& filename) const; - - /** Returns the algorithm string identifier. - This string is used as top level xml/yml node tag when the object is saved to a file or string. */ - CV_WRAP virtual String getDefaultName() const; - -protected: - void writeFormat(FileStorage& fs) const; -}; - -enum struct Param { - INT=0, BOOLEAN=1, REAL=2, STRING=3, MAT=4, MAT_VECTOR=5, ALGORITHM=6, FLOAT=7, - UNSIGNED_INT=8, UINT64=9, UCHAR=11, SCALAR=12 -}; - - - -template<> struct ParamType -{ - typedef bool const_param_type; - typedef bool member_type; - - static const Param type = Param::BOOLEAN; -}; - -template<> struct ParamType -{ - typedef int const_param_type; - typedef int member_type; - - static const Param type = Param::INT; -}; - -template<> struct ParamType -{ - typedef double const_param_type; - typedef double member_type; - - static const Param type = Param::REAL; -}; - -template<> struct ParamType -{ - typedef const String& const_param_type; - typedef String member_type; - - static const Param type = Param::STRING; -}; - -template<> struct ParamType -{ - typedef const Mat& const_param_type; - typedef Mat member_type; - - static const Param type = Param::MAT; -}; - -template<> struct ParamType > -{ - typedef const std::vector& const_param_type; - typedef std::vector member_type; - - static const Param type = Param::MAT_VECTOR; -}; - -template<> struct ParamType -{ - typedef const Ptr& const_param_type; - typedef Ptr member_type; - - static const Param type = Param::ALGORITHM; -}; - -template<> struct ParamType -{ - typedef float const_param_type; - typedef float member_type; - - static const Param type = Param::FLOAT; -}; - -template<> struct ParamType -{ - typedef unsigned const_param_type; - typedef unsigned member_type; - - static const Param type = Param::UNSIGNED_INT; -}; - -template<> struct ParamType -{ - typedef uint64 const_param_type; - typedef uint64 member_type; - - static const Param type = Param::UINT64; -}; - -template<> struct ParamType -{ - typedef uchar const_param_type; - typedef uchar member_type; - - static const Param type = Param::UCHAR; -}; - -template<> struct ParamType -{ - typedef const Scalar& const_param_type; - typedef Scalar member_type; - - static const Param type = Param::SCALAR; -}; - -template -struct ParamType<_Tp, typename std::enable_if< std::is_enum<_Tp>::value >::type> -{ - typedef typename std::underlying_type<_Tp>::type const_param_type; - typedef typename std::underlying_type<_Tp>::type member_type; - - static const Param type = Param::INT; -}; - -//! @} core_basic - -} //namespace cv - -#include "opencv2/core/operations.hpp" -#include "opencv2/core/cvstd.inl.hpp" -#include "opencv2/core/utility.hpp" -#include "opencv2/core/optim.hpp" -#include "opencv2/core/ovx.hpp" - -#endif /*OPENCV_CORE_HPP*/ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2015, Intel Corporation, all rights reserved. +// Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved. +// Copyright (C) 2015, OpenCV Foundation, all rights reserved. +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CORE_HPP +#define OPENCV_CORE_HPP + +#ifndef __cplusplus +# error core.hpp header must be compiled as C++ +#endif + +#include "opencv2/core/cvdef.h" +#include "opencv2/core/base.hpp" +#include "opencv2/core/cvstd.hpp" +#include "opencv2/core/traits.hpp" +#include "opencv2/core/matx.hpp" +#include "opencv2/core/types.hpp" +#include "opencv2/core/mat.hpp" +#include "opencv2/core/persistence.hpp" + +/** +@defgroup core Core functionality + +The Core module is the backbone of OpenCV, offering fundamental data structures, matrix operations, +and utility functions that other modules depend on. It’s essential for handling image data, +performing mathematical computations, and managing memory efficiently within the OpenCV ecosystem. + +@{ + @defgroup core_basic Basic structures + @defgroup core_array Operations on arrays + @defgroup core_async Asynchronous API + @defgroup core_xml XML/YAML/JSON Persistence + @defgroup core_cluster Clustering + @defgroup core_utils Utility and system functions and macros + @{ + @defgroup core_logging Logging facilities + @defgroup core_utils_sse SSE utilities + @defgroup core_utils_neon NEON utilities + @defgroup core_utils_vsx VSX utilities + @defgroup core_utils_softfloat Softfloat support + @defgroup core_utils_samples Utility functions for OpenCV samples + @} + @defgroup core_opengl OpenGL interoperability + @defgroup core_optim Optimization Algorithms + @defgroup core_directx DirectX interoperability + @defgroup core_eigen Eigen support + @defgroup core_opencl OpenCL support + @defgroup core_va_intel Intel VA-API/OpenCL (CL-VA) interoperability + @defgroup core_hal Hardware Acceleration Layer + @{ + @defgroup core_hal_functions Functions + @defgroup core_hal_interface Interface + @defgroup core_hal_intrin Universal intrinsics + @{ + @defgroup core_hal_intrin_impl Private implementation helpers + @} + @defgroup core_lowlevel_api Low-level API for external libraries / plugins + @} + @defgroup core_parallel Parallel Processing + @{ + @defgroup core_parallel_backend Parallel backends API + @} + @defgroup core_quaternion Quaternion +@} + */ + +namespace cv { + +//! @addtogroup core_utils +//! @{ + +/*! @brief Class passed to an error. + +This class encapsulates all or almost all necessary +information about the error happened in the program. The exception is +usually constructed and thrown implicitly via CV_Error and CV_Error_ macros. +@see error + */ +class CV_EXPORTS Exception : public std::exception +{ +public: + /*! + Default constructor + */ + Exception(); + /*! + Full constructor. Normally the constructor is not called explicitly. + Instead, the macros CV_Error(), CV_Error_() and CV_Assert() are used. + */ + Exception(int _code, const String& _err, const String& _func, const String& _file, int _line); + virtual ~Exception() CV_NOEXCEPT; + + /*! + \return the error description and the context as a text string. + */ + virtual const char *what() const CV_NOEXCEPT CV_OVERRIDE; + void formatMessage(); + + String msg; ///< the formatted error message + + int code; ///< error code @see CVStatus + String err; ///< error description + String func; ///< function name. Available only when the compiler supports getting it + String file; ///< source file name where the error has occurred + int line; ///< line number in the source file where the error has occurred +}; + +/*! @brief Signals an error and raises the exception. + +By default the function prints information about the error to stderr, +then it either stops if cv::setBreakOnError() had been called before or raises the exception. +It is possible to alternate error processing by using #redirectError(). +@param exc the exception raisen. +@deprecated drop this version + */ +CV_EXPORTS CV_NORETURN void error(const Exception& exc); + +enum SortFlags { SORT_EVERY_ROW = 0, //!< each matrix row is sorted independently + SORT_EVERY_COLUMN = 1, //!< each matrix column is sorted + //!< independently; this flag and the previous one are + //!< mutually exclusive. + SORT_ASCENDING = 0, //!< each matrix row is sorted in the ascending + //!< order. + SORT_DESCENDING = 16 //!< each matrix row is sorted in the + //!< descending order; this flag and the previous one are also + //!< mutually exclusive. + }; + +//! @} core_utils + +//! @addtogroup core_array +//! @{ + +//! Covariation flags +enum CovarFlags { + /** The output covariance matrix is calculated as: + \f[\texttt{scale} \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...]^T \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...],\f] + The covariance matrix will be nsamples x nsamples. Such an unusual covariance matrix is used + for fast PCA of a set of very large vectors (see, for example, the EigenFaces technique for + face recognition). Eigenvalues of this "scrambled" matrix match the eigenvalues of the true + covariance matrix. The "true" eigenvectors can be easily calculated from the eigenvectors of + the "scrambled" covariance matrix. */ + COVAR_SCRAMBLED = 0, + /**The output covariance matrix is calculated as: + \f[\texttt{scale} \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...] \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...]^T,\f] + covar will be a square matrix of the same size as the total number of elements in each input + vector. One and only one of #COVAR_SCRAMBLED and #COVAR_NORMAL must be specified.*/ + COVAR_NORMAL = 1, + /** If the flag is specified, the function does not calculate mean from + the input vectors but, instead, uses the passed mean vector. This is useful if mean has been + pre-calculated or known in advance, or if the covariance matrix is calculated by parts. In + this case, mean is not a mean vector of the input sub-set of vectors but rather the mean + vector of the whole set.*/ + COVAR_USE_AVG = 2, + /** If the flag is specified, the covariance matrix is scaled. In the + "normal" mode, scale is 1./nsamples . In the "scrambled" mode, scale is the reciprocal of the + total number of elements in each input vector. By default (if the flag is not specified), the + covariance matrix is not scaled ( scale=1 ).*/ + COVAR_SCALE = 4, + /** If the flag is + specified, all the input vectors are stored as rows of the samples matrix. mean should be a + single-row vector in this case.*/ + COVAR_ROWS = 8, + /** If the flag is + specified, all the input vectors are stored as columns of the samples matrix. mean should be a + single-column vector in this case.*/ + COVAR_COLS = 16 +}; + +enum ReduceTypes { REDUCE_SUM = 0, //!< the output is the sum of all rows/columns of the matrix. + REDUCE_AVG = 1, //!< the output is the mean vector of all rows/columns of the matrix. + REDUCE_MAX = 2, //!< the output is the maximum (column/row-wise) of all rows/columns of the matrix. + REDUCE_MIN = 3, //!< the output is the minimum (column/row-wise) of all rows/columns of the matrix. + REDUCE_SUM2 = 4 //!< the output is the sum of all squared rows/columns of the matrix. + }; + +/** @brief Swaps two matrices +*/ +CV_EXPORTS void swap(Mat& a, Mat& b); +/** @overload */ +CV_EXPORTS void swap( UMat& a, UMat& b ); + +/** @brief Computes the source location of an extrapolated pixel. + +The function computes and returns the coordinate of a donor pixel corresponding to the specified +extrapolated pixel when using the specified extrapolation border mode. For example, if you use +cv::BORDER_WRAP mode in the horizontal direction, cv::BORDER_REFLECT_101 in the vertical direction and +want to compute value of the "virtual" pixel Point(-5, 100) in a floating-point image img, it +looks like: +@code{.cpp} + float val = img.at(borderInterpolate(100, img.rows, cv::BORDER_REFLECT_101), + borderInterpolate(-5, img.cols, cv::BORDER_WRAP)); +@endcode +Normally, the function is not called directly. It is used inside filtering functions and also in +copyMakeBorder. +@param p 0-based coordinate of the extrapolated pixel along one of the axes, likely \<0 or \>= len +@param len Length of the array along the corresponding axis. +@param borderType Border type, one of the #BorderTypes, except for #BORDER_TRANSPARENT and +#BORDER_ISOLATED. When borderType==#BORDER_CONSTANT, the function always returns -1, regardless +of p and len. + +@sa copyMakeBorder +*/ +CV_EXPORTS_W int borderInterpolate(int p, int len, int borderType); + +/** @example samples/cpp/tutorial_code/ImgTrans/copyMakeBorder_demo.cpp +An example using copyMakeBorder function. +Check @ref tutorial_copyMakeBorder "the corresponding tutorial" for more details +*/ + +/** @brief Forms a border around an image. + +The function copies the source image into the middle of the destination image. The areas to the +left, to the right, above and below the copied source image will be filled with extrapolated +pixels. This is not what filtering functions based on it do (they extrapolate pixels on-fly), but +what other more complex functions, including your own, may do to simplify image boundary handling. + +The function supports the mode when src is already in the middle of dst . In this case, the +function does not copy src itself but simply constructs the border, for example: + +@code{.cpp} + // let border be the same in all directions + int border=2; + // constructs a larger image to fit both the image and the border + Mat gray_buf(rgb.rows + border*2, rgb.cols + border*2, rgb.depth()); + // select the middle part of it w/o copying data + Mat gray(gray_canvas, Rect(border, border, rgb.cols, rgb.rows)); + // convert image from RGB to grayscale + cvtColor(rgb, gray, COLOR_RGB2GRAY); + // form a border in-place + copyMakeBorder(gray, gray_buf, border, border, + border, border, BORDER_REPLICATE); + // now do some custom filtering ... + ... +@endcode +@note When the source image is a part (ROI) of a bigger image, the function will try to use the +pixels outside of the ROI to form a border. To disable this feature and always do extrapolation, as +if src was not a ROI, use borderType | #BORDER_ISOLATED. + +@param src Source image. +@param dst Destination image of the same type as src and the size Size(src.cols+left+right, +src.rows+top+bottom) . +@param top the top pixels +@param bottom the bottom pixels +@param left the left pixels +@param right Parameter specifying how many pixels in each direction from the source image rectangle +to extrapolate. For example, top=1, bottom=1, left=1, right=1 mean that 1 pixel-wide border needs +to be built. +@param borderType Border type. See borderInterpolate for details. +@param value Border value if borderType==BORDER_CONSTANT . + +@sa borderInterpolate +*/ +CV_EXPORTS_W void copyMakeBorder(InputArray src, OutputArray dst, + int top, int bottom, int left, int right, + int borderType, const Scalar& value = Scalar() ); + +/** @brief Calculates the per-element sum of two arrays or an array and a scalar. + +The function add calculates: +- Sum of two arrays when both input arrays have the same size and the same number of channels: +\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) + \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0\f] +- Sum of an array and a scalar when src2 is constructed from Scalar or has the same number of +elements as `src1.channels()`: +\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) + \texttt{src2} ) \quad \texttt{if mask}(I) \ne0\f] +- Sum of a scalar and an array when src1 is constructed from Scalar or has the same number of +elements as `src2.channels()`: +\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1} + \texttt{src2}(I) ) \quad \texttt{if mask}(I) \ne0\f] +where `I` is a multi-dimensional index of array elements. In case of multi-channel arrays, each +channel is processed independently. + +The first function in the list above can be replaced with matrix expressions: +@code{.cpp} + dst = src1 + src2; + dst += src1; // equivalent to add(dst, src1, dst); +@endcode +The input arrays and the output array can all have the same or different depths. For example, you +can add a 16-bit unsigned array to a 8-bit signed array and store the sum as a 32-bit +floating-point array. Depth of the output array is determined by the dtype parameter. In the second +and third cases above, as well as in the first case, when src1.depth() == src2.depth(), dtype can +be set to the default -1. In this case, the output array will have the same depth as the input +array, be it src1, src2 or both. +@note Saturation is not applied when the output array has the depth CV_32S. You may even get +result of an incorrect sign in the case of overflow. +@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. +`add(src,X)` means `add(src,(X,X,X,X))`. +`add(src,(X,))` means `add(src,(X,0,0,0))`. +@param src1 first input array or a scalar. +@param src2 second input array or a scalar. +@param dst output array that has the same size and number of channels as the input array(s); the +depth is defined by dtype or src1/src2. +@param mask optional operation mask - 8-bit single channel array, that specifies elements of the +output array to be changed. +@param dtype optional depth of the output array (see the discussion below). +@sa subtract, addWeighted, scaleAdd, Mat::convertTo +*/ +CV_EXPORTS_W void add(InputArray src1, InputArray src2, OutputArray dst, + InputArray mask = noArray(), int dtype = -1); + +/** @brief Calculates the per-element difference between two arrays or array and a scalar. + +The function subtract calculates: +- Difference between two arrays, when both input arrays have the same size and the same number of +channels: + \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) - \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0\f] +- Difference between an array and a scalar, when src2 is constructed from Scalar or has the same +number of elements as `src1.channels()`: + \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) - \texttt{src2} ) \quad \texttt{if mask}(I) \ne0\f] +- Difference between a scalar and an array, when src1 is constructed from Scalar or has the same +number of elements as `src2.channels()`: + \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1} - \texttt{src2}(I) ) \quad \texttt{if mask}(I) \ne0\f] +- The reverse difference between a scalar and an array in the case of `SubRS`: + \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src2} - \texttt{src1}(I) ) \quad \texttt{if mask}(I) \ne0\f] +where I is a multi-dimensional index of array elements. In case of multi-channel arrays, each +channel is processed independently. + +The first function in the list above can be replaced with matrix expressions: +@code{.cpp} + dst = src1 - src2; + dst -= src1; // equivalent to subtract(dst, src1, dst); +@endcode +The input arrays and the output array can all have the same or different depths. For example, you +can subtract to 8-bit unsigned arrays and store the difference in a 16-bit signed array. Depth of +the output array is determined by dtype parameter. In the second and third cases above, as well as +in the first case, when src1.depth() == src2.depth(), dtype can be set to the default -1. In this +case the output array will have the same depth as the input array, be it src1, src2 or both. +@note Saturation is not applied when the output array has the depth CV_32S. You may even get +result of an incorrect sign in the case of overflow. +@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. +`subtract(src,X)` means `subtract(src,(X,X,X,X))`. +`subtract(src,(X,))` means `subtract(src,(X,0,0,0))`. +@param src1 first input array or a scalar. +@param src2 second input array or a scalar. +@param dst output array of the same size and the same number of channels as the input array. +@param mask optional operation mask; this is an 8-bit single channel array that specifies elements +of the output array to be changed. +@param dtype optional depth of the output array +@sa add, addWeighted, scaleAdd, Mat::convertTo + */ +CV_EXPORTS_W void subtract(InputArray src1, InputArray src2, OutputArray dst, + InputArray mask = noArray(), int dtype = -1); + + +/** @brief Calculates the per-element scaled product of two arrays. + +The function multiply calculates the per-element product of two arrays: + +\f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{scale} \cdot \texttt{src1} (I) \cdot \texttt{src2} (I))\f] + +There is also a @ref MatrixExpressions -friendly variant of the first function. See Mat::mul . + +For a not-per-element matrix product, see gemm . + +@note Saturation is not applied when the output array has the depth +CV_32S. You may even get result of an incorrect sign in the case of +overflow. +@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. +`multiply(src,X)` means `multiply(src,(X,X,X,X))`. +`multiply(src,(X,))` means `multiply(src,(X,0,0,0))`. +@param src1 first input array. +@param src2 second input array of the same size and the same type as src1. +@param dst output array of the same size and type as src1. +@param scale optional scale factor. +@param dtype optional depth of the output array +@sa add, subtract, divide, scaleAdd, addWeighted, accumulate, accumulateProduct, accumulateSquare, +Mat::convertTo +*/ +CV_EXPORTS_W void multiply(InputArray src1, InputArray src2, + OutputArray dst, double scale = 1, int dtype = -1); + +/** @brief Performs per-element division of two arrays or a scalar by an array. + +The function cv::divide divides one array by another: +\f[\texttt{dst(I) = saturate(src1(I)*scale/src2(I))}\f] +or a scalar by an array when there is no src1 : +\f[\texttt{dst(I) = saturate(scale/src2(I))}\f] + +Different channels of multi-channel arrays are processed independently. + +For integer types when src2(I) is zero, dst(I) will also be zero. + +@note In case of floating point data there is no special defined behavior for zero src2(I) values. +Regular floating-point division is used. +Expect correct IEEE-754 behaviour for floating-point data (with NaN, Inf result values). + +@note Saturation is not applied when the output array has the depth CV_32S. You may even get +result of an incorrect sign in the case of overflow. +@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. +`divide(src,X)` means `divide(src,(X,X,X,X))`. +`divide(src,(X,))` means `divide(src,(X,0,0,0))`. +@param src1 first input array. +@param src2 second input array of the same size and type as src1. +@param scale scalar factor. +@param dst output array of the same size and type as src2. +@param dtype optional depth of the output array; if -1, dst will have depth src2.depth(), but in +case of an array-by-array division, you can only pass -1 when src1.depth()==src2.depth(). +@sa multiply, add, subtract +*/ +CV_EXPORTS_W void divide(InputArray src1, InputArray src2, OutputArray dst, + double scale = 1, int dtype = -1); + +/** @overload */ +CV_EXPORTS_W void divide(double scale, InputArray src2, + OutputArray dst, int dtype = -1); + +/** @brief Calculates the sum of a scaled array and another array. + +The function scaleAdd is one of the classical primitive linear algebra operations, known as DAXPY +or SAXPY in [BLAS](http://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms). It calculates +the sum of a scaled array and another array: +\f[\texttt{dst} (I)= \texttt{scale} \cdot \texttt{src1} (I) + \texttt{src2} (I)\f] +The function can also be emulated with a matrix expression, for example: +@code{.cpp} + Mat A(3, 3, CV_64F); + ... + A.row(0) = A.row(1)*2 + A.row(2); +@endcode +@param src1 first input array. +@param alpha scale factor for the first array. +@param src2 second input array of the same size and type as src1. +@param dst output array of the same size and type as src1. +@sa add, addWeighted, subtract, Mat::dot, Mat::convertTo +*/ +CV_EXPORTS_W void scaleAdd(InputArray src1, double alpha, InputArray src2, OutputArray dst); + +/** @brief Calculates the weighted sum of two arrays. + +The function addWeighted calculates the weighted sum of two arrays as follows: +\f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{src1} (I)* \texttt{alpha} + \texttt{src2} (I)* \texttt{beta} + \texttt{gamma} )\f] +where I is a multi-dimensional index of array elements. In case of multi-channel arrays, each +channel is processed independently. +The function can be replaced with a matrix expression: +@code{.cpp} + dst = src1*alpha + src2*beta + gamma; +@endcode +@note Saturation is not applied when the output array has the depth CV_32S. You may even get +result of an incorrect sign in the case of overflow. +@param src1 first input array. +@param alpha weight of the first array elements. +@param src2 second input array of the same size and channel number as src1. +@param beta weight of the second array elements. +@param gamma scalar added to each sum. +@param dst output array that has the same size and number of channels as the input arrays. +@param dtype optional depth of the output array; when both input arrays have the same depth, dtype +can be set to -1, which will be equivalent to src1.depth(). +@sa add, subtract, scaleAdd, Mat::convertTo +*/ +CV_EXPORTS_W void addWeighted(InputArray src1, double alpha, InputArray src2, + double beta, double gamma, OutputArray dst, int dtype = -1); + +/** @brief Scales, calculates absolute values, and converts the result to 8-bit. + +On each element of the input array, the function convertScaleAbs +performs three operations sequentially: scaling, taking an absolute +value, conversion to an unsigned 8-bit type: +\f[\texttt{dst} (I)= \texttt{saturate\_cast} (| \texttt{src} (I)* \texttt{alpha} + \texttt{beta} |)\f] +In case of multi-channel arrays, the function processes each channel +independently. When the output is not 8-bit, the operation can be +emulated by calling the Mat::convertTo method (or by using matrix +expressions) and then by calculating an absolute value of the result. +For example: +@code{.cpp} + Mat_ A(30,30); + randu(A, Scalar(-100), Scalar(100)); + Mat_ B = A*5 + 3; + B = abs(B); + // Mat_ B = abs(A*5+3) will also do the job, + // but it will allocate a temporary matrix +@endcode +@param src input array. +@param dst output array. +@param alpha optional scale factor. +@param beta optional delta added to the scaled values. +@sa Mat::convertTo, cv::abs(const Mat&) +*/ +CV_EXPORTS_W void convertScaleAbs(InputArray src, OutputArray dst, + double alpha = 1, double beta = 0); + +/** @brief Converts an array to half precision floating number. + +This function converts FP32 (single precision floating point) from/to FP16 (half precision floating point). CV_16S format is used to represent FP16 data. +There are two use modes (src -> dst): CV_32F -> CV_16S and CV_16S -> CV_32F. The input array has to have type of CV_32F or +CV_16S to represent the bit depth. If the input array is neither of them, the function will raise an error. +The format of half precision floating point is defined in IEEE 754-2008. + +@param src input array. +@param dst output array. + +@deprecated Use Mat::convertTo with CV_16F instead. +*/ +CV_EXPORTS_W void convertFp16(InputArray src, OutputArray dst); + +/** @example samples/cpp/tutorial_code/core/how_to_scan_images/how_to_scan_images.cpp +Check @ref tutorial_how_to_scan_images "the corresponding tutorial" for more details +*/ + +/** @brief Performs a look-up table transform of an array. + +The function LUT fills the output array with values from the look-up table. Indices of the entries +are taken from the input array. That is, the function processes each element of src as follows: +\f[\texttt{dst} (I) \leftarrow \texttt{lut(src(I) + d)}\f] +where +\f[d = \fork{0}{if \(\texttt{src}\) has depth \(\texttt{CV_8U}\)}{128}{if \(\texttt{src}\) has depth \(\texttt{CV_8S}\)}\f] +@param src input array of 8-bit elements. +@param lut look-up table of 256 elements; in case of multi-channel input array, the table should +either have a single channel (in this case the same table is used for all channels) or the same +number of channels as in the input array. +@param dst output array of the same size and number of channels as src, and the same depth as lut. +@sa convertScaleAbs, Mat::convertTo +*/ +CV_EXPORTS_W void LUT(InputArray src, InputArray lut, OutputArray dst); + +/** @brief Calculates the sum of array elements. + +The function cv::sum calculates and returns the sum of array elements, +independently for each channel. +@param src input array that must have from 1 to 4 channels. +@sa countNonZero, mean, meanStdDev, norm, minMaxLoc, reduce +*/ +CV_EXPORTS_AS(sumElems) Scalar sum(InputArray src); + +/** @brief Checks for the presence of at least one non-zero array element. + +The function returns whether there are non-zero elements in src + +The function do not work with multi-channel arrays. If you need to check non-zero array +elements across all the channels, use Mat::reshape first to reinterpret the array as +single-channel. Or you may extract the particular channel using either extractImageCOI, or +mixChannels, or split. + +@note +- If the location of non-zero array elements is important, @ref findNonZero is helpful. +- If the count of non-zero array elements is important, @ref countNonZero is helpful. +@param src single-channel array. +@sa mean, meanStdDev, norm, minMaxLoc, calcCovarMatrix +@sa findNonZero, countNonZero +*/ +CV_EXPORTS_W bool hasNonZero( InputArray src ); + +/** @brief Counts non-zero array elements. + +The function returns the number of non-zero elements in src : +\f[\sum _{I: \; \texttt{src} (I) \ne0 } 1\f] + +The function do not work with multi-channel arrays. If you need to count non-zero array +elements across all the channels, use Mat::reshape first to reinterpret the array as +single-channel. Or you may extract the particular channel using either extractImageCOI, or +mixChannels, or split. + +@note +- If only whether there are non-zero elements is important, @ref hasNonZero is helpful. +- If the location of non-zero array elements is important, @ref findNonZero is helpful. +@param src single-channel array. +@sa mean, meanStdDev, norm, minMaxLoc, calcCovarMatrix +@sa findNonZero, hasNonZero +*/ +CV_EXPORTS_W int countNonZero( InputArray src ); + +/** @brief Returns the list of locations of non-zero pixels + +Given a binary matrix (likely returned from an operation such +as threshold(), compare(), >, ==, etc, return all of +the non-zero indices as a cv::Mat or std::vector (x,y) +For example: +@code{.cpp} + cv::Mat binaryImage; // input, binary image + cv::Mat locations; // output, locations of non-zero pixels + cv::findNonZero(binaryImage, locations); + + // access pixel coordinates + Point pnt = locations.at(i); +@endcode +or +@code{.cpp} + cv::Mat binaryImage; // input, binary image + vector locations; // output, locations of non-zero pixels + cv::findNonZero(binaryImage, locations); + + // access pixel coordinates + Point pnt = locations[i]; +@endcode + +The function do not work with multi-channel arrays. If you need to find non-zero +elements across all the channels, use Mat::reshape first to reinterpret the array as +single-channel. Or you may extract the particular channel using either extractImageCOI, or +mixChannels, or split. + +@note +- If only count of non-zero array elements is important, @ref countNonZero is helpful. +- If only whether there are non-zero elements is important, @ref hasNonZero is helpful. +@param src single-channel array +@param idx the output array, type of cv::Mat or std::vector, corresponding to non-zero indices in the input +@sa countNonZero, hasNonZero +*/ +CV_EXPORTS_W void findNonZero( InputArray src, OutputArray idx ); + +/** @brief Calculates an average (mean) of array elements. + +The function cv::mean calculates the mean value M of array elements, +independently for each channel, and return it: +\f[\begin{array}{l} N = \sum _{I: \; \texttt{mask} (I) \ne 0} 1 \\ M_c = \left ( \sum _{I: \; \texttt{mask} (I) \ne 0}{ \texttt{mtx} (I)_c} \right )/N \end{array}\f] +When all the mask elements are 0's, the function returns Scalar::all(0) +@param src input array that should have from 1 to 4 channels so that the result can be stored in +Scalar_ . +@param mask optional operation mask. +@sa countNonZero, meanStdDev, norm, minMaxLoc +*/ +CV_EXPORTS_W Scalar mean(InputArray src, InputArray mask = noArray()); + +/** Calculates a mean and standard deviation of array elements. + +The function cv::meanStdDev calculates the mean and the standard deviation M +of array elements independently for each channel and returns it via the +output parameters: +\f[\begin{array}{l} N = \sum _{I, \texttt{mask} (I) \ne 0} 1 \\ \texttt{mean} _c = \frac{\sum_{ I: \; \texttt{mask}(I) \ne 0} \texttt{src} (I)_c}{N} \\ \texttt{stddev} _c = \sqrt{\frac{\sum_{ I: \; \texttt{mask}(I) \ne 0} \left ( \texttt{src} (I)_c - \texttt{mean} _c \right )^2}{N}} \end{array}\f] +When all the mask elements are 0's, the function returns +mean=stddev=Scalar::all(0). +@note The calculated standard deviation is only the diagonal of the +complete normalized covariance matrix. If the full matrix is needed, you +can reshape the multi-channel array M x N to the single-channel array +M\*N x mtx.channels() (only possible when the matrix is continuous) and +then pass the matrix to calcCovarMatrix . +@param src input array that should have from 1 to 4 channels so that the results can be stored in +Scalar_ 's. +@param mean output parameter: calculated mean value. +@param stddev output parameter: calculated standard deviation. +@param mask optional operation mask. +@sa countNonZero, mean, norm, minMaxLoc, calcCovarMatrix +*/ +CV_EXPORTS_W void meanStdDev(InputArray src, OutputArray mean, OutputArray stddev, + InputArray mask=noArray()); + +/** @brief Calculates the absolute norm of an array. + +This version of #norm calculates the absolute norm of src1. The type of norm to calculate is specified using #NormTypes. + +As example for one array consider the function \f$r(x)= \begin{pmatrix} x \\ 1-x \end{pmatrix}, x \in [-1;1]\f$. +The \f$ L_{1}, L_{2} \f$ and \f$ L_{\infty} \f$ norm for the sample value \f$r(-1) = \begin{pmatrix} -1 \\ 2 \end{pmatrix}\f$ +is calculated as follows +\f{align*} + \| r(-1) \|_{L_1} &= |-1| + |2| = 3 \\ + \| r(-1) \|_{L_2} &= \sqrt{(-1)^{2} + (2)^{2}} = \sqrt{5} \\ + \| r(-1) \|_{L_\infty} &= \max(|-1|,|2|) = 2 +\f} +and for \f$r(0.5) = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}\f$ the calculation is +\f{align*} + \| r(0.5) \|_{L_1} &= |0.5| + |0.5| = 1 \\ + \| r(0.5) \|_{L_2} &= \sqrt{(0.5)^{2} + (0.5)^{2}} = \sqrt{0.5} \\ + \| r(0.5) \|_{L_\infty} &= \max(|0.5|,|0.5|) = 0.5. +\f} +The following graphic shows all values for the three norm functions \f$\| r(x) \|_{L_1}, \| r(x) \|_{L_2}\f$ and \f$\| r(x) \|_{L_\infty}\f$. +It is notable that the \f$ L_{1} \f$ norm forms the upper and the \f$ L_{\infty} \f$ norm forms the lower border for the example function \f$ r(x) \f$. +![Graphs for the different norm functions from the above example](pics/NormTypes_OneArray_1-2-INF.png) + +When the mask parameter is specified and it is not empty, the norm is + +If normType is not specified, #NORM_L2 is used. +calculated only over the region specified by the mask. + +Multi-channel input arrays are treated as single-channel arrays, that is, +the results for all channels are combined. + +Hamming norms can only be calculated with CV_8U depth arrays. + +@param src1 first input array. +@param normType type of the norm (see #NormTypes). +@param mask optional operation mask; it must have the same size as src1 and CV_8UC1 type. +*/ +CV_EXPORTS_W double norm(InputArray src1, int normType = NORM_L2, InputArray mask = noArray()); + +/** @brief Calculates an absolute difference norm or a relative difference norm. + +This version of cv::norm calculates the absolute difference norm +or the relative difference norm of arrays src1 and src2. +The type of norm to calculate is specified using #NormTypes. + +@param src1 first input array. +@param src2 second input array of the same size and the same type as src1. +@param normType type of the norm (see #NormTypes). +@param mask optional operation mask; it must have the same size as src1 and CV_8UC1 type. +*/ +CV_EXPORTS_W double norm(InputArray src1, InputArray src2, + int normType = NORM_L2, InputArray mask = noArray()); +/** @overload +@param src first input array. +@param normType type of the norm (see #NormTypes). +*/ +CV_EXPORTS double norm( const SparseMat& src, int normType ); + +/** @brief Computes the Peak Signal-to-Noise Ratio (PSNR) image quality metric. + +This function calculates the Peak Signal-to-Noise Ratio (PSNR) image quality metric in decibels (dB), +between two input arrays src1 and src2. The arrays must have the same type. + +The PSNR is calculated as follows: + +\f[ +\texttt{PSNR} = 10 \cdot \log_{10}{\left( \frac{R^2}{MSE} \right) } +\f] + +where R is the maximum integer value of depth (e.g. 255 in the case of CV_8U data) +and MSE is the mean squared error between the two arrays. + +@param src1 first input array. +@param src2 second input array of the same size as src1. +@param R the maximum pixel value (255 by default) + + */ +CV_EXPORTS_W double PSNR(InputArray src1, InputArray src2, double R=255.); + +/** @brief naive nearest neighbor finder + +see http://en.wikipedia.org/wiki/Nearest_neighbor_search +@todo document + */ +CV_EXPORTS_W void batchDistance(InputArray src1, InputArray src2, + OutputArray dist, int dtype, OutputArray nidx, + int normType = NORM_L2, int K = 0, + InputArray mask = noArray(), int update = 0, + bool crosscheck = false); + +/** @brief Normalizes the norm or value range of an array. + +The function cv::normalize normalizes scale and shift the input array elements so that +\f[\| \texttt{dst} \| _{L_p}= \texttt{alpha}\f] +(where p=Inf, 1 or 2) when normType=NORM_INF, NORM_L1, or NORM_L2, respectively; or so that +\f[\min _I \texttt{dst} (I)= \texttt{alpha} , \, \, \max _I \texttt{dst} (I)= \texttt{beta}\f] + +when normType=NORM_MINMAX (for dense arrays only). The optional mask specifies a sub-array to be +normalized. This means that the norm or min-n-max are calculated over the sub-array, and then this +sub-array is modified to be normalized. If you want to only use the mask to calculate the norm or +min-max but modify the whole array, you can use norm and Mat::convertTo. + +In case of sparse matrices, only the non-zero values are analyzed and transformed. Because of this, +the range transformation for sparse matrices is not allowed since it can shift the zero level. + +Possible usage with some positive example data: +@code{.cpp} + vector positiveData = { 2.0, 8.0, 10.0 }; + vector normalizedData_l1, normalizedData_l2, normalizedData_inf, normalizedData_minmax; + + // Norm to probability (total count) + // sum(numbers) = 20.0 + // 2.0 0.1 (2.0/20.0) + // 8.0 0.4 (8.0/20.0) + // 10.0 0.5 (10.0/20.0) + normalize(positiveData, normalizedData_l1, 1.0, 0.0, NORM_L1); + + // Norm to unit vector: ||positiveData|| = 1.0 + // 2.0 0.15 + // 8.0 0.62 + // 10.0 0.77 + normalize(positiveData, normalizedData_l2, 1.0, 0.0, NORM_L2); + + // Norm to max element + // 2.0 0.2 (2.0/10.0) + // 8.0 0.8 (8.0/10.0) + // 10.0 1.0 (10.0/10.0) + normalize(positiveData, normalizedData_inf, 1.0, 0.0, NORM_INF); + + // Norm to range [0.0;1.0] + // 2.0 0.0 (shift to left border) + // 8.0 0.75 (6.0/8.0) + // 10.0 1.0 (shift to right border) + normalize(positiveData, normalizedData_minmax, 1.0, 0.0, NORM_MINMAX); +@endcode + +@param src input array. +@param dst output array of the same size as src . +@param alpha norm value to normalize to or the lower range boundary in case of the range +normalization. +@param beta upper range boundary in case of the range normalization; it is not used for the norm +normalization. +@param norm_type normalization type (see cv::NormTypes). +@param dtype when negative, the output array has the same type as src; otherwise, it has the same +number of channels as src and the depth =CV_MAT_DEPTH(dtype). +@param mask optional operation mask. +@sa norm, Mat::convertTo, SparseMat::convertTo +*/ +CV_EXPORTS_W void normalize( InputArray src, InputOutputArray dst, double alpha = 1, double beta = 0, + int norm_type = NORM_L2, int dtype = -1, InputArray mask = noArray()); + +/** @overload +@param src input array. +@param dst output array of the same size as src . +@param alpha norm value to normalize to or the lower range boundary in case of the range +normalization. +@param normType normalization type (see cv::NormTypes). +*/ +CV_EXPORTS void normalize( const SparseMat& src, SparseMat& dst, double alpha, int normType ); + +/** @brief Finds the global minimum and maximum in an array. + +The function cv::minMaxLoc finds the minimum and maximum element values and their positions. The +extrema are searched across the whole array or, if mask is not an empty array, in the specified +array region. + +In C++, if the input is multi-channel, you should omit the minLoc, maxLoc, and mask arguments +(i.e. leave them as NULL, NULL, and noArray() respectively). These arguments are not +supported for multi-channel input arrays. If working with multi-channel input and you +need the minLoc, maxLoc, or mask arguments, then use Mat::reshape first to reinterpret +the array as single-channel. Alternatively, you can extract the particular channel using either +extractImageCOI, mixChannels, or split. + +In Python, multi-channel input is not supported at all due to a limitation in the +binding generation process (there is no way to set minLoc and maxLoc to NULL). A +workaround is to operate on each channel individually or to use NumPy to achieve the same +functionality. + +@param src input single-channel array. +@param minVal pointer to the returned minimum value; NULL is used if not required. +@param maxVal pointer to the returned maximum value; NULL is used if not required. +@param minLoc pointer to the returned minimum location (in 2D case); NULL is used if not required. +@param maxLoc pointer to the returned maximum location (in 2D case); NULL is used if not required. +@param mask optional mask used to select a sub-array. +@sa max, min, reduceArgMin, reduceArgMax, compare, inRange, extractImageCOI, mixChannels, split, Mat::reshape +*/ +CV_EXPORTS_W void minMaxLoc(InputArray src, CV_OUT double* minVal, + CV_OUT double* maxVal = 0, CV_OUT Point* minLoc = 0, + CV_OUT Point* maxLoc = 0, InputArray mask = noArray()); + +/** + * @brief Finds indices of min elements along provided axis + * + * @note + * - If input or output array is not continuous, this function will create an internal copy. + * - NaN handling is left unspecified, see patchNaNs(). + * - The returned index is always in bounds of input matrix. + * + * @param src input single-channel array. + * @param dst output array of type CV_32SC1 with the same dimensionality as src, + * except for axis being reduced - it should be set to 1. + * @param lastIndex whether to get the index of first or last occurrence of min. + * @param axis axis to reduce along. + * @sa reduceArgMax, minMaxLoc, min, max, compare, reduce + */ +CV_EXPORTS_W void reduceArgMin(InputArray src, OutputArray dst, int axis, bool lastIndex = false); + +/** + * @brief Finds indices of max elements along provided axis + * + * @note + * - If input or output array is not continuous, this function will create an internal copy. + * - NaN handling is left unspecified, see patchNaNs(). + * - The returned index is always in bounds of input matrix. + * + * @param src input single-channel array. + * @param dst output array of type CV_32SC1 with the same dimensionality as src, + * except for axis being reduced - it should be set to 1. + * @param lastIndex whether to get the index of first or last occurrence of max. + * @param axis axis to reduce along. + * @sa reduceArgMin, minMaxLoc, min, max, compare, reduce + */ +CV_EXPORTS_W void reduceArgMax(InputArray src, OutputArray dst, int axis, bool lastIndex = false); + +/** @brief Finds the global minimum and maximum in an array + +The function cv::minMaxIdx finds the minimum and maximum element values and their positions. The +extremums are searched across the whole array or, if mask is not an empty array, in the specified +array region. In case of a sparse matrix, the minimum is found among non-zero elements +only. Multi-channel input is supported without mask and extremums indexes (should be nullptr). +@note When minIdx is not NULL, it must have at least 2 elements (as well as maxIdx), even if src is +a single-row or single-column matrix. In OpenCV (following MATLAB) each array has at least 2 +dimensions, i.e. single-column matrix is Mx1 matrix (and therefore minIdx/maxIdx will be +(i1,0)/(i2,0)) and single-row matrix is 1xN matrix (and therefore minIdx/maxIdx will be +(0,j1)/(0,j2)). +@param src input single-channel array. +@param minVal pointer to the returned minimum value; NULL is used if not required. +@param maxVal pointer to the returned maximum value; NULL is used if not required. +@param minIdx pointer to the returned minimum location (in nD case); NULL is used if not required; +Otherwise, it must point to an array of src.dims elements, the coordinates of the minimum element +in each dimension are stored there sequentially. +@param maxIdx pointer to the returned maximum location (in nD case). NULL is used if not required. +@param mask specified array region +*/ +CV_EXPORTS void minMaxIdx(InputArray src, double* minVal, double* maxVal = 0, + int* minIdx = 0, int* maxIdx = 0, InputArray mask = noArray()); + +/** @overload +@param a input single-channel array. +@param minVal pointer to the returned minimum value; NULL is used if not required. +@param maxVal pointer to the returned maximum value; NULL is used if not required. +@param minIdx pointer to the returned minimum location (in nD case); NULL is used if not required; +Otherwise, it must point to an array of src.dims elements, the coordinates of the minimum element +in each dimension are stored there sequentially. +@param maxIdx pointer to the returned maximum location (in nD case). NULL is used if not required. +*/ +CV_EXPORTS void minMaxLoc(const SparseMat& a, double* minVal, + double* maxVal, int* minIdx = 0, int* maxIdx = 0); + +/** @brief Reduces a matrix to a vector. + +The function #reduce reduces the matrix to a vector by treating the matrix rows/columns as a set of +1D vectors and performing the specified operation on the vectors until a single row/column is +obtained. For example, the function can be used to compute horizontal and vertical projections of a +raster image. In case of #REDUCE_MAX and #REDUCE_MIN, the output image should have the same type as the source one. +In case of #REDUCE_SUM, #REDUCE_SUM2 and #REDUCE_AVG, the output may have a larger element bit-depth to preserve accuracy. +And multi-channel arrays are also supported in these two reduction modes. + +The following code demonstrates its usage for a single channel matrix. +@snippet snippets/core_reduce.cpp example + +And the following code demonstrates its usage for a two-channel matrix. +@snippet snippets/core_reduce.cpp example2 + +@param src input 2D matrix. +@param dst output vector. Its size and type is defined by dim and dtype parameters. +@param dim dimension index along which the matrix is reduced. 0 means that the matrix is reduced to +a single row. 1 means that the matrix is reduced to a single column. +@param rtype reduction operation that could be one of #ReduceTypes +@param dtype when negative, the output vector will have the same type as the input matrix, +otherwise, its type will be CV_MAKE_TYPE(CV_MAT_DEPTH(dtype), src.channels()). +@sa repeat, reduceArgMin, reduceArgMax +*/ +CV_EXPORTS_W void reduce(InputArray src, OutputArray dst, int dim, int rtype, int dtype = -1); + +/** @brief Creates one multi-channel array out of several single-channel ones. + +The function cv::merge merges several arrays to make a single multi-channel array. That is, each +element of the output array will be a concatenation of the elements of the input arrays, where +elements of i-th input array are treated as mv[i].channels()-element vectors. + +The function cv::split does the reverse operation. If you need to shuffle channels in some other +advanced way, use cv::mixChannels. + +The following example shows how to merge 3 single channel matrices into a single 3-channel matrix. +@snippet snippets/core_merge.cpp example + +@param mv input array of matrices to be merged; all the matrices in mv must have the same +size and the same depth. +@param count number of input matrices when mv is a plain C array; it must be greater than zero. +@param dst output array of the same size and the same depth as mv[0]; The number of channels will +be equal to the parameter count. +@sa mixChannels, split, Mat::reshape +*/ +CV_EXPORTS void merge(const Mat* mv, size_t count, OutputArray dst); + +/** @overload +@param mv input vector of matrices to be merged; all the matrices in mv must have the same +size and the same depth. +@param dst output array of the same size and the same depth as mv[0]; The number of channels will +be the total number of channels in the matrix array. + */ +CV_EXPORTS_W void merge(InputArrayOfArrays mv, OutputArray dst); + +/** @brief Divides a multi-channel array into several single-channel arrays. + +The function cv::split splits a multi-channel array into separate single-channel arrays: +\f[\texttt{mv} [c](I) = \texttt{src} (I)_c\f] +If you need to extract a single channel or do some other sophisticated channel permutation, use +mixChannels. + +The following example demonstrates how to split a 3-channel matrix into 3 single channel matrices. +@snippet snippets/core_split.cpp example + +@param src input multi-channel array. +@param mvbegin output array; the number of arrays must match src.channels(); the arrays themselves are +reallocated, if needed. +@sa merge, mixChannels, cvtColor +*/ +CV_EXPORTS void split(const Mat& src, Mat* mvbegin); + +/** @overload +@param m input multi-channel array. +@param mv output vector of arrays; the arrays themselves are reallocated, if needed. +*/ +CV_EXPORTS_W void split(InputArray m, OutputArrayOfArrays mv); + +/** @brief Copies specified channels from input arrays to the specified channels of +output arrays. + +The function cv::mixChannels provides an advanced mechanism for shuffling image channels. + +cv::split,cv::merge,cv::extractChannel,cv::insertChannel and some forms of cv::cvtColor are partial cases of cv::mixChannels. + +In the example below, the code splits a 4-channel BGRA image into a 3-channel BGR (with B and R +channels swapped) and a separate alpha-channel image: +@code{.cpp} + Mat bgra( 100, 100, CV_8UC4, Scalar(255,0,0,255) ); + Mat bgr( bgra.rows, bgra.cols, CV_8UC3 ); + Mat alpha( bgra.rows, bgra.cols, CV_8UC1 ); + + // forming an array of matrices is a quite efficient operation, + // because the matrix data is not copied, only the headers + Mat out[] = { bgr, alpha }; + // bgra[0] -> bgr[2], bgra[1] -> bgr[1], + // bgra[2] -> bgr[0], bgra[3] -> alpha[0] + int from_to[] = { 0,2, 1,1, 2,0, 3,3 }; + mixChannels( &bgra, 1, out, 2, from_to, 4 ); +@endcode +@note Unlike many other new-style C++ functions in OpenCV (see the introduction section and +Mat::create ), cv::mixChannels requires the output arrays to be pre-allocated before calling the +function. +@param src input array or vector of matrices; all of the matrices must have the same size and the +same depth. +@param nsrcs number of matrices in `src`. +@param dst output array or vector of matrices; all the matrices **must be allocated**; their size and +depth must be the same as in `src[0]`. +@param ndsts number of matrices in `dst`. +@param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is +a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in +dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to +src[0].channels()-1, the second input image channels are indexed from src[0].channels() to +src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image +channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is +filled with zero . +@param npairs number of index pairs in `fromTo`. +@sa split, merge, extractChannel, insertChannel, cvtColor +*/ +CV_EXPORTS void mixChannels(const Mat* src, size_t nsrcs, Mat* dst, size_t ndsts, + const int* fromTo, size_t npairs); + +/** @overload +@param src input array or vector of matrices; all of the matrices must have the same size and the +same depth. +@param dst output array or vector of matrices; all the matrices **must be allocated**; their size and +depth must be the same as in src[0]. +@param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is +a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in +dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to +src[0].channels()-1, the second input image channels are indexed from src[0].channels() to +src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image +channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is +filled with zero . +@param npairs number of index pairs in fromTo. +*/ +CV_EXPORTS void mixChannels(InputArrayOfArrays src, InputOutputArrayOfArrays dst, + const int* fromTo, size_t npairs); + +/** @overload +@param src input array or vector of matrices; all of the matrices must have the same size and the +same depth. +@param dst output array or vector of matrices; all the matrices **must be allocated**; their size and +depth must be the same as in src[0]. +@param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is +a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in +dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to +src[0].channels()-1, the second input image channels are indexed from src[0].channels() to +src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image +channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is +filled with zero . +*/ +CV_EXPORTS_W void mixChannels(InputArrayOfArrays src, InputOutputArrayOfArrays dst, + const std::vector& fromTo); + +/** @brief Extracts a single channel from src (coi is 0-based index) +@param src input array +@param dst output array +@param coi index of channel to extract +@sa mixChannels, split +*/ +CV_EXPORTS_W void extractChannel(InputArray src, OutputArray dst, int coi); + +/** @brief Inserts a single channel to dst (coi is 0-based index) +@param src input array +@param dst output array +@param coi index of channel for insertion +@sa mixChannels, merge +*/ +CV_EXPORTS_W void insertChannel(InputArray src, InputOutputArray dst, int coi); + +/** @brief Flips a 2D array around vertical, horizontal, or both axes. + +The function cv::flip flips the array in one of three different ways (row +and column indices are 0-based): +\f[\texttt{dst} _{ij} = +\left\{ +\begin{array}{l l} +\texttt{src} _{\texttt{src.rows}-i-1,j} & if\; \texttt{flipCode} = 0 \\ +\texttt{src} _{i, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} > 0 \\ +\texttt{src} _{ \texttt{src.rows} -i-1, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} < 0 \\ +\end{array} +\right.\f] +The example scenarios of using the function are the following: +* Vertical flipping of the image (flipCode == 0) to switch between + top-left and bottom-left image origin. This is a typical operation + in video processing on Microsoft Windows\* OS. +* Horizontal flipping of the image with the subsequent horizontal + shift and absolute difference calculation to check for a + vertical-axis symmetry (flipCode \> 0). +* Simultaneous horizontal and vertical flipping of the image with + the subsequent shift and absolute difference calculation to check + for a central symmetry (flipCode \< 0). +* Reversing the order of point arrays (flipCode \> 0 or + flipCode == 0). +@param src input array. +@param dst output array of the same size and type as src. +@param flipCode a flag to specify how to flip the array; 0 means +flipping around the x-axis and positive value (for example, 1) means +flipping around y-axis. Negative value (for example, -1) means flipping +around both axes. +@sa transpose, repeat, completeSymm +*/ +CV_EXPORTS_W void flip(InputArray src, OutputArray dst, int flipCode); + +/** @brief Flips a n-dimensional at given axis + * @param src input array + * @param dst output array that has the same shape of src + * @param axis axis that performs a flip on. 0 <= axis < src.dims. + */ +CV_EXPORTS_W void flipND(InputArray src, OutputArray dst, int axis); + +/** @brief Broadcast the given Mat to the given shape. + * @param src input array + * @param shape target shape. Should be a list of CV_32S numbers. Note that negative values are not supported. + * @param dst output array that has the given shape + */ +CV_EXPORTS_W void broadcast(InputArray src, InputArray shape, OutputArray dst); + +enum RotateFlags { + ROTATE_90_CLOCKWISE = 0, //! A = (cv::Mat_(3, 2) << 1, 4, + 2, 5, + 3, 6); + cv::Mat_ B = (cv::Mat_(3, 2) << 7, 10, + 8, 11, + 9, 12); + + cv::Mat C; + cv::hconcat(A, B, C); + //C: + //[1, 4, 7, 10; + // 2, 5, 8, 11; + // 3, 6, 9, 12] + @endcode + @param src1 first input array to be considered for horizontal concatenation. + @param src2 second input array to be considered for horizontal concatenation. + @param dst output array. It has the same number of rows and depth as the src1 and src2, and the sum of cols of the src1 and src2. + */ +CV_EXPORTS void hconcat(InputArray src1, InputArray src2, OutputArray dst); +/** @overload + @code{.cpp} + std::vector matrices = { cv::Mat(4, 1, CV_8UC1, cv::Scalar(1)), + cv::Mat(4, 1, CV_8UC1, cv::Scalar(2)), + cv::Mat(4, 1, CV_8UC1, cv::Scalar(3)),}; + + cv::Mat out; + cv::hconcat( matrices, out ); + //out: + //[1, 2, 3; + // 1, 2, 3; + // 1, 2, 3; + // 1, 2, 3] + @endcode + @param src input array or vector of matrices. all of the matrices must have the same number of rows and the same depth. + @param dst output array. It has the same number of rows and depth as the src, and the sum of cols of the src. +same depth. + */ +CV_EXPORTS_W void hconcat(InputArrayOfArrays src, OutputArray dst); + +/** @brief Applies vertical concatenation to given matrices. + +The function vertically concatenates two or more cv::Mat matrices (with the same number of cols). +@code{.cpp} + cv::Mat matArray[] = { cv::Mat(1, 4, CV_8UC1, cv::Scalar(1)), + cv::Mat(1, 4, CV_8UC1, cv::Scalar(2)), + cv::Mat(1, 4, CV_8UC1, cv::Scalar(3)),}; + + cv::Mat out; + cv::vconcat( matArray, 3, out ); + //out: + //[1, 1, 1, 1; + // 2, 2, 2, 2; + // 3, 3, 3, 3] +@endcode +@param src input array or vector of matrices. all of the matrices must have the same number of cols and the same depth. +@param nsrc number of matrices in src. +@param dst output array. It has the same number of cols and depth as the src, and the sum of rows of the src. +@sa cv::hconcat(const Mat*, size_t, OutputArray), @sa cv::hconcat(InputArrayOfArrays, OutputArray) and @sa cv::hconcat(InputArray, InputArray, OutputArray) +*/ +CV_EXPORTS void vconcat(const Mat* src, size_t nsrc, OutputArray dst); +/** @overload + @code{.cpp} + cv::Mat_ A = (cv::Mat_(3, 2) << 1, 7, + 2, 8, + 3, 9); + cv::Mat_ B = (cv::Mat_(3, 2) << 4, 10, + 5, 11, + 6, 12); + + cv::Mat C; + cv::vconcat(A, B, C); + //C: + //[1, 7; + // 2, 8; + // 3, 9; + // 4, 10; + // 5, 11; + // 6, 12] + @endcode + @param src1 first input array to be considered for vertical concatenation. + @param src2 second input array to be considered for vertical concatenation. + @param dst output array. It has the same number of cols and depth as the src1 and src2, and the sum of rows of the src1 and src2. + */ +CV_EXPORTS void vconcat(InputArray src1, InputArray src2, OutputArray dst); +/** @overload + @code{.cpp} + std::vector matrices = { cv::Mat(1, 4, CV_8UC1, cv::Scalar(1)), + cv::Mat(1, 4, CV_8UC1, cv::Scalar(2)), + cv::Mat(1, 4, CV_8UC1, cv::Scalar(3)),}; + + cv::Mat out; + cv::vconcat( matrices, out ); + //out: + //[1, 1, 1, 1; + // 2, 2, 2, 2; + // 3, 3, 3, 3] + @endcode + @param src input array or vector of matrices. all of the matrices must have the same number of cols and the same depth + @param dst output array. It has the same number of cols and depth as the src, and the sum of rows of the src. +same depth. + */ +CV_EXPORTS_W void vconcat(InputArrayOfArrays src, OutputArray dst); + +/** @brief computes bitwise conjunction of the two arrays (dst = src1 & src2) +Calculates the per-element bit-wise conjunction of two arrays or an +array and a scalar. + +The function cv::bitwise_and calculates the per-element bit-wise logical conjunction for: +* Two arrays when src1 and src2 have the same size: + \f[\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] +* An array and a scalar when src2 is constructed from Scalar or has + the same number of elements as `src1.channels()`: + \f[\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} \quad \texttt{if mask} (I) \ne0\f] +* A scalar and an array when src1 is constructed from Scalar or has + the same number of elements as `src2.channels()`: + \f[\texttt{dst} (I) = \texttt{src1} \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] +In case of floating-point arrays, their machine-specific bit +representations (usually IEEE754-compliant) are used for the operation. +In case of multi-channel arrays, each channel is processed +independently. In the second and third cases above, the scalar is first +converted to the array type. +@param src1 first input array or a scalar. +@param src2 second input array or a scalar. +@param dst output array that has the same size and type as the input +arrays. +@param mask optional operation mask, 8-bit single channel array, that +specifies elements of the output array to be changed. +*/ +CV_EXPORTS_W void bitwise_and(InputArray src1, InputArray src2, + OutputArray dst, InputArray mask = noArray()); + +/** @brief Calculates the per-element bit-wise disjunction of two arrays or an +array and a scalar. + +The function cv::bitwise_or calculates the per-element bit-wise logical disjunction for: +* Two arrays when src1 and src2 have the same size: + \f[\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] +* An array and a scalar when src2 is constructed from Scalar or has + the same number of elements as `src1.channels()`: + \f[\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} \quad \texttt{if mask} (I) \ne0\f] +* A scalar and an array when src1 is constructed from Scalar or has + the same number of elements as `src2.channels()`: + \f[\texttt{dst} (I) = \texttt{src1} \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] +In case of floating-point arrays, their machine-specific bit +representations (usually IEEE754-compliant) are used for the operation. +In case of multi-channel arrays, each channel is processed +independently. In the second and third cases above, the scalar is first +converted to the array type. +@param src1 first input array or a scalar. +@param src2 second input array or a scalar. +@param dst output array that has the same size and type as the input +arrays. +@param mask optional operation mask, 8-bit single channel array, that +specifies elements of the output array to be changed. +*/ +CV_EXPORTS_W void bitwise_or(InputArray src1, InputArray src2, + OutputArray dst, InputArray mask = noArray()); + +/** @brief Calculates the per-element bit-wise "exclusive or" operation on two +arrays or an array and a scalar. + +The function cv::bitwise_xor calculates the per-element bit-wise logical "exclusive-or" +operation for: +* Two arrays when src1 and src2 have the same size: + \f[\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] +* An array and a scalar when src2 is constructed from Scalar or has + the same number of elements as `src1.channels()`: + \f[\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} \quad \texttt{if mask} (I) \ne0\f] +* A scalar and an array when src1 is constructed from Scalar or has + the same number of elements as `src2.channels()`: + \f[\texttt{dst} (I) = \texttt{src1} \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] +In case of floating-point arrays, their machine-specific bit +representations (usually IEEE754-compliant) are used for the operation. +In case of multi-channel arrays, each channel is processed +independently. In the 2nd and 3rd cases above, the scalar is first +converted to the array type. +@param src1 first input array or a scalar. +@param src2 second input array or a scalar. +@param dst output array that has the same size and type as the input +arrays. +@param mask optional operation mask, 8-bit single channel array, that +specifies elements of the output array to be changed. +*/ +CV_EXPORTS_W void bitwise_xor(InputArray src1, InputArray src2, + OutputArray dst, InputArray mask = noArray()); + +/** @brief Inverts every bit of an array. + +The function cv::bitwise_not calculates per-element bit-wise inversion of the input +array: +\f[\texttt{dst} (I) = \neg \texttt{src} (I)\f] +In case of a floating-point input array, its machine-specific bit +representation (usually IEEE754-compliant) is used for the operation. In +case of multi-channel arrays, each channel is processed independently. +@param src input array. +@param dst output array that has the same size and type as the input +array. +@param mask optional operation mask, 8-bit single channel array, that +specifies elements of the output array to be changed. +*/ +CV_EXPORTS_W void bitwise_not(InputArray src, OutputArray dst, + InputArray mask = noArray()); + +/** @brief Calculates the per-element absolute difference between two arrays or between an array and a scalar. + +The function cv::absdiff calculates: +* Absolute difference between two arrays when they have the same + size and type: + \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2}(I)|)\f] +* Absolute difference between an array and a scalar when the second + array is constructed from Scalar or has as many elements as the + number of channels in `src1`: + \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2} |)\f] +* Absolute difference between a scalar and an array when the first + array is constructed from Scalar or has as many elements as the + number of channels in `src2`: + \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1} - \texttt{src2}(I) |)\f] + where I is a multi-dimensional index of array elements. In case of + multi-channel arrays, each channel is processed independently. +@note Saturation is not applied when the arrays have the depth CV_32S. +You may even get a negative value in the case of overflow. +@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. +`absdiff(src,X)` means `absdiff(src,(X,X,X,X))`. +`absdiff(src,(X,))` means `absdiff(src,(X,0,0,0))`. +@param src1 first input array or a scalar. +@param src2 second input array or a scalar. +@param dst output array that has the same size and type as input arrays. +@sa cv::abs(const Mat&) +*/ +CV_EXPORTS_W void absdiff(InputArray src1, InputArray src2, OutputArray dst); + +/** @brief This is an overloaded member function, provided for convenience (python) +Copies the matrix to another one. +When the operation mask is specified, if the Mat::create call shown above reallocates the matrix, the newly allocated matrix is initialized with all zeros before copying the data. +@param src source matrix. +@param dst Destination matrix. If it does not have a proper size or type before the operation, it is +reallocated. +@param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix +elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels. +*/ + +void CV_EXPORTS_W copyTo(InputArray src, OutputArray dst, InputArray mask); +/** @brief Checks if array elements lie between the elements of two other arrays. + +The function checks the range as follows: +- For every element of a single-channel input array: + \f[\texttt{dst} (I)= \texttt{lowerb} (I)_0 \leq \texttt{src} (I)_0 \leq \texttt{upperb} (I)_0\f] +- For two-channel arrays: + \f[\texttt{dst} (I)= \texttt{lowerb} (I)_0 \leq \texttt{src} (I)_0 \leq \texttt{upperb} (I)_0 \land \texttt{lowerb} (I)_1 \leq \texttt{src} (I)_1 \leq \texttt{upperb} (I)_1\f] +- and so forth. + +That is, dst (I) is set to 255 (all 1 -bits) if src (I) is within the +specified 1D, 2D, 3D, ... box and 0 otherwise. + +When the lower and/or upper boundary parameters are scalars, the indexes +(I) at lowerb and upperb in the above formulas should be omitted. +@param src first input array. +@param lowerb inclusive lower boundary array or a scalar. +@param upperb inclusive upper boundary array or a scalar. +@param dst output array of the same size as src and CV_8U type. +*/ +CV_EXPORTS_W void inRange(InputArray src, InputArray lowerb, + InputArray upperb, OutputArray dst); + +/** @brief Performs the per-element comparison of two arrays or an array and scalar value. + +The function compares: +* Elements of two arrays when src1 and src2 have the same size: + \f[\texttt{dst} (I) = \texttt{src1} (I) \,\texttt{cmpop}\, \texttt{src2} (I)\f] +* Elements of src1 with a scalar src2 when src2 is constructed from + Scalar or has a single element: + \f[\texttt{dst} (I) = \texttt{src1}(I) \,\texttt{cmpop}\, \texttt{src2}\f] +* src1 with elements of src2 when src1 is constructed from Scalar or + has a single element: + \f[\texttt{dst} (I) = \texttt{src1} \,\texttt{cmpop}\, \texttt{src2} (I)\f] +When the comparison result is true, the corresponding element of output +array is set to 255. The comparison operations can be replaced with the +equivalent matrix expressions: +@code{.cpp} + Mat dst1 = src1 >= src2; + Mat dst2 = src1 < 8; + ... +@endcode +@param src1 first input array or a scalar; when it is an array, it must have a single channel. +@param src2 second input array or a scalar; when it is an array, it must have a single channel. +@param dst output array of type ref CV_8U that has the same size and the same number of channels as + the input arrays. +@param cmpop a flag, that specifies correspondence between the arrays (cv::CmpTypes) +@sa checkRange, min, max, threshold +*/ +CV_EXPORTS_W void compare(InputArray src1, InputArray src2, OutputArray dst, int cmpop); + +/** @brief Calculates per-element minimum of two arrays or an array and a scalar. + +The function cv::min calculates the per-element minimum of two arrays: +\f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{src2} (I))\f] +or array and a scalar: +\f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{value} )\f] +@param src1 first input array. +@param src2 second input array of the same size and type as src1. +@param dst output array of the same size and type as src1. +@sa max, compare, inRange, minMaxLoc +*/ +CV_EXPORTS_W void min(InputArray src1, InputArray src2, OutputArray dst); +/** @overload +needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare) +*/ +CV_EXPORTS void min(const Mat& src1, const Mat& src2, Mat& dst); +/** @overload +needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare) +*/ +CV_EXPORTS void min(const UMat& src1, const UMat& src2, UMat& dst); + +/** @brief Calculates per-element maximum of two arrays or an array and a scalar. + +The function cv::max calculates the per-element maximum of two arrays: +\f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{src2} (I))\f] +or array and a scalar: +\f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{value} )\f] +@param src1 first input array. +@param src2 second input array of the same size and type as src1 . +@param dst output array of the same size and type as src1. +@sa min, compare, inRange, minMaxLoc, @ref MatrixExpressions +*/ +CV_EXPORTS_W void max(InputArray src1, InputArray src2, OutputArray dst); +/** @overload +needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare) +*/ +CV_EXPORTS void max(const Mat& src1, const Mat& src2, Mat& dst); +/** @overload +needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare) +*/ +CV_EXPORTS void max(const UMat& src1, const UMat& src2, UMat& dst); + +/** @brief Calculates a square root of array elements. + +The function cv::sqrt calculates a square root of each input array element. +In case of multi-channel arrays, each channel is processed +independently. The accuracy is approximately the same as of the built-in +std::sqrt . +@param src input floating-point array. +@param dst output array of the same size and type as src. +*/ +CV_EXPORTS_W void sqrt(InputArray src, OutputArray dst); + +/** @brief Raises every array element to a power. + +The function cv::pow raises every element of the input array to power : +\f[\texttt{dst} (I) = \fork{\texttt{src}(I)^{power}}{if \(\texttt{power}\) is integer}{|\texttt{src}(I)|^{power}}{otherwise}\f] + +So, for a non-integer power exponent, the absolute values of input array +elements are used. However, it is possible to get true values for +negative values using some extra operations. In the example below, +computing the 5th root of array src shows: +@code{.cpp} + Mat mask = src < 0; + pow(src, 1./5, dst); + subtract(Scalar::all(0), dst, dst, mask); +@endcode +For some values of power, such as integer values, 0.5 and -0.5, +specialized faster algorithms are used. + +Special values (NaN, Inf) are not handled. +@param src input array. +@param power exponent of power. +@param dst output array of the same size and type as src. +@sa sqrt, exp, log, cartToPolar, polarToCart +*/ +CV_EXPORTS_W void pow(InputArray src, double power, OutputArray dst); + +/** @brief Calculates the exponent of every array element. + +The function cv::exp calculates the exponent of every element of the input +array: +\f[\texttt{dst} [I] = e^{ src(I) }\f] + +The maximum relative error is about 7e-6 for single-precision input and +less than 1e-10 for double-precision input. Currently, the function +converts denormalized values to zeros on output. Special values (NaN, +Inf) are not handled. +@param src input array. +@param dst output array of the same size and type as src. +@sa log, cartToPolar, polarToCart, phase, pow, sqrt, magnitude +*/ +CV_EXPORTS_W void exp(InputArray src, OutputArray dst); + +/** @brief Calculates the natural logarithm of every array element. + +The function cv::log calculates the natural logarithm of every element of the input array: +\f[\texttt{dst} (I) = \log (\texttt{src}(I)) \f] + +Output on zero, negative and special (NaN, Inf) values is undefined. + +@param src input array. +@param dst output array of the same size and type as src . +@sa exp, cartToPolar, polarToCart, phase, pow, sqrt, magnitude +*/ +CV_EXPORTS_W void log(InputArray src, OutputArray dst); + +/** @brief Calculates x and y coordinates of 2D vectors from their magnitude and angle. + +The function cv::polarToCart calculates the Cartesian coordinates of each 2D +vector represented by the corresponding elements of magnitude and angle: +\f[\begin{array}{l} \texttt{x} (I) = \texttt{magnitude} (I) \cos ( \texttt{angle} (I)) \\ \texttt{y} (I) = \texttt{magnitude} (I) \sin ( \texttt{angle} (I)) \\ \end{array}\f] + +The relative accuracy of the estimated coordinates is about 1e-6. +@param magnitude input floating-point array of magnitudes of 2D vectors; +it can be an empty matrix (=Mat()), in this case, the function assumes +that all the magnitudes are =1; if it is not empty, it must have the +same size and type as angle. +@param angle input floating-point array of angles of 2D vectors. +@param x output array of x-coordinates of 2D vectors; it has the same +size and type as angle. +@param y output array of y-coordinates of 2D vectors; it has the same +size and type as angle. +@param angleInDegrees when true, the input angles are measured in +degrees, otherwise, they are measured in radians. +@sa cartToPolar, magnitude, phase, exp, log, pow, sqrt +*/ +CV_EXPORTS_W void polarToCart(InputArray magnitude, InputArray angle, + OutputArray x, OutputArray y, bool angleInDegrees = false); + +/** @brief Calculates the magnitude and angle of 2D vectors. + +The function cv::cartToPolar calculates either the magnitude, angle, or both +for every 2D vector (x(I),y(I)): +\f[\begin{array}{l} \texttt{magnitude} (I)= \sqrt{\texttt{x}(I)^2+\texttt{y}(I)^2} , \\ \texttt{angle} (I)= \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))[ \cdot180 / \pi ] \end{array}\f] + +The angles are calculated with accuracy about 0.3 degrees. For the point +(0,0), the angle is set to 0. +@param x array of x-coordinates; this must be a single-precision or +double-precision floating-point array. +@param y array of y-coordinates, that must have the same size and same type as x. +@param magnitude output array of magnitudes of the same size and type as x. +@param angle output array of angles that has the same size and type as +x; the angles are measured in radians (from 0 to 2\*Pi) or in degrees (0 to 360 degrees). +@param angleInDegrees a flag, indicating whether the angles are measured +in radians (which is by default), or in degrees. +@sa Sobel, Scharr +*/ +CV_EXPORTS_W void cartToPolar(InputArray x, InputArray y, + OutputArray magnitude, OutputArray angle, + bool angleInDegrees = false); + +/** @brief Calculates the rotation angle of 2D vectors. + +The function cv::phase calculates the rotation angle of each 2D vector that +is formed from the corresponding elements of x and y : +\f[\texttt{angle} (I) = \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))\f] + +The angle estimation accuracy is about 0.3 degrees. When x(I)=y(I)=0 , +the corresponding angle(I) is set to 0. +@param x input floating-point array of x-coordinates of 2D vectors. +@param y input array of y-coordinates of 2D vectors; it must have the +same size and the same type as x. +@param angle output array of vector angles; it has the same size and +same type as x . +@param angleInDegrees when true, the function calculates the angle in +degrees, otherwise, they are measured in radians. +*/ +CV_EXPORTS_W void phase(InputArray x, InputArray y, OutputArray angle, + bool angleInDegrees = false); + +/** @brief Calculates the magnitude of 2D vectors. + +The function cv::magnitude calculates the magnitude of 2D vectors formed +from the corresponding elements of x and y arrays: +\f[\texttt{dst} (I) = \sqrt{\texttt{x}(I)^2 + \texttt{y}(I)^2}\f] +@param x floating-point array of x-coordinates of the vectors. +@param y floating-point array of y-coordinates of the vectors; it must +have the same size as x. +@param magnitude output array of the same size and type as x. +@sa cartToPolar, polarToCart, phase, sqrt +*/ +CV_EXPORTS_W void magnitude(InputArray x, InputArray y, OutputArray magnitude); + +/** @brief Checks every element of an input array for invalid values. + +The function cv::checkRange checks that every array element is neither NaN nor infinite. When minVal \> +-DBL_MAX and maxVal \< DBL_MAX, the function also checks that each value is between minVal and +maxVal. In case of multi-channel arrays, each channel is processed independently. If some values +are out of range, position of the first outlier is stored in pos (when pos != NULL). Then, the +function either returns false (when quiet=true) or throws an exception. +@param a input array. +@param quiet a flag, indicating whether the functions quietly return false when the array elements +are out of range or they throw an exception. +@param pos optional output parameter, when not NULL, must be a pointer to array of src.dims +elements. +@param minVal inclusive lower boundary of valid values range. +@param maxVal exclusive upper boundary of valid values range. +*/ +CV_EXPORTS_W bool checkRange(InputArray a, bool quiet = true, CV_OUT Point* pos = 0, + double minVal = -DBL_MAX, double maxVal = DBL_MAX); + +/** @brief Replaces NaNs by given number +@param a input/output matrix (CV_32F type). +@param val value to convert the NaNs +*/ +CV_EXPORTS_W void patchNaNs(InputOutputArray a, double val = 0); + +/** @brief Performs generalized matrix multiplication. + +The function cv::gemm performs generalized matrix multiplication similar to the +gemm functions in BLAS level 3. For example, +`gemm(src1, src2, alpha, src3, beta, dst, GEMM_1_T + GEMM_3_T)` +corresponds to +\f[\texttt{dst} = \texttt{alpha} \cdot \texttt{src1} ^T \cdot \texttt{src2} + \texttt{beta} \cdot \texttt{src3} ^T\f] + +In case of complex (two-channel) data, performed a complex matrix +multiplication. + +The function can be replaced with a matrix expression. For example, the +above call can be replaced with: +@code{.cpp} + dst = alpha*src1.t()*src2 + beta*src3.t(); +@endcode +@param src1 first multiplied input matrix that could be real(CV_32FC1, +CV_64FC1) or complex(CV_32FC2, CV_64FC2). +@param src2 second multiplied input matrix of the same type as src1. +@param alpha weight of the matrix product. +@param src3 third optional delta matrix added to the matrix product; it +should have the same type as src1 and src2. +@param beta weight of src3. +@param dst output matrix; it has the proper size and the same type as +input matrices. +@param flags operation flags (cv::GemmFlags) +@sa mulTransposed, transform +*/ +CV_EXPORTS_W void gemm(InputArray src1, InputArray src2, double alpha, + InputArray src3, double beta, OutputArray dst, int flags = 0); + +/** @brief Calculates the product of a matrix and its transposition. + +The function cv::mulTransposed calculates the product of src and its +transposition: +\f[\texttt{dst} = \texttt{scale} ( \texttt{src} - \texttt{delta} )^T ( \texttt{src} - \texttt{delta} )\f] +if aTa=true, and +\f[\texttt{dst} = \texttt{scale} ( \texttt{src} - \texttt{delta} ) ( \texttt{src} - \texttt{delta} )^T\f] +otherwise. The function is used to calculate the covariance matrix. With +zero delta, it can be used as a faster substitute for general matrix +product A\*B when B=A' +@param src input single-channel matrix. Note that unlike gemm, the +function can multiply not only floating-point matrices. +@param dst output square matrix. +@param aTa Flag specifying the multiplication ordering. See the +description below. +@param delta Optional delta matrix subtracted from src before the +multiplication. When the matrix is empty ( delta=noArray() ), it is +assumed to be zero, that is, nothing is subtracted. If it has the same +size as src, it is simply subtracted. Otherwise, it is "repeated" (see +repeat ) to cover the full src and then subtracted. Type of the delta +matrix, when it is not empty, must be the same as the type of created +output matrix. See the dtype parameter description below. +@param scale Optional scale factor for the matrix product. +@param dtype Optional type of the output matrix. When it is negative, +the output matrix will have the same type as src . Otherwise, it will be +type=CV_MAT_DEPTH(dtype) that should be either CV_32F or CV_64F . +@sa calcCovarMatrix, gemm, repeat, reduce +*/ +CV_EXPORTS_W void mulTransposed( InputArray src, OutputArray dst, bool aTa, + InputArray delta = noArray(), + double scale = 1, int dtype = -1 ); + +/** @brief Transposes a matrix. + +The function cv::transpose transposes the matrix src : +\f[\texttt{dst} (i,j) = \texttt{src} (j,i)\f] +@note No complex conjugation is done in case of a complex matrix. It +should be done separately if needed. +@param src input array. +@param dst output array of the same type as src. +*/ +CV_EXPORTS_W void transpose(InputArray src, OutputArray dst); + +/** @brief Transpose for n-dimensional matrices. + * + * @note Input should be continuous single-channel matrix. + * @param src input array. + * @param order a permutation of [0,1,..,N-1] where N is the number of axes of src. + * The i'th axis of dst will correspond to the axis numbered order[i] of the input. + * @param dst output array of the same type as src. + */ +CV_EXPORTS_W void transposeND(InputArray src, const std::vector& order, OutputArray dst); + +/** @brief Performs the matrix transformation of every array element. + +The function cv::transform performs the matrix transformation of every +element of the array src and stores the results in dst : +\f[\texttt{dst} (I) = \texttt{m} \cdot \texttt{src} (I)\f] +(when m.cols=src.channels() ), or +\f[\texttt{dst} (I) = \texttt{m} \cdot [ \texttt{src} (I); 1]\f] +(when m.cols=src.channels()+1 ) + +Every element of the N -channel array src is interpreted as N -element +vector that is transformed using the M x N or M x (N+1) matrix m to +M-element vector - the corresponding element of the output array dst . + +The function may be used for geometrical transformation of +N -dimensional points, arbitrary linear color space transformation (such +as various kinds of RGB to YUV transforms), shuffling the image +channels, and so forth. +@param src input array that must have as many channels (1 to 4) as +m.cols or m.cols-1. +@param dst output array of the same size and depth as src; it has as +many channels as m.rows. +@param m transformation 2x2 or 2x3 floating-point matrix. +@sa perspectiveTransform, getAffineTransform, estimateAffine2D, warpAffine, warpPerspective +*/ +CV_EXPORTS_W void transform(InputArray src, OutputArray dst, InputArray m ); + +/** @brief Performs the perspective matrix transformation of vectors. + +The function cv::perspectiveTransform transforms every element of src by +treating it as a 2D or 3D vector, in the following way: +\f[(x, y, z) \rightarrow (x'/w, y'/w, z'/w)\f] +where +\f[(x', y', z', w') = \texttt{mat} \cdot \begin{bmatrix} x & y & z & 1 \end{bmatrix}\f] +and +\f[w = \fork{w'}{if \(w' \ne 0\)}{\infty}{otherwise}\f] + +Here a 3D vector transformation is shown. In case of a 2D vector +transformation, the z component is omitted. + +@note The function transforms a sparse set of 2D or 3D vectors. If you +want to transform an image using perspective transformation, use +warpPerspective . If you have an inverse problem, that is, you want to +compute the most probable perspective transformation out of several +pairs of corresponding points, you can use getPerspectiveTransform or +findHomography . +@param src input two-channel or three-channel floating-point array; each +element is a 2D/3D vector to be transformed. +@param dst output array of the same size and type as src. +@param m 3x3 or 4x4 floating-point transformation matrix. +@sa transform, warpPerspective, getPerspectiveTransform, findHomography +*/ +CV_EXPORTS_W void perspectiveTransform(InputArray src, OutputArray dst, InputArray m ); + +/** @brief Copies the lower or the upper half of a square matrix to its another half. + +The function cv::completeSymm copies the lower or the upper half of a square matrix to +its another half. The matrix diagonal remains unchanged: + - \f$\texttt{m}_{ij}=\texttt{m}_{ji}\f$ for \f$i > j\f$ if + lowerToUpper=false + - \f$\texttt{m}_{ij}=\texttt{m}_{ji}\f$ for \f$i < j\f$ if + lowerToUpper=true + +@param m input-output floating-point square matrix. +@param lowerToUpper operation flag; if true, the lower half is copied to +the upper half. Otherwise, the upper half is copied to the lower half. +@sa flip, transpose +*/ +CV_EXPORTS_W void completeSymm(InputOutputArray m, bool lowerToUpper = false); + +/** @brief Initializes a scaled identity matrix. + +The function cv::setIdentity initializes a scaled identity matrix: +\f[\texttt{mtx} (i,j)= \fork{\texttt{value}}{ if \(i=j\)}{0}{otherwise}\f] + +The function can also be emulated using the matrix initializers and the +matrix expressions: +@code + Mat A = Mat::eye(4, 3, CV_32F)*5; + // A will be set to [[5, 0, 0], [0, 5, 0], [0, 0, 5], [0, 0, 0]] +@endcode +@param mtx matrix to initialize (not necessarily square). +@param s value to assign to diagonal elements. +@sa Mat::zeros, Mat::ones, Mat::setTo, Mat::operator= +*/ +CV_EXPORTS_W void setIdentity(InputOutputArray mtx, const Scalar& s = Scalar(1)); + +/** @brief Returns the determinant of a square floating-point matrix. + +The function cv::determinant calculates and returns the determinant of the +specified matrix. For small matrices ( mtx.cols=mtx.rows\<=3 ), the +direct method is used. For larger matrices, the function uses LU +factorization with partial pivoting. + +For symmetric positively-determined matrices, it is also possible to use +eigen decomposition to calculate the determinant. +@param mtx input matrix that must have CV_32FC1 or CV_64FC1 type and +square size. +@sa trace, invert, solve, eigen, @ref MatrixExpressions +*/ +CV_EXPORTS_W double determinant(InputArray mtx); + +/** @brief Returns the trace of a matrix. + +The function cv::trace returns the sum of the diagonal elements of the +matrix mtx . +\f[\mathrm{tr} ( \texttt{mtx} ) = \sum _i \texttt{mtx} (i,i)\f] +@param mtx input matrix. +*/ +CV_EXPORTS_W Scalar trace(InputArray mtx); + +/** @brief Finds the inverse or pseudo-inverse of a matrix. + +The function cv::invert inverts the matrix src and stores the result in dst +. When the matrix src is singular or non-square, the function calculates +the pseudo-inverse matrix (the dst matrix) so that norm(src\*dst - I) is +minimal, where I is an identity matrix. + +In case of the #DECOMP_LU method, the function returns non-zero value if +the inverse has been successfully calculated and 0 if src is singular. + +In case of the #DECOMP_SVD method, the function returns the inverse +condition number of src (the ratio of the smallest singular value to the +largest singular value) and 0 if src is singular. The SVD method +calculates a pseudo-inverse matrix if src is singular. + +Similarly to #DECOMP_LU, the method #DECOMP_CHOLESKY works only with +non-singular square matrices that should also be symmetrical and +positively defined. In this case, the function stores the inverted +matrix in dst and returns non-zero. Otherwise, it returns 0. + +@param src input floating-point M x N matrix. +@param dst output matrix of N x M size and the same type as src. +@param flags inversion method (cv::DecompTypes) +@sa solve, SVD +*/ +CV_EXPORTS_W double invert(InputArray src, OutputArray dst, int flags = DECOMP_LU); + +/** @brief Solves one or more linear systems or least-squares problems. + +The function cv::solve solves a linear system or least-squares problem (the +latter is possible with SVD or QR methods, or by specifying the flag +#DECOMP_NORMAL ): +\f[\texttt{dst} = \arg \min _X \| \texttt{src1} \cdot \texttt{X} - \texttt{src2} \|\f] + +If #DECOMP_LU or #DECOMP_CHOLESKY method is used, the function returns 1 +if src1 (or \f$\texttt{src1}^T\texttt{src1}\f$ ) is non-singular. Otherwise, +it returns 0. In the latter case, dst is not valid. Other methods find a +pseudo-solution in case of a singular left-hand side part. + +@note If you want to find a unity-norm solution of an under-defined +singular system \f$\texttt{src1}\cdot\texttt{dst}=0\f$ , the function solve +will not do the work. Use SVD::solveZ instead. + +@param src1 input matrix on the left-hand side of the system. +@param src2 input matrix on the right-hand side of the system. +@param dst output solution. +@param flags solution (matrix inversion) method (#DecompTypes) +@sa invert, SVD, eigen +*/ +CV_EXPORTS_W bool solve(InputArray src1, InputArray src2, + OutputArray dst, int flags = DECOMP_LU); + +/** @brief Sorts each row or each column of a matrix. + +The function cv::sort sorts each matrix row or each matrix column in +ascending or descending order. So you should pass two operation flags to +get desired behaviour. If you want to sort matrix rows or columns +lexicographically, you can use STL std::sort generic function with the +proper comparison predicate. + +@param src input single-channel array. +@param dst output array of the same size and type as src. +@param flags operation flags, a combination of #SortFlags +@sa sortIdx, randShuffle +*/ +CV_EXPORTS_W void sort(InputArray src, OutputArray dst, int flags); + +/** @brief Sorts each row or each column of a matrix. + +The function cv::sortIdx sorts each matrix row or each matrix column in the +ascending or descending order. So you should pass two operation flags to +get desired behaviour. Instead of reordering the elements themselves, it +stores the indices of sorted elements in the output array. For example: +@code + Mat A = Mat::eye(3,3,CV_32F), B; + sortIdx(A, B, SORT_EVERY_ROW + SORT_ASCENDING); + // B will probably contain + // (because of equal elements in A some permutations are possible): + // [[1, 2, 0], [0, 2, 1], [0, 1, 2]] +@endcode +@param src input single-channel array. +@param dst output integer array of the same size as src. +@param flags operation flags that could be a combination of cv::SortFlags +@sa sort, randShuffle +*/ +CV_EXPORTS_W void sortIdx(InputArray src, OutputArray dst, int flags); + +/** @brief Finds the real roots of a cubic equation. + +The function solveCubic finds the real roots of a cubic equation: +- if coeffs is a 4-element vector: +\f[\texttt{coeffs} [0] x^3 + \texttt{coeffs} [1] x^2 + \texttt{coeffs} [2] x + \texttt{coeffs} [3] = 0\f] +- if coeffs is a 3-element vector: +\f[x^3 + \texttt{coeffs} [0] x^2 + \texttt{coeffs} [1] x + \texttt{coeffs} [2] = 0\f] + +The roots are stored in the roots array. +@param coeffs equation coefficients, an array of 3 or 4 elements. +@param roots output array of real roots that has 1 or 3 elements. +@return number of real roots. It can be 0, 1 or 2. +*/ +CV_EXPORTS_W int solveCubic(InputArray coeffs, OutputArray roots); + +/** @brief Finds the real or complex roots of a polynomial equation. + +The function cv::solvePoly finds real and complex roots of a polynomial equation: +\f[\texttt{coeffs} [n] x^{n} + \texttt{coeffs} [n-1] x^{n-1} + ... + \texttt{coeffs} [1] x + \texttt{coeffs} [0] = 0\f] +@param coeffs array of polynomial coefficients. +@param roots output (complex) array of roots. +@param maxIters maximum number of iterations the algorithm does. +*/ +CV_EXPORTS_W double solvePoly(InputArray coeffs, OutputArray roots, int maxIters = 300); + +/** @brief Calculates eigenvalues and eigenvectors of a symmetric matrix. + +The function cv::eigen calculates just eigenvalues, or eigenvalues and eigenvectors of the symmetric +matrix src: +@code + src*eigenvectors.row(i).t() = eigenvalues.at(i)*eigenvectors.row(i).t() +@endcode + +@note Use cv::eigenNonSymmetric for calculation of real eigenvalues and eigenvectors of non-symmetric matrix. + +@param src input matrix that must have CV_32FC1 or CV_64FC1 type, square size and be symmetrical +(src ^T^ == src). +@param eigenvalues output vector of eigenvalues of the same type as src; the eigenvalues are stored +in the descending order. +@param eigenvectors output matrix of eigenvectors; it has the same size and type as src; the +eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding +eigenvalues. +@sa eigenNonSymmetric, completeSymm, PCA +*/ +CV_EXPORTS_W bool eigen(InputArray src, OutputArray eigenvalues, + OutputArray eigenvectors = noArray()); + +/** @brief Calculates eigenvalues and eigenvectors of a non-symmetric matrix (real eigenvalues only). + +@note Assumes real eigenvalues. + +The function calculates eigenvalues and eigenvectors (optional) of the square matrix src: +@code + src*eigenvectors.row(i).t() = eigenvalues.at(i)*eigenvectors.row(i).t() +@endcode + +@param src input matrix (CV_32FC1 or CV_64FC1 type). +@param eigenvalues output vector of eigenvalues (type is the same type as src). +@param eigenvectors output matrix of eigenvectors (type is the same type as src). The eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding eigenvalues. +@sa eigen +*/ +CV_EXPORTS_W void eigenNonSymmetric(InputArray src, OutputArray eigenvalues, + OutputArray eigenvectors); + +/** @brief Calculates the covariance matrix of a set of vectors. + +The function cv::calcCovarMatrix calculates the covariance matrix and, optionally, the mean vector of +the set of input vectors. +@param samples samples stored as separate matrices +@param nsamples number of samples +@param covar output covariance matrix of the type ctype and square size. +@param mean input or output (depending on the flags) array as the average value of the input vectors. +@param flags operation flags as a combination of #CovarFlags +@param ctype type of the matrixl; it equals 'CV_64F' by default. +@sa PCA, mulTransposed, Mahalanobis +@todo InputArrayOfArrays +*/ +CV_EXPORTS void calcCovarMatrix( const Mat* samples, int nsamples, Mat& covar, Mat& mean, + int flags, int ctype = CV_64F); + +/** @overload +@note use #COVAR_ROWS or #COVAR_COLS flag +@param samples samples stored as rows/columns of a single matrix. +@param covar output covariance matrix of the type ctype and square size. +@param mean input or output (depending on the flags) array as the average value of the input vectors. +@param flags operation flags as a combination of #CovarFlags +@param ctype type of the matrixl; it equals 'CV_64F' by default. +*/ +CV_EXPORTS_W void calcCovarMatrix( InputArray samples, OutputArray covar, + InputOutputArray mean, int flags, int ctype = CV_64F); + +/** wrap PCA::operator() */ +CV_EXPORTS_W void PCACompute(InputArray data, InputOutputArray mean, + OutputArray eigenvectors, int maxComponents = 0); + +/** wrap PCA::operator() and add eigenvalues output parameter */ +CV_EXPORTS_AS(PCACompute2) void PCACompute(InputArray data, InputOutputArray mean, + OutputArray eigenvectors, OutputArray eigenvalues, + int maxComponents = 0); + +/** wrap PCA::operator() */ +CV_EXPORTS_W void PCACompute(InputArray data, InputOutputArray mean, + OutputArray eigenvectors, double retainedVariance); + +/** wrap PCA::operator() and add eigenvalues output parameter */ +CV_EXPORTS_AS(PCACompute2) void PCACompute(InputArray data, InputOutputArray mean, + OutputArray eigenvectors, OutputArray eigenvalues, + double retainedVariance); + +/** wrap PCA::project */ +CV_EXPORTS_W void PCAProject(InputArray data, InputArray mean, + InputArray eigenvectors, OutputArray result); + +/** wrap PCA::backProject */ +CV_EXPORTS_W void PCABackProject(InputArray data, InputArray mean, + InputArray eigenvectors, OutputArray result); + +/** wrap SVD::compute */ +CV_EXPORTS_W void SVDecomp( InputArray src, OutputArray w, OutputArray u, OutputArray vt, int flags = 0 ); + +/** wrap SVD::backSubst */ +CV_EXPORTS_W void SVBackSubst( InputArray w, InputArray u, InputArray vt, + InputArray rhs, OutputArray dst ); + +/** @brief Calculates the Mahalanobis distance between two vectors. + +The function cv::Mahalanobis calculates and returns the weighted distance between two vectors: +\f[d( \texttt{vec1} , \texttt{vec2} )= \sqrt{\sum_{i,j}{\texttt{icovar(i,j)}\cdot(\texttt{vec1}(I)-\texttt{vec2}(I))\cdot(\texttt{vec1(j)}-\texttt{vec2(j)})} }\f] +The covariance matrix may be calculated using the #calcCovarMatrix function and then inverted using +the invert function (preferably using the #DECOMP_SVD method, as the most accurate). +@param v1 first 1D input vector. +@param v2 second 1D input vector. +@param icovar inverse covariance matrix. +*/ +CV_EXPORTS_W double Mahalanobis(InputArray v1, InputArray v2, InputArray icovar); + +/** @brief Performs a forward or inverse Discrete Fourier transform of a 1D or 2D floating-point array. + +The function cv::dft performs one of the following: +- Forward the Fourier transform of a 1D vector of N elements: + \f[Y = F^{(N)} \cdot X,\f] + where \f$F^{(N)}_{jk}=\exp(-2\pi i j k/N)\f$ and \f$i=\sqrt{-1}\f$ +- Inverse the Fourier transform of a 1D vector of N elements: + \f[\begin{array}{l} X'= \left (F^{(N)} \right )^{-1} \cdot Y = \left (F^{(N)} \right )^* \cdot y \\ X = (1/N) \cdot X, \end{array}\f] + where \f$F^*=\left(\textrm{Re}(F^{(N)})-\textrm{Im}(F^{(N)})\right)^T\f$ +- Forward the 2D Fourier transform of a M x N matrix: + \f[Y = F^{(M)} \cdot X \cdot F^{(N)}\f] +- Inverse the 2D Fourier transform of a M x N matrix: + \f[\begin{array}{l} X'= \left (F^{(M)} \right )^* \cdot Y \cdot \left (F^{(N)} \right )^* \\ X = \frac{1}{M \cdot N} \cdot X' \end{array}\f] + +In case of real (single-channel) data, the output spectrum of the forward Fourier transform or input +spectrum of the inverse Fourier transform can be represented in a packed format called *CCS* +(complex-conjugate-symmetrical). It was borrowed from IPL (Intel\* Image Processing Library). Here +is how 2D *CCS* spectrum looks: +\f[\begin{bmatrix} Re Y_{0,0} & Re Y_{0,1} & Im Y_{0,1} & Re Y_{0,2} & Im Y_{0,2} & \cdots & Re Y_{0,N/2-1} & Im Y_{0,N/2-1} & Re Y_{0,N/2} \\ Re Y_{1,0} & Re Y_{1,1} & Im Y_{1,1} & Re Y_{1,2} & Im Y_{1,2} & \cdots & Re Y_{1,N/2-1} & Im Y_{1,N/2-1} & Re Y_{1,N/2} \\ Im Y_{1,0} & Re Y_{2,1} & Im Y_{2,1} & Re Y_{2,2} & Im Y_{2,2} & \cdots & Re Y_{2,N/2-1} & Im Y_{2,N/2-1} & Im Y_{1,N/2} \\ \hdotsfor{9} \\ Re Y_{M/2-1,0} & Re Y_{M-3,1} & Im Y_{M-3,1} & \hdotsfor{3} & Re Y_{M-3,N/2-1} & Im Y_{M-3,N/2-1}& Re Y_{M/2-1,N/2} \\ Im Y_{M/2-1,0} & Re Y_{M-2,1} & Im Y_{M-2,1} & \hdotsfor{3} & Re Y_{M-2,N/2-1} & Im Y_{M-2,N/2-1}& Im Y_{M/2-1,N/2} \\ Re Y_{M/2,0} & Re Y_{M-1,1} & Im Y_{M-1,1} & \hdotsfor{3} & Re Y_{M-1,N/2-1} & Im Y_{M-1,N/2-1}& Re Y_{M/2,N/2} \end{bmatrix}\f] + +In case of 1D transform of a real vector, the output looks like the first row of the matrix above. + +So, the function chooses an operation mode depending on the flags and size of the input array: +- If #DFT_ROWS is set or the input array has a single row or single column, the function + performs a 1D forward or inverse transform of each row of a matrix when #DFT_ROWS is set. + Otherwise, it performs a 2D transform. +- If the input array is real and #DFT_INVERSE is not set, the function performs a forward 1D or + 2D transform: + - When #DFT_COMPLEX_OUTPUT is set, the output is a complex matrix of the same size as + input. + - When #DFT_COMPLEX_OUTPUT is not set, the output is a real matrix of the same size as + input. In case of 2D transform, it uses the packed format as shown above. In case of a + single 1D transform, it looks like the first row of the matrix above. In case of + multiple 1D transforms (when using the #DFT_ROWS flag), each row of the output matrix + looks like the first row of the matrix above. +- If the input array is complex and either #DFT_INVERSE or #DFT_REAL_OUTPUT are not set, the + output is a complex array of the same size as input. The function performs a forward or + inverse 1D or 2D transform of the whole input array or each row of the input array + independently, depending on the flags DFT_INVERSE and DFT_ROWS. +- When #DFT_INVERSE is set and the input array is real, or it is complex but #DFT_REAL_OUTPUT + is set, the output is a real array of the same size as input. The function performs a 1D or 2D + inverse transformation of the whole input array or each individual row, depending on the flags + #DFT_INVERSE and #DFT_ROWS. + +If #DFT_SCALE is set, the scaling is done after the transformation. + +Unlike dct, the function supports arrays of arbitrary size. But only those arrays are processed +efficiently, whose sizes can be factorized in a product of small prime numbers (2, 3, and 5 in the +current implementation). Such an efficient DFT size can be calculated using the getOptimalDFTSize +method. + +The sample below illustrates how to calculate a DFT-based convolution of two 2D real arrays: +@code + void convolveDFT(InputArray A, InputArray B, OutputArray C) + { + // reallocate the output array if needed + C.create(abs(A.rows - B.rows)+1, abs(A.cols - B.cols)+1, A.type()); + Size dftSize; + // calculate the size of DFT transform + dftSize.width = getOptimalDFTSize(A.cols + B.cols - 1); + dftSize.height = getOptimalDFTSize(A.rows + B.rows - 1); + + // allocate temporary buffers and initialize them with 0's + Mat tempA(dftSize, A.type(), Scalar::all(0)); + Mat tempB(dftSize, B.type(), Scalar::all(0)); + + // copy A and B to the top-left corners of tempA and tempB, respectively + Mat roiA(tempA, Rect(0,0,A.cols,A.rows)); + A.copyTo(roiA); + Mat roiB(tempB, Rect(0,0,B.cols,B.rows)); + B.copyTo(roiB); + + // now transform the padded A & B in-place; + // use "nonzeroRows" hint for faster processing + dft(tempA, tempA, 0, A.rows); + dft(tempB, tempB, 0, B.rows); + + // multiply the spectrums; + // the function handles packed spectrum representations well + mulSpectrums(tempA, tempB, tempA); + + // transform the product back from the frequency domain. + // Even though all the result rows will be non-zero, + // you need only the first C.rows of them, and thus you + // pass nonzeroRows == C.rows + dft(tempA, tempA, DFT_INVERSE + DFT_SCALE, C.rows); + + // now copy the result back to C. + tempA(Rect(0, 0, C.cols, C.rows)).copyTo(C); + + // all the temporary buffers will be deallocated automatically + } +@endcode +To optimize this sample, consider the following approaches: +- Since nonzeroRows != 0 is passed to the forward transform calls and since A and B are copied to + the top-left corners of tempA and tempB, respectively, it is not necessary to clear the whole + tempA and tempB. It is only necessary to clear the tempA.cols - A.cols ( tempB.cols - B.cols) + rightmost columns of the matrices. +- This DFT-based convolution does not have to be applied to the whole big arrays, especially if B + is significantly smaller than A or vice versa. Instead, you can calculate convolution by parts. + To do this, you need to split the output array C into multiple tiles. For each tile, estimate + which parts of A and B are required to calculate convolution in this tile. If the tiles in C are + too small, the speed will decrease a lot because of repeated work. In the ultimate case, when + each tile in C is a single pixel, the algorithm becomes equivalent to the naive convolution + algorithm. If the tiles are too big, the temporary arrays tempA and tempB become too big and + there is also a slowdown because of bad cache locality. So, there is an optimal tile size + somewhere in the middle. +- If different tiles in C can be calculated in parallel and, thus, the convolution is done by + parts, the loop can be threaded. + +All of the above improvements have been implemented in #matchTemplate and #filter2D . Therefore, by +using them, you can get the performance even better than with the above theoretically optimal +implementation. Though, those two functions actually calculate cross-correlation, not convolution, +so you need to "flip" the second convolution operand B vertically and horizontally using flip . +@note +- An example using the discrete fourier transform can be found at + opencv_source_code/samples/cpp/dft.cpp +- (Python) An example using the dft functionality to perform Wiener deconvolution can be found + at opencv_source/samples/python/deconvolution.py +- (Python) An example rearranging the quadrants of a Fourier image can be found at + opencv_source/samples/python/dft.py +@param src input array that could be real or complex. +@param dst output array whose size and type depends on the flags . +@param flags transformation flags, representing a combination of the #DftFlags +@param nonzeroRows when the parameter is not zero, the function assumes that only the first +nonzeroRows rows of the input array (#DFT_INVERSE is not set) or only the first nonzeroRows of the +output array (#DFT_INVERSE is set) contain non-zeros, thus, the function can handle the rest of the +rows more efficiently and save some time; this technique is very useful for calculating array +cross-correlation or convolution using DFT. +@sa dct, getOptimalDFTSize, mulSpectrums, filter2D, matchTemplate, flip, cartToPolar, +magnitude, phase +*/ +CV_EXPORTS_W void dft(InputArray src, OutputArray dst, int flags = 0, int nonzeroRows = 0); + +/** @brief Calculates the inverse Discrete Fourier Transform of a 1D or 2D array. + +idft(src, dst, flags) is equivalent to dft(src, dst, flags | #DFT_INVERSE) . +@note None of dft and idft scales the result by default. So, you should pass #DFT_SCALE to one of +dft or idft explicitly to make these transforms mutually inverse. +@sa dft, dct, idct, mulSpectrums, getOptimalDFTSize +@param src input floating-point real or complex array. +@param dst output array whose size and type depend on the flags. +@param flags operation flags (see dft and #DftFlags). +@param nonzeroRows number of dst rows to process; the rest of the rows have undefined content (see +the convolution sample in dft description. +*/ +CV_EXPORTS_W void idft(InputArray src, OutputArray dst, int flags = 0, int nonzeroRows = 0); + +/** @brief Performs a forward or inverse discrete Cosine transform of 1D or 2D array. + +The function cv::dct performs a forward or inverse discrete Cosine transform (DCT) of a 1D or 2D +floating-point array: +- Forward Cosine transform of a 1D vector of N elements: + \f[Y = C^{(N)} \cdot X\f] + where + \f[C^{(N)}_{jk}= \sqrt{\alpha_j/N} \cos \left ( \frac{\pi(2k+1)j}{2N} \right )\f] + and + \f$\alpha_0=1\f$, \f$\alpha_j=2\f$ for *j \> 0*. +- Inverse Cosine transform of a 1D vector of N elements: + \f[X = \left (C^{(N)} \right )^{-1} \cdot Y = \left (C^{(N)} \right )^T \cdot Y\f] + (since \f$C^{(N)}\f$ is an orthogonal matrix, \f$C^{(N)} \cdot \left(C^{(N)}\right)^T = I\f$ ) +- Forward 2D Cosine transform of M x N matrix: + \f[Y = C^{(N)} \cdot X \cdot \left (C^{(N)} \right )^T\f] +- Inverse 2D Cosine transform of M x N matrix: + \f[X = \left (C^{(N)} \right )^T \cdot X \cdot C^{(N)}\f] + +The function chooses the mode of operation by looking at the flags and size of the input array: +- If (flags & #DCT_INVERSE) == 0, the function does a forward 1D or 2D transform. Otherwise, it + is an inverse 1D or 2D transform. +- If (flags & #DCT_ROWS) != 0, the function performs a 1D transform of each row. +- If the array is a single column or a single row, the function performs a 1D transform. +- If none of the above is true, the function performs a 2D transform. + +@note Currently dct supports even-size arrays (2, 4, 6 ...). For data analysis and approximation, you +can pad the array when necessary. +Also, the function performance depends very much, and not monotonically, on the array size (see +getOptimalDFTSize ). In the current implementation DCT of a vector of size N is calculated via DFT +of a vector of size N/2 . Thus, the optimal DCT size N1 \>= N can be calculated as: +@code + size_t getOptimalDCTSize(size_t N) { return 2*getOptimalDFTSize((N+1)/2); } + N1 = getOptimalDCTSize(N); +@endcode +@param src input floating-point array. +@param dst output array of the same size and type as src . +@param flags transformation flags as a combination of cv::DftFlags (DCT_*) +@sa dft, getOptimalDFTSize, idct +*/ +CV_EXPORTS_W void dct(InputArray src, OutputArray dst, int flags = 0); + +/** @brief Calculates the inverse Discrete Cosine Transform of a 1D or 2D array. + +idct(src, dst, flags) is equivalent to dct(src, dst, flags | DCT_INVERSE). +@param src input floating-point single-channel array. +@param dst output array of the same size and type as src. +@param flags operation flags. +@sa dct, dft, idft, getOptimalDFTSize +*/ +CV_EXPORTS_W void idct(InputArray src, OutputArray dst, int flags = 0); + +/** @brief Performs the per-element multiplication of two Fourier spectrums. + +The function cv::mulSpectrums performs the per-element multiplication of the two CCS-packed or complex +matrices that are results of a real or complex Fourier transform. + +The function, together with dft and idft, may be used to calculate convolution (pass conjB=false ) +or correlation (pass conjB=true ) of two arrays rapidly. When the arrays are complex, they are +simply multiplied (per element) with an optional conjugation of the second-array elements. When the +arrays are real, they are assumed to be CCS-packed (see dft for details). +@param a first input array. +@param b second input array of the same size and type as src1 . +@param c output array of the same size and type as src1 . +@param flags operation flags; currently, the only supported flag is cv::DFT_ROWS, which indicates that +each row of src1 and src2 is an independent 1D Fourier spectrum. If you do not want to use this flag, then simply add a `0` as value. +@param conjB optional flag that conjugates the second input array before the multiplication (true) +or not (false). +*/ +CV_EXPORTS_W void mulSpectrums(InputArray a, InputArray b, OutputArray c, + int flags, bool conjB = false); + +/** @brief Returns the optimal DFT size for a given vector size. + +DFT performance is not a monotonic function of a vector size. Therefore, when you calculate +convolution of two arrays or perform the spectral analysis of an array, it usually makes sense to +pad the input data with zeros to get a bit larger array that can be transformed much faster than the +original one. Arrays whose size is a power-of-two (2, 4, 8, 16, 32, ...) are the fastest to process. +Though, the arrays whose size is a product of 2's, 3's, and 5's (for example, 300 = 5\*5\*3\*2\*2) +are also processed quite efficiently. + +The function cv::getOptimalDFTSize returns the minimum number N that is greater than or equal to vecsize +so that the DFT of a vector of size N can be processed efficiently. In the current implementation N += 2 ^p^ \* 3 ^q^ \* 5 ^r^ for some integer p, q, r. + +The function returns a negative number if vecsize is too large (very close to INT_MAX ). + +While the function cannot be used directly to estimate the optimal vector size for DCT transform +(since the current DCT implementation supports only even-size vectors), it can be easily processed +as getOptimalDFTSize((vecsize+1)/2)\*2. +@param vecsize vector size. +@sa dft, dct, idft, idct, mulSpectrums +*/ +CV_EXPORTS_W int getOptimalDFTSize(int vecsize); + +/** @brief Returns the default random number generator. + +The function cv::theRNG returns the default random number generator. For each thread, there is a +separate random number generator, so you can use the function safely in multi-thread environments. +If you just need to get a single random number using this generator or initialize an array, you can +use randu or randn instead. But if you are going to generate many random numbers inside a loop, it +is much faster to use this function to retrieve the generator and then use RNG::operator _Tp() . +@sa RNG, randu, randn +*/ +CV_EXPORTS RNG& theRNG(); + +/** @brief Sets state of default random number generator. + +The function cv::setRNGSeed sets state of default random number generator to custom value. +@param seed new state for default random number generator +@sa RNG, randu, randn +*/ +CV_EXPORTS_W void setRNGSeed(int seed); + +/** @brief Generates a single uniformly-distributed random number or an array of random numbers. + +Non-template variant of the function fills the matrix dst with uniformly-distributed +random numbers from the specified range: +\f[\texttt{low} _c \leq \texttt{dst} (I)_c < \texttt{high} _c\f] +@param dst output array of random numbers; the array must be pre-allocated. +@param low inclusive lower boundary of the generated random numbers. +@param high exclusive upper boundary of the generated random numbers. +@sa RNG, randn, theRNG +*/ +CV_EXPORTS_W void randu(InputOutputArray dst, InputArray low, InputArray high); + +/** @brief Fills the array with normally distributed random numbers. + +The function cv::randn fills the matrix dst with normally distributed random numbers with the specified +mean vector and the standard deviation matrix. The generated random numbers are clipped to fit the +value range of the output array data type. +@param dst output array of random numbers; the array must be pre-allocated and have 1 to 4 channels. +@param mean mean value (expectation) of the generated random numbers. +@param stddev standard deviation of the generated random numbers; it can be either a vector (in +which case a diagonal standard deviation matrix is assumed) or a square matrix. +@sa RNG, randu +*/ +CV_EXPORTS_W void randn(InputOutputArray dst, InputArray mean, InputArray stddev); + +/** @brief Shuffles the array elements randomly. + +The function cv::randShuffle shuffles the specified 1D array by randomly choosing pairs of elements and +swapping them. The number of such swap operations will be dst.rows\*dst.cols\*iterFactor . +@param dst input/output numerical 1D array. +@param iterFactor scale factor that determines the number of random swap operations (see the details +below). +@param rng optional random number generator used for shuffling; if it is zero, theRNG () is used +instead. +@sa RNG, sort +*/ +CV_EXPORTS_W void randShuffle(InputOutputArray dst, double iterFactor = 1., RNG* rng = 0); + +/** @brief Principal Component Analysis + +The class is used to calculate a special basis for a set of vectors. The +basis will consist of eigenvectors of the covariance matrix calculated +from the input set of vectors. The class %PCA can also transform +vectors to/from the new coordinate space defined by the basis. Usually, +in this new coordinate system, each vector from the original set (and +any linear combination of such vectors) can be quite accurately +approximated by taking its first few components, corresponding to the +eigenvectors of the largest eigenvalues of the covariance matrix. +Geometrically it means that you calculate a projection of the vector to +a subspace formed by a few eigenvectors corresponding to the dominant +eigenvalues of the covariance matrix. And usually such a projection is +very close to the original vector. So, you can represent the original +vector from a high-dimensional space with a much shorter vector +consisting of the projected vector's coordinates in the subspace. Such a +transformation is also known as Karhunen-Loeve Transform, or KLT. +See http://en.wikipedia.org/wiki/Principal_component_analysis + +The sample below is the function that takes two matrices. The first +function stores a set of vectors (a row per vector) that is used to +calculate PCA. The second function stores another "test" set of vectors +(a row per vector). First, these vectors are compressed with PCA, then +reconstructed back, and then the reconstruction error norm is computed +and printed for each vector. : + +@code{.cpp} +using namespace cv; + +PCA compressPCA(const Mat& pcaset, int maxComponents, + const Mat& testset, Mat& compressed) +{ + PCA pca(pcaset, // pass the data + Mat(), // we do not have a pre-computed mean vector, + // so let the PCA engine to compute it + PCA::DATA_AS_ROW, // indicate that the vectors + // are stored as matrix rows + // (use PCA::DATA_AS_COL if the vectors are + // the matrix columns) + maxComponents // specify, how many principal components to retain + ); + // if there is no test data, just return the computed basis, ready-to-use + if( !testset.data ) + return pca; + CV_Assert( testset.cols == pcaset.cols ); + + compressed.create(testset.rows, maxComponents, testset.type()); + + Mat reconstructed; + for( int i = 0; i < testset.rows; i++ ) + { + Mat vec = testset.row(i), coeffs = compressed.row(i), reconstructed; + // compress the vector, the result will be stored + // in the i-th row of the output matrix + pca.project(vec, coeffs); + // and then reconstruct it + pca.backProject(coeffs, reconstructed); + // and measure the error + printf("%d. diff = %g\n", i, norm(vec, reconstructed, NORM_L2)); + } + return pca; +} +@endcode +@sa calcCovarMatrix, mulTransposed, SVD, dft, dct +*/ +class CV_EXPORTS PCA +{ +public: + enum Flags { DATA_AS_ROW = 0, //!< indicates that the input samples are stored as matrix rows + DATA_AS_COL = 1, //!< indicates that the input samples are stored as matrix columns + USE_AVG = 2 //! + }; + + /** @brief default constructor + + The default constructor initializes an empty %PCA structure. The other + constructors initialize the structure and call PCA::operator()(). + */ + PCA(); + + /** @overload + @param data input samples stored as matrix rows or matrix columns. + @param mean optional mean value; if the matrix is empty (@c noArray()), + the mean is computed from the data. + @param flags operation flags; currently the parameter is only used to + specify the data layout (PCA::Flags) + @param maxComponents maximum number of components that %PCA should + retain; by default, all the components are retained. + */ + PCA(InputArray data, InputArray mean, int flags, int maxComponents = 0); + + /** @overload + @param data input samples stored as matrix rows or matrix columns. + @param mean optional mean value; if the matrix is empty (noArray()), + the mean is computed from the data. + @param flags operation flags; currently the parameter is only used to + specify the data layout (PCA::Flags) + @param retainedVariance Percentage of variance that PCA should retain. + Using this parameter will let the PCA decided how many components to + retain but it will always keep at least 2. + */ + PCA(InputArray data, InputArray mean, int flags, double retainedVariance); + + /** @brief performs %PCA + + The operator performs %PCA of the supplied dataset. It is safe to reuse + the same PCA structure for multiple datasets. That is, if the structure + has been previously used with another dataset, the existing internal + data is reclaimed and the new @ref eigenvalues, @ref eigenvectors and @ref + mean are allocated and computed. + + The computed @ref eigenvalues are sorted from the largest to the smallest and + the corresponding @ref eigenvectors are stored as eigenvectors rows. + + @param data input samples stored as the matrix rows or as the matrix + columns. + @param mean optional mean value; if the matrix is empty (noArray()), + the mean is computed from the data. + @param flags operation flags; currently the parameter is only used to + specify the data layout. (Flags) + @param maxComponents maximum number of components that PCA should + retain; by default, all the components are retained. + */ + PCA& operator()(InputArray data, InputArray mean, int flags, int maxComponents = 0); + + /** @overload + @param data input samples stored as the matrix rows or as the matrix + columns. + @param mean optional mean value; if the matrix is empty (noArray()), + the mean is computed from the data. + @param flags operation flags; currently the parameter is only used to + specify the data layout. (PCA::Flags) + @param retainedVariance Percentage of variance that %PCA should retain. + Using this parameter will let the %PCA decided how many components to + retain but it will always keep at least 2. + */ + PCA& operator()(InputArray data, InputArray mean, int flags, double retainedVariance); + + /** @brief Projects vector(s) to the principal component subspace. + + The methods project one or more vectors to the principal component + subspace, where each vector projection is represented by coefficients in + the principal component basis. The first form of the method returns the + matrix that the second form writes to the result. So the first form can + be used as a part of expression while the second form can be more + efficient in a processing loop. + @param vec input vector(s); must have the same dimensionality and the + same layout as the input data used at %PCA phase, that is, if + DATA_AS_ROW are specified, then `vec.cols==data.cols` + (vector dimensionality) and `vec.rows` is the number of vectors to + project, and the same is true for the PCA::DATA_AS_COL case. + */ + Mat project(InputArray vec) const; + + /** @overload + @param vec input vector(s); must have the same dimensionality and the + same layout as the input data used at PCA phase, that is, if + DATA_AS_ROW are specified, then `vec.cols==data.cols` + (vector dimensionality) and `vec.rows` is the number of vectors to + project, and the same is true for the PCA::DATA_AS_COL case. + @param result output vectors; in case of PCA::DATA_AS_COL, the + output matrix has as many columns as the number of input vectors, this + means that `result.cols==vec.cols` and the number of rows match the + number of principal components (for example, `maxComponents` parameter + passed to the constructor). + */ + void project(InputArray vec, OutputArray result) const; + + /** @brief Reconstructs vectors from their PC projections. + + The methods are inverse operations to PCA::project. They take PC + coordinates of projected vectors and reconstruct the original vectors. + Unless all the principal components have been retained, the + reconstructed vectors are different from the originals. But typically, + the difference is small if the number of components is large enough (but + still much smaller than the original vector dimensionality). As a + result, PCA is used. + @param vec coordinates of the vectors in the principal component + subspace, the layout and size are the same as of PCA::project output + vectors. + */ + Mat backProject(InputArray vec) const; + + /** @overload + @param vec coordinates of the vectors in the principal component + subspace, the layout and size are the same as of PCA::project output + vectors. + @param result reconstructed vectors; the layout and size are the same as + of PCA::project input vectors. + */ + void backProject(InputArray vec, OutputArray result) const; + + /** @brief write PCA objects + + Writes @ref eigenvalues @ref eigenvectors and @ref mean to specified FileStorage + */ + void write(FileStorage& fs) const; + + /** @brief load PCA objects + + Loads @ref eigenvalues @ref eigenvectors and @ref mean from specified FileNode + */ + void read(const FileNode& fn); + + Mat eigenvectors; //!< eigenvectors of the covariation matrix + Mat eigenvalues; //!< eigenvalues of the covariation matrix + Mat mean; //!< mean value subtracted before the projection and added after the back projection +}; + +/** @example samples/cpp/pca.cpp +An example using %PCA for dimensionality reduction while maintaining an amount of variance +*/ + +/** @example samples/cpp/tutorial_code/ml/introduction_to_pca/introduction_to_pca.cpp +Check @ref tutorial_introduction_to_pca "the corresponding tutorial" for more details +*/ + +/** +@brief Linear Discriminant Analysis +@todo document this class +*/ +class CV_EXPORTS LDA +{ +public: + /** @brief constructor + Initializes a LDA with num_components (default 0). + */ + explicit LDA(int num_components = 0); + + /** Initializes and performs a Discriminant Analysis with Fisher's + Optimization Criterion on given data in src and corresponding labels + in labels. If 0 (or less) number of components are given, they are + automatically determined for given data in computation. + */ + LDA(InputArrayOfArrays src, InputArray labels, int num_components = 0); + + /** Serializes this object to a given filename. + */ + void save(const String& filename) const; + + /** Deserializes this object from a given filename. + */ + void load(const String& filename); + + /** Serializes this object to a given cv::FileStorage. + */ + void save(FileStorage& fs) const; + + /** Deserializes this object from a given cv::FileStorage. + */ + void load(const FileStorage& node); + + /** destructor + */ + ~LDA(); + + /** Compute the discriminants for data in src (row aligned) and labels. + */ + void compute(InputArrayOfArrays src, InputArray labels); + + /** Projects samples into the LDA subspace. + src may be one or more row aligned samples. + */ + Mat project(InputArray src); + + /** Reconstructs projections from the LDA subspace. + src may be one or more row aligned projections. + */ + Mat reconstruct(InputArray src); + + /** Returns the eigenvectors of this LDA. + */ + Mat eigenvectors() const { return _eigenvectors; } + + /** Returns the eigenvalues of this LDA. + */ + Mat eigenvalues() const { return _eigenvalues; } + + static Mat subspaceProject(InputArray W, InputArray mean, InputArray src); + static Mat subspaceReconstruct(InputArray W, InputArray mean, InputArray src); + +protected: + int _num_components; + Mat _eigenvectors; + Mat _eigenvalues; + void lda(InputArrayOfArrays src, InputArray labels); +}; + +/** @brief Singular Value Decomposition + +Class for computing Singular Value Decomposition of a floating-point +matrix. The Singular Value Decomposition is used to solve least-square +problems, under-determined linear systems, invert matrices, compute +condition numbers, and so on. + +If you want to compute a condition number of a matrix or an absolute value of +its determinant, you do not need `u` and `vt`. You can pass +flags=SVD::NO_UV|... . Another flag SVD::FULL_UV indicates that full-size u +and vt must be computed, which is not necessary most of the time. + +@sa invert, solve, eigen, determinant +*/ +class CV_EXPORTS SVD +{ +public: + enum Flags { + /** allow the algorithm to modify the decomposed matrix; it can save space and speed up + processing. currently ignored. */ + MODIFY_A = 1, + /** indicates that only a vector of singular values `w` is to be processed, while u and vt + will be set to empty matrices */ + NO_UV = 2, + /** when the matrix is not square, by default the algorithm produces u and vt matrices of + sufficiently large size for the further A reconstruction; if, however, FULL_UV flag is + specified, u and vt will be full-size square orthogonal matrices.*/ + FULL_UV = 4 + }; + + /** @brief the default constructor + + initializes an empty SVD structure + */ + SVD(); + + /** @overload + initializes an empty SVD structure and then calls SVD::operator() + @param src decomposed matrix. The depth has to be CV_32F or CV_64F. + @param flags operation flags (SVD::Flags) + */ + SVD( InputArray src, int flags = 0 ); + + /** @brief the operator that performs SVD. The previously allocated u, w and vt are released. + + The operator performs the singular value decomposition of the supplied + matrix. The u,`vt` , and the vector of singular values w are stored in + the structure. The same SVD structure can be reused many times with + different matrices. Each time, if needed, the previous u,`vt` , and w + are reclaimed and the new matrices are created, which is all handled by + Mat::create. + @param src decomposed matrix. The depth has to be CV_32F or CV_64F. + @param flags operation flags (SVD::Flags) + */ + SVD& operator ()( InputArray src, int flags = 0 ); + + /** @brief decomposes matrix and stores the results to user-provided matrices + + The methods/functions perform SVD of matrix. Unlike SVD::SVD constructor + and SVD::operator(), they store the results to the user-provided + matrices: + + @code{.cpp} + Mat A, w, u, vt; + SVD::compute(A, w, u, vt); + @endcode + + @param src decomposed matrix. The depth has to be CV_32F or CV_64F. + @param w calculated singular values + @param u calculated left singular vectors + @param vt transposed matrix of right singular vectors + @param flags operation flags - see SVD::Flags. + */ + static void compute( InputArray src, OutputArray w, + OutputArray u, OutputArray vt, int flags = 0 ); + + /** @overload + computes singular values of a matrix + @param src decomposed matrix. The depth has to be CV_32F or CV_64F. + @param w calculated singular values + @param flags operation flags - see SVD::Flags. + */ + static void compute( InputArray src, OutputArray w, int flags = 0 ); + + /** @brief performs back substitution + */ + static void backSubst( InputArray w, InputArray u, + InputArray vt, InputArray rhs, + OutputArray dst ); + + /** @brief solves an under-determined singular linear system + + The method finds a unit-length solution x of a singular linear system + A\*x = 0. Depending on the rank of A, there can be no solutions, a + single solution or an infinite number of solutions. In general, the + algorithm solves the following problem: + \f[dst = \arg \min _{x: \| x \| =1} \| src \cdot x \|\f] + @param src left-hand-side matrix. + @param dst found solution. + */ + static void solveZ( InputArray src, OutputArray dst ); + + /** @brief performs a singular value back substitution. + + The method calculates a back substitution for the specified right-hand + side: + + \f[\texttt{x} = \texttt{vt} ^T \cdot diag( \texttt{w} )^{-1} \cdot \texttt{u} ^T \cdot \texttt{rhs} \sim \texttt{A} ^{-1} \cdot \texttt{rhs}\f] + + Using this technique you can either get a very accurate solution of the + convenient linear system, or the best (in the least-squares terms) + pseudo-solution of an overdetermined linear system. + + @param rhs right-hand side of a linear system (u\*w\*v')\*dst = rhs to + be solved, where A has been previously decomposed. + + @param dst found solution of the system. + + @note Explicit SVD with the further back substitution only makes sense + if you need to solve many linear systems with the same left-hand side + (for example, src ). If all you need is to solve a single system + (possibly with multiple rhs immediately available), simply call solve + add pass #DECOMP_SVD there. It does absolutely the same thing. + */ + void backSubst( InputArray rhs, OutputArray dst ) const; + + /** @todo document */ + template static + void compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt ); + + /** @todo document */ + template static + void compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w ); + + /** @todo document */ + template static + void backSubst( const Matx<_Tp, nm, 1>& w, const Matx<_Tp, m, nm>& u, const Matx<_Tp, n, nm>& vt, const Matx<_Tp, m, nb>& rhs, Matx<_Tp, n, nb>& dst ); + + Mat u, w, vt; +}; + +/** @brief Random Number Generator + +Random number generator. It encapsulates the state (currently, a 64-bit +integer) and has methods to return scalar random values and to fill +arrays with random values. Currently it supports uniform and Gaussian +(normal) distributions. The generator uses Multiply-With-Carry +algorithm, introduced by G. Marsaglia ( + ). +Gaussian-distribution random numbers are generated using the Ziggurat +algorithm ( ), +introduced by G. Marsaglia and W. W. Tsang. +*/ +class CV_EXPORTS RNG +{ +public: + enum { UNIFORM = 0, + NORMAL = 1 + }; + + /** @brief constructor + + These are the RNG constructors. The first form sets the state to some + pre-defined value, equal to 2\*\*32-1 in the current implementation. The + second form sets the state to the specified value. If you passed state=0 + , the constructor uses the above default value instead to avoid the + singular random number sequence, consisting of all zeros. + */ + RNG(); + /** @overload + @param state 64-bit value used to initialize the RNG. + */ + RNG(uint64 state); + /**The method updates the state using the MWC algorithm and returns the + next 32-bit random number.*/ + unsigned next(); + + /**Each of the methods updates the state using the MWC algorithm and + returns the next random number of the specified type. In case of integer + types, the returned number is from the available value range for the + specified type. In case of floating-point types, the returned value is + from [0,1) range. + */ + operator uchar(); + /** @overload */ + operator schar(); + /** @overload */ + operator ushort(); + /** @overload */ + operator short(); + /** @overload */ + operator unsigned(); + /** @overload */ + operator int(); + /** @overload */ + operator float(); + /** @overload */ + operator double(); + + /** @brief returns a random integer sampled uniformly from [0, N). + + The methods transform the state using the MWC algorithm and return the + next random number. The first form is equivalent to RNG::next . The + second form returns the random number modulo N, which means that the + result is in the range [0, N) . + */ + unsigned operator ()(); + /** @overload + @param N upper non-inclusive boundary of the returned random number. + */ + unsigned operator ()(unsigned N); + + /** @brief returns uniformly distributed integer random number from [a,b) range + + The methods transform the state using the MWC algorithm and return the + next uniformly-distributed random number of the specified type, deduced + from the input parameter type, from the range [a, b) . There is a nuance + illustrated by the following sample: + + @code{.cpp} + RNG rng; + + // always produces 0 + double a = rng.uniform(0, 1); + + // produces double from [0, 1) + double a1 = rng.uniform((double)0, (double)1); + + // produces float from [0, 1) + float b = rng.uniform(0.f, 1.f); + + // produces double from [0, 1) + double c = rng.uniform(0., 1.); + + // may cause compiler error because of ambiguity: + // RNG::uniform(0, (int)0.999999)? or RNG::uniform((double)0, 0.99999)? + double d = rng.uniform(0, 0.999999); + @endcode + + The compiler does not take into account the type of the variable to + which you assign the result of RNG::uniform . The only thing that + matters to the compiler is the type of a and b parameters. So, if you + want a floating-point random number, but the range boundaries are + integer numbers, either put dots in the end, if they are constants, or + use explicit type cast operators, as in the a1 initialization above. + @param a lower inclusive boundary of the returned random number. + @param b upper non-inclusive boundary of the returned random number. + */ + int uniform(int a, int b); + /** @overload */ + float uniform(float a, float b); + /** @overload */ + double uniform(double a, double b); + + /** @brief Fills arrays with random numbers. + + @param mat 2D or N-dimensional matrix; currently matrices with more than + 4 channels are not supported by the methods, use Mat::reshape as a + possible workaround. + @param distType distribution type, RNG::UNIFORM or RNG::NORMAL. + @param a first distribution parameter; in case of the uniform + distribution, this is an inclusive lower boundary, in case of the normal + distribution, this is a mean value. + @param b second distribution parameter; in case of the uniform + distribution, this is a non-inclusive upper boundary, in case of the + normal distribution, this is a standard deviation (diagonal of the + standard deviation matrix or the full standard deviation matrix). + @param saturateRange pre-saturation flag; for uniform distribution only; + if true, the method will first convert a and b to the acceptable value + range (according to the mat datatype) and then will generate uniformly + distributed random numbers within the range [saturate(a), saturate(b)), + if saturateRange=false, the method will generate uniformly distributed + random numbers in the original range [a, b) and then will saturate them, + it means, for example, that + theRNG().fill(mat_8u, RNG::UNIFORM, -DBL_MAX, DBL_MAX) will likely + produce array mostly filled with 0's and 255's, since the range (0, 255) + is significantly smaller than [-DBL_MAX, DBL_MAX). + + Each of the methods fills the matrix with the random values from the + specified distribution. As the new numbers are generated, the RNG state + is updated accordingly. In case of multiple-channel images, every + channel is filled independently, which means that RNG cannot generate + samples from the multi-dimensional Gaussian distribution with + non-diagonal covariance matrix directly. To do that, the method + generates samples from multi-dimensional standard Gaussian distribution + with zero mean and identity covariation matrix, and then transforms them + using transform to get samples from the specified Gaussian distribution. + */ + void fill( InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange = false ); + + /** @brief Returns the next random number sampled from the Gaussian distribution + @param sigma standard deviation of the distribution. + + The method transforms the state using the MWC algorithm and returns the + next random number from the Gaussian distribution N(0,sigma) . That is, + the mean value of the returned random numbers is zero and the standard + deviation is the specified sigma . + */ + double gaussian(double sigma); + + uint64 state; + + bool operator ==(const RNG& other) const; +}; + +/** @brief Mersenne Twister random number generator + +Inspired by http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c +@todo document +*/ +class CV_EXPORTS RNG_MT19937 +{ +public: + RNG_MT19937(); + RNG_MT19937(unsigned s); + void seed(unsigned s); + + unsigned next(); + + operator int(); + operator unsigned(); + operator float(); + operator double(); + + unsigned operator ()(unsigned N); + unsigned operator ()(); + + /** @brief returns uniformly distributed integer random number from [a,b) range*/ + int uniform(int a, int b); + /** @brief returns uniformly distributed floating-point random number from [a,b) range*/ + float uniform(float a, float b); + /** @brief returns uniformly distributed double-precision floating-point random number from [a,b) range*/ + double uniform(double a, double b); + +private: + enum PeriodParameters {N = 624, M = 397}; + unsigned state[N]; + int mti; +}; + +//! @} core_array + +//! @addtogroup core_cluster +//! @{ + +//! k-means flags +enum KmeansFlags { + /** Select random initial centers in each attempt.*/ + KMEANS_RANDOM_CENTERS = 0, + /** Use kmeans++ center initialization by Arthur and Vassilvitskii [Arthur2007].*/ + KMEANS_PP_CENTERS = 2, + /** During the first (and possibly the only) attempt, use the + user-supplied labels instead of computing them from the initial centers. For the second and + further attempts, use the random or semi-random centers. Use one of KMEANS_\*_CENTERS flag + to specify the exact method.*/ + KMEANS_USE_INITIAL_LABELS = 1 +}; + +/** @example samples/cpp/kmeans.cpp +An example on k-means clustering +*/ + +/** @brief Finds centers of clusters and groups input samples around the clusters. + +The function kmeans implements a k-means algorithm that finds the centers of cluster_count clusters +and groups the input samples around the clusters. As an output, \f$\texttt{bestLabels}_i\f$ contains a +0-based cluster index for the sample stored in the \f$i^{th}\f$ row of the samples matrix. + +@note +- (Python) An example on k-means clustering can be found at + opencv_source_code/samples/python/kmeans.py +@param data Data for clustering. An array of N-Dimensional points with float coordinates is needed. +Examples of this array can be: +- Mat points(count, 2, CV_32F); +- Mat points(count, 1, CV_32FC2); +- Mat points(1, count, CV_32FC2); +- std::vector\ points(sampleCount); +@param K Number of clusters to split the set by. +@param bestLabels Input/output integer array that stores the cluster indices for every sample. +@param criteria The algorithm termination criteria, that is, the maximum number of iterations and/or +the desired accuracy. The accuracy is specified as criteria.epsilon. As soon as each of the cluster +centers moves by less than criteria.epsilon on some iteration, the algorithm stops. +@param attempts Flag to specify the number of times the algorithm is executed using different +initial labellings. The algorithm returns the labels that yield the best compactness (see the last +function parameter). +@param flags Flag that can take values of cv::KmeansFlags +@param centers Output matrix of the cluster centers, one row per each cluster center. +@return The function returns the compactness measure that is computed as +\f[\sum _i \| \texttt{samples} _i - \texttt{centers} _{ \texttt{labels} _i} \| ^2\f] +after every attempt. The best (minimum) value is chosen and the corresponding labels and the +compactness value are returned by the function. Basically, you can use only the core of the +function, set the number of attempts to 1, initialize labels each time using a custom algorithm, +pass them with the ( flags = #KMEANS_USE_INITIAL_LABELS ) flag, and then choose the best +(most-compact) clustering. +*/ +CV_EXPORTS_W double kmeans( InputArray data, int K, InputOutputArray bestLabels, + TermCriteria criteria, int attempts, + int flags, OutputArray centers = noArray() ); + +//! @} core_cluster + +//! @addtogroup core_basic +//! @{ + +/////////////////////////////// Formatted output of cv::Mat /////////////////////////// + +/** @todo document */ +class CV_EXPORTS Formatted +{ +public: + virtual const char* next() = 0; + virtual void reset() = 0; + virtual ~Formatted(); +}; + +/** @todo document */ +class CV_EXPORTS Formatter +{ +public: + enum FormatType { + FMT_DEFAULT = 0, + FMT_MATLAB = 1, + FMT_CSV = 2, + FMT_PYTHON = 3, + FMT_NUMPY = 4, + FMT_C = 5 + }; + + virtual ~Formatter(); + + virtual Ptr format(const Mat& mtx) const = 0; + + virtual void set16fPrecision(int p = 4) = 0; + virtual void set32fPrecision(int p = 8) = 0; + virtual void set64fPrecision(int p = 16) = 0; + virtual void setMultiline(bool ml = true) = 0; + + static Ptr get(Formatter::FormatType fmt = FMT_DEFAULT); + +}; + +static inline +String& operator << (String& out, Ptr fmtd) +{ + fmtd->reset(); + for(const char* str = fmtd->next(); str; str = fmtd->next()) + out += cv::String(str); + return out; +} + +static inline +String& operator << (String& out, const Mat& mtx) +{ + return out << Formatter::get()->format(mtx); +} + +//////////////////////////////////////// Algorithm //////////////////////////////////// + +class CV_EXPORTS Algorithm; + +template struct ParamType {}; + + +/** @brief This is a base class for all more or less complex algorithms in OpenCV + +especially for classes of algorithms, for which there can be multiple implementations. The examples +are stereo correspondence (for which there are algorithms like block matching, semi-global block +matching, graph-cut etc.), background subtraction (which can be done using mixture-of-gaussians +models, codebook-based algorithm etc.), optical flow (block matching, Lucas-Kanade, Horn-Schunck +etc.). + +Here is example of SimpleBlobDetector use in your application via Algorithm interface: +@snippet snippets/core_various.cpp Algorithm +*/ +class CV_EXPORTS_W Algorithm +{ +public: + Algorithm(); + virtual ~Algorithm(); + + /** @brief Clears the algorithm state + */ + CV_WRAP virtual void clear() {} + + /** @brief Stores algorithm parameters in a file storage + */ + CV_WRAP virtual void write(FileStorage& fs) const { CV_UNUSED(fs); } + + /** + * @overload + */ + CV_WRAP void write(FileStorage& fs, const String& name) const; +#if CV_VERSION_MAJOR < 5 + /** @deprecated */ + void write(const Ptr& fs, const String& name = String()) const; +#endif + + /** @brief Reads algorithm parameters from a file storage + */ + CV_WRAP virtual void read(const FileNode& fn) { CV_UNUSED(fn); } + + /** @brief Returns true if the Algorithm is empty (e.g. in the very beginning or after unsuccessful read + */ + CV_WRAP virtual bool empty() const { return false; } + + /** @brief Reads algorithm from the file node + + This is static template method of Algorithm. It's usage is following (in the case of SVM): + @code + cv::FileStorage fsRead("example.xml", FileStorage::READ); + Ptr svm = Algorithm::read(fsRead.root()); + @endcode + In order to make this method work, the derived class must overwrite Algorithm::read(const + FileNode& fn) and also have static create() method without parameters + (or with all the optional parameters) + */ + template static Ptr<_Tp> read(const FileNode& fn) + { + Ptr<_Tp> obj = _Tp::create(); + obj->read(fn); + return !obj->empty() ? obj : Ptr<_Tp>(); + } + + /** @brief Loads algorithm from the file + + @param filename Name of the file to read. + @param objname The optional name of the node to read (if empty, the first top-level node will be used) + + This is static template method of Algorithm. It's usage is following (in the case of SVM): + @code + Ptr svm = Algorithm::load("my_svm_model.xml"); + @endcode + In order to make this method work, the derived class must overwrite Algorithm::read(const + FileNode& fn). + */ + template static Ptr<_Tp> load(const String& filename, const String& objname=String()) + { + FileStorage fs(filename, FileStorage::READ); + CV_Assert(fs.isOpened()); + FileNode fn = objname.empty() ? fs.getFirstTopLevelNode() : fs[objname]; + if (fn.empty()) return Ptr<_Tp>(); + Ptr<_Tp> obj = _Tp::create(); + obj->read(fn); + return !obj->empty() ? obj : Ptr<_Tp>(); + } + + /** @brief Loads algorithm from a String + + @param strModel The string variable containing the model you want to load. + @param objname The optional name of the node to read (if empty, the first top-level node will be used) + + This is static template method of Algorithm. It's usage is following (in the case of SVM): + @code + Ptr svm = Algorithm::loadFromString(myStringModel); + @endcode + */ + template static Ptr<_Tp> loadFromString(const String& strModel, const String& objname=String()) + { + FileStorage fs(strModel, FileStorage::READ + FileStorage::MEMORY); + FileNode fn = objname.empty() ? fs.getFirstTopLevelNode() : fs[objname]; + Ptr<_Tp> obj = _Tp::create(); + obj->read(fn); + return !obj->empty() ? obj : Ptr<_Tp>(); + } + + /** Saves the algorithm to a file. + In order to make this method work, the derived class must implement Algorithm::write(FileStorage& fs). */ + CV_WRAP virtual void save(const String& filename) const; + + /** Returns the algorithm string identifier. + This string is used as top level xml/yml node tag when the object is saved to a file or string. */ + CV_WRAP virtual String getDefaultName() const; + +protected: + void writeFormat(FileStorage& fs) const; +}; + +enum struct Param { + INT=0, BOOLEAN=1, REAL=2, STRING=3, MAT=4, MAT_VECTOR=5, ALGORITHM=6, FLOAT=7, + UNSIGNED_INT=8, UINT64=9, UCHAR=11, SCALAR=12 +}; + + + +template<> struct ParamType +{ + typedef bool const_param_type; + typedef bool member_type; + + static const Param type = Param::BOOLEAN; +}; + +template<> struct ParamType +{ + typedef int const_param_type; + typedef int member_type; + + static const Param type = Param::INT; +}; + +template<> struct ParamType +{ + typedef double const_param_type; + typedef double member_type; + + static const Param type = Param::REAL; +}; + +template<> struct ParamType +{ + typedef const String& const_param_type; + typedef String member_type; + + static const Param type = Param::STRING; +}; + +template<> struct ParamType +{ + typedef const Mat& const_param_type; + typedef Mat member_type; + + static const Param type = Param::MAT; +}; + +template<> struct ParamType > +{ + typedef const std::vector& const_param_type; + typedef std::vector member_type; + + static const Param type = Param::MAT_VECTOR; +}; + +template<> struct ParamType +{ + typedef const Ptr& const_param_type; + typedef Ptr member_type; + + static const Param type = Param::ALGORITHM; +}; + +template<> struct ParamType +{ + typedef float const_param_type; + typedef float member_type; + + static const Param type = Param::FLOAT; +}; + +template<> struct ParamType +{ + typedef unsigned const_param_type; + typedef unsigned member_type; + + static const Param type = Param::UNSIGNED_INT; +}; + +template<> struct ParamType +{ + typedef uint64 const_param_type; + typedef uint64 member_type; + + static const Param type = Param::UINT64; +}; + +template<> struct ParamType +{ + typedef uchar const_param_type; + typedef uchar member_type; + + static const Param type = Param::UCHAR; +}; + +template<> struct ParamType +{ + typedef const Scalar& const_param_type; + typedef Scalar member_type; + + static const Param type = Param::SCALAR; +}; + +template +struct ParamType<_Tp, typename std::enable_if< std::is_enum<_Tp>::value >::type> +{ + typedef typename std::underlying_type<_Tp>::type const_param_type; + typedef typename std::underlying_type<_Tp>::type member_type; + + static const Param type = Param::INT; +}; + +//! @} core_basic + +} //namespace cv + +#include "opencv2/core/operations.hpp" +#include "opencv2/core/cvstd.inl.hpp" +#include "opencv2/core/utility.hpp" +#include "opencv2/core/optim.hpp" +#include "opencv2/core/ovx.hpp" + +#endif /*OPENCV_CORE_HPP*/ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/affine.hpp b/3rdParty/opencv-4.11.0/opencv2/core/affine.hpp index 1aebf2b507..bb5774231c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/affine.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/affine.hpp @@ -1,678 +1,678 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CORE_AFFINE3_HPP -#define OPENCV_CORE_AFFINE3_HPP - -#ifdef __cplusplus - -#include - -namespace cv -{ - -//! @addtogroup core_eigen -//! @{ - - /** @brief Affine transform - * - * It represents a 4x4 homogeneous transformation matrix \f$T\f$ - * - * \f[T = - * \begin{bmatrix} - * R & t\\ - * 0 & 1\\ - * \end{bmatrix} - * \f] - * - * where \f$R\f$ is a 3x3 rotation matrix and \f$t\f$ is a 3x1 translation vector. - * - * You can specify \f$R\f$ either by a 3x3 rotation matrix or by a 3x1 rotation vector, - * which is converted to a 3x3 rotation matrix by the Rodrigues formula. - * - * To construct a matrix \f$T\f$ representing first rotation around the axis \f$r\f$ with rotation - * angle \f$|r|\f$ in radian (right hand rule) and then translation by the vector \f$t\f$, you can use - * - * @code - * cv::Vec3f r, t; - * cv::Affine3f T(r, t); - * @endcode - * - * If you already have the rotation matrix \f$R\f$, then you can use - * - * @code - * cv::Matx33f R; - * cv::Affine3f T(R, t); - * @endcode - * - * To extract the rotation matrix \f$R\f$ from \f$T\f$, use - * - * @code - * cv::Matx33f R = T.rotation(); - * @endcode - * - * To extract the translation vector \f$t\f$ from \f$T\f$, use - * - * @code - * cv::Vec3f t = T.translation(); - * @endcode - * - * To extract the rotation vector \f$r\f$ from \f$T\f$, use - * - * @code - * cv::Vec3f r = T.rvec(); - * @endcode - * - * Note that since the mapping from rotation vectors to rotation matrices - * is many to one. The returned rotation vector is not necessarily the one - * you used before to set the matrix. - * - * If you have two transformations \f$T = T_1 * T_2\f$, use - * - * @code - * cv::Affine3f T, T1, T2; - * T = T2.concatenate(T1); - * @endcode - * - * To get the inverse transform of \f$T\f$, use - * - * @code - * cv::Affine3f T, T_inv; - * T_inv = T.inv(); - * @endcode - * - */ - template - class Affine3 - { - public: - typedef T float_type; - typedef Matx Mat3; - typedef Matx Mat4; - typedef Vec Vec3; - - //! Default constructor. It represents a 4x4 identity matrix. - Affine3(); - - //! Augmented affine matrix - Affine3(const Mat4& affine); - - /** - * The resulting 4x4 matrix is - * - * \f[ - * \begin{bmatrix} - * R & t\\ - * 0 & 1\\ - * \end{bmatrix} - * \f] - * - * @param R 3x3 rotation matrix. - * @param t 3x1 translation vector. - */ - Affine3(const Mat3& R, const Vec3& t = Vec3::all(0)); - - /** - * Rodrigues vector. - * - * The last row of the current matrix is set to [0,0,0,1]. - * - * @param rvec 3x1 rotation vector. Its direction indicates the rotation axis and its length - * indicates the rotation angle in radian (using right hand rule). - * @param t 3x1 translation vector. - */ - Affine3(const Vec3& rvec, const Vec3& t = Vec3::all(0)); - - /** - * Combines all constructors above. Supports 4x4, 3x4, 3x3, 1x3, 3x1 sizes of data matrix. - * - * The last row of the current matrix is set to [0,0,0,1] when data is not 4x4. - * - * @param data 1-channel matrix. - * when it is 4x4, it is copied to the current matrix and t is not used. - * When it is 3x4, it is copied to the upper part 3x4 of the current matrix and t is not used. - * When it is 3x3, it is copied to the upper left 3x3 part of the current matrix. - * When it is 3x1 or 1x3, it is treated as a rotation vector and the Rodrigues formula is used - * to compute a 3x3 rotation matrix. - * @param t 3x1 translation vector. It is used only when data is neither 4x4 nor 3x4. - */ - explicit Affine3(const Mat& data, const Vec3& t = Vec3::all(0)); - - //! From 16-element array - explicit Affine3(const float_type* vals); - - //! Create an 4x4 identity transform - static Affine3 Identity(); - - /** - * Rotation matrix. - * - * Copy the rotation matrix to the upper left 3x3 part of the current matrix. - * The remaining elements of the current matrix are not changed. - * - * @param R 3x3 rotation matrix. - * - */ - void rotation(const Mat3& R); - - /** - * Rodrigues vector. - * - * It sets the upper left 3x3 part of the matrix. The remaining part is unaffected. - * - * @param rvec 3x1 rotation vector. The direction indicates the rotation axis and - * its length indicates the rotation angle in radian (using the right thumb convention). - */ - void rotation(const Vec3& rvec); - - /** - * Combines rotation methods above. Supports 3x3, 1x3, 3x1 sizes of data matrix. - * - * It sets the upper left 3x3 part of the matrix. The remaining part is unaffected. - * - * @param data 1-channel matrix. - * When it is a 3x3 matrix, it sets the upper left 3x3 part of the current matrix. - * When it is a 1x3 or 3x1 matrix, it is used as a rotation vector. The Rodrigues formula - * is used to compute the rotation matrix and sets the upper left 3x3 part of the current matrix. - */ - void rotation(const Mat& data); - - /** - * Copy the 3x3 matrix L to the upper left part of the current matrix - * - * It sets the upper left 3x3 part of the matrix. The remaining part is unaffected. - * - * @param L 3x3 matrix. - */ - void linear(const Mat3& L); - - /** - * Copy t to the first three elements of the last column of the current matrix - * - * It sets the upper right 3x1 part of the matrix. The remaining part is unaffected. - * - * @param t 3x1 translation vector. - */ - void translation(const Vec3& t); - - //! @return the upper left 3x3 part - Mat3 rotation() const; - - //! @return the upper left 3x3 part - Mat3 linear() const; - - //! @return the upper right 3x1 part - Vec3 translation() const; - - //! Rodrigues vector. - //! @return a vector representing the upper left 3x3 rotation matrix of the current matrix. - //! @warning Since the mapping between rotation vectors and rotation matrices is many to one, - //! this function returns only one rotation vector that represents the current rotation matrix, - //! which is not necessarily the same one set by `rotation(const Vec3& rvec)`. - Vec3 rvec() const; - - //! @return the inverse of the current matrix. - Affine3 inv(int method = cv::DECOMP_SVD) const; - - //! a.rotate(R) is equivalent to Affine(R, 0) * a; - Affine3 rotate(const Mat3& R) const; - - //! a.rotate(rvec) is equivalent to Affine(rvec, 0) * a; - Affine3 rotate(const Vec3& rvec) const; - - //! a.translate(t) is equivalent to Affine(E, t) * a, where E is an identity matrix - Affine3 translate(const Vec3& t) const; - - //! a.concatenate(affine) is equivalent to affine * a; - Affine3 concatenate(const Affine3& affine) const; - - template operator Affine3() const; - - template Affine3 cast() const; - - Mat4 matrix; - -#if defined EIGEN_WORLD_VERSION && defined EIGEN_GEOMETRY_MODULE_H - Affine3(const Eigen::Transform& affine); - Affine3(const Eigen::Transform& affine); - operator Eigen::Transform() const; - operator Eigen::Transform() const; -#endif - }; - - template static - Affine3 operator*(const Affine3& affine1, const Affine3& affine2); - - //! V is a 3-element vector with member fields x, y and z - template static - V operator*(const Affine3& affine, const V& vector); - - typedef Affine3 Affine3f; - typedef Affine3 Affine3d; - - static Vec3f operator*(const Affine3f& affine, const Vec3f& vector); - static Vec3d operator*(const Affine3d& affine, const Vec3d& vector); - - template class DataType< Affine3<_Tp> > - { - public: - typedef Affine3<_Tp> value_type; - typedef Affine3::work_type> work_type; - typedef _Tp channel_type; - - enum { generic_type = 0, - channels = 16, - fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - ,depth = DataType::depth - ,type = CV_MAKETYPE(depth, channels) -#endif - }; - - typedef Vec vec_type; - }; - - namespace traits { - template - struct Depth< Affine3<_Tp> > { enum { value = Depth<_Tp>::value }; }; - template - struct Type< Affine3<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 16) }; }; - } // namespace - -//! @} core - -} - -//! @cond IGNORED - -/////////////////////////////////////////////////////////////////////////////////// -// Implementation - -template inline -cv::Affine3::Affine3() - : matrix(Mat4::eye()) -{} - -template inline -cv::Affine3::Affine3(const Mat4& affine) - : matrix(affine) -{} - -template inline -cv::Affine3::Affine3(const Mat3& R, const Vec3& t) -{ - rotation(R); - translation(t); - matrix.val[12] = matrix.val[13] = matrix.val[14] = 0; - matrix.val[15] = 1; -} - -template inline -cv::Affine3::Affine3(const Vec3& _rvec, const Vec3& t) -{ - rotation(_rvec); - translation(t); - matrix.val[12] = matrix.val[13] = matrix.val[14] = 0; - matrix.val[15] = 1; -} - -template inline -cv::Affine3::Affine3(const cv::Mat& data, const Vec3& t) -{ - CV_Assert(data.type() == cv::traits::Type::value); - CV_Assert(data.channels() == 1); - - if (data.cols == 4 && data.rows == 4) - { - data.copyTo(matrix); - return; - } - else if (data.cols == 4 && data.rows == 3) - { - rotation(data(Rect(0, 0, 3, 3))); - translation(data(Rect(3, 0, 1, 3))); - } - else - { - rotation(data); - translation(t); - } - - matrix.val[12] = matrix.val[13] = matrix.val[14] = 0; - matrix.val[15] = 1; -} - -template inline -cv::Affine3::Affine3(const float_type* vals) : matrix(vals) -{} - -template inline -cv::Affine3 cv::Affine3::Identity() -{ - return Affine3(cv::Affine3::Mat4::eye()); -} - -template inline -void cv::Affine3::rotation(const Mat3& R) -{ - linear(R); -} - -template inline -void cv::Affine3::rotation(const Vec3& _rvec) -{ - double theta = norm(_rvec); - - if (theta < DBL_EPSILON) - rotation(Mat3::eye()); - else - { - double c = std::cos(theta); - double s = std::sin(theta); - double c1 = 1. - c; - double itheta = (theta != 0) ? 1./theta : 0.; - - Point3_ r = _rvec*itheta; - - Mat3 rrt( r.x*r.x, r.x*r.y, r.x*r.z, r.x*r.y, r.y*r.y, r.y*r.z, r.x*r.z, r.y*r.z, r.z*r.z ); - Mat3 r_x( 0, -r.z, r.y, r.z, 0, -r.x, -r.y, r.x, 0 ); - - // R = cos(theta)*I + (1 - cos(theta))*r*rT + sin(theta)*[r_x] - // where [r_x] is [0 -rz ry; rz 0 -rx; -ry rx 0] - Mat3 R = c*Mat3::eye() + c1*rrt + s*r_x; - - rotation(R); - } -} - -//Combines rotation methods above. Supports 3x3, 1x3, 3x1 sizes of data matrix; -template inline -void cv::Affine3::rotation(const cv::Mat& data) -{ - CV_Assert(data.type() == cv::traits::Type::value); - CV_Assert(data.channels() == 1); - - if (data.cols == 3 && data.rows == 3) - { - Mat3 R; - data.copyTo(R); - rotation(R); - } - else if ((data.cols == 3 && data.rows == 1) || (data.cols == 1 && data.rows == 3)) - { - Vec3 _rvec; - data.reshape(1, 3).copyTo(_rvec); - rotation(_rvec); - } - else - CV_Error(Error::StsError, "Input matrix can only be 3x3, 1x3 or 3x1"); -} - -template inline -void cv::Affine3::linear(const Mat3& L) -{ - matrix.val[0] = L.val[0]; matrix.val[1] = L.val[1]; matrix.val[ 2] = L.val[2]; - matrix.val[4] = L.val[3]; matrix.val[5] = L.val[4]; matrix.val[ 6] = L.val[5]; - matrix.val[8] = L.val[6]; matrix.val[9] = L.val[7]; matrix.val[10] = L.val[8]; -} - -template inline -void cv::Affine3::translation(const Vec3& t) -{ - matrix.val[3] = t[0]; matrix.val[7] = t[1]; matrix.val[11] = t[2]; -} - -template inline -typename cv::Affine3::Mat3 cv::Affine3::rotation() const -{ - return linear(); -} - -template inline -typename cv::Affine3::Mat3 cv::Affine3::linear() const -{ - typename cv::Affine3::Mat3 R; - R.val[0] = matrix.val[0]; R.val[1] = matrix.val[1]; R.val[2] = matrix.val[ 2]; - R.val[3] = matrix.val[4]; R.val[4] = matrix.val[5]; R.val[5] = matrix.val[ 6]; - R.val[6] = matrix.val[8]; R.val[7] = matrix.val[9]; R.val[8] = matrix.val[10]; - return R; -} - -template inline -typename cv::Affine3::Vec3 cv::Affine3::translation() const -{ - return Vec3(matrix.val[3], matrix.val[7], matrix.val[11]); -} - -template inline -typename cv::Affine3::Vec3 cv::Affine3::rvec() const -{ - cv::Vec3d w; - cv::Matx33d u, vt, R = rotation(); - cv::SVD::compute(R, w, u, vt, cv::SVD::FULL_UV + cv::SVD::MODIFY_A); - R = u * vt; - - double rx = R.val[7] - R.val[5]; - double ry = R.val[2] - R.val[6]; - double rz = R.val[3] - R.val[1]; - - double s = std::sqrt((rx*rx + ry*ry + rz*rz)*0.25); - double c = (R.val[0] + R.val[4] + R.val[8] - 1) * 0.5; - c = c > 1.0 ? 1.0 : c < -1.0 ? -1.0 : c; - double theta = std::acos(c); - - if( s < 1e-5 ) - { - if( c > 0 ) - rx = ry = rz = 0; - else - { - double t; - t = (R.val[0] + 1) * 0.5; - rx = std::sqrt(std::max(t, 0.0)); - t = (R.val[4] + 1) * 0.5; - ry = std::sqrt(std::max(t, 0.0)) * (R.val[1] < 0 ? -1.0 : 1.0); - t = (R.val[8] + 1) * 0.5; - rz = std::sqrt(std::max(t, 0.0)) * (R.val[2] < 0 ? -1.0 : 1.0); - - if( fabs(rx) < fabs(ry) && fabs(rx) < fabs(rz) && (R.val[5] > 0) != (ry*rz > 0) ) - rz = -rz; - theta /= std::sqrt(rx*rx + ry*ry + rz*rz); - rx *= theta; - ry *= theta; - rz *= theta; - } - } - else - { - double vth = 1/(2*s); - vth *= theta; - rx *= vth; ry *= vth; rz *= vth; - } - - return cv::Vec3d(rx, ry, rz); -} - -template inline -cv::Affine3 cv::Affine3::inv(int method) const -{ - return matrix.inv(method); -} - -template inline -cv::Affine3 cv::Affine3::rotate(const Mat3& R) const -{ - Mat3 Lc = linear(); - Vec3 tc = translation(); - Mat4 result; - result.val[12] = result.val[13] = result.val[14] = 0; - result.val[15] = 1; - - for(int j = 0; j < 3; ++j) - { - for(int i = 0; i < 3; ++i) - { - float_type value = 0; - for(int k = 0; k < 3; ++k) - value += R(j, k) * Lc(k, i); - result(j, i) = value; - } - - result(j, 3) = R.row(j).dot(tc.t()); - } - return result; -} - -template inline -cv::Affine3 cv::Affine3::rotate(const Vec3& _rvec) const -{ - return rotate(Affine3f(_rvec).rotation()); -} - -template inline -cv::Affine3 cv::Affine3::translate(const Vec3& t) const -{ - Mat4 m = matrix; - m.val[ 3] += t[0]; - m.val[ 7] += t[1]; - m.val[11] += t[2]; - return m; -} - -template inline -cv::Affine3 cv::Affine3::concatenate(const Affine3& affine) const -{ - return (*this).rotate(affine.rotation()).translate(affine.translation()); -} - -template template inline -cv::Affine3::operator Affine3() const -{ - return Affine3(matrix); -} - -template template inline -cv::Affine3 cv::Affine3::cast() const -{ - return Affine3(matrix); -} - -template inline -cv::Affine3 cv::operator*(const cv::Affine3& affine1, const cv::Affine3& affine2) -{ - return affine2.concatenate(affine1); -} - -template inline -V cv::operator*(const cv::Affine3& affine, const V& v) -{ - const typename Affine3::Mat4& m = affine.matrix; - - V r; - r.x = m.val[0] * v.x + m.val[1] * v.y + m.val[ 2] * v.z + m.val[ 3]; - r.y = m.val[4] * v.x + m.val[5] * v.y + m.val[ 6] * v.z + m.val[ 7]; - r.z = m.val[8] * v.x + m.val[9] * v.y + m.val[10] * v.z + m.val[11]; - return r; -} - -static inline -cv::Vec3f cv::operator*(const cv::Affine3f& affine, const cv::Vec3f& v) -{ - const cv::Matx44f& m = affine.matrix; - cv::Vec3f r; - r.val[0] = m.val[0] * v[0] + m.val[1] * v[1] + m.val[ 2] * v[2] + m.val[ 3]; - r.val[1] = m.val[4] * v[0] + m.val[5] * v[1] + m.val[ 6] * v[2] + m.val[ 7]; - r.val[2] = m.val[8] * v[0] + m.val[9] * v[1] + m.val[10] * v[2] + m.val[11]; - return r; -} - -static inline -cv::Vec3d cv::operator*(const cv::Affine3d& affine, const cv::Vec3d& v) -{ - const cv::Matx44d& m = affine.matrix; - cv::Vec3d r; - r.val[0] = m.val[0] * v[0] + m.val[1] * v[1] + m.val[ 2] * v[2] + m.val[ 3]; - r.val[1] = m.val[4] * v[0] + m.val[5] * v[1] + m.val[ 6] * v[2] + m.val[ 7]; - r.val[2] = m.val[8] * v[0] + m.val[9] * v[1] + m.val[10] * v[2] + m.val[11]; - return r; -} - - - -#if defined EIGEN_WORLD_VERSION && defined EIGEN_GEOMETRY_MODULE_H - -template inline -cv::Affine3::Affine3(const Eigen::Transform& affine) -{ - cv::Mat(4, 4, cv::traits::Type::value, affine.matrix().data()).copyTo(matrix); -} - -template inline -cv::Affine3::Affine3(const Eigen::Transform& affine) -{ - Eigen::Transform a = affine; - cv::Mat(4, 4, cv::traits::Type::value, a.matrix().data()).copyTo(matrix); -} - -template inline -cv::Affine3::operator Eigen::Transform() const -{ - Eigen::Transform r; - cv::Mat hdr(4, 4, cv::traits::Type::value, r.matrix().data()); - cv::Mat(matrix, false).copyTo(hdr); - return r; -} - -template inline -cv::Affine3::operator Eigen::Transform() const -{ - return this->operator Eigen::Transform(); -} - -#endif /* defined EIGEN_WORLD_VERSION && defined EIGEN_GEOMETRY_MODULE_H */ - -//! @endcond - -#endif /* __cplusplus */ - -#endif /* OPENCV_CORE_AFFINE3_HPP */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CORE_AFFINE3_HPP +#define OPENCV_CORE_AFFINE3_HPP + +#ifdef __cplusplus + +#include + +namespace cv +{ + +//! @addtogroup core_eigen +//! @{ + + /** @brief Affine transform + * + * It represents a 4x4 homogeneous transformation matrix \f$T\f$ + * + * \f[T = + * \begin{bmatrix} + * R & t\\ + * 0 & 1\\ + * \end{bmatrix} + * \f] + * + * where \f$R\f$ is a 3x3 rotation matrix and \f$t\f$ is a 3x1 translation vector. + * + * You can specify \f$R\f$ either by a 3x3 rotation matrix or by a 3x1 rotation vector, + * which is converted to a 3x3 rotation matrix by the Rodrigues formula. + * + * To construct a matrix \f$T\f$ representing first rotation around the axis \f$r\f$ with rotation + * angle \f$|r|\f$ in radian (right hand rule) and then translation by the vector \f$t\f$, you can use + * + * @code + * cv::Vec3f r, t; + * cv::Affine3f T(r, t); + * @endcode + * + * If you already have the rotation matrix \f$R\f$, then you can use + * + * @code + * cv::Matx33f R; + * cv::Affine3f T(R, t); + * @endcode + * + * To extract the rotation matrix \f$R\f$ from \f$T\f$, use + * + * @code + * cv::Matx33f R = T.rotation(); + * @endcode + * + * To extract the translation vector \f$t\f$ from \f$T\f$, use + * + * @code + * cv::Vec3f t = T.translation(); + * @endcode + * + * To extract the rotation vector \f$r\f$ from \f$T\f$, use + * + * @code + * cv::Vec3f r = T.rvec(); + * @endcode + * + * Note that since the mapping from rotation vectors to rotation matrices + * is many to one. The returned rotation vector is not necessarily the one + * you used before to set the matrix. + * + * If you have two transformations \f$T = T_1 * T_2\f$, use + * + * @code + * cv::Affine3f T, T1, T2; + * T = T2.concatenate(T1); + * @endcode + * + * To get the inverse transform of \f$T\f$, use + * + * @code + * cv::Affine3f T, T_inv; + * T_inv = T.inv(); + * @endcode + * + */ + template + class Affine3 + { + public: + typedef T float_type; + typedef Matx Mat3; + typedef Matx Mat4; + typedef Vec Vec3; + + //! Default constructor. It represents a 4x4 identity matrix. + Affine3(); + + //! Augmented affine matrix + Affine3(const Mat4& affine); + + /** + * The resulting 4x4 matrix is + * + * \f[ + * \begin{bmatrix} + * R & t\\ + * 0 & 1\\ + * \end{bmatrix} + * \f] + * + * @param R 3x3 rotation matrix. + * @param t 3x1 translation vector. + */ + Affine3(const Mat3& R, const Vec3& t = Vec3::all(0)); + + /** + * Rodrigues vector. + * + * The last row of the current matrix is set to [0,0,0,1]. + * + * @param rvec 3x1 rotation vector. Its direction indicates the rotation axis and its length + * indicates the rotation angle in radian (using right hand rule). + * @param t 3x1 translation vector. + */ + Affine3(const Vec3& rvec, const Vec3& t = Vec3::all(0)); + + /** + * Combines all constructors above. Supports 4x4, 3x4, 3x3, 1x3, 3x1 sizes of data matrix. + * + * The last row of the current matrix is set to [0,0,0,1] when data is not 4x4. + * + * @param data 1-channel matrix. + * when it is 4x4, it is copied to the current matrix and t is not used. + * When it is 3x4, it is copied to the upper part 3x4 of the current matrix and t is not used. + * When it is 3x3, it is copied to the upper left 3x3 part of the current matrix. + * When it is 3x1 or 1x3, it is treated as a rotation vector and the Rodrigues formula is used + * to compute a 3x3 rotation matrix. + * @param t 3x1 translation vector. It is used only when data is neither 4x4 nor 3x4. + */ + explicit Affine3(const Mat& data, const Vec3& t = Vec3::all(0)); + + //! From 16-element array + explicit Affine3(const float_type* vals); + + //! Create an 4x4 identity transform + static Affine3 Identity(); + + /** + * Rotation matrix. + * + * Copy the rotation matrix to the upper left 3x3 part of the current matrix. + * The remaining elements of the current matrix are not changed. + * + * @param R 3x3 rotation matrix. + * + */ + void rotation(const Mat3& R); + + /** + * Rodrigues vector. + * + * It sets the upper left 3x3 part of the matrix. The remaining part is unaffected. + * + * @param rvec 3x1 rotation vector. The direction indicates the rotation axis and + * its length indicates the rotation angle in radian (using the right thumb convention). + */ + void rotation(const Vec3& rvec); + + /** + * Combines rotation methods above. Supports 3x3, 1x3, 3x1 sizes of data matrix. + * + * It sets the upper left 3x3 part of the matrix. The remaining part is unaffected. + * + * @param data 1-channel matrix. + * When it is a 3x3 matrix, it sets the upper left 3x3 part of the current matrix. + * When it is a 1x3 or 3x1 matrix, it is used as a rotation vector. The Rodrigues formula + * is used to compute the rotation matrix and sets the upper left 3x3 part of the current matrix. + */ + void rotation(const Mat& data); + + /** + * Copy the 3x3 matrix L to the upper left part of the current matrix + * + * It sets the upper left 3x3 part of the matrix. The remaining part is unaffected. + * + * @param L 3x3 matrix. + */ + void linear(const Mat3& L); + + /** + * Copy t to the first three elements of the last column of the current matrix + * + * It sets the upper right 3x1 part of the matrix. The remaining part is unaffected. + * + * @param t 3x1 translation vector. + */ + void translation(const Vec3& t); + + //! @return the upper left 3x3 part + Mat3 rotation() const; + + //! @return the upper left 3x3 part + Mat3 linear() const; + + //! @return the upper right 3x1 part + Vec3 translation() const; + + //! Rodrigues vector. + //! @return a vector representing the upper left 3x3 rotation matrix of the current matrix. + //! @warning Since the mapping between rotation vectors and rotation matrices is many to one, + //! this function returns only one rotation vector that represents the current rotation matrix, + //! which is not necessarily the same one set by `rotation(const Vec3& rvec)`. + Vec3 rvec() const; + + //! @return the inverse of the current matrix. + Affine3 inv(int method = cv::DECOMP_SVD) const; + + //! a.rotate(R) is equivalent to Affine(R, 0) * a; + Affine3 rotate(const Mat3& R) const; + + //! a.rotate(rvec) is equivalent to Affine(rvec, 0) * a; + Affine3 rotate(const Vec3& rvec) const; + + //! a.translate(t) is equivalent to Affine(E, t) * a, where E is an identity matrix + Affine3 translate(const Vec3& t) const; + + //! a.concatenate(affine) is equivalent to affine * a; + Affine3 concatenate(const Affine3& affine) const; + + template operator Affine3() const; + + template Affine3 cast() const; + + Mat4 matrix; + +#if defined EIGEN_WORLD_VERSION && defined EIGEN_GEOMETRY_MODULE_H + Affine3(const Eigen::Transform& affine); + Affine3(const Eigen::Transform& affine); + operator Eigen::Transform() const; + operator Eigen::Transform() const; +#endif + }; + + template static + Affine3 operator*(const Affine3& affine1, const Affine3& affine2); + + //! V is a 3-element vector with member fields x, y and z + template static + V operator*(const Affine3& affine, const V& vector); + + typedef Affine3 Affine3f; + typedef Affine3 Affine3d; + + static Vec3f operator*(const Affine3f& affine, const Vec3f& vector); + static Vec3d operator*(const Affine3d& affine, const Vec3d& vector); + + template class DataType< Affine3<_Tp> > + { + public: + typedef Affine3<_Tp> value_type; + typedef Affine3::work_type> work_type; + typedef _Tp channel_type; + + enum { generic_type = 0, + channels = 16, + fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + ,depth = DataType::depth + ,type = CV_MAKETYPE(depth, channels) +#endif + }; + + typedef Vec vec_type; + }; + + namespace traits { + template + struct Depth< Affine3<_Tp> > { enum { value = Depth<_Tp>::value }; }; + template + struct Type< Affine3<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 16) }; }; + } // namespace + +//! @} core + +} + +//! @cond IGNORED + +/////////////////////////////////////////////////////////////////////////////////// +// Implementation + +template inline +cv::Affine3::Affine3() + : matrix(Mat4::eye()) +{} + +template inline +cv::Affine3::Affine3(const Mat4& affine) + : matrix(affine) +{} + +template inline +cv::Affine3::Affine3(const Mat3& R, const Vec3& t) +{ + rotation(R); + translation(t); + matrix.val[12] = matrix.val[13] = matrix.val[14] = 0; + matrix.val[15] = 1; +} + +template inline +cv::Affine3::Affine3(const Vec3& _rvec, const Vec3& t) +{ + rotation(_rvec); + translation(t); + matrix.val[12] = matrix.val[13] = matrix.val[14] = 0; + matrix.val[15] = 1; +} + +template inline +cv::Affine3::Affine3(const cv::Mat& data, const Vec3& t) +{ + CV_Assert(data.type() == cv::traits::Type::value); + CV_Assert(data.channels() == 1); + + if (data.cols == 4 && data.rows == 4) + { + data.copyTo(matrix); + return; + } + else if (data.cols == 4 && data.rows == 3) + { + rotation(data(Rect(0, 0, 3, 3))); + translation(data(Rect(3, 0, 1, 3))); + } + else + { + rotation(data); + translation(t); + } + + matrix.val[12] = matrix.val[13] = matrix.val[14] = 0; + matrix.val[15] = 1; +} + +template inline +cv::Affine3::Affine3(const float_type* vals) : matrix(vals) +{} + +template inline +cv::Affine3 cv::Affine3::Identity() +{ + return Affine3(cv::Affine3::Mat4::eye()); +} + +template inline +void cv::Affine3::rotation(const Mat3& R) +{ + linear(R); +} + +template inline +void cv::Affine3::rotation(const Vec3& _rvec) +{ + double theta = norm(_rvec); + + if (theta < DBL_EPSILON) + rotation(Mat3::eye()); + else + { + double c = std::cos(theta); + double s = std::sin(theta); + double c1 = 1. - c; + double itheta = (theta != 0) ? 1./theta : 0.; + + Point3_ r = _rvec*itheta; + + Mat3 rrt( r.x*r.x, r.x*r.y, r.x*r.z, r.x*r.y, r.y*r.y, r.y*r.z, r.x*r.z, r.y*r.z, r.z*r.z ); + Mat3 r_x( 0, -r.z, r.y, r.z, 0, -r.x, -r.y, r.x, 0 ); + + // R = cos(theta)*I + (1 - cos(theta))*r*rT + sin(theta)*[r_x] + // where [r_x] is [0 -rz ry; rz 0 -rx; -ry rx 0] + Mat3 R = c*Mat3::eye() + c1*rrt + s*r_x; + + rotation(R); + } +} + +//Combines rotation methods above. Supports 3x3, 1x3, 3x1 sizes of data matrix; +template inline +void cv::Affine3::rotation(const cv::Mat& data) +{ + CV_Assert(data.type() == cv::traits::Type::value); + CV_Assert(data.channels() == 1); + + if (data.cols == 3 && data.rows == 3) + { + Mat3 R; + data.copyTo(R); + rotation(R); + } + else if ((data.cols == 3 && data.rows == 1) || (data.cols == 1 && data.rows == 3)) + { + Vec3 _rvec; + data.reshape(1, 3).copyTo(_rvec); + rotation(_rvec); + } + else + CV_Error(Error::StsError, "Input matrix can only be 3x3, 1x3 or 3x1"); +} + +template inline +void cv::Affine3::linear(const Mat3& L) +{ + matrix.val[0] = L.val[0]; matrix.val[1] = L.val[1]; matrix.val[ 2] = L.val[2]; + matrix.val[4] = L.val[3]; matrix.val[5] = L.val[4]; matrix.val[ 6] = L.val[5]; + matrix.val[8] = L.val[6]; matrix.val[9] = L.val[7]; matrix.val[10] = L.val[8]; +} + +template inline +void cv::Affine3::translation(const Vec3& t) +{ + matrix.val[3] = t[0]; matrix.val[7] = t[1]; matrix.val[11] = t[2]; +} + +template inline +typename cv::Affine3::Mat3 cv::Affine3::rotation() const +{ + return linear(); +} + +template inline +typename cv::Affine3::Mat3 cv::Affine3::linear() const +{ + typename cv::Affine3::Mat3 R; + R.val[0] = matrix.val[0]; R.val[1] = matrix.val[1]; R.val[2] = matrix.val[ 2]; + R.val[3] = matrix.val[4]; R.val[4] = matrix.val[5]; R.val[5] = matrix.val[ 6]; + R.val[6] = matrix.val[8]; R.val[7] = matrix.val[9]; R.val[8] = matrix.val[10]; + return R; +} + +template inline +typename cv::Affine3::Vec3 cv::Affine3::translation() const +{ + return Vec3(matrix.val[3], matrix.val[7], matrix.val[11]); +} + +template inline +typename cv::Affine3::Vec3 cv::Affine3::rvec() const +{ + cv::Vec3d w; + cv::Matx33d u, vt, R = rotation(); + cv::SVD::compute(R, w, u, vt, cv::SVD::FULL_UV + cv::SVD::MODIFY_A); + R = u * vt; + + double rx = R.val[7] - R.val[5]; + double ry = R.val[2] - R.val[6]; + double rz = R.val[3] - R.val[1]; + + double s = std::sqrt((rx*rx + ry*ry + rz*rz)*0.25); + double c = (R.val[0] + R.val[4] + R.val[8] - 1) * 0.5; + c = c > 1.0 ? 1.0 : c < -1.0 ? -1.0 : c; + double theta = std::acos(c); + + if( s < 1e-5 ) + { + if( c > 0 ) + rx = ry = rz = 0; + else + { + double t; + t = (R.val[0] + 1) * 0.5; + rx = std::sqrt(std::max(t, 0.0)); + t = (R.val[4] + 1) * 0.5; + ry = std::sqrt(std::max(t, 0.0)) * (R.val[1] < 0 ? -1.0 : 1.0); + t = (R.val[8] + 1) * 0.5; + rz = std::sqrt(std::max(t, 0.0)) * (R.val[2] < 0 ? -1.0 : 1.0); + + if( fabs(rx) < fabs(ry) && fabs(rx) < fabs(rz) && (R.val[5] > 0) != (ry*rz > 0) ) + rz = -rz; + theta /= std::sqrt(rx*rx + ry*ry + rz*rz); + rx *= theta; + ry *= theta; + rz *= theta; + } + } + else + { + double vth = 1/(2*s); + vth *= theta; + rx *= vth; ry *= vth; rz *= vth; + } + + return cv::Vec3d(rx, ry, rz); +} + +template inline +cv::Affine3 cv::Affine3::inv(int method) const +{ + return matrix.inv(method); +} + +template inline +cv::Affine3 cv::Affine3::rotate(const Mat3& R) const +{ + Mat3 Lc = linear(); + Vec3 tc = translation(); + Mat4 result; + result.val[12] = result.val[13] = result.val[14] = 0; + result.val[15] = 1; + + for(int j = 0; j < 3; ++j) + { + for(int i = 0; i < 3; ++i) + { + float_type value = 0; + for(int k = 0; k < 3; ++k) + value += R(j, k) * Lc(k, i); + result(j, i) = value; + } + + result(j, 3) = R.row(j).dot(tc.t()); + } + return result; +} + +template inline +cv::Affine3 cv::Affine3::rotate(const Vec3& _rvec) const +{ + return rotate(Affine3f(_rvec).rotation()); +} + +template inline +cv::Affine3 cv::Affine3::translate(const Vec3& t) const +{ + Mat4 m = matrix; + m.val[ 3] += t[0]; + m.val[ 7] += t[1]; + m.val[11] += t[2]; + return m; +} + +template inline +cv::Affine3 cv::Affine3::concatenate(const Affine3& affine) const +{ + return (*this).rotate(affine.rotation()).translate(affine.translation()); +} + +template template inline +cv::Affine3::operator Affine3() const +{ + return Affine3(matrix); +} + +template template inline +cv::Affine3 cv::Affine3::cast() const +{ + return Affine3(matrix); +} + +template inline +cv::Affine3 cv::operator*(const cv::Affine3& affine1, const cv::Affine3& affine2) +{ + return affine2.concatenate(affine1); +} + +template inline +V cv::operator*(const cv::Affine3& affine, const V& v) +{ + const typename Affine3::Mat4& m = affine.matrix; + + V r; + r.x = m.val[0] * v.x + m.val[1] * v.y + m.val[ 2] * v.z + m.val[ 3]; + r.y = m.val[4] * v.x + m.val[5] * v.y + m.val[ 6] * v.z + m.val[ 7]; + r.z = m.val[8] * v.x + m.val[9] * v.y + m.val[10] * v.z + m.val[11]; + return r; +} + +static inline +cv::Vec3f cv::operator*(const cv::Affine3f& affine, const cv::Vec3f& v) +{ + const cv::Matx44f& m = affine.matrix; + cv::Vec3f r; + r.val[0] = m.val[0] * v[0] + m.val[1] * v[1] + m.val[ 2] * v[2] + m.val[ 3]; + r.val[1] = m.val[4] * v[0] + m.val[5] * v[1] + m.val[ 6] * v[2] + m.val[ 7]; + r.val[2] = m.val[8] * v[0] + m.val[9] * v[1] + m.val[10] * v[2] + m.val[11]; + return r; +} + +static inline +cv::Vec3d cv::operator*(const cv::Affine3d& affine, const cv::Vec3d& v) +{ + const cv::Matx44d& m = affine.matrix; + cv::Vec3d r; + r.val[0] = m.val[0] * v[0] + m.val[1] * v[1] + m.val[ 2] * v[2] + m.val[ 3]; + r.val[1] = m.val[4] * v[0] + m.val[5] * v[1] + m.val[ 6] * v[2] + m.val[ 7]; + r.val[2] = m.val[8] * v[0] + m.val[9] * v[1] + m.val[10] * v[2] + m.val[11]; + return r; +} + + + +#if defined EIGEN_WORLD_VERSION && defined EIGEN_GEOMETRY_MODULE_H + +template inline +cv::Affine3::Affine3(const Eigen::Transform& affine) +{ + cv::Mat(4, 4, cv::traits::Type::value, affine.matrix().data()).copyTo(matrix); +} + +template inline +cv::Affine3::Affine3(const Eigen::Transform& affine) +{ + Eigen::Transform a = affine; + cv::Mat(4, 4, cv::traits::Type::value, a.matrix().data()).copyTo(matrix); +} + +template inline +cv::Affine3::operator Eigen::Transform() const +{ + Eigen::Transform r; + cv::Mat hdr(4, 4, cv::traits::Type::value, r.matrix().data()); + cv::Mat(matrix, false).copyTo(hdr); + return r; +} + +template inline +cv::Affine3::operator Eigen::Transform() const +{ + return this->operator Eigen::Transform(); +} + +#endif /* defined EIGEN_WORLD_VERSION && defined EIGEN_GEOMETRY_MODULE_H */ + +//! @endcond + +#endif /* __cplusplus */ + +#endif /* OPENCV_CORE_AFFINE3_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/async.hpp b/3rdParty/opencv-4.11.0/opencv2/core/async.hpp index 98868a130b..4c56354d28 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/async.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/async.hpp @@ -1,101 +1,101 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_ASYNC_HPP -#define OPENCV_CORE_ASYNC_HPP - -#include - -//#include -#include - -namespace cv { - -/** @addtogroup core_async - -@{ -*/ - - -/** @brief Returns result of asynchronous operations - -Object has attached asynchronous state. -Assignment operator doesn't clone asynchronous state (it is shared between all instances). - -Result can be fetched via get() method only once. - -*/ -class CV_EXPORTS_W AsyncArray -{ -public: - ~AsyncArray() CV_NOEXCEPT; - CV_WRAP AsyncArray() CV_NOEXCEPT; - AsyncArray(const AsyncArray& o) CV_NOEXCEPT; - AsyncArray& operator=(const AsyncArray& o) CV_NOEXCEPT; - CV_WRAP void release() CV_NOEXCEPT; - - /** Fetch the result. - @param[out] dst destination array - - Waits for result until container has valid result. - Throws exception if exception was stored as a result. - - Throws exception on invalid container state. - - @note Result or stored exception can be fetched only once. - */ - CV_WRAP void get(OutputArray dst) const; - - /** Retrieving the result with timeout - @param[out] dst destination array - @param[in] timeoutNs timeout in nanoseconds, -1 for infinite wait - - @returns true if result is ready, false if the timeout has expired - - @note Result or stored exception can be fetched only once. - */ - bool get(OutputArray dst, int64 timeoutNs) const; - - CV_WRAP inline - bool get(OutputArray dst, double timeoutNs) const { return get(dst, (int64)timeoutNs); } - - bool wait_for(int64 timeoutNs) const; - - CV_WRAP inline - bool wait_for(double timeoutNs) const { return wait_for((int64)timeoutNs); } - - CV_WRAP bool valid() const CV_NOEXCEPT; - - inline AsyncArray(AsyncArray&& o) { p = o.p; o.p = NULL; } - inline AsyncArray& operator=(AsyncArray&& o) CV_NOEXCEPT { std::swap(p, o.p); return *this; } - - template - inline bool get(OutputArray dst, const std::chrono::duration<_Rep, _Period>& timeout) - { - return get(dst, (int64)(std::chrono::nanoseconds(timeout).count())); - } - - template - inline bool wait_for(const std::chrono::duration<_Rep, _Period>& timeout) - { - return wait_for((int64)(std::chrono::nanoseconds(timeout).count())); - } - -#if 0 - std::future getFutureMat() const; - std::future getFutureUMat() const; -#endif - - - // PImpl - struct Impl; friend struct Impl; - inline void* _getImpl() const CV_NOEXCEPT { return p; } -protected: - Impl* p; -}; - - -//! @} -} // namespace -#endif // OPENCV_CORE_ASYNC_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_ASYNC_HPP +#define OPENCV_CORE_ASYNC_HPP + +#include + +//#include +#include + +namespace cv { + +/** @addtogroup core_async + +@{ +*/ + + +/** @brief Returns result of asynchronous operations + +Object has attached asynchronous state. +Assignment operator doesn't clone asynchronous state (it is shared between all instances). + +Result can be fetched via get() method only once. + +*/ +class CV_EXPORTS_W AsyncArray +{ +public: + ~AsyncArray() CV_NOEXCEPT; + CV_WRAP AsyncArray() CV_NOEXCEPT; + AsyncArray(const AsyncArray& o) CV_NOEXCEPT; + AsyncArray& operator=(const AsyncArray& o) CV_NOEXCEPT; + CV_WRAP void release() CV_NOEXCEPT; + + /** Fetch the result. + @param[out] dst destination array + + Waits for result until container has valid result. + Throws exception if exception was stored as a result. + + Throws exception on invalid container state. + + @note Result or stored exception can be fetched only once. + */ + CV_WRAP void get(OutputArray dst) const; + + /** Retrieving the result with timeout + @param[out] dst destination array + @param[in] timeoutNs timeout in nanoseconds, -1 for infinite wait + + @returns true if result is ready, false if the timeout has expired + + @note Result or stored exception can be fetched only once. + */ + bool get(OutputArray dst, int64 timeoutNs) const; + + CV_WRAP inline + bool get(OutputArray dst, double timeoutNs) const { return get(dst, (int64)timeoutNs); } + + bool wait_for(int64 timeoutNs) const; + + CV_WRAP inline + bool wait_for(double timeoutNs) const { return wait_for((int64)timeoutNs); } + + CV_WRAP bool valid() const CV_NOEXCEPT; + + inline AsyncArray(AsyncArray&& o) { p = o.p; o.p = NULL; } + inline AsyncArray& operator=(AsyncArray&& o) CV_NOEXCEPT { std::swap(p, o.p); return *this; } + + template + inline bool get(OutputArray dst, const std::chrono::duration<_Rep, _Period>& timeout) + { + return get(dst, (int64)(std::chrono::nanoseconds(timeout).count())); + } + + template + inline bool wait_for(const std::chrono::duration<_Rep, _Period>& timeout) + { + return wait_for((int64)(std::chrono::nanoseconds(timeout).count())); + } + +#if 0 + std::future getFutureMat() const; + std::future getFutureUMat() const; +#endif + + + // PImpl + struct Impl; friend struct Impl; + inline void* _getImpl() const CV_NOEXCEPT { return p; } +protected: + Impl* p; +}; + + +//! @} +} // namespace +#endif // OPENCV_CORE_ASYNC_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/base.hpp b/3rdParty/opencv-4.11.0/opencv2/core/base.hpp index 5e63ae3700..4e810931cb 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/base.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/base.hpp @@ -1,682 +1,682 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2014, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CORE_BASE_HPP -#define OPENCV_CORE_BASE_HPP - -#ifndef __cplusplus -# error base.hpp header must be compiled as C++ -#endif - -#include "opencv2/opencv_modules.hpp" - -#include -#include - -#include "opencv2/core/cvdef.h" -#include "opencv2/core/cvstd.hpp" - -namespace cv -{ - -//! @addtogroup core_utils -//! @{ - -namespace Error { -//! error codes -enum Code { - StsOk= 0, //!< everything is ok - StsBackTrace= -1, //!< pseudo error for back trace - StsError= -2, //!< unknown /unspecified error - StsInternal= -3, //!< internal error (bad state) - StsNoMem= -4, //!< insufficient memory - StsBadArg= -5, //!< function arg/param is bad - StsBadFunc= -6, //!< unsupported function - StsNoConv= -7, //!< iteration didn't converge - StsAutoTrace= -8, //!< tracing - HeaderIsNull= -9, //!< image header is NULL - BadImageSize= -10, //!< image size is invalid - BadOffset= -11, //!< offset is invalid - BadDataPtr= -12, //!< - BadStep= -13, //!< image step is wrong, this may happen for a non-continuous matrix. - BadModelOrChSeq= -14, //!< - BadNumChannels= -15, //!< bad number of channels, for example, some functions accept only single channel matrices. - BadNumChannel1U= -16, //!< - BadDepth= -17, //!< input image depth is not supported by the function - BadAlphaChannel= -18, //!< - BadOrder= -19, //!< number of dimensions is out of range - BadOrigin= -20, //!< incorrect input origin - BadAlign= -21, //!< incorrect input align - BadCallBack= -22, //!< - BadTileSize= -23, //!< - BadCOI= -24, //!< input COI is not supported - BadROISize= -25, //!< incorrect input roi - MaskIsTiled= -26, //!< - StsNullPtr= -27, //!< null pointer - StsVecLengthErr= -28, //!< incorrect vector length - StsFilterStructContentErr= -29, //!< incorrect filter structure content - StsKernelStructContentErr= -30, //!< incorrect transform kernel content - StsFilterOffsetErr= -31, //!< incorrect filter offset value - StsBadSize= -201, //!< the input/output structure size is incorrect - StsDivByZero= -202, //!< division by zero - StsInplaceNotSupported= -203, //!< in-place operation is not supported - StsObjectNotFound= -204, //!< request can't be completed - StsUnmatchedFormats= -205, //!< formats of input/output arrays differ - StsBadFlag= -206, //!< flag is wrong or not supported - StsBadPoint= -207, //!< bad CvPoint - StsBadMask= -208, //!< bad format of mask (neither 8uC1 nor 8sC1) - StsUnmatchedSizes= -209, //!< sizes of input/output structures do not match - StsUnsupportedFormat= -210, //!< the data format/type is not supported by the function - StsOutOfRange= -211, //!< some of parameters are out of range - StsParseError= -212, //!< invalid syntax/structure of the parsed file - StsNotImplemented= -213, //!< the requested function/feature is not implemented - StsBadMemBlock= -214, //!< an allocated block has been corrupted - StsAssert= -215, //!< assertion failed - GpuNotSupported= -216, //!< no CUDA support - GpuApiCallError= -217, //!< GPU API call error - OpenGlNotSupported= -218, //!< no OpenGL support - OpenGlApiCallError= -219, //!< OpenGL API call error - OpenCLApiCallError= -220, //!< OpenCL API call error - OpenCLDoubleNotSupported= -221, - OpenCLInitError= -222, //!< OpenCL initialization error - OpenCLNoAMDBlasFft= -223 -}; -} //Error - -//! @} core_utils - -//! @addtogroup core_array -//! @{ - -//! matrix decomposition types -enum DecompTypes { - /** Gaussian elimination with the optimal pivot element chosen. */ - DECOMP_LU = 0, - /** singular value decomposition (SVD) method; the system can be over-defined and/or the matrix - src1 can be singular */ - DECOMP_SVD = 1, - /** eigenvalue decomposition; the matrix src1 must be symmetrical */ - DECOMP_EIG = 2, - /** Cholesky \f$LL^T\f$ factorization; the matrix src1 must be symmetrical and positively - defined */ - DECOMP_CHOLESKY = 3, - /** QR factorization; the system can be over-defined and/or the matrix src1 can be singular */ - DECOMP_QR = 4, - /** while all the previous flags are mutually exclusive, this flag can be used together with - any of the previous; it means that the normal equations - \f$\texttt{src1}^T\cdot\texttt{src1}\cdot\texttt{dst}=\texttt{src1}^T\texttt{src2}\f$ are - solved instead of the original system - \f$\texttt{src1}\cdot\texttt{dst}=\texttt{src2}\f$ */ - DECOMP_NORMAL = 16 -}; - -/** norm types - -src1 and src2 denote input arrays. -*/ - -enum NormTypes { - /** - \f[ - norm = \forkthree - {\|\texttt{src1}\|_{L_{\infty}} = \max _I | \texttt{src1} (I)|}{if \(\texttt{normType} = \texttt{NORM_INF}\) } - {\|\texttt{src1}-\texttt{src2}\|_{L_{\infty}} = \max _I | \texttt{src1} (I) - \texttt{src2} (I)|}{if \(\texttt{normType} = \texttt{NORM_INF}\) } - {\frac{\|\texttt{src1}-\texttt{src2}\|_{L_{\infty}} }{\|\texttt{src2}\|_{L_{\infty}} }}{if \(\texttt{normType} = \texttt{NORM_RELATIVE | NORM_INF}\) } - \f] - */ - NORM_INF = 1, - /** - \f[ - norm = \forkthree - {\| \texttt{src1} \| _{L_1} = \sum _I | \texttt{src1} (I)|}{if \(\texttt{normType} = \texttt{NORM_L1}\)} - { \| \texttt{src1} - \texttt{src2} \| _{L_1} = \sum _I | \texttt{src1} (I) - \texttt{src2} (I)|}{if \(\texttt{normType} = \texttt{NORM_L1}\) } - { \frac{\|\texttt{src1}-\texttt{src2}\|_{L_1} }{\|\texttt{src2}\|_{L_1}} }{if \(\texttt{normType} = \texttt{NORM_RELATIVE | NORM_L1}\) } - \f]*/ - NORM_L1 = 2, - /** - \f[ - norm = \forkthree - { \| \texttt{src1} \| _{L_2} = \sqrt{\sum_I \texttt{src1}(I)^2} }{if \(\texttt{normType} = \texttt{NORM_L2}\) } - { \| \texttt{src1} - \texttt{src2} \| _{L_2} = \sqrt{\sum_I (\texttt{src1}(I) - \texttt{src2}(I))^2} }{if \(\texttt{normType} = \texttt{NORM_L2}\) } - { \frac{\|\texttt{src1}-\texttt{src2}\|_{L_2} }{\|\texttt{src2}\|_{L_2}} }{if \(\texttt{normType} = \texttt{NORM_RELATIVE | NORM_L2}\) } - \f] - */ - NORM_L2 = 4, - /** - \f[ - norm = \forkthree - { \| \texttt{src1} \| _{L_2} ^{2} = \sum_I \texttt{src1}(I)^2} {if \(\texttt{normType} = \texttt{NORM_L2SQR}\)} - { \| \texttt{src1} - \texttt{src2} \| _{L_2} ^{2} = \sum_I (\texttt{src1}(I) - \texttt{src2}(I))^2 }{if \(\texttt{normType} = \texttt{NORM_L2SQR}\) } - { \left(\frac{\|\texttt{src1}-\texttt{src2}\|_{L_2} }{\|\texttt{src2}\|_{L_2}}\right)^2 }{if \(\texttt{normType} = \texttt{NORM_RELATIVE | NORM_L2SQR}\) } - \f] - */ - NORM_L2SQR = 5, - /** - In the case of one input array, calculates the Hamming distance of the array from zero, - In the case of two input arrays, calculates the Hamming distance between the arrays. - */ - NORM_HAMMING = 6, - /** - Similar to NORM_HAMMING, but in the calculation, each two bits of the input sequence will - be added and treated as a single bit to be used in the same calculation as NORM_HAMMING. - */ - NORM_HAMMING2 = 7, - NORM_TYPE_MASK = 7, //!< bit-mask which can be used to separate norm type from norm flags - NORM_RELATIVE = 8, //!< flag - NORM_MINMAX = 32 //!< flag - }; - -//! comparison types -enum CmpTypes { CMP_EQ = 0, //!< src1 is equal to src2. - CMP_GT = 1, //!< src1 is greater than src2. - CMP_GE = 2, //!< src1 is greater than or equal to src2. - CMP_LT = 3, //!< src1 is less than src2. - CMP_LE = 4, //!< src1 is less than or equal to src2. - CMP_NE = 5 //!< src1 is unequal to src2. - }; - -//! generalized matrix multiplication flags -enum GemmFlags { GEMM_1_T = 1, //!< transposes src1 - GEMM_2_T = 2, //!< transposes src2 - GEMM_3_T = 4 //!< transposes src3 - }; - -enum DftFlags { - /** performs an inverse 1D or 2D transform instead of the default forward - transform. */ - DFT_INVERSE = 1, - /** scales the result: divide it by the number of array elements. Normally, it is - combined with DFT_INVERSE. */ - DFT_SCALE = 2, - /** performs a forward or inverse transform of every individual row of the input - matrix; this flag enables you to transform multiple vectors simultaneously and can be used to - decrease the overhead (which is sometimes several times larger than the processing itself) to - perform 3D and higher-dimensional transformations and so forth.*/ - DFT_ROWS = 4, - /** performs a forward transformation of 1D or 2D real array; the result, - though being a complex array, has complex-conjugate symmetry (*CCS*, see the function - description below for details), and such an array can be packed into a real array of the same - size as input, which is the fastest option and which is what the function does by default; - however, you may wish to get a full complex array (for simpler spectrum analysis, and so on) - - pass the flag to enable the function to produce a full-size complex output array. */ - DFT_COMPLEX_OUTPUT = 16, - /** performs an inverse transformation of a 1D or 2D complex array; the - result is normally a complex array of the same size, however, if the input array has - conjugate-complex symmetry (for example, it is a result of forward transformation with - DFT_COMPLEX_OUTPUT flag), the output is a real array; while the function itself does not - check whether the input is symmetrical or not, you can pass the flag and then the function - will assume the symmetry and produce the real output array (note that when the input is packed - into a real array and inverse transformation is executed, the function treats the input as a - packed complex-conjugate symmetrical array, and the output will also be a real array). */ - DFT_REAL_OUTPUT = 32, - /** specifies that input is complex input. If this flag is set, the input must have 2 channels. - On the other hand, for backwards compatibility reason, if input has 2 channels, input is - already considered complex. */ - DFT_COMPLEX_INPUT = 64, - /** performs an inverse 1D or 2D transform instead of the default forward transform. */ - DCT_INVERSE = DFT_INVERSE, - /** performs a forward or inverse transform of every individual row of the input - matrix. This flag enables you to transform multiple vectors simultaneously and can be used to - decrease the overhead (which is sometimes several times larger than the processing itself) to - perform 3D and higher-dimensional transforms and so forth.*/ - DCT_ROWS = DFT_ROWS -}; - -//! Various border types, image boundaries are denoted with `|` -//! @see borderInterpolate, copyMakeBorder -enum BorderTypes { - BORDER_CONSTANT = 0, //!< `iiiiii|abcdefgh|iiiiiii` with some specified `i` - BORDER_REPLICATE = 1, //!< `aaaaaa|abcdefgh|hhhhhhh` - BORDER_REFLECT = 2, //!< `fedcba|abcdefgh|hgfedcb` - BORDER_WRAP = 3, //!< `cdefgh|abcdefgh|abcdefg` - BORDER_REFLECT_101 = 4, //!< `gfedcb|abcdefgh|gfedcba` - BORDER_TRANSPARENT = 5, //!< `uvwxyz|abcdefgh|ijklmno` - Treats outliers as transparent. - - BORDER_REFLECT101 = BORDER_REFLECT_101, //!< same as BORDER_REFLECT_101 - BORDER_DEFAULT = BORDER_REFLECT_101, //!< same as BORDER_REFLECT_101 - BORDER_ISOLATED = 16 //!< Interpolation restricted within the ROI boundaries. -}; - -//! @} core_array - -//! @addtogroup core_utils -//! @{ - -/*! @brief Signals an error and raises the exception. - -By default the function prints information about the error to stderr, -then it either stops if setBreakOnError() had been called before or raises the exception. -It is possible to alternate error processing by using redirectError(). -@param code - error code (Error::Code) -@param err - error description -@param func - function name. Available only when the compiler supports getting it -@param file - source file name where the error has occurred -@param line - line number in the source file where the error has occurred -@see CV_Error, CV_Error_, CV_Assert, CV_DbgAssert - */ -CV_EXPORTS CV_NORETURN void error(int code, const String& err, const char* func, const char* file, int line); - -/*! @brief Signals an error and terminate application. - -By default the function prints information about the error to stderr, then it terminates application -with std::terminate. The function is designed for invariants check in functions and methods with -noexcept attribute. -@param code - error code (Error::Code) -@param err - error description -@param func - function name. Available only when the compiler supports getting it -@param file - source file name where the error has occurred -@param line - line number in the source file where the error has occurred -@see CV_AssertTerminate - */ -CV_EXPORTS CV_NORETURN void terminate(int code, const String& err, const char* func, const char* file, int line) CV_NOEXCEPT; - - -#ifdef CV_STATIC_ANALYSIS - -// In practice, some macro are not processed correctly (noreturn is not detected). -// We need to use simplified definition for them. -#define CV_Error(code, msg) do { (void)(code); (void)(msg); abort(); } while (0) -#define CV_Error_(code, args) do { (void)(code); (void)(cv::format args); abort(); } while (0) -#define CV_Assert( expr ) do { if (!(expr)) abort(); } while (0) - -#else // CV_STATIC_ANALYSIS - -/** @brief Call the error handler. - -Currently, the error handler prints the error code and the error message to the standard -error stream `stderr`. In the Debug configuration, it then provokes memory access violation, so that -the execution stack and all the parameters can be analyzed by the debugger. In the Release -configuration, the exception is thrown. - -@param code one of Error::Code -@param msg error message -*/ -#define CV_Error( code, msg ) cv::error( code, msg, CV_Func, __FILE__, __LINE__ ) - -/** @brief Call the error handler. - -This macro can be used to construct an error message on-fly to include some dynamic information, -for example: -@code - // note the extra parentheses around the formatted text message - CV_Error_(Error::StsOutOfRange, - ("the value at (%d, %d)=%g is out of range", badPt.x, badPt.y, badValue)); -@endcode -@param code one of Error::Code -@param args printf-like formatted error message in parentheses -*/ -#define CV_Error_( code, args ) cv::error( code, cv::format args, CV_Func, __FILE__, __LINE__ ) - -/** @brief Checks a condition at runtime and throws exception if it fails - -The macros CV_Assert (and CV_DbgAssert(expr)) evaluate the specified expression. If it is 0, the macros -raise an error (see cv::error). The macro CV_Assert checks the condition in both Debug and Release -configurations while CV_DbgAssert is only retained in the Debug configuration. -CV_AssertTerminate is analog of CV_Assert for invariants check in functions with noexcept attribute. -It does not throw exception, but terminates the application. -*/ -#define CV_Assert( expr ) do { if(!!(expr)) ; else cv::error( cv::Error::StsAssert, #expr, CV_Func, __FILE__, __LINE__ ); } while(0) -#define CV_AssertTerminate( expr ) do { if(!!(expr)) ; else cv::terminate( #expr, CV_Func, __FILE__, __LINE__ ); } while(0) - -#endif // CV_STATIC_ANALYSIS - -//! @cond IGNORED -#if !defined(__OPENCV_BUILD) // TODO: backward compatibility only -#ifndef CV_ErrorNoReturn -#define CV_ErrorNoReturn CV_Error -#endif -#ifndef CV_ErrorNoReturn_ -#define CV_ErrorNoReturn_ CV_Error_ -#endif -#endif - -#define CV_Assert_1 CV_Assert -#define CV_Assert_2( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_1( __VA_ARGS__ )) -#define CV_Assert_3( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_2( __VA_ARGS__ )) -#define CV_Assert_4( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_3( __VA_ARGS__ )) -#define CV_Assert_5( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_4( __VA_ARGS__ )) -#define CV_Assert_6( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_5( __VA_ARGS__ )) -#define CV_Assert_7( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_6( __VA_ARGS__ )) -#define CV_Assert_8( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_7( __VA_ARGS__ )) -#define CV_Assert_9( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_8( __VA_ARGS__ )) -#define CV_Assert_10( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_9( __VA_ARGS__ )) - -#define CV_Assert_N(...) do { __CV_EXPAND(__CV_CAT(CV_Assert_, __CV_VA_NUM_ARGS(__VA_ARGS__)) (__VA_ARGS__)); } while(0) - -//! @endcond - -#if defined _DEBUG || defined CV_STATIC_ANALYSIS -# define CV_DbgAssert(expr) CV_Assert(expr) -#else -/** replaced with CV_Assert(expr) in Debug configuration */ -# define CV_DbgAssert(expr) -#endif - -/* - * Hamming distance functor - counts the bit differences between two strings - useful for the Brief descriptor - * bit count of A exclusive XOR'ed with B - */ -struct CV_EXPORTS Hamming -{ - static const NormTypes normType = NORM_HAMMING; - typedef unsigned char ValueType; - typedef int ResultType; - - /** this will count the bits in a ^ b - */ - ResultType operator()( const unsigned char* a, const unsigned char* b, int size ) const; -}; - -typedef Hamming HammingLUT; - -/////////////////////////////////// inline norms //////////////////////////////////// - -template inline _Tp cv_abs(_Tp x) { return std::abs(x); } -inline int cv_abs(uchar x) { return x; } -inline int cv_abs(schar x) { return std::abs(x); } -inline int cv_abs(ushort x) { return x; } -inline int cv_abs(short x) { return std::abs(x); } - -template static inline -_AccTp normL2Sqr(const _Tp* a, int n) -{ - _AccTp s = 0; - int i=0; -#if CV_ENABLE_UNROLLED - for( ; i <= n - 4; i += 4 ) - { - _AccTp v0 = a[i], v1 = a[i+1], v2 = a[i+2], v3 = a[i+3]; - s += v0*v0 + v1*v1 + v2*v2 + v3*v3; - } -#endif - for( ; i < n; i++ ) - { - _AccTp v = a[i]; - s += v*v; - } - return s; -} - -template static inline -_AccTp normL1(const _Tp* a, int n) -{ - _AccTp s = 0; - int i = 0; -#if CV_ENABLE_UNROLLED - for(; i <= n - 4; i += 4 ) - { - s += (_AccTp)cv_abs(a[i]) + (_AccTp)cv_abs(a[i+1]) + - (_AccTp)cv_abs(a[i+2]) + (_AccTp)cv_abs(a[i+3]); - } -#endif - for( ; i < n; i++ ) - s += cv_abs(a[i]); - return s; -} - -template static inline -_AccTp normInf(const _Tp* a, int n) -{ - _AccTp s = 0; - for( int i = 0; i < n; i++ ) - s = std::max(s, (_AccTp)cv_abs(a[i])); - return s; -} - -template static inline -_AccTp normL2Sqr(const _Tp* a, const _Tp* b, int n) -{ - _AccTp s = 0; - int i= 0; -#if CV_ENABLE_UNROLLED - for(; i <= n - 4; i += 4 ) - { - _AccTp v0 = _AccTp(a[i] - b[i]), v1 = _AccTp(a[i+1] - b[i+1]), v2 = _AccTp(a[i+2] - b[i+2]), v3 = _AccTp(a[i+3] - b[i+3]); - s += v0*v0 + v1*v1 + v2*v2 + v3*v3; - } -#endif - for( ; i < n; i++ ) - { - _AccTp v = _AccTp(a[i] - b[i]); - s += v*v; - } - return s; -} - -static inline float normL2Sqr(const float* a, const float* b, int n) -{ - float s = 0.f; - for( int i = 0; i < n; i++ ) - { - float v = a[i] - b[i]; - s += v*v; - } - return s; -} - -template static inline -_AccTp normL1(const _Tp* a, const _Tp* b, int n) -{ - _AccTp s = 0; - int i= 0; -#if CV_ENABLE_UNROLLED - for(; i <= n - 4; i += 4 ) - { - _AccTp v0 = _AccTp(a[i] - b[i]), v1 = _AccTp(a[i+1] - b[i+1]), v2 = _AccTp(a[i+2] - b[i+2]), v3 = _AccTp(a[i+3] - b[i+3]); - s += std::abs(v0) + std::abs(v1) + std::abs(v2) + std::abs(v3); - } -#endif - for( ; i < n; i++ ) - { - _AccTp v = _AccTp(a[i] - b[i]); - s += std::abs(v); - } - return s; -} - -inline float normL1(const float* a, const float* b, int n) -{ - float s = 0.f; - for( int i = 0; i < n; i++ ) - { - s += std::abs(a[i] - b[i]); - } - return s; -} - -inline int normL1(const uchar* a, const uchar* b, int n) -{ - int s = 0; - for( int i = 0; i < n; i++ ) - { - s += std::abs(a[i] - b[i]); - } - return s; -} - -template static inline -_AccTp normInf(const _Tp* a, const _Tp* b, int n) -{ - _AccTp s = 0; - for( int i = 0; i < n; i++ ) - { - _AccTp v0 = a[i] - b[i]; - s = std::max(s, std::abs(v0)); - } - return s; -} - -/** @brief Computes the cube root of an argument. - - The function cubeRoot computes \f$\sqrt[3]{\texttt{val}}\f$. Negative arguments are handled correctly. - NaN and Inf are not handled. The accuracy approaches the maximum possible accuracy for - single-precision data. - @param val A function argument. - */ -CV_EXPORTS_W float cubeRoot(float val); - -/** @overload - -cubeRoot with argument of `double` type calls `std::cbrt(double)` -*/ -static inline -double cubeRoot(double val) -{ - return std::cbrt(val); -} - -/** @brief Calculates the angle of a 2D vector in degrees. - - The function fastAtan2 calculates the full-range angle of an input 2D vector. The angle is measured - in degrees and varies from 0 to 360 degrees. The accuracy is about 0.3 degrees. - @param x x-coordinate of the vector. - @param y y-coordinate of the vector. - */ -CV_EXPORTS_W float fastAtan2(float y, float x); - -/** proxy for hal::LU */ -CV_EXPORTS int LU(float* A, size_t astep, int m, float* b, size_t bstep, int n); -/** proxy for hal::LU */ -CV_EXPORTS int LU(double* A, size_t astep, int m, double* b, size_t bstep, int n); -/** proxy for hal::Cholesky */ -CV_EXPORTS bool Cholesky(float* A, size_t astep, int m, float* b, size_t bstep, int n); -/** proxy for hal::Cholesky */ -CV_EXPORTS bool Cholesky(double* A, size_t astep, int m, double* b, size_t bstep, int n); - -////////////////// forward declarations for important OpenCV types ////////////////// - -//! @cond IGNORED - -template class Vec; -template class Matx; - -template class Complex; -template class Point_; -template class Point3_; -template class Size_; -template class Rect_; -template class Scalar_; - -class CV_EXPORTS RotatedRect; -class CV_EXPORTS Range; -class CV_EXPORTS TermCriteria; -class CV_EXPORTS KeyPoint; -class CV_EXPORTS DMatch; -class CV_EXPORTS RNG; - -class CV_EXPORTS Mat; -class CV_EXPORTS MatExpr; - -class CV_EXPORTS UMat; - -class CV_EXPORTS SparseMat; -typedef Mat MatND; - -template class Mat_; -template class SparseMat_; - -class CV_EXPORTS MatConstIterator; -class CV_EXPORTS SparseMatIterator; -class CV_EXPORTS SparseMatConstIterator; -template class MatIterator_; -template class MatConstIterator_; -template class SparseMatIterator_; -template class SparseMatConstIterator_; - -namespace ogl -{ - class CV_EXPORTS Buffer; - class CV_EXPORTS Texture2D; - class CV_EXPORTS Arrays; -} - -namespace cuda -{ - class CV_EXPORTS GpuMat; - class CV_EXPORTS HostMem; - class CV_EXPORTS Stream; - class CV_EXPORTS Event; -} - -namespace cudev -{ - template class GpuMat_; -} - -namespace ipp -{ -CV_EXPORTS unsigned long long getIppFeatures(); -CV_EXPORTS void setIppStatus(int status, const char * const funcname = NULL, const char * const filename = NULL, - int line = 0); -CV_EXPORTS int getIppStatus(); -CV_EXPORTS String getIppErrorLocation(); -CV_EXPORTS_W bool useIPP(); -CV_EXPORTS_W void setUseIPP(bool flag); -CV_EXPORTS_W String getIppVersion(); - -// IPP Not-Exact mode. This function may force use of IPP then both IPP and OpenCV provide proper results -// but have internal accuracy differences which have too much direct or indirect impact on accuracy tests. -CV_EXPORTS_W bool useIPP_NotExact(); -CV_EXPORTS_W void setUseIPP_NotExact(bool flag); -#ifndef DISABLE_OPENCV_3_COMPATIBILITY -static inline bool useIPP_NE() { return useIPP_NotExact(); } -static inline void setUseIPP_NE(bool flag) { setUseIPP_NotExact(flag); } -#endif - -} // ipp - -//! @endcond - -//! @} core_utils - - - - -} // cv - -#include "opencv2/core/neon_utils.hpp" -#include "opencv2/core/vsx_utils.hpp" -#include "opencv2/core/check.hpp" - -#endif //OPENCV_CORE_BASE_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2014, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CORE_BASE_HPP +#define OPENCV_CORE_BASE_HPP + +#ifndef __cplusplus +# error base.hpp header must be compiled as C++ +#endif + +#include "opencv2/opencv_modules.hpp" + +#include +#include + +#include "opencv2/core/cvdef.h" +#include "opencv2/core/cvstd.hpp" + +namespace cv +{ + +//! @addtogroup core_utils +//! @{ + +namespace Error { +//! error codes +enum Code { + StsOk= 0, //!< everything is ok + StsBackTrace= -1, //!< pseudo error for back trace + StsError= -2, //!< unknown /unspecified error + StsInternal= -3, //!< internal error (bad state) + StsNoMem= -4, //!< insufficient memory + StsBadArg= -5, //!< function arg/param is bad + StsBadFunc= -6, //!< unsupported function + StsNoConv= -7, //!< iteration didn't converge + StsAutoTrace= -8, //!< tracing + HeaderIsNull= -9, //!< image header is NULL + BadImageSize= -10, //!< image size is invalid + BadOffset= -11, //!< offset is invalid + BadDataPtr= -12, //!< + BadStep= -13, //!< image step is wrong, this may happen for a non-continuous matrix. + BadModelOrChSeq= -14, //!< + BadNumChannels= -15, //!< bad number of channels, for example, some functions accept only single channel matrices. + BadNumChannel1U= -16, //!< + BadDepth= -17, //!< input image depth is not supported by the function + BadAlphaChannel= -18, //!< + BadOrder= -19, //!< number of dimensions is out of range + BadOrigin= -20, //!< incorrect input origin + BadAlign= -21, //!< incorrect input align + BadCallBack= -22, //!< + BadTileSize= -23, //!< + BadCOI= -24, //!< input COI is not supported + BadROISize= -25, //!< incorrect input roi + MaskIsTiled= -26, //!< + StsNullPtr= -27, //!< null pointer + StsVecLengthErr= -28, //!< incorrect vector length + StsFilterStructContentErr= -29, //!< incorrect filter structure content + StsKernelStructContentErr= -30, //!< incorrect transform kernel content + StsFilterOffsetErr= -31, //!< incorrect filter offset value + StsBadSize= -201, //!< the input/output structure size is incorrect + StsDivByZero= -202, //!< division by zero + StsInplaceNotSupported= -203, //!< in-place operation is not supported + StsObjectNotFound= -204, //!< request can't be completed + StsUnmatchedFormats= -205, //!< formats of input/output arrays differ + StsBadFlag= -206, //!< flag is wrong or not supported + StsBadPoint= -207, //!< bad CvPoint + StsBadMask= -208, //!< bad format of mask (neither 8uC1 nor 8sC1) + StsUnmatchedSizes= -209, //!< sizes of input/output structures do not match + StsUnsupportedFormat= -210, //!< the data format/type is not supported by the function + StsOutOfRange= -211, //!< some of parameters are out of range + StsParseError= -212, //!< invalid syntax/structure of the parsed file + StsNotImplemented= -213, //!< the requested function/feature is not implemented + StsBadMemBlock= -214, //!< an allocated block has been corrupted + StsAssert= -215, //!< assertion failed + GpuNotSupported= -216, //!< no CUDA support + GpuApiCallError= -217, //!< GPU API call error + OpenGlNotSupported= -218, //!< no OpenGL support + OpenGlApiCallError= -219, //!< OpenGL API call error + OpenCLApiCallError= -220, //!< OpenCL API call error + OpenCLDoubleNotSupported= -221, + OpenCLInitError= -222, //!< OpenCL initialization error + OpenCLNoAMDBlasFft= -223 +}; +} //Error + +//! @} core_utils + +//! @addtogroup core_array +//! @{ + +//! matrix decomposition types +enum DecompTypes { + /** Gaussian elimination with the optimal pivot element chosen. */ + DECOMP_LU = 0, + /** singular value decomposition (SVD) method; the system can be over-defined and/or the matrix + src1 can be singular */ + DECOMP_SVD = 1, + /** eigenvalue decomposition; the matrix src1 must be symmetrical */ + DECOMP_EIG = 2, + /** Cholesky \f$LL^T\f$ factorization; the matrix src1 must be symmetrical and positively + defined */ + DECOMP_CHOLESKY = 3, + /** QR factorization; the system can be over-defined and/or the matrix src1 can be singular */ + DECOMP_QR = 4, + /** while all the previous flags are mutually exclusive, this flag can be used together with + any of the previous; it means that the normal equations + \f$\texttt{src1}^T\cdot\texttt{src1}\cdot\texttt{dst}=\texttt{src1}^T\texttt{src2}\f$ are + solved instead of the original system + \f$\texttt{src1}\cdot\texttt{dst}=\texttt{src2}\f$ */ + DECOMP_NORMAL = 16 +}; + +/** norm types + +src1 and src2 denote input arrays. +*/ + +enum NormTypes { + /** + \f[ + norm = \forkthree + {\|\texttt{src1}\|_{L_{\infty}} = \max _I | \texttt{src1} (I)|}{if \(\texttt{normType} = \texttt{NORM_INF}\) } + {\|\texttt{src1}-\texttt{src2}\|_{L_{\infty}} = \max _I | \texttt{src1} (I) - \texttt{src2} (I)|}{if \(\texttt{normType} = \texttt{NORM_INF}\) } + {\frac{\|\texttt{src1}-\texttt{src2}\|_{L_{\infty}} }{\|\texttt{src2}\|_{L_{\infty}} }}{if \(\texttt{normType} = \texttt{NORM_RELATIVE | NORM_INF}\) } + \f] + */ + NORM_INF = 1, + /** + \f[ + norm = \forkthree + {\| \texttt{src1} \| _{L_1} = \sum _I | \texttt{src1} (I)|}{if \(\texttt{normType} = \texttt{NORM_L1}\)} + { \| \texttt{src1} - \texttt{src2} \| _{L_1} = \sum _I | \texttt{src1} (I) - \texttt{src2} (I)|}{if \(\texttt{normType} = \texttt{NORM_L1}\) } + { \frac{\|\texttt{src1}-\texttt{src2}\|_{L_1} }{\|\texttt{src2}\|_{L_1}} }{if \(\texttt{normType} = \texttt{NORM_RELATIVE | NORM_L1}\) } + \f]*/ + NORM_L1 = 2, + /** + \f[ + norm = \forkthree + { \| \texttt{src1} \| _{L_2} = \sqrt{\sum_I \texttt{src1}(I)^2} }{if \(\texttt{normType} = \texttt{NORM_L2}\) } + { \| \texttt{src1} - \texttt{src2} \| _{L_2} = \sqrt{\sum_I (\texttt{src1}(I) - \texttt{src2}(I))^2} }{if \(\texttt{normType} = \texttt{NORM_L2}\) } + { \frac{\|\texttt{src1}-\texttt{src2}\|_{L_2} }{\|\texttt{src2}\|_{L_2}} }{if \(\texttt{normType} = \texttt{NORM_RELATIVE | NORM_L2}\) } + \f] + */ + NORM_L2 = 4, + /** + \f[ + norm = \forkthree + { \| \texttt{src1} \| _{L_2} ^{2} = \sum_I \texttt{src1}(I)^2} {if \(\texttt{normType} = \texttt{NORM_L2SQR}\)} + { \| \texttt{src1} - \texttt{src2} \| _{L_2} ^{2} = \sum_I (\texttt{src1}(I) - \texttt{src2}(I))^2 }{if \(\texttt{normType} = \texttt{NORM_L2SQR}\) } + { \left(\frac{\|\texttt{src1}-\texttt{src2}\|_{L_2} }{\|\texttt{src2}\|_{L_2}}\right)^2 }{if \(\texttt{normType} = \texttt{NORM_RELATIVE | NORM_L2SQR}\) } + \f] + */ + NORM_L2SQR = 5, + /** + In the case of one input array, calculates the Hamming distance of the array from zero, + In the case of two input arrays, calculates the Hamming distance between the arrays. + */ + NORM_HAMMING = 6, + /** + Similar to NORM_HAMMING, but in the calculation, each two bits of the input sequence will + be added and treated as a single bit to be used in the same calculation as NORM_HAMMING. + */ + NORM_HAMMING2 = 7, + NORM_TYPE_MASK = 7, //!< bit-mask which can be used to separate norm type from norm flags + NORM_RELATIVE = 8, //!< flag + NORM_MINMAX = 32 //!< flag + }; + +//! comparison types +enum CmpTypes { CMP_EQ = 0, //!< src1 is equal to src2. + CMP_GT = 1, //!< src1 is greater than src2. + CMP_GE = 2, //!< src1 is greater than or equal to src2. + CMP_LT = 3, //!< src1 is less than src2. + CMP_LE = 4, //!< src1 is less than or equal to src2. + CMP_NE = 5 //!< src1 is unequal to src2. + }; + +//! generalized matrix multiplication flags +enum GemmFlags { GEMM_1_T = 1, //!< transposes src1 + GEMM_2_T = 2, //!< transposes src2 + GEMM_3_T = 4 //!< transposes src3 + }; + +enum DftFlags { + /** performs an inverse 1D or 2D transform instead of the default forward + transform. */ + DFT_INVERSE = 1, + /** scales the result: divide it by the number of array elements. Normally, it is + combined with DFT_INVERSE. */ + DFT_SCALE = 2, + /** performs a forward or inverse transform of every individual row of the input + matrix; this flag enables you to transform multiple vectors simultaneously and can be used to + decrease the overhead (which is sometimes several times larger than the processing itself) to + perform 3D and higher-dimensional transformations and so forth.*/ + DFT_ROWS = 4, + /** performs a forward transformation of 1D or 2D real array; the result, + though being a complex array, has complex-conjugate symmetry (*CCS*, see the function + description below for details), and such an array can be packed into a real array of the same + size as input, which is the fastest option and which is what the function does by default; + however, you may wish to get a full complex array (for simpler spectrum analysis, and so on) - + pass the flag to enable the function to produce a full-size complex output array. */ + DFT_COMPLEX_OUTPUT = 16, + /** performs an inverse transformation of a 1D or 2D complex array; the + result is normally a complex array of the same size, however, if the input array has + conjugate-complex symmetry (for example, it is a result of forward transformation with + DFT_COMPLEX_OUTPUT flag), the output is a real array; while the function itself does not + check whether the input is symmetrical or not, you can pass the flag and then the function + will assume the symmetry and produce the real output array (note that when the input is packed + into a real array and inverse transformation is executed, the function treats the input as a + packed complex-conjugate symmetrical array, and the output will also be a real array). */ + DFT_REAL_OUTPUT = 32, + /** specifies that input is complex input. If this flag is set, the input must have 2 channels. + On the other hand, for backwards compatibility reason, if input has 2 channels, input is + already considered complex. */ + DFT_COMPLEX_INPUT = 64, + /** performs an inverse 1D or 2D transform instead of the default forward transform. */ + DCT_INVERSE = DFT_INVERSE, + /** performs a forward or inverse transform of every individual row of the input + matrix. This flag enables you to transform multiple vectors simultaneously and can be used to + decrease the overhead (which is sometimes several times larger than the processing itself) to + perform 3D and higher-dimensional transforms and so forth.*/ + DCT_ROWS = DFT_ROWS +}; + +//! Various border types, image boundaries are denoted with `|` +//! @see borderInterpolate, copyMakeBorder +enum BorderTypes { + BORDER_CONSTANT = 0, //!< `iiiiii|abcdefgh|iiiiiii` with some specified `i` + BORDER_REPLICATE = 1, //!< `aaaaaa|abcdefgh|hhhhhhh` + BORDER_REFLECT = 2, //!< `fedcba|abcdefgh|hgfedcb` + BORDER_WRAP = 3, //!< `cdefgh|abcdefgh|abcdefg` + BORDER_REFLECT_101 = 4, //!< `gfedcb|abcdefgh|gfedcba` + BORDER_TRANSPARENT = 5, //!< `uvwxyz|abcdefgh|ijklmno` - Treats outliers as transparent. + + BORDER_REFLECT101 = BORDER_REFLECT_101, //!< same as BORDER_REFLECT_101 + BORDER_DEFAULT = BORDER_REFLECT_101, //!< same as BORDER_REFLECT_101 + BORDER_ISOLATED = 16 //!< Interpolation restricted within the ROI boundaries. +}; + +//! @} core_array + +//! @addtogroup core_utils +//! @{ + +/*! @brief Signals an error and raises the exception. + +By default the function prints information about the error to stderr, +then it either stops if setBreakOnError() had been called before or raises the exception. +It is possible to alternate error processing by using redirectError(). +@param code - error code (Error::Code) +@param err - error description +@param func - function name. Available only when the compiler supports getting it +@param file - source file name where the error has occurred +@param line - line number in the source file where the error has occurred +@see CV_Error, CV_Error_, CV_Assert, CV_DbgAssert + */ +CV_EXPORTS CV_NORETURN void error(int code, const String& err, const char* func, const char* file, int line); + +/*! @brief Signals an error and terminate application. + +By default the function prints information about the error to stderr, then it terminates application +with std::terminate. The function is designed for invariants check in functions and methods with +noexcept attribute. +@param code - error code (Error::Code) +@param err - error description +@param func - function name. Available only when the compiler supports getting it +@param file - source file name where the error has occurred +@param line - line number in the source file where the error has occurred +@see CV_AssertTerminate + */ +CV_EXPORTS CV_NORETURN void terminate(int code, const String& err, const char* func, const char* file, int line) CV_NOEXCEPT; + + +#ifdef CV_STATIC_ANALYSIS + +// In practice, some macro are not processed correctly (noreturn is not detected). +// We need to use simplified definition for them. +#define CV_Error(code, msg) do { (void)(code); (void)(msg); abort(); } while (0) +#define CV_Error_(code, args) do { (void)(code); (void)(cv::format args); abort(); } while (0) +#define CV_Assert( expr ) do { if (!(expr)) abort(); } while (0) + +#else // CV_STATIC_ANALYSIS + +/** @brief Call the error handler. + +Currently, the error handler prints the error code and the error message to the standard +error stream `stderr`. In the Debug configuration, it then provokes memory access violation, so that +the execution stack and all the parameters can be analyzed by the debugger. In the Release +configuration, the exception is thrown. + +@param code one of Error::Code +@param msg error message +*/ +#define CV_Error( code, msg ) cv::error( code, msg, CV_Func, __FILE__, __LINE__ ) + +/** @brief Call the error handler. + +This macro can be used to construct an error message on-fly to include some dynamic information, +for example: +@code + // note the extra parentheses around the formatted text message + CV_Error_(Error::StsOutOfRange, + ("the value at (%d, %d)=%g is out of range", badPt.x, badPt.y, badValue)); +@endcode +@param code one of Error::Code +@param args printf-like formatted error message in parentheses +*/ +#define CV_Error_( code, args ) cv::error( code, cv::format args, CV_Func, __FILE__, __LINE__ ) + +/** @brief Checks a condition at runtime and throws exception if it fails + +The macros CV_Assert (and CV_DbgAssert(expr)) evaluate the specified expression. If it is 0, the macros +raise an error (see cv::error). The macro CV_Assert checks the condition in both Debug and Release +configurations while CV_DbgAssert is only retained in the Debug configuration. +CV_AssertTerminate is analog of CV_Assert for invariants check in functions with noexcept attribute. +It does not throw exception, but terminates the application. +*/ +#define CV_Assert( expr ) do { if(!!(expr)) ; else cv::error( cv::Error::StsAssert, #expr, CV_Func, __FILE__, __LINE__ ); } while(0) +#define CV_AssertTerminate( expr ) do { if(!!(expr)) ; else cv::terminate( #expr, CV_Func, __FILE__, __LINE__ ); } while(0) + +#endif // CV_STATIC_ANALYSIS + +//! @cond IGNORED +#if !defined(__OPENCV_BUILD) // TODO: backward compatibility only +#ifndef CV_ErrorNoReturn +#define CV_ErrorNoReturn CV_Error +#endif +#ifndef CV_ErrorNoReturn_ +#define CV_ErrorNoReturn_ CV_Error_ +#endif +#endif + +#define CV_Assert_1 CV_Assert +#define CV_Assert_2( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_1( __VA_ARGS__ )) +#define CV_Assert_3( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_2( __VA_ARGS__ )) +#define CV_Assert_4( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_3( __VA_ARGS__ )) +#define CV_Assert_5( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_4( __VA_ARGS__ )) +#define CV_Assert_6( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_5( __VA_ARGS__ )) +#define CV_Assert_7( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_6( __VA_ARGS__ )) +#define CV_Assert_8( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_7( __VA_ARGS__ )) +#define CV_Assert_9( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_8( __VA_ARGS__ )) +#define CV_Assert_10( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_9( __VA_ARGS__ )) + +#define CV_Assert_N(...) do { __CV_EXPAND(__CV_CAT(CV_Assert_, __CV_VA_NUM_ARGS(__VA_ARGS__)) (__VA_ARGS__)); } while(0) + +//! @endcond + +#if defined _DEBUG || defined CV_STATIC_ANALYSIS +# define CV_DbgAssert(expr) CV_Assert(expr) +#else +/** replaced with CV_Assert(expr) in Debug configuration */ +# define CV_DbgAssert(expr) +#endif + +/* + * Hamming distance functor - counts the bit differences between two strings - useful for the Brief descriptor + * bit count of A exclusive XOR'ed with B + */ +struct CV_EXPORTS Hamming +{ + static const NormTypes normType = NORM_HAMMING; + typedef unsigned char ValueType; + typedef int ResultType; + + /** this will count the bits in a ^ b + */ + ResultType operator()( const unsigned char* a, const unsigned char* b, int size ) const; +}; + +typedef Hamming HammingLUT; + +/////////////////////////////////// inline norms //////////////////////////////////// + +template inline _Tp cv_abs(_Tp x) { return std::abs(x); } +inline int cv_abs(uchar x) { return x; } +inline int cv_abs(schar x) { return std::abs(x); } +inline int cv_abs(ushort x) { return x; } +inline int cv_abs(short x) { return std::abs(x); } + +template static inline +_AccTp normL2Sqr(const _Tp* a, int n) +{ + _AccTp s = 0; + int i=0; +#if CV_ENABLE_UNROLLED + for( ; i <= n - 4; i += 4 ) + { + _AccTp v0 = a[i], v1 = a[i+1], v2 = a[i+2], v3 = a[i+3]; + s += v0*v0 + v1*v1 + v2*v2 + v3*v3; + } +#endif + for( ; i < n; i++ ) + { + _AccTp v = a[i]; + s += v*v; + } + return s; +} + +template static inline +_AccTp normL1(const _Tp* a, int n) +{ + _AccTp s = 0; + int i = 0; +#if CV_ENABLE_UNROLLED + for(; i <= n - 4; i += 4 ) + { + s += (_AccTp)cv_abs(a[i]) + (_AccTp)cv_abs(a[i+1]) + + (_AccTp)cv_abs(a[i+2]) + (_AccTp)cv_abs(a[i+3]); + } +#endif + for( ; i < n; i++ ) + s += cv_abs(a[i]); + return s; +} + +template static inline +_AccTp normInf(const _Tp* a, int n) +{ + _AccTp s = 0; + for( int i = 0; i < n; i++ ) + s = std::max(s, (_AccTp)cv_abs(a[i])); + return s; +} + +template static inline +_AccTp normL2Sqr(const _Tp* a, const _Tp* b, int n) +{ + _AccTp s = 0; + int i= 0; +#if CV_ENABLE_UNROLLED + for(; i <= n - 4; i += 4 ) + { + _AccTp v0 = _AccTp(a[i] - b[i]), v1 = _AccTp(a[i+1] - b[i+1]), v2 = _AccTp(a[i+2] - b[i+2]), v3 = _AccTp(a[i+3] - b[i+3]); + s += v0*v0 + v1*v1 + v2*v2 + v3*v3; + } +#endif + for( ; i < n; i++ ) + { + _AccTp v = _AccTp(a[i] - b[i]); + s += v*v; + } + return s; +} + +static inline float normL2Sqr(const float* a, const float* b, int n) +{ + float s = 0.f; + for( int i = 0; i < n; i++ ) + { + float v = a[i] - b[i]; + s += v*v; + } + return s; +} + +template static inline +_AccTp normL1(const _Tp* a, const _Tp* b, int n) +{ + _AccTp s = 0; + int i= 0; +#if CV_ENABLE_UNROLLED + for(; i <= n - 4; i += 4 ) + { + _AccTp v0 = _AccTp(a[i] - b[i]), v1 = _AccTp(a[i+1] - b[i+1]), v2 = _AccTp(a[i+2] - b[i+2]), v3 = _AccTp(a[i+3] - b[i+3]); + s += std::abs(v0) + std::abs(v1) + std::abs(v2) + std::abs(v3); + } +#endif + for( ; i < n; i++ ) + { + _AccTp v = _AccTp(a[i] - b[i]); + s += std::abs(v); + } + return s; +} + +inline float normL1(const float* a, const float* b, int n) +{ + float s = 0.f; + for( int i = 0; i < n; i++ ) + { + s += std::abs(a[i] - b[i]); + } + return s; +} + +inline int normL1(const uchar* a, const uchar* b, int n) +{ + int s = 0; + for( int i = 0; i < n; i++ ) + { + s += std::abs(a[i] - b[i]); + } + return s; +} + +template static inline +_AccTp normInf(const _Tp* a, const _Tp* b, int n) +{ + _AccTp s = 0; + for( int i = 0; i < n; i++ ) + { + _AccTp v0 = a[i] - b[i]; + s = std::max(s, std::abs(v0)); + } + return s; +} + +/** @brief Computes the cube root of an argument. + + The function cubeRoot computes \f$\sqrt[3]{\texttt{val}}\f$. Negative arguments are handled correctly. + NaN and Inf are not handled. The accuracy approaches the maximum possible accuracy for + single-precision data. + @param val A function argument. + */ +CV_EXPORTS_W float cubeRoot(float val); + +/** @overload + +cubeRoot with argument of `double` type calls `std::cbrt(double)` +*/ +static inline +double cubeRoot(double val) +{ + return std::cbrt(val); +} + +/** @brief Calculates the angle of a 2D vector in degrees. + + The function fastAtan2 calculates the full-range angle of an input 2D vector. The angle is measured + in degrees and varies from 0 to 360 degrees. The accuracy is about 0.3 degrees. + @param x x-coordinate of the vector. + @param y y-coordinate of the vector. + */ +CV_EXPORTS_W float fastAtan2(float y, float x); + +/** proxy for hal::LU */ +CV_EXPORTS int LU(float* A, size_t astep, int m, float* b, size_t bstep, int n); +/** proxy for hal::LU */ +CV_EXPORTS int LU(double* A, size_t astep, int m, double* b, size_t bstep, int n); +/** proxy for hal::Cholesky */ +CV_EXPORTS bool Cholesky(float* A, size_t astep, int m, float* b, size_t bstep, int n); +/** proxy for hal::Cholesky */ +CV_EXPORTS bool Cholesky(double* A, size_t astep, int m, double* b, size_t bstep, int n); + +////////////////// forward declarations for important OpenCV types ////////////////// + +//! @cond IGNORED + +template class Vec; +template class Matx; + +template class Complex; +template class Point_; +template class Point3_; +template class Size_; +template class Rect_; +template class Scalar_; + +class CV_EXPORTS RotatedRect; +class CV_EXPORTS Range; +class CV_EXPORTS TermCriteria; +class CV_EXPORTS KeyPoint; +class CV_EXPORTS DMatch; +class CV_EXPORTS RNG; + +class CV_EXPORTS Mat; +class CV_EXPORTS MatExpr; + +class CV_EXPORTS UMat; + +class CV_EXPORTS SparseMat; +typedef Mat MatND; + +template class Mat_; +template class SparseMat_; + +class CV_EXPORTS MatConstIterator; +class CV_EXPORTS SparseMatIterator; +class CV_EXPORTS SparseMatConstIterator; +template class MatIterator_; +template class MatConstIterator_; +template class SparseMatIterator_; +template class SparseMatConstIterator_; + +namespace ogl +{ + class CV_EXPORTS Buffer; + class CV_EXPORTS Texture2D; + class CV_EXPORTS Arrays; +} + +namespace cuda +{ + class CV_EXPORTS GpuMat; + class CV_EXPORTS HostMem; + class CV_EXPORTS Stream; + class CV_EXPORTS Event; +} + +namespace cudev +{ + template class GpuMat_; +} + +namespace ipp +{ +CV_EXPORTS unsigned long long getIppFeatures(); +CV_EXPORTS void setIppStatus(int status, const char * const funcname = NULL, const char * const filename = NULL, + int line = 0); +CV_EXPORTS int getIppStatus(); +CV_EXPORTS String getIppErrorLocation(); +CV_EXPORTS_W bool useIPP(); +CV_EXPORTS_W void setUseIPP(bool flag); +CV_EXPORTS_W String getIppVersion(); + +// IPP Not-Exact mode. This function may force use of IPP then both IPP and OpenCV provide proper results +// but have internal accuracy differences which have too much direct or indirect impact on accuracy tests. +CV_EXPORTS_W bool useIPP_NotExact(); +CV_EXPORTS_W void setUseIPP_NotExact(bool flag); +#ifndef DISABLE_OPENCV_3_COMPATIBILITY +static inline bool useIPP_NE() { return useIPP_NotExact(); } +static inline void setUseIPP_NE(bool flag) { setUseIPP_NotExact(flag); } +#endif + +} // ipp + +//! @endcond + +//! @} core_utils + + + + +} // cv + +#include "opencv2/core/neon_utils.hpp" +#include "opencv2/core/vsx_utils.hpp" +#include "opencv2/core/check.hpp" + +#endif //OPENCV_CORE_BASE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/bindings_utils.hpp b/3rdParty/opencv-4.11.0/opencv2/core/bindings_utils.hpp index 9c8f9e0f2b..0e18693e24 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/bindings_utils.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/bindings_utils.hpp @@ -1,357 +1,357 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_BINDINGS_UTILS_HPP -#define OPENCV_CORE_BINDINGS_UTILS_HPP - -#include -#include -#include - -#include - -namespace cv { namespace utils { -//! @addtogroup core_utils -//! @{ - -CV_EXPORTS_W String dumpInputArray(InputArray argument); - -CV_EXPORTS_W String dumpInputArrayOfArrays(InputArrayOfArrays argument); - -CV_EXPORTS_W String dumpInputOutputArray(InputOutputArray argument); - -CV_EXPORTS_W String dumpInputOutputArrayOfArrays(InputOutputArrayOfArrays argument); - -CV_WRAP static inline -String dumpBool(bool argument) -{ - return (argument) ? String("Bool: True") : String("Bool: False"); -} - -CV_WRAP static inline -String dumpInt(int argument) -{ - return cv::format("Int: %d", argument); -} - -CV_WRAP static inline -String dumpInt64(int64 argument) -{ - std::ostringstream oss("Int64: ", std::ios::ate); - oss << argument; - return oss.str(); -} - -CV_WRAP static inline -String dumpSizeT(size_t argument) -{ - std::ostringstream oss("size_t: ", std::ios::ate); - oss << argument; - return oss.str(); -} - -CV_WRAP static inline -String dumpFloat(float argument) -{ - return cv::format("Float: %.2f", argument); -} - -CV_WRAP static inline -String dumpDouble(double argument) -{ - return cv::format("Double: %.2f", argument); -} - -CV_WRAP static inline -String dumpCString(const char* argument) -{ - return cv::format("String: %s", argument); -} - -CV_WRAP static inline -String dumpString(const String& argument) -{ - return cv::format("String: %s", argument.c_str()); -} - -CV_WRAP static inline -String dumpRect(const Rect& argument) -{ - return format("rect: (x=%d, y=%d, w=%d, h=%d)", argument.x, argument.y, - argument.width, argument.height); -} - -CV_WRAP static inline -String dumpTermCriteria(const TermCriteria& argument) -{ - return format("term_criteria: (type=%d, max_count=%d, epsilon=%lf", - argument.type, argument.maxCount, argument.epsilon); -} - -CV_WRAP static inline -String dumpRotatedRect(const RotatedRect& argument) -{ - return format("rotated_rect: (c_x=%f, c_y=%f, w=%f, h=%f, a=%f)", - argument.center.x, argument.center.y, argument.size.width, - argument.size.height, argument.angle); -} - -CV_WRAP static inline -String dumpRange(const Range& argument) -{ - if (argument == Range::all()) - { - return "range: all"; - } - else - { - return format("range: (s=%d, e=%d)", argument.start, argument.end); - } -} - -CV_EXPORTS_W String dumpVectorOfInt(const std::vector& vec); - -CV_EXPORTS_W String dumpVectorOfDouble(const std::vector& vec); - -CV_EXPORTS_W String dumpVectorOfRect(const std::vector& vec); - - -//! @cond IGNORED - -CV_WRAP static inline -String testOverloadResolution(int value, const Point& point = Point(42, 24)) -{ - return format("overload (int=%d, point=(x=%d, y=%d))", value, point.x, - point.y); -} - -CV_WRAP static inline -String testOverloadResolution(const Rect& rect) -{ - return format("overload (rect=(x=%d, y=%d, w=%d, h=%d))", rect.x, rect.y, - rect.width, rect.height); -} - -CV_WRAP static inline -RotatedRect testRotatedRect(float x, float y, float w, float h, float angle) -{ - return RotatedRect(Point2f(x, y), Size2f(w, h), angle); -} - -CV_WRAP static inline -std::vector testRotatedRectVector(float x, float y, float w, float h, float angle) -{ - std::vector result; - for (int i = 0; i < 10; i++) - result.push_back(RotatedRect(Point2f(x + i, y + 2 * i), Size2f(w, h), angle + 10 * i)); - return result; -} - -CV_WRAP static inline -int testOverwriteNativeMethod(int argument) -{ - return argument; -} - -CV_WRAP static inline -String testReservedKeywordConversion(int positional_argument, int lambda = 2, int from = 3) -{ - return format("arg=%d, lambda=%d, from=%d", positional_argument, lambda, from); -} - -CV_WRAP static inline -void generateVectorOfRect(size_t len, CV_OUT std::vector& vec) -{ - vec.resize(len); - if (len > 0) - { - RNG rng(12345); - Mat tmp(static_cast(len), 1, CV_32SC4); - rng.fill(tmp, RNG::UNIFORM, 10, 20); - tmp.copyTo(vec); - } -} - -CV_WRAP static inline -void generateVectorOfInt(size_t len, CV_OUT std::vector& vec) -{ - vec.resize(len); - if (len > 0) - { - RNG rng(554433); - Mat tmp(static_cast(len), 1, CV_32SC1); - rng.fill(tmp, RNG::UNIFORM, -10, 10); - tmp.copyTo(vec); - } -} - -CV_WRAP static inline -void generateVectorOfMat(size_t len, int rows, int cols, int dtype, CV_OUT std::vector& vec) -{ - vec.resize(len); - if (len > 0) - { - RNG rng(65431); - for (size_t i = 0; i < len; ++i) - { - vec[i].create(rows, cols, dtype); - rng.fill(vec[i], RNG::UNIFORM, 0, 10); - } - } -} - -CV_WRAP static inline -void testRaiseGeneralException() -{ - throw std::runtime_error("exception text"); -} - -CV_WRAP static inline -AsyncArray testAsyncArray(InputArray argument) -{ - AsyncPromise p; - p.setValue(argument); - return p.getArrayResult(); -} - -CV_WRAP static inline -AsyncArray testAsyncException() -{ - AsyncPromise p; - try - { - CV_Error(Error::StsOk, "Test: Generated async error"); - } - catch (const cv::Exception& e) - { - p.setException(e); - } - return p.getArrayResult(); -} - -CV_WRAP static inline -String dumpVec2i(const cv::Vec2i value = cv::Vec2i(42, 24)) { - return format("Vec2i(%d, %d)", value[0], value[1]); -} - -struct CV_EXPORTS_W_SIMPLE ClassWithKeywordProperties { - CV_PROP_RW int lambda; - CV_PROP int except; - - CV_WRAP explicit ClassWithKeywordProperties(int lambda_arg = 24, int except_arg = 42) - { - lambda = lambda_arg; - except = except_arg; - } -}; - -struct CV_EXPORTS_W_PARAMS FunctionParams -{ - CV_PROP_RW int lambda = -1; - CV_PROP_RW float sigma = 0.0f; - - FunctionParams& setLambda(int value) CV_NOEXCEPT - { - lambda = value; - return *this; - } - - FunctionParams& setSigma(float value) CV_NOEXCEPT - { - sigma = value; - return *this; - } -}; - -CV_WRAP static inline String -copyMatAndDumpNamedArguments(InputArray src, OutputArray dst, - const FunctionParams& params = FunctionParams()) -{ - src.copyTo(dst); - return format("lambda=%d, sigma=%.1f", params.lambda, - params.sigma); -} - -namespace nested { -CV_WRAP static inline bool testEchoBooleanFunction(bool flag) { - return flag; -} - -class CV_EXPORTS_W CV_WRAP_AS(ExportClassName) OriginalClassName -{ -public: - struct CV_EXPORTS_W_SIMPLE Params - { - CV_PROP_RW int int_value; - CV_PROP_RW float float_value; - - CV_WRAP explicit Params(int int_param = 123, float float_param = 3.5f) - { - int_value = int_param; - float_value = float_param; - } - }; - - explicit OriginalClassName(const OriginalClassName::Params& params = OriginalClassName::Params()) - { - params_ = params; - } - - CV_WRAP int getIntParam() const - { - return params_.int_value; - } - - CV_WRAP float getFloatParam() const - { - return params_.float_value; - } - - CV_WRAP static std::string originalName() - { - return "OriginalClassName"; - } - - CV_WRAP static Ptr - create(const OriginalClassName::Params& params = OriginalClassName::Params()) - { - return makePtr(params); - } - -private: - OriginalClassName::Params params_; -}; - -typedef OriginalClassName::Params OriginalClassName_Params; -} // namespace nested - -//! @endcond IGNORED - -namespace fs { - CV_EXPORTS_W cv::String getCacheDirectoryForDownloads(); -} // namespace fs - -//! @} // core_utils -} // namespace cv::utils - -//! @cond IGNORED - -CV_WRAP static inline -int setLogLevel(int level) -{ - // NB: Binding generators doesn't work with enums properly yet, so we define separate overload here - return cv::utils::logging::setLogLevel((cv::utils::logging::LogLevel)level); -} - -CV_WRAP static inline -int getLogLevel() -{ - return cv::utils::logging::getLogLevel(); -} - -//! @endcond IGNORED - -} // namespaces cv / utils - -#endif // OPENCV_CORE_BINDINGS_UTILS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_BINDINGS_UTILS_HPP +#define OPENCV_CORE_BINDINGS_UTILS_HPP + +#include +#include +#include + +#include + +namespace cv { namespace utils { +//! @addtogroup core_utils +//! @{ + +CV_EXPORTS_W String dumpInputArray(InputArray argument); + +CV_EXPORTS_W String dumpInputArrayOfArrays(InputArrayOfArrays argument); + +CV_EXPORTS_W String dumpInputOutputArray(InputOutputArray argument); + +CV_EXPORTS_W String dumpInputOutputArrayOfArrays(InputOutputArrayOfArrays argument); + +CV_WRAP static inline +String dumpBool(bool argument) +{ + return (argument) ? String("Bool: True") : String("Bool: False"); +} + +CV_WRAP static inline +String dumpInt(int argument) +{ + return cv::format("Int: %d", argument); +} + +CV_WRAP static inline +String dumpInt64(int64 argument) +{ + std::ostringstream oss("Int64: ", std::ios::ate); + oss << argument; + return oss.str(); +} + +CV_WRAP static inline +String dumpSizeT(size_t argument) +{ + std::ostringstream oss("size_t: ", std::ios::ate); + oss << argument; + return oss.str(); +} + +CV_WRAP static inline +String dumpFloat(float argument) +{ + return cv::format("Float: %.2f", argument); +} + +CV_WRAP static inline +String dumpDouble(double argument) +{ + return cv::format("Double: %.2f", argument); +} + +CV_WRAP static inline +String dumpCString(const char* argument) +{ + return cv::format("String: %s", argument); +} + +CV_WRAP static inline +String dumpString(const String& argument) +{ + return cv::format("String: %s", argument.c_str()); +} + +CV_WRAP static inline +String dumpRect(const Rect& argument) +{ + return format("rect: (x=%d, y=%d, w=%d, h=%d)", argument.x, argument.y, + argument.width, argument.height); +} + +CV_WRAP static inline +String dumpTermCriteria(const TermCriteria& argument) +{ + return format("term_criteria: (type=%d, max_count=%d, epsilon=%lf", + argument.type, argument.maxCount, argument.epsilon); +} + +CV_WRAP static inline +String dumpRotatedRect(const RotatedRect& argument) +{ + return format("rotated_rect: (c_x=%f, c_y=%f, w=%f, h=%f, a=%f)", + argument.center.x, argument.center.y, argument.size.width, + argument.size.height, argument.angle); +} + +CV_WRAP static inline +String dumpRange(const Range& argument) +{ + if (argument == Range::all()) + { + return "range: all"; + } + else + { + return format("range: (s=%d, e=%d)", argument.start, argument.end); + } +} + +CV_EXPORTS_W String dumpVectorOfInt(const std::vector& vec); + +CV_EXPORTS_W String dumpVectorOfDouble(const std::vector& vec); + +CV_EXPORTS_W String dumpVectorOfRect(const std::vector& vec); + + +//! @cond IGNORED + +CV_WRAP static inline +String testOverloadResolution(int value, const Point& point = Point(42, 24)) +{ + return format("overload (int=%d, point=(x=%d, y=%d))", value, point.x, + point.y); +} + +CV_WRAP static inline +String testOverloadResolution(const Rect& rect) +{ + return format("overload (rect=(x=%d, y=%d, w=%d, h=%d))", rect.x, rect.y, + rect.width, rect.height); +} + +CV_WRAP static inline +RotatedRect testRotatedRect(float x, float y, float w, float h, float angle) +{ + return RotatedRect(Point2f(x, y), Size2f(w, h), angle); +} + +CV_WRAP static inline +std::vector testRotatedRectVector(float x, float y, float w, float h, float angle) +{ + std::vector result; + for (int i = 0; i < 10; i++) + result.push_back(RotatedRect(Point2f(x + i, y + 2 * i), Size2f(w, h), angle + 10 * i)); + return result; +} + +CV_WRAP static inline +int testOverwriteNativeMethod(int argument) +{ + return argument; +} + +CV_WRAP static inline +String testReservedKeywordConversion(int positional_argument, int lambda = 2, int from = 3) +{ + return format("arg=%d, lambda=%d, from=%d", positional_argument, lambda, from); +} + +CV_WRAP static inline +void generateVectorOfRect(size_t len, CV_OUT std::vector& vec) +{ + vec.resize(len); + if (len > 0) + { + RNG rng(12345); + Mat tmp(static_cast(len), 1, CV_32SC4); + rng.fill(tmp, RNG::UNIFORM, 10, 20); + tmp.copyTo(vec); + } +} + +CV_WRAP static inline +void generateVectorOfInt(size_t len, CV_OUT std::vector& vec) +{ + vec.resize(len); + if (len > 0) + { + RNG rng(554433); + Mat tmp(static_cast(len), 1, CV_32SC1); + rng.fill(tmp, RNG::UNIFORM, -10, 10); + tmp.copyTo(vec); + } +} + +CV_WRAP static inline +void generateVectorOfMat(size_t len, int rows, int cols, int dtype, CV_OUT std::vector& vec) +{ + vec.resize(len); + if (len > 0) + { + RNG rng(65431); + for (size_t i = 0; i < len; ++i) + { + vec[i].create(rows, cols, dtype); + rng.fill(vec[i], RNG::UNIFORM, 0, 10); + } + } +} + +CV_WRAP static inline +void testRaiseGeneralException() +{ + throw std::runtime_error("exception text"); +} + +CV_WRAP static inline +AsyncArray testAsyncArray(InputArray argument) +{ + AsyncPromise p; + p.setValue(argument); + return p.getArrayResult(); +} + +CV_WRAP static inline +AsyncArray testAsyncException() +{ + AsyncPromise p; + try + { + CV_Error(Error::StsOk, "Test: Generated async error"); + } + catch (const cv::Exception& e) + { + p.setException(e); + } + return p.getArrayResult(); +} + +CV_WRAP static inline +String dumpVec2i(const cv::Vec2i value = cv::Vec2i(42, 24)) { + return format("Vec2i(%d, %d)", value[0], value[1]); +} + +struct CV_EXPORTS_W_SIMPLE ClassWithKeywordProperties { + CV_PROP_RW int lambda; + CV_PROP int except; + + CV_WRAP explicit ClassWithKeywordProperties(int lambda_arg = 24, int except_arg = 42) + { + lambda = lambda_arg; + except = except_arg; + } +}; + +struct CV_EXPORTS_W_PARAMS FunctionParams +{ + CV_PROP_RW int lambda = -1; + CV_PROP_RW float sigma = 0.0f; + + FunctionParams& setLambda(int value) CV_NOEXCEPT + { + lambda = value; + return *this; + } + + FunctionParams& setSigma(float value) CV_NOEXCEPT + { + sigma = value; + return *this; + } +}; + +CV_WRAP static inline String +copyMatAndDumpNamedArguments(InputArray src, OutputArray dst, + const FunctionParams& params = FunctionParams()) +{ + src.copyTo(dst); + return format("lambda=%d, sigma=%.1f", params.lambda, + params.sigma); +} + +namespace nested { +CV_WRAP static inline bool testEchoBooleanFunction(bool flag) { + return flag; +} + +class CV_EXPORTS_W CV_WRAP_AS(ExportClassName) OriginalClassName +{ +public: + struct CV_EXPORTS_W_SIMPLE Params + { + CV_PROP_RW int int_value; + CV_PROP_RW float float_value; + + CV_WRAP explicit Params(int int_param = 123, float float_param = 3.5f) + { + int_value = int_param; + float_value = float_param; + } + }; + + explicit OriginalClassName(const OriginalClassName::Params& params = OriginalClassName::Params()) + { + params_ = params; + } + + CV_WRAP int getIntParam() const + { + return params_.int_value; + } + + CV_WRAP float getFloatParam() const + { + return params_.float_value; + } + + CV_WRAP static std::string originalName() + { + return "OriginalClassName"; + } + + CV_WRAP static Ptr + create(const OriginalClassName::Params& params = OriginalClassName::Params()) + { + return makePtr(params); + } + +private: + OriginalClassName::Params params_; +}; + +typedef OriginalClassName::Params OriginalClassName_Params; +} // namespace nested + +//! @endcond IGNORED + +namespace fs { + CV_EXPORTS_W cv::String getCacheDirectoryForDownloads(); +} // namespace fs + +//! @} // core_utils +} // namespace cv::utils + +//! @cond IGNORED + +CV_WRAP static inline +int setLogLevel(int level) +{ + // NB: Binding generators doesn't work with enums properly yet, so we define separate overload here + return cv::utils::logging::setLogLevel((cv::utils::logging::LogLevel)level); +} + +CV_WRAP static inline +int getLogLevel() +{ + return cv::utils::logging::getLogLevel(); +} + +//! @endcond IGNORED + +} // namespaces cv / utils + +#endif // OPENCV_CORE_BINDINGS_UTILS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/bufferpool.hpp b/3rdParty/opencv-4.11.0/opencv2/core/bufferpool.hpp index e835ad025c..5322c87953 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/bufferpool.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/bufferpool.hpp @@ -1,40 +1,40 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2014, Advanced Micro Devices, Inc., all rights reserved. - -#ifndef OPENCV_CORE_BUFFER_POOL_HPP -#define OPENCV_CORE_BUFFER_POOL_HPP - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable: 4265) -#endif - -namespace cv -{ - -//! @addtogroup core_opencl -//! @{ - -class BufferPoolController -{ -protected: - ~BufferPoolController() { } -public: - virtual size_t getReservedSize() const = 0; - virtual size_t getMaxReservedSize() const = 0; - virtual void setMaxReservedSize(size_t size) = 0; - virtual void freeAllReservedBuffers() = 0; -}; - -//! @} - -} - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -#endif // OPENCV_CORE_BUFFER_POOL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2014, Advanced Micro Devices, Inc., all rights reserved. + +#ifndef OPENCV_CORE_BUFFER_POOL_HPP +#define OPENCV_CORE_BUFFER_POOL_HPP + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable: 4265) +#endif + +namespace cv +{ + +//! @addtogroup core_opencl +//! @{ + +class BufferPoolController +{ +protected: + ~BufferPoolController() { } +public: + virtual size_t getReservedSize() const = 0; + virtual size_t getMaxReservedSize() const = 0; + virtual void setMaxReservedSize(size_t size) = 0; + virtual void freeAllReservedBuffers() = 0; +}; + +//! @} + +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#endif // OPENCV_CORE_BUFFER_POOL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/check.hpp b/3rdParty/opencv-4.11.0/opencv2/core/check.hpp index aa1a839f70..dc1dd70820 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/check.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/check.hpp @@ -1,173 +1,173 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_CHECK_HPP -#define OPENCV_CORE_CHECK_HPP - -#include - -namespace cv { - -/** Returns string of cv::Mat depth value: CV_8U -> "CV_8U" or "" */ -CV_EXPORTS const char* depthToString(int depth); - -/** Returns string of cv::Mat depth value: CV_8UC3 -> "CV_8UC3" or "" */ -CV_EXPORTS String typeToString(int type); - - -//! @cond IGNORED -namespace detail { - -/** Returns string of cv::Mat depth value: CV_8U -> "CV_8U" or NULL */ -CV_EXPORTS const char* depthToString_(int depth); - -/** Returns string of cv::Mat depth value: CV_8UC3 -> "CV_8UC3" or cv::String() */ -CV_EXPORTS cv::String typeToString_(int type); - -enum TestOp { - TEST_CUSTOM = 0, - TEST_EQ = 1, - TEST_NE = 2, - TEST_LE = 3, - TEST_LT = 4, - TEST_GE = 5, - TEST_GT = 6, - CV__LAST_TEST_OP -}; - -struct CheckContext { - const char* func; - const char* file; - int line; - enum TestOp testOp; - const char* message; - const char* p1_str; - const char* p2_str; -}; - -#ifndef CV__CHECK_FILENAME -# define CV__CHECK_FILENAME __FILE__ -#endif - -#ifndef CV__CHECK_FUNCTION -# if defined _MSC_VER -# define CV__CHECK_FUNCTION __FUNCSIG__ -# elif defined __GNUC__ -# define CV__CHECK_FUNCTION __PRETTY_FUNCTION__ -# else -# define CV__CHECK_FUNCTION "" -# endif -#endif - -#define CV__CHECK_LOCATION_VARNAME(id) CVAUX_CONCAT(CVAUX_CONCAT(__cv_check_, id), __LINE__) -#define CV__DEFINE_CHECK_CONTEXT(id, message, testOp, p1_str, p2_str) \ - static const cv::detail::CheckContext CV__CHECK_LOCATION_VARNAME(id) = \ - { CV__CHECK_FUNCTION, CV__CHECK_FILENAME, __LINE__, testOp, "" message, "" p1_str, "" p2_str } - -CV_EXPORTS void CV_NORETURN check_failed_auto(const bool v1, const bool v2, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_auto(const int v1, const int v2, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_auto(const size_t v1, const size_t v2, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_auto(const float v1, const float v2, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_auto(const double v1, const double v2, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_auto(const Size_ v1, const Size_ v2, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_MatDepth(const int v1, const int v2, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_MatType(const int v1, const int v2, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_MatChannels(const int v1, const int v2, const CheckContext& ctx); - -CV_EXPORTS void CV_NORETURN check_failed_true(const bool v, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_false(const bool v, const CheckContext& ctx); - -CV_EXPORTS void CV_NORETURN check_failed_auto(const int v, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_auto(const size_t v, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_auto(const float v, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_auto(const double v, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_auto(const Size_ v, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_auto(const std::string& v1, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_MatDepth(const int v, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_MatType(const int v, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_MatChannels(const int v, const CheckContext& ctx); - - -#define CV__TEST_EQ(v1, v2) ((v1) == (v2)) -#define CV__TEST_NE(v1, v2) ((v1) != (v2)) -#define CV__TEST_LE(v1, v2) ((v1) <= (v2)) -#define CV__TEST_LT(v1, v2) ((v1) < (v2)) -#define CV__TEST_GE(v1, v2) ((v1) >= (v2)) -#define CV__TEST_GT(v1, v2) ((v1) > (v2)) - -#define CV__CHECK(id, op, type, v1, v2, v1_str, v2_str, msg_str) do { \ - if(CV__TEST_##op((v1), (v2))) ; else { \ - CV__DEFINE_CHECK_CONTEXT(id, msg_str, cv::detail::TEST_ ## op, v1_str, v2_str); \ - cv::detail::check_failed_ ## type((v1), (v2), CV__CHECK_LOCATION_VARNAME(id)); \ - } \ -} while (0) - -#define CV__CHECK_CUSTOM_TEST(id, type, v, test_expr, v_str, test_expr_str, msg_str) do { \ - if(!!(test_expr)) ; else { \ - CV__DEFINE_CHECK_CONTEXT(id, msg_str, cv::detail::TEST_CUSTOM, v_str, test_expr_str); \ - cv::detail::check_failed_ ## type((v), CV__CHECK_LOCATION_VARNAME(id)); \ - } \ -} while (0) - -} // namespace -//! @endcond - - -/// Supported values of these types: int, float, double -#define CV_CheckEQ(v1, v2, msg) CV__CHECK(_, EQ, auto, v1, v2, #v1, #v2, msg) -#define CV_CheckNE(v1, v2, msg) CV__CHECK(_, NE, auto, v1, v2, #v1, #v2, msg) -#define CV_CheckLE(v1, v2, msg) CV__CHECK(_, LE, auto, v1, v2, #v1, #v2, msg) -#define CV_CheckLT(v1, v2, msg) CV__CHECK(_, LT, auto, v1, v2, #v1, #v2, msg) -#define CV_CheckGE(v1, v2, msg) CV__CHECK(_, GE, auto, v1, v2, #v1, #v2, msg) -#define CV_CheckGT(v1, v2, msg) CV__CHECK(_, GT, auto, v1, v2, #v1, #v2, msg) - -/// Check with additional "decoding" of type values in error message -#define CV_CheckTypeEQ(t1, t2, msg) CV__CHECK(_, EQ, MatType, t1, t2, #t1, #t2, msg) -/// Check with additional "decoding" of depth values in error message -#define CV_CheckDepthEQ(d1, d2, msg) CV__CHECK(_, EQ, MatDepth, d1, d2, #d1, #d2, msg) - -#define CV_CheckChannelsEQ(c1, c2, msg) CV__CHECK(_, EQ, MatChannels, c1, c2, #c1, #c2, msg) - -/// Example: type == CV_8UC1 || type == CV_8UC3 -#define CV_CheckType(t, test_expr, msg) CV__CHECK_CUSTOM_TEST(_, MatType, t, (test_expr), #t, #test_expr, msg) - -/// Example: depth == CV_32F || depth == CV_64F -#define CV_CheckDepth(t, test_expr, msg) CV__CHECK_CUSTOM_TEST(_, MatDepth, t, (test_expr), #t, #test_expr, msg) - -/// Example: channel == 1 || channel == 3 -#define CV_CheckChannels(t, test_expr, msg) CV__CHECK_CUSTOM_TEST(_, MatChannels, t, (test_expr), #t, #test_expr, msg) - -/// Example: v == A || v == B -#define CV_Check(v, test_expr, msg) CV__CHECK_CUSTOM_TEST(_, auto, v, (test_expr), #v, #test_expr, msg) - -/// Example: v == true -#define CV_CheckTrue(v, msg) CV__CHECK_CUSTOM_TEST(_, true, v, v, #v, "", msg) - -/// Example: v == false -#define CV_CheckFalse(v, msg) CV__CHECK_CUSTOM_TEST(_, false, v, (!(v)), #v, "", msg) - -/// Some complex conditions: CV_Check(src2, src2.empty() || (src2.type() == src1.type() && src2.size() == src1.size()), "src2 should have same size/type as src1") -// TODO define pretty-printers - -#ifndef NDEBUG -#define CV_DbgCheck(v, test_expr, msg) CV__CHECK_CUSTOM_TEST(_, auto, v, (test_expr), #v, #test_expr, msg) -#define CV_DbgCheckEQ(v1, v2, msg) CV__CHECK(_, EQ, auto, v1, v2, #v1, #v2, msg) -#define CV_DbgCheckNE(v1, v2, msg) CV__CHECK(_, NE, auto, v1, v2, #v1, #v2, msg) -#define CV_DbgCheckLE(v1, v2, msg) CV__CHECK(_, LE, auto, v1, v2, #v1, #v2, msg) -#define CV_DbgCheckLT(v1, v2, msg) CV__CHECK(_, LT, auto, v1, v2, #v1, #v2, msg) -#define CV_DbgCheckGE(v1, v2, msg) CV__CHECK(_, GE, auto, v1, v2, #v1, #v2, msg) -#define CV_DbgCheckGT(v1, v2, msg) CV__CHECK(_, GT, auto, v1, v2, #v1, #v2, msg) -#else -#define CV_DbgCheck(v, test_expr, msg) do { } while (0) -#define CV_DbgCheckEQ(v1, v2, msg) do { } while (0) -#define CV_DbgCheckNE(v1, v2, msg) do { } while (0) -#define CV_DbgCheckLE(v1, v2, msg) do { } while (0) -#define CV_DbgCheckLT(v1, v2, msg) do { } while (0) -#define CV_DbgCheckGE(v1, v2, msg) do { } while (0) -#define CV_DbgCheckGT(v1, v2, msg) do { } while (0) -#endif - -} // namespace - -#endif // OPENCV_CORE_CHECK_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_CHECK_HPP +#define OPENCV_CORE_CHECK_HPP + +#include + +namespace cv { + +/** Returns string of cv::Mat depth value: CV_8U -> "CV_8U" or "" */ +CV_EXPORTS const char* depthToString(int depth); + +/** Returns string of cv::Mat depth value: CV_8UC3 -> "CV_8UC3" or "" */ +CV_EXPORTS String typeToString(int type); + + +//! @cond IGNORED +namespace detail { + +/** Returns string of cv::Mat depth value: CV_8U -> "CV_8U" or NULL */ +CV_EXPORTS const char* depthToString_(int depth); + +/** Returns string of cv::Mat depth value: CV_8UC3 -> "CV_8UC3" or cv::String() */ +CV_EXPORTS cv::String typeToString_(int type); + +enum TestOp { + TEST_CUSTOM = 0, + TEST_EQ = 1, + TEST_NE = 2, + TEST_LE = 3, + TEST_LT = 4, + TEST_GE = 5, + TEST_GT = 6, + CV__LAST_TEST_OP +}; + +struct CheckContext { + const char* func; + const char* file; + int line; + enum TestOp testOp; + const char* message; + const char* p1_str; + const char* p2_str; +}; + +#ifndef CV__CHECK_FILENAME +# define CV__CHECK_FILENAME __FILE__ +#endif + +#ifndef CV__CHECK_FUNCTION +# if defined _MSC_VER +# define CV__CHECK_FUNCTION __FUNCSIG__ +# elif defined __GNUC__ +# define CV__CHECK_FUNCTION __PRETTY_FUNCTION__ +# else +# define CV__CHECK_FUNCTION "" +# endif +#endif + +#define CV__CHECK_LOCATION_VARNAME(id) CVAUX_CONCAT(CVAUX_CONCAT(__cv_check_, id), __LINE__) +#define CV__DEFINE_CHECK_CONTEXT(id, message, testOp, p1_str, p2_str) \ + static const cv::detail::CheckContext CV__CHECK_LOCATION_VARNAME(id) = \ + { CV__CHECK_FUNCTION, CV__CHECK_FILENAME, __LINE__, testOp, "" message, "" p1_str, "" p2_str } + +CV_EXPORTS void CV_NORETURN check_failed_auto(const bool v1, const bool v2, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_auto(const int v1, const int v2, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_auto(const size_t v1, const size_t v2, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_auto(const float v1, const float v2, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_auto(const double v1, const double v2, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_auto(const Size_ v1, const Size_ v2, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_MatDepth(const int v1, const int v2, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_MatType(const int v1, const int v2, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_MatChannels(const int v1, const int v2, const CheckContext& ctx); + +CV_EXPORTS void CV_NORETURN check_failed_true(const bool v, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_false(const bool v, const CheckContext& ctx); + +CV_EXPORTS void CV_NORETURN check_failed_auto(const int v, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_auto(const size_t v, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_auto(const float v, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_auto(const double v, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_auto(const Size_ v, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_auto(const std::string& v1, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_MatDepth(const int v, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_MatType(const int v, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_MatChannels(const int v, const CheckContext& ctx); + + +#define CV__TEST_EQ(v1, v2) ((v1) == (v2)) +#define CV__TEST_NE(v1, v2) ((v1) != (v2)) +#define CV__TEST_LE(v1, v2) ((v1) <= (v2)) +#define CV__TEST_LT(v1, v2) ((v1) < (v2)) +#define CV__TEST_GE(v1, v2) ((v1) >= (v2)) +#define CV__TEST_GT(v1, v2) ((v1) > (v2)) + +#define CV__CHECK(id, op, type, v1, v2, v1_str, v2_str, msg_str) do { \ + if(CV__TEST_##op((v1), (v2))) ; else { \ + CV__DEFINE_CHECK_CONTEXT(id, msg_str, cv::detail::TEST_ ## op, v1_str, v2_str); \ + cv::detail::check_failed_ ## type((v1), (v2), CV__CHECK_LOCATION_VARNAME(id)); \ + } \ +} while (0) + +#define CV__CHECK_CUSTOM_TEST(id, type, v, test_expr, v_str, test_expr_str, msg_str) do { \ + if(!!(test_expr)) ; else { \ + CV__DEFINE_CHECK_CONTEXT(id, msg_str, cv::detail::TEST_CUSTOM, v_str, test_expr_str); \ + cv::detail::check_failed_ ## type((v), CV__CHECK_LOCATION_VARNAME(id)); \ + } \ +} while (0) + +} // namespace +//! @endcond + + +/// Supported values of these types: int, float, double +#define CV_CheckEQ(v1, v2, msg) CV__CHECK(_, EQ, auto, v1, v2, #v1, #v2, msg) +#define CV_CheckNE(v1, v2, msg) CV__CHECK(_, NE, auto, v1, v2, #v1, #v2, msg) +#define CV_CheckLE(v1, v2, msg) CV__CHECK(_, LE, auto, v1, v2, #v1, #v2, msg) +#define CV_CheckLT(v1, v2, msg) CV__CHECK(_, LT, auto, v1, v2, #v1, #v2, msg) +#define CV_CheckGE(v1, v2, msg) CV__CHECK(_, GE, auto, v1, v2, #v1, #v2, msg) +#define CV_CheckGT(v1, v2, msg) CV__CHECK(_, GT, auto, v1, v2, #v1, #v2, msg) + +/// Check with additional "decoding" of type values in error message +#define CV_CheckTypeEQ(t1, t2, msg) CV__CHECK(_, EQ, MatType, t1, t2, #t1, #t2, msg) +/// Check with additional "decoding" of depth values in error message +#define CV_CheckDepthEQ(d1, d2, msg) CV__CHECK(_, EQ, MatDepth, d1, d2, #d1, #d2, msg) + +#define CV_CheckChannelsEQ(c1, c2, msg) CV__CHECK(_, EQ, MatChannels, c1, c2, #c1, #c2, msg) + +/// Example: type == CV_8UC1 || type == CV_8UC3 +#define CV_CheckType(t, test_expr, msg) CV__CHECK_CUSTOM_TEST(_, MatType, t, (test_expr), #t, #test_expr, msg) + +/// Example: depth == CV_32F || depth == CV_64F +#define CV_CheckDepth(t, test_expr, msg) CV__CHECK_CUSTOM_TEST(_, MatDepth, t, (test_expr), #t, #test_expr, msg) + +/// Example: channel == 1 || channel == 3 +#define CV_CheckChannels(t, test_expr, msg) CV__CHECK_CUSTOM_TEST(_, MatChannels, t, (test_expr), #t, #test_expr, msg) + +/// Example: v == A || v == B +#define CV_Check(v, test_expr, msg) CV__CHECK_CUSTOM_TEST(_, auto, v, (test_expr), #v, #test_expr, msg) + +/// Example: v == true +#define CV_CheckTrue(v, msg) CV__CHECK_CUSTOM_TEST(_, true, v, v, #v, "", msg) + +/// Example: v == false +#define CV_CheckFalse(v, msg) CV__CHECK_CUSTOM_TEST(_, false, v, (!(v)), #v, "", msg) + +/// Some complex conditions: CV_Check(src2, src2.empty() || (src2.type() == src1.type() && src2.size() == src1.size()), "src2 should have same size/type as src1") +// TODO define pretty-printers + +#ifndef NDEBUG +#define CV_DbgCheck(v, test_expr, msg) CV__CHECK_CUSTOM_TEST(_, auto, v, (test_expr), #v, #test_expr, msg) +#define CV_DbgCheckEQ(v1, v2, msg) CV__CHECK(_, EQ, auto, v1, v2, #v1, #v2, msg) +#define CV_DbgCheckNE(v1, v2, msg) CV__CHECK(_, NE, auto, v1, v2, #v1, #v2, msg) +#define CV_DbgCheckLE(v1, v2, msg) CV__CHECK(_, LE, auto, v1, v2, #v1, #v2, msg) +#define CV_DbgCheckLT(v1, v2, msg) CV__CHECK(_, LT, auto, v1, v2, #v1, #v2, msg) +#define CV_DbgCheckGE(v1, v2, msg) CV__CHECK(_, GE, auto, v1, v2, #v1, #v2, msg) +#define CV_DbgCheckGT(v1, v2, msg) CV__CHECK(_, GT, auto, v1, v2, #v1, #v2, msg) +#else +#define CV_DbgCheck(v, test_expr, msg) do { } while (0) +#define CV_DbgCheckEQ(v1, v2, msg) do { } while (0) +#define CV_DbgCheckNE(v1, v2, msg) do { } while (0) +#define CV_DbgCheckLE(v1, v2, msg) do { } while (0) +#define CV_DbgCheckLT(v1, v2, msg) do { } while (0) +#define CV_DbgCheckGE(v1, v2, msg) do { } while (0) +#define CV_DbgCheckGT(v1, v2, msg) do { } while (0) +#endif + +} // namespace + +#endif // OPENCV_CORE_CHECK_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/core.hpp b/3rdParty/opencv-4.11.0/opencv2/core/core.hpp index 438918359b..3a884c3909 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/core.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/core.hpp @@ -1,48 +1,48 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifdef __OPENCV_BUILD -#error this is a compatibility header which should not be used inside the OpenCV library -#endif - -#include "opencv2/core.hpp" +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/core.hpp" diff --git a/3rdParty/opencv-4.11.0/opencv2/core/core_c.h b/3rdParty/opencv-4.11.0/opencv2/core/core_c.h index 7b686b86f3..7ed5cf221b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/core_c.h +++ b/3rdParty/opencv-4.11.0/opencv2/core/core_c.h @@ -1,3128 +1,3128 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - - -#ifndef OPENCV_CORE_C_H -#define OPENCV_CORE_C_H - -#include "opencv2/core/types_c.h" - -#ifdef __cplusplus -/* disable MSVC warning C4190 / clang-cl -Wreturn-type-c-linkage: - 'function' has C-linkage specified, but returns UDT 'typename' - which is incompatible with C - - It is OK to disable it because we only extend few plain structures with - C++ constructors for simpler interoperability with C++ API of the library -*/ -# if defined(__clang__) - // handle clang on Linux and clang-cl (i. e. clang on Windows) first -# pragma GCC diagnostic ignored "-Wreturn-type-c-linkage" -# elif defined(_MSC_VER) - // then handle MSVC -# pragma warning(disable:4190) -# endif -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/** @addtogroup core_c - @{ -*/ - -/****************************************************************************************\ -* Array allocation, deallocation, initialization and access to elements * -\****************************************************************************************/ - -/** `malloc` wrapper. - If there is no enough memory, the function - (as well as other OpenCV functions that call cvAlloc) - raises an error. */ -CVAPI(void*) cvAlloc( size_t size ); - -/** `free` wrapper. - Here and further all the memory releasing functions - (that all call cvFree) take double pointer in order to - to clear pointer to the data after releasing it. - Passing pointer to NULL pointer is Ok: nothing happens in this case -*/ -CVAPI(void) cvFree_( void* ptr ); -#define cvFree(ptr) (cvFree_(*(ptr)), *(ptr)=0) - -/** @brief Creates an image header but does not allocate the image data. - -@param size Image width and height -@param depth Image depth (see cvCreateImage ) -@param channels Number of channels (see cvCreateImage ) - */ -CVAPI(IplImage*) cvCreateImageHeader( CvSize size, int depth, int channels ); - -/** @brief Initializes an image header that was previously allocated. - -The returned IplImage\* points to the initialized header. -@param image Image header to initialize -@param size Image width and height -@param depth Image depth (see cvCreateImage ) -@param channels Number of channels (see cvCreateImage ) -@param origin Top-left IPL_ORIGIN_TL or bottom-left IPL_ORIGIN_BL -@param align Alignment for image rows, typically 4 or 8 bytes - */ -CVAPI(IplImage*) cvInitImageHeader( IplImage* image, CvSize size, int depth, - int channels, int origin CV_DEFAULT(0), - int align CV_DEFAULT(4)); - -/** @brief Creates an image header and allocates the image data. - -This function call is equivalent to the following code: -@code - header = cvCreateImageHeader(size, depth, channels); - cvCreateData(header); -@endcode -@param size Image width and height -@param depth Bit depth of image elements. See IplImage for valid depths. -@param channels Number of channels per pixel. See IplImage for details. This function only creates -images with interleaved channels. - */ -CVAPI(IplImage*) cvCreateImage( CvSize size, int depth, int channels ); - -/** @brief Deallocates an image header. - -This call is an analogue of : -@code - if(image ) - { - iplDeallocate(*image, IPL_IMAGE_HEADER | IPL_IMAGE_ROI); - *image = 0; - } -@endcode -but it does not use IPL functions by default (see the CV_TURN_ON_IPL_COMPATIBILITY macro). -@param image Double pointer to the image header - */ -CVAPI(void) cvReleaseImageHeader( IplImage** image ); - -/** @brief Deallocates the image header and the image data. - -This call is a shortened form of : -@code - if(*image ) - { - cvReleaseData(*image); - cvReleaseImageHeader(image); - } -@endcode -@param image Double pointer to the image header -*/ -CVAPI(void) cvReleaseImage( IplImage** image ); - -/** Creates a copy of IPL image (widthStep may differ) */ -CVAPI(IplImage*) cvCloneImage( const IplImage* image ); - -/** @brief Sets the channel of interest in an IplImage. - -If the ROI is set to NULL and the coi is *not* 0, the ROI is allocated. Most OpenCV functions do -*not* support the COI setting, so to process an individual image/matrix channel one may copy (via -cvCopy or cvSplit) the channel to a separate image/matrix, process it and then copy the result -back (via cvCopy or cvMerge) if needed. -@param image A pointer to the image header -@param coi The channel of interest. 0 - all channels are selected, 1 - first channel is selected, -etc. Note that the channel indices become 1-based. - */ -CVAPI(void) cvSetImageCOI( IplImage* image, int coi ); - -/** @brief Returns the index of the channel of interest. - -Returns the channel of interest of in an IplImage. Returned values correspond to the coi in -cvSetImageCOI. -@param image A pointer to the image header - */ -CVAPI(int) cvGetImageCOI( const IplImage* image ); - -/** @brief Sets an image Region Of Interest (ROI) for a given rectangle. - -If the original image ROI was NULL and the rect is not the whole image, the ROI structure is -allocated. - -Most OpenCV functions support the use of ROI and treat the image rectangle as a separate image. For -example, all of the pixel coordinates are counted from the top-left (or bottom-left) corner of the -ROI, not the original image. -@param image A pointer to the image header -@param rect The ROI rectangle - */ -CVAPI(void) cvSetImageROI( IplImage* image, CvRect rect ); - -/** @brief Resets the image ROI to include the entire image and releases the ROI structure. - -This produces a similar result to the following, but in addition it releases the ROI structure. : -@code - cvSetImageROI(image, cvRect(0, 0, image->width, image->height )); - cvSetImageCOI(image, 0); -@endcode -@param image A pointer to the image header - */ -CVAPI(void) cvResetImageROI( IplImage* image ); - -/** @brief Returns the image ROI. - -If there is no ROI set, cvRect(0,0,image-\>width,image-\>height) is returned. -@param image A pointer to the image header - */ -CVAPI(CvRect) cvGetImageROI( const IplImage* image ); - -/** @brief Creates a matrix header but does not allocate the matrix data. - -The function allocates a new matrix header and returns a pointer to it. The matrix data can then be -allocated using cvCreateData or set explicitly to user-allocated data via cvSetData. -@param rows Number of rows in the matrix -@param cols Number of columns in the matrix -@param type Type of the matrix elements, see cvCreateMat - */ -CVAPI(CvMat*) cvCreateMatHeader( int rows, int cols, int type ); - -#define CV_AUTOSTEP 0x7fffffff - -/** @brief Initializes a pre-allocated matrix header. - -This function is often used to process raw data with OpenCV matrix functions. For example, the -following code computes the matrix product of two matrices, stored as ordinary arrays: -@code - double a[] = { 1, 2, 3, 4, - 5, 6, 7, 8, - 9, 10, 11, 12 }; - - double b[] = { 1, 5, 9, - 2, 6, 10, - 3, 7, 11, - 4, 8, 12 }; - - double c[9]; - CvMat Ma, Mb, Mc ; - - cvInitMatHeader(&Ma, 3, 4, CV_64FC1, a); - cvInitMatHeader(&Mb, 4, 3, CV_64FC1, b); - cvInitMatHeader(&Mc, 3, 3, CV_64FC1, c); - - cvMatMulAdd(&Ma, &Mb, 0, &Mc); - // the c array now contains the product of a (3x4) and b (4x3) -@endcode -@param mat A pointer to the matrix header to be initialized -@param rows Number of rows in the matrix -@param cols Number of columns in the matrix -@param type Type of the matrix elements, see cvCreateMat . -@param data Optional: data pointer assigned to the matrix header -@param step Optional: full row width in bytes of the assigned data. By default, the minimal -possible step is used which assumes there are no gaps between subsequent rows of the matrix. - */ -CVAPI(CvMat*) cvInitMatHeader( CvMat* mat, int rows, int cols, - int type, void* data CV_DEFAULT(NULL), - int step CV_DEFAULT(CV_AUTOSTEP) ); - -/** @brief Creates a matrix header and allocates the matrix data. - -The function call is equivalent to the following code: -@code - CvMat* mat = cvCreateMatHeader(rows, cols, type); - cvCreateData(mat); -@endcode -@param rows Number of rows in the matrix -@param cols Number of columns in the matrix -@param type The type of the matrix elements in the form -CV_\\C\ , where S=signed, U=unsigned, F=float. For -example, CV _ 8UC1 means the elements are 8-bit unsigned and the there is 1 channel, and CV _ -32SC2 means the elements are 32-bit signed and there are 2 channels. - */ -CVAPI(CvMat*) cvCreateMat( int rows, int cols, int type ); - -/** @brief Deallocates a matrix. - -The function decrements the matrix data reference counter and deallocates matrix header. If the data -reference counter is 0, it also deallocates the data. : -@code - if(*mat ) - cvDecRefData(*mat); - cvFree((void**)mat); -@endcode -@param mat Double pointer to the matrix - */ -CVAPI(void) cvReleaseMat( CvMat** mat ); - -/** @brief Decrements an array data reference counter. - -The function decrements the data reference counter in a CvMat or CvMatND if the reference counter - -pointer is not NULL. If the counter reaches zero, the data is deallocated. In the current -implementation the reference counter is not NULL only if the data was allocated using the -cvCreateData function. The counter will be NULL in other cases such as: external data was assigned -to the header using cvSetData, header is part of a larger matrix or image, or the header was -converted from an image or n-dimensional matrix header. -@param arr Pointer to an array header - */ -CV_INLINE void cvDecRefData( CvArr* arr ) -{ - if( CV_IS_MAT( arr )) - { - CvMat* mat = (CvMat*)arr; - mat->data.ptr = NULL; - if( mat->refcount != NULL && --*mat->refcount == 0 ) - cvFree( &mat->refcount ); - mat->refcount = NULL; - } - else if( CV_IS_MATND( arr )) - { - CvMatND* mat = (CvMatND*)arr; - mat->data.ptr = NULL; - if( mat->refcount != NULL && --*mat->refcount == 0 ) - cvFree( &mat->refcount ); - mat->refcount = NULL; - } -} - -/** @brief Increments array data reference counter. - -The function increments CvMat or CvMatND data reference counter and returns the new counter value if -the reference counter pointer is not NULL, otherwise it returns zero. -@param arr Array header - */ -CV_INLINE int cvIncRefData( CvArr* arr ) -{ - int refcount = 0; - if( CV_IS_MAT( arr )) - { - CvMat* mat = (CvMat*)arr; - if( mat->refcount != NULL ) - refcount = ++*mat->refcount; - } - else if( CV_IS_MATND( arr )) - { - CvMatND* mat = (CvMatND*)arr; - if( mat->refcount != NULL ) - refcount = ++*mat->refcount; - } - return refcount; -} - - -/** Creates an exact copy of the input matrix (except, may be, step value) */ -CVAPI(CvMat*) cvCloneMat( const CvMat* mat ); - - -/** @brief Returns matrix header corresponding to the rectangular sub-array of input image or matrix. - -The function returns header, corresponding to a specified rectangle of the input array. In other - -words, it allows the user to treat a rectangular part of input array as a stand-alone array. ROI is -taken into account by the function so the sub-array of ROI is actually extracted. -@param arr Input array -@param submat Pointer to the resultant sub-array header -@param rect Zero-based coordinates of the rectangle of interest - */ -CVAPI(CvMat*) cvGetSubRect( const CvArr* arr, CvMat* submat, CvRect rect ); -#define cvGetSubArr cvGetSubRect - -/** @brief Returns array row or row span. - -The function returns the header, corresponding to a specified row/row span of the input array. -cvGetRow(arr, submat, row) is a shortcut for cvGetRows(arr, submat, row, row+1). -@param arr Input array -@param submat Pointer to the resulting sub-array header -@param start_row Zero-based index of the starting row (inclusive) of the span -@param end_row Zero-based index of the ending row (exclusive) of the span -@param delta_row Index step in the row span. That is, the function extracts every delta_row -th -row from start_row and up to (but not including) end_row . - */ -CVAPI(CvMat*) cvGetRows( const CvArr* arr, CvMat* submat, - int start_row, int end_row, - int delta_row CV_DEFAULT(1)); - -/** @overload -@param arr Input array -@param submat Pointer to the resulting sub-array header -@param row Zero-based index of the selected row -*/ -CV_INLINE CvMat* cvGetRow( const CvArr* arr, CvMat* submat, int row ) -{ - return cvGetRows( arr, submat, row, row + 1, 1 ); -} - - -/** @brief Returns one of more array columns. - -The function returns the header, corresponding to a specified column span of the input array. That - -is, no data is copied. Therefore, any modifications of the submatrix will affect the original array. -If you need to copy the columns, use cvCloneMat. cvGetCol(arr, submat, col) is a shortcut for -cvGetCols(arr, submat, col, col+1). -@param arr Input array -@param submat Pointer to the resulting sub-array header -@param start_col Zero-based index of the starting column (inclusive) of the span -@param end_col Zero-based index of the ending column (exclusive) of the span - */ -CVAPI(CvMat*) cvGetCols( const CvArr* arr, CvMat* submat, - int start_col, int end_col ); - -/** @overload -@param arr Input array -@param submat Pointer to the resulting sub-array header -@param col Zero-based index of the selected column -*/ -CV_INLINE CvMat* cvGetCol( const CvArr* arr, CvMat* submat, int col ) -{ - return cvGetCols( arr, submat, col, col + 1 ); -} - -/** @brief Returns one of array diagonals. - -The function returns the header, corresponding to a specified diagonal of the input array. -@param arr Input array -@param submat Pointer to the resulting sub-array header -@param diag Index of the array diagonal. Zero value corresponds to the main diagonal, -1 -corresponds to the diagonal above the main, 1 corresponds to the diagonal below the main, and so -forth. - */ -CVAPI(CvMat*) cvGetDiag( const CvArr* arr, CvMat* submat, - int diag CV_DEFAULT(0)); - -/** low-level scalar <-> raw data conversion functions */ -CVAPI(void) cvScalarToRawData( const CvScalar* scalar, void* data, int type, - int extend_to_12 CV_DEFAULT(0) ); - -CVAPI(void) cvRawDataToScalar( const void* data, int type, CvScalar* scalar ); - -/** @brief Creates a new matrix header but does not allocate the matrix data. - -The function allocates a header for a multi-dimensional dense array. The array data can further be -allocated using cvCreateData or set explicitly to user-allocated data via cvSetData. -@param dims Number of array dimensions -@param sizes Array of dimension sizes -@param type Type of array elements, see cvCreateMat - */ -CVAPI(CvMatND*) cvCreateMatNDHeader( int dims, const int* sizes, int type ); - -/** @brief Creates the header and allocates the data for a multi-dimensional dense array. - -This function call is equivalent to the following code: -@code - CvMatND* mat = cvCreateMatNDHeader(dims, sizes, type); - cvCreateData(mat); -@endcode -@param dims Number of array dimensions. This must not exceed CV_MAX_DIM (32 by default, but can be -changed at build time). -@param sizes Array of dimension sizes. -@param type Type of array elements, see cvCreateMat . - */ -CVAPI(CvMatND*) cvCreateMatND( int dims, const int* sizes, int type ); - -/** @brief Initializes a pre-allocated multi-dimensional array header. - -@param mat A pointer to the array header to be initialized -@param dims The number of array dimensions -@param sizes An array of dimension sizes -@param type Type of array elements, see cvCreateMat -@param data Optional data pointer assigned to the matrix header - */ -CVAPI(CvMatND*) cvInitMatNDHeader( CvMatND* mat, int dims, const int* sizes, - int type, void* data CV_DEFAULT(NULL) ); - -/** @brief Deallocates a multi-dimensional array. - -The function decrements the array data reference counter and releases the array header. If the -reference counter reaches 0, it also deallocates the data. : -@code - if(*mat ) - cvDecRefData(*mat); - cvFree((void**)mat); -@endcode -@param mat Double pointer to the array - */ -CV_INLINE void cvReleaseMatND( CvMatND** mat ) -{ - cvReleaseMat( (CvMat**)mat ); -} - -/** Creates a copy of CvMatND (except, may be, steps) */ -CVAPI(CvMatND*) cvCloneMatND( const CvMatND* mat ); - -/** @brief Creates sparse array. - -The function allocates a multi-dimensional sparse array. Initially the array contain no elements, -that is PtrND and other related functions will return 0 for every index. -@param dims Number of array dimensions. In contrast to the dense matrix, the number of dimensions is -practically unlimited (up to \f$2^{16}\f$ ). -@param sizes Array of dimension sizes -@param type Type of array elements. The same as for CvMat - */ -CVAPI(CvSparseMat*) cvCreateSparseMat( int dims, const int* sizes, int type ); - -/** @brief Deallocates sparse array. - -The function releases the sparse array and clears the array pointer upon exit. -@param mat Double pointer to the array - */ -CVAPI(void) cvReleaseSparseMat( CvSparseMat** mat ); - -/** Creates a copy of CvSparseMat (except, may be, zero items) */ -CVAPI(CvSparseMat*) cvCloneSparseMat( const CvSparseMat* mat ); - -/** @brief Initializes sparse array elements iterator. - -The function initializes iterator of sparse array elements and returns pointer to the first element, -or NULL if the array is empty. -@param mat Input array -@param mat_iterator Initialized iterator - */ -CVAPI(CvSparseNode*) cvInitSparseMatIterator( const CvSparseMat* mat, - CvSparseMatIterator* mat_iterator ); - -/** @brief Returns the next sparse matrix element - -The function moves iterator to the next sparse matrix element and returns pointer to it. In the -current version there is no any particular order of the elements, because they are stored in the -hash table. The sample below demonstrates how to iterate through the sparse matrix: -@code - // print all the non-zero sparse matrix elements and compute their sum - double sum = 0; - int i, dims = cvGetDims(sparsemat); - CvSparseMatIterator it; - CvSparseNode* node = cvInitSparseMatIterator(sparsemat, &it); - - for(; node != 0; node = cvGetNextSparseNode(&it)) - { - int* idx = CV_NODE_IDX(array, node); - float val = *(float*)CV_NODE_VAL(array, node); - printf("M"); - for(i = 0; i < dims; i++ ) - printf("[%d]", idx[i]); - printf("=%g\n", val); - - sum += val; - } - - printf("nTotal sum = %g\n", sum); -@endcode -@param mat_iterator Sparse array iterator - */ -CV_INLINE CvSparseNode* cvGetNextSparseNode( CvSparseMatIterator* mat_iterator ) -{ - if( mat_iterator->node->next ) - return mat_iterator->node = mat_iterator->node->next; - else - { - int idx; - for( idx = ++mat_iterator->curidx; idx < mat_iterator->mat->hashsize; idx++ ) - { - CvSparseNode* node = (CvSparseNode*)mat_iterator->mat->hashtable[idx]; - if( node ) - { - mat_iterator->curidx = idx; - return mat_iterator->node = node; - } - } - return NULL; - } -} - - -#define CV_MAX_ARR 10 - -/** matrix iterator: used for n-ary operations on dense arrays */ -typedef struct CvNArrayIterator -{ - int count; /**< number of arrays */ - int dims; /**< number of dimensions to iterate */ - CvSize size; /**< maximal common linear size: { width = size, height = 1 } */ - uchar* ptr[CV_MAX_ARR]; /**< pointers to the array slices */ - int stack[CV_MAX_DIM]; /**< for internal use */ - CvMatND* hdr[CV_MAX_ARR]; /**< pointers to the headers of the - matrices that are processed */ -} -CvNArrayIterator; - -#define CV_NO_DEPTH_CHECK 1 -#define CV_NO_CN_CHECK 2 -#define CV_NO_SIZE_CHECK 4 - -/** initializes iterator that traverses through several arrays simultaneously - (the function together with cvNextArraySlice is used for - N-ari element-wise operations) */ -CVAPI(int) cvInitNArrayIterator( int count, CvArr** arrs, - const CvArr* mask, CvMatND* stubs, - CvNArrayIterator* array_iterator, - int flags CV_DEFAULT(0) ); - -/** returns zero value if iteration is finished, non-zero (slice length) otherwise */ -CVAPI(int) cvNextNArraySlice( CvNArrayIterator* array_iterator ); - - -/** @brief Returns type of array elements. - -The function returns type of the array elements. In the case of IplImage the type is converted to -CvMat-like representation. For example, if the image has been created as: -@code - IplImage* img = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 3); -@endcode -The code cvGetElemType(img) will return CV_8UC3. -@param arr Input array - */ -CVAPI(int) cvGetElemType( const CvArr* arr ); - -/** @brief Return number of array dimensions - -The function returns the array dimensionality and the array of dimension sizes. In the case of -IplImage or CvMat it always returns 2 regardless of number of image/matrix rows. For example, the -following code calculates total number of array elements: -@code - int sizes[CV_MAX_DIM]; - int i, total = 1; - int dims = cvGetDims(arr, size); - for(i = 0; i < dims; i++ ) - total *= sizes[i]; -@endcode -@param arr Input array -@param sizes Optional output vector of the array dimension sizes. For 2d arrays the number of rows -(height) goes first, number of columns (width) next. - */ -CVAPI(int) cvGetDims( const CvArr* arr, int* sizes CV_DEFAULT(NULL) ); - - -/** @brief Returns array size along the specified dimension. - -@param arr Input array -@param index Zero-based dimension index (for matrices 0 means number of rows, 1 means number of -columns; for images 0 means height, 1 means width) - */ -CVAPI(int) cvGetDimSize( const CvArr* arr, int index ); - - -/** @brief Return pointer to a particular array element. - -The functions return a pointer to a specific array element. Number of array dimension should match -to the number of indices passed to the function except for cvPtr1D function that can be used for -sequential access to 1D, 2D or nD dense arrays. - -The functions can be used for sparse arrays as well - if the requested node does not exist they -create it and set it to zero. - -All these as well as other functions accessing array elements ( cvGetND , cvGetRealND , cvSet -, cvSetND , cvSetRealND ) raise an error in case if the element index is out of range. -@param arr Input array -@param idx0 The first zero-based component of the element index -@param type Optional output parameter: type of matrix elements - */ -CVAPI(uchar*) cvPtr1D( const CvArr* arr, int idx0, int* type CV_DEFAULT(NULL)); -/** @overload */ -CVAPI(uchar*) cvPtr2D( const CvArr* arr, int idx0, int idx1, int* type CV_DEFAULT(NULL) ); -/** @overload */ -CVAPI(uchar*) cvPtr3D( const CvArr* arr, int idx0, int idx1, int idx2, - int* type CV_DEFAULT(NULL)); -/** @overload -@param arr Input array -@param idx Array of the element indices -@param type Optional output parameter: type of matrix elements -@param create_node Optional input parameter for sparse matrices. Non-zero value of the parameter -means that the requested element is created if it does not exist already. -@param precalc_hashval Optional input parameter for sparse matrices. If the pointer is not NULL, -the function does not recalculate the node hash value, but takes it from the specified location. -It is useful for speeding up pair-wise operations (TODO: provide an example) -*/ -CVAPI(uchar*) cvPtrND( const CvArr* arr, const int* idx, int* type CV_DEFAULT(NULL), - int create_node CV_DEFAULT(1), - unsigned* precalc_hashval CV_DEFAULT(NULL)); - -/** @brief Return a specific array element. - -The functions return a specific array element. In the case of a sparse array the functions return 0 -if the requested node does not exist (no new node is created by the functions). -@param arr Input array -@param idx0 The first zero-based component of the element index - */ -CVAPI(CvScalar) cvGet1D( const CvArr* arr, int idx0 ); -/** @overload */ -CVAPI(CvScalar) cvGet2D( const CvArr* arr, int idx0, int idx1 ); -/** @overload */ -CVAPI(CvScalar) cvGet3D( const CvArr* arr, int idx0, int idx1, int idx2 ); -/** @overload -@param arr Input array -@param idx Array of the element indices -*/ -CVAPI(CvScalar) cvGetND( const CvArr* arr, const int* idx ); - -/** @brief Return a specific element of single-channel 1D, 2D, 3D or nD array. - -Returns a specific element of a single-channel array. If the array has multiple channels, a runtime -error is raised. Note that Get?D functions can be used safely for both single-channel and -multiple-channel arrays though they are a bit slower. - -In the case of a sparse array the functions return 0 if the requested node does not exist (no new -node is created by the functions). -@param arr Input array. Must have a single channel. -@param idx0 The first zero-based component of the element index - */ -CVAPI(double) cvGetReal1D( const CvArr* arr, int idx0 ); -/** @overload */ -CVAPI(double) cvGetReal2D( const CvArr* arr, int idx0, int idx1 ); -/** @overload */ -CVAPI(double) cvGetReal3D( const CvArr* arr, int idx0, int idx1, int idx2 ); -/** @overload -@param arr Input array. Must have a single channel. -@param idx Array of the element indices -*/ -CVAPI(double) cvGetRealND( const CvArr* arr, const int* idx ); - -/** @brief Change the particular array element. - -The functions assign the new value to a particular array element. In the case of a sparse array the -functions create the node if it does not exist yet. -@param arr Input array -@param idx0 The first zero-based component of the element index -@param value The assigned value - */ -CVAPI(void) cvSet1D( CvArr* arr, int idx0, CvScalar value ); -/** @overload */ -CVAPI(void) cvSet2D( CvArr* arr, int idx0, int idx1, CvScalar value ); -/** @overload */ -CVAPI(void) cvSet3D( CvArr* arr, int idx0, int idx1, int idx2, CvScalar value ); -/** @overload -@param arr Input array -@param idx Array of the element indices -@param value The assigned value -*/ -CVAPI(void) cvSetND( CvArr* arr, const int* idx, CvScalar value ); - -/** @brief Change a specific array element. - -The functions assign a new value to a specific element of a single-channel array. If the array has -multiple channels, a runtime error is raised. Note that the Set\*D function can be used safely for -both single-channel and multiple-channel arrays, though they are a bit slower. - -In the case of a sparse array the functions create the node if it does not yet exist. -@param arr Input array -@param idx0 The first zero-based component of the element index -@param value The assigned value - */ -CVAPI(void) cvSetReal1D( CvArr* arr, int idx0, double value ); -/** @overload */ -CVAPI(void) cvSetReal2D( CvArr* arr, int idx0, int idx1, double value ); -/** @overload */ -CVAPI(void) cvSetReal3D( CvArr* arr, int idx0, - int idx1, int idx2, double value ); -/** @overload -@param arr Input array -@param idx Array of the element indices -@param value The assigned value -*/ -CVAPI(void) cvSetRealND( CvArr* arr, const int* idx, double value ); - -/** clears element of ND dense array, - in case of sparse arrays it deletes the specified node */ -CVAPI(void) cvClearND( CvArr* arr, const int* idx ); - -/** @brief Returns matrix header for arbitrary array. - -The function returns a matrix header for the input array that can be a matrix - CvMat, an image - -IplImage, or a multi-dimensional dense array - CvMatND (the third option is allowed only if -allowND != 0) . In the case of matrix the function simply returns the input pointer. In the case of -IplImage\* or CvMatND it initializes the header structure with parameters of the current image ROI -and returns &header. Because COI is not supported by CvMat, it is returned separately. - -The function provides an easy way to handle both types of arrays - IplImage and CvMat using the same -code. Input array must have non-zero data pointer, otherwise the function will report an error. - -@note If the input array is IplImage with planar data layout and COI set, the function returns the -pointer to the selected plane and COI == 0. This feature allows user to process IplImage structures -with planar data layout, even though OpenCV does not support such images. -@param arr Input array -@param header Pointer to CvMat structure used as a temporary buffer -@param coi Optional output parameter for storing COI -@param allowND If non-zero, the function accepts multi-dimensional dense arrays (CvMatND\*) and -returns 2D matrix (if CvMatND has two dimensions) or 1D matrix (when CvMatND has 1 dimension or -more than 2 dimensions). The CvMatND array must be continuous. -@sa cvGetImage, cvarrToMat. - */ -CVAPI(CvMat*) cvGetMat( const CvArr* arr, CvMat* header, - int* coi CV_DEFAULT(NULL), - int allowND CV_DEFAULT(0)); - -/** @brief Returns image header for arbitrary array. - -The function returns the image header for the input array that can be a matrix (CvMat) or image -(IplImage). In the case of an image the function simply returns the input pointer. In the case of -CvMat it initializes an image_header structure with the parameters of the input matrix. Note that -if we transform IplImage to CvMat using cvGetMat and then transform CvMat back to IplImage using -this function, we will get different headers if the ROI is set in the original image. -@param arr Input array -@param image_header Pointer to IplImage structure used as a temporary buffer - */ -CVAPI(IplImage*) cvGetImage( const CvArr* arr, IplImage* image_header ); - - -/** @brief Changes the shape of a multi-dimensional array without copying the data. - -The function is an advanced version of cvReshape that can work with multi-dimensional arrays as -well (though it can work with ordinary images and matrices) and change the number of dimensions. - -Below are the two samples from the cvReshape description rewritten using cvReshapeMatND: -@code - IplImage* color_img = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U, 3); - IplImage gray_img_hdr, *gray_img; - gray_img = (IplImage*)cvReshapeMatND(color_img, sizeof(gray_img_hdr), &gray_img_hdr, 1, 0, 0); - ... - int size[] = { 2, 2, 2 }; - CvMatND* mat = cvCreateMatND(3, size, CV_32F); - CvMat row_header, *row; - row = (CvMat*)cvReshapeMatND(mat, sizeof(row_header), &row_header, 0, 1, 0); -@endcode -In C, the header file for this function includes a convenient macro cvReshapeND that does away with -the sizeof_header parameter. So, the lines containing the call to cvReshapeMatND in the examples -may be replaced as follow: -@code - gray_img = (IplImage*)cvReshapeND(color_img, &gray_img_hdr, 1, 0, 0); - ... - row = (CvMat*)cvReshapeND(mat, &row_header, 0, 1, 0); -@endcode -@param arr Input array -@param sizeof_header Size of output header to distinguish between IplImage, CvMat and CvMatND -output headers -@param header Output header to be filled -@param new_cn New number of channels. new_cn = 0 means that the number of channels remains -unchanged. -@param new_dims New number of dimensions. new_dims = 0 means that the number of dimensions -remains the same. -@param new_sizes Array of new dimension sizes. Only new_dims-1 values are used, because the -total number of elements must remain the same. Thus, if new_dims = 1, new_sizes array is not -used. - */ -CVAPI(CvArr*) cvReshapeMatND( const CvArr* arr, - int sizeof_header, CvArr* header, - int new_cn, int new_dims, int* new_sizes ); - -#define cvReshapeND( arr, header, new_cn, new_dims, new_sizes ) \ - cvReshapeMatND( (arr), sizeof(*(header)), (header), \ - (new_cn), (new_dims), (new_sizes)) - -/** @brief Changes shape of matrix/image without copying data. - -The function initializes the CvMat header so that it points to the same data as the original array -but has a different shape - different number of channels, different number of rows, or both. - -The following example code creates one image buffer and two image headers, the first is for a -320x240x3 image and the second is for a 960x240x1 image: -@code - IplImage* color_img = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U, 3); - CvMat gray_mat_hdr; - IplImage gray_img_hdr, *gray_img; - cvReshape(color_img, &gray_mat_hdr, 1); - gray_img = cvGetImage(&gray_mat_hdr, &gray_img_hdr); -@endcode -And the next example converts a 3x3 matrix to a single 1x9 vector: -@code - CvMat* mat = cvCreateMat(3, 3, CV_32F); - CvMat row_header, *row; - row = cvReshape(mat, &row_header, 0, 1); -@endcode -@param arr Input array -@param header Output header to be filled -@param new_cn New number of channels. 'new_cn = 0' means that the number of channels remains -unchanged. -@param new_rows New number of rows. 'new_rows = 0' means that the number of rows remains -unchanged unless it needs to be changed according to new_cn value. -*/ -CVAPI(CvMat*) cvReshape( const CvArr* arr, CvMat* header, - int new_cn, int new_rows CV_DEFAULT(0) ); - -/** Repeats source 2d array several times in both horizontal and - vertical direction to fill destination array */ -CVAPI(void) cvRepeat( const CvArr* src, CvArr* dst ); - -/** @brief Allocates array data - -The function allocates image, matrix or multi-dimensional dense array data. Note that in the case of -matrix types OpenCV allocation functions are used. In the case of IplImage they are used unless -CV_TURN_ON_IPL_COMPATIBILITY() has been called before. In the latter case IPL functions are used -to allocate the data. -@param arr Array header - */ -CVAPI(void) cvCreateData( CvArr* arr ); - -/** @brief Releases array data. - -The function releases the array data. In the case of CvMat or CvMatND it simply calls -cvDecRefData(), that is the function can not deallocate external data. See also the note to -cvCreateData . -@param arr Array header - */ -CVAPI(void) cvReleaseData( CvArr* arr ); - -/** @brief Assigns user data to the array header. - -The function assigns user data to the array header. Header should be initialized before using -cvCreateMatHeader, cvCreateImageHeader, cvCreateMatNDHeader, cvInitMatHeader, -cvInitImageHeader or cvInitMatNDHeader. -@param arr Array header -@param data User data -@param step Full row length in bytes - */ -CVAPI(void) cvSetData( CvArr* arr, void* data, int step ); - -/** @brief Retrieves low-level information about the array. - -The function fills output variables with low-level information about the array data. All output - -parameters are optional, so some of the pointers may be set to NULL. If the array is IplImage with -ROI set, the parameters of ROI are returned. - -The following example shows how to get access to array elements. It computes absolute values of the -array elements : -@code - float* data; - int step; - CvSize size; - - cvGetRawData(array, (uchar**)&data, &step, &size); - step /= sizeof(data[0]); - - for(int y = 0; y < size.height; y++, data += step ) - for(int x = 0; x < size.width; x++ ) - data[x] = (float)fabs(data[x]); -@endcode -@param arr Array header -@param data Output pointer to the whole image origin or ROI origin if ROI is set -@param step Output full row length in bytes -@param roi_size Output ROI size - */ -CVAPI(void) cvGetRawData( const CvArr* arr, uchar** data, - int* step CV_DEFAULT(NULL), - CvSize* roi_size CV_DEFAULT(NULL)); - -/** @brief Returns size of matrix or image ROI. - -The function returns number of rows (CvSize::height) and number of columns (CvSize::width) of the -input matrix or image. In the case of image the size of ROI is returned. -@param arr array header - */ -CVAPI(CvSize) cvGetSize( const CvArr* arr ); - -/** @brief Copies one array to another. - -The function copies selected elements from an input array to an output array: - -\f[\texttt{dst} (I)= \texttt{src} (I) \quad \text{if} \quad \texttt{mask} (I) \ne 0.\f] - -If any of the passed arrays is of IplImage type, then its ROI and COI fields are used. Both arrays -must have the same type, the same number of dimensions, and the same size. The function can also -copy sparse arrays (mask is not supported in this case). -@param src The source array -@param dst The destination array -@param mask Operation mask, 8-bit single channel array; specifies elements of the destination array -to be changed - */ -CVAPI(void) cvCopy( const CvArr* src, CvArr* dst, - const CvArr* mask CV_DEFAULT(NULL) ); - -/** @brief Sets every element of an array to a given value. - -The function copies the scalar value to every selected element of the destination array: -\f[\texttt{arr} (I)= \texttt{value} \quad \text{if} \quad \texttt{mask} (I) \ne 0\f] -If array arr is of IplImage type, then is ROI used, but COI must not be set. -@param arr The destination array -@param value Fill value -@param mask Operation mask, 8-bit single channel array; specifies elements of the destination -array to be changed - */ -CVAPI(void) cvSet( CvArr* arr, CvScalar value, - const CvArr* mask CV_DEFAULT(NULL) ); - -/** @brief Clears the array. - -The function clears the array. In the case of dense arrays (CvMat, CvMatND or IplImage), -cvZero(array) is equivalent to cvSet(array,cvScalarAll(0),0). In the case of sparse arrays all the -elements are removed. -@param arr Array to be cleared - */ -CVAPI(void) cvSetZero( CvArr* arr ); -#define cvZero cvSetZero - - -/** Splits a multi-channel array into the set of single-channel arrays or - extracts particular [color] plane */ -CVAPI(void) cvSplit( const CvArr* src, CvArr* dst0, CvArr* dst1, - CvArr* dst2, CvArr* dst3 ); - -/** Merges a set of single-channel arrays into the single multi-channel array - or inserts one particular [color] plane to the array */ -CVAPI(void) cvMerge( const CvArr* src0, const CvArr* src1, - const CvArr* src2, const CvArr* src3, - CvArr* dst ); - -/** Copies several channels from input arrays to - certain channels of output arrays */ -CVAPI(void) cvMixChannels( const CvArr** src, int src_count, - CvArr** dst, int dst_count, - const int* from_to, int pair_count ); - -/** @brief Converts one array to another with optional linear transformation. - -The function has several different purposes, and thus has several different names. It copies one -array to another with optional scaling, which is performed first, and/or optional type conversion, -performed after: - -\f[\texttt{dst} (I) = \texttt{scale} \texttt{src} (I) + ( \texttt{shift} _0, \texttt{shift} _1,...)\f] - -All the channels of multi-channel arrays are processed independently. - -The type of conversion is done with rounding and saturation, that is if the result of scaling + -conversion can not be represented exactly by a value of the destination array element type, it is -set to the nearest representable value on the real axis. -@param src Source array -@param dst Destination array -@param scale Scale factor -@param shift Value added to the scaled source array elements - */ -CVAPI(void) cvConvertScale( const CvArr* src, CvArr* dst, - double scale CV_DEFAULT(1), - double shift CV_DEFAULT(0) ); -#define cvCvtScale cvConvertScale -#define cvScale cvConvertScale -#define cvConvert( src, dst ) cvConvertScale( (src), (dst), 1, 0 ) - - -/** Performs linear transformation on every source array element, - stores absolute value of the result: - dst(x,y,c) = abs(scale*src(x,y,c)+shift). - destination array must have 8u type. - In other cases one may use cvConvertScale + cvAbsDiffS */ -CVAPI(void) cvConvertScaleAbs( const CvArr* src, CvArr* dst, - double scale CV_DEFAULT(1), - double shift CV_DEFAULT(0) ); -#define cvCvtScaleAbs cvConvertScaleAbs - - -/** checks termination criteria validity and - sets eps to default_eps (if it is not set), - max_iter to default_max_iters (if it is not set) -*/ -CVAPI(CvTermCriteria) cvCheckTermCriteria( CvTermCriteria criteria, - double default_eps, - int default_max_iters ); - -/****************************************************************************************\ -* Arithmetic, logic and comparison operations * -\****************************************************************************************/ - -/** dst(mask) = src1(mask) + src2(mask) */ -CVAPI(void) cvAdd( const CvArr* src1, const CvArr* src2, CvArr* dst, - const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(mask) = src(mask) + value */ -CVAPI(void) cvAddS( const CvArr* src, CvScalar value, CvArr* dst, - const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(mask) = src1(mask) - src2(mask) */ -CVAPI(void) cvSub( const CvArr* src1, const CvArr* src2, CvArr* dst, - const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(mask) = src(mask) - value = src(mask) + (-value) */ -CV_INLINE void cvSubS( const CvArr* src, CvScalar value, CvArr* dst, - const CvArr* mask CV_DEFAULT(NULL)) -{ - cvAddS( src, cvScalar( -value.val[0], -value.val[1], -value.val[2], -value.val[3]), - dst, mask ); -} - -/** dst(mask) = value - src(mask) */ -CVAPI(void) cvSubRS( const CvArr* src, CvScalar value, CvArr* dst, - const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(idx) = src1(idx) * src2(idx) * scale - (scaled element-wise multiplication of 2 arrays) */ -CVAPI(void) cvMul( const CvArr* src1, const CvArr* src2, - CvArr* dst, double scale CV_DEFAULT(1) ); - -/** element-wise division/inversion with scaling: - dst(idx) = src1(idx) * scale / src2(idx) - or dst(idx) = scale / src2(idx) if src1 == 0 */ -CVAPI(void) cvDiv( const CvArr* src1, const CvArr* src2, - CvArr* dst, double scale CV_DEFAULT(1)); - -/** dst = src1 * scale + src2 */ -CVAPI(void) cvScaleAdd( const CvArr* src1, CvScalar scale, - const CvArr* src2, CvArr* dst ); -#define cvAXPY( A, real_scalar, B, C ) cvScaleAdd(A, cvRealScalar(real_scalar), B, C) - -/** dst = src1 * alpha + src2 * beta + gamma */ -CVAPI(void) cvAddWeighted( const CvArr* src1, double alpha, - const CvArr* src2, double beta, - double gamma, CvArr* dst ); - -/** @brief Calculates the dot product of two arrays in Euclidean metrics. - -The function calculates and returns the Euclidean dot product of two arrays. - -\f[src1 \bullet src2 = \sum _I ( \texttt{src1} (I) \texttt{src2} (I))\f] - -In the case of multiple channel arrays, the results for all channels are accumulated. In particular, -cvDotProduct(a,a) where a is a complex vector, will return \f$||\texttt{a}||^2\f$. The function can -process multi-dimensional arrays, row by row, layer by layer, and so on. -@param src1 The first source array -@param src2 The second source array - */ -CVAPI(double) cvDotProduct( const CvArr* src1, const CvArr* src2 ); - -/** dst(idx) = src1(idx) & src2(idx) */ -CVAPI(void) cvAnd( const CvArr* src1, const CvArr* src2, - CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(idx) = src(idx) & value */ -CVAPI(void) cvAndS( const CvArr* src, CvScalar value, - CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(idx) = src1(idx) | src2(idx) */ -CVAPI(void) cvOr( const CvArr* src1, const CvArr* src2, - CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(idx) = src(idx) | value */ -CVAPI(void) cvOrS( const CvArr* src, CvScalar value, - CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(idx) = src1(idx) ^ src2(idx) */ -CVAPI(void) cvXor( const CvArr* src1, const CvArr* src2, - CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(idx) = src(idx) ^ value */ -CVAPI(void) cvXorS( const CvArr* src, CvScalar value, - CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(idx) = ~src(idx) */ -CVAPI(void) cvNot( const CvArr* src, CvArr* dst ); - -/** dst(idx) = lower(idx) <= src(idx) < upper(idx) */ -CVAPI(void) cvInRange( const CvArr* src, const CvArr* lower, - const CvArr* upper, CvArr* dst ); - -/** dst(idx) = lower <= src(idx) < upper */ -CVAPI(void) cvInRangeS( const CvArr* src, CvScalar lower, - CvScalar upper, CvArr* dst ); - -#define CV_CMP_EQ 0 -#define CV_CMP_GT 1 -#define CV_CMP_GE 2 -#define CV_CMP_LT 3 -#define CV_CMP_LE 4 -#define CV_CMP_NE 5 - -/** The comparison operation support single-channel arrays only. - Destination image should be 8uC1 or 8sC1 */ - -/** dst(idx) = src1(idx) _cmp_op_ src2(idx) */ -CVAPI(void) cvCmp( const CvArr* src1, const CvArr* src2, CvArr* dst, int cmp_op ); - -/** dst(idx) = src1(idx) _cmp_op_ value */ -CVAPI(void) cvCmpS( const CvArr* src, double value, CvArr* dst, int cmp_op ); - -/** dst(idx) = min(src1(idx),src2(idx)) */ -CVAPI(void) cvMin( const CvArr* src1, const CvArr* src2, CvArr* dst ); - -/** dst(idx) = max(src1(idx),src2(idx)) */ -CVAPI(void) cvMax( const CvArr* src1, const CvArr* src2, CvArr* dst ); - -/** dst(idx) = min(src(idx),value) */ -CVAPI(void) cvMinS( const CvArr* src, double value, CvArr* dst ); - -/** dst(idx) = max(src(idx),value) */ -CVAPI(void) cvMaxS( const CvArr* src, double value, CvArr* dst ); - -/** dst(x,y,c) = abs(src1(x,y,c) - src2(x,y,c)) */ -CVAPI(void) cvAbsDiff( const CvArr* src1, const CvArr* src2, CvArr* dst ); - -/** dst(x,y,c) = abs(src(x,y,c) - value(c)) */ -CVAPI(void) cvAbsDiffS( const CvArr* src, CvArr* dst, CvScalar value ); -#define cvAbs( src, dst ) cvAbsDiffS( (src), (dst), cvScalarAll(0)) - -/****************************************************************************************\ -* Math operations * -\****************************************************************************************/ - -/** Does cartesian->polar coordinates conversion. - Either of output components (magnitude or angle) is optional */ -CVAPI(void) cvCartToPolar( const CvArr* x, const CvArr* y, - CvArr* magnitude, CvArr* angle CV_DEFAULT(NULL), - int angle_in_degrees CV_DEFAULT(0)); - -/** Does polar->cartesian coordinates conversion. - Either of output components (magnitude or angle) is optional. - If magnitude is missing it is assumed to be all 1's */ -CVAPI(void) cvPolarToCart( const CvArr* magnitude, const CvArr* angle, - CvArr* x, CvArr* y, - int angle_in_degrees CV_DEFAULT(0)); - -/** Does powering: dst(idx) = src(idx)^power */ -CVAPI(void) cvPow( const CvArr* src, CvArr* dst, double power ); - -/** Does exponention: dst(idx) = exp(src(idx)). - Overflow is not handled yet. Underflow is handled. - Maximal relative error is ~7e-6 for single-precision input */ -CVAPI(void) cvExp( const CvArr* src, CvArr* dst ); - -/** Calculates natural logarithms: dst(idx) = log(abs(src(idx))). - Logarithm of 0 gives large negative number(~-700) - Maximal relative error is ~3e-7 for single-precision output -*/ -CVAPI(void) cvLog( const CvArr* src, CvArr* dst ); - -/** Fast arctangent calculation */ -CVAPI(float) cvFastArctan( float y, float x ); - -/** Fast cubic root calculation */ -CVAPI(float) cvCbrt( float value ); - -#define CV_CHECK_RANGE 1 -#define CV_CHECK_QUIET 2 -/** Checks array values for NaNs, Infs or simply for too large numbers - (if CV_CHECK_RANGE is set). If CV_CHECK_QUIET is set, - no runtime errors is raised (function returns zero value in case of "bad" values). - Otherwise cvError is called */ -CVAPI(int) cvCheckArr( const CvArr* arr, int flags CV_DEFAULT(0), - double min_val CV_DEFAULT(0), double max_val CV_DEFAULT(0)); -#define cvCheckArray cvCheckArr - -#define CV_RAND_UNI 0 -#define CV_RAND_NORMAL 1 - -/** @brief Fills an array with random numbers and updates the RNG state. - -The function fills the destination array with uniformly or normally distributed random numbers. -@param rng CvRNG state initialized by cvRNG -@param arr The destination array -@param dist_type Distribution type -> - **CV_RAND_UNI** uniform distribution -> - **CV_RAND_NORMAL** normal or Gaussian distribution -@param param1 The first parameter of the distribution. In the case of a uniform distribution it is -the inclusive lower boundary of the random numbers range. In the case of a normal distribution it -is the mean value of the random numbers. -@param param2 The second parameter of the distribution. In the case of a uniform distribution it -is the exclusive upper boundary of the random numbers range. In the case of a normal distribution -it is the standard deviation of the random numbers. -@sa randu, randn, RNG::fill. - */ -CVAPI(void) cvRandArr( CvRNG* rng, CvArr* arr, int dist_type, - CvScalar param1, CvScalar param2 ); - -CVAPI(void) cvRandShuffle( CvArr* mat, CvRNG* rng, - double iter_factor CV_DEFAULT(1.)); - -#define CV_SORT_EVERY_ROW 0 -#define CV_SORT_EVERY_COLUMN 1 -#define CV_SORT_ASCENDING 0 -#define CV_SORT_DESCENDING 16 - -CVAPI(void) cvSort( const CvArr* src, CvArr* dst CV_DEFAULT(NULL), - CvArr* idxmat CV_DEFAULT(NULL), - int flags CV_DEFAULT(0)); - -/** Finds real roots of a cubic equation */ -CVAPI(int) cvSolveCubic( const CvMat* coeffs, CvMat* roots ); - -/** Finds all real and complex roots of a polynomial equation */ -CVAPI(void) cvSolvePoly(const CvMat* coeffs, CvMat *roots2, - int maxiter CV_DEFAULT(20), int fig CV_DEFAULT(100)); - -/****************************************************************************************\ -* Matrix operations * -\****************************************************************************************/ - -/** @brief Calculates the cross product of two 3D vectors. - -The function calculates the cross product of two 3D vectors: -\f[\texttt{dst} = \texttt{src1} \times \texttt{src2}\f] -or: -\f[\begin{array}{l} \texttt{dst} _1 = \texttt{src1} _2 \texttt{src2} _3 - \texttt{src1} _3 \texttt{src2} _2 \\ \texttt{dst} _2 = \texttt{src1} _3 \texttt{src2} _1 - \texttt{src1} _1 \texttt{src2} _3 \\ \texttt{dst} _3 = \texttt{src1} _1 \texttt{src2} _2 - \texttt{src1} _2 \texttt{src2} _1 \end{array}\f] -@param src1 The first source vector -@param src2 The second source vector -@param dst The destination vector - */ -CVAPI(void) cvCrossProduct( const CvArr* src1, const CvArr* src2, CvArr* dst ); - -/** Matrix transform: dst = A*B + C, C is optional */ -#define cvMatMulAdd( src1, src2, src3, dst ) cvGEMM( (src1), (src2), 1., (src3), 1., (dst), 0 ) -#define cvMatMul( src1, src2, dst ) cvMatMulAdd( (src1), (src2), NULL, (dst)) - -#define CV_GEMM_A_T 1 -#define CV_GEMM_B_T 2 -#define CV_GEMM_C_T 4 -/** Extended matrix transform: - dst = alpha*op(A)*op(B) + beta*op(C), where op(X) is X or X^T */ -CVAPI(void) cvGEMM( const CvArr* src1, const CvArr* src2, double alpha, - const CvArr* src3, double beta, CvArr* dst, - int tABC CV_DEFAULT(0)); -#define cvMatMulAddEx cvGEMM - -/** Transforms each element of source array and stores - resultant vectors in destination array */ -CVAPI(void) cvTransform( const CvArr* src, CvArr* dst, - const CvMat* transmat, - const CvMat* shiftvec CV_DEFAULT(NULL)); -#define cvMatMulAddS cvTransform - -/** Does perspective transform on every element of input array */ -CVAPI(void) cvPerspectiveTransform( const CvArr* src, CvArr* dst, - const CvMat* mat ); - -/** Calculates (A-delta)*(A-delta)^T (order=0) or (A-delta)^T*(A-delta) (order=1) */ -CVAPI(void) cvMulTransposed( const CvArr* src, CvArr* dst, int order, - const CvArr* delta CV_DEFAULT(NULL), - double scale CV_DEFAULT(1.) ); - -/** Transposes matrix. Square matrices can be transposed in-place */ -CVAPI(void) cvTranspose( const CvArr* src, CvArr* dst ); -#define cvT cvTranspose - -/** Completes the symmetric matrix from the lower (LtoR=0) or from the upper (LtoR!=0) part */ -CVAPI(void) cvCompleteSymm( CvMat* matrix, int LtoR CV_DEFAULT(0) ); - -/** Mirror array data around horizontal (flip=0), - vertical (flip=1) or both(flip=-1) axises: - cvFlip(src) flips images vertically and sequences horizontally (inplace) */ -CVAPI(void) cvFlip( const CvArr* src, CvArr* dst CV_DEFAULT(NULL), - int flip_mode CV_DEFAULT(0)); -#define cvMirror cvFlip - - -#define CV_SVD_MODIFY_A 1 -#define CV_SVD_U_T 2 -#define CV_SVD_V_T 4 - -/** Performs Singular Value Decomposition of a matrix */ -CVAPI(void) cvSVD( CvArr* A, CvArr* W, CvArr* U CV_DEFAULT(NULL), - CvArr* V CV_DEFAULT(NULL), int flags CV_DEFAULT(0)); - -/** Performs Singular Value Back Substitution (solves A*X = B): - flags must be the same as in cvSVD */ -CVAPI(void) cvSVBkSb( const CvArr* W, const CvArr* U, - const CvArr* V, const CvArr* B, - CvArr* X, int flags ); - -#define CV_LU 0 -#define CV_SVD 1 -#define CV_SVD_SYM 2 -#define CV_CHOLESKY 3 -#define CV_QR 4 -#define CV_NORMAL 16 - -/** Inverts matrix */ -CVAPI(double) cvInvert( const CvArr* src, CvArr* dst, - int method CV_DEFAULT(CV_LU)); -#define cvInv cvInvert - -/** Solves linear system (src1)*(dst) = (src2) - (returns 0 if src1 is a singular and CV_LU method is used) */ -CVAPI(int) cvSolve( const CvArr* src1, const CvArr* src2, CvArr* dst, - int method CV_DEFAULT(CV_LU)); - -/** Calculates determinant of input matrix */ -CVAPI(double) cvDet( const CvArr* mat ); - -/** Calculates trace of the matrix (sum of elements on the main diagonal) */ -CVAPI(CvScalar) cvTrace( const CvArr* mat ); - -/** Finds eigen values and vectors of a symmetric matrix */ -CVAPI(void) cvEigenVV( CvArr* mat, CvArr* evects, CvArr* evals, - double eps CV_DEFAULT(0), - int lowindex CV_DEFAULT(-1), - int highindex CV_DEFAULT(-1)); - -///* Finds selected eigen values and vectors of a symmetric matrix */ -//CVAPI(void) cvSelectedEigenVV( CvArr* mat, CvArr* evects, CvArr* evals, -// int lowindex, int highindex ); - -/** Makes an identity matrix (mat_ij = i == j) */ -CVAPI(void) cvSetIdentity( CvArr* mat, CvScalar value CV_DEFAULT(cvRealScalar(1)) ); - -/** Fills matrix with given range of numbers */ -CVAPI(CvArr*) cvRange( CvArr* mat, double start, double end ); - -/** @anchor core_c_CovarFlags -@name Flags for cvCalcCovarMatrix -@see cvCalcCovarMatrix - @{ -*/ - -/** flag for cvCalcCovarMatrix, transpose([v1-avg, v2-avg,...]) * [v1-avg,v2-avg,...] */ -#define CV_COVAR_SCRAMBLED 0 - -/** flag for cvCalcCovarMatrix, [v1-avg, v2-avg,...] * transpose([v1-avg,v2-avg,...]) */ -#define CV_COVAR_NORMAL 1 - -/** flag for cvCalcCovarMatrix, do not calc average (i.e. mean vector) - use the input vector instead - (useful for calculating covariance matrix by parts) */ -#define CV_COVAR_USE_AVG 2 - -/** flag for cvCalcCovarMatrix, scale the covariance matrix coefficients by number of the vectors */ -#define CV_COVAR_SCALE 4 - -/** flag for cvCalcCovarMatrix, all the input vectors are stored in a single matrix, as its rows */ -#define CV_COVAR_ROWS 8 - -/** flag for cvCalcCovarMatrix, all the input vectors are stored in a single matrix, as its columns */ -#define CV_COVAR_COLS 16 - -/** @} */ - -/** Calculates covariation matrix for a set of vectors -@see @ref core_c_CovarFlags "flags" -*/ -CVAPI(void) cvCalcCovarMatrix( const CvArr** vects, int count, - CvArr* cov_mat, CvArr* avg, int flags ); - -#define CV_PCA_DATA_AS_ROW 0 -#define CV_PCA_DATA_AS_COL 1 -#define CV_PCA_USE_AVG 2 -CVAPI(void) cvCalcPCA( const CvArr* data, CvArr* mean, - CvArr* eigenvals, CvArr* eigenvects, int flags ); - -CVAPI(void) cvProjectPCA( const CvArr* data, const CvArr* mean, - const CvArr* eigenvects, CvArr* result ); - -CVAPI(void) cvBackProjectPCA( const CvArr* proj, const CvArr* mean, - const CvArr* eigenvects, CvArr* result ); - -/** Calculates Mahalanobis(weighted) distance */ -CVAPI(double) cvMahalanobis( const CvArr* vec1, const CvArr* vec2, const CvArr* mat ); -#define cvMahalonobis cvMahalanobis - -/****************************************************************************************\ -* Array Statistics * -\****************************************************************************************/ - -/** Finds sum of array elements */ -CVAPI(CvScalar) cvSum( const CvArr* arr ); - -/** Calculates number of non-zero pixels */ -CVAPI(int) cvCountNonZero( const CvArr* arr ); - -/** Calculates mean value of array elements */ -CVAPI(CvScalar) cvAvg( const CvArr* arr, const CvArr* mask CV_DEFAULT(NULL) ); - -/** Calculates mean and standard deviation of pixel values */ -CVAPI(void) cvAvgSdv( const CvArr* arr, CvScalar* mean, CvScalar* std_dev, - const CvArr* mask CV_DEFAULT(NULL) ); - -/** Finds global minimum, maximum and their positions */ -CVAPI(void) cvMinMaxLoc( const CvArr* arr, double* min_val, double* max_val, - CvPoint* min_loc CV_DEFAULT(NULL), - CvPoint* max_loc CV_DEFAULT(NULL), - const CvArr* mask CV_DEFAULT(NULL) ); - -/** @anchor core_c_NormFlags - @name Flags for cvNorm and cvNormalize - @{ -*/ -#define CV_C 1 -#define CV_L1 2 -#define CV_L2 4 -#define CV_NORM_MASK 7 -#define CV_RELATIVE 8 -#define CV_DIFF 16 -#define CV_MINMAX 32 - -#define CV_DIFF_C (CV_DIFF | CV_C) -#define CV_DIFF_L1 (CV_DIFF | CV_L1) -#define CV_DIFF_L2 (CV_DIFF | CV_L2) -#define CV_RELATIVE_C (CV_RELATIVE | CV_C) -#define CV_RELATIVE_L1 (CV_RELATIVE | CV_L1) -#define CV_RELATIVE_L2 (CV_RELATIVE | CV_L2) -/** @} */ - -/** Finds norm, difference norm or relative difference norm for an array (or two arrays) -@see ref core_c_NormFlags "flags" -*/ -CVAPI(double) cvNorm( const CvArr* arr1, const CvArr* arr2 CV_DEFAULT(NULL), - int norm_type CV_DEFAULT(CV_L2), - const CvArr* mask CV_DEFAULT(NULL) ); - -/** @see ref core_c_NormFlags "flags" */ -CVAPI(void) cvNormalize( const CvArr* src, CvArr* dst, - double a CV_DEFAULT(1.), double b CV_DEFAULT(0.), - int norm_type CV_DEFAULT(CV_L2), - const CvArr* mask CV_DEFAULT(NULL) ); - -/** @anchor core_c_ReduceFlags - @name Flags for cvReduce - @{ -*/ -#define CV_REDUCE_SUM 0 -#define CV_REDUCE_AVG 1 -#define CV_REDUCE_MAX 2 -#define CV_REDUCE_MIN 3 -/** @} */ - -/** @see @ref core_c_ReduceFlags "flags" */ -CVAPI(void) cvReduce( const CvArr* src, CvArr* dst, int dim CV_DEFAULT(-1), - int op CV_DEFAULT(CV_REDUCE_SUM) ); - -/****************************************************************************************\ -* Discrete Linear Transforms and Related Functions * -\****************************************************************************************/ - -/** @anchor core_c_DftFlags - @name Flags for cvDFT, cvDCT and cvMulSpectrums - @{ - */ -#define CV_DXT_FORWARD 0 -#define CV_DXT_INVERSE 1 -#define CV_DXT_SCALE 2 /**< divide result by size of array */ -#define CV_DXT_INV_SCALE (CV_DXT_INVERSE + CV_DXT_SCALE) -#define CV_DXT_INVERSE_SCALE CV_DXT_INV_SCALE -#define CV_DXT_ROWS 4 /**< transform each row individually */ -#define CV_DXT_MUL_CONJ 8 /**< conjugate the second argument of cvMulSpectrums */ -/** @} */ - -/** Discrete Fourier Transform: - complex->complex, - real->ccs (forward), - ccs->real (inverse) -@see core_c_DftFlags "flags" -*/ -CVAPI(void) cvDFT( const CvArr* src, CvArr* dst, int flags, - int nonzero_rows CV_DEFAULT(0) ); -#define cvFFT cvDFT - -/** Multiply results of DFTs: DFT(X)*DFT(Y) or DFT(X)*conj(DFT(Y)) -@see core_c_DftFlags "flags" -*/ -CVAPI(void) cvMulSpectrums( const CvArr* src1, const CvArr* src2, - CvArr* dst, int flags ); - -/** Finds optimal DFT vector size >= size0 */ -CVAPI(int) cvGetOptimalDFTSize( int size0 ); - -/** Discrete Cosine Transform -@see core_c_DftFlags "flags" -*/ -CVAPI(void) cvDCT( const CvArr* src, CvArr* dst, int flags ); - -/****************************************************************************************\ -* Dynamic data structures * -\****************************************************************************************/ - -/** Calculates length of sequence slice (with support of negative indices). */ -CVAPI(int) cvSliceLength( CvSlice slice, const CvSeq* seq ); - - -/** Creates new memory storage. - block_size == 0 means that default, - somewhat optimal size, is used (currently, it is 64K) */ -CVAPI(CvMemStorage*) cvCreateMemStorage( int block_size CV_DEFAULT(0)); - - -/** Creates a memory storage that will borrow memory blocks from parent storage */ -CVAPI(CvMemStorage*) cvCreateChildMemStorage( CvMemStorage* parent ); - - -/** Releases memory storage. All the children of a parent must be released before - the parent. A child storage returns all the blocks to parent when it is released */ -CVAPI(void) cvReleaseMemStorage( CvMemStorage** storage ); - - -/** Clears memory storage. This is the only way(!!!) (besides cvRestoreMemStoragePos) - to reuse memory allocated for the storage - cvClearSeq,cvClearSet ... - do not free any memory. - A child storage returns all the blocks to the parent when it is cleared */ -CVAPI(void) cvClearMemStorage( CvMemStorage* storage ); - -/** Remember a storage "free memory" position */ -CVAPI(void) cvSaveMemStoragePos( const CvMemStorage* storage, CvMemStoragePos* pos ); - -/** Restore a storage "free memory" position */ -CVAPI(void) cvRestoreMemStoragePos( CvMemStorage* storage, CvMemStoragePos* pos ); - -/** Allocates continuous buffer of the specified size in the storage */ -CVAPI(void*) cvMemStorageAlloc( CvMemStorage* storage, size_t size ); - -/** Allocates string in memory storage */ -//CVAPI(CvString) cvMemStorageAllocString( CvMemStorage* storage, const char* ptr, -// int len CV_DEFAULT(-1) ); - -/** Creates new empty sequence that will reside in the specified storage */ -CVAPI(CvSeq*) cvCreateSeq( int seq_flags, size_t header_size, - size_t elem_size, CvMemStorage* storage ); - -/** Changes default size (granularity) of sequence blocks. - The default size is ~1Kbyte */ -CVAPI(void) cvSetSeqBlockSize( CvSeq* seq, int delta_elems ); - - -/** Adds new element to the end of sequence. Returns pointer to the element */ -CVAPI(schar*) cvSeqPush( CvSeq* seq, const void* element CV_DEFAULT(NULL)); - - -/** Adds new element to the beginning of sequence. Returns pointer to it */ -CVAPI(schar*) cvSeqPushFront( CvSeq* seq, const void* element CV_DEFAULT(NULL)); - - -/** Removes the last element from sequence and optionally saves it */ -CVAPI(void) cvSeqPop( CvSeq* seq, void* element CV_DEFAULT(NULL)); - - -/** Removes the first element from sequence and optioanally saves it */ -CVAPI(void) cvSeqPopFront( CvSeq* seq, void* element CV_DEFAULT(NULL)); - - -#define CV_FRONT 1 -#define CV_BACK 0 -/** Adds several new elements to the end of sequence */ -CVAPI(void) cvSeqPushMulti( CvSeq* seq, const void* elements, - int count, int in_front CV_DEFAULT(0) ); - -/** Removes several elements from the end of sequence and optionally saves them */ -CVAPI(void) cvSeqPopMulti( CvSeq* seq, void* elements, - int count, int in_front CV_DEFAULT(0) ); - -/** Inserts a new element in the middle of sequence. - cvSeqInsert(seq,0,elem) == cvSeqPushFront(seq,elem) */ -CVAPI(schar*) cvSeqInsert( CvSeq* seq, int before_index, - const void* element CV_DEFAULT(NULL)); - -/** Removes specified sequence element */ -CVAPI(void) cvSeqRemove( CvSeq* seq, int index ); - - -/** Removes all the elements from the sequence. The freed memory - can be reused later only by the same sequence unless cvClearMemStorage - or cvRestoreMemStoragePos is called */ -CVAPI(void) cvClearSeq( CvSeq* seq ); - - -/** Retrieves pointer to specified sequence element. - Negative indices are supported and mean counting from the end - (e.g -1 means the last sequence element) */ -CVAPI(schar*) cvGetSeqElem( const CvSeq* seq, int index ); - -/** Calculates index of the specified sequence element. - Returns -1 if element does not belong to the sequence */ -CVAPI(int) cvSeqElemIdx( const CvSeq* seq, const void* element, - CvSeqBlock** block CV_DEFAULT(NULL) ); - -/** Initializes sequence writer. The new elements will be added to the end of sequence */ -CVAPI(void) cvStartAppendToSeq( CvSeq* seq, CvSeqWriter* writer ); - - -/** Combination of cvCreateSeq and cvStartAppendToSeq */ -CVAPI(void) cvStartWriteSeq( int seq_flags, int header_size, - int elem_size, CvMemStorage* storage, - CvSeqWriter* writer ); - -/** Closes sequence writer, updates sequence header and returns pointer - to the resultant sequence - (which may be useful if the sequence was created using cvStartWriteSeq)) -*/ -CVAPI(CvSeq*) cvEndWriteSeq( CvSeqWriter* writer ); - - -/** Updates sequence header. May be useful to get access to some of previously - written elements via cvGetSeqElem or sequence reader */ -CVAPI(void) cvFlushSeqWriter( CvSeqWriter* writer ); - - -/** Initializes sequence reader. - The sequence can be read in forward or backward direction */ -CVAPI(void) cvStartReadSeq( const CvSeq* seq, CvSeqReader* reader, - int reverse CV_DEFAULT(0) ); - - -/** Returns current sequence reader position (currently observed sequence element) */ -CVAPI(int) cvGetSeqReaderPos( CvSeqReader* reader ); - - -/** Changes sequence reader position. It may seek to an absolute or - to relative to the current position */ -CVAPI(void) cvSetSeqReaderPos( CvSeqReader* reader, int index, - int is_relative CV_DEFAULT(0)); - -/** Copies sequence content to a continuous piece of memory */ -CVAPI(void*) cvCvtSeqToArray( const CvSeq* seq, void* elements, - CvSlice slice CV_DEFAULT(CV_WHOLE_SEQ) ); - -/** Creates sequence header for array. - After that all the operations on sequences that do not alter the content - can be applied to the resultant sequence */ -CVAPI(CvSeq*) cvMakeSeqHeaderForArray( int seq_type, int header_size, - int elem_size, void* elements, int total, - CvSeq* seq, CvSeqBlock* block ); - -/** Extracts sequence slice (with or without copying sequence elements) */ -CVAPI(CvSeq*) cvSeqSlice( const CvSeq* seq, CvSlice slice, - CvMemStorage* storage CV_DEFAULT(NULL), - int copy_data CV_DEFAULT(0)); - -CV_INLINE CvSeq* cvCloneSeq( const CvSeq* seq, CvMemStorage* storage CV_DEFAULT(NULL)) -{ - return cvSeqSlice( seq, CV_WHOLE_SEQ, storage, 1 ); -} - -/** Removes sequence slice */ -CVAPI(void) cvSeqRemoveSlice( CvSeq* seq, CvSlice slice ); - -/** Inserts a sequence or array into another sequence */ -CVAPI(void) cvSeqInsertSlice( CvSeq* seq, int before_index, const CvArr* from_arr ); - -/** a < b ? -1 : a > b ? 1 : 0 */ -typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata ); - -/** Sorts sequence in-place given element comparison function */ -CVAPI(void) cvSeqSort( CvSeq* seq, CvCmpFunc func, void* userdata CV_DEFAULT(NULL) ); - -/** Finds element in a [sorted] sequence */ -CVAPI(schar*) cvSeqSearch( CvSeq* seq, const void* elem, CvCmpFunc func, - int is_sorted, int* elem_idx, - void* userdata CV_DEFAULT(NULL) ); - -/** Reverses order of sequence elements in-place */ -CVAPI(void) cvSeqInvert( CvSeq* seq ); - -/** Splits sequence into one or more equivalence classes using the specified criteria */ -CVAPI(int) cvSeqPartition( const CvSeq* seq, CvMemStorage* storage, - CvSeq** labels, CvCmpFunc is_equal, void* userdata ); - -/************ Internal sequence functions ************/ -CVAPI(void) cvChangeSeqBlock( void* reader, int direction ); -CVAPI(void) cvCreateSeqBlock( CvSeqWriter* writer ); - - -/** Creates a new set */ -CVAPI(CvSet*) cvCreateSet( int set_flags, int header_size, - int elem_size, CvMemStorage* storage ); - -/** Adds new element to the set and returns pointer to it */ -CVAPI(int) cvSetAdd( CvSet* set_header, CvSetElem* elem CV_DEFAULT(NULL), - CvSetElem** inserted_elem CV_DEFAULT(NULL) ); - -/** Fast variant of cvSetAdd */ -CV_INLINE CvSetElem* cvSetNew( CvSet* set_header ) -{ - CvSetElem* elem = set_header->free_elems; - if( elem ) - { - set_header->free_elems = elem->next_free; - elem->flags = elem->flags & CV_SET_ELEM_IDX_MASK; - set_header->active_count++; - } - else - cvSetAdd( set_header, NULL, &elem ); - return elem; -} - -/** Removes set element given its pointer */ -CV_INLINE void cvSetRemoveByPtr( CvSet* set_header, void* elem ) -{ - CvSetElem* _elem = (CvSetElem*)elem; - assert( _elem->flags >= 0 /*&& (elem->flags & CV_SET_ELEM_IDX_MASK) < set_header->total*/ ); - _elem->next_free = set_header->free_elems; - _elem->flags = (_elem->flags & CV_SET_ELEM_IDX_MASK) | CV_SET_ELEM_FREE_FLAG; - set_header->free_elems = _elem; - set_header->active_count--; -} - -/** Removes element from the set by its index */ -CVAPI(void) cvSetRemove( CvSet* set_header, int index ); - -/** Returns a set element by index. If the element doesn't belong to the set, - NULL is returned */ -CV_INLINE CvSetElem* cvGetSetElem( const CvSet* set_header, int idx ) -{ - CvSetElem* elem = (CvSetElem*)(void *)cvGetSeqElem( (CvSeq*)set_header, idx ); - return elem && CV_IS_SET_ELEM( elem ) ? elem : 0; -} - -/** Removes all the elements from the set */ -CVAPI(void) cvClearSet( CvSet* set_header ); - -/** Creates new graph */ -CVAPI(CvGraph*) cvCreateGraph( int graph_flags, int header_size, - int vtx_size, int edge_size, - CvMemStorage* storage ); - -/** Adds new vertex to the graph */ -CVAPI(int) cvGraphAddVtx( CvGraph* graph, const CvGraphVtx* vtx CV_DEFAULT(NULL), - CvGraphVtx** inserted_vtx CV_DEFAULT(NULL) ); - - -/** Removes vertex from the graph together with all incident edges */ -CVAPI(int) cvGraphRemoveVtx( CvGraph* graph, int index ); -CVAPI(int) cvGraphRemoveVtxByPtr( CvGraph* graph, CvGraphVtx* vtx ); - - -/** Link two vertices specified by indices or pointers if they - are not connected or return pointer to already existing edge - connecting the vertices. - Functions return 1 if a new edge was created, 0 otherwise */ -CVAPI(int) cvGraphAddEdge( CvGraph* graph, - int start_idx, int end_idx, - const CvGraphEdge* edge CV_DEFAULT(NULL), - CvGraphEdge** inserted_edge CV_DEFAULT(NULL) ); - -CVAPI(int) cvGraphAddEdgeByPtr( CvGraph* graph, - CvGraphVtx* start_vtx, CvGraphVtx* end_vtx, - const CvGraphEdge* edge CV_DEFAULT(NULL), - CvGraphEdge** inserted_edge CV_DEFAULT(NULL) ); - -/** Remove edge connecting two vertices */ -CVAPI(void) cvGraphRemoveEdge( CvGraph* graph, int start_idx, int end_idx ); -CVAPI(void) cvGraphRemoveEdgeByPtr( CvGraph* graph, CvGraphVtx* start_vtx, - CvGraphVtx* end_vtx ); - -/** Find edge connecting two vertices */ -CVAPI(CvGraphEdge*) cvFindGraphEdge( const CvGraph* graph, int start_idx, int end_idx ); -CVAPI(CvGraphEdge*) cvFindGraphEdgeByPtr( const CvGraph* graph, - const CvGraphVtx* start_vtx, - const CvGraphVtx* end_vtx ); -#define cvGraphFindEdge cvFindGraphEdge -#define cvGraphFindEdgeByPtr cvFindGraphEdgeByPtr - -/** Remove all vertices and edges from the graph */ -CVAPI(void) cvClearGraph( CvGraph* graph ); - - -/** Count number of edges incident to the vertex */ -CVAPI(int) cvGraphVtxDegree( const CvGraph* graph, int vtx_idx ); -CVAPI(int) cvGraphVtxDegreeByPtr( const CvGraph* graph, const CvGraphVtx* vtx ); - - -/** Retrieves graph vertex by given index */ -#define cvGetGraphVtx( graph, idx ) (CvGraphVtx*)cvGetSetElem((CvSet*)(graph), (idx)) - -/** Retrieves index of a graph vertex given its pointer */ -#define cvGraphVtxIdx( graph, vtx ) ((vtx)->flags & CV_SET_ELEM_IDX_MASK) - -/** Retrieves index of a graph edge given its pointer */ -#define cvGraphEdgeIdx( graph, edge ) ((edge)->flags & CV_SET_ELEM_IDX_MASK) - -#define cvGraphGetVtxCount( graph ) ((graph)->active_count) -#define cvGraphGetEdgeCount( graph ) ((graph)->edges->active_count) - -#define CV_GRAPH_VERTEX 1 -#define CV_GRAPH_TREE_EDGE 2 -#define CV_GRAPH_BACK_EDGE 4 -#define CV_GRAPH_FORWARD_EDGE 8 -#define CV_GRAPH_CROSS_EDGE 16 -#define CV_GRAPH_ANY_EDGE 30 -#define CV_GRAPH_NEW_TREE 32 -#define CV_GRAPH_BACKTRACKING 64 -#define CV_GRAPH_OVER -1 - -#define CV_GRAPH_ALL_ITEMS -1 - -/** flags for graph vertices and edges */ -#define CV_GRAPH_ITEM_VISITED_FLAG (1 << 30) -#define CV_IS_GRAPH_VERTEX_VISITED(vtx) \ - (((CvGraphVtx*)(vtx))->flags & CV_GRAPH_ITEM_VISITED_FLAG) -#define CV_IS_GRAPH_EDGE_VISITED(edge) \ - (((CvGraphEdge*)(edge))->flags & CV_GRAPH_ITEM_VISITED_FLAG) -#define CV_GRAPH_SEARCH_TREE_NODE_FLAG (1 << 29) -#define CV_GRAPH_FORWARD_EDGE_FLAG (1 << 28) - -typedef struct CvGraphScanner -{ - CvGraphVtx* vtx; /* current graph vertex (or current edge origin) */ - CvGraphVtx* dst; /* current graph edge destination vertex */ - CvGraphEdge* edge; /* current edge */ - - CvGraph* graph; /* the graph */ - CvSeq* stack; /* the graph vertex stack */ - int index; /* the lower bound of certainly visited vertices */ - int mask; /* event mask */ -} -CvGraphScanner; - -/** Creates new graph scanner. */ -CVAPI(CvGraphScanner*) cvCreateGraphScanner( CvGraph* graph, - CvGraphVtx* vtx CV_DEFAULT(NULL), - int mask CV_DEFAULT(CV_GRAPH_ALL_ITEMS)); - -/** Releases graph scanner. */ -CVAPI(void) cvReleaseGraphScanner( CvGraphScanner** scanner ); - -/** Get next graph element */ -CVAPI(int) cvNextGraphItem( CvGraphScanner* scanner ); - -/** Creates a copy of graph */ -CVAPI(CvGraph*) cvCloneGraph( const CvGraph* graph, CvMemStorage* storage ); - - -/** Does look-up transformation. Elements of the source array - (that should be 8uC1 or 8sC1) are used as indexes in lutarr 256-element table */ -CVAPI(void) cvLUT( const CvArr* src, CvArr* dst, const CvArr* lut ); - - -/******************* Iteration through the sequence tree *****************/ -typedef struct CvTreeNodeIterator -{ - const void* node; - int level; - int max_level; -} -CvTreeNodeIterator; - -CVAPI(void) cvInitTreeNodeIterator( CvTreeNodeIterator* tree_iterator, - const void* first, int max_level ); -CVAPI(void*) cvNextTreeNode( CvTreeNodeIterator* tree_iterator ); -CVAPI(void*) cvPrevTreeNode( CvTreeNodeIterator* tree_iterator ); - -/** Inserts sequence into tree with specified "parent" sequence. - If parent is equal to frame (e.g. the most external contour), - then added contour will have null pointer to parent. */ -CVAPI(void) cvInsertNodeIntoTree( void* node, void* parent, void* frame ); - -/** Removes contour from tree (together with the contour children). */ -CVAPI(void) cvRemoveNodeFromTree( void* node, void* frame ); - -/** Gathers pointers to all the sequences, - accessible from the `first`, to the single sequence */ -CVAPI(CvSeq*) cvTreeToNodeSeq( const void* first, int header_size, - CvMemStorage* storage ); - -/** The function implements the K-means algorithm for clustering an array of sample - vectors in a specified number of classes */ -#define CV_KMEANS_USE_INITIAL_LABELS 1 -CVAPI(int) cvKMeans2( const CvArr* samples, int cluster_count, CvArr* labels, - CvTermCriteria termcrit, int attempts CV_DEFAULT(1), - CvRNG* rng CV_DEFAULT(0), int flags CV_DEFAULT(0), - CvArr* _centers CV_DEFAULT(0), double* compactness CV_DEFAULT(0) ); - -/****************************************************************************************\ -* System functions * -\****************************************************************************************/ - -/** Loads optimized functions from IPP, MKL etc. or switches back to pure C code */ -CVAPI(int) cvUseOptimized( int on_off ); - -typedef IplImage* (CV_STDCALL* Cv_iplCreateImageHeader) - (int,int,int,char*,char*,int,int,int,int,int, - IplROI*,IplImage*,void*,IplTileInfo*); -typedef void (CV_STDCALL* Cv_iplAllocateImageData)(IplImage*,int,int); -typedef void (CV_STDCALL* Cv_iplDeallocate)(IplImage*,int); -typedef IplROI* (CV_STDCALL* Cv_iplCreateROI)(int,int,int,int,int); -typedef IplImage* (CV_STDCALL* Cv_iplCloneImage)(const IplImage*); - -/** @brief Makes OpenCV use IPL functions for allocating IplImage and IplROI structures. - -Normally, the function is not called directly. Instead, a simple macro -CV_TURN_ON_IPL_COMPATIBILITY() is used that calls cvSetIPLAllocators and passes there pointers -to IPL allocation functions. : -@code - ... - CV_TURN_ON_IPL_COMPATIBILITY() - ... -@endcode -@param create_header pointer to a function, creating IPL image header. -@param allocate_data pointer to a function, allocating IPL image data. -@param deallocate pointer to a function, deallocating IPL image. -@param create_roi pointer to a function, creating IPL image ROI (i.e. Region of Interest). -@param clone_image pointer to a function, cloning an IPL image. - */ -CVAPI(void) cvSetIPLAllocators( Cv_iplCreateImageHeader create_header, - Cv_iplAllocateImageData allocate_data, - Cv_iplDeallocate deallocate, - Cv_iplCreateROI create_roi, - Cv_iplCloneImage clone_image ); - -#define CV_TURN_ON_IPL_COMPATIBILITY() \ - cvSetIPLAllocators( iplCreateImageHeader, iplAllocateImage, \ - iplDeallocate, iplCreateROI, iplCloneImage ) - -/****************************************************************************************\ -* Data Persistence * -\****************************************************************************************/ - -#if 0 -/********************************** High-level functions ********************************/ - -/** @brief Opens file storage for reading or writing data. - -The function opens file storage for reading or writing data. In the latter case, a new file is -created or an existing file is rewritten. The type of the read or written file is determined by the -filename extension: .xml for XML, .yml or .yaml for YAML and .json for JSON. - -At the same time, it also supports adding parameters like "example.xml?base64". - -The function returns a pointer to the CvFileStorage structure. -If the file cannot be opened then the function returns NULL. -@param filename Name of the file associated with the storage -@param memstorage Memory storage used for temporary data and for -: storing dynamic structures, such as CvSeq or CvGraph . If it is NULL, a temporary memory - storage is created and used. -@param flags Can be one of the following: -> - **CV_STORAGE_READ** the storage is open for reading -> - **CV_STORAGE_WRITE** the storage is open for writing - (use **CV_STORAGE_WRITE | CV_STORAGE_WRITE_BASE64** to write rawdata in Base64) -@param encoding - */ -CVAPI(CvFileStorage*) cvOpenFileStorage( const char* filename, CvMemStorage* memstorage, - int flags, const char* encoding CV_DEFAULT(NULL) ); - -/** @brief Releases file storage. - -The function closes the file associated with the storage and releases all the temporary structures. -It must be called after all I/O operations with the storage are finished. -@param fs Double pointer to the released file storage - */ -CVAPI(void) cvReleaseFileStorage( CvFileStorage** fs ); - -/** returns attribute value or 0 (NULL) if there is no such attribute */ -CVAPI(const char*) cvAttrValue( const CvAttrList* attr, const char* attr_name ); - -/** @brief Starts writing a new structure. - -The function starts writing a compound structure (collection) that can be a sequence or a map. After -all the structure fields, which can be scalars or structures, are written, cvEndWriteStruct should -be called. The function can be used to group some objects or to implement the write function for a -some user object (see CvTypeInfo). -@param fs File storage -@param name Name of the written structure. The structure can be accessed by this name when the -storage is read. -@param struct_flags A combination one of the following values: -- **CV_NODE_SEQ** the written structure is a sequence (see discussion of CvFileStorage ), - that is, its elements do not have a name. -- **CV_NODE_MAP** the written structure is a map (see discussion of CvFileStorage ), that - is, all its elements have names. -One and only one of the two above flags must be specified -- **CV_NODE_FLOW** the optional flag that makes sense only for YAML streams. It means that - the structure is written as a flow (not as a block), which is more compact. It is - recommended to use this flag for structures or arrays whose elements are all scalars. -@param type_name Optional parameter - the object type name. In - case of XML it is written as a type_id attribute of the structure opening tag. In the case of - YAML it is written after a colon following the structure name (see the example in - CvFileStorage description). In case of JSON it is written as a name/value pair. - Mainly it is used with user objects. When the storage is read, the - encoded type name is used to determine the object type (see CvTypeInfo and cvFindType ). -@param attributes This parameter is not used in the current implementation - */ -CVAPI(void) cvStartWriteStruct( CvFileStorage* fs, const char* name, - int struct_flags, const char* type_name CV_DEFAULT(NULL), - CvAttrList attributes CV_DEFAULT(cvAttrList())); - -/** @brief Finishes writing to a file node collection. -@param fs File storage -@sa cvStartWriteStruct. - */ -CVAPI(void) cvEndWriteStruct( CvFileStorage* fs ); - -/** @brief Writes an integer value. - -The function writes a single integer value (with or without a name) to the file storage. -@param fs File storage -@param name Name of the written value. Should be NULL if and only if the parent structure is a -sequence. -@param value The written value - */ -CVAPI(void) cvWriteInt( CvFileStorage* fs, const char* name, int value ); - -/** @brief Writes a floating-point value. - -The function writes a single floating-point value (with or without a name) to file storage. Special -values are encoded as follows: NaN (Not A Number) as .NaN, infinity as +.Inf or -.Inf. - -The following example shows how to use the low-level writing functions to store custom structures, -such as termination criteria, without registering a new type. : -@code - void write_termcriteria( CvFileStorage* fs, const char* struct_name, - CvTermCriteria* termcrit ) - { - cvStartWriteStruct( fs, struct_name, CV_NODE_MAP, NULL, cvAttrList(0,0)); - cvWriteComment( fs, "termination criteria", 1 ); // just a description - if( termcrit->type & CV_TERMCRIT_ITER ) - cvWriteInteger( fs, "max_iterations", termcrit->max_iter ); - if( termcrit->type & CV_TERMCRIT_EPS ) - cvWriteReal( fs, "accuracy", termcrit->epsilon ); - cvEndWriteStruct( fs ); - } -@endcode -@param fs File storage -@param name Name of the written value. Should be NULL if and only if the parent structure is a -sequence. -@param value The written value -*/ -CVAPI(void) cvWriteReal( CvFileStorage* fs, const char* name, double value ); - -/** @brief Writes a text string. - -The function writes a text string to file storage. -@param fs File storage -@param name Name of the written string . Should be NULL if and only if the parent structure is a -sequence. -@param str The written text string -@param quote If non-zero, the written string is put in quotes, regardless of whether they are -required. Otherwise, if the flag is zero, quotes are used only when they are required (e.g. when -the string starts with a digit or contains spaces). - */ -CVAPI(void) cvWriteString( CvFileStorage* fs, const char* name, - const char* str, int quote CV_DEFAULT(0) ); - -/** @brief Writes a comment. - -The function writes a comment into file storage. The comments are skipped when the storage is read. -@param fs File storage -@param comment The written comment, single-line or multi-line -@param eol_comment If non-zero, the function tries to put the comment at the end of current line. -If the flag is zero, if the comment is multi-line, or if it does not fit at the end of the current -line, the comment starts a new line. - */ -CVAPI(void) cvWriteComment( CvFileStorage* fs, const char* comment, - int eol_comment ); - -/** @brief Writes an object to file storage. - -The function writes an object to file storage. First, the appropriate type info is found using -cvTypeOf. Then, the write method associated with the type info is called. - -Attributes are used to customize the writing procedure. The standard types support the following -attributes (all the dt attributes have the same format as in cvWriteRawData): - --# CvSeq - - **header_dt** description of user fields of the sequence header that follow CvSeq, or - CvChain (if the sequence is a Freeman chain) or CvContour (if the sequence is a contour or - point sequence) - - **dt** description of the sequence elements. - - **recursive** if the attribute is present and is not equal to "0" or "false", the whole - tree of sequences (contours) is stored. --# CvGraph - - **header_dt** description of user fields of the graph header that follows CvGraph; - - **vertex_dt** description of user fields of graph vertices - - **edge_dt** description of user fields of graph edges (note that the edge weight is - always written, so there is no need to specify it explicitly) - -Below is the code that creates the YAML file shown in the CvFileStorage description: -@code - #include "cxcore.h" - - int main( int argc, char** argv ) - { - CvMat* mat = cvCreateMat( 3, 3, CV_32F ); - CvFileStorage* fs = cvOpenFileStorage( "example.yml", 0, CV_STORAGE_WRITE ); - - cvSetIdentity( mat ); - cvWrite( fs, "A", mat, cvAttrList(0,0) ); - - cvReleaseFileStorage( &fs ); - cvReleaseMat( &mat ); - return 0; - } -@endcode -@param fs File storage -@param name Name of the written object. Should be NULL if and only if the parent structure is a -sequence. -@param ptr Pointer to the object -@param attributes The attributes of the object. They are specific for each particular type (see -the discussion below). - */ -CVAPI(void) cvWrite( CvFileStorage* fs, const char* name, const void* ptr, - CvAttrList attributes CV_DEFAULT(cvAttrList())); - -/** @brief Starts the next stream. - -The function finishes the currently written stream and starts the next stream. In the case of XML -the file with multiple streams looks like this: -@code{.xml} - - - - - - - ... -@endcode -The YAML file will look like this: -@code{.yaml} - %YAML 1.0 - # stream #1 data - ... - --- - # stream #2 data -@endcode -This is useful for concatenating files or for resuming the writing process. -@param fs File storage - */ -CVAPI(void) cvStartNextStream( CvFileStorage* fs ); - -/** @brief Writes multiple numbers. - -The function writes an array, whose elements consist of single or multiple numbers. The function -call can be replaced with a loop containing a few cvWriteInt and cvWriteReal calls, but a single -call is more efficient. Note that because none of the elements have a name, they should be written -to a sequence rather than a map. -@param fs File storage -@param src Pointer to the written array -@param len Number of the array elements to write -@param dt Specification of each array element, see @ref format_spec "format specification" - */ -CVAPI(void) cvWriteRawData( CvFileStorage* fs, const void* src, - int len, const char* dt ); - -/** @brief Writes multiple numbers in Base64. - -If either CV_STORAGE_WRITE_BASE64 or cv::FileStorage::WRITE_BASE64 is used, -this function will be the same as cvWriteRawData. If neither, the main -difference is that it outputs a sequence in Base64 encoding rather than -in plain text. - -This function can only be used to write a sequence with a type "binary". - -@param fs File storage -@param src Pointer to the written array -@param len Number of the array elements to write -@param dt Specification of each array element, see @ref format_spec "format specification" -*/ -CVAPI(void) cvWriteRawDataBase64( CvFileStorage* fs, const void* src, - int len, const char* dt ); - -/** @brief Returns a unique pointer for a given name. - -The function returns a unique pointer for each particular file node name. This pointer can be then -passed to the cvGetFileNode function that is faster than cvGetFileNodeByName because it compares -text strings by comparing pointers rather than the strings' content. - -Consider the following example where an array of points is encoded as a sequence of 2-entry maps: -@code - points: - - { x: 10, y: 10 } - - { x: 20, y: 20 } - - { x: 30, y: 30 } - # ... -@endcode -Then, it is possible to get hashed "x" and "y" pointers to speed up decoding of the points. : -@code - #include "cxcore.h" - - int main( int argc, char** argv ) - { - CvFileStorage* fs = cvOpenFileStorage( "points.yml", 0, CV_STORAGE_READ ); - CvStringHashNode* x_key = cvGetHashedNode( fs, "x", -1, 1 ); - CvStringHashNode* y_key = cvGetHashedNode( fs, "y", -1, 1 ); - CvFileNode* points = cvGetFileNodeByName( fs, 0, "points" ); - - if( CV_NODE_IS_SEQ(points->tag) ) - { - CvSeq* seq = points->data.seq; - int i, total = seq->total; - CvSeqReader reader; - cvStartReadSeq( seq, &reader, 0 ); - for( i = 0; i < total; i++ ) - { - CvFileNode* pt = (CvFileNode*)reader.ptr; - #if 1 // faster variant - CvFileNode* xnode = cvGetFileNode( fs, pt, x_key, 0 ); - CvFileNode* ynode = cvGetFileNode( fs, pt, y_key, 0 ); - assert( xnode && CV_NODE_IS_INT(xnode->tag) && - ynode && CV_NODE_IS_INT(ynode->tag)); - int x = xnode->data.i; // or x = cvReadInt( xnode, 0 ); - int y = ynode->data.i; // or y = cvReadInt( ynode, 0 ); - #elif 1 // slower variant; does not use x_key & y_key - CvFileNode* xnode = cvGetFileNodeByName( fs, pt, "x" ); - CvFileNode* ynode = cvGetFileNodeByName( fs, pt, "y" ); - assert( xnode && CV_NODE_IS_INT(xnode->tag) && - ynode && CV_NODE_IS_INT(ynode->tag)); - int x = xnode->data.i; // or x = cvReadInt( xnode, 0 ); - int y = ynode->data.i; // or y = cvReadInt( ynode, 0 ); - #else // the slowest yet the easiest to use variant - int x = cvReadIntByName( fs, pt, "x", 0 ); - int y = cvReadIntByName( fs, pt, "y", 0 ); - #endif - CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); - printf(" - } - } - cvReleaseFileStorage( &fs ); - return 0; - } -@endcode -Please note that whatever method of accessing a map you are using, it is still much slower than -using plain sequences; for example, in the above example, it is more efficient to encode the points -as pairs of integers in a single numeric sequence. -@param fs File storage -@param name Literal node name -@param len Length of the name (if it is known apriori), or -1 if it needs to be calculated -@param create_missing Flag that specifies, whether an absent key should be added into the hash table -*/ -CVAPI(CvStringHashNode*) cvGetHashedKey( CvFileStorage* fs, const char* name, - int len CV_DEFAULT(-1), - int create_missing CV_DEFAULT(0)); - -/** @brief Retrieves one of the top-level nodes of the file storage. - -The function returns one of the top-level file nodes. The top-level nodes do not have a name, they -correspond to the streams that are stored one after another in the file storage. If the index is out -of range, the function returns a NULL pointer, so all the top-level nodes can be iterated by -subsequent calls to the function with stream_index=0,1,..., until the NULL pointer is returned. -This function can be used as a base for recursive traversal of the file storage. -@param fs File storage -@param stream_index Zero-based index of the stream. See cvStartNextStream . In most cases, -there is only one stream in the file; however, there can be several. - */ -CVAPI(CvFileNode*) cvGetRootFileNode( const CvFileStorage* fs, - int stream_index CV_DEFAULT(0) ); - -/** @brief Finds a node in a map or file storage. - -The function finds a file node. It is a faster version of cvGetFileNodeByName (see -cvGetHashedKey discussion). Also, the function can insert a new node, if it is not in the map yet. -@param fs File storage -@param map The parent map. If it is NULL, the function searches a top-level node. If both map and -key are NULLs, the function returns the root file node - a map that contains top-level nodes. -@param key Unique pointer to the node name, retrieved with cvGetHashedKey -@param create_missing Flag that specifies whether an absent node should be added to the map - */ -CVAPI(CvFileNode*) cvGetFileNode( CvFileStorage* fs, CvFileNode* map, - const CvStringHashNode* key, - int create_missing CV_DEFAULT(0) ); - -/** @brief Finds a node in a map or file storage. - -The function finds a file node by name. The node is searched either in map or, if the pointer is -NULL, among the top-level file storage nodes. Using this function for maps and cvGetSeqElem (or -sequence reader) for sequences, it is possible to navigate through the file storage. To speed up -multiple queries for a certain key (e.g., in the case of an array of structures) one may use a -combination of cvGetHashedKey and cvGetFileNode. -@param fs File storage -@param map The parent map. If it is NULL, the function searches in all the top-level nodes -(streams), starting with the first one. -@param name The file node name - */ -CVAPI(CvFileNode*) cvGetFileNodeByName( const CvFileStorage* fs, - const CvFileNode* map, - const char* name ); - -/** @brief Retrieves an integer value from a file node. - -The function returns an integer that is represented by the file node. If the file node is NULL, the -default_value is returned (thus, it is convenient to call the function right after cvGetFileNode -without checking for a NULL pointer). If the file node has type CV_NODE_INT, then node-\>data.i is -returned. If the file node has type CV_NODE_REAL, then node-\>data.f is converted to an integer -and returned. Otherwise the error is reported. -@param node File node -@param default_value The value that is returned if node is NULL - */ -CV_INLINE int cvReadInt( const CvFileNode* node, int default_value CV_DEFAULT(0) ) -{ - return !node ? default_value : - CV_NODE_IS_INT(node->tag) ? node->data.i : - CV_NODE_IS_REAL(node->tag) ? cvRound(node->data.f) : 0x7fffffff; -} - -/** @brief Finds a file node and returns its value. - -The function is a simple superposition of cvGetFileNodeByName and cvReadInt. -@param fs File storage -@param map The parent map. If it is NULL, the function searches a top-level node. -@param name The node name -@param default_value The value that is returned if the file node is not found - */ -CV_INLINE int cvReadIntByName( const CvFileStorage* fs, const CvFileNode* map, - const char* name, int default_value CV_DEFAULT(0) ) -{ - return cvReadInt( cvGetFileNodeByName( fs, map, name ), default_value ); -} - -/** @brief Retrieves a floating-point value from a file node. - -The function returns a floating-point value that is represented by the file node. If the file node -is NULL, the default_value is returned (thus, it is convenient to call the function right after -cvGetFileNode without checking for a NULL pointer). If the file node has type CV_NODE_REAL , -then node-\>data.f is returned. If the file node has type CV_NODE_INT , then node-:math:\>data.f -is converted to floating-point and returned. Otherwise the result is not determined. -@param node File node -@param default_value The value that is returned if node is NULL - */ -CV_INLINE double cvReadReal( const CvFileNode* node, double default_value CV_DEFAULT(0.) ) -{ - return !node ? default_value : - CV_NODE_IS_INT(node->tag) ? (double)node->data.i : - CV_NODE_IS_REAL(node->tag) ? node->data.f : 1e300; -} - -/** @brief Finds a file node and returns its value. - -The function is a simple superposition of cvGetFileNodeByName and cvReadReal . -@param fs File storage -@param map The parent map. If it is NULL, the function searches a top-level node. -@param name The node name -@param default_value The value that is returned if the file node is not found - */ -CV_INLINE double cvReadRealByName( const CvFileStorage* fs, const CvFileNode* map, - const char* name, double default_value CV_DEFAULT(0.) ) -{ - return cvReadReal( cvGetFileNodeByName( fs, map, name ), default_value ); -} - -/** @brief Retrieves a text string from a file node. - -The function returns a text string that is represented by the file node. If the file node is NULL, -the default_value is returned (thus, it is convenient to call the function right after -cvGetFileNode without checking for a NULL pointer). If the file node has type CV_NODE_STR , then -node-:math:\>data.str.ptr is returned. Otherwise the result is not determined. -@param node File node -@param default_value The value that is returned if node is NULL - */ -CV_INLINE const char* cvReadString( const CvFileNode* node, - const char* default_value CV_DEFAULT(NULL) ) -{ - return !node ? default_value : CV_NODE_IS_STRING(node->tag) ? node->data.str.ptr : 0; -} - -/** @brief Finds a file node by its name and returns its value. - -The function is a simple superposition of cvGetFileNodeByName and cvReadString . -@param fs File storage -@param map The parent map. If it is NULL, the function searches a top-level node. -@param name The node name -@param default_value The value that is returned if the file node is not found - */ -CV_INLINE const char* cvReadStringByName( const CvFileStorage* fs, const CvFileNode* map, - const char* name, const char* default_value CV_DEFAULT(NULL) ) -{ - return cvReadString( cvGetFileNodeByName( fs, map, name ), default_value ); -} - - -/** @brief Decodes an object and returns a pointer to it. - -The function decodes a user object (creates an object in a native representation from the file -storage subtree) and returns it. The object to be decoded must be an instance of a registered type -that supports the read method (see CvTypeInfo). The type of the object is determined by the type -name that is encoded in the file. If the object is a dynamic structure, it is created either in -memory storage and passed to cvOpenFileStorage or, if a NULL pointer was passed, in temporary -memory storage, which is released when cvReleaseFileStorage is called. Otherwise, if the object is -not a dynamic structure, it is created in a heap and should be released with a specialized function -or by using the generic cvRelease. -@param fs File storage -@param node The root object node -@param attributes Unused parameter - */ -CVAPI(void*) cvRead( CvFileStorage* fs, CvFileNode* node, - CvAttrList* attributes CV_DEFAULT(NULL)); - -/** @brief Finds an object by name and decodes it. - -The function is a simple superposition of cvGetFileNodeByName and cvRead. -@param fs File storage -@param map The parent map. If it is NULL, the function searches a top-level node. -@param name The node name -@param attributes Unused parameter - */ -CV_INLINE void* cvReadByName( CvFileStorage* fs, const CvFileNode* map, - const char* name, CvAttrList* attributes CV_DEFAULT(NULL) ) -{ - return cvRead( fs, cvGetFileNodeByName( fs, map, name ), attributes ); -} - - -/** @brief Initializes the file node sequence reader. - -The function initializes the sequence reader to read data from a file node. The initialized reader -can be then passed to cvReadRawDataSlice. -@param fs File storage -@param src The file node (a sequence) to read numbers from -@param reader Pointer to the sequence reader - */ -CVAPI(void) cvStartReadRawData( const CvFileStorage* fs, const CvFileNode* src, - CvSeqReader* reader ); - -/** @brief Initializes file node sequence reader. - -The function reads one or more elements from the file node, representing a sequence, to a -user-specified array. The total number of read sequence elements is a product of total and the -number of components in each array element. For example, if dt=2if, the function will read total\*3 -sequence elements. As with any sequence, some parts of the file node sequence can be skipped or read -repeatedly by repositioning the reader using cvSetSeqReaderPos. -@param fs File storage -@param reader The sequence reader. Initialize it with cvStartReadRawData . -@param count The number of elements to read -@param dst Pointer to the destination array -@param dt Specification of each array element. It has the same format as in cvWriteRawData . - */ -CVAPI(void) cvReadRawDataSlice( const CvFileStorage* fs, CvSeqReader* reader, - int count, void* dst, const char* dt ); - -/** @brief Reads multiple numbers. - -The function reads elements from a file node that represents a sequence of scalars. -@param fs File storage -@param src The file node (a sequence) to read numbers from -@param dst Pointer to the destination array -@param dt Specification of each array element. It has the same format as in cvWriteRawData . - */ -CVAPI(void) cvReadRawData( const CvFileStorage* fs, const CvFileNode* src, - void* dst, const char* dt ); - -/** @brief Writes a file node to another file storage. - -The function writes a copy of a file node to file storage. Possible applications of the function are -merging several file storages into one and conversion between XML, YAML and JSON formats. -@param fs Destination file storage -@param new_node_name New name of the file node in the destination file storage. To keep the -existing name, use cvcvGetFileNodeName -@param node The written node -@param embed If the written node is a collection and this parameter is not zero, no extra level of -hierarchy is created. Instead, all the elements of node are written into the currently written -structure. Of course, map elements can only be embedded into another map, and sequence elements -can only be embedded into another sequence. - */ -CVAPI(void) cvWriteFileNode( CvFileStorage* fs, const char* new_node_name, - const CvFileNode* node, int embed ); - -/** @brief Returns the name of a file node. - -The function returns the name of a file node or NULL, if the file node does not have a name or if -node is NULL. -@param node File node - */ -CVAPI(const char*) cvGetFileNodeName( const CvFileNode* node ); - -/*********************************** Adding own types ***********************************/ - -/** @brief Registers a new type. - -The function registers a new type, which is described by info . The function creates a copy of the -structure, so the user should delete it after calling the function. -@param info Type info structure - */ -CVAPI(void) cvRegisterType( const CvTypeInfo* info ); - -/** @brief Unregisters the type. - -The function unregisters a type with a specified name. If the name is unknown, it is possible to -locate the type info by an instance of the type using cvTypeOf or by iterating the type list, -starting from cvFirstType, and then calling cvUnregisterType(info-\>typeName). -@param type_name Name of an unregistered type - */ -CVAPI(void) cvUnregisterType( const char* type_name ); - -/** @brief Returns the beginning of a type list. - -The function returns the first type in the list of registered types. Navigation through the list can -be done via the prev and next fields of the CvTypeInfo structure. - */ -CVAPI(CvTypeInfo*) cvFirstType(void); - -/** @brief Finds a type by its name. - -The function finds a registered type by its name. It returns NULL if there is no type with the -specified name. -@param type_name Type name - */ -CVAPI(CvTypeInfo*) cvFindType( const char* type_name ); - -/** @brief Returns the type of an object. - -The function finds the type of a given object. It iterates through the list of registered types and -calls the is_instance function/method for every type info structure with that object until one of -them returns non-zero or until the whole list has been traversed. In the latter case, the function -returns NULL. -@param struct_ptr The object pointer - */ -CVAPI(CvTypeInfo*) cvTypeOf( const void* struct_ptr ); - -#endif - -/** @brief Releases an object. - - The function finds the type of a given object and calls release with the double pointer. - @param struct_ptr Double pointer to the object - */ -CVAPI(void) cvRelease( void** struct_ptr ); - -/** @brief Makes a clone of an object. - -The function finds the type of a given object and calls clone with the passed object. Of course, if -you know the object type, for example, struct_ptr is CvMat\*, it is faster to call the specific -function, like cvCloneMat. -@param struct_ptr The object to clone - */ -CVAPI(void*) cvClone( const void* struct_ptr ); - -/*********************************** Measuring Execution Time ***************************/ - -/** helper functions for RNG initialization and accurate time measurement: - uses internal clock counter on x86 */ -CVAPI(int64) cvGetTickCount( void ); -CVAPI(double) cvGetTickFrequency( void ); - -/*********************************** CPU capabilities ***********************************/ - -CVAPI(int) cvCheckHardwareSupport(int feature); - -/*********************************** Multi-Threading ************************************/ - -/** retrieve/set the number of threads used in OpenMP implementations */ -CVAPI(int) cvGetNumThreads( void ); -CVAPI(void) cvSetNumThreads( int threads CV_DEFAULT(0) ); -/** get index of the thread being executed */ -CVAPI(int) cvGetThreadNum( void ); - - -/********************************** Error Handling **************************************/ - -/** Get current OpenCV error status */ -CVAPI(int) cvGetErrStatus( void ); - -/** Sets error status silently */ -CVAPI(void) cvSetErrStatus( int status ); - -#define CV_ErrModeLeaf 0 /* Print error and exit program */ -#define CV_ErrModeParent 1 /* Print error and continue */ -#define CV_ErrModeSilent 2 /* Don't print and continue */ - -/** Retrieves current error processing mode */ -CVAPI(int) cvGetErrMode( void ); - -/** Sets error processing mode, returns previously used mode */ -CVAPI(int) cvSetErrMode( int mode ); - -/** Sets error status and performs some additional actions (displaying message box, - writing message to stderr, terminating application etc.) - depending on the current error mode */ -CVAPI(void) cvError( int status, const char* func_name, - const char* err_msg, const char* file_name, int line ); - -/** Retrieves textual description of the error given its code */ -CVAPI(const char*) cvErrorStr( int status ); - -/** Retrieves detailed information about the last error occurred */ -CVAPI(int) cvGetErrInfo( const char** errcode_desc, const char** description, - const char** filename, int* line ); - -/** Maps IPP error codes to the counterparts from OpenCV */ -CVAPI(int) cvErrorFromIppStatus( int ipp_status ); - -typedef int (CV_CDECL *CvErrorCallback)( int status, const char* func_name, - const char* err_msg, const char* file_name, int line, void* userdata ); - -/** Assigns a new error-handling function */ -CVAPI(CvErrorCallback) cvRedirectError( CvErrorCallback error_handler, - void* userdata CV_DEFAULT(NULL), - void** prev_userdata CV_DEFAULT(NULL) ); - -/** Output nothing */ -CVAPI(int) cvNulDevReport( int status, const char* func_name, const char* err_msg, - const char* file_name, int line, void* userdata ); - -/** Output to console(fprintf(stderr,...)) */ -CVAPI(int) cvStdErrReport( int status, const char* func_name, const char* err_msg, - const char* file_name, int line, void* userdata ); - -/** Output to MessageBox(WIN32) */ -CVAPI(int) cvGuiBoxReport( int status, const char* func_name, const char* err_msg, - const char* file_name, int line, void* userdata ); - -#define OPENCV_ERROR(status,func,context) \ -cvError((status),(func),(context),__FILE__,__LINE__) - -#define OPENCV_ASSERT(expr,func,context) \ -{if (! (expr)) \ -{OPENCV_ERROR(CV_StsInternal,(func),(context));}} - -#define OPENCV_CALL( Func ) \ -{ \ -Func; \ -} - - -/** CV_FUNCNAME macro defines icvFuncName constant which is used by CV_ERROR macro */ -#ifdef CV_NO_FUNC_NAMES -#define CV_FUNCNAME( Name ) -#define cvFuncName "" -#else -#define CV_FUNCNAME( Name ) \ -static char cvFuncName[] = Name -#endif - - -/** - CV_ERROR macro unconditionally raises error with passed code and message. - After raising error, control will be transferred to the exit label. - */ -#define CV_ERROR( Code, Msg ) \ -{ \ - cvError( (Code), cvFuncName, Msg, __FILE__, __LINE__ ); \ - __CV_EXIT__; \ -} - -/** - CV_CHECK macro checks error status after CV (or IPL) - function call. If error detected, control will be transferred to the exit - label. - */ -#define CV_CHECK() \ -{ \ - if( cvGetErrStatus() < 0 ) \ - CV_ERROR( CV_StsBackTrace, "Inner function failed." ); \ -} - - -/** - CV_CALL macro calls CV (or IPL) function, checks error status and - signals a error if the function failed. Useful in "parent node" - error processing mode - */ -#define CV_CALL( Func ) \ -{ \ - Func; \ - CV_CHECK(); \ -} - - -/** Runtime assertion macro */ -#define CV_ASSERT( Condition ) \ -{ \ - if( !(Condition) ) \ - CV_ERROR( CV_StsInternal, "Assertion: " #Condition " failed" ); \ -} - -#define __CV_BEGIN__ { -#define __CV_END__ goto exit; exit: ; } -#define __CV_EXIT__ goto exit - -/** @} core_c */ - -#ifdef __cplusplus -} // extern "C" -#endif - -#ifdef __cplusplus - -#include "opencv2/core/utility.hpp" - -namespace cv -{ - -//! @addtogroup core_c_glue -//! @{ - -/////////////////////////////////////////// glue /////////////////////////////////////////// - -//! converts array (CvMat or IplImage) to cv::Mat -CV_EXPORTS Mat cvarrToMat(const CvArr* arr, bool copyData=false, - bool allowND=true, int coiMode=0, - AutoBuffer* buf=0); - -static inline Mat cvarrToMatND(const CvArr* arr, bool copyData=false, int coiMode=0) -{ - return cvarrToMat(arr, copyData, true, coiMode); -} - - -//! extracts Channel of Interest from CvMat or IplImage and makes cv::Mat out of it. -CV_EXPORTS void extractImageCOI(const CvArr* arr, OutputArray coiimg, int coi=-1); -//! inserts single-channel cv::Mat into a multi-channel CvMat or IplImage -CV_EXPORTS void insertImageCOI(InputArray coiimg, CvArr* arr, int coi=-1); - - - -////// specialized implementations of DefaultDeleter::operator() for classic OpenCV types ////// - -template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvMat* obj) const; }; -template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(IplImage* obj) const; }; -template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvMatND* obj) const; }; -template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvSparseMat* obj) const; }; -template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvMemStorage* obj) const; }; - -////////////// convenient wrappers for operating old-style dynamic structures ////////////// - -template class SeqIterator; - -typedef Ptr MemStorage; - -/*! - Template Sequence Class derived from CvSeq - - The class provides more convenient access to sequence elements, - STL-style operations and iterators. - - \note The class is targeted for simple data types, - i.e. no constructors or destructors - are called for the sequence elements. -*/ -template class Seq -{ -public: - typedef SeqIterator<_Tp> iterator; - typedef SeqIterator<_Tp> const_iterator; - - //! the default constructor - Seq(); - //! the constructor for wrapping CvSeq structure. The real element type in CvSeq should match _Tp. - Seq(const CvSeq* seq); - //! creates the empty sequence that resides in the specified storage - Seq(MemStorage& storage, int headerSize = sizeof(CvSeq)); - //! returns read-write reference to the specified element - _Tp& operator [](int idx); - //! returns read-only reference to the specified element - const _Tp& operator[](int idx) const; - //! returns iterator pointing to the beginning of the sequence - SeqIterator<_Tp> begin() const; - //! returns iterator pointing to the element following the last sequence element - SeqIterator<_Tp> end() const; - //! returns the number of elements in the sequence - size_t size() const; - //! returns the type of sequence elements (CV_8UC1 ... CV_64FC(CV_CN_MAX) ...) - int type() const; - //! returns the depth of sequence elements (CV_8U ... CV_64F) - int depth() const; - //! returns the number of channels in each sequence element - int channels() const; - //! returns the size of each sequence element - size_t elemSize() const; - //! returns index of the specified sequence element - size_t index(const _Tp& elem) const; - //! appends the specified element to the end of the sequence - void push_back(const _Tp& elem); - //! appends the specified element to the front of the sequence - void push_front(const _Tp& elem); - //! appends zero or more elements to the end of the sequence - void push_back(const _Tp* elems, size_t count); - //! appends zero or more elements to the front of the sequence - void push_front(const _Tp* elems, size_t count); - //! inserts the specified element to the specified position - void insert(int idx, const _Tp& elem); - //! inserts zero or more elements to the specified position - void insert(int idx, const _Tp* elems, size_t count); - //! removes element at the specified position - void remove(int idx); - //! removes the specified subsequence - void remove(const Range& r); - - //! returns reference to the first sequence element - _Tp& front(); - //! returns read-only reference to the first sequence element - const _Tp& front() const; - //! returns reference to the last sequence element - _Tp& back(); - //! returns read-only reference to the last sequence element - const _Tp& back() const; - //! returns true iff the sequence contains no elements - bool empty() const; - - //! removes all the elements from the sequence - void clear(); - //! removes the first element from the sequence - void pop_front(); - //! removes the last element from the sequence - void pop_back(); - //! removes zero or more elements from the beginning of the sequence - void pop_front(_Tp* elems, size_t count); - //! removes zero or more elements from the end of the sequence - void pop_back(_Tp* elems, size_t count); - - //! copies the whole sequence or the sequence slice to the specified vector - void copyTo(std::vector<_Tp>& vec, const Range& range=Range::all()) const; - //! returns the vector containing all the sequence elements - operator std::vector<_Tp>() const; - - CvSeq* seq; -}; - - -/*! - STL-style Sequence Iterator inherited from the CvSeqReader structure -*/ -template class SeqIterator : public CvSeqReader -{ -public: - //! the default constructor - SeqIterator(); - //! the constructor setting the iterator to the beginning or to the end of the sequence - SeqIterator(const Seq<_Tp>& seq, bool seekEnd=false); - //! positions the iterator within the sequence - void seek(size_t pos); - //! reports the current iterator position - size_t tell() const; - //! returns reference to the current sequence element - _Tp& operator *(); - //! returns read-only reference to the current sequence element - const _Tp& operator *() const; - //! moves iterator to the next sequence element - SeqIterator& operator ++(); - //! moves iterator to the next sequence element - SeqIterator operator ++(int) const; - //! moves iterator to the previous sequence element - SeqIterator& operator --(); - //! moves iterator to the previous sequence element - SeqIterator operator --(int) const; - - //! moves iterator forward by the specified offset (possibly negative) - SeqIterator& operator +=(int); - //! moves iterator backward by the specified offset (possibly negative) - SeqIterator& operator -=(int); - - // this is index of the current element module seq->total*2 - // (to distinguish between 0 and seq->total) - int index; -}; - - - -// bridge C++ => C Seq API -CV_EXPORTS schar* seqPush( CvSeq* seq, const void* element=0); -CV_EXPORTS schar* seqPushFront( CvSeq* seq, const void* element=0); -CV_EXPORTS void seqPop( CvSeq* seq, void* element=0); -CV_EXPORTS void seqPopFront( CvSeq* seq, void* element=0); -CV_EXPORTS void seqPopMulti( CvSeq* seq, void* elements, - int count, int in_front=0 ); -CV_EXPORTS void seqRemove( CvSeq* seq, int index ); -CV_EXPORTS void clearSeq( CvSeq* seq ); -CV_EXPORTS schar* getSeqElem( const CvSeq* seq, int index ); -CV_EXPORTS void seqRemoveSlice( CvSeq* seq, CvSlice slice ); -CV_EXPORTS void seqInsertSlice( CvSeq* seq, int before_index, const CvArr* from_arr ); - -template inline Seq<_Tp>::Seq() : seq(0) {} -template inline Seq<_Tp>::Seq( const CvSeq* _seq ) : seq((CvSeq*)_seq) -{ - CV_Assert(!_seq || _seq->elem_size == sizeof(_Tp)); -} - -template inline Seq<_Tp>::Seq( MemStorage& storage, - int headerSize ) -{ - CV_Assert(headerSize >= (int)sizeof(CvSeq)); - seq = cvCreateSeq(DataType<_Tp>::type, headerSize, sizeof(_Tp), storage); -} - -template inline _Tp& Seq<_Tp>::operator [](int idx) -{ return *(_Tp*)getSeqElem(seq, idx); } - -template inline const _Tp& Seq<_Tp>::operator [](int idx) const -{ return *(_Tp*)getSeqElem(seq, idx); } - -template inline SeqIterator<_Tp> Seq<_Tp>::begin() const -{ return SeqIterator<_Tp>(*this); } - -template inline SeqIterator<_Tp> Seq<_Tp>::end() const -{ return SeqIterator<_Tp>(*this, true); } - -template inline size_t Seq<_Tp>::size() const -{ return seq ? seq->total : 0; } - -template inline int Seq<_Tp>::type() const -{ return seq ? CV_MAT_TYPE(seq->flags) : 0; } - -template inline int Seq<_Tp>::depth() const -{ return seq ? CV_MAT_DEPTH(seq->flags) : 0; } - -template inline int Seq<_Tp>::channels() const -{ return seq ? CV_MAT_CN(seq->flags) : 0; } - -template inline size_t Seq<_Tp>::elemSize() const -{ return seq ? seq->elem_size : 0; } - -template inline size_t Seq<_Tp>::index(const _Tp& elem) const -{ return cvSeqElemIdx(seq, &elem); } - -template inline void Seq<_Tp>::push_back(const _Tp& elem) -{ cvSeqPush(seq, &elem); } - -template inline void Seq<_Tp>::push_front(const _Tp& elem) -{ cvSeqPushFront(seq, &elem); } - -template inline void Seq<_Tp>::push_back(const _Tp* elem, size_t count) -{ cvSeqPushMulti(seq, elem, (int)count, 0); } - -template inline void Seq<_Tp>::push_front(const _Tp* elem, size_t count) -{ cvSeqPushMulti(seq, elem, (int)count, 1); } - -template inline _Tp& Seq<_Tp>::back() -{ return *(_Tp*)getSeqElem(seq, -1); } - -template inline const _Tp& Seq<_Tp>::back() const -{ return *(const _Tp*)getSeqElem(seq, -1); } - -template inline _Tp& Seq<_Tp>::front() -{ return *(_Tp*)getSeqElem(seq, 0); } - -template inline const _Tp& Seq<_Tp>::front() const -{ return *(const _Tp*)getSeqElem(seq, 0); } - -template inline bool Seq<_Tp>::empty() const -{ return !seq || seq->total == 0; } - -template inline void Seq<_Tp>::clear() -{ if(seq) clearSeq(seq); } - -template inline void Seq<_Tp>::pop_back() -{ seqPop(seq); } - -template inline void Seq<_Tp>::pop_front() -{ seqPopFront(seq); } - -template inline void Seq<_Tp>::pop_back(_Tp* elem, size_t count) -{ seqPopMulti(seq, elem, (int)count, 0); } - -template inline void Seq<_Tp>::pop_front(_Tp* elem, size_t count) -{ seqPopMulti(seq, elem, (int)count, 1); } - -template inline void Seq<_Tp>::insert(int idx, const _Tp& elem) -{ seqInsert(seq, idx, &elem); } - -template inline void Seq<_Tp>::insert(int idx, const _Tp* elems, size_t count) -{ - CvMat m = cvMat(1, count, DataType<_Tp>::type, elems); - seqInsertSlice(seq, idx, &m); -} - -template inline void Seq<_Tp>::remove(int idx) -{ seqRemove(seq, idx); } - -template inline void Seq<_Tp>::remove(const Range& r) -{ seqRemoveSlice(seq, cvSlice(r.start, r.end)); } - -template inline void Seq<_Tp>::copyTo(std::vector<_Tp>& vec, const Range& range) const -{ - size_t len = !seq ? 0 : range == Range::all() ? seq->total : range.end - range.start; - vec.resize(len); - if( seq && len ) - cvCvtSeqToArray(seq, &vec[0], cvSlice(range)); -} - -template inline Seq<_Tp>::operator std::vector<_Tp>() const -{ - std::vector<_Tp> vec; - copyTo(vec); - return vec; -} - -template inline SeqIterator<_Tp>::SeqIterator() -{ memset(this, 0, sizeof(*this)); } - -template inline SeqIterator<_Tp>::SeqIterator(const Seq<_Tp>& _seq, bool seekEnd) -{ - cvStartReadSeq(_seq.seq, this); - index = seekEnd ? _seq.seq->total : 0; -} - -template inline void SeqIterator<_Tp>::seek(size_t pos) -{ - cvSetSeqReaderPos(this, (int)pos, false); - index = pos; -} - -template inline size_t SeqIterator<_Tp>::tell() const -{ return index; } - -template inline _Tp& SeqIterator<_Tp>::operator *() -{ return *(_Tp*)ptr; } - -template inline const _Tp& SeqIterator<_Tp>::operator *() const -{ return *(const _Tp*)ptr; } - -template inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator ++() -{ - CV_NEXT_SEQ_ELEM(sizeof(_Tp), *this); - if( ++index >= seq->total*2 ) - index = 0; - return *this; -} - -template inline SeqIterator<_Tp> SeqIterator<_Tp>::operator ++(int) const -{ - SeqIterator<_Tp> it = *this; - ++*this; - return it; -} - -template inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator --() -{ - CV_PREV_SEQ_ELEM(sizeof(_Tp), *this); - if( --index < 0 ) - index = seq->total*2-1; - return *this; -} - -template inline SeqIterator<_Tp> SeqIterator<_Tp>::operator --(int) const -{ - SeqIterator<_Tp> it = *this; - --*this; - return it; -} - -template inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator +=(int delta) -{ - cvSetSeqReaderPos(this, delta, 1); - index += delta; - int n = seq->total*2; - if( index < 0 ) - index += n; - if( index >= n ) - index -= n; - return *this; -} - -template inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator -=(int delta) -{ - return (*this += -delta); -} - -template inline ptrdiff_t operator - (const SeqIterator<_Tp>& a, - const SeqIterator<_Tp>& b) -{ - ptrdiff_t delta = a.index - b.index, n = a.seq->total; - if( delta > n || delta < -n ) - delta += delta < 0 ? n : -n; - return delta; -} - -template inline bool operator == (const SeqIterator<_Tp>& a, - const SeqIterator<_Tp>& b) -{ - return a.seq == b.seq && a.index == b.index; -} - -template inline bool operator != (const SeqIterator<_Tp>& a, - const SeqIterator<_Tp>& b) -{ - return !(a == b); -} - -//! @} - -} // cv - -#endif - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + + +#ifndef OPENCV_CORE_C_H +#define OPENCV_CORE_C_H + +#include "opencv2/core/types_c.h" + +#ifdef __cplusplus +/* disable MSVC warning C4190 / clang-cl -Wreturn-type-c-linkage: + 'function' has C-linkage specified, but returns UDT 'typename' + which is incompatible with C + + It is OK to disable it because we only extend few plain structures with + C++ constructors for simpler interoperability with C++ API of the library +*/ +# if defined(__clang__) + // handle clang on Linux and clang-cl (i. e. clang on Windows) first +# pragma GCC diagnostic ignored "-Wreturn-type-c-linkage" +# elif defined(_MSC_VER) + // then handle MSVC +# pragma warning(disable:4190) +# endif +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** @addtogroup core_c + @{ +*/ + +/****************************************************************************************\ +* Array allocation, deallocation, initialization and access to elements * +\****************************************************************************************/ + +/** `malloc` wrapper. + If there is no enough memory, the function + (as well as other OpenCV functions that call cvAlloc) + raises an error. */ +CVAPI(void*) cvAlloc( size_t size ); + +/** `free` wrapper. + Here and further all the memory releasing functions + (that all call cvFree) take double pointer in order to + to clear pointer to the data after releasing it. + Passing pointer to NULL pointer is Ok: nothing happens in this case +*/ +CVAPI(void) cvFree_( void* ptr ); +#define cvFree(ptr) (cvFree_(*(ptr)), *(ptr)=0) + +/** @brief Creates an image header but does not allocate the image data. + +@param size Image width and height +@param depth Image depth (see cvCreateImage ) +@param channels Number of channels (see cvCreateImage ) + */ +CVAPI(IplImage*) cvCreateImageHeader( CvSize size, int depth, int channels ); + +/** @brief Initializes an image header that was previously allocated. + +The returned IplImage\* points to the initialized header. +@param image Image header to initialize +@param size Image width and height +@param depth Image depth (see cvCreateImage ) +@param channels Number of channels (see cvCreateImage ) +@param origin Top-left IPL_ORIGIN_TL or bottom-left IPL_ORIGIN_BL +@param align Alignment for image rows, typically 4 or 8 bytes + */ +CVAPI(IplImage*) cvInitImageHeader( IplImage* image, CvSize size, int depth, + int channels, int origin CV_DEFAULT(0), + int align CV_DEFAULT(4)); + +/** @brief Creates an image header and allocates the image data. + +This function call is equivalent to the following code: +@code + header = cvCreateImageHeader(size, depth, channels); + cvCreateData(header); +@endcode +@param size Image width and height +@param depth Bit depth of image elements. See IplImage for valid depths. +@param channels Number of channels per pixel. See IplImage for details. This function only creates +images with interleaved channels. + */ +CVAPI(IplImage*) cvCreateImage( CvSize size, int depth, int channels ); + +/** @brief Deallocates an image header. + +This call is an analogue of : +@code + if(image ) + { + iplDeallocate(*image, IPL_IMAGE_HEADER | IPL_IMAGE_ROI); + *image = 0; + } +@endcode +but it does not use IPL functions by default (see the CV_TURN_ON_IPL_COMPATIBILITY macro). +@param image Double pointer to the image header + */ +CVAPI(void) cvReleaseImageHeader( IplImage** image ); + +/** @brief Deallocates the image header and the image data. + +This call is a shortened form of : +@code + if(*image ) + { + cvReleaseData(*image); + cvReleaseImageHeader(image); + } +@endcode +@param image Double pointer to the image header +*/ +CVAPI(void) cvReleaseImage( IplImage** image ); + +/** Creates a copy of IPL image (widthStep may differ) */ +CVAPI(IplImage*) cvCloneImage( const IplImage* image ); + +/** @brief Sets the channel of interest in an IplImage. + +If the ROI is set to NULL and the coi is *not* 0, the ROI is allocated. Most OpenCV functions do +*not* support the COI setting, so to process an individual image/matrix channel one may copy (via +cvCopy or cvSplit) the channel to a separate image/matrix, process it and then copy the result +back (via cvCopy or cvMerge) if needed. +@param image A pointer to the image header +@param coi The channel of interest. 0 - all channels are selected, 1 - first channel is selected, +etc. Note that the channel indices become 1-based. + */ +CVAPI(void) cvSetImageCOI( IplImage* image, int coi ); + +/** @brief Returns the index of the channel of interest. + +Returns the channel of interest of in an IplImage. Returned values correspond to the coi in +cvSetImageCOI. +@param image A pointer to the image header + */ +CVAPI(int) cvGetImageCOI( const IplImage* image ); + +/** @brief Sets an image Region Of Interest (ROI) for a given rectangle. + +If the original image ROI was NULL and the rect is not the whole image, the ROI structure is +allocated. + +Most OpenCV functions support the use of ROI and treat the image rectangle as a separate image. For +example, all of the pixel coordinates are counted from the top-left (or bottom-left) corner of the +ROI, not the original image. +@param image A pointer to the image header +@param rect The ROI rectangle + */ +CVAPI(void) cvSetImageROI( IplImage* image, CvRect rect ); + +/** @brief Resets the image ROI to include the entire image and releases the ROI structure. + +This produces a similar result to the following, but in addition it releases the ROI structure. : +@code + cvSetImageROI(image, cvRect(0, 0, image->width, image->height )); + cvSetImageCOI(image, 0); +@endcode +@param image A pointer to the image header + */ +CVAPI(void) cvResetImageROI( IplImage* image ); + +/** @brief Returns the image ROI. + +If there is no ROI set, cvRect(0,0,image-\>width,image-\>height) is returned. +@param image A pointer to the image header + */ +CVAPI(CvRect) cvGetImageROI( const IplImage* image ); + +/** @brief Creates a matrix header but does not allocate the matrix data. + +The function allocates a new matrix header and returns a pointer to it. The matrix data can then be +allocated using cvCreateData or set explicitly to user-allocated data via cvSetData. +@param rows Number of rows in the matrix +@param cols Number of columns in the matrix +@param type Type of the matrix elements, see cvCreateMat + */ +CVAPI(CvMat*) cvCreateMatHeader( int rows, int cols, int type ); + +#define CV_AUTOSTEP 0x7fffffff + +/** @brief Initializes a pre-allocated matrix header. + +This function is often used to process raw data with OpenCV matrix functions. For example, the +following code computes the matrix product of two matrices, stored as ordinary arrays: +@code + double a[] = { 1, 2, 3, 4, + 5, 6, 7, 8, + 9, 10, 11, 12 }; + + double b[] = { 1, 5, 9, + 2, 6, 10, + 3, 7, 11, + 4, 8, 12 }; + + double c[9]; + CvMat Ma, Mb, Mc ; + + cvInitMatHeader(&Ma, 3, 4, CV_64FC1, a); + cvInitMatHeader(&Mb, 4, 3, CV_64FC1, b); + cvInitMatHeader(&Mc, 3, 3, CV_64FC1, c); + + cvMatMulAdd(&Ma, &Mb, 0, &Mc); + // the c array now contains the product of a (3x4) and b (4x3) +@endcode +@param mat A pointer to the matrix header to be initialized +@param rows Number of rows in the matrix +@param cols Number of columns in the matrix +@param type Type of the matrix elements, see cvCreateMat . +@param data Optional: data pointer assigned to the matrix header +@param step Optional: full row width in bytes of the assigned data. By default, the minimal +possible step is used which assumes there are no gaps between subsequent rows of the matrix. + */ +CVAPI(CvMat*) cvInitMatHeader( CvMat* mat, int rows, int cols, + int type, void* data CV_DEFAULT(NULL), + int step CV_DEFAULT(CV_AUTOSTEP) ); + +/** @brief Creates a matrix header and allocates the matrix data. + +The function call is equivalent to the following code: +@code + CvMat* mat = cvCreateMatHeader(rows, cols, type); + cvCreateData(mat); +@endcode +@param rows Number of rows in the matrix +@param cols Number of columns in the matrix +@param type The type of the matrix elements in the form +CV_\\C\ , where S=signed, U=unsigned, F=float. For +example, CV _ 8UC1 means the elements are 8-bit unsigned and the there is 1 channel, and CV _ +32SC2 means the elements are 32-bit signed and there are 2 channels. + */ +CVAPI(CvMat*) cvCreateMat( int rows, int cols, int type ); + +/** @brief Deallocates a matrix. + +The function decrements the matrix data reference counter and deallocates matrix header. If the data +reference counter is 0, it also deallocates the data. : +@code + if(*mat ) + cvDecRefData(*mat); + cvFree((void**)mat); +@endcode +@param mat Double pointer to the matrix + */ +CVAPI(void) cvReleaseMat( CvMat** mat ); + +/** @brief Decrements an array data reference counter. + +The function decrements the data reference counter in a CvMat or CvMatND if the reference counter + +pointer is not NULL. If the counter reaches zero, the data is deallocated. In the current +implementation the reference counter is not NULL only if the data was allocated using the +cvCreateData function. The counter will be NULL in other cases such as: external data was assigned +to the header using cvSetData, header is part of a larger matrix or image, or the header was +converted from an image or n-dimensional matrix header. +@param arr Pointer to an array header + */ +CV_INLINE void cvDecRefData( CvArr* arr ) +{ + if( CV_IS_MAT( arr )) + { + CvMat* mat = (CvMat*)arr; + mat->data.ptr = NULL; + if( mat->refcount != NULL && --*mat->refcount == 0 ) + cvFree( &mat->refcount ); + mat->refcount = NULL; + } + else if( CV_IS_MATND( arr )) + { + CvMatND* mat = (CvMatND*)arr; + mat->data.ptr = NULL; + if( mat->refcount != NULL && --*mat->refcount == 0 ) + cvFree( &mat->refcount ); + mat->refcount = NULL; + } +} + +/** @brief Increments array data reference counter. + +The function increments CvMat or CvMatND data reference counter and returns the new counter value if +the reference counter pointer is not NULL, otherwise it returns zero. +@param arr Array header + */ +CV_INLINE int cvIncRefData( CvArr* arr ) +{ + int refcount = 0; + if( CV_IS_MAT( arr )) + { + CvMat* mat = (CvMat*)arr; + if( mat->refcount != NULL ) + refcount = ++*mat->refcount; + } + else if( CV_IS_MATND( arr )) + { + CvMatND* mat = (CvMatND*)arr; + if( mat->refcount != NULL ) + refcount = ++*mat->refcount; + } + return refcount; +} + + +/** Creates an exact copy of the input matrix (except, may be, step value) */ +CVAPI(CvMat*) cvCloneMat( const CvMat* mat ); + + +/** @brief Returns matrix header corresponding to the rectangular sub-array of input image or matrix. + +The function returns header, corresponding to a specified rectangle of the input array. In other + +words, it allows the user to treat a rectangular part of input array as a stand-alone array. ROI is +taken into account by the function so the sub-array of ROI is actually extracted. +@param arr Input array +@param submat Pointer to the resultant sub-array header +@param rect Zero-based coordinates of the rectangle of interest + */ +CVAPI(CvMat*) cvGetSubRect( const CvArr* arr, CvMat* submat, CvRect rect ); +#define cvGetSubArr cvGetSubRect + +/** @brief Returns array row or row span. + +The function returns the header, corresponding to a specified row/row span of the input array. +cvGetRow(arr, submat, row) is a shortcut for cvGetRows(arr, submat, row, row+1). +@param arr Input array +@param submat Pointer to the resulting sub-array header +@param start_row Zero-based index of the starting row (inclusive) of the span +@param end_row Zero-based index of the ending row (exclusive) of the span +@param delta_row Index step in the row span. That is, the function extracts every delta_row -th +row from start_row and up to (but not including) end_row . + */ +CVAPI(CvMat*) cvGetRows( const CvArr* arr, CvMat* submat, + int start_row, int end_row, + int delta_row CV_DEFAULT(1)); + +/** @overload +@param arr Input array +@param submat Pointer to the resulting sub-array header +@param row Zero-based index of the selected row +*/ +CV_INLINE CvMat* cvGetRow( const CvArr* arr, CvMat* submat, int row ) +{ + return cvGetRows( arr, submat, row, row + 1, 1 ); +} + + +/** @brief Returns one of more array columns. + +The function returns the header, corresponding to a specified column span of the input array. That + +is, no data is copied. Therefore, any modifications of the submatrix will affect the original array. +If you need to copy the columns, use cvCloneMat. cvGetCol(arr, submat, col) is a shortcut for +cvGetCols(arr, submat, col, col+1). +@param arr Input array +@param submat Pointer to the resulting sub-array header +@param start_col Zero-based index of the starting column (inclusive) of the span +@param end_col Zero-based index of the ending column (exclusive) of the span + */ +CVAPI(CvMat*) cvGetCols( const CvArr* arr, CvMat* submat, + int start_col, int end_col ); + +/** @overload +@param arr Input array +@param submat Pointer to the resulting sub-array header +@param col Zero-based index of the selected column +*/ +CV_INLINE CvMat* cvGetCol( const CvArr* arr, CvMat* submat, int col ) +{ + return cvGetCols( arr, submat, col, col + 1 ); +} + +/** @brief Returns one of array diagonals. + +The function returns the header, corresponding to a specified diagonal of the input array. +@param arr Input array +@param submat Pointer to the resulting sub-array header +@param diag Index of the array diagonal. Zero value corresponds to the main diagonal, -1 +corresponds to the diagonal above the main, 1 corresponds to the diagonal below the main, and so +forth. + */ +CVAPI(CvMat*) cvGetDiag( const CvArr* arr, CvMat* submat, + int diag CV_DEFAULT(0)); + +/** low-level scalar <-> raw data conversion functions */ +CVAPI(void) cvScalarToRawData( const CvScalar* scalar, void* data, int type, + int extend_to_12 CV_DEFAULT(0) ); + +CVAPI(void) cvRawDataToScalar( const void* data, int type, CvScalar* scalar ); + +/** @brief Creates a new matrix header but does not allocate the matrix data. + +The function allocates a header for a multi-dimensional dense array. The array data can further be +allocated using cvCreateData or set explicitly to user-allocated data via cvSetData. +@param dims Number of array dimensions +@param sizes Array of dimension sizes +@param type Type of array elements, see cvCreateMat + */ +CVAPI(CvMatND*) cvCreateMatNDHeader( int dims, const int* sizes, int type ); + +/** @brief Creates the header and allocates the data for a multi-dimensional dense array. + +This function call is equivalent to the following code: +@code + CvMatND* mat = cvCreateMatNDHeader(dims, sizes, type); + cvCreateData(mat); +@endcode +@param dims Number of array dimensions. This must not exceed CV_MAX_DIM (32 by default, but can be +changed at build time). +@param sizes Array of dimension sizes. +@param type Type of array elements, see cvCreateMat . + */ +CVAPI(CvMatND*) cvCreateMatND( int dims, const int* sizes, int type ); + +/** @brief Initializes a pre-allocated multi-dimensional array header. + +@param mat A pointer to the array header to be initialized +@param dims The number of array dimensions +@param sizes An array of dimension sizes +@param type Type of array elements, see cvCreateMat +@param data Optional data pointer assigned to the matrix header + */ +CVAPI(CvMatND*) cvInitMatNDHeader( CvMatND* mat, int dims, const int* sizes, + int type, void* data CV_DEFAULT(NULL) ); + +/** @brief Deallocates a multi-dimensional array. + +The function decrements the array data reference counter and releases the array header. If the +reference counter reaches 0, it also deallocates the data. : +@code + if(*mat ) + cvDecRefData(*mat); + cvFree((void**)mat); +@endcode +@param mat Double pointer to the array + */ +CV_INLINE void cvReleaseMatND( CvMatND** mat ) +{ + cvReleaseMat( (CvMat**)mat ); +} + +/** Creates a copy of CvMatND (except, may be, steps) */ +CVAPI(CvMatND*) cvCloneMatND( const CvMatND* mat ); + +/** @brief Creates sparse array. + +The function allocates a multi-dimensional sparse array. Initially the array contain no elements, +that is PtrND and other related functions will return 0 for every index. +@param dims Number of array dimensions. In contrast to the dense matrix, the number of dimensions is +practically unlimited (up to \f$2^{16}\f$ ). +@param sizes Array of dimension sizes +@param type Type of array elements. The same as for CvMat + */ +CVAPI(CvSparseMat*) cvCreateSparseMat( int dims, const int* sizes, int type ); + +/** @brief Deallocates sparse array. + +The function releases the sparse array and clears the array pointer upon exit. +@param mat Double pointer to the array + */ +CVAPI(void) cvReleaseSparseMat( CvSparseMat** mat ); + +/** Creates a copy of CvSparseMat (except, may be, zero items) */ +CVAPI(CvSparseMat*) cvCloneSparseMat( const CvSparseMat* mat ); + +/** @brief Initializes sparse array elements iterator. + +The function initializes iterator of sparse array elements and returns pointer to the first element, +or NULL if the array is empty. +@param mat Input array +@param mat_iterator Initialized iterator + */ +CVAPI(CvSparseNode*) cvInitSparseMatIterator( const CvSparseMat* mat, + CvSparseMatIterator* mat_iterator ); + +/** @brief Returns the next sparse matrix element + +The function moves iterator to the next sparse matrix element and returns pointer to it. In the +current version there is no any particular order of the elements, because they are stored in the +hash table. The sample below demonstrates how to iterate through the sparse matrix: +@code + // print all the non-zero sparse matrix elements and compute their sum + double sum = 0; + int i, dims = cvGetDims(sparsemat); + CvSparseMatIterator it; + CvSparseNode* node = cvInitSparseMatIterator(sparsemat, &it); + + for(; node != 0; node = cvGetNextSparseNode(&it)) + { + int* idx = CV_NODE_IDX(array, node); + float val = *(float*)CV_NODE_VAL(array, node); + printf("M"); + for(i = 0; i < dims; i++ ) + printf("[%d]", idx[i]); + printf("=%g\n", val); + + sum += val; + } + + printf("nTotal sum = %g\n", sum); +@endcode +@param mat_iterator Sparse array iterator + */ +CV_INLINE CvSparseNode* cvGetNextSparseNode( CvSparseMatIterator* mat_iterator ) +{ + if( mat_iterator->node->next ) + return mat_iterator->node = mat_iterator->node->next; + else + { + int idx; + for( idx = ++mat_iterator->curidx; idx < mat_iterator->mat->hashsize; idx++ ) + { + CvSparseNode* node = (CvSparseNode*)mat_iterator->mat->hashtable[idx]; + if( node ) + { + mat_iterator->curidx = idx; + return mat_iterator->node = node; + } + } + return NULL; + } +} + + +#define CV_MAX_ARR 10 + +/** matrix iterator: used for n-ary operations on dense arrays */ +typedef struct CvNArrayIterator +{ + int count; /**< number of arrays */ + int dims; /**< number of dimensions to iterate */ + CvSize size; /**< maximal common linear size: { width = size, height = 1 } */ + uchar* ptr[CV_MAX_ARR]; /**< pointers to the array slices */ + int stack[CV_MAX_DIM]; /**< for internal use */ + CvMatND* hdr[CV_MAX_ARR]; /**< pointers to the headers of the + matrices that are processed */ +} +CvNArrayIterator; + +#define CV_NO_DEPTH_CHECK 1 +#define CV_NO_CN_CHECK 2 +#define CV_NO_SIZE_CHECK 4 + +/** initializes iterator that traverses through several arrays simultaneously + (the function together with cvNextArraySlice is used for + N-ari element-wise operations) */ +CVAPI(int) cvInitNArrayIterator( int count, CvArr** arrs, + const CvArr* mask, CvMatND* stubs, + CvNArrayIterator* array_iterator, + int flags CV_DEFAULT(0) ); + +/** returns zero value if iteration is finished, non-zero (slice length) otherwise */ +CVAPI(int) cvNextNArraySlice( CvNArrayIterator* array_iterator ); + + +/** @brief Returns type of array elements. + +The function returns type of the array elements. In the case of IplImage the type is converted to +CvMat-like representation. For example, if the image has been created as: +@code + IplImage* img = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 3); +@endcode +The code cvGetElemType(img) will return CV_8UC3. +@param arr Input array + */ +CVAPI(int) cvGetElemType( const CvArr* arr ); + +/** @brief Return number of array dimensions + +The function returns the array dimensionality and the array of dimension sizes. In the case of +IplImage or CvMat it always returns 2 regardless of number of image/matrix rows. For example, the +following code calculates total number of array elements: +@code + int sizes[CV_MAX_DIM]; + int i, total = 1; + int dims = cvGetDims(arr, size); + for(i = 0; i < dims; i++ ) + total *= sizes[i]; +@endcode +@param arr Input array +@param sizes Optional output vector of the array dimension sizes. For 2d arrays the number of rows +(height) goes first, number of columns (width) next. + */ +CVAPI(int) cvGetDims( const CvArr* arr, int* sizes CV_DEFAULT(NULL) ); + + +/** @brief Returns array size along the specified dimension. + +@param arr Input array +@param index Zero-based dimension index (for matrices 0 means number of rows, 1 means number of +columns; for images 0 means height, 1 means width) + */ +CVAPI(int) cvGetDimSize( const CvArr* arr, int index ); + + +/** @brief Return pointer to a particular array element. + +The functions return a pointer to a specific array element. Number of array dimension should match +to the number of indices passed to the function except for cvPtr1D function that can be used for +sequential access to 1D, 2D or nD dense arrays. + +The functions can be used for sparse arrays as well - if the requested node does not exist they +create it and set it to zero. + +All these as well as other functions accessing array elements ( cvGetND , cvGetRealND , cvSet +, cvSetND , cvSetRealND ) raise an error in case if the element index is out of range. +@param arr Input array +@param idx0 The first zero-based component of the element index +@param type Optional output parameter: type of matrix elements + */ +CVAPI(uchar*) cvPtr1D( const CvArr* arr, int idx0, int* type CV_DEFAULT(NULL)); +/** @overload */ +CVAPI(uchar*) cvPtr2D( const CvArr* arr, int idx0, int idx1, int* type CV_DEFAULT(NULL) ); +/** @overload */ +CVAPI(uchar*) cvPtr3D( const CvArr* arr, int idx0, int idx1, int idx2, + int* type CV_DEFAULT(NULL)); +/** @overload +@param arr Input array +@param idx Array of the element indices +@param type Optional output parameter: type of matrix elements +@param create_node Optional input parameter for sparse matrices. Non-zero value of the parameter +means that the requested element is created if it does not exist already. +@param precalc_hashval Optional input parameter for sparse matrices. If the pointer is not NULL, +the function does not recalculate the node hash value, but takes it from the specified location. +It is useful for speeding up pair-wise operations (TODO: provide an example) +*/ +CVAPI(uchar*) cvPtrND( const CvArr* arr, const int* idx, int* type CV_DEFAULT(NULL), + int create_node CV_DEFAULT(1), + unsigned* precalc_hashval CV_DEFAULT(NULL)); + +/** @brief Return a specific array element. + +The functions return a specific array element. In the case of a sparse array the functions return 0 +if the requested node does not exist (no new node is created by the functions). +@param arr Input array +@param idx0 The first zero-based component of the element index + */ +CVAPI(CvScalar) cvGet1D( const CvArr* arr, int idx0 ); +/** @overload */ +CVAPI(CvScalar) cvGet2D( const CvArr* arr, int idx0, int idx1 ); +/** @overload */ +CVAPI(CvScalar) cvGet3D( const CvArr* arr, int idx0, int idx1, int idx2 ); +/** @overload +@param arr Input array +@param idx Array of the element indices +*/ +CVAPI(CvScalar) cvGetND( const CvArr* arr, const int* idx ); + +/** @brief Return a specific element of single-channel 1D, 2D, 3D or nD array. + +Returns a specific element of a single-channel array. If the array has multiple channels, a runtime +error is raised. Note that Get?D functions can be used safely for both single-channel and +multiple-channel arrays though they are a bit slower. + +In the case of a sparse array the functions return 0 if the requested node does not exist (no new +node is created by the functions). +@param arr Input array. Must have a single channel. +@param idx0 The first zero-based component of the element index + */ +CVAPI(double) cvGetReal1D( const CvArr* arr, int idx0 ); +/** @overload */ +CVAPI(double) cvGetReal2D( const CvArr* arr, int idx0, int idx1 ); +/** @overload */ +CVAPI(double) cvGetReal3D( const CvArr* arr, int idx0, int idx1, int idx2 ); +/** @overload +@param arr Input array. Must have a single channel. +@param idx Array of the element indices +*/ +CVAPI(double) cvGetRealND( const CvArr* arr, const int* idx ); + +/** @brief Change the particular array element. + +The functions assign the new value to a particular array element. In the case of a sparse array the +functions create the node if it does not exist yet. +@param arr Input array +@param idx0 The first zero-based component of the element index +@param value The assigned value + */ +CVAPI(void) cvSet1D( CvArr* arr, int idx0, CvScalar value ); +/** @overload */ +CVAPI(void) cvSet2D( CvArr* arr, int idx0, int idx1, CvScalar value ); +/** @overload */ +CVAPI(void) cvSet3D( CvArr* arr, int idx0, int idx1, int idx2, CvScalar value ); +/** @overload +@param arr Input array +@param idx Array of the element indices +@param value The assigned value +*/ +CVAPI(void) cvSetND( CvArr* arr, const int* idx, CvScalar value ); + +/** @brief Change a specific array element. + +The functions assign a new value to a specific element of a single-channel array. If the array has +multiple channels, a runtime error is raised. Note that the Set\*D function can be used safely for +both single-channel and multiple-channel arrays, though they are a bit slower. + +In the case of a sparse array the functions create the node if it does not yet exist. +@param arr Input array +@param idx0 The first zero-based component of the element index +@param value The assigned value + */ +CVAPI(void) cvSetReal1D( CvArr* arr, int idx0, double value ); +/** @overload */ +CVAPI(void) cvSetReal2D( CvArr* arr, int idx0, int idx1, double value ); +/** @overload */ +CVAPI(void) cvSetReal3D( CvArr* arr, int idx0, + int idx1, int idx2, double value ); +/** @overload +@param arr Input array +@param idx Array of the element indices +@param value The assigned value +*/ +CVAPI(void) cvSetRealND( CvArr* arr, const int* idx, double value ); + +/** clears element of ND dense array, + in case of sparse arrays it deletes the specified node */ +CVAPI(void) cvClearND( CvArr* arr, const int* idx ); + +/** @brief Returns matrix header for arbitrary array. + +The function returns a matrix header for the input array that can be a matrix - CvMat, an image - +IplImage, or a multi-dimensional dense array - CvMatND (the third option is allowed only if +allowND != 0) . In the case of matrix the function simply returns the input pointer. In the case of +IplImage\* or CvMatND it initializes the header structure with parameters of the current image ROI +and returns &header. Because COI is not supported by CvMat, it is returned separately. + +The function provides an easy way to handle both types of arrays - IplImage and CvMat using the same +code. Input array must have non-zero data pointer, otherwise the function will report an error. + +@note If the input array is IplImage with planar data layout and COI set, the function returns the +pointer to the selected plane and COI == 0. This feature allows user to process IplImage structures +with planar data layout, even though OpenCV does not support such images. +@param arr Input array +@param header Pointer to CvMat structure used as a temporary buffer +@param coi Optional output parameter for storing COI +@param allowND If non-zero, the function accepts multi-dimensional dense arrays (CvMatND\*) and +returns 2D matrix (if CvMatND has two dimensions) or 1D matrix (when CvMatND has 1 dimension or +more than 2 dimensions). The CvMatND array must be continuous. +@sa cvGetImage, cvarrToMat. + */ +CVAPI(CvMat*) cvGetMat( const CvArr* arr, CvMat* header, + int* coi CV_DEFAULT(NULL), + int allowND CV_DEFAULT(0)); + +/** @brief Returns image header for arbitrary array. + +The function returns the image header for the input array that can be a matrix (CvMat) or image +(IplImage). In the case of an image the function simply returns the input pointer. In the case of +CvMat it initializes an image_header structure with the parameters of the input matrix. Note that +if we transform IplImage to CvMat using cvGetMat and then transform CvMat back to IplImage using +this function, we will get different headers if the ROI is set in the original image. +@param arr Input array +@param image_header Pointer to IplImage structure used as a temporary buffer + */ +CVAPI(IplImage*) cvGetImage( const CvArr* arr, IplImage* image_header ); + + +/** @brief Changes the shape of a multi-dimensional array without copying the data. + +The function is an advanced version of cvReshape that can work with multi-dimensional arrays as +well (though it can work with ordinary images and matrices) and change the number of dimensions. + +Below are the two samples from the cvReshape description rewritten using cvReshapeMatND: +@code + IplImage* color_img = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U, 3); + IplImage gray_img_hdr, *gray_img; + gray_img = (IplImage*)cvReshapeMatND(color_img, sizeof(gray_img_hdr), &gray_img_hdr, 1, 0, 0); + ... + int size[] = { 2, 2, 2 }; + CvMatND* mat = cvCreateMatND(3, size, CV_32F); + CvMat row_header, *row; + row = (CvMat*)cvReshapeMatND(mat, sizeof(row_header), &row_header, 0, 1, 0); +@endcode +In C, the header file for this function includes a convenient macro cvReshapeND that does away with +the sizeof_header parameter. So, the lines containing the call to cvReshapeMatND in the examples +may be replaced as follow: +@code + gray_img = (IplImage*)cvReshapeND(color_img, &gray_img_hdr, 1, 0, 0); + ... + row = (CvMat*)cvReshapeND(mat, &row_header, 0, 1, 0); +@endcode +@param arr Input array +@param sizeof_header Size of output header to distinguish between IplImage, CvMat and CvMatND +output headers +@param header Output header to be filled +@param new_cn New number of channels. new_cn = 0 means that the number of channels remains +unchanged. +@param new_dims New number of dimensions. new_dims = 0 means that the number of dimensions +remains the same. +@param new_sizes Array of new dimension sizes. Only new_dims-1 values are used, because the +total number of elements must remain the same. Thus, if new_dims = 1, new_sizes array is not +used. + */ +CVAPI(CvArr*) cvReshapeMatND( const CvArr* arr, + int sizeof_header, CvArr* header, + int new_cn, int new_dims, int* new_sizes ); + +#define cvReshapeND( arr, header, new_cn, new_dims, new_sizes ) \ + cvReshapeMatND( (arr), sizeof(*(header)), (header), \ + (new_cn), (new_dims), (new_sizes)) + +/** @brief Changes shape of matrix/image without copying data. + +The function initializes the CvMat header so that it points to the same data as the original array +but has a different shape - different number of channels, different number of rows, or both. + +The following example code creates one image buffer and two image headers, the first is for a +320x240x3 image and the second is for a 960x240x1 image: +@code + IplImage* color_img = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U, 3); + CvMat gray_mat_hdr; + IplImage gray_img_hdr, *gray_img; + cvReshape(color_img, &gray_mat_hdr, 1); + gray_img = cvGetImage(&gray_mat_hdr, &gray_img_hdr); +@endcode +And the next example converts a 3x3 matrix to a single 1x9 vector: +@code + CvMat* mat = cvCreateMat(3, 3, CV_32F); + CvMat row_header, *row; + row = cvReshape(mat, &row_header, 0, 1); +@endcode +@param arr Input array +@param header Output header to be filled +@param new_cn New number of channels. 'new_cn = 0' means that the number of channels remains +unchanged. +@param new_rows New number of rows. 'new_rows = 0' means that the number of rows remains +unchanged unless it needs to be changed according to new_cn value. +*/ +CVAPI(CvMat*) cvReshape( const CvArr* arr, CvMat* header, + int new_cn, int new_rows CV_DEFAULT(0) ); + +/** Repeats source 2d array several times in both horizontal and + vertical direction to fill destination array */ +CVAPI(void) cvRepeat( const CvArr* src, CvArr* dst ); + +/** @brief Allocates array data + +The function allocates image, matrix or multi-dimensional dense array data. Note that in the case of +matrix types OpenCV allocation functions are used. In the case of IplImage they are used unless +CV_TURN_ON_IPL_COMPATIBILITY() has been called before. In the latter case IPL functions are used +to allocate the data. +@param arr Array header + */ +CVAPI(void) cvCreateData( CvArr* arr ); + +/** @brief Releases array data. + +The function releases the array data. In the case of CvMat or CvMatND it simply calls +cvDecRefData(), that is the function can not deallocate external data. See also the note to +cvCreateData . +@param arr Array header + */ +CVAPI(void) cvReleaseData( CvArr* arr ); + +/** @brief Assigns user data to the array header. + +The function assigns user data to the array header. Header should be initialized before using +cvCreateMatHeader, cvCreateImageHeader, cvCreateMatNDHeader, cvInitMatHeader, +cvInitImageHeader or cvInitMatNDHeader. +@param arr Array header +@param data User data +@param step Full row length in bytes + */ +CVAPI(void) cvSetData( CvArr* arr, void* data, int step ); + +/** @brief Retrieves low-level information about the array. + +The function fills output variables with low-level information about the array data. All output + +parameters are optional, so some of the pointers may be set to NULL. If the array is IplImage with +ROI set, the parameters of ROI are returned. + +The following example shows how to get access to array elements. It computes absolute values of the +array elements : +@code + float* data; + int step; + CvSize size; + + cvGetRawData(array, (uchar**)&data, &step, &size); + step /= sizeof(data[0]); + + for(int y = 0; y < size.height; y++, data += step ) + for(int x = 0; x < size.width; x++ ) + data[x] = (float)fabs(data[x]); +@endcode +@param arr Array header +@param data Output pointer to the whole image origin or ROI origin if ROI is set +@param step Output full row length in bytes +@param roi_size Output ROI size + */ +CVAPI(void) cvGetRawData( const CvArr* arr, uchar** data, + int* step CV_DEFAULT(NULL), + CvSize* roi_size CV_DEFAULT(NULL)); + +/** @brief Returns size of matrix or image ROI. + +The function returns number of rows (CvSize::height) and number of columns (CvSize::width) of the +input matrix or image. In the case of image the size of ROI is returned. +@param arr array header + */ +CVAPI(CvSize) cvGetSize( const CvArr* arr ); + +/** @brief Copies one array to another. + +The function copies selected elements from an input array to an output array: + +\f[\texttt{dst} (I)= \texttt{src} (I) \quad \text{if} \quad \texttt{mask} (I) \ne 0.\f] + +If any of the passed arrays is of IplImage type, then its ROI and COI fields are used. Both arrays +must have the same type, the same number of dimensions, and the same size. The function can also +copy sparse arrays (mask is not supported in this case). +@param src The source array +@param dst The destination array +@param mask Operation mask, 8-bit single channel array; specifies elements of the destination array +to be changed + */ +CVAPI(void) cvCopy( const CvArr* src, CvArr* dst, + const CvArr* mask CV_DEFAULT(NULL) ); + +/** @brief Sets every element of an array to a given value. + +The function copies the scalar value to every selected element of the destination array: +\f[\texttt{arr} (I)= \texttt{value} \quad \text{if} \quad \texttt{mask} (I) \ne 0\f] +If array arr is of IplImage type, then is ROI used, but COI must not be set. +@param arr The destination array +@param value Fill value +@param mask Operation mask, 8-bit single channel array; specifies elements of the destination +array to be changed + */ +CVAPI(void) cvSet( CvArr* arr, CvScalar value, + const CvArr* mask CV_DEFAULT(NULL) ); + +/** @brief Clears the array. + +The function clears the array. In the case of dense arrays (CvMat, CvMatND or IplImage), +cvZero(array) is equivalent to cvSet(array,cvScalarAll(0),0). In the case of sparse arrays all the +elements are removed. +@param arr Array to be cleared + */ +CVAPI(void) cvSetZero( CvArr* arr ); +#define cvZero cvSetZero + + +/** Splits a multi-channel array into the set of single-channel arrays or + extracts particular [color] plane */ +CVAPI(void) cvSplit( const CvArr* src, CvArr* dst0, CvArr* dst1, + CvArr* dst2, CvArr* dst3 ); + +/** Merges a set of single-channel arrays into the single multi-channel array + or inserts one particular [color] plane to the array */ +CVAPI(void) cvMerge( const CvArr* src0, const CvArr* src1, + const CvArr* src2, const CvArr* src3, + CvArr* dst ); + +/** Copies several channels from input arrays to + certain channels of output arrays */ +CVAPI(void) cvMixChannels( const CvArr** src, int src_count, + CvArr** dst, int dst_count, + const int* from_to, int pair_count ); + +/** @brief Converts one array to another with optional linear transformation. + +The function has several different purposes, and thus has several different names. It copies one +array to another with optional scaling, which is performed first, and/or optional type conversion, +performed after: + +\f[\texttt{dst} (I) = \texttt{scale} \texttt{src} (I) + ( \texttt{shift} _0, \texttt{shift} _1,...)\f] + +All the channels of multi-channel arrays are processed independently. + +The type of conversion is done with rounding and saturation, that is if the result of scaling + +conversion can not be represented exactly by a value of the destination array element type, it is +set to the nearest representable value on the real axis. +@param src Source array +@param dst Destination array +@param scale Scale factor +@param shift Value added to the scaled source array elements + */ +CVAPI(void) cvConvertScale( const CvArr* src, CvArr* dst, + double scale CV_DEFAULT(1), + double shift CV_DEFAULT(0) ); +#define cvCvtScale cvConvertScale +#define cvScale cvConvertScale +#define cvConvert( src, dst ) cvConvertScale( (src), (dst), 1, 0 ) + + +/** Performs linear transformation on every source array element, + stores absolute value of the result: + dst(x,y,c) = abs(scale*src(x,y,c)+shift). + destination array must have 8u type. + In other cases one may use cvConvertScale + cvAbsDiffS */ +CVAPI(void) cvConvertScaleAbs( const CvArr* src, CvArr* dst, + double scale CV_DEFAULT(1), + double shift CV_DEFAULT(0) ); +#define cvCvtScaleAbs cvConvertScaleAbs + + +/** checks termination criteria validity and + sets eps to default_eps (if it is not set), + max_iter to default_max_iters (if it is not set) +*/ +CVAPI(CvTermCriteria) cvCheckTermCriteria( CvTermCriteria criteria, + double default_eps, + int default_max_iters ); + +/****************************************************************************************\ +* Arithmetic, logic and comparison operations * +\****************************************************************************************/ + +/** dst(mask) = src1(mask) + src2(mask) */ +CVAPI(void) cvAdd( const CvArr* src1, const CvArr* src2, CvArr* dst, + const CvArr* mask CV_DEFAULT(NULL)); + +/** dst(mask) = src(mask) + value */ +CVAPI(void) cvAddS( const CvArr* src, CvScalar value, CvArr* dst, + const CvArr* mask CV_DEFAULT(NULL)); + +/** dst(mask) = src1(mask) - src2(mask) */ +CVAPI(void) cvSub( const CvArr* src1, const CvArr* src2, CvArr* dst, + const CvArr* mask CV_DEFAULT(NULL)); + +/** dst(mask) = src(mask) - value = src(mask) + (-value) */ +CV_INLINE void cvSubS( const CvArr* src, CvScalar value, CvArr* dst, + const CvArr* mask CV_DEFAULT(NULL)) +{ + cvAddS( src, cvScalar( -value.val[0], -value.val[1], -value.val[2], -value.val[3]), + dst, mask ); +} + +/** dst(mask) = value - src(mask) */ +CVAPI(void) cvSubRS( const CvArr* src, CvScalar value, CvArr* dst, + const CvArr* mask CV_DEFAULT(NULL)); + +/** dst(idx) = src1(idx) * src2(idx) * scale + (scaled element-wise multiplication of 2 arrays) */ +CVAPI(void) cvMul( const CvArr* src1, const CvArr* src2, + CvArr* dst, double scale CV_DEFAULT(1) ); + +/** element-wise division/inversion with scaling: + dst(idx) = src1(idx) * scale / src2(idx) + or dst(idx) = scale / src2(idx) if src1 == 0 */ +CVAPI(void) cvDiv( const CvArr* src1, const CvArr* src2, + CvArr* dst, double scale CV_DEFAULT(1)); + +/** dst = src1 * scale + src2 */ +CVAPI(void) cvScaleAdd( const CvArr* src1, CvScalar scale, + const CvArr* src2, CvArr* dst ); +#define cvAXPY( A, real_scalar, B, C ) cvScaleAdd(A, cvRealScalar(real_scalar), B, C) + +/** dst = src1 * alpha + src2 * beta + gamma */ +CVAPI(void) cvAddWeighted( const CvArr* src1, double alpha, + const CvArr* src2, double beta, + double gamma, CvArr* dst ); + +/** @brief Calculates the dot product of two arrays in Euclidean metrics. + +The function calculates and returns the Euclidean dot product of two arrays. + +\f[src1 \bullet src2 = \sum _I ( \texttt{src1} (I) \texttt{src2} (I))\f] + +In the case of multiple channel arrays, the results for all channels are accumulated. In particular, +cvDotProduct(a,a) where a is a complex vector, will return \f$||\texttt{a}||^2\f$. The function can +process multi-dimensional arrays, row by row, layer by layer, and so on. +@param src1 The first source array +@param src2 The second source array + */ +CVAPI(double) cvDotProduct( const CvArr* src1, const CvArr* src2 ); + +/** dst(idx) = src1(idx) & src2(idx) */ +CVAPI(void) cvAnd( const CvArr* src1, const CvArr* src2, + CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); + +/** dst(idx) = src(idx) & value */ +CVAPI(void) cvAndS( const CvArr* src, CvScalar value, + CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); + +/** dst(idx) = src1(idx) | src2(idx) */ +CVAPI(void) cvOr( const CvArr* src1, const CvArr* src2, + CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); + +/** dst(idx) = src(idx) | value */ +CVAPI(void) cvOrS( const CvArr* src, CvScalar value, + CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); + +/** dst(idx) = src1(idx) ^ src2(idx) */ +CVAPI(void) cvXor( const CvArr* src1, const CvArr* src2, + CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); + +/** dst(idx) = src(idx) ^ value */ +CVAPI(void) cvXorS( const CvArr* src, CvScalar value, + CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); + +/** dst(idx) = ~src(idx) */ +CVAPI(void) cvNot( const CvArr* src, CvArr* dst ); + +/** dst(idx) = lower(idx) <= src(idx) < upper(idx) */ +CVAPI(void) cvInRange( const CvArr* src, const CvArr* lower, + const CvArr* upper, CvArr* dst ); + +/** dst(idx) = lower <= src(idx) < upper */ +CVAPI(void) cvInRangeS( const CvArr* src, CvScalar lower, + CvScalar upper, CvArr* dst ); + +#define CV_CMP_EQ 0 +#define CV_CMP_GT 1 +#define CV_CMP_GE 2 +#define CV_CMP_LT 3 +#define CV_CMP_LE 4 +#define CV_CMP_NE 5 + +/** The comparison operation support single-channel arrays only. + Destination image should be 8uC1 or 8sC1 */ + +/** dst(idx) = src1(idx) _cmp_op_ src2(idx) */ +CVAPI(void) cvCmp( const CvArr* src1, const CvArr* src2, CvArr* dst, int cmp_op ); + +/** dst(idx) = src1(idx) _cmp_op_ value */ +CVAPI(void) cvCmpS( const CvArr* src, double value, CvArr* dst, int cmp_op ); + +/** dst(idx) = min(src1(idx),src2(idx)) */ +CVAPI(void) cvMin( const CvArr* src1, const CvArr* src2, CvArr* dst ); + +/** dst(idx) = max(src1(idx),src2(idx)) */ +CVAPI(void) cvMax( const CvArr* src1, const CvArr* src2, CvArr* dst ); + +/** dst(idx) = min(src(idx),value) */ +CVAPI(void) cvMinS( const CvArr* src, double value, CvArr* dst ); + +/** dst(idx) = max(src(idx),value) */ +CVAPI(void) cvMaxS( const CvArr* src, double value, CvArr* dst ); + +/** dst(x,y,c) = abs(src1(x,y,c) - src2(x,y,c)) */ +CVAPI(void) cvAbsDiff( const CvArr* src1, const CvArr* src2, CvArr* dst ); + +/** dst(x,y,c) = abs(src(x,y,c) - value(c)) */ +CVAPI(void) cvAbsDiffS( const CvArr* src, CvArr* dst, CvScalar value ); +#define cvAbs( src, dst ) cvAbsDiffS( (src), (dst), cvScalarAll(0)) + +/****************************************************************************************\ +* Math operations * +\****************************************************************************************/ + +/** Does cartesian->polar coordinates conversion. + Either of output components (magnitude or angle) is optional */ +CVAPI(void) cvCartToPolar( const CvArr* x, const CvArr* y, + CvArr* magnitude, CvArr* angle CV_DEFAULT(NULL), + int angle_in_degrees CV_DEFAULT(0)); + +/** Does polar->cartesian coordinates conversion. + Either of output components (magnitude or angle) is optional. + If magnitude is missing it is assumed to be all 1's */ +CVAPI(void) cvPolarToCart( const CvArr* magnitude, const CvArr* angle, + CvArr* x, CvArr* y, + int angle_in_degrees CV_DEFAULT(0)); + +/** Does powering: dst(idx) = src(idx)^power */ +CVAPI(void) cvPow( const CvArr* src, CvArr* dst, double power ); + +/** Does exponention: dst(idx) = exp(src(idx)). + Overflow is not handled yet. Underflow is handled. + Maximal relative error is ~7e-6 for single-precision input */ +CVAPI(void) cvExp( const CvArr* src, CvArr* dst ); + +/** Calculates natural logarithms: dst(idx) = log(abs(src(idx))). + Logarithm of 0 gives large negative number(~-700) + Maximal relative error is ~3e-7 for single-precision output +*/ +CVAPI(void) cvLog( const CvArr* src, CvArr* dst ); + +/** Fast arctangent calculation */ +CVAPI(float) cvFastArctan( float y, float x ); + +/** Fast cubic root calculation */ +CVAPI(float) cvCbrt( float value ); + +#define CV_CHECK_RANGE 1 +#define CV_CHECK_QUIET 2 +/** Checks array values for NaNs, Infs or simply for too large numbers + (if CV_CHECK_RANGE is set). If CV_CHECK_QUIET is set, + no runtime errors is raised (function returns zero value in case of "bad" values). + Otherwise cvError is called */ +CVAPI(int) cvCheckArr( const CvArr* arr, int flags CV_DEFAULT(0), + double min_val CV_DEFAULT(0), double max_val CV_DEFAULT(0)); +#define cvCheckArray cvCheckArr + +#define CV_RAND_UNI 0 +#define CV_RAND_NORMAL 1 + +/** @brief Fills an array with random numbers and updates the RNG state. + +The function fills the destination array with uniformly or normally distributed random numbers. +@param rng CvRNG state initialized by cvRNG +@param arr The destination array +@param dist_type Distribution type +> - **CV_RAND_UNI** uniform distribution +> - **CV_RAND_NORMAL** normal or Gaussian distribution +@param param1 The first parameter of the distribution. In the case of a uniform distribution it is +the inclusive lower boundary of the random numbers range. In the case of a normal distribution it +is the mean value of the random numbers. +@param param2 The second parameter of the distribution. In the case of a uniform distribution it +is the exclusive upper boundary of the random numbers range. In the case of a normal distribution +it is the standard deviation of the random numbers. +@sa randu, randn, RNG::fill. + */ +CVAPI(void) cvRandArr( CvRNG* rng, CvArr* arr, int dist_type, + CvScalar param1, CvScalar param2 ); + +CVAPI(void) cvRandShuffle( CvArr* mat, CvRNG* rng, + double iter_factor CV_DEFAULT(1.)); + +#define CV_SORT_EVERY_ROW 0 +#define CV_SORT_EVERY_COLUMN 1 +#define CV_SORT_ASCENDING 0 +#define CV_SORT_DESCENDING 16 + +CVAPI(void) cvSort( const CvArr* src, CvArr* dst CV_DEFAULT(NULL), + CvArr* idxmat CV_DEFAULT(NULL), + int flags CV_DEFAULT(0)); + +/** Finds real roots of a cubic equation */ +CVAPI(int) cvSolveCubic( const CvMat* coeffs, CvMat* roots ); + +/** Finds all real and complex roots of a polynomial equation */ +CVAPI(void) cvSolvePoly(const CvMat* coeffs, CvMat *roots2, + int maxiter CV_DEFAULT(20), int fig CV_DEFAULT(100)); + +/****************************************************************************************\ +* Matrix operations * +\****************************************************************************************/ + +/** @brief Calculates the cross product of two 3D vectors. + +The function calculates the cross product of two 3D vectors: +\f[\texttt{dst} = \texttt{src1} \times \texttt{src2}\f] +or: +\f[\begin{array}{l} \texttt{dst} _1 = \texttt{src1} _2 \texttt{src2} _3 - \texttt{src1} _3 \texttt{src2} _2 \\ \texttt{dst} _2 = \texttt{src1} _3 \texttt{src2} _1 - \texttt{src1} _1 \texttt{src2} _3 \\ \texttt{dst} _3 = \texttt{src1} _1 \texttt{src2} _2 - \texttt{src1} _2 \texttt{src2} _1 \end{array}\f] +@param src1 The first source vector +@param src2 The second source vector +@param dst The destination vector + */ +CVAPI(void) cvCrossProduct( const CvArr* src1, const CvArr* src2, CvArr* dst ); + +/** Matrix transform: dst = A*B + C, C is optional */ +#define cvMatMulAdd( src1, src2, src3, dst ) cvGEMM( (src1), (src2), 1., (src3), 1., (dst), 0 ) +#define cvMatMul( src1, src2, dst ) cvMatMulAdd( (src1), (src2), NULL, (dst)) + +#define CV_GEMM_A_T 1 +#define CV_GEMM_B_T 2 +#define CV_GEMM_C_T 4 +/** Extended matrix transform: + dst = alpha*op(A)*op(B) + beta*op(C), where op(X) is X or X^T */ +CVAPI(void) cvGEMM( const CvArr* src1, const CvArr* src2, double alpha, + const CvArr* src3, double beta, CvArr* dst, + int tABC CV_DEFAULT(0)); +#define cvMatMulAddEx cvGEMM + +/** Transforms each element of source array and stores + resultant vectors in destination array */ +CVAPI(void) cvTransform( const CvArr* src, CvArr* dst, + const CvMat* transmat, + const CvMat* shiftvec CV_DEFAULT(NULL)); +#define cvMatMulAddS cvTransform + +/** Does perspective transform on every element of input array */ +CVAPI(void) cvPerspectiveTransform( const CvArr* src, CvArr* dst, + const CvMat* mat ); + +/** Calculates (A-delta)*(A-delta)^T (order=0) or (A-delta)^T*(A-delta) (order=1) */ +CVAPI(void) cvMulTransposed( const CvArr* src, CvArr* dst, int order, + const CvArr* delta CV_DEFAULT(NULL), + double scale CV_DEFAULT(1.) ); + +/** Transposes matrix. Square matrices can be transposed in-place */ +CVAPI(void) cvTranspose( const CvArr* src, CvArr* dst ); +#define cvT cvTranspose + +/** Completes the symmetric matrix from the lower (LtoR=0) or from the upper (LtoR!=0) part */ +CVAPI(void) cvCompleteSymm( CvMat* matrix, int LtoR CV_DEFAULT(0) ); + +/** Mirror array data around horizontal (flip=0), + vertical (flip=1) or both(flip=-1) axises: + cvFlip(src) flips images vertically and sequences horizontally (inplace) */ +CVAPI(void) cvFlip( const CvArr* src, CvArr* dst CV_DEFAULT(NULL), + int flip_mode CV_DEFAULT(0)); +#define cvMirror cvFlip + + +#define CV_SVD_MODIFY_A 1 +#define CV_SVD_U_T 2 +#define CV_SVD_V_T 4 + +/** Performs Singular Value Decomposition of a matrix */ +CVAPI(void) cvSVD( CvArr* A, CvArr* W, CvArr* U CV_DEFAULT(NULL), + CvArr* V CV_DEFAULT(NULL), int flags CV_DEFAULT(0)); + +/** Performs Singular Value Back Substitution (solves A*X = B): + flags must be the same as in cvSVD */ +CVAPI(void) cvSVBkSb( const CvArr* W, const CvArr* U, + const CvArr* V, const CvArr* B, + CvArr* X, int flags ); + +#define CV_LU 0 +#define CV_SVD 1 +#define CV_SVD_SYM 2 +#define CV_CHOLESKY 3 +#define CV_QR 4 +#define CV_NORMAL 16 + +/** Inverts matrix */ +CVAPI(double) cvInvert( const CvArr* src, CvArr* dst, + int method CV_DEFAULT(CV_LU)); +#define cvInv cvInvert + +/** Solves linear system (src1)*(dst) = (src2) + (returns 0 if src1 is a singular and CV_LU method is used) */ +CVAPI(int) cvSolve( const CvArr* src1, const CvArr* src2, CvArr* dst, + int method CV_DEFAULT(CV_LU)); + +/** Calculates determinant of input matrix */ +CVAPI(double) cvDet( const CvArr* mat ); + +/** Calculates trace of the matrix (sum of elements on the main diagonal) */ +CVAPI(CvScalar) cvTrace( const CvArr* mat ); + +/** Finds eigen values and vectors of a symmetric matrix */ +CVAPI(void) cvEigenVV( CvArr* mat, CvArr* evects, CvArr* evals, + double eps CV_DEFAULT(0), + int lowindex CV_DEFAULT(-1), + int highindex CV_DEFAULT(-1)); + +///* Finds selected eigen values and vectors of a symmetric matrix */ +//CVAPI(void) cvSelectedEigenVV( CvArr* mat, CvArr* evects, CvArr* evals, +// int lowindex, int highindex ); + +/** Makes an identity matrix (mat_ij = i == j) */ +CVAPI(void) cvSetIdentity( CvArr* mat, CvScalar value CV_DEFAULT(cvRealScalar(1)) ); + +/** Fills matrix with given range of numbers */ +CVAPI(CvArr*) cvRange( CvArr* mat, double start, double end ); + +/** @anchor core_c_CovarFlags +@name Flags for cvCalcCovarMatrix +@see cvCalcCovarMatrix + @{ +*/ + +/** flag for cvCalcCovarMatrix, transpose([v1-avg, v2-avg,...]) * [v1-avg,v2-avg,...] */ +#define CV_COVAR_SCRAMBLED 0 + +/** flag for cvCalcCovarMatrix, [v1-avg, v2-avg,...] * transpose([v1-avg,v2-avg,...]) */ +#define CV_COVAR_NORMAL 1 + +/** flag for cvCalcCovarMatrix, do not calc average (i.e. mean vector) - use the input vector instead + (useful for calculating covariance matrix by parts) */ +#define CV_COVAR_USE_AVG 2 + +/** flag for cvCalcCovarMatrix, scale the covariance matrix coefficients by number of the vectors */ +#define CV_COVAR_SCALE 4 + +/** flag for cvCalcCovarMatrix, all the input vectors are stored in a single matrix, as its rows */ +#define CV_COVAR_ROWS 8 + +/** flag for cvCalcCovarMatrix, all the input vectors are stored in a single matrix, as its columns */ +#define CV_COVAR_COLS 16 + +/** @} */ + +/** Calculates covariation matrix for a set of vectors +@see @ref core_c_CovarFlags "flags" +*/ +CVAPI(void) cvCalcCovarMatrix( const CvArr** vects, int count, + CvArr* cov_mat, CvArr* avg, int flags ); + +#define CV_PCA_DATA_AS_ROW 0 +#define CV_PCA_DATA_AS_COL 1 +#define CV_PCA_USE_AVG 2 +CVAPI(void) cvCalcPCA( const CvArr* data, CvArr* mean, + CvArr* eigenvals, CvArr* eigenvects, int flags ); + +CVAPI(void) cvProjectPCA( const CvArr* data, const CvArr* mean, + const CvArr* eigenvects, CvArr* result ); + +CVAPI(void) cvBackProjectPCA( const CvArr* proj, const CvArr* mean, + const CvArr* eigenvects, CvArr* result ); + +/** Calculates Mahalanobis(weighted) distance */ +CVAPI(double) cvMahalanobis( const CvArr* vec1, const CvArr* vec2, const CvArr* mat ); +#define cvMahalonobis cvMahalanobis + +/****************************************************************************************\ +* Array Statistics * +\****************************************************************************************/ + +/** Finds sum of array elements */ +CVAPI(CvScalar) cvSum( const CvArr* arr ); + +/** Calculates number of non-zero pixels */ +CVAPI(int) cvCountNonZero( const CvArr* arr ); + +/** Calculates mean value of array elements */ +CVAPI(CvScalar) cvAvg( const CvArr* arr, const CvArr* mask CV_DEFAULT(NULL) ); + +/** Calculates mean and standard deviation of pixel values */ +CVAPI(void) cvAvgSdv( const CvArr* arr, CvScalar* mean, CvScalar* std_dev, + const CvArr* mask CV_DEFAULT(NULL) ); + +/** Finds global minimum, maximum and their positions */ +CVAPI(void) cvMinMaxLoc( const CvArr* arr, double* min_val, double* max_val, + CvPoint* min_loc CV_DEFAULT(NULL), + CvPoint* max_loc CV_DEFAULT(NULL), + const CvArr* mask CV_DEFAULT(NULL) ); + +/** @anchor core_c_NormFlags + @name Flags for cvNorm and cvNormalize + @{ +*/ +#define CV_C 1 +#define CV_L1 2 +#define CV_L2 4 +#define CV_NORM_MASK 7 +#define CV_RELATIVE 8 +#define CV_DIFF 16 +#define CV_MINMAX 32 + +#define CV_DIFF_C (CV_DIFF | CV_C) +#define CV_DIFF_L1 (CV_DIFF | CV_L1) +#define CV_DIFF_L2 (CV_DIFF | CV_L2) +#define CV_RELATIVE_C (CV_RELATIVE | CV_C) +#define CV_RELATIVE_L1 (CV_RELATIVE | CV_L1) +#define CV_RELATIVE_L2 (CV_RELATIVE | CV_L2) +/** @} */ + +/** Finds norm, difference norm or relative difference norm for an array (or two arrays) +@see ref core_c_NormFlags "flags" +*/ +CVAPI(double) cvNorm( const CvArr* arr1, const CvArr* arr2 CV_DEFAULT(NULL), + int norm_type CV_DEFAULT(CV_L2), + const CvArr* mask CV_DEFAULT(NULL) ); + +/** @see ref core_c_NormFlags "flags" */ +CVAPI(void) cvNormalize( const CvArr* src, CvArr* dst, + double a CV_DEFAULT(1.), double b CV_DEFAULT(0.), + int norm_type CV_DEFAULT(CV_L2), + const CvArr* mask CV_DEFAULT(NULL) ); + +/** @anchor core_c_ReduceFlags + @name Flags for cvReduce + @{ +*/ +#define CV_REDUCE_SUM 0 +#define CV_REDUCE_AVG 1 +#define CV_REDUCE_MAX 2 +#define CV_REDUCE_MIN 3 +/** @} */ + +/** @see @ref core_c_ReduceFlags "flags" */ +CVAPI(void) cvReduce( const CvArr* src, CvArr* dst, int dim CV_DEFAULT(-1), + int op CV_DEFAULT(CV_REDUCE_SUM) ); + +/****************************************************************************************\ +* Discrete Linear Transforms and Related Functions * +\****************************************************************************************/ + +/** @anchor core_c_DftFlags + @name Flags for cvDFT, cvDCT and cvMulSpectrums + @{ + */ +#define CV_DXT_FORWARD 0 +#define CV_DXT_INVERSE 1 +#define CV_DXT_SCALE 2 /**< divide result by size of array */ +#define CV_DXT_INV_SCALE (CV_DXT_INVERSE + CV_DXT_SCALE) +#define CV_DXT_INVERSE_SCALE CV_DXT_INV_SCALE +#define CV_DXT_ROWS 4 /**< transform each row individually */ +#define CV_DXT_MUL_CONJ 8 /**< conjugate the second argument of cvMulSpectrums */ +/** @} */ + +/** Discrete Fourier Transform: + complex->complex, + real->ccs (forward), + ccs->real (inverse) +@see core_c_DftFlags "flags" +*/ +CVAPI(void) cvDFT( const CvArr* src, CvArr* dst, int flags, + int nonzero_rows CV_DEFAULT(0) ); +#define cvFFT cvDFT + +/** Multiply results of DFTs: DFT(X)*DFT(Y) or DFT(X)*conj(DFT(Y)) +@see core_c_DftFlags "flags" +*/ +CVAPI(void) cvMulSpectrums( const CvArr* src1, const CvArr* src2, + CvArr* dst, int flags ); + +/** Finds optimal DFT vector size >= size0 */ +CVAPI(int) cvGetOptimalDFTSize( int size0 ); + +/** Discrete Cosine Transform +@see core_c_DftFlags "flags" +*/ +CVAPI(void) cvDCT( const CvArr* src, CvArr* dst, int flags ); + +/****************************************************************************************\ +* Dynamic data structures * +\****************************************************************************************/ + +/** Calculates length of sequence slice (with support of negative indices). */ +CVAPI(int) cvSliceLength( CvSlice slice, const CvSeq* seq ); + + +/** Creates new memory storage. + block_size == 0 means that default, + somewhat optimal size, is used (currently, it is 64K) */ +CVAPI(CvMemStorage*) cvCreateMemStorage( int block_size CV_DEFAULT(0)); + + +/** Creates a memory storage that will borrow memory blocks from parent storage */ +CVAPI(CvMemStorage*) cvCreateChildMemStorage( CvMemStorage* parent ); + + +/** Releases memory storage. All the children of a parent must be released before + the parent. A child storage returns all the blocks to parent when it is released */ +CVAPI(void) cvReleaseMemStorage( CvMemStorage** storage ); + + +/** Clears memory storage. This is the only way(!!!) (besides cvRestoreMemStoragePos) + to reuse memory allocated for the storage - cvClearSeq,cvClearSet ... + do not free any memory. + A child storage returns all the blocks to the parent when it is cleared */ +CVAPI(void) cvClearMemStorage( CvMemStorage* storage ); + +/** Remember a storage "free memory" position */ +CVAPI(void) cvSaveMemStoragePos( const CvMemStorage* storage, CvMemStoragePos* pos ); + +/** Restore a storage "free memory" position */ +CVAPI(void) cvRestoreMemStoragePos( CvMemStorage* storage, CvMemStoragePos* pos ); + +/** Allocates continuous buffer of the specified size in the storage */ +CVAPI(void*) cvMemStorageAlloc( CvMemStorage* storage, size_t size ); + +/** Allocates string in memory storage */ +//CVAPI(CvString) cvMemStorageAllocString( CvMemStorage* storage, const char* ptr, +// int len CV_DEFAULT(-1) ); + +/** Creates new empty sequence that will reside in the specified storage */ +CVAPI(CvSeq*) cvCreateSeq( int seq_flags, size_t header_size, + size_t elem_size, CvMemStorage* storage ); + +/** Changes default size (granularity) of sequence blocks. + The default size is ~1Kbyte */ +CVAPI(void) cvSetSeqBlockSize( CvSeq* seq, int delta_elems ); + + +/** Adds new element to the end of sequence. Returns pointer to the element */ +CVAPI(schar*) cvSeqPush( CvSeq* seq, const void* element CV_DEFAULT(NULL)); + + +/** Adds new element to the beginning of sequence. Returns pointer to it */ +CVAPI(schar*) cvSeqPushFront( CvSeq* seq, const void* element CV_DEFAULT(NULL)); + + +/** Removes the last element from sequence and optionally saves it */ +CVAPI(void) cvSeqPop( CvSeq* seq, void* element CV_DEFAULT(NULL)); + + +/** Removes the first element from sequence and optioanally saves it */ +CVAPI(void) cvSeqPopFront( CvSeq* seq, void* element CV_DEFAULT(NULL)); + + +#define CV_FRONT 1 +#define CV_BACK 0 +/** Adds several new elements to the end of sequence */ +CVAPI(void) cvSeqPushMulti( CvSeq* seq, const void* elements, + int count, int in_front CV_DEFAULT(0) ); + +/** Removes several elements from the end of sequence and optionally saves them */ +CVAPI(void) cvSeqPopMulti( CvSeq* seq, void* elements, + int count, int in_front CV_DEFAULT(0) ); + +/** Inserts a new element in the middle of sequence. + cvSeqInsert(seq,0,elem) == cvSeqPushFront(seq,elem) */ +CVAPI(schar*) cvSeqInsert( CvSeq* seq, int before_index, + const void* element CV_DEFAULT(NULL)); + +/** Removes specified sequence element */ +CVAPI(void) cvSeqRemove( CvSeq* seq, int index ); + + +/** Removes all the elements from the sequence. The freed memory + can be reused later only by the same sequence unless cvClearMemStorage + or cvRestoreMemStoragePos is called */ +CVAPI(void) cvClearSeq( CvSeq* seq ); + + +/** Retrieves pointer to specified sequence element. + Negative indices are supported and mean counting from the end + (e.g -1 means the last sequence element) */ +CVAPI(schar*) cvGetSeqElem( const CvSeq* seq, int index ); + +/** Calculates index of the specified sequence element. + Returns -1 if element does not belong to the sequence */ +CVAPI(int) cvSeqElemIdx( const CvSeq* seq, const void* element, + CvSeqBlock** block CV_DEFAULT(NULL) ); + +/** Initializes sequence writer. The new elements will be added to the end of sequence */ +CVAPI(void) cvStartAppendToSeq( CvSeq* seq, CvSeqWriter* writer ); + + +/** Combination of cvCreateSeq and cvStartAppendToSeq */ +CVAPI(void) cvStartWriteSeq( int seq_flags, int header_size, + int elem_size, CvMemStorage* storage, + CvSeqWriter* writer ); + +/** Closes sequence writer, updates sequence header and returns pointer + to the resultant sequence + (which may be useful if the sequence was created using cvStartWriteSeq)) +*/ +CVAPI(CvSeq*) cvEndWriteSeq( CvSeqWriter* writer ); + + +/** Updates sequence header. May be useful to get access to some of previously + written elements via cvGetSeqElem or sequence reader */ +CVAPI(void) cvFlushSeqWriter( CvSeqWriter* writer ); + + +/** Initializes sequence reader. + The sequence can be read in forward or backward direction */ +CVAPI(void) cvStartReadSeq( const CvSeq* seq, CvSeqReader* reader, + int reverse CV_DEFAULT(0) ); + + +/** Returns current sequence reader position (currently observed sequence element) */ +CVAPI(int) cvGetSeqReaderPos( CvSeqReader* reader ); + + +/** Changes sequence reader position. It may seek to an absolute or + to relative to the current position */ +CVAPI(void) cvSetSeqReaderPos( CvSeqReader* reader, int index, + int is_relative CV_DEFAULT(0)); + +/** Copies sequence content to a continuous piece of memory */ +CVAPI(void*) cvCvtSeqToArray( const CvSeq* seq, void* elements, + CvSlice slice CV_DEFAULT(CV_WHOLE_SEQ) ); + +/** Creates sequence header for array. + After that all the operations on sequences that do not alter the content + can be applied to the resultant sequence */ +CVAPI(CvSeq*) cvMakeSeqHeaderForArray( int seq_type, int header_size, + int elem_size, void* elements, int total, + CvSeq* seq, CvSeqBlock* block ); + +/** Extracts sequence slice (with or without copying sequence elements) */ +CVAPI(CvSeq*) cvSeqSlice( const CvSeq* seq, CvSlice slice, + CvMemStorage* storage CV_DEFAULT(NULL), + int copy_data CV_DEFAULT(0)); + +CV_INLINE CvSeq* cvCloneSeq( const CvSeq* seq, CvMemStorage* storage CV_DEFAULT(NULL)) +{ + return cvSeqSlice( seq, CV_WHOLE_SEQ, storage, 1 ); +} + +/** Removes sequence slice */ +CVAPI(void) cvSeqRemoveSlice( CvSeq* seq, CvSlice slice ); + +/** Inserts a sequence or array into another sequence */ +CVAPI(void) cvSeqInsertSlice( CvSeq* seq, int before_index, const CvArr* from_arr ); + +/** a < b ? -1 : a > b ? 1 : 0 */ +typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata ); + +/** Sorts sequence in-place given element comparison function */ +CVAPI(void) cvSeqSort( CvSeq* seq, CvCmpFunc func, void* userdata CV_DEFAULT(NULL) ); + +/** Finds element in a [sorted] sequence */ +CVAPI(schar*) cvSeqSearch( CvSeq* seq, const void* elem, CvCmpFunc func, + int is_sorted, int* elem_idx, + void* userdata CV_DEFAULT(NULL) ); + +/** Reverses order of sequence elements in-place */ +CVAPI(void) cvSeqInvert( CvSeq* seq ); + +/** Splits sequence into one or more equivalence classes using the specified criteria */ +CVAPI(int) cvSeqPartition( const CvSeq* seq, CvMemStorage* storage, + CvSeq** labels, CvCmpFunc is_equal, void* userdata ); + +/************ Internal sequence functions ************/ +CVAPI(void) cvChangeSeqBlock( void* reader, int direction ); +CVAPI(void) cvCreateSeqBlock( CvSeqWriter* writer ); + + +/** Creates a new set */ +CVAPI(CvSet*) cvCreateSet( int set_flags, int header_size, + int elem_size, CvMemStorage* storage ); + +/** Adds new element to the set and returns pointer to it */ +CVAPI(int) cvSetAdd( CvSet* set_header, CvSetElem* elem CV_DEFAULT(NULL), + CvSetElem** inserted_elem CV_DEFAULT(NULL) ); + +/** Fast variant of cvSetAdd */ +CV_INLINE CvSetElem* cvSetNew( CvSet* set_header ) +{ + CvSetElem* elem = set_header->free_elems; + if( elem ) + { + set_header->free_elems = elem->next_free; + elem->flags = elem->flags & CV_SET_ELEM_IDX_MASK; + set_header->active_count++; + } + else + cvSetAdd( set_header, NULL, &elem ); + return elem; +} + +/** Removes set element given its pointer */ +CV_INLINE void cvSetRemoveByPtr( CvSet* set_header, void* elem ) +{ + CvSetElem* _elem = (CvSetElem*)elem; + assert( _elem->flags >= 0 /*&& (elem->flags & CV_SET_ELEM_IDX_MASK) < set_header->total*/ ); + _elem->next_free = set_header->free_elems; + _elem->flags = (_elem->flags & CV_SET_ELEM_IDX_MASK) | CV_SET_ELEM_FREE_FLAG; + set_header->free_elems = _elem; + set_header->active_count--; +} + +/** Removes element from the set by its index */ +CVAPI(void) cvSetRemove( CvSet* set_header, int index ); + +/** Returns a set element by index. If the element doesn't belong to the set, + NULL is returned */ +CV_INLINE CvSetElem* cvGetSetElem( const CvSet* set_header, int idx ) +{ + CvSetElem* elem = (CvSetElem*)(void *)cvGetSeqElem( (CvSeq*)set_header, idx ); + return elem && CV_IS_SET_ELEM( elem ) ? elem : 0; +} + +/** Removes all the elements from the set */ +CVAPI(void) cvClearSet( CvSet* set_header ); + +/** Creates new graph */ +CVAPI(CvGraph*) cvCreateGraph( int graph_flags, int header_size, + int vtx_size, int edge_size, + CvMemStorage* storage ); + +/** Adds new vertex to the graph */ +CVAPI(int) cvGraphAddVtx( CvGraph* graph, const CvGraphVtx* vtx CV_DEFAULT(NULL), + CvGraphVtx** inserted_vtx CV_DEFAULT(NULL) ); + + +/** Removes vertex from the graph together with all incident edges */ +CVAPI(int) cvGraphRemoveVtx( CvGraph* graph, int index ); +CVAPI(int) cvGraphRemoveVtxByPtr( CvGraph* graph, CvGraphVtx* vtx ); + + +/** Link two vertices specified by indices or pointers if they + are not connected or return pointer to already existing edge + connecting the vertices. + Functions return 1 if a new edge was created, 0 otherwise */ +CVAPI(int) cvGraphAddEdge( CvGraph* graph, + int start_idx, int end_idx, + const CvGraphEdge* edge CV_DEFAULT(NULL), + CvGraphEdge** inserted_edge CV_DEFAULT(NULL) ); + +CVAPI(int) cvGraphAddEdgeByPtr( CvGraph* graph, + CvGraphVtx* start_vtx, CvGraphVtx* end_vtx, + const CvGraphEdge* edge CV_DEFAULT(NULL), + CvGraphEdge** inserted_edge CV_DEFAULT(NULL) ); + +/** Remove edge connecting two vertices */ +CVAPI(void) cvGraphRemoveEdge( CvGraph* graph, int start_idx, int end_idx ); +CVAPI(void) cvGraphRemoveEdgeByPtr( CvGraph* graph, CvGraphVtx* start_vtx, + CvGraphVtx* end_vtx ); + +/** Find edge connecting two vertices */ +CVAPI(CvGraphEdge*) cvFindGraphEdge( const CvGraph* graph, int start_idx, int end_idx ); +CVAPI(CvGraphEdge*) cvFindGraphEdgeByPtr( const CvGraph* graph, + const CvGraphVtx* start_vtx, + const CvGraphVtx* end_vtx ); +#define cvGraphFindEdge cvFindGraphEdge +#define cvGraphFindEdgeByPtr cvFindGraphEdgeByPtr + +/** Remove all vertices and edges from the graph */ +CVAPI(void) cvClearGraph( CvGraph* graph ); + + +/** Count number of edges incident to the vertex */ +CVAPI(int) cvGraphVtxDegree( const CvGraph* graph, int vtx_idx ); +CVAPI(int) cvGraphVtxDegreeByPtr( const CvGraph* graph, const CvGraphVtx* vtx ); + + +/** Retrieves graph vertex by given index */ +#define cvGetGraphVtx( graph, idx ) (CvGraphVtx*)cvGetSetElem((CvSet*)(graph), (idx)) + +/** Retrieves index of a graph vertex given its pointer */ +#define cvGraphVtxIdx( graph, vtx ) ((vtx)->flags & CV_SET_ELEM_IDX_MASK) + +/** Retrieves index of a graph edge given its pointer */ +#define cvGraphEdgeIdx( graph, edge ) ((edge)->flags & CV_SET_ELEM_IDX_MASK) + +#define cvGraphGetVtxCount( graph ) ((graph)->active_count) +#define cvGraphGetEdgeCount( graph ) ((graph)->edges->active_count) + +#define CV_GRAPH_VERTEX 1 +#define CV_GRAPH_TREE_EDGE 2 +#define CV_GRAPH_BACK_EDGE 4 +#define CV_GRAPH_FORWARD_EDGE 8 +#define CV_GRAPH_CROSS_EDGE 16 +#define CV_GRAPH_ANY_EDGE 30 +#define CV_GRAPH_NEW_TREE 32 +#define CV_GRAPH_BACKTRACKING 64 +#define CV_GRAPH_OVER -1 + +#define CV_GRAPH_ALL_ITEMS -1 + +/** flags for graph vertices and edges */ +#define CV_GRAPH_ITEM_VISITED_FLAG (1 << 30) +#define CV_IS_GRAPH_VERTEX_VISITED(vtx) \ + (((CvGraphVtx*)(vtx))->flags & CV_GRAPH_ITEM_VISITED_FLAG) +#define CV_IS_GRAPH_EDGE_VISITED(edge) \ + (((CvGraphEdge*)(edge))->flags & CV_GRAPH_ITEM_VISITED_FLAG) +#define CV_GRAPH_SEARCH_TREE_NODE_FLAG (1 << 29) +#define CV_GRAPH_FORWARD_EDGE_FLAG (1 << 28) + +typedef struct CvGraphScanner +{ + CvGraphVtx* vtx; /* current graph vertex (or current edge origin) */ + CvGraphVtx* dst; /* current graph edge destination vertex */ + CvGraphEdge* edge; /* current edge */ + + CvGraph* graph; /* the graph */ + CvSeq* stack; /* the graph vertex stack */ + int index; /* the lower bound of certainly visited vertices */ + int mask; /* event mask */ +} +CvGraphScanner; + +/** Creates new graph scanner. */ +CVAPI(CvGraphScanner*) cvCreateGraphScanner( CvGraph* graph, + CvGraphVtx* vtx CV_DEFAULT(NULL), + int mask CV_DEFAULT(CV_GRAPH_ALL_ITEMS)); + +/** Releases graph scanner. */ +CVAPI(void) cvReleaseGraphScanner( CvGraphScanner** scanner ); + +/** Get next graph element */ +CVAPI(int) cvNextGraphItem( CvGraphScanner* scanner ); + +/** Creates a copy of graph */ +CVAPI(CvGraph*) cvCloneGraph( const CvGraph* graph, CvMemStorage* storage ); + + +/** Does look-up transformation. Elements of the source array + (that should be 8uC1 or 8sC1) are used as indexes in lutarr 256-element table */ +CVAPI(void) cvLUT( const CvArr* src, CvArr* dst, const CvArr* lut ); + + +/******************* Iteration through the sequence tree *****************/ +typedef struct CvTreeNodeIterator +{ + const void* node; + int level; + int max_level; +} +CvTreeNodeIterator; + +CVAPI(void) cvInitTreeNodeIterator( CvTreeNodeIterator* tree_iterator, + const void* first, int max_level ); +CVAPI(void*) cvNextTreeNode( CvTreeNodeIterator* tree_iterator ); +CVAPI(void*) cvPrevTreeNode( CvTreeNodeIterator* tree_iterator ); + +/** Inserts sequence into tree with specified "parent" sequence. + If parent is equal to frame (e.g. the most external contour), + then added contour will have null pointer to parent. */ +CVAPI(void) cvInsertNodeIntoTree( void* node, void* parent, void* frame ); + +/** Removes contour from tree (together with the contour children). */ +CVAPI(void) cvRemoveNodeFromTree( void* node, void* frame ); + +/** Gathers pointers to all the sequences, + accessible from the `first`, to the single sequence */ +CVAPI(CvSeq*) cvTreeToNodeSeq( const void* first, int header_size, + CvMemStorage* storage ); + +/** The function implements the K-means algorithm for clustering an array of sample + vectors in a specified number of classes */ +#define CV_KMEANS_USE_INITIAL_LABELS 1 +CVAPI(int) cvKMeans2( const CvArr* samples, int cluster_count, CvArr* labels, + CvTermCriteria termcrit, int attempts CV_DEFAULT(1), + CvRNG* rng CV_DEFAULT(0), int flags CV_DEFAULT(0), + CvArr* _centers CV_DEFAULT(0), double* compactness CV_DEFAULT(0) ); + +/****************************************************************************************\ +* System functions * +\****************************************************************************************/ + +/** Loads optimized functions from IPP, MKL etc. or switches back to pure C code */ +CVAPI(int) cvUseOptimized( int on_off ); + +typedef IplImage* (CV_STDCALL* Cv_iplCreateImageHeader) + (int,int,int,char*,char*,int,int,int,int,int, + IplROI*,IplImage*,void*,IplTileInfo*); +typedef void (CV_STDCALL* Cv_iplAllocateImageData)(IplImage*,int,int); +typedef void (CV_STDCALL* Cv_iplDeallocate)(IplImage*,int); +typedef IplROI* (CV_STDCALL* Cv_iplCreateROI)(int,int,int,int,int); +typedef IplImage* (CV_STDCALL* Cv_iplCloneImage)(const IplImage*); + +/** @brief Makes OpenCV use IPL functions for allocating IplImage and IplROI structures. + +Normally, the function is not called directly. Instead, a simple macro +CV_TURN_ON_IPL_COMPATIBILITY() is used that calls cvSetIPLAllocators and passes there pointers +to IPL allocation functions. : +@code + ... + CV_TURN_ON_IPL_COMPATIBILITY() + ... +@endcode +@param create_header pointer to a function, creating IPL image header. +@param allocate_data pointer to a function, allocating IPL image data. +@param deallocate pointer to a function, deallocating IPL image. +@param create_roi pointer to a function, creating IPL image ROI (i.e. Region of Interest). +@param clone_image pointer to a function, cloning an IPL image. + */ +CVAPI(void) cvSetIPLAllocators( Cv_iplCreateImageHeader create_header, + Cv_iplAllocateImageData allocate_data, + Cv_iplDeallocate deallocate, + Cv_iplCreateROI create_roi, + Cv_iplCloneImage clone_image ); + +#define CV_TURN_ON_IPL_COMPATIBILITY() \ + cvSetIPLAllocators( iplCreateImageHeader, iplAllocateImage, \ + iplDeallocate, iplCreateROI, iplCloneImage ) + +/****************************************************************************************\ +* Data Persistence * +\****************************************************************************************/ + +#if 0 +/********************************** High-level functions ********************************/ + +/** @brief Opens file storage for reading or writing data. + +The function opens file storage for reading or writing data. In the latter case, a new file is +created or an existing file is rewritten. The type of the read or written file is determined by the +filename extension: .xml for XML, .yml or .yaml for YAML and .json for JSON. + +At the same time, it also supports adding parameters like "example.xml?base64". + +The function returns a pointer to the CvFileStorage structure. +If the file cannot be opened then the function returns NULL. +@param filename Name of the file associated with the storage +@param memstorage Memory storage used for temporary data and for +: storing dynamic structures, such as CvSeq or CvGraph . If it is NULL, a temporary memory + storage is created and used. +@param flags Can be one of the following: +> - **CV_STORAGE_READ** the storage is open for reading +> - **CV_STORAGE_WRITE** the storage is open for writing + (use **CV_STORAGE_WRITE | CV_STORAGE_WRITE_BASE64** to write rawdata in Base64) +@param encoding + */ +CVAPI(CvFileStorage*) cvOpenFileStorage( const char* filename, CvMemStorage* memstorage, + int flags, const char* encoding CV_DEFAULT(NULL) ); + +/** @brief Releases file storage. + +The function closes the file associated with the storage and releases all the temporary structures. +It must be called after all I/O operations with the storage are finished. +@param fs Double pointer to the released file storage + */ +CVAPI(void) cvReleaseFileStorage( CvFileStorage** fs ); + +/** returns attribute value or 0 (NULL) if there is no such attribute */ +CVAPI(const char*) cvAttrValue( const CvAttrList* attr, const char* attr_name ); + +/** @brief Starts writing a new structure. + +The function starts writing a compound structure (collection) that can be a sequence or a map. After +all the structure fields, which can be scalars or structures, are written, cvEndWriteStruct should +be called. The function can be used to group some objects or to implement the write function for a +some user object (see CvTypeInfo). +@param fs File storage +@param name Name of the written structure. The structure can be accessed by this name when the +storage is read. +@param struct_flags A combination one of the following values: +- **CV_NODE_SEQ** the written structure is a sequence (see discussion of CvFileStorage ), + that is, its elements do not have a name. +- **CV_NODE_MAP** the written structure is a map (see discussion of CvFileStorage ), that + is, all its elements have names. +One and only one of the two above flags must be specified +- **CV_NODE_FLOW** the optional flag that makes sense only for YAML streams. It means that + the structure is written as a flow (not as a block), which is more compact. It is + recommended to use this flag for structures or arrays whose elements are all scalars. +@param type_name Optional parameter - the object type name. In + case of XML it is written as a type_id attribute of the structure opening tag. In the case of + YAML it is written after a colon following the structure name (see the example in + CvFileStorage description). In case of JSON it is written as a name/value pair. + Mainly it is used with user objects. When the storage is read, the + encoded type name is used to determine the object type (see CvTypeInfo and cvFindType ). +@param attributes This parameter is not used in the current implementation + */ +CVAPI(void) cvStartWriteStruct( CvFileStorage* fs, const char* name, + int struct_flags, const char* type_name CV_DEFAULT(NULL), + CvAttrList attributes CV_DEFAULT(cvAttrList())); + +/** @brief Finishes writing to a file node collection. +@param fs File storage +@sa cvStartWriteStruct. + */ +CVAPI(void) cvEndWriteStruct( CvFileStorage* fs ); + +/** @brief Writes an integer value. + +The function writes a single integer value (with or without a name) to the file storage. +@param fs File storage +@param name Name of the written value. Should be NULL if and only if the parent structure is a +sequence. +@param value The written value + */ +CVAPI(void) cvWriteInt( CvFileStorage* fs, const char* name, int value ); + +/** @brief Writes a floating-point value. + +The function writes a single floating-point value (with or without a name) to file storage. Special +values are encoded as follows: NaN (Not A Number) as .NaN, infinity as +.Inf or -.Inf. + +The following example shows how to use the low-level writing functions to store custom structures, +such as termination criteria, without registering a new type. : +@code + void write_termcriteria( CvFileStorage* fs, const char* struct_name, + CvTermCriteria* termcrit ) + { + cvStartWriteStruct( fs, struct_name, CV_NODE_MAP, NULL, cvAttrList(0,0)); + cvWriteComment( fs, "termination criteria", 1 ); // just a description + if( termcrit->type & CV_TERMCRIT_ITER ) + cvWriteInteger( fs, "max_iterations", termcrit->max_iter ); + if( termcrit->type & CV_TERMCRIT_EPS ) + cvWriteReal( fs, "accuracy", termcrit->epsilon ); + cvEndWriteStruct( fs ); + } +@endcode +@param fs File storage +@param name Name of the written value. Should be NULL if and only if the parent structure is a +sequence. +@param value The written value +*/ +CVAPI(void) cvWriteReal( CvFileStorage* fs, const char* name, double value ); + +/** @brief Writes a text string. + +The function writes a text string to file storage. +@param fs File storage +@param name Name of the written string . Should be NULL if and only if the parent structure is a +sequence. +@param str The written text string +@param quote If non-zero, the written string is put in quotes, regardless of whether they are +required. Otherwise, if the flag is zero, quotes are used only when they are required (e.g. when +the string starts with a digit or contains spaces). + */ +CVAPI(void) cvWriteString( CvFileStorage* fs, const char* name, + const char* str, int quote CV_DEFAULT(0) ); + +/** @brief Writes a comment. + +The function writes a comment into file storage. The comments are skipped when the storage is read. +@param fs File storage +@param comment The written comment, single-line or multi-line +@param eol_comment If non-zero, the function tries to put the comment at the end of current line. +If the flag is zero, if the comment is multi-line, or if it does not fit at the end of the current +line, the comment starts a new line. + */ +CVAPI(void) cvWriteComment( CvFileStorage* fs, const char* comment, + int eol_comment ); + +/** @brief Writes an object to file storage. + +The function writes an object to file storage. First, the appropriate type info is found using +cvTypeOf. Then, the write method associated with the type info is called. + +Attributes are used to customize the writing procedure. The standard types support the following +attributes (all the dt attributes have the same format as in cvWriteRawData): + +-# CvSeq + - **header_dt** description of user fields of the sequence header that follow CvSeq, or + CvChain (if the sequence is a Freeman chain) or CvContour (if the sequence is a contour or + point sequence) + - **dt** description of the sequence elements. + - **recursive** if the attribute is present and is not equal to "0" or "false", the whole + tree of sequences (contours) is stored. +-# CvGraph + - **header_dt** description of user fields of the graph header that follows CvGraph; + - **vertex_dt** description of user fields of graph vertices + - **edge_dt** description of user fields of graph edges (note that the edge weight is + always written, so there is no need to specify it explicitly) + +Below is the code that creates the YAML file shown in the CvFileStorage description: +@code + #include "cxcore.h" + + int main( int argc, char** argv ) + { + CvMat* mat = cvCreateMat( 3, 3, CV_32F ); + CvFileStorage* fs = cvOpenFileStorage( "example.yml", 0, CV_STORAGE_WRITE ); + + cvSetIdentity( mat ); + cvWrite( fs, "A", mat, cvAttrList(0,0) ); + + cvReleaseFileStorage( &fs ); + cvReleaseMat( &mat ); + return 0; + } +@endcode +@param fs File storage +@param name Name of the written object. Should be NULL if and only if the parent structure is a +sequence. +@param ptr Pointer to the object +@param attributes The attributes of the object. They are specific for each particular type (see +the discussion below). + */ +CVAPI(void) cvWrite( CvFileStorage* fs, const char* name, const void* ptr, + CvAttrList attributes CV_DEFAULT(cvAttrList())); + +/** @brief Starts the next stream. + +The function finishes the currently written stream and starts the next stream. In the case of XML +the file with multiple streams looks like this: +@code{.xml} + + + + + + + ... +@endcode +The YAML file will look like this: +@code{.yaml} + %YAML 1.0 + # stream #1 data + ... + --- + # stream #2 data +@endcode +This is useful for concatenating files or for resuming the writing process. +@param fs File storage + */ +CVAPI(void) cvStartNextStream( CvFileStorage* fs ); + +/** @brief Writes multiple numbers. + +The function writes an array, whose elements consist of single or multiple numbers. The function +call can be replaced with a loop containing a few cvWriteInt and cvWriteReal calls, but a single +call is more efficient. Note that because none of the elements have a name, they should be written +to a sequence rather than a map. +@param fs File storage +@param src Pointer to the written array +@param len Number of the array elements to write +@param dt Specification of each array element, see @ref format_spec "format specification" + */ +CVAPI(void) cvWriteRawData( CvFileStorage* fs, const void* src, + int len, const char* dt ); + +/** @brief Writes multiple numbers in Base64. + +If either CV_STORAGE_WRITE_BASE64 or cv::FileStorage::WRITE_BASE64 is used, +this function will be the same as cvWriteRawData. If neither, the main +difference is that it outputs a sequence in Base64 encoding rather than +in plain text. + +This function can only be used to write a sequence with a type "binary". + +@param fs File storage +@param src Pointer to the written array +@param len Number of the array elements to write +@param dt Specification of each array element, see @ref format_spec "format specification" +*/ +CVAPI(void) cvWriteRawDataBase64( CvFileStorage* fs, const void* src, + int len, const char* dt ); + +/** @brief Returns a unique pointer for a given name. + +The function returns a unique pointer for each particular file node name. This pointer can be then +passed to the cvGetFileNode function that is faster than cvGetFileNodeByName because it compares +text strings by comparing pointers rather than the strings' content. + +Consider the following example where an array of points is encoded as a sequence of 2-entry maps: +@code + points: + - { x: 10, y: 10 } + - { x: 20, y: 20 } + - { x: 30, y: 30 } + # ... +@endcode +Then, it is possible to get hashed "x" and "y" pointers to speed up decoding of the points. : +@code + #include "cxcore.h" + + int main( int argc, char** argv ) + { + CvFileStorage* fs = cvOpenFileStorage( "points.yml", 0, CV_STORAGE_READ ); + CvStringHashNode* x_key = cvGetHashedNode( fs, "x", -1, 1 ); + CvStringHashNode* y_key = cvGetHashedNode( fs, "y", -1, 1 ); + CvFileNode* points = cvGetFileNodeByName( fs, 0, "points" ); + + if( CV_NODE_IS_SEQ(points->tag) ) + { + CvSeq* seq = points->data.seq; + int i, total = seq->total; + CvSeqReader reader; + cvStartReadSeq( seq, &reader, 0 ); + for( i = 0; i < total; i++ ) + { + CvFileNode* pt = (CvFileNode*)reader.ptr; + #if 1 // faster variant + CvFileNode* xnode = cvGetFileNode( fs, pt, x_key, 0 ); + CvFileNode* ynode = cvGetFileNode( fs, pt, y_key, 0 ); + assert( xnode && CV_NODE_IS_INT(xnode->tag) && + ynode && CV_NODE_IS_INT(ynode->tag)); + int x = xnode->data.i; // or x = cvReadInt( xnode, 0 ); + int y = ynode->data.i; // or y = cvReadInt( ynode, 0 ); + #elif 1 // slower variant; does not use x_key & y_key + CvFileNode* xnode = cvGetFileNodeByName( fs, pt, "x" ); + CvFileNode* ynode = cvGetFileNodeByName( fs, pt, "y" ); + assert( xnode && CV_NODE_IS_INT(xnode->tag) && + ynode && CV_NODE_IS_INT(ynode->tag)); + int x = xnode->data.i; // or x = cvReadInt( xnode, 0 ); + int y = ynode->data.i; // or y = cvReadInt( ynode, 0 ); + #else // the slowest yet the easiest to use variant + int x = cvReadIntByName( fs, pt, "x", 0 ); + int y = cvReadIntByName( fs, pt, "y", 0 ); + #endif + CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); + printf(" + } + } + cvReleaseFileStorage( &fs ); + return 0; + } +@endcode +Please note that whatever method of accessing a map you are using, it is still much slower than +using plain sequences; for example, in the above example, it is more efficient to encode the points +as pairs of integers in a single numeric sequence. +@param fs File storage +@param name Literal node name +@param len Length of the name (if it is known apriori), or -1 if it needs to be calculated +@param create_missing Flag that specifies, whether an absent key should be added into the hash table +*/ +CVAPI(CvStringHashNode*) cvGetHashedKey( CvFileStorage* fs, const char* name, + int len CV_DEFAULT(-1), + int create_missing CV_DEFAULT(0)); + +/** @brief Retrieves one of the top-level nodes of the file storage. + +The function returns one of the top-level file nodes. The top-level nodes do not have a name, they +correspond to the streams that are stored one after another in the file storage. If the index is out +of range, the function returns a NULL pointer, so all the top-level nodes can be iterated by +subsequent calls to the function with stream_index=0,1,..., until the NULL pointer is returned. +This function can be used as a base for recursive traversal of the file storage. +@param fs File storage +@param stream_index Zero-based index of the stream. See cvStartNextStream . In most cases, +there is only one stream in the file; however, there can be several. + */ +CVAPI(CvFileNode*) cvGetRootFileNode( const CvFileStorage* fs, + int stream_index CV_DEFAULT(0) ); + +/** @brief Finds a node in a map or file storage. + +The function finds a file node. It is a faster version of cvGetFileNodeByName (see +cvGetHashedKey discussion). Also, the function can insert a new node, if it is not in the map yet. +@param fs File storage +@param map The parent map. If it is NULL, the function searches a top-level node. If both map and +key are NULLs, the function returns the root file node - a map that contains top-level nodes. +@param key Unique pointer to the node name, retrieved with cvGetHashedKey +@param create_missing Flag that specifies whether an absent node should be added to the map + */ +CVAPI(CvFileNode*) cvGetFileNode( CvFileStorage* fs, CvFileNode* map, + const CvStringHashNode* key, + int create_missing CV_DEFAULT(0) ); + +/** @brief Finds a node in a map or file storage. + +The function finds a file node by name. The node is searched either in map or, if the pointer is +NULL, among the top-level file storage nodes. Using this function for maps and cvGetSeqElem (or +sequence reader) for sequences, it is possible to navigate through the file storage. To speed up +multiple queries for a certain key (e.g., in the case of an array of structures) one may use a +combination of cvGetHashedKey and cvGetFileNode. +@param fs File storage +@param map The parent map. If it is NULL, the function searches in all the top-level nodes +(streams), starting with the first one. +@param name The file node name + */ +CVAPI(CvFileNode*) cvGetFileNodeByName( const CvFileStorage* fs, + const CvFileNode* map, + const char* name ); + +/** @brief Retrieves an integer value from a file node. + +The function returns an integer that is represented by the file node. If the file node is NULL, the +default_value is returned (thus, it is convenient to call the function right after cvGetFileNode +without checking for a NULL pointer). If the file node has type CV_NODE_INT, then node-\>data.i is +returned. If the file node has type CV_NODE_REAL, then node-\>data.f is converted to an integer +and returned. Otherwise the error is reported. +@param node File node +@param default_value The value that is returned if node is NULL + */ +CV_INLINE int cvReadInt( const CvFileNode* node, int default_value CV_DEFAULT(0) ) +{ + return !node ? default_value : + CV_NODE_IS_INT(node->tag) ? node->data.i : + CV_NODE_IS_REAL(node->tag) ? cvRound(node->data.f) : 0x7fffffff; +} + +/** @brief Finds a file node and returns its value. + +The function is a simple superposition of cvGetFileNodeByName and cvReadInt. +@param fs File storage +@param map The parent map. If it is NULL, the function searches a top-level node. +@param name The node name +@param default_value The value that is returned if the file node is not found + */ +CV_INLINE int cvReadIntByName( const CvFileStorage* fs, const CvFileNode* map, + const char* name, int default_value CV_DEFAULT(0) ) +{ + return cvReadInt( cvGetFileNodeByName( fs, map, name ), default_value ); +} + +/** @brief Retrieves a floating-point value from a file node. + +The function returns a floating-point value that is represented by the file node. If the file node +is NULL, the default_value is returned (thus, it is convenient to call the function right after +cvGetFileNode without checking for a NULL pointer). If the file node has type CV_NODE_REAL , +then node-\>data.f is returned. If the file node has type CV_NODE_INT , then node-:math:\>data.f +is converted to floating-point and returned. Otherwise the result is not determined. +@param node File node +@param default_value The value that is returned if node is NULL + */ +CV_INLINE double cvReadReal( const CvFileNode* node, double default_value CV_DEFAULT(0.) ) +{ + return !node ? default_value : + CV_NODE_IS_INT(node->tag) ? (double)node->data.i : + CV_NODE_IS_REAL(node->tag) ? node->data.f : 1e300; +} + +/** @brief Finds a file node and returns its value. + +The function is a simple superposition of cvGetFileNodeByName and cvReadReal . +@param fs File storage +@param map The parent map. If it is NULL, the function searches a top-level node. +@param name The node name +@param default_value The value that is returned if the file node is not found + */ +CV_INLINE double cvReadRealByName( const CvFileStorage* fs, const CvFileNode* map, + const char* name, double default_value CV_DEFAULT(0.) ) +{ + return cvReadReal( cvGetFileNodeByName( fs, map, name ), default_value ); +} + +/** @brief Retrieves a text string from a file node. + +The function returns a text string that is represented by the file node. If the file node is NULL, +the default_value is returned (thus, it is convenient to call the function right after +cvGetFileNode without checking for a NULL pointer). If the file node has type CV_NODE_STR , then +node-:math:\>data.str.ptr is returned. Otherwise the result is not determined. +@param node File node +@param default_value The value that is returned if node is NULL + */ +CV_INLINE const char* cvReadString( const CvFileNode* node, + const char* default_value CV_DEFAULT(NULL) ) +{ + return !node ? default_value : CV_NODE_IS_STRING(node->tag) ? node->data.str.ptr : 0; +} + +/** @brief Finds a file node by its name and returns its value. + +The function is a simple superposition of cvGetFileNodeByName and cvReadString . +@param fs File storage +@param map The parent map. If it is NULL, the function searches a top-level node. +@param name The node name +@param default_value The value that is returned if the file node is not found + */ +CV_INLINE const char* cvReadStringByName( const CvFileStorage* fs, const CvFileNode* map, + const char* name, const char* default_value CV_DEFAULT(NULL) ) +{ + return cvReadString( cvGetFileNodeByName( fs, map, name ), default_value ); +} + + +/** @brief Decodes an object and returns a pointer to it. + +The function decodes a user object (creates an object in a native representation from the file +storage subtree) and returns it. The object to be decoded must be an instance of a registered type +that supports the read method (see CvTypeInfo). The type of the object is determined by the type +name that is encoded in the file. If the object is a dynamic structure, it is created either in +memory storage and passed to cvOpenFileStorage or, if a NULL pointer was passed, in temporary +memory storage, which is released when cvReleaseFileStorage is called. Otherwise, if the object is +not a dynamic structure, it is created in a heap and should be released with a specialized function +or by using the generic cvRelease. +@param fs File storage +@param node The root object node +@param attributes Unused parameter + */ +CVAPI(void*) cvRead( CvFileStorage* fs, CvFileNode* node, + CvAttrList* attributes CV_DEFAULT(NULL)); + +/** @brief Finds an object by name and decodes it. + +The function is a simple superposition of cvGetFileNodeByName and cvRead. +@param fs File storage +@param map The parent map. If it is NULL, the function searches a top-level node. +@param name The node name +@param attributes Unused parameter + */ +CV_INLINE void* cvReadByName( CvFileStorage* fs, const CvFileNode* map, + const char* name, CvAttrList* attributes CV_DEFAULT(NULL) ) +{ + return cvRead( fs, cvGetFileNodeByName( fs, map, name ), attributes ); +} + + +/** @brief Initializes the file node sequence reader. + +The function initializes the sequence reader to read data from a file node. The initialized reader +can be then passed to cvReadRawDataSlice. +@param fs File storage +@param src The file node (a sequence) to read numbers from +@param reader Pointer to the sequence reader + */ +CVAPI(void) cvStartReadRawData( const CvFileStorage* fs, const CvFileNode* src, + CvSeqReader* reader ); + +/** @brief Initializes file node sequence reader. + +The function reads one or more elements from the file node, representing a sequence, to a +user-specified array. The total number of read sequence elements is a product of total and the +number of components in each array element. For example, if dt=2if, the function will read total\*3 +sequence elements. As with any sequence, some parts of the file node sequence can be skipped or read +repeatedly by repositioning the reader using cvSetSeqReaderPos. +@param fs File storage +@param reader The sequence reader. Initialize it with cvStartReadRawData . +@param count The number of elements to read +@param dst Pointer to the destination array +@param dt Specification of each array element. It has the same format as in cvWriteRawData . + */ +CVAPI(void) cvReadRawDataSlice( const CvFileStorage* fs, CvSeqReader* reader, + int count, void* dst, const char* dt ); + +/** @brief Reads multiple numbers. + +The function reads elements from a file node that represents a sequence of scalars. +@param fs File storage +@param src The file node (a sequence) to read numbers from +@param dst Pointer to the destination array +@param dt Specification of each array element. It has the same format as in cvWriteRawData . + */ +CVAPI(void) cvReadRawData( const CvFileStorage* fs, const CvFileNode* src, + void* dst, const char* dt ); + +/** @brief Writes a file node to another file storage. + +The function writes a copy of a file node to file storage. Possible applications of the function are +merging several file storages into one and conversion between XML, YAML and JSON formats. +@param fs Destination file storage +@param new_node_name New name of the file node in the destination file storage. To keep the +existing name, use cvcvGetFileNodeName +@param node The written node +@param embed If the written node is a collection and this parameter is not zero, no extra level of +hierarchy is created. Instead, all the elements of node are written into the currently written +structure. Of course, map elements can only be embedded into another map, and sequence elements +can only be embedded into another sequence. + */ +CVAPI(void) cvWriteFileNode( CvFileStorage* fs, const char* new_node_name, + const CvFileNode* node, int embed ); + +/** @brief Returns the name of a file node. + +The function returns the name of a file node or NULL, if the file node does not have a name or if +node is NULL. +@param node File node + */ +CVAPI(const char*) cvGetFileNodeName( const CvFileNode* node ); + +/*********************************** Adding own types ***********************************/ + +/** @brief Registers a new type. + +The function registers a new type, which is described by info . The function creates a copy of the +structure, so the user should delete it after calling the function. +@param info Type info structure + */ +CVAPI(void) cvRegisterType( const CvTypeInfo* info ); + +/** @brief Unregisters the type. + +The function unregisters a type with a specified name. If the name is unknown, it is possible to +locate the type info by an instance of the type using cvTypeOf or by iterating the type list, +starting from cvFirstType, and then calling cvUnregisterType(info-\>typeName). +@param type_name Name of an unregistered type + */ +CVAPI(void) cvUnregisterType( const char* type_name ); + +/** @brief Returns the beginning of a type list. + +The function returns the first type in the list of registered types. Navigation through the list can +be done via the prev and next fields of the CvTypeInfo structure. + */ +CVAPI(CvTypeInfo*) cvFirstType(void); + +/** @brief Finds a type by its name. + +The function finds a registered type by its name. It returns NULL if there is no type with the +specified name. +@param type_name Type name + */ +CVAPI(CvTypeInfo*) cvFindType( const char* type_name ); + +/** @brief Returns the type of an object. + +The function finds the type of a given object. It iterates through the list of registered types and +calls the is_instance function/method for every type info structure with that object until one of +them returns non-zero or until the whole list has been traversed. In the latter case, the function +returns NULL. +@param struct_ptr The object pointer + */ +CVAPI(CvTypeInfo*) cvTypeOf( const void* struct_ptr ); + +#endif + +/** @brief Releases an object. + + The function finds the type of a given object and calls release with the double pointer. + @param struct_ptr Double pointer to the object + */ +CVAPI(void) cvRelease( void** struct_ptr ); + +/** @brief Makes a clone of an object. + +The function finds the type of a given object and calls clone with the passed object. Of course, if +you know the object type, for example, struct_ptr is CvMat\*, it is faster to call the specific +function, like cvCloneMat. +@param struct_ptr The object to clone + */ +CVAPI(void*) cvClone( const void* struct_ptr ); + +/*********************************** Measuring Execution Time ***************************/ + +/** helper functions for RNG initialization and accurate time measurement: + uses internal clock counter on x86 */ +CVAPI(int64) cvGetTickCount( void ); +CVAPI(double) cvGetTickFrequency( void ); + +/*********************************** CPU capabilities ***********************************/ + +CVAPI(int) cvCheckHardwareSupport(int feature); + +/*********************************** Multi-Threading ************************************/ + +/** retrieve/set the number of threads used in OpenMP implementations */ +CVAPI(int) cvGetNumThreads( void ); +CVAPI(void) cvSetNumThreads( int threads CV_DEFAULT(0) ); +/** get index of the thread being executed */ +CVAPI(int) cvGetThreadNum( void ); + + +/********************************** Error Handling **************************************/ + +/** Get current OpenCV error status */ +CVAPI(int) cvGetErrStatus( void ); + +/** Sets error status silently */ +CVAPI(void) cvSetErrStatus( int status ); + +#define CV_ErrModeLeaf 0 /* Print error and exit program */ +#define CV_ErrModeParent 1 /* Print error and continue */ +#define CV_ErrModeSilent 2 /* Don't print and continue */ + +/** Retrieves current error processing mode */ +CVAPI(int) cvGetErrMode( void ); + +/** Sets error processing mode, returns previously used mode */ +CVAPI(int) cvSetErrMode( int mode ); + +/** Sets error status and performs some additional actions (displaying message box, + writing message to stderr, terminating application etc.) + depending on the current error mode */ +CVAPI(void) cvError( int status, const char* func_name, + const char* err_msg, const char* file_name, int line ); + +/** Retrieves textual description of the error given its code */ +CVAPI(const char*) cvErrorStr( int status ); + +/** Retrieves detailed information about the last error occurred */ +CVAPI(int) cvGetErrInfo( const char** errcode_desc, const char** description, + const char** filename, int* line ); + +/** Maps IPP error codes to the counterparts from OpenCV */ +CVAPI(int) cvErrorFromIppStatus( int ipp_status ); + +typedef int (CV_CDECL *CvErrorCallback)( int status, const char* func_name, + const char* err_msg, const char* file_name, int line, void* userdata ); + +/** Assigns a new error-handling function */ +CVAPI(CvErrorCallback) cvRedirectError( CvErrorCallback error_handler, + void* userdata CV_DEFAULT(NULL), + void** prev_userdata CV_DEFAULT(NULL) ); + +/** Output nothing */ +CVAPI(int) cvNulDevReport( int status, const char* func_name, const char* err_msg, + const char* file_name, int line, void* userdata ); + +/** Output to console(fprintf(stderr,...)) */ +CVAPI(int) cvStdErrReport( int status, const char* func_name, const char* err_msg, + const char* file_name, int line, void* userdata ); + +/** Output to MessageBox(WIN32) */ +CVAPI(int) cvGuiBoxReport( int status, const char* func_name, const char* err_msg, + const char* file_name, int line, void* userdata ); + +#define OPENCV_ERROR(status,func,context) \ +cvError((status),(func),(context),__FILE__,__LINE__) + +#define OPENCV_ASSERT(expr,func,context) \ +{if (! (expr)) \ +{OPENCV_ERROR(CV_StsInternal,(func),(context));}} + +#define OPENCV_CALL( Func ) \ +{ \ +Func; \ +} + + +/** CV_FUNCNAME macro defines icvFuncName constant which is used by CV_ERROR macro */ +#ifdef CV_NO_FUNC_NAMES +#define CV_FUNCNAME( Name ) +#define cvFuncName "" +#else +#define CV_FUNCNAME( Name ) \ +static char cvFuncName[] = Name +#endif + + +/** + CV_ERROR macro unconditionally raises error with passed code and message. + After raising error, control will be transferred to the exit label. + */ +#define CV_ERROR( Code, Msg ) \ +{ \ + cvError( (Code), cvFuncName, Msg, __FILE__, __LINE__ ); \ + __CV_EXIT__; \ +} + +/** + CV_CHECK macro checks error status after CV (or IPL) + function call. If error detected, control will be transferred to the exit + label. + */ +#define CV_CHECK() \ +{ \ + if( cvGetErrStatus() < 0 ) \ + CV_ERROR( CV_StsBackTrace, "Inner function failed." ); \ +} + + +/** + CV_CALL macro calls CV (or IPL) function, checks error status and + signals a error if the function failed. Useful in "parent node" + error processing mode + */ +#define CV_CALL( Func ) \ +{ \ + Func; \ + CV_CHECK(); \ +} + + +/** Runtime assertion macro */ +#define CV_ASSERT( Condition ) \ +{ \ + if( !(Condition) ) \ + CV_ERROR( CV_StsInternal, "Assertion: " #Condition " failed" ); \ +} + +#define __CV_BEGIN__ { +#define __CV_END__ goto exit; exit: ; } +#define __CV_EXIT__ goto exit + +/** @} core_c */ + +#ifdef __cplusplus +} // extern "C" +#endif + +#ifdef __cplusplus + +#include "opencv2/core/utility.hpp" + +namespace cv +{ + +//! @addtogroup core_c_glue +//! @{ + +/////////////////////////////////////////// glue /////////////////////////////////////////// + +//! converts array (CvMat or IplImage) to cv::Mat +CV_EXPORTS Mat cvarrToMat(const CvArr* arr, bool copyData=false, + bool allowND=true, int coiMode=0, + AutoBuffer* buf=0); + +static inline Mat cvarrToMatND(const CvArr* arr, bool copyData=false, int coiMode=0) +{ + return cvarrToMat(arr, copyData, true, coiMode); +} + + +//! extracts Channel of Interest from CvMat or IplImage and makes cv::Mat out of it. +CV_EXPORTS void extractImageCOI(const CvArr* arr, OutputArray coiimg, int coi=-1); +//! inserts single-channel cv::Mat into a multi-channel CvMat or IplImage +CV_EXPORTS void insertImageCOI(InputArray coiimg, CvArr* arr, int coi=-1); + + + +////// specialized implementations of DefaultDeleter::operator() for classic OpenCV types ////// + +template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvMat* obj) const; }; +template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(IplImage* obj) const; }; +template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvMatND* obj) const; }; +template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvSparseMat* obj) const; }; +template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvMemStorage* obj) const; }; + +////////////// convenient wrappers for operating old-style dynamic structures ////////////// + +template class SeqIterator; + +typedef Ptr MemStorage; + +/*! + Template Sequence Class derived from CvSeq + + The class provides more convenient access to sequence elements, + STL-style operations and iterators. + + \note The class is targeted for simple data types, + i.e. no constructors or destructors + are called for the sequence elements. +*/ +template class Seq +{ +public: + typedef SeqIterator<_Tp> iterator; + typedef SeqIterator<_Tp> const_iterator; + + //! the default constructor + Seq(); + //! the constructor for wrapping CvSeq structure. The real element type in CvSeq should match _Tp. + Seq(const CvSeq* seq); + //! creates the empty sequence that resides in the specified storage + Seq(MemStorage& storage, int headerSize = sizeof(CvSeq)); + //! returns read-write reference to the specified element + _Tp& operator [](int idx); + //! returns read-only reference to the specified element + const _Tp& operator[](int idx) const; + //! returns iterator pointing to the beginning of the sequence + SeqIterator<_Tp> begin() const; + //! returns iterator pointing to the element following the last sequence element + SeqIterator<_Tp> end() const; + //! returns the number of elements in the sequence + size_t size() const; + //! returns the type of sequence elements (CV_8UC1 ... CV_64FC(CV_CN_MAX) ...) + int type() const; + //! returns the depth of sequence elements (CV_8U ... CV_64F) + int depth() const; + //! returns the number of channels in each sequence element + int channels() const; + //! returns the size of each sequence element + size_t elemSize() const; + //! returns index of the specified sequence element + size_t index(const _Tp& elem) const; + //! appends the specified element to the end of the sequence + void push_back(const _Tp& elem); + //! appends the specified element to the front of the sequence + void push_front(const _Tp& elem); + //! appends zero or more elements to the end of the sequence + void push_back(const _Tp* elems, size_t count); + //! appends zero or more elements to the front of the sequence + void push_front(const _Tp* elems, size_t count); + //! inserts the specified element to the specified position + void insert(int idx, const _Tp& elem); + //! inserts zero or more elements to the specified position + void insert(int idx, const _Tp* elems, size_t count); + //! removes element at the specified position + void remove(int idx); + //! removes the specified subsequence + void remove(const Range& r); + + //! returns reference to the first sequence element + _Tp& front(); + //! returns read-only reference to the first sequence element + const _Tp& front() const; + //! returns reference to the last sequence element + _Tp& back(); + //! returns read-only reference to the last sequence element + const _Tp& back() const; + //! returns true iff the sequence contains no elements + bool empty() const; + + //! removes all the elements from the sequence + void clear(); + //! removes the first element from the sequence + void pop_front(); + //! removes the last element from the sequence + void pop_back(); + //! removes zero or more elements from the beginning of the sequence + void pop_front(_Tp* elems, size_t count); + //! removes zero or more elements from the end of the sequence + void pop_back(_Tp* elems, size_t count); + + //! copies the whole sequence or the sequence slice to the specified vector + void copyTo(std::vector<_Tp>& vec, const Range& range=Range::all()) const; + //! returns the vector containing all the sequence elements + operator std::vector<_Tp>() const; + + CvSeq* seq; +}; + + +/*! + STL-style Sequence Iterator inherited from the CvSeqReader structure +*/ +template class SeqIterator : public CvSeqReader +{ +public: + //! the default constructor + SeqIterator(); + //! the constructor setting the iterator to the beginning or to the end of the sequence + SeqIterator(const Seq<_Tp>& seq, bool seekEnd=false); + //! positions the iterator within the sequence + void seek(size_t pos); + //! reports the current iterator position + size_t tell() const; + //! returns reference to the current sequence element + _Tp& operator *(); + //! returns read-only reference to the current sequence element + const _Tp& operator *() const; + //! moves iterator to the next sequence element + SeqIterator& operator ++(); + //! moves iterator to the next sequence element + SeqIterator operator ++(int) const; + //! moves iterator to the previous sequence element + SeqIterator& operator --(); + //! moves iterator to the previous sequence element + SeqIterator operator --(int) const; + + //! moves iterator forward by the specified offset (possibly negative) + SeqIterator& operator +=(int); + //! moves iterator backward by the specified offset (possibly negative) + SeqIterator& operator -=(int); + + // this is index of the current element module seq->total*2 + // (to distinguish between 0 and seq->total) + int index; +}; + + + +// bridge C++ => C Seq API +CV_EXPORTS schar* seqPush( CvSeq* seq, const void* element=0); +CV_EXPORTS schar* seqPushFront( CvSeq* seq, const void* element=0); +CV_EXPORTS void seqPop( CvSeq* seq, void* element=0); +CV_EXPORTS void seqPopFront( CvSeq* seq, void* element=0); +CV_EXPORTS void seqPopMulti( CvSeq* seq, void* elements, + int count, int in_front=0 ); +CV_EXPORTS void seqRemove( CvSeq* seq, int index ); +CV_EXPORTS void clearSeq( CvSeq* seq ); +CV_EXPORTS schar* getSeqElem( const CvSeq* seq, int index ); +CV_EXPORTS void seqRemoveSlice( CvSeq* seq, CvSlice slice ); +CV_EXPORTS void seqInsertSlice( CvSeq* seq, int before_index, const CvArr* from_arr ); + +template inline Seq<_Tp>::Seq() : seq(0) {} +template inline Seq<_Tp>::Seq( const CvSeq* _seq ) : seq((CvSeq*)_seq) +{ + CV_Assert(!_seq || _seq->elem_size == sizeof(_Tp)); +} + +template inline Seq<_Tp>::Seq( MemStorage& storage, + int headerSize ) +{ + CV_Assert(headerSize >= (int)sizeof(CvSeq)); + seq = cvCreateSeq(DataType<_Tp>::type, headerSize, sizeof(_Tp), storage); +} + +template inline _Tp& Seq<_Tp>::operator [](int idx) +{ return *(_Tp*)getSeqElem(seq, idx); } + +template inline const _Tp& Seq<_Tp>::operator [](int idx) const +{ return *(_Tp*)getSeqElem(seq, idx); } + +template inline SeqIterator<_Tp> Seq<_Tp>::begin() const +{ return SeqIterator<_Tp>(*this); } + +template inline SeqIterator<_Tp> Seq<_Tp>::end() const +{ return SeqIterator<_Tp>(*this, true); } + +template inline size_t Seq<_Tp>::size() const +{ return seq ? seq->total : 0; } + +template inline int Seq<_Tp>::type() const +{ return seq ? CV_MAT_TYPE(seq->flags) : 0; } + +template inline int Seq<_Tp>::depth() const +{ return seq ? CV_MAT_DEPTH(seq->flags) : 0; } + +template inline int Seq<_Tp>::channels() const +{ return seq ? CV_MAT_CN(seq->flags) : 0; } + +template inline size_t Seq<_Tp>::elemSize() const +{ return seq ? seq->elem_size : 0; } + +template inline size_t Seq<_Tp>::index(const _Tp& elem) const +{ return cvSeqElemIdx(seq, &elem); } + +template inline void Seq<_Tp>::push_back(const _Tp& elem) +{ cvSeqPush(seq, &elem); } + +template inline void Seq<_Tp>::push_front(const _Tp& elem) +{ cvSeqPushFront(seq, &elem); } + +template inline void Seq<_Tp>::push_back(const _Tp* elem, size_t count) +{ cvSeqPushMulti(seq, elem, (int)count, 0); } + +template inline void Seq<_Tp>::push_front(const _Tp* elem, size_t count) +{ cvSeqPushMulti(seq, elem, (int)count, 1); } + +template inline _Tp& Seq<_Tp>::back() +{ return *(_Tp*)getSeqElem(seq, -1); } + +template inline const _Tp& Seq<_Tp>::back() const +{ return *(const _Tp*)getSeqElem(seq, -1); } + +template inline _Tp& Seq<_Tp>::front() +{ return *(_Tp*)getSeqElem(seq, 0); } + +template inline const _Tp& Seq<_Tp>::front() const +{ return *(const _Tp*)getSeqElem(seq, 0); } + +template inline bool Seq<_Tp>::empty() const +{ return !seq || seq->total == 0; } + +template inline void Seq<_Tp>::clear() +{ if(seq) clearSeq(seq); } + +template inline void Seq<_Tp>::pop_back() +{ seqPop(seq); } + +template inline void Seq<_Tp>::pop_front() +{ seqPopFront(seq); } + +template inline void Seq<_Tp>::pop_back(_Tp* elem, size_t count) +{ seqPopMulti(seq, elem, (int)count, 0); } + +template inline void Seq<_Tp>::pop_front(_Tp* elem, size_t count) +{ seqPopMulti(seq, elem, (int)count, 1); } + +template inline void Seq<_Tp>::insert(int idx, const _Tp& elem) +{ seqInsert(seq, idx, &elem); } + +template inline void Seq<_Tp>::insert(int idx, const _Tp* elems, size_t count) +{ + CvMat m = cvMat(1, count, DataType<_Tp>::type, elems); + seqInsertSlice(seq, idx, &m); +} + +template inline void Seq<_Tp>::remove(int idx) +{ seqRemove(seq, idx); } + +template inline void Seq<_Tp>::remove(const Range& r) +{ seqRemoveSlice(seq, cvSlice(r.start, r.end)); } + +template inline void Seq<_Tp>::copyTo(std::vector<_Tp>& vec, const Range& range) const +{ + size_t len = !seq ? 0 : range == Range::all() ? seq->total : range.end - range.start; + vec.resize(len); + if( seq && len ) + cvCvtSeqToArray(seq, &vec[0], cvSlice(range)); +} + +template inline Seq<_Tp>::operator std::vector<_Tp>() const +{ + std::vector<_Tp> vec; + copyTo(vec); + return vec; +} + +template inline SeqIterator<_Tp>::SeqIterator() +{ memset(this, 0, sizeof(*this)); } + +template inline SeqIterator<_Tp>::SeqIterator(const Seq<_Tp>& _seq, bool seekEnd) +{ + cvStartReadSeq(_seq.seq, this); + index = seekEnd ? _seq.seq->total : 0; +} + +template inline void SeqIterator<_Tp>::seek(size_t pos) +{ + cvSetSeqReaderPos(this, (int)pos, false); + index = pos; +} + +template inline size_t SeqIterator<_Tp>::tell() const +{ return index; } + +template inline _Tp& SeqIterator<_Tp>::operator *() +{ return *(_Tp*)ptr; } + +template inline const _Tp& SeqIterator<_Tp>::operator *() const +{ return *(const _Tp*)ptr; } + +template inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator ++() +{ + CV_NEXT_SEQ_ELEM(sizeof(_Tp), *this); + if( ++index >= seq->total*2 ) + index = 0; + return *this; +} + +template inline SeqIterator<_Tp> SeqIterator<_Tp>::operator ++(int) const +{ + SeqIterator<_Tp> it = *this; + ++*this; + return it; +} + +template inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator --() +{ + CV_PREV_SEQ_ELEM(sizeof(_Tp), *this); + if( --index < 0 ) + index = seq->total*2-1; + return *this; +} + +template inline SeqIterator<_Tp> SeqIterator<_Tp>::operator --(int) const +{ + SeqIterator<_Tp> it = *this; + --*this; + return it; +} + +template inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator +=(int delta) +{ + cvSetSeqReaderPos(this, delta, 1); + index += delta; + int n = seq->total*2; + if( index < 0 ) + index += n; + if( index >= n ) + index -= n; + return *this; +} + +template inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator -=(int delta) +{ + return (*this += -delta); +} + +template inline ptrdiff_t operator - (const SeqIterator<_Tp>& a, + const SeqIterator<_Tp>& b) +{ + ptrdiff_t delta = a.index - b.index, n = a.seq->total; + if( delta > n || delta < -n ) + delta += delta < 0 ? n : -n; + return delta; +} + +template inline bool operator == (const SeqIterator<_Tp>& a, + const SeqIterator<_Tp>& b) +{ + return a.seq == b.seq && a.index == b.index; +} + +template inline bool operator != (const SeqIterator<_Tp>& a, + const SeqIterator<_Tp>& b) +{ + return !(a == b); +} + +//! @} + +} // cv + +#endif + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda.hpp index 8191c00783..53898171f2 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda.hpp @@ -1,1339 +1,1339 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CORE_CUDA_HPP -#define OPENCV_CORE_CUDA_HPP - -#ifndef __cplusplus -# error cuda.hpp header must be compiled as C++ -#endif - -#include "opencv2/core.hpp" -#include "opencv2/core/cuda_types.hpp" - -/** - @defgroup cuda CUDA-accelerated Computer Vision - @{ - @defgroup cudacore Core part - @{ - @defgroup cudacore_init Initialization and Information - @defgroup cudacore_struct Data Structures - @} - @} - */ - -namespace cv { namespace cuda { - -//! @addtogroup cudacore_struct -//! @{ - -//=================================================================================== -// GpuMat -//=================================================================================== - -/** @brief Base storage class for GPU memory with reference counting. - -Its interface matches the Mat interface with the following limitations: - -- no arbitrary dimensions support (only 2D) -- no functions that return references to their data (because references on GPU are not valid for - CPU) -- no expression templates technique support - -Beware that the latter limitation may lead to overloaded matrix operators that cause memory -allocations. The GpuMat class is convertible to cuda::PtrStepSz and cuda::PtrStep so it can be -passed directly to the kernel. - -@note In contrast with Mat, in most cases GpuMat::isContinuous() == false . This means that rows are -aligned to a size depending on the hardware. Single-row GpuMat is always a continuous matrix. - -@note You are not recommended to leave static or global GpuMat variables allocated, that is, to rely -on its destructor. The destruction order of such variables and CUDA context is undefined. GPU memory -release function returns error if the CUDA context has been destroyed before. - -Some member functions are described as a "Blocking Call" while some are described as a -"Non-Blocking Call". Blocking functions are synchronous to host. It is guaranteed that the GPU -operation is finished when the function returns. However, non-blocking functions are asynchronous to -host. Those functions may return even if the GPU operation is not finished. - -Compared to their blocking counterpart, non-blocking functions accept Stream as an additional -argument. If a non-default stream is passed, the GPU operation may overlap with operations in other -streams. - -@sa Mat - */ -class CV_EXPORTS_W GpuMat -{ -public: - class CV_EXPORTS_W Allocator - { - public: - virtual ~Allocator() {} - - // allocator must fill data, step and refcount fields - virtual bool allocate(GpuMat* mat, int rows, int cols, size_t elemSize) = 0; - virtual void free(GpuMat* mat) = 0; - }; - - //! default allocator - CV_WRAP static GpuMat::Allocator* defaultAllocator(); - CV_WRAP static void setDefaultAllocator(GpuMat::Allocator* allocator); - CV_WRAP static GpuMat::Allocator* getStdAllocator(); - - //! default constructor - CV_WRAP explicit GpuMat(GpuMat::Allocator* allocator = GpuMat::defaultAllocator()); - - //! constructs GpuMat of the specified size and type - CV_WRAP GpuMat(int rows, int cols, int type, GpuMat::Allocator* allocator = GpuMat::defaultAllocator()); - CV_WRAP GpuMat(Size size, int type, GpuMat::Allocator* allocator = GpuMat::defaultAllocator()); - - //! constructs GpuMat and fills it with the specified value _s - CV_WRAP GpuMat(int rows, int cols, int type, Scalar s, GpuMat::Allocator* allocator = GpuMat::defaultAllocator()); - CV_WRAP GpuMat(Size size, int type, Scalar s, GpuMat::Allocator* allocator = GpuMat::defaultAllocator()); - - //! copy constructor - CV_WRAP GpuMat(const GpuMat& m); - - //! constructor for GpuMat headers pointing to user-allocated data - GpuMat(int rows, int cols, int type, void* data, size_t step = Mat::AUTO_STEP); - GpuMat(Size size, int type, void* data, size_t step = Mat::AUTO_STEP); - - //! creates a GpuMat header for a part of the bigger matrix - CV_WRAP GpuMat(const GpuMat& m, Range rowRange, Range colRange); - CV_WRAP GpuMat(const GpuMat& m, Rect roi); - - //! builds GpuMat from host memory (Blocking call) - CV_WRAP explicit GpuMat(InputArray arr, GpuMat::Allocator* allocator = GpuMat::defaultAllocator()); - - //! destructor - calls release() - ~GpuMat(); - - //! assignment operators - GpuMat& operator =(const GpuMat& m); - - //! allocates new GpuMat data unless the GpuMat already has specified size and type - CV_WRAP void create(int rows, int cols, int type); - CV_WRAP void create(Size size, int type); - - //! decreases reference counter, deallocate the data when reference counter reaches 0 - CV_WRAP void release(); - - //! swaps with other smart pointer - CV_WRAP void swap(GpuMat& mat); - - /** @brief Performs data upload to GpuMat (Blocking call) - - This function copies data from host memory to device memory. As being a blocking call, it is - guaranteed that the copy operation is finished when this function returns. - */ - CV_WRAP void upload(InputArray arr); - - /** @brief Performs data upload to GpuMat (Non-Blocking call) - - This function copies data from host memory to device memory. As being a non-blocking call, this - function may return even if the copy operation is not finished. - - The copy operation may be overlapped with operations in other non-default streams if \p stream is - not the default stream and \p dst is HostMem allocated with HostMem::PAGE_LOCKED option. - */ - CV_WRAP void upload(InputArray arr, Stream& stream); - - /** @brief Performs data download from GpuMat (Blocking call) - - This function copies data from device memory to host memory. As being a blocking call, it is - guaranteed that the copy operation is finished when this function returns. - */ - CV_WRAP void download(OutputArray dst) const; - - /** @brief Performs data download from GpuMat (Non-Blocking call) - - This function copies data from device memory to host memory. As being a non-blocking call, this - function may return even if the copy operation is not finished. - - The copy operation may be overlapped with operations in other non-default streams if \p stream is - not the default stream and \p dst is HostMem allocated with HostMem::PAGE_LOCKED option. - */ - CV_WRAP void download(OutputArray dst, Stream& stream) const; - - //! returns deep copy of the GpuMat, i.e. the data is copied - CV_WRAP GpuMat clone() const; - - //! copies the GpuMat content to device memory (Blocking call) - void copyTo(OutputArray dst) const; - //! bindings overload which copies the GpuMat content to device memory (Blocking call) - CV_WRAP void copyTo(CV_OUT GpuMat& dst) const { - copyTo(static_cast(dst)); - } - - //! copies the GpuMat content to device memory (Non-Blocking call) - void copyTo(OutputArray dst, Stream& stream) const; - //! bindings overload which copies the GpuMat content to device memory (Non-Blocking call) - CV_WRAP void copyTo(CV_OUT GpuMat& dst, Stream& stream) const { - copyTo(static_cast(dst), stream); - } - - //! copies those GpuMat elements to "m" that are marked with non-zero mask elements (Blocking call) - void copyTo(OutputArray dst, InputArray mask) const; - //! bindings overload which copies those GpuMat elements to "m" that are marked with non-zero mask elements (Blocking call) - CV_WRAP void copyTo(CV_OUT GpuMat& dst, GpuMat& mask) const { - copyTo(static_cast(dst), static_cast(mask)); - } - - //! copies those GpuMat elements to "m" that are marked with non-zero mask elements (Non-Blocking call) - void copyTo(OutputArray dst, InputArray mask, Stream& stream) const; - //! bindings overload which copies those GpuMat elements to "m" that are marked with non-zero mask elements (Non-Blocking call) - CV_WRAP void copyTo(CV_OUT GpuMat& dst, GpuMat& mask, Stream& stream) const { - copyTo(static_cast(dst), static_cast(mask), stream); - } - - //! sets some of the GpuMat elements to s (Blocking call) - CV_WRAP GpuMat& setTo(Scalar s); - - //! sets some of the GpuMat elements to s (Non-Blocking call) - CV_WRAP GpuMat& setTo(Scalar s, Stream& stream); - - //! sets some of the GpuMat elements to s, according to the mask (Blocking call) - CV_WRAP GpuMat& setTo(Scalar s, InputArray mask); - - //! sets some of the GpuMat elements to s, according to the mask (Non-Blocking call) - CV_WRAP GpuMat& setTo(Scalar s, InputArray mask, Stream& stream); - - //! converts GpuMat to another datatype (Blocking call) - void convertTo(OutputArray dst, int rtype) const; - - //! converts GpuMat to another datatype (Non-Blocking call) - void convertTo(OutputArray dst, int rtype, Stream& stream) const; - //! bindings overload which converts GpuMat to another datatype (Non-Blocking call) - CV_WRAP void convertTo(CV_OUT GpuMat& dst, int rtype, Stream& stream) const { - convertTo(static_cast(dst), rtype, stream); - } - - //! converts GpuMat to another datatype with scaling (Blocking call) - void convertTo(OutputArray dst, int rtype, double alpha, double beta = 0.0) const; - //! bindings overload which converts GpuMat to another datatype with scaling(Blocking call) - CV_WRAP void convertTo(CV_OUT GpuMat& dst, int rtype, double alpha = 1.0, double beta = 0.0) const { - convertTo(static_cast(dst), rtype, alpha, beta); - } - - //! converts GpuMat to another datatype with scaling (Non-Blocking call) - void convertTo(OutputArray dst, int rtype, double alpha, Stream& stream) const; - - //! converts GpuMat to another datatype with scaling (Non-Blocking call) - void convertTo(OutputArray dst, int rtype, double alpha, double beta, Stream& stream) const; - //! bindings overload which converts GpuMat to another datatype with scaling (Non-Blocking call) - CV_WRAP void convertTo(CV_OUT GpuMat& dst, int rtype, double alpha, double beta, Stream& stream) const { - convertTo(static_cast(dst), rtype, alpha, beta, stream); - } - - CV_WRAP void assignTo(GpuMat& m, int type = -1) const; - - //! returns pointer to y-th row - uchar* ptr(int y = 0); - const uchar* ptr(int y = 0) const; - - //! template version of the above method - template _Tp* ptr(int y = 0); - template const _Tp* ptr(int y = 0) const; - - template operator PtrStepSz<_Tp>() const; - template operator PtrStep<_Tp>() const; - - //! returns a new GpuMat header for the specified row - CV_WRAP GpuMat row(int y) const; - - //! returns a new GpuMat header for the specified column - CV_WRAP GpuMat col(int x) const; - - //! ... for the specified row span - CV_WRAP GpuMat rowRange(int startrow, int endrow) const; - CV_WRAP GpuMat rowRange(Range r) const; - - //! ... for the specified column span - CV_WRAP GpuMat colRange(int startcol, int endcol) const; - CV_WRAP GpuMat colRange(Range r) const; - - //! extracts a rectangular sub-GpuMat (this is a generalized form of row, rowRange etc.) - GpuMat operator ()(Range rowRange, Range colRange) const; - GpuMat operator ()(Rect roi) const; - - //! creates alternative GpuMat header for the same data, with different - //! number of channels and/or different number of rows - CV_WRAP GpuMat reshape(int cn, int rows = 0) const; - - //! locates GpuMat header within a parent GpuMat - CV_WRAP void locateROI(Size& wholeSize, Point& ofs) const; - - //! moves/resizes the current GpuMat ROI inside the parent GpuMat - CV_WRAP GpuMat& adjustROI(int dtop, int dbottom, int dleft, int dright); - - //! returns true iff the GpuMat data is continuous - //! (i.e. when there are no gaps between successive rows) - CV_WRAP bool isContinuous() const; - - //! returns element size in bytes - CV_WRAP size_t elemSize() const; - - //! returns the size of element channel in bytes - CV_WRAP size_t elemSize1() const; - - //! returns element type - CV_WRAP int type() const; - - //! returns element type - CV_WRAP int depth() const; - - //! returns number of channels - CV_WRAP int channels() const; - - //! returns step/elemSize1() - CV_WRAP size_t step1() const; - - //! returns GpuMat size : width == number of columns, height == number of rows - CV_WRAP Size size() const; - - //! returns true if GpuMat data is NULL - CV_WRAP bool empty() const; - - // returns pointer to cuda memory - CV_WRAP void* cudaPtr() const; - - //! internal use method: updates the continuity flag - CV_WRAP void updateContinuityFlag(); - - /*! includes several bit-fields: - - the magic signature - - continuity flag - - depth - - number of channels - */ - int flags; - - //! the number of rows and columns - int rows, cols; - - //! a distance between successive rows in bytes; includes the gap if any - CV_PROP size_t step; - - //! pointer to the data - uchar* data; - - //! pointer to the reference counter; - //! when GpuMat points to user-allocated data, the pointer is NULL - int* refcount; - - //! helper fields used in locateROI and adjustROI - uchar* datastart; - const uchar* dataend; - - //! allocator - Allocator* allocator; -}; - -struct CV_EXPORTS_W GpuData -{ - explicit GpuData(size_t _size); - ~GpuData(); - - GpuData(const GpuData&) = delete; - GpuData& operator=(const GpuData&) = delete; - - GpuData(GpuData&&) = delete; - GpuData& operator=(GpuData&&) = delete; - - uchar* data; - size_t size; -}; - -class CV_EXPORTS_W GpuMatND -{ -public: - using SizeArray = std::vector; - using StepArray = std::vector; - using IndexArray = std::vector; - - //! destructor - ~GpuMatND(); - - //! default constructor - GpuMatND(); - - /** @overload - @param size Array of integers specifying an n-dimensional array shape. - @param type Array type. Use CV_8UC1, ..., CV_16FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - */ - GpuMatND(SizeArray size, int type); - - /** @overload - @param size Array of integers specifying an n-dimensional array shape. - @param type Array type. Use CV_8UC1, ..., CV_16FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - @param data Pointer to the user data. Matrix constructors that take data and step parameters do not - allocate matrix data. Instead, they just initialize the matrix header that points to the specified - data, which means that no data is copied. This operation is very efficient and can be used to - process external data using OpenCV functions. The external data is not automatically deallocated, so - you should take care of it. - @param step Array of _size.size() or _size.size()-1 steps in case of a multi-dimensional array - (if specified, the last step must be equal to the element size, otherwise it will be added as such). - If not specified, the matrix is assumed to be continuous. - */ - GpuMatND(SizeArray size, int type, void* data, StepArray step = StepArray()); - - /** @brief Allocates GPU memory. - Suppose there is some GPU memory already allocated. In that case, this method may choose to reuse that - GPU memory under the specific condition: it must be of the same size and type, not externally allocated, - the GPU memory is continuous(i.e., isContinuous() is true), and is not a sub-matrix of another GpuMatND - (i.e., isSubmatrix() is false). In other words, this method guarantees that the GPU memory allocated by - this method is always continuous and is not a sub-region of another GpuMatND. - */ - void create(SizeArray size, int type); - - void release(); - - void swap(GpuMatND& m) noexcept; - - /** @brief Creates a full copy of the array and the underlying data. - The method creates a full copy of the array. It mimics the behavior of Mat::clone(), i.e. - the original step is not taken into account. So, the array copy is a continuous array - occupying total()\*elemSize() bytes. - */ - GpuMatND clone() const; - - /** @overload - This overload is non-blocking, so it may return even if the copy operation is not finished. - */ - GpuMatND clone(Stream& stream) const; - - /** @brief Extracts a sub-matrix. - The operator makes a new header for the specified sub-array of \*this. - The operator is an O(1) operation, that is, no matrix data is copied. - @param ranges Array of selected ranges along each dimension. - */ - GpuMatND operator()(const std::vector& ranges) const; - - /** @brief Creates a GpuMat header for a 2D plane part of an n-dim matrix. - @note The returned GpuMat is constructed with the constructor for user-allocated data. - That is, It does not perform reference counting. - @note This function does not increment this GpuMatND's reference counter. - */ - GpuMat createGpuMatHeader(IndexArray idx, Range rowRange, Range colRange) const; - - /** @overload - Creates a GpuMat header if this GpuMatND is effectively 2D. - @note The returned GpuMat is constructed with the constructor for user-allocated data. - That is, It does not perform reference counting. - @note This function does not increment this GpuMatND's reference counter. - */ - GpuMat createGpuMatHeader() const; - - /** @brief Extracts a 2D plane part of an n-dim matrix. - It differs from createGpuMatHeader(IndexArray, Range, Range) in that it clones a part of this - GpuMatND to the returned GpuMat. - @note This operator does not increment this GpuMatND's reference counter; - */ - GpuMat operator()(IndexArray idx, Range rowRange, Range colRange) const; - - /** @brief Extracts a 2D plane part of an n-dim matrix if this GpuMatND is effectively 2D. - It differs from createGpuMatHeader() in that it clones a part of this GpuMatND. - @note This operator does not increment this GpuMatND's reference counter; - */ - operator GpuMat() const; - - GpuMatND(const GpuMatND&) = default; - GpuMatND& operator=(const GpuMatND&) = default; - -#if defined(__GNUC__) && __GNUC__ < 5 - // error: function '...' defaulted on its first declaration with an exception-specification - // that differs from the implicit declaration '...' - - GpuMatND(GpuMatND&&) = default; - GpuMatND& operator=(GpuMatND&&) = default; -#else - GpuMatND(GpuMatND&&) noexcept = default; - GpuMatND& operator=(GpuMatND&&) noexcept = default; -#endif - - void upload(InputArray src); - void upload(InputArray src, Stream& stream); - void download(OutputArray dst) const; - void download(OutputArray dst, Stream& stream) const; - - //! returns true iff the GpuMatND data is continuous - //! (i.e. when there are no gaps between successive rows) - bool isContinuous() const; - - //! returns true if the matrix is a sub-matrix of another matrix - bool isSubmatrix() const; - - //! returns element size in bytes - size_t elemSize() const; - - //! returns the size of element channel in bytes - size_t elemSize1() const; - - //! returns true if data is null - bool empty() const; - - //! returns true if not empty and points to external(user-allocated) gpu memory - bool external() const; - - //! returns pointer to the first byte of the GPU memory - uchar* getDevicePtr() const; - - //! returns the total number of array elements - size_t total() const; - - //! returns the size of underlying memory in bytes - size_t totalMemSize() const; - - //! returns element type - int type() const; - -private: - //! internal use - void setFields(SizeArray size, int type, StepArray step = StepArray()); - -public: - /*! includes several bit-fields: - - the magic signature - - continuity flag - - depth - - number of channels - */ - int flags; - - //! matrix dimensionality - int dims; - - //! shape of this array - SizeArray size; - - /*! step values - Their semantics is identical to the semantics of step for Mat. - */ - StepArray step; - -private: - /*! internal use - If this GpuMatND holds external memory, this is empty. - */ - std::shared_ptr data_; - - /*! internal use - If this GpuMatND manages memory with reference counting, this value is - always equal to data_->data. If this GpuMatND holds external memory, - data_ is empty and data points to the external memory. - */ - uchar* data; - - /*! internal use - If this GpuMatND is a sub-matrix of a larger matrix, this value is the - difference of the first byte between the sub-matrix and the whole matrix. - */ - size_t offset; -}; - -/** @brief Creates a continuous matrix. - -@param rows Row count. -@param cols Column count. -@param type Type of the matrix. -@param arr Destination matrix. This parameter changes only if it has a proper type and area ( -\f$\texttt{rows} \times \texttt{cols}\f$ ). - -Matrix is called continuous if its elements are stored continuously, that is, without gaps at the -end of each row. - */ -CV_EXPORTS_W void createContinuous(int rows, int cols, int type, OutputArray arr); - -/** @brief Ensures that the size of a matrix is big enough and the matrix has a proper type. - -@param rows Minimum desired number of rows. -@param cols Minimum desired number of columns. -@param type Desired matrix type. -@param arr Destination matrix. - -The function does not reallocate memory if the matrix has proper attributes already. - */ -CV_EXPORTS_W void ensureSizeIsEnough(int rows, int cols, int type, OutputArray arr); - -/** @brief Bindings overload to create a GpuMat from existing GPU memory. -@param rows Row count. -@param cols Column count. -@param type Type of the matrix. -@param cudaMemoryAddress Address of the allocated GPU memory on the device. This does not allocate matrix data. Instead, it just initializes the matrix header that points to the specified \a cudaMemoryAddress, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it. -@param step Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. If the parameter is missing (set to Mat::AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize(). See GpuMat::elemSize. -@note Overload for generation of bindings only, not exported or intended for use internally from C++. - */ -CV_EXPORTS_W GpuMat inline createGpuMatFromCudaMemory(int rows, int cols, int type, size_t cudaMemoryAddress, size_t step = Mat::AUTO_STEP) { - return GpuMat(rows, cols, type, reinterpret_cast(cudaMemoryAddress), step); -} - - /** @overload -@param size 2D array size: Size(cols, rows). In the Size() constructor, the number of rows and the number of columns go in the reverse order. -@param type Type of the matrix. -@param cudaMemoryAddress Address of the allocated GPU memory on the device. This does not allocate matrix data. Instead, it just initializes the matrix header that points to the specified \a cudaMemoryAddress, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it. -@param step Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. If the parameter is missing (set to Mat::AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize(). See GpuMat::elemSize. -@note Overload for generation of bindings only, not exported or intended for use internally from C++. - */ -CV_EXPORTS_W inline GpuMat createGpuMatFromCudaMemory(Size size, int type, size_t cudaMemoryAddress, size_t step = Mat::AUTO_STEP) { - return GpuMat(size, type, reinterpret_cast(cudaMemoryAddress), step); -} - -/** @brief BufferPool for use with CUDA streams - -BufferPool utilizes Stream's allocator to create new buffers for GpuMat's. It is -only useful when enabled with #setBufferPoolUsage. - -@code - setBufferPoolUsage(true); -@endcode - -@note #setBufferPoolUsage must be called \em before any Stream declaration. - -Users may specify custom allocator for Stream and may implement their own stream based -functions utilizing the same underlying GPU memory management. - -If custom allocator is not specified, BufferPool utilizes StackAllocator by -default. StackAllocator allocates a chunk of GPU device memory beforehand, -and when GpuMat is declared later on, it is given the pre-allocated memory. -This kind of strategy reduces the number of calls for memory allocating APIs -such as cudaMalloc or cudaMallocPitch. - -Below is an example that utilizes BufferPool with StackAllocator: - -@code - #include - - using namespace cv; - using namespace cv::cuda - - int main() - { - setBufferPoolUsage(true); // Tell OpenCV that we are going to utilize BufferPool - setBufferPoolConfig(getDevice(), 1024 * 1024 * 64, 2); // Allocate 64 MB, 2 stacks (default is 10 MB, 5 stacks) - - Stream stream1, stream2; // Each stream uses 1 stack - BufferPool pool1(stream1), pool2(stream2); - - GpuMat d_src1 = pool1.getBuffer(4096, 4096, CV_8UC1); // 16MB - GpuMat d_dst1 = pool1.getBuffer(4096, 4096, CV_8UC3); // 48MB, pool1 is now full - - GpuMat d_src2 = pool2.getBuffer(1024, 1024, CV_8UC1); // 1MB - GpuMat d_dst2 = pool2.getBuffer(1024, 1024, CV_8UC3); // 3MB - - cvtColor(d_src1, d_dst1, cv::COLOR_GRAY2BGR, 0, stream1); - cvtColor(d_src2, d_dst2, cv::COLOR_GRAY2BGR, 0, stream2); - } -@endcode - -If we allocate another GpuMat on pool1 in the above example, it will be carried out by -the DefaultAllocator since the stack for pool1 is full. - -@code - GpuMat d_add1 = pool1.getBuffer(1024, 1024, CV_8UC1); // Stack for pool1 is full, memory is allocated with DefaultAllocator -@endcode - -If a third stream is declared in the above example, allocating with #getBuffer -within that stream will also be carried out by the DefaultAllocator because we've run out of -stacks. - -@code - Stream stream3; // Only 2 stacks were allocated, we've run out of stacks - BufferPool pool3(stream3); - GpuMat d_src3 = pool3.getBuffer(1024, 1024, CV_8UC1); // Memory is allocated with DefaultAllocator -@endcode - -@warning When utilizing StackAllocator, deallocation order is important. - -Just like a stack, deallocation must be done in LIFO order. Below is an example of -erroneous usage that violates LIFO rule. If OpenCV is compiled in Debug mode, this -sample code will emit CV_Assert error. - -@code - int main() - { - setBufferPoolUsage(true); // Tell OpenCV that we are going to utilize BufferPool - Stream stream; // A default size (10 MB) stack is allocated to this stream - BufferPool pool(stream); - - GpuMat mat1 = pool.getBuffer(1024, 1024, CV_8UC1); // Allocate mat1 (1MB) - GpuMat mat2 = pool.getBuffer(1024, 1024, CV_8UC1); // Allocate mat2 (1MB) - - mat1.release(); // erroneous usage : mat2 must be deallocated before mat1 - } -@endcode - -Since C++ local variables are destroyed in the reverse order of construction, -the code sample below satisfies the LIFO rule. Local GpuMat's are deallocated -and the corresponding memory is automatically returned to the pool for later usage. - -@code - int main() - { - setBufferPoolUsage(true); // Tell OpenCV that we are going to utilize BufferPool - setBufferPoolConfig(getDevice(), 1024 * 1024 * 64, 2); // Allocate 64 MB, 2 stacks (default is 10 MB, 5 stacks) - - Stream stream1, stream2; // Each stream uses 1 stack - BufferPool pool1(stream1), pool2(stream2); - - for (int i = 0; i < 10; i++) - { - GpuMat d_src1 = pool1.getBuffer(4096, 4096, CV_8UC1); // 16MB - GpuMat d_dst1 = pool1.getBuffer(4096, 4096, CV_8UC3); // 48MB, pool1 is now full - - GpuMat d_src2 = pool2.getBuffer(1024, 1024, CV_8UC1); // 1MB - GpuMat d_dst2 = pool2.getBuffer(1024, 1024, CV_8UC3); // 3MB - - d_src1.setTo(Scalar(i), stream1); - d_src2.setTo(Scalar(i), stream2); - - cvtColor(d_src1, d_dst1, cv::COLOR_GRAY2BGR, 0, stream1); - cvtColor(d_src2, d_dst2, cv::COLOR_GRAY2BGR, 0, stream2); - // The order of destruction of the local variables is: - // d_dst2 => d_src2 => d_dst1 => d_src1 - // LIFO rule is satisfied, this code runs without error - } - } -@endcode - */ -class CV_EXPORTS_W BufferPool -{ -public: - - //! Gets the BufferPool for the given stream. - CV_WRAP explicit BufferPool(Stream& stream); - - //! Allocates a new GpuMat of given size and type. - CV_WRAP GpuMat getBuffer(int rows, int cols, int type); - -// WARNING: unreachable code using Ninja -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(push) -#pragma warning(disable: 4702) -#endif - //! Allocates a new GpuMat of given size and type. - CV_WRAP GpuMat getBuffer(Size size, int type) { return getBuffer(size.height, size.width, type); } -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(pop) -#endif - - //! Returns the allocator associated with the stream. - CV_WRAP Ptr getAllocator() const { return allocator_; } - -private: - Ptr allocator_; -}; - -//! BufferPool management (must be called before Stream creation) -CV_EXPORTS_W void setBufferPoolUsage(bool on); -CV_EXPORTS_W void setBufferPoolConfig(int deviceId, size_t stackSize, int stackCount); - -//=================================================================================== -// HostMem -//=================================================================================== - -/** @brief Class with reference counting wrapping special memory type allocation functions from CUDA. - -Its interface is also Mat-like but with additional memory type parameters. - -- **PAGE_LOCKED** sets a page locked memory type used commonly for fast and asynchronous - uploading/downloading data from/to GPU. -- **SHARED** specifies a zero copy memory allocation that enables mapping the host memory to GPU - address space, if supported. -- **WRITE_COMBINED** sets the write combined buffer that is not cached by CPU. Such buffers are - used to supply GPU with data when GPU only reads it. The advantage is a better CPU cache - utilization. - -@note Allocation size of such memory types is usually limited. For more details, see *CUDA 2.2 -Pinned Memory APIs* document or *CUDA C Programming Guide*. - */ -class CV_EXPORTS_W HostMem -{ -public: - enum AllocType { PAGE_LOCKED = 1, SHARED = 2, WRITE_COMBINED = 4 }; - - static MatAllocator* getAllocator(HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED); - - CV_WRAP explicit HostMem(HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED); - - HostMem(const HostMem& m); - - CV_WRAP HostMem(int rows, int cols, int type, HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED); - CV_WRAP HostMem(Size size, int type, HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED); - - //! creates from host memory with coping data - CV_WRAP explicit HostMem(InputArray arr, HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED); - - ~HostMem(); - - HostMem& operator =(const HostMem& m); - - //! swaps with other smart pointer - CV_WRAP void swap(HostMem& b); - - //! returns deep copy of the matrix, i.e. the data is copied - CV_WRAP HostMem clone() const; - - //! allocates new matrix data unless the matrix already has specified size and type. - CV_WRAP void create(int rows, int cols, int type); - void create(Size size, int type); - - //! creates alternative HostMem header for the same data, with different - //! number of channels and/or different number of rows - CV_WRAP HostMem reshape(int cn, int rows = 0) const; - - //! decrements reference counter and released memory if needed. - void release(); - - //! returns matrix header with disabled reference counting for HostMem data. - CV_WRAP Mat createMatHeader() const; - - /** @brief Maps CPU memory to GPU address space and creates the cuda::GpuMat header without reference counting - for it. - - This can be done only if memory was allocated with the SHARED flag and if it is supported by the - hardware. Laptops often share video and CPU memory, so address spaces can be mapped, which - eliminates an extra copy. - */ - GpuMat createGpuMatHeader() const; - - // Please see cv::Mat for descriptions - CV_WRAP bool isContinuous() const; - CV_WRAP size_t elemSize() const; - CV_WRAP size_t elemSize1() const; - CV_WRAP int type() const; - CV_WRAP int depth() const; - CV_WRAP int channels() const; - CV_WRAP size_t step1() const; - CV_WRAP Size size() const; - CV_WRAP bool empty() const; - - // Please see cv::Mat for descriptions - int flags; - int rows, cols; - CV_PROP size_t step; - - uchar* data; - int* refcount; - - uchar* datastart; - const uchar* dataend; - - AllocType alloc_type; -}; - -/** @brief Page-locks the memory of matrix and maps it for the device(s). - -@param m Input matrix. - */ -CV_EXPORTS_W void registerPageLocked(Mat& m); - -/** @brief Unmaps the memory of matrix and makes it pageable again. - -@param m Input matrix. - */ -CV_EXPORTS_W void unregisterPageLocked(Mat& m); - -//=================================================================================== -// Stream -//=================================================================================== - -/** @brief This class encapsulates a queue of asynchronous calls. - -@note Currently, you may face problems if an operation is enqueued twice with different data. Some -functions use the constant GPU memory, and next call may update the memory before the previous one -has been finished. But calling different operations asynchronously is safe because each operation -has its own constant buffer. Memory copy/upload/download/set operations to the buffers you hold are -also safe. - -@note The Stream class is not thread-safe. Please use different Stream objects for different CPU threads. - -@code -void thread1() -{ - cv::cuda::Stream stream1; - cv::cuda::func1(..., stream1); -} - -void thread2() -{ - cv::cuda::Stream stream2; - cv::cuda::func2(..., stream2); -} -@endcode - -@note By default all CUDA routines are launched in Stream::Null() object, if the stream is not specified by user. -In multi-threading environment the stream objects must be passed explicitly (see previous note). - */ -class CV_EXPORTS_W Stream -{ - typedef void (Stream::*bool_type)() const; - void this_type_does_not_support_comparisons() const {} - -public: - typedef void (*StreamCallback)(int status, void* userData); - - //! creates a new asynchronous stream - CV_WRAP Stream(); - - //! creates a new asynchronous stream with custom allocator - CV_WRAP Stream(const Ptr& allocator); - - /** @brief creates a new Stream using the cudaFlags argument to determine the behaviors of the stream - - @note The cudaFlags parameter is passed to the underlying api cudaStreamCreateWithFlags() and - supports the same parameter values. - @code - // creates an OpenCV cuda::Stream that manages an asynchronous, non-blocking, - // non-default CUDA stream - cv::cuda::Stream cvStream(cudaStreamNonBlocking); - @endcode - */ - CV_WRAP Stream(const size_t cudaFlags); - - /** @brief Returns true if the current stream queue is finished. Otherwise, it returns false. - */ - CV_WRAP bool queryIfComplete() const; - - /** @brief Blocks the current CPU thread until all operations in the stream are complete. - */ - CV_WRAP void waitForCompletion(); - - /** @brief Makes a compute stream wait on an event. - */ - CV_WRAP void waitEvent(const Event& event); - - /** @brief Adds a callback to be called on the host after all currently enqueued items in the stream have - completed. - - @note Callbacks must not make any CUDA API calls. Callbacks must not perform any synchronization - that may depend on outstanding device work or other callbacks that are not mandated to run earlier. - Callbacks without a mandated order (in independent streams) execute in undefined order and may be - serialized. - */ - void enqueueHostCallback(StreamCallback callback, void* userData); - - //! return Stream object for default CUDA stream - CV_WRAP static Stream& Null(); - - //! returns true if stream object is not default (!= 0) - operator bool_type() const; - - //! return Pointer to CUDA stream - CV_WRAP void* cudaPtr() const; - - class Impl; - -private: - Ptr impl_; - Stream(const Ptr& impl); - - friend struct StreamAccessor; - friend class BufferPool; - friend class DefaultDeviceInitializer; -}; - - -/** @brief Bindings overload to create a Stream object from the address stored in an existing CUDA Runtime API stream pointer (cudaStream_t). -@param cudaStreamMemoryAddress Memory address stored in a CUDA Runtime API stream pointer (cudaStream_t). The created Stream object does not perform any allocation or deallocation and simply wraps existing raw CUDA Runtime API stream pointer. -@note Overload for generation of bindings only, not exported or intended for use internally from C++. - */ -CV_EXPORTS_W Stream wrapStream(size_t cudaStreamMemoryAddress); - -class CV_EXPORTS_W Event -{ -public: - enum CreateFlags - { - DEFAULT = 0x00, /**< Default event flag */ - BLOCKING_SYNC = 0x01, /**< Event uses blocking synchronization */ - DISABLE_TIMING = 0x02, /**< Event will not record timing data */ - INTERPROCESS = 0x04 /**< Event is suitable for interprocess use. DisableTiming must be set */ - }; - - CV_WRAP explicit Event(const Event::CreateFlags flags = Event::CreateFlags::DEFAULT); - - //! records an event - CV_WRAP void record(Stream& stream = Stream::Null()); - - //! queries an event's status - CV_WRAP bool queryIfComplete() const; - - //! waits for an event to complete - CV_WRAP void waitForCompletion(); - - //! computes the elapsed time between events - CV_WRAP static float elapsedTime(const Event& start, const Event& end); - - class Impl; - -private: - Ptr impl_; - Event(const Ptr& impl); - - friend struct EventAccessor; -}; -CV_ENUM_FLAGS(Event::CreateFlags) - -//! @} cudacore_struct - -//=================================================================================== -// Initialization & Info -//=================================================================================== - -//! @addtogroup cudacore_init -//! @{ - -/** @brief Returns the number of installed CUDA-enabled devices. - -Use this function before any other CUDA functions calls. If OpenCV is compiled without CUDA support, -this function returns 0. If the CUDA driver is not installed, or is incompatible, this function -returns -1. - */ -CV_EXPORTS_W int getCudaEnabledDeviceCount(); - -/** @brief Sets a device and initializes it for the current thread. - -@param device System index of a CUDA device starting with 0. - -If the call of this function is omitted, a default device is initialized at the fist CUDA usage. - */ -CV_EXPORTS_W void setDevice(int device); - -/** @brief Returns the current device index set by cuda::setDevice or initialized by default. - */ -CV_EXPORTS_W int getDevice(); - -/** @brief Explicitly destroys and cleans up all resources associated with the current device in the current -process. - -Any subsequent API call to this device will reinitialize the device. - */ -CV_EXPORTS_W void resetDevice(); - -/** @brief Enumeration providing CUDA computing features. - */ -enum FeatureSet -{ - FEATURE_SET_COMPUTE_10 = 10, - FEATURE_SET_COMPUTE_11 = 11, - FEATURE_SET_COMPUTE_12 = 12, - FEATURE_SET_COMPUTE_13 = 13, - FEATURE_SET_COMPUTE_20 = 20, - FEATURE_SET_COMPUTE_21 = 21, - FEATURE_SET_COMPUTE_30 = 30, - FEATURE_SET_COMPUTE_32 = 32, - FEATURE_SET_COMPUTE_35 = 35, - FEATURE_SET_COMPUTE_50 = 50, - - GLOBAL_ATOMICS = FEATURE_SET_COMPUTE_11, - SHARED_ATOMICS = FEATURE_SET_COMPUTE_12, - NATIVE_DOUBLE = FEATURE_SET_COMPUTE_13, - WARP_SHUFFLE_FUNCTIONS = FEATURE_SET_COMPUTE_30, - DYNAMIC_PARALLELISM = FEATURE_SET_COMPUTE_35 -}; - -//! checks whether current device supports the given feature -CV_EXPORTS bool deviceSupports(FeatureSet feature_set); - -/** @brief Class providing a set of static methods to check what NVIDIA\* card architecture the CUDA module was -built for. - -According to the CUDA C Programming Guide Version 3.2: "PTX code produced for some specific compute -capability can always be compiled to binary code of greater or equal compute capability". - */ -class CV_EXPORTS_W TargetArchs -{ -public: - /** @brief The following method checks whether the module was built with the support of the given feature: - - @param feature_set Features to be checked. See :ocvcuda::FeatureSet. - */ - static bool builtWith(FeatureSet feature_set); - - /** @brief There is a set of methods to check whether the module contains intermediate (PTX) or binary CUDA - code for the given architecture(s): - - @param major Major compute capability version. - @param minor Minor compute capability version. - */ - CV_WRAP static bool has(int major, int minor); - CV_WRAP static bool hasPtx(int major, int minor); - CV_WRAP static bool hasBin(int major, int minor); - - CV_WRAP static bool hasEqualOrLessPtx(int major, int minor); - CV_WRAP static bool hasEqualOrGreater(int major, int minor); - CV_WRAP static bool hasEqualOrGreaterPtx(int major, int minor); - CV_WRAP static bool hasEqualOrGreaterBin(int major, int minor); -}; - -/** @brief Class providing functionality for querying the specified GPU properties. - */ -class CV_EXPORTS_W DeviceInfo -{ -public: - //! creates DeviceInfo object for the current GPU - CV_WRAP DeviceInfo(); - - /** @brief The constructors. - - @param device_id System index of the CUDA device starting with 0. - - Constructs the DeviceInfo object for the specified device. If device_id parameter is missed, it - constructs an object for the current device. - */ - CV_WRAP DeviceInfo(int device_id); - - /** @brief Returns system index of the CUDA device starting with 0. - */ - CV_WRAP int deviceID() const; - - //! ASCII string identifying device - const char* name() const; - - //! global memory available on device in bytes - CV_WRAP size_t totalGlobalMem() const; - - //! shared memory available per block in bytes - CV_WRAP size_t sharedMemPerBlock() const; - - //! 32-bit registers available per block - CV_WRAP int regsPerBlock() const; - - //! warp size in threads - CV_WRAP int warpSize() const; - - //! maximum pitch in bytes allowed by memory copies - CV_WRAP size_t memPitch() const; - - //! maximum number of threads per block - CV_WRAP int maxThreadsPerBlock() const; - - //! maximum size of each dimension of a block - CV_WRAP Vec3i maxThreadsDim() const; - - //! maximum size of each dimension of a grid - CV_WRAP Vec3i maxGridSize() const; - - //! clock frequency in kilohertz - CV_WRAP int clockRate() const; - - //! constant memory available on device in bytes - CV_WRAP size_t totalConstMem() const; - - //! major compute capability - CV_WRAP int majorVersion() const; - - //! minor compute capability - CV_WRAP int minorVersion() const; - - //! alignment requirement for textures - CV_WRAP size_t textureAlignment() const; - - //! pitch alignment requirement for texture references bound to pitched memory - CV_WRAP size_t texturePitchAlignment() const; - - //! number of multiprocessors on device - CV_WRAP int multiProcessorCount() const; - - //! specified whether there is a run time limit on kernels - CV_WRAP bool kernelExecTimeoutEnabled() const; - - //! device is integrated as opposed to discrete - CV_WRAP bool integrated() const; - - //! device can map host memory with cudaHostAlloc/cudaHostGetDevicePointer - CV_WRAP bool canMapHostMemory() const; - - enum ComputeMode - { - ComputeModeDefault, /**< default compute mode (Multiple threads can use cudaSetDevice with this device) */ - ComputeModeExclusive, /**< compute-exclusive-thread mode (Only one thread in one process will be able to use cudaSetDevice with this device) */ - ComputeModeProhibited, /**< compute-prohibited mode (No threads can use cudaSetDevice with this device) */ - ComputeModeExclusiveProcess /**< compute-exclusive-process mode (Many threads in one process will be able to use cudaSetDevice with this device) */ - }; - - //! compute mode - CV_WRAP DeviceInfo::ComputeMode computeMode() const; - - //! maximum 1D texture size - CV_WRAP int maxTexture1D() const; - - //! maximum 1D mipmapped texture size - CV_WRAP int maxTexture1DMipmap() const; - - //! maximum size for 1D textures bound to linear memory - CV_WRAP int maxTexture1DLinear() const; - - //! maximum 2D texture dimensions - CV_WRAP Vec2i maxTexture2D() const; - - //! maximum 2D mipmapped texture dimensions - CV_WRAP Vec2i maxTexture2DMipmap() const; - - //! maximum dimensions (width, height, pitch) for 2D textures bound to pitched memory - CV_WRAP Vec3i maxTexture2DLinear() const; - - //! maximum 2D texture dimensions if texture gather operations have to be performed - CV_WRAP Vec2i maxTexture2DGather() const; - - //! maximum 3D texture dimensions - CV_WRAP Vec3i maxTexture3D() const; - - //! maximum Cubemap texture dimensions - CV_WRAP int maxTextureCubemap() const; - - //! maximum 1D layered texture dimensions - CV_WRAP Vec2i maxTexture1DLayered() const; - - //! maximum 2D layered texture dimensions - CV_WRAP Vec3i maxTexture2DLayered() const; - - //! maximum Cubemap layered texture dimensions - CV_WRAP Vec2i maxTextureCubemapLayered() const; - - //! maximum 1D surface size - CV_WRAP int maxSurface1D() const; - - //! maximum 2D surface dimensions - CV_WRAP Vec2i maxSurface2D() const; - - //! maximum 3D surface dimensions - CV_WRAP Vec3i maxSurface3D() const; - - //! maximum 1D layered surface dimensions - CV_WRAP Vec2i maxSurface1DLayered() const; - - //! maximum 2D layered surface dimensions - CV_WRAP Vec3i maxSurface2DLayered() const; - - //! maximum Cubemap surface dimensions - CV_WRAP int maxSurfaceCubemap() const; - - //! maximum Cubemap layered surface dimensions - CV_WRAP Vec2i maxSurfaceCubemapLayered() const; - - //! alignment requirements for surfaces - CV_WRAP size_t surfaceAlignment() const; - - //! device can possibly execute multiple kernels concurrently - CV_WRAP bool concurrentKernels() const; - - //! device has ECC support enabled - CV_WRAP bool ECCEnabled() const; - - //! PCI bus ID of the device - CV_WRAP int pciBusID() const; - - //! PCI device ID of the device - CV_WRAP int pciDeviceID() const; - - //! PCI domain ID of the device - CV_WRAP int pciDomainID() const; - - //! true if device is a Tesla device using TCC driver, false otherwise - CV_WRAP bool tccDriver() const; - - //! number of asynchronous engines - CV_WRAP int asyncEngineCount() const; - - //! device shares a unified address space with the host - CV_WRAP bool unifiedAddressing() const; - - //! peak memory clock frequency in kilohertz - CV_WRAP int memoryClockRate() const; - - //! global memory bus width in bits - CV_WRAP int memoryBusWidth() const; - - //! size of L2 cache in bytes - CV_WRAP int l2CacheSize() const; - - //! maximum resident threads per multiprocessor - CV_WRAP int maxThreadsPerMultiProcessor() const; - - //! gets free and total device memory - CV_WRAP void queryMemory(size_t& totalMemory, size_t& freeMemory) const; - CV_WRAP size_t freeMemory() const; - CV_WRAP size_t totalMemory() const; - - /** @brief Provides information on CUDA feature support. - - @param feature_set Features to be checked. See cuda::FeatureSet. - - This function returns true if the device has the specified CUDA feature. Otherwise, it returns false - */ - bool supports(FeatureSet feature_set) const; - - /** @brief Checks the CUDA module and device compatibility. - - This function returns true if the CUDA module can be run on the specified device. Otherwise, it - returns false . - */ - CV_WRAP bool isCompatible() const; - -private: - int device_id_; -}; - -CV_EXPORTS_W void printCudaDeviceInfo(int device); -CV_EXPORTS_W void printShortCudaDeviceInfo(int device); - -/** @brief Converts an array to half precision floating number. - -@param _src input array. -@param _dst output array. -@param stream Stream for the asynchronous version. -@sa convertFp16 -*/ -CV_EXPORTS void convertFp16(InputArray _src, OutputArray _dst, Stream& stream = Stream::Null()); - -//! @} cudacore_init - -}} // namespace cv { namespace cuda { - - -#include "opencv2/core/cuda.inl.hpp" - -#endif /* OPENCV_CORE_CUDA_HPP */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CORE_CUDA_HPP +#define OPENCV_CORE_CUDA_HPP + +#ifndef __cplusplus +# error cuda.hpp header must be compiled as C++ +#endif + +#include "opencv2/core.hpp" +#include "opencv2/core/cuda_types.hpp" + +/** + @defgroup cuda CUDA-accelerated Computer Vision + @{ + @defgroup cudacore Core part + @{ + @defgroup cudacore_init Initialization and Information + @defgroup cudacore_struct Data Structures + @} + @} + */ + +namespace cv { namespace cuda { + +//! @addtogroup cudacore_struct +//! @{ + +//=================================================================================== +// GpuMat +//=================================================================================== + +/** @brief Base storage class for GPU memory with reference counting. + +Its interface matches the Mat interface with the following limitations: + +- no arbitrary dimensions support (only 2D) +- no functions that return references to their data (because references on GPU are not valid for + CPU) +- no expression templates technique support + +Beware that the latter limitation may lead to overloaded matrix operators that cause memory +allocations. The GpuMat class is convertible to cuda::PtrStepSz and cuda::PtrStep so it can be +passed directly to the kernel. + +@note In contrast with Mat, in most cases GpuMat::isContinuous() == false . This means that rows are +aligned to a size depending on the hardware. Single-row GpuMat is always a continuous matrix. + +@note You are not recommended to leave static or global GpuMat variables allocated, that is, to rely +on its destructor. The destruction order of such variables and CUDA context is undefined. GPU memory +release function returns error if the CUDA context has been destroyed before. + +Some member functions are described as a "Blocking Call" while some are described as a +"Non-Blocking Call". Blocking functions are synchronous to host. It is guaranteed that the GPU +operation is finished when the function returns. However, non-blocking functions are asynchronous to +host. Those functions may return even if the GPU operation is not finished. + +Compared to their blocking counterpart, non-blocking functions accept Stream as an additional +argument. If a non-default stream is passed, the GPU operation may overlap with operations in other +streams. + +@sa Mat + */ +class CV_EXPORTS_W GpuMat +{ +public: + class CV_EXPORTS_W Allocator + { + public: + virtual ~Allocator() {} + + // allocator must fill data, step and refcount fields + virtual bool allocate(GpuMat* mat, int rows, int cols, size_t elemSize) = 0; + virtual void free(GpuMat* mat) = 0; + }; + + //! default allocator + CV_WRAP static GpuMat::Allocator* defaultAllocator(); + CV_WRAP static void setDefaultAllocator(GpuMat::Allocator* allocator); + CV_WRAP static GpuMat::Allocator* getStdAllocator(); + + //! default constructor + CV_WRAP explicit GpuMat(GpuMat::Allocator* allocator = GpuMat::defaultAllocator()); + + //! constructs GpuMat of the specified size and type + CV_WRAP GpuMat(int rows, int cols, int type, GpuMat::Allocator* allocator = GpuMat::defaultAllocator()); + CV_WRAP GpuMat(Size size, int type, GpuMat::Allocator* allocator = GpuMat::defaultAllocator()); + + //! constructs GpuMat and fills it with the specified value _s + CV_WRAP GpuMat(int rows, int cols, int type, Scalar s, GpuMat::Allocator* allocator = GpuMat::defaultAllocator()); + CV_WRAP GpuMat(Size size, int type, Scalar s, GpuMat::Allocator* allocator = GpuMat::defaultAllocator()); + + //! copy constructor + CV_WRAP GpuMat(const GpuMat& m); + + //! constructor for GpuMat headers pointing to user-allocated data + GpuMat(int rows, int cols, int type, void* data, size_t step = Mat::AUTO_STEP); + GpuMat(Size size, int type, void* data, size_t step = Mat::AUTO_STEP); + + //! creates a GpuMat header for a part of the bigger matrix + CV_WRAP GpuMat(const GpuMat& m, Range rowRange, Range colRange); + CV_WRAP GpuMat(const GpuMat& m, Rect roi); + + //! builds GpuMat from host memory (Blocking call) + CV_WRAP explicit GpuMat(InputArray arr, GpuMat::Allocator* allocator = GpuMat::defaultAllocator()); + + //! destructor - calls release() + ~GpuMat(); + + //! assignment operators + GpuMat& operator =(const GpuMat& m); + + //! allocates new GpuMat data unless the GpuMat already has specified size and type + CV_WRAP void create(int rows, int cols, int type); + CV_WRAP void create(Size size, int type); + + //! decreases reference counter, deallocate the data when reference counter reaches 0 + CV_WRAP void release(); + + //! swaps with other smart pointer + CV_WRAP void swap(GpuMat& mat); + + /** @brief Performs data upload to GpuMat (Blocking call) + + This function copies data from host memory to device memory. As being a blocking call, it is + guaranteed that the copy operation is finished when this function returns. + */ + CV_WRAP void upload(InputArray arr); + + /** @brief Performs data upload to GpuMat (Non-Blocking call) + + This function copies data from host memory to device memory. As being a non-blocking call, this + function may return even if the copy operation is not finished. + + The copy operation may be overlapped with operations in other non-default streams if \p stream is + not the default stream and \p dst is HostMem allocated with HostMem::PAGE_LOCKED option. + */ + CV_WRAP void upload(InputArray arr, Stream& stream); + + /** @brief Performs data download from GpuMat (Blocking call) + + This function copies data from device memory to host memory. As being a blocking call, it is + guaranteed that the copy operation is finished when this function returns. + */ + CV_WRAP void download(OutputArray dst) const; + + /** @brief Performs data download from GpuMat (Non-Blocking call) + + This function copies data from device memory to host memory. As being a non-blocking call, this + function may return even if the copy operation is not finished. + + The copy operation may be overlapped with operations in other non-default streams if \p stream is + not the default stream and \p dst is HostMem allocated with HostMem::PAGE_LOCKED option. + */ + CV_WRAP void download(OutputArray dst, Stream& stream) const; + + //! returns deep copy of the GpuMat, i.e. the data is copied + CV_WRAP GpuMat clone() const; + + //! copies the GpuMat content to device memory (Blocking call) + void copyTo(OutputArray dst) const; + //! bindings overload which copies the GpuMat content to device memory (Blocking call) + CV_WRAP void copyTo(CV_OUT GpuMat& dst) const { + copyTo(static_cast(dst)); + } + + //! copies the GpuMat content to device memory (Non-Blocking call) + void copyTo(OutputArray dst, Stream& stream) const; + //! bindings overload which copies the GpuMat content to device memory (Non-Blocking call) + CV_WRAP void copyTo(CV_OUT GpuMat& dst, Stream& stream) const { + copyTo(static_cast(dst), stream); + } + + //! copies those GpuMat elements to "m" that are marked with non-zero mask elements (Blocking call) + void copyTo(OutputArray dst, InputArray mask) const; + //! bindings overload which copies those GpuMat elements to "m" that are marked with non-zero mask elements (Blocking call) + CV_WRAP void copyTo(CV_OUT GpuMat& dst, GpuMat& mask) const { + copyTo(static_cast(dst), static_cast(mask)); + } + + //! copies those GpuMat elements to "m" that are marked with non-zero mask elements (Non-Blocking call) + void copyTo(OutputArray dst, InputArray mask, Stream& stream) const; + //! bindings overload which copies those GpuMat elements to "m" that are marked with non-zero mask elements (Non-Blocking call) + CV_WRAP void copyTo(CV_OUT GpuMat& dst, GpuMat& mask, Stream& stream) const { + copyTo(static_cast(dst), static_cast(mask), stream); + } + + //! sets some of the GpuMat elements to s (Blocking call) + CV_WRAP GpuMat& setTo(Scalar s); + + //! sets some of the GpuMat elements to s (Non-Blocking call) + CV_WRAP GpuMat& setTo(Scalar s, Stream& stream); + + //! sets some of the GpuMat elements to s, according to the mask (Blocking call) + CV_WRAP GpuMat& setTo(Scalar s, InputArray mask); + + //! sets some of the GpuMat elements to s, according to the mask (Non-Blocking call) + CV_WRAP GpuMat& setTo(Scalar s, InputArray mask, Stream& stream); + + //! converts GpuMat to another datatype (Blocking call) + void convertTo(OutputArray dst, int rtype) const; + + //! converts GpuMat to another datatype (Non-Blocking call) + void convertTo(OutputArray dst, int rtype, Stream& stream) const; + //! bindings overload which converts GpuMat to another datatype (Non-Blocking call) + CV_WRAP void convertTo(CV_OUT GpuMat& dst, int rtype, Stream& stream) const { + convertTo(static_cast(dst), rtype, stream); + } + + //! converts GpuMat to another datatype with scaling (Blocking call) + void convertTo(OutputArray dst, int rtype, double alpha, double beta = 0.0) const; + //! bindings overload which converts GpuMat to another datatype with scaling(Blocking call) + CV_WRAP void convertTo(CV_OUT GpuMat& dst, int rtype, double alpha = 1.0, double beta = 0.0) const { + convertTo(static_cast(dst), rtype, alpha, beta); + } + + //! converts GpuMat to another datatype with scaling (Non-Blocking call) + void convertTo(OutputArray dst, int rtype, double alpha, Stream& stream) const; + + //! converts GpuMat to another datatype with scaling (Non-Blocking call) + void convertTo(OutputArray dst, int rtype, double alpha, double beta, Stream& stream) const; + //! bindings overload which converts GpuMat to another datatype with scaling (Non-Blocking call) + CV_WRAP void convertTo(CV_OUT GpuMat& dst, int rtype, double alpha, double beta, Stream& stream) const { + convertTo(static_cast(dst), rtype, alpha, beta, stream); + } + + CV_WRAP void assignTo(GpuMat& m, int type = -1) const; + + //! returns pointer to y-th row + uchar* ptr(int y = 0); + const uchar* ptr(int y = 0) const; + + //! template version of the above method + template _Tp* ptr(int y = 0); + template const _Tp* ptr(int y = 0) const; + + template operator PtrStepSz<_Tp>() const; + template operator PtrStep<_Tp>() const; + + //! returns a new GpuMat header for the specified row + CV_WRAP GpuMat row(int y) const; + + //! returns a new GpuMat header for the specified column + CV_WRAP GpuMat col(int x) const; + + //! ... for the specified row span + CV_WRAP GpuMat rowRange(int startrow, int endrow) const; + CV_WRAP GpuMat rowRange(Range r) const; + + //! ... for the specified column span + CV_WRAP GpuMat colRange(int startcol, int endcol) const; + CV_WRAP GpuMat colRange(Range r) const; + + //! extracts a rectangular sub-GpuMat (this is a generalized form of row, rowRange etc.) + GpuMat operator ()(Range rowRange, Range colRange) const; + GpuMat operator ()(Rect roi) const; + + //! creates alternative GpuMat header for the same data, with different + //! number of channels and/or different number of rows + CV_WRAP GpuMat reshape(int cn, int rows = 0) const; + + //! locates GpuMat header within a parent GpuMat + CV_WRAP void locateROI(Size& wholeSize, Point& ofs) const; + + //! moves/resizes the current GpuMat ROI inside the parent GpuMat + CV_WRAP GpuMat& adjustROI(int dtop, int dbottom, int dleft, int dright); + + //! returns true iff the GpuMat data is continuous + //! (i.e. when there are no gaps between successive rows) + CV_WRAP bool isContinuous() const; + + //! returns element size in bytes + CV_WRAP size_t elemSize() const; + + //! returns the size of element channel in bytes + CV_WRAP size_t elemSize1() const; + + //! returns element type + CV_WRAP int type() const; + + //! returns element type + CV_WRAP int depth() const; + + //! returns number of channels + CV_WRAP int channels() const; + + //! returns step/elemSize1() + CV_WRAP size_t step1() const; + + //! returns GpuMat size : width == number of columns, height == number of rows + CV_WRAP Size size() const; + + //! returns true if GpuMat data is NULL + CV_WRAP bool empty() const; + + // returns pointer to cuda memory + CV_WRAP void* cudaPtr() const; + + //! internal use method: updates the continuity flag + CV_WRAP void updateContinuityFlag(); + + /*! includes several bit-fields: + - the magic signature + - continuity flag + - depth + - number of channels + */ + int flags; + + //! the number of rows and columns + int rows, cols; + + //! a distance between successive rows in bytes; includes the gap if any + CV_PROP size_t step; + + //! pointer to the data + uchar* data; + + //! pointer to the reference counter; + //! when GpuMat points to user-allocated data, the pointer is NULL + int* refcount; + + //! helper fields used in locateROI and adjustROI + uchar* datastart; + const uchar* dataend; + + //! allocator + Allocator* allocator; +}; + +struct CV_EXPORTS_W GpuData +{ + explicit GpuData(size_t _size); + ~GpuData(); + + GpuData(const GpuData&) = delete; + GpuData& operator=(const GpuData&) = delete; + + GpuData(GpuData&&) = delete; + GpuData& operator=(GpuData&&) = delete; + + uchar* data; + size_t size; +}; + +class CV_EXPORTS_W GpuMatND +{ +public: + using SizeArray = std::vector; + using StepArray = std::vector; + using IndexArray = std::vector; + + //! destructor + ~GpuMatND(); + + //! default constructor + GpuMatND(); + + /** @overload + @param size Array of integers specifying an n-dimensional array shape. + @param type Array type. Use CV_8UC1, ..., CV_16FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + */ + GpuMatND(SizeArray size, int type); + + /** @overload + @param size Array of integers specifying an n-dimensional array shape. + @param type Array type. Use CV_8UC1, ..., CV_16FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param data Pointer to the user data. Matrix constructors that take data and step parameters do not + allocate matrix data. Instead, they just initialize the matrix header that points to the specified + data, which means that no data is copied. This operation is very efficient and can be used to + process external data using OpenCV functions. The external data is not automatically deallocated, so + you should take care of it. + @param step Array of _size.size() or _size.size()-1 steps in case of a multi-dimensional array + (if specified, the last step must be equal to the element size, otherwise it will be added as such). + If not specified, the matrix is assumed to be continuous. + */ + GpuMatND(SizeArray size, int type, void* data, StepArray step = StepArray()); + + /** @brief Allocates GPU memory. + Suppose there is some GPU memory already allocated. In that case, this method may choose to reuse that + GPU memory under the specific condition: it must be of the same size and type, not externally allocated, + the GPU memory is continuous(i.e., isContinuous() is true), and is not a sub-matrix of another GpuMatND + (i.e., isSubmatrix() is false). In other words, this method guarantees that the GPU memory allocated by + this method is always continuous and is not a sub-region of another GpuMatND. + */ + void create(SizeArray size, int type); + + void release(); + + void swap(GpuMatND& m) noexcept; + + /** @brief Creates a full copy of the array and the underlying data. + The method creates a full copy of the array. It mimics the behavior of Mat::clone(), i.e. + the original step is not taken into account. So, the array copy is a continuous array + occupying total()\*elemSize() bytes. + */ + GpuMatND clone() const; + + /** @overload + This overload is non-blocking, so it may return even if the copy operation is not finished. + */ + GpuMatND clone(Stream& stream) const; + + /** @brief Extracts a sub-matrix. + The operator makes a new header for the specified sub-array of \*this. + The operator is an O(1) operation, that is, no matrix data is copied. + @param ranges Array of selected ranges along each dimension. + */ + GpuMatND operator()(const std::vector& ranges) const; + + /** @brief Creates a GpuMat header for a 2D plane part of an n-dim matrix. + @note The returned GpuMat is constructed with the constructor for user-allocated data. + That is, It does not perform reference counting. + @note This function does not increment this GpuMatND's reference counter. + */ + GpuMat createGpuMatHeader(IndexArray idx, Range rowRange, Range colRange) const; + + /** @overload + Creates a GpuMat header if this GpuMatND is effectively 2D. + @note The returned GpuMat is constructed with the constructor for user-allocated data. + That is, It does not perform reference counting. + @note This function does not increment this GpuMatND's reference counter. + */ + GpuMat createGpuMatHeader() const; + + /** @brief Extracts a 2D plane part of an n-dim matrix. + It differs from createGpuMatHeader(IndexArray, Range, Range) in that it clones a part of this + GpuMatND to the returned GpuMat. + @note This operator does not increment this GpuMatND's reference counter; + */ + GpuMat operator()(IndexArray idx, Range rowRange, Range colRange) const; + + /** @brief Extracts a 2D plane part of an n-dim matrix if this GpuMatND is effectively 2D. + It differs from createGpuMatHeader() in that it clones a part of this GpuMatND. + @note This operator does not increment this GpuMatND's reference counter; + */ + operator GpuMat() const; + + GpuMatND(const GpuMatND&) = default; + GpuMatND& operator=(const GpuMatND&) = default; + +#if defined(__GNUC__) && __GNUC__ < 5 + // error: function '...' defaulted on its first declaration with an exception-specification + // that differs from the implicit declaration '...' + + GpuMatND(GpuMatND&&) = default; + GpuMatND& operator=(GpuMatND&&) = default; +#else + GpuMatND(GpuMatND&&) noexcept = default; + GpuMatND& operator=(GpuMatND&&) noexcept = default; +#endif + + void upload(InputArray src); + void upload(InputArray src, Stream& stream); + void download(OutputArray dst) const; + void download(OutputArray dst, Stream& stream) const; + + //! returns true iff the GpuMatND data is continuous + //! (i.e. when there are no gaps between successive rows) + bool isContinuous() const; + + //! returns true if the matrix is a sub-matrix of another matrix + bool isSubmatrix() const; + + //! returns element size in bytes + size_t elemSize() const; + + //! returns the size of element channel in bytes + size_t elemSize1() const; + + //! returns true if data is null + bool empty() const; + + //! returns true if not empty and points to external(user-allocated) gpu memory + bool external() const; + + //! returns pointer to the first byte of the GPU memory + uchar* getDevicePtr() const; + + //! returns the total number of array elements + size_t total() const; + + //! returns the size of underlying memory in bytes + size_t totalMemSize() const; + + //! returns element type + int type() const; + +private: + //! internal use + void setFields(SizeArray size, int type, StepArray step = StepArray()); + +public: + /*! includes several bit-fields: + - the magic signature + - continuity flag + - depth + - number of channels + */ + int flags; + + //! matrix dimensionality + int dims; + + //! shape of this array + SizeArray size; + + /*! step values + Their semantics is identical to the semantics of step for Mat. + */ + StepArray step; + +private: + /*! internal use + If this GpuMatND holds external memory, this is empty. + */ + std::shared_ptr data_; + + /*! internal use + If this GpuMatND manages memory with reference counting, this value is + always equal to data_->data. If this GpuMatND holds external memory, + data_ is empty and data points to the external memory. + */ + uchar* data; + + /*! internal use + If this GpuMatND is a sub-matrix of a larger matrix, this value is the + difference of the first byte between the sub-matrix and the whole matrix. + */ + size_t offset; +}; + +/** @brief Creates a continuous matrix. + +@param rows Row count. +@param cols Column count. +@param type Type of the matrix. +@param arr Destination matrix. This parameter changes only if it has a proper type and area ( +\f$\texttt{rows} \times \texttt{cols}\f$ ). + +Matrix is called continuous if its elements are stored continuously, that is, without gaps at the +end of each row. + */ +CV_EXPORTS_W void createContinuous(int rows, int cols, int type, OutputArray arr); + +/** @brief Ensures that the size of a matrix is big enough and the matrix has a proper type. + +@param rows Minimum desired number of rows. +@param cols Minimum desired number of columns. +@param type Desired matrix type. +@param arr Destination matrix. + +The function does not reallocate memory if the matrix has proper attributes already. + */ +CV_EXPORTS_W void ensureSizeIsEnough(int rows, int cols, int type, OutputArray arr); + +/** @brief Bindings overload to create a GpuMat from existing GPU memory. +@param rows Row count. +@param cols Column count. +@param type Type of the matrix. +@param cudaMemoryAddress Address of the allocated GPU memory on the device. This does not allocate matrix data. Instead, it just initializes the matrix header that points to the specified \a cudaMemoryAddress, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it. +@param step Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. If the parameter is missing (set to Mat::AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize(). See GpuMat::elemSize. +@note Overload for generation of bindings only, not exported or intended for use internally from C++. + */ +CV_EXPORTS_W GpuMat inline createGpuMatFromCudaMemory(int rows, int cols, int type, size_t cudaMemoryAddress, size_t step = Mat::AUTO_STEP) { + return GpuMat(rows, cols, type, reinterpret_cast(cudaMemoryAddress), step); +} + + /** @overload +@param size 2D array size: Size(cols, rows). In the Size() constructor, the number of rows and the number of columns go in the reverse order. +@param type Type of the matrix. +@param cudaMemoryAddress Address of the allocated GPU memory on the device. This does not allocate matrix data. Instead, it just initializes the matrix header that points to the specified \a cudaMemoryAddress, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it. +@param step Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. If the parameter is missing (set to Mat::AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize(). See GpuMat::elemSize. +@note Overload for generation of bindings only, not exported or intended for use internally from C++. + */ +CV_EXPORTS_W inline GpuMat createGpuMatFromCudaMemory(Size size, int type, size_t cudaMemoryAddress, size_t step = Mat::AUTO_STEP) { + return GpuMat(size, type, reinterpret_cast(cudaMemoryAddress), step); +} + +/** @brief BufferPool for use with CUDA streams + +BufferPool utilizes Stream's allocator to create new buffers for GpuMat's. It is +only useful when enabled with #setBufferPoolUsage. + +@code + setBufferPoolUsage(true); +@endcode + +@note #setBufferPoolUsage must be called \em before any Stream declaration. + +Users may specify custom allocator for Stream and may implement their own stream based +functions utilizing the same underlying GPU memory management. + +If custom allocator is not specified, BufferPool utilizes StackAllocator by +default. StackAllocator allocates a chunk of GPU device memory beforehand, +and when GpuMat is declared later on, it is given the pre-allocated memory. +This kind of strategy reduces the number of calls for memory allocating APIs +such as cudaMalloc or cudaMallocPitch. + +Below is an example that utilizes BufferPool with StackAllocator: + +@code + #include + + using namespace cv; + using namespace cv::cuda + + int main() + { + setBufferPoolUsage(true); // Tell OpenCV that we are going to utilize BufferPool + setBufferPoolConfig(getDevice(), 1024 * 1024 * 64, 2); // Allocate 64 MB, 2 stacks (default is 10 MB, 5 stacks) + + Stream stream1, stream2; // Each stream uses 1 stack + BufferPool pool1(stream1), pool2(stream2); + + GpuMat d_src1 = pool1.getBuffer(4096, 4096, CV_8UC1); // 16MB + GpuMat d_dst1 = pool1.getBuffer(4096, 4096, CV_8UC3); // 48MB, pool1 is now full + + GpuMat d_src2 = pool2.getBuffer(1024, 1024, CV_8UC1); // 1MB + GpuMat d_dst2 = pool2.getBuffer(1024, 1024, CV_8UC3); // 3MB + + cvtColor(d_src1, d_dst1, cv::COLOR_GRAY2BGR, 0, stream1); + cvtColor(d_src2, d_dst2, cv::COLOR_GRAY2BGR, 0, stream2); + } +@endcode + +If we allocate another GpuMat on pool1 in the above example, it will be carried out by +the DefaultAllocator since the stack for pool1 is full. + +@code + GpuMat d_add1 = pool1.getBuffer(1024, 1024, CV_8UC1); // Stack for pool1 is full, memory is allocated with DefaultAllocator +@endcode + +If a third stream is declared in the above example, allocating with #getBuffer +within that stream will also be carried out by the DefaultAllocator because we've run out of +stacks. + +@code + Stream stream3; // Only 2 stacks were allocated, we've run out of stacks + BufferPool pool3(stream3); + GpuMat d_src3 = pool3.getBuffer(1024, 1024, CV_8UC1); // Memory is allocated with DefaultAllocator +@endcode + +@warning When utilizing StackAllocator, deallocation order is important. + +Just like a stack, deallocation must be done in LIFO order. Below is an example of +erroneous usage that violates LIFO rule. If OpenCV is compiled in Debug mode, this +sample code will emit CV_Assert error. + +@code + int main() + { + setBufferPoolUsage(true); // Tell OpenCV that we are going to utilize BufferPool + Stream stream; // A default size (10 MB) stack is allocated to this stream + BufferPool pool(stream); + + GpuMat mat1 = pool.getBuffer(1024, 1024, CV_8UC1); // Allocate mat1 (1MB) + GpuMat mat2 = pool.getBuffer(1024, 1024, CV_8UC1); // Allocate mat2 (1MB) + + mat1.release(); // erroneous usage : mat2 must be deallocated before mat1 + } +@endcode + +Since C++ local variables are destroyed in the reverse order of construction, +the code sample below satisfies the LIFO rule. Local GpuMat's are deallocated +and the corresponding memory is automatically returned to the pool for later usage. + +@code + int main() + { + setBufferPoolUsage(true); // Tell OpenCV that we are going to utilize BufferPool + setBufferPoolConfig(getDevice(), 1024 * 1024 * 64, 2); // Allocate 64 MB, 2 stacks (default is 10 MB, 5 stacks) + + Stream stream1, stream2; // Each stream uses 1 stack + BufferPool pool1(stream1), pool2(stream2); + + for (int i = 0; i < 10; i++) + { + GpuMat d_src1 = pool1.getBuffer(4096, 4096, CV_8UC1); // 16MB + GpuMat d_dst1 = pool1.getBuffer(4096, 4096, CV_8UC3); // 48MB, pool1 is now full + + GpuMat d_src2 = pool2.getBuffer(1024, 1024, CV_8UC1); // 1MB + GpuMat d_dst2 = pool2.getBuffer(1024, 1024, CV_8UC3); // 3MB + + d_src1.setTo(Scalar(i), stream1); + d_src2.setTo(Scalar(i), stream2); + + cvtColor(d_src1, d_dst1, cv::COLOR_GRAY2BGR, 0, stream1); + cvtColor(d_src2, d_dst2, cv::COLOR_GRAY2BGR, 0, stream2); + // The order of destruction of the local variables is: + // d_dst2 => d_src2 => d_dst1 => d_src1 + // LIFO rule is satisfied, this code runs without error + } + } +@endcode + */ +class CV_EXPORTS_W BufferPool +{ +public: + + //! Gets the BufferPool for the given stream. + CV_WRAP explicit BufferPool(Stream& stream); + + //! Allocates a new GpuMat of given size and type. + CV_WRAP GpuMat getBuffer(int rows, int cols, int type); + +// WARNING: unreachable code using Ninja +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(push) +#pragma warning(disable: 4702) +#endif + //! Allocates a new GpuMat of given size and type. + CV_WRAP GpuMat getBuffer(Size size, int type) { return getBuffer(size.height, size.width, type); } +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(pop) +#endif + + //! Returns the allocator associated with the stream. + CV_WRAP Ptr getAllocator() const { return allocator_; } + +private: + Ptr allocator_; +}; + +//! BufferPool management (must be called before Stream creation) +CV_EXPORTS_W void setBufferPoolUsage(bool on); +CV_EXPORTS_W void setBufferPoolConfig(int deviceId, size_t stackSize, int stackCount); + +//=================================================================================== +// HostMem +//=================================================================================== + +/** @brief Class with reference counting wrapping special memory type allocation functions from CUDA. + +Its interface is also Mat-like but with additional memory type parameters. + +- **PAGE_LOCKED** sets a page locked memory type used commonly for fast and asynchronous + uploading/downloading data from/to GPU. +- **SHARED** specifies a zero copy memory allocation that enables mapping the host memory to GPU + address space, if supported. +- **WRITE_COMBINED** sets the write combined buffer that is not cached by CPU. Such buffers are + used to supply GPU with data when GPU only reads it. The advantage is a better CPU cache + utilization. + +@note Allocation size of such memory types is usually limited. For more details, see *CUDA 2.2 +Pinned Memory APIs* document or *CUDA C Programming Guide*. + */ +class CV_EXPORTS_W HostMem +{ +public: + enum AllocType { PAGE_LOCKED = 1, SHARED = 2, WRITE_COMBINED = 4 }; + + static MatAllocator* getAllocator(HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED); + + CV_WRAP explicit HostMem(HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED); + + HostMem(const HostMem& m); + + CV_WRAP HostMem(int rows, int cols, int type, HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED); + CV_WRAP HostMem(Size size, int type, HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED); + + //! creates from host memory with coping data + CV_WRAP explicit HostMem(InputArray arr, HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED); + + ~HostMem(); + + HostMem& operator =(const HostMem& m); + + //! swaps with other smart pointer + CV_WRAP void swap(HostMem& b); + + //! returns deep copy of the matrix, i.e. the data is copied + CV_WRAP HostMem clone() const; + + //! allocates new matrix data unless the matrix already has specified size and type. + CV_WRAP void create(int rows, int cols, int type); + void create(Size size, int type); + + //! creates alternative HostMem header for the same data, with different + //! number of channels and/or different number of rows + CV_WRAP HostMem reshape(int cn, int rows = 0) const; + + //! decrements reference counter and released memory if needed. + void release(); + + //! returns matrix header with disabled reference counting for HostMem data. + CV_WRAP Mat createMatHeader() const; + + /** @brief Maps CPU memory to GPU address space and creates the cuda::GpuMat header without reference counting + for it. + + This can be done only if memory was allocated with the SHARED flag and if it is supported by the + hardware. Laptops often share video and CPU memory, so address spaces can be mapped, which + eliminates an extra copy. + */ + GpuMat createGpuMatHeader() const; + + // Please see cv::Mat for descriptions + CV_WRAP bool isContinuous() const; + CV_WRAP size_t elemSize() const; + CV_WRAP size_t elemSize1() const; + CV_WRAP int type() const; + CV_WRAP int depth() const; + CV_WRAP int channels() const; + CV_WRAP size_t step1() const; + CV_WRAP Size size() const; + CV_WRAP bool empty() const; + + // Please see cv::Mat for descriptions + int flags; + int rows, cols; + CV_PROP size_t step; + + uchar* data; + int* refcount; + + uchar* datastart; + const uchar* dataend; + + AllocType alloc_type; +}; + +/** @brief Page-locks the memory of matrix and maps it for the device(s). + +@param m Input matrix. + */ +CV_EXPORTS_W void registerPageLocked(Mat& m); + +/** @brief Unmaps the memory of matrix and makes it pageable again. + +@param m Input matrix. + */ +CV_EXPORTS_W void unregisterPageLocked(Mat& m); + +//=================================================================================== +// Stream +//=================================================================================== + +/** @brief This class encapsulates a queue of asynchronous calls. + +@note Currently, you may face problems if an operation is enqueued twice with different data. Some +functions use the constant GPU memory, and next call may update the memory before the previous one +has been finished. But calling different operations asynchronously is safe because each operation +has its own constant buffer. Memory copy/upload/download/set operations to the buffers you hold are +also safe. + +@note The Stream class is not thread-safe. Please use different Stream objects for different CPU threads. + +@code +void thread1() +{ + cv::cuda::Stream stream1; + cv::cuda::func1(..., stream1); +} + +void thread2() +{ + cv::cuda::Stream stream2; + cv::cuda::func2(..., stream2); +} +@endcode + +@note By default all CUDA routines are launched in Stream::Null() object, if the stream is not specified by user. +In multi-threading environment the stream objects must be passed explicitly (see previous note). + */ +class CV_EXPORTS_W Stream +{ + typedef void (Stream::*bool_type)() const; + void this_type_does_not_support_comparisons() const {} + +public: + typedef void (*StreamCallback)(int status, void* userData); + + //! creates a new asynchronous stream + CV_WRAP Stream(); + + //! creates a new asynchronous stream with custom allocator + CV_WRAP Stream(const Ptr& allocator); + + /** @brief creates a new Stream using the cudaFlags argument to determine the behaviors of the stream + + @note The cudaFlags parameter is passed to the underlying api cudaStreamCreateWithFlags() and + supports the same parameter values. + @code + // creates an OpenCV cuda::Stream that manages an asynchronous, non-blocking, + // non-default CUDA stream + cv::cuda::Stream cvStream(cudaStreamNonBlocking); + @endcode + */ + CV_WRAP Stream(const size_t cudaFlags); + + /** @brief Returns true if the current stream queue is finished. Otherwise, it returns false. + */ + CV_WRAP bool queryIfComplete() const; + + /** @brief Blocks the current CPU thread until all operations in the stream are complete. + */ + CV_WRAP void waitForCompletion(); + + /** @brief Makes a compute stream wait on an event. + */ + CV_WRAP void waitEvent(const Event& event); + + /** @brief Adds a callback to be called on the host after all currently enqueued items in the stream have + completed. + + @note Callbacks must not make any CUDA API calls. Callbacks must not perform any synchronization + that may depend on outstanding device work or other callbacks that are not mandated to run earlier. + Callbacks without a mandated order (in independent streams) execute in undefined order and may be + serialized. + */ + void enqueueHostCallback(StreamCallback callback, void* userData); + + //! return Stream object for default CUDA stream + CV_WRAP static Stream& Null(); + + //! returns true if stream object is not default (!= 0) + operator bool_type() const; + + //! return Pointer to CUDA stream + CV_WRAP void* cudaPtr() const; + + class Impl; + +private: + Ptr impl_; + Stream(const Ptr& impl); + + friend struct StreamAccessor; + friend class BufferPool; + friend class DefaultDeviceInitializer; +}; + + +/** @brief Bindings overload to create a Stream object from the address stored in an existing CUDA Runtime API stream pointer (cudaStream_t). +@param cudaStreamMemoryAddress Memory address stored in a CUDA Runtime API stream pointer (cudaStream_t). The created Stream object does not perform any allocation or deallocation and simply wraps existing raw CUDA Runtime API stream pointer. +@note Overload for generation of bindings only, not exported or intended for use internally from C++. + */ +CV_EXPORTS_W Stream wrapStream(size_t cudaStreamMemoryAddress); + +class CV_EXPORTS_W Event +{ +public: + enum CreateFlags + { + DEFAULT = 0x00, /**< Default event flag */ + BLOCKING_SYNC = 0x01, /**< Event uses blocking synchronization */ + DISABLE_TIMING = 0x02, /**< Event will not record timing data */ + INTERPROCESS = 0x04 /**< Event is suitable for interprocess use. DisableTiming must be set */ + }; + + CV_WRAP explicit Event(const Event::CreateFlags flags = Event::CreateFlags::DEFAULT); + + //! records an event + CV_WRAP void record(Stream& stream = Stream::Null()); + + //! queries an event's status + CV_WRAP bool queryIfComplete() const; + + //! waits for an event to complete + CV_WRAP void waitForCompletion(); + + //! computes the elapsed time between events + CV_WRAP static float elapsedTime(const Event& start, const Event& end); + + class Impl; + +private: + Ptr impl_; + Event(const Ptr& impl); + + friend struct EventAccessor; +}; +CV_ENUM_FLAGS(Event::CreateFlags) + +//! @} cudacore_struct + +//=================================================================================== +// Initialization & Info +//=================================================================================== + +//! @addtogroup cudacore_init +//! @{ + +/** @brief Returns the number of installed CUDA-enabled devices. + +Use this function before any other CUDA functions calls. If OpenCV is compiled without CUDA support, +this function returns 0. If the CUDA driver is not installed, or is incompatible, this function +returns -1. + */ +CV_EXPORTS_W int getCudaEnabledDeviceCount(); + +/** @brief Sets a device and initializes it for the current thread. + +@param device System index of a CUDA device starting with 0. + +If the call of this function is omitted, a default device is initialized at the fist CUDA usage. + */ +CV_EXPORTS_W void setDevice(int device); + +/** @brief Returns the current device index set by cuda::setDevice or initialized by default. + */ +CV_EXPORTS_W int getDevice(); + +/** @brief Explicitly destroys and cleans up all resources associated with the current device in the current +process. + +Any subsequent API call to this device will reinitialize the device. + */ +CV_EXPORTS_W void resetDevice(); + +/** @brief Enumeration providing CUDA computing features. + */ +enum FeatureSet +{ + FEATURE_SET_COMPUTE_10 = 10, + FEATURE_SET_COMPUTE_11 = 11, + FEATURE_SET_COMPUTE_12 = 12, + FEATURE_SET_COMPUTE_13 = 13, + FEATURE_SET_COMPUTE_20 = 20, + FEATURE_SET_COMPUTE_21 = 21, + FEATURE_SET_COMPUTE_30 = 30, + FEATURE_SET_COMPUTE_32 = 32, + FEATURE_SET_COMPUTE_35 = 35, + FEATURE_SET_COMPUTE_50 = 50, + + GLOBAL_ATOMICS = FEATURE_SET_COMPUTE_11, + SHARED_ATOMICS = FEATURE_SET_COMPUTE_12, + NATIVE_DOUBLE = FEATURE_SET_COMPUTE_13, + WARP_SHUFFLE_FUNCTIONS = FEATURE_SET_COMPUTE_30, + DYNAMIC_PARALLELISM = FEATURE_SET_COMPUTE_35 +}; + +//! checks whether current device supports the given feature +CV_EXPORTS bool deviceSupports(FeatureSet feature_set); + +/** @brief Class providing a set of static methods to check what NVIDIA\* card architecture the CUDA module was +built for. + +According to the CUDA C Programming Guide Version 3.2: "PTX code produced for some specific compute +capability can always be compiled to binary code of greater or equal compute capability". + */ +class CV_EXPORTS_W TargetArchs +{ +public: + /** @brief The following method checks whether the module was built with the support of the given feature: + + @param feature_set Features to be checked. See :ocvcuda::FeatureSet. + */ + static bool builtWith(FeatureSet feature_set); + + /** @brief There is a set of methods to check whether the module contains intermediate (PTX) or binary CUDA + code for the given architecture(s): + + @param major Major compute capability version. + @param minor Minor compute capability version. + */ + CV_WRAP static bool has(int major, int minor); + CV_WRAP static bool hasPtx(int major, int minor); + CV_WRAP static bool hasBin(int major, int minor); + + CV_WRAP static bool hasEqualOrLessPtx(int major, int minor); + CV_WRAP static bool hasEqualOrGreater(int major, int minor); + CV_WRAP static bool hasEqualOrGreaterPtx(int major, int minor); + CV_WRAP static bool hasEqualOrGreaterBin(int major, int minor); +}; + +/** @brief Class providing functionality for querying the specified GPU properties. + */ +class CV_EXPORTS_W DeviceInfo +{ +public: + //! creates DeviceInfo object for the current GPU + CV_WRAP DeviceInfo(); + + /** @brief The constructors. + + @param device_id System index of the CUDA device starting with 0. + + Constructs the DeviceInfo object for the specified device. If device_id parameter is missed, it + constructs an object for the current device. + */ + CV_WRAP DeviceInfo(int device_id); + + /** @brief Returns system index of the CUDA device starting with 0. + */ + CV_WRAP int deviceID() const; + + //! ASCII string identifying device + const char* name() const; + + //! global memory available on device in bytes + CV_WRAP size_t totalGlobalMem() const; + + //! shared memory available per block in bytes + CV_WRAP size_t sharedMemPerBlock() const; + + //! 32-bit registers available per block + CV_WRAP int regsPerBlock() const; + + //! warp size in threads + CV_WRAP int warpSize() const; + + //! maximum pitch in bytes allowed by memory copies + CV_WRAP size_t memPitch() const; + + //! maximum number of threads per block + CV_WRAP int maxThreadsPerBlock() const; + + //! maximum size of each dimension of a block + CV_WRAP Vec3i maxThreadsDim() const; + + //! maximum size of each dimension of a grid + CV_WRAP Vec3i maxGridSize() const; + + //! clock frequency in kilohertz + CV_WRAP int clockRate() const; + + //! constant memory available on device in bytes + CV_WRAP size_t totalConstMem() const; + + //! major compute capability + CV_WRAP int majorVersion() const; + + //! minor compute capability + CV_WRAP int minorVersion() const; + + //! alignment requirement for textures + CV_WRAP size_t textureAlignment() const; + + //! pitch alignment requirement for texture references bound to pitched memory + CV_WRAP size_t texturePitchAlignment() const; + + //! number of multiprocessors on device + CV_WRAP int multiProcessorCount() const; + + //! specified whether there is a run time limit on kernels + CV_WRAP bool kernelExecTimeoutEnabled() const; + + //! device is integrated as opposed to discrete + CV_WRAP bool integrated() const; + + //! device can map host memory with cudaHostAlloc/cudaHostGetDevicePointer + CV_WRAP bool canMapHostMemory() const; + + enum ComputeMode + { + ComputeModeDefault, /**< default compute mode (Multiple threads can use cudaSetDevice with this device) */ + ComputeModeExclusive, /**< compute-exclusive-thread mode (Only one thread in one process will be able to use cudaSetDevice with this device) */ + ComputeModeProhibited, /**< compute-prohibited mode (No threads can use cudaSetDevice with this device) */ + ComputeModeExclusiveProcess /**< compute-exclusive-process mode (Many threads in one process will be able to use cudaSetDevice with this device) */ + }; + + //! compute mode + CV_WRAP DeviceInfo::ComputeMode computeMode() const; + + //! maximum 1D texture size + CV_WRAP int maxTexture1D() const; + + //! maximum 1D mipmapped texture size + CV_WRAP int maxTexture1DMipmap() const; + + //! maximum size for 1D textures bound to linear memory + CV_WRAP int maxTexture1DLinear() const; + + //! maximum 2D texture dimensions + CV_WRAP Vec2i maxTexture2D() const; + + //! maximum 2D mipmapped texture dimensions + CV_WRAP Vec2i maxTexture2DMipmap() const; + + //! maximum dimensions (width, height, pitch) for 2D textures bound to pitched memory + CV_WRAP Vec3i maxTexture2DLinear() const; + + //! maximum 2D texture dimensions if texture gather operations have to be performed + CV_WRAP Vec2i maxTexture2DGather() const; + + //! maximum 3D texture dimensions + CV_WRAP Vec3i maxTexture3D() const; + + //! maximum Cubemap texture dimensions + CV_WRAP int maxTextureCubemap() const; + + //! maximum 1D layered texture dimensions + CV_WRAP Vec2i maxTexture1DLayered() const; + + //! maximum 2D layered texture dimensions + CV_WRAP Vec3i maxTexture2DLayered() const; + + //! maximum Cubemap layered texture dimensions + CV_WRAP Vec2i maxTextureCubemapLayered() const; + + //! maximum 1D surface size + CV_WRAP int maxSurface1D() const; + + //! maximum 2D surface dimensions + CV_WRAP Vec2i maxSurface2D() const; + + //! maximum 3D surface dimensions + CV_WRAP Vec3i maxSurface3D() const; + + //! maximum 1D layered surface dimensions + CV_WRAP Vec2i maxSurface1DLayered() const; + + //! maximum 2D layered surface dimensions + CV_WRAP Vec3i maxSurface2DLayered() const; + + //! maximum Cubemap surface dimensions + CV_WRAP int maxSurfaceCubemap() const; + + //! maximum Cubemap layered surface dimensions + CV_WRAP Vec2i maxSurfaceCubemapLayered() const; + + //! alignment requirements for surfaces + CV_WRAP size_t surfaceAlignment() const; + + //! device can possibly execute multiple kernels concurrently + CV_WRAP bool concurrentKernels() const; + + //! device has ECC support enabled + CV_WRAP bool ECCEnabled() const; + + //! PCI bus ID of the device + CV_WRAP int pciBusID() const; + + //! PCI device ID of the device + CV_WRAP int pciDeviceID() const; + + //! PCI domain ID of the device + CV_WRAP int pciDomainID() const; + + //! true if device is a Tesla device using TCC driver, false otherwise + CV_WRAP bool tccDriver() const; + + //! number of asynchronous engines + CV_WRAP int asyncEngineCount() const; + + //! device shares a unified address space with the host + CV_WRAP bool unifiedAddressing() const; + + //! peak memory clock frequency in kilohertz + CV_WRAP int memoryClockRate() const; + + //! global memory bus width in bits + CV_WRAP int memoryBusWidth() const; + + //! size of L2 cache in bytes + CV_WRAP int l2CacheSize() const; + + //! maximum resident threads per multiprocessor + CV_WRAP int maxThreadsPerMultiProcessor() const; + + //! gets free and total device memory + CV_WRAP void queryMemory(size_t& totalMemory, size_t& freeMemory) const; + CV_WRAP size_t freeMemory() const; + CV_WRAP size_t totalMemory() const; + + /** @brief Provides information on CUDA feature support. + + @param feature_set Features to be checked. See cuda::FeatureSet. + + This function returns true if the device has the specified CUDA feature. Otherwise, it returns false + */ + bool supports(FeatureSet feature_set) const; + + /** @brief Checks the CUDA module and device compatibility. + + This function returns true if the CUDA module can be run on the specified device. Otherwise, it + returns false . + */ + CV_WRAP bool isCompatible() const; + +private: + int device_id_; +}; + +CV_EXPORTS_W void printCudaDeviceInfo(int device); +CV_EXPORTS_W void printShortCudaDeviceInfo(int device); + +/** @brief Converts an array to half precision floating number. + +@param _src input array. +@param _dst output array. +@param stream Stream for the asynchronous version. +@sa convertFp16 +*/ +CV_EXPORTS void convertFp16(InputArray _src, OutputArray _dst, Stream& stream = Stream::Null()); + +//! @} cudacore_init + +}} // namespace cv { namespace cuda { + + +#include "opencv2/core/cuda.inl.hpp" + +#endif /* OPENCV_CORE_CUDA_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda.inl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda.inl.hpp index 9390b3a529..9eae299806 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda.inl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda.inl.hpp @@ -1,763 +1,763 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CORE_CUDAINL_HPP -#define OPENCV_CORE_CUDAINL_HPP - -#include "opencv2/core/cuda.hpp" - -//! @cond IGNORED - -namespace cv { namespace cuda { - -//=================================================================================== -// GpuMat -//=================================================================================== - -inline -GpuMat::GpuMat(Allocator* allocator_) - : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) -{} - -inline -GpuMat::GpuMat(int rows_, int cols_, int type_, Allocator* allocator_) - : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) -{ - if (rows_ > 0 && cols_ > 0) - create(rows_, cols_, type_); -} - -inline -GpuMat::GpuMat(Size size_, int type_, Allocator* allocator_) - : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) -{ - if (size_.height > 0 && size_.width > 0) - create(size_.height, size_.width, type_); -} - -// WARNING: unreachable code using Ninja -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(push) -#pragma warning(disable: 4702) -#endif -inline -GpuMat::GpuMat(int rows_, int cols_, int type_, Scalar s_, Allocator* allocator_) - : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) -{ - if (rows_ > 0 && cols_ > 0) - { - create(rows_, cols_, type_); - setTo(s_); - } -} - -inline -GpuMat::GpuMat(Size size_, int type_, Scalar s_, Allocator* allocator_) - : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) -{ - if (size_.height > 0 && size_.width > 0) - { - create(size_.height, size_.width, type_); - setTo(s_); - } -} -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(pop) -#endif - -inline -GpuMat::GpuMat(const GpuMat& m) - : flags(m.flags), rows(m.rows), cols(m.cols), step(m.step), data(m.data), refcount(m.refcount), datastart(m.datastart), dataend(m.dataend), allocator(m.allocator) -{ - if (refcount) - CV_XADD(refcount, 1); -} - -inline -GpuMat::GpuMat(InputArray arr, Allocator* allocator_) : - flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) -{ - upload(arr); -} - -inline -GpuMat::~GpuMat() -{ - release(); -} - -inline -GpuMat& GpuMat::operator =(const GpuMat& m) -{ - if (this != &m) - { - GpuMat temp(m); - swap(temp); - } - - return *this; -} - -inline -void GpuMat::create(Size size_, int type_) -{ - create(size_.height, size_.width, type_); -} - -inline -void GpuMat::swap(GpuMat& b) -{ - std::swap(flags, b.flags); - std::swap(rows, b.rows); - std::swap(cols, b.cols); - std::swap(step, b.step); - std::swap(data, b.data); - std::swap(datastart, b.datastart); - std::swap(dataend, b.dataend); - std::swap(refcount, b.refcount); - std::swap(allocator, b.allocator); -} - -inline -GpuMat GpuMat::clone() const -{ - GpuMat m; - copyTo(m); - return m; -} - -// WARNING: unreachable code using Ninja -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(push) -#pragma warning(disable: 4702) -#endif -inline -void GpuMat::copyTo(OutputArray dst, InputArray mask) const -{ - copyTo(dst, mask, Stream::Null()); -} -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(pop) -#endif - -inline -GpuMat& GpuMat::setTo(Scalar s) -{ - return setTo(s, Stream::Null()); -} - -inline -GpuMat& GpuMat::setTo(Scalar s, InputArray mask) -{ - return setTo(s, mask, Stream::Null()); -} - -// WARNING: unreachable code using Ninja -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(push) -#pragma warning(disable: 4702) -#endif -inline -void GpuMat::convertTo(OutputArray dst, int rtype) const -{ - convertTo(dst, rtype, Stream::Null()); -} - -inline -void GpuMat::convertTo(OutputArray dst, int rtype, double alpha, double beta) const -{ - convertTo(dst, rtype, alpha, beta, Stream::Null()); -} -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(pop) -#endif - -inline -void GpuMat::convertTo(OutputArray dst, int rtype, double alpha, Stream& stream) const -{ - convertTo(dst, rtype, alpha, 0.0, stream); -} - -inline -void GpuMat::assignTo(GpuMat& m, int _type) const -{ - if (_type < 0) - m = *this; - else - convertTo(m, _type); -} - -inline -uchar* GpuMat::ptr(int y) -{ - CV_DbgAssert( (unsigned)y < (unsigned)rows ); - return data + step * y; -} - -inline -const uchar* GpuMat::ptr(int y) const -{ - CV_DbgAssert( (unsigned)y < (unsigned)rows ); - return data + step * y; -} - -template inline -_Tp* GpuMat::ptr(int y) -{ - return (_Tp*)ptr(y); -} - -template inline -const _Tp* GpuMat::ptr(int y) const -{ - return (const _Tp*)ptr(y); -} - -template inline -GpuMat::operator PtrStepSz() const -{ - return PtrStepSz(rows, cols, (T*)data, step); -} - -template inline -GpuMat::operator PtrStep() const -{ - return PtrStep((T*)data, step); -} - -inline -GpuMat GpuMat::row(int y) const -{ - return GpuMat(*this, Range(y, y+1), Range::all()); -} - -inline -GpuMat GpuMat::col(int x) const -{ - return GpuMat(*this, Range::all(), Range(x, x+1)); -} - -inline -GpuMat GpuMat::rowRange(int startrow, int endrow) const -{ - return GpuMat(*this, Range(startrow, endrow), Range::all()); -} - -inline -GpuMat GpuMat::rowRange(Range r) const -{ - return GpuMat(*this, r, Range::all()); -} - -inline -GpuMat GpuMat::colRange(int startcol, int endcol) const -{ - return GpuMat(*this, Range::all(), Range(startcol, endcol)); -} - -inline -GpuMat GpuMat::colRange(Range r) const -{ - return GpuMat(*this, Range::all(), r); -} - -inline -GpuMat GpuMat::operator ()(Range rowRange_, Range colRange_) const -{ - return GpuMat(*this, rowRange_, colRange_); -} - -inline -GpuMat GpuMat::operator ()(Rect roi) const -{ - return GpuMat(*this, roi); -} - -inline -bool GpuMat::isContinuous() const -{ - return (flags & Mat::CONTINUOUS_FLAG) != 0; -} - -inline -size_t GpuMat::elemSize() const -{ - return CV_ELEM_SIZE(flags); -} - -inline -size_t GpuMat::elemSize1() const -{ - return CV_ELEM_SIZE1(flags); -} - -inline -int GpuMat::type() const -{ - return CV_MAT_TYPE(flags); -} - -inline -int GpuMat::depth() const -{ - return CV_MAT_DEPTH(flags); -} - -inline -int GpuMat::channels() const -{ - return CV_MAT_CN(flags); -} - -inline -size_t GpuMat::step1() const -{ - return step / elemSize1(); -} - -inline -Size GpuMat::size() const -{ - return Size(cols, rows); -} - -inline -bool GpuMat::empty() const -{ - return data == 0; -} - -inline -void* GpuMat::cudaPtr() const -{ - return data; -} - -static inline -GpuMat createContinuous(int rows, int cols, int type) -{ - GpuMat m; - createContinuous(rows, cols, type, m); - return m; -} - -static inline -void createContinuous(Size size, int type, OutputArray arr) -{ - createContinuous(size.height, size.width, type, arr); -} - -static inline -GpuMat createContinuous(Size size, int type) -{ - GpuMat m; - createContinuous(size, type, m); - return m; -} - -static inline -void ensureSizeIsEnough(Size size, int type, OutputArray arr) -{ - ensureSizeIsEnough(size.height, size.width, type, arr); -} - -static inline -void swap(GpuMat& a, GpuMat& b) -{ - a.swap(b); -} - -//=================================================================================== -// GpuMatND -//=================================================================================== - -inline -GpuMatND::GpuMatND() : - flags(0), dims(0), data(nullptr), offset(0) -{ -} - -inline -GpuMatND::GpuMatND(SizeArray _size, int _type) : - flags(0), dims(0), data(nullptr), offset(0) -{ - create(std::move(_size), _type); -} - -inline -void GpuMatND::swap(GpuMatND& m) noexcept -{ - std::swap(*this, m); -} - -inline -bool GpuMatND::isContinuous() const -{ - return (flags & Mat::CONTINUOUS_FLAG) != 0; -} - -inline -bool GpuMatND::isSubmatrix() const -{ - return (flags & Mat::SUBMATRIX_FLAG) != 0; -} - -inline -size_t GpuMatND::elemSize() const -{ - return CV_ELEM_SIZE(flags); -} - -inline -size_t GpuMatND::elemSize1() const -{ - return CV_ELEM_SIZE1(flags); -} - -inline -bool GpuMatND::empty() const -{ - return data == nullptr; -} - -inline -bool GpuMatND::external() const -{ - return !empty() && data_.use_count() == 0; -} - -inline -uchar* GpuMatND::getDevicePtr() const -{ - return data + offset; -} - -inline -size_t GpuMatND::total() const -{ - size_t p = 1; - for(auto s : size) - p *= s; - return p; -} - -inline -size_t GpuMatND::totalMemSize() const -{ - return size[0] * step[0]; -} - -inline -int GpuMatND::type() const -{ - return CV_MAT_TYPE(flags); -} - -//=================================================================================== -// HostMem -//=================================================================================== - -inline -HostMem::HostMem(AllocType alloc_type_) - : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(alloc_type_) -{ -} - -inline -HostMem::HostMem(const HostMem& m) - : flags(m.flags), rows(m.rows), cols(m.cols), step(m.step), data(m.data), refcount(m.refcount), datastart(m.datastart), dataend(m.dataend), alloc_type(m.alloc_type) -{ - if( refcount ) - CV_XADD(refcount, 1); -} - -inline -HostMem::HostMem(int rows_, int cols_, int type_, AllocType alloc_type_) - : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(alloc_type_) -{ - if (rows_ > 0 && cols_ > 0) - create(rows_, cols_, type_); -} - -inline -HostMem::HostMem(Size size_, int type_, AllocType alloc_type_) - : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(alloc_type_) -{ - if (size_.height > 0 && size_.width > 0) - create(size_.height, size_.width, type_); -} - -inline -HostMem::HostMem(InputArray arr, AllocType alloc_type_) - : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(alloc_type_) -{ - arr.getMat().copyTo(*this); -} - -inline -HostMem::~HostMem() -{ - release(); -} - -inline -HostMem& HostMem::operator =(const HostMem& m) -{ - if (this != &m) - { - HostMem temp(m); - swap(temp); - } - - return *this; -} - -inline -void HostMem::swap(HostMem& b) -{ - std::swap(flags, b.flags); - std::swap(rows, b.rows); - std::swap(cols, b.cols); - std::swap(step, b.step); - std::swap(data, b.data); - std::swap(datastart, b.datastart); - std::swap(dataend, b.dataend); - std::swap(refcount, b.refcount); - std::swap(alloc_type, b.alloc_type); -} - -inline -HostMem HostMem::clone() const -{ - HostMem m(size(), type(), alloc_type); - createMatHeader().copyTo(m); - return m; -} - -inline -void HostMem::create(Size size_, int type_) -{ - create(size_.height, size_.width, type_); -} - -inline -Mat HostMem::createMatHeader() const -{ - return Mat(size(), type(), data, step); -} - -inline -bool HostMem::isContinuous() const -{ - return (flags & Mat::CONTINUOUS_FLAG) != 0; -} - -inline -size_t HostMem::elemSize() const -{ - return CV_ELEM_SIZE(flags); -} - -inline -size_t HostMem::elemSize1() const -{ - return CV_ELEM_SIZE1(flags); -} - -inline -int HostMem::type() const -{ - return CV_MAT_TYPE(flags); -} - -inline -int HostMem::depth() const -{ - return CV_MAT_DEPTH(flags); -} - -inline -int HostMem::channels() const -{ - return CV_MAT_CN(flags); -} - -inline -size_t HostMem::step1() const -{ - return step / elemSize1(); -} - -inline -Size HostMem::size() const -{ - return Size(cols, rows); -} - -inline -bool HostMem::empty() const -{ - return data == 0; -} - -static inline -void swap(HostMem& a, HostMem& b) -{ - a.swap(b); -} - -//=================================================================================== -// Stream -//=================================================================================== - -inline -Stream::Stream(const Ptr& impl) - : impl_(impl) -{ -} - -//=================================================================================== -// Event -//=================================================================================== - -inline -Event::Event(const Ptr& impl) - : impl_(impl) -{ -} - -//=================================================================================== -// Initialization & Info -//=================================================================================== - -// WARNING: unreachable code using Ninja -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(push) -#pragma warning(disable: 4702) -#endif -inline -bool TargetArchs::has(int major, int minor) -{ - return hasPtx(major, minor) || hasBin(major, minor); -} - -inline -bool TargetArchs::hasEqualOrGreater(int major, int minor) -{ - return hasEqualOrGreaterPtx(major, minor) || hasEqualOrGreaterBin(major, minor); -} - -inline -DeviceInfo::DeviceInfo() -{ - device_id_ = getDevice(); -} -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(pop) -#endif - -inline -DeviceInfo::DeviceInfo(int device_id) -{ - CV_Assert( device_id >= 0 && device_id < getCudaEnabledDeviceCount() ); - device_id_ = device_id; -} - -// WARNING: unreachable code using Ninja -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(push) -#pragma warning(disable: 4702) -#endif -inline -int DeviceInfo::deviceID() const -{ - return device_id_; -} - -inline -size_t DeviceInfo::freeMemory() const -{ - size_t _totalMemory = 0, _freeMemory = 0; - queryMemory(_totalMemory, _freeMemory); - return _freeMemory; -} - -inline -size_t DeviceInfo::totalMemory() const -{ - size_t _totalMemory = 0, _freeMemory = 0; - queryMemory(_totalMemory, _freeMemory); - return _totalMemory; -} - -inline -bool DeviceInfo::supports(FeatureSet feature_set) const -{ - int version = majorVersion() * 10 + minorVersion(); - return version >= feature_set; -} -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(pop) -#endif - - -}} // namespace cv { namespace cuda { - -//=================================================================================== -// Mat -//=================================================================================== - -namespace cv { - -inline -Mat::Mat(const cuda::GpuMat& m) - : flags(0), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows) -{ - m.download(*this); -} - -} - -//! @endcond - -#endif // OPENCV_CORE_CUDAINL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CORE_CUDAINL_HPP +#define OPENCV_CORE_CUDAINL_HPP + +#include "opencv2/core/cuda.hpp" + +//! @cond IGNORED + +namespace cv { namespace cuda { + +//=================================================================================== +// GpuMat +//=================================================================================== + +inline +GpuMat::GpuMat(Allocator* allocator_) + : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) +{} + +inline +GpuMat::GpuMat(int rows_, int cols_, int type_, Allocator* allocator_) + : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) +{ + if (rows_ > 0 && cols_ > 0) + create(rows_, cols_, type_); +} + +inline +GpuMat::GpuMat(Size size_, int type_, Allocator* allocator_) + : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) +{ + if (size_.height > 0 && size_.width > 0) + create(size_.height, size_.width, type_); +} + +// WARNING: unreachable code using Ninja +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(push) +#pragma warning(disable: 4702) +#endif +inline +GpuMat::GpuMat(int rows_, int cols_, int type_, Scalar s_, Allocator* allocator_) + : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) +{ + if (rows_ > 0 && cols_ > 0) + { + create(rows_, cols_, type_); + setTo(s_); + } +} + +inline +GpuMat::GpuMat(Size size_, int type_, Scalar s_, Allocator* allocator_) + : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) +{ + if (size_.height > 0 && size_.width > 0) + { + create(size_.height, size_.width, type_); + setTo(s_); + } +} +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(pop) +#endif + +inline +GpuMat::GpuMat(const GpuMat& m) + : flags(m.flags), rows(m.rows), cols(m.cols), step(m.step), data(m.data), refcount(m.refcount), datastart(m.datastart), dataend(m.dataend), allocator(m.allocator) +{ + if (refcount) + CV_XADD(refcount, 1); +} + +inline +GpuMat::GpuMat(InputArray arr, Allocator* allocator_) : + flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) +{ + upload(arr); +} + +inline +GpuMat::~GpuMat() +{ + release(); +} + +inline +GpuMat& GpuMat::operator =(const GpuMat& m) +{ + if (this != &m) + { + GpuMat temp(m); + swap(temp); + } + + return *this; +} + +inline +void GpuMat::create(Size size_, int type_) +{ + create(size_.height, size_.width, type_); +} + +inline +void GpuMat::swap(GpuMat& b) +{ + std::swap(flags, b.flags); + std::swap(rows, b.rows); + std::swap(cols, b.cols); + std::swap(step, b.step); + std::swap(data, b.data); + std::swap(datastart, b.datastart); + std::swap(dataend, b.dataend); + std::swap(refcount, b.refcount); + std::swap(allocator, b.allocator); +} + +inline +GpuMat GpuMat::clone() const +{ + GpuMat m; + copyTo(m); + return m; +} + +// WARNING: unreachable code using Ninja +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(push) +#pragma warning(disable: 4702) +#endif +inline +void GpuMat::copyTo(OutputArray dst, InputArray mask) const +{ + copyTo(dst, mask, Stream::Null()); +} +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(pop) +#endif + +inline +GpuMat& GpuMat::setTo(Scalar s) +{ + return setTo(s, Stream::Null()); +} + +inline +GpuMat& GpuMat::setTo(Scalar s, InputArray mask) +{ + return setTo(s, mask, Stream::Null()); +} + +// WARNING: unreachable code using Ninja +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(push) +#pragma warning(disable: 4702) +#endif +inline +void GpuMat::convertTo(OutputArray dst, int rtype) const +{ + convertTo(dst, rtype, Stream::Null()); +} + +inline +void GpuMat::convertTo(OutputArray dst, int rtype, double alpha, double beta) const +{ + convertTo(dst, rtype, alpha, beta, Stream::Null()); +} +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(pop) +#endif + +inline +void GpuMat::convertTo(OutputArray dst, int rtype, double alpha, Stream& stream) const +{ + convertTo(dst, rtype, alpha, 0.0, stream); +} + +inline +void GpuMat::assignTo(GpuMat& m, int _type) const +{ + if (_type < 0) + m = *this; + else + convertTo(m, _type); +} + +inline +uchar* GpuMat::ptr(int y) +{ + CV_DbgAssert( (unsigned)y < (unsigned)rows ); + return data + step * y; +} + +inline +const uchar* GpuMat::ptr(int y) const +{ + CV_DbgAssert( (unsigned)y < (unsigned)rows ); + return data + step * y; +} + +template inline +_Tp* GpuMat::ptr(int y) +{ + return (_Tp*)ptr(y); +} + +template inline +const _Tp* GpuMat::ptr(int y) const +{ + return (const _Tp*)ptr(y); +} + +template inline +GpuMat::operator PtrStepSz() const +{ + return PtrStepSz(rows, cols, (T*)data, step); +} + +template inline +GpuMat::operator PtrStep() const +{ + return PtrStep((T*)data, step); +} + +inline +GpuMat GpuMat::row(int y) const +{ + return GpuMat(*this, Range(y, y+1), Range::all()); +} + +inline +GpuMat GpuMat::col(int x) const +{ + return GpuMat(*this, Range::all(), Range(x, x+1)); +} + +inline +GpuMat GpuMat::rowRange(int startrow, int endrow) const +{ + return GpuMat(*this, Range(startrow, endrow), Range::all()); +} + +inline +GpuMat GpuMat::rowRange(Range r) const +{ + return GpuMat(*this, r, Range::all()); +} + +inline +GpuMat GpuMat::colRange(int startcol, int endcol) const +{ + return GpuMat(*this, Range::all(), Range(startcol, endcol)); +} + +inline +GpuMat GpuMat::colRange(Range r) const +{ + return GpuMat(*this, Range::all(), r); +} + +inline +GpuMat GpuMat::operator ()(Range rowRange_, Range colRange_) const +{ + return GpuMat(*this, rowRange_, colRange_); +} + +inline +GpuMat GpuMat::operator ()(Rect roi) const +{ + return GpuMat(*this, roi); +} + +inline +bool GpuMat::isContinuous() const +{ + return (flags & Mat::CONTINUOUS_FLAG) != 0; +} + +inline +size_t GpuMat::elemSize() const +{ + return CV_ELEM_SIZE(flags); +} + +inline +size_t GpuMat::elemSize1() const +{ + return CV_ELEM_SIZE1(flags); +} + +inline +int GpuMat::type() const +{ + return CV_MAT_TYPE(flags); +} + +inline +int GpuMat::depth() const +{ + return CV_MAT_DEPTH(flags); +} + +inline +int GpuMat::channels() const +{ + return CV_MAT_CN(flags); +} + +inline +size_t GpuMat::step1() const +{ + return step / elemSize1(); +} + +inline +Size GpuMat::size() const +{ + return Size(cols, rows); +} + +inline +bool GpuMat::empty() const +{ + return data == 0; +} + +inline +void* GpuMat::cudaPtr() const +{ + return data; +} + +static inline +GpuMat createContinuous(int rows, int cols, int type) +{ + GpuMat m; + createContinuous(rows, cols, type, m); + return m; +} + +static inline +void createContinuous(Size size, int type, OutputArray arr) +{ + createContinuous(size.height, size.width, type, arr); +} + +static inline +GpuMat createContinuous(Size size, int type) +{ + GpuMat m; + createContinuous(size, type, m); + return m; +} + +static inline +void ensureSizeIsEnough(Size size, int type, OutputArray arr) +{ + ensureSizeIsEnough(size.height, size.width, type, arr); +} + +static inline +void swap(GpuMat& a, GpuMat& b) +{ + a.swap(b); +} + +//=================================================================================== +// GpuMatND +//=================================================================================== + +inline +GpuMatND::GpuMatND() : + flags(0), dims(0), data(nullptr), offset(0) +{ +} + +inline +GpuMatND::GpuMatND(SizeArray _size, int _type) : + flags(0), dims(0), data(nullptr), offset(0) +{ + create(std::move(_size), _type); +} + +inline +void GpuMatND::swap(GpuMatND& m) noexcept +{ + std::swap(*this, m); +} + +inline +bool GpuMatND::isContinuous() const +{ + return (flags & Mat::CONTINUOUS_FLAG) != 0; +} + +inline +bool GpuMatND::isSubmatrix() const +{ + return (flags & Mat::SUBMATRIX_FLAG) != 0; +} + +inline +size_t GpuMatND::elemSize() const +{ + return CV_ELEM_SIZE(flags); +} + +inline +size_t GpuMatND::elemSize1() const +{ + return CV_ELEM_SIZE1(flags); +} + +inline +bool GpuMatND::empty() const +{ + return data == nullptr; +} + +inline +bool GpuMatND::external() const +{ + return !empty() && data_.use_count() == 0; +} + +inline +uchar* GpuMatND::getDevicePtr() const +{ + return data + offset; +} + +inline +size_t GpuMatND::total() const +{ + size_t p = 1; + for(auto s : size) + p *= s; + return p; +} + +inline +size_t GpuMatND::totalMemSize() const +{ + return size[0] * step[0]; +} + +inline +int GpuMatND::type() const +{ + return CV_MAT_TYPE(flags); +} + +//=================================================================================== +// HostMem +//=================================================================================== + +inline +HostMem::HostMem(AllocType alloc_type_) + : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(alloc_type_) +{ +} + +inline +HostMem::HostMem(const HostMem& m) + : flags(m.flags), rows(m.rows), cols(m.cols), step(m.step), data(m.data), refcount(m.refcount), datastart(m.datastart), dataend(m.dataend), alloc_type(m.alloc_type) +{ + if( refcount ) + CV_XADD(refcount, 1); +} + +inline +HostMem::HostMem(int rows_, int cols_, int type_, AllocType alloc_type_) + : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(alloc_type_) +{ + if (rows_ > 0 && cols_ > 0) + create(rows_, cols_, type_); +} + +inline +HostMem::HostMem(Size size_, int type_, AllocType alloc_type_) + : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(alloc_type_) +{ + if (size_.height > 0 && size_.width > 0) + create(size_.height, size_.width, type_); +} + +inline +HostMem::HostMem(InputArray arr, AllocType alloc_type_) + : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(alloc_type_) +{ + arr.getMat().copyTo(*this); +} + +inline +HostMem::~HostMem() +{ + release(); +} + +inline +HostMem& HostMem::operator =(const HostMem& m) +{ + if (this != &m) + { + HostMem temp(m); + swap(temp); + } + + return *this; +} + +inline +void HostMem::swap(HostMem& b) +{ + std::swap(flags, b.flags); + std::swap(rows, b.rows); + std::swap(cols, b.cols); + std::swap(step, b.step); + std::swap(data, b.data); + std::swap(datastart, b.datastart); + std::swap(dataend, b.dataend); + std::swap(refcount, b.refcount); + std::swap(alloc_type, b.alloc_type); +} + +inline +HostMem HostMem::clone() const +{ + HostMem m(size(), type(), alloc_type); + createMatHeader().copyTo(m); + return m; +} + +inline +void HostMem::create(Size size_, int type_) +{ + create(size_.height, size_.width, type_); +} + +inline +Mat HostMem::createMatHeader() const +{ + return Mat(size(), type(), data, step); +} + +inline +bool HostMem::isContinuous() const +{ + return (flags & Mat::CONTINUOUS_FLAG) != 0; +} + +inline +size_t HostMem::elemSize() const +{ + return CV_ELEM_SIZE(flags); +} + +inline +size_t HostMem::elemSize1() const +{ + return CV_ELEM_SIZE1(flags); +} + +inline +int HostMem::type() const +{ + return CV_MAT_TYPE(flags); +} + +inline +int HostMem::depth() const +{ + return CV_MAT_DEPTH(flags); +} + +inline +int HostMem::channels() const +{ + return CV_MAT_CN(flags); +} + +inline +size_t HostMem::step1() const +{ + return step / elemSize1(); +} + +inline +Size HostMem::size() const +{ + return Size(cols, rows); +} + +inline +bool HostMem::empty() const +{ + return data == 0; +} + +static inline +void swap(HostMem& a, HostMem& b) +{ + a.swap(b); +} + +//=================================================================================== +// Stream +//=================================================================================== + +inline +Stream::Stream(const Ptr& impl) + : impl_(impl) +{ +} + +//=================================================================================== +// Event +//=================================================================================== + +inline +Event::Event(const Ptr& impl) + : impl_(impl) +{ +} + +//=================================================================================== +// Initialization & Info +//=================================================================================== + +// WARNING: unreachable code using Ninja +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(push) +#pragma warning(disable: 4702) +#endif +inline +bool TargetArchs::has(int major, int minor) +{ + return hasPtx(major, minor) || hasBin(major, minor); +} + +inline +bool TargetArchs::hasEqualOrGreater(int major, int minor) +{ + return hasEqualOrGreaterPtx(major, minor) || hasEqualOrGreaterBin(major, minor); +} + +inline +DeviceInfo::DeviceInfo() +{ + device_id_ = getDevice(); +} +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(pop) +#endif + +inline +DeviceInfo::DeviceInfo(int device_id) +{ + CV_Assert( device_id >= 0 && device_id < getCudaEnabledDeviceCount() ); + device_id_ = device_id; +} + +// WARNING: unreachable code using Ninja +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(push) +#pragma warning(disable: 4702) +#endif +inline +int DeviceInfo::deviceID() const +{ + return device_id_; +} + +inline +size_t DeviceInfo::freeMemory() const +{ + size_t _totalMemory = 0, _freeMemory = 0; + queryMemory(_totalMemory, _freeMemory); + return _freeMemory; +} + +inline +size_t DeviceInfo::totalMemory() const +{ + size_t _totalMemory = 0, _freeMemory = 0; + queryMemory(_totalMemory, _freeMemory); + return _totalMemory; +} + +inline +bool DeviceInfo::supports(FeatureSet feature_set) const +{ + int version = majorVersion() * 10 + minorVersion(); + return version >= feature_set; +} +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(pop) +#endif + + +}} // namespace cv { namespace cuda { + +//=================================================================================== +// Mat +//=================================================================================== + +namespace cv { + +inline +Mat::Mat(const cuda::GpuMat& m) + : flags(0), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows) +{ + m.download(*this); +} + +} + +//! @endcond + +#endif // OPENCV_CORE_CUDAINL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/block.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/block.hpp index c277f0ea9c..f64d9edd69 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/block.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/block.hpp @@ -1,211 +1,211 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_DEVICE_BLOCK_HPP -#define OPENCV_CUDA_DEVICE_BLOCK_HPP - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - struct Block - { - static __device__ __forceinline__ unsigned int id() - { - return blockIdx.x; - } - - static __device__ __forceinline__ unsigned int stride() - { - return blockDim.x * blockDim.y * blockDim.z; - } - - static __device__ __forceinline__ void sync() - { - __syncthreads(); - } - - static __device__ __forceinline__ int flattenedThreadId() - { - return threadIdx.z * blockDim.x * blockDim.y + threadIdx.y * blockDim.x + threadIdx.x; - } - - template - static __device__ __forceinline__ void fill(It beg, It end, const T& value) - { - int STRIDE = stride(); - It t = beg + flattenedThreadId(); - - for(; t < end; t += STRIDE) - *t = value; - } - - template - static __device__ __forceinline__ void yota(OutIt beg, OutIt end, T value) - { - int STRIDE = stride(); - int tid = flattenedThreadId(); - value += tid; - - for(OutIt t = beg + tid; t < end; t += STRIDE, value += STRIDE) - *t = value; - } - - template - static __device__ __forceinline__ void copy(InIt beg, InIt end, OutIt out) - { - int STRIDE = stride(); - InIt t = beg + flattenedThreadId(); - OutIt o = out + (t - beg); - - for(; t < end; t += STRIDE, o += STRIDE) - *o = *t; - } - - template - static __device__ __forceinline__ void transform(InIt beg, InIt end, OutIt out, UnOp op) - { - int STRIDE = stride(); - InIt t = beg + flattenedThreadId(); - OutIt o = out + (t - beg); - - for(; t < end; t += STRIDE, o += STRIDE) - *o = op(*t); - } - - template - static __device__ __forceinline__ void transform(InIt1 beg1, InIt1 end1, InIt2 beg2, OutIt out, BinOp op) - { - int STRIDE = stride(); - InIt1 t1 = beg1 + flattenedThreadId(); - InIt2 t2 = beg2 + flattenedThreadId(); - OutIt o = out + (t1 - beg1); - - for(; t1 < end1; t1 += STRIDE, t2 += STRIDE, o += STRIDE) - *o = op(*t1, *t2); - } - - template - static __device__ __forceinline__ void reduce(volatile T* buffer, BinOp op) - { - int tid = flattenedThreadId(); - T val = buffer[tid]; - - if (CTA_SIZE >= 1024) { if (tid < 512) buffer[tid] = val = op(val, buffer[tid + 512]); __syncthreads(); } - if (CTA_SIZE >= 512) { if (tid < 256) buffer[tid] = val = op(val, buffer[tid + 256]); __syncthreads(); } - if (CTA_SIZE >= 256) { if (tid < 128) buffer[tid] = val = op(val, buffer[tid + 128]); __syncthreads(); } - if (CTA_SIZE >= 128) { if (tid < 64) buffer[tid] = val = op(val, buffer[tid + 64]); __syncthreads(); } - - if (tid < 32) - { - if (CTA_SIZE >= 64) { buffer[tid] = val = op(val, buffer[tid + 32]); } - if (CTA_SIZE >= 32) { buffer[tid] = val = op(val, buffer[tid + 16]); } - if (CTA_SIZE >= 16) { buffer[tid] = val = op(val, buffer[tid + 8]); } - if (CTA_SIZE >= 8) { buffer[tid] = val = op(val, buffer[tid + 4]); } - if (CTA_SIZE >= 4) { buffer[tid] = val = op(val, buffer[tid + 2]); } - if (CTA_SIZE >= 2) { buffer[tid] = val = op(val, buffer[tid + 1]); } - } - } - - template - static __device__ __forceinline__ T reduce(volatile T* buffer, T init, BinOp op) - { - int tid = flattenedThreadId(); - T val = buffer[tid] = init; - __syncthreads(); - - if (CTA_SIZE >= 1024) { if (tid < 512) buffer[tid] = val = op(val, buffer[tid + 512]); __syncthreads(); } - if (CTA_SIZE >= 512) { if (tid < 256) buffer[tid] = val = op(val, buffer[tid + 256]); __syncthreads(); } - if (CTA_SIZE >= 256) { if (tid < 128) buffer[tid] = val = op(val, buffer[tid + 128]); __syncthreads(); } - if (CTA_SIZE >= 128) { if (tid < 64) buffer[tid] = val = op(val, buffer[tid + 64]); __syncthreads(); } - - if (tid < 32) - { - if (CTA_SIZE >= 64) { buffer[tid] = val = op(val, buffer[tid + 32]); } - if (CTA_SIZE >= 32) { buffer[tid] = val = op(val, buffer[tid + 16]); } - if (CTA_SIZE >= 16) { buffer[tid] = val = op(val, buffer[tid + 8]); } - if (CTA_SIZE >= 8) { buffer[tid] = val = op(val, buffer[tid + 4]); } - if (CTA_SIZE >= 4) { buffer[tid] = val = op(val, buffer[tid + 2]); } - if (CTA_SIZE >= 2) { buffer[tid] = val = op(val, buffer[tid + 1]); } - } - __syncthreads(); - return buffer[0]; - } - - template - static __device__ __forceinline__ void reduce_n(T* data, unsigned int n, BinOp op) - { - int ftid = flattenedThreadId(); - int sft = stride(); - - if (sft < n) - { - for (unsigned int i = sft + ftid; i < n; i += sft) - data[ftid] = op(data[ftid], data[i]); - - __syncthreads(); - - n = sft; - } - - while (n > 1) - { - unsigned int half = n/2; - - if (ftid < half) - data[ftid] = op(data[ftid], data[n - ftid - 1]); - - __syncthreads(); - - n = n - half; - } - } - }; -}}} - -//! @endcond - -#endif /* OPENCV_CUDA_DEVICE_BLOCK_HPP */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_DEVICE_BLOCK_HPP +#define OPENCV_CUDA_DEVICE_BLOCK_HPP + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + struct Block + { + static __device__ __forceinline__ unsigned int id() + { + return blockIdx.x; + } + + static __device__ __forceinline__ unsigned int stride() + { + return blockDim.x * blockDim.y * blockDim.z; + } + + static __device__ __forceinline__ void sync() + { + __syncthreads(); + } + + static __device__ __forceinline__ int flattenedThreadId() + { + return threadIdx.z * blockDim.x * blockDim.y + threadIdx.y * blockDim.x + threadIdx.x; + } + + template + static __device__ __forceinline__ void fill(It beg, It end, const T& value) + { + int STRIDE = stride(); + It t = beg + flattenedThreadId(); + + for(; t < end; t += STRIDE) + *t = value; + } + + template + static __device__ __forceinline__ void yota(OutIt beg, OutIt end, T value) + { + int STRIDE = stride(); + int tid = flattenedThreadId(); + value += tid; + + for(OutIt t = beg + tid; t < end; t += STRIDE, value += STRIDE) + *t = value; + } + + template + static __device__ __forceinline__ void copy(InIt beg, InIt end, OutIt out) + { + int STRIDE = stride(); + InIt t = beg + flattenedThreadId(); + OutIt o = out + (t - beg); + + for(; t < end; t += STRIDE, o += STRIDE) + *o = *t; + } + + template + static __device__ __forceinline__ void transform(InIt beg, InIt end, OutIt out, UnOp op) + { + int STRIDE = stride(); + InIt t = beg + flattenedThreadId(); + OutIt o = out + (t - beg); + + for(; t < end; t += STRIDE, o += STRIDE) + *o = op(*t); + } + + template + static __device__ __forceinline__ void transform(InIt1 beg1, InIt1 end1, InIt2 beg2, OutIt out, BinOp op) + { + int STRIDE = stride(); + InIt1 t1 = beg1 + flattenedThreadId(); + InIt2 t2 = beg2 + flattenedThreadId(); + OutIt o = out + (t1 - beg1); + + for(; t1 < end1; t1 += STRIDE, t2 += STRIDE, o += STRIDE) + *o = op(*t1, *t2); + } + + template + static __device__ __forceinline__ void reduce(volatile T* buffer, BinOp op) + { + int tid = flattenedThreadId(); + T val = buffer[tid]; + + if (CTA_SIZE >= 1024) { if (tid < 512) buffer[tid] = val = op(val, buffer[tid + 512]); __syncthreads(); } + if (CTA_SIZE >= 512) { if (tid < 256) buffer[tid] = val = op(val, buffer[tid + 256]); __syncthreads(); } + if (CTA_SIZE >= 256) { if (tid < 128) buffer[tid] = val = op(val, buffer[tid + 128]); __syncthreads(); } + if (CTA_SIZE >= 128) { if (tid < 64) buffer[tid] = val = op(val, buffer[tid + 64]); __syncthreads(); } + + if (tid < 32) + { + if (CTA_SIZE >= 64) { buffer[tid] = val = op(val, buffer[tid + 32]); } + if (CTA_SIZE >= 32) { buffer[tid] = val = op(val, buffer[tid + 16]); } + if (CTA_SIZE >= 16) { buffer[tid] = val = op(val, buffer[tid + 8]); } + if (CTA_SIZE >= 8) { buffer[tid] = val = op(val, buffer[tid + 4]); } + if (CTA_SIZE >= 4) { buffer[tid] = val = op(val, buffer[tid + 2]); } + if (CTA_SIZE >= 2) { buffer[tid] = val = op(val, buffer[tid + 1]); } + } + } + + template + static __device__ __forceinline__ T reduce(volatile T* buffer, T init, BinOp op) + { + int tid = flattenedThreadId(); + T val = buffer[tid] = init; + __syncthreads(); + + if (CTA_SIZE >= 1024) { if (tid < 512) buffer[tid] = val = op(val, buffer[tid + 512]); __syncthreads(); } + if (CTA_SIZE >= 512) { if (tid < 256) buffer[tid] = val = op(val, buffer[tid + 256]); __syncthreads(); } + if (CTA_SIZE >= 256) { if (tid < 128) buffer[tid] = val = op(val, buffer[tid + 128]); __syncthreads(); } + if (CTA_SIZE >= 128) { if (tid < 64) buffer[tid] = val = op(val, buffer[tid + 64]); __syncthreads(); } + + if (tid < 32) + { + if (CTA_SIZE >= 64) { buffer[tid] = val = op(val, buffer[tid + 32]); } + if (CTA_SIZE >= 32) { buffer[tid] = val = op(val, buffer[tid + 16]); } + if (CTA_SIZE >= 16) { buffer[tid] = val = op(val, buffer[tid + 8]); } + if (CTA_SIZE >= 8) { buffer[tid] = val = op(val, buffer[tid + 4]); } + if (CTA_SIZE >= 4) { buffer[tid] = val = op(val, buffer[tid + 2]); } + if (CTA_SIZE >= 2) { buffer[tid] = val = op(val, buffer[tid + 1]); } + } + __syncthreads(); + return buffer[0]; + } + + template + static __device__ __forceinline__ void reduce_n(T* data, unsigned int n, BinOp op) + { + int ftid = flattenedThreadId(); + int sft = stride(); + + if (sft < n) + { + for (unsigned int i = sft + ftid; i < n; i += sft) + data[ftid] = op(data[ftid], data[i]); + + __syncthreads(); + + n = sft; + } + + while (n > 1) + { + unsigned int half = n/2; + + if (ftid < half) + data[ftid] = op(data[ftid], data[n - ftid - 1]); + + __syncthreads(); + + n = n - half; + } + } + }; +}}} + +//! @endcond + +#endif /* OPENCV_CUDA_DEVICE_BLOCK_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/border_interpolate.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/border_interpolate.hpp index 874f705baf..62864c4857 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/border_interpolate.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/border_interpolate.hpp @@ -1,722 +1,722 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_BORDER_INTERPOLATE_HPP -#define OPENCV_CUDA_BORDER_INTERPOLATE_HPP - -#include "saturate_cast.hpp" -#include "vec_traits.hpp" -#include "vec_math.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - ////////////////////////////////////////////////////////////// - // BrdConstant - - template struct BrdRowConstant - { - typedef D result_type; - - explicit __host__ __device__ __forceinline__ BrdRowConstant(int width_, const D& val_ = VecTraits::all(0)) : width(width_), val(val_) {} - - template __device__ __forceinline__ D at_low(int x, const T* data) const - { - return x >= 0 ? saturate_cast(data[x]) : val; - } - - template __device__ __forceinline__ D at_high(int x, const T* data) const - { - return x < width ? saturate_cast(data[x]) : val; - } - - template __device__ __forceinline__ D at(int x, const T* data) const - { - return (x >= 0 && x < width) ? saturate_cast(data[x]) : val; - } - - int width; - D val; - }; - - template struct BrdColConstant - { - typedef D result_type; - - explicit __host__ __device__ __forceinline__ BrdColConstant(int height_, const D& val_ = VecTraits::all(0)) : height(height_), val(val_) {} - - template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const - { - return y >= 0 ? saturate_cast(*(const T*)((const char*)data + y * step)) : val; - } - - template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const - { - return y < height ? saturate_cast(*(const T*)((const char*)data + y * step)) : val; - } - - template __device__ __forceinline__ D at(int y, const T* data, size_t step) const - { - return (y >= 0 && y < height) ? saturate_cast(*(const T*)((const char*)data + y * step)) : val; - } - - int height; - D val; - }; - - template struct BrdConstant - { - typedef D result_type; - - __host__ __device__ __forceinline__ BrdConstant(int height_, int width_, const D& val_ = VecTraits::all(0)) : height(height_), width(width_), val(val_) - { - } - - template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const - { - return (x >= 0 && x < width && y >= 0 && y < height) ? saturate_cast(((const T*)((const uchar*)data + y * step))[x]) : val; - } - - template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const - { - return (x >= 0 && x < width && y >= 0 && y < height) ? saturate_cast(src(y, x)) : val; - } - - int height; - int width; - D val; - }; - - ////////////////////////////////////////////////////////////// - // BrdReplicate - - template struct BrdRowReplicate - { - typedef D result_type; - - explicit __host__ __device__ __forceinline__ BrdRowReplicate(int width) : last_col(width - 1) {} - template __host__ __device__ __forceinline__ BrdRowReplicate(int width, U) : last_col(width - 1) {} - - __device__ __forceinline__ int idx_col_low(int x) const - { - return ::max(x, 0); - } - - __device__ __forceinline__ int idx_col_high(int x) const - { - return ::min(x, last_col); - } - - __device__ __forceinline__ int idx_col(int x) const - { - return idx_col_low(idx_col_high(x)); - } - - template __device__ __forceinline__ D at_low(int x, const T* data) const - { - return saturate_cast(data[idx_col_low(x)]); - } - - template __device__ __forceinline__ D at_high(int x, const T* data) const - { - return saturate_cast(data[idx_col_high(x)]); - } - - template __device__ __forceinline__ D at(int x, const T* data) const - { - return saturate_cast(data[idx_col(x)]); - } - - int last_col; - }; - - template struct BrdColReplicate - { - typedef D result_type; - - explicit __host__ __device__ __forceinline__ BrdColReplicate(int height) : last_row(height - 1) {} - template __host__ __device__ __forceinline__ BrdColReplicate(int height, U) : last_row(height - 1) {} - - __device__ __forceinline__ int idx_row_low(int y) const - { - return ::max(y, 0); - } - - __device__ __forceinline__ int idx_row_high(int y) const - { - return ::min(y, last_row); - } - - __device__ __forceinline__ int idx_row(int y) const - { - return idx_row_low(idx_row_high(y)); - } - - template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const - { - return saturate_cast(*(const T*)((const char*)data + idx_row_low(y) * step)); - } - - template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const - { - return saturate_cast(*(const T*)((const char*)data + idx_row_high(y) * step)); - } - - template __device__ __forceinline__ D at(int y, const T* data, size_t step) const - { - return saturate_cast(*(const T*)((const char*)data + idx_row(y) * step)); - } - - int last_row; - }; - - template struct BrdReplicate - { - typedef D result_type; - - __host__ __device__ __forceinline__ BrdReplicate(int height, int width) : last_row(height - 1), last_col(width - 1) {} - template __host__ __device__ __forceinline__ BrdReplicate(int height, int width, U) : last_row(height - 1), last_col(width - 1) {} - - __device__ __forceinline__ int idx_row_low(int y) const - { - return ::max(y, 0); - } - - __device__ __forceinline__ int idx_row_high(int y) const - { - return ::min(y, last_row); - } - - __device__ __forceinline__ int idx_row(int y) const - { - return idx_row_low(idx_row_high(y)); - } - - __device__ __forceinline__ int idx_col_low(int x) const - { - return ::max(x, 0); - } - - __device__ __forceinline__ int idx_col_high(int x) const - { - return ::min(x, last_col); - } - - __device__ __forceinline__ int idx_col(int x) const - { - return idx_col_low(idx_col_high(x)); - } - - template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const - { - return saturate_cast(((const T*)((const char*)data + idx_row(y) * step))[idx_col(x)]); - } - - template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const - { - return saturate_cast(src(idx_row(y), idx_col(x))); - } - - int last_row; - int last_col; - }; - - ////////////////////////////////////////////////////////////// - // BrdReflect101 - - template struct BrdRowReflect101 - { - typedef D result_type; - - explicit __host__ __device__ __forceinline__ BrdRowReflect101(int width) : last_col(width - 1) {} - template __host__ __device__ __forceinline__ BrdRowReflect101(int width, U) : last_col(width - 1) {} - - __device__ __forceinline__ int idx_col_low(int x) const - { - return ::abs(x) % (last_col + 1); - } - - __device__ __forceinline__ int idx_col_high(int x) const - { - return ::abs(last_col - ::abs(last_col - x)) % (last_col + 1); - } - - __device__ __forceinline__ int idx_col(int x) const - { - return idx_col_low(idx_col_high(x)); - } - - template __device__ __forceinline__ D at_low(int x, const T* data) const - { - return saturate_cast(data[idx_col_low(x)]); - } - - template __device__ __forceinline__ D at_high(int x, const T* data) const - { - return saturate_cast(data[idx_col_high(x)]); - } - - template __device__ __forceinline__ D at(int x, const T* data) const - { - return saturate_cast(data[idx_col(x)]); - } - - int last_col; - }; - - template struct BrdColReflect101 - { - typedef D result_type; - - explicit __host__ __device__ __forceinline__ BrdColReflect101(int height) : last_row(height - 1) {} - template __host__ __device__ __forceinline__ BrdColReflect101(int height, U) : last_row(height - 1) {} - - __device__ __forceinline__ int idx_row_low(int y) const - { - return ::abs(y) % (last_row + 1); - } - - __device__ __forceinline__ int idx_row_high(int y) const - { - return ::abs(last_row - ::abs(last_row - y)) % (last_row + 1); - } - - __device__ __forceinline__ int idx_row(int y) const - { - return idx_row_low(idx_row_high(y)); - } - - template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const - { - return saturate_cast(*(const D*)((const char*)data + idx_row_low(y) * step)); - } - - template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const - { - return saturate_cast(*(const D*)((const char*)data + idx_row_high(y) * step)); - } - - template __device__ __forceinline__ D at(int y, const T* data, size_t step) const - { - return saturate_cast(*(const D*)((const char*)data + idx_row(y) * step)); - } - - int last_row; - }; - - template struct BrdReflect101 - { - typedef D result_type; - - __host__ __device__ __forceinline__ BrdReflect101(int height, int width) : last_row(height - 1), last_col(width - 1) {} - template __host__ __device__ __forceinline__ BrdReflect101(int height, int width, U) : last_row(height - 1), last_col(width - 1) {} - - __device__ __forceinline__ int idx_row_low(int y) const - { - return ::abs(y) % (last_row + 1); - } - - __device__ __forceinline__ int idx_row_high(int y) const - { - return ::abs(last_row - ::abs(last_row - y)) % (last_row + 1); - } - - __device__ __forceinline__ int idx_row(int y) const - { - return idx_row_low(idx_row_high(y)); - } - - __device__ __forceinline__ int idx_col_low(int x) const - { - return ::abs(x) % (last_col + 1); - } - - __device__ __forceinline__ int idx_col_high(int x) const - { - return ::abs(last_col - ::abs(last_col - x)) % (last_col + 1); - } - - __device__ __forceinline__ int idx_col(int x) const - { - return idx_col_low(idx_col_high(x)); - } - - template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const - { - return saturate_cast(((const T*)((const char*)data + idx_row(y) * step))[idx_col(x)]); - } - - template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const - { - return saturate_cast(src(idx_row(y), idx_col(x))); - } - - int last_row; - int last_col; - }; - - ////////////////////////////////////////////////////////////// - // BrdReflect - - template struct BrdRowReflect - { - typedef D result_type; - - explicit __host__ __device__ __forceinline__ BrdRowReflect(int width) : last_col(width - 1) {} - template __host__ __device__ __forceinline__ BrdRowReflect(int width, U) : last_col(width - 1) {} - - __device__ __forceinline__ int idx_col_low(int x) const - { - return (::abs(x) - (x < 0)) % (last_col + 1); - } - - __device__ __forceinline__ int idx_col_high(int x) const - { - return ::abs(last_col - ::abs(last_col - x) + (x > last_col)) % (last_col + 1); - } - - __device__ __forceinline__ int idx_col(int x) const - { - return idx_col_high(::abs(x) - (x < 0)); - } - - template __device__ __forceinline__ D at_low(int x, const T* data) const - { - return saturate_cast(data[idx_col_low(x)]); - } - - template __device__ __forceinline__ D at_high(int x, const T* data) const - { - return saturate_cast(data[idx_col_high(x)]); - } - - template __device__ __forceinline__ D at(int x, const T* data) const - { - return saturate_cast(data[idx_col(x)]); - } - - int last_col; - }; - - template struct BrdColReflect - { - typedef D result_type; - - explicit __host__ __device__ __forceinline__ BrdColReflect(int height) : last_row(height - 1) {} - template __host__ __device__ __forceinline__ BrdColReflect(int height, U) : last_row(height - 1) {} - - __device__ __forceinline__ int idx_row_low(int y) const - { - return (::abs(y) - (y < 0)) % (last_row + 1); - } - - __device__ __forceinline__ int idx_row_high(int y) const - { - return ::abs(last_row - ::abs(last_row - y) + (y > last_row)) % (last_row + 1); - } - - __device__ __forceinline__ int idx_row(int y) const - { - return idx_row_high(::abs(y) - (y < 0)); - } - - template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const - { - return saturate_cast(*(const D*)((const char*)data + idx_row_low(y) * step)); - } - - template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const - { - return saturate_cast(*(const D*)((const char*)data + idx_row_high(y) * step)); - } - - template __device__ __forceinline__ D at(int y, const T* data, size_t step) const - { - return saturate_cast(*(const D*)((const char*)data + idx_row(y) * step)); - } - - int last_row; - }; - - template struct BrdReflect - { - typedef D result_type; - - __host__ __device__ __forceinline__ BrdReflect(int height, int width) : last_row(height - 1), last_col(width - 1) {} - template __host__ __device__ __forceinline__ BrdReflect(int height, int width, U) : last_row(height - 1), last_col(width - 1) {} - - __device__ __forceinline__ int idx_row_low(int y) const - { - return (::abs(y) - (y < 0)) % (last_row + 1); - } - - __device__ __forceinline__ int idx_row_high(int y) const - { - return /*::abs*/(last_row - ::abs(last_row - y) + (y > last_row)) /*% (last_row + 1)*/; - } - - __device__ __forceinline__ int idx_row(int y) const - { - return idx_row_low(idx_row_high(y)); - } - - __device__ __forceinline__ int idx_col_low(int x) const - { - return (::abs(x) - (x < 0)) % (last_col + 1); - } - - __device__ __forceinline__ int idx_col_high(int x) const - { - return (last_col - ::abs(last_col - x) + (x > last_col)); - } - - __device__ __forceinline__ int idx_col(int x) const - { - return idx_col_low(idx_col_high(x)); - } - - template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const - { - return saturate_cast(((const T*)((const char*)data + idx_row(y) * step))[idx_col(x)]); - } - - template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const - { - return saturate_cast(src(idx_row(y), idx_col(x))); - } - - int last_row; - int last_col; - }; - - ////////////////////////////////////////////////////////////// - // BrdWrap - - template struct BrdRowWrap - { - typedef D result_type; - - explicit __host__ __device__ __forceinline__ BrdRowWrap(int width_) : width(width_) {} - template __host__ __device__ __forceinline__ BrdRowWrap(int width_, U) : width(width_) {} - - __device__ __forceinline__ int idx_col_low(int x) const - { - return (x >= 0) * x + (x < 0) * (x - ((x - width + 1) / width) * width); - } - - __device__ __forceinline__ int idx_col_high(int x) const - { - return (x < width) * x + (x >= width) * (x % width); - } - - __device__ __forceinline__ int idx_col(int x) const - { - return idx_col_high(idx_col_low(x)); - } - - template __device__ __forceinline__ D at_low(int x, const T* data) const - { - return saturate_cast(data[idx_col_low(x)]); - } - - template __device__ __forceinline__ D at_high(int x, const T* data) const - { - return saturate_cast(data[idx_col_high(x)]); - } - - template __device__ __forceinline__ D at(int x, const T* data) const - { - return saturate_cast(data[idx_col(x)]); - } - - int width; - }; - - template struct BrdColWrap - { - typedef D result_type; - - explicit __host__ __device__ __forceinline__ BrdColWrap(int height_) : height(height_) {} - template __host__ __device__ __forceinline__ BrdColWrap(int height_, U) : height(height_) {} - - __device__ __forceinline__ int idx_row_low(int y) const - { - return (y >= 0) * y + (y < 0) * (y - ((y - height + 1) / height) * height); - } - - __device__ __forceinline__ int idx_row_high(int y) const - { - return (y < height) * y + (y >= height) * (y % height); - } - - __device__ __forceinline__ int idx_row(int y) const - { - return idx_row_high(idx_row_low(y)); - } - - template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const - { - return saturate_cast(*(const D*)((const char*)data + idx_row_low(y) * step)); - } - - template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const - { - return saturate_cast(*(const D*)((const char*)data + idx_row_high(y) * step)); - } - - template __device__ __forceinline__ D at(int y, const T* data, size_t step) const - { - return saturate_cast(*(const D*)((const char*)data + idx_row(y) * step)); - } - - int height; - }; - - template struct BrdWrap - { - typedef D result_type; - - __host__ __device__ __forceinline__ BrdWrap(int height_, int width_) : - height(height_), width(width_) - { - } - template - __host__ __device__ __forceinline__ BrdWrap(int height_, int width_, U) : - height(height_), width(width_) - { - } - - __device__ __forceinline__ int idx_row_low(int y) const - { - return (y >= 0) ? y : (y - ((y - height + 1) / height) * height); - } - - __device__ __forceinline__ int idx_row_high(int y) const - { - return (y < height) ? y : (y % height); - } - - __device__ __forceinline__ int idx_row(int y) const - { - return idx_row_high(idx_row_low(y)); - } - - __device__ __forceinline__ int idx_col_low(int x) const - { - return (x >= 0) ? x : (x - ((x - width + 1) / width) * width); - } - - __device__ __forceinline__ int idx_col_high(int x) const - { - return (x < width) ? x : (x % width); - } - - __device__ __forceinline__ int idx_col(int x) const - { - return idx_col_high(idx_col_low(x)); - } - - template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const - { - return saturate_cast(((const T*)((const char*)data + idx_row(y) * step))[idx_col(x)]); - } - - template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const - { - return saturate_cast(src(idx_row(y), idx_col(x))); - } - - int height; - int width; - }; - - ////////////////////////////////////////////////////////////// - // BorderReader - - template struct BorderReader - { - typedef typename B::result_type elem_type; - typedef typename Ptr2D::index_type index_type; - - __host__ __device__ __forceinline__ BorderReader(const Ptr2D& ptr_, const B& b_) : ptr(ptr_), b(b_) {} - - __device__ __forceinline__ elem_type operator ()(index_type y, index_type x) const - { - return b.at(y, x, ptr); - } - - Ptr2D ptr; - B b; - }; - - // under win32 there is some bug with templated types that passed as kernel parameters - // with this specialization all works fine - template struct BorderReader< Ptr2D, BrdConstant > - { - typedef typename BrdConstant::result_type elem_type; - typedef typename Ptr2D::index_type index_type; - - __host__ __device__ __forceinline__ BorderReader(const Ptr2D& src_, const BrdConstant& b) : - src(src_), height(b.height), width(b.width), val(b.val) - { - } - - __device__ __forceinline__ D operator ()(index_type y, index_type x) const - { - return (x >= 0 && x < width && y >= 0 && y < height) ? saturate_cast(src(y, x)) : val; - } - - Ptr2D src; - int height; - int width; - D val; - }; -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif // OPENCV_CUDA_BORDER_INTERPOLATE_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_BORDER_INTERPOLATE_HPP +#define OPENCV_CUDA_BORDER_INTERPOLATE_HPP + +#include "saturate_cast.hpp" +#include "vec_traits.hpp" +#include "vec_math.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + ////////////////////////////////////////////////////////////// + // BrdConstant + + template struct BrdRowConstant + { + typedef D result_type; + + explicit __host__ __device__ __forceinline__ BrdRowConstant(int width_, const D& val_ = VecTraits::all(0)) : width(width_), val(val_) {} + + template __device__ __forceinline__ D at_low(int x, const T* data) const + { + return x >= 0 ? saturate_cast(data[x]) : val; + } + + template __device__ __forceinline__ D at_high(int x, const T* data) const + { + return x < width ? saturate_cast(data[x]) : val; + } + + template __device__ __forceinline__ D at(int x, const T* data) const + { + return (x >= 0 && x < width) ? saturate_cast(data[x]) : val; + } + + int width; + D val; + }; + + template struct BrdColConstant + { + typedef D result_type; + + explicit __host__ __device__ __forceinline__ BrdColConstant(int height_, const D& val_ = VecTraits::all(0)) : height(height_), val(val_) {} + + template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const + { + return y >= 0 ? saturate_cast(*(const T*)((const char*)data + y * step)) : val; + } + + template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const + { + return y < height ? saturate_cast(*(const T*)((const char*)data + y * step)) : val; + } + + template __device__ __forceinline__ D at(int y, const T* data, size_t step) const + { + return (y >= 0 && y < height) ? saturate_cast(*(const T*)((const char*)data + y * step)) : val; + } + + int height; + D val; + }; + + template struct BrdConstant + { + typedef D result_type; + + __host__ __device__ __forceinline__ BrdConstant(int height_, int width_, const D& val_ = VecTraits::all(0)) : height(height_), width(width_), val(val_) + { + } + + template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const + { + return (x >= 0 && x < width && y >= 0 && y < height) ? saturate_cast(((const T*)((const uchar*)data + y * step))[x]) : val; + } + + template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const + { + return (x >= 0 && x < width && y >= 0 && y < height) ? saturate_cast(src(y, x)) : val; + } + + int height; + int width; + D val; + }; + + ////////////////////////////////////////////////////////////// + // BrdReplicate + + template struct BrdRowReplicate + { + typedef D result_type; + + explicit __host__ __device__ __forceinline__ BrdRowReplicate(int width) : last_col(width - 1) {} + template __host__ __device__ __forceinline__ BrdRowReplicate(int width, U) : last_col(width - 1) {} + + __device__ __forceinline__ int idx_col_low(int x) const + { + return ::max(x, 0); + } + + __device__ __forceinline__ int idx_col_high(int x) const + { + return ::min(x, last_col); + } + + __device__ __forceinline__ int idx_col(int x) const + { + return idx_col_low(idx_col_high(x)); + } + + template __device__ __forceinline__ D at_low(int x, const T* data) const + { + return saturate_cast(data[idx_col_low(x)]); + } + + template __device__ __forceinline__ D at_high(int x, const T* data) const + { + return saturate_cast(data[idx_col_high(x)]); + } + + template __device__ __forceinline__ D at(int x, const T* data) const + { + return saturate_cast(data[idx_col(x)]); + } + + int last_col; + }; + + template struct BrdColReplicate + { + typedef D result_type; + + explicit __host__ __device__ __forceinline__ BrdColReplicate(int height) : last_row(height - 1) {} + template __host__ __device__ __forceinline__ BrdColReplicate(int height, U) : last_row(height - 1) {} + + __device__ __forceinline__ int idx_row_low(int y) const + { + return ::max(y, 0); + } + + __device__ __forceinline__ int idx_row_high(int y) const + { + return ::min(y, last_row); + } + + __device__ __forceinline__ int idx_row(int y) const + { + return idx_row_low(idx_row_high(y)); + } + + template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const + { + return saturate_cast(*(const T*)((const char*)data + idx_row_low(y) * step)); + } + + template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const + { + return saturate_cast(*(const T*)((const char*)data + idx_row_high(y) * step)); + } + + template __device__ __forceinline__ D at(int y, const T* data, size_t step) const + { + return saturate_cast(*(const T*)((const char*)data + idx_row(y) * step)); + } + + int last_row; + }; + + template struct BrdReplicate + { + typedef D result_type; + + __host__ __device__ __forceinline__ BrdReplicate(int height, int width) : last_row(height - 1), last_col(width - 1) {} + template __host__ __device__ __forceinline__ BrdReplicate(int height, int width, U) : last_row(height - 1), last_col(width - 1) {} + + __device__ __forceinline__ int idx_row_low(int y) const + { + return ::max(y, 0); + } + + __device__ __forceinline__ int idx_row_high(int y) const + { + return ::min(y, last_row); + } + + __device__ __forceinline__ int idx_row(int y) const + { + return idx_row_low(idx_row_high(y)); + } + + __device__ __forceinline__ int idx_col_low(int x) const + { + return ::max(x, 0); + } + + __device__ __forceinline__ int idx_col_high(int x) const + { + return ::min(x, last_col); + } + + __device__ __forceinline__ int idx_col(int x) const + { + return idx_col_low(idx_col_high(x)); + } + + template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const + { + return saturate_cast(((const T*)((const char*)data + idx_row(y) * step))[idx_col(x)]); + } + + template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const + { + return saturate_cast(src(idx_row(y), idx_col(x))); + } + + int last_row; + int last_col; + }; + + ////////////////////////////////////////////////////////////// + // BrdReflect101 + + template struct BrdRowReflect101 + { + typedef D result_type; + + explicit __host__ __device__ __forceinline__ BrdRowReflect101(int width) : last_col(width - 1) {} + template __host__ __device__ __forceinline__ BrdRowReflect101(int width, U) : last_col(width - 1) {} + + __device__ __forceinline__ int idx_col_low(int x) const + { + return ::abs(x) % (last_col + 1); + } + + __device__ __forceinline__ int idx_col_high(int x) const + { + return ::abs(last_col - ::abs(last_col - x)) % (last_col + 1); + } + + __device__ __forceinline__ int idx_col(int x) const + { + return idx_col_low(idx_col_high(x)); + } + + template __device__ __forceinline__ D at_low(int x, const T* data) const + { + return saturate_cast(data[idx_col_low(x)]); + } + + template __device__ __forceinline__ D at_high(int x, const T* data) const + { + return saturate_cast(data[idx_col_high(x)]); + } + + template __device__ __forceinline__ D at(int x, const T* data) const + { + return saturate_cast(data[idx_col(x)]); + } + + int last_col; + }; + + template struct BrdColReflect101 + { + typedef D result_type; + + explicit __host__ __device__ __forceinline__ BrdColReflect101(int height) : last_row(height - 1) {} + template __host__ __device__ __forceinline__ BrdColReflect101(int height, U) : last_row(height - 1) {} + + __device__ __forceinline__ int idx_row_low(int y) const + { + return ::abs(y) % (last_row + 1); + } + + __device__ __forceinline__ int idx_row_high(int y) const + { + return ::abs(last_row - ::abs(last_row - y)) % (last_row + 1); + } + + __device__ __forceinline__ int idx_row(int y) const + { + return idx_row_low(idx_row_high(y)); + } + + template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const + { + return saturate_cast(*(const D*)((const char*)data + idx_row_low(y) * step)); + } + + template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const + { + return saturate_cast(*(const D*)((const char*)data + idx_row_high(y) * step)); + } + + template __device__ __forceinline__ D at(int y, const T* data, size_t step) const + { + return saturate_cast(*(const D*)((const char*)data + idx_row(y) * step)); + } + + int last_row; + }; + + template struct BrdReflect101 + { + typedef D result_type; + + __host__ __device__ __forceinline__ BrdReflect101(int height, int width) : last_row(height - 1), last_col(width - 1) {} + template __host__ __device__ __forceinline__ BrdReflect101(int height, int width, U) : last_row(height - 1), last_col(width - 1) {} + + __device__ __forceinline__ int idx_row_low(int y) const + { + return ::abs(y) % (last_row + 1); + } + + __device__ __forceinline__ int idx_row_high(int y) const + { + return ::abs(last_row - ::abs(last_row - y)) % (last_row + 1); + } + + __device__ __forceinline__ int idx_row(int y) const + { + return idx_row_low(idx_row_high(y)); + } + + __device__ __forceinline__ int idx_col_low(int x) const + { + return ::abs(x) % (last_col + 1); + } + + __device__ __forceinline__ int idx_col_high(int x) const + { + return ::abs(last_col - ::abs(last_col - x)) % (last_col + 1); + } + + __device__ __forceinline__ int idx_col(int x) const + { + return idx_col_low(idx_col_high(x)); + } + + template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const + { + return saturate_cast(((const T*)((const char*)data + idx_row(y) * step))[idx_col(x)]); + } + + template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const + { + return saturate_cast(src(idx_row(y), idx_col(x))); + } + + int last_row; + int last_col; + }; + + ////////////////////////////////////////////////////////////// + // BrdReflect + + template struct BrdRowReflect + { + typedef D result_type; + + explicit __host__ __device__ __forceinline__ BrdRowReflect(int width) : last_col(width - 1) {} + template __host__ __device__ __forceinline__ BrdRowReflect(int width, U) : last_col(width - 1) {} + + __device__ __forceinline__ int idx_col_low(int x) const + { + return (::abs(x) - (x < 0)) % (last_col + 1); + } + + __device__ __forceinline__ int idx_col_high(int x) const + { + return ::abs(last_col - ::abs(last_col - x) + (x > last_col)) % (last_col + 1); + } + + __device__ __forceinline__ int idx_col(int x) const + { + return idx_col_high(::abs(x) - (x < 0)); + } + + template __device__ __forceinline__ D at_low(int x, const T* data) const + { + return saturate_cast(data[idx_col_low(x)]); + } + + template __device__ __forceinline__ D at_high(int x, const T* data) const + { + return saturate_cast(data[idx_col_high(x)]); + } + + template __device__ __forceinline__ D at(int x, const T* data) const + { + return saturate_cast(data[idx_col(x)]); + } + + int last_col; + }; + + template struct BrdColReflect + { + typedef D result_type; + + explicit __host__ __device__ __forceinline__ BrdColReflect(int height) : last_row(height - 1) {} + template __host__ __device__ __forceinline__ BrdColReflect(int height, U) : last_row(height - 1) {} + + __device__ __forceinline__ int idx_row_low(int y) const + { + return (::abs(y) - (y < 0)) % (last_row + 1); + } + + __device__ __forceinline__ int idx_row_high(int y) const + { + return ::abs(last_row - ::abs(last_row - y) + (y > last_row)) % (last_row + 1); + } + + __device__ __forceinline__ int idx_row(int y) const + { + return idx_row_high(::abs(y) - (y < 0)); + } + + template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const + { + return saturate_cast(*(const D*)((const char*)data + idx_row_low(y) * step)); + } + + template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const + { + return saturate_cast(*(const D*)((const char*)data + idx_row_high(y) * step)); + } + + template __device__ __forceinline__ D at(int y, const T* data, size_t step) const + { + return saturate_cast(*(const D*)((const char*)data + idx_row(y) * step)); + } + + int last_row; + }; + + template struct BrdReflect + { + typedef D result_type; + + __host__ __device__ __forceinline__ BrdReflect(int height, int width) : last_row(height - 1), last_col(width - 1) {} + template __host__ __device__ __forceinline__ BrdReflect(int height, int width, U) : last_row(height - 1), last_col(width - 1) {} + + __device__ __forceinline__ int idx_row_low(int y) const + { + return (::abs(y) - (y < 0)) % (last_row + 1); + } + + __device__ __forceinline__ int idx_row_high(int y) const + { + return /*::abs*/(last_row - ::abs(last_row - y) + (y > last_row)) /*% (last_row + 1)*/; + } + + __device__ __forceinline__ int idx_row(int y) const + { + return idx_row_low(idx_row_high(y)); + } + + __device__ __forceinline__ int idx_col_low(int x) const + { + return (::abs(x) - (x < 0)) % (last_col + 1); + } + + __device__ __forceinline__ int idx_col_high(int x) const + { + return (last_col - ::abs(last_col - x) + (x > last_col)); + } + + __device__ __forceinline__ int idx_col(int x) const + { + return idx_col_low(idx_col_high(x)); + } + + template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const + { + return saturate_cast(((const T*)((const char*)data + idx_row(y) * step))[idx_col(x)]); + } + + template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const + { + return saturate_cast(src(idx_row(y), idx_col(x))); + } + + int last_row; + int last_col; + }; + + ////////////////////////////////////////////////////////////// + // BrdWrap + + template struct BrdRowWrap + { + typedef D result_type; + + explicit __host__ __device__ __forceinline__ BrdRowWrap(int width_) : width(width_) {} + template __host__ __device__ __forceinline__ BrdRowWrap(int width_, U) : width(width_) {} + + __device__ __forceinline__ int idx_col_low(int x) const + { + return (x >= 0) * x + (x < 0) * (x - ((x - width + 1) / width) * width); + } + + __device__ __forceinline__ int idx_col_high(int x) const + { + return (x < width) * x + (x >= width) * (x % width); + } + + __device__ __forceinline__ int idx_col(int x) const + { + return idx_col_high(idx_col_low(x)); + } + + template __device__ __forceinline__ D at_low(int x, const T* data) const + { + return saturate_cast(data[idx_col_low(x)]); + } + + template __device__ __forceinline__ D at_high(int x, const T* data) const + { + return saturate_cast(data[idx_col_high(x)]); + } + + template __device__ __forceinline__ D at(int x, const T* data) const + { + return saturate_cast(data[idx_col(x)]); + } + + int width; + }; + + template struct BrdColWrap + { + typedef D result_type; + + explicit __host__ __device__ __forceinline__ BrdColWrap(int height_) : height(height_) {} + template __host__ __device__ __forceinline__ BrdColWrap(int height_, U) : height(height_) {} + + __device__ __forceinline__ int idx_row_low(int y) const + { + return (y >= 0) * y + (y < 0) * (y - ((y - height + 1) / height) * height); + } + + __device__ __forceinline__ int idx_row_high(int y) const + { + return (y < height) * y + (y >= height) * (y % height); + } + + __device__ __forceinline__ int idx_row(int y) const + { + return idx_row_high(idx_row_low(y)); + } + + template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const + { + return saturate_cast(*(const D*)((const char*)data + idx_row_low(y) * step)); + } + + template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const + { + return saturate_cast(*(const D*)((const char*)data + idx_row_high(y) * step)); + } + + template __device__ __forceinline__ D at(int y, const T* data, size_t step) const + { + return saturate_cast(*(const D*)((const char*)data + idx_row(y) * step)); + } + + int height; + }; + + template struct BrdWrap + { + typedef D result_type; + + __host__ __device__ __forceinline__ BrdWrap(int height_, int width_) : + height(height_), width(width_) + { + } + template + __host__ __device__ __forceinline__ BrdWrap(int height_, int width_, U) : + height(height_), width(width_) + { + } + + __device__ __forceinline__ int idx_row_low(int y) const + { + return (y >= 0) ? y : (y - ((y - height + 1) / height) * height); + } + + __device__ __forceinline__ int idx_row_high(int y) const + { + return (y < height) ? y : (y % height); + } + + __device__ __forceinline__ int idx_row(int y) const + { + return idx_row_high(idx_row_low(y)); + } + + __device__ __forceinline__ int idx_col_low(int x) const + { + return (x >= 0) ? x : (x - ((x - width + 1) / width) * width); + } + + __device__ __forceinline__ int idx_col_high(int x) const + { + return (x < width) ? x : (x % width); + } + + __device__ __forceinline__ int idx_col(int x) const + { + return idx_col_high(idx_col_low(x)); + } + + template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const + { + return saturate_cast(((const T*)((const char*)data + idx_row(y) * step))[idx_col(x)]); + } + + template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const + { + return saturate_cast(src(idx_row(y), idx_col(x))); + } + + int height; + int width; + }; + + ////////////////////////////////////////////////////////////// + // BorderReader + + template struct BorderReader + { + typedef typename B::result_type elem_type; + typedef typename Ptr2D::index_type index_type; + + __host__ __device__ __forceinline__ BorderReader(const Ptr2D& ptr_, const B& b_) : ptr(ptr_), b(b_) {} + + __device__ __forceinline__ elem_type operator ()(index_type y, index_type x) const + { + return b.at(y, x, ptr); + } + + Ptr2D ptr; + B b; + }; + + // under win32 there is some bug with templated types that passed as kernel parameters + // with this specialization all works fine + template struct BorderReader< Ptr2D, BrdConstant > + { + typedef typename BrdConstant::result_type elem_type; + typedef typename Ptr2D::index_type index_type; + + __host__ __device__ __forceinline__ BorderReader(const Ptr2D& src_, const BrdConstant& b) : + src(src_), height(b.height), width(b.width), val(b.val) + { + } + + __device__ __forceinline__ D operator ()(index_type y, index_type x) const + { + return (x >= 0 && x < width && y >= 0 && y < height) ? saturate_cast(src(y, x)) : val; + } + + Ptr2D src; + int height; + int width; + D val; + }; +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif // OPENCV_CUDA_BORDER_INTERPOLATE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/color.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/color.hpp index dcce280214..0b9fb84b7c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/color.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/color.hpp @@ -1,309 +1,309 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_COLOR_HPP -#define OPENCV_CUDA_COLOR_HPP - -#include "detail/color_detail.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - // All OPENCV_CUDA_IMPLEMENT_*_TRAITS(ColorSpace1_to_ColorSpace2, ...) macros implements - // template class ColorSpace1_to_ColorSpace2_traits - // { - // typedef ... functor_type; - // static __host__ __device__ functor_type create_functor(); - // }; - - OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgr_to_rgb, 3, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgr_to_bgra, 3, 4, 0) - OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgr_to_rgba, 3, 4, 2) - OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgra_to_bgr, 4, 3, 0) - OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgra_to_rgb, 4, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgra_to_rgba, 4, 4, 2) - - #undef OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS - - OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(bgr_to_bgr555, 3, 0, 5) - OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(bgr_to_bgr565, 3, 0, 6) - OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(rgb_to_bgr555, 3, 2, 5) - OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(rgb_to_bgr565, 3, 2, 6) - OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(bgra_to_bgr555, 4, 0, 5) - OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(bgra_to_bgr565, 4, 0, 6) - OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(rgba_to_bgr555, 4, 2, 5) - OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(rgba_to_bgr565, 4, 2, 6) - - #undef OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS - - OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr555_to_rgb, 3, 2, 5) - OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr565_to_rgb, 3, 2, 6) - OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr555_to_bgr, 3, 0, 5) - OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr565_to_bgr, 3, 0, 6) - OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr555_to_rgba, 4, 2, 5) - OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr565_to_rgba, 4, 2, 6) - OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr555_to_bgra, 4, 0, 5) - OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr565_to_bgra, 4, 0, 6) - - #undef OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS - - OPENCV_CUDA_IMPLEMENT_GRAY2RGB_TRAITS(gray_to_bgr, 3) - OPENCV_CUDA_IMPLEMENT_GRAY2RGB_TRAITS(gray_to_bgra, 4) - - #undef OPENCV_CUDA_IMPLEMENT_GRAY2RGB_TRAITS - - OPENCV_CUDA_IMPLEMENT_GRAY2RGB5x5_TRAITS(gray_to_bgr555, 5) - OPENCV_CUDA_IMPLEMENT_GRAY2RGB5x5_TRAITS(gray_to_bgr565, 6) - - #undef OPENCV_CUDA_IMPLEMENT_GRAY2RGB5x5_TRAITS - - OPENCV_CUDA_IMPLEMENT_RGB5x52GRAY_TRAITS(bgr555_to_gray, 5) - OPENCV_CUDA_IMPLEMENT_RGB5x52GRAY_TRAITS(bgr565_to_gray, 6) - - #undef OPENCV_CUDA_IMPLEMENT_RGB5x52GRAY_TRAITS - - OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(rgb_to_gray, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(bgr_to_gray, 3, 0) - OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(rgba_to_gray, 4, 2) - OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(bgra_to_gray, 4, 0) - - #undef OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS - - OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(rgb_to_yuv, 3, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(rgba_to_yuv, 4, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(rgb_to_yuv4, 3, 4, 2) - OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(rgba_to_yuv4, 4, 4, 2) - OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(bgr_to_yuv, 3, 3, 0) - OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(bgra_to_yuv, 4, 3, 0) - OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(bgr_to_yuv4, 3, 4, 0) - OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(bgra_to_yuv4, 4, 4, 0) - - #undef OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS - - OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv_to_rgb, 3, 3, 2) - OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv_to_rgba, 3, 4, 2) - OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv4_to_rgb, 4, 3, 2) - OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv4_to_rgba, 4, 4, 2) - OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv_to_bgr, 3, 3, 0) - OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv_to_bgra, 3, 4, 0) - OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv4_to_bgr, 4, 3, 0) - OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv4_to_bgra, 4, 4, 0) - - #undef OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS - - OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(rgb_to_YCrCb, 3, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(rgba_to_YCrCb, 4, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(rgb_to_YCrCb4, 3, 4, 2) - OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(rgba_to_YCrCb4, 4, 4, 2) - OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(bgr_to_YCrCb, 3, 3, 0) - OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(bgra_to_YCrCb, 4, 3, 0) - OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(bgr_to_YCrCb4, 3, 4, 0) - OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(bgra_to_YCrCb4, 4, 4, 0) - - #undef OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS - - OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb_to_rgb, 3, 3, 2) - OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb_to_rgba, 3, 4, 2) - OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb4_to_rgb, 4, 3, 2) - OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb4_to_rgba, 4, 4, 2) - OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb_to_bgr, 3, 3, 0) - OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb_to_bgra, 3, 4, 0) - OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb4_to_bgr, 4, 3, 0) - OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb4_to_bgra, 4, 4, 0) - - #undef OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS - - OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(rgb_to_xyz, 3, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(rgba_to_xyz, 4, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(rgb_to_xyz4, 3, 4, 2) - OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(rgba_to_xyz4, 4, 4, 2) - OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(bgr_to_xyz, 3, 3, 0) - OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(bgra_to_xyz, 4, 3, 0) - OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(bgr_to_xyz4, 3, 4, 0) - OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(bgra_to_xyz4, 4, 4, 0) - - #undef OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS - - OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz_to_rgb, 3, 3, 2) - OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz4_to_rgb, 4, 3, 2) - OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz_to_rgba, 3, 4, 2) - OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz4_to_rgba, 4, 4, 2) - OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz_to_bgr, 3, 3, 0) - OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz4_to_bgr, 4, 3, 0) - OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz_to_bgra, 3, 4, 0) - OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz4_to_bgra, 4, 4, 0) - - #undef OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS - - OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(rgb_to_hsv, 3, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(rgba_to_hsv, 4, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(rgb_to_hsv4, 3, 4, 2) - OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(rgba_to_hsv4, 4, 4, 2) - OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(bgr_to_hsv, 3, 3, 0) - OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(bgra_to_hsv, 4, 3, 0) - OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(bgr_to_hsv4, 3, 4, 0) - OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(bgra_to_hsv4, 4, 4, 0) - - #undef OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS - - OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv_to_rgb, 3, 3, 2) - OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv_to_rgba, 3, 4, 2) - OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv4_to_rgb, 4, 3, 2) - OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv4_to_rgba, 4, 4, 2) - OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv_to_bgr, 3, 3, 0) - OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv_to_bgra, 3, 4, 0) - OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv4_to_bgr, 4, 3, 0) - OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv4_to_bgra, 4, 4, 0) - - #undef OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS - - OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(rgb_to_hls, 3, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(rgba_to_hls, 4, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(rgb_to_hls4, 3, 4, 2) - OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(rgba_to_hls4, 4, 4, 2) - OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(bgr_to_hls, 3, 3, 0) - OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(bgra_to_hls, 4, 3, 0) - OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(bgr_to_hls4, 3, 4, 0) - OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(bgra_to_hls4, 4, 4, 0) - - #undef OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS - - OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls_to_rgb, 3, 3, 2) - OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls_to_rgba, 3, 4, 2) - OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls4_to_rgb, 4, 3, 2) - OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls4_to_rgba, 4, 4, 2) - OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls_to_bgr, 3, 3, 0) - OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls_to_bgra, 3, 4, 0) - OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls4_to_bgr, 4, 3, 0) - OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls4_to_bgra, 4, 4, 0) - - #undef OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS - - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(rgb_to_lab, 3, 3, true, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(rgba_to_lab, 4, 3, true, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(rgb_to_lab4, 3, 4, true, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(rgba_to_lab4, 4, 4, true, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(bgr_to_lab, 3, 3, true, 0) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(bgra_to_lab, 4, 3, true, 0) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(bgr_to_lab4, 3, 4, true, 0) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(bgra_to_lab4, 4, 4, true, 0) - - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lrgb_to_lab, 3, 3, false, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lrgba_to_lab, 4, 3, false, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lrgb_to_lab4, 3, 4, false, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lrgba_to_lab4, 4, 4, false, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lbgr_to_lab, 3, 3, false, 0) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lbgra_to_lab, 4, 3, false, 0) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lbgr_to_lab4, 3, 4, false, 0) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lbgra_to_lab4, 4, 4, false, 0) - - #undef OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS - - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_rgb, 3, 3, true, 2) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_rgb, 4, 3, true, 2) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_rgba, 3, 4, true, 2) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_rgba, 4, 4, true, 2) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_bgr, 3, 3, true, 0) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_bgr, 4, 3, true, 0) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_bgra, 3, 4, true, 0) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_bgra, 4, 4, true, 0) - - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_lrgb, 3, 3, false, 2) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_lrgb, 4, 3, false, 2) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_lrgba, 3, 4, false, 2) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_lrgba, 4, 4, false, 2) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_lbgr, 3, 3, false, 0) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_lbgr, 4, 3, false, 0) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_lbgra, 3, 4, false, 0) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_lbgra, 4, 4, false, 0) - - #undef OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS - - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(rgb_to_luv, 3, 3, true, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(rgba_to_luv, 4, 3, true, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(rgb_to_luv4, 3, 4, true, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(rgba_to_luv4, 4, 4, true, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(bgr_to_luv, 3, 3, true, 0) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(bgra_to_luv, 4, 3, true, 0) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(bgr_to_luv4, 3, 4, true, 0) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(bgra_to_luv4, 4, 4, true, 0) - - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lrgb_to_luv, 3, 3, false, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lrgba_to_luv, 4, 3, false, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lrgb_to_luv4, 3, 4, false, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lrgba_to_luv4, 4, 4, false, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lbgr_to_luv, 3, 3, false, 0) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lbgra_to_luv, 4, 3, false, 0) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lbgr_to_luv4, 3, 4, false, 0) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lbgra_to_luv4, 4, 4, false, 0) - - #undef OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS - - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_rgb, 3, 3, true, 2) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_rgb, 4, 3, true, 2) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_rgba, 3, 4, true, 2) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_rgba, 4, 4, true, 2) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_bgr, 3, 3, true, 0) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_bgr, 4, 3, true, 0) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_bgra, 3, 4, true, 0) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_bgra, 4, 4, true, 0) - - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_lrgb, 3, 3, false, 2) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_lrgb, 4, 3, false, 2) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_lrgba, 3, 4, false, 2) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_lrgba, 4, 4, false, 2) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_lbgr, 3, 3, false, 0) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_lbgr, 4, 3, false, 0) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_lbgra, 3, 4, false, 0) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_lbgra, 4, 4, false, 0) - - #undef OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif // OPENCV_CUDA_COLOR_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_COLOR_HPP +#define OPENCV_CUDA_COLOR_HPP + +#include "detail/color_detail.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + // All OPENCV_CUDA_IMPLEMENT_*_TRAITS(ColorSpace1_to_ColorSpace2, ...) macros implements + // template class ColorSpace1_to_ColorSpace2_traits + // { + // typedef ... functor_type; + // static __host__ __device__ functor_type create_functor(); + // }; + + OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgr_to_rgb, 3, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgr_to_bgra, 3, 4, 0) + OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgr_to_rgba, 3, 4, 2) + OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgra_to_bgr, 4, 3, 0) + OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgra_to_rgb, 4, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgra_to_rgba, 4, 4, 2) + + #undef OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS + + OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(bgr_to_bgr555, 3, 0, 5) + OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(bgr_to_bgr565, 3, 0, 6) + OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(rgb_to_bgr555, 3, 2, 5) + OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(rgb_to_bgr565, 3, 2, 6) + OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(bgra_to_bgr555, 4, 0, 5) + OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(bgra_to_bgr565, 4, 0, 6) + OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(rgba_to_bgr555, 4, 2, 5) + OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(rgba_to_bgr565, 4, 2, 6) + + #undef OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS + + OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr555_to_rgb, 3, 2, 5) + OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr565_to_rgb, 3, 2, 6) + OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr555_to_bgr, 3, 0, 5) + OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr565_to_bgr, 3, 0, 6) + OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr555_to_rgba, 4, 2, 5) + OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr565_to_rgba, 4, 2, 6) + OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr555_to_bgra, 4, 0, 5) + OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr565_to_bgra, 4, 0, 6) + + #undef OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS + + OPENCV_CUDA_IMPLEMENT_GRAY2RGB_TRAITS(gray_to_bgr, 3) + OPENCV_CUDA_IMPLEMENT_GRAY2RGB_TRAITS(gray_to_bgra, 4) + + #undef OPENCV_CUDA_IMPLEMENT_GRAY2RGB_TRAITS + + OPENCV_CUDA_IMPLEMENT_GRAY2RGB5x5_TRAITS(gray_to_bgr555, 5) + OPENCV_CUDA_IMPLEMENT_GRAY2RGB5x5_TRAITS(gray_to_bgr565, 6) + + #undef OPENCV_CUDA_IMPLEMENT_GRAY2RGB5x5_TRAITS + + OPENCV_CUDA_IMPLEMENT_RGB5x52GRAY_TRAITS(bgr555_to_gray, 5) + OPENCV_CUDA_IMPLEMENT_RGB5x52GRAY_TRAITS(bgr565_to_gray, 6) + + #undef OPENCV_CUDA_IMPLEMENT_RGB5x52GRAY_TRAITS + + OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(rgb_to_gray, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(bgr_to_gray, 3, 0) + OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(rgba_to_gray, 4, 2) + OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(bgra_to_gray, 4, 0) + + #undef OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS + + OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(rgb_to_yuv, 3, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(rgba_to_yuv, 4, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(rgb_to_yuv4, 3, 4, 2) + OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(rgba_to_yuv4, 4, 4, 2) + OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(bgr_to_yuv, 3, 3, 0) + OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(bgra_to_yuv, 4, 3, 0) + OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(bgr_to_yuv4, 3, 4, 0) + OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(bgra_to_yuv4, 4, 4, 0) + + #undef OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS + + OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv_to_rgb, 3, 3, 2) + OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv_to_rgba, 3, 4, 2) + OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv4_to_rgb, 4, 3, 2) + OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv4_to_rgba, 4, 4, 2) + OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv_to_bgr, 3, 3, 0) + OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv_to_bgra, 3, 4, 0) + OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv4_to_bgr, 4, 3, 0) + OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv4_to_bgra, 4, 4, 0) + + #undef OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS + + OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(rgb_to_YCrCb, 3, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(rgba_to_YCrCb, 4, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(rgb_to_YCrCb4, 3, 4, 2) + OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(rgba_to_YCrCb4, 4, 4, 2) + OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(bgr_to_YCrCb, 3, 3, 0) + OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(bgra_to_YCrCb, 4, 3, 0) + OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(bgr_to_YCrCb4, 3, 4, 0) + OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(bgra_to_YCrCb4, 4, 4, 0) + + #undef OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS + + OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb_to_rgb, 3, 3, 2) + OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb_to_rgba, 3, 4, 2) + OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb4_to_rgb, 4, 3, 2) + OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb4_to_rgba, 4, 4, 2) + OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb_to_bgr, 3, 3, 0) + OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb_to_bgra, 3, 4, 0) + OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb4_to_bgr, 4, 3, 0) + OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb4_to_bgra, 4, 4, 0) + + #undef OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS + + OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(rgb_to_xyz, 3, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(rgba_to_xyz, 4, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(rgb_to_xyz4, 3, 4, 2) + OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(rgba_to_xyz4, 4, 4, 2) + OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(bgr_to_xyz, 3, 3, 0) + OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(bgra_to_xyz, 4, 3, 0) + OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(bgr_to_xyz4, 3, 4, 0) + OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(bgra_to_xyz4, 4, 4, 0) + + #undef OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS + + OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz_to_rgb, 3, 3, 2) + OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz4_to_rgb, 4, 3, 2) + OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz_to_rgba, 3, 4, 2) + OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz4_to_rgba, 4, 4, 2) + OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz_to_bgr, 3, 3, 0) + OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz4_to_bgr, 4, 3, 0) + OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz_to_bgra, 3, 4, 0) + OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz4_to_bgra, 4, 4, 0) + + #undef OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS + + OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(rgb_to_hsv, 3, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(rgba_to_hsv, 4, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(rgb_to_hsv4, 3, 4, 2) + OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(rgba_to_hsv4, 4, 4, 2) + OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(bgr_to_hsv, 3, 3, 0) + OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(bgra_to_hsv, 4, 3, 0) + OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(bgr_to_hsv4, 3, 4, 0) + OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(bgra_to_hsv4, 4, 4, 0) + + #undef OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS + + OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv_to_rgb, 3, 3, 2) + OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv_to_rgba, 3, 4, 2) + OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv4_to_rgb, 4, 3, 2) + OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv4_to_rgba, 4, 4, 2) + OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv_to_bgr, 3, 3, 0) + OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv_to_bgra, 3, 4, 0) + OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv4_to_bgr, 4, 3, 0) + OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv4_to_bgra, 4, 4, 0) + + #undef OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS + + OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(rgb_to_hls, 3, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(rgba_to_hls, 4, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(rgb_to_hls4, 3, 4, 2) + OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(rgba_to_hls4, 4, 4, 2) + OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(bgr_to_hls, 3, 3, 0) + OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(bgra_to_hls, 4, 3, 0) + OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(bgr_to_hls4, 3, 4, 0) + OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(bgra_to_hls4, 4, 4, 0) + + #undef OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS + + OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls_to_rgb, 3, 3, 2) + OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls_to_rgba, 3, 4, 2) + OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls4_to_rgb, 4, 3, 2) + OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls4_to_rgba, 4, 4, 2) + OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls_to_bgr, 3, 3, 0) + OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls_to_bgra, 3, 4, 0) + OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls4_to_bgr, 4, 3, 0) + OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls4_to_bgra, 4, 4, 0) + + #undef OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS + + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(rgb_to_lab, 3, 3, true, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(rgba_to_lab, 4, 3, true, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(rgb_to_lab4, 3, 4, true, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(rgba_to_lab4, 4, 4, true, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(bgr_to_lab, 3, 3, true, 0) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(bgra_to_lab, 4, 3, true, 0) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(bgr_to_lab4, 3, 4, true, 0) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(bgra_to_lab4, 4, 4, true, 0) + + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lrgb_to_lab, 3, 3, false, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lrgba_to_lab, 4, 3, false, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lrgb_to_lab4, 3, 4, false, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lrgba_to_lab4, 4, 4, false, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lbgr_to_lab, 3, 3, false, 0) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lbgra_to_lab, 4, 3, false, 0) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lbgr_to_lab4, 3, 4, false, 0) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lbgra_to_lab4, 4, 4, false, 0) + + #undef OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS + + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_rgb, 3, 3, true, 2) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_rgb, 4, 3, true, 2) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_rgba, 3, 4, true, 2) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_rgba, 4, 4, true, 2) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_bgr, 3, 3, true, 0) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_bgr, 4, 3, true, 0) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_bgra, 3, 4, true, 0) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_bgra, 4, 4, true, 0) + + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_lrgb, 3, 3, false, 2) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_lrgb, 4, 3, false, 2) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_lrgba, 3, 4, false, 2) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_lrgba, 4, 4, false, 2) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_lbgr, 3, 3, false, 0) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_lbgr, 4, 3, false, 0) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_lbgra, 3, 4, false, 0) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_lbgra, 4, 4, false, 0) + + #undef OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS + + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(rgb_to_luv, 3, 3, true, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(rgba_to_luv, 4, 3, true, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(rgb_to_luv4, 3, 4, true, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(rgba_to_luv4, 4, 4, true, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(bgr_to_luv, 3, 3, true, 0) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(bgra_to_luv, 4, 3, true, 0) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(bgr_to_luv4, 3, 4, true, 0) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(bgra_to_luv4, 4, 4, true, 0) + + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lrgb_to_luv, 3, 3, false, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lrgba_to_luv, 4, 3, false, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lrgb_to_luv4, 3, 4, false, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lrgba_to_luv4, 4, 4, false, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lbgr_to_luv, 3, 3, false, 0) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lbgra_to_luv, 4, 3, false, 0) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lbgr_to_luv4, 3, 4, false, 0) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lbgra_to_luv4, 4, 4, false, 0) + + #undef OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS + + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_rgb, 3, 3, true, 2) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_rgb, 4, 3, true, 2) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_rgba, 3, 4, true, 2) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_rgba, 4, 4, true, 2) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_bgr, 3, 3, true, 0) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_bgr, 4, 3, true, 0) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_bgra, 3, 4, true, 0) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_bgra, 4, 4, true, 0) + + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_lrgb, 3, 3, false, 2) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_lrgb, 4, 3, false, 2) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_lrgba, 3, 4, false, 2) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_lrgba, 4, 4, false, 2) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_lbgr, 3, 3, false, 0) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_lbgr, 4, 3, false, 0) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_lbgra, 3, 4, false, 0) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_lbgra, 4, 4, false, 0) + + #undef OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif // OPENCV_CUDA_COLOR_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/common.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/common.hpp index 1e1d5de1b0..58cf9d8579 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/common.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/common.hpp @@ -1,131 +1,131 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_COMMON_HPP -#define OPENCV_CUDA_COMMON_HPP - -#include -#include "opencv2/core/cuda_types.hpp" -#include "opencv2/core/cvdef.h" -#include "opencv2/core/base.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -#ifndef CV_PI_F - #ifndef CV_PI - #define CV_PI_F 3.14159265f - #else - #define CV_PI_F ((float)CV_PI) - #endif -#endif - -namespace cv { namespace cuda { - static inline void checkCudaError(cudaError_t err, const char* file, const int line, const char* func) - { - if (cudaSuccess != err) { - cudaGetLastError(); // reset the last stored error to cudaSuccess - cv::error(cv::Error::GpuApiCallError, cudaGetErrorString(err), func, file, line); - } - } -}} - -#ifndef cudaSafeCall - #define cudaSafeCall(expr) cv::cuda::checkCudaError(expr, __FILE__, __LINE__, CV_Func) -#endif - -namespace cv { namespace cuda -{ - template static inline bool isAligned(const T* ptr, size_t size) - { - return reinterpret_cast(ptr) % size == 0; - } - - static inline bool isAligned(size_t step, size_t size) - { - return step % size == 0; - } -}} - -namespace cv { namespace cuda -{ - namespace device - { - __host__ __device__ __forceinline__ int divUp(int total, int grain) - { - return (total + grain - 1) / grain; - } - -#if (CUDART_VERSION >= 12000) - template inline void createTextureObjectPitch2D(cudaTextureObject_t*, PtrStepSz&, const cudaTextureDesc&) { - CV_Error(cv::Error::GpuNotSupported, "Function removed in CUDA SDK 12"); } -#else - //TODO: remove from OpenCV 5.x - template inline void bindTexture(const textureReference* tex, const PtrStepSz& img) - { - cudaChannelFormatDesc desc = cudaCreateChannelDesc(); - cudaSafeCall( cudaBindTexture2D(0, tex, img.ptr(), &desc, img.cols, img.rows, img.step) ); - } - - template inline void createTextureObjectPitch2D(cudaTextureObject_t* tex, PtrStepSz& img, const cudaTextureDesc& texDesc) - { - cudaResourceDesc resDesc; - memset(&resDesc, 0, sizeof(resDesc)); - resDesc.resType = cudaResourceTypePitch2D; - resDesc.res.pitch2D.devPtr = static_cast(img.ptr()); - resDesc.res.pitch2D.height = img.rows; - resDesc.res.pitch2D.width = img.cols; - resDesc.res.pitch2D.pitchInBytes = img.step; - resDesc.res.pitch2D.desc = cudaCreateChannelDesc(); - - cudaSafeCall( cudaCreateTextureObject(tex, &resDesc, &texDesc, NULL) ); - } -#endif - } -}} - -//! @endcond - -#endif // OPENCV_CUDA_COMMON_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_COMMON_HPP +#define OPENCV_CUDA_COMMON_HPP + +#include +#include "opencv2/core/cuda_types.hpp" +#include "opencv2/core/cvdef.h" +#include "opencv2/core/base.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +#ifndef CV_PI_F + #ifndef CV_PI + #define CV_PI_F 3.14159265f + #else + #define CV_PI_F ((float)CV_PI) + #endif +#endif + +namespace cv { namespace cuda { + static inline void checkCudaError(cudaError_t err, const char* file, const int line, const char* func) + { + if (cudaSuccess != err) { + cudaGetLastError(); // reset the last stored error to cudaSuccess + cv::error(cv::Error::GpuApiCallError, cudaGetErrorString(err), func, file, line); + } + } +}} + +#ifndef cudaSafeCall + #define cudaSafeCall(expr) cv::cuda::checkCudaError(expr, __FILE__, __LINE__, CV_Func) +#endif + +namespace cv { namespace cuda +{ + template static inline bool isAligned(const T* ptr, size_t size) + { + return reinterpret_cast(ptr) % size == 0; + } + + static inline bool isAligned(size_t step, size_t size) + { + return step % size == 0; + } +}} + +namespace cv { namespace cuda +{ + namespace device + { + __host__ __device__ __forceinline__ int divUp(int total, int grain) + { + return (total + grain - 1) / grain; + } + +#if (CUDART_VERSION >= 12000) + template inline void createTextureObjectPitch2D(cudaTextureObject_t*, PtrStepSz&, const cudaTextureDesc&) { + CV_Error(cv::Error::GpuNotSupported, "Function removed in CUDA SDK 12"); } +#else + //TODO: remove from OpenCV 5.x + template inline void bindTexture(const textureReference* tex, const PtrStepSz& img) + { + cudaChannelFormatDesc desc = cudaCreateChannelDesc(); + cudaSafeCall( cudaBindTexture2D(0, tex, img.ptr(), &desc, img.cols, img.rows, img.step) ); + } + + template inline void createTextureObjectPitch2D(cudaTextureObject_t* tex, PtrStepSz& img, const cudaTextureDesc& texDesc) + { + cudaResourceDesc resDesc; + memset(&resDesc, 0, sizeof(resDesc)); + resDesc.resType = cudaResourceTypePitch2D; + resDesc.res.pitch2D.devPtr = static_cast(img.ptr()); + resDesc.res.pitch2D.height = img.rows; + resDesc.res.pitch2D.width = img.cols; + resDesc.res.pitch2D.pitchInBytes = img.step; + resDesc.res.pitch2D.desc = cudaCreateChannelDesc(); + + cudaSafeCall( cudaCreateTextureObject(tex, &resDesc, &texDesc, NULL) ); + } +#endif + } +}} + +//! @endcond + +#endif // OPENCV_CUDA_COMMON_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/datamov_utils.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/datamov_utils.hpp index 6820d0fd64..46eb4e0f81 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/datamov_utils.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/datamov_utils.hpp @@ -1,113 +1,113 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_DATAMOV_UTILS_HPP -#define OPENCV_CUDA_DATAMOV_UTILS_HPP - -#include "common.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 200 - - // for Fermi memory space is detected automatically - template struct ForceGlob - { - __device__ __forceinline__ static void Load(const T* ptr, int offset, T& val) { val = ptr[offset]; } - }; - - #else // __CUDA_ARCH__ >= 200 - - #if defined(_WIN64) || defined(__LP64__) - // 64-bit register modifier for inlined asm - #define OPENCV_CUDA_ASM_PTR "l" - #else - // 32-bit register modifier for inlined asm - #define OPENCV_CUDA_ASM_PTR "r" - #endif - - template struct ForceGlob; - - #define OPENCV_CUDA_DEFINE_FORCE_GLOB(base_type, ptx_type, reg_mod) \ - template <> struct ForceGlob \ - { \ - __device__ __forceinline__ static void Load(const base_type* ptr, int offset, base_type& val) \ - { \ - asm("ld.global."#ptx_type" %0, [%1];" : "="#reg_mod(val) : OPENCV_CUDA_ASM_PTR(ptr + offset)); \ - } \ - }; - - #define OPENCV_CUDA_DEFINE_FORCE_GLOB_B(base_type, ptx_type) \ - template <> struct ForceGlob \ - { \ - __device__ __forceinline__ static void Load(const base_type* ptr, int offset, base_type& val) \ - { \ - asm("ld.global."#ptx_type" %0, [%1];" : "=r"(*reinterpret_cast(&val)) : OPENCV_CUDA_ASM_PTR(ptr + offset)); \ - } \ - }; - - OPENCV_CUDA_DEFINE_FORCE_GLOB_B(uchar, u8) - OPENCV_CUDA_DEFINE_FORCE_GLOB_B(schar, s8) - OPENCV_CUDA_DEFINE_FORCE_GLOB_B(char, b8) - OPENCV_CUDA_DEFINE_FORCE_GLOB (ushort, u16, h) - OPENCV_CUDA_DEFINE_FORCE_GLOB (short, s16, h) - OPENCV_CUDA_DEFINE_FORCE_GLOB (uint, u32, r) - OPENCV_CUDA_DEFINE_FORCE_GLOB (int, s32, r) - OPENCV_CUDA_DEFINE_FORCE_GLOB (float, f32, f) - OPENCV_CUDA_DEFINE_FORCE_GLOB (double, f64, d) - - #undef OPENCV_CUDA_DEFINE_FORCE_GLOB - #undef OPENCV_CUDA_DEFINE_FORCE_GLOB_B - #undef OPENCV_CUDA_ASM_PTR - - #endif // __CUDA_ARCH__ >= 200 -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif // OPENCV_CUDA_DATAMOV_UTILS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_DATAMOV_UTILS_HPP +#define OPENCV_CUDA_DATAMOV_UTILS_HPP + +#include "common.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 200 + + // for Fermi memory space is detected automatically + template struct ForceGlob + { + __device__ __forceinline__ static void Load(const T* ptr, int offset, T& val) { val = ptr[offset]; } + }; + + #else // __CUDA_ARCH__ >= 200 + + #if defined(_WIN64) || defined(__LP64__) + // 64-bit register modifier for inlined asm + #define OPENCV_CUDA_ASM_PTR "l" + #else + // 32-bit register modifier for inlined asm + #define OPENCV_CUDA_ASM_PTR "r" + #endif + + template struct ForceGlob; + + #define OPENCV_CUDA_DEFINE_FORCE_GLOB(base_type, ptx_type, reg_mod) \ + template <> struct ForceGlob \ + { \ + __device__ __forceinline__ static void Load(const base_type* ptr, int offset, base_type& val) \ + { \ + asm("ld.global."#ptx_type" %0, [%1];" : "="#reg_mod(val) : OPENCV_CUDA_ASM_PTR(ptr + offset)); \ + } \ + }; + + #define OPENCV_CUDA_DEFINE_FORCE_GLOB_B(base_type, ptx_type) \ + template <> struct ForceGlob \ + { \ + __device__ __forceinline__ static void Load(const base_type* ptr, int offset, base_type& val) \ + { \ + asm("ld.global."#ptx_type" %0, [%1];" : "=r"(*reinterpret_cast(&val)) : OPENCV_CUDA_ASM_PTR(ptr + offset)); \ + } \ + }; + + OPENCV_CUDA_DEFINE_FORCE_GLOB_B(uchar, u8) + OPENCV_CUDA_DEFINE_FORCE_GLOB_B(schar, s8) + OPENCV_CUDA_DEFINE_FORCE_GLOB_B(char, b8) + OPENCV_CUDA_DEFINE_FORCE_GLOB (ushort, u16, h) + OPENCV_CUDA_DEFINE_FORCE_GLOB (short, s16, h) + OPENCV_CUDA_DEFINE_FORCE_GLOB (uint, u32, r) + OPENCV_CUDA_DEFINE_FORCE_GLOB (int, s32, r) + OPENCV_CUDA_DEFINE_FORCE_GLOB (float, f32, f) + OPENCV_CUDA_DEFINE_FORCE_GLOB (double, f64, d) + + #undef OPENCV_CUDA_DEFINE_FORCE_GLOB + #undef OPENCV_CUDA_DEFINE_FORCE_GLOB_B + #undef OPENCV_CUDA_ASM_PTR + + #endif // __CUDA_ARCH__ >= 200 +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif // OPENCV_CUDA_DATAMOV_UTILS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/color_detail.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/color_detail.hpp index f4b4796571..fbe8c82dc7 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/color_detail.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/color_detail.hpp @@ -1,2018 +1,2018 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_COLOR_DETAIL_HPP -#define OPENCV_CUDA_COLOR_DETAIL_HPP - -#include "../common.hpp" -#include "../vec_traits.hpp" -#include "../saturate_cast.hpp" -#include "../limits.hpp" -#include "../functional.hpp" - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - #ifndef CV_DESCALE - #define CV_DESCALE(x, n) (((x) + (1 << ((n)-1))) >> (n)) - #endif - - namespace color_detail - { - template struct ColorChannel - { - typedef float worktype_f; - static __device__ __forceinline__ T max() { return numeric_limits::max(); } - static __device__ __forceinline__ T half() { return (T)(max()/2 + 1); } - }; - - template<> struct ColorChannel - { - typedef float worktype_f; - static __device__ __forceinline__ float max() { return 1.f; } - static __device__ __forceinline__ float half() { return 0.5f; } - }; - - template static __device__ __forceinline__ void setAlpha(typename TypeVec::vec_type& vec, T val) - { - } - - template static __device__ __forceinline__ void setAlpha(typename TypeVec::vec_type& vec, T val) - { - vec.w = val; - } - - template static __device__ __forceinline__ T getAlpha(const typename TypeVec::vec_type& vec) - { - return ColorChannel::max(); - } - - template static __device__ __forceinline__ T getAlpha(const typename TypeVec::vec_type& vec) - { - return vec.w; - } - - //constants for conversion from/to RGB and Gray, YUV, YCrCb according to BT.601 - constexpr float B2YF = 0.114f; - constexpr float G2YF = 0.587f; - constexpr float R2YF = 0.299f; - - //to YCbCr - constexpr float YCBF = 0.564f; // == 1/2/(1-B2YF) - constexpr float YCRF = 0.713f; // == 1/2/(1-R2YF) - const int YCBI = 9241; // == YCBF*16384 - const int YCRI = 11682; // == YCRF*16384 - //to YUV - constexpr float B2UF = 0.492f; - constexpr float R2VF = 0.877f; - const int B2UI = 8061; // == B2UF*16384 - const int R2VI = 14369; // == R2VF*16384 - //from YUV - constexpr float U2BF = 2.032f; - constexpr float U2GF = -0.395f; - constexpr float V2GF = -0.581f; - constexpr float V2RF = 1.140f; - const int U2BI = 33292; - const int U2GI = -6472; - const int V2GI = -9519; - const int V2RI = 18678; - //from YCrCb - constexpr float CB2BF = 1.773f; - constexpr float CB2GF = -0.344f; - constexpr float CR2GF = -0.714f; - constexpr float CR2RF = 1.403f; - const int CB2BI = 29049; - const int CB2GI = -5636; - const int CR2GI = -11698; - const int CR2RI = 22987; - - enum - { - yuv_shift = 14, - xyz_shift = 12, - gray_shift = 15, - R2Y = 4899, - G2Y = 9617, - B2Y = 1868, - RY15 = 9798, // == R2YF*32768 + 0.5 - GY15 = 19235, // == G2YF*32768 + 0.5 - BY15 = 3735, // == B2YF*32768 + 0.5 - BLOCK_SIZE = 256 - }; - } - -////////////////// Various 3/4-channel to 3/4-channel RGB transformations ///////////////// - - namespace color_detail - { - template struct RGB2RGB - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - dst.x = (&src.x)[bidx]; - dst.y = src.y; - dst.z = (&src.x)[bidx^2]; - setAlpha(dst, getAlpha(src)); - - return dst; - } - - __host__ __device__ __forceinline__ RGB2RGB() {} - __host__ __device__ __forceinline__ RGB2RGB(const RGB2RGB&) {} - }; - - template <> struct RGB2RGB : unary_function - { - __device__ uint operator()(uint src) const - { - uint dst = 0; - - dst |= (0xffu & (src >> 16)); - dst |= (0xffu & (src >> 8)) << 8; - dst |= (0xffu & (src)) << 16; - dst |= (0xffu & (src >> 24)) << 24; - - return dst; - } - - __host__ __device__ __forceinline__ RGB2RGB() {} - __host__ __device__ __forceinline__ RGB2RGB(const RGB2RGB&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(name, scn, dcn, bidx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - -/////////// Transforming 16-bit (565 or 555) RGB to/from 24/32-bit (888[8]) RGB ////////// - - namespace color_detail - { - template struct RGB2RGB5x5Converter; - template struct RGB2RGB5x5Converter<6, bidx> - { - static __device__ __forceinline__ ushort cvt(const uchar3& src) - { - return (ushort)(((&src.x)[bidx] >> 3) | ((src.y & ~3) << 3) | (((&src.x)[bidx^2] & ~7) << 8)); - } - - static __device__ __forceinline__ ushort cvt(uint src) - { - uint b = 0xffu & (src >> (bidx * 8)); - uint g = 0xffu & (src >> 8); - uint r = 0xffu & (src >> ((bidx ^ 2) * 8)); - return (ushort)((b >> 3) | ((g & ~3) << 3) | ((r & ~7) << 8)); - } - }; - - template struct RGB2RGB5x5Converter<5, bidx> - { - static __device__ __forceinline__ ushort cvt(const uchar3& src) - { - return (ushort)(((&src.x)[bidx] >> 3) | ((src.y & ~7) << 2) | (((&src.x)[bidx^2] & ~7) << 7)); - } - - static __device__ __forceinline__ ushort cvt(uint src) - { - uint b = 0xffu & (src >> (bidx * 8)); - uint g = 0xffu & (src >> 8); - uint r = 0xffu & (src >> ((bidx ^ 2) * 8)); - uint a = 0xffu & (src >> 24); - return (ushort)((b >> 3) | ((g & ~7) << 2) | ((r & ~7) << 7) | (a * 0x8000)); - } - }; - - template struct RGB2RGB5x5; - - template struct RGB2RGB5x5<3, bidx,green_bits> : unary_function - { - __device__ __forceinline__ ushort operator()(const uchar3& src) const - { - return RGB2RGB5x5Converter::cvt(src); - } - - __host__ __device__ __forceinline__ RGB2RGB5x5() {} - __host__ __device__ __forceinline__ RGB2RGB5x5(const RGB2RGB5x5&) {} - }; - - template struct RGB2RGB5x5<4, bidx,green_bits> : unary_function - { - __device__ __forceinline__ ushort operator()(uint src) const - { - return RGB2RGB5x5Converter::cvt(src); - } - - __host__ __device__ __forceinline__ RGB2RGB5x5() {} - __host__ __device__ __forceinline__ RGB2RGB5x5(const RGB2RGB5x5&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(name, scn, bidx, green_bits) \ - struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2RGB5x5 functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - - namespace color_detail - { - template struct RGB5x52RGBConverter; - - template struct RGB5x52RGBConverter<5, bidx> - { - static __device__ __forceinline__ void cvt(uint src, uchar3& dst) - { - (&dst.x)[bidx] = src << 3; - dst.y = (src >> 2) & ~7; - (&dst.x)[bidx ^ 2] = (src >> 7) & ~7; - } - - static __device__ __forceinline__ void cvt(uint src, uint& dst) - { - dst = 0; - - dst |= (0xffu & (src << 3)) << (bidx * 8); - dst |= (0xffu & ((src >> 2) & ~7)) << 8; - dst |= (0xffu & ((src >> 7) & ~7)) << ((bidx ^ 2) * 8); - dst |= ((src & 0x8000) * 0xffu) << 24; - } - }; - - template struct RGB5x52RGBConverter<6, bidx> - { - static __device__ __forceinline__ void cvt(uint src, uchar3& dst) - { - (&dst.x)[bidx] = src << 3; - dst.y = (src >> 3) & ~3; - (&dst.x)[bidx ^ 2] = (src >> 8) & ~7; - } - - static __device__ __forceinline__ void cvt(uint src, uint& dst) - { - dst = 0xffu << 24; - - dst |= (0xffu & (src << 3)) << (bidx * 8); - dst |= (0xffu &((src >> 3) & ~3)) << 8; - dst |= (0xffu & ((src >> 8) & ~7)) << ((bidx ^ 2) * 8); - } - }; - - template struct RGB5x52RGB; - - template struct RGB5x52RGB<3, bidx, green_bits> : unary_function - { - __device__ __forceinline__ uchar3 operator()(ushort src) const - { - uchar3 dst; - RGB5x52RGBConverter::cvt(src, dst); - return dst; - } - __host__ __device__ __forceinline__ RGB5x52RGB() {} - __host__ __device__ __forceinline__ RGB5x52RGB(const RGB5x52RGB&) {} - - }; - - template struct RGB5x52RGB<4, bidx, green_bits> : unary_function - { - __device__ __forceinline__ uint operator()(ushort src) const - { - uint dst; - RGB5x52RGBConverter::cvt(src, dst); - return dst; - } - __host__ __device__ __forceinline__ RGB5x52RGB() {} - __host__ __device__ __forceinline__ RGB5x52RGB(const RGB5x52RGB&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(name, dcn, bidx, green_bits) \ - struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB5x52RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - -///////////////////////////////// Grayscale to Color //////////////////////////////// - - namespace color_detail - { - template struct Gray2RGB : unary_function::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator()(T src) const - { - typename TypeVec::vec_type dst; - - dst.z = dst.y = dst.x = src; - setAlpha(dst, ColorChannel::max()); - - return dst; - } - __host__ __device__ __forceinline__ Gray2RGB() {} - __host__ __device__ __forceinline__ Gray2RGB(const Gray2RGB&) {} - }; - - template <> struct Gray2RGB : unary_function - { - __device__ __forceinline__ uint operator()(uint src) const - { - uint dst = 0xffu << 24; - - dst |= src; - dst |= src << 8; - dst |= src << 16; - - return dst; - } - __host__ __device__ __forceinline__ Gray2RGB() {} - __host__ __device__ __forceinline__ Gray2RGB(const Gray2RGB&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_GRAY2RGB_TRAITS(name, dcn) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::Gray2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - - namespace color_detail - { - template struct Gray2RGB5x5Converter; - template<> struct Gray2RGB5x5Converter<6> - { - static __device__ __forceinline__ ushort cvt(uint t) - { - return (ushort)((t >> 3) | ((t & ~3) << 3) | ((t & ~7) << 8)); - } - }; - - template<> struct Gray2RGB5x5Converter<5> - { - static __device__ __forceinline__ ushort cvt(uint t) - { - t >>= 3; - return (ushort)(t | (t << 5) | (t << 10)); - } - }; - - template struct Gray2RGB5x5 : unary_function - { - __device__ __forceinline__ ushort operator()(uint src) const - { - return Gray2RGB5x5Converter::cvt(src); - } - - __host__ __device__ __forceinline__ Gray2RGB5x5() {} - __host__ __device__ __forceinline__ Gray2RGB5x5(const Gray2RGB5x5&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_GRAY2RGB5x5_TRAITS(name, green_bits) \ - struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::Gray2RGB5x5 functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - -///////////////////////////////// Color to Grayscale //////////////////////////////// - - namespace color_detail - { - template struct RGB5x52GrayConverter; - template <> struct RGB5x52GrayConverter<6> - { - static __device__ __forceinline__ uchar cvt(uint t) - { - return (uchar)CV_DESCALE(((t << 3) & 0xf8) * BY15 + ((t >> 3) & 0xfc) * GY15 + ((t >> 8) & 0xf8) * RY15, gray_shift); - } - }; - - template <> struct RGB5x52GrayConverter<5> - { - static __device__ __forceinline__ uchar cvt(uint t) - { - return (uchar)CV_DESCALE(((t << 3) & 0xf8) * BY15 + ((t >> 2) & 0xf8) * GY15 + ((t >> 7) & 0xf8) * RY15, gray_shift); - } - }; - - template struct RGB5x52Gray : unary_function - { - __device__ __forceinline__ uchar operator()(uint src) const - { - return RGB5x52GrayConverter::cvt(src); - } - __host__ __device__ __forceinline__ RGB5x52Gray() {} - __host__ __device__ __forceinline__ RGB5x52Gray(const RGB5x52Gray&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_RGB5x52GRAY_TRAITS(name, green_bits) \ - struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB5x52Gray functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - - namespace color_detail - { - template static __device__ __forceinline__ T RGB2GrayConvert(const T* src) - { - return (T)CV_DESCALE((unsigned)(src[bidx] * BY15 + src[1] * GY15 + src[bidx^2] * RY15), gray_shift); - } - - template static __device__ __forceinline__ uchar RGB2GrayConvert(uint src) - { - uint b = 0xffu & (src >> (bidx * 8)); - uint g = 0xffu & (src >> 8); - uint r = 0xffu & (src >> ((bidx ^ 2) * 8)); - return CV_DESCALE((uint)(b * BY15 + g * GY15 + r * RY15), gray_shift); - } - - template static __device__ __forceinline__ float RGB2GrayConvert(const float* src) - { - return src[bidx] * B2YF + src[1] * G2YF + src[bidx^2] * R2YF; - } - - template struct RGB2Gray : unary_function::vec_type, T> - { - __device__ __forceinline__ T operator()(const typename TypeVec::vec_type& src) const - { - return RGB2GrayConvert(&src.x); - } - __host__ __device__ __forceinline__ RGB2Gray() {} - __host__ __device__ __forceinline__ RGB2Gray(const RGB2Gray&) {} - }; - - template struct RGB2Gray : unary_function - { - __device__ __forceinline__ uchar operator()(uint src) const - { - return RGB2GrayConvert(src); - } - __host__ __device__ __forceinline__ RGB2Gray() {} - __host__ __device__ __forceinline__ RGB2Gray(const RGB2Gray&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(name, scn, bidx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2Gray functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - -///////////////////////////////////// RGB <-> YUV ////////////////////////////////////// - - namespace color_detail - { - __constant__ float c_RGB2YUVCoeffs_f[5] = { B2YF, G2YF, R2YF, B2UF, R2VF }; - __constant__ int c_RGB2YUVCoeffs_i[5] = { B2Y, G2Y, R2Y, B2UI, R2VI }; - - template static __device__ void RGB2YUVConvert(const T* src, D& dst) - { - const int delta = ColorChannel::half() * (1 << yuv_shift); - - const int Y = CV_DESCALE(src[0] * c_RGB2YUVCoeffs_i[bidx^2] + src[1] * c_RGB2YUVCoeffs_i[1] + src[2] * c_RGB2YUVCoeffs_i[bidx], yuv_shift); - const int Cr = CV_DESCALE((src[bidx^2] - Y) * c_RGB2YUVCoeffs_i[3] + delta, yuv_shift); - const int Cb = CV_DESCALE((src[bidx] - Y) * c_RGB2YUVCoeffs_i[4] + delta, yuv_shift); - - dst.x = saturate_cast(Y); - dst.y = saturate_cast(Cr); - dst.z = saturate_cast(Cb); - } - - template static __device__ __forceinline__ void RGB2YUVConvert(const float* src, D& dst) - { - dst.x = src[0] * c_RGB2YUVCoeffs_f[bidx^2] + src[1] * c_RGB2YUVCoeffs_f[1] + src[2] * c_RGB2YUVCoeffs_f[bidx]; - dst.y = (src[bidx^2] - dst.x) * c_RGB2YUVCoeffs_f[3] + ColorChannel::half(); - dst.z = (src[bidx] - dst.x) * c_RGB2YUVCoeffs_f[4] + ColorChannel::half(); - } - - template struct RGB2YUV - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - RGB2YUVConvert(&src.x, dst); - return dst; - } - __host__ __device__ __forceinline__ RGB2YUV() {} - __host__ __device__ __forceinline__ RGB2YUV(const RGB2YUV&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(name, scn, dcn, bidx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2YUV functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - - namespace color_detail - { - __constant__ float c_YUV2RGBCoeffs_f[5] = { U2BF, U2GF, V2GF, V2RF }; - __constant__ int c_YUV2RGBCoeffs_i[5] = { U2BI, U2GI, V2GI, V2RI }; - - template static __device__ void YUV2RGBConvert(const T& src, D* dst) - { - const int b = src.x + CV_DESCALE((src.z - ColorChannel::half()) * c_YUV2RGBCoeffs_i[3], yuv_shift); - - const int g = src.x + CV_DESCALE((src.z - ColorChannel::half()) * c_YUV2RGBCoeffs_i[2] - + (src.y - ColorChannel::half()) * c_YUV2RGBCoeffs_i[1], yuv_shift); - - const int r = src.x + CV_DESCALE((src.y - ColorChannel::half()) * c_YUV2RGBCoeffs_i[0], yuv_shift); - - dst[bidx] = saturate_cast(b); - dst[1] = saturate_cast(g); - dst[bidx^2] = saturate_cast(r); - } - - template static __device__ uint YUV2RGBConvert(uint src) - { - const int x = 0xff & (src); - const int y = 0xff & (src >> 8); - const int z = 0xff & (src >> 16); - - const int b = x + CV_DESCALE((z - ColorChannel::half()) * c_YUV2RGBCoeffs_i[3], yuv_shift); - - const int g = x + CV_DESCALE((z - ColorChannel::half()) * c_YUV2RGBCoeffs_i[2] - + (y - ColorChannel::half()) * c_YUV2RGBCoeffs_i[1], yuv_shift); - - const int r = x + CV_DESCALE((y - ColorChannel::half()) * c_YUV2RGBCoeffs_i[0], yuv_shift); - - uint dst = 0xffu << 24; - - dst |= saturate_cast(b) << (bidx * 8); - dst |= saturate_cast(g) << 8; - dst |= saturate_cast(r) << ((bidx ^ 2) * 8); - - return dst; - } - - template static __device__ __forceinline__ void YUV2RGBConvert(const T& src, float* dst) - { - dst[bidx] = src.x + (src.z - ColorChannel::half()) * c_YUV2RGBCoeffs_f[3]; - - dst[1] = src.x + (src.z - ColorChannel::half()) * c_YUV2RGBCoeffs_f[2] - + (src.y - ColorChannel::half()) * c_YUV2RGBCoeffs_f[1]; - - dst[bidx^2] = src.x + (src.y - ColorChannel::half()) * c_YUV2RGBCoeffs_f[0]; - } - - template struct YUV2RGB - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - YUV2RGBConvert(src, &dst.x); - setAlpha(dst, ColorChannel::max()); - - return dst; - } - __host__ __device__ __forceinline__ YUV2RGB() {} - __host__ __device__ __forceinline__ YUV2RGB(const YUV2RGB&) {} - }; - - template struct YUV2RGB : unary_function - { - __device__ __forceinline__ uint operator ()(uint src) const - { - return YUV2RGBConvert(src); - } - __host__ __device__ __forceinline__ YUV2RGB() {} - __host__ __device__ __forceinline__ YUV2RGB(const YUV2RGB&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(name, scn, dcn, bidx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::YUV2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - -///////////////////////////////////// RGB <-> YCrCb ////////////////////////////////////// - - namespace color_detail - { - __constant__ float c_RGB2YCrCbCoeffs_f[5] = {R2YF, G2YF, B2YF, YCRF, YCBF}; - __constant__ int c_RGB2YCrCbCoeffs_i[5] = {R2Y, G2Y, B2Y, YCRI, YCBI}; - - template static __device__ void RGB2YCrCbConvert(const T* src, D& dst) - { - const int delta = ColorChannel::half() * (1 << yuv_shift); - - const int Y = CV_DESCALE(src[0] * c_RGB2YCrCbCoeffs_i[bidx^2] + src[1] * c_RGB2YCrCbCoeffs_i[1] + src[2] * c_RGB2YCrCbCoeffs_i[bidx], yuv_shift); - const int Cr = CV_DESCALE((src[bidx^2] - Y) * c_RGB2YCrCbCoeffs_i[3] + delta, yuv_shift); - const int Cb = CV_DESCALE((src[bidx] - Y) * c_RGB2YCrCbCoeffs_i[4] + delta, yuv_shift); - - dst.x = saturate_cast(Y); - dst.y = saturate_cast(Cr); - dst.z = saturate_cast(Cb); - } - - template static __device__ uint RGB2YCrCbConvert(uint src) - { - const int delta = ColorChannel::half() * (1 << yuv_shift); - - const int Y = CV_DESCALE((0xffu & src) * c_RGB2YCrCbCoeffs_i[bidx^2] + (0xffu & (src >> 8)) * c_RGB2YCrCbCoeffs_i[1] + (0xffu & (src >> 16)) * c_RGB2YCrCbCoeffs_i[bidx], yuv_shift); - const int Cr = CV_DESCALE(((0xffu & (src >> ((bidx ^ 2) * 8))) - Y) * c_RGB2YCrCbCoeffs_i[3] + delta, yuv_shift); - const int Cb = CV_DESCALE(((0xffu & (src >> (bidx * 8))) - Y) * c_RGB2YCrCbCoeffs_i[4] + delta, yuv_shift); - - uint dst = 0; - - dst |= saturate_cast(Y); - dst |= saturate_cast(Cr) << 8; - dst |= saturate_cast(Cb) << 16; - - return dst; - } - - template static __device__ __forceinline__ void RGB2YCrCbConvert(const float* src, D& dst) - { - dst.x = src[0] * c_RGB2YCrCbCoeffs_f[bidx^2] + src[1] * c_RGB2YCrCbCoeffs_f[1] + src[2] * c_RGB2YCrCbCoeffs_f[bidx]; - dst.y = (src[bidx^2] - dst.x) * c_RGB2YCrCbCoeffs_f[3] + ColorChannel::half(); - dst.z = (src[bidx] - dst.x) * c_RGB2YCrCbCoeffs_f[4] + ColorChannel::half(); - } - - template struct RGB2YCrCb - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - RGB2YCrCbConvert(&src.x, dst); - return dst; - } - __host__ __device__ __forceinline__ RGB2YCrCb() {} - __host__ __device__ __forceinline__ RGB2YCrCb(const RGB2YCrCb&) {} - }; - - template struct RGB2YCrCb : unary_function - { - __device__ __forceinline__ uint operator ()(uint src) const - { - return RGB2YCrCbConvert(src); - } - - __host__ __device__ __forceinline__ RGB2YCrCb() {} - __host__ __device__ __forceinline__ RGB2YCrCb(const RGB2YCrCb&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(name, scn, dcn, bidx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2YCrCb functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - - namespace color_detail - { - __constant__ float c_YCrCb2RGBCoeffs_f[5] = {CR2RF, CR2GF, CB2GF, CB2BF}; - __constant__ int c_YCrCb2RGBCoeffs_i[5] = {CR2RI, CR2GI, CB2GI, CB2BI}; - - template static __device__ void YCrCb2RGBConvert(const T& src, D* dst) - { - const int b = src.x + CV_DESCALE((src.z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[3], yuv_shift); - const int g = src.x + CV_DESCALE((src.z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[2] + (src.y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[1], yuv_shift); - const int r = src.x + CV_DESCALE((src.y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[0], yuv_shift); - - dst[bidx] = saturate_cast(b); - dst[1] = saturate_cast(g); - dst[bidx^2] = saturate_cast(r); - } - - template static __device__ uint YCrCb2RGBConvert(uint src) - { - const int x = 0xff & (src); - const int y = 0xff & (src >> 8); - const int z = 0xff & (src >> 16); - - const int b = x + CV_DESCALE((z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[3], yuv_shift); - const int g = x + CV_DESCALE((z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[2] + (y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[1], yuv_shift); - const int r = x + CV_DESCALE((y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[0], yuv_shift); - - uint dst = 0xffu << 24; - - dst |= saturate_cast(b) << (bidx * 8); - dst |= saturate_cast(g) << 8; - dst |= saturate_cast(r) << ((bidx ^ 2) * 8); - - return dst; - } - - template __device__ __forceinline__ void YCrCb2RGBConvert(const T& src, float* dst) - { - dst[bidx] = src.x + (src.z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_f[3]; - dst[1] = src.x + (src.z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_f[2] + (src.y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_f[1]; - dst[bidx^2] = src.x + (src.y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_f[0]; - } - - template struct YCrCb2RGB - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - YCrCb2RGBConvert(src, &dst.x); - setAlpha(dst, ColorChannel::max()); - - return dst; - } - __host__ __device__ __forceinline__ YCrCb2RGB() {} - __host__ __device__ __forceinline__ YCrCb2RGB(const YCrCb2RGB&) {} - }; - - template struct YCrCb2RGB : unary_function - { - __device__ __forceinline__ uint operator ()(uint src) const - { - return YCrCb2RGBConvert(src); - } - __host__ __device__ __forceinline__ YCrCb2RGB() {} - __host__ __device__ __forceinline__ YCrCb2RGB(const YCrCb2RGB&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(name, scn, dcn, bidx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::YCrCb2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - -////////////////////////////////////// RGB <-> XYZ /////////////////////////////////////// - - namespace color_detail - { - __constant__ float c_RGB2XYZ_D65f[9] = { 0.412453f, 0.357580f, 0.180423f, 0.212671f, 0.715160f, 0.072169f, 0.019334f, 0.119193f, 0.950227f }; - __constant__ int c_RGB2XYZ_D65i[9] = { 1689, 1465, 739, 871, 2929, 296, 79, 488, 3892 }; - - template static __device__ __forceinline__ void RGB2XYZConvert(const T* src, D& dst) - { - dst.z = saturate_cast(CV_DESCALE(src[bidx^2] * c_RGB2XYZ_D65i[6] + src[1] * c_RGB2XYZ_D65i[7] + src[bidx] * c_RGB2XYZ_D65i[8], xyz_shift)); - dst.x = saturate_cast(CV_DESCALE(src[bidx^2] * c_RGB2XYZ_D65i[0] + src[1] * c_RGB2XYZ_D65i[1] + src[bidx] * c_RGB2XYZ_D65i[2], xyz_shift)); - dst.y = saturate_cast(CV_DESCALE(src[bidx^2] * c_RGB2XYZ_D65i[3] + src[1] * c_RGB2XYZ_D65i[4] + src[bidx] * c_RGB2XYZ_D65i[5], xyz_shift)); - } - - template static __device__ __forceinline__ uint RGB2XYZConvert(uint src) - { - const uint b = 0xffu & (src >> (bidx * 8)); - const uint g = 0xffu & (src >> 8); - const uint r = 0xffu & (src >> ((bidx ^ 2) * 8)); - - const uint x = saturate_cast(CV_DESCALE(r * c_RGB2XYZ_D65i[0] + g * c_RGB2XYZ_D65i[1] + b * c_RGB2XYZ_D65i[2], xyz_shift)); - const uint y = saturate_cast(CV_DESCALE(r * c_RGB2XYZ_D65i[3] + g * c_RGB2XYZ_D65i[4] + b * c_RGB2XYZ_D65i[5], xyz_shift)); - const uint z = saturate_cast(CV_DESCALE(r * c_RGB2XYZ_D65i[6] + g * c_RGB2XYZ_D65i[7] + b * c_RGB2XYZ_D65i[8], xyz_shift)); - - uint dst = 0; - - dst |= x; - dst |= y << 8; - dst |= z << 16; - - return dst; - } - - template static __device__ __forceinline__ void RGB2XYZConvert(const float* src, D& dst) - { - dst.x = src[bidx^2] * c_RGB2XYZ_D65f[0] + src[1] * c_RGB2XYZ_D65f[1] + src[bidx] * c_RGB2XYZ_D65f[2]; - dst.y = src[bidx^2] * c_RGB2XYZ_D65f[3] + src[1] * c_RGB2XYZ_D65f[4] + src[bidx] * c_RGB2XYZ_D65f[5]; - dst.z = src[bidx^2] * c_RGB2XYZ_D65f[6] + src[1] * c_RGB2XYZ_D65f[7] + src[bidx] * c_RGB2XYZ_D65f[8]; - } - - template struct RGB2XYZ - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - RGB2XYZConvert(&src.x, dst); - - return dst; - } - __host__ __device__ __forceinline__ RGB2XYZ() {} - __host__ __device__ __forceinline__ RGB2XYZ(const RGB2XYZ&) {} - }; - - template struct RGB2XYZ : unary_function - { - __device__ __forceinline__ uint operator()(uint src) const - { - return RGB2XYZConvert(src); - } - __host__ __device__ __forceinline__ RGB2XYZ() {} - __host__ __device__ __forceinline__ RGB2XYZ(const RGB2XYZ&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(name, scn, dcn, bidx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2XYZ functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - - namespace color_detail - { - __constant__ float c_XYZ2sRGB_D65f[9] = { 3.240479f, -1.53715f, -0.498535f, -0.969256f, 1.875991f, 0.041556f, 0.055648f, -0.204043f, 1.057311f }; - __constant__ int c_XYZ2sRGB_D65i[9] = { 13273, -6296, -2042, -3970, 7684, 170, 228, -836, 4331 }; - - template static __device__ __forceinline__ void XYZ2RGBConvert(const T& src, D* dst) - { - dst[bidx^2] = saturate_cast(CV_DESCALE(src.x * c_XYZ2sRGB_D65i[0] + src.y * c_XYZ2sRGB_D65i[1] + src.z * c_XYZ2sRGB_D65i[2], xyz_shift)); - dst[1] = saturate_cast(CV_DESCALE(src.x * c_XYZ2sRGB_D65i[3] + src.y * c_XYZ2sRGB_D65i[4] + src.z * c_XYZ2sRGB_D65i[5], xyz_shift)); - dst[bidx] = saturate_cast(CV_DESCALE(src.x * c_XYZ2sRGB_D65i[6] + src.y * c_XYZ2sRGB_D65i[7] + src.z * c_XYZ2sRGB_D65i[8], xyz_shift)); - } - - template static __device__ __forceinline__ uint XYZ2RGBConvert(uint src) - { - const int x = 0xff & src; - const int y = 0xff & (src >> 8); - const int z = 0xff & (src >> 16); - - const uint r = saturate_cast(CV_DESCALE(x * c_XYZ2sRGB_D65i[0] + y * c_XYZ2sRGB_D65i[1] + z * c_XYZ2sRGB_D65i[2], xyz_shift)); - const uint g = saturate_cast(CV_DESCALE(x * c_XYZ2sRGB_D65i[3] + y * c_XYZ2sRGB_D65i[4] + z * c_XYZ2sRGB_D65i[5], xyz_shift)); - const uint b = saturate_cast(CV_DESCALE(x * c_XYZ2sRGB_D65i[6] + y * c_XYZ2sRGB_D65i[7] + z * c_XYZ2sRGB_D65i[8], xyz_shift)); - - uint dst = 0xffu << 24; - - dst |= b << (bidx * 8); - dst |= g << 8; - dst |= r << ((bidx ^ 2) * 8); - - return dst; - } - - template static __device__ __forceinline__ void XYZ2RGBConvert(const T& src, float* dst) - { - dst[bidx^2] = src.x * c_XYZ2sRGB_D65f[0] + src.y * c_XYZ2sRGB_D65f[1] + src.z * c_XYZ2sRGB_D65f[2]; - dst[1] = src.x * c_XYZ2sRGB_D65f[3] + src.y * c_XYZ2sRGB_D65f[4] + src.z * c_XYZ2sRGB_D65f[5]; - dst[bidx] = src.x * c_XYZ2sRGB_D65f[6] + src.y * c_XYZ2sRGB_D65f[7] + src.z * c_XYZ2sRGB_D65f[8]; - } - - template struct XYZ2RGB - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - XYZ2RGBConvert(src, &dst.x); - setAlpha(dst, ColorChannel::max()); - - return dst; - } - __host__ __device__ __forceinline__ XYZ2RGB() {} - __host__ __device__ __forceinline__ XYZ2RGB(const XYZ2RGB&) {} - }; - - template struct XYZ2RGB : unary_function - { - __device__ __forceinline__ uint operator()(uint src) const - { - return XYZ2RGBConvert(src); - } - __host__ __device__ __forceinline__ XYZ2RGB() {} - __host__ __device__ __forceinline__ XYZ2RGB(const XYZ2RGB&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(name, scn, dcn, bidx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::XYZ2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - -////////////////////////////////////// RGB <-> HSV /////////////////////////////////////// - - namespace color_detail - { - __constant__ int c_HsvDivTable [256] = {0, 1044480, 522240, 348160, 261120, 208896, 174080, 149211, 130560, 116053, 104448, 94953, 87040, 80345, 74606, 69632, 65280, 61440, 58027, 54973, 52224, 49737, 47476, 45412, 43520, 41779, 40172, 38684, 37303, 36017, 34816, 33693, 32640, 31651, 30720, 29842, 29013, 28229, 27486, 26782, 26112, 25475, 24869, 24290, 23738, 23211, 22706, 22223, 21760, 21316, 20890, 20480, 20086, 19707, 19342, 18991, 18651, 18324, 18008, 17703, 17408, 17123, 16846, 16579, 16320, 16069, 15825, 15589, 15360, 15137, 14921, 14711, 14507, 14308, 14115, 13926, 13743, 13565, 13391, 13221, 13056, 12895, 12738, 12584, 12434, 12288, 12145, 12006, 11869, 11736, 11605, 11478, 11353, 11231, 11111, 10995, 10880, 10768, 10658, 10550, 10445, 10341, 10240, 10141, 10043, 9947, 9854, 9761, 9671, 9582, 9495, 9410, 9326, 9243, 9162, 9082, 9004, 8927, 8852, 8777, 8704, 8632, 8561, 8492, 8423, 8356, 8290, 8224, 8160, 8097, 8034, 7973, 7913, 7853, 7795, 7737, 7680, 7624, 7569, 7514, 7461, 7408, 7355, 7304, 7253, 7203, 7154, 7105, 7057, 7010, 6963, 6917, 6872, 6827, 6782, 6739, 6695, 6653, 6611, 6569, 6528, 6487, 6447, 6408, 6369, 6330, 6292, 6254, 6217, 6180, 6144, 6108, 6073, 6037, 6003, 5968, 5935, 5901, 5868, 5835, 5803, 5771, 5739, 5708, 5677, 5646, 5615, 5585, 5556, 5526, 5497, 5468, 5440, 5412, 5384, 5356, 5329, 5302, 5275, 5249, 5222, 5196, 5171, 5145, 5120, 5095, 5070, 5046, 5022, 4998, 4974, 4950, 4927, 4904, 4881, 4858, 4836, 4813, 4791, 4769, 4748, 4726, 4705, 4684, 4663, 4642, 4622, 4601, 4581, 4561, 4541, 4522, 4502, 4483, 4464, 4445, 4426, 4407, 4389, 4370, 4352, 4334, 4316, 4298, 4281, 4263, 4246, 4229, 4212, 4195, 4178, 4161, 4145, 4128, 4112, 4096}; - __constant__ int c_HsvDivTable180[256] = {0, 122880, 61440, 40960, 30720, 24576, 20480, 17554, 15360, 13653, 12288, 11171, 10240, 9452, 8777, 8192, 7680, 7228, 6827, 6467, 6144, 5851, 5585, 5343, 5120, 4915, 4726, 4551, 4389, 4237, 4096, 3964, 3840, 3724, 3614, 3511, 3413, 3321, 3234, 3151, 3072, 2997, 2926, 2858, 2793, 2731, 2671, 2614, 2560, 2508, 2458, 2409, 2363, 2318, 2276, 2234, 2194, 2156, 2119, 2083, 2048, 2014, 1982, 1950, 1920, 1890, 1862, 1834, 1807, 1781, 1755, 1731, 1707, 1683, 1661, 1638, 1617, 1596, 1575, 1555, 1536, 1517, 1499, 1480, 1463, 1446, 1429, 1412, 1396, 1381, 1365, 1350, 1336, 1321, 1307, 1293, 1280, 1267, 1254, 1241, 1229, 1217, 1205, 1193, 1182, 1170, 1159, 1148, 1138, 1127, 1117, 1107, 1097, 1087, 1078, 1069, 1059, 1050, 1041, 1033, 1024, 1016, 1007, 999, 991, 983, 975, 968, 960, 953, 945, 938, 931, 924, 917, 910, 904, 897, 890, 884, 878, 871, 865, 859, 853, 847, 842, 836, 830, 825, 819, 814, 808, 803, 798, 793, 788, 783, 778, 773, 768, 763, 759, 754, 749, 745, 740, 736, 731, 727, 723, 719, 714, 710, 706, 702, 698, 694, 690, 686, 683, 679, 675, 671, 668, 664, 661, 657, 654, 650, 647, 643, 640, 637, 633, 630, 627, 624, 621, 617, 614, 611, 608, 605, 602, 599, 597, 594, 591, 588, 585, 582, 580, 577, 574, 572, 569, 566, 564, 561, 559, 556, 554, 551, 549, 546, 544, 541, 539, 537, 534, 532, 530, 527, 525, 523, 521, 518, 516, 514, 512, 510, 508, 506, 504, 502, 500, 497, 495, 493, 492, 490, 488, 486, 484, 482}; - __constant__ int c_HsvDivTable256[256] = {0, 174763, 87381, 58254, 43691, 34953, 29127, 24966, 21845, 19418, 17476, 15888, 14564, 13443, 12483, 11651, 10923, 10280, 9709, 9198, 8738, 8322, 7944, 7598, 7282, 6991, 6722, 6473, 6242, 6026, 5825, 5638, 5461, 5296, 5140, 4993, 4855, 4723, 4599, 4481, 4369, 4263, 4161, 4064, 3972, 3884, 3799, 3718, 3641, 3567, 3495, 3427, 3361, 3297, 3236, 3178, 3121, 3066, 3013, 2962, 2913, 2865, 2819, 2774, 2731, 2689, 2648, 2608, 2570, 2533, 2497, 2461, 2427, 2394, 2362, 2330, 2300, 2270, 2241, 2212, 2185, 2158, 2131, 2106, 2081, 2056, 2032, 2009, 1986, 1964, 1942, 1920, 1900, 1879, 1859, 1840, 1820, 1802, 1783, 1765, 1748, 1730, 1713, 1697, 1680, 1664, 1649, 1633, 1618, 1603, 1589, 1574, 1560, 1547, 1533, 1520, 1507, 1494, 1481, 1469, 1456, 1444, 1432, 1421, 1409, 1398, 1387, 1376, 1365, 1355, 1344, 1334, 1324, 1314, 1304, 1295, 1285, 1276, 1266, 1257, 1248, 1239, 1231, 1222, 1214, 1205, 1197, 1189, 1181, 1173, 1165, 1157, 1150, 1142, 1135, 1128, 1120, 1113, 1106, 1099, 1092, 1085, 1079, 1072, 1066, 1059, 1053, 1046, 1040, 1034, 1028, 1022, 1016, 1010, 1004, 999, 993, 987, 982, 976, 971, 966, 960, 955, 950, 945, 940, 935, 930, 925, 920, 915, 910, 906, 901, 896, 892, 887, 883, 878, 874, 869, 865, 861, 857, 853, 848, 844, 840, 836, 832, 828, 824, 820, 817, 813, 809, 805, 802, 798, 794, 791, 787, 784, 780, 777, 773, 770, 767, 763, 760, 757, 753, 750, 747, 744, 741, 737, 734, 731, 728, 725, 722, 719, 716, 713, 710, 708, 705, 702, 699, 696, 694, 691, 688, 685}; - - template static __device__ void RGB2HSVConvert(const uchar* src, D& dst) - { - const int hsv_shift = 12; - const int* hdiv_table = hr == 180 ? c_HsvDivTable180 : c_HsvDivTable256; - - int b = src[bidx], g = src[1], r = src[bidx^2]; - int h, s, v = b; - int vmin = b, diff; - int vr, vg; - - v = ::max(v, g); - v = ::max(v, r); - vmin = ::min(vmin, g); - vmin = ::min(vmin, r); - - diff = v - vmin; - vr = (v == r) * -1; - vg = (v == g) * -1; - - s = (diff * c_HsvDivTable[v] + (1 << (hsv_shift-1))) >> hsv_shift; - h = (vr & (g - b)) + (~vr & ((vg & (b - r + 2 * diff)) + ((~vg) & (r - g + 4 * diff)))); - h = (h * hdiv_table[diff] + (1 << (hsv_shift-1))) >> hsv_shift; - h += (h < 0) * hr; - - dst.x = saturate_cast(h); - dst.y = (uchar)s; - dst.z = (uchar)v; - } - - template static __device__ uint RGB2HSVConvert(uint src) - { - const int hsv_shift = 12; - const int* hdiv_table = hr == 180 ? c_HsvDivTable180 : c_HsvDivTable256; - - const int b = 0xff & (src >> (bidx * 8)); - const int g = 0xff & (src >> 8); - const int r = 0xff & (src >> ((bidx ^ 2) * 8)); - - int h, s, v = b; - int vmin = b, diff; - int vr, vg; - - v = ::max(v, g); - v = ::max(v, r); - vmin = ::min(vmin, g); - vmin = ::min(vmin, r); - - diff = v - vmin; - vr = (v == r) * -1; - vg = (v == g) * -1; - - s = (diff * c_HsvDivTable[v] + (1 << (hsv_shift-1))) >> hsv_shift; - h = (vr & (g - b)) + (~vr & ((vg & (b - r + 2 * diff)) + ((~vg) & (r - g + 4 * diff)))); - h = (h * hdiv_table[diff] + (1 << (hsv_shift-1))) >> hsv_shift; - h += (h < 0) * hr; - - uint dst = 0; - - dst |= saturate_cast(h); - dst |= (0xffu & s) << 8; - dst |= (0xffu & v) << 16; - - return dst; - } - - template static __device__ void RGB2HSVConvert(const float* src, D& dst) - { - const float hscale = hr * (1.f / 360.f); - - float b = src[bidx], g = src[1], r = src[bidx^2]; - float h, s, v; - - float vmin, diff; - - v = vmin = r; - v = fmax(v, g); - v = fmax(v, b); - vmin = fmin(vmin, g); - vmin = fmin(vmin, b); - - diff = v - vmin; - s = diff / (float)(::fabs(v) + numeric_limits::epsilon()); - diff = (float)(60. / (diff + numeric_limits::epsilon())); - - h = (v == r) * (g - b) * diff; - h += (v != r && v == g) * ((b - r) * diff + 120.f); - h += (v != r && v != g) * ((r - g) * diff + 240.f); - h += (h < 0) * 360.f; - - dst.x = h * hscale; - dst.y = s; - dst.z = v; - } - - template struct RGB2HSV - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - RGB2HSVConvert(&src.x, dst); - - return dst; - } - __host__ __device__ __forceinline__ RGB2HSV() {} - __host__ __device__ __forceinline__ RGB2HSV(const RGB2HSV&) {} - }; - - template struct RGB2HSV : unary_function - { - __device__ __forceinline__ uint operator()(uint src) const - { - return RGB2HSVConvert(src); - } - __host__ __device__ __forceinline__ RGB2HSV() {} - __host__ __device__ __forceinline__ RGB2HSV(const RGB2HSV&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(name, scn, dcn, bidx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2HSV functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; \ - template struct name ## _full_traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2HSV functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; \ - template <> struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2HSV functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; \ - template <> struct name ## _full_traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2HSV functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - - namespace color_detail - { - __constant__ int c_HsvSectorData[6][3] = { {1,3,0}, {1,0,2}, {3,0,1}, {0,2,1}, {0,1,3}, {2,1,0} }; - - template static __device__ void HSV2RGBConvert(const T& src, float* dst) - { - const float hscale = 6.f / hr; - - float h = src.x, s = src.y, v = src.z; - float b = v, g = v, r = v; - - if (s != 0) - { - h *= hscale; - - if( h < 0 ) - do h += 6; while( h < 0 ); - else if( h >= 6 ) - do h -= 6; while( h >= 6 ); - - int sector = __float2int_rd(h); - h -= sector; - - if ( (unsigned)sector >= 6u ) - { - sector = 0; - h = 0.f; - } - - float tab[4]; - tab[0] = v; - tab[1] = v * (1.f - s); - tab[2] = v * (1.f - s * h); - tab[3] = v * (1.f - s * (1.f - h)); - - b = tab[c_HsvSectorData[sector][0]]; - g = tab[c_HsvSectorData[sector][1]]; - r = tab[c_HsvSectorData[sector][2]]; - } - - dst[bidx] = b; - dst[1] = g; - dst[bidx^2] = r; - } - - template static __device__ void HSV2RGBConvert(const T& src, uchar* dst) - { - float3 buf; - - buf.x = src.x; - buf.y = src.y * (1.f / 255.f); - buf.z = src.z * (1.f / 255.f); - - HSV2RGBConvert(buf, &buf.x); - - dst[0] = saturate_cast(buf.x * 255.f); - dst[1] = saturate_cast(buf.y * 255.f); - dst[2] = saturate_cast(buf.z * 255.f); - } - - template static __device__ uint HSV2RGBConvert(uint src) - { - float3 buf; - - buf.x = src & 0xff; - buf.y = ((src >> 8) & 0xff) * (1.f/255.f); - buf.z = ((src >> 16) & 0xff) * (1.f/255.f); - - HSV2RGBConvert(buf, &buf.x); - - uint dst = 0xffu << 24; - - dst |= saturate_cast(buf.x * 255.f); - dst |= saturate_cast(buf.y * 255.f) << 8; - dst |= saturate_cast(buf.z * 255.f) << 16; - - return dst; - } - - template struct HSV2RGB - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - HSV2RGBConvert(src, &dst.x); - setAlpha(dst, ColorChannel::max()); - - return dst; - } - __host__ __device__ __forceinline__ HSV2RGB() {} - __host__ __device__ __forceinline__ HSV2RGB(const HSV2RGB&) {} - }; - - template struct HSV2RGB : unary_function - { - __device__ __forceinline__ uint operator()(uint src) const - { - return HSV2RGBConvert(src); - } - __host__ __device__ __forceinline__ HSV2RGB() {} - __host__ __device__ __forceinline__ HSV2RGB(const HSV2RGB&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(name, scn, dcn, bidx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::HSV2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; \ - template struct name ## _full_traits \ - { \ - typedef ::cv::cuda::device::color_detail::HSV2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; \ - template <> struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::HSV2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; \ - template <> struct name ## _full_traits \ - { \ - typedef ::cv::cuda::device::color_detail::HSV2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - -/////////////////////////////////////// RGB <-> HLS //////////////////////////////////////// - - namespace color_detail - { - template static __device__ void RGB2HLSConvert(const float* src, D& dst) - { - const float hscale = hr * (1.f / 360.f); - - float b = src[bidx], g = src[1], r = src[bidx^2]; - float h = 0.f, s = 0.f, l; - float vmin, vmax, diff; - - vmax = vmin = r; - vmax = fmax(vmax, g); - vmax = fmax(vmax, b); - vmin = fmin(vmin, g); - vmin = fmin(vmin, b); - - diff = vmax - vmin; - l = (vmax + vmin) * 0.5f; - - if (diff > numeric_limits::epsilon()) - { - s = (l < 0.5f) * diff / (vmax + vmin); - s += (l >= 0.5f) * diff / (2.0f - vmax - vmin); - - diff = 60.f / diff; - - h = (vmax == r) * (g - b) * diff; - h += (vmax != r && vmax == g) * ((b - r) * diff + 120.f); - h += (vmax != r && vmax != g) * ((r - g) * diff + 240.f); - h += (h < 0.f) * 360.f; - } - - dst.x = h * hscale; - dst.y = l; - dst.z = s; - } - - template static __device__ void RGB2HLSConvert(const uchar* src, D& dst) - { - float3 buf; - - buf.x = src[0] * (1.f / 255.f); - buf.y = src[1] * (1.f / 255.f); - buf.z = src[2] * (1.f / 255.f); - - RGB2HLSConvert(&buf.x, buf); - - dst.x = saturate_cast(buf.x); - dst.y = saturate_cast(buf.y*255.f); - dst.z = saturate_cast(buf.z*255.f); - } - - template static __device__ uint RGB2HLSConvert(uint src) - { - float3 buf; - - buf.x = (0xff & src) * (1.f / 255.f); - buf.y = (0xff & (src >> 8)) * (1.f / 255.f); - buf.z = (0xff & (src >> 16)) * (1.f / 255.f); - - RGB2HLSConvert(&buf.x, buf); - - uint dst = 0xffu << 24; - - dst |= saturate_cast(buf.x); - dst |= saturate_cast(buf.y * 255.f) << 8; - dst |= saturate_cast(buf.z * 255.f) << 16; - - return dst; - } - - template struct RGB2HLS - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - RGB2HLSConvert(&src.x, dst); - - return dst; - } - __host__ __device__ __forceinline__ RGB2HLS() {} - __host__ __device__ __forceinline__ RGB2HLS(const RGB2HLS&) {} - }; - - template struct RGB2HLS : unary_function - { - __device__ __forceinline__ uint operator()(uint src) const - { - return RGB2HLSConvert(src); - } - __host__ __device__ __forceinline__ RGB2HLS() {} - __host__ __device__ __forceinline__ RGB2HLS(const RGB2HLS&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(name, scn, dcn, bidx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2HLS functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; \ - template struct name ## _full_traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2HLS functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; \ - template <> struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2HLS functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; \ - template <> struct name ## _full_traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2HLS functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - - namespace color_detail - { - __constant__ int c_HlsSectorData[6][3] = { {1,3,0}, {1,0,2}, {3,0,1}, {0,2,1}, {0,1,3}, {2,1,0} }; - - template static __device__ void HLS2RGBConvert(const T& src, float* dst) - { - const float hscale = 6.0f / hr; - - float h = src.x, l = src.y, s = src.z; - float b = l, g = l, r = l; - - if (s != 0) - { - float p2 = (l <= 0.5f) * l * (1 + s); - p2 += (l > 0.5f) * (l + s - l * s); - float p1 = 2 * l - p2; - - h *= hscale; - - if( h < 0 ) - do h += 6; while( h < 0 ); - else if( h >= 6 ) - do h -= 6; while( h >= 6 ); - - int sector; - sector = __float2int_rd(h); - - h -= sector; - - float tab[4]; - tab[0] = p2; - tab[1] = p1; - tab[2] = p1 + (p2 - p1) * (1 - h); - tab[3] = p1 + (p2 - p1) * h; - - b = tab[c_HlsSectorData[sector][0]]; - g = tab[c_HlsSectorData[sector][1]]; - r = tab[c_HlsSectorData[sector][2]]; - } - - dst[bidx] = b; - dst[1] = g; - dst[bidx^2] = r; - } - - template static __device__ void HLS2RGBConvert(const T& src, uchar* dst) - { - float3 buf; - - buf.x = src.x; - buf.y = src.y * (1.f / 255.f); - buf.z = src.z * (1.f / 255.f); - - HLS2RGBConvert(buf, &buf.x); - - dst[0] = saturate_cast(buf.x * 255.f); - dst[1] = saturate_cast(buf.y * 255.f); - dst[2] = saturate_cast(buf.z * 255.f); - } - - template static __device__ uint HLS2RGBConvert(uint src) - { - float3 buf; - - buf.x = 0xff & src; - buf.y = (0xff & (src >> 8)) * (1.f / 255.f); - buf.z = (0xff & (src >> 16)) * (1.f / 255.f); - - HLS2RGBConvert(buf, &buf.x); - - uint dst = 0xffu << 24; - - dst |= saturate_cast(buf.x * 255.f); - dst |= saturate_cast(buf.y * 255.f) << 8; - dst |= saturate_cast(buf.z * 255.f) << 16; - - return dst; - } - - template struct HLS2RGB - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - HLS2RGBConvert(src, &dst.x); - setAlpha(dst, ColorChannel::max()); - - return dst; - } - __host__ __device__ __forceinline__ HLS2RGB() {} - __host__ __device__ __forceinline__ HLS2RGB(const HLS2RGB&) {} - }; - - template struct HLS2RGB : unary_function - { - __device__ __forceinline__ uint operator()(uint src) const - { - return HLS2RGBConvert(src); - } - __host__ __device__ __forceinline__ HLS2RGB() {} - __host__ __device__ __forceinline__ HLS2RGB(const HLS2RGB&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(name, scn, dcn, bidx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::HLS2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; \ - template struct name ## _full_traits \ - { \ - typedef ::cv::cuda::device::color_detail::HLS2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; \ - template <> struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::HLS2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; \ - template <> struct name ## _full_traits \ - { \ - typedef ::cv::cuda::device::color_detail::HLS2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - -///////////////////////////////////// RGB <-> Lab ///////////////////////////////////// - - namespace color_detail - { - enum - { - LAB_CBRT_TAB_SIZE = 1024, - GAMMA_TAB_SIZE = 1024, - lab_shift = xyz_shift, - gamma_shift = 3, - lab_shift2 = (lab_shift + gamma_shift), - LAB_CBRT_TAB_SIZE_B = (256 * 3 / 2 * (1 << gamma_shift)) - }; - - __constant__ ushort c_sRGBGammaTab_b[] = {0,1,1,2,2,3,4,4,5,6,6,7,8,8,9,10,11,11,12,13,14,15,16,17,19,20,21,22,24,25,26,28,29,31,33,34,36,38,40,41,43,45,47,49,51,54,56,58,60,63,65,68,70,73,75,78,81,83,86,89,92,95,98,101,105,108,111,115,118,121,125,129,132,136,140,144,147,151,155,160,164,168,172,176,181,185,190,194,199,204,209,213,218,223,228,233,239,244,249,255,260,265,271,277,282,288,294,300,306,312,318,324,331,337,343,350,356,363,370,376,383,390,397,404,411,418,426,433,440,448,455,463,471,478,486,494,502,510,518,527,535,543,552,560,569,578,586,595,604,613,622,631,641,650,659,669,678,688,698,707,717,727,737,747,757,768,778,788,799,809,820,831,842,852,863,875,886,897,908,920,931,943,954,966,978,990,1002,1014,1026,1038,1050,1063,1075,1088,1101,1113,1126,1139,1152,1165,1178,1192,1205,1218,1232,1245,1259,1273,1287,1301,1315,1329,1343,1357,1372,1386,1401,1415,1430,1445,1460,1475,1490,1505,1521,1536,1551,1567,1583,1598,1614,1630,1646,1662,1678,1695,1711,1728,1744,1761,1778,1794,1811,1828,1846,1863,1880,1897,1915,1933,1950,1968,1986,2004,2022,2040}; - - __device__ __forceinline__ int LabCbrt_b(int i) - { - float x = i * (1.f / (255.f * (1 << gamma_shift))); - return (1 << lab_shift2) * (x < 0.008856f ? x * 7.787f + 0.13793103448275862f : ::cbrtf(x)); - } - - template - __device__ __forceinline__ void RGB2LabConvert_b(const T& src, D& dst) - { - const int Lscale = (116 * 255 + 50) / 100; - const int Lshift = -((16 * 255 * (1 << lab_shift2) + 50) / 100); - - int B = blueIdx == 0 ? src.x : src.z; - int G = src.y; - int R = blueIdx == 0 ? src.z : src.x; - - if (srgb) - { - B = c_sRGBGammaTab_b[B]; - G = c_sRGBGammaTab_b[G]; - R = c_sRGBGammaTab_b[R]; - } - else - { - B <<= 3; - G <<= 3; - R <<= 3; - } - - int fX = LabCbrt_b(CV_DESCALE(B * 778 + G * 1541 + R * 1777, lab_shift)); - int fY = LabCbrt_b(CV_DESCALE(B * 296 + G * 2929 + R * 871, lab_shift)); - int fZ = LabCbrt_b(CV_DESCALE(B * 3575 + G * 448 + R * 73, lab_shift)); - - int L = CV_DESCALE(Lscale * fY + Lshift, lab_shift2); - int a = CV_DESCALE(500 * (fX - fY) + 128 * (1 << lab_shift2), lab_shift2); - int b = CV_DESCALE(200 * (fY - fZ) + 128 * (1 << lab_shift2), lab_shift2); - - dst.x = saturate_cast(L); - dst.y = saturate_cast(a); - dst.z = saturate_cast(b); - } - - __device__ __forceinline__ float splineInterpolate(float x, const float* tab, int n) - { - int ix = ::min(::max(int(x), 0), n-1); - x -= ix; - tab += ix * 4; - return ((tab[3] * x + tab[2]) * x + tab[1]) * x + tab[0]; - } - - __constant__ float c_sRGBGammaTab[] = {0,7.55853e-05,0.,-7.51331e-13,7.55853e-05,7.55853e-05,-2.25399e-12,3.75665e-12,0.000151171,7.55853e-05,9.01597e-12,-6.99932e-12,0.000226756,7.55853e-05,-1.1982e-11,2.41277e-12,0.000302341,7.55853e-05,-4.74369e-12,1.19001e-11,0.000377927,7.55853e-05,3.09568e-11,-2.09095e-11,0.000453512,7.55853e-05,-3.17718e-11,1.35303e-11,0.000529097,7.55853e-05,8.81905e-12,-4.10782e-12,0.000604683,7.55853e-05,-3.50439e-12,2.90097e-12,0.000680268,7.55853e-05,5.19852e-12,-7.49607e-12,0.000755853,7.55853e-05,-1.72897e-11,2.70833e-11,0.000831439,7.55854e-05,6.39602e-11,-4.26295e-11,0.000907024,7.55854e-05,-6.39282e-11,2.70193e-11,0.000982609,7.55853e-05,1.71298e-11,-7.24017e-12,0.00105819,7.55853e-05,-4.59077e-12,1.94137e-12,0.00113378,7.55853e-05,1.23333e-12,-5.25291e-13,0.00120937,7.55853e-05,-3.42545e-13,1.59799e-13,0.00128495,7.55853e-05,1.36852e-13,-1.13904e-13,0.00136054,7.55853e-05,-2.04861e-13,2.95818e-13,0.00143612,7.55853e-05,6.82594e-13,-1.06937e-12,0.00151171,7.55853e-05,-2.52551e-12,3.98166e-12,0.00158729,7.55853e-05,9.41946e-12,-1.48573e-11,0.00166288,7.55853e-05,-3.51523e-11,5.54474e-11,0.00173846,7.55854e-05,1.3119e-10,-9.0517e-11,0.00181405,7.55854e-05,-1.40361e-10,7.37899e-11,0.00188963,7.55853e-05,8.10085e-11,-8.82272e-11,0.00196522,7.55852e-05,-1.83673e-10,1.62704e-10,0.0020408,7.55853e-05,3.04438e-10,-2.13341e-10,0.00211639,7.55853e-05,-3.35586e-10,2.25e-10,0.00219197,7.55853e-05,3.39414e-10,-2.20997e-10,0.00226756,7.55853e-05,-3.23576e-10,1.93326e-10,0.00234315,7.55853e-05,2.564e-10,-8.66446e-11,0.00241873,7.55855e-05,-3.53328e-12,-7.9578e-11,0.00249432,7.55853e-05,-2.42267e-10,1.72126e-10,0.0025699,7.55853e-05,2.74111e-10,-1.43265e-10,0.00264549,7.55854e-05,-1.55683e-10,-6.47292e-11,0.00272107,7.55849e-05,-3.4987e-10,8.67842e-10,0.00279666,7.55868e-05,2.25366e-09,-3.8723e-09,0.00287224,7.55797e-05,-9.36325e-09,1.5087e-08,0.00294783,7.56063e-05,3.58978e-08,-5.69415e-08,0.00302341,7.55072e-05,-1.34927e-07,2.13144e-07,0.003099,7.58768e-05,5.04507e-07,1.38713e-07,0.00317552,7.7302e-05,9.20646e-07,-1.55186e-07,0.00325359,7.86777e-05,4.55087e-07,4.26813e-08,0.00333276,7.97159e-05,5.83131e-07,-1.06495e-08,0.00341305,8.08502e-05,5.51182e-07,3.87467e-09,0.00349446,8.19642e-05,5.62806e-07,-1.92586e-10,0.00357698,8.30892e-05,5.62228e-07,1.0866e-09,0.00366063,8.4217e-05,5.65488e-07,5.02818e-10,0.00374542,8.53494e-05,5.66997e-07,8.60211e-10,0.00383133,8.6486e-05,5.69577e-07,7.13044e-10,0.00391839,8.76273e-05,5.71716e-07,4.78527e-10,0.00400659,8.87722e-05,5.73152e-07,1.09818e-09,0.00409594,8.99218e-05,5.76447e-07,2.50964e-10,0.00418644,9.10754e-05,5.772e-07,1.15762e-09,0.00427809,9.22333e-05,5.80672e-07,2.40865e-10,0.0043709,9.33954e-05,5.81395e-07,1.13854e-09,0.00446488,9.45616e-05,5.84811e-07,3.27267e-10,0.00456003,9.57322e-05,5.85792e-07,8.1197e-10,0.00465635,9.69062e-05,5.88228e-07,6.15823e-10,0.00475384,9.80845e-05,5.90076e-07,9.15747e-10,0.00485252,9.92674e-05,5.92823e-07,3.778e-10,0.00495238,0.000100454,5.93956e-07,8.32623e-10,0.00505343,0.000101645,5.96454e-07,4.82695e-10,0.00515567,0.000102839,5.97902e-07,9.61904e-10,0.00525911,0.000104038,6.00788e-07,3.26281e-10,0.00536375,0.00010524,6.01767e-07,9.926e-10,0.00546959,0.000106447,6.04745e-07,3.59933e-10,0.00557664,0.000107657,6.05824e-07,8.2728e-10,0.0056849,0.000108871,6.08306e-07,5.21898e-10,0.00579438,0.00011009,6.09872e-07,8.10492e-10,0.00590508,0.000111312,6.12303e-07,4.27046e-10,0.00601701,0.000112538,6.13585e-07,7.40878e-10,0.00613016,0.000113767,6.15807e-07,8.00469e-10,0.00624454,0.000115001,6.18209e-07,2.48178e-10,0.00636016,0.000116238,6.18953e-07,1.00073e-09,0.00647702,0.000117479,6.21955e-07,4.05654e-10,0.00659512,0.000118724,6.23172e-07,6.36192e-10,0.00671447,0.000119973,6.25081e-07,7.74927e-10,0.00683507,0.000121225,6.27406e-07,4.54975e-10,0.00695692,0.000122481,6.28771e-07,6.64841e-10,0.00708003,0.000123741,6.30765e-07,6.10972e-10,0.00720441,0.000125004,6.32598e-07,6.16543e-10,0.00733004,0.000126271,6.34448e-07,6.48204e-10,0.00745695,0.000127542,6.36392e-07,5.15835e-10,0.00758513,0.000128816,6.3794e-07,5.48103e-10,0.00771458,0.000130094,6.39584e-07,1.01706e-09,0.00784532,0.000131376,6.42635e-07,4.0283e-11,0.00797734,0.000132661,6.42756e-07,6.84471e-10,0.00811064,0.000133949,6.4481e-07,9.47144e-10,0.00824524,0.000135241,6.47651e-07,1.83472e-10,0.00838112,0.000136537,6.48201e-07,1.11296e-09,0.00851831,0.000137837,6.5154e-07,2.13163e-11,0.0086568,0.00013914,6.51604e-07,6.64462e-10,0.00879659,0.000140445,6.53598e-07,1.04613e-09,0.00893769,0.000141756,6.56736e-07,-1.92377e-10,0.0090801,0.000143069,6.56159e-07,1.58601e-09,0.00922383,0.000144386,6.60917e-07,-5.63754e-10,0.00936888,0.000145706,6.59226e-07,1.60033e-09,0.00951524,0.000147029,6.64027e-07,-2.49543e-10,0.00966294,0.000148356,6.63278e-07,1.26043e-09,0.00981196,0.000149687,6.67059e-07,-1.35572e-10,0.00996231,0.00015102,6.66653e-07,1.14458e-09,0.010114,0.000152357,6.70086e-07,2.13864e-10,0.010267,0.000153698,6.70728e-07,7.93856e-10,0.0104214,0.000155042,6.73109e-07,3.36077e-10,0.0105771,0.000156389,6.74118e-07,6.55765e-10,0.0107342,0.000157739,6.76085e-07,7.66211e-10,0.0108926,0.000159094,6.78384e-07,4.66116e-12,0.0110524,0.000160451,6.78398e-07,1.07775e-09,0.0112135,0.000161811,6.81631e-07,3.41023e-10,0.011376,0.000163175,6.82654e-07,3.5205e-10,0.0115398,0.000164541,6.8371e-07,1.04473e-09,0.0117051,0.000165912,6.86844e-07,1.25757e-10,0.0118717,0.000167286,6.87222e-07,3.14818e-10,0.0120396,0.000168661,6.88166e-07,1.40886e-09,0.012209,0.000170042,6.92393e-07,-3.62244e-10,0.0123797,0.000171425,6.91306e-07,9.71397e-10,0.0125518,0.000172811,6.9422e-07,2.02003e-10,0.0127253,0.0001742,6.94826e-07,1.01448e-09,0.0129002,0.000175593,6.97869e-07,3.96653e-10,0.0130765,0.00017699,6.99059e-07,1.92927e-10,0.0132542,0.000178388,6.99638e-07,6.94305e-10,0.0134333,0.00017979,7.01721e-07,7.55108e-10,0.0136138,0.000181195,7.03986e-07,1.05918e-11,0.0137957,0.000182603,7.04018e-07,1.06513e-09,0.013979,0.000184015,7.07214e-07,3.85512e-10,0.0141637,0.00018543,7.0837e-07,1.86769e-10,0.0143499,0.000186848,7.0893e-07,7.30116e-10,0.0145374,0.000188268,7.11121e-07,6.17983e-10,0.0147264,0.000189692,7.12975e-07,5.23282e-10,0.0149168,0.000191119,7.14545e-07,8.28398e-11,0.0151087,0.000192549,7.14793e-07,1.0081e-09,0.0153019,0.000193981,7.17817e-07,5.41244e-10,0.0154966,0.000195418,7.19441e-07,-3.7907e-10,0.0156928,0.000196856,7.18304e-07,1.90641e-09,0.0158903,0.000198298,7.24023e-07,-7.27387e-10,0.0160893,0.000199744,7.21841e-07,1.00317e-09,0.0162898,0.000201191,7.24851e-07,4.39949e-10,0.0164917,0.000202642,7.2617e-07,9.6234e-10,0.0166951,0.000204097,7.29057e-07,-5.64019e-10,0.0168999,0.000205554,7.27365e-07,1.29374e-09,0.0171062,0.000207012,7.31247e-07,9.77025e-10,0.017314,0.000208478,7.34178e-07,-1.47651e-09,0.0175232,0.000209942,7.29748e-07,3.06636e-09,0.0177338,0.00021141,7.38947e-07,-1.47573e-09,0.017946,0.000212884,7.3452e-07,9.7386e-10,0.0181596,0.000214356,7.37442e-07,1.30562e-09,0.0183747,0.000215835,7.41358e-07,-6.08376e-10,0.0185913,0.000217315,7.39533e-07,1.12785e-09,0.0188093,0.000218798,7.42917e-07,-1.77711e-10,0.0190289,0.000220283,7.42384e-07,1.44562e-09,0.0192499,0.000221772,7.46721e-07,-1.68825e-11,0.0194724,0.000223266,7.4667e-07,4.84533e-10,0.0196964,0.000224761,7.48124e-07,-5.85298e-11,0.0199219,0.000226257,7.47948e-07,1.61217e-09,0.0201489,0.000227757,7.52785e-07,-8.02136e-10,0.0203775,0.00022926,7.50378e-07,1.59637e-09,0.0206075,0.000230766,7.55167e-07,4.47168e-12,0.020839,0.000232276,7.55181e-07,2.48387e-10,0.021072,0.000233787,7.55926e-07,8.6474e-10,0.0213066,0.000235302,7.5852e-07,1.78299e-11,0.0215426,0.000236819,7.58573e-07,9.26567e-10,0.0217802,0.000238339,7.61353e-07,1.34529e-12,0.0220193,0.000239862,7.61357e-07,9.30659e-10,0.0222599,0.000241387,7.64149e-07,1.34529e-12,0.0225021,0.000242915,7.64153e-07,9.26567e-10,0.0227458,0.000244447,7.66933e-07,1.76215e-11,0.022991,0.00024598,7.66986e-07,8.65536e-10,0.0232377,0.000247517,7.69582e-07,2.45677e-10,0.023486,0.000249057,7.70319e-07,1.44193e-11,0.0237358,0.000250598,7.70363e-07,1.55918e-09,0.0239872,0.000252143,7.7504e-07,-6.63173e-10,0.0242401,0.000253691,7.73051e-07,1.09357e-09,0.0244946,0.000255241,7.76331e-07,1.41919e-11,0.0247506,0.000256793,7.76374e-07,7.12248e-10,0.0250082,0.000258348,7.78511e-07,8.62049e-10,0.0252673,0.000259908,7.81097e-07,-4.35061e-10,0.025528,0.000261469,7.79792e-07,8.7825e-10,0.0257902,0.000263031,7.82426e-07,6.47181e-10,0.0260541,0.000264598,7.84368e-07,2.58448e-10,0.0263194,0.000266167,7.85143e-07,1.81558e-10,0.0265864,0.000267738,7.85688e-07,8.78041e-10,0.0268549,0.000269312,7.88322e-07,3.15102e-11,0.027125,0.000270889,7.88417e-07,8.58525e-10,0.0273967,0.000272468,7.90992e-07,2.59812e-10,0.02767,0.000274051,7.91772e-07,-3.5224e-11,0.0279448,0.000275634,7.91666e-07,1.74377e-09,0.0282212,0.000277223,7.96897e-07,-1.35196e-09,0.0284992,0.000278813,7.92841e-07,1.80141e-09,0.0287788,0.000280404,7.98246e-07,-2.65629e-10,0.0290601,0.000281999,7.97449e-07,1.12374e-09,0.0293428,0.000283598,8.0082e-07,-5.04106e-10,0.0296272,0.000285198,7.99308e-07,8.92764e-10,0.0299132,0.000286799,8.01986e-07,6.58379e-10,0.0302008,0.000288405,8.03961e-07,1.98971e-10,0.0304901,0.000290014,8.04558e-07,4.08382e-10,0.0307809,0.000291624,8.05783e-07,3.01839e-11,0.0310733,0.000293236,8.05874e-07,1.33343e-09,0.0313673,0.000294851,8.09874e-07,2.2419e-10,0.031663,0.000296472,8.10547e-07,-3.67606e-10,0.0319603,0.000298092,8.09444e-07,1.24624e-09,0.0322592,0.000299714,8.13182e-07,-8.92025e-10,0.0325597,0.000301338,8.10506e-07,2.32183e-09,0.0328619,0.000302966,8.17472e-07,-9.44719e-10,0.0331657,0.000304598,8.14638e-07,1.45703e-09,0.0334711,0.000306232,8.19009e-07,-1.15805e-09,0.0337781,0.000307866,8.15535e-07,3.17507e-09,0.0340868,0.000309507,8.2506e-07,-4.09161e-09,0.0343971,0.000311145,8.12785e-07,5.74079e-09,0.0347091,0.000312788,8.30007e-07,-3.97034e-09,0.0350227,0.000314436,8.18096e-07,2.68985e-09,0.035338,0.00031608,8.26166e-07,6.61676e-10,0.0356549,0.000317734,8.28151e-07,-1.61123e-09,0.0359734,0.000319386,8.23317e-07,2.05786e-09,0.0362936,0.000321038,8.29491e-07,8.30388e-10,0.0366155,0.0003227,8.31982e-07,-1.65424e-09,0.036939,0.000324359,8.27019e-07,2.06129e-09,0.0372642,0.000326019,8.33203e-07,8.59719e-10,0.0375911,0.000327688,8.35782e-07,-1.77488e-09,0.0379196,0.000329354,8.30458e-07,2.51464e-09,0.0382498,0.000331023,8.38002e-07,-8.33135e-10,0.0385817,0.000332696,8.35502e-07,8.17825e-10,0.0389152,0.00033437,8.37956e-07,1.28718e-09,0.0392504,0.00033605,8.41817e-07,-2.2413e-09,0.0395873,0.000337727,8.35093e-07,3.95265e-09,0.0399258,0.000339409,8.46951e-07,-2.39332e-09,0.0402661,0.000341095,8.39771e-07,1.89533e-09,0.040608,0.000342781,8.45457e-07,-1.46271e-09,0.0409517,0.000344467,8.41069e-07,3.95554e-09,0.041297,0.000346161,8.52936e-07,-3.18369e-09,0.041644,0.000347857,8.43385e-07,1.32873e-09,0.0419927,0.000349548,8.47371e-07,1.59402e-09,0.0423431,0.000351248,8.52153e-07,-2.54336e-10,0.0426952,0.000352951,8.5139e-07,-5.76676e-10,0.043049,0.000354652,8.4966e-07,2.56114e-09,0.0434045,0.000356359,8.57343e-07,-2.21744e-09,0.0437617,0.000358067,8.50691e-07,2.58344e-09,0.0441206,0.000359776,8.58441e-07,-6.65826e-10,0.0444813,0.000361491,8.56444e-07,7.99218e-11,0.0448436,0.000363204,8.56684e-07,3.46063e-10,0.0452077,0.000364919,8.57722e-07,2.26116e-09,0.0455734,0.000366641,8.64505e-07,-1.94005e-09,0.045941,0.000368364,8.58685e-07,1.77384e-09,0.0463102,0.000370087,8.64007e-07,-1.43005e-09,0.0466811,0.000371811,8.59717e-07,3.94634e-09,0.0470538,0.000373542,8.71556e-07,-3.17946e-09,0.0474282,0.000375276,8.62017e-07,1.32104e-09,0.0478043,0.000377003,8.6598e-07,1.62045e-09,0.0481822,0.00037874,8.70842e-07,-3.52297e-10,0.0485618,0.000380481,8.69785e-07,-2.11211e-10,0.0489432,0.00038222,8.69151e-07,1.19716e-09,0.0493263,0.000383962,8.72743e-07,-8.52026e-10,0.0497111,0.000385705,8.70187e-07,2.21092e-09,0.0500977,0.000387452,8.76819e-07,-5.41339e-10,0.050486,0.000389204,8.75195e-07,-4.5361e-11,0.0508761,0.000390954,8.75059e-07,7.22669e-10,0.0512679,0.000392706,8.77227e-07,8.79936e-10,0.0516615,0.000394463,8.79867e-07,-5.17048e-10,0.0520568,0.000396222,8.78316e-07,1.18833e-09,0.0524539,0.000397982,8.81881e-07,-5.11022e-10,0.0528528,0.000399744,8.80348e-07,8.55683e-10,0.0532534,0.000401507,8.82915e-07,8.13562e-10,0.0536558,0.000403276,8.85356e-07,-3.84603e-10,0.05406,0.000405045,8.84202e-07,7.24962e-10,0.0544659,0.000406816,8.86377e-07,1.20986e-09,0.0548736,0.000408592,8.90006e-07,-1.83896e-09,0.0552831,0.000410367,8.84489e-07,2.42071e-09,0.0556944,0.000412143,8.91751e-07,-3.93413e-10,0.0561074,0.000413925,8.90571e-07,-8.46967e-10,0.0565222,0.000415704,8.8803e-07,3.78122e-09,0.0569388,0.000417491,8.99374e-07,-3.1021e-09,0.0573572,0.000419281,8.90068e-07,1.17658e-09,0.0577774,0.000421064,8.93597e-07,2.12117e-09,0.0581993,0.000422858,8.99961e-07,-2.21068e-09,0.0586231,0.000424651,8.93329e-07,2.9961e-09,0.0590486,0.000426447,9.02317e-07,-2.32311e-09,0.059476,0.000428244,8.95348e-07,2.57122e-09,0.0599051,0.000430043,9.03062e-07,-5.11098e-10,0.0603361,0.000431847,9.01528e-07,-5.27166e-10,0.0607688,0.000433649,8.99947e-07,2.61984e-09,0.0612034,0.000435457,9.07806e-07,-2.50141e-09,0.0616397,0.000437265,9.00302e-07,3.66045e-09,0.0620779,0.000439076,9.11283e-07,-4.68977e-09,0.0625179,0.000440885,8.97214e-07,7.64783e-09,0.0629597,0.000442702,9.20158e-07,-7.27499e-09,0.0634033,0.000444521,8.98333e-07,6.55113e-09,0.0638487,0.000446337,9.17986e-07,-4.02844e-09,0.0642959,0.000448161,9.05901e-07,2.11196e-09,0.064745,0.000449979,9.12236e-07,3.03125e-09,0.0651959,0.000451813,9.2133e-07,-6.78648e-09,0.0656486,0.000453635,9.00971e-07,9.21375e-09,0.0661032,0.000455464,9.28612e-07,-7.71684e-09,0.0665596,0.000457299,9.05462e-07,6.7522e-09,0.0670178,0.00045913,9.25718e-07,-4.3907e-09,0.0674778,0.000460968,9.12546e-07,3.36e-09,0.0679397,0.000462803,9.22626e-07,-1.59876e-09,0.0684034,0.000464644,9.1783e-07,3.0351e-09,0.068869,0.000466488,9.26935e-07,-3.09101e-09,0.0693364,0.000468333,9.17662e-07,1.8785e-09,0.0698057,0.000470174,9.23298e-07,3.02733e-09,0.0702768,0.00047203,9.3238e-07,-6.53722e-09,0.0707497,0.000473875,9.12768e-07,8.22054e-09,0.0712245,0.000475725,9.37429e-07,-3.99325e-09,0.0717012,0.000477588,9.2545e-07,3.01839e-10,0.0721797,0.00047944,9.26355e-07,2.78597e-09,0.0726601,0.000481301,9.34713e-07,-3.99507e-09,0.0731423,0.000483158,9.22728e-07,5.7435e-09,0.0736264,0.000485021,9.39958e-07,-4.07776e-09,0.0741123,0.000486888,9.27725e-07,3.11695e-09,0.0746002,0.000488753,9.37076e-07,-9.39394e-10,0.0750898,0.000490625,9.34258e-07,6.4055e-10,0.0755814,0.000492495,9.3618e-07,-1.62265e-09,0.0760748,0.000494363,9.31312e-07,5.84995e-09,0.0765701,0.000496243,9.48861e-07,-6.87601e-09,0.0770673,0.00049812,9.28233e-07,6.75296e-09,0.0775664,0.000499997,9.48492e-07,-5.23467e-09,0.0780673,0.000501878,9.32788e-07,6.73523e-09,0.0785701,0.000503764,9.52994e-07,-6.80514e-09,0.0790748,0.000505649,9.32578e-07,5.5842e-09,0.0795814,0.000507531,9.49331e-07,-6.30583e-10,0.0800899,0.000509428,9.47439e-07,-3.0618e-09,0.0806003,0.000511314,9.38254e-07,5.4273e-09,0.0811125,0.000513206,9.54536e-07,-3.74627e-09,0.0816267,0.000515104,9.43297e-07,2.10713e-09,0.0821427,0.000516997,9.49618e-07,2.76839e-09,0.0826607,0.000518905,9.57924e-07,-5.73006e-09,0.0831805,0.000520803,9.40733e-07,5.25072e-09,0.0837023,0.0005227,9.56486e-07,-3.71718e-10,0.084226,0.000524612,9.5537e-07,-3.76404e-09,0.0847515,0.000526512,9.44078e-07,7.97735e-09,0.085279,0.000528424,9.6801e-07,-5.79367e-09,0.0858084,0.000530343,9.50629e-07,2.96268e-10,0.0863397,0.000532245,9.51518e-07,4.6086e-09,0.0868729,0.000534162,9.65344e-07,-3.82947e-09,0.087408,0.000536081,9.53856e-07,3.25861e-09,0.087945,0.000537998,9.63631e-07,-1.7543e-09,0.088484,0.00053992,9.58368e-07,3.75849e-09,0.0890249,0.000541848,9.69644e-07,-5.82891e-09,0.0895677,0.00054377,9.52157e-07,4.65593e-09,0.0901124,0.000545688,9.66125e-07,2.10643e-09,0.0906591,0.000547627,9.72444e-07,-5.63099e-09,0.0912077,0.000549555,9.55551e-07,5.51627e-09,0.0917582,0.000551483,9.721e-07,-1.53292e-09,0.0923106,0.000553422,9.67501e-07,6.15311e-10,0.092865,0.000555359,9.69347e-07,-9.28291e-10,0.0934213,0.000557295,9.66562e-07,3.09774e-09,0.0939796,0.000559237,9.75856e-07,-4.01186e-09,0.0945398,0.000561177,9.6382e-07,5.49892e-09,0.095102,0.000563121,9.80317e-07,-3.08258e-09,0.0956661,0.000565073,9.71069e-07,-6.19176e-10,0.0962321,0.000567013,9.69212e-07,5.55932e-09,0.0968001,0.000568968,9.8589e-07,-6.71704e-09,0.09737,0.00057092,9.65738e-07,6.40762e-09,0.0979419,0.00057287,9.84961e-07,-4.0122e-09,0.0985158,0.000574828,9.72925e-07,2.19059e-09,0.0990916,0.000576781,9.79496e-07,2.70048e-09,0.0996693,0.000578748,9.87598e-07,-5.54193e-09,0.100249,0.000580706,9.70972e-07,4.56597e-09,0.100831,0.000582662,9.8467e-07,2.17923e-09,0.101414,0.000584638,9.91208e-07,-5.83232e-09,0.102,0.000586603,9.73711e-07,6.24884e-09,0.102588,0.000588569,9.92457e-07,-4.26178e-09,0.103177,0.000590541,9.79672e-07,3.34781e-09,0.103769,0.00059251,9.89715e-07,-1.67904e-09,0.104362,0.000594485,9.84678e-07,3.36839e-09,0.104958,0.000596464,9.94783e-07,-4.34397e-09,0.105555,0.000598441,9.81751e-07,6.55696e-09,0.106155,0.000600424,1.00142e-06,-6.98272e-09,0.106756,0.000602406,9.80474e-07,6.4728e-09,0.107359,0.000604386,9.99893e-07,-4.00742e-09,0.107965,0.000606374,9.8787e-07,2.10654e-09,0.108572,0.000608356,9.9419e-07,3.0318e-09,0.109181,0.000610353,1.00329e-06,-6.7832e-09,0.109793,0.00061234,9.82936e-07,9.1998e-09,0.110406,0.000614333,1.01054e-06,-7.6642e-09,0.111021,0.000616331,9.87543e-07,6.55579e-09,0.111639,0.000618326,1.00721e-06,-3.65791e-09,0.112258,0.000620329,9.96236e-07,6.25467e-10,0.112879,0.000622324,9.98113e-07,1.15593e-09,0.113503,0.000624323,1.00158e-06,2.20158e-09,0.114128,0.000626333,1.00819e-06,-2.51191e-09,0.114755,0.000628342,1.00065e-06,3.95517e-10,0.115385,0.000630345,1.00184e-06,9.29807e-10,0.116016,0.000632351,1.00463e-06,3.33599e-09,0.116649,0.00063437,1.01463e-06,-6.82329e-09,0.117285,0.000636379,9.94163e-07,9.05595e-09,0.117922,0.000638395,1.02133e-06,-7.04862e-09,0.118562,0.000640416,1.00019e-06,4.23737e-09,0.119203,0.000642429,1.0129e-06,-2.45033e-09,0.119847,0.000644448,1.00555e-06,5.56395e-09,0.120492,0.000646475,1.02224e-06,-4.9043e-09,0.121139,0.000648505,1.00753e-06,-8.47952e-10,0.121789,0.000650518,1.00498e-06,8.29622e-09,0.122441,0.000652553,1.02987e-06,-9.98538e-09,0.123094,0.000654582,9.99914e-07,9.2936e-09,0.12375,0.00065661,1.02779e-06,-4.83707e-09,0.124407,0.000658651,1.01328e-06,2.60411e-09,0.125067,0.000660685,1.0211e-06,-5.57945e-09,0.125729,0.000662711,1.00436e-06,1.22631e-08,0.126392,0.000664756,1.04115e-06,-1.36704e-08,0.127058,0.000666798,1.00014e-06,1.26161e-08,0.127726,0.000668836,1.03798e-06,-6.99155e-09,0.128396,0.000670891,1.01701e-06,4.48836e-10,0.129068,0.000672926,1.01836e-06,5.19606e-09,0.129742,0.000674978,1.03394e-06,-6.3319e-09,0.130418,0.000677027,1.01495e-06,5.2305e-09,0.131096,0.000679073,1.03064e-06,3.11123e-10,0.131776,0.000681135,1.03157e-06,-6.47511e-09,0.132458,0.000683179,1.01215e-06,1.06882e-08,0.133142,0.000685235,1.04421e-06,-6.47519e-09,0.133829,0.000687304,1.02479e-06,3.11237e-10,0.134517,0.000689355,1.02572e-06,5.23035e-09,0.135207,0.000691422,1.04141e-06,-6.3316e-09,0.1359,0.000693486,1.02242e-06,5.19484e-09,0.136594,0.000695546,1.038e-06,4.53497e-10,0.137291,0.000697623,1.03936e-06,-7.00891e-09,0.137989,0.000699681,1.01834e-06,1.2681e-08,0.13869,0.000701756,1.05638e-06,-1.39128e-08,0.139393,0.000703827,1.01464e-06,1.31679e-08,0.140098,0.000705896,1.05414e-06,-8.95659e-09,0.140805,0.000707977,1.02727e-06,7.75742e-09,0.141514,0.000710055,1.05055e-06,-7.17182e-09,0.142225,0.000712135,1.02903e-06,6.02862e-09,0.142938,0.000714211,1.04712e-06,-2.04163e-09,0.143653,0.000716299,1.04099e-06,2.13792e-09,0.144371,0.000718387,1.04741e-06,-6.51009e-09,0.14509,0.000720462,1.02787e-06,9.00123e-09,0.145812,0.000722545,1.05488e-06,3.07523e-10,0.146535,0.000724656,1.0558e-06,-1.02312e-08,0.147261,0.000726737,1.02511e-06,1.0815e-08,0.147989,0.000728819,1.05755e-06,-3.22681e-09,0.148719,0.000730925,1.04787e-06,2.09244e-09,0.14945,0.000733027,1.05415e-06,-5.143e-09,0.150185,0.00073512,1.03872e-06,3.57844e-09,0.150921,0.000737208,1.04946e-06,5.73027e-09,0.151659,0.000739324,1.06665e-06,-1.15983e-08,0.152399,0.000741423,1.03185e-06,1.08605e-08,0.153142,0.000743519,1.06443e-06,-2.04106e-09,0.153886,0.000745642,1.05831e-06,-2.69642e-09,0.154633,0.00074775,1.05022e-06,-2.07425e-09,0.155382,0.000749844,1.044e-06,1.09934e-08,0.156133,0.000751965,1.07698e-06,-1.20972e-08,0.156886,0.000754083,1.04069e-06,7.59288e-09,0.157641,0.000756187,1.06347e-06,-3.37305e-09,0.158398,0.000758304,1.05335e-06,5.89921e-09,0.159158,0.000760428,1.07104e-06,-5.32248e-09,0.159919,0.000762554,1.05508e-06,4.8927e-10,0.160683,0.000764666,1.05654e-06,3.36547e-09,0.161448,0.000766789,1.06664e-06,9.50081e-10,0.162216,0.000768925,1.06949e-06,-7.16568e-09,0.162986,0.000771043,1.04799e-06,1.28114e-08,0.163758,0.000773177,1.08643e-06,-1.42774e-08,0.164533,0.000775307,1.0436e-06,1.44956e-08,0.165309,0.000777438,1.08708e-06,-1.39025e-08,0.166087,0.00077957,1.04538e-06,1.13118e-08,0.166868,0.000781695,1.07931e-06,-1.54224e-09,0.167651,0.000783849,1.07468e-06,-5.14312e-09,0.168436,0.000785983,1.05925e-06,7.21381e-09,0.169223,0.000788123,1.0809e-06,-8.81096e-09,0.170012,0.000790259,1.05446e-06,1.31289e-08,0.170803,0.000792407,1.09385e-06,-1.39022e-08,0.171597,0.000794553,1.05214e-06,1.26775e-08,0.172392,0.000796695,1.09018e-06,-7.00557e-09,0.17319,0.000798855,1.06916e-06,4.43796e-10,0.17399,0.000800994,1.07049e-06,5.23031e-09,0.174792,0.000803151,1.08618e-06,-6.46397e-09,0.175596,0.000805304,1.06679e-06,5.72444e-09,0.176403,0.000807455,1.08396e-06,-1.53254e-09,0.177211,0.000809618,1.07937e-06,4.05673e-10,0.178022,0.000811778,1.08058e-06,-9.01916e-11,0.178835,0.000813939,1.08031e-06,-4.49821e-11,0.17965,0.000816099,1.08018e-06,2.70234e-10,0.180467,0.00081826,1.08099e-06,-1.03603e-09,0.181286,0.000820419,1.07788e-06,3.87392e-09,0.182108,0.000822587,1.0895e-06,4.41522e-10,0.182932,0.000824767,1.09083e-06,-5.63997e-09,0.183758,0.000826932,1.07391e-06,7.21707e-09,0.184586,0.000829101,1.09556e-06,-8.32718e-09,0.185416,0.000831267,1.07058e-06,1.11907e-08,0.186248,0.000833442,1.10415e-06,-6.63336e-09,0.187083,0.00083563,1.08425e-06,4.41484e-10,0.187919,0.0008378,1.08557e-06,4.86754e-09,0.188758,0.000839986,1.10017e-06,-5.01041e-09,0.189599,0.000842171,1.08514e-06,2.72811e-10,0.190443,0.000844342,1.08596e-06,3.91916e-09,0.191288,0.000846526,1.09772e-06,-1.04819e-09,0.192136,0.000848718,1.09457e-06,2.73531e-10,0.192985,0.000850908,1.0954e-06,-4.58916e-11,0.193837,0.000853099,1.09526e-06,-9.01158e-11,0.194692,0.000855289,1.09499e-06,4.06506e-10,0.195548,0.00085748,1.09621e-06,-1.53595e-09,0.196407,0.000859668,1.0916e-06,5.73717e-09,0.197267,0.000861869,1.10881e-06,-6.51164e-09,0.19813,0.000864067,1.08928e-06,5.40831e-09,0.198995,0.000866261,1.1055e-06,-2.20401e-10,0.199863,0.000868472,1.10484e-06,-4.52652e-09,0.200732,0.000870668,1.09126e-06,3.42508e-09,0.201604,0.000872861,1.10153e-06,5.72762e-09,0.202478,0.000875081,1.11872e-06,-1.14344e-08,0.203354,0.000877284,1.08441e-06,1.02076e-08,0.204233,0.000879484,1.11504e-06,4.06355e-10,0.205113,0.000881715,1.11626e-06,-1.18329e-08,0.205996,0.000883912,1.08076e-06,1.71227e-08,0.206881,0.000886125,1.13213e-06,-1.19546e-08,0.207768,0.000888353,1.09626e-06,8.93465e-10,0.208658,0.000890548,1.09894e-06,8.38062e-09,0.209549,0.000892771,1.12408e-06,-4.61353e-09,0.210443,0.000895006,1.11024e-06,-4.82756e-09,0.211339,0.000897212,1.09576e-06,9.02245e-09,0.212238,0.00089943,1.12283e-06,-1.45997e-09,0.213138,0.000901672,1.11845e-06,-3.18255e-09,0.214041,0.000903899,1.1089e-06,-7.11073e-10,0.214946,0.000906115,1.10677e-06,6.02692e-09,0.215853,0.000908346,1.12485e-06,-8.49548e-09,0.216763,0.00091057,1.09936e-06,1.30537e-08,0.217675,0.000912808,1.13852e-06,-1.3917e-08,0.218588,0.000915044,1.09677e-06,1.28121e-08,0.219505,0.000917276,1.13521e-06,-7.5288e-09,0.220423,0.000919523,1.11262e-06,2.40205e-09,0.221344,0.000921756,1.11983e-06,-2.07941e-09,0.222267,0.000923989,1.11359e-06,5.91551e-09,0.223192,0.000926234,1.13134e-06,-6.68149e-09,0.224119,0.000928477,1.11129e-06,5.90929e-09,0.225049,0.000930717,1.12902e-06,-2.05436e-09,0.22598,0.000932969,1.12286e-06,2.30807e-09,0.226915,0.000935222,1.12978e-06,-7.17796e-09,0.227851,0.00093746,1.10825e-06,1.15028e-08,0.228789,0.000939711,1.14276e-06,-9.03083e-09,0.22973,0.000941969,1.11566e-06,9.71932e-09,0.230673,0.00094423,1.14482e-06,-1.49452e-08,0.231619,0.000946474,1.09998e-06,2.02591e-08,0.232566,0.000948735,1.16076e-06,-2.13879e-08,0.233516,0.000950993,1.0966e-06,2.05888e-08,0.234468,0.000953247,1.15837e-06,-1.62642e-08,0.235423,0.000955515,1.10957e-06,1.46658e-08,0.236379,0.000957779,1.15357e-06,-1.25966e-08,0.237338,0.000960048,1.11578e-06,5.91793e-09,0.238299,0.000962297,1.13353e-06,3.82602e-09,0.239263,0.000964576,1.14501e-06,-6.3208e-09,0.240229,0.000966847,1.12605e-06,6.55613e-09,0.241197,0.000969119,1.14572e-06,-5.00268e-09,0.242167,0.000971395,1.13071e-06,-1.44659e-09,0.243139,0.000973652,1.12637e-06,1.07891e-08,0.244114,0.000975937,1.15874e-06,-1.19073e-08,0.245091,0.000978219,1.12302e-06,7.03782e-09,0.246071,0.000980486,1.14413e-06,-1.34276e-09,0.247052,0.00098277,1.1401e-06,-1.66669e-09,0.248036,0.000985046,1.1351e-06,8.00935e-09,0.249022,0.00098734,1.15913e-06,-1.54694e-08,0.250011,0.000989612,1.11272e-06,2.4066e-08,0.251002,0.000991909,1.18492e-06,-2.11901e-08,0.251995,0.000994215,1.12135e-06,1.08973e-09,0.25299,0.000996461,1.12462e-06,1.68311e-08,0.253988,0.000998761,1.17511e-06,-8.8094e-09,0.254987,0.00100109,1.14868e-06,-1.13958e-08,0.25599,0.00100335,1.1145e-06,2.45902e-08,0.256994,0.00100565,1.18827e-06,-2.73603e-08,0.258001,0.00100795,1.10618e-06,2.52464e-08,0.25901,0.00101023,1.18192e-06,-1.40207e-08,0.260021,0.00101256,1.13986e-06,1.03387e-09,0.261035,0.00101484,1.14296e-06,9.8853e-09,0.262051,0.00101715,1.17262e-06,-1.07726e-08,0.263069,0.00101947,1.1403e-06,3.40272e-09,0.26409,0.00102176,1.15051e-06,-2.83827e-09,0.265113,0.00102405,1.142e-06,7.95039e-09,0.266138,0.00102636,1.16585e-06,8.39047e-10,0.267166,0.00102869,1.16836e-06,-1.13066e-08,0.268196,0.00103099,1.13444e-06,1.4585e-08,0.269228,0.00103331,1.1782e-06,-1.72314e-08,0.270262,0.00103561,1.1265e-06,2.45382e-08,0.271299,0.00103794,1.20012e-06,-2.13166e-08,0.272338,0.00104028,1.13617e-06,1.12364e-09,0.273379,0.00104255,1.13954e-06,1.68221e-08,0.274423,0.00104488,1.19001e-06,-8.80736e-09,0.275469,0.00104723,1.16358e-06,-1.13948e-08,0.276518,0.00104953,1.1294e-06,2.45839e-08,0.277568,0.00105186,1.20315e-06,-2.73361e-08,0.278621,0.00105418,1.12114e-06,2.51559e-08,0.279677,0.0010565,1.19661e-06,-1.36832e-08,0.280734,0.00105885,1.15556e-06,-2.25706e-10,0.281794,0.00106116,1.15488e-06,1.45862e-08,0.282857,0.00106352,1.19864e-06,-2.83167e-08,0.283921,0.00106583,1.11369e-06,3.90759e-08,0.284988,0.00106817,1.23092e-06,-3.85801e-08,0.286058,0.00107052,1.11518e-06,2.58375e-08,0.287129,0.00107283,1.19269e-06,-5.16498e-09,0.288203,0.0010752,1.1772e-06,-5.17768e-09,0.28928,0.00107754,1.16167e-06,-3.92671e-09,0.290358,0.00107985,1.14988e-06,2.08846e-08,0.29144,0.00108221,1.21254e-06,-2.00072e-08,0.292523,0.00108458,1.15252e-06,-4.60659e-10,0.293609,0.00108688,1.15114e-06,2.18499e-08,0.294697,0.00108925,1.21669e-06,-2.73343e-08,0.295787,0.0010916,1.13468e-06,2.78826e-08,0.29688,0.00109395,1.21833e-06,-2.45915e-08,0.297975,0.00109632,1.14456e-06,1.08787e-08,0.299073,0.00109864,1.17719e-06,1.08788e-08,0.300172,0.00110102,1.20983e-06,-2.45915e-08,0.301275,0.00110337,1.13605e-06,2.78828e-08,0.302379,0.00110573,1.2197e-06,-2.73348e-08,0.303486,0.00110808,1.1377e-06,2.18518e-08,0.304595,0.00111042,1.20325e-06,-4.67556e-10,0.305707,0.00111283,1.20185e-06,-1.99816e-08,0.306821,0.00111517,1.14191e-06,2.07891e-08,0.307937,0.00111752,1.20427e-06,-3.57026e-09,0.309056,0.00111992,1.19356e-06,-6.50797e-09,0.310177,0.00112228,1.17404e-06,-2.00165e-10,0.3113,0.00112463,1.17344e-06,7.30874e-09,0.312426,0.001127,1.19536e-06,7.67424e-10,0.313554,0.00112939,1.19767e-06,-1.03784e-08,0.314685,0.00113176,1.16653e-06,1.09437e-08,0.315818,0.00113412,1.19936e-06,-3.59406e-09,0.316953,0.00113651,1.18858e-06,3.43251e-09,0.318091,0.0011389,1.19888e-06,-1.0136e-08,0.319231,0.00114127,1.16847e-06,7.30915e-09,0.320374,0.00114363,1.1904e-06,1.07018e-08,0.321518,0.00114604,1.2225e-06,-2.03137e-08,0.322666,0.00114842,1.16156e-06,1.09484e-08,0.323815,0.00115078,1.19441e-06,6.32224e-09,0.324967,0.00115319,1.21337e-06,-6.43509e-09,0.326122,0.00115559,1.19407e-06,-1.03842e-08,0.327278,0.00115795,1.16291e-06,1.81697e-08,0.328438,0.00116033,1.21742e-06,-2.6901e-09,0.329599,0.00116276,1.20935e-06,-7.40939e-09,0.330763,0.00116515,1.18713e-06,2.52533e-09,0.331929,0.00116754,1.1947e-06,-2.69191e-09,0.333098,0.00116992,1.18663e-06,8.24218e-09,0.334269,0.00117232,1.21135e-06,-4.74377e-10,0.335443,0.00117474,1.20993e-06,-6.34471e-09,0.336619,0.00117714,1.1909e-06,-3.94922e-09,0.337797,0.00117951,1.17905e-06,2.21417e-08,0.338978,0.00118193,1.24547e-06,-2.50128e-08,0.340161,0.00118435,1.17043e-06,1.8305e-08,0.341346,0.00118674,1.22535e-06,-1.84048e-08,0.342534,0.00118914,1.17013e-06,2.55121e-08,0.343725,0.00119156,1.24667e-06,-2.40389e-08,0.344917,0.00119398,1.17455e-06,1.10389e-08,0.346113,0.00119636,1.20767e-06,9.68574e-09,0.34731,0.0011988,1.23673e-06,-1.99797e-08,0.34851,0.00120122,1.17679e-06,1.06284e-08,0.349713,0.0012036,1.20867e-06,7.26868e-09,0.350917,0.00120604,1.23048e-06,-9.90072e-09,0.352125,0.00120847,1.20078e-06,2.53177e-09,0.353334,0.00121088,1.20837e-06,-2.26199e-10,0.354546,0.0012133,1.20769e-06,-1.62705e-09,0.355761,0.00121571,1.20281e-06,6.73435e-09,0.356978,0.00121813,1.22302e-06,4.49207e-09,0.358197,0.00122059,1.23649e-06,-2.47027e-08,0.359419,0.00122299,1.16238e-06,3.47142e-08,0.360643,0.00122542,1.26653e-06,-2.47472e-08,0.36187,0.00122788,1.19229e-06,4.66965e-09,0.363099,0.00123028,1.20629e-06,6.06872e-09,0.36433,0.00123271,1.2245e-06,8.57729e-10,0.365564,0.00123516,1.22707e-06,-9.49952e-09,0.366801,0.00123759,1.19858e-06,7.33792e-09,0.36804,0.00124001,1.22059e-06,9.95025e-09,0.369281,0.00124248,1.25044e-06,-1.73366e-08,0.370525,0.00124493,1.19843e-06,-2.08464e-10,0.371771,0.00124732,1.1978e-06,1.81704e-08,0.373019,0.00124977,1.25232e-06,-1.28683e-08,0.37427,0.00125224,1.21371e-06,3.50042e-09,0.375524,0.00125468,1.22421e-06,-1.1335e-09,0.37678,0.00125712,1.22081e-06,1.03345e-09,0.378038,0.00125957,1.22391e-06,-3.00023e-09,0.379299,0.00126201,1.21491e-06,1.09676e-08,0.380562,0.00126447,1.24781e-06,-1.10676e-08,0.381828,0.00126693,1.21461e-06,3.50042e-09,0.383096,0.00126937,1.22511e-06,-2.93403e-09,0.384366,0.00127181,1.21631e-06,8.23574e-09,0.385639,0.00127427,1.24102e-06,-2.06607e-10,0.386915,0.00127675,1.2404e-06,-7.40935e-09,0.388193,0.00127921,1.21817e-06,4.1761e-11,0.389473,0.00128165,1.21829e-06,7.24223e-09,0.390756,0.0012841,1.24002e-06,7.91564e-10,0.392042,0.00128659,1.2424e-06,-1.04086e-08,0.393329,0.00128904,1.21117e-06,1.10405e-08,0.39462,0.0012915,1.24429e-06,-3.951e-09,0.395912,0.00129397,1.23244e-06,4.7634e-09,0.397208,0.00129645,1.24673e-06,-1.51025e-08,0.398505,0.0012989,1.20142e-06,2.58443e-08,0.399805,0.00130138,1.27895e-06,-2.86702e-08,0.401108,0.00130385,1.19294e-06,2.92318e-08,0.402413,0.00130632,1.28064e-06,-2.86524e-08,0.403721,0.0013088,1.19468e-06,2.57731e-08,0.405031,0.00131127,1.272e-06,-1.48355e-08,0.406343,0.00131377,1.2275e-06,3.76652e-09,0.407658,0.00131623,1.23879e-06,-2.30784e-10,0.408976,0.00131871,1.2381e-06,-2.84331e-09,0.410296,0.00132118,1.22957e-06,1.16041e-08,0.411618,0.00132367,1.26438e-06,-1.37708e-08,0.412943,0.00132616,1.22307e-06,1.36768e-08,0.41427,0.00132865,1.2641e-06,-1.1134e-08,0.4156,0.00133114,1.2307e-06,1.05714e-09,0.416933,0.00133361,1.23387e-06,6.90538e-09,0.418267,0.00133609,1.25459e-06,1.12372e-09,0.419605,0.00133861,1.25796e-06,-1.14002e-08,0.420945,0.00134109,1.22376e-06,1.46747e-08,0.422287,0.00134358,1.26778e-06,-1.7496e-08,0.423632,0.00134606,1.21529e-06,2.5507e-08,0.424979,0.00134857,1.29182e-06,-2.49272e-08,0.426329,0.00135108,1.21703e-06,1.45972e-08,0.427681,0.00135356,1.26083e-06,-3.65935e-09,0.429036,0.00135607,1.24985e-06,4.00178e-11,0.430393,0.00135857,1.24997e-06,3.49917e-09,0.431753,0.00136108,1.26047e-06,-1.40366e-08,0.433116,0.00136356,1.21836e-06,2.28448e-08,0.43448,0.00136606,1.28689e-06,-1.77378e-08,0.435848,0.00136858,1.23368e-06,1.83043e-08,0.437218,0.0013711,1.28859e-06,-2.56769e-08,0.43859,0.0013736,1.21156e-06,2.47987e-08,0.439965,0.0013761,1.28595e-06,-1.39133e-08,0.441342,0.00137863,1.24421e-06,1.05202e-09,0.442722,0.00138112,1.24737e-06,9.70507e-09,0.444104,0.00138365,1.27649e-06,-1.00698e-08,0.445489,0.00138617,1.24628e-06,7.72123e-10,0.446877,0.00138867,1.24859e-06,6.98132e-09,0.448267,0.00139118,1.26954e-06,1.10477e-09,0.449659,0.00139373,1.27285e-06,-1.14003e-08,0.451054,0.00139624,1.23865e-06,1.4694e-08,0.452452,0.00139876,1.28273e-06,-1.75734e-08,0.453852,0.00140127,1.23001e-06,2.5797e-08,0.455254,0.00140381,1.3074e-06,-2.60097e-08,0.456659,0.00140635,1.22937e-06,1.86371e-08,0.458067,0.00140886,1.28529e-06,-1.8736e-08,0.459477,0.00141137,1.22908e-06,2.65048e-08,0.46089,0.00141391,1.30859e-06,-2.76784e-08,0.462305,0.00141645,1.22556e-06,2.46043e-08,0.463722,0.00141897,1.29937e-06,-1.11341e-08,0.465143,0.00142154,1.26597e-06,-9.87033e-09,0.466565,0.00142404,1.23636e-06,2.08131e-08,0.467991,0.00142657,1.2988e-06,-1.37773e-08,0.469419,0.00142913,1.25746e-06,4.49378e-09,0.470849,0.00143166,1.27094e-06,-4.19781e-09,0.472282,0.00143419,1.25835e-06,1.22975e-08,0.473717,0.00143674,1.29524e-06,-1.51902e-08,0.475155,0.00143929,1.24967e-06,1.86608e-08,0.476596,0.00144184,1.30566e-06,-2.96506e-08,0.478039,0.00144436,1.2167e-06,4.03368e-08,0.479485,0.00144692,1.33771e-06,-4.22896e-08,0.480933,0.00144947,1.21085e-06,3.94148e-08,0.482384,0.00145201,1.32909e-06,-2.59626e-08,0.483837,0.00145459,1.2512e-06,4.83124e-09,0.485293,0.0014571,1.2657e-06,6.63757e-09,0.486751,0.00145966,1.28561e-06,-1.57911e-09,0.488212,0.00146222,1.28087e-06,-3.21468e-10,0.489676,0.00146478,1.27991e-06,2.86517e-09,0.491142,0.00146735,1.2885e-06,-1.11392e-08,0.49261,0.00146989,1.25508e-06,1.18893e-08,0.494081,0.00147244,1.29075e-06,-6.61574e-09,0.495555,0.001475,1.27091e-06,1.45736e-08,0.497031,0.00147759,1.31463e-06,-2.18759e-08,0.49851,0.00148015,1.249e-06,1.33252e-08,0.499992,0.00148269,1.28897e-06,-1.62277e-09,0.501476,0.00148526,1.28411e-06,-6.83421e-09,0.502962,0.00148781,1.2636e-06,2.89596e-08,0.504451,0.00149042,1.35048e-06,-4.93997e-08,0.505943,0.00149298,1.20228e-06,4.94299e-08,0.507437,0.00149553,1.35057e-06,-2.91107e-08,0.508934,0.00149814,1.26324e-06,7.40848e-09,0.510434,0.00150069,1.28547e-06,-5.23187e-10,0.511936,0.00150326,1.2839e-06,-5.31585e-09,0.51344,0.00150581,1.26795e-06,2.17866e-08,0.514947,0.00150841,1.33331e-06,-2.22257e-08,0.516457,0.00151101,1.26663e-06,7.51178e-09,0.517969,0.00151357,1.28917e-06,-7.82128e-09,0.519484,0.00151613,1.2657e-06,2.37733e-08,0.521002,0.00151873,1.33702e-06,-2.76674e-08,0.522522,0.00152132,1.25402e-06,2.72917e-08,0.524044,0.00152391,1.3359e-06,-2.18949e-08,0.525569,0.00152652,1.27021e-06,6.83372e-10,0.527097,0.00152906,1.27226e-06,1.91613e-08,0.528628,0.00153166,1.32974e-06,-1.77241e-08,0.53016,0.00153427,1.27657e-06,-7.86963e-09,0.531696,0.0015368,1.25296e-06,4.92027e-08,0.533234,0.00153945,1.40057e-06,-6.9732e-08,0.534775,0.00154204,1.19138e-06,5.09114e-08,0.536318,0.00154458,1.34411e-06,-1.4704e-08,0.537864,0.00154722,1.3e-06,7.9048e-09,0.539413,0.00154984,1.32371e-06,-1.69152e-08,0.540964,0.00155244,1.27297e-06,1.51355e-10,0.542517,0.00155499,1.27342e-06,1.63099e-08,0.544074,0.00155758,1.32235e-06,-5.78647e-09,0.545633,0.00156021,1.30499e-06,6.83599e-09,0.547194,0.00156284,1.3255e-06,-2.15575e-08,0.548758,0.00156543,1.26083e-06,1.97892e-08,0.550325,0.00156801,1.32019e-06,2.00525e-09,0.551894,0.00157065,1.32621e-06,-2.78103e-08,0.553466,0.00157322,1.24278e-06,4.96314e-08,0.555041,0.00157586,1.39167e-06,-5.1506e-08,0.556618,0.00157849,1.23716e-06,3.71835e-08,0.558198,0.00158107,1.34871e-06,-3.76233e-08,0.55978,0.00158366,1.23584e-06,5.37052e-08,0.561365,0.00158629,1.39695e-06,-5.79884e-08,0.562953,0.00158891,1.22299e-06,5.90392e-08,0.564543,0.00159153,1.4001e-06,-5.89592e-08,0.566136,0.00159416,1.22323e-06,5.7588e-08,0.567731,0.00159678,1.39599e-06,-5.21835e-08,0.569329,0.00159941,1.23944e-06,3.19369e-08,0.57093,0.00160199,1.33525e-06,-1.59594e-08,0.572533,0.00160461,1.28737e-06,3.19006e-08,0.574139,0.00160728,1.38307e-06,-5.20383e-08,0.575748,0.00160989,1.22696e-06,5.70431e-08,0.577359,0.00161251,1.39809e-06,-5.69247e-08,0.578973,0.00161514,1.22731e-06,5.14463e-08,0.580589,0.00161775,1.38165e-06,-2.9651e-08,0.582208,0.00162042,1.2927e-06,7.55339e-09,0.58383,0.00162303,1.31536e-06,-5.62636e-10,0.585455,0.00162566,1.31367e-06,-5.30281e-09,0.587081,0.00162827,1.29776e-06,2.17738e-08,0.588711,0.00163093,1.36309e-06,-2.21875e-08,0.590343,0.00163359,1.29652e-06,7.37164e-09,0.591978,0.00163621,1.31864e-06,-7.29907e-09,0.593616,0.00163882,1.29674e-06,2.18247e-08,0.595256,0.00164148,1.36221e-06,-2.03952e-08,0.596899,0.00164414,1.30103e-06,1.51241e-10,0.598544,0.00164675,1.30148e-06,1.97902e-08,0.600192,0.00164941,1.36085e-06,-1.97074e-08,0.601843,0.00165207,1.30173e-06,-5.65175e-10,0.603496,0.00165467,1.30004e-06,2.1968e-08,0.605152,0.00165734,1.36594e-06,-2.77024e-08,0.606811,0.00165999,1.28283e-06,2.92369e-08,0.608472,0.00166264,1.37054e-06,-2.96407e-08,0.610136,0.00166529,1.28162e-06,2.97215e-08,0.611803,0.00166795,1.37079e-06,-2.96408e-08,0.613472,0.0016706,1.28186e-06,2.92371e-08,0.615144,0.00167325,1.36957e-06,-2.77031e-08,0.616819,0.00167591,1.28647e-06,2.19708e-08,0.618496,0.00167855,1.35238e-06,-5.75407e-10,0.620176,0.00168125,1.35065e-06,-1.9669e-08,0.621858,0.00168389,1.29164e-06,1.96468e-08,0.623544,0.00168653,1.35058e-06,6.86403e-10,0.625232,0.00168924,1.35264e-06,-2.23924e-08,0.626922,0.00169187,1.28547e-06,2.92788e-08,0.628615,0.00169453,1.3733e-06,-3.51181e-08,0.630311,0.00169717,1.26795e-06,5.15889e-08,0.63201,0.00169987,1.42272e-06,-5.2028e-08,0.633711,0.00170255,1.26663e-06,3.73139e-08,0.635415,0.0017052,1.37857e-06,-3.76227e-08,0.637121,0.00170784,1.2657e-06,5.35722e-08,0.63883,0.00171054,1.42642e-06,-5.74567e-08,0.640542,0.00171322,1.25405e-06,5.70456e-08,0.642257,0.0017159,1.42519e-06,-5.15163e-08,0.643974,0.00171859,1.27064e-06,2.98103e-08,0.645694,0.00172122,1.36007e-06,-8.12016e-09,0.647417,0.00172392,1.33571e-06,2.67039e-09,0.649142,0.0017266,1.34372e-06,-2.56152e-09,0.65087,0.00172928,1.33604e-06,7.57571e-09,0.6526,0.00173197,1.35876e-06,-2.77413e-08,0.654334,0.00173461,1.27554e-06,4.3785e-08,0.65607,0.00173729,1.40689e-06,-2.81896e-08,0.657808,0.00174002,1.32233e-06,9.36893e-09,0.65955,0.00174269,1.35043e-06,-9.28617e-09,0.661294,0.00174536,1.32257e-06,2.77757e-08,0.66304,0.00174809,1.4059e-06,-4.2212e-08,0.66479,0.00175078,1.27926e-06,2.1863e-08,0.666542,0.0017534,1.34485e-06,1.43648e-08,0.668297,0.00175613,1.38795e-06,-1.97177e-08,0.670054,0.00175885,1.3288e-06,4.90115e-09,0.671814,0.00176152,1.3435e-06,1.13232e-10,0.673577,0.00176421,1.34384e-06,-5.3542e-09,0.675343,0.00176688,1.32778e-06,2.13035e-08,0.677111,0.0017696,1.39169e-06,-2.02553e-08,0.678882,0.00177232,1.33092e-06,1.13005e-10,0.680656,0.00177499,1.33126e-06,1.98031e-08,0.682432,0.00177771,1.39067e-06,-1.97211e-08,0.684211,0.00178043,1.33151e-06,-5.2349e-10,0.685993,0.00178309,1.32994e-06,2.18151e-08,0.687777,0.00178582,1.39538e-06,-2.71325e-08,0.689564,0.00178853,1.31398e-06,2.71101e-08,0.691354,0.00179124,1.39531e-06,-2.17035e-08,0.693147,0.00179396,1.3302e-06,9.92865e-11,0.694942,0.00179662,1.3305e-06,2.13063e-08,0.69674,0.00179935,1.39442e-06,-2.57198e-08,0.698541,0.00180206,1.31726e-06,2.19682e-08,0.700344,0.00180476,1.38317e-06,-2.54852e-09,0.70215,0.00180752,1.37552e-06,-1.17741e-08,0.703959,0.00181023,1.3402e-06,-9.95999e-09,0.705771,0.00181288,1.31032e-06,5.16141e-08,0.707585,0.00181566,1.46516e-06,-7.72869e-08,0.709402,0.00181836,1.2333e-06,7.87197e-08,0.711222,0.00182106,1.46946e-06,-5.87781e-08,0.713044,0.00182382,1.29312e-06,3.71834e-08,0.714869,0.00182652,1.40467e-06,-3.03511e-08,0.716697,0.00182924,1.31362e-06,2.46161e-08,0.718528,0.00183194,1.38747e-06,-8.5087e-09,0.720361,0.00183469,1.36194e-06,9.41892e-09,0.722197,0.00183744,1.3902e-06,-2.91671e-08,0.724036,0.00184014,1.3027e-06,4.76448e-08,0.725878,0.00184288,1.44563e-06,-4.22028e-08,0.727722,0.00184565,1.31902e-06,1.95682e-09,0.729569,0.00184829,1.3249e-06,3.43754e-08,0.731419,0.00185104,1.42802e-06,-2.0249e-08,0.733271,0.00185384,1.36727e-06,-1.29838e-08,0.735126,0.00185654,1.32832e-06,1.25794e-08,0.736984,0.00185923,1.36606e-06,2.22711e-08,0.738845,0.00186203,1.43287e-06,-4.20594e-08,0.740708,0.00186477,1.3067e-06,2.67571e-08,0.742574,0.00186746,1.38697e-06,-5.36424e-09,0.744443,0.00187022,1.37087e-06,-5.30023e-09,0.746315,0.00187295,1.35497e-06,2.65653e-08,0.748189,0.00187574,1.43467e-06,-4.13564e-08,0.750066,0.00187848,1.3106e-06,1.9651e-08,0.751946,0.00188116,1.36955e-06,2.23572e-08,0.753828,0.00188397,1.43663e-06,-4.9475e-08,0.755714,0.00188669,1.2882e-06,5.63335e-08,0.757602,0.00188944,1.4572e-06,-5.66499e-08,0.759493,0.00189218,1.28725e-06,5.10567e-08,0.761386,0.00189491,1.44042e-06,-2.83677e-08,0.763283,0.00189771,1.35532e-06,2.80962e-09,0.765182,0.00190042,1.36375e-06,1.71293e-08,0.767083,0.0019032,1.41513e-06,-1.17221e-08,0.768988,0.001906,1.37997e-06,-2.98453e-08,0.770895,0.00190867,1.29043e-06,7.14987e-08,0.772805,0.00191146,1.50493e-06,-7.73354e-08,0.774718,0.00191424,1.27292e-06,5.90292e-08,0.776634,0.00191697,1.45001e-06,-3.9572e-08,0.778552,0.00191975,1.33129e-06,3.9654e-08,0.780473,0.00192253,1.45026e-06,-5.94395e-08,0.782397,0.00192525,1.27194e-06,7.88945e-08,0.784324,0.00192803,1.50862e-06,-7.73249e-08,0.786253,0.00193082,1.27665e-06,5.15913e-08,0.788185,0.00193352,1.43142e-06,-9.83099e-09,0.79012,0.00193636,1.40193e-06,-1.22672e-08,0.792058,0.00193912,1.36513e-06,-7.05275e-10,0.793999,0.00194185,1.36301e-06,1.50883e-08,0.795942,0.00194462,1.40828e-06,-4.33147e-11,0.797888,0.00194744,1.40815e-06,-1.49151e-08,0.799837,0.00195021,1.3634e-06,9.93244e-11,0.801788,0.00195294,1.3637e-06,1.45179e-08,0.803743,0.00195571,1.40725e-06,1.43363e-09,0.8057,0.00195853,1.41155e-06,-2.02525e-08,0.80766,0.00196129,1.35079e-06,1.99718e-08,0.809622,0.00196405,1.41071e-06,-3.01649e-11,0.811588,0.00196687,1.41062e-06,-1.9851e-08,0.813556,0.00196964,1.35107e-06,1.98296e-08,0.815527,0.0019724,1.41056e-06,1.37485e-10,0.817501,0.00197522,1.41097e-06,-2.03796e-08,0.819477,0.00197798,1.34983e-06,2.17763e-08,0.821457,0.00198074,1.41516e-06,-7.12085e-09,0.823439,0.00198355,1.3938e-06,6.70707e-09,0.825424,0.00198636,1.41392e-06,-1.97074e-08,0.827412,0.00198913,1.35479e-06,1.25179e-08,0.829402,0.00199188,1.39235e-06,2.92405e-08,0.831396,0.00199475,1.48007e-06,-6.98755e-08,0.833392,0.0019975,1.27044e-06,7.14477e-08,0.835391,0.00200026,1.48479e-06,-3.71014e-08,0.837392,0.00200311,1.37348e-06,1.73533e-08,0.839397,0.00200591,1.42554e-06,-3.23118e-08,0.841404,0.00200867,1.32861e-06,5.2289e-08,0.843414,0.00201148,1.48547e-06,-5.76348e-08,0.845427,0.00201428,1.31257e-06,5.9041e-08,0.847443,0.00201708,1.48969e-06,-5.93197e-08,0.849461,0.00201988,1.31173e-06,5.90289e-08,0.851482,0.00202268,1.48882e-06,-5.75864e-08,0.853507,0.00202549,1.31606e-06,5.21075e-08,0.855533,0.00202828,1.47238e-06,-3.16344e-08,0.857563,0.00203113,1.37748e-06,1.48257e-08,0.859596,0.00203393,1.42196e-06,-2.76684e-08,0.861631,0.00203669,1.33895e-06,3.62433e-08,0.863669,0.00203947,1.44768e-06,1.90463e-09,0.86571,0.00204237,1.45339e-06,-4.38617e-08,0.867754,0.00204515,1.32181e-06,5.43328e-08,0.8698,0.00204796,1.48481e-06,-5.42603e-08,0.87185,0.00205076,1.32203e-06,4.34989e-08,0.873902,0.00205354,1.45252e-06,-5.26029e-10,0.875957,0.00205644,1.45095e-06,-4.13949e-08,0.878015,0.00205922,1.32676e-06,4.68962e-08,0.880075,0.00206201,1.46745e-06,-2.69807e-08,0.882139,0.00206487,1.38651e-06,1.42181e-09,0.884205,0.00206764,1.39077e-06,2.12935e-08,0.886274,0.00207049,1.45465e-06,-2.69912e-08,0.888346,0.00207332,1.37368e-06,2.70664e-08,0.890421,0.00207615,1.45488e-06,-2.16698e-08,0.892498,0.00207899,1.38987e-06,8.14756e-12,0.894579,0.00208177,1.38989e-06,2.16371e-08,0.896662,0.00208462,1.45481e-06,-2.6952e-08,0.898748,0.00208744,1.37395e-06,2.65663e-08,0.900837,0.00209027,1.45365e-06,-1.97084e-08,0.902928,0.00209312,1.39452e-06,-7.33731e-09,0.905023,0.00209589,1.37251e-06,4.90578e-08,0.90712,0.00209878,1.51968e-06,-6.96845e-08,0.90922,0.00210161,1.31063e-06,5.08664e-08,0.911323,0.00210438,1.46323e-06,-1.45717e-08,0.913429,0.00210727,1.41952e-06,7.42038e-09,0.915538,0.00211013,1.44178e-06,-1.51097e-08,0.917649,0.00211297,1.39645e-06,-6.58618e-09,0.919764,0.00211574,1.37669e-06,4.14545e-08,0.921881,0.00211862,1.50105e-06,-4.00222e-08,0.924001,0.0021215,1.38099e-06,-5.7518e-10,0.926124,0.00212426,1.37926e-06,4.23229e-08,0.92825,0.00212714,1.50623e-06,-4.9507e-08,0.930378,0.00213001,1.35771e-06,3.64958e-08,0.93251,0.00213283,1.4672e-06,-3.68713e-08,0.934644,0.00213566,1.35658e-06,5.13848e-08,0.936781,0.00213852,1.51074e-06,-4.94585e-08,0.938921,0.0021414,1.36236e-06,2.72399e-08,0.941064,0.0021442,1.44408e-06,1.0372e-10,0.943209,0.00214709,1.44439e-06,-2.76547e-08,0.945358,0.0021499,1.36143e-06,5.09106e-08,0.947509,0.00215277,1.51416e-06,-5.67784e-08,0.949663,0.00215563,1.34382e-06,5.69935e-08,0.95182,0.00215849,1.5148e-06,-5.19861e-08,0.95398,0.00216136,1.35885e-06,3.17417e-08,0.956143,0.00216418,1.45407e-06,-1.53758e-08,0.958309,0.00216704,1.40794e-06,2.97615e-08,0.960477,0.00216994,1.49723e-06,-4.40657e-08,0.962649,0.00217281,1.36503e-06,2.72919e-08,0.964823,0.00217562,1.44691e-06,-5.49729e-09,0.967,0.0021785,1.43041e-06,-5.30273e-09,0.96918,0.00218134,1.41451e-06,2.67084e-08,0.971363,0.00218425,1.49463e-06,-4.19265e-08,0.973548,0.00218711,1.36885e-06,2.17881e-08,0.975737,0.00218992,1.43422e-06,1.43789e-08,0.977928,0.00219283,1.47735e-06,-1.96989e-08,0.980122,0.00219572,1.41826e-06,4.81221e-09,0.98232,0.00219857,1.43269e-06,4.50048e-10,0.98452,0.00220144,1.43404e-06,-6.61237e-09,0.986722,0.00220429,1.41421e-06,2.59993e-08,0.988928,0.0022072,1.4922e-06,-3.77803e-08,0.991137,0.00221007,1.37886e-06,5.9127e-09,0.993348,0.00221284,1.3966e-06,1.33339e-07,0.995563,0.00221604,1.79662e-06,-5.98872e-07,0.99778,0.00222015,0.,0.}; - - template - __device__ __forceinline__ void RGB2LabConvert_f(const T& src, D& dst) - { - const float _1_3 = 1.0f / 3.0f; - const float _a = 16.0f / 116.0f; - - float B = blueIdx == 0 ? src.x : src.z; - float G = src.y; - float R = blueIdx == 0 ? src.z : src.x; - - if (srgb) - { - B = splineInterpolate(B * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); - G = splineInterpolate(G * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); - R = splineInterpolate(R * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); - } - - float X = B * 0.189828f + G * 0.376219f + R * 0.433953f; - float Y = B * 0.072169f + G * 0.715160f + R * 0.212671f; - float Z = B * 0.872766f + G * 0.109477f + R * 0.017758f; - - float FX = X > 0.008856f ? ::powf(X, _1_3) : (7.787f * X + _a); - float FY = Y > 0.008856f ? ::powf(Y, _1_3) : (7.787f * Y + _a); - float FZ = Z > 0.008856f ? ::powf(Z, _1_3) : (7.787f * Z + _a); - - float L = Y > 0.008856f ? (116.f * FY - 16.f) : (903.3f * Y); - float a = 500.f * (FX - FY); - float b = 200.f * (FY - FZ); - - dst.x = L; - dst.y = a; - dst.z = b; - } - - template struct RGB2Lab; - template - struct RGB2Lab - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - RGB2LabConvert_b(src, dst); - - return dst; - } - __host__ __device__ __forceinline__ RGB2Lab() {} - __host__ __device__ __forceinline__ RGB2Lab(const RGB2Lab&) {} - }; - template - struct RGB2Lab - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - RGB2LabConvert_f(src, dst); - - return dst; - } - __host__ __device__ __forceinline__ RGB2Lab() {} - __host__ __device__ __forceinline__ RGB2Lab(const RGB2Lab&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(name, scn, dcn, srgb, blueIdx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2Lab functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - - namespace color_detail - { - __constant__ float c_sRGBInvGammaTab[] = {0,0.0126255,0.,-8.33961e-06,0.0126172,0.0126005,-2.50188e-05,4.1698e-05,0.0252344,0.0126756,0.000100075,-0.000158451,0.0378516,0.0124004,-0.000375277,-0.000207393,0.0496693,0.0110276,-0.000997456,0.00016837,0.0598678,0.00953783,-0.000492346,2.07235e-05,0.068934,0.00861531,-0.000430176,3.62876e-05,0.0771554,0.00786382,-0.000321313,1.87625e-05,0.0847167,0.00727748,-0.000265025,1.53594e-05,0.0917445,0.00679351,-0.000218947,1.10545e-05,0.0983301,0.00638877,-0.000185784,8.66984e-06,0.104542,0.00604322,-0.000159774,6.82996e-06,0.110432,0.00574416,-0.000139284,5.51008e-06,0.116042,0.00548212,-0.000122754,4.52322e-06,0.121406,0.00525018,-0.000109184,3.75557e-06,0.126551,0.00504308,-9.79177e-05,3.17134e-06,0.131499,0.00485676,-8.84037e-05,2.68469e-06,0.13627,0.004688,-8.03496e-05,2.31725e-06,0.14088,0.00453426,-7.33978e-05,2.00868e-06,0.145343,0.00439349,-6.73718e-05,1.74775e-06,0.149671,0.00426399,-6.21286e-05,1.53547e-06,0.153875,0.00414434,-5.75222e-05,1.364e-06,0.157963,0.00403338,-5.34301e-05,1.20416e-06,0.161944,0.00393014,-4.98177e-05,1.09114e-06,0.165825,0.00383377,-4.65443e-05,9.57987e-07,0.169613,0.00374356,-4.36703e-05,8.88359e-07,0.173314,0.00365888,-4.10052e-05,7.7849e-07,0.176933,0.00357921,-3.86697e-05,7.36254e-07,0.180474,0.00350408,-3.6461e-05,6.42534e-07,0.183942,0.00343308,-3.45334e-05,6.12614e-07,0.187342,0.00336586,-3.26955e-05,5.42894e-07,0.190675,0.00330209,-3.10669e-05,5.08967e-07,0.193947,0.00324149,-2.954e-05,4.75977e-07,0.197159,0.00318383,-2.8112e-05,4.18343e-07,0.200315,0.00312887,-2.6857e-05,4.13651e-07,0.203418,0.00307639,-2.5616e-05,3.70847e-07,0.206469,0.00302627,-2.45035e-05,3.3813e-07,0.209471,0.00297828,-2.34891e-05,3.32999e-07,0.212426,0.0029323,-2.24901e-05,2.96826e-07,0.215336,0.00288821,-2.15996e-05,2.82736e-07,0.218203,0.00284586,-2.07514e-05,2.70961e-07,0.221029,0.00280517,-1.99385e-05,2.42744e-07,0.223814,0.00276602,-1.92103e-05,2.33277e-07,0.226561,0.0027283,-1.85105e-05,2.2486e-07,0.229271,0.00269195,-1.78359e-05,2.08383e-07,0.231945,0.00265691,-1.72108e-05,1.93305e-07,0.234585,0.00262307,-1.66308e-05,1.80687e-07,0.237192,0.00259035,-1.60888e-05,1.86632e-07,0.239766,0.00255873,-1.55289e-05,1.60569e-07,0.24231,0.00252815,-1.50472e-05,1.54566e-07,0.244823,0.00249852,-1.45835e-05,1.59939e-07,0.247307,0.00246983,-1.41037e-05,1.29549e-07,0.249763,0.00244202,-1.3715e-05,1.41429e-07,0.252191,0.00241501,-1.32907e-05,1.39198e-07,0.254593,0.00238885,-1.28731e-05,1.06444e-07,0.256969,0.00236342,-1.25538e-05,1.2048e-07,0.25932,0.00233867,-1.21924e-05,1.26892e-07,0.261647,0.00231467,-1.18117e-05,8.72084e-08,0.26395,0.00229131,-1.15501e-05,1.20323e-07,0.26623,0.00226857,-1.11891e-05,8.71514e-08,0.268487,0.00224645,-1.09276e-05,9.73165e-08,0.270723,0.00222489,-1.06357e-05,8.98259e-08,0.272937,0.00220389,-1.03662e-05,7.98218e-08,0.275131,0.00218339,-1.01267e-05,9.75254e-08,0.277304,0.00216343,-9.83416e-06,6.65195e-08,0.279458,0.00214396,-9.63461e-06,8.34313e-08,0.281592,0.00212494,-9.38431e-06,7.65919e-08,0.283708,0.00210641,-9.15454e-06,5.7236e-08,0.285805,0.00208827,-8.98283e-06,8.18939e-08,0.287885,0.00207055,-8.73715e-06,6.2224e-08,0.289946,0.00205326,-8.55047e-06,5.66388e-08,0.291991,0.00203633,-8.38056e-06,6.88491e-08,0.294019,0.00201978,-8.17401e-06,5.53955e-08,0.296031,0.00200359,-8.00782e-06,6.71971e-08,0.298027,0.00198778,-7.80623e-06,3.34439e-08,0.300007,0.00197227,-7.7059e-06,6.7248e-08,0.301971,0.00195706,-7.50416e-06,5.51915e-08,0.303921,0.00194221,-7.33858e-06,3.98124e-08,0.305856,0.00192766,-7.21915e-06,5.37795e-08,0.307776,0.00191338,-7.05781e-06,4.30919e-08,0.309683,0.00189939,-6.92853e-06,4.20744e-08,0.311575,0.00188566,-6.80231e-06,5.68321e-08,0.313454,0.00187223,-6.63181e-06,2.86195e-08,0.31532,0.00185905,-6.54595e-06,3.73075e-08,0.317172,0.00184607,-6.43403e-06,6.05684e-08,0.319012,0.00183338,-6.25233e-06,1.84426e-08,0.320839,0.00182094,-6.197e-06,4.44757e-08,0.322654,0.00180867,-6.06357e-06,4.20729e-08,0.324456,0.00179667,-5.93735e-06,2.56511e-08,0.326247,0.00178488,-5.8604e-06,3.41368e-08,0.328026,0.00177326,-5.75799e-06,4.64177e-08,0.329794,0.00176188,-5.61874e-06,1.86107e-08,0.33155,0.0017507,-5.5629e-06,2.81511e-08,0.333295,0.00173966,-5.47845e-06,4.75987e-08,0.335029,0.00172884,-5.33565e-06,1.98726e-08,0.336753,0.00171823,-5.27604e-06,2.19226e-08,0.338466,0.00170775,-5.21027e-06,4.14483e-08,0.340169,0.00169745,-5.08592e-06,2.09017e-08,0.341861,0.00168734,-5.02322e-06,2.39561e-08,0.343543,0.00167737,-4.95135e-06,3.22852e-08,0.345216,0.00166756,-4.85449e-06,2.57173e-08,0.346878,0.00165793,-4.77734e-06,1.38569e-08,0.348532,0.00164841,-4.73577e-06,3.80634e-08,0.350175,0.00163906,-4.62158e-06,1.27043e-08,0.35181,0.00162985,-4.58347e-06,3.03279e-08,0.353435,0.00162078,-4.49249e-06,1.49961e-08,0.355051,0.00161184,-4.4475e-06,2.88977e-08,0.356659,0.00160303,-4.3608e-06,1.84241e-08,0.358257,0.00159436,-4.30553e-06,1.6616e-08,0.359848,0.0015858,-4.25568e-06,3.43218e-08,0.361429,0.00157739,-4.15272e-06,-4.89172e-09,0.363002,0.00156907,-4.16739e-06,4.48498e-08,0.364567,0.00156087,-4.03284e-06,4.30676e-09,0.366124,0.00155282,-4.01992e-06,2.73303e-08,0.367673,0.00154486,-3.93793e-06,5.58036e-09,0.369214,0.001537,-3.92119e-06,3.97554e-08,0.370747,0.00152928,-3.80193e-06,-1.55904e-08,0.372272,0.00152163,-3.8487e-06,5.24081e-08,0.37379,0.00151409,-3.69147e-06,-1.52272e-08,0.375301,0.00150666,-3.73715e-06,3.83028e-08,0.376804,0.0014993,-3.62225e-06,1.10278e-08,0.378299,0.00149209,-3.58916e-06,6.99326e-09,0.379788,0.00148493,-3.56818e-06,2.06038e-08,0.381269,0.00147786,-3.50637e-06,2.98009e-08,0.382744,0.00147093,-3.41697e-06,-2.05978e-08,0.384211,0.00146404,-3.47876e-06,5.25899e-08,0.385672,0.00145724,-3.32099e-06,-1.09471e-08,0.387126,0.00145056,-3.35383e-06,2.10009e-08,0.388573,0.00144392,-3.29083e-06,1.63501e-08,0.390014,0.00143739,-3.24178e-06,3.00641e-09,0.391448,0.00143091,-3.23276e-06,3.12282e-08,0.392875,0.00142454,-3.13908e-06,-8.70932e-09,0.394297,0.00141824,-3.16521e-06,3.34114e-08,0.395712,0.00141201,-3.06497e-06,-5.72754e-09,0.397121,0.00140586,-3.08215e-06,1.9301e-08,0.398524,0.00139975,-3.02425e-06,1.7931e-08,0.39992,0.00139376,-2.97046e-06,-1.61822e-09,0.401311,0.00138781,-2.97531e-06,1.83442e-08,0.402696,0.00138192,-2.92028e-06,1.76485e-08,0.404075,0.00137613,-2.86733e-06,4.68617e-10,0.405448,0.00137039,-2.86593e-06,1.02794e-08,0.406816,0.00136469,-2.83509e-06,1.80179e-08,0.408178,0.00135908,-2.78104e-06,7.05594e-09,0.409534,0.00135354,-2.75987e-06,1.33633e-08,0.410885,0.00134806,-2.71978e-06,-9.04568e-10,0.41223,0.00134261,-2.72249e-06,2.0057e-08,0.41357,0.00133723,-2.66232e-06,1.00841e-08,0.414905,0.00133194,-2.63207e-06,-7.88835e-10,0.416234,0.00132667,-2.63444e-06,2.28734e-08,0.417558,0.00132147,-2.56582e-06,-1.29785e-09,0.418877,0.00131633,-2.56971e-06,1.21205e-08,0.420191,0.00131123,-2.53335e-06,1.24202e-08,0.421499,0.0013062,-2.49609e-06,-2.19681e-09,0.422803,0.0013012,-2.50268e-06,2.61696e-08,0.424102,0.00129628,-2.42417e-06,-1.30747e-08,0.425396,0.00129139,-2.46339e-06,2.6129e-08,0.426685,0.00128654,-2.38501e-06,-2.03454e-09,0.427969,0.00128176,-2.39111e-06,1.18115e-08,0.429248,0.00127702,-2.35567e-06,1.43932e-08,0.430523,0.00127235,-2.31249e-06,-9.77965e-09,0.431793,0.00126769,-2.34183e-06,2.47253e-08,0.433058,0.00126308,-2.26766e-06,2.85278e-10,0.434319,0.00125855,-2.2668e-06,3.93614e-09,0.435575,0.00125403,-2.25499e-06,1.37722e-08,0.436827,0.00124956,-2.21368e-06,5.79803e-10,0.438074,0.00124513,-2.21194e-06,1.37112e-08,0.439317,0.00124075,-2.1708e-06,4.17973e-09,0.440556,0.00123642,-2.15826e-06,-6.27703e-10,0.44179,0.0012321,-2.16015e-06,2.81332e-08,0.44302,0.00122787,-2.07575e-06,-2.24985e-08,0.444246,0.00122365,-2.14324e-06,3.20586e-08,0.445467,0.00121946,-2.04707e-06,-1.6329e-08,0.446685,0.00121532,-2.09605e-06,3.32573e-08,0.447898,0.00121122,-1.99628e-06,-2.72927e-08,0.449107,0.00120715,-2.07816e-06,4.6111e-08,0.450312,0.00120313,-1.93983e-06,-3.79416e-08,0.451514,0.00119914,-2.05365e-06,4.60507e-08,0.452711,0.00119517,-1.9155e-06,-2.7052e-08,0.453904,0.00119126,-1.99666e-06,3.23551e-08,0.455093,0.00118736,-1.89959e-06,-1.29613e-08,0.456279,0.00118352,-1.93848e-06,1.94905e-08,0.45746,0.0011797,-1.88e-06,-5.39588e-09,0.458638,0.00117593,-1.89619e-06,2.09282e-09,0.459812,0.00117214,-1.88991e-06,2.68267e-08,0.460982,0.00116844,-1.80943e-06,-1.99925e-08,0.462149,0.00116476,-1.86941e-06,2.3341e-08,0.463312,0.00116109,-1.79939e-06,-1.37674e-08,0.464471,0.00115745,-1.84069e-06,3.17287e-08,0.465627,0.00115387,-1.7455e-06,-2.37407e-08,0.466779,0.00115031,-1.81673e-06,3.34315e-08,0.467927,0.00114677,-1.71643e-06,-2.05786e-08,0.469073,0.00114328,-1.77817e-06,1.90802e-08,0.470214,0.00113978,-1.72093e-06,3.86247e-09,0.471352,0.00113635,-1.70934e-06,-4.72759e-09,0.472487,0.00113292,-1.72352e-06,1.50478e-08,0.473618,0.00112951,-1.67838e-06,4.14108e-09,0.474746,0.00112617,-1.66595e-06,-1.80986e-09,0.47587,0.00112283,-1.67138e-06,3.09816e-09,0.476991,0.0011195,-1.66209e-06,1.92198e-08,0.478109,0.00111623,-1.60443e-06,-2.03726e-08,0.479224,0.00111296,-1.66555e-06,3.2468e-08,0.480335,0.00110973,-1.56814e-06,-2.00922e-08,0.481443,0.00110653,-1.62842e-06,1.80983e-08,0.482548,0.00110333,-1.57413e-06,7.30362e-09,0.48365,0.0011002,-1.55221e-06,-1.75107e-08,0.484749,0.00109705,-1.60475e-06,3.29373e-08,0.485844,0.00109393,-1.50594e-06,-2.48315e-08,0.486937,0.00109085,-1.58043e-06,3.65865e-08,0.488026,0.0010878,-1.47067e-06,-3.21078e-08,0.489112,0.00108476,-1.56699e-06,3.22397e-08,0.490195,0.00108172,-1.47027e-06,-7.44391e-09,0.491276,0.00107876,-1.49261e-06,-2.46428e-09,0.492353,0.00107577,-1.5e-06,1.73011e-08,0.493427,0.00107282,-1.4481e-06,-7.13552e-09,0.494499,0.0010699,-1.4695e-06,1.1241e-08,0.495567,0.001067,-1.43578e-06,-8.02637e-09,0.496633,0.0010641,-1.45986e-06,2.08645e-08,0.497695,0.00106124,-1.39726e-06,-1.58271e-08,0.498755,0.0010584,-1.44475e-06,1.26415e-08,0.499812,0.00105555,-1.40682e-06,2.48655e-08,0.500866,0.00105281,-1.33222e-06,-5.24988e-08,0.501918,0.00104999,-1.48972e-06,6.59206e-08,0.502966,0.00104721,-1.29196e-06,-3.237e-08,0.504012,0.00104453,-1.38907e-06,3.95479e-09,0.505055,0.00104176,-1.3772e-06,1.65509e-08,0.506096,0.00103905,-1.32755e-06,-1.05539e-08,0.507133,0.00103637,-1.35921e-06,2.56648e-08,0.508168,0.00103373,-1.28222e-06,-3.25007e-08,0.509201,0.00103106,-1.37972e-06,4.47336e-08,0.51023,0.00102844,-1.24552e-06,-2.72245e-08,0.511258,0.00102587,-1.32719e-06,4.55952e-09,0.512282,0.00102323,-1.31352e-06,8.98645e-09,0.513304,0.00102063,-1.28656e-06,1.90992e-08,0.514323,0.00101811,-1.22926e-06,-2.57786e-08,0.51534,0.00101557,-1.30659e-06,2.44104e-08,0.516355,0.00101303,-1.23336e-06,-1.22581e-08,0.517366,0.00101053,-1.27014e-06,2.4622e-08,0.518376,0.00100806,-1.19627e-06,-2.66253e-08,0.519383,0.00100559,-1.27615e-06,2.22744e-08,0.520387,0.00100311,-1.20932e-06,-2.8679e-09,0.521389,0.00100068,-1.21793e-06,-1.08029e-08,0.522388,0.000998211,-1.25034e-06,4.60795e-08,0.523385,0.000995849,-1.1121e-06,-5.4306e-08,0.52438,0.000993462,-1.27502e-06,5.19354e-08,0.525372,0.000991067,-1.11921e-06,-3.42262e-08,0.526362,0.000988726,-1.22189e-06,2.53646e-08,0.52735,0.000986359,-1.14579e-06,-7.62782e-09,0.528335,0.000984044,-1.16868e-06,5.14668e-09,0.529318,0.000981722,-1.15324e-06,-1.29589e-08,0.530298,0.000979377,-1.19211e-06,4.66888e-08,0.531276,0.000977133,-1.05205e-06,-5.45868e-08,0.532252,0.000974865,-1.21581e-06,5.24495e-08,0.533226,0.000972591,-1.05846e-06,-3.60019e-08,0.534198,0.000970366,-1.16647e-06,3.19537e-08,0.535167,0.000968129,-1.07061e-06,-3.2208e-08,0.536134,0.000965891,-1.16723e-06,3.72738e-08,0.537099,0.000963668,-1.05541e-06,2.32205e-09,0.538061,0.000961564,-1.04844e-06,-4.65618e-08,0.539022,0.000959328,-1.18813e-06,6.47159e-08,0.53998,0.000957146,-9.93979e-07,-3.3488e-08,0.540936,0.000955057,-1.09444e-06,9.63166e-09,0.54189,0.000952897,-1.06555e-06,-5.03871e-09,0.542842,0.000950751,-1.08066e-06,1.05232e-08,0.543792,0.000948621,-1.04909e-06,2.25503e-08,0.544739,0.000946591,-9.81444e-07,-4.11195e-08,0.545685,0.000944504,-1.1048e-06,2.27182e-08,0.546628,0.000942363,-1.03665e-06,9.85146e-09,0.54757,0.000940319,-1.00709e-06,-2.51938e-09,0.548509,0.000938297,-1.01465e-06,2.25858e-10,0.549446,0.000936269,-1.01397e-06,1.61598e-09,0.550381,0.000934246,-1.00913e-06,-6.68983e-09,0.551315,0.000932207,-1.0292e-06,2.51434e-08,0.552246,0.000930224,-9.53765e-07,-3.42793e-08,0.553175,0.000928214,-1.0566e-06,5.23688e-08,0.554102,0.000926258,-8.99497e-07,-5.59865e-08,0.555028,0.000924291,-1.06746e-06,5.23679e-08,0.555951,0.000922313,-9.10352e-07,-3.42763e-08,0.556872,0.00092039,-1.01318e-06,2.51326e-08,0.557792,0.000918439,-9.37783e-07,-6.64954e-09,0.558709,0.000916543,-9.57732e-07,1.46554e-09,0.559625,0.000914632,-9.53335e-07,7.87281e-10,0.560538,0.000912728,-9.50973e-07,-4.61466e-09,0.56145,0.000910812,-9.64817e-07,1.76713e-08,0.56236,0.000908935,-9.11804e-07,-6.46564e-09,0.563268,0.000907092,-9.312e-07,8.19121e-09,0.564174,0.000905255,-9.06627e-07,-2.62992e-08,0.565078,0.000903362,-9.85524e-07,3.74007e-08,0.565981,0.000901504,-8.73322e-07,-4.0942e-09,0.566882,0.000899745,-8.85605e-07,-2.1024e-08,0.56778,0.00089791,-9.48677e-07,2.85854e-08,0.568677,0.000896099,-8.62921e-07,-3.3713e-08,0.569573,0.000894272,-9.64059e-07,4.6662e-08,0.570466,0.000892484,-8.24073e-07,-3.37258e-08,0.571358,0.000890734,-9.25251e-07,2.86365e-08,0.572247,0.00088897,-8.39341e-07,-2.12155e-08,0.573135,0.000887227,-9.02988e-07,-3.37913e-09,0.574022,0.000885411,-9.13125e-07,3.47319e-08,0.574906,0.000883689,-8.08929e-07,-1.63394e-08,0.575789,0.000882022,-8.57947e-07,-2.8979e-08,0.57667,0.00088022,-9.44885e-07,7.26509e-08,0.57755,0.000878548,-7.26932e-07,-8.28106e-08,0.578427,0.000876845,-9.75364e-07,7.97774e-08,0.579303,0.000875134,-7.36032e-07,-5.74849e-08,0.580178,0.00087349,-9.08486e-07,3.09529e-08,0.58105,0.000871765,-8.15628e-07,-6.72206e-09,0.581921,0.000870114,-8.35794e-07,-4.06451e-09,0.582791,0.00086843,-8.47987e-07,2.29799e-08,0.583658,0.000866803,-7.79048e-07,-2.82503e-08,0.584524,0.00086516,-8.63799e-07,3.04167e-08,0.585388,0.000863524,-7.72548e-07,-3.38119e-08,0.586251,0.000861877,-8.73984e-07,4.52264e-08,0.587112,0.000860265,-7.38305e-07,-2.78842e-08,0.587972,0.000858705,-8.21958e-07,6.70567e-09,0.58883,0.000857081,-8.01841e-07,1.06161e-09,0.589686,0.000855481,-7.98656e-07,-1.09521e-08,0.590541,0.00085385,-8.31512e-07,4.27468e-08,0.591394,0.000852316,-7.03272e-07,-4.08257e-08,0.592245,0.000850787,-8.25749e-07,1.34677e-09,0.593095,0.000849139,-8.21709e-07,3.54387e-08,0.593944,0.000847602,-7.15393e-07,-2.38924e-08,0.59479,0.0008461,-7.8707e-07,5.26143e-10,0.595636,0.000844527,-7.85491e-07,2.17879e-08,0.596479,0.000843021,-7.20127e-07,-2.80733e-08,0.597322,0.000841497,-8.04347e-07,3.09005e-08,0.598162,0.000839981,-7.11646e-07,-3.5924e-08,0.599002,0.00083845,-8.19418e-07,5.3191e-08,0.599839,0.000836971,-6.59845e-07,-5.76307e-08,0.600676,0.000835478,-8.32737e-07,5.81227e-08,0.60151,0.000833987,-6.58369e-07,-5.56507e-08,0.602344,0.000832503,-8.25321e-07,4.52706e-08,0.603175,0.000830988,-6.89509e-07,-6.22236e-09,0.604006,0.000829591,-7.08176e-07,-2.03811e-08,0.604834,0.000828113,-7.6932e-07,2.8142e-08,0.605662,0.000826659,-6.84894e-07,-3.25822e-08,0.606488,0.000825191,-7.8264e-07,4.25823e-08,0.607312,0.000823754,-6.54893e-07,-1.85376e-08,0.608135,0.000822389,-7.10506e-07,-2.80365e-08,0.608957,0.000820883,-7.94616e-07,7.1079e-08,0.609777,0.000819507,-5.81379e-07,-7.74655e-08,0.610596,0.000818112,-8.13775e-07,5.9969e-08,0.611413,0.000816665,-6.33868e-07,-4.32013e-08,0.612229,0.000815267,-7.63472e-07,5.32313e-08,0.613044,0.0008139,-6.03778e-07,-5.05148e-08,0.613857,0.000812541,-7.55323e-07,2.96187e-08,0.614669,0.000811119,-6.66466e-07,-8.35545e-09,0.615479,0.000809761,-6.91533e-07,3.80301e-09,0.616288,0.00080839,-6.80124e-07,-6.85666e-09,0.617096,0.000807009,-7.00694e-07,2.36237e-08,0.617903,0.000805678,-6.29822e-07,-2.80336e-08,0.618708,0.000804334,-7.13923e-07,2.8906e-08,0.619511,0.000802993,-6.27205e-07,-2.79859e-08,0.620314,0.000801655,-7.11163e-07,2.34329e-08,0.621114,0.000800303,-6.40864e-07,-6.14108e-09,0.621914,0.000799003,-6.59287e-07,1.13151e-09,0.622712,0.000797688,-6.55893e-07,1.61507e-09,0.62351,0.000796381,-6.51048e-07,-7.59186e-09,0.624305,0.000795056,-6.73823e-07,2.87524e-08,0.6251,0.000793794,-5.87566e-07,-4.7813e-08,0.625893,0.000792476,-7.31005e-07,4.32901e-08,0.626685,0.000791144,-6.01135e-07,-6.13814e-09,0.627475,0.000789923,-6.19549e-07,-1.87376e-08,0.628264,0.000788628,-6.75762e-07,2.14837e-08,0.629052,0.000787341,-6.11311e-07,-7.59265e-09,0.629839,0.000786095,-6.34089e-07,8.88692e-09,0.630625,0.000784854,-6.07428e-07,-2.7955e-08,0.631409,0.000783555,-6.91293e-07,4.33285e-08,0.632192,0.000782302,-5.61307e-07,-2.61497e-08,0.632973,0.000781101,-6.39757e-07,1.6658e-09,0.633754,0.000779827,-6.34759e-07,1.94866e-08,0.634533,0.000778616,-5.76299e-07,-2.00076e-08,0.635311,0.000777403,-6.36322e-07,9.39091e-10,0.636088,0.000776133,-6.33505e-07,1.62512e-08,0.636863,0.000774915,-5.84751e-07,-6.33937e-09,0.637638,0.000773726,-6.03769e-07,9.10609e-09,0.638411,0.000772546,-5.76451e-07,-3.00849e-08,0.639183,0.000771303,-6.66706e-07,5.1629e-08,0.639953,0.000770125,-5.11819e-07,-5.7222e-08,0.640723,0.000768929,-6.83485e-07,5.80497e-08,0.641491,0.000767736,-5.09336e-07,-5.57674e-08,0.642259,0.000766551,-6.76638e-07,4.58105e-08,0.643024,0.000765335,-5.39206e-07,-8.26541e-09,0.643789,0.000764231,-5.64002e-07,-1.27488e-08,0.644553,0.000763065,-6.02249e-07,-3.44168e-10,0.645315,0.00076186,-6.03281e-07,1.41254e-08,0.646077,0.000760695,-5.60905e-07,3.44727e-09,0.646837,0.000759584,-5.50563e-07,-2.79144e-08,0.647596,0.000758399,-6.34307e-07,4.86057e-08,0.648354,0.000757276,-4.88489e-07,-4.72989e-08,0.64911,0.000756158,-6.30386e-07,2.13807e-08,0.649866,0.000754961,-5.66244e-07,2.13808e-08,0.65062,0.000753893,-5.02102e-07,-4.7299e-08,0.651374,0.000752746,-6.43999e-07,4.86059e-08,0.652126,0.000751604,-4.98181e-07,-2.79154e-08,0.652877,0.000750524,-5.81927e-07,3.45089e-09,0.653627,0.000749371,-5.71575e-07,1.41119e-08,0.654376,0.00074827,-5.29239e-07,-2.93748e-10,0.655123,0.00074721,-5.3012e-07,-1.29368e-08,0.65587,0.000746111,-5.68931e-07,-7.56355e-09,0.656616,0.000744951,-5.91621e-07,4.3191e-08,0.65736,0.000743897,-4.62048e-07,-4.59911e-08,0.658103,0.000742835,-6.00022e-07,2.15642e-08,0.658846,0.0007417,-5.35329e-07,1.93389e-08,0.659587,0.000740687,-4.77312e-07,-3.93152e-08,0.660327,0.000739615,-5.95258e-07,1.87126e-08,0.661066,0.00073848,-5.3912e-07,2.40695e-08,0.661804,0.000737474,-4.66912e-07,-5.53859e-08,0.662541,0.000736374,-6.33069e-07,7.82648e-08,0.663277,0.000735343,-3.98275e-07,-7.88593e-08,0.664012,0.00073431,-6.34853e-07,5.83585e-08,0.664745,0.000733215,-4.59777e-07,-3.53656e-08,0.665478,0.000732189,-5.65874e-07,2.34994e-08,0.66621,0.000731128,-4.95376e-07,9.72743e-10,0.66694,0.00073014,-4.92458e-07,-2.73903e-08,0.66767,0.000729073,-5.74629e-07,4.89839e-08,0.668398,0.000728071,-4.27677e-07,-4.93359e-08,0.669126,0.000727068,-5.75685e-07,2.91504e-08,0.669853,0.000726004,-4.88234e-07,-7.66109e-09,0.670578,0.000725004,-5.11217e-07,1.49392e-09,0.671303,0.000723986,-5.06735e-07,1.68533e-09,0.672026,0.000722978,-5.01679e-07,-8.23525e-09,0.672749,0.00072195,-5.26385e-07,3.12556e-08,0.67347,0.000720991,-4.32618e-07,-5.71825e-08,0.674191,0.000719954,-6.04166e-07,7.8265e-08,0.67491,0.00071898,-3.69371e-07,-7.70634e-08,0.675628,0.00071801,-6.00561e-07,5.11747e-08,0.676346,0.000716963,-4.47037e-07,-8.42615e-09,0.677062,0.000716044,-4.72315e-07,-1.747e-08,0.677778,0.000715046,-5.24725e-07,1.87015e-08,0.678493,0.000714053,-4.68621e-07,2.26856e-09,0.679206,0.000713123,-4.61815e-07,-2.77758e-08,0.679919,0.000712116,-5.45142e-07,4.92298e-08,0.68063,0.000711173,-3.97453e-07,-4.99339e-08,0.681341,0.000710228,-5.47255e-07,3.12967e-08,0.682051,0.000709228,-4.53365e-07,-1.56481e-08,0.68276,0.000708274,-5.00309e-07,3.12958e-08,0.683467,0.000707367,-4.06422e-07,-4.99303e-08,0.684174,0.000706405,-5.56213e-07,4.9216e-08,0.68488,0.00070544,-4.08565e-07,-2.77245e-08,0.685585,0.00070454,-4.91738e-07,2.07748e-09,0.686289,0.000703562,-4.85506e-07,1.94146e-08,0.686992,0.00070265,-4.27262e-07,-2.01314e-08,0.687695,0.000701735,-4.87656e-07,1.50616e-09,0.688396,0.000700764,-4.83137e-07,1.41067e-08,0.689096,0.00069984,-4.40817e-07,1.67168e-09,0.689795,0.000698963,-4.35802e-07,-2.07934e-08,0.690494,0.000698029,-4.98182e-07,2.18972e-08,0.691192,0.000697099,-4.32491e-07,-7.19092e-09,0.691888,0.000696212,-4.54064e-07,6.86642e-09,0.692584,0.000695325,-4.33464e-07,-2.02747e-08,0.693279,0.000694397,-4.94288e-07,1.46279e-08,0.693973,0.000693452,-4.50405e-07,2.13678e-08,0.694666,0.000692616,-3.86301e-07,-4.04945e-08,0.695358,0.000691721,-5.07785e-07,2.14009e-08,0.696049,0.00069077,-4.43582e-07,1.44955e-08,0.69674,0.000689926,-4.00096e-07,-1.97783e-08,0.697429,0.000689067,-4.5943e-07,5.01296e-09,0.698118,0.000688163,-4.44392e-07,-2.73521e-10,0.698805,0.000687273,-4.45212e-07,-3.91893e-09,0.699492,0.000686371,-4.56969e-07,1.59493e-08,0.700178,0.000685505,-4.09121e-07,-2.73351e-10,0.700863,0.000684686,-4.09941e-07,-1.4856e-08,0.701548,0.000683822,-4.54509e-07,9.25979e-11,0.702231,0.000682913,-4.54231e-07,1.44855e-08,0.702913,0.000682048,-4.10775e-07,1.56992e-09,0.703595,0.000681231,-4.06065e-07,-2.07652e-08,0.704276,0.000680357,-4.68361e-07,2.18864e-08,0.704956,0.000679486,-4.02701e-07,-7.17595e-09,0.705635,0.000678659,-4.24229e-07,6.81748e-09,0.706313,0.000677831,-4.03777e-07,-2.0094e-08,0.70699,0.000676963,-4.64059e-07,1.39538e-08,0.707667,0.000676077,-4.22197e-07,2.38835e-08,0.708343,0.000675304,-3.50547e-07,-4.98831e-08,0.709018,0.000674453,-5.00196e-07,5.64395e-08,0.709692,0.000673622,-3.30878e-07,-5.66657e-08,0.710365,0.00067279,-5.00875e-07,5.1014e-08,0.711037,0.000671942,-3.47833e-07,-2.81809e-08,0.711709,0.000671161,-4.32376e-07,2.10513e-09,0.712379,0.000670303,-4.2606e-07,1.97604e-08,0.713049,0.00066951,-3.66779e-07,-2.15422e-08,0.713718,0.000668712,-4.31406e-07,6.8038e-09,0.714387,0.000667869,-4.10994e-07,-5.67295e-09,0.715054,0.00066703,-4.28013e-07,1.5888e-08,0.715721,0.000666222,-3.80349e-07,1.72576e-09,0.716387,0.000665467,-3.75172e-07,-2.27911e-08,0.717052,0.000664648,-4.43545e-07,2.9834e-08,0.717716,0.00066385,-3.54043e-07,-3.69401e-08,0.718379,0.000663031,-4.64864e-07,5.83219e-08,0.719042,0.000662277,-2.89898e-07,-7.71382e-08,0.719704,0.000661465,-5.21313e-07,7.14171e-08,0.720365,0.000660637,-3.07061e-07,-2.97161e-08,0.721025,0.000659934,-3.96209e-07,-1.21575e-08,0.721685,0.000659105,-4.32682e-07,1.87412e-08,0.722343,0.000658296,-3.76458e-07,-3.2029e-09,0.723001,0.000657533,-3.86067e-07,-5.9296e-09,0.723659,0.000656743,-4.03856e-07,2.69213e-08,0.724315,0.000656016,-3.23092e-07,-4.21511e-08,0.724971,0.000655244,-4.49545e-07,2.24737e-08,0.725625,0.000654412,-3.82124e-07,1.18611e-08,0.726279,0.000653683,-3.46541e-07,-1.03132e-08,0.726933,0.000652959,-3.7748e-07,-3.02128e-08,0.727585,0.000652114,-4.68119e-07,7.15597e-08,0.728237,0.000651392,-2.5344e-07,-7.72119e-08,0.728888,0.000650654,-4.85075e-07,5.8474e-08,0.729538,0.000649859,-3.09654e-07,-3.74746e-08,0.730188,0.000649127,-4.22077e-07,3.18197e-08,0.730837,0.000648379,-3.26618e-07,-3.01997e-08,0.731485,0.000647635,-4.17217e-07,2.93747e-08,0.732132,0.000646888,-3.29093e-07,-2.76943e-08,0.732778,0.000646147,-4.12176e-07,2.17979e-08,0.733424,0.000645388,-3.46783e-07,1.07292e-10,0.734069,0.000644695,-3.46461e-07,-2.22271e-08,0.734713,0.000643935,-4.13142e-07,2.91963e-08,0.735357,0.000643197,-3.25553e-07,-3.49536e-08,0.736,0.000642441,-4.30414e-07,5.10133e-08,0.736642,0.000641733,-2.77374e-07,-4.98904e-08,0.737283,0.000641028,-4.27045e-07,2.93392e-08,0.737924,0.000640262,-3.39028e-07,-7.86156e-09,0.738564,0.000639561,-3.62612e-07,2.10703e-09,0.739203,0.000638842,-3.56291e-07,-5.6653e-10,0.739842,0.000638128,-3.57991e-07,1.59086e-10,0.740479,0.000637412,-3.57513e-07,-6.98321e-11,0.741116,0.000636697,-3.57723e-07,1.20214e-10,0.741753,0.000635982,-3.57362e-07,-4.10987e-10,0.742388,0.000635266,-3.58595e-07,1.5237e-09,0.743023,0.000634553,-3.54024e-07,-5.68376e-09,0.743657,0.000633828,-3.71075e-07,2.12113e-08,0.744291,0.00063315,-3.07441e-07,-1.95569e-08,0.744924,0.000632476,-3.66112e-07,-2.58816e-09,0.745556,0.000631736,-3.73877e-07,2.99096e-08,0.746187,0.000631078,-2.84148e-07,-5.74454e-08,0.746818,0.000630337,-4.56484e-07,8.06629e-08,0.747448,0.000629666,-2.14496e-07,-8.63922e-08,0.748077,0.000628978,-4.73672e-07,8.60918e-08,0.748706,0.000628289,-2.15397e-07,-7.91613e-08,0.749334,0.000627621,-4.5288e-07,5.17393e-08,0.749961,0.00062687,-2.97663e-07,-8.58662e-09,0.750588,0.000626249,-3.23422e-07,-1.73928e-08,0.751214,0.00062555,-3.75601e-07,1.85532e-08,0.751839,0.000624855,-3.19941e-07,2.78479e-09,0.752463,0.000624223,-3.11587e-07,-2.96923e-08,0.753087,0.000623511,-4.00664e-07,5.63799e-08,0.75371,0.000622879,-2.31524e-07,-7.66179e-08,0.754333,0.000622186,-4.61378e-07,7.12778e-08,0.754955,0.000621477,-2.47545e-07,-2.96794e-08,0.755576,0.000620893,-3.36583e-07,-1.21648e-08,0.756196,0.000620183,-3.73077e-07,1.87339e-08,0.756816,0.000619493,-3.16875e-07,-3.16622e-09,0.757435,0.00061885,-3.26374e-07,-6.0691e-09,0.758054,0.000618179,-3.44581e-07,2.74426e-08,0.758672,0.000617572,-2.62254e-07,-4.40968e-08,0.759289,0.000616915,-3.94544e-07,2.97352e-08,0.759906,0.000616215,-3.05338e-07,-1.52393e-08,0.760522,0.000615559,-3.51056e-07,3.12221e-08,0.761137,0.000614951,-2.5739e-07,-5.00443e-08,0.761751,0.000614286,-4.07523e-07,4.9746e-08,0.762365,0.00061362,-2.58285e-07,-2.97303e-08,0.762979,0.000613014,-3.47476e-07,9.57079e-09,0.763591,0.000612348,-3.18764e-07,-8.55287e-09,0.764203,0.000611685,-3.44422e-07,2.46407e-08,0.764815,0.00061107,-2.705e-07,-3.04053e-08,0.765426,0.000610437,-3.61716e-07,3.73759e-08,0.766036,0.000609826,-2.49589e-07,-5.94935e-08,0.766645,0.000609149,-4.28069e-07,8.13889e-08,0.767254,0.000608537,-1.83902e-07,-8.72483e-08,0.767862,0.000607907,-4.45647e-07,8.87901e-08,0.76847,0.000607282,-1.79277e-07,-8.90983e-08,0.769077,0.000606656,-4.46572e-07,8.87892e-08,0.769683,0.000606029,-1.80204e-07,-8.72446e-08,0.770289,0.000605407,-4.41938e-07,8.13752e-08,0.770894,0.000604768,-1.97812e-07,-5.94423e-08,0.771498,0.000604194,-3.76139e-07,3.71848e-08,0.772102,0.000603553,-2.64585e-07,-2.96922e-08,0.772705,0.000602935,-3.53661e-07,2.19793e-08,0.773308,0.000602293,-2.87723e-07,1.37955e-09,0.77391,0.000601722,-2.83585e-07,-2.74976e-08,0.774512,0.000601072,-3.66077e-07,4.9006e-08,0.775112,0.000600487,-2.19059e-07,-4.93171e-08,0.775712,0.000599901,-3.67011e-07,2.90531e-08,0.776312,0.000599254,-2.79851e-07,-7.29081e-09,0.776911,0.000598673,-3.01724e-07,1.10077e-10,0.777509,0.00059807,-3.01393e-07,6.85053e-09,0.778107,0.000597487,-2.80842e-07,-2.75123e-08,0.778704,0.000596843,-3.63379e-07,4.35939e-08,0.779301,0.000596247,-2.32597e-07,-2.7654e-08,0.779897,0.000595699,-3.15559e-07,7.41741e-09,0.780492,0.00059509,-2.93307e-07,-2.01562e-09,0.781087,0.000594497,-2.99354e-07,6.45059e-10,0.781681,0.000593901,-2.97418e-07,-5.64635e-10,0.782275,0.000593304,-2.99112e-07,1.61347e-09,0.782868,0.000592711,-2.94272e-07,-5.88926e-09,0.78346,0.000592105,-3.1194e-07,2.19436e-08,0.784052,0.000591546,-2.46109e-07,-2.22805e-08,0.784643,0.000590987,-3.1295e-07,7.57368e-09,0.785234,0.000590384,-2.90229e-07,-8.01428e-09,0.785824,0.00058978,-3.14272e-07,2.44834e-08,0.786414,0.000589225,-2.40822e-07,-3.03148e-08,0.787003,0.000588652,-3.31766e-07,3.7171e-08,0.787591,0.0005881,-2.20253e-07,-5.87646e-08,0.788179,0.000587483,-3.96547e-07,7.86782e-08,0.788766,0.000586926,-1.60512e-07,-7.71342e-08,0.789353,0.000586374,-3.91915e-07,5.10444e-08,0.789939,0.000585743,-2.38782e-07,-7.83422e-09,0.790524,0.000585242,-2.62284e-07,-1.97076e-08,0.791109,0.000584658,-3.21407e-07,2.70598e-08,0.791693,0.000584097,-2.40228e-07,-2.89269e-08,0.792277,0.000583529,-3.27008e-07,2.90431e-08,0.792861,0.000582963,-2.39879e-07,-2.76409e-08,0.793443,0.0005824,-3.22802e-07,2.1916e-08,0.794025,0.00058182,-2.57054e-07,-4.18368e-10,0.794607,0.000581305,-2.58309e-07,-2.02425e-08,0.795188,0.000580727,-3.19036e-07,2.17838e-08,0.795768,0.000580155,-2.53685e-07,-7.28814e-09,0.796348,0.000579625,-2.75549e-07,7.36871e-09,0.796928,0.000579096,-2.53443e-07,-2.21867e-08,0.797506,0.000578523,-3.20003e-07,2.17736e-08,0.798085,0.000577948,-2.54683e-07,-5.30296e-09,0.798662,0.000577423,-2.70592e-07,-5.61698e-10,0.799239,0.00057688,-2.72277e-07,7.54977e-09,0.799816,0.000576358,-2.49627e-07,-2.96374e-08,0.800392,0.00057577,-3.38539e-07,5.1395e-08,0.800968,0.000575247,-1.84354e-07,-5.67335e-08,0.801543,0.000574708,-3.54555e-07,5.63297e-08,0.802117,0.000574168,-1.85566e-07,-4.93759e-08,0.802691,0.000573649,-3.33693e-07,2.19646e-08,0.803264,0.000573047,-2.678e-07,2.1122e-08,0.803837,0.000572575,-2.04433e-07,-4.68482e-08,0.804409,0.000572026,-3.44978e-07,4.70613e-08,0.804981,0.000571477,-2.03794e-07,-2.21877e-08,0.805552,0.000571003,-2.70357e-07,-1.79153e-08,0.806123,0.000570408,-3.24103e-07,3.42443e-08,0.806693,0.000569863,-2.2137e-07,1.47556e-10,0.807263,0.000569421,-2.20928e-07,-3.48345e-08,0.807832,0.000568874,-3.25431e-07,1.99812e-08,0.808401,0.000568283,-2.65487e-07,1.45143e-08,0.808969,0.000567796,-2.21945e-07,-1.84338e-08,0.809536,0.000567297,-2.77246e-07,-3.83608e-10,0.810103,0.000566741,-2.78397e-07,1.99683e-08,0.81067,0.000566244,-2.18492e-07,-1.98848e-08,0.811236,0.000565747,-2.78146e-07,-3.38976e-11,0.811801,0.000565191,-2.78248e-07,2.00204e-08,0.812366,0.000564695,-2.18187e-07,-2.04429e-08,0.812931,0.000564197,-2.79516e-07,2.1467e-09,0.813495,0.000563644,-2.73076e-07,1.18561e-08,0.814058,0.000563134,-2.37507e-07,1.00334e-08,0.814621,0.000562689,-2.07407e-07,-5.19898e-08,0.815183,0.000562118,-3.63376e-07,7.87163e-08,0.815745,0.000561627,-1.27227e-07,-8.40616e-08,0.816306,0.000561121,-3.79412e-07,7.87163e-08,0.816867,0.000560598,-1.43263e-07,-5.19898e-08,0.817428,0.000560156,-2.99233e-07,1.00335e-08,0.817988,0.000559587,-2.69132e-07,1.18559e-08,0.818547,0.000559085,-2.33564e-07,2.14764e-09,0.819106,0.000558624,-2.27122e-07,-2.04464e-08,0.819664,0.000558108,-2.88461e-07,2.00334e-08,0.820222,0.000557591,-2.28361e-07,-8.24277e-11,0.820779,0.000557135,-2.28608e-07,-1.97037e-08,0.821336,0.000556618,-2.87719e-07,1.92925e-08,0.821893,0.000556101,-2.29841e-07,2.13831e-09,0.822448,0.000555647,-2.23427e-07,-2.78458e-08,0.823004,0.000555117,-3.06964e-07,4.96402e-08,0.823559,0.000554652,-1.58043e-07,-5.15058e-08,0.824113,0.000554181,-3.12561e-07,3.71737e-08,0.824667,0.000553668,-2.0104e-07,-3.75844e-08,0.82522,0.000553153,-3.13793e-07,5.35592e-08,0.825773,0.000552686,-1.53115e-07,-5.74431e-08,0.826326,0.000552207,-3.25444e-07,5.7004e-08,0.826878,0.000551728,-1.54433e-07,-5.13635e-08,0.827429,0.000551265,-3.08523e-07,2.92406e-08,0.82798,0.000550735,-2.20801e-07,-5.99424e-09,0.828531,0.000550276,-2.38784e-07,-5.26363e-09,0.829081,0.000549782,-2.54575e-07,2.70488e-08,0.82963,0.000549354,-1.73429e-07,-4.33268e-08,0.83018,0.000548878,-3.03409e-07,2.7049e-08,0.830728,0.000548352,-2.22262e-07,-5.26461e-09,0.831276,0.000547892,-2.38056e-07,-5.99057e-09,0.831824,0.000547397,-2.56027e-07,2.92269e-08,0.832371,0.000546973,-1.68347e-07,-5.13125e-08,0.832918,0.000546482,-3.22284e-07,5.68139e-08,0.833464,0.000546008,-1.51843e-07,-5.67336e-08,0.83401,0.000545534,-3.22043e-07,5.09113e-08,0.834555,0.000545043,-1.6931e-07,-2.77022e-08,0.8351,0.000544621,-2.52416e-07,2.92924e-10,0.835644,0.000544117,-2.51537e-07,2.65305e-08,0.836188,0.000543694,-1.71946e-07,-4.68105e-08,0.836732,0.00054321,-3.12377e-07,4.15021e-08,0.837275,0.000542709,-1.87871e-07,1.13355e-11,0.837817,0.000542334,-1.87837e-07,-4.15474e-08,0.838359,0.000541833,-3.12479e-07,4.69691e-08,0.838901,0.000541349,-1.71572e-07,-2.71196e-08,0.839442,0.000540925,-2.52931e-07,1.90462e-09,0.839983,0.000540425,-2.47217e-07,1.95011e-08,0.840523,0.000539989,-1.88713e-07,-2.03045e-08,0.841063,0.00053955,-2.49627e-07,2.11216e-09,0.841602,0.000539057,-2.4329e-07,1.18558e-08,0.842141,0.000538606,-2.07723e-07,1.00691e-08,0.842679,0.000538221,-1.77516e-07,-5.21324e-08,0.843217,0.00053771,-3.33913e-07,7.92513e-08,0.843755,0.00053728,-9.6159e-08,-8.60587e-08,0.844292,0.000536829,-3.54335e-07,8.61696e-08,0.844828,0.000536379,-9.58263e-08,-7.98057e-08,0.845364,0.000535948,-3.35243e-07,5.42394e-08,0.8459,0.00053544,-1.72525e-07,-1.79426e-08,0.846435,0.000535041,-2.26353e-07,1.75308e-08,0.84697,0.000534641,-1.73761e-07,-5.21806e-08,0.847505,0.000534137,-3.30302e-07,7.19824e-08,0.848038,0.000533692,-1.14355e-07,-5.69349e-08,0.848572,0.000533293,-2.8516e-07,3.65479e-08,0.849105,0.000532832,-1.75516e-07,-2.96519e-08,0.849638,0.000532392,-2.64472e-07,2.2455e-08,0.85017,0.000531931,-1.97107e-07,-5.63451e-10,0.850702,0.000531535,-1.98797e-07,-2.02011e-08,0.851233,0.000531077,-2.59401e-07,2.17634e-08,0.851764,0.000530623,-1.94111e-07,-7.24794e-09,0.852294,0.000530213,-2.15854e-07,7.22832e-09,0.852824,0.000529803,-1.94169e-07,-2.16653e-08,0.853354,0.00052935,-2.59165e-07,1.98283e-08,0.853883,0.000528891,-1.9968e-07,1.95678e-09,0.854412,0.000528497,-1.9381e-07,-2.76554e-08,0.85494,0.000528027,-2.76776e-07,4.90603e-08,0.855468,0.00052762,-1.29596e-07,-4.93764e-08,0.855995,0.000527213,-2.77725e-07,2.92361e-08,0.856522,0.000526745,-1.90016e-07,-7.96341e-09,0.857049,0.000526341,-2.13907e-07,2.61752e-09,0.857575,0.000525922,-2.06054e-07,-2.50665e-09,0.8581,0.000525502,-2.13574e-07,7.40906e-09,0.858626,0.000525097,-1.91347e-07,-2.71296e-08,0.859151,0.000524633,-2.72736e-07,4.15048e-08,0.859675,0.000524212,-1.48221e-07,-1.96802e-08,0.860199,0.000523856,-2.07262e-07,-2.23886e-08,0.860723,0.000523375,-2.74428e-07,4.96299e-08,0.861246,0.000522975,-1.25538e-07,-5.69216e-08,0.861769,0.000522553,-2.96303e-07,5.88473e-08,0.862291,0.000522137,-1.19761e-07,-5.92584e-08,0.862813,0.00052172,-2.97536e-07,5.8977e-08,0.863334,0.000521301,-1.20605e-07,-5.74403e-08,0.863855,0.000520888,-2.92926e-07,5.15751e-08,0.864376,0.000520457,-1.38201e-07,-2.96506e-08,0.864896,0.000520091,-2.27153e-07,7.42277e-09,0.865416,0.000519659,-2.04885e-07,-4.05057e-11,0.865936,0.00051925,-2.05006e-07,-7.26074e-09,0.866455,0.000518818,-2.26788e-07,2.90835e-08,0.866973,0.000518451,-1.39538e-07,-4.94686e-08,0.867492,0.000518024,-2.87944e-07,4.95814e-08,0.868009,0.000517597,-1.39199e-07,-2.96479e-08,0.868527,0.000517229,-2.28143e-07,9.40539e-09,0.869044,0.000516801,-1.99927e-07,-7.9737e-09,0.86956,0.000516378,-2.23848e-07,2.24894e-08,0.870077,0.000515997,-1.5638e-07,-2.23793e-08,0.870592,0.000515617,-2.23517e-07,7.42302e-09,0.871108,0.000515193,-2.01248e-07,-7.31283e-09,0.871623,0.000514768,-2.23187e-07,2.18283e-08,0.872137,0.000514387,-1.57702e-07,-2.03959e-08,0.872652,0.000514011,-2.1889e-07,1.50711e-10,0.873165,0.000513573,-2.18437e-07,1.97931e-08,0.873679,0.000513196,-1.59058e-07,-1.97183e-08,0.874192,0.000512819,-2.18213e-07,-5.24324e-10,0.874704,0.000512381,-2.19786e-07,2.18156e-08,0.875217,0.000512007,-1.54339e-07,-2.71336e-08,0.875728,0.000511616,-2.3574e-07,2.71141e-08,0.87624,0.000511226,-1.54398e-07,-2.17182e-08,0.876751,0.000510852,-2.19552e-07,1.54131e-10,0.877262,0.000510414,-2.1909e-07,2.11017e-08,0.877772,0.000510039,-1.55785e-07,-2.49562e-08,0.878282,0.000509652,-2.30654e-07,1.91183e-08,0.878791,0.000509248,-1.73299e-07,8.08751e-09,0.8793,0.000508926,-1.49036e-07,-5.14684e-08,0.879809,0.000508474,-3.03441e-07,7.85766e-08,0.880317,0.000508103,-6.77112e-08,-8.40242e-08,0.880825,0.000507715,-3.19784e-07,7.87063e-08,0.881333,0.000507312,-8.36649e-08,-5.19871e-08,0.88184,0.000506988,-2.39626e-07,1.00327e-08,0.882346,0.000506539,-2.09528e-07,1.18562e-08,0.882853,0.000506156,-1.73959e-07,2.14703e-09,0.883359,0.000505814,-1.67518e-07,-2.04444e-08,0.883864,0.000505418,-2.28851e-07,2.00258e-08,0.88437,0.00050502,-1.68774e-07,-5.42855e-11,0.884874,0.000504682,-1.68937e-07,-1.98087e-08,0.885379,0.000504285,-2.28363e-07,1.96842e-08,0.885883,0.000503887,-1.6931e-07,6.76342e-10,0.886387,0.000503551,-1.67281e-07,-2.23896e-08,0.88689,0.000503149,-2.3445e-07,2.92774e-08,0.887393,0.000502768,-1.46618e-07,-3.51152e-08,0.887896,0.00050237,-2.51963e-07,5.15787e-08,0.888398,0.00050202,-9.72271e-08,-5.19903e-08,0.8889,0.00050167,-2.53198e-07,3.71732e-08,0.889401,0.000501275,-1.41678e-07,-3.70978e-08,0.889902,0.00050088,-2.52972e-07,5.16132e-08,0.890403,0.000500529,-9.81321e-08,-5.01459e-08,0.890903,0.000500183,-2.4857e-07,2.9761e-08,0.891403,0.000499775,-1.59287e-07,-9.29351e-09,0.891903,0.000499428,-1.87167e-07,7.41301e-09,0.892402,0.000499076,-1.64928e-07,-2.03585e-08,0.892901,0.000498685,-2.26004e-07,1.44165e-08,0.893399,0.000498276,-1.82754e-07,2.22974e-08,0.893898,0.000497978,-1.15862e-07,-4.40013e-08,0.894395,0.000497614,-2.47866e-07,3.44985e-08,0.894893,0.000497222,-1.44371e-07,-3.43882e-08,0.89539,0.00049683,-2.47535e-07,4.34497e-08,0.895886,0.000496465,-1.17186e-07,-2.02012e-08,0.896383,0.00049617,-1.7779e-07,-2.22497e-08,0.896879,0.000495748,-2.44539e-07,4.95952e-08,0.897374,0.000495408,-9.57532e-08,-5.69217e-08,0.89787,0.000495045,-2.66518e-07,5.88823e-08,0.898364,0.000494689,-8.98713e-08,-5.93983e-08,0.898859,0.000494331,-2.68066e-07,5.95017e-08,0.899353,0.000493973,-8.95613e-08,-5.9399e-08,0.899847,0.000493616,-2.67758e-07,5.8885e-08,0.90034,0.000493257,-9.11033e-08,-5.69317e-08,0.900833,0.000492904,-2.61898e-07,4.96326e-08,0.901326,0.000492529,-1.13001e-07,-2.23893e-08,0.901819,0.000492236,-1.80169e-07,-1.968e-08,0.902311,0.000491817,-2.39209e-07,4.15047e-08,0.902802,0.000491463,-1.14694e-07,-2.71296e-08,0.903293,0.000491152,-1.96083e-07,7.409e-09,0.903784,0.000490782,-1.73856e-07,-2.50645e-09,0.904275,0.000490427,-1.81376e-07,2.61679e-09,0.904765,0.000490072,-1.73525e-07,-7.96072e-09,0.905255,0.000489701,-1.97407e-07,2.92261e-08,0.905745,0.000489394,-1.09729e-07,-4.93389e-08,0.906234,0.000489027,-2.57746e-07,4.89204e-08,0.906723,0.000488658,-1.10985e-07,-2.71333e-08,0.907211,0.000488354,-1.92385e-07,8.30861e-12,0.907699,0.00048797,-1.9236e-07,2.71001e-08,0.908187,0.000487666,-1.1106e-07,-4.88041e-08,0.908675,0.000487298,-2.57472e-07,4.89069e-08,0.909162,0.000486929,-1.10751e-07,-2.76143e-08,0.909649,0.000486625,-1.93594e-07,1.9457e-09,0.910135,0.000486244,-1.87757e-07,1.98315e-08,0.910621,0.000485928,-1.28262e-07,-2.16671e-08,0.911107,0.000485606,-1.93264e-07,7.23216e-09,0.911592,0.000485241,-1.71567e-07,-7.26152e-09,0.912077,0.000484877,-1.93352e-07,2.18139e-08,0.912562,0.000484555,-1.2791e-07,-2.03895e-08,0.913047,0.000484238,-1.89078e-07,1.39494e-10,0.913531,0.000483861,-1.8866e-07,1.98315e-08,0.914014,0.000483543,-1.29165e-07,-1.98609e-08,0.914498,0.000483225,-1.88748e-07,7.39912e-12,0.914981,0.000482847,-1.88726e-07,1.98313e-08,0.915463,0.000482529,-1.29232e-07,-1.9728e-08,0.915946,0.000482212,-1.88416e-07,-5.24035e-10,0.916428,0.000481833,-1.89988e-07,2.18241e-08,0.916909,0.000481519,-1.24516e-07,-2.71679e-08,0.917391,0.000481188,-2.06019e-07,2.72427e-08,0.917872,0.000480858,-1.24291e-07,-2.21985e-08,0.918353,0.000480543,-1.90886e-07,1.94644e-09,0.918833,0.000480167,-1.85047e-07,1.44127e-08,0.919313,0.00047984,-1.41809e-07,7.39438e-12,0.919793,0.000479556,-1.41787e-07,-1.44423e-08,0.920272,0.000479229,-1.85114e-07,-1.84291e-09,0.920751,0.000478854,-1.90642e-07,2.18139e-08,0.92123,0.000478538,-1.25201e-07,-2.58081e-08,0.921708,0.00047821,-2.02625e-07,2.18139e-08,0.922186,0.00047787,-1.37183e-07,-1.84291e-09,0.922664,0.00047759,-1.42712e-07,-1.44423e-08,0.923141,0.000477262,-1.86039e-07,7.34701e-12,0.923618,0.00047689,-1.86017e-07,1.44129e-08,0.924095,0.000476561,-1.42778e-07,1.94572e-09,0.924572,0.000476281,-1.36941e-07,-2.21958e-08,0.925048,0.000475941,-2.03528e-07,2.72327e-08,0.925523,0.000475615,-1.2183e-07,-2.71304e-08,0.925999,0.00047529,-2.03221e-07,2.16843e-08,0.926474,0.000474949,-1.38168e-07,-2.16005e-12,0.926949,0.000474672,-1.38175e-07,-2.16756e-08,0.927423,0.000474331,-2.03202e-07,2.71001e-08,0.927897,0.000474006,-1.21902e-07,-2.71201e-08,0.928371,0.000473681,-2.03262e-07,2.17757e-08,0.928845,0.00047334,-1.37935e-07,-3.78028e-10,0.929318,0.000473063,-1.39069e-07,-2.02636e-08,0.929791,0.000472724,-1.9986e-07,2.18276e-08,0.930263,0.000472389,-1.34377e-07,-7.44231e-09,0.930736,0.000472098,-1.56704e-07,7.94165e-09,0.931208,0.000471809,-1.32879e-07,-2.43243e-08,0.931679,0.00047147,-2.05851e-07,2.97508e-08,0.932151,0.000471148,-1.16599e-07,-3.50742e-08,0.932622,0.000470809,-2.21822e-07,5.09414e-08,0.933092,0.000470518,-6.89976e-08,-4.94821e-08,0.933563,0.000470232,-2.17444e-07,2.77775e-08,0.934033,0.00046988,-1.34111e-07,-2.02351e-09,0.934502,0.000469606,-1.40182e-07,-1.96835e-08,0.934972,0.000469267,-1.99232e-07,2.11529e-08,0.935441,0.000468932,-1.35774e-07,-5.32332e-09,0.93591,0.000468644,-1.51743e-07,1.40413e-10,0.936378,0.000468341,-1.51322e-07,4.76166e-09,0.936846,0.000468053,-1.37037e-07,-1.9187e-08,0.937314,0.000467721,-1.94598e-07,1.23819e-08,0.937782,0.000467369,-1.57453e-07,2.92642e-08,0.938249,0.000467142,-6.96601e-08,-6.98342e-08,0.938716,0.000466793,-2.79163e-07,7.12586e-08,0.939183,0.000466449,-6.53869e-08,-3.63863e-08,0.939649,0.000466209,-1.74546e-07,1.46818e-08,0.940115,0.000465904,-1.305e-07,-2.2341e-08,0.940581,0.000465576,-1.97523e-07,1.50774e-08,0.941046,0.000465226,-1.52291e-07,2.16359e-08,0.941511,0.000464986,-8.73832e-08,-4.20162e-08,0.941976,0.000464685,-2.13432e-07,2.72198e-08,0.942441,0.00046434,-1.31773e-07,-7.2581e-09,0.942905,0.000464055,-1.53547e-07,1.81263e-09,0.943369,0.000463753,-1.48109e-07,7.58386e-12,0.943832,0.000463457,-1.48086e-07,-1.84298e-09,0.944296,0.000463155,-1.53615e-07,7.36433e-09,0.944759,0.00046287,-1.31522e-07,-2.76143e-08,0.945221,0.000462524,-2.14365e-07,4.34883e-08,0.945684,0.000462226,-8.39003e-08,-2.71297e-08,0.946146,0.000461977,-1.65289e-07,5.42595e-09,0.946608,0.000461662,-1.49012e-07,5.42593e-09,0.947069,0.000461381,-1.32734e-07,-2.71297e-08,0.94753,0.000461034,-2.14123e-07,4.34881e-08,0.947991,0.000460736,-8.36585e-08,-2.76134e-08,0.948452,0.000460486,-1.66499e-07,7.36083e-09,0.948912,0.000460175,-1.44416e-07,-1.82993e-09,0.949372,0.000459881,-1.49906e-07,-4.11073e-11,0.949832,0.000459581,-1.50029e-07,1.99434e-09,0.950291,0.000459287,-1.44046e-07,-7.93627e-09,0.950751,0.000458975,-1.67855e-07,2.97507e-08,0.951209,0.000458728,-7.86029e-08,-5.1462e-08,0.951668,0.000458417,-2.32989e-07,5.6888e-08,0.952126,0.000458121,-6.2325e-08,-5.68806e-08,0.952584,0.000457826,-2.32967e-07,5.14251e-08,0.953042,0.000457514,-7.86914e-08,-2.96107e-08,0.953499,0.000457268,-1.67523e-07,7.41296e-09,0.953956,0.000456955,-1.45285e-07,-4.11262e-11,0.954413,0.000456665,-1.45408e-07,-7.24847e-09,0.95487,0.000456352,-1.67153e-07,2.9035e-08,0.955326,0.000456105,-8.00484e-08,-4.92869e-08,0.955782,0.000455797,-2.27909e-07,4.89032e-08,0.956238,0.000455488,-8.11994e-08,-2.71166e-08,0.956693,0.000455244,-1.62549e-07,-4.13678e-11,0.957148,0.000454919,-1.62673e-07,2.72821e-08,0.957603,0.000454675,-8.0827e-08,-4.94824e-08,0.958057,0.000454365,-2.29274e-07,5.14382e-08,0.958512,0.000454061,-7.49597e-08,-3.7061e-08,0.958965,0.0004538,-1.86143e-07,3.72013e-08,0.959419,0.000453539,-7.45389e-08,-5.21396e-08,0.959873,0.000453234,-2.30958e-07,5.21476e-08,0.960326,0.000452928,-7.45146e-08,-3.72416e-08,0.960778,0.000452667,-1.8624e-07,3.72143e-08,0.961231,0.000452407,-7.45967e-08,-5.20109e-08,0.961683,0.000452101,-2.30629e-07,5.16199e-08,0.962135,0.000451795,-7.57696e-08,-3.52595e-08,0.962587,0.000451538,-1.81548e-07,2.98133e-08,0.963038,0.000451264,-9.2108e-08,-2.43892e-08,0.963489,0.000451007,-1.65276e-07,8.13892e-09,0.96394,0.000450701,-1.40859e-07,-8.16647e-09,0.964391,0.000450394,-1.65358e-07,2.45269e-08,0.964841,0.000450137,-9.17775e-08,-3.03367e-08,0.965291,0.000449863,-1.82787e-07,3.7215e-08,0.965741,0.000449609,-7.11424e-08,-5.89188e-08,0.96619,0.00044929,-2.47899e-07,7.92509e-08,0.966639,0.000449032,-1.01462e-08,-7.92707e-08,0.967088,0.000448773,-2.47958e-07,5.90181e-08,0.967537,0.000448455,-7.0904e-08,-3.75925e-08,0.967985,0.0004482,-1.83681e-07,3.17471e-08,0.968433,0.000447928,-8.84401e-08,-2.97913e-08,0.968881,0.000447662,-1.77814e-07,2.78133e-08,0.969329,0.000447389,-9.4374e-08,-2.18572e-08,0.969776,0.000447135,-1.59946e-07,1.10134e-11,0.970223,0.000446815,-1.59913e-07,2.18132e-08,0.97067,0.000446561,-9.44732e-08,-2.76591e-08,0.971116,0.000446289,-1.7745e-07,2.92185e-08,0.971562,0.000446022,-8.97948e-08,-2.96104e-08,0.972008,0.000445753,-1.78626e-07,2.96185e-08,0.972454,0.000445485,-8.97706e-08,-2.92588e-08,0.972899,0.000445218,-1.77547e-07,2.78123e-08,0.973344,0.000444946,-9.41103e-08,-2.23856e-08,0.973789,0.000444691,-1.61267e-07,2.12559e-09,0.974233,0.000444374,-1.5489e-07,1.38833e-08,0.974678,0.000444106,-1.13241e-07,1.94591e-09,0.975122,0.000443886,-1.07403e-07,-2.16669e-08,0.975565,0.000443606,-1.72404e-07,2.5117e-08,0.976009,0.000443336,-9.70526e-08,-1.91963e-08,0.976452,0.000443085,-1.54642e-07,-7.93627e-09,0.976895,0.000442752,-1.7845e-07,5.09414e-08,0.977338,0.000442548,-2.56262e-08,-7.66201e-08,0.97778,0.000442266,-2.55486e-07,7.67249e-08,0.978222,0.000441986,-2.53118e-08,-5.14655e-08,0.978664,0.000441781,-1.79708e-07,9.92773e-09,0.979106,0.000441451,-1.49925e-07,1.17546e-08,0.979547,0.000441186,-1.14661e-07,2.65868e-09,0.979988,0.000440965,-1.06685e-07,-2.23893e-08,0.980429,0.000440684,-1.73853e-07,2.72939e-08,0.980869,0.000440419,-9.19716e-08,-2.71816e-08,0.98131,0.000440153,-1.73516e-07,2.18278e-08,0.98175,0.000439872,-1.08033e-07,-5.24833e-10,0.982189,0.000439654,-1.09607e-07,-1.97284e-08,0.982629,0.000439376,-1.68793e-07,1.98339e-08,0.983068,0.000439097,-1.09291e-07,-2.62901e-12,0.983507,0.000438879,-1.09299e-07,-1.98234e-08,0.983946,0.000438601,-1.68769e-07,1.96916e-08,0.984384,0.000438322,-1.09694e-07,6.6157e-10,0.984823,0.000438105,-1.0771e-07,-2.23379e-08,0.985261,0.000437823,-1.74723e-07,2.90855e-08,0.985698,0.00043756,-8.74669e-08,-3.43992e-08,0.986136,0.000437282,-1.90665e-07,4.89068e-08,0.986573,0.000437048,-4.39442e-08,-4.20188e-08,0.98701,0.000436834,-1.7e-07,-4.11073e-11,0.987446,0.000436494,-1.70124e-07,4.21832e-08,0.987883,0.00043628,-4.35742e-08,-4.94824e-08,0.988319,0.000436044,-1.92021e-07,3.6537e-08,0.988755,0.00043577,-8.24102e-08,-3.70611e-08,0.989191,0.000435494,-1.93593e-07,5.21026e-08,0.989626,0.000435263,-3.72855e-08,-5.21402e-08,0.990061,0.000435032,-1.93706e-07,3.7249e-08,0.990496,0.000434756,-8.19592e-08,-3.72512e-08,0.990931,0.000434481,-1.93713e-07,5.21511e-08,0.991365,0.00043425,-3.72595e-08,-5.21439e-08,0.991799,0.000434019,-1.93691e-07,3.72152e-08,0.992233,0.000433743,-8.20456e-08,-3.71123e-08,0.992667,0.000433468,-1.93382e-07,5.16292e-08,0.9931,0.000433236,-3.84947e-08,-5.01953e-08,0.993533,0.000433008,-1.89081e-07,2.99427e-08,0.993966,0.00043272,-9.92525e-08,-9.9708e-09,0.994399,0.000432491,-1.29165e-07,9.94051e-09,0.994831,0.000432263,-9.93434e-08,-2.97912e-08,0.995263,0.000431975,-1.88717e-07,4.96198e-08,0.995695,0.000431746,-3.98578e-08,-4.94785e-08,0.996127,0.000431518,-1.88293e-07,2.9085e-08,0.996558,0.000431229,-1.01038e-07,-7.25675e-09,0.996989,0.000431005,-1.22809e-07,-5.79945e-11,0.99742,0.000430759,-1.22983e-07,7.48873e-09,0.997851,0.000430536,-1.00516e-07,-2.98969e-08,0.998281,0.000430245,-1.90207e-07,5.24942e-08,0.998711,0.000430022,-3.27246e-08,-6.08706e-08,0.999141,0.000429774,-2.15336e-07,7.17788e-08,0.999571,0.000429392,0.,0.}; - - template - __device__ __forceinline__ void Lab2RGBConvert_f(const T& src, D& dst) - { - const float lThresh = 0.008856f * 903.3f; - const float fThresh = 7.787f * 0.008856f + 16.0f / 116.0f; - - float Y, fy; - - if (src.x <= lThresh) - { - Y = src.x / 903.3f; - fy = 7.787f * Y + 16.0f / 116.0f; - } - else - { - fy = (src.x + 16.0f) / 116.0f; - Y = fy * fy * fy; - } - - float X = src.y / 500.0f + fy; - float Z = fy - src.z / 200.0f; - - if (X <= fThresh) - X = (X - 16.0f / 116.0f) / 7.787f; - else - X = X * X * X; - - if (Z <= fThresh) - Z = (Z - 16.0f / 116.0f) / 7.787f; - else - Z = Z * Z * Z; - - float B = 0.052891f * X - 0.204043f * Y + 1.151152f * Z; - float G = -0.921235f * X + 1.875991f * Y + 0.045244f * Z; - float R = 3.079933f * X - 1.537150f * Y - 0.542782f * Z; - - if (srgb) - { - B = splineInterpolate(B * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); - G = splineInterpolate(G * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); - R = splineInterpolate(R * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); - } - - dst.x = blueIdx == 0 ? B : R; - dst.y = G; - dst.z = blueIdx == 0 ? R : B; - setAlpha(dst, ColorChannel::max()); - } - - template - __device__ __forceinline__ void Lab2RGBConvert_b(const T& src, D& dst) - { - float3 srcf, dstf; - - srcf.x = src.x * (100.f / 255.f); - srcf.y = src.y - 128; - srcf.z = src.z - 128; - - Lab2RGBConvert_f(srcf, dstf); - - dst.x = saturate_cast(dstf.x * 255.f); - dst.y = saturate_cast(dstf.y * 255.f); - dst.z = saturate_cast(dstf.z * 255.f); - setAlpha(dst, ColorChannel::max()); - } - - template struct Lab2RGB; - template - struct Lab2RGB - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - Lab2RGBConvert_b(src, dst); - - return dst; - } - __host__ __device__ __forceinline__ Lab2RGB() {} - __host__ __device__ __forceinline__ Lab2RGB(const Lab2RGB&) {} - }; - template - struct Lab2RGB - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - Lab2RGBConvert_f(src, dst); - - return dst; - } - __host__ __device__ __forceinline__ Lab2RGB() {} - __host__ __device__ __forceinline__ Lab2RGB(const Lab2RGB&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(name, scn, dcn, srgb, blueIdx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::Lab2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - -///////////////////////////////////// RGB <-> Luv ///////////////////////////////////// - - namespace color_detail - { - __constant__ float c_LabCbrtTab[] = {0.137931,0.0114066,0.,1.18859e-07,0.149338,0.011407,3.56578e-07,-5.79396e-07,0.160745,0.0114059,-1.38161e-06,2.16892e-06,0.172151,0.0114097,5.12516e-06,-8.0814e-06,0.183558,0.0113957,-1.9119e-05,3.01567e-05,0.194965,0.0114479,7.13509e-05,-0.000112545,0.206371,0.011253,-0.000266285,-0.000106493,0.217252,0.0104009,-0.000585765,7.32149e-05,0.22714,0.00944906,-0.00036612,1.21917e-05,0.236235,0.0087534,-0.000329545,2.01753e-05,0.244679,0.00815483,-0.000269019,1.24435e-05,0.252577,0.00765412,-0.000231689,1.05618e-05,0.26001,0.00722243,-0.000200003,8.26662e-06,0.267041,0.00684723,-0.000175203,6.76746e-06,0.27372,0.00651712,-0.000154901,5.61192e-06,0.280088,0.00622416,-0.000138065,4.67009e-06,0.286179,0.00596204,-0.000124055,3.99012e-06,0.292021,0.0057259,-0.000112085,3.36032e-06,0.297638,0.00551181,-0.000102004,2.95338e-06,0.30305,0.00531666,-9.31435e-05,2.52875e-06,0.308277,0.00513796,-8.55572e-05,2.22022e-06,0.313331,0.00497351,-7.88966e-05,1.97163e-06,0.318228,0.00482163,-7.29817e-05,1.7248e-06,0.322978,0.00468084,-6.78073e-05,1.55998e-06,0.327593,0.0045499,-6.31274e-05,1.36343e-06,0.332081,0.00442774,-5.90371e-05,1.27136e-06,0.336451,0.00431348,-5.5223e-05,1.09111e-06,0.34071,0.00420631,-5.19496e-05,1.0399e-06,0.344866,0.00410553,-4.88299e-05,9.18347e-07,0.348923,0.00401062,-4.60749e-05,8.29942e-07,0.352889,0.00392096,-4.35851e-05,7.98478e-07,0.356767,0.00383619,-4.11896e-05,6.84917e-07,0.360562,0.00375586,-3.91349e-05,6.63976e-07,0.36428,0.00367959,-3.7143e-05,5.93086e-07,0.367923,0.00360708,-3.53637e-05,5.6976e-07,0.371495,0.00353806,-3.36544e-05,4.95533e-07,0.375,0.00347224,-3.21678e-05,4.87951e-07,0.378441,0.00340937,-3.0704e-05,4.4349e-07,0.38182,0.00334929,-2.93735e-05,4.20297e-07,0.38514,0.0032918,-2.81126e-05,3.7872e-07,0.388404,0.00323671,-2.69764e-05,3.596e-07,0.391614,0.00318384,-2.58976e-05,3.5845e-07,0.394772,0.00313312,-2.48223e-05,2.92765e-07,0.397881,0.00308435,-2.3944e-05,3.18232e-07,0.400942,0.00303742,-2.29893e-05,2.82046e-07,0.403957,0.00299229,-2.21432e-05,2.52315e-07,0.406927,0.00294876,-2.13862e-05,2.58416e-07,0.409855,0.00290676,-2.0611e-05,2.33939e-07,0.412741,0.00286624,-1.99092e-05,2.36342e-07,0.415587,0.00282713,-1.92001e-05,1.916e-07,0.418396,0.00278931,-1.86253e-05,2.1915e-07,0.421167,0.00275271,-1.79679e-05,1.83498e-07,0.423901,0.00271733,-1.74174e-05,1.79343e-07,0.426602,0.00268303,-1.68794e-05,1.72013e-07,0.429268,0.00264979,-1.63633e-05,1.75686e-07,0.431901,0.00261759,-1.58363e-05,1.3852e-07,0.434503,0.00258633,-1.54207e-05,1.64304e-07,0.437074,0.00255598,-1.49278e-05,1.28136e-07,0.439616,0.00252651,-1.45434e-05,1.57618e-07,0.442128,0.0024979,-1.40705e-05,1.0566e-07,0.444612,0.00247007,-1.37535e-05,1.34998e-07,0.447068,0.00244297,-1.33485e-05,1.29207e-07,0.449498,0.00241666,-1.29609e-05,9.32347e-08,0.451902,0.00239102,-1.26812e-05,1.23703e-07,0.45428,0.00236603,-1.23101e-05,9.74072e-08,0.456634,0.0023417,-1.20179e-05,1.12518e-07,0.458964,0.002318,-1.16803e-05,7.83681e-08,0.46127,0.00229488,-1.14452e-05,1.10452e-07,0.463554,0.00227232,-1.11139e-05,7.58719e-08,0.465815,0.00225032,-1.08863e-05,9.2699e-08,0.468055,0.00222882,-1.06082e-05,8.97738e-08,0.470273,0.00220788,-1.03388e-05,5.4845e-08,0.47247,0.00218736,-1.01743e-05,1.0808e-07,0.474648,0.00216734,-9.85007e-06,4.9277e-08,0.476805,0.00214779,-9.70224e-06,8.22408e-08,0.478943,0.00212863,-9.45551e-06,6.87942e-08,0.481063,0.00210993,-9.24913e-06,5.98144e-08,0.483163,0.00209161,-9.06969e-06,7.93789e-08,0.485246,0.00207371,-8.83155e-06,3.99032e-08,0.487311,0.00205616,-8.71184e-06,8.88325e-08,0.489358,0.002039,-8.44534e-06,2.20004e-08,0.491389,0.00202218,-8.37934e-06,9.13872e-08,0.493403,0.0020057,-8.10518e-06,2.96829e-08,0.495401,0.00198957,-8.01613e-06,5.81028e-08,0.497382,0.00197372,-7.84183e-06,6.5731e-08,0.499348,0.00195823,-7.64463e-06,3.66019e-08,0.501299,0.00194305,-7.53483e-06,2.62811e-08,0.503234,0.00192806,-7.45598e-06,9.66907e-08,0.505155,0.00191344,-7.16591e-06,4.18928e-09,0.507061,0.00189912,-7.15334e-06,6.53665e-08,0.508953,0.00188501,-6.95724e-06,3.23686e-08,0.510831,0.00187119,-6.86014e-06,4.35774e-08,0.512696,0.0018576,-6.72941e-06,3.17406e-08,0.514547,0.00184424,-6.63418e-06,6.78785e-08,0.516384,0.00183117,-6.43055e-06,-5.23126e-09,0.518209,0.0018183,-6.44624e-06,7.22562e-08,0.520021,0.00180562,-6.22947e-06,1.42292e-08,0.52182,0.0017932,-6.18679e-06,4.9641e-08,0.523607,0.00178098,-6.03786e-06,2.56259e-08,0.525382,0.00176898,-5.96099e-06,2.66696e-08,0.527145,0.00175714,-5.88098e-06,4.65094e-08,0.528897,0.00174552,-5.74145e-06,2.57114e-08,0.530637,0.00173411,-5.66431e-06,2.94588e-08,0.532365,0.00172287,-5.57594e-06,3.52667e-08,0.534082,0.00171182,-5.47014e-06,8.28868e-09,0.535789,0.00170091,-5.44527e-06,5.07871e-08,0.537484,0.00169017,-5.29291e-06,2.69817e-08,0.539169,0.00167967,-5.21197e-06,2.01009e-08,0.540844,0.0016693,-5.15166e-06,1.18237e-08,0.542508,0.00165903,-5.11619e-06,5.18135e-08,0.544162,0.00164896,-4.96075e-06,1.9341e-08,0.545806,0.00163909,-4.90273e-06,-9.96867e-09,0.54744,0.00162926,-4.93263e-06,8.01382e-08,0.549064,0.00161963,-4.69222e-06,-1.25601e-08,0.550679,0.00161021,-4.7299e-06,2.97067e-08,0.552285,0.00160084,-4.64078e-06,1.29426e-08,0.553881,0.0015916,-4.60195e-06,3.77327e-08,0.555468,0.00158251,-4.48875e-06,1.49412e-08,0.557046,0.00157357,-4.44393e-06,2.17118e-08,0.558615,0.00156475,-4.3788e-06,1.74206e-08,0.560176,0.00155605,-4.32653e-06,2.78152e-08,0.561727,0.00154748,-4.24309e-06,-9.47239e-09,0.563271,0.00153896,-4.27151e-06,6.9679e-08,0.564805,0.00153063,-4.06247e-06,-3.08246e-08,0.566332,0.00152241,-4.15494e-06,5.36188e-08,0.56785,0.00151426,-3.99409e-06,-4.83594e-09,0.56936,0.00150626,-4.00859e-06,2.53293e-08,0.570863,0.00149832,-3.93261e-06,2.27286e-08,0.572357,0.00149052,-3.86442e-06,2.96541e-09,0.573844,0.0014828,-3.85552e-06,2.50147e-08,0.575323,0.00147516,-3.78048e-06,1.61842e-08,0.576794,0.00146765,-3.73193e-06,2.94582e-08,0.578258,0.00146028,-3.64355e-06,-1.48076e-08,0.579715,0.00145295,-3.68798e-06,2.97724e-08,0.581164,0.00144566,-3.59866e-06,1.49272e-08,0.582606,0.00143851,-3.55388e-06,2.97285e-08,0.584041,0.00143149,-3.46469e-06,-1.46323e-08,0.585469,0.00142451,-3.50859e-06,2.88004e-08,0.58689,0.00141758,-3.42219e-06,1.864e-08,0.588304,0.00141079,-3.36627e-06,1.58482e-08,0.589712,0.00140411,-3.31872e-06,-2.24279e-08,0.591112,0.00139741,-3.38601e-06,7.38639e-08,0.592507,0.00139085,-3.16441e-06,-3.46088e-08,0.593894,0.00138442,-3.26824e-06,4.96675e-09,0.595275,0.0013779,-3.25334e-06,7.4346e-08,0.59665,0.00137162,-3.0303e-06,-6.39319e-08,0.598019,0.00136536,-3.2221e-06,6.21725e-08,0.599381,0.00135911,-3.03558e-06,-5.94423e-09,0.600737,0.00135302,-3.05341e-06,2.12091e-08,0.602087,0.00134697,-2.98979e-06,-1.92876e-08,0.603431,0.00134094,-3.04765e-06,5.5941e-08,0.604769,0.00133501,-2.87983e-06,-2.56622e-08,0.606101,0.00132917,-2.95681e-06,4.67078e-08,0.607427,0.0013234,-2.81669e-06,-4.19592e-08,0.608748,0.00131764,-2.94257e-06,6.15243e-08,0.610062,0.00131194,-2.75799e-06,-2.53244e-08,0.611372,0.00130635,-2.83397e-06,3.97739e-08,0.612675,0.0013008,-2.71465e-06,-1.45618e-08,0.613973,0.00129533,-2.75833e-06,1.84733e-08,0.615266,0.00128986,-2.70291e-06,2.73606e-10,0.616553,0.00128446,-2.70209e-06,4.00367e-08,0.617835,0.00127918,-2.58198e-06,-4.12113e-08,0.619111,0.00127389,-2.70561e-06,6.52039e-08,0.620383,0.00126867,-2.51e-06,-4.07901e-08,0.621649,0.00126353,-2.63237e-06,3.83516e-08,0.62291,0.00125838,-2.51732e-06,6.59315e-09,0.624166,0.00125337,-2.49754e-06,-5.11939e-09,0.625416,0.00124836,-2.5129e-06,1.38846e-08,0.626662,0.00124337,-2.47124e-06,9.18514e-09,0.627903,0.00123846,-2.44369e-06,8.97952e-09,0.629139,0.0012336,-2.41675e-06,1.45012e-08,0.63037,0.00122881,-2.37325e-06,-7.37949e-09,0.631597,0.00122404,-2.39538e-06,1.50169e-08,0.632818,0.00121929,-2.35033e-06,6.91648e-09,0.634035,0.00121461,-2.32958e-06,1.69219e-08,0.635248,0.00121,-2.27882e-06,-1.49997e-08,0.636455,0.0012054,-2.32382e-06,4.30769e-08,0.637659,0.00120088,-2.19459e-06,-3.80986e-08,0.638857,0.00119638,-2.30888e-06,4.97134e-08,0.640051,0.00119191,-2.15974e-06,-4.15463e-08,0.641241,0.00118747,-2.28438e-06,5.68667e-08,0.642426,0.00118307,-2.11378e-06,-7.10641e-09,0.643607,0.00117882,-2.1351e-06,-2.8441e-08,0.644784,0.00117446,-2.22042e-06,6.12658e-08,0.645956,0.00117021,-2.03663e-06,-3.78083e-08,0.647124,0.00116602,-2.15005e-06,3.03627e-08,0.648288,0.00116181,-2.05896e-06,-2.40379e-08,0.649448,0.00115762,-2.13108e-06,6.57887e-08,0.650603,0.00115356,-1.93371e-06,-6.03028e-08,0.651755,0.00114951,-2.11462e-06,5.62134e-08,0.652902,0.00114545,-1.94598e-06,-4.53417e-08,0.654046,0.00114142,-2.082e-06,6.55489e-08,0.655185,0.00113745,-1.88536e-06,-3.80396e-08,0.656321,0.00113357,-1.99948e-06,2.70049e-08,0.657452,0.00112965,-1.91846e-06,-1.03755e-08,0.65858,0.00112578,-1.94959e-06,1.44973e-08,0.659704,0.00112192,-1.9061e-06,1.1991e-08,0.660824,0.00111815,-1.87012e-06,-2.85634e-09,0.66194,0.0011144,-1.87869e-06,-5.65782e-10,0.663053,0.00111064,-1.88039e-06,5.11947e-09,0.664162,0.0011069,-1.86503e-06,3.96924e-08,0.665267,0.00110328,-1.74595e-06,-4.46795e-08,0.666368,0.00109966,-1.87999e-06,1.98161e-08,0.667466,0.00109596,-1.82054e-06,2.502e-08,0.66856,0.00109239,-1.74548e-06,-6.86593e-10,0.669651,0.0010889,-1.74754e-06,-2.22739e-08,0.670738,0.00108534,-1.81437e-06,3.01776e-08,0.671821,0.0010818,-1.72383e-06,2.07732e-08,0.672902,0.00107841,-1.66151e-06,-5.36658e-08,0.673978,0.00107493,-1.82251e-06,7.46802e-08,0.675051,0.00107151,-1.59847e-06,-6.62411e-08,0.676121,0.00106811,-1.79719e-06,7.10748e-08,0.677188,0.00106473,-1.58397e-06,-3.92441e-08,0.678251,0.00106145,-1.7017e-06,2.62973e-08,0.679311,0.00105812,-1.62281e-06,-6.34035e-09,0.680367,0.00105486,-1.64183e-06,-9.36249e-10,0.68142,0.00105157,-1.64464e-06,1.00854e-08,0.68247,0.00104831,-1.61438e-06,2.01995e-08,0.683517,0.00104514,-1.55378e-06,-3.1279e-08,0.68456,0.00104194,-1.64762e-06,4.53114e-08,0.685601,0.00103878,-1.51169e-06,-3.07573e-08,0.686638,0.00103567,-1.60396e-06,1.81133e-08,0.687672,0.00103251,-1.54962e-06,1.79085e-08,0.688703,0.00102947,-1.49589e-06,-3.01428e-08,0.689731,0.00102639,-1.58632e-06,4.30583e-08,0.690756,0.00102334,-1.45715e-06,-2.28814e-08,0.691778,0.00102036,-1.52579e-06,-1.11373e-08,0.692797,0.00101727,-1.5592e-06,6.74305e-08,0.693812,0.00101436,-1.35691e-06,-7.97709e-08,0.694825,0.0010114,-1.59622e-06,7.28391e-08,0.695835,0.00100843,-1.37771e-06,-3.27715e-08,0.696842,0.00100558,-1.47602e-06,-1.35807e-09,0.697846,0.00100262,-1.48009e-06,3.82037e-08,0.698847,0.000999775,-1.36548e-06,-3.22474e-08,0.699846,0.000996948,-1.46223e-06,3.11809e-08,0.700841,0.000994117,-1.36868e-06,-3.28714e-08,0.701834,0.000991281,-1.4673e-06,4.07001e-08,0.702824,0.000988468,-1.3452e-06,-1.07197e-08,0.703811,0.000985746,-1.37736e-06,2.17866e-09,0.704795,0.000982998,-1.37082e-06,2.00521e-09,0.705777,0.000980262,-1.3648e-06,-1.01996e-08,0.706756,0.000977502,-1.3954e-06,3.87931e-08,0.707732,0.000974827,-1.27902e-06,-2.57632e-08,0.708706,0.000972192,-1.35631e-06,4.65513e-09,0.709676,0.000969493,-1.34235e-06,7.14257e-09,0.710645,0.00096683,-1.32092e-06,2.63791e-08,0.71161,0.000964267,-1.24178e-06,-5.30543e-08,0.712573,0.000961625,-1.40095e-06,6.66289e-08,0.713533,0.000959023,-1.20106e-06,-3.46474e-08,0.714491,0.000956517,-1.305e-06,1.23559e-08,0.715446,0.000953944,-1.26793e-06,-1.47763e-08,0.716399,0.000951364,-1.31226e-06,4.67494e-08,0.717349,0.000948879,-1.17201e-06,-5.3012e-08,0.718297,0.000946376,-1.33105e-06,4.60894e-08,0.719242,0.000943852,-1.19278e-06,-1.21366e-08,0.720185,0.00094143,-1.22919e-06,2.45673e-09,0.721125,0.000938979,-1.22182e-06,2.30966e-09,0.722063,0.000936543,-1.21489e-06,-1.16954e-08,0.722998,0.000934078,-1.24998e-06,4.44718e-08,0.723931,0.000931711,-1.11656e-06,-4.69823e-08,0.724861,0.000929337,-1.25751e-06,2.4248e-08,0.725789,0.000926895,-1.18477e-06,9.5949e-09,0.726715,0.000924554,-1.15598e-06,-3.02286e-09,0.727638,0.000922233,-1.16505e-06,2.49649e-09,0.72856,0.00091991,-1.15756e-06,-6.96321e-09,0.729478,0.000917575,-1.17845e-06,2.53564e-08,0.730395,0.000915294,-1.10238e-06,-3.48578e-08,0.731309,0.000912984,-1.20695e-06,5.44704e-08,0.732221,0.000910734,-1.04354e-06,-6.38144e-08,0.73313,0.000908455,-1.23499e-06,8.15781e-08,0.734038,0.00090623,-9.90253e-07,-8.3684e-08,0.734943,0.000903999,-1.2413e-06,7.43441e-08,0.735846,0.000901739,-1.01827e-06,-3.48787e-08,0.736746,0.000899598,-1.12291e-06,5.56596e-09,0.737645,0.000897369,-1.10621e-06,1.26148e-08,0.738541,0.000895194,-1.06837e-06,3.57935e-09,0.739435,0.000893068,-1.05763e-06,-2.69322e-08,0.740327,0.000890872,-1.13842e-06,4.45448e-08,0.741217,0.000888729,-1.00479e-06,-3.20376e-08,0.742105,0.000886623,-1.1009e-06,2.40011e-08,0.74299,0.000884493,-1.0289e-06,-4.36209e-09,0.743874,0.000882422,-1.04199e-06,-6.55268e-09,0.744755,0.000880319,-1.06164e-06,3.05728e-08,0.745634,0.000878287,-9.69926e-07,-5.61338e-08,0.746512,0.000876179,-1.13833e-06,7.4753e-08,0.747387,0.000874127,-9.14068e-07,-6.40644e-08,0.74826,0.000872106,-1.10626e-06,6.22955e-08,0.749131,0.000870081,-9.19375e-07,-6.59083e-08,0.75,0.000868044,-1.1171e-06,8.21284e-08,0.750867,0.000866056,-8.70714e-07,-8.37915e-08,0.751732,0.000864064,-1.12209e-06,7.42237e-08,0.752595,0.000862042,-8.99418e-07,-3.42894e-08,0.753456,0.00086014,-1.00229e-06,3.32955e-09,0.754315,0.000858146,-9.92297e-07,2.09712e-08,0.755173,0.000856224,-9.29384e-07,-2.76096e-08,0.756028,0.000854282,-1.01221e-06,2.98627e-08,0.756881,0.000852348,-9.22625e-07,-3.22365e-08,0.757733,0.000850406,-1.01933e-06,3.94786e-08,0.758582,0.000848485,-9.00898e-07,-6.46833e-09,0.75943,0.000846664,-9.20303e-07,-1.36052e-08,0.760275,0.000844783,-9.61119e-07,1.28447e-09,0.761119,0.000842864,-9.57266e-07,8.4674e-09,0.761961,0.000840975,-9.31864e-07,2.44506e-08,0.762801,0.000839185,-8.58512e-07,-4.6665e-08,0.763639,0.000837328,-9.98507e-07,4.30001e-08,0.764476,0.00083546,-8.69507e-07,-6.12609e-09,0.76531,0.000833703,-8.87885e-07,-1.84959e-08,0.766143,0.000831871,-9.43372e-07,2.05052e-08,0.766974,0.000830046,-8.81857e-07,-3.92026e-09,0.767803,0.000828271,-8.93618e-07,-4.82426e-09,0.768631,0.000826469,-9.0809e-07,2.32172e-08,0.769456,0.000824722,-8.38439e-07,-2.84401e-08,0.77028,0.00082296,-9.23759e-07,3.09386e-08,0.771102,0.000821205,-8.30943e-07,-3.57099e-08,0.771922,0.000819436,-9.38073e-07,5.22963e-08,0.772741,0.000817717,-7.81184e-07,-5.42658e-08,0.773558,0.000815992,-9.43981e-07,4.55579e-08,0.774373,0.000814241,-8.07308e-07,-8.75656e-09,0.775186,0.0008126,-8.33578e-07,-1.05315e-08,0.775998,0.000810901,-8.65172e-07,-8.72188e-09,0.776808,0.000809145,-8.91338e-07,4.54191e-08,0.777616,0.000807498,-7.5508e-07,-5.37454e-08,0.778423,0.000805827,-9.16317e-07,5.03532e-08,0.779228,0.000804145,-7.65257e-07,-2.84584e-08,0.780031,0.000802529,-8.50632e-07,3.87579e-09,0.780833,0.00080084,-8.39005e-07,1.29552e-08,0.781633,0.0007992,-8.00139e-07,3.90804e-09,0.782432,0.000797612,-7.88415e-07,-2.85874e-08,0.783228,0.000795949,-8.74177e-07,5.0837e-08,0.784023,0.000794353,-7.21666e-07,-5.55513e-08,0.784817,0.000792743,-8.8832e-07,5.21587e-08,0.785609,0.000791123,-7.31844e-07,-3.38744e-08,0.786399,0.000789558,-8.33467e-07,2.37342e-08,0.787188,0.000787962,-7.62264e-07,-1.45775e-09,0.787975,0.000786433,-7.66638e-07,-1.79034e-08,0.788761,0.000784846,-8.20348e-07,1.34665e-08,0.789545,0.000783246,-7.79948e-07,2.3642e-08,0.790327,0.000781757,-7.09022e-07,-4.84297e-08,0.791108,0.000780194,-8.54311e-07,5.08674e-08,0.791888,0.000778638,-7.01709e-07,-3.58303e-08,0.792666,0.000777127,-8.092e-07,3.28493e-08,0.793442,0.000775607,-7.10652e-07,-3.59624e-08,0.794217,0.000774078,-8.1854e-07,5.13959e-08,0.79499,0.000772595,-6.64352e-07,-5.04121e-08,0.795762,0.000771115,-8.15588e-07,3.10431e-08,0.796532,0.000769577,-7.22459e-07,-1.41557e-08,0.797301,0.00076809,-7.64926e-07,2.55795e-08,0.798069,0.000766636,-6.88187e-07,-2.85578e-08,0.798835,0.000765174,-7.73861e-07,2.90472e-08,0.799599,0.000763714,-6.86719e-07,-2.80262e-08,0.800362,0.000762256,-7.70798e-07,2.34531e-08,0.801123,0.000760785,-7.00438e-07,-6.18144e-09,0.801884,0.000759366,-7.18983e-07,1.27263e-09,0.802642,0.000757931,-7.15165e-07,1.09101e-09,0.803399,0.000756504,-7.11892e-07,-5.63675e-09,0.804155,0.000755064,-7.28802e-07,2.14559e-08,0.80491,0.00075367,-6.64434e-07,-2.05821e-08,0.805663,0.00075228,-7.26181e-07,1.26812e-09,0.806414,0.000750831,-7.22377e-07,1.55097e-08,0.807164,0.000749433,-6.75848e-07,-3.70216e-09,0.807913,0.00074807,-6.86954e-07,-7.0105e-10,0.80866,0.000746694,-6.89057e-07,6.5063e-09,0.809406,0.000745336,-6.69538e-07,-2.53242e-08,0.810151,0.000743921,-7.45511e-07,3.51858e-08,0.810894,0.000742535,-6.39953e-07,3.79034e-09,0.811636,0.000741267,-6.28582e-07,-5.03471e-08,0.812377,0.000739858,-7.79624e-07,7.83886e-08,0.813116,0.000738534,-5.44458e-07,-8.43935e-08,0.813854,0.000737192,-7.97638e-07,8.03714e-08,0.81459,0.000735838,-5.56524e-07,-5.82784e-08,0.815325,0.00073455,-7.31359e-07,3.35329e-08,0.816059,0.000733188,-6.3076e-07,-1.62486e-08,0.816792,0.000731878,-6.79506e-07,3.14614e-08,0.817523,0.000730613,-5.85122e-07,-4.99925e-08,0.818253,0.000729293,-7.35099e-07,4.92994e-08,0.818982,0.000727971,-5.87201e-07,-2.79959e-08,0.819709,0.000726712,-6.71189e-07,3.07959e-09,0.820435,0.000725379,-6.6195e-07,1.56777e-08,0.82116,0.000724102,-6.14917e-07,-6.18564e-09,0.821883,0.000722854,-6.33474e-07,9.06488e-09,0.822606,0.000721614,-6.06279e-07,-3.00739e-08,0.823327,0.000720311,-6.96501e-07,5.16262e-08,0.824046,0.000719073,-5.41623e-07,-5.72214e-08,0.824765,0.000717818,-7.13287e-07,5.80503e-08,0.825482,0.000716566,-5.39136e-07,-5.57703e-08,0.826198,0.00071532,-7.06447e-07,4.58215e-08,0.826912,0.000714045,-5.68983e-07,-8.30636e-09,0.827626,0.000712882,-5.93902e-07,-1.25961e-08,0.828338,0.000711656,-6.3169e-07,-9.13985e-10,0.829049,0.00071039,-6.34432e-07,1.62519e-08,0.829759,0.00070917,-5.85676e-07,-4.48904e-09,0.830468,0.000707985,-5.99143e-07,1.70418e-09,0.831175,0.000706792,-5.9403e-07,-2.32768e-09,0.831881,0.000705597,-6.01014e-07,7.60648e-09,0.832586,0.000704418,-5.78194e-07,-2.80982e-08,0.83329,0.000703177,-6.62489e-07,4.51817e-08,0.833993,0.000701988,-5.26944e-07,-3.34192e-08,0.834694,0.000700834,-6.27201e-07,2.88904e-08,0.835394,0.000699666,-5.4053e-07,-2.25378e-08,0.836093,0.000698517,-6.08143e-07,1.65589e-09,0.836791,0.000697306,-6.03176e-07,1.59142e-08,0.837488,0.000696147,-5.55433e-07,-5.70801e-09,0.838184,0.000695019,-5.72557e-07,6.91792e-09,0.838878,0.000693895,-5.51803e-07,-2.19637e-08,0.839571,0.000692725,-6.17694e-07,2.13321e-08,0.840263,0.000691554,-5.53698e-07,-3.75996e-09,0.840954,0.000690435,-5.64978e-07,-6.29219e-09,0.841644,0.000689287,-5.83855e-07,2.89287e-08,0.842333,0.000688206,-4.97068e-07,-4.98181e-08,0.843021,0.000687062,-6.46523e-07,5.11344e-08,0.843707,0.000685922,-4.9312e-07,-3.55102e-08,0.844393,0.00068483,-5.9965e-07,3.13019e-08,0.845077,0.000683724,-5.05745e-07,-3.00925e-08,0.84576,0.000682622,-5.96022e-07,2.94636e-08,0.846442,0.000681519,-5.07631e-07,-2.81572e-08,0.847123,0.000680419,-5.92103e-07,2.35606e-08,0.847803,0.000679306,-5.21421e-07,-6.48045e-09,0.848482,0.000678243,-5.40863e-07,2.36124e-09,0.849159,0.000677169,-5.33779e-07,-2.96461e-09,0.849836,0.000676092,-5.42673e-07,9.49728e-09,0.850512,0.000675035,-5.14181e-07,-3.50245e-08,0.851186,0.000673902,-6.19254e-07,7.09959e-08,0.851859,0.000672876,-4.06267e-07,-7.01453e-08,0.852532,0.000671853,-6.16703e-07,3.07714e-08,0.853203,0.000670712,-5.24388e-07,6.66423e-09,0.853873,0.000669684,-5.04396e-07,2.17629e-09,0.854542,0.000668681,-4.97867e-07,-1.53693e-08,0.855211,0.000667639,-5.43975e-07,-3.03752e-10,0.855878,0.000666551,-5.44886e-07,1.65844e-08,0.856544,0.000665511,-4.95133e-07,-6.42907e-09,0.857209,0.000664501,-5.1442e-07,9.13195e-09,0.857873,0.0006635,-4.87024e-07,-3.00987e-08,0.858536,0.000662435,-5.7732e-07,5.16584e-08,0.859198,0.000661436,-4.22345e-07,-5.73255e-08,0.859859,0.000660419,-5.94322e-07,5.84343e-08,0.860518,0.000659406,-4.19019e-07,-5.72022e-08,0.861177,0.000658396,-5.90626e-07,5.11653e-08,0.861835,0.000657368,-4.3713e-07,-2.82495e-08,0.862492,0.000656409,-5.21878e-07,2.22788e-09,0.863148,0.000655372,-5.15195e-07,1.9338e-08,0.863803,0.0006544,-4.5718e-07,-1.99754e-08,0.864457,0.000653425,-5.17107e-07,9.59024e-10,0.86511,0.000652394,-5.1423e-07,1.61393e-08,0.865762,0.000651414,-4.65812e-07,-5.91149e-09,0.866413,0.000650465,-4.83546e-07,7.50665e-09,0.867063,0.00064952,-4.61026e-07,-2.4115e-08,0.867712,0.000648526,-5.33371e-07,2.93486e-08,0.86836,0.000647547,-4.45325e-07,-3.36748e-08,0.869007,0.000646555,-5.4635e-07,4.57461e-08,0.869653,0.0006456,-4.09112e-07,-3.01002e-08,0.870298,0.000644691,-4.99412e-07,1.50501e-08,0.870942,0.000643738,-4.54262e-07,-3.01002e-08,0.871585,0.000642739,-5.44563e-07,4.57461e-08,0.872228,0.000641787,-4.07324e-07,-3.36748e-08,0.872869,0.000640871,-5.08349e-07,2.93486e-08,0.873509,0.000639943,-4.20303e-07,-2.4115e-08,0.874149,0.00063903,-4.92648e-07,7.50655e-09,0.874787,0.000638067,-4.70128e-07,-5.91126e-09,0.875425,0.000637109,-4.87862e-07,1.61385e-08,0.876062,0.000636182,-4.39447e-07,9.61961e-10,0.876697,0.000635306,-4.36561e-07,-1.99863e-08,0.877332,0.000634373,-4.9652e-07,1.93785e-08,0.877966,0.000633438,-4.38384e-07,2.07697e-09,0.878599,0.000632567,-4.32153e-07,-2.76864e-08,0.879231,0.00063162,-5.15212e-07,4.90641e-08,0.879862,0.000630737,-3.6802e-07,-4.93606e-08,0.880493,0.000629852,-5.16102e-07,2.9169e-08,0.881122,0.000628908,-4.28595e-07,-7.71083e-09,0.881751,0.000628027,-4.51727e-07,1.6744e-09,0.882378,0.000627129,-4.46704e-07,1.01317e-09,0.883005,0.000626239,-4.43665e-07,-5.72703e-09,0.883631,0.000625334,-4.60846e-07,2.1895e-08,0.884255,0.000624478,-3.95161e-07,-2.22481e-08,0.88488,0.000623621,-4.61905e-07,7.4928e-09,0.885503,0.00062272,-4.39427e-07,-7.72306e-09,0.886125,0.000621818,-4.62596e-07,2.33995e-08,0.886746,0.000620963,-3.92398e-07,-2.62704e-08,0.887367,0.000620099,-4.71209e-07,2.20775e-08,0.887987,0.000619223,-4.04976e-07,-2.43496e-09,0.888605,0.000618406,-4.12281e-07,-1.23377e-08,0.889223,0.000617544,-4.49294e-07,-7.81876e-09,0.88984,0.000616622,-4.72751e-07,4.36128e-08,0.890457,0.000615807,-3.41912e-07,-4.7423e-08,0.891072,0.000614981,-4.84181e-07,2.68698e-08,0.891687,0.000614093,-4.03572e-07,-4.51384e-10,0.8923,0.000613285,-4.04926e-07,-2.50643e-08,0.892913,0.0006124,-4.80119e-07,4.11038e-08,0.893525,0.000611563,-3.56808e-07,-2.01414e-08,0.894136,0.000610789,-4.17232e-07,-2.01426e-08,0.894747,0.000609894,-4.7766e-07,4.11073e-08,0.895356,0.000609062,-3.54338e-07,-2.50773e-08,0.895965,0.000608278,-4.2957e-07,-4.02954e-10,0.896573,0.000607418,-4.30779e-07,2.66891e-08,0.89718,0.000606636,-3.50711e-07,-4.67489e-08,0.897786,0.000605795,-4.90958e-07,4.10972e-08,0.898391,0.000604936,-3.67666e-07,1.56948e-09,0.898996,0.000604205,-3.62958e-07,-4.73751e-08,0.8996,0.000603337,-5.05083e-07,6.87214e-08,0.900202,0.000602533,-2.98919e-07,-4.86966e-08,0.900805,0.000601789,-4.45009e-07,6.85589e-09,0.901406,0.00060092,-4.24441e-07,2.1273e-08,0.902007,0.000600135,-3.60622e-07,-3.23434e-08,0.902606,0.000599317,-4.57652e-07,4.84959e-08,0.903205,0.000598547,-3.12164e-07,-4.24309e-08,0.903803,0.000597795,-4.39457e-07,2.01844e-09,0.904401,0.000596922,-4.33402e-07,3.43571e-08,0.904997,0.000596159,-3.30331e-07,-2.02374e-08,0.905593,0.000595437,-3.91043e-07,-1.30123e-08,0.906188,0.000594616,-4.3008e-07,1.26819e-08,0.906782,0.000593794,-3.92034e-07,2.18894e-08,0.907376,0.000593076,-3.26366e-07,-4.06349e-08,0.907968,0.000592301,-4.4827e-07,2.1441e-08,0.90856,0.000591469,-3.83947e-07,1.44754e-08,0.909151,0.000590744,-3.40521e-07,-1.97379e-08,0.909742,0.000590004,-3.99735e-07,4.87161e-09,0.910331,0.000589219,-3.8512e-07,2.51532e-10,0.91092,0.00058845,-3.84366e-07,-5.87776e-09,0.911508,0.000587663,-4.01999e-07,2.32595e-08,0.912096,0.000586929,-3.3222e-07,-2.75554e-08,0.912682,0.000586182,-4.14887e-07,2.73573e-08,0.913268,0.000585434,-3.32815e-07,-2.22692e-08,0.913853,0.000584702,-3.99622e-07,2.11486e-09,0.914437,0.000583909,-3.93278e-07,1.38098e-08,0.915021,0.000583164,-3.51848e-07,2.25042e-09,0.915604,0.000582467,-3.45097e-07,-2.28115e-08,0.916186,0.000581708,-4.13531e-07,2.93911e-08,0.916767,0.000580969,-3.25358e-07,-3.51481e-08,0.917348,0.000580213,-4.30803e-07,5.15967e-08,0.917928,0.000579506,-2.76012e-07,-5.20296e-08,0.918507,0.000578798,-4.32101e-07,3.73124e-08,0.919085,0.000578046,-3.20164e-07,-3.76154e-08,0.919663,0.000577293,-4.3301e-07,5.35447e-08,0.92024,0.000576587,-2.72376e-07,-5.7354e-08,0.920816,0.000575871,-4.44438e-07,5.66621e-08,0.921391,0.000575152,-2.74452e-07,-5.00851e-08,0.921966,0.000574453,-4.24707e-07,2.4469e-08,0.92254,0.000573677,-3.513e-07,1.18138e-08,0.923114,0.000573009,-3.15859e-07,-1.21195e-08,0.923686,0.000572341,-3.52217e-07,-2.29403e-08,0.924258,0.000571568,-4.21038e-07,4.4276e-08,0.924829,0.000570859,-2.8821e-07,-3.49546e-08,0.9254,0.000570178,-3.93074e-07,3.59377e-08,0.92597,0.000569499,-2.85261e-07,-4.91915e-08,0.926539,0.000568781,-4.32835e-07,4.16189e-08,0.927107,0.00056804,-3.07979e-07,1.92523e-09,0.927675,0.00056743,-3.02203e-07,-4.93198e-08,0.928242,0.000566678,-4.50162e-07,7.61447e-08,0.928809,0.000566006,-2.21728e-07,-7.6445e-08,0.929374,0.000565333,-4.51063e-07,5.08216e-08,0.929939,0.000564583,-2.98599e-07,-7.63212e-09,0.930503,0.000563963,-3.21495e-07,-2.02931e-08,0.931067,0.000563259,-3.82374e-07,2.92001e-08,0.93163,0.000562582,-2.94774e-07,-3.69025e-08,0.932192,0.000561882,-4.05482e-07,5.88053e-08,0.932754,0.000561247,-2.29066e-07,-7.91094e-08,0.933315,0.000560552,-4.66394e-07,7.88184e-08,0.933875,0.000559856,-2.29939e-07,-5.73501e-08,0.934434,0.000559224,-4.01989e-07,3.13727e-08,0.934993,0.000558514,-3.07871e-07,-8.53611e-09,0.935551,0.000557873,-3.33479e-07,2.77175e-09,0.936109,0.000557214,-3.25164e-07,-2.55091e-09,0.936666,0.000556556,-3.32817e-07,7.43188e-09,0.937222,0.000555913,-3.10521e-07,-2.71766e-08,0.937778,0.00055521,-3.92051e-07,4.167e-08,0.938333,0.000554551,-2.67041e-07,-2.02941e-08,0.938887,0.000553956,-3.27923e-07,-2.00984e-08,0.93944,0.00055324,-3.88218e-07,4.10828e-08,0.939993,0.000552587,-2.6497e-07,-2.50237e-08,0.940546,0.000551982,-3.40041e-07,-5.92583e-10,0.941097,0.0005513,-3.41819e-07,2.7394e-08,0.941648,0.000550698,-2.59637e-07,-4.93788e-08,0.942199,0.000550031,-4.07773e-07,5.09119e-08,0.942748,0.000549368,-2.55038e-07,-3.50595e-08,0.943297,0.000548753,-3.60216e-07,2.97214e-08,0.943846,0.000548122,-2.71052e-07,-2.42215e-08,0.944394,0.000547507,-3.43716e-07,7.55985e-09,0.944941,0.000546842,-3.21037e-07,-6.01796e-09,0.945487,0.000546182,-3.3909e-07,1.65119e-08,0.946033,0.000545553,-2.89555e-07,-4.2498e-10,0.946578,0.000544973,-2.9083e-07,-1.4812e-08,0.947123,0.000544347,-3.35266e-07,6.83068e-11,0.947667,0.000543676,-3.35061e-07,1.45388e-08,0.94821,0.00054305,-2.91444e-07,1.38123e-09,0.948753,0.000542471,-2.87301e-07,-2.00637e-08,0.949295,0.000541836,-3.47492e-07,1.92688e-08,0.949837,0.000541199,-2.89685e-07,2.59298e-09,0.950378,0.000540628,-2.81906e-07,-2.96407e-08,0.950918,0.000539975,-3.70829e-07,5.63652e-08,0.951458,0.000539402,-2.01733e-07,-7.66107e-08,0.951997,0.000538769,-4.31565e-07,7.12638e-08,0.952535,0.00053812,-2.17774e-07,-2.96305e-08,0.953073,0.000537595,-3.06665e-07,-1.23464e-08,0.95361,0.000536945,-3.43704e-07,1.94114e-08,0.954147,0.000536316,-2.8547e-07,-5.69451e-09,0.954683,0.000535728,-3.02554e-07,3.36666e-09,0.955219,0.000535133,-2.92454e-07,-7.77208e-09,0.955753,0.000534525,-3.1577e-07,2.77216e-08,0.956288,0.000533976,-2.32605e-07,-4.35097e-08,0.956821,0.00053338,-3.63134e-07,2.7108e-08,0.957354,0.000532735,-2.8181e-07,-5.31772e-09,0.957887,0.000532156,-2.97764e-07,-5.83718e-09,0.958419,0.000531543,-3.15275e-07,2.86664e-08,0.95895,0.000530998,-2.29276e-07,-4.9224e-08,0.959481,0.000530392,-3.76948e-07,4.90201e-08,0.960011,0.000529785,-2.29887e-07,-2.76471e-08,0.96054,0.000529243,-3.12829e-07,1.96385e-09,0.961069,0.000528623,-3.06937e-07,1.97917e-08,0.961598,0.000528068,-2.47562e-07,-2.15261e-08,0.962125,0.000527508,-3.1214e-07,6.70795e-09,0.962653,0.000526904,-2.92016e-07,-5.30573e-09,0.963179,0.000526304,-3.07934e-07,1.4515e-08,0.963705,0.000525732,-2.64389e-07,6.85048e-09,0.964231,0.000525224,-2.43837e-07,-4.19169e-08,0.964756,0.00052461,-3.69588e-07,4.1608e-08,0.96528,0.000523996,-2.44764e-07,-5.30598e-09,0.965804,0.000523491,-2.60682e-07,-2.03841e-08,0.966327,0.000522908,-3.21834e-07,2.72378e-08,0.966849,0.000522346,-2.40121e-07,-2.89625e-08,0.967371,0.000521779,-3.27008e-07,2.90075e-08,0.967893,0.000521212,-2.39986e-07,-2.74629e-08,0.968414,0.00052065,-3.22374e-07,2.12396e-08,0.968934,0.000520069,-2.58656e-07,2.10922e-09,0.969454,0.000519558,-2.52328e-07,-2.96765e-08,0.969973,0.000518964,-3.41357e-07,5.6992e-08,0.970492,0.000518452,-1.70382e-07,-7.90821e-08,0.97101,0.000517874,-4.07628e-07,8.05224e-08,0.971528,0.000517301,-1.66061e-07,-6.41937e-08,0.972045,0.000516776,-3.58642e-07,5.70429e-08,0.972561,0.00051623,-1.87513e-07,-4.47686e-08,0.973077,0.00051572,-3.21819e-07,2.82237e-09,0.973593,0.000515085,-3.13352e-07,3.34792e-08,0.974108,0.000514559,-2.12914e-07,-1.75298e-08,0.974622,0.000514081,-2.65503e-07,-2.29648e-08,0.975136,0.000513481,-3.34398e-07,4.97843e-08,0.975649,0.000512961,-1.85045e-07,-5.6963e-08,0.976162,0.00051242,-3.55934e-07,5.88585e-08,0.976674,0.000511885,-1.79359e-07,-5.92616e-08,0.977185,0.000511348,-3.57143e-07,5.89785e-08,0.977696,0.000510811,-1.80208e-07,-5.74433e-08,0.978207,0.000510278,-3.52538e-07,5.15854e-08,0.978717,0.000509728,-1.97781e-07,-2.9689e-08,0.979226,0.000509243,-2.86848e-07,7.56591e-09,0.979735,0.000508692,-2.64151e-07,-5.74649e-10,0.980244,0.000508162,-2.65875e-07,-5.26732e-09,0.980752,0.000507615,-2.81677e-07,2.16439e-08,0.981259,0.000507116,-2.16745e-07,-2.17037e-08,0.981766,0.000506618,-2.81856e-07,5.56636e-09,0.982272,0.000506071,-2.65157e-07,-5.61689e-10,0.982778,0.000505539,-2.66842e-07,-3.31963e-09,0.983283,0.000504995,-2.76801e-07,1.38402e-08,0.983788,0.000504483,-2.3528e-07,7.56339e-09,0.984292,0.000504035,-2.1259e-07,-4.40938e-08,0.984796,0.000503478,-3.44871e-07,4.96026e-08,0.985299,0.000502937,-1.96064e-07,-3.51071e-08,0.985802,0.000502439,-3.01385e-07,3.12212e-08,0.986304,0.00050193,-2.07721e-07,-3.0173e-08,0.986806,0.000501424,-2.9824e-07,2.9866e-08,0.987307,0.000500917,-2.08642e-07,-2.96865e-08,0.987808,0.000500411,-2.97702e-07,2.92753e-08,0.988308,0.000499903,-2.09876e-07,-2.78101e-08,0.988807,0.0004994,-2.93306e-07,2.23604e-08,0.989307,0.000498881,-2.26225e-07,-2.02681e-09,0.989805,0.000498422,-2.32305e-07,-1.42531e-08,0.990303,0.000497915,-2.75065e-07,-5.65232e-10,0.990801,0.000497363,-2.76761e-07,1.65141e-08,0.991298,0.000496859,-2.27218e-07,-5.88639e-09,0.991795,0.000496387,-2.44878e-07,7.0315e-09,0.992291,0.000495918,-2.23783e-07,-2.22396e-08,0.992787,0.000495404,-2.90502e-07,2.23224e-08,0.993282,0.00049489,-2.23535e-07,-7.44543e-09,0.993776,0.000494421,-2.45871e-07,7.45924e-09,0.994271,0.000493951,-2.23493e-07,-2.23915e-08,0.994764,0.000493437,-2.90668e-07,2.25021e-08,0.995257,0.000492923,-2.23161e-07,-8.01218e-09,0.99575,0.000492453,-2.47198e-07,9.54669e-09,0.996242,0.000491987,-2.18558e-07,-3.01746e-08,0.996734,0.000491459,-3.09082e-07,5.1547e-08,0.997225,0.000490996,-1.54441e-07,-5.68039e-08,0.997716,0.000490517,-3.24853e-07,5.64594e-08,0.998206,0.000490036,-1.55474e-07,-4.98245e-08,0.998696,0.000489576,-3.04948e-07,2.36292e-08,0.999186,0.000489037,-2.3406e-07,1.49121e-08,0.999674,0.000488613,-1.89324e-07,-2.3673e-08,1.00016,0.000488164,-2.60343e-07,2.01754e-08,1.00065,0.000487704,-1.99816e-07,-5.70288e-08,1.00114,0.000487133,-3.70903e-07,8.87303e-08,1.00162,0.000486657,-1.04712e-07,-5.94737e-08,1.00211,0.000486269,-2.83133e-07,2.99553e-08,1.0026,0.000485793,-1.93267e-07,-6.03474e-08,1.00308,0.000485225,-3.74309e-07,9.2225e-08,1.00357,0.000484754,-9.76345e-08,-7.0134e-08,1.00405,0.000484348,-3.08036e-07,6.91016e-08,1.00454,0.000483939,-1.00731e-07,-8.70633e-08,1.00502,0.000483476,-3.61921e-07,4.07328e-08,1.0055,0.000482875,-2.39723e-07,4.33413e-08,1.00599,0.000482525,-1.09699e-07,-9.48886e-08,1.00647,0.000482021,-3.94365e-07,9.77947e-08,1.00695,0.000481526,-1.00981e-07,-5.78713e-08,1.00743,0.00048115,-2.74595e-07,1.44814e-08,1.00791,0.000480645,-2.31151e-07,-5.42665e-11,1.00839,0.000480182,-2.31314e-07,-1.42643e-08,1.00887,0.000479677,-2.74106e-07,5.71115e-08,1.00935,0.0004793,-1.02772e-07,-9.49724e-08,1.00983,0.000478809,-3.87689e-07,8.43596e-08,1.01031,0.000478287,-1.3461e-07,-4.04755e-09,1.01079,0.000478006,-1.46753e-07,-6.81694e-08,1.01127,0.000477508,-3.51261e-07,3.83067e-08,1.01174,0.00047692,-2.36341e-07,3.41521e-08,1.01222,0.00047655,-1.33885e-07,-5.57058e-08,1.0127,0.000476115,-3.01002e-07,6.94616e-08,1.01317,0.000475721,-9.26174e-08,-1.02931e-07,1.01365,0.000475227,-4.01412e-07,1.03846e-07,1.01412,0.000474736,-8.98751e-08,-7.40321e-08,1.0146,0.000474334,-3.11971e-07,7.30735e-08,1.01507,0.00047393,-9.27508e-08,-9.90527e-08,1.01554,0.000473447,-3.89909e-07,8.47188e-08,1.01602,0.000472921,-1.35753e-07,-1.40381e-09,1.01649,0.000472645,-1.39964e-07,-7.91035e-08,1.01696,0.000472128,-3.77275e-07,7.93993e-08,1.01744,0.000471612,-1.39077e-07,-7.52607e-11,1.01791,0.000471334,-1.39302e-07,-7.90983e-08,1.01838,0.000470818,-3.76597e-07,7.80499e-08,1.01885,0.000470299,-1.42448e-07,5.31733e-09,1.01932,0.00047003,-1.26496e-07,-9.93193e-08,1.01979,0.000469479,-4.24453e-07,1.53541e-07,1.02026,0.00046909,3.617e-08,-1.57217e-07,1.02073,0.000468691,-4.35482e-07,1.177e-07,1.02119,0.000468173,-8.23808e-08,-7.51659e-08,1.02166,0.000467783,-3.07878e-07,6.37538e-08,1.02213,0.000467358,-1.16617e-07,-6.064e-08,1.0226,0.000466943,-2.98537e-07,5.9597e-08,1.02306,0.000466525,-1.19746e-07,-5.85386e-08,1.02353,0.00046611,-2.95362e-07,5.53482e-08,1.024,0.000465685,-1.29317e-07,-4.36449e-08,1.02446,0.000465296,-2.60252e-07,2.20268e-11,1.02493,0.000464775,-2.60186e-07,4.35568e-08,1.02539,0.000464386,-1.29516e-07,-5.50398e-08,1.02586,0.000463961,-2.94635e-07,5.73932e-08,1.02632,0.000463544,-1.22456e-07,-5.53236e-08,1.02678,0.000463133,-2.88426e-07,4.46921e-08,1.02725,0.000462691,-1.5435e-07,-4.23534e-09,1.02771,0.000462369,-1.67056e-07,-2.77507e-08,1.02817,0.000461952,-2.50308e-07,-3.97101e-09,1.02863,0.000461439,-2.62221e-07,4.36348e-08,1.02909,0.000461046,-1.31317e-07,-5.13589e-08,1.02955,0.000460629,-2.85394e-07,4.25913e-08,1.03001,0.000460186,-1.5762e-07,2.0285e-10,1.03047,0.000459871,-1.57011e-07,-4.34027e-08,1.03093,0.000459427,-2.87219e-07,5.41987e-08,1.03139,0.000459015,-1.24623e-07,-5.4183e-08,1.03185,0.000458604,-2.87172e-07,4.33239e-08,1.03231,0.000458159,-1.572e-07,9.65817e-11,1.03277,0.000457845,-1.56911e-07,-4.37103e-08,1.03323,0.0004574,-2.88041e-07,5.55351e-08,1.03368,0.000456991,-1.21436e-07,-5.9221e-08,1.03414,0.00045657,-2.99099e-07,6.21394e-08,1.0346,0.000456158,-1.1268e-07,-7.01275e-08,1.03505,0.000455723,-3.23063e-07,9.91614e-08,1.03551,0.000455374,-2.55788e-08,-8.80996e-08,1.03596,0.000455058,-2.89878e-07,1.48184e-08,1.03642,0.000454523,-2.45422e-07,2.88258e-08,1.03687,0.000454119,-1.58945e-07,-1.09125e-08,1.03733,0.000453768,-1.91682e-07,1.48241e-08,1.03778,0.000453429,-1.4721e-07,-4.83838e-08,1.03823,0.00045299,-2.92361e-07,5.95019e-08,1.03869,0.000452584,-1.13856e-07,-7.04146e-08,1.03914,0.000452145,-3.25099e-07,1.02947e-07,1.03959,0.000451803,-1.62583e-08,-1.02955e-07,1.04004,0.000451462,-3.25123e-07,7.04544e-08,1.04049,0.000451023,-1.1376e-07,-5.96534e-08,1.04094,0.000450616,-2.9272e-07,4.89499e-08,1.04139,0.000450178,-1.45871e-07,-1.69369e-08,1.04184,0.000449835,-1.96681e-07,1.87977e-08,1.04229,0.000449498,-1.40288e-07,-5.82539e-08,1.04274,0.000449043,-3.1505e-07,9.50087e-08,1.04319,0.000448698,-3.00238e-08,-8.33623e-08,1.04364,0.000448388,-2.80111e-07,2.20363e-11,1.04409,0.000447828,-2.80045e-07,8.32742e-08,1.04454,0.000447517,-3.02221e-08,-9.47002e-08,1.04498,0.000447173,-3.14323e-07,5.7108e-08,1.04543,0.000446716,-1.42999e-07,-1.45225e-08,1.04588,0.000446386,-1.86566e-07,9.82022e-10,1.04632,0.000446016,-1.8362e-07,1.05944e-08,1.04677,0.00044568,-1.51837e-07,-4.33597e-08,1.04721,0.000445247,-2.81916e-07,4.36352e-08,1.04766,0.000444814,-1.51011e-07,-1.19717e-08,1.0481,0.000444476,-1.86926e-07,4.25158e-09,1.04855,0.000444115,-1.74171e-07,-5.03461e-09,1.04899,0.000443751,-1.89275e-07,1.58868e-08,1.04944,0.00044342,-1.41614e-07,-5.85127e-08,1.04988,0.000442961,-3.17152e-07,9.89548e-08,1.05032,0.000442624,-2.0288e-08,-9.88878e-08,1.05076,0.000442287,-3.16951e-07,5.81779e-08,1.05121,0.000441827,-1.42418e-07,-1.46144e-08,1.05165,0.000441499,-1.86261e-07,2.79892e-10,1.05209,0.000441127,-1.85421e-07,1.34949e-08,1.05253,0.000440797,-1.44937e-07,-5.42594e-08,1.05297,0.000440344,-3.07715e-07,8.43335e-08,1.05341,0.000439982,-5.47146e-08,-4.46558e-08,1.05385,0.000439738,-1.88682e-07,-2.49193e-08,1.05429,0.000439286,-2.6344e-07,2.5124e-08,1.05473,0.000438835,-1.88068e-07,4.36328e-08,1.05517,0.000438589,-5.71699e-08,-8.04459e-08,1.05561,0.000438234,-2.98508e-07,3.97324e-08,1.05605,0.000437756,-1.79311e-07,4.07258e-08,1.05648,0.000437519,-5.71332e-08,-8.34263e-08,1.05692,0.000437155,-3.07412e-07,5.45608e-08,1.05736,0.000436704,-1.4373e-07,-1.56078e-08,1.05779,0.000436369,-1.90553e-07,7.87043e-09,1.05823,0.000436012,-1.66942e-07,-1.58739e-08,1.05867,0.00043563,-2.14563e-07,5.56251e-08,1.0591,0.000435368,-4.76881e-08,-8.74172e-08,1.05954,0.000435011,-3.0994e-07,5.56251e-08,1.05997,0.000434558,-1.43064e-07,-1.58739e-08,1.06041,0.000434224,-1.90686e-07,7.87042e-09,1.06084,0.000433866,-1.67075e-07,-1.56078e-08,1.06127,0.000433485,-2.13898e-07,5.45609e-08,1.06171,0.000433221,-5.02157e-08,-8.34263e-08,1.06214,0.00043287,-3.00495e-07,4.07258e-08,1.06257,0.000432391,-1.78317e-07,3.97325e-08,1.063,0.000432154,-5.91198e-08,-8.04464e-08,1.06344,0.000431794,-3.00459e-07,4.36347e-08,1.06387,0.000431324,-1.69555e-07,2.5117e-08,1.0643,0.000431061,-9.42041e-08,-2.48934e-08,1.06473,0.000430798,-1.68884e-07,-4.47527e-08,1.06516,0.000430326,-3.03142e-07,8.46951e-08,1.06559,0.000429973,-4.90573e-08,-5.56089e-08,1.06602,0.000429708,-2.15884e-07,1.85314e-08,1.06645,0.000429332,-1.6029e-07,-1.85166e-08,1.06688,0.000428956,-2.1584e-07,5.5535e-08,1.06731,0.000428691,-4.92347e-08,-8.44142e-08,1.06774,0.000428339,-3.02477e-07,4.37032e-08,1.06816,0.000427865,-1.71368e-07,2.88107e-08,1.06859,0.000427609,-8.49356e-08,-3.97367e-08,1.06902,0.00042732,-2.04146e-07,1.09267e-08,1.06945,0.000426945,-1.71365e-07,-3.97023e-09,1.06987,0.00042659,-1.83276e-07,4.9542e-09,1.0703,0.000426238,-1.68414e-07,-1.58466e-08,1.07073,0.000425854,-2.15953e-07,5.84321e-08,1.07115,0.000425597,-4.0657e-08,-9.86725e-08,1.07158,0.00042522,-3.36674e-07,9.78392e-08,1.072,0.00042484,-4.31568e-08,-5.42658e-08,1.07243,0.000424591,-2.05954e-07,1.45377e-11,1.07285,0.000424179,-2.0591e-07,5.42076e-08,1.07328,0.00042393,-4.32877e-08,-9.76357e-08,1.0737,0.00042355,-3.36195e-07,9.79165e-08,1.07412,0.000423172,-4.24451e-08,-5.56118e-08,1.07455,0.00042292,-2.09281e-07,5.32143e-09,1.07497,0.000422518,-1.93316e-07,3.43261e-08,1.07539,0.000422234,-9.0338e-08,-2.34165e-08,1.07581,0.000421983,-1.60588e-07,-5.98692e-08,1.07623,0.000421482,-3.40195e-07,1.43684e-07,1.07666,0.000421233,9.08574e-08,-1.5724e-07,1.07708,0.000420943,-3.80862e-07,1.27647e-07,1.0775,0.000420564,2.0791e-09,-1.1493e-07,1.07792,0.000420223,-3.4271e-07,9.36534e-08,1.07834,0.000419819,-6.17499e-08,-2.12653e-08,1.07876,0.000419632,-1.25546e-07,-8.59219e-09,1.07918,0.000419355,-1.51322e-07,-6.35752e-08,1.0796,0.000418861,-3.42048e-07,1.43684e-07,1.08002,0.000418608,8.90034e-08,-1.53532e-07,1.08043,0.000418326,-3.71593e-07,1.12817e-07,1.08085,0.000417921,-3.31414e-08,-5.93184e-08,1.08127,0.000417677,-2.11097e-07,5.24697e-09,1.08169,0.00041727,-1.95356e-07,3.83305e-08,1.0821,0.000416995,-8.03642e-08,-3.93597e-08,1.08252,0.000416716,-1.98443e-07,-1.0094e-10,1.08294,0.000416319,-1.98746e-07,3.97635e-08,1.08335,0.00041604,-7.94557e-08,-3.97437e-08,1.08377,0.000415762,-1.98687e-07,1.94215e-12,1.08419,0.000415365,-1.98681e-07,3.97359e-08,1.0846,0.000415087,-7.94732e-08,-3.97362e-08,1.08502,0.000414809,-1.98682e-07,-4.31063e-13,1.08543,0.000414411,-1.98683e-07,3.97379e-08,1.08584,0.000414133,-7.94694e-08,-3.97418e-08,1.08626,0.000413855,-1.98695e-07,2.00563e-11,1.08667,0.000413458,-1.98635e-07,3.96616e-08,1.08709,0.000413179,-7.965e-08,-3.9457e-08,1.0875,0.000412902,-1.98021e-07,-1.04281e-09,1.08791,0.000412502,-2.01149e-07,4.36282e-08,1.08832,0.000412231,-7.02648e-08,-5.42608e-08,1.08874,0.000411928,-2.33047e-07,5.42057e-08,1.08915,0.000411624,-7.04301e-08,-4.33527e-08,1.08956,0.000411353,-2.00488e-07,-4.07378e-12,1.08997,0.000410952,-2.005e-07,4.3369e-08,1.09038,0.000410681,-7.03934e-08,-5.42627e-08,1.09079,0.000410378,-2.33182e-07,5.44726e-08,1.0912,0.000410075,-6.97637e-08,-4.44186e-08,1.09161,0.000409802,-2.03019e-07,3.99235e-09,1.09202,0.000409408,-1.91042e-07,2.84491e-08,1.09243,0.000409111,-1.05695e-07,1.42043e-09,1.09284,0.000408904,-1.01434e-07,-3.41308e-08,1.09325,0.000408599,-2.03826e-07,1.58937e-08,1.09366,0.000408239,-1.56145e-07,-2.94438e-08,1.09406,0.000407838,-2.44476e-07,1.01881e-07,1.09447,0.000407655,6.11676e-08,-1.39663e-07,1.09488,0.000407358,-3.57822e-07,9.91432e-08,1.09529,0.00040694,-6.03921e-08,-1.84912e-08,1.09569,0.000406764,-1.15866e-07,-2.51785e-08,1.0961,0.000406457,-1.91401e-07,-4.03115e-12,1.09651,0.000406074,-1.91413e-07,2.51947e-08,1.09691,0.000405767,-1.15829e-07,1.84346e-08,1.09732,0.00040559,-6.05254e-08,-9.89332e-08,1.09772,0.000405172,-3.57325e-07,1.3888e-07,1.09813,0.000404874,5.93136e-08,-9.8957e-08,1.09853,0.000404696,-2.37557e-07,1.853e-08,1.09894,0.000404277,-1.81968e-07,2.48372e-08,1.09934,0.000403987,-1.07456e-07,1.33047e-09,1.09975,0.000403776,-1.03465e-07,-3.01591e-08,1.10015,0.000403479,-1.93942e-07,9.66054e-11,1.10055,0.000403091,-1.93652e-07,2.97727e-08,1.10096,0.000402793,-1.04334e-07,2.19273e-11,1.10136,0.000402585,-1.04268e-07,-2.98604e-08,1.10176,0.000402287,-1.93849e-07,2.10325e-10,1.10216,0.0004019,-1.93218e-07,2.90191e-08,1.10256,0.0004016,-1.06161e-07,2.92264e-09,1.10297,0.000401397,-9.73931e-08,-4.07096e-08,1.10337,0.00040108,-2.19522e-07,4.07067e-08,1.10377,0.000400763,-9.7402e-08,-2.90783e-09,1.10417,0.000400559,-1.06126e-07,-2.90754e-08,1.10457,0.00040026,-1.93352e-07,9.00021e-14,1.10497,0.000399873,-1.93351e-07,2.9075e-08,1.10537,0.000399574,-1.06126e-07,2.90902e-09,1.10577,0.00039937,-9.73992e-08,-4.07111e-08,1.10617,0.000399053,-2.19533e-07,4.07262e-08,1.10657,0.000398736,-9.73541e-08,-2.98424e-09,1.10697,0.000398533,-1.06307e-07,-2.87892e-08,1.10736,0.000398234,-1.92674e-07,-1.06824e-09,1.10776,0.000397845,-1.95879e-07,3.30622e-08,1.10816,0.000397552,-9.66926e-08,-1.19712e-08,1.10856,0.000397323,-1.32606e-07,1.48225e-08,1.10895,0.000397102,-8.81387e-08,-4.73187e-08,1.10935,0.000396784,-2.30095e-07,5.52429e-08,1.10975,0.00039649,-6.4366e-08,-5.44437e-08,1.11014,0.000396198,-2.27697e-07,4.33226e-08,1.11054,0.000395872,-9.77293e-08,3.62656e-10,1.11094,0.000395678,-9.66414e-08,-4.47732e-08,1.11133,0.00039535,-2.30961e-07,5.95208e-08,1.11173,0.000395067,-5.23985e-08,-7.41008e-08,1.11212,0.00039474,-2.74701e-07,1.17673e-07,1.11252,0.000394543,7.83181e-08,-1.58172e-07,1.11291,0.000394225,-3.96199e-07,1.57389e-07,1.1133,0.000393905,7.59679e-08,-1.13756e-07,1.1137,0.000393716,-2.653e-07,5.92165e-08,1.11409,0.000393363,-8.76507e-08,-3.90074e-09,1.11449,0.000393176,-9.93529e-08,-4.36136e-08,1.11488,0.000392846,-2.30194e-07,5.91457e-08,1.11527,0.000392563,-5.27564e-08,-7.376e-08,1.11566,0.000392237,-2.74037e-07,1.16685e-07,1.11606,0.000392039,7.60189e-08,-1.54562e-07,1.11645,0.000391727,-3.87667e-07,1.43935e-07,1.11684,0.000391384,4.4137e-08,-6.35487e-08,1.11723,0.000391281,-1.46509e-07,-8.94896e-09,1.11762,0.000390961,-1.73356e-07,-1.98647e-08,1.11801,0.000390555,-2.3295e-07,8.8408e-08,1.1184,0.000390354,3.22736e-08,-9.53486e-08,1.11879,0.000390133,-2.53772e-07,5.45677e-08,1.11918,0.000389789,-9.0069e-08,-3.71296e-09,1.11957,0.000389598,-1.01208e-07,-3.97159e-08,1.11996,0.000389276,-2.20355e-07,4.33671e-08,1.12035,0.000388966,-9.02542e-08,-1.45431e-08,1.12074,0.000388741,-1.33883e-07,1.48052e-08,1.12113,0.000388518,-8.94678e-08,-4.46778e-08,1.12152,0.000388205,-2.23501e-07,4.46966e-08,1.12191,0.000387892,-8.94114e-08,-1.48992e-08,1.12229,0.000387669,-1.34109e-07,1.49003e-08,1.12268,0.000387445,-8.94082e-08,-4.47019e-08,1.12307,0.000387132,-2.23514e-07,4.4698e-08,1.12345,0.000386819,-8.942e-08,-1.48806e-08,1.12384,0.000386596,-1.34062e-07,1.48245e-08,1.12423,0.000386372,-8.95885e-08,-4.44172e-08,1.12461,0.00038606,-2.2284e-07,4.36351e-08,1.125,0.000385745,-9.19348e-08,-1.09139e-08,1.12539,0.000385528,-1.24677e-07,2.05584e-11,1.12577,0.000385279,-1.24615e-07,1.08317e-08,1.12616,0.000385062,-9.21198e-08,-4.33473e-08,1.12654,0.000384748,-2.22162e-07,4.33481e-08,1.12693,0.000384434,-9.21174e-08,-1.08356e-08,1.12731,0.000384217,-1.24624e-07,-5.50907e-12,1.12769,0.000383968,-1.24641e-07,1.08577e-08,1.12808,0.000383751,-9.20679e-08,-4.34252e-08,1.12846,0.000383437,-2.22343e-07,4.36337e-08,1.12884,0.000383123,-9.14422e-08,-1.19005e-08,1.12923,0.000382904,-1.27144e-07,3.96813e-09,1.12961,0.000382662,-1.15239e-07,-3.97207e-09,1.12999,0.000382419,-1.27155e-07,1.19201e-08,1.13038,0.000382201,-9.1395e-08,-4.37085e-08,1.13076,0.000381887,-2.2252e-07,4.37046e-08,1.13114,0.000381573,-9.14068e-08,-1.19005e-08,1.13152,0.000381355,-1.27108e-07,3.89734e-09,1.1319,0.000381112,-1.15416e-07,-3.68887e-09,1.13228,0.00038087,-1.26483e-07,1.08582e-08,1.13266,0.00038065,-9.39083e-08,-3.97438e-08,1.13304,0.000380343,-2.1314e-07,2.89076e-08,1.13342,0.000380003,-1.26417e-07,4.33225e-08,1.1338,0.00037988,3.55072e-09,-8.29883e-08,1.13418,0.000379638,-2.45414e-07,5.0212e-08,1.13456,0.000379298,-9.47781e-08,1.34964e-09,1.13494,0.000379113,-9.07292e-08,-5.56105e-08,1.13532,0.000378764,-2.57561e-07,1.01883e-07,1.1357,0.000378555,4.80889e-08,-1.13504e-07,1.13608,0.000378311,-2.92423e-07,1.13713e-07,1.13646,0.000378067,4.87176e-08,-1.02931e-07,1.13683,0.000377856,-2.60076e-07,5.95923e-08,1.13721,0.000377514,-8.12988e-08,-1.62288e-08,1.13759,0.000377303,-1.29985e-07,5.32278e-09,1.13797,0.000377059,-1.14017e-07,-5.06237e-09,1.13834,0.000376816,-1.29204e-07,1.49267e-08,1.13872,0.000376602,-8.44237e-08,-5.46444e-08,1.1391,0.000376269,-2.48357e-07,8.44417e-08,1.13947,0.000376026,4.96815e-09,-4.47039e-08,1.13985,0.000375902,-1.29143e-07,-2.48355e-08,1.14023,0.000375569,-2.0365e-07,2.48368e-08,1.1406,0.000375236,-1.2914e-07,4.46977e-08,1.14098,0.000375112,4.95341e-09,-8.44184e-08,1.14135,0.000374869,-2.48302e-07,5.45572e-08,1.14173,0.000374536,-8.463e-08,-1.46013e-08,1.1421,0.000374323,-1.28434e-07,3.8478e-09,1.14247,0.000374077,-1.1689e-07,-7.89941e-10,1.14285,0.000373841,-1.1926e-07,-6.88042e-10,1.14322,0.0003736,-1.21324e-07,3.54213e-09,1.1436,0.000373368,-1.10698e-07,-1.34805e-08,1.14397,0.000373107,-1.51139e-07,5.03798e-08,1.14434,0.000372767,0.,0.}; - - template - __device__ __forceinline__ void RGB2LuvConvert_f(const T& src, D& dst) - { - const float _d = 1.f / (0.950456f + 15 + 1.088754f * 3); - const float _un = 13 * (4 * 0.950456f * _d); - const float _vn = 13 * (9 * _d); - - float B = blueIdx == 0 ? src.x : src.z; - float G = src.y; - float R = blueIdx == 0 ? src.z : src.x; - - if (srgb) - { - B = splineInterpolate(B * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); - G = splineInterpolate(G * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); - R = splineInterpolate(R * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); - } - - float X = R * 0.412453f + G * 0.357580f + B * 0.180423f; - float Y = R * 0.212671f + G * 0.715160f + B * 0.072169f; - float Z = R * 0.019334f + G * 0.119193f + B * 0.950227f; - - float L = splineInterpolate(Y * (LAB_CBRT_TAB_SIZE / 1.5f), c_LabCbrtTab, LAB_CBRT_TAB_SIZE); - L = 116.f * L - 16.f; - - const float d = (4 * 13) / ::fmaxf(X + 15 * Y + 3 * Z, numeric_limits::epsilon()); - float u = L * (X * d - _un); - float v = L * ((9 * 0.25f) * Y * d - _vn); - - dst.x = L; - dst.y = u; - dst.z = v; - } - - template - __device__ __forceinline__ void RGB2LuvConvert_b(const T& src, D& dst) - { - float3 srcf, dstf; - - srcf.x = src.x * (1.f / 255.f); - srcf.y = src.y * (1.f / 255.f); - srcf.z = src.z * (1.f / 255.f); - - RGB2LuvConvert_f(srcf, dstf); - - dst.x = saturate_cast(dstf.x * 2.55f); - dst.y = saturate_cast(dstf.y * 0.72033898305084743f + 96.525423728813564f); - dst.z = saturate_cast(dstf.z * 0.9732824427480916f + 136.259541984732824f); - } - - template struct RGB2Luv; - template - struct RGB2Luv - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - RGB2LuvConvert_b(src, dst); - - return dst; - } - __host__ __device__ __forceinline__ RGB2Luv() {} - __host__ __device__ __forceinline__ RGB2Luv(const RGB2Luv&) {} - }; - template - struct RGB2Luv - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - RGB2LuvConvert_f(src, dst); - - return dst; - } - __host__ __device__ __forceinline__ RGB2Luv() {} - __host__ __device__ __forceinline__ RGB2Luv(const RGB2Luv&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(name, scn, dcn, srgb, blueIdx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2Luv functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - - namespace color_detail - { - template - __device__ __forceinline__ void Luv2RGBConvert_f(const T& src, D& dst) - { - const float _d = 1.f / (0.950456f + 15 + 1.088754f * 3); - const float _un = 4 * 0.950456f * _d; - const float _vn = 9 * _d; - - float L = src.x; - float u = src.y; - float v = src.z; - - float Y = (L + 16.f) * (1.f / 116.f); - Y = Y * Y * Y; - - float d = (1.f / 13.f) / L; - u = u * d + _un; - v = v * d + _vn; - - float iv = 1.f / v; - float X = 2.25f * u * Y * iv; - float Z = (12 - 3 * u - 20 * v) * Y * 0.25f * iv; - - float B = 0.055648f * X - 0.204043f * Y + 1.057311f * Z; - float G = -0.969256f * X + 1.875991f * Y + 0.041556f * Z; - float R = 3.240479f * X - 1.537150f * Y - 0.498535f * Z; - - if (srgb) - { - B = splineInterpolate(B * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); - G = splineInterpolate(G * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); - R = splineInterpolate(R * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); - } - - dst.x = blueIdx == 0 ? B : R; - dst.y = G; - dst.z = blueIdx == 0 ? R : B; - setAlpha(dst, ColorChannel::max()); - } - - template - __device__ __forceinline__ void Luv2RGBConvert_b(const T& src, D& dst) - { - float3 srcf, dstf; - - srcf.x = src.x * (100.f / 255.f); - srcf.y = src.y * 1.388235294117647f - 134.f; - srcf.z = src.z * 1.027450980392157f - 140.f; - - Luv2RGBConvert_f(srcf, dstf); - - dst.x = saturate_cast(dstf.x * 255.f); - dst.y = saturate_cast(dstf.y * 255.f); - dst.z = saturate_cast(dstf.z * 255.f); - setAlpha(dst, ColorChannel::max()); - } - - template struct Luv2RGB; - template - struct Luv2RGB - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - Luv2RGBConvert_b(src, dst); - - return dst; - } - __host__ __device__ __forceinline__ Luv2RGB() {} - __host__ __device__ __forceinline__ Luv2RGB(const Luv2RGB&) {} - }; - template - struct Luv2RGB - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - Luv2RGBConvert_f(src, dst); - - return dst; - } - __host__ __device__ __forceinline__ Luv2RGB() {} - __host__ __device__ __forceinline__ Luv2RGB(const Luv2RGB&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(name, scn, dcn, srgb, blueIdx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::Luv2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - - #undef CV_DESCALE - -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif // OPENCV_CUDA_COLOR_DETAIL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_COLOR_DETAIL_HPP +#define OPENCV_CUDA_COLOR_DETAIL_HPP + +#include "../common.hpp" +#include "../vec_traits.hpp" +#include "../saturate_cast.hpp" +#include "../limits.hpp" +#include "../functional.hpp" + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + #ifndef CV_DESCALE + #define CV_DESCALE(x, n) (((x) + (1 << ((n)-1))) >> (n)) + #endif + + namespace color_detail + { + template struct ColorChannel + { + typedef float worktype_f; + static __device__ __forceinline__ T max() { return numeric_limits::max(); } + static __device__ __forceinline__ T half() { return (T)(max()/2 + 1); } + }; + + template<> struct ColorChannel + { + typedef float worktype_f; + static __device__ __forceinline__ float max() { return 1.f; } + static __device__ __forceinline__ float half() { return 0.5f; } + }; + + template static __device__ __forceinline__ void setAlpha(typename TypeVec::vec_type& vec, T val) + { + } + + template static __device__ __forceinline__ void setAlpha(typename TypeVec::vec_type& vec, T val) + { + vec.w = val; + } + + template static __device__ __forceinline__ T getAlpha(const typename TypeVec::vec_type& vec) + { + return ColorChannel::max(); + } + + template static __device__ __forceinline__ T getAlpha(const typename TypeVec::vec_type& vec) + { + return vec.w; + } + + //constants for conversion from/to RGB and Gray, YUV, YCrCb according to BT.601 + constexpr float B2YF = 0.114f; + constexpr float G2YF = 0.587f; + constexpr float R2YF = 0.299f; + + //to YCbCr + constexpr float YCBF = 0.564f; // == 1/2/(1-B2YF) + constexpr float YCRF = 0.713f; // == 1/2/(1-R2YF) + const int YCBI = 9241; // == YCBF*16384 + const int YCRI = 11682; // == YCRF*16384 + //to YUV + constexpr float B2UF = 0.492f; + constexpr float R2VF = 0.877f; + const int B2UI = 8061; // == B2UF*16384 + const int R2VI = 14369; // == R2VF*16384 + //from YUV + constexpr float U2BF = 2.032f; + constexpr float U2GF = -0.395f; + constexpr float V2GF = -0.581f; + constexpr float V2RF = 1.140f; + const int U2BI = 33292; + const int U2GI = -6472; + const int V2GI = -9519; + const int V2RI = 18678; + //from YCrCb + constexpr float CB2BF = 1.773f; + constexpr float CB2GF = -0.344f; + constexpr float CR2GF = -0.714f; + constexpr float CR2RF = 1.403f; + const int CB2BI = 29049; + const int CB2GI = -5636; + const int CR2GI = -11698; + const int CR2RI = 22987; + + enum + { + yuv_shift = 14, + xyz_shift = 12, + gray_shift = 15, + R2Y = 4899, + G2Y = 9617, + B2Y = 1868, + RY15 = 9798, // == R2YF*32768 + 0.5 + GY15 = 19235, // == G2YF*32768 + 0.5 + BY15 = 3735, // == B2YF*32768 + 0.5 + BLOCK_SIZE = 256 + }; + } + +////////////////// Various 3/4-channel to 3/4-channel RGB transformations ///////////////// + + namespace color_detail + { + template struct RGB2RGB + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + dst.x = (&src.x)[bidx]; + dst.y = src.y; + dst.z = (&src.x)[bidx^2]; + setAlpha(dst, getAlpha(src)); + + return dst; + } + + __host__ __device__ __forceinline__ RGB2RGB() {} + __host__ __device__ __forceinline__ RGB2RGB(const RGB2RGB&) {} + }; + + template <> struct RGB2RGB : unary_function + { + __device__ uint operator()(uint src) const + { + uint dst = 0; + + dst |= (0xffu & (src >> 16)); + dst |= (0xffu & (src >> 8)) << 8; + dst |= (0xffu & (src)) << 16; + dst |= (0xffu & (src >> 24)) << 24; + + return dst; + } + + __host__ __device__ __forceinline__ RGB2RGB() {} + __host__ __device__ __forceinline__ RGB2RGB(const RGB2RGB&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(name, scn, dcn, bidx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + +/////////// Transforming 16-bit (565 or 555) RGB to/from 24/32-bit (888[8]) RGB ////////// + + namespace color_detail + { + template struct RGB2RGB5x5Converter; + template struct RGB2RGB5x5Converter<6, bidx> + { + static __device__ __forceinline__ ushort cvt(const uchar3& src) + { + return (ushort)(((&src.x)[bidx] >> 3) | ((src.y & ~3) << 3) | (((&src.x)[bidx^2] & ~7) << 8)); + } + + static __device__ __forceinline__ ushort cvt(uint src) + { + uint b = 0xffu & (src >> (bidx * 8)); + uint g = 0xffu & (src >> 8); + uint r = 0xffu & (src >> ((bidx ^ 2) * 8)); + return (ushort)((b >> 3) | ((g & ~3) << 3) | ((r & ~7) << 8)); + } + }; + + template struct RGB2RGB5x5Converter<5, bidx> + { + static __device__ __forceinline__ ushort cvt(const uchar3& src) + { + return (ushort)(((&src.x)[bidx] >> 3) | ((src.y & ~7) << 2) | (((&src.x)[bidx^2] & ~7) << 7)); + } + + static __device__ __forceinline__ ushort cvt(uint src) + { + uint b = 0xffu & (src >> (bidx * 8)); + uint g = 0xffu & (src >> 8); + uint r = 0xffu & (src >> ((bidx ^ 2) * 8)); + uint a = 0xffu & (src >> 24); + return (ushort)((b >> 3) | ((g & ~7) << 2) | ((r & ~7) << 7) | (a * 0x8000)); + } + }; + + template struct RGB2RGB5x5; + + template struct RGB2RGB5x5<3, bidx,green_bits> : unary_function + { + __device__ __forceinline__ ushort operator()(const uchar3& src) const + { + return RGB2RGB5x5Converter::cvt(src); + } + + __host__ __device__ __forceinline__ RGB2RGB5x5() {} + __host__ __device__ __forceinline__ RGB2RGB5x5(const RGB2RGB5x5&) {} + }; + + template struct RGB2RGB5x5<4, bidx,green_bits> : unary_function + { + __device__ __forceinline__ ushort operator()(uint src) const + { + return RGB2RGB5x5Converter::cvt(src); + } + + __host__ __device__ __forceinline__ RGB2RGB5x5() {} + __host__ __device__ __forceinline__ RGB2RGB5x5(const RGB2RGB5x5&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(name, scn, bidx, green_bits) \ + struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2RGB5x5 functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + + namespace color_detail + { + template struct RGB5x52RGBConverter; + + template struct RGB5x52RGBConverter<5, bidx> + { + static __device__ __forceinline__ void cvt(uint src, uchar3& dst) + { + (&dst.x)[bidx] = src << 3; + dst.y = (src >> 2) & ~7; + (&dst.x)[bidx ^ 2] = (src >> 7) & ~7; + } + + static __device__ __forceinline__ void cvt(uint src, uint& dst) + { + dst = 0; + + dst |= (0xffu & (src << 3)) << (bidx * 8); + dst |= (0xffu & ((src >> 2) & ~7)) << 8; + dst |= (0xffu & ((src >> 7) & ~7)) << ((bidx ^ 2) * 8); + dst |= ((src & 0x8000) * 0xffu) << 24; + } + }; + + template struct RGB5x52RGBConverter<6, bidx> + { + static __device__ __forceinline__ void cvt(uint src, uchar3& dst) + { + (&dst.x)[bidx] = src << 3; + dst.y = (src >> 3) & ~3; + (&dst.x)[bidx ^ 2] = (src >> 8) & ~7; + } + + static __device__ __forceinline__ void cvt(uint src, uint& dst) + { + dst = 0xffu << 24; + + dst |= (0xffu & (src << 3)) << (bidx * 8); + dst |= (0xffu &((src >> 3) & ~3)) << 8; + dst |= (0xffu & ((src >> 8) & ~7)) << ((bidx ^ 2) * 8); + } + }; + + template struct RGB5x52RGB; + + template struct RGB5x52RGB<3, bidx, green_bits> : unary_function + { + __device__ __forceinline__ uchar3 operator()(ushort src) const + { + uchar3 dst; + RGB5x52RGBConverter::cvt(src, dst); + return dst; + } + __host__ __device__ __forceinline__ RGB5x52RGB() {} + __host__ __device__ __forceinline__ RGB5x52RGB(const RGB5x52RGB&) {} + + }; + + template struct RGB5x52RGB<4, bidx, green_bits> : unary_function + { + __device__ __forceinline__ uint operator()(ushort src) const + { + uint dst; + RGB5x52RGBConverter::cvt(src, dst); + return dst; + } + __host__ __device__ __forceinline__ RGB5x52RGB() {} + __host__ __device__ __forceinline__ RGB5x52RGB(const RGB5x52RGB&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(name, dcn, bidx, green_bits) \ + struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB5x52RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + +///////////////////////////////// Grayscale to Color //////////////////////////////// + + namespace color_detail + { + template struct Gray2RGB : unary_function::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator()(T src) const + { + typename TypeVec::vec_type dst; + + dst.z = dst.y = dst.x = src; + setAlpha(dst, ColorChannel::max()); + + return dst; + } + __host__ __device__ __forceinline__ Gray2RGB() {} + __host__ __device__ __forceinline__ Gray2RGB(const Gray2RGB&) {} + }; + + template <> struct Gray2RGB : unary_function + { + __device__ __forceinline__ uint operator()(uint src) const + { + uint dst = 0xffu << 24; + + dst |= src; + dst |= src << 8; + dst |= src << 16; + + return dst; + } + __host__ __device__ __forceinline__ Gray2RGB() {} + __host__ __device__ __forceinline__ Gray2RGB(const Gray2RGB&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_GRAY2RGB_TRAITS(name, dcn) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::Gray2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + + namespace color_detail + { + template struct Gray2RGB5x5Converter; + template<> struct Gray2RGB5x5Converter<6> + { + static __device__ __forceinline__ ushort cvt(uint t) + { + return (ushort)((t >> 3) | ((t & ~3) << 3) | ((t & ~7) << 8)); + } + }; + + template<> struct Gray2RGB5x5Converter<5> + { + static __device__ __forceinline__ ushort cvt(uint t) + { + t >>= 3; + return (ushort)(t | (t << 5) | (t << 10)); + } + }; + + template struct Gray2RGB5x5 : unary_function + { + __device__ __forceinline__ ushort operator()(uint src) const + { + return Gray2RGB5x5Converter::cvt(src); + } + + __host__ __device__ __forceinline__ Gray2RGB5x5() {} + __host__ __device__ __forceinline__ Gray2RGB5x5(const Gray2RGB5x5&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_GRAY2RGB5x5_TRAITS(name, green_bits) \ + struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::Gray2RGB5x5 functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + +///////////////////////////////// Color to Grayscale //////////////////////////////// + + namespace color_detail + { + template struct RGB5x52GrayConverter; + template <> struct RGB5x52GrayConverter<6> + { + static __device__ __forceinline__ uchar cvt(uint t) + { + return (uchar)CV_DESCALE(((t << 3) & 0xf8) * BY15 + ((t >> 3) & 0xfc) * GY15 + ((t >> 8) & 0xf8) * RY15, gray_shift); + } + }; + + template <> struct RGB5x52GrayConverter<5> + { + static __device__ __forceinline__ uchar cvt(uint t) + { + return (uchar)CV_DESCALE(((t << 3) & 0xf8) * BY15 + ((t >> 2) & 0xf8) * GY15 + ((t >> 7) & 0xf8) * RY15, gray_shift); + } + }; + + template struct RGB5x52Gray : unary_function + { + __device__ __forceinline__ uchar operator()(uint src) const + { + return RGB5x52GrayConverter::cvt(src); + } + __host__ __device__ __forceinline__ RGB5x52Gray() {} + __host__ __device__ __forceinline__ RGB5x52Gray(const RGB5x52Gray&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_RGB5x52GRAY_TRAITS(name, green_bits) \ + struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB5x52Gray functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + + namespace color_detail + { + template static __device__ __forceinline__ T RGB2GrayConvert(const T* src) + { + return (T)CV_DESCALE((unsigned)(src[bidx] * BY15 + src[1] * GY15 + src[bidx^2] * RY15), gray_shift); + } + + template static __device__ __forceinline__ uchar RGB2GrayConvert(uint src) + { + uint b = 0xffu & (src >> (bidx * 8)); + uint g = 0xffu & (src >> 8); + uint r = 0xffu & (src >> ((bidx ^ 2) * 8)); + return CV_DESCALE((uint)(b * BY15 + g * GY15 + r * RY15), gray_shift); + } + + template static __device__ __forceinline__ float RGB2GrayConvert(const float* src) + { + return src[bidx] * B2YF + src[1] * G2YF + src[bidx^2] * R2YF; + } + + template struct RGB2Gray : unary_function::vec_type, T> + { + __device__ __forceinline__ T operator()(const typename TypeVec::vec_type& src) const + { + return RGB2GrayConvert(&src.x); + } + __host__ __device__ __forceinline__ RGB2Gray() {} + __host__ __device__ __forceinline__ RGB2Gray(const RGB2Gray&) {} + }; + + template struct RGB2Gray : unary_function + { + __device__ __forceinline__ uchar operator()(uint src) const + { + return RGB2GrayConvert(src); + } + __host__ __device__ __forceinline__ RGB2Gray() {} + __host__ __device__ __forceinline__ RGB2Gray(const RGB2Gray&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(name, scn, bidx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2Gray functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + +///////////////////////////////////// RGB <-> YUV ////////////////////////////////////// + + namespace color_detail + { + __constant__ float c_RGB2YUVCoeffs_f[5] = { B2YF, G2YF, R2YF, B2UF, R2VF }; + __constant__ int c_RGB2YUVCoeffs_i[5] = { B2Y, G2Y, R2Y, B2UI, R2VI }; + + template static __device__ void RGB2YUVConvert(const T* src, D& dst) + { + const int delta = ColorChannel::half() * (1 << yuv_shift); + + const int Y = CV_DESCALE(src[0] * c_RGB2YUVCoeffs_i[bidx^2] + src[1] * c_RGB2YUVCoeffs_i[1] + src[2] * c_RGB2YUVCoeffs_i[bidx], yuv_shift); + const int Cr = CV_DESCALE((src[bidx^2] - Y) * c_RGB2YUVCoeffs_i[3] + delta, yuv_shift); + const int Cb = CV_DESCALE((src[bidx] - Y) * c_RGB2YUVCoeffs_i[4] + delta, yuv_shift); + + dst.x = saturate_cast(Y); + dst.y = saturate_cast(Cr); + dst.z = saturate_cast(Cb); + } + + template static __device__ __forceinline__ void RGB2YUVConvert(const float* src, D& dst) + { + dst.x = src[0] * c_RGB2YUVCoeffs_f[bidx^2] + src[1] * c_RGB2YUVCoeffs_f[1] + src[2] * c_RGB2YUVCoeffs_f[bidx]; + dst.y = (src[bidx^2] - dst.x) * c_RGB2YUVCoeffs_f[3] + ColorChannel::half(); + dst.z = (src[bidx] - dst.x) * c_RGB2YUVCoeffs_f[4] + ColorChannel::half(); + } + + template struct RGB2YUV + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + RGB2YUVConvert(&src.x, dst); + return dst; + } + __host__ __device__ __forceinline__ RGB2YUV() {} + __host__ __device__ __forceinline__ RGB2YUV(const RGB2YUV&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(name, scn, dcn, bidx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2YUV functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + + namespace color_detail + { + __constant__ float c_YUV2RGBCoeffs_f[5] = { U2BF, U2GF, V2GF, V2RF }; + __constant__ int c_YUV2RGBCoeffs_i[5] = { U2BI, U2GI, V2GI, V2RI }; + + template static __device__ void YUV2RGBConvert(const T& src, D* dst) + { + const int b = src.x + CV_DESCALE((src.z - ColorChannel::half()) * c_YUV2RGBCoeffs_i[3], yuv_shift); + + const int g = src.x + CV_DESCALE((src.z - ColorChannel::half()) * c_YUV2RGBCoeffs_i[2] + + (src.y - ColorChannel::half()) * c_YUV2RGBCoeffs_i[1], yuv_shift); + + const int r = src.x + CV_DESCALE((src.y - ColorChannel::half()) * c_YUV2RGBCoeffs_i[0], yuv_shift); + + dst[bidx] = saturate_cast(b); + dst[1] = saturate_cast(g); + dst[bidx^2] = saturate_cast(r); + } + + template static __device__ uint YUV2RGBConvert(uint src) + { + const int x = 0xff & (src); + const int y = 0xff & (src >> 8); + const int z = 0xff & (src >> 16); + + const int b = x + CV_DESCALE((z - ColorChannel::half()) * c_YUV2RGBCoeffs_i[3], yuv_shift); + + const int g = x + CV_DESCALE((z - ColorChannel::half()) * c_YUV2RGBCoeffs_i[2] + + (y - ColorChannel::half()) * c_YUV2RGBCoeffs_i[1], yuv_shift); + + const int r = x + CV_DESCALE((y - ColorChannel::half()) * c_YUV2RGBCoeffs_i[0], yuv_shift); + + uint dst = 0xffu << 24; + + dst |= saturate_cast(b) << (bidx * 8); + dst |= saturate_cast(g) << 8; + dst |= saturate_cast(r) << ((bidx ^ 2) * 8); + + return dst; + } + + template static __device__ __forceinline__ void YUV2RGBConvert(const T& src, float* dst) + { + dst[bidx] = src.x + (src.z - ColorChannel::half()) * c_YUV2RGBCoeffs_f[3]; + + dst[1] = src.x + (src.z - ColorChannel::half()) * c_YUV2RGBCoeffs_f[2] + + (src.y - ColorChannel::half()) * c_YUV2RGBCoeffs_f[1]; + + dst[bidx^2] = src.x + (src.y - ColorChannel::half()) * c_YUV2RGBCoeffs_f[0]; + } + + template struct YUV2RGB + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + YUV2RGBConvert(src, &dst.x); + setAlpha(dst, ColorChannel::max()); + + return dst; + } + __host__ __device__ __forceinline__ YUV2RGB() {} + __host__ __device__ __forceinline__ YUV2RGB(const YUV2RGB&) {} + }; + + template struct YUV2RGB : unary_function + { + __device__ __forceinline__ uint operator ()(uint src) const + { + return YUV2RGBConvert(src); + } + __host__ __device__ __forceinline__ YUV2RGB() {} + __host__ __device__ __forceinline__ YUV2RGB(const YUV2RGB&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(name, scn, dcn, bidx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::YUV2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + +///////////////////////////////////// RGB <-> YCrCb ////////////////////////////////////// + + namespace color_detail + { + __constant__ float c_RGB2YCrCbCoeffs_f[5] = {R2YF, G2YF, B2YF, YCRF, YCBF}; + __constant__ int c_RGB2YCrCbCoeffs_i[5] = {R2Y, G2Y, B2Y, YCRI, YCBI}; + + template static __device__ void RGB2YCrCbConvert(const T* src, D& dst) + { + const int delta = ColorChannel::half() * (1 << yuv_shift); + + const int Y = CV_DESCALE(src[0] * c_RGB2YCrCbCoeffs_i[bidx^2] + src[1] * c_RGB2YCrCbCoeffs_i[1] + src[2] * c_RGB2YCrCbCoeffs_i[bidx], yuv_shift); + const int Cr = CV_DESCALE((src[bidx^2] - Y) * c_RGB2YCrCbCoeffs_i[3] + delta, yuv_shift); + const int Cb = CV_DESCALE((src[bidx] - Y) * c_RGB2YCrCbCoeffs_i[4] + delta, yuv_shift); + + dst.x = saturate_cast(Y); + dst.y = saturate_cast(Cr); + dst.z = saturate_cast(Cb); + } + + template static __device__ uint RGB2YCrCbConvert(uint src) + { + const int delta = ColorChannel::half() * (1 << yuv_shift); + + const int Y = CV_DESCALE((0xffu & src) * c_RGB2YCrCbCoeffs_i[bidx^2] + (0xffu & (src >> 8)) * c_RGB2YCrCbCoeffs_i[1] + (0xffu & (src >> 16)) * c_RGB2YCrCbCoeffs_i[bidx], yuv_shift); + const int Cr = CV_DESCALE(((0xffu & (src >> ((bidx ^ 2) * 8))) - Y) * c_RGB2YCrCbCoeffs_i[3] + delta, yuv_shift); + const int Cb = CV_DESCALE(((0xffu & (src >> (bidx * 8))) - Y) * c_RGB2YCrCbCoeffs_i[4] + delta, yuv_shift); + + uint dst = 0; + + dst |= saturate_cast(Y); + dst |= saturate_cast(Cr) << 8; + dst |= saturate_cast(Cb) << 16; + + return dst; + } + + template static __device__ __forceinline__ void RGB2YCrCbConvert(const float* src, D& dst) + { + dst.x = src[0] * c_RGB2YCrCbCoeffs_f[bidx^2] + src[1] * c_RGB2YCrCbCoeffs_f[1] + src[2] * c_RGB2YCrCbCoeffs_f[bidx]; + dst.y = (src[bidx^2] - dst.x) * c_RGB2YCrCbCoeffs_f[3] + ColorChannel::half(); + dst.z = (src[bidx] - dst.x) * c_RGB2YCrCbCoeffs_f[4] + ColorChannel::half(); + } + + template struct RGB2YCrCb + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + RGB2YCrCbConvert(&src.x, dst); + return dst; + } + __host__ __device__ __forceinline__ RGB2YCrCb() {} + __host__ __device__ __forceinline__ RGB2YCrCb(const RGB2YCrCb&) {} + }; + + template struct RGB2YCrCb : unary_function + { + __device__ __forceinline__ uint operator ()(uint src) const + { + return RGB2YCrCbConvert(src); + } + + __host__ __device__ __forceinline__ RGB2YCrCb() {} + __host__ __device__ __forceinline__ RGB2YCrCb(const RGB2YCrCb&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(name, scn, dcn, bidx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2YCrCb functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + + namespace color_detail + { + __constant__ float c_YCrCb2RGBCoeffs_f[5] = {CR2RF, CR2GF, CB2GF, CB2BF}; + __constant__ int c_YCrCb2RGBCoeffs_i[5] = {CR2RI, CR2GI, CB2GI, CB2BI}; + + template static __device__ void YCrCb2RGBConvert(const T& src, D* dst) + { + const int b = src.x + CV_DESCALE((src.z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[3], yuv_shift); + const int g = src.x + CV_DESCALE((src.z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[2] + (src.y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[1], yuv_shift); + const int r = src.x + CV_DESCALE((src.y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[0], yuv_shift); + + dst[bidx] = saturate_cast(b); + dst[1] = saturate_cast(g); + dst[bidx^2] = saturate_cast(r); + } + + template static __device__ uint YCrCb2RGBConvert(uint src) + { + const int x = 0xff & (src); + const int y = 0xff & (src >> 8); + const int z = 0xff & (src >> 16); + + const int b = x + CV_DESCALE((z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[3], yuv_shift); + const int g = x + CV_DESCALE((z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[2] + (y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[1], yuv_shift); + const int r = x + CV_DESCALE((y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[0], yuv_shift); + + uint dst = 0xffu << 24; + + dst |= saturate_cast(b) << (bidx * 8); + dst |= saturate_cast(g) << 8; + dst |= saturate_cast(r) << ((bidx ^ 2) * 8); + + return dst; + } + + template __device__ __forceinline__ void YCrCb2RGBConvert(const T& src, float* dst) + { + dst[bidx] = src.x + (src.z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_f[3]; + dst[1] = src.x + (src.z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_f[2] + (src.y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_f[1]; + dst[bidx^2] = src.x + (src.y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_f[0]; + } + + template struct YCrCb2RGB + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + YCrCb2RGBConvert(src, &dst.x); + setAlpha(dst, ColorChannel::max()); + + return dst; + } + __host__ __device__ __forceinline__ YCrCb2RGB() {} + __host__ __device__ __forceinline__ YCrCb2RGB(const YCrCb2RGB&) {} + }; + + template struct YCrCb2RGB : unary_function + { + __device__ __forceinline__ uint operator ()(uint src) const + { + return YCrCb2RGBConvert(src); + } + __host__ __device__ __forceinline__ YCrCb2RGB() {} + __host__ __device__ __forceinline__ YCrCb2RGB(const YCrCb2RGB&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(name, scn, dcn, bidx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::YCrCb2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + +////////////////////////////////////// RGB <-> XYZ /////////////////////////////////////// + + namespace color_detail + { + __constant__ float c_RGB2XYZ_D65f[9] = { 0.412453f, 0.357580f, 0.180423f, 0.212671f, 0.715160f, 0.072169f, 0.019334f, 0.119193f, 0.950227f }; + __constant__ int c_RGB2XYZ_D65i[9] = { 1689, 1465, 739, 871, 2929, 296, 79, 488, 3892 }; + + template static __device__ __forceinline__ void RGB2XYZConvert(const T* src, D& dst) + { + dst.z = saturate_cast(CV_DESCALE(src[bidx^2] * c_RGB2XYZ_D65i[6] + src[1] * c_RGB2XYZ_D65i[7] + src[bidx] * c_RGB2XYZ_D65i[8], xyz_shift)); + dst.x = saturate_cast(CV_DESCALE(src[bidx^2] * c_RGB2XYZ_D65i[0] + src[1] * c_RGB2XYZ_D65i[1] + src[bidx] * c_RGB2XYZ_D65i[2], xyz_shift)); + dst.y = saturate_cast(CV_DESCALE(src[bidx^2] * c_RGB2XYZ_D65i[3] + src[1] * c_RGB2XYZ_D65i[4] + src[bidx] * c_RGB2XYZ_D65i[5], xyz_shift)); + } + + template static __device__ __forceinline__ uint RGB2XYZConvert(uint src) + { + const uint b = 0xffu & (src >> (bidx * 8)); + const uint g = 0xffu & (src >> 8); + const uint r = 0xffu & (src >> ((bidx ^ 2) * 8)); + + const uint x = saturate_cast(CV_DESCALE(r * c_RGB2XYZ_D65i[0] + g * c_RGB2XYZ_D65i[1] + b * c_RGB2XYZ_D65i[2], xyz_shift)); + const uint y = saturate_cast(CV_DESCALE(r * c_RGB2XYZ_D65i[3] + g * c_RGB2XYZ_D65i[4] + b * c_RGB2XYZ_D65i[5], xyz_shift)); + const uint z = saturate_cast(CV_DESCALE(r * c_RGB2XYZ_D65i[6] + g * c_RGB2XYZ_D65i[7] + b * c_RGB2XYZ_D65i[8], xyz_shift)); + + uint dst = 0; + + dst |= x; + dst |= y << 8; + dst |= z << 16; + + return dst; + } + + template static __device__ __forceinline__ void RGB2XYZConvert(const float* src, D& dst) + { + dst.x = src[bidx^2] * c_RGB2XYZ_D65f[0] + src[1] * c_RGB2XYZ_D65f[1] + src[bidx] * c_RGB2XYZ_D65f[2]; + dst.y = src[bidx^2] * c_RGB2XYZ_D65f[3] + src[1] * c_RGB2XYZ_D65f[4] + src[bidx] * c_RGB2XYZ_D65f[5]; + dst.z = src[bidx^2] * c_RGB2XYZ_D65f[6] + src[1] * c_RGB2XYZ_D65f[7] + src[bidx] * c_RGB2XYZ_D65f[8]; + } + + template struct RGB2XYZ + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + RGB2XYZConvert(&src.x, dst); + + return dst; + } + __host__ __device__ __forceinline__ RGB2XYZ() {} + __host__ __device__ __forceinline__ RGB2XYZ(const RGB2XYZ&) {} + }; + + template struct RGB2XYZ : unary_function + { + __device__ __forceinline__ uint operator()(uint src) const + { + return RGB2XYZConvert(src); + } + __host__ __device__ __forceinline__ RGB2XYZ() {} + __host__ __device__ __forceinline__ RGB2XYZ(const RGB2XYZ&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(name, scn, dcn, bidx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2XYZ functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + + namespace color_detail + { + __constant__ float c_XYZ2sRGB_D65f[9] = { 3.240479f, -1.53715f, -0.498535f, -0.969256f, 1.875991f, 0.041556f, 0.055648f, -0.204043f, 1.057311f }; + __constant__ int c_XYZ2sRGB_D65i[9] = { 13273, -6296, -2042, -3970, 7684, 170, 228, -836, 4331 }; + + template static __device__ __forceinline__ void XYZ2RGBConvert(const T& src, D* dst) + { + dst[bidx^2] = saturate_cast(CV_DESCALE(src.x * c_XYZ2sRGB_D65i[0] + src.y * c_XYZ2sRGB_D65i[1] + src.z * c_XYZ2sRGB_D65i[2], xyz_shift)); + dst[1] = saturate_cast(CV_DESCALE(src.x * c_XYZ2sRGB_D65i[3] + src.y * c_XYZ2sRGB_D65i[4] + src.z * c_XYZ2sRGB_D65i[5], xyz_shift)); + dst[bidx] = saturate_cast(CV_DESCALE(src.x * c_XYZ2sRGB_D65i[6] + src.y * c_XYZ2sRGB_D65i[7] + src.z * c_XYZ2sRGB_D65i[8], xyz_shift)); + } + + template static __device__ __forceinline__ uint XYZ2RGBConvert(uint src) + { + const int x = 0xff & src; + const int y = 0xff & (src >> 8); + const int z = 0xff & (src >> 16); + + const uint r = saturate_cast(CV_DESCALE(x * c_XYZ2sRGB_D65i[0] + y * c_XYZ2sRGB_D65i[1] + z * c_XYZ2sRGB_D65i[2], xyz_shift)); + const uint g = saturate_cast(CV_DESCALE(x * c_XYZ2sRGB_D65i[3] + y * c_XYZ2sRGB_D65i[4] + z * c_XYZ2sRGB_D65i[5], xyz_shift)); + const uint b = saturate_cast(CV_DESCALE(x * c_XYZ2sRGB_D65i[6] + y * c_XYZ2sRGB_D65i[7] + z * c_XYZ2sRGB_D65i[8], xyz_shift)); + + uint dst = 0xffu << 24; + + dst |= b << (bidx * 8); + dst |= g << 8; + dst |= r << ((bidx ^ 2) * 8); + + return dst; + } + + template static __device__ __forceinline__ void XYZ2RGBConvert(const T& src, float* dst) + { + dst[bidx^2] = src.x * c_XYZ2sRGB_D65f[0] + src.y * c_XYZ2sRGB_D65f[1] + src.z * c_XYZ2sRGB_D65f[2]; + dst[1] = src.x * c_XYZ2sRGB_D65f[3] + src.y * c_XYZ2sRGB_D65f[4] + src.z * c_XYZ2sRGB_D65f[5]; + dst[bidx] = src.x * c_XYZ2sRGB_D65f[6] + src.y * c_XYZ2sRGB_D65f[7] + src.z * c_XYZ2sRGB_D65f[8]; + } + + template struct XYZ2RGB + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + XYZ2RGBConvert(src, &dst.x); + setAlpha(dst, ColorChannel::max()); + + return dst; + } + __host__ __device__ __forceinline__ XYZ2RGB() {} + __host__ __device__ __forceinline__ XYZ2RGB(const XYZ2RGB&) {} + }; + + template struct XYZ2RGB : unary_function + { + __device__ __forceinline__ uint operator()(uint src) const + { + return XYZ2RGBConvert(src); + } + __host__ __device__ __forceinline__ XYZ2RGB() {} + __host__ __device__ __forceinline__ XYZ2RGB(const XYZ2RGB&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(name, scn, dcn, bidx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::XYZ2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + +////////////////////////////////////// RGB <-> HSV /////////////////////////////////////// + + namespace color_detail + { + __constant__ int c_HsvDivTable [256] = {0, 1044480, 522240, 348160, 261120, 208896, 174080, 149211, 130560, 116053, 104448, 94953, 87040, 80345, 74606, 69632, 65280, 61440, 58027, 54973, 52224, 49737, 47476, 45412, 43520, 41779, 40172, 38684, 37303, 36017, 34816, 33693, 32640, 31651, 30720, 29842, 29013, 28229, 27486, 26782, 26112, 25475, 24869, 24290, 23738, 23211, 22706, 22223, 21760, 21316, 20890, 20480, 20086, 19707, 19342, 18991, 18651, 18324, 18008, 17703, 17408, 17123, 16846, 16579, 16320, 16069, 15825, 15589, 15360, 15137, 14921, 14711, 14507, 14308, 14115, 13926, 13743, 13565, 13391, 13221, 13056, 12895, 12738, 12584, 12434, 12288, 12145, 12006, 11869, 11736, 11605, 11478, 11353, 11231, 11111, 10995, 10880, 10768, 10658, 10550, 10445, 10341, 10240, 10141, 10043, 9947, 9854, 9761, 9671, 9582, 9495, 9410, 9326, 9243, 9162, 9082, 9004, 8927, 8852, 8777, 8704, 8632, 8561, 8492, 8423, 8356, 8290, 8224, 8160, 8097, 8034, 7973, 7913, 7853, 7795, 7737, 7680, 7624, 7569, 7514, 7461, 7408, 7355, 7304, 7253, 7203, 7154, 7105, 7057, 7010, 6963, 6917, 6872, 6827, 6782, 6739, 6695, 6653, 6611, 6569, 6528, 6487, 6447, 6408, 6369, 6330, 6292, 6254, 6217, 6180, 6144, 6108, 6073, 6037, 6003, 5968, 5935, 5901, 5868, 5835, 5803, 5771, 5739, 5708, 5677, 5646, 5615, 5585, 5556, 5526, 5497, 5468, 5440, 5412, 5384, 5356, 5329, 5302, 5275, 5249, 5222, 5196, 5171, 5145, 5120, 5095, 5070, 5046, 5022, 4998, 4974, 4950, 4927, 4904, 4881, 4858, 4836, 4813, 4791, 4769, 4748, 4726, 4705, 4684, 4663, 4642, 4622, 4601, 4581, 4561, 4541, 4522, 4502, 4483, 4464, 4445, 4426, 4407, 4389, 4370, 4352, 4334, 4316, 4298, 4281, 4263, 4246, 4229, 4212, 4195, 4178, 4161, 4145, 4128, 4112, 4096}; + __constant__ int c_HsvDivTable180[256] = {0, 122880, 61440, 40960, 30720, 24576, 20480, 17554, 15360, 13653, 12288, 11171, 10240, 9452, 8777, 8192, 7680, 7228, 6827, 6467, 6144, 5851, 5585, 5343, 5120, 4915, 4726, 4551, 4389, 4237, 4096, 3964, 3840, 3724, 3614, 3511, 3413, 3321, 3234, 3151, 3072, 2997, 2926, 2858, 2793, 2731, 2671, 2614, 2560, 2508, 2458, 2409, 2363, 2318, 2276, 2234, 2194, 2156, 2119, 2083, 2048, 2014, 1982, 1950, 1920, 1890, 1862, 1834, 1807, 1781, 1755, 1731, 1707, 1683, 1661, 1638, 1617, 1596, 1575, 1555, 1536, 1517, 1499, 1480, 1463, 1446, 1429, 1412, 1396, 1381, 1365, 1350, 1336, 1321, 1307, 1293, 1280, 1267, 1254, 1241, 1229, 1217, 1205, 1193, 1182, 1170, 1159, 1148, 1138, 1127, 1117, 1107, 1097, 1087, 1078, 1069, 1059, 1050, 1041, 1033, 1024, 1016, 1007, 999, 991, 983, 975, 968, 960, 953, 945, 938, 931, 924, 917, 910, 904, 897, 890, 884, 878, 871, 865, 859, 853, 847, 842, 836, 830, 825, 819, 814, 808, 803, 798, 793, 788, 783, 778, 773, 768, 763, 759, 754, 749, 745, 740, 736, 731, 727, 723, 719, 714, 710, 706, 702, 698, 694, 690, 686, 683, 679, 675, 671, 668, 664, 661, 657, 654, 650, 647, 643, 640, 637, 633, 630, 627, 624, 621, 617, 614, 611, 608, 605, 602, 599, 597, 594, 591, 588, 585, 582, 580, 577, 574, 572, 569, 566, 564, 561, 559, 556, 554, 551, 549, 546, 544, 541, 539, 537, 534, 532, 530, 527, 525, 523, 521, 518, 516, 514, 512, 510, 508, 506, 504, 502, 500, 497, 495, 493, 492, 490, 488, 486, 484, 482}; + __constant__ int c_HsvDivTable256[256] = {0, 174763, 87381, 58254, 43691, 34953, 29127, 24966, 21845, 19418, 17476, 15888, 14564, 13443, 12483, 11651, 10923, 10280, 9709, 9198, 8738, 8322, 7944, 7598, 7282, 6991, 6722, 6473, 6242, 6026, 5825, 5638, 5461, 5296, 5140, 4993, 4855, 4723, 4599, 4481, 4369, 4263, 4161, 4064, 3972, 3884, 3799, 3718, 3641, 3567, 3495, 3427, 3361, 3297, 3236, 3178, 3121, 3066, 3013, 2962, 2913, 2865, 2819, 2774, 2731, 2689, 2648, 2608, 2570, 2533, 2497, 2461, 2427, 2394, 2362, 2330, 2300, 2270, 2241, 2212, 2185, 2158, 2131, 2106, 2081, 2056, 2032, 2009, 1986, 1964, 1942, 1920, 1900, 1879, 1859, 1840, 1820, 1802, 1783, 1765, 1748, 1730, 1713, 1697, 1680, 1664, 1649, 1633, 1618, 1603, 1589, 1574, 1560, 1547, 1533, 1520, 1507, 1494, 1481, 1469, 1456, 1444, 1432, 1421, 1409, 1398, 1387, 1376, 1365, 1355, 1344, 1334, 1324, 1314, 1304, 1295, 1285, 1276, 1266, 1257, 1248, 1239, 1231, 1222, 1214, 1205, 1197, 1189, 1181, 1173, 1165, 1157, 1150, 1142, 1135, 1128, 1120, 1113, 1106, 1099, 1092, 1085, 1079, 1072, 1066, 1059, 1053, 1046, 1040, 1034, 1028, 1022, 1016, 1010, 1004, 999, 993, 987, 982, 976, 971, 966, 960, 955, 950, 945, 940, 935, 930, 925, 920, 915, 910, 906, 901, 896, 892, 887, 883, 878, 874, 869, 865, 861, 857, 853, 848, 844, 840, 836, 832, 828, 824, 820, 817, 813, 809, 805, 802, 798, 794, 791, 787, 784, 780, 777, 773, 770, 767, 763, 760, 757, 753, 750, 747, 744, 741, 737, 734, 731, 728, 725, 722, 719, 716, 713, 710, 708, 705, 702, 699, 696, 694, 691, 688, 685}; + + template static __device__ void RGB2HSVConvert(const uchar* src, D& dst) + { + const int hsv_shift = 12; + const int* hdiv_table = hr == 180 ? c_HsvDivTable180 : c_HsvDivTable256; + + int b = src[bidx], g = src[1], r = src[bidx^2]; + int h, s, v = b; + int vmin = b, diff; + int vr, vg; + + v = ::max(v, g); + v = ::max(v, r); + vmin = ::min(vmin, g); + vmin = ::min(vmin, r); + + diff = v - vmin; + vr = (v == r) * -1; + vg = (v == g) * -1; + + s = (diff * c_HsvDivTable[v] + (1 << (hsv_shift-1))) >> hsv_shift; + h = (vr & (g - b)) + (~vr & ((vg & (b - r + 2 * diff)) + ((~vg) & (r - g + 4 * diff)))); + h = (h * hdiv_table[diff] + (1 << (hsv_shift-1))) >> hsv_shift; + h += (h < 0) * hr; + + dst.x = saturate_cast(h); + dst.y = (uchar)s; + dst.z = (uchar)v; + } + + template static __device__ uint RGB2HSVConvert(uint src) + { + const int hsv_shift = 12; + const int* hdiv_table = hr == 180 ? c_HsvDivTable180 : c_HsvDivTable256; + + const int b = 0xff & (src >> (bidx * 8)); + const int g = 0xff & (src >> 8); + const int r = 0xff & (src >> ((bidx ^ 2) * 8)); + + int h, s, v = b; + int vmin = b, diff; + int vr, vg; + + v = ::max(v, g); + v = ::max(v, r); + vmin = ::min(vmin, g); + vmin = ::min(vmin, r); + + diff = v - vmin; + vr = (v == r) * -1; + vg = (v == g) * -1; + + s = (diff * c_HsvDivTable[v] + (1 << (hsv_shift-1))) >> hsv_shift; + h = (vr & (g - b)) + (~vr & ((vg & (b - r + 2 * diff)) + ((~vg) & (r - g + 4 * diff)))); + h = (h * hdiv_table[diff] + (1 << (hsv_shift-1))) >> hsv_shift; + h += (h < 0) * hr; + + uint dst = 0; + + dst |= saturate_cast(h); + dst |= (0xffu & s) << 8; + dst |= (0xffu & v) << 16; + + return dst; + } + + template static __device__ void RGB2HSVConvert(const float* src, D& dst) + { + const float hscale = hr * (1.f / 360.f); + + float b = src[bidx], g = src[1], r = src[bidx^2]; + float h, s, v; + + float vmin, diff; + + v = vmin = r; + v = fmax(v, g); + v = fmax(v, b); + vmin = fmin(vmin, g); + vmin = fmin(vmin, b); + + diff = v - vmin; + s = diff / (float)(::fabs(v) + numeric_limits::epsilon()); + diff = (float)(60. / (diff + numeric_limits::epsilon())); + + h = (v == r) * (g - b) * diff; + h += (v != r && v == g) * ((b - r) * diff + 120.f); + h += (v != r && v != g) * ((r - g) * diff + 240.f); + h += (h < 0) * 360.f; + + dst.x = h * hscale; + dst.y = s; + dst.z = v; + } + + template struct RGB2HSV + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + RGB2HSVConvert(&src.x, dst); + + return dst; + } + __host__ __device__ __forceinline__ RGB2HSV() {} + __host__ __device__ __forceinline__ RGB2HSV(const RGB2HSV&) {} + }; + + template struct RGB2HSV : unary_function + { + __device__ __forceinline__ uint operator()(uint src) const + { + return RGB2HSVConvert(src); + } + __host__ __device__ __forceinline__ RGB2HSV() {} + __host__ __device__ __forceinline__ RGB2HSV(const RGB2HSV&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(name, scn, dcn, bidx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2HSV functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; \ + template struct name ## _full_traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2HSV functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; \ + template <> struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2HSV functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; \ + template <> struct name ## _full_traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2HSV functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + + namespace color_detail + { + __constant__ int c_HsvSectorData[6][3] = { {1,3,0}, {1,0,2}, {3,0,1}, {0,2,1}, {0,1,3}, {2,1,0} }; + + template static __device__ void HSV2RGBConvert(const T& src, float* dst) + { + const float hscale = 6.f / hr; + + float h = src.x, s = src.y, v = src.z; + float b = v, g = v, r = v; + + if (s != 0) + { + h *= hscale; + + if( h < 0 ) + do h += 6; while( h < 0 ); + else if( h >= 6 ) + do h -= 6; while( h >= 6 ); + + int sector = __float2int_rd(h); + h -= sector; + + if ( (unsigned)sector >= 6u ) + { + sector = 0; + h = 0.f; + } + + float tab[4]; + tab[0] = v; + tab[1] = v * (1.f - s); + tab[2] = v * (1.f - s * h); + tab[3] = v * (1.f - s * (1.f - h)); + + b = tab[c_HsvSectorData[sector][0]]; + g = tab[c_HsvSectorData[sector][1]]; + r = tab[c_HsvSectorData[sector][2]]; + } + + dst[bidx] = b; + dst[1] = g; + dst[bidx^2] = r; + } + + template static __device__ void HSV2RGBConvert(const T& src, uchar* dst) + { + float3 buf; + + buf.x = src.x; + buf.y = src.y * (1.f / 255.f); + buf.z = src.z * (1.f / 255.f); + + HSV2RGBConvert(buf, &buf.x); + + dst[0] = saturate_cast(buf.x * 255.f); + dst[1] = saturate_cast(buf.y * 255.f); + dst[2] = saturate_cast(buf.z * 255.f); + } + + template static __device__ uint HSV2RGBConvert(uint src) + { + float3 buf; + + buf.x = src & 0xff; + buf.y = ((src >> 8) & 0xff) * (1.f/255.f); + buf.z = ((src >> 16) & 0xff) * (1.f/255.f); + + HSV2RGBConvert(buf, &buf.x); + + uint dst = 0xffu << 24; + + dst |= saturate_cast(buf.x * 255.f); + dst |= saturate_cast(buf.y * 255.f) << 8; + dst |= saturate_cast(buf.z * 255.f) << 16; + + return dst; + } + + template struct HSV2RGB + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + HSV2RGBConvert(src, &dst.x); + setAlpha(dst, ColorChannel::max()); + + return dst; + } + __host__ __device__ __forceinline__ HSV2RGB() {} + __host__ __device__ __forceinline__ HSV2RGB(const HSV2RGB&) {} + }; + + template struct HSV2RGB : unary_function + { + __device__ __forceinline__ uint operator()(uint src) const + { + return HSV2RGBConvert(src); + } + __host__ __device__ __forceinline__ HSV2RGB() {} + __host__ __device__ __forceinline__ HSV2RGB(const HSV2RGB&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(name, scn, dcn, bidx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::HSV2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; \ + template struct name ## _full_traits \ + { \ + typedef ::cv::cuda::device::color_detail::HSV2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; \ + template <> struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::HSV2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; \ + template <> struct name ## _full_traits \ + { \ + typedef ::cv::cuda::device::color_detail::HSV2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + +/////////////////////////////////////// RGB <-> HLS //////////////////////////////////////// + + namespace color_detail + { + template static __device__ void RGB2HLSConvert(const float* src, D& dst) + { + const float hscale = hr * (1.f / 360.f); + + float b = src[bidx], g = src[1], r = src[bidx^2]; + float h = 0.f, s = 0.f, l; + float vmin, vmax, diff; + + vmax = vmin = r; + vmax = fmax(vmax, g); + vmax = fmax(vmax, b); + vmin = fmin(vmin, g); + vmin = fmin(vmin, b); + + diff = vmax - vmin; + l = (vmax + vmin) * 0.5f; + + if (diff > numeric_limits::epsilon()) + { + s = (l < 0.5f) * diff / (vmax + vmin); + s += (l >= 0.5f) * diff / (2.0f - vmax - vmin); + + diff = 60.f / diff; + + h = (vmax == r) * (g - b) * diff; + h += (vmax != r && vmax == g) * ((b - r) * diff + 120.f); + h += (vmax != r && vmax != g) * ((r - g) * diff + 240.f); + h += (h < 0.f) * 360.f; + } + + dst.x = h * hscale; + dst.y = l; + dst.z = s; + } + + template static __device__ void RGB2HLSConvert(const uchar* src, D& dst) + { + float3 buf; + + buf.x = src[0] * (1.f / 255.f); + buf.y = src[1] * (1.f / 255.f); + buf.z = src[2] * (1.f / 255.f); + + RGB2HLSConvert(&buf.x, buf); + + dst.x = saturate_cast(buf.x); + dst.y = saturate_cast(buf.y*255.f); + dst.z = saturate_cast(buf.z*255.f); + } + + template static __device__ uint RGB2HLSConvert(uint src) + { + float3 buf; + + buf.x = (0xff & src) * (1.f / 255.f); + buf.y = (0xff & (src >> 8)) * (1.f / 255.f); + buf.z = (0xff & (src >> 16)) * (1.f / 255.f); + + RGB2HLSConvert(&buf.x, buf); + + uint dst = 0xffu << 24; + + dst |= saturate_cast(buf.x); + dst |= saturate_cast(buf.y * 255.f) << 8; + dst |= saturate_cast(buf.z * 255.f) << 16; + + return dst; + } + + template struct RGB2HLS + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + RGB2HLSConvert(&src.x, dst); + + return dst; + } + __host__ __device__ __forceinline__ RGB2HLS() {} + __host__ __device__ __forceinline__ RGB2HLS(const RGB2HLS&) {} + }; + + template struct RGB2HLS : unary_function + { + __device__ __forceinline__ uint operator()(uint src) const + { + return RGB2HLSConvert(src); + } + __host__ __device__ __forceinline__ RGB2HLS() {} + __host__ __device__ __forceinline__ RGB2HLS(const RGB2HLS&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(name, scn, dcn, bidx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2HLS functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; \ + template struct name ## _full_traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2HLS functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; \ + template <> struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2HLS functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; \ + template <> struct name ## _full_traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2HLS functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + + namespace color_detail + { + __constant__ int c_HlsSectorData[6][3] = { {1,3,0}, {1,0,2}, {3,0,1}, {0,2,1}, {0,1,3}, {2,1,0} }; + + template static __device__ void HLS2RGBConvert(const T& src, float* dst) + { + const float hscale = 6.0f / hr; + + float h = src.x, l = src.y, s = src.z; + float b = l, g = l, r = l; + + if (s != 0) + { + float p2 = (l <= 0.5f) * l * (1 + s); + p2 += (l > 0.5f) * (l + s - l * s); + float p1 = 2 * l - p2; + + h *= hscale; + + if( h < 0 ) + do h += 6; while( h < 0 ); + else if( h >= 6 ) + do h -= 6; while( h >= 6 ); + + int sector; + sector = __float2int_rd(h); + + h -= sector; + + float tab[4]; + tab[0] = p2; + tab[1] = p1; + tab[2] = p1 + (p2 - p1) * (1 - h); + tab[3] = p1 + (p2 - p1) * h; + + b = tab[c_HlsSectorData[sector][0]]; + g = tab[c_HlsSectorData[sector][1]]; + r = tab[c_HlsSectorData[sector][2]]; + } + + dst[bidx] = b; + dst[1] = g; + dst[bidx^2] = r; + } + + template static __device__ void HLS2RGBConvert(const T& src, uchar* dst) + { + float3 buf; + + buf.x = src.x; + buf.y = src.y * (1.f / 255.f); + buf.z = src.z * (1.f / 255.f); + + HLS2RGBConvert(buf, &buf.x); + + dst[0] = saturate_cast(buf.x * 255.f); + dst[1] = saturate_cast(buf.y * 255.f); + dst[2] = saturate_cast(buf.z * 255.f); + } + + template static __device__ uint HLS2RGBConvert(uint src) + { + float3 buf; + + buf.x = 0xff & src; + buf.y = (0xff & (src >> 8)) * (1.f / 255.f); + buf.z = (0xff & (src >> 16)) * (1.f / 255.f); + + HLS2RGBConvert(buf, &buf.x); + + uint dst = 0xffu << 24; + + dst |= saturate_cast(buf.x * 255.f); + dst |= saturate_cast(buf.y * 255.f) << 8; + dst |= saturate_cast(buf.z * 255.f) << 16; + + return dst; + } + + template struct HLS2RGB + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + HLS2RGBConvert(src, &dst.x); + setAlpha(dst, ColorChannel::max()); + + return dst; + } + __host__ __device__ __forceinline__ HLS2RGB() {} + __host__ __device__ __forceinline__ HLS2RGB(const HLS2RGB&) {} + }; + + template struct HLS2RGB : unary_function + { + __device__ __forceinline__ uint operator()(uint src) const + { + return HLS2RGBConvert(src); + } + __host__ __device__ __forceinline__ HLS2RGB() {} + __host__ __device__ __forceinline__ HLS2RGB(const HLS2RGB&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(name, scn, dcn, bidx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::HLS2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; \ + template struct name ## _full_traits \ + { \ + typedef ::cv::cuda::device::color_detail::HLS2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; \ + template <> struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::HLS2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; \ + template <> struct name ## _full_traits \ + { \ + typedef ::cv::cuda::device::color_detail::HLS2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + +///////////////////////////////////// RGB <-> Lab ///////////////////////////////////// + + namespace color_detail + { + enum + { + LAB_CBRT_TAB_SIZE = 1024, + GAMMA_TAB_SIZE = 1024, + lab_shift = xyz_shift, + gamma_shift = 3, + lab_shift2 = (lab_shift + gamma_shift), + LAB_CBRT_TAB_SIZE_B = (256 * 3 / 2 * (1 << gamma_shift)) + }; + + __constant__ ushort c_sRGBGammaTab_b[] = {0,1,1,2,2,3,4,4,5,6,6,7,8,8,9,10,11,11,12,13,14,15,16,17,19,20,21,22,24,25,26,28,29,31,33,34,36,38,40,41,43,45,47,49,51,54,56,58,60,63,65,68,70,73,75,78,81,83,86,89,92,95,98,101,105,108,111,115,118,121,125,129,132,136,140,144,147,151,155,160,164,168,172,176,181,185,190,194,199,204,209,213,218,223,228,233,239,244,249,255,260,265,271,277,282,288,294,300,306,312,318,324,331,337,343,350,356,363,370,376,383,390,397,404,411,418,426,433,440,448,455,463,471,478,486,494,502,510,518,527,535,543,552,560,569,578,586,595,604,613,622,631,641,650,659,669,678,688,698,707,717,727,737,747,757,768,778,788,799,809,820,831,842,852,863,875,886,897,908,920,931,943,954,966,978,990,1002,1014,1026,1038,1050,1063,1075,1088,1101,1113,1126,1139,1152,1165,1178,1192,1205,1218,1232,1245,1259,1273,1287,1301,1315,1329,1343,1357,1372,1386,1401,1415,1430,1445,1460,1475,1490,1505,1521,1536,1551,1567,1583,1598,1614,1630,1646,1662,1678,1695,1711,1728,1744,1761,1778,1794,1811,1828,1846,1863,1880,1897,1915,1933,1950,1968,1986,2004,2022,2040}; + + __device__ __forceinline__ int LabCbrt_b(int i) + { + float x = i * (1.f / (255.f * (1 << gamma_shift))); + return (1 << lab_shift2) * (x < 0.008856f ? x * 7.787f + 0.13793103448275862f : ::cbrtf(x)); + } + + template + __device__ __forceinline__ void RGB2LabConvert_b(const T& src, D& dst) + { + const int Lscale = (116 * 255 + 50) / 100; + const int Lshift = -((16 * 255 * (1 << lab_shift2) + 50) / 100); + + int B = blueIdx == 0 ? src.x : src.z; + int G = src.y; + int R = blueIdx == 0 ? src.z : src.x; + + if (srgb) + { + B = c_sRGBGammaTab_b[B]; + G = c_sRGBGammaTab_b[G]; + R = c_sRGBGammaTab_b[R]; + } + else + { + B <<= 3; + G <<= 3; + R <<= 3; + } + + int fX = LabCbrt_b(CV_DESCALE(B * 778 + G * 1541 + R * 1777, lab_shift)); + int fY = LabCbrt_b(CV_DESCALE(B * 296 + G * 2929 + R * 871, lab_shift)); + int fZ = LabCbrt_b(CV_DESCALE(B * 3575 + G * 448 + R * 73, lab_shift)); + + int L = CV_DESCALE(Lscale * fY + Lshift, lab_shift2); + int a = CV_DESCALE(500 * (fX - fY) + 128 * (1 << lab_shift2), lab_shift2); + int b = CV_DESCALE(200 * (fY - fZ) + 128 * (1 << lab_shift2), lab_shift2); + + dst.x = saturate_cast(L); + dst.y = saturate_cast(a); + dst.z = saturate_cast(b); + } + + __device__ __forceinline__ float splineInterpolate(float x, const float* tab, int n) + { + int ix = ::min(::max(int(x), 0), n-1); + x -= ix; + tab += ix * 4; + return ((tab[3] * x + tab[2]) * x + tab[1]) * x + tab[0]; + } + + __constant__ float c_sRGBGammaTab[] = {0,7.55853e-05,0.,-7.51331e-13,7.55853e-05,7.55853e-05,-2.25399e-12,3.75665e-12,0.000151171,7.55853e-05,9.01597e-12,-6.99932e-12,0.000226756,7.55853e-05,-1.1982e-11,2.41277e-12,0.000302341,7.55853e-05,-4.74369e-12,1.19001e-11,0.000377927,7.55853e-05,3.09568e-11,-2.09095e-11,0.000453512,7.55853e-05,-3.17718e-11,1.35303e-11,0.000529097,7.55853e-05,8.81905e-12,-4.10782e-12,0.000604683,7.55853e-05,-3.50439e-12,2.90097e-12,0.000680268,7.55853e-05,5.19852e-12,-7.49607e-12,0.000755853,7.55853e-05,-1.72897e-11,2.70833e-11,0.000831439,7.55854e-05,6.39602e-11,-4.26295e-11,0.000907024,7.55854e-05,-6.39282e-11,2.70193e-11,0.000982609,7.55853e-05,1.71298e-11,-7.24017e-12,0.00105819,7.55853e-05,-4.59077e-12,1.94137e-12,0.00113378,7.55853e-05,1.23333e-12,-5.25291e-13,0.00120937,7.55853e-05,-3.42545e-13,1.59799e-13,0.00128495,7.55853e-05,1.36852e-13,-1.13904e-13,0.00136054,7.55853e-05,-2.04861e-13,2.95818e-13,0.00143612,7.55853e-05,6.82594e-13,-1.06937e-12,0.00151171,7.55853e-05,-2.52551e-12,3.98166e-12,0.00158729,7.55853e-05,9.41946e-12,-1.48573e-11,0.00166288,7.55853e-05,-3.51523e-11,5.54474e-11,0.00173846,7.55854e-05,1.3119e-10,-9.0517e-11,0.00181405,7.55854e-05,-1.40361e-10,7.37899e-11,0.00188963,7.55853e-05,8.10085e-11,-8.82272e-11,0.00196522,7.55852e-05,-1.83673e-10,1.62704e-10,0.0020408,7.55853e-05,3.04438e-10,-2.13341e-10,0.00211639,7.55853e-05,-3.35586e-10,2.25e-10,0.00219197,7.55853e-05,3.39414e-10,-2.20997e-10,0.00226756,7.55853e-05,-3.23576e-10,1.93326e-10,0.00234315,7.55853e-05,2.564e-10,-8.66446e-11,0.00241873,7.55855e-05,-3.53328e-12,-7.9578e-11,0.00249432,7.55853e-05,-2.42267e-10,1.72126e-10,0.0025699,7.55853e-05,2.74111e-10,-1.43265e-10,0.00264549,7.55854e-05,-1.55683e-10,-6.47292e-11,0.00272107,7.55849e-05,-3.4987e-10,8.67842e-10,0.00279666,7.55868e-05,2.25366e-09,-3.8723e-09,0.00287224,7.55797e-05,-9.36325e-09,1.5087e-08,0.00294783,7.56063e-05,3.58978e-08,-5.69415e-08,0.00302341,7.55072e-05,-1.34927e-07,2.13144e-07,0.003099,7.58768e-05,5.04507e-07,1.38713e-07,0.00317552,7.7302e-05,9.20646e-07,-1.55186e-07,0.00325359,7.86777e-05,4.55087e-07,4.26813e-08,0.00333276,7.97159e-05,5.83131e-07,-1.06495e-08,0.00341305,8.08502e-05,5.51182e-07,3.87467e-09,0.00349446,8.19642e-05,5.62806e-07,-1.92586e-10,0.00357698,8.30892e-05,5.62228e-07,1.0866e-09,0.00366063,8.4217e-05,5.65488e-07,5.02818e-10,0.00374542,8.53494e-05,5.66997e-07,8.60211e-10,0.00383133,8.6486e-05,5.69577e-07,7.13044e-10,0.00391839,8.76273e-05,5.71716e-07,4.78527e-10,0.00400659,8.87722e-05,5.73152e-07,1.09818e-09,0.00409594,8.99218e-05,5.76447e-07,2.50964e-10,0.00418644,9.10754e-05,5.772e-07,1.15762e-09,0.00427809,9.22333e-05,5.80672e-07,2.40865e-10,0.0043709,9.33954e-05,5.81395e-07,1.13854e-09,0.00446488,9.45616e-05,5.84811e-07,3.27267e-10,0.00456003,9.57322e-05,5.85792e-07,8.1197e-10,0.00465635,9.69062e-05,5.88228e-07,6.15823e-10,0.00475384,9.80845e-05,5.90076e-07,9.15747e-10,0.00485252,9.92674e-05,5.92823e-07,3.778e-10,0.00495238,0.000100454,5.93956e-07,8.32623e-10,0.00505343,0.000101645,5.96454e-07,4.82695e-10,0.00515567,0.000102839,5.97902e-07,9.61904e-10,0.00525911,0.000104038,6.00788e-07,3.26281e-10,0.00536375,0.00010524,6.01767e-07,9.926e-10,0.00546959,0.000106447,6.04745e-07,3.59933e-10,0.00557664,0.000107657,6.05824e-07,8.2728e-10,0.0056849,0.000108871,6.08306e-07,5.21898e-10,0.00579438,0.00011009,6.09872e-07,8.10492e-10,0.00590508,0.000111312,6.12303e-07,4.27046e-10,0.00601701,0.000112538,6.13585e-07,7.40878e-10,0.00613016,0.000113767,6.15807e-07,8.00469e-10,0.00624454,0.000115001,6.18209e-07,2.48178e-10,0.00636016,0.000116238,6.18953e-07,1.00073e-09,0.00647702,0.000117479,6.21955e-07,4.05654e-10,0.00659512,0.000118724,6.23172e-07,6.36192e-10,0.00671447,0.000119973,6.25081e-07,7.74927e-10,0.00683507,0.000121225,6.27406e-07,4.54975e-10,0.00695692,0.000122481,6.28771e-07,6.64841e-10,0.00708003,0.000123741,6.30765e-07,6.10972e-10,0.00720441,0.000125004,6.32598e-07,6.16543e-10,0.00733004,0.000126271,6.34448e-07,6.48204e-10,0.00745695,0.000127542,6.36392e-07,5.15835e-10,0.00758513,0.000128816,6.3794e-07,5.48103e-10,0.00771458,0.000130094,6.39584e-07,1.01706e-09,0.00784532,0.000131376,6.42635e-07,4.0283e-11,0.00797734,0.000132661,6.42756e-07,6.84471e-10,0.00811064,0.000133949,6.4481e-07,9.47144e-10,0.00824524,0.000135241,6.47651e-07,1.83472e-10,0.00838112,0.000136537,6.48201e-07,1.11296e-09,0.00851831,0.000137837,6.5154e-07,2.13163e-11,0.0086568,0.00013914,6.51604e-07,6.64462e-10,0.00879659,0.000140445,6.53598e-07,1.04613e-09,0.00893769,0.000141756,6.56736e-07,-1.92377e-10,0.0090801,0.000143069,6.56159e-07,1.58601e-09,0.00922383,0.000144386,6.60917e-07,-5.63754e-10,0.00936888,0.000145706,6.59226e-07,1.60033e-09,0.00951524,0.000147029,6.64027e-07,-2.49543e-10,0.00966294,0.000148356,6.63278e-07,1.26043e-09,0.00981196,0.000149687,6.67059e-07,-1.35572e-10,0.00996231,0.00015102,6.66653e-07,1.14458e-09,0.010114,0.000152357,6.70086e-07,2.13864e-10,0.010267,0.000153698,6.70728e-07,7.93856e-10,0.0104214,0.000155042,6.73109e-07,3.36077e-10,0.0105771,0.000156389,6.74118e-07,6.55765e-10,0.0107342,0.000157739,6.76085e-07,7.66211e-10,0.0108926,0.000159094,6.78384e-07,4.66116e-12,0.0110524,0.000160451,6.78398e-07,1.07775e-09,0.0112135,0.000161811,6.81631e-07,3.41023e-10,0.011376,0.000163175,6.82654e-07,3.5205e-10,0.0115398,0.000164541,6.8371e-07,1.04473e-09,0.0117051,0.000165912,6.86844e-07,1.25757e-10,0.0118717,0.000167286,6.87222e-07,3.14818e-10,0.0120396,0.000168661,6.88166e-07,1.40886e-09,0.012209,0.000170042,6.92393e-07,-3.62244e-10,0.0123797,0.000171425,6.91306e-07,9.71397e-10,0.0125518,0.000172811,6.9422e-07,2.02003e-10,0.0127253,0.0001742,6.94826e-07,1.01448e-09,0.0129002,0.000175593,6.97869e-07,3.96653e-10,0.0130765,0.00017699,6.99059e-07,1.92927e-10,0.0132542,0.000178388,6.99638e-07,6.94305e-10,0.0134333,0.00017979,7.01721e-07,7.55108e-10,0.0136138,0.000181195,7.03986e-07,1.05918e-11,0.0137957,0.000182603,7.04018e-07,1.06513e-09,0.013979,0.000184015,7.07214e-07,3.85512e-10,0.0141637,0.00018543,7.0837e-07,1.86769e-10,0.0143499,0.000186848,7.0893e-07,7.30116e-10,0.0145374,0.000188268,7.11121e-07,6.17983e-10,0.0147264,0.000189692,7.12975e-07,5.23282e-10,0.0149168,0.000191119,7.14545e-07,8.28398e-11,0.0151087,0.000192549,7.14793e-07,1.0081e-09,0.0153019,0.000193981,7.17817e-07,5.41244e-10,0.0154966,0.000195418,7.19441e-07,-3.7907e-10,0.0156928,0.000196856,7.18304e-07,1.90641e-09,0.0158903,0.000198298,7.24023e-07,-7.27387e-10,0.0160893,0.000199744,7.21841e-07,1.00317e-09,0.0162898,0.000201191,7.24851e-07,4.39949e-10,0.0164917,0.000202642,7.2617e-07,9.6234e-10,0.0166951,0.000204097,7.29057e-07,-5.64019e-10,0.0168999,0.000205554,7.27365e-07,1.29374e-09,0.0171062,0.000207012,7.31247e-07,9.77025e-10,0.017314,0.000208478,7.34178e-07,-1.47651e-09,0.0175232,0.000209942,7.29748e-07,3.06636e-09,0.0177338,0.00021141,7.38947e-07,-1.47573e-09,0.017946,0.000212884,7.3452e-07,9.7386e-10,0.0181596,0.000214356,7.37442e-07,1.30562e-09,0.0183747,0.000215835,7.41358e-07,-6.08376e-10,0.0185913,0.000217315,7.39533e-07,1.12785e-09,0.0188093,0.000218798,7.42917e-07,-1.77711e-10,0.0190289,0.000220283,7.42384e-07,1.44562e-09,0.0192499,0.000221772,7.46721e-07,-1.68825e-11,0.0194724,0.000223266,7.4667e-07,4.84533e-10,0.0196964,0.000224761,7.48124e-07,-5.85298e-11,0.0199219,0.000226257,7.47948e-07,1.61217e-09,0.0201489,0.000227757,7.52785e-07,-8.02136e-10,0.0203775,0.00022926,7.50378e-07,1.59637e-09,0.0206075,0.000230766,7.55167e-07,4.47168e-12,0.020839,0.000232276,7.55181e-07,2.48387e-10,0.021072,0.000233787,7.55926e-07,8.6474e-10,0.0213066,0.000235302,7.5852e-07,1.78299e-11,0.0215426,0.000236819,7.58573e-07,9.26567e-10,0.0217802,0.000238339,7.61353e-07,1.34529e-12,0.0220193,0.000239862,7.61357e-07,9.30659e-10,0.0222599,0.000241387,7.64149e-07,1.34529e-12,0.0225021,0.000242915,7.64153e-07,9.26567e-10,0.0227458,0.000244447,7.66933e-07,1.76215e-11,0.022991,0.00024598,7.66986e-07,8.65536e-10,0.0232377,0.000247517,7.69582e-07,2.45677e-10,0.023486,0.000249057,7.70319e-07,1.44193e-11,0.0237358,0.000250598,7.70363e-07,1.55918e-09,0.0239872,0.000252143,7.7504e-07,-6.63173e-10,0.0242401,0.000253691,7.73051e-07,1.09357e-09,0.0244946,0.000255241,7.76331e-07,1.41919e-11,0.0247506,0.000256793,7.76374e-07,7.12248e-10,0.0250082,0.000258348,7.78511e-07,8.62049e-10,0.0252673,0.000259908,7.81097e-07,-4.35061e-10,0.025528,0.000261469,7.79792e-07,8.7825e-10,0.0257902,0.000263031,7.82426e-07,6.47181e-10,0.0260541,0.000264598,7.84368e-07,2.58448e-10,0.0263194,0.000266167,7.85143e-07,1.81558e-10,0.0265864,0.000267738,7.85688e-07,8.78041e-10,0.0268549,0.000269312,7.88322e-07,3.15102e-11,0.027125,0.000270889,7.88417e-07,8.58525e-10,0.0273967,0.000272468,7.90992e-07,2.59812e-10,0.02767,0.000274051,7.91772e-07,-3.5224e-11,0.0279448,0.000275634,7.91666e-07,1.74377e-09,0.0282212,0.000277223,7.96897e-07,-1.35196e-09,0.0284992,0.000278813,7.92841e-07,1.80141e-09,0.0287788,0.000280404,7.98246e-07,-2.65629e-10,0.0290601,0.000281999,7.97449e-07,1.12374e-09,0.0293428,0.000283598,8.0082e-07,-5.04106e-10,0.0296272,0.000285198,7.99308e-07,8.92764e-10,0.0299132,0.000286799,8.01986e-07,6.58379e-10,0.0302008,0.000288405,8.03961e-07,1.98971e-10,0.0304901,0.000290014,8.04558e-07,4.08382e-10,0.0307809,0.000291624,8.05783e-07,3.01839e-11,0.0310733,0.000293236,8.05874e-07,1.33343e-09,0.0313673,0.000294851,8.09874e-07,2.2419e-10,0.031663,0.000296472,8.10547e-07,-3.67606e-10,0.0319603,0.000298092,8.09444e-07,1.24624e-09,0.0322592,0.000299714,8.13182e-07,-8.92025e-10,0.0325597,0.000301338,8.10506e-07,2.32183e-09,0.0328619,0.000302966,8.17472e-07,-9.44719e-10,0.0331657,0.000304598,8.14638e-07,1.45703e-09,0.0334711,0.000306232,8.19009e-07,-1.15805e-09,0.0337781,0.000307866,8.15535e-07,3.17507e-09,0.0340868,0.000309507,8.2506e-07,-4.09161e-09,0.0343971,0.000311145,8.12785e-07,5.74079e-09,0.0347091,0.000312788,8.30007e-07,-3.97034e-09,0.0350227,0.000314436,8.18096e-07,2.68985e-09,0.035338,0.00031608,8.26166e-07,6.61676e-10,0.0356549,0.000317734,8.28151e-07,-1.61123e-09,0.0359734,0.000319386,8.23317e-07,2.05786e-09,0.0362936,0.000321038,8.29491e-07,8.30388e-10,0.0366155,0.0003227,8.31982e-07,-1.65424e-09,0.036939,0.000324359,8.27019e-07,2.06129e-09,0.0372642,0.000326019,8.33203e-07,8.59719e-10,0.0375911,0.000327688,8.35782e-07,-1.77488e-09,0.0379196,0.000329354,8.30458e-07,2.51464e-09,0.0382498,0.000331023,8.38002e-07,-8.33135e-10,0.0385817,0.000332696,8.35502e-07,8.17825e-10,0.0389152,0.00033437,8.37956e-07,1.28718e-09,0.0392504,0.00033605,8.41817e-07,-2.2413e-09,0.0395873,0.000337727,8.35093e-07,3.95265e-09,0.0399258,0.000339409,8.46951e-07,-2.39332e-09,0.0402661,0.000341095,8.39771e-07,1.89533e-09,0.040608,0.000342781,8.45457e-07,-1.46271e-09,0.0409517,0.000344467,8.41069e-07,3.95554e-09,0.041297,0.000346161,8.52936e-07,-3.18369e-09,0.041644,0.000347857,8.43385e-07,1.32873e-09,0.0419927,0.000349548,8.47371e-07,1.59402e-09,0.0423431,0.000351248,8.52153e-07,-2.54336e-10,0.0426952,0.000352951,8.5139e-07,-5.76676e-10,0.043049,0.000354652,8.4966e-07,2.56114e-09,0.0434045,0.000356359,8.57343e-07,-2.21744e-09,0.0437617,0.000358067,8.50691e-07,2.58344e-09,0.0441206,0.000359776,8.58441e-07,-6.65826e-10,0.0444813,0.000361491,8.56444e-07,7.99218e-11,0.0448436,0.000363204,8.56684e-07,3.46063e-10,0.0452077,0.000364919,8.57722e-07,2.26116e-09,0.0455734,0.000366641,8.64505e-07,-1.94005e-09,0.045941,0.000368364,8.58685e-07,1.77384e-09,0.0463102,0.000370087,8.64007e-07,-1.43005e-09,0.0466811,0.000371811,8.59717e-07,3.94634e-09,0.0470538,0.000373542,8.71556e-07,-3.17946e-09,0.0474282,0.000375276,8.62017e-07,1.32104e-09,0.0478043,0.000377003,8.6598e-07,1.62045e-09,0.0481822,0.00037874,8.70842e-07,-3.52297e-10,0.0485618,0.000380481,8.69785e-07,-2.11211e-10,0.0489432,0.00038222,8.69151e-07,1.19716e-09,0.0493263,0.000383962,8.72743e-07,-8.52026e-10,0.0497111,0.000385705,8.70187e-07,2.21092e-09,0.0500977,0.000387452,8.76819e-07,-5.41339e-10,0.050486,0.000389204,8.75195e-07,-4.5361e-11,0.0508761,0.000390954,8.75059e-07,7.22669e-10,0.0512679,0.000392706,8.77227e-07,8.79936e-10,0.0516615,0.000394463,8.79867e-07,-5.17048e-10,0.0520568,0.000396222,8.78316e-07,1.18833e-09,0.0524539,0.000397982,8.81881e-07,-5.11022e-10,0.0528528,0.000399744,8.80348e-07,8.55683e-10,0.0532534,0.000401507,8.82915e-07,8.13562e-10,0.0536558,0.000403276,8.85356e-07,-3.84603e-10,0.05406,0.000405045,8.84202e-07,7.24962e-10,0.0544659,0.000406816,8.86377e-07,1.20986e-09,0.0548736,0.000408592,8.90006e-07,-1.83896e-09,0.0552831,0.000410367,8.84489e-07,2.42071e-09,0.0556944,0.000412143,8.91751e-07,-3.93413e-10,0.0561074,0.000413925,8.90571e-07,-8.46967e-10,0.0565222,0.000415704,8.8803e-07,3.78122e-09,0.0569388,0.000417491,8.99374e-07,-3.1021e-09,0.0573572,0.000419281,8.90068e-07,1.17658e-09,0.0577774,0.000421064,8.93597e-07,2.12117e-09,0.0581993,0.000422858,8.99961e-07,-2.21068e-09,0.0586231,0.000424651,8.93329e-07,2.9961e-09,0.0590486,0.000426447,9.02317e-07,-2.32311e-09,0.059476,0.000428244,8.95348e-07,2.57122e-09,0.0599051,0.000430043,9.03062e-07,-5.11098e-10,0.0603361,0.000431847,9.01528e-07,-5.27166e-10,0.0607688,0.000433649,8.99947e-07,2.61984e-09,0.0612034,0.000435457,9.07806e-07,-2.50141e-09,0.0616397,0.000437265,9.00302e-07,3.66045e-09,0.0620779,0.000439076,9.11283e-07,-4.68977e-09,0.0625179,0.000440885,8.97214e-07,7.64783e-09,0.0629597,0.000442702,9.20158e-07,-7.27499e-09,0.0634033,0.000444521,8.98333e-07,6.55113e-09,0.0638487,0.000446337,9.17986e-07,-4.02844e-09,0.0642959,0.000448161,9.05901e-07,2.11196e-09,0.064745,0.000449979,9.12236e-07,3.03125e-09,0.0651959,0.000451813,9.2133e-07,-6.78648e-09,0.0656486,0.000453635,9.00971e-07,9.21375e-09,0.0661032,0.000455464,9.28612e-07,-7.71684e-09,0.0665596,0.000457299,9.05462e-07,6.7522e-09,0.0670178,0.00045913,9.25718e-07,-4.3907e-09,0.0674778,0.000460968,9.12546e-07,3.36e-09,0.0679397,0.000462803,9.22626e-07,-1.59876e-09,0.0684034,0.000464644,9.1783e-07,3.0351e-09,0.068869,0.000466488,9.26935e-07,-3.09101e-09,0.0693364,0.000468333,9.17662e-07,1.8785e-09,0.0698057,0.000470174,9.23298e-07,3.02733e-09,0.0702768,0.00047203,9.3238e-07,-6.53722e-09,0.0707497,0.000473875,9.12768e-07,8.22054e-09,0.0712245,0.000475725,9.37429e-07,-3.99325e-09,0.0717012,0.000477588,9.2545e-07,3.01839e-10,0.0721797,0.00047944,9.26355e-07,2.78597e-09,0.0726601,0.000481301,9.34713e-07,-3.99507e-09,0.0731423,0.000483158,9.22728e-07,5.7435e-09,0.0736264,0.000485021,9.39958e-07,-4.07776e-09,0.0741123,0.000486888,9.27725e-07,3.11695e-09,0.0746002,0.000488753,9.37076e-07,-9.39394e-10,0.0750898,0.000490625,9.34258e-07,6.4055e-10,0.0755814,0.000492495,9.3618e-07,-1.62265e-09,0.0760748,0.000494363,9.31312e-07,5.84995e-09,0.0765701,0.000496243,9.48861e-07,-6.87601e-09,0.0770673,0.00049812,9.28233e-07,6.75296e-09,0.0775664,0.000499997,9.48492e-07,-5.23467e-09,0.0780673,0.000501878,9.32788e-07,6.73523e-09,0.0785701,0.000503764,9.52994e-07,-6.80514e-09,0.0790748,0.000505649,9.32578e-07,5.5842e-09,0.0795814,0.000507531,9.49331e-07,-6.30583e-10,0.0800899,0.000509428,9.47439e-07,-3.0618e-09,0.0806003,0.000511314,9.38254e-07,5.4273e-09,0.0811125,0.000513206,9.54536e-07,-3.74627e-09,0.0816267,0.000515104,9.43297e-07,2.10713e-09,0.0821427,0.000516997,9.49618e-07,2.76839e-09,0.0826607,0.000518905,9.57924e-07,-5.73006e-09,0.0831805,0.000520803,9.40733e-07,5.25072e-09,0.0837023,0.0005227,9.56486e-07,-3.71718e-10,0.084226,0.000524612,9.5537e-07,-3.76404e-09,0.0847515,0.000526512,9.44078e-07,7.97735e-09,0.085279,0.000528424,9.6801e-07,-5.79367e-09,0.0858084,0.000530343,9.50629e-07,2.96268e-10,0.0863397,0.000532245,9.51518e-07,4.6086e-09,0.0868729,0.000534162,9.65344e-07,-3.82947e-09,0.087408,0.000536081,9.53856e-07,3.25861e-09,0.087945,0.000537998,9.63631e-07,-1.7543e-09,0.088484,0.00053992,9.58368e-07,3.75849e-09,0.0890249,0.000541848,9.69644e-07,-5.82891e-09,0.0895677,0.00054377,9.52157e-07,4.65593e-09,0.0901124,0.000545688,9.66125e-07,2.10643e-09,0.0906591,0.000547627,9.72444e-07,-5.63099e-09,0.0912077,0.000549555,9.55551e-07,5.51627e-09,0.0917582,0.000551483,9.721e-07,-1.53292e-09,0.0923106,0.000553422,9.67501e-07,6.15311e-10,0.092865,0.000555359,9.69347e-07,-9.28291e-10,0.0934213,0.000557295,9.66562e-07,3.09774e-09,0.0939796,0.000559237,9.75856e-07,-4.01186e-09,0.0945398,0.000561177,9.6382e-07,5.49892e-09,0.095102,0.000563121,9.80317e-07,-3.08258e-09,0.0956661,0.000565073,9.71069e-07,-6.19176e-10,0.0962321,0.000567013,9.69212e-07,5.55932e-09,0.0968001,0.000568968,9.8589e-07,-6.71704e-09,0.09737,0.00057092,9.65738e-07,6.40762e-09,0.0979419,0.00057287,9.84961e-07,-4.0122e-09,0.0985158,0.000574828,9.72925e-07,2.19059e-09,0.0990916,0.000576781,9.79496e-07,2.70048e-09,0.0996693,0.000578748,9.87598e-07,-5.54193e-09,0.100249,0.000580706,9.70972e-07,4.56597e-09,0.100831,0.000582662,9.8467e-07,2.17923e-09,0.101414,0.000584638,9.91208e-07,-5.83232e-09,0.102,0.000586603,9.73711e-07,6.24884e-09,0.102588,0.000588569,9.92457e-07,-4.26178e-09,0.103177,0.000590541,9.79672e-07,3.34781e-09,0.103769,0.00059251,9.89715e-07,-1.67904e-09,0.104362,0.000594485,9.84678e-07,3.36839e-09,0.104958,0.000596464,9.94783e-07,-4.34397e-09,0.105555,0.000598441,9.81751e-07,6.55696e-09,0.106155,0.000600424,1.00142e-06,-6.98272e-09,0.106756,0.000602406,9.80474e-07,6.4728e-09,0.107359,0.000604386,9.99893e-07,-4.00742e-09,0.107965,0.000606374,9.8787e-07,2.10654e-09,0.108572,0.000608356,9.9419e-07,3.0318e-09,0.109181,0.000610353,1.00329e-06,-6.7832e-09,0.109793,0.00061234,9.82936e-07,9.1998e-09,0.110406,0.000614333,1.01054e-06,-7.6642e-09,0.111021,0.000616331,9.87543e-07,6.55579e-09,0.111639,0.000618326,1.00721e-06,-3.65791e-09,0.112258,0.000620329,9.96236e-07,6.25467e-10,0.112879,0.000622324,9.98113e-07,1.15593e-09,0.113503,0.000624323,1.00158e-06,2.20158e-09,0.114128,0.000626333,1.00819e-06,-2.51191e-09,0.114755,0.000628342,1.00065e-06,3.95517e-10,0.115385,0.000630345,1.00184e-06,9.29807e-10,0.116016,0.000632351,1.00463e-06,3.33599e-09,0.116649,0.00063437,1.01463e-06,-6.82329e-09,0.117285,0.000636379,9.94163e-07,9.05595e-09,0.117922,0.000638395,1.02133e-06,-7.04862e-09,0.118562,0.000640416,1.00019e-06,4.23737e-09,0.119203,0.000642429,1.0129e-06,-2.45033e-09,0.119847,0.000644448,1.00555e-06,5.56395e-09,0.120492,0.000646475,1.02224e-06,-4.9043e-09,0.121139,0.000648505,1.00753e-06,-8.47952e-10,0.121789,0.000650518,1.00498e-06,8.29622e-09,0.122441,0.000652553,1.02987e-06,-9.98538e-09,0.123094,0.000654582,9.99914e-07,9.2936e-09,0.12375,0.00065661,1.02779e-06,-4.83707e-09,0.124407,0.000658651,1.01328e-06,2.60411e-09,0.125067,0.000660685,1.0211e-06,-5.57945e-09,0.125729,0.000662711,1.00436e-06,1.22631e-08,0.126392,0.000664756,1.04115e-06,-1.36704e-08,0.127058,0.000666798,1.00014e-06,1.26161e-08,0.127726,0.000668836,1.03798e-06,-6.99155e-09,0.128396,0.000670891,1.01701e-06,4.48836e-10,0.129068,0.000672926,1.01836e-06,5.19606e-09,0.129742,0.000674978,1.03394e-06,-6.3319e-09,0.130418,0.000677027,1.01495e-06,5.2305e-09,0.131096,0.000679073,1.03064e-06,3.11123e-10,0.131776,0.000681135,1.03157e-06,-6.47511e-09,0.132458,0.000683179,1.01215e-06,1.06882e-08,0.133142,0.000685235,1.04421e-06,-6.47519e-09,0.133829,0.000687304,1.02479e-06,3.11237e-10,0.134517,0.000689355,1.02572e-06,5.23035e-09,0.135207,0.000691422,1.04141e-06,-6.3316e-09,0.1359,0.000693486,1.02242e-06,5.19484e-09,0.136594,0.000695546,1.038e-06,4.53497e-10,0.137291,0.000697623,1.03936e-06,-7.00891e-09,0.137989,0.000699681,1.01834e-06,1.2681e-08,0.13869,0.000701756,1.05638e-06,-1.39128e-08,0.139393,0.000703827,1.01464e-06,1.31679e-08,0.140098,0.000705896,1.05414e-06,-8.95659e-09,0.140805,0.000707977,1.02727e-06,7.75742e-09,0.141514,0.000710055,1.05055e-06,-7.17182e-09,0.142225,0.000712135,1.02903e-06,6.02862e-09,0.142938,0.000714211,1.04712e-06,-2.04163e-09,0.143653,0.000716299,1.04099e-06,2.13792e-09,0.144371,0.000718387,1.04741e-06,-6.51009e-09,0.14509,0.000720462,1.02787e-06,9.00123e-09,0.145812,0.000722545,1.05488e-06,3.07523e-10,0.146535,0.000724656,1.0558e-06,-1.02312e-08,0.147261,0.000726737,1.02511e-06,1.0815e-08,0.147989,0.000728819,1.05755e-06,-3.22681e-09,0.148719,0.000730925,1.04787e-06,2.09244e-09,0.14945,0.000733027,1.05415e-06,-5.143e-09,0.150185,0.00073512,1.03872e-06,3.57844e-09,0.150921,0.000737208,1.04946e-06,5.73027e-09,0.151659,0.000739324,1.06665e-06,-1.15983e-08,0.152399,0.000741423,1.03185e-06,1.08605e-08,0.153142,0.000743519,1.06443e-06,-2.04106e-09,0.153886,0.000745642,1.05831e-06,-2.69642e-09,0.154633,0.00074775,1.05022e-06,-2.07425e-09,0.155382,0.000749844,1.044e-06,1.09934e-08,0.156133,0.000751965,1.07698e-06,-1.20972e-08,0.156886,0.000754083,1.04069e-06,7.59288e-09,0.157641,0.000756187,1.06347e-06,-3.37305e-09,0.158398,0.000758304,1.05335e-06,5.89921e-09,0.159158,0.000760428,1.07104e-06,-5.32248e-09,0.159919,0.000762554,1.05508e-06,4.8927e-10,0.160683,0.000764666,1.05654e-06,3.36547e-09,0.161448,0.000766789,1.06664e-06,9.50081e-10,0.162216,0.000768925,1.06949e-06,-7.16568e-09,0.162986,0.000771043,1.04799e-06,1.28114e-08,0.163758,0.000773177,1.08643e-06,-1.42774e-08,0.164533,0.000775307,1.0436e-06,1.44956e-08,0.165309,0.000777438,1.08708e-06,-1.39025e-08,0.166087,0.00077957,1.04538e-06,1.13118e-08,0.166868,0.000781695,1.07931e-06,-1.54224e-09,0.167651,0.000783849,1.07468e-06,-5.14312e-09,0.168436,0.000785983,1.05925e-06,7.21381e-09,0.169223,0.000788123,1.0809e-06,-8.81096e-09,0.170012,0.000790259,1.05446e-06,1.31289e-08,0.170803,0.000792407,1.09385e-06,-1.39022e-08,0.171597,0.000794553,1.05214e-06,1.26775e-08,0.172392,0.000796695,1.09018e-06,-7.00557e-09,0.17319,0.000798855,1.06916e-06,4.43796e-10,0.17399,0.000800994,1.07049e-06,5.23031e-09,0.174792,0.000803151,1.08618e-06,-6.46397e-09,0.175596,0.000805304,1.06679e-06,5.72444e-09,0.176403,0.000807455,1.08396e-06,-1.53254e-09,0.177211,0.000809618,1.07937e-06,4.05673e-10,0.178022,0.000811778,1.08058e-06,-9.01916e-11,0.178835,0.000813939,1.08031e-06,-4.49821e-11,0.17965,0.000816099,1.08018e-06,2.70234e-10,0.180467,0.00081826,1.08099e-06,-1.03603e-09,0.181286,0.000820419,1.07788e-06,3.87392e-09,0.182108,0.000822587,1.0895e-06,4.41522e-10,0.182932,0.000824767,1.09083e-06,-5.63997e-09,0.183758,0.000826932,1.07391e-06,7.21707e-09,0.184586,0.000829101,1.09556e-06,-8.32718e-09,0.185416,0.000831267,1.07058e-06,1.11907e-08,0.186248,0.000833442,1.10415e-06,-6.63336e-09,0.187083,0.00083563,1.08425e-06,4.41484e-10,0.187919,0.0008378,1.08557e-06,4.86754e-09,0.188758,0.000839986,1.10017e-06,-5.01041e-09,0.189599,0.000842171,1.08514e-06,2.72811e-10,0.190443,0.000844342,1.08596e-06,3.91916e-09,0.191288,0.000846526,1.09772e-06,-1.04819e-09,0.192136,0.000848718,1.09457e-06,2.73531e-10,0.192985,0.000850908,1.0954e-06,-4.58916e-11,0.193837,0.000853099,1.09526e-06,-9.01158e-11,0.194692,0.000855289,1.09499e-06,4.06506e-10,0.195548,0.00085748,1.09621e-06,-1.53595e-09,0.196407,0.000859668,1.0916e-06,5.73717e-09,0.197267,0.000861869,1.10881e-06,-6.51164e-09,0.19813,0.000864067,1.08928e-06,5.40831e-09,0.198995,0.000866261,1.1055e-06,-2.20401e-10,0.199863,0.000868472,1.10484e-06,-4.52652e-09,0.200732,0.000870668,1.09126e-06,3.42508e-09,0.201604,0.000872861,1.10153e-06,5.72762e-09,0.202478,0.000875081,1.11872e-06,-1.14344e-08,0.203354,0.000877284,1.08441e-06,1.02076e-08,0.204233,0.000879484,1.11504e-06,4.06355e-10,0.205113,0.000881715,1.11626e-06,-1.18329e-08,0.205996,0.000883912,1.08076e-06,1.71227e-08,0.206881,0.000886125,1.13213e-06,-1.19546e-08,0.207768,0.000888353,1.09626e-06,8.93465e-10,0.208658,0.000890548,1.09894e-06,8.38062e-09,0.209549,0.000892771,1.12408e-06,-4.61353e-09,0.210443,0.000895006,1.11024e-06,-4.82756e-09,0.211339,0.000897212,1.09576e-06,9.02245e-09,0.212238,0.00089943,1.12283e-06,-1.45997e-09,0.213138,0.000901672,1.11845e-06,-3.18255e-09,0.214041,0.000903899,1.1089e-06,-7.11073e-10,0.214946,0.000906115,1.10677e-06,6.02692e-09,0.215853,0.000908346,1.12485e-06,-8.49548e-09,0.216763,0.00091057,1.09936e-06,1.30537e-08,0.217675,0.000912808,1.13852e-06,-1.3917e-08,0.218588,0.000915044,1.09677e-06,1.28121e-08,0.219505,0.000917276,1.13521e-06,-7.5288e-09,0.220423,0.000919523,1.11262e-06,2.40205e-09,0.221344,0.000921756,1.11983e-06,-2.07941e-09,0.222267,0.000923989,1.11359e-06,5.91551e-09,0.223192,0.000926234,1.13134e-06,-6.68149e-09,0.224119,0.000928477,1.11129e-06,5.90929e-09,0.225049,0.000930717,1.12902e-06,-2.05436e-09,0.22598,0.000932969,1.12286e-06,2.30807e-09,0.226915,0.000935222,1.12978e-06,-7.17796e-09,0.227851,0.00093746,1.10825e-06,1.15028e-08,0.228789,0.000939711,1.14276e-06,-9.03083e-09,0.22973,0.000941969,1.11566e-06,9.71932e-09,0.230673,0.00094423,1.14482e-06,-1.49452e-08,0.231619,0.000946474,1.09998e-06,2.02591e-08,0.232566,0.000948735,1.16076e-06,-2.13879e-08,0.233516,0.000950993,1.0966e-06,2.05888e-08,0.234468,0.000953247,1.15837e-06,-1.62642e-08,0.235423,0.000955515,1.10957e-06,1.46658e-08,0.236379,0.000957779,1.15357e-06,-1.25966e-08,0.237338,0.000960048,1.11578e-06,5.91793e-09,0.238299,0.000962297,1.13353e-06,3.82602e-09,0.239263,0.000964576,1.14501e-06,-6.3208e-09,0.240229,0.000966847,1.12605e-06,6.55613e-09,0.241197,0.000969119,1.14572e-06,-5.00268e-09,0.242167,0.000971395,1.13071e-06,-1.44659e-09,0.243139,0.000973652,1.12637e-06,1.07891e-08,0.244114,0.000975937,1.15874e-06,-1.19073e-08,0.245091,0.000978219,1.12302e-06,7.03782e-09,0.246071,0.000980486,1.14413e-06,-1.34276e-09,0.247052,0.00098277,1.1401e-06,-1.66669e-09,0.248036,0.000985046,1.1351e-06,8.00935e-09,0.249022,0.00098734,1.15913e-06,-1.54694e-08,0.250011,0.000989612,1.11272e-06,2.4066e-08,0.251002,0.000991909,1.18492e-06,-2.11901e-08,0.251995,0.000994215,1.12135e-06,1.08973e-09,0.25299,0.000996461,1.12462e-06,1.68311e-08,0.253988,0.000998761,1.17511e-06,-8.8094e-09,0.254987,0.00100109,1.14868e-06,-1.13958e-08,0.25599,0.00100335,1.1145e-06,2.45902e-08,0.256994,0.00100565,1.18827e-06,-2.73603e-08,0.258001,0.00100795,1.10618e-06,2.52464e-08,0.25901,0.00101023,1.18192e-06,-1.40207e-08,0.260021,0.00101256,1.13986e-06,1.03387e-09,0.261035,0.00101484,1.14296e-06,9.8853e-09,0.262051,0.00101715,1.17262e-06,-1.07726e-08,0.263069,0.00101947,1.1403e-06,3.40272e-09,0.26409,0.00102176,1.15051e-06,-2.83827e-09,0.265113,0.00102405,1.142e-06,7.95039e-09,0.266138,0.00102636,1.16585e-06,8.39047e-10,0.267166,0.00102869,1.16836e-06,-1.13066e-08,0.268196,0.00103099,1.13444e-06,1.4585e-08,0.269228,0.00103331,1.1782e-06,-1.72314e-08,0.270262,0.00103561,1.1265e-06,2.45382e-08,0.271299,0.00103794,1.20012e-06,-2.13166e-08,0.272338,0.00104028,1.13617e-06,1.12364e-09,0.273379,0.00104255,1.13954e-06,1.68221e-08,0.274423,0.00104488,1.19001e-06,-8.80736e-09,0.275469,0.00104723,1.16358e-06,-1.13948e-08,0.276518,0.00104953,1.1294e-06,2.45839e-08,0.277568,0.00105186,1.20315e-06,-2.73361e-08,0.278621,0.00105418,1.12114e-06,2.51559e-08,0.279677,0.0010565,1.19661e-06,-1.36832e-08,0.280734,0.00105885,1.15556e-06,-2.25706e-10,0.281794,0.00106116,1.15488e-06,1.45862e-08,0.282857,0.00106352,1.19864e-06,-2.83167e-08,0.283921,0.00106583,1.11369e-06,3.90759e-08,0.284988,0.00106817,1.23092e-06,-3.85801e-08,0.286058,0.00107052,1.11518e-06,2.58375e-08,0.287129,0.00107283,1.19269e-06,-5.16498e-09,0.288203,0.0010752,1.1772e-06,-5.17768e-09,0.28928,0.00107754,1.16167e-06,-3.92671e-09,0.290358,0.00107985,1.14988e-06,2.08846e-08,0.29144,0.00108221,1.21254e-06,-2.00072e-08,0.292523,0.00108458,1.15252e-06,-4.60659e-10,0.293609,0.00108688,1.15114e-06,2.18499e-08,0.294697,0.00108925,1.21669e-06,-2.73343e-08,0.295787,0.0010916,1.13468e-06,2.78826e-08,0.29688,0.00109395,1.21833e-06,-2.45915e-08,0.297975,0.00109632,1.14456e-06,1.08787e-08,0.299073,0.00109864,1.17719e-06,1.08788e-08,0.300172,0.00110102,1.20983e-06,-2.45915e-08,0.301275,0.00110337,1.13605e-06,2.78828e-08,0.302379,0.00110573,1.2197e-06,-2.73348e-08,0.303486,0.00110808,1.1377e-06,2.18518e-08,0.304595,0.00111042,1.20325e-06,-4.67556e-10,0.305707,0.00111283,1.20185e-06,-1.99816e-08,0.306821,0.00111517,1.14191e-06,2.07891e-08,0.307937,0.00111752,1.20427e-06,-3.57026e-09,0.309056,0.00111992,1.19356e-06,-6.50797e-09,0.310177,0.00112228,1.17404e-06,-2.00165e-10,0.3113,0.00112463,1.17344e-06,7.30874e-09,0.312426,0.001127,1.19536e-06,7.67424e-10,0.313554,0.00112939,1.19767e-06,-1.03784e-08,0.314685,0.00113176,1.16653e-06,1.09437e-08,0.315818,0.00113412,1.19936e-06,-3.59406e-09,0.316953,0.00113651,1.18858e-06,3.43251e-09,0.318091,0.0011389,1.19888e-06,-1.0136e-08,0.319231,0.00114127,1.16847e-06,7.30915e-09,0.320374,0.00114363,1.1904e-06,1.07018e-08,0.321518,0.00114604,1.2225e-06,-2.03137e-08,0.322666,0.00114842,1.16156e-06,1.09484e-08,0.323815,0.00115078,1.19441e-06,6.32224e-09,0.324967,0.00115319,1.21337e-06,-6.43509e-09,0.326122,0.00115559,1.19407e-06,-1.03842e-08,0.327278,0.00115795,1.16291e-06,1.81697e-08,0.328438,0.00116033,1.21742e-06,-2.6901e-09,0.329599,0.00116276,1.20935e-06,-7.40939e-09,0.330763,0.00116515,1.18713e-06,2.52533e-09,0.331929,0.00116754,1.1947e-06,-2.69191e-09,0.333098,0.00116992,1.18663e-06,8.24218e-09,0.334269,0.00117232,1.21135e-06,-4.74377e-10,0.335443,0.00117474,1.20993e-06,-6.34471e-09,0.336619,0.00117714,1.1909e-06,-3.94922e-09,0.337797,0.00117951,1.17905e-06,2.21417e-08,0.338978,0.00118193,1.24547e-06,-2.50128e-08,0.340161,0.00118435,1.17043e-06,1.8305e-08,0.341346,0.00118674,1.22535e-06,-1.84048e-08,0.342534,0.00118914,1.17013e-06,2.55121e-08,0.343725,0.00119156,1.24667e-06,-2.40389e-08,0.344917,0.00119398,1.17455e-06,1.10389e-08,0.346113,0.00119636,1.20767e-06,9.68574e-09,0.34731,0.0011988,1.23673e-06,-1.99797e-08,0.34851,0.00120122,1.17679e-06,1.06284e-08,0.349713,0.0012036,1.20867e-06,7.26868e-09,0.350917,0.00120604,1.23048e-06,-9.90072e-09,0.352125,0.00120847,1.20078e-06,2.53177e-09,0.353334,0.00121088,1.20837e-06,-2.26199e-10,0.354546,0.0012133,1.20769e-06,-1.62705e-09,0.355761,0.00121571,1.20281e-06,6.73435e-09,0.356978,0.00121813,1.22302e-06,4.49207e-09,0.358197,0.00122059,1.23649e-06,-2.47027e-08,0.359419,0.00122299,1.16238e-06,3.47142e-08,0.360643,0.00122542,1.26653e-06,-2.47472e-08,0.36187,0.00122788,1.19229e-06,4.66965e-09,0.363099,0.00123028,1.20629e-06,6.06872e-09,0.36433,0.00123271,1.2245e-06,8.57729e-10,0.365564,0.00123516,1.22707e-06,-9.49952e-09,0.366801,0.00123759,1.19858e-06,7.33792e-09,0.36804,0.00124001,1.22059e-06,9.95025e-09,0.369281,0.00124248,1.25044e-06,-1.73366e-08,0.370525,0.00124493,1.19843e-06,-2.08464e-10,0.371771,0.00124732,1.1978e-06,1.81704e-08,0.373019,0.00124977,1.25232e-06,-1.28683e-08,0.37427,0.00125224,1.21371e-06,3.50042e-09,0.375524,0.00125468,1.22421e-06,-1.1335e-09,0.37678,0.00125712,1.22081e-06,1.03345e-09,0.378038,0.00125957,1.22391e-06,-3.00023e-09,0.379299,0.00126201,1.21491e-06,1.09676e-08,0.380562,0.00126447,1.24781e-06,-1.10676e-08,0.381828,0.00126693,1.21461e-06,3.50042e-09,0.383096,0.00126937,1.22511e-06,-2.93403e-09,0.384366,0.00127181,1.21631e-06,8.23574e-09,0.385639,0.00127427,1.24102e-06,-2.06607e-10,0.386915,0.00127675,1.2404e-06,-7.40935e-09,0.388193,0.00127921,1.21817e-06,4.1761e-11,0.389473,0.00128165,1.21829e-06,7.24223e-09,0.390756,0.0012841,1.24002e-06,7.91564e-10,0.392042,0.00128659,1.2424e-06,-1.04086e-08,0.393329,0.00128904,1.21117e-06,1.10405e-08,0.39462,0.0012915,1.24429e-06,-3.951e-09,0.395912,0.00129397,1.23244e-06,4.7634e-09,0.397208,0.00129645,1.24673e-06,-1.51025e-08,0.398505,0.0012989,1.20142e-06,2.58443e-08,0.399805,0.00130138,1.27895e-06,-2.86702e-08,0.401108,0.00130385,1.19294e-06,2.92318e-08,0.402413,0.00130632,1.28064e-06,-2.86524e-08,0.403721,0.0013088,1.19468e-06,2.57731e-08,0.405031,0.00131127,1.272e-06,-1.48355e-08,0.406343,0.00131377,1.2275e-06,3.76652e-09,0.407658,0.00131623,1.23879e-06,-2.30784e-10,0.408976,0.00131871,1.2381e-06,-2.84331e-09,0.410296,0.00132118,1.22957e-06,1.16041e-08,0.411618,0.00132367,1.26438e-06,-1.37708e-08,0.412943,0.00132616,1.22307e-06,1.36768e-08,0.41427,0.00132865,1.2641e-06,-1.1134e-08,0.4156,0.00133114,1.2307e-06,1.05714e-09,0.416933,0.00133361,1.23387e-06,6.90538e-09,0.418267,0.00133609,1.25459e-06,1.12372e-09,0.419605,0.00133861,1.25796e-06,-1.14002e-08,0.420945,0.00134109,1.22376e-06,1.46747e-08,0.422287,0.00134358,1.26778e-06,-1.7496e-08,0.423632,0.00134606,1.21529e-06,2.5507e-08,0.424979,0.00134857,1.29182e-06,-2.49272e-08,0.426329,0.00135108,1.21703e-06,1.45972e-08,0.427681,0.00135356,1.26083e-06,-3.65935e-09,0.429036,0.00135607,1.24985e-06,4.00178e-11,0.430393,0.00135857,1.24997e-06,3.49917e-09,0.431753,0.00136108,1.26047e-06,-1.40366e-08,0.433116,0.00136356,1.21836e-06,2.28448e-08,0.43448,0.00136606,1.28689e-06,-1.77378e-08,0.435848,0.00136858,1.23368e-06,1.83043e-08,0.437218,0.0013711,1.28859e-06,-2.56769e-08,0.43859,0.0013736,1.21156e-06,2.47987e-08,0.439965,0.0013761,1.28595e-06,-1.39133e-08,0.441342,0.00137863,1.24421e-06,1.05202e-09,0.442722,0.00138112,1.24737e-06,9.70507e-09,0.444104,0.00138365,1.27649e-06,-1.00698e-08,0.445489,0.00138617,1.24628e-06,7.72123e-10,0.446877,0.00138867,1.24859e-06,6.98132e-09,0.448267,0.00139118,1.26954e-06,1.10477e-09,0.449659,0.00139373,1.27285e-06,-1.14003e-08,0.451054,0.00139624,1.23865e-06,1.4694e-08,0.452452,0.00139876,1.28273e-06,-1.75734e-08,0.453852,0.00140127,1.23001e-06,2.5797e-08,0.455254,0.00140381,1.3074e-06,-2.60097e-08,0.456659,0.00140635,1.22937e-06,1.86371e-08,0.458067,0.00140886,1.28529e-06,-1.8736e-08,0.459477,0.00141137,1.22908e-06,2.65048e-08,0.46089,0.00141391,1.30859e-06,-2.76784e-08,0.462305,0.00141645,1.22556e-06,2.46043e-08,0.463722,0.00141897,1.29937e-06,-1.11341e-08,0.465143,0.00142154,1.26597e-06,-9.87033e-09,0.466565,0.00142404,1.23636e-06,2.08131e-08,0.467991,0.00142657,1.2988e-06,-1.37773e-08,0.469419,0.00142913,1.25746e-06,4.49378e-09,0.470849,0.00143166,1.27094e-06,-4.19781e-09,0.472282,0.00143419,1.25835e-06,1.22975e-08,0.473717,0.00143674,1.29524e-06,-1.51902e-08,0.475155,0.00143929,1.24967e-06,1.86608e-08,0.476596,0.00144184,1.30566e-06,-2.96506e-08,0.478039,0.00144436,1.2167e-06,4.03368e-08,0.479485,0.00144692,1.33771e-06,-4.22896e-08,0.480933,0.00144947,1.21085e-06,3.94148e-08,0.482384,0.00145201,1.32909e-06,-2.59626e-08,0.483837,0.00145459,1.2512e-06,4.83124e-09,0.485293,0.0014571,1.2657e-06,6.63757e-09,0.486751,0.00145966,1.28561e-06,-1.57911e-09,0.488212,0.00146222,1.28087e-06,-3.21468e-10,0.489676,0.00146478,1.27991e-06,2.86517e-09,0.491142,0.00146735,1.2885e-06,-1.11392e-08,0.49261,0.00146989,1.25508e-06,1.18893e-08,0.494081,0.00147244,1.29075e-06,-6.61574e-09,0.495555,0.001475,1.27091e-06,1.45736e-08,0.497031,0.00147759,1.31463e-06,-2.18759e-08,0.49851,0.00148015,1.249e-06,1.33252e-08,0.499992,0.00148269,1.28897e-06,-1.62277e-09,0.501476,0.00148526,1.28411e-06,-6.83421e-09,0.502962,0.00148781,1.2636e-06,2.89596e-08,0.504451,0.00149042,1.35048e-06,-4.93997e-08,0.505943,0.00149298,1.20228e-06,4.94299e-08,0.507437,0.00149553,1.35057e-06,-2.91107e-08,0.508934,0.00149814,1.26324e-06,7.40848e-09,0.510434,0.00150069,1.28547e-06,-5.23187e-10,0.511936,0.00150326,1.2839e-06,-5.31585e-09,0.51344,0.00150581,1.26795e-06,2.17866e-08,0.514947,0.00150841,1.33331e-06,-2.22257e-08,0.516457,0.00151101,1.26663e-06,7.51178e-09,0.517969,0.00151357,1.28917e-06,-7.82128e-09,0.519484,0.00151613,1.2657e-06,2.37733e-08,0.521002,0.00151873,1.33702e-06,-2.76674e-08,0.522522,0.00152132,1.25402e-06,2.72917e-08,0.524044,0.00152391,1.3359e-06,-2.18949e-08,0.525569,0.00152652,1.27021e-06,6.83372e-10,0.527097,0.00152906,1.27226e-06,1.91613e-08,0.528628,0.00153166,1.32974e-06,-1.77241e-08,0.53016,0.00153427,1.27657e-06,-7.86963e-09,0.531696,0.0015368,1.25296e-06,4.92027e-08,0.533234,0.00153945,1.40057e-06,-6.9732e-08,0.534775,0.00154204,1.19138e-06,5.09114e-08,0.536318,0.00154458,1.34411e-06,-1.4704e-08,0.537864,0.00154722,1.3e-06,7.9048e-09,0.539413,0.00154984,1.32371e-06,-1.69152e-08,0.540964,0.00155244,1.27297e-06,1.51355e-10,0.542517,0.00155499,1.27342e-06,1.63099e-08,0.544074,0.00155758,1.32235e-06,-5.78647e-09,0.545633,0.00156021,1.30499e-06,6.83599e-09,0.547194,0.00156284,1.3255e-06,-2.15575e-08,0.548758,0.00156543,1.26083e-06,1.97892e-08,0.550325,0.00156801,1.32019e-06,2.00525e-09,0.551894,0.00157065,1.32621e-06,-2.78103e-08,0.553466,0.00157322,1.24278e-06,4.96314e-08,0.555041,0.00157586,1.39167e-06,-5.1506e-08,0.556618,0.00157849,1.23716e-06,3.71835e-08,0.558198,0.00158107,1.34871e-06,-3.76233e-08,0.55978,0.00158366,1.23584e-06,5.37052e-08,0.561365,0.00158629,1.39695e-06,-5.79884e-08,0.562953,0.00158891,1.22299e-06,5.90392e-08,0.564543,0.00159153,1.4001e-06,-5.89592e-08,0.566136,0.00159416,1.22323e-06,5.7588e-08,0.567731,0.00159678,1.39599e-06,-5.21835e-08,0.569329,0.00159941,1.23944e-06,3.19369e-08,0.57093,0.00160199,1.33525e-06,-1.59594e-08,0.572533,0.00160461,1.28737e-06,3.19006e-08,0.574139,0.00160728,1.38307e-06,-5.20383e-08,0.575748,0.00160989,1.22696e-06,5.70431e-08,0.577359,0.00161251,1.39809e-06,-5.69247e-08,0.578973,0.00161514,1.22731e-06,5.14463e-08,0.580589,0.00161775,1.38165e-06,-2.9651e-08,0.582208,0.00162042,1.2927e-06,7.55339e-09,0.58383,0.00162303,1.31536e-06,-5.62636e-10,0.585455,0.00162566,1.31367e-06,-5.30281e-09,0.587081,0.00162827,1.29776e-06,2.17738e-08,0.588711,0.00163093,1.36309e-06,-2.21875e-08,0.590343,0.00163359,1.29652e-06,7.37164e-09,0.591978,0.00163621,1.31864e-06,-7.29907e-09,0.593616,0.00163882,1.29674e-06,2.18247e-08,0.595256,0.00164148,1.36221e-06,-2.03952e-08,0.596899,0.00164414,1.30103e-06,1.51241e-10,0.598544,0.00164675,1.30148e-06,1.97902e-08,0.600192,0.00164941,1.36085e-06,-1.97074e-08,0.601843,0.00165207,1.30173e-06,-5.65175e-10,0.603496,0.00165467,1.30004e-06,2.1968e-08,0.605152,0.00165734,1.36594e-06,-2.77024e-08,0.606811,0.00165999,1.28283e-06,2.92369e-08,0.608472,0.00166264,1.37054e-06,-2.96407e-08,0.610136,0.00166529,1.28162e-06,2.97215e-08,0.611803,0.00166795,1.37079e-06,-2.96408e-08,0.613472,0.0016706,1.28186e-06,2.92371e-08,0.615144,0.00167325,1.36957e-06,-2.77031e-08,0.616819,0.00167591,1.28647e-06,2.19708e-08,0.618496,0.00167855,1.35238e-06,-5.75407e-10,0.620176,0.00168125,1.35065e-06,-1.9669e-08,0.621858,0.00168389,1.29164e-06,1.96468e-08,0.623544,0.00168653,1.35058e-06,6.86403e-10,0.625232,0.00168924,1.35264e-06,-2.23924e-08,0.626922,0.00169187,1.28547e-06,2.92788e-08,0.628615,0.00169453,1.3733e-06,-3.51181e-08,0.630311,0.00169717,1.26795e-06,5.15889e-08,0.63201,0.00169987,1.42272e-06,-5.2028e-08,0.633711,0.00170255,1.26663e-06,3.73139e-08,0.635415,0.0017052,1.37857e-06,-3.76227e-08,0.637121,0.00170784,1.2657e-06,5.35722e-08,0.63883,0.00171054,1.42642e-06,-5.74567e-08,0.640542,0.00171322,1.25405e-06,5.70456e-08,0.642257,0.0017159,1.42519e-06,-5.15163e-08,0.643974,0.00171859,1.27064e-06,2.98103e-08,0.645694,0.00172122,1.36007e-06,-8.12016e-09,0.647417,0.00172392,1.33571e-06,2.67039e-09,0.649142,0.0017266,1.34372e-06,-2.56152e-09,0.65087,0.00172928,1.33604e-06,7.57571e-09,0.6526,0.00173197,1.35876e-06,-2.77413e-08,0.654334,0.00173461,1.27554e-06,4.3785e-08,0.65607,0.00173729,1.40689e-06,-2.81896e-08,0.657808,0.00174002,1.32233e-06,9.36893e-09,0.65955,0.00174269,1.35043e-06,-9.28617e-09,0.661294,0.00174536,1.32257e-06,2.77757e-08,0.66304,0.00174809,1.4059e-06,-4.2212e-08,0.66479,0.00175078,1.27926e-06,2.1863e-08,0.666542,0.0017534,1.34485e-06,1.43648e-08,0.668297,0.00175613,1.38795e-06,-1.97177e-08,0.670054,0.00175885,1.3288e-06,4.90115e-09,0.671814,0.00176152,1.3435e-06,1.13232e-10,0.673577,0.00176421,1.34384e-06,-5.3542e-09,0.675343,0.00176688,1.32778e-06,2.13035e-08,0.677111,0.0017696,1.39169e-06,-2.02553e-08,0.678882,0.00177232,1.33092e-06,1.13005e-10,0.680656,0.00177499,1.33126e-06,1.98031e-08,0.682432,0.00177771,1.39067e-06,-1.97211e-08,0.684211,0.00178043,1.33151e-06,-5.2349e-10,0.685993,0.00178309,1.32994e-06,2.18151e-08,0.687777,0.00178582,1.39538e-06,-2.71325e-08,0.689564,0.00178853,1.31398e-06,2.71101e-08,0.691354,0.00179124,1.39531e-06,-2.17035e-08,0.693147,0.00179396,1.3302e-06,9.92865e-11,0.694942,0.00179662,1.3305e-06,2.13063e-08,0.69674,0.00179935,1.39442e-06,-2.57198e-08,0.698541,0.00180206,1.31726e-06,2.19682e-08,0.700344,0.00180476,1.38317e-06,-2.54852e-09,0.70215,0.00180752,1.37552e-06,-1.17741e-08,0.703959,0.00181023,1.3402e-06,-9.95999e-09,0.705771,0.00181288,1.31032e-06,5.16141e-08,0.707585,0.00181566,1.46516e-06,-7.72869e-08,0.709402,0.00181836,1.2333e-06,7.87197e-08,0.711222,0.00182106,1.46946e-06,-5.87781e-08,0.713044,0.00182382,1.29312e-06,3.71834e-08,0.714869,0.00182652,1.40467e-06,-3.03511e-08,0.716697,0.00182924,1.31362e-06,2.46161e-08,0.718528,0.00183194,1.38747e-06,-8.5087e-09,0.720361,0.00183469,1.36194e-06,9.41892e-09,0.722197,0.00183744,1.3902e-06,-2.91671e-08,0.724036,0.00184014,1.3027e-06,4.76448e-08,0.725878,0.00184288,1.44563e-06,-4.22028e-08,0.727722,0.00184565,1.31902e-06,1.95682e-09,0.729569,0.00184829,1.3249e-06,3.43754e-08,0.731419,0.00185104,1.42802e-06,-2.0249e-08,0.733271,0.00185384,1.36727e-06,-1.29838e-08,0.735126,0.00185654,1.32832e-06,1.25794e-08,0.736984,0.00185923,1.36606e-06,2.22711e-08,0.738845,0.00186203,1.43287e-06,-4.20594e-08,0.740708,0.00186477,1.3067e-06,2.67571e-08,0.742574,0.00186746,1.38697e-06,-5.36424e-09,0.744443,0.00187022,1.37087e-06,-5.30023e-09,0.746315,0.00187295,1.35497e-06,2.65653e-08,0.748189,0.00187574,1.43467e-06,-4.13564e-08,0.750066,0.00187848,1.3106e-06,1.9651e-08,0.751946,0.00188116,1.36955e-06,2.23572e-08,0.753828,0.00188397,1.43663e-06,-4.9475e-08,0.755714,0.00188669,1.2882e-06,5.63335e-08,0.757602,0.00188944,1.4572e-06,-5.66499e-08,0.759493,0.00189218,1.28725e-06,5.10567e-08,0.761386,0.00189491,1.44042e-06,-2.83677e-08,0.763283,0.00189771,1.35532e-06,2.80962e-09,0.765182,0.00190042,1.36375e-06,1.71293e-08,0.767083,0.0019032,1.41513e-06,-1.17221e-08,0.768988,0.001906,1.37997e-06,-2.98453e-08,0.770895,0.00190867,1.29043e-06,7.14987e-08,0.772805,0.00191146,1.50493e-06,-7.73354e-08,0.774718,0.00191424,1.27292e-06,5.90292e-08,0.776634,0.00191697,1.45001e-06,-3.9572e-08,0.778552,0.00191975,1.33129e-06,3.9654e-08,0.780473,0.00192253,1.45026e-06,-5.94395e-08,0.782397,0.00192525,1.27194e-06,7.88945e-08,0.784324,0.00192803,1.50862e-06,-7.73249e-08,0.786253,0.00193082,1.27665e-06,5.15913e-08,0.788185,0.00193352,1.43142e-06,-9.83099e-09,0.79012,0.00193636,1.40193e-06,-1.22672e-08,0.792058,0.00193912,1.36513e-06,-7.05275e-10,0.793999,0.00194185,1.36301e-06,1.50883e-08,0.795942,0.00194462,1.40828e-06,-4.33147e-11,0.797888,0.00194744,1.40815e-06,-1.49151e-08,0.799837,0.00195021,1.3634e-06,9.93244e-11,0.801788,0.00195294,1.3637e-06,1.45179e-08,0.803743,0.00195571,1.40725e-06,1.43363e-09,0.8057,0.00195853,1.41155e-06,-2.02525e-08,0.80766,0.00196129,1.35079e-06,1.99718e-08,0.809622,0.00196405,1.41071e-06,-3.01649e-11,0.811588,0.00196687,1.41062e-06,-1.9851e-08,0.813556,0.00196964,1.35107e-06,1.98296e-08,0.815527,0.0019724,1.41056e-06,1.37485e-10,0.817501,0.00197522,1.41097e-06,-2.03796e-08,0.819477,0.00197798,1.34983e-06,2.17763e-08,0.821457,0.00198074,1.41516e-06,-7.12085e-09,0.823439,0.00198355,1.3938e-06,6.70707e-09,0.825424,0.00198636,1.41392e-06,-1.97074e-08,0.827412,0.00198913,1.35479e-06,1.25179e-08,0.829402,0.00199188,1.39235e-06,2.92405e-08,0.831396,0.00199475,1.48007e-06,-6.98755e-08,0.833392,0.0019975,1.27044e-06,7.14477e-08,0.835391,0.00200026,1.48479e-06,-3.71014e-08,0.837392,0.00200311,1.37348e-06,1.73533e-08,0.839397,0.00200591,1.42554e-06,-3.23118e-08,0.841404,0.00200867,1.32861e-06,5.2289e-08,0.843414,0.00201148,1.48547e-06,-5.76348e-08,0.845427,0.00201428,1.31257e-06,5.9041e-08,0.847443,0.00201708,1.48969e-06,-5.93197e-08,0.849461,0.00201988,1.31173e-06,5.90289e-08,0.851482,0.00202268,1.48882e-06,-5.75864e-08,0.853507,0.00202549,1.31606e-06,5.21075e-08,0.855533,0.00202828,1.47238e-06,-3.16344e-08,0.857563,0.00203113,1.37748e-06,1.48257e-08,0.859596,0.00203393,1.42196e-06,-2.76684e-08,0.861631,0.00203669,1.33895e-06,3.62433e-08,0.863669,0.00203947,1.44768e-06,1.90463e-09,0.86571,0.00204237,1.45339e-06,-4.38617e-08,0.867754,0.00204515,1.32181e-06,5.43328e-08,0.8698,0.00204796,1.48481e-06,-5.42603e-08,0.87185,0.00205076,1.32203e-06,4.34989e-08,0.873902,0.00205354,1.45252e-06,-5.26029e-10,0.875957,0.00205644,1.45095e-06,-4.13949e-08,0.878015,0.00205922,1.32676e-06,4.68962e-08,0.880075,0.00206201,1.46745e-06,-2.69807e-08,0.882139,0.00206487,1.38651e-06,1.42181e-09,0.884205,0.00206764,1.39077e-06,2.12935e-08,0.886274,0.00207049,1.45465e-06,-2.69912e-08,0.888346,0.00207332,1.37368e-06,2.70664e-08,0.890421,0.00207615,1.45488e-06,-2.16698e-08,0.892498,0.00207899,1.38987e-06,8.14756e-12,0.894579,0.00208177,1.38989e-06,2.16371e-08,0.896662,0.00208462,1.45481e-06,-2.6952e-08,0.898748,0.00208744,1.37395e-06,2.65663e-08,0.900837,0.00209027,1.45365e-06,-1.97084e-08,0.902928,0.00209312,1.39452e-06,-7.33731e-09,0.905023,0.00209589,1.37251e-06,4.90578e-08,0.90712,0.00209878,1.51968e-06,-6.96845e-08,0.90922,0.00210161,1.31063e-06,5.08664e-08,0.911323,0.00210438,1.46323e-06,-1.45717e-08,0.913429,0.00210727,1.41952e-06,7.42038e-09,0.915538,0.00211013,1.44178e-06,-1.51097e-08,0.917649,0.00211297,1.39645e-06,-6.58618e-09,0.919764,0.00211574,1.37669e-06,4.14545e-08,0.921881,0.00211862,1.50105e-06,-4.00222e-08,0.924001,0.0021215,1.38099e-06,-5.7518e-10,0.926124,0.00212426,1.37926e-06,4.23229e-08,0.92825,0.00212714,1.50623e-06,-4.9507e-08,0.930378,0.00213001,1.35771e-06,3.64958e-08,0.93251,0.00213283,1.4672e-06,-3.68713e-08,0.934644,0.00213566,1.35658e-06,5.13848e-08,0.936781,0.00213852,1.51074e-06,-4.94585e-08,0.938921,0.0021414,1.36236e-06,2.72399e-08,0.941064,0.0021442,1.44408e-06,1.0372e-10,0.943209,0.00214709,1.44439e-06,-2.76547e-08,0.945358,0.0021499,1.36143e-06,5.09106e-08,0.947509,0.00215277,1.51416e-06,-5.67784e-08,0.949663,0.00215563,1.34382e-06,5.69935e-08,0.95182,0.00215849,1.5148e-06,-5.19861e-08,0.95398,0.00216136,1.35885e-06,3.17417e-08,0.956143,0.00216418,1.45407e-06,-1.53758e-08,0.958309,0.00216704,1.40794e-06,2.97615e-08,0.960477,0.00216994,1.49723e-06,-4.40657e-08,0.962649,0.00217281,1.36503e-06,2.72919e-08,0.964823,0.00217562,1.44691e-06,-5.49729e-09,0.967,0.0021785,1.43041e-06,-5.30273e-09,0.96918,0.00218134,1.41451e-06,2.67084e-08,0.971363,0.00218425,1.49463e-06,-4.19265e-08,0.973548,0.00218711,1.36885e-06,2.17881e-08,0.975737,0.00218992,1.43422e-06,1.43789e-08,0.977928,0.00219283,1.47735e-06,-1.96989e-08,0.980122,0.00219572,1.41826e-06,4.81221e-09,0.98232,0.00219857,1.43269e-06,4.50048e-10,0.98452,0.00220144,1.43404e-06,-6.61237e-09,0.986722,0.00220429,1.41421e-06,2.59993e-08,0.988928,0.0022072,1.4922e-06,-3.77803e-08,0.991137,0.00221007,1.37886e-06,5.9127e-09,0.993348,0.00221284,1.3966e-06,1.33339e-07,0.995563,0.00221604,1.79662e-06,-5.98872e-07,0.99778,0.00222015,0.,0.}; + + template + __device__ __forceinline__ void RGB2LabConvert_f(const T& src, D& dst) + { + const float _1_3 = 1.0f / 3.0f; + const float _a = 16.0f / 116.0f; + + float B = blueIdx == 0 ? src.x : src.z; + float G = src.y; + float R = blueIdx == 0 ? src.z : src.x; + + if (srgb) + { + B = splineInterpolate(B * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); + G = splineInterpolate(G * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); + R = splineInterpolate(R * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); + } + + float X = B * 0.189828f + G * 0.376219f + R * 0.433953f; + float Y = B * 0.072169f + G * 0.715160f + R * 0.212671f; + float Z = B * 0.872766f + G * 0.109477f + R * 0.017758f; + + float FX = X > 0.008856f ? ::powf(X, _1_3) : (7.787f * X + _a); + float FY = Y > 0.008856f ? ::powf(Y, _1_3) : (7.787f * Y + _a); + float FZ = Z > 0.008856f ? ::powf(Z, _1_3) : (7.787f * Z + _a); + + float L = Y > 0.008856f ? (116.f * FY - 16.f) : (903.3f * Y); + float a = 500.f * (FX - FY); + float b = 200.f * (FY - FZ); + + dst.x = L; + dst.y = a; + dst.z = b; + } + + template struct RGB2Lab; + template + struct RGB2Lab + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + RGB2LabConvert_b(src, dst); + + return dst; + } + __host__ __device__ __forceinline__ RGB2Lab() {} + __host__ __device__ __forceinline__ RGB2Lab(const RGB2Lab&) {} + }; + template + struct RGB2Lab + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + RGB2LabConvert_f(src, dst); + + return dst; + } + __host__ __device__ __forceinline__ RGB2Lab() {} + __host__ __device__ __forceinline__ RGB2Lab(const RGB2Lab&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(name, scn, dcn, srgb, blueIdx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2Lab functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + + namespace color_detail + { + __constant__ float c_sRGBInvGammaTab[] = {0,0.0126255,0.,-8.33961e-06,0.0126172,0.0126005,-2.50188e-05,4.1698e-05,0.0252344,0.0126756,0.000100075,-0.000158451,0.0378516,0.0124004,-0.000375277,-0.000207393,0.0496693,0.0110276,-0.000997456,0.00016837,0.0598678,0.00953783,-0.000492346,2.07235e-05,0.068934,0.00861531,-0.000430176,3.62876e-05,0.0771554,0.00786382,-0.000321313,1.87625e-05,0.0847167,0.00727748,-0.000265025,1.53594e-05,0.0917445,0.00679351,-0.000218947,1.10545e-05,0.0983301,0.00638877,-0.000185784,8.66984e-06,0.104542,0.00604322,-0.000159774,6.82996e-06,0.110432,0.00574416,-0.000139284,5.51008e-06,0.116042,0.00548212,-0.000122754,4.52322e-06,0.121406,0.00525018,-0.000109184,3.75557e-06,0.126551,0.00504308,-9.79177e-05,3.17134e-06,0.131499,0.00485676,-8.84037e-05,2.68469e-06,0.13627,0.004688,-8.03496e-05,2.31725e-06,0.14088,0.00453426,-7.33978e-05,2.00868e-06,0.145343,0.00439349,-6.73718e-05,1.74775e-06,0.149671,0.00426399,-6.21286e-05,1.53547e-06,0.153875,0.00414434,-5.75222e-05,1.364e-06,0.157963,0.00403338,-5.34301e-05,1.20416e-06,0.161944,0.00393014,-4.98177e-05,1.09114e-06,0.165825,0.00383377,-4.65443e-05,9.57987e-07,0.169613,0.00374356,-4.36703e-05,8.88359e-07,0.173314,0.00365888,-4.10052e-05,7.7849e-07,0.176933,0.00357921,-3.86697e-05,7.36254e-07,0.180474,0.00350408,-3.6461e-05,6.42534e-07,0.183942,0.00343308,-3.45334e-05,6.12614e-07,0.187342,0.00336586,-3.26955e-05,5.42894e-07,0.190675,0.00330209,-3.10669e-05,5.08967e-07,0.193947,0.00324149,-2.954e-05,4.75977e-07,0.197159,0.00318383,-2.8112e-05,4.18343e-07,0.200315,0.00312887,-2.6857e-05,4.13651e-07,0.203418,0.00307639,-2.5616e-05,3.70847e-07,0.206469,0.00302627,-2.45035e-05,3.3813e-07,0.209471,0.00297828,-2.34891e-05,3.32999e-07,0.212426,0.0029323,-2.24901e-05,2.96826e-07,0.215336,0.00288821,-2.15996e-05,2.82736e-07,0.218203,0.00284586,-2.07514e-05,2.70961e-07,0.221029,0.00280517,-1.99385e-05,2.42744e-07,0.223814,0.00276602,-1.92103e-05,2.33277e-07,0.226561,0.0027283,-1.85105e-05,2.2486e-07,0.229271,0.00269195,-1.78359e-05,2.08383e-07,0.231945,0.00265691,-1.72108e-05,1.93305e-07,0.234585,0.00262307,-1.66308e-05,1.80687e-07,0.237192,0.00259035,-1.60888e-05,1.86632e-07,0.239766,0.00255873,-1.55289e-05,1.60569e-07,0.24231,0.00252815,-1.50472e-05,1.54566e-07,0.244823,0.00249852,-1.45835e-05,1.59939e-07,0.247307,0.00246983,-1.41037e-05,1.29549e-07,0.249763,0.00244202,-1.3715e-05,1.41429e-07,0.252191,0.00241501,-1.32907e-05,1.39198e-07,0.254593,0.00238885,-1.28731e-05,1.06444e-07,0.256969,0.00236342,-1.25538e-05,1.2048e-07,0.25932,0.00233867,-1.21924e-05,1.26892e-07,0.261647,0.00231467,-1.18117e-05,8.72084e-08,0.26395,0.00229131,-1.15501e-05,1.20323e-07,0.26623,0.00226857,-1.11891e-05,8.71514e-08,0.268487,0.00224645,-1.09276e-05,9.73165e-08,0.270723,0.00222489,-1.06357e-05,8.98259e-08,0.272937,0.00220389,-1.03662e-05,7.98218e-08,0.275131,0.00218339,-1.01267e-05,9.75254e-08,0.277304,0.00216343,-9.83416e-06,6.65195e-08,0.279458,0.00214396,-9.63461e-06,8.34313e-08,0.281592,0.00212494,-9.38431e-06,7.65919e-08,0.283708,0.00210641,-9.15454e-06,5.7236e-08,0.285805,0.00208827,-8.98283e-06,8.18939e-08,0.287885,0.00207055,-8.73715e-06,6.2224e-08,0.289946,0.00205326,-8.55047e-06,5.66388e-08,0.291991,0.00203633,-8.38056e-06,6.88491e-08,0.294019,0.00201978,-8.17401e-06,5.53955e-08,0.296031,0.00200359,-8.00782e-06,6.71971e-08,0.298027,0.00198778,-7.80623e-06,3.34439e-08,0.300007,0.00197227,-7.7059e-06,6.7248e-08,0.301971,0.00195706,-7.50416e-06,5.51915e-08,0.303921,0.00194221,-7.33858e-06,3.98124e-08,0.305856,0.00192766,-7.21915e-06,5.37795e-08,0.307776,0.00191338,-7.05781e-06,4.30919e-08,0.309683,0.00189939,-6.92853e-06,4.20744e-08,0.311575,0.00188566,-6.80231e-06,5.68321e-08,0.313454,0.00187223,-6.63181e-06,2.86195e-08,0.31532,0.00185905,-6.54595e-06,3.73075e-08,0.317172,0.00184607,-6.43403e-06,6.05684e-08,0.319012,0.00183338,-6.25233e-06,1.84426e-08,0.320839,0.00182094,-6.197e-06,4.44757e-08,0.322654,0.00180867,-6.06357e-06,4.20729e-08,0.324456,0.00179667,-5.93735e-06,2.56511e-08,0.326247,0.00178488,-5.8604e-06,3.41368e-08,0.328026,0.00177326,-5.75799e-06,4.64177e-08,0.329794,0.00176188,-5.61874e-06,1.86107e-08,0.33155,0.0017507,-5.5629e-06,2.81511e-08,0.333295,0.00173966,-5.47845e-06,4.75987e-08,0.335029,0.00172884,-5.33565e-06,1.98726e-08,0.336753,0.00171823,-5.27604e-06,2.19226e-08,0.338466,0.00170775,-5.21027e-06,4.14483e-08,0.340169,0.00169745,-5.08592e-06,2.09017e-08,0.341861,0.00168734,-5.02322e-06,2.39561e-08,0.343543,0.00167737,-4.95135e-06,3.22852e-08,0.345216,0.00166756,-4.85449e-06,2.57173e-08,0.346878,0.00165793,-4.77734e-06,1.38569e-08,0.348532,0.00164841,-4.73577e-06,3.80634e-08,0.350175,0.00163906,-4.62158e-06,1.27043e-08,0.35181,0.00162985,-4.58347e-06,3.03279e-08,0.353435,0.00162078,-4.49249e-06,1.49961e-08,0.355051,0.00161184,-4.4475e-06,2.88977e-08,0.356659,0.00160303,-4.3608e-06,1.84241e-08,0.358257,0.00159436,-4.30553e-06,1.6616e-08,0.359848,0.0015858,-4.25568e-06,3.43218e-08,0.361429,0.00157739,-4.15272e-06,-4.89172e-09,0.363002,0.00156907,-4.16739e-06,4.48498e-08,0.364567,0.00156087,-4.03284e-06,4.30676e-09,0.366124,0.00155282,-4.01992e-06,2.73303e-08,0.367673,0.00154486,-3.93793e-06,5.58036e-09,0.369214,0.001537,-3.92119e-06,3.97554e-08,0.370747,0.00152928,-3.80193e-06,-1.55904e-08,0.372272,0.00152163,-3.8487e-06,5.24081e-08,0.37379,0.00151409,-3.69147e-06,-1.52272e-08,0.375301,0.00150666,-3.73715e-06,3.83028e-08,0.376804,0.0014993,-3.62225e-06,1.10278e-08,0.378299,0.00149209,-3.58916e-06,6.99326e-09,0.379788,0.00148493,-3.56818e-06,2.06038e-08,0.381269,0.00147786,-3.50637e-06,2.98009e-08,0.382744,0.00147093,-3.41697e-06,-2.05978e-08,0.384211,0.00146404,-3.47876e-06,5.25899e-08,0.385672,0.00145724,-3.32099e-06,-1.09471e-08,0.387126,0.00145056,-3.35383e-06,2.10009e-08,0.388573,0.00144392,-3.29083e-06,1.63501e-08,0.390014,0.00143739,-3.24178e-06,3.00641e-09,0.391448,0.00143091,-3.23276e-06,3.12282e-08,0.392875,0.00142454,-3.13908e-06,-8.70932e-09,0.394297,0.00141824,-3.16521e-06,3.34114e-08,0.395712,0.00141201,-3.06497e-06,-5.72754e-09,0.397121,0.00140586,-3.08215e-06,1.9301e-08,0.398524,0.00139975,-3.02425e-06,1.7931e-08,0.39992,0.00139376,-2.97046e-06,-1.61822e-09,0.401311,0.00138781,-2.97531e-06,1.83442e-08,0.402696,0.00138192,-2.92028e-06,1.76485e-08,0.404075,0.00137613,-2.86733e-06,4.68617e-10,0.405448,0.00137039,-2.86593e-06,1.02794e-08,0.406816,0.00136469,-2.83509e-06,1.80179e-08,0.408178,0.00135908,-2.78104e-06,7.05594e-09,0.409534,0.00135354,-2.75987e-06,1.33633e-08,0.410885,0.00134806,-2.71978e-06,-9.04568e-10,0.41223,0.00134261,-2.72249e-06,2.0057e-08,0.41357,0.00133723,-2.66232e-06,1.00841e-08,0.414905,0.00133194,-2.63207e-06,-7.88835e-10,0.416234,0.00132667,-2.63444e-06,2.28734e-08,0.417558,0.00132147,-2.56582e-06,-1.29785e-09,0.418877,0.00131633,-2.56971e-06,1.21205e-08,0.420191,0.00131123,-2.53335e-06,1.24202e-08,0.421499,0.0013062,-2.49609e-06,-2.19681e-09,0.422803,0.0013012,-2.50268e-06,2.61696e-08,0.424102,0.00129628,-2.42417e-06,-1.30747e-08,0.425396,0.00129139,-2.46339e-06,2.6129e-08,0.426685,0.00128654,-2.38501e-06,-2.03454e-09,0.427969,0.00128176,-2.39111e-06,1.18115e-08,0.429248,0.00127702,-2.35567e-06,1.43932e-08,0.430523,0.00127235,-2.31249e-06,-9.77965e-09,0.431793,0.00126769,-2.34183e-06,2.47253e-08,0.433058,0.00126308,-2.26766e-06,2.85278e-10,0.434319,0.00125855,-2.2668e-06,3.93614e-09,0.435575,0.00125403,-2.25499e-06,1.37722e-08,0.436827,0.00124956,-2.21368e-06,5.79803e-10,0.438074,0.00124513,-2.21194e-06,1.37112e-08,0.439317,0.00124075,-2.1708e-06,4.17973e-09,0.440556,0.00123642,-2.15826e-06,-6.27703e-10,0.44179,0.0012321,-2.16015e-06,2.81332e-08,0.44302,0.00122787,-2.07575e-06,-2.24985e-08,0.444246,0.00122365,-2.14324e-06,3.20586e-08,0.445467,0.00121946,-2.04707e-06,-1.6329e-08,0.446685,0.00121532,-2.09605e-06,3.32573e-08,0.447898,0.00121122,-1.99628e-06,-2.72927e-08,0.449107,0.00120715,-2.07816e-06,4.6111e-08,0.450312,0.00120313,-1.93983e-06,-3.79416e-08,0.451514,0.00119914,-2.05365e-06,4.60507e-08,0.452711,0.00119517,-1.9155e-06,-2.7052e-08,0.453904,0.00119126,-1.99666e-06,3.23551e-08,0.455093,0.00118736,-1.89959e-06,-1.29613e-08,0.456279,0.00118352,-1.93848e-06,1.94905e-08,0.45746,0.0011797,-1.88e-06,-5.39588e-09,0.458638,0.00117593,-1.89619e-06,2.09282e-09,0.459812,0.00117214,-1.88991e-06,2.68267e-08,0.460982,0.00116844,-1.80943e-06,-1.99925e-08,0.462149,0.00116476,-1.86941e-06,2.3341e-08,0.463312,0.00116109,-1.79939e-06,-1.37674e-08,0.464471,0.00115745,-1.84069e-06,3.17287e-08,0.465627,0.00115387,-1.7455e-06,-2.37407e-08,0.466779,0.00115031,-1.81673e-06,3.34315e-08,0.467927,0.00114677,-1.71643e-06,-2.05786e-08,0.469073,0.00114328,-1.77817e-06,1.90802e-08,0.470214,0.00113978,-1.72093e-06,3.86247e-09,0.471352,0.00113635,-1.70934e-06,-4.72759e-09,0.472487,0.00113292,-1.72352e-06,1.50478e-08,0.473618,0.00112951,-1.67838e-06,4.14108e-09,0.474746,0.00112617,-1.66595e-06,-1.80986e-09,0.47587,0.00112283,-1.67138e-06,3.09816e-09,0.476991,0.0011195,-1.66209e-06,1.92198e-08,0.478109,0.00111623,-1.60443e-06,-2.03726e-08,0.479224,0.00111296,-1.66555e-06,3.2468e-08,0.480335,0.00110973,-1.56814e-06,-2.00922e-08,0.481443,0.00110653,-1.62842e-06,1.80983e-08,0.482548,0.00110333,-1.57413e-06,7.30362e-09,0.48365,0.0011002,-1.55221e-06,-1.75107e-08,0.484749,0.00109705,-1.60475e-06,3.29373e-08,0.485844,0.00109393,-1.50594e-06,-2.48315e-08,0.486937,0.00109085,-1.58043e-06,3.65865e-08,0.488026,0.0010878,-1.47067e-06,-3.21078e-08,0.489112,0.00108476,-1.56699e-06,3.22397e-08,0.490195,0.00108172,-1.47027e-06,-7.44391e-09,0.491276,0.00107876,-1.49261e-06,-2.46428e-09,0.492353,0.00107577,-1.5e-06,1.73011e-08,0.493427,0.00107282,-1.4481e-06,-7.13552e-09,0.494499,0.0010699,-1.4695e-06,1.1241e-08,0.495567,0.001067,-1.43578e-06,-8.02637e-09,0.496633,0.0010641,-1.45986e-06,2.08645e-08,0.497695,0.00106124,-1.39726e-06,-1.58271e-08,0.498755,0.0010584,-1.44475e-06,1.26415e-08,0.499812,0.00105555,-1.40682e-06,2.48655e-08,0.500866,0.00105281,-1.33222e-06,-5.24988e-08,0.501918,0.00104999,-1.48972e-06,6.59206e-08,0.502966,0.00104721,-1.29196e-06,-3.237e-08,0.504012,0.00104453,-1.38907e-06,3.95479e-09,0.505055,0.00104176,-1.3772e-06,1.65509e-08,0.506096,0.00103905,-1.32755e-06,-1.05539e-08,0.507133,0.00103637,-1.35921e-06,2.56648e-08,0.508168,0.00103373,-1.28222e-06,-3.25007e-08,0.509201,0.00103106,-1.37972e-06,4.47336e-08,0.51023,0.00102844,-1.24552e-06,-2.72245e-08,0.511258,0.00102587,-1.32719e-06,4.55952e-09,0.512282,0.00102323,-1.31352e-06,8.98645e-09,0.513304,0.00102063,-1.28656e-06,1.90992e-08,0.514323,0.00101811,-1.22926e-06,-2.57786e-08,0.51534,0.00101557,-1.30659e-06,2.44104e-08,0.516355,0.00101303,-1.23336e-06,-1.22581e-08,0.517366,0.00101053,-1.27014e-06,2.4622e-08,0.518376,0.00100806,-1.19627e-06,-2.66253e-08,0.519383,0.00100559,-1.27615e-06,2.22744e-08,0.520387,0.00100311,-1.20932e-06,-2.8679e-09,0.521389,0.00100068,-1.21793e-06,-1.08029e-08,0.522388,0.000998211,-1.25034e-06,4.60795e-08,0.523385,0.000995849,-1.1121e-06,-5.4306e-08,0.52438,0.000993462,-1.27502e-06,5.19354e-08,0.525372,0.000991067,-1.11921e-06,-3.42262e-08,0.526362,0.000988726,-1.22189e-06,2.53646e-08,0.52735,0.000986359,-1.14579e-06,-7.62782e-09,0.528335,0.000984044,-1.16868e-06,5.14668e-09,0.529318,0.000981722,-1.15324e-06,-1.29589e-08,0.530298,0.000979377,-1.19211e-06,4.66888e-08,0.531276,0.000977133,-1.05205e-06,-5.45868e-08,0.532252,0.000974865,-1.21581e-06,5.24495e-08,0.533226,0.000972591,-1.05846e-06,-3.60019e-08,0.534198,0.000970366,-1.16647e-06,3.19537e-08,0.535167,0.000968129,-1.07061e-06,-3.2208e-08,0.536134,0.000965891,-1.16723e-06,3.72738e-08,0.537099,0.000963668,-1.05541e-06,2.32205e-09,0.538061,0.000961564,-1.04844e-06,-4.65618e-08,0.539022,0.000959328,-1.18813e-06,6.47159e-08,0.53998,0.000957146,-9.93979e-07,-3.3488e-08,0.540936,0.000955057,-1.09444e-06,9.63166e-09,0.54189,0.000952897,-1.06555e-06,-5.03871e-09,0.542842,0.000950751,-1.08066e-06,1.05232e-08,0.543792,0.000948621,-1.04909e-06,2.25503e-08,0.544739,0.000946591,-9.81444e-07,-4.11195e-08,0.545685,0.000944504,-1.1048e-06,2.27182e-08,0.546628,0.000942363,-1.03665e-06,9.85146e-09,0.54757,0.000940319,-1.00709e-06,-2.51938e-09,0.548509,0.000938297,-1.01465e-06,2.25858e-10,0.549446,0.000936269,-1.01397e-06,1.61598e-09,0.550381,0.000934246,-1.00913e-06,-6.68983e-09,0.551315,0.000932207,-1.0292e-06,2.51434e-08,0.552246,0.000930224,-9.53765e-07,-3.42793e-08,0.553175,0.000928214,-1.0566e-06,5.23688e-08,0.554102,0.000926258,-8.99497e-07,-5.59865e-08,0.555028,0.000924291,-1.06746e-06,5.23679e-08,0.555951,0.000922313,-9.10352e-07,-3.42763e-08,0.556872,0.00092039,-1.01318e-06,2.51326e-08,0.557792,0.000918439,-9.37783e-07,-6.64954e-09,0.558709,0.000916543,-9.57732e-07,1.46554e-09,0.559625,0.000914632,-9.53335e-07,7.87281e-10,0.560538,0.000912728,-9.50973e-07,-4.61466e-09,0.56145,0.000910812,-9.64817e-07,1.76713e-08,0.56236,0.000908935,-9.11804e-07,-6.46564e-09,0.563268,0.000907092,-9.312e-07,8.19121e-09,0.564174,0.000905255,-9.06627e-07,-2.62992e-08,0.565078,0.000903362,-9.85524e-07,3.74007e-08,0.565981,0.000901504,-8.73322e-07,-4.0942e-09,0.566882,0.000899745,-8.85605e-07,-2.1024e-08,0.56778,0.00089791,-9.48677e-07,2.85854e-08,0.568677,0.000896099,-8.62921e-07,-3.3713e-08,0.569573,0.000894272,-9.64059e-07,4.6662e-08,0.570466,0.000892484,-8.24073e-07,-3.37258e-08,0.571358,0.000890734,-9.25251e-07,2.86365e-08,0.572247,0.00088897,-8.39341e-07,-2.12155e-08,0.573135,0.000887227,-9.02988e-07,-3.37913e-09,0.574022,0.000885411,-9.13125e-07,3.47319e-08,0.574906,0.000883689,-8.08929e-07,-1.63394e-08,0.575789,0.000882022,-8.57947e-07,-2.8979e-08,0.57667,0.00088022,-9.44885e-07,7.26509e-08,0.57755,0.000878548,-7.26932e-07,-8.28106e-08,0.578427,0.000876845,-9.75364e-07,7.97774e-08,0.579303,0.000875134,-7.36032e-07,-5.74849e-08,0.580178,0.00087349,-9.08486e-07,3.09529e-08,0.58105,0.000871765,-8.15628e-07,-6.72206e-09,0.581921,0.000870114,-8.35794e-07,-4.06451e-09,0.582791,0.00086843,-8.47987e-07,2.29799e-08,0.583658,0.000866803,-7.79048e-07,-2.82503e-08,0.584524,0.00086516,-8.63799e-07,3.04167e-08,0.585388,0.000863524,-7.72548e-07,-3.38119e-08,0.586251,0.000861877,-8.73984e-07,4.52264e-08,0.587112,0.000860265,-7.38305e-07,-2.78842e-08,0.587972,0.000858705,-8.21958e-07,6.70567e-09,0.58883,0.000857081,-8.01841e-07,1.06161e-09,0.589686,0.000855481,-7.98656e-07,-1.09521e-08,0.590541,0.00085385,-8.31512e-07,4.27468e-08,0.591394,0.000852316,-7.03272e-07,-4.08257e-08,0.592245,0.000850787,-8.25749e-07,1.34677e-09,0.593095,0.000849139,-8.21709e-07,3.54387e-08,0.593944,0.000847602,-7.15393e-07,-2.38924e-08,0.59479,0.0008461,-7.8707e-07,5.26143e-10,0.595636,0.000844527,-7.85491e-07,2.17879e-08,0.596479,0.000843021,-7.20127e-07,-2.80733e-08,0.597322,0.000841497,-8.04347e-07,3.09005e-08,0.598162,0.000839981,-7.11646e-07,-3.5924e-08,0.599002,0.00083845,-8.19418e-07,5.3191e-08,0.599839,0.000836971,-6.59845e-07,-5.76307e-08,0.600676,0.000835478,-8.32737e-07,5.81227e-08,0.60151,0.000833987,-6.58369e-07,-5.56507e-08,0.602344,0.000832503,-8.25321e-07,4.52706e-08,0.603175,0.000830988,-6.89509e-07,-6.22236e-09,0.604006,0.000829591,-7.08176e-07,-2.03811e-08,0.604834,0.000828113,-7.6932e-07,2.8142e-08,0.605662,0.000826659,-6.84894e-07,-3.25822e-08,0.606488,0.000825191,-7.8264e-07,4.25823e-08,0.607312,0.000823754,-6.54893e-07,-1.85376e-08,0.608135,0.000822389,-7.10506e-07,-2.80365e-08,0.608957,0.000820883,-7.94616e-07,7.1079e-08,0.609777,0.000819507,-5.81379e-07,-7.74655e-08,0.610596,0.000818112,-8.13775e-07,5.9969e-08,0.611413,0.000816665,-6.33868e-07,-4.32013e-08,0.612229,0.000815267,-7.63472e-07,5.32313e-08,0.613044,0.0008139,-6.03778e-07,-5.05148e-08,0.613857,0.000812541,-7.55323e-07,2.96187e-08,0.614669,0.000811119,-6.66466e-07,-8.35545e-09,0.615479,0.000809761,-6.91533e-07,3.80301e-09,0.616288,0.00080839,-6.80124e-07,-6.85666e-09,0.617096,0.000807009,-7.00694e-07,2.36237e-08,0.617903,0.000805678,-6.29822e-07,-2.80336e-08,0.618708,0.000804334,-7.13923e-07,2.8906e-08,0.619511,0.000802993,-6.27205e-07,-2.79859e-08,0.620314,0.000801655,-7.11163e-07,2.34329e-08,0.621114,0.000800303,-6.40864e-07,-6.14108e-09,0.621914,0.000799003,-6.59287e-07,1.13151e-09,0.622712,0.000797688,-6.55893e-07,1.61507e-09,0.62351,0.000796381,-6.51048e-07,-7.59186e-09,0.624305,0.000795056,-6.73823e-07,2.87524e-08,0.6251,0.000793794,-5.87566e-07,-4.7813e-08,0.625893,0.000792476,-7.31005e-07,4.32901e-08,0.626685,0.000791144,-6.01135e-07,-6.13814e-09,0.627475,0.000789923,-6.19549e-07,-1.87376e-08,0.628264,0.000788628,-6.75762e-07,2.14837e-08,0.629052,0.000787341,-6.11311e-07,-7.59265e-09,0.629839,0.000786095,-6.34089e-07,8.88692e-09,0.630625,0.000784854,-6.07428e-07,-2.7955e-08,0.631409,0.000783555,-6.91293e-07,4.33285e-08,0.632192,0.000782302,-5.61307e-07,-2.61497e-08,0.632973,0.000781101,-6.39757e-07,1.6658e-09,0.633754,0.000779827,-6.34759e-07,1.94866e-08,0.634533,0.000778616,-5.76299e-07,-2.00076e-08,0.635311,0.000777403,-6.36322e-07,9.39091e-10,0.636088,0.000776133,-6.33505e-07,1.62512e-08,0.636863,0.000774915,-5.84751e-07,-6.33937e-09,0.637638,0.000773726,-6.03769e-07,9.10609e-09,0.638411,0.000772546,-5.76451e-07,-3.00849e-08,0.639183,0.000771303,-6.66706e-07,5.1629e-08,0.639953,0.000770125,-5.11819e-07,-5.7222e-08,0.640723,0.000768929,-6.83485e-07,5.80497e-08,0.641491,0.000767736,-5.09336e-07,-5.57674e-08,0.642259,0.000766551,-6.76638e-07,4.58105e-08,0.643024,0.000765335,-5.39206e-07,-8.26541e-09,0.643789,0.000764231,-5.64002e-07,-1.27488e-08,0.644553,0.000763065,-6.02249e-07,-3.44168e-10,0.645315,0.00076186,-6.03281e-07,1.41254e-08,0.646077,0.000760695,-5.60905e-07,3.44727e-09,0.646837,0.000759584,-5.50563e-07,-2.79144e-08,0.647596,0.000758399,-6.34307e-07,4.86057e-08,0.648354,0.000757276,-4.88489e-07,-4.72989e-08,0.64911,0.000756158,-6.30386e-07,2.13807e-08,0.649866,0.000754961,-5.66244e-07,2.13808e-08,0.65062,0.000753893,-5.02102e-07,-4.7299e-08,0.651374,0.000752746,-6.43999e-07,4.86059e-08,0.652126,0.000751604,-4.98181e-07,-2.79154e-08,0.652877,0.000750524,-5.81927e-07,3.45089e-09,0.653627,0.000749371,-5.71575e-07,1.41119e-08,0.654376,0.00074827,-5.29239e-07,-2.93748e-10,0.655123,0.00074721,-5.3012e-07,-1.29368e-08,0.65587,0.000746111,-5.68931e-07,-7.56355e-09,0.656616,0.000744951,-5.91621e-07,4.3191e-08,0.65736,0.000743897,-4.62048e-07,-4.59911e-08,0.658103,0.000742835,-6.00022e-07,2.15642e-08,0.658846,0.0007417,-5.35329e-07,1.93389e-08,0.659587,0.000740687,-4.77312e-07,-3.93152e-08,0.660327,0.000739615,-5.95258e-07,1.87126e-08,0.661066,0.00073848,-5.3912e-07,2.40695e-08,0.661804,0.000737474,-4.66912e-07,-5.53859e-08,0.662541,0.000736374,-6.33069e-07,7.82648e-08,0.663277,0.000735343,-3.98275e-07,-7.88593e-08,0.664012,0.00073431,-6.34853e-07,5.83585e-08,0.664745,0.000733215,-4.59777e-07,-3.53656e-08,0.665478,0.000732189,-5.65874e-07,2.34994e-08,0.66621,0.000731128,-4.95376e-07,9.72743e-10,0.66694,0.00073014,-4.92458e-07,-2.73903e-08,0.66767,0.000729073,-5.74629e-07,4.89839e-08,0.668398,0.000728071,-4.27677e-07,-4.93359e-08,0.669126,0.000727068,-5.75685e-07,2.91504e-08,0.669853,0.000726004,-4.88234e-07,-7.66109e-09,0.670578,0.000725004,-5.11217e-07,1.49392e-09,0.671303,0.000723986,-5.06735e-07,1.68533e-09,0.672026,0.000722978,-5.01679e-07,-8.23525e-09,0.672749,0.00072195,-5.26385e-07,3.12556e-08,0.67347,0.000720991,-4.32618e-07,-5.71825e-08,0.674191,0.000719954,-6.04166e-07,7.8265e-08,0.67491,0.00071898,-3.69371e-07,-7.70634e-08,0.675628,0.00071801,-6.00561e-07,5.11747e-08,0.676346,0.000716963,-4.47037e-07,-8.42615e-09,0.677062,0.000716044,-4.72315e-07,-1.747e-08,0.677778,0.000715046,-5.24725e-07,1.87015e-08,0.678493,0.000714053,-4.68621e-07,2.26856e-09,0.679206,0.000713123,-4.61815e-07,-2.77758e-08,0.679919,0.000712116,-5.45142e-07,4.92298e-08,0.68063,0.000711173,-3.97453e-07,-4.99339e-08,0.681341,0.000710228,-5.47255e-07,3.12967e-08,0.682051,0.000709228,-4.53365e-07,-1.56481e-08,0.68276,0.000708274,-5.00309e-07,3.12958e-08,0.683467,0.000707367,-4.06422e-07,-4.99303e-08,0.684174,0.000706405,-5.56213e-07,4.9216e-08,0.68488,0.00070544,-4.08565e-07,-2.77245e-08,0.685585,0.00070454,-4.91738e-07,2.07748e-09,0.686289,0.000703562,-4.85506e-07,1.94146e-08,0.686992,0.00070265,-4.27262e-07,-2.01314e-08,0.687695,0.000701735,-4.87656e-07,1.50616e-09,0.688396,0.000700764,-4.83137e-07,1.41067e-08,0.689096,0.00069984,-4.40817e-07,1.67168e-09,0.689795,0.000698963,-4.35802e-07,-2.07934e-08,0.690494,0.000698029,-4.98182e-07,2.18972e-08,0.691192,0.000697099,-4.32491e-07,-7.19092e-09,0.691888,0.000696212,-4.54064e-07,6.86642e-09,0.692584,0.000695325,-4.33464e-07,-2.02747e-08,0.693279,0.000694397,-4.94288e-07,1.46279e-08,0.693973,0.000693452,-4.50405e-07,2.13678e-08,0.694666,0.000692616,-3.86301e-07,-4.04945e-08,0.695358,0.000691721,-5.07785e-07,2.14009e-08,0.696049,0.00069077,-4.43582e-07,1.44955e-08,0.69674,0.000689926,-4.00096e-07,-1.97783e-08,0.697429,0.000689067,-4.5943e-07,5.01296e-09,0.698118,0.000688163,-4.44392e-07,-2.73521e-10,0.698805,0.000687273,-4.45212e-07,-3.91893e-09,0.699492,0.000686371,-4.56969e-07,1.59493e-08,0.700178,0.000685505,-4.09121e-07,-2.73351e-10,0.700863,0.000684686,-4.09941e-07,-1.4856e-08,0.701548,0.000683822,-4.54509e-07,9.25979e-11,0.702231,0.000682913,-4.54231e-07,1.44855e-08,0.702913,0.000682048,-4.10775e-07,1.56992e-09,0.703595,0.000681231,-4.06065e-07,-2.07652e-08,0.704276,0.000680357,-4.68361e-07,2.18864e-08,0.704956,0.000679486,-4.02701e-07,-7.17595e-09,0.705635,0.000678659,-4.24229e-07,6.81748e-09,0.706313,0.000677831,-4.03777e-07,-2.0094e-08,0.70699,0.000676963,-4.64059e-07,1.39538e-08,0.707667,0.000676077,-4.22197e-07,2.38835e-08,0.708343,0.000675304,-3.50547e-07,-4.98831e-08,0.709018,0.000674453,-5.00196e-07,5.64395e-08,0.709692,0.000673622,-3.30878e-07,-5.66657e-08,0.710365,0.00067279,-5.00875e-07,5.1014e-08,0.711037,0.000671942,-3.47833e-07,-2.81809e-08,0.711709,0.000671161,-4.32376e-07,2.10513e-09,0.712379,0.000670303,-4.2606e-07,1.97604e-08,0.713049,0.00066951,-3.66779e-07,-2.15422e-08,0.713718,0.000668712,-4.31406e-07,6.8038e-09,0.714387,0.000667869,-4.10994e-07,-5.67295e-09,0.715054,0.00066703,-4.28013e-07,1.5888e-08,0.715721,0.000666222,-3.80349e-07,1.72576e-09,0.716387,0.000665467,-3.75172e-07,-2.27911e-08,0.717052,0.000664648,-4.43545e-07,2.9834e-08,0.717716,0.00066385,-3.54043e-07,-3.69401e-08,0.718379,0.000663031,-4.64864e-07,5.83219e-08,0.719042,0.000662277,-2.89898e-07,-7.71382e-08,0.719704,0.000661465,-5.21313e-07,7.14171e-08,0.720365,0.000660637,-3.07061e-07,-2.97161e-08,0.721025,0.000659934,-3.96209e-07,-1.21575e-08,0.721685,0.000659105,-4.32682e-07,1.87412e-08,0.722343,0.000658296,-3.76458e-07,-3.2029e-09,0.723001,0.000657533,-3.86067e-07,-5.9296e-09,0.723659,0.000656743,-4.03856e-07,2.69213e-08,0.724315,0.000656016,-3.23092e-07,-4.21511e-08,0.724971,0.000655244,-4.49545e-07,2.24737e-08,0.725625,0.000654412,-3.82124e-07,1.18611e-08,0.726279,0.000653683,-3.46541e-07,-1.03132e-08,0.726933,0.000652959,-3.7748e-07,-3.02128e-08,0.727585,0.000652114,-4.68119e-07,7.15597e-08,0.728237,0.000651392,-2.5344e-07,-7.72119e-08,0.728888,0.000650654,-4.85075e-07,5.8474e-08,0.729538,0.000649859,-3.09654e-07,-3.74746e-08,0.730188,0.000649127,-4.22077e-07,3.18197e-08,0.730837,0.000648379,-3.26618e-07,-3.01997e-08,0.731485,0.000647635,-4.17217e-07,2.93747e-08,0.732132,0.000646888,-3.29093e-07,-2.76943e-08,0.732778,0.000646147,-4.12176e-07,2.17979e-08,0.733424,0.000645388,-3.46783e-07,1.07292e-10,0.734069,0.000644695,-3.46461e-07,-2.22271e-08,0.734713,0.000643935,-4.13142e-07,2.91963e-08,0.735357,0.000643197,-3.25553e-07,-3.49536e-08,0.736,0.000642441,-4.30414e-07,5.10133e-08,0.736642,0.000641733,-2.77374e-07,-4.98904e-08,0.737283,0.000641028,-4.27045e-07,2.93392e-08,0.737924,0.000640262,-3.39028e-07,-7.86156e-09,0.738564,0.000639561,-3.62612e-07,2.10703e-09,0.739203,0.000638842,-3.56291e-07,-5.6653e-10,0.739842,0.000638128,-3.57991e-07,1.59086e-10,0.740479,0.000637412,-3.57513e-07,-6.98321e-11,0.741116,0.000636697,-3.57723e-07,1.20214e-10,0.741753,0.000635982,-3.57362e-07,-4.10987e-10,0.742388,0.000635266,-3.58595e-07,1.5237e-09,0.743023,0.000634553,-3.54024e-07,-5.68376e-09,0.743657,0.000633828,-3.71075e-07,2.12113e-08,0.744291,0.00063315,-3.07441e-07,-1.95569e-08,0.744924,0.000632476,-3.66112e-07,-2.58816e-09,0.745556,0.000631736,-3.73877e-07,2.99096e-08,0.746187,0.000631078,-2.84148e-07,-5.74454e-08,0.746818,0.000630337,-4.56484e-07,8.06629e-08,0.747448,0.000629666,-2.14496e-07,-8.63922e-08,0.748077,0.000628978,-4.73672e-07,8.60918e-08,0.748706,0.000628289,-2.15397e-07,-7.91613e-08,0.749334,0.000627621,-4.5288e-07,5.17393e-08,0.749961,0.00062687,-2.97663e-07,-8.58662e-09,0.750588,0.000626249,-3.23422e-07,-1.73928e-08,0.751214,0.00062555,-3.75601e-07,1.85532e-08,0.751839,0.000624855,-3.19941e-07,2.78479e-09,0.752463,0.000624223,-3.11587e-07,-2.96923e-08,0.753087,0.000623511,-4.00664e-07,5.63799e-08,0.75371,0.000622879,-2.31524e-07,-7.66179e-08,0.754333,0.000622186,-4.61378e-07,7.12778e-08,0.754955,0.000621477,-2.47545e-07,-2.96794e-08,0.755576,0.000620893,-3.36583e-07,-1.21648e-08,0.756196,0.000620183,-3.73077e-07,1.87339e-08,0.756816,0.000619493,-3.16875e-07,-3.16622e-09,0.757435,0.00061885,-3.26374e-07,-6.0691e-09,0.758054,0.000618179,-3.44581e-07,2.74426e-08,0.758672,0.000617572,-2.62254e-07,-4.40968e-08,0.759289,0.000616915,-3.94544e-07,2.97352e-08,0.759906,0.000616215,-3.05338e-07,-1.52393e-08,0.760522,0.000615559,-3.51056e-07,3.12221e-08,0.761137,0.000614951,-2.5739e-07,-5.00443e-08,0.761751,0.000614286,-4.07523e-07,4.9746e-08,0.762365,0.00061362,-2.58285e-07,-2.97303e-08,0.762979,0.000613014,-3.47476e-07,9.57079e-09,0.763591,0.000612348,-3.18764e-07,-8.55287e-09,0.764203,0.000611685,-3.44422e-07,2.46407e-08,0.764815,0.00061107,-2.705e-07,-3.04053e-08,0.765426,0.000610437,-3.61716e-07,3.73759e-08,0.766036,0.000609826,-2.49589e-07,-5.94935e-08,0.766645,0.000609149,-4.28069e-07,8.13889e-08,0.767254,0.000608537,-1.83902e-07,-8.72483e-08,0.767862,0.000607907,-4.45647e-07,8.87901e-08,0.76847,0.000607282,-1.79277e-07,-8.90983e-08,0.769077,0.000606656,-4.46572e-07,8.87892e-08,0.769683,0.000606029,-1.80204e-07,-8.72446e-08,0.770289,0.000605407,-4.41938e-07,8.13752e-08,0.770894,0.000604768,-1.97812e-07,-5.94423e-08,0.771498,0.000604194,-3.76139e-07,3.71848e-08,0.772102,0.000603553,-2.64585e-07,-2.96922e-08,0.772705,0.000602935,-3.53661e-07,2.19793e-08,0.773308,0.000602293,-2.87723e-07,1.37955e-09,0.77391,0.000601722,-2.83585e-07,-2.74976e-08,0.774512,0.000601072,-3.66077e-07,4.9006e-08,0.775112,0.000600487,-2.19059e-07,-4.93171e-08,0.775712,0.000599901,-3.67011e-07,2.90531e-08,0.776312,0.000599254,-2.79851e-07,-7.29081e-09,0.776911,0.000598673,-3.01724e-07,1.10077e-10,0.777509,0.00059807,-3.01393e-07,6.85053e-09,0.778107,0.000597487,-2.80842e-07,-2.75123e-08,0.778704,0.000596843,-3.63379e-07,4.35939e-08,0.779301,0.000596247,-2.32597e-07,-2.7654e-08,0.779897,0.000595699,-3.15559e-07,7.41741e-09,0.780492,0.00059509,-2.93307e-07,-2.01562e-09,0.781087,0.000594497,-2.99354e-07,6.45059e-10,0.781681,0.000593901,-2.97418e-07,-5.64635e-10,0.782275,0.000593304,-2.99112e-07,1.61347e-09,0.782868,0.000592711,-2.94272e-07,-5.88926e-09,0.78346,0.000592105,-3.1194e-07,2.19436e-08,0.784052,0.000591546,-2.46109e-07,-2.22805e-08,0.784643,0.000590987,-3.1295e-07,7.57368e-09,0.785234,0.000590384,-2.90229e-07,-8.01428e-09,0.785824,0.00058978,-3.14272e-07,2.44834e-08,0.786414,0.000589225,-2.40822e-07,-3.03148e-08,0.787003,0.000588652,-3.31766e-07,3.7171e-08,0.787591,0.0005881,-2.20253e-07,-5.87646e-08,0.788179,0.000587483,-3.96547e-07,7.86782e-08,0.788766,0.000586926,-1.60512e-07,-7.71342e-08,0.789353,0.000586374,-3.91915e-07,5.10444e-08,0.789939,0.000585743,-2.38782e-07,-7.83422e-09,0.790524,0.000585242,-2.62284e-07,-1.97076e-08,0.791109,0.000584658,-3.21407e-07,2.70598e-08,0.791693,0.000584097,-2.40228e-07,-2.89269e-08,0.792277,0.000583529,-3.27008e-07,2.90431e-08,0.792861,0.000582963,-2.39879e-07,-2.76409e-08,0.793443,0.0005824,-3.22802e-07,2.1916e-08,0.794025,0.00058182,-2.57054e-07,-4.18368e-10,0.794607,0.000581305,-2.58309e-07,-2.02425e-08,0.795188,0.000580727,-3.19036e-07,2.17838e-08,0.795768,0.000580155,-2.53685e-07,-7.28814e-09,0.796348,0.000579625,-2.75549e-07,7.36871e-09,0.796928,0.000579096,-2.53443e-07,-2.21867e-08,0.797506,0.000578523,-3.20003e-07,2.17736e-08,0.798085,0.000577948,-2.54683e-07,-5.30296e-09,0.798662,0.000577423,-2.70592e-07,-5.61698e-10,0.799239,0.00057688,-2.72277e-07,7.54977e-09,0.799816,0.000576358,-2.49627e-07,-2.96374e-08,0.800392,0.00057577,-3.38539e-07,5.1395e-08,0.800968,0.000575247,-1.84354e-07,-5.67335e-08,0.801543,0.000574708,-3.54555e-07,5.63297e-08,0.802117,0.000574168,-1.85566e-07,-4.93759e-08,0.802691,0.000573649,-3.33693e-07,2.19646e-08,0.803264,0.000573047,-2.678e-07,2.1122e-08,0.803837,0.000572575,-2.04433e-07,-4.68482e-08,0.804409,0.000572026,-3.44978e-07,4.70613e-08,0.804981,0.000571477,-2.03794e-07,-2.21877e-08,0.805552,0.000571003,-2.70357e-07,-1.79153e-08,0.806123,0.000570408,-3.24103e-07,3.42443e-08,0.806693,0.000569863,-2.2137e-07,1.47556e-10,0.807263,0.000569421,-2.20928e-07,-3.48345e-08,0.807832,0.000568874,-3.25431e-07,1.99812e-08,0.808401,0.000568283,-2.65487e-07,1.45143e-08,0.808969,0.000567796,-2.21945e-07,-1.84338e-08,0.809536,0.000567297,-2.77246e-07,-3.83608e-10,0.810103,0.000566741,-2.78397e-07,1.99683e-08,0.81067,0.000566244,-2.18492e-07,-1.98848e-08,0.811236,0.000565747,-2.78146e-07,-3.38976e-11,0.811801,0.000565191,-2.78248e-07,2.00204e-08,0.812366,0.000564695,-2.18187e-07,-2.04429e-08,0.812931,0.000564197,-2.79516e-07,2.1467e-09,0.813495,0.000563644,-2.73076e-07,1.18561e-08,0.814058,0.000563134,-2.37507e-07,1.00334e-08,0.814621,0.000562689,-2.07407e-07,-5.19898e-08,0.815183,0.000562118,-3.63376e-07,7.87163e-08,0.815745,0.000561627,-1.27227e-07,-8.40616e-08,0.816306,0.000561121,-3.79412e-07,7.87163e-08,0.816867,0.000560598,-1.43263e-07,-5.19898e-08,0.817428,0.000560156,-2.99233e-07,1.00335e-08,0.817988,0.000559587,-2.69132e-07,1.18559e-08,0.818547,0.000559085,-2.33564e-07,2.14764e-09,0.819106,0.000558624,-2.27122e-07,-2.04464e-08,0.819664,0.000558108,-2.88461e-07,2.00334e-08,0.820222,0.000557591,-2.28361e-07,-8.24277e-11,0.820779,0.000557135,-2.28608e-07,-1.97037e-08,0.821336,0.000556618,-2.87719e-07,1.92925e-08,0.821893,0.000556101,-2.29841e-07,2.13831e-09,0.822448,0.000555647,-2.23427e-07,-2.78458e-08,0.823004,0.000555117,-3.06964e-07,4.96402e-08,0.823559,0.000554652,-1.58043e-07,-5.15058e-08,0.824113,0.000554181,-3.12561e-07,3.71737e-08,0.824667,0.000553668,-2.0104e-07,-3.75844e-08,0.82522,0.000553153,-3.13793e-07,5.35592e-08,0.825773,0.000552686,-1.53115e-07,-5.74431e-08,0.826326,0.000552207,-3.25444e-07,5.7004e-08,0.826878,0.000551728,-1.54433e-07,-5.13635e-08,0.827429,0.000551265,-3.08523e-07,2.92406e-08,0.82798,0.000550735,-2.20801e-07,-5.99424e-09,0.828531,0.000550276,-2.38784e-07,-5.26363e-09,0.829081,0.000549782,-2.54575e-07,2.70488e-08,0.82963,0.000549354,-1.73429e-07,-4.33268e-08,0.83018,0.000548878,-3.03409e-07,2.7049e-08,0.830728,0.000548352,-2.22262e-07,-5.26461e-09,0.831276,0.000547892,-2.38056e-07,-5.99057e-09,0.831824,0.000547397,-2.56027e-07,2.92269e-08,0.832371,0.000546973,-1.68347e-07,-5.13125e-08,0.832918,0.000546482,-3.22284e-07,5.68139e-08,0.833464,0.000546008,-1.51843e-07,-5.67336e-08,0.83401,0.000545534,-3.22043e-07,5.09113e-08,0.834555,0.000545043,-1.6931e-07,-2.77022e-08,0.8351,0.000544621,-2.52416e-07,2.92924e-10,0.835644,0.000544117,-2.51537e-07,2.65305e-08,0.836188,0.000543694,-1.71946e-07,-4.68105e-08,0.836732,0.00054321,-3.12377e-07,4.15021e-08,0.837275,0.000542709,-1.87871e-07,1.13355e-11,0.837817,0.000542334,-1.87837e-07,-4.15474e-08,0.838359,0.000541833,-3.12479e-07,4.69691e-08,0.838901,0.000541349,-1.71572e-07,-2.71196e-08,0.839442,0.000540925,-2.52931e-07,1.90462e-09,0.839983,0.000540425,-2.47217e-07,1.95011e-08,0.840523,0.000539989,-1.88713e-07,-2.03045e-08,0.841063,0.00053955,-2.49627e-07,2.11216e-09,0.841602,0.000539057,-2.4329e-07,1.18558e-08,0.842141,0.000538606,-2.07723e-07,1.00691e-08,0.842679,0.000538221,-1.77516e-07,-5.21324e-08,0.843217,0.00053771,-3.33913e-07,7.92513e-08,0.843755,0.00053728,-9.6159e-08,-8.60587e-08,0.844292,0.000536829,-3.54335e-07,8.61696e-08,0.844828,0.000536379,-9.58263e-08,-7.98057e-08,0.845364,0.000535948,-3.35243e-07,5.42394e-08,0.8459,0.00053544,-1.72525e-07,-1.79426e-08,0.846435,0.000535041,-2.26353e-07,1.75308e-08,0.84697,0.000534641,-1.73761e-07,-5.21806e-08,0.847505,0.000534137,-3.30302e-07,7.19824e-08,0.848038,0.000533692,-1.14355e-07,-5.69349e-08,0.848572,0.000533293,-2.8516e-07,3.65479e-08,0.849105,0.000532832,-1.75516e-07,-2.96519e-08,0.849638,0.000532392,-2.64472e-07,2.2455e-08,0.85017,0.000531931,-1.97107e-07,-5.63451e-10,0.850702,0.000531535,-1.98797e-07,-2.02011e-08,0.851233,0.000531077,-2.59401e-07,2.17634e-08,0.851764,0.000530623,-1.94111e-07,-7.24794e-09,0.852294,0.000530213,-2.15854e-07,7.22832e-09,0.852824,0.000529803,-1.94169e-07,-2.16653e-08,0.853354,0.00052935,-2.59165e-07,1.98283e-08,0.853883,0.000528891,-1.9968e-07,1.95678e-09,0.854412,0.000528497,-1.9381e-07,-2.76554e-08,0.85494,0.000528027,-2.76776e-07,4.90603e-08,0.855468,0.00052762,-1.29596e-07,-4.93764e-08,0.855995,0.000527213,-2.77725e-07,2.92361e-08,0.856522,0.000526745,-1.90016e-07,-7.96341e-09,0.857049,0.000526341,-2.13907e-07,2.61752e-09,0.857575,0.000525922,-2.06054e-07,-2.50665e-09,0.8581,0.000525502,-2.13574e-07,7.40906e-09,0.858626,0.000525097,-1.91347e-07,-2.71296e-08,0.859151,0.000524633,-2.72736e-07,4.15048e-08,0.859675,0.000524212,-1.48221e-07,-1.96802e-08,0.860199,0.000523856,-2.07262e-07,-2.23886e-08,0.860723,0.000523375,-2.74428e-07,4.96299e-08,0.861246,0.000522975,-1.25538e-07,-5.69216e-08,0.861769,0.000522553,-2.96303e-07,5.88473e-08,0.862291,0.000522137,-1.19761e-07,-5.92584e-08,0.862813,0.00052172,-2.97536e-07,5.8977e-08,0.863334,0.000521301,-1.20605e-07,-5.74403e-08,0.863855,0.000520888,-2.92926e-07,5.15751e-08,0.864376,0.000520457,-1.38201e-07,-2.96506e-08,0.864896,0.000520091,-2.27153e-07,7.42277e-09,0.865416,0.000519659,-2.04885e-07,-4.05057e-11,0.865936,0.00051925,-2.05006e-07,-7.26074e-09,0.866455,0.000518818,-2.26788e-07,2.90835e-08,0.866973,0.000518451,-1.39538e-07,-4.94686e-08,0.867492,0.000518024,-2.87944e-07,4.95814e-08,0.868009,0.000517597,-1.39199e-07,-2.96479e-08,0.868527,0.000517229,-2.28143e-07,9.40539e-09,0.869044,0.000516801,-1.99927e-07,-7.9737e-09,0.86956,0.000516378,-2.23848e-07,2.24894e-08,0.870077,0.000515997,-1.5638e-07,-2.23793e-08,0.870592,0.000515617,-2.23517e-07,7.42302e-09,0.871108,0.000515193,-2.01248e-07,-7.31283e-09,0.871623,0.000514768,-2.23187e-07,2.18283e-08,0.872137,0.000514387,-1.57702e-07,-2.03959e-08,0.872652,0.000514011,-2.1889e-07,1.50711e-10,0.873165,0.000513573,-2.18437e-07,1.97931e-08,0.873679,0.000513196,-1.59058e-07,-1.97183e-08,0.874192,0.000512819,-2.18213e-07,-5.24324e-10,0.874704,0.000512381,-2.19786e-07,2.18156e-08,0.875217,0.000512007,-1.54339e-07,-2.71336e-08,0.875728,0.000511616,-2.3574e-07,2.71141e-08,0.87624,0.000511226,-1.54398e-07,-2.17182e-08,0.876751,0.000510852,-2.19552e-07,1.54131e-10,0.877262,0.000510414,-2.1909e-07,2.11017e-08,0.877772,0.000510039,-1.55785e-07,-2.49562e-08,0.878282,0.000509652,-2.30654e-07,1.91183e-08,0.878791,0.000509248,-1.73299e-07,8.08751e-09,0.8793,0.000508926,-1.49036e-07,-5.14684e-08,0.879809,0.000508474,-3.03441e-07,7.85766e-08,0.880317,0.000508103,-6.77112e-08,-8.40242e-08,0.880825,0.000507715,-3.19784e-07,7.87063e-08,0.881333,0.000507312,-8.36649e-08,-5.19871e-08,0.88184,0.000506988,-2.39626e-07,1.00327e-08,0.882346,0.000506539,-2.09528e-07,1.18562e-08,0.882853,0.000506156,-1.73959e-07,2.14703e-09,0.883359,0.000505814,-1.67518e-07,-2.04444e-08,0.883864,0.000505418,-2.28851e-07,2.00258e-08,0.88437,0.00050502,-1.68774e-07,-5.42855e-11,0.884874,0.000504682,-1.68937e-07,-1.98087e-08,0.885379,0.000504285,-2.28363e-07,1.96842e-08,0.885883,0.000503887,-1.6931e-07,6.76342e-10,0.886387,0.000503551,-1.67281e-07,-2.23896e-08,0.88689,0.000503149,-2.3445e-07,2.92774e-08,0.887393,0.000502768,-1.46618e-07,-3.51152e-08,0.887896,0.00050237,-2.51963e-07,5.15787e-08,0.888398,0.00050202,-9.72271e-08,-5.19903e-08,0.8889,0.00050167,-2.53198e-07,3.71732e-08,0.889401,0.000501275,-1.41678e-07,-3.70978e-08,0.889902,0.00050088,-2.52972e-07,5.16132e-08,0.890403,0.000500529,-9.81321e-08,-5.01459e-08,0.890903,0.000500183,-2.4857e-07,2.9761e-08,0.891403,0.000499775,-1.59287e-07,-9.29351e-09,0.891903,0.000499428,-1.87167e-07,7.41301e-09,0.892402,0.000499076,-1.64928e-07,-2.03585e-08,0.892901,0.000498685,-2.26004e-07,1.44165e-08,0.893399,0.000498276,-1.82754e-07,2.22974e-08,0.893898,0.000497978,-1.15862e-07,-4.40013e-08,0.894395,0.000497614,-2.47866e-07,3.44985e-08,0.894893,0.000497222,-1.44371e-07,-3.43882e-08,0.89539,0.00049683,-2.47535e-07,4.34497e-08,0.895886,0.000496465,-1.17186e-07,-2.02012e-08,0.896383,0.00049617,-1.7779e-07,-2.22497e-08,0.896879,0.000495748,-2.44539e-07,4.95952e-08,0.897374,0.000495408,-9.57532e-08,-5.69217e-08,0.89787,0.000495045,-2.66518e-07,5.88823e-08,0.898364,0.000494689,-8.98713e-08,-5.93983e-08,0.898859,0.000494331,-2.68066e-07,5.95017e-08,0.899353,0.000493973,-8.95613e-08,-5.9399e-08,0.899847,0.000493616,-2.67758e-07,5.8885e-08,0.90034,0.000493257,-9.11033e-08,-5.69317e-08,0.900833,0.000492904,-2.61898e-07,4.96326e-08,0.901326,0.000492529,-1.13001e-07,-2.23893e-08,0.901819,0.000492236,-1.80169e-07,-1.968e-08,0.902311,0.000491817,-2.39209e-07,4.15047e-08,0.902802,0.000491463,-1.14694e-07,-2.71296e-08,0.903293,0.000491152,-1.96083e-07,7.409e-09,0.903784,0.000490782,-1.73856e-07,-2.50645e-09,0.904275,0.000490427,-1.81376e-07,2.61679e-09,0.904765,0.000490072,-1.73525e-07,-7.96072e-09,0.905255,0.000489701,-1.97407e-07,2.92261e-08,0.905745,0.000489394,-1.09729e-07,-4.93389e-08,0.906234,0.000489027,-2.57746e-07,4.89204e-08,0.906723,0.000488658,-1.10985e-07,-2.71333e-08,0.907211,0.000488354,-1.92385e-07,8.30861e-12,0.907699,0.00048797,-1.9236e-07,2.71001e-08,0.908187,0.000487666,-1.1106e-07,-4.88041e-08,0.908675,0.000487298,-2.57472e-07,4.89069e-08,0.909162,0.000486929,-1.10751e-07,-2.76143e-08,0.909649,0.000486625,-1.93594e-07,1.9457e-09,0.910135,0.000486244,-1.87757e-07,1.98315e-08,0.910621,0.000485928,-1.28262e-07,-2.16671e-08,0.911107,0.000485606,-1.93264e-07,7.23216e-09,0.911592,0.000485241,-1.71567e-07,-7.26152e-09,0.912077,0.000484877,-1.93352e-07,2.18139e-08,0.912562,0.000484555,-1.2791e-07,-2.03895e-08,0.913047,0.000484238,-1.89078e-07,1.39494e-10,0.913531,0.000483861,-1.8866e-07,1.98315e-08,0.914014,0.000483543,-1.29165e-07,-1.98609e-08,0.914498,0.000483225,-1.88748e-07,7.39912e-12,0.914981,0.000482847,-1.88726e-07,1.98313e-08,0.915463,0.000482529,-1.29232e-07,-1.9728e-08,0.915946,0.000482212,-1.88416e-07,-5.24035e-10,0.916428,0.000481833,-1.89988e-07,2.18241e-08,0.916909,0.000481519,-1.24516e-07,-2.71679e-08,0.917391,0.000481188,-2.06019e-07,2.72427e-08,0.917872,0.000480858,-1.24291e-07,-2.21985e-08,0.918353,0.000480543,-1.90886e-07,1.94644e-09,0.918833,0.000480167,-1.85047e-07,1.44127e-08,0.919313,0.00047984,-1.41809e-07,7.39438e-12,0.919793,0.000479556,-1.41787e-07,-1.44423e-08,0.920272,0.000479229,-1.85114e-07,-1.84291e-09,0.920751,0.000478854,-1.90642e-07,2.18139e-08,0.92123,0.000478538,-1.25201e-07,-2.58081e-08,0.921708,0.00047821,-2.02625e-07,2.18139e-08,0.922186,0.00047787,-1.37183e-07,-1.84291e-09,0.922664,0.00047759,-1.42712e-07,-1.44423e-08,0.923141,0.000477262,-1.86039e-07,7.34701e-12,0.923618,0.00047689,-1.86017e-07,1.44129e-08,0.924095,0.000476561,-1.42778e-07,1.94572e-09,0.924572,0.000476281,-1.36941e-07,-2.21958e-08,0.925048,0.000475941,-2.03528e-07,2.72327e-08,0.925523,0.000475615,-1.2183e-07,-2.71304e-08,0.925999,0.00047529,-2.03221e-07,2.16843e-08,0.926474,0.000474949,-1.38168e-07,-2.16005e-12,0.926949,0.000474672,-1.38175e-07,-2.16756e-08,0.927423,0.000474331,-2.03202e-07,2.71001e-08,0.927897,0.000474006,-1.21902e-07,-2.71201e-08,0.928371,0.000473681,-2.03262e-07,2.17757e-08,0.928845,0.00047334,-1.37935e-07,-3.78028e-10,0.929318,0.000473063,-1.39069e-07,-2.02636e-08,0.929791,0.000472724,-1.9986e-07,2.18276e-08,0.930263,0.000472389,-1.34377e-07,-7.44231e-09,0.930736,0.000472098,-1.56704e-07,7.94165e-09,0.931208,0.000471809,-1.32879e-07,-2.43243e-08,0.931679,0.00047147,-2.05851e-07,2.97508e-08,0.932151,0.000471148,-1.16599e-07,-3.50742e-08,0.932622,0.000470809,-2.21822e-07,5.09414e-08,0.933092,0.000470518,-6.89976e-08,-4.94821e-08,0.933563,0.000470232,-2.17444e-07,2.77775e-08,0.934033,0.00046988,-1.34111e-07,-2.02351e-09,0.934502,0.000469606,-1.40182e-07,-1.96835e-08,0.934972,0.000469267,-1.99232e-07,2.11529e-08,0.935441,0.000468932,-1.35774e-07,-5.32332e-09,0.93591,0.000468644,-1.51743e-07,1.40413e-10,0.936378,0.000468341,-1.51322e-07,4.76166e-09,0.936846,0.000468053,-1.37037e-07,-1.9187e-08,0.937314,0.000467721,-1.94598e-07,1.23819e-08,0.937782,0.000467369,-1.57453e-07,2.92642e-08,0.938249,0.000467142,-6.96601e-08,-6.98342e-08,0.938716,0.000466793,-2.79163e-07,7.12586e-08,0.939183,0.000466449,-6.53869e-08,-3.63863e-08,0.939649,0.000466209,-1.74546e-07,1.46818e-08,0.940115,0.000465904,-1.305e-07,-2.2341e-08,0.940581,0.000465576,-1.97523e-07,1.50774e-08,0.941046,0.000465226,-1.52291e-07,2.16359e-08,0.941511,0.000464986,-8.73832e-08,-4.20162e-08,0.941976,0.000464685,-2.13432e-07,2.72198e-08,0.942441,0.00046434,-1.31773e-07,-7.2581e-09,0.942905,0.000464055,-1.53547e-07,1.81263e-09,0.943369,0.000463753,-1.48109e-07,7.58386e-12,0.943832,0.000463457,-1.48086e-07,-1.84298e-09,0.944296,0.000463155,-1.53615e-07,7.36433e-09,0.944759,0.00046287,-1.31522e-07,-2.76143e-08,0.945221,0.000462524,-2.14365e-07,4.34883e-08,0.945684,0.000462226,-8.39003e-08,-2.71297e-08,0.946146,0.000461977,-1.65289e-07,5.42595e-09,0.946608,0.000461662,-1.49012e-07,5.42593e-09,0.947069,0.000461381,-1.32734e-07,-2.71297e-08,0.94753,0.000461034,-2.14123e-07,4.34881e-08,0.947991,0.000460736,-8.36585e-08,-2.76134e-08,0.948452,0.000460486,-1.66499e-07,7.36083e-09,0.948912,0.000460175,-1.44416e-07,-1.82993e-09,0.949372,0.000459881,-1.49906e-07,-4.11073e-11,0.949832,0.000459581,-1.50029e-07,1.99434e-09,0.950291,0.000459287,-1.44046e-07,-7.93627e-09,0.950751,0.000458975,-1.67855e-07,2.97507e-08,0.951209,0.000458728,-7.86029e-08,-5.1462e-08,0.951668,0.000458417,-2.32989e-07,5.6888e-08,0.952126,0.000458121,-6.2325e-08,-5.68806e-08,0.952584,0.000457826,-2.32967e-07,5.14251e-08,0.953042,0.000457514,-7.86914e-08,-2.96107e-08,0.953499,0.000457268,-1.67523e-07,7.41296e-09,0.953956,0.000456955,-1.45285e-07,-4.11262e-11,0.954413,0.000456665,-1.45408e-07,-7.24847e-09,0.95487,0.000456352,-1.67153e-07,2.9035e-08,0.955326,0.000456105,-8.00484e-08,-4.92869e-08,0.955782,0.000455797,-2.27909e-07,4.89032e-08,0.956238,0.000455488,-8.11994e-08,-2.71166e-08,0.956693,0.000455244,-1.62549e-07,-4.13678e-11,0.957148,0.000454919,-1.62673e-07,2.72821e-08,0.957603,0.000454675,-8.0827e-08,-4.94824e-08,0.958057,0.000454365,-2.29274e-07,5.14382e-08,0.958512,0.000454061,-7.49597e-08,-3.7061e-08,0.958965,0.0004538,-1.86143e-07,3.72013e-08,0.959419,0.000453539,-7.45389e-08,-5.21396e-08,0.959873,0.000453234,-2.30958e-07,5.21476e-08,0.960326,0.000452928,-7.45146e-08,-3.72416e-08,0.960778,0.000452667,-1.8624e-07,3.72143e-08,0.961231,0.000452407,-7.45967e-08,-5.20109e-08,0.961683,0.000452101,-2.30629e-07,5.16199e-08,0.962135,0.000451795,-7.57696e-08,-3.52595e-08,0.962587,0.000451538,-1.81548e-07,2.98133e-08,0.963038,0.000451264,-9.2108e-08,-2.43892e-08,0.963489,0.000451007,-1.65276e-07,8.13892e-09,0.96394,0.000450701,-1.40859e-07,-8.16647e-09,0.964391,0.000450394,-1.65358e-07,2.45269e-08,0.964841,0.000450137,-9.17775e-08,-3.03367e-08,0.965291,0.000449863,-1.82787e-07,3.7215e-08,0.965741,0.000449609,-7.11424e-08,-5.89188e-08,0.96619,0.00044929,-2.47899e-07,7.92509e-08,0.966639,0.000449032,-1.01462e-08,-7.92707e-08,0.967088,0.000448773,-2.47958e-07,5.90181e-08,0.967537,0.000448455,-7.0904e-08,-3.75925e-08,0.967985,0.0004482,-1.83681e-07,3.17471e-08,0.968433,0.000447928,-8.84401e-08,-2.97913e-08,0.968881,0.000447662,-1.77814e-07,2.78133e-08,0.969329,0.000447389,-9.4374e-08,-2.18572e-08,0.969776,0.000447135,-1.59946e-07,1.10134e-11,0.970223,0.000446815,-1.59913e-07,2.18132e-08,0.97067,0.000446561,-9.44732e-08,-2.76591e-08,0.971116,0.000446289,-1.7745e-07,2.92185e-08,0.971562,0.000446022,-8.97948e-08,-2.96104e-08,0.972008,0.000445753,-1.78626e-07,2.96185e-08,0.972454,0.000445485,-8.97706e-08,-2.92588e-08,0.972899,0.000445218,-1.77547e-07,2.78123e-08,0.973344,0.000444946,-9.41103e-08,-2.23856e-08,0.973789,0.000444691,-1.61267e-07,2.12559e-09,0.974233,0.000444374,-1.5489e-07,1.38833e-08,0.974678,0.000444106,-1.13241e-07,1.94591e-09,0.975122,0.000443886,-1.07403e-07,-2.16669e-08,0.975565,0.000443606,-1.72404e-07,2.5117e-08,0.976009,0.000443336,-9.70526e-08,-1.91963e-08,0.976452,0.000443085,-1.54642e-07,-7.93627e-09,0.976895,0.000442752,-1.7845e-07,5.09414e-08,0.977338,0.000442548,-2.56262e-08,-7.66201e-08,0.97778,0.000442266,-2.55486e-07,7.67249e-08,0.978222,0.000441986,-2.53118e-08,-5.14655e-08,0.978664,0.000441781,-1.79708e-07,9.92773e-09,0.979106,0.000441451,-1.49925e-07,1.17546e-08,0.979547,0.000441186,-1.14661e-07,2.65868e-09,0.979988,0.000440965,-1.06685e-07,-2.23893e-08,0.980429,0.000440684,-1.73853e-07,2.72939e-08,0.980869,0.000440419,-9.19716e-08,-2.71816e-08,0.98131,0.000440153,-1.73516e-07,2.18278e-08,0.98175,0.000439872,-1.08033e-07,-5.24833e-10,0.982189,0.000439654,-1.09607e-07,-1.97284e-08,0.982629,0.000439376,-1.68793e-07,1.98339e-08,0.983068,0.000439097,-1.09291e-07,-2.62901e-12,0.983507,0.000438879,-1.09299e-07,-1.98234e-08,0.983946,0.000438601,-1.68769e-07,1.96916e-08,0.984384,0.000438322,-1.09694e-07,6.6157e-10,0.984823,0.000438105,-1.0771e-07,-2.23379e-08,0.985261,0.000437823,-1.74723e-07,2.90855e-08,0.985698,0.00043756,-8.74669e-08,-3.43992e-08,0.986136,0.000437282,-1.90665e-07,4.89068e-08,0.986573,0.000437048,-4.39442e-08,-4.20188e-08,0.98701,0.000436834,-1.7e-07,-4.11073e-11,0.987446,0.000436494,-1.70124e-07,4.21832e-08,0.987883,0.00043628,-4.35742e-08,-4.94824e-08,0.988319,0.000436044,-1.92021e-07,3.6537e-08,0.988755,0.00043577,-8.24102e-08,-3.70611e-08,0.989191,0.000435494,-1.93593e-07,5.21026e-08,0.989626,0.000435263,-3.72855e-08,-5.21402e-08,0.990061,0.000435032,-1.93706e-07,3.7249e-08,0.990496,0.000434756,-8.19592e-08,-3.72512e-08,0.990931,0.000434481,-1.93713e-07,5.21511e-08,0.991365,0.00043425,-3.72595e-08,-5.21439e-08,0.991799,0.000434019,-1.93691e-07,3.72152e-08,0.992233,0.000433743,-8.20456e-08,-3.71123e-08,0.992667,0.000433468,-1.93382e-07,5.16292e-08,0.9931,0.000433236,-3.84947e-08,-5.01953e-08,0.993533,0.000433008,-1.89081e-07,2.99427e-08,0.993966,0.00043272,-9.92525e-08,-9.9708e-09,0.994399,0.000432491,-1.29165e-07,9.94051e-09,0.994831,0.000432263,-9.93434e-08,-2.97912e-08,0.995263,0.000431975,-1.88717e-07,4.96198e-08,0.995695,0.000431746,-3.98578e-08,-4.94785e-08,0.996127,0.000431518,-1.88293e-07,2.9085e-08,0.996558,0.000431229,-1.01038e-07,-7.25675e-09,0.996989,0.000431005,-1.22809e-07,-5.79945e-11,0.99742,0.000430759,-1.22983e-07,7.48873e-09,0.997851,0.000430536,-1.00516e-07,-2.98969e-08,0.998281,0.000430245,-1.90207e-07,5.24942e-08,0.998711,0.000430022,-3.27246e-08,-6.08706e-08,0.999141,0.000429774,-2.15336e-07,7.17788e-08,0.999571,0.000429392,0.,0.}; + + template + __device__ __forceinline__ void Lab2RGBConvert_f(const T& src, D& dst) + { + const float lThresh = 0.008856f * 903.3f; + const float fThresh = 7.787f * 0.008856f + 16.0f / 116.0f; + + float Y, fy; + + if (src.x <= lThresh) + { + Y = src.x / 903.3f; + fy = 7.787f * Y + 16.0f / 116.0f; + } + else + { + fy = (src.x + 16.0f) / 116.0f; + Y = fy * fy * fy; + } + + float X = src.y / 500.0f + fy; + float Z = fy - src.z / 200.0f; + + if (X <= fThresh) + X = (X - 16.0f / 116.0f) / 7.787f; + else + X = X * X * X; + + if (Z <= fThresh) + Z = (Z - 16.0f / 116.0f) / 7.787f; + else + Z = Z * Z * Z; + + float B = 0.052891f * X - 0.204043f * Y + 1.151152f * Z; + float G = -0.921235f * X + 1.875991f * Y + 0.045244f * Z; + float R = 3.079933f * X - 1.537150f * Y - 0.542782f * Z; + + if (srgb) + { + B = splineInterpolate(B * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); + G = splineInterpolate(G * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); + R = splineInterpolate(R * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); + } + + dst.x = blueIdx == 0 ? B : R; + dst.y = G; + dst.z = blueIdx == 0 ? R : B; + setAlpha(dst, ColorChannel::max()); + } + + template + __device__ __forceinline__ void Lab2RGBConvert_b(const T& src, D& dst) + { + float3 srcf, dstf; + + srcf.x = src.x * (100.f / 255.f); + srcf.y = src.y - 128; + srcf.z = src.z - 128; + + Lab2RGBConvert_f(srcf, dstf); + + dst.x = saturate_cast(dstf.x * 255.f); + dst.y = saturate_cast(dstf.y * 255.f); + dst.z = saturate_cast(dstf.z * 255.f); + setAlpha(dst, ColorChannel::max()); + } + + template struct Lab2RGB; + template + struct Lab2RGB + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + Lab2RGBConvert_b(src, dst); + + return dst; + } + __host__ __device__ __forceinline__ Lab2RGB() {} + __host__ __device__ __forceinline__ Lab2RGB(const Lab2RGB&) {} + }; + template + struct Lab2RGB + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + Lab2RGBConvert_f(src, dst); + + return dst; + } + __host__ __device__ __forceinline__ Lab2RGB() {} + __host__ __device__ __forceinline__ Lab2RGB(const Lab2RGB&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(name, scn, dcn, srgb, blueIdx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::Lab2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + +///////////////////////////////////// RGB <-> Luv ///////////////////////////////////// + + namespace color_detail + { + __constant__ float c_LabCbrtTab[] = {0.137931,0.0114066,0.,1.18859e-07,0.149338,0.011407,3.56578e-07,-5.79396e-07,0.160745,0.0114059,-1.38161e-06,2.16892e-06,0.172151,0.0114097,5.12516e-06,-8.0814e-06,0.183558,0.0113957,-1.9119e-05,3.01567e-05,0.194965,0.0114479,7.13509e-05,-0.000112545,0.206371,0.011253,-0.000266285,-0.000106493,0.217252,0.0104009,-0.000585765,7.32149e-05,0.22714,0.00944906,-0.00036612,1.21917e-05,0.236235,0.0087534,-0.000329545,2.01753e-05,0.244679,0.00815483,-0.000269019,1.24435e-05,0.252577,0.00765412,-0.000231689,1.05618e-05,0.26001,0.00722243,-0.000200003,8.26662e-06,0.267041,0.00684723,-0.000175203,6.76746e-06,0.27372,0.00651712,-0.000154901,5.61192e-06,0.280088,0.00622416,-0.000138065,4.67009e-06,0.286179,0.00596204,-0.000124055,3.99012e-06,0.292021,0.0057259,-0.000112085,3.36032e-06,0.297638,0.00551181,-0.000102004,2.95338e-06,0.30305,0.00531666,-9.31435e-05,2.52875e-06,0.308277,0.00513796,-8.55572e-05,2.22022e-06,0.313331,0.00497351,-7.88966e-05,1.97163e-06,0.318228,0.00482163,-7.29817e-05,1.7248e-06,0.322978,0.00468084,-6.78073e-05,1.55998e-06,0.327593,0.0045499,-6.31274e-05,1.36343e-06,0.332081,0.00442774,-5.90371e-05,1.27136e-06,0.336451,0.00431348,-5.5223e-05,1.09111e-06,0.34071,0.00420631,-5.19496e-05,1.0399e-06,0.344866,0.00410553,-4.88299e-05,9.18347e-07,0.348923,0.00401062,-4.60749e-05,8.29942e-07,0.352889,0.00392096,-4.35851e-05,7.98478e-07,0.356767,0.00383619,-4.11896e-05,6.84917e-07,0.360562,0.00375586,-3.91349e-05,6.63976e-07,0.36428,0.00367959,-3.7143e-05,5.93086e-07,0.367923,0.00360708,-3.53637e-05,5.6976e-07,0.371495,0.00353806,-3.36544e-05,4.95533e-07,0.375,0.00347224,-3.21678e-05,4.87951e-07,0.378441,0.00340937,-3.0704e-05,4.4349e-07,0.38182,0.00334929,-2.93735e-05,4.20297e-07,0.38514,0.0032918,-2.81126e-05,3.7872e-07,0.388404,0.00323671,-2.69764e-05,3.596e-07,0.391614,0.00318384,-2.58976e-05,3.5845e-07,0.394772,0.00313312,-2.48223e-05,2.92765e-07,0.397881,0.00308435,-2.3944e-05,3.18232e-07,0.400942,0.00303742,-2.29893e-05,2.82046e-07,0.403957,0.00299229,-2.21432e-05,2.52315e-07,0.406927,0.00294876,-2.13862e-05,2.58416e-07,0.409855,0.00290676,-2.0611e-05,2.33939e-07,0.412741,0.00286624,-1.99092e-05,2.36342e-07,0.415587,0.00282713,-1.92001e-05,1.916e-07,0.418396,0.00278931,-1.86253e-05,2.1915e-07,0.421167,0.00275271,-1.79679e-05,1.83498e-07,0.423901,0.00271733,-1.74174e-05,1.79343e-07,0.426602,0.00268303,-1.68794e-05,1.72013e-07,0.429268,0.00264979,-1.63633e-05,1.75686e-07,0.431901,0.00261759,-1.58363e-05,1.3852e-07,0.434503,0.00258633,-1.54207e-05,1.64304e-07,0.437074,0.00255598,-1.49278e-05,1.28136e-07,0.439616,0.00252651,-1.45434e-05,1.57618e-07,0.442128,0.0024979,-1.40705e-05,1.0566e-07,0.444612,0.00247007,-1.37535e-05,1.34998e-07,0.447068,0.00244297,-1.33485e-05,1.29207e-07,0.449498,0.00241666,-1.29609e-05,9.32347e-08,0.451902,0.00239102,-1.26812e-05,1.23703e-07,0.45428,0.00236603,-1.23101e-05,9.74072e-08,0.456634,0.0023417,-1.20179e-05,1.12518e-07,0.458964,0.002318,-1.16803e-05,7.83681e-08,0.46127,0.00229488,-1.14452e-05,1.10452e-07,0.463554,0.00227232,-1.11139e-05,7.58719e-08,0.465815,0.00225032,-1.08863e-05,9.2699e-08,0.468055,0.00222882,-1.06082e-05,8.97738e-08,0.470273,0.00220788,-1.03388e-05,5.4845e-08,0.47247,0.00218736,-1.01743e-05,1.0808e-07,0.474648,0.00216734,-9.85007e-06,4.9277e-08,0.476805,0.00214779,-9.70224e-06,8.22408e-08,0.478943,0.00212863,-9.45551e-06,6.87942e-08,0.481063,0.00210993,-9.24913e-06,5.98144e-08,0.483163,0.00209161,-9.06969e-06,7.93789e-08,0.485246,0.00207371,-8.83155e-06,3.99032e-08,0.487311,0.00205616,-8.71184e-06,8.88325e-08,0.489358,0.002039,-8.44534e-06,2.20004e-08,0.491389,0.00202218,-8.37934e-06,9.13872e-08,0.493403,0.0020057,-8.10518e-06,2.96829e-08,0.495401,0.00198957,-8.01613e-06,5.81028e-08,0.497382,0.00197372,-7.84183e-06,6.5731e-08,0.499348,0.00195823,-7.64463e-06,3.66019e-08,0.501299,0.00194305,-7.53483e-06,2.62811e-08,0.503234,0.00192806,-7.45598e-06,9.66907e-08,0.505155,0.00191344,-7.16591e-06,4.18928e-09,0.507061,0.00189912,-7.15334e-06,6.53665e-08,0.508953,0.00188501,-6.95724e-06,3.23686e-08,0.510831,0.00187119,-6.86014e-06,4.35774e-08,0.512696,0.0018576,-6.72941e-06,3.17406e-08,0.514547,0.00184424,-6.63418e-06,6.78785e-08,0.516384,0.00183117,-6.43055e-06,-5.23126e-09,0.518209,0.0018183,-6.44624e-06,7.22562e-08,0.520021,0.00180562,-6.22947e-06,1.42292e-08,0.52182,0.0017932,-6.18679e-06,4.9641e-08,0.523607,0.00178098,-6.03786e-06,2.56259e-08,0.525382,0.00176898,-5.96099e-06,2.66696e-08,0.527145,0.00175714,-5.88098e-06,4.65094e-08,0.528897,0.00174552,-5.74145e-06,2.57114e-08,0.530637,0.00173411,-5.66431e-06,2.94588e-08,0.532365,0.00172287,-5.57594e-06,3.52667e-08,0.534082,0.00171182,-5.47014e-06,8.28868e-09,0.535789,0.00170091,-5.44527e-06,5.07871e-08,0.537484,0.00169017,-5.29291e-06,2.69817e-08,0.539169,0.00167967,-5.21197e-06,2.01009e-08,0.540844,0.0016693,-5.15166e-06,1.18237e-08,0.542508,0.00165903,-5.11619e-06,5.18135e-08,0.544162,0.00164896,-4.96075e-06,1.9341e-08,0.545806,0.00163909,-4.90273e-06,-9.96867e-09,0.54744,0.00162926,-4.93263e-06,8.01382e-08,0.549064,0.00161963,-4.69222e-06,-1.25601e-08,0.550679,0.00161021,-4.7299e-06,2.97067e-08,0.552285,0.00160084,-4.64078e-06,1.29426e-08,0.553881,0.0015916,-4.60195e-06,3.77327e-08,0.555468,0.00158251,-4.48875e-06,1.49412e-08,0.557046,0.00157357,-4.44393e-06,2.17118e-08,0.558615,0.00156475,-4.3788e-06,1.74206e-08,0.560176,0.00155605,-4.32653e-06,2.78152e-08,0.561727,0.00154748,-4.24309e-06,-9.47239e-09,0.563271,0.00153896,-4.27151e-06,6.9679e-08,0.564805,0.00153063,-4.06247e-06,-3.08246e-08,0.566332,0.00152241,-4.15494e-06,5.36188e-08,0.56785,0.00151426,-3.99409e-06,-4.83594e-09,0.56936,0.00150626,-4.00859e-06,2.53293e-08,0.570863,0.00149832,-3.93261e-06,2.27286e-08,0.572357,0.00149052,-3.86442e-06,2.96541e-09,0.573844,0.0014828,-3.85552e-06,2.50147e-08,0.575323,0.00147516,-3.78048e-06,1.61842e-08,0.576794,0.00146765,-3.73193e-06,2.94582e-08,0.578258,0.00146028,-3.64355e-06,-1.48076e-08,0.579715,0.00145295,-3.68798e-06,2.97724e-08,0.581164,0.00144566,-3.59866e-06,1.49272e-08,0.582606,0.00143851,-3.55388e-06,2.97285e-08,0.584041,0.00143149,-3.46469e-06,-1.46323e-08,0.585469,0.00142451,-3.50859e-06,2.88004e-08,0.58689,0.00141758,-3.42219e-06,1.864e-08,0.588304,0.00141079,-3.36627e-06,1.58482e-08,0.589712,0.00140411,-3.31872e-06,-2.24279e-08,0.591112,0.00139741,-3.38601e-06,7.38639e-08,0.592507,0.00139085,-3.16441e-06,-3.46088e-08,0.593894,0.00138442,-3.26824e-06,4.96675e-09,0.595275,0.0013779,-3.25334e-06,7.4346e-08,0.59665,0.00137162,-3.0303e-06,-6.39319e-08,0.598019,0.00136536,-3.2221e-06,6.21725e-08,0.599381,0.00135911,-3.03558e-06,-5.94423e-09,0.600737,0.00135302,-3.05341e-06,2.12091e-08,0.602087,0.00134697,-2.98979e-06,-1.92876e-08,0.603431,0.00134094,-3.04765e-06,5.5941e-08,0.604769,0.00133501,-2.87983e-06,-2.56622e-08,0.606101,0.00132917,-2.95681e-06,4.67078e-08,0.607427,0.0013234,-2.81669e-06,-4.19592e-08,0.608748,0.00131764,-2.94257e-06,6.15243e-08,0.610062,0.00131194,-2.75799e-06,-2.53244e-08,0.611372,0.00130635,-2.83397e-06,3.97739e-08,0.612675,0.0013008,-2.71465e-06,-1.45618e-08,0.613973,0.00129533,-2.75833e-06,1.84733e-08,0.615266,0.00128986,-2.70291e-06,2.73606e-10,0.616553,0.00128446,-2.70209e-06,4.00367e-08,0.617835,0.00127918,-2.58198e-06,-4.12113e-08,0.619111,0.00127389,-2.70561e-06,6.52039e-08,0.620383,0.00126867,-2.51e-06,-4.07901e-08,0.621649,0.00126353,-2.63237e-06,3.83516e-08,0.62291,0.00125838,-2.51732e-06,6.59315e-09,0.624166,0.00125337,-2.49754e-06,-5.11939e-09,0.625416,0.00124836,-2.5129e-06,1.38846e-08,0.626662,0.00124337,-2.47124e-06,9.18514e-09,0.627903,0.00123846,-2.44369e-06,8.97952e-09,0.629139,0.0012336,-2.41675e-06,1.45012e-08,0.63037,0.00122881,-2.37325e-06,-7.37949e-09,0.631597,0.00122404,-2.39538e-06,1.50169e-08,0.632818,0.00121929,-2.35033e-06,6.91648e-09,0.634035,0.00121461,-2.32958e-06,1.69219e-08,0.635248,0.00121,-2.27882e-06,-1.49997e-08,0.636455,0.0012054,-2.32382e-06,4.30769e-08,0.637659,0.00120088,-2.19459e-06,-3.80986e-08,0.638857,0.00119638,-2.30888e-06,4.97134e-08,0.640051,0.00119191,-2.15974e-06,-4.15463e-08,0.641241,0.00118747,-2.28438e-06,5.68667e-08,0.642426,0.00118307,-2.11378e-06,-7.10641e-09,0.643607,0.00117882,-2.1351e-06,-2.8441e-08,0.644784,0.00117446,-2.22042e-06,6.12658e-08,0.645956,0.00117021,-2.03663e-06,-3.78083e-08,0.647124,0.00116602,-2.15005e-06,3.03627e-08,0.648288,0.00116181,-2.05896e-06,-2.40379e-08,0.649448,0.00115762,-2.13108e-06,6.57887e-08,0.650603,0.00115356,-1.93371e-06,-6.03028e-08,0.651755,0.00114951,-2.11462e-06,5.62134e-08,0.652902,0.00114545,-1.94598e-06,-4.53417e-08,0.654046,0.00114142,-2.082e-06,6.55489e-08,0.655185,0.00113745,-1.88536e-06,-3.80396e-08,0.656321,0.00113357,-1.99948e-06,2.70049e-08,0.657452,0.00112965,-1.91846e-06,-1.03755e-08,0.65858,0.00112578,-1.94959e-06,1.44973e-08,0.659704,0.00112192,-1.9061e-06,1.1991e-08,0.660824,0.00111815,-1.87012e-06,-2.85634e-09,0.66194,0.0011144,-1.87869e-06,-5.65782e-10,0.663053,0.00111064,-1.88039e-06,5.11947e-09,0.664162,0.0011069,-1.86503e-06,3.96924e-08,0.665267,0.00110328,-1.74595e-06,-4.46795e-08,0.666368,0.00109966,-1.87999e-06,1.98161e-08,0.667466,0.00109596,-1.82054e-06,2.502e-08,0.66856,0.00109239,-1.74548e-06,-6.86593e-10,0.669651,0.0010889,-1.74754e-06,-2.22739e-08,0.670738,0.00108534,-1.81437e-06,3.01776e-08,0.671821,0.0010818,-1.72383e-06,2.07732e-08,0.672902,0.00107841,-1.66151e-06,-5.36658e-08,0.673978,0.00107493,-1.82251e-06,7.46802e-08,0.675051,0.00107151,-1.59847e-06,-6.62411e-08,0.676121,0.00106811,-1.79719e-06,7.10748e-08,0.677188,0.00106473,-1.58397e-06,-3.92441e-08,0.678251,0.00106145,-1.7017e-06,2.62973e-08,0.679311,0.00105812,-1.62281e-06,-6.34035e-09,0.680367,0.00105486,-1.64183e-06,-9.36249e-10,0.68142,0.00105157,-1.64464e-06,1.00854e-08,0.68247,0.00104831,-1.61438e-06,2.01995e-08,0.683517,0.00104514,-1.55378e-06,-3.1279e-08,0.68456,0.00104194,-1.64762e-06,4.53114e-08,0.685601,0.00103878,-1.51169e-06,-3.07573e-08,0.686638,0.00103567,-1.60396e-06,1.81133e-08,0.687672,0.00103251,-1.54962e-06,1.79085e-08,0.688703,0.00102947,-1.49589e-06,-3.01428e-08,0.689731,0.00102639,-1.58632e-06,4.30583e-08,0.690756,0.00102334,-1.45715e-06,-2.28814e-08,0.691778,0.00102036,-1.52579e-06,-1.11373e-08,0.692797,0.00101727,-1.5592e-06,6.74305e-08,0.693812,0.00101436,-1.35691e-06,-7.97709e-08,0.694825,0.0010114,-1.59622e-06,7.28391e-08,0.695835,0.00100843,-1.37771e-06,-3.27715e-08,0.696842,0.00100558,-1.47602e-06,-1.35807e-09,0.697846,0.00100262,-1.48009e-06,3.82037e-08,0.698847,0.000999775,-1.36548e-06,-3.22474e-08,0.699846,0.000996948,-1.46223e-06,3.11809e-08,0.700841,0.000994117,-1.36868e-06,-3.28714e-08,0.701834,0.000991281,-1.4673e-06,4.07001e-08,0.702824,0.000988468,-1.3452e-06,-1.07197e-08,0.703811,0.000985746,-1.37736e-06,2.17866e-09,0.704795,0.000982998,-1.37082e-06,2.00521e-09,0.705777,0.000980262,-1.3648e-06,-1.01996e-08,0.706756,0.000977502,-1.3954e-06,3.87931e-08,0.707732,0.000974827,-1.27902e-06,-2.57632e-08,0.708706,0.000972192,-1.35631e-06,4.65513e-09,0.709676,0.000969493,-1.34235e-06,7.14257e-09,0.710645,0.00096683,-1.32092e-06,2.63791e-08,0.71161,0.000964267,-1.24178e-06,-5.30543e-08,0.712573,0.000961625,-1.40095e-06,6.66289e-08,0.713533,0.000959023,-1.20106e-06,-3.46474e-08,0.714491,0.000956517,-1.305e-06,1.23559e-08,0.715446,0.000953944,-1.26793e-06,-1.47763e-08,0.716399,0.000951364,-1.31226e-06,4.67494e-08,0.717349,0.000948879,-1.17201e-06,-5.3012e-08,0.718297,0.000946376,-1.33105e-06,4.60894e-08,0.719242,0.000943852,-1.19278e-06,-1.21366e-08,0.720185,0.00094143,-1.22919e-06,2.45673e-09,0.721125,0.000938979,-1.22182e-06,2.30966e-09,0.722063,0.000936543,-1.21489e-06,-1.16954e-08,0.722998,0.000934078,-1.24998e-06,4.44718e-08,0.723931,0.000931711,-1.11656e-06,-4.69823e-08,0.724861,0.000929337,-1.25751e-06,2.4248e-08,0.725789,0.000926895,-1.18477e-06,9.5949e-09,0.726715,0.000924554,-1.15598e-06,-3.02286e-09,0.727638,0.000922233,-1.16505e-06,2.49649e-09,0.72856,0.00091991,-1.15756e-06,-6.96321e-09,0.729478,0.000917575,-1.17845e-06,2.53564e-08,0.730395,0.000915294,-1.10238e-06,-3.48578e-08,0.731309,0.000912984,-1.20695e-06,5.44704e-08,0.732221,0.000910734,-1.04354e-06,-6.38144e-08,0.73313,0.000908455,-1.23499e-06,8.15781e-08,0.734038,0.00090623,-9.90253e-07,-8.3684e-08,0.734943,0.000903999,-1.2413e-06,7.43441e-08,0.735846,0.000901739,-1.01827e-06,-3.48787e-08,0.736746,0.000899598,-1.12291e-06,5.56596e-09,0.737645,0.000897369,-1.10621e-06,1.26148e-08,0.738541,0.000895194,-1.06837e-06,3.57935e-09,0.739435,0.000893068,-1.05763e-06,-2.69322e-08,0.740327,0.000890872,-1.13842e-06,4.45448e-08,0.741217,0.000888729,-1.00479e-06,-3.20376e-08,0.742105,0.000886623,-1.1009e-06,2.40011e-08,0.74299,0.000884493,-1.0289e-06,-4.36209e-09,0.743874,0.000882422,-1.04199e-06,-6.55268e-09,0.744755,0.000880319,-1.06164e-06,3.05728e-08,0.745634,0.000878287,-9.69926e-07,-5.61338e-08,0.746512,0.000876179,-1.13833e-06,7.4753e-08,0.747387,0.000874127,-9.14068e-07,-6.40644e-08,0.74826,0.000872106,-1.10626e-06,6.22955e-08,0.749131,0.000870081,-9.19375e-07,-6.59083e-08,0.75,0.000868044,-1.1171e-06,8.21284e-08,0.750867,0.000866056,-8.70714e-07,-8.37915e-08,0.751732,0.000864064,-1.12209e-06,7.42237e-08,0.752595,0.000862042,-8.99418e-07,-3.42894e-08,0.753456,0.00086014,-1.00229e-06,3.32955e-09,0.754315,0.000858146,-9.92297e-07,2.09712e-08,0.755173,0.000856224,-9.29384e-07,-2.76096e-08,0.756028,0.000854282,-1.01221e-06,2.98627e-08,0.756881,0.000852348,-9.22625e-07,-3.22365e-08,0.757733,0.000850406,-1.01933e-06,3.94786e-08,0.758582,0.000848485,-9.00898e-07,-6.46833e-09,0.75943,0.000846664,-9.20303e-07,-1.36052e-08,0.760275,0.000844783,-9.61119e-07,1.28447e-09,0.761119,0.000842864,-9.57266e-07,8.4674e-09,0.761961,0.000840975,-9.31864e-07,2.44506e-08,0.762801,0.000839185,-8.58512e-07,-4.6665e-08,0.763639,0.000837328,-9.98507e-07,4.30001e-08,0.764476,0.00083546,-8.69507e-07,-6.12609e-09,0.76531,0.000833703,-8.87885e-07,-1.84959e-08,0.766143,0.000831871,-9.43372e-07,2.05052e-08,0.766974,0.000830046,-8.81857e-07,-3.92026e-09,0.767803,0.000828271,-8.93618e-07,-4.82426e-09,0.768631,0.000826469,-9.0809e-07,2.32172e-08,0.769456,0.000824722,-8.38439e-07,-2.84401e-08,0.77028,0.00082296,-9.23759e-07,3.09386e-08,0.771102,0.000821205,-8.30943e-07,-3.57099e-08,0.771922,0.000819436,-9.38073e-07,5.22963e-08,0.772741,0.000817717,-7.81184e-07,-5.42658e-08,0.773558,0.000815992,-9.43981e-07,4.55579e-08,0.774373,0.000814241,-8.07308e-07,-8.75656e-09,0.775186,0.0008126,-8.33578e-07,-1.05315e-08,0.775998,0.000810901,-8.65172e-07,-8.72188e-09,0.776808,0.000809145,-8.91338e-07,4.54191e-08,0.777616,0.000807498,-7.5508e-07,-5.37454e-08,0.778423,0.000805827,-9.16317e-07,5.03532e-08,0.779228,0.000804145,-7.65257e-07,-2.84584e-08,0.780031,0.000802529,-8.50632e-07,3.87579e-09,0.780833,0.00080084,-8.39005e-07,1.29552e-08,0.781633,0.0007992,-8.00139e-07,3.90804e-09,0.782432,0.000797612,-7.88415e-07,-2.85874e-08,0.783228,0.000795949,-8.74177e-07,5.0837e-08,0.784023,0.000794353,-7.21666e-07,-5.55513e-08,0.784817,0.000792743,-8.8832e-07,5.21587e-08,0.785609,0.000791123,-7.31844e-07,-3.38744e-08,0.786399,0.000789558,-8.33467e-07,2.37342e-08,0.787188,0.000787962,-7.62264e-07,-1.45775e-09,0.787975,0.000786433,-7.66638e-07,-1.79034e-08,0.788761,0.000784846,-8.20348e-07,1.34665e-08,0.789545,0.000783246,-7.79948e-07,2.3642e-08,0.790327,0.000781757,-7.09022e-07,-4.84297e-08,0.791108,0.000780194,-8.54311e-07,5.08674e-08,0.791888,0.000778638,-7.01709e-07,-3.58303e-08,0.792666,0.000777127,-8.092e-07,3.28493e-08,0.793442,0.000775607,-7.10652e-07,-3.59624e-08,0.794217,0.000774078,-8.1854e-07,5.13959e-08,0.79499,0.000772595,-6.64352e-07,-5.04121e-08,0.795762,0.000771115,-8.15588e-07,3.10431e-08,0.796532,0.000769577,-7.22459e-07,-1.41557e-08,0.797301,0.00076809,-7.64926e-07,2.55795e-08,0.798069,0.000766636,-6.88187e-07,-2.85578e-08,0.798835,0.000765174,-7.73861e-07,2.90472e-08,0.799599,0.000763714,-6.86719e-07,-2.80262e-08,0.800362,0.000762256,-7.70798e-07,2.34531e-08,0.801123,0.000760785,-7.00438e-07,-6.18144e-09,0.801884,0.000759366,-7.18983e-07,1.27263e-09,0.802642,0.000757931,-7.15165e-07,1.09101e-09,0.803399,0.000756504,-7.11892e-07,-5.63675e-09,0.804155,0.000755064,-7.28802e-07,2.14559e-08,0.80491,0.00075367,-6.64434e-07,-2.05821e-08,0.805663,0.00075228,-7.26181e-07,1.26812e-09,0.806414,0.000750831,-7.22377e-07,1.55097e-08,0.807164,0.000749433,-6.75848e-07,-3.70216e-09,0.807913,0.00074807,-6.86954e-07,-7.0105e-10,0.80866,0.000746694,-6.89057e-07,6.5063e-09,0.809406,0.000745336,-6.69538e-07,-2.53242e-08,0.810151,0.000743921,-7.45511e-07,3.51858e-08,0.810894,0.000742535,-6.39953e-07,3.79034e-09,0.811636,0.000741267,-6.28582e-07,-5.03471e-08,0.812377,0.000739858,-7.79624e-07,7.83886e-08,0.813116,0.000738534,-5.44458e-07,-8.43935e-08,0.813854,0.000737192,-7.97638e-07,8.03714e-08,0.81459,0.000735838,-5.56524e-07,-5.82784e-08,0.815325,0.00073455,-7.31359e-07,3.35329e-08,0.816059,0.000733188,-6.3076e-07,-1.62486e-08,0.816792,0.000731878,-6.79506e-07,3.14614e-08,0.817523,0.000730613,-5.85122e-07,-4.99925e-08,0.818253,0.000729293,-7.35099e-07,4.92994e-08,0.818982,0.000727971,-5.87201e-07,-2.79959e-08,0.819709,0.000726712,-6.71189e-07,3.07959e-09,0.820435,0.000725379,-6.6195e-07,1.56777e-08,0.82116,0.000724102,-6.14917e-07,-6.18564e-09,0.821883,0.000722854,-6.33474e-07,9.06488e-09,0.822606,0.000721614,-6.06279e-07,-3.00739e-08,0.823327,0.000720311,-6.96501e-07,5.16262e-08,0.824046,0.000719073,-5.41623e-07,-5.72214e-08,0.824765,0.000717818,-7.13287e-07,5.80503e-08,0.825482,0.000716566,-5.39136e-07,-5.57703e-08,0.826198,0.00071532,-7.06447e-07,4.58215e-08,0.826912,0.000714045,-5.68983e-07,-8.30636e-09,0.827626,0.000712882,-5.93902e-07,-1.25961e-08,0.828338,0.000711656,-6.3169e-07,-9.13985e-10,0.829049,0.00071039,-6.34432e-07,1.62519e-08,0.829759,0.00070917,-5.85676e-07,-4.48904e-09,0.830468,0.000707985,-5.99143e-07,1.70418e-09,0.831175,0.000706792,-5.9403e-07,-2.32768e-09,0.831881,0.000705597,-6.01014e-07,7.60648e-09,0.832586,0.000704418,-5.78194e-07,-2.80982e-08,0.83329,0.000703177,-6.62489e-07,4.51817e-08,0.833993,0.000701988,-5.26944e-07,-3.34192e-08,0.834694,0.000700834,-6.27201e-07,2.88904e-08,0.835394,0.000699666,-5.4053e-07,-2.25378e-08,0.836093,0.000698517,-6.08143e-07,1.65589e-09,0.836791,0.000697306,-6.03176e-07,1.59142e-08,0.837488,0.000696147,-5.55433e-07,-5.70801e-09,0.838184,0.000695019,-5.72557e-07,6.91792e-09,0.838878,0.000693895,-5.51803e-07,-2.19637e-08,0.839571,0.000692725,-6.17694e-07,2.13321e-08,0.840263,0.000691554,-5.53698e-07,-3.75996e-09,0.840954,0.000690435,-5.64978e-07,-6.29219e-09,0.841644,0.000689287,-5.83855e-07,2.89287e-08,0.842333,0.000688206,-4.97068e-07,-4.98181e-08,0.843021,0.000687062,-6.46523e-07,5.11344e-08,0.843707,0.000685922,-4.9312e-07,-3.55102e-08,0.844393,0.00068483,-5.9965e-07,3.13019e-08,0.845077,0.000683724,-5.05745e-07,-3.00925e-08,0.84576,0.000682622,-5.96022e-07,2.94636e-08,0.846442,0.000681519,-5.07631e-07,-2.81572e-08,0.847123,0.000680419,-5.92103e-07,2.35606e-08,0.847803,0.000679306,-5.21421e-07,-6.48045e-09,0.848482,0.000678243,-5.40863e-07,2.36124e-09,0.849159,0.000677169,-5.33779e-07,-2.96461e-09,0.849836,0.000676092,-5.42673e-07,9.49728e-09,0.850512,0.000675035,-5.14181e-07,-3.50245e-08,0.851186,0.000673902,-6.19254e-07,7.09959e-08,0.851859,0.000672876,-4.06267e-07,-7.01453e-08,0.852532,0.000671853,-6.16703e-07,3.07714e-08,0.853203,0.000670712,-5.24388e-07,6.66423e-09,0.853873,0.000669684,-5.04396e-07,2.17629e-09,0.854542,0.000668681,-4.97867e-07,-1.53693e-08,0.855211,0.000667639,-5.43975e-07,-3.03752e-10,0.855878,0.000666551,-5.44886e-07,1.65844e-08,0.856544,0.000665511,-4.95133e-07,-6.42907e-09,0.857209,0.000664501,-5.1442e-07,9.13195e-09,0.857873,0.0006635,-4.87024e-07,-3.00987e-08,0.858536,0.000662435,-5.7732e-07,5.16584e-08,0.859198,0.000661436,-4.22345e-07,-5.73255e-08,0.859859,0.000660419,-5.94322e-07,5.84343e-08,0.860518,0.000659406,-4.19019e-07,-5.72022e-08,0.861177,0.000658396,-5.90626e-07,5.11653e-08,0.861835,0.000657368,-4.3713e-07,-2.82495e-08,0.862492,0.000656409,-5.21878e-07,2.22788e-09,0.863148,0.000655372,-5.15195e-07,1.9338e-08,0.863803,0.0006544,-4.5718e-07,-1.99754e-08,0.864457,0.000653425,-5.17107e-07,9.59024e-10,0.86511,0.000652394,-5.1423e-07,1.61393e-08,0.865762,0.000651414,-4.65812e-07,-5.91149e-09,0.866413,0.000650465,-4.83546e-07,7.50665e-09,0.867063,0.00064952,-4.61026e-07,-2.4115e-08,0.867712,0.000648526,-5.33371e-07,2.93486e-08,0.86836,0.000647547,-4.45325e-07,-3.36748e-08,0.869007,0.000646555,-5.4635e-07,4.57461e-08,0.869653,0.0006456,-4.09112e-07,-3.01002e-08,0.870298,0.000644691,-4.99412e-07,1.50501e-08,0.870942,0.000643738,-4.54262e-07,-3.01002e-08,0.871585,0.000642739,-5.44563e-07,4.57461e-08,0.872228,0.000641787,-4.07324e-07,-3.36748e-08,0.872869,0.000640871,-5.08349e-07,2.93486e-08,0.873509,0.000639943,-4.20303e-07,-2.4115e-08,0.874149,0.00063903,-4.92648e-07,7.50655e-09,0.874787,0.000638067,-4.70128e-07,-5.91126e-09,0.875425,0.000637109,-4.87862e-07,1.61385e-08,0.876062,0.000636182,-4.39447e-07,9.61961e-10,0.876697,0.000635306,-4.36561e-07,-1.99863e-08,0.877332,0.000634373,-4.9652e-07,1.93785e-08,0.877966,0.000633438,-4.38384e-07,2.07697e-09,0.878599,0.000632567,-4.32153e-07,-2.76864e-08,0.879231,0.00063162,-5.15212e-07,4.90641e-08,0.879862,0.000630737,-3.6802e-07,-4.93606e-08,0.880493,0.000629852,-5.16102e-07,2.9169e-08,0.881122,0.000628908,-4.28595e-07,-7.71083e-09,0.881751,0.000628027,-4.51727e-07,1.6744e-09,0.882378,0.000627129,-4.46704e-07,1.01317e-09,0.883005,0.000626239,-4.43665e-07,-5.72703e-09,0.883631,0.000625334,-4.60846e-07,2.1895e-08,0.884255,0.000624478,-3.95161e-07,-2.22481e-08,0.88488,0.000623621,-4.61905e-07,7.4928e-09,0.885503,0.00062272,-4.39427e-07,-7.72306e-09,0.886125,0.000621818,-4.62596e-07,2.33995e-08,0.886746,0.000620963,-3.92398e-07,-2.62704e-08,0.887367,0.000620099,-4.71209e-07,2.20775e-08,0.887987,0.000619223,-4.04976e-07,-2.43496e-09,0.888605,0.000618406,-4.12281e-07,-1.23377e-08,0.889223,0.000617544,-4.49294e-07,-7.81876e-09,0.88984,0.000616622,-4.72751e-07,4.36128e-08,0.890457,0.000615807,-3.41912e-07,-4.7423e-08,0.891072,0.000614981,-4.84181e-07,2.68698e-08,0.891687,0.000614093,-4.03572e-07,-4.51384e-10,0.8923,0.000613285,-4.04926e-07,-2.50643e-08,0.892913,0.0006124,-4.80119e-07,4.11038e-08,0.893525,0.000611563,-3.56808e-07,-2.01414e-08,0.894136,0.000610789,-4.17232e-07,-2.01426e-08,0.894747,0.000609894,-4.7766e-07,4.11073e-08,0.895356,0.000609062,-3.54338e-07,-2.50773e-08,0.895965,0.000608278,-4.2957e-07,-4.02954e-10,0.896573,0.000607418,-4.30779e-07,2.66891e-08,0.89718,0.000606636,-3.50711e-07,-4.67489e-08,0.897786,0.000605795,-4.90958e-07,4.10972e-08,0.898391,0.000604936,-3.67666e-07,1.56948e-09,0.898996,0.000604205,-3.62958e-07,-4.73751e-08,0.8996,0.000603337,-5.05083e-07,6.87214e-08,0.900202,0.000602533,-2.98919e-07,-4.86966e-08,0.900805,0.000601789,-4.45009e-07,6.85589e-09,0.901406,0.00060092,-4.24441e-07,2.1273e-08,0.902007,0.000600135,-3.60622e-07,-3.23434e-08,0.902606,0.000599317,-4.57652e-07,4.84959e-08,0.903205,0.000598547,-3.12164e-07,-4.24309e-08,0.903803,0.000597795,-4.39457e-07,2.01844e-09,0.904401,0.000596922,-4.33402e-07,3.43571e-08,0.904997,0.000596159,-3.30331e-07,-2.02374e-08,0.905593,0.000595437,-3.91043e-07,-1.30123e-08,0.906188,0.000594616,-4.3008e-07,1.26819e-08,0.906782,0.000593794,-3.92034e-07,2.18894e-08,0.907376,0.000593076,-3.26366e-07,-4.06349e-08,0.907968,0.000592301,-4.4827e-07,2.1441e-08,0.90856,0.000591469,-3.83947e-07,1.44754e-08,0.909151,0.000590744,-3.40521e-07,-1.97379e-08,0.909742,0.000590004,-3.99735e-07,4.87161e-09,0.910331,0.000589219,-3.8512e-07,2.51532e-10,0.91092,0.00058845,-3.84366e-07,-5.87776e-09,0.911508,0.000587663,-4.01999e-07,2.32595e-08,0.912096,0.000586929,-3.3222e-07,-2.75554e-08,0.912682,0.000586182,-4.14887e-07,2.73573e-08,0.913268,0.000585434,-3.32815e-07,-2.22692e-08,0.913853,0.000584702,-3.99622e-07,2.11486e-09,0.914437,0.000583909,-3.93278e-07,1.38098e-08,0.915021,0.000583164,-3.51848e-07,2.25042e-09,0.915604,0.000582467,-3.45097e-07,-2.28115e-08,0.916186,0.000581708,-4.13531e-07,2.93911e-08,0.916767,0.000580969,-3.25358e-07,-3.51481e-08,0.917348,0.000580213,-4.30803e-07,5.15967e-08,0.917928,0.000579506,-2.76012e-07,-5.20296e-08,0.918507,0.000578798,-4.32101e-07,3.73124e-08,0.919085,0.000578046,-3.20164e-07,-3.76154e-08,0.919663,0.000577293,-4.3301e-07,5.35447e-08,0.92024,0.000576587,-2.72376e-07,-5.7354e-08,0.920816,0.000575871,-4.44438e-07,5.66621e-08,0.921391,0.000575152,-2.74452e-07,-5.00851e-08,0.921966,0.000574453,-4.24707e-07,2.4469e-08,0.92254,0.000573677,-3.513e-07,1.18138e-08,0.923114,0.000573009,-3.15859e-07,-1.21195e-08,0.923686,0.000572341,-3.52217e-07,-2.29403e-08,0.924258,0.000571568,-4.21038e-07,4.4276e-08,0.924829,0.000570859,-2.8821e-07,-3.49546e-08,0.9254,0.000570178,-3.93074e-07,3.59377e-08,0.92597,0.000569499,-2.85261e-07,-4.91915e-08,0.926539,0.000568781,-4.32835e-07,4.16189e-08,0.927107,0.00056804,-3.07979e-07,1.92523e-09,0.927675,0.00056743,-3.02203e-07,-4.93198e-08,0.928242,0.000566678,-4.50162e-07,7.61447e-08,0.928809,0.000566006,-2.21728e-07,-7.6445e-08,0.929374,0.000565333,-4.51063e-07,5.08216e-08,0.929939,0.000564583,-2.98599e-07,-7.63212e-09,0.930503,0.000563963,-3.21495e-07,-2.02931e-08,0.931067,0.000563259,-3.82374e-07,2.92001e-08,0.93163,0.000562582,-2.94774e-07,-3.69025e-08,0.932192,0.000561882,-4.05482e-07,5.88053e-08,0.932754,0.000561247,-2.29066e-07,-7.91094e-08,0.933315,0.000560552,-4.66394e-07,7.88184e-08,0.933875,0.000559856,-2.29939e-07,-5.73501e-08,0.934434,0.000559224,-4.01989e-07,3.13727e-08,0.934993,0.000558514,-3.07871e-07,-8.53611e-09,0.935551,0.000557873,-3.33479e-07,2.77175e-09,0.936109,0.000557214,-3.25164e-07,-2.55091e-09,0.936666,0.000556556,-3.32817e-07,7.43188e-09,0.937222,0.000555913,-3.10521e-07,-2.71766e-08,0.937778,0.00055521,-3.92051e-07,4.167e-08,0.938333,0.000554551,-2.67041e-07,-2.02941e-08,0.938887,0.000553956,-3.27923e-07,-2.00984e-08,0.93944,0.00055324,-3.88218e-07,4.10828e-08,0.939993,0.000552587,-2.6497e-07,-2.50237e-08,0.940546,0.000551982,-3.40041e-07,-5.92583e-10,0.941097,0.0005513,-3.41819e-07,2.7394e-08,0.941648,0.000550698,-2.59637e-07,-4.93788e-08,0.942199,0.000550031,-4.07773e-07,5.09119e-08,0.942748,0.000549368,-2.55038e-07,-3.50595e-08,0.943297,0.000548753,-3.60216e-07,2.97214e-08,0.943846,0.000548122,-2.71052e-07,-2.42215e-08,0.944394,0.000547507,-3.43716e-07,7.55985e-09,0.944941,0.000546842,-3.21037e-07,-6.01796e-09,0.945487,0.000546182,-3.3909e-07,1.65119e-08,0.946033,0.000545553,-2.89555e-07,-4.2498e-10,0.946578,0.000544973,-2.9083e-07,-1.4812e-08,0.947123,0.000544347,-3.35266e-07,6.83068e-11,0.947667,0.000543676,-3.35061e-07,1.45388e-08,0.94821,0.00054305,-2.91444e-07,1.38123e-09,0.948753,0.000542471,-2.87301e-07,-2.00637e-08,0.949295,0.000541836,-3.47492e-07,1.92688e-08,0.949837,0.000541199,-2.89685e-07,2.59298e-09,0.950378,0.000540628,-2.81906e-07,-2.96407e-08,0.950918,0.000539975,-3.70829e-07,5.63652e-08,0.951458,0.000539402,-2.01733e-07,-7.66107e-08,0.951997,0.000538769,-4.31565e-07,7.12638e-08,0.952535,0.00053812,-2.17774e-07,-2.96305e-08,0.953073,0.000537595,-3.06665e-07,-1.23464e-08,0.95361,0.000536945,-3.43704e-07,1.94114e-08,0.954147,0.000536316,-2.8547e-07,-5.69451e-09,0.954683,0.000535728,-3.02554e-07,3.36666e-09,0.955219,0.000535133,-2.92454e-07,-7.77208e-09,0.955753,0.000534525,-3.1577e-07,2.77216e-08,0.956288,0.000533976,-2.32605e-07,-4.35097e-08,0.956821,0.00053338,-3.63134e-07,2.7108e-08,0.957354,0.000532735,-2.8181e-07,-5.31772e-09,0.957887,0.000532156,-2.97764e-07,-5.83718e-09,0.958419,0.000531543,-3.15275e-07,2.86664e-08,0.95895,0.000530998,-2.29276e-07,-4.9224e-08,0.959481,0.000530392,-3.76948e-07,4.90201e-08,0.960011,0.000529785,-2.29887e-07,-2.76471e-08,0.96054,0.000529243,-3.12829e-07,1.96385e-09,0.961069,0.000528623,-3.06937e-07,1.97917e-08,0.961598,0.000528068,-2.47562e-07,-2.15261e-08,0.962125,0.000527508,-3.1214e-07,6.70795e-09,0.962653,0.000526904,-2.92016e-07,-5.30573e-09,0.963179,0.000526304,-3.07934e-07,1.4515e-08,0.963705,0.000525732,-2.64389e-07,6.85048e-09,0.964231,0.000525224,-2.43837e-07,-4.19169e-08,0.964756,0.00052461,-3.69588e-07,4.1608e-08,0.96528,0.000523996,-2.44764e-07,-5.30598e-09,0.965804,0.000523491,-2.60682e-07,-2.03841e-08,0.966327,0.000522908,-3.21834e-07,2.72378e-08,0.966849,0.000522346,-2.40121e-07,-2.89625e-08,0.967371,0.000521779,-3.27008e-07,2.90075e-08,0.967893,0.000521212,-2.39986e-07,-2.74629e-08,0.968414,0.00052065,-3.22374e-07,2.12396e-08,0.968934,0.000520069,-2.58656e-07,2.10922e-09,0.969454,0.000519558,-2.52328e-07,-2.96765e-08,0.969973,0.000518964,-3.41357e-07,5.6992e-08,0.970492,0.000518452,-1.70382e-07,-7.90821e-08,0.97101,0.000517874,-4.07628e-07,8.05224e-08,0.971528,0.000517301,-1.66061e-07,-6.41937e-08,0.972045,0.000516776,-3.58642e-07,5.70429e-08,0.972561,0.00051623,-1.87513e-07,-4.47686e-08,0.973077,0.00051572,-3.21819e-07,2.82237e-09,0.973593,0.000515085,-3.13352e-07,3.34792e-08,0.974108,0.000514559,-2.12914e-07,-1.75298e-08,0.974622,0.000514081,-2.65503e-07,-2.29648e-08,0.975136,0.000513481,-3.34398e-07,4.97843e-08,0.975649,0.000512961,-1.85045e-07,-5.6963e-08,0.976162,0.00051242,-3.55934e-07,5.88585e-08,0.976674,0.000511885,-1.79359e-07,-5.92616e-08,0.977185,0.000511348,-3.57143e-07,5.89785e-08,0.977696,0.000510811,-1.80208e-07,-5.74433e-08,0.978207,0.000510278,-3.52538e-07,5.15854e-08,0.978717,0.000509728,-1.97781e-07,-2.9689e-08,0.979226,0.000509243,-2.86848e-07,7.56591e-09,0.979735,0.000508692,-2.64151e-07,-5.74649e-10,0.980244,0.000508162,-2.65875e-07,-5.26732e-09,0.980752,0.000507615,-2.81677e-07,2.16439e-08,0.981259,0.000507116,-2.16745e-07,-2.17037e-08,0.981766,0.000506618,-2.81856e-07,5.56636e-09,0.982272,0.000506071,-2.65157e-07,-5.61689e-10,0.982778,0.000505539,-2.66842e-07,-3.31963e-09,0.983283,0.000504995,-2.76801e-07,1.38402e-08,0.983788,0.000504483,-2.3528e-07,7.56339e-09,0.984292,0.000504035,-2.1259e-07,-4.40938e-08,0.984796,0.000503478,-3.44871e-07,4.96026e-08,0.985299,0.000502937,-1.96064e-07,-3.51071e-08,0.985802,0.000502439,-3.01385e-07,3.12212e-08,0.986304,0.00050193,-2.07721e-07,-3.0173e-08,0.986806,0.000501424,-2.9824e-07,2.9866e-08,0.987307,0.000500917,-2.08642e-07,-2.96865e-08,0.987808,0.000500411,-2.97702e-07,2.92753e-08,0.988308,0.000499903,-2.09876e-07,-2.78101e-08,0.988807,0.0004994,-2.93306e-07,2.23604e-08,0.989307,0.000498881,-2.26225e-07,-2.02681e-09,0.989805,0.000498422,-2.32305e-07,-1.42531e-08,0.990303,0.000497915,-2.75065e-07,-5.65232e-10,0.990801,0.000497363,-2.76761e-07,1.65141e-08,0.991298,0.000496859,-2.27218e-07,-5.88639e-09,0.991795,0.000496387,-2.44878e-07,7.0315e-09,0.992291,0.000495918,-2.23783e-07,-2.22396e-08,0.992787,0.000495404,-2.90502e-07,2.23224e-08,0.993282,0.00049489,-2.23535e-07,-7.44543e-09,0.993776,0.000494421,-2.45871e-07,7.45924e-09,0.994271,0.000493951,-2.23493e-07,-2.23915e-08,0.994764,0.000493437,-2.90668e-07,2.25021e-08,0.995257,0.000492923,-2.23161e-07,-8.01218e-09,0.99575,0.000492453,-2.47198e-07,9.54669e-09,0.996242,0.000491987,-2.18558e-07,-3.01746e-08,0.996734,0.000491459,-3.09082e-07,5.1547e-08,0.997225,0.000490996,-1.54441e-07,-5.68039e-08,0.997716,0.000490517,-3.24853e-07,5.64594e-08,0.998206,0.000490036,-1.55474e-07,-4.98245e-08,0.998696,0.000489576,-3.04948e-07,2.36292e-08,0.999186,0.000489037,-2.3406e-07,1.49121e-08,0.999674,0.000488613,-1.89324e-07,-2.3673e-08,1.00016,0.000488164,-2.60343e-07,2.01754e-08,1.00065,0.000487704,-1.99816e-07,-5.70288e-08,1.00114,0.000487133,-3.70903e-07,8.87303e-08,1.00162,0.000486657,-1.04712e-07,-5.94737e-08,1.00211,0.000486269,-2.83133e-07,2.99553e-08,1.0026,0.000485793,-1.93267e-07,-6.03474e-08,1.00308,0.000485225,-3.74309e-07,9.2225e-08,1.00357,0.000484754,-9.76345e-08,-7.0134e-08,1.00405,0.000484348,-3.08036e-07,6.91016e-08,1.00454,0.000483939,-1.00731e-07,-8.70633e-08,1.00502,0.000483476,-3.61921e-07,4.07328e-08,1.0055,0.000482875,-2.39723e-07,4.33413e-08,1.00599,0.000482525,-1.09699e-07,-9.48886e-08,1.00647,0.000482021,-3.94365e-07,9.77947e-08,1.00695,0.000481526,-1.00981e-07,-5.78713e-08,1.00743,0.00048115,-2.74595e-07,1.44814e-08,1.00791,0.000480645,-2.31151e-07,-5.42665e-11,1.00839,0.000480182,-2.31314e-07,-1.42643e-08,1.00887,0.000479677,-2.74106e-07,5.71115e-08,1.00935,0.0004793,-1.02772e-07,-9.49724e-08,1.00983,0.000478809,-3.87689e-07,8.43596e-08,1.01031,0.000478287,-1.3461e-07,-4.04755e-09,1.01079,0.000478006,-1.46753e-07,-6.81694e-08,1.01127,0.000477508,-3.51261e-07,3.83067e-08,1.01174,0.00047692,-2.36341e-07,3.41521e-08,1.01222,0.00047655,-1.33885e-07,-5.57058e-08,1.0127,0.000476115,-3.01002e-07,6.94616e-08,1.01317,0.000475721,-9.26174e-08,-1.02931e-07,1.01365,0.000475227,-4.01412e-07,1.03846e-07,1.01412,0.000474736,-8.98751e-08,-7.40321e-08,1.0146,0.000474334,-3.11971e-07,7.30735e-08,1.01507,0.00047393,-9.27508e-08,-9.90527e-08,1.01554,0.000473447,-3.89909e-07,8.47188e-08,1.01602,0.000472921,-1.35753e-07,-1.40381e-09,1.01649,0.000472645,-1.39964e-07,-7.91035e-08,1.01696,0.000472128,-3.77275e-07,7.93993e-08,1.01744,0.000471612,-1.39077e-07,-7.52607e-11,1.01791,0.000471334,-1.39302e-07,-7.90983e-08,1.01838,0.000470818,-3.76597e-07,7.80499e-08,1.01885,0.000470299,-1.42448e-07,5.31733e-09,1.01932,0.00047003,-1.26496e-07,-9.93193e-08,1.01979,0.000469479,-4.24453e-07,1.53541e-07,1.02026,0.00046909,3.617e-08,-1.57217e-07,1.02073,0.000468691,-4.35482e-07,1.177e-07,1.02119,0.000468173,-8.23808e-08,-7.51659e-08,1.02166,0.000467783,-3.07878e-07,6.37538e-08,1.02213,0.000467358,-1.16617e-07,-6.064e-08,1.0226,0.000466943,-2.98537e-07,5.9597e-08,1.02306,0.000466525,-1.19746e-07,-5.85386e-08,1.02353,0.00046611,-2.95362e-07,5.53482e-08,1.024,0.000465685,-1.29317e-07,-4.36449e-08,1.02446,0.000465296,-2.60252e-07,2.20268e-11,1.02493,0.000464775,-2.60186e-07,4.35568e-08,1.02539,0.000464386,-1.29516e-07,-5.50398e-08,1.02586,0.000463961,-2.94635e-07,5.73932e-08,1.02632,0.000463544,-1.22456e-07,-5.53236e-08,1.02678,0.000463133,-2.88426e-07,4.46921e-08,1.02725,0.000462691,-1.5435e-07,-4.23534e-09,1.02771,0.000462369,-1.67056e-07,-2.77507e-08,1.02817,0.000461952,-2.50308e-07,-3.97101e-09,1.02863,0.000461439,-2.62221e-07,4.36348e-08,1.02909,0.000461046,-1.31317e-07,-5.13589e-08,1.02955,0.000460629,-2.85394e-07,4.25913e-08,1.03001,0.000460186,-1.5762e-07,2.0285e-10,1.03047,0.000459871,-1.57011e-07,-4.34027e-08,1.03093,0.000459427,-2.87219e-07,5.41987e-08,1.03139,0.000459015,-1.24623e-07,-5.4183e-08,1.03185,0.000458604,-2.87172e-07,4.33239e-08,1.03231,0.000458159,-1.572e-07,9.65817e-11,1.03277,0.000457845,-1.56911e-07,-4.37103e-08,1.03323,0.0004574,-2.88041e-07,5.55351e-08,1.03368,0.000456991,-1.21436e-07,-5.9221e-08,1.03414,0.00045657,-2.99099e-07,6.21394e-08,1.0346,0.000456158,-1.1268e-07,-7.01275e-08,1.03505,0.000455723,-3.23063e-07,9.91614e-08,1.03551,0.000455374,-2.55788e-08,-8.80996e-08,1.03596,0.000455058,-2.89878e-07,1.48184e-08,1.03642,0.000454523,-2.45422e-07,2.88258e-08,1.03687,0.000454119,-1.58945e-07,-1.09125e-08,1.03733,0.000453768,-1.91682e-07,1.48241e-08,1.03778,0.000453429,-1.4721e-07,-4.83838e-08,1.03823,0.00045299,-2.92361e-07,5.95019e-08,1.03869,0.000452584,-1.13856e-07,-7.04146e-08,1.03914,0.000452145,-3.25099e-07,1.02947e-07,1.03959,0.000451803,-1.62583e-08,-1.02955e-07,1.04004,0.000451462,-3.25123e-07,7.04544e-08,1.04049,0.000451023,-1.1376e-07,-5.96534e-08,1.04094,0.000450616,-2.9272e-07,4.89499e-08,1.04139,0.000450178,-1.45871e-07,-1.69369e-08,1.04184,0.000449835,-1.96681e-07,1.87977e-08,1.04229,0.000449498,-1.40288e-07,-5.82539e-08,1.04274,0.000449043,-3.1505e-07,9.50087e-08,1.04319,0.000448698,-3.00238e-08,-8.33623e-08,1.04364,0.000448388,-2.80111e-07,2.20363e-11,1.04409,0.000447828,-2.80045e-07,8.32742e-08,1.04454,0.000447517,-3.02221e-08,-9.47002e-08,1.04498,0.000447173,-3.14323e-07,5.7108e-08,1.04543,0.000446716,-1.42999e-07,-1.45225e-08,1.04588,0.000446386,-1.86566e-07,9.82022e-10,1.04632,0.000446016,-1.8362e-07,1.05944e-08,1.04677,0.00044568,-1.51837e-07,-4.33597e-08,1.04721,0.000445247,-2.81916e-07,4.36352e-08,1.04766,0.000444814,-1.51011e-07,-1.19717e-08,1.0481,0.000444476,-1.86926e-07,4.25158e-09,1.04855,0.000444115,-1.74171e-07,-5.03461e-09,1.04899,0.000443751,-1.89275e-07,1.58868e-08,1.04944,0.00044342,-1.41614e-07,-5.85127e-08,1.04988,0.000442961,-3.17152e-07,9.89548e-08,1.05032,0.000442624,-2.0288e-08,-9.88878e-08,1.05076,0.000442287,-3.16951e-07,5.81779e-08,1.05121,0.000441827,-1.42418e-07,-1.46144e-08,1.05165,0.000441499,-1.86261e-07,2.79892e-10,1.05209,0.000441127,-1.85421e-07,1.34949e-08,1.05253,0.000440797,-1.44937e-07,-5.42594e-08,1.05297,0.000440344,-3.07715e-07,8.43335e-08,1.05341,0.000439982,-5.47146e-08,-4.46558e-08,1.05385,0.000439738,-1.88682e-07,-2.49193e-08,1.05429,0.000439286,-2.6344e-07,2.5124e-08,1.05473,0.000438835,-1.88068e-07,4.36328e-08,1.05517,0.000438589,-5.71699e-08,-8.04459e-08,1.05561,0.000438234,-2.98508e-07,3.97324e-08,1.05605,0.000437756,-1.79311e-07,4.07258e-08,1.05648,0.000437519,-5.71332e-08,-8.34263e-08,1.05692,0.000437155,-3.07412e-07,5.45608e-08,1.05736,0.000436704,-1.4373e-07,-1.56078e-08,1.05779,0.000436369,-1.90553e-07,7.87043e-09,1.05823,0.000436012,-1.66942e-07,-1.58739e-08,1.05867,0.00043563,-2.14563e-07,5.56251e-08,1.0591,0.000435368,-4.76881e-08,-8.74172e-08,1.05954,0.000435011,-3.0994e-07,5.56251e-08,1.05997,0.000434558,-1.43064e-07,-1.58739e-08,1.06041,0.000434224,-1.90686e-07,7.87042e-09,1.06084,0.000433866,-1.67075e-07,-1.56078e-08,1.06127,0.000433485,-2.13898e-07,5.45609e-08,1.06171,0.000433221,-5.02157e-08,-8.34263e-08,1.06214,0.00043287,-3.00495e-07,4.07258e-08,1.06257,0.000432391,-1.78317e-07,3.97325e-08,1.063,0.000432154,-5.91198e-08,-8.04464e-08,1.06344,0.000431794,-3.00459e-07,4.36347e-08,1.06387,0.000431324,-1.69555e-07,2.5117e-08,1.0643,0.000431061,-9.42041e-08,-2.48934e-08,1.06473,0.000430798,-1.68884e-07,-4.47527e-08,1.06516,0.000430326,-3.03142e-07,8.46951e-08,1.06559,0.000429973,-4.90573e-08,-5.56089e-08,1.06602,0.000429708,-2.15884e-07,1.85314e-08,1.06645,0.000429332,-1.6029e-07,-1.85166e-08,1.06688,0.000428956,-2.1584e-07,5.5535e-08,1.06731,0.000428691,-4.92347e-08,-8.44142e-08,1.06774,0.000428339,-3.02477e-07,4.37032e-08,1.06816,0.000427865,-1.71368e-07,2.88107e-08,1.06859,0.000427609,-8.49356e-08,-3.97367e-08,1.06902,0.00042732,-2.04146e-07,1.09267e-08,1.06945,0.000426945,-1.71365e-07,-3.97023e-09,1.06987,0.00042659,-1.83276e-07,4.9542e-09,1.0703,0.000426238,-1.68414e-07,-1.58466e-08,1.07073,0.000425854,-2.15953e-07,5.84321e-08,1.07115,0.000425597,-4.0657e-08,-9.86725e-08,1.07158,0.00042522,-3.36674e-07,9.78392e-08,1.072,0.00042484,-4.31568e-08,-5.42658e-08,1.07243,0.000424591,-2.05954e-07,1.45377e-11,1.07285,0.000424179,-2.0591e-07,5.42076e-08,1.07328,0.00042393,-4.32877e-08,-9.76357e-08,1.0737,0.00042355,-3.36195e-07,9.79165e-08,1.07412,0.000423172,-4.24451e-08,-5.56118e-08,1.07455,0.00042292,-2.09281e-07,5.32143e-09,1.07497,0.000422518,-1.93316e-07,3.43261e-08,1.07539,0.000422234,-9.0338e-08,-2.34165e-08,1.07581,0.000421983,-1.60588e-07,-5.98692e-08,1.07623,0.000421482,-3.40195e-07,1.43684e-07,1.07666,0.000421233,9.08574e-08,-1.5724e-07,1.07708,0.000420943,-3.80862e-07,1.27647e-07,1.0775,0.000420564,2.0791e-09,-1.1493e-07,1.07792,0.000420223,-3.4271e-07,9.36534e-08,1.07834,0.000419819,-6.17499e-08,-2.12653e-08,1.07876,0.000419632,-1.25546e-07,-8.59219e-09,1.07918,0.000419355,-1.51322e-07,-6.35752e-08,1.0796,0.000418861,-3.42048e-07,1.43684e-07,1.08002,0.000418608,8.90034e-08,-1.53532e-07,1.08043,0.000418326,-3.71593e-07,1.12817e-07,1.08085,0.000417921,-3.31414e-08,-5.93184e-08,1.08127,0.000417677,-2.11097e-07,5.24697e-09,1.08169,0.00041727,-1.95356e-07,3.83305e-08,1.0821,0.000416995,-8.03642e-08,-3.93597e-08,1.08252,0.000416716,-1.98443e-07,-1.0094e-10,1.08294,0.000416319,-1.98746e-07,3.97635e-08,1.08335,0.00041604,-7.94557e-08,-3.97437e-08,1.08377,0.000415762,-1.98687e-07,1.94215e-12,1.08419,0.000415365,-1.98681e-07,3.97359e-08,1.0846,0.000415087,-7.94732e-08,-3.97362e-08,1.08502,0.000414809,-1.98682e-07,-4.31063e-13,1.08543,0.000414411,-1.98683e-07,3.97379e-08,1.08584,0.000414133,-7.94694e-08,-3.97418e-08,1.08626,0.000413855,-1.98695e-07,2.00563e-11,1.08667,0.000413458,-1.98635e-07,3.96616e-08,1.08709,0.000413179,-7.965e-08,-3.9457e-08,1.0875,0.000412902,-1.98021e-07,-1.04281e-09,1.08791,0.000412502,-2.01149e-07,4.36282e-08,1.08832,0.000412231,-7.02648e-08,-5.42608e-08,1.08874,0.000411928,-2.33047e-07,5.42057e-08,1.08915,0.000411624,-7.04301e-08,-4.33527e-08,1.08956,0.000411353,-2.00488e-07,-4.07378e-12,1.08997,0.000410952,-2.005e-07,4.3369e-08,1.09038,0.000410681,-7.03934e-08,-5.42627e-08,1.09079,0.000410378,-2.33182e-07,5.44726e-08,1.0912,0.000410075,-6.97637e-08,-4.44186e-08,1.09161,0.000409802,-2.03019e-07,3.99235e-09,1.09202,0.000409408,-1.91042e-07,2.84491e-08,1.09243,0.000409111,-1.05695e-07,1.42043e-09,1.09284,0.000408904,-1.01434e-07,-3.41308e-08,1.09325,0.000408599,-2.03826e-07,1.58937e-08,1.09366,0.000408239,-1.56145e-07,-2.94438e-08,1.09406,0.000407838,-2.44476e-07,1.01881e-07,1.09447,0.000407655,6.11676e-08,-1.39663e-07,1.09488,0.000407358,-3.57822e-07,9.91432e-08,1.09529,0.00040694,-6.03921e-08,-1.84912e-08,1.09569,0.000406764,-1.15866e-07,-2.51785e-08,1.0961,0.000406457,-1.91401e-07,-4.03115e-12,1.09651,0.000406074,-1.91413e-07,2.51947e-08,1.09691,0.000405767,-1.15829e-07,1.84346e-08,1.09732,0.00040559,-6.05254e-08,-9.89332e-08,1.09772,0.000405172,-3.57325e-07,1.3888e-07,1.09813,0.000404874,5.93136e-08,-9.8957e-08,1.09853,0.000404696,-2.37557e-07,1.853e-08,1.09894,0.000404277,-1.81968e-07,2.48372e-08,1.09934,0.000403987,-1.07456e-07,1.33047e-09,1.09975,0.000403776,-1.03465e-07,-3.01591e-08,1.10015,0.000403479,-1.93942e-07,9.66054e-11,1.10055,0.000403091,-1.93652e-07,2.97727e-08,1.10096,0.000402793,-1.04334e-07,2.19273e-11,1.10136,0.000402585,-1.04268e-07,-2.98604e-08,1.10176,0.000402287,-1.93849e-07,2.10325e-10,1.10216,0.0004019,-1.93218e-07,2.90191e-08,1.10256,0.0004016,-1.06161e-07,2.92264e-09,1.10297,0.000401397,-9.73931e-08,-4.07096e-08,1.10337,0.00040108,-2.19522e-07,4.07067e-08,1.10377,0.000400763,-9.7402e-08,-2.90783e-09,1.10417,0.000400559,-1.06126e-07,-2.90754e-08,1.10457,0.00040026,-1.93352e-07,9.00021e-14,1.10497,0.000399873,-1.93351e-07,2.9075e-08,1.10537,0.000399574,-1.06126e-07,2.90902e-09,1.10577,0.00039937,-9.73992e-08,-4.07111e-08,1.10617,0.000399053,-2.19533e-07,4.07262e-08,1.10657,0.000398736,-9.73541e-08,-2.98424e-09,1.10697,0.000398533,-1.06307e-07,-2.87892e-08,1.10736,0.000398234,-1.92674e-07,-1.06824e-09,1.10776,0.000397845,-1.95879e-07,3.30622e-08,1.10816,0.000397552,-9.66926e-08,-1.19712e-08,1.10856,0.000397323,-1.32606e-07,1.48225e-08,1.10895,0.000397102,-8.81387e-08,-4.73187e-08,1.10935,0.000396784,-2.30095e-07,5.52429e-08,1.10975,0.00039649,-6.4366e-08,-5.44437e-08,1.11014,0.000396198,-2.27697e-07,4.33226e-08,1.11054,0.000395872,-9.77293e-08,3.62656e-10,1.11094,0.000395678,-9.66414e-08,-4.47732e-08,1.11133,0.00039535,-2.30961e-07,5.95208e-08,1.11173,0.000395067,-5.23985e-08,-7.41008e-08,1.11212,0.00039474,-2.74701e-07,1.17673e-07,1.11252,0.000394543,7.83181e-08,-1.58172e-07,1.11291,0.000394225,-3.96199e-07,1.57389e-07,1.1133,0.000393905,7.59679e-08,-1.13756e-07,1.1137,0.000393716,-2.653e-07,5.92165e-08,1.11409,0.000393363,-8.76507e-08,-3.90074e-09,1.11449,0.000393176,-9.93529e-08,-4.36136e-08,1.11488,0.000392846,-2.30194e-07,5.91457e-08,1.11527,0.000392563,-5.27564e-08,-7.376e-08,1.11566,0.000392237,-2.74037e-07,1.16685e-07,1.11606,0.000392039,7.60189e-08,-1.54562e-07,1.11645,0.000391727,-3.87667e-07,1.43935e-07,1.11684,0.000391384,4.4137e-08,-6.35487e-08,1.11723,0.000391281,-1.46509e-07,-8.94896e-09,1.11762,0.000390961,-1.73356e-07,-1.98647e-08,1.11801,0.000390555,-2.3295e-07,8.8408e-08,1.1184,0.000390354,3.22736e-08,-9.53486e-08,1.11879,0.000390133,-2.53772e-07,5.45677e-08,1.11918,0.000389789,-9.0069e-08,-3.71296e-09,1.11957,0.000389598,-1.01208e-07,-3.97159e-08,1.11996,0.000389276,-2.20355e-07,4.33671e-08,1.12035,0.000388966,-9.02542e-08,-1.45431e-08,1.12074,0.000388741,-1.33883e-07,1.48052e-08,1.12113,0.000388518,-8.94678e-08,-4.46778e-08,1.12152,0.000388205,-2.23501e-07,4.46966e-08,1.12191,0.000387892,-8.94114e-08,-1.48992e-08,1.12229,0.000387669,-1.34109e-07,1.49003e-08,1.12268,0.000387445,-8.94082e-08,-4.47019e-08,1.12307,0.000387132,-2.23514e-07,4.4698e-08,1.12345,0.000386819,-8.942e-08,-1.48806e-08,1.12384,0.000386596,-1.34062e-07,1.48245e-08,1.12423,0.000386372,-8.95885e-08,-4.44172e-08,1.12461,0.00038606,-2.2284e-07,4.36351e-08,1.125,0.000385745,-9.19348e-08,-1.09139e-08,1.12539,0.000385528,-1.24677e-07,2.05584e-11,1.12577,0.000385279,-1.24615e-07,1.08317e-08,1.12616,0.000385062,-9.21198e-08,-4.33473e-08,1.12654,0.000384748,-2.22162e-07,4.33481e-08,1.12693,0.000384434,-9.21174e-08,-1.08356e-08,1.12731,0.000384217,-1.24624e-07,-5.50907e-12,1.12769,0.000383968,-1.24641e-07,1.08577e-08,1.12808,0.000383751,-9.20679e-08,-4.34252e-08,1.12846,0.000383437,-2.22343e-07,4.36337e-08,1.12884,0.000383123,-9.14422e-08,-1.19005e-08,1.12923,0.000382904,-1.27144e-07,3.96813e-09,1.12961,0.000382662,-1.15239e-07,-3.97207e-09,1.12999,0.000382419,-1.27155e-07,1.19201e-08,1.13038,0.000382201,-9.1395e-08,-4.37085e-08,1.13076,0.000381887,-2.2252e-07,4.37046e-08,1.13114,0.000381573,-9.14068e-08,-1.19005e-08,1.13152,0.000381355,-1.27108e-07,3.89734e-09,1.1319,0.000381112,-1.15416e-07,-3.68887e-09,1.13228,0.00038087,-1.26483e-07,1.08582e-08,1.13266,0.00038065,-9.39083e-08,-3.97438e-08,1.13304,0.000380343,-2.1314e-07,2.89076e-08,1.13342,0.000380003,-1.26417e-07,4.33225e-08,1.1338,0.00037988,3.55072e-09,-8.29883e-08,1.13418,0.000379638,-2.45414e-07,5.0212e-08,1.13456,0.000379298,-9.47781e-08,1.34964e-09,1.13494,0.000379113,-9.07292e-08,-5.56105e-08,1.13532,0.000378764,-2.57561e-07,1.01883e-07,1.1357,0.000378555,4.80889e-08,-1.13504e-07,1.13608,0.000378311,-2.92423e-07,1.13713e-07,1.13646,0.000378067,4.87176e-08,-1.02931e-07,1.13683,0.000377856,-2.60076e-07,5.95923e-08,1.13721,0.000377514,-8.12988e-08,-1.62288e-08,1.13759,0.000377303,-1.29985e-07,5.32278e-09,1.13797,0.000377059,-1.14017e-07,-5.06237e-09,1.13834,0.000376816,-1.29204e-07,1.49267e-08,1.13872,0.000376602,-8.44237e-08,-5.46444e-08,1.1391,0.000376269,-2.48357e-07,8.44417e-08,1.13947,0.000376026,4.96815e-09,-4.47039e-08,1.13985,0.000375902,-1.29143e-07,-2.48355e-08,1.14023,0.000375569,-2.0365e-07,2.48368e-08,1.1406,0.000375236,-1.2914e-07,4.46977e-08,1.14098,0.000375112,4.95341e-09,-8.44184e-08,1.14135,0.000374869,-2.48302e-07,5.45572e-08,1.14173,0.000374536,-8.463e-08,-1.46013e-08,1.1421,0.000374323,-1.28434e-07,3.8478e-09,1.14247,0.000374077,-1.1689e-07,-7.89941e-10,1.14285,0.000373841,-1.1926e-07,-6.88042e-10,1.14322,0.0003736,-1.21324e-07,3.54213e-09,1.1436,0.000373368,-1.10698e-07,-1.34805e-08,1.14397,0.000373107,-1.51139e-07,5.03798e-08,1.14434,0.000372767,0.,0.}; + + template + __device__ __forceinline__ void RGB2LuvConvert_f(const T& src, D& dst) + { + const float _d = 1.f / (0.950456f + 15 + 1.088754f * 3); + const float _un = 13 * (4 * 0.950456f * _d); + const float _vn = 13 * (9 * _d); + + float B = blueIdx == 0 ? src.x : src.z; + float G = src.y; + float R = blueIdx == 0 ? src.z : src.x; + + if (srgb) + { + B = splineInterpolate(B * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); + G = splineInterpolate(G * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); + R = splineInterpolate(R * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); + } + + float X = R * 0.412453f + G * 0.357580f + B * 0.180423f; + float Y = R * 0.212671f + G * 0.715160f + B * 0.072169f; + float Z = R * 0.019334f + G * 0.119193f + B * 0.950227f; + + float L = splineInterpolate(Y * (LAB_CBRT_TAB_SIZE / 1.5f), c_LabCbrtTab, LAB_CBRT_TAB_SIZE); + L = 116.f * L - 16.f; + + const float d = (4 * 13) / ::fmaxf(X + 15 * Y + 3 * Z, numeric_limits::epsilon()); + float u = L * (X * d - _un); + float v = L * ((9 * 0.25f) * Y * d - _vn); + + dst.x = L; + dst.y = u; + dst.z = v; + } + + template + __device__ __forceinline__ void RGB2LuvConvert_b(const T& src, D& dst) + { + float3 srcf, dstf; + + srcf.x = src.x * (1.f / 255.f); + srcf.y = src.y * (1.f / 255.f); + srcf.z = src.z * (1.f / 255.f); + + RGB2LuvConvert_f(srcf, dstf); + + dst.x = saturate_cast(dstf.x * 2.55f); + dst.y = saturate_cast(dstf.y * 0.72033898305084743f + 96.525423728813564f); + dst.z = saturate_cast(dstf.z * 0.9732824427480916f + 136.259541984732824f); + } + + template struct RGB2Luv; + template + struct RGB2Luv + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + RGB2LuvConvert_b(src, dst); + + return dst; + } + __host__ __device__ __forceinline__ RGB2Luv() {} + __host__ __device__ __forceinline__ RGB2Luv(const RGB2Luv&) {} + }; + template + struct RGB2Luv + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + RGB2LuvConvert_f(src, dst); + + return dst; + } + __host__ __device__ __forceinline__ RGB2Luv() {} + __host__ __device__ __forceinline__ RGB2Luv(const RGB2Luv&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(name, scn, dcn, srgb, blueIdx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2Luv functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + + namespace color_detail + { + template + __device__ __forceinline__ void Luv2RGBConvert_f(const T& src, D& dst) + { + const float _d = 1.f / (0.950456f + 15 + 1.088754f * 3); + const float _un = 4 * 0.950456f * _d; + const float _vn = 9 * _d; + + float L = src.x; + float u = src.y; + float v = src.z; + + float Y = (L + 16.f) * (1.f / 116.f); + Y = Y * Y * Y; + + float d = (1.f / 13.f) / L; + u = u * d + _un; + v = v * d + _vn; + + float iv = 1.f / v; + float X = 2.25f * u * Y * iv; + float Z = (12 - 3 * u - 20 * v) * Y * 0.25f * iv; + + float B = 0.055648f * X - 0.204043f * Y + 1.057311f * Z; + float G = -0.969256f * X + 1.875991f * Y + 0.041556f * Z; + float R = 3.240479f * X - 1.537150f * Y - 0.498535f * Z; + + if (srgb) + { + B = splineInterpolate(B * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); + G = splineInterpolate(G * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); + R = splineInterpolate(R * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); + } + + dst.x = blueIdx == 0 ? B : R; + dst.y = G; + dst.z = blueIdx == 0 ? R : B; + setAlpha(dst, ColorChannel::max()); + } + + template + __device__ __forceinline__ void Luv2RGBConvert_b(const T& src, D& dst) + { + float3 srcf, dstf; + + srcf.x = src.x * (100.f / 255.f); + srcf.y = src.y * 1.388235294117647f - 134.f; + srcf.z = src.z * 1.027450980392157f - 140.f; + + Luv2RGBConvert_f(srcf, dstf); + + dst.x = saturate_cast(dstf.x * 255.f); + dst.y = saturate_cast(dstf.y * 255.f); + dst.z = saturate_cast(dstf.z * 255.f); + setAlpha(dst, ColorChannel::max()); + } + + template struct Luv2RGB; + template + struct Luv2RGB + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + Luv2RGBConvert_b(src, dst); + + return dst; + } + __host__ __device__ __forceinline__ Luv2RGB() {} + __host__ __device__ __forceinline__ Luv2RGB(const Luv2RGB&) {} + }; + template + struct Luv2RGB + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + Luv2RGBConvert_f(src, dst); + + return dst; + } + __host__ __device__ __forceinline__ Luv2RGB() {} + __host__ __device__ __forceinline__ Luv2RGB(const Luv2RGB&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(name, scn, dcn, srgb, blueIdx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::Luv2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + + #undef CV_DESCALE + +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif // OPENCV_CUDA_COLOR_DETAIL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/reduce.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/reduce.hpp index 05a672c3dc..507e6b334d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/reduce.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/reduce.hpp @@ -1,394 +1,394 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_REDUCE_DETAIL_HPP -#define OPENCV_CUDA_REDUCE_DETAIL_HPP - -#include -#include "../warp.hpp" -#include "../warp_shuffle.hpp" - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - namespace reduce_detail - { - template struct GetType; - template struct GetType - { - typedef T type; - }; - template struct GetType - { - typedef T type; - }; - template struct GetType - { - typedef T type; - }; - - template - struct For - { - template - static __device__ void loadToSmem(const PointerTuple& smem, const ValTuple& val, unsigned int tid) - { - thrust::get(smem)[tid] = thrust::get(val); - - For::loadToSmem(smem, val, tid); - } - template - static __device__ void loadFromSmem(const PointerTuple& smem, const ValTuple& val, unsigned int tid) - { - thrust::get(val) = thrust::get(smem)[tid]; - - For::loadFromSmem(smem, val, tid); - } - - template - static __device__ void merge(const PointerTuple& smem, const ValTuple& val, unsigned int tid, unsigned int delta, const OpTuple& op) - { - typename GetType::type>::type reg = thrust::get(smem)[tid + delta]; - thrust::get(smem)[tid] = thrust::get(val) = thrust::get(op)(thrust::get(val), reg); - - For::merge(smem, val, tid, delta, op); - } - template - static __device__ void mergeShfl(const ValTuple& val, unsigned int delta, unsigned int width, const OpTuple& op) - { - typename GetType::type>::type reg = shfl_down(thrust::get(val), delta, width); - thrust::get(val) = thrust::get(op)(thrust::get(val), reg); - - For::mergeShfl(val, delta, width, op); - } - }; - template - struct For - { - template - static __device__ void loadToSmem(const PointerTuple&, const ValTuple&, unsigned int) - { - } - template - static __device__ void loadFromSmem(const PointerTuple&, const ValTuple&, unsigned int) - { - } - - template - static __device__ void merge(const PointerTuple&, const ValTuple&, unsigned int, unsigned int, const OpTuple&) - { - } - template - static __device__ void mergeShfl(const ValTuple&, unsigned int, unsigned int, const OpTuple&) - { - } - }; - - template - __device__ __forceinline__ void loadToSmem(volatile T* smem, T& val, unsigned int tid) - { - smem[tid] = val; - } - template - __device__ __forceinline__ void loadFromSmem(volatile T* smem, T& val, unsigned int tid) - { - val = smem[tid]; - } - - template - __device__ __forceinline__ void merge(volatile T* smem, T& val, unsigned int tid, unsigned int delta, const Op& op) - { - T reg = smem[tid + delta]; - smem[tid] = val = op(val, reg); - } - - template - __device__ __forceinline__ void mergeShfl(T& val, unsigned int delta, unsigned int width, const Op& op) - { - T reg = shfl_down(val, delta, width); - val = op(val, reg); - } - -#if (CUDART_VERSION < 12040) // details: https://github.com/opencv/opencv_contrib/issues/3690 - template - __device__ __forceinline__ void loadToSmem(const thrust::tuple& smem, - const thrust::tuple& val, - unsigned int tid) - { - For<0, thrust::tuple_size >::value>::loadToSmem(smem, val, tid); - } - - template - __device__ __forceinline__ void loadFromSmem(const thrust::tuple& smem, - const thrust::tuple& val, - unsigned int tid) - { - For<0, thrust::tuple_size >::value>::loadFromSmem(smem, val, tid); - } - - template - __device__ __forceinline__ void merge(const thrust::tuple& smem, - const thrust::tuple& val, - unsigned int tid, - unsigned int delta, - const thrust::tuple& op) - { - For<0, thrust::tuple_size >::value>::merge(smem, val, tid, delta, op); - } - template - __device__ __forceinline__ void mergeShfl(const thrust::tuple& val, - unsigned int delta, - unsigned int width, - const thrust::tuple& op) - { - For<0, thrust::tuple_size >::value>::mergeShfl(val, delta, width, op); - } -#else - template - __device__ __forceinline__ void loadToSmem(const thrust::tuple& smem, const thrust::tuple& val, unsigned int tid) - { - For<0, thrust::tuple_size >::value>::loadToSmem(smem, val, tid); - } - - template - __device__ __forceinline__ void loadFromSmem(const thrust::tuple& smem, const thrust::tuple& val, unsigned int tid) - { - For<0, thrust::tuple_size >::value>::loadFromSmem(smem, val, tid); - } - - template - __device__ __forceinline__ void merge(const thrust::tuple& smem, const thrust::tuple& val, unsigned int tid, unsigned int delta, const thrust::tuple& op) - { - For<0, thrust::tuple_size >::value>::merge(smem, val, tid, delta, op); - } - - template - __device__ __forceinline__ void mergeShfl(const thrust::tuple& val, unsigned int delta, unsigned int width, const thrust::tuple& op) - { - For<0, thrust::tuple_size >::value>::mergeShfl(val, delta, width, op); - } -#endif - template struct Generic - { - template - static __device__ void reduce(Pointer smem, Reference val, unsigned int tid, Op op) - { - loadToSmem(smem, val, tid); - if (N >= 32) - __syncthreads(); - - if (N >= 2048) - { - if (tid < 1024) - merge(smem, val, tid, 1024, op); - - __syncthreads(); - } - if (N >= 1024) - { - if (tid < 512) - merge(smem, val, tid, 512, op); - - __syncthreads(); - } - if (N >= 512) - { - if (tid < 256) - merge(smem, val, tid, 256, op); - - __syncthreads(); - } - if (N >= 256) - { - if (tid < 128) - merge(smem, val, tid, 128, op); - - __syncthreads(); - } - if (N >= 128) - { - if (tid < 64) - merge(smem, val, tid, 64, op); - - __syncthreads(); - } - if (N >= 64) - { - if (tid < 32) - merge(smem, val, tid, 32, op); - } - - if (tid < 16) - { - merge(smem, val, tid, 16, op); - merge(smem, val, tid, 8, op); - merge(smem, val, tid, 4, op); - merge(smem, val, tid, 2, op); - merge(smem, val, tid, 1, op); - } - } - }; - - template - struct Unroll - { - static __device__ void loopShfl(Reference val, Op op, unsigned int N) - { - mergeShfl(val, I, N, op); - Unroll::loopShfl(val, op, N); - } - static __device__ void loop(Pointer smem, Reference val, unsigned int tid, Op op) - { - merge(smem, val, tid, I, op); - Unroll::loop(smem, val, tid, op); - } - }; - template - struct Unroll<0, Pointer, Reference, Op> - { - static __device__ void loopShfl(Reference, Op, unsigned int) - { - } - static __device__ void loop(Pointer, Reference, unsigned int, Op) - { - } - }; - - template struct WarpOptimized - { - template - static __device__ void reduce(Pointer smem, Reference val, unsigned int tid, Op op) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 - CV_UNUSED(smem); - CV_UNUSED(tid); - - Unroll::loopShfl(val, op, N); - #else - loadToSmem(smem, val, tid); - - if (tid < N / 2) - Unroll::loop(smem, val, tid, op); - #endif - } - }; - - template struct GenericOptimized32 - { - enum { M = N / 32 }; - - template - static __device__ void reduce(Pointer smem, Reference val, unsigned int tid, Op op) - { - const unsigned int laneId = Warp::laneId(); - - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 - Unroll<16, Pointer, Reference, Op>::loopShfl(val, op, warpSize); - - if (laneId == 0) - loadToSmem(smem, val, tid / 32); - #else - loadToSmem(smem, val, tid); - - if (laneId < 16) - Unroll<16, Pointer, Reference, Op>::loop(smem, val, tid, op); - - __syncthreads(); - - if (laneId == 0) - loadToSmem(smem, val, tid / 32); - #endif - - __syncthreads(); - - loadFromSmem(smem, val, tid); - - if (tid < 32) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 - Unroll::loopShfl(val, op, M); - #else - Unroll::loop(smem, val, tid, op); - #endif - } - } - }; - - template struct StaticIf; - template struct StaticIf - { - typedef T1 type; - }; - template struct StaticIf - { - typedef T2 type; - }; - - template struct IsPowerOf2 - { - enum { value = ((N != 0) && !(N & (N - 1))) }; - }; - - template struct Dispatcher - { - typedef typename StaticIf< - (N <= 32) && IsPowerOf2::value, - WarpOptimized, - typename StaticIf< - (N <= 1024) && IsPowerOf2::value, - GenericOptimized32, - Generic - >::type - >::type reductor; - }; - } -}}} - -//! @endcond - -#endif // OPENCV_CUDA_REDUCE_DETAIL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_REDUCE_DETAIL_HPP +#define OPENCV_CUDA_REDUCE_DETAIL_HPP + +#include +#include "../warp.hpp" +#include "../warp_shuffle.hpp" + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + namespace reduce_detail + { + template struct GetType; + template struct GetType + { + typedef T type; + }; + template struct GetType + { + typedef T type; + }; + template struct GetType + { + typedef T type; + }; + + template + struct For + { + template + static __device__ void loadToSmem(const PointerTuple& smem, const ValTuple& val, unsigned int tid) + { + thrust::get(smem)[tid] = thrust::get(val); + + For::loadToSmem(smem, val, tid); + } + template + static __device__ void loadFromSmem(const PointerTuple& smem, const ValTuple& val, unsigned int tid) + { + thrust::get(val) = thrust::get(smem)[tid]; + + For::loadFromSmem(smem, val, tid); + } + + template + static __device__ void merge(const PointerTuple& smem, const ValTuple& val, unsigned int tid, unsigned int delta, const OpTuple& op) + { + typename GetType::type>::type reg = thrust::get(smem)[tid + delta]; + thrust::get(smem)[tid] = thrust::get(val) = thrust::get(op)(thrust::get(val), reg); + + For::merge(smem, val, tid, delta, op); + } + template + static __device__ void mergeShfl(const ValTuple& val, unsigned int delta, unsigned int width, const OpTuple& op) + { + typename GetType::type>::type reg = shfl_down(thrust::get(val), delta, width); + thrust::get(val) = thrust::get(op)(thrust::get(val), reg); + + For::mergeShfl(val, delta, width, op); + } + }; + template + struct For + { + template + static __device__ void loadToSmem(const PointerTuple&, const ValTuple&, unsigned int) + { + } + template + static __device__ void loadFromSmem(const PointerTuple&, const ValTuple&, unsigned int) + { + } + + template + static __device__ void merge(const PointerTuple&, const ValTuple&, unsigned int, unsigned int, const OpTuple&) + { + } + template + static __device__ void mergeShfl(const ValTuple&, unsigned int, unsigned int, const OpTuple&) + { + } + }; + + template + __device__ __forceinline__ void loadToSmem(volatile T* smem, T& val, unsigned int tid) + { + smem[tid] = val; + } + template + __device__ __forceinline__ void loadFromSmem(volatile T* smem, T& val, unsigned int tid) + { + val = smem[tid]; + } + + template + __device__ __forceinline__ void merge(volatile T* smem, T& val, unsigned int tid, unsigned int delta, const Op& op) + { + T reg = smem[tid + delta]; + smem[tid] = val = op(val, reg); + } + + template + __device__ __forceinline__ void mergeShfl(T& val, unsigned int delta, unsigned int width, const Op& op) + { + T reg = shfl_down(val, delta, width); + val = op(val, reg); + } + +#if (CUDART_VERSION < 12040) // details: https://github.com/opencv/opencv_contrib/issues/3690 + template + __device__ __forceinline__ void loadToSmem(const thrust::tuple& smem, + const thrust::tuple& val, + unsigned int tid) + { + For<0, thrust::tuple_size >::value>::loadToSmem(smem, val, tid); + } + + template + __device__ __forceinline__ void loadFromSmem(const thrust::tuple& smem, + const thrust::tuple& val, + unsigned int tid) + { + For<0, thrust::tuple_size >::value>::loadFromSmem(smem, val, tid); + } + + template + __device__ __forceinline__ void merge(const thrust::tuple& smem, + const thrust::tuple& val, + unsigned int tid, + unsigned int delta, + const thrust::tuple& op) + { + For<0, thrust::tuple_size >::value>::merge(smem, val, tid, delta, op); + } + template + __device__ __forceinline__ void mergeShfl(const thrust::tuple& val, + unsigned int delta, + unsigned int width, + const thrust::tuple& op) + { + For<0, thrust::tuple_size >::value>::mergeShfl(val, delta, width, op); + } +#else + template + __device__ __forceinline__ void loadToSmem(const thrust::tuple& smem, const thrust::tuple& val, unsigned int tid) + { + For<0, thrust::tuple_size >::value>::loadToSmem(smem, val, tid); + } + + template + __device__ __forceinline__ void loadFromSmem(const thrust::tuple& smem, const thrust::tuple& val, unsigned int tid) + { + For<0, thrust::tuple_size >::value>::loadFromSmem(smem, val, tid); + } + + template + __device__ __forceinline__ void merge(const thrust::tuple& smem, const thrust::tuple& val, unsigned int tid, unsigned int delta, const thrust::tuple& op) + { + For<0, thrust::tuple_size >::value>::merge(smem, val, tid, delta, op); + } + + template + __device__ __forceinline__ void mergeShfl(const thrust::tuple& val, unsigned int delta, unsigned int width, const thrust::tuple& op) + { + For<0, thrust::tuple_size >::value>::mergeShfl(val, delta, width, op); + } +#endif + template struct Generic + { + template + static __device__ void reduce(Pointer smem, Reference val, unsigned int tid, Op op) + { + loadToSmem(smem, val, tid); + if (N >= 32) + __syncthreads(); + + if (N >= 2048) + { + if (tid < 1024) + merge(smem, val, tid, 1024, op); + + __syncthreads(); + } + if (N >= 1024) + { + if (tid < 512) + merge(smem, val, tid, 512, op); + + __syncthreads(); + } + if (N >= 512) + { + if (tid < 256) + merge(smem, val, tid, 256, op); + + __syncthreads(); + } + if (N >= 256) + { + if (tid < 128) + merge(smem, val, tid, 128, op); + + __syncthreads(); + } + if (N >= 128) + { + if (tid < 64) + merge(smem, val, tid, 64, op); + + __syncthreads(); + } + if (N >= 64) + { + if (tid < 32) + merge(smem, val, tid, 32, op); + } + + if (tid < 16) + { + merge(smem, val, tid, 16, op); + merge(smem, val, tid, 8, op); + merge(smem, val, tid, 4, op); + merge(smem, val, tid, 2, op); + merge(smem, val, tid, 1, op); + } + } + }; + + template + struct Unroll + { + static __device__ void loopShfl(Reference val, Op op, unsigned int N) + { + mergeShfl(val, I, N, op); + Unroll::loopShfl(val, op, N); + } + static __device__ void loop(Pointer smem, Reference val, unsigned int tid, Op op) + { + merge(smem, val, tid, I, op); + Unroll::loop(smem, val, tid, op); + } + }; + template + struct Unroll<0, Pointer, Reference, Op> + { + static __device__ void loopShfl(Reference, Op, unsigned int) + { + } + static __device__ void loop(Pointer, Reference, unsigned int, Op) + { + } + }; + + template struct WarpOptimized + { + template + static __device__ void reduce(Pointer smem, Reference val, unsigned int tid, Op op) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 + CV_UNUSED(smem); + CV_UNUSED(tid); + + Unroll::loopShfl(val, op, N); + #else + loadToSmem(smem, val, tid); + + if (tid < N / 2) + Unroll::loop(smem, val, tid, op); + #endif + } + }; + + template struct GenericOptimized32 + { + enum { M = N / 32 }; + + template + static __device__ void reduce(Pointer smem, Reference val, unsigned int tid, Op op) + { + const unsigned int laneId = Warp::laneId(); + + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 + Unroll<16, Pointer, Reference, Op>::loopShfl(val, op, warpSize); + + if (laneId == 0) + loadToSmem(smem, val, tid / 32); + #else + loadToSmem(smem, val, tid); + + if (laneId < 16) + Unroll<16, Pointer, Reference, Op>::loop(smem, val, tid, op); + + __syncthreads(); + + if (laneId == 0) + loadToSmem(smem, val, tid / 32); + #endif + + __syncthreads(); + + loadFromSmem(smem, val, tid); + + if (tid < 32) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 + Unroll::loopShfl(val, op, M); + #else + Unroll::loop(smem, val, tid, op); + #endif + } + } + }; + + template struct StaticIf; + template struct StaticIf + { + typedef T1 type; + }; + template struct StaticIf + { + typedef T2 type; + }; + + template struct IsPowerOf2 + { + enum { value = ((N != 0) && !(N & (N - 1))) }; + }; + + template struct Dispatcher + { + typedef typename StaticIf< + (N <= 32) && IsPowerOf2::value, + WarpOptimized, + typename StaticIf< + (N <= 1024) && IsPowerOf2::value, + GenericOptimized32, + Generic + >::type + >::type reductor; + }; + } +}}} + +//! @endcond + +#endif // OPENCV_CUDA_REDUCE_DETAIL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/reduce_key_val.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/reduce_key_val.hpp index 4a248c8365..535f9d8ed0 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/reduce_key_val.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/reduce_key_val.hpp @@ -1,567 +1,567 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_PRED_VAL_REDUCE_DETAIL_HPP -#define OPENCV_CUDA_PRED_VAL_REDUCE_DETAIL_HPP - -#include -#include "../warp.hpp" -#include "../warp_shuffle.hpp" - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - namespace reduce_key_val_detail - { - template struct GetType; - template struct GetType - { - typedef T type; - }; - template struct GetType - { - typedef T type; - }; - template struct GetType - { - typedef T type; - }; - - template - struct For - { - template - static __device__ void loadToSmem(const PointerTuple& smem, const ReferenceTuple& data, unsigned int tid) - { - thrust::get(smem)[tid] = thrust::get(data); - - For::loadToSmem(smem, data, tid); - } - template - static __device__ void loadFromSmem(const PointerTuple& smem, const ReferenceTuple& data, unsigned int tid) - { - thrust::get(data) = thrust::get(smem)[tid]; - - For::loadFromSmem(smem, data, tid); - } - - template - static __device__ void copyShfl(const ReferenceTuple& val, unsigned int delta, int width) - { - thrust::get(val) = shfl_down(thrust::get(val), delta, width); - - For::copyShfl(val, delta, width); - } - template - static __device__ void copy(const PointerTuple& svals, const ReferenceTuple& val, unsigned int tid, unsigned int delta) - { - thrust::get(svals)[tid] = thrust::get(val) = thrust::get(svals)[tid + delta]; - - For::copy(svals, val, tid, delta); - } - - template - static __device__ void mergeShfl(const KeyReferenceTuple& key, const ValReferenceTuple& val, const CmpTuple& cmp, unsigned int delta, int width) - { - typename GetType::type>::type reg = shfl_down(thrust::get(key), delta, width); - - if (thrust::get(cmp)(reg, thrust::get(key))) - { - thrust::get(key) = reg; - thrust::get(val) = shfl_down(thrust::get(val), delta, width); - } - - For::mergeShfl(key, val, cmp, delta, width); - } - template - static __device__ void merge(const KeyPointerTuple& skeys, const KeyReferenceTuple& key, - const ValPointerTuple& svals, const ValReferenceTuple& val, - const CmpTuple& cmp, - unsigned int tid, unsigned int delta) - { - typename GetType::type>::type reg = thrust::get(skeys)[tid + delta]; - - if (thrust::get(cmp)(reg, thrust::get(key))) - { - thrust::get(skeys)[tid] = thrust::get(key) = reg; - thrust::get(svals)[tid] = thrust::get(val) = thrust::get(svals)[tid + delta]; - } - - For::merge(skeys, key, svals, val, cmp, tid, delta); - } - }; - template - struct For - { - template - static __device__ void loadToSmem(const PointerTuple&, const ReferenceTuple&, unsigned int) - { - } - template - static __device__ void loadFromSmem(const PointerTuple&, const ReferenceTuple&, unsigned int) - { - } - - template - static __device__ void copyShfl(const ReferenceTuple&, unsigned int, int) - { - } - template - static __device__ void copy(const PointerTuple&, const ReferenceTuple&, unsigned int, unsigned int) - { - } - - template - static __device__ void mergeShfl(const KeyReferenceTuple&, const ValReferenceTuple&, const CmpTuple&, unsigned int, int) - { - } - template - static __device__ void merge(const KeyPointerTuple&, const KeyReferenceTuple&, - const ValPointerTuple&, const ValReferenceTuple&, - const CmpTuple&, - unsigned int, unsigned int) - { - } - }; - - ////////////////////////////////////////////////////// - // loadToSmem - - template - __device__ __forceinline__ void loadToSmem(volatile T* smem, T& data, unsigned int tid) - { - smem[tid] = data; - } - template - __device__ __forceinline__ void loadFromSmem(volatile T* smem, T& data, unsigned int tid) - { - data = smem[tid]; - } - -#if (CUDART_VERSION < 12040) - template - __device__ __forceinline__ void loadToSmem(const thrust::tuple& smem, - const thrust::tuple& data, - unsigned int tid) - { - For<0, thrust::tuple_size >::value>::loadToSmem(smem, data, tid); - } - template - __device__ __forceinline__ void loadFromSmem(const thrust::tuple& smem, - const thrust::tuple& data, - unsigned int tid) - { - For<0, thrust::tuple_size >::value>::loadFromSmem(smem, data, tid); - } -#else - template - __device__ __forceinline__ void loadToSmem(const thrust::tuple& smem, const thrust::tuple& data, unsigned int tid) - { - For<0, thrust::tuple_size >::value>::loadToSmem(smem, data, tid); - } - template - __device__ __forceinline__ void loadFromSmem(const thrust::tuple& smem, const thrust::tuple& data, unsigned int tid) - { - For<0, thrust::tuple_size >::value>::loadFromSmem(smem, data, tid); - } -#endif - - template - __device__ __forceinline__ void copyValsShfl(V& val, unsigned int delta, int width) - { - val = shfl_down(val, delta, width); - } - template - __device__ __forceinline__ void copyVals(volatile V* svals, V& val, unsigned int tid, unsigned int delta) - { - svals[tid] = val = svals[tid + delta]; - } - - template - __device__ __forceinline__ void mergeShfl(K& key, V& val, const Cmp& cmp, unsigned int delta, int width) - { - K reg = shfl_down(key, delta, width); - - if (cmp(reg, key)) - { - key = reg; - copyValsShfl(val, delta, width); - } - } - template - __device__ __forceinline__ void merge(volatile K* skeys, K& key, volatile V* svals, V& val, const Cmp& cmp, unsigned int tid, unsigned int delta) - { - K reg = skeys[tid + delta]; - - if (cmp(reg, key)) - { - skeys[tid] = key = reg; - copyVals(svals, val, tid, delta); - } - } - -#if (CUDART_VERSION < 12040) // details: https://github.com/opencv/opencv_contrib/issues/3690 - template - __device__ __forceinline__ void copyValsShfl(const thrust::tuple& val, - unsigned int delta, - int width) - { - For<0, thrust::tuple_size >::value>::copyShfl(val, delta, width); - } - template - __device__ __forceinline__ void copyVals(const thrust::tuple& svals, - const thrust::tuple& val, - unsigned int tid, unsigned int delta) - { - For<0, thrust::tuple_size >::value>::copy(svals, val, tid, delta); - } - - template - __device__ __forceinline__ void mergeShfl(K& key, - const thrust::tuple& val, - const Cmp& cmp, - unsigned int delta, int width) - { - K reg = shfl_down(key, delta, width); - - if (cmp(reg, key)) - { - key = reg; - copyValsShfl(val, delta, width); - } - } - template - __device__ __forceinline__ void merge(volatile K* skeys, K& key, - const thrust::tuple& svals, - const thrust::tuple& val, - const Cmp& cmp, unsigned int tid, unsigned int delta) - { - K reg = skeys[tid + delta]; - - if (cmp(reg, key)) - { - skeys[tid] = key = reg; - copyVals(svals, val, tid, delta); - } - } - template - __device__ __forceinline__ void mergeShfl(const thrust::tuple& key, - const thrust::tuple& val, - const thrust::tuple& cmp, - unsigned int delta, int width) - { - For<0, thrust::tuple_size >::value>::mergeShfl(key, val, cmp, delta, width); - } - template - __device__ __forceinline__ void merge(const thrust::tuple& skeys, - const thrust::tuple& key, - const thrust::tuple& svals, - const thrust::tuple& val, - const thrust::tuple& cmp, - unsigned int tid, unsigned int delta) - { - For<0, thrust::tuple_size >::value>::merge(skeys, key, svals, val, cmp, tid, delta); - } -#else - template - __device__ __forceinline__ void copyValsShfl(const thrust::tuple& val, unsigned int delta, int width) - { - For<0, thrust::tuple_size >::value>::copyShfl(val, delta, width); - } - template - __device__ __forceinline__ void copyVals(const thrust::tuple& svals, const thrust::tuple& val, unsigned int tid, unsigned int delta) - { - For<0, thrust::tuple_size >::value>::copy(svals, val, tid, delta); - } - - template - __device__ __forceinline__ void mergeShfl(K& key, const thrust::tuple& val, const Cmp& cmp, unsigned int delta, int width) - { - K reg = shfl_down(key, delta, width); - - if (cmp(reg, key)) - { - key = reg; - copyValsShfl(val, delta, width); - } - } - template - __device__ __forceinline__ void merge(volatile K* skeys, K& key, const thrust::tuple& svals, - const thrust::tuple& val, const Cmp& cmp, unsigned int tid, unsigned int delta) - { - K reg = skeys[tid + delta]; - - if (cmp(reg, key)) - { - skeys[tid] = key = reg; - copyVals(svals, val, tid, delta); - } - } - template - __device__ __forceinline__ void mergeShfl(const thrust::tuple& key, - const thrust::tuple& val, - const thrust::tuple& cmp, - unsigned int delta, int width) - { - For<0, thrust::tuple_size >::value>::mergeShfl(key, val, cmp, delta, width); - } - template - __device__ __forceinline__ void merge(const thrust::tuple& skeys, - const thrust::tuple& key, - const thrust::tuple& svals, - const thrust::tuple& val, - const thrust::tuple& cmp, - unsigned int tid, unsigned int delta) - { - For<0, thrust::tuple_size >::value>::merge(skeys, key, svals, val, cmp, tid, delta); - } - -#endif - ////////////////////////////////////////////////////// - // Generic - - template struct Generic - { - template - static __device__ void reduce(KP skeys, KR key, VP svals, VR val, unsigned int tid, Cmp cmp) - { - loadToSmem(skeys, key, tid); - loadValsToSmem(svals, val, tid); - if (N >= 32) - __syncthreads(); - - if (N >= 2048) - { - if (tid < 1024) - merge(skeys, key, svals, val, cmp, tid, 1024); - - __syncthreads(); - } - if (N >= 1024) - { - if (tid < 512) - merge(skeys, key, svals, val, cmp, tid, 512); - - __syncthreads(); - } - if (N >= 512) - { - if (tid < 256) - merge(skeys, key, svals, val, cmp, tid, 256); - - __syncthreads(); - } - if (N >= 256) - { - if (tid < 128) - merge(skeys, key, svals, val, cmp, tid, 128); - - __syncthreads(); - } - if (N >= 128) - { - if (tid < 64) - merge(skeys, key, svals, val, cmp, tid, 64); - - __syncthreads(); - } - if (N >= 64) - { - if (tid < 32) - merge(skeys, key, svals, val, cmp, tid, 32); - } - - if (tid < 16) - { - merge(skeys, key, svals, val, cmp, tid, 16); - merge(skeys, key, svals, val, cmp, tid, 8); - merge(skeys, key, svals, val, cmp, tid, 4); - merge(skeys, key, svals, val, cmp, tid, 2); - merge(skeys, key, svals, val, cmp, tid, 1); - } - } - }; - - template - struct Unroll - { - static __device__ void loopShfl(KR key, VR val, Cmp cmp, unsigned int N) - { - mergeShfl(key, val, cmp, I, N); - Unroll::loopShfl(key, val, cmp, N); - } - static __device__ void loop(KP skeys, KR key, VP svals, VR val, unsigned int tid, Cmp cmp) - { - merge(skeys, key, svals, val, cmp, tid, I); - Unroll::loop(skeys, key, svals, val, tid, cmp); - } - }; - template - struct Unroll<0, KP, KR, VP, VR, Cmp> - { - static __device__ void loopShfl(KR, VR, Cmp, unsigned int) - { - } - static __device__ void loop(KP, KR, VP, VR, unsigned int, Cmp) - { - } - }; - - template struct WarpOptimized - { - template - static __device__ void reduce(KP skeys, KR key, VP svals, VR val, unsigned int tid, Cmp cmp) - { - #if 0 // __CUDA_ARCH__ >= 300 - CV_UNUSED(skeys); - CV_UNUSED(svals); - CV_UNUSED(tid); - - Unroll::loopShfl(key, val, cmp, N); - #else - loadToSmem(skeys, key, tid); - loadToSmem(svals, val, tid); - - if (tid < N / 2) - Unroll::loop(skeys, key, svals, val, tid, cmp); - #endif - } - }; - - template struct GenericOptimized32 - { - enum { M = N / 32 }; - - template - static __device__ void reduce(KP skeys, KR key, VP svals, VR val, unsigned int tid, Cmp cmp) - { - const unsigned int laneId = Warp::laneId(); - - #if 0 // __CUDA_ARCH__ >= 300 - Unroll<16, KP, KR, VP, VR, Cmp>::loopShfl(key, val, cmp, warpSize); - - if (laneId == 0) - { - loadToSmem(skeys, key, tid / 32); - loadToSmem(svals, val, tid / 32); - } - #else - loadToSmem(skeys, key, tid); - loadToSmem(svals, val, tid); - - if (laneId < 16) - Unroll<16, KP, KR, VP, VR, Cmp>::loop(skeys, key, svals, val, tid, cmp); - - __syncthreads(); - - if (laneId == 0) - { - loadToSmem(skeys, key, tid / 32); - loadToSmem(svals, val, tid / 32); - } - #endif - - __syncthreads(); - - loadFromSmem(skeys, key, tid); - - if (tid < 32) - { - #if 0 // __CUDA_ARCH__ >= 300 - loadFromSmem(svals, val, tid); - - Unroll::loopShfl(key, val, cmp, M); - #else - Unroll::loop(skeys, key, svals, val, tid, cmp); - #endif - } - } - }; - - template struct StaticIf; - template struct StaticIf - { - typedef T1 type; - }; - template struct StaticIf - { - typedef T2 type; - }; - - template struct IsPowerOf2 - { - enum { value = ((N != 0) && !(N & (N - 1))) }; - }; - - template struct Dispatcher - { - typedef typename StaticIf< - (N <= 32) && IsPowerOf2::value, - WarpOptimized, - typename StaticIf< - (N <= 1024) && IsPowerOf2::value, - GenericOptimized32, - Generic - >::type - >::type reductor; - }; - } -}}} - -//! @endcond - -#endif // OPENCV_CUDA_PRED_VAL_REDUCE_DETAIL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_PRED_VAL_REDUCE_DETAIL_HPP +#define OPENCV_CUDA_PRED_VAL_REDUCE_DETAIL_HPP + +#include +#include "../warp.hpp" +#include "../warp_shuffle.hpp" + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + namespace reduce_key_val_detail + { + template struct GetType; + template struct GetType + { + typedef T type; + }; + template struct GetType + { + typedef T type; + }; + template struct GetType + { + typedef T type; + }; + + template + struct For + { + template + static __device__ void loadToSmem(const PointerTuple& smem, const ReferenceTuple& data, unsigned int tid) + { + thrust::get(smem)[tid] = thrust::get(data); + + For::loadToSmem(smem, data, tid); + } + template + static __device__ void loadFromSmem(const PointerTuple& smem, const ReferenceTuple& data, unsigned int tid) + { + thrust::get(data) = thrust::get(smem)[tid]; + + For::loadFromSmem(smem, data, tid); + } + + template + static __device__ void copyShfl(const ReferenceTuple& val, unsigned int delta, int width) + { + thrust::get(val) = shfl_down(thrust::get(val), delta, width); + + For::copyShfl(val, delta, width); + } + template + static __device__ void copy(const PointerTuple& svals, const ReferenceTuple& val, unsigned int tid, unsigned int delta) + { + thrust::get(svals)[tid] = thrust::get(val) = thrust::get(svals)[tid + delta]; + + For::copy(svals, val, tid, delta); + } + + template + static __device__ void mergeShfl(const KeyReferenceTuple& key, const ValReferenceTuple& val, const CmpTuple& cmp, unsigned int delta, int width) + { + typename GetType::type>::type reg = shfl_down(thrust::get(key), delta, width); + + if (thrust::get(cmp)(reg, thrust::get(key))) + { + thrust::get(key) = reg; + thrust::get(val) = shfl_down(thrust::get(val), delta, width); + } + + For::mergeShfl(key, val, cmp, delta, width); + } + template + static __device__ void merge(const KeyPointerTuple& skeys, const KeyReferenceTuple& key, + const ValPointerTuple& svals, const ValReferenceTuple& val, + const CmpTuple& cmp, + unsigned int tid, unsigned int delta) + { + typename GetType::type>::type reg = thrust::get(skeys)[tid + delta]; + + if (thrust::get(cmp)(reg, thrust::get(key))) + { + thrust::get(skeys)[tid] = thrust::get(key) = reg; + thrust::get(svals)[tid] = thrust::get(val) = thrust::get(svals)[tid + delta]; + } + + For::merge(skeys, key, svals, val, cmp, tid, delta); + } + }; + template + struct For + { + template + static __device__ void loadToSmem(const PointerTuple&, const ReferenceTuple&, unsigned int) + { + } + template + static __device__ void loadFromSmem(const PointerTuple&, const ReferenceTuple&, unsigned int) + { + } + + template + static __device__ void copyShfl(const ReferenceTuple&, unsigned int, int) + { + } + template + static __device__ void copy(const PointerTuple&, const ReferenceTuple&, unsigned int, unsigned int) + { + } + + template + static __device__ void mergeShfl(const KeyReferenceTuple&, const ValReferenceTuple&, const CmpTuple&, unsigned int, int) + { + } + template + static __device__ void merge(const KeyPointerTuple&, const KeyReferenceTuple&, + const ValPointerTuple&, const ValReferenceTuple&, + const CmpTuple&, + unsigned int, unsigned int) + { + } + }; + + ////////////////////////////////////////////////////// + // loadToSmem + + template + __device__ __forceinline__ void loadToSmem(volatile T* smem, T& data, unsigned int tid) + { + smem[tid] = data; + } + template + __device__ __forceinline__ void loadFromSmem(volatile T* smem, T& data, unsigned int tid) + { + data = smem[tid]; + } + +#if (CUDART_VERSION < 12040) + template + __device__ __forceinline__ void loadToSmem(const thrust::tuple& smem, + const thrust::tuple& data, + unsigned int tid) + { + For<0, thrust::tuple_size >::value>::loadToSmem(smem, data, tid); + } + template + __device__ __forceinline__ void loadFromSmem(const thrust::tuple& smem, + const thrust::tuple& data, + unsigned int tid) + { + For<0, thrust::tuple_size >::value>::loadFromSmem(smem, data, tid); + } +#else + template + __device__ __forceinline__ void loadToSmem(const thrust::tuple& smem, const thrust::tuple& data, unsigned int tid) + { + For<0, thrust::tuple_size >::value>::loadToSmem(smem, data, tid); + } + template + __device__ __forceinline__ void loadFromSmem(const thrust::tuple& smem, const thrust::tuple& data, unsigned int tid) + { + For<0, thrust::tuple_size >::value>::loadFromSmem(smem, data, tid); + } +#endif + + template + __device__ __forceinline__ void copyValsShfl(V& val, unsigned int delta, int width) + { + val = shfl_down(val, delta, width); + } + template + __device__ __forceinline__ void copyVals(volatile V* svals, V& val, unsigned int tid, unsigned int delta) + { + svals[tid] = val = svals[tid + delta]; + } + + template + __device__ __forceinline__ void mergeShfl(K& key, V& val, const Cmp& cmp, unsigned int delta, int width) + { + K reg = shfl_down(key, delta, width); + + if (cmp(reg, key)) + { + key = reg; + copyValsShfl(val, delta, width); + } + } + template + __device__ __forceinline__ void merge(volatile K* skeys, K& key, volatile V* svals, V& val, const Cmp& cmp, unsigned int tid, unsigned int delta) + { + K reg = skeys[tid + delta]; + + if (cmp(reg, key)) + { + skeys[tid] = key = reg; + copyVals(svals, val, tid, delta); + } + } + +#if (CUDART_VERSION < 12040) // details: https://github.com/opencv/opencv_contrib/issues/3690 + template + __device__ __forceinline__ void copyValsShfl(const thrust::tuple& val, + unsigned int delta, + int width) + { + For<0, thrust::tuple_size >::value>::copyShfl(val, delta, width); + } + template + __device__ __forceinline__ void copyVals(const thrust::tuple& svals, + const thrust::tuple& val, + unsigned int tid, unsigned int delta) + { + For<0, thrust::tuple_size >::value>::copy(svals, val, tid, delta); + } + + template + __device__ __forceinline__ void mergeShfl(K& key, + const thrust::tuple& val, + const Cmp& cmp, + unsigned int delta, int width) + { + K reg = shfl_down(key, delta, width); + + if (cmp(reg, key)) + { + key = reg; + copyValsShfl(val, delta, width); + } + } + template + __device__ __forceinline__ void merge(volatile K* skeys, K& key, + const thrust::tuple& svals, + const thrust::tuple& val, + const Cmp& cmp, unsigned int tid, unsigned int delta) + { + K reg = skeys[tid + delta]; + + if (cmp(reg, key)) + { + skeys[tid] = key = reg; + copyVals(svals, val, tid, delta); + } + } + template + __device__ __forceinline__ void mergeShfl(const thrust::tuple& key, + const thrust::tuple& val, + const thrust::tuple& cmp, + unsigned int delta, int width) + { + For<0, thrust::tuple_size >::value>::mergeShfl(key, val, cmp, delta, width); + } + template + __device__ __forceinline__ void merge(const thrust::tuple& skeys, + const thrust::tuple& key, + const thrust::tuple& svals, + const thrust::tuple& val, + const thrust::tuple& cmp, + unsigned int tid, unsigned int delta) + { + For<0, thrust::tuple_size >::value>::merge(skeys, key, svals, val, cmp, tid, delta); + } +#else + template + __device__ __forceinline__ void copyValsShfl(const thrust::tuple& val, unsigned int delta, int width) + { + For<0, thrust::tuple_size >::value>::copyShfl(val, delta, width); + } + template + __device__ __forceinline__ void copyVals(const thrust::tuple& svals, const thrust::tuple& val, unsigned int tid, unsigned int delta) + { + For<0, thrust::tuple_size >::value>::copy(svals, val, tid, delta); + } + + template + __device__ __forceinline__ void mergeShfl(K& key, const thrust::tuple& val, const Cmp& cmp, unsigned int delta, int width) + { + K reg = shfl_down(key, delta, width); + + if (cmp(reg, key)) + { + key = reg; + copyValsShfl(val, delta, width); + } + } + template + __device__ __forceinline__ void merge(volatile K* skeys, K& key, const thrust::tuple& svals, + const thrust::tuple& val, const Cmp& cmp, unsigned int tid, unsigned int delta) + { + K reg = skeys[tid + delta]; + + if (cmp(reg, key)) + { + skeys[tid] = key = reg; + copyVals(svals, val, tid, delta); + } + } + template + __device__ __forceinline__ void mergeShfl(const thrust::tuple& key, + const thrust::tuple& val, + const thrust::tuple& cmp, + unsigned int delta, int width) + { + For<0, thrust::tuple_size >::value>::mergeShfl(key, val, cmp, delta, width); + } + template + __device__ __forceinline__ void merge(const thrust::tuple& skeys, + const thrust::tuple& key, + const thrust::tuple& svals, + const thrust::tuple& val, + const thrust::tuple& cmp, + unsigned int tid, unsigned int delta) + { + For<0, thrust::tuple_size >::value>::merge(skeys, key, svals, val, cmp, tid, delta); + } + +#endif + ////////////////////////////////////////////////////// + // Generic + + template struct Generic + { + template + static __device__ void reduce(KP skeys, KR key, VP svals, VR val, unsigned int tid, Cmp cmp) + { + loadToSmem(skeys, key, tid); + loadValsToSmem(svals, val, tid); + if (N >= 32) + __syncthreads(); + + if (N >= 2048) + { + if (tid < 1024) + merge(skeys, key, svals, val, cmp, tid, 1024); + + __syncthreads(); + } + if (N >= 1024) + { + if (tid < 512) + merge(skeys, key, svals, val, cmp, tid, 512); + + __syncthreads(); + } + if (N >= 512) + { + if (tid < 256) + merge(skeys, key, svals, val, cmp, tid, 256); + + __syncthreads(); + } + if (N >= 256) + { + if (tid < 128) + merge(skeys, key, svals, val, cmp, tid, 128); + + __syncthreads(); + } + if (N >= 128) + { + if (tid < 64) + merge(skeys, key, svals, val, cmp, tid, 64); + + __syncthreads(); + } + if (N >= 64) + { + if (tid < 32) + merge(skeys, key, svals, val, cmp, tid, 32); + } + + if (tid < 16) + { + merge(skeys, key, svals, val, cmp, tid, 16); + merge(skeys, key, svals, val, cmp, tid, 8); + merge(skeys, key, svals, val, cmp, tid, 4); + merge(skeys, key, svals, val, cmp, tid, 2); + merge(skeys, key, svals, val, cmp, tid, 1); + } + } + }; + + template + struct Unroll + { + static __device__ void loopShfl(KR key, VR val, Cmp cmp, unsigned int N) + { + mergeShfl(key, val, cmp, I, N); + Unroll::loopShfl(key, val, cmp, N); + } + static __device__ void loop(KP skeys, KR key, VP svals, VR val, unsigned int tid, Cmp cmp) + { + merge(skeys, key, svals, val, cmp, tid, I); + Unroll::loop(skeys, key, svals, val, tid, cmp); + } + }; + template + struct Unroll<0, KP, KR, VP, VR, Cmp> + { + static __device__ void loopShfl(KR, VR, Cmp, unsigned int) + { + } + static __device__ void loop(KP, KR, VP, VR, unsigned int, Cmp) + { + } + }; + + template struct WarpOptimized + { + template + static __device__ void reduce(KP skeys, KR key, VP svals, VR val, unsigned int tid, Cmp cmp) + { + #if 0 // __CUDA_ARCH__ >= 300 + CV_UNUSED(skeys); + CV_UNUSED(svals); + CV_UNUSED(tid); + + Unroll::loopShfl(key, val, cmp, N); + #else + loadToSmem(skeys, key, tid); + loadToSmem(svals, val, tid); + + if (tid < N / 2) + Unroll::loop(skeys, key, svals, val, tid, cmp); + #endif + } + }; + + template struct GenericOptimized32 + { + enum { M = N / 32 }; + + template + static __device__ void reduce(KP skeys, KR key, VP svals, VR val, unsigned int tid, Cmp cmp) + { + const unsigned int laneId = Warp::laneId(); + + #if 0 // __CUDA_ARCH__ >= 300 + Unroll<16, KP, KR, VP, VR, Cmp>::loopShfl(key, val, cmp, warpSize); + + if (laneId == 0) + { + loadToSmem(skeys, key, tid / 32); + loadToSmem(svals, val, tid / 32); + } + #else + loadToSmem(skeys, key, tid); + loadToSmem(svals, val, tid); + + if (laneId < 16) + Unroll<16, KP, KR, VP, VR, Cmp>::loop(skeys, key, svals, val, tid, cmp); + + __syncthreads(); + + if (laneId == 0) + { + loadToSmem(skeys, key, tid / 32); + loadToSmem(svals, val, tid / 32); + } + #endif + + __syncthreads(); + + loadFromSmem(skeys, key, tid); + + if (tid < 32) + { + #if 0 // __CUDA_ARCH__ >= 300 + loadFromSmem(svals, val, tid); + + Unroll::loopShfl(key, val, cmp, M); + #else + Unroll::loop(skeys, key, svals, val, tid, cmp); + #endif + } + } + }; + + template struct StaticIf; + template struct StaticIf + { + typedef T1 type; + }; + template struct StaticIf + { + typedef T2 type; + }; + + template struct IsPowerOf2 + { + enum { value = ((N != 0) && !(N & (N - 1))) }; + }; + + template struct Dispatcher + { + typedef typename StaticIf< + (N <= 32) && IsPowerOf2::value, + WarpOptimized, + typename StaticIf< + (N <= 1024) && IsPowerOf2::value, + GenericOptimized32, + Generic + >::type + >::type reductor; + }; + } +}}} + +//! @endcond + +#endif // OPENCV_CUDA_PRED_VAL_REDUCE_DETAIL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/transform_detail.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/transform_detail.hpp index 1919848827..e04e5b45aa 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/transform_detail.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/transform_detail.hpp @@ -1,392 +1,392 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_TRANSFORM_DETAIL_HPP -#define OPENCV_CUDA_TRANSFORM_DETAIL_HPP - -#include "../common.hpp" -#include "../vec_traits.hpp" -#include "../functional.hpp" - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - namespace transform_detail - { - //! Read Write Traits - - template struct UnaryReadWriteTraits - { - typedef typename TypeVec::vec_type read_type; - typedef typename TypeVec::vec_type write_type; - }; - - template struct BinaryReadWriteTraits - { - typedef typename TypeVec::vec_type read_type1; - typedef typename TypeVec::vec_type read_type2; - typedef typename TypeVec::vec_type write_type; - }; - - //! Transform kernels - - template struct OpUnroller; - template <> struct OpUnroller<1> - { - template - static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, UnOp& op, int x_shifted, int y) - { - if (mask(y, x_shifted)) - dst.x = op(src.x); - } - - template - static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, BinOp& op, int x_shifted, int y) - { - if (mask(y, x_shifted)) - dst.x = op(src1.x, src2.x); - } - }; - template <> struct OpUnroller<2> - { - template - static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, UnOp& op, int x_shifted, int y) - { - if (mask(y, x_shifted)) - dst.x = op(src.x); - if (mask(y, x_shifted + 1)) - dst.y = op(src.y); - } - - template - static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, BinOp& op, int x_shifted, int y) - { - if (mask(y, x_shifted)) - dst.x = op(src1.x, src2.x); - if (mask(y, x_shifted + 1)) - dst.y = op(src1.y, src2.y); - } - }; - template <> struct OpUnroller<3> - { - template - static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, const UnOp& op, int x_shifted, int y) - { - if (mask(y, x_shifted)) - dst.x = op(src.x); - if (mask(y, x_shifted + 1)) - dst.y = op(src.y); - if (mask(y, x_shifted + 2)) - dst.z = op(src.z); - } - - template - static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, const BinOp& op, int x_shifted, int y) - { - if (mask(y, x_shifted)) - dst.x = op(src1.x, src2.x); - if (mask(y, x_shifted + 1)) - dst.y = op(src1.y, src2.y); - if (mask(y, x_shifted + 2)) - dst.z = op(src1.z, src2.z); - } - }; - template <> struct OpUnroller<4> - { - template - static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, const UnOp& op, int x_shifted, int y) - { - if (mask(y, x_shifted)) - dst.x = op(src.x); - if (mask(y, x_shifted + 1)) - dst.y = op(src.y); - if (mask(y, x_shifted + 2)) - dst.z = op(src.z); - if (mask(y, x_shifted + 3)) - dst.w = op(src.w); - } - - template - static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, const BinOp& op, int x_shifted, int y) - { - if (mask(y, x_shifted)) - dst.x = op(src1.x, src2.x); - if (mask(y, x_shifted + 1)) - dst.y = op(src1.y, src2.y); - if (mask(y, x_shifted + 2)) - dst.z = op(src1.z, src2.z); - if (mask(y, x_shifted + 3)) - dst.w = op(src1.w, src2.w); - } - }; - template <> struct OpUnroller<8> - { - template - static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, const UnOp& op, int x_shifted, int y) - { - if (mask(y, x_shifted)) - dst.a0 = op(src.a0); - if (mask(y, x_shifted + 1)) - dst.a1 = op(src.a1); - if (mask(y, x_shifted + 2)) - dst.a2 = op(src.a2); - if (mask(y, x_shifted + 3)) - dst.a3 = op(src.a3); - if (mask(y, x_shifted + 4)) - dst.a4 = op(src.a4); - if (mask(y, x_shifted + 5)) - dst.a5 = op(src.a5); - if (mask(y, x_shifted + 6)) - dst.a6 = op(src.a6); - if (mask(y, x_shifted + 7)) - dst.a7 = op(src.a7); - } - - template - static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, const BinOp& op, int x_shifted, int y) - { - if (mask(y, x_shifted)) - dst.a0 = op(src1.a0, src2.a0); - if (mask(y, x_shifted + 1)) - dst.a1 = op(src1.a1, src2.a1); - if (mask(y, x_shifted + 2)) - dst.a2 = op(src1.a2, src2.a2); - if (mask(y, x_shifted + 3)) - dst.a3 = op(src1.a3, src2.a3); - if (mask(y, x_shifted + 4)) - dst.a4 = op(src1.a4, src2.a4); - if (mask(y, x_shifted + 5)) - dst.a5 = op(src1.a5, src2.a5); - if (mask(y, x_shifted + 6)) - dst.a6 = op(src1.a6, src2.a6); - if (mask(y, x_shifted + 7)) - dst.a7 = op(src1.a7, src2.a7); - } - }; - - template - static __global__ void transformSmart(const PtrStepSz src_, PtrStep dst_, const Mask mask, const UnOp op) - { - typedef TransformFunctorTraits ft; - typedef typename UnaryReadWriteTraits::read_type read_type; - typedef typename UnaryReadWriteTraits::write_type write_type; - - const int x = threadIdx.x + blockIdx.x * blockDim.x; - const int y = threadIdx.y + blockIdx.y * blockDim.y; - const int x_shifted = x * ft::smart_shift; - - if (y < src_.rows) - { - const T* src = src_.ptr(y); - D* dst = dst_.ptr(y); - - if (x_shifted + ft::smart_shift - 1 < src_.cols) - { - const read_type src_n_el = ((const read_type*)src)[x]; - OpUnroller::unroll(src_n_el, ((write_type*)dst)[x], mask, op, x_shifted, y); - } - else - { - for (int real_x = x_shifted; real_x < src_.cols; ++real_x) - { - if (mask(y, real_x)) - dst[real_x] = op(src[real_x]); - } - } - } - } - - template - __global__ static void transformSimple(const PtrStepSz src, PtrStep dst, const Mask mask, const UnOp op) - { - const int x = blockDim.x * blockIdx.x + threadIdx.x; - const int y = blockDim.y * blockIdx.y + threadIdx.y; - - if (x < src.cols && y < src.rows && mask(y, x)) - { - dst.ptr(y)[x] = op(src.ptr(y)[x]); - } - } - - template - static __global__ void transformSmart(const PtrStepSz src1_, const PtrStep src2_, PtrStep dst_, - const Mask mask, const BinOp op) - { - typedef TransformFunctorTraits ft; - typedef typename BinaryReadWriteTraits::read_type1 read_type1; - typedef typename BinaryReadWriteTraits::read_type2 read_type2; - typedef typename BinaryReadWriteTraits::write_type write_type; - - const int x = threadIdx.x + blockIdx.x * blockDim.x; - const int y = threadIdx.y + blockIdx.y * blockDim.y; - const int x_shifted = x * ft::smart_shift; - - if (y < src1_.rows) - { - const T1* src1 = src1_.ptr(y); - const T2* src2 = src2_.ptr(y); - D* dst = dst_.ptr(y); - - if (x_shifted + ft::smart_shift - 1 < src1_.cols) - { - const read_type1 src1_n_el = ((const read_type1*)src1)[x]; - const read_type2 src2_n_el = ((const read_type2*)src2)[x]; - - OpUnroller::unroll(src1_n_el, src2_n_el, ((write_type*)dst)[x], mask, op, x_shifted, y); - } - else - { - for (int real_x = x_shifted; real_x < src1_.cols; ++real_x) - { - if (mask(y, real_x)) - dst[real_x] = op(src1[real_x], src2[real_x]); - } - } - } - } - - template - static __global__ void transformSimple(const PtrStepSz src1, const PtrStep src2, PtrStep dst, - const Mask mask, const BinOp op) - { - const int x = blockDim.x * blockIdx.x + threadIdx.x; - const int y = blockDim.y * blockIdx.y + threadIdx.y; - - if (x < src1.cols && y < src1.rows && mask(y, x)) - { - const T1 src1_data = src1.ptr(y)[x]; - const T2 src2_data = src2.ptr(y)[x]; - dst.ptr(y)[x] = op(src1_data, src2_data); - } - } - - template struct TransformDispatcher; - template<> struct TransformDispatcher - { - template - static void call(PtrStepSz src, PtrStepSz dst, UnOp op, Mask mask, cudaStream_t stream) - { - typedef TransformFunctorTraits ft; - - const dim3 threads(ft::simple_block_dim_x, ft::simple_block_dim_y, 1); - const dim3 grid(divUp(src.cols, threads.x), divUp(src.rows, threads.y), 1); - - transformSimple<<>>(src, dst, mask, op); - cudaSafeCall( cudaGetLastError() ); - - if (stream == 0) - cudaSafeCall( cudaDeviceSynchronize() ); - } - - template - static void call(PtrStepSz src1, PtrStepSz src2, PtrStepSz dst, BinOp op, Mask mask, cudaStream_t stream) - { - typedef TransformFunctorTraits ft; - - const dim3 threads(ft::simple_block_dim_x, ft::simple_block_dim_y, 1); - const dim3 grid(divUp(src1.cols, threads.x), divUp(src1.rows, threads.y), 1); - - transformSimple<<>>(src1, src2, dst, mask, op); - cudaSafeCall( cudaGetLastError() ); - - if (stream == 0) - cudaSafeCall( cudaDeviceSynchronize() ); - } - }; - template<> struct TransformDispatcher - { - template - static void call(PtrStepSz src, PtrStepSz dst, UnOp op, Mask mask, cudaStream_t stream) - { - typedef TransformFunctorTraits ft; - - CV_StaticAssert(ft::smart_shift != 1, ""); - - if (!isAligned(src.data, ft::smart_shift * sizeof(T)) || !isAligned(src.step, ft::smart_shift * sizeof(T)) || - !isAligned(dst.data, ft::smart_shift * sizeof(D)) || !isAligned(dst.step, ft::smart_shift * sizeof(D))) - { - TransformDispatcher::call(src, dst, op, mask, stream); - return; - } - - const dim3 threads(ft::smart_block_dim_x, ft::smart_block_dim_y, 1); - const dim3 grid(divUp(src.cols, threads.x * ft::smart_shift), divUp(src.rows, threads.y), 1); - - transformSmart<<>>(src, dst, mask, op); - cudaSafeCall( cudaGetLastError() ); - - if (stream == 0) - cudaSafeCall( cudaDeviceSynchronize() ); - } - - template - static void call(PtrStepSz src1, PtrStepSz src2, PtrStepSz dst, BinOp op, Mask mask, cudaStream_t stream) - { - typedef TransformFunctorTraits ft; - - CV_StaticAssert(ft::smart_shift != 1, ""); - - if (!isAligned(src1.data, ft::smart_shift * sizeof(T1)) || !isAligned(src1.step, ft::smart_shift * sizeof(T1)) || - !isAligned(src2.data, ft::smart_shift * sizeof(T2)) || !isAligned(src2.step, ft::smart_shift * sizeof(T2)) || - !isAligned(dst.data, ft::smart_shift * sizeof(D)) || !isAligned(dst.step, ft::smart_shift * sizeof(D))) - { - TransformDispatcher::call(src1, src2, dst, op, mask, stream); - return; - } - - const dim3 threads(ft::smart_block_dim_x, ft::smart_block_dim_y, 1); - const dim3 grid(divUp(src1.cols, threads.x * ft::smart_shift), divUp(src1.rows, threads.y), 1); - - transformSmart<<>>(src1, src2, dst, mask, op); - cudaSafeCall( cudaGetLastError() ); - - if (stream == 0) - cudaSafeCall( cudaDeviceSynchronize() ); - } - }; - } // namespace transform_detail -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif // OPENCV_CUDA_TRANSFORM_DETAIL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_TRANSFORM_DETAIL_HPP +#define OPENCV_CUDA_TRANSFORM_DETAIL_HPP + +#include "../common.hpp" +#include "../vec_traits.hpp" +#include "../functional.hpp" + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + namespace transform_detail + { + //! Read Write Traits + + template struct UnaryReadWriteTraits + { + typedef typename TypeVec::vec_type read_type; + typedef typename TypeVec::vec_type write_type; + }; + + template struct BinaryReadWriteTraits + { + typedef typename TypeVec::vec_type read_type1; + typedef typename TypeVec::vec_type read_type2; + typedef typename TypeVec::vec_type write_type; + }; + + //! Transform kernels + + template struct OpUnroller; + template <> struct OpUnroller<1> + { + template + static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, UnOp& op, int x_shifted, int y) + { + if (mask(y, x_shifted)) + dst.x = op(src.x); + } + + template + static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, BinOp& op, int x_shifted, int y) + { + if (mask(y, x_shifted)) + dst.x = op(src1.x, src2.x); + } + }; + template <> struct OpUnroller<2> + { + template + static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, UnOp& op, int x_shifted, int y) + { + if (mask(y, x_shifted)) + dst.x = op(src.x); + if (mask(y, x_shifted + 1)) + dst.y = op(src.y); + } + + template + static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, BinOp& op, int x_shifted, int y) + { + if (mask(y, x_shifted)) + dst.x = op(src1.x, src2.x); + if (mask(y, x_shifted + 1)) + dst.y = op(src1.y, src2.y); + } + }; + template <> struct OpUnroller<3> + { + template + static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, const UnOp& op, int x_shifted, int y) + { + if (mask(y, x_shifted)) + dst.x = op(src.x); + if (mask(y, x_shifted + 1)) + dst.y = op(src.y); + if (mask(y, x_shifted + 2)) + dst.z = op(src.z); + } + + template + static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, const BinOp& op, int x_shifted, int y) + { + if (mask(y, x_shifted)) + dst.x = op(src1.x, src2.x); + if (mask(y, x_shifted + 1)) + dst.y = op(src1.y, src2.y); + if (mask(y, x_shifted + 2)) + dst.z = op(src1.z, src2.z); + } + }; + template <> struct OpUnroller<4> + { + template + static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, const UnOp& op, int x_shifted, int y) + { + if (mask(y, x_shifted)) + dst.x = op(src.x); + if (mask(y, x_shifted + 1)) + dst.y = op(src.y); + if (mask(y, x_shifted + 2)) + dst.z = op(src.z); + if (mask(y, x_shifted + 3)) + dst.w = op(src.w); + } + + template + static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, const BinOp& op, int x_shifted, int y) + { + if (mask(y, x_shifted)) + dst.x = op(src1.x, src2.x); + if (mask(y, x_shifted + 1)) + dst.y = op(src1.y, src2.y); + if (mask(y, x_shifted + 2)) + dst.z = op(src1.z, src2.z); + if (mask(y, x_shifted + 3)) + dst.w = op(src1.w, src2.w); + } + }; + template <> struct OpUnroller<8> + { + template + static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, const UnOp& op, int x_shifted, int y) + { + if (mask(y, x_shifted)) + dst.a0 = op(src.a0); + if (mask(y, x_shifted + 1)) + dst.a1 = op(src.a1); + if (mask(y, x_shifted + 2)) + dst.a2 = op(src.a2); + if (mask(y, x_shifted + 3)) + dst.a3 = op(src.a3); + if (mask(y, x_shifted + 4)) + dst.a4 = op(src.a4); + if (mask(y, x_shifted + 5)) + dst.a5 = op(src.a5); + if (mask(y, x_shifted + 6)) + dst.a6 = op(src.a6); + if (mask(y, x_shifted + 7)) + dst.a7 = op(src.a7); + } + + template + static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, const BinOp& op, int x_shifted, int y) + { + if (mask(y, x_shifted)) + dst.a0 = op(src1.a0, src2.a0); + if (mask(y, x_shifted + 1)) + dst.a1 = op(src1.a1, src2.a1); + if (mask(y, x_shifted + 2)) + dst.a2 = op(src1.a2, src2.a2); + if (mask(y, x_shifted + 3)) + dst.a3 = op(src1.a3, src2.a3); + if (mask(y, x_shifted + 4)) + dst.a4 = op(src1.a4, src2.a4); + if (mask(y, x_shifted + 5)) + dst.a5 = op(src1.a5, src2.a5); + if (mask(y, x_shifted + 6)) + dst.a6 = op(src1.a6, src2.a6); + if (mask(y, x_shifted + 7)) + dst.a7 = op(src1.a7, src2.a7); + } + }; + + template + static __global__ void transformSmart(const PtrStepSz src_, PtrStep dst_, const Mask mask, const UnOp op) + { + typedef TransformFunctorTraits ft; + typedef typename UnaryReadWriteTraits::read_type read_type; + typedef typename UnaryReadWriteTraits::write_type write_type; + + const int x = threadIdx.x + blockIdx.x * blockDim.x; + const int y = threadIdx.y + blockIdx.y * blockDim.y; + const int x_shifted = x * ft::smart_shift; + + if (y < src_.rows) + { + const T* src = src_.ptr(y); + D* dst = dst_.ptr(y); + + if (x_shifted + ft::smart_shift - 1 < src_.cols) + { + const read_type src_n_el = ((const read_type*)src)[x]; + OpUnroller::unroll(src_n_el, ((write_type*)dst)[x], mask, op, x_shifted, y); + } + else + { + for (int real_x = x_shifted; real_x < src_.cols; ++real_x) + { + if (mask(y, real_x)) + dst[real_x] = op(src[real_x]); + } + } + } + } + + template + __global__ static void transformSimple(const PtrStepSz src, PtrStep dst, const Mask mask, const UnOp op) + { + const int x = blockDim.x * blockIdx.x + threadIdx.x; + const int y = blockDim.y * blockIdx.y + threadIdx.y; + + if (x < src.cols && y < src.rows && mask(y, x)) + { + dst.ptr(y)[x] = op(src.ptr(y)[x]); + } + } + + template + static __global__ void transformSmart(const PtrStepSz src1_, const PtrStep src2_, PtrStep dst_, + const Mask mask, const BinOp op) + { + typedef TransformFunctorTraits ft; + typedef typename BinaryReadWriteTraits::read_type1 read_type1; + typedef typename BinaryReadWriteTraits::read_type2 read_type2; + typedef typename BinaryReadWriteTraits::write_type write_type; + + const int x = threadIdx.x + blockIdx.x * blockDim.x; + const int y = threadIdx.y + blockIdx.y * blockDim.y; + const int x_shifted = x * ft::smart_shift; + + if (y < src1_.rows) + { + const T1* src1 = src1_.ptr(y); + const T2* src2 = src2_.ptr(y); + D* dst = dst_.ptr(y); + + if (x_shifted + ft::smart_shift - 1 < src1_.cols) + { + const read_type1 src1_n_el = ((const read_type1*)src1)[x]; + const read_type2 src2_n_el = ((const read_type2*)src2)[x]; + + OpUnroller::unroll(src1_n_el, src2_n_el, ((write_type*)dst)[x], mask, op, x_shifted, y); + } + else + { + for (int real_x = x_shifted; real_x < src1_.cols; ++real_x) + { + if (mask(y, real_x)) + dst[real_x] = op(src1[real_x], src2[real_x]); + } + } + } + } + + template + static __global__ void transformSimple(const PtrStepSz src1, const PtrStep src2, PtrStep dst, + const Mask mask, const BinOp op) + { + const int x = blockDim.x * blockIdx.x + threadIdx.x; + const int y = blockDim.y * blockIdx.y + threadIdx.y; + + if (x < src1.cols && y < src1.rows && mask(y, x)) + { + const T1 src1_data = src1.ptr(y)[x]; + const T2 src2_data = src2.ptr(y)[x]; + dst.ptr(y)[x] = op(src1_data, src2_data); + } + } + + template struct TransformDispatcher; + template<> struct TransformDispatcher + { + template + static void call(PtrStepSz src, PtrStepSz dst, UnOp op, Mask mask, cudaStream_t stream) + { + typedef TransformFunctorTraits ft; + + const dim3 threads(ft::simple_block_dim_x, ft::simple_block_dim_y, 1); + const dim3 grid(divUp(src.cols, threads.x), divUp(src.rows, threads.y), 1); + + transformSimple<<>>(src, dst, mask, op); + cudaSafeCall( cudaGetLastError() ); + + if (stream == 0) + cudaSafeCall( cudaDeviceSynchronize() ); + } + + template + static void call(PtrStepSz src1, PtrStepSz src2, PtrStepSz dst, BinOp op, Mask mask, cudaStream_t stream) + { + typedef TransformFunctorTraits ft; + + const dim3 threads(ft::simple_block_dim_x, ft::simple_block_dim_y, 1); + const dim3 grid(divUp(src1.cols, threads.x), divUp(src1.rows, threads.y), 1); + + transformSimple<<>>(src1, src2, dst, mask, op); + cudaSafeCall( cudaGetLastError() ); + + if (stream == 0) + cudaSafeCall( cudaDeviceSynchronize() ); + } + }; + template<> struct TransformDispatcher + { + template + static void call(PtrStepSz src, PtrStepSz dst, UnOp op, Mask mask, cudaStream_t stream) + { + typedef TransformFunctorTraits ft; + + CV_StaticAssert(ft::smart_shift != 1, ""); + + if (!isAligned(src.data, ft::smart_shift * sizeof(T)) || !isAligned(src.step, ft::smart_shift * sizeof(T)) || + !isAligned(dst.data, ft::smart_shift * sizeof(D)) || !isAligned(dst.step, ft::smart_shift * sizeof(D))) + { + TransformDispatcher::call(src, dst, op, mask, stream); + return; + } + + const dim3 threads(ft::smart_block_dim_x, ft::smart_block_dim_y, 1); + const dim3 grid(divUp(src.cols, threads.x * ft::smart_shift), divUp(src.rows, threads.y), 1); + + transformSmart<<>>(src, dst, mask, op); + cudaSafeCall( cudaGetLastError() ); + + if (stream == 0) + cudaSafeCall( cudaDeviceSynchronize() ); + } + + template + static void call(PtrStepSz src1, PtrStepSz src2, PtrStepSz dst, BinOp op, Mask mask, cudaStream_t stream) + { + typedef TransformFunctorTraits ft; + + CV_StaticAssert(ft::smart_shift != 1, ""); + + if (!isAligned(src1.data, ft::smart_shift * sizeof(T1)) || !isAligned(src1.step, ft::smart_shift * sizeof(T1)) || + !isAligned(src2.data, ft::smart_shift * sizeof(T2)) || !isAligned(src2.step, ft::smart_shift * sizeof(T2)) || + !isAligned(dst.data, ft::smart_shift * sizeof(D)) || !isAligned(dst.step, ft::smart_shift * sizeof(D))) + { + TransformDispatcher::call(src1, src2, dst, op, mask, stream); + return; + } + + const dim3 threads(ft::smart_block_dim_x, ft::smart_block_dim_y, 1); + const dim3 grid(divUp(src1.cols, threads.x * ft::smart_shift), divUp(src1.rows, threads.y), 1); + + transformSmart<<>>(src1, src2, dst, mask, op); + cudaSafeCall( cudaGetLastError() ); + + if (stream == 0) + cudaSafeCall( cudaDeviceSynchronize() ); + } + }; + } // namespace transform_detail +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif // OPENCV_CUDA_TRANSFORM_DETAIL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/type_traits_detail.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/type_traits_detail.hpp index a78bd2c0d8..da62978d19 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/type_traits_detail.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/type_traits_detail.hpp @@ -1,191 +1,191 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_TYPE_TRAITS_DETAIL_HPP -#define OPENCV_CUDA_TYPE_TRAITS_DETAIL_HPP - -#include "../common.hpp" -#include "../vec_traits.hpp" - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - namespace type_traits_detail - { - template struct Select { typedef T1 type; }; - template struct Select { typedef T2 type; }; - - template struct IsSignedIntergral { enum {value = 0}; }; - template <> struct IsSignedIntergral { enum {value = 1}; }; - template <> struct IsSignedIntergral { enum {value = 1}; }; - template <> struct IsSignedIntergral { enum {value = 1}; }; - template <> struct IsSignedIntergral { enum {value = 1}; }; - template <> struct IsSignedIntergral { enum {value = 1}; }; - template <> struct IsSignedIntergral { enum {value = 1}; }; - - template struct IsUnsignedIntegral { enum {value = 0}; }; - template <> struct IsUnsignedIntegral { enum {value = 1}; }; - template <> struct IsUnsignedIntegral { enum {value = 1}; }; - template <> struct IsUnsignedIntegral { enum {value = 1}; }; - template <> struct IsUnsignedIntegral { enum {value = 1}; }; - template <> struct IsUnsignedIntegral { enum {value = 1}; }; - template <> struct IsUnsignedIntegral { enum {value = 1}; }; - - template struct IsIntegral { enum {value = IsSignedIntergral::value || IsUnsignedIntegral::value}; }; - template <> struct IsIntegral { enum {value = 1}; }; - template <> struct IsIntegral { enum {value = 1}; }; - - template struct IsFloat { enum {value = 0}; }; - template <> struct IsFloat { enum {value = 1}; }; - template <> struct IsFloat { enum {value = 1}; }; - - template struct IsVec { enum {value = 0}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - - template struct AddParameterType { typedef const U& type; }; - template struct AddParameterType { typedef U& type; }; - template <> struct AddParameterType { typedef void type; }; - - template struct ReferenceTraits - { - enum { value = false }; - typedef U type; - }; - template struct ReferenceTraits - { - enum { value = true }; - typedef U type; - }; - - template struct PointerTraits - { - enum { value = false }; - typedef void type; - }; - template struct PointerTraits - { - enum { value = true }; - typedef U type; - }; - template struct PointerTraits - { - enum { value = true }; - typedef U type; - }; - - template struct UnConst - { - typedef U type; - enum { value = 0 }; - }; - template struct UnConst - { - typedef U type; - enum { value = 1 }; - }; - template struct UnConst - { - typedef U& type; - enum { value = 1 }; - }; - - template struct UnVolatile - { - typedef U type; - enum { value = 0 }; - }; - template struct UnVolatile - { - typedef U type; - enum { value = 1 }; - }; - template struct UnVolatile - { - typedef U& type; - enum { value = 1 }; - }; - } // namespace type_traits_detail -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif // OPENCV_CUDA_TYPE_TRAITS_DETAIL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_TYPE_TRAITS_DETAIL_HPP +#define OPENCV_CUDA_TYPE_TRAITS_DETAIL_HPP + +#include "../common.hpp" +#include "../vec_traits.hpp" + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + namespace type_traits_detail + { + template struct Select { typedef T1 type; }; + template struct Select { typedef T2 type; }; + + template struct IsSignedIntergral { enum {value = 0}; }; + template <> struct IsSignedIntergral { enum {value = 1}; }; + template <> struct IsSignedIntergral { enum {value = 1}; }; + template <> struct IsSignedIntergral { enum {value = 1}; }; + template <> struct IsSignedIntergral { enum {value = 1}; }; + template <> struct IsSignedIntergral { enum {value = 1}; }; + template <> struct IsSignedIntergral { enum {value = 1}; }; + + template struct IsUnsignedIntegral { enum {value = 0}; }; + template <> struct IsUnsignedIntegral { enum {value = 1}; }; + template <> struct IsUnsignedIntegral { enum {value = 1}; }; + template <> struct IsUnsignedIntegral { enum {value = 1}; }; + template <> struct IsUnsignedIntegral { enum {value = 1}; }; + template <> struct IsUnsignedIntegral { enum {value = 1}; }; + template <> struct IsUnsignedIntegral { enum {value = 1}; }; + + template struct IsIntegral { enum {value = IsSignedIntergral::value || IsUnsignedIntegral::value}; }; + template <> struct IsIntegral { enum {value = 1}; }; + template <> struct IsIntegral { enum {value = 1}; }; + + template struct IsFloat { enum {value = 0}; }; + template <> struct IsFloat { enum {value = 1}; }; + template <> struct IsFloat { enum {value = 1}; }; + + template struct IsVec { enum {value = 0}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + + template struct AddParameterType { typedef const U& type; }; + template struct AddParameterType { typedef U& type; }; + template <> struct AddParameterType { typedef void type; }; + + template struct ReferenceTraits + { + enum { value = false }; + typedef U type; + }; + template struct ReferenceTraits + { + enum { value = true }; + typedef U type; + }; + + template struct PointerTraits + { + enum { value = false }; + typedef void type; + }; + template struct PointerTraits + { + enum { value = true }; + typedef U type; + }; + template struct PointerTraits + { + enum { value = true }; + typedef U type; + }; + + template struct UnConst + { + typedef U type; + enum { value = 0 }; + }; + template struct UnConst + { + typedef U type; + enum { value = 1 }; + }; + template struct UnConst + { + typedef U& type; + enum { value = 1 }; + }; + + template struct UnVolatile + { + typedef U type; + enum { value = 0 }; + }; + template struct UnVolatile + { + typedef U type; + enum { value = 1 }; + }; + template struct UnVolatile + { + typedef U& type; + enum { value = 1 }; + }; + } // namespace type_traits_detail +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif // OPENCV_CUDA_TYPE_TRAITS_DETAIL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/vec_distance_detail.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/vec_distance_detail.hpp index 8283a99560..74604f8302 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/vec_distance_detail.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/vec_distance_detail.hpp @@ -1,121 +1,121 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_VEC_DISTANCE_DETAIL_HPP -#define OPENCV_CUDA_VEC_DISTANCE_DETAIL_HPP - -#include "../datamov_utils.hpp" - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - namespace vec_distance_detail - { - template struct UnrollVecDiffCached - { - template - static __device__ void calcCheck(const T1* vecCached, const T2* vecGlob, int len, Dist& dist, int ind) - { - if (ind < len) - { - T1 val1 = *vecCached++; - - T2 val2; - ForceGlob::Load(vecGlob, ind, val2); - - dist.reduceIter(val1, val2); - - UnrollVecDiffCached::calcCheck(vecCached, vecGlob, len, dist, ind + THREAD_DIM); - } - } - - template - static __device__ void calcWithoutCheck(const T1* vecCached, const T2* vecGlob, Dist& dist) - { - T1 val1 = *vecCached++; - - T2 val2; - ForceGlob::Load(vecGlob, 0, val2); - vecGlob += THREAD_DIM; - - dist.reduceIter(val1, val2); - - UnrollVecDiffCached::calcWithoutCheck(vecCached, vecGlob, dist); - } - }; - template struct UnrollVecDiffCached - { - template - static __device__ __forceinline__ void calcCheck(const T1*, const T2*, int, Dist&, int) - { - } - - template - static __device__ __forceinline__ void calcWithoutCheck(const T1*, const T2*, Dist&) - { - } - }; - - template struct VecDiffCachedCalculator; - template struct VecDiffCachedCalculator - { - template - static __device__ __forceinline__ void calc(const T1* vecCached, const T2* vecGlob, int len, Dist& dist, int tid) - { - UnrollVecDiffCached::calcCheck(vecCached, vecGlob, len, dist, tid); - } - }; - template struct VecDiffCachedCalculator - { - template - static __device__ __forceinline__ void calc(const T1* vecCached, const T2* vecGlob, int len, Dist& dist, int tid) - { - UnrollVecDiffCached::calcWithoutCheck(vecCached, vecGlob + tid, dist); - } - }; - } // namespace vec_distance_detail -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif // OPENCV_CUDA_VEC_DISTANCE_DETAIL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_VEC_DISTANCE_DETAIL_HPP +#define OPENCV_CUDA_VEC_DISTANCE_DETAIL_HPP + +#include "../datamov_utils.hpp" + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + namespace vec_distance_detail + { + template struct UnrollVecDiffCached + { + template + static __device__ void calcCheck(const T1* vecCached, const T2* vecGlob, int len, Dist& dist, int ind) + { + if (ind < len) + { + T1 val1 = *vecCached++; + + T2 val2; + ForceGlob::Load(vecGlob, ind, val2); + + dist.reduceIter(val1, val2); + + UnrollVecDiffCached::calcCheck(vecCached, vecGlob, len, dist, ind + THREAD_DIM); + } + } + + template + static __device__ void calcWithoutCheck(const T1* vecCached, const T2* vecGlob, Dist& dist) + { + T1 val1 = *vecCached++; + + T2 val2; + ForceGlob::Load(vecGlob, 0, val2); + vecGlob += THREAD_DIM; + + dist.reduceIter(val1, val2); + + UnrollVecDiffCached::calcWithoutCheck(vecCached, vecGlob, dist); + } + }; + template struct UnrollVecDiffCached + { + template + static __device__ __forceinline__ void calcCheck(const T1*, const T2*, int, Dist&, int) + { + } + + template + static __device__ __forceinline__ void calcWithoutCheck(const T1*, const T2*, Dist&) + { + } + }; + + template struct VecDiffCachedCalculator; + template struct VecDiffCachedCalculator + { + template + static __device__ __forceinline__ void calc(const T1* vecCached, const T2* vecGlob, int len, Dist& dist, int tid) + { + UnrollVecDiffCached::calcCheck(vecCached, vecGlob, len, dist, tid); + } + }; + template struct VecDiffCachedCalculator + { + template + static __device__ __forceinline__ void calc(const T1* vecCached, const T2* vecGlob, int len, Dist& dist, int tid) + { + UnrollVecDiffCached::calcWithoutCheck(vecCached, vecGlob + tid, dist); + } + }; + } // namespace vec_distance_detail +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif // OPENCV_CUDA_VEC_DISTANCE_DETAIL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/dynamic_smem.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/dynamic_smem.hpp index 42570c6830..61e88cfff0 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/dynamic_smem.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/dynamic_smem.hpp @@ -1,88 +1,88 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_DYNAMIC_SMEM_HPP -#define OPENCV_CUDA_DYNAMIC_SMEM_HPP - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - template struct DynamicSharedMem - { - __device__ __forceinline__ operator T*() - { - extern __shared__ int __smem[]; - return (T*)__smem; - } - - __device__ __forceinline__ operator const T*() const - { - extern __shared__ int __smem[]; - return (T*)__smem; - } - }; - - // specialize for double to avoid unaligned memory access compile errors - template<> struct DynamicSharedMem - { - __device__ __forceinline__ operator double*() - { - extern __shared__ double __smem_d[]; - return (double*)__smem_d; - } - - __device__ __forceinline__ operator const double*() const - { - extern __shared__ double __smem_d[]; - return (double*)__smem_d; - } - }; -}}} - -//! @endcond - -#endif // OPENCV_CUDA_DYNAMIC_SMEM_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_DYNAMIC_SMEM_HPP +#define OPENCV_CUDA_DYNAMIC_SMEM_HPP + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + template struct DynamicSharedMem + { + __device__ __forceinline__ operator T*() + { + extern __shared__ int __smem[]; + return (T*)__smem; + } + + __device__ __forceinline__ operator const T*() const + { + extern __shared__ int __smem[]; + return (T*)__smem; + } + }; + + // specialize for double to avoid unaligned memory access compile errors + template<> struct DynamicSharedMem + { + __device__ __forceinline__ operator double*() + { + extern __shared__ double __smem_d[]; + return (double*)__smem_d; + } + + __device__ __forceinline__ operator const double*() const + { + extern __shared__ double __smem_d[]; + return (double*)__smem_d; + } + }; +}}} + +//! @endcond + +#endif // OPENCV_CUDA_DYNAMIC_SMEM_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/emulation.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/emulation.hpp index 17dc1171a2..7697a876b3 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/emulation.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/emulation.hpp @@ -1,269 +1,269 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_EMULATION_HPP_ -#define OPENCV_CUDA_EMULATION_HPP_ - -#include "common.hpp" -#include "warp_reduce.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - struct Emulation - { - - static __device__ __forceinline__ int syncthreadsOr(int pred) - { -#if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ < 200) - // just campilation stab - return 0; -#else - return __syncthreads_or(pred); -#endif - } - - template - static __forceinline__ __device__ int Ballot(int predicate) - { -#if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ >= 200) - return __ballot(predicate); -#else - __shared__ volatile int cta_buffer[CTA_SIZE]; - - int tid = threadIdx.x; - cta_buffer[tid] = predicate ? (1 << (tid & 31)) : 0; - return warp_reduce(cta_buffer); -#endif - } - - struct smem - { - enum { TAG_MASK = (1U << ( (sizeof(unsigned int) << 3) - 5U)) - 1U }; - - template - static __device__ __forceinline__ T atomicInc(T* address, T val) - { -#if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ < 120) - T count; - unsigned int tag = threadIdx.x << ( (sizeof(unsigned int) << 3) - 5U); - do - { - count = *address & TAG_MASK; - count = tag | (count + 1); - *address = count; - } while (*address != count); - - return (count & TAG_MASK) - 1; -#else - return ::atomicInc(address, val); -#endif - } - - template - static __device__ __forceinline__ T atomicAdd(T* address, T val) - { -#if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ < 120) - T count; - unsigned int tag = threadIdx.x << ( (sizeof(unsigned int) << 3) - 5U); - do - { - count = *address & TAG_MASK; - count = tag | (count + val); - *address = count; - } while (*address != count); - - return (count & TAG_MASK) - val; -#else - return ::atomicAdd(address, val); -#endif - } - - template - static __device__ __forceinline__ T atomicMin(T* address, T val) - { -#if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ < 120) - T count = ::min(*address, val); - do - { - *address = count; - } while (*address > count); - - return count; -#else - return ::atomicMin(address, val); -#endif - } - }; // struct cmem - - struct glob - { - static __device__ __forceinline__ int atomicAdd(int* address, int val) - { - return ::atomicAdd(address, val); - } - static __device__ __forceinline__ unsigned int atomicAdd(unsigned int* address, unsigned int val) - { - return ::atomicAdd(address, val); - } - static __device__ __forceinline__ float atomicAdd(float* address, float val) - { - #if __CUDA_ARCH__ >= 200 - return ::atomicAdd(address, val); - #else - int* address_as_i = (int*) address; - int old = *address_as_i, assumed; - do { - assumed = old; - old = ::atomicCAS(address_as_i, assumed, - __float_as_int(val + __int_as_float(assumed))); - } while (assumed != old); - return __int_as_float(old); - #endif - } - static __device__ __forceinline__ double atomicAdd(double* address, double val) - { - #if __CUDA_ARCH__ >= 130 - unsigned long long int* address_as_ull = (unsigned long long int*) address; - unsigned long long int old = *address_as_ull, assumed; - do { - assumed = old; - old = ::atomicCAS(address_as_ull, assumed, - __double_as_longlong(val + __longlong_as_double(assumed))); - } while (assumed != old); - return __longlong_as_double(old); - #else - CV_UNUSED(address); - CV_UNUSED(val); - return 0.0; - #endif - } - - static __device__ __forceinline__ int atomicMin(int* address, int val) - { - return ::atomicMin(address, val); - } - static __device__ __forceinline__ float atomicMin(float* address, float val) - { - #if __CUDA_ARCH__ >= 120 - int* address_as_i = (int*) address; - int old = *address_as_i, assumed; - do { - assumed = old; - old = ::atomicCAS(address_as_i, assumed, - __float_as_int(::fminf(val, __int_as_float(assumed)))); - } while (assumed != old); - return __int_as_float(old); - #else - CV_UNUSED(address); - CV_UNUSED(val); - return 0.0f; - #endif - } - static __device__ __forceinline__ double atomicMin(double* address, double val) - { - #if __CUDA_ARCH__ >= 130 - unsigned long long int* address_as_ull = (unsigned long long int*) address; - unsigned long long int old = *address_as_ull, assumed; - do { - assumed = old; - old = ::atomicCAS(address_as_ull, assumed, - __double_as_longlong(::fmin(val, __longlong_as_double(assumed)))); - } while (assumed != old); - return __longlong_as_double(old); - #else - CV_UNUSED(address); - CV_UNUSED(val); - return 0.0; - #endif - } - - static __device__ __forceinline__ int atomicMax(int* address, int val) - { - return ::atomicMax(address, val); - } - static __device__ __forceinline__ float atomicMax(float* address, float val) - { - #if __CUDA_ARCH__ >= 120 - int* address_as_i = (int*) address; - int old = *address_as_i, assumed; - do { - assumed = old; - old = ::atomicCAS(address_as_i, assumed, - __float_as_int(::fmaxf(val, __int_as_float(assumed)))); - } while (assumed != old); - return __int_as_float(old); - #else - CV_UNUSED(address); - CV_UNUSED(val); - return 0.0f; - #endif - } - static __device__ __forceinline__ double atomicMax(double* address, double val) - { - #if __CUDA_ARCH__ >= 130 - unsigned long long int* address_as_ull = (unsigned long long int*) address; - unsigned long long int old = *address_as_ull, assumed; - do { - assumed = old; - old = ::atomicCAS(address_as_ull, assumed, - __double_as_longlong(::fmax(val, __longlong_as_double(assumed)))); - } while (assumed != old); - return __longlong_as_double(old); - #else - CV_UNUSED(address); - CV_UNUSED(val); - return 0.0; - #endif - } - }; - }; //struct Emulation -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif /* OPENCV_CUDA_EMULATION_HPP_ */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_EMULATION_HPP_ +#define OPENCV_CUDA_EMULATION_HPP_ + +#include "common.hpp" +#include "warp_reduce.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + struct Emulation + { + + static __device__ __forceinline__ int syncthreadsOr(int pred) + { +#if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ < 200) + // just campilation stab + return 0; +#else + return __syncthreads_or(pred); +#endif + } + + template + static __forceinline__ __device__ int Ballot(int predicate) + { +#if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ >= 200) + return __ballot(predicate); +#else + __shared__ volatile int cta_buffer[CTA_SIZE]; + + int tid = threadIdx.x; + cta_buffer[tid] = predicate ? (1 << (tid & 31)) : 0; + return warp_reduce(cta_buffer); +#endif + } + + struct smem + { + enum { TAG_MASK = (1U << ( (sizeof(unsigned int) << 3) - 5U)) - 1U }; + + template + static __device__ __forceinline__ T atomicInc(T* address, T val) + { +#if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ < 120) + T count; + unsigned int tag = threadIdx.x << ( (sizeof(unsigned int) << 3) - 5U); + do + { + count = *address & TAG_MASK; + count = tag | (count + 1); + *address = count; + } while (*address != count); + + return (count & TAG_MASK) - 1; +#else + return ::atomicInc(address, val); +#endif + } + + template + static __device__ __forceinline__ T atomicAdd(T* address, T val) + { +#if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ < 120) + T count; + unsigned int tag = threadIdx.x << ( (sizeof(unsigned int) << 3) - 5U); + do + { + count = *address & TAG_MASK; + count = tag | (count + val); + *address = count; + } while (*address != count); + + return (count & TAG_MASK) - val; +#else + return ::atomicAdd(address, val); +#endif + } + + template + static __device__ __forceinline__ T atomicMin(T* address, T val) + { +#if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ < 120) + T count = ::min(*address, val); + do + { + *address = count; + } while (*address > count); + + return count; +#else + return ::atomicMin(address, val); +#endif + } + }; // struct cmem + + struct glob + { + static __device__ __forceinline__ int atomicAdd(int* address, int val) + { + return ::atomicAdd(address, val); + } + static __device__ __forceinline__ unsigned int atomicAdd(unsigned int* address, unsigned int val) + { + return ::atomicAdd(address, val); + } + static __device__ __forceinline__ float atomicAdd(float* address, float val) + { + #if __CUDA_ARCH__ >= 200 + return ::atomicAdd(address, val); + #else + int* address_as_i = (int*) address; + int old = *address_as_i, assumed; + do { + assumed = old; + old = ::atomicCAS(address_as_i, assumed, + __float_as_int(val + __int_as_float(assumed))); + } while (assumed != old); + return __int_as_float(old); + #endif + } + static __device__ __forceinline__ double atomicAdd(double* address, double val) + { + #if __CUDA_ARCH__ >= 130 + unsigned long long int* address_as_ull = (unsigned long long int*) address; + unsigned long long int old = *address_as_ull, assumed; + do { + assumed = old; + old = ::atomicCAS(address_as_ull, assumed, + __double_as_longlong(val + __longlong_as_double(assumed))); + } while (assumed != old); + return __longlong_as_double(old); + #else + CV_UNUSED(address); + CV_UNUSED(val); + return 0.0; + #endif + } + + static __device__ __forceinline__ int atomicMin(int* address, int val) + { + return ::atomicMin(address, val); + } + static __device__ __forceinline__ float atomicMin(float* address, float val) + { + #if __CUDA_ARCH__ >= 120 + int* address_as_i = (int*) address; + int old = *address_as_i, assumed; + do { + assumed = old; + old = ::atomicCAS(address_as_i, assumed, + __float_as_int(::fminf(val, __int_as_float(assumed)))); + } while (assumed != old); + return __int_as_float(old); + #else + CV_UNUSED(address); + CV_UNUSED(val); + return 0.0f; + #endif + } + static __device__ __forceinline__ double atomicMin(double* address, double val) + { + #if __CUDA_ARCH__ >= 130 + unsigned long long int* address_as_ull = (unsigned long long int*) address; + unsigned long long int old = *address_as_ull, assumed; + do { + assumed = old; + old = ::atomicCAS(address_as_ull, assumed, + __double_as_longlong(::fmin(val, __longlong_as_double(assumed)))); + } while (assumed != old); + return __longlong_as_double(old); + #else + CV_UNUSED(address); + CV_UNUSED(val); + return 0.0; + #endif + } + + static __device__ __forceinline__ int atomicMax(int* address, int val) + { + return ::atomicMax(address, val); + } + static __device__ __forceinline__ float atomicMax(float* address, float val) + { + #if __CUDA_ARCH__ >= 120 + int* address_as_i = (int*) address; + int old = *address_as_i, assumed; + do { + assumed = old; + old = ::atomicCAS(address_as_i, assumed, + __float_as_int(::fmaxf(val, __int_as_float(assumed)))); + } while (assumed != old); + return __int_as_float(old); + #else + CV_UNUSED(address); + CV_UNUSED(val); + return 0.0f; + #endif + } + static __device__ __forceinline__ double atomicMax(double* address, double val) + { + #if __CUDA_ARCH__ >= 130 + unsigned long long int* address_as_ull = (unsigned long long int*) address; + unsigned long long int old = *address_as_ull, assumed; + do { + assumed = old; + old = ::atomicCAS(address_as_ull, assumed, + __double_as_longlong(::fmax(val, __longlong_as_double(assumed)))); + } while (assumed != old); + return __longlong_as_double(old); + #else + CV_UNUSED(address); + CV_UNUSED(val); + return 0.0; + #endif + } + }; + }; //struct Emulation +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif /* OPENCV_CUDA_EMULATION_HPP_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/filters.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/filters.hpp index bf3147edb9..bba354036a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/filters.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/filters.hpp @@ -1,293 +1,293 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_FILTERS_HPP -#define OPENCV_CUDA_FILTERS_HPP - -#include "saturate_cast.hpp" -#include "vec_traits.hpp" -#include "vec_math.hpp" -#include "type_traits.hpp" -#include "nppdefs.h" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - template struct PointFilter - { - typedef typename Ptr2D::elem_type elem_type; - typedef float index_type; - - explicit __host__ __device__ __forceinline__ PointFilter(const Ptr2D& src_, float fx = 0.f, float fy = 0.f) - : src(src_) - { - CV_UNUSED(fx); - CV_UNUSED(fy); - } - - __device__ __forceinline__ elem_type operator ()(float y, float x) const - { - return src(__float2int_rz(y), __float2int_rz(x)); - } - - Ptr2D src; - }; - - template struct LinearFilter - { - typedef typename Ptr2D::elem_type elem_type; - typedef float index_type; - - explicit __host__ __device__ __forceinline__ LinearFilter(const Ptr2D& src_, float fx = 0.f, float fy = 0.f) - : src(src_) - { - CV_UNUSED(fx); - CV_UNUSED(fy); - } - __device__ __forceinline__ elem_type operator ()(float y, float x) const - { - typedef typename TypeVec::cn>::vec_type work_type; - - work_type out = VecTraits::all(0); - - const int x1 = __float2int_rd(x); - const int y1 = __float2int_rd(y); - if (x1 <= NPP_MIN_32S || x1 >= NPP_MAX_32S || y1 <= NPP_MIN_32S || y1 >= NPP_MAX_32S) - { - elem_type src_reg = src(y1, x1); - out = out + src_reg * 1.0f; - return saturate_cast(out); - } - const int x2 = x1 + 1; - const int y2 = y1 + 1; - - elem_type src_reg = src(y1, x1); - out = out + src_reg * ((x2 - x) * (y2 - y)); - - src_reg = src(y1, x2); - out = out + src_reg * ((x - x1) * (y2 - y)); - - src_reg = src(y2, x1); - out = out + src_reg * ((x2 - x) * (y - y1)); - - src_reg = src(y2, x2); - out = out + src_reg * ((x - x1) * (y - y1)); - - return saturate_cast(out); - } - - Ptr2D src; - }; - - template struct CubicFilter - { - typedef typename Ptr2D::elem_type elem_type; - typedef float index_type; - typedef typename TypeVec::cn>::vec_type work_type; - - explicit __host__ __device__ __forceinline__ CubicFilter(const Ptr2D& src_, float fx = 0.f, float fy = 0.f) - : src(src_) - { - CV_UNUSED(fx); - CV_UNUSED(fy); - } - - static __device__ __forceinline__ float bicubicCoeff(float x_) - { - float x = fabsf(x_); - if (x <= 1.0f) - { - return x * x * (1.5f * x - 2.5f) + 1.0f; - } - else if (x < 2.0f) - { - return x * (x * (-0.5f * x + 2.5f) - 4.0f) + 2.0f; - } - else - { - return 0.0f; - } - } - - __device__ elem_type operator ()(float y, float x) const - { - const float xmin = ::ceilf(x - 2.0f); - const float xmax = ::floorf(x + 2.0f); - - const float ymin = ::ceilf(y - 2.0f); - const float ymax = ::floorf(y + 2.0f); - - work_type sum = VecTraits::all(0); - float wsum = 0.0f; - - for (float cy = ymin; cy <= ymax; cy += 1.0f) - { - for (float cx = xmin; cx <= xmax; cx += 1.0f) - { - const float w = bicubicCoeff(x - cx) * bicubicCoeff(y - cy); - sum = sum + w * src(__float2int_rd(cy), __float2int_rd(cx)); - wsum += w; - } - } - - work_type res = (!wsum)? VecTraits::all(0) : sum / wsum; - - return saturate_cast(res); - } - - Ptr2D src; - }; - // for integer scaling - template struct IntegerAreaFilter - { - typedef typename Ptr2D::elem_type elem_type; - typedef float index_type; - - explicit __host__ __device__ __forceinline__ IntegerAreaFilter(const Ptr2D& src_, float scale_x_, float scale_y_) - : src(src_), scale_x(scale_x_), scale_y(scale_y_), scale(1.f / (scale_x * scale_y)) {} - - __device__ __forceinline__ elem_type operator ()(float y, float x) const - { - float fsx1 = x * scale_x; - float fsx2 = fsx1 + scale_x; - - int sx1 = __float2int_ru(fsx1); - int sx2 = __float2int_rd(fsx2); - - float fsy1 = y * scale_y; - float fsy2 = fsy1 + scale_y; - - int sy1 = __float2int_ru(fsy1); - int sy2 = __float2int_rd(fsy2); - - typedef typename TypeVec::cn>::vec_type work_type; - work_type out = VecTraits::all(0.f); - - for(int dy = sy1; dy < sy2; ++dy) - for(int dx = sx1; dx < sx2; ++dx) - { - out = out + src(dy, dx) * scale; - } - - return saturate_cast(out); - } - - Ptr2D src; - float scale_x, scale_y ,scale; - }; - - template struct AreaFilter - { - typedef typename Ptr2D::elem_type elem_type; - typedef float index_type; - - explicit __host__ __device__ __forceinline__ AreaFilter(const Ptr2D& src_, float scale_x_, float scale_y_) - : src(src_), scale_x(scale_x_), scale_y(scale_y_){} - - __device__ __forceinline__ elem_type operator ()(float y, float x) const - { - float fsx1 = x * scale_x; - float fsx2 = fsx1 + scale_x; - - int sx1 = __float2int_ru(fsx1); - int sx2 = __float2int_rd(fsx2); - - float fsy1 = y * scale_y; - float fsy2 = fsy1 + scale_y; - - int sy1 = __float2int_ru(fsy1); - int sy2 = __float2int_rd(fsy2); - - float scale = 1.f / (fminf(scale_x, src.width - fsx1) * fminf(scale_y, src.height - fsy1)); - - typedef typename TypeVec::cn>::vec_type work_type; - work_type out = VecTraits::all(0.f); - - for (int dy = sy1; dy < sy2; ++dy) - { - for (int dx = sx1; dx < sx2; ++dx) - out = out + src(dy, dx) * scale; - - if (sx1 > fsx1) - out = out + src(dy, (sx1 -1) ) * ((sx1 - fsx1) * scale); - - if (sx2 < fsx2) - out = out + src(dy, sx2) * ((fsx2 -sx2) * scale); - } - - if (sy1 > fsy1) - for (int dx = sx1; dx < sx2; ++dx) - out = out + src( (sy1 - 1) , dx) * ((sy1 -fsy1) * scale); - - if (sy2 < fsy2) - for (int dx = sx1; dx < sx2; ++dx) - out = out + src(sy2, dx) * ((fsy2 -sy2) * scale); - - if ((sy1 > fsy1) && (sx1 > fsx1)) - out = out + src( (sy1 - 1) , (sx1 - 1)) * ((sy1 -fsy1) * (sx1 -fsx1) * scale); - - if ((sy1 > fsy1) && (sx2 < fsx2)) - out = out + src( (sy1 - 1) , sx2) * ((sy1 -fsy1) * (fsx2 -sx2) * scale); - - if ((sy2 < fsy2) && (sx2 < fsx2)) - out = out + src(sy2, sx2) * ((fsy2 -sy2) * (fsx2 -sx2) * scale); - - if ((sy2 < fsy2) && (sx1 > fsx1)) - out = out + src(sy2, (sx1 - 1)) * ((fsy2 -sy2) * (sx1 -fsx1) * scale); - - return saturate_cast(out); - } - - Ptr2D src; - float scale_x, scale_y; - int width, haight; - }; -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif // OPENCV_CUDA_FILTERS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_FILTERS_HPP +#define OPENCV_CUDA_FILTERS_HPP + +#include "saturate_cast.hpp" +#include "vec_traits.hpp" +#include "vec_math.hpp" +#include "type_traits.hpp" +#include "nppdefs.h" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + template struct PointFilter + { + typedef typename Ptr2D::elem_type elem_type; + typedef float index_type; + + explicit __host__ __device__ __forceinline__ PointFilter(const Ptr2D& src_, float fx = 0.f, float fy = 0.f) + : src(src_) + { + CV_UNUSED(fx); + CV_UNUSED(fy); + } + + __device__ __forceinline__ elem_type operator ()(float y, float x) const + { + return src(__float2int_rz(y), __float2int_rz(x)); + } + + Ptr2D src; + }; + + template struct LinearFilter + { + typedef typename Ptr2D::elem_type elem_type; + typedef float index_type; + + explicit __host__ __device__ __forceinline__ LinearFilter(const Ptr2D& src_, float fx = 0.f, float fy = 0.f) + : src(src_) + { + CV_UNUSED(fx); + CV_UNUSED(fy); + } + __device__ __forceinline__ elem_type operator ()(float y, float x) const + { + typedef typename TypeVec::cn>::vec_type work_type; + + work_type out = VecTraits::all(0); + + const int x1 = __float2int_rd(x); + const int y1 = __float2int_rd(y); + if (x1 <= NPP_MIN_32S || x1 >= NPP_MAX_32S || y1 <= NPP_MIN_32S || y1 >= NPP_MAX_32S) + { + elem_type src_reg = src(y1, x1); + out = out + src_reg * 1.0f; + return saturate_cast(out); + } + const int x2 = x1 + 1; + const int y2 = y1 + 1; + + elem_type src_reg = src(y1, x1); + out = out + src_reg * ((x2 - x) * (y2 - y)); + + src_reg = src(y1, x2); + out = out + src_reg * ((x - x1) * (y2 - y)); + + src_reg = src(y2, x1); + out = out + src_reg * ((x2 - x) * (y - y1)); + + src_reg = src(y2, x2); + out = out + src_reg * ((x - x1) * (y - y1)); + + return saturate_cast(out); + } + + Ptr2D src; + }; + + template struct CubicFilter + { + typedef typename Ptr2D::elem_type elem_type; + typedef float index_type; + typedef typename TypeVec::cn>::vec_type work_type; + + explicit __host__ __device__ __forceinline__ CubicFilter(const Ptr2D& src_, float fx = 0.f, float fy = 0.f) + : src(src_) + { + CV_UNUSED(fx); + CV_UNUSED(fy); + } + + static __device__ __forceinline__ float bicubicCoeff(float x_) + { + float x = fabsf(x_); + if (x <= 1.0f) + { + return x * x * (1.5f * x - 2.5f) + 1.0f; + } + else if (x < 2.0f) + { + return x * (x * (-0.5f * x + 2.5f) - 4.0f) + 2.0f; + } + else + { + return 0.0f; + } + } + + __device__ elem_type operator ()(float y, float x) const + { + const float xmin = ::ceilf(x - 2.0f); + const float xmax = ::floorf(x + 2.0f); + + const float ymin = ::ceilf(y - 2.0f); + const float ymax = ::floorf(y + 2.0f); + + work_type sum = VecTraits::all(0); + float wsum = 0.0f; + + for (float cy = ymin; cy <= ymax; cy += 1.0f) + { + for (float cx = xmin; cx <= xmax; cx += 1.0f) + { + const float w = bicubicCoeff(x - cx) * bicubicCoeff(y - cy); + sum = sum + w * src(__float2int_rd(cy), __float2int_rd(cx)); + wsum += w; + } + } + + work_type res = (!wsum)? VecTraits::all(0) : sum / wsum; + + return saturate_cast(res); + } + + Ptr2D src; + }; + // for integer scaling + template struct IntegerAreaFilter + { + typedef typename Ptr2D::elem_type elem_type; + typedef float index_type; + + explicit __host__ __device__ __forceinline__ IntegerAreaFilter(const Ptr2D& src_, float scale_x_, float scale_y_) + : src(src_), scale_x(scale_x_), scale_y(scale_y_), scale(1.f / (scale_x * scale_y)) {} + + __device__ __forceinline__ elem_type operator ()(float y, float x) const + { + float fsx1 = x * scale_x; + float fsx2 = fsx1 + scale_x; + + int sx1 = __float2int_ru(fsx1); + int sx2 = __float2int_rd(fsx2); + + float fsy1 = y * scale_y; + float fsy2 = fsy1 + scale_y; + + int sy1 = __float2int_ru(fsy1); + int sy2 = __float2int_rd(fsy2); + + typedef typename TypeVec::cn>::vec_type work_type; + work_type out = VecTraits::all(0.f); + + for(int dy = sy1; dy < sy2; ++dy) + for(int dx = sx1; dx < sx2; ++dx) + { + out = out + src(dy, dx) * scale; + } + + return saturate_cast(out); + } + + Ptr2D src; + float scale_x, scale_y ,scale; + }; + + template struct AreaFilter + { + typedef typename Ptr2D::elem_type elem_type; + typedef float index_type; + + explicit __host__ __device__ __forceinline__ AreaFilter(const Ptr2D& src_, float scale_x_, float scale_y_) + : src(src_), scale_x(scale_x_), scale_y(scale_y_){} + + __device__ __forceinline__ elem_type operator ()(float y, float x) const + { + float fsx1 = x * scale_x; + float fsx2 = fsx1 + scale_x; + + int sx1 = __float2int_ru(fsx1); + int sx2 = __float2int_rd(fsx2); + + float fsy1 = y * scale_y; + float fsy2 = fsy1 + scale_y; + + int sy1 = __float2int_ru(fsy1); + int sy2 = __float2int_rd(fsy2); + + float scale = 1.f / (fminf(scale_x, src.width - fsx1) * fminf(scale_y, src.height - fsy1)); + + typedef typename TypeVec::cn>::vec_type work_type; + work_type out = VecTraits::all(0.f); + + for (int dy = sy1; dy < sy2; ++dy) + { + for (int dx = sx1; dx < sx2; ++dx) + out = out + src(dy, dx) * scale; + + if (sx1 > fsx1) + out = out + src(dy, (sx1 -1) ) * ((sx1 - fsx1) * scale); + + if (sx2 < fsx2) + out = out + src(dy, sx2) * ((fsx2 -sx2) * scale); + } + + if (sy1 > fsy1) + for (int dx = sx1; dx < sx2; ++dx) + out = out + src( (sy1 - 1) , dx) * ((sy1 -fsy1) * scale); + + if (sy2 < fsy2) + for (int dx = sx1; dx < sx2; ++dx) + out = out + src(sy2, dx) * ((fsy2 -sy2) * scale); + + if ((sy1 > fsy1) && (sx1 > fsx1)) + out = out + src( (sy1 - 1) , (sx1 - 1)) * ((sy1 -fsy1) * (sx1 -fsx1) * scale); + + if ((sy1 > fsy1) && (sx2 < fsx2)) + out = out + src( (sy1 - 1) , sx2) * ((sy1 -fsy1) * (fsx2 -sx2) * scale); + + if ((sy2 < fsy2) && (sx2 < fsx2)) + out = out + src(sy2, sx2) * ((fsy2 -sy2) * (fsx2 -sx2) * scale); + + if ((sy2 < fsy2) && (sx1 > fsx1)) + out = out + src(sy2, (sx1 - 1)) * ((fsy2 -sy2) * (sx1 -fsx1) * scale); + + return saturate_cast(out); + } + + Ptr2D src; + float scale_x, scale_y; + int width, haight; + }; +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif // OPENCV_CUDA_FILTERS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/funcattrib.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/funcattrib.hpp index f582080488..6a01132d1e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/funcattrib.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/funcattrib.hpp @@ -1,79 +1,79 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_DEVICE_FUNCATTRIB_HPP -#define OPENCV_CUDA_DEVICE_FUNCATTRIB_HPP - -#include - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - template - void printFuncAttrib(Func& func) - { - - cudaFuncAttributes attrs; - cudaFuncGetAttributes(&attrs, func); - - printf("=== Function stats ===\n"); - printf("Name: \n"); - printf("sharedSizeBytes = %d\n", attrs.sharedSizeBytes); - printf("constSizeBytes = %d\n", attrs.constSizeBytes); - printf("localSizeBytes = %d\n", attrs.localSizeBytes); - printf("maxThreadsPerBlock = %d\n", attrs.maxThreadsPerBlock); - printf("numRegs = %d\n", attrs.numRegs); - printf("ptxVersion = %d\n", attrs.ptxVersion); - printf("binaryVersion = %d\n", attrs.binaryVersion); - printf("\n"); - fflush(stdout); - } -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif /* OPENCV_CUDA_DEVICE_FUNCATTRIB_HPP */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_DEVICE_FUNCATTRIB_HPP +#define OPENCV_CUDA_DEVICE_FUNCATTRIB_HPP + +#include + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + template + void printFuncAttrib(Func& func) + { + + cudaFuncAttributes attrs; + cudaFuncGetAttributes(&attrs, func); + + printf("=== Function stats ===\n"); + printf("Name: \n"); + printf("sharedSizeBytes = %d\n", attrs.sharedSizeBytes); + printf("constSizeBytes = %d\n", attrs.constSizeBytes); + printf("localSizeBytes = %d\n", attrs.localSizeBytes); + printf("maxThreadsPerBlock = %d\n", attrs.maxThreadsPerBlock); + printf("numRegs = %d\n", attrs.numRegs); + printf("ptxVersion = %d\n", attrs.ptxVersion); + printf("binaryVersion = %d\n", attrs.binaryVersion); + printf("\n"); + fflush(stdout); + } +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif /* OPENCV_CUDA_DEVICE_FUNCATTRIB_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/functional.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/functional.hpp index 9f53d87527..213f10c1bd 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/functional.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/functional.hpp @@ -1,805 +1,805 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_FUNCTIONAL_HPP -#define OPENCV_CUDA_FUNCTIONAL_HPP - -#include -#include "saturate_cast.hpp" -#include "vec_traits.hpp" -#include "type_traits.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - // Function Objects - template struct unary_function - { - typedef Argument argument_type; - typedef Result result_type; - }; - template struct binary_function - { - typedef Argument1 first_argument_type; - typedef Argument2 second_argument_type; - typedef Result result_type; - }; - - // Arithmetic Operations - template struct plus : binary_function - { - __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a + b; - } - __host__ __device__ __forceinline__ plus() {} - __host__ __device__ __forceinline__ plus(const plus&) {} - }; - - template struct minus : binary_function - { - __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a - b; - } - __host__ __device__ __forceinline__ minus() {} - __host__ __device__ __forceinline__ minus(const minus&) {} - }; - - template struct multiplies : binary_function - { - __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a * b; - } - __host__ __device__ __forceinline__ multiplies() {} - __host__ __device__ __forceinline__ multiplies(const multiplies&) {} - }; - - template struct divides : binary_function - { - __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a / b; - } - __host__ __device__ __forceinline__ divides() {} - __host__ __device__ __forceinline__ divides(const divides&) {} - }; - - template struct modulus : binary_function - { - __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a % b; - } - __host__ __device__ __forceinline__ modulus() {} - __host__ __device__ __forceinline__ modulus(const modulus&) {} - }; - - template struct negate : unary_function - { - __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a) const - { - return -a; - } - __host__ __device__ __forceinline__ negate() {} - __host__ __device__ __forceinline__ negate(const negate&) {} - }; - - // Comparison Operations - template struct equal_to : binary_function - { - __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a == b; - } - __host__ __device__ __forceinline__ equal_to() {} - __host__ __device__ __forceinline__ equal_to(const equal_to&) {} - }; - - template struct not_equal_to : binary_function - { - __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a != b; - } - __host__ __device__ __forceinline__ not_equal_to() {} - __host__ __device__ __forceinline__ not_equal_to(const not_equal_to&) {} - }; - - template struct greater : binary_function - { - __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a > b; - } - __host__ __device__ __forceinline__ greater() {} - __host__ __device__ __forceinline__ greater(const greater&) {} - }; - - template struct less : binary_function - { - __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a < b; - } - __host__ __device__ __forceinline__ less() {} - __host__ __device__ __forceinline__ less(const less&) {} - }; - - template struct greater_equal : binary_function - { - __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a >= b; - } - __host__ __device__ __forceinline__ greater_equal() {} - __host__ __device__ __forceinline__ greater_equal(const greater_equal&) {} - }; - - template struct less_equal : binary_function - { - __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a <= b; - } - __host__ __device__ __forceinline__ less_equal() {} - __host__ __device__ __forceinline__ less_equal(const less_equal&) {} - }; - - // Logical Operations - template struct logical_and : binary_function - { - __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a && b; - } - __host__ __device__ __forceinline__ logical_and() {} - __host__ __device__ __forceinline__ logical_and(const logical_and&) {} - }; - - template struct logical_or : binary_function - { - __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a || b; - } - __host__ __device__ __forceinline__ logical_or() {} - __host__ __device__ __forceinline__ logical_or(const logical_or&) {} - }; - - template struct logical_not : unary_function - { - __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a) const - { - return !a; - } - __host__ __device__ __forceinline__ logical_not() {} - __host__ __device__ __forceinline__ logical_not(const logical_not&) {} - }; - - // Bitwise Operations - template struct bit_and : binary_function - { - __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a & b; - } - __host__ __device__ __forceinline__ bit_and() {} - __host__ __device__ __forceinline__ bit_and(const bit_and&) {} - }; - - template struct bit_or : binary_function - { - __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a | b; - } - __host__ __device__ __forceinline__ bit_or() {} - __host__ __device__ __forceinline__ bit_or(const bit_or&) {} - }; - - template struct bit_xor : binary_function - { - __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a ^ b; - } - __host__ __device__ __forceinline__ bit_xor() {} - __host__ __device__ __forceinline__ bit_xor(const bit_xor&) {} - }; - - template struct bit_not : unary_function - { - __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType v) const - { - return ~v; - } - __host__ __device__ __forceinline__ bit_not() {} - __host__ __device__ __forceinline__ bit_not(const bit_not&) {} - }; - - // Generalized Identity Operations - template struct identity : unary_function - { - __device__ __forceinline__ typename TypeTraits::ParameterType operator()(typename TypeTraits::ParameterType x) const - { - return x; - } - __host__ __device__ __forceinline__ identity() {} - __host__ __device__ __forceinline__ identity(const identity&) {} - }; - - template struct project1st : binary_function - { - __device__ __forceinline__ typename TypeTraits::ParameterType operator()(typename TypeTraits::ParameterType lhs, typename TypeTraits::ParameterType rhs) const - { - return lhs; - } - __host__ __device__ __forceinline__ project1st() {} - __host__ __device__ __forceinline__ project1st(const project1st&) {} - }; - - template struct project2nd : binary_function - { - __device__ __forceinline__ typename TypeTraits::ParameterType operator()(typename TypeTraits::ParameterType lhs, typename TypeTraits::ParameterType rhs) const - { - return rhs; - } - __host__ __device__ __forceinline__ project2nd() {} - __host__ __device__ __forceinline__ project2nd(const project2nd&) {} - }; - - // Min/Max Operations - -#define OPENCV_CUDA_IMPLEMENT_MINMAX(name, type, op) \ - template <> struct name : binary_function \ - { \ - __device__ __forceinline__ type operator()(type lhs, type rhs) const {return op(lhs, rhs);} \ - __host__ __device__ __forceinline__ name() {}\ - __host__ __device__ __forceinline__ name(const name&) {}\ - }; - - template struct maximum : binary_function - { - __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType lhs, typename TypeTraits::ParameterType rhs) const - { - return max(lhs, rhs); - } - __host__ __device__ __forceinline__ maximum() {} - __host__ __device__ __forceinline__ maximum(const maximum&) {} - }; - - OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, uchar, ::max) - OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, schar, ::max) - OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, char, ::max) - OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, ushort, ::max) - OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, short, ::max) - OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, int, ::max) - OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, uint, ::max) - OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, float, ::fmax) - OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, double, ::fmax) - - template struct minimum : binary_function - { - __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType lhs, typename TypeTraits::ParameterType rhs) const - { - return min(lhs, rhs); - } - __host__ __device__ __forceinline__ minimum() {} - __host__ __device__ __forceinline__ minimum(const minimum&) {} - }; - - OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, uchar, ::min) - OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, schar, ::min) - OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, char, ::min) - OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, ushort, ::min) - OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, short, ::min) - OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, int, ::min) - OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, uint, ::min) - OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, float, ::fmin) - OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, double, ::fmin) - -#undef OPENCV_CUDA_IMPLEMENT_MINMAX - - // Math functions - - template struct abs_func : unary_function - { - __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType x) const - { - return abs(x); - } - - __host__ __device__ __forceinline__ abs_func() {} - __host__ __device__ __forceinline__ abs_func(const abs_func&) {} - }; - template <> struct abs_func : unary_function - { - __device__ __forceinline__ unsigned char operator ()(unsigned char x) const - { - return x; - } - - __host__ __device__ __forceinline__ abs_func() {} - __host__ __device__ __forceinline__ abs_func(const abs_func&) {} - }; - template <> struct abs_func : unary_function - { - __device__ __forceinline__ signed char operator ()(signed char x) const - { - return ::abs((int)x); - } - - __host__ __device__ __forceinline__ abs_func() {} - __host__ __device__ __forceinline__ abs_func(const abs_func&) {} - }; - template <> struct abs_func : unary_function - { - __device__ __forceinline__ char operator ()(char x) const - { - return ::abs((int)x); - } - - __host__ __device__ __forceinline__ abs_func() {} - __host__ __device__ __forceinline__ abs_func(const abs_func&) {} - }; - template <> struct abs_func : unary_function - { - __device__ __forceinline__ unsigned short operator ()(unsigned short x) const - { - return x; - } - - __host__ __device__ __forceinline__ abs_func() {} - __host__ __device__ __forceinline__ abs_func(const abs_func&) {} - }; - template <> struct abs_func : unary_function - { - __device__ __forceinline__ short operator ()(short x) const - { - return ::abs((int)x); - } - - __host__ __device__ __forceinline__ abs_func() {} - __host__ __device__ __forceinline__ abs_func(const abs_func&) {} - }; - template <> struct abs_func : unary_function - { - __device__ __forceinline__ unsigned int operator ()(unsigned int x) const - { - return x; - } - - __host__ __device__ __forceinline__ abs_func() {} - __host__ __device__ __forceinline__ abs_func(const abs_func&) {} - }; - template <> struct abs_func : unary_function - { - __device__ __forceinline__ int operator ()(int x) const - { - return ::abs(x); - } - - __host__ __device__ __forceinline__ abs_func() {} - __host__ __device__ __forceinline__ abs_func(const abs_func&) {} - }; - template <> struct abs_func : unary_function - { - __device__ __forceinline__ float operator ()(float x) const - { - return ::fabsf(x); - } - - __host__ __device__ __forceinline__ abs_func() {} - __host__ __device__ __forceinline__ abs_func(const abs_func&) {} - }; - template <> struct abs_func : unary_function - { - __device__ __forceinline__ double operator ()(double x) const - { - return ::fabs(x); - } - - __host__ __device__ __forceinline__ abs_func() {} - __host__ __device__ __forceinline__ abs_func(const abs_func&) {} - }; - -#define OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(name, func) \ - template struct name ## _func : unary_function \ - { \ - __device__ __forceinline__ float operator ()(typename TypeTraits::ParameterType v) const \ - { \ - return func ## f(v); \ - } \ - __host__ __device__ __forceinline__ name ## _func() {} \ - __host__ __device__ __forceinline__ name ## _func(const name ## _func&) {} \ - }; \ - template <> struct name ## _func : unary_function \ - { \ - __device__ __forceinline__ double operator ()(double v) const \ - { \ - return func(v); \ - } \ - __host__ __device__ __forceinline__ name ## _func() {} \ - __host__ __device__ __forceinline__ name ## _func(const name ## _func&) {} \ - }; - -#define OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR(name, func) \ - template struct name ## _func : binary_function \ - { \ - __device__ __forceinline__ float operator ()(typename TypeTraits::ParameterType v1, typename TypeTraits::ParameterType v2) const \ - { \ - return func ## f(v1, v2); \ - } \ - __host__ __device__ __forceinline__ name ## _func() {} \ - __host__ __device__ __forceinline__ name ## _func(const name ## _func&) {} \ - }; \ - template <> struct name ## _func : binary_function \ - { \ - __device__ __forceinline__ double operator ()(double v1, double v2) const \ - { \ - return func(v1, v2); \ - } \ - __host__ __device__ __forceinline__ name ## _func() {} \ - __host__ __device__ __forceinline__ name ## _func(const name ## _func&) {} \ - }; - - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(sqrt, ::sqrt) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(exp, ::exp) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(exp2, ::exp2) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(exp10, ::exp10) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(log, ::log) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(log2, ::log2) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(log10, ::log10) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(sin, ::sin) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(cos, ::cos) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(tan, ::tan) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(asin, ::asin) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(acos, ::acos) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(atan, ::atan) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(sinh, ::sinh) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(cosh, ::cosh) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(tanh, ::tanh) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(asinh, ::asinh) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(acosh, ::acosh) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(atanh, ::atanh) - - OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR(hypot, ::hypot) - OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR(atan2, ::atan2) - OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR(pow, ::pow) - - #undef OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR - #undef OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR_NO_DOUBLE - #undef OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR - - template struct hypot_sqr_func : binary_function - { - __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType src1, typename TypeTraits::ParameterType src2) const - { - return src1 * src1 + src2 * src2; - } - __host__ __device__ __forceinline__ hypot_sqr_func() {} - __host__ __device__ __forceinline__ hypot_sqr_func(const hypot_sqr_func&) {} - }; - - // Saturate Cast Functor - template struct saturate_cast_func : unary_function - { - __device__ __forceinline__ D operator ()(typename TypeTraits::ParameterType v) const - { - return saturate_cast(v); - } - __host__ __device__ __forceinline__ saturate_cast_func() {} - __host__ __device__ __forceinline__ saturate_cast_func(const saturate_cast_func&) {} - }; - - // Threshold Functors - template struct thresh_binary_func : unary_function - { - __host__ __device__ __forceinline__ thresh_binary_func(T thresh_, T maxVal_) : thresh(thresh_), maxVal(maxVal_) {} - - __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const - { - return (src > thresh) * maxVal; - } - - __host__ __device__ __forceinline__ thresh_binary_func() {} - __host__ __device__ __forceinline__ thresh_binary_func(const thresh_binary_func& other) - : thresh(other.thresh), maxVal(other.maxVal) {} - - T thresh; - T maxVal; - }; - - template struct thresh_binary_inv_func : unary_function - { - __host__ __device__ __forceinline__ thresh_binary_inv_func(T thresh_, T maxVal_) : thresh(thresh_), maxVal(maxVal_) {} - - __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const - { - return (src <= thresh) * maxVal; - } - - __host__ __device__ __forceinline__ thresh_binary_inv_func() {} - __host__ __device__ __forceinline__ thresh_binary_inv_func(const thresh_binary_inv_func& other) - : thresh(other.thresh), maxVal(other.maxVal) {} - - T thresh; - T maxVal; - }; - - template struct thresh_trunc_func : unary_function - { - explicit __host__ __device__ __forceinline__ thresh_trunc_func(T thresh_, T maxVal_ = 0) : thresh(thresh_) {CV_UNUSED(maxVal_);} - - __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const - { - return minimum()(src, thresh); - } - - __host__ __device__ __forceinline__ thresh_trunc_func() {} - __host__ __device__ __forceinline__ thresh_trunc_func(const thresh_trunc_func& other) - : thresh(other.thresh) {} - - T thresh; - }; - - template struct thresh_to_zero_func : unary_function - { - explicit __host__ __device__ __forceinline__ thresh_to_zero_func(T thresh_, T maxVal_ = 0) : thresh(thresh_) {CV_UNUSED(maxVal_);} - - __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const - { - return (src > thresh) * src; - } - - __host__ __device__ __forceinline__ thresh_to_zero_func() {} - __host__ __device__ __forceinline__ thresh_to_zero_func(const thresh_to_zero_func& other) - : thresh(other.thresh) {} - - T thresh; - }; - - template struct thresh_to_zero_inv_func : unary_function - { - explicit __host__ __device__ __forceinline__ thresh_to_zero_inv_func(T thresh_, T maxVal_ = 0) : thresh(thresh_) {CV_UNUSED(maxVal_);} - - __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const - { - return (src <= thresh) * src; - } - - __host__ __device__ __forceinline__ thresh_to_zero_inv_func() {} - __host__ __device__ __forceinline__ thresh_to_zero_inv_func(const thresh_to_zero_inv_func& other) - : thresh(other.thresh) {} - - T thresh; - }; - - // Function Object Adaptors - template struct unary_negate : unary_function - { - explicit __host__ __device__ __forceinline__ unary_negate(const Predicate& p) : pred(p) {} - - __device__ __forceinline__ bool operator()(typename TypeTraits::ParameterType x) const - { - return !pred(x); - } - - __host__ __device__ __forceinline__ unary_negate() {} - __host__ __device__ __forceinline__ unary_negate(const unary_negate& other) : pred(other.pred) {} - - Predicate pred; - }; - - template __host__ __device__ __forceinline__ unary_negate not1(const Predicate& pred) - { - return unary_negate(pred); - } - - template struct binary_negate : binary_function - { - explicit __host__ __device__ __forceinline__ binary_negate(const Predicate& p) : pred(p) {} - - __device__ __forceinline__ bool operator()(typename TypeTraits::ParameterType x, - typename TypeTraits::ParameterType y) const - { - return !pred(x,y); - } - - __host__ __device__ __forceinline__ binary_negate() {} - __host__ __device__ __forceinline__ binary_negate(const binary_negate& other) : pred(other.pred) {} - - Predicate pred; - }; - - template __host__ __device__ __forceinline__ binary_negate not2(const BinaryPredicate& pred) - { - return binary_negate(pred); - } - - template struct binder1st : unary_function - { - __host__ __device__ __forceinline__ binder1st(const Op& op_, const typename Op::first_argument_type& arg1_) : op(op_), arg1(arg1_) {} - - __device__ __forceinline__ typename Op::result_type operator ()(typename TypeTraits::ParameterType a) const - { - return op(arg1, a); - } - - __host__ __device__ __forceinline__ binder1st() {} - __host__ __device__ __forceinline__ binder1st(const binder1st& other) : op(other.op), arg1(other.arg1) {} - - Op op; - typename Op::first_argument_type arg1; - }; - - template __host__ __device__ __forceinline__ binder1st bind1st(const Op& op, const T& x) - { - return binder1st(op, typename Op::first_argument_type(x)); - } - - template struct binder2nd : unary_function - { - __host__ __device__ __forceinline__ binder2nd(const Op& op_, const typename Op::second_argument_type& arg2_) : op(op_), arg2(arg2_) {} - - __forceinline__ __device__ typename Op::result_type operator ()(typename TypeTraits::ParameterType a) const - { - return op(a, arg2); - } - - __host__ __device__ __forceinline__ binder2nd() {} - __host__ __device__ __forceinline__ binder2nd(const binder2nd& other) : op(other.op), arg2(other.arg2) {} - - Op op; - typename Op::second_argument_type arg2; - }; - - template __host__ __device__ __forceinline__ binder2nd bind2nd(const Op& op, const T& x) - { - return binder2nd(op, typename Op::second_argument_type(x)); - } - - // Functor Traits - template struct IsUnaryFunction - { - typedef char Yes; - struct No {Yes a[2];}; - - template static Yes check(unary_function); - static No check(...); - - static F makeF(); - - enum { value = (sizeof(check(makeF())) == sizeof(Yes)) }; - }; - - template struct IsBinaryFunction - { - typedef char Yes; - struct No {Yes a[2];}; - - template static Yes check(binary_function); - static No check(...); - - static F makeF(); - - enum { value = (sizeof(check(makeF())) == sizeof(Yes)) }; - }; - - namespace functional_detail - { - template struct UnOpShift { enum { shift = 1 }; }; - template struct UnOpShift { enum { shift = 4 }; }; - template struct UnOpShift { enum { shift = 2 }; }; - - template struct DefaultUnaryShift - { - enum { shift = UnOpShift::shift }; - }; - - template struct BinOpShift { enum { shift = 1 }; }; - template struct BinOpShift { enum { shift = 4 }; }; - template struct BinOpShift { enum { shift = 2 }; }; - - template struct DefaultBinaryShift - { - enum { shift = BinOpShift::shift }; - }; - - template ::value> struct ShiftDispatcher; - template struct ShiftDispatcher - { - enum { shift = DefaultUnaryShift::shift }; - }; - template struct ShiftDispatcher - { - enum { shift = DefaultBinaryShift::shift }; - }; - } - - template struct DefaultTransformShift - { - enum { shift = functional_detail::ShiftDispatcher::shift }; - }; - - template struct DefaultTransformFunctorTraits - { - enum { simple_block_dim_x = 16 }; - enum { simple_block_dim_y = 16 }; - - enum { smart_block_dim_x = 16 }; - enum { smart_block_dim_y = 16 }; - enum { smart_shift = DefaultTransformShift::shift }; - }; - - template struct TransformFunctorTraits : DefaultTransformFunctorTraits {}; - -#define OPENCV_CUDA_TRANSFORM_FUNCTOR_TRAITS(type) \ - template <> struct TransformFunctorTraits< type > : DefaultTransformFunctorTraits< type > -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif // OPENCV_CUDA_FUNCTIONAL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_FUNCTIONAL_HPP +#define OPENCV_CUDA_FUNCTIONAL_HPP + +#include +#include "saturate_cast.hpp" +#include "vec_traits.hpp" +#include "type_traits.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + // Function Objects + template struct unary_function + { + typedef Argument argument_type; + typedef Result result_type; + }; + template struct binary_function + { + typedef Argument1 first_argument_type; + typedef Argument2 second_argument_type; + typedef Result result_type; + }; + + // Arithmetic Operations + template struct plus : binary_function + { + __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a + b; + } + __host__ __device__ __forceinline__ plus() {} + __host__ __device__ __forceinline__ plus(const plus&) {} + }; + + template struct minus : binary_function + { + __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a - b; + } + __host__ __device__ __forceinline__ minus() {} + __host__ __device__ __forceinline__ minus(const minus&) {} + }; + + template struct multiplies : binary_function + { + __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a * b; + } + __host__ __device__ __forceinline__ multiplies() {} + __host__ __device__ __forceinline__ multiplies(const multiplies&) {} + }; + + template struct divides : binary_function + { + __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a / b; + } + __host__ __device__ __forceinline__ divides() {} + __host__ __device__ __forceinline__ divides(const divides&) {} + }; + + template struct modulus : binary_function + { + __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a % b; + } + __host__ __device__ __forceinline__ modulus() {} + __host__ __device__ __forceinline__ modulus(const modulus&) {} + }; + + template struct negate : unary_function + { + __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a) const + { + return -a; + } + __host__ __device__ __forceinline__ negate() {} + __host__ __device__ __forceinline__ negate(const negate&) {} + }; + + // Comparison Operations + template struct equal_to : binary_function + { + __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a == b; + } + __host__ __device__ __forceinline__ equal_to() {} + __host__ __device__ __forceinline__ equal_to(const equal_to&) {} + }; + + template struct not_equal_to : binary_function + { + __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a != b; + } + __host__ __device__ __forceinline__ not_equal_to() {} + __host__ __device__ __forceinline__ not_equal_to(const not_equal_to&) {} + }; + + template struct greater : binary_function + { + __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a > b; + } + __host__ __device__ __forceinline__ greater() {} + __host__ __device__ __forceinline__ greater(const greater&) {} + }; + + template struct less : binary_function + { + __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a < b; + } + __host__ __device__ __forceinline__ less() {} + __host__ __device__ __forceinline__ less(const less&) {} + }; + + template struct greater_equal : binary_function + { + __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a >= b; + } + __host__ __device__ __forceinline__ greater_equal() {} + __host__ __device__ __forceinline__ greater_equal(const greater_equal&) {} + }; + + template struct less_equal : binary_function + { + __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a <= b; + } + __host__ __device__ __forceinline__ less_equal() {} + __host__ __device__ __forceinline__ less_equal(const less_equal&) {} + }; + + // Logical Operations + template struct logical_and : binary_function + { + __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a && b; + } + __host__ __device__ __forceinline__ logical_and() {} + __host__ __device__ __forceinline__ logical_and(const logical_and&) {} + }; + + template struct logical_or : binary_function + { + __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a || b; + } + __host__ __device__ __forceinline__ logical_or() {} + __host__ __device__ __forceinline__ logical_or(const logical_or&) {} + }; + + template struct logical_not : unary_function + { + __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a) const + { + return !a; + } + __host__ __device__ __forceinline__ logical_not() {} + __host__ __device__ __forceinline__ logical_not(const logical_not&) {} + }; + + // Bitwise Operations + template struct bit_and : binary_function + { + __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a & b; + } + __host__ __device__ __forceinline__ bit_and() {} + __host__ __device__ __forceinline__ bit_and(const bit_and&) {} + }; + + template struct bit_or : binary_function + { + __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a | b; + } + __host__ __device__ __forceinline__ bit_or() {} + __host__ __device__ __forceinline__ bit_or(const bit_or&) {} + }; + + template struct bit_xor : binary_function + { + __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a ^ b; + } + __host__ __device__ __forceinline__ bit_xor() {} + __host__ __device__ __forceinline__ bit_xor(const bit_xor&) {} + }; + + template struct bit_not : unary_function + { + __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType v) const + { + return ~v; + } + __host__ __device__ __forceinline__ bit_not() {} + __host__ __device__ __forceinline__ bit_not(const bit_not&) {} + }; + + // Generalized Identity Operations + template struct identity : unary_function + { + __device__ __forceinline__ typename TypeTraits::ParameterType operator()(typename TypeTraits::ParameterType x) const + { + return x; + } + __host__ __device__ __forceinline__ identity() {} + __host__ __device__ __forceinline__ identity(const identity&) {} + }; + + template struct project1st : binary_function + { + __device__ __forceinline__ typename TypeTraits::ParameterType operator()(typename TypeTraits::ParameterType lhs, typename TypeTraits::ParameterType rhs) const + { + return lhs; + } + __host__ __device__ __forceinline__ project1st() {} + __host__ __device__ __forceinline__ project1st(const project1st&) {} + }; + + template struct project2nd : binary_function + { + __device__ __forceinline__ typename TypeTraits::ParameterType operator()(typename TypeTraits::ParameterType lhs, typename TypeTraits::ParameterType rhs) const + { + return rhs; + } + __host__ __device__ __forceinline__ project2nd() {} + __host__ __device__ __forceinline__ project2nd(const project2nd&) {} + }; + + // Min/Max Operations + +#define OPENCV_CUDA_IMPLEMENT_MINMAX(name, type, op) \ + template <> struct name : binary_function \ + { \ + __device__ __forceinline__ type operator()(type lhs, type rhs) const {return op(lhs, rhs);} \ + __host__ __device__ __forceinline__ name() {}\ + __host__ __device__ __forceinline__ name(const name&) {}\ + }; + + template struct maximum : binary_function + { + __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType lhs, typename TypeTraits::ParameterType rhs) const + { + return max(lhs, rhs); + } + __host__ __device__ __forceinline__ maximum() {} + __host__ __device__ __forceinline__ maximum(const maximum&) {} + }; + + OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, uchar, ::max) + OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, schar, ::max) + OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, char, ::max) + OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, ushort, ::max) + OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, short, ::max) + OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, int, ::max) + OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, uint, ::max) + OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, float, ::fmax) + OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, double, ::fmax) + + template struct minimum : binary_function + { + __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType lhs, typename TypeTraits::ParameterType rhs) const + { + return min(lhs, rhs); + } + __host__ __device__ __forceinline__ minimum() {} + __host__ __device__ __forceinline__ minimum(const minimum&) {} + }; + + OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, uchar, ::min) + OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, schar, ::min) + OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, char, ::min) + OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, ushort, ::min) + OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, short, ::min) + OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, int, ::min) + OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, uint, ::min) + OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, float, ::fmin) + OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, double, ::fmin) + +#undef OPENCV_CUDA_IMPLEMENT_MINMAX + + // Math functions + + template struct abs_func : unary_function + { + __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType x) const + { + return abs(x); + } + + __host__ __device__ __forceinline__ abs_func() {} + __host__ __device__ __forceinline__ abs_func(const abs_func&) {} + }; + template <> struct abs_func : unary_function + { + __device__ __forceinline__ unsigned char operator ()(unsigned char x) const + { + return x; + } + + __host__ __device__ __forceinline__ abs_func() {} + __host__ __device__ __forceinline__ abs_func(const abs_func&) {} + }; + template <> struct abs_func : unary_function + { + __device__ __forceinline__ signed char operator ()(signed char x) const + { + return ::abs((int)x); + } + + __host__ __device__ __forceinline__ abs_func() {} + __host__ __device__ __forceinline__ abs_func(const abs_func&) {} + }; + template <> struct abs_func : unary_function + { + __device__ __forceinline__ char operator ()(char x) const + { + return ::abs((int)x); + } + + __host__ __device__ __forceinline__ abs_func() {} + __host__ __device__ __forceinline__ abs_func(const abs_func&) {} + }; + template <> struct abs_func : unary_function + { + __device__ __forceinline__ unsigned short operator ()(unsigned short x) const + { + return x; + } + + __host__ __device__ __forceinline__ abs_func() {} + __host__ __device__ __forceinline__ abs_func(const abs_func&) {} + }; + template <> struct abs_func : unary_function + { + __device__ __forceinline__ short operator ()(short x) const + { + return ::abs((int)x); + } + + __host__ __device__ __forceinline__ abs_func() {} + __host__ __device__ __forceinline__ abs_func(const abs_func&) {} + }; + template <> struct abs_func : unary_function + { + __device__ __forceinline__ unsigned int operator ()(unsigned int x) const + { + return x; + } + + __host__ __device__ __forceinline__ abs_func() {} + __host__ __device__ __forceinline__ abs_func(const abs_func&) {} + }; + template <> struct abs_func : unary_function + { + __device__ __forceinline__ int operator ()(int x) const + { + return ::abs(x); + } + + __host__ __device__ __forceinline__ abs_func() {} + __host__ __device__ __forceinline__ abs_func(const abs_func&) {} + }; + template <> struct abs_func : unary_function + { + __device__ __forceinline__ float operator ()(float x) const + { + return ::fabsf(x); + } + + __host__ __device__ __forceinline__ abs_func() {} + __host__ __device__ __forceinline__ abs_func(const abs_func&) {} + }; + template <> struct abs_func : unary_function + { + __device__ __forceinline__ double operator ()(double x) const + { + return ::fabs(x); + } + + __host__ __device__ __forceinline__ abs_func() {} + __host__ __device__ __forceinline__ abs_func(const abs_func&) {} + }; + +#define OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(name, func) \ + template struct name ## _func : unary_function \ + { \ + __device__ __forceinline__ float operator ()(typename TypeTraits::ParameterType v) const \ + { \ + return func ## f(v); \ + } \ + __host__ __device__ __forceinline__ name ## _func() {} \ + __host__ __device__ __forceinline__ name ## _func(const name ## _func&) {} \ + }; \ + template <> struct name ## _func : unary_function \ + { \ + __device__ __forceinline__ double operator ()(double v) const \ + { \ + return func(v); \ + } \ + __host__ __device__ __forceinline__ name ## _func() {} \ + __host__ __device__ __forceinline__ name ## _func(const name ## _func&) {} \ + }; + +#define OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR(name, func) \ + template struct name ## _func : binary_function \ + { \ + __device__ __forceinline__ float operator ()(typename TypeTraits::ParameterType v1, typename TypeTraits::ParameterType v2) const \ + { \ + return func ## f(v1, v2); \ + } \ + __host__ __device__ __forceinline__ name ## _func() {} \ + __host__ __device__ __forceinline__ name ## _func(const name ## _func&) {} \ + }; \ + template <> struct name ## _func : binary_function \ + { \ + __device__ __forceinline__ double operator ()(double v1, double v2) const \ + { \ + return func(v1, v2); \ + } \ + __host__ __device__ __forceinline__ name ## _func() {} \ + __host__ __device__ __forceinline__ name ## _func(const name ## _func&) {} \ + }; + + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(sqrt, ::sqrt) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(exp, ::exp) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(exp2, ::exp2) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(exp10, ::exp10) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(log, ::log) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(log2, ::log2) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(log10, ::log10) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(sin, ::sin) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(cos, ::cos) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(tan, ::tan) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(asin, ::asin) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(acos, ::acos) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(atan, ::atan) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(sinh, ::sinh) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(cosh, ::cosh) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(tanh, ::tanh) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(asinh, ::asinh) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(acosh, ::acosh) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(atanh, ::atanh) + + OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR(hypot, ::hypot) + OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR(atan2, ::atan2) + OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR(pow, ::pow) + + #undef OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR + #undef OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR_NO_DOUBLE + #undef OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR + + template struct hypot_sqr_func : binary_function + { + __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType src1, typename TypeTraits::ParameterType src2) const + { + return src1 * src1 + src2 * src2; + } + __host__ __device__ __forceinline__ hypot_sqr_func() {} + __host__ __device__ __forceinline__ hypot_sqr_func(const hypot_sqr_func&) {} + }; + + // Saturate Cast Functor + template struct saturate_cast_func : unary_function + { + __device__ __forceinline__ D operator ()(typename TypeTraits::ParameterType v) const + { + return saturate_cast(v); + } + __host__ __device__ __forceinline__ saturate_cast_func() {} + __host__ __device__ __forceinline__ saturate_cast_func(const saturate_cast_func&) {} + }; + + // Threshold Functors + template struct thresh_binary_func : unary_function + { + __host__ __device__ __forceinline__ thresh_binary_func(T thresh_, T maxVal_) : thresh(thresh_), maxVal(maxVal_) {} + + __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const + { + return (src > thresh) * maxVal; + } + + __host__ __device__ __forceinline__ thresh_binary_func() {} + __host__ __device__ __forceinline__ thresh_binary_func(const thresh_binary_func& other) + : thresh(other.thresh), maxVal(other.maxVal) {} + + T thresh; + T maxVal; + }; + + template struct thresh_binary_inv_func : unary_function + { + __host__ __device__ __forceinline__ thresh_binary_inv_func(T thresh_, T maxVal_) : thresh(thresh_), maxVal(maxVal_) {} + + __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const + { + return (src <= thresh) * maxVal; + } + + __host__ __device__ __forceinline__ thresh_binary_inv_func() {} + __host__ __device__ __forceinline__ thresh_binary_inv_func(const thresh_binary_inv_func& other) + : thresh(other.thresh), maxVal(other.maxVal) {} + + T thresh; + T maxVal; + }; + + template struct thresh_trunc_func : unary_function + { + explicit __host__ __device__ __forceinline__ thresh_trunc_func(T thresh_, T maxVal_ = 0) : thresh(thresh_) {CV_UNUSED(maxVal_);} + + __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const + { + return minimum()(src, thresh); + } + + __host__ __device__ __forceinline__ thresh_trunc_func() {} + __host__ __device__ __forceinline__ thresh_trunc_func(const thresh_trunc_func& other) + : thresh(other.thresh) {} + + T thresh; + }; + + template struct thresh_to_zero_func : unary_function + { + explicit __host__ __device__ __forceinline__ thresh_to_zero_func(T thresh_, T maxVal_ = 0) : thresh(thresh_) {CV_UNUSED(maxVal_);} + + __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const + { + return (src > thresh) * src; + } + + __host__ __device__ __forceinline__ thresh_to_zero_func() {} + __host__ __device__ __forceinline__ thresh_to_zero_func(const thresh_to_zero_func& other) + : thresh(other.thresh) {} + + T thresh; + }; + + template struct thresh_to_zero_inv_func : unary_function + { + explicit __host__ __device__ __forceinline__ thresh_to_zero_inv_func(T thresh_, T maxVal_ = 0) : thresh(thresh_) {CV_UNUSED(maxVal_);} + + __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const + { + return (src <= thresh) * src; + } + + __host__ __device__ __forceinline__ thresh_to_zero_inv_func() {} + __host__ __device__ __forceinline__ thresh_to_zero_inv_func(const thresh_to_zero_inv_func& other) + : thresh(other.thresh) {} + + T thresh; + }; + + // Function Object Adaptors + template struct unary_negate : unary_function + { + explicit __host__ __device__ __forceinline__ unary_negate(const Predicate& p) : pred(p) {} + + __device__ __forceinline__ bool operator()(typename TypeTraits::ParameterType x) const + { + return !pred(x); + } + + __host__ __device__ __forceinline__ unary_negate() {} + __host__ __device__ __forceinline__ unary_negate(const unary_negate& other) : pred(other.pred) {} + + Predicate pred; + }; + + template __host__ __device__ __forceinline__ unary_negate not1(const Predicate& pred) + { + return unary_negate(pred); + } + + template struct binary_negate : binary_function + { + explicit __host__ __device__ __forceinline__ binary_negate(const Predicate& p) : pred(p) {} + + __device__ __forceinline__ bool operator()(typename TypeTraits::ParameterType x, + typename TypeTraits::ParameterType y) const + { + return !pred(x,y); + } + + __host__ __device__ __forceinline__ binary_negate() {} + __host__ __device__ __forceinline__ binary_negate(const binary_negate& other) : pred(other.pred) {} + + Predicate pred; + }; + + template __host__ __device__ __forceinline__ binary_negate not2(const BinaryPredicate& pred) + { + return binary_negate(pred); + } + + template struct binder1st : unary_function + { + __host__ __device__ __forceinline__ binder1st(const Op& op_, const typename Op::first_argument_type& arg1_) : op(op_), arg1(arg1_) {} + + __device__ __forceinline__ typename Op::result_type operator ()(typename TypeTraits::ParameterType a) const + { + return op(arg1, a); + } + + __host__ __device__ __forceinline__ binder1st() {} + __host__ __device__ __forceinline__ binder1st(const binder1st& other) : op(other.op), arg1(other.arg1) {} + + Op op; + typename Op::first_argument_type arg1; + }; + + template __host__ __device__ __forceinline__ binder1st bind1st(const Op& op, const T& x) + { + return binder1st(op, typename Op::first_argument_type(x)); + } + + template struct binder2nd : unary_function + { + __host__ __device__ __forceinline__ binder2nd(const Op& op_, const typename Op::second_argument_type& arg2_) : op(op_), arg2(arg2_) {} + + __forceinline__ __device__ typename Op::result_type operator ()(typename TypeTraits::ParameterType a) const + { + return op(a, arg2); + } + + __host__ __device__ __forceinline__ binder2nd() {} + __host__ __device__ __forceinline__ binder2nd(const binder2nd& other) : op(other.op), arg2(other.arg2) {} + + Op op; + typename Op::second_argument_type arg2; + }; + + template __host__ __device__ __forceinline__ binder2nd bind2nd(const Op& op, const T& x) + { + return binder2nd(op, typename Op::second_argument_type(x)); + } + + // Functor Traits + template struct IsUnaryFunction + { + typedef char Yes; + struct No {Yes a[2];}; + + template static Yes check(unary_function); + static No check(...); + + static F makeF(); + + enum { value = (sizeof(check(makeF())) == sizeof(Yes)) }; + }; + + template struct IsBinaryFunction + { + typedef char Yes; + struct No {Yes a[2];}; + + template static Yes check(binary_function); + static No check(...); + + static F makeF(); + + enum { value = (sizeof(check(makeF())) == sizeof(Yes)) }; + }; + + namespace functional_detail + { + template struct UnOpShift { enum { shift = 1 }; }; + template struct UnOpShift { enum { shift = 4 }; }; + template struct UnOpShift { enum { shift = 2 }; }; + + template struct DefaultUnaryShift + { + enum { shift = UnOpShift::shift }; + }; + + template struct BinOpShift { enum { shift = 1 }; }; + template struct BinOpShift { enum { shift = 4 }; }; + template struct BinOpShift { enum { shift = 2 }; }; + + template struct DefaultBinaryShift + { + enum { shift = BinOpShift::shift }; + }; + + template ::value> struct ShiftDispatcher; + template struct ShiftDispatcher + { + enum { shift = DefaultUnaryShift::shift }; + }; + template struct ShiftDispatcher + { + enum { shift = DefaultBinaryShift::shift }; + }; + } + + template struct DefaultTransformShift + { + enum { shift = functional_detail::ShiftDispatcher::shift }; + }; + + template struct DefaultTransformFunctorTraits + { + enum { simple_block_dim_x = 16 }; + enum { simple_block_dim_y = 16 }; + + enum { smart_block_dim_x = 16 }; + enum { smart_block_dim_y = 16 }; + enum { smart_shift = DefaultTransformShift::shift }; + }; + + template struct TransformFunctorTraits : DefaultTransformFunctorTraits {}; + +#define OPENCV_CUDA_TRANSFORM_FUNCTOR_TRAITS(type) \ + template <> struct TransformFunctorTraits< type > : DefaultTransformFunctorTraits< type > +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif // OPENCV_CUDA_FUNCTIONAL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/limits.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/limits.hpp index 7e15ed629a..5f830b3365 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/limits.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/limits.hpp @@ -1,128 +1,128 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_LIMITS_HPP -#define OPENCV_CUDA_LIMITS_HPP - -#include -#include -#include "common.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ -template struct numeric_limits; - -template <> struct numeric_limits -{ - __device__ __forceinline__ static bool min() { return false; } - __device__ __forceinline__ static bool max() { return true; } - static const bool is_signed = false; -}; - -template <> struct numeric_limits -{ - __device__ __forceinline__ static signed char min() { return SCHAR_MIN; } - __device__ __forceinline__ static signed char max() { return SCHAR_MAX; } - static const bool is_signed = true; -}; - -template <> struct numeric_limits -{ - __device__ __forceinline__ static unsigned char min() { return 0; } - __device__ __forceinline__ static unsigned char max() { return UCHAR_MAX; } - static const bool is_signed = false; -}; - -template <> struct numeric_limits -{ - __device__ __forceinline__ static short min() { return SHRT_MIN; } - __device__ __forceinline__ static short max() { return SHRT_MAX; } - static const bool is_signed = true; -}; - -template <> struct numeric_limits -{ - __device__ __forceinline__ static unsigned short min() { return 0; } - __device__ __forceinline__ static unsigned short max() { return USHRT_MAX; } - static const bool is_signed = false; -}; - -template <> struct numeric_limits -{ - __device__ __forceinline__ static int min() { return INT_MIN; } - __device__ __forceinline__ static int max() { return INT_MAX; } - static const bool is_signed = true; -}; - -template <> struct numeric_limits -{ - __device__ __forceinline__ static unsigned int min() { return 0; } - __device__ __forceinline__ static unsigned int max() { return UINT_MAX; } - static const bool is_signed = false; -}; - -template <> struct numeric_limits -{ - __device__ __forceinline__ static float min() { return FLT_MIN; } - __device__ __forceinline__ static float max() { return FLT_MAX; } - __device__ __forceinline__ static float epsilon() { return FLT_EPSILON; } - static const bool is_signed = true; -}; - -template <> struct numeric_limits -{ - __device__ __forceinline__ static double min() { return DBL_MIN; } - __device__ __forceinline__ static double max() { return DBL_MAX; } - __device__ __forceinline__ static double epsilon() { return DBL_EPSILON; } - static const bool is_signed = true; -}; -}}} // namespace cv { namespace cuda { namespace cudev { - -//! @endcond - -#endif // OPENCV_CUDA_LIMITS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_LIMITS_HPP +#define OPENCV_CUDA_LIMITS_HPP + +#include +#include +#include "common.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ +template struct numeric_limits; + +template <> struct numeric_limits +{ + __device__ __forceinline__ static bool min() { return false; } + __device__ __forceinline__ static bool max() { return true; } + static const bool is_signed = false; +}; + +template <> struct numeric_limits +{ + __device__ __forceinline__ static signed char min() { return SCHAR_MIN; } + __device__ __forceinline__ static signed char max() { return SCHAR_MAX; } + static const bool is_signed = true; +}; + +template <> struct numeric_limits +{ + __device__ __forceinline__ static unsigned char min() { return 0; } + __device__ __forceinline__ static unsigned char max() { return UCHAR_MAX; } + static const bool is_signed = false; +}; + +template <> struct numeric_limits +{ + __device__ __forceinline__ static short min() { return SHRT_MIN; } + __device__ __forceinline__ static short max() { return SHRT_MAX; } + static const bool is_signed = true; +}; + +template <> struct numeric_limits +{ + __device__ __forceinline__ static unsigned short min() { return 0; } + __device__ __forceinline__ static unsigned short max() { return USHRT_MAX; } + static const bool is_signed = false; +}; + +template <> struct numeric_limits +{ + __device__ __forceinline__ static int min() { return INT_MIN; } + __device__ __forceinline__ static int max() { return INT_MAX; } + static const bool is_signed = true; +}; + +template <> struct numeric_limits +{ + __device__ __forceinline__ static unsigned int min() { return 0; } + __device__ __forceinline__ static unsigned int max() { return UINT_MAX; } + static const bool is_signed = false; +}; + +template <> struct numeric_limits +{ + __device__ __forceinline__ static float min() { return FLT_MIN; } + __device__ __forceinline__ static float max() { return FLT_MAX; } + __device__ __forceinline__ static float epsilon() { return FLT_EPSILON; } + static const bool is_signed = true; +}; + +template <> struct numeric_limits +{ + __device__ __forceinline__ static double min() { return DBL_MIN; } + __device__ __forceinline__ static double max() { return DBL_MAX; } + __device__ __forceinline__ static double epsilon() { return DBL_EPSILON; } + static const bool is_signed = true; +}; +}}} // namespace cv { namespace cuda { namespace cudev { + +//! @endcond + +#endif // OPENCV_CUDA_LIMITS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/reduce.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/reduce.hpp index fb74de95a8..f422b0d58d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/reduce.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/reduce.hpp @@ -1,230 +1,230 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_REDUCE_HPP -#define OPENCV_CUDA_REDUCE_HPP - -#ifndef THRUST_DEBUG // eliminate -Wundef warning -#define THRUST_DEBUG 0 -#endif - -#include -#include "detail/reduce.hpp" -#include "detail/reduce_key_val.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - template - __device__ __forceinline__ void reduce(volatile T* smem, T& val, unsigned int tid, const Op& op) - { - reduce_detail::Dispatcher::reductor::template reduce(smem, val, tid, op); - } - template - __device__ __forceinline__ void reduceKeyVal(volatile K* skeys, K& key, volatile V* svals, V& val, unsigned int tid, const Cmp& cmp) - { - reduce_key_val_detail::Dispatcher::reductor::template reduce(skeys, key, svals, val, tid, cmp); - } -#if (CUDART_VERSION < 12040) // details: https://github.com/opencv/opencv_contrib/issues/3690 - template - __device__ __forceinline__ void reduce(const thrust::tuple& smem, - const thrust::tuple& val, - unsigned int tid, - const thrust::tuple& op) - { - reduce_detail::Dispatcher::reductor::template reduce< - const thrust::tuple&, - const thrust::tuple&, - const thrust::tuple&>(smem, val, tid, op); - } - - template - __device__ __forceinline__ void reduceKeyVal(volatile K* skeys, K& key, - const thrust::tuple& svals, - const thrust::tuple& val, - unsigned int tid, const Cmp& cmp) - { - reduce_key_val_detail::Dispatcher::reductor::template reduce&, - const thrust::tuple&, - const Cmp&>(skeys, key, svals, val, tid, cmp); - } - - template - __device__ __forceinline__ void reduceKeyVal(const thrust::tuple& skeys, - const thrust::tuple& key, - const thrust::tuple& svals, - const thrust::tuple& val, - unsigned int tid, - const thrust::tuple& cmp) - { - reduce_key_val_detail::Dispatcher::reductor::template reduce< - const thrust::tuple&, - const thrust::tuple&, - const thrust::tuple&, - const thrust::tuple&, - const thrust::tuple& - >(skeys, key, svals, val, tid, cmp); - } -#else - template - __device__ __forceinline__ void reduce(const thrust::tuple& smem, const thrust::tuple& val, unsigned int tid, const thrust::tuple& op) - { - reduce_detail::Dispatcher::reductor::template reduce&, const thrust::tuple&, const thrust::tuple&>(smem, val, tid, op); - } - - template - __device__ __forceinline__ void reduceKeyVal(volatile K* skeys, K& key, const thrust::tuple& svals, const thrust::tuple& val, unsigned int tid, const Cmp& cmp) - { - reduce_key_val_detail::Dispatcher::reductor::template reduce&, const thrust::tuple&, const Cmp&>(skeys, key, svals, val, tid, cmp); - } - - template - __device__ __forceinline__ void reduceKeyVal(const thrust::tuple& skeys, const thrust::tuple& key, const thrust::tuple& svals, const thrust::tuple& val, unsigned int tid, const thrust::tuple& cmp) - { - reduce_key_val_detail::Dispatcher::reductor::template reduce&, const thrust::tuple&, const thrust::tuple&, const thrust::tuple&, const thrust::tuple&>(skeys, key, svals, val, tid, cmp); - } -#endif - - // smem_tuple - - template - __device__ __forceinline__ - thrust::tuple - smem_tuple(T0* t0) - { - return thrust::make_tuple((volatile T0*) t0); - } - - template - __device__ __forceinline__ - thrust::tuple - smem_tuple(T0* t0, T1* t1) - { - return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1); - } - - template - __device__ __forceinline__ - thrust::tuple - smem_tuple(T0* t0, T1* t1, T2* t2) - { - return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2); - } - - template - __device__ __forceinline__ - thrust::tuple - smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3) - { - return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3); - } - - template - __device__ __forceinline__ - thrust::tuple - smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4) - { - return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4); - } - - template - __device__ __forceinline__ - thrust::tuple - smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5) - { - return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5); - } - - template - __device__ __forceinline__ - thrust::tuple - smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5, T6* t6) - { - return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5, (volatile T6*) t6); - } - - template - __device__ __forceinline__ - thrust::tuple - smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5, T6* t6, T7* t7) - { - return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5, (volatile T6*) t6, (volatile T7*) t7); - } - - template - __device__ __forceinline__ - thrust::tuple - smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5, T6* t6, T7* t7, T8* t8) - { - return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5, (volatile T6*) t6, (volatile T7*) t7, (volatile T8*) t8); - } - - template - __device__ __forceinline__ - thrust::tuple - smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5, T6* t6, T7* t7, T8* t8, T9* t9) - { - return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5, (volatile T6*) t6, (volatile T7*) t7, (volatile T8*) t8, (volatile T9*) t9); - } -}}} - -//! @endcond - -#endif // OPENCV_CUDA_REDUCE_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_REDUCE_HPP +#define OPENCV_CUDA_REDUCE_HPP + +#ifndef THRUST_DEBUG // eliminate -Wundef warning +#define THRUST_DEBUG 0 +#endif + +#include +#include "detail/reduce.hpp" +#include "detail/reduce_key_val.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + template + __device__ __forceinline__ void reduce(volatile T* smem, T& val, unsigned int tid, const Op& op) + { + reduce_detail::Dispatcher::reductor::template reduce(smem, val, tid, op); + } + template + __device__ __forceinline__ void reduceKeyVal(volatile K* skeys, K& key, volatile V* svals, V& val, unsigned int tid, const Cmp& cmp) + { + reduce_key_val_detail::Dispatcher::reductor::template reduce(skeys, key, svals, val, tid, cmp); + } +#if (CUDART_VERSION < 12040) // details: https://github.com/opencv/opencv_contrib/issues/3690 + template + __device__ __forceinline__ void reduce(const thrust::tuple& smem, + const thrust::tuple& val, + unsigned int tid, + const thrust::tuple& op) + { + reduce_detail::Dispatcher::reductor::template reduce< + const thrust::tuple&, + const thrust::tuple&, + const thrust::tuple&>(smem, val, tid, op); + } + + template + __device__ __forceinline__ void reduceKeyVal(volatile K* skeys, K& key, + const thrust::tuple& svals, + const thrust::tuple& val, + unsigned int tid, const Cmp& cmp) + { + reduce_key_val_detail::Dispatcher::reductor::template reduce&, + const thrust::tuple&, + const Cmp&>(skeys, key, svals, val, tid, cmp); + } + + template + __device__ __forceinline__ void reduceKeyVal(const thrust::tuple& skeys, + const thrust::tuple& key, + const thrust::tuple& svals, + const thrust::tuple& val, + unsigned int tid, + const thrust::tuple& cmp) + { + reduce_key_val_detail::Dispatcher::reductor::template reduce< + const thrust::tuple&, + const thrust::tuple&, + const thrust::tuple&, + const thrust::tuple&, + const thrust::tuple& + >(skeys, key, svals, val, tid, cmp); + } +#else + template + __device__ __forceinline__ void reduce(const thrust::tuple& smem, const thrust::tuple& val, unsigned int tid, const thrust::tuple& op) + { + reduce_detail::Dispatcher::reductor::template reduce&, const thrust::tuple&, const thrust::tuple&>(smem, val, tid, op); + } + + template + __device__ __forceinline__ void reduceKeyVal(volatile K* skeys, K& key, const thrust::tuple& svals, const thrust::tuple& val, unsigned int tid, const Cmp& cmp) + { + reduce_key_val_detail::Dispatcher::reductor::template reduce&, const thrust::tuple&, const Cmp&>(skeys, key, svals, val, tid, cmp); + } + + template + __device__ __forceinline__ void reduceKeyVal(const thrust::tuple& skeys, const thrust::tuple& key, const thrust::tuple& svals, const thrust::tuple& val, unsigned int tid, const thrust::tuple& cmp) + { + reduce_key_val_detail::Dispatcher::reductor::template reduce&, const thrust::tuple&, const thrust::tuple&, const thrust::tuple&, const thrust::tuple&>(skeys, key, svals, val, tid, cmp); + } +#endif + + // smem_tuple + + template + __device__ __forceinline__ + thrust::tuple + smem_tuple(T0* t0) + { + return thrust::make_tuple((volatile T0*) t0); + } + + template + __device__ __forceinline__ + thrust::tuple + smem_tuple(T0* t0, T1* t1) + { + return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1); + } + + template + __device__ __forceinline__ + thrust::tuple + smem_tuple(T0* t0, T1* t1, T2* t2) + { + return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2); + } + + template + __device__ __forceinline__ + thrust::tuple + smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3) + { + return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3); + } + + template + __device__ __forceinline__ + thrust::tuple + smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4) + { + return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4); + } + + template + __device__ __forceinline__ + thrust::tuple + smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5) + { + return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5); + } + + template + __device__ __forceinline__ + thrust::tuple + smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5, T6* t6) + { + return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5, (volatile T6*) t6); + } + + template + __device__ __forceinline__ + thrust::tuple + smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5, T6* t6, T7* t7) + { + return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5, (volatile T6*) t6, (volatile T7*) t7); + } + + template + __device__ __forceinline__ + thrust::tuple + smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5, T6* t6, T7* t7, T8* t8) + { + return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5, (volatile T6*) t6, (volatile T7*) t7, (volatile T8*) t8); + } + + template + __device__ __forceinline__ + thrust::tuple + smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5, T6* t6, T7* t7, T8* t8, T9* t9) + { + return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5, (volatile T6*) t6, (volatile T7*) t7, (volatile T8*) t8, (volatile T9*) t9); + } +}}} + +//! @endcond + +#endif // OPENCV_CUDA_REDUCE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/saturate_cast.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/saturate_cast.hpp index c3a3d1cb83..865d883683 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/saturate_cast.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/saturate_cast.hpp @@ -1,292 +1,292 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_SATURATE_CAST_HPP -#define OPENCV_CUDA_SATURATE_CAST_HPP - -#include "common.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - template __device__ __forceinline__ _Tp saturate_cast(uchar v) { return _Tp(v); } - template __device__ __forceinline__ _Tp saturate_cast(schar v) { return _Tp(v); } - template __device__ __forceinline__ _Tp saturate_cast(ushort v) { return _Tp(v); } - template __device__ __forceinline__ _Tp saturate_cast(short v) { return _Tp(v); } - template __device__ __forceinline__ _Tp saturate_cast(uint v) { return _Tp(v); } - template __device__ __forceinline__ _Tp saturate_cast(int v) { return _Tp(v); } - template __device__ __forceinline__ _Tp saturate_cast(float v) { return _Tp(v); } - template __device__ __forceinline__ _Tp saturate_cast(double v) { return _Tp(v); } - - template<> __device__ __forceinline__ uchar saturate_cast(schar v) - { - uint res = 0; - int vi = v; - asm("cvt.sat.u8.s8 %0, %1;" : "=r"(res) : "r"(vi)); - return res; - } - template<> __device__ __forceinline__ uchar saturate_cast(short v) - { - uint res = 0; - asm("cvt.sat.u8.s16 %0, %1;" : "=r"(res) : "h"(v)); - return res; - } - template<> __device__ __forceinline__ uchar saturate_cast(ushort v) - { - uint res = 0; - asm("cvt.sat.u8.u16 %0, %1;" : "=r"(res) : "h"(v)); - return res; - } - template<> __device__ __forceinline__ uchar saturate_cast(int v) - { - uint res = 0; - asm("cvt.sat.u8.s32 %0, %1;" : "=r"(res) : "r"(v)); - return res; - } - template<> __device__ __forceinline__ uchar saturate_cast(uint v) - { - uint res = 0; - asm("cvt.sat.u8.u32 %0, %1;" : "=r"(res) : "r"(v)); - return res; - } - template<> __device__ __forceinline__ uchar saturate_cast(float v) - { - uint res = 0; - asm("cvt.rni.sat.u8.f32 %0, %1;" : "=r"(res) : "f"(v)); - return res; - } - template<> __device__ __forceinline__ uchar saturate_cast(double v) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 - uint res = 0; - asm("cvt.rni.sat.u8.f64 %0, %1;" : "=r"(res) : "d"(v)); - return res; - #else - return saturate_cast((float)v); - #endif - } - - template<> __device__ __forceinline__ schar saturate_cast(uchar v) - { - uint res = 0; - uint vi = v; - asm("cvt.sat.s8.u8 %0, %1;" : "=r"(res) : "r"(vi)); - return res; - } - template<> __device__ __forceinline__ schar saturate_cast(short v) - { - uint res = 0; - asm("cvt.sat.s8.s16 %0, %1;" : "=r"(res) : "h"(v)); - return res; - } - template<> __device__ __forceinline__ schar saturate_cast(ushort v) - { - uint res = 0; - asm("cvt.sat.s8.u16 %0, %1;" : "=r"(res) : "h"(v)); - return res; - } - template<> __device__ __forceinline__ schar saturate_cast(int v) - { - uint res = 0; - asm("cvt.sat.s8.s32 %0, %1;" : "=r"(res) : "r"(v)); - return res; - } - template<> __device__ __forceinline__ schar saturate_cast(uint v) - { - uint res = 0; - asm("cvt.sat.s8.u32 %0, %1;" : "=r"(res) : "r"(v)); - return res; - } - template<> __device__ __forceinline__ schar saturate_cast(float v) - { - uint res = 0; - asm("cvt.rni.sat.s8.f32 %0, %1;" : "=r"(res) : "f"(v)); - return res; - } - template<> __device__ __forceinline__ schar saturate_cast(double v) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 - uint res = 0; - asm("cvt.rni.sat.s8.f64 %0, %1;" : "=r"(res) : "d"(v)); - return res; - #else - return saturate_cast((float)v); - #endif - } - - template<> __device__ __forceinline__ ushort saturate_cast(schar v) - { - ushort res = 0; - int vi = v; - asm("cvt.sat.u16.s8 %0, %1;" : "=h"(res) : "r"(vi)); - return res; - } - template<> __device__ __forceinline__ ushort saturate_cast(short v) - { - ushort res = 0; - asm("cvt.sat.u16.s16 %0, %1;" : "=h"(res) : "h"(v)); - return res; - } - template<> __device__ __forceinline__ ushort saturate_cast(int v) - { - ushort res = 0; - asm("cvt.sat.u16.s32 %0, %1;" : "=h"(res) : "r"(v)); - return res; - } - template<> __device__ __forceinline__ ushort saturate_cast(uint v) - { - ushort res = 0; - asm("cvt.sat.u16.u32 %0, %1;" : "=h"(res) : "r"(v)); - return res; - } - template<> __device__ __forceinline__ ushort saturate_cast(float v) - { - ushort res = 0; - asm("cvt.rni.sat.u16.f32 %0, %1;" : "=h"(res) : "f"(v)); - return res; - } - template<> __device__ __forceinline__ ushort saturate_cast(double v) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 - ushort res = 0; - asm("cvt.rni.sat.u16.f64 %0, %1;" : "=h"(res) : "d"(v)); - return res; - #else - return saturate_cast((float)v); - #endif - } - - template<> __device__ __forceinline__ short saturate_cast(ushort v) - { - short res = 0; - asm("cvt.sat.s16.u16 %0, %1;" : "=h"(res) : "h"(v)); - return res; - } - template<> __device__ __forceinline__ short saturate_cast(int v) - { - short res = 0; - asm("cvt.sat.s16.s32 %0, %1;" : "=h"(res) : "r"(v)); - return res; - } - template<> __device__ __forceinline__ short saturate_cast(uint v) - { - short res = 0; - asm("cvt.sat.s16.u32 %0, %1;" : "=h"(res) : "r"(v)); - return res; - } - template<> __device__ __forceinline__ short saturate_cast(float v) - { - short res = 0; - asm("cvt.rni.sat.s16.f32 %0, %1;" : "=h"(res) : "f"(v)); - return res; - } - template<> __device__ __forceinline__ short saturate_cast(double v) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 - short res = 0; - asm("cvt.rni.sat.s16.f64 %0, %1;" : "=h"(res) : "d"(v)); - return res; - #else - return saturate_cast((float)v); - #endif - } - - template<> __device__ __forceinline__ int saturate_cast(uint v) - { - int res = 0; - asm("cvt.sat.s32.u32 %0, %1;" : "=r"(res) : "r"(v)); - return res; - } - template<> __device__ __forceinline__ int saturate_cast(float v) - { - return __float2int_rn(v); - } - template<> __device__ __forceinline__ int saturate_cast(double v) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 - return __double2int_rn(v); - #else - return saturate_cast((float)v); - #endif - } - - template<> __device__ __forceinline__ uint saturate_cast(schar v) - { - uint res = 0; - int vi = v; - asm("cvt.sat.u32.s8 %0, %1;" : "=r"(res) : "r"(vi)); - return res; - } - template<> __device__ __forceinline__ uint saturate_cast(short v) - { - uint res = 0; - asm("cvt.sat.u32.s16 %0, %1;" : "=r"(res) : "h"(v)); - return res; - } - template<> __device__ __forceinline__ uint saturate_cast(int v) - { - uint res = 0; - asm("cvt.sat.u32.s32 %0, %1;" : "=r"(res) : "r"(v)); - return res; - } - template<> __device__ __forceinline__ uint saturate_cast(float v) - { - return __float2uint_rn(v); - } - template<> __device__ __forceinline__ uint saturate_cast(double v) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 - return __double2uint_rn(v); - #else - return saturate_cast((float)v); - #endif - } -}}} - -//! @endcond - -#endif /* OPENCV_CUDA_SATURATE_CAST_HPP */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_SATURATE_CAST_HPP +#define OPENCV_CUDA_SATURATE_CAST_HPP + +#include "common.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + template __device__ __forceinline__ _Tp saturate_cast(uchar v) { return _Tp(v); } + template __device__ __forceinline__ _Tp saturate_cast(schar v) { return _Tp(v); } + template __device__ __forceinline__ _Tp saturate_cast(ushort v) { return _Tp(v); } + template __device__ __forceinline__ _Tp saturate_cast(short v) { return _Tp(v); } + template __device__ __forceinline__ _Tp saturate_cast(uint v) { return _Tp(v); } + template __device__ __forceinline__ _Tp saturate_cast(int v) { return _Tp(v); } + template __device__ __forceinline__ _Tp saturate_cast(float v) { return _Tp(v); } + template __device__ __forceinline__ _Tp saturate_cast(double v) { return _Tp(v); } + + template<> __device__ __forceinline__ uchar saturate_cast(schar v) + { + uint res = 0; + int vi = v; + asm("cvt.sat.u8.s8 %0, %1;" : "=r"(res) : "r"(vi)); + return res; + } + template<> __device__ __forceinline__ uchar saturate_cast(short v) + { + uint res = 0; + asm("cvt.sat.u8.s16 %0, %1;" : "=r"(res) : "h"(v)); + return res; + } + template<> __device__ __forceinline__ uchar saturate_cast(ushort v) + { + uint res = 0; + asm("cvt.sat.u8.u16 %0, %1;" : "=r"(res) : "h"(v)); + return res; + } + template<> __device__ __forceinline__ uchar saturate_cast(int v) + { + uint res = 0; + asm("cvt.sat.u8.s32 %0, %1;" : "=r"(res) : "r"(v)); + return res; + } + template<> __device__ __forceinline__ uchar saturate_cast(uint v) + { + uint res = 0; + asm("cvt.sat.u8.u32 %0, %1;" : "=r"(res) : "r"(v)); + return res; + } + template<> __device__ __forceinline__ uchar saturate_cast(float v) + { + uint res = 0; + asm("cvt.rni.sat.u8.f32 %0, %1;" : "=r"(res) : "f"(v)); + return res; + } + template<> __device__ __forceinline__ uchar saturate_cast(double v) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 + uint res = 0; + asm("cvt.rni.sat.u8.f64 %0, %1;" : "=r"(res) : "d"(v)); + return res; + #else + return saturate_cast((float)v); + #endif + } + + template<> __device__ __forceinline__ schar saturate_cast(uchar v) + { + uint res = 0; + uint vi = v; + asm("cvt.sat.s8.u8 %0, %1;" : "=r"(res) : "r"(vi)); + return res; + } + template<> __device__ __forceinline__ schar saturate_cast(short v) + { + uint res = 0; + asm("cvt.sat.s8.s16 %0, %1;" : "=r"(res) : "h"(v)); + return res; + } + template<> __device__ __forceinline__ schar saturate_cast(ushort v) + { + uint res = 0; + asm("cvt.sat.s8.u16 %0, %1;" : "=r"(res) : "h"(v)); + return res; + } + template<> __device__ __forceinline__ schar saturate_cast(int v) + { + uint res = 0; + asm("cvt.sat.s8.s32 %0, %1;" : "=r"(res) : "r"(v)); + return res; + } + template<> __device__ __forceinline__ schar saturate_cast(uint v) + { + uint res = 0; + asm("cvt.sat.s8.u32 %0, %1;" : "=r"(res) : "r"(v)); + return res; + } + template<> __device__ __forceinline__ schar saturate_cast(float v) + { + uint res = 0; + asm("cvt.rni.sat.s8.f32 %0, %1;" : "=r"(res) : "f"(v)); + return res; + } + template<> __device__ __forceinline__ schar saturate_cast(double v) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 + uint res = 0; + asm("cvt.rni.sat.s8.f64 %0, %1;" : "=r"(res) : "d"(v)); + return res; + #else + return saturate_cast((float)v); + #endif + } + + template<> __device__ __forceinline__ ushort saturate_cast(schar v) + { + ushort res = 0; + int vi = v; + asm("cvt.sat.u16.s8 %0, %1;" : "=h"(res) : "r"(vi)); + return res; + } + template<> __device__ __forceinline__ ushort saturate_cast(short v) + { + ushort res = 0; + asm("cvt.sat.u16.s16 %0, %1;" : "=h"(res) : "h"(v)); + return res; + } + template<> __device__ __forceinline__ ushort saturate_cast(int v) + { + ushort res = 0; + asm("cvt.sat.u16.s32 %0, %1;" : "=h"(res) : "r"(v)); + return res; + } + template<> __device__ __forceinline__ ushort saturate_cast(uint v) + { + ushort res = 0; + asm("cvt.sat.u16.u32 %0, %1;" : "=h"(res) : "r"(v)); + return res; + } + template<> __device__ __forceinline__ ushort saturate_cast(float v) + { + ushort res = 0; + asm("cvt.rni.sat.u16.f32 %0, %1;" : "=h"(res) : "f"(v)); + return res; + } + template<> __device__ __forceinline__ ushort saturate_cast(double v) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 + ushort res = 0; + asm("cvt.rni.sat.u16.f64 %0, %1;" : "=h"(res) : "d"(v)); + return res; + #else + return saturate_cast((float)v); + #endif + } + + template<> __device__ __forceinline__ short saturate_cast(ushort v) + { + short res = 0; + asm("cvt.sat.s16.u16 %0, %1;" : "=h"(res) : "h"(v)); + return res; + } + template<> __device__ __forceinline__ short saturate_cast(int v) + { + short res = 0; + asm("cvt.sat.s16.s32 %0, %1;" : "=h"(res) : "r"(v)); + return res; + } + template<> __device__ __forceinline__ short saturate_cast(uint v) + { + short res = 0; + asm("cvt.sat.s16.u32 %0, %1;" : "=h"(res) : "r"(v)); + return res; + } + template<> __device__ __forceinline__ short saturate_cast(float v) + { + short res = 0; + asm("cvt.rni.sat.s16.f32 %0, %1;" : "=h"(res) : "f"(v)); + return res; + } + template<> __device__ __forceinline__ short saturate_cast(double v) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 + short res = 0; + asm("cvt.rni.sat.s16.f64 %0, %1;" : "=h"(res) : "d"(v)); + return res; + #else + return saturate_cast((float)v); + #endif + } + + template<> __device__ __forceinline__ int saturate_cast(uint v) + { + int res = 0; + asm("cvt.sat.s32.u32 %0, %1;" : "=r"(res) : "r"(v)); + return res; + } + template<> __device__ __forceinline__ int saturate_cast(float v) + { + return __float2int_rn(v); + } + template<> __device__ __forceinline__ int saturate_cast(double v) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 + return __double2int_rn(v); + #else + return saturate_cast((float)v); + #endif + } + + template<> __device__ __forceinline__ uint saturate_cast(schar v) + { + uint res = 0; + int vi = v; + asm("cvt.sat.u32.s8 %0, %1;" : "=r"(res) : "r"(vi)); + return res; + } + template<> __device__ __forceinline__ uint saturate_cast(short v) + { + uint res = 0; + asm("cvt.sat.u32.s16 %0, %1;" : "=r"(res) : "h"(v)); + return res; + } + template<> __device__ __forceinline__ uint saturate_cast(int v) + { + uint res = 0; + asm("cvt.sat.u32.s32 %0, %1;" : "=r"(res) : "r"(v)); + return res; + } + template<> __device__ __forceinline__ uint saturate_cast(float v) + { + return __float2uint_rn(v); + } + template<> __device__ __forceinline__ uint saturate_cast(double v) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 + return __double2uint_rn(v); + #else + return saturate_cast((float)v); + #endif + } +}}} + +//! @endcond + +#endif /* OPENCV_CUDA_SATURATE_CAST_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/scan.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/scan.hpp index e128fb0962..e7b0e2ae89 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/scan.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/scan.hpp @@ -1,258 +1,258 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_SCAN_HPP -#define OPENCV_CUDA_SCAN_HPP - -#include "opencv2/core/cuda/common.hpp" -#include "opencv2/core/cuda/utility.hpp" -#include "opencv2/core/cuda/warp.hpp" -#include "opencv2/core/cuda/warp_shuffle.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - enum ScanKind { EXCLUSIVE = 0, INCLUSIVE = 1 }; - - template struct WarpScan - { - __device__ __forceinline__ WarpScan() {} - __device__ __forceinline__ WarpScan(const WarpScan& other) { CV_UNUSED(other); } - - __device__ __forceinline__ T operator()( volatile T *ptr , const unsigned int idx) - { - const unsigned int lane = idx & 31; - F op; - - if ( lane >= 1) ptr [idx ] = op(ptr [idx - 1], ptr [idx]); - if ( lane >= 2) ptr [idx ] = op(ptr [idx - 2], ptr [idx]); - if ( lane >= 4) ptr [idx ] = op(ptr [idx - 4], ptr [idx]); - if ( lane >= 8) ptr [idx ] = op(ptr [idx - 8], ptr [idx]); - if ( lane >= 16) ptr [idx ] = op(ptr [idx - 16], ptr [idx]); - - if( Kind == INCLUSIVE ) - return ptr [idx]; - else - return (lane > 0) ? ptr [idx - 1] : 0; - } - - __device__ __forceinline__ unsigned int index(const unsigned int tid) - { - return tid; - } - - __device__ __forceinline__ void init(volatile T *ptr){} - - static const int warp_offset = 0; - - typedef WarpScan merge; - }; - - template struct WarpScanNoComp - { - __device__ __forceinline__ WarpScanNoComp() {} - __device__ __forceinline__ WarpScanNoComp(const WarpScanNoComp& other) { CV_UNUSED(other); } - - __device__ __forceinline__ T operator()( volatile T *ptr , const unsigned int idx) - { - const unsigned int lane = threadIdx.x & 31; - F op; - - ptr [idx ] = op(ptr [idx - 1], ptr [idx]); - ptr [idx ] = op(ptr [idx - 2], ptr [idx]); - ptr [idx ] = op(ptr [idx - 4], ptr [idx]); - ptr [idx ] = op(ptr [idx - 8], ptr [idx]); - ptr [idx ] = op(ptr [idx - 16], ptr [idx]); - - if( Kind == INCLUSIVE ) - return ptr [idx]; - else - return (lane > 0) ? ptr [idx - 1] : 0; - } - - __device__ __forceinline__ unsigned int index(const unsigned int tid) - { - return (tid >> warp_log) * warp_smem_stride + 16 + (tid & warp_mask); - } - - __device__ __forceinline__ void init(volatile T *ptr) - { - ptr[threadIdx.x] = 0; - } - - static const int warp_smem_stride = 32 + 16 + 1; - static const int warp_offset = 16; - static const int warp_log = 5; - static const int warp_mask = 31; - - typedef WarpScanNoComp merge; - }; - - template struct BlockScan - { - __device__ __forceinline__ BlockScan() {} - __device__ __forceinline__ BlockScan(const BlockScan& other) { CV_UNUSED(other); } - - __device__ __forceinline__ T operator()(volatile T *ptr) - { - const unsigned int tid = threadIdx.x; - const unsigned int lane = tid & warp_mask; - const unsigned int warp = tid >> warp_log; - - Sc scan; - typename Sc::merge merge_scan; - const unsigned int idx = scan.index(tid); - - T val = scan(ptr, idx); - __syncthreads (); - - if( warp == 0) - scan.init(ptr); - __syncthreads (); - - if( lane == 31 ) - ptr [scan.warp_offset + warp ] = (Kind == INCLUSIVE) ? val : ptr [idx]; - __syncthreads (); - - if( warp == 0 ) - merge_scan(ptr, idx); - __syncthreads(); - - if ( warp > 0) - val = ptr [scan.warp_offset + warp - 1] + val; - __syncthreads (); - - ptr[idx] = val; - __syncthreads (); - - return val ; - } - - static const int warp_log = 5; - static const int warp_mask = 31; - }; - - template - __device__ T warpScanInclusive(T idata, volatile T* s_Data, unsigned int tid) - { - #if __CUDA_ARCH__ >= 300 - const unsigned int laneId = cv::cuda::device::Warp::laneId(); - - // scan on shuffl functions - #pragma unroll - for (int i = 1; i <= (OPENCV_CUDA_WARP_SIZE / 2); i *= 2) - { - const T n = cv::cuda::device::shfl_up(idata, i); - if (laneId >= i) - idata += n; - } - - return idata; - #else - unsigned int pos = 2 * tid - (tid & (OPENCV_CUDA_WARP_SIZE - 1)); - s_Data[pos] = 0; - pos += OPENCV_CUDA_WARP_SIZE; - s_Data[pos] = idata; - - s_Data[pos] += s_Data[pos - 1]; - s_Data[pos] += s_Data[pos - 2]; - s_Data[pos] += s_Data[pos - 4]; - s_Data[pos] += s_Data[pos - 8]; - s_Data[pos] += s_Data[pos - 16]; - - return s_Data[pos]; - #endif - } - - template - __device__ __forceinline__ T warpScanExclusive(T idata, volatile T* s_Data, unsigned int tid) - { - return warpScanInclusive(idata, s_Data, tid) - idata; - } - - template - __device__ T blockScanInclusive(T idata, volatile T* s_Data, unsigned int tid) - { - if (tiNumScanThreads > OPENCV_CUDA_WARP_SIZE) - { - //Bottom-level inclusive warp scan - T warpResult = warpScanInclusive(idata, s_Data, tid); - - //Save top elements of each warp for exclusive warp scan - //sync to wait for warp scans to complete (because s_Data is being overwritten) - __syncthreads(); - if ((tid & (OPENCV_CUDA_WARP_SIZE - 1)) == (OPENCV_CUDA_WARP_SIZE - 1)) - { - s_Data[tid >> OPENCV_CUDA_LOG_WARP_SIZE] = warpResult; - } - - //wait for warp scans to complete - __syncthreads(); - - if (tid < (tiNumScanThreads / OPENCV_CUDA_WARP_SIZE) ) - { - //grab top warp elements - T val = s_Data[tid]; - //calculate exclusive scan and write back to shared memory - s_Data[tid] = warpScanExclusive(val, s_Data, tid); - } - - //return updated warp scans with exclusive scan results - __syncthreads(); - - return warpResult + s_Data[tid >> OPENCV_CUDA_LOG_WARP_SIZE]; - } - else - { - return warpScanInclusive(idata, s_Data, tid); - } - } -}}} - -//! @endcond - -#endif // OPENCV_CUDA_SCAN_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_SCAN_HPP +#define OPENCV_CUDA_SCAN_HPP + +#include "opencv2/core/cuda/common.hpp" +#include "opencv2/core/cuda/utility.hpp" +#include "opencv2/core/cuda/warp.hpp" +#include "opencv2/core/cuda/warp_shuffle.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + enum ScanKind { EXCLUSIVE = 0, INCLUSIVE = 1 }; + + template struct WarpScan + { + __device__ __forceinline__ WarpScan() {} + __device__ __forceinline__ WarpScan(const WarpScan& other) { CV_UNUSED(other); } + + __device__ __forceinline__ T operator()( volatile T *ptr , const unsigned int idx) + { + const unsigned int lane = idx & 31; + F op; + + if ( lane >= 1) ptr [idx ] = op(ptr [idx - 1], ptr [idx]); + if ( lane >= 2) ptr [idx ] = op(ptr [idx - 2], ptr [idx]); + if ( lane >= 4) ptr [idx ] = op(ptr [idx - 4], ptr [idx]); + if ( lane >= 8) ptr [idx ] = op(ptr [idx - 8], ptr [idx]); + if ( lane >= 16) ptr [idx ] = op(ptr [idx - 16], ptr [idx]); + + if( Kind == INCLUSIVE ) + return ptr [idx]; + else + return (lane > 0) ? ptr [idx - 1] : 0; + } + + __device__ __forceinline__ unsigned int index(const unsigned int tid) + { + return tid; + } + + __device__ __forceinline__ void init(volatile T *ptr){} + + static const int warp_offset = 0; + + typedef WarpScan merge; + }; + + template struct WarpScanNoComp + { + __device__ __forceinline__ WarpScanNoComp() {} + __device__ __forceinline__ WarpScanNoComp(const WarpScanNoComp& other) { CV_UNUSED(other); } + + __device__ __forceinline__ T operator()( volatile T *ptr , const unsigned int idx) + { + const unsigned int lane = threadIdx.x & 31; + F op; + + ptr [idx ] = op(ptr [idx - 1], ptr [idx]); + ptr [idx ] = op(ptr [idx - 2], ptr [idx]); + ptr [idx ] = op(ptr [idx - 4], ptr [idx]); + ptr [idx ] = op(ptr [idx - 8], ptr [idx]); + ptr [idx ] = op(ptr [idx - 16], ptr [idx]); + + if( Kind == INCLUSIVE ) + return ptr [idx]; + else + return (lane > 0) ? ptr [idx - 1] : 0; + } + + __device__ __forceinline__ unsigned int index(const unsigned int tid) + { + return (tid >> warp_log) * warp_smem_stride + 16 + (tid & warp_mask); + } + + __device__ __forceinline__ void init(volatile T *ptr) + { + ptr[threadIdx.x] = 0; + } + + static const int warp_smem_stride = 32 + 16 + 1; + static const int warp_offset = 16; + static const int warp_log = 5; + static const int warp_mask = 31; + + typedef WarpScanNoComp merge; + }; + + template struct BlockScan + { + __device__ __forceinline__ BlockScan() {} + __device__ __forceinline__ BlockScan(const BlockScan& other) { CV_UNUSED(other); } + + __device__ __forceinline__ T operator()(volatile T *ptr) + { + const unsigned int tid = threadIdx.x; + const unsigned int lane = tid & warp_mask; + const unsigned int warp = tid >> warp_log; + + Sc scan; + typename Sc::merge merge_scan; + const unsigned int idx = scan.index(tid); + + T val = scan(ptr, idx); + __syncthreads (); + + if( warp == 0) + scan.init(ptr); + __syncthreads (); + + if( lane == 31 ) + ptr [scan.warp_offset + warp ] = (Kind == INCLUSIVE) ? val : ptr [idx]; + __syncthreads (); + + if( warp == 0 ) + merge_scan(ptr, idx); + __syncthreads(); + + if ( warp > 0) + val = ptr [scan.warp_offset + warp - 1] + val; + __syncthreads (); + + ptr[idx] = val; + __syncthreads (); + + return val ; + } + + static const int warp_log = 5; + static const int warp_mask = 31; + }; + + template + __device__ T warpScanInclusive(T idata, volatile T* s_Data, unsigned int tid) + { + #if __CUDA_ARCH__ >= 300 + const unsigned int laneId = cv::cuda::device::Warp::laneId(); + + // scan on shuffl functions + #pragma unroll + for (int i = 1; i <= (OPENCV_CUDA_WARP_SIZE / 2); i *= 2) + { + const T n = cv::cuda::device::shfl_up(idata, i); + if (laneId >= i) + idata += n; + } + + return idata; + #else + unsigned int pos = 2 * tid - (tid & (OPENCV_CUDA_WARP_SIZE - 1)); + s_Data[pos] = 0; + pos += OPENCV_CUDA_WARP_SIZE; + s_Data[pos] = idata; + + s_Data[pos] += s_Data[pos - 1]; + s_Data[pos] += s_Data[pos - 2]; + s_Data[pos] += s_Data[pos - 4]; + s_Data[pos] += s_Data[pos - 8]; + s_Data[pos] += s_Data[pos - 16]; + + return s_Data[pos]; + #endif + } + + template + __device__ __forceinline__ T warpScanExclusive(T idata, volatile T* s_Data, unsigned int tid) + { + return warpScanInclusive(idata, s_Data, tid) - idata; + } + + template + __device__ T blockScanInclusive(T idata, volatile T* s_Data, unsigned int tid) + { + if (tiNumScanThreads > OPENCV_CUDA_WARP_SIZE) + { + //Bottom-level inclusive warp scan + T warpResult = warpScanInclusive(idata, s_Data, tid); + + //Save top elements of each warp for exclusive warp scan + //sync to wait for warp scans to complete (because s_Data is being overwritten) + __syncthreads(); + if ((tid & (OPENCV_CUDA_WARP_SIZE - 1)) == (OPENCV_CUDA_WARP_SIZE - 1)) + { + s_Data[tid >> OPENCV_CUDA_LOG_WARP_SIZE] = warpResult; + } + + //wait for warp scans to complete + __syncthreads(); + + if (tid < (tiNumScanThreads / OPENCV_CUDA_WARP_SIZE) ) + { + //grab top warp elements + T val = s_Data[tid]; + //calculate exclusive scan and write back to shared memory + s_Data[tid] = warpScanExclusive(val, s_Data, tid); + } + + //return updated warp scans with exclusive scan results + __syncthreads(); + + return warpResult + s_Data[tid >> OPENCV_CUDA_LOG_WARP_SIZE]; + } + else + { + return warpScanInclusive(idata, s_Data, tid); + } + } +}}} + +//! @endcond + +#endif // OPENCV_CUDA_SCAN_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/simd_functions.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/simd_functions.hpp index 3d8c2e0d8e..406fed748a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/simd_functions.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/simd_functions.hpp @@ -1,869 +1,869 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -/* - * Copyright (c) 2013 NVIDIA Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 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. - * - * Neither the name of NVIDIA Corporation nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT HOLDER 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 OPENCV_CUDA_SIMD_FUNCTIONS_HPP -#define OPENCV_CUDA_SIMD_FUNCTIONS_HPP - -#include "common.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - // 2 - - static __device__ __forceinline__ unsigned int vadd2(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vadd2.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #elif __CUDA_ARCH__ >= 200 - asm("vadd.u32.u32.u32.sat %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vadd.u32.u32.u32.sat %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int s; - s = a ^ b; // sum bits - r = a + b; // actual sum - s = s ^ r; // determine carry-ins for each bit position - s = s & 0x00010000; // carry-in to high word (= carry-out from low word) - r = r - s; // subtract out carry-out from low word - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vsub2(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vsub2.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #elif __CUDA_ARCH__ >= 200 - asm("vsub.u32.u32.u32.sat %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vsub.u32.u32.u32.sat %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int s; - s = a ^ b; // sum bits - r = a - b; // actual sum - s = s ^ r; // determine carry-ins for each bit position - s = s & 0x00010000; // borrow to high word - r = r + s; // compensate for borrow from low word - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vabsdiff2(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vabsdiff2.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #elif __CUDA_ARCH__ >= 200 - asm("vabsdiff.u32.u32.u32.sat %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vabsdiff.u32.u32.u32.sat %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int s, t, u, v; - s = a & 0x0000ffff; // extract low halfword - r = b & 0x0000ffff; // extract low halfword - u = ::max(r, s); // maximum of low halfwords - v = ::min(r, s); // minimum of low halfwords - s = a & 0xffff0000; // extract high halfword - r = b & 0xffff0000; // extract high halfword - t = ::max(r, s); // maximum of high halfwords - s = ::min(r, s); // minimum of high halfwords - r = u | t; // maximum of both halfwords - s = v | s; // minimum of both halfwords - r = r - s; // |a - b| = max(a,b) - min(a,b); - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vavg2(unsigned int a, unsigned int b) - { - unsigned int r, s; - - // HAKMEM #23: a + b = 2 * (a & b) + (a ^ b) ==> - // (a + b) / 2 = (a & b) + ((a ^ b) >> 1) - s = a ^ b; - r = a & b; - s = s & 0xfffefffe; // ensure shift doesn't cross halfword boundaries - s = s >> 1; - s = r + s; - - return s; - } - - static __device__ __forceinline__ unsigned int vavrg2(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vavrg2.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - // HAKMEM #23: a + b = 2 * (a | b) - (a ^ b) ==> - // (a + b + 1) / 2 = (a | b) - ((a ^ b) >> 1) - unsigned int s; - s = a ^ b; - r = a | b; - s = s & 0xfffefffe; // ensure shift doesn't cross half-word boundaries - s = s >> 1; - r = r - s; - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vseteq2(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vset2.u32.u32.eq %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - // inspired by Alan Mycroft's null-byte detection algorithm: - // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) - unsigned int c; - r = a ^ b; // 0x0000 if a == b - c = r | 0x80008000; // set msbs, to catch carry out - r = r ^ c; // extract msbs, msb = 1 if r < 0x8000 - c = c - 0x00010001; // msb = 0, if r was 0x0000 or 0x8000 - c = r & ~c; // msb = 1, if r was 0x0000 - r = c >> 15; // convert to bool - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vcmpeq2(unsigned int a, unsigned int b) - { - unsigned int r, c; - - #if __CUDA_ARCH__ >= 300 - r = vseteq2(a, b); - c = r << 16; // convert bool - r = c - r; // into mask - #else - // inspired by Alan Mycroft's null-byte detection algorithm: - // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) - r = a ^ b; // 0x0000 if a == b - c = r | 0x80008000; // set msbs, to catch carry out - r = r ^ c; // extract msbs, msb = 1 if r < 0x8000 - c = c - 0x00010001; // msb = 0, if r was 0x0000 or 0x8000 - c = r & ~c; // msb = 1, if r was 0x0000 - r = c >> 15; // convert - r = c - r; // msbs to - r = c | r; // mask - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vsetge2(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vset2.u32.u32.ge %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int c; - asm("not.b32 %0, %0;" : "+r"(b)); - c = vavrg2(a, b); // (a + ~b + 1) / 2 = (a - b) / 2 - c = c & 0x80008000; // msb = carry-outs - r = c >> 15; // convert to bool - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vcmpge2(unsigned int a, unsigned int b) - { - unsigned int r, c; - - #if __CUDA_ARCH__ >= 300 - r = vsetge2(a, b); - c = r << 16; // convert bool - r = c - r; // into mask - #else - asm("not.b32 %0, %0;" : "+r"(b)); - c = vavrg2(a, b); // (a + ~b + 1) / 2 = (a - b) / 2 - c = c & 0x80008000; // msb = carry-outs - r = c >> 15; // convert - r = c - r; // msbs to - r = c | r; // mask - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vsetgt2(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vset2.u32.u32.gt %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int c; - asm("not.b32 %0, %0;" : "+r"(b)); - c = vavg2(a, b); // (a + ~b) / 2 = (a - b) / 2 [rounded down] - c = c & 0x80008000; // msbs = carry-outs - r = c >> 15; // convert to bool - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vcmpgt2(unsigned int a, unsigned int b) - { - unsigned int r, c; - - #if __CUDA_ARCH__ >= 300 - r = vsetgt2(a, b); - c = r << 16; // convert bool - r = c - r; // into mask - #else - asm("not.b32 %0, %0;" : "+r"(b)); - c = vavg2(a, b); // (a + ~b) / 2 = (a - b) / 2 [rounded down] - c = c & 0x80008000; // msbs = carry-outs - r = c >> 15; // convert - r = c - r; // msbs to - r = c | r; // mask - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vsetle2(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vset2.u32.u32.le %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int c; - asm("not.b32 %0, %0;" : "+r"(a)); - c = vavrg2(a, b); // (b + ~a + 1) / 2 = (b - a) / 2 - c = c & 0x80008000; // msb = carry-outs - r = c >> 15; // convert to bool - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vcmple2(unsigned int a, unsigned int b) - { - unsigned int r, c; - - #if __CUDA_ARCH__ >= 300 - r = vsetle2(a, b); - c = r << 16; // convert bool - r = c - r; // into mask - #else - asm("not.b32 %0, %0;" : "+r"(a)); - c = vavrg2(a, b); // (b + ~a + 1) / 2 = (b - a) / 2 - c = c & 0x80008000; // msb = carry-outs - r = c >> 15; // convert - r = c - r; // msbs to - r = c | r; // mask - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vsetlt2(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vset2.u32.u32.lt %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int c; - asm("not.b32 %0, %0;" : "+r"(a)); - c = vavg2(a, b); // (b + ~a) / 2 = (b - a) / 2 [rounded down] - c = c & 0x80008000; // msb = carry-outs - r = c >> 15; // convert to bool - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vcmplt2(unsigned int a, unsigned int b) - { - unsigned int r, c; - - #if __CUDA_ARCH__ >= 300 - r = vsetlt2(a, b); - c = r << 16; // convert bool - r = c - r; // into mask - #else - asm("not.b32 %0, %0;" : "+r"(a)); - c = vavg2(a, b); // (b + ~a) / 2 = (b - a) / 2 [rounded down] - c = c & 0x80008000; // msb = carry-outs - r = c >> 15; // convert - r = c - r; // msbs to - r = c | r; // mask - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vsetne2(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm ("vset2.u32.u32.ne %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - // inspired by Alan Mycroft's null-byte detection algorithm: - // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) - unsigned int c; - r = a ^ b; // 0x0000 if a == b - c = r | 0x80008000; // set msbs, to catch carry out - c = c - 0x00010001; // msb = 0, if r was 0x0000 or 0x8000 - c = r | c; // msb = 1, if r was not 0x0000 - c = c & 0x80008000; // extract msbs - r = c >> 15; // convert to bool - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vcmpne2(unsigned int a, unsigned int b) - { - unsigned int r, c; - - #if __CUDA_ARCH__ >= 300 - r = vsetne2(a, b); - c = r << 16; // convert bool - r = c - r; // into mask - #else - // inspired by Alan Mycroft's null-byte detection algorithm: - // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) - r = a ^ b; // 0x0000 if a == b - c = r | 0x80008000; // set msbs, to catch carry out - c = c - 0x00010001; // msb = 0, if r was 0x0000 or 0x8000 - c = r | c; // msb = 1, if r was not 0x0000 - c = c & 0x80008000; // extract msbs - r = c >> 15; // convert - r = c - r; // msbs to - r = c | r; // mask - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vmax2(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vmax2.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #elif __CUDA_ARCH__ >= 200 - asm("vmax.u32.u32.u32 %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vmax.u32.u32.u32 %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int s, t, u; - r = a & 0x0000ffff; // extract low halfword - s = b & 0x0000ffff; // extract low halfword - t = ::max(r, s); // maximum of low halfwords - r = a & 0xffff0000; // extract high halfword - s = b & 0xffff0000; // extract high halfword - u = ::max(r, s); // maximum of high halfwords - r = t | u; // combine halfword maximums - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vmin2(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vmin2.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #elif __CUDA_ARCH__ >= 200 - asm("vmin.u32.u32.u32 %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vmin.u32.u32.u32 %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int s, t, u; - r = a & 0x0000ffff; // extract low halfword - s = b & 0x0000ffff; // extract low halfword - t = ::min(r, s); // minimum of low halfwords - r = a & 0xffff0000; // extract high halfword - s = b & 0xffff0000; // extract high halfword - u = ::min(r, s); // minimum of high halfwords - r = t | u; // combine halfword minimums - #endif - - return r; - } - - // 4 - - static __device__ __forceinline__ unsigned int vadd4(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vadd4.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #elif __CUDA_ARCH__ >= 200 - asm("vadd.u32.u32.u32.sat %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vadd.u32.u32.u32.sat %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vadd.u32.u32.u32.sat %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vadd.u32.u32.u32.sat %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int s, t; - s = a ^ b; // sum bits - r = a & 0x7f7f7f7f; // clear msbs - t = b & 0x7f7f7f7f; // clear msbs - s = s & 0x80808080; // msb sum bits - r = r + t; // add without msbs, record carry-out in msbs - r = r ^ s; // sum of msb sum and carry-in bits, w/o carry-out - #endif /* __CUDA_ARCH__ >= 300 */ - - return r; - } - - static __device__ __forceinline__ unsigned int vsub4(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vsub4.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #elif __CUDA_ARCH__ >= 200 - asm("vsub.u32.u32.u32.sat %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vsub.u32.u32.u32.sat %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vsub.u32.u32.u32.sat %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vsub.u32.u32.u32.sat %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int s, t; - s = a ^ ~b; // inverted sum bits - r = a | 0x80808080; // set msbs - t = b & 0x7f7f7f7f; // clear msbs - s = s & 0x80808080; // inverted msb sum bits - r = r - t; // subtract w/o msbs, record inverted borrows in msb - r = r ^ s; // combine inverted msb sum bits and borrows - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vavg4(unsigned int a, unsigned int b) - { - unsigned int r, s; - - // HAKMEM #23: a + b = 2 * (a & b) + (a ^ b) ==> - // (a + b) / 2 = (a & b) + ((a ^ b) >> 1) - s = a ^ b; - r = a & b; - s = s & 0xfefefefe; // ensure following shift doesn't cross byte boundaries - s = s >> 1; - s = r + s; - - return s; - } - - static __device__ __forceinline__ unsigned int vavrg4(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vavrg4.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - // HAKMEM #23: a + b = 2 * (a | b) - (a ^ b) ==> - // (a + b + 1) / 2 = (a | b) - ((a ^ b) >> 1) - unsigned int c; - c = a ^ b; - r = a | b; - c = c & 0xfefefefe; // ensure following shift doesn't cross byte boundaries - c = c >> 1; - r = r - c; - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vseteq4(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vset4.u32.u32.eq %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - // inspired by Alan Mycroft's null-byte detection algorithm: - // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) - unsigned int c; - r = a ^ b; // 0x00 if a == b - c = r | 0x80808080; // set msbs, to catch carry out - r = r ^ c; // extract msbs, msb = 1 if r < 0x80 - c = c - 0x01010101; // msb = 0, if r was 0x00 or 0x80 - c = r & ~c; // msb = 1, if r was 0x00 - r = c >> 7; // convert to bool - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vcmpeq4(unsigned int a, unsigned int b) - { - unsigned int r, t; - - #if __CUDA_ARCH__ >= 300 - r = vseteq4(a, b); - t = r << 8; // convert bool - r = t - r; // to mask - #else - // inspired by Alan Mycroft's null-byte detection algorithm: - // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) - t = a ^ b; // 0x00 if a == b - r = t | 0x80808080; // set msbs, to catch carry out - t = t ^ r; // extract msbs, msb = 1 if t < 0x80 - r = r - 0x01010101; // msb = 0, if t was 0x00 or 0x80 - r = t & ~r; // msb = 1, if t was 0x00 - t = r >> 7; // build mask - t = r - t; // from - r = t | r; // msbs - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vsetle4(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vset4.u32.u32.le %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int c; - asm("not.b32 %0, %0;" : "+r"(a)); - c = vavrg4(a, b); // (b + ~a + 1) / 2 = (b - a) / 2 - c = c & 0x80808080; // msb = carry-outs - r = c >> 7; // convert to bool - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vcmple4(unsigned int a, unsigned int b) - { - unsigned int r, c; - - #if __CUDA_ARCH__ >= 300 - r = vsetle4(a, b); - c = r << 8; // convert bool - r = c - r; // to mask - #else - asm("not.b32 %0, %0;" : "+r"(a)); - c = vavrg4(a, b); // (b + ~a + 1) / 2 = (b - a) / 2 - c = c & 0x80808080; // msbs = carry-outs - r = c >> 7; // convert - r = c - r; // msbs to - r = c | r; // mask - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vsetlt4(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vset4.u32.u32.lt %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int c; - asm("not.b32 %0, %0;" : "+r"(a)); - c = vavg4(a, b); // (b + ~a) / 2 = (b - a) / 2 [rounded down] - c = c & 0x80808080; // msb = carry-outs - r = c >> 7; // convert to bool - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vcmplt4(unsigned int a, unsigned int b) - { - unsigned int r, c; - - #if __CUDA_ARCH__ >= 300 - r = vsetlt4(a, b); - c = r << 8; // convert bool - r = c - r; // to mask - #else - asm("not.b32 %0, %0;" : "+r"(a)); - c = vavg4(a, b); // (b + ~a) / 2 = (b - a) / 2 [rounded down] - c = c & 0x80808080; // msbs = carry-outs - r = c >> 7; // convert - r = c - r; // msbs to - r = c | r; // mask - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vsetge4(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vset4.u32.u32.ge %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int c; - asm("not.b32 %0, %0;" : "+r"(b)); - c = vavrg4(a, b); // (a + ~b + 1) / 2 = (a - b) / 2 - c = c & 0x80808080; // msb = carry-outs - r = c >> 7; // convert to bool - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vcmpge4(unsigned int a, unsigned int b) - { - unsigned int r, s; - - #if __CUDA_ARCH__ >= 300 - r = vsetge4(a, b); - s = r << 8; // convert bool - r = s - r; // to mask - #else - asm ("not.b32 %0,%0;" : "+r"(b)); - r = vavrg4 (a, b); // (a + ~b + 1) / 2 = (a - b) / 2 - r = r & 0x80808080; // msb = carry-outs - s = r >> 7; // build mask - s = r - s; // from - r = s | r; // msbs - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vsetgt4(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vset4.u32.u32.gt %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int c; - asm("not.b32 %0, %0;" : "+r"(b)); - c = vavg4(a, b); // (a + ~b) / 2 = (a - b) / 2 [rounded down] - c = c & 0x80808080; // msb = carry-outs - r = c >> 7; // convert to bool - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vcmpgt4(unsigned int a, unsigned int b) - { - unsigned int r, c; - - #if __CUDA_ARCH__ >= 300 - r = vsetgt4(a, b); - c = r << 8; // convert bool - r = c - r; // to mask - #else - asm("not.b32 %0, %0;" : "+r"(b)); - c = vavg4(a, b); // (a + ~b) / 2 = (a - b) / 2 [rounded down] - c = c & 0x80808080; // msb = carry-outs - r = c >> 7; // convert - r = c - r; // msbs to - r = c | r; // mask - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vsetne4(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vset4.u32.u32.ne %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - // inspired by Alan Mycroft's null-byte detection algorithm: - // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) - unsigned int c; - r = a ^ b; // 0x00 if a == b - c = r | 0x80808080; // set msbs, to catch carry out - c = c - 0x01010101; // msb = 0, if r was 0x00 or 0x80 - c = r | c; // msb = 1, if r was not 0x00 - c = c & 0x80808080; // extract msbs - r = c >> 7; // convert to bool - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vcmpne4(unsigned int a, unsigned int b) - { - unsigned int r, c; - - #if __CUDA_ARCH__ >= 300 - r = vsetne4(a, b); - c = r << 8; // convert bool - r = c - r; // to mask - #else - // inspired by Alan Mycroft's null-byte detection algorithm: - // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) - r = a ^ b; // 0x00 if a == b - c = r | 0x80808080; // set msbs, to catch carry out - c = c - 0x01010101; // msb = 0, if r was 0x00 or 0x80 - c = r | c; // msb = 1, if r was not 0x00 - c = c & 0x80808080; // extract msbs - r = c >> 7; // convert - r = c - r; // msbs to - r = c | r; // mask - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vabsdiff4(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vabsdiff4.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #elif __CUDA_ARCH__ >= 200 - asm("vabsdiff.u32.u32.u32.sat %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vabsdiff.u32.u32.u32.sat %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vabsdiff.u32.u32.u32.sat %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vabsdiff.u32.u32.u32.sat %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int s; - s = vcmpge4(a, b); // mask = 0xff if a >= b - r = a ^ b; // - s = (r & s) ^ b; // select a when a >= b, else select b => max(a,b) - r = s ^ r; // select a when b >= a, else select b => min(a,b) - r = s - r; // |a - b| = max(a,b) - min(a,b); - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vmax4(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vmax4.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #elif __CUDA_ARCH__ >= 200 - asm("vmax.u32.u32.u32 %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vmax.u32.u32.u32 %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vmax.u32.u32.u32 %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vmax.u32.u32.u32 %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int s; - s = vcmpge4(a, b); // mask = 0xff if a >= b - r = a & s; // select a when b >= a - s = b & ~s; // select b when b < a - r = r | s; // combine byte selections - #endif - - return r; // byte-wise unsigned maximum - } - - static __device__ __forceinline__ unsigned int vmin4(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vmin4.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #elif __CUDA_ARCH__ >= 200 - asm("vmin.u32.u32.u32 %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vmin.u32.u32.u32 %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vmin.u32.u32.u32 %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vmin.u32.u32.u32 %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int s; - s = vcmpge4(b, a); // mask = 0xff if a >= b - r = a & s; // select a when b >= a - s = b & ~s; // select b when b < a - r = r | s; // combine byte selections - #endif - - return r; - } -}}} - -//! @endcond - -#endif // OPENCV_CUDA_SIMD_FUNCTIONS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +/* + * Copyright (c) 2013 NVIDIA Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 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. + * + * Neither the name of NVIDIA Corporation nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT HOLDER 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 OPENCV_CUDA_SIMD_FUNCTIONS_HPP +#define OPENCV_CUDA_SIMD_FUNCTIONS_HPP + +#include "common.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + // 2 + + static __device__ __forceinline__ unsigned int vadd2(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vadd2.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #elif __CUDA_ARCH__ >= 200 + asm("vadd.u32.u32.u32.sat %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vadd.u32.u32.u32.sat %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int s; + s = a ^ b; // sum bits + r = a + b; // actual sum + s = s ^ r; // determine carry-ins for each bit position + s = s & 0x00010000; // carry-in to high word (= carry-out from low word) + r = r - s; // subtract out carry-out from low word + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vsub2(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vsub2.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #elif __CUDA_ARCH__ >= 200 + asm("vsub.u32.u32.u32.sat %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vsub.u32.u32.u32.sat %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int s; + s = a ^ b; // sum bits + r = a - b; // actual sum + s = s ^ r; // determine carry-ins for each bit position + s = s & 0x00010000; // borrow to high word + r = r + s; // compensate for borrow from low word + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vabsdiff2(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vabsdiff2.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #elif __CUDA_ARCH__ >= 200 + asm("vabsdiff.u32.u32.u32.sat %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vabsdiff.u32.u32.u32.sat %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int s, t, u, v; + s = a & 0x0000ffff; // extract low halfword + r = b & 0x0000ffff; // extract low halfword + u = ::max(r, s); // maximum of low halfwords + v = ::min(r, s); // minimum of low halfwords + s = a & 0xffff0000; // extract high halfword + r = b & 0xffff0000; // extract high halfword + t = ::max(r, s); // maximum of high halfwords + s = ::min(r, s); // minimum of high halfwords + r = u | t; // maximum of both halfwords + s = v | s; // minimum of both halfwords + r = r - s; // |a - b| = max(a,b) - min(a,b); + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vavg2(unsigned int a, unsigned int b) + { + unsigned int r, s; + + // HAKMEM #23: a + b = 2 * (a & b) + (a ^ b) ==> + // (a + b) / 2 = (a & b) + ((a ^ b) >> 1) + s = a ^ b; + r = a & b; + s = s & 0xfffefffe; // ensure shift doesn't cross halfword boundaries + s = s >> 1; + s = r + s; + + return s; + } + + static __device__ __forceinline__ unsigned int vavrg2(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vavrg2.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + // HAKMEM #23: a + b = 2 * (a | b) - (a ^ b) ==> + // (a + b + 1) / 2 = (a | b) - ((a ^ b) >> 1) + unsigned int s; + s = a ^ b; + r = a | b; + s = s & 0xfffefffe; // ensure shift doesn't cross half-word boundaries + s = s >> 1; + r = r - s; + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vseteq2(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vset2.u32.u32.eq %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + // inspired by Alan Mycroft's null-byte detection algorithm: + // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) + unsigned int c; + r = a ^ b; // 0x0000 if a == b + c = r | 0x80008000; // set msbs, to catch carry out + r = r ^ c; // extract msbs, msb = 1 if r < 0x8000 + c = c - 0x00010001; // msb = 0, if r was 0x0000 or 0x8000 + c = r & ~c; // msb = 1, if r was 0x0000 + r = c >> 15; // convert to bool + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vcmpeq2(unsigned int a, unsigned int b) + { + unsigned int r, c; + + #if __CUDA_ARCH__ >= 300 + r = vseteq2(a, b); + c = r << 16; // convert bool + r = c - r; // into mask + #else + // inspired by Alan Mycroft's null-byte detection algorithm: + // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) + r = a ^ b; // 0x0000 if a == b + c = r | 0x80008000; // set msbs, to catch carry out + r = r ^ c; // extract msbs, msb = 1 if r < 0x8000 + c = c - 0x00010001; // msb = 0, if r was 0x0000 or 0x8000 + c = r & ~c; // msb = 1, if r was 0x0000 + r = c >> 15; // convert + r = c - r; // msbs to + r = c | r; // mask + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vsetge2(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vset2.u32.u32.ge %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int c; + asm("not.b32 %0, %0;" : "+r"(b)); + c = vavrg2(a, b); // (a + ~b + 1) / 2 = (a - b) / 2 + c = c & 0x80008000; // msb = carry-outs + r = c >> 15; // convert to bool + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vcmpge2(unsigned int a, unsigned int b) + { + unsigned int r, c; + + #if __CUDA_ARCH__ >= 300 + r = vsetge2(a, b); + c = r << 16; // convert bool + r = c - r; // into mask + #else + asm("not.b32 %0, %0;" : "+r"(b)); + c = vavrg2(a, b); // (a + ~b + 1) / 2 = (a - b) / 2 + c = c & 0x80008000; // msb = carry-outs + r = c >> 15; // convert + r = c - r; // msbs to + r = c | r; // mask + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vsetgt2(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vset2.u32.u32.gt %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int c; + asm("not.b32 %0, %0;" : "+r"(b)); + c = vavg2(a, b); // (a + ~b) / 2 = (a - b) / 2 [rounded down] + c = c & 0x80008000; // msbs = carry-outs + r = c >> 15; // convert to bool + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vcmpgt2(unsigned int a, unsigned int b) + { + unsigned int r, c; + + #if __CUDA_ARCH__ >= 300 + r = vsetgt2(a, b); + c = r << 16; // convert bool + r = c - r; // into mask + #else + asm("not.b32 %0, %0;" : "+r"(b)); + c = vavg2(a, b); // (a + ~b) / 2 = (a - b) / 2 [rounded down] + c = c & 0x80008000; // msbs = carry-outs + r = c >> 15; // convert + r = c - r; // msbs to + r = c | r; // mask + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vsetle2(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vset2.u32.u32.le %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int c; + asm("not.b32 %0, %0;" : "+r"(a)); + c = vavrg2(a, b); // (b + ~a + 1) / 2 = (b - a) / 2 + c = c & 0x80008000; // msb = carry-outs + r = c >> 15; // convert to bool + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vcmple2(unsigned int a, unsigned int b) + { + unsigned int r, c; + + #if __CUDA_ARCH__ >= 300 + r = vsetle2(a, b); + c = r << 16; // convert bool + r = c - r; // into mask + #else + asm("not.b32 %0, %0;" : "+r"(a)); + c = vavrg2(a, b); // (b + ~a + 1) / 2 = (b - a) / 2 + c = c & 0x80008000; // msb = carry-outs + r = c >> 15; // convert + r = c - r; // msbs to + r = c | r; // mask + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vsetlt2(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vset2.u32.u32.lt %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int c; + asm("not.b32 %0, %0;" : "+r"(a)); + c = vavg2(a, b); // (b + ~a) / 2 = (b - a) / 2 [rounded down] + c = c & 0x80008000; // msb = carry-outs + r = c >> 15; // convert to bool + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vcmplt2(unsigned int a, unsigned int b) + { + unsigned int r, c; + + #if __CUDA_ARCH__ >= 300 + r = vsetlt2(a, b); + c = r << 16; // convert bool + r = c - r; // into mask + #else + asm("not.b32 %0, %0;" : "+r"(a)); + c = vavg2(a, b); // (b + ~a) / 2 = (b - a) / 2 [rounded down] + c = c & 0x80008000; // msb = carry-outs + r = c >> 15; // convert + r = c - r; // msbs to + r = c | r; // mask + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vsetne2(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm ("vset2.u32.u32.ne %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + // inspired by Alan Mycroft's null-byte detection algorithm: + // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) + unsigned int c; + r = a ^ b; // 0x0000 if a == b + c = r | 0x80008000; // set msbs, to catch carry out + c = c - 0x00010001; // msb = 0, if r was 0x0000 or 0x8000 + c = r | c; // msb = 1, if r was not 0x0000 + c = c & 0x80008000; // extract msbs + r = c >> 15; // convert to bool + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vcmpne2(unsigned int a, unsigned int b) + { + unsigned int r, c; + + #if __CUDA_ARCH__ >= 300 + r = vsetne2(a, b); + c = r << 16; // convert bool + r = c - r; // into mask + #else + // inspired by Alan Mycroft's null-byte detection algorithm: + // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) + r = a ^ b; // 0x0000 if a == b + c = r | 0x80008000; // set msbs, to catch carry out + c = c - 0x00010001; // msb = 0, if r was 0x0000 or 0x8000 + c = r | c; // msb = 1, if r was not 0x0000 + c = c & 0x80008000; // extract msbs + r = c >> 15; // convert + r = c - r; // msbs to + r = c | r; // mask + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vmax2(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vmax2.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #elif __CUDA_ARCH__ >= 200 + asm("vmax.u32.u32.u32 %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vmax.u32.u32.u32 %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int s, t, u; + r = a & 0x0000ffff; // extract low halfword + s = b & 0x0000ffff; // extract low halfword + t = ::max(r, s); // maximum of low halfwords + r = a & 0xffff0000; // extract high halfword + s = b & 0xffff0000; // extract high halfword + u = ::max(r, s); // maximum of high halfwords + r = t | u; // combine halfword maximums + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vmin2(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vmin2.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #elif __CUDA_ARCH__ >= 200 + asm("vmin.u32.u32.u32 %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vmin.u32.u32.u32 %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int s, t, u; + r = a & 0x0000ffff; // extract low halfword + s = b & 0x0000ffff; // extract low halfword + t = ::min(r, s); // minimum of low halfwords + r = a & 0xffff0000; // extract high halfword + s = b & 0xffff0000; // extract high halfword + u = ::min(r, s); // minimum of high halfwords + r = t | u; // combine halfword minimums + #endif + + return r; + } + + // 4 + + static __device__ __forceinline__ unsigned int vadd4(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vadd4.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #elif __CUDA_ARCH__ >= 200 + asm("vadd.u32.u32.u32.sat %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vadd.u32.u32.u32.sat %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vadd.u32.u32.u32.sat %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vadd.u32.u32.u32.sat %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int s, t; + s = a ^ b; // sum bits + r = a & 0x7f7f7f7f; // clear msbs + t = b & 0x7f7f7f7f; // clear msbs + s = s & 0x80808080; // msb sum bits + r = r + t; // add without msbs, record carry-out in msbs + r = r ^ s; // sum of msb sum and carry-in bits, w/o carry-out + #endif /* __CUDA_ARCH__ >= 300 */ + + return r; + } + + static __device__ __forceinline__ unsigned int vsub4(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vsub4.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #elif __CUDA_ARCH__ >= 200 + asm("vsub.u32.u32.u32.sat %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vsub.u32.u32.u32.sat %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vsub.u32.u32.u32.sat %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vsub.u32.u32.u32.sat %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int s, t; + s = a ^ ~b; // inverted sum bits + r = a | 0x80808080; // set msbs + t = b & 0x7f7f7f7f; // clear msbs + s = s & 0x80808080; // inverted msb sum bits + r = r - t; // subtract w/o msbs, record inverted borrows in msb + r = r ^ s; // combine inverted msb sum bits and borrows + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vavg4(unsigned int a, unsigned int b) + { + unsigned int r, s; + + // HAKMEM #23: a + b = 2 * (a & b) + (a ^ b) ==> + // (a + b) / 2 = (a & b) + ((a ^ b) >> 1) + s = a ^ b; + r = a & b; + s = s & 0xfefefefe; // ensure following shift doesn't cross byte boundaries + s = s >> 1; + s = r + s; + + return s; + } + + static __device__ __forceinline__ unsigned int vavrg4(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vavrg4.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + // HAKMEM #23: a + b = 2 * (a | b) - (a ^ b) ==> + // (a + b + 1) / 2 = (a | b) - ((a ^ b) >> 1) + unsigned int c; + c = a ^ b; + r = a | b; + c = c & 0xfefefefe; // ensure following shift doesn't cross byte boundaries + c = c >> 1; + r = r - c; + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vseteq4(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vset4.u32.u32.eq %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + // inspired by Alan Mycroft's null-byte detection algorithm: + // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) + unsigned int c; + r = a ^ b; // 0x00 if a == b + c = r | 0x80808080; // set msbs, to catch carry out + r = r ^ c; // extract msbs, msb = 1 if r < 0x80 + c = c - 0x01010101; // msb = 0, if r was 0x00 or 0x80 + c = r & ~c; // msb = 1, if r was 0x00 + r = c >> 7; // convert to bool + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vcmpeq4(unsigned int a, unsigned int b) + { + unsigned int r, t; + + #if __CUDA_ARCH__ >= 300 + r = vseteq4(a, b); + t = r << 8; // convert bool + r = t - r; // to mask + #else + // inspired by Alan Mycroft's null-byte detection algorithm: + // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) + t = a ^ b; // 0x00 if a == b + r = t | 0x80808080; // set msbs, to catch carry out + t = t ^ r; // extract msbs, msb = 1 if t < 0x80 + r = r - 0x01010101; // msb = 0, if t was 0x00 or 0x80 + r = t & ~r; // msb = 1, if t was 0x00 + t = r >> 7; // build mask + t = r - t; // from + r = t | r; // msbs + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vsetle4(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vset4.u32.u32.le %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int c; + asm("not.b32 %0, %0;" : "+r"(a)); + c = vavrg4(a, b); // (b + ~a + 1) / 2 = (b - a) / 2 + c = c & 0x80808080; // msb = carry-outs + r = c >> 7; // convert to bool + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vcmple4(unsigned int a, unsigned int b) + { + unsigned int r, c; + + #if __CUDA_ARCH__ >= 300 + r = vsetle4(a, b); + c = r << 8; // convert bool + r = c - r; // to mask + #else + asm("not.b32 %0, %0;" : "+r"(a)); + c = vavrg4(a, b); // (b + ~a + 1) / 2 = (b - a) / 2 + c = c & 0x80808080; // msbs = carry-outs + r = c >> 7; // convert + r = c - r; // msbs to + r = c | r; // mask + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vsetlt4(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vset4.u32.u32.lt %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int c; + asm("not.b32 %0, %0;" : "+r"(a)); + c = vavg4(a, b); // (b + ~a) / 2 = (b - a) / 2 [rounded down] + c = c & 0x80808080; // msb = carry-outs + r = c >> 7; // convert to bool + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vcmplt4(unsigned int a, unsigned int b) + { + unsigned int r, c; + + #if __CUDA_ARCH__ >= 300 + r = vsetlt4(a, b); + c = r << 8; // convert bool + r = c - r; // to mask + #else + asm("not.b32 %0, %0;" : "+r"(a)); + c = vavg4(a, b); // (b + ~a) / 2 = (b - a) / 2 [rounded down] + c = c & 0x80808080; // msbs = carry-outs + r = c >> 7; // convert + r = c - r; // msbs to + r = c | r; // mask + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vsetge4(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vset4.u32.u32.ge %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int c; + asm("not.b32 %0, %0;" : "+r"(b)); + c = vavrg4(a, b); // (a + ~b + 1) / 2 = (a - b) / 2 + c = c & 0x80808080; // msb = carry-outs + r = c >> 7; // convert to bool + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vcmpge4(unsigned int a, unsigned int b) + { + unsigned int r, s; + + #if __CUDA_ARCH__ >= 300 + r = vsetge4(a, b); + s = r << 8; // convert bool + r = s - r; // to mask + #else + asm ("not.b32 %0,%0;" : "+r"(b)); + r = vavrg4 (a, b); // (a + ~b + 1) / 2 = (a - b) / 2 + r = r & 0x80808080; // msb = carry-outs + s = r >> 7; // build mask + s = r - s; // from + r = s | r; // msbs + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vsetgt4(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vset4.u32.u32.gt %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int c; + asm("not.b32 %0, %0;" : "+r"(b)); + c = vavg4(a, b); // (a + ~b) / 2 = (a - b) / 2 [rounded down] + c = c & 0x80808080; // msb = carry-outs + r = c >> 7; // convert to bool + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vcmpgt4(unsigned int a, unsigned int b) + { + unsigned int r, c; + + #if __CUDA_ARCH__ >= 300 + r = vsetgt4(a, b); + c = r << 8; // convert bool + r = c - r; // to mask + #else + asm("not.b32 %0, %0;" : "+r"(b)); + c = vavg4(a, b); // (a + ~b) / 2 = (a - b) / 2 [rounded down] + c = c & 0x80808080; // msb = carry-outs + r = c >> 7; // convert + r = c - r; // msbs to + r = c | r; // mask + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vsetne4(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vset4.u32.u32.ne %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + // inspired by Alan Mycroft's null-byte detection algorithm: + // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) + unsigned int c; + r = a ^ b; // 0x00 if a == b + c = r | 0x80808080; // set msbs, to catch carry out + c = c - 0x01010101; // msb = 0, if r was 0x00 or 0x80 + c = r | c; // msb = 1, if r was not 0x00 + c = c & 0x80808080; // extract msbs + r = c >> 7; // convert to bool + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vcmpne4(unsigned int a, unsigned int b) + { + unsigned int r, c; + + #if __CUDA_ARCH__ >= 300 + r = vsetne4(a, b); + c = r << 8; // convert bool + r = c - r; // to mask + #else + // inspired by Alan Mycroft's null-byte detection algorithm: + // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) + r = a ^ b; // 0x00 if a == b + c = r | 0x80808080; // set msbs, to catch carry out + c = c - 0x01010101; // msb = 0, if r was 0x00 or 0x80 + c = r | c; // msb = 1, if r was not 0x00 + c = c & 0x80808080; // extract msbs + r = c >> 7; // convert + r = c - r; // msbs to + r = c | r; // mask + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vabsdiff4(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vabsdiff4.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #elif __CUDA_ARCH__ >= 200 + asm("vabsdiff.u32.u32.u32.sat %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vabsdiff.u32.u32.u32.sat %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vabsdiff.u32.u32.u32.sat %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vabsdiff.u32.u32.u32.sat %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int s; + s = vcmpge4(a, b); // mask = 0xff if a >= b + r = a ^ b; // + s = (r & s) ^ b; // select a when a >= b, else select b => max(a,b) + r = s ^ r; // select a when b >= a, else select b => min(a,b) + r = s - r; // |a - b| = max(a,b) - min(a,b); + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vmax4(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vmax4.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #elif __CUDA_ARCH__ >= 200 + asm("vmax.u32.u32.u32 %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vmax.u32.u32.u32 %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vmax.u32.u32.u32 %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vmax.u32.u32.u32 %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int s; + s = vcmpge4(a, b); // mask = 0xff if a >= b + r = a & s; // select a when b >= a + s = b & ~s; // select b when b < a + r = r | s; // combine byte selections + #endif + + return r; // byte-wise unsigned maximum + } + + static __device__ __forceinline__ unsigned int vmin4(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vmin4.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #elif __CUDA_ARCH__ >= 200 + asm("vmin.u32.u32.u32 %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vmin.u32.u32.u32 %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vmin.u32.u32.u32 %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vmin.u32.u32.u32 %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int s; + s = vcmpge4(b, a); // mask = 0xff if a >= b + r = a & s; // select a when b >= a + s = b & ~s; // select b when b < a + r = r | s; // combine byte selections + #endif + + return r; + } +}}} + +//! @endcond + +#endif // OPENCV_CUDA_SIMD_FUNCTIONS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/transform.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/transform.hpp index 42aa6ea170..fd4fb6f0c6 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/transform.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/transform.hpp @@ -1,75 +1,75 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_TRANSFORM_HPP -#define OPENCV_CUDA_TRANSFORM_HPP - -#include "common.hpp" -#include "utility.hpp" -#include "detail/transform_detail.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - template - static inline void transform(PtrStepSz src, PtrStepSz dst, UnOp op, const Mask& mask, cudaStream_t stream) - { - typedef TransformFunctorTraits ft; - transform_detail::TransformDispatcher::cn == 1 && VecTraits::cn == 1 && ft::smart_shift != 1>::call(src, dst, op, mask, stream); - } - - template - static inline void transform(PtrStepSz src1, PtrStepSz src2, PtrStepSz dst, BinOp op, const Mask& mask, cudaStream_t stream) - { - typedef TransformFunctorTraits ft; - transform_detail::TransformDispatcher::cn == 1 && VecTraits::cn == 1 && VecTraits::cn == 1 && ft::smart_shift != 1>::call(src1, src2, dst, op, mask, stream); - } -}}} - -//! @endcond - -#endif // OPENCV_CUDA_TRANSFORM_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_TRANSFORM_HPP +#define OPENCV_CUDA_TRANSFORM_HPP + +#include "common.hpp" +#include "utility.hpp" +#include "detail/transform_detail.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + template + static inline void transform(PtrStepSz src, PtrStepSz dst, UnOp op, const Mask& mask, cudaStream_t stream) + { + typedef TransformFunctorTraits ft; + transform_detail::TransformDispatcher::cn == 1 && VecTraits::cn == 1 && ft::smart_shift != 1>::call(src, dst, op, mask, stream); + } + + template + static inline void transform(PtrStepSz src1, PtrStepSz src2, PtrStepSz dst, BinOp op, const Mask& mask, cudaStream_t stream) + { + typedef TransformFunctorTraits ft; + transform_detail::TransformDispatcher::cn == 1 && VecTraits::cn == 1 && VecTraits::cn == 1 && ft::smart_shift != 1>::call(src1, src2, dst, op, mask, stream); + } +}}} + +//! @endcond + +#endif // OPENCV_CUDA_TRANSFORM_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/type_traits.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/type_traits.hpp index 8b7a3fd168..e7faa905a0 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/type_traits.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/type_traits.hpp @@ -1,90 +1,90 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_TYPE_TRAITS_HPP -#define OPENCV_CUDA_TYPE_TRAITS_HPP - -#include "detail/type_traits_detail.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - template struct IsSimpleParameter - { - enum {value = type_traits_detail::IsIntegral::value || type_traits_detail::IsFloat::value || - type_traits_detail::PointerTraits::type>::value}; - }; - - template struct TypeTraits - { - typedef typename type_traits_detail::UnConst::type NonConstType; - typedef typename type_traits_detail::UnVolatile::type NonVolatileType; - typedef typename type_traits_detail::UnVolatile::type>::type UnqualifiedType; - typedef typename type_traits_detail::PointerTraits::type PointeeType; - typedef typename type_traits_detail::ReferenceTraits::type ReferredType; - - enum { isConst = type_traits_detail::UnConst::value }; - enum { isVolatile = type_traits_detail::UnVolatile::value }; - - enum { isReference = type_traits_detail::ReferenceTraits::value }; - enum { isPointer = type_traits_detail::PointerTraits::type>::value }; - - enum { isUnsignedInt = type_traits_detail::IsUnsignedIntegral::value }; - enum { isSignedInt = type_traits_detail::IsSignedIntergral::value }; - enum { isIntegral = type_traits_detail::IsIntegral::value }; - enum { isFloat = type_traits_detail::IsFloat::value }; - enum { isArith = isIntegral || isFloat }; - enum { isVec = type_traits_detail::IsVec::value }; - - typedef typename type_traits_detail::Select::value, - T, typename type_traits_detail::AddParameterType::type>::type ParameterType; - }; -}}} - -//! @endcond - -#endif // OPENCV_CUDA_TYPE_TRAITS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_TYPE_TRAITS_HPP +#define OPENCV_CUDA_TYPE_TRAITS_HPP + +#include "detail/type_traits_detail.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + template struct IsSimpleParameter + { + enum {value = type_traits_detail::IsIntegral::value || type_traits_detail::IsFloat::value || + type_traits_detail::PointerTraits::type>::value}; + }; + + template struct TypeTraits + { + typedef typename type_traits_detail::UnConst::type NonConstType; + typedef typename type_traits_detail::UnVolatile::type NonVolatileType; + typedef typename type_traits_detail::UnVolatile::type>::type UnqualifiedType; + typedef typename type_traits_detail::PointerTraits::type PointeeType; + typedef typename type_traits_detail::ReferenceTraits::type ReferredType; + + enum { isConst = type_traits_detail::UnConst::value }; + enum { isVolatile = type_traits_detail::UnVolatile::value }; + + enum { isReference = type_traits_detail::ReferenceTraits::value }; + enum { isPointer = type_traits_detail::PointerTraits::type>::value }; + + enum { isUnsignedInt = type_traits_detail::IsUnsignedIntegral::value }; + enum { isSignedInt = type_traits_detail::IsSignedIntergral::value }; + enum { isIntegral = type_traits_detail::IsIntegral::value }; + enum { isFloat = type_traits_detail::IsFloat::value }; + enum { isArith = isIntegral || isFloat }; + enum { isVec = type_traits_detail::IsVec::value }; + + typedef typename type_traits_detail::Select::value, + T, typename type_traits_detail::AddParameterType::type>::type ParameterType; + }; +}}} + +//! @endcond + +#endif // OPENCV_CUDA_TYPE_TRAITS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/utility.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/utility.hpp index 7f5db48a50..525419265c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/utility.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/utility.hpp @@ -1,230 +1,230 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_UTILITY_HPP -#define OPENCV_CUDA_UTILITY_HPP - -#include "saturate_cast.hpp" -#include "datamov_utils.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - struct CV_EXPORTS ThrustAllocator - { - typedef uchar value_type; - virtual ~ThrustAllocator(); - virtual __device__ __host__ uchar* allocate(size_t numBytes) = 0; - virtual __device__ __host__ void deallocate(uchar* ptr, size_t numBytes) = 0; - static ThrustAllocator& getAllocator(); - static void setAllocator(ThrustAllocator* allocator); - }; - #define OPENCV_CUDA_LOG_WARP_SIZE (5) - #define OPENCV_CUDA_WARP_SIZE (1 << OPENCV_CUDA_LOG_WARP_SIZE) - #define OPENCV_CUDA_LOG_MEM_BANKS ((__CUDA_ARCH__ >= 200) ? 5 : 4) // 32 banks on fermi, 16 on tesla - #define OPENCV_CUDA_MEM_BANKS (1 << OPENCV_CUDA_LOG_MEM_BANKS) - - /////////////////////////////////////////////////////////////////////////////// - // swap - - template void __device__ __host__ __forceinline__ swap(T& a, T& b) - { - const T temp = a; - a = b; - b = temp; - } - - /////////////////////////////////////////////////////////////////////////////// - // Mask Reader - - struct SingleMask - { - explicit __host__ __device__ __forceinline__ SingleMask(PtrStepb mask_) : mask(mask_) {} - __host__ __device__ __forceinline__ SingleMask(const SingleMask& mask_): mask(mask_.mask){} - - __device__ __forceinline__ bool operator()(int y, int x) const - { - return mask.ptr(y)[x] != 0; - } - - PtrStepb mask; - }; - - struct SingleMaskChannels - { - __host__ __device__ __forceinline__ SingleMaskChannels(PtrStepb mask_, int channels_) - : mask(mask_), channels(channels_) {} - __host__ __device__ __forceinline__ SingleMaskChannels(const SingleMaskChannels& mask_) - :mask(mask_.mask), channels(mask_.channels){} - - __device__ __forceinline__ bool operator()(int y, int x) const - { - return mask.ptr(y)[x / channels] != 0; - } - - PtrStepb mask; - int channels; - }; - - struct MaskCollection - { - explicit __host__ __device__ __forceinline__ MaskCollection(PtrStepb* maskCollection_) - : maskCollection(maskCollection_) {} - - __device__ __forceinline__ MaskCollection(const MaskCollection& masks_) - : maskCollection(masks_.maskCollection), curMask(masks_.curMask){} - - __device__ __forceinline__ void next() - { - curMask = *maskCollection++; - } - __device__ __forceinline__ void setMask(int z) - { - curMask = maskCollection[z]; - } - - __device__ __forceinline__ bool operator()(int y, int x) const - { - uchar val; - return curMask.data == 0 || (ForceGlob::Load(curMask.ptr(y), x, val), (val != 0)); - } - - const PtrStepb* maskCollection; - PtrStepb curMask; - }; - - struct WithOutMask - { - __host__ __device__ __forceinline__ WithOutMask(){} - __host__ __device__ __forceinline__ WithOutMask(const WithOutMask&){} - - __device__ __forceinline__ void next() const - { - } - __device__ __forceinline__ void setMask(int) const - { - } - - __device__ __forceinline__ bool operator()(int, int) const - { - return true; - } - - __device__ __forceinline__ bool operator()(int, int, int) const - { - return true; - } - - static __device__ __forceinline__ bool check(int, int) - { - return true; - } - - static __device__ __forceinline__ bool check(int, int, int) - { - return true; - } - }; - - /////////////////////////////////////////////////////////////////////////////// - // Solve linear system - - // solve 2x2 linear system Ax=b - template __device__ __forceinline__ bool solve2x2(const T A[2][2], const T b[2], T x[2]) - { - T det = A[0][0] * A[1][1] - A[1][0] * A[0][1]; - - if (det != 0) - { - double invdet = 1.0 / det; - - x[0] = saturate_cast(invdet * (b[0] * A[1][1] - b[1] * A[0][1])); - - x[1] = saturate_cast(invdet * (A[0][0] * b[1] - A[1][0] * b[0])); - - return true; - } - - return false; - } - - // solve 3x3 linear system Ax=b - template __device__ __forceinline__ bool solve3x3(const T A[3][3], const T b[3], T x[3]) - { - T det = A[0][0] * (A[1][1] * A[2][2] - A[1][2] * A[2][1]) - - A[0][1] * (A[1][0] * A[2][2] - A[1][2] * A[2][0]) - + A[0][2] * (A[1][0] * A[2][1] - A[1][1] * A[2][0]); - - if (det != 0) - { - double invdet = 1.0 / det; - - x[0] = saturate_cast(invdet * - (b[0] * (A[1][1] * A[2][2] - A[1][2] * A[2][1]) - - A[0][1] * (b[1] * A[2][2] - A[1][2] * b[2] ) + - A[0][2] * (b[1] * A[2][1] - A[1][1] * b[2] ))); - - x[1] = saturate_cast(invdet * - (A[0][0] * (b[1] * A[2][2] - A[1][2] * b[2] ) - - b[0] * (A[1][0] * A[2][2] - A[1][2] * A[2][0]) + - A[0][2] * (A[1][0] * b[2] - b[1] * A[2][0]))); - - x[2] = saturate_cast(invdet * - (A[0][0] * (A[1][1] * b[2] - b[1] * A[2][1]) - - A[0][1] * (A[1][0] * b[2] - b[1] * A[2][0]) + - b[0] * (A[1][0] * A[2][1] - A[1][1] * A[2][0]))); - - return true; - } - - return false; - } -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif // OPENCV_CUDA_UTILITY_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_UTILITY_HPP +#define OPENCV_CUDA_UTILITY_HPP + +#include "saturate_cast.hpp" +#include "datamov_utils.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + struct CV_EXPORTS ThrustAllocator + { + typedef uchar value_type; + virtual ~ThrustAllocator(); + virtual __device__ __host__ uchar* allocate(size_t numBytes) = 0; + virtual __device__ __host__ void deallocate(uchar* ptr, size_t numBytes) = 0; + static ThrustAllocator& getAllocator(); + static void setAllocator(ThrustAllocator* allocator); + }; + #define OPENCV_CUDA_LOG_WARP_SIZE (5) + #define OPENCV_CUDA_WARP_SIZE (1 << OPENCV_CUDA_LOG_WARP_SIZE) + #define OPENCV_CUDA_LOG_MEM_BANKS ((__CUDA_ARCH__ >= 200) ? 5 : 4) // 32 banks on fermi, 16 on tesla + #define OPENCV_CUDA_MEM_BANKS (1 << OPENCV_CUDA_LOG_MEM_BANKS) + + /////////////////////////////////////////////////////////////////////////////// + // swap + + template void __device__ __host__ __forceinline__ swap(T& a, T& b) + { + const T temp = a; + a = b; + b = temp; + } + + /////////////////////////////////////////////////////////////////////////////// + // Mask Reader + + struct SingleMask + { + explicit __host__ __device__ __forceinline__ SingleMask(PtrStepb mask_) : mask(mask_) {} + __host__ __device__ __forceinline__ SingleMask(const SingleMask& mask_): mask(mask_.mask){} + + __device__ __forceinline__ bool operator()(int y, int x) const + { + return mask.ptr(y)[x] != 0; + } + + PtrStepb mask; + }; + + struct SingleMaskChannels + { + __host__ __device__ __forceinline__ SingleMaskChannels(PtrStepb mask_, int channels_) + : mask(mask_), channels(channels_) {} + __host__ __device__ __forceinline__ SingleMaskChannels(const SingleMaskChannels& mask_) + :mask(mask_.mask), channels(mask_.channels){} + + __device__ __forceinline__ bool operator()(int y, int x) const + { + return mask.ptr(y)[x / channels] != 0; + } + + PtrStepb mask; + int channels; + }; + + struct MaskCollection + { + explicit __host__ __device__ __forceinline__ MaskCollection(PtrStepb* maskCollection_) + : maskCollection(maskCollection_) {} + + __device__ __forceinline__ MaskCollection(const MaskCollection& masks_) + : maskCollection(masks_.maskCollection), curMask(masks_.curMask){} + + __device__ __forceinline__ void next() + { + curMask = *maskCollection++; + } + __device__ __forceinline__ void setMask(int z) + { + curMask = maskCollection[z]; + } + + __device__ __forceinline__ bool operator()(int y, int x) const + { + uchar val; + return curMask.data == 0 || (ForceGlob::Load(curMask.ptr(y), x, val), (val != 0)); + } + + const PtrStepb* maskCollection; + PtrStepb curMask; + }; + + struct WithOutMask + { + __host__ __device__ __forceinline__ WithOutMask(){} + __host__ __device__ __forceinline__ WithOutMask(const WithOutMask&){} + + __device__ __forceinline__ void next() const + { + } + __device__ __forceinline__ void setMask(int) const + { + } + + __device__ __forceinline__ bool operator()(int, int) const + { + return true; + } + + __device__ __forceinline__ bool operator()(int, int, int) const + { + return true; + } + + static __device__ __forceinline__ bool check(int, int) + { + return true; + } + + static __device__ __forceinline__ bool check(int, int, int) + { + return true; + } + }; + + /////////////////////////////////////////////////////////////////////////////// + // Solve linear system + + // solve 2x2 linear system Ax=b + template __device__ __forceinline__ bool solve2x2(const T A[2][2], const T b[2], T x[2]) + { + T det = A[0][0] * A[1][1] - A[1][0] * A[0][1]; + + if (det != 0) + { + double invdet = 1.0 / det; + + x[0] = saturate_cast(invdet * (b[0] * A[1][1] - b[1] * A[0][1])); + + x[1] = saturate_cast(invdet * (A[0][0] * b[1] - A[1][0] * b[0])); + + return true; + } + + return false; + } + + // solve 3x3 linear system Ax=b + template __device__ __forceinline__ bool solve3x3(const T A[3][3], const T b[3], T x[3]) + { + T det = A[0][0] * (A[1][1] * A[2][2] - A[1][2] * A[2][1]) + - A[0][1] * (A[1][0] * A[2][2] - A[1][2] * A[2][0]) + + A[0][2] * (A[1][0] * A[2][1] - A[1][1] * A[2][0]); + + if (det != 0) + { + double invdet = 1.0 / det; + + x[0] = saturate_cast(invdet * + (b[0] * (A[1][1] * A[2][2] - A[1][2] * A[2][1]) - + A[0][1] * (b[1] * A[2][2] - A[1][2] * b[2] ) + + A[0][2] * (b[1] * A[2][1] - A[1][1] * b[2] ))); + + x[1] = saturate_cast(invdet * + (A[0][0] * (b[1] * A[2][2] - A[1][2] * b[2] ) - + b[0] * (A[1][0] * A[2][2] - A[1][2] * A[2][0]) + + A[0][2] * (A[1][0] * b[2] - b[1] * A[2][0]))); + + x[2] = saturate_cast(invdet * + (A[0][0] * (A[1][1] * b[2] - b[1] * A[2][1]) - + A[0][1] * (A[1][0] * b[2] - b[1] * A[2][0]) + + b[0] * (A[1][0] * A[2][1] - A[1][1] * A[2][0]))); + + return true; + } + + return false; + } +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif // OPENCV_CUDA_UTILITY_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/vec_distance.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/vec_distance.hpp index ef6e51087d..64a372bb09 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/vec_distance.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/vec_distance.hpp @@ -1,232 +1,232 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_VEC_DISTANCE_HPP -#define OPENCV_CUDA_VEC_DISTANCE_HPP - -#include "reduce.hpp" -#include "functional.hpp" -#include "detail/vec_distance_detail.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - template struct L1Dist - { - typedef int value_type; - typedef int result_type; - - __device__ __forceinline__ L1Dist() : mySum(0) {} - - __device__ __forceinline__ void reduceIter(int val1, int val2) - { - mySum = __sad(val1, val2, mySum); - } - - template __device__ __forceinline__ void reduceAll(int* smem, int tid) - { - reduce(smem, mySum, tid, plus()); - } - - __device__ __forceinline__ operator int() const - { - return mySum; - } - - int mySum; - }; - template <> struct L1Dist - { - typedef float value_type; - typedef float result_type; - - __device__ __forceinline__ L1Dist() : mySum(0.0f) {} - - __device__ __forceinline__ void reduceIter(float val1, float val2) - { - mySum += ::fabs(val1 - val2); - } - - template __device__ __forceinline__ void reduceAll(float* smem, int tid) - { - reduce(smem, mySum, tid, plus()); - } - - __device__ __forceinline__ operator float() const - { - return mySum; - } - - float mySum; - }; - - struct L2Dist - { - typedef float value_type; - typedef float result_type; - - __device__ __forceinline__ L2Dist() : mySum(0.0f) {} - - __device__ __forceinline__ void reduceIter(float val1, float val2) - { - float reg = val1 - val2; - mySum += reg * reg; - } - - template __device__ __forceinline__ void reduceAll(float* smem, int tid) - { - reduce(smem, mySum, tid, plus()); - } - - __device__ __forceinline__ operator float() const - { - return sqrtf(mySum); - } - - float mySum; - }; - - struct HammingDist - { - typedef int value_type; - typedef int result_type; - - __device__ __forceinline__ HammingDist() : mySum(0) {} - - __device__ __forceinline__ void reduceIter(int val1, int val2) - { - mySum += __popc(val1 ^ val2); - } - - template __device__ __forceinline__ void reduceAll(int* smem, int tid) - { - reduce(smem, mySum, tid, plus()); - } - - __device__ __forceinline__ operator int() const - { - return mySum; - } - - int mySum; - }; - - // calc distance between two vectors in global memory - template - __device__ void calcVecDiffGlobal(const T1* vec1, const T2* vec2, int len, Dist& dist, typename Dist::result_type* smem, int tid) - { - for (int i = tid; i < len; i += THREAD_DIM) - { - T1 val1; - ForceGlob::Load(vec1, i, val1); - - T2 val2; - ForceGlob::Load(vec2, i, val2); - - dist.reduceIter(val1, val2); - } - - dist.reduceAll(smem, tid); - } - - // calc distance between two vectors, first vector is cached in register or shared memory, second vector is in global memory - template - __device__ __forceinline__ void calcVecDiffCached(const T1* vecCached, const T2* vecGlob, int len, Dist& dist, typename Dist::result_type* smem, int tid) - { - vec_distance_detail::VecDiffCachedCalculator::calc(vecCached, vecGlob, len, dist, tid); - - dist.reduceAll(smem, tid); - } - - // calc distance between two vectors in global memory - template struct VecDiffGlobal - { - explicit __device__ __forceinline__ VecDiffGlobal(const T1* vec1_, int = 0, void* = 0, int = 0, int = 0) - { - vec1 = vec1_; - } - - template - __device__ __forceinline__ void calc(const T2* vec2, int len, Dist& dist, typename Dist::result_type* smem, int tid) const - { - calcVecDiffGlobal(vec1, vec2, len, dist, smem, tid); - } - - const T1* vec1; - }; - - // calc distance between two vectors, first vector is cached in register memory, second vector is in global memory - template struct VecDiffCachedRegister - { - template __device__ __forceinline__ VecDiffCachedRegister(const T1* vec1, int len, U* smem, int glob_tid, int tid) - { - if (glob_tid < len) - smem[glob_tid] = vec1[glob_tid]; - __syncthreads(); - - U* vec1ValsPtr = vec1Vals; - - #pragma unroll - for (int i = tid; i < MAX_LEN; i += THREAD_DIM) - *vec1ValsPtr++ = smem[i]; - - __syncthreads(); - } - - template - __device__ __forceinline__ void calc(const T2* vec2, int len, Dist& dist, typename Dist::result_type* smem, int tid) const - { - calcVecDiffCached(vec1Vals, vec2, len, dist, smem, tid); - } - - U vec1Vals[MAX_LEN / THREAD_DIM]; - }; -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif // OPENCV_CUDA_VEC_DISTANCE_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_VEC_DISTANCE_HPP +#define OPENCV_CUDA_VEC_DISTANCE_HPP + +#include "reduce.hpp" +#include "functional.hpp" +#include "detail/vec_distance_detail.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + template struct L1Dist + { + typedef int value_type; + typedef int result_type; + + __device__ __forceinline__ L1Dist() : mySum(0) {} + + __device__ __forceinline__ void reduceIter(int val1, int val2) + { + mySum = __sad(val1, val2, mySum); + } + + template __device__ __forceinline__ void reduceAll(int* smem, int tid) + { + reduce(smem, mySum, tid, plus()); + } + + __device__ __forceinline__ operator int() const + { + return mySum; + } + + int mySum; + }; + template <> struct L1Dist + { + typedef float value_type; + typedef float result_type; + + __device__ __forceinline__ L1Dist() : mySum(0.0f) {} + + __device__ __forceinline__ void reduceIter(float val1, float val2) + { + mySum += ::fabs(val1 - val2); + } + + template __device__ __forceinline__ void reduceAll(float* smem, int tid) + { + reduce(smem, mySum, tid, plus()); + } + + __device__ __forceinline__ operator float() const + { + return mySum; + } + + float mySum; + }; + + struct L2Dist + { + typedef float value_type; + typedef float result_type; + + __device__ __forceinline__ L2Dist() : mySum(0.0f) {} + + __device__ __forceinline__ void reduceIter(float val1, float val2) + { + float reg = val1 - val2; + mySum += reg * reg; + } + + template __device__ __forceinline__ void reduceAll(float* smem, int tid) + { + reduce(smem, mySum, tid, plus()); + } + + __device__ __forceinline__ operator float() const + { + return sqrtf(mySum); + } + + float mySum; + }; + + struct HammingDist + { + typedef int value_type; + typedef int result_type; + + __device__ __forceinline__ HammingDist() : mySum(0) {} + + __device__ __forceinline__ void reduceIter(int val1, int val2) + { + mySum += __popc(val1 ^ val2); + } + + template __device__ __forceinline__ void reduceAll(int* smem, int tid) + { + reduce(smem, mySum, tid, plus()); + } + + __device__ __forceinline__ operator int() const + { + return mySum; + } + + int mySum; + }; + + // calc distance between two vectors in global memory + template + __device__ void calcVecDiffGlobal(const T1* vec1, const T2* vec2, int len, Dist& dist, typename Dist::result_type* smem, int tid) + { + for (int i = tid; i < len; i += THREAD_DIM) + { + T1 val1; + ForceGlob::Load(vec1, i, val1); + + T2 val2; + ForceGlob::Load(vec2, i, val2); + + dist.reduceIter(val1, val2); + } + + dist.reduceAll(smem, tid); + } + + // calc distance between two vectors, first vector is cached in register or shared memory, second vector is in global memory + template + __device__ __forceinline__ void calcVecDiffCached(const T1* vecCached, const T2* vecGlob, int len, Dist& dist, typename Dist::result_type* smem, int tid) + { + vec_distance_detail::VecDiffCachedCalculator::calc(vecCached, vecGlob, len, dist, tid); + + dist.reduceAll(smem, tid); + } + + // calc distance between two vectors in global memory + template struct VecDiffGlobal + { + explicit __device__ __forceinline__ VecDiffGlobal(const T1* vec1_, int = 0, void* = 0, int = 0, int = 0) + { + vec1 = vec1_; + } + + template + __device__ __forceinline__ void calc(const T2* vec2, int len, Dist& dist, typename Dist::result_type* smem, int tid) const + { + calcVecDiffGlobal(vec1, vec2, len, dist, smem, tid); + } + + const T1* vec1; + }; + + // calc distance between two vectors, first vector is cached in register memory, second vector is in global memory + template struct VecDiffCachedRegister + { + template __device__ __forceinline__ VecDiffCachedRegister(const T1* vec1, int len, U* smem, int glob_tid, int tid) + { + if (glob_tid < len) + smem[glob_tid] = vec1[glob_tid]; + __syncthreads(); + + U* vec1ValsPtr = vec1Vals; + + #pragma unroll + for (int i = tid; i < MAX_LEN; i += THREAD_DIM) + *vec1ValsPtr++ = smem[i]; + + __syncthreads(); + } + + template + __device__ __forceinline__ void calc(const T2* vec2, int len, Dist& dist, typename Dist::result_type* smem, int tid) const + { + calcVecDiffCached(vec1Vals, vec2, len, dist, smem, tid); + } + + U vec1Vals[MAX_LEN / THREAD_DIM]; + }; +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif // OPENCV_CUDA_VEC_DISTANCE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/vec_math.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/vec_math.hpp index 80b1303681..cc22ddbbe4 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/vec_math.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/vec_math.hpp @@ -1,923 +1,923 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_VECMATH_HPP -#define OPENCV_CUDA_VECMATH_HPP - -#include "vec_traits.hpp" -#include "saturate_cast.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - -// saturate_cast - -namespace vec_math_detail -{ - template struct SatCastHelper; - template struct SatCastHelper<1, VecD> - { - template static __device__ __forceinline__ VecD cast(const VecS& v) - { - typedef typename VecTraits::elem_type D; - return VecTraits::make(saturate_cast(v.x)); - } - }; - template struct SatCastHelper<2, VecD> - { - template static __device__ __forceinline__ VecD cast(const VecS& v) - { - typedef typename VecTraits::elem_type D; - return VecTraits::make(saturate_cast(v.x), saturate_cast(v.y)); - } - }; - template struct SatCastHelper<3, VecD> - { - template static __device__ __forceinline__ VecD cast(const VecS& v) - { - typedef typename VecTraits::elem_type D; - return VecTraits::make(saturate_cast(v.x), saturate_cast(v.y), saturate_cast(v.z)); - } - }; - template struct SatCastHelper<4, VecD> - { - template static __device__ __forceinline__ VecD cast(const VecS& v) - { - typedef typename VecTraits::elem_type D; - return VecTraits::make(saturate_cast(v.x), saturate_cast(v.y), saturate_cast(v.z), saturate_cast(v.w)); - } - }; - - template static __device__ __forceinline__ VecD saturate_cast_helper(const VecS& v) - { - return SatCastHelper::cn, VecD>::cast(v); - } -} - -template static __device__ __forceinline__ T saturate_cast(const uchar1& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const char1& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const ushort1& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const short1& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const uint1& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const int1& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const float1& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const double1& v) {return vec_math_detail::saturate_cast_helper(v);} - -template static __device__ __forceinline__ T saturate_cast(const uchar2& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const char2& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const ushort2& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const short2& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const uint2& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const int2& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const float2& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const double2& v) {return vec_math_detail::saturate_cast_helper(v);} - -template static __device__ __forceinline__ T saturate_cast(const uchar3& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const char3& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const ushort3& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const short3& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const uint3& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const int3& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const float3& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const double3& v) {return vec_math_detail::saturate_cast_helper(v);} - -template static __device__ __forceinline__ T saturate_cast(const uchar4& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const char4& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const ushort4& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const short4& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const uint4& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const int4& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const float4& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const double4& v) {return vec_math_detail::saturate_cast_helper(v);} - -// unary operators - -#define CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(op, input_type, output_type) \ - __device__ __forceinline__ output_type ## 1 operator op(const input_type ## 1 & a) \ - { \ - return VecTraits::make(op (a.x)); \ - } \ - __device__ __forceinline__ output_type ## 2 operator op(const input_type ## 2 & a) \ - { \ - return VecTraits::make(op (a.x), op (a.y)); \ - } \ - __device__ __forceinline__ output_type ## 3 operator op(const input_type ## 3 & a) \ - { \ - return VecTraits::make(op (a.x), op (a.y), op (a.z)); \ - } \ - __device__ __forceinline__ output_type ## 4 operator op(const input_type ## 4 & a) \ - { \ - return VecTraits::make(op (a.x), op (a.y), op (a.z), op (a.w)); \ - } - -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, char, char) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, short, short) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, int, int) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, char, uchar) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, ushort, uchar) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, short, uchar) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, int, uchar) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, uint, uchar) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, float, uchar) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, double, uchar) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, char, char) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, ushort, ushort) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, short, short) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, int, int) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, uint, uint) - -#undef CV_CUDEV_IMPLEMENT_VEC_UNARY_OP - -// unary functions - -#define CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(func_name, func, input_type, output_type) \ - __device__ __forceinline__ output_type ## 1 func_name(const input_type ## 1 & a) \ - { \ - return VecTraits::make(func (a.x)); \ - } \ - __device__ __forceinline__ output_type ## 2 func_name(const input_type ## 2 & a) \ - { \ - return VecTraits::make(func (a.x), func (a.y)); \ - } \ - __device__ __forceinline__ output_type ## 3 func_name(const input_type ## 3 & a) \ - { \ - return VecTraits::make(func (a.x), func (a.y), func (a.z)); \ - } \ - __device__ __forceinline__ output_type ## 4 func_name(const input_type ## 4 & a) \ - { \ - return VecTraits::make(func (a.x), func (a.y), func (a.z), func (a.w)); \ - } - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(abs, ::fabsf, float, float) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrt, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::exp, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::log, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sin, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cos, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tan, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asin, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acos, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atan, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinh, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::cosh, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanh, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinh, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acosh, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanh, double, double) - -#undef CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC - -// binary operators (vec & vec) - -#define CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(op, input_type, output_type) \ - __device__ __forceinline__ output_type ## 1 operator op(const input_type ## 1 & a, const input_type ## 1 & b) \ - { \ - return VecTraits::make(a.x op b.x); \ - } \ - __device__ __forceinline__ output_type ## 2 operator op(const input_type ## 2 & a, const input_type ## 2 & b) \ - { \ - return VecTraits::make(a.x op b.x, a.y op b.y); \ - } \ - __device__ __forceinline__ output_type ## 3 operator op(const input_type ## 3 & a, const input_type ## 3 & b) \ - { \ - return VecTraits::make(a.x op b.x, a.y op b.y, a.z op b.z); \ - } \ - __device__ __forceinline__ output_type ## 4 operator op(const input_type ## 4 & a, const input_type ## 4 & b) \ - { \ - return VecTraits::make(a.x op b.x, a.y op b.y, a.z op b.z, a.w op b.w); \ - } - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, uchar, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, char, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, ushort, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, short, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, int, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, uint, uint) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, float, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, double, double) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, uchar, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, char, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, ushort, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, short, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, int, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, uint, uint) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, float, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, double, double) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, uchar, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, char, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, ushort, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, short, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, int, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, uint, uint) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, float, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, double, double) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, uchar, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, char, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, ushort, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, short, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, int, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, uint, uint) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, float, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, double, double) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, char, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, ushort, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, short, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, int, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, uint, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, float, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, double, uchar) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, char, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, ushort, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, short, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, int, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, uint, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, float, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, double, uchar) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, char, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, ushort, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, short, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, int, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, uint, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, float, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, double, uchar) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, char, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, ushort, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, short, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, int, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, uint, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, float, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, double, uchar) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, char, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, ushort, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, short, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, int, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, uint, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, float, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, double, uchar) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, char, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, ushort, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, short, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, int, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, uint, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, float, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, double, uchar) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, char, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, ushort, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, short, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, int, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, uint, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, float, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, double, uchar) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, char, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, ushort, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, short, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, int, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, uint, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, float, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, double, uchar) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, char, char) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, ushort, ushort) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, short, short) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, int, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, uint, uint) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, char, char) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, ushort, ushort) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, short, short) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, int, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, uint, uint) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, char, char) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, ushort, ushort) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, short, short) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, int, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, uint, uint) - -#undef CV_CUDEV_IMPLEMENT_VEC_BINARY_OP - -// binary operators (vec & scalar) - -#define CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(op, input_type, scalar_type, output_type) \ - __device__ __forceinline__ output_type ## 1 operator op(const input_type ## 1 & a, scalar_type s) \ - { \ - return VecTraits::make(a.x op s); \ - } \ - __device__ __forceinline__ output_type ## 1 operator op(scalar_type s, const input_type ## 1 & b) \ - { \ - return VecTraits::make(s op b.x); \ - } \ - __device__ __forceinline__ output_type ## 2 operator op(const input_type ## 2 & a, scalar_type s) \ - { \ - return VecTraits::make(a.x op s, a.y op s); \ - } \ - __device__ __forceinline__ output_type ## 2 operator op(scalar_type s, const input_type ## 2 & b) \ - { \ - return VecTraits::make(s op b.x, s op b.y); \ - } \ - __device__ __forceinline__ output_type ## 3 operator op(const input_type ## 3 & a, scalar_type s) \ - { \ - return VecTraits::make(a.x op s, a.y op s, a.z op s); \ - } \ - __device__ __forceinline__ output_type ## 3 operator op(scalar_type s, const input_type ## 3 & b) \ - { \ - return VecTraits::make(s op b.x, s op b.y, s op b.z); \ - } \ - __device__ __forceinline__ output_type ## 4 operator op(const input_type ## 4 & a, scalar_type s) \ - { \ - return VecTraits::make(a.x op s, a.y op s, a.z op s, a.w op s); \ - } \ - __device__ __forceinline__ output_type ## 4 operator op(scalar_type s, const input_type ## 4 & b) \ - { \ - return VecTraits::make(s op b.x, s op b.y, s op b.z, s op b.w); \ - } - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uchar, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uchar, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uchar, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, char, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, char, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, char, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, ushort, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, ushort, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, ushort, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, short, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, short, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, short, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, int, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, int, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, int, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uint, uint, uint) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uint, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uint, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, float, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, float, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, double, double, double) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uchar, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uchar, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uchar, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, char, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, char, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, char, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, ushort, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, ushort, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, ushort, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, short, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, short, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, short, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, int, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, int, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, int, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uint, uint, uint) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uint, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uint, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, float, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, float, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, double, double, double) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uchar, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uchar, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uchar, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, char, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, char, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, char, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, ushort, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, ushort, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, ushort, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, short, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, short, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, short, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, int, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, int, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, int, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uint, uint, uint) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uint, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uint, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, float, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, float, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, double, double, double) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uchar, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uchar, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uchar, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, char, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, char, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, char, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, ushort, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, ushort, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, ushort, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, short, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, short, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, short, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, int, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, int, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, int, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uint, uint, uint) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uint, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uint, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, float, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, float, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, double, double, double) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, char, char, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, ushort, ushort, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, short, short, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, int, int, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, uint, uint, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, float, float, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, double, double, uchar) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, char, char, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, ushort, ushort, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, short, short, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, int, int, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, uint, uint, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, float, float, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, double, double, uchar) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, char, char, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, ushort, ushort, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, short, short, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, int, int, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, uint, uint, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, float, float, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, double, double, uchar) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, char, char, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, ushort, ushort, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, short, short, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, int, int, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, uint, uint, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, float, float, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, double, double, uchar) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, char, char, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, ushort, ushort, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, short, short, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, int, int, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, uint, uint, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, float, float, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, double, double, uchar) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, char, char, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, ushort, ushort, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, short, short, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, int, int, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, uint, uint, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, float, float, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, double, double, uchar) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, char, char, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, ushort, ushort, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, short, short, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, int, int, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, uint, uint, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, float, float, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, double, double, uchar) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, char, char, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, ushort, ushort, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, short, short, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, int, int, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, uint, uint, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, float, float, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, double, double, uchar) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, char, char, char) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, ushort, ushort, ushort) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, short, short, short) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, int, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, uint, uint, uint) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, char, char, char) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, ushort, ushort, ushort) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, short, short, short) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, int, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, uint, uint, uint) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, char, char, char) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, ushort, ushort, ushort) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, short, short, short) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, int, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, uint, uint, uint) - -#undef CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP - -// binary function (vec & vec) - -#define CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(func_name, func, input_type, output_type) \ - __device__ __forceinline__ output_type ## 1 func_name(const input_type ## 1 & a, const input_type ## 1 & b) \ - { \ - return VecTraits::make(func (a.x, b.x)); \ - } \ - __device__ __forceinline__ output_type ## 2 func_name(const input_type ## 2 & a, const input_type ## 2 & b) \ - { \ - return VecTraits::make(func (a.x, b.x), func (a.y, b.y)); \ - } \ - __device__ __forceinline__ output_type ## 3 func_name(const input_type ## 3 & a, const input_type ## 3 & b) \ - { \ - return VecTraits::make(func (a.x, b.x), func (a.y, b.y), func (a.z, b.z)); \ - } \ - __device__ __forceinline__ output_type ## 4 func_name(const input_type ## 4 & a, const input_type ## 4 & b) \ - { \ - return VecTraits::make(func (a.x, b.x), func (a.y, b.y), func (a.z, b.z), func (a.w, b.w)); \ - } - -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, char, char) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, ushort, ushort) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, short, short) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, uint, uint) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, int, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::fmaxf, float, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::fmax, double, double) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, char, char) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, ushort, ushort) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, short, short) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, uint, uint) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, int, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::fminf, float, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::fmin, double, double) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, char, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, short, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, int, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, float, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypot, double, double) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, char, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, short, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, uint, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, int, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, float, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2, double, double) - -#undef CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC - -// binary function (vec & scalar) - -#define CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(func_name, func, input_type, scalar_type, output_type) \ - __device__ __forceinline__ output_type ## 1 func_name(const input_type ## 1 & a, scalar_type s) \ - { \ - return VecTraits::make(func ((output_type) a.x, (output_type) s)); \ - } \ - __device__ __forceinline__ output_type ## 1 func_name(scalar_type s, const input_type ## 1 & b) \ - { \ - return VecTraits::make(func ((output_type) s, (output_type) b.x)); \ - } \ - __device__ __forceinline__ output_type ## 2 func_name(const input_type ## 2 & a, scalar_type s) \ - { \ - return VecTraits::make(func ((output_type) a.x, (output_type) s), func ((output_type) a.y, (output_type) s)); \ - } \ - __device__ __forceinline__ output_type ## 2 func_name(scalar_type s, const input_type ## 2 & b) \ - { \ - return VecTraits::make(func ((output_type) s, (output_type) b.x), func ((output_type) s, (output_type) b.y)); \ - } \ - __device__ __forceinline__ output_type ## 3 func_name(const input_type ## 3 & a, scalar_type s) \ - { \ - return VecTraits::make(func ((output_type) a.x, (output_type) s), func ((output_type) a.y, (output_type) s), func ((output_type) a.z, (output_type) s)); \ - } \ - __device__ __forceinline__ output_type ## 3 func_name(scalar_type s, const input_type ## 3 & b) \ - { \ - return VecTraits::make(func ((output_type) s, (output_type) b.x), func ((output_type) s, (output_type) b.y), func ((output_type) s, (output_type) b.z)); \ - } \ - __device__ __forceinline__ output_type ## 4 func_name(const input_type ## 4 & a, scalar_type s) \ - { \ - return VecTraits::make(func ((output_type) a.x, (output_type) s), func ((output_type) a.y, (output_type) s), func ((output_type) a.z, (output_type) s), func ((output_type) a.w, (output_type) s)); \ - } \ - __device__ __forceinline__ output_type ## 4 func_name(scalar_type s, const input_type ## 4 & b) \ - { \ - return VecTraits::make(func ((output_type) s, (output_type) b.x), func ((output_type) s, (output_type) b.y), func ((output_type) s, (output_type) b.z), func ((output_type) s, (output_type) b.w)); \ - } - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, uchar, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, uchar, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, char, char, char) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, char, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, char, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, ushort, ushort, ushort) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, ushort, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, ushort, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, short, short, short) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, short, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, short, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, uint, uint, uint) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, uint, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, uint, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, int, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, int, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, int, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, float, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, float, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, double, double, double) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, uchar, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, uchar, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, char, char, char) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, char, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, char, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, ushort, ushort, ushort) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, ushort, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, ushort, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, short, short, short) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, short, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, short, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, uint, uint, uint) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, uint, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, uint, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, int, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, int, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, int, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, float, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, float, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, double, double, double) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, uchar, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, uchar, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, char, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, char, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, ushort, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, ushort, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, short, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, short, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, uint, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, uint, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, int, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, int, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, float, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, float, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, double, double, double) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, uchar, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, uchar, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, char, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, char, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, ushort, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, ushort, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, short, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, short, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, uint, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, uint, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, int, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, int, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, float, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, float, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, double, double, double) - -#undef CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC - -}}} // namespace cv { namespace cuda { namespace device - -//! @endcond - -#endif // OPENCV_CUDA_VECMATH_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_VECMATH_HPP +#define OPENCV_CUDA_VECMATH_HPP + +#include "vec_traits.hpp" +#include "saturate_cast.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + +// saturate_cast + +namespace vec_math_detail +{ + template struct SatCastHelper; + template struct SatCastHelper<1, VecD> + { + template static __device__ __forceinline__ VecD cast(const VecS& v) + { + typedef typename VecTraits::elem_type D; + return VecTraits::make(saturate_cast(v.x)); + } + }; + template struct SatCastHelper<2, VecD> + { + template static __device__ __forceinline__ VecD cast(const VecS& v) + { + typedef typename VecTraits::elem_type D; + return VecTraits::make(saturate_cast(v.x), saturate_cast(v.y)); + } + }; + template struct SatCastHelper<3, VecD> + { + template static __device__ __forceinline__ VecD cast(const VecS& v) + { + typedef typename VecTraits::elem_type D; + return VecTraits::make(saturate_cast(v.x), saturate_cast(v.y), saturate_cast(v.z)); + } + }; + template struct SatCastHelper<4, VecD> + { + template static __device__ __forceinline__ VecD cast(const VecS& v) + { + typedef typename VecTraits::elem_type D; + return VecTraits::make(saturate_cast(v.x), saturate_cast(v.y), saturate_cast(v.z), saturate_cast(v.w)); + } + }; + + template static __device__ __forceinline__ VecD saturate_cast_helper(const VecS& v) + { + return SatCastHelper::cn, VecD>::cast(v); + } +} + +template static __device__ __forceinline__ T saturate_cast(const uchar1& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const char1& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const ushort1& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const short1& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const uint1& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const int1& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const float1& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const double1& v) {return vec_math_detail::saturate_cast_helper(v);} + +template static __device__ __forceinline__ T saturate_cast(const uchar2& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const char2& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const ushort2& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const short2& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const uint2& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const int2& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const float2& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const double2& v) {return vec_math_detail::saturate_cast_helper(v);} + +template static __device__ __forceinline__ T saturate_cast(const uchar3& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const char3& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const ushort3& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const short3& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const uint3& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const int3& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const float3& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const double3& v) {return vec_math_detail::saturate_cast_helper(v);} + +template static __device__ __forceinline__ T saturate_cast(const uchar4& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const char4& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const ushort4& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const short4& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const uint4& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const int4& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const float4& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const double4& v) {return vec_math_detail::saturate_cast_helper(v);} + +// unary operators + +#define CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(op, input_type, output_type) \ + __device__ __forceinline__ output_type ## 1 operator op(const input_type ## 1 & a) \ + { \ + return VecTraits::make(op (a.x)); \ + } \ + __device__ __forceinline__ output_type ## 2 operator op(const input_type ## 2 & a) \ + { \ + return VecTraits::make(op (a.x), op (a.y)); \ + } \ + __device__ __forceinline__ output_type ## 3 operator op(const input_type ## 3 & a) \ + { \ + return VecTraits::make(op (a.x), op (a.y), op (a.z)); \ + } \ + __device__ __forceinline__ output_type ## 4 operator op(const input_type ## 4 & a) \ + { \ + return VecTraits::make(op (a.x), op (a.y), op (a.z), op (a.w)); \ + } + +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, char, char) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, short, short) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, int, int) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, char, uchar) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, ushort, uchar) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, short, uchar) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, int, uchar) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, uint, uchar) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, float, uchar) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, double, uchar) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, char, char) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, ushort, ushort) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, short, short) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, int, int) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, uint, uint) + +#undef CV_CUDEV_IMPLEMENT_VEC_UNARY_OP + +// unary functions + +#define CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(func_name, func, input_type, output_type) \ + __device__ __forceinline__ output_type ## 1 func_name(const input_type ## 1 & a) \ + { \ + return VecTraits::make(func (a.x)); \ + } \ + __device__ __forceinline__ output_type ## 2 func_name(const input_type ## 2 & a) \ + { \ + return VecTraits::make(func (a.x), func (a.y)); \ + } \ + __device__ __forceinline__ output_type ## 3 func_name(const input_type ## 3 & a) \ + { \ + return VecTraits::make(func (a.x), func (a.y), func (a.z)); \ + } \ + __device__ __forceinline__ output_type ## 4 func_name(const input_type ## 4 & a) \ + { \ + return VecTraits::make(func (a.x), func (a.y), func (a.z), func (a.w)); \ + } + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(abs, ::fabsf, float, float) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrt, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::exp, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::log, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sin, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cos, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tan, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asin, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acos, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atan, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinh, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::cosh, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanh, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinh, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acosh, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanh, double, double) + +#undef CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC + +// binary operators (vec & vec) + +#define CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(op, input_type, output_type) \ + __device__ __forceinline__ output_type ## 1 operator op(const input_type ## 1 & a, const input_type ## 1 & b) \ + { \ + return VecTraits::make(a.x op b.x); \ + } \ + __device__ __forceinline__ output_type ## 2 operator op(const input_type ## 2 & a, const input_type ## 2 & b) \ + { \ + return VecTraits::make(a.x op b.x, a.y op b.y); \ + } \ + __device__ __forceinline__ output_type ## 3 operator op(const input_type ## 3 & a, const input_type ## 3 & b) \ + { \ + return VecTraits::make(a.x op b.x, a.y op b.y, a.z op b.z); \ + } \ + __device__ __forceinline__ output_type ## 4 operator op(const input_type ## 4 & a, const input_type ## 4 & b) \ + { \ + return VecTraits::make(a.x op b.x, a.y op b.y, a.z op b.z, a.w op b.w); \ + } + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, uchar, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, char, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, ushort, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, short, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, int, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, uint, uint) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, float, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, double, double) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, uchar, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, char, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, ushort, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, short, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, int, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, uint, uint) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, float, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, double, double) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, uchar, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, char, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, ushort, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, short, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, int, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, uint, uint) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, float, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, double, double) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, uchar, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, char, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, ushort, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, short, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, int, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, uint, uint) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, float, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, double, double) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, char, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, ushort, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, short, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, int, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, uint, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, float, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, double, uchar) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, char, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, ushort, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, short, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, int, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, uint, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, float, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, double, uchar) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, char, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, ushort, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, short, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, int, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, uint, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, float, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, double, uchar) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, char, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, ushort, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, short, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, int, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, uint, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, float, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, double, uchar) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, char, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, ushort, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, short, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, int, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, uint, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, float, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, double, uchar) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, char, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, ushort, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, short, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, int, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, uint, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, float, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, double, uchar) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, char, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, ushort, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, short, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, int, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, uint, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, float, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, double, uchar) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, char, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, ushort, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, short, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, int, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, uint, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, float, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, double, uchar) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, char, char) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, ushort, ushort) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, short, short) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, int, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, uint, uint) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, char, char) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, ushort, ushort) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, short, short) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, int, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, uint, uint) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, char, char) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, ushort, ushort) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, short, short) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, int, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, uint, uint) + +#undef CV_CUDEV_IMPLEMENT_VEC_BINARY_OP + +// binary operators (vec & scalar) + +#define CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(op, input_type, scalar_type, output_type) \ + __device__ __forceinline__ output_type ## 1 operator op(const input_type ## 1 & a, scalar_type s) \ + { \ + return VecTraits::make(a.x op s); \ + } \ + __device__ __forceinline__ output_type ## 1 operator op(scalar_type s, const input_type ## 1 & b) \ + { \ + return VecTraits::make(s op b.x); \ + } \ + __device__ __forceinline__ output_type ## 2 operator op(const input_type ## 2 & a, scalar_type s) \ + { \ + return VecTraits::make(a.x op s, a.y op s); \ + } \ + __device__ __forceinline__ output_type ## 2 operator op(scalar_type s, const input_type ## 2 & b) \ + { \ + return VecTraits::make(s op b.x, s op b.y); \ + } \ + __device__ __forceinline__ output_type ## 3 operator op(const input_type ## 3 & a, scalar_type s) \ + { \ + return VecTraits::make(a.x op s, a.y op s, a.z op s); \ + } \ + __device__ __forceinline__ output_type ## 3 operator op(scalar_type s, const input_type ## 3 & b) \ + { \ + return VecTraits::make(s op b.x, s op b.y, s op b.z); \ + } \ + __device__ __forceinline__ output_type ## 4 operator op(const input_type ## 4 & a, scalar_type s) \ + { \ + return VecTraits::make(a.x op s, a.y op s, a.z op s, a.w op s); \ + } \ + __device__ __forceinline__ output_type ## 4 operator op(scalar_type s, const input_type ## 4 & b) \ + { \ + return VecTraits::make(s op b.x, s op b.y, s op b.z, s op b.w); \ + } + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uchar, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uchar, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uchar, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, char, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, char, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, char, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, ushort, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, ushort, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, ushort, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, short, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, short, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, short, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, int, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, int, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, int, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uint, uint, uint) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uint, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uint, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, float, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, float, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, double, double, double) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uchar, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uchar, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uchar, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, char, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, char, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, char, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, ushort, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, ushort, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, ushort, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, short, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, short, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, short, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, int, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, int, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, int, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uint, uint, uint) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uint, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uint, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, float, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, float, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, double, double, double) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uchar, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uchar, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uchar, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, char, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, char, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, char, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, ushort, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, ushort, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, ushort, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, short, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, short, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, short, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, int, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, int, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, int, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uint, uint, uint) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uint, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uint, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, float, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, float, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, double, double, double) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uchar, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uchar, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uchar, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, char, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, char, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, char, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, ushort, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, ushort, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, ushort, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, short, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, short, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, short, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, int, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, int, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, int, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uint, uint, uint) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uint, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uint, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, float, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, float, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, double, double, double) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, char, char, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, ushort, ushort, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, short, short, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, int, int, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, uint, uint, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, float, float, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, double, double, uchar) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, char, char, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, ushort, ushort, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, short, short, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, int, int, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, uint, uint, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, float, float, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, double, double, uchar) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, char, char, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, ushort, ushort, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, short, short, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, int, int, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, uint, uint, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, float, float, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, double, double, uchar) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, char, char, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, ushort, ushort, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, short, short, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, int, int, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, uint, uint, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, float, float, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, double, double, uchar) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, char, char, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, ushort, ushort, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, short, short, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, int, int, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, uint, uint, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, float, float, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, double, double, uchar) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, char, char, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, ushort, ushort, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, short, short, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, int, int, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, uint, uint, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, float, float, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, double, double, uchar) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, char, char, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, ushort, ushort, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, short, short, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, int, int, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, uint, uint, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, float, float, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, double, double, uchar) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, char, char, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, ushort, ushort, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, short, short, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, int, int, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, uint, uint, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, float, float, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, double, double, uchar) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, char, char, char) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, ushort, ushort, ushort) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, short, short, short) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, int, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, uint, uint, uint) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, char, char, char) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, ushort, ushort, ushort) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, short, short, short) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, int, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, uint, uint, uint) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, char, char, char) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, ushort, ushort, ushort) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, short, short, short) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, int, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, uint, uint, uint) + +#undef CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP + +// binary function (vec & vec) + +#define CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(func_name, func, input_type, output_type) \ + __device__ __forceinline__ output_type ## 1 func_name(const input_type ## 1 & a, const input_type ## 1 & b) \ + { \ + return VecTraits::make(func (a.x, b.x)); \ + } \ + __device__ __forceinline__ output_type ## 2 func_name(const input_type ## 2 & a, const input_type ## 2 & b) \ + { \ + return VecTraits::make(func (a.x, b.x), func (a.y, b.y)); \ + } \ + __device__ __forceinline__ output_type ## 3 func_name(const input_type ## 3 & a, const input_type ## 3 & b) \ + { \ + return VecTraits::make(func (a.x, b.x), func (a.y, b.y), func (a.z, b.z)); \ + } \ + __device__ __forceinline__ output_type ## 4 func_name(const input_type ## 4 & a, const input_type ## 4 & b) \ + { \ + return VecTraits::make(func (a.x, b.x), func (a.y, b.y), func (a.z, b.z), func (a.w, b.w)); \ + } + +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, char, char) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, ushort, ushort) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, short, short) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, uint, uint) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, int, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::fmaxf, float, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::fmax, double, double) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, char, char) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, ushort, ushort) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, short, short) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, uint, uint) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, int, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::fminf, float, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::fmin, double, double) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, char, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, short, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, int, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, float, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypot, double, double) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, char, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, short, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, uint, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, int, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, float, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2, double, double) + +#undef CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC + +// binary function (vec & scalar) + +#define CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(func_name, func, input_type, scalar_type, output_type) \ + __device__ __forceinline__ output_type ## 1 func_name(const input_type ## 1 & a, scalar_type s) \ + { \ + return VecTraits::make(func ((output_type) a.x, (output_type) s)); \ + } \ + __device__ __forceinline__ output_type ## 1 func_name(scalar_type s, const input_type ## 1 & b) \ + { \ + return VecTraits::make(func ((output_type) s, (output_type) b.x)); \ + } \ + __device__ __forceinline__ output_type ## 2 func_name(const input_type ## 2 & a, scalar_type s) \ + { \ + return VecTraits::make(func ((output_type) a.x, (output_type) s), func ((output_type) a.y, (output_type) s)); \ + } \ + __device__ __forceinline__ output_type ## 2 func_name(scalar_type s, const input_type ## 2 & b) \ + { \ + return VecTraits::make(func ((output_type) s, (output_type) b.x), func ((output_type) s, (output_type) b.y)); \ + } \ + __device__ __forceinline__ output_type ## 3 func_name(const input_type ## 3 & a, scalar_type s) \ + { \ + return VecTraits::make(func ((output_type) a.x, (output_type) s), func ((output_type) a.y, (output_type) s), func ((output_type) a.z, (output_type) s)); \ + } \ + __device__ __forceinline__ output_type ## 3 func_name(scalar_type s, const input_type ## 3 & b) \ + { \ + return VecTraits::make(func ((output_type) s, (output_type) b.x), func ((output_type) s, (output_type) b.y), func ((output_type) s, (output_type) b.z)); \ + } \ + __device__ __forceinline__ output_type ## 4 func_name(const input_type ## 4 & a, scalar_type s) \ + { \ + return VecTraits::make(func ((output_type) a.x, (output_type) s), func ((output_type) a.y, (output_type) s), func ((output_type) a.z, (output_type) s), func ((output_type) a.w, (output_type) s)); \ + } \ + __device__ __forceinline__ output_type ## 4 func_name(scalar_type s, const input_type ## 4 & b) \ + { \ + return VecTraits::make(func ((output_type) s, (output_type) b.x), func ((output_type) s, (output_type) b.y), func ((output_type) s, (output_type) b.z), func ((output_type) s, (output_type) b.w)); \ + } + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, uchar, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, uchar, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, char, char, char) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, char, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, char, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, ushort, ushort, ushort) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, ushort, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, ushort, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, short, short, short) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, short, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, short, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, uint, uint, uint) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, uint, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, uint, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, int, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, int, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, int, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, float, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, float, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, double, double, double) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, uchar, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, uchar, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, char, char, char) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, char, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, char, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, ushort, ushort, ushort) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, ushort, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, ushort, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, short, short, short) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, short, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, short, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, uint, uint, uint) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, uint, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, uint, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, int, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, int, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, int, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, float, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, float, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, double, double, double) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, uchar, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, uchar, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, char, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, char, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, ushort, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, ushort, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, short, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, short, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, uint, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, uint, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, int, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, int, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, float, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, float, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, double, double, double) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, uchar, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, uchar, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, char, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, char, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, ushort, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, ushort, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, short, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, short, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, uint, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, uint, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, int, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, int, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, float, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, float, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, double, double, double) + +#undef CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC + +}}} // namespace cv { namespace cuda { namespace device + +//! @endcond + +#endif // OPENCV_CUDA_VECMATH_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/vec_traits.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/vec_traits.hpp index b5ff281a0b..582187210d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/vec_traits.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/vec_traits.hpp @@ -1,288 +1,288 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_VEC_TRAITS_HPP -#define OPENCV_CUDA_VEC_TRAITS_HPP - -#include "common.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - template struct TypeVec; - - struct __align__(8) uchar8 - { - uchar a0, a1, a2, a3, a4, a5, a6, a7; - }; - static __host__ __device__ __forceinline__ uchar8 make_uchar8(uchar a0, uchar a1, uchar a2, uchar a3, uchar a4, uchar a5, uchar a6, uchar a7) - { - uchar8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; - return val; - } - struct __align__(8) char8 - { - schar a0, a1, a2, a3, a4, a5, a6, a7; - }; - static __host__ __device__ __forceinline__ char8 make_char8(schar a0, schar a1, schar a2, schar a3, schar a4, schar a5, schar a6, schar a7) - { - char8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; - return val; - } - struct __align__(16) ushort8 - { - ushort a0, a1, a2, a3, a4, a5, a6, a7; - }; - static __host__ __device__ __forceinline__ ushort8 make_ushort8(ushort a0, ushort a1, ushort a2, ushort a3, ushort a4, ushort a5, ushort a6, ushort a7) - { - ushort8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; - return val; - } - struct __align__(16) short8 - { - short a0, a1, a2, a3, a4, a5, a6, a7; - }; - static __host__ __device__ __forceinline__ short8 make_short8(short a0, short a1, short a2, short a3, short a4, short a5, short a6, short a7) - { - short8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; - return val; - } - struct __align__(32) uint8 - { - uint a0, a1, a2, a3, a4, a5, a6, a7; - }; - static __host__ __device__ __forceinline__ uint8 make_uint8(uint a0, uint a1, uint a2, uint a3, uint a4, uint a5, uint a6, uint a7) - { - uint8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; - return val; - } - struct __align__(32) int8 - { - int a0, a1, a2, a3, a4, a5, a6, a7; - }; - static __host__ __device__ __forceinline__ int8 make_int8(int a0, int a1, int a2, int a3, int a4, int a5, int a6, int a7) - { - int8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; - return val; - } - struct __align__(32) float8 - { - float a0, a1, a2, a3, a4, a5, a6, a7; - }; - static __host__ __device__ __forceinline__ float8 make_float8(float a0, float a1, float a2, float a3, float a4, float a5, float a6, float a7) - { - float8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; - return val; - } - struct double8 - { - double a0, a1, a2, a3, a4, a5, a6, a7; - }; - static __host__ __device__ __forceinline__ double8 make_double8(double a0, double a1, double a2, double a3, double a4, double a5, double a6, double a7) - { - double8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; - return val; - } - -#define OPENCV_CUDA_IMPLEMENT_TYPE_VEC(type) \ - template<> struct TypeVec { typedef type vec_type; }; \ - template<> struct TypeVec { typedef type ## 1 vec_type; }; \ - template<> struct TypeVec { typedef type ## 2 vec_type; }; \ - template<> struct TypeVec { typedef type ## 2 vec_type; }; \ - template<> struct TypeVec { typedef type ## 3 vec_type; }; \ - template<> struct TypeVec { typedef type ## 3 vec_type; }; \ - template<> struct TypeVec { typedef type ## 4 vec_type; }; \ - template<> struct TypeVec { typedef type ## 4 vec_type; }; \ - template<> struct TypeVec { typedef type ## 8 vec_type; }; \ - template<> struct TypeVec { typedef type ## 8 vec_type; }; - - OPENCV_CUDA_IMPLEMENT_TYPE_VEC(uchar) - OPENCV_CUDA_IMPLEMENT_TYPE_VEC(char) - OPENCV_CUDA_IMPLEMENT_TYPE_VEC(ushort) - OPENCV_CUDA_IMPLEMENT_TYPE_VEC(short) - OPENCV_CUDA_IMPLEMENT_TYPE_VEC(int) - OPENCV_CUDA_IMPLEMENT_TYPE_VEC(uint) - OPENCV_CUDA_IMPLEMENT_TYPE_VEC(float) - OPENCV_CUDA_IMPLEMENT_TYPE_VEC(double) - - #undef OPENCV_CUDA_IMPLEMENT_TYPE_VEC - - template<> struct TypeVec { typedef schar vec_type; }; - template<> struct TypeVec { typedef char2 vec_type; }; - template<> struct TypeVec { typedef char3 vec_type; }; - template<> struct TypeVec { typedef char4 vec_type; }; - template<> struct TypeVec { typedef char8 vec_type; }; - - template<> struct TypeVec { typedef uchar vec_type; }; - template<> struct TypeVec { typedef uchar2 vec_type; }; - template<> struct TypeVec { typedef uchar3 vec_type; }; - template<> struct TypeVec { typedef uchar4 vec_type; }; - template<> struct TypeVec { typedef uchar8 vec_type; }; - - template struct VecTraits; - -#define OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(type) \ - template<> struct VecTraits \ - { \ - typedef type elem_type; \ - enum {cn=1}; \ - static __device__ __host__ __forceinline__ type all(type v) {return v;} \ - static __device__ __host__ __forceinline__ type make(type x) {return x;} \ - static __device__ __host__ __forceinline__ type make(const type* v) {return *v;} \ - }; \ - template<> struct VecTraits \ - { \ - typedef type elem_type; \ - enum {cn=1}; \ - static __device__ __host__ __forceinline__ type ## 1 all(type v) {return make_ ## type ## 1(v);} \ - static __device__ __host__ __forceinline__ type ## 1 make(type x) {return make_ ## type ## 1(x);} \ - static __device__ __host__ __forceinline__ type ## 1 make(const type* v) {return make_ ## type ## 1(*v);} \ - }; \ - template<> struct VecTraits \ - { \ - typedef type elem_type; \ - enum {cn=2}; \ - static __device__ __host__ __forceinline__ type ## 2 all(type v) {return make_ ## type ## 2(v, v);} \ - static __device__ __host__ __forceinline__ type ## 2 make(type x, type y) {return make_ ## type ## 2(x, y);} \ - static __device__ __host__ __forceinline__ type ## 2 make(const type* v) {return make_ ## type ## 2(v[0], v[1]);} \ - }; \ - template<> struct VecTraits \ - { \ - typedef type elem_type; \ - enum {cn=3}; \ - static __device__ __host__ __forceinline__ type ## 3 all(type v) {return make_ ## type ## 3(v, v, v);} \ - static __device__ __host__ __forceinline__ type ## 3 make(type x, type y, type z) {return make_ ## type ## 3(x, y, z);} \ - static __device__ __host__ __forceinline__ type ## 3 make(const type* v) {return make_ ## type ## 3(v[0], v[1], v[2]);} \ - }; \ - template<> struct VecTraits \ - { \ - typedef type elem_type; \ - enum {cn=4}; \ - static __device__ __host__ __forceinline__ type ## 4 all(type v) {return make_ ## type ## 4(v, v, v, v);} \ - static __device__ __host__ __forceinline__ type ## 4 make(type x, type y, type z, type w) {return make_ ## type ## 4(x, y, z, w);} \ - static __device__ __host__ __forceinline__ type ## 4 make(const type* v) {return make_ ## type ## 4(v[0], v[1], v[2], v[3]);} \ - }; \ - template<> struct VecTraits \ - { \ - typedef type elem_type; \ - enum {cn=8}; \ - static __device__ __host__ __forceinline__ type ## 8 all(type v) {return make_ ## type ## 8(v, v, v, v, v, v, v, v);} \ - static __device__ __host__ __forceinline__ type ## 8 make(type a0, type a1, type a2, type a3, type a4, type a5, type a6, type a7) {return make_ ## type ## 8(a0, a1, a2, a3, a4, a5, a6, a7);} \ - static __device__ __host__ __forceinline__ type ## 8 make(const type* v) {return make_ ## type ## 8(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]);} \ - }; - - OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(uchar) - OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(ushort) - OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(short) - OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(int) - OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(uint) - OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(float) - OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(double) - - #undef OPENCV_CUDA_IMPLEMENT_VEC_TRAITS - - template<> struct VecTraits - { - typedef char elem_type; - enum {cn=1}; - static __device__ __host__ __forceinline__ char all(char v) {return v;} - static __device__ __host__ __forceinline__ char make(char x) {return x;} - static __device__ __host__ __forceinline__ char make(const char* x) {return *x;} - }; - template<> struct VecTraits - { - typedef schar elem_type; - enum {cn=1}; - static __device__ __host__ __forceinline__ schar all(schar v) {return v;} - static __device__ __host__ __forceinline__ schar make(schar x) {return x;} - static __device__ __host__ __forceinline__ schar make(const schar* x) {return *x;} - }; - template<> struct VecTraits - { - typedef schar elem_type; - enum {cn=1}; - static __device__ __host__ __forceinline__ char1 all(schar v) {return make_char1(v);} - static __device__ __host__ __forceinline__ char1 make(schar x) {return make_char1(x);} - static __device__ __host__ __forceinline__ char1 make(const schar* v) {return make_char1(v[0]);} - }; - template<> struct VecTraits - { - typedef schar elem_type; - enum {cn=2}; - static __device__ __host__ __forceinline__ char2 all(schar v) {return make_char2(v, v);} - static __device__ __host__ __forceinline__ char2 make(schar x, schar y) {return make_char2(x, y);} - static __device__ __host__ __forceinline__ char2 make(const schar* v) {return make_char2(v[0], v[1]);} - }; - template<> struct VecTraits - { - typedef schar elem_type; - enum {cn=3}; - static __device__ __host__ __forceinline__ char3 all(schar v) {return make_char3(v, v, v);} - static __device__ __host__ __forceinline__ char3 make(schar x, schar y, schar z) {return make_char3(x, y, z);} - static __device__ __host__ __forceinline__ char3 make(const schar* v) {return make_char3(v[0], v[1], v[2]);} - }; - template<> struct VecTraits - { - typedef schar elem_type; - enum {cn=4}; - static __device__ __host__ __forceinline__ char4 all(schar v) {return make_char4(v, v, v, v);} - static __device__ __host__ __forceinline__ char4 make(schar x, schar y, schar z, schar w) {return make_char4(x, y, z, w);} - static __device__ __host__ __forceinline__ char4 make(const schar* v) {return make_char4(v[0], v[1], v[2], v[3]);} - }; - template<> struct VecTraits - { - typedef schar elem_type; - enum {cn=8}; - static __device__ __host__ __forceinline__ char8 all(schar v) {return make_char8(v, v, v, v, v, v, v, v);} - static __device__ __host__ __forceinline__ char8 make(schar a0, schar a1, schar a2, schar a3, schar a4, schar a5, schar a6, schar a7) {return make_char8(a0, a1, a2, a3, a4, a5, a6, a7);} - static __device__ __host__ __forceinline__ char8 make(const schar* v) {return make_char8(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]);} - }; -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif // OPENCV_CUDA_VEC_TRAITS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_VEC_TRAITS_HPP +#define OPENCV_CUDA_VEC_TRAITS_HPP + +#include "common.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + template struct TypeVec; + + struct __align__(8) uchar8 + { + uchar a0, a1, a2, a3, a4, a5, a6, a7; + }; + static __host__ __device__ __forceinline__ uchar8 make_uchar8(uchar a0, uchar a1, uchar a2, uchar a3, uchar a4, uchar a5, uchar a6, uchar a7) + { + uchar8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; + return val; + } + struct __align__(8) char8 + { + schar a0, a1, a2, a3, a4, a5, a6, a7; + }; + static __host__ __device__ __forceinline__ char8 make_char8(schar a0, schar a1, schar a2, schar a3, schar a4, schar a5, schar a6, schar a7) + { + char8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; + return val; + } + struct __align__(16) ushort8 + { + ushort a0, a1, a2, a3, a4, a5, a6, a7; + }; + static __host__ __device__ __forceinline__ ushort8 make_ushort8(ushort a0, ushort a1, ushort a2, ushort a3, ushort a4, ushort a5, ushort a6, ushort a7) + { + ushort8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; + return val; + } + struct __align__(16) short8 + { + short a0, a1, a2, a3, a4, a5, a6, a7; + }; + static __host__ __device__ __forceinline__ short8 make_short8(short a0, short a1, short a2, short a3, short a4, short a5, short a6, short a7) + { + short8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; + return val; + } + struct __align__(32) uint8 + { + uint a0, a1, a2, a3, a4, a5, a6, a7; + }; + static __host__ __device__ __forceinline__ uint8 make_uint8(uint a0, uint a1, uint a2, uint a3, uint a4, uint a5, uint a6, uint a7) + { + uint8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; + return val; + } + struct __align__(32) int8 + { + int a0, a1, a2, a3, a4, a5, a6, a7; + }; + static __host__ __device__ __forceinline__ int8 make_int8(int a0, int a1, int a2, int a3, int a4, int a5, int a6, int a7) + { + int8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; + return val; + } + struct __align__(32) float8 + { + float a0, a1, a2, a3, a4, a5, a6, a7; + }; + static __host__ __device__ __forceinline__ float8 make_float8(float a0, float a1, float a2, float a3, float a4, float a5, float a6, float a7) + { + float8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; + return val; + } + struct double8 + { + double a0, a1, a2, a3, a4, a5, a6, a7; + }; + static __host__ __device__ __forceinline__ double8 make_double8(double a0, double a1, double a2, double a3, double a4, double a5, double a6, double a7) + { + double8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; + return val; + } + +#define OPENCV_CUDA_IMPLEMENT_TYPE_VEC(type) \ + template<> struct TypeVec { typedef type vec_type; }; \ + template<> struct TypeVec { typedef type ## 1 vec_type; }; \ + template<> struct TypeVec { typedef type ## 2 vec_type; }; \ + template<> struct TypeVec { typedef type ## 2 vec_type; }; \ + template<> struct TypeVec { typedef type ## 3 vec_type; }; \ + template<> struct TypeVec { typedef type ## 3 vec_type; }; \ + template<> struct TypeVec { typedef type ## 4 vec_type; }; \ + template<> struct TypeVec { typedef type ## 4 vec_type; }; \ + template<> struct TypeVec { typedef type ## 8 vec_type; }; \ + template<> struct TypeVec { typedef type ## 8 vec_type; }; + + OPENCV_CUDA_IMPLEMENT_TYPE_VEC(uchar) + OPENCV_CUDA_IMPLEMENT_TYPE_VEC(char) + OPENCV_CUDA_IMPLEMENT_TYPE_VEC(ushort) + OPENCV_CUDA_IMPLEMENT_TYPE_VEC(short) + OPENCV_CUDA_IMPLEMENT_TYPE_VEC(int) + OPENCV_CUDA_IMPLEMENT_TYPE_VEC(uint) + OPENCV_CUDA_IMPLEMENT_TYPE_VEC(float) + OPENCV_CUDA_IMPLEMENT_TYPE_VEC(double) + + #undef OPENCV_CUDA_IMPLEMENT_TYPE_VEC + + template<> struct TypeVec { typedef schar vec_type; }; + template<> struct TypeVec { typedef char2 vec_type; }; + template<> struct TypeVec { typedef char3 vec_type; }; + template<> struct TypeVec { typedef char4 vec_type; }; + template<> struct TypeVec { typedef char8 vec_type; }; + + template<> struct TypeVec { typedef uchar vec_type; }; + template<> struct TypeVec { typedef uchar2 vec_type; }; + template<> struct TypeVec { typedef uchar3 vec_type; }; + template<> struct TypeVec { typedef uchar4 vec_type; }; + template<> struct TypeVec { typedef uchar8 vec_type; }; + + template struct VecTraits; + +#define OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(type) \ + template<> struct VecTraits \ + { \ + typedef type elem_type; \ + enum {cn=1}; \ + static __device__ __host__ __forceinline__ type all(type v) {return v;} \ + static __device__ __host__ __forceinline__ type make(type x) {return x;} \ + static __device__ __host__ __forceinline__ type make(const type* v) {return *v;} \ + }; \ + template<> struct VecTraits \ + { \ + typedef type elem_type; \ + enum {cn=1}; \ + static __device__ __host__ __forceinline__ type ## 1 all(type v) {return make_ ## type ## 1(v);} \ + static __device__ __host__ __forceinline__ type ## 1 make(type x) {return make_ ## type ## 1(x);} \ + static __device__ __host__ __forceinline__ type ## 1 make(const type* v) {return make_ ## type ## 1(*v);} \ + }; \ + template<> struct VecTraits \ + { \ + typedef type elem_type; \ + enum {cn=2}; \ + static __device__ __host__ __forceinline__ type ## 2 all(type v) {return make_ ## type ## 2(v, v);} \ + static __device__ __host__ __forceinline__ type ## 2 make(type x, type y) {return make_ ## type ## 2(x, y);} \ + static __device__ __host__ __forceinline__ type ## 2 make(const type* v) {return make_ ## type ## 2(v[0], v[1]);} \ + }; \ + template<> struct VecTraits \ + { \ + typedef type elem_type; \ + enum {cn=3}; \ + static __device__ __host__ __forceinline__ type ## 3 all(type v) {return make_ ## type ## 3(v, v, v);} \ + static __device__ __host__ __forceinline__ type ## 3 make(type x, type y, type z) {return make_ ## type ## 3(x, y, z);} \ + static __device__ __host__ __forceinline__ type ## 3 make(const type* v) {return make_ ## type ## 3(v[0], v[1], v[2]);} \ + }; \ + template<> struct VecTraits \ + { \ + typedef type elem_type; \ + enum {cn=4}; \ + static __device__ __host__ __forceinline__ type ## 4 all(type v) {return make_ ## type ## 4(v, v, v, v);} \ + static __device__ __host__ __forceinline__ type ## 4 make(type x, type y, type z, type w) {return make_ ## type ## 4(x, y, z, w);} \ + static __device__ __host__ __forceinline__ type ## 4 make(const type* v) {return make_ ## type ## 4(v[0], v[1], v[2], v[3]);} \ + }; \ + template<> struct VecTraits \ + { \ + typedef type elem_type; \ + enum {cn=8}; \ + static __device__ __host__ __forceinline__ type ## 8 all(type v) {return make_ ## type ## 8(v, v, v, v, v, v, v, v);} \ + static __device__ __host__ __forceinline__ type ## 8 make(type a0, type a1, type a2, type a3, type a4, type a5, type a6, type a7) {return make_ ## type ## 8(a0, a1, a2, a3, a4, a5, a6, a7);} \ + static __device__ __host__ __forceinline__ type ## 8 make(const type* v) {return make_ ## type ## 8(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]);} \ + }; + + OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(uchar) + OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(ushort) + OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(short) + OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(int) + OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(uint) + OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(float) + OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(double) + + #undef OPENCV_CUDA_IMPLEMENT_VEC_TRAITS + + template<> struct VecTraits + { + typedef char elem_type; + enum {cn=1}; + static __device__ __host__ __forceinline__ char all(char v) {return v;} + static __device__ __host__ __forceinline__ char make(char x) {return x;} + static __device__ __host__ __forceinline__ char make(const char* x) {return *x;} + }; + template<> struct VecTraits + { + typedef schar elem_type; + enum {cn=1}; + static __device__ __host__ __forceinline__ schar all(schar v) {return v;} + static __device__ __host__ __forceinline__ schar make(schar x) {return x;} + static __device__ __host__ __forceinline__ schar make(const schar* x) {return *x;} + }; + template<> struct VecTraits + { + typedef schar elem_type; + enum {cn=1}; + static __device__ __host__ __forceinline__ char1 all(schar v) {return make_char1(v);} + static __device__ __host__ __forceinline__ char1 make(schar x) {return make_char1(x);} + static __device__ __host__ __forceinline__ char1 make(const schar* v) {return make_char1(v[0]);} + }; + template<> struct VecTraits + { + typedef schar elem_type; + enum {cn=2}; + static __device__ __host__ __forceinline__ char2 all(schar v) {return make_char2(v, v);} + static __device__ __host__ __forceinline__ char2 make(schar x, schar y) {return make_char2(x, y);} + static __device__ __host__ __forceinline__ char2 make(const schar* v) {return make_char2(v[0], v[1]);} + }; + template<> struct VecTraits + { + typedef schar elem_type; + enum {cn=3}; + static __device__ __host__ __forceinline__ char3 all(schar v) {return make_char3(v, v, v);} + static __device__ __host__ __forceinline__ char3 make(schar x, schar y, schar z) {return make_char3(x, y, z);} + static __device__ __host__ __forceinline__ char3 make(const schar* v) {return make_char3(v[0], v[1], v[2]);} + }; + template<> struct VecTraits + { + typedef schar elem_type; + enum {cn=4}; + static __device__ __host__ __forceinline__ char4 all(schar v) {return make_char4(v, v, v, v);} + static __device__ __host__ __forceinline__ char4 make(schar x, schar y, schar z, schar w) {return make_char4(x, y, z, w);} + static __device__ __host__ __forceinline__ char4 make(const schar* v) {return make_char4(v[0], v[1], v[2], v[3]);} + }; + template<> struct VecTraits + { + typedef schar elem_type; + enum {cn=8}; + static __device__ __host__ __forceinline__ char8 all(schar v) {return make_char8(v, v, v, v, v, v, v, v);} + static __device__ __host__ __forceinline__ char8 make(schar a0, schar a1, schar a2, schar a3, schar a4, schar a5, schar a6, schar a7) {return make_char8(a0, a1, a2, a3, a4, a5, a6, a7);} + static __device__ __host__ __forceinline__ char8 make(const schar* v) {return make_char8(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]);} + }; +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif // OPENCV_CUDA_VEC_TRAITS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/warp.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/warp.hpp index 8af7e6a212..58e2c324c8 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/warp.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/warp.hpp @@ -1,139 +1,139 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_DEVICE_WARP_HPP -#define OPENCV_CUDA_DEVICE_WARP_HPP - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - struct Warp - { - enum - { - LOG_WARP_SIZE = 5, - WARP_SIZE = 1 << LOG_WARP_SIZE, - STRIDE = WARP_SIZE - }; - - /** \brief Returns the warp lane ID of the calling thread. */ - static __device__ __forceinline__ unsigned int laneId() - { - unsigned int ret; - asm("mov.u32 %0, %%laneid;" : "=r"(ret) ); - return ret; - } - - template - static __device__ __forceinline__ void fill(It beg, It end, const T& value) - { - for(It t = beg + laneId(); t < end; t += STRIDE) - *t = value; - } - - template - static __device__ __forceinline__ OutIt copy(InIt beg, InIt end, OutIt out) - { - for(InIt t = beg + laneId(); t < end; t += STRIDE, out += STRIDE) - *out = *t; - return out; - } - - template - static __device__ __forceinline__ OutIt transform(InIt beg, InIt end, OutIt out, UnOp op) - { - for(InIt t = beg + laneId(); t < end; t += STRIDE, out += STRIDE) - *out = op(*t); - return out; - } - - template - static __device__ __forceinline__ OutIt transform(InIt1 beg1, InIt1 end1, InIt2 beg2, OutIt out, BinOp op) - { - unsigned int lane = laneId(); - - InIt1 t1 = beg1 + lane; - InIt2 t2 = beg2 + lane; - for(; t1 < end1; t1 += STRIDE, t2 += STRIDE, out += STRIDE) - *out = op(*t1, *t2); - return out; - } - - template - static __device__ __forceinline__ T reduce(volatile T *ptr, BinOp op) - { - const unsigned int lane = laneId(); - - if (lane < 16) - { - T partial = ptr[lane]; - - ptr[lane] = partial = op(partial, ptr[lane + 16]); - ptr[lane] = partial = op(partial, ptr[lane + 8]); - ptr[lane] = partial = op(partial, ptr[lane + 4]); - ptr[lane] = partial = op(partial, ptr[lane + 2]); - ptr[lane] = partial = op(partial, ptr[lane + 1]); - } - - return *ptr; - } - - template - static __device__ __forceinline__ void yota(OutIt beg, OutIt end, T value) - { - unsigned int lane = laneId(); - value += lane; - - for(OutIt t = beg + lane; t < end; t += STRIDE, value += STRIDE) - *t = value; - } - }; -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif /* OPENCV_CUDA_DEVICE_WARP_HPP */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_DEVICE_WARP_HPP +#define OPENCV_CUDA_DEVICE_WARP_HPP + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + struct Warp + { + enum + { + LOG_WARP_SIZE = 5, + WARP_SIZE = 1 << LOG_WARP_SIZE, + STRIDE = WARP_SIZE + }; + + /** \brief Returns the warp lane ID of the calling thread. */ + static __device__ __forceinline__ unsigned int laneId() + { + unsigned int ret; + asm("mov.u32 %0, %%laneid;" : "=r"(ret) ); + return ret; + } + + template + static __device__ __forceinline__ void fill(It beg, It end, const T& value) + { + for(It t = beg + laneId(); t < end; t += STRIDE) + *t = value; + } + + template + static __device__ __forceinline__ OutIt copy(InIt beg, InIt end, OutIt out) + { + for(InIt t = beg + laneId(); t < end; t += STRIDE, out += STRIDE) + *out = *t; + return out; + } + + template + static __device__ __forceinline__ OutIt transform(InIt beg, InIt end, OutIt out, UnOp op) + { + for(InIt t = beg + laneId(); t < end; t += STRIDE, out += STRIDE) + *out = op(*t); + return out; + } + + template + static __device__ __forceinline__ OutIt transform(InIt1 beg1, InIt1 end1, InIt2 beg2, OutIt out, BinOp op) + { + unsigned int lane = laneId(); + + InIt1 t1 = beg1 + lane; + InIt2 t2 = beg2 + lane; + for(; t1 < end1; t1 += STRIDE, t2 += STRIDE, out += STRIDE) + *out = op(*t1, *t2); + return out; + } + + template + static __device__ __forceinline__ T reduce(volatile T *ptr, BinOp op) + { + const unsigned int lane = laneId(); + + if (lane < 16) + { + T partial = ptr[lane]; + + ptr[lane] = partial = op(partial, ptr[lane + 16]); + ptr[lane] = partial = op(partial, ptr[lane + 8]); + ptr[lane] = partial = op(partial, ptr[lane + 4]); + ptr[lane] = partial = op(partial, ptr[lane + 2]); + ptr[lane] = partial = op(partial, ptr[lane + 1]); + } + + return *ptr; + } + + template + static __device__ __forceinline__ void yota(OutIt beg, OutIt end, T value) + { + unsigned int lane = laneId(); + value += lane; + + for(OutIt t = beg + lane; t < end; t += STRIDE, value += STRIDE) + *t = value; + } + }; +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif /* OPENCV_CUDA_DEVICE_WARP_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/warp_reduce.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/warp_reduce.hpp index 530303d249..ee5c7ab645 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/warp_reduce.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/warp_reduce.hpp @@ -1,76 +1,76 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_WARP_REDUCE_HPP__ -#define OPENCV_CUDA_WARP_REDUCE_HPP__ - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - template - __device__ __forceinline__ T warp_reduce(volatile T *ptr , const unsigned int tid = threadIdx.x) - { - const unsigned int lane = tid & 31; // index of thread in warp (0..31) - - if (lane < 16) - { - T partial = ptr[tid]; - - ptr[tid] = partial = partial + ptr[tid + 16]; - ptr[tid] = partial = partial + ptr[tid + 8]; - ptr[tid] = partial = partial + ptr[tid + 4]; - ptr[tid] = partial = partial + ptr[tid + 2]; - ptr[tid] = partial = partial + ptr[tid + 1]; - } - - return ptr[tid - lane]; - } -}}} // namespace cv { namespace cuda { namespace cudev { - -//! @endcond - -#endif /* OPENCV_CUDA_WARP_REDUCE_HPP__ */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_WARP_REDUCE_HPP__ +#define OPENCV_CUDA_WARP_REDUCE_HPP__ + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + template + __device__ __forceinline__ T warp_reduce(volatile T *ptr , const unsigned int tid = threadIdx.x) + { + const unsigned int lane = tid & 31; // index of thread in warp (0..31) + + if (lane < 16) + { + T partial = ptr[tid]; + + ptr[tid] = partial = partial + ptr[tid + 16]; + ptr[tid] = partial = partial + ptr[tid + 8]; + ptr[tid] = partial = partial + ptr[tid + 4]; + ptr[tid] = partial = partial + ptr[tid + 2]; + ptr[tid] = partial = partial + ptr[tid + 1]; + } + + return ptr[tid - lane]; + } +}}} // namespace cv { namespace cuda { namespace cudev { + +//! @endcond + +#endif /* OPENCV_CUDA_WARP_REDUCE_HPP__ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/warp_shuffle.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/warp_shuffle.hpp index 0da54aee99..e61df5fdc6 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/warp_shuffle.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/warp_shuffle.hpp @@ -1,162 +1,162 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CUDA_WARP_SHUFFLE_HPP -#define OPENCV_CUDA_WARP_SHUFFLE_HPP - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ -#if __CUDACC_VER_MAJOR__ >= 9 -# define __shfl(x, y, z) __shfl_sync(0xFFFFFFFFU, x, y, z) -# define __shfl_up(x, y, z) __shfl_up_sync(0xFFFFFFFFU, x, y, z) -# define __shfl_down(x, y, z) __shfl_down_sync(0xFFFFFFFFU, x, y, z) -#endif - template - __device__ __forceinline__ T shfl(T val, int srcLane, int width = warpSize) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 - return __shfl(val, srcLane, width); - #else - return T(); - #endif - } - __device__ __forceinline__ unsigned int shfl(unsigned int val, int srcLane, int width = warpSize) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 - return (unsigned int) __shfl((int) val, srcLane, width); - #else - return 0; - #endif - } - __device__ __forceinline__ double shfl(double val, int srcLane, int width = warpSize) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 - int lo = __double2loint(val); - int hi = __double2hiint(val); - - lo = __shfl(lo, srcLane, width); - hi = __shfl(hi, srcLane, width); - - return __hiloint2double(hi, lo); - #else - return 0.0; - #endif - } - - template - __device__ __forceinline__ T shfl_down(T val, unsigned int delta, int width = warpSize) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 - return __shfl_down(val, delta, width); - #else - return T(); - #endif - } - __device__ __forceinline__ unsigned int shfl_down(unsigned int val, unsigned int delta, int width = warpSize) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 - return (unsigned int) __shfl_down((int) val, delta, width); - #else - return 0; - #endif - } - __device__ __forceinline__ double shfl_down(double val, unsigned int delta, int width = warpSize) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 - int lo = __double2loint(val); - int hi = __double2hiint(val); - - lo = __shfl_down(lo, delta, width); - hi = __shfl_down(hi, delta, width); - - return __hiloint2double(hi, lo); - #else - return 0.0; - #endif - } - - template - __device__ __forceinline__ T shfl_up(T val, unsigned int delta, int width = warpSize) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 - return __shfl_up(val, delta, width); - #else - return T(); - #endif - } - __device__ __forceinline__ unsigned int shfl_up(unsigned int val, unsigned int delta, int width = warpSize) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 - return (unsigned int) __shfl_up((int) val, delta, width); - #else - return 0; - #endif - } - __device__ __forceinline__ double shfl_up(double val, unsigned int delta, int width = warpSize) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 - int lo = __double2loint(val); - int hi = __double2hiint(val); - - lo = __shfl_up(lo, delta, width); - hi = __shfl_up(hi, delta, width); - - return __hiloint2double(hi, lo); - #else - return 0.0; - #endif - } -}}} - -# undef __shfl -# undef __shfl_up -# undef __shfl_down - -//! @endcond - -#endif // OPENCV_CUDA_WARP_SHUFFLE_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CUDA_WARP_SHUFFLE_HPP +#define OPENCV_CUDA_WARP_SHUFFLE_HPP + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ +#if __CUDACC_VER_MAJOR__ >= 9 +# define __shfl(x, y, z) __shfl_sync(0xFFFFFFFFU, x, y, z) +# define __shfl_up(x, y, z) __shfl_up_sync(0xFFFFFFFFU, x, y, z) +# define __shfl_down(x, y, z) __shfl_down_sync(0xFFFFFFFFU, x, y, z) +#endif + template + __device__ __forceinline__ T shfl(T val, int srcLane, int width = warpSize) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 + return __shfl(val, srcLane, width); + #else + return T(); + #endif + } + __device__ __forceinline__ unsigned int shfl(unsigned int val, int srcLane, int width = warpSize) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 + return (unsigned int) __shfl((int) val, srcLane, width); + #else + return 0; + #endif + } + __device__ __forceinline__ double shfl(double val, int srcLane, int width = warpSize) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 + int lo = __double2loint(val); + int hi = __double2hiint(val); + + lo = __shfl(lo, srcLane, width); + hi = __shfl(hi, srcLane, width); + + return __hiloint2double(hi, lo); + #else + return 0.0; + #endif + } + + template + __device__ __forceinline__ T shfl_down(T val, unsigned int delta, int width = warpSize) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 + return __shfl_down(val, delta, width); + #else + return T(); + #endif + } + __device__ __forceinline__ unsigned int shfl_down(unsigned int val, unsigned int delta, int width = warpSize) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 + return (unsigned int) __shfl_down((int) val, delta, width); + #else + return 0; + #endif + } + __device__ __forceinline__ double shfl_down(double val, unsigned int delta, int width = warpSize) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 + int lo = __double2loint(val); + int hi = __double2hiint(val); + + lo = __shfl_down(lo, delta, width); + hi = __shfl_down(hi, delta, width); + + return __hiloint2double(hi, lo); + #else + return 0.0; + #endif + } + + template + __device__ __forceinline__ T shfl_up(T val, unsigned int delta, int width = warpSize) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 + return __shfl_up(val, delta, width); + #else + return T(); + #endif + } + __device__ __forceinline__ unsigned int shfl_up(unsigned int val, unsigned int delta, int width = warpSize) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 + return (unsigned int) __shfl_up((int) val, delta, width); + #else + return 0; + #endif + } + __device__ __forceinline__ double shfl_up(double val, unsigned int delta, int width = warpSize) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 + int lo = __double2loint(val); + int hi = __double2hiint(val); + + lo = __shfl_up(lo, delta, width); + hi = __shfl_up(hi, delta, width); + + return __hiloint2double(hi, lo); + #else + return 0.0; + #endif + } +}}} + +# undef __shfl +# undef __shfl_up +# undef __shfl_down + +//! @endcond + +#endif // OPENCV_CUDA_WARP_SHUFFLE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda_stream_accessor.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda_stream_accessor.hpp index deaf356fff..507194286e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda_stream_accessor.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda_stream_accessor.hpp @@ -1,86 +1,86 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CORE_CUDA_STREAM_ACCESSOR_HPP -#define OPENCV_CORE_CUDA_STREAM_ACCESSOR_HPP - -#ifndef __cplusplus -# error cuda_stream_accessor.hpp header must be compiled as C++ -#endif - -/** @file cuda_stream_accessor.hpp - * This is only header file that depends on CUDA Runtime API. All other headers are independent. - */ - -#include -#include "opencv2/core/cuda.hpp" - -namespace cv -{ - namespace cuda - { - -//! @addtogroup cudacore_struct -//! @{ - - /** @brief Class that enables getting cudaStream_t from cuda::Stream - */ - struct StreamAccessor - { - CV_EXPORTS static cudaStream_t getStream(const Stream& stream); - CV_EXPORTS static Stream wrapStream(cudaStream_t stream); - }; - - /** @brief Class that enables getting cudaEvent_t from cuda::Event - */ - struct EventAccessor - { - CV_EXPORTS static cudaEvent_t getEvent(const Event& event); - CV_EXPORTS static Event wrapEvent(cudaEvent_t event); - }; - -//! @} - - } -} - -#endif /* OPENCV_CORE_CUDA_STREAM_ACCESSOR_HPP */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CORE_CUDA_STREAM_ACCESSOR_HPP +#define OPENCV_CORE_CUDA_STREAM_ACCESSOR_HPP + +#ifndef __cplusplus +# error cuda_stream_accessor.hpp header must be compiled as C++ +#endif + +/** @file cuda_stream_accessor.hpp + * This is only header file that depends on CUDA Runtime API. All other headers are independent. + */ + +#include +#include "opencv2/core/cuda.hpp" + +namespace cv +{ + namespace cuda + { + +//! @addtogroup cudacore_struct +//! @{ + + /** @brief Class that enables getting cudaStream_t from cuda::Stream + */ + struct StreamAccessor + { + CV_EXPORTS static cudaStream_t getStream(const Stream& stream); + CV_EXPORTS static Stream wrapStream(cudaStream_t stream); + }; + + /** @brief Class that enables getting cudaEvent_t from cuda::Event + */ + struct EventAccessor + { + CV_EXPORTS static cudaEvent_t getEvent(const Event& event); + CV_EXPORTS static Event wrapEvent(cudaEvent_t event); + }; + +//! @} + + } +} + +#endif /* OPENCV_CORE_CUDA_STREAM_ACCESSOR_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda_types.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda_types.hpp index ddee2f3d59..73131b1d32 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda_types.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda_types.hpp @@ -1,152 +1,152 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CORE_CUDA_TYPES_HPP -#define OPENCV_CORE_CUDA_TYPES_HPP - -#ifndef __cplusplus -# error cuda_types.hpp header must be compiled as C++ -#endif - -#if defined(__OPENCV_BUILD) && defined(__clang__) -#pragma clang diagnostic ignored "-Winconsistent-missing-override" -#endif -#if defined(__OPENCV_BUILD) && defined(__GNUC__) && __GNUC__ >= 5 -#pragma GCC diagnostic ignored "-Wsuggest-override" -#endif - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -#ifdef __CUDACC__ - #define __CV_CUDA_HOST_DEVICE__ __host__ __device__ __forceinline__ -#else - #define __CV_CUDA_HOST_DEVICE__ -#endif - -#include "opencv2/core/cvdef.h" -#include "opencv2/core.hpp" - -namespace cv -{ - namespace cuda - { - - // Simple lightweight structures that encapsulates information about an image on device. - // It is intended to pass to nvcc-compiled code. GpuMat depends on headers that nvcc can't compile - - template struct DevPtr - { - typedef T elem_type; - typedef int index_type; - - enum { elem_size = sizeof(elem_type) }; - - T* data; - - __CV_CUDA_HOST_DEVICE__ DevPtr() : data(0) {} - __CV_CUDA_HOST_DEVICE__ DevPtr(T* data_) : data(data_) {} - - __CV_CUDA_HOST_DEVICE__ size_t elemSize() const { return elem_size; } - __CV_CUDA_HOST_DEVICE__ operator T*() { return data; } - __CV_CUDA_HOST_DEVICE__ operator const T*() const { return data; } - }; - - template struct PtrSz : public DevPtr - { - __CV_CUDA_HOST_DEVICE__ PtrSz() : size(0) {} - __CV_CUDA_HOST_DEVICE__ PtrSz(T* data_, size_t size_) : DevPtr(data_), size(size_) {} - - size_t size; - }; - - template struct PtrStep : public DevPtr - { - __CV_CUDA_HOST_DEVICE__ PtrStep() : step(0) {} - __CV_CUDA_HOST_DEVICE__ PtrStep(T* data_, size_t step_) : DevPtr(data_), step(step_) {} - - size_t step; - - __CV_CUDA_HOST_DEVICE__ T* ptr(int y = 0) { return ( T*)( ( char*)(((DevPtr*)this)->data) + y * step); } - __CV_CUDA_HOST_DEVICE__ const T* ptr(int y = 0) const { return (const T*)( (const char*)(((DevPtr*)this)->data) + y * step); } - - __CV_CUDA_HOST_DEVICE__ T& operator ()(int y, int x) { return ptr(y)[x]; } - __CV_CUDA_HOST_DEVICE__ const T& operator ()(int y, int x) const { return ptr(y)[x]; } - }; - - template struct PtrStepSz : public PtrStep - { - __CV_CUDA_HOST_DEVICE__ PtrStepSz() : cols(0), rows(0) {} - __CV_CUDA_HOST_DEVICE__ PtrStepSz(int rows_, int cols_, T* data_, size_t step_) - : PtrStep(data_, step_), cols(cols_), rows(rows_) {} - - template - explicit PtrStepSz(const PtrStepSz& d) : PtrStep((T*)d.data, d.step), cols(d.cols), rows(d.rows){} - - int cols; - int rows; - - CV_NODISCARD_STD __CV_CUDA_HOST_DEVICE__ Size size() const { return {cols, rows}; } - CV_NODISCARD_STD __CV_CUDA_HOST_DEVICE__ T& operator ()(const Point &pos) { return (*this)(pos.y, pos.x); } - CV_NODISCARD_STD __CV_CUDA_HOST_DEVICE__ const T& operator ()(const Point &pos) const { return (*this)(pos.y, pos.x); } - using PtrStep::operator(); - }; - - typedef PtrStepSz PtrStepSzb; - typedef PtrStepSz PtrStepSzus; - typedef PtrStepSz PtrStepSzf; - typedef PtrStepSz PtrStepSzi; - - typedef PtrStep PtrStepb; - typedef PtrStep PtrStepus; - typedef PtrStep PtrStepf; - typedef PtrStep PtrStepi; - - } -} - -//! @endcond - -#endif /* OPENCV_CORE_CUDA_TYPES_HPP */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CORE_CUDA_TYPES_HPP +#define OPENCV_CORE_CUDA_TYPES_HPP + +#ifndef __cplusplus +# error cuda_types.hpp header must be compiled as C++ +#endif + +#if defined(__OPENCV_BUILD) && defined(__clang__) +#pragma clang diagnostic ignored "-Winconsistent-missing-override" +#endif +#if defined(__OPENCV_BUILD) && defined(__GNUC__) && __GNUC__ >= 5 +#pragma GCC diagnostic ignored "-Wsuggest-override" +#endif + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +#ifdef __CUDACC__ + #define __CV_CUDA_HOST_DEVICE__ __host__ __device__ __forceinline__ +#else + #define __CV_CUDA_HOST_DEVICE__ +#endif + +#include "opencv2/core/cvdef.h" +#include "opencv2/core.hpp" + +namespace cv +{ + namespace cuda + { + + // Simple lightweight structures that encapsulates information about an image on device. + // It is intended to pass to nvcc-compiled code. GpuMat depends on headers that nvcc can't compile + + template struct DevPtr + { + typedef T elem_type; + typedef int index_type; + + enum { elem_size = sizeof(elem_type) }; + + T* data; + + __CV_CUDA_HOST_DEVICE__ DevPtr() : data(0) {} + __CV_CUDA_HOST_DEVICE__ DevPtr(T* data_) : data(data_) {} + + __CV_CUDA_HOST_DEVICE__ size_t elemSize() const { return elem_size; } + __CV_CUDA_HOST_DEVICE__ operator T*() { return data; } + __CV_CUDA_HOST_DEVICE__ operator const T*() const { return data; } + }; + + template struct PtrSz : public DevPtr + { + __CV_CUDA_HOST_DEVICE__ PtrSz() : size(0) {} + __CV_CUDA_HOST_DEVICE__ PtrSz(T* data_, size_t size_) : DevPtr(data_), size(size_) {} + + size_t size; + }; + + template struct PtrStep : public DevPtr + { + __CV_CUDA_HOST_DEVICE__ PtrStep() : step(0) {} + __CV_CUDA_HOST_DEVICE__ PtrStep(T* data_, size_t step_) : DevPtr(data_), step(step_) {} + + size_t step; + + __CV_CUDA_HOST_DEVICE__ T* ptr(int y = 0) { return ( T*)( ( char*)(((DevPtr*)this)->data) + y * step); } + __CV_CUDA_HOST_DEVICE__ const T* ptr(int y = 0) const { return (const T*)( (const char*)(((DevPtr*)this)->data) + y * step); } + + __CV_CUDA_HOST_DEVICE__ T& operator ()(int y, int x) { return ptr(y)[x]; } + __CV_CUDA_HOST_DEVICE__ const T& operator ()(int y, int x) const { return ptr(y)[x]; } + }; + + template struct PtrStepSz : public PtrStep + { + __CV_CUDA_HOST_DEVICE__ PtrStepSz() : cols(0), rows(0) {} + __CV_CUDA_HOST_DEVICE__ PtrStepSz(int rows_, int cols_, T* data_, size_t step_) + : PtrStep(data_, step_), cols(cols_), rows(rows_) {} + + template + explicit PtrStepSz(const PtrStepSz& d) : PtrStep((T*)d.data, d.step), cols(d.cols), rows(d.rows){} + + int cols; + int rows; + + CV_NODISCARD_STD __CV_CUDA_HOST_DEVICE__ Size size() const { return {cols, rows}; } + CV_NODISCARD_STD __CV_CUDA_HOST_DEVICE__ T& operator ()(const Point &pos) { return (*this)(pos.y, pos.x); } + CV_NODISCARD_STD __CV_CUDA_HOST_DEVICE__ const T& operator ()(const Point &pos) const { return (*this)(pos.y, pos.x); } + using PtrStep::operator(); + }; + + typedef PtrStepSz PtrStepSzb; + typedef PtrStepSz PtrStepSzus; + typedef PtrStepSz PtrStepSzf; + typedef PtrStepSz PtrStepSzi; + + typedef PtrStep PtrStepb; + typedef PtrStep PtrStepus; + typedef PtrStep PtrStepf; + typedef PtrStep PtrStepi; + + } +} + +//! @endcond + +#endif /* OPENCV_CORE_CUDA_TYPES_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cv_cpu_dispatch.h b/3rdParty/opencv-4.11.0/opencv2/core/cv_cpu_dispatch.h index 607f286615..fb4f4a133b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cv_cpu_dispatch.h +++ b/3rdParty/opencv-4.11.0/opencv2/core/cv_cpu_dispatch.h @@ -1,395 +1,395 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#if defined __OPENCV_BUILD \ - -#include "cv_cpu_config.h" -#include "cv_cpu_helper.h" - -#ifdef CV_CPU_DISPATCH_MODE -#define CV_CPU_OPTIMIZATION_NAMESPACE __CV_CAT(opt_, CV_CPU_DISPATCH_MODE) -#define CV_CPU_OPTIMIZATION_NAMESPACE_BEGIN namespace __CV_CAT(opt_, CV_CPU_DISPATCH_MODE) { -#define CV_CPU_OPTIMIZATION_NAMESPACE_END } -#else -#define CV_CPU_OPTIMIZATION_NAMESPACE cpu_baseline -#define CV_CPU_OPTIMIZATION_NAMESPACE_BEGIN namespace cpu_baseline { -#define CV_CPU_OPTIMIZATION_NAMESPACE_END } -#define CV_CPU_BASELINE_MODE 1 -#endif - - -#define __CV_CPU_DISPATCH_CHAIN_END(fn, args, mode, ...) /* done */ -#define __CV_CPU_DISPATCH(fn, args, mode, ...) __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) -#define __CV_CPU_DISPATCH_EXPAND(fn, args, ...) __CV_EXPAND(__CV_CPU_DISPATCH(fn, args, __VA_ARGS__)) -#define CV_CPU_DISPATCH(fn, args, ...) __CV_CPU_DISPATCH_EXPAND(fn, args, __VA_ARGS__, END) // expand macros - - -#if defined CV_ENABLE_INTRINSICS \ - && !defined CV_DISABLE_OPTIMIZATION \ - && !defined __CUDACC__ /* do not include SSE/AVX/NEON headers for NVCC compiler */ \ - -#ifdef CV_CPU_COMPILE_SSE2 -# include -# define CV_MMX 1 -# define CV_SSE 1 -# define CV_SSE2 1 -#endif -#ifdef CV_CPU_COMPILE_SSE3 -# include -# define CV_SSE3 1 -#endif -#ifdef CV_CPU_COMPILE_SSSE3 -# include -# define CV_SSSE3 1 -#endif -#ifdef CV_CPU_COMPILE_SSE4_1 -# include -# define CV_SSE4_1 1 -#endif -#ifdef CV_CPU_COMPILE_SSE4_2 -# include -# define CV_SSE4_2 1 -#endif -#ifdef CV_CPU_COMPILE_POPCNT -# ifdef _MSC_VER -# include -# if defined(_M_X64) -# define CV_POPCNT_U64 (int)_mm_popcnt_u64 -# endif -# define CV_POPCNT_U32 _mm_popcnt_u32 -# else -# include -# if defined(__x86_64__) -# define CV_POPCNT_U64 __builtin_popcountll -# endif -# define CV_POPCNT_U32 __builtin_popcount -# endif -# define CV_POPCNT 1 -#endif -#ifdef CV_CPU_COMPILE_AVX -# include -# define CV_AVX 1 -#endif -#ifdef CV_CPU_COMPILE_FP16 -# if defined(__arm__) || defined(__aarch64__) || defined(_M_ARM) || defined(_M_ARM64) -# include -# else -# include -# endif -# define CV_FP16 1 -#endif -#ifdef CV_CPU_COMPILE_NEON_DOTPROD -# include -# define CV_NEON_DOT 1 -#endif -#ifdef CV_CPU_COMPILE_AVX2 -# include -# define CV_AVX2 1 -#endif -#ifdef CV_CPU_COMPILE_AVX_512F -# include -# define CV_AVX_512F 1 -#endif -#ifdef CV_CPU_COMPILE_AVX512_COMMON -# define CV_AVX512_COMMON 1 -# define CV_AVX_512CD 1 -#endif -#ifdef CV_CPU_COMPILE_AVX512_KNL -# define CV_AVX512_KNL 1 -# define CV_AVX_512ER 1 -# define CV_AVX_512PF 1 -#endif -#ifdef CV_CPU_COMPILE_AVX512_KNM -# define CV_AVX512_KNM 1 -# define CV_AVX_5124FMAPS 1 -# define CV_AVX_5124VNNIW 1 -# define CV_AVX_512VPOPCNTDQ 1 -#endif -#ifdef CV_CPU_COMPILE_AVX512_SKX -# define CV_AVX512_SKX 1 -# define CV_AVX_512VL 1 -# define CV_AVX_512BW 1 -# define CV_AVX_512DQ 1 -#endif -#ifdef CV_CPU_COMPILE_AVX512_CNL -# define CV_AVX512_CNL 1 -# define CV_AVX_512IFMA 1 -# define CV_AVX_512VBMI 1 -#endif -#ifdef CV_CPU_COMPILE_AVX512_CLX -# define CV_AVX512_CLX 1 -# define CV_AVX_512VNNI 1 -#endif -#ifdef CV_CPU_COMPILE_AVX512_ICL -# define CV_AVX512_ICL 1 -# undef CV_AVX_512IFMA -# define CV_AVX_512IFMA 1 -# undef CV_AVX_512VBMI -# define CV_AVX_512VBMI 1 -# undef CV_AVX_512VNNI -# define CV_AVX_512VNNI 1 -# define CV_AVX_512VBMI2 1 -# define CV_AVX_512BITALG 1 -# define CV_AVX_512VPOPCNTDQ 1 -#endif -#ifdef CV_CPU_COMPILE_FMA3 -# define CV_FMA3 1 -#endif - -#if defined _WIN32 && (defined(_M_ARM) || defined(_M_ARM64)) && (defined(CV_CPU_COMPILE_NEON) || !defined(_MSC_VER)) -# include -# include -# define CV_NEON 1 -#elif defined(__ARM_NEON) -# include -# define CV_NEON 1 -#endif - -/* RVV-related macro states with different compiler -// +--------------------+----------+----------+ -// | Macro | Upstream | XuanTie | -// +--------------------+----------+----------+ -// | CV_CPU_COMPILE_RVV | defined | defined | -// | CV_RVV | 1 | 0 | -// | CV_RVV071 | 0 | 1 | -// | CV_TRY_RVV | 1 | 1 | -// +--------------------+----------+----------+ -*/ -#ifdef CV_CPU_COMPILE_RVV -# ifdef __riscv_vector_071 -# define CV_RVV071 1 -# else -# define CV_RVV 1 -# endif -#include -#endif - -#ifdef CV_CPU_COMPILE_VSX -# include -# undef vector -# undef pixel -# undef bool -# define CV_VSX 1 -#endif - -#ifdef CV_CPU_COMPILE_VSX3 -# define CV_VSX3 1 -#endif - -#ifdef CV_CPU_COMPILE_MSA -# include "hal/msa_macros.h" -# define CV_MSA 1 -#endif - -#ifdef CV_CPU_COMPILE_LSX -# include -# define CV_LSX 1 -#endif - -#ifdef CV_CPU_COMPILE_LASX -# include -# define CV_LASX 1 -#endif - -#ifdef __EMSCRIPTEN__ -# define CV_WASM_SIMD 1 -# include -#endif - -#endif // CV_ENABLE_INTRINSICS && !CV_DISABLE_OPTIMIZATION && !__CUDACC__ - -#if defined CV_CPU_COMPILE_AVX && !defined CV_CPU_BASELINE_COMPILE_AVX -struct VZeroUpperGuard { -#ifdef __GNUC__ - __attribute__((always_inline)) -#endif - inline VZeroUpperGuard() { _mm256_zeroupper(); } -#ifdef __GNUC__ - __attribute__((always_inline)) -#endif - inline ~VZeroUpperGuard() { _mm256_zeroupper(); } -}; -#define __CV_AVX_GUARD VZeroUpperGuard __vzeroupper_guard; CV_UNUSED(__vzeroupper_guard); -#endif - -#ifdef __CV_AVX_GUARD -#define CV_AVX_GUARD __CV_AVX_GUARD -#else -#define CV_AVX_GUARD -#endif - -#endif // __OPENCV_BUILD - - - -#if !defined __OPENCV_BUILD /* Compatibility code */ \ - && !defined __CUDACC__ /* do not include SSE/AVX/NEON headers for NVCC compiler */ -#if defined __SSE2__ || defined _M_X64 || (defined _M_IX86_FP && _M_IX86_FP >= 2) -# include -# define CV_MMX 1 -# define CV_SSE 1 -# define CV_SSE2 1 -#elif defined _WIN32 && (defined(_M_ARM) || defined(_M_ARM64)) && (defined(CV_CPU_COMPILE_NEON) || !defined(_MSC_VER)) -# include -# include -# define CV_NEON 1 -#elif defined(__ARM_NEON) -# include -# define CV_NEON 1 -#elif defined(__VSX__) && defined(__PPC64__) && defined(__LITTLE_ENDIAN__) -# include -# undef vector -# undef pixel -# undef bool -# define CV_VSX 1 -#endif - -#ifdef __F16C__ -# include -# define CV_FP16 1 -#endif - -#endif // !__OPENCV_BUILD && !__CUDACC (Compatibility code) - - - -#ifndef CV_MMX -# define CV_MMX 0 -#endif -#ifndef CV_SSE -# define CV_SSE 0 -#endif -#ifndef CV_SSE2 -# define CV_SSE2 0 -#endif -#ifndef CV_SSE3 -# define CV_SSE3 0 -#endif -#ifndef CV_SSSE3 -# define CV_SSSE3 0 -#endif -#ifndef CV_SSE4_1 -# define CV_SSE4_1 0 -#endif -#ifndef CV_SSE4_2 -# define CV_SSE4_2 0 -#endif -#ifndef CV_POPCNT -# define CV_POPCNT 0 -#endif -#ifndef CV_AVX -# define CV_AVX 0 -#endif -#ifndef CV_FP16 -# define CV_FP16 0 -#endif -#ifndef CV_AVX2 -# define CV_AVX2 0 -#endif -#ifndef CV_FMA3 -# define CV_FMA3 0 -#endif -#ifndef CV_AVX_512F -# define CV_AVX_512F 0 -#endif -#ifndef CV_AVX_512BW -# define CV_AVX_512BW 0 -#endif -#ifndef CV_AVX_512CD -# define CV_AVX_512CD 0 -#endif -#ifndef CV_AVX_512DQ -# define CV_AVX_512DQ 0 -#endif -#ifndef CV_AVX_512ER -# define CV_AVX_512ER 0 -#endif -#ifndef CV_AVX_512IFMA -# define CV_AVX_512IFMA 0 -#endif -#define CV_AVX_512IFMA512 CV_AVX_512IFMA // deprecated -#ifndef CV_AVX_512PF -# define CV_AVX_512PF 0 -#endif -#ifndef CV_AVX_512VBMI -# define CV_AVX_512VBMI 0 -#endif -#ifndef CV_AVX_512VL -# define CV_AVX_512VL 0 -#endif -#ifndef CV_AVX_5124FMAPS -# define CV_AVX_5124FMAPS 0 -#endif -#ifndef CV_AVX_5124VNNIW -# define CV_AVX_5124VNNIW 0 -#endif -#ifndef CV_AVX_512VPOPCNTDQ -# define CV_AVX_512VPOPCNTDQ 0 -#endif -#ifndef CV_AVX_512VNNI -# define CV_AVX_512VNNI 0 -#endif -#ifndef CV_AVX_512VBMI2 -# define CV_AVX_512VBMI2 0 -#endif -#ifndef CV_AVX_512BITALG -# define CV_AVX_512BITALG 0 -#endif -#ifndef CV_AVX512_COMMON -# define CV_AVX512_COMMON 0 -#endif -#ifndef CV_AVX512_KNL -# define CV_AVX512_KNL 0 -#endif -#ifndef CV_AVX512_KNM -# define CV_AVX512_KNM 0 -#endif -#ifndef CV_AVX512_SKX -# define CV_AVX512_SKX 0 -#endif -#ifndef CV_AVX512_CNL -# define CV_AVX512_CNL 0 -#endif -#ifndef CV_AVX512_CLX -# define CV_AVX512_CLX 0 -#endif -#ifndef CV_AVX512_ICL -# define CV_AVX512_ICL 0 -#endif - -#ifndef CV_NEON -# define CV_NEON 0 -#endif - -#ifndef CV_RVV071 -# define CV_RVV071 0 -#endif - -#ifndef CV_VSX -# define CV_VSX 0 -#endif - -#ifndef CV_VSX3 -# define CV_VSX3 0 -#endif - -#ifndef CV_MSA -# define CV_MSA 0 -#endif - -#ifndef CV_WASM_SIMD -# define CV_WASM_SIMD 0 -#endif - -#ifndef CV_RVV -# define CV_RVV 0 -#endif - -#ifndef CV_LSX -# define CV_LSX 0 -#endif - -#ifndef CV_LASX -# define CV_LASX 0 -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#if defined __OPENCV_BUILD \ + +#include "cv_cpu_config.h" +#include "cv_cpu_helper.h" + +#ifdef CV_CPU_DISPATCH_MODE +#define CV_CPU_OPTIMIZATION_NAMESPACE __CV_CAT(opt_, CV_CPU_DISPATCH_MODE) +#define CV_CPU_OPTIMIZATION_NAMESPACE_BEGIN namespace __CV_CAT(opt_, CV_CPU_DISPATCH_MODE) { +#define CV_CPU_OPTIMIZATION_NAMESPACE_END } +#else +#define CV_CPU_OPTIMIZATION_NAMESPACE cpu_baseline +#define CV_CPU_OPTIMIZATION_NAMESPACE_BEGIN namespace cpu_baseline { +#define CV_CPU_OPTIMIZATION_NAMESPACE_END } +#define CV_CPU_BASELINE_MODE 1 +#endif + + +#define __CV_CPU_DISPATCH_CHAIN_END(fn, args, mode, ...) /* done */ +#define __CV_CPU_DISPATCH(fn, args, mode, ...) __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) +#define __CV_CPU_DISPATCH_EXPAND(fn, args, ...) __CV_EXPAND(__CV_CPU_DISPATCH(fn, args, __VA_ARGS__)) +#define CV_CPU_DISPATCH(fn, args, ...) __CV_CPU_DISPATCH_EXPAND(fn, args, __VA_ARGS__, END) // expand macros + + +#if defined CV_ENABLE_INTRINSICS \ + && !defined CV_DISABLE_OPTIMIZATION \ + && !defined __CUDACC__ /* do not include SSE/AVX/NEON headers for NVCC compiler */ \ + +#ifdef CV_CPU_COMPILE_SSE2 +# include +# define CV_MMX 1 +# define CV_SSE 1 +# define CV_SSE2 1 +#endif +#ifdef CV_CPU_COMPILE_SSE3 +# include +# define CV_SSE3 1 +#endif +#ifdef CV_CPU_COMPILE_SSSE3 +# include +# define CV_SSSE3 1 +#endif +#ifdef CV_CPU_COMPILE_SSE4_1 +# include +# define CV_SSE4_1 1 +#endif +#ifdef CV_CPU_COMPILE_SSE4_2 +# include +# define CV_SSE4_2 1 +#endif +#ifdef CV_CPU_COMPILE_POPCNT +# ifdef _MSC_VER +# include +# if defined(_M_X64) +# define CV_POPCNT_U64 (int)_mm_popcnt_u64 +# endif +# define CV_POPCNT_U32 _mm_popcnt_u32 +# else +# include +# if defined(__x86_64__) +# define CV_POPCNT_U64 __builtin_popcountll +# endif +# define CV_POPCNT_U32 __builtin_popcount +# endif +# define CV_POPCNT 1 +#endif +#ifdef CV_CPU_COMPILE_AVX +# include +# define CV_AVX 1 +#endif +#ifdef CV_CPU_COMPILE_FP16 +# if defined(__arm__) || defined(__aarch64__) || defined(_M_ARM) || defined(_M_ARM64) +# include +# else +# include +# endif +# define CV_FP16 1 +#endif +#ifdef CV_CPU_COMPILE_NEON_DOTPROD +# include +# define CV_NEON_DOT 1 +#endif +#ifdef CV_CPU_COMPILE_AVX2 +# include +# define CV_AVX2 1 +#endif +#ifdef CV_CPU_COMPILE_AVX_512F +# include +# define CV_AVX_512F 1 +#endif +#ifdef CV_CPU_COMPILE_AVX512_COMMON +# define CV_AVX512_COMMON 1 +# define CV_AVX_512CD 1 +#endif +#ifdef CV_CPU_COMPILE_AVX512_KNL +# define CV_AVX512_KNL 1 +# define CV_AVX_512ER 1 +# define CV_AVX_512PF 1 +#endif +#ifdef CV_CPU_COMPILE_AVX512_KNM +# define CV_AVX512_KNM 1 +# define CV_AVX_5124FMAPS 1 +# define CV_AVX_5124VNNIW 1 +# define CV_AVX_512VPOPCNTDQ 1 +#endif +#ifdef CV_CPU_COMPILE_AVX512_SKX +# define CV_AVX512_SKX 1 +# define CV_AVX_512VL 1 +# define CV_AVX_512BW 1 +# define CV_AVX_512DQ 1 +#endif +#ifdef CV_CPU_COMPILE_AVX512_CNL +# define CV_AVX512_CNL 1 +# define CV_AVX_512IFMA 1 +# define CV_AVX_512VBMI 1 +#endif +#ifdef CV_CPU_COMPILE_AVX512_CLX +# define CV_AVX512_CLX 1 +# define CV_AVX_512VNNI 1 +#endif +#ifdef CV_CPU_COMPILE_AVX512_ICL +# define CV_AVX512_ICL 1 +# undef CV_AVX_512IFMA +# define CV_AVX_512IFMA 1 +# undef CV_AVX_512VBMI +# define CV_AVX_512VBMI 1 +# undef CV_AVX_512VNNI +# define CV_AVX_512VNNI 1 +# define CV_AVX_512VBMI2 1 +# define CV_AVX_512BITALG 1 +# define CV_AVX_512VPOPCNTDQ 1 +#endif +#ifdef CV_CPU_COMPILE_FMA3 +# define CV_FMA3 1 +#endif + +#if defined _WIN32 && (defined(_M_ARM) || defined(_M_ARM64)) && (defined(CV_CPU_COMPILE_NEON) || !defined(_MSC_VER)) +# include +# include +# define CV_NEON 1 +#elif defined(__ARM_NEON) +# include +# define CV_NEON 1 +#endif + +/* RVV-related macro states with different compiler +// +--------------------+----------+----------+ +// | Macro | Upstream | XuanTie | +// +--------------------+----------+----------+ +// | CV_CPU_COMPILE_RVV | defined | defined | +// | CV_RVV | 1 | 0 | +// | CV_RVV071 | 0 | 1 | +// | CV_TRY_RVV | 1 | 1 | +// +--------------------+----------+----------+ +*/ +#ifdef CV_CPU_COMPILE_RVV +# ifdef __riscv_vector_071 +# define CV_RVV071 1 +# else +# define CV_RVV 1 +# endif +#include +#endif + +#ifdef CV_CPU_COMPILE_VSX +# include +# undef vector +# undef pixel +# undef bool +# define CV_VSX 1 +#endif + +#ifdef CV_CPU_COMPILE_VSX3 +# define CV_VSX3 1 +#endif + +#ifdef CV_CPU_COMPILE_MSA +# include "hal/msa_macros.h" +# define CV_MSA 1 +#endif + +#ifdef CV_CPU_COMPILE_LSX +# include +# define CV_LSX 1 +#endif + +#ifdef CV_CPU_COMPILE_LASX +# include +# define CV_LASX 1 +#endif + +#ifdef __EMSCRIPTEN__ +# define CV_WASM_SIMD 1 +# include +#endif + +#endif // CV_ENABLE_INTRINSICS && !CV_DISABLE_OPTIMIZATION && !__CUDACC__ + +#if defined CV_CPU_COMPILE_AVX && !defined CV_CPU_BASELINE_COMPILE_AVX +struct VZeroUpperGuard { +#ifdef __GNUC__ + __attribute__((always_inline)) +#endif + inline VZeroUpperGuard() { _mm256_zeroupper(); } +#ifdef __GNUC__ + __attribute__((always_inline)) +#endif + inline ~VZeroUpperGuard() { _mm256_zeroupper(); } +}; +#define __CV_AVX_GUARD VZeroUpperGuard __vzeroupper_guard; CV_UNUSED(__vzeroupper_guard); +#endif + +#ifdef __CV_AVX_GUARD +#define CV_AVX_GUARD __CV_AVX_GUARD +#else +#define CV_AVX_GUARD +#endif + +#endif // __OPENCV_BUILD + + + +#if !defined __OPENCV_BUILD /* Compatibility code */ \ + && !defined __CUDACC__ /* do not include SSE/AVX/NEON headers for NVCC compiler */ +#if defined __SSE2__ || defined _M_X64 || (defined _M_IX86_FP && _M_IX86_FP >= 2) +# include +# define CV_MMX 1 +# define CV_SSE 1 +# define CV_SSE2 1 +#elif defined _WIN32 && (defined(_M_ARM) || defined(_M_ARM64)) && (defined(CV_CPU_COMPILE_NEON) || !defined(_MSC_VER)) +# include +# include +# define CV_NEON 1 +#elif defined(__ARM_NEON) +# include +# define CV_NEON 1 +#elif defined(__VSX__) && defined(__PPC64__) && defined(__LITTLE_ENDIAN__) +# include +# undef vector +# undef pixel +# undef bool +# define CV_VSX 1 +#endif + +#ifdef __F16C__ +# include +# define CV_FP16 1 +#endif + +#endif // !__OPENCV_BUILD && !__CUDACC (Compatibility code) + + + +#ifndef CV_MMX +# define CV_MMX 0 +#endif +#ifndef CV_SSE +# define CV_SSE 0 +#endif +#ifndef CV_SSE2 +# define CV_SSE2 0 +#endif +#ifndef CV_SSE3 +# define CV_SSE3 0 +#endif +#ifndef CV_SSSE3 +# define CV_SSSE3 0 +#endif +#ifndef CV_SSE4_1 +# define CV_SSE4_1 0 +#endif +#ifndef CV_SSE4_2 +# define CV_SSE4_2 0 +#endif +#ifndef CV_POPCNT +# define CV_POPCNT 0 +#endif +#ifndef CV_AVX +# define CV_AVX 0 +#endif +#ifndef CV_FP16 +# define CV_FP16 0 +#endif +#ifndef CV_AVX2 +# define CV_AVX2 0 +#endif +#ifndef CV_FMA3 +# define CV_FMA3 0 +#endif +#ifndef CV_AVX_512F +# define CV_AVX_512F 0 +#endif +#ifndef CV_AVX_512BW +# define CV_AVX_512BW 0 +#endif +#ifndef CV_AVX_512CD +# define CV_AVX_512CD 0 +#endif +#ifndef CV_AVX_512DQ +# define CV_AVX_512DQ 0 +#endif +#ifndef CV_AVX_512ER +# define CV_AVX_512ER 0 +#endif +#ifndef CV_AVX_512IFMA +# define CV_AVX_512IFMA 0 +#endif +#define CV_AVX_512IFMA512 CV_AVX_512IFMA // deprecated +#ifndef CV_AVX_512PF +# define CV_AVX_512PF 0 +#endif +#ifndef CV_AVX_512VBMI +# define CV_AVX_512VBMI 0 +#endif +#ifndef CV_AVX_512VL +# define CV_AVX_512VL 0 +#endif +#ifndef CV_AVX_5124FMAPS +# define CV_AVX_5124FMAPS 0 +#endif +#ifndef CV_AVX_5124VNNIW +# define CV_AVX_5124VNNIW 0 +#endif +#ifndef CV_AVX_512VPOPCNTDQ +# define CV_AVX_512VPOPCNTDQ 0 +#endif +#ifndef CV_AVX_512VNNI +# define CV_AVX_512VNNI 0 +#endif +#ifndef CV_AVX_512VBMI2 +# define CV_AVX_512VBMI2 0 +#endif +#ifndef CV_AVX_512BITALG +# define CV_AVX_512BITALG 0 +#endif +#ifndef CV_AVX512_COMMON +# define CV_AVX512_COMMON 0 +#endif +#ifndef CV_AVX512_KNL +# define CV_AVX512_KNL 0 +#endif +#ifndef CV_AVX512_KNM +# define CV_AVX512_KNM 0 +#endif +#ifndef CV_AVX512_SKX +# define CV_AVX512_SKX 0 +#endif +#ifndef CV_AVX512_CNL +# define CV_AVX512_CNL 0 +#endif +#ifndef CV_AVX512_CLX +# define CV_AVX512_CLX 0 +#endif +#ifndef CV_AVX512_ICL +# define CV_AVX512_ICL 0 +#endif + +#ifndef CV_NEON +# define CV_NEON 0 +#endif + +#ifndef CV_RVV071 +# define CV_RVV071 0 +#endif + +#ifndef CV_VSX +# define CV_VSX 0 +#endif + +#ifndef CV_VSX3 +# define CV_VSX3 0 +#endif + +#ifndef CV_MSA +# define CV_MSA 0 +#endif + +#ifndef CV_WASM_SIMD +# define CV_WASM_SIMD 0 +#endif + +#ifndef CV_RVV +# define CV_RVV 0 +#endif + +#ifndef CV_LSX +# define CV_LSX 0 +#endif + +#ifndef CV_LASX +# define CV_LASX 0 +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cv_cpu_helper.h b/3rdParty/opencv-4.11.0/opencv2/core/cv_cpu_helper.h index 04b00d2024..29952aec36 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cv_cpu_helper.h +++ b/3rdParty/opencv-4.11.0/opencv2/core/cv_cpu_helper.h @@ -1,613 +1,613 @@ -// AUTOGENERATED, DO NOT EDIT - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE -# define CV_TRY_SSE 1 -# define CV_CPU_FORCE_SSE 1 -# define CV_CPU_HAS_SUPPORT_SSE 1 -# define CV_CPU_CALL_SSE(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_SSE_(fn, args) return (opt_SSE::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE -# define CV_TRY_SSE 1 -# define CV_CPU_FORCE_SSE 0 -# define CV_CPU_HAS_SUPPORT_SSE (cv::checkHardwareSupport(CV_CPU_SSE)) -# define CV_CPU_CALL_SSE(fn, args) if (CV_CPU_HAS_SUPPORT_SSE) return (opt_SSE::fn args) -# define CV_CPU_CALL_SSE_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE) return (opt_SSE::fn args) -#else -# define CV_TRY_SSE 0 -# define CV_CPU_FORCE_SSE 0 -# define CV_CPU_HAS_SUPPORT_SSE 0 -# define CV_CPU_CALL_SSE(fn, args) -# define CV_CPU_CALL_SSE_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_SSE(fn, args, mode, ...) CV_CPU_CALL_SSE(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE2 -# define CV_TRY_SSE2 1 -# define CV_CPU_FORCE_SSE2 1 -# define CV_CPU_HAS_SUPPORT_SSE2 1 -# define CV_CPU_CALL_SSE2(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_SSE2_(fn, args) return (opt_SSE2::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE2 -# define CV_TRY_SSE2 1 -# define CV_CPU_FORCE_SSE2 0 -# define CV_CPU_HAS_SUPPORT_SSE2 (cv::checkHardwareSupport(CV_CPU_SSE2)) -# define CV_CPU_CALL_SSE2(fn, args) if (CV_CPU_HAS_SUPPORT_SSE2) return (opt_SSE2::fn args) -# define CV_CPU_CALL_SSE2_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE2) return (opt_SSE2::fn args) -#else -# define CV_TRY_SSE2 0 -# define CV_CPU_FORCE_SSE2 0 -# define CV_CPU_HAS_SUPPORT_SSE2 0 -# define CV_CPU_CALL_SSE2(fn, args) -# define CV_CPU_CALL_SSE2_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_SSE2(fn, args, mode, ...) CV_CPU_CALL_SSE2(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE3 -# define CV_TRY_SSE3 1 -# define CV_CPU_FORCE_SSE3 1 -# define CV_CPU_HAS_SUPPORT_SSE3 1 -# define CV_CPU_CALL_SSE3(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_SSE3_(fn, args) return (opt_SSE3::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE3 -# define CV_TRY_SSE3 1 -# define CV_CPU_FORCE_SSE3 0 -# define CV_CPU_HAS_SUPPORT_SSE3 (cv::checkHardwareSupport(CV_CPU_SSE3)) -# define CV_CPU_CALL_SSE3(fn, args) if (CV_CPU_HAS_SUPPORT_SSE3) return (opt_SSE3::fn args) -# define CV_CPU_CALL_SSE3_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE3) return (opt_SSE3::fn args) -#else -# define CV_TRY_SSE3 0 -# define CV_CPU_FORCE_SSE3 0 -# define CV_CPU_HAS_SUPPORT_SSE3 0 -# define CV_CPU_CALL_SSE3(fn, args) -# define CV_CPU_CALL_SSE3_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_SSE3(fn, args, mode, ...) CV_CPU_CALL_SSE3(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSSE3 -# define CV_TRY_SSSE3 1 -# define CV_CPU_FORCE_SSSE3 1 -# define CV_CPU_HAS_SUPPORT_SSSE3 1 -# define CV_CPU_CALL_SSSE3(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_SSSE3_(fn, args) return (opt_SSSE3::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSSE3 -# define CV_TRY_SSSE3 1 -# define CV_CPU_FORCE_SSSE3 0 -# define CV_CPU_HAS_SUPPORT_SSSE3 (cv::checkHardwareSupport(CV_CPU_SSSE3)) -# define CV_CPU_CALL_SSSE3(fn, args) if (CV_CPU_HAS_SUPPORT_SSSE3) return (opt_SSSE3::fn args) -# define CV_CPU_CALL_SSSE3_(fn, args) if (CV_CPU_HAS_SUPPORT_SSSE3) return (opt_SSSE3::fn args) -#else -# define CV_TRY_SSSE3 0 -# define CV_CPU_FORCE_SSSE3 0 -# define CV_CPU_HAS_SUPPORT_SSSE3 0 -# define CV_CPU_CALL_SSSE3(fn, args) -# define CV_CPU_CALL_SSSE3_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_SSSE3(fn, args, mode, ...) CV_CPU_CALL_SSSE3(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE4_1 -# define CV_TRY_SSE4_1 1 -# define CV_CPU_FORCE_SSE4_1 1 -# define CV_CPU_HAS_SUPPORT_SSE4_1 1 -# define CV_CPU_CALL_SSE4_1(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_SSE4_1_(fn, args) return (opt_SSE4_1::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE4_1 -# define CV_TRY_SSE4_1 1 -# define CV_CPU_FORCE_SSE4_1 0 -# define CV_CPU_HAS_SUPPORT_SSE4_1 (cv::checkHardwareSupport(CV_CPU_SSE4_1)) -# define CV_CPU_CALL_SSE4_1(fn, args) if (CV_CPU_HAS_SUPPORT_SSE4_1) return (opt_SSE4_1::fn args) -# define CV_CPU_CALL_SSE4_1_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE4_1) return (opt_SSE4_1::fn args) -#else -# define CV_TRY_SSE4_1 0 -# define CV_CPU_FORCE_SSE4_1 0 -# define CV_CPU_HAS_SUPPORT_SSE4_1 0 -# define CV_CPU_CALL_SSE4_1(fn, args) -# define CV_CPU_CALL_SSE4_1_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_SSE4_1(fn, args, mode, ...) CV_CPU_CALL_SSE4_1(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE4_2 -# define CV_TRY_SSE4_2 1 -# define CV_CPU_FORCE_SSE4_2 1 -# define CV_CPU_HAS_SUPPORT_SSE4_2 1 -# define CV_CPU_CALL_SSE4_2(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_SSE4_2_(fn, args) return (opt_SSE4_2::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE4_2 -# define CV_TRY_SSE4_2 1 -# define CV_CPU_FORCE_SSE4_2 0 -# define CV_CPU_HAS_SUPPORT_SSE4_2 (cv::checkHardwareSupport(CV_CPU_SSE4_2)) -# define CV_CPU_CALL_SSE4_2(fn, args) if (CV_CPU_HAS_SUPPORT_SSE4_2) return (opt_SSE4_2::fn args) -# define CV_CPU_CALL_SSE4_2_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE4_2) return (opt_SSE4_2::fn args) -#else -# define CV_TRY_SSE4_2 0 -# define CV_CPU_FORCE_SSE4_2 0 -# define CV_CPU_HAS_SUPPORT_SSE4_2 0 -# define CV_CPU_CALL_SSE4_2(fn, args) -# define CV_CPU_CALL_SSE4_2_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_SSE4_2(fn, args, mode, ...) CV_CPU_CALL_SSE4_2(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_POPCNT -# define CV_TRY_POPCNT 1 -# define CV_CPU_FORCE_POPCNT 1 -# define CV_CPU_HAS_SUPPORT_POPCNT 1 -# define CV_CPU_CALL_POPCNT(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_POPCNT_(fn, args) return (opt_POPCNT::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_POPCNT -# define CV_TRY_POPCNT 1 -# define CV_CPU_FORCE_POPCNT 0 -# define CV_CPU_HAS_SUPPORT_POPCNT (cv::checkHardwareSupport(CV_CPU_POPCNT)) -# define CV_CPU_CALL_POPCNT(fn, args) if (CV_CPU_HAS_SUPPORT_POPCNT) return (opt_POPCNT::fn args) -# define CV_CPU_CALL_POPCNT_(fn, args) if (CV_CPU_HAS_SUPPORT_POPCNT) return (opt_POPCNT::fn args) -#else -# define CV_TRY_POPCNT 0 -# define CV_CPU_FORCE_POPCNT 0 -# define CV_CPU_HAS_SUPPORT_POPCNT 0 -# define CV_CPU_CALL_POPCNT(fn, args) -# define CV_CPU_CALL_POPCNT_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_POPCNT(fn, args, mode, ...) CV_CPU_CALL_POPCNT(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX -# define CV_TRY_AVX 1 -# define CV_CPU_FORCE_AVX 1 -# define CV_CPU_HAS_SUPPORT_AVX 1 -# define CV_CPU_CALL_AVX(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_AVX_(fn, args) return (opt_AVX::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX -# define CV_TRY_AVX 1 -# define CV_CPU_FORCE_AVX 0 -# define CV_CPU_HAS_SUPPORT_AVX (cv::checkHardwareSupport(CV_CPU_AVX)) -# define CV_CPU_CALL_AVX(fn, args) if (CV_CPU_HAS_SUPPORT_AVX) return (opt_AVX::fn args) -# define CV_CPU_CALL_AVX_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX) return (opt_AVX::fn args) -#else -# define CV_TRY_AVX 0 -# define CV_CPU_FORCE_AVX 0 -# define CV_CPU_HAS_SUPPORT_AVX 0 -# define CV_CPU_CALL_AVX(fn, args) -# define CV_CPU_CALL_AVX_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_AVX(fn, args, mode, ...) CV_CPU_CALL_AVX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_FP16 -# define CV_TRY_FP16 1 -# define CV_CPU_FORCE_FP16 1 -# define CV_CPU_HAS_SUPPORT_FP16 1 -# define CV_CPU_CALL_FP16(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_FP16_(fn, args) return (opt_FP16::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_FP16 -# define CV_TRY_FP16 1 -# define CV_CPU_FORCE_FP16 0 -# define CV_CPU_HAS_SUPPORT_FP16 (cv::checkHardwareSupport(CV_CPU_FP16)) -# define CV_CPU_CALL_FP16(fn, args) if (CV_CPU_HAS_SUPPORT_FP16) return (opt_FP16::fn args) -# define CV_CPU_CALL_FP16_(fn, args) if (CV_CPU_HAS_SUPPORT_FP16) return (opt_FP16::fn args) -#else -# define CV_TRY_FP16 0 -# define CV_CPU_FORCE_FP16 0 -# define CV_CPU_HAS_SUPPORT_FP16 0 -# define CV_CPU_CALL_FP16(fn, args) -# define CV_CPU_CALL_FP16_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_FP16(fn, args, mode, ...) CV_CPU_CALL_FP16(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX2 -# define CV_TRY_AVX2 1 -# define CV_CPU_FORCE_AVX2 1 -# define CV_CPU_HAS_SUPPORT_AVX2 1 -# define CV_CPU_CALL_AVX2(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_AVX2_(fn, args) return (opt_AVX2::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX2 -# define CV_TRY_AVX2 1 -# define CV_CPU_FORCE_AVX2 0 -# define CV_CPU_HAS_SUPPORT_AVX2 (cv::checkHardwareSupport(CV_CPU_AVX2)) -# define CV_CPU_CALL_AVX2(fn, args) if (CV_CPU_HAS_SUPPORT_AVX2) return (opt_AVX2::fn args) -# define CV_CPU_CALL_AVX2_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX2) return (opt_AVX2::fn args) -#else -# define CV_TRY_AVX2 0 -# define CV_CPU_FORCE_AVX2 0 -# define CV_CPU_HAS_SUPPORT_AVX2 0 -# define CV_CPU_CALL_AVX2(fn, args) -# define CV_CPU_CALL_AVX2_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_AVX2(fn, args, mode, ...) CV_CPU_CALL_AVX2(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_FMA3 -# define CV_TRY_FMA3 1 -# define CV_CPU_FORCE_FMA3 1 -# define CV_CPU_HAS_SUPPORT_FMA3 1 -# define CV_CPU_CALL_FMA3(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_FMA3_(fn, args) return (opt_FMA3::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_FMA3 -# define CV_TRY_FMA3 1 -# define CV_CPU_FORCE_FMA3 0 -# define CV_CPU_HAS_SUPPORT_FMA3 (cv::checkHardwareSupport(CV_CPU_FMA3)) -# define CV_CPU_CALL_FMA3(fn, args) if (CV_CPU_HAS_SUPPORT_FMA3) return (opt_FMA3::fn args) -# define CV_CPU_CALL_FMA3_(fn, args) if (CV_CPU_HAS_SUPPORT_FMA3) return (opt_FMA3::fn args) -#else -# define CV_TRY_FMA3 0 -# define CV_CPU_FORCE_FMA3 0 -# define CV_CPU_HAS_SUPPORT_FMA3 0 -# define CV_CPU_CALL_FMA3(fn, args) -# define CV_CPU_CALL_FMA3_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_FMA3(fn, args, mode, ...) CV_CPU_CALL_FMA3(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX_512F -# define CV_TRY_AVX_512F 1 -# define CV_CPU_FORCE_AVX_512F 1 -# define CV_CPU_HAS_SUPPORT_AVX_512F 1 -# define CV_CPU_CALL_AVX_512F(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_AVX_512F_(fn, args) return (opt_AVX_512F::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX_512F -# define CV_TRY_AVX_512F 1 -# define CV_CPU_FORCE_AVX_512F 0 -# define CV_CPU_HAS_SUPPORT_AVX_512F (cv::checkHardwareSupport(CV_CPU_AVX_512F)) -# define CV_CPU_CALL_AVX_512F(fn, args) if (CV_CPU_HAS_SUPPORT_AVX_512F) return (opt_AVX_512F::fn args) -# define CV_CPU_CALL_AVX_512F_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX_512F) return (opt_AVX_512F::fn args) -#else -# define CV_TRY_AVX_512F 0 -# define CV_CPU_FORCE_AVX_512F 0 -# define CV_CPU_HAS_SUPPORT_AVX_512F 0 -# define CV_CPU_CALL_AVX_512F(fn, args) -# define CV_CPU_CALL_AVX_512F_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_AVX_512F(fn, args, mode, ...) CV_CPU_CALL_AVX_512F(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_COMMON -# define CV_TRY_AVX512_COMMON 1 -# define CV_CPU_FORCE_AVX512_COMMON 1 -# define CV_CPU_HAS_SUPPORT_AVX512_COMMON 1 -# define CV_CPU_CALL_AVX512_COMMON(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_AVX512_COMMON_(fn, args) return (opt_AVX512_COMMON::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_COMMON -# define CV_TRY_AVX512_COMMON 1 -# define CV_CPU_FORCE_AVX512_COMMON 0 -# define CV_CPU_HAS_SUPPORT_AVX512_COMMON (cv::checkHardwareSupport(CV_CPU_AVX512_COMMON)) -# define CV_CPU_CALL_AVX512_COMMON(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_COMMON) return (opt_AVX512_COMMON::fn args) -# define CV_CPU_CALL_AVX512_COMMON_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_COMMON) return (opt_AVX512_COMMON::fn args) -#else -# define CV_TRY_AVX512_COMMON 0 -# define CV_CPU_FORCE_AVX512_COMMON 0 -# define CV_CPU_HAS_SUPPORT_AVX512_COMMON 0 -# define CV_CPU_CALL_AVX512_COMMON(fn, args) -# define CV_CPU_CALL_AVX512_COMMON_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_AVX512_COMMON(fn, args, mode, ...) CV_CPU_CALL_AVX512_COMMON(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_KNL -# define CV_TRY_AVX512_KNL 1 -# define CV_CPU_FORCE_AVX512_KNL 1 -# define CV_CPU_HAS_SUPPORT_AVX512_KNL 1 -# define CV_CPU_CALL_AVX512_KNL(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_AVX512_KNL_(fn, args) return (opt_AVX512_KNL::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_KNL -# define CV_TRY_AVX512_KNL 1 -# define CV_CPU_FORCE_AVX512_KNL 0 -# define CV_CPU_HAS_SUPPORT_AVX512_KNL (cv::checkHardwareSupport(CV_CPU_AVX512_KNL)) -# define CV_CPU_CALL_AVX512_KNL(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_KNL) return (opt_AVX512_KNL::fn args) -# define CV_CPU_CALL_AVX512_KNL_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_KNL) return (opt_AVX512_KNL::fn args) -#else -# define CV_TRY_AVX512_KNL 0 -# define CV_CPU_FORCE_AVX512_KNL 0 -# define CV_CPU_HAS_SUPPORT_AVX512_KNL 0 -# define CV_CPU_CALL_AVX512_KNL(fn, args) -# define CV_CPU_CALL_AVX512_KNL_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_AVX512_KNL(fn, args, mode, ...) CV_CPU_CALL_AVX512_KNL(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_KNM -# define CV_TRY_AVX512_KNM 1 -# define CV_CPU_FORCE_AVX512_KNM 1 -# define CV_CPU_HAS_SUPPORT_AVX512_KNM 1 -# define CV_CPU_CALL_AVX512_KNM(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_AVX512_KNM_(fn, args) return (opt_AVX512_KNM::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_KNM -# define CV_TRY_AVX512_KNM 1 -# define CV_CPU_FORCE_AVX512_KNM 0 -# define CV_CPU_HAS_SUPPORT_AVX512_KNM (cv::checkHardwareSupport(CV_CPU_AVX512_KNM)) -# define CV_CPU_CALL_AVX512_KNM(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_KNM) return (opt_AVX512_KNM::fn args) -# define CV_CPU_CALL_AVX512_KNM_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_KNM) return (opt_AVX512_KNM::fn args) -#else -# define CV_TRY_AVX512_KNM 0 -# define CV_CPU_FORCE_AVX512_KNM 0 -# define CV_CPU_HAS_SUPPORT_AVX512_KNM 0 -# define CV_CPU_CALL_AVX512_KNM(fn, args) -# define CV_CPU_CALL_AVX512_KNM_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_AVX512_KNM(fn, args, mode, ...) CV_CPU_CALL_AVX512_KNM(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_SKX -# define CV_TRY_AVX512_SKX 1 -# define CV_CPU_FORCE_AVX512_SKX 1 -# define CV_CPU_HAS_SUPPORT_AVX512_SKX 1 -# define CV_CPU_CALL_AVX512_SKX(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_AVX512_SKX_(fn, args) return (opt_AVX512_SKX::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_SKX -# define CV_TRY_AVX512_SKX 1 -# define CV_CPU_FORCE_AVX512_SKX 0 -# define CV_CPU_HAS_SUPPORT_AVX512_SKX (cv::checkHardwareSupport(CV_CPU_AVX512_SKX)) -# define CV_CPU_CALL_AVX512_SKX(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_SKX) return (opt_AVX512_SKX::fn args) -# define CV_CPU_CALL_AVX512_SKX_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_SKX) return (opt_AVX512_SKX::fn args) -#else -# define CV_TRY_AVX512_SKX 0 -# define CV_CPU_FORCE_AVX512_SKX 0 -# define CV_CPU_HAS_SUPPORT_AVX512_SKX 0 -# define CV_CPU_CALL_AVX512_SKX(fn, args) -# define CV_CPU_CALL_AVX512_SKX_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_AVX512_SKX(fn, args, mode, ...) CV_CPU_CALL_AVX512_SKX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_CNL -# define CV_TRY_AVX512_CNL 1 -# define CV_CPU_FORCE_AVX512_CNL 1 -# define CV_CPU_HAS_SUPPORT_AVX512_CNL 1 -# define CV_CPU_CALL_AVX512_CNL(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_AVX512_CNL_(fn, args) return (opt_AVX512_CNL::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_CNL -# define CV_TRY_AVX512_CNL 1 -# define CV_CPU_FORCE_AVX512_CNL 0 -# define CV_CPU_HAS_SUPPORT_AVX512_CNL (cv::checkHardwareSupport(CV_CPU_AVX512_CNL)) -# define CV_CPU_CALL_AVX512_CNL(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_CNL) return (opt_AVX512_CNL::fn args) -# define CV_CPU_CALL_AVX512_CNL_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_CNL) return (opt_AVX512_CNL::fn args) -#else -# define CV_TRY_AVX512_CNL 0 -# define CV_CPU_FORCE_AVX512_CNL 0 -# define CV_CPU_HAS_SUPPORT_AVX512_CNL 0 -# define CV_CPU_CALL_AVX512_CNL(fn, args) -# define CV_CPU_CALL_AVX512_CNL_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_AVX512_CNL(fn, args, mode, ...) CV_CPU_CALL_AVX512_CNL(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_CLX -# define CV_TRY_AVX512_CLX 1 -# define CV_CPU_FORCE_AVX512_CLX 1 -# define CV_CPU_HAS_SUPPORT_AVX512_CLX 1 -# define CV_CPU_CALL_AVX512_CLX(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_AVX512_CLX_(fn, args) return (opt_AVX512_CLX::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_CLX -# define CV_TRY_AVX512_CLX 1 -# define CV_CPU_FORCE_AVX512_CLX 0 -# define CV_CPU_HAS_SUPPORT_AVX512_CLX (cv::checkHardwareSupport(CV_CPU_AVX512_CLX)) -# define CV_CPU_CALL_AVX512_CLX(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_CLX) return (opt_AVX512_CLX::fn args) -# define CV_CPU_CALL_AVX512_CLX_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_CLX) return (opt_AVX512_CLX::fn args) -#else -# define CV_TRY_AVX512_CLX 0 -# define CV_CPU_FORCE_AVX512_CLX 0 -# define CV_CPU_HAS_SUPPORT_AVX512_CLX 0 -# define CV_CPU_CALL_AVX512_CLX(fn, args) -# define CV_CPU_CALL_AVX512_CLX_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_AVX512_CLX(fn, args, mode, ...) CV_CPU_CALL_AVX512_CLX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_ICL -# define CV_TRY_AVX512_ICL 1 -# define CV_CPU_FORCE_AVX512_ICL 1 -# define CV_CPU_HAS_SUPPORT_AVX512_ICL 1 -# define CV_CPU_CALL_AVX512_ICL(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_AVX512_ICL_(fn, args) return (opt_AVX512_ICL::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_ICL -# define CV_TRY_AVX512_ICL 1 -# define CV_CPU_FORCE_AVX512_ICL 0 -# define CV_CPU_HAS_SUPPORT_AVX512_ICL (cv::checkHardwareSupport(CV_CPU_AVX512_ICL)) -# define CV_CPU_CALL_AVX512_ICL(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_ICL) return (opt_AVX512_ICL::fn args) -# define CV_CPU_CALL_AVX512_ICL_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_ICL) return (opt_AVX512_ICL::fn args) -#else -# define CV_TRY_AVX512_ICL 0 -# define CV_CPU_FORCE_AVX512_ICL 0 -# define CV_CPU_HAS_SUPPORT_AVX512_ICL 0 -# define CV_CPU_CALL_AVX512_ICL(fn, args) -# define CV_CPU_CALL_AVX512_ICL_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_AVX512_ICL(fn, args, mode, ...) CV_CPU_CALL_AVX512_ICL(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_NEON -# define CV_TRY_NEON 1 -# define CV_CPU_FORCE_NEON 1 -# define CV_CPU_HAS_SUPPORT_NEON 1 -# define CV_CPU_CALL_NEON(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_NEON_(fn, args) return (opt_NEON::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_NEON -# define CV_TRY_NEON 1 -# define CV_CPU_FORCE_NEON 0 -# define CV_CPU_HAS_SUPPORT_NEON (cv::checkHardwareSupport(CV_CPU_NEON)) -# define CV_CPU_CALL_NEON(fn, args) if (CV_CPU_HAS_SUPPORT_NEON) return (opt_NEON::fn args) -# define CV_CPU_CALL_NEON_(fn, args) if (CV_CPU_HAS_SUPPORT_NEON) return (opt_NEON::fn args) -#else -# define CV_TRY_NEON 0 -# define CV_CPU_FORCE_NEON 0 -# define CV_CPU_HAS_SUPPORT_NEON 0 -# define CV_CPU_CALL_NEON(fn, args) -# define CV_CPU_CALL_NEON_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_NEON(fn, args, mode, ...) CV_CPU_CALL_NEON(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_NEON_DOTPROD -# define CV_TRY_NEON_DOTPROD 1 -# define CV_CPU_FORCE_NEON_DOTPROD 1 -# define CV_CPU_HAS_SUPPORT_NEON_DOTPROD 1 -# define CV_CPU_CALL_NEON_DOTPROD(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_NEON_DOTPROD_(fn, args) return (opt_NEON_DOTPROD::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_NEON_DOTPROD -# define CV_TRY_NEON_DOTPROD 1 -# define CV_CPU_FORCE_NEON_DOTPROD 0 -# define CV_CPU_HAS_SUPPORT_NEON_DOTPROD (cv::checkHardwareSupport(CV_CPU_NEON_DOTPROD)) -# define CV_CPU_CALL_NEON_DOTPROD(fn, args) if (CV_CPU_HAS_SUPPORT_NEON_DOTPROD) return (opt_NEON_DOTPROD::fn args) -# define CV_CPU_CALL_NEON_DOTPROD_(fn, args) if (CV_CPU_HAS_SUPPORT_NEON_DOTPROD) return (opt_NEON_DOTPROD::fn args) -#else -# define CV_TRY_NEON_DOTPROD 0 -# define CV_CPU_FORCE_NEON_DOTPROD 0 -# define CV_CPU_HAS_SUPPORT_NEON_DOTPROD 0 -# define CV_CPU_CALL_NEON_DOTPROD(fn, args) -# define CV_CPU_CALL_NEON_DOTPROD_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_NEON_DOTPROD(fn, args, mode, ...) CV_CPU_CALL_NEON_DOTPROD(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_NEON_FP16 -# define CV_TRY_NEON_FP16 1 -# define CV_CPU_FORCE_NEON_FP16 1 -# define CV_CPU_HAS_SUPPORT_NEON_FP16 1 -# define CV_CPU_CALL_NEON_FP16(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_NEON_FP16_(fn, args) return (opt_NEON_FP16::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_NEON_FP16 -# define CV_TRY_NEON_FP16 1 -# define CV_CPU_FORCE_NEON_FP16 0 -# define CV_CPU_HAS_SUPPORT_NEON_FP16 (cv::checkHardwareSupport(CV_CPU_NEON_FP16)) -# define CV_CPU_CALL_NEON_FP16(fn, args) if (CV_CPU_HAS_SUPPORT_NEON_FP16) return (opt_NEON_FP16::fn args) -# define CV_CPU_CALL_NEON_FP16_(fn, args) if (CV_CPU_HAS_SUPPORT_NEON_FP16) return (opt_NEON_FP16::fn args) -#else -# define CV_TRY_NEON_FP16 0 -# define CV_CPU_FORCE_NEON_FP16 0 -# define CV_CPU_HAS_SUPPORT_NEON_FP16 0 -# define CV_CPU_CALL_NEON_FP16(fn, args) -# define CV_CPU_CALL_NEON_FP16_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_NEON_FP16(fn, args, mode, ...) CV_CPU_CALL_NEON_FP16(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_NEON_BF16 -# define CV_TRY_NEON_BF16 1 -# define CV_CPU_FORCE_NEON_BF16 1 -# define CV_CPU_HAS_SUPPORT_NEON_BF16 1 -# define CV_CPU_CALL_NEON_BF16(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_NEON_BF16_(fn, args) return (opt_NEON_BF16::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_NEON_BF16 -# define CV_TRY_NEON_BF16 1 -# define CV_CPU_FORCE_NEON_BF16 0 -# define CV_CPU_HAS_SUPPORT_NEON_BF16 (cv::checkHardwareSupport(CV_CPU_NEON_BF16)) -# define CV_CPU_CALL_NEON_BF16(fn, args) if (CV_CPU_HAS_SUPPORT_NEON_BF16) return (opt_NEON_BF16::fn args) -# define CV_CPU_CALL_NEON_BF16_(fn, args) if (CV_CPU_HAS_SUPPORT_NEON_BF16) return (opt_NEON_BF16::fn args) -#else -# define CV_TRY_NEON_BF16 0 -# define CV_CPU_FORCE_NEON_BF16 0 -# define CV_CPU_HAS_SUPPORT_NEON_BF16 0 -# define CV_CPU_CALL_NEON_BF16(fn, args) -# define CV_CPU_CALL_NEON_BF16_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_NEON_BF16(fn, args, mode, ...) CV_CPU_CALL_NEON_BF16(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_MSA -# define CV_TRY_MSA 1 -# define CV_CPU_FORCE_MSA 1 -# define CV_CPU_HAS_SUPPORT_MSA 1 -# define CV_CPU_CALL_MSA(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_MSA_(fn, args) return (opt_MSA::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_MSA -# define CV_TRY_MSA 1 -# define CV_CPU_FORCE_MSA 0 -# define CV_CPU_HAS_SUPPORT_MSA (cv::checkHardwareSupport(CV_CPU_MSA)) -# define CV_CPU_CALL_MSA(fn, args) if (CV_CPU_HAS_SUPPORT_MSA) return (opt_MSA::fn args) -# define CV_CPU_CALL_MSA_(fn, args) if (CV_CPU_HAS_SUPPORT_MSA) return (opt_MSA::fn args) -#else -# define CV_TRY_MSA 0 -# define CV_CPU_FORCE_MSA 0 -# define CV_CPU_HAS_SUPPORT_MSA 0 -# define CV_CPU_CALL_MSA(fn, args) -# define CV_CPU_CALL_MSA_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_MSA(fn, args, mode, ...) CV_CPU_CALL_MSA(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_VSX -# define CV_TRY_VSX 1 -# define CV_CPU_FORCE_VSX 1 -# define CV_CPU_HAS_SUPPORT_VSX 1 -# define CV_CPU_CALL_VSX(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_VSX_(fn, args) return (opt_VSX::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_VSX -# define CV_TRY_VSX 1 -# define CV_CPU_FORCE_VSX 0 -# define CV_CPU_HAS_SUPPORT_VSX (cv::checkHardwareSupport(CV_CPU_VSX)) -# define CV_CPU_CALL_VSX(fn, args) if (CV_CPU_HAS_SUPPORT_VSX) return (opt_VSX::fn args) -# define CV_CPU_CALL_VSX_(fn, args) if (CV_CPU_HAS_SUPPORT_VSX) return (opt_VSX::fn args) -#else -# define CV_TRY_VSX 0 -# define CV_CPU_FORCE_VSX 0 -# define CV_CPU_HAS_SUPPORT_VSX 0 -# define CV_CPU_CALL_VSX(fn, args) -# define CV_CPU_CALL_VSX_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_VSX(fn, args, mode, ...) CV_CPU_CALL_VSX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_VSX3 -# define CV_TRY_VSX3 1 -# define CV_CPU_FORCE_VSX3 1 -# define CV_CPU_HAS_SUPPORT_VSX3 1 -# define CV_CPU_CALL_VSX3(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_VSX3_(fn, args) return (opt_VSX3::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_VSX3 -# define CV_TRY_VSX3 1 -# define CV_CPU_FORCE_VSX3 0 -# define CV_CPU_HAS_SUPPORT_VSX3 (cv::checkHardwareSupport(CV_CPU_VSX3)) -# define CV_CPU_CALL_VSX3(fn, args) if (CV_CPU_HAS_SUPPORT_VSX3) return (opt_VSX3::fn args) -# define CV_CPU_CALL_VSX3_(fn, args) if (CV_CPU_HAS_SUPPORT_VSX3) return (opt_VSX3::fn args) -#else -# define CV_TRY_VSX3 0 -# define CV_CPU_FORCE_VSX3 0 -# define CV_CPU_HAS_SUPPORT_VSX3 0 -# define CV_CPU_CALL_VSX3(fn, args) -# define CV_CPU_CALL_VSX3_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_VSX3(fn, args, mode, ...) CV_CPU_CALL_VSX3(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_RVV -# define CV_TRY_RVV 1 -# define CV_CPU_FORCE_RVV 1 -# define CV_CPU_HAS_SUPPORT_RVV 1 -# define CV_CPU_CALL_RVV(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_RVV_(fn, args) return (opt_RVV::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_RVV -# define CV_TRY_RVV 1 -# define CV_CPU_FORCE_RVV 0 -# define CV_CPU_HAS_SUPPORT_RVV (cv::checkHardwareSupport(CV_CPU_RVV)) -# define CV_CPU_CALL_RVV(fn, args) if (CV_CPU_HAS_SUPPORT_RVV) return (opt_RVV::fn args) -# define CV_CPU_CALL_RVV_(fn, args) if (CV_CPU_HAS_SUPPORT_RVV) return (opt_RVV::fn args) -#else -# define CV_TRY_RVV 0 -# define CV_CPU_FORCE_RVV 0 -# define CV_CPU_HAS_SUPPORT_RVV 0 -# define CV_CPU_CALL_RVV(fn, args) -# define CV_CPU_CALL_RVV_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_RVV(fn, args, mode, ...) CV_CPU_CALL_RVV(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_LSX -# define CV_TRY_LSX 1 -# define CV_CPU_FORCE_LSX 1 -# define CV_CPU_HAS_SUPPORT_LSX 1 -# define CV_CPU_CALL_LSX(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_LSX_(fn, args) return (opt_LSX::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_LSX -# define CV_TRY_LSX 1 -# define CV_CPU_FORCE_LSX 0 -# define CV_CPU_HAS_SUPPORT_LSX (cv::checkHardwareSupport(CV_CPU_LSX)) -# define CV_CPU_CALL_LSX(fn, args) if (CV_CPU_HAS_SUPPORT_LSX) return (opt_LSX::fn args) -# define CV_CPU_CALL_LSX_(fn, args) if (CV_CPU_HAS_SUPPORT_LSX) return (opt_LSX::fn args) -#else -# define CV_TRY_LSX 0 -# define CV_CPU_FORCE_LSX 0 -# define CV_CPU_HAS_SUPPORT_LSX 0 -# define CV_CPU_CALL_LSX(fn, args) -# define CV_CPU_CALL_LSX_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_LSX(fn, args, mode, ...) CV_CPU_CALL_LSX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_LASX -# define CV_TRY_LASX 1 -# define CV_CPU_FORCE_LASX 1 -# define CV_CPU_HAS_SUPPORT_LASX 1 -# define CV_CPU_CALL_LASX(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_LASX_(fn, args) return (opt_LASX::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_LASX -# define CV_TRY_LASX 1 -# define CV_CPU_FORCE_LASX 0 -# define CV_CPU_HAS_SUPPORT_LASX (cv::checkHardwareSupport(CV_CPU_LASX)) -# define CV_CPU_CALL_LASX(fn, args) if (CV_CPU_HAS_SUPPORT_LASX) return (opt_LASX::fn args) -# define CV_CPU_CALL_LASX_(fn, args) if (CV_CPU_HAS_SUPPORT_LASX) return (opt_LASX::fn args) -#else -# define CV_TRY_LASX 0 -# define CV_CPU_FORCE_LASX 0 -# define CV_CPU_HAS_SUPPORT_LASX 0 -# define CV_CPU_CALL_LASX(fn, args) -# define CV_CPU_CALL_LASX_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_LASX(fn, args, mode, ...) CV_CPU_CALL_LASX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#define CV_CPU_CALL_BASELINE(fn, args) return (cpu_baseline::fn args) -#define __CV_CPU_DISPATCH_CHAIN_BASELINE(fn, args, mode, ...) CV_CPU_CALL_BASELINE(fn, args) /* last in sequence */ +// AUTOGENERATED, DO NOT EDIT + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE +# define CV_TRY_SSE 1 +# define CV_CPU_FORCE_SSE 1 +# define CV_CPU_HAS_SUPPORT_SSE 1 +# define CV_CPU_CALL_SSE(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_SSE_(fn, args) return (opt_SSE::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE +# define CV_TRY_SSE 1 +# define CV_CPU_FORCE_SSE 0 +# define CV_CPU_HAS_SUPPORT_SSE (cv::checkHardwareSupport(CV_CPU_SSE)) +# define CV_CPU_CALL_SSE(fn, args) if (CV_CPU_HAS_SUPPORT_SSE) return (opt_SSE::fn args) +# define CV_CPU_CALL_SSE_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE) return (opt_SSE::fn args) +#else +# define CV_TRY_SSE 0 +# define CV_CPU_FORCE_SSE 0 +# define CV_CPU_HAS_SUPPORT_SSE 0 +# define CV_CPU_CALL_SSE(fn, args) +# define CV_CPU_CALL_SSE_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_SSE(fn, args, mode, ...) CV_CPU_CALL_SSE(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE2 +# define CV_TRY_SSE2 1 +# define CV_CPU_FORCE_SSE2 1 +# define CV_CPU_HAS_SUPPORT_SSE2 1 +# define CV_CPU_CALL_SSE2(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_SSE2_(fn, args) return (opt_SSE2::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE2 +# define CV_TRY_SSE2 1 +# define CV_CPU_FORCE_SSE2 0 +# define CV_CPU_HAS_SUPPORT_SSE2 (cv::checkHardwareSupport(CV_CPU_SSE2)) +# define CV_CPU_CALL_SSE2(fn, args) if (CV_CPU_HAS_SUPPORT_SSE2) return (opt_SSE2::fn args) +# define CV_CPU_CALL_SSE2_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE2) return (opt_SSE2::fn args) +#else +# define CV_TRY_SSE2 0 +# define CV_CPU_FORCE_SSE2 0 +# define CV_CPU_HAS_SUPPORT_SSE2 0 +# define CV_CPU_CALL_SSE2(fn, args) +# define CV_CPU_CALL_SSE2_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_SSE2(fn, args, mode, ...) CV_CPU_CALL_SSE2(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE3 +# define CV_TRY_SSE3 1 +# define CV_CPU_FORCE_SSE3 1 +# define CV_CPU_HAS_SUPPORT_SSE3 1 +# define CV_CPU_CALL_SSE3(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_SSE3_(fn, args) return (opt_SSE3::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE3 +# define CV_TRY_SSE3 1 +# define CV_CPU_FORCE_SSE3 0 +# define CV_CPU_HAS_SUPPORT_SSE3 (cv::checkHardwareSupport(CV_CPU_SSE3)) +# define CV_CPU_CALL_SSE3(fn, args) if (CV_CPU_HAS_SUPPORT_SSE3) return (opt_SSE3::fn args) +# define CV_CPU_CALL_SSE3_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE3) return (opt_SSE3::fn args) +#else +# define CV_TRY_SSE3 0 +# define CV_CPU_FORCE_SSE3 0 +# define CV_CPU_HAS_SUPPORT_SSE3 0 +# define CV_CPU_CALL_SSE3(fn, args) +# define CV_CPU_CALL_SSE3_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_SSE3(fn, args, mode, ...) CV_CPU_CALL_SSE3(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSSE3 +# define CV_TRY_SSSE3 1 +# define CV_CPU_FORCE_SSSE3 1 +# define CV_CPU_HAS_SUPPORT_SSSE3 1 +# define CV_CPU_CALL_SSSE3(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_SSSE3_(fn, args) return (opt_SSSE3::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSSE3 +# define CV_TRY_SSSE3 1 +# define CV_CPU_FORCE_SSSE3 0 +# define CV_CPU_HAS_SUPPORT_SSSE3 (cv::checkHardwareSupport(CV_CPU_SSSE3)) +# define CV_CPU_CALL_SSSE3(fn, args) if (CV_CPU_HAS_SUPPORT_SSSE3) return (opt_SSSE3::fn args) +# define CV_CPU_CALL_SSSE3_(fn, args) if (CV_CPU_HAS_SUPPORT_SSSE3) return (opt_SSSE3::fn args) +#else +# define CV_TRY_SSSE3 0 +# define CV_CPU_FORCE_SSSE3 0 +# define CV_CPU_HAS_SUPPORT_SSSE3 0 +# define CV_CPU_CALL_SSSE3(fn, args) +# define CV_CPU_CALL_SSSE3_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_SSSE3(fn, args, mode, ...) CV_CPU_CALL_SSSE3(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE4_1 +# define CV_TRY_SSE4_1 1 +# define CV_CPU_FORCE_SSE4_1 1 +# define CV_CPU_HAS_SUPPORT_SSE4_1 1 +# define CV_CPU_CALL_SSE4_1(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_SSE4_1_(fn, args) return (opt_SSE4_1::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE4_1 +# define CV_TRY_SSE4_1 1 +# define CV_CPU_FORCE_SSE4_1 0 +# define CV_CPU_HAS_SUPPORT_SSE4_1 (cv::checkHardwareSupport(CV_CPU_SSE4_1)) +# define CV_CPU_CALL_SSE4_1(fn, args) if (CV_CPU_HAS_SUPPORT_SSE4_1) return (opt_SSE4_1::fn args) +# define CV_CPU_CALL_SSE4_1_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE4_1) return (opt_SSE4_1::fn args) +#else +# define CV_TRY_SSE4_1 0 +# define CV_CPU_FORCE_SSE4_1 0 +# define CV_CPU_HAS_SUPPORT_SSE4_1 0 +# define CV_CPU_CALL_SSE4_1(fn, args) +# define CV_CPU_CALL_SSE4_1_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_SSE4_1(fn, args, mode, ...) CV_CPU_CALL_SSE4_1(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE4_2 +# define CV_TRY_SSE4_2 1 +# define CV_CPU_FORCE_SSE4_2 1 +# define CV_CPU_HAS_SUPPORT_SSE4_2 1 +# define CV_CPU_CALL_SSE4_2(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_SSE4_2_(fn, args) return (opt_SSE4_2::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE4_2 +# define CV_TRY_SSE4_2 1 +# define CV_CPU_FORCE_SSE4_2 0 +# define CV_CPU_HAS_SUPPORT_SSE4_2 (cv::checkHardwareSupport(CV_CPU_SSE4_2)) +# define CV_CPU_CALL_SSE4_2(fn, args) if (CV_CPU_HAS_SUPPORT_SSE4_2) return (opt_SSE4_2::fn args) +# define CV_CPU_CALL_SSE4_2_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE4_2) return (opt_SSE4_2::fn args) +#else +# define CV_TRY_SSE4_2 0 +# define CV_CPU_FORCE_SSE4_2 0 +# define CV_CPU_HAS_SUPPORT_SSE4_2 0 +# define CV_CPU_CALL_SSE4_2(fn, args) +# define CV_CPU_CALL_SSE4_2_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_SSE4_2(fn, args, mode, ...) CV_CPU_CALL_SSE4_2(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_POPCNT +# define CV_TRY_POPCNT 1 +# define CV_CPU_FORCE_POPCNT 1 +# define CV_CPU_HAS_SUPPORT_POPCNT 1 +# define CV_CPU_CALL_POPCNT(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_POPCNT_(fn, args) return (opt_POPCNT::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_POPCNT +# define CV_TRY_POPCNT 1 +# define CV_CPU_FORCE_POPCNT 0 +# define CV_CPU_HAS_SUPPORT_POPCNT (cv::checkHardwareSupport(CV_CPU_POPCNT)) +# define CV_CPU_CALL_POPCNT(fn, args) if (CV_CPU_HAS_SUPPORT_POPCNT) return (opt_POPCNT::fn args) +# define CV_CPU_CALL_POPCNT_(fn, args) if (CV_CPU_HAS_SUPPORT_POPCNT) return (opt_POPCNT::fn args) +#else +# define CV_TRY_POPCNT 0 +# define CV_CPU_FORCE_POPCNT 0 +# define CV_CPU_HAS_SUPPORT_POPCNT 0 +# define CV_CPU_CALL_POPCNT(fn, args) +# define CV_CPU_CALL_POPCNT_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_POPCNT(fn, args, mode, ...) CV_CPU_CALL_POPCNT(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX +# define CV_TRY_AVX 1 +# define CV_CPU_FORCE_AVX 1 +# define CV_CPU_HAS_SUPPORT_AVX 1 +# define CV_CPU_CALL_AVX(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_AVX_(fn, args) return (opt_AVX::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX +# define CV_TRY_AVX 1 +# define CV_CPU_FORCE_AVX 0 +# define CV_CPU_HAS_SUPPORT_AVX (cv::checkHardwareSupport(CV_CPU_AVX)) +# define CV_CPU_CALL_AVX(fn, args) if (CV_CPU_HAS_SUPPORT_AVX) return (opt_AVX::fn args) +# define CV_CPU_CALL_AVX_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX) return (opt_AVX::fn args) +#else +# define CV_TRY_AVX 0 +# define CV_CPU_FORCE_AVX 0 +# define CV_CPU_HAS_SUPPORT_AVX 0 +# define CV_CPU_CALL_AVX(fn, args) +# define CV_CPU_CALL_AVX_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_AVX(fn, args, mode, ...) CV_CPU_CALL_AVX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_FP16 +# define CV_TRY_FP16 1 +# define CV_CPU_FORCE_FP16 1 +# define CV_CPU_HAS_SUPPORT_FP16 1 +# define CV_CPU_CALL_FP16(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_FP16_(fn, args) return (opt_FP16::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_FP16 +# define CV_TRY_FP16 1 +# define CV_CPU_FORCE_FP16 0 +# define CV_CPU_HAS_SUPPORT_FP16 (cv::checkHardwareSupport(CV_CPU_FP16)) +# define CV_CPU_CALL_FP16(fn, args) if (CV_CPU_HAS_SUPPORT_FP16) return (opt_FP16::fn args) +# define CV_CPU_CALL_FP16_(fn, args) if (CV_CPU_HAS_SUPPORT_FP16) return (opt_FP16::fn args) +#else +# define CV_TRY_FP16 0 +# define CV_CPU_FORCE_FP16 0 +# define CV_CPU_HAS_SUPPORT_FP16 0 +# define CV_CPU_CALL_FP16(fn, args) +# define CV_CPU_CALL_FP16_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_FP16(fn, args, mode, ...) CV_CPU_CALL_FP16(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX2 +# define CV_TRY_AVX2 1 +# define CV_CPU_FORCE_AVX2 1 +# define CV_CPU_HAS_SUPPORT_AVX2 1 +# define CV_CPU_CALL_AVX2(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_AVX2_(fn, args) return (opt_AVX2::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX2 +# define CV_TRY_AVX2 1 +# define CV_CPU_FORCE_AVX2 0 +# define CV_CPU_HAS_SUPPORT_AVX2 (cv::checkHardwareSupport(CV_CPU_AVX2)) +# define CV_CPU_CALL_AVX2(fn, args) if (CV_CPU_HAS_SUPPORT_AVX2) return (opt_AVX2::fn args) +# define CV_CPU_CALL_AVX2_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX2) return (opt_AVX2::fn args) +#else +# define CV_TRY_AVX2 0 +# define CV_CPU_FORCE_AVX2 0 +# define CV_CPU_HAS_SUPPORT_AVX2 0 +# define CV_CPU_CALL_AVX2(fn, args) +# define CV_CPU_CALL_AVX2_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_AVX2(fn, args, mode, ...) CV_CPU_CALL_AVX2(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_FMA3 +# define CV_TRY_FMA3 1 +# define CV_CPU_FORCE_FMA3 1 +# define CV_CPU_HAS_SUPPORT_FMA3 1 +# define CV_CPU_CALL_FMA3(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_FMA3_(fn, args) return (opt_FMA3::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_FMA3 +# define CV_TRY_FMA3 1 +# define CV_CPU_FORCE_FMA3 0 +# define CV_CPU_HAS_SUPPORT_FMA3 (cv::checkHardwareSupport(CV_CPU_FMA3)) +# define CV_CPU_CALL_FMA3(fn, args) if (CV_CPU_HAS_SUPPORT_FMA3) return (opt_FMA3::fn args) +# define CV_CPU_CALL_FMA3_(fn, args) if (CV_CPU_HAS_SUPPORT_FMA3) return (opt_FMA3::fn args) +#else +# define CV_TRY_FMA3 0 +# define CV_CPU_FORCE_FMA3 0 +# define CV_CPU_HAS_SUPPORT_FMA3 0 +# define CV_CPU_CALL_FMA3(fn, args) +# define CV_CPU_CALL_FMA3_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_FMA3(fn, args, mode, ...) CV_CPU_CALL_FMA3(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX_512F +# define CV_TRY_AVX_512F 1 +# define CV_CPU_FORCE_AVX_512F 1 +# define CV_CPU_HAS_SUPPORT_AVX_512F 1 +# define CV_CPU_CALL_AVX_512F(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_AVX_512F_(fn, args) return (opt_AVX_512F::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX_512F +# define CV_TRY_AVX_512F 1 +# define CV_CPU_FORCE_AVX_512F 0 +# define CV_CPU_HAS_SUPPORT_AVX_512F (cv::checkHardwareSupport(CV_CPU_AVX_512F)) +# define CV_CPU_CALL_AVX_512F(fn, args) if (CV_CPU_HAS_SUPPORT_AVX_512F) return (opt_AVX_512F::fn args) +# define CV_CPU_CALL_AVX_512F_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX_512F) return (opt_AVX_512F::fn args) +#else +# define CV_TRY_AVX_512F 0 +# define CV_CPU_FORCE_AVX_512F 0 +# define CV_CPU_HAS_SUPPORT_AVX_512F 0 +# define CV_CPU_CALL_AVX_512F(fn, args) +# define CV_CPU_CALL_AVX_512F_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_AVX_512F(fn, args, mode, ...) CV_CPU_CALL_AVX_512F(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_COMMON +# define CV_TRY_AVX512_COMMON 1 +# define CV_CPU_FORCE_AVX512_COMMON 1 +# define CV_CPU_HAS_SUPPORT_AVX512_COMMON 1 +# define CV_CPU_CALL_AVX512_COMMON(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_AVX512_COMMON_(fn, args) return (opt_AVX512_COMMON::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_COMMON +# define CV_TRY_AVX512_COMMON 1 +# define CV_CPU_FORCE_AVX512_COMMON 0 +# define CV_CPU_HAS_SUPPORT_AVX512_COMMON (cv::checkHardwareSupport(CV_CPU_AVX512_COMMON)) +# define CV_CPU_CALL_AVX512_COMMON(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_COMMON) return (opt_AVX512_COMMON::fn args) +# define CV_CPU_CALL_AVX512_COMMON_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_COMMON) return (opt_AVX512_COMMON::fn args) +#else +# define CV_TRY_AVX512_COMMON 0 +# define CV_CPU_FORCE_AVX512_COMMON 0 +# define CV_CPU_HAS_SUPPORT_AVX512_COMMON 0 +# define CV_CPU_CALL_AVX512_COMMON(fn, args) +# define CV_CPU_CALL_AVX512_COMMON_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_AVX512_COMMON(fn, args, mode, ...) CV_CPU_CALL_AVX512_COMMON(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_KNL +# define CV_TRY_AVX512_KNL 1 +# define CV_CPU_FORCE_AVX512_KNL 1 +# define CV_CPU_HAS_SUPPORT_AVX512_KNL 1 +# define CV_CPU_CALL_AVX512_KNL(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_AVX512_KNL_(fn, args) return (opt_AVX512_KNL::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_KNL +# define CV_TRY_AVX512_KNL 1 +# define CV_CPU_FORCE_AVX512_KNL 0 +# define CV_CPU_HAS_SUPPORT_AVX512_KNL (cv::checkHardwareSupport(CV_CPU_AVX512_KNL)) +# define CV_CPU_CALL_AVX512_KNL(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_KNL) return (opt_AVX512_KNL::fn args) +# define CV_CPU_CALL_AVX512_KNL_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_KNL) return (opt_AVX512_KNL::fn args) +#else +# define CV_TRY_AVX512_KNL 0 +# define CV_CPU_FORCE_AVX512_KNL 0 +# define CV_CPU_HAS_SUPPORT_AVX512_KNL 0 +# define CV_CPU_CALL_AVX512_KNL(fn, args) +# define CV_CPU_CALL_AVX512_KNL_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_AVX512_KNL(fn, args, mode, ...) CV_CPU_CALL_AVX512_KNL(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_KNM +# define CV_TRY_AVX512_KNM 1 +# define CV_CPU_FORCE_AVX512_KNM 1 +# define CV_CPU_HAS_SUPPORT_AVX512_KNM 1 +# define CV_CPU_CALL_AVX512_KNM(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_AVX512_KNM_(fn, args) return (opt_AVX512_KNM::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_KNM +# define CV_TRY_AVX512_KNM 1 +# define CV_CPU_FORCE_AVX512_KNM 0 +# define CV_CPU_HAS_SUPPORT_AVX512_KNM (cv::checkHardwareSupport(CV_CPU_AVX512_KNM)) +# define CV_CPU_CALL_AVX512_KNM(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_KNM) return (opt_AVX512_KNM::fn args) +# define CV_CPU_CALL_AVX512_KNM_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_KNM) return (opt_AVX512_KNM::fn args) +#else +# define CV_TRY_AVX512_KNM 0 +# define CV_CPU_FORCE_AVX512_KNM 0 +# define CV_CPU_HAS_SUPPORT_AVX512_KNM 0 +# define CV_CPU_CALL_AVX512_KNM(fn, args) +# define CV_CPU_CALL_AVX512_KNM_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_AVX512_KNM(fn, args, mode, ...) CV_CPU_CALL_AVX512_KNM(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_SKX +# define CV_TRY_AVX512_SKX 1 +# define CV_CPU_FORCE_AVX512_SKX 1 +# define CV_CPU_HAS_SUPPORT_AVX512_SKX 1 +# define CV_CPU_CALL_AVX512_SKX(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_AVX512_SKX_(fn, args) return (opt_AVX512_SKX::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_SKX +# define CV_TRY_AVX512_SKX 1 +# define CV_CPU_FORCE_AVX512_SKX 0 +# define CV_CPU_HAS_SUPPORT_AVX512_SKX (cv::checkHardwareSupport(CV_CPU_AVX512_SKX)) +# define CV_CPU_CALL_AVX512_SKX(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_SKX) return (opt_AVX512_SKX::fn args) +# define CV_CPU_CALL_AVX512_SKX_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_SKX) return (opt_AVX512_SKX::fn args) +#else +# define CV_TRY_AVX512_SKX 0 +# define CV_CPU_FORCE_AVX512_SKX 0 +# define CV_CPU_HAS_SUPPORT_AVX512_SKX 0 +# define CV_CPU_CALL_AVX512_SKX(fn, args) +# define CV_CPU_CALL_AVX512_SKX_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_AVX512_SKX(fn, args, mode, ...) CV_CPU_CALL_AVX512_SKX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_CNL +# define CV_TRY_AVX512_CNL 1 +# define CV_CPU_FORCE_AVX512_CNL 1 +# define CV_CPU_HAS_SUPPORT_AVX512_CNL 1 +# define CV_CPU_CALL_AVX512_CNL(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_AVX512_CNL_(fn, args) return (opt_AVX512_CNL::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_CNL +# define CV_TRY_AVX512_CNL 1 +# define CV_CPU_FORCE_AVX512_CNL 0 +# define CV_CPU_HAS_SUPPORT_AVX512_CNL (cv::checkHardwareSupport(CV_CPU_AVX512_CNL)) +# define CV_CPU_CALL_AVX512_CNL(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_CNL) return (opt_AVX512_CNL::fn args) +# define CV_CPU_CALL_AVX512_CNL_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_CNL) return (opt_AVX512_CNL::fn args) +#else +# define CV_TRY_AVX512_CNL 0 +# define CV_CPU_FORCE_AVX512_CNL 0 +# define CV_CPU_HAS_SUPPORT_AVX512_CNL 0 +# define CV_CPU_CALL_AVX512_CNL(fn, args) +# define CV_CPU_CALL_AVX512_CNL_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_AVX512_CNL(fn, args, mode, ...) CV_CPU_CALL_AVX512_CNL(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_CLX +# define CV_TRY_AVX512_CLX 1 +# define CV_CPU_FORCE_AVX512_CLX 1 +# define CV_CPU_HAS_SUPPORT_AVX512_CLX 1 +# define CV_CPU_CALL_AVX512_CLX(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_AVX512_CLX_(fn, args) return (opt_AVX512_CLX::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_CLX +# define CV_TRY_AVX512_CLX 1 +# define CV_CPU_FORCE_AVX512_CLX 0 +# define CV_CPU_HAS_SUPPORT_AVX512_CLX (cv::checkHardwareSupport(CV_CPU_AVX512_CLX)) +# define CV_CPU_CALL_AVX512_CLX(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_CLX) return (opt_AVX512_CLX::fn args) +# define CV_CPU_CALL_AVX512_CLX_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_CLX) return (opt_AVX512_CLX::fn args) +#else +# define CV_TRY_AVX512_CLX 0 +# define CV_CPU_FORCE_AVX512_CLX 0 +# define CV_CPU_HAS_SUPPORT_AVX512_CLX 0 +# define CV_CPU_CALL_AVX512_CLX(fn, args) +# define CV_CPU_CALL_AVX512_CLX_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_AVX512_CLX(fn, args, mode, ...) CV_CPU_CALL_AVX512_CLX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_ICL +# define CV_TRY_AVX512_ICL 1 +# define CV_CPU_FORCE_AVX512_ICL 1 +# define CV_CPU_HAS_SUPPORT_AVX512_ICL 1 +# define CV_CPU_CALL_AVX512_ICL(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_AVX512_ICL_(fn, args) return (opt_AVX512_ICL::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_ICL +# define CV_TRY_AVX512_ICL 1 +# define CV_CPU_FORCE_AVX512_ICL 0 +# define CV_CPU_HAS_SUPPORT_AVX512_ICL (cv::checkHardwareSupport(CV_CPU_AVX512_ICL)) +# define CV_CPU_CALL_AVX512_ICL(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_ICL) return (opt_AVX512_ICL::fn args) +# define CV_CPU_CALL_AVX512_ICL_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_ICL) return (opt_AVX512_ICL::fn args) +#else +# define CV_TRY_AVX512_ICL 0 +# define CV_CPU_FORCE_AVX512_ICL 0 +# define CV_CPU_HAS_SUPPORT_AVX512_ICL 0 +# define CV_CPU_CALL_AVX512_ICL(fn, args) +# define CV_CPU_CALL_AVX512_ICL_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_AVX512_ICL(fn, args, mode, ...) CV_CPU_CALL_AVX512_ICL(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_NEON +# define CV_TRY_NEON 1 +# define CV_CPU_FORCE_NEON 1 +# define CV_CPU_HAS_SUPPORT_NEON 1 +# define CV_CPU_CALL_NEON(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_NEON_(fn, args) return (opt_NEON::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_NEON +# define CV_TRY_NEON 1 +# define CV_CPU_FORCE_NEON 0 +# define CV_CPU_HAS_SUPPORT_NEON (cv::checkHardwareSupport(CV_CPU_NEON)) +# define CV_CPU_CALL_NEON(fn, args) if (CV_CPU_HAS_SUPPORT_NEON) return (opt_NEON::fn args) +# define CV_CPU_CALL_NEON_(fn, args) if (CV_CPU_HAS_SUPPORT_NEON) return (opt_NEON::fn args) +#else +# define CV_TRY_NEON 0 +# define CV_CPU_FORCE_NEON 0 +# define CV_CPU_HAS_SUPPORT_NEON 0 +# define CV_CPU_CALL_NEON(fn, args) +# define CV_CPU_CALL_NEON_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_NEON(fn, args, mode, ...) CV_CPU_CALL_NEON(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_NEON_DOTPROD +# define CV_TRY_NEON_DOTPROD 1 +# define CV_CPU_FORCE_NEON_DOTPROD 1 +# define CV_CPU_HAS_SUPPORT_NEON_DOTPROD 1 +# define CV_CPU_CALL_NEON_DOTPROD(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_NEON_DOTPROD_(fn, args) return (opt_NEON_DOTPROD::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_NEON_DOTPROD +# define CV_TRY_NEON_DOTPROD 1 +# define CV_CPU_FORCE_NEON_DOTPROD 0 +# define CV_CPU_HAS_SUPPORT_NEON_DOTPROD (cv::checkHardwareSupport(CV_CPU_NEON_DOTPROD)) +# define CV_CPU_CALL_NEON_DOTPROD(fn, args) if (CV_CPU_HAS_SUPPORT_NEON_DOTPROD) return (opt_NEON_DOTPROD::fn args) +# define CV_CPU_CALL_NEON_DOTPROD_(fn, args) if (CV_CPU_HAS_SUPPORT_NEON_DOTPROD) return (opt_NEON_DOTPROD::fn args) +#else +# define CV_TRY_NEON_DOTPROD 0 +# define CV_CPU_FORCE_NEON_DOTPROD 0 +# define CV_CPU_HAS_SUPPORT_NEON_DOTPROD 0 +# define CV_CPU_CALL_NEON_DOTPROD(fn, args) +# define CV_CPU_CALL_NEON_DOTPROD_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_NEON_DOTPROD(fn, args, mode, ...) CV_CPU_CALL_NEON_DOTPROD(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_NEON_FP16 +# define CV_TRY_NEON_FP16 1 +# define CV_CPU_FORCE_NEON_FP16 1 +# define CV_CPU_HAS_SUPPORT_NEON_FP16 1 +# define CV_CPU_CALL_NEON_FP16(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_NEON_FP16_(fn, args) return (opt_NEON_FP16::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_NEON_FP16 +# define CV_TRY_NEON_FP16 1 +# define CV_CPU_FORCE_NEON_FP16 0 +# define CV_CPU_HAS_SUPPORT_NEON_FP16 (cv::checkHardwareSupport(CV_CPU_NEON_FP16)) +# define CV_CPU_CALL_NEON_FP16(fn, args) if (CV_CPU_HAS_SUPPORT_NEON_FP16) return (opt_NEON_FP16::fn args) +# define CV_CPU_CALL_NEON_FP16_(fn, args) if (CV_CPU_HAS_SUPPORT_NEON_FP16) return (opt_NEON_FP16::fn args) +#else +# define CV_TRY_NEON_FP16 0 +# define CV_CPU_FORCE_NEON_FP16 0 +# define CV_CPU_HAS_SUPPORT_NEON_FP16 0 +# define CV_CPU_CALL_NEON_FP16(fn, args) +# define CV_CPU_CALL_NEON_FP16_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_NEON_FP16(fn, args, mode, ...) CV_CPU_CALL_NEON_FP16(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_NEON_BF16 +# define CV_TRY_NEON_BF16 1 +# define CV_CPU_FORCE_NEON_BF16 1 +# define CV_CPU_HAS_SUPPORT_NEON_BF16 1 +# define CV_CPU_CALL_NEON_BF16(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_NEON_BF16_(fn, args) return (opt_NEON_BF16::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_NEON_BF16 +# define CV_TRY_NEON_BF16 1 +# define CV_CPU_FORCE_NEON_BF16 0 +# define CV_CPU_HAS_SUPPORT_NEON_BF16 (cv::checkHardwareSupport(CV_CPU_NEON_BF16)) +# define CV_CPU_CALL_NEON_BF16(fn, args) if (CV_CPU_HAS_SUPPORT_NEON_BF16) return (opt_NEON_BF16::fn args) +# define CV_CPU_CALL_NEON_BF16_(fn, args) if (CV_CPU_HAS_SUPPORT_NEON_BF16) return (opt_NEON_BF16::fn args) +#else +# define CV_TRY_NEON_BF16 0 +# define CV_CPU_FORCE_NEON_BF16 0 +# define CV_CPU_HAS_SUPPORT_NEON_BF16 0 +# define CV_CPU_CALL_NEON_BF16(fn, args) +# define CV_CPU_CALL_NEON_BF16_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_NEON_BF16(fn, args, mode, ...) CV_CPU_CALL_NEON_BF16(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_MSA +# define CV_TRY_MSA 1 +# define CV_CPU_FORCE_MSA 1 +# define CV_CPU_HAS_SUPPORT_MSA 1 +# define CV_CPU_CALL_MSA(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_MSA_(fn, args) return (opt_MSA::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_MSA +# define CV_TRY_MSA 1 +# define CV_CPU_FORCE_MSA 0 +# define CV_CPU_HAS_SUPPORT_MSA (cv::checkHardwareSupport(CV_CPU_MSA)) +# define CV_CPU_CALL_MSA(fn, args) if (CV_CPU_HAS_SUPPORT_MSA) return (opt_MSA::fn args) +# define CV_CPU_CALL_MSA_(fn, args) if (CV_CPU_HAS_SUPPORT_MSA) return (opt_MSA::fn args) +#else +# define CV_TRY_MSA 0 +# define CV_CPU_FORCE_MSA 0 +# define CV_CPU_HAS_SUPPORT_MSA 0 +# define CV_CPU_CALL_MSA(fn, args) +# define CV_CPU_CALL_MSA_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_MSA(fn, args, mode, ...) CV_CPU_CALL_MSA(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_VSX +# define CV_TRY_VSX 1 +# define CV_CPU_FORCE_VSX 1 +# define CV_CPU_HAS_SUPPORT_VSX 1 +# define CV_CPU_CALL_VSX(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_VSX_(fn, args) return (opt_VSX::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_VSX +# define CV_TRY_VSX 1 +# define CV_CPU_FORCE_VSX 0 +# define CV_CPU_HAS_SUPPORT_VSX (cv::checkHardwareSupport(CV_CPU_VSX)) +# define CV_CPU_CALL_VSX(fn, args) if (CV_CPU_HAS_SUPPORT_VSX) return (opt_VSX::fn args) +# define CV_CPU_CALL_VSX_(fn, args) if (CV_CPU_HAS_SUPPORT_VSX) return (opt_VSX::fn args) +#else +# define CV_TRY_VSX 0 +# define CV_CPU_FORCE_VSX 0 +# define CV_CPU_HAS_SUPPORT_VSX 0 +# define CV_CPU_CALL_VSX(fn, args) +# define CV_CPU_CALL_VSX_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_VSX(fn, args, mode, ...) CV_CPU_CALL_VSX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_VSX3 +# define CV_TRY_VSX3 1 +# define CV_CPU_FORCE_VSX3 1 +# define CV_CPU_HAS_SUPPORT_VSX3 1 +# define CV_CPU_CALL_VSX3(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_VSX3_(fn, args) return (opt_VSX3::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_VSX3 +# define CV_TRY_VSX3 1 +# define CV_CPU_FORCE_VSX3 0 +# define CV_CPU_HAS_SUPPORT_VSX3 (cv::checkHardwareSupport(CV_CPU_VSX3)) +# define CV_CPU_CALL_VSX3(fn, args) if (CV_CPU_HAS_SUPPORT_VSX3) return (opt_VSX3::fn args) +# define CV_CPU_CALL_VSX3_(fn, args) if (CV_CPU_HAS_SUPPORT_VSX3) return (opt_VSX3::fn args) +#else +# define CV_TRY_VSX3 0 +# define CV_CPU_FORCE_VSX3 0 +# define CV_CPU_HAS_SUPPORT_VSX3 0 +# define CV_CPU_CALL_VSX3(fn, args) +# define CV_CPU_CALL_VSX3_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_VSX3(fn, args, mode, ...) CV_CPU_CALL_VSX3(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_RVV +# define CV_TRY_RVV 1 +# define CV_CPU_FORCE_RVV 1 +# define CV_CPU_HAS_SUPPORT_RVV 1 +# define CV_CPU_CALL_RVV(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_RVV_(fn, args) return (opt_RVV::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_RVV +# define CV_TRY_RVV 1 +# define CV_CPU_FORCE_RVV 0 +# define CV_CPU_HAS_SUPPORT_RVV (cv::checkHardwareSupport(CV_CPU_RVV)) +# define CV_CPU_CALL_RVV(fn, args) if (CV_CPU_HAS_SUPPORT_RVV) return (opt_RVV::fn args) +# define CV_CPU_CALL_RVV_(fn, args) if (CV_CPU_HAS_SUPPORT_RVV) return (opt_RVV::fn args) +#else +# define CV_TRY_RVV 0 +# define CV_CPU_FORCE_RVV 0 +# define CV_CPU_HAS_SUPPORT_RVV 0 +# define CV_CPU_CALL_RVV(fn, args) +# define CV_CPU_CALL_RVV_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_RVV(fn, args, mode, ...) CV_CPU_CALL_RVV(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_LSX +# define CV_TRY_LSX 1 +# define CV_CPU_FORCE_LSX 1 +# define CV_CPU_HAS_SUPPORT_LSX 1 +# define CV_CPU_CALL_LSX(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_LSX_(fn, args) return (opt_LSX::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_LSX +# define CV_TRY_LSX 1 +# define CV_CPU_FORCE_LSX 0 +# define CV_CPU_HAS_SUPPORT_LSX (cv::checkHardwareSupport(CV_CPU_LSX)) +# define CV_CPU_CALL_LSX(fn, args) if (CV_CPU_HAS_SUPPORT_LSX) return (opt_LSX::fn args) +# define CV_CPU_CALL_LSX_(fn, args) if (CV_CPU_HAS_SUPPORT_LSX) return (opt_LSX::fn args) +#else +# define CV_TRY_LSX 0 +# define CV_CPU_FORCE_LSX 0 +# define CV_CPU_HAS_SUPPORT_LSX 0 +# define CV_CPU_CALL_LSX(fn, args) +# define CV_CPU_CALL_LSX_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_LSX(fn, args, mode, ...) CV_CPU_CALL_LSX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_LASX +# define CV_TRY_LASX 1 +# define CV_CPU_FORCE_LASX 1 +# define CV_CPU_HAS_SUPPORT_LASX 1 +# define CV_CPU_CALL_LASX(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_LASX_(fn, args) return (opt_LASX::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_LASX +# define CV_TRY_LASX 1 +# define CV_CPU_FORCE_LASX 0 +# define CV_CPU_HAS_SUPPORT_LASX (cv::checkHardwareSupport(CV_CPU_LASX)) +# define CV_CPU_CALL_LASX(fn, args) if (CV_CPU_HAS_SUPPORT_LASX) return (opt_LASX::fn args) +# define CV_CPU_CALL_LASX_(fn, args) if (CV_CPU_HAS_SUPPORT_LASX) return (opt_LASX::fn args) +#else +# define CV_TRY_LASX 0 +# define CV_CPU_FORCE_LASX 0 +# define CV_CPU_HAS_SUPPORT_LASX 0 +# define CV_CPU_CALL_LASX(fn, args) +# define CV_CPU_CALL_LASX_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_LASX(fn, args, mode, ...) CV_CPU_CALL_LASX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#define CV_CPU_CALL_BASELINE(fn, args) return (cpu_baseline::fn args) +#define __CV_CPU_DISPATCH_CHAIN_BASELINE(fn, args, mode, ...) CV_CPU_CALL_BASELINE(fn, args) /* last in sequence */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cvdef.h b/3rdParty/opencv-4.11.0/opencv2/core/cvdef.h index 0e6d6ff49b..002a60f4d2 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cvdef.h +++ b/3rdParty/opencv-4.11.0/opencv2/core/cvdef.h @@ -1,948 +1,948 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CORE_CVDEF_H -#define OPENCV_CORE_CVDEF_H - -#include "opencv2/core/version.hpp" - -//! @addtogroup core_utils -//! @{ - -#ifdef OPENCV_INCLUDE_PORT_FILE // User-provided header file with custom platform configuration -#include OPENCV_INCLUDE_PORT_FILE -#endif - -#if !defined CV_DOXYGEN && !defined CV_IGNORE_DEBUG_BUILD_GUARD -#if (defined(_MSC_VER) && (defined(DEBUG) || defined(_DEBUG))) || \ - (defined(_GLIBCXX_DEBUG) || defined(_GLIBCXX_DEBUG_PEDANTIC)) -// Guard to prevent using of binary incompatible binaries / runtimes -// https://github.com/opencv/opencv/pull/9161 -#define CV__DEBUG_NS_BEGIN namespace debug_build_guard { -#define CV__DEBUG_NS_END } -namespace cv { namespace debug_build_guard { } using namespace debug_build_guard; } -#endif -#endif - -#ifndef CV__DEBUG_NS_BEGIN -#define CV__DEBUG_NS_BEGIN -#define CV__DEBUG_NS_END -#endif - - -#ifdef __OPENCV_BUILD -#include "cvconfig.h" -#endif - -#ifndef __CV_EXPAND -#define __CV_EXPAND(x) x -#endif - -#ifndef __CV_CAT -#define __CV_CAT__(x, y) x ## y -#define __CV_CAT_(x, y) __CV_CAT__(x, y) -#define __CV_CAT(x, y) __CV_CAT_(x, y) -#endif - -#define __CV_VA_NUM_ARGS_HELPER(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N -#define __CV_VA_NUM_ARGS(...) __CV_EXPAND(__CV_VA_NUM_ARGS_HELPER(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)) - -#ifdef CV_Func -// keep current value (through OpenCV port file) -#elif defined __GNUC__ || (defined (__cpluscplus) && (__cpluscplus >= 201103)) -#define CV_Func __func__ -#elif defined __clang__ && (__clang_minor__ * 100 + __clang_major__ >= 305) -#define CV_Func __func__ -#elif defined(__STDC_VERSION__) && (__STDC_VERSION >= 199901) -#define CV_Func __func__ -#elif defined _MSC_VER -#define CV_Func __FUNCTION__ -#elif defined(__INTEL_COMPILER) && (_INTEL_COMPILER >= 600) -#define CV_Func __FUNCTION__ -#elif defined __IBMCPP__ && __IBMCPP__ >=500 -#define CV_Func __FUNCTION__ -#elif defined __BORLAND__ && (__BORLANDC__ >= 0x550) -#define CV_Func __FUNC__ -#else -#define CV_Func "" -#endif - -//! @cond IGNORED - -//////////////// static assert ///////////////// -#define CVAUX_CONCAT_EXP(a, b) a##b -#define CVAUX_CONCAT(a, b) CVAUX_CONCAT_EXP(a,b) - -#if defined(__clang__) -# ifndef __has_extension -# define __has_extension __has_feature /* compatibility, for older versions of clang */ -# endif -# if __has_extension(cxx_static_assert) -# define CV_StaticAssert(condition, reason) static_assert((condition), reason " " #condition) -# elif __has_extension(c_static_assert) -# define CV_StaticAssert(condition, reason) _Static_assert((condition), reason " " #condition) -# endif -#elif defined(__GNUC__) -# if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L) -# define CV_StaticAssert(condition, reason) static_assert((condition), reason " " #condition) -# endif -#elif defined(_MSC_VER) -# if _MSC_VER >= 1600 /* MSVC 10 */ -# define CV_StaticAssert(condition, reason) static_assert((condition), reason " " #condition) -# endif -#endif -#ifndef CV_StaticAssert -# if !defined(__clang__) && defined(__GNUC__) && (__GNUC__*100 + __GNUC_MINOR__ > 302) -# define CV_StaticAssert(condition, reason) ({ extern int __attribute__((error("CV_StaticAssert: " reason " " #condition))) CV_StaticAssert(); ((condition) ? 0 : CV_StaticAssert()); }) -# else -namespace cv { - template struct CV_StaticAssert_failed; - template <> struct CV_StaticAssert_failed { enum { val = 1 }; }; - template struct CV_StaticAssert_test {}; -} -# define CV_StaticAssert(condition, reason)\ - typedef cv::CV_StaticAssert_test< sizeof(cv::CV_StaticAssert_failed< static_cast(condition) >) > CVAUX_CONCAT(CV_StaticAssert_failed_at_, __LINE__) -# endif -#endif - -// Suppress warning "-Wdeprecated-declarations" / C4996 -#if defined(_MSC_VER) - #define CV_DO_PRAGMA(x) __pragma(x) -#elif defined(__GNUC__) - #define CV_DO_PRAGMA(x) _Pragma (#x) -#else - #define CV_DO_PRAGMA(x) -#endif - -#ifdef _MSC_VER -#define CV_SUPPRESS_DEPRECATED_START \ - CV_DO_PRAGMA(warning(push)) \ - CV_DO_PRAGMA(warning(disable: 4996)) -#define CV_SUPPRESS_DEPRECATED_END CV_DO_PRAGMA(warning(pop)) -#elif defined (__clang__) || ((__GNUC__) && (__GNUC__*100 + __GNUC_MINOR__ > 405)) -#define CV_SUPPRESS_DEPRECATED_START \ - CV_DO_PRAGMA(GCC diagnostic push) \ - CV_DO_PRAGMA(GCC diagnostic ignored "-Wdeprecated-declarations") -#define CV_SUPPRESS_DEPRECATED_END CV_DO_PRAGMA(GCC diagnostic pop) -#else -#define CV_SUPPRESS_DEPRECATED_START -#define CV_SUPPRESS_DEPRECATED_END -#endif - -#define CV_UNUSED(name) (void)name - -//! @endcond - -// undef problematic defines sometimes defined by system headers (windows.h in particular) -#undef small -#undef min -#undef max -#undef abs -#undef Complex - -#if defined __cplusplus -#include -#else -#include -#endif - -#include "opencv2/core/hal/interface.h" - -#if defined __ICL -# define CV_ICC __ICL -#elif defined __ICC -# define CV_ICC __ICC -#elif defined __ECL -# define CV_ICC __ECL -#elif defined __ECC -# define CV_ICC __ECC -#elif defined __INTEL_COMPILER -# define CV_ICC __INTEL_COMPILER -#endif - -#if defined _WIN32 -# define CV_CDECL __cdecl -# define CV_STDCALL __stdcall -#else -# define CV_CDECL -# define CV_STDCALL -#endif - -#ifndef CV_INLINE -# if defined __cplusplus -# define CV_INLINE static inline -# elif defined _MSC_VER -# define CV_INLINE __inline -# else -# define CV_INLINE static -# endif -#endif - -#ifndef CV_ALWAYS_INLINE -#if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) -#define CV_ALWAYS_INLINE inline __attribute__((always_inline)) -#elif defined(_MSC_VER) -#define CV_ALWAYS_INLINE __forceinline -#else -#define CV_ALWAYS_INLINE inline -#endif -#endif - -#if defined CV_DISABLE_OPTIMIZATION || (defined CV_ICC && !defined CV_ENABLE_UNROLLED) -# define CV_ENABLE_UNROLLED 0 -#else -# define CV_ENABLE_UNROLLED 1 -#endif - -#ifdef __GNUC__ -# define CV_DECL_ALIGNED(x) __attribute__ ((aligned (x))) -#elif defined _MSC_VER -# define CV_DECL_ALIGNED(x) __declspec(align(x)) -#else -# define CV_DECL_ALIGNED(x) -#endif - -/* CPU features and intrinsics support */ -#define CV_CPU_NONE 0 -#define CV_CPU_MMX 1 -#define CV_CPU_SSE 2 -#define CV_CPU_SSE2 3 -#define CV_CPU_SSE3 4 -#define CV_CPU_SSSE3 5 -#define CV_CPU_SSE4_1 6 -#define CV_CPU_SSE4_2 7 -#define CV_CPU_POPCNT 8 -#define CV_CPU_FP16 9 -#define CV_CPU_AVX 10 -#define CV_CPU_AVX2 11 -#define CV_CPU_FMA3 12 - -#define CV_CPU_AVX_512F 13 -#define CV_CPU_AVX_512BW 14 -#define CV_CPU_AVX_512CD 15 -#define CV_CPU_AVX_512DQ 16 -#define CV_CPU_AVX_512ER 17 -#define CV_CPU_AVX_512IFMA512 18 // deprecated -#define CV_CPU_AVX_512IFMA 18 -#define CV_CPU_AVX_512PF 19 -#define CV_CPU_AVX_512VBMI 20 -#define CV_CPU_AVX_512VL 21 -#define CV_CPU_AVX_512VBMI2 22 -#define CV_CPU_AVX_512VNNI 23 -#define CV_CPU_AVX_512BITALG 24 -#define CV_CPU_AVX_512VPOPCNTDQ 25 -#define CV_CPU_AVX_5124VNNIW 26 -#define CV_CPU_AVX_5124FMAPS 27 - -#define CV_CPU_NEON 100 -#define CV_CPU_NEON_DOTPROD 101 -#define CV_CPU_NEON_FP16 102 -#define CV_CPU_NEON_BF16 103 - -#define CV_CPU_MSA 150 - -#define CV_CPU_RISCVV 170 - -#define CV_CPU_VSX 200 -#define CV_CPU_VSX3 201 - -#define CV_CPU_RVV 210 - -#define CV_CPU_LSX 230 -#define CV_CPU_LASX 231 - -// CPU features groups -#define CV_CPU_AVX512_SKX 256 -#define CV_CPU_AVX512_COMMON 257 -#define CV_CPU_AVX512_KNL 258 -#define CV_CPU_AVX512_KNM 259 -#define CV_CPU_AVX512_CNL 260 -#define CV_CPU_AVX512_CLX 261 -#define CV_CPU_AVX512_ICL 262 - -// when adding to this list remember to update the following enum -#define CV_HARDWARE_MAX_FEATURE 512 - -/** @brief Available CPU features. -*/ -enum CpuFeatures { - CPU_MMX = 1, - CPU_SSE = 2, - CPU_SSE2 = 3, - CPU_SSE3 = 4, - CPU_SSSE3 = 5, - CPU_SSE4_1 = 6, - CPU_SSE4_2 = 7, - CPU_POPCNT = 8, - CPU_FP16 = 9, - CPU_AVX = 10, - CPU_AVX2 = 11, - CPU_FMA3 = 12, - - CPU_AVX_512F = 13, - CPU_AVX_512BW = 14, - CPU_AVX_512CD = 15, - CPU_AVX_512DQ = 16, - CPU_AVX_512ER = 17, - CPU_AVX_512IFMA512 = 18, // deprecated - CPU_AVX_512IFMA = 18, - CPU_AVX_512PF = 19, - CPU_AVX_512VBMI = 20, - CPU_AVX_512VL = 21, - CPU_AVX_512VBMI2 = 22, - CPU_AVX_512VNNI = 23, - CPU_AVX_512BITALG = 24, - CPU_AVX_512VPOPCNTDQ= 25, - CPU_AVX_5124VNNIW = 26, - CPU_AVX_5124FMAPS = 27, - - CPU_NEON = 100, - CPU_NEON_DOTPROD = 101, - CPU_NEON_FP16 = 102, - CPU_NEON_BF16 = 103, - - CPU_MSA = 150, - - CPU_RISCVV = 170, - - CPU_VSX = 200, - CPU_VSX3 = 201, - - CPU_RVV = 210, - - CPU_LSX = 230, - CPU_LASX = 231, - - CPU_AVX512_SKX = 256, //!< Skylake-X with AVX-512F/CD/BW/DQ/VL - CPU_AVX512_COMMON = 257, //!< Common instructions AVX-512F/CD for all CPUs that support AVX-512 - CPU_AVX512_KNL = 258, //!< Knights Landing with AVX-512F/CD/ER/PF - CPU_AVX512_KNM = 259, //!< Knights Mill with AVX-512F/CD/ER/PF/4FMAPS/4VNNIW/VPOPCNTDQ - CPU_AVX512_CNL = 260, //!< Cannon Lake with AVX-512F/CD/BW/DQ/VL/IFMA/VBMI - CPU_AVX512_CLX = 261, //!< Cascade Lake with AVX-512F/CD/BW/DQ/VL/VNNI - CPU_AVX512_ICL = 262, //!< Ice Lake with AVX-512F/CD/BW/DQ/VL/IFMA/VBMI/VNNI/VBMI2/BITALG/VPOPCNTDQ - - CPU_MAX_FEATURE = 512 // see CV_HARDWARE_MAX_FEATURE -}; - - -#include "cv_cpu_dispatch.h" - -#if !defined(CV_STRONG_ALIGNMENT) && defined(__arm__) && !(defined(__aarch64__) || defined(_M_ARM64)) -// int*, int64* should be propertly aligned pointers on ARMv7 -#define CV_STRONG_ALIGNMENT 1 -#endif -#if !defined(CV_STRONG_ALIGNMENT) -#define CV_STRONG_ALIGNMENT 0 -#endif - -/* fundamental constants */ -#define CV_PI 3.1415926535897932384626433832795 -#define CV_2PI 6.283185307179586476925286766559 -#define CV_LOG2 0.69314718055994530941723212145818 - -#if defined __ARM_FP16_FORMAT_IEEE \ - && !defined __CUDACC__ -# define CV_FP16_TYPE 1 -#else -# define CV_FP16_TYPE 0 -#endif - -typedef union Cv16suf -{ - short i; - ushort u; -#if CV_FP16_TYPE - __fp16 h; -#endif -} -Cv16suf; - -typedef union Cv32suf -{ - int i; - unsigned u; - float f; -} -Cv32suf; - -typedef union Cv64suf -{ - int64 i; - uint64 u; - double f; -} -Cv64suf; - -#ifndef OPENCV_ABI_COMPATIBILITY -#define OPENCV_ABI_COMPATIBILITY 400 -#endif - -#ifdef __OPENCV_BUILD -# define DISABLE_OPENCV_3_COMPATIBILITY -# define OPENCV_DISABLE_DEPRECATED_COMPATIBILITY -#endif - -#ifndef CV_EXPORTS -# if (defined _WIN32 || defined WINCE || defined __CYGWIN__) && defined(CVAPI_EXPORTS) -# define CV_EXPORTS __declspec(dllexport) -# elif defined __GNUC__ && __GNUC__ >= 4 && (defined(CVAPI_EXPORTS) || defined(__APPLE__)) -# define CV_EXPORTS __attribute__ ((visibility ("default"))) -# endif -#endif - -#ifndef CV_EXPORTS -# define CV_EXPORTS -#endif - -#ifdef _MSC_VER -# define CV_EXPORTS_TEMPLATE -#else -# define CV_EXPORTS_TEMPLATE CV_EXPORTS -#endif - -#ifndef CV_DEPRECATED -# if defined(__GNUC__) -# define CV_DEPRECATED __attribute__ ((deprecated)) -# elif defined(_MSC_VER) -# define CV_DEPRECATED __declspec(deprecated) -# else -# define CV_DEPRECATED -# endif -#endif - -#ifndef CV_DEPRECATED_EXTERNAL -# if defined(__OPENCV_BUILD) -# define CV_DEPRECATED_EXTERNAL /* nothing */ -# else -# define CV_DEPRECATED_EXTERNAL CV_DEPRECATED -# endif -#endif - - -#ifndef CV_EXTERN_C -# ifdef __cplusplus -# define CV_EXTERN_C extern "C" -# else -# define CV_EXTERN_C -# endif -#endif - -/* special informative macros for wrapper generators */ -#define CV_EXPORTS_W CV_EXPORTS -#define CV_EXPORTS_W_SIMPLE CV_EXPORTS -#define CV_EXPORTS_AS(synonym) CV_EXPORTS -#define CV_EXPORTS_W_MAP CV_EXPORTS -#define CV_EXPORTS_W_PARAMS CV_EXPORTS -#define CV_IN_OUT -#define CV_OUT -#define CV_PROP -#define CV_PROP_RW -#define CV_ND // Indicates that input data should be parsed into Mat without channels -#define CV_WRAP -#define CV_WRAP_AS(synonym) -#define CV_WRAP_MAPPABLE(mappable) -#define CV_WRAP_PHANTOM(phantom_header) -#define CV_WRAP_DEFAULT(val) -/* Indicates that the function parameter has filesystem path semantic */ -#define CV_WRAP_FILE_PATH - -/****************************************************************************************\ -* Matrix type (Mat) * -\****************************************************************************************/ - -#define CV_MAX_DIM 32 -#define CV_MAT_CN_MASK ((CV_CN_MAX - 1) << CV_CN_SHIFT) -#define CV_MAT_CN(flags) ((((flags) & CV_MAT_CN_MASK) >> CV_CN_SHIFT) + 1) -#define CV_MAT_TYPE_MASK (CV_DEPTH_MAX*CV_CN_MAX - 1) -#define CV_MAT_TYPE(flags) ((flags) & CV_MAT_TYPE_MASK) -#define CV_MAT_CONT_FLAG_SHIFT 14 -#define CV_MAT_CONT_FLAG (1 << CV_MAT_CONT_FLAG_SHIFT) -#define CV_IS_MAT_CONT(flags) ((flags) & CV_MAT_CONT_FLAG) -#define CV_IS_CONT_MAT CV_IS_MAT_CONT -#define CV_SUBMAT_FLAG_SHIFT 15 -#define CV_SUBMAT_FLAG (1 << CV_SUBMAT_FLAG_SHIFT) -#define CV_IS_SUBMAT(flags) ((flags) & CV_MAT_SUBMAT_FLAG) - -/** Size of each channel item, - 0x28442211 = 0010 1000 0100 0100 0010 0010 0001 0001 ~ array of sizeof(arr_type_elem) */ -#define CV_ELEM_SIZE1(type) ((0x28442211 >> CV_MAT_DEPTH(type)*4) & 15) - -#define CV_ELEM_SIZE(type) (CV_MAT_CN(type)*CV_ELEM_SIZE1(type)) - -#ifndef MIN -# define MIN(a,b) ((a) > (b) ? (b) : (a)) -#endif - -#ifndef MAX -# define MAX(a,b) ((a) < (b) ? (b) : (a)) -#endif - -/** min & max without jumps */ -#define CV_IMIN(a, b) ((a) ^ (((a)^(b)) & (((a) < (b)) - 1))) -#define CV_IMAX(a, b) ((a) ^ (((a)^(b)) & (((a) > (b)) - 1))) -#define CV_SWAP(a,b,t) ((t) = (a), (a) = (b), (b) = (t)) -#define CV_CMP(a,b) (((a) > (b)) - ((a) < (b))) -#define CV_SIGN(a) CV_CMP((a),0) - -///////////////////////////////////////// Enum operators /////////////////////////////////////// - -/** - -Provides compatibility operators for both classical and C++11 enum classes, -as well as exposing the C++11 enum class members for backwards compatibility - -@code - // Provides operators required for flag enums - CV_ENUM_FLAGS(AccessFlag) - - // Exposes the listed members of the enum class AccessFlag to the current namespace - CV_ENUM_CLASS_EXPOSE(AccessFlag, ACCESS_READ [, ACCESS_WRITE [, ...] ]); -@endcode -*/ - -#define __CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST) \ -static const EnumType MEMBER_CONST = EnumType::MEMBER_CONST; \ - -#define __CV_ENUM_CLASS_EXPOSE_2(EnumType, MEMBER_CONST, ...) \ -__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ -__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_1(EnumType, __VA_ARGS__)); \ - -#define __CV_ENUM_CLASS_EXPOSE_3(EnumType, MEMBER_CONST, ...) \ -__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ -__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_2(EnumType, __VA_ARGS__)); \ - -#define __CV_ENUM_CLASS_EXPOSE_4(EnumType, MEMBER_CONST, ...) \ -__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ -__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_3(EnumType, __VA_ARGS__)); \ - -#define __CV_ENUM_CLASS_EXPOSE_5(EnumType, MEMBER_CONST, ...) \ -__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ -__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_4(EnumType, __VA_ARGS__)); \ - -#define __CV_ENUM_CLASS_EXPOSE_6(EnumType, MEMBER_CONST, ...) \ -__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ -__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_5(EnumType, __VA_ARGS__)); \ - -#define __CV_ENUM_CLASS_EXPOSE_7(EnumType, MEMBER_CONST, ...) \ -__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ -__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_6(EnumType, __VA_ARGS__)); \ - -#define __CV_ENUM_CLASS_EXPOSE_8(EnumType, MEMBER_CONST, ...) \ -__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ -__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_7(EnumType, __VA_ARGS__)); \ - -#define __CV_ENUM_CLASS_EXPOSE_9(EnumType, MEMBER_CONST, ...) \ -__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ -__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_8(EnumType, __VA_ARGS__)); \ - -#define __CV_ENUM_FLAGS_LOGICAL_NOT(EnumType) \ -static inline bool operator!(const EnumType& val) \ -{ \ - typedef std::underlying_type::type UnderlyingType; \ - return !static_cast(val); \ -} \ - -#define __CV_ENUM_FLAGS_LOGICAL_NOT_EQ(Arg1Type, Arg2Type) \ -static inline bool operator!=(const Arg1Type& a, const Arg2Type& b) \ -{ \ - return static_cast(a) != static_cast(b); \ -} \ - -#define __CV_ENUM_FLAGS_LOGICAL_EQ(Arg1Type, Arg2Type) \ -static inline bool operator==(const Arg1Type& a, const Arg2Type& b) \ -{ \ - return static_cast(a) == static_cast(b); \ -} \ - -#define __CV_ENUM_FLAGS_BITWISE_NOT(EnumType) \ -static inline EnumType operator~(const EnumType& val) \ -{ \ - typedef std::underlying_type::type UnderlyingType; \ - return static_cast(~static_cast(val)); \ -} \ - -#define __CV_ENUM_FLAGS_BITWISE_OR(EnumType, Arg1Type, Arg2Type) \ -static inline EnumType operator|(const Arg1Type& a, const Arg2Type& b) \ -{ \ - typedef std::underlying_type::type UnderlyingType; \ - return static_cast(static_cast(a) | static_cast(b)); \ -} \ - -#define __CV_ENUM_FLAGS_BITWISE_AND(EnumType, Arg1Type, Arg2Type) \ -static inline EnumType operator&(const Arg1Type& a, const Arg2Type& b) \ -{ \ - typedef std::underlying_type::type UnderlyingType; \ - return static_cast(static_cast(a) & static_cast(b)); \ -} \ - -#define __CV_ENUM_FLAGS_BITWISE_XOR(EnumType, Arg1Type, Arg2Type) \ -static inline EnumType operator^(const Arg1Type& a, const Arg2Type& b) \ -{ \ - typedef std::underlying_type::type UnderlyingType; \ - return static_cast(static_cast(a) ^ static_cast(b)); \ -} \ - -#define __CV_ENUM_FLAGS_BITWISE_OR_EQ(EnumType, Arg1Type) \ -static inline EnumType& operator|=(EnumType& _this, const Arg1Type& val) \ -{ \ - _this = static_cast(static_cast(_this) | static_cast(val)); \ - return _this; \ -} \ - -#define __CV_ENUM_FLAGS_BITWISE_AND_EQ(EnumType, Arg1Type) \ -static inline EnumType& operator&=(EnumType& _this, const Arg1Type& val) \ -{ \ - _this = static_cast(static_cast(_this) & static_cast(val)); \ - return _this; \ -} \ - -#define __CV_ENUM_FLAGS_BITWISE_XOR_EQ(EnumType, Arg1Type) \ -static inline EnumType& operator^=(EnumType& _this, const Arg1Type& val) \ -{ \ - _this = static_cast(static_cast(_this) ^ static_cast(val)); \ - return _this; \ -} \ - -#define CV_ENUM_CLASS_EXPOSE(EnumType, ...) \ -__CV_EXPAND(__CV_CAT(__CV_ENUM_CLASS_EXPOSE_, __CV_VA_NUM_ARGS(__VA_ARGS__))(EnumType, __VA_ARGS__)); \ - -#define CV_ENUM_FLAGS(EnumType) \ -__CV_ENUM_FLAGS_LOGICAL_NOT (EnumType) \ -__CV_ENUM_FLAGS_LOGICAL_EQ (EnumType, int) \ -__CV_ENUM_FLAGS_LOGICAL_NOT_EQ (EnumType, int) \ - \ -__CV_ENUM_FLAGS_BITWISE_NOT (EnumType) \ -__CV_ENUM_FLAGS_BITWISE_OR (EnumType, EnumType, EnumType) \ -__CV_ENUM_FLAGS_BITWISE_AND (EnumType, EnumType, EnumType) \ -__CV_ENUM_FLAGS_BITWISE_XOR (EnumType, EnumType, EnumType) \ - \ -__CV_ENUM_FLAGS_BITWISE_OR_EQ (EnumType, EnumType) \ -__CV_ENUM_FLAGS_BITWISE_AND_EQ (EnumType, EnumType) \ -__CV_ENUM_FLAGS_BITWISE_XOR_EQ (EnumType, EnumType) \ - -/****************************************************************************************\ -* static analysys * -\****************************************************************************************/ - -// In practice, some macro are not processed correctly (noreturn is not detected). -// We need to use simplified definition for them. -#ifndef CV_STATIC_ANALYSIS -# if defined(__KLOCWORK__) || defined(__clang_analyzer__) || defined(__COVERITY__) -# define CV_STATIC_ANALYSIS 1 -# endif -#else -# if defined(CV_STATIC_ANALYSIS) && !(__CV_CAT(1, CV_STATIC_ANALYSIS) == 1) // defined and not empty -# if 0 == CV_STATIC_ANALYSIS -# undef CV_STATIC_ANALYSIS -# endif -# endif -#endif - -/****************************************************************************************\ -* Thread sanitizer * -\****************************************************************************************/ -#ifndef CV_THREAD_SANITIZER -# if defined(__has_feature) -# if __has_feature(thread_sanitizer) -# define CV_THREAD_SANITIZER -# endif -# endif -#endif - -/****************************************************************************************\ -* exchange-add operation for atomic operations on reference counters * -\****************************************************************************************/ - -#ifdef CV_XADD - // allow to use user-defined macro -#elif defined __GNUC__ || defined __clang__ -# if defined __clang__ && __clang_major__ >= 3 && !defined __ANDROID__ && !defined __EMSCRIPTEN__ && !defined(__CUDACC__) && !defined __INTEL_COMPILER -# ifdef __ATOMIC_ACQ_REL -# define CV_XADD(addr, delta) __c11_atomic_fetch_add((_Atomic(int)*)(addr), delta, __ATOMIC_ACQ_REL) -# else -# define CV_XADD(addr, delta) __atomic_fetch_add((_Atomic(int)*)(addr), delta, 4) -# endif -# else -# if defined __ATOMIC_ACQ_REL && !defined __clang__ - // version for gcc >= 4.7 -# define CV_XADD(addr, delta) (int)__atomic_fetch_add((unsigned*)(addr), (unsigned)(delta), __ATOMIC_ACQ_REL) -# else -# define CV_XADD(addr, delta) (int)__sync_fetch_and_add((unsigned*)(addr), (unsigned)(delta)) -# endif -# endif -#elif defined _MSC_VER && !defined RC_INVOKED -# include -# define CV_XADD(addr, delta) (int)_InterlockedExchangeAdd((long volatile*)addr, delta) -#else - #ifdef OPENCV_FORCE_UNSAFE_XADD - CV_INLINE int CV_XADD(int* addr, int delta) { int tmp = *addr; *addr += delta; return tmp; } - #else - #error "OpenCV: can't define safe CV_XADD macro for current platform (unsupported). Define CV_XADD macro through custom port header (see OPENCV_INCLUDE_PORT_FILE)" - #endif -#endif - - -/****************************************************************************************\ -* CV_NORETURN attribute * -\****************************************************************************************/ - -#ifndef CV_NORETURN -# if defined(__GNUC__) -# define CV_NORETURN __attribute__((__noreturn__)) -# elif defined(_MSC_VER) && (_MSC_VER >= 1300) -# define CV_NORETURN __declspec(noreturn) -# else -# define CV_NORETURN /* nothing by default */ -# endif -#endif - -/****************************************************************************************\ -* CV_NODISCARD_STD attribute (C++17) * -* encourages the compiler to issue a warning if the return value is discarded * -\****************************************************************************************/ -#ifndef CV_NODISCARD_STD -# ifndef __has_cpp_attribute -// workaround preprocessor non-compliance https://reviews.llvm.org/D57851 -# define __has_cpp_attribute(__x) 0 -# endif -# if __has_cpp_attribute(nodiscard) -# if defined(__NVCC__) && __CUDACC_VER_MAJOR__ < 12 -# define CV_NODISCARD_STD -# else -# define CV_NODISCARD_STD [[nodiscard]] -# endif -# elif __cplusplus >= 201703L -// available when compiler is C++17 compliant -# define CV_NODISCARD_STD [[nodiscard]] -# elif defined(__INTEL_COMPILER) - // see above, available when C++17 is enabled -# elif defined(_MSC_VER) && _MSC_VER >= 1911 && _MSVC_LANG >= 201703L -// available with VS2017 v15.3+ with /std:c++17 or higher; works on functions and classes -# define CV_NODISCARD_STD [[nodiscard]] -# elif defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 700) && (__cplusplus >= 201103L) -// available with GCC 7.0+; works on functions, works or silently fails on classes -# define CV_NODISCARD_STD [[nodiscard]] -# elif defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 408) && (__cplusplus >= 201103L) -// available with GCC 4.8+ but it usually does nothing and can fail noisily -- therefore not used -// define CV_NODISCARD_STD [[gnu::warn_unused_result]] -# endif -#endif -#ifndef CV_NODISCARD_STD -# define CV_NODISCARD_STD /* nothing by default */ -#endif - - -/****************************************************************************************\ -* C++ 11 * -\****************************************************************************************/ -#ifdef __cplusplus -// MSVC was stuck at __cplusplus == 199711L for a long time, even where it supports C++11, -// so check _MSC_VER instead. See: -// -# if defined(_MSC_VER) -# if _MSC_VER < 1800 -# error "OpenCV 4.x+ requires enabled C++11 support" -# endif -# elif __cplusplus < 201103L -# error "OpenCV 4.x+ requires enabled C++11 support" -# endif -#endif - -#ifndef CV_CXX11 -# define CV_CXX11 1 -#endif - -#ifndef CV_OVERRIDE -# define CV_OVERRIDE override -#endif - -#ifndef CV_FINAL -# define CV_FINAL final -#endif - -#ifndef CV_NOEXCEPT -# define CV_NOEXCEPT noexcept -#endif - -#ifndef CV_CONSTEXPR -# define CV_CONSTEXPR constexpr -#endif - -// Integer types portability -#ifdef __cplusplus -#include -namespace cv { -using std::int8_t; -using std::uint8_t; -using std::int16_t; -using std::uint16_t; -using std::int32_t; -using std::uint32_t; -using std::int64_t; -using std::uint64_t; -} -#else // pure C -#include -#endif - -#ifdef __cplusplus -namespace cv -{ - -class hfloat -{ -public: -#if CV_FP16_TYPE - - hfloat() : h(0) {} - explicit hfloat(float x) { h = (__fp16)x; } - operator float() const { return (float)h; } -protected: - __fp16 h; - -#else - hfloat() : w(0) {} - explicit hfloat(float x) - { - #if CV_FP16 && CV_AVX2 - __m128 v = _mm_load_ss(&x); - w = (ushort)_mm_cvtsi128_si32(_mm_cvtps_ph(v, 0)); - #else - Cv32suf in; - in.f = x; - unsigned sign = in.u & 0x80000000; - in.u ^= sign; - - if( in.u >= 0x47800000 ) - w = (ushort)(in.u > 0x7f800000 ? 0x7e00 : 0x7c00); - else - { - if (in.u < 0x38800000) - { - in.f += 0.5f; - w = (ushort)(in.u - 0x3f000000); - } - else - { - unsigned t = in.u + 0xc8000fff; - w = (ushort)((t + ((in.u >> 13) & 1)) >> 13); - } - } - - w = (ushort)(w | (sign >> 16)); - #endif - } - - operator float() const - { - #if CV_FP16 && CV_AVX2 - float f; - _mm_store_ss(&f, _mm_cvtph_ps(_mm_cvtsi32_si128(w))); - return f; - #else - Cv32suf out; - - unsigned t = ((w & 0x7fff) << 13) + 0x38000000; - unsigned sign = (w & 0x8000) << 16; - unsigned e = w & 0x7c00; - - out.u = t + (1 << 23); - out.u = (e >= 0x7c00 ? t + 0x38000000 : - e == 0 ? (static_cast(out.f -= 6.103515625e-05f), out.u) : t) | sign; - return out.f; - #endif - } - -protected: - ushort w; - -#endif -}; - -inline hfloat hfloatFromBits(ushort w) { -#if CV_FP16_TYPE - Cv16suf u; - u.u = w; - hfloat res(float(u.h)); - return res; -#else - Cv32suf out; - - unsigned t = ((w & 0x7fff) << 13) + 0x38000000; - unsigned sign = (w & 0x8000) << 16; - unsigned e = w & 0x7c00; - - out.u = t + (1 << 23); - out.u = (e >= 0x7c00 ? t + 0x38000000 : - e == 0 ? (static_cast(out.f -= 6.103515625e-05f), out.u) : t) | sign; - hfloat res(out.f); - return res; -#endif -} - -#if !defined(__OPENCV_BUILD) && !(defined __STDCPP_FLOAT16_T__) && !(defined __ARM_NEON) -typedef hfloat float16_t; -#endif - -} -#endif - -/** @brief Constructs the 'fourcc' code, used in video codecs and many other places. - Simply call it with 4 chars like `CV_FOURCC('I', 'Y', 'U', 'V')` -*/ -CV_INLINE int CV_FOURCC(char c1, char c2, char c3, char c4) -{ - return (c1 & 255) + ((c2 & 255) << 8) + ((c3 & 255) << 16) + ((c4 & 255) << 24); -} - -//! Macro to construct the fourcc code of the codec. Same as CV_FOURCC() -#define CV_FOURCC_MACRO(c1, c2, c3, c4) (((c1) & 255) + (((c2) & 255) << 8) + (((c3) & 255) << 16) + (((c4) & 255) << 24)) - -//! @} - -#ifndef __cplusplus -#include "opencv2/core/fast_math.hpp" // define cvRound(double) -#endif - -#endif // OPENCV_CORE_CVDEF_H +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CORE_CVDEF_H +#define OPENCV_CORE_CVDEF_H + +#include "opencv2/core/version.hpp" + +//! @addtogroup core_utils +//! @{ + +#ifdef OPENCV_INCLUDE_PORT_FILE // User-provided header file with custom platform configuration +#include OPENCV_INCLUDE_PORT_FILE +#endif + +#if !defined CV_DOXYGEN && !defined CV_IGNORE_DEBUG_BUILD_GUARD +#if (defined(_MSC_VER) && (defined(DEBUG) || defined(_DEBUG))) || \ + (defined(_GLIBCXX_DEBUG) || defined(_GLIBCXX_DEBUG_PEDANTIC)) +// Guard to prevent using of binary incompatible binaries / runtimes +// https://github.com/opencv/opencv/pull/9161 +#define CV__DEBUG_NS_BEGIN namespace debug_build_guard { +#define CV__DEBUG_NS_END } +namespace cv { namespace debug_build_guard { } using namespace debug_build_guard; } +#endif +#endif + +#ifndef CV__DEBUG_NS_BEGIN +#define CV__DEBUG_NS_BEGIN +#define CV__DEBUG_NS_END +#endif + + +#ifdef __OPENCV_BUILD +#include "cvconfig.h" +#endif + +#ifndef __CV_EXPAND +#define __CV_EXPAND(x) x +#endif + +#ifndef __CV_CAT +#define __CV_CAT__(x, y) x ## y +#define __CV_CAT_(x, y) __CV_CAT__(x, y) +#define __CV_CAT(x, y) __CV_CAT_(x, y) +#endif + +#define __CV_VA_NUM_ARGS_HELPER(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N +#define __CV_VA_NUM_ARGS(...) __CV_EXPAND(__CV_VA_NUM_ARGS_HELPER(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)) + +#ifdef CV_Func +// keep current value (through OpenCV port file) +#elif defined __GNUC__ || (defined (__cpluscplus) && (__cpluscplus >= 201103)) +#define CV_Func __func__ +#elif defined __clang__ && (__clang_minor__ * 100 + __clang_major__ >= 305) +#define CV_Func __func__ +#elif defined(__STDC_VERSION__) && (__STDC_VERSION >= 199901) +#define CV_Func __func__ +#elif defined _MSC_VER +#define CV_Func __FUNCTION__ +#elif defined(__INTEL_COMPILER) && (_INTEL_COMPILER >= 600) +#define CV_Func __FUNCTION__ +#elif defined __IBMCPP__ && __IBMCPP__ >=500 +#define CV_Func __FUNCTION__ +#elif defined __BORLAND__ && (__BORLANDC__ >= 0x550) +#define CV_Func __FUNC__ +#else +#define CV_Func "" +#endif + +//! @cond IGNORED + +//////////////// static assert ///////////////// +#define CVAUX_CONCAT_EXP(a, b) a##b +#define CVAUX_CONCAT(a, b) CVAUX_CONCAT_EXP(a,b) + +#if defined(__clang__) +# ifndef __has_extension +# define __has_extension __has_feature /* compatibility, for older versions of clang */ +# endif +# if __has_extension(cxx_static_assert) +# define CV_StaticAssert(condition, reason) static_assert((condition), reason " " #condition) +# elif __has_extension(c_static_assert) +# define CV_StaticAssert(condition, reason) _Static_assert((condition), reason " " #condition) +# endif +#elif defined(__GNUC__) +# if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L) +# define CV_StaticAssert(condition, reason) static_assert((condition), reason " " #condition) +# endif +#elif defined(_MSC_VER) +# if _MSC_VER >= 1600 /* MSVC 10 */ +# define CV_StaticAssert(condition, reason) static_assert((condition), reason " " #condition) +# endif +#endif +#ifndef CV_StaticAssert +# if !defined(__clang__) && defined(__GNUC__) && (__GNUC__*100 + __GNUC_MINOR__ > 302) +# define CV_StaticAssert(condition, reason) ({ extern int __attribute__((error("CV_StaticAssert: " reason " " #condition))) CV_StaticAssert(); ((condition) ? 0 : CV_StaticAssert()); }) +# else +namespace cv { + template struct CV_StaticAssert_failed; + template <> struct CV_StaticAssert_failed { enum { val = 1 }; }; + template struct CV_StaticAssert_test {}; +} +# define CV_StaticAssert(condition, reason)\ + typedef cv::CV_StaticAssert_test< sizeof(cv::CV_StaticAssert_failed< static_cast(condition) >) > CVAUX_CONCAT(CV_StaticAssert_failed_at_, __LINE__) +# endif +#endif + +// Suppress warning "-Wdeprecated-declarations" / C4996 +#if defined(_MSC_VER) + #define CV_DO_PRAGMA(x) __pragma(x) +#elif defined(__GNUC__) + #define CV_DO_PRAGMA(x) _Pragma (#x) +#else + #define CV_DO_PRAGMA(x) +#endif + +#ifdef _MSC_VER +#define CV_SUPPRESS_DEPRECATED_START \ + CV_DO_PRAGMA(warning(push)) \ + CV_DO_PRAGMA(warning(disable: 4996)) +#define CV_SUPPRESS_DEPRECATED_END CV_DO_PRAGMA(warning(pop)) +#elif defined (__clang__) || ((__GNUC__) && (__GNUC__*100 + __GNUC_MINOR__ > 405)) +#define CV_SUPPRESS_DEPRECATED_START \ + CV_DO_PRAGMA(GCC diagnostic push) \ + CV_DO_PRAGMA(GCC diagnostic ignored "-Wdeprecated-declarations") +#define CV_SUPPRESS_DEPRECATED_END CV_DO_PRAGMA(GCC diagnostic pop) +#else +#define CV_SUPPRESS_DEPRECATED_START +#define CV_SUPPRESS_DEPRECATED_END +#endif + +#define CV_UNUSED(name) (void)name + +//! @endcond + +// undef problematic defines sometimes defined by system headers (windows.h in particular) +#undef small +#undef min +#undef max +#undef abs +#undef Complex + +#if defined __cplusplus +#include +#else +#include +#endif + +#include "opencv2/core/hal/interface.h" + +#if defined __ICL +# define CV_ICC __ICL +#elif defined __ICC +# define CV_ICC __ICC +#elif defined __ECL +# define CV_ICC __ECL +#elif defined __ECC +# define CV_ICC __ECC +#elif defined __INTEL_COMPILER +# define CV_ICC __INTEL_COMPILER +#endif + +#if defined _WIN32 +# define CV_CDECL __cdecl +# define CV_STDCALL __stdcall +#else +# define CV_CDECL +# define CV_STDCALL +#endif + +#ifndef CV_INLINE +# if defined __cplusplus +# define CV_INLINE static inline +# elif defined _MSC_VER +# define CV_INLINE __inline +# else +# define CV_INLINE static +# endif +#endif + +#ifndef CV_ALWAYS_INLINE +#if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) +#define CV_ALWAYS_INLINE inline __attribute__((always_inline)) +#elif defined(_MSC_VER) +#define CV_ALWAYS_INLINE __forceinline +#else +#define CV_ALWAYS_INLINE inline +#endif +#endif + +#if defined CV_DISABLE_OPTIMIZATION || (defined CV_ICC && !defined CV_ENABLE_UNROLLED) +# define CV_ENABLE_UNROLLED 0 +#else +# define CV_ENABLE_UNROLLED 1 +#endif + +#ifdef __GNUC__ +# define CV_DECL_ALIGNED(x) __attribute__ ((aligned (x))) +#elif defined _MSC_VER +# define CV_DECL_ALIGNED(x) __declspec(align(x)) +#else +# define CV_DECL_ALIGNED(x) +#endif + +/* CPU features and intrinsics support */ +#define CV_CPU_NONE 0 +#define CV_CPU_MMX 1 +#define CV_CPU_SSE 2 +#define CV_CPU_SSE2 3 +#define CV_CPU_SSE3 4 +#define CV_CPU_SSSE3 5 +#define CV_CPU_SSE4_1 6 +#define CV_CPU_SSE4_2 7 +#define CV_CPU_POPCNT 8 +#define CV_CPU_FP16 9 +#define CV_CPU_AVX 10 +#define CV_CPU_AVX2 11 +#define CV_CPU_FMA3 12 + +#define CV_CPU_AVX_512F 13 +#define CV_CPU_AVX_512BW 14 +#define CV_CPU_AVX_512CD 15 +#define CV_CPU_AVX_512DQ 16 +#define CV_CPU_AVX_512ER 17 +#define CV_CPU_AVX_512IFMA512 18 // deprecated +#define CV_CPU_AVX_512IFMA 18 +#define CV_CPU_AVX_512PF 19 +#define CV_CPU_AVX_512VBMI 20 +#define CV_CPU_AVX_512VL 21 +#define CV_CPU_AVX_512VBMI2 22 +#define CV_CPU_AVX_512VNNI 23 +#define CV_CPU_AVX_512BITALG 24 +#define CV_CPU_AVX_512VPOPCNTDQ 25 +#define CV_CPU_AVX_5124VNNIW 26 +#define CV_CPU_AVX_5124FMAPS 27 + +#define CV_CPU_NEON 100 +#define CV_CPU_NEON_DOTPROD 101 +#define CV_CPU_NEON_FP16 102 +#define CV_CPU_NEON_BF16 103 + +#define CV_CPU_MSA 150 + +#define CV_CPU_RISCVV 170 + +#define CV_CPU_VSX 200 +#define CV_CPU_VSX3 201 + +#define CV_CPU_RVV 210 + +#define CV_CPU_LSX 230 +#define CV_CPU_LASX 231 + +// CPU features groups +#define CV_CPU_AVX512_SKX 256 +#define CV_CPU_AVX512_COMMON 257 +#define CV_CPU_AVX512_KNL 258 +#define CV_CPU_AVX512_KNM 259 +#define CV_CPU_AVX512_CNL 260 +#define CV_CPU_AVX512_CLX 261 +#define CV_CPU_AVX512_ICL 262 + +// when adding to this list remember to update the following enum +#define CV_HARDWARE_MAX_FEATURE 512 + +/** @brief Available CPU features. +*/ +enum CpuFeatures { + CPU_MMX = 1, + CPU_SSE = 2, + CPU_SSE2 = 3, + CPU_SSE3 = 4, + CPU_SSSE3 = 5, + CPU_SSE4_1 = 6, + CPU_SSE4_2 = 7, + CPU_POPCNT = 8, + CPU_FP16 = 9, + CPU_AVX = 10, + CPU_AVX2 = 11, + CPU_FMA3 = 12, + + CPU_AVX_512F = 13, + CPU_AVX_512BW = 14, + CPU_AVX_512CD = 15, + CPU_AVX_512DQ = 16, + CPU_AVX_512ER = 17, + CPU_AVX_512IFMA512 = 18, // deprecated + CPU_AVX_512IFMA = 18, + CPU_AVX_512PF = 19, + CPU_AVX_512VBMI = 20, + CPU_AVX_512VL = 21, + CPU_AVX_512VBMI2 = 22, + CPU_AVX_512VNNI = 23, + CPU_AVX_512BITALG = 24, + CPU_AVX_512VPOPCNTDQ= 25, + CPU_AVX_5124VNNIW = 26, + CPU_AVX_5124FMAPS = 27, + + CPU_NEON = 100, + CPU_NEON_DOTPROD = 101, + CPU_NEON_FP16 = 102, + CPU_NEON_BF16 = 103, + + CPU_MSA = 150, + + CPU_RISCVV = 170, + + CPU_VSX = 200, + CPU_VSX3 = 201, + + CPU_RVV = 210, + + CPU_LSX = 230, + CPU_LASX = 231, + + CPU_AVX512_SKX = 256, //!< Skylake-X with AVX-512F/CD/BW/DQ/VL + CPU_AVX512_COMMON = 257, //!< Common instructions AVX-512F/CD for all CPUs that support AVX-512 + CPU_AVX512_KNL = 258, //!< Knights Landing with AVX-512F/CD/ER/PF + CPU_AVX512_KNM = 259, //!< Knights Mill with AVX-512F/CD/ER/PF/4FMAPS/4VNNIW/VPOPCNTDQ + CPU_AVX512_CNL = 260, //!< Cannon Lake with AVX-512F/CD/BW/DQ/VL/IFMA/VBMI + CPU_AVX512_CLX = 261, //!< Cascade Lake with AVX-512F/CD/BW/DQ/VL/VNNI + CPU_AVX512_ICL = 262, //!< Ice Lake with AVX-512F/CD/BW/DQ/VL/IFMA/VBMI/VNNI/VBMI2/BITALG/VPOPCNTDQ + + CPU_MAX_FEATURE = 512 // see CV_HARDWARE_MAX_FEATURE +}; + + +#include "cv_cpu_dispatch.h" + +#if !defined(CV_STRONG_ALIGNMENT) && defined(__arm__) && !(defined(__aarch64__) || defined(_M_ARM64)) +// int*, int64* should be propertly aligned pointers on ARMv7 +#define CV_STRONG_ALIGNMENT 1 +#endif +#if !defined(CV_STRONG_ALIGNMENT) +#define CV_STRONG_ALIGNMENT 0 +#endif + +/* fundamental constants */ +#define CV_PI 3.1415926535897932384626433832795 +#define CV_2PI 6.283185307179586476925286766559 +#define CV_LOG2 0.69314718055994530941723212145818 + +#if defined __ARM_FP16_FORMAT_IEEE \ + && !defined __CUDACC__ +# define CV_FP16_TYPE 1 +#else +# define CV_FP16_TYPE 0 +#endif + +typedef union Cv16suf +{ + short i; + ushort u; +#if CV_FP16_TYPE + __fp16 h; +#endif +} +Cv16suf; + +typedef union Cv32suf +{ + int i; + unsigned u; + float f; +} +Cv32suf; + +typedef union Cv64suf +{ + int64 i; + uint64 u; + double f; +} +Cv64suf; + +#ifndef OPENCV_ABI_COMPATIBILITY +#define OPENCV_ABI_COMPATIBILITY 400 +#endif + +#ifdef __OPENCV_BUILD +# define DISABLE_OPENCV_3_COMPATIBILITY +# define OPENCV_DISABLE_DEPRECATED_COMPATIBILITY +#endif + +#ifndef CV_EXPORTS +# if (defined _WIN32 || defined WINCE || defined __CYGWIN__) && defined(CVAPI_EXPORTS) +# define CV_EXPORTS __declspec(dllexport) +# elif defined __GNUC__ && __GNUC__ >= 4 && (defined(CVAPI_EXPORTS) || defined(__APPLE__)) +# define CV_EXPORTS __attribute__ ((visibility ("default"))) +# endif +#endif + +#ifndef CV_EXPORTS +# define CV_EXPORTS +#endif + +#ifdef _MSC_VER +# define CV_EXPORTS_TEMPLATE +#else +# define CV_EXPORTS_TEMPLATE CV_EXPORTS +#endif + +#ifndef CV_DEPRECATED +# if defined(__GNUC__) +# define CV_DEPRECATED __attribute__ ((deprecated)) +# elif defined(_MSC_VER) +# define CV_DEPRECATED __declspec(deprecated) +# else +# define CV_DEPRECATED +# endif +#endif + +#ifndef CV_DEPRECATED_EXTERNAL +# if defined(__OPENCV_BUILD) +# define CV_DEPRECATED_EXTERNAL /* nothing */ +# else +# define CV_DEPRECATED_EXTERNAL CV_DEPRECATED +# endif +#endif + + +#ifndef CV_EXTERN_C +# ifdef __cplusplus +# define CV_EXTERN_C extern "C" +# else +# define CV_EXTERN_C +# endif +#endif + +/* special informative macros for wrapper generators */ +#define CV_EXPORTS_W CV_EXPORTS +#define CV_EXPORTS_W_SIMPLE CV_EXPORTS +#define CV_EXPORTS_AS(synonym) CV_EXPORTS +#define CV_EXPORTS_W_MAP CV_EXPORTS +#define CV_EXPORTS_W_PARAMS CV_EXPORTS +#define CV_IN_OUT +#define CV_OUT +#define CV_PROP +#define CV_PROP_RW +#define CV_ND // Indicates that input data should be parsed into Mat without channels +#define CV_WRAP +#define CV_WRAP_AS(synonym) +#define CV_WRAP_MAPPABLE(mappable) +#define CV_WRAP_PHANTOM(phantom_header) +#define CV_WRAP_DEFAULT(val) +/* Indicates that the function parameter has filesystem path semantic */ +#define CV_WRAP_FILE_PATH + +/****************************************************************************************\ +* Matrix type (Mat) * +\****************************************************************************************/ + +#define CV_MAX_DIM 32 +#define CV_MAT_CN_MASK ((CV_CN_MAX - 1) << CV_CN_SHIFT) +#define CV_MAT_CN(flags) ((((flags) & CV_MAT_CN_MASK) >> CV_CN_SHIFT) + 1) +#define CV_MAT_TYPE_MASK (CV_DEPTH_MAX*CV_CN_MAX - 1) +#define CV_MAT_TYPE(flags) ((flags) & CV_MAT_TYPE_MASK) +#define CV_MAT_CONT_FLAG_SHIFT 14 +#define CV_MAT_CONT_FLAG (1 << CV_MAT_CONT_FLAG_SHIFT) +#define CV_IS_MAT_CONT(flags) ((flags) & CV_MAT_CONT_FLAG) +#define CV_IS_CONT_MAT CV_IS_MAT_CONT +#define CV_SUBMAT_FLAG_SHIFT 15 +#define CV_SUBMAT_FLAG (1 << CV_SUBMAT_FLAG_SHIFT) +#define CV_IS_SUBMAT(flags) ((flags) & CV_MAT_SUBMAT_FLAG) + +/** Size of each channel item, + 0x28442211 = 0010 1000 0100 0100 0010 0010 0001 0001 ~ array of sizeof(arr_type_elem) */ +#define CV_ELEM_SIZE1(type) ((0x28442211 >> CV_MAT_DEPTH(type)*4) & 15) + +#define CV_ELEM_SIZE(type) (CV_MAT_CN(type)*CV_ELEM_SIZE1(type)) + +#ifndef MIN +# define MIN(a,b) ((a) > (b) ? (b) : (a)) +#endif + +#ifndef MAX +# define MAX(a,b) ((a) < (b) ? (b) : (a)) +#endif + +/** min & max without jumps */ +#define CV_IMIN(a, b) ((a) ^ (((a)^(b)) & (((a) < (b)) - 1))) +#define CV_IMAX(a, b) ((a) ^ (((a)^(b)) & (((a) > (b)) - 1))) +#define CV_SWAP(a,b,t) ((t) = (a), (a) = (b), (b) = (t)) +#define CV_CMP(a,b) (((a) > (b)) - ((a) < (b))) +#define CV_SIGN(a) CV_CMP((a),0) + +///////////////////////////////////////// Enum operators /////////////////////////////////////// + +/** + +Provides compatibility operators for both classical and C++11 enum classes, +as well as exposing the C++11 enum class members for backwards compatibility + +@code + // Provides operators required for flag enums + CV_ENUM_FLAGS(AccessFlag) + + // Exposes the listed members of the enum class AccessFlag to the current namespace + CV_ENUM_CLASS_EXPOSE(AccessFlag, ACCESS_READ [, ACCESS_WRITE [, ...] ]); +@endcode +*/ + +#define __CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST) \ +static const EnumType MEMBER_CONST = EnumType::MEMBER_CONST; \ + +#define __CV_ENUM_CLASS_EXPOSE_2(EnumType, MEMBER_CONST, ...) \ +__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ +__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_1(EnumType, __VA_ARGS__)); \ + +#define __CV_ENUM_CLASS_EXPOSE_3(EnumType, MEMBER_CONST, ...) \ +__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ +__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_2(EnumType, __VA_ARGS__)); \ + +#define __CV_ENUM_CLASS_EXPOSE_4(EnumType, MEMBER_CONST, ...) \ +__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ +__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_3(EnumType, __VA_ARGS__)); \ + +#define __CV_ENUM_CLASS_EXPOSE_5(EnumType, MEMBER_CONST, ...) \ +__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ +__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_4(EnumType, __VA_ARGS__)); \ + +#define __CV_ENUM_CLASS_EXPOSE_6(EnumType, MEMBER_CONST, ...) \ +__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ +__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_5(EnumType, __VA_ARGS__)); \ + +#define __CV_ENUM_CLASS_EXPOSE_7(EnumType, MEMBER_CONST, ...) \ +__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ +__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_6(EnumType, __VA_ARGS__)); \ + +#define __CV_ENUM_CLASS_EXPOSE_8(EnumType, MEMBER_CONST, ...) \ +__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ +__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_7(EnumType, __VA_ARGS__)); \ + +#define __CV_ENUM_CLASS_EXPOSE_9(EnumType, MEMBER_CONST, ...) \ +__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ +__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_8(EnumType, __VA_ARGS__)); \ + +#define __CV_ENUM_FLAGS_LOGICAL_NOT(EnumType) \ +static inline bool operator!(const EnumType& val) \ +{ \ + typedef std::underlying_type::type UnderlyingType; \ + return !static_cast(val); \ +} \ + +#define __CV_ENUM_FLAGS_LOGICAL_NOT_EQ(Arg1Type, Arg2Type) \ +static inline bool operator!=(const Arg1Type& a, const Arg2Type& b) \ +{ \ + return static_cast(a) != static_cast(b); \ +} \ + +#define __CV_ENUM_FLAGS_LOGICAL_EQ(Arg1Type, Arg2Type) \ +static inline bool operator==(const Arg1Type& a, const Arg2Type& b) \ +{ \ + return static_cast(a) == static_cast(b); \ +} \ + +#define __CV_ENUM_FLAGS_BITWISE_NOT(EnumType) \ +static inline EnumType operator~(const EnumType& val) \ +{ \ + typedef std::underlying_type::type UnderlyingType; \ + return static_cast(~static_cast(val)); \ +} \ + +#define __CV_ENUM_FLAGS_BITWISE_OR(EnumType, Arg1Type, Arg2Type) \ +static inline EnumType operator|(const Arg1Type& a, const Arg2Type& b) \ +{ \ + typedef std::underlying_type::type UnderlyingType; \ + return static_cast(static_cast(a) | static_cast(b)); \ +} \ + +#define __CV_ENUM_FLAGS_BITWISE_AND(EnumType, Arg1Type, Arg2Type) \ +static inline EnumType operator&(const Arg1Type& a, const Arg2Type& b) \ +{ \ + typedef std::underlying_type::type UnderlyingType; \ + return static_cast(static_cast(a) & static_cast(b)); \ +} \ + +#define __CV_ENUM_FLAGS_BITWISE_XOR(EnumType, Arg1Type, Arg2Type) \ +static inline EnumType operator^(const Arg1Type& a, const Arg2Type& b) \ +{ \ + typedef std::underlying_type::type UnderlyingType; \ + return static_cast(static_cast(a) ^ static_cast(b)); \ +} \ + +#define __CV_ENUM_FLAGS_BITWISE_OR_EQ(EnumType, Arg1Type) \ +static inline EnumType& operator|=(EnumType& _this, const Arg1Type& val) \ +{ \ + _this = static_cast(static_cast(_this) | static_cast(val)); \ + return _this; \ +} \ + +#define __CV_ENUM_FLAGS_BITWISE_AND_EQ(EnumType, Arg1Type) \ +static inline EnumType& operator&=(EnumType& _this, const Arg1Type& val) \ +{ \ + _this = static_cast(static_cast(_this) & static_cast(val)); \ + return _this; \ +} \ + +#define __CV_ENUM_FLAGS_BITWISE_XOR_EQ(EnumType, Arg1Type) \ +static inline EnumType& operator^=(EnumType& _this, const Arg1Type& val) \ +{ \ + _this = static_cast(static_cast(_this) ^ static_cast(val)); \ + return _this; \ +} \ + +#define CV_ENUM_CLASS_EXPOSE(EnumType, ...) \ +__CV_EXPAND(__CV_CAT(__CV_ENUM_CLASS_EXPOSE_, __CV_VA_NUM_ARGS(__VA_ARGS__))(EnumType, __VA_ARGS__)); \ + +#define CV_ENUM_FLAGS(EnumType) \ +__CV_ENUM_FLAGS_LOGICAL_NOT (EnumType) \ +__CV_ENUM_FLAGS_LOGICAL_EQ (EnumType, int) \ +__CV_ENUM_FLAGS_LOGICAL_NOT_EQ (EnumType, int) \ + \ +__CV_ENUM_FLAGS_BITWISE_NOT (EnumType) \ +__CV_ENUM_FLAGS_BITWISE_OR (EnumType, EnumType, EnumType) \ +__CV_ENUM_FLAGS_BITWISE_AND (EnumType, EnumType, EnumType) \ +__CV_ENUM_FLAGS_BITWISE_XOR (EnumType, EnumType, EnumType) \ + \ +__CV_ENUM_FLAGS_BITWISE_OR_EQ (EnumType, EnumType) \ +__CV_ENUM_FLAGS_BITWISE_AND_EQ (EnumType, EnumType) \ +__CV_ENUM_FLAGS_BITWISE_XOR_EQ (EnumType, EnumType) \ + +/****************************************************************************************\ +* static analysys * +\****************************************************************************************/ + +// In practice, some macro are not processed correctly (noreturn is not detected). +// We need to use simplified definition for them. +#ifndef CV_STATIC_ANALYSIS +# if defined(__KLOCWORK__) || defined(__clang_analyzer__) || defined(__COVERITY__) +# define CV_STATIC_ANALYSIS 1 +# endif +#else +# if defined(CV_STATIC_ANALYSIS) && !(__CV_CAT(1, CV_STATIC_ANALYSIS) == 1) // defined and not empty +# if 0 == CV_STATIC_ANALYSIS +# undef CV_STATIC_ANALYSIS +# endif +# endif +#endif + +/****************************************************************************************\ +* Thread sanitizer * +\****************************************************************************************/ +#ifndef CV_THREAD_SANITIZER +# if defined(__has_feature) +# if __has_feature(thread_sanitizer) +# define CV_THREAD_SANITIZER +# endif +# endif +#endif + +/****************************************************************************************\ +* exchange-add operation for atomic operations on reference counters * +\****************************************************************************************/ + +#ifdef CV_XADD + // allow to use user-defined macro +#elif defined __GNUC__ || defined __clang__ +# if defined __clang__ && __clang_major__ >= 3 && !defined __ANDROID__ && !defined __EMSCRIPTEN__ && !defined(__CUDACC__) && !defined __INTEL_COMPILER +# ifdef __ATOMIC_ACQ_REL +# define CV_XADD(addr, delta) __c11_atomic_fetch_add((_Atomic(int)*)(addr), delta, __ATOMIC_ACQ_REL) +# else +# define CV_XADD(addr, delta) __atomic_fetch_add((_Atomic(int)*)(addr), delta, 4) +# endif +# else +# if defined __ATOMIC_ACQ_REL && !defined __clang__ + // version for gcc >= 4.7 +# define CV_XADD(addr, delta) (int)__atomic_fetch_add((unsigned*)(addr), (unsigned)(delta), __ATOMIC_ACQ_REL) +# else +# define CV_XADD(addr, delta) (int)__sync_fetch_and_add((unsigned*)(addr), (unsigned)(delta)) +# endif +# endif +#elif defined _MSC_VER && !defined RC_INVOKED +# include +# define CV_XADD(addr, delta) (int)_InterlockedExchangeAdd((long volatile*)addr, delta) +#else + #ifdef OPENCV_FORCE_UNSAFE_XADD + CV_INLINE int CV_XADD(int* addr, int delta) { int tmp = *addr; *addr += delta; return tmp; } + #else + #error "OpenCV: can't define safe CV_XADD macro for current platform (unsupported). Define CV_XADD macro through custom port header (see OPENCV_INCLUDE_PORT_FILE)" + #endif +#endif + + +/****************************************************************************************\ +* CV_NORETURN attribute * +\****************************************************************************************/ + +#ifndef CV_NORETURN +# if defined(__GNUC__) +# define CV_NORETURN __attribute__((__noreturn__)) +# elif defined(_MSC_VER) && (_MSC_VER >= 1300) +# define CV_NORETURN __declspec(noreturn) +# else +# define CV_NORETURN /* nothing by default */ +# endif +#endif + +/****************************************************************************************\ +* CV_NODISCARD_STD attribute (C++17) * +* encourages the compiler to issue a warning if the return value is discarded * +\****************************************************************************************/ +#ifndef CV_NODISCARD_STD +# ifndef __has_cpp_attribute +// workaround preprocessor non-compliance https://reviews.llvm.org/D57851 +# define __has_cpp_attribute(__x) 0 +# endif +# if __has_cpp_attribute(nodiscard) +# if defined(__NVCC__) && __CUDACC_VER_MAJOR__ < 12 +# define CV_NODISCARD_STD +# else +# define CV_NODISCARD_STD [[nodiscard]] +# endif +# elif __cplusplus >= 201703L +// available when compiler is C++17 compliant +# define CV_NODISCARD_STD [[nodiscard]] +# elif defined(__INTEL_COMPILER) + // see above, available when C++17 is enabled +# elif defined(_MSC_VER) && _MSC_VER >= 1911 && _MSVC_LANG >= 201703L +// available with VS2017 v15.3+ with /std:c++17 or higher; works on functions and classes +# define CV_NODISCARD_STD [[nodiscard]] +# elif defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 700) && (__cplusplus >= 201103L) +// available with GCC 7.0+; works on functions, works or silently fails on classes +# define CV_NODISCARD_STD [[nodiscard]] +# elif defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 408) && (__cplusplus >= 201103L) +// available with GCC 4.8+ but it usually does nothing and can fail noisily -- therefore not used +// define CV_NODISCARD_STD [[gnu::warn_unused_result]] +# endif +#endif +#ifndef CV_NODISCARD_STD +# define CV_NODISCARD_STD /* nothing by default */ +#endif + + +/****************************************************************************************\ +* C++ 11 * +\****************************************************************************************/ +#ifdef __cplusplus +// MSVC was stuck at __cplusplus == 199711L for a long time, even where it supports C++11, +// so check _MSC_VER instead. See: +// +# if defined(_MSC_VER) +# if _MSC_VER < 1800 +# error "OpenCV 4.x+ requires enabled C++11 support" +# endif +# elif __cplusplus < 201103L +# error "OpenCV 4.x+ requires enabled C++11 support" +# endif +#endif + +#ifndef CV_CXX11 +# define CV_CXX11 1 +#endif + +#ifndef CV_OVERRIDE +# define CV_OVERRIDE override +#endif + +#ifndef CV_FINAL +# define CV_FINAL final +#endif + +#ifndef CV_NOEXCEPT +# define CV_NOEXCEPT noexcept +#endif + +#ifndef CV_CONSTEXPR +# define CV_CONSTEXPR constexpr +#endif + +// Integer types portability +#ifdef __cplusplus +#include +namespace cv { +using std::int8_t; +using std::uint8_t; +using std::int16_t; +using std::uint16_t; +using std::int32_t; +using std::uint32_t; +using std::int64_t; +using std::uint64_t; +} +#else // pure C +#include +#endif + +#ifdef __cplusplus +namespace cv +{ + +class hfloat +{ +public: +#if CV_FP16_TYPE + + hfloat() : h(0) {} + explicit hfloat(float x) { h = (__fp16)x; } + operator float() const { return (float)h; } +protected: + __fp16 h; + +#else + hfloat() : w(0) {} + explicit hfloat(float x) + { + #if CV_FP16 && CV_AVX2 + __m128 v = _mm_load_ss(&x); + w = (ushort)_mm_cvtsi128_si32(_mm_cvtps_ph(v, 0)); + #else + Cv32suf in; + in.f = x; + unsigned sign = in.u & 0x80000000; + in.u ^= sign; + + if( in.u >= 0x47800000 ) + w = (ushort)(in.u > 0x7f800000 ? 0x7e00 : 0x7c00); + else + { + if (in.u < 0x38800000) + { + in.f += 0.5f; + w = (ushort)(in.u - 0x3f000000); + } + else + { + unsigned t = in.u + 0xc8000fff; + w = (ushort)((t + ((in.u >> 13) & 1)) >> 13); + } + } + + w = (ushort)(w | (sign >> 16)); + #endif + } + + operator float() const + { + #if CV_FP16 && CV_AVX2 + float f; + _mm_store_ss(&f, _mm_cvtph_ps(_mm_cvtsi32_si128(w))); + return f; + #else + Cv32suf out; + + unsigned t = ((w & 0x7fff) << 13) + 0x38000000; + unsigned sign = (w & 0x8000) << 16; + unsigned e = w & 0x7c00; + + out.u = t + (1 << 23); + out.u = (e >= 0x7c00 ? t + 0x38000000 : + e == 0 ? (static_cast(out.f -= 6.103515625e-05f), out.u) : t) | sign; + return out.f; + #endif + } + +protected: + ushort w; + +#endif +}; + +inline hfloat hfloatFromBits(ushort w) { +#if CV_FP16_TYPE + Cv16suf u; + u.u = w; + hfloat res(float(u.h)); + return res; +#else + Cv32suf out; + + unsigned t = ((w & 0x7fff) << 13) + 0x38000000; + unsigned sign = (w & 0x8000) << 16; + unsigned e = w & 0x7c00; + + out.u = t + (1 << 23); + out.u = (e >= 0x7c00 ? t + 0x38000000 : + e == 0 ? (static_cast(out.f -= 6.103515625e-05f), out.u) : t) | sign; + hfloat res(out.f); + return res; +#endif +} + +#if !defined(__OPENCV_BUILD) && !(defined __STDCPP_FLOAT16_T__) && !(defined __ARM_NEON) +typedef hfloat float16_t; +#endif + +} +#endif + +/** @brief Constructs the 'fourcc' code, used in video codecs and many other places. + Simply call it with 4 chars like `CV_FOURCC('I', 'Y', 'U', 'V')` +*/ +CV_INLINE int CV_FOURCC(char c1, char c2, char c3, char c4) +{ + return (c1 & 255) + ((c2 & 255) << 8) + ((c3 & 255) << 16) + ((c4 & 255) << 24); +} + +//! Macro to construct the fourcc code of the codec. Same as CV_FOURCC() +#define CV_FOURCC_MACRO(c1, c2, c3, c4) (((c1) & 255) + (((c2) & 255) << 8) + (((c3) & 255) << 16) + (((c4) & 255) << 24)) + +//! @} + +#ifndef __cplusplus +#include "opencv2/core/fast_math.hpp" // define cvRound(double) +#endif + +#endif // OPENCV_CORE_CVDEF_H diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cvstd.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cvstd.hpp index d216d267ef..1946f2521f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cvstd.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cvstd.hpp @@ -1,189 +1,189 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CORE_CVSTD_HPP -#define OPENCV_CORE_CVSTD_HPP - -#ifndef __cplusplus -# error cvstd.hpp header must be compiled as C++ -#endif - -#include "opencv2/core/cvdef.h" -#include -#include -#include - -#include - -// import useful primitives from stl -# include -# include -# include //for abs(int) -# include - -namespace cv -{ - static inline uchar abs(uchar a) { return a; } - static inline ushort abs(ushort a) { return a; } - static inline unsigned abs(unsigned a) { return a; } - static inline uint64 abs(uint64 a) { return a; } - - using std::min; - using std::max; - using std::abs; - using std::swap; - using std::sqrt; - using std::exp; - using std::pow; - using std::log; -} - -#include "cvstd_wrapper.hpp" - -namespace cv { - -//! @addtogroup core_utils -//! @{ - -//////////////////////////// memory management functions //////////////////////////// - -/** @brief Allocates an aligned memory buffer. - -The function allocates the buffer of the specified size and returns it. When the buffer size is 16 -bytes or more, the returned buffer is aligned to 16 bytes. -@param bufSize Allocated buffer size. - */ -CV_EXPORTS void* fastMalloc(size_t bufSize); - -/** @brief Deallocates a memory buffer. - -The function deallocates the buffer allocated with fastMalloc . If NULL pointer is passed, the -function does nothing. C version of the function clears the pointer *pptr* to avoid problems with -double memory deallocation. -@param ptr Pointer to the allocated buffer. - */ -CV_EXPORTS void fastFree(void* ptr); - -/*! - The STL-compliant memory Allocator based on cv::fastMalloc() and cv::fastFree() -*/ -template class Allocator -{ -public: - typedef _Tp value_type; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef size_t size_type; - typedef ptrdiff_t difference_type; - template class rebind { typedef Allocator other; }; - - explicit Allocator() {} - ~Allocator() {} - explicit Allocator(Allocator const&) {} - template - explicit Allocator(Allocator const&) {} - - // address - pointer address(reference r) { return &r; } - const_pointer address(const_reference r) { return &r; } - - pointer allocate(size_type count, const void* =0) { return reinterpret_cast(fastMalloc(count * sizeof (_Tp))); } - void deallocate(pointer p, size_type) { fastFree(p); } - - void construct(pointer p, const _Tp& v) { new(static_cast(p)) _Tp(v); } - void destroy(pointer p) { p->~_Tp(); } - - size_type max_size() const { return cv::max(static_cast<_Tp>(-1)/sizeof(_Tp), 1); } -}; - -//! @} core_utils - - -//! @addtogroup core_basic -//! @{ - -//////////////////////////////// string class //////////////////////////////// - -class CV_EXPORTS FileNode; //for string constructor from FileNode - -typedef std::string String; - -#ifndef OPENCV_DISABLE_STRING_LOWER_UPPER_CONVERSIONS - -//! @cond IGNORED -namespace details { -// std::tolower is int->int -static inline char char_tolower(char ch) -{ - return (char)std::tolower((int)ch); -} -// std::toupper is int->int -static inline char char_toupper(char ch) -{ - return (char)std::toupper((int)ch); -} -} // namespace details -//! @endcond - -static inline std::string toLowerCase(const std::string& str) -{ - std::string result(str); - std::transform(result.begin(), result.end(), result.begin(), details::char_tolower); - return result; -} - -static inline std::string toUpperCase(const std::string& str) -{ - std::string result(str); - std::transform(result.begin(), result.end(), result.begin(), details::char_toupper); - return result; -} - -#endif // OPENCV_DISABLE_STRING_LOWER_UPPER_CONVERSIONS - -//! @} core_basic -} // cv - -#endif //OPENCV_CORE_CVSTD_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CORE_CVSTD_HPP +#define OPENCV_CORE_CVSTD_HPP + +#ifndef __cplusplus +# error cvstd.hpp header must be compiled as C++ +#endif + +#include "opencv2/core/cvdef.h" +#include +#include +#include + +#include + +// import useful primitives from stl +# include +# include +# include //for abs(int) +# include + +namespace cv +{ + static inline uchar abs(uchar a) { return a; } + static inline ushort abs(ushort a) { return a; } + static inline unsigned abs(unsigned a) { return a; } + static inline uint64 abs(uint64 a) { return a; } + + using std::min; + using std::max; + using std::abs; + using std::swap; + using std::sqrt; + using std::exp; + using std::pow; + using std::log; +} + +#include "cvstd_wrapper.hpp" + +namespace cv { + +//! @addtogroup core_utils +//! @{ + +//////////////////////////// memory management functions //////////////////////////// + +/** @brief Allocates an aligned memory buffer. + +The function allocates the buffer of the specified size and returns it. When the buffer size is 16 +bytes or more, the returned buffer is aligned to 16 bytes. +@param bufSize Allocated buffer size. + */ +CV_EXPORTS void* fastMalloc(size_t bufSize); + +/** @brief Deallocates a memory buffer. + +The function deallocates the buffer allocated with fastMalloc . If NULL pointer is passed, the +function does nothing. C version of the function clears the pointer *pptr* to avoid problems with +double memory deallocation. +@param ptr Pointer to the allocated buffer. + */ +CV_EXPORTS void fastFree(void* ptr); + +/*! + The STL-compliant memory Allocator based on cv::fastMalloc() and cv::fastFree() +*/ +template class Allocator +{ +public: + typedef _Tp value_type; + typedef value_type* pointer; + typedef const value_type* const_pointer; + typedef value_type& reference; + typedef const value_type& const_reference; + typedef size_t size_type; + typedef ptrdiff_t difference_type; + template class rebind { typedef Allocator other; }; + + explicit Allocator() {} + ~Allocator() {} + explicit Allocator(Allocator const&) {} + template + explicit Allocator(Allocator const&) {} + + // address + pointer address(reference r) { return &r; } + const_pointer address(const_reference r) { return &r; } + + pointer allocate(size_type count, const void* =0) { return reinterpret_cast(fastMalloc(count * sizeof (_Tp))); } + void deallocate(pointer p, size_type) { fastFree(p); } + + void construct(pointer p, const _Tp& v) { new(static_cast(p)) _Tp(v); } + void destroy(pointer p) { p->~_Tp(); } + + size_type max_size() const { return cv::max(static_cast<_Tp>(-1)/sizeof(_Tp), 1); } +}; + +//! @} core_utils + + +//! @addtogroup core_basic +//! @{ + +//////////////////////////////// string class //////////////////////////////// + +class CV_EXPORTS FileNode; //for string constructor from FileNode + +typedef std::string String; + +#ifndef OPENCV_DISABLE_STRING_LOWER_UPPER_CONVERSIONS + +//! @cond IGNORED +namespace details { +// std::tolower is int->int +static inline char char_tolower(char ch) +{ + return (char)std::tolower((int)ch); +} +// std::toupper is int->int +static inline char char_toupper(char ch) +{ + return (char)std::toupper((int)ch); +} +} // namespace details +//! @endcond + +static inline std::string toLowerCase(const std::string& str) +{ + std::string result(str); + std::transform(result.begin(), result.end(), result.begin(), details::char_tolower); + return result; +} + +static inline std::string toUpperCase(const std::string& str) +{ + std::string result(str); + std::transform(result.begin(), result.end(), result.begin(), details::char_toupper); + return result; +} + +#endif // OPENCV_DISABLE_STRING_LOWER_UPPER_CONVERSIONS + +//! @} core_basic +} // cv + +#endif //OPENCV_CORE_CVSTD_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cvstd.inl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cvstd.inl.hpp index 37ad1e6906..42acfe09c7 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cvstd.inl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cvstd.inl.hpp @@ -1,197 +1,197 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CORE_CVSTDINL_HPP -#define OPENCV_CORE_CVSTDINL_HPP - -#include -#include -#include - -//! @cond IGNORED - -#ifdef _MSC_VER -#pragma warning( push ) -#pragma warning( disable: 4127 ) -#endif - -namespace cv -{ - -template class DataType< std::complex<_Tp> > -{ -public: - typedef std::complex<_Tp> value_type; - typedef value_type work_type; - typedef _Tp channel_type; - - enum { generic_type = 0, - depth = DataType::depth, - channels = 2, - fmt = DataType::fmt + ((channels - 1) << 8), - type = CV_MAKETYPE(depth, channels) }; - - typedef Vec vec_type; -}; - -static inline -std::ostream& operator << (std::ostream& out, Ptr fmtd) -{ - fmtd->reset(); - for(const char* str = fmtd->next(); str; str = fmtd->next()) - out << str; - return out; -} - -static inline -std::ostream& operator << (std::ostream& out, const Mat& mtx) -{ - return out << Formatter::get()->format(mtx); -} - -static inline -std::ostream& operator << (std::ostream& out, const UMat& m) -{ - return out << m.getMat(ACCESS_READ); -} - -template static inline -std::ostream& operator << (std::ostream& out, const Complex<_Tp>& c) -{ - return out << "(" << c.re << "," << c.im << ")"; -} - -template static inline -std::ostream& operator << (std::ostream& out, const std::vector >& vec) -{ - return out << Formatter::get()->format(Mat(vec)); -} - - -template static inline -std::ostream& operator << (std::ostream& out, const std::vector >& vec) -{ - return out << Formatter::get()->format(Mat(vec)); -} - - -template static inline -std::ostream& operator << (std::ostream& out, const Matx<_Tp, m, n>& matx) -{ - return out << Formatter::get()->format(Mat(matx)); -} - -template static inline -std::ostream& operator << (std::ostream& out, const Point_<_Tp>& p) -{ - out << "[" << p.x << ", " << p.y << "]"; - return out; -} - -template static inline -std::ostream& operator << (std::ostream& out, const Point3_<_Tp>& p) -{ - out << "[" << p.x << ", " << p.y << ", " << p.z << "]"; - return out; -} - -template static inline -std::ostream& operator << (std::ostream& out, const Vec<_Tp, n>& vec) -{ - out << "["; - if (cv::traits::Depth<_Tp>::value <= CV_32S) - { - for (int i = 0; i < n - 1; ++i) { - out << (int)vec[i] << ", "; - } - out << (int)vec[n-1] << "]"; - } - else - { - for (int i = 0; i < n - 1; ++i) { - out << vec[i] << ", "; - } - out << vec[n-1] << "]"; - } - - return out; -} - -template static inline -std::ostream& operator << (std::ostream& out, const Size_<_Tp>& size) -{ - return out << "[" << size.width << " x " << size.height << "]"; -} - -template static inline -std::ostream& operator << (std::ostream& out, const Rect_<_Tp>& rect) -{ - return out << "[" << rect.width << " x " << rect.height << " from (" << rect.x << ", " << rect.y << ")]"; -} - -static inline std::ostream& operator << (std::ostream& out, const MatSize& msize) -{ - int i, dims = msize.dims(); - for( i = 0; i < dims; i++ ) - { - out << msize[i]; - if( i < dims-1 ) - out << " x "; - } - return out; -} - -static inline std::ostream &operator<< (std::ostream &s, cv::Range &r) -{ - return s << "[" << r.start << " : " << r.end << ")"; -} - -} // cv - -#ifdef _MSC_VER -#pragma warning( pop ) -#endif - -//! @endcond - -#endif // OPENCV_CORE_CVSTDINL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CORE_CVSTDINL_HPP +#define OPENCV_CORE_CVSTDINL_HPP + +#include +#include +#include + +//! @cond IGNORED + +#ifdef _MSC_VER +#pragma warning( push ) +#pragma warning( disable: 4127 ) +#endif + +namespace cv +{ + +template class DataType< std::complex<_Tp> > +{ +public: + typedef std::complex<_Tp> value_type; + typedef value_type work_type; + typedef _Tp channel_type; + + enum { generic_type = 0, + depth = DataType::depth, + channels = 2, + fmt = DataType::fmt + ((channels - 1) << 8), + type = CV_MAKETYPE(depth, channels) }; + + typedef Vec vec_type; +}; + +static inline +std::ostream& operator << (std::ostream& out, Ptr fmtd) +{ + fmtd->reset(); + for(const char* str = fmtd->next(); str; str = fmtd->next()) + out << str; + return out; +} + +static inline +std::ostream& operator << (std::ostream& out, const Mat& mtx) +{ + return out << Formatter::get()->format(mtx); +} + +static inline +std::ostream& operator << (std::ostream& out, const UMat& m) +{ + return out << m.getMat(ACCESS_READ); +} + +template static inline +std::ostream& operator << (std::ostream& out, const Complex<_Tp>& c) +{ + return out << "(" << c.re << "," << c.im << ")"; +} + +template static inline +std::ostream& operator << (std::ostream& out, const std::vector >& vec) +{ + return out << Formatter::get()->format(Mat(vec)); +} + + +template static inline +std::ostream& operator << (std::ostream& out, const std::vector >& vec) +{ + return out << Formatter::get()->format(Mat(vec)); +} + + +template static inline +std::ostream& operator << (std::ostream& out, const Matx<_Tp, m, n>& matx) +{ + return out << Formatter::get()->format(Mat(matx)); +} + +template static inline +std::ostream& operator << (std::ostream& out, const Point_<_Tp>& p) +{ + out << "[" << p.x << ", " << p.y << "]"; + return out; +} + +template static inline +std::ostream& operator << (std::ostream& out, const Point3_<_Tp>& p) +{ + out << "[" << p.x << ", " << p.y << ", " << p.z << "]"; + return out; +} + +template static inline +std::ostream& operator << (std::ostream& out, const Vec<_Tp, n>& vec) +{ + out << "["; + if (cv::traits::Depth<_Tp>::value <= CV_32S) + { + for (int i = 0; i < n - 1; ++i) { + out << (int)vec[i] << ", "; + } + out << (int)vec[n-1] << "]"; + } + else + { + for (int i = 0; i < n - 1; ++i) { + out << vec[i] << ", "; + } + out << vec[n-1] << "]"; + } + + return out; +} + +template static inline +std::ostream& operator << (std::ostream& out, const Size_<_Tp>& size) +{ + return out << "[" << size.width << " x " << size.height << "]"; +} + +template static inline +std::ostream& operator << (std::ostream& out, const Rect_<_Tp>& rect) +{ + return out << "[" << rect.width << " x " << rect.height << " from (" << rect.x << ", " << rect.y << ")]"; +} + +static inline std::ostream& operator << (std::ostream& out, const MatSize& msize) +{ + int i, dims = msize.dims(); + for( i = 0; i < dims; i++ ) + { + out << msize[i]; + if( i < dims-1 ) + out << " x "; + } + return out; +} + +static inline std::ostream &operator<< (std::ostream &s, cv::Range &r) +{ + return s << "[" << r.start << " : " << r.end << ")"; +} + +} // cv + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +//! @endcond + +#endif // OPENCV_CORE_CVSTDINL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cvstd_wrapper.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cvstd_wrapper.hpp index 25e0041f28..7770d54a83 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cvstd_wrapper.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cvstd_wrapper.hpp @@ -1,154 +1,154 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_CVSTD_WRAPPER_HPP -#define OPENCV_CORE_CVSTD_WRAPPER_HPP - -#include "opencv2/core/cvdef.h" - -#include -#include // std::shared_ptr -#include // std::enable_if - -namespace cv { - -using std::nullptr_t; - -//! @addtogroup core_basic -//! @{ - -#ifdef CV_DOXYGEN - -template using Ptr = std::shared_ptr<_Tp>; // In ideal world it should look like this, but we need some compatibility workarounds below - -template static inline -Ptr<_Tp> makePtr(const A1&... a1) { return std::make_shared<_Tp>(a1...); } - -#else // cv::Ptr with compatibility workarounds - -// It should be defined for C-API types only. -// C++ types should use regular "delete" operator. -template struct DefaultDeleter; -#if 0 -{ - void operator()(Y* p) const; -}; -#endif - -namespace sfinae { -template -struct has_parenthesis_operator -{ -private: - template - static CV_CONSTEXPR std::true_type has_parenthesis_operator_check(typename std::is_same().operator()(std::declval()...))>::type, Ret>::type*); - - template static CV_CONSTEXPR std::false_type has_parenthesis_operator_check(...); - - typedef decltype(has_parenthesis_operator_check(0)) type; - -public: -#if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900/*MSVS 2015*/) - static CV_CONSTEXPR bool value = type::value; -#else - // support MSVS 2013 - static const int value = type::value; -#endif -}; -} // namespace sfinae - -template -struct has_custom_delete - : public std::false_type {}; - -// Force has_custom_delete to std::false_type when NVCC is compiling CUDA source files -#ifndef __CUDACC__ -template -struct has_custom_delete, void, T*>::value >::type > - : public std::true_type {}; -#endif - -template -struct Ptr : public std::shared_ptr -{ -#if 0 - using std::shared_ptr::shared_ptr; // GCC 5.x can't handle this -#else - inline Ptr() CV_NOEXCEPT : std::shared_ptr() {} - inline Ptr(nullptr_t) CV_NOEXCEPT : std::shared_ptr(nullptr) {} - template inline Ptr(Y* p, D d) : std::shared_ptr(p, d) {} - template inline Ptr(nullptr_t, D d) : std::shared_ptr(nullptr, d) {} - - template inline Ptr(const Ptr& r, T* ptr) CV_NOEXCEPT : std::shared_ptr(r, ptr) {} - - inline Ptr(const Ptr& o) CV_NOEXCEPT : std::shared_ptr(o) {} - inline Ptr(Ptr&& o) CV_NOEXCEPT : std::shared_ptr(std::move(o)) {} - - template inline Ptr(const Ptr& o) CV_NOEXCEPT : std::shared_ptr(o) {} - template inline Ptr(Ptr&& o) CV_NOEXCEPT : std::shared_ptr(std::move(o)) {} -#endif - inline Ptr(const std::shared_ptr& o) CV_NOEXCEPT : std::shared_ptr(o) {} - inline Ptr(std::shared_ptr&& o) CV_NOEXCEPT : std::shared_ptr(std::move(o)) {} - - // Overload with custom DefaultDeleter: Ptr(...) - template - inline Ptr(const std::true_type&, Y* ptr) : std::shared_ptr(ptr, DefaultDeleter()) {} - - // Overload without custom deleter: Ptr(...); - template - inline Ptr(const std::false_type&, Y* ptr) : std::shared_ptr(ptr) {} - - template - inline Ptr(Y* ptr) : Ptr(has_custom_delete(), ptr) {} - - // Overload with custom DefaultDeleter: Ptr(...) - template - inline void reset(const std::true_type&, Y* ptr) { std::shared_ptr::reset(ptr, DefaultDeleter()); } - - // Overload without custom deleter: Ptr(...); - template - inline void reset(const std::false_type&, Y* ptr) { std::shared_ptr::reset(ptr); } - - template - inline void reset(Y* ptr) { Ptr::reset(has_custom_delete(), ptr); } - - template - void reset(Y* ptr, Deleter d) { std::shared_ptr::reset(ptr, d); } - - void reset() CV_NOEXCEPT { std::shared_ptr::reset(); } - - Ptr& operator=(const Ptr& o) { std::shared_ptr::operator =(o); return *this; } - template inline Ptr& operator=(const Ptr& o) { std::shared_ptr::operator =(o); return *this; } - - T* operator->() const CV_NOEXCEPT { return std::shared_ptr::get();} - typename std::add_lvalue_reference::type operator*() const CV_NOEXCEPT { return *std::shared_ptr::get(); } - - // OpenCV 3.x methods (not a part of standard C++ library) - inline void release() { std::shared_ptr::reset(); } - inline operator T* () const { return std::shared_ptr::get(); } - inline bool empty() const { return std::shared_ptr::get() == nullptr; } - - template inline - Ptr staticCast() const CV_NOEXCEPT { return std::static_pointer_cast(*this); } - - template inline - Ptr constCast() const CV_NOEXCEPT { return std::const_pointer_cast(*this); } - - template inline - Ptr dynamicCast() const CV_NOEXCEPT { return std::dynamic_pointer_cast(*this); } -}; - -template static inline -Ptr<_Tp> makePtr(const A1&... a1) -{ - static_assert( !has_custom_delete<_Tp>::value, "Can't use this makePtr with custom DefaultDeleter"); - return (Ptr<_Tp>)std::make_shared<_Tp>(a1...); -} - -#endif // CV_DOXYGEN - -//! @} core_basic -} // cv - -#endif //OPENCV_CORE_CVSTD_WRAPPER_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_CVSTD_WRAPPER_HPP +#define OPENCV_CORE_CVSTD_WRAPPER_HPP + +#include "opencv2/core/cvdef.h" + +#include +#include // std::shared_ptr +#include // std::enable_if + +namespace cv { + +using std::nullptr_t; + +//! @addtogroup core_basic +//! @{ + +#ifdef CV_DOXYGEN + +template using Ptr = std::shared_ptr<_Tp>; // In ideal world it should look like this, but we need some compatibility workarounds below + +template static inline +Ptr<_Tp> makePtr(const A1&... a1) { return std::make_shared<_Tp>(a1...); } + +#else // cv::Ptr with compatibility workarounds + +// It should be defined for C-API types only. +// C++ types should use regular "delete" operator. +template struct DefaultDeleter; +#if 0 +{ + void operator()(Y* p) const; +}; +#endif + +namespace sfinae { +template +struct has_parenthesis_operator +{ +private: + template + static CV_CONSTEXPR std::true_type has_parenthesis_operator_check(typename std::is_same().operator()(std::declval()...))>::type, Ret>::type*); + + template static CV_CONSTEXPR std::false_type has_parenthesis_operator_check(...); + + typedef decltype(has_parenthesis_operator_check(0)) type; + +public: +#if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900/*MSVS 2015*/) + static CV_CONSTEXPR bool value = type::value; +#else + // support MSVS 2013 + static const int value = type::value; +#endif +}; +} // namespace sfinae + +template +struct has_custom_delete + : public std::false_type {}; + +// Force has_custom_delete to std::false_type when NVCC is compiling CUDA source files +#ifndef __CUDACC__ +template +struct has_custom_delete, void, T*>::value >::type > + : public std::true_type {}; +#endif + +template +struct Ptr : public std::shared_ptr +{ +#if 0 + using std::shared_ptr::shared_ptr; // GCC 5.x can't handle this +#else + inline Ptr() CV_NOEXCEPT : std::shared_ptr() {} + inline Ptr(nullptr_t) CV_NOEXCEPT : std::shared_ptr(nullptr) {} + template inline Ptr(Y* p, D d) : std::shared_ptr(p, d) {} + template inline Ptr(nullptr_t, D d) : std::shared_ptr(nullptr, d) {} + + template inline Ptr(const Ptr& r, T* ptr) CV_NOEXCEPT : std::shared_ptr(r, ptr) {} + + inline Ptr(const Ptr& o) CV_NOEXCEPT : std::shared_ptr(o) {} + inline Ptr(Ptr&& o) CV_NOEXCEPT : std::shared_ptr(std::move(o)) {} + + template inline Ptr(const Ptr& o) CV_NOEXCEPT : std::shared_ptr(o) {} + template inline Ptr(Ptr&& o) CV_NOEXCEPT : std::shared_ptr(std::move(o)) {} +#endif + inline Ptr(const std::shared_ptr& o) CV_NOEXCEPT : std::shared_ptr(o) {} + inline Ptr(std::shared_ptr&& o) CV_NOEXCEPT : std::shared_ptr(std::move(o)) {} + + // Overload with custom DefaultDeleter: Ptr(...) + template + inline Ptr(const std::true_type&, Y* ptr) : std::shared_ptr(ptr, DefaultDeleter()) {} + + // Overload without custom deleter: Ptr(...); + template + inline Ptr(const std::false_type&, Y* ptr) : std::shared_ptr(ptr) {} + + template + inline Ptr(Y* ptr) : Ptr(has_custom_delete(), ptr) {} + + // Overload with custom DefaultDeleter: Ptr(...) + template + inline void reset(const std::true_type&, Y* ptr) { std::shared_ptr::reset(ptr, DefaultDeleter()); } + + // Overload without custom deleter: Ptr(...); + template + inline void reset(const std::false_type&, Y* ptr) { std::shared_ptr::reset(ptr); } + + template + inline void reset(Y* ptr) { Ptr::reset(has_custom_delete(), ptr); } + + template + void reset(Y* ptr, Deleter d) { std::shared_ptr::reset(ptr, d); } + + void reset() CV_NOEXCEPT { std::shared_ptr::reset(); } + + Ptr& operator=(const Ptr& o) { std::shared_ptr::operator =(o); return *this; } + template inline Ptr& operator=(const Ptr& o) { std::shared_ptr::operator =(o); return *this; } + + T* operator->() const CV_NOEXCEPT { return std::shared_ptr::get();} + typename std::add_lvalue_reference::type operator*() const CV_NOEXCEPT { return *std::shared_ptr::get(); } + + // OpenCV 3.x methods (not a part of standard C++ library) + inline void release() { std::shared_ptr::reset(); } + inline operator T* () const { return std::shared_ptr::get(); } + inline bool empty() const { return std::shared_ptr::get() == nullptr; } + + template inline + Ptr staticCast() const CV_NOEXCEPT { return std::static_pointer_cast(*this); } + + template inline + Ptr constCast() const CV_NOEXCEPT { return std::const_pointer_cast(*this); } + + template inline + Ptr dynamicCast() const CV_NOEXCEPT { return std::dynamic_pointer_cast(*this); } +}; + +template static inline +Ptr<_Tp> makePtr(const A1&... a1) +{ + static_assert( !has_custom_delete<_Tp>::value, "Can't use this makePtr with custom DefaultDeleter"); + return (Ptr<_Tp>)std::make_shared<_Tp>(a1...); +} + +#endif // CV_DOXYGEN + +//! @} core_basic +} // cv + +#endif //OPENCV_CORE_CVSTD_WRAPPER_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/detail/async_promise.hpp b/3rdParty/opencv-4.11.0/opencv2/core/detail/async_promise.hpp index c039ec046a..811a24324f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/detail/async_promise.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/detail/async_promise.hpp @@ -1,69 +1,69 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_ASYNC_PROMISE_HPP -#define OPENCV_CORE_ASYNC_PROMISE_HPP - -#include "../async.hpp" - -#include "exception_ptr.hpp" - -namespace cv { - -/** @addtogroup core_async -@{ -*/ - - -/** @brief Provides result of asynchronous operations - -*/ -class CV_EXPORTS AsyncPromise -{ -public: - ~AsyncPromise() CV_NOEXCEPT; - AsyncPromise() CV_NOEXCEPT; - explicit AsyncPromise(const AsyncPromise& o) CV_NOEXCEPT; - AsyncPromise& operator=(const AsyncPromise& o) CV_NOEXCEPT; - void release() CV_NOEXCEPT; - - /** Returns associated AsyncArray - @note Can be called once - */ - AsyncArray getArrayResult(); - - /** Stores asynchronous result. - @param[in] value result - */ - void setValue(InputArray value); - - // TODO "move" setters - -#if CV__EXCEPTION_PTR - /** Stores exception. - @param[in] exception exception to be raised in AsyncArray - */ - void setException(std::exception_ptr exception); -#endif - - /** Stores exception. - @param[in] exception exception to be raised in AsyncArray - */ - void setException(const cv::Exception& exception); - - explicit AsyncPromise(AsyncPromise&& o) { p = o.p; o.p = NULL; } - AsyncPromise& operator=(AsyncPromise&& o) CV_NOEXCEPT { std::swap(p, o.p); return *this; } - - - // PImpl - typedef struct AsyncArray::Impl Impl; friend struct AsyncArray::Impl; - inline void* _getImpl() const CV_NOEXCEPT { return p; } -protected: - Impl* p; -}; - - -//! @} -} // namespace -#endif // OPENCV_CORE_ASYNC_PROMISE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_ASYNC_PROMISE_HPP +#define OPENCV_CORE_ASYNC_PROMISE_HPP + +#include "../async.hpp" + +#include "exception_ptr.hpp" + +namespace cv { + +/** @addtogroup core_async +@{ +*/ + + +/** @brief Provides result of asynchronous operations + +*/ +class CV_EXPORTS AsyncPromise +{ +public: + ~AsyncPromise() CV_NOEXCEPT; + AsyncPromise() CV_NOEXCEPT; + explicit AsyncPromise(const AsyncPromise& o) CV_NOEXCEPT; + AsyncPromise& operator=(const AsyncPromise& o) CV_NOEXCEPT; + void release() CV_NOEXCEPT; + + /** Returns associated AsyncArray + @note Can be called once + */ + AsyncArray getArrayResult(); + + /** Stores asynchronous result. + @param[in] value result + */ + void setValue(InputArray value); + + // TODO "move" setters + +#if CV__EXCEPTION_PTR + /** Stores exception. + @param[in] exception exception to be raised in AsyncArray + */ + void setException(std::exception_ptr exception); +#endif + + /** Stores exception. + @param[in] exception exception to be raised in AsyncArray + */ + void setException(const cv::Exception& exception); + + explicit AsyncPromise(AsyncPromise&& o) { p = o.p; o.p = NULL; } + AsyncPromise& operator=(AsyncPromise&& o) CV_NOEXCEPT { std::swap(p, o.p); return *this; } + + + // PImpl + typedef struct AsyncArray::Impl Impl; friend struct AsyncArray::Impl; + inline void* _getImpl() const CV_NOEXCEPT { return p; } +protected: + Impl* p; +}; + + +//! @} +} // namespace +#endif // OPENCV_CORE_ASYNC_PROMISE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/detail/dispatch_helper.impl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/detail/dispatch_helper.impl.hpp index d6ec676922..230306f914 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/detail/dispatch_helper.impl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/detail/dispatch_helper.impl.hpp @@ -1,49 +1,49 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_DETAIL_DISPATCH_HELPER_IMPL_HPP -#define OPENCV_CORE_DETAIL_DISPATCH_HELPER_IMPL_HPP - -//! @cond IGNORED - -namespace cv { -namespace detail { - -template class Functor, typename... Args> -static inline void depthDispatch(const int depth, Args&&... args) -{ - switch (depth) - { - case CV_8U: - Functor{}(std::forward(args)...); - break; - case CV_8S: - Functor{}(std::forward(args)...); - break; - case CV_16U: - Functor{}(std::forward(args)...); - break; - case CV_16S: - Functor{}(std::forward(args)...); - break; - case CV_32S: - Functor{}(std::forward(args)...); - break; - case CV_32F: - Functor{}(std::forward(args)...); - break; - case CV_64F: - Functor{}(std::forward(args)...); - break; - case CV_16F: - default: - CV_Error(cv::Error::BadDepth, "Unsupported matrix type."); - }; -} - -}} - -//! @endcond - -#endif //OPENCV_CORE_DETAIL_DISPATCH_HELPER_IMPL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_DETAIL_DISPATCH_HELPER_IMPL_HPP +#define OPENCV_CORE_DETAIL_DISPATCH_HELPER_IMPL_HPP + +//! @cond IGNORED + +namespace cv { +namespace detail { + +template class Functor, typename... Args> +static inline void depthDispatch(const int depth, Args&&... args) +{ + switch (depth) + { + case CV_8U: + Functor{}(std::forward(args)...); + break; + case CV_8S: + Functor{}(std::forward(args)...); + break; + case CV_16U: + Functor{}(std::forward(args)...); + break; + case CV_16S: + Functor{}(std::forward(args)...); + break; + case CV_32S: + Functor{}(std::forward(args)...); + break; + case CV_32F: + Functor{}(std::forward(args)...); + break; + case CV_64F: + Functor{}(std::forward(args)...); + break; + case CV_16F: + default: + CV_Error(cv::Error::BadDepth, "Unsupported matrix type."); + }; +} + +}} + +//! @endcond + +#endif //OPENCV_CORE_DETAIL_DISPATCH_HELPER_IMPL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/detail/exception_ptr.hpp b/3rdParty/opencv-4.11.0/opencv2/core/detail/exception_ptr.hpp index a1a591e455..ed5c40f24f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/detail/exception_ptr.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/detail/exception_ptr.hpp @@ -1,21 +1,21 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_DETAILS_EXCEPTION_PTR_H -#define OPENCV_CORE_DETAILS_EXCEPTION_PTR_H - -#ifndef CV__EXCEPTION_PTR -# if defined(__ANDROID__) && defined(ATOMIC_INT_LOCK_FREE) && ATOMIC_INT_LOCK_FREE < 2 -# define CV__EXCEPTION_PTR 0 // Not supported, details: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58938 -# else -# define CV__EXCEPTION_PTR 1 -# endif -#endif -#ifndef CV__EXCEPTION_PTR -# define CV__EXCEPTION_PTR 0 -#elif CV__EXCEPTION_PTR -# include // std::exception_ptr -#endif - -#endif // OPENCV_CORE_DETAILS_EXCEPTION_PTR_H +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_DETAILS_EXCEPTION_PTR_H +#define OPENCV_CORE_DETAILS_EXCEPTION_PTR_H + +#ifndef CV__EXCEPTION_PTR +# if defined(__ANDROID__) && defined(ATOMIC_INT_LOCK_FREE) && ATOMIC_INT_LOCK_FREE < 2 +# define CV__EXCEPTION_PTR 0 // Not supported, details: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58938 +# else +# define CV__EXCEPTION_PTR 1 +# endif +#endif +#ifndef CV__EXCEPTION_PTR +# define CV__EXCEPTION_PTR 0 +#elif CV__EXCEPTION_PTR +# include // std::exception_ptr +#endif + +#endif // OPENCV_CORE_DETAILS_EXCEPTION_PTR_H diff --git a/3rdParty/opencv-4.11.0/opencv2/core/directx.hpp b/3rdParty/opencv-4.11.0/opencv2/core/directx.hpp index 056a85a1bc..431eb6e71f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/directx.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/directx.hpp @@ -1,184 +1,184 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 copyright holders 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. -// -//M*/ - -#ifndef OPENCV_CORE_DIRECTX_HPP -#define OPENCV_CORE_DIRECTX_HPP - -#include "mat.hpp" -#include "ocl.hpp" - -#if !defined(__d3d11_h__) -struct ID3D11Device; -struct ID3D11Texture2D; -#endif - -#if !defined(__d3d10_h__) -struct ID3D10Device; -struct ID3D10Texture2D; -#endif - -#if !defined(_D3D9_H_) -struct IDirect3DDevice9; -struct IDirect3DDevice9Ex; -struct IDirect3DSurface9; -#endif - - -namespace cv { namespace directx { - -namespace ocl { -using namespace cv::ocl; - -//! @addtogroup core_directx -// This section describes OpenCL and DirectX interoperability. -// -// To enable DirectX support, configure OpenCV using CMake with WITH_DIRECTX=ON . Note, DirectX is -// supported only on Windows. -// -// To use OpenCL functionality you should first initialize OpenCL context from DirectX resource. -// -//! @{ - -// TODO static functions in the Context class -//! @brief Creates OpenCL context from D3D11 device -// -//! @param pD3D11Device - pointer to D3D11 device -//! @return Returns reference to OpenCL Context -CV_EXPORTS Context& initializeContextFromD3D11Device(ID3D11Device* pD3D11Device); - -//! @brief Creates OpenCL context from D3D10 device -// -//! @param pD3D10Device - pointer to D3D10 device -//! @return Returns reference to OpenCL Context -CV_EXPORTS Context& initializeContextFromD3D10Device(ID3D10Device* pD3D10Device); - -//! @brief Creates OpenCL context from Direct3DDevice9Ex device -// -//! @param pDirect3DDevice9Ex - pointer to Direct3DDevice9Ex device -//! @return Returns reference to OpenCL Context -CV_EXPORTS Context& initializeContextFromDirect3DDevice9Ex(IDirect3DDevice9Ex* pDirect3DDevice9Ex); - -//! @brief Creates OpenCL context from Direct3DDevice9 device -// -//! @param pDirect3DDevice9 - pointer to Direct3Device9 device -//! @return Returns reference to OpenCL Context -CV_EXPORTS Context& initializeContextFromDirect3DDevice9(IDirect3DDevice9* pDirect3DDevice9); - -//! @} - -} // namespace cv::directx::ocl - -//! @addtogroup core_directx -//! @{ - -//! @brief Converts InputArray to ID3D11Texture2D. If destination texture format is DXGI_FORMAT_NV12 then -//! input UMat expected to be in BGR format and data will be downsampled and color-converted to NV12. -// -//! @note Note: Destination texture must be allocated by application. Function does memory copy from src to -//! pD3D11Texture2D -// -//! @param src - source InputArray -//! @param pD3D11Texture2D - destination D3D11 texture -CV_EXPORTS void convertToD3D11Texture2D(InputArray src, ID3D11Texture2D* pD3D11Texture2D); - -//! @brief Converts ID3D11Texture2D to OutputArray. If input texture format is DXGI_FORMAT_NV12 then -//! data will be upsampled and color-converted to BGR format. -// -//! @note Note: Destination matrix will be re-allocated if it has not enough memory to match texture size. -//! function does memory copy from pD3D11Texture2D to dst -// -//! @param pD3D11Texture2D - source D3D11 texture -//! @param dst - destination OutputArray -CV_EXPORTS void convertFromD3D11Texture2D(ID3D11Texture2D* pD3D11Texture2D, OutputArray dst); - -//! @brief Converts InputArray to ID3D10Texture2D -// -//! @note Note: function does memory copy from src to -//! pD3D10Texture2D -// -//! @param src - source InputArray -//! @param pD3D10Texture2D - destination D3D10 texture -CV_EXPORTS void convertToD3D10Texture2D(InputArray src, ID3D10Texture2D* pD3D10Texture2D); - -//! @brief Converts ID3D10Texture2D to OutputArray -// -//! @note Note: function does memory copy from pD3D10Texture2D -//! to dst -// -//! @param pD3D10Texture2D - source D3D10 texture -//! @param dst - destination OutputArray -CV_EXPORTS void convertFromD3D10Texture2D(ID3D10Texture2D* pD3D10Texture2D, OutputArray dst); - -//! @brief Converts InputArray to IDirect3DSurface9 -// -//! @note Note: function does memory copy from src to -//! pDirect3DSurface9 -// -//! @param src - source InputArray -//! @param pDirect3DSurface9 - destination D3D10 texture -//! @param surfaceSharedHandle - shared handle -CV_EXPORTS void convertToDirect3DSurface9(InputArray src, IDirect3DSurface9* pDirect3DSurface9, void* surfaceSharedHandle = NULL); - -//! @brief Converts IDirect3DSurface9 to OutputArray -// -//! @note Note: function does memory copy from pDirect3DSurface9 -//! to dst -// -//! @param pDirect3DSurface9 - source D3D10 texture -//! @param dst - destination OutputArray -//! @param surfaceSharedHandle - shared handle -CV_EXPORTS void convertFromDirect3DSurface9(IDirect3DSurface9* pDirect3DSurface9, OutputArray dst, void* surfaceSharedHandle = NULL); - -//! @brief Get OpenCV type from DirectX type -//! @param iDXGI_FORMAT - enum DXGI_FORMAT for D3D10/D3D11 -//! @return OpenCV type or -1 if there is no equivalent -CV_EXPORTS int getTypeFromDXGI_FORMAT(const int iDXGI_FORMAT); // enum DXGI_FORMAT for D3D10/D3D11 - -//! @brief Get OpenCV type from DirectX type -//! @param iD3DFORMAT - enum D3DTYPE for D3D9 -//! @return OpenCV type or -1 if there is no equivalent -CV_EXPORTS int getTypeFromD3DFORMAT(const int iD3DFORMAT); // enum D3DTYPE for D3D9 - -//! @} - -} } // namespace cv::directx - -#endif // OPENCV_CORE_DIRECTX_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 copyright holders 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. +// +//M*/ + +#ifndef OPENCV_CORE_DIRECTX_HPP +#define OPENCV_CORE_DIRECTX_HPP + +#include "mat.hpp" +#include "ocl.hpp" + +#if !defined(__d3d11_h__) +struct ID3D11Device; +struct ID3D11Texture2D; +#endif + +#if !defined(__d3d10_h__) +struct ID3D10Device; +struct ID3D10Texture2D; +#endif + +#if !defined(_D3D9_H_) +struct IDirect3DDevice9; +struct IDirect3DDevice9Ex; +struct IDirect3DSurface9; +#endif + + +namespace cv { namespace directx { + +namespace ocl { +using namespace cv::ocl; + +//! @addtogroup core_directx +// This section describes OpenCL and DirectX interoperability. +// +// To enable DirectX support, configure OpenCV using CMake with WITH_DIRECTX=ON . Note, DirectX is +// supported only on Windows. +// +// To use OpenCL functionality you should first initialize OpenCL context from DirectX resource. +// +//! @{ + +// TODO static functions in the Context class +//! @brief Creates OpenCL context from D3D11 device +// +//! @param pD3D11Device - pointer to D3D11 device +//! @return Returns reference to OpenCL Context +CV_EXPORTS Context& initializeContextFromD3D11Device(ID3D11Device* pD3D11Device); + +//! @brief Creates OpenCL context from D3D10 device +// +//! @param pD3D10Device - pointer to D3D10 device +//! @return Returns reference to OpenCL Context +CV_EXPORTS Context& initializeContextFromD3D10Device(ID3D10Device* pD3D10Device); + +//! @brief Creates OpenCL context from Direct3DDevice9Ex device +// +//! @param pDirect3DDevice9Ex - pointer to Direct3DDevice9Ex device +//! @return Returns reference to OpenCL Context +CV_EXPORTS Context& initializeContextFromDirect3DDevice9Ex(IDirect3DDevice9Ex* pDirect3DDevice9Ex); + +//! @brief Creates OpenCL context from Direct3DDevice9 device +// +//! @param pDirect3DDevice9 - pointer to Direct3Device9 device +//! @return Returns reference to OpenCL Context +CV_EXPORTS Context& initializeContextFromDirect3DDevice9(IDirect3DDevice9* pDirect3DDevice9); + +//! @} + +} // namespace cv::directx::ocl + +//! @addtogroup core_directx +//! @{ + +//! @brief Converts InputArray to ID3D11Texture2D. If destination texture format is DXGI_FORMAT_NV12 then +//! input UMat expected to be in BGR format and data will be downsampled and color-converted to NV12. +// +//! @note Note: Destination texture must be allocated by application. Function does memory copy from src to +//! pD3D11Texture2D +// +//! @param src - source InputArray +//! @param pD3D11Texture2D - destination D3D11 texture +CV_EXPORTS void convertToD3D11Texture2D(InputArray src, ID3D11Texture2D* pD3D11Texture2D); + +//! @brief Converts ID3D11Texture2D to OutputArray. If input texture format is DXGI_FORMAT_NV12 then +//! data will be upsampled and color-converted to BGR format. +// +//! @note Note: Destination matrix will be re-allocated if it has not enough memory to match texture size. +//! function does memory copy from pD3D11Texture2D to dst +// +//! @param pD3D11Texture2D - source D3D11 texture +//! @param dst - destination OutputArray +CV_EXPORTS void convertFromD3D11Texture2D(ID3D11Texture2D* pD3D11Texture2D, OutputArray dst); + +//! @brief Converts InputArray to ID3D10Texture2D +// +//! @note Note: function does memory copy from src to +//! pD3D10Texture2D +// +//! @param src - source InputArray +//! @param pD3D10Texture2D - destination D3D10 texture +CV_EXPORTS void convertToD3D10Texture2D(InputArray src, ID3D10Texture2D* pD3D10Texture2D); + +//! @brief Converts ID3D10Texture2D to OutputArray +// +//! @note Note: function does memory copy from pD3D10Texture2D +//! to dst +// +//! @param pD3D10Texture2D - source D3D10 texture +//! @param dst - destination OutputArray +CV_EXPORTS void convertFromD3D10Texture2D(ID3D10Texture2D* pD3D10Texture2D, OutputArray dst); + +//! @brief Converts InputArray to IDirect3DSurface9 +// +//! @note Note: function does memory copy from src to +//! pDirect3DSurface9 +// +//! @param src - source InputArray +//! @param pDirect3DSurface9 - destination D3D10 texture +//! @param surfaceSharedHandle - shared handle +CV_EXPORTS void convertToDirect3DSurface9(InputArray src, IDirect3DSurface9* pDirect3DSurface9, void* surfaceSharedHandle = NULL); + +//! @brief Converts IDirect3DSurface9 to OutputArray +// +//! @note Note: function does memory copy from pDirect3DSurface9 +//! to dst +// +//! @param pDirect3DSurface9 - source D3D10 texture +//! @param dst - destination OutputArray +//! @param surfaceSharedHandle - shared handle +CV_EXPORTS void convertFromDirect3DSurface9(IDirect3DSurface9* pDirect3DSurface9, OutputArray dst, void* surfaceSharedHandle = NULL); + +//! @brief Get OpenCV type from DirectX type +//! @param iDXGI_FORMAT - enum DXGI_FORMAT for D3D10/D3D11 +//! @return OpenCV type or -1 if there is no equivalent +CV_EXPORTS int getTypeFromDXGI_FORMAT(const int iDXGI_FORMAT); // enum DXGI_FORMAT for D3D10/D3D11 + +//! @brief Get OpenCV type from DirectX type +//! @param iD3DFORMAT - enum D3DTYPE for D3D9 +//! @return OpenCV type or -1 if there is no equivalent +CV_EXPORTS int getTypeFromD3DFORMAT(const int iD3DFORMAT); // enum D3DTYPE for D3D9 + +//! @} + +} } // namespace cv::directx + +#endif // OPENCV_CORE_DIRECTX_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/dualquaternion.hpp b/3rdParty/opencv-4.11.0/opencv2/core/dualquaternion.hpp index 4fec990461..990ca101c6 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/dualquaternion.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/dualquaternion.hpp @@ -1,979 +1,979 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2020, Huawei Technologies Co., Ltd. All rights reserved. -// Third party copyrights are property of their respective owners. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Author: Liangqian Kong -// Longbu Wang -#ifndef OPENCV_CORE_DUALQUATERNION_HPP -#define OPENCV_CORE_DUALQUATERNION_HPP - -#include -#include - -namespace cv{ -//! @addtogroup core_quaternion -//! @{ - -template class DualQuat; -template std::ostream& operator<<(std::ostream&, const DualQuat<_Tp>&); - -/** - * Dual quaternions were introduced to describe rotation together with translation while ordinary - * quaternions can only describe rotation. It can be used for shortest path pose interpolation, - * local pose optimization or volumetric deformation. More details can be found - * - https://en.wikipedia.org/wiki/Dual_quaternion - * - ["A beginners guide to dual-quaternions: what they are, how they work, and how to use them for 3D character hierarchies", Ben Kenwright, 2012](https://borodust.org/public/shared/beginner_dual_quats.pdf) - * - ["Dual Quaternions", Yan-Bin Jia, 2013](http://web.cs.iastate.edu/~cs577/handouts/dual-quaternion.pdf) - * - ["Geometric Skinning with Approximate Dual Quaternion Blending", Kavan, 2008](https://www.cs.utah.edu/~ladislav/kavan08geometric/kavan08geometric) - * - http://rodolphe-vaillant.fr/?e=29 - * - * A unit dual quaternion can be classically represented as: - * \f[ - * \begin{equation} - * \begin{split} - * \sigma &= \left(r+\frac{\epsilon}{2}tr\right)\\ - * &= [w, x, y, z, w\_, x\_, y\_, z\_] - * \end{split} - * \end{equation} - * \f] - * where \f$r, t\f$ represents the rotation (ordinary unit quaternion) and translation (pure ordinary quaternion) respectively. - * - * A general dual quaternions which consist of two quaternions is usually represented in form of: - * \f[ - * \sigma = p + \epsilon q - * \f] - * where the introduced dual unit \f$\epsilon\f$ satisfies \f$\epsilon^2 = \epsilon^3 =...=0\f$, and \f$p, q\f$ are quaternions. - * - * Alternatively, dual quaternions can also be interpreted as four components which are all [dual numbers](https://www.cs.utah.edu/~ladislav/kavan08geometric/kavan08geometric): - * \f[ - * \sigma = \hat{q}_w + \hat{q}_xi + \hat{q}_yj + \hat{q}_zk - * \f] - * If we set \f$\hat{q}_x, \hat{q}_y\f$ and \f$\hat{q}_z\f$ equal to 0, a dual quaternion is transformed to a dual number. see normalize(). - * - * If you want to create a dual quaternion, you can use: - * - * ``` - * using namespace cv; - * double angle = CV_PI; - * - * // create from eight number - * DualQuatd dq1(1, 2, 3, 4, 5, 6, 7, 8); //p = [1,2,3,4]. q=[5,6,7,8] - * - * // create from Vec - * Vec v{1,2,3,4,5,6,7,8}; - * DualQuatd dq_v{v}; - * - * // create from two quaternion - * Quatd p(1, 2, 3, 4); - * Quatd q(5, 6, 7, 8); - * DualQuatd dq2 = DualQuatd::createFromQuat(p, q); - * - * // create from an angle, an axis and a translation - * Vec3d axis{0, 0, 1}; - * Vec3d trans{3, 4, 5}; - * DualQuatd dq3 = DualQuatd::createFromAngleAxisTrans(angle, axis, trans); - * - * // If you already have an instance of class Affine3, then you can use - * Affine3d R = dq3.toAffine3(); - * DualQuatd dq4 = DualQuatd::createFromAffine3(R); - * - * // or create directly by affine transformation matrix Rt - * // see createFromMat() in detail for the form of Rt - * Matx44d Rt = dq3.toMat(); - * DualQuatd dq5 = DualQuatd::createFromMat(Rt); - * - * // Any rotation + translation movement can - * // be expressed as a rotation + translation around the same line in space (expressed by Plucker - * // coords), and here's a way to represent it this way. - * Vec3d axis{1, 1, 1}; // axis will be normalized in createFromPitch - * Vec3d trans{3, 4 ,5}; - * axis = axis / std::sqrt(axis.dot(axis));// The formula for computing moment that I use below requires a normalized axis - * Vec3d moment = 1.0 / 2 * (trans.cross(axis) + axis.cross(trans.cross(axis)) * - * std::cos(rotation_angle / 2) / std::sin(rotation_angle / 2)); - * double d = trans.dot(qaxis); - * DualQuatd dq6 = DualQuatd::createFromPitch(angle, d, axis, moment); - * ``` - * - * A point \f$v=(x, y, z)\f$ in form of dual quaternion is \f$[1+\epsilon v]=[1,0,0,0,0,x,y,z]\f$. - * The transformation of a point \f$v_1\f$ to another point \f$v_2\f$ under the dual quaternion \f$\sigma\f$ is - * \f[ - * 1 + \epsilon v_2 = \sigma * (1 + \epsilon v_1) * \sigma^{\star} - * \f] - * where \f$\sigma^{\star}=p^*-\epsilon q^*.\f$ - * - * A line in the \f$Pl\ddot{u}cker\f$ coordinates \f$(\hat{l}, m)\f$ defined by the dual quaternion \f$l=\hat{l}+\epsilon m\f$. - * To transform a line, \f[l_2 = \sigma * l_1 * \sigma^*,\f] where \f$\sigma=r+\frac{\epsilon}{2}rt\f$ and - * \f$\sigma^*=p^*+\epsilon q^*\f$. - * - * To extract the Vec or Vec, see toVec(); - * - * To extract the affine transformation matrix, see toMat(); - * - * To extract the instance of Affine3, see toAffine3(); - * - * If two quaternions \f$q_0, q_1\f$ are needed to be interpolated, you can use sclerp() - * ``` - * DualQuatd::sclerp(q0, q1, t) - * ``` - * or dqblend(). - * ``` - * DualQuatd::dqblend(q0, q1, t) - * ``` - * With more than two dual quaternions to be blended, you can use generalize linear dual quaternion blending - * with the corresponding weights, i.e. gdqblend(). - * - */ -template -class CV_EXPORTS DualQuat{ - static_assert(std::is_floating_point<_Tp>::value, "Dual quaternion only make sense with type of float or double"); - using value_type = _Tp; - -public: - static constexpr _Tp CV_DUAL_QUAT_EPS = (_Tp)1.e-6; - - DualQuat(); - - /** - * @brief create from eight same type numbers. - */ - DualQuat(const _Tp w, const _Tp x, const _Tp y, const _Tp z, const _Tp w_, const _Tp x_, const _Tp y_, const _Tp z_); - - /** - * @brief create from a double or float vector. - */ - DualQuat(const Vec<_Tp, 8> &q); - - _Tp w, x, y, z, w_, x_, y_, z_; - - /** - * @brief create Dual Quaternion from two same type quaternions p and q. - * A Dual Quaternion \f$\sigma\f$ has the form: - * \f[\sigma = p + \epsilon q\f] - * where p and q are defined as follows: - * \f[\begin{equation} - * \begin{split} - * p &= w + x\boldsymbol{i} + y\boldsymbol{j} + z\boldsymbol{k}\\ - * q &= w\_ + x\_\boldsymbol{i} + y\_\boldsymbol{j} + z\_\boldsymbol{k}. - * \end{split} - * \end{equation} - * \f] - * The p and q are the real part and dual part respectively. - * @param realPart a quaternion, real part of dual quaternion. - * @param dualPart a quaternion, dual part of dual quaternion. - * @sa Quat - */ - static DualQuat<_Tp> createFromQuat(const Quat<_Tp> &realPart, const Quat<_Tp> &dualPart); - - /** - * @brief create a dual quaternion from a rotation angle \f$\theta\f$, a rotation axis - * \f$\boldsymbol{u}\f$ and a translation \f$\boldsymbol{t}\f$. - * It generates a dual quaternion \f$\sigma\f$ in the form of - * \f[\begin{equation} - * \begin{split} - * \sigma &= r + \frac{\epsilon}{2}\boldsymbol{t}r \\ - * &= [\cos(\frac{\theta}{2}), \boldsymbol{u}\sin(\frac{\theta}{2})] - * + \frac{\epsilon}{2}[0, \boldsymbol{t}][[\cos(\frac{\theta}{2}), - * \boldsymbol{u}\sin(\frac{\theta}{2})]]\\ - * &= \cos(\frac{\theta}{2}) + \boldsymbol{u}\sin(\frac{\theta}{2}) - * + \frac{\epsilon}{2}(-(\boldsymbol{t} \cdot \boldsymbol{u})\sin(\frac{\theta}{2}) - * + \boldsymbol{t}\cos(\frac{\theta}{2}) + \boldsymbol{u} \times \boldsymbol{t} \sin(\frac{\theta}{2})). - * \end{split} - * \end{equation}\f] - * @param angle rotation angle. - * @param axis rotation axis. - * @param translation a vector of length 3. - * @note Axis will be normalized in this function. And translation is applied - * after the rotation. Use @ref createFromQuat(r, r * t / 2) to create a dual quaternion - * which translation is applied before rotation. - * @sa Quat - */ - static DualQuat<_Tp> createFromAngleAxisTrans(const _Tp angle, const Vec<_Tp, 3> &axis, const Vec<_Tp, 3> &translation); - - /** - * @brief Transform this dual quaternion to an affine transformation matrix \f$M\f$. - * Dual quaternion consists of a rotation \f$r=[a,b,c,d]\f$ and a translation \f$t=[\Delta x,\Delta y,\Delta z]\f$. The - * affine transformation matrix \f$M\f$ has the form - * \f[ - * \begin{bmatrix} - * 1-2(e_2^2 +e_3^2) &2(e_1e_2-e_0e_3) &2(e_0e_2+e_1e_3) &\Delta x\\ - * 2(e_0e_3+e_1e_2) &1-2(e_1^2+e_3^2) &2(e_2e_3-e_0e_1) &\Delta y\\ - * 2(e_1e_3-e_0e_2) &2(e_0e_1+e_2e_3) &1-2(e_1^2-e_2^2) &\Delta z\\ - * 0&0&0&1 - * \end{bmatrix} - * \f] - * if A is a matrix consisting of n points to be transformed, this could be achieved by - * \f[ - * new\_A = M * A - * \f] - * where A has the form - * \f[ - * \begin{bmatrix} - * x_0& x_1& x_2&...&x_n\\ - * y_0& y_1& y_2&...&y_n\\ - * z_0& z_1& z_2&...&z_n\\ - * 1&1&1&...&1 - * \end{bmatrix} - * \f] - * where the same subscript represent the same point. The size of A should be \f$[4,n]\f$. - * and the same size for matrix new_A. - * @param _R 4x4 matrix that represents rotations and translation. - * @note Translation is applied after the rotation. Use createFromQuat(r, r * t / 2) to create - * a dual quaternion which translation is applied before rotation. - */ - static DualQuat<_Tp> createFromMat(InputArray _R); - - /** - * @brief create dual quaternion from an affine matrix. The definition of affine matrix can refer to createFromMat() - */ - static DualQuat<_Tp> createFromAffine3(const Affine3<_Tp> &R); - - /** - * @brief A dual quaternion is a vector in form of - * \f[ - * \begin{equation} - * \begin{split} - * \sigma &=\boldsymbol{p} + \epsilon \boldsymbol{q}\\ - * &= \cos\hat{\frac{\theta}{2}}+\overline{\hat{l}}\sin\frac{\hat{\theta}}{2} - * \end{split} - * \end{equation} - * \f] - * where \f$\hat{\theta}\f$ is dual angle and \f$\overline{\hat{l}}\f$ is dual axis: - * \f[ - * \hat{\theta}=\theta + \epsilon d,\\ - * \overline{\hat{l}}= \hat{l} +\epsilon m. - * \f] - * In this representation, \f$\theta\f$ is rotation angle and \f$(\hat{l},m)\f$ is the screw axis, d is the translation distance along the axis. - * - * @param angle rotation angle. - * @param d translation along the rotation axis. - * @param axis rotation axis represented by quaternion with w = 0. - * @param moment the moment of line, and it should be orthogonal to axis. - * @note Translation is applied after the rotation. Use createFromQuat(r, r * t / 2) to create - * a dual quaternion which translation is applied before rotation. - */ - static DualQuat<_Tp> createFromPitch(const _Tp angle, const _Tp d, const Vec<_Tp, 3> &axis, const Vec<_Tp, 3> &moment); - - /** - * @brief return a quaternion which represent the real part of dual quaternion. - * The definition of real part is in createFromQuat(). - * @sa createFromQuat, getDualPart - */ - Quat<_Tp> getRealPart() const; - - /** - * @brief return a quaternion which represent the dual part of dual quaternion. - * The definition of dual part is in createFromQuat(). - * @sa createFromQuat, getRealPart - */ - Quat<_Tp> getDualPart() const; - - /** - * @brief return the conjugate of a dual quaternion. - * \f[ - * \begin{equation} - * \begin{split} - * \sigma^* &= (p + \epsilon q)^* - * &= (p^* + \epsilon q^*) - * \end{split} - * \end{equation} - * \f] - * @param dq a dual quaternion. - */ - template - friend DualQuat conjugate(const DualQuat &dq); - - /** - * @brief return the conjugate of a dual quaternion. - * \f[ - * \begin{equation} - * \begin{split} - * \sigma^* &= (p + \epsilon q)^* - * &= (p^* + \epsilon q^*) - * \end{split} - * \end{equation} - * \f] - */ - DualQuat<_Tp> conjugate() const; - - /** - * @brief return the rotation in quaternion form. - */ - Quat<_Tp> getRotation(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief return the translation vector. - * The rotation \f$r\f$ in this dual quaternion \f$\sigma\f$ is applied before translation \f$t\f$. - * The dual quaternion \f$\sigma\f$ is defined as - * \f[\begin{equation} - * \begin{split} - * \sigma &= p + \epsilon q \\ - * &= r + \frac{\epsilon}{2}{t}r. - * \end{split} - * \end{equation}\f] - * Thus, the translation can be obtained as follows - * \f[t = 2qp^*.\f] - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a unit dual quaternion - * and this function will save some computations. - * @note This dual quaternion's translation is applied after the rotation. - */ - Vec<_Tp, 3> getTranslation(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief return the norm \f$||\sigma||\f$ of dual quaternion \f$\sigma = p + \epsilon q\f$. - * \f[ - * \begin{equation} - * \begin{split} - * ||\sigma|| &= \sqrt{\sigma * \sigma^*} \\ - * &= ||p|| + \epsilon \frac{p \cdot q}{||p||}. - * \end{split} - * \end{equation} - * \f] - * Generally speaking, the norm of a not unit dual - * quaternion is a dual number. For convenience, we return it in the form of a dual quaternion - * , i.e. - * \f[ ||\sigma|| = [||p||, 0, 0, 0, \frac{p \cdot q}{||p||}, 0, 0, 0].\f] - * - * @note The data type of dual number is dual quaternion. - */ - DualQuat<_Tp> norm() const; - - /** - * @brief return a normalized dual quaternion. - * A dual quaternion can be expressed as - * \f[ - * \begin{equation} - * \begin{split} - * \sigma &= p + \epsilon q\\ - * &=||\sigma||\left(r+\frac{1}{2}tr\right) - * \end{split} - * \end{equation} - * \f] - * where \f$r, t\f$ represents the rotation (ordinary quaternion) and translation (pure ordinary quaternion) respectively, - * and \f$||\sigma||\f$ is the norm of dual quaternion(a dual number). - * A dual quaternion is unit if and only if - * \f[ - * ||p||=1, p \cdot q=0 - * \f] - * where \f$\cdot\f$ means dot product. - * The process of normalization is - * \f[ - * \sigma_{u}=\frac{\sigma}{||\sigma||} - * \f] - * Next, we simply proof \f$\sigma_u\f$ is a unit dual quaternion: - * \f[ - * \renewcommand{\Im}{\operatorname{Im}} - * \begin{equation} - * \begin{split} - * \sigma_{u}=\frac{\sigma}{||\sigma||}&=\frac{p + \epsilon q}{||p||+\epsilon\frac{p\cdot q}{||p||}}\\ - * &=\frac{p}{||p||}+\epsilon\left(\frac{q}{||p||}-p\frac{p\cdot q}{||p||^3}\right)\\ - * &=\frac{p}{||p||}+\epsilon\frac{1}{||p||^2}\left(qp^{*}-p\cdot q\right)\frac{p}{||p||}\\ - * &=\frac{p}{||p||}+\epsilon\frac{1}{||p||^2}\Im(qp^*)\frac{p}{||p||}.\\ - * \end{split} - * \end{equation} - * \f] - * As expected, the real part is a rotation and dual part is a pure quaternion. - */ - DualQuat<_Tp> normalize() const; - - /** - * @brief if \f$\sigma = p + \epsilon q\f$ is a dual quaternion, p is not zero, - * the inverse dual quaternion is - * \f[\sigma^{-1} = \frac{\sigma^*}{||\sigma||^2}, \f] - * or equivalentlly, - * \f[\sigma^{-1} = p^{-1} - \epsilon p^{-1}qp^{-1}.\f] - * @param dq a dual quaternion. - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, dual quaternion dq assume to be a unit dual quaternion - * and this function will save some computations. - */ - template - friend DualQuat inv(const DualQuat &dq, QuatAssumeType assumeUnit); - - /** - * @brief if \f$\sigma = p + \epsilon q\f$ is a dual quaternion, p is not zero, - * the inverse dual quaternion is - * \f[\sigma^{-1} = \frac{\sigma^*}{||\sigma||^2}, \f] - * or equivalentlly, - * \f[\sigma^{-1} = p^{-1} - \epsilon p^{-1}qp^{-1}.\f] - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a unit dual quaternion - * and this function will save some computations. - */ - DualQuat<_Tp> inv(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief return the dot product of two dual quaternion. - * @param p other dual quaternion. - */ - _Tp dot(DualQuat<_Tp> p) const; - - /** - ** @brief return the value of \f$p^t\f$ where p is a dual quaternion. - * This could be calculated as: - * \f[ - * p^t = \exp(t\ln p) - * \f] - * @param dq a dual quaternion. - * @param t index of power function. - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, dual quaternion dq assume to be a unit dual quaternion - * and this function will save some computations. - */ - template - friend DualQuat power(const DualQuat &dq, const T t, QuatAssumeType assumeUnit); - - /** - ** @brief return the value of \f$p^t\f$ where p is a dual quaternion. - * This could be calculated as: - * \f[ - * p^t = \exp(t\ln p) - * \f] - * - * @param t index of power function. - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a unit dual quaternion - * and this function will save some computations. - */ - DualQuat<_Tp> power(const _Tp t, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief return the value of \f$p^q\f$ where p and q are dual quaternions. - * This could be calculated as: - * \f[ - * p^q = \exp(q\ln p) - * \f] - * @param p a dual quaternion. - * @param q a dual quaternion. - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, dual quaternion p assume to be a dual unit quaternion - * and this function will save some computations. - */ - template - friend DualQuat power(const DualQuat& p, const DualQuat& q, QuatAssumeType assumeUnit); - - /** - * @brief return the value of \f$p^q\f$ where p and q are dual quaternions. - * This could be calculated as: - * \f[ - * p^q = \exp(q\ln p) - * \f] - * - * @param q a dual quaternion - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a dual unit quaternion - * and this function will save some computations. - */ - DualQuat<_Tp> power(const DualQuat<_Tp>& q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief return the value of exponential function value - * @param dq a dual quaternion. - */ - template - friend DualQuat exp(const DualQuat &dq); - - /** - * @brief return the value of exponential function value - */ - DualQuat<_Tp> exp() const; - - /** - * @brief return the value of logarithm function value - * - * @param dq a dual quaternion. - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, dual quaternion dq assume to be a unit dual quaternion - * and this function will save some computations. - */ - template - friend DualQuat log(const DualQuat &dq, QuatAssumeType assumeUnit); - - /** - * @brief return the value of logarithm function value - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a unit dual quaternion - * and this function will save some computations. - */ - DualQuat<_Tp> log(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief Transform this dual quaternion to a vector. - */ - Vec<_Tp, 8> toVec() const; - - /** - * @brief Transform this dual quaternion to a affine transformation matrix - * the form of matrix, see createFromMat(). - */ - Matx<_Tp, 4, 4> toMat(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief Transform this dual quaternion to a instance of Affine3. - */ - Affine3<_Tp> toAffine3(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief The screw linear interpolation(ScLERP) is an extension of spherical linear interpolation of dual quaternion. - * If \f$\sigma_1\f$ and \f$\sigma_2\f$ are two dual quaternions representing the initial and final pose. - * The interpolation of ScLERP function can be defined as: - * \f[ - * ScLERP(t;\sigma_1,\sigma_2) = \sigma_1 * (\sigma_1^{-1} * \sigma_2)^t, t\in[0,1] - * \f] - * - * @param q1 a dual quaternion represents a initial pose. - * @param q2 a dual quaternion represents a final pose. - * @param t interpolation parameter - * @param directChange if true, it always return the shortest path. - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a unit dual quaternion - * and this function will save some computations. - * - * For example - * ``` - * double angle1 = CV_PI / 2; - * Vec3d axis{0, 0, 1}; - * Vec3d t(0, 0, 3); - * DualQuatd initial = DualQuatd::createFromAngleAxisTrans(angle1, axis, t); - * double angle2 = CV_PI; - * DualQuatd final = DualQuatd::createFromAngleAxisTrans(angle2, axis, t); - * DualQuatd inter = DualQuatd::sclerp(initial, final, 0.5); - * ``` - */ - static DualQuat<_Tp> sclerp(const DualQuat<_Tp> &q1, const DualQuat<_Tp> &q2, const _Tp t, - bool directChange=true, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); - /** - * @brief The method of Dual Quaternion linear Blending(DQB) is to compute a transformation between dual quaternion - * \f$q_1\f$ and \f$q_2\f$ and can be defined as: - * \f[ - * DQB(t;{\boldsymbol{q}}_1,{\boldsymbol{q}}_2)= - * \frac{(1-t){\boldsymbol{q}}_1+t{\boldsymbol{q}}_2}{||(1-t){\boldsymbol{q}}_1+t{\boldsymbol{q}}_2||}. - * \f] - * where \f$q_1\f$ and \f$q_2\f$ are unit dual quaternions representing the input transformations. - * If you want to use DQB that works for more than two rigid transformations, see @ref gdqblend - * - * @param q1 a unit dual quaternion representing the input transformations. - * @param q2 a unit dual quaternion representing the input transformations. - * @param t parameter \f$t\in[0,1]\f$. - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a unit dual quaternion - * and this function will save some computations. - * - * @sa gdqblend - */ - static DualQuat<_Tp> dqblend(const DualQuat<_Tp> &q1, const DualQuat<_Tp> &q2, const _Tp t, - QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); - - /** - * @brief The generalized Dual Quaternion linear Blending works for more than two rigid transformations. - * If these transformations are expressed as unit dual quaternions \f$q_1,...,q_n\f$ with convex weights - * \f$w = (w_1,...,w_n)\f$, the generalized DQB is simply - * \f[ - * gDQB(\boldsymbol{w};{\boldsymbol{q}}_1,...,{\boldsymbol{q}}_n)=\frac{w_1{\boldsymbol{q}}_1+...+w_n{\boldsymbol{q}}_n} - * {||w_1{\boldsymbol{q}}_1+...+w_n{\boldsymbol{q}}_n||}. - * \f] - * @param dualquat vector of dual quaternions - * @param weights vector of weights, the size of weights should be the same as dualquat, and the weights should - * satisfy \f$\sum_0^n w_{i} = 1\f$ and \f$w_i>0\f$. - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, these dual quaternions assume to be unit quaternions - * and this function will save some computations. - * @note the type of weights' element should be the same as the date type of dual quaternion inside the dualquat. - */ - template - static DualQuat<_Tp> gdqblend(const Vec, cn> &dualquat, InputArray weights, - QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); - - /** - * @brief The generalized Dual Quaternion linear Blending works for more than two rigid transformations. - * If these transformations are expressed as unit dual quaternions \f$q_1,...,q_n\f$ with convex weights - * \f$w = (w_1,...,w_n)\f$, the generalized DQB is simply - * \f[ - * gDQB(\boldsymbol{w};{\boldsymbol{q}}_1,...,{\boldsymbol{q}}_n)=\frac{w_1{\boldsymbol{q}}_1+...+w_n{\boldsymbol{q}}_n} - * {||w_1{\boldsymbol{q}}_1+...+w_n{\boldsymbol{q}}_n||}. - * \f] - * @param dualquat The dual quaternions which have 8 channels and 1 row or 1 col. - * @param weights vector of weights, the size of weights should be the same as dualquat, and the weights should - * satisfy \f$\sum_0^n w_{i} = 1\f$ and \f$w_i>0\f$. - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, these dual quaternions assume to be unit quaternions - * and this function will save some computations. - * @note the type of weights' element should be the same as the date type of dual quaternion inside the dualquat. - */ - static DualQuat<_Tp> gdqblend(InputArray dualquat, InputArray weights, - QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); - - /** - * @brief Return opposite dual quaternion \f$-p\f$ - * which satisfies \f$p + (-p) = 0.\f$ - * - * For example - * ``` - * DualQuatd q{1, 2, 3, 4, 5, 6, 7, 8}; - * std::cout << -q << std::endl; // [-1, -2, -3, -4, -5, -6, -7, -8] - * ``` - */ - DualQuat<_Tp> operator-() const; - - /** - * @brief return true if two dual quaternions p and q are nearly equal, i.e. when the absolute - * value of each \f$p_i\f$ and \f$q_i\f$ is less than CV_DUAL_QUAT_EPS. - */ - bool operator==(const DualQuat<_Tp>&) const; - - /** - * @brief Subtraction operator of two dual quaternions p and q. - * It returns a new dual quaternion that each value is the sum of \f$p_i\f$ and \f$-q_i\f$. - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; - * std::cout << p - q << std::endl; //[-4, -4, -4, -4, 4, -4, -4, -4] - * ``` - */ - DualQuat<_Tp> operator-(const DualQuat<_Tp>&) const; - - /** - * @brief Subtraction assignment operator of two dual quaternions p and q. - * It subtracts right operand from the left operand and assign the result to left operand. - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; - * p -= q; // equivalent to p = p - q - * std::cout << p << std::endl; //[-4, -4, -4, -4, 4, -4, -4, -4] - * - * ``` - */ - DualQuat<_Tp>& operator-=(const DualQuat<_Tp>&); - - /** - * @brief Addition operator of two dual quaternions p and q. - * It returns a new dual quaternion that each value is the sum of \f$p_i\f$ and \f$q_i\f$. - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; - * std::cout << p + q << std::endl; //[6, 8, 10, 12, 14, 16, 18, 20] - * ``` - */ - DualQuat<_Tp> operator+(const DualQuat<_Tp>&) const; - - /** - * @brief Addition assignment operator of two dual quaternions p and q. - * It adds right operand to the left operand and assign the result to left operand. - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; - * p += q; // equivalent to p = p + q - * std::cout << p << std::endl; //[6, 8, 10, 12, 14, 16, 18, 20] - * - * ``` - */ - DualQuat<_Tp>& operator+=(const DualQuat<_Tp>&); - - /** - * @brief Multiplication assignment operator of two quaternions. - * It multiplies right operand with the left operand and assign the result to left operand. - * - * Rule of dual quaternion multiplication: - * The dual quaternion can be written as an ordered pair of quaternions [A, B]. Thus - * \f[ - * \begin{equation} - * \begin{split} - * p * q &= [A, B][C, D]\\ - * &=[AC, AD + BC] - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; - * p *= q; - * std::cout << p << std::endl; //[-60, 12, 30, 24, -216, 80, 124, 120] - * ``` - */ - DualQuat<_Tp>& operator*=(const DualQuat<_Tp>&); - - /** - * @brief Multiplication assignment operator of a quaternions and a scalar. - * It multiplies right operand with the left operand and assign the result to left operand. - * - * Rule of dual quaternion multiplication with a scalar: - * \f[ - * \begin{equation} - * \begin{split} - * p * s &= [w, x, y, z, w\_, x\_, y\_, z\_] * s\\ - * &=[w s, x s, y s, z s, w\_ \space s, x\_ \space s, y\_ \space s, z\_ \space s]. - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * double s = 2.0; - * p *= s; - * std::cout << p << std::endl; //[2, 4, 6, 8, 10, 12, 14, 16] - * ``` - * @note the type of scalar should be equal to the dual quaternion. - */ - DualQuat<_Tp> operator*=(const _Tp s); - - - /** - * @brief Multiplication operator of two dual quaternions q and p. - * Multiplies values on either side of the operator. - * - * Rule of dual quaternion multiplication: - * The dual quaternion can be written as an ordered pair of quaternions [A, B]. Thus - * \f[ - * \begin{equation} - * \begin{split} - * p * q &= [A, B][C, D]\\ - * &=[AC, AD + BC] - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; - * std::cout << p * q << std::endl; //[-60, 12, 30, 24, -216, 80, 124, 120] - * ``` - */ - DualQuat<_Tp> operator*(const DualQuat<_Tp>&) const; - - /** - * @brief Division operator of a dual quaternions and a scalar. - * It divides left operand with the right operand and assign the result to left operand. - * - * Rule of dual quaternion division with a scalar: - * \f[ - * \begin{equation} - * \begin{split} - * p / s &= [w, x, y, z, w\_, x\_, y\_, z\_] / s\\ - * &=[w/s, x/s, y/s, z/s, w\_/s, x\_/s, y\_/s, z\_/s]. - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * double s = 2.0; - * p /= s; // equivalent to p = p / s - * std::cout << p << std::endl; //[0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4] - * ``` - * @note the type of scalar should be equal to this dual quaternion. - */ - DualQuat<_Tp> operator/(const _Tp s) const; - - /** - * @brief Division operator of two dual quaternions p and q. - * Divides left hand operand by right hand operand. - * - * Rule of dual quaternion division with a dual quaternion: - * \f[ - * \begin{equation} - * \begin{split} - * p / q &= p * q.inv()\\ - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; - * std::cout << p / q << std::endl; // equivalent to p * q.inv() - * ``` - */ - DualQuat<_Tp> operator/(const DualQuat<_Tp>&) const; - - /** - * @brief Division assignment operator of two dual quaternions p and q; - * It divides left operand with the right operand and assign the result to left operand. - * - * Rule of dual quaternion division with a quaternion: - * \f[ - * \begin{equation} - * \begin{split} - * p / q&= p * q.inv()\\ - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; - * p /= q; // equivalent to p = p * q.inv() - * std::cout << p << std::endl; - * ``` - */ - DualQuat<_Tp>& operator/=(const DualQuat<_Tp>&); - - /** - * @brief Division assignment operator of a dual quaternions and a scalar. - * It divides left operand with the right operand and assign the result to left operand. - * - * Rule of dual quaternion division with a scalar: - * \f[ - * \begin{equation} - * \begin{split} - * p / s &= [w, x, y, z, w\_, x\_, y\_ ,z\_] / s\\ - * &=[w / s, x / s, y / s, z / s, w\_ / \space s, x\_ / \space s, y\_ / \space s, z\_ / \space s]. - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * double s = 2.0;; - * p /= s; // equivalent to p = p / s - * std::cout << p << std::endl; //[0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0] - * ``` - * @note the type of scalar should be equal to the dual quaternion. - */ - Quat<_Tp>& operator/=(const _Tp s); - - /** - * @brief Addition operator of a scalar and a dual quaternions. - * Adds right hand operand from left hand operand. - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * double scalar = 2.0; - * std::cout << scalar + p << std::endl; //[3.0, 2, 3, 4, 5, 6, 7, 8] - * ``` - * @note the type of scalar should be equal to the dual quaternion. - */ - template - friend DualQuat cv::operator+(const T s, const DualQuat&); - - /** - * @brief Addition operator of a dual quaternions and a scalar. - * Adds right hand operand from left hand operand. - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * double scalar = 2.0; - * std::cout << p + scalar << std::endl; //[3.0, 2, 3, 4, 5, 6, 7, 8] - * ``` - * @note the type of scalar should be equal to the dual quaternion. - */ - template - friend DualQuat cv::operator+(const DualQuat&, const T s); - - /** - * @brief Multiplication operator of a scalar and a dual quaternions. - * It multiplies right operand with the left operand and assign the result to left operand. - * - * Rule of dual quaternion multiplication with a scalar: - * \f[ - * \begin{equation} - * \begin{split} - * p * s &= [w, x, y, z, w\_, x\_, y\_, z\_] * s\\ - * &=[w s, x s, y s, z s, w\_ \space s, x\_ \space s, y\_ \space s, z\_ \space s]. - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * double s = 2.0; - * std::cout << s * p << std::endl; //[2, 4, 6, 8, 10, 12, 14, 16] - * ``` - * @note the type of scalar should be equal to the dual quaternion. - */ - template - friend DualQuat cv::operator*(const T s, const DualQuat&); - - /** - * @brief Subtraction operator of a dual quaternion and a scalar. - * Subtracts right hand operand from left hand operand. - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * double scalar = 2.0; - * std::cout << p - scalar << std::endl; //[-1, 2, 3, 4, 5, 6, 7, 8] - * ``` - * @note the type of scalar should be equal to the dual quaternion. - */ - template - friend DualQuat cv::operator-(const DualQuat&, const T s); - - /** - * @brief Subtraction operator of a scalar and a dual quaternions. - * Subtracts right hand operand from left hand operand. - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * double scalar = 2.0; - * std::cout << scalar - p << std::endl; //[1.0, -2, -3, -4, -5, -6, -7, -8] - * ``` - * @note the type of scalar should be equal to the dual quaternion. - */ - template - friend DualQuat cv::operator-(const T s, const DualQuat&); - - /** - * @brief Multiplication operator of a dual quaternions and a scalar. - * It multiplies right operand with the left operand and assign the result to left operand. - * - * Rule of dual quaternion multiplication with a scalar: - * \f[ - * \begin{equation} - * \begin{split} - * p * s &= [w, x, y, z, w\_, x\_, y\_, z\_] * s\\ - * &=[w s, x s, y s, z s, w\_ \space s, x\_ \space s, y\_ \space s, z\_ \space s]. - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * double s = 2.0; - * std::cout << p * s << std::endl; //[2, 4, 6, 8, 10, 12, 14, 16] - * ``` - * @note the type of scalar should be equal to the dual quaternion. - */ - template - friend DualQuat cv::operator*(const DualQuat&, const T s); - - template - friend std::ostream& cv::operator<<(std::ostream&, const DualQuat&); - -}; - -using DualQuatd = DualQuat; -using DualQuatf = DualQuat; - -//! @} core -}//namespace - -#include "dualquaternion.inl.hpp" - -#endif /* OPENCV_CORE_QUATERNION_HPP */ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2020, Huawei Technologies Co., Ltd. All rights reserved. +// Third party copyrights are property of their respective owners. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Author: Liangqian Kong +// Longbu Wang +#ifndef OPENCV_CORE_DUALQUATERNION_HPP +#define OPENCV_CORE_DUALQUATERNION_HPP + +#include +#include + +namespace cv{ +//! @addtogroup core_quaternion +//! @{ + +template class DualQuat; +template std::ostream& operator<<(std::ostream&, const DualQuat<_Tp>&); + +/** + * Dual quaternions were introduced to describe rotation together with translation while ordinary + * quaternions can only describe rotation. It can be used for shortest path pose interpolation, + * local pose optimization or volumetric deformation. More details can be found + * - https://en.wikipedia.org/wiki/Dual_quaternion + * - ["A beginners guide to dual-quaternions: what they are, how they work, and how to use them for 3D character hierarchies", Ben Kenwright, 2012](https://borodust.org/public/shared/beginner_dual_quats.pdf) + * - ["Dual Quaternions", Yan-Bin Jia, 2013](http://web.cs.iastate.edu/~cs577/handouts/dual-quaternion.pdf) + * - ["Geometric Skinning with Approximate Dual Quaternion Blending", Kavan, 2008](https://www.cs.utah.edu/~ladislav/kavan08geometric/kavan08geometric) + * - http://rodolphe-vaillant.fr/?e=29 + * + * A unit dual quaternion can be classically represented as: + * \f[ + * \begin{equation} + * \begin{split} + * \sigma &= \left(r+\frac{\epsilon}{2}tr\right)\\ + * &= [w, x, y, z, w\_, x\_, y\_, z\_] + * \end{split} + * \end{equation} + * \f] + * where \f$r, t\f$ represents the rotation (ordinary unit quaternion) and translation (pure ordinary quaternion) respectively. + * + * A general dual quaternions which consist of two quaternions is usually represented in form of: + * \f[ + * \sigma = p + \epsilon q + * \f] + * where the introduced dual unit \f$\epsilon\f$ satisfies \f$\epsilon^2 = \epsilon^3 =...=0\f$, and \f$p, q\f$ are quaternions. + * + * Alternatively, dual quaternions can also be interpreted as four components which are all [dual numbers](https://www.cs.utah.edu/~ladislav/kavan08geometric/kavan08geometric): + * \f[ + * \sigma = \hat{q}_w + \hat{q}_xi + \hat{q}_yj + \hat{q}_zk + * \f] + * If we set \f$\hat{q}_x, \hat{q}_y\f$ and \f$\hat{q}_z\f$ equal to 0, a dual quaternion is transformed to a dual number. see normalize(). + * + * If you want to create a dual quaternion, you can use: + * + * ``` + * using namespace cv; + * double angle = CV_PI; + * + * // create from eight number + * DualQuatd dq1(1, 2, 3, 4, 5, 6, 7, 8); //p = [1,2,3,4]. q=[5,6,7,8] + * + * // create from Vec + * Vec v{1,2,3,4,5,6,7,8}; + * DualQuatd dq_v{v}; + * + * // create from two quaternion + * Quatd p(1, 2, 3, 4); + * Quatd q(5, 6, 7, 8); + * DualQuatd dq2 = DualQuatd::createFromQuat(p, q); + * + * // create from an angle, an axis and a translation + * Vec3d axis{0, 0, 1}; + * Vec3d trans{3, 4, 5}; + * DualQuatd dq3 = DualQuatd::createFromAngleAxisTrans(angle, axis, trans); + * + * // If you already have an instance of class Affine3, then you can use + * Affine3d R = dq3.toAffine3(); + * DualQuatd dq4 = DualQuatd::createFromAffine3(R); + * + * // or create directly by affine transformation matrix Rt + * // see createFromMat() in detail for the form of Rt + * Matx44d Rt = dq3.toMat(); + * DualQuatd dq5 = DualQuatd::createFromMat(Rt); + * + * // Any rotation + translation movement can + * // be expressed as a rotation + translation around the same line in space (expressed by Plucker + * // coords), and here's a way to represent it this way. + * Vec3d axis{1, 1, 1}; // axis will be normalized in createFromPitch + * Vec3d trans{3, 4 ,5}; + * axis = axis / std::sqrt(axis.dot(axis));// The formula for computing moment that I use below requires a normalized axis + * Vec3d moment = 1.0 / 2 * (trans.cross(axis) + axis.cross(trans.cross(axis)) * + * std::cos(rotation_angle / 2) / std::sin(rotation_angle / 2)); + * double d = trans.dot(qaxis); + * DualQuatd dq6 = DualQuatd::createFromPitch(angle, d, axis, moment); + * ``` + * + * A point \f$v=(x, y, z)\f$ in form of dual quaternion is \f$[1+\epsilon v]=[1,0,0,0,0,x,y,z]\f$. + * The transformation of a point \f$v_1\f$ to another point \f$v_2\f$ under the dual quaternion \f$\sigma\f$ is + * \f[ + * 1 + \epsilon v_2 = \sigma * (1 + \epsilon v_1) * \sigma^{\star} + * \f] + * where \f$\sigma^{\star}=p^*-\epsilon q^*.\f$ + * + * A line in the \f$Pl\ddot{u}cker\f$ coordinates \f$(\hat{l}, m)\f$ defined by the dual quaternion \f$l=\hat{l}+\epsilon m\f$. + * To transform a line, \f[l_2 = \sigma * l_1 * \sigma^*,\f] where \f$\sigma=r+\frac{\epsilon}{2}rt\f$ and + * \f$\sigma^*=p^*+\epsilon q^*\f$. + * + * To extract the Vec or Vec, see toVec(); + * + * To extract the affine transformation matrix, see toMat(); + * + * To extract the instance of Affine3, see toAffine3(); + * + * If two quaternions \f$q_0, q_1\f$ are needed to be interpolated, you can use sclerp() + * ``` + * DualQuatd::sclerp(q0, q1, t) + * ``` + * or dqblend(). + * ``` + * DualQuatd::dqblend(q0, q1, t) + * ``` + * With more than two dual quaternions to be blended, you can use generalize linear dual quaternion blending + * with the corresponding weights, i.e. gdqblend(). + * + */ +template +class CV_EXPORTS DualQuat{ + static_assert(std::is_floating_point<_Tp>::value, "Dual quaternion only make sense with type of float or double"); + using value_type = _Tp; + +public: + static constexpr _Tp CV_DUAL_QUAT_EPS = (_Tp)1.e-6; + + DualQuat(); + + /** + * @brief create from eight same type numbers. + */ + DualQuat(const _Tp w, const _Tp x, const _Tp y, const _Tp z, const _Tp w_, const _Tp x_, const _Tp y_, const _Tp z_); + + /** + * @brief create from a double or float vector. + */ + DualQuat(const Vec<_Tp, 8> &q); + + _Tp w, x, y, z, w_, x_, y_, z_; + + /** + * @brief create Dual Quaternion from two same type quaternions p and q. + * A Dual Quaternion \f$\sigma\f$ has the form: + * \f[\sigma = p + \epsilon q\f] + * where p and q are defined as follows: + * \f[\begin{equation} + * \begin{split} + * p &= w + x\boldsymbol{i} + y\boldsymbol{j} + z\boldsymbol{k}\\ + * q &= w\_ + x\_\boldsymbol{i} + y\_\boldsymbol{j} + z\_\boldsymbol{k}. + * \end{split} + * \end{equation} + * \f] + * The p and q are the real part and dual part respectively. + * @param realPart a quaternion, real part of dual quaternion. + * @param dualPart a quaternion, dual part of dual quaternion. + * @sa Quat + */ + static DualQuat<_Tp> createFromQuat(const Quat<_Tp> &realPart, const Quat<_Tp> &dualPart); + + /** + * @brief create a dual quaternion from a rotation angle \f$\theta\f$, a rotation axis + * \f$\boldsymbol{u}\f$ and a translation \f$\boldsymbol{t}\f$. + * It generates a dual quaternion \f$\sigma\f$ in the form of + * \f[\begin{equation} + * \begin{split} + * \sigma &= r + \frac{\epsilon}{2}\boldsymbol{t}r \\ + * &= [\cos(\frac{\theta}{2}), \boldsymbol{u}\sin(\frac{\theta}{2})] + * + \frac{\epsilon}{2}[0, \boldsymbol{t}][[\cos(\frac{\theta}{2}), + * \boldsymbol{u}\sin(\frac{\theta}{2})]]\\ + * &= \cos(\frac{\theta}{2}) + \boldsymbol{u}\sin(\frac{\theta}{2}) + * + \frac{\epsilon}{2}(-(\boldsymbol{t} \cdot \boldsymbol{u})\sin(\frac{\theta}{2}) + * + \boldsymbol{t}\cos(\frac{\theta}{2}) + \boldsymbol{u} \times \boldsymbol{t} \sin(\frac{\theta}{2})). + * \end{split} + * \end{equation}\f] + * @param angle rotation angle. + * @param axis rotation axis. + * @param translation a vector of length 3. + * @note Axis will be normalized in this function. And translation is applied + * after the rotation. Use @ref createFromQuat(r, r * t / 2) to create a dual quaternion + * which translation is applied before rotation. + * @sa Quat + */ + static DualQuat<_Tp> createFromAngleAxisTrans(const _Tp angle, const Vec<_Tp, 3> &axis, const Vec<_Tp, 3> &translation); + + /** + * @brief Transform this dual quaternion to an affine transformation matrix \f$M\f$. + * Dual quaternion consists of a rotation \f$r=[a,b,c,d]\f$ and a translation \f$t=[\Delta x,\Delta y,\Delta z]\f$. The + * affine transformation matrix \f$M\f$ has the form + * \f[ + * \begin{bmatrix} + * 1-2(e_2^2 +e_3^2) &2(e_1e_2-e_0e_3) &2(e_0e_2+e_1e_3) &\Delta x\\ + * 2(e_0e_3+e_1e_2) &1-2(e_1^2+e_3^2) &2(e_2e_3-e_0e_1) &\Delta y\\ + * 2(e_1e_3-e_0e_2) &2(e_0e_1+e_2e_3) &1-2(e_1^2-e_2^2) &\Delta z\\ + * 0&0&0&1 + * \end{bmatrix} + * \f] + * if A is a matrix consisting of n points to be transformed, this could be achieved by + * \f[ + * new\_A = M * A + * \f] + * where A has the form + * \f[ + * \begin{bmatrix} + * x_0& x_1& x_2&...&x_n\\ + * y_0& y_1& y_2&...&y_n\\ + * z_0& z_1& z_2&...&z_n\\ + * 1&1&1&...&1 + * \end{bmatrix} + * \f] + * where the same subscript represent the same point. The size of A should be \f$[4,n]\f$. + * and the same size for matrix new_A. + * @param _R 4x4 matrix that represents rotations and translation. + * @note Translation is applied after the rotation. Use createFromQuat(r, r * t / 2) to create + * a dual quaternion which translation is applied before rotation. + */ + static DualQuat<_Tp> createFromMat(InputArray _R); + + /** + * @brief create dual quaternion from an affine matrix. The definition of affine matrix can refer to createFromMat() + */ + static DualQuat<_Tp> createFromAffine3(const Affine3<_Tp> &R); + + /** + * @brief A dual quaternion is a vector in form of + * \f[ + * \begin{equation} + * \begin{split} + * \sigma &=\boldsymbol{p} + \epsilon \boldsymbol{q}\\ + * &= \cos\hat{\frac{\theta}{2}}+\overline{\hat{l}}\sin\frac{\hat{\theta}}{2} + * \end{split} + * \end{equation} + * \f] + * where \f$\hat{\theta}\f$ is dual angle and \f$\overline{\hat{l}}\f$ is dual axis: + * \f[ + * \hat{\theta}=\theta + \epsilon d,\\ + * \overline{\hat{l}}= \hat{l} +\epsilon m. + * \f] + * In this representation, \f$\theta\f$ is rotation angle and \f$(\hat{l},m)\f$ is the screw axis, d is the translation distance along the axis. + * + * @param angle rotation angle. + * @param d translation along the rotation axis. + * @param axis rotation axis represented by quaternion with w = 0. + * @param moment the moment of line, and it should be orthogonal to axis. + * @note Translation is applied after the rotation. Use createFromQuat(r, r * t / 2) to create + * a dual quaternion which translation is applied before rotation. + */ + static DualQuat<_Tp> createFromPitch(const _Tp angle, const _Tp d, const Vec<_Tp, 3> &axis, const Vec<_Tp, 3> &moment); + + /** + * @brief return a quaternion which represent the real part of dual quaternion. + * The definition of real part is in createFromQuat(). + * @sa createFromQuat, getDualPart + */ + Quat<_Tp> getRealPart() const; + + /** + * @brief return a quaternion which represent the dual part of dual quaternion. + * The definition of dual part is in createFromQuat(). + * @sa createFromQuat, getRealPart + */ + Quat<_Tp> getDualPart() const; + + /** + * @brief return the conjugate of a dual quaternion. + * \f[ + * \begin{equation} + * \begin{split} + * \sigma^* &= (p + \epsilon q)^* + * &= (p^* + \epsilon q^*) + * \end{split} + * \end{equation} + * \f] + * @param dq a dual quaternion. + */ + template + friend DualQuat conjugate(const DualQuat &dq); + + /** + * @brief return the conjugate of a dual quaternion. + * \f[ + * \begin{equation} + * \begin{split} + * \sigma^* &= (p + \epsilon q)^* + * &= (p^* + \epsilon q^*) + * \end{split} + * \end{equation} + * \f] + */ + DualQuat<_Tp> conjugate() const; + + /** + * @brief return the rotation in quaternion form. + */ + Quat<_Tp> getRotation(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief return the translation vector. + * The rotation \f$r\f$ in this dual quaternion \f$\sigma\f$ is applied before translation \f$t\f$. + * The dual quaternion \f$\sigma\f$ is defined as + * \f[\begin{equation} + * \begin{split} + * \sigma &= p + \epsilon q \\ + * &= r + \frac{\epsilon}{2}{t}r. + * \end{split} + * \end{equation}\f] + * Thus, the translation can be obtained as follows + * \f[t = 2qp^*.\f] + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a unit dual quaternion + * and this function will save some computations. + * @note This dual quaternion's translation is applied after the rotation. + */ + Vec<_Tp, 3> getTranslation(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief return the norm \f$||\sigma||\f$ of dual quaternion \f$\sigma = p + \epsilon q\f$. + * \f[ + * \begin{equation} + * \begin{split} + * ||\sigma|| &= \sqrt{\sigma * \sigma^*} \\ + * &= ||p|| + \epsilon \frac{p \cdot q}{||p||}. + * \end{split} + * \end{equation} + * \f] + * Generally speaking, the norm of a not unit dual + * quaternion is a dual number. For convenience, we return it in the form of a dual quaternion + * , i.e. + * \f[ ||\sigma|| = [||p||, 0, 0, 0, \frac{p \cdot q}{||p||}, 0, 0, 0].\f] + * + * @note The data type of dual number is dual quaternion. + */ + DualQuat<_Tp> norm() const; + + /** + * @brief return a normalized dual quaternion. + * A dual quaternion can be expressed as + * \f[ + * \begin{equation} + * \begin{split} + * \sigma &= p + \epsilon q\\ + * &=||\sigma||\left(r+\frac{1}{2}tr\right) + * \end{split} + * \end{equation} + * \f] + * where \f$r, t\f$ represents the rotation (ordinary quaternion) and translation (pure ordinary quaternion) respectively, + * and \f$||\sigma||\f$ is the norm of dual quaternion(a dual number). + * A dual quaternion is unit if and only if + * \f[ + * ||p||=1, p \cdot q=0 + * \f] + * where \f$\cdot\f$ means dot product. + * The process of normalization is + * \f[ + * \sigma_{u}=\frac{\sigma}{||\sigma||} + * \f] + * Next, we simply proof \f$\sigma_u\f$ is a unit dual quaternion: + * \f[ + * \renewcommand{\Im}{\operatorname{Im}} + * \begin{equation} + * \begin{split} + * \sigma_{u}=\frac{\sigma}{||\sigma||}&=\frac{p + \epsilon q}{||p||+\epsilon\frac{p\cdot q}{||p||}}\\ + * &=\frac{p}{||p||}+\epsilon\left(\frac{q}{||p||}-p\frac{p\cdot q}{||p||^3}\right)\\ + * &=\frac{p}{||p||}+\epsilon\frac{1}{||p||^2}\left(qp^{*}-p\cdot q\right)\frac{p}{||p||}\\ + * &=\frac{p}{||p||}+\epsilon\frac{1}{||p||^2}\Im(qp^*)\frac{p}{||p||}.\\ + * \end{split} + * \end{equation} + * \f] + * As expected, the real part is a rotation and dual part is a pure quaternion. + */ + DualQuat<_Tp> normalize() const; + + /** + * @brief if \f$\sigma = p + \epsilon q\f$ is a dual quaternion, p is not zero, + * the inverse dual quaternion is + * \f[\sigma^{-1} = \frac{\sigma^*}{||\sigma||^2}, \f] + * or equivalentlly, + * \f[\sigma^{-1} = p^{-1} - \epsilon p^{-1}qp^{-1}.\f] + * @param dq a dual quaternion. + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, dual quaternion dq assume to be a unit dual quaternion + * and this function will save some computations. + */ + template + friend DualQuat inv(const DualQuat &dq, QuatAssumeType assumeUnit); + + /** + * @brief if \f$\sigma = p + \epsilon q\f$ is a dual quaternion, p is not zero, + * the inverse dual quaternion is + * \f[\sigma^{-1} = \frac{\sigma^*}{||\sigma||^2}, \f] + * or equivalentlly, + * \f[\sigma^{-1} = p^{-1} - \epsilon p^{-1}qp^{-1}.\f] + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a unit dual quaternion + * and this function will save some computations. + */ + DualQuat<_Tp> inv(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief return the dot product of two dual quaternion. + * @param p other dual quaternion. + */ + _Tp dot(DualQuat<_Tp> p) const; + + /** + ** @brief return the value of \f$p^t\f$ where p is a dual quaternion. + * This could be calculated as: + * \f[ + * p^t = \exp(t\ln p) + * \f] + * @param dq a dual quaternion. + * @param t index of power function. + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, dual quaternion dq assume to be a unit dual quaternion + * and this function will save some computations. + */ + template + friend DualQuat power(const DualQuat &dq, const T t, QuatAssumeType assumeUnit); + + /** + ** @brief return the value of \f$p^t\f$ where p is a dual quaternion. + * This could be calculated as: + * \f[ + * p^t = \exp(t\ln p) + * \f] + * + * @param t index of power function. + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a unit dual quaternion + * and this function will save some computations. + */ + DualQuat<_Tp> power(const _Tp t, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief return the value of \f$p^q\f$ where p and q are dual quaternions. + * This could be calculated as: + * \f[ + * p^q = \exp(q\ln p) + * \f] + * @param p a dual quaternion. + * @param q a dual quaternion. + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, dual quaternion p assume to be a dual unit quaternion + * and this function will save some computations. + */ + template + friend DualQuat power(const DualQuat& p, const DualQuat& q, QuatAssumeType assumeUnit); + + /** + * @brief return the value of \f$p^q\f$ where p and q are dual quaternions. + * This could be calculated as: + * \f[ + * p^q = \exp(q\ln p) + * \f] + * + * @param q a dual quaternion + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a dual unit quaternion + * and this function will save some computations. + */ + DualQuat<_Tp> power(const DualQuat<_Tp>& q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief return the value of exponential function value + * @param dq a dual quaternion. + */ + template + friend DualQuat exp(const DualQuat &dq); + + /** + * @brief return the value of exponential function value + */ + DualQuat<_Tp> exp() const; + + /** + * @brief return the value of logarithm function value + * + * @param dq a dual quaternion. + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, dual quaternion dq assume to be a unit dual quaternion + * and this function will save some computations. + */ + template + friend DualQuat log(const DualQuat &dq, QuatAssumeType assumeUnit); + + /** + * @brief return the value of logarithm function value + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a unit dual quaternion + * and this function will save some computations. + */ + DualQuat<_Tp> log(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief Transform this dual quaternion to a vector. + */ + Vec<_Tp, 8> toVec() const; + + /** + * @brief Transform this dual quaternion to a affine transformation matrix + * the form of matrix, see createFromMat(). + */ + Matx<_Tp, 4, 4> toMat(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief Transform this dual quaternion to a instance of Affine3. + */ + Affine3<_Tp> toAffine3(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief The screw linear interpolation(ScLERP) is an extension of spherical linear interpolation of dual quaternion. + * If \f$\sigma_1\f$ and \f$\sigma_2\f$ are two dual quaternions representing the initial and final pose. + * The interpolation of ScLERP function can be defined as: + * \f[ + * ScLERP(t;\sigma_1,\sigma_2) = \sigma_1 * (\sigma_1^{-1} * \sigma_2)^t, t\in[0,1] + * \f] + * + * @param q1 a dual quaternion represents a initial pose. + * @param q2 a dual quaternion represents a final pose. + * @param t interpolation parameter + * @param directChange if true, it always return the shortest path. + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a unit dual quaternion + * and this function will save some computations. + * + * For example + * ``` + * double angle1 = CV_PI / 2; + * Vec3d axis{0, 0, 1}; + * Vec3d t(0, 0, 3); + * DualQuatd initial = DualQuatd::createFromAngleAxisTrans(angle1, axis, t); + * double angle2 = CV_PI; + * DualQuatd final = DualQuatd::createFromAngleAxisTrans(angle2, axis, t); + * DualQuatd inter = DualQuatd::sclerp(initial, final, 0.5); + * ``` + */ + static DualQuat<_Tp> sclerp(const DualQuat<_Tp> &q1, const DualQuat<_Tp> &q2, const _Tp t, + bool directChange=true, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); + /** + * @brief The method of Dual Quaternion linear Blending(DQB) is to compute a transformation between dual quaternion + * \f$q_1\f$ and \f$q_2\f$ and can be defined as: + * \f[ + * DQB(t;{\boldsymbol{q}}_1,{\boldsymbol{q}}_2)= + * \frac{(1-t){\boldsymbol{q}}_1+t{\boldsymbol{q}}_2}{||(1-t){\boldsymbol{q}}_1+t{\boldsymbol{q}}_2||}. + * \f] + * where \f$q_1\f$ and \f$q_2\f$ are unit dual quaternions representing the input transformations. + * If you want to use DQB that works for more than two rigid transformations, see @ref gdqblend + * + * @param q1 a unit dual quaternion representing the input transformations. + * @param q2 a unit dual quaternion representing the input transformations. + * @param t parameter \f$t\in[0,1]\f$. + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a unit dual quaternion + * and this function will save some computations. + * + * @sa gdqblend + */ + static DualQuat<_Tp> dqblend(const DualQuat<_Tp> &q1, const DualQuat<_Tp> &q2, const _Tp t, + QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); + + /** + * @brief The generalized Dual Quaternion linear Blending works for more than two rigid transformations. + * If these transformations are expressed as unit dual quaternions \f$q_1,...,q_n\f$ with convex weights + * \f$w = (w_1,...,w_n)\f$, the generalized DQB is simply + * \f[ + * gDQB(\boldsymbol{w};{\boldsymbol{q}}_1,...,{\boldsymbol{q}}_n)=\frac{w_1{\boldsymbol{q}}_1+...+w_n{\boldsymbol{q}}_n} + * {||w_1{\boldsymbol{q}}_1+...+w_n{\boldsymbol{q}}_n||}. + * \f] + * @param dualquat vector of dual quaternions + * @param weights vector of weights, the size of weights should be the same as dualquat, and the weights should + * satisfy \f$\sum_0^n w_{i} = 1\f$ and \f$w_i>0\f$. + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, these dual quaternions assume to be unit quaternions + * and this function will save some computations. + * @note the type of weights' element should be the same as the date type of dual quaternion inside the dualquat. + */ + template + static DualQuat<_Tp> gdqblend(const Vec, cn> &dualquat, InputArray weights, + QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); + + /** + * @brief The generalized Dual Quaternion linear Blending works for more than two rigid transformations. + * If these transformations are expressed as unit dual quaternions \f$q_1,...,q_n\f$ with convex weights + * \f$w = (w_1,...,w_n)\f$, the generalized DQB is simply + * \f[ + * gDQB(\boldsymbol{w};{\boldsymbol{q}}_1,...,{\boldsymbol{q}}_n)=\frac{w_1{\boldsymbol{q}}_1+...+w_n{\boldsymbol{q}}_n} + * {||w_1{\boldsymbol{q}}_1+...+w_n{\boldsymbol{q}}_n||}. + * \f] + * @param dualquat The dual quaternions which have 8 channels and 1 row or 1 col. + * @param weights vector of weights, the size of weights should be the same as dualquat, and the weights should + * satisfy \f$\sum_0^n w_{i} = 1\f$ and \f$w_i>0\f$. + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, these dual quaternions assume to be unit quaternions + * and this function will save some computations. + * @note the type of weights' element should be the same as the date type of dual quaternion inside the dualquat. + */ + static DualQuat<_Tp> gdqblend(InputArray dualquat, InputArray weights, + QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); + + /** + * @brief Return opposite dual quaternion \f$-p\f$ + * which satisfies \f$p + (-p) = 0.\f$ + * + * For example + * ``` + * DualQuatd q{1, 2, 3, 4, 5, 6, 7, 8}; + * std::cout << -q << std::endl; // [-1, -2, -3, -4, -5, -6, -7, -8] + * ``` + */ + DualQuat<_Tp> operator-() const; + + /** + * @brief return true if two dual quaternions p and q are nearly equal, i.e. when the absolute + * value of each \f$p_i\f$ and \f$q_i\f$ is less than CV_DUAL_QUAT_EPS. + */ + bool operator==(const DualQuat<_Tp>&) const; + + /** + * @brief Subtraction operator of two dual quaternions p and q. + * It returns a new dual quaternion that each value is the sum of \f$p_i\f$ and \f$-q_i\f$. + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; + * std::cout << p - q << std::endl; //[-4, -4, -4, -4, 4, -4, -4, -4] + * ``` + */ + DualQuat<_Tp> operator-(const DualQuat<_Tp>&) const; + + /** + * @brief Subtraction assignment operator of two dual quaternions p and q. + * It subtracts right operand from the left operand and assign the result to left operand. + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; + * p -= q; // equivalent to p = p - q + * std::cout << p << std::endl; //[-4, -4, -4, -4, 4, -4, -4, -4] + * + * ``` + */ + DualQuat<_Tp>& operator-=(const DualQuat<_Tp>&); + + /** + * @brief Addition operator of two dual quaternions p and q. + * It returns a new dual quaternion that each value is the sum of \f$p_i\f$ and \f$q_i\f$. + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; + * std::cout << p + q << std::endl; //[6, 8, 10, 12, 14, 16, 18, 20] + * ``` + */ + DualQuat<_Tp> operator+(const DualQuat<_Tp>&) const; + + /** + * @brief Addition assignment operator of two dual quaternions p and q. + * It adds right operand to the left operand and assign the result to left operand. + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; + * p += q; // equivalent to p = p + q + * std::cout << p << std::endl; //[6, 8, 10, 12, 14, 16, 18, 20] + * + * ``` + */ + DualQuat<_Tp>& operator+=(const DualQuat<_Tp>&); + + /** + * @brief Multiplication assignment operator of two quaternions. + * It multiplies right operand with the left operand and assign the result to left operand. + * + * Rule of dual quaternion multiplication: + * The dual quaternion can be written as an ordered pair of quaternions [A, B]. Thus + * \f[ + * \begin{equation} + * \begin{split} + * p * q &= [A, B][C, D]\\ + * &=[AC, AD + BC] + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; + * p *= q; + * std::cout << p << std::endl; //[-60, 12, 30, 24, -216, 80, 124, 120] + * ``` + */ + DualQuat<_Tp>& operator*=(const DualQuat<_Tp>&); + + /** + * @brief Multiplication assignment operator of a quaternions and a scalar. + * It multiplies right operand with the left operand and assign the result to left operand. + * + * Rule of dual quaternion multiplication with a scalar: + * \f[ + * \begin{equation} + * \begin{split} + * p * s &= [w, x, y, z, w\_, x\_, y\_, z\_] * s\\ + * &=[w s, x s, y s, z s, w\_ \space s, x\_ \space s, y\_ \space s, z\_ \space s]. + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * double s = 2.0; + * p *= s; + * std::cout << p << std::endl; //[2, 4, 6, 8, 10, 12, 14, 16] + * ``` + * @note the type of scalar should be equal to the dual quaternion. + */ + DualQuat<_Tp> operator*=(const _Tp s); + + + /** + * @brief Multiplication operator of two dual quaternions q and p. + * Multiplies values on either side of the operator. + * + * Rule of dual quaternion multiplication: + * The dual quaternion can be written as an ordered pair of quaternions [A, B]. Thus + * \f[ + * \begin{equation} + * \begin{split} + * p * q &= [A, B][C, D]\\ + * &=[AC, AD + BC] + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; + * std::cout << p * q << std::endl; //[-60, 12, 30, 24, -216, 80, 124, 120] + * ``` + */ + DualQuat<_Tp> operator*(const DualQuat<_Tp>&) const; + + /** + * @brief Division operator of a dual quaternions and a scalar. + * It divides left operand with the right operand and assign the result to left operand. + * + * Rule of dual quaternion division with a scalar: + * \f[ + * \begin{equation} + * \begin{split} + * p / s &= [w, x, y, z, w\_, x\_, y\_, z\_] / s\\ + * &=[w/s, x/s, y/s, z/s, w\_/s, x\_/s, y\_/s, z\_/s]. + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * double s = 2.0; + * p /= s; // equivalent to p = p / s + * std::cout << p << std::endl; //[0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4] + * ``` + * @note the type of scalar should be equal to this dual quaternion. + */ + DualQuat<_Tp> operator/(const _Tp s) const; + + /** + * @brief Division operator of two dual quaternions p and q. + * Divides left hand operand by right hand operand. + * + * Rule of dual quaternion division with a dual quaternion: + * \f[ + * \begin{equation} + * \begin{split} + * p / q &= p * q.inv()\\ + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; + * std::cout << p / q << std::endl; // equivalent to p * q.inv() + * ``` + */ + DualQuat<_Tp> operator/(const DualQuat<_Tp>&) const; + + /** + * @brief Division assignment operator of two dual quaternions p and q; + * It divides left operand with the right operand and assign the result to left operand. + * + * Rule of dual quaternion division with a quaternion: + * \f[ + * \begin{equation} + * \begin{split} + * p / q&= p * q.inv()\\ + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; + * p /= q; // equivalent to p = p * q.inv() + * std::cout << p << std::endl; + * ``` + */ + DualQuat<_Tp>& operator/=(const DualQuat<_Tp>&); + + /** + * @brief Division assignment operator of a dual quaternions and a scalar. + * It divides left operand with the right operand and assign the result to left operand. + * + * Rule of dual quaternion division with a scalar: + * \f[ + * \begin{equation} + * \begin{split} + * p / s &= [w, x, y, z, w\_, x\_, y\_ ,z\_] / s\\ + * &=[w / s, x / s, y / s, z / s, w\_ / \space s, x\_ / \space s, y\_ / \space s, z\_ / \space s]. + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * double s = 2.0;; + * p /= s; // equivalent to p = p / s + * std::cout << p << std::endl; //[0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0] + * ``` + * @note the type of scalar should be equal to the dual quaternion. + */ + Quat<_Tp>& operator/=(const _Tp s); + + /** + * @brief Addition operator of a scalar and a dual quaternions. + * Adds right hand operand from left hand operand. + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * double scalar = 2.0; + * std::cout << scalar + p << std::endl; //[3.0, 2, 3, 4, 5, 6, 7, 8] + * ``` + * @note the type of scalar should be equal to the dual quaternion. + */ + template + friend DualQuat cv::operator+(const T s, const DualQuat&); + + /** + * @brief Addition operator of a dual quaternions and a scalar. + * Adds right hand operand from left hand operand. + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * double scalar = 2.0; + * std::cout << p + scalar << std::endl; //[3.0, 2, 3, 4, 5, 6, 7, 8] + * ``` + * @note the type of scalar should be equal to the dual quaternion. + */ + template + friend DualQuat cv::operator+(const DualQuat&, const T s); + + /** + * @brief Multiplication operator of a scalar and a dual quaternions. + * It multiplies right operand with the left operand and assign the result to left operand. + * + * Rule of dual quaternion multiplication with a scalar: + * \f[ + * \begin{equation} + * \begin{split} + * p * s &= [w, x, y, z, w\_, x\_, y\_, z\_] * s\\ + * &=[w s, x s, y s, z s, w\_ \space s, x\_ \space s, y\_ \space s, z\_ \space s]. + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * double s = 2.0; + * std::cout << s * p << std::endl; //[2, 4, 6, 8, 10, 12, 14, 16] + * ``` + * @note the type of scalar should be equal to the dual quaternion. + */ + template + friend DualQuat cv::operator*(const T s, const DualQuat&); + + /** + * @brief Subtraction operator of a dual quaternion and a scalar. + * Subtracts right hand operand from left hand operand. + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * double scalar = 2.0; + * std::cout << p - scalar << std::endl; //[-1, 2, 3, 4, 5, 6, 7, 8] + * ``` + * @note the type of scalar should be equal to the dual quaternion. + */ + template + friend DualQuat cv::operator-(const DualQuat&, const T s); + + /** + * @brief Subtraction operator of a scalar and a dual quaternions. + * Subtracts right hand operand from left hand operand. + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * double scalar = 2.0; + * std::cout << scalar - p << std::endl; //[1.0, -2, -3, -4, -5, -6, -7, -8] + * ``` + * @note the type of scalar should be equal to the dual quaternion. + */ + template + friend DualQuat cv::operator-(const T s, const DualQuat&); + + /** + * @brief Multiplication operator of a dual quaternions and a scalar. + * It multiplies right operand with the left operand and assign the result to left operand. + * + * Rule of dual quaternion multiplication with a scalar: + * \f[ + * \begin{equation} + * \begin{split} + * p * s &= [w, x, y, z, w\_, x\_, y\_, z\_] * s\\ + * &=[w s, x s, y s, z s, w\_ \space s, x\_ \space s, y\_ \space s, z\_ \space s]. + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * double s = 2.0; + * std::cout << p * s << std::endl; //[2, 4, 6, 8, 10, 12, 14, 16] + * ``` + * @note the type of scalar should be equal to the dual quaternion. + */ + template + friend DualQuat cv::operator*(const DualQuat&, const T s); + + template + friend std::ostream& cv::operator<<(std::ostream&, const DualQuat&); + +}; + +using DualQuatd = DualQuat; +using DualQuatf = DualQuat; + +//! @} core +}//namespace + +#include "dualquaternion.inl.hpp" + +#endif /* OPENCV_CORE_QUATERNION_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/dualquaternion.inl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/dualquaternion.inl.hpp index 1a68f12d30..6d3d1f0f2e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/dualquaternion.inl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/dualquaternion.inl.hpp @@ -1,487 +1,487 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2020, Huawei Technologies Co., Ltd. All rights reserved. -// Third party copyrights are property of their respective owners. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Author: Liangqian Kong -// Longbu Wang - -#ifndef OPENCV_CORE_DUALQUATERNION_INL_HPP -#define OPENCV_CORE_DUALQUATERNION_INL_HPP - -#ifndef OPENCV_CORE_DUALQUATERNION_HPP -#error This is not a standalone header. Include dualquaternion.hpp instead. -#endif - -/////////////////////////////////////////////////////////////////////////////////////// -//Implementation -namespace cv { - -template -DualQuat::DualQuat():w(0), x(0), y(0), z(0), w_(0), x_(0), y_(0), z_(0){} - -template -DualQuat::DualQuat(const T vw, const T vx, const T vy, const T vz, const T _w, const T _x, const T _y, const T _z): - w(vw), x(vx), y(vy), z(vz), w_(_w), x_(_x), y_(_y), z_(_z){} - -template -DualQuat::DualQuat(const Vec &q):w(q[0]), x(q[1]), y(q[2]), z(q[3]), - w_(q[4]), x_(q[5]), y_(q[6]), z_(q[7]){} - -template -DualQuat DualQuat::createFromQuat(const Quat &realPart, const Quat &dualPart) -{ - T w = realPart.w; - T x = realPart.x; - T y = realPart.y; - T z = realPart.z; - T w_ = dualPart.w; - T x_ = dualPart.x; - T y_ = dualPart.y; - T z_ = dualPart.z; - return DualQuat(w, x, y, z, w_, x_, y_, z_); -} - -template -DualQuat DualQuat::createFromAngleAxisTrans(const T angle, const Vec &axis, const Vec &trans) -{ - Quat r = Quat::createFromAngleAxis(angle, axis); - Quat t{0, trans[0], trans[1], trans[2]}; - return createFromQuat(r, t * r * T(0.5)); -} - -template -DualQuat DualQuat::createFromMat(InputArray _R) -{ - CV_CheckTypeEQ(_R.type(), cv::traits::Type::value, ""); - if (_R.size() != Size(4, 4)) - { - CV_Error(Error::StsBadArg, "The input matrix must have 4 columns and 4 rows"); - } - Mat R = _R.getMat(); - Quat r = Quat::createFromRotMat(R.colRange(0, 3).rowRange(0, 3)); - Quat trans(0, R.at(0, 3), R.at(1, 3), R.at(2, 3)); - return createFromQuat(r, trans * r * T(0.5)); -} - -template -DualQuat DualQuat::createFromAffine3(const Affine3 &R) -{ - return createFromMat(R.matrix); -} - -template -DualQuat DualQuat::createFromPitch(const T angle, const T d, const Vec &axis, const Vec &moment) -{ - T half_angle = angle * T(0.5), half_d = d * T(0.5); - Quat qaxis = Quat(0, axis[0], axis[1], axis[2]).normalize(); - Quat qmoment = Quat(0, moment[0], moment[1], moment[2]); - qmoment -= qaxis * axis.dot(moment); - Quat dual = -half_d * std::sin(half_angle) + std::sin(half_angle) * qmoment + - half_d * std::cos(half_angle) * qaxis; - return createFromQuat(Quat::createFromAngleAxis(angle, axis), dual); -} - -template -inline bool DualQuat::operator==(const DualQuat &q) const -{ - return (abs(w - q.w) < CV_DUAL_QUAT_EPS && abs(x - q.x) < CV_DUAL_QUAT_EPS && - abs(y - q.y) < CV_DUAL_QUAT_EPS && abs(z - q.z) < CV_DUAL_QUAT_EPS && - abs(w_ - q.w_) < CV_DUAL_QUAT_EPS && abs(x_ - q.x_) < CV_DUAL_QUAT_EPS && - abs(y_ - q.y_) < CV_DUAL_QUAT_EPS && abs(z_ - q.z_) < CV_DUAL_QUAT_EPS); -} - -template -inline Quat DualQuat::getRealPart() const -{ - return Quat(w, x, y, z); -} - -template -inline Quat DualQuat::getDualPart() const -{ - return Quat(w_, x_, y_, z_); -} - -template -inline DualQuat conjugate(const DualQuat &dq) -{ - return dq.conjugate(); -} - -template -inline DualQuat DualQuat::conjugate() const -{ - return DualQuat(w, -x, -y, -z, w_, -x_, -y_, -z_); -} - -template -DualQuat DualQuat::norm() const -{ - Quat real = getRealPart(); - T realNorm = real.norm(); - Quat dual = getDualPart(); - if (realNorm < CV_DUAL_QUAT_EPS){ - return DualQuat(0, 0, 0, 0, 0, 0, 0, 0); - } - return DualQuat(realNorm, 0, 0, 0, real.dot(dual) / realNorm, 0, 0, 0); -} - -template -inline Quat DualQuat::getRotation(QuatAssumeType assumeUnit) const -{ - if (assumeUnit) - { - return getRealPart(); - } - return getRealPart().normalize(); -} - -template -inline Vec DualQuat::getTranslation(QuatAssumeType assumeUnit) const -{ - Quat trans = T(2.0) * (getDualPart() * getRealPart().inv(assumeUnit)); - return Vec{trans[1], trans[2], trans[3]}; -} - -template -DualQuat DualQuat::normalize() const -{ - Quat p = getRealPart(); - Quat q = getDualPart(); - T p_norm = p.norm(); - if (p_norm < CV_DUAL_QUAT_EPS) - { - CV_Error(Error::StsBadArg, "Cannot normalize this dual quaternion: the norm is too small."); - } - Quat p_nr = p / p_norm; - Quat q_nr = q / p_norm; - return createFromQuat(p_nr, q_nr - p_nr * p_nr.dot(q_nr)); -} - -template -inline T DualQuat::dot(DualQuat q) const -{ - return q.w * w + q.x * x + q.y * y + q.z * z + q.w_ * w_ + q.x_ * x_ + q.y_ * y_ + q.z_ * z_; -} - -template -inline DualQuat inv(const DualQuat &dq, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) -{ - return dq.inv(assumeUnit); -} - -template -inline DualQuat DualQuat::inv(QuatAssumeType assumeUnit) const -{ - Quat real = getRealPart(); - Quat dual = getDualPart(); - return createFromQuat(real.inv(assumeUnit), -real.inv(assumeUnit) * dual * real.inv(assumeUnit)); -} - -template -inline DualQuat DualQuat::operator-(const DualQuat &q) const -{ - return DualQuat(w - q.w, x - q.x, y - q.y, z - q.z, w_ - q.w_, x_ - q.x_, y_ - q.y_, z_ - q.z_); -} - -template -inline DualQuat DualQuat::operator-() const -{ - return DualQuat(-w, -x, -y, -z, -w_, -x_, -y_, -z_); -} - -template -inline DualQuat DualQuat::operator+(const DualQuat &q) const -{ - return DualQuat(w + q.w, x + q.x, y + q.y, z + q.z, w_ + q.w_, x_ + q.x_, y_ + q.y_, z_ + q.z_); -} - -template -inline DualQuat& DualQuat::operator+=(const DualQuat &q) -{ - *this = *this + q; - return *this; -} - -template -inline DualQuat DualQuat::operator*(const DualQuat &q) const -{ - Quat A = getRealPart(); - Quat B = getDualPart(); - Quat C = q.getRealPart(); - Quat D = q.getDualPart(); - return DualQuat::createFromQuat(A * C, A * D + B * C); -} - -template -inline DualQuat& DualQuat::operator*=(const DualQuat &q) -{ - *this = *this * q; - return *this; -} - -template -inline DualQuat operator+(const T a, const DualQuat &q) -{ - return DualQuat(a + q.w, q.x, q.y, q.z, q.w_, q.x_, q.y_, q.z_); -} - -template -inline DualQuat operator+(const DualQuat &q, const T a) -{ - return DualQuat(a + q.w, q.x, q.y, q.z, q.w_, q.x_, q.y_, q.z_); -} - -template -inline DualQuat operator-(const DualQuat &q, const T a) -{ - return DualQuat(q.w - a, q.x, q.y, q.z, q.w_, q.x_, q.y_, q.z_); -} - -template -inline DualQuat& DualQuat::operator-=(const DualQuat &q) -{ - *this = *this - q; - return *this; -} - -template -inline DualQuat operator-(const T a, const DualQuat &q) -{ - return DualQuat(a - q.w, -q.x, -q.y, -q.z, -q.w_, -q.x_, -q.y_, -q.z_); -} - -template -inline DualQuat operator*(const T a, const DualQuat &q) -{ - return DualQuat(q.w * a, q.x * a, q.y * a, q.z * a, q.w_ * a, q.x_ * a, q.y_ * a, q.z_ * a); -} - -template -inline DualQuat operator*(const DualQuat &q, const T a) -{ - return DualQuat(q.w * a, q.x * a, q.y * a, q.z * a, q.w_ * a, q.x_ * a, q.y_ * a, q.z_ * a); -} - -template -inline DualQuat DualQuat::operator/(const T a) const -{ - return DualQuat(w / a, x / a, y / a, z / a, w_ / a, x_ / a, y_ / a, z_ / a); -} - -template -inline DualQuat DualQuat::operator/(const DualQuat &q) const -{ - return *this * q.inv(); -} - -template -inline DualQuat& DualQuat::operator/=(const DualQuat &q) -{ - *this = *this / q; - return *this; -} - -template -std::ostream & operator<<(std::ostream &os, const DualQuat &q) -{ - os << "DualQuat " << Vec{q.w, q.x, q.y, q.z, q.w_, q.x_, q.y_, q.z_}; - return os; -} - -template -inline DualQuat exp(const DualQuat &dq) -{ - return dq.exp(); -} - -namespace detail { - -template -Matx<_Tp, 4, 4> jacob_exp(const Quat<_Tp> &q) -{ - _Tp nv = std::sqrt(q.x * q.x + q.y * q.y + q.z * q.z); - _Tp sinc_nv = abs(nv) < cv::DualQuat<_Tp>::CV_DUAL_QUAT_EPS ? _Tp(1.0) - nv * nv * _Tp(1.0/6.0) : std::sin(nv) / nv; - _Tp csiii_nv = abs(nv) < cv::DualQuat<_Tp>::CV_DUAL_QUAT_EPS ? -_Tp(1.0/3.0) : (std::cos(nv) - sinc_nv) / nv / nv; - Matx<_Tp, 4, 4> J_exp_quat { - std::cos(nv), -sinc_nv * q.x, -sinc_nv * q.y, -sinc_nv * q.z, - sinc_nv * q.x, csiii_nv * q.x * q.x + sinc_nv, csiii_nv * q.x * q.y, csiii_nv * q.x * q.z, - sinc_nv * q.y, csiii_nv * q.y * q.x, csiii_nv * q.y * q.y + sinc_nv, csiii_nv * q.y * q.z, - sinc_nv * q.z, csiii_nv * q.z * q.x, csiii_nv * q.z * q.y, csiii_nv * q.z * q.z + sinc_nv - }; - return std::exp(q.w) * J_exp_quat; -} - -} // namespace detail - -template -DualQuat DualQuat::exp() const -{ - Quat real = getRealPart(); - return createFromQuat(real.exp(), Quat(detail::jacob_exp(real) * getDualPart().toVec())); -} - -template -DualQuat log(const DualQuat &dq, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) -{ - return dq.log(assumeUnit); -} - -template -DualQuat DualQuat::log(QuatAssumeType assumeUnit) const -{ - Quat plog = getRealPart().log(assumeUnit); - Matx jacob = detail::jacob_exp(plog); - return createFromQuat(plog, Quat(jacob.inv() * getDualPart().toVec())); -} - -template -inline DualQuat power(const DualQuat &dq, const T t, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) -{ - return dq.power(t, assumeUnit); -} - -template -inline DualQuat DualQuat::power(const T t, QuatAssumeType assumeUnit) const -{ - return (t * log(assumeUnit)).exp(); -} - -template -inline DualQuat power(const DualQuat &p, const DualQuat &q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) -{ - return p.power(q, assumeUnit); -} - -template -inline DualQuat DualQuat::power(const DualQuat &q, QuatAssumeType assumeUnit) const -{ - return (q * log(assumeUnit)).exp(); -} - -template -inline Vec DualQuat::toVec() const -{ - return Vec(w, x, y, z, w_, x_, y_, z_); -} - -template -Affine3 DualQuat::toAffine3(QuatAssumeType assumeUnit) const -{ - return Affine3(toMat(assumeUnit)); -} - -template -Matx DualQuat::toMat(QuatAssumeType assumeUnit) const -{ - Matx rot44 = getRotation(assumeUnit).toRotMat4x4(); - Vec translation = getTranslation(assumeUnit); - rot44(0, 3) = translation[0]; - rot44(1, 3) = translation[1]; - rot44(2, 3) = translation[2]; - return rot44; -} - -template -DualQuat DualQuat::sclerp(const DualQuat &q0, const DualQuat &q1, const T t, bool directChange, QuatAssumeType assumeUnit) -{ - DualQuat v0(q0), v1(q1); - if (!assumeUnit) - { - v0 = v0.normalize(); - v1 = v1.normalize(); - } - Quat v0Real = v0.getRealPart(); - Quat v1Real = v1.getRealPart(); - if (directChange && v1Real.dot(v0Real) < 0) - { - v0 = -v0; - } - DualQuat v0inv1 = v0.inv() * v1; - return v0 * v0inv1.power(t, QUAT_ASSUME_UNIT); -} - -template -DualQuat DualQuat::dqblend(const DualQuat &q1, const DualQuat &q2, const T t, QuatAssumeType assumeUnit) -{ - DualQuat v1(q1), v2(q2); - if (!assumeUnit) - { - v1 = v1.normalize(); - v2 = v2.normalize(); - } - if (v1.getRotation(assumeUnit).dot(v2.getRotation(assumeUnit)) < 0) - { - return ((1 - t) * v1 - t * v2).normalize(); - } - return ((1 - t) * v1 + t * v2).normalize(); -} - -template -DualQuat DualQuat::gdqblend(InputArray _dualquat, InputArray _weight, QuatAssumeType assumeUnit) -{ - CV_CheckTypeEQ(_weight.type(), cv::traits::Type::value, ""); - CV_CheckTypeEQ(_dualquat.type(), CV_MAKETYPE(CV_MAT_DEPTH(cv::traits::Type::value), 8), ""); - Size dq_s = _dualquat.size(); - if (dq_s != _weight.size() || (dq_s.height != 1 && dq_s.width != 1)) - { - CV_Error(Error::StsBadArg, "The size of weight must be the same as dualquat, both of them should be (1, n) or (n, 1)"); - } - Mat dualquat = _dualquat.getMat(), weight = _weight.getMat(); - const int cn = std::max(dq_s.width, dq_s.height); - if (!assumeUnit) - { - for (int i = 0; i < cn; ++i) - { - dualquat.at>(i) = DualQuat{dualquat.at>(i)}.normalize().toVec(); - } - } - Vec dq_blend = dualquat.at>(0) * weight.at(0); - Quat q0 = DualQuat {dualquat.at>(0)}.getRotation(assumeUnit); - for (int i = 1; i < cn; ++i) - { - T k = q0.dot(DualQuat{dualquat.at>(i)}.getRotation(assumeUnit)) < 0 ? -1: 1; - dq_blend = dq_blend + dualquat.at>(i) * k * weight.at(i); - } - return DualQuat{dq_blend}.normalize(); -} - -template -template -DualQuat DualQuat::gdqblend(const Vec, cn> &_dualquat, InputArray _weight, QuatAssumeType assumeUnit) -{ - Vec, cn> dualquat(_dualquat); - if (cn == 0) - { - return DualQuat(1, 0, 0, 0, 0, 0, 0, 0); - } - Mat dualquat_mat(cn, 1, CV_64FC(8)); - for (int i = 0; i < cn ; ++i) - { - dualquat_mat.at>(i) = dualquat[i].toVec(); - } - return gdqblend(dualquat_mat, _weight, assumeUnit); -} - -} //namespace cv - -#endif /*OPENCV_CORE_DUALQUATERNION_INL_HPP*/ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2020, Huawei Technologies Co., Ltd. All rights reserved. +// Third party copyrights are property of their respective owners. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Author: Liangqian Kong +// Longbu Wang + +#ifndef OPENCV_CORE_DUALQUATERNION_INL_HPP +#define OPENCV_CORE_DUALQUATERNION_INL_HPP + +#ifndef OPENCV_CORE_DUALQUATERNION_HPP +#error This is not a standalone header. Include dualquaternion.hpp instead. +#endif + +/////////////////////////////////////////////////////////////////////////////////////// +//Implementation +namespace cv { + +template +DualQuat::DualQuat():w(0), x(0), y(0), z(0), w_(0), x_(0), y_(0), z_(0){} + +template +DualQuat::DualQuat(const T vw, const T vx, const T vy, const T vz, const T _w, const T _x, const T _y, const T _z): + w(vw), x(vx), y(vy), z(vz), w_(_w), x_(_x), y_(_y), z_(_z){} + +template +DualQuat::DualQuat(const Vec &q):w(q[0]), x(q[1]), y(q[2]), z(q[3]), + w_(q[4]), x_(q[5]), y_(q[6]), z_(q[7]){} + +template +DualQuat DualQuat::createFromQuat(const Quat &realPart, const Quat &dualPart) +{ + T w = realPart.w; + T x = realPart.x; + T y = realPart.y; + T z = realPart.z; + T w_ = dualPart.w; + T x_ = dualPart.x; + T y_ = dualPart.y; + T z_ = dualPart.z; + return DualQuat(w, x, y, z, w_, x_, y_, z_); +} + +template +DualQuat DualQuat::createFromAngleAxisTrans(const T angle, const Vec &axis, const Vec &trans) +{ + Quat r = Quat::createFromAngleAxis(angle, axis); + Quat t{0, trans[0], trans[1], trans[2]}; + return createFromQuat(r, t * r * T(0.5)); +} + +template +DualQuat DualQuat::createFromMat(InputArray _R) +{ + CV_CheckTypeEQ(_R.type(), cv::traits::Type::value, ""); + if (_R.size() != Size(4, 4)) + { + CV_Error(Error::StsBadArg, "The input matrix must have 4 columns and 4 rows"); + } + Mat R = _R.getMat(); + Quat r = Quat::createFromRotMat(R.colRange(0, 3).rowRange(0, 3)); + Quat trans(0, R.at(0, 3), R.at(1, 3), R.at(2, 3)); + return createFromQuat(r, trans * r * T(0.5)); +} + +template +DualQuat DualQuat::createFromAffine3(const Affine3 &R) +{ + return createFromMat(R.matrix); +} + +template +DualQuat DualQuat::createFromPitch(const T angle, const T d, const Vec &axis, const Vec &moment) +{ + T half_angle = angle * T(0.5), half_d = d * T(0.5); + Quat qaxis = Quat(0, axis[0], axis[1], axis[2]).normalize(); + Quat qmoment = Quat(0, moment[0], moment[1], moment[2]); + qmoment -= qaxis * axis.dot(moment); + Quat dual = -half_d * std::sin(half_angle) + std::sin(half_angle) * qmoment + + half_d * std::cos(half_angle) * qaxis; + return createFromQuat(Quat::createFromAngleAxis(angle, axis), dual); +} + +template +inline bool DualQuat::operator==(const DualQuat &q) const +{ + return (abs(w - q.w) < CV_DUAL_QUAT_EPS && abs(x - q.x) < CV_DUAL_QUAT_EPS && + abs(y - q.y) < CV_DUAL_QUAT_EPS && abs(z - q.z) < CV_DUAL_QUAT_EPS && + abs(w_ - q.w_) < CV_DUAL_QUAT_EPS && abs(x_ - q.x_) < CV_DUAL_QUAT_EPS && + abs(y_ - q.y_) < CV_DUAL_QUAT_EPS && abs(z_ - q.z_) < CV_DUAL_QUAT_EPS); +} + +template +inline Quat DualQuat::getRealPart() const +{ + return Quat(w, x, y, z); +} + +template +inline Quat DualQuat::getDualPart() const +{ + return Quat(w_, x_, y_, z_); +} + +template +inline DualQuat conjugate(const DualQuat &dq) +{ + return dq.conjugate(); +} + +template +inline DualQuat DualQuat::conjugate() const +{ + return DualQuat(w, -x, -y, -z, w_, -x_, -y_, -z_); +} + +template +DualQuat DualQuat::norm() const +{ + Quat real = getRealPart(); + T realNorm = real.norm(); + Quat dual = getDualPart(); + if (realNorm < CV_DUAL_QUAT_EPS){ + return DualQuat(0, 0, 0, 0, 0, 0, 0, 0); + } + return DualQuat(realNorm, 0, 0, 0, real.dot(dual) / realNorm, 0, 0, 0); +} + +template +inline Quat DualQuat::getRotation(QuatAssumeType assumeUnit) const +{ + if (assumeUnit) + { + return getRealPart(); + } + return getRealPart().normalize(); +} + +template +inline Vec DualQuat::getTranslation(QuatAssumeType assumeUnit) const +{ + Quat trans = T(2.0) * (getDualPart() * getRealPart().inv(assumeUnit)); + return Vec{trans[1], trans[2], trans[3]}; +} + +template +DualQuat DualQuat::normalize() const +{ + Quat p = getRealPart(); + Quat q = getDualPart(); + T p_norm = p.norm(); + if (p_norm < CV_DUAL_QUAT_EPS) + { + CV_Error(Error::StsBadArg, "Cannot normalize this dual quaternion: the norm is too small."); + } + Quat p_nr = p / p_norm; + Quat q_nr = q / p_norm; + return createFromQuat(p_nr, q_nr - p_nr * p_nr.dot(q_nr)); +} + +template +inline T DualQuat::dot(DualQuat q) const +{ + return q.w * w + q.x * x + q.y * y + q.z * z + q.w_ * w_ + q.x_ * x_ + q.y_ * y_ + q.z_ * z_; +} + +template +inline DualQuat inv(const DualQuat &dq, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) +{ + return dq.inv(assumeUnit); +} + +template +inline DualQuat DualQuat::inv(QuatAssumeType assumeUnit) const +{ + Quat real = getRealPart(); + Quat dual = getDualPart(); + return createFromQuat(real.inv(assumeUnit), -real.inv(assumeUnit) * dual * real.inv(assumeUnit)); +} + +template +inline DualQuat DualQuat::operator-(const DualQuat &q) const +{ + return DualQuat(w - q.w, x - q.x, y - q.y, z - q.z, w_ - q.w_, x_ - q.x_, y_ - q.y_, z_ - q.z_); +} + +template +inline DualQuat DualQuat::operator-() const +{ + return DualQuat(-w, -x, -y, -z, -w_, -x_, -y_, -z_); +} + +template +inline DualQuat DualQuat::operator+(const DualQuat &q) const +{ + return DualQuat(w + q.w, x + q.x, y + q.y, z + q.z, w_ + q.w_, x_ + q.x_, y_ + q.y_, z_ + q.z_); +} + +template +inline DualQuat& DualQuat::operator+=(const DualQuat &q) +{ + *this = *this + q; + return *this; +} + +template +inline DualQuat DualQuat::operator*(const DualQuat &q) const +{ + Quat A = getRealPart(); + Quat B = getDualPart(); + Quat C = q.getRealPart(); + Quat D = q.getDualPart(); + return DualQuat::createFromQuat(A * C, A * D + B * C); +} + +template +inline DualQuat& DualQuat::operator*=(const DualQuat &q) +{ + *this = *this * q; + return *this; +} + +template +inline DualQuat operator+(const T a, const DualQuat &q) +{ + return DualQuat(a + q.w, q.x, q.y, q.z, q.w_, q.x_, q.y_, q.z_); +} + +template +inline DualQuat operator+(const DualQuat &q, const T a) +{ + return DualQuat(a + q.w, q.x, q.y, q.z, q.w_, q.x_, q.y_, q.z_); +} + +template +inline DualQuat operator-(const DualQuat &q, const T a) +{ + return DualQuat(q.w - a, q.x, q.y, q.z, q.w_, q.x_, q.y_, q.z_); +} + +template +inline DualQuat& DualQuat::operator-=(const DualQuat &q) +{ + *this = *this - q; + return *this; +} + +template +inline DualQuat operator-(const T a, const DualQuat &q) +{ + return DualQuat(a - q.w, -q.x, -q.y, -q.z, -q.w_, -q.x_, -q.y_, -q.z_); +} + +template +inline DualQuat operator*(const T a, const DualQuat &q) +{ + return DualQuat(q.w * a, q.x * a, q.y * a, q.z * a, q.w_ * a, q.x_ * a, q.y_ * a, q.z_ * a); +} + +template +inline DualQuat operator*(const DualQuat &q, const T a) +{ + return DualQuat(q.w * a, q.x * a, q.y * a, q.z * a, q.w_ * a, q.x_ * a, q.y_ * a, q.z_ * a); +} + +template +inline DualQuat DualQuat::operator/(const T a) const +{ + return DualQuat(w / a, x / a, y / a, z / a, w_ / a, x_ / a, y_ / a, z_ / a); +} + +template +inline DualQuat DualQuat::operator/(const DualQuat &q) const +{ + return *this * q.inv(); +} + +template +inline DualQuat& DualQuat::operator/=(const DualQuat &q) +{ + *this = *this / q; + return *this; +} + +template +std::ostream & operator<<(std::ostream &os, const DualQuat &q) +{ + os << "DualQuat " << Vec{q.w, q.x, q.y, q.z, q.w_, q.x_, q.y_, q.z_}; + return os; +} + +template +inline DualQuat exp(const DualQuat &dq) +{ + return dq.exp(); +} + +namespace detail { + +template +Matx<_Tp, 4, 4> jacob_exp(const Quat<_Tp> &q) +{ + _Tp nv = std::sqrt(q.x * q.x + q.y * q.y + q.z * q.z); + _Tp sinc_nv = abs(nv) < cv::DualQuat<_Tp>::CV_DUAL_QUAT_EPS ? _Tp(1.0) - nv * nv * _Tp(1.0/6.0) : std::sin(nv) / nv; + _Tp csiii_nv = abs(nv) < cv::DualQuat<_Tp>::CV_DUAL_QUAT_EPS ? -_Tp(1.0/3.0) : (std::cos(nv) - sinc_nv) / nv / nv; + Matx<_Tp, 4, 4> J_exp_quat { + std::cos(nv), -sinc_nv * q.x, -sinc_nv * q.y, -sinc_nv * q.z, + sinc_nv * q.x, csiii_nv * q.x * q.x + sinc_nv, csiii_nv * q.x * q.y, csiii_nv * q.x * q.z, + sinc_nv * q.y, csiii_nv * q.y * q.x, csiii_nv * q.y * q.y + sinc_nv, csiii_nv * q.y * q.z, + sinc_nv * q.z, csiii_nv * q.z * q.x, csiii_nv * q.z * q.y, csiii_nv * q.z * q.z + sinc_nv + }; + return std::exp(q.w) * J_exp_quat; +} + +} // namespace detail + +template +DualQuat DualQuat::exp() const +{ + Quat real = getRealPart(); + return createFromQuat(real.exp(), Quat(detail::jacob_exp(real) * getDualPart().toVec())); +} + +template +DualQuat log(const DualQuat &dq, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) +{ + return dq.log(assumeUnit); +} + +template +DualQuat DualQuat::log(QuatAssumeType assumeUnit) const +{ + Quat plog = getRealPart().log(assumeUnit); + Matx jacob = detail::jacob_exp(plog); + return createFromQuat(plog, Quat(jacob.inv() * getDualPart().toVec())); +} + +template +inline DualQuat power(const DualQuat &dq, const T t, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) +{ + return dq.power(t, assumeUnit); +} + +template +inline DualQuat DualQuat::power(const T t, QuatAssumeType assumeUnit) const +{ + return (t * log(assumeUnit)).exp(); +} + +template +inline DualQuat power(const DualQuat &p, const DualQuat &q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) +{ + return p.power(q, assumeUnit); +} + +template +inline DualQuat DualQuat::power(const DualQuat &q, QuatAssumeType assumeUnit) const +{ + return (q * log(assumeUnit)).exp(); +} + +template +inline Vec DualQuat::toVec() const +{ + return Vec(w, x, y, z, w_, x_, y_, z_); +} + +template +Affine3 DualQuat::toAffine3(QuatAssumeType assumeUnit) const +{ + return Affine3(toMat(assumeUnit)); +} + +template +Matx DualQuat::toMat(QuatAssumeType assumeUnit) const +{ + Matx rot44 = getRotation(assumeUnit).toRotMat4x4(); + Vec translation = getTranslation(assumeUnit); + rot44(0, 3) = translation[0]; + rot44(1, 3) = translation[1]; + rot44(2, 3) = translation[2]; + return rot44; +} + +template +DualQuat DualQuat::sclerp(const DualQuat &q0, const DualQuat &q1, const T t, bool directChange, QuatAssumeType assumeUnit) +{ + DualQuat v0(q0), v1(q1); + if (!assumeUnit) + { + v0 = v0.normalize(); + v1 = v1.normalize(); + } + Quat v0Real = v0.getRealPart(); + Quat v1Real = v1.getRealPart(); + if (directChange && v1Real.dot(v0Real) < 0) + { + v0 = -v0; + } + DualQuat v0inv1 = v0.inv() * v1; + return v0 * v0inv1.power(t, QUAT_ASSUME_UNIT); +} + +template +DualQuat DualQuat::dqblend(const DualQuat &q1, const DualQuat &q2, const T t, QuatAssumeType assumeUnit) +{ + DualQuat v1(q1), v2(q2); + if (!assumeUnit) + { + v1 = v1.normalize(); + v2 = v2.normalize(); + } + if (v1.getRotation(assumeUnit).dot(v2.getRotation(assumeUnit)) < 0) + { + return ((1 - t) * v1 - t * v2).normalize(); + } + return ((1 - t) * v1 + t * v2).normalize(); +} + +template +DualQuat DualQuat::gdqblend(InputArray _dualquat, InputArray _weight, QuatAssumeType assumeUnit) +{ + CV_CheckTypeEQ(_weight.type(), cv::traits::Type::value, ""); + CV_CheckTypeEQ(_dualquat.type(), CV_MAKETYPE(CV_MAT_DEPTH(cv::traits::Type::value), 8), ""); + Size dq_s = _dualquat.size(); + if (dq_s != _weight.size() || (dq_s.height != 1 && dq_s.width != 1)) + { + CV_Error(Error::StsBadArg, "The size of weight must be the same as dualquat, both of them should be (1, n) or (n, 1)"); + } + Mat dualquat = _dualquat.getMat(), weight = _weight.getMat(); + const int cn = std::max(dq_s.width, dq_s.height); + if (!assumeUnit) + { + for (int i = 0; i < cn; ++i) + { + dualquat.at>(i) = DualQuat{dualquat.at>(i)}.normalize().toVec(); + } + } + Vec dq_blend = dualquat.at>(0) * weight.at(0); + Quat q0 = DualQuat {dualquat.at>(0)}.getRotation(assumeUnit); + for (int i = 1; i < cn; ++i) + { + T k = q0.dot(DualQuat{dualquat.at>(i)}.getRotation(assumeUnit)) < 0 ? -1: 1; + dq_blend = dq_blend + dualquat.at>(i) * k * weight.at(i); + } + return DualQuat{dq_blend}.normalize(); +} + +template +template +DualQuat DualQuat::gdqblend(const Vec, cn> &_dualquat, InputArray _weight, QuatAssumeType assumeUnit) +{ + Vec, cn> dualquat(_dualquat); + if (cn == 0) + { + return DualQuat(1, 0, 0, 0, 0, 0, 0, 0); + } + Mat dualquat_mat(cn, 1, CV_64FC(8)); + for (int i = 0; i < cn ; ++i) + { + dualquat_mat.at>(i) = dualquat[i].toVec(); + } + return gdqblend(dualquat_mat, _weight, assumeUnit); +} + +} //namespace cv + +#endif /*OPENCV_CORE_DUALQUATERNION_INL_HPP*/ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/eigen.hpp b/3rdParty/opencv-4.11.0/opencv2/core/eigen.hpp index d4b1774cf9..ad3c84225f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/eigen.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/eigen.hpp @@ -1,425 +1,425 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - - -#ifndef OPENCV_CORE_EIGEN_HPP -#define OPENCV_CORE_EIGEN_HPP - -#ifndef EIGEN_WORLD_VERSION -#error "Wrong usage of OpenCV's Eigen utility header. Include Eigen's headers first. See https://github.com/opencv/opencv/issues/17366" -#endif - -#include "opencv2/core.hpp" - -#if defined _MSC_VER && _MSC_VER >= 1200 -#ifndef NOMINMAX -#define NOMINMAX // fix https://github.com/opencv/opencv/issues/17548 -#endif -#pragma warning( disable: 4714 ) //__forceinline is not inlined -#pragma warning( disable: 4127 ) //conditional expression is constant -#pragma warning( disable: 4244 ) //conversion from '__int64' to 'int', possible loss of data -#endif - -#if !defined(OPENCV_DISABLE_EIGEN_TENSOR_SUPPORT) -#if EIGEN_WORLD_VERSION == 3 && EIGEN_MAJOR_VERSION >= 3 -#include -#define OPENCV_EIGEN_TENSOR_SUPPORT 1 -#endif // EIGEN_WORLD_VERSION == 3 && EIGEN_MAJOR_VERSION >= 3 -#endif // !defined(OPENCV_DISABLE_EIGEN_TENSOR_SUPPORT) - -namespace cv -{ - -/** @addtogroup core_eigen -These functions are provided for OpenCV-Eigen interoperability. They convert `Mat` -objects to corresponding `Eigen::Matrix` objects and vice-versa. Consult the [Eigen -documentation](https://eigen.tuxfamily.org/dox/group__TutorialMatrixClass.html) for -information about the `Matrix` template type. - -@note Using these functions requires the `Eigen/Dense` or similar header to be -included before this header. -*/ -//! @{ - -#if defined(OPENCV_EIGEN_TENSOR_SUPPORT) || defined(CV_DOXYGEN) -/** @brief Converts an Eigen::Tensor to a cv::Mat. - -The method converts an Eigen::Tensor with shape (H x W x C) to a cv::Mat where: - H = number of rows - W = number of columns - C = number of channels - -Usage: -\code -Eigen::Tensor a_tensor(...); -// populate tensor with values -Mat a_mat; -eigen2cv(a_tensor, a_mat); -\endcode -*/ -template static inline -void eigen2cv( const Eigen::Tensor<_Tp, 3, _layout> &src, OutputArray dst ) -{ - if( !(_layout & Eigen::RowMajorBit) ) - { - const std::array shuffle{2, 1, 0}; - Eigen::Tensor<_Tp, 3, !_layout> row_major_tensor = src.swap_layout().shuffle(shuffle); - Mat _src(src.dimension(0), src.dimension(1), CV_MAKETYPE(DataType<_Tp>::type, src.dimension(2)), row_major_tensor.data()); - _src.copyTo(dst); - } - else - { - Mat _src(src.dimension(0), src.dimension(1), CV_MAKETYPE(DataType<_Tp>::type, src.dimension(2)), (void *)src.data()); - _src.copyTo(dst); - } -} - -/** @brief Converts a cv::Mat to an Eigen::Tensor. - -The method converts a cv::Mat to an Eigen Tensor with shape (H x W x C) where: - H = number of rows - W = number of columns - C = number of channels - -Usage: -\code -Mat a_mat(...); -// populate Mat with values -Eigen::Tensor a_tensor(...); -cv2eigen(a_mat, a_tensor); -\endcode -*/ -template static inline -void cv2eigen( const Mat &src, Eigen::Tensor<_Tp, 3, _layout> &dst ) -{ - if( !(_layout & Eigen::RowMajorBit) ) - { - Eigen::Tensor<_Tp, 3, !_layout> row_major_tensor(src.rows, src.cols, src.channels()); - Mat _dst(src.rows, src.cols, CV_MAKETYPE(DataType<_Tp>::type, src.channels()), row_major_tensor.data()); - if (src.type() == _dst.type()) - src.copyTo(_dst); - else - src.convertTo(_dst, _dst.type()); - const std::array shuffle{2, 1, 0}; - dst = row_major_tensor.swap_layout().shuffle(shuffle); - } - else - { - dst.resize(src.rows, src.cols, src.channels()); - Mat _dst(src.rows, src.cols, CV_MAKETYPE(DataType<_Tp>::type, src.channels()), dst.data()); - if (src.type() == _dst.type()) - src.copyTo(_dst); - else - src.convertTo(_dst, _dst.type()); - } -} - -/** @brief Maps cv::Mat data to an Eigen::TensorMap. - -The method wraps an existing Mat data array with an Eigen TensorMap of shape (H x W x C) where: - H = number of rows - W = number of columns - C = number of channels - -Explicit instantiation of the return type is required. - -@note Caller should be aware of the lifetime of the cv::Mat instance and take appropriate safety measures. -The cv::Mat instance will retain ownership of the data and the Eigen::TensorMap will lose access when the cv::Mat data is deallocated. - -The example below initializes a cv::Mat and produces an Eigen::TensorMap: -\code -float arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; -Mat a_mat(2, 2, CV_32FC3, arr); -Eigen::TensorMap> a_tensormap = cv2eigen_tensormap(a_mat); -\endcode -*/ -template static inline -Eigen::TensorMap> cv2eigen_tensormap(InputArray src) -{ - Mat mat = src.getMat(); - CV_CheckTypeEQ(mat.type(), CV_MAKETYPE(traits::Type<_Tp>::value, mat.channels()), ""); - return Eigen::TensorMap>((_Tp *)mat.data, mat.rows, mat.cols, mat.channels()); -} -#endif // OPENCV_EIGEN_TENSOR_SUPPORT - -template static inline -void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, OutputArray dst ) -{ - if( !(src.Flags & Eigen::RowMajorBit) ) - { - Mat _src(src.cols(), src.rows(), traits::Type<_Tp>::value, - (void*)src.data(), src.outerStride()*sizeof(_Tp)); - transpose(_src, dst); - } - else - { - Mat _src(src.rows(), src.cols(), traits::Type<_Tp>::value, - (void*)src.data(), src.outerStride()*sizeof(_Tp)); - _src.copyTo(dst); - } -} - -// Matx case -template static inline -void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, - Matx<_Tp, _rows, _cols>& dst ) -{ - if( !(src.Flags & Eigen::RowMajorBit) ) - { - dst = Matx<_Tp, _cols, _rows>(static_cast(src.data())).t(); - } - else - { - dst = Matx<_Tp, _rows, _cols>(static_cast(src.data())); - } -} - -template static inline -void cv2eigen( const Mat& src, - Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& dst ) -{ - CV_DbgAssert(src.rows == _rows && src.cols == _cols); - if( !(dst.Flags & Eigen::RowMajorBit) ) - { - const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - if( src.type() == _dst.type() ) - transpose(src, _dst); - else if( src.cols == src.rows ) - { - src.convertTo(_dst, _dst.type()); - transpose(_dst, _dst); - } - else - Mat(src.t()).convertTo(_dst, _dst.type()); - } - else - { - const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - src.convertTo(_dst, _dst.type()); - } -} - -// Matx case -template static inline -void cv2eigen( const Matx<_Tp, _rows, _cols>& src, - Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& dst ) -{ - if( !(dst.Flags & Eigen::RowMajorBit) ) - { - const Mat _dst(_cols, _rows, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - transpose(src, _dst); - } - else - { - const Mat _dst(_rows, _cols, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - Mat(src).copyTo(_dst); - } -} - -template static inline -void cv2eigen( const Mat& src, - Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic>& dst ) -{ - dst.resize(src.rows, src.cols); - if( !(dst.Flags & Eigen::RowMajorBit) ) - { - const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - if( src.type() == _dst.type() ) - transpose(src, _dst); - else if( src.cols == src.rows ) - { - src.convertTo(_dst, _dst.type()); - transpose(_dst, _dst); - } - else - Mat(src.t()).convertTo(_dst, _dst.type()); - } - else - { - const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - src.convertTo(_dst, _dst.type()); - } -} - -template static inline -void cv2eigen( const Mat& src, - Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>& dst ) -{ - CV_CheckEQ(src.dims, 2, ""); - dst.resize(src.rows, src.cols); - const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - src.convertTo(_dst, _dst.type()); -} - -// Matx case -template static inline -void cv2eigen( const Matx<_Tp, _rows, _cols>& src, - Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic>& dst ) -{ - dst.resize(_rows, _cols); - if( !(dst.Flags & Eigen::RowMajorBit) ) - { - const Mat _dst(_cols, _rows, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - transpose(src, _dst); - } - else - { - const Mat _dst(_rows, _cols, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - Mat(src).copyTo(_dst); - } -} - -template static inline -void cv2eigen( const Matx<_Tp, _rows, _cols>& src, - Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>& dst ) -{ - CV_CheckEQ(src.dims, 2, ""); - dst.resize(_rows, _cols); - const Mat _dst(_rows, _cols, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - Mat(src).copyTo(_dst); -} - -template static inline -void cv2eigen( const Mat& src, - Eigen::Matrix<_Tp, Eigen::Dynamic, 1>& dst ) -{ - CV_Assert(src.cols == 1); - dst.resize(src.rows); - - if( !(dst.Flags & Eigen::RowMajorBit) ) - { - const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - if( src.type() == _dst.type() ) - transpose(src, _dst); - else - Mat(src.t()).convertTo(_dst, _dst.type()); - } - else - { - const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - src.convertTo(_dst, _dst.type()); - } -} - -// Matx case -template static inline -void cv2eigen( const Matx<_Tp, _rows, 1>& src, - Eigen::Matrix<_Tp, Eigen::Dynamic, 1>& dst ) -{ - dst.resize(_rows); - - if( !(dst.Flags & Eigen::RowMajorBit) ) - { - const Mat _dst(1, _rows, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - transpose(src, _dst); - } - else - { - const Mat _dst(_rows, 1, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - src.copyTo(_dst); - } -} - - -template static inline -void cv2eigen( const Mat& src, - Eigen::Matrix<_Tp, 1, Eigen::Dynamic>& dst ) -{ - CV_Assert(src.rows == 1); - dst.resize(src.cols); - if( !(dst.Flags & Eigen::RowMajorBit) ) - { - const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - if( src.type() == _dst.type() ) - transpose(src, _dst); - else - Mat(src.t()).convertTo(_dst, _dst.type()); - } - else - { - const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - src.convertTo(_dst, _dst.type()); - } -} - -//Matx -template static inline -void cv2eigen( const Matx<_Tp, 1, _cols>& src, - Eigen::Matrix<_Tp, 1, Eigen::Dynamic>& dst ) -{ - dst.resize(_cols); - if( !(dst.Flags & Eigen::RowMajorBit) ) - { - const Mat _dst(_cols, 1, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - transpose(src, _dst); - } - else - { - const Mat _dst(1, _cols, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - Mat(src).copyTo(_dst); - } -} - -//! @} - -} // cv - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + + +#ifndef OPENCV_CORE_EIGEN_HPP +#define OPENCV_CORE_EIGEN_HPP + +#ifndef EIGEN_WORLD_VERSION +#error "Wrong usage of OpenCV's Eigen utility header. Include Eigen's headers first. See https://github.com/opencv/opencv/issues/17366" +#endif + +#include "opencv2/core.hpp" + +#if defined _MSC_VER && _MSC_VER >= 1200 +#ifndef NOMINMAX +#define NOMINMAX // fix https://github.com/opencv/opencv/issues/17548 +#endif +#pragma warning( disable: 4714 ) //__forceinline is not inlined +#pragma warning( disable: 4127 ) //conditional expression is constant +#pragma warning( disable: 4244 ) //conversion from '__int64' to 'int', possible loss of data +#endif + +#if !defined(OPENCV_DISABLE_EIGEN_TENSOR_SUPPORT) +#if EIGEN_WORLD_VERSION == 3 && EIGEN_MAJOR_VERSION >= 3 +#include +#define OPENCV_EIGEN_TENSOR_SUPPORT 1 +#endif // EIGEN_WORLD_VERSION == 3 && EIGEN_MAJOR_VERSION >= 3 +#endif // !defined(OPENCV_DISABLE_EIGEN_TENSOR_SUPPORT) + +namespace cv +{ + +/** @addtogroup core_eigen +These functions are provided for OpenCV-Eigen interoperability. They convert `Mat` +objects to corresponding `Eigen::Matrix` objects and vice-versa. Consult the [Eigen +documentation](https://eigen.tuxfamily.org/dox/group__TutorialMatrixClass.html) for +information about the `Matrix` template type. + +@note Using these functions requires the `Eigen/Dense` or similar header to be +included before this header. +*/ +//! @{ + +#if defined(OPENCV_EIGEN_TENSOR_SUPPORT) || defined(CV_DOXYGEN) +/** @brief Converts an Eigen::Tensor to a cv::Mat. + +The method converts an Eigen::Tensor with shape (H x W x C) to a cv::Mat where: + H = number of rows + W = number of columns + C = number of channels + +Usage: +\code +Eigen::Tensor a_tensor(...); +// populate tensor with values +Mat a_mat; +eigen2cv(a_tensor, a_mat); +\endcode +*/ +template static inline +void eigen2cv( const Eigen::Tensor<_Tp, 3, _layout> &src, OutputArray dst ) +{ + if( !(_layout & Eigen::RowMajorBit) ) + { + const std::array shuffle{2, 1, 0}; + Eigen::Tensor<_Tp, 3, !_layout> row_major_tensor = src.swap_layout().shuffle(shuffle); + Mat _src(src.dimension(0), src.dimension(1), CV_MAKETYPE(DataType<_Tp>::type, src.dimension(2)), row_major_tensor.data()); + _src.copyTo(dst); + } + else + { + Mat _src(src.dimension(0), src.dimension(1), CV_MAKETYPE(DataType<_Tp>::type, src.dimension(2)), (void *)src.data()); + _src.copyTo(dst); + } +} + +/** @brief Converts a cv::Mat to an Eigen::Tensor. + +The method converts a cv::Mat to an Eigen Tensor with shape (H x W x C) where: + H = number of rows + W = number of columns + C = number of channels + +Usage: +\code +Mat a_mat(...); +// populate Mat with values +Eigen::Tensor a_tensor(...); +cv2eigen(a_mat, a_tensor); +\endcode +*/ +template static inline +void cv2eigen( const Mat &src, Eigen::Tensor<_Tp, 3, _layout> &dst ) +{ + if( !(_layout & Eigen::RowMajorBit) ) + { + Eigen::Tensor<_Tp, 3, !_layout> row_major_tensor(src.rows, src.cols, src.channels()); + Mat _dst(src.rows, src.cols, CV_MAKETYPE(DataType<_Tp>::type, src.channels()), row_major_tensor.data()); + if (src.type() == _dst.type()) + src.copyTo(_dst); + else + src.convertTo(_dst, _dst.type()); + const std::array shuffle{2, 1, 0}; + dst = row_major_tensor.swap_layout().shuffle(shuffle); + } + else + { + dst.resize(src.rows, src.cols, src.channels()); + Mat _dst(src.rows, src.cols, CV_MAKETYPE(DataType<_Tp>::type, src.channels()), dst.data()); + if (src.type() == _dst.type()) + src.copyTo(_dst); + else + src.convertTo(_dst, _dst.type()); + } +} + +/** @brief Maps cv::Mat data to an Eigen::TensorMap. + +The method wraps an existing Mat data array with an Eigen TensorMap of shape (H x W x C) where: + H = number of rows + W = number of columns + C = number of channels + +Explicit instantiation of the return type is required. + +@note Caller should be aware of the lifetime of the cv::Mat instance and take appropriate safety measures. +The cv::Mat instance will retain ownership of the data and the Eigen::TensorMap will lose access when the cv::Mat data is deallocated. + +The example below initializes a cv::Mat and produces an Eigen::TensorMap: +\code +float arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; +Mat a_mat(2, 2, CV_32FC3, arr); +Eigen::TensorMap> a_tensormap = cv2eigen_tensormap(a_mat); +\endcode +*/ +template static inline +Eigen::TensorMap> cv2eigen_tensormap(InputArray src) +{ + Mat mat = src.getMat(); + CV_CheckTypeEQ(mat.type(), CV_MAKETYPE(traits::Type<_Tp>::value, mat.channels()), ""); + return Eigen::TensorMap>((_Tp *)mat.data, mat.rows, mat.cols, mat.channels()); +} +#endif // OPENCV_EIGEN_TENSOR_SUPPORT + +template static inline +void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, OutputArray dst ) +{ + if( !(src.Flags & Eigen::RowMajorBit) ) + { + Mat _src(src.cols(), src.rows(), traits::Type<_Tp>::value, + (void*)src.data(), src.outerStride()*sizeof(_Tp)); + transpose(_src, dst); + } + else + { + Mat _src(src.rows(), src.cols(), traits::Type<_Tp>::value, + (void*)src.data(), src.outerStride()*sizeof(_Tp)); + _src.copyTo(dst); + } +} + +// Matx case +template static inline +void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, + Matx<_Tp, _rows, _cols>& dst ) +{ + if( !(src.Flags & Eigen::RowMajorBit) ) + { + dst = Matx<_Tp, _cols, _rows>(static_cast(src.data())).t(); + } + else + { + dst = Matx<_Tp, _rows, _cols>(static_cast(src.data())); + } +} + +template static inline +void cv2eigen( const Mat& src, + Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& dst ) +{ + CV_DbgAssert(src.rows == _rows && src.cols == _cols); + if( !(dst.Flags & Eigen::RowMajorBit) ) + { + const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + if( src.type() == _dst.type() ) + transpose(src, _dst); + else if( src.cols == src.rows ) + { + src.convertTo(_dst, _dst.type()); + transpose(_dst, _dst); + } + else + Mat(src.t()).convertTo(_dst, _dst.type()); + } + else + { + const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + src.convertTo(_dst, _dst.type()); + } +} + +// Matx case +template static inline +void cv2eigen( const Matx<_Tp, _rows, _cols>& src, + Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& dst ) +{ + if( !(dst.Flags & Eigen::RowMajorBit) ) + { + const Mat _dst(_cols, _rows, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + transpose(src, _dst); + } + else + { + const Mat _dst(_rows, _cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + Mat(src).copyTo(_dst); + } +} + +template static inline +void cv2eigen( const Mat& src, + Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic>& dst ) +{ + dst.resize(src.rows, src.cols); + if( !(dst.Flags & Eigen::RowMajorBit) ) + { + const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + if( src.type() == _dst.type() ) + transpose(src, _dst); + else if( src.cols == src.rows ) + { + src.convertTo(_dst, _dst.type()); + transpose(_dst, _dst); + } + else + Mat(src.t()).convertTo(_dst, _dst.type()); + } + else + { + const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + src.convertTo(_dst, _dst.type()); + } +} + +template static inline +void cv2eigen( const Mat& src, + Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>& dst ) +{ + CV_CheckEQ(src.dims, 2, ""); + dst.resize(src.rows, src.cols); + const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + src.convertTo(_dst, _dst.type()); +} + +// Matx case +template static inline +void cv2eigen( const Matx<_Tp, _rows, _cols>& src, + Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic>& dst ) +{ + dst.resize(_rows, _cols); + if( !(dst.Flags & Eigen::RowMajorBit) ) + { + const Mat _dst(_cols, _rows, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + transpose(src, _dst); + } + else + { + const Mat _dst(_rows, _cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + Mat(src).copyTo(_dst); + } +} + +template static inline +void cv2eigen( const Matx<_Tp, _rows, _cols>& src, + Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>& dst ) +{ + CV_CheckEQ(src.dims, 2, ""); + dst.resize(_rows, _cols); + const Mat _dst(_rows, _cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + Mat(src).copyTo(_dst); +} + +template static inline +void cv2eigen( const Mat& src, + Eigen::Matrix<_Tp, Eigen::Dynamic, 1>& dst ) +{ + CV_Assert(src.cols == 1); + dst.resize(src.rows); + + if( !(dst.Flags & Eigen::RowMajorBit) ) + { + const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + if( src.type() == _dst.type() ) + transpose(src, _dst); + else + Mat(src.t()).convertTo(_dst, _dst.type()); + } + else + { + const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + src.convertTo(_dst, _dst.type()); + } +} + +// Matx case +template static inline +void cv2eigen( const Matx<_Tp, _rows, 1>& src, + Eigen::Matrix<_Tp, Eigen::Dynamic, 1>& dst ) +{ + dst.resize(_rows); + + if( !(dst.Flags & Eigen::RowMajorBit) ) + { + const Mat _dst(1, _rows, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + transpose(src, _dst); + } + else + { + const Mat _dst(_rows, 1, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + src.copyTo(_dst); + } +} + + +template static inline +void cv2eigen( const Mat& src, + Eigen::Matrix<_Tp, 1, Eigen::Dynamic>& dst ) +{ + CV_Assert(src.rows == 1); + dst.resize(src.cols); + if( !(dst.Flags & Eigen::RowMajorBit) ) + { + const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + if( src.type() == _dst.type() ) + transpose(src, _dst); + else + Mat(src.t()).convertTo(_dst, _dst.type()); + } + else + { + const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + src.convertTo(_dst, _dst.type()); + } +} + +//Matx +template static inline +void cv2eigen( const Matx<_Tp, 1, _cols>& src, + Eigen::Matrix<_Tp, 1, Eigen::Dynamic>& dst ) +{ + dst.resize(_cols); + if( !(dst.Flags & Eigen::RowMajorBit) ) + { + const Mat _dst(_cols, 1, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + transpose(src, _dst); + } + else + { + const Mat _dst(1, _cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + Mat(src).copyTo(_dst); + } +} + +//! @} + +} // cv + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/fast_math.hpp b/3rdParty/opencv-4.11.0/opencv2/core/fast_math.hpp index a28c3fbedf..3a6f8163fe 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/fast_math.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/fast_math.hpp @@ -1,433 +1,433 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CORE_FAST_MATH_HPP -#define OPENCV_CORE_FAST_MATH_HPP - -#include "opencv2/core/cvdef.h" - -//! @addtogroup core_utils -//! @{ - -/****************************************************************************************\ -* fast math * -\****************************************************************************************/ - -#ifdef __cplusplus -# include -#else -# ifdef __BORLANDC__ -# include -# else -# include -# endif -#endif - -#if defined(__CUDACC__) - // nothing, intrinsics/asm code is not supported -#else - #if ((defined _MSC_VER && defined _M_X64) \ - || (defined __GNUC__ && defined __SSE2__)) \ - && !defined(OPENCV_SKIP_INCLUDE_EMMINTRIN_H) - #include - #endif - - #if defined __PPC64__ && defined __GNUC__ && defined _ARCH_PWR8 \ - && !defined(OPENCV_SKIP_INCLUDE_ALTIVEC_H) - #include - #undef vector - #undef bool - #undef pixel - #endif - - #if defined(CV_INLINE_ROUND_FLT) - // user-specified version - // CV_INLINE_ROUND_DBL should be defined too - #elif defined __GNUC__ && defined __arm__ && (defined __ARM_PCS_VFP || defined __ARM_VFPV3__ || defined __ARM_NEON) && !defined __SOFTFP__ - // 1. general scheme - #define ARM_ROUND(_value, _asm_string) \ - int res; \ - float temp; \ - CV_UNUSED(temp); \ - __asm__(_asm_string : [res] "=r" (res), [temp] "=w" (temp) : [value] "w" (_value)); \ - return res - // 2. version for double - #ifdef __clang__ - #define CV_INLINE_ROUND_DBL(value) ARM_ROUND(value, "vcvtr.s32.f64 %[temp], %[value] \n vmov %[res], %[temp]") - #else - #define CV_INLINE_ROUND_DBL(value) ARM_ROUND(value, "vcvtr.s32.f64 %[temp], %P[value] \n vmov %[res], %[temp]") - #endif - // 3. version for float - #define CV_INLINE_ROUND_FLT(value) ARM_ROUND(value, "vcvtr.s32.f32 %[temp], %[value]\n vmov %[res], %[temp]") - #elif defined __PPC64__ && defined __GNUC__ && defined _ARCH_PWR8 - // P8 and newer machines can convert fp32/64 to int quickly. - #define CV_INLINE_ROUND_DBL(value) \ - int out; \ - double temp; \ - __asm__( "fctiw %[temp],%[in]\n\tmfvsrwz %[out],%[temp]\n\t" : [out] "=r" (out), [temp] "=d" (temp) : [in] "d" ((double)(value)) : ); \ - return out; - - // FP32 also works with FP64 routine above - #define CV_INLINE_ROUND_FLT(value) CV_INLINE_ROUND_DBL(value) - #endif - - #ifdef CV_INLINE_ISINF_FLT - // user-specified version - // CV_INLINE_ISINF_DBL should be defined too - #elif defined __PPC64__ && defined _ARCH_PWR9 && defined(scalar_test_data_class) - #define CV_INLINE_ISINF_DBL(value) return scalar_test_data_class(value, 0x30); - #define CV_INLINE_ISINF_FLT(value) CV_INLINE_ISINF_DBL(value) - #endif - - #ifdef CV_INLINE_ISNAN_FLT - // user-specified version - // CV_INLINE_ISNAN_DBL should be defined too - #elif defined __PPC64__ && defined _ARCH_PWR9 && defined(scalar_test_data_class) - #define CV_INLINE_ISNAN_DBL(value) return scalar_test_data_class(value, 0x40); - #define CV_INLINE_ISNAN_FLT(value) CV_INLINE_ISNAN_DBL(value) - #endif - - #if !defined(OPENCV_USE_FASTMATH_BUILTINS) \ - && ( \ - defined(__x86_64__) || defined(__i686__) \ - || defined(__arm__) \ - || defined(__PPC64__) \ - ) - /* Let builtin C math functions when available. Dedicated hardware is available to - round and convert FP values. */ - #define OPENCV_USE_FASTMATH_BUILTINS 1 - #endif - - /* Enable builtin math functions if possible, desired, and available. - Note, not all math functions inline equally. E.g lrint will not inline - without the -fno-math-errno option. */ - #if defined(CV_ICC) - // nothing - #elif defined(OPENCV_USE_FASTMATH_BUILTINS) && OPENCV_USE_FASTMATH_BUILTINS - #if defined(__clang__) - #define CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS - #if !defined(CV_INLINE_ISNAN_DBL) && __has_builtin(__builtin_isnan) - #define CV_INLINE_ISNAN_DBL(value) return __builtin_isnan(value); - #endif - #if !defined(CV_INLINE_ISNAN_FLT) && __has_builtin(__builtin_isnan) - #define CV_INLINE_ISNAN_FLT(value) return __builtin_isnan(value); - #endif - #if !defined(CV_INLINE_ISINF_DBL) && __has_builtin(__builtin_isinf) - #define CV_INLINE_ISINF_DBL(value) return __builtin_isinf(value); - #endif - #if !defined(CV_INLINE_ISINF_FLT) && __has_builtin(__builtin_isinf) - #define CV_INLINE_ISINF_FLT(value) return __builtin_isinf(value); - #endif - #elif defined(__GNUC__) - #define CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS - #if !defined(CV_INLINE_ISNAN_DBL) - #define CV_INLINE_ISNAN_DBL(value) return __builtin_isnan(value); - #endif - #if !defined(CV_INLINE_ISNAN_FLT) - #define CV_INLINE_ISNAN_FLT(value) return __builtin_isnanf(value); - #endif - #if !defined(CV_INLINE_ISINF_DBL) - #define CV_INLINE_ISINF_DBL(value) return __builtin_isinf(value); - #endif - #if !defined(CV_INLINE_ISINF_FLT) - #define CV_INLINE_ISINF_FLT(value) return __builtin_isinff(value); - #endif - #elif defined(_MSC_VER) - #if !defined(CV_INLINE_ISNAN_DBL) - #define CV_INLINE_ISNAN_DBL(value) return isnan(value); - #endif - #if !defined(CV_INLINE_ISNAN_FLT) - #define CV_INLINE_ISNAN_FLT(value) return isnan(value); - #endif - #if !defined(CV_INLINE_ISINF_DBL) - #define CV_INLINE_ISINF_DBL(value) return isinf(value); - #endif - #if !defined(CV_INLINE_ISINF_FLT) - #define CV_INLINE_ISINF_FLT(value) return isinf(value); - #endif - #endif - #endif - -#endif // defined(__CUDACC__) - -/** @brief Rounds floating-point number to the nearest integer - - @param value floating-point number. If the value is outside of INT_MIN ... INT_MAX range, the - result is not defined. - */ -CV_INLINE int -cvRound( double value ) -{ -#if defined CV_INLINE_ROUND_DBL - CV_INLINE_ROUND_DBL(value); -#elif ((defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __SSE2__)) && !defined(__CUDACC__) - __m128d t = _mm_set_sd( value ); - return _mm_cvtsd_si32(t); -#elif defined _MSC_VER && defined _M_IX86 - int t; - __asm - { - fld value; - fistp t; - } - return t; -#elif defined CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS || \ - defined CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS - return (int)__builtin_lrint(value); -#else - return (int)lrint(value); -#endif -} - - -/** @brief Rounds floating-point number to the nearest integer not larger than the original. - - The function computes an integer i such that: - \f[i \le \texttt{value} < i+1\f] - @param value floating-point number. If the value is outside of INT_MIN ... INT_MAX range, the - result is not defined. - */ -CV_INLINE int cvFloor( double value ) -{ -#if defined CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS || \ - defined CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS - return (int)__builtin_floor(value); -#elif defined __loongarch64 - int i; - double tmp; - __asm__ ("ftintrm.l.d %[tmp], %[in] \n\t" - "movfr2gr.d %[i], %[tmp] \n\t" - : [i] "=r" (i), [tmp] "=f" (tmp) - : [in] "f" (value) - :); - return i; -#else - int i = (int)value; - return i - (i > value); -#endif -} - -/** @brief Rounds floating-point number to the nearest integer not smaller than the original. - - The function computes an integer i such that: - \f[i \le \texttt{value} < i+1\f] - @param value floating-point number. If the value is outside of INT_MIN ... INT_MAX range, the - result is not defined. - */ -CV_INLINE int cvCeil( double value ) -{ -#if defined CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS || \ - defined CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS - return (int)__builtin_ceil(value); -#elif defined __loongarch64 - int i; - double tmp; - __asm__ ("ftintrp.l.d %[tmp], %[in] \n\t" - "movfr2gr.d %[i], %[tmp] \n\t" - : [i] "=r" (i), [tmp] "=f" (tmp) - : [in] "f" (value) - :); - return i; -#else - int i = (int)value; - return i + (i < value); -#endif -} - -/** @brief Determines if the argument is Not A Number. - - @param value The input floating-point value - - The function returns 1 if the argument is Not A Number (as defined by IEEE754 standard), 0 - otherwise. */ -CV_INLINE int cvIsNaN( double value ) -{ -#if defined CV_INLINE_ISNAN_DBL - CV_INLINE_ISNAN_DBL(value); -#else - Cv64suf ieee754; - ieee754.f = value; - return ((unsigned)(ieee754.u >> 32) & 0x7fffffff) + - ((unsigned)ieee754.u != 0) > 0x7ff00000; -#endif -} - -/** @brief Determines if the argument is Infinity. - - @param value The input floating-point value - - The function returns 1 if the argument is a plus or minus infinity (as defined by IEEE754 standard) - and 0 otherwise. */ -CV_INLINE int cvIsInf( double value ) -{ -#if defined CV_INLINE_ISINF_DBL - CV_INLINE_ISINF_DBL(value); -#elif defined(__x86_64__) || defined(_M_X64) || defined(__aarch64__) || defined(_M_ARM64) || defined(__PPC64__) || defined(__loongarch64) - Cv64suf ieee754; - ieee754.f = value; - return (ieee754.u & 0x7fffffffffffffff) == - 0x7ff0000000000000; -#else - Cv64suf ieee754; - ieee754.f = value; - return ((unsigned)(ieee754.u >> 32) & 0x7fffffff) == 0x7ff00000 && - (unsigned)ieee754.u == 0; -#endif -} - -#ifdef __cplusplus - -/** @overload */ -CV_INLINE int cvRound(float value) -{ -#if defined CV_INLINE_ROUND_FLT - CV_INLINE_ROUND_FLT(value); -#elif ((defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __SSE2__)) && !defined(__CUDACC__) - __m128 t = _mm_set_ss( value ); - return _mm_cvtss_si32(t); -#elif defined _MSC_VER && defined _M_IX86 - int t; - __asm - { - fld value; - fistp t; - } - return t; -#elif defined CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS || \ - defined CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS - return (int)__builtin_lrintf(value); -#else - return (int)lrintf(value); -#endif -} - -/** @overload */ -CV_INLINE int cvRound( int value ) -{ - return value; -} - -/** @overload */ -CV_INLINE int cvFloor( float value ) -{ -#if defined CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS || \ - defined CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS - return (int)__builtin_floorf(value); -#elif defined __loongarch__ - int i; - float tmp; - __asm__ ("ftintrm.w.s %[tmp], %[in] \n\t" - "movfr2gr.s %[i], %[tmp] \n\t" - : [i] "=r" (i), [tmp] "=f" (tmp) - : [in] "f" (value) - :); - return i; -#else - int i = (int)value; - return i - (i > value); -#endif -} - -/** @overload */ -CV_INLINE int cvFloor( int value ) -{ - return value; -} - -/** @overload */ -CV_INLINE int cvCeil( float value ) -{ -#if defined CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS || \ - defined CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS - return (int)__builtin_ceilf(value); -#elif defined __loongarch__ - int i; - float tmp; - __asm__ ("ftintrp.w.s %[tmp], %[in] \n\t" - "movfr2gr.s %[i], %[tmp] \n\t" - : [i] "=r" (i), [tmp] "=f" (tmp) - : [in] "f" (value) - :); - return i; -#else - int i = (int)value; - return i + (i < value); -#endif -} - -/** @overload */ -CV_INLINE int cvCeil( int value ) -{ - return value; -} - -/** @overload */ -CV_INLINE int cvIsNaN( float value ) -{ -#if defined CV_INLINE_ISNAN_FLT - CV_INLINE_ISNAN_FLT(value); -#else - Cv32suf ieee754; - ieee754.f = value; - return (ieee754.u & 0x7fffffff) > 0x7f800000; -#endif -} - -/** @overload */ -CV_INLINE int cvIsInf( float value ) -{ -#if defined CV_INLINE_ISINF_FLT - CV_INLINE_ISINF_FLT(value); -#else - Cv32suf ieee754; - ieee754.f = value; - return (ieee754.u & 0x7fffffff) == 0x7f800000; -#endif -} - -#endif // __cplusplus - -//! @} core_utils - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CORE_FAST_MATH_HPP +#define OPENCV_CORE_FAST_MATH_HPP + +#include "opencv2/core/cvdef.h" + +//! @addtogroup core_utils +//! @{ + +/****************************************************************************************\ +* fast math * +\****************************************************************************************/ + +#ifdef __cplusplus +# include +#else +# ifdef __BORLANDC__ +# include +# else +# include +# endif +#endif + +#if defined(__CUDACC__) + // nothing, intrinsics/asm code is not supported +#else + #if ((defined _MSC_VER && defined _M_X64) \ + || (defined __GNUC__ && defined __SSE2__)) \ + && !defined(OPENCV_SKIP_INCLUDE_EMMINTRIN_H) + #include + #endif + + #if defined __PPC64__ && defined __GNUC__ && defined _ARCH_PWR8 \ + && !defined(OPENCV_SKIP_INCLUDE_ALTIVEC_H) + #include + #undef vector + #undef bool + #undef pixel + #endif + + #if defined(CV_INLINE_ROUND_FLT) + // user-specified version + // CV_INLINE_ROUND_DBL should be defined too + #elif defined __GNUC__ && defined __arm__ && (defined __ARM_PCS_VFP || defined __ARM_VFPV3__ || defined __ARM_NEON) && !defined __SOFTFP__ + // 1. general scheme + #define ARM_ROUND(_value, _asm_string) \ + int res; \ + float temp; \ + CV_UNUSED(temp); \ + __asm__(_asm_string : [res] "=r" (res), [temp] "=w" (temp) : [value] "w" (_value)); \ + return res + // 2. version for double + #ifdef __clang__ + #define CV_INLINE_ROUND_DBL(value) ARM_ROUND(value, "vcvtr.s32.f64 %[temp], %[value] \n vmov %[res], %[temp]") + #else + #define CV_INLINE_ROUND_DBL(value) ARM_ROUND(value, "vcvtr.s32.f64 %[temp], %P[value] \n vmov %[res], %[temp]") + #endif + // 3. version for float + #define CV_INLINE_ROUND_FLT(value) ARM_ROUND(value, "vcvtr.s32.f32 %[temp], %[value]\n vmov %[res], %[temp]") + #elif defined __PPC64__ && defined __GNUC__ && defined _ARCH_PWR8 + // P8 and newer machines can convert fp32/64 to int quickly. + #define CV_INLINE_ROUND_DBL(value) \ + int out; \ + double temp; \ + __asm__( "fctiw %[temp],%[in]\n\tmfvsrwz %[out],%[temp]\n\t" : [out] "=r" (out), [temp] "=d" (temp) : [in] "d" ((double)(value)) : ); \ + return out; + + // FP32 also works with FP64 routine above + #define CV_INLINE_ROUND_FLT(value) CV_INLINE_ROUND_DBL(value) + #endif + + #ifdef CV_INLINE_ISINF_FLT + // user-specified version + // CV_INLINE_ISINF_DBL should be defined too + #elif defined __PPC64__ && defined _ARCH_PWR9 && defined(scalar_test_data_class) + #define CV_INLINE_ISINF_DBL(value) return scalar_test_data_class(value, 0x30); + #define CV_INLINE_ISINF_FLT(value) CV_INLINE_ISINF_DBL(value) + #endif + + #ifdef CV_INLINE_ISNAN_FLT + // user-specified version + // CV_INLINE_ISNAN_DBL should be defined too + #elif defined __PPC64__ && defined _ARCH_PWR9 && defined(scalar_test_data_class) + #define CV_INLINE_ISNAN_DBL(value) return scalar_test_data_class(value, 0x40); + #define CV_INLINE_ISNAN_FLT(value) CV_INLINE_ISNAN_DBL(value) + #endif + + #if !defined(OPENCV_USE_FASTMATH_BUILTINS) \ + && ( \ + defined(__x86_64__) || defined(__i686__) \ + || defined(__arm__) \ + || defined(__PPC64__) \ + ) + /* Let builtin C math functions when available. Dedicated hardware is available to + round and convert FP values. */ + #define OPENCV_USE_FASTMATH_BUILTINS 1 + #endif + + /* Enable builtin math functions if possible, desired, and available. + Note, not all math functions inline equally. E.g lrint will not inline + without the -fno-math-errno option. */ + #if defined(CV_ICC) + // nothing + #elif defined(OPENCV_USE_FASTMATH_BUILTINS) && OPENCV_USE_FASTMATH_BUILTINS + #if defined(__clang__) + #define CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS + #if !defined(CV_INLINE_ISNAN_DBL) && __has_builtin(__builtin_isnan) + #define CV_INLINE_ISNAN_DBL(value) return __builtin_isnan(value); + #endif + #if !defined(CV_INLINE_ISNAN_FLT) && __has_builtin(__builtin_isnan) + #define CV_INLINE_ISNAN_FLT(value) return __builtin_isnan(value); + #endif + #if !defined(CV_INLINE_ISINF_DBL) && __has_builtin(__builtin_isinf) + #define CV_INLINE_ISINF_DBL(value) return __builtin_isinf(value); + #endif + #if !defined(CV_INLINE_ISINF_FLT) && __has_builtin(__builtin_isinf) + #define CV_INLINE_ISINF_FLT(value) return __builtin_isinf(value); + #endif + #elif defined(__GNUC__) + #define CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS + #if !defined(CV_INLINE_ISNAN_DBL) + #define CV_INLINE_ISNAN_DBL(value) return __builtin_isnan(value); + #endif + #if !defined(CV_INLINE_ISNAN_FLT) + #define CV_INLINE_ISNAN_FLT(value) return __builtin_isnanf(value); + #endif + #if !defined(CV_INLINE_ISINF_DBL) + #define CV_INLINE_ISINF_DBL(value) return __builtin_isinf(value); + #endif + #if !defined(CV_INLINE_ISINF_FLT) + #define CV_INLINE_ISINF_FLT(value) return __builtin_isinff(value); + #endif + #elif defined(_MSC_VER) + #if !defined(CV_INLINE_ISNAN_DBL) + #define CV_INLINE_ISNAN_DBL(value) return isnan(value); + #endif + #if !defined(CV_INLINE_ISNAN_FLT) + #define CV_INLINE_ISNAN_FLT(value) return isnan(value); + #endif + #if !defined(CV_INLINE_ISINF_DBL) + #define CV_INLINE_ISINF_DBL(value) return isinf(value); + #endif + #if !defined(CV_INLINE_ISINF_FLT) + #define CV_INLINE_ISINF_FLT(value) return isinf(value); + #endif + #endif + #endif + +#endif // defined(__CUDACC__) + +/** @brief Rounds floating-point number to the nearest integer + + @param value floating-point number. If the value is outside of INT_MIN ... INT_MAX range, the + result is not defined. + */ +CV_INLINE int +cvRound( double value ) +{ +#if defined CV_INLINE_ROUND_DBL + CV_INLINE_ROUND_DBL(value); +#elif ((defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __SSE2__)) && !defined(__CUDACC__) + __m128d t = _mm_set_sd( value ); + return _mm_cvtsd_si32(t); +#elif defined _MSC_VER && defined _M_IX86 + int t; + __asm + { + fld value; + fistp t; + } + return t; +#elif defined CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS || \ + defined CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS + return (int)__builtin_lrint(value); +#else + return (int)lrint(value); +#endif +} + + +/** @brief Rounds floating-point number to the nearest integer not larger than the original. + + The function computes an integer i such that: + \f[i \le \texttt{value} < i+1\f] + @param value floating-point number. If the value is outside of INT_MIN ... INT_MAX range, the + result is not defined. + */ +CV_INLINE int cvFloor( double value ) +{ +#if defined CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS || \ + defined CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS + return (int)__builtin_floor(value); +#elif defined __loongarch64 + int i; + double tmp; + __asm__ ("ftintrm.l.d %[tmp], %[in] \n\t" + "movfr2gr.d %[i], %[tmp] \n\t" + : [i] "=r" (i), [tmp] "=f" (tmp) + : [in] "f" (value) + :); + return i; +#else + int i = (int)value; + return i - (i > value); +#endif +} + +/** @brief Rounds floating-point number to the nearest integer not smaller than the original. + + The function computes an integer i such that: + \f[i \le \texttt{value} < i+1\f] + @param value floating-point number. If the value is outside of INT_MIN ... INT_MAX range, the + result is not defined. + */ +CV_INLINE int cvCeil( double value ) +{ +#if defined CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS || \ + defined CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS + return (int)__builtin_ceil(value); +#elif defined __loongarch64 + int i; + double tmp; + __asm__ ("ftintrp.l.d %[tmp], %[in] \n\t" + "movfr2gr.d %[i], %[tmp] \n\t" + : [i] "=r" (i), [tmp] "=f" (tmp) + : [in] "f" (value) + :); + return i; +#else + int i = (int)value; + return i + (i < value); +#endif +} + +/** @brief Determines if the argument is Not A Number. + + @param value The input floating-point value + + The function returns 1 if the argument is Not A Number (as defined by IEEE754 standard), 0 + otherwise. */ +CV_INLINE int cvIsNaN( double value ) +{ +#if defined CV_INLINE_ISNAN_DBL + CV_INLINE_ISNAN_DBL(value); +#else + Cv64suf ieee754; + ieee754.f = value; + return ((unsigned)(ieee754.u >> 32) & 0x7fffffff) + + ((unsigned)ieee754.u != 0) > 0x7ff00000; +#endif +} + +/** @brief Determines if the argument is Infinity. + + @param value The input floating-point value + + The function returns 1 if the argument is a plus or minus infinity (as defined by IEEE754 standard) + and 0 otherwise. */ +CV_INLINE int cvIsInf( double value ) +{ +#if defined CV_INLINE_ISINF_DBL + CV_INLINE_ISINF_DBL(value); +#elif defined(__x86_64__) || defined(_M_X64) || defined(__aarch64__) || defined(_M_ARM64) || defined(__PPC64__) || defined(__loongarch64) + Cv64suf ieee754; + ieee754.f = value; + return (ieee754.u & 0x7fffffffffffffff) == + 0x7ff0000000000000; +#else + Cv64suf ieee754; + ieee754.f = value; + return ((unsigned)(ieee754.u >> 32) & 0x7fffffff) == 0x7ff00000 && + (unsigned)ieee754.u == 0; +#endif +} + +#ifdef __cplusplus + +/** @overload */ +CV_INLINE int cvRound(float value) +{ +#if defined CV_INLINE_ROUND_FLT + CV_INLINE_ROUND_FLT(value); +#elif ((defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __SSE2__)) && !defined(__CUDACC__) + __m128 t = _mm_set_ss( value ); + return _mm_cvtss_si32(t); +#elif defined _MSC_VER && defined _M_IX86 + int t; + __asm + { + fld value; + fistp t; + } + return t; +#elif defined CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS || \ + defined CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS + return (int)__builtin_lrintf(value); +#else + return (int)lrintf(value); +#endif +} + +/** @overload */ +CV_INLINE int cvRound( int value ) +{ + return value; +} + +/** @overload */ +CV_INLINE int cvFloor( float value ) +{ +#if defined CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS || \ + defined CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS + return (int)__builtin_floorf(value); +#elif defined __loongarch__ + int i; + float tmp; + __asm__ ("ftintrm.w.s %[tmp], %[in] \n\t" + "movfr2gr.s %[i], %[tmp] \n\t" + : [i] "=r" (i), [tmp] "=f" (tmp) + : [in] "f" (value) + :); + return i; +#else + int i = (int)value; + return i - (i > value); +#endif +} + +/** @overload */ +CV_INLINE int cvFloor( int value ) +{ + return value; +} + +/** @overload */ +CV_INLINE int cvCeil( float value ) +{ +#if defined CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS || \ + defined CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS + return (int)__builtin_ceilf(value); +#elif defined __loongarch__ + int i; + float tmp; + __asm__ ("ftintrp.w.s %[tmp], %[in] \n\t" + "movfr2gr.s %[i], %[tmp] \n\t" + : [i] "=r" (i), [tmp] "=f" (tmp) + : [in] "f" (value) + :); + return i; +#else + int i = (int)value; + return i + (i < value); +#endif +} + +/** @overload */ +CV_INLINE int cvCeil( int value ) +{ + return value; +} + +/** @overload */ +CV_INLINE int cvIsNaN( float value ) +{ +#if defined CV_INLINE_ISNAN_FLT + CV_INLINE_ISNAN_FLT(value); +#else + Cv32suf ieee754; + ieee754.f = value; + return (ieee754.u & 0x7fffffff) > 0x7f800000; +#endif +} + +/** @overload */ +CV_INLINE int cvIsInf( float value ) +{ +#if defined CV_INLINE_ISINF_FLT + CV_INLINE_ISINF_FLT(value); +#else + Cv32suf ieee754; + ieee754.f = value; + return (ieee754.u & 0x7fffffff) == 0x7f800000; +#endif +} + +#endif // __cplusplus + +//! @} core_utils + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/hal.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/hal.hpp index deca4e9539..34505515c0 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/hal.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/hal.hpp @@ -1,260 +1,260 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_HAL_HPP -#define OPENCV_HAL_HPP - -#include "opencv2/core/cvdef.h" -#include "opencv2/core/cvstd.hpp" -#include "opencv2/core/hal/interface.h" - -namespace cv { namespace hal { - -//! @addtogroup core_hal_functions -//! @{ - -CV_EXPORTS int normHamming(const uchar* a, int n); -CV_EXPORTS int normHamming(const uchar* a, const uchar* b, int n); - -CV_EXPORTS int normHamming(const uchar* a, int n, int cellSize); -CV_EXPORTS int normHamming(const uchar* a, const uchar* b, int n, int cellSize); - -CV_EXPORTS int LU32f(float* A, size_t astep, int m, float* b, size_t bstep, int n); -CV_EXPORTS int LU64f(double* A, size_t astep, int m, double* b, size_t bstep, int n); -CV_EXPORTS bool Cholesky32f(float* A, size_t astep, int m, float* b, size_t bstep, int n); -CV_EXPORTS bool Cholesky64f(double* A, size_t astep, int m, double* b, size_t bstep, int n); -CV_EXPORTS void SVD32f(float* At, size_t astep, float* W, float* U, size_t ustep, float* Vt, size_t vstep, int m, int n, int flags); -CV_EXPORTS void SVD64f(double* At, size_t astep, double* W, double* U, size_t ustep, double* Vt, size_t vstep, int m, int n, int flags); -CV_EXPORTS int QR32f(float* A, size_t astep, int m, int n, int k, float* b, size_t bstep, float* hFactors); -CV_EXPORTS int QR64f(double* A, size_t astep, int m, int n, int k, double* b, size_t bstep, double* hFactors); - -CV_EXPORTS void gemm32f(const float* src1, size_t src1_step, const float* src2, size_t src2_step, - float alpha, const float* src3, size_t src3_step, float beta, float* dst, size_t dst_step, - int m_a, int n_a, int n_d, int flags); -CV_EXPORTS void gemm64f(const double* src1, size_t src1_step, const double* src2, size_t src2_step, - double alpha, const double* src3, size_t src3_step, double beta, double* dst, size_t dst_step, - int m_a, int n_a, int n_d, int flags); -CV_EXPORTS void gemm32fc(const float* src1, size_t src1_step, const float* src2, size_t src2_step, - float alpha, const float* src3, size_t src3_step, float beta, float* dst, size_t dst_step, - int m_a, int n_a, int n_d, int flags); -CV_EXPORTS void gemm64fc(const double* src1, size_t src1_step, const double* src2, size_t src2_step, - double alpha, const double* src3, size_t src3_step, double beta, double* dst, size_t dst_step, - int m_a, int n_a, int n_d, int flags); - -CV_EXPORTS int normL1_(const uchar* a, const uchar* b, int n); -CV_EXPORTS float normL1_(const float* a, const float* b, int n); -CV_EXPORTS float normL2Sqr_(const float* a, const float* b, int n); - -CV_EXPORTS void exp32f(const float* src, float* dst, int n); -CV_EXPORTS void exp64f(const double* src, double* dst, int n); -CV_EXPORTS void log32f(const float* src, float* dst, int n); -CV_EXPORTS void log64f(const double* src, double* dst, int n); - -CV_EXPORTS void cartToPolar32f(const float* x, const float* y, float* mag, float* angle, int n, bool angleInDegrees); -CV_EXPORTS void cartToPolar64f(const double* x, const double* y, double* mag, double* angle, int n, bool angleInDegrees); -CV_EXPORTS void fastAtan32f(const float* y, const float* x, float* dst, int n, bool angleInDegrees); -CV_EXPORTS void fastAtan64f(const double* y, const double* x, double* dst, int n, bool angleInDegrees); -CV_EXPORTS void magnitude32f(const float* x, const float* y, float* dst, int n); -CV_EXPORTS void magnitude64f(const double* x, const double* y, double* dst, int n); -CV_EXPORTS void polarToCart32f(const float* mag, const float* angle, float* x, float* y, int n, bool angleInDegrees); -CV_EXPORTS void polarToCart64f(const double* mag, const double* angle, double* x, double* y, int n, bool angleInDegrees); -CV_EXPORTS void sqrt32f(const float* src, float* dst, int len); -CV_EXPORTS void sqrt64f(const double* src, double* dst, int len); -CV_EXPORTS void invSqrt32f(const float* src, float* dst, int len); -CV_EXPORTS void invSqrt64f(const double* src, double* dst, int len); - -CV_EXPORTS void split8u(const uchar* src, uchar** dst, int len, int cn ); -CV_EXPORTS void split16u(const ushort* src, ushort** dst, int len, int cn ); -CV_EXPORTS void split32s(const int* src, int** dst, int len, int cn ); -CV_EXPORTS void split64s(const int64* src, int64** dst, int len, int cn ); - -CV_EXPORTS void merge8u(const uchar** src, uchar* dst, int len, int cn ); -CV_EXPORTS void merge16u(const ushort** src, ushort* dst, int len, int cn ); -CV_EXPORTS void merge32s(const int** src, int* dst, int len, int cn ); -CV_EXPORTS void merge64s(const int64** src, int64* dst, int len, int cn ); - -CV_EXPORTS void add8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void add8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void add16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void add16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void add32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void add32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void add64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); - -CV_EXPORTS void sub8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void sub8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void sub16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void sub16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void sub32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void sub32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void sub64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); - -CV_EXPORTS void max8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void max8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void max16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void max16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void max32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void max32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void max64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); - -CV_EXPORTS void min8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void min8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void min16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void min16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void min32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void min32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void min64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); - -CV_EXPORTS void absdiff8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void absdiff8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void absdiff16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void absdiff16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void absdiff32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void absdiff32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void absdiff64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); - -CV_EXPORTS void and8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void or8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void xor8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void not8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); - -CV_EXPORTS void cmp8u(const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); -CV_EXPORTS void cmp8s(const schar* src1, size_t step1, const schar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); -CV_EXPORTS void cmp16u(const ushort* src1, size_t step1, const ushort* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); -CV_EXPORTS void cmp16s(const short* src1, size_t step1, const short* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); -CV_EXPORTS void cmp32s(const int* src1, size_t step1, const int* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); -CV_EXPORTS void cmp32f(const float* src1, size_t step1, const float* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); -CV_EXPORTS void cmp64f(const double* src1, size_t step1, const double* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); - -CV_EXPORTS void mul8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void mul8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void mul16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void mul16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void mul32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void mul32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void mul64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* scale); - -CV_EXPORTS void div8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void div8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void div16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void div16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void div32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void div32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void div64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* scale); - -CV_EXPORTS void recip8u( const uchar *, size_t, const uchar * src2, size_t step2, uchar* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void recip8s( const schar *, size_t, const schar * src2, size_t step2, schar* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void recip16u( const ushort *, size_t, const ushort * src2, size_t step2, ushort* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void recip16s( const short *, size_t, const short * src2, size_t step2, short* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void recip32s( const int *, size_t, const int * src2, size_t step2, int* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void recip32f( const float *, size_t, const float * src2, size_t step2, float* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void recip64f( const double *, size_t, const double * src2, size_t step2, double* dst, size_t step, int width, int height, void* scale); - -CV_EXPORTS void addWeighted8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _scalars ); -CV_EXPORTS void addWeighted8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* scalars ); -CV_EXPORTS void addWeighted16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* scalars ); -CV_EXPORTS void addWeighted16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* scalars ); -CV_EXPORTS void addWeighted32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* scalars ); -CV_EXPORTS void addWeighted32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* scalars ); -CV_EXPORTS void addWeighted64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* scalars ); - -CV_EXPORTS void cvt16f32f( const hfloat* src, float* dst, int len ); -CV_EXPORTS void cvt32f16f( const float* src, hfloat* dst, int len ); - -CV_EXPORTS void addRNGBias32f( float* arr, const float* scaleBiasPairs, int len ); -CV_EXPORTS void addRNGBias64f( double* arr, const double* scaleBiasPairs, int len ); - -struct CV_EXPORTS DFT1D -{ - static Ptr create(int len, int count, int depth, int flags, bool * useBuffer = 0); - virtual void apply(const uchar *src, uchar *dst) = 0; - virtual ~DFT1D() {} -}; - -struct CV_EXPORTS DFT2D -{ - static Ptr create(int width, int height, int depth, - int src_channels, int dst_channels, - int flags, int nonzero_rows = 0); - virtual void apply(const uchar *src_data, size_t src_step, uchar *dst_data, size_t dst_step) = 0; - virtual ~DFT2D() {} -}; - -struct CV_EXPORTS DCT2D -{ - static Ptr create(int width, int height, int depth, int flags); - virtual void apply(const uchar *src_data, size_t src_step, uchar *dst_data, size_t dst_step) = 0; - virtual ~DCT2D() {} -}; - -//! @} core_hal - -//============================================================================= -// for binary compatibility with 3.0 - -//! @cond IGNORED - -CV_EXPORTS int LU(float* A, size_t astep, int m, float* b, size_t bstep, int n); -CV_EXPORTS int LU(double* A, size_t astep, int m, double* b, size_t bstep, int n); -CV_EXPORTS bool Cholesky(float* A, size_t astep, int m, float* b, size_t bstep, int n); -CV_EXPORTS bool Cholesky(double* A, size_t astep, int m, double* b, size_t bstep, int n); - -CV_EXPORTS void exp(const float* src, float* dst, int n); -CV_EXPORTS void exp(const double* src, double* dst, int n); -CV_EXPORTS void log(const float* src, float* dst, int n); -CV_EXPORTS void log(const double* src, double* dst, int n); - -CV_EXPORTS void fastAtan2(const float* y, const float* x, float* dst, int n, bool angleInDegrees); -CV_EXPORTS void magnitude(const float* x, const float* y, float* dst, int n); -CV_EXPORTS void magnitude(const double* x, const double* y, double* dst, int n); -CV_EXPORTS void sqrt(const float* src, float* dst, int len); -CV_EXPORTS void sqrt(const double* src, double* dst, int len); -CV_EXPORTS void invSqrt(const float* src, float* dst, int len); -CV_EXPORTS void invSqrt(const double* src, double* dst, int len); - -//! @endcond - -}} //cv::hal - -#endif //OPENCV_HAL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_HAL_HPP +#define OPENCV_HAL_HPP + +#include "opencv2/core/cvdef.h" +#include "opencv2/core/cvstd.hpp" +#include "opencv2/core/hal/interface.h" + +namespace cv { namespace hal { + +//! @addtogroup core_hal_functions +//! @{ + +CV_EXPORTS int normHamming(const uchar* a, int n); +CV_EXPORTS int normHamming(const uchar* a, const uchar* b, int n); + +CV_EXPORTS int normHamming(const uchar* a, int n, int cellSize); +CV_EXPORTS int normHamming(const uchar* a, const uchar* b, int n, int cellSize); + +CV_EXPORTS int LU32f(float* A, size_t astep, int m, float* b, size_t bstep, int n); +CV_EXPORTS int LU64f(double* A, size_t astep, int m, double* b, size_t bstep, int n); +CV_EXPORTS bool Cholesky32f(float* A, size_t astep, int m, float* b, size_t bstep, int n); +CV_EXPORTS bool Cholesky64f(double* A, size_t astep, int m, double* b, size_t bstep, int n); +CV_EXPORTS void SVD32f(float* At, size_t astep, float* W, float* U, size_t ustep, float* Vt, size_t vstep, int m, int n, int flags); +CV_EXPORTS void SVD64f(double* At, size_t astep, double* W, double* U, size_t ustep, double* Vt, size_t vstep, int m, int n, int flags); +CV_EXPORTS int QR32f(float* A, size_t astep, int m, int n, int k, float* b, size_t bstep, float* hFactors); +CV_EXPORTS int QR64f(double* A, size_t astep, int m, int n, int k, double* b, size_t bstep, double* hFactors); + +CV_EXPORTS void gemm32f(const float* src1, size_t src1_step, const float* src2, size_t src2_step, + float alpha, const float* src3, size_t src3_step, float beta, float* dst, size_t dst_step, + int m_a, int n_a, int n_d, int flags); +CV_EXPORTS void gemm64f(const double* src1, size_t src1_step, const double* src2, size_t src2_step, + double alpha, const double* src3, size_t src3_step, double beta, double* dst, size_t dst_step, + int m_a, int n_a, int n_d, int flags); +CV_EXPORTS void gemm32fc(const float* src1, size_t src1_step, const float* src2, size_t src2_step, + float alpha, const float* src3, size_t src3_step, float beta, float* dst, size_t dst_step, + int m_a, int n_a, int n_d, int flags); +CV_EXPORTS void gemm64fc(const double* src1, size_t src1_step, const double* src2, size_t src2_step, + double alpha, const double* src3, size_t src3_step, double beta, double* dst, size_t dst_step, + int m_a, int n_a, int n_d, int flags); + +CV_EXPORTS int normL1_(const uchar* a, const uchar* b, int n); +CV_EXPORTS float normL1_(const float* a, const float* b, int n); +CV_EXPORTS float normL2Sqr_(const float* a, const float* b, int n); + +CV_EXPORTS void exp32f(const float* src, float* dst, int n); +CV_EXPORTS void exp64f(const double* src, double* dst, int n); +CV_EXPORTS void log32f(const float* src, float* dst, int n); +CV_EXPORTS void log64f(const double* src, double* dst, int n); + +CV_EXPORTS void cartToPolar32f(const float* x, const float* y, float* mag, float* angle, int n, bool angleInDegrees); +CV_EXPORTS void cartToPolar64f(const double* x, const double* y, double* mag, double* angle, int n, bool angleInDegrees); +CV_EXPORTS void fastAtan32f(const float* y, const float* x, float* dst, int n, bool angleInDegrees); +CV_EXPORTS void fastAtan64f(const double* y, const double* x, double* dst, int n, bool angleInDegrees); +CV_EXPORTS void magnitude32f(const float* x, const float* y, float* dst, int n); +CV_EXPORTS void magnitude64f(const double* x, const double* y, double* dst, int n); +CV_EXPORTS void polarToCart32f(const float* mag, const float* angle, float* x, float* y, int n, bool angleInDegrees); +CV_EXPORTS void polarToCart64f(const double* mag, const double* angle, double* x, double* y, int n, bool angleInDegrees); +CV_EXPORTS void sqrt32f(const float* src, float* dst, int len); +CV_EXPORTS void sqrt64f(const double* src, double* dst, int len); +CV_EXPORTS void invSqrt32f(const float* src, float* dst, int len); +CV_EXPORTS void invSqrt64f(const double* src, double* dst, int len); + +CV_EXPORTS void split8u(const uchar* src, uchar** dst, int len, int cn ); +CV_EXPORTS void split16u(const ushort* src, ushort** dst, int len, int cn ); +CV_EXPORTS void split32s(const int* src, int** dst, int len, int cn ); +CV_EXPORTS void split64s(const int64* src, int64** dst, int len, int cn ); + +CV_EXPORTS void merge8u(const uchar** src, uchar* dst, int len, int cn ); +CV_EXPORTS void merge16u(const ushort** src, ushort* dst, int len, int cn ); +CV_EXPORTS void merge32s(const int** src, int* dst, int len, int cn ); +CV_EXPORTS void merge64s(const int64** src, int64* dst, int len, int cn ); + +CV_EXPORTS void add8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void add8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void add16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void add16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void add32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void add32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void add64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); + +CV_EXPORTS void sub8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void sub8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void sub16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void sub16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void sub32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void sub32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void sub64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); + +CV_EXPORTS void max8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void max8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void max16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void max16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void max32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void max32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void max64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); + +CV_EXPORTS void min8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void min8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void min16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void min16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void min32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void min32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void min64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); + +CV_EXPORTS void absdiff8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void absdiff8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void absdiff16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void absdiff16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void absdiff32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void absdiff32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void absdiff64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); + +CV_EXPORTS void and8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void or8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void xor8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void not8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); + +CV_EXPORTS void cmp8u(const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); +CV_EXPORTS void cmp8s(const schar* src1, size_t step1, const schar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); +CV_EXPORTS void cmp16u(const ushort* src1, size_t step1, const ushort* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); +CV_EXPORTS void cmp16s(const short* src1, size_t step1, const short* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); +CV_EXPORTS void cmp32s(const int* src1, size_t step1, const int* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); +CV_EXPORTS void cmp32f(const float* src1, size_t step1, const float* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); +CV_EXPORTS void cmp64f(const double* src1, size_t step1, const double* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); + +CV_EXPORTS void mul8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void mul8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void mul16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void mul16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void mul32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void mul32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void mul64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* scale); + +CV_EXPORTS void div8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void div8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void div16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void div16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void div32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void div32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void div64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* scale); + +CV_EXPORTS void recip8u( const uchar *, size_t, const uchar * src2, size_t step2, uchar* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void recip8s( const schar *, size_t, const schar * src2, size_t step2, schar* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void recip16u( const ushort *, size_t, const ushort * src2, size_t step2, ushort* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void recip16s( const short *, size_t, const short * src2, size_t step2, short* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void recip32s( const int *, size_t, const int * src2, size_t step2, int* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void recip32f( const float *, size_t, const float * src2, size_t step2, float* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void recip64f( const double *, size_t, const double * src2, size_t step2, double* dst, size_t step, int width, int height, void* scale); + +CV_EXPORTS void addWeighted8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _scalars ); +CV_EXPORTS void addWeighted8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* scalars ); +CV_EXPORTS void addWeighted16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* scalars ); +CV_EXPORTS void addWeighted16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* scalars ); +CV_EXPORTS void addWeighted32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* scalars ); +CV_EXPORTS void addWeighted32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* scalars ); +CV_EXPORTS void addWeighted64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* scalars ); + +CV_EXPORTS void cvt16f32f( const hfloat* src, float* dst, int len ); +CV_EXPORTS void cvt32f16f( const float* src, hfloat* dst, int len ); + +CV_EXPORTS void addRNGBias32f( float* arr, const float* scaleBiasPairs, int len ); +CV_EXPORTS void addRNGBias64f( double* arr, const double* scaleBiasPairs, int len ); + +struct CV_EXPORTS DFT1D +{ + static Ptr create(int len, int count, int depth, int flags, bool * useBuffer = 0); + virtual void apply(const uchar *src, uchar *dst) = 0; + virtual ~DFT1D() {} +}; + +struct CV_EXPORTS DFT2D +{ + static Ptr create(int width, int height, int depth, + int src_channels, int dst_channels, + int flags, int nonzero_rows = 0); + virtual void apply(const uchar *src_data, size_t src_step, uchar *dst_data, size_t dst_step) = 0; + virtual ~DFT2D() {} +}; + +struct CV_EXPORTS DCT2D +{ + static Ptr create(int width, int height, int depth, int flags); + virtual void apply(const uchar *src_data, size_t src_step, uchar *dst_data, size_t dst_step) = 0; + virtual ~DCT2D() {} +}; + +//! @} core_hal + +//============================================================================= +// for binary compatibility with 3.0 + +//! @cond IGNORED + +CV_EXPORTS int LU(float* A, size_t astep, int m, float* b, size_t bstep, int n); +CV_EXPORTS int LU(double* A, size_t astep, int m, double* b, size_t bstep, int n); +CV_EXPORTS bool Cholesky(float* A, size_t astep, int m, float* b, size_t bstep, int n); +CV_EXPORTS bool Cholesky(double* A, size_t astep, int m, double* b, size_t bstep, int n); + +CV_EXPORTS void exp(const float* src, float* dst, int n); +CV_EXPORTS void exp(const double* src, double* dst, int n); +CV_EXPORTS void log(const float* src, float* dst, int n); +CV_EXPORTS void log(const double* src, double* dst, int n); + +CV_EXPORTS void fastAtan2(const float* y, const float* x, float* dst, int n, bool angleInDegrees); +CV_EXPORTS void magnitude(const float* x, const float* y, float* dst, int n); +CV_EXPORTS void magnitude(const double* x, const double* y, double* dst, int n); +CV_EXPORTS void sqrt(const float* src, float* dst, int len); +CV_EXPORTS void sqrt(const double* src, double* dst, int len); +CV_EXPORTS void invSqrt(const float* src, float* dst, int len); +CV_EXPORTS void invSqrt(const double* src, double* dst, int len); + +//! @endcond + +}} //cv::hal + +#endif //OPENCV_HAL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/interface.h b/3rdParty/opencv-4.11.0/opencv2/core/hal/interface.h index 6f0a83d359..2fbb13f4ad 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/interface.h +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/interface.h @@ -1,190 +1,190 @@ -#ifndef OPENCV_CORE_HAL_INTERFACE_H -#define OPENCV_CORE_HAL_INTERFACE_H - -//! @addtogroup core_hal_interface -//! @{ - -//! @name Return codes -//! @{ -#define CV_HAL_ERROR_OK 0 -#define CV_HAL_ERROR_NOT_IMPLEMENTED 1 -#define CV_HAL_ERROR_UNKNOWN -1 -//! @} - -#ifdef __cplusplus -#include -#else -#include -#include -#endif - -//! @name Data types -//! primitive types -//! - schar - signed 1 byte integer -//! - uchar - unsigned 1 byte integer -//! - short - signed 2 byte integer -//! - ushort - unsigned 2 byte integer -//! - int - signed 4 byte integer -//! - uint - unsigned 4 byte integer -//! - int64 - signed 8 byte integer -//! - uint64 - unsigned 8 byte integer -//! @{ -#if !defined _MSC_VER && !defined __BORLANDC__ -# if defined __cplusplus && __cplusplus >= 201103L && !defined __APPLE__ -# include -# ifdef __NEWLIB__ - typedef unsigned int uint; -# else - typedef std::uint32_t uint; -# endif -# else -# include - typedef uint32_t uint; -# endif -#else - typedef unsigned uint; -#endif - -typedef signed char schar; - -#ifndef __IPL_H__ - typedef unsigned char uchar; - typedef unsigned short ushort; -#endif - -#if defined _MSC_VER || defined __BORLANDC__ - typedef __int64 int64; - typedef unsigned __int64 uint64; -# define CV_BIG_INT(n) n##I64 -# define CV_BIG_UINT(n) n##UI64 -#else - typedef int64_t int64; - typedef uint64_t uint64; -# define CV_BIG_INT(n) n##LL -# define CV_BIG_UINT(n) n##ULL -#endif - -#define CV_USRTYPE1 (void)"CV_USRTYPE1 support has been dropped in OpenCV 4.0" - -#define CV_CN_MAX 512 -#define CV_CN_SHIFT 3 -#define CV_DEPTH_MAX (1 << CV_CN_SHIFT) - -#define CV_8U 0 -#define CV_8S 1 -#define CV_16U 2 -#define CV_16S 3 -#define CV_32S 4 -#define CV_32F 5 -#define CV_64F 6 -#define CV_16F 7 - -#define CV_MAT_DEPTH_MASK (CV_DEPTH_MAX - 1) -#define CV_MAT_DEPTH(flags) ((flags) & CV_MAT_DEPTH_MASK) - -#define CV_MAKETYPE(depth,cn) (CV_MAT_DEPTH(depth) + (((cn)-1) << CV_CN_SHIFT)) -#define CV_MAKE_TYPE CV_MAKETYPE - -#define CV_8UC1 CV_MAKETYPE(CV_8U,1) -#define CV_8UC2 CV_MAKETYPE(CV_8U,2) -#define CV_8UC3 CV_MAKETYPE(CV_8U,3) -#define CV_8UC4 CV_MAKETYPE(CV_8U,4) -#define CV_8UC(n) CV_MAKETYPE(CV_8U,(n)) - -#define CV_8SC1 CV_MAKETYPE(CV_8S,1) -#define CV_8SC2 CV_MAKETYPE(CV_8S,2) -#define CV_8SC3 CV_MAKETYPE(CV_8S,3) -#define CV_8SC4 CV_MAKETYPE(CV_8S,4) -#define CV_8SC(n) CV_MAKETYPE(CV_8S,(n)) - -#define CV_16UC1 CV_MAKETYPE(CV_16U,1) -#define CV_16UC2 CV_MAKETYPE(CV_16U,2) -#define CV_16UC3 CV_MAKETYPE(CV_16U,3) -#define CV_16UC4 CV_MAKETYPE(CV_16U,4) -#define CV_16UC(n) CV_MAKETYPE(CV_16U,(n)) - -#define CV_16SC1 CV_MAKETYPE(CV_16S,1) -#define CV_16SC2 CV_MAKETYPE(CV_16S,2) -#define CV_16SC3 CV_MAKETYPE(CV_16S,3) -#define CV_16SC4 CV_MAKETYPE(CV_16S,4) -#define CV_16SC(n) CV_MAKETYPE(CV_16S,(n)) - -#define CV_32SC1 CV_MAKETYPE(CV_32S,1) -#define CV_32SC2 CV_MAKETYPE(CV_32S,2) -#define CV_32SC3 CV_MAKETYPE(CV_32S,3) -#define CV_32SC4 CV_MAKETYPE(CV_32S,4) -#define CV_32SC(n) CV_MAKETYPE(CV_32S,(n)) - -#define CV_32FC1 CV_MAKETYPE(CV_32F,1) -#define CV_32FC2 CV_MAKETYPE(CV_32F,2) -#define CV_32FC3 CV_MAKETYPE(CV_32F,3) -#define CV_32FC4 CV_MAKETYPE(CV_32F,4) -#define CV_32FC(n) CV_MAKETYPE(CV_32F,(n)) - -#define CV_64FC1 CV_MAKETYPE(CV_64F,1) -#define CV_64FC2 CV_MAKETYPE(CV_64F,2) -#define CV_64FC3 CV_MAKETYPE(CV_64F,3) -#define CV_64FC4 CV_MAKETYPE(CV_64F,4) -#define CV_64FC(n) CV_MAKETYPE(CV_64F,(n)) - -#define CV_16FC1 CV_MAKETYPE(CV_16F,1) -#define CV_16FC2 CV_MAKETYPE(CV_16F,2) -#define CV_16FC3 CV_MAKETYPE(CV_16F,3) -#define CV_16FC4 CV_MAKETYPE(CV_16F,4) -#define CV_16FC(n) CV_MAKETYPE(CV_16F,(n)) -//! @} - -//! @name Comparison operation -//! @sa cv::CmpTypes -//! @{ -#define CV_HAL_CMP_EQ 0 -#define CV_HAL_CMP_GT 1 -#define CV_HAL_CMP_GE 2 -#define CV_HAL_CMP_LT 3 -#define CV_HAL_CMP_LE 4 -#define CV_HAL_CMP_NE 5 -//! @} - -//! @name Border processing modes -//! @sa cv::BorderTypes -//! @{ -#define CV_HAL_BORDER_CONSTANT 0 -#define CV_HAL_BORDER_REPLICATE 1 -#define CV_HAL_BORDER_REFLECT 2 -#define CV_HAL_BORDER_WRAP 3 -#define CV_HAL_BORDER_REFLECT_101 4 -#define CV_HAL_BORDER_TRANSPARENT 5 -#define CV_HAL_BORDER_ISOLATED 16 -//! @} - -//! @name DFT flags -//! @{ -#define CV_HAL_DFT_INVERSE 1 -#define CV_HAL_DFT_SCALE 2 -#define CV_HAL_DFT_ROWS 4 -#define CV_HAL_DFT_COMPLEX_OUTPUT 16 -#define CV_HAL_DFT_REAL_OUTPUT 32 -#define CV_HAL_DFT_TWO_STAGE 64 -#define CV_HAL_DFT_STAGE_COLS 128 -#define CV_HAL_DFT_IS_CONTINUOUS 512 -#define CV_HAL_DFT_IS_INPLACE 1024 -//! @} - -//! @name SVD flags -//! @{ -#define CV_HAL_SVD_NO_UV 1 -#define CV_HAL_SVD_SHORT_UV 2 -#define CV_HAL_SVD_MODIFY_A 4 -#define CV_HAL_SVD_FULL_UV 8 -//! @} - -//! @name Gemm flags -//! @{ -#define CV_HAL_GEMM_1_T 1 -#define CV_HAL_GEMM_2_T 2 -#define CV_HAL_GEMM_3_T 4 -//! @} - -//! @} - -#endif +#ifndef OPENCV_CORE_HAL_INTERFACE_H +#define OPENCV_CORE_HAL_INTERFACE_H + +//! @addtogroup core_hal_interface +//! @{ + +//! @name Return codes +//! @{ +#define CV_HAL_ERROR_OK 0 +#define CV_HAL_ERROR_NOT_IMPLEMENTED 1 +#define CV_HAL_ERROR_UNKNOWN -1 +//! @} + +#ifdef __cplusplus +#include +#else +#include +#include +#endif + +//! @name Data types +//! primitive types +//! - schar - signed 1 byte integer +//! - uchar - unsigned 1 byte integer +//! - short - signed 2 byte integer +//! - ushort - unsigned 2 byte integer +//! - int - signed 4 byte integer +//! - uint - unsigned 4 byte integer +//! - int64 - signed 8 byte integer +//! - uint64 - unsigned 8 byte integer +//! @{ +#if !defined _MSC_VER && !defined __BORLANDC__ +# if defined __cplusplus && __cplusplus >= 201103L && !defined __APPLE__ +# include +# ifdef __NEWLIB__ + typedef unsigned int uint; +# else + typedef std::uint32_t uint; +# endif +# else +# include + typedef uint32_t uint; +# endif +#else + typedef unsigned uint; +#endif + +typedef signed char schar; + +#ifndef __IPL_H__ + typedef unsigned char uchar; + typedef unsigned short ushort; +#endif + +#if defined _MSC_VER || defined __BORLANDC__ + typedef __int64 int64; + typedef unsigned __int64 uint64; +# define CV_BIG_INT(n) n##I64 +# define CV_BIG_UINT(n) n##UI64 +#else + typedef int64_t int64; + typedef uint64_t uint64; +# define CV_BIG_INT(n) n##LL +# define CV_BIG_UINT(n) n##ULL +#endif + +#define CV_USRTYPE1 (void)"CV_USRTYPE1 support has been dropped in OpenCV 4.0" + +#define CV_CN_MAX 512 +#define CV_CN_SHIFT 3 +#define CV_DEPTH_MAX (1 << CV_CN_SHIFT) + +#define CV_8U 0 +#define CV_8S 1 +#define CV_16U 2 +#define CV_16S 3 +#define CV_32S 4 +#define CV_32F 5 +#define CV_64F 6 +#define CV_16F 7 + +#define CV_MAT_DEPTH_MASK (CV_DEPTH_MAX - 1) +#define CV_MAT_DEPTH(flags) ((flags) & CV_MAT_DEPTH_MASK) + +#define CV_MAKETYPE(depth,cn) (CV_MAT_DEPTH(depth) + (((cn)-1) << CV_CN_SHIFT)) +#define CV_MAKE_TYPE CV_MAKETYPE + +#define CV_8UC1 CV_MAKETYPE(CV_8U,1) +#define CV_8UC2 CV_MAKETYPE(CV_8U,2) +#define CV_8UC3 CV_MAKETYPE(CV_8U,3) +#define CV_8UC4 CV_MAKETYPE(CV_8U,4) +#define CV_8UC(n) CV_MAKETYPE(CV_8U,(n)) + +#define CV_8SC1 CV_MAKETYPE(CV_8S,1) +#define CV_8SC2 CV_MAKETYPE(CV_8S,2) +#define CV_8SC3 CV_MAKETYPE(CV_8S,3) +#define CV_8SC4 CV_MAKETYPE(CV_8S,4) +#define CV_8SC(n) CV_MAKETYPE(CV_8S,(n)) + +#define CV_16UC1 CV_MAKETYPE(CV_16U,1) +#define CV_16UC2 CV_MAKETYPE(CV_16U,2) +#define CV_16UC3 CV_MAKETYPE(CV_16U,3) +#define CV_16UC4 CV_MAKETYPE(CV_16U,4) +#define CV_16UC(n) CV_MAKETYPE(CV_16U,(n)) + +#define CV_16SC1 CV_MAKETYPE(CV_16S,1) +#define CV_16SC2 CV_MAKETYPE(CV_16S,2) +#define CV_16SC3 CV_MAKETYPE(CV_16S,3) +#define CV_16SC4 CV_MAKETYPE(CV_16S,4) +#define CV_16SC(n) CV_MAKETYPE(CV_16S,(n)) + +#define CV_32SC1 CV_MAKETYPE(CV_32S,1) +#define CV_32SC2 CV_MAKETYPE(CV_32S,2) +#define CV_32SC3 CV_MAKETYPE(CV_32S,3) +#define CV_32SC4 CV_MAKETYPE(CV_32S,4) +#define CV_32SC(n) CV_MAKETYPE(CV_32S,(n)) + +#define CV_32FC1 CV_MAKETYPE(CV_32F,1) +#define CV_32FC2 CV_MAKETYPE(CV_32F,2) +#define CV_32FC3 CV_MAKETYPE(CV_32F,3) +#define CV_32FC4 CV_MAKETYPE(CV_32F,4) +#define CV_32FC(n) CV_MAKETYPE(CV_32F,(n)) + +#define CV_64FC1 CV_MAKETYPE(CV_64F,1) +#define CV_64FC2 CV_MAKETYPE(CV_64F,2) +#define CV_64FC3 CV_MAKETYPE(CV_64F,3) +#define CV_64FC4 CV_MAKETYPE(CV_64F,4) +#define CV_64FC(n) CV_MAKETYPE(CV_64F,(n)) + +#define CV_16FC1 CV_MAKETYPE(CV_16F,1) +#define CV_16FC2 CV_MAKETYPE(CV_16F,2) +#define CV_16FC3 CV_MAKETYPE(CV_16F,3) +#define CV_16FC4 CV_MAKETYPE(CV_16F,4) +#define CV_16FC(n) CV_MAKETYPE(CV_16F,(n)) +//! @} + +//! @name Comparison operation +//! @sa cv::CmpTypes +//! @{ +#define CV_HAL_CMP_EQ 0 +#define CV_HAL_CMP_GT 1 +#define CV_HAL_CMP_GE 2 +#define CV_HAL_CMP_LT 3 +#define CV_HAL_CMP_LE 4 +#define CV_HAL_CMP_NE 5 +//! @} + +//! @name Border processing modes +//! @sa cv::BorderTypes +//! @{ +#define CV_HAL_BORDER_CONSTANT 0 +#define CV_HAL_BORDER_REPLICATE 1 +#define CV_HAL_BORDER_REFLECT 2 +#define CV_HAL_BORDER_WRAP 3 +#define CV_HAL_BORDER_REFLECT_101 4 +#define CV_HAL_BORDER_TRANSPARENT 5 +#define CV_HAL_BORDER_ISOLATED 16 +//! @} + +//! @name DFT flags +//! @{ +#define CV_HAL_DFT_INVERSE 1 +#define CV_HAL_DFT_SCALE 2 +#define CV_HAL_DFT_ROWS 4 +#define CV_HAL_DFT_COMPLEX_OUTPUT 16 +#define CV_HAL_DFT_REAL_OUTPUT 32 +#define CV_HAL_DFT_TWO_STAGE 64 +#define CV_HAL_DFT_STAGE_COLS 128 +#define CV_HAL_DFT_IS_CONTINUOUS 512 +#define CV_HAL_DFT_IS_INPLACE 1024 +//! @} + +//! @name SVD flags +//! @{ +#define CV_HAL_SVD_NO_UV 1 +#define CV_HAL_SVD_SHORT_UV 2 +#define CV_HAL_SVD_MODIFY_A 4 +#define CV_HAL_SVD_FULL_UV 8 +//! @} + +//! @name Gemm flags +//! @{ +#define CV_HAL_GEMM_1_T 1 +#define CV_HAL_GEMM_2_T 2 +#define CV_HAL_GEMM_3_T 4 +//! @} + +//! @} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin.hpp index 781bd045a5..afb74dc953 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin.hpp @@ -1,988 +1,988 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_HAL_INTRIN_HPP -#define OPENCV_HAL_INTRIN_HPP - -#include -#include -#include -#include "opencv2/core/cvdef.h" - -#if defined(__GNUC__) && __GNUC__ == 12 -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wuninitialized" -#pragma GCC diagnostic ignored "-Wmaybe-uninitialized" -#endif - -#define OPENCV_HAL_ADD(a, b) ((a) + (b)) -#define OPENCV_HAL_AND(a, b) ((a) & (b)) -#define OPENCV_HAL_NOP(a) (a) -#define OPENCV_HAL_1ST(a, b) (a) - -namespace { -inline unsigned int trailingZeros32(unsigned int value) { -#if defined(_MSC_VER) -#if (_MSC_VER < 1700) || defined(_M_ARM) || defined(_M_ARM64) || defined(_M_ARM64EC) - unsigned long index = 0; - _BitScanForward(&index, value); - return (unsigned int)index; -#elif defined(__clang__) - // clang-cl doesn't export _tzcnt_u32 for non BMI systems - return value ? __builtin_ctz(value) : 32; -#else - return _tzcnt_u32(value); -#endif -#elif defined(__GNUC__) || defined(__GNUG__) - return __builtin_ctz(value); -#elif defined(__ICC) || defined(__INTEL_COMPILER) - return _bit_scan_forward(value); -#elif defined(__clang__) - return llvm.cttz.i32(value, true); -#else - static const int MultiplyDeBruijnBitPosition[32] = { - 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, - 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9 }; - return MultiplyDeBruijnBitPosition[((uint32_t)((value & -value) * 0x077CB531U)) >> 27]; -#endif -} -} - -// unlike HAL API, which is in cv::hal, -// we put intrinsics into cv namespace to make its -// access from within opencv code more accessible -namespace cv { - -namespace hal { - -enum StoreMode -{ - STORE_UNALIGNED = 0, - STORE_ALIGNED = 1, - STORE_ALIGNED_NOCACHE = 2 -}; - -} - -// TODO FIXIT: Don't use "God" traits. Split on separate cases. -template struct V_TypeTraits -{ -}; - -#define CV_INTRIN_DEF_TYPE_TRAITS(type, int_type_, uint_type_, abs_type_, w_type_, q_type_, sum_type_) \ - template<> struct V_TypeTraits \ - { \ - typedef type value_type; \ - typedef int_type_ int_type; \ - typedef abs_type_ abs_type; \ - typedef uint_type_ uint_type; \ - typedef w_type_ w_type; \ - typedef q_type_ q_type; \ - typedef sum_type_ sum_type; \ - \ - static inline int_type reinterpret_int(type x) \ - { \ - union { type l; int_type i; } v; \ - v.l = x; \ - return v.i; \ - } \ - \ - static inline type reinterpret_from_int(int_type x) \ - { \ - union { type l; int_type i; } v; \ - v.i = x; \ - return v.l; \ - } \ - } - -#define CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(type, int_type_, uint_type_, abs_type_, w_type_, sum_type_) \ - template<> struct V_TypeTraits \ - { \ - typedef type value_type; \ - typedef int_type_ int_type; \ - typedef abs_type_ abs_type; \ - typedef uint_type_ uint_type; \ - typedef w_type_ w_type; \ - typedef sum_type_ sum_type; \ - \ - static inline int_type reinterpret_int(type x) \ - { \ - union { type l; int_type i; } v; \ - v.l = x; \ - return v.i; \ - } \ - \ - static inline type reinterpret_from_int(int_type x) \ - { \ - union { type l; int_type i; } v; \ - v.i = x; \ - return v.l; \ - } \ - } - -CV_INTRIN_DEF_TYPE_TRAITS(uchar, schar, uchar, uchar, ushort, unsigned, unsigned); -CV_INTRIN_DEF_TYPE_TRAITS(schar, schar, uchar, uchar, short, int, int); -CV_INTRIN_DEF_TYPE_TRAITS(ushort, short, ushort, ushort, unsigned, uint64, unsigned); -CV_INTRIN_DEF_TYPE_TRAITS(short, short, ushort, ushort, int, int64, int); -CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(unsigned, int, unsigned, unsigned, uint64, unsigned); -CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(int, int, unsigned, unsigned, int64, int); -CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(float, int, unsigned, float, double, float); -CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(uint64, int64, uint64, uint64, void, uint64); -CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(int64, int64, uint64, uint64, void, int64); -CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(double, int64, uint64, double, void, double); - -#ifndef CV_DOXYGEN - -#ifndef CV_CPU_OPTIMIZATION_HAL_NAMESPACE -#ifdef CV_FORCE_SIMD128_CPP - #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE hal_EMULATOR_CPP - #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN namespace hal_EMULATOR_CPP { - #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END } -#elif defined(CV_CPU_DISPATCH_MODE) - #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE __CV_CAT(hal_, CV_CPU_DISPATCH_MODE) - #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN namespace __CV_CAT(hal_, CV_CPU_DISPATCH_MODE) { - #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END } -#else - #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE hal_baseline - #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN namespace hal_baseline { - #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END } -#endif -#endif // CV_CPU_OPTIMIZATION_HAL_NAMESPACE - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -template inline _VecTp v_setzero_(); -template inline _VecTp v_setall_(uchar); -template inline _VecTp v_setall_(schar); -template inline _VecTp v_setall_(ushort); -template inline _VecTp v_setall_(short); -template inline _VecTp v_setall_(unsigned); -template inline _VecTp v_setall_(int); -template inline _VecTp v_setall_(uint64); -template inline _VecTp v_setall_(int64); -template inline _VecTp v_setall_(float); -template inline _VecTp v_setall_(double); - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END -using namespace CV_CPU_OPTIMIZATION_HAL_NAMESPACE; -#endif -} - -#ifdef CV_DOXYGEN -# undef CV_AVX2 -# undef CV_SSE2 -# undef CV_NEON -# undef CV_VSX -# undef CV_FP16 -# undef CV_MSA -# undef CV_RVV -#endif - -#if (CV_SSE2 || CV_NEON || CV_VSX || CV_MSA || CV_WASM_SIMD || CV_RVV071 || CV_LSX) && !defined(CV_FORCE_SIMD128_CPP) -#define CV__SIMD_FORWARD 128 -#include "opencv2/core/hal/intrin_forward.hpp" -#endif - -#if CV_SSE2 && !defined(CV_FORCE_SIMD128_CPP) - -#include "opencv2/core/hal/intrin_sse_em.hpp" -#include "opencv2/core/hal/intrin_sse.hpp" - -#elif CV_NEON && !defined(CV_FORCE_SIMD128_CPP) - -#include "opencv2/core/hal/intrin_neon.hpp" - -#elif CV_RVV071 && !defined(CV_FORCE_SIMD128_CPP) -#define CV_SIMD128_CPP 0 -#include "opencv2/core/hal/intrin_rvv071.hpp" - -#elif CV_VSX && !defined(CV_FORCE_SIMD128_CPP) - -#include "opencv2/core/hal/intrin_vsx.hpp" - -#elif CV_MSA && !defined(CV_FORCE_SIMD128_CPP) - -#include "opencv2/core/hal/intrin_msa.hpp" - -#elif CV_WASM_SIMD && !defined(CV_FORCE_SIMD128_CPP) -#include "opencv2/core/hal/intrin_wasm.hpp" - -#elif CV_RVV && !defined(CV_FORCE_SIMD128_CPP) -#include "opencv2/core/hal/intrin_rvv_scalable.hpp" - -#elif CV_LSX && !defined(CV_FORCE_SIMD128_CPP) - -#include "opencv2/core/hal/intrin_lsx.hpp" - -#else - -#include "opencv2/core/hal/intrin_cpp.hpp" - -#endif - -// AVX2 can be used together with SSE2, so -// we define those two sets of intrinsics at once. -// Most of the intrinsics do not conflict (the proper overloaded variant is -// resolved by the argument types, e.g. v_float32x4 ~ SSE2, v_float32x8 ~ AVX2), -// but some of AVX2 intrinsics get v256_ prefix instead of v_, e.g. v256_load() vs v_load(). -// Correspondingly, the wide intrinsics (which are mapped to the "widest" -// available instruction set) will get vx_ prefix -// (and will be mapped to v256_ counterparts) (e.g. vx_load() => v256_load()) -#if CV_AVX2 - -#define CV__SIMD_FORWARD 256 -#include "opencv2/core/hal/intrin_forward.hpp" -#include "opencv2/core/hal/intrin_avx.hpp" - -#endif - -// AVX512 can be used together with SSE2 and AVX2, so -// we define those sets of intrinsics at once. -// For some of AVX512 intrinsics get v512_ prefix instead of v_, e.g. v512_load() vs v_load(). -// Wide intrinsics will be mapped to v512_ counterparts in this case(e.g. vx_load() => v512_load()) -#if CV_AVX512_SKX - -#define CV__SIMD_FORWARD 512 -#include "opencv2/core/hal/intrin_forward.hpp" -#include "opencv2/core/hal/intrin_avx512.hpp" - -#endif - -#if CV_LASX - -#define CV__SIMD_FORWARD 256 -#include "opencv2/core/hal/intrin_forward.hpp" -#include "opencv2/core/hal/intrin_lasx.hpp" - -#endif - -//! @cond IGNORED - -namespace cv { - -#ifndef CV_DOXYGEN -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN -#endif - -#ifndef CV_SIMD128 -#define CV_SIMD128 0 -#endif - -#ifndef CV_SIMD128_CPP -#define CV_SIMD128_CPP 0 -#endif - -#ifndef CV_SIMD128_64F -#define CV_SIMD128_64F 0 -#endif - -#ifndef CV_SIMD256 -#define CV_SIMD256 0 -#endif - -#ifndef CV_SIMD256_64F -#define CV_SIMD256_64F 0 -#endif - -#ifndef CV_SIMD512 -#define CV_SIMD512 0 -#endif - -#ifndef CV_SIMD512_64F -#define CV_SIMD512_64F 0 -#endif - -#ifndef CV_SIMD128_FP16 -#define CV_SIMD128_FP16 0 -#endif - -#ifndef CV_SIMD256_FP16 -#define CV_SIMD256_FP16 0 -#endif - -#ifndef CV_SIMD512_FP16 -#define CV_SIMD512_FP16 0 -#endif - -#ifndef CV_SIMD_SCALABLE -#define CV_SIMD_SCALABLE 0 -#endif - -#ifndef CV_SIMD_SCALABLE_64F -#define CV_SIMD_SCALABLE_64F 0 -#endif - -//================================================================================================== - -template struct V_RegTraits -{ -}; - -#define CV_DEF_REG_TRAITS(prefix, _reg, lane_type, suffix, _u_reg, _w_reg, _q_reg, _int_reg, _round_reg) \ - template<> struct V_RegTraits<_reg> \ - { \ - typedef _reg reg; \ - typedef _u_reg u_reg; \ - typedef _w_reg w_reg; \ - typedef _q_reg q_reg; \ - typedef _int_reg int_reg; \ - typedef _round_reg round_reg; \ - } - -#if CV_SIMD128 || CV_SIMD128_CPP - CV_DEF_REG_TRAITS(v, v_uint8x16, uchar, u8, v_uint8x16, v_uint16x8, v_uint32x4, v_int8x16, void); - CV_DEF_REG_TRAITS(v, v_int8x16, schar, s8, v_uint8x16, v_int16x8, v_int32x4, v_int8x16, void); - CV_DEF_REG_TRAITS(v, v_uint16x8, ushort, u16, v_uint16x8, v_uint32x4, v_uint64x2, v_int16x8, void); - CV_DEF_REG_TRAITS(v, v_int16x8, short, s16, v_uint16x8, v_int32x4, v_int64x2, v_int16x8, void); - CV_DEF_REG_TRAITS(v, v_uint32x4, unsigned, u32, v_uint32x4, v_uint64x2, void, v_int32x4, void); - CV_DEF_REG_TRAITS(v, v_int32x4, int, s32, v_uint32x4, v_int64x2, void, v_int32x4, void); -#if CV_SIMD128_64F || CV_SIMD128_CPP - CV_DEF_REG_TRAITS(v, v_float32x4, float, f32, v_float32x4, v_float64x2, void, v_int32x4, v_int32x4); -#else - CV_DEF_REG_TRAITS(v, v_float32x4, float, f32, v_float32x4, void, void, v_int32x4, v_int32x4); -#endif - CV_DEF_REG_TRAITS(v, v_uint64x2, uint64, u64, v_uint64x2, void, void, v_int64x2, void); - CV_DEF_REG_TRAITS(v, v_int64x2, int64, s64, v_uint64x2, void, void, v_int64x2, void); -#if CV_SIMD128_64F - CV_DEF_REG_TRAITS(v, v_float64x2, double, f64, v_float64x2, void, void, v_int64x2, v_int32x4); -#endif -#endif - -#if CV_SIMD256 - CV_DEF_REG_TRAITS(v256, v_uint8x32, uchar, u8, v_uint8x32, v_uint16x16, v_uint32x8, v_int8x32, void); - CV_DEF_REG_TRAITS(v256, v_int8x32, schar, s8, v_uint8x32, v_int16x16, v_int32x8, v_int8x32, void); - CV_DEF_REG_TRAITS(v256, v_uint16x16, ushort, u16, v_uint16x16, v_uint32x8, v_uint64x4, v_int16x16, void); - CV_DEF_REG_TRAITS(v256, v_int16x16, short, s16, v_uint16x16, v_int32x8, v_int64x4, v_int16x16, void); - CV_DEF_REG_TRAITS(v256, v_uint32x8, unsigned, u32, v_uint32x8, v_uint64x4, void, v_int32x8, void); - CV_DEF_REG_TRAITS(v256, v_int32x8, int, s32, v_uint32x8, v_int64x4, void, v_int32x8, void); - CV_DEF_REG_TRAITS(v256, v_float32x8, float, f32, v_float32x8, v_float64x4, void, v_int32x8, v_int32x8); - CV_DEF_REG_TRAITS(v256, v_uint64x4, uint64, u64, v_uint64x4, void, void, v_int64x4, void); - CV_DEF_REG_TRAITS(v256, v_int64x4, int64, s64, v_uint64x4, void, void, v_int64x4, void); - CV_DEF_REG_TRAITS(v256, v_float64x4, double, f64, v_float64x4, void, void, v_int64x4, v_int32x8); -#endif - -#if CV_SIMD512 - CV_DEF_REG_TRAITS(v512, v_uint8x64, uchar, u8, v_uint8x64, v_uint16x32, v_uint32x16, v_int8x64, void); - CV_DEF_REG_TRAITS(v512, v_int8x64, schar, s8, v_uint8x64, v_int16x32, v_int32x16, v_int8x64, void); - CV_DEF_REG_TRAITS(v512, v_uint16x32, ushort, u16, v_uint16x32, v_uint32x16, v_uint64x8, v_int16x32, void); - CV_DEF_REG_TRAITS(v512, v_int16x32, short, s16, v_uint16x32, v_int32x16, v_int64x8, v_int16x32, void); - CV_DEF_REG_TRAITS(v512, v_uint32x16, unsigned, u32, v_uint32x16, v_uint64x8, void, v_int32x16, void); - CV_DEF_REG_TRAITS(v512, v_int32x16, int, s32, v_uint32x16, v_int64x8, void, v_int32x16, void); - CV_DEF_REG_TRAITS(v512, v_float32x16, float, f32, v_float32x16, v_float64x8, void, v_int32x16, v_int32x16); - CV_DEF_REG_TRAITS(v512, v_uint64x8, uint64, u64, v_uint64x8, void, void, v_int64x8, void); - CV_DEF_REG_TRAITS(v512, v_int64x8, int64, s64, v_uint64x8, void, void, v_int64x8, void); - CV_DEF_REG_TRAITS(v512, v_float64x8, double, f64, v_float64x8, void, void, v_int64x8, v_int32x16); -#endif -#if CV_SIMD_SCALABLE - CV_DEF_REG_TRAITS(v, v_uint8, uchar, u8, v_uint8, v_uint16, v_uint32, v_int8, void); - CV_DEF_REG_TRAITS(v, v_int8, schar, s8, v_uint8, v_int16, v_int32, v_int8, void); - CV_DEF_REG_TRAITS(v, v_uint16, ushort, u16, v_uint16, v_uint32, v_uint64, v_int16, void); - CV_DEF_REG_TRAITS(v, v_int16, short, s16, v_uint16, v_int32, v_int64, v_int16, void); - CV_DEF_REG_TRAITS(v, v_uint32, unsigned, u32, v_uint32, v_uint64, void, v_int32, void); - CV_DEF_REG_TRAITS(v, v_int32, int, s32, v_uint32, v_int64, void, v_int32, void); - CV_DEF_REG_TRAITS(v, v_float32, float, f32, v_float32, v_float64, void, v_int32, v_int32); - CV_DEF_REG_TRAITS(v, v_uint64, uint64, u64, v_uint64, void, void, v_int64, void); - CV_DEF_REG_TRAITS(v, v_int64, int64, s64, v_uint64, void, void, v_int64, void); - CV_DEF_REG_TRAITS(v, v_float64, double, f64, v_float64, void, void, v_int64, v_int32); -#endif -//! @endcond - -#if CV_SIMD512 && (!defined(CV__SIMD_FORCE_WIDTH) || CV__SIMD_FORCE_WIDTH == 512) -#define CV__SIMD_NAMESPACE simd512 -namespace CV__SIMD_NAMESPACE { - #define CV_SIMD 1 - #define CV_SIMD_64F CV_SIMD512_64F - #define CV_SIMD_FP16 CV_SIMD512_FP16 - #define CV_SIMD_WIDTH 64 -//! @addtogroup core_hal_intrin -//! @{ - //! @brief Maximum available vector register capacity 8-bit unsigned integer values - typedef v_uint8x64 v_uint8; - //! @brief Maximum available vector register capacity 8-bit signed integer values - typedef v_int8x64 v_int8; - //! @brief Maximum available vector register capacity 16-bit unsigned integer values - typedef v_uint16x32 v_uint16; - //! @brief Maximum available vector register capacity 16-bit signed integer values - typedef v_int16x32 v_int16; - //! @brief Maximum available vector register capacity 32-bit unsigned integer values - typedef v_uint32x16 v_uint32; - //! @brief Maximum available vector register capacity 32-bit signed integer values - typedef v_int32x16 v_int32; - //! @brief Maximum available vector register capacity 64-bit unsigned integer values - typedef v_uint64x8 v_uint64; - //! @brief Maximum available vector register capacity 64-bit signed integer values - typedef v_int64x8 v_int64; - //! @brief Maximum available vector register capacity 32-bit floating point values (single precision) - typedef v_float32x16 v_float32; - #if CV_SIMD512_64F - //! @brief Maximum available vector register capacity 64-bit floating point values (double precision) - typedef v_float64x8 v_float64; - #endif -//! @} - - #define VXPREFIX(func) v512##func -} // namespace -using namespace CV__SIMD_NAMESPACE; -#elif CV_SIMD256 && (!defined(CV__SIMD_FORCE_WIDTH) || CV__SIMD_FORCE_WIDTH == 256) -#define CV__SIMD_NAMESPACE simd256 -namespace CV__SIMD_NAMESPACE { - #define CV_SIMD 1 - #define CV_SIMD_64F CV_SIMD256_64F - #define CV_SIMD_FP16 CV_SIMD256_FP16 - #define CV_SIMD_WIDTH 32 -//! @addtogroup core_hal_intrin -//! @{ - //! @brief Maximum available vector register capacity 8-bit unsigned integer values - typedef v_uint8x32 v_uint8; - //! @brief Maximum available vector register capacity 8-bit signed integer values - typedef v_int8x32 v_int8; - //! @brief Maximum available vector register capacity 16-bit unsigned integer values - typedef v_uint16x16 v_uint16; - //! @brief Maximum available vector register capacity 16-bit signed integer values - typedef v_int16x16 v_int16; - //! @brief Maximum available vector register capacity 32-bit unsigned integer values - typedef v_uint32x8 v_uint32; - //! @brief Maximum available vector register capacity 32-bit signed integer values - typedef v_int32x8 v_int32; - //! @brief Maximum available vector register capacity 64-bit unsigned integer values - typedef v_uint64x4 v_uint64; - //! @brief Maximum available vector register capacity 64-bit signed integer values - typedef v_int64x4 v_int64; - //! @brief Maximum available vector register capacity 32-bit floating point values (single precision) - typedef v_float32x8 v_float32; - #if CV_SIMD256_64F - //! @brief Maximum available vector register capacity 64-bit floating point values (double precision) - typedef v_float64x4 v_float64; - #endif -//! @} - - #define VXPREFIX(func) v256##func -} // namespace -using namespace CV__SIMD_NAMESPACE; -#elif (CV_SIMD128 || CV_SIMD128_CPP) && (!defined(CV__SIMD_FORCE_WIDTH) || CV__SIMD_FORCE_WIDTH == 128) -#if defined CV_SIMD128_CPP -#define CV__SIMD_NAMESPACE simd128_cpp -#else -#define CV__SIMD_NAMESPACE simd128 -#endif -namespace CV__SIMD_NAMESPACE { - #define CV_SIMD CV_SIMD128 - #define CV_SIMD_64F CV_SIMD128_64F - #define CV_SIMD_WIDTH 16 -//! @addtogroup core_hal_intrin -//! @{ - //! @brief Maximum available vector register capacity 8-bit unsigned integer values - typedef v_uint8x16 v_uint8; - //! @brief Maximum available vector register capacity 8-bit signed integer values - typedef v_int8x16 v_int8; - //! @brief Maximum available vector register capacity 16-bit unsigned integer values - typedef v_uint16x8 v_uint16; - //! @brief Maximum available vector register capacity 16-bit signed integer values - typedef v_int16x8 v_int16; - //! @brief Maximum available vector register capacity 32-bit unsigned integer values - typedef v_uint32x4 v_uint32; - //! @brief Maximum available vector register capacity 32-bit signed integer values - typedef v_int32x4 v_int32; - //! @brief Maximum available vector register capacity 64-bit unsigned integer values - typedef v_uint64x2 v_uint64; - //! @brief Maximum available vector register capacity 64-bit signed integer values - typedef v_int64x2 v_int64; - //! @brief Maximum available vector register capacity 32-bit floating point values (single precision) - typedef v_float32x4 v_float32; - #if CV_SIMD128_64F - //! @brief Maximum available vector register capacity 64-bit floating point values (double precision) - typedef v_float64x2 v_float64; - #endif -//! @} - - #define VXPREFIX(func) v##func -} // namespace -using namespace CV__SIMD_NAMESPACE; - -#elif CV_SIMD_SCALABLE -#define CV__SIMD_NAMESPACE simd -namespace CV__SIMD_NAMESPACE { - #define CV_SIMD 0 - #define CV_SIMD_WIDTH 128 /* 1024/8 */ - - #define VXPREFIX(func) v##func -} // namespace -using namespace CV__SIMD_NAMESPACE; - -#endif - -//! @cond IGNORED -#ifndef CV_SIMD_64F -#define CV_SIMD_64F 0 -#endif - -namespace CV__SIMD_NAMESPACE { -//! @addtogroup core_hal_intrin -//! @{ - //! @name Wide init with value - //! @{ - //! @brief Create maximum available capacity vector with elements set to a specific value - inline v_uint8 vx_setall_u8(uchar v) { return VXPREFIX(_setall_u8)(v); } - inline v_int8 vx_setall_s8(schar v) { return VXPREFIX(_setall_s8)(v); } - inline v_uint16 vx_setall_u16(ushort v) { return VXPREFIX(_setall_u16)(v); } - inline v_int16 vx_setall_s16(short v) { return VXPREFIX(_setall_s16)(v); } - inline v_int32 vx_setall_s32(int v) { return VXPREFIX(_setall_s32)(v); } - inline v_uint32 vx_setall_u32(unsigned v) { return VXPREFIX(_setall_u32)(v); } - inline v_float32 vx_setall_f32(float v) { return VXPREFIX(_setall_f32)(v); } - inline v_int64 vx_setall_s64(int64 v) { return VXPREFIX(_setall_s64)(v); } - inline v_uint64 vx_setall_u64(uint64 v) { return VXPREFIX(_setall_u64)(v); } -#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F - inline v_float64 vx_setall_f64(double v) { return VXPREFIX(_setall_f64)(v); } -#endif - //! @} - - //! @name Wide init with zero - //! @{ - //! @brief Create maximum available capacity vector with elements set to zero - inline v_uint8 vx_setzero_u8() { return VXPREFIX(_setzero_u8)(); } - inline v_int8 vx_setzero_s8() { return VXPREFIX(_setzero_s8)(); } - inline v_uint16 vx_setzero_u16() { return VXPREFIX(_setzero_u16)(); } - inline v_int16 vx_setzero_s16() { return VXPREFIX(_setzero_s16)(); } - inline v_int32 vx_setzero_s32() { return VXPREFIX(_setzero_s32)(); } - inline v_uint32 vx_setzero_u32() { return VXPREFIX(_setzero_u32)(); } - inline v_float32 vx_setzero_f32() { return VXPREFIX(_setzero_f32)(); } - inline v_int64 vx_setzero_s64() { return VXPREFIX(_setzero_s64)(); } - inline v_uint64 vx_setzero_u64() { return VXPREFIX(_setzero_u64)(); } -#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F - inline v_float64 vx_setzero_f64() { return VXPREFIX(_setzero_f64)(); } -#endif - //! @} - - //! @name Wide load from memory - //! @{ - //! @brief Load maximum available capacity register contents from memory - inline v_uint8 vx_load(const uchar * ptr) { return VXPREFIX(_load)(ptr); } - inline v_int8 vx_load(const schar * ptr) { return VXPREFIX(_load)(ptr); } - inline v_uint16 vx_load(const ushort * ptr) { return VXPREFIX(_load)(ptr); } - inline v_int16 vx_load(const short * ptr) { return VXPREFIX(_load)(ptr); } - inline v_int32 vx_load(const int * ptr) { return VXPREFIX(_load)(ptr); } - inline v_uint32 vx_load(const unsigned * ptr) { return VXPREFIX(_load)(ptr); } - inline v_float32 vx_load(const float * ptr) { return VXPREFIX(_load)(ptr); } - inline v_int64 vx_load(const int64 * ptr) { return VXPREFIX(_load)(ptr); } - inline v_uint64 vx_load(const uint64 * ptr) { return VXPREFIX(_load)(ptr); } -#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F - inline v_float64 vx_load(const double * ptr) { return VXPREFIX(_load)(ptr); } -#endif - //! @} - - //! @name Wide load from memory(aligned) - //! @{ - //! @brief Load maximum available capacity register contents from memory(aligned) - inline v_uint8 vx_load_aligned(const uchar * ptr) { return VXPREFIX(_load_aligned)(ptr); } - inline v_int8 vx_load_aligned(const schar * ptr) { return VXPREFIX(_load_aligned)(ptr); } - inline v_uint16 vx_load_aligned(const ushort * ptr) { return VXPREFIX(_load_aligned)(ptr); } - inline v_int16 vx_load_aligned(const short * ptr) { return VXPREFIX(_load_aligned)(ptr); } - inline v_int32 vx_load_aligned(const int * ptr) { return VXPREFIX(_load_aligned)(ptr); } - inline v_uint32 vx_load_aligned(const unsigned * ptr) { return VXPREFIX(_load_aligned)(ptr); } - inline v_float32 vx_load_aligned(const float * ptr) { return VXPREFIX(_load_aligned)(ptr); } - inline v_int64 vx_load_aligned(const int64 * ptr) { return VXPREFIX(_load_aligned)(ptr); } - inline v_uint64 vx_load_aligned(const uint64 * ptr) { return VXPREFIX(_load_aligned)(ptr); } -#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F - inline v_float64 vx_load_aligned(const double * ptr) { return VXPREFIX(_load_aligned)(ptr); } -#endif - //! @} - - //! @name Wide load lower half from memory - //! @{ - //! @brief Load lower half of maximum available capacity register from memory - inline v_uint8 vx_load_low(const uchar * ptr) { return VXPREFIX(_load_low)(ptr); } - inline v_int8 vx_load_low(const schar * ptr) { return VXPREFIX(_load_low)(ptr); } - inline v_uint16 vx_load_low(const ushort * ptr) { return VXPREFIX(_load_low)(ptr); } - inline v_int16 vx_load_low(const short * ptr) { return VXPREFIX(_load_low)(ptr); } - inline v_int32 vx_load_low(const int * ptr) { return VXPREFIX(_load_low)(ptr); } - inline v_uint32 vx_load_low(const unsigned * ptr) { return VXPREFIX(_load_low)(ptr); } - inline v_float32 vx_load_low(const float * ptr) { return VXPREFIX(_load_low)(ptr); } - inline v_int64 vx_load_low(const int64 * ptr) { return VXPREFIX(_load_low)(ptr); } - inline v_uint64 vx_load_low(const uint64 * ptr) { return VXPREFIX(_load_low)(ptr); } -#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F - inline v_float64 vx_load_low(const double * ptr) { return VXPREFIX(_load_low)(ptr); } -#endif - //! @} - - //! @name Wide load halfs from memory - //! @{ - //! @brief Load maximum available capacity register contents from two memory blocks - inline v_uint8 vx_load_halves(const uchar * ptr0, const uchar * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } - inline v_int8 vx_load_halves(const schar * ptr0, const schar * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } - inline v_uint16 vx_load_halves(const ushort * ptr0, const ushort * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } - inline v_int16 vx_load_halves(const short * ptr0, const short * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } - inline v_int32 vx_load_halves(const int * ptr0, const int * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } - inline v_uint32 vx_load_halves(const unsigned * ptr0, const unsigned * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } - inline v_float32 vx_load_halves(const float * ptr0, const float * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } - inline v_int64 vx_load_halves(const int64 * ptr0, const int64 * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } - inline v_uint64 vx_load_halves(const uint64 * ptr0, const uint64 * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } -#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F - inline v_float64 vx_load_halves(const double * ptr0, const double * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } -#endif - //! @} - - //! @name Wide LUT of elements - //! @{ - //! @brief Load maximum available capacity register contents with array elements by provided indexes - inline v_uint8 vx_lut(const uchar * ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } - inline v_int8 vx_lut(const schar * ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } - inline v_uint16 vx_lut(const ushort * ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } - inline v_int16 vx_lut(const short* ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } - inline v_int32 vx_lut(const int* ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } - inline v_uint32 vx_lut(const unsigned* ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } - inline v_float32 vx_lut(const float* ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } - inline v_int64 vx_lut(const int64 * ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } - inline v_uint64 vx_lut(const uint64 * ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } -#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F - inline v_float64 vx_lut(const double* ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } -#endif - //! @} - - //! @name Wide LUT of element pairs - //! @{ - //! @brief Load maximum available capacity register contents with array element pairs by provided indexes - inline v_uint8 vx_lut_pairs(const uchar * ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } - inline v_int8 vx_lut_pairs(const schar * ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } - inline v_uint16 vx_lut_pairs(const ushort * ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } - inline v_int16 vx_lut_pairs(const short* ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } - inline v_int32 vx_lut_pairs(const int* ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } - inline v_uint32 vx_lut_pairs(const unsigned* ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } - inline v_float32 vx_lut_pairs(const float* ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } - inline v_int64 vx_lut_pairs(const int64 * ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } - inline v_uint64 vx_lut_pairs(const uint64 * ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } -#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F - inline v_float64 vx_lut_pairs(const double* ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } -#endif - //! @} - - //! @name Wide LUT of element quads - //! @{ - //! @brief Load maximum available capacity register contents with array element quads by provided indexes - inline v_uint8 vx_lut_quads(const uchar* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } - inline v_int8 vx_lut_quads(const schar* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } - inline v_uint16 vx_lut_quads(const ushort* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } - inline v_int16 vx_lut_quads(const short* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } - inline v_int32 vx_lut_quads(const int* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } - inline v_uint32 vx_lut_quads(const unsigned* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } - inline v_float32 vx_lut_quads(const float* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } - //! @} - - //! @name Wide load with double expansion - //! @{ - //! @brief Load maximum available capacity register contents from memory with double expand - inline v_uint16 vx_load_expand(const uchar * ptr) { return VXPREFIX(_load_expand)(ptr); } - inline v_int16 vx_load_expand(const schar * ptr) { return VXPREFIX(_load_expand)(ptr); } - inline v_uint32 vx_load_expand(const ushort * ptr) { return VXPREFIX(_load_expand)(ptr); } - inline v_int32 vx_load_expand(const short* ptr) { return VXPREFIX(_load_expand)(ptr); } - inline v_int64 vx_load_expand(const int* ptr) { return VXPREFIX(_load_expand)(ptr); } - inline v_uint64 vx_load_expand(const unsigned* ptr) { return VXPREFIX(_load_expand)(ptr); } - inline v_float32 vx_load_expand(const hfloat * ptr) { return VXPREFIX(_load_expand)(ptr); } - //! @} - - //! @name Wide load with quad expansion - //! @{ - //! @brief Load maximum available capacity register contents from memory with quad expand - inline v_uint32 vx_load_expand_q(const uchar * ptr) { return VXPREFIX(_load_expand_q)(ptr); } - inline v_int32 vx_load_expand_q(const schar * ptr) { return VXPREFIX(_load_expand_q)(ptr); } - //! @} - - /** @brief SIMD processing state cleanup call */ - inline void vx_cleanup() { VXPREFIX(_cleanup)(); } - -#if !CV_SIMD_SCALABLE - // Compatibility layer -#if !(CV_NEON && !defined(CV_FORCE_SIMD128_CPP)) - template struct VTraits { - static inline int vlanes() { return T::nlanes; } - enum { nlanes = T::nlanes, max_nlanes = T::nlanes }; - using lane_type = typename T::lane_type; - }; - - //////////// get0 //////////// - #define OPENCV_HAL_WRAP_GRT0(_Tpvec) \ - inline typename VTraits<_Tpvec>::lane_type v_get0(const _Tpvec& v) \ - { \ - return v.get0(); \ - } - - OPENCV_HAL_WRAP_GRT0(v_uint8) - OPENCV_HAL_WRAP_GRT0(v_int8) - OPENCV_HAL_WRAP_GRT0(v_uint16) - OPENCV_HAL_WRAP_GRT0(v_int16) - OPENCV_HAL_WRAP_GRT0(v_uint32) - OPENCV_HAL_WRAP_GRT0(v_int32) - OPENCV_HAL_WRAP_GRT0(v_uint64) - OPENCV_HAL_WRAP_GRT0(v_int64) - OPENCV_HAL_WRAP_GRT0(v_float32) - #if CV_SIMD_64F - OPENCV_HAL_WRAP_GRT0(v_float64) - #endif - #if CV_SIMD_WIDTH != 16/*128*/ && CV_SIMD128 - OPENCV_HAL_WRAP_GRT0(v_uint8x16) - OPENCV_HAL_WRAP_GRT0(v_uint16x8) - OPENCV_HAL_WRAP_GRT0(v_uint32x4) - OPENCV_HAL_WRAP_GRT0(v_uint64x2) - OPENCV_HAL_WRAP_GRT0(v_int8x16) - OPENCV_HAL_WRAP_GRT0(v_int16x8) - OPENCV_HAL_WRAP_GRT0(v_int32x4) - OPENCV_HAL_WRAP_GRT0(v_int64x2) - OPENCV_HAL_WRAP_GRT0(v_float32x4) - #if CV_SIMD_64F - OPENCV_HAL_WRAP_GRT0(v_float64x2) - #endif - #endif - #if CV_SIMD_WIDTH != 32/*256*/ && CV_SIMD256 - OPENCV_HAL_WRAP_GRT0(v_uint8x32) - OPENCV_HAL_WRAP_GRT0(v_uint16x16) - OPENCV_HAL_WRAP_GRT0(v_uint32x8) - OPENCV_HAL_WRAP_GRT0(v_uint64x4) - OPENCV_HAL_WRAP_GRT0(v_int8x32) - OPENCV_HAL_WRAP_GRT0(v_int16x16) - OPENCV_HAL_WRAP_GRT0(v_int32x8) - OPENCV_HAL_WRAP_GRT0(v_int64x4) - OPENCV_HAL_WRAP_GRT0(v_float32x8) - #if CV_SIMD_64F - OPENCV_HAL_WRAP_GRT0(v_float64x4) - #endif - #endif -#endif - - #define OPENCV_HAL_WRAP_BIN_OP_ADDSUB(_Tpvec) \ - template \ - inline _Tpvec v_add(const _Tpvec& f1, const _Tpvec& f2, const _Tpvec& f3, const Args&... vf) { \ - return v_add(v_add(f1, f2), f3, vf...); \ - } - - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint8) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint16) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint32) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint64) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int8) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int16) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int32) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int64) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_float32) - #if CV_SIMD_64F - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_float64) - #endif - #if CV_SIMD_WIDTH != 16/*128*/ && CV_SIMD128 - // when we use CV_SIMD128 with 256/512 bit SIMD (e.g. AVX2 or AVX512) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint8x16) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint16x8) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint32x4) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint64x2) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int8x16) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int16x8) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int32x4) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int64x2) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_float32x4) - #if CV_SIMD_64F - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_float64x2) - #endif - #endif - #if CV_SIMD_WIDTH != 32/*256*/ && CV_SIMD256 - // when we use CV_SIMD256 with 512 bit SIMD (e.g. AVX512) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint8x32) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint16x16) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint32x8) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint64x4) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int8x32) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int16x16) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int32x8) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int64x4) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_float32x8) - #if CV_SIMD_64F - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_float64x4) - #endif - #endif - - #define OPENCV_HAL_WRAP_BIN_OP_MUL(_Tpvec) \ - template \ - inline _Tpvec v_mul(const _Tpvec& f1, const _Tpvec& f2, const _Tpvec& f3, const Args&... vf) { \ - return v_mul(v_mul(f1, f2), f3, vf...); \ - } - OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint8) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_int8) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint16) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint32) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_int16) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_int32) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_float32) - #if CV_SIMD_64F - OPENCV_HAL_WRAP_BIN_OP_MUL(v_float64) - #endif - #if CV_SIMD_WIDTH != 16/*128*/ && CV_SIMD128 - OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint8x16) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint16x8) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint32x4) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_int8x16) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_int16x8) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_int32x4) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_float32x4) - #if CV_SIMD_64F - OPENCV_HAL_WRAP_BIN_OP_MUL(v_float64x2) - #endif - #endif - #if CV_SIMD_WIDTH != 32/*256*/ && CV_SIMD256 - OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint8x32) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint16x16) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint32x8) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_int8x32) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_int16x16) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_int32x8) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_float32x8) - #if CV_SIMD_64F - OPENCV_HAL_WRAP_BIN_OP_MUL(v_float64x4) - #endif - #endif - - #define OPENCV_HAL_WRAP_EXTRACT(_Tpvec) \ - inline typename VTraits<_Tpvec>::lane_type v_extract_highest(const _Tpvec& v) \ - { \ - return v_extract_n::nlanes-1>(v); \ - } - - OPENCV_HAL_WRAP_EXTRACT(v_uint8) - OPENCV_HAL_WRAP_EXTRACT(v_int8) - OPENCV_HAL_WRAP_EXTRACT(v_uint16) - OPENCV_HAL_WRAP_EXTRACT(v_int16) - OPENCV_HAL_WRAP_EXTRACT(v_uint32) - OPENCV_HAL_WRAP_EXTRACT(v_int32) - OPENCV_HAL_WRAP_EXTRACT(v_uint64) - OPENCV_HAL_WRAP_EXTRACT(v_int64) - OPENCV_HAL_WRAP_EXTRACT(v_float32) - #if CV_SIMD_64F - OPENCV_HAL_WRAP_EXTRACT(v_float64) - #endif - #if CV_SIMD_WIDTH != 16/*128*/ && CV_SIMD128 - OPENCV_HAL_WRAP_EXTRACT(v_uint8x16) - OPENCV_HAL_WRAP_EXTRACT(v_uint16x8) - OPENCV_HAL_WRAP_EXTRACT(v_uint32x4) - OPENCV_HAL_WRAP_EXTRACT(v_uint64x2) - OPENCV_HAL_WRAP_EXTRACT(v_int8x16) - OPENCV_HAL_WRAP_EXTRACT(v_int16x8) - OPENCV_HAL_WRAP_EXTRACT(v_int32x4) - OPENCV_HAL_WRAP_EXTRACT(v_int64x2) - OPENCV_HAL_WRAP_EXTRACT(v_float32x4) - #if CV_SIMD_64F - OPENCV_HAL_WRAP_EXTRACT(v_float64x2) - #endif - #endif - #if CV_SIMD_WIDTH != 32/*256*/ && CV_SIMD256 - OPENCV_HAL_WRAP_EXTRACT(v_uint8x32) - OPENCV_HAL_WRAP_EXTRACT(v_uint16x16) - OPENCV_HAL_WRAP_EXTRACT(v_uint32x8) - OPENCV_HAL_WRAP_EXTRACT(v_uint64x4) - OPENCV_HAL_WRAP_EXTRACT(v_int8x32) - OPENCV_HAL_WRAP_EXTRACT(v_int16x16) - OPENCV_HAL_WRAP_EXTRACT(v_int32x8) - OPENCV_HAL_WRAP_EXTRACT(v_int64x4) - OPENCV_HAL_WRAP_EXTRACT(v_float32x8) - #if CV_SIMD_64F - OPENCV_HAL_WRAP_EXTRACT(v_float64x4) - #endif - #endif - - #define OPENCV_HAL_WRAP_BROADCAST(_Tpvec) \ - inline _Tpvec v_broadcast_highest(const _Tpvec& v) \ - { \ - return v_broadcast_element::nlanes-1>(v); \ - } - - OPENCV_HAL_WRAP_BROADCAST(v_uint32) - OPENCV_HAL_WRAP_BROADCAST(v_int32) - OPENCV_HAL_WRAP_BROADCAST(v_float32) - #if CV_SIMD_WIDTH != 16/*128*/ && CV_SIMD128 - OPENCV_HAL_WRAP_BROADCAST(v_uint32x4) - OPENCV_HAL_WRAP_BROADCAST(v_int32x4) - OPENCV_HAL_WRAP_BROADCAST(v_float32x4) - #endif - #if CV_SIMD_WIDTH != 32/*256*/ && CV_SIMD256 - OPENCV_HAL_WRAP_BROADCAST(v_uint32x8) - OPENCV_HAL_WRAP_BROADCAST(v_int32x8) - OPENCV_HAL_WRAP_BROADCAST(v_float32x8) - #endif - -#endif //!CV_SIMD_SCALABLE - -//! @cond IGNORED - - // backward compatibility - template static inline - void vx_store(_Tp* dst, const _Tvec& v) { return v_store(dst, v); } - // backward compatibility - template static inline - void vx_store_aligned(_Tp* dst, const _Tvec& v) { return v_store_aligned(dst, v); } - -//! @endcond - - -//! @} - #undef VXPREFIX -} // namespace - - -#ifndef CV_SIMD_FP16 -#define CV_SIMD_FP16 0 //!< Defined to 1 on native support of operations with float16x8_t / float16x16_t (SIMD256) types -#endif - -#ifndef CV_SIMD -#define CV_SIMD 0 -#endif - -#include "simd_utils.impl.hpp" - -#ifndef CV_DOXYGEN -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END -#endif - -} // cv:: - -//! @endcond - -#if defined(__GNUC__) && __GNUC__ == 12 -#pragma GCC diagnostic pop -#endif - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_HAL_INTRIN_HPP +#define OPENCV_HAL_INTRIN_HPP + +#include +#include +#include +#include "opencv2/core/cvdef.h" + +#if defined(__GNUC__) && __GNUC__ == 12 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wuninitialized" +#pragma GCC diagnostic ignored "-Wmaybe-uninitialized" +#endif + +#define OPENCV_HAL_ADD(a, b) ((a) + (b)) +#define OPENCV_HAL_AND(a, b) ((a) & (b)) +#define OPENCV_HAL_NOP(a) (a) +#define OPENCV_HAL_1ST(a, b) (a) + +namespace { +inline unsigned int trailingZeros32(unsigned int value) { +#if defined(_MSC_VER) +#if (_MSC_VER < 1700) || defined(_M_ARM) || defined(_M_ARM64) || defined(_M_ARM64EC) + unsigned long index = 0; + _BitScanForward(&index, value); + return (unsigned int)index; +#elif defined(__clang__) + // clang-cl doesn't export _tzcnt_u32 for non BMI systems + return value ? __builtin_ctz(value) : 32; +#else + return _tzcnt_u32(value); +#endif +#elif defined(__GNUC__) || defined(__GNUG__) + return __builtin_ctz(value); +#elif defined(__ICC) || defined(__INTEL_COMPILER) + return _bit_scan_forward(value); +#elif defined(__clang__) + return llvm.cttz.i32(value, true); +#else + static const int MultiplyDeBruijnBitPosition[32] = { + 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, + 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9 }; + return MultiplyDeBruijnBitPosition[((uint32_t)((value & -value) * 0x077CB531U)) >> 27]; +#endif +} +} + +// unlike HAL API, which is in cv::hal, +// we put intrinsics into cv namespace to make its +// access from within opencv code more accessible +namespace cv { + +namespace hal { + +enum StoreMode +{ + STORE_UNALIGNED = 0, + STORE_ALIGNED = 1, + STORE_ALIGNED_NOCACHE = 2 +}; + +} + +// TODO FIXIT: Don't use "God" traits. Split on separate cases. +template struct V_TypeTraits +{ +}; + +#define CV_INTRIN_DEF_TYPE_TRAITS(type, int_type_, uint_type_, abs_type_, w_type_, q_type_, sum_type_) \ + template<> struct V_TypeTraits \ + { \ + typedef type value_type; \ + typedef int_type_ int_type; \ + typedef abs_type_ abs_type; \ + typedef uint_type_ uint_type; \ + typedef w_type_ w_type; \ + typedef q_type_ q_type; \ + typedef sum_type_ sum_type; \ + \ + static inline int_type reinterpret_int(type x) \ + { \ + union { type l; int_type i; } v; \ + v.l = x; \ + return v.i; \ + } \ + \ + static inline type reinterpret_from_int(int_type x) \ + { \ + union { type l; int_type i; } v; \ + v.i = x; \ + return v.l; \ + } \ + } + +#define CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(type, int_type_, uint_type_, abs_type_, w_type_, sum_type_) \ + template<> struct V_TypeTraits \ + { \ + typedef type value_type; \ + typedef int_type_ int_type; \ + typedef abs_type_ abs_type; \ + typedef uint_type_ uint_type; \ + typedef w_type_ w_type; \ + typedef sum_type_ sum_type; \ + \ + static inline int_type reinterpret_int(type x) \ + { \ + union { type l; int_type i; } v; \ + v.l = x; \ + return v.i; \ + } \ + \ + static inline type reinterpret_from_int(int_type x) \ + { \ + union { type l; int_type i; } v; \ + v.i = x; \ + return v.l; \ + } \ + } + +CV_INTRIN_DEF_TYPE_TRAITS(uchar, schar, uchar, uchar, ushort, unsigned, unsigned); +CV_INTRIN_DEF_TYPE_TRAITS(schar, schar, uchar, uchar, short, int, int); +CV_INTRIN_DEF_TYPE_TRAITS(ushort, short, ushort, ushort, unsigned, uint64, unsigned); +CV_INTRIN_DEF_TYPE_TRAITS(short, short, ushort, ushort, int, int64, int); +CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(unsigned, int, unsigned, unsigned, uint64, unsigned); +CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(int, int, unsigned, unsigned, int64, int); +CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(float, int, unsigned, float, double, float); +CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(uint64, int64, uint64, uint64, void, uint64); +CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(int64, int64, uint64, uint64, void, int64); +CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(double, int64, uint64, double, void, double); + +#ifndef CV_DOXYGEN + +#ifndef CV_CPU_OPTIMIZATION_HAL_NAMESPACE +#ifdef CV_FORCE_SIMD128_CPP + #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE hal_EMULATOR_CPP + #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN namespace hal_EMULATOR_CPP { + #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END } +#elif defined(CV_CPU_DISPATCH_MODE) + #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE __CV_CAT(hal_, CV_CPU_DISPATCH_MODE) + #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN namespace __CV_CAT(hal_, CV_CPU_DISPATCH_MODE) { + #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END } +#else + #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE hal_baseline + #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN namespace hal_baseline { + #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END } +#endif +#endif // CV_CPU_OPTIMIZATION_HAL_NAMESPACE + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +template inline _VecTp v_setzero_(); +template inline _VecTp v_setall_(uchar); +template inline _VecTp v_setall_(schar); +template inline _VecTp v_setall_(ushort); +template inline _VecTp v_setall_(short); +template inline _VecTp v_setall_(unsigned); +template inline _VecTp v_setall_(int); +template inline _VecTp v_setall_(uint64); +template inline _VecTp v_setall_(int64); +template inline _VecTp v_setall_(float); +template inline _VecTp v_setall_(double); + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END +using namespace CV_CPU_OPTIMIZATION_HAL_NAMESPACE; +#endif +} + +#ifdef CV_DOXYGEN +# undef CV_AVX2 +# undef CV_SSE2 +# undef CV_NEON +# undef CV_VSX +# undef CV_FP16 +# undef CV_MSA +# undef CV_RVV +#endif + +#if (CV_SSE2 || CV_NEON || CV_VSX || CV_MSA || CV_WASM_SIMD || CV_RVV071 || CV_LSX) && !defined(CV_FORCE_SIMD128_CPP) +#define CV__SIMD_FORWARD 128 +#include "opencv2/core/hal/intrin_forward.hpp" +#endif + +#if CV_SSE2 && !defined(CV_FORCE_SIMD128_CPP) + +#include "opencv2/core/hal/intrin_sse_em.hpp" +#include "opencv2/core/hal/intrin_sse.hpp" + +#elif CV_NEON && !defined(CV_FORCE_SIMD128_CPP) + +#include "opencv2/core/hal/intrin_neon.hpp" + +#elif CV_RVV071 && !defined(CV_FORCE_SIMD128_CPP) +#define CV_SIMD128_CPP 0 +#include "opencv2/core/hal/intrin_rvv071.hpp" + +#elif CV_VSX && !defined(CV_FORCE_SIMD128_CPP) + +#include "opencv2/core/hal/intrin_vsx.hpp" + +#elif CV_MSA && !defined(CV_FORCE_SIMD128_CPP) + +#include "opencv2/core/hal/intrin_msa.hpp" + +#elif CV_WASM_SIMD && !defined(CV_FORCE_SIMD128_CPP) +#include "opencv2/core/hal/intrin_wasm.hpp" + +#elif CV_RVV && !defined(CV_FORCE_SIMD128_CPP) +#include "opencv2/core/hal/intrin_rvv_scalable.hpp" + +#elif CV_LSX && !defined(CV_FORCE_SIMD128_CPP) + +#include "opencv2/core/hal/intrin_lsx.hpp" + +#else + +#include "opencv2/core/hal/intrin_cpp.hpp" + +#endif + +// AVX2 can be used together with SSE2, so +// we define those two sets of intrinsics at once. +// Most of the intrinsics do not conflict (the proper overloaded variant is +// resolved by the argument types, e.g. v_float32x4 ~ SSE2, v_float32x8 ~ AVX2), +// but some of AVX2 intrinsics get v256_ prefix instead of v_, e.g. v256_load() vs v_load(). +// Correspondingly, the wide intrinsics (which are mapped to the "widest" +// available instruction set) will get vx_ prefix +// (and will be mapped to v256_ counterparts) (e.g. vx_load() => v256_load()) +#if CV_AVX2 + +#define CV__SIMD_FORWARD 256 +#include "opencv2/core/hal/intrin_forward.hpp" +#include "opencv2/core/hal/intrin_avx.hpp" + +#endif + +// AVX512 can be used together with SSE2 and AVX2, so +// we define those sets of intrinsics at once. +// For some of AVX512 intrinsics get v512_ prefix instead of v_, e.g. v512_load() vs v_load(). +// Wide intrinsics will be mapped to v512_ counterparts in this case(e.g. vx_load() => v512_load()) +#if CV_AVX512_SKX + +#define CV__SIMD_FORWARD 512 +#include "opencv2/core/hal/intrin_forward.hpp" +#include "opencv2/core/hal/intrin_avx512.hpp" + +#endif + +#if CV_LASX + +#define CV__SIMD_FORWARD 256 +#include "opencv2/core/hal/intrin_forward.hpp" +#include "opencv2/core/hal/intrin_lasx.hpp" + +#endif + +//! @cond IGNORED + +namespace cv { + +#ifndef CV_DOXYGEN +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN +#endif + +#ifndef CV_SIMD128 +#define CV_SIMD128 0 +#endif + +#ifndef CV_SIMD128_CPP +#define CV_SIMD128_CPP 0 +#endif + +#ifndef CV_SIMD128_64F +#define CV_SIMD128_64F 0 +#endif + +#ifndef CV_SIMD256 +#define CV_SIMD256 0 +#endif + +#ifndef CV_SIMD256_64F +#define CV_SIMD256_64F 0 +#endif + +#ifndef CV_SIMD512 +#define CV_SIMD512 0 +#endif + +#ifndef CV_SIMD512_64F +#define CV_SIMD512_64F 0 +#endif + +#ifndef CV_SIMD128_FP16 +#define CV_SIMD128_FP16 0 +#endif + +#ifndef CV_SIMD256_FP16 +#define CV_SIMD256_FP16 0 +#endif + +#ifndef CV_SIMD512_FP16 +#define CV_SIMD512_FP16 0 +#endif + +#ifndef CV_SIMD_SCALABLE +#define CV_SIMD_SCALABLE 0 +#endif + +#ifndef CV_SIMD_SCALABLE_64F +#define CV_SIMD_SCALABLE_64F 0 +#endif + +//================================================================================================== + +template struct V_RegTraits +{ +}; + +#define CV_DEF_REG_TRAITS(prefix, _reg, lane_type, suffix, _u_reg, _w_reg, _q_reg, _int_reg, _round_reg) \ + template<> struct V_RegTraits<_reg> \ + { \ + typedef _reg reg; \ + typedef _u_reg u_reg; \ + typedef _w_reg w_reg; \ + typedef _q_reg q_reg; \ + typedef _int_reg int_reg; \ + typedef _round_reg round_reg; \ + } + +#if CV_SIMD128 || CV_SIMD128_CPP + CV_DEF_REG_TRAITS(v, v_uint8x16, uchar, u8, v_uint8x16, v_uint16x8, v_uint32x4, v_int8x16, void); + CV_DEF_REG_TRAITS(v, v_int8x16, schar, s8, v_uint8x16, v_int16x8, v_int32x4, v_int8x16, void); + CV_DEF_REG_TRAITS(v, v_uint16x8, ushort, u16, v_uint16x8, v_uint32x4, v_uint64x2, v_int16x8, void); + CV_DEF_REG_TRAITS(v, v_int16x8, short, s16, v_uint16x8, v_int32x4, v_int64x2, v_int16x8, void); + CV_DEF_REG_TRAITS(v, v_uint32x4, unsigned, u32, v_uint32x4, v_uint64x2, void, v_int32x4, void); + CV_DEF_REG_TRAITS(v, v_int32x4, int, s32, v_uint32x4, v_int64x2, void, v_int32x4, void); +#if CV_SIMD128_64F || CV_SIMD128_CPP + CV_DEF_REG_TRAITS(v, v_float32x4, float, f32, v_float32x4, v_float64x2, void, v_int32x4, v_int32x4); +#else + CV_DEF_REG_TRAITS(v, v_float32x4, float, f32, v_float32x4, void, void, v_int32x4, v_int32x4); +#endif + CV_DEF_REG_TRAITS(v, v_uint64x2, uint64, u64, v_uint64x2, void, void, v_int64x2, void); + CV_DEF_REG_TRAITS(v, v_int64x2, int64, s64, v_uint64x2, void, void, v_int64x2, void); +#if CV_SIMD128_64F + CV_DEF_REG_TRAITS(v, v_float64x2, double, f64, v_float64x2, void, void, v_int64x2, v_int32x4); +#endif +#endif + +#if CV_SIMD256 + CV_DEF_REG_TRAITS(v256, v_uint8x32, uchar, u8, v_uint8x32, v_uint16x16, v_uint32x8, v_int8x32, void); + CV_DEF_REG_TRAITS(v256, v_int8x32, schar, s8, v_uint8x32, v_int16x16, v_int32x8, v_int8x32, void); + CV_DEF_REG_TRAITS(v256, v_uint16x16, ushort, u16, v_uint16x16, v_uint32x8, v_uint64x4, v_int16x16, void); + CV_DEF_REG_TRAITS(v256, v_int16x16, short, s16, v_uint16x16, v_int32x8, v_int64x4, v_int16x16, void); + CV_DEF_REG_TRAITS(v256, v_uint32x8, unsigned, u32, v_uint32x8, v_uint64x4, void, v_int32x8, void); + CV_DEF_REG_TRAITS(v256, v_int32x8, int, s32, v_uint32x8, v_int64x4, void, v_int32x8, void); + CV_DEF_REG_TRAITS(v256, v_float32x8, float, f32, v_float32x8, v_float64x4, void, v_int32x8, v_int32x8); + CV_DEF_REG_TRAITS(v256, v_uint64x4, uint64, u64, v_uint64x4, void, void, v_int64x4, void); + CV_DEF_REG_TRAITS(v256, v_int64x4, int64, s64, v_uint64x4, void, void, v_int64x4, void); + CV_DEF_REG_TRAITS(v256, v_float64x4, double, f64, v_float64x4, void, void, v_int64x4, v_int32x8); +#endif + +#if CV_SIMD512 + CV_DEF_REG_TRAITS(v512, v_uint8x64, uchar, u8, v_uint8x64, v_uint16x32, v_uint32x16, v_int8x64, void); + CV_DEF_REG_TRAITS(v512, v_int8x64, schar, s8, v_uint8x64, v_int16x32, v_int32x16, v_int8x64, void); + CV_DEF_REG_TRAITS(v512, v_uint16x32, ushort, u16, v_uint16x32, v_uint32x16, v_uint64x8, v_int16x32, void); + CV_DEF_REG_TRAITS(v512, v_int16x32, short, s16, v_uint16x32, v_int32x16, v_int64x8, v_int16x32, void); + CV_DEF_REG_TRAITS(v512, v_uint32x16, unsigned, u32, v_uint32x16, v_uint64x8, void, v_int32x16, void); + CV_DEF_REG_TRAITS(v512, v_int32x16, int, s32, v_uint32x16, v_int64x8, void, v_int32x16, void); + CV_DEF_REG_TRAITS(v512, v_float32x16, float, f32, v_float32x16, v_float64x8, void, v_int32x16, v_int32x16); + CV_DEF_REG_TRAITS(v512, v_uint64x8, uint64, u64, v_uint64x8, void, void, v_int64x8, void); + CV_DEF_REG_TRAITS(v512, v_int64x8, int64, s64, v_uint64x8, void, void, v_int64x8, void); + CV_DEF_REG_TRAITS(v512, v_float64x8, double, f64, v_float64x8, void, void, v_int64x8, v_int32x16); +#endif +#if CV_SIMD_SCALABLE + CV_DEF_REG_TRAITS(v, v_uint8, uchar, u8, v_uint8, v_uint16, v_uint32, v_int8, void); + CV_DEF_REG_TRAITS(v, v_int8, schar, s8, v_uint8, v_int16, v_int32, v_int8, void); + CV_DEF_REG_TRAITS(v, v_uint16, ushort, u16, v_uint16, v_uint32, v_uint64, v_int16, void); + CV_DEF_REG_TRAITS(v, v_int16, short, s16, v_uint16, v_int32, v_int64, v_int16, void); + CV_DEF_REG_TRAITS(v, v_uint32, unsigned, u32, v_uint32, v_uint64, void, v_int32, void); + CV_DEF_REG_TRAITS(v, v_int32, int, s32, v_uint32, v_int64, void, v_int32, void); + CV_DEF_REG_TRAITS(v, v_float32, float, f32, v_float32, v_float64, void, v_int32, v_int32); + CV_DEF_REG_TRAITS(v, v_uint64, uint64, u64, v_uint64, void, void, v_int64, void); + CV_DEF_REG_TRAITS(v, v_int64, int64, s64, v_uint64, void, void, v_int64, void); + CV_DEF_REG_TRAITS(v, v_float64, double, f64, v_float64, void, void, v_int64, v_int32); +#endif +//! @endcond + +#if CV_SIMD512 && (!defined(CV__SIMD_FORCE_WIDTH) || CV__SIMD_FORCE_WIDTH == 512) +#define CV__SIMD_NAMESPACE simd512 +namespace CV__SIMD_NAMESPACE { + #define CV_SIMD 1 + #define CV_SIMD_64F CV_SIMD512_64F + #define CV_SIMD_FP16 CV_SIMD512_FP16 + #define CV_SIMD_WIDTH 64 +//! @addtogroup core_hal_intrin +//! @{ + //! @brief Maximum available vector register capacity 8-bit unsigned integer values + typedef v_uint8x64 v_uint8; + //! @brief Maximum available vector register capacity 8-bit signed integer values + typedef v_int8x64 v_int8; + //! @brief Maximum available vector register capacity 16-bit unsigned integer values + typedef v_uint16x32 v_uint16; + //! @brief Maximum available vector register capacity 16-bit signed integer values + typedef v_int16x32 v_int16; + //! @brief Maximum available vector register capacity 32-bit unsigned integer values + typedef v_uint32x16 v_uint32; + //! @brief Maximum available vector register capacity 32-bit signed integer values + typedef v_int32x16 v_int32; + //! @brief Maximum available vector register capacity 64-bit unsigned integer values + typedef v_uint64x8 v_uint64; + //! @brief Maximum available vector register capacity 64-bit signed integer values + typedef v_int64x8 v_int64; + //! @brief Maximum available vector register capacity 32-bit floating point values (single precision) + typedef v_float32x16 v_float32; + #if CV_SIMD512_64F + //! @brief Maximum available vector register capacity 64-bit floating point values (double precision) + typedef v_float64x8 v_float64; + #endif +//! @} + + #define VXPREFIX(func) v512##func +} // namespace +using namespace CV__SIMD_NAMESPACE; +#elif CV_SIMD256 && (!defined(CV__SIMD_FORCE_WIDTH) || CV__SIMD_FORCE_WIDTH == 256) +#define CV__SIMD_NAMESPACE simd256 +namespace CV__SIMD_NAMESPACE { + #define CV_SIMD 1 + #define CV_SIMD_64F CV_SIMD256_64F + #define CV_SIMD_FP16 CV_SIMD256_FP16 + #define CV_SIMD_WIDTH 32 +//! @addtogroup core_hal_intrin +//! @{ + //! @brief Maximum available vector register capacity 8-bit unsigned integer values + typedef v_uint8x32 v_uint8; + //! @brief Maximum available vector register capacity 8-bit signed integer values + typedef v_int8x32 v_int8; + //! @brief Maximum available vector register capacity 16-bit unsigned integer values + typedef v_uint16x16 v_uint16; + //! @brief Maximum available vector register capacity 16-bit signed integer values + typedef v_int16x16 v_int16; + //! @brief Maximum available vector register capacity 32-bit unsigned integer values + typedef v_uint32x8 v_uint32; + //! @brief Maximum available vector register capacity 32-bit signed integer values + typedef v_int32x8 v_int32; + //! @brief Maximum available vector register capacity 64-bit unsigned integer values + typedef v_uint64x4 v_uint64; + //! @brief Maximum available vector register capacity 64-bit signed integer values + typedef v_int64x4 v_int64; + //! @brief Maximum available vector register capacity 32-bit floating point values (single precision) + typedef v_float32x8 v_float32; + #if CV_SIMD256_64F + //! @brief Maximum available vector register capacity 64-bit floating point values (double precision) + typedef v_float64x4 v_float64; + #endif +//! @} + + #define VXPREFIX(func) v256##func +} // namespace +using namespace CV__SIMD_NAMESPACE; +#elif (CV_SIMD128 || CV_SIMD128_CPP) && (!defined(CV__SIMD_FORCE_WIDTH) || CV__SIMD_FORCE_WIDTH == 128) +#if defined CV_SIMD128_CPP +#define CV__SIMD_NAMESPACE simd128_cpp +#else +#define CV__SIMD_NAMESPACE simd128 +#endif +namespace CV__SIMD_NAMESPACE { + #define CV_SIMD CV_SIMD128 + #define CV_SIMD_64F CV_SIMD128_64F + #define CV_SIMD_WIDTH 16 +//! @addtogroup core_hal_intrin +//! @{ + //! @brief Maximum available vector register capacity 8-bit unsigned integer values + typedef v_uint8x16 v_uint8; + //! @brief Maximum available vector register capacity 8-bit signed integer values + typedef v_int8x16 v_int8; + //! @brief Maximum available vector register capacity 16-bit unsigned integer values + typedef v_uint16x8 v_uint16; + //! @brief Maximum available vector register capacity 16-bit signed integer values + typedef v_int16x8 v_int16; + //! @brief Maximum available vector register capacity 32-bit unsigned integer values + typedef v_uint32x4 v_uint32; + //! @brief Maximum available vector register capacity 32-bit signed integer values + typedef v_int32x4 v_int32; + //! @brief Maximum available vector register capacity 64-bit unsigned integer values + typedef v_uint64x2 v_uint64; + //! @brief Maximum available vector register capacity 64-bit signed integer values + typedef v_int64x2 v_int64; + //! @brief Maximum available vector register capacity 32-bit floating point values (single precision) + typedef v_float32x4 v_float32; + #if CV_SIMD128_64F + //! @brief Maximum available vector register capacity 64-bit floating point values (double precision) + typedef v_float64x2 v_float64; + #endif +//! @} + + #define VXPREFIX(func) v##func +} // namespace +using namespace CV__SIMD_NAMESPACE; + +#elif CV_SIMD_SCALABLE +#define CV__SIMD_NAMESPACE simd +namespace CV__SIMD_NAMESPACE { + #define CV_SIMD 0 + #define CV_SIMD_WIDTH 128 /* 1024/8 */ + + #define VXPREFIX(func) v##func +} // namespace +using namespace CV__SIMD_NAMESPACE; + +#endif + +//! @cond IGNORED +#ifndef CV_SIMD_64F +#define CV_SIMD_64F 0 +#endif + +namespace CV__SIMD_NAMESPACE { +//! @addtogroup core_hal_intrin +//! @{ + //! @name Wide init with value + //! @{ + //! @brief Create maximum available capacity vector with elements set to a specific value + inline v_uint8 vx_setall_u8(uchar v) { return VXPREFIX(_setall_u8)(v); } + inline v_int8 vx_setall_s8(schar v) { return VXPREFIX(_setall_s8)(v); } + inline v_uint16 vx_setall_u16(ushort v) { return VXPREFIX(_setall_u16)(v); } + inline v_int16 vx_setall_s16(short v) { return VXPREFIX(_setall_s16)(v); } + inline v_int32 vx_setall_s32(int v) { return VXPREFIX(_setall_s32)(v); } + inline v_uint32 vx_setall_u32(unsigned v) { return VXPREFIX(_setall_u32)(v); } + inline v_float32 vx_setall_f32(float v) { return VXPREFIX(_setall_f32)(v); } + inline v_int64 vx_setall_s64(int64 v) { return VXPREFIX(_setall_s64)(v); } + inline v_uint64 vx_setall_u64(uint64 v) { return VXPREFIX(_setall_u64)(v); } +#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F + inline v_float64 vx_setall_f64(double v) { return VXPREFIX(_setall_f64)(v); } +#endif + //! @} + + //! @name Wide init with zero + //! @{ + //! @brief Create maximum available capacity vector with elements set to zero + inline v_uint8 vx_setzero_u8() { return VXPREFIX(_setzero_u8)(); } + inline v_int8 vx_setzero_s8() { return VXPREFIX(_setzero_s8)(); } + inline v_uint16 vx_setzero_u16() { return VXPREFIX(_setzero_u16)(); } + inline v_int16 vx_setzero_s16() { return VXPREFIX(_setzero_s16)(); } + inline v_int32 vx_setzero_s32() { return VXPREFIX(_setzero_s32)(); } + inline v_uint32 vx_setzero_u32() { return VXPREFIX(_setzero_u32)(); } + inline v_float32 vx_setzero_f32() { return VXPREFIX(_setzero_f32)(); } + inline v_int64 vx_setzero_s64() { return VXPREFIX(_setzero_s64)(); } + inline v_uint64 vx_setzero_u64() { return VXPREFIX(_setzero_u64)(); } +#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F + inline v_float64 vx_setzero_f64() { return VXPREFIX(_setzero_f64)(); } +#endif + //! @} + + //! @name Wide load from memory + //! @{ + //! @brief Load maximum available capacity register contents from memory + inline v_uint8 vx_load(const uchar * ptr) { return VXPREFIX(_load)(ptr); } + inline v_int8 vx_load(const schar * ptr) { return VXPREFIX(_load)(ptr); } + inline v_uint16 vx_load(const ushort * ptr) { return VXPREFIX(_load)(ptr); } + inline v_int16 vx_load(const short * ptr) { return VXPREFIX(_load)(ptr); } + inline v_int32 vx_load(const int * ptr) { return VXPREFIX(_load)(ptr); } + inline v_uint32 vx_load(const unsigned * ptr) { return VXPREFIX(_load)(ptr); } + inline v_float32 vx_load(const float * ptr) { return VXPREFIX(_load)(ptr); } + inline v_int64 vx_load(const int64 * ptr) { return VXPREFIX(_load)(ptr); } + inline v_uint64 vx_load(const uint64 * ptr) { return VXPREFIX(_load)(ptr); } +#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F + inline v_float64 vx_load(const double * ptr) { return VXPREFIX(_load)(ptr); } +#endif + //! @} + + //! @name Wide load from memory(aligned) + //! @{ + //! @brief Load maximum available capacity register contents from memory(aligned) + inline v_uint8 vx_load_aligned(const uchar * ptr) { return VXPREFIX(_load_aligned)(ptr); } + inline v_int8 vx_load_aligned(const schar * ptr) { return VXPREFIX(_load_aligned)(ptr); } + inline v_uint16 vx_load_aligned(const ushort * ptr) { return VXPREFIX(_load_aligned)(ptr); } + inline v_int16 vx_load_aligned(const short * ptr) { return VXPREFIX(_load_aligned)(ptr); } + inline v_int32 vx_load_aligned(const int * ptr) { return VXPREFIX(_load_aligned)(ptr); } + inline v_uint32 vx_load_aligned(const unsigned * ptr) { return VXPREFIX(_load_aligned)(ptr); } + inline v_float32 vx_load_aligned(const float * ptr) { return VXPREFIX(_load_aligned)(ptr); } + inline v_int64 vx_load_aligned(const int64 * ptr) { return VXPREFIX(_load_aligned)(ptr); } + inline v_uint64 vx_load_aligned(const uint64 * ptr) { return VXPREFIX(_load_aligned)(ptr); } +#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F + inline v_float64 vx_load_aligned(const double * ptr) { return VXPREFIX(_load_aligned)(ptr); } +#endif + //! @} + + //! @name Wide load lower half from memory + //! @{ + //! @brief Load lower half of maximum available capacity register from memory + inline v_uint8 vx_load_low(const uchar * ptr) { return VXPREFIX(_load_low)(ptr); } + inline v_int8 vx_load_low(const schar * ptr) { return VXPREFIX(_load_low)(ptr); } + inline v_uint16 vx_load_low(const ushort * ptr) { return VXPREFIX(_load_low)(ptr); } + inline v_int16 vx_load_low(const short * ptr) { return VXPREFIX(_load_low)(ptr); } + inline v_int32 vx_load_low(const int * ptr) { return VXPREFIX(_load_low)(ptr); } + inline v_uint32 vx_load_low(const unsigned * ptr) { return VXPREFIX(_load_low)(ptr); } + inline v_float32 vx_load_low(const float * ptr) { return VXPREFIX(_load_low)(ptr); } + inline v_int64 vx_load_low(const int64 * ptr) { return VXPREFIX(_load_low)(ptr); } + inline v_uint64 vx_load_low(const uint64 * ptr) { return VXPREFIX(_load_low)(ptr); } +#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F + inline v_float64 vx_load_low(const double * ptr) { return VXPREFIX(_load_low)(ptr); } +#endif + //! @} + + //! @name Wide load halfs from memory + //! @{ + //! @brief Load maximum available capacity register contents from two memory blocks + inline v_uint8 vx_load_halves(const uchar * ptr0, const uchar * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } + inline v_int8 vx_load_halves(const schar * ptr0, const schar * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } + inline v_uint16 vx_load_halves(const ushort * ptr0, const ushort * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } + inline v_int16 vx_load_halves(const short * ptr0, const short * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } + inline v_int32 vx_load_halves(const int * ptr0, const int * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } + inline v_uint32 vx_load_halves(const unsigned * ptr0, const unsigned * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } + inline v_float32 vx_load_halves(const float * ptr0, const float * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } + inline v_int64 vx_load_halves(const int64 * ptr0, const int64 * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } + inline v_uint64 vx_load_halves(const uint64 * ptr0, const uint64 * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } +#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F + inline v_float64 vx_load_halves(const double * ptr0, const double * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } +#endif + //! @} + + //! @name Wide LUT of elements + //! @{ + //! @brief Load maximum available capacity register contents with array elements by provided indexes + inline v_uint8 vx_lut(const uchar * ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } + inline v_int8 vx_lut(const schar * ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } + inline v_uint16 vx_lut(const ushort * ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } + inline v_int16 vx_lut(const short* ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } + inline v_int32 vx_lut(const int* ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } + inline v_uint32 vx_lut(const unsigned* ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } + inline v_float32 vx_lut(const float* ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } + inline v_int64 vx_lut(const int64 * ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } + inline v_uint64 vx_lut(const uint64 * ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } +#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F + inline v_float64 vx_lut(const double* ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } +#endif + //! @} + + //! @name Wide LUT of element pairs + //! @{ + //! @brief Load maximum available capacity register contents with array element pairs by provided indexes + inline v_uint8 vx_lut_pairs(const uchar * ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } + inline v_int8 vx_lut_pairs(const schar * ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } + inline v_uint16 vx_lut_pairs(const ushort * ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } + inline v_int16 vx_lut_pairs(const short* ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } + inline v_int32 vx_lut_pairs(const int* ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } + inline v_uint32 vx_lut_pairs(const unsigned* ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } + inline v_float32 vx_lut_pairs(const float* ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } + inline v_int64 vx_lut_pairs(const int64 * ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } + inline v_uint64 vx_lut_pairs(const uint64 * ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } +#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F + inline v_float64 vx_lut_pairs(const double* ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } +#endif + //! @} + + //! @name Wide LUT of element quads + //! @{ + //! @brief Load maximum available capacity register contents with array element quads by provided indexes + inline v_uint8 vx_lut_quads(const uchar* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } + inline v_int8 vx_lut_quads(const schar* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } + inline v_uint16 vx_lut_quads(const ushort* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } + inline v_int16 vx_lut_quads(const short* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } + inline v_int32 vx_lut_quads(const int* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } + inline v_uint32 vx_lut_quads(const unsigned* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } + inline v_float32 vx_lut_quads(const float* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } + //! @} + + //! @name Wide load with double expansion + //! @{ + //! @brief Load maximum available capacity register contents from memory with double expand + inline v_uint16 vx_load_expand(const uchar * ptr) { return VXPREFIX(_load_expand)(ptr); } + inline v_int16 vx_load_expand(const schar * ptr) { return VXPREFIX(_load_expand)(ptr); } + inline v_uint32 vx_load_expand(const ushort * ptr) { return VXPREFIX(_load_expand)(ptr); } + inline v_int32 vx_load_expand(const short* ptr) { return VXPREFIX(_load_expand)(ptr); } + inline v_int64 vx_load_expand(const int* ptr) { return VXPREFIX(_load_expand)(ptr); } + inline v_uint64 vx_load_expand(const unsigned* ptr) { return VXPREFIX(_load_expand)(ptr); } + inline v_float32 vx_load_expand(const hfloat * ptr) { return VXPREFIX(_load_expand)(ptr); } + //! @} + + //! @name Wide load with quad expansion + //! @{ + //! @brief Load maximum available capacity register contents from memory with quad expand + inline v_uint32 vx_load_expand_q(const uchar * ptr) { return VXPREFIX(_load_expand_q)(ptr); } + inline v_int32 vx_load_expand_q(const schar * ptr) { return VXPREFIX(_load_expand_q)(ptr); } + //! @} + + /** @brief SIMD processing state cleanup call */ + inline void vx_cleanup() { VXPREFIX(_cleanup)(); } + +#if !CV_SIMD_SCALABLE + // Compatibility layer +#if !(CV_NEON && !defined(CV_FORCE_SIMD128_CPP)) + template struct VTraits { + static inline int vlanes() { return T::nlanes; } + enum { nlanes = T::nlanes, max_nlanes = T::nlanes }; + using lane_type = typename T::lane_type; + }; + + //////////// get0 //////////// + #define OPENCV_HAL_WRAP_GRT0(_Tpvec) \ + inline typename VTraits<_Tpvec>::lane_type v_get0(const _Tpvec& v) \ + { \ + return v.get0(); \ + } + + OPENCV_HAL_WRAP_GRT0(v_uint8) + OPENCV_HAL_WRAP_GRT0(v_int8) + OPENCV_HAL_WRAP_GRT0(v_uint16) + OPENCV_HAL_WRAP_GRT0(v_int16) + OPENCV_HAL_WRAP_GRT0(v_uint32) + OPENCV_HAL_WRAP_GRT0(v_int32) + OPENCV_HAL_WRAP_GRT0(v_uint64) + OPENCV_HAL_WRAP_GRT0(v_int64) + OPENCV_HAL_WRAP_GRT0(v_float32) + #if CV_SIMD_64F + OPENCV_HAL_WRAP_GRT0(v_float64) + #endif + #if CV_SIMD_WIDTH != 16/*128*/ && CV_SIMD128 + OPENCV_HAL_WRAP_GRT0(v_uint8x16) + OPENCV_HAL_WRAP_GRT0(v_uint16x8) + OPENCV_HAL_WRAP_GRT0(v_uint32x4) + OPENCV_HAL_WRAP_GRT0(v_uint64x2) + OPENCV_HAL_WRAP_GRT0(v_int8x16) + OPENCV_HAL_WRAP_GRT0(v_int16x8) + OPENCV_HAL_WRAP_GRT0(v_int32x4) + OPENCV_HAL_WRAP_GRT0(v_int64x2) + OPENCV_HAL_WRAP_GRT0(v_float32x4) + #if CV_SIMD_64F + OPENCV_HAL_WRAP_GRT0(v_float64x2) + #endif + #endif + #if CV_SIMD_WIDTH != 32/*256*/ && CV_SIMD256 + OPENCV_HAL_WRAP_GRT0(v_uint8x32) + OPENCV_HAL_WRAP_GRT0(v_uint16x16) + OPENCV_HAL_WRAP_GRT0(v_uint32x8) + OPENCV_HAL_WRAP_GRT0(v_uint64x4) + OPENCV_HAL_WRAP_GRT0(v_int8x32) + OPENCV_HAL_WRAP_GRT0(v_int16x16) + OPENCV_HAL_WRAP_GRT0(v_int32x8) + OPENCV_HAL_WRAP_GRT0(v_int64x4) + OPENCV_HAL_WRAP_GRT0(v_float32x8) + #if CV_SIMD_64F + OPENCV_HAL_WRAP_GRT0(v_float64x4) + #endif + #endif +#endif + + #define OPENCV_HAL_WRAP_BIN_OP_ADDSUB(_Tpvec) \ + template \ + inline _Tpvec v_add(const _Tpvec& f1, const _Tpvec& f2, const _Tpvec& f3, const Args&... vf) { \ + return v_add(v_add(f1, f2), f3, vf...); \ + } + + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint8) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint16) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint32) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint64) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int8) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int16) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int32) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int64) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_float32) + #if CV_SIMD_64F + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_float64) + #endif + #if CV_SIMD_WIDTH != 16/*128*/ && CV_SIMD128 + // when we use CV_SIMD128 with 256/512 bit SIMD (e.g. AVX2 or AVX512) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint8x16) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint16x8) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint32x4) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint64x2) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int8x16) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int16x8) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int32x4) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int64x2) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_float32x4) + #if CV_SIMD_64F + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_float64x2) + #endif + #endif + #if CV_SIMD_WIDTH != 32/*256*/ && CV_SIMD256 + // when we use CV_SIMD256 with 512 bit SIMD (e.g. AVX512) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint8x32) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint16x16) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint32x8) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint64x4) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int8x32) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int16x16) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int32x8) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int64x4) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_float32x8) + #if CV_SIMD_64F + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_float64x4) + #endif + #endif + + #define OPENCV_HAL_WRAP_BIN_OP_MUL(_Tpvec) \ + template \ + inline _Tpvec v_mul(const _Tpvec& f1, const _Tpvec& f2, const _Tpvec& f3, const Args&... vf) { \ + return v_mul(v_mul(f1, f2), f3, vf...); \ + } + OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint8) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_int8) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint16) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint32) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_int16) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_int32) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_float32) + #if CV_SIMD_64F + OPENCV_HAL_WRAP_BIN_OP_MUL(v_float64) + #endif + #if CV_SIMD_WIDTH != 16/*128*/ && CV_SIMD128 + OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint8x16) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint16x8) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint32x4) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_int8x16) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_int16x8) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_int32x4) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_float32x4) + #if CV_SIMD_64F + OPENCV_HAL_WRAP_BIN_OP_MUL(v_float64x2) + #endif + #endif + #if CV_SIMD_WIDTH != 32/*256*/ && CV_SIMD256 + OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint8x32) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint16x16) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint32x8) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_int8x32) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_int16x16) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_int32x8) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_float32x8) + #if CV_SIMD_64F + OPENCV_HAL_WRAP_BIN_OP_MUL(v_float64x4) + #endif + #endif + + #define OPENCV_HAL_WRAP_EXTRACT(_Tpvec) \ + inline typename VTraits<_Tpvec>::lane_type v_extract_highest(const _Tpvec& v) \ + { \ + return v_extract_n::nlanes-1>(v); \ + } + + OPENCV_HAL_WRAP_EXTRACT(v_uint8) + OPENCV_HAL_WRAP_EXTRACT(v_int8) + OPENCV_HAL_WRAP_EXTRACT(v_uint16) + OPENCV_HAL_WRAP_EXTRACT(v_int16) + OPENCV_HAL_WRAP_EXTRACT(v_uint32) + OPENCV_HAL_WRAP_EXTRACT(v_int32) + OPENCV_HAL_WRAP_EXTRACT(v_uint64) + OPENCV_HAL_WRAP_EXTRACT(v_int64) + OPENCV_HAL_WRAP_EXTRACT(v_float32) + #if CV_SIMD_64F + OPENCV_HAL_WRAP_EXTRACT(v_float64) + #endif + #if CV_SIMD_WIDTH != 16/*128*/ && CV_SIMD128 + OPENCV_HAL_WRAP_EXTRACT(v_uint8x16) + OPENCV_HAL_WRAP_EXTRACT(v_uint16x8) + OPENCV_HAL_WRAP_EXTRACT(v_uint32x4) + OPENCV_HAL_WRAP_EXTRACT(v_uint64x2) + OPENCV_HAL_WRAP_EXTRACT(v_int8x16) + OPENCV_HAL_WRAP_EXTRACT(v_int16x8) + OPENCV_HAL_WRAP_EXTRACT(v_int32x4) + OPENCV_HAL_WRAP_EXTRACT(v_int64x2) + OPENCV_HAL_WRAP_EXTRACT(v_float32x4) + #if CV_SIMD_64F + OPENCV_HAL_WRAP_EXTRACT(v_float64x2) + #endif + #endif + #if CV_SIMD_WIDTH != 32/*256*/ && CV_SIMD256 + OPENCV_HAL_WRAP_EXTRACT(v_uint8x32) + OPENCV_HAL_WRAP_EXTRACT(v_uint16x16) + OPENCV_HAL_WRAP_EXTRACT(v_uint32x8) + OPENCV_HAL_WRAP_EXTRACT(v_uint64x4) + OPENCV_HAL_WRAP_EXTRACT(v_int8x32) + OPENCV_HAL_WRAP_EXTRACT(v_int16x16) + OPENCV_HAL_WRAP_EXTRACT(v_int32x8) + OPENCV_HAL_WRAP_EXTRACT(v_int64x4) + OPENCV_HAL_WRAP_EXTRACT(v_float32x8) + #if CV_SIMD_64F + OPENCV_HAL_WRAP_EXTRACT(v_float64x4) + #endif + #endif + + #define OPENCV_HAL_WRAP_BROADCAST(_Tpvec) \ + inline _Tpvec v_broadcast_highest(const _Tpvec& v) \ + { \ + return v_broadcast_element::nlanes-1>(v); \ + } + + OPENCV_HAL_WRAP_BROADCAST(v_uint32) + OPENCV_HAL_WRAP_BROADCAST(v_int32) + OPENCV_HAL_WRAP_BROADCAST(v_float32) + #if CV_SIMD_WIDTH != 16/*128*/ && CV_SIMD128 + OPENCV_HAL_WRAP_BROADCAST(v_uint32x4) + OPENCV_HAL_WRAP_BROADCAST(v_int32x4) + OPENCV_HAL_WRAP_BROADCAST(v_float32x4) + #endif + #if CV_SIMD_WIDTH != 32/*256*/ && CV_SIMD256 + OPENCV_HAL_WRAP_BROADCAST(v_uint32x8) + OPENCV_HAL_WRAP_BROADCAST(v_int32x8) + OPENCV_HAL_WRAP_BROADCAST(v_float32x8) + #endif + +#endif //!CV_SIMD_SCALABLE + +//! @cond IGNORED + + // backward compatibility + template static inline + void vx_store(_Tp* dst, const _Tvec& v) { return v_store(dst, v); } + // backward compatibility + template static inline + void vx_store_aligned(_Tp* dst, const _Tvec& v) { return v_store_aligned(dst, v); } + +//! @endcond + + +//! @} + #undef VXPREFIX +} // namespace + + +#ifndef CV_SIMD_FP16 +#define CV_SIMD_FP16 0 //!< Defined to 1 on native support of operations with float16x8_t / float16x16_t (SIMD256) types +#endif + +#ifndef CV_SIMD +#define CV_SIMD 0 +#endif + +#include "simd_utils.impl.hpp" + +#ifndef CV_DOXYGEN +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END +#endif + +} // cv:: + +//! @endcond + +#if defined(__GNUC__) && __GNUC__ == 12 +#pragma GCC diagnostic pop +#endif + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_avx.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_avx.hpp index c7ce1e3d33..f9a58ccd77 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_avx.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_avx.hpp @@ -1,3189 +1,3189 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -#ifndef OPENCV_HAL_INTRIN_AVX_HPP -#define OPENCV_HAL_INTRIN_AVX_HPP - -#define CV_SIMD256 1 -#define CV_SIMD256_64F 1 -#define CV_SIMD256_FP16 0 // no native operations with FP16 type. Only load/store from float32x8 are available (if CV_FP16 == 1) - -namespace cv -{ - -//! @cond IGNORED - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -///////// Utils //////////// - -inline __m256i _v256_combine(const __m128i& lo, const __m128i& hi) -{ return _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1); } - -inline __m256 _v256_combine(const __m128& lo, const __m128& hi) -{ return _mm256_insertf128_ps(_mm256_castps128_ps256(lo), hi, 1); } - -inline __m256d _v256_combine(const __m128d& lo, const __m128d& hi) -{ return _mm256_insertf128_pd(_mm256_castpd128_pd256(lo), hi, 1); } - -inline int _v_cvtsi256_si32(const __m256i& a) -{ return _mm_cvtsi128_si32(_mm256_castsi256_si128(a)); } - -inline __m256i _v256_shuffle_odd_64(const __m256i& v) -{ return _mm256_permute4x64_epi64(v, _MM_SHUFFLE(3, 1, 2, 0)); } - -inline __m256d _v256_shuffle_odd_64(const __m256d& v) -{ return _mm256_permute4x64_pd(v, _MM_SHUFFLE(3, 1, 2, 0)); } - -template -inline __m256i _v256_permute2x128(const __m256i& a, const __m256i& b) -{ return _mm256_permute2x128_si256(a, b, imm); } - -template -inline __m256 _v256_permute2x128(const __m256& a, const __m256& b) -{ return _mm256_permute2f128_ps(a, b, imm); } - -template -inline __m256d _v256_permute2x128(const __m256d& a, const __m256d& b) -{ return _mm256_permute2f128_pd(a, b, imm); } - -template -inline _Tpvec v256_permute2x128(const _Tpvec& a, const _Tpvec& b) -{ return _Tpvec(_v256_permute2x128(a.val, b.val)); } - -template -inline __m256i _v256_permute4x64(const __m256i& a) -{ return _mm256_permute4x64_epi64(a, imm); } - -template -inline __m256d _v256_permute4x64(const __m256d& a) -{ return _mm256_permute4x64_pd(a, imm); } - -template -inline _Tpvec v256_permute4x64(const _Tpvec& a) -{ return _Tpvec(_v256_permute4x64(a.val)); } - -inline __m128i _v256_extract_high(const __m256i& v) -{ return _mm256_extracti128_si256(v, 1); } - -inline __m128 _v256_extract_high(const __m256& v) -{ return _mm256_extractf128_ps(v, 1); } - -inline __m128d _v256_extract_high(const __m256d& v) -{ return _mm256_extractf128_pd(v, 1); } - -inline __m128i _v256_extract_low(const __m256i& v) -{ return _mm256_castsi256_si128(v); } - -inline __m128 _v256_extract_low(const __m256& v) -{ return _mm256_castps256_ps128(v); } - -inline __m128d _v256_extract_low(const __m256d& v) -{ return _mm256_castpd256_pd128(v); } - -inline __m256i _v256_packs_epu32(const __m256i& a, const __m256i& b) -{ - const __m256i m = _mm256_set1_epi32(65535); - __m256i am = _mm256_min_epu32(a, m); - __m256i bm = _mm256_min_epu32(b, m); - return _mm256_packus_epi32(am, bm); -} - -template -inline int _v256_extract_epi8(const __m256i& a) -{ -#if defined(CV__SIMD_HAVE_mm256_extract_epi8) || (CV_AVX2 && (!defined(_MSC_VER) || _MSC_VER >= 1910/*MSVS 2017*/)) - return _mm256_extract_epi8(a, i); -#else - __m128i b = _mm256_extractf128_si256(a, ((i) >> 4)); - return _mm_extract_epi8(b, i & 15); // SSE4.1 -#endif -} - -template -inline int _v256_extract_epi16(const __m256i& a) -{ -#if defined(CV__SIMD_HAVE_mm256_extract_epi8) || (CV_AVX2 && (!defined(_MSC_VER) || _MSC_VER >= 1910/*MSVS 2017*/)) - return _mm256_extract_epi16(a, i); -#else - __m128i b = _mm256_extractf128_si256(a, ((i) >> 3)); - return _mm_extract_epi16(b, i & 7); // SSE2 -#endif -} - -template -inline int _v256_extract_epi32(const __m256i& a) -{ -#if defined(CV__SIMD_HAVE_mm256_extract_epi8) || (CV_AVX2 && (!defined(_MSC_VER) || _MSC_VER >= 1910/*MSVS 2017*/)) - return _mm256_extract_epi32(a, i); -#else - __m128i b = _mm256_extractf128_si256(a, ((i) >> 2)); - return _mm_extract_epi32(b, i & 3); // SSE4.1 -#endif -} - -template -inline int64 _v256_extract_epi64(const __m256i& a) -{ -#if defined(CV__SIMD_HAVE_mm256_extract_epi8) || (CV_AVX2 && (!defined(_MSC_VER) || _MSC_VER >= 1910/*MSVS 2017*/)) - return _mm256_extract_epi64(a, i); -#else - __m128i b = _mm256_extractf128_si256(a, ((i) >> 1)); - return _mm_extract_epi64(b, i & 1); // SSE4.1 -#endif -} - -///////// Types //////////// - -struct v_uint8x32 -{ - typedef uchar lane_type; - enum { nlanes = 32 }; - __m256i val; - - explicit v_uint8x32(__m256i v) : val(v) {} - v_uint8x32(uchar v0, uchar v1, uchar v2, uchar v3, - uchar v4, uchar v5, uchar v6, uchar v7, - uchar v8, uchar v9, uchar v10, uchar v11, - uchar v12, uchar v13, uchar v14, uchar v15, - uchar v16, uchar v17, uchar v18, uchar v19, - uchar v20, uchar v21, uchar v22, uchar v23, - uchar v24, uchar v25, uchar v26, uchar v27, - uchar v28, uchar v29, uchar v30, uchar v31) - { - val = _mm256_setr_epi8((char)v0, (char)v1, (char)v2, (char)v3, - (char)v4, (char)v5, (char)v6 , (char)v7, (char)v8, (char)v9, - (char)v10, (char)v11, (char)v12, (char)v13, (char)v14, (char)v15, - (char)v16, (char)v17, (char)v18, (char)v19, (char)v20, (char)v21, - (char)v22, (char)v23, (char)v24, (char)v25, (char)v26, (char)v27, - (char)v28, (char)v29, (char)v30, (char)v31); - } - /* coverity[uninit_ctor]: suppress warning */ - v_uint8x32() {} - - uchar get0() const { return (uchar)_v_cvtsi256_si32(val); } -}; - -struct v_int8x32 -{ - typedef schar lane_type; - enum { nlanes = 32 }; - __m256i val; - - explicit v_int8x32(__m256i v) : val(v) {} - v_int8x32(schar v0, schar v1, schar v2, schar v3, - schar v4, schar v5, schar v6, schar v7, - schar v8, schar v9, schar v10, schar v11, - schar v12, schar v13, schar v14, schar v15, - schar v16, schar v17, schar v18, schar v19, - schar v20, schar v21, schar v22, schar v23, - schar v24, schar v25, schar v26, schar v27, - schar v28, schar v29, schar v30, schar v31) - { - val = _mm256_setr_epi8(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, - v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, - v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31); - } - /* coverity[uninit_ctor]: suppress warning */ - v_int8x32() {} - - schar get0() const { return (schar)_v_cvtsi256_si32(val); } -}; - -struct v_uint16x16 -{ - typedef ushort lane_type; - enum { nlanes = 16 }; - __m256i val; - - explicit v_uint16x16(__m256i v) : val(v) {} - v_uint16x16(ushort v0, ushort v1, ushort v2, ushort v3, - ushort v4, ushort v5, ushort v6, ushort v7, - ushort v8, ushort v9, ushort v10, ushort v11, - ushort v12, ushort v13, ushort v14, ushort v15) - { - val = _mm256_setr_epi16((short)v0, (short)v1, (short)v2, (short)v3, - (short)v4, (short)v5, (short)v6, (short)v7, (short)v8, (short)v9, - (short)v10, (short)v11, (short)v12, (short)v13, (short)v14, (short)v15); - } - /* coverity[uninit_ctor]: suppress warning */ - v_uint16x16() {} - - ushort get0() const { return (ushort)_v_cvtsi256_si32(val); } -}; - -struct v_int16x16 -{ - typedef short lane_type; - enum { nlanes = 16 }; - __m256i val; - - explicit v_int16x16(__m256i v) : val(v) {} - v_int16x16(short v0, short v1, short v2, short v3, - short v4, short v5, short v6, short v7, - short v8, short v9, short v10, short v11, - short v12, short v13, short v14, short v15) - { - val = _mm256_setr_epi16(v0, v1, v2, v3, v4, v5, v6, v7, - v8, v9, v10, v11, v12, v13, v14, v15); - } - /* coverity[uninit_ctor]: suppress warning */ - v_int16x16() {} - - short get0() const { return (short)_v_cvtsi256_si32(val); } -}; - -struct v_uint32x8 -{ - typedef unsigned lane_type; - enum { nlanes = 8 }; - __m256i val; - - explicit v_uint32x8(__m256i v) : val(v) {} - v_uint32x8(unsigned v0, unsigned v1, unsigned v2, unsigned v3, - unsigned v4, unsigned v5, unsigned v6, unsigned v7) - { - val = _mm256_setr_epi32((unsigned)v0, (unsigned)v1, (unsigned)v2, - (unsigned)v3, (unsigned)v4, (unsigned)v5, (unsigned)v6, (unsigned)v7); - } - /* coverity[uninit_ctor]: suppress warning */ - v_uint32x8() {} - - unsigned get0() const { return (unsigned)_v_cvtsi256_si32(val); } -}; - -struct v_int32x8 -{ - typedef int lane_type; - enum { nlanes = 8 }; - __m256i val; - - explicit v_int32x8(__m256i v) : val(v) {} - v_int32x8(int v0, int v1, int v2, int v3, - int v4, int v5, int v6, int v7) - { - val = _mm256_setr_epi32(v0, v1, v2, v3, v4, v5, v6, v7); - } - /* coverity[uninit_ctor]: suppress warning */ - v_int32x8() {} - - int get0() const { return _v_cvtsi256_si32(val); } -}; - -struct v_float32x8 -{ - typedef float lane_type; - enum { nlanes = 8 }; - __m256 val; - - explicit v_float32x8(__m256 v) : val(v) {} - v_float32x8(float v0, float v1, float v2, float v3, - float v4, float v5, float v6, float v7) - { - val = _mm256_setr_ps(v0, v1, v2, v3, v4, v5, v6, v7); - } - /* coverity[uninit_ctor]: suppress warning */ - v_float32x8() {} - - float get0() const { return _mm_cvtss_f32(_mm256_castps256_ps128(val)); } -}; - -struct v_uint64x4 -{ - typedef uint64 lane_type; - enum { nlanes = 4 }; - __m256i val; - - explicit v_uint64x4(__m256i v) : val(v) {} - v_uint64x4(uint64 v0, uint64 v1, uint64 v2, uint64 v3) - { val = _mm256_setr_epi64x((int64)v0, (int64)v1, (int64)v2, (int64)v3); } - /* coverity[uninit_ctor]: suppress warning */ - v_uint64x4() {} - - uint64 get0() const - { - #if defined __x86_64__ || defined _M_X64 - return (uint64)_mm_cvtsi128_si64(_mm256_castsi256_si128(val)); - #else - int a = _mm_cvtsi128_si32(_mm256_castsi256_si128(val)); - int b = _mm_cvtsi128_si32(_mm256_castsi256_si128(_mm256_srli_epi64(val, 32))); - return (unsigned)a | ((uint64)(unsigned)b << 32); - #endif - } -}; - -struct v_int64x4 -{ - typedef int64 lane_type; - enum { nlanes = 4 }; - __m256i val; - - explicit v_int64x4(__m256i v) : val(v) {} - v_int64x4(int64 v0, int64 v1, int64 v2, int64 v3) - { val = _mm256_setr_epi64x(v0, v1, v2, v3); } - /* coverity[uninit_ctor]: suppress warning */ - v_int64x4() {} - - int64 get0() const - { - #if defined __x86_64__ || defined _M_X64 - return (int64)_mm_cvtsi128_si64(_mm256_castsi256_si128(val)); - #else - int a = _mm_cvtsi128_si32(_mm256_castsi256_si128(val)); - int b = _mm_cvtsi128_si32(_mm256_castsi256_si128(_mm256_srli_epi64(val, 32))); - return (int64)((unsigned)a | ((uint64)(unsigned)b << 32)); - #endif - } -}; - -struct v_float64x4 -{ - typedef double lane_type; - enum { nlanes = 4 }; - __m256d val; - - explicit v_float64x4(__m256d v) : val(v) {} - v_float64x4(double v0, double v1, double v2, double v3) - { val = _mm256_setr_pd(v0, v1, v2, v3); } - /* coverity[uninit_ctor]: suppress warning */ - v_float64x4() {} - - double get0() const { return _mm_cvtsd_f64(_mm256_castpd256_pd128(val)); } -}; - -//////////////// Load and store operations /////////////// - -#define OPENCV_HAL_IMPL_AVX_LOADSTORE(_Tpvec, _Tp) \ - inline _Tpvec v256_load(const _Tp* ptr) \ - { return _Tpvec(_mm256_loadu_si256((const __m256i*)ptr)); } \ - inline _Tpvec v256_load_aligned(const _Tp* ptr) \ - { return _Tpvec(_mm256_load_si256((const __m256i*)ptr)); } \ - inline _Tpvec v256_load_low(const _Tp* ptr) \ - { \ - __m128i v128 = _mm_loadu_si128((const __m128i*)ptr); \ - return _Tpvec(_mm256_castsi128_si256(v128)); \ - } \ - inline _Tpvec v256_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ - { \ - __m128i vlo = _mm_loadu_si128((const __m128i*)ptr0); \ - __m128i vhi = _mm_loadu_si128((const __m128i*)ptr1); \ - return _Tpvec(_v256_combine(vlo, vhi)); \ - } \ - inline void v_store(_Tp* ptr, const _Tpvec& a) \ - { _mm256_storeu_si256((__m256i*)ptr, a.val); } \ - inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ - { _mm256_store_si256((__m256i*)ptr, a.val); } \ - inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ - { _mm256_stream_si256((__m256i*)ptr, a.val); } \ - inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ - { \ - if( mode == hal::STORE_UNALIGNED ) \ - _mm256_storeu_si256((__m256i*)ptr, a.val); \ - else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ - _mm256_stream_si256((__m256i*)ptr, a.val); \ - else \ - _mm256_store_si256((__m256i*)ptr, a.val); \ - } \ - inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ - { _mm_storeu_si128((__m128i*)ptr, _v256_extract_low(a.val)); } \ - inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ - { _mm_storeu_si128((__m128i*)ptr, _v256_extract_high(a.val)); } - -OPENCV_HAL_IMPL_AVX_LOADSTORE(v_uint8x32, uchar) -OPENCV_HAL_IMPL_AVX_LOADSTORE(v_int8x32, schar) -OPENCV_HAL_IMPL_AVX_LOADSTORE(v_uint16x16, ushort) -OPENCV_HAL_IMPL_AVX_LOADSTORE(v_int16x16, short) -OPENCV_HAL_IMPL_AVX_LOADSTORE(v_uint32x8, unsigned) -OPENCV_HAL_IMPL_AVX_LOADSTORE(v_int32x8, int) -OPENCV_HAL_IMPL_AVX_LOADSTORE(v_uint64x4, uint64) -OPENCV_HAL_IMPL_AVX_LOADSTORE(v_int64x4, int64) - -#define OPENCV_HAL_IMPL_AVX_LOADSTORE_FLT(_Tpvec, _Tp, suffix, halfreg) \ - inline _Tpvec v256_load(const _Tp* ptr) \ - { return _Tpvec(_mm256_loadu_##suffix(ptr)); } \ - inline _Tpvec v256_load_aligned(const _Tp* ptr) \ - { return _Tpvec(_mm256_load_##suffix(ptr)); } \ - inline _Tpvec v256_load_low(const _Tp* ptr) \ - { \ - return _Tpvec(_mm256_cast##suffix##128_##suffix##256 \ - (_mm_loadu_##suffix(ptr))); \ - } \ - inline _Tpvec v256_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ - { \ - halfreg vlo = _mm_loadu_##suffix(ptr0); \ - halfreg vhi = _mm_loadu_##suffix(ptr1); \ - return _Tpvec(_v256_combine(vlo, vhi)); \ - } \ - inline void v_store(_Tp* ptr, const _Tpvec& a) \ - { _mm256_storeu_##suffix(ptr, a.val); } \ - inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ - { _mm256_store_##suffix(ptr, a.val); } \ - inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ - { _mm256_stream_##suffix(ptr, a.val); } \ - inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ - { \ - if( mode == hal::STORE_UNALIGNED ) \ - _mm256_storeu_##suffix(ptr, a.val); \ - else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ - _mm256_stream_##suffix(ptr, a.val); \ - else \ - _mm256_store_##suffix(ptr, a.val); \ - } \ - inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ - { _mm_storeu_##suffix(ptr, _v256_extract_low(a.val)); } \ - inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ - { _mm_storeu_##suffix(ptr, _v256_extract_high(a.val)); } - -OPENCV_HAL_IMPL_AVX_LOADSTORE_FLT(v_float32x8, float, ps, __m128) -OPENCV_HAL_IMPL_AVX_LOADSTORE_FLT(v_float64x4, double, pd, __m128d) - -#define OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, _Tpvecf, suffix, cast) \ - inline _Tpvec v_reinterpret_as_##suffix(const _Tpvecf& a) \ - { return _Tpvec(cast(a.val)); } - -#define OPENCV_HAL_IMPL_AVX_INIT(_Tpvec, _Tp, suffix, ssuffix, ctype_s) \ - inline _Tpvec v256_setzero_##suffix() \ - { return _Tpvec(_mm256_setzero_si256()); } \ - inline _Tpvec v256_setall_##suffix(_Tp v) \ - { return _Tpvec(_mm256_set1_##ssuffix((ctype_s)v)); } \ - template <> inline _Tpvec v_setzero_() \ - { return v256_setzero_##suffix(); } \ - template <> inline _Tpvec v_setall_(_Tp v) \ - { return v256_setall_##suffix(v); } \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint8x32, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int8x32, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint16x16, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int16x16, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint32x8, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int32x8, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint64x4, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int64x4, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_float32x8, suffix, _mm256_castps_si256) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_float64x4, suffix, _mm256_castpd_si256) - -OPENCV_HAL_IMPL_AVX_INIT(v_uint8x32, uchar, u8, epi8, char) -OPENCV_HAL_IMPL_AVX_INIT(v_int8x32, schar, s8, epi8, char) -OPENCV_HAL_IMPL_AVX_INIT(v_uint16x16, ushort, u16, epi16, short) -OPENCV_HAL_IMPL_AVX_INIT(v_int16x16, short, s16, epi16, short) -OPENCV_HAL_IMPL_AVX_INIT(v_uint32x8, unsigned, u32, epi32, int) -OPENCV_HAL_IMPL_AVX_INIT(v_int32x8, int, s32, epi32, int) -OPENCV_HAL_IMPL_AVX_INIT(v_uint64x4, uint64, u64, epi64x, int64) -OPENCV_HAL_IMPL_AVX_INIT(v_int64x4, int64, s64, epi64x, int64) - -#define OPENCV_HAL_IMPL_AVX_INIT_FLT(_Tpvec, _Tp, suffix, zsuffix, cast) \ - inline _Tpvec v256_setzero_##suffix() \ - { return _Tpvec(_mm256_setzero_##zsuffix()); } \ - inline _Tpvec v256_setall_##suffix(_Tp v) \ - { return _Tpvec(_mm256_set1_##zsuffix(v)); } \ - template <> inline _Tpvec v_setzero_() \ - { return v256_setzero_##suffix(); } \ - template <> inline _Tpvec v_setall_(_Tp v) \ - { return v256_setall_##suffix(v); } \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint8x32, suffix, cast) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int8x32, suffix, cast) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint16x16, suffix, cast) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int16x16, suffix, cast) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint32x8, suffix, cast) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int32x8, suffix, cast) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint64x4, suffix, cast) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int64x4, suffix, cast) - -OPENCV_HAL_IMPL_AVX_INIT_FLT(v_float32x8, float, f32, ps, _mm256_castsi256_ps) -OPENCV_HAL_IMPL_AVX_INIT_FLT(v_float64x4, double, f64, pd, _mm256_castsi256_pd) - -inline v_float32x8 v_reinterpret_as_f32(const v_float32x8& a) -{ return a; } -inline v_float32x8 v_reinterpret_as_f32(const v_float64x4& a) -{ return v_float32x8(_mm256_castpd_ps(a.val)); } - -inline v_float64x4 v_reinterpret_as_f64(const v_float64x4& a) -{ return a; } -inline v_float64x4 v_reinterpret_as_f64(const v_float32x8& a) -{ return v_float64x4(_mm256_castps_pd(a.val)); } - -/* Recombine */ -/*#define OPENCV_HAL_IMPL_AVX_COMBINE(_Tpvec, perm) \ - inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(perm(a.val, b.val, 0x20)); } \ - inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(perm(a.val, b.val, 0x31)); } \ - inline void v_recombine(const _Tpvec& a, const _Tpvec& b, \ - _Tpvec& c, _Tpvec& d) \ - { c = v_combine_low(a, b); d = v_combine_high(a, b); } - -#define OPENCV_HAL_IMPL_AVX_UNPACKS(_Tpvec, suffix) \ - OPENCV_HAL_IMPL_AVX_COMBINE(_Tpvec, _mm256_permute2x128_si256) \ - inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, \ - _Tpvec& b0, _Tpvec& b1) \ - { \ - __m256i v0 = _v256_shuffle_odd_64(a0.val); \ - __m256i v1 = _v256_shuffle_odd_64(a1.val); \ - b0.val = _mm256_unpacklo_##suffix(v0, v1); \ - b1.val = _mm256_unpackhi_##suffix(v0, v1); \ - } - -OPENCV_HAL_IMPL_AVX_UNPACKS(v_uint8x32, epi8) -OPENCV_HAL_IMPL_AVX_UNPACKS(v_int8x32, epi8) -OPENCV_HAL_IMPL_AVX_UNPACKS(v_uint16x16, epi16) -OPENCV_HAL_IMPL_AVX_UNPACKS(v_int16x16, epi16) -OPENCV_HAL_IMPL_AVX_UNPACKS(v_uint32x8, epi32) -OPENCV_HAL_IMPL_AVX_UNPACKS(v_int32x8, epi32) -OPENCV_HAL_IMPL_AVX_UNPACKS(v_uint64x4, epi64) -OPENCV_HAL_IMPL_AVX_UNPACKS(v_int64x4, epi64) -OPENCV_HAL_IMPL_AVX_COMBINE(v_float32x8, _mm256_permute2f128_ps) -OPENCV_HAL_IMPL_AVX_COMBINE(v_float64x4, _mm256_permute2f128_pd) - -inline void v_zip(const v_float32x8& a0, const v_float32x8& a1, v_float32x8& b0, v_float32x8& b1) -{ - __m256 v0 = _mm256_unpacklo_ps(a0.val, a1.val); - __m256 v1 = _mm256_unpackhi_ps(a0.val, a1.val); - v_recombine(v_float32x8(v0), v_float32x8(v1), b0, b1); -} - -inline void v_zip(const v_float64x4& a0, const v_float64x4& a1, v_float64x4& b0, v_float64x4& b1) -{ - __m256d v0 = _v_shuffle_odd_64(a0.val); - __m256d v1 = _v_shuffle_odd_64(a1.val); - b0.val = _mm256_unpacklo_pd(v0, v1); - b1.val = _mm256_unpackhi_pd(v0, v1); -}*/ - -//////////////// Variant Value reordering /////////////// - -// unpacks -#define OPENCV_HAL_IMPL_AVX_UNPACK(_Tpvec, suffix) \ - inline _Tpvec v256_unpacklo(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(_mm256_unpacklo_##suffix(a.val, b.val)); } \ - inline _Tpvec v256_unpackhi(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(_mm256_unpackhi_##suffix(a.val, b.val)); } - -OPENCV_HAL_IMPL_AVX_UNPACK(v_uint8x32, epi8) -OPENCV_HAL_IMPL_AVX_UNPACK(v_int8x32, epi8) -OPENCV_HAL_IMPL_AVX_UNPACK(v_uint16x16, epi16) -OPENCV_HAL_IMPL_AVX_UNPACK(v_int16x16, epi16) -OPENCV_HAL_IMPL_AVX_UNPACK(v_uint32x8, epi32) -OPENCV_HAL_IMPL_AVX_UNPACK(v_int32x8, epi32) -OPENCV_HAL_IMPL_AVX_UNPACK(v_uint64x4, epi64) -OPENCV_HAL_IMPL_AVX_UNPACK(v_int64x4, epi64) -OPENCV_HAL_IMPL_AVX_UNPACK(v_float32x8, ps) -OPENCV_HAL_IMPL_AVX_UNPACK(v_float64x4, pd) - -// blend -#define OPENCV_HAL_IMPL_AVX_BLEND(_Tpvec, suffix) \ - template \ - inline _Tpvec v256_blend(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(_mm256_blend_##suffix(a.val, b.val, m)); } - -OPENCV_HAL_IMPL_AVX_BLEND(v_uint16x16, epi16) -OPENCV_HAL_IMPL_AVX_BLEND(v_int16x16, epi16) -OPENCV_HAL_IMPL_AVX_BLEND(v_uint32x8, epi32) -OPENCV_HAL_IMPL_AVX_BLEND(v_int32x8, epi32) -OPENCV_HAL_IMPL_AVX_BLEND(v_float32x8, ps) -OPENCV_HAL_IMPL_AVX_BLEND(v_float64x4, pd) - -template -inline v_uint64x4 v256_blend(const v_uint64x4& a, const v_uint64x4& b) -{ - enum {M0 = m}; - enum {M1 = (M0 | (M0 << 2)) & 0x33}; - enum {M2 = (M1 | (M1 << 1)) & 0x55}; - enum {MM = M2 | (M2 << 1)}; - return v_uint64x4(_mm256_blend_epi32(a.val, b.val, MM)); -} -template -inline v_int64x4 v256_blend(const v_int64x4& a, const v_int64x4& b) -{ return v_int64x4(v256_blend(v_uint64x4(a.val), v_uint64x4(b.val)).val); } - -// shuffle -// todo: emulate 64bit -#define OPENCV_HAL_IMPL_AVX_SHUFFLE(_Tpvec, intrin) \ - template \ - inline _Tpvec v256_shuffle(const _Tpvec& a) \ - { return _Tpvec(_mm256_##intrin(a.val, m)); } - -OPENCV_HAL_IMPL_AVX_SHUFFLE(v_uint32x8, shuffle_epi32) -OPENCV_HAL_IMPL_AVX_SHUFFLE(v_int32x8, shuffle_epi32) -OPENCV_HAL_IMPL_AVX_SHUFFLE(v_float32x8, permute_ps) -OPENCV_HAL_IMPL_AVX_SHUFFLE(v_float64x4, permute_pd) - -template -inline void v256_zip(const _Tpvec& a, const _Tpvec& b, _Tpvec& ab0, _Tpvec& ab1) -{ - ab0 = v256_unpacklo(a, b); - ab1 = v256_unpackhi(a, b); -} - -template -inline _Tpvec v256_combine_diagonal(const _Tpvec& a, const _Tpvec& b) -{ return _Tpvec(_mm256_blend_epi32(a.val, b.val, 0xf0)); } - -inline v_float32x8 v256_combine_diagonal(const v_float32x8& a, const v_float32x8& b) -{ return v256_blend<0xf0>(a, b); } - -inline v_float64x4 v256_combine_diagonal(const v_float64x4& a, const v_float64x4& b) -{ return v256_blend<0xc>(a, b); } - -template -inline _Tpvec v256_alignr_128(const _Tpvec& a, const _Tpvec& b) -{ return v256_permute2x128<0x21>(a, b); } - -template -inline _Tpvec v256_alignr_64(const _Tpvec& a, const _Tpvec& b) -{ return _Tpvec(_mm256_alignr_epi8(a.val, b.val, 8)); } -inline v_float64x4 v256_alignr_64(const v_float64x4& a, const v_float64x4& b) -{ return v_float64x4(_mm256_shuffle_pd(b.val, a.val, _MM_SHUFFLE(0, 0, 1, 1))); } -// todo: emulate float32 - -template -inline _Tpvec v256_swap_halves(const _Tpvec& a) -{ return v256_permute2x128<1>(a, a); } - -template -inline _Tpvec v256_reverse_64(const _Tpvec& a) -{ return v256_permute4x64<_MM_SHUFFLE(0, 1, 2, 3)>(a); } - -// ZIP -#define OPENCV_HAL_IMPL_AVX_ZIP(_Tpvec) \ - inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ - { return v256_permute2x128<0x20>(a, b); } \ - inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ - { return v256_permute2x128<0x31>(a, b); } \ - inline void v_recombine(const _Tpvec& a, const _Tpvec& b, \ - _Tpvec& c, _Tpvec& d) \ - { \ - _Tpvec a1b0 = v256_alignr_128(a, b); \ - c = v256_combine_diagonal(a, a1b0); \ - d = v256_combine_diagonal(a1b0, b); \ - } \ - inline void v_zip(const _Tpvec& a, const _Tpvec& b, \ - _Tpvec& ab0, _Tpvec& ab1) \ - { \ - _Tpvec ab0ab2, ab1ab3; \ - v256_zip(a, b, ab0ab2, ab1ab3); \ - v_recombine(ab0ab2, ab1ab3, ab0, ab1); \ - } - -OPENCV_HAL_IMPL_AVX_ZIP(v_uint8x32) -OPENCV_HAL_IMPL_AVX_ZIP(v_int8x32) -OPENCV_HAL_IMPL_AVX_ZIP(v_uint16x16) -OPENCV_HAL_IMPL_AVX_ZIP(v_int16x16) -OPENCV_HAL_IMPL_AVX_ZIP(v_uint32x8) -OPENCV_HAL_IMPL_AVX_ZIP(v_int32x8) -OPENCV_HAL_IMPL_AVX_ZIP(v_uint64x4) -OPENCV_HAL_IMPL_AVX_ZIP(v_int64x4) -OPENCV_HAL_IMPL_AVX_ZIP(v_float32x8) -OPENCV_HAL_IMPL_AVX_ZIP(v_float64x4) - -////////// Arithmetic, bitwise and comparison operations ///////// - -/* Element-wise binary and unary operations */ - -/** Arithmetics **/ -#define OPENCV_HAL_IMPL_AVX_BIN_OP(bin_op, _Tpvec, intrin) \ - inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(intrin(a.val, b.val)); } - -OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_uint8x32, _mm256_adds_epu8) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_uint8x32, _mm256_subs_epu8) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_int8x32, _mm256_adds_epi8) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_int8x32, _mm256_subs_epi8) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_uint16x16, _mm256_adds_epu16) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_uint16x16, _mm256_subs_epu16) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_int16x16, _mm256_adds_epi16) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_int16x16, _mm256_subs_epi16) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_uint32x8, _mm256_add_epi32) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_uint32x8, _mm256_sub_epi32) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_mul, v_uint32x8, _mm256_mullo_epi32) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_int32x8, _mm256_add_epi32) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_int32x8, _mm256_sub_epi32) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_mul, v_int32x8, _mm256_mullo_epi32) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_uint64x4, _mm256_add_epi64) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_uint64x4, _mm256_sub_epi64) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_int64x4, _mm256_add_epi64) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_int64x4, _mm256_sub_epi64) - -OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_float32x8, _mm256_add_ps) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_float32x8, _mm256_sub_ps) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_mul, v_float32x8, _mm256_mul_ps) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_div, v_float32x8, _mm256_div_ps) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_float64x4, _mm256_add_pd) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_float64x4, _mm256_sub_pd) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_mul, v_float64x4, _mm256_mul_pd) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_div, v_float64x4, _mm256_div_pd) - -// saturating multiply 8-bit, 16-bit -inline v_uint8x32 v_mul(const v_uint8x32& a, const v_uint8x32& b) -{ - v_uint16x16 c, d; - v_mul_expand(a, b, c, d); - return v_pack(c, d); -} -inline v_int8x32 v_mul(const v_int8x32& a, const v_int8x32& b) -{ - v_int16x16 c, d; - v_mul_expand(a, b, c, d); - return v_pack(c, d); -} -inline v_uint16x16 v_mul(const v_uint16x16& a, const v_uint16x16& b) -{ - __m256i pl = _mm256_mullo_epi16(a.val, b.val); - __m256i ph = _mm256_mulhi_epu16(a.val, b.val); - __m256i p0 = _mm256_unpacklo_epi16(pl, ph); - __m256i p1 = _mm256_unpackhi_epi16(pl, ph); - return v_uint16x16(_v256_packs_epu32(p0, p1)); -} -inline v_int16x16 v_mul(const v_int16x16& a, const v_int16x16& b) -{ - __m256i pl = _mm256_mullo_epi16(a.val, b.val); - __m256i ph = _mm256_mulhi_epi16(a.val, b.val); - __m256i p0 = _mm256_unpacklo_epi16(pl, ph); - __m256i p1 = _mm256_unpackhi_epi16(pl, ph); - return v_int16x16(_mm256_packs_epi32(p0, p1)); -} - -/** Non-saturating arithmetics **/ -#define OPENCV_HAL_IMPL_AVX_BIN_FUNC(func, _Tpvec, intrin) \ - inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(intrin(a.val, b.val)); } - -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_add_wrap, v_uint8x32, _mm256_add_epi8) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_add_wrap, v_int8x32, _mm256_add_epi8) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_add_wrap, v_uint16x16, _mm256_add_epi16) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_add_wrap, v_int16x16, _mm256_add_epi16) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_sub_wrap, v_uint8x32, _mm256_sub_epi8) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_sub_wrap, v_int8x32, _mm256_sub_epi8) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_sub_wrap, v_uint16x16, _mm256_sub_epi16) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_sub_wrap, v_int16x16, _mm256_sub_epi16) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_mul_wrap, v_uint16x16, _mm256_mullo_epi16) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_mul_wrap, v_int16x16, _mm256_mullo_epi16) - -inline v_uint8x32 v_mul_wrap(const v_uint8x32& a, const v_uint8x32& b) -{ - __m256i ad = _mm256_srai_epi16(a.val, 8); - __m256i bd = _mm256_srai_epi16(b.val, 8); - __m256i p0 = _mm256_mullo_epi16(a.val, b.val); // even - __m256i p1 = _mm256_slli_epi16(_mm256_mullo_epi16(ad, bd), 8); // odd - - const __m256i b01 = _mm256_set1_epi32(0xFF00FF00); - return v_uint8x32(_mm256_blendv_epi8(p0, p1, b01)); -} -inline v_int8x32 v_mul_wrap(const v_int8x32& a, const v_int8x32& b) -{ - return v_reinterpret_as_s8(v_mul_wrap(v_reinterpret_as_u8(a), v_reinterpret_as_u8(b))); -} - -// Multiply and expand -inline void v_mul_expand(const v_uint8x32& a, const v_uint8x32& b, - v_uint16x16& c, v_uint16x16& d) -{ - v_uint16x16 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c = v_mul_wrap(a0, b0); - d = v_mul_wrap(a1, b1); -} - -inline void v_mul_expand(const v_int8x32& a, const v_int8x32& b, - v_int16x16& c, v_int16x16& d) -{ - v_int16x16 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c = v_mul_wrap(a0, b0); - d = v_mul_wrap(a1, b1); -} - -inline void v_mul_expand(const v_int16x16& a, const v_int16x16& b, - v_int32x8& c, v_int32x8& d) -{ - v_int16x16 vhi = v_int16x16(_mm256_mulhi_epi16(a.val, b.val)); - - v_int16x16 v0, v1; - v_zip(v_mul_wrap(a, b), vhi, v0, v1); - - c = v_reinterpret_as_s32(v0); - d = v_reinterpret_as_s32(v1); -} - -inline void v_mul_expand(const v_uint16x16& a, const v_uint16x16& b, - v_uint32x8& c, v_uint32x8& d) -{ - v_uint16x16 vhi = v_uint16x16(_mm256_mulhi_epu16(a.val, b.val)); - - v_uint16x16 v0, v1; - v_zip(v_mul_wrap(a, b), vhi, v0, v1); - - c = v_reinterpret_as_u32(v0); - d = v_reinterpret_as_u32(v1); -} - -inline void v_mul_expand(const v_uint32x8& a, const v_uint32x8& b, - v_uint64x4& c, v_uint64x4& d) -{ - __m256i v0 = _mm256_mul_epu32(a.val, b.val); - __m256i v1 = _mm256_mul_epu32(_mm256_srli_epi64(a.val, 32), _mm256_srli_epi64(b.val, 32)); - v_zip(v_uint64x4(v0), v_uint64x4(v1), c, d); -} - -inline v_int16x16 v_mul_hi(const v_int16x16& a, const v_int16x16& b) { return v_int16x16(_mm256_mulhi_epi16(a.val, b.val)); } -inline v_uint16x16 v_mul_hi(const v_uint16x16& a, const v_uint16x16& b) { return v_uint16x16(_mm256_mulhi_epu16(a.val, b.val)); } - -/** Bitwise shifts **/ -#define OPENCV_HAL_IMPL_AVX_SHIFT_OP(_Tpuvec, _Tpsvec, suffix, srai) \ - inline _Tpuvec v_shl(const _Tpuvec& a, int imm) \ - { return _Tpuvec(_mm256_slli_##suffix(a.val, imm)); } \ - inline _Tpsvec v_shl(const _Tpsvec& a, int imm) \ - { return _Tpsvec(_mm256_slli_##suffix(a.val, imm)); } \ - inline _Tpuvec v_shr(const _Tpuvec& a, int imm) \ - { return _Tpuvec(_mm256_srli_##suffix(a.val, imm)); } \ - inline _Tpsvec v_shr(const _Tpsvec& a, int imm) \ - { return _Tpsvec(srai(a.val, imm)); } \ - template \ - inline _Tpuvec v_shl(const _Tpuvec& a) \ - { return _Tpuvec(_mm256_slli_##suffix(a.val, imm)); } \ - template \ - inline _Tpsvec v_shl(const _Tpsvec& a) \ - { return _Tpsvec(_mm256_slli_##suffix(a.val, imm)); } \ - template \ - inline _Tpuvec v_shr(const _Tpuvec& a) \ - { return _Tpuvec(_mm256_srli_##suffix(a.val, imm)); } \ - template \ - inline _Tpsvec v_shr(const _Tpsvec& a) \ - { return _Tpsvec(srai(a.val, imm)); } - -OPENCV_HAL_IMPL_AVX_SHIFT_OP(v_uint16x16, v_int16x16, epi16, _mm256_srai_epi16) -OPENCV_HAL_IMPL_AVX_SHIFT_OP(v_uint32x8, v_int32x8, epi32, _mm256_srai_epi32) - -inline __m256i _mm256_srai_epi64xx(const __m256i a, int imm) -{ - __m256i d = _mm256_set1_epi64x((int64)1 << 63); - __m256i r = _mm256_srli_epi64(_mm256_add_epi64(a, d), imm); - return _mm256_sub_epi64(r, _mm256_srli_epi64(d, imm)); -} -OPENCV_HAL_IMPL_AVX_SHIFT_OP(v_uint64x4, v_int64x4, epi64, _mm256_srai_epi64xx) - - -/** Bitwise logic **/ -#define OPENCV_HAL_IMPL_AVX_LOGIC_OP(_Tpvec, suffix, not_const) \ - OPENCV_HAL_IMPL_AVX_BIN_OP(v_and, _Tpvec, _mm256_and_##suffix) \ - OPENCV_HAL_IMPL_AVX_BIN_OP(v_or, _Tpvec, _mm256_or_##suffix) \ - OPENCV_HAL_IMPL_AVX_BIN_OP(v_xor, _Tpvec, _mm256_xor_##suffix) \ - inline _Tpvec v_not(const _Tpvec& a) \ - { return _Tpvec(_mm256_xor_##suffix(a.val, not_const)); } - -OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_uint8x32, si256, _mm256_set1_epi32(-1)) -OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_int8x32, si256, _mm256_set1_epi32(-1)) -OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_uint16x16, si256, _mm256_set1_epi32(-1)) -OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_int16x16, si256, _mm256_set1_epi32(-1)) -OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_uint32x8, si256, _mm256_set1_epi32(-1)) -OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_int32x8, si256, _mm256_set1_epi32(-1)) -OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_uint64x4, si256, _mm256_set1_epi64x(-1)) -OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_int64x4, si256, _mm256_set1_epi64x(-1)) -OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_float32x8, ps, _mm256_castsi256_ps(_mm256_set1_epi32(-1))) -OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_float64x4, pd, _mm256_castsi256_pd(_mm256_set1_epi32(-1))) - -/** Select **/ -#define OPENCV_HAL_IMPL_AVX_SELECT(_Tpvec, suffix) \ - inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(_mm256_blendv_##suffix(b.val, a.val, mask.val)); } - -OPENCV_HAL_IMPL_AVX_SELECT(v_uint8x32, epi8) -OPENCV_HAL_IMPL_AVX_SELECT(v_int8x32, epi8) -OPENCV_HAL_IMPL_AVX_SELECT(v_uint16x16, epi8) -OPENCV_HAL_IMPL_AVX_SELECT(v_int16x16, epi8) -OPENCV_HAL_IMPL_AVX_SELECT(v_uint32x8, epi8) -OPENCV_HAL_IMPL_AVX_SELECT(v_int32x8, epi8) -OPENCV_HAL_IMPL_AVX_SELECT(v_float32x8, ps) -OPENCV_HAL_IMPL_AVX_SELECT(v_float64x4, pd) - -/** Comparison **/ -#define OPENCV_HAL_IMPL_AVX_CMP_OP_OV(_Tpvec) \ - inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ - { return v_not(v_eq(a, b)); } \ - inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ - { return v_gt(b, a); } \ - inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ - { return v_not(v_lt(a, b)); } \ - inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ - { return v_ge(b, a); } - -#define OPENCV_HAL_IMPL_AVX_CMP_OP_INT(_Tpuvec, _Tpsvec, suffix, sbit) \ - inline _Tpuvec v_eq(const _Tpuvec& a, const _Tpuvec& b) \ - { return _Tpuvec(_mm256_cmpeq_##suffix(a.val, b.val)); } \ - inline _Tpuvec v_gt(const _Tpuvec& a, const _Tpuvec& b) \ - { \ - __m256i smask = _mm256_set1_##suffix(sbit); \ - return _Tpuvec(_mm256_cmpgt_##suffix( \ - _mm256_xor_si256(a.val, smask), \ - _mm256_xor_si256(b.val, smask))); \ - } \ - inline _Tpsvec v_eq(const _Tpsvec& a, const _Tpsvec& b) \ - { return _Tpsvec(_mm256_cmpeq_##suffix(a.val, b.val)); } \ - inline _Tpsvec v_gt(const _Tpsvec& a, const _Tpsvec& b) \ - { return _Tpsvec(_mm256_cmpgt_##suffix(a.val, b.val)); } \ - OPENCV_HAL_IMPL_AVX_CMP_OP_OV(_Tpuvec) \ - OPENCV_HAL_IMPL_AVX_CMP_OP_OV(_Tpsvec) - -OPENCV_HAL_IMPL_AVX_CMP_OP_INT(v_uint8x32, v_int8x32, epi8, (char)-128) -OPENCV_HAL_IMPL_AVX_CMP_OP_INT(v_uint16x16, v_int16x16, epi16, (short)-32768) -OPENCV_HAL_IMPL_AVX_CMP_OP_INT(v_uint32x8, v_int32x8, epi32, (int)0x80000000) - -#define OPENCV_HAL_IMPL_AVX_CMP_OP_64BIT(_Tpvec) \ - inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(_mm256_cmpeq_epi64(a.val, b.val)); } \ - inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ - { return v_not(v_eq(a, b)); } - -OPENCV_HAL_IMPL_AVX_CMP_OP_64BIT(v_uint64x4) -OPENCV_HAL_IMPL_AVX_CMP_OP_64BIT(v_int64x4) - -#define OPENCV_HAL_IMPL_AVX_CMP_FLT(bin_op, imm8, _Tpvec, suffix) \ - inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(_mm256_cmp_##suffix(a.val, b.val, imm8)); } - -#define OPENCV_HAL_IMPL_AVX_CMP_OP_FLT(_Tpvec, suffix) \ - OPENCV_HAL_IMPL_AVX_CMP_FLT(v_eq, _CMP_EQ_OQ, _Tpvec, suffix) \ - OPENCV_HAL_IMPL_AVX_CMP_FLT(v_ne, _CMP_NEQ_OQ, _Tpvec, suffix) \ - OPENCV_HAL_IMPL_AVX_CMP_FLT(v_lt, _CMP_LT_OQ, _Tpvec, suffix) \ - OPENCV_HAL_IMPL_AVX_CMP_FLT(v_gt, _CMP_GT_OQ, _Tpvec, suffix) \ - OPENCV_HAL_IMPL_AVX_CMP_FLT(v_le, _CMP_LE_OQ, _Tpvec, suffix) \ - OPENCV_HAL_IMPL_AVX_CMP_FLT(v_ge, _CMP_GE_OQ, _Tpvec, suffix) - -OPENCV_HAL_IMPL_AVX_CMP_OP_FLT(v_float32x8, ps) -OPENCV_HAL_IMPL_AVX_CMP_OP_FLT(v_float64x4, pd) - -inline v_float32x8 v_not_nan(const v_float32x8& a) -{ return v_float32x8(_mm256_cmp_ps(a.val, a.val, _CMP_ORD_Q)); } -inline v_float64x4 v_not_nan(const v_float64x4& a) -{ return v_float64x4(_mm256_cmp_pd(a.val, a.val, _CMP_ORD_Q)); } - -/** min/max **/ -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_uint8x32, _mm256_min_epu8) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_uint8x32, _mm256_max_epu8) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_int8x32, _mm256_min_epi8) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_int8x32, _mm256_max_epi8) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_uint16x16, _mm256_min_epu16) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_uint16x16, _mm256_max_epu16) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_int16x16, _mm256_min_epi16) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_int16x16, _mm256_max_epi16) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_uint32x8, _mm256_min_epu32) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_uint32x8, _mm256_max_epu32) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_int32x8, _mm256_min_epi32) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_int32x8, _mm256_max_epi32) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_float32x8, _mm256_min_ps) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_float32x8, _mm256_max_ps) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_float64x4, _mm256_min_pd) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_float64x4, _mm256_max_pd) - -/** Rotate **/ -template -inline v_uint8x32 v_rotate_left(const v_uint8x32& a, const v_uint8x32& b) -{ - enum {IMM_R = (16 - imm) & 0xFF}; - enum {IMM_R2 = (32 - imm) & 0xFF}; - - if (imm == 0) return a; - if (imm == 32) return b; - if (imm > 32) return v_uint8x32(); - - __m256i swap = _mm256_permute2x128_si256(a.val, b.val, 0x03); - if (imm == 16) return v_uint8x32(swap); - if (imm < 16) return v_uint8x32(_mm256_alignr_epi8(a.val, swap, IMM_R)); - return v_uint8x32(_mm256_alignr_epi8(swap, b.val, IMM_R2)); // imm < 32 -} - -template -inline v_uint8x32 v_rotate_right(const v_uint8x32& a, const v_uint8x32& b) -{ - enum {IMM_L = (imm - 16) & 0xFF}; - - if (imm == 0) return a; - if (imm == 32) return b; - if (imm > 32) return v_uint8x32(); - - __m256i swap = _mm256_permute2x128_si256(a.val, b.val, 0x21); - if (imm == 16) return v_uint8x32(swap); - if (imm < 16) return v_uint8x32(_mm256_alignr_epi8(swap, a.val, imm)); - return v_uint8x32(_mm256_alignr_epi8(b.val, swap, IMM_L)); -} - -template -inline v_uint8x32 v_rotate_left(const v_uint8x32& a) -{ - enum {IMM_L = (imm - 16) & 0xFF}; - enum {IMM_R = (16 - imm) & 0xFF}; - - if (imm == 0) return a; - if (imm > 32) return v_uint8x32(); - - // ESAC control[3] ? [127:0] = 0 - __m256i swapz = _mm256_permute2x128_si256(a.val, a.val, _MM_SHUFFLE(0, 0, 2, 0)); - if (imm == 16) return v_uint8x32(swapz); - if (imm < 16) return v_uint8x32(_mm256_alignr_epi8(a.val, swapz, IMM_R)); - return v_uint8x32(_mm256_slli_si256(swapz, IMM_L)); -} - -template -inline v_uint8x32 v_rotate_right(const v_uint8x32& a) -{ - enum {IMM_L = (imm - 16) & 0xFF}; - - if (imm == 0) return a; - if (imm > 32) return v_uint8x32(); - - // ESAC control[3] ? [127:0] = 0 - __m256i swapz = _mm256_permute2x128_si256(a.val, a.val, _MM_SHUFFLE(2, 0, 0, 1)); - if (imm == 16) return v_uint8x32(swapz); - if (imm < 16) return v_uint8x32(_mm256_alignr_epi8(swapz, a.val, imm)); - return v_uint8x32(_mm256_srli_si256(swapz, IMM_L)); -} - -#define OPENCV_HAL_IMPL_AVX_ROTATE_CAST(intrin, _Tpvec, cast) \ - template \ - inline _Tpvec intrin(const _Tpvec& a, const _Tpvec& b) \ - { \ - enum {IMMxW = imm * sizeof(typename _Tpvec::lane_type)}; \ - v_uint8x32 ret = intrin(v_reinterpret_as_u8(a), \ - v_reinterpret_as_u8(b)); \ - return _Tpvec(cast(ret.val)); \ - } \ - template \ - inline _Tpvec intrin(const _Tpvec& a) \ - { \ - enum {IMMxW = imm * sizeof(typename _Tpvec::lane_type)}; \ - v_uint8x32 ret = intrin(v_reinterpret_as_u8(a)); \ - return _Tpvec(cast(ret.val)); \ - } - -#define OPENCV_HAL_IMPL_AVX_ROTATE(_Tpvec) \ - OPENCV_HAL_IMPL_AVX_ROTATE_CAST(v_rotate_left, _Tpvec, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX_ROTATE_CAST(v_rotate_right, _Tpvec, OPENCV_HAL_NOP) - -OPENCV_HAL_IMPL_AVX_ROTATE(v_int8x32) -OPENCV_HAL_IMPL_AVX_ROTATE(v_uint16x16) -OPENCV_HAL_IMPL_AVX_ROTATE(v_int16x16) -OPENCV_HAL_IMPL_AVX_ROTATE(v_uint32x8) -OPENCV_HAL_IMPL_AVX_ROTATE(v_int32x8) -OPENCV_HAL_IMPL_AVX_ROTATE(v_uint64x4) -OPENCV_HAL_IMPL_AVX_ROTATE(v_int64x4) - -OPENCV_HAL_IMPL_AVX_ROTATE_CAST(v_rotate_left, v_float32x8, _mm256_castsi256_ps) -OPENCV_HAL_IMPL_AVX_ROTATE_CAST(v_rotate_right, v_float32x8, _mm256_castsi256_ps) -OPENCV_HAL_IMPL_AVX_ROTATE_CAST(v_rotate_left, v_float64x4, _mm256_castsi256_pd) -OPENCV_HAL_IMPL_AVX_ROTATE_CAST(v_rotate_right, v_float64x4, _mm256_castsi256_pd) - -/** Reverse **/ -inline v_uint8x32 v_reverse(const v_uint8x32 &a) -{ - static const __m256i perm = _mm256_setr_epi8( - 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, - 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); - __m256i vec = _mm256_shuffle_epi8(a.val, perm); - return v_uint8x32(_mm256_permute2x128_si256(vec, vec, 1)); -} - -inline v_int8x32 v_reverse(const v_int8x32 &a) -{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } - -inline v_uint16x16 v_reverse(const v_uint16x16 &a) -{ - static const __m256i perm = _mm256_setr_epi8( - 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1, - 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1); - __m256i vec = _mm256_shuffle_epi8(a.val, perm); - return v_uint16x16(_mm256_permute2x128_si256(vec, vec, 1)); -} - -inline v_int16x16 v_reverse(const v_int16x16 &a) -{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } - -inline v_uint32x8 v_reverse(const v_uint32x8 &a) -{ - static const __m256i perm = _mm256_setr_epi32(7, 6, 5, 4, 3, 2, 1, 0); - return v_uint32x8(_mm256_permutevar8x32_epi32(a.val, perm)); -} - -inline v_int32x8 v_reverse(const v_int32x8 &a) -{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_float32x8 v_reverse(const v_float32x8 &a) -{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_uint64x4 v_reverse(const v_uint64x4 &a) -{ - return v_uint64x4(_mm256_permute4x64_epi64(a.val, _MM_SHUFFLE(0, 1, 2, 3))); -} - -inline v_int64x4 v_reverse(const v_int64x4 &a) -{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } - -inline v_float64x4 v_reverse(const v_float64x4 &a) -{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } - -////////// Reduce and mask ///////// - -/** Reduce **/ -inline unsigned v_reduce_sum(const v_uint8x32& a) -{ - __m256i half = _mm256_sad_epu8(a.val, _mm256_setzero_si256()); - __m128i quarter = _mm_add_epi32(_v256_extract_low(half), _v256_extract_high(half)); - return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(quarter, _mm_unpackhi_epi64(quarter, quarter))); -} -inline int v_reduce_sum(const v_int8x32& a) -{ - __m256i half = _mm256_sad_epu8(_mm256_xor_si256(a.val, _mm256_set1_epi8((schar)-128)), _mm256_setzero_si256()); - __m128i quarter = _mm_add_epi32(_v256_extract_low(half), _v256_extract_high(half)); - return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(quarter, _mm_unpackhi_epi64(quarter, quarter))) - 4096; -} -#define OPENCV_HAL_IMPL_AVX_REDUCE_32(_Tpvec, sctype, func, intrin) \ - inline sctype v_reduce_##func(const _Tpvec& a) \ - { \ - __m128i val = intrin(_v256_extract_low(a.val), _v256_extract_high(a.val)); \ - val = intrin(val, _mm_srli_si128(val,8)); \ - val = intrin(val, _mm_srli_si128(val,4)); \ - val = intrin(val, _mm_srli_si128(val,2)); \ - val = intrin(val, _mm_srli_si128(val,1)); \ - return (sctype)_mm_cvtsi128_si32(val); \ - } - -OPENCV_HAL_IMPL_AVX_REDUCE_32(v_uint8x32, uchar, min, _mm_min_epu8) -OPENCV_HAL_IMPL_AVX_REDUCE_32(v_int8x32, schar, min, _mm_min_epi8) -OPENCV_HAL_IMPL_AVX_REDUCE_32(v_uint8x32, uchar, max, _mm_max_epu8) -OPENCV_HAL_IMPL_AVX_REDUCE_32(v_int8x32, schar, max, _mm_max_epi8) - -#define OPENCV_HAL_IMPL_AVX_REDUCE_16(_Tpvec, sctype, func, intrin) \ - inline sctype v_reduce_##func(const _Tpvec& a) \ - { \ - __m128i v0 = _v256_extract_low(a.val); \ - __m128i v1 = _v256_extract_high(a.val); \ - v0 = intrin(v0, v1); \ - v0 = intrin(v0, _mm_srli_si128(v0, 8)); \ - v0 = intrin(v0, _mm_srli_si128(v0, 4)); \ - v0 = intrin(v0, _mm_srli_si128(v0, 2)); \ - return (sctype) _mm_cvtsi128_si32(v0); \ - } - -OPENCV_HAL_IMPL_AVX_REDUCE_16(v_uint16x16, ushort, min, _mm_min_epu16) -OPENCV_HAL_IMPL_AVX_REDUCE_16(v_int16x16, short, min, _mm_min_epi16) -OPENCV_HAL_IMPL_AVX_REDUCE_16(v_uint16x16, ushort, max, _mm_max_epu16) -OPENCV_HAL_IMPL_AVX_REDUCE_16(v_int16x16, short, max, _mm_max_epi16) - -#define OPENCV_HAL_IMPL_AVX_REDUCE_8(_Tpvec, sctype, func, intrin) \ - inline sctype v_reduce_##func(const _Tpvec& a) \ - { \ - __m128i v0 = _v256_extract_low(a.val); \ - __m128i v1 = _v256_extract_high(a.val); \ - v0 = intrin(v0, v1); \ - v0 = intrin(v0, _mm_srli_si128(v0, 8)); \ - v0 = intrin(v0, _mm_srli_si128(v0, 4)); \ - return (sctype) _mm_cvtsi128_si32(v0); \ - } - -OPENCV_HAL_IMPL_AVX_REDUCE_8(v_uint32x8, unsigned, min, _mm_min_epu32) -OPENCV_HAL_IMPL_AVX_REDUCE_8(v_int32x8, int, min, _mm_min_epi32) -OPENCV_HAL_IMPL_AVX_REDUCE_8(v_uint32x8, unsigned, max, _mm_max_epu32) -OPENCV_HAL_IMPL_AVX_REDUCE_8(v_int32x8, int, max, _mm_max_epi32) - -#define OPENCV_HAL_IMPL_AVX_REDUCE_FLT(func, intrin) \ - inline float v_reduce_##func(const v_float32x8& a) \ - { \ - __m128 v0 = _v256_extract_low(a.val); \ - __m128 v1 = _v256_extract_high(a.val); \ - v0 = intrin(v0, v1); \ - v0 = intrin(v0, _mm_permute_ps(v0, _MM_SHUFFLE(0, 0, 3, 2))); \ - v0 = intrin(v0, _mm_permute_ps(v0, _MM_SHUFFLE(0, 0, 0, 1))); \ - return _mm_cvtss_f32(v0); \ - } - -OPENCV_HAL_IMPL_AVX_REDUCE_FLT(min, _mm_min_ps) -OPENCV_HAL_IMPL_AVX_REDUCE_FLT(max, _mm_max_ps) - -inline int v_reduce_sum(const v_int32x8& a) -{ - __m256i s0 = _mm256_hadd_epi32(a.val, a.val); - s0 = _mm256_hadd_epi32(s0, s0); - - __m128i s1 = _v256_extract_high(s0); - s1 = _mm_add_epi32(_v256_extract_low(s0), s1); - - return _mm_cvtsi128_si32(s1); -} - -inline unsigned v_reduce_sum(const v_uint32x8& a) -{ return v_reduce_sum(v_reinterpret_as_s32(a)); } - -inline int v_reduce_sum(const v_int16x16& a) -{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } -inline unsigned v_reduce_sum(const v_uint16x16& a) -{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } - -inline float v_reduce_sum(const v_float32x8& a) -{ - __m256 s0 = _mm256_hadd_ps(a.val, a.val); - s0 = _mm256_hadd_ps(s0, s0); - - __m128 s1 = _v256_extract_high(s0); - s1 = _mm_add_ps(_v256_extract_low(s0), s1); - - return _mm_cvtss_f32(s1); -} - -inline uint64 v_reduce_sum(const v_uint64x4& a) -{ - uint64 CV_DECL_ALIGNED(32) idx[2]; - _mm_store_si128((__m128i*)idx, _mm_add_epi64(_v256_extract_low(a.val), _v256_extract_high(a.val))); - return idx[0] + idx[1]; -} -inline int64 v_reduce_sum(const v_int64x4& a) -{ - int64 CV_DECL_ALIGNED(32) idx[2]; - _mm_store_si128((__m128i*)idx, _mm_add_epi64(_v256_extract_low(a.val), _v256_extract_high(a.val))); - return idx[0] + idx[1]; -} -inline double v_reduce_sum(const v_float64x4& a) -{ - __m256d s0 = _mm256_hadd_pd(a.val, a.val); - return _mm_cvtsd_f64(_mm_add_pd(_v256_extract_low(s0), _v256_extract_high(s0))); -} - -inline v_float32x8 v_reduce_sum4(const v_float32x8& a, const v_float32x8& b, - const v_float32x8& c, const v_float32x8& d) -{ - __m256 ab = _mm256_hadd_ps(a.val, b.val); - __m256 cd = _mm256_hadd_ps(c.val, d.val); - return v_float32x8(_mm256_hadd_ps(ab, cd)); -} - -inline unsigned v_reduce_sad(const v_uint8x32& a, const v_uint8x32& b) -{ - __m256i half = _mm256_sad_epu8(a.val, b.val); - __m128i quarter = _mm_add_epi32(_v256_extract_low(half), _v256_extract_high(half)); - return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(quarter, _mm_unpackhi_epi64(quarter, quarter))); -} -inline unsigned v_reduce_sad(const v_int8x32& a, const v_int8x32& b) -{ - __m256i half = _mm256_set1_epi8(0x7f); - half = _mm256_sad_epu8(_mm256_add_epi8(a.val, half), _mm256_add_epi8(b.val, half)); - __m128i quarter = _mm_add_epi32(_v256_extract_low(half), _v256_extract_high(half)); - return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(quarter, _mm_unpackhi_epi64(quarter, quarter))); -} -inline unsigned v_reduce_sad(const v_uint16x16& a, const v_uint16x16& b) -{ - v_uint32x8 l, h; - v_expand(v_add_wrap(v_sub(a, b), v_sub(b, a)), l, h); - return v_reduce_sum(v_add(l, h)); -} -inline unsigned v_reduce_sad(const v_int16x16& a, const v_int16x16& b) -{ - v_uint32x8 l, h; - v_expand(v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))), l, h); - return v_reduce_sum(v_add(l, h)); -} -inline unsigned v_reduce_sad(const v_uint32x8& a, const v_uint32x8& b) -{ - return v_reduce_sum(v_sub(v_max(a, b), v_min(a, b))); -} -inline unsigned v_reduce_sad(const v_int32x8& a, const v_int32x8& b) -{ - v_int32x8 m = v_lt(a, b); - return v_reduce_sum(v_reinterpret_as_u32(v_sub(v_xor(v_sub(a, b), m), m))); -} -inline float v_reduce_sad(const v_float32x8& a, const v_float32x8& b) -{ - return v_reduce_sum(v_and(v_sub(a, b), v_float32x8(_mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffff))))); -} - -/** Popcount **/ -inline v_uint8x32 v_popcount(const v_uint8x32& a) -{ - __m256i _popcnt_table = _mm256_setr_epi8(0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, - 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4); - __m256i _popcnt_mask = _mm256_set1_epi8(0x0F); - return v_uint8x32(_mm256_add_epi8(_mm256_shuffle_epi8(_popcnt_table, _mm256_and_si256( a.val , _popcnt_mask)), - _mm256_shuffle_epi8(_popcnt_table, _mm256_and_si256(_mm256_srli_epi16(a.val, 4), _popcnt_mask)))); -} -inline v_uint16x16 v_popcount(const v_uint16x16& a) -{ - v_uint8x32 p = v_popcount(v_reinterpret_as_u8(a)); - p = v_add(p, v_rotate_right<1>(p)); - return v_and(v_reinterpret_as_u16(p), v256_setall_u16(0x00ff)); -} -inline v_uint32x8 v_popcount(const v_uint32x8& a) -{ - v_uint8x32 p = v_popcount(v_reinterpret_as_u8(a)); - p = v_add(p, v_rotate_right<1>(p)); - p = v_add(p, v_rotate_right<2>(p)); - return v_and(v_reinterpret_as_u32(p), v256_setall_u32(0x000000ff)); -} -inline v_uint64x4 v_popcount(const v_uint64x4& a) -{ - return v_uint64x4(_mm256_sad_epu8(v_popcount(v_reinterpret_as_u8(a)).val, _mm256_setzero_si256())); -} -inline v_uint8x32 v_popcount(const v_int8x32& a) -{ return v_popcount(v_reinterpret_as_u8(a)); } -inline v_uint16x16 v_popcount(const v_int16x16& a) -{ return v_popcount(v_reinterpret_as_u16(a)); } -inline v_uint32x8 v_popcount(const v_int32x8& a) -{ return v_popcount(v_reinterpret_as_u32(a)); } -inline v_uint64x4 v_popcount(const v_int64x4& a) -{ return v_popcount(v_reinterpret_as_u64(a)); } - -/** Mask **/ -inline int v_signmask(const v_int8x32& a) -{ return _mm256_movemask_epi8(a.val); } -inline int v_signmask(const v_uint8x32& a) -{ return v_signmask(v_reinterpret_as_s8(a)); } - -inline int v_signmask(const v_int16x16& a) -{ return v_signmask(v_pack(a, a)) & 0xFFFF; } -inline int v_signmask(const v_uint16x16& a) -{ return v_signmask(v_reinterpret_as_s16(a)); } - -inline int v_signmask(const v_float32x8& a) -{ return _mm256_movemask_ps(a.val); } -inline int v_signmask(const v_float64x4& a) -{ return _mm256_movemask_pd(a.val); } - -inline int v_signmask(const v_int32x8& a) -{ return v_signmask(v_reinterpret_as_f32(a)); } -inline int v_signmask(const v_uint32x8& a) -{ return v_signmask(v_reinterpret_as_f32(a)); } - -inline int v_signmask(const v_int64x4& a) -{ return v_signmask(v_reinterpret_as_f64(a)); } -inline int v_signmask(const v_uint64x4& a) -{ return v_signmask(v_reinterpret_as_f64(a)); } - -inline int v_scan_forward(const v_int8x32& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } -inline int v_scan_forward(const v_uint8x32& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } -inline int v_scan_forward(const v_int16x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } -inline int v_scan_forward(const v_uint16x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } -inline int v_scan_forward(const v_int32x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_uint32x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_float32x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_int64x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } -inline int v_scan_forward(const v_uint64x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } -inline int v_scan_forward(const v_float64x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } - -/** Checks **/ -#define OPENCV_HAL_IMPL_AVX_CHECK(_Tpvec, allmask) \ - inline bool v_check_all(const _Tpvec& a) { return v_signmask(a) == allmask; } \ - inline bool v_check_any(const _Tpvec& a) { return v_signmask(a) != 0; } -OPENCV_HAL_IMPL_AVX_CHECK(v_uint8x32, -1) -OPENCV_HAL_IMPL_AVX_CHECK(v_int8x32, -1) -OPENCV_HAL_IMPL_AVX_CHECK(v_uint32x8, 255) -OPENCV_HAL_IMPL_AVX_CHECK(v_int32x8, 255) -OPENCV_HAL_IMPL_AVX_CHECK(v_uint64x4, 15) -OPENCV_HAL_IMPL_AVX_CHECK(v_int64x4, 15) -OPENCV_HAL_IMPL_AVX_CHECK(v_float32x8, 255) -OPENCV_HAL_IMPL_AVX_CHECK(v_float64x4, 15) - -#define OPENCV_HAL_IMPL_AVX_CHECK_SHORT(_Tpvec) \ - inline bool v_check_all(const _Tpvec& a) { return (v_signmask(v_reinterpret_as_s8(a)) & 0xaaaaaaaa) == 0xaaaaaaaa; } \ - inline bool v_check_any(const _Tpvec& a) { return (v_signmask(v_reinterpret_as_s8(a)) & 0xaaaaaaaa) != 0; } -OPENCV_HAL_IMPL_AVX_CHECK_SHORT(v_uint16x16) -OPENCV_HAL_IMPL_AVX_CHECK_SHORT(v_int16x16) - -////////// Other math ///////// - -/** Some frequent operations **/ -#if CV_FMA3 -#define OPENCV_HAL_IMPL_AVX_MULADD(_Tpvec, suffix) \ - inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ - { return _Tpvec(_mm256_fmadd_##suffix(a.val, b.val, c.val)); } \ - inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ - { return _Tpvec(_mm256_fmadd_##suffix(a.val, b.val, c.val)); } -#else -#define OPENCV_HAL_IMPL_AVX_MULADD(_Tpvec, suffix) \ - inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ - { return _Tpvec(_mm256_add_##suffix(_mm256_mul_##suffix(a.val, b.val), c.val)); } \ - inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ - { return _Tpvec(_mm256_add_##suffix(_mm256_mul_##suffix(a.val, b.val), c.val)); } -#endif - -#define OPENCV_HAL_IMPL_AVX_MISC(_Tpvec, suffix) \ - inline _Tpvec v_sqrt(const _Tpvec& x) \ - { return _Tpvec(_mm256_sqrt_##suffix(x.val)); } \ - inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ - { return v_fma(a, a, v_mul(b, b)); } \ - inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ - { return v_sqrt(v_fma(a, a, v_mul(b, b))); } - -OPENCV_HAL_IMPL_AVX_MULADD(v_float32x8, ps) -OPENCV_HAL_IMPL_AVX_MULADD(v_float64x4, pd) -OPENCV_HAL_IMPL_AVX_MISC(v_float32x8, ps) -OPENCV_HAL_IMPL_AVX_MISC(v_float64x4, pd) - -inline v_int32x8 v_fma(const v_int32x8& a, const v_int32x8& b, const v_int32x8& c) -{ - return v_add(v_mul(a, b), c); -} - -inline v_int32x8 v_muladd(const v_int32x8& a, const v_int32x8& b, const v_int32x8& c) -{ - return v_fma(a, b, c); -} - -inline v_float32x8 v_invsqrt(const v_float32x8& x) -{ - v_float32x8 half = v_mul(x, v256_setall_f32(0.5)); - v_float32x8 t = v_float32x8(_mm256_rsqrt_ps(x.val)); - // todo: _mm256_fnmsub_ps - t = v_mul(t, v_sub(v256_setall_f32(1.5), v_mul(v_mul(t, t), half))); - return t; -} - -inline v_float64x4 v_invsqrt(const v_float64x4& x) -{ - return v_div(v256_setall_f64(1.), v_sqrt(x)); -} - -/** Absolute values **/ -#define OPENCV_HAL_IMPL_AVX_ABS(_Tpvec, suffix) \ - inline v_u##_Tpvec v_abs(const v_##_Tpvec& x) \ - { return v_u##_Tpvec(_mm256_abs_##suffix(x.val)); } - -OPENCV_HAL_IMPL_AVX_ABS(int8x32, epi8) -OPENCV_HAL_IMPL_AVX_ABS(int16x16, epi16) -OPENCV_HAL_IMPL_AVX_ABS(int32x8, epi32) - -inline v_float32x8 v_abs(const v_float32x8& x) -{ return v_and(x, v_float32x8(_mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffff)))); } -inline v_float64x4 v_abs(const v_float64x4& x) -{ return v_and(x, v_float64x4(_mm256_castsi256_pd(_mm256_srli_epi64(_mm256_set1_epi64x(-1), 1)))); } - -/** Absolute difference **/ -inline v_uint8x32 v_absdiff(const v_uint8x32& a, const v_uint8x32& b) -{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } -inline v_uint16x16 v_absdiff(const v_uint16x16& a, const v_uint16x16& b) -{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } -inline v_uint32x8 v_absdiff(const v_uint32x8& a, const v_uint32x8& b) -{ return v_sub(v_max(a, b), v_min(a, b)); } - -inline v_uint8x32 v_absdiff(const v_int8x32& a, const v_int8x32& b) -{ - v_int8x32 d = v_sub_wrap(a, b); - v_int8x32 m = v_lt(a, b); - return v_reinterpret_as_u8(v_sub_wrap(v_xor(d, m), m)); -} - -inline v_uint16x16 v_absdiff(const v_int16x16& a, const v_int16x16& b) -{ return v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))); } - -inline v_uint32x8 v_absdiff(const v_int32x8& a, const v_int32x8& b) -{ - v_int32x8 d = v_sub(a, b); - v_int32x8 m = v_lt(a, b); - return v_reinterpret_as_u32(v_sub(v_xor(d, m), m)); -} - -inline v_float32x8 v_absdiff(const v_float32x8& a, const v_float32x8& b) -{ return v_abs(v_sub(a, b)); } - -inline v_float64x4 v_absdiff(const v_float64x4& a, const v_float64x4& b) -{ return v_abs(v_sub(a, b)); } - -/** Saturating absolute difference **/ -inline v_int8x32 v_absdiffs(const v_int8x32& a, const v_int8x32& b) -{ - v_int8x32 d = v_sub(a, b); - v_int8x32 m = v_lt(a, b); - return v_sub(v_xor(d, m), m); -} -inline v_int16x16 v_absdiffs(const v_int16x16& a, const v_int16x16& b) -{ return v_sub(v_max(a, b), v_min(a, b)); } - -////////// Conversions ///////// - -/** Rounding **/ -inline v_int32x8 v_round(const v_float32x8& a) -{ return v_int32x8(_mm256_cvtps_epi32(a.val)); } - -inline v_int32x8 v_round(const v_float64x4& a) -{ return v_int32x8(_mm256_castsi128_si256(_mm256_cvtpd_epi32(a.val))); } - -inline v_int32x8 v_round(const v_float64x4& a, const v_float64x4& b) -{ - __m128i ai = _mm256_cvtpd_epi32(a.val), bi = _mm256_cvtpd_epi32(b.val); - return v_int32x8(_v256_combine(ai, bi)); -} - -inline v_int32x8 v_trunc(const v_float32x8& a) -{ return v_int32x8(_mm256_cvttps_epi32(a.val)); } - -inline v_int32x8 v_trunc(const v_float64x4& a) -{ return v_int32x8(_mm256_castsi128_si256(_mm256_cvttpd_epi32(a.val))); } - -inline v_int32x8 v_floor(const v_float32x8& a) -{ return v_int32x8(_mm256_cvttps_epi32(_mm256_floor_ps(a.val))); } - -inline v_int32x8 v_floor(const v_float64x4& a) -{ return v_trunc(v_float64x4(_mm256_floor_pd(a.val))); } - -inline v_int32x8 v_ceil(const v_float32x8& a) -{ return v_int32x8(_mm256_cvttps_epi32(_mm256_ceil_ps(a.val))); } - -inline v_int32x8 v_ceil(const v_float64x4& a) -{ return v_trunc(v_float64x4(_mm256_ceil_pd(a.val))); } - -/** To float **/ -inline v_float32x8 v_cvt_f32(const v_int32x8& a) -{ return v_float32x8(_mm256_cvtepi32_ps(a.val)); } - -inline v_float32x8 v_cvt_f32(const v_float64x4& a) -{ return v_float32x8(_mm256_castps128_ps256(_mm256_cvtpd_ps(a.val))); } - -inline v_float32x8 v_cvt_f32(const v_float64x4& a, const v_float64x4& b) -{ - __m128 af = _mm256_cvtpd_ps(a.val), bf = _mm256_cvtpd_ps(b.val); - return v_float32x8(_v256_combine(af, bf)); -} - -inline v_float64x4 v_cvt_f64(const v_int32x8& a) -{ return v_float64x4(_mm256_cvtepi32_pd(_v256_extract_low(a.val))); } - -inline v_float64x4 v_cvt_f64_high(const v_int32x8& a) -{ return v_float64x4(_mm256_cvtepi32_pd(_v256_extract_high(a.val))); } - -inline v_float64x4 v_cvt_f64(const v_float32x8& a) -{ return v_float64x4(_mm256_cvtps_pd(_v256_extract_low(a.val))); } - -inline v_float64x4 v_cvt_f64_high(const v_float32x8& a) -{ return v_float64x4(_mm256_cvtps_pd(_v256_extract_high(a.val))); } - -// from (Mysticial and wim) https://stackoverflow.com/q/41144668 -inline v_float64x4 v_cvt_f64(const v_int64x4& v) -{ - // constants encoded as floating-point - __m256i magic_i_lo = _mm256_set1_epi64x(0x4330000000000000); // 2^52 - __m256i magic_i_hi32 = _mm256_set1_epi64x(0x4530000080000000); // 2^84 + 2^63 - __m256i magic_i_all = _mm256_set1_epi64x(0x4530000080100000); // 2^84 + 2^63 + 2^52 - __m256d magic_d_all = _mm256_castsi256_pd(magic_i_all); - - // Blend the 32 lowest significant bits of v with magic_int_lo - __m256i v_lo = _mm256_blend_epi32(magic_i_lo, v.val, 0x55); - // Extract the 32 most significant bits of v - __m256i v_hi = _mm256_srli_epi64(v.val, 32); - // Flip the msb of v_hi and blend with 0x45300000 - v_hi = _mm256_xor_si256(v_hi, magic_i_hi32); - // Compute in double precision - __m256d v_hi_dbl = _mm256_sub_pd(_mm256_castsi256_pd(v_hi), magic_d_all); - // (v_hi - magic_d_all) + v_lo Do not assume associativity of floating point addition - __m256d result = _mm256_add_pd(v_hi_dbl, _mm256_castsi256_pd(v_lo)); - return v_float64x4(result); -} - -////////////// Lookup table access //////////////////// - -inline v_int8x32 v256_lut(const schar* tab, const int* idx) -{ - return v_int8x32(_mm256_setr_epi8(tab[idx[ 0]], tab[idx[ 1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], tab[idx[ 5]], tab[idx[ 6]], tab[idx[ 7]], - tab[idx[ 8]], tab[idx[ 9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]], - tab[idx[16]], tab[idx[17]], tab[idx[18]], tab[idx[19]], tab[idx[20]], tab[idx[21]], tab[idx[22]], tab[idx[23]], - tab[idx[24]], tab[idx[25]], tab[idx[26]], tab[idx[27]], tab[idx[28]], tab[idx[29]], tab[idx[30]], tab[idx[31]])); -} -inline v_int8x32 v256_lut_pairs(const schar* tab, const int* idx) -{ - return v_int8x32(_mm256_setr_epi16(*(const short*)(tab + idx[ 0]), *(const short*)(tab + idx[ 1]), *(const short*)(tab + idx[ 2]), *(const short*)(tab + idx[ 3]), - *(const short*)(tab + idx[ 4]), *(const short*)(tab + idx[ 5]), *(const short*)(tab + idx[ 6]), *(const short*)(tab + idx[ 7]), - *(const short*)(tab + idx[ 8]), *(const short*)(tab + idx[ 9]), *(const short*)(tab + idx[10]), *(const short*)(tab + idx[11]), - *(const short*)(tab + idx[12]), *(const short*)(tab + idx[13]), *(const short*)(tab + idx[14]), *(const short*)(tab + idx[15]))); -} -inline v_int8x32 v256_lut_quads(const schar* tab, const int* idx) -{ - return v_int8x32(_mm256_i32gather_epi32((const int*)tab, _mm256_loadu_si256((const __m256i*)idx), 1)); -} -inline v_uint8x32 v256_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v256_lut((const schar *)tab, idx)); } -inline v_uint8x32 v256_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v256_lut_pairs((const schar *)tab, idx)); } -inline v_uint8x32 v256_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v256_lut_quads((const schar *)tab, idx)); } - -inline v_int16x16 v256_lut(const short* tab, const int* idx) -{ - return v_int16x16(_mm256_setr_epi16(tab[idx[0]], tab[idx[1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], tab[idx[ 5]], tab[idx[ 6]], tab[idx[ 7]], - tab[idx[8]], tab[idx[9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]])); -} -inline v_int16x16 v256_lut_pairs(const short* tab, const int* idx) -{ - return v_int16x16(_mm256_i32gather_epi32((const int*)tab, _mm256_loadu_si256((const __m256i*)idx), 2)); -} -inline v_int16x16 v256_lut_quads(const short* tab, const int* idx) -{ -#if defined(__GNUC__) - return v_int16x16(_mm256_i32gather_epi64((const long long int*)tab, _mm_loadu_si128((const __m128i*)idx), 2));//Looks like intrinsic has wrong definition -#else - return v_int16x16(_mm256_i32gather_epi64((const int64*)tab, _mm_loadu_si128((const __m128i*)idx), 2)); -#endif -} -inline v_uint16x16 v256_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v256_lut((const short *)tab, idx)); } -inline v_uint16x16 v256_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v256_lut_pairs((const short *)tab, idx)); } -inline v_uint16x16 v256_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v256_lut_quads((const short *)tab, idx)); } - -inline v_int32x8 v256_lut(const int* tab, const int* idx) -{ - return v_int32x8(_mm256_i32gather_epi32(tab, _mm256_loadu_si256((const __m256i*)idx), 4)); -} -inline v_int32x8 v256_lut_pairs(const int* tab, const int* idx) -{ -#if defined(__GNUC__) - return v_int32x8(_mm256_i32gather_epi64((const long long int*)tab, _mm_loadu_si128((const __m128i*)idx), 4)); -#else - return v_int32x8(_mm256_i32gather_epi64((const int64*)tab, _mm_loadu_si128((const __m128i*)idx), 4)); -#endif -} -inline v_int32x8 v256_lut_quads(const int* tab, const int* idx) -{ - return v_int32x8(_v256_combine(_mm_loadu_si128((const __m128i*)(tab + idx[0])), _mm_loadu_si128((const __m128i*)(tab + idx[1])))); -} -inline v_uint32x8 v256_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v256_lut((const int *)tab, idx)); } -inline v_uint32x8 v256_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v256_lut_pairs((const int *)tab, idx)); } -inline v_uint32x8 v256_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v256_lut_quads((const int *)tab, idx)); } - -inline v_int64x4 v256_lut(const int64* tab, const int* idx) -{ -#if defined(__GNUC__) - return v_int64x4(_mm256_i32gather_epi64((const long long int*)tab, _mm_loadu_si128((const __m128i*)idx), 8)); -#else - return v_int64x4(_mm256_i32gather_epi64(tab, _mm_loadu_si128((const __m128i*)idx), 8)); -#endif -} -inline v_int64x4 v256_lut_pairs(const int64* tab, const int* idx) -{ - return v_int64x4(_v256_combine(_mm_loadu_si128((const __m128i*)(tab + idx[0])), _mm_loadu_si128((const __m128i*)(tab + idx[1])))); -} -inline v_uint64x4 v256_lut(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v256_lut((const int64 *)tab, idx)); } -inline v_uint64x4 v256_lut_pairs(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v256_lut_pairs((const int64 *)tab, idx)); } - -inline v_float32x8 v256_lut(const float* tab, const int* idx) -{ - return v_float32x8(_mm256_i32gather_ps(tab, _mm256_loadu_si256((const __m256i*)idx), 4)); -} -inline v_float32x8 v256_lut_pairs(const float* tab, const int* idx) { return v_reinterpret_as_f32(v256_lut_pairs((const int *)tab, idx)); } -inline v_float32x8 v256_lut_quads(const float* tab, const int* idx) { return v_reinterpret_as_f32(v256_lut_quads((const int *)tab, idx)); } - -inline v_float64x4 v256_lut(const double* tab, const int* idx) -{ - return v_float64x4(_mm256_i32gather_pd(tab, _mm_loadu_si128((const __m128i*)idx), 8)); -} -inline v_float64x4 v256_lut_pairs(const double* tab, const int* idx) { return v_float64x4(_v256_combine(_mm_loadu_pd(tab + idx[0]), _mm_loadu_pd(tab + idx[1]))); } - -inline v_int32x8 v_lut(const int* tab, const v_int32x8& idxvec) -{ - return v_int32x8(_mm256_i32gather_epi32(tab, idxvec.val, 4)); -} - -inline v_uint32x8 v_lut(const unsigned* tab, const v_int32x8& idxvec) -{ - return v_reinterpret_as_u32(v_lut((const int *)tab, idxvec)); -} - -inline v_float32x8 v_lut(const float* tab, const v_int32x8& idxvec) -{ - return v_float32x8(_mm256_i32gather_ps(tab, idxvec.val, 4)); -} - -inline v_float64x4 v_lut(const double* tab, const v_int32x8& idxvec) -{ - return v_float64x4(_mm256_i32gather_pd(tab, _mm256_castsi256_si128(idxvec.val), 8)); -} - -inline void v_lut_deinterleave(const float* tab, const v_int32x8& idxvec, v_float32x8& x, v_float32x8& y) -{ - int CV_DECL_ALIGNED(32) idx[8]; - v_store_aligned(idx, idxvec); - __m128 z = _mm_setzero_ps(); - __m128 xy01, xy45, xy23, xy67; - xy01 = _mm_loadl_pi(z, (const __m64*)(tab + idx[0])); - xy01 = _mm_loadh_pi(xy01, (const __m64*)(tab + idx[1])); - xy45 = _mm_loadl_pi(z, (const __m64*)(tab + idx[4])); - xy45 = _mm_loadh_pi(xy45, (const __m64*)(tab + idx[5])); - __m256 xy0145 = _v256_combine(xy01, xy45); - xy23 = _mm_loadl_pi(z, (const __m64*)(tab + idx[2])); - xy23 = _mm_loadh_pi(xy23, (const __m64*)(tab + idx[3])); - xy67 = _mm_loadl_pi(z, (const __m64*)(tab + idx[6])); - xy67 = _mm_loadh_pi(xy67, (const __m64*)(tab + idx[7])); - __m256 xy2367 = _v256_combine(xy23, xy67); - - __m256 xxyy0145 = _mm256_unpacklo_ps(xy0145, xy2367); - __m256 xxyy2367 = _mm256_unpackhi_ps(xy0145, xy2367); - - x = v_float32x8(_mm256_unpacklo_ps(xxyy0145, xxyy2367)); - y = v_float32x8(_mm256_unpackhi_ps(xxyy0145, xxyy2367)); -} - -inline void v_lut_deinterleave(const double* tab, const v_int32x8& idxvec, v_float64x4& x, v_float64x4& y) -{ - int CV_DECL_ALIGNED(32) idx[4]; - v_store_low(idx, idxvec); - __m128d xy0 = _mm_loadu_pd(tab + idx[0]); - __m128d xy2 = _mm_loadu_pd(tab + idx[2]); - __m128d xy1 = _mm_loadu_pd(tab + idx[1]); - __m128d xy3 = _mm_loadu_pd(tab + idx[3]); - __m256d xy02 = _v256_combine(xy0, xy2); - __m256d xy13 = _v256_combine(xy1, xy3); - - x = v_float64x4(_mm256_unpacklo_pd(xy02, xy13)); - y = v_float64x4(_mm256_unpackhi_pd(xy02, xy13)); -} - -inline v_int8x32 v_interleave_pairs(const v_int8x32& vec) -{ - return v_int8x32(_mm256_shuffle_epi8(vec.val, _mm256_set_epi64x(0x0f0d0e0c0b090a08, 0x0705060403010200, 0x0f0d0e0c0b090a08, 0x0705060403010200))); -} -inline v_uint8x32 v_interleave_pairs(const v_uint8x32& vec) { return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } -inline v_int8x32 v_interleave_quads(const v_int8x32& vec) -{ - return v_int8x32(_mm256_shuffle_epi8(vec.val, _mm256_set_epi64x(0x0f0b0e0a0d090c08, 0x0703060205010400, 0x0f0b0e0a0d090c08, 0x0703060205010400))); -} -inline v_uint8x32 v_interleave_quads(const v_uint8x32& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } - -inline v_int16x16 v_interleave_pairs(const v_int16x16& vec) -{ - return v_int16x16(_mm256_shuffle_epi8(vec.val, _mm256_set_epi64x(0x0f0e0b0a0d0c0908, 0x0706030205040100, 0x0f0e0b0a0d0c0908, 0x0706030205040100))); -} -inline v_uint16x16 v_interleave_pairs(const v_uint16x16& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } -inline v_int16x16 v_interleave_quads(const v_int16x16& vec) -{ - return v_int16x16(_mm256_shuffle_epi8(vec.val, _mm256_set_epi64x(0x0f0e07060d0c0504, 0x0b0a030209080100, 0x0f0e07060d0c0504, 0x0b0a030209080100))); -} -inline v_uint16x16 v_interleave_quads(const v_uint16x16& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } - -inline v_int32x8 v_interleave_pairs(const v_int32x8& vec) -{ - return v_int32x8(_mm256_shuffle_epi32(vec.val, _MM_SHUFFLE(3, 1, 2, 0))); -} -inline v_uint32x8 v_interleave_pairs(const v_uint32x8& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } -inline v_float32x8 v_interleave_pairs(const v_float32x8& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } - -inline v_int8x32 v_pack_triplets(const v_int8x32& vec) -{ - return v_int8x32(_mm256_permutevar8x32_epi32(_mm256_shuffle_epi8(vec.val, _mm256_broadcastsi128_si256(_mm_set_epi64x(0xffffff0f0e0d0c0a, 0x0908060504020100))), - _mm256_set_epi64x(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); -} -inline v_uint8x32 v_pack_triplets(const v_uint8x32& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } - -inline v_int16x16 v_pack_triplets(const v_int16x16& vec) -{ - return v_int16x16(_mm256_permutevar8x32_epi32(_mm256_shuffle_epi8(vec.val, _mm256_broadcastsi128_si256(_mm_set_epi64x(0xffff0f0e0d0c0b0a, 0x0908050403020100))), - _mm256_set_epi64x(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); -} -inline v_uint16x16 v_pack_triplets(const v_uint16x16& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } - -inline v_int32x8 v_pack_triplets(const v_int32x8& vec) -{ - return v_int32x8(_mm256_permutevar8x32_epi32(vec.val, _mm256_set_epi64x(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); -} -inline v_uint32x8 v_pack_triplets(const v_uint32x8& vec) { return v_reinterpret_as_u32(v_pack_triplets(v_reinterpret_as_s32(vec))); } -inline v_float32x8 v_pack_triplets(const v_float32x8& vec) -{ - return v_float32x8(_mm256_permutevar8x32_ps(vec.val, _mm256_set_epi64x(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); -} - -////////// Matrix operations ///////// - -//////// Dot Product //////// - -// 16 >> 32 -inline v_int32x8 v_dotprod(const v_int16x16& a, const v_int16x16& b) -{ return v_int32x8(_mm256_madd_epi16(a.val, b.val)); } -inline v_int32x8 v_dotprod(const v_int16x16& a, const v_int16x16& b, const v_int32x8& c) -{ return v_add(v_dotprod(a, b), c); } - -// 32 >> 64 -inline v_int64x4 v_dotprod(const v_int32x8& a, const v_int32x8& b) -{ - __m256i even = _mm256_mul_epi32(a.val, b.val); - __m256i odd = _mm256_mul_epi32(_mm256_srli_epi64(a.val, 32), _mm256_srli_epi64(b.val, 32)); - return v_int64x4(_mm256_add_epi64(even, odd)); -} -inline v_int64x4 v_dotprod(const v_int32x8& a, const v_int32x8& b, const v_int64x4& c) -{ return v_add(v_dotprod(a, b), c); } - -// 8 >> 32 -inline v_uint32x8 v_dotprod_expand(const v_uint8x32& a, const v_uint8x32& b) -{ - __m256i even_m = _mm256_set1_epi32(0xFF00FF00); - __m256i even_a = _mm256_blendv_epi8(a.val, _mm256_setzero_si256(), even_m); - __m256i odd_a = _mm256_srli_epi16(a.val, 8); - - __m256i even_b = _mm256_blendv_epi8(b.val, _mm256_setzero_si256(), even_m); - __m256i odd_b = _mm256_srli_epi16(b.val, 8); - - __m256i prod0 = _mm256_madd_epi16(even_a, even_b); - __m256i prod1 = _mm256_madd_epi16(odd_a, odd_b); - return v_uint32x8(_mm256_add_epi32(prod0, prod1)); -} -inline v_uint32x8 v_dotprod_expand(const v_uint8x32& a, const v_uint8x32& b, const v_uint32x8& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int32x8 v_dotprod_expand(const v_int8x32& a, const v_int8x32& b) -{ - __m256i even_a = _mm256_srai_epi16(_mm256_bslli_epi128(a.val, 1), 8); - __m256i odd_a = _mm256_srai_epi16(a.val, 8); - - __m256i even_b = _mm256_srai_epi16(_mm256_bslli_epi128(b.val, 1), 8); - __m256i odd_b = _mm256_srai_epi16(b.val, 8); - - __m256i prod0 = _mm256_madd_epi16(even_a, even_b); - __m256i prod1 = _mm256_madd_epi16(odd_a, odd_b); - return v_int32x8(_mm256_add_epi32(prod0, prod1)); -} -inline v_int32x8 v_dotprod_expand(const v_int8x32& a, const v_int8x32& b, const v_int32x8& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 16 >> 64 -inline v_uint64x4 v_dotprod_expand(const v_uint16x16& a, const v_uint16x16& b) -{ - __m256i mullo = _mm256_mullo_epi16(a.val, b.val); - __m256i mulhi = _mm256_mulhi_epu16(a.val, b.val); - __m256i mul0 = _mm256_unpacklo_epi16(mullo, mulhi); - __m256i mul1 = _mm256_unpackhi_epi16(mullo, mulhi); - - __m256i p02 = _mm256_blend_epi32(mul0, _mm256_setzero_si256(), 0xAA); - __m256i p13 = _mm256_srli_epi64(mul0, 32); - __m256i p46 = _mm256_blend_epi32(mul1, _mm256_setzero_si256(), 0xAA); - __m256i p57 = _mm256_srli_epi64(mul1, 32); - - __m256i p15_ = _mm256_add_epi64(p02, p13); - __m256i p9d_ = _mm256_add_epi64(p46, p57); - - return v_uint64x4(_mm256_add_epi64( - _mm256_unpacklo_epi64(p15_, p9d_), - _mm256_unpackhi_epi64(p15_, p9d_) - )); -} -inline v_uint64x4 v_dotprod_expand(const v_uint16x16& a, const v_uint16x16& b, const v_uint64x4& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int64x4 v_dotprod_expand(const v_int16x16& a, const v_int16x16& b) -{ - __m256i prod = _mm256_madd_epi16(a.val, b.val); - __m256i sign = _mm256_srai_epi32(prod, 31); - - __m256i lo = _mm256_unpacklo_epi32(prod, sign); - __m256i hi = _mm256_unpackhi_epi32(prod, sign); - - return v_int64x4(_mm256_add_epi64( - _mm256_unpacklo_epi64(lo, hi), - _mm256_unpackhi_epi64(lo, hi) - )); -} -inline v_int64x4 v_dotprod_expand(const v_int16x16& a, const v_int16x16& b, const v_int64x4& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 32 >> 64f -inline v_float64x4 v_dotprod_expand(const v_int32x8& a, const v_int32x8& b) -{ return v_cvt_f64(v_dotprod(a, b)); } -inline v_float64x4 v_dotprod_expand(const v_int32x8& a, const v_int32x8& b, const v_float64x4& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -//////// Fast Dot Product //////// - -// 16 >> 32 -inline v_int32x8 v_dotprod_fast(const v_int16x16& a, const v_int16x16& b) -{ return v_dotprod(a, b); } -inline v_int32x8 v_dotprod_fast(const v_int16x16& a, const v_int16x16& b, const v_int32x8& c) -{ return v_dotprod(a, b, c); } - -// 32 >> 64 -inline v_int64x4 v_dotprod_fast(const v_int32x8& a, const v_int32x8& b) -{ return v_dotprod(a, b); } -inline v_int64x4 v_dotprod_fast(const v_int32x8& a, const v_int32x8& b, const v_int64x4& c) -{ return v_dotprod(a, b, c); } - -// 8 >> 32 -inline v_uint32x8 v_dotprod_expand_fast(const v_uint8x32& a, const v_uint8x32& b) -{ return v_dotprod_expand(a, b); } -inline v_uint32x8 v_dotprod_expand_fast(const v_uint8x32& a, const v_uint8x32& b, const v_uint32x8& c) -{ return v_dotprod_expand(a, b, c); } - -inline v_int32x8 v_dotprod_expand_fast(const v_int8x32& a, const v_int8x32& b) -{ return v_dotprod_expand(a, b); } -inline v_int32x8 v_dotprod_expand_fast(const v_int8x32& a, const v_int8x32& b, const v_int32x8& c) -{ return v_dotprod_expand(a, b, c); } - -// 16 >> 64 -inline v_uint64x4 v_dotprod_expand_fast(const v_uint16x16& a, const v_uint16x16& b) -{ - __m256i mullo = _mm256_mullo_epi16(a.val, b.val); - __m256i mulhi = _mm256_mulhi_epu16(a.val, b.val); - __m256i mul0 = _mm256_unpacklo_epi16(mullo, mulhi); - __m256i mul1 = _mm256_unpackhi_epi16(mullo, mulhi); - - __m256i p02 = _mm256_blend_epi32(mul0, _mm256_setzero_si256(), 0xAA); - __m256i p13 = _mm256_srli_epi64(mul0, 32); - __m256i p46 = _mm256_blend_epi32(mul1, _mm256_setzero_si256(), 0xAA); - __m256i p57 = _mm256_srli_epi64(mul1, 32); - - __m256i p15_ = _mm256_add_epi64(p02, p13); - __m256i p9d_ = _mm256_add_epi64(p46, p57); - - return v_uint64x4(_mm256_add_epi64(p15_, p9d_)); -} -inline v_uint64x4 v_dotprod_expand_fast(const v_uint16x16& a, const v_uint16x16& b, const v_uint64x4& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -inline v_int64x4 v_dotprod_expand_fast(const v_int16x16& a, const v_int16x16& b) -{ - __m256i prod = _mm256_madd_epi16(a.val, b.val); - __m256i sign = _mm256_srai_epi32(prod, 31); - __m256i lo = _mm256_unpacklo_epi32(prod, sign); - __m256i hi = _mm256_unpackhi_epi32(prod, sign); - return v_int64x4(_mm256_add_epi64(lo, hi)); -} -inline v_int64x4 v_dotprod_expand_fast(const v_int16x16& a, const v_int16x16& b, const v_int64x4& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -// 32 >> 64f -inline v_float64x4 v_dotprod_expand_fast(const v_int32x8& a, const v_int32x8& b) -{ return v_dotprod_expand(a, b); } -inline v_float64x4 v_dotprod_expand_fast(const v_int32x8& a, const v_int32x8& b, const v_float64x4& c) -{ return v_dotprod_expand(a, b, c); } - -#define OPENCV_HAL_AVX_SPLAT2_PS(a, im) \ - v_float32x8(_mm256_permute_ps(a.val, _MM_SHUFFLE(im, im, im, im))) - -inline v_float32x8 v_matmul(const v_float32x8& v, const v_float32x8& m0, - const v_float32x8& m1, const v_float32x8& m2, - const v_float32x8& m3) -{ - v_float32x8 v04 = OPENCV_HAL_AVX_SPLAT2_PS(v, 0); - v_float32x8 v15 = OPENCV_HAL_AVX_SPLAT2_PS(v, 1); - v_float32x8 v26 = OPENCV_HAL_AVX_SPLAT2_PS(v, 2); - v_float32x8 v37 = OPENCV_HAL_AVX_SPLAT2_PS(v, 3); - return v_fma(v04, m0, v_fma(v15, m1, v_fma(v26, m2, v_mul(v37, m3)))); -} - -inline v_float32x8 v_matmuladd(const v_float32x8& v, const v_float32x8& m0, - const v_float32x8& m1, const v_float32x8& m2, - const v_float32x8& a) -{ - v_float32x8 v04 = OPENCV_HAL_AVX_SPLAT2_PS(v, 0); - v_float32x8 v15 = OPENCV_HAL_AVX_SPLAT2_PS(v, 1); - v_float32x8 v26 = OPENCV_HAL_AVX_SPLAT2_PS(v, 2); - return v_fma(v04, m0, v_fma(v15, m1, v_fma(v26, m2, a))); -} - -#define OPENCV_HAL_IMPL_AVX_TRANSPOSE4x4(_Tpvec, suffix, cast_from, cast_to) \ - inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ - const _Tpvec& a2, const _Tpvec& a3, \ - _Tpvec& b0, _Tpvec& b1, _Tpvec& b2, _Tpvec& b3) \ - { \ - __m256i t0 = cast_from(_mm256_unpacklo_##suffix(a0.val, a1.val)); \ - __m256i t1 = cast_from(_mm256_unpacklo_##suffix(a2.val, a3.val)); \ - __m256i t2 = cast_from(_mm256_unpackhi_##suffix(a0.val, a1.val)); \ - __m256i t3 = cast_from(_mm256_unpackhi_##suffix(a2.val, a3.val)); \ - b0.val = cast_to(_mm256_unpacklo_epi64(t0, t1)); \ - b1.val = cast_to(_mm256_unpackhi_epi64(t0, t1)); \ - b2.val = cast_to(_mm256_unpacklo_epi64(t2, t3)); \ - b3.val = cast_to(_mm256_unpackhi_epi64(t2, t3)); \ - } - -OPENCV_HAL_IMPL_AVX_TRANSPOSE4x4(v_uint32x8, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_AVX_TRANSPOSE4x4(v_int32x8, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_AVX_TRANSPOSE4x4(v_float32x8, ps, _mm256_castps_si256, _mm256_castsi256_ps) - -//////////////// Value reordering /////////////// - -/* Expand */ -#define OPENCV_HAL_IMPL_AVX_EXPAND(_Tpvec, _Tpwvec, _Tp, intrin) \ - inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ - { \ - b0.val = intrin(_v256_extract_low(a.val)); \ - b1.val = intrin(_v256_extract_high(a.val)); \ - } \ - inline _Tpwvec v_expand_low(const _Tpvec& a) \ - { return _Tpwvec(intrin(_v256_extract_low(a.val))); } \ - inline _Tpwvec v_expand_high(const _Tpvec& a) \ - { return _Tpwvec(intrin(_v256_extract_high(a.val))); } \ - inline _Tpwvec v256_load_expand(const _Tp* ptr) \ - { \ - __m128i a = _mm_loadu_si128((const __m128i*)ptr); \ - return _Tpwvec(intrin(a)); \ - } - -OPENCV_HAL_IMPL_AVX_EXPAND(v_uint8x32, v_uint16x16, uchar, _mm256_cvtepu8_epi16) -OPENCV_HAL_IMPL_AVX_EXPAND(v_int8x32, v_int16x16, schar, _mm256_cvtepi8_epi16) -OPENCV_HAL_IMPL_AVX_EXPAND(v_uint16x16, v_uint32x8, ushort, _mm256_cvtepu16_epi32) -OPENCV_HAL_IMPL_AVX_EXPAND(v_int16x16, v_int32x8, short, _mm256_cvtepi16_epi32) -OPENCV_HAL_IMPL_AVX_EXPAND(v_uint32x8, v_uint64x4, unsigned, _mm256_cvtepu32_epi64) -OPENCV_HAL_IMPL_AVX_EXPAND(v_int32x8, v_int64x4, int, _mm256_cvtepi32_epi64) - -#define OPENCV_HAL_IMPL_AVX_EXPAND_Q(_Tpvec, _Tp, intrin) \ - inline _Tpvec v256_load_expand_q(const _Tp* ptr) \ - { \ - __m128i a = _mm_loadl_epi64((const __m128i*)ptr); \ - return _Tpvec(intrin(a)); \ - } - -OPENCV_HAL_IMPL_AVX_EXPAND_Q(v_uint32x8, uchar, _mm256_cvtepu8_epi32) -OPENCV_HAL_IMPL_AVX_EXPAND_Q(v_int32x8, schar, _mm256_cvtepi8_epi32) - -/* pack */ -// 16 -inline v_int8x32 v_pack(const v_int16x16& a, const v_int16x16& b) -{ return v_int8x32(_v256_shuffle_odd_64(_mm256_packs_epi16(a.val, b.val))); } - -inline v_uint8x32 v_pack(const v_uint16x16& a, const v_uint16x16& b) -{ - __m256i t = _mm256_set1_epi16(255); - __m256i a1 = _mm256_min_epu16(a.val, t); - __m256i b1 = _mm256_min_epu16(b.val, t); - return v_uint8x32(_v256_shuffle_odd_64(_mm256_packus_epi16(a1, b1))); -} - -inline v_uint8x32 v_pack_u(const v_int16x16& a, const v_int16x16& b) -{ - return v_uint8x32(_v256_shuffle_odd_64(_mm256_packus_epi16(a.val, b.val))); -} - -inline void v_pack_store(schar* ptr, const v_int16x16& a) -{ v_store_low(ptr, v_pack(a, a)); } - -inline void v_pack_store(uchar* ptr, const v_uint16x16& a) -{ - const __m256i m = _mm256_set1_epi16(255); - __m256i am = _mm256_min_epu16(a.val, m); - am = _v256_shuffle_odd_64(_mm256_packus_epi16(am, am)); - v_store_low(ptr, v_uint8x32(am)); -} - -inline void v_pack_u_store(uchar* ptr, const v_int16x16& a) -{ v_store_low(ptr, v_pack_u(a, a)); } - -template inline -v_uint8x32 v_rshr_pack(const v_uint16x16& a, const v_uint16x16& b) -{ - // we assume that n > 0, and so the shifted 16-bit values can be treated as signed numbers. - v_uint16x16 delta = v256_setall_u16((short)(1 << (n-1))); - return v_pack_u(v_reinterpret_as_s16(v_shr(v_add(a, delta), n)), - v_reinterpret_as_s16(v_shr(v_add(b, delta), n))); -} - -template inline -void v_rshr_pack_store(uchar* ptr, const v_uint16x16& a) -{ - v_uint16x16 delta = v256_setall_u16((short)(1 << (n-1))); - v_pack_u_store(ptr, v_reinterpret_as_s16(v_shr(v_add(a, delta), n))); -} - -template inline -v_uint8x32 v_rshr_pack_u(const v_int16x16& a, const v_int16x16& b) -{ - v_int16x16 delta = v256_setall_s16((short)(1 << (n-1))); - return v_pack_u(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); -} - -template inline -void v_rshr_pack_u_store(uchar* ptr, const v_int16x16& a) -{ - v_int16x16 delta = v256_setall_s16((short)(1 << (n-1))); - v_pack_u_store(ptr, v_shr(v_add(a, delta), n)); -} - -template inline -v_int8x32 v_rshr_pack(const v_int16x16& a, const v_int16x16& b) -{ - v_int16x16 delta = v256_setall_s16((short)(1 << (n-1))); - return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); -} - -template inline -void v_rshr_pack_store(schar* ptr, const v_int16x16& a) -{ - v_int16x16 delta = v256_setall_s16((short)(1 << (n-1))); - v_pack_store(ptr, v_shr(v_add(a, delta), n)); -} - -// 32 -inline v_int16x16 v_pack(const v_int32x8& a, const v_int32x8& b) -{ return v_int16x16(_v256_shuffle_odd_64(_mm256_packs_epi32(a.val, b.val))); } - -inline v_uint16x16 v_pack(const v_uint32x8& a, const v_uint32x8& b) -{ return v_uint16x16(_v256_shuffle_odd_64(_v256_packs_epu32(a.val, b.val))); } - -inline v_uint16x16 v_pack_u(const v_int32x8& a, const v_int32x8& b) -{ return v_uint16x16(_v256_shuffle_odd_64(_mm256_packus_epi32(a.val, b.val))); } - -inline void v_pack_store(short* ptr, const v_int32x8& a) -{ v_store_low(ptr, v_pack(a, a)); } - -inline void v_pack_store(ushort* ptr, const v_uint32x8& a) -{ - const __m256i m = _mm256_set1_epi32(65535); - __m256i am = _mm256_min_epu32(a.val, m); - am = _v256_shuffle_odd_64(_mm256_packus_epi32(am, am)); - v_store_low(ptr, v_uint16x16(am)); -} - -inline void v_pack_u_store(ushort* ptr, const v_int32x8& a) -{ v_store_low(ptr, v_pack_u(a, a)); } - - -template inline -v_uint16x16 v_rshr_pack(const v_uint32x8& a, const v_uint32x8& b) -{ - // we assume that n > 0, and so the shifted 32-bit values can be treated as signed numbers. - v_uint32x8 delta = v256_setall_u32(1 << (n-1)); - return v_pack_u(v_reinterpret_as_s32(v_shr(v_add(a, delta), n)), - v_reinterpret_as_s32(v_shr(v_add(b, delta), n))); -} - -template inline -void v_rshr_pack_store(ushort* ptr, const v_uint32x8& a) -{ - v_uint32x8 delta = v256_setall_u32(1 << (n-1)); - v_pack_u_store(ptr, v_reinterpret_as_s32(v_shr(v_add(a, delta), n))); -} - -template inline -v_uint16x16 v_rshr_pack_u(const v_int32x8& a, const v_int32x8& b) -{ - v_int32x8 delta = v256_setall_s32(1 << (n-1)); - return v_pack_u(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); -} - -template inline -void v_rshr_pack_u_store(ushort* ptr, const v_int32x8& a) -{ - v_int32x8 delta = v256_setall_s32(1 << (n-1)); - v_pack_u_store(ptr, v_shr(v_add(a, delta), n)); -} - -template inline -v_int16x16 v_rshr_pack(const v_int32x8& a, const v_int32x8& b) -{ - v_int32x8 delta = v256_setall_s32(1 << (n-1)); - return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); -} - -template inline -void v_rshr_pack_store(short* ptr, const v_int32x8& a) -{ - v_int32x8 delta = v256_setall_s32(1 << (n-1)); - v_pack_store(ptr, v_shr(v_add(a, delta), n)); -} - -// 64 -// Non-saturating pack -inline v_uint32x8 v_pack(const v_uint64x4& a, const v_uint64x4& b) -{ - __m256i a0 = _mm256_shuffle_epi32(a.val, _MM_SHUFFLE(0, 0, 2, 0)); - __m256i b0 = _mm256_shuffle_epi32(b.val, _MM_SHUFFLE(0, 0, 2, 0)); - __m256i ab = _mm256_unpacklo_epi64(a0, b0); // a0, a1, b0, b1, a2, a3, b2, b3 - return v_uint32x8(_v256_shuffle_odd_64(ab)); -} - -inline v_int32x8 v_pack(const v_int64x4& a, const v_int64x4& b) -{ return v_reinterpret_as_s32(v_pack(v_reinterpret_as_u64(a), v_reinterpret_as_u64(b))); } - -inline void v_pack_store(unsigned* ptr, const v_uint64x4& a) -{ - __m256i a0 = _mm256_shuffle_epi32(a.val, _MM_SHUFFLE(0, 0, 2, 0)); - v_store_low(ptr, v_uint32x8(_v256_shuffle_odd_64(a0))); -} - -inline void v_pack_store(int* ptr, const v_int64x4& b) -{ v_pack_store((unsigned*)ptr, v_reinterpret_as_u64(b)); } - -template inline -v_uint32x8 v_rshr_pack(const v_uint64x4& a, const v_uint64x4& b) -{ - v_uint64x4 delta = v256_setall_u64((uint64)1 << (n-1)); - return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); -} - -template inline -void v_rshr_pack_store(unsigned* ptr, const v_uint64x4& a) -{ - v_uint64x4 delta = v256_setall_u64((uint64)1 << (n-1)); - v_pack_store(ptr, v_shr(v_add(a, delta), n)); -} - -template inline -v_int32x8 v_rshr_pack(const v_int64x4& a, const v_int64x4& b) -{ - v_int64x4 delta = v256_setall_s64((int64)1 << (n-1)); - return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); -} - -template inline -void v_rshr_pack_store(int* ptr, const v_int64x4& a) -{ - v_int64x4 delta = v256_setall_s64((int64)1 << (n-1)); - v_pack_store(ptr, v_shr(v_add(a, delta), n)); -} - -// pack boolean -inline v_uint8x32 v_pack_b(const v_uint16x16& a, const v_uint16x16& b) -{ - __m256i ab = _mm256_packs_epi16(a.val, b.val); - return v_uint8x32(_v256_shuffle_odd_64(ab)); -} - -inline v_uint8x32 v_pack_b(const v_uint32x8& a, const v_uint32x8& b, - const v_uint32x8& c, const v_uint32x8& d) -{ - __m256i ab = _mm256_packs_epi32(a.val, b.val); - __m256i cd = _mm256_packs_epi32(c.val, d.val); - - __m256i abcd = _v256_shuffle_odd_64(_mm256_packs_epi16(ab, cd)); - return v_uint8x32(_mm256_shuffle_epi32(abcd, _MM_SHUFFLE(3, 1, 2, 0))); -} - -inline v_uint8x32 v_pack_b(const v_uint64x4& a, const v_uint64x4& b, const v_uint64x4& c, - const v_uint64x4& d, const v_uint64x4& e, const v_uint64x4& f, - const v_uint64x4& g, const v_uint64x4& h) -{ - __m256i ab = _mm256_packs_epi32(a.val, b.val); - __m256i cd = _mm256_packs_epi32(c.val, d.val); - __m256i ef = _mm256_packs_epi32(e.val, f.val); - __m256i gh = _mm256_packs_epi32(g.val, h.val); - - __m256i abcd = _mm256_packs_epi32(ab, cd); - __m256i efgh = _mm256_packs_epi32(ef, gh); - __m256i pkall = _v256_shuffle_odd_64(_mm256_packs_epi16(abcd, efgh)); - - __m256i rev = _mm256_alignr_epi8(pkall, pkall, 8); - return v_uint8x32(_mm256_unpacklo_epi16(pkall, rev)); -} - -/* Recombine */ -// its up there with load and store operations - -/* Extract */ -#define OPENCV_HAL_IMPL_AVX_EXTRACT(_Tpvec) \ - template \ - inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \ - { return v_rotate_right(a, b); } - -OPENCV_HAL_IMPL_AVX_EXTRACT(v_uint8x32) -OPENCV_HAL_IMPL_AVX_EXTRACT(v_int8x32) -OPENCV_HAL_IMPL_AVX_EXTRACT(v_uint16x16) -OPENCV_HAL_IMPL_AVX_EXTRACT(v_int16x16) -OPENCV_HAL_IMPL_AVX_EXTRACT(v_uint32x8) -OPENCV_HAL_IMPL_AVX_EXTRACT(v_int32x8) -OPENCV_HAL_IMPL_AVX_EXTRACT(v_uint64x4) -OPENCV_HAL_IMPL_AVX_EXTRACT(v_int64x4) -OPENCV_HAL_IMPL_AVX_EXTRACT(v_float32x8) -OPENCV_HAL_IMPL_AVX_EXTRACT(v_float64x4) - -template -inline uchar v_extract_n(v_uint8x32 a) -{ - return (uchar)_v256_extract_epi8(a.val); -} - -template -inline schar v_extract_n(v_int8x32 a) -{ - return (schar)v_extract_n(v_reinterpret_as_u8(a)); -} - -template -inline ushort v_extract_n(v_uint16x16 a) -{ - return (ushort)_v256_extract_epi16(a.val); -} - -template -inline short v_extract_n(v_int16x16 a) -{ - return (short)v_extract_n(v_reinterpret_as_u16(a)); -} - -template -inline uint v_extract_n(v_uint32x8 a) -{ - return (uint)_v256_extract_epi32(a.val); -} - -template -inline int v_extract_n(v_int32x8 a) -{ - return (int)v_extract_n(v_reinterpret_as_u32(a)); -} - -template -inline uint64 v_extract_n(v_uint64x4 a) -{ - return (uint64)_v256_extract_epi64(a.val); -} - -template -inline int64 v_extract_n(v_int64x4 v) -{ - return (int64)v_extract_n(v_reinterpret_as_u64(v)); -} - -template -inline float v_extract_n(v_float32x8 v) -{ - union { uint iv; float fv; } d; - d.iv = v_extract_n(v_reinterpret_as_u32(v)); - return d.fv; -} - -template -inline double v_extract_n(v_float64x4 v) -{ - union { uint64 iv; double dv; } d; - d.iv = v_extract_n(v_reinterpret_as_u64(v)); - return d.dv; -} - -template -inline v_uint32x8 v_broadcast_element(v_uint32x8 a) -{ - static const __m256i perm = _mm256_set1_epi32((char)i); - return v_uint32x8(_mm256_permutevar8x32_epi32(a.val, perm)); -} - -template -inline v_int32x8 v_broadcast_element(const v_int32x8 &a) -{ return v_reinterpret_as_s32(v_broadcast_element(v_reinterpret_as_u32(a))); } - -template -inline v_float32x8 v_broadcast_element(const v_float32x8 &a) -{ return v_reinterpret_as_f32(v_broadcast_element(v_reinterpret_as_u32(a))); } - - -///////////////////// load deinterleave ///////////////////////////// - -inline void v_load_deinterleave( const uchar* ptr, v_uint8x32& a, v_uint8x32& b ) -{ - __m256i ab0 = _mm256_loadu_si256((const __m256i*)ptr); - __m256i ab1 = _mm256_loadu_si256((const __m256i*)(ptr + 32)); - - const __m256i sh = _mm256_setr_epi8(0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15, - 0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15); - __m256i p0 = _mm256_shuffle_epi8(ab0, sh); - __m256i p1 = _mm256_shuffle_epi8(ab1, sh); - __m256i pl = _mm256_permute2x128_si256(p0, p1, 0 + 2*16); - __m256i ph = _mm256_permute2x128_si256(p0, p1, 1 + 3*16); - __m256i a0 = _mm256_unpacklo_epi64(pl, ph); - __m256i b0 = _mm256_unpackhi_epi64(pl, ph); - a = v_uint8x32(a0); - b = v_uint8x32(b0); -} - -inline void v_load_deinterleave( const ushort* ptr, v_uint16x16& a, v_uint16x16& b ) -{ - __m256i ab0 = _mm256_loadu_si256((const __m256i*)ptr); - __m256i ab1 = _mm256_loadu_si256((const __m256i*)(ptr + 16)); - - const __m256i sh = _mm256_setr_epi8(0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15, - 0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15); - __m256i p0 = _mm256_shuffle_epi8(ab0, sh); - __m256i p1 = _mm256_shuffle_epi8(ab1, sh); - __m256i pl = _mm256_permute2x128_si256(p0, p1, 0 + 2*16); - __m256i ph = _mm256_permute2x128_si256(p0, p1, 1 + 3*16); - __m256i a0 = _mm256_unpacklo_epi64(pl, ph); - __m256i b0 = _mm256_unpackhi_epi64(pl, ph); - a = v_uint16x16(a0); - b = v_uint16x16(b0); -} - -inline void v_load_deinterleave( const unsigned* ptr, v_uint32x8& a, v_uint32x8& b ) -{ - __m256i ab0 = _mm256_loadu_si256((const __m256i*)ptr); - __m256i ab1 = _mm256_loadu_si256((const __m256i*)(ptr + 8)); - - enum { sh = 0+2*4+1*16+3*64 }; - __m256i p0 = _mm256_shuffle_epi32(ab0, sh); - __m256i p1 = _mm256_shuffle_epi32(ab1, sh); - __m256i pl = _mm256_permute2x128_si256(p0, p1, 0 + 2*16); - __m256i ph = _mm256_permute2x128_si256(p0, p1, 1 + 3*16); - __m256i a0 = _mm256_unpacklo_epi64(pl, ph); - __m256i b0 = _mm256_unpackhi_epi64(pl, ph); - a = v_uint32x8(a0); - b = v_uint32x8(b0); -} - -inline void v_load_deinterleave( const uint64* ptr, v_uint64x4& a, v_uint64x4& b ) -{ - __m256i ab0 = _mm256_loadu_si256((const __m256i*)ptr); - __m256i ab1 = _mm256_loadu_si256((const __m256i*)(ptr + 4)); - - __m256i pl = _mm256_permute2x128_si256(ab0, ab1, 0 + 2*16); - __m256i ph = _mm256_permute2x128_si256(ab0, ab1, 1 + 3*16); - __m256i a0 = _mm256_unpacklo_epi64(pl, ph); - __m256i b0 = _mm256_unpackhi_epi64(pl, ph); - a = v_uint64x4(a0); - b = v_uint64x4(b0); -} - -inline void v_load_deinterleave( const uchar* ptr, v_uint8x32& a, v_uint8x32& b, v_uint8x32& c ) -{ - __m256i bgr0 = _mm256_loadu_si256((const __m256i*)ptr); - __m256i bgr1 = _mm256_loadu_si256((const __m256i*)(ptr + 32)); - __m256i bgr2 = _mm256_loadu_si256((const __m256i*)(ptr + 64)); - - __m256i s02_low = _mm256_permute2x128_si256(bgr0, bgr2, 0 + 2*16); - __m256i s02_high = _mm256_permute2x128_si256(bgr0, bgr2, 1 + 3*16); - - const __m256i m0 = _mm256_setr_epi8(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, - 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); - const __m256i m1 = _mm256_setr_epi8(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, - -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); - - __m256i b0 = _mm256_blendv_epi8(_mm256_blendv_epi8(s02_low, s02_high, m0), bgr1, m1); - __m256i g0 = _mm256_blendv_epi8(_mm256_blendv_epi8(s02_high, s02_low, m1), bgr1, m0); - __m256i r0 = _mm256_blendv_epi8(_mm256_blendv_epi8(bgr1, s02_low, m0), s02_high, m1); - - const __m256i - sh_b = _mm256_setr_epi8(0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13, - 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13), - sh_g = _mm256_setr_epi8(1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, - 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14), - sh_r = _mm256_setr_epi8(2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, - 2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15); - b0 = _mm256_shuffle_epi8(b0, sh_b); - g0 = _mm256_shuffle_epi8(g0, sh_g); - r0 = _mm256_shuffle_epi8(r0, sh_r); - - a = v_uint8x32(b0); - b = v_uint8x32(g0); - c = v_uint8x32(r0); -} - -inline void v_load_deinterleave( const ushort* ptr, v_uint16x16& a, v_uint16x16& b, v_uint16x16& c ) -{ - __m256i bgr0 = _mm256_loadu_si256((const __m256i*)ptr); - __m256i bgr1 = _mm256_loadu_si256((const __m256i*)(ptr + 16)); - __m256i bgr2 = _mm256_loadu_si256((const __m256i*)(ptr + 32)); - - __m256i s02_low = _mm256_permute2x128_si256(bgr0, bgr2, 0 + 2*16); - __m256i s02_high = _mm256_permute2x128_si256(bgr0, bgr2, 1 + 3*16); - - const __m256i m0 = _mm256_setr_epi8(0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, - 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0); - const __m256i m1 = _mm256_setr_epi8(0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, - -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0); - __m256i b0 = _mm256_blendv_epi8(_mm256_blendv_epi8(s02_low, s02_high, m0), bgr1, m1); - __m256i g0 = _mm256_blendv_epi8(_mm256_blendv_epi8(bgr1, s02_low, m0), s02_high, m1); - __m256i r0 = _mm256_blendv_epi8(_mm256_blendv_epi8(s02_high, s02_low, m1), bgr1, m0); - const __m256i sh_b = _mm256_setr_epi8(0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, - 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11); - const __m256i sh_g = _mm256_setr_epi8(2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, - 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 0, 1, 6, 7, 12, 13); - const __m256i sh_r = _mm256_setr_epi8(4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, - 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15); - b0 = _mm256_shuffle_epi8(b0, sh_b); - g0 = _mm256_shuffle_epi8(g0, sh_g); - r0 = _mm256_shuffle_epi8(r0, sh_r); - - a = v_uint16x16(b0); - b = v_uint16x16(g0); - c = v_uint16x16(r0); -} - -inline void v_load_deinterleave( const unsigned* ptr, v_uint32x8& a, v_uint32x8& b, v_uint32x8& c ) -{ - __m256i bgr0 = _mm256_loadu_si256((const __m256i*)ptr); - __m256i bgr1 = _mm256_loadu_si256((const __m256i*)(ptr + 8)); - __m256i bgr2 = _mm256_loadu_si256((const __m256i*)(ptr + 16)); - - __m256i s02_low = _mm256_permute2x128_si256(bgr0, bgr2, 0 + 2*16); - __m256i s02_high = _mm256_permute2x128_si256(bgr0, bgr2, 1 + 3*16); - - __m256i b0 = _mm256_blend_epi32(_mm256_blend_epi32(s02_low, s02_high, 0x24), bgr1, 0x92); - __m256i g0 = _mm256_blend_epi32(_mm256_blend_epi32(s02_high, s02_low, 0x92), bgr1, 0x24); - __m256i r0 = _mm256_blend_epi32(_mm256_blend_epi32(bgr1, s02_low, 0x24), s02_high, 0x92); - - b0 = _mm256_shuffle_epi32(b0, 0x6c); - g0 = _mm256_shuffle_epi32(g0, 0xb1); - r0 = _mm256_shuffle_epi32(r0, 0xc6); - - a = v_uint32x8(b0); - b = v_uint32x8(g0); - c = v_uint32x8(r0); -} - -inline void v_load_deinterleave( const uint64* ptr, v_uint64x4& a, v_uint64x4& b, v_uint64x4& c ) -{ - __m256i bgr0 = _mm256_loadu_si256((const __m256i*)ptr); - __m256i bgr1 = _mm256_loadu_si256((const __m256i*)(ptr + 4)); - __m256i bgr2 = _mm256_loadu_si256((const __m256i*)(ptr + 8)); - - __m256i s01 = _mm256_blend_epi32(bgr0, bgr1, 0xf0); - __m256i s12 = _mm256_blend_epi32(bgr1, bgr2, 0xf0); - __m256i s20r = _mm256_permute4x64_epi64(_mm256_blend_epi32(bgr2, bgr0, 0xf0), 0x1b); - __m256i b0 = _mm256_unpacklo_epi64(s01, s20r); - __m256i g0 = _mm256_alignr_epi8(s12, s01, 8); - __m256i r0 = _mm256_unpackhi_epi64(s20r, s12); - - a = v_uint64x4(b0); - b = v_uint64x4(g0); - c = v_uint64x4(r0); -} - -inline void v_load_deinterleave( const uchar* ptr, v_uint8x32& a, v_uint8x32& b, v_uint8x32& c, v_uint8x32& d ) -{ - __m256i bgr0 = _mm256_loadu_si256((const __m256i*)ptr); - __m256i bgr1 = _mm256_loadu_si256((const __m256i*)(ptr + 32)); - __m256i bgr2 = _mm256_loadu_si256((const __m256i*)(ptr + 64)); - __m256i bgr3 = _mm256_loadu_si256((const __m256i*)(ptr + 96)); - const __m256i sh = _mm256_setr_epi8(0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, - 0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15); - - __m256i p0 = _mm256_shuffle_epi8(bgr0, sh); - __m256i p1 = _mm256_shuffle_epi8(bgr1, sh); - __m256i p2 = _mm256_shuffle_epi8(bgr2, sh); - __m256i p3 = _mm256_shuffle_epi8(bgr3, sh); - - __m256i p01l = _mm256_unpacklo_epi32(p0, p1); - __m256i p01h = _mm256_unpackhi_epi32(p0, p1); - __m256i p23l = _mm256_unpacklo_epi32(p2, p3); - __m256i p23h = _mm256_unpackhi_epi32(p2, p3); - - __m256i pll = _mm256_permute2x128_si256(p01l, p23l, 0 + 2*16); - __m256i plh = _mm256_permute2x128_si256(p01l, p23l, 1 + 3*16); - __m256i phl = _mm256_permute2x128_si256(p01h, p23h, 0 + 2*16); - __m256i phh = _mm256_permute2x128_si256(p01h, p23h, 1 + 3*16); - - __m256i b0 = _mm256_unpacklo_epi32(pll, plh); - __m256i g0 = _mm256_unpackhi_epi32(pll, plh); - __m256i r0 = _mm256_unpacklo_epi32(phl, phh); - __m256i a0 = _mm256_unpackhi_epi32(phl, phh); - - a = v_uint8x32(b0); - b = v_uint8x32(g0); - c = v_uint8x32(r0); - d = v_uint8x32(a0); -} - -inline void v_load_deinterleave( const ushort* ptr, v_uint16x16& a, v_uint16x16& b, v_uint16x16& c, v_uint16x16& d ) -{ - __m256i bgr0 = _mm256_loadu_si256((const __m256i*)ptr); - __m256i bgr1 = _mm256_loadu_si256((const __m256i*)(ptr + 16)); - __m256i bgr2 = _mm256_loadu_si256((const __m256i*)(ptr + 32)); - __m256i bgr3 = _mm256_loadu_si256((const __m256i*)(ptr + 48)); - const __m256i sh = _mm256_setr_epi8(0, 1, 8, 9, 2, 3, 10, 11, 4, 5, 12, 13, 6, 7, 14, 15, - 0, 1, 8, 9, 2, 3, 10, 11, 4, 5, 12, 13, 6, 7, 14, 15); - __m256i p0 = _mm256_shuffle_epi8(bgr0, sh); - __m256i p1 = _mm256_shuffle_epi8(bgr1, sh); - __m256i p2 = _mm256_shuffle_epi8(bgr2, sh); - __m256i p3 = _mm256_shuffle_epi8(bgr3, sh); - - __m256i p01l = _mm256_unpacklo_epi32(p0, p1); - __m256i p01h = _mm256_unpackhi_epi32(p0, p1); - __m256i p23l = _mm256_unpacklo_epi32(p2, p3); - __m256i p23h = _mm256_unpackhi_epi32(p2, p3); - - __m256i pll = _mm256_permute2x128_si256(p01l, p23l, 0 + 2*16); - __m256i plh = _mm256_permute2x128_si256(p01l, p23l, 1 + 3*16); - __m256i phl = _mm256_permute2x128_si256(p01h, p23h, 0 + 2*16); - __m256i phh = _mm256_permute2x128_si256(p01h, p23h, 1 + 3*16); - - __m256i b0 = _mm256_unpacklo_epi32(pll, plh); - __m256i g0 = _mm256_unpackhi_epi32(pll, plh); - __m256i r0 = _mm256_unpacklo_epi32(phl, phh); - __m256i a0 = _mm256_unpackhi_epi32(phl, phh); - - a = v_uint16x16(b0); - b = v_uint16x16(g0); - c = v_uint16x16(r0); - d = v_uint16x16(a0); -} - -inline void v_load_deinterleave( const unsigned* ptr, v_uint32x8& a, v_uint32x8& b, v_uint32x8& c, v_uint32x8& d ) -{ - __m256i p0 = _mm256_loadu_si256((const __m256i*)ptr); - __m256i p1 = _mm256_loadu_si256((const __m256i*)(ptr + 8)); - __m256i p2 = _mm256_loadu_si256((const __m256i*)(ptr + 16)); - __m256i p3 = _mm256_loadu_si256((const __m256i*)(ptr + 24)); - - __m256i p01l = _mm256_unpacklo_epi32(p0, p1); - __m256i p01h = _mm256_unpackhi_epi32(p0, p1); - __m256i p23l = _mm256_unpacklo_epi32(p2, p3); - __m256i p23h = _mm256_unpackhi_epi32(p2, p3); - - __m256i pll = _mm256_permute2x128_si256(p01l, p23l, 0 + 2*16); - __m256i plh = _mm256_permute2x128_si256(p01l, p23l, 1 + 3*16); - __m256i phl = _mm256_permute2x128_si256(p01h, p23h, 0 + 2*16); - __m256i phh = _mm256_permute2x128_si256(p01h, p23h, 1 + 3*16); - - __m256i b0 = _mm256_unpacklo_epi32(pll, plh); - __m256i g0 = _mm256_unpackhi_epi32(pll, plh); - __m256i r0 = _mm256_unpacklo_epi32(phl, phh); - __m256i a0 = _mm256_unpackhi_epi32(phl, phh); - - a = v_uint32x8(b0); - b = v_uint32x8(g0); - c = v_uint32x8(r0); - d = v_uint32x8(a0); -} - -inline void v_load_deinterleave( const uint64* ptr, v_uint64x4& a, v_uint64x4& b, v_uint64x4& c, v_uint64x4& d ) -{ - __m256i bgra0 = _mm256_loadu_si256((const __m256i*)ptr); - __m256i bgra1 = _mm256_loadu_si256((const __m256i*)(ptr + 4)); - __m256i bgra2 = _mm256_loadu_si256((const __m256i*)(ptr + 8)); - __m256i bgra3 = _mm256_loadu_si256((const __m256i*)(ptr + 12)); - - __m256i l02 = _mm256_permute2x128_si256(bgra0, bgra2, 0 + 2*16); - __m256i h02 = _mm256_permute2x128_si256(bgra0, bgra2, 1 + 3*16); - __m256i l13 = _mm256_permute2x128_si256(bgra1, bgra3, 0 + 2*16); - __m256i h13 = _mm256_permute2x128_si256(bgra1, bgra3, 1 + 3*16); - - __m256i b0 = _mm256_unpacklo_epi64(l02, l13); - __m256i g0 = _mm256_unpackhi_epi64(l02, l13); - __m256i r0 = _mm256_unpacklo_epi64(h02, h13); - __m256i a0 = _mm256_unpackhi_epi64(h02, h13); - - a = v_uint64x4(b0); - b = v_uint64x4(g0); - c = v_uint64x4(r0); - d = v_uint64x4(a0); -} - -///////////////////////////// store interleave ///////////////////////////////////// - -inline void v_store_interleave( uchar* ptr, const v_uint8x32& x, const v_uint8x32& y, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m256i xy_l = _mm256_unpacklo_epi8(x.val, y.val); - __m256i xy_h = _mm256_unpackhi_epi8(x.val, y.val); - - __m256i xy0 = _mm256_permute2x128_si256(xy_l, xy_h, 0 + 2*16); - __m256i xy1 = _mm256_permute2x128_si256(xy_l, xy_h, 1 + 3*16); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm256_stream_si256((__m256i*)ptr, xy0); - _mm256_stream_si256((__m256i*)(ptr + 32), xy1); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm256_store_si256((__m256i*)ptr, xy0); - _mm256_store_si256((__m256i*)(ptr + 32), xy1); - } - else - { - _mm256_storeu_si256((__m256i*)ptr, xy0); - _mm256_storeu_si256((__m256i*)(ptr + 32), xy1); - } -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x16& x, const v_uint16x16& y, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m256i xy_l = _mm256_unpacklo_epi16(x.val, y.val); - __m256i xy_h = _mm256_unpackhi_epi16(x.val, y.val); - - __m256i xy0 = _mm256_permute2x128_si256(xy_l, xy_h, 0 + 2*16); - __m256i xy1 = _mm256_permute2x128_si256(xy_l, xy_h, 1 + 3*16); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm256_stream_si256((__m256i*)ptr, xy0); - _mm256_stream_si256((__m256i*)(ptr + 16), xy1); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm256_store_si256((__m256i*)ptr, xy0); - _mm256_store_si256((__m256i*)(ptr + 16), xy1); - } - else - { - _mm256_storeu_si256((__m256i*)ptr, xy0); - _mm256_storeu_si256((__m256i*)(ptr + 16), xy1); - } -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x8& x, const v_uint32x8& y, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m256i xy_l = _mm256_unpacklo_epi32(x.val, y.val); - __m256i xy_h = _mm256_unpackhi_epi32(x.val, y.val); - - __m256i xy0 = _mm256_permute2x128_si256(xy_l, xy_h, 0 + 2*16); - __m256i xy1 = _mm256_permute2x128_si256(xy_l, xy_h, 1 + 3*16); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm256_stream_si256((__m256i*)ptr, xy0); - _mm256_stream_si256((__m256i*)(ptr + 8), xy1); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm256_store_si256((__m256i*)ptr, xy0); - _mm256_store_si256((__m256i*)(ptr + 8), xy1); - } - else - { - _mm256_storeu_si256((__m256i*)ptr, xy0); - _mm256_storeu_si256((__m256i*)(ptr + 8), xy1); - } -} - -inline void v_store_interleave( uint64* ptr, const v_uint64x4& x, const v_uint64x4& y, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m256i xy_l = _mm256_unpacklo_epi64(x.val, y.val); - __m256i xy_h = _mm256_unpackhi_epi64(x.val, y.val); - - __m256i xy0 = _mm256_permute2x128_si256(xy_l, xy_h, 0 + 2*16); - __m256i xy1 = _mm256_permute2x128_si256(xy_l, xy_h, 1 + 3*16); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm256_stream_si256((__m256i*)ptr, xy0); - _mm256_stream_si256((__m256i*)(ptr + 4), xy1); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm256_store_si256((__m256i*)ptr, xy0); - _mm256_store_si256((__m256i*)(ptr + 4), xy1); - } - else - { - _mm256_storeu_si256((__m256i*)ptr, xy0); - _mm256_storeu_si256((__m256i*)(ptr + 4), xy1); - } -} - -inline void v_store_interleave( uchar* ptr, const v_uint8x32& a, const v_uint8x32& b, const v_uint8x32& c, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - const __m256i sh_b = _mm256_setr_epi8( - 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5, - 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5); - const __m256i sh_g = _mm256_setr_epi8( - 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, - 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10); - const __m256i sh_r = _mm256_setr_epi8( - 10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, - 10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15); - - __m256i b0 = _mm256_shuffle_epi8(a.val, sh_b); - __m256i g0 = _mm256_shuffle_epi8(b.val, sh_g); - __m256i r0 = _mm256_shuffle_epi8(c.val, sh_r); - - const __m256i m0 = _mm256_setr_epi8(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, - 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); - const __m256i m1 = _mm256_setr_epi8(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, - 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0); - - __m256i p0 = _mm256_blendv_epi8(_mm256_blendv_epi8(b0, g0, m0), r0, m1); - __m256i p1 = _mm256_blendv_epi8(_mm256_blendv_epi8(g0, r0, m0), b0, m1); - __m256i p2 = _mm256_blendv_epi8(_mm256_blendv_epi8(r0, b0, m0), g0, m1); - - __m256i bgr0 = _mm256_permute2x128_si256(p0, p1, 0 + 2*16); - __m256i bgr1 = _mm256_permute2x128_si256(p2, p0, 0 + 3*16); - __m256i bgr2 = _mm256_permute2x128_si256(p1, p2, 1 + 3*16); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm256_stream_si256((__m256i*)ptr, bgr0); - _mm256_stream_si256((__m256i*)(ptr + 32), bgr1); - _mm256_stream_si256((__m256i*)(ptr + 64), bgr2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm256_store_si256((__m256i*)ptr, bgr0); - _mm256_store_si256((__m256i*)(ptr + 32), bgr1); - _mm256_store_si256((__m256i*)(ptr + 64), bgr2); - } - else - { - _mm256_storeu_si256((__m256i*)ptr, bgr0); - _mm256_storeu_si256((__m256i*)(ptr + 32), bgr1); - _mm256_storeu_si256((__m256i*)(ptr + 64), bgr2); - } -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x16& a, const v_uint16x16& b, const v_uint16x16& c, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - const __m256i sh_b = _mm256_setr_epi8( - 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, - 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11); - const __m256i sh_g = _mm256_setr_epi8( - 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, - 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5); - const __m256i sh_r = _mm256_setr_epi8( - 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, - 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15); - - __m256i b0 = _mm256_shuffle_epi8(a.val, sh_b); - __m256i g0 = _mm256_shuffle_epi8(b.val, sh_g); - __m256i r0 = _mm256_shuffle_epi8(c.val, sh_r); - - const __m256i m0 = _mm256_setr_epi8(0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, - 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0); - const __m256i m1 = _mm256_setr_epi8(0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, - -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0); - - __m256i p0 = _mm256_blendv_epi8(_mm256_blendv_epi8(b0, g0, m0), r0, m1); - __m256i p1 = _mm256_blendv_epi8(_mm256_blendv_epi8(g0, r0, m0), b0, m1); - __m256i p2 = _mm256_blendv_epi8(_mm256_blendv_epi8(r0, b0, m0), g0, m1); - - __m256i bgr0 = _mm256_permute2x128_si256(p0, p2, 0 + 2*16); - //__m256i bgr1 = p1; - __m256i bgr2 = _mm256_permute2x128_si256(p0, p2, 1 + 3*16); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm256_stream_si256((__m256i*)ptr, bgr0); - _mm256_stream_si256((__m256i*)(ptr + 16), p1); - _mm256_stream_si256((__m256i*)(ptr + 32), bgr2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm256_store_si256((__m256i*)ptr, bgr0); - _mm256_store_si256((__m256i*)(ptr + 16), p1); - _mm256_store_si256((__m256i*)(ptr + 32), bgr2); - } - else - { - _mm256_storeu_si256((__m256i*)ptr, bgr0); - _mm256_storeu_si256((__m256i*)(ptr + 16), p1); - _mm256_storeu_si256((__m256i*)(ptr + 32), bgr2); - } -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x8& a, const v_uint32x8& b, const v_uint32x8& c, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m256i b0 = _mm256_shuffle_epi32(a.val, 0x6c); - __m256i g0 = _mm256_shuffle_epi32(b.val, 0xb1); - __m256i r0 = _mm256_shuffle_epi32(c.val, 0xc6); - - __m256i p0 = _mm256_blend_epi32(_mm256_blend_epi32(b0, g0, 0x92), r0, 0x24); - __m256i p1 = _mm256_blend_epi32(_mm256_blend_epi32(g0, r0, 0x92), b0, 0x24); - __m256i p2 = _mm256_blend_epi32(_mm256_blend_epi32(r0, b0, 0x92), g0, 0x24); - - __m256i bgr0 = _mm256_permute2x128_si256(p0, p1, 0 + 2*16); - //__m256i bgr1 = p2; - __m256i bgr2 = _mm256_permute2x128_si256(p0, p1, 1 + 3*16); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm256_stream_si256((__m256i*)ptr, bgr0); - _mm256_stream_si256((__m256i*)(ptr + 8), p2); - _mm256_stream_si256((__m256i*)(ptr + 16), bgr2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm256_store_si256((__m256i*)ptr, bgr0); - _mm256_store_si256((__m256i*)(ptr + 8), p2); - _mm256_store_si256((__m256i*)(ptr + 16), bgr2); - } - else - { - _mm256_storeu_si256((__m256i*)ptr, bgr0); - _mm256_storeu_si256((__m256i*)(ptr + 8), p2); - _mm256_storeu_si256((__m256i*)(ptr + 16), bgr2); - } -} - -inline void v_store_interleave( uint64* ptr, const v_uint64x4& a, const v_uint64x4& b, const v_uint64x4& c, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m256i s01 = _mm256_unpacklo_epi64(a.val, b.val); - __m256i s12 = _mm256_unpackhi_epi64(b.val, c.val); - __m256i s20 = _mm256_blend_epi32(c.val, a.val, 0xcc); - - __m256i bgr0 = _mm256_permute2x128_si256(s01, s20, 0 + 2*16); - __m256i bgr1 = _mm256_blend_epi32(s01, s12, 0x0f); - __m256i bgr2 = _mm256_permute2x128_si256(s20, s12, 1 + 3*16); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm256_stream_si256((__m256i*)ptr, bgr0); - _mm256_stream_si256((__m256i*)(ptr + 4), bgr1); - _mm256_stream_si256((__m256i*)(ptr + 8), bgr2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm256_store_si256((__m256i*)ptr, bgr0); - _mm256_store_si256((__m256i*)(ptr + 4), bgr1); - _mm256_store_si256((__m256i*)(ptr + 8), bgr2); - } - else - { - _mm256_storeu_si256((__m256i*)ptr, bgr0); - _mm256_storeu_si256((__m256i*)(ptr + 4), bgr1); - _mm256_storeu_si256((__m256i*)(ptr + 8), bgr2); - } -} - -inline void v_store_interleave( uchar* ptr, const v_uint8x32& a, const v_uint8x32& b, - const v_uint8x32& c, const v_uint8x32& d, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m256i bg0 = _mm256_unpacklo_epi8(a.val, b.val); - __m256i bg1 = _mm256_unpackhi_epi8(a.val, b.val); - __m256i ra0 = _mm256_unpacklo_epi8(c.val, d.val); - __m256i ra1 = _mm256_unpackhi_epi8(c.val, d.val); - - __m256i bgra0_ = _mm256_unpacklo_epi16(bg0, ra0); - __m256i bgra1_ = _mm256_unpackhi_epi16(bg0, ra0); - __m256i bgra2_ = _mm256_unpacklo_epi16(bg1, ra1); - __m256i bgra3_ = _mm256_unpackhi_epi16(bg1, ra1); - - __m256i bgra0 = _mm256_permute2x128_si256(bgra0_, bgra1_, 0 + 2*16); - __m256i bgra2 = _mm256_permute2x128_si256(bgra0_, bgra1_, 1 + 3*16); - __m256i bgra1 = _mm256_permute2x128_si256(bgra2_, bgra3_, 0 + 2*16); - __m256i bgra3 = _mm256_permute2x128_si256(bgra2_, bgra3_, 1 + 3*16); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm256_stream_si256((__m256i*)ptr, bgra0); - _mm256_stream_si256((__m256i*)(ptr + 32), bgra1); - _mm256_stream_si256((__m256i*)(ptr + 64), bgra2); - _mm256_stream_si256((__m256i*)(ptr + 96), bgra3); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm256_store_si256((__m256i*)ptr, bgra0); - _mm256_store_si256((__m256i*)(ptr + 32), bgra1); - _mm256_store_si256((__m256i*)(ptr + 64), bgra2); - _mm256_store_si256((__m256i*)(ptr + 96), bgra3); - } - else - { - _mm256_storeu_si256((__m256i*)ptr, bgra0); - _mm256_storeu_si256((__m256i*)(ptr + 32), bgra1); - _mm256_storeu_si256((__m256i*)(ptr + 64), bgra2); - _mm256_storeu_si256((__m256i*)(ptr + 96), bgra3); - } -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x16& a, const v_uint16x16& b, - const v_uint16x16& c, const v_uint16x16& d, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m256i bg0 = _mm256_unpacklo_epi16(a.val, b.val); - __m256i bg1 = _mm256_unpackhi_epi16(a.val, b.val); - __m256i ra0 = _mm256_unpacklo_epi16(c.val, d.val); - __m256i ra1 = _mm256_unpackhi_epi16(c.val, d.val); - - __m256i bgra0_ = _mm256_unpacklo_epi32(bg0, ra0); - __m256i bgra1_ = _mm256_unpackhi_epi32(bg0, ra0); - __m256i bgra2_ = _mm256_unpacklo_epi32(bg1, ra1); - __m256i bgra3_ = _mm256_unpackhi_epi32(bg1, ra1); - - __m256i bgra0 = _mm256_permute2x128_si256(bgra0_, bgra1_, 0 + 2*16); - __m256i bgra2 = _mm256_permute2x128_si256(bgra0_, bgra1_, 1 + 3*16); - __m256i bgra1 = _mm256_permute2x128_si256(bgra2_, bgra3_, 0 + 2*16); - __m256i bgra3 = _mm256_permute2x128_si256(bgra2_, bgra3_, 1 + 3*16); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm256_stream_si256((__m256i*)ptr, bgra0); - _mm256_stream_si256((__m256i*)(ptr + 16), bgra1); - _mm256_stream_si256((__m256i*)(ptr + 32), bgra2); - _mm256_stream_si256((__m256i*)(ptr + 48), bgra3); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm256_store_si256((__m256i*)ptr, bgra0); - _mm256_store_si256((__m256i*)(ptr + 16), bgra1); - _mm256_store_si256((__m256i*)(ptr + 32), bgra2); - _mm256_store_si256((__m256i*)(ptr + 48), bgra3); - } - else - { - _mm256_storeu_si256((__m256i*)ptr, bgra0); - _mm256_storeu_si256((__m256i*)(ptr + 16), bgra1); - _mm256_storeu_si256((__m256i*)(ptr + 32), bgra2); - _mm256_storeu_si256((__m256i*)(ptr + 48), bgra3); - } -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x8& a, const v_uint32x8& b, - const v_uint32x8& c, const v_uint32x8& d, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m256i bg0 = _mm256_unpacklo_epi32(a.val, b.val); - __m256i bg1 = _mm256_unpackhi_epi32(a.val, b.val); - __m256i ra0 = _mm256_unpacklo_epi32(c.val, d.val); - __m256i ra1 = _mm256_unpackhi_epi32(c.val, d.val); - - __m256i bgra0_ = _mm256_unpacklo_epi64(bg0, ra0); - __m256i bgra1_ = _mm256_unpackhi_epi64(bg0, ra0); - __m256i bgra2_ = _mm256_unpacklo_epi64(bg1, ra1); - __m256i bgra3_ = _mm256_unpackhi_epi64(bg1, ra1); - - __m256i bgra0 = _mm256_permute2x128_si256(bgra0_, bgra1_, 0 + 2*16); - __m256i bgra2 = _mm256_permute2x128_si256(bgra0_, bgra1_, 1 + 3*16); - __m256i bgra1 = _mm256_permute2x128_si256(bgra2_, bgra3_, 0 + 2*16); - __m256i bgra3 = _mm256_permute2x128_si256(bgra2_, bgra3_, 1 + 3*16); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm256_stream_si256((__m256i*)ptr, bgra0); - _mm256_stream_si256((__m256i*)(ptr + 8), bgra1); - _mm256_stream_si256((__m256i*)(ptr + 16), bgra2); - _mm256_stream_si256((__m256i*)(ptr + 24), bgra3); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm256_store_si256((__m256i*)ptr, bgra0); - _mm256_store_si256((__m256i*)(ptr + 8), bgra1); - _mm256_store_si256((__m256i*)(ptr + 16), bgra2); - _mm256_store_si256((__m256i*)(ptr + 24), bgra3); - } - else - { - _mm256_storeu_si256((__m256i*)ptr, bgra0); - _mm256_storeu_si256((__m256i*)(ptr + 8), bgra1); - _mm256_storeu_si256((__m256i*)(ptr + 16), bgra2); - _mm256_storeu_si256((__m256i*)(ptr + 24), bgra3); - } -} - -inline void v_store_interleave( uint64* ptr, const v_uint64x4& a, const v_uint64x4& b, - const v_uint64x4& c, const v_uint64x4& d, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m256i bg0 = _mm256_unpacklo_epi64(a.val, b.val); - __m256i bg1 = _mm256_unpackhi_epi64(a.val, b.val); - __m256i ra0 = _mm256_unpacklo_epi64(c.val, d.val); - __m256i ra1 = _mm256_unpackhi_epi64(c.val, d.val); - - __m256i bgra0 = _mm256_permute2x128_si256(bg0, ra0, 0 + 2*16); - __m256i bgra1 = _mm256_permute2x128_si256(bg1, ra1, 0 + 2*16); - __m256i bgra2 = _mm256_permute2x128_si256(bg0, ra0, 1 + 3*16); - __m256i bgra3 = _mm256_permute2x128_si256(bg1, ra1, 1 + 3*16); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm256_stream_si256((__m256i*)ptr, bgra0); - _mm256_stream_si256((__m256i*)(ptr + 4), bgra1); - _mm256_stream_si256((__m256i*)(ptr + 8), bgra2); - _mm256_stream_si256((__m256i*)(ptr + 12), bgra3); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm256_store_si256((__m256i*)ptr, bgra0); - _mm256_store_si256((__m256i*)(ptr + 4), bgra1); - _mm256_store_si256((__m256i*)(ptr + 8), bgra2); - _mm256_store_si256((__m256i*)(ptr + 12), bgra3); - } - else - { - _mm256_storeu_si256((__m256i*)ptr, bgra0); - _mm256_storeu_si256((__m256i*)(ptr + 4), bgra1); - _mm256_storeu_si256((__m256i*)(ptr + 8), bgra2); - _mm256_storeu_si256((__m256i*)(ptr + 12), bgra3); - } -} - -#define OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(_Tpvec0, _Tp0, suffix0, _Tpvec1, _Tp1, suffix1) \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0 ) \ -{ \ - _Tpvec1 a1, b1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ -} \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0 ) \ -{ \ - _Tpvec1 a1, b1, c1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ - c0 = v_reinterpret_as_##suffix0(c1); \ -} \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0, _Tpvec0& d0 ) \ -{ \ - _Tpvec1 a1, b1, c1, d1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1, d1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ - c0 = v_reinterpret_as_##suffix0(c1); \ - d0 = v_reinterpret_as_##suffix0(d1); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - hal::StoreMode mode=hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, mode); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, const _Tpvec0& c0, \ - hal::StoreMode mode=hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, c1, mode); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - const _Tpvec0& c0, const _Tpvec0& d0, \ - hal::StoreMode mode=hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ - _Tpvec1 d1 = v_reinterpret_as_##suffix1(d0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, c1, d1, mode); \ -} - -OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_int8x32, schar, s8, v_uint8x32, uchar, u8) -OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_int16x16, short, s16, v_uint16x16, ushort, u16) -OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_int32x8, int, s32, v_uint32x8, unsigned, u32) -OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_float32x8, float, f32, v_uint32x8, unsigned, u32) -OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_int64x4, int64, s64, v_uint64x4, uint64, u64) -OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_float64x4, double, f64, v_uint64x4, uint64, u64) - -// -// FP16 -// - -inline v_float32x8 v256_load_expand(const hfloat* ptr) -{ -#if CV_FP16 - return v_float32x8(_mm256_cvtph_ps(_mm_loadu_si128((const __m128i*)ptr))); -#else - float CV_DECL_ALIGNED(32) buf[8]; - for (int i = 0; i < 8; i++) - buf[i] = (float)ptr[i]; - return v256_load_aligned(buf); -#endif -} - -inline void v_pack_store(hfloat* ptr, const v_float32x8& a) -{ -#if CV_FP16 - __m128i ah = _mm256_cvtps_ph(a.val, 0); - _mm_storeu_si128((__m128i*)ptr, ah); -#else - float CV_DECL_ALIGNED(32) buf[8]; - v_store_aligned(buf, a); - for (int i = 0; i < 8; i++) - ptr[i] = hfloat(buf[i]); -#endif -} - -// -// end of FP16 -// - -inline void v256_cleanup() { _mm256_zeroall(); } - -#include "intrin_math.hpp" -inline v_float32x8 v_exp(const v_float32x8& x) { return v_exp_default_32f(x); } -inline v_float32x8 v_log(const v_float32x8& x) { return v_log_default_32f(x); } -inline void v_sincos(const v_float32x8& x, v_float32x8& s, v_float32x8& c) { v_sincos_default_32f(x, s, c); } -inline v_float32x8 v_sin(const v_float32x8& x) { return v_sin_default_32f(x); } -inline v_float32x8 v_cos(const v_float32x8& x) { return v_cos_default_32f(x); } -inline v_float32x8 v_erf(const v_float32x8& x) { return v_erf_default_32f(x); } - -inline v_float64x4 v_exp(const v_float64x4& x) { return v_exp_default_64f(x); } -inline v_float64x4 v_log(const v_float64x4& x) { return v_log_default_64f(x); } -inline void v_sincos(const v_float64x4& x, v_float64x4& s, v_float64x4& c) { v_sincos_default_64f(x, s, c); } -inline v_float64x4 v_sin(const v_float64x4& x) { return v_sin_default_64f(x); } -inline v_float64x4 v_cos(const v_float64x4& x) { return v_cos_default_64f(x); } - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} // cv:: - -#endif // OPENCV_HAL_INTRIN_AVX_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +#ifndef OPENCV_HAL_INTRIN_AVX_HPP +#define OPENCV_HAL_INTRIN_AVX_HPP + +#define CV_SIMD256 1 +#define CV_SIMD256_64F 1 +#define CV_SIMD256_FP16 0 // no native operations with FP16 type. Only load/store from float32x8 are available (if CV_FP16 == 1) + +namespace cv +{ + +//! @cond IGNORED + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +///////// Utils //////////// + +inline __m256i _v256_combine(const __m128i& lo, const __m128i& hi) +{ return _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1); } + +inline __m256 _v256_combine(const __m128& lo, const __m128& hi) +{ return _mm256_insertf128_ps(_mm256_castps128_ps256(lo), hi, 1); } + +inline __m256d _v256_combine(const __m128d& lo, const __m128d& hi) +{ return _mm256_insertf128_pd(_mm256_castpd128_pd256(lo), hi, 1); } + +inline int _v_cvtsi256_si32(const __m256i& a) +{ return _mm_cvtsi128_si32(_mm256_castsi256_si128(a)); } + +inline __m256i _v256_shuffle_odd_64(const __m256i& v) +{ return _mm256_permute4x64_epi64(v, _MM_SHUFFLE(3, 1, 2, 0)); } + +inline __m256d _v256_shuffle_odd_64(const __m256d& v) +{ return _mm256_permute4x64_pd(v, _MM_SHUFFLE(3, 1, 2, 0)); } + +template +inline __m256i _v256_permute2x128(const __m256i& a, const __m256i& b) +{ return _mm256_permute2x128_si256(a, b, imm); } + +template +inline __m256 _v256_permute2x128(const __m256& a, const __m256& b) +{ return _mm256_permute2f128_ps(a, b, imm); } + +template +inline __m256d _v256_permute2x128(const __m256d& a, const __m256d& b) +{ return _mm256_permute2f128_pd(a, b, imm); } + +template +inline _Tpvec v256_permute2x128(const _Tpvec& a, const _Tpvec& b) +{ return _Tpvec(_v256_permute2x128(a.val, b.val)); } + +template +inline __m256i _v256_permute4x64(const __m256i& a) +{ return _mm256_permute4x64_epi64(a, imm); } + +template +inline __m256d _v256_permute4x64(const __m256d& a) +{ return _mm256_permute4x64_pd(a, imm); } + +template +inline _Tpvec v256_permute4x64(const _Tpvec& a) +{ return _Tpvec(_v256_permute4x64(a.val)); } + +inline __m128i _v256_extract_high(const __m256i& v) +{ return _mm256_extracti128_si256(v, 1); } + +inline __m128 _v256_extract_high(const __m256& v) +{ return _mm256_extractf128_ps(v, 1); } + +inline __m128d _v256_extract_high(const __m256d& v) +{ return _mm256_extractf128_pd(v, 1); } + +inline __m128i _v256_extract_low(const __m256i& v) +{ return _mm256_castsi256_si128(v); } + +inline __m128 _v256_extract_low(const __m256& v) +{ return _mm256_castps256_ps128(v); } + +inline __m128d _v256_extract_low(const __m256d& v) +{ return _mm256_castpd256_pd128(v); } + +inline __m256i _v256_packs_epu32(const __m256i& a, const __m256i& b) +{ + const __m256i m = _mm256_set1_epi32(65535); + __m256i am = _mm256_min_epu32(a, m); + __m256i bm = _mm256_min_epu32(b, m); + return _mm256_packus_epi32(am, bm); +} + +template +inline int _v256_extract_epi8(const __m256i& a) +{ +#if defined(CV__SIMD_HAVE_mm256_extract_epi8) || (CV_AVX2 && (!defined(_MSC_VER) || _MSC_VER >= 1910/*MSVS 2017*/)) + return _mm256_extract_epi8(a, i); +#else + __m128i b = _mm256_extractf128_si256(a, ((i) >> 4)); + return _mm_extract_epi8(b, i & 15); // SSE4.1 +#endif +} + +template +inline int _v256_extract_epi16(const __m256i& a) +{ +#if defined(CV__SIMD_HAVE_mm256_extract_epi8) || (CV_AVX2 && (!defined(_MSC_VER) || _MSC_VER >= 1910/*MSVS 2017*/)) + return _mm256_extract_epi16(a, i); +#else + __m128i b = _mm256_extractf128_si256(a, ((i) >> 3)); + return _mm_extract_epi16(b, i & 7); // SSE2 +#endif +} + +template +inline int _v256_extract_epi32(const __m256i& a) +{ +#if defined(CV__SIMD_HAVE_mm256_extract_epi8) || (CV_AVX2 && (!defined(_MSC_VER) || _MSC_VER >= 1910/*MSVS 2017*/)) + return _mm256_extract_epi32(a, i); +#else + __m128i b = _mm256_extractf128_si256(a, ((i) >> 2)); + return _mm_extract_epi32(b, i & 3); // SSE4.1 +#endif +} + +template +inline int64 _v256_extract_epi64(const __m256i& a) +{ +#if defined(CV__SIMD_HAVE_mm256_extract_epi8) || (CV_AVX2 && (!defined(_MSC_VER) || _MSC_VER >= 1910/*MSVS 2017*/)) + return _mm256_extract_epi64(a, i); +#else + __m128i b = _mm256_extractf128_si256(a, ((i) >> 1)); + return _mm_extract_epi64(b, i & 1); // SSE4.1 +#endif +} + +///////// Types //////////// + +struct v_uint8x32 +{ + typedef uchar lane_type; + enum { nlanes = 32 }; + __m256i val; + + explicit v_uint8x32(__m256i v) : val(v) {} + v_uint8x32(uchar v0, uchar v1, uchar v2, uchar v3, + uchar v4, uchar v5, uchar v6, uchar v7, + uchar v8, uchar v9, uchar v10, uchar v11, + uchar v12, uchar v13, uchar v14, uchar v15, + uchar v16, uchar v17, uchar v18, uchar v19, + uchar v20, uchar v21, uchar v22, uchar v23, + uchar v24, uchar v25, uchar v26, uchar v27, + uchar v28, uchar v29, uchar v30, uchar v31) + { + val = _mm256_setr_epi8((char)v0, (char)v1, (char)v2, (char)v3, + (char)v4, (char)v5, (char)v6 , (char)v7, (char)v8, (char)v9, + (char)v10, (char)v11, (char)v12, (char)v13, (char)v14, (char)v15, + (char)v16, (char)v17, (char)v18, (char)v19, (char)v20, (char)v21, + (char)v22, (char)v23, (char)v24, (char)v25, (char)v26, (char)v27, + (char)v28, (char)v29, (char)v30, (char)v31); + } + /* coverity[uninit_ctor]: suppress warning */ + v_uint8x32() {} + + uchar get0() const { return (uchar)_v_cvtsi256_si32(val); } +}; + +struct v_int8x32 +{ + typedef schar lane_type; + enum { nlanes = 32 }; + __m256i val; + + explicit v_int8x32(__m256i v) : val(v) {} + v_int8x32(schar v0, schar v1, schar v2, schar v3, + schar v4, schar v5, schar v6, schar v7, + schar v8, schar v9, schar v10, schar v11, + schar v12, schar v13, schar v14, schar v15, + schar v16, schar v17, schar v18, schar v19, + schar v20, schar v21, schar v22, schar v23, + schar v24, schar v25, schar v26, schar v27, + schar v28, schar v29, schar v30, schar v31) + { + val = _mm256_setr_epi8(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, + v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, + v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31); + } + /* coverity[uninit_ctor]: suppress warning */ + v_int8x32() {} + + schar get0() const { return (schar)_v_cvtsi256_si32(val); } +}; + +struct v_uint16x16 +{ + typedef ushort lane_type; + enum { nlanes = 16 }; + __m256i val; + + explicit v_uint16x16(__m256i v) : val(v) {} + v_uint16x16(ushort v0, ushort v1, ushort v2, ushort v3, + ushort v4, ushort v5, ushort v6, ushort v7, + ushort v8, ushort v9, ushort v10, ushort v11, + ushort v12, ushort v13, ushort v14, ushort v15) + { + val = _mm256_setr_epi16((short)v0, (short)v1, (short)v2, (short)v3, + (short)v4, (short)v5, (short)v6, (short)v7, (short)v8, (short)v9, + (short)v10, (short)v11, (short)v12, (short)v13, (short)v14, (short)v15); + } + /* coverity[uninit_ctor]: suppress warning */ + v_uint16x16() {} + + ushort get0() const { return (ushort)_v_cvtsi256_si32(val); } +}; + +struct v_int16x16 +{ + typedef short lane_type; + enum { nlanes = 16 }; + __m256i val; + + explicit v_int16x16(__m256i v) : val(v) {} + v_int16x16(short v0, short v1, short v2, short v3, + short v4, short v5, short v6, short v7, + short v8, short v9, short v10, short v11, + short v12, short v13, short v14, short v15) + { + val = _mm256_setr_epi16(v0, v1, v2, v3, v4, v5, v6, v7, + v8, v9, v10, v11, v12, v13, v14, v15); + } + /* coverity[uninit_ctor]: suppress warning */ + v_int16x16() {} + + short get0() const { return (short)_v_cvtsi256_si32(val); } +}; + +struct v_uint32x8 +{ + typedef unsigned lane_type; + enum { nlanes = 8 }; + __m256i val; + + explicit v_uint32x8(__m256i v) : val(v) {} + v_uint32x8(unsigned v0, unsigned v1, unsigned v2, unsigned v3, + unsigned v4, unsigned v5, unsigned v6, unsigned v7) + { + val = _mm256_setr_epi32((unsigned)v0, (unsigned)v1, (unsigned)v2, + (unsigned)v3, (unsigned)v4, (unsigned)v5, (unsigned)v6, (unsigned)v7); + } + /* coverity[uninit_ctor]: suppress warning */ + v_uint32x8() {} + + unsigned get0() const { return (unsigned)_v_cvtsi256_si32(val); } +}; + +struct v_int32x8 +{ + typedef int lane_type; + enum { nlanes = 8 }; + __m256i val; + + explicit v_int32x8(__m256i v) : val(v) {} + v_int32x8(int v0, int v1, int v2, int v3, + int v4, int v5, int v6, int v7) + { + val = _mm256_setr_epi32(v0, v1, v2, v3, v4, v5, v6, v7); + } + /* coverity[uninit_ctor]: suppress warning */ + v_int32x8() {} + + int get0() const { return _v_cvtsi256_si32(val); } +}; + +struct v_float32x8 +{ + typedef float lane_type; + enum { nlanes = 8 }; + __m256 val; + + explicit v_float32x8(__m256 v) : val(v) {} + v_float32x8(float v0, float v1, float v2, float v3, + float v4, float v5, float v6, float v7) + { + val = _mm256_setr_ps(v0, v1, v2, v3, v4, v5, v6, v7); + } + /* coverity[uninit_ctor]: suppress warning */ + v_float32x8() {} + + float get0() const { return _mm_cvtss_f32(_mm256_castps256_ps128(val)); } +}; + +struct v_uint64x4 +{ + typedef uint64 lane_type; + enum { nlanes = 4 }; + __m256i val; + + explicit v_uint64x4(__m256i v) : val(v) {} + v_uint64x4(uint64 v0, uint64 v1, uint64 v2, uint64 v3) + { val = _mm256_setr_epi64x((int64)v0, (int64)v1, (int64)v2, (int64)v3); } + /* coverity[uninit_ctor]: suppress warning */ + v_uint64x4() {} + + uint64 get0() const + { + #if defined __x86_64__ || defined _M_X64 + return (uint64)_mm_cvtsi128_si64(_mm256_castsi256_si128(val)); + #else + int a = _mm_cvtsi128_si32(_mm256_castsi256_si128(val)); + int b = _mm_cvtsi128_si32(_mm256_castsi256_si128(_mm256_srli_epi64(val, 32))); + return (unsigned)a | ((uint64)(unsigned)b << 32); + #endif + } +}; + +struct v_int64x4 +{ + typedef int64 lane_type; + enum { nlanes = 4 }; + __m256i val; + + explicit v_int64x4(__m256i v) : val(v) {} + v_int64x4(int64 v0, int64 v1, int64 v2, int64 v3) + { val = _mm256_setr_epi64x(v0, v1, v2, v3); } + /* coverity[uninit_ctor]: suppress warning */ + v_int64x4() {} + + int64 get0() const + { + #if defined __x86_64__ || defined _M_X64 + return (int64)_mm_cvtsi128_si64(_mm256_castsi256_si128(val)); + #else + int a = _mm_cvtsi128_si32(_mm256_castsi256_si128(val)); + int b = _mm_cvtsi128_si32(_mm256_castsi256_si128(_mm256_srli_epi64(val, 32))); + return (int64)((unsigned)a | ((uint64)(unsigned)b << 32)); + #endif + } +}; + +struct v_float64x4 +{ + typedef double lane_type; + enum { nlanes = 4 }; + __m256d val; + + explicit v_float64x4(__m256d v) : val(v) {} + v_float64x4(double v0, double v1, double v2, double v3) + { val = _mm256_setr_pd(v0, v1, v2, v3); } + /* coverity[uninit_ctor]: suppress warning */ + v_float64x4() {} + + double get0() const { return _mm_cvtsd_f64(_mm256_castpd256_pd128(val)); } +}; + +//////////////// Load and store operations /////////////// + +#define OPENCV_HAL_IMPL_AVX_LOADSTORE(_Tpvec, _Tp) \ + inline _Tpvec v256_load(const _Tp* ptr) \ + { return _Tpvec(_mm256_loadu_si256((const __m256i*)ptr)); } \ + inline _Tpvec v256_load_aligned(const _Tp* ptr) \ + { return _Tpvec(_mm256_load_si256((const __m256i*)ptr)); } \ + inline _Tpvec v256_load_low(const _Tp* ptr) \ + { \ + __m128i v128 = _mm_loadu_si128((const __m128i*)ptr); \ + return _Tpvec(_mm256_castsi128_si256(v128)); \ + } \ + inline _Tpvec v256_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ + { \ + __m128i vlo = _mm_loadu_si128((const __m128i*)ptr0); \ + __m128i vhi = _mm_loadu_si128((const __m128i*)ptr1); \ + return _Tpvec(_v256_combine(vlo, vhi)); \ + } \ + inline void v_store(_Tp* ptr, const _Tpvec& a) \ + { _mm256_storeu_si256((__m256i*)ptr, a.val); } \ + inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ + { _mm256_store_si256((__m256i*)ptr, a.val); } \ + inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ + { _mm256_stream_si256((__m256i*)ptr, a.val); } \ + inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ + { \ + if( mode == hal::STORE_UNALIGNED ) \ + _mm256_storeu_si256((__m256i*)ptr, a.val); \ + else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ + _mm256_stream_si256((__m256i*)ptr, a.val); \ + else \ + _mm256_store_si256((__m256i*)ptr, a.val); \ + } \ + inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ + { _mm_storeu_si128((__m128i*)ptr, _v256_extract_low(a.val)); } \ + inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ + { _mm_storeu_si128((__m128i*)ptr, _v256_extract_high(a.val)); } + +OPENCV_HAL_IMPL_AVX_LOADSTORE(v_uint8x32, uchar) +OPENCV_HAL_IMPL_AVX_LOADSTORE(v_int8x32, schar) +OPENCV_HAL_IMPL_AVX_LOADSTORE(v_uint16x16, ushort) +OPENCV_HAL_IMPL_AVX_LOADSTORE(v_int16x16, short) +OPENCV_HAL_IMPL_AVX_LOADSTORE(v_uint32x8, unsigned) +OPENCV_HAL_IMPL_AVX_LOADSTORE(v_int32x8, int) +OPENCV_HAL_IMPL_AVX_LOADSTORE(v_uint64x4, uint64) +OPENCV_HAL_IMPL_AVX_LOADSTORE(v_int64x4, int64) + +#define OPENCV_HAL_IMPL_AVX_LOADSTORE_FLT(_Tpvec, _Tp, suffix, halfreg) \ + inline _Tpvec v256_load(const _Tp* ptr) \ + { return _Tpvec(_mm256_loadu_##suffix(ptr)); } \ + inline _Tpvec v256_load_aligned(const _Tp* ptr) \ + { return _Tpvec(_mm256_load_##suffix(ptr)); } \ + inline _Tpvec v256_load_low(const _Tp* ptr) \ + { \ + return _Tpvec(_mm256_cast##suffix##128_##suffix##256 \ + (_mm_loadu_##suffix(ptr))); \ + } \ + inline _Tpvec v256_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ + { \ + halfreg vlo = _mm_loadu_##suffix(ptr0); \ + halfreg vhi = _mm_loadu_##suffix(ptr1); \ + return _Tpvec(_v256_combine(vlo, vhi)); \ + } \ + inline void v_store(_Tp* ptr, const _Tpvec& a) \ + { _mm256_storeu_##suffix(ptr, a.val); } \ + inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ + { _mm256_store_##suffix(ptr, a.val); } \ + inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ + { _mm256_stream_##suffix(ptr, a.val); } \ + inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ + { \ + if( mode == hal::STORE_UNALIGNED ) \ + _mm256_storeu_##suffix(ptr, a.val); \ + else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ + _mm256_stream_##suffix(ptr, a.val); \ + else \ + _mm256_store_##suffix(ptr, a.val); \ + } \ + inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ + { _mm_storeu_##suffix(ptr, _v256_extract_low(a.val)); } \ + inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ + { _mm_storeu_##suffix(ptr, _v256_extract_high(a.val)); } + +OPENCV_HAL_IMPL_AVX_LOADSTORE_FLT(v_float32x8, float, ps, __m128) +OPENCV_HAL_IMPL_AVX_LOADSTORE_FLT(v_float64x4, double, pd, __m128d) + +#define OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, _Tpvecf, suffix, cast) \ + inline _Tpvec v_reinterpret_as_##suffix(const _Tpvecf& a) \ + { return _Tpvec(cast(a.val)); } + +#define OPENCV_HAL_IMPL_AVX_INIT(_Tpvec, _Tp, suffix, ssuffix, ctype_s) \ + inline _Tpvec v256_setzero_##suffix() \ + { return _Tpvec(_mm256_setzero_si256()); } \ + inline _Tpvec v256_setall_##suffix(_Tp v) \ + { return _Tpvec(_mm256_set1_##ssuffix((ctype_s)v)); } \ + template <> inline _Tpvec v_setzero_() \ + { return v256_setzero_##suffix(); } \ + template <> inline _Tpvec v_setall_(_Tp v) \ + { return v256_setall_##suffix(v); } \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint8x32, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int8x32, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint16x16, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int16x16, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint32x8, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int32x8, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint64x4, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int64x4, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_float32x8, suffix, _mm256_castps_si256) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_float64x4, suffix, _mm256_castpd_si256) + +OPENCV_HAL_IMPL_AVX_INIT(v_uint8x32, uchar, u8, epi8, char) +OPENCV_HAL_IMPL_AVX_INIT(v_int8x32, schar, s8, epi8, char) +OPENCV_HAL_IMPL_AVX_INIT(v_uint16x16, ushort, u16, epi16, short) +OPENCV_HAL_IMPL_AVX_INIT(v_int16x16, short, s16, epi16, short) +OPENCV_HAL_IMPL_AVX_INIT(v_uint32x8, unsigned, u32, epi32, int) +OPENCV_HAL_IMPL_AVX_INIT(v_int32x8, int, s32, epi32, int) +OPENCV_HAL_IMPL_AVX_INIT(v_uint64x4, uint64, u64, epi64x, int64) +OPENCV_HAL_IMPL_AVX_INIT(v_int64x4, int64, s64, epi64x, int64) + +#define OPENCV_HAL_IMPL_AVX_INIT_FLT(_Tpvec, _Tp, suffix, zsuffix, cast) \ + inline _Tpvec v256_setzero_##suffix() \ + { return _Tpvec(_mm256_setzero_##zsuffix()); } \ + inline _Tpvec v256_setall_##suffix(_Tp v) \ + { return _Tpvec(_mm256_set1_##zsuffix(v)); } \ + template <> inline _Tpvec v_setzero_() \ + { return v256_setzero_##suffix(); } \ + template <> inline _Tpvec v_setall_(_Tp v) \ + { return v256_setall_##suffix(v); } \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint8x32, suffix, cast) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int8x32, suffix, cast) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint16x16, suffix, cast) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int16x16, suffix, cast) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint32x8, suffix, cast) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int32x8, suffix, cast) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint64x4, suffix, cast) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int64x4, suffix, cast) + +OPENCV_HAL_IMPL_AVX_INIT_FLT(v_float32x8, float, f32, ps, _mm256_castsi256_ps) +OPENCV_HAL_IMPL_AVX_INIT_FLT(v_float64x4, double, f64, pd, _mm256_castsi256_pd) + +inline v_float32x8 v_reinterpret_as_f32(const v_float32x8& a) +{ return a; } +inline v_float32x8 v_reinterpret_as_f32(const v_float64x4& a) +{ return v_float32x8(_mm256_castpd_ps(a.val)); } + +inline v_float64x4 v_reinterpret_as_f64(const v_float64x4& a) +{ return a; } +inline v_float64x4 v_reinterpret_as_f64(const v_float32x8& a) +{ return v_float64x4(_mm256_castps_pd(a.val)); } + +/* Recombine */ +/*#define OPENCV_HAL_IMPL_AVX_COMBINE(_Tpvec, perm) \ + inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(perm(a.val, b.val, 0x20)); } \ + inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(perm(a.val, b.val, 0x31)); } \ + inline void v_recombine(const _Tpvec& a, const _Tpvec& b, \ + _Tpvec& c, _Tpvec& d) \ + { c = v_combine_low(a, b); d = v_combine_high(a, b); } + +#define OPENCV_HAL_IMPL_AVX_UNPACKS(_Tpvec, suffix) \ + OPENCV_HAL_IMPL_AVX_COMBINE(_Tpvec, _mm256_permute2x128_si256) \ + inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, \ + _Tpvec& b0, _Tpvec& b1) \ + { \ + __m256i v0 = _v256_shuffle_odd_64(a0.val); \ + __m256i v1 = _v256_shuffle_odd_64(a1.val); \ + b0.val = _mm256_unpacklo_##suffix(v0, v1); \ + b1.val = _mm256_unpackhi_##suffix(v0, v1); \ + } + +OPENCV_HAL_IMPL_AVX_UNPACKS(v_uint8x32, epi8) +OPENCV_HAL_IMPL_AVX_UNPACKS(v_int8x32, epi8) +OPENCV_HAL_IMPL_AVX_UNPACKS(v_uint16x16, epi16) +OPENCV_HAL_IMPL_AVX_UNPACKS(v_int16x16, epi16) +OPENCV_HAL_IMPL_AVX_UNPACKS(v_uint32x8, epi32) +OPENCV_HAL_IMPL_AVX_UNPACKS(v_int32x8, epi32) +OPENCV_HAL_IMPL_AVX_UNPACKS(v_uint64x4, epi64) +OPENCV_HAL_IMPL_AVX_UNPACKS(v_int64x4, epi64) +OPENCV_HAL_IMPL_AVX_COMBINE(v_float32x8, _mm256_permute2f128_ps) +OPENCV_HAL_IMPL_AVX_COMBINE(v_float64x4, _mm256_permute2f128_pd) + +inline void v_zip(const v_float32x8& a0, const v_float32x8& a1, v_float32x8& b0, v_float32x8& b1) +{ + __m256 v0 = _mm256_unpacklo_ps(a0.val, a1.val); + __m256 v1 = _mm256_unpackhi_ps(a0.val, a1.val); + v_recombine(v_float32x8(v0), v_float32x8(v1), b0, b1); +} + +inline void v_zip(const v_float64x4& a0, const v_float64x4& a1, v_float64x4& b0, v_float64x4& b1) +{ + __m256d v0 = _v_shuffle_odd_64(a0.val); + __m256d v1 = _v_shuffle_odd_64(a1.val); + b0.val = _mm256_unpacklo_pd(v0, v1); + b1.val = _mm256_unpackhi_pd(v0, v1); +}*/ + +//////////////// Variant Value reordering /////////////// + +// unpacks +#define OPENCV_HAL_IMPL_AVX_UNPACK(_Tpvec, suffix) \ + inline _Tpvec v256_unpacklo(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(_mm256_unpacklo_##suffix(a.val, b.val)); } \ + inline _Tpvec v256_unpackhi(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(_mm256_unpackhi_##suffix(a.val, b.val)); } + +OPENCV_HAL_IMPL_AVX_UNPACK(v_uint8x32, epi8) +OPENCV_HAL_IMPL_AVX_UNPACK(v_int8x32, epi8) +OPENCV_HAL_IMPL_AVX_UNPACK(v_uint16x16, epi16) +OPENCV_HAL_IMPL_AVX_UNPACK(v_int16x16, epi16) +OPENCV_HAL_IMPL_AVX_UNPACK(v_uint32x8, epi32) +OPENCV_HAL_IMPL_AVX_UNPACK(v_int32x8, epi32) +OPENCV_HAL_IMPL_AVX_UNPACK(v_uint64x4, epi64) +OPENCV_HAL_IMPL_AVX_UNPACK(v_int64x4, epi64) +OPENCV_HAL_IMPL_AVX_UNPACK(v_float32x8, ps) +OPENCV_HAL_IMPL_AVX_UNPACK(v_float64x4, pd) + +// blend +#define OPENCV_HAL_IMPL_AVX_BLEND(_Tpvec, suffix) \ + template \ + inline _Tpvec v256_blend(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(_mm256_blend_##suffix(a.val, b.val, m)); } + +OPENCV_HAL_IMPL_AVX_BLEND(v_uint16x16, epi16) +OPENCV_HAL_IMPL_AVX_BLEND(v_int16x16, epi16) +OPENCV_HAL_IMPL_AVX_BLEND(v_uint32x8, epi32) +OPENCV_HAL_IMPL_AVX_BLEND(v_int32x8, epi32) +OPENCV_HAL_IMPL_AVX_BLEND(v_float32x8, ps) +OPENCV_HAL_IMPL_AVX_BLEND(v_float64x4, pd) + +template +inline v_uint64x4 v256_blend(const v_uint64x4& a, const v_uint64x4& b) +{ + enum {M0 = m}; + enum {M1 = (M0 | (M0 << 2)) & 0x33}; + enum {M2 = (M1 | (M1 << 1)) & 0x55}; + enum {MM = M2 | (M2 << 1)}; + return v_uint64x4(_mm256_blend_epi32(a.val, b.val, MM)); +} +template +inline v_int64x4 v256_blend(const v_int64x4& a, const v_int64x4& b) +{ return v_int64x4(v256_blend(v_uint64x4(a.val), v_uint64x4(b.val)).val); } + +// shuffle +// todo: emulate 64bit +#define OPENCV_HAL_IMPL_AVX_SHUFFLE(_Tpvec, intrin) \ + template \ + inline _Tpvec v256_shuffle(const _Tpvec& a) \ + { return _Tpvec(_mm256_##intrin(a.val, m)); } + +OPENCV_HAL_IMPL_AVX_SHUFFLE(v_uint32x8, shuffle_epi32) +OPENCV_HAL_IMPL_AVX_SHUFFLE(v_int32x8, shuffle_epi32) +OPENCV_HAL_IMPL_AVX_SHUFFLE(v_float32x8, permute_ps) +OPENCV_HAL_IMPL_AVX_SHUFFLE(v_float64x4, permute_pd) + +template +inline void v256_zip(const _Tpvec& a, const _Tpvec& b, _Tpvec& ab0, _Tpvec& ab1) +{ + ab0 = v256_unpacklo(a, b); + ab1 = v256_unpackhi(a, b); +} + +template +inline _Tpvec v256_combine_diagonal(const _Tpvec& a, const _Tpvec& b) +{ return _Tpvec(_mm256_blend_epi32(a.val, b.val, 0xf0)); } + +inline v_float32x8 v256_combine_diagonal(const v_float32x8& a, const v_float32x8& b) +{ return v256_blend<0xf0>(a, b); } + +inline v_float64x4 v256_combine_diagonal(const v_float64x4& a, const v_float64x4& b) +{ return v256_blend<0xc>(a, b); } + +template +inline _Tpvec v256_alignr_128(const _Tpvec& a, const _Tpvec& b) +{ return v256_permute2x128<0x21>(a, b); } + +template +inline _Tpvec v256_alignr_64(const _Tpvec& a, const _Tpvec& b) +{ return _Tpvec(_mm256_alignr_epi8(a.val, b.val, 8)); } +inline v_float64x4 v256_alignr_64(const v_float64x4& a, const v_float64x4& b) +{ return v_float64x4(_mm256_shuffle_pd(b.val, a.val, _MM_SHUFFLE(0, 0, 1, 1))); } +// todo: emulate float32 + +template +inline _Tpvec v256_swap_halves(const _Tpvec& a) +{ return v256_permute2x128<1>(a, a); } + +template +inline _Tpvec v256_reverse_64(const _Tpvec& a) +{ return v256_permute4x64<_MM_SHUFFLE(0, 1, 2, 3)>(a); } + +// ZIP +#define OPENCV_HAL_IMPL_AVX_ZIP(_Tpvec) \ + inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ + { return v256_permute2x128<0x20>(a, b); } \ + inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ + { return v256_permute2x128<0x31>(a, b); } \ + inline void v_recombine(const _Tpvec& a, const _Tpvec& b, \ + _Tpvec& c, _Tpvec& d) \ + { \ + _Tpvec a1b0 = v256_alignr_128(a, b); \ + c = v256_combine_diagonal(a, a1b0); \ + d = v256_combine_diagonal(a1b0, b); \ + } \ + inline void v_zip(const _Tpvec& a, const _Tpvec& b, \ + _Tpvec& ab0, _Tpvec& ab1) \ + { \ + _Tpvec ab0ab2, ab1ab3; \ + v256_zip(a, b, ab0ab2, ab1ab3); \ + v_recombine(ab0ab2, ab1ab3, ab0, ab1); \ + } + +OPENCV_HAL_IMPL_AVX_ZIP(v_uint8x32) +OPENCV_HAL_IMPL_AVX_ZIP(v_int8x32) +OPENCV_HAL_IMPL_AVX_ZIP(v_uint16x16) +OPENCV_HAL_IMPL_AVX_ZIP(v_int16x16) +OPENCV_HAL_IMPL_AVX_ZIP(v_uint32x8) +OPENCV_HAL_IMPL_AVX_ZIP(v_int32x8) +OPENCV_HAL_IMPL_AVX_ZIP(v_uint64x4) +OPENCV_HAL_IMPL_AVX_ZIP(v_int64x4) +OPENCV_HAL_IMPL_AVX_ZIP(v_float32x8) +OPENCV_HAL_IMPL_AVX_ZIP(v_float64x4) + +////////// Arithmetic, bitwise and comparison operations ///////// + +/* Element-wise binary and unary operations */ + +/** Arithmetics **/ +#define OPENCV_HAL_IMPL_AVX_BIN_OP(bin_op, _Tpvec, intrin) \ + inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(intrin(a.val, b.val)); } + +OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_uint8x32, _mm256_adds_epu8) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_uint8x32, _mm256_subs_epu8) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_int8x32, _mm256_adds_epi8) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_int8x32, _mm256_subs_epi8) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_uint16x16, _mm256_adds_epu16) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_uint16x16, _mm256_subs_epu16) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_int16x16, _mm256_adds_epi16) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_int16x16, _mm256_subs_epi16) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_uint32x8, _mm256_add_epi32) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_uint32x8, _mm256_sub_epi32) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_mul, v_uint32x8, _mm256_mullo_epi32) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_int32x8, _mm256_add_epi32) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_int32x8, _mm256_sub_epi32) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_mul, v_int32x8, _mm256_mullo_epi32) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_uint64x4, _mm256_add_epi64) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_uint64x4, _mm256_sub_epi64) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_int64x4, _mm256_add_epi64) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_int64x4, _mm256_sub_epi64) + +OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_float32x8, _mm256_add_ps) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_float32x8, _mm256_sub_ps) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_mul, v_float32x8, _mm256_mul_ps) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_div, v_float32x8, _mm256_div_ps) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_float64x4, _mm256_add_pd) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_float64x4, _mm256_sub_pd) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_mul, v_float64x4, _mm256_mul_pd) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_div, v_float64x4, _mm256_div_pd) + +// saturating multiply 8-bit, 16-bit +inline v_uint8x32 v_mul(const v_uint8x32& a, const v_uint8x32& b) +{ + v_uint16x16 c, d; + v_mul_expand(a, b, c, d); + return v_pack(c, d); +} +inline v_int8x32 v_mul(const v_int8x32& a, const v_int8x32& b) +{ + v_int16x16 c, d; + v_mul_expand(a, b, c, d); + return v_pack(c, d); +} +inline v_uint16x16 v_mul(const v_uint16x16& a, const v_uint16x16& b) +{ + __m256i pl = _mm256_mullo_epi16(a.val, b.val); + __m256i ph = _mm256_mulhi_epu16(a.val, b.val); + __m256i p0 = _mm256_unpacklo_epi16(pl, ph); + __m256i p1 = _mm256_unpackhi_epi16(pl, ph); + return v_uint16x16(_v256_packs_epu32(p0, p1)); +} +inline v_int16x16 v_mul(const v_int16x16& a, const v_int16x16& b) +{ + __m256i pl = _mm256_mullo_epi16(a.val, b.val); + __m256i ph = _mm256_mulhi_epi16(a.val, b.val); + __m256i p0 = _mm256_unpacklo_epi16(pl, ph); + __m256i p1 = _mm256_unpackhi_epi16(pl, ph); + return v_int16x16(_mm256_packs_epi32(p0, p1)); +} + +/** Non-saturating arithmetics **/ +#define OPENCV_HAL_IMPL_AVX_BIN_FUNC(func, _Tpvec, intrin) \ + inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(intrin(a.val, b.val)); } + +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_add_wrap, v_uint8x32, _mm256_add_epi8) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_add_wrap, v_int8x32, _mm256_add_epi8) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_add_wrap, v_uint16x16, _mm256_add_epi16) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_add_wrap, v_int16x16, _mm256_add_epi16) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_sub_wrap, v_uint8x32, _mm256_sub_epi8) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_sub_wrap, v_int8x32, _mm256_sub_epi8) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_sub_wrap, v_uint16x16, _mm256_sub_epi16) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_sub_wrap, v_int16x16, _mm256_sub_epi16) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_mul_wrap, v_uint16x16, _mm256_mullo_epi16) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_mul_wrap, v_int16x16, _mm256_mullo_epi16) + +inline v_uint8x32 v_mul_wrap(const v_uint8x32& a, const v_uint8x32& b) +{ + __m256i ad = _mm256_srai_epi16(a.val, 8); + __m256i bd = _mm256_srai_epi16(b.val, 8); + __m256i p0 = _mm256_mullo_epi16(a.val, b.val); // even + __m256i p1 = _mm256_slli_epi16(_mm256_mullo_epi16(ad, bd), 8); // odd + + const __m256i b01 = _mm256_set1_epi32(0xFF00FF00); + return v_uint8x32(_mm256_blendv_epi8(p0, p1, b01)); +} +inline v_int8x32 v_mul_wrap(const v_int8x32& a, const v_int8x32& b) +{ + return v_reinterpret_as_s8(v_mul_wrap(v_reinterpret_as_u8(a), v_reinterpret_as_u8(b))); +} + +// Multiply and expand +inline void v_mul_expand(const v_uint8x32& a, const v_uint8x32& b, + v_uint16x16& c, v_uint16x16& d) +{ + v_uint16x16 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c = v_mul_wrap(a0, b0); + d = v_mul_wrap(a1, b1); +} + +inline void v_mul_expand(const v_int8x32& a, const v_int8x32& b, + v_int16x16& c, v_int16x16& d) +{ + v_int16x16 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c = v_mul_wrap(a0, b0); + d = v_mul_wrap(a1, b1); +} + +inline void v_mul_expand(const v_int16x16& a, const v_int16x16& b, + v_int32x8& c, v_int32x8& d) +{ + v_int16x16 vhi = v_int16x16(_mm256_mulhi_epi16(a.val, b.val)); + + v_int16x16 v0, v1; + v_zip(v_mul_wrap(a, b), vhi, v0, v1); + + c = v_reinterpret_as_s32(v0); + d = v_reinterpret_as_s32(v1); +} + +inline void v_mul_expand(const v_uint16x16& a, const v_uint16x16& b, + v_uint32x8& c, v_uint32x8& d) +{ + v_uint16x16 vhi = v_uint16x16(_mm256_mulhi_epu16(a.val, b.val)); + + v_uint16x16 v0, v1; + v_zip(v_mul_wrap(a, b), vhi, v0, v1); + + c = v_reinterpret_as_u32(v0); + d = v_reinterpret_as_u32(v1); +} + +inline void v_mul_expand(const v_uint32x8& a, const v_uint32x8& b, + v_uint64x4& c, v_uint64x4& d) +{ + __m256i v0 = _mm256_mul_epu32(a.val, b.val); + __m256i v1 = _mm256_mul_epu32(_mm256_srli_epi64(a.val, 32), _mm256_srli_epi64(b.val, 32)); + v_zip(v_uint64x4(v0), v_uint64x4(v1), c, d); +} + +inline v_int16x16 v_mul_hi(const v_int16x16& a, const v_int16x16& b) { return v_int16x16(_mm256_mulhi_epi16(a.val, b.val)); } +inline v_uint16x16 v_mul_hi(const v_uint16x16& a, const v_uint16x16& b) { return v_uint16x16(_mm256_mulhi_epu16(a.val, b.val)); } + +/** Bitwise shifts **/ +#define OPENCV_HAL_IMPL_AVX_SHIFT_OP(_Tpuvec, _Tpsvec, suffix, srai) \ + inline _Tpuvec v_shl(const _Tpuvec& a, int imm) \ + { return _Tpuvec(_mm256_slli_##suffix(a.val, imm)); } \ + inline _Tpsvec v_shl(const _Tpsvec& a, int imm) \ + { return _Tpsvec(_mm256_slli_##suffix(a.val, imm)); } \ + inline _Tpuvec v_shr(const _Tpuvec& a, int imm) \ + { return _Tpuvec(_mm256_srli_##suffix(a.val, imm)); } \ + inline _Tpsvec v_shr(const _Tpsvec& a, int imm) \ + { return _Tpsvec(srai(a.val, imm)); } \ + template \ + inline _Tpuvec v_shl(const _Tpuvec& a) \ + { return _Tpuvec(_mm256_slli_##suffix(a.val, imm)); } \ + template \ + inline _Tpsvec v_shl(const _Tpsvec& a) \ + { return _Tpsvec(_mm256_slli_##suffix(a.val, imm)); } \ + template \ + inline _Tpuvec v_shr(const _Tpuvec& a) \ + { return _Tpuvec(_mm256_srli_##suffix(a.val, imm)); } \ + template \ + inline _Tpsvec v_shr(const _Tpsvec& a) \ + { return _Tpsvec(srai(a.val, imm)); } + +OPENCV_HAL_IMPL_AVX_SHIFT_OP(v_uint16x16, v_int16x16, epi16, _mm256_srai_epi16) +OPENCV_HAL_IMPL_AVX_SHIFT_OP(v_uint32x8, v_int32x8, epi32, _mm256_srai_epi32) + +inline __m256i _mm256_srai_epi64xx(const __m256i a, int imm) +{ + __m256i d = _mm256_set1_epi64x((int64)1 << 63); + __m256i r = _mm256_srli_epi64(_mm256_add_epi64(a, d), imm); + return _mm256_sub_epi64(r, _mm256_srli_epi64(d, imm)); +} +OPENCV_HAL_IMPL_AVX_SHIFT_OP(v_uint64x4, v_int64x4, epi64, _mm256_srai_epi64xx) + + +/** Bitwise logic **/ +#define OPENCV_HAL_IMPL_AVX_LOGIC_OP(_Tpvec, suffix, not_const) \ + OPENCV_HAL_IMPL_AVX_BIN_OP(v_and, _Tpvec, _mm256_and_##suffix) \ + OPENCV_HAL_IMPL_AVX_BIN_OP(v_or, _Tpvec, _mm256_or_##suffix) \ + OPENCV_HAL_IMPL_AVX_BIN_OP(v_xor, _Tpvec, _mm256_xor_##suffix) \ + inline _Tpvec v_not(const _Tpvec& a) \ + { return _Tpvec(_mm256_xor_##suffix(a.val, not_const)); } + +OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_uint8x32, si256, _mm256_set1_epi32(-1)) +OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_int8x32, si256, _mm256_set1_epi32(-1)) +OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_uint16x16, si256, _mm256_set1_epi32(-1)) +OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_int16x16, si256, _mm256_set1_epi32(-1)) +OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_uint32x8, si256, _mm256_set1_epi32(-1)) +OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_int32x8, si256, _mm256_set1_epi32(-1)) +OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_uint64x4, si256, _mm256_set1_epi64x(-1)) +OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_int64x4, si256, _mm256_set1_epi64x(-1)) +OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_float32x8, ps, _mm256_castsi256_ps(_mm256_set1_epi32(-1))) +OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_float64x4, pd, _mm256_castsi256_pd(_mm256_set1_epi32(-1))) + +/** Select **/ +#define OPENCV_HAL_IMPL_AVX_SELECT(_Tpvec, suffix) \ + inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(_mm256_blendv_##suffix(b.val, a.val, mask.val)); } + +OPENCV_HAL_IMPL_AVX_SELECT(v_uint8x32, epi8) +OPENCV_HAL_IMPL_AVX_SELECT(v_int8x32, epi8) +OPENCV_HAL_IMPL_AVX_SELECT(v_uint16x16, epi8) +OPENCV_HAL_IMPL_AVX_SELECT(v_int16x16, epi8) +OPENCV_HAL_IMPL_AVX_SELECT(v_uint32x8, epi8) +OPENCV_HAL_IMPL_AVX_SELECT(v_int32x8, epi8) +OPENCV_HAL_IMPL_AVX_SELECT(v_float32x8, ps) +OPENCV_HAL_IMPL_AVX_SELECT(v_float64x4, pd) + +/** Comparison **/ +#define OPENCV_HAL_IMPL_AVX_CMP_OP_OV(_Tpvec) \ + inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ + { return v_not(v_eq(a, b)); } \ + inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ + { return v_gt(b, a); } \ + inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ + { return v_not(v_lt(a, b)); } \ + inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ + { return v_ge(b, a); } + +#define OPENCV_HAL_IMPL_AVX_CMP_OP_INT(_Tpuvec, _Tpsvec, suffix, sbit) \ + inline _Tpuvec v_eq(const _Tpuvec& a, const _Tpuvec& b) \ + { return _Tpuvec(_mm256_cmpeq_##suffix(a.val, b.val)); } \ + inline _Tpuvec v_gt(const _Tpuvec& a, const _Tpuvec& b) \ + { \ + __m256i smask = _mm256_set1_##suffix(sbit); \ + return _Tpuvec(_mm256_cmpgt_##suffix( \ + _mm256_xor_si256(a.val, smask), \ + _mm256_xor_si256(b.val, smask))); \ + } \ + inline _Tpsvec v_eq(const _Tpsvec& a, const _Tpsvec& b) \ + { return _Tpsvec(_mm256_cmpeq_##suffix(a.val, b.val)); } \ + inline _Tpsvec v_gt(const _Tpsvec& a, const _Tpsvec& b) \ + { return _Tpsvec(_mm256_cmpgt_##suffix(a.val, b.val)); } \ + OPENCV_HAL_IMPL_AVX_CMP_OP_OV(_Tpuvec) \ + OPENCV_HAL_IMPL_AVX_CMP_OP_OV(_Tpsvec) + +OPENCV_HAL_IMPL_AVX_CMP_OP_INT(v_uint8x32, v_int8x32, epi8, (char)-128) +OPENCV_HAL_IMPL_AVX_CMP_OP_INT(v_uint16x16, v_int16x16, epi16, (short)-32768) +OPENCV_HAL_IMPL_AVX_CMP_OP_INT(v_uint32x8, v_int32x8, epi32, (int)0x80000000) + +#define OPENCV_HAL_IMPL_AVX_CMP_OP_64BIT(_Tpvec) \ + inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(_mm256_cmpeq_epi64(a.val, b.val)); } \ + inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ + { return v_not(v_eq(a, b)); } + +OPENCV_HAL_IMPL_AVX_CMP_OP_64BIT(v_uint64x4) +OPENCV_HAL_IMPL_AVX_CMP_OP_64BIT(v_int64x4) + +#define OPENCV_HAL_IMPL_AVX_CMP_FLT(bin_op, imm8, _Tpvec, suffix) \ + inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(_mm256_cmp_##suffix(a.val, b.val, imm8)); } + +#define OPENCV_HAL_IMPL_AVX_CMP_OP_FLT(_Tpvec, suffix) \ + OPENCV_HAL_IMPL_AVX_CMP_FLT(v_eq, _CMP_EQ_OQ, _Tpvec, suffix) \ + OPENCV_HAL_IMPL_AVX_CMP_FLT(v_ne, _CMP_NEQ_OQ, _Tpvec, suffix) \ + OPENCV_HAL_IMPL_AVX_CMP_FLT(v_lt, _CMP_LT_OQ, _Tpvec, suffix) \ + OPENCV_HAL_IMPL_AVX_CMP_FLT(v_gt, _CMP_GT_OQ, _Tpvec, suffix) \ + OPENCV_HAL_IMPL_AVX_CMP_FLT(v_le, _CMP_LE_OQ, _Tpvec, suffix) \ + OPENCV_HAL_IMPL_AVX_CMP_FLT(v_ge, _CMP_GE_OQ, _Tpvec, suffix) + +OPENCV_HAL_IMPL_AVX_CMP_OP_FLT(v_float32x8, ps) +OPENCV_HAL_IMPL_AVX_CMP_OP_FLT(v_float64x4, pd) + +inline v_float32x8 v_not_nan(const v_float32x8& a) +{ return v_float32x8(_mm256_cmp_ps(a.val, a.val, _CMP_ORD_Q)); } +inline v_float64x4 v_not_nan(const v_float64x4& a) +{ return v_float64x4(_mm256_cmp_pd(a.val, a.val, _CMP_ORD_Q)); } + +/** min/max **/ +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_uint8x32, _mm256_min_epu8) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_uint8x32, _mm256_max_epu8) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_int8x32, _mm256_min_epi8) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_int8x32, _mm256_max_epi8) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_uint16x16, _mm256_min_epu16) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_uint16x16, _mm256_max_epu16) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_int16x16, _mm256_min_epi16) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_int16x16, _mm256_max_epi16) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_uint32x8, _mm256_min_epu32) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_uint32x8, _mm256_max_epu32) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_int32x8, _mm256_min_epi32) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_int32x8, _mm256_max_epi32) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_float32x8, _mm256_min_ps) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_float32x8, _mm256_max_ps) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_float64x4, _mm256_min_pd) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_float64x4, _mm256_max_pd) + +/** Rotate **/ +template +inline v_uint8x32 v_rotate_left(const v_uint8x32& a, const v_uint8x32& b) +{ + enum {IMM_R = (16 - imm) & 0xFF}; + enum {IMM_R2 = (32 - imm) & 0xFF}; + + if (imm == 0) return a; + if (imm == 32) return b; + if (imm > 32) return v_uint8x32(); + + __m256i swap = _mm256_permute2x128_si256(a.val, b.val, 0x03); + if (imm == 16) return v_uint8x32(swap); + if (imm < 16) return v_uint8x32(_mm256_alignr_epi8(a.val, swap, IMM_R)); + return v_uint8x32(_mm256_alignr_epi8(swap, b.val, IMM_R2)); // imm < 32 +} + +template +inline v_uint8x32 v_rotate_right(const v_uint8x32& a, const v_uint8x32& b) +{ + enum {IMM_L = (imm - 16) & 0xFF}; + + if (imm == 0) return a; + if (imm == 32) return b; + if (imm > 32) return v_uint8x32(); + + __m256i swap = _mm256_permute2x128_si256(a.val, b.val, 0x21); + if (imm == 16) return v_uint8x32(swap); + if (imm < 16) return v_uint8x32(_mm256_alignr_epi8(swap, a.val, imm)); + return v_uint8x32(_mm256_alignr_epi8(b.val, swap, IMM_L)); +} + +template +inline v_uint8x32 v_rotate_left(const v_uint8x32& a) +{ + enum {IMM_L = (imm - 16) & 0xFF}; + enum {IMM_R = (16 - imm) & 0xFF}; + + if (imm == 0) return a; + if (imm > 32) return v_uint8x32(); + + // ESAC control[3] ? [127:0] = 0 + __m256i swapz = _mm256_permute2x128_si256(a.val, a.val, _MM_SHUFFLE(0, 0, 2, 0)); + if (imm == 16) return v_uint8x32(swapz); + if (imm < 16) return v_uint8x32(_mm256_alignr_epi8(a.val, swapz, IMM_R)); + return v_uint8x32(_mm256_slli_si256(swapz, IMM_L)); +} + +template +inline v_uint8x32 v_rotate_right(const v_uint8x32& a) +{ + enum {IMM_L = (imm - 16) & 0xFF}; + + if (imm == 0) return a; + if (imm > 32) return v_uint8x32(); + + // ESAC control[3] ? [127:0] = 0 + __m256i swapz = _mm256_permute2x128_si256(a.val, a.val, _MM_SHUFFLE(2, 0, 0, 1)); + if (imm == 16) return v_uint8x32(swapz); + if (imm < 16) return v_uint8x32(_mm256_alignr_epi8(swapz, a.val, imm)); + return v_uint8x32(_mm256_srli_si256(swapz, IMM_L)); +} + +#define OPENCV_HAL_IMPL_AVX_ROTATE_CAST(intrin, _Tpvec, cast) \ + template \ + inline _Tpvec intrin(const _Tpvec& a, const _Tpvec& b) \ + { \ + enum {IMMxW = imm * sizeof(typename _Tpvec::lane_type)}; \ + v_uint8x32 ret = intrin(v_reinterpret_as_u8(a), \ + v_reinterpret_as_u8(b)); \ + return _Tpvec(cast(ret.val)); \ + } \ + template \ + inline _Tpvec intrin(const _Tpvec& a) \ + { \ + enum {IMMxW = imm * sizeof(typename _Tpvec::lane_type)}; \ + v_uint8x32 ret = intrin(v_reinterpret_as_u8(a)); \ + return _Tpvec(cast(ret.val)); \ + } + +#define OPENCV_HAL_IMPL_AVX_ROTATE(_Tpvec) \ + OPENCV_HAL_IMPL_AVX_ROTATE_CAST(v_rotate_left, _Tpvec, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX_ROTATE_CAST(v_rotate_right, _Tpvec, OPENCV_HAL_NOP) + +OPENCV_HAL_IMPL_AVX_ROTATE(v_int8x32) +OPENCV_HAL_IMPL_AVX_ROTATE(v_uint16x16) +OPENCV_HAL_IMPL_AVX_ROTATE(v_int16x16) +OPENCV_HAL_IMPL_AVX_ROTATE(v_uint32x8) +OPENCV_HAL_IMPL_AVX_ROTATE(v_int32x8) +OPENCV_HAL_IMPL_AVX_ROTATE(v_uint64x4) +OPENCV_HAL_IMPL_AVX_ROTATE(v_int64x4) + +OPENCV_HAL_IMPL_AVX_ROTATE_CAST(v_rotate_left, v_float32x8, _mm256_castsi256_ps) +OPENCV_HAL_IMPL_AVX_ROTATE_CAST(v_rotate_right, v_float32x8, _mm256_castsi256_ps) +OPENCV_HAL_IMPL_AVX_ROTATE_CAST(v_rotate_left, v_float64x4, _mm256_castsi256_pd) +OPENCV_HAL_IMPL_AVX_ROTATE_CAST(v_rotate_right, v_float64x4, _mm256_castsi256_pd) + +/** Reverse **/ +inline v_uint8x32 v_reverse(const v_uint8x32 &a) +{ + static const __m256i perm = _mm256_setr_epi8( + 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, + 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); + __m256i vec = _mm256_shuffle_epi8(a.val, perm); + return v_uint8x32(_mm256_permute2x128_si256(vec, vec, 1)); +} + +inline v_int8x32 v_reverse(const v_int8x32 &a) +{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } + +inline v_uint16x16 v_reverse(const v_uint16x16 &a) +{ + static const __m256i perm = _mm256_setr_epi8( + 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1, + 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1); + __m256i vec = _mm256_shuffle_epi8(a.val, perm); + return v_uint16x16(_mm256_permute2x128_si256(vec, vec, 1)); +} + +inline v_int16x16 v_reverse(const v_int16x16 &a) +{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } + +inline v_uint32x8 v_reverse(const v_uint32x8 &a) +{ + static const __m256i perm = _mm256_setr_epi32(7, 6, 5, 4, 3, 2, 1, 0); + return v_uint32x8(_mm256_permutevar8x32_epi32(a.val, perm)); +} + +inline v_int32x8 v_reverse(const v_int32x8 &a) +{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_float32x8 v_reverse(const v_float32x8 &a) +{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_uint64x4 v_reverse(const v_uint64x4 &a) +{ + return v_uint64x4(_mm256_permute4x64_epi64(a.val, _MM_SHUFFLE(0, 1, 2, 3))); +} + +inline v_int64x4 v_reverse(const v_int64x4 &a) +{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } + +inline v_float64x4 v_reverse(const v_float64x4 &a) +{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } + +////////// Reduce and mask ///////// + +/** Reduce **/ +inline unsigned v_reduce_sum(const v_uint8x32& a) +{ + __m256i half = _mm256_sad_epu8(a.val, _mm256_setzero_si256()); + __m128i quarter = _mm_add_epi32(_v256_extract_low(half), _v256_extract_high(half)); + return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(quarter, _mm_unpackhi_epi64(quarter, quarter))); +} +inline int v_reduce_sum(const v_int8x32& a) +{ + __m256i half = _mm256_sad_epu8(_mm256_xor_si256(a.val, _mm256_set1_epi8((schar)-128)), _mm256_setzero_si256()); + __m128i quarter = _mm_add_epi32(_v256_extract_low(half), _v256_extract_high(half)); + return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(quarter, _mm_unpackhi_epi64(quarter, quarter))) - 4096; +} +#define OPENCV_HAL_IMPL_AVX_REDUCE_32(_Tpvec, sctype, func, intrin) \ + inline sctype v_reduce_##func(const _Tpvec& a) \ + { \ + __m128i val = intrin(_v256_extract_low(a.val), _v256_extract_high(a.val)); \ + val = intrin(val, _mm_srli_si128(val,8)); \ + val = intrin(val, _mm_srli_si128(val,4)); \ + val = intrin(val, _mm_srli_si128(val,2)); \ + val = intrin(val, _mm_srli_si128(val,1)); \ + return (sctype)_mm_cvtsi128_si32(val); \ + } + +OPENCV_HAL_IMPL_AVX_REDUCE_32(v_uint8x32, uchar, min, _mm_min_epu8) +OPENCV_HAL_IMPL_AVX_REDUCE_32(v_int8x32, schar, min, _mm_min_epi8) +OPENCV_HAL_IMPL_AVX_REDUCE_32(v_uint8x32, uchar, max, _mm_max_epu8) +OPENCV_HAL_IMPL_AVX_REDUCE_32(v_int8x32, schar, max, _mm_max_epi8) + +#define OPENCV_HAL_IMPL_AVX_REDUCE_16(_Tpvec, sctype, func, intrin) \ + inline sctype v_reduce_##func(const _Tpvec& a) \ + { \ + __m128i v0 = _v256_extract_low(a.val); \ + __m128i v1 = _v256_extract_high(a.val); \ + v0 = intrin(v0, v1); \ + v0 = intrin(v0, _mm_srli_si128(v0, 8)); \ + v0 = intrin(v0, _mm_srli_si128(v0, 4)); \ + v0 = intrin(v0, _mm_srli_si128(v0, 2)); \ + return (sctype) _mm_cvtsi128_si32(v0); \ + } + +OPENCV_HAL_IMPL_AVX_REDUCE_16(v_uint16x16, ushort, min, _mm_min_epu16) +OPENCV_HAL_IMPL_AVX_REDUCE_16(v_int16x16, short, min, _mm_min_epi16) +OPENCV_HAL_IMPL_AVX_REDUCE_16(v_uint16x16, ushort, max, _mm_max_epu16) +OPENCV_HAL_IMPL_AVX_REDUCE_16(v_int16x16, short, max, _mm_max_epi16) + +#define OPENCV_HAL_IMPL_AVX_REDUCE_8(_Tpvec, sctype, func, intrin) \ + inline sctype v_reduce_##func(const _Tpvec& a) \ + { \ + __m128i v0 = _v256_extract_low(a.val); \ + __m128i v1 = _v256_extract_high(a.val); \ + v0 = intrin(v0, v1); \ + v0 = intrin(v0, _mm_srli_si128(v0, 8)); \ + v0 = intrin(v0, _mm_srli_si128(v0, 4)); \ + return (sctype) _mm_cvtsi128_si32(v0); \ + } + +OPENCV_HAL_IMPL_AVX_REDUCE_8(v_uint32x8, unsigned, min, _mm_min_epu32) +OPENCV_HAL_IMPL_AVX_REDUCE_8(v_int32x8, int, min, _mm_min_epi32) +OPENCV_HAL_IMPL_AVX_REDUCE_8(v_uint32x8, unsigned, max, _mm_max_epu32) +OPENCV_HAL_IMPL_AVX_REDUCE_8(v_int32x8, int, max, _mm_max_epi32) + +#define OPENCV_HAL_IMPL_AVX_REDUCE_FLT(func, intrin) \ + inline float v_reduce_##func(const v_float32x8& a) \ + { \ + __m128 v0 = _v256_extract_low(a.val); \ + __m128 v1 = _v256_extract_high(a.val); \ + v0 = intrin(v0, v1); \ + v0 = intrin(v0, _mm_permute_ps(v0, _MM_SHUFFLE(0, 0, 3, 2))); \ + v0 = intrin(v0, _mm_permute_ps(v0, _MM_SHUFFLE(0, 0, 0, 1))); \ + return _mm_cvtss_f32(v0); \ + } + +OPENCV_HAL_IMPL_AVX_REDUCE_FLT(min, _mm_min_ps) +OPENCV_HAL_IMPL_AVX_REDUCE_FLT(max, _mm_max_ps) + +inline int v_reduce_sum(const v_int32x8& a) +{ + __m256i s0 = _mm256_hadd_epi32(a.val, a.val); + s0 = _mm256_hadd_epi32(s0, s0); + + __m128i s1 = _v256_extract_high(s0); + s1 = _mm_add_epi32(_v256_extract_low(s0), s1); + + return _mm_cvtsi128_si32(s1); +} + +inline unsigned v_reduce_sum(const v_uint32x8& a) +{ return v_reduce_sum(v_reinterpret_as_s32(a)); } + +inline int v_reduce_sum(const v_int16x16& a) +{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } +inline unsigned v_reduce_sum(const v_uint16x16& a) +{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } + +inline float v_reduce_sum(const v_float32x8& a) +{ + __m256 s0 = _mm256_hadd_ps(a.val, a.val); + s0 = _mm256_hadd_ps(s0, s0); + + __m128 s1 = _v256_extract_high(s0); + s1 = _mm_add_ps(_v256_extract_low(s0), s1); + + return _mm_cvtss_f32(s1); +} + +inline uint64 v_reduce_sum(const v_uint64x4& a) +{ + uint64 CV_DECL_ALIGNED(32) idx[2]; + _mm_store_si128((__m128i*)idx, _mm_add_epi64(_v256_extract_low(a.val), _v256_extract_high(a.val))); + return idx[0] + idx[1]; +} +inline int64 v_reduce_sum(const v_int64x4& a) +{ + int64 CV_DECL_ALIGNED(32) idx[2]; + _mm_store_si128((__m128i*)idx, _mm_add_epi64(_v256_extract_low(a.val), _v256_extract_high(a.val))); + return idx[0] + idx[1]; +} +inline double v_reduce_sum(const v_float64x4& a) +{ + __m256d s0 = _mm256_hadd_pd(a.val, a.val); + return _mm_cvtsd_f64(_mm_add_pd(_v256_extract_low(s0), _v256_extract_high(s0))); +} + +inline v_float32x8 v_reduce_sum4(const v_float32x8& a, const v_float32x8& b, + const v_float32x8& c, const v_float32x8& d) +{ + __m256 ab = _mm256_hadd_ps(a.val, b.val); + __m256 cd = _mm256_hadd_ps(c.val, d.val); + return v_float32x8(_mm256_hadd_ps(ab, cd)); +} + +inline unsigned v_reduce_sad(const v_uint8x32& a, const v_uint8x32& b) +{ + __m256i half = _mm256_sad_epu8(a.val, b.val); + __m128i quarter = _mm_add_epi32(_v256_extract_low(half), _v256_extract_high(half)); + return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(quarter, _mm_unpackhi_epi64(quarter, quarter))); +} +inline unsigned v_reduce_sad(const v_int8x32& a, const v_int8x32& b) +{ + __m256i half = _mm256_set1_epi8(0x7f); + half = _mm256_sad_epu8(_mm256_add_epi8(a.val, half), _mm256_add_epi8(b.val, half)); + __m128i quarter = _mm_add_epi32(_v256_extract_low(half), _v256_extract_high(half)); + return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(quarter, _mm_unpackhi_epi64(quarter, quarter))); +} +inline unsigned v_reduce_sad(const v_uint16x16& a, const v_uint16x16& b) +{ + v_uint32x8 l, h; + v_expand(v_add_wrap(v_sub(a, b), v_sub(b, a)), l, h); + return v_reduce_sum(v_add(l, h)); +} +inline unsigned v_reduce_sad(const v_int16x16& a, const v_int16x16& b) +{ + v_uint32x8 l, h; + v_expand(v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))), l, h); + return v_reduce_sum(v_add(l, h)); +} +inline unsigned v_reduce_sad(const v_uint32x8& a, const v_uint32x8& b) +{ + return v_reduce_sum(v_sub(v_max(a, b), v_min(a, b))); +} +inline unsigned v_reduce_sad(const v_int32x8& a, const v_int32x8& b) +{ + v_int32x8 m = v_lt(a, b); + return v_reduce_sum(v_reinterpret_as_u32(v_sub(v_xor(v_sub(a, b), m), m))); +} +inline float v_reduce_sad(const v_float32x8& a, const v_float32x8& b) +{ + return v_reduce_sum(v_and(v_sub(a, b), v_float32x8(_mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffff))))); +} + +/** Popcount **/ +inline v_uint8x32 v_popcount(const v_uint8x32& a) +{ + __m256i _popcnt_table = _mm256_setr_epi8(0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4); + __m256i _popcnt_mask = _mm256_set1_epi8(0x0F); + return v_uint8x32(_mm256_add_epi8(_mm256_shuffle_epi8(_popcnt_table, _mm256_and_si256( a.val , _popcnt_mask)), + _mm256_shuffle_epi8(_popcnt_table, _mm256_and_si256(_mm256_srli_epi16(a.val, 4), _popcnt_mask)))); +} +inline v_uint16x16 v_popcount(const v_uint16x16& a) +{ + v_uint8x32 p = v_popcount(v_reinterpret_as_u8(a)); + p = v_add(p, v_rotate_right<1>(p)); + return v_and(v_reinterpret_as_u16(p), v256_setall_u16(0x00ff)); +} +inline v_uint32x8 v_popcount(const v_uint32x8& a) +{ + v_uint8x32 p = v_popcount(v_reinterpret_as_u8(a)); + p = v_add(p, v_rotate_right<1>(p)); + p = v_add(p, v_rotate_right<2>(p)); + return v_and(v_reinterpret_as_u32(p), v256_setall_u32(0x000000ff)); +} +inline v_uint64x4 v_popcount(const v_uint64x4& a) +{ + return v_uint64x4(_mm256_sad_epu8(v_popcount(v_reinterpret_as_u8(a)).val, _mm256_setzero_si256())); +} +inline v_uint8x32 v_popcount(const v_int8x32& a) +{ return v_popcount(v_reinterpret_as_u8(a)); } +inline v_uint16x16 v_popcount(const v_int16x16& a) +{ return v_popcount(v_reinterpret_as_u16(a)); } +inline v_uint32x8 v_popcount(const v_int32x8& a) +{ return v_popcount(v_reinterpret_as_u32(a)); } +inline v_uint64x4 v_popcount(const v_int64x4& a) +{ return v_popcount(v_reinterpret_as_u64(a)); } + +/** Mask **/ +inline int v_signmask(const v_int8x32& a) +{ return _mm256_movemask_epi8(a.val); } +inline int v_signmask(const v_uint8x32& a) +{ return v_signmask(v_reinterpret_as_s8(a)); } + +inline int v_signmask(const v_int16x16& a) +{ return v_signmask(v_pack(a, a)) & 0xFFFF; } +inline int v_signmask(const v_uint16x16& a) +{ return v_signmask(v_reinterpret_as_s16(a)); } + +inline int v_signmask(const v_float32x8& a) +{ return _mm256_movemask_ps(a.val); } +inline int v_signmask(const v_float64x4& a) +{ return _mm256_movemask_pd(a.val); } + +inline int v_signmask(const v_int32x8& a) +{ return v_signmask(v_reinterpret_as_f32(a)); } +inline int v_signmask(const v_uint32x8& a) +{ return v_signmask(v_reinterpret_as_f32(a)); } + +inline int v_signmask(const v_int64x4& a) +{ return v_signmask(v_reinterpret_as_f64(a)); } +inline int v_signmask(const v_uint64x4& a) +{ return v_signmask(v_reinterpret_as_f64(a)); } + +inline int v_scan_forward(const v_int8x32& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } +inline int v_scan_forward(const v_uint8x32& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } +inline int v_scan_forward(const v_int16x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } +inline int v_scan_forward(const v_uint16x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } +inline int v_scan_forward(const v_int32x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_uint32x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_float32x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_int64x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } +inline int v_scan_forward(const v_uint64x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } +inline int v_scan_forward(const v_float64x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } + +/** Checks **/ +#define OPENCV_HAL_IMPL_AVX_CHECK(_Tpvec, allmask) \ + inline bool v_check_all(const _Tpvec& a) { return v_signmask(a) == allmask; } \ + inline bool v_check_any(const _Tpvec& a) { return v_signmask(a) != 0; } +OPENCV_HAL_IMPL_AVX_CHECK(v_uint8x32, -1) +OPENCV_HAL_IMPL_AVX_CHECK(v_int8x32, -1) +OPENCV_HAL_IMPL_AVX_CHECK(v_uint32x8, 255) +OPENCV_HAL_IMPL_AVX_CHECK(v_int32x8, 255) +OPENCV_HAL_IMPL_AVX_CHECK(v_uint64x4, 15) +OPENCV_HAL_IMPL_AVX_CHECK(v_int64x4, 15) +OPENCV_HAL_IMPL_AVX_CHECK(v_float32x8, 255) +OPENCV_HAL_IMPL_AVX_CHECK(v_float64x4, 15) + +#define OPENCV_HAL_IMPL_AVX_CHECK_SHORT(_Tpvec) \ + inline bool v_check_all(const _Tpvec& a) { return (v_signmask(v_reinterpret_as_s8(a)) & 0xaaaaaaaa) == 0xaaaaaaaa; } \ + inline bool v_check_any(const _Tpvec& a) { return (v_signmask(v_reinterpret_as_s8(a)) & 0xaaaaaaaa) != 0; } +OPENCV_HAL_IMPL_AVX_CHECK_SHORT(v_uint16x16) +OPENCV_HAL_IMPL_AVX_CHECK_SHORT(v_int16x16) + +////////// Other math ///////// + +/** Some frequent operations **/ +#if CV_FMA3 +#define OPENCV_HAL_IMPL_AVX_MULADD(_Tpvec, suffix) \ + inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ + { return _Tpvec(_mm256_fmadd_##suffix(a.val, b.val, c.val)); } \ + inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ + { return _Tpvec(_mm256_fmadd_##suffix(a.val, b.val, c.val)); } +#else +#define OPENCV_HAL_IMPL_AVX_MULADD(_Tpvec, suffix) \ + inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ + { return _Tpvec(_mm256_add_##suffix(_mm256_mul_##suffix(a.val, b.val), c.val)); } \ + inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ + { return _Tpvec(_mm256_add_##suffix(_mm256_mul_##suffix(a.val, b.val), c.val)); } +#endif + +#define OPENCV_HAL_IMPL_AVX_MISC(_Tpvec, suffix) \ + inline _Tpvec v_sqrt(const _Tpvec& x) \ + { return _Tpvec(_mm256_sqrt_##suffix(x.val)); } \ + inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ + { return v_fma(a, a, v_mul(b, b)); } \ + inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ + { return v_sqrt(v_fma(a, a, v_mul(b, b))); } + +OPENCV_HAL_IMPL_AVX_MULADD(v_float32x8, ps) +OPENCV_HAL_IMPL_AVX_MULADD(v_float64x4, pd) +OPENCV_HAL_IMPL_AVX_MISC(v_float32x8, ps) +OPENCV_HAL_IMPL_AVX_MISC(v_float64x4, pd) + +inline v_int32x8 v_fma(const v_int32x8& a, const v_int32x8& b, const v_int32x8& c) +{ + return v_add(v_mul(a, b), c); +} + +inline v_int32x8 v_muladd(const v_int32x8& a, const v_int32x8& b, const v_int32x8& c) +{ + return v_fma(a, b, c); +} + +inline v_float32x8 v_invsqrt(const v_float32x8& x) +{ + v_float32x8 half = v_mul(x, v256_setall_f32(0.5)); + v_float32x8 t = v_float32x8(_mm256_rsqrt_ps(x.val)); + // todo: _mm256_fnmsub_ps + t = v_mul(t, v_sub(v256_setall_f32(1.5), v_mul(v_mul(t, t), half))); + return t; +} + +inline v_float64x4 v_invsqrt(const v_float64x4& x) +{ + return v_div(v256_setall_f64(1.), v_sqrt(x)); +} + +/** Absolute values **/ +#define OPENCV_HAL_IMPL_AVX_ABS(_Tpvec, suffix) \ + inline v_u##_Tpvec v_abs(const v_##_Tpvec& x) \ + { return v_u##_Tpvec(_mm256_abs_##suffix(x.val)); } + +OPENCV_HAL_IMPL_AVX_ABS(int8x32, epi8) +OPENCV_HAL_IMPL_AVX_ABS(int16x16, epi16) +OPENCV_HAL_IMPL_AVX_ABS(int32x8, epi32) + +inline v_float32x8 v_abs(const v_float32x8& x) +{ return v_and(x, v_float32x8(_mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffff)))); } +inline v_float64x4 v_abs(const v_float64x4& x) +{ return v_and(x, v_float64x4(_mm256_castsi256_pd(_mm256_srli_epi64(_mm256_set1_epi64x(-1), 1)))); } + +/** Absolute difference **/ +inline v_uint8x32 v_absdiff(const v_uint8x32& a, const v_uint8x32& b) +{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } +inline v_uint16x16 v_absdiff(const v_uint16x16& a, const v_uint16x16& b) +{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } +inline v_uint32x8 v_absdiff(const v_uint32x8& a, const v_uint32x8& b) +{ return v_sub(v_max(a, b), v_min(a, b)); } + +inline v_uint8x32 v_absdiff(const v_int8x32& a, const v_int8x32& b) +{ + v_int8x32 d = v_sub_wrap(a, b); + v_int8x32 m = v_lt(a, b); + return v_reinterpret_as_u8(v_sub_wrap(v_xor(d, m), m)); +} + +inline v_uint16x16 v_absdiff(const v_int16x16& a, const v_int16x16& b) +{ return v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))); } + +inline v_uint32x8 v_absdiff(const v_int32x8& a, const v_int32x8& b) +{ + v_int32x8 d = v_sub(a, b); + v_int32x8 m = v_lt(a, b); + return v_reinterpret_as_u32(v_sub(v_xor(d, m), m)); +} + +inline v_float32x8 v_absdiff(const v_float32x8& a, const v_float32x8& b) +{ return v_abs(v_sub(a, b)); } + +inline v_float64x4 v_absdiff(const v_float64x4& a, const v_float64x4& b) +{ return v_abs(v_sub(a, b)); } + +/** Saturating absolute difference **/ +inline v_int8x32 v_absdiffs(const v_int8x32& a, const v_int8x32& b) +{ + v_int8x32 d = v_sub(a, b); + v_int8x32 m = v_lt(a, b); + return v_sub(v_xor(d, m), m); +} +inline v_int16x16 v_absdiffs(const v_int16x16& a, const v_int16x16& b) +{ return v_sub(v_max(a, b), v_min(a, b)); } + +////////// Conversions ///////// + +/** Rounding **/ +inline v_int32x8 v_round(const v_float32x8& a) +{ return v_int32x8(_mm256_cvtps_epi32(a.val)); } + +inline v_int32x8 v_round(const v_float64x4& a) +{ return v_int32x8(_mm256_castsi128_si256(_mm256_cvtpd_epi32(a.val))); } + +inline v_int32x8 v_round(const v_float64x4& a, const v_float64x4& b) +{ + __m128i ai = _mm256_cvtpd_epi32(a.val), bi = _mm256_cvtpd_epi32(b.val); + return v_int32x8(_v256_combine(ai, bi)); +} + +inline v_int32x8 v_trunc(const v_float32x8& a) +{ return v_int32x8(_mm256_cvttps_epi32(a.val)); } + +inline v_int32x8 v_trunc(const v_float64x4& a) +{ return v_int32x8(_mm256_castsi128_si256(_mm256_cvttpd_epi32(a.val))); } + +inline v_int32x8 v_floor(const v_float32x8& a) +{ return v_int32x8(_mm256_cvttps_epi32(_mm256_floor_ps(a.val))); } + +inline v_int32x8 v_floor(const v_float64x4& a) +{ return v_trunc(v_float64x4(_mm256_floor_pd(a.val))); } + +inline v_int32x8 v_ceil(const v_float32x8& a) +{ return v_int32x8(_mm256_cvttps_epi32(_mm256_ceil_ps(a.val))); } + +inline v_int32x8 v_ceil(const v_float64x4& a) +{ return v_trunc(v_float64x4(_mm256_ceil_pd(a.val))); } + +/** To float **/ +inline v_float32x8 v_cvt_f32(const v_int32x8& a) +{ return v_float32x8(_mm256_cvtepi32_ps(a.val)); } + +inline v_float32x8 v_cvt_f32(const v_float64x4& a) +{ return v_float32x8(_mm256_castps128_ps256(_mm256_cvtpd_ps(a.val))); } + +inline v_float32x8 v_cvt_f32(const v_float64x4& a, const v_float64x4& b) +{ + __m128 af = _mm256_cvtpd_ps(a.val), bf = _mm256_cvtpd_ps(b.val); + return v_float32x8(_v256_combine(af, bf)); +} + +inline v_float64x4 v_cvt_f64(const v_int32x8& a) +{ return v_float64x4(_mm256_cvtepi32_pd(_v256_extract_low(a.val))); } + +inline v_float64x4 v_cvt_f64_high(const v_int32x8& a) +{ return v_float64x4(_mm256_cvtepi32_pd(_v256_extract_high(a.val))); } + +inline v_float64x4 v_cvt_f64(const v_float32x8& a) +{ return v_float64x4(_mm256_cvtps_pd(_v256_extract_low(a.val))); } + +inline v_float64x4 v_cvt_f64_high(const v_float32x8& a) +{ return v_float64x4(_mm256_cvtps_pd(_v256_extract_high(a.val))); } + +// from (Mysticial and wim) https://stackoverflow.com/q/41144668 +inline v_float64x4 v_cvt_f64(const v_int64x4& v) +{ + // constants encoded as floating-point + __m256i magic_i_lo = _mm256_set1_epi64x(0x4330000000000000); // 2^52 + __m256i magic_i_hi32 = _mm256_set1_epi64x(0x4530000080000000); // 2^84 + 2^63 + __m256i magic_i_all = _mm256_set1_epi64x(0x4530000080100000); // 2^84 + 2^63 + 2^52 + __m256d magic_d_all = _mm256_castsi256_pd(magic_i_all); + + // Blend the 32 lowest significant bits of v with magic_int_lo + __m256i v_lo = _mm256_blend_epi32(magic_i_lo, v.val, 0x55); + // Extract the 32 most significant bits of v + __m256i v_hi = _mm256_srli_epi64(v.val, 32); + // Flip the msb of v_hi and blend with 0x45300000 + v_hi = _mm256_xor_si256(v_hi, magic_i_hi32); + // Compute in double precision + __m256d v_hi_dbl = _mm256_sub_pd(_mm256_castsi256_pd(v_hi), magic_d_all); + // (v_hi - magic_d_all) + v_lo Do not assume associativity of floating point addition + __m256d result = _mm256_add_pd(v_hi_dbl, _mm256_castsi256_pd(v_lo)); + return v_float64x4(result); +} + +////////////// Lookup table access //////////////////// + +inline v_int8x32 v256_lut(const schar* tab, const int* idx) +{ + return v_int8x32(_mm256_setr_epi8(tab[idx[ 0]], tab[idx[ 1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], tab[idx[ 5]], tab[idx[ 6]], tab[idx[ 7]], + tab[idx[ 8]], tab[idx[ 9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]], + tab[idx[16]], tab[idx[17]], tab[idx[18]], tab[idx[19]], tab[idx[20]], tab[idx[21]], tab[idx[22]], tab[idx[23]], + tab[idx[24]], tab[idx[25]], tab[idx[26]], tab[idx[27]], tab[idx[28]], tab[idx[29]], tab[idx[30]], tab[idx[31]])); +} +inline v_int8x32 v256_lut_pairs(const schar* tab, const int* idx) +{ + return v_int8x32(_mm256_setr_epi16(*(const short*)(tab + idx[ 0]), *(const short*)(tab + idx[ 1]), *(const short*)(tab + idx[ 2]), *(const short*)(tab + idx[ 3]), + *(const short*)(tab + idx[ 4]), *(const short*)(tab + idx[ 5]), *(const short*)(tab + idx[ 6]), *(const short*)(tab + idx[ 7]), + *(const short*)(tab + idx[ 8]), *(const short*)(tab + idx[ 9]), *(const short*)(tab + idx[10]), *(const short*)(tab + idx[11]), + *(const short*)(tab + idx[12]), *(const short*)(tab + idx[13]), *(const short*)(tab + idx[14]), *(const short*)(tab + idx[15]))); +} +inline v_int8x32 v256_lut_quads(const schar* tab, const int* idx) +{ + return v_int8x32(_mm256_i32gather_epi32((const int*)tab, _mm256_loadu_si256((const __m256i*)idx), 1)); +} +inline v_uint8x32 v256_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v256_lut((const schar *)tab, idx)); } +inline v_uint8x32 v256_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v256_lut_pairs((const schar *)tab, idx)); } +inline v_uint8x32 v256_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v256_lut_quads((const schar *)tab, idx)); } + +inline v_int16x16 v256_lut(const short* tab, const int* idx) +{ + return v_int16x16(_mm256_setr_epi16(tab[idx[0]], tab[idx[1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], tab[idx[ 5]], tab[idx[ 6]], tab[idx[ 7]], + tab[idx[8]], tab[idx[9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]])); +} +inline v_int16x16 v256_lut_pairs(const short* tab, const int* idx) +{ + return v_int16x16(_mm256_i32gather_epi32((const int*)tab, _mm256_loadu_si256((const __m256i*)idx), 2)); +} +inline v_int16x16 v256_lut_quads(const short* tab, const int* idx) +{ +#if defined(__GNUC__) + return v_int16x16(_mm256_i32gather_epi64((const long long int*)tab, _mm_loadu_si128((const __m128i*)idx), 2));//Looks like intrinsic has wrong definition +#else + return v_int16x16(_mm256_i32gather_epi64((const int64*)tab, _mm_loadu_si128((const __m128i*)idx), 2)); +#endif +} +inline v_uint16x16 v256_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v256_lut((const short *)tab, idx)); } +inline v_uint16x16 v256_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v256_lut_pairs((const short *)tab, idx)); } +inline v_uint16x16 v256_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v256_lut_quads((const short *)tab, idx)); } + +inline v_int32x8 v256_lut(const int* tab, const int* idx) +{ + return v_int32x8(_mm256_i32gather_epi32(tab, _mm256_loadu_si256((const __m256i*)idx), 4)); +} +inline v_int32x8 v256_lut_pairs(const int* tab, const int* idx) +{ +#if defined(__GNUC__) + return v_int32x8(_mm256_i32gather_epi64((const long long int*)tab, _mm_loadu_si128((const __m128i*)idx), 4)); +#else + return v_int32x8(_mm256_i32gather_epi64((const int64*)tab, _mm_loadu_si128((const __m128i*)idx), 4)); +#endif +} +inline v_int32x8 v256_lut_quads(const int* tab, const int* idx) +{ + return v_int32x8(_v256_combine(_mm_loadu_si128((const __m128i*)(tab + idx[0])), _mm_loadu_si128((const __m128i*)(tab + idx[1])))); +} +inline v_uint32x8 v256_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v256_lut((const int *)tab, idx)); } +inline v_uint32x8 v256_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v256_lut_pairs((const int *)tab, idx)); } +inline v_uint32x8 v256_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v256_lut_quads((const int *)tab, idx)); } + +inline v_int64x4 v256_lut(const int64* tab, const int* idx) +{ +#if defined(__GNUC__) + return v_int64x4(_mm256_i32gather_epi64((const long long int*)tab, _mm_loadu_si128((const __m128i*)idx), 8)); +#else + return v_int64x4(_mm256_i32gather_epi64(tab, _mm_loadu_si128((const __m128i*)idx), 8)); +#endif +} +inline v_int64x4 v256_lut_pairs(const int64* tab, const int* idx) +{ + return v_int64x4(_v256_combine(_mm_loadu_si128((const __m128i*)(tab + idx[0])), _mm_loadu_si128((const __m128i*)(tab + idx[1])))); +} +inline v_uint64x4 v256_lut(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v256_lut((const int64 *)tab, idx)); } +inline v_uint64x4 v256_lut_pairs(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v256_lut_pairs((const int64 *)tab, idx)); } + +inline v_float32x8 v256_lut(const float* tab, const int* idx) +{ + return v_float32x8(_mm256_i32gather_ps(tab, _mm256_loadu_si256((const __m256i*)idx), 4)); +} +inline v_float32x8 v256_lut_pairs(const float* tab, const int* idx) { return v_reinterpret_as_f32(v256_lut_pairs((const int *)tab, idx)); } +inline v_float32x8 v256_lut_quads(const float* tab, const int* idx) { return v_reinterpret_as_f32(v256_lut_quads((const int *)tab, idx)); } + +inline v_float64x4 v256_lut(const double* tab, const int* idx) +{ + return v_float64x4(_mm256_i32gather_pd(tab, _mm_loadu_si128((const __m128i*)idx), 8)); +} +inline v_float64x4 v256_lut_pairs(const double* tab, const int* idx) { return v_float64x4(_v256_combine(_mm_loadu_pd(tab + idx[0]), _mm_loadu_pd(tab + idx[1]))); } + +inline v_int32x8 v_lut(const int* tab, const v_int32x8& idxvec) +{ + return v_int32x8(_mm256_i32gather_epi32(tab, idxvec.val, 4)); +} + +inline v_uint32x8 v_lut(const unsigned* tab, const v_int32x8& idxvec) +{ + return v_reinterpret_as_u32(v_lut((const int *)tab, idxvec)); +} + +inline v_float32x8 v_lut(const float* tab, const v_int32x8& idxvec) +{ + return v_float32x8(_mm256_i32gather_ps(tab, idxvec.val, 4)); +} + +inline v_float64x4 v_lut(const double* tab, const v_int32x8& idxvec) +{ + return v_float64x4(_mm256_i32gather_pd(tab, _mm256_castsi256_si128(idxvec.val), 8)); +} + +inline void v_lut_deinterleave(const float* tab, const v_int32x8& idxvec, v_float32x8& x, v_float32x8& y) +{ + int CV_DECL_ALIGNED(32) idx[8]; + v_store_aligned(idx, idxvec); + __m128 z = _mm_setzero_ps(); + __m128 xy01, xy45, xy23, xy67; + xy01 = _mm_loadl_pi(z, (const __m64*)(tab + idx[0])); + xy01 = _mm_loadh_pi(xy01, (const __m64*)(tab + idx[1])); + xy45 = _mm_loadl_pi(z, (const __m64*)(tab + idx[4])); + xy45 = _mm_loadh_pi(xy45, (const __m64*)(tab + idx[5])); + __m256 xy0145 = _v256_combine(xy01, xy45); + xy23 = _mm_loadl_pi(z, (const __m64*)(tab + idx[2])); + xy23 = _mm_loadh_pi(xy23, (const __m64*)(tab + idx[3])); + xy67 = _mm_loadl_pi(z, (const __m64*)(tab + idx[6])); + xy67 = _mm_loadh_pi(xy67, (const __m64*)(tab + idx[7])); + __m256 xy2367 = _v256_combine(xy23, xy67); + + __m256 xxyy0145 = _mm256_unpacklo_ps(xy0145, xy2367); + __m256 xxyy2367 = _mm256_unpackhi_ps(xy0145, xy2367); + + x = v_float32x8(_mm256_unpacklo_ps(xxyy0145, xxyy2367)); + y = v_float32x8(_mm256_unpackhi_ps(xxyy0145, xxyy2367)); +} + +inline void v_lut_deinterleave(const double* tab, const v_int32x8& idxvec, v_float64x4& x, v_float64x4& y) +{ + int CV_DECL_ALIGNED(32) idx[4]; + v_store_low(idx, idxvec); + __m128d xy0 = _mm_loadu_pd(tab + idx[0]); + __m128d xy2 = _mm_loadu_pd(tab + idx[2]); + __m128d xy1 = _mm_loadu_pd(tab + idx[1]); + __m128d xy3 = _mm_loadu_pd(tab + idx[3]); + __m256d xy02 = _v256_combine(xy0, xy2); + __m256d xy13 = _v256_combine(xy1, xy3); + + x = v_float64x4(_mm256_unpacklo_pd(xy02, xy13)); + y = v_float64x4(_mm256_unpackhi_pd(xy02, xy13)); +} + +inline v_int8x32 v_interleave_pairs(const v_int8x32& vec) +{ + return v_int8x32(_mm256_shuffle_epi8(vec.val, _mm256_set_epi64x(0x0f0d0e0c0b090a08, 0x0705060403010200, 0x0f0d0e0c0b090a08, 0x0705060403010200))); +} +inline v_uint8x32 v_interleave_pairs(const v_uint8x32& vec) { return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } +inline v_int8x32 v_interleave_quads(const v_int8x32& vec) +{ + return v_int8x32(_mm256_shuffle_epi8(vec.val, _mm256_set_epi64x(0x0f0b0e0a0d090c08, 0x0703060205010400, 0x0f0b0e0a0d090c08, 0x0703060205010400))); +} +inline v_uint8x32 v_interleave_quads(const v_uint8x32& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } + +inline v_int16x16 v_interleave_pairs(const v_int16x16& vec) +{ + return v_int16x16(_mm256_shuffle_epi8(vec.val, _mm256_set_epi64x(0x0f0e0b0a0d0c0908, 0x0706030205040100, 0x0f0e0b0a0d0c0908, 0x0706030205040100))); +} +inline v_uint16x16 v_interleave_pairs(const v_uint16x16& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } +inline v_int16x16 v_interleave_quads(const v_int16x16& vec) +{ + return v_int16x16(_mm256_shuffle_epi8(vec.val, _mm256_set_epi64x(0x0f0e07060d0c0504, 0x0b0a030209080100, 0x0f0e07060d0c0504, 0x0b0a030209080100))); +} +inline v_uint16x16 v_interleave_quads(const v_uint16x16& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } + +inline v_int32x8 v_interleave_pairs(const v_int32x8& vec) +{ + return v_int32x8(_mm256_shuffle_epi32(vec.val, _MM_SHUFFLE(3, 1, 2, 0))); +} +inline v_uint32x8 v_interleave_pairs(const v_uint32x8& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } +inline v_float32x8 v_interleave_pairs(const v_float32x8& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } + +inline v_int8x32 v_pack_triplets(const v_int8x32& vec) +{ + return v_int8x32(_mm256_permutevar8x32_epi32(_mm256_shuffle_epi8(vec.val, _mm256_broadcastsi128_si256(_mm_set_epi64x(0xffffff0f0e0d0c0a, 0x0908060504020100))), + _mm256_set_epi64x(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); +} +inline v_uint8x32 v_pack_triplets(const v_uint8x32& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } + +inline v_int16x16 v_pack_triplets(const v_int16x16& vec) +{ + return v_int16x16(_mm256_permutevar8x32_epi32(_mm256_shuffle_epi8(vec.val, _mm256_broadcastsi128_si256(_mm_set_epi64x(0xffff0f0e0d0c0b0a, 0x0908050403020100))), + _mm256_set_epi64x(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); +} +inline v_uint16x16 v_pack_triplets(const v_uint16x16& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } + +inline v_int32x8 v_pack_triplets(const v_int32x8& vec) +{ + return v_int32x8(_mm256_permutevar8x32_epi32(vec.val, _mm256_set_epi64x(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); +} +inline v_uint32x8 v_pack_triplets(const v_uint32x8& vec) { return v_reinterpret_as_u32(v_pack_triplets(v_reinterpret_as_s32(vec))); } +inline v_float32x8 v_pack_triplets(const v_float32x8& vec) +{ + return v_float32x8(_mm256_permutevar8x32_ps(vec.val, _mm256_set_epi64x(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); +} + +////////// Matrix operations ///////// + +//////// Dot Product //////// + +// 16 >> 32 +inline v_int32x8 v_dotprod(const v_int16x16& a, const v_int16x16& b) +{ return v_int32x8(_mm256_madd_epi16(a.val, b.val)); } +inline v_int32x8 v_dotprod(const v_int16x16& a, const v_int16x16& b, const v_int32x8& c) +{ return v_add(v_dotprod(a, b), c); } + +// 32 >> 64 +inline v_int64x4 v_dotprod(const v_int32x8& a, const v_int32x8& b) +{ + __m256i even = _mm256_mul_epi32(a.val, b.val); + __m256i odd = _mm256_mul_epi32(_mm256_srli_epi64(a.val, 32), _mm256_srli_epi64(b.val, 32)); + return v_int64x4(_mm256_add_epi64(even, odd)); +} +inline v_int64x4 v_dotprod(const v_int32x8& a, const v_int32x8& b, const v_int64x4& c) +{ return v_add(v_dotprod(a, b), c); } + +// 8 >> 32 +inline v_uint32x8 v_dotprod_expand(const v_uint8x32& a, const v_uint8x32& b) +{ + __m256i even_m = _mm256_set1_epi32(0xFF00FF00); + __m256i even_a = _mm256_blendv_epi8(a.val, _mm256_setzero_si256(), even_m); + __m256i odd_a = _mm256_srli_epi16(a.val, 8); + + __m256i even_b = _mm256_blendv_epi8(b.val, _mm256_setzero_si256(), even_m); + __m256i odd_b = _mm256_srli_epi16(b.val, 8); + + __m256i prod0 = _mm256_madd_epi16(even_a, even_b); + __m256i prod1 = _mm256_madd_epi16(odd_a, odd_b); + return v_uint32x8(_mm256_add_epi32(prod0, prod1)); +} +inline v_uint32x8 v_dotprod_expand(const v_uint8x32& a, const v_uint8x32& b, const v_uint32x8& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int32x8 v_dotprod_expand(const v_int8x32& a, const v_int8x32& b) +{ + __m256i even_a = _mm256_srai_epi16(_mm256_bslli_epi128(a.val, 1), 8); + __m256i odd_a = _mm256_srai_epi16(a.val, 8); + + __m256i even_b = _mm256_srai_epi16(_mm256_bslli_epi128(b.val, 1), 8); + __m256i odd_b = _mm256_srai_epi16(b.val, 8); + + __m256i prod0 = _mm256_madd_epi16(even_a, even_b); + __m256i prod1 = _mm256_madd_epi16(odd_a, odd_b); + return v_int32x8(_mm256_add_epi32(prod0, prod1)); +} +inline v_int32x8 v_dotprod_expand(const v_int8x32& a, const v_int8x32& b, const v_int32x8& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 16 >> 64 +inline v_uint64x4 v_dotprod_expand(const v_uint16x16& a, const v_uint16x16& b) +{ + __m256i mullo = _mm256_mullo_epi16(a.val, b.val); + __m256i mulhi = _mm256_mulhi_epu16(a.val, b.val); + __m256i mul0 = _mm256_unpacklo_epi16(mullo, mulhi); + __m256i mul1 = _mm256_unpackhi_epi16(mullo, mulhi); + + __m256i p02 = _mm256_blend_epi32(mul0, _mm256_setzero_si256(), 0xAA); + __m256i p13 = _mm256_srli_epi64(mul0, 32); + __m256i p46 = _mm256_blend_epi32(mul1, _mm256_setzero_si256(), 0xAA); + __m256i p57 = _mm256_srli_epi64(mul1, 32); + + __m256i p15_ = _mm256_add_epi64(p02, p13); + __m256i p9d_ = _mm256_add_epi64(p46, p57); + + return v_uint64x4(_mm256_add_epi64( + _mm256_unpacklo_epi64(p15_, p9d_), + _mm256_unpackhi_epi64(p15_, p9d_) + )); +} +inline v_uint64x4 v_dotprod_expand(const v_uint16x16& a, const v_uint16x16& b, const v_uint64x4& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int64x4 v_dotprod_expand(const v_int16x16& a, const v_int16x16& b) +{ + __m256i prod = _mm256_madd_epi16(a.val, b.val); + __m256i sign = _mm256_srai_epi32(prod, 31); + + __m256i lo = _mm256_unpacklo_epi32(prod, sign); + __m256i hi = _mm256_unpackhi_epi32(prod, sign); + + return v_int64x4(_mm256_add_epi64( + _mm256_unpacklo_epi64(lo, hi), + _mm256_unpackhi_epi64(lo, hi) + )); +} +inline v_int64x4 v_dotprod_expand(const v_int16x16& a, const v_int16x16& b, const v_int64x4& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 32 >> 64f +inline v_float64x4 v_dotprod_expand(const v_int32x8& a, const v_int32x8& b) +{ return v_cvt_f64(v_dotprod(a, b)); } +inline v_float64x4 v_dotprod_expand(const v_int32x8& a, const v_int32x8& b, const v_float64x4& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +//////// Fast Dot Product //////// + +// 16 >> 32 +inline v_int32x8 v_dotprod_fast(const v_int16x16& a, const v_int16x16& b) +{ return v_dotprod(a, b); } +inline v_int32x8 v_dotprod_fast(const v_int16x16& a, const v_int16x16& b, const v_int32x8& c) +{ return v_dotprod(a, b, c); } + +// 32 >> 64 +inline v_int64x4 v_dotprod_fast(const v_int32x8& a, const v_int32x8& b) +{ return v_dotprod(a, b); } +inline v_int64x4 v_dotprod_fast(const v_int32x8& a, const v_int32x8& b, const v_int64x4& c) +{ return v_dotprod(a, b, c); } + +// 8 >> 32 +inline v_uint32x8 v_dotprod_expand_fast(const v_uint8x32& a, const v_uint8x32& b) +{ return v_dotprod_expand(a, b); } +inline v_uint32x8 v_dotprod_expand_fast(const v_uint8x32& a, const v_uint8x32& b, const v_uint32x8& c) +{ return v_dotprod_expand(a, b, c); } + +inline v_int32x8 v_dotprod_expand_fast(const v_int8x32& a, const v_int8x32& b) +{ return v_dotprod_expand(a, b); } +inline v_int32x8 v_dotprod_expand_fast(const v_int8x32& a, const v_int8x32& b, const v_int32x8& c) +{ return v_dotprod_expand(a, b, c); } + +// 16 >> 64 +inline v_uint64x4 v_dotprod_expand_fast(const v_uint16x16& a, const v_uint16x16& b) +{ + __m256i mullo = _mm256_mullo_epi16(a.val, b.val); + __m256i mulhi = _mm256_mulhi_epu16(a.val, b.val); + __m256i mul0 = _mm256_unpacklo_epi16(mullo, mulhi); + __m256i mul1 = _mm256_unpackhi_epi16(mullo, mulhi); + + __m256i p02 = _mm256_blend_epi32(mul0, _mm256_setzero_si256(), 0xAA); + __m256i p13 = _mm256_srli_epi64(mul0, 32); + __m256i p46 = _mm256_blend_epi32(mul1, _mm256_setzero_si256(), 0xAA); + __m256i p57 = _mm256_srli_epi64(mul1, 32); + + __m256i p15_ = _mm256_add_epi64(p02, p13); + __m256i p9d_ = _mm256_add_epi64(p46, p57); + + return v_uint64x4(_mm256_add_epi64(p15_, p9d_)); +} +inline v_uint64x4 v_dotprod_expand_fast(const v_uint16x16& a, const v_uint16x16& b, const v_uint64x4& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +inline v_int64x4 v_dotprod_expand_fast(const v_int16x16& a, const v_int16x16& b) +{ + __m256i prod = _mm256_madd_epi16(a.val, b.val); + __m256i sign = _mm256_srai_epi32(prod, 31); + __m256i lo = _mm256_unpacklo_epi32(prod, sign); + __m256i hi = _mm256_unpackhi_epi32(prod, sign); + return v_int64x4(_mm256_add_epi64(lo, hi)); +} +inline v_int64x4 v_dotprod_expand_fast(const v_int16x16& a, const v_int16x16& b, const v_int64x4& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +// 32 >> 64f +inline v_float64x4 v_dotprod_expand_fast(const v_int32x8& a, const v_int32x8& b) +{ return v_dotprod_expand(a, b); } +inline v_float64x4 v_dotprod_expand_fast(const v_int32x8& a, const v_int32x8& b, const v_float64x4& c) +{ return v_dotprod_expand(a, b, c); } + +#define OPENCV_HAL_AVX_SPLAT2_PS(a, im) \ + v_float32x8(_mm256_permute_ps(a.val, _MM_SHUFFLE(im, im, im, im))) + +inline v_float32x8 v_matmul(const v_float32x8& v, const v_float32x8& m0, + const v_float32x8& m1, const v_float32x8& m2, + const v_float32x8& m3) +{ + v_float32x8 v04 = OPENCV_HAL_AVX_SPLAT2_PS(v, 0); + v_float32x8 v15 = OPENCV_HAL_AVX_SPLAT2_PS(v, 1); + v_float32x8 v26 = OPENCV_HAL_AVX_SPLAT2_PS(v, 2); + v_float32x8 v37 = OPENCV_HAL_AVX_SPLAT2_PS(v, 3); + return v_fma(v04, m0, v_fma(v15, m1, v_fma(v26, m2, v_mul(v37, m3)))); +} + +inline v_float32x8 v_matmuladd(const v_float32x8& v, const v_float32x8& m0, + const v_float32x8& m1, const v_float32x8& m2, + const v_float32x8& a) +{ + v_float32x8 v04 = OPENCV_HAL_AVX_SPLAT2_PS(v, 0); + v_float32x8 v15 = OPENCV_HAL_AVX_SPLAT2_PS(v, 1); + v_float32x8 v26 = OPENCV_HAL_AVX_SPLAT2_PS(v, 2); + return v_fma(v04, m0, v_fma(v15, m1, v_fma(v26, m2, a))); +} + +#define OPENCV_HAL_IMPL_AVX_TRANSPOSE4x4(_Tpvec, suffix, cast_from, cast_to) \ + inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ + const _Tpvec& a2, const _Tpvec& a3, \ + _Tpvec& b0, _Tpvec& b1, _Tpvec& b2, _Tpvec& b3) \ + { \ + __m256i t0 = cast_from(_mm256_unpacklo_##suffix(a0.val, a1.val)); \ + __m256i t1 = cast_from(_mm256_unpacklo_##suffix(a2.val, a3.val)); \ + __m256i t2 = cast_from(_mm256_unpackhi_##suffix(a0.val, a1.val)); \ + __m256i t3 = cast_from(_mm256_unpackhi_##suffix(a2.val, a3.val)); \ + b0.val = cast_to(_mm256_unpacklo_epi64(t0, t1)); \ + b1.val = cast_to(_mm256_unpackhi_epi64(t0, t1)); \ + b2.val = cast_to(_mm256_unpacklo_epi64(t2, t3)); \ + b3.val = cast_to(_mm256_unpackhi_epi64(t2, t3)); \ + } + +OPENCV_HAL_IMPL_AVX_TRANSPOSE4x4(v_uint32x8, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_AVX_TRANSPOSE4x4(v_int32x8, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_AVX_TRANSPOSE4x4(v_float32x8, ps, _mm256_castps_si256, _mm256_castsi256_ps) + +//////////////// Value reordering /////////////// + +/* Expand */ +#define OPENCV_HAL_IMPL_AVX_EXPAND(_Tpvec, _Tpwvec, _Tp, intrin) \ + inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ + { \ + b0.val = intrin(_v256_extract_low(a.val)); \ + b1.val = intrin(_v256_extract_high(a.val)); \ + } \ + inline _Tpwvec v_expand_low(const _Tpvec& a) \ + { return _Tpwvec(intrin(_v256_extract_low(a.val))); } \ + inline _Tpwvec v_expand_high(const _Tpvec& a) \ + { return _Tpwvec(intrin(_v256_extract_high(a.val))); } \ + inline _Tpwvec v256_load_expand(const _Tp* ptr) \ + { \ + __m128i a = _mm_loadu_si128((const __m128i*)ptr); \ + return _Tpwvec(intrin(a)); \ + } + +OPENCV_HAL_IMPL_AVX_EXPAND(v_uint8x32, v_uint16x16, uchar, _mm256_cvtepu8_epi16) +OPENCV_HAL_IMPL_AVX_EXPAND(v_int8x32, v_int16x16, schar, _mm256_cvtepi8_epi16) +OPENCV_HAL_IMPL_AVX_EXPAND(v_uint16x16, v_uint32x8, ushort, _mm256_cvtepu16_epi32) +OPENCV_HAL_IMPL_AVX_EXPAND(v_int16x16, v_int32x8, short, _mm256_cvtepi16_epi32) +OPENCV_HAL_IMPL_AVX_EXPAND(v_uint32x8, v_uint64x4, unsigned, _mm256_cvtepu32_epi64) +OPENCV_HAL_IMPL_AVX_EXPAND(v_int32x8, v_int64x4, int, _mm256_cvtepi32_epi64) + +#define OPENCV_HAL_IMPL_AVX_EXPAND_Q(_Tpvec, _Tp, intrin) \ + inline _Tpvec v256_load_expand_q(const _Tp* ptr) \ + { \ + __m128i a = _mm_loadl_epi64((const __m128i*)ptr); \ + return _Tpvec(intrin(a)); \ + } + +OPENCV_HAL_IMPL_AVX_EXPAND_Q(v_uint32x8, uchar, _mm256_cvtepu8_epi32) +OPENCV_HAL_IMPL_AVX_EXPAND_Q(v_int32x8, schar, _mm256_cvtepi8_epi32) + +/* pack */ +// 16 +inline v_int8x32 v_pack(const v_int16x16& a, const v_int16x16& b) +{ return v_int8x32(_v256_shuffle_odd_64(_mm256_packs_epi16(a.val, b.val))); } + +inline v_uint8x32 v_pack(const v_uint16x16& a, const v_uint16x16& b) +{ + __m256i t = _mm256_set1_epi16(255); + __m256i a1 = _mm256_min_epu16(a.val, t); + __m256i b1 = _mm256_min_epu16(b.val, t); + return v_uint8x32(_v256_shuffle_odd_64(_mm256_packus_epi16(a1, b1))); +} + +inline v_uint8x32 v_pack_u(const v_int16x16& a, const v_int16x16& b) +{ + return v_uint8x32(_v256_shuffle_odd_64(_mm256_packus_epi16(a.val, b.val))); +} + +inline void v_pack_store(schar* ptr, const v_int16x16& a) +{ v_store_low(ptr, v_pack(a, a)); } + +inline void v_pack_store(uchar* ptr, const v_uint16x16& a) +{ + const __m256i m = _mm256_set1_epi16(255); + __m256i am = _mm256_min_epu16(a.val, m); + am = _v256_shuffle_odd_64(_mm256_packus_epi16(am, am)); + v_store_low(ptr, v_uint8x32(am)); +} + +inline void v_pack_u_store(uchar* ptr, const v_int16x16& a) +{ v_store_low(ptr, v_pack_u(a, a)); } + +template inline +v_uint8x32 v_rshr_pack(const v_uint16x16& a, const v_uint16x16& b) +{ + // we assume that n > 0, and so the shifted 16-bit values can be treated as signed numbers. + v_uint16x16 delta = v256_setall_u16((short)(1 << (n-1))); + return v_pack_u(v_reinterpret_as_s16(v_shr(v_add(a, delta), n)), + v_reinterpret_as_s16(v_shr(v_add(b, delta), n))); +} + +template inline +void v_rshr_pack_store(uchar* ptr, const v_uint16x16& a) +{ + v_uint16x16 delta = v256_setall_u16((short)(1 << (n-1))); + v_pack_u_store(ptr, v_reinterpret_as_s16(v_shr(v_add(a, delta), n))); +} + +template inline +v_uint8x32 v_rshr_pack_u(const v_int16x16& a, const v_int16x16& b) +{ + v_int16x16 delta = v256_setall_s16((short)(1 << (n-1))); + return v_pack_u(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); +} + +template inline +void v_rshr_pack_u_store(uchar* ptr, const v_int16x16& a) +{ + v_int16x16 delta = v256_setall_s16((short)(1 << (n-1))); + v_pack_u_store(ptr, v_shr(v_add(a, delta), n)); +} + +template inline +v_int8x32 v_rshr_pack(const v_int16x16& a, const v_int16x16& b) +{ + v_int16x16 delta = v256_setall_s16((short)(1 << (n-1))); + return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); +} + +template inline +void v_rshr_pack_store(schar* ptr, const v_int16x16& a) +{ + v_int16x16 delta = v256_setall_s16((short)(1 << (n-1))); + v_pack_store(ptr, v_shr(v_add(a, delta), n)); +} + +// 32 +inline v_int16x16 v_pack(const v_int32x8& a, const v_int32x8& b) +{ return v_int16x16(_v256_shuffle_odd_64(_mm256_packs_epi32(a.val, b.val))); } + +inline v_uint16x16 v_pack(const v_uint32x8& a, const v_uint32x8& b) +{ return v_uint16x16(_v256_shuffle_odd_64(_v256_packs_epu32(a.val, b.val))); } + +inline v_uint16x16 v_pack_u(const v_int32x8& a, const v_int32x8& b) +{ return v_uint16x16(_v256_shuffle_odd_64(_mm256_packus_epi32(a.val, b.val))); } + +inline void v_pack_store(short* ptr, const v_int32x8& a) +{ v_store_low(ptr, v_pack(a, a)); } + +inline void v_pack_store(ushort* ptr, const v_uint32x8& a) +{ + const __m256i m = _mm256_set1_epi32(65535); + __m256i am = _mm256_min_epu32(a.val, m); + am = _v256_shuffle_odd_64(_mm256_packus_epi32(am, am)); + v_store_low(ptr, v_uint16x16(am)); +} + +inline void v_pack_u_store(ushort* ptr, const v_int32x8& a) +{ v_store_low(ptr, v_pack_u(a, a)); } + + +template inline +v_uint16x16 v_rshr_pack(const v_uint32x8& a, const v_uint32x8& b) +{ + // we assume that n > 0, and so the shifted 32-bit values can be treated as signed numbers. + v_uint32x8 delta = v256_setall_u32(1 << (n-1)); + return v_pack_u(v_reinterpret_as_s32(v_shr(v_add(a, delta), n)), + v_reinterpret_as_s32(v_shr(v_add(b, delta), n))); +} + +template inline +void v_rshr_pack_store(ushort* ptr, const v_uint32x8& a) +{ + v_uint32x8 delta = v256_setall_u32(1 << (n-1)); + v_pack_u_store(ptr, v_reinterpret_as_s32(v_shr(v_add(a, delta), n))); +} + +template inline +v_uint16x16 v_rshr_pack_u(const v_int32x8& a, const v_int32x8& b) +{ + v_int32x8 delta = v256_setall_s32(1 << (n-1)); + return v_pack_u(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); +} + +template inline +void v_rshr_pack_u_store(ushort* ptr, const v_int32x8& a) +{ + v_int32x8 delta = v256_setall_s32(1 << (n-1)); + v_pack_u_store(ptr, v_shr(v_add(a, delta), n)); +} + +template inline +v_int16x16 v_rshr_pack(const v_int32x8& a, const v_int32x8& b) +{ + v_int32x8 delta = v256_setall_s32(1 << (n-1)); + return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); +} + +template inline +void v_rshr_pack_store(short* ptr, const v_int32x8& a) +{ + v_int32x8 delta = v256_setall_s32(1 << (n-1)); + v_pack_store(ptr, v_shr(v_add(a, delta), n)); +} + +// 64 +// Non-saturating pack +inline v_uint32x8 v_pack(const v_uint64x4& a, const v_uint64x4& b) +{ + __m256i a0 = _mm256_shuffle_epi32(a.val, _MM_SHUFFLE(0, 0, 2, 0)); + __m256i b0 = _mm256_shuffle_epi32(b.val, _MM_SHUFFLE(0, 0, 2, 0)); + __m256i ab = _mm256_unpacklo_epi64(a0, b0); // a0, a1, b0, b1, a2, a3, b2, b3 + return v_uint32x8(_v256_shuffle_odd_64(ab)); +} + +inline v_int32x8 v_pack(const v_int64x4& a, const v_int64x4& b) +{ return v_reinterpret_as_s32(v_pack(v_reinterpret_as_u64(a), v_reinterpret_as_u64(b))); } + +inline void v_pack_store(unsigned* ptr, const v_uint64x4& a) +{ + __m256i a0 = _mm256_shuffle_epi32(a.val, _MM_SHUFFLE(0, 0, 2, 0)); + v_store_low(ptr, v_uint32x8(_v256_shuffle_odd_64(a0))); +} + +inline void v_pack_store(int* ptr, const v_int64x4& b) +{ v_pack_store((unsigned*)ptr, v_reinterpret_as_u64(b)); } + +template inline +v_uint32x8 v_rshr_pack(const v_uint64x4& a, const v_uint64x4& b) +{ + v_uint64x4 delta = v256_setall_u64((uint64)1 << (n-1)); + return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); +} + +template inline +void v_rshr_pack_store(unsigned* ptr, const v_uint64x4& a) +{ + v_uint64x4 delta = v256_setall_u64((uint64)1 << (n-1)); + v_pack_store(ptr, v_shr(v_add(a, delta), n)); +} + +template inline +v_int32x8 v_rshr_pack(const v_int64x4& a, const v_int64x4& b) +{ + v_int64x4 delta = v256_setall_s64((int64)1 << (n-1)); + return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); +} + +template inline +void v_rshr_pack_store(int* ptr, const v_int64x4& a) +{ + v_int64x4 delta = v256_setall_s64((int64)1 << (n-1)); + v_pack_store(ptr, v_shr(v_add(a, delta), n)); +} + +// pack boolean +inline v_uint8x32 v_pack_b(const v_uint16x16& a, const v_uint16x16& b) +{ + __m256i ab = _mm256_packs_epi16(a.val, b.val); + return v_uint8x32(_v256_shuffle_odd_64(ab)); +} + +inline v_uint8x32 v_pack_b(const v_uint32x8& a, const v_uint32x8& b, + const v_uint32x8& c, const v_uint32x8& d) +{ + __m256i ab = _mm256_packs_epi32(a.val, b.val); + __m256i cd = _mm256_packs_epi32(c.val, d.val); + + __m256i abcd = _v256_shuffle_odd_64(_mm256_packs_epi16(ab, cd)); + return v_uint8x32(_mm256_shuffle_epi32(abcd, _MM_SHUFFLE(3, 1, 2, 0))); +} + +inline v_uint8x32 v_pack_b(const v_uint64x4& a, const v_uint64x4& b, const v_uint64x4& c, + const v_uint64x4& d, const v_uint64x4& e, const v_uint64x4& f, + const v_uint64x4& g, const v_uint64x4& h) +{ + __m256i ab = _mm256_packs_epi32(a.val, b.val); + __m256i cd = _mm256_packs_epi32(c.val, d.val); + __m256i ef = _mm256_packs_epi32(e.val, f.val); + __m256i gh = _mm256_packs_epi32(g.val, h.val); + + __m256i abcd = _mm256_packs_epi32(ab, cd); + __m256i efgh = _mm256_packs_epi32(ef, gh); + __m256i pkall = _v256_shuffle_odd_64(_mm256_packs_epi16(abcd, efgh)); + + __m256i rev = _mm256_alignr_epi8(pkall, pkall, 8); + return v_uint8x32(_mm256_unpacklo_epi16(pkall, rev)); +} + +/* Recombine */ +// its up there with load and store operations + +/* Extract */ +#define OPENCV_HAL_IMPL_AVX_EXTRACT(_Tpvec) \ + template \ + inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \ + { return v_rotate_right(a, b); } + +OPENCV_HAL_IMPL_AVX_EXTRACT(v_uint8x32) +OPENCV_HAL_IMPL_AVX_EXTRACT(v_int8x32) +OPENCV_HAL_IMPL_AVX_EXTRACT(v_uint16x16) +OPENCV_HAL_IMPL_AVX_EXTRACT(v_int16x16) +OPENCV_HAL_IMPL_AVX_EXTRACT(v_uint32x8) +OPENCV_HAL_IMPL_AVX_EXTRACT(v_int32x8) +OPENCV_HAL_IMPL_AVX_EXTRACT(v_uint64x4) +OPENCV_HAL_IMPL_AVX_EXTRACT(v_int64x4) +OPENCV_HAL_IMPL_AVX_EXTRACT(v_float32x8) +OPENCV_HAL_IMPL_AVX_EXTRACT(v_float64x4) + +template +inline uchar v_extract_n(v_uint8x32 a) +{ + return (uchar)_v256_extract_epi8(a.val); +} + +template +inline schar v_extract_n(v_int8x32 a) +{ + return (schar)v_extract_n(v_reinterpret_as_u8(a)); +} + +template +inline ushort v_extract_n(v_uint16x16 a) +{ + return (ushort)_v256_extract_epi16(a.val); +} + +template +inline short v_extract_n(v_int16x16 a) +{ + return (short)v_extract_n(v_reinterpret_as_u16(a)); +} + +template +inline uint v_extract_n(v_uint32x8 a) +{ + return (uint)_v256_extract_epi32(a.val); +} + +template +inline int v_extract_n(v_int32x8 a) +{ + return (int)v_extract_n(v_reinterpret_as_u32(a)); +} + +template +inline uint64 v_extract_n(v_uint64x4 a) +{ + return (uint64)_v256_extract_epi64(a.val); +} + +template +inline int64 v_extract_n(v_int64x4 v) +{ + return (int64)v_extract_n(v_reinterpret_as_u64(v)); +} + +template +inline float v_extract_n(v_float32x8 v) +{ + union { uint iv; float fv; } d; + d.iv = v_extract_n(v_reinterpret_as_u32(v)); + return d.fv; +} + +template +inline double v_extract_n(v_float64x4 v) +{ + union { uint64 iv; double dv; } d; + d.iv = v_extract_n(v_reinterpret_as_u64(v)); + return d.dv; +} + +template +inline v_uint32x8 v_broadcast_element(v_uint32x8 a) +{ + static const __m256i perm = _mm256_set1_epi32((char)i); + return v_uint32x8(_mm256_permutevar8x32_epi32(a.val, perm)); +} + +template +inline v_int32x8 v_broadcast_element(const v_int32x8 &a) +{ return v_reinterpret_as_s32(v_broadcast_element(v_reinterpret_as_u32(a))); } + +template +inline v_float32x8 v_broadcast_element(const v_float32x8 &a) +{ return v_reinterpret_as_f32(v_broadcast_element(v_reinterpret_as_u32(a))); } + + +///////////////////// load deinterleave ///////////////////////////// + +inline void v_load_deinterleave( const uchar* ptr, v_uint8x32& a, v_uint8x32& b ) +{ + __m256i ab0 = _mm256_loadu_si256((const __m256i*)ptr); + __m256i ab1 = _mm256_loadu_si256((const __m256i*)(ptr + 32)); + + const __m256i sh = _mm256_setr_epi8(0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15, + 0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15); + __m256i p0 = _mm256_shuffle_epi8(ab0, sh); + __m256i p1 = _mm256_shuffle_epi8(ab1, sh); + __m256i pl = _mm256_permute2x128_si256(p0, p1, 0 + 2*16); + __m256i ph = _mm256_permute2x128_si256(p0, p1, 1 + 3*16); + __m256i a0 = _mm256_unpacklo_epi64(pl, ph); + __m256i b0 = _mm256_unpackhi_epi64(pl, ph); + a = v_uint8x32(a0); + b = v_uint8x32(b0); +} + +inline void v_load_deinterleave( const ushort* ptr, v_uint16x16& a, v_uint16x16& b ) +{ + __m256i ab0 = _mm256_loadu_si256((const __m256i*)ptr); + __m256i ab1 = _mm256_loadu_si256((const __m256i*)(ptr + 16)); + + const __m256i sh = _mm256_setr_epi8(0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15, + 0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15); + __m256i p0 = _mm256_shuffle_epi8(ab0, sh); + __m256i p1 = _mm256_shuffle_epi8(ab1, sh); + __m256i pl = _mm256_permute2x128_si256(p0, p1, 0 + 2*16); + __m256i ph = _mm256_permute2x128_si256(p0, p1, 1 + 3*16); + __m256i a0 = _mm256_unpacklo_epi64(pl, ph); + __m256i b0 = _mm256_unpackhi_epi64(pl, ph); + a = v_uint16x16(a0); + b = v_uint16x16(b0); +} + +inline void v_load_deinterleave( const unsigned* ptr, v_uint32x8& a, v_uint32x8& b ) +{ + __m256i ab0 = _mm256_loadu_si256((const __m256i*)ptr); + __m256i ab1 = _mm256_loadu_si256((const __m256i*)(ptr + 8)); + + enum { sh = 0+2*4+1*16+3*64 }; + __m256i p0 = _mm256_shuffle_epi32(ab0, sh); + __m256i p1 = _mm256_shuffle_epi32(ab1, sh); + __m256i pl = _mm256_permute2x128_si256(p0, p1, 0 + 2*16); + __m256i ph = _mm256_permute2x128_si256(p0, p1, 1 + 3*16); + __m256i a0 = _mm256_unpacklo_epi64(pl, ph); + __m256i b0 = _mm256_unpackhi_epi64(pl, ph); + a = v_uint32x8(a0); + b = v_uint32x8(b0); +} + +inline void v_load_deinterleave( const uint64* ptr, v_uint64x4& a, v_uint64x4& b ) +{ + __m256i ab0 = _mm256_loadu_si256((const __m256i*)ptr); + __m256i ab1 = _mm256_loadu_si256((const __m256i*)(ptr + 4)); + + __m256i pl = _mm256_permute2x128_si256(ab0, ab1, 0 + 2*16); + __m256i ph = _mm256_permute2x128_si256(ab0, ab1, 1 + 3*16); + __m256i a0 = _mm256_unpacklo_epi64(pl, ph); + __m256i b0 = _mm256_unpackhi_epi64(pl, ph); + a = v_uint64x4(a0); + b = v_uint64x4(b0); +} + +inline void v_load_deinterleave( const uchar* ptr, v_uint8x32& a, v_uint8x32& b, v_uint8x32& c ) +{ + __m256i bgr0 = _mm256_loadu_si256((const __m256i*)ptr); + __m256i bgr1 = _mm256_loadu_si256((const __m256i*)(ptr + 32)); + __m256i bgr2 = _mm256_loadu_si256((const __m256i*)(ptr + 64)); + + __m256i s02_low = _mm256_permute2x128_si256(bgr0, bgr2, 0 + 2*16); + __m256i s02_high = _mm256_permute2x128_si256(bgr0, bgr2, 1 + 3*16); + + const __m256i m0 = _mm256_setr_epi8(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, + 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); + const __m256i m1 = _mm256_setr_epi8(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, + -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); + + __m256i b0 = _mm256_blendv_epi8(_mm256_blendv_epi8(s02_low, s02_high, m0), bgr1, m1); + __m256i g0 = _mm256_blendv_epi8(_mm256_blendv_epi8(s02_high, s02_low, m1), bgr1, m0); + __m256i r0 = _mm256_blendv_epi8(_mm256_blendv_epi8(bgr1, s02_low, m0), s02_high, m1); + + const __m256i + sh_b = _mm256_setr_epi8(0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13, + 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13), + sh_g = _mm256_setr_epi8(1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, + 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14), + sh_r = _mm256_setr_epi8(2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, + 2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15); + b0 = _mm256_shuffle_epi8(b0, sh_b); + g0 = _mm256_shuffle_epi8(g0, sh_g); + r0 = _mm256_shuffle_epi8(r0, sh_r); + + a = v_uint8x32(b0); + b = v_uint8x32(g0); + c = v_uint8x32(r0); +} + +inline void v_load_deinterleave( const ushort* ptr, v_uint16x16& a, v_uint16x16& b, v_uint16x16& c ) +{ + __m256i bgr0 = _mm256_loadu_si256((const __m256i*)ptr); + __m256i bgr1 = _mm256_loadu_si256((const __m256i*)(ptr + 16)); + __m256i bgr2 = _mm256_loadu_si256((const __m256i*)(ptr + 32)); + + __m256i s02_low = _mm256_permute2x128_si256(bgr0, bgr2, 0 + 2*16); + __m256i s02_high = _mm256_permute2x128_si256(bgr0, bgr2, 1 + 3*16); + + const __m256i m0 = _mm256_setr_epi8(0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, + 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0); + const __m256i m1 = _mm256_setr_epi8(0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, + -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0); + __m256i b0 = _mm256_blendv_epi8(_mm256_blendv_epi8(s02_low, s02_high, m0), bgr1, m1); + __m256i g0 = _mm256_blendv_epi8(_mm256_blendv_epi8(bgr1, s02_low, m0), s02_high, m1); + __m256i r0 = _mm256_blendv_epi8(_mm256_blendv_epi8(s02_high, s02_low, m1), bgr1, m0); + const __m256i sh_b = _mm256_setr_epi8(0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, + 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11); + const __m256i sh_g = _mm256_setr_epi8(2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, + 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 0, 1, 6, 7, 12, 13); + const __m256i sh_r = _mm256_setr_epi8(4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, + 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15); + b0 = _mm256_shuffle_epi8(b0, sh_b); + g0 = _mm256_shuffle_epi8(g0, sh_g); + r0 = _mm256_shuffle_epi8(r0, sh_r); + + a = v_uint16x16(b0); + b = v_uint16x16(g0); + c = v_uint16x16(r0); +} + +inline void v_load_deinterleave( const unsigned* ptr, v_uint32x8& a, v_uint32x8& b, v_uint32x8& c ) +{ + __m256i bgr0 = _mm256_loadu_si256((const __m256i*)ptr); + __m256i bgr1 = _mm256_loadu_si256((const __m256i*)(ptr + 8)); + __m256i bgr2 = _mm256_loadu_si256((const __m256i*)(ptr + 16)); + + __m256i s02_low = _mm256_permute2x128_si256(bgr0, bgr2, 0 + 2*16); + __m256i s02_high = _mm256_permute2x128_si256(bgr0, bgr2, 1 + 3*16); + + __m256i b0 = _mm256_blend_epi32(_mm256_blend_epi32(s02_low, s02_high, 0x24), bgr1, 0x92); + __m256i g0 = _mm256_blend_epi32(_mm256_blend_epi32(s02_high, s02_low, 0x92), bgr1, 0x24); + __m256i r0 = _mm256_blend_epi32(_mm256_blend_epi32(bgr1, s02_low, 0x24), s02_high, 0x92); + + b0 = _mm256_shuffle_epi32(b0, 0x6c); + g0 = _mm256_shuffle_epi32(g0, 0xb1); + r0 = _mm256_shuffle_epi32(r0, 0xc6); + + a = v_uint32x8(b0); + b = v_uint32x8(g0); + c = v_uint32x8(r0); +} + +inline void v_load_deinterleave( const uint64* ptr, v_uint64x4& a, v_uint64x4& b, v_uint64x4& c ) +{ + __m256i bgr0 = _mm256_loadu_si256((const __m256i*)ptr); + __m256i bgr1 = _mm256_loadu_si256((const __m256i*)(ptr + 4)); + __m256i bgr2 = _mm256_loadu_si256((const __m256i*)(ptr + 8)); + + __m256i s01 = _mm256_blend_epi32(bgr0, bgr1, 0xf0); + __m256i s12 = _mm256_blend_epi32(bgr1, bgr2, 0xf0); + __m256i s20r = _mm256_permute4x64_epi64(_mm256_blend_epi32(bgr2, bgr0, 0xf0), 0x1b); + __m256i b0 = _mm256_unpacklo_epi64(s01, s20r); + __m256i g0 = _mm256_alignr_epi8(s12, s01, 8); + __m256i r0 = _mm256_unpackhi_epi64(s20r, s12); + + a = v_uint64x4(b0); + b = v_uint64x4(g0); + c = v_uint64x4(r0); +} + +inline void v_load_deinterleave( const uchar* ptr, v_uint8x32& a, v_uint8x32& b, v_uint8x32& c, v_uint8x32& d ) +{ + __m256i bgr0 = _mm256_loadu_si256((const __m256i*)ptr); + __m256i bgr1 = _mm256_loadu_si256((const __m256i*)(ptr + 32)); + __m256i bgr2 = _mm256_loadu_si256((const __m256i*)(ptr + 64)); + __m256i bgr3 = _mm256_loadu_si256((const __m256i*)(ptr + 96)); + const __m256i sh = _mm256_setr_epi8(0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, + 0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15); + + __m256i p0 = _mm256_shuffle_epi8(bgr0, sh); + __m256i p1 = _mm256_shuffle_epi8(bgr1, sh); + __m256i p2 = _mm256_shuffle_epi8(bgr2, sh); + __m256i p3 = _mm256_shuffle_epi8(bgr3, sh); + + __m256i p01l = _mm256_unpacklo_epi32(p0, p1); + __m256i p01h = _mm256_unpackhi_epi32(p0, p1); + __m256i p23l = _mm256_unpacklo_epi32(p2, p3); + __m256i p23h = _mm256_unpackhi_epi32(p2, p3); + + __m256i pll = _mm256_permute2x128_si256(p01l, p23l, 0 + 2*16); + __m256i plh = _mm256_permute2x128_si256(p01l, p23l, 1 + 3*16); + __m256i phl = _mm256_permute2x128_si256(p01h, p23h, 0 + 2*16); + __m256i phh = _mm256_permute2x128_si256(p01h, p23h, 1 + 3*16); + + __m256i b0 = _mm256_unpacklo_epi32(pll, plh); + __m256i g0 = _mm256_unpackhi_epi32(pll, plh); + __m256i r0 = _mm256_unpacklo_epi32(phl, phh); + __m256i a0 = _mm256_unpackhi_epi32(phl, phh); + + a = v_uint8x32(b0); + b = v_uint8x32(g0); + c = v_uint8x32(r0); + d = v_uint8x32(a0); +} + +inline void v_load_deinterleave( const ushort* ptr, v_uint16x16& a, v_uint16x16& b, v_uint16x16& c, v_uint16x16& d ) +{ + __m256i bgr0 = _mm256_loadu_si256((const __m256i*)ptr); + __m256i bgr1 = _mm256_loadu_si256((const __m256i*)(ptr + 16)); + __m256i bgr2 = _mm256_loadu_si256((const __m256i*)(ptr + 32)); + __m256i bgr3 = _mm256_loadu_si256((const __m256i*)(ptr + 48)); + const __m256i sh = _mm256_setr_epi8(0, 1, 8, 9, 2, 3, 10, 11, 4, 5, 12, 13, 6, 7, 14, 15, + 0, 1, 8, 9, 2, 3, 10, 11, 4, 5, 12, 13, 6, 7, 14, 15); + __m256i p0 = _mm256_shuffle_epi8(bgr0, sh); + __m256i p1 = _mm256_shuffle_epi8(bgr1, sh); + __m256i p2 = _mm256_shuffle_epi8(bgr2, sh); + __m256i p3 = _mm256_shuffle_epi8(bgr3, sh); + + __m256i p01l = _mm256_unpacklo_epi32(p0, p1); + __m256i p01h = _mm256_unpackhi_epi32(p0, p1); + __m256i p23l = _mm256_unpacklo_epi32(p2, p3); + __m256i p23h = _mm256_unpackhi_epi32(p2, p3); + + __m256i pll = _mm256_permute2x128_si256(p01l, p23l, 0 + 2*16); + __m256i plh = _mm256_permute2x128_si256(p01l, p23l, 1 + 3*16); + __m256i phl = _mm256_permute2x128_si256(p01h, p23h, 0 + 2*16); + __m256i phh = _mm256_permute2x128_si256(p01h, p23h, 1 + 3*16); + + __m256i b0 = _mm256_unpacklo_epi32(pll, plh); + __m256i g0 = _mm256_unpackhi_epi32(pll, plh); + __m256i r0 = _mm256_unpacklo_epi32(phl, phh); + __m256i a0 = _mm256_unpackhi_epi32(phl, phh); + + a = v_uint16x16(b0); + b = v_uint16x16(g0); + c = v_uint16x16(r0); + d = v_uint16x16(a0); +} + +inline void v_load_deinterleave( const unsigned* ptr, v_uint32x8& a, v_uint32x8& b, v_uint32x8& c, v_uint32x8& d ) +{ + __m256i p0 = _mm256_loadu_si256((const __m256i*)ptr); + __m256i p1 = _mm256_loadu_si256((const __m256i*)(ptr + 8)); + __m256i p2 = _mm256_loadu_si256((const __m256i*)(ptr + 16)); + __m256i p3 = _mm256_loadu_si256((const __m256i*)(ptr + 24)); + + __m256i p01l = _mm256_unpacklo_epi32(p0, p1); + __m256i p01h = _mm256_unpackhi_epi32(p0, p1); + __m256i p23l = _mm256_unpacklo_epi32(p2, p3); + __m256i p23h = _mm256_unpackhi_epi32(p2, p3); + + __m256i pll = _mm256_permute2x128_si256(p01l, p23l, 0 + 2*16); + __m256i plh = _mm256_permute2x128_si256(p01l, p23l, 1 + 3*16); + __m256i phl = _mm256_permute2x128_si256(p01h, p23h, 0 + 2*16); + __m256i phh = _mm256_permute2x128_si256(p01h, p23h, 1 + 3*16); + + __m256i b0 = _mm256_unpacklo_epi32(pll, plh); + __m256i g0 = _mm256_unpackhi_epi32(pll, plh); + __m256i r0 = _mm256_unpacklo_epi32(phl, phh); + __m256i a0 = _mm256_unpackhi_epi32(phl, phh); + + a = v_uint32x8(b0); + b = v_uint32x8(g0); + c = v_uint32x8(r0); + d = v_uint32x8(a0); +} + +inline void v_load_deinterleave( const uint64* ptr, v_uint64x4& a, v_uint64x4& b, v_uint64x4& c, v_uint64x4& d ) +{ + __m256i bgra0 = _mm256_loadu_si256((const __m256i*)ptr); + __m256i bgra1 = _mm256_loadu_si256((const __m256i*)(ptr + 4)); + __m256i bgra2 = _mm256_loadu_si256((const __m256i*)(ptr + 8)); + __m256i bgra3 = _mm256_loadu_si256((const __m256i*)(ptr + 12)); + + __m256i l02 = _mm256_permute2x128_si256(bgra0, bgra2, 0 + 2*16); + __m256i h02 = _mm256_permute2x128_si256(bgra0, bgra2, 1 + 3*16); + __m256i l13 = _mm256_permute2x128_si256(bgra1, bgra3, 0 + 2*16); + __m256i h13 = _mm256_permute2x128_si256(bgra1, bgra3, 1 + 3*16); + + __m256i b0 = _mm256_unpacklo_epi64(l02, l13); + __m256i g0 = _mm256_unpackhi_epi64(l02, l13); + __m256i r0 = _mm256_unpacklo_epi64(h02, h13); + __m256i a0 = _mm256_unpackhi_epi64(h02, h13); + + a = v_uint64x4(b0); + b = v_uint64x4(g0); + c = v_uint64x4(r0); + d = v_uint64x4(a0); +} + +///////////////////////////// store interleave ///////////////////////////////////// + +inline void v_store_interleave( uchar* ptr, const v_uint8x32& x, const v_uint8x32& y, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m256i xy_l = _mm256_unpacklo_epi8(x.val, y.val); + __m256i xy_h = _mm256_unpackhi_epi8(x.val, y.val); + + __m256i xy0 = _mm256_permute2x128_si256(xy_l, xy_h, 0 + 2*16); + __m256i xy1 = _mm256_permute2x128_si256(xy_l, xy_h, 1 + 3*16); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm256_stream_si256((__m256i*)ptr, xy0); + _mm256_stream_si256((__m256i*)(ptr + 32), xy1); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm256_store_si256((__m256i*)ptr, xy0); + _mm256_store_si256((__m256i*)(ptr + 32), xy1); + } + else + { + _mm256_storeu_si256((__m256i*)ptr, xy0); + _mm256_storeu_si256((__m256i*)(ptr + 32), xy1); + } +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x16& x, const v_uint16x16& y, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m256i xy_l = _mm256_unpacklo_epi16(x.val, y.val); + __m256i xy_h = _mm256_unpackhi_epi16(x.val, y.val); + + __m256i xy0 = _mm256_permute2x128_si256(xy_l, xy_h, 0 + 2*16); + __m256i xy1 = _mm256_permute2x128_si256(xy_l, xy_h, 1 + 3*16); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm256_stream_si256((__m256i*)ptr, xy0); + _mm256_stream_si256((__m256i*)(ptr + 16), xy1); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm256_store_si256((__m256i*)ptr, xy0); + _mm256_store_si256((__m256i*)(ptr + 16), xy1); + } + else + { + _mm256_storeu_si256((__m256i*)ptr, xy0); + _mm256_storeu_si256((__m256i*)(ptr + 16), xy1); + } +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x8& x, const v_uint32x8& y, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m256i xy_l = _mm256_unpacklo_epi32(x.val, y.val); + __m256i xy_h = _mm256_unpackhi_epi32(x.val, y.val); + + __m256i xy0 = _mm256_permute2x128_si256(xy_l, xy_h, 0 + 2*16); + __m256i xy1 = _mm256_permute2x128_si256(xy_l, xy_h, 1 + 3*16); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm256_stream_si256((__m256i*)ptr, xy0); + _mm256_stream_si256((__m256i*)(ptr + 8), xy1); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm256_store_si256((__m256i*)ptr, xy0); + _mm256_store_si256((__m256i*)(ptr + 8), xy1); + } + else + { + _mm256_storeu_si256((__m256i*)ptr, xy0); + _mm256_storeu_si256((__m256i*)(ptr + 8), xy1); + } +} + +inline void v_store_interleave( uint64* ptr, const v_uint64x4& x, const v_uint64x4& y, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m256i xy_l = _mm256_unpacklo_epi64(x.val, y.val); + __m256i xy_h = _mm256_unpackhi_epi64(x.val, y.val); + + __m256i xy0 = _mm256_permute2x128_si256(xy_l, xy_h, 0 + 2*16); + __m256i xy1 = _mm256_permute2x128_si256(xy_l, xy_h, 1 + 3*16); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm256_stream_si256((__m256i*)ptr, xy0); + _mm256_stream_si256((__m256i*)(ptr + 4), xy1); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm256_store_si256((__m256i*)ptr, xy0); + _mm256_store_si256((__m256i*)(ptr + 4), xy1); + } + else + { + _mm256_storeu_si256((__m256i*)ptr, xy0); + _mm256_storeu_si256((__m256i*)(ptr + 4), xy1); + } +} + +inline void v_store_interleave( uchar* ptr, const v_uint8x32& a, const v_uint8x32& b, const v_uint8x32& c, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + const __m256i sh_b = _mm256_setr_epi8( + 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5, + 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5); + const __m256i sh_g = _mm256_setr_epi8( + 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, + 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10); + const __m256i sh_r = _mm256_setr_epi8( + 10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, + 10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15); + + __m256i b0 = _mm256_shuffle_epi8(a.val, sh_b); + __m256i g0 = _mm256_shuffle_epi8(b.val, sh_g); + __m256i r0 = _mm256_shuffle_epi8(c.val, sh_r); + + const __m256i m0 = _mm256_setr_epi8(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, + 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); + const __m256i m1 = _mm256_setr_epi8(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, + 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0); + + __m256i p0 = _mm256_blendv_epi8(_mm256_blendv_epi8(b0, g0, m0), r0, m1); + __m256i p1 = _mm256_blendv_epi8(_mm256_blendv_epi8(g0, r0, m0), b0, m1); + __m256i p2 = _mm256_blendv_epi8(_mm256_blendv_epi8(r0, b0, m0), g0, m1); + + __m256i bgr0 = _mm256_permute2x128_si256(p0, p1, 0 + 2*16); + __m256i bgr1 = _mm256_permute2x128_si256(p2, p0, 0 + 3*16); + __m256i bgr2 = _mm256_permute2x128_si256(p1, p2, 1 + 3*16); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm256_stream_si256((__m256i*)ptr, bgr0); + _mm256_stream_si256((__m256i*)(ptr + 32), bgr1); + _mm256_stream_si256((__m256i*)(ptr + 64), bgr2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm256_store_si256((__m256i*)ptr, bgr0); + _mm256_store_si256((__m256i*)(ptr + 32), bgr1); + _mm256_store_si256((__m256i*)(ptr + 64), bgr2); + } + else + { + _mm256_storeu_si256((__m256i*)ptr, bgr0); + _mm256_storeu_si256((__m256i*)(ptr + 32), bgr1); + _mm256_storeu_si256((__m256i*)(ptr + 64), bgr2); + } +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x16& a, const v_uint16x16& b, const v_uint16x16& c, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + const __m256i sh_b = _mm256_setr_epi8( + 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, + 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11); + const __m256i sh_g = _mm256_setr_epi8( + 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, + 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5); + const __m256i sh_r = _mm256_setr_epi8( + 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, + 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15); + + __m256i b0 = _mm256_shuffle_epi8(a.val, sh_b); + __m256i g0 = _mm256_shuffle_epi8(b.val, sh_g); + __m256i r0 = _mm256_shuffle_epi8(c.val, sh_r); + + const __m256i m0 = _mm256_setr_epi8(0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, + 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0); + const __m256i m1 = _mm256_setr_epi8(0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, + -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0); + + __m256i p0 = _mm256_blendv_epi8(_mm256_blendv_epi8(b0, g0, m0), r0, m1); + __m256i p1 = _mm256_blendv_epi8(_mm256_blendv_epi8(g0, r0, m0), b0, m1); + __m256i p2 = _mm256_blendv_epi8(_mm256_blendv_epi8(r0, b0, m0), g0, m1); + + __m256i bgr0 = _mm256_permute2x128_si256(p0, p2, 0 + 2*16); + //__m256i bgr1 = p1; + __m256i bgr2 = _mm256_permute2x128_si256(p0, p2, 1 + 3*16); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm256_stream_si256((__m256i*)ptr, bgr0); + _mm256_stream_si256((__m256i*)(ptr + 16), p1); + _mm256_stream_si256((__m256i*)(ptr + 32), bgr2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm256_store_si256((__m256i*)ptr, bgr0); + _mm256_store_si256((__m256i*)(ptr + 16), p1); + _mm256_store_si256((__m256i*)(ptr + 32), bgr2); + } + else + { + _mm256_storeu_si256((__m256i*)ptr, bgr0); + _mm256_storeu_si256((__m256i*)(ptr + 16), p1); + _mm256_storeu_si256((__m256i*)(ptr + 32), bgr2); + } +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x8& a, const v_uint32x8& b, const v_uint32x8& c, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m256i b0 = _mm256_shuffle_epi32(a.val, 0x6c); + __m256i g0 = _mm256_shuffle_epi32(b.val, 0xb1); + __m256i r0 = _mm256_shuffle_epi32(c.val, 0xc6); + + __m256i p0 = _mm256_blend_epi32(_mm256_blend_epi32(b0, g0, 0x92), r0, 0x24); + __m256i p1 = _mm256_blend_epi32(_mm256_blend_epi32(g0, r0, 0x92), b0, 0x24); + __m256i p2 = _mm256_blend_epi32(_mm256_blend_epi32(r0, b0, 0x92), g0, 0x24); + + __m256i bgr0 = _mm256_permute2x128_si256(p0, p1, 0 + 2*16); + //__m256i bgr1 = p2; + __m256i bgr2 = _mm256_permute2x128_si256(p0, p1, 1 + 3*16); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm256_stream_si256((__m256i*)ptr, bgr0); + _mm256_stream_si256((__m256i*)(ptr + 8), p2); + _mm256_stream_si256((__m256i*)(ptr + 16), bgr2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm256_store_si256((__m256i*)ptr, bgr0); + _mm256_store_si256((__m256i*)(ptr + 8), p2); + _mm256_store_si256((__m256i*)(ptr + 16), bgr2); + } + else + { + _mm256_storeu_si256((__m256i*)ptr, bgr0); + _mm256_storeu_si256((__m256i*)(ptr + 8), p2); + _mm256_storeu_si256((__m256i*)(ptr + 16), bgr2); + } +} + +inline void v_store_interleave( uint64* ptr, const v_uint64x4& a, const v_uint64x4& b, const v_uint64x4& c, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m256i s01 = _mm256_unpacklo_epi64(a.val, b.val); + __m256i s12 = _mm256_unpackhi_epi64(b.val, c.val); + __m256i s20 = _mm256_blend_epi32(c.val, a.val, 0xcc); + + __m256i bgr0 = _mm256_permute2x128_si256(s01, s20, 0 + 2*16); + __m256i bgr1 = _mm256_blend_epi32(s01, s12, 0x0f); + __m256i bgr2 = _mm256_permute2x128_si256(s20, s12, 1 + 3*16); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm256_stream_si256((__m256i*)ptr, bgr0); + _mm256_stream_si256((__m256i*)(ptr + 4), bgr1); + _mm256_stream_si256((__m256i*)(ptr + 8), bgr2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm256_store_si256((__m256i*)ptr, bgr0); + _mm256_store_si256((__m256i*)(ptr + 4), bgr1); + _mm256_store_si256((__m256i*)(ptr + 8), bgr2); + } + else + { + _mm256_storeu_si256((__m256i*)ptr, bgr0); + _mm256_storeu_si256((__m256i*)(ptr + 4), bgr1); + _mm256_storeu_si256((__m256i*)(ptr + 8), bgr2); + } +} + +inline void v_store_interleave( uchar* ptr, const v_uint8x32& a, const v_uint8x32& b, + const v_uint8x32& c, const v_uint8x32& d, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m256i bg0 = _mm256_unpacklo_epi8(a.val, b.val); + __m256i bg1 = _mm256_unpackhi_epi8(a.val, b.val); + __m256i ra0 = _mm256_unpacklo_epi8(c.val, d.val); + __m256i ra1 = _mm256_unpackhi_epi8(c.val, d.val); + + __m256i bgra0_ = _mm256_unpacklo_epi16(bg0, ra0); + __m256i bgra1_ = _mm256_unpackhi_epi16(bg0, ra0); + __m256i bgra2_ = _mm256_unpacklo_epi16(bg1, ra1); + __m256i bgra3_ = _mm256_unpackhi_epi16(bg1, ra1); + + __m256i bgra0 = _mm256_permute2x128_si256(bgra0_, bgra1_, 0 + 2*16); + __m256i bgra2 = _mm256_permute2x128_si256(bgra0_, bgra1_, 1 + 3*16); + __m256i bgra1 = _mm256_permute2x128_si256(bgra2_, bgra3_, 0 + 2*16); + __m256i bgra3 = _mm256_permute2x128_si256(bgra2_, bgra3_, 1 + 3*16); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm256_stream_si256((__m256i*)ptr, bgra0); + _mm256_stream_si256((__m256i*)(ptr + 32), bgra1); + _mm256_stream_si256((__m256i*)(ptr + 64), bgra2); + _mm256_stream_si256((__m256i*)(ptr + 96), bgra3); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm256_store_si256((__m256i*)ptr, bgra0); + _mm256_store_si256((__m256i*)(ptr + 32), bgra1); + _mm256_store_si256((__m256i*)(ptr + 64), bgra2); + _mm256_store_si256((__m256i*)(ptr + 96), bgra3); + } + else + { + _mm256_storeu_si256((__m256i*)ptr, bgra0); + _mm256_storeu_si256((__m256i*)(ptr + 32), bgra1); + _mm256_storeu_si256((__m256i*)(ptr + 64), bgra2); + _mm256_storeu_si256((__m256i*)(ptr + 96), bgra3); + } +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x16& a, const v_uint16x16& b, + const v_uint16x16& c, const v_uint16x16& d, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m256i bg0 = _mm256_unpacklo_epi16(a.val, b.val); + __m256i bg1 = _mm256_unpackhi_epi16(a.val, b.val); + __m256i ra0 = _mm256_unpacklo_epi16(c.val, d.val); + __m256i ra1 = _mm256_unpackhi_epi16(c.val, d.val); + + __m256i bgra0_ = _mm256_unpacklo_epi32(bg0, ra0); + __m256i bgra1_ = _mm256_unpackhi_epi32(bg0, ra0); + __m256i bgra2_ = _mm256_unpacklo_epi32(bg1, ra1); + __m256i bgra3_ = _mm256_unpackhi_epi32(bg1, ra1); + + __m256i bgra0 = _mm256_permute2x128_si256(bgra0_, bgra1_, 0 + 2*16); + __m256i bgra2 = _mm256_permute2x128_si256(bgra0_, bgra1_, 1 + 3*16); + __m256i bgra1 = _mm256_permute2x128_si256(bgra2_, bgra3_, 0 + 2*16); + __m256i bgra3 = _mm256_permute2x128_si256(bgra2_, bgra3_, 1 + 3*16); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm256_stream_si256((__m256i*)ptr, bgra0); + _mm256_stream_si256((__m256i*)(ptr + 16), bgra1); + _mm256_stream_si256((__m256i*)(ptr + 32), bgra2); + _mm256_stream_si256((__m256i*)(ptr + 48), bgra3); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm256_store_si256((__m256i*)ptr, bgra0); + _mm256_store_si256((__m256i*)(ptr + 16), bgra1); + _mm256_store_si256((__m256i*)(ptr + 32), bgra2); + _mm256_store_si256((__m256i*)(ptr + 48), bgra3); + } + else + { + _mm256_storeu_si256((__m256i*)ptr, bgra0); + _mm256_storeu_si256((__m256i*)(ptr + 16), bgra1); + _mm256_storeu_si256((__m256i*)(ptr + 32), bgra2); + _mm256_storeu_si256((__m256i*)(ptr + 48), bgra3); + } +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x8& a, const v_uint32x8& b, + const v_uint32x8& c, const v_uint32x8& d, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m256i bg0 = _mm256_unpacklo_epi32(a.val, b.val); + __m256i bg1 = _mm256_unpackhi_epi32(a.val, b.val); + __m256i ra0 = _mm256_unpacklo_epi32(c.val, d.val); + __m256i ra1 = _mm256_unpackhi_epi32(c.val, d.val); + + __m256i bgra0_ = _mm256_unpacklo_epi64(bg0, ra0); + __m256i bgra1_ = _mm256_unpackhi_epi64(bg0, ra0); + __m256i bgra2_ = _mm256_unpacklo_epi64(bg1, ra1); + __m256i bgra3_ = _mm256_unpackhi_epi64(bg1, ra1); + + __m256i bgra0 = _mm256_permute2x128_si256(bgra0_, bgra1_, 0 + 2*16); + __m256i bgra2 = _mm256_permute2x128_si256(bgra0_, bgra1_, 1 + 3*16); + __m256i bgra1 = _mm256_permute2x128_si256(bgra2_, bgra3_, 0 + 2*16); + __m256i bgra3 = _mm256_permute2x128_si256(bgra2_, bgra3_, 1 + 3*16); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm256_stream_si256((__m256i*)ptr, bgra0); + _mm256_stream_si256((__m256i*)(ptr + 8), bgra1); + _mm256_stream_si256((__m256i*)(ptr + 16), bgra2); + _mm256_stream_si256((__m256i*)(ptr + 24), bgra3); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm256_store_si256((__m256i*)ptr, bgra0); + _mm256_store_si256((__m256i*)(ptr + 8), bgra1); + _mm256_store_si256((__m256i*)(ptr + 16), bgra2); + _mm256_store_si256((__m256i*)(ptr + 24), bgra3); + } + else + { + _mm256_storeu_si256((__m256i*)ptr, bgra0); + _mm256_storeu_si256((__m256i*)(ptr + 8), bgra1); + _mm256_storeu_si256((__m256i*)(ptr + 16), bgra2); + _mm256_storeu_si256((__m256i*)(ptr + 24), bgra3); + } +} + +inline void v_store_interleave( uint64* ptr, const v_uint64x4& a, const v_uint64x4& b, + const v_uint64x4& c, const v_uint64x4& d, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m256i bg0 = _mm256_unpacklo_epi64(a.val, b.val); + __m256i bg1 = _mm256_unpackhi_epi64(a.val, b.val); + __m256i ra0 = _mm256_unpacklo_epi64(c.val, d.val); + __m256i ra1 = _mm256_unpackhi_epi64(c.val, d.val); + + __m256i bgra0 = _mm256_permute2x128_si256(bg0, ra0, 0 + 2*16); + __m256i bgra1 = _mm256_permute2x128_si256(bg1, ra1, 0 + 2*16); + __m256i bgra2 = _mm256_permute2x128_si256(bg0, ra0, 1 + 3*16); + __m256i bgra3 = _mm256_permute2x128_si256(bg1, ra1, 1 + 3*16); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm256_stream_si256((__m256i*)ptr, bgra0); + _mm256_stream_si256((__m256i*)(ptr + 4), bgra1); + _mm256_stream_si256((__m256i*)(ptr + 8), bgra2); + _mm256_stream_si256((__m256i*)(ptr + 12), bgra3); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm256_store_si256((__m256i*)ptr, bgra0); + _mm256_store_si256((__m256i*)(ptr + 4), bgra1); + _mm256_store_si256((__m256i*)(ptr + 8), bgra2); + _mm256_store_si256((__m256i*)(ptr + 12), bgra3); + } + else + { + _mm256_storeu_si256((__m256i*)ptr, bgra0); + _mm256_storeu_si256((__m256i*)(ptr + 4), bgra1); + _mm256_storeu_si256((__m256i*)(ptr + 8), bgra2); + _mm256_storeu_si256((__m256i*)(ptr + 12), bgra3); + } +} + +#define OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(_Tpvec0, _Tp0, suffix0, _Tpvec1, _Tp1, suffix1) \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0 ) \ +{ \ + _Tpvec1 a1, b1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ +} \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0 ) \ +{ \ + _Tpvec1 a1, b1, c1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ + c0 = v_reinterpret_as_##suffix0(c1); \ +} \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0, _Tpvec0& d0 ) \ +{ \ + _Tpvec1 a1, b1, c1, d1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1, d1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ + c0 = v_reinterpret_as_##suffix0(c1); \ + d0 = v_reinterpret_as_##suffix0(d1); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + hal::StoreMode mode=hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, mode); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, const _Tpvec0& c0, \ + hal::StoreMode mode=hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, c1, mode); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + const _Tpvec0& c0, const _Tpvec0& d0, \ + hal::StoreMode mode=hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ + _Tpvec1 d1 = v_reinterpret_as_##suffix1(d0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, c1, d1, mode); \ +} + +OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_int8x32, schar, s8, v_uint8x32, uchar, u8) +OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_int16x16, short, s16, v_uint16x16, ushort, u16) +OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_int32x8, int, s32, v_uint32x8, unsigned, u32) +OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_float32x8, float, f32, v_uint32x8, unsigned, u32) +OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_int64x4, int64, s64, v_uint64x4, uint64, u64) +OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_float64x4, double, f64, v_uint64x4, uint64, u64) + +// +// FP16 +// + +inline v_float32x8 v256_load_expand(const hfloat* ptr) +{ +#if CV_FP16 + return v_float32x8(_mm256_cvtph_ps(_mm_loadu_si128((const __m128i*)ptr))); +#else + float CV_DECL_ALIGNED(32) buf[8]; + for (int i = 0; i < 8; i++) + buf[i] = (float)ptr[i]; + return v256_load_aligned(buf); +#endif +} + +inline void v_pack_store(hfloat* ptr, const v_float32x8& a) +{ +#if CV_FP16 + __m128i ah = _mm256_cvtps_ph(a.val, 0); + _mm_storeu_si128((__m128i*)ptr, ah); +#else + float CV_DECL_ALIGNED(32) buf[8]; + v_store_aligned(buf, a); + for (int i = 0; i < 8; i++) + ptr[i] = hfloat(buf[i]); +#endif +} + +// +// end of FP16 +// + +inline void v256_cleanup() { _mm256_zeroall(); } + +#include "intrin_math.hpp" +inline v_float32x8 v_exp(const v_float32x8& x) { return v_exp_default_32f(x); } +inline v_float32x8 v_log(const v_float32x8& x) { return v_log_default_32f(x); } +inline void v_sincos(const v_float32x8& x, v_float32x8& s, v_float32x8& c) { v_sincos_default_32f(x, s, c); } +inline v_float32x8 v_sin(const v_float32x8& x) { return v_sin_default_32f(x); } +inline v_float32x8 v_cos(const v_float32x8& x) { return v_cos_default_32f(x); } +inline v_float32x8 v_erf(const v_float32x8& x) { return v_erf_default_32f(x); } + +inline v_float64x4 v_exp(const v_float64x4& x) { return v_exp_default_64f(x); } +inline v_float64x4 v_log(const v_float64x4& x) { return v_log_default_64f(x); } +inline void v_sincos(const v_float64x4& x, v_float64x4& s, v_float64x4& c) { v_sincos_default_64f(x, s, c); } +inline v_float64x4 v_sin(const v_float64x4& x) { return v_sin_default_64f(x); } +inline v_float64x4 v_cos(const v_float64x4& x) { return v_cos_default_64f(x); } + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} // cv:: + +#endif // OPENCV_HAL_INTRIN_AVX_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_avx512.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_avx512.hpp index 077b4d17a7..9d6eee2dde 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_avx512.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_avx512.hpp @@ -1,3101 +1,3101 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -#ifndef OPENCV_HAL_INTRIN_AVX512_HPP -#define OPENCV_HAL_INTRIN_AVX512_HPP - -#if defined(_MSC_VER) && (_MSC_VER < 1920/*MSVS2019*/) -# pragma warning(disable:4146) // unary minus operator applied to unsigned type, result still unsigned -# pragma warning(disable:4309) // 'argument': truncation of constant value -# pragma warning(disable:4310) // cast truncates constant value -#endif - -#define CVT_ROUND_MODES_IMPLEMENTED 0 - -#define CV_SIMD512 1 -#define CV_SIMD512_64F 1 -#define CV_SIMD512_FP16 0 // no native operations with FP16 type. Only load/store from float32x8 are available (if CV_FP16 == 1) - -#define _v512_set_epu64(a7, a6, a5, a4, a3, a2, a1, a0) _mm512_set_epi64((int64)(a7),(int64)(a6),(int64)(a5),(int64)(a4),(int64)(a3),(int64)(a2),(int64)(a1),(int64)(a0)) -#define _v512_set_epu32(a15, a14, a13, a12, a11, a10, a9, a8, a7, a6, a5, a4, a3, a2, a1, a0) \ - _mm512_set_epi64(((int64)(a15)<<32)|(int64)(a14), ((int64)(a13)<<32)|(int64)(a12), ((int64)(a11)<<32)|(int64)(a10), ((int64)( a9)<<32)|(int64)( a8), \ - ((int64)( a7)<<32)|(int64)( a6), ((int64)( a5)<<32)|(int64)( a4), ((int64)( a3)<<32)|(int64)( a2), ((int64)( a1)<<32)|(int64)( a0)) -#define _v512_set_epu16(a31, a30, a29, a28, a27, a26, a25, a24, a23, a22, a21, a20, a19, a18, a17, a16, \ - a15, a14, a13, a12, a11, a10, a9, a8, a7, a6, a5, a4, a3, a2, a1, a0) \ - _v512_set_epu32(((unsigned)(a31)<<16)|(unsigned)(a30), ((unsigned)(a29)<<16)|(unsigned)(a28), ((unsigned)(a27)<<16)|(unsigned)(a26), ((unsigned)(a25)<<16)|(unsigned)(a24), \ - ((unsigned)(a23)<<16)|(unsigned)(a22), ((unsigned)(a21)<<16)|(unsigned)(a20), ((unsigned)(a19)<<16)|(unsigned)(a18), ((unsigned)(a17)<<16)|(unsigned)(a16), \ - ((unsigned)(a15)<<16)|(unsigned)(a14), ((unsigned)(a13)<<16)|(unsigned)(a12), ((unsigned)(a11)<<16)|(unsigned)(a10), ((unsigned)( a9)<<16)|(unsigned)( a8), \ - ((unsigned)( a7)<<16)|(unsigned)( a6), ((unsigned)( a5)<<16)|(unsigned)( a4), ((unsigned)( a3)<<16)|(unsigned)( a2), ((unsigned)( a1)<<16)|(unsigned)( a0)) -#define _v512_set_epu8(a63, a62, a61, a60, a59, a58, a57, a56, a55, a54, a53, a52, a51, a50, a49, a48, \ - a47, a46, a45, a44, a43, a42, a41, a40, a39, a38, a37, a36, a35, a34, a33, a32, \ - a31, a30, a29, a28, a27, a26, a25, a24, a23, a22, a21, a20, a19, a18, a17, a16, \ - a15, a14, a13, a12, a11, a10, a9, a8, a7, a6, a5, a4, a3, a2, a1, a0) \ - _v512_set_epu32(((unsigned)(a63)<<24)|((unsigned)(a62)<<16)|((unsigned)(a61)<<8)|(unsigned)(a60),((unsigned)(a59)<<24)|((unsigned)(a58)<<16)|((unsigned)(a57)<<8)|(unsigned)(a56), \ - ((unsigned)(a55)<<24)|((unsigned)(a54)<<16)|((unsigned)(a53)<<8)|(unsigned)(a52),((unsigned)(a51)<<24)|((unsigned)(a50)<<16)|((unsigned)(a49)<<8)|(unsigned)(a48), \ - ((unsigned)(a47)<<24)|((unsigned)(a46)<<16)|((unsigned)(a45)<<8)|(unsigned)(a44),((unsigned)(a43)<<24)|((unsigned)(a42)<<16)|((unsigned)(a41)<<8)|(unsigned)(a40), \ - ((unsigned)(a39)<<24)|((unsigned)(a38)<<16)|((unsigned)(a37)<<8)|(unsigned)(a36),((unsigned)(a35)<<24)|((unsigned)(a34)<<16)|((unsigned)(a33)<<8)|(unsigned)(a32), \ - ((unsigned)(a31)<<24)|((unsigned)(a30)<<16)|((unsigned)(a29)<<8)|(unsigned)(a28),((unsigned)(a27)<<24)|((unsigned)(a26)<<16)|((unsigned)(a25)<<8)|(unsigned)(a24), \ - ((unsigned)(a23)<<24)|((unsigned)(a22)<<16)|((unsigned)(a21)<<8)|(unsigned)(a20),((unsigned)(a19)<<24)|((unsigned)(a18)<<16)|((unsigned)(a17)<<8)|(unsigned)(a16), \ - ((unsigned)(a15)<<24)|((unsigned)(a14)<<16)|((unsigned)(a13)<<8)|(unsigned)(a12),((unsigned)(a11)<<24)|((unsigned)(a10)<<16)|((unsigned)( a9)<<8)|(unsigned)( a8), \ - ((unsigned)( a7)<<24)|((unsigned)( a6)<<16)|((unsigned)( a5)<<8)|(unsigned)( a4),((unsigned)( a3)<<24)|((unsigned)( a2)<<16)|((unsigned)( a1)<<8)|(unsigned)( a0)) -#define _v512_set_epi8(a63, a62, a61, a60, a59, a58, a57, a56, a55, a54, a53, a52, a51, a50, a49, a48, \ - a47, a46, a45, a44, a43, a42, a41, a40, a39, a38, a37, a36, a35, a34, a33, a32, \ - a31, a30, a29, a28, a27, a26, a25, a24, a23, a22, a21, a20, a19, a18, a17, a16, \ - a15, a14, a13, a12, a11, a10, a9, a8, a7, a6, a5, a4, a3, a2, a1, a0) \ - _v512_set_epu8((uchar)(a63), (uchar)(a62), (uchar)(a61), (uchar)(a60), (uchar)(a59), (uchar)(a58), (uchar)(a57), (uchar)(a56), \ - (uchar)(a55), (uchar)(a54), (uchar)(a53), (uchar)(a52), (uchar)(a51), (uchar)(a50), (uchar)(a49), (uchar)(a48), \ - (uchar)(a47), (uchar)(a46), (uchar)(a45), (uchar)(a44), (uchar)(a43), (uchar)(a42), (uchar)(a41), (uchar)(a40), \ - (uchar)(a39), (uchar)(a38), (uchar)(a37), (uchar)(a36), (uchar)(a35), (uchar)(a34), (uchar)(a33), (uchar)(a32), \ - (uchar)(a31), (uchar)(a30), (uchar)(a29), (uchar)(a28), (uchar)(a27), (uchar)(a26), (uchar)(a25), (uchar)(a24), \ - (uchar)(a23), (uchar)(a22), (uchar)(a21), (uchar)(a20), (uchar)(a19), (uchar)(a18), (uchar)(a17), (uchar)(a16), \ - (uchar)(a15), (uchar)(a14), (uchar)(a13), (uchar)(a12), (uchar)(a11), (uchar)(a10), (uchar)( a9), (uchar)( a8), \ - (uchar)( a7), (uchar)( a6), (uchar)( a5), (uchar)( a4), (uchar)( a3), (uchar)( a2), (uchar)( a1), (uchar)( a0)) - -#ifndef _mm512_cvtpd_pslo -#ifdef _mm512_zextsi256_si512 -#define _mm512_cvtpd_pslo(a) _mm512_zextps256_ps512(_mm512_cvtpd_ps(a)) -#else -//if preferred way to extend with zeros is unavailable -#define _mm512_cvtpd_pslo(a) _mm512_castps256_ps512(_mm512_cvtpd_ps(a)) -#endif -#endif -///////// Utils //////////// - -namespace -{ - -inline __m512i _v512_combine(const __m256i& lo, const __m256i& hi) -{ return _mm512_inserti32x8(_mm512_castsi256_si512(lo), hi, 1); } - -inline __m512 _v512_combine(const __m256& lo, const __m256& hi) -{ return _mm512_insertf32x8(_mm512_castps256_ps512(lo), hi, 1); } - -inline __m512d _v512_combine(const __m256d& lo, const __m256d& hi) -{ return _mm512_insertf64x4(_mm512_castpd256_pd512(lo), hi, 1); } - -inline int _v_cvtsi512_si32(const __m512i& a) -{ return _mm_cvtsi128_si32(_mm512_castsi512_si128(a)); } - -inline __m256i _v512_extract_high(const __m512i& v) -{ return _mm512_extracti32x8_epi32(v, 1); } - -inline __m256 _v512_extract_high(const __m512& v) -{ return _mm512_extractf32x8_ps(v, 1); } - -inline __m256d _v512_extract_high(const __m512d& v) -{ return _mm512_extractf64x4_pd(v, 1); } - -inline __m256i _v512_extract_low(const __m512i& v) -{ return _mm512_castsi512_si256(v); } - -inline __m256 _v512_extract_low(const __m512& v) -{ return _mm512_castps512_ps256(v); } - -inline __m256d _v512_extract_low(const __m512d& v) -{ return _mm512_castpd512_pd256(v); } - -inline __m512i _v512_insert(const __m512i& a, const __m256i& b) -{ return _mm512_inserti32x8(a, b, 0); } - -inline __m512 _v512_insert(const __m512& a, const __m256& b) -{ return _mm512_insertf32x8(a, b, 0); } - -inline __m512d _v512_insert(const __m512d& a, const __m256d& b) -{ return _mm512_insertf64x4(a, b, 0); } - -} - -namespace cv -{ - -//! @cond IGNORED - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -///////// Types //////////// - -struct v_uint8x64 -{ - typedef uchar lane_type; - enum { nlanes = 64 }; - __m512i val; - - explicit v_uint8x64(__m512i v) : val(v) {} - v_uint8x64(uchar v0, uchar v1, uchar v2, uchar v3, - uchar v4, uchar v5, uchar v6, uchar v7, - uchar v8, uchar v9, uchar v10, uchar v11, - uchar v12, uchar v13, uchar v14, uchar v15, - uchar v16, uchar v17, uchar v18, uchar v19, - uchar v20, uchar v21, uchar v22, uchar v23, - uchar v24, uchar v25, uchar v26, uchar v27, - uchar v28, uchar v29, uchar v30, uchar v31, - uchar v32, uchar v33, uchar v34, uchar v35, - uchar v36, uchar v37, uchar v38, uchar v39, - uchar v40, uchar v41, uchar v42, uchar v43, - uchar v44, uchar v45, uchar v46, uchar v47, - uchar v48, uchar v49, uchar v50, uchar v51, - uchar v52, uchar v53, uchar v54, uchar v55, - uchar v56, uchar v57, uchar v58, uchar v59, - uchar v60, uchar v61, uchar v62, uchar v63) - { - val = _v512_set_epu8(v63, v62, v61, v60, v59, v58, v57, v56, v55, v54, v53, v52, v51, v50, v49, v48, - v47, v46, v45, v44, v43, v42, v41, v40, v39, v38, v37, v36, v35, v34, v33, v32, - v31, v30, v29, v28, v27, v26, v25, v24, v23, v22, v21, v20, v19, v18, v17, v16, - v15, v14, v13, v12, v11, v10, v9, v8, v7, v6, v5, v4, v3, v2, v1, v0); - } - v_uint8x64() {} - - static inline v_uint8x64 zero() { return v_uint8x64(_mm512_setzero_si512()); } - - uchar get0() const { return (uchar)_v_cvtsi512_si32(val); } -}; - -struct v_int8x64 -{ - typedef schar lane_type; - enum { nlanes = 64 }; - __m512i val; - - explicit v_int8x64(__m512i v) : val(v) {} - v_int8x64(schar v0, schar v1, schar v2, schar v3, - schar v4, schar v5, schar v6, schar v7, - schar v8, schar v9, schar v10, schar v11, - schar v12, schar v13, schar v14, schar v15, - schar v16, schar v17, schar v18, schar v19, - schar v20, schar v21, schar v22, schar v23, - schar v24, schar v25, schar v26, schar v27, - schar v28, schar v29, schar v30, schar v31, - schar v32, schar v33, schar v34, schar v35, - schar v36, schar v37, schar v38, schar v39, - schar v40, schar v41, schar v42, schar v43, - schar v44, schar v45, schar v46, schar v47, - schar v48, schar v49, schar v50, schar v51, - schar v52, schar v53, schar v54, schar v55, - schar v56, schar v57, schar v58, schar v59, - schar v60, schar v61, schar v62, schar v63) - { - val = _v512_set_epi8(v63, v62, v61, v60, v59, v58, v57, v56, v55, v54, v53, v52, v51, v50, v49, v48, - v47, v46, v45, v44, v43, v42, v41, v40, v39, v38, v37, v36, v35, v34, v33, v32, - v31, v30, v29, v28, v27, v26, v25, v24, v23, v22, v21, v20, v19, v18, v17, v16, - v15, v14, v13, v12, v11, v10, v9, v8, v7, v6, v5, v4, v3, v2, v1, v0); - } - v_int8x64() {} - - static inline v_int8x64 zero() { return v_int8x64(_mm512_setzero_si512()); } - - schar get0() const { return (schar)_v_cvtsi512_si32(val); } -}; - -struct v_uint16x32 -{ - typedef ushort lane_type; - enum { nlanes = 32 }; - __m512i val; - - explicit v_uint16x32(__m512i v) : val(v) {} - v_uint16x32(ushort v0, ushort v1, ushort v2, ushort v3, - ushort v4, ushort v5, ushort v6, ushort v7, - ushort v8, ushort v9, ushort v10, ushort v11, - ushort v12, ushort v13, ushort v14, ushort v15, - ushort v16, ushort v17, ushort v18, ushort v19, - ushort v20, ushort v21, ushort v22, ushort v23, - ushort v24, ushort v25, ushort v26, ushort v27, - ushort v28, ushort v29, ushort v30, ushort v31) - { - val = _v512_set_epu16(v31, v30, v29, v28, v27, v26, v25, v24, v23, v22, v21, v20, v19, v18, v17, v16, - v15, v14, v13, v12, v11, v10, v9, v8, v7, v6, v5, v4, v3, v2, v1, v0); - } - v_uint16x32() {} - - static inline v_uint16x32 zero() { return v_uint16x32(_mm512_setzero_si512()); } - - ushort get0() const { return (ushort)_v_cvtsi512_si32(val); } -}; - -struct v_int16x32 -{ - typedef short lane_type; - enum { nlanes = 32 }; - __m512i val; - - explicit v_int16x32(__m512i v) : val(v) {} - v_int16x32(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7, - short v8, short v9, short v10, short v11, short v12, short v13, short v14, short v15, - short v16, short v17, short v18, short v19, short v20, short v21, short v22, short v23, - short v24, short v25, short v26, short v27, short v28, short v29, short v30, short v31) - { - val = _v512_set_epu16((ushort)v31, (ushort)v30, (ushort)v29, (ushort)v28, (ushort)v27, (ushort)v26, (ushort)v25, (ushort)v24, - (ushort)v23, (ushort)v22, (ushort)v21, (ushort)v20, (ushort)v19, (ushort)v18, (ushort)v17, (ushort)v16, - (ushort)v15, (ushort)v14, (ushort)v13, (ushort)v12, (ushort)v11, (ushort)v10, (ushort)v9 , (ushort)v8, - (ushort)v7 , (ushort)v6 , (ushort)v5 , (ushort)v4 , (ushort)v3 , (ushort)v2 , (ushort)v1 , (ushort)v0); - } - v_int16x32() {} - - static inline v_int16x32 zero() { return v_int16x32(_mm512_setzero_si512()); } - - short get0() const { return (short)_v_cvtsi512_si32(val); } -}; - -struct v_uint32x16 -{ - typedef unsigned lane_type; - enum { nlanes = 16 }; - __m512i val; - - explicit v_uint32x16(__m512i v) : val(v) {} - v_uint32x16(unsigned v0, unsigned v1, unsigned v2, unsigned v3, - unsigned v4, unsigned v5, unsigned v6, unsigned v7, - unsigned v8, unsigned v9, unsigned v10, unsigned v11, - unsigned v12, unsigned v13, unsigned v14, unsigned v15) - { - val = _mm512_setr_epi32((int)v0, (int)v1, (int)v2, (int)v3, (int)v4, (int)v5, (int)v6, (int)v7, - (int)v8, (int)v9, (int)v10, (int)v11, (int)v12, (int)v13, (int)v14, (int)v15); - } - v_uint32x16() {} - - static inline v_uint32x16 zero() { return v_uint32x16(_mm512_setzero_si512()); } - - unsigned get0() const { return (unsigned)_v_cvtsi512_si32(val); } -}; - -struct v_int32x16 -{ - typedef int lane_type; - enum { nlanes = 16 }; - __m512i val; - - explicit v_int32x16(__m512i v) : val(v) {} - v_int32x16(int v0, int v1, int v2, int v3, int v4, int v5, int v6, int v7, - int v8, int v9, int v10, int v11, int v12, int v13, int v14, int v15) - { - val = _mm512_setr_epi32(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15); - } - v_int32x16() {} - - static inline v_int32x16 zero() { return v_int32x16(_mm512_setzero_si512()); } - - int get0() const { return _v_cvtsi512_si32(val); } -}; - -struct v_float32x16 -{ - typedef float lane_type; - enum { nlanes = 16 }; - __m512 val; - - explicit v_float32x16(__m512 v) : val(v) {} - v_float32x16(float v0, float v1, float v2, float v3, float v4, float v5, float v6, float v7, - float v8, float v9, float v10, float v11, float v12, float v13, float v14, float v15) - { - val = _mm512_setr_ps(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15); - } - v_float32x16() {} - - static inline v_float32x16 zero() { return v_float32x16(_mm512_setzero_ps()); } - - float get0() const { return _mm_cvtss_f32(_mm512_castps512_ps128(val)); } -}; - -struct v_uint64x8 -{ - typedef uint64 lane_type; - enum { nlanes = 8 }; - __m512i val; - - explicit v_uint64x8(__m512i v) : val(v) {} - v_uint64x8(uint64 v0, uint64 v1, uint64 v2, uint64 v3, uint64 v4, uint64 v5, uint64 v6, uint64 v7) - { val = _mm512_setr_epi64((int64)v0, (int64)v1, (int64)v2, (int64)v3, (int64)v4, (int64)v5, (int64)v6, (int64)v7); } - v_uint64x8() {} - - static inline v_uint64x8 zero() { return v_uint64x8(_mm512_setzero_si512()); } - - uint64 get0() const - { - #if defined __x86_64__ || defined _M_X64 - return (uint64)_mm_cvtsi128_si64(_mm512_castsi512_si128(val)); - #else - int a = _mm_cvtsi128_si32(_mm512_castsi512_si128(val)); - int b = _mm_cvtsi128_si32(_mm512_castsi512_si128(_mm512_srli_epi64(val, 32))); - return (unsigned)a | ((uint64)(unsigned)b << 32); - #endif - } -}; - -struct v_int64x8 -{ - typedef int64 lane_type; - enum { nlanes = 8 }; - __m512i val; - - explicit v_int64x8(__m512i v) : val(v) {} - v_int64x8(int64 v0, int64 v1, int64 v2, int64 v3, int64 v4, int64 v5, int64 v6, int64 v7) - { val = _mm512_setr_epi64(v0, v1, v2, v3, v4, v5, v6, v7); } - v_int64x8() {} - - static inline v_int64x8 zero() { return v_int64x8(_mm512_setzero_si512()); } - - int64 get0() const - { - #if defined __x86_64__ || defined _M_X64 - return (int64)_mm_cvtsi128_si64(_mm512_castsi512_si128(val)); - #else - int a = _mm_cvtsi128_si32(_mm512_castsi512_si128(val)); - int b = _mm_cvtsi128_si32(_mm512_castsi512_si128(_mm512_srli_epi64(val, 32))); - return (int64)((unsigned)a | ((uint64)(unsigned)b << 32)); - #endif - } -}; - -struct v_float64x8 -{ - typedef double lane_type; - enum { nlanes = 8 }; - __m512d val; - - explicit v_float64x8(__m512d v) : val(v) {} - v_float64x8(double v0, double v1, double v2, double v3, double v4, double v5, double v6, double v7) - { val = _mm512_setr_pd(v0, v1, v2, v3, v4, v5, v6, v7); } - v_float64x8() {} - - static inline v_float64x8 zero() { return v_float64x8(_mm512_setzero_pd()); } - - double get0() const { return _mm_cvtsd_f64(_mm512_castpd512_pd128(val)); } -}; - -//////////////// Load and store operations /////////////// - -#define OPENCV_HAL_IMPL_AVX512_LOADSTORE(_Tpvec, _Tp) \ - inline _Tpvec v512_load(const _Tp* ptr) \ - { return _Tpvec(_mm512_loadu_si512((const __m512i*)ptr)); } \ - inline _Tpvec v512_load_aligned(const _Tp* ptr) \ - { return _Tpvec(_mm512_load_si512((const __m512i*)ptr)); } \ - inline _Tpvec v512_load_low(const _Tp* ptr) \ - { \ - __m256i v256 = _mm256_loadu_si256((const __m256i*)ptr); \ - return _Tpvec(_mm512_castsi256_si512(v256)); \ - } \ - inline _Tpvec v512_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ - { \ - __m256i vlo = _mm256_loadu_si256((const __m256i*)ptr0); \ - __m256i vhi = _mm256_loadu_si256((const __m256i*)ptr1); \ - return _Tpvec(_v512_combine(vlo, vhi)); \ - } \ - inline void v_store(_Tp* ptr, const _Tpvec& a) \ - { _mm512_storeu_si512((__m512i*)ptr, a.val); } \ - inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ - { _mm512_store_si512((__m512i*)ptr, a.val); } \ - inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ - { _mm512_stream_si512((__m512i*)ptr, a.val); } \ - inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ - { \ - if( mode == hal::STORE_UNALIGNED ) \ - _mm512_storeu_si512((__m512i*)ptr, a.val); \ - else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ - _mm512_stream_si512((__m512i*)ptr, a.val); \ - else \ - _mm512_store_si512((__m512i*)ptr, a.val); \ - } \ - inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ - { _mm256_storeu_si256((__m256i*)ptr, _v512_extract_low(a.val)); } \ - inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ - { _mm256_storeu_si256((__m256i*)ptr, _v512_extract_high(a.val)); } - -OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_uint8x64, uchar) -OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_int8x64, schar) -OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_uint16x32, ushort) -OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_int16x32, short) -OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_uint32x16, unsigned) -OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_int32x16, int) -OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_uint64x8, uint64) -OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_int64x8, int64) - -#define OPENCV_HAL_IMPL_AVX512_LOADSTORE_FLT(_Tpvec, _Tp, suffix, halfreg) \ - inline _Tpvec v512_load(const _Tp* ptr) \ - { return _Tpvec(_mm512_loadu_##suffix(ptr)); } \ - inline _Tpvec v512_load_aligned(const _Tp* ptr) \ - { return _Tpvec(_mm512_load_##suffix(ptr)); } \ - inline _Tpvec v512_load_low(const _Tp* ptr) \ - { \ - return _Tpvec(_mm512_cast##suffix##256_##suffix##512 \ - (_mm256_loadu_##suffix(ptr))); \ - } \ - inline _Tpvec v512_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ - { \ - halfreg vlo = _mm256_loadu_##suffix(ptr0); \ - halfreg vhi = _mm256_loadu_##suffix(ptr1); \ - return _Tpvec(_v512_combine(vlo, vhi)); \ - } \ - inline void v_store(_Tp* ptr, const _Tpvec& a) \ - { _mm512_storeu_##suffix(ptr, a.val); } \ - inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ - { _mm512_store_##suffix(ptr, a.val); } \ - inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ - { _mm512_stream_##suffix(ptr, a.val); } \ - inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ - { \ - if( mode == hal::STORE_UNALIGNED ) \ - _mm512_storeu_##suffix(ptr, a.val); \ - else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ - _mm512_stream_##suffix(ptr, a.val); \ - else \ - _mm512_store_##suffix(ptr, a.val); \ - } \ - inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ - { _mm256_storeu_##suffix(ptr, _v512_extract_low(a.val)); } \ - inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ - { _mm256_storeu_##suffix(ptr, _v512_extract_high(a.val)); } - -OPENCV_HAL_IMPL_AVX512_LOADSTORE_FLT(v_float32x16, float, ps, __m256) -OPENCV_HAL_IMPL_AVX512_LOADSTORE_FLT(v_float64x8, double, pd, __m256d) - -#define OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, _Tpvecf, suffix, cast) \ - inline _Tpvec v_reinterpret_as_##suffix(const _Tpvecf& a) \ - { return _Tpvec(cast(a.val)); } - -#define OPENCV_HAL_IMPL_AVX512_INIT(_Tpvec, _Tp, suffix, ssuffix, ctype_s) \ - inline _Tpvec v512_setzero_##suffix() \ - { return _Tpvec(_mm512_setzero_si512()); } \ - inline _Tpvec v512_setall_##suffix(_Tp v) \ - { return _Tpvec(_mm512_set1_##ssuffix((ctype_s)v)); } \ - template <> inline _Tpvec v_setzero_() \ - { return v512_setzero_##suffix(); } \ - template <> inline _Tpvec v_setall_(_Tp v) \ - { return v512_setall_##suffix(v); } \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint8x64, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int8x64, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint16x32, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int16x32, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint32x16, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int32x16, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint64x8, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int64x8, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_float32x16, suffix, _mm512_castps_si512) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_float64x8, suffix, _mm512_castpd_si512) - -OPENCV_HAL_IMPL_AVX512_INIT(v_uint8x64, uchar, u8, epi8, char) -OPENCV_HAL_IMPL_AVX512_INIT(v_int8x64, schar, s8, epi8, char) -OPENCV_HAL_IMPL_AVX512_INIT(v_uint16x32, ushort, u16, epi16, short) -OPENCV_HAL_IMPL_AVX512_INIT(v_int16x32, short, s16, epi16, short) -OPENCV_HAL_IMPL_AVX512_INIT(v_uint32x16, unsigned, u32, epi32, int) -OPENCV_HAL_IMPL_AVX512_INIT(v_int32x16, int, s32, epi32, int) -OPENCV_HAL_IMPL_AVX512_INIT(v_uint64x8, uint64, u64, epi64, int64) -OPENCV_HAL_IMPL_AVX512_INIT(v_int64x8, int64, s64, epi64, int64) - -#define OPENCV_HAL_IMPL_AVX512_INIT_FLT(_Tpvec, _Tp, suffix, zsuffix, cast) \ - inline _Tpvec v512_setzero_##suffix() \ - { return _Tpvec(_mm512_setzero_##zsuffix()); } \ - inline _Tpvec v512_setall_##suffix(_Tp v) \ - { return _Tpvec(_mm512_set1_##zsuffix(v)); } \ - template <> inline _Tpvec v_setzero_() \ - { return v512_setzero_##suffix(); } \ - template <> inline _Tpvec v_setall_(_Tp v) \ - { return v512_setall_##suffix(v); } \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint8x64, suffix, cast) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int8x64, suffix, cast) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint16x32, suffix, cast) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int16x32, suffix, cast) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint32x16, suffix, cast) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int32x16, suffix, cast) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint64x8, suffix, cast) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int64x8, suffix, cast) - -OPENCV_HAL_IMPL_AVX512_INIT_FLT(v_float32x16, float, f32, ps, _mm512_castsi512_ps) -OPENCV_HAL_IMPL_AVX512_INIT_FLT(v_float64x8, double, f64, pd, _mm512_castsi512_pd) - -inline v_float32x16 v_reinterpret_as_f32(const v_float32x16& a) -{ return a; } -inline v_float32x16 v_reinterpret_as_f32(const v_float64x8& a) -{ return v_float32x16(_mm512_castpd_ps(a.val)); } - -inline v_float64x8 v_reinterpret_as_f64(const v_float64x8& a) -{ return a; } -inline v_float64x8 v_reinterpret_as_f64(const v_float32x16& a) -{ return v_float64x8(_mm512_castps_pd(a.val)); } - -// FP16 -inline v_float32x16 v512_load_expand(const hfloat* ptr) -{ - return v_float32x16(_mm512_cvtph_ps(_mm256_loadu_si256((const __m256i*)ptr))); -} - -inline void v_pack_store(hfloat* ptr, const v_float32x16& a) -{ - __m256i ah = _mm512_cvtps_ph(a.val, 0); - _mm256_storeu_si256((__m256i*)ptr, ah); -} - -/* Recombine & ZIP */ -inline void v_zip(const v_int8x64& a, const v_int8x64& b, v_int8x64& ab0, v_int8x64& ab1) -{ -#if CV_AVX_512VBMI - __m512i mask0 = _v512_set_epu8( 95, 31, 94, 30, 93, 29, 92, 28, 91, 27, 90, 26, 89, 25, 88, 24, - 87, 23, 86, 22, 85, 21, 84, 20, 83, 19, 82, 18, 81, 17, 80, 16, - 79, 15, 78, 14, 77, 13, 76, 12, 75, 11, 74, 10, 73, 9, 72, 8, - 71, 7, 70, 6, 69, 5, 68, 4, 67, 3, 66, 2, 65, 1, 64, 0); - ab0 = v_int8x64(_mm512_permutex2var_epi8(a.val, mask0, b.val)); - __m512i mask1 = _v512_set_epu8(127, 63, 126, 62, 125, 61, 124, 60, 123, 59, 122, 58, 121, 57, 120, 56, - 119, 55, 118, 54, 117, 53, 116, 52, 115, 51, 114, 50, 113, 49, 112, 48, - 111, 47, 110, 46, 109, 45, 108, 44, 107, 43, 106, 42, 105, 41, 104, 40, - 103, 39, 102, 38, 101, 37, 100, 36, 99, 35, 98, 34, 97, 33, 96, 32); - ab1 = v_int8x64(_mm512_permutex2var_epi8(a.val, mask1, b.val)); -#else - __m512i low = _mm512_unpacklo_epi8(a.val, b.val); - __m512i high = _mm512_unpackhi_epi8(a.val, b.val); - ab0 = v_int8x64(_mm512_permutex2var_epi64(low, _v512_set_epu64(11, 10, 3, 2, 9, 8, 1, 0), high)); - ab1 = v_int8x64(_mm512_permutex2var_epi64(low, _v512_set_epu64(15, 14, 7, 6, 13, 12, 5, 4), high)); -#endif -} -inline void v_zip(const v_int16x32& a, const v_int16x32& b, v_int16x32& ab0, v_int16x32& ab1) -{ - __m512i mask0 = _v512_set_epu16(47, 15, 46, 14, 45, 13, 44, 12, 43, 11, 42, 10, 41, 9, 40, 8, - 39, 7, 38, 6, 37, 5, 36, 4, 35, 3, 34, 2, 33, 1, 32, 0); - ab0 = v_int16x32(_mm512_permutex2var_epi16(a.val, mask0, b.val)); - __m512i mask1 = _v512_set_epu16(63, 31, 62, 30, 61, 29, 60, 28, 59, 27, 58, 26, 57, 25, 56, 24, - 55, 23, 54, 22, 53, 21, 52, 20, 51, 19, 50, 18, 49, 17, 48, 16); - ab1 = v_int16x32(_mm512_permutex2var_epi16(a.val, mask1, b.val)); -} -inline void v_zip(const v_int32x16& a, const v_int32x16& b, v_int32x16& ab0, v_int32x16& ab1) -{ - __m512i mask0 = _v512_set_epu32(23, 7, 22, 6, 21, 5, 20, 4, 19, 3, 18, 2, 17, 1, 16, 0); - ab0 = v_int32x16(_mm512_permutex2var_epi32(a.val, mask0, b.val)); - __m512i mask1 = _v512_set_epu32(31, 15, 30, 14, 29, 13, 28, 12, 27, 11, 26, 10, 25, 9, 24, 8); - ab1 = v_int32x16(_mm512_permutex2var_epi32(a.val, mask1, b.val)); -} -inline void v_zip(const v_int64x8& a, const v_int64x8& b, v_int64x8& ab0, v_int64x8& ab1) -{ - __m512i mask0 = _v512_set_epu64(11, 3, 10, 2, 9, 1, 8, 0); - ab0 = v_int64x8(_mm512_permutex2var_epi64(a.val, mask0, b.val)); - __m512i mask1 = _v512_set_epu64(15, 7, 14, 6, 13, 5, 12, 4); - ab1 = v_int64x8(_mm512_permutex2var_epi64(a.val, mask1, b.val)); -} - -inline void v_zip(const v_uint8x64& a, const v_uint8x64& b, v_uint8x64& ab0, v_uint8x64& ab1) -{ - v_int8x64 i0, i1; - v_zip(v_reinterpret_as_s8(a), v_reinterpret_as_s8(b), i0, i1); - ab0 = v_reinterpret_as_u8(i0); - ab1 = v_reinterpret_as_u8(i1); -} -inline void v_zip(const v_uint16x32& a, const v_uint16x32& b, v_uint16x32& ab0, v_uint16x32& ab1) -{ - v_int16x32 i0, i1; - v_zip(v_reinterpret_as_s16(a), v_reinterpret_as_s16(b), i0, i1); - ab0 = v_reinterpret_as_u16(i0); - ab1 = v_reinterpret_as_u16(i1); -} -inline void v_zip(const v_uint32x16& a, const v_uint32x16& b, v_uint32x16& ab0, v_uint32x16& ab1) -{ - v_int32x16 i0, i1; - v_zip(v_reinterpret_as_s32(a), v_reinterpret_as_s32(b), i0, i1); - ab0 = v_reinterpret_as_u32(i0); - ab1 = v_reinterpret_as_u32(i1); -} -inline void v_zip(const v_uint64x8& a, const v_uint64x8& b, v_uint64x8& ab0, v_uint64x8& ab1) -{ - v_int64x8 i0, i1; - v_zip(v_reinterpret_as_s64(a), v_reinterpret_as_s64(b), i0, i1); - ab0 = v_reinterpret_as_u64(i0); - ab1 = v_reinterpret_as_u64(i1); -} -inline void v_zip(const v_float32x16& a, const v_float32x16& b, v_float32x16& ab0, v_float32x16& ab1) -{ - v_int32x16 i0, i1; - v_zip(v_reinterpret_as_s32(a), v_reinterpret_as_s32(b), i0, i1); - ab0 = v_reinterpret_as_f32(i0); - ab1 = v_reinterpret_as_f32(i1); -} -inline void v_zip(const v_float64x8& a, const v_float64x8& b, v_float64x8& ab0, v_float64x8& ab1) -{ - v_int64x8 i0, i1; - v_zip(v_reinterpret_as_s64(a), v_reinterpret_as_s64(b), i0, i1); - ab0 = v_reinterpret_as_f64(i0); - ab1 = v_reinterpret_as_f64(i1); -} - -#define OPENCV_HAL_IMPL_AVX512_COMBINE(_Tpvec, suffix) \ - inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(_v512_combine(_v512_extract_low(a.val), _v512_extract_low(b.val))); } \ - inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(_v512_insert(b.val, _v512_extract_high(a.val))); } \ - inline void v_recombine(const _Tpvec& a, const _Tpvec& b, \ - _Tpvec& c, _Tpvec& d) \ - { \ - c.val = _v512_combine(_v512_extract_low(a.val),_v512_extract_low(b.val)); \ - d.val = _v512_insert(b.val,_v512_extract_high(a.val)); \ - } - - -OPENCV_HAL_IMPL_AVX512_COMBINE(v_uint8x64, epi8) -OPENCV_HAL_IMPL_AVX512_COMBINE(v_int8x64, epi8) -OPENCV_HAL_IMPL_AVX512_COMBINE(v_uint16x32, epi16) -OPENCV_HAL_IMPL_AVX512_COMBINE(v_int16x32, epi16) -OPENCV_HAL_IMPL_AVX512_COMBINE(v_uint32x16, epi32) -OPENCV_HAL_IMPL_AVX512_COMBINE(v_int32x16, epi32) -OPENCV_HAL_IMPL_AVX512_COMBINE(v_uint64x8, epi64) -OPENCV_HAL_IMPL_AVX512_COMBINE(v_int64x8, epi64) -OPENCV_HAL_IMPL_AVX512_COMBINE(v_float32x16, ps) -OPENCV_HAL_IMPL_AVX512_COMBINE(v_float64x8, pd) - -////////// Arithmetic, bitwise and comparison operations ///////// - -/* Element-wise binary and unary operations */ - -/** Non-saturating arithmetics **/ -#define OPENCV_HAL_IMPL_AVX512_BIN_FUNC(func, _Tpvec, intrin) \ - inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(intrin(a.val, b.val)); } - -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_add_wrap, v_uint8x64, _mm512_add_epi8) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_add_wrap, v_int8x64, _mm512_add_epi8) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_add_wrap, v_uint16x32, _mm512_add_epi16) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_add_wrap, v_int16x32, _mm512_add_epi16) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_sub_wrap, v_uint8x64, _mm512_sub_epi8) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_sub_wrap, v_int8x64, _mm512_sub_epi8) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_sub_wrap, v_uint16x32, _mm512_sub_epi16) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_sub_wrap, v_int16x32, _mm512_sub_epi16) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_mul_wrap, v_uint16x32, _mm512_mullo_epi16) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_mul_wrap, v_int16x32, _mm512_mullo_epi16) - -inline v_uint8x64 v_mul_wrap(const v_uint8x64& a, const v_uint8x64& b) -{ - __m512i ad = _mm512_srai_epi16(a.val, 8); - __m512i bd = _mm512_srai_epi16(b.val, 8); - __m512i p0 = _mm512_mullo_epi16(a.val, b.val); // even - __m512i p1 = _mm512_slli_epi16(_mm512_mullo_epi16(ad, bd), 8); // odd - return v_uint8x64(_mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, p0, p1)); -} -inline v_int8x64 v_mul_wrap(const v_int8x64& a, const v_int8x64& b) -{ - return v_reinterpret_as_s8(v_mul_wrap(v_reinterpret_as_u8(a), v_reinterpret_as_u8(b))); -} - -#define OPENCV_HAL_IMPL_AVX512_BIN_OP(bin_op, _Tpvec, intrin) \ - inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(intrin(a.val, b.val)); } - -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_uint32x16, _mm512_add_epi32) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_uint32x16, _mm512_sub_epi32) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_int32x16, _mm512_add_epi32) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_int32x16, _mm512_sub_epi32) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_uint64x8, _mm512_add_epi64) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_uint64x8, _mm512_sub_epi64) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_int64x8, _mm512_add_epi64) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_int64x8, _mm512_sub_epi64) - -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_mul, v_uint32x16, _mm512_mullo_epi32) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_mul, v_int32x16, _mm512_mullo_epi32) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_mul, v_uint64x8, _mm512_mullo_epi64) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_mul, v_int64x8, _mm512_mullo_epi64) - -/** Saturating arithmetics **/ -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_uint8x64, _mm512_adds_epu8) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_uint8x64, _mm512_subs_epu8) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_int8x64, _mm512_adds_epi8) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_int8x64, _mm512_subs_epi8) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_uint16x32, _mm512_adds_epu16) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_uint16x32, _mm512_subs_epu16) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_int16x32, _mm512_adds_epi16) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_int16x32, _mm512_subs_epi16) - -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_float32x16, _mm512_add_ps) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_float32x16, _mm512_sub_ps) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_mul, v_float32x16, _mm512_mul_ps) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_div, v_float32x16, _mm512_div_ps) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_float64x8, _mm512_add_pd) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_float64x8, _mm512_sub_pd) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_mul, v_float64x8, _mm512_mul_pd) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_div, v_float64x8, _mm512_div_pd) - -// saturating multiply -inline v_uint8x64 v_mul(const v_uint8x64& a, const v_uint8x64& b) -{ - v_uint16x32 c, d; - v_mul_expand(a, b, c, d); - return v_pack(c, d); -} -inline v_int8x64 v_mul(const v_int8x64& a, const v_int8x64& b) -{ - v_int16x32 c, d; - v_mul_expand(a, b, c, d); - return v_pack(c, d); -} -inline v_uint16x32 v_mul(const v_uint16x32& a, const v_uint16x32& b) -{ - __m512i pl = _mm512_mullo_epi16(a.val, b.val); - __m512i ph = _mm512_mulhi_epu16(a.val, b.val); - __m512i p0 = _mm512_unpacklo_epi16(pl, ph); - __m512i p1 = _mm512_unpackhi_epi16(pl, ph); - - const __m512i m = _mm512_set1_epi32(65535); - return v_uint16x32(_mm512_packus_epi32(_mm512_min_epu32(p0, m), _mm512_min_epu32(p1, m))); -} -inline v_int16x32 v_mul(const v_int16x32& a, const v_int16x32& b) -{ - __m512i pl = _mm512_mullo_epi16(a.val, b.val); - __m512i ph = _mm512_mulhi_epi16(a.val, b.val); - __m512i p0 = _mm512_unpacklo_epi16(pl, ph); - __m512i p1 = _mm512_unpackhi_epi16(pl, ph); - return v_int16x32(_mm512_packs_epi32(p0, p1)); -} - -inline v_int16x32 v_mul_hi(const v_int16x32& a, const v_int16x32& b) { return v_int16x32(_mm512_mulhi_epi16(a.val, b.val)); } -inline v_uint16x32 v_mul_hi(const v_uint16x32& a, const v_uint16x32& b) { return v_uint16x32(_mm512_mulhi_epu16(a.val, b.val)); } - -// Multiply and expand -inline void v_mul_expand(const v_uint8x64& a, const v_uint8x64& b, - v_uint16x32& c, v_uint16x32& d) -{ - v_uint16x32 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c = v_mul_wrap(a0, b0); - d = v_mul_wrap(a1, b1); -} - -inline void v_mul_expand(const v_int8x64& a, const v_int8x64& b, - v_int16x32& c, v_int16x32& d) -{ - v_int16x32 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c = v_mul_wrap(a0, b0); - d = v_mul_wrap(a1, b1); -} - -inline void v_mul_expand(const v_int16x32& a, const v_int16x32& b, - v_int32x16& c, v_int32x16& d) -{ - v_int16x32 v0, v1; - v_zip(v_mul_wrap(a, b), v_mul_hi(a, b), v0, v1); - - c = v_reinterpret_as_s32(v0); - d = v_reinterpret_as_s32(v1); -} - -inline void v_mul_expand(const v_uint16x32& a, const v_uint16x32& b, - v_uint32x16& c, v_uint32x16& d) -{ - v_uint16x32 v0, v1; - v_zip(v_mul_wrap(a, b), v_mul_hi(a, b), v0, v1); - - c = v_reinterpret_as_u32(v0); - d = v_reinterpret_as_u32(v1); -} - -inline void v_mul_expand(const v_uint32x16& a, const v_uint32x16& b, - v_uint64x8& c, v_uint64x8& d) -{ - v_zip(v_uint64x8(_mm512_mul_epu32(a.val, b.val)), - v_uint64x8(_mm512_mul_epu32(_mm512_srli_epi64(a.val, 32), _mm512_srli_epi64(b.val, 32))), c, d); -} - -inline void v_mul_expand(const v_int32x16& a, const v_int32x16& b, - v_int64x8& c, v_int64x8& d) -{ - v_zip(v_int64x8(_mm512_mul_epi32(a.val, b.val)), - v_int64x8(_mm512_mul_epi32(_mm512_srli_epi64(a.val, 32), _mm512_srli_epi64(b.val, 32))), c, d); -} - -/** Bitwise shifts **/ -#define OPENCV_HAL_IMPL_AVX512_SHIFT_OP(_Tpuvec, _Tpsvec, suffix) \ - inline _Tpuvec v_shl(const _Tpuvec& a, int imm) \ - { return _Tpuvec(_mm512_slli_##suffix(a.val, imm)); } \ - inline _Tpsvec v_shl(const _Tpsvec& a, int imm) \ - { return _Tpsvec(_mm512_slli_##suffix(a.val, imm)); } \ - inline _Tpuvec v_shr(const _Tpuvec& a, int imm) \ - { return _Tpuvec(_mm512_srli_##suffix(a.val, imm)); } \ - inline _Tpsvec v_shr(const _Tpsvec& a, int imm) \ - { return _Tpsvec(_mm512_srai_##suffix(a.val, imm)); } \ - template \ - inline _Tpuvec v_shl(const _Tpuvec& a) \ - { return _Tpuvec(_mm512_slli_##suffix(a.val, imm)); } \ - template \ - inline _Tpsvec v_shl(const _Tpsvec& a) \ - { return _Tpsvec(_mm512_slli_##suffix(a.val, imm)); } \ - template \ - inline _Tpuvec v_shr(const _Tpuvec& a) \ - { return _Tpuvec(_mm512_srli_##suffix(a.val, imm)); } \ - template \ - inline _Tpsvec v_shr(const _Tpsvec& a) \ - { return _Tpsvec(_mm512_srai_##suffix(a.val, imm)); } - -OPENCV_HAL_IMPL_AVX512_SHIFT_OP(v_uint16x32, v_int16x32, epi16) -OPENCV_HAL_IMPL_AVX512_SHIFT_OP(v_uint32x16, v_int32x16, epi32) -OPENCV_HAL_IMPL_AVX512_SHIFT_OP(v_uint64x8, v_int64x8, epi64) - - -/** Bitwise logic **/ -#define OPENCV_HAL_IMPL_AVX512_LOGIC_OP(_Tpvec, suffix, not_const) \ - OPENCV_HAL_IMPL_AVX512_BIN_OP(v_and, _Tpvec, _mm512_and_##suffix) \ - OPENCV_HAL_IMPL_AVX512_BIN_OP(v_or, _Tpvec, _mm512_or_##suffix) \ - OPENCV_HAL_IMPL_AVX512_BIN_OP(v_xor, _Tpvec, _mm512_xor_##suffix) \ - inline _Tpvec v_not(const _Tpvec& a) \ - { return _Tpvec(_mm512_xor_##suffix(a.val, not_const)); } - -OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_uint8x64, si512, _mm512_set1_epi32(-1)) -OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_int8x64, si512, _mm512_set1_epi32(-1)) -OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_uint16x32, si512, _mm512_set1_epi32(-1)) -OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_int16x32, si512, _mm512_set1_epi32(-1)) -OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_uint32x16, si512, _mm512_set1_epi32(-1)) -OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_int32x16, si512, _mm512_set1_epi32(-1)) -OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_uint64x8, si512, _mm512_set1_epi64(-1)) -OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_int64x8, si512, _mm512_set1_epi64(-1)) -OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_float32x16, ps, _mm512_castsi512_ps(_mm512_set1_epi32(-1))) -OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_float64x8, pd, _mm512_castsi512_pd(_mm512_set1_epi32(-1))) - -/** Select **/ -#define OPENCV_HAL_IMPL_AVX512_SELECT(_Tpvec, suffix, zsuf) \ - inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(_mm512_mask_blend_##suffix(_mm512_cmp_##suffix##_mask(mask.val, _mm512_setzero_##zsuf(), _MM_CMPINT_EQ), a.val, b.val)); } - -OPENCV_HAL_IMPL_AVX512_SELECT(v_uint8x64, epi8, si512) -OPENCV_HAL_IMPL_AVX512_SELECT(v_int8x64, epi8, si512) -OPENCV_HAL_IMPL_AVX512_SELECT(v_uint16x32, epi16, si512) -OPENCV_HAL_IMPL_AVX512_SELECT(v_int16x32, epi16, si512) -OPENCV_HAL_IMPL_AVX512_SELECT(v_uint32x16, epi32, si512) -OPENCV_HAL_IMPL_AVX512_SELECT(v_int32x16, epi32, si512) -OPENCV_HAL_IMPL_AVX512_SELECT(v_uint64x8, epi64, si512) -OPENCV_HAL_IMPL_AVX512_SELECT(v_int64x8, epi64, si512) -OPENCV_HAL_IMPL_AVX512_SELECT(v_float32x16, ps, ps) -OPENCV_HAL_IMPL_AVX512_SELECT(v_float64x8, pd, pd) - -/** Comparison **/ -#define OPENCV_HAL_IMPL_AVX512_CMP_INT(bin_op, imm8, _Tpvec, sufcmp, sufset, tval) \ - inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(_mm512_maskz_set1_##sufset(_mm512_cmp_##sufcmp##_mask(a.val, b.val, imm8), tval)); } - -#define OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(_Tpvec, sufcmp, sufset, tval) \ - OPENCV_HAL_IMPL_AVX512_CMP_INT(v_eq, _MM_CMPINT_EQ, _Tpvec, sufcmp, sufset, tval) \ - OPENCV_HAL_IMPL_AVX512_CMP_INT(v_ne, _MM_CMPINT_NE, _Tpvec, sufcmp, sufset, tval) \ - OPENCV_HAL_IMPL_AVX512_CMP_INT(v_lt, _MM_CMPINT_LT, _Tpvec, sufcmp, sufset, tval) \ - OPENCV_HAL_IMPL_AVX512_CMP_INT(v_gt, _MM_CMPINT_NLE, _Tpvec, sufcmp, sufset, tval) \ - OPENCV_HAL_IMPL_AVX512_CMP_INT(v_le, _MM_CMPINT_LE, _Tpvec, sufcmp, sufset, tval) \ - OPENCV_HAL_IMPL_AVX512_CMP_INT(v_ge, _MM_CMPINT_NLT, _Tpvec, sufcmp, sufset, tval) - -OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_uint8x64, epu8, epi8, (char)-1) -OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_int8x64, epi8, epi8, (char)-1) -OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_uint16x32, epu16, epi16, (short)-1) -OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_int16x32, epi16, epi16, (short)-1) -OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_uint32x16, epu32, epi32, (int)-1) -OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_int32x16, epi32, epi32, (int)-1) -OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_uint64x8, epu64, epi64, (int64)-1) -OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_int64x8, epi64, epi64, (int64)-1) - -#define OPENCV_HAL_IMPL_AVX512_CMP_FLT(bin_op, imm8, _Tpvec, sufcmp, sufset, tval) \ - inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(_mm512_castsi512_##sufcmp(_mm512_maskz_set1_##sufset(_mm512_cmp_##sufcmp##_mask(a.val, b.val, imm8), tval))); } - -#define OPENCV_HAL_IMPL_AVX512_CMP_OP_FLT(_Tpvec, sufcmp, sufset, tval) \ - OPENCV_HAL_IMPL_AVX512_CMP_FLT(v_eq, _CMP_EQ_OQ, _Tpvec, sufcmp, sufset, tval) \ - OPENCV_HAL_IMPL_AVX512_CMP_FLT(v_ne, _CMP_NEQ_OQ, _Tpvec, sufcmp, sufset, tval) \ - OPENCV_HAL_IMPL_AVX512_CMP_FLT(v_lt, _CMP_LT_OQ, _Tpvec, sufcmp, sufset, tval) \ - OPENCV_HAL_IMPL_AVX512_CMP_FLT(v_gt, _CMP_GT_OQ, _Tpvec, sufcmp, sufset, tval) \ - OPENCV_HAL_IMPL_AVX512_CMP_FLT(v_le, _CMP_LE_OQ, _Tpvec, sufcmp, sufset, tval) \ - OPENCV_HAL_IMPL_AVX512_CMP_FLT(v_ge, _CMP_GE_OQ, _Tpvec, sufcmp, sufset, tval) - -OPENCV_HAL_IMPL_AVX512_CMP_OP_FLT(v_float32x16, ps, epi32, (int)-1) -OPENCV_HAL_IMPL_AVX512_CMP_OP_FLT(v_float64x8, pd, epi64, (int64)-1) - -inline v_float32x16 v_not_nan(const v_float32x16& a) -{ return v_float32x16(_mm512_castsi512_ps(_mm512_maskz_set1_epi32(_mm512_cmp_ps_mask(a.val, a.val, _CMP_ORD_Q), (int)-1))); } -inline v_float64x8 v_not_nan(const v_float64x8& a) -{ return v_float64x8(_mm512_castsi512_pd(_mm512_maskz_set1_epi64(_mm512_cmp_pd_mask(a.val, a.val, _CMP_ORD_Q), (int64)-1))); } - -/** min/max **/ -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_uint8x64, _mm512_min_epu8) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_uint8x64, _mm512_max_epu8) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_int8x64, _mm512_min_epi8) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_int8x64, _mm512_max_epi8) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_uint16x32, _mm512_min_epu16) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_uint16x32, _mm512_max_epu16) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_int16x32, _mm512_min_epi16) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_int16x32, _mm512_max_epi16) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_uint32x16, _mm512_min_epu32) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_uint32x16, _mm512_max_epu32) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_int32x16, _mm512_min_epi32) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_int32x16, _mm512_max_epi32) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_uint64x8, _mm512_min_epu64) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_uint64x8, _mm512_max_epu64) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_int64x8, _mm512_min_epi64) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_int64x8, _mm512_max_epi64) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_float32x16, _mm512_min_ps) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_float32x16, _mm512_max_ps) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_float64x8, _mm512_min_pd) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_float64x8, _mm512_max_pd) - -/** Rotate **/ -namespace { - template - struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64&, const v_int8x64&) { return v_int8x64(); }}; - template - struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64& a, const v_int8x64& b) - { - return v_int8x64(_mm512_or_si512(_mm512_srli_epi32(_mm512_alignr_epi32(b.val, a.val, imm32 ), imm4 *8), - _mm512_slli_epi32(_mm512_alignr_epi32(b.val, a.val, imm32 + 1), (4-imm4)*8))); - }}; - template - struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64& a, const v_int8x64& b) - { - return v_int8x64(_mm512_or_si512(_mm512_srli_epi32(_mm512_alignr_epi32(b.val, a.val, 15), imm4 *8), - _mm512_slli_epi32( b.val, (4-imm4)*8))); - }}; - template - struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64&, const v_int8x64& b) - { - return v_int8x64(_mm512_or_si512(_mm512_srli_epi32(_mm512_alignr_epi32(_mm512_setzero_si512(), b.val, imm32 - 16), imm4 *8), - _mm512_slli_epi32(_mm512_alignr_epi32(_mm512_setzero_si512(), b.val, imm32 - 15), (4-imm4)*8))); - }}; - template - struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64&, const v_int8x64& b) - { return v_int8x64(_mm512_srli_epi32(_mm512_alignr_epi32(_mm512_setzero_si512(), b.val, 15), imm4*8)); }}; - template - struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64& a, const v_int8x64& b) - { return v_int8x64(_mm512_alignr_epi32(b.val, a.val, imm32)); }}; - template<> - struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64& a, const v_int8x64&) { return a; }}; - template - struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64&, const v_int8x64& b) - { return v_int8x64(_mm512_alignr_epi32(_mm512_setzero_si512(), b.val, imm32 - 16)); }}; - template<> - struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64&, const v_int8x64& b) { return b; }}; - template<> - struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64&, const v_int8x64&) { return v_int8x64(); }}; -} -template inline v_int8x64 v_rotate_right(const v_int8x64& a, const v_int8x64& b) -{ - return imm >= 128 ? v_int8x64() : -#if CV_AVX_512VBMI - v_int8x64(_mm512_permutex2var_epi8(a.val, - _v512_set_epu8(0x3f + imm, 0x3e + imm, 0x3d + imm, 0x3c + imm, 0x3b + imm, 0x3a + imm, 0x39 + imm, 0x38 + imm, - 0x37 + imm, 0x36 + imm, 0x35 + imm, 0x34 + imm, 0x33 + imm, 0x32 + imm, 0x31 + imm, 0x30 + imm, - 0x2f + imm, 0x2e + imm, 0x2d + imm, 0x2c + imm, 0x2b + imm, 0x2a + imm, 0x29 + imm, 0x28 + imm, - 0x27 + imm, 0x26 + imm, 0x25 + imm, 0x24 + imm, 0x23 + imm, 0x22 + imm, 0x21 + imm, 0x20 + imm, - 0x1f + imm, 0x1e + imm, 0x1d + imm, 0x1c + imm, 0x1b + imm, 0x1a + imm, 0x19 + imm, 0x18 + imm, - 0x17 + imm, 0x16 + imm, 0x15 + imm, 0x14 + imm, 0x13 + imm, 0x12 + imm, 0x11 + imm, 0x10 + imm, - 0x0f + imm, 0x0e + imm, 0x0d + imm, 0x0c + imm, 0x0b + imm, 0x0a + imm, 0x09 + imm, 0x08 + imm, - 0x07 + imm, 0x06 + imm, 0x05 + imm, 0x04 + imm, 0x03 + imm, 0x02 + imm, 0x01 + imm, 0x00 + imm), b.val)); -#else - _v_rotate_right 15), imm/4>::eval(a, b); -#endif -} -template -inline v_int8x64 v_rotate_left(const v_int8x64& a, const v_int8x64& b) -{ - if (imm == 0) return a; - if (imm == 64) return b; - if (imm >= 128) return v_int8x64(); -#if CV_AVX_512VBMI - return v_int8x64(_mm512_permutex2var_epi8(b.val, - _v512_set_epi8(0x7f - imm,0x7e - imm,0x7d - imm,0x7c - imm,0x7b - imm,0x7a - imm,0x79 - imm,0x78 - imm, - 0x77 - imm,0x76 - imm,0x75 - imm,0x74 - imm,0x73 - imm,0x72 - imm,0x71 - imm,0x70 - imm, - 0x6f - imm,0x6e - imm,0x6d - imm,0x6c - imm,0x6b - imm,0x6a - imm,0x69 - imm,0x68 - imm, - 0x67 - imm,0x66 - imm,0x65 - imm,0x64 - imm,0x63 - imm,0x62 - imm,0x61 - imm,0x60 - imm, - 0x5f - imm,0x5e - imm,0x5d - imm,0x5c - imm,0x5b - imm,0x5a - imm,0x59 - imm,0x58 - imm, - 0x57 - imm,0x56 - imm,0x55 - imm,0x54 - imm,0x53 - imm,0x52 - imm,0x51 - imm,0x50 - imm, - 0x4f - imm,0x4e - imm,0x4d - imm,0x4c - imm,0x4b - imm,0x4a - imm,0x49 - imm,0x48 - imm, - 0x47 - imm,0x46 - imm,0x45 - imm,0x44 - imm,0x43 - imm,0x42 - imm,0x41 - imm,0x40 - imm), a.val)); -#else - return imm < 64 ? v_rotate_right<64 - imm>(b, a) : v_rotate_right<128 - imm>(v512_setzero_s8(), b); -#endif -} -template -inline v_int8x64 v_rotate_right(const v_int8x64& a) -{ - if (imm == 0) return a; - if (imm >= 64) return v_int8x64(); -#if CV_AVX_512VBMI - return v_int8x64(_mm512_maskz_permutexvar_epi8(0xFFFFFFFFFFFFFFFF >> imm, - _v512_set_epu8(0x3f + imm,0x3e + imm,0x3d + imm,0x3c + imm,0x3b + imm,0x3a + imm,0x39 + imm,0x38 + imm, - 0x37 + imm,0x36 + imm,0x35 + imm,0x34 + imm,0x33 + imm,0x32 + imm,0x31 + imm,0x30 + imm, - 0x2f + imm,0x2e + imm,0x2d + imm,0x2c + imm,0x2b + imm,0x2a + imm,0x29 + imm,0x28 + imm, - 0x27 + imm,0x26 + imm,0x25 + imm,0x24 + imm,0x23 + imm,0x22 + imm,0x21 + imm,0x20 + imm, - 0x1f + imm,0x1e + imm,0x1d + imm,0x1c + imm,0x1b + imm,0x1a + imm,0x19 + imm,0x18 + imm, - 0x17 + imm,0x16 + imm,0x15 + imm,0x14 + imm,0x13 + imm,0x12 + imm,0x11 + imm,0x10 + imm, - 0x0f + imm,0x0e + imm,0x0d + imm,0x0c + imm,0x0b + imm,0x0a + imm,0x09 + imm,0x08 + imm, - 0x07 + imm,0x06 + imm,0x05 + imm,0x04 + imm,0x03 + imm,0x02 + imm,0x01 + imm,0x00 + imm), a.val)); -#else - return v_rotate_right(a, v512_setzero_s8()); -#endif -} -template -inline v_int8x64 v_rotate_left(const v_int8x64& a) -{ - if (imm == 0) return a; - if (imm >= 64) return v_int8x64(); -#if CV_AVX_512VBMI - return v_int8x64(_mm512_maskz_permutexvar_epi8(0xFFFFFFFFFFFFFFFF << imm, - _v512_set_epi8(0x3f - imm,0x3e - imm,0x3d - imm,0x3c - imm,0x3b - imm,0x3a - imm,0x39 - imm,0x38 - imm, - 0x37 - imm,0x36 - imm,0x35 - imm,0x34 - imm,0x33 - imm,0x32 - imm,0x31 - imm,0x30 - imm, - 0x2f - imm,0x2e - imm,0x2d - imm,0x2c - imm,0x2b - imm,0x2a - imm,0x29 - imm,0x28 - imm, - 0x27 - imm,0x26 - imm,0x25 - imm,0x24 - imm,0x23 - imm,0x22 - imm,0x21 - imm,0x20 - imm, - 0x1f - imm,0x1e - imm,0x1d - imm,0x1c - imm,0x1b - imm,0x1a - imm,0x19 - imm,0x18 - imm, - 0x17 - imm,0x16 - imm,0x15 - imm,0x14 - imm,0x13 - imm,0x12 - imm,0x11 - imm,0x10 - imm, - 0x0f - imm,0x0e - imm,0x0d - imm,0x0c - imm,0x0b - imm,0x0a - imm,0x09 - imm,0x08 - imm, - 0x07 - imm,0x06 - imm,0x05 - imm,0x04 - imm,0x03 - imm,0x02 - imm,0x01 - imm,0x00 - imm), a.val)); -#else - return v_rotate_right<64 - imm>(v512_setzero_s8(), a); -#endif -} - -#define OPENCV_HAL_IMPL_AVX512_ROTATE_PM(_Tpvec, suffix) \ -template inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ -{ return v_reinterpret_as_##suffix(v_rotate_left(v_reinterpret_as_s8(a), v_reinterpret_as_s8(b))); } \ -template inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ -{ return v_reinterpret_as_##suffix(v_rotate_right(v_reinterpret_as_s8(a), v_reinterpret_as_s8(b))); } \ -template inline _Tpvec v_rotate_left(const _Tpvec& a) \ -{ return v_reinterpret_as_##suffix(v_rotate_left(v_reinterpret_as_s8(a))); } \ -template inline _Tpvec v_rotate_right(const _Tpvec& a) \ -{ return v_reinterpret_as_##suffix(v_rotate_right(v_reinterpret_as_s8(a))); } - -#define OPENCV_HAL_IMPL_AVX512_ROTATE_EC(_Tpvec, suffix) \ -template \ -inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ -{ \ - enum { SHIFT2 = (_Tpvec::nlanes - imm) }; \ - enum { MASK = ((1 << _Tpvec::nlanes) - 1) }; \ - if (imm == 0) return a; \ - if (imm == _Tpvec::nlanes) return b; \ - if (imm >= 2*_Tpvec::nlanes) return _Tpvec::zero(); \ - return _Tpvec(_mm512_mask_expand_##suffix(_mm512_maskz_compress_##suffix((MASK << SHIFT2)&MASK, b.val), (MASK << (imm))&MASK, a.val)); \ -} \ -template \ -inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ -{ \ - enum { SHIFT2 = (_Tpvec::nlanes - imm) }; \ - enum { MASK = ((1 << _Tpvec::nlanes) - 1) }; \ - if (imm == 0) return a; \ - if (imm == _Tpvec::nlanes) return b; \ - if (imm >= 2*_Tpvec::nlanes) return _Tpvec::zero(); \ - return _Tpvec(_mm512_mask_expand_##suffix(_mm512_maskz_compress_##suffix((MASK << (imm))&MASK, a.val), (MASK << SHIFT2)&MASK, b.val)); \ -} \ -template \ -inline _Tpvec v_rotate_left(const _Tpvec& a) \ -{ \ - if (imm == 0) return a; \ - if (imm >= _Tpvec::nlanes) return _Tpvec::zero(); \ - return _Tpvec(_mm512_maskz_expand_##suffix((1 << _Tpvec::nlanes) - (1 << (imm)), a.val)); \ -} \ -template \ -inline _Tpvec v_rotate_right(const _Tpvec& a) \ -{ \ - if (imm == 0) return a; \ - if (imm >= _Tpvec::nlanes) return _Tpvec::zero(); \ - return _Tpvec(_mm512_maskz_compress_##suffix((1 << _Tpvec::nlanes) - (1 << (imm)), a.val)); \ -} - -OPENCV_HAL_IMPL_AVX512_ROTATE_PM(v_uint8x64, u8) -OPENCV_HAL_IMPL_AVX512_ROTATE_PM(v_uint16x32, u16) -OPENCV_HAL_IMPL_AVX512_ROTATE_PM(v_int16x32, s16) -OPENCV_HAL_IMPL_AVX512_ROTATE_EC(v_uint32x16, epi32) -OPENCV_HAL_IMPL_AVX512_ROTATE_EC(v_int32x16, epi32) -OPENCV_HAL_IMPL_AVX512_ROTATE_EC(v_uint64x8, epi64) -OPENCV_HAL_IMPL_AVX512_ROTATE_EC(v_int64x8, epi64) -OPENCV_HAL_IMPL_AVX512_ROTATE_EC(v_float32x16, ps) -OPENCV_HAL_IMPL_AVX512_ROTATE_EC(v_float64x8, pd) - -/** Reverse **/ -inline v_uint8x64 v_reverse(const v_uint8x64 &a) -{ -#if CV_AVX_512VBMI - static const __m512i perm = _mm512_set_epi32( - 0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f, - 0x10111213, 0x14151617, 0x18191a1b, 0x1c1d1e1f, - 0x20212223, 0x24252627, 0x28292a2b, 0x2c2d2e2f, - 0x30313233, 0x34353637, 0x38393a3b, 0x3c3d3e3f); - return v_uint8x64(_mm512_permutexvar_epi8(perm, a.val)); -#else - static const __m512i shuf = _mm512_set_epi32( - 0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f, - 0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f, - 0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f, - 0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f); - static const __m512i perm = _mm512_set_epi64(1, 0, 3, 2, 5, 4, 7, 6); - __m512i vec = _mm512_shuffle_epi8(a.val, shuf); - return v_uint8x64(_mm512_permutexvar_epi64(perm, vec)); -#endif -} - -inline v_int8x64 v_reverse(const v_int8x64 &a) -{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } - -inline v_uint16x32 v_reverse(const v_uint16x32 &a) -{ -#if CV_AVX_512VBMI - static const __m512i perm = _mm512_set_epi32( - 0x00000001, 0x00020003, 0x00040005, 0x00060007, - 0x00080009, 0x000a000b, 0x000c000d, 0x000e000f, - 0x00100011, 0x00120013, 0x00140015, 0x00160017, - 0x00180019, 0x001a001b, 0x001c001d, 0x001e001f); - return v_uint16x32(_mm512_permutexvar_epi16(perm, a.val)); -#else - static const __m512i shuf = _mm512_set_epi32( - 0x01000302, 0x05040706, 0x09080b0a, 0x0d0c0f0e, - 0x01000302, 0x05040706, 0x09080b0a, 0x0d0c0f0e, - 0x01000302, 0x05040706, 0x09080b0a, 0x0d0c0f0e, - 0x01000302, 0x05040706, 0x09080b0a, 0x0d0c0f0e); - static const __m512i perm = _mm512_set_epi64(1, 0, 3, 2, 5, 4, 7, 6); - __m512i vec = _mm512_shuffle_epi8(a.val, shuf); - return v_uint16x32(_mm512_permutexvar_epi64(perm, vec)); -#endif -} - -inline v_int16x32 v_reverse(const v_int16x32 &a) -{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } - -inline v_uint32x16 v_reverse(const v_uint32x16 &a) -{ - static const __m512i perm = _mm512_set_epi32(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,14, 15); - return v_uint32x16(_mm512_permutexvar_epi32(perm, a.val)); -} - -inline v_int32x16 v_reverse(const v_int32x16 &a) -{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_float32x16 v_reverse(const v_float32x16 &a) -{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_uint64x8 v_reverse(const v_uint64x8 &a) -{ - static const __m512i perm = _mm512_set_epi64(0, 1, 2, 3, 4, 5, 6, 7); - return v_uint64x8(_mm512_permutexvar_epi64(perm, a.val)); -} - -inline v_int64x8 v_reverse(const v_int64x8 &a) -{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } - -inline v_float64x8 v_reverse(const v_float64x8 &a) -{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } - -////////// Reduce ///////// - -/** Reduce **/ -#define OPENCV_HAL_IMPL_AVX512_REDUCE_ADD64(a, b) a + b -#define OPENCV_HAL_IMPL_AVX512_REDUCE_8(sctype, func, _Tpvec, ifunc, scop) \ - inline sctype v_reduce_##func(const _Tpvec& a) \ - { __m256i half = _mm256_##ifunc(_v512_extract_low(a.val), _v512_extract_high(a.val)); \ - sctype CV_DECL_ALIGNED(64) idx[2]; \ - _mm_store_si128((__m128i*)idx, _mm_##ifunc(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1))); \ - return scop(idx[0], idx[1]); } -OPENCV_HAL_IMPL_AVX512_REDUCE_8(uint64, min, v_uint64x8, min_epu64, min) -OPENCV_HAL_IMPL_AVX512_REDUCE_8(uint64, max, v_uint64x8, max_epu64, max) -OPENCV_HAL_IMPL_AVX512_REDUCE_8(uint64, sum, v_uint64x8, add_epi64, OPENCV_HAL_IMPL_AVX512_REDUCE_ADD64) -OPENCV_HAL_IMPL_AVX512_REDUCE_8(int64, min, v_int64x8, min_epi64, min) -OPENCV_HAL_IMPL_AVX512_REDUCE_8(int64, max, v_int64x8, max_epi64, max) -OPENCV_HAL_IMPL_AVX512_REDUCE_8(int64, sum, v_int64x8, add_epi64, OPENCV_HAL_IMPL_AVX512_REDUCE_ADD64) - -#define OPENCV_HAL_IMPL_AVX512_REDUCE_8F(func, ifunc, scop) \ - inline double v_reduce_##func(const v_float64x8& a) \ - { __m256d half = _mm256_##ifunc(_v512_extract_low(a.val), _v512_extract_high(a.val)); \ - double CV_DECL_ALIGNED(64) idx[2]; \ - _mm_store_pd(idx, _mm_##ifunc(_mm256_castpd256_pd128(half), _mm256_extractf128_pd(half, 1))); \ - return scop(idx[0], idx[1]); } -OPENCV_HAL_IMPL_AVX512_REDUCE_8F(min, min_pd, min) -OPENCV_HAL_IMPL_AVX512_REDUCE_8F(max, max_pd, max) -OPENCV_HAL_IMPL_AVX512_REDUCE_8F(sum, add_pd, OPENCV_HAL_IMPL_AVX512_REDUCE_ADD64) - -#define OPENCV_HAL_IMPL_AVX512_REDUCE_16(sctype, func, _Tpvec, ifunc) \ - inline sctype v_reduce_##func(const _Tpvec& a) \ - { __m256i half = _mm256_##ifunc(_v512_extract_low(a.val), _v512_extract_high(a.val)); \ - __m128i quarter = _mm_##ifunc(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1)); \ - quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 8)); \ - quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 4)); \ - return (sctype)_mm_cvtsi128_si32(quarter); } -OPENCV_HAL_IMPL_AVX512_REDUCE_16(uint, min, v_uint32x16, min_epu32) -OPENCV_HAL_IMPL_AVX512_REDUCE_16(uint, max, v_uint32x16, max_epu32) -OPENCV_HAL_IMPL_AVX512_REDUCE_16(int, min, v_int32x16, min_epi32) -OPENCV_HAL_IMPL_AVX512_REDUCE_16(int, max, v_int32x16, max_epi32) - -#define OPENCV_HAL_IMPL_AVX512_REDUCE_16F(func, ifunc) \ - inline float v_reduce_##func(const v_float32x16& a) \ - { __m256 half = _mm256_##ifunc(_v512_extract_low(a.val), _v512_extract_high(a.val)); \ - __m128 quarter = _mm_##ifunc(_mm256_castps256_ps128(half), _mm256_extractf128_ps(half, 1)); \ - quarter = _mm_##ifunc(quarter, _mm_permute_ps(quarter, _MM_SHUFFLE(0, 0, 3, 2))); \ - quarter = _mm_##ifunc(quarter, _mm_permute_ps(quarter, _MM_SHUFFLE(0, 0, 0, 1))); \ - return _mm_cvtss_f32(quarter); } -OPENCV_HAL_IMPL_AVX512_REDUCE_16F(min, min_ps) -OPENCV_HAL_IMPL_AVX512_REDUCE_16F(max, max_ps) - -inline float v_reduce_sum(const v_float32x16& a) -{ - __m256 half = _mm256_add_ps(_v512_extract_low(a.val), _v512_extract_high(a.val)); - __m128 quarter = _mm_add_ps(_mm256_castps256_ps128(half), _mm256_extractf128_ps(half, 1)); - quarter = _mm_hadd_ps(quarter, quarter); - return _mm_cvtss_f32(_mm_hadd_ps(quarter, quarter)); -} -inline int v_reduce_sum(const v_int32x16& a) -{ - __m256i half = _mm256_add_epi32(_v512_extract_low(a.val), _v512_extract_high(a.val)); - __m128i quarter = _mm_add_epi32(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1)); - quarter = _mm_hadd_epi32(quarter, quarter); - return _mm_cvtsi128_si32(_mm_hadd_epi32(quarter, quarter)); -} -inline uint v_reduce_sum(const v_uint32x16& a) -{ return (uint)v_reduce_sum(v_reinterpret_as_s32(a)); } - -#define OPENCV_HAL_IMPL_AVX512_REDUCE_32(sctype, func, _Tpvec, ifunc) \ - inline sctype v_reduce_##func(const _Tpvec& a) \ - { __m256i half = _mm256_##ifunc(_v512_extract_low(a.val), _v512_extract_high(a.val)); \ - __m128i quarter = _mm_##ifunc(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1)); \ - quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 8)); \ - quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 4)); \ - quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 2)); \ - return (sctype)_mm_cvtsi128_si32(quarter); } -OPENCV_HAL_IMPL_AVX512_REDUCE_32(ushort, min, v_uint16x32, min_epu16) -OPENCV_HAL_IMPL_AVX512_REDUCE_32(ushort, max, v_uint16x32, max_epu16) -OPENCV_HAL_IMPL_AVX512_REDUCE_32(short, min, v_int16x32, min_epi16) -OPENCV_HAL_IMPL_AVX512_REDUCE_32(short, max, v_int16x32, max_epi16) - -inline int v_reduce_sum(const v_int16x32& a) -{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } -inline uint v_reduce_sum(const v_uint16x32& a) -{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } - -#define OPENCV_HAL_IMPL_AVX512_REDUCE_64(sctype, func, _Tpvec, ifunc) \ - inline sctype v_reduce_##func(const _Tpvec& a) \ - { __m256i half = _mm256_##ifunc(_v512_extract_low(a.val), _v512_extract_high(a.val)); \ - __m128i quarter = _mm_##ifunc(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1)); \ - quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 8)); \ - quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 4)); \ - quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 2)); \ - quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 1)); \ - return (sctype)_mm_cvtsi128_si32(quarter); } -OPENCV_HAL_IMPL_AVX512_REDUCE_64(uchar, min, v_uint8x64, min_epu8) -OPENCV_HAL_IMPL_AVX512_REDUCE_64(uchar, max, v_uint8x64, max_epu8) -OPENCV_HAL_IMPL_AVX512_REDUCE_64(schar, min, v_int8x64, min_epi8) -OPENCV_HAL_IMPL_AVX512_REDUCE_64(schar, max, v_int8x64, max_epi8) - -#define OPENCV_HAL_IMPL_AVX512_REDUCE_64_SUM(sctype, _Tpvec, suffix) \ - inline sctype v_reduce_sum(const _Tpvec& a) \ - { __m512i a16 = _mm512_add_epi16(_mm512_cvt##suffix##_epi16(_v512_extract_low(a.val)), \ - _mm512_cvt##suffix##_epi16(_v512_extract_high(a.val))); \ - a16 = _mm512_cvtepi16_epi32(_mm256_add_epi16(_v512_extract_low(a16), _v512_extract_high(a16))); \ - __m256i a8 = _mm256_add_epi32(_v512_extract_low(a16), _v512_extract_high(a16)); \ - __m128i a4 = _mm_add_epi32(_mm256_castsi256_si128(a8), _mm256_extracti128_si256(a8, 1)); \ - a4 = _mm_hadd_epi32(a4, a4); \ - return (sctype)_mm_cvtsi128_si32(_mm_hadd_epi32(a4, a4)); } -OPENCV_HAL_IMPL_AVX512_REDUCE_64_SUM(uint, v_uint8x64, epu8) -OPENCV_HAL_IMPL_AVX512_REDUCE_64_SUM(int, v_int8x64, epi8) - -inline v_float32x16 v_reduce_sum4(const v_float32x16& a, const v_float32x16& b, - const v_float32x16& c, const v_float32x16& d) -{ - __m256 abl = _mm256_hadd_ps(_v512_extract_low(a.val), _v512_extract_low(b.val)); - __m256 abh = _mm256_hadd_ps(_v512_extract_high(a.val), _v512_extract_high(b.val)); - __m256 cdl = _mm256_hadd_ps(_v512_extract_low(c.val), _v512_extract_low(d.val)); - __m256 cdh = _mm256_hadd_ps(_v512_extract_high(c.val), _v512_extract_high(d.val)); - return v_float32x16(_v512_combine(_mm256_hadd_ps(abl, cdl), _mm256_hadd_ps(abh, cdh))); -} - -inline unsigned v_reduce_sad(const v_uint8x64& a, const v_uint8x64& b) -{ - __m512i val = _mm512_sad_epu8(a.val, b.val); - __m256i half = _mm256_add_epi32(_v512_extract_low(val), _v512_extract_high(val)); - __m128i quarter = _mm_add_epi32(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1)); - return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(quarter, _mm_unpackhi_epi64(quarter, quarter))); -} -inline unsigned v_reduce_sad(const v_int8x64& a, const v_int8x64& b) -{ - __m512i val = _mm512_set1_epi8(-128); - val = _mm512_sad_epu8(_mm512_add_epi8(a.val, val), _mm512_add_epi8(b.val, val)); - __m256i half = _mm256_add_epi32(_v512_extract_low(val), _v512_extract_high(val)); - __m128i quarter = _mm_add_epi32(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1)); - return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(quarter, _mm_unpackhi_epi64(quarter, quarter))); -} -inline unsigned v_reduce_sad(const v_uint16x32& a, const v_uint16x32& b) -{ return v_reduce_sum(v_add_wrap(v_sub(a, b), v_sub(b, a))); } -inline unsigned v_reduce_sad(const v_int16x32& a, const v_int16x32& b) -{ return v_reduce_sum(v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b)))); } -inline unsigned v_reduce_sad(const v_uint32x16& a, const v_uint32x16& b) -{ return v_reduce_sum(v_sub(v_max(a, b), v_min(a, b))); } -inline unsigned v_reduce_sad(const v_int32x16& a, const v_int32x16& b) -{ return v_reduce_sum(v_reinterpret_as_u32(v_sub(v_max(a, b), v_min(a, b)))); } -inline float v_reduce_sad(const v_float32x16& a, const v_float32x16& b) -{ return v_reduce_sum(v_and(v_sub(a, b), v_float32x16(_mm512_castsi512_ps(_mm512_set1_epi32(0x7fffffff))))); } -inline double v_reduce_sad(const v_float64x8& a, const v_float64x8& b) -{ return v_reduce_sum(v_and(v_sub(a, b), v_float64x8(_mm512_castsi512_pd(_mm512_set1_epi64(0x7fffffffffffffff))))); } - -/** Popcount **/ -inline v_uint8x64 v_popcount(const v_int8x64& a) -{ -#if CV_AVX_512BITALG - return v_uint8x64(_mm512_popcnt_epi8(a.val)); -#elif CV_AVX_512VBMI - __m512i _popcnt_table0 = _v512_set_epu8(7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3, - 5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1, - 5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1, - 4, 3, 3, 2, 3, 2, 2, 1, 3, 2, 2, 1, 2, 1, 1, 0); - __m512i _popcnt_table1 = _v512_set_epu8(7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3, - 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, - 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, - 5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1); - return v_uint8x64(_mm512_sub_epi8(_mm512_permutex2var_epi8(_popcnt_table0, a.val, _popcnt_table1), _mm512_movm_epi8(_mm512_movepi8_mask(a.val)))); -#else - __m512i _popcnt_table = _mm512_set4_epi32(0x04030302, 0x03020201, 0x03020201, 0x02010100); - __m512i _popcnt_mask = _mm512_set1_epi8(0x0F); - - return v_uint8x64(_mm512_add_epi8(_mm512_shuffle_epi8(_popcnt_table, _mm512_and_si512( a.val, _popcnt_mask)), - _mm512_shuffle_epi8(_popcnt_table, _mm512_and_si512(_mm512_srli_epi16(a.val, 4), _popcnt_mask)))); -#endif -} -inline v_uint16x32 v_popcount(const v_int16x32& a) -{ -#if CV_AVX_512BITALG - return v_uint16x32(_mm512_popcnt_epi16(a.val)); -#elif CV_AVX_512VPOPCNTDQ - __m512i zero = _mm512_setzero_si512(); - return v_uint16x32(_mm512_packs_epi32(_mm512_popcnt_epi32(_mm512_unpacklo_epi16(a.val, zero)), - _mm512_popcnt_epi32(_mm512_unpackhi_epi16(a.val, zero)))); -#else - v_uint8x64 p = v_popcount(v_reinterpret_as_s8(a)); - p = v_add(p, v_rotate_right<1>(p)); - return v_and(v_reinterpret_as_u16(p), v512_setall_u16(0x00ff)); -#endif -} -inline v_uint32x16 v_popcount(const v_int32x16& a) -{ -#if CV_AVX_512VPOPCNTDQ - return v_uint32x16(_mm512_popcnt_epi32(a.val)); -#else - v_uint8x64 p = v_popcount(v_reinterpret_as_s8(a)); - p = v_add(p, v_rotate_right<1>(p)); - p = v_add(p, v_rotate_right<2>(p)); - return v_and(v_reinterpret_as_u32(p), v512_setall_u32(0x000000ff)); -#endif -} -inline v_uint64x8 v_popcount(const v_int64x8& a) -{ -#if CV_AVX_512VPOPCNTDQ - return v_uint64x8(_mm512_popcnt_epi64(a.val)); -#else - return v_uint64x8(_mm512_sad_epu8(v_popcount(v_reinterpret_as_s8(a)).val, _mm512_setzero_si512())); -#endif -} - - -inline v_uint8x64 v_popcount(const v_uint8x64& a) { return v_popcount(v_reinterpret_as_s8 (a)); } -inline v_uint16x32 v_popcount(const v_uint16x32& a) { return v_popcount(v_reinterpret_as_s16(a)); } -inline v_uint32x16 v_popcount(const v_uint32x16& a) { return v_popcount(v_reinterpret_as_s32(a)); } -inline v_uint64x8 v_popcount(const v_uint64x8& a) { return v_popcount(v_reinterpret_as_s64(a)); } - - -////////// Other math ///////// - -/** Some frequent operations **/ -#if CV_FMA3 -#define OPENCV_HAL_IMPL_AVX512_MULADD(_Tpvec, suffix) \ - inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ - { return _Tpvec(_mm512_fmadd_##suffix(a.val, b.val, c.val)); } \ - inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ - { return _Tpvec(_mm512_fmadd_##suffix(a.val, b.val, c.val)); } -#else -#define OPENCV_HAL_IMPL_AVX512_MULADD(_Tpvec, suffix) \ - inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ - { return _Tpvec(_mm512_add_##suffix(_mm512_mul_##suffix(a.val, b.val), c.val)); } \ - inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ - { return _Tpvec(_mm512_add_##suffix(_mm512_mul_##suffix(a.val, b.val), c.val)); } -#endif - -#define OPENCV_HAL_IMPL_AVX512_MISC(_Tpvec, suffix) \ - inline _Tpvec v_sqrt(const _Tpvec& x) \ - { return _Tpvec(_mm512_sqrt_##suffix(x.val)); } \ - inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ - { return v_fma(a, a, v_mul(b, b)); } \ - inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ - { return v_sqrt(v_fma(a, a, v_mul(b, b))); } - -OPENCV_HAL_IMPL_AVX512_MULADD(v_float32x16, ps) -OPENCV_HAL_IMPL_AVX512_MULADD(v_float64x8, pd) -OPENCV_HAL_IMPL_AVX512_MISC(v_float32x16, ps) -OPENCV_HAL_IMPL_AVX512_MISC(v_float64x8, pd) - -inline v_int32x16 v_fma(const v_int32x16& a, const v_int32x16& b, const v_int32x16& c) -{ return v_add(v_mul(a, b), c); } -inline v_int32x16 v_muladd(const v_int32x16& a, const v_int32x16& b, const v_int32x16& c) -{ return v_fma(a, b, c); } - -inline v_float32x16 v_invsqrt(const v_float32x16& x) -{ -#if CV_AVX_512ER - return v_float32x16(_mm512_rsqrt28_ps(x.val)); -#else - v_float32x16 half = v_mul(x, v512_setall_f32(0.5)); - v_float32x16 t = v_float32x16(_mm512_rsqrt14_ps(x.val)); - t = v_mul(t, v_sub(v512_setall_f32(1.5), v_mul(v_mul(t, t), half))); - return t; -#endif -} - -inline v_float64x8 v_invsqrt(const v_float64x8& x) -{ -#if CV_AVX_512ER - return v_float64x8(_mm512_rsqrt28_pd(x.val)); -#else - return v_div(v512_setall_f64(1.), v_sqrt(x)); -// v_float64x8 half = x * v512_setall_f64(0.5); -// v_float64x8 t = v_float64x8(_mm512_rsqrt14_pd(x.val)); -// t *= v512_setall_f64(1.5) - ((t * t) * half); -// t *= v512_setall_f64(1.5) - ((t * t) * half); -// return t; -#endif -} - -/** Absolute values **/ -#define OPENCV_HAL_IMPL_AVX512_ABS(_Tpvec, _Tpuvec, suffix) \ - inline _Tpuvec v_abs(const _Tpvec& x) \ - { return _Tpuvec(_mm512_abs_##suffix(x.val)); } - -OPENCV_HAL_IMPL_AVX512_ABS(v_int8x64, v_uint8x64, epi8) -OPENCV_HAL_IMPL_AVX512_ABS(v_int16x32, v_uint16x32, epi16) -OPENCV_HAL_IMPL_AVX512_ABS(v_int32x16, v_uint32x16, epi32) -OPENCV_HAL_IMPL_AVX512_ABS(v_int64x8, v_uint64x8, epi64) - -inline v_float32x16 v_abs(const v_float32x16& x) -{ -#ifdef _mm512_abs_pd - return v_float32x16(_mm512_abs_ps(x.val)); -#else - return v_float32x16(_mm512_castsi512_ps(_mm512_and_si512(_mm512_castps_si512(x.val), - _v512_set_epu64(0x7FFFFFFF7FFFFFFF, 0x7FFFFFFF7FFFFFFF, 0x7FFFFFFF7FFFFFFF, 0x7FFFFFFF7FFFFFFF, - 0x7FFFFFFF7FFFFFFF, 0x7FFFFFFF7FFFFFFF, 0x7FFFFFFF7FFFFFFF, 0x7FFFFFFF7FFFFFFF)))); -#endif -} - -inline v_float64x8 v_abs(const v_float64x8& x) -{ -#ifdef _mm512_abs_pd - #if defined __GNUC__ && (__GNUC__ < 7 || (__GNUC__ == 7 && __GNUC_MINOR__ <= 3) || (__GNUC__ == 8 && __GNUC_MINOR__ <= 2)) - // Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=87476 - return v_float64x8(_mm512_abs_pd(_mm512_castpd_ps(x.val))); - #else - return v_float64x8(_mm512_abs_pd(x.val)); - #endif -#else - return v_float64x8(_mm512_castsi512_pd(_mm512_and_si512(_mm512_castpd_si512(x.val), - _v512_set_epu64(0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, - 0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF)))); -#endif -} - -/** Absolute difference **/ -inline v_uint8x64 v_absdiff(const v_uint8x64& a, const v_uint8x64& b) -{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } -inline v_uint16x32 v_absdiff(const v_uint16x32& a, const v_uint16x32& b) -{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } -inline v_uint32x16 v_absdiff(const v_uint32x16& a, const v_uint32x16& b) -{ return v_sub(v_max(a, b), v_min(a, b)); } - -inline v_uint8x64 v_absdiff(const v_int8x64& a, const v_int8x64& b) -{ - v_int8x64 d = v_sub_wrap(a, b); - v_int8x64 m = v_lt(a, b); - return v_reinterpret_as_u8(v_sub_wrap(v_xor(d, m), m)); -} - -inline v_uint16x32 v_absdiff(const v_int16x32& a, const v_int16x32& b) -{ return v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))); } - -inline v_uint32x16 v_absdiff(const v_int32x16& a, const v_int32x16& b) -{ - v_int32x16 d = v_sub(a, b); - v_int32x16 m = v_lt(a, b); - return v_reinterpret_as_u32(v_sub(v_xor(d, m), m)); -} - -inline v_float32x16 v_absdiff(const v_float32x16& a, const v_float32x16& b) -{ return v_abs(v_sub(a, b)); } - -inline v_float64x8 v_absdiff(const v_float64x8& a, const v_float64x8& b) -{ return v_abs(v_sub(a, b)); } - -/** Saturating absolute difference **/ -inline v_int8x64 v_absdiffs(const v_int8x64& a, const v_int8x64& b) -{ - v_int8x64 d = v_sub(a, b); - v_int8x64 m = v_lt(a, b); - return v_sub(v_xor(d, m), m); -} -inline v_int16x32 v_absdiffs(const v_int16x32& a, const v_int16x32& b) -{ return v_sub(v_max(a, b), v_min(a, b)); } - -////////// Conversions ///////// - -/** Rounding **/ -inline v_int32x16 v_round(const v_float32x16& a) -{ return v_int32x16(_mm512_cvtps_epi32(a.val)); } - -inline v_int32x16 v_round(const v_float64x8& a) -{ return v_int32x16(_mm512_castsi256_si512(_mm512_cvtpd_epi32(a.val))); } - -inline v_int32x16 v_round(const v_float64x8& a, const v_float64x8& b) -{ return v_int32x16(_v512_combine(_mm512_cvtpd_epi32(a.val), _mm512_cvtpd_epi32(b.val))); } - -inline v_int32x16 v_trunc(const v_float32x16& a) -{ return v_int32x16(_mm512_cvttps_epi32(a.val)); } - -inline v_int32x16 v_trunc(const v_float64x8& a) -{ return v_int32x16(_mm512_castsi256_si512(_mm512_cvttpd_epi32(a.val))); } - -#if CVT_ROUND_MODES_IMPLEMENTED -inline v_int32x16 v_floor(const v_float32x16& a) -{ return v_int32x16(_mm512_cvt_roundps_epi32(a.val, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC)); } - -inline v_int32x16 v_floor(const v_float64x8& a) -{ return v_int32x16(_mm512_castsi256_si512(_mm512_cvt_roundpd_epi32(a.val, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC))); } - -inline v_int32x16 v_ceil(const v_float32x16& a) -{ return v_int32x16(_mm512_cvt_roundps_epi32(a.val, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC)); } - -inline v_int32x16 v_ceil(const v_float64x8& a) -{ return v_int32x16(_mm512_castsi256_si512(_mm512_cvt_roundpd_epi32(a.val, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC))); } -#else -inline v_int32x16 v_floor(const v_float32x16& a) -{ return v_int32x16(_mm512_cvtps_epi32(_mm512_roundscale_ps(a.val, 1))); } - -inline v_int32x16 v_floor(const v_float64x8& a) -{ return v_int32x16(_mm512_castsi256_si512(_mm512_cvtpd_epi32(_mm512_roundscale_pd(a.val, 1)))); } - -inline v_int32x16 v_ceil(const v_float32x16& a) -{ return v_int32x16(_mm512_cvtps_epi32(_mm512_roundscale_ps(a.val, 2))); } - -inline v_int32x16 v_ceil(const v_float64x8& a) -{ return v_int32x16(_mm512_castsi256_si512(_mm512_cvtpd_epi32(_mm512_roundscale_pd(a.val, 2)))); } -#endif - -/** To float **/ -inline v_float32x16 v_cvt_f32(const v_int32x16& a) -{ return v_float32x16(_mm512_cvtepi32_ps(a.val)); } - -inline v_float32x16 v_cvt_f32(const v_float64x8& a) -{ return v_float32x16(_mm512_cvtpd_pslo(a.val)); } - -inline v_float32x16 v_cvt_f32(const v_float64x8& a, const v_float64x8& b) -{ return v_float32x16(_v512_combine(_mm512_cvtpd_ps(a.val), _mm512_cvtpd_ps(b.val))); } - -inline v_float64x8 v_cvt_f64(const v_int32x16& a) -{ return v_float64x8(_mm512_cvtepi32_pd(_v512_extract_low(a.val))); } - -inline v_float64x8 v_cvt_f64_high(const v_int32x16& a) -{ return v_float64x8(_mm512_cvtepi32_pd(_v512_extract_high(a.val))); } - -inline v_float64x8 v_cvt_f64(const v_float32x16& a) -{ return v_float64x8(_mm512_cvtps_pd(_v512_extract_low(a.val))); } - -inline v_float64x8 v_cvt_f64_high(const v_float32x16& a) -{ return v_float64x8(_mm512_cvtps_pd(_v512_extract_high(a.val))); } - -// from (Mysticial and wim) https://stackoverflow.com/q/41144668 -inline v_float64x8 v_cvt_f64(const v_int64x8& v) -{ -#if CV_AVX_512DQ - return v_float64x8(_mm512_cvtepi64_pd(v.val)); -#else - // constants encoded as floating-point - __m512i magic_i_lo = _mm512_set1_epi64(0x4330000000000000); // 2^52 - __m512i magic_i_hi32 = _mm512_set1_epi64(0x4530000080000000); // 2^84 + 2^63 - __m512i magic_i_all = _mm512_set1_epi64(0x4530000080100000); // 2^84 + 2^63 + 2^52 - __m512d magic_d_all = _mm512_castsi512_pd(magic_i_all); - - // Blend the 32 lowest significant bits of v with magic_int_lo - __m512i v_lo = _mm512_mask_blend_epi32(0x5555, magic_i_lo, v.val); - // Extract the 32 most significant bits of v - __m512i v_hi = _mm512_srli_epi64(v.val, 32); - // Flip the msb of v_hi and blend with 0x45300000 - v_hi = _mm512_xor_si512(v_hi, magic_i_hi32); - // Compute in double precision - __m512d v_hi_dbl = _mm512_sub_pd(_mm512_castsi512_pd(v_hi), magic_d_all); - // (v_hi - magic_d_all) + v_lo Do not assume associativity of floating point addition - __m512d result = _mm512_add_pd(v_hi_dbl, _mm512_castsi512_pd(v_lo)); - return v_float64x8(result); -#endif -} - -////////////// Lookup table access //////////////////// - -inline v_int8x64 v512_lut(const schar* tab, const int* idx) -{ - __m128i p0 = _mm512_cvtepi32_epi8(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx ), (const int *)tab, 1)); - __m128i p1 = _mm512_cvtepi32_epi8(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx + 1), (const int *)tab, 1)); - __m128i p2 = _mm512_cvtepi32_epi8(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx + 2), (const int *)tab, 1)); - __m128i p3 = _mm512_cvtepi32_epi8(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx + 3), (const int *)tab, 1)); - return v_int8x64(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_castsi128_si512(p0), p1, 1), p2, 2), p3, 3)); -} -inline v_int8x64 v512_lut_pairs(const schar* tab, const int* idx) -{ - __m256i p0 = _mm512_cvtepi32_epi16(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx ), (const int *)tab, 1)); - __m256i p1 = _mm512_cvtepi32_epi16(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx + 1), (const int *)tab, 1)); - return v_int8x64(_v512_combine(p0, p1)); -} -inline v_int8x64 v512_lut_quads(const schar* tab, const int* idx) -{ - return v_int8x64(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx), (const int *)tab, 1)); -} -inline v_uint8x64 v512_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v512_lut((const schar *)tab, idx)); } -inline v_uint8x64 v512_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v512_lut_pairs((const schar *)tab, idx)); } -inline v_uint8x64 v512_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v512_lut_quads((const schar *)tab, idx)); } - -inline v_int16x32 v512_lut(const short* tab, const int* idx) -{ - __m256i p0 = _mm512_cvtepi32_epi16(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx ), (const int *)tab, 2)); - __m256i p1 = _mm512_cvtepi32_epi16(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx + 1), (const int *)tab, 2)); - return v_int16x32(_v512_combine(p0, p1)); -} -inline v_int16x32 v512_lut_pairs(const short* tab, const int* idx) -{ - return v_int16x32(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx), (const int *)tab, 2)); -} -inline v_int16x32 v512_lut_quads(const short* tab, const int* idx) -{ -#if defined(__GNUC__) - return v_int16x32(_mm512_i32gather_epi64(_mm256_loadu_si256((const __m256i*)idx), (const long long int*)tab, 2)); -#else - return v_int16x32(_mm512_i32gather_epi64(_mm256_loadu_si256((const __m256i*)idx), (const int64*)tab, 2)); -#endif -} -inline v_uint16x32 v512_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v512_lut((const short *)tab, idx)); } -inline v_uint16x32 v512_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v512_lut_pairs((const short *)tab, idx)); } -inline v_uint16x32 v512_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v512_lut_quads((const short *)tab, idx)); } - -inline v_int32x16 v512_lut(const int* tab, const int* idx) -{ - return v_int32x16(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx), tab, 4)); -} -inline v_int32x16 v512_lut_pairs(const int* tab, const int* idx) -{ -#if defined(__GNUC__) - return v_int32x16(_mm512_i32gather_epi64(_mm256_loadu_si256((const __m256i*)idx), (const long long int*)tab, 4)); -#else - return v_int32x16(_mm512_i32gather_epi64(_mm256_loadu_si256((const __m256i*)idx), (const int64*)tab, 4)); -#endif -} -inline v_int32x16 v512_lut_quads(const int* tab, const int* idx) -{ - return v_int32x16(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_castsi128_si512( - _mm_loadu_si128((const __m128i*)(tab + idx[0]))), - _mm_loadu_si128((const __m128i*)(tab + idx[1])), 1), - _mm_loadu_si128((const __m128i*)(tab + idx[2])), 2), - _mm_loadu_si128((const __m128i*)(tab + idx[3])), 3)); -} -inline v_uint32x16 v512_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v512_lut((const int *)tab, idx)); } -inline v_uint32x16 v512_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v512_lut_pairs((const int *)tab, idx)); } -inline v_uint32x16 v512_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v512_lut_quads((const int *)tab, idx)); } - -inline v_int64x8 v512_lut(const int64* tab, const int* idx) -{ -#if defined(__GNUC__) - return v_int64x8(_mm512_i32gather_epi64(_mm256_loadu_si256((const __m256i*)idx), (const long long int*)tab, 8)); -#else - return v_int64x8(_mm512_i32gather_epi64(_mm256_loadu_si256((const __m256i*)idx), tab , 8)); -#endif -} -inline v_int64x8 v512_lut_pairs(const int64* tab, const int* idx) -{ - return v_int64x8(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_castsi128_si512( - _mm_loadu_si128((const __m128i*)(tab + idx[0]))), - _mm_loadu_si128((const __m128i*)(tab + idx[1])), 1), - _mm_loadu_si128((const __m128i*)(tab + idx[2])), 2), - _mm_loadu_si128((const __m128i*)(tab + idx[3])), 3)); -} -inline v_uint64x8 v512_lut(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v512_lut((const int64 *)tab, idx)); } -inline v_uint64x8 v512_lut_pairs(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v512_lut_pairs((const int64 *)tab, idx)); } - -inline v_float32x16 v512_lut(const float* tab, const int* idx) -{ - return v_float32x16(_mm512_i32gather_ps(_mm512_loadu_si512((const __m512i*)idx), tab, 4)); -} -inline v_float32x16 v512_lut_pairs(const float* tab, const int* idx) { return v_reinterpret_as_f32(v512_lut_pairs((const int *)tab, idx)); } -inline v_float32x16 v512_lut_quads(const float* tab, const int* idx) { return v_reinterpret_as_f32(v512_lut_quads((const int *)tab, idx)); } - -inline v_float64x8 v512_lut(const double* tab, const int* idx) -{ - return v_float64x8(_mm512_i32gather_pd(_mm256_loadu_si256((const __m256i*)idx), tab, 8)); -} -inline v_float64x8 v512_lut_pairs(const double* tab, const int* idx) -{ - return v_float64x8(_mm512_insertf64x2(_mm512_insertf64x2(_mm512_insertf64x2(_mm512_castpd128_pd512( - _mm_loadu_pd(tab + idx[0])), - _mm_loadu_pd(tab + idx[1]), 1), - _mm_loadu_pd(tab + idx[2]), 2), - _mm_loadu_pd(tab + idx[3]), 3)); -} - -inline v_int32x16 v_lut(const int* tab, const v_int32x16& idxvec) -{ - return v_int32x16(_mm512_i32gather_epi32(idxvec.val, tab, 4)); -} - -inline v_uint32x16 v_lut(const unsigned* tab, const v_int32x16& idxvec) -{ - return v_reinterpret_as_u32(v_lut((const int *)tab, idxvec)); -} - -inline v_float32x16 v_lut(const float* tab, const v_int32x16& idxvec) -{ - return v_float32x16(_mm512_i32gather_ps(idxvec.val, tab, 4)); -} - -inline v_float64x8 v_lut(const double* tab, const v_int32x16& idxvec) -{ - return v_float64x8(_mm512_i32gather_pd(_v512_extract_low(idxvec.val), tab, 8)); -} - -inline void v_lut_deinterleave(const float* tab, const v_int32x16& idxvec, v_float32x16& x, v_float32x16& y) -{ - x.val = _mm512_i32gather_ps(idxvec.val, tab, 4); - y.val = _mm512_i32gather_ps(idxvec.val, &tab[1], 4); -} - -inline void v_lut_deinterleave(const double* tab, const v_int32x16& idxvec, v_float64x8& x, v_float64x8& y) -{ - x.val = _mm512_i32gather_pd(_v512_extract_low(idxvec.val), tab, 8); - y.val = _mm512_i32gather_pd(_v512_extract_low(idxvec.val), &tab[1], 8); -} - -inline v_int8x64 v_interleave_pairs(const v_int8x64& vec) -{ - return v_int8x64(_mm512_shuffle_epi8(vec.val, _mm512_set4_epi32(0x0f0d0e0c, 0x0b090a08, 0x07050604, 0x03010200))); -} -inline v_uint8x64 v_interleave_pairs(const v_uint8x64& vec) { return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } -inline v_int8x64 v_interleave_quads(const v_int8x64& vec) -{ - return v_int8x64(_mm512_shuffle_epi8(vec.val, _mm512_set4_epi32(0x0f0b0e0a, 0x0d090c08, 0x07030602, 0x05010400))); -} -inline v_uint8x64 v_interleave_quads(const v_uint8x64& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } - -inline v_int16x32 v_interleave_pairs(const v_int16x32& vec) -{ - return v_int16x32(_mm512_shuffle_epi8(vec.val, _mm512_set4_epi32(0x0f0e0b0a, 0x0d0c0908, 0x07060302, 0x05040100))); -} -inline v_uint16x32 v_interleave_pairs(const v_uint16x32& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } -inline v_int16x32 v_interleave_quads(const v_int16x32& vec) -{ - return v_int16x32(_mm512_shuffle_epi8(vec.val, _mm512_set4_epi32(0x0f0e0706, 0x0d0c0504, 0x0b0a0302, 0x09080100))); -} -inline v_uint16x32 v_interleave_quads(const v_uint16x32& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } - -inline v_int32x16 v_interleave_pairs(const v_int32x16& vec) -{ - return v_int32x16(_mm512_shuffle_epi32(vec.val, _MM_PERM_ACBD)); -} -inline v_uint32x16 v_interleave_pairs(const v_uint32x16& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } -inline v_float32x16 v_interleave_pairs(const v_float32x16& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } - -inline v_int8x64 v_pack_triplets(const v_int8x64& vec) -{ - return v_int8x64(_mm512_permutexvar_epi32(_v512_set_epu64(0x0000000f0000000f, 0x0000000f0000000f, 0x0000000e0000000d, 0x0000000c0000000a, - 0x0000000900000008, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000), - _mm512_shuffle_epi8(vec.val, _mm512_set4_epi32(0xffffff0f, 0x0e0d0c0a, 0x09080605, 0x04020100)))); -} -inline v_uint8x64 v_pack_triplets(const v_uint8x64& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } - -inline v_int16x32 v_pack_triplets(const v_int16x32& vec) -{ - return v_int16x32(_mm512_permutexvar_epi16(_v512_set_epu64(0x001f001f001f001f, 0x001f001f001f001f, 0x001e001d001c001a, 0x0019001800160015, - 0x0014001200110010, 0x000e000d000c000a, 0x0009000800060005, 0x0004000200010000), vec.val)); -} -inline v_uint16x32 v_pack_triplets(const v_uint16x32& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } - -inline v_int32x16 v_pack_triplets(const v_int32x16& vec) -{ - return v_int32x16(_mm512_permutexvar_epi32(_v512_set_epu64(0x0000000f0000000f, 0x0000000f0000000f, 0x0000000e0000000d, 0x0000000c0000000a, - 0x0000000900000008, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000), vec.val)); -} -inline v_uint32x16 v_pack_triplets(const v_uint32x16& vec) { return v_reinterpret_as_u32(v_pack_triplets(v_reinterpret_as_s32(vec))); } -inline v_float32x16 v_pack_triplets(const v_float32x16& vec) -{ - return v_float32x16(_mm512_permutexvar_ps(_v512_set_epu64(0x0000000f0000000f, 0x0000000f0000000f, 0x0000000e0000000d, 0x0000000c0000000a, - 0x0000000900000008, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000), vec.val)); -} - -////////// Matrix operations ///////// - -//////// Dot Product //////// - -// 16 >> 32 -inline v_int32x16 v_dotprod(const v_int16x32& a, const v_int16x32& b) -{ return v_int32x16(_mm512_madd_epi16(a.val, b.val)); } -inline v_int32x16 v_dotprod(const v_int16x32& a, const v_int16x32& b, const v_int32x16& c) -{ return v_add(v_dotprod(a, b), c); } - -// 32 >> 64 -inline v_int64x8 v_dotprod(const v_int32x16& a, const v_int32x16& b) -{ - __m512i even = _mm512_mul_epi32(a.val, b.val); - __m512i odd = _mm512_mul_epi32(_mm512_srli_epi64(a.val, 32), _mm512_srli_epi64(b.val, 32)); - return v_int64x8(_mm512_add_epi64(even, odd)); -} -inline v_int64x8 v_dotprod(const v_int32x16& a, const v_int32x16& b, const v_int64x8& c) -{ return v_add(v_dotprod(a, b), c); } - -// 8 >> 32 -inline v_uint32x16 v_dotprod_expand(const v_uint8x64& a, const v_uint8x64& b) -{ - __m512i even_a = _mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, a.val, _mm512_setzero_si512()); - __m512i odd_a = _mm512_srli_epi16(a.val, 8); - - __m512i even_b = _mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, b.val, _mm512_setzero_si512()); - __m512i odd_b = _mm512_srli_epi16(b.val, 8); - - __m512i prod0 = _mm512_madd_epi16(even_a, even_b); - __m512i prod1 = _mm512_madd_epi16(odd_a, odd_b); - return v_uint32x16(_mm512_add_epi32(prod0, prod1)); -} -inline v_uint32x16 v_dotprod_expand(const v_uint8x64& a, const v_uint8x64& b, const v_uint32x16& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int32x16 v_dotprod_expand(const v_int8x64& a, const v_int8x64& b) -{ - __m512i even_a = _mm512_srai_epi16(_mm512_bslli_epi128(a.val, 1), 8); - __m512i odd_a = _mm512_srai_epi16(a.val, 8); - - __m512i even_b = _mm512_srai_epi16(_mm512_bslli_epi128(b.val, 1), 8); - __m512i odd_b = _mm512_srai_epi16(b.val, 8); - - __m512i prod0 = _mm512_madd_epi16(even_a, even_b); - __m512i prod1 = _mm512_madd_epi16(odd_a, odd_b); - return v_int32x16(_mm512_add_epi32(prod0, prod1)); -} -inline v_int32x16 v_dotprod_expand(const v_int8x64& a, const v_int8x64& b, const v_int32x16& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 16 >> 64 -inline v_uint64x8 v_dotprod_expand(const v_uint16x32& a, const v_uint16x32& b) -{ - __m512i mullo = _mm512_mullo_epi16(a.val, b.val); - __m512i mulhi = _mm512_mulhi_epu16(a.val, b.val); - __m512i mul0 = _mm512_unpacklo_epi16(mullo, mulhi); - __m512i mul1 = _mm512_unpackhi_epi16(mullo, mulhi); - - __m512i p02 = _mm512_mask_blend_epi32(0xAAAA, mul0, _mm512_setzero_si512()); - __m512i p13 = _mm512_srli_epi64(mul0, 32); - __m512i p46 = _mm512_mask_blend_epi32(0xAAAA, mul1, _mm512_setzero_si512()); - __m512i p57 = _mm512_srli_epi64(mul1, 32); - - __m512i p15_ = _mm512_add_epi64(p02, p13); - __m512i p9d_ = _mm512_add_epi64(p46, p57); - - return v_uint64x8(_mm512_add_epi64( - _mm512_unpacklo_epi64(p15_, p9d_), - _mm512_unpackhi_epi64(p15_, p9d_) - )); -} -inline v_uint64x8 v_dotprod_expand(const v_uint16x32& a, const v_uint16x32& b, const v_uint64x8& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int64x8 v_dotprod_expand(const v_int16x32& a, const v_int16x32& b) -{ - __m512i prod = _mm512_madd_epi16(a.val, b.val); - __m512i even = _mm512_srai_epi64(_mm512_bslli_epi128(prod, 4), 32); - __m512i odd = _mm512_srai_epi64(prod, 32); - return v_int64x8(_mm512_add_epi64(even, odd)); -} -inline v_int64x8 v_dotprod_expand(const v_int16x32& a, const v_int16x32& b, const v_int64x8& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 32 >> 64f -inline v_float64x8 v_dotprod_expand(const v_int32x16& a, const v_int32x16& b) -{ return v_cvt_f64(v_dotprod(a, b)); } -inline v_float64x8 v_dotprod_expand(const v_int32x16& a, const v_int32x16& b, const v_float64x8& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -//////// Fast Dot Product //////// - -// 16 >> 32 -inline v_int32x16 v_dotprod_fast(const v_int16x32& a, const v_int16x32& b) -{ return v_dotprod(a, b); } -inline v_int32x16 v_dotprod_fast(const v_int16x32& a, const v_int16x32& b, const v_int32x16& c) -{ return v_dotprod(a, b, c); } - -// 32 >> 64 -inline v_int64x8 v_dotprod_fast(const v_int32x16& a, const v_int32x16& b) -{ return v_dotprod(a, b); } -inline v_int64x8 v_dotprod_fast(const v_int32x16& a, const v_int32x16& b, const v_int64x8& c) -{ return v_dotprod(a, b, c); } - -// 8 >> 32 -inline v_uint32x16 v_dotprod_expand_fast(const v_uint8x64& a, const v_uint8x64& b) -{ return v_dotprod_expand(a, b); } -inline v_uint32x16 v_dotprod_expand_fast(const v_uint8x64& a, const v_uint8x64& b, const v_uint32x16& c) -{ return v_dotprod_expand(a, b, c); } - -inline v_int32x16 v_dotprod_expand_fast(const v_int8x64& a, const v_int8x64& b) -{ return v_dotprod_expand(a, b); } -inline v_int32x16 v_dotprod_expand_fast(const v_int8x64& a, const v_int8x64& b, const v_int32x16& c) -{ return v_dotprod_expand(a, b, c); } - -// 16 >> 64 -inline v_uint64x8 v_dotprod_expand_fast(const v_uint16x32& a, const v_uint16x32& b) -{ - __m512i mullo = _mm512_mullo_epi16(a.val, b.val); - __m512i mulhi = _mm512_mulhi_epu16(a.val, b.val); - __m512i mul0 = _mm512_unpacklo_epi16(mullo, mulhi); - __m512i mul1 = _mm512_unpackhi_epi16(mullo, mulhi); - - __m512i p02 = _mm512_mask_blend_epi32(0xAAAA, mul0, _mm512_setzero_si512()); - __m512i p13 = _mm512_srli_epi64(mul0, 32); - __m512i p46 = _mm512_mask_blend_epi32(0xAAAA, mul1, _mm512_setzero_si512()); - __m512i p57 = _mm512_srli_epi64(mul1, 32); - - __m512i p15_ = _mm512_add_epi64(p02, p13); - __m512i p9d_ = _mm512_add_epi64(p46, p57); - return v_uint64x8(_mm512_add_epi64(p15_, p9d_)); -} -inline v_uint64x8 v_dotprod_expand_fast(const v_uint16x32& a, const v_uint16x32& b, const v_uint64x8& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -inline v_int64x8 v_dotprod_expand_fast(const v_int16x32& a, const v_int16x32& b) -{ return v_dotprod_expand(a, b); } -inline v_int64x8 v_dotprod_expand_fast(const v_int16x32& a, const v_int16x32& b, const v_int64x8& c) -{ return v_dotprod_expand(a, b, c); } - -// 32 >> 64f -inline v_float64x8 v_dotprod_expand_fast(const v_int32x16& a, const v_int32x16& b) -{ return v_dotprod_expand(a, b); } -inline v_float64x8 v_dotprod_expand_fast(const v_int32x16& a, const v_int32x16& b, const v_float64x8& c) -{ return v_add(v_dotprod_expand(a, b), c); } - - -#define OPENCV_HAL_AVX512_SPLAT2_PS(a, im) \ - v_float32x16(_mm512_permute_ps(a.val, _MM_SHUFFLE(im, im, im, im))) - -inline v_float32x16 v_matmul(const v_float32x16& v, - const v_float32x16& m0, const v_float32x16& m1, - const v_float32x16& m2, const v_float32x16& m3) -{ - v_float32x16 v04 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 0); - v_float32x16 v15 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 1); - v_float32x16 v26 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 2); - v_float32x16 v37 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 3); - return v_fma(v04, m0, v_fma(v15, m1, v_fma(v26, m2, v_mul(v37, m3)))); -} - -inline v_float32x16 v_matmuladd(const v_float32x16& v, - const v_float32x16& m0, const v_float32x16& m1, - const v_float32x16& m2, const v_float32x16& a) -{ - v_float32x16 v04 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 0); - v_float32x16 v15 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 1); - v_float32x16 v26 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 2); - return v_fma(v04, m0, v_fma(v15, m1, v_fma(v26, m2, a))); -} - -#define OPENCV_HAL_IMPL_AVX512_TRANSPOSE4x4(_Tpvec, suffix, cast_from, cast_to) \ - inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ - const _Tpvec& a2, const _Tpvec& a3, \ - _Tpvec& b0, _Tpvec& b1, _Tpvec& b2, _Tpvec& b3) \ - { \ - __m512i t0 = cast_from(_mm512_unpacklo_##suffix(a0.val, a1.val)); \ - __m512i t1 = cast_from(_mm512_unpacklo_##suffix(a2.val, a3.val)); \ - __m512i t2 = cast_from(_mm512_unpackhi_##suffix(a0.val, a1.val)); \ - __m512i t3 = cast_from(_mm512_unpackhi_##suffix(a2.val, a3.val)); \ - b0.val = cast_to(_mm512_unpacklo_epi64(t0, t1)); \ - b1.val = cast_to(_mm512_unpackhi_epi64(t0, t1)); \ - b2.val = cast_to(_mm512_unpacklo_epi64(t2, t3)); \ - b3.val = cast_to(_mm512_unpackhi_epi64(t2, t3)); \ - } - -OPENCV_HAL_IMPL_AVX512_TRANSPOSE4x4(v_uint32x16, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_AVX512_TRANSPOSE4x4(v_int32x16, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_AVX512_TRANSPOSE4x4(v_float32x16, ps, _mm512_castps_si512, _mm512_castsi512_ps) - -//////////////// Value reordering /////////////// - -/* Expand */ -#define OPENCV_HAL_IMPL_AVX512_EXPAND(_Tpvec, _Tpwvec, _Tp, intrin) \ - inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ - { \ - b0.val = intrin(_v512_extract_low(a.val)); \ - b1.val = intrin(_v512_extract_high(a.val)); \ - } \ - inline _Tpwvec v_expand_low(const _Tpvec& a) \ - { return _Tpwvec(intrin(_v512_extract_low(a.val))); } \ - inline _Tpwvec v_expand_high(const _Tpvec& a) \ - { return _Tpwvec(intrin(_v512_extract_high(a.val))); } \ - inline _Tpwvec v512_load_expand(const _Tp* ptr) \ - { \ - __m256i a = _mm256_loadu_si256((const __m256i*)ptr); \ - return _Tpwvec(intrin(a)); \ - } - -OPENCV_HAL_IMPL_AVX512_EXPAND(v_uint8x64, v_uint16x32, uchar, _mm512_cvtepu8_epi16) -OPENCV_HAL_IMPL_AVX512_EXPAND(v_int8x64, v_int16x32, schar, _mm512_cvtepi8_epi16) -OPENCV_HAL_IMPL_AVX512_EXPAND(v_uint16x32, v_uint32x16, ushort, _mm512_cvtepu16_epi32) -OPENCV_HAL_IMPL_AVX512_EXPAND(v_int16x32, v_int32x16, short, _mm512_cvtepi16_epi32) -OPENCV_HAL_IMPL_AVX512_EXPAND(v_uint32x16, v_uint64x8, unsigned, _mm512_cvtepu32_epi64) -OPENCV_HAL_IMPL_AVX512_EXPAND(v_int32x16, v_int64x8, int, _mm512_cvtepi32_epi64) - -#define OPENCV_HAL_IMPL_AVX512_EXPAND_Q(_Tpvec, _Tp, intrin) \ - inline _Tpvec v512_load_expand_q(const _Tp* ptr) \ - { \ - __m128i a = _mm_loadu_si128((const __m128i*)ptr); \ - return _Tpvec(intrin(a)); \ - } - -OPENCV_HAL_IMPL_AVX512_EXPAND_Q(v_uint32x16, uchar, _mm512_cvtepu8_epi32) -OPENCV_HAL_IMPL_AVX512_EXPAND_Q(v_int32x16, schar, _mm512_cvtepi8_epi32) - -/* pack */ -// 16 -inline v_int8x64 v_pack(const v_int16x32& a, const v_int16x32& b) -{ return v_int8x64(_mm512_permutexvar_epi64(_v512_set_epu64(7, 5, 3, 1, 6, 4, 2, 0), _mm512_packs_epi16(a.val, b.val))); } - -inline v_uint8x64 v_pack(const v_uint16x32& a, const v_uint16x32& b) -{ - const __m512i t = _mm512_set1_epi16(255); - return v_uint8x64(_v512_combine(_mm512_cvtepi16_epi8(_mm512_min_epu16(a.val, t)), _mm512_cvtepi16_epi8(_mm512_min_epu16(b.val, t)))); -} - -inline v_uint8x64 v_pack_u(const v_int16x32& a, const v_int16x32& b) -{ - return v_uint8x64(_mm512_permutexvar_epi64(_v512_set_epu64(7, 5, 3, 1, 6, 4, 2, 0), _mm512_packus_epi16(a.val, b.val))); -} - -inline void v_pack_store(schar* ptr, const v_int16x32& a) -{ v_store_low(ptr, v_pack(a, a)); } - -inline void v_pack_store(uchar* ptr, const v_uint16x32& a) -{ - const __m512i m = _mm512_set1_epi16(255); - _mm256_storeu_si256((__m256i*)ptr, _mm512_cvtepi16_epi8(_mm512_min_epu16(a.val, m))); -} - -inline void v_pack_u_store(uchar* ptr, const v_int16x32& a) -{ v_store_low(ptr, v_pack_u(a, a)); } - -template inline -v_uint8x64 v_rshr_pack(const v_uint16x32& a, const v_uint16x32& b) -{ - // we assume that n > 0, and so the shifted 16-bit values can be treated as signed numbers. - v_uint16x32 delta = v512_setall_u16((short)(1 << (n-1))); - return v_pack_u(v_reinterpret_as_s16(v_shr(v_add(a, delta), n)), - v_reinterpret_as_s16(v_shr(v_add(b, delta), n))); -} - -template inline -void v_rshr_pack_store(uchar* ptr, const v_uint16x32& a) -{ - v_uint16x32 delta = v512_setall_u16((short)(1 << (n-1))); - v_pack_u_store(ptr, v_reinterpret_as_s16(v_shr(v_add(a, delta), n))); -} - -template inline -v_uint8x64 v_rshr_pack_u(const v_int16x32& a, const v_int16x32& b) -{ - v_int16x32 delta = v512_setall_s16((short)(1 << (n-1))); - return v_pack_u(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); -} - -template inline -void v_rshr_pack_u_store(uchar* ptr, const v_int16x32& a) -{ - v_int16x32 delta = v512_setall_s16((short)(1 << (n-1))); - v_pack_u_store(ptr, v_shr(v_add(a, delta), n)); -} - -template inline -v_int8x64 v_rshr_pack(const v_int16x32& a, const v_int16x32& b) -{ - v_int16x32 delta = v512_setall_s16((short)(1 << (n-1))); - return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); -} - -template inline -void v_rshr_pack_store(schar* ptr, const v_int16x32& a) -{ - v_int16x32 delta = v512_setall_s16((short)(1 << (n-1))); - v_pack_store(ptr, v_shr(v_add(a, delta), n)); -} - -// 32 -inline v_int16x32 v_pack(const v_int32x16& a, const v_int32x16& b) -{ return v_int16x32(_mm512_permutexvar_epi64(_v512_set_epu64(7, 5, 3, 1, 6, 4, 2, 0), _mm512_packs_epi32(a.val, b.val))); } - -inline v_uint16x32 v_pack(const v_uint32x16& a, const v_uint32x16& b) -{ - const __m512i m = _mm512_set1_epi32(65535); - return v_uint16x32(_v512_combine(_mm512_cvtepi32_epi16(_mm512_min_epu32(a.val, m)), _mm512_cvtepi32_epi16(_mm512_min_epu32(b.val, m)))); -} - -inline v_uint16x32 v_pack_u(const v_int32x16& a, const v_int32x16& b) -{ return v_uint16x32(_mm512_permutexvar_epi64(_v512_set_epu64(7, 5, 3, 1, 6, 4, 2, 0), _mm512_packus_epi32(a.val, b.val))); } - -inline void v_pack_store(short* ptr, const v_int32x16& a) -{ v_store_low(ptr, v_pack(a, a)); } - -inline void v_pack_store(ushort* ptr, const v_uint32x16& a) -{ - const __m512i m = _mm512_set1_epi32(65535); - _mm256_storeu_si256((__m256i*)ptr, _mm512_cvtepi32_epi16(_mm512_min_epu32(a.val, m))); -} - -inline void v_pack_u_store(ushort* ptr, const v_int32x16& a) -{ v_store_low(ptr, v_pack_u(a, a)); } - - -template inline -v_uint16x32 v_rshr_pack(const v_uint32x16& a, const v_uint32x16& b) -{ - v_uint32x16 delta = v512_setall_u32(1 << (n-1)); - return v_pack_u(v_reinterpret_as_s32(v_shr(v_add(a, delta), n)), - v_reinterpret_as_s32(v_shr(v_add(b, delta), n))); -} - -template inline -void v_rshr_pack_store(ushort* ptr, const v_uint32x16& a) -{ - v_uint32x16 delta = v512_setall_u32(1 << (n-1)); - v_pack_u_store(ptr, v_reinterpret_as_s32(v_shr(v_add(a, delta), n))); -} - -template inline -v_uint16x32 v_rshr_pack_u(const v_int32x16& a, const v_int32x16& b) -{ - v_int32x16 delta = v512_setall_s32(1 << (n-1)); - return v_pack_u(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); -} - -template inline -void v_rshr_pack_u_store(ushort* ptr, const v_int32x16& a) -{ - v_int32x16 delta = v512_setall_s32(1 << (n-1)); - v_pack_u_store(ptr, v_shr(v_add(a, delta), n)); -} - -template inline -v_int16x32 v_rshr_pack(const v_int32x16& a, const v_int32x16& b) -{ - v_int32x16 delta = v512_setall_s32(1 << (n-1)); - return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); -} - -template inline -void v_rshr_pack_store(short* ptr, const v_int32x16& a) -{ - v_int32x16 delta = v512_setall_s32(1 << (n-1)); - v_pack_store(ptr, v_shr(v_add(a, delta), n)); -} - -// 64 -// Non-saturating pack -inline v_uint32x16 v_pack(const v_uint64x8& a, const v_uint64x8& b) -{ return v_uint32x16(_v512_combine(_mm512_cvtepi64_epi32(a.val), _mm512_cvtepi64_epi32(b.val))); } - -inline v_int32x16 v_pack(const v_int64x8& a, const v_int64x8& b) -{ return v_reinterpret_as_s32(v_pack(v_reinterpret_as_u64(a), v_reinterpret_as_u64(b))); } - -inline void v_pack_store(unsigned* ptr, const v_uint64x8& a) -{ _mm256_storeu_si256((__m256i*)ptr, _mm512_cvtepi64_epi32(a.val)); } - -inline void v_pack_store(int* ptr, const v_int64x8& b) -{ v_pack_store((unsigned*)ptr, v_reinterpret_as_u64(b)); } - -template inline -v_uint32x16 v_rshr_pack(const v_uint64x8& a, const v_uint64x8& b) -{ - v_uint64x8 delta = v512_setall_u64((uint64)1 << (n-1)); - return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); -} - -template inline -void v_rshr_pack_store(unsigned* ptr, const v_uint64x8& a) -{ - v_uint64x8 delta = v512_setall_u64((uint64)1 << (n-1)); - v_pack_store(ptr, v_shr(v_add(a, delta), n)); -} - -template inline -v_int32x16 v_rshr_pack(const v_int64x8& a, const v_int64x8& b) -{ - v_int64x8 delta = v512_setall_s64((int64)1 << (n-1)); - return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); -} - -template inline -void v_rshr_pack_store(int* ptr, const v_int64x8& a) -{ - v_int64x8 delta = v512_setall_s64((int64)1 << (n-1)); - v_pack_store(ptr, v_shr(v_add(a, delta), n)); -} - -// pack boolean -inline v_uint8x64 v_pack_b(const v_uint16x32& a, const v_uint16x32& b) -{ return v_uint8x64(_mm512_permutexvar_epi64(_v512_set_epu64(7, 5, 3, 1, 6, 4, 2, 0), _mm512_packs_epi16(a.val, b.val))); } - -inline v_uint8x64 v_pack_b(const v_uint32x16& a, const v_uint32x16& b, - const v_uint32x16& c, const v_uint32x16& d) -{ - __m512i ab = _mm512_packs_epi32(a.val, b.val); - __m512i cd = _mm512_packs_epi32(c.val, d.val); - - return v_uint8x64(_mm512_permutexvar_epi32(_v512_set_epu32(15, 11, 7, 3, 14, 10, 6, 2, 13, 9, 5, 1, 12, 8, 4, 0), _mm512_packs_epi16(ab, cd))); -} - -inline v_uint8x64 v_pack_b(const v_uint64x8& a, const v_uint64x8& b, const v_uint64x8& c, - const v_uint64x8& d, const v_uint64x8& e, const v_uint64x8& f, - const v_uint64x8& g, const v_uint64x8& h) -{ - __m512i ab = _mm512_packs_epi32(a.val, b.val); - __m512i cd = _mm512_packs_epi32(c.val, d.val); - __m512i ef = _mm512_packs_epi32(e.val, f.val); - __m512i gh = _mm512_packs_epi32(g.val, h.val); - - __m512i abcd = _mm512_packs_epi32(ab, cd); - __m512i efgh = _mm512_packs_epi32(ef, gh); - - return v_uint8x64(_mm512_permutexvar_epi16(_v512_set_epu16(31, 23, 15, 7, 30, 22, 14, 6, 29, 21, 13, 5, 28, 20, 12, 4, - 27, 19, 11, 3, 26, 18, 10, 2, 25, 17, 9, 1, 24, 16, 8, 0), _mm512_packs_epi16(abcd, efgh))); -} - -/* Recombine */ -// its up there with load and store operations - -/* Extract */ -#define OPENCV_HAL_IMPL_AVX512_EXTRACT(_Tpvec) \ - template \ - inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \ - { return v_rotate_right(a, b); } - -OPENCV_HAL_IMPL_AVX512_EXTRACT(v_uint8x64) -OPENCV_HAL_IMPL_AVX512_EXTRACT(v_int8x64) -OPENCV_HAL_IMPL_AVX512_EXTRACT(v_uint16x32) -OPENCV_HAL_IMPL_AVX512_EXTRACT(v_int16x32) -OPENCV_HAL_IMPL_AVX512_EXTRACT(v_uint32x16) -OPENCV_HAL_IMPL_AVX512_EXTRACT(v_int32x16) -OPENCV_HAL_IMPL_AVX512_EXTRACT(v_uint64x8) -OPENCV_HAL_IMPL_AVX512_EXTRACT(v_int64x8) -OPENCV_HAL_IMPL_AVX512_EXTRACT(v_float32x16) -OPENCV_HAL_IMPL_AVX512_EXTRACT(v_float64x8) - -#define OPENCV_HAL_IMPL_AVX512_EXTRACT_N(_Tpvec, _Tp) \ -template inline _Tp v_extract_n(_Tpvec v) { return v_rotate_right(v).get0(); } - -OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_uint8x64, uchar) -OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_int8x64, schar) -OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_uint16x32, ushort) -OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_int16x32, short) -OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_uint32x16, uint) -OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_int32x16, int) -OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_uint64x8, uint64) -OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_int64x8, int64) -OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_float32x16, float) -OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_float64x8, double) - -template -inline v_uint32x16 v_broadcast_element(v_uint32x16 a) -{ - static const __m512i perm = _mm512_set1_epi32((char)i); - return v_uint32x16(_mm512_permutexvar_epi32(perm, a.val)); -} - -template -inline v_int32x16 v_broadcast_element(const v_int32x16 &a) -{ return v_reinterpret_as_s32(v_broadcast_element(v_reinterpret_as_u32(a))); } - -template -inline v_float32x16 v_broadcast_element(const v_float32x16 &a) -{ return v_reinterpret_as_f32(v_broadcast_element(v_reinterpret_as_u32(a))); } - - -///////////////////// load deinterleave ///////////////////////////// - -inline void v_load_deinterleave( const uchar* ptr, v_uint8x64& a, v_uint8x64& b ) -{ - __m512i ab0 = _mm512_loadu_si512((const __m512i*)ptr); - __m512i ab1 = _mm512_loadu_si512((const __m512i*)(ptr + 64)); -#if CV_AVX_512VBMI - __m512i mask0 = _v512_set_epu8(126, 124, 122, 120, 118, 116, 114, 112, 110, 108, 106, 104, 102, 100, 98, 96, - 94, 92, 90, 88, 86, 84, 82, 80, 78, 76, 74, 72, 70, 68, 66, 64, - 62, 60, 58, 56, 54, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32, - 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); - __m512i mask1 = _v512_set_epu8(127, 125, 123, 121, 119, 117, 115, 113, 111, 109, 107, 105, 103, 101, 99, 97, - 95, 93, 91, 89, 87, 85, 83, 81, 79, 77, 75, 73, 71, 69, 67, 65, - 63, 61, 59, 57, 55, 53, 51, 49, 47, 45, 43, 41, 39, 37, 35, 33, - 31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); - a = v_uint8x64(_mm512_permutex2var_epi8(ab0, mask0, ab1)); - b = v_uint8x64(_mm512_permutex2var_epi8(ab0, mask1, ab1)); -#else - __m512i mask0 = _mm512_set4_epi32(0x0f0d0b09, 0x07050301, 0x0e0c0a08, 0x06040200); - __m512i a0b0 = _mm512_shuffle_epi8(ab0, mask0); - __m512i a1b1 = _mm512_shuffle_epi8(ab1, mask0); - __m512i mask1 = _v512_set_epu64(14, 12, 10, 8, 6, 4, 2, 0); - __m512i mask2 = _v512_set_epu64(15, 13, 11, 9, 7, 5, 3, 1); - a = v_uint8x64(_mm512_permutex2var_epi64(a0b0, mask1, a1b1)); - b = v_uint8x64(_mm512_permutex2var_epi64(a0b0, mask2, a1b1)); -#endif -} - -inline void v_load_deinterleave( const ushort* ptr, v_uint16x32& a, v_uint16x32& b ) -{ - __m512i ab0 = _mm512_loadu_si512((const __m512i*)ptr); - __m512i ab1 = _mm512_loadu_si512((const __m512i*)(ptr + 32)); - __m512i mask0 = _v512_set_epu16(62, 60, 58, 56, 54, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32, - 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); - __m512i mask1 = _v512_set_epu16(63, 61, 59, 57, 55, 53, 51, 49, 47, 45, 43, 41, 39, 37, 35, 33, - 31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); - a = v_uint16x32(_mm512_permutex2var_epi16(ab0, mask0, ab1)); - b = v_uint16x32(_mm512_permutex2var_epi16(ab0, mask1, ab1)); -} - -inline void v_load_deinterleave( const unsigned* ptr, v_uint32x16& a, v_uint32x16& b ) -{ - __m512i ab0 = _mm512_loadu_si512((const __m512i*)ptr); - __m512i ab1 = _mm512_loadu_si512((const __m512i*)(ptr + 16)); - __m512i mask0 = _v512_set_epu32(30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); - __m512i mask1 = _v512_set_epu32(31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); - a = v_uint32x16(_mm512_permutex2var_epi32(ab0, mask0, ab1)); - b = v_uint32x16(_mm512_permutex2var_epi32(ab0, mask1, ab1)); -} - -inline void v_load_deinterleave( const uint64* ptr, v_uint64x8& a, v_uint64x8& b ) -{ - __m512i ab0 = _mm512_loadu_si512((const __m512i*)ptr); - __m512i ab1 = _mm512_loadu_si512((const __m512i*)(ptr + 8)); - __m512i mask0 = _v512_set_epu64(14, 12, 10, 8, 6, 4, 2, 0); - __m512i mask1 = _v512_set_epu64(15, 13, 11, 9, 7, 5, 3, 1); - a = v_uint64x8(_mm512_permutex2var_epi64(ab0, mask0, ab1)); - b = v_uint64x8(_mm512_permutex2var_epi64(ab0, mask1, ab1)); -} - -inline void v_load_deinterleave( const uchar* ptr, v_uint8x64& a, v_uint8x64& b, v_uint8x64& c ) -{ - __m512i bgr0 = _mm512_loadu_si512((const __m512i*)ptr); - __m512i bgr1 = _mm512_loadu_si512((const __m512i*)(ptr + 64)); - __m512i bgr2 = _mm512_loadu_si512((const __m512i*)(ptr + 128)); - -#if CV_AVX_512VBMI2 - __m512i mask0 = _v512_set_epu8(126, 123, 120, 117, 114, 111, 108, 105, 102, 99, 96, 93, 90, 87, 84, 81, - 78, 75, 72, 69, 66, 63, 60, 57, 54, 51, 48, 45, 42, 39, 36, 33, - 30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 0, 62, 59, 56, 53, 50, - 47, 44, 41, 38, 35, 32, 29, 26, 23, 20, 17, 14, 11, 8, 5, 2); - __m512i r0b01 = _mm512_permutex2var_epi8(bgr0, mask0, bgr1); - __m512i b1g12 = _mm512_permutex2var_epi8(bgr1, mask0, bgr2); - __m512i r12b2 = _mm512_permutex2var_epi8(bgr1, - _v512_set_epu8(125, 122, 119, 116, 113, 110, 107, 104, 101, 98, 95, 92, 89, 86, 83, 80, - 77, 74, 71, 68, 65, 127, 124, 121, 118, 115, 112, 109, 106, 103, 100, 97, - 94, 91, 88, 85, 82, 79, 76, 73, 70, 67, 64, 61, 58, 55, 52, 49, - 46, 43, 40, 37, 34, 31, 28, 25, 22, 19, 16, 13, 10, 7, 4, 1), bgr2); - a = v_uint8x64(_mm512_mask_compress_epi8(r12b2, 0xffffffffffe00000, r0b01)); - b = v_uint8x64(_mm512_mask_compress_epi8(b1g12, 0x2492492492492492, bgr0)); - c = v_uint8x64(_mm512_mask_expand_epi8(r0b01, 0xffffffffffe00000, r12b2)); -#elif CV_AVX_512VBMI - __m512i b0g0b1 = _mm512_mask_blend_epi8(0xb6db6db6db6db6db, bgr1, bgr0); - __m512i g1r1g2 = _mm512_mask_blend_epi8(0xb6db6db6db6db6db, bgr2, bgr1); - __m512i r2b2r0 = _mm512_mask_blend_epi8(0xb6db6db6db6db6db, bgr0, bgr2); - a = v_uint8x64(_mm512_permutex2var_epi8(b0g0b1, _v512_set_epu8(125, 122, 119, 116, 113, 110, 107, 104, 101, 98, 95, 92, 89, 86, 83, 80, - 77, 74, 71, 68, 65, 63, 61, 60, 58, 57, 55, 54, 52, 51, 49, 48, - 46, 45, 43, 42, 40, 39, 37, 36, 34, 33, 31, 30, 28, 27, 25, 24, - 23, 21, 20, 18, 17, 15, 14, 12, 11, 9, 8, 6, 5, 3, 2, 0), bgr2)); - b = v_uint8x64(_mm512_permutex2var_epi8(g1r1g2, _v512_set_epu8( 63, 61, 60, 58, 57, 55, 54, 52, 51, 49, 48, 46, 45, 43, 42, 40, - 39, 37, 36, 34, 33, 31, 30, 28, 27, 25, 24, 23, 21, 20, 18, 17, - 15, 14, 12, 11, 9, 8, 6, 5, 3, 2, 0, 126, 123, 120, 117, 114, - 111, 108, 105, 102, 99, 96, 93, 90, 87, 84, 81, 78, 75, 72, 69, 66), bgr0)); - c = v_uint8x64(_mm512_permutex2var_epi8(r2b2r0, _v512_set_epu8( 63, 60, 57, 54, 51, 48, 45, 42, 39, 36, 33, 30, 27, 24, 21, 18, - 15, 12, 9, 6, 3, 0, 125, 122, 119, 116, 113, 110, 107, 104, 101, 98, - 95, 92, 89, 86, 83, 80, 77, 74, 71, 68, 65, 62, 59, 56, 53, 50, - 47, 44, 41, 38, 35, 32, 29, 26, 23, 20, 17, 14, 11, 8, 5, 2), bgr1)); -#else - __m512i mask0 = _v512_set_epu16(61, 58, 55, 52, 49, 46, 43, 40, 37, 34, 63, 60, 57, 54, 51, 48, - 45, 42, 39, 36, 33, 30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 0); - __m512i b01g1 = _mm512_permutex2var_epi16(bgr0, mask0, bgr1); - __m512i r12b2 = _mm512_permutex2var_epi16(bgr1, mask0, bgr2); - __m512i g20r0 = _mm512_permutex2var_epi16(bgr2, mask0, bgr0); - - __m512i b0g0 = _mm512_mask_blend_epi32(0xf800, b01g1, r12b2); - __m512i r0b1 = _mm512_permutex2var_epi16(bgr1, _v512_set_epu16(42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 29, 26, 23, 20, 17, - 14, 11, 8, 5, 2, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43), g20r0); - __m512i g1r1 = _mm512_alignr_epi32(r12b2, g20r0, 11); - a = v_uint8x64(_mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, b0g0, r0b1)); - c = v_uint8x64(_mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, r0b1, g1r1)); - b = v_uint8x64(_mm512_shuffle_epi8(_mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, g1r1, b0g0), _mm512_set4_epi32(0x0e0f0c0d, 0x0a0b0809, 0x06070405, 0x02030001))); -#endif -} - -inline void v_load_deinterleave( const ushort* ptr, v_uint16x32& a, v_uint16x32& b, v_uint16x32& c ) -{ - __m512i bgr0 = _mm512_loadu_si512((const __m512i*)ptr); - __m512i bgr1 = _mm512_loadu_si512((const __m512i*)(ptr + 32)); - __m512i bgr2 = _mm512_loadu_si512((const __m512i*)(ptr + 64)); - - __m512i mask0 = _v512_set_epu16(61, 58, 55, 52, 49, 46, 43, 40, 37, 34, 63, 60, 57, 54, 51, 48, - 45, 42, 39, 36, 33, 30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 0); - __m512i b01g1 = _mm512_permutex2var_epi16(bgr0, mask0, bgr1); - __m512i r12b2 = _mm512_permutex2var_epi16(bgr1, mask0, bgr2); - __m512i g20r0 = _mm512_permutex2var_epi16(bgr2, mask0, bgr0); - - a = v_uint16x32(_mm512_mask_blend_epi32(0xf800, b01g1, r12b2)); - b = v_uint16x32(_mm512_permutex2var_epi16(bgr1, _v512_set_epu16(42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 29, 26, 23, 20, 17, - 14, 11, 8, 5, 2, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43), g20r0)); - c = v_uint16x32(_mm512_alignr_epi32(r12b2, g20r0, 11)); -} - -inline void v_load_deinterleave( const unsigned* ptr, v_uint32x16& a, v_uint32x16& b, v_uint32x16& c ) -{ - __m512i bgr0 = _mm512_loadu_si512((const __m512i*)ptr); - __m512i bgr1 = _mm512_loadu_si512((const __m512i*)(ptr + 16)); - __m512i bgr2 = _mm512_loadu_si512((const __m512i*)(ptr + 32)); - - __m512i mask0 = _v512_set_epu32(29, 26, 23, 20, 17, 30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 0); - __m512i b01r1 = _mm512_permutex2var_epi32(bgr0, mask0, bgr1); - __m512i g12b2 = _mm512_permutex2var_epi32(bgr1, mask0, bgr2); - __m512i r20g0 = _mm512_permutex2var_epi32(bgr2, mask0, bgr0); - - a = v_uint32x16(_mm512_mask_blend_epi32(0xf800, b01r1, g12b2)); - b = v_uint32x16(_mm512_alignr_epi32(g12b2, r20g0, 11)); - c = v_uint32x16(_mm512_permutex2var_epi32(bgr1, _v512_set_epu32(21, 20, 19, 18, 17, 16, 13, 10, 7, 4, 1, 26, 25, 24, 23, 22), r20g0)); -} - -inline void v_load_deinterleave( const uint64* ptr, v_uint64x8& a, v_uint64x8& b, v_uint64x8& c ) -{ - __m512i bgr0 = _mm512_loadu_si512((const __m512i*)ptr); - __m512i bgr1 = _mm512_loadu_si512((const __m512i*)(ptr + 8)); - __m512i bgr2 = _mm512_loadu_si512((const __m512i*)(ptr + 16)); - - __m512i mask0 = _v512_set_epu64(13, 10, 15, 12, 9, 6, 3, 0); - __m512i b01g1 = _mm512_permutex2var_epi64(bgr0, mask0, bgr1); - __m512i r12b2 = _mm512_permutex2var_epi64(bgr1, mask0, bgr2); - __m512i g20r0 = _mm512_permutex2var_epi64(bgr2, mask0, bgr0); - - a = v_uint64x8(_mm512_mask_blend_epi64(0xc0, b01g1, r12b2)); - c = v_uint64x8(_mm512_alignr_epi64(r12b2, g20r0, 6)); - b = v_uint64x8(_mm512_permutex2var_epi64(bgr1, _v512_set_epu64(10, 9, 8, 5, 2, 13, 12, 11), g20r0)); -} - -inline void v_load_deinterleave( const uchar* ptr, v_uint8x64& a, v_uint8x64& b, v_uint8x64& c, v_uint8x64& d ) -{ - __m512i bgra0 = _mm512_loadu_si512((const __m512i*)ptr); - __m512i bgra1 = _mm512_loadu_si512((const __m512i*)(ptr + 64)); - __m512i bgra2 = _mm512_loadu_si512((const __m512i*)(ptr + 128)); - __m512i bgra3 = _mm512_loadu_si512((const __m512i*)(ptr + 192)); - -#if CV_AVX_512VBMI - __m512i mask0 = _v512_set_epu8(126, 124, 122, 120, 118, 116, 114, 112, 110, 108, 106, 104, 102, 100, 98, 96, - 94, 92, 90, 88, 86, 84, 82, 80, 78, 76, 74, 72, 70, 68, 66, 64, - 62, 60, 58, 56, 54, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32, - 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); - __m512i mask1 = _v512_set_epu8(127, 125, 123, 121, 119, 117, 115, 113, 111, 109, 107, 105, 103, 101, 99, 97, - 95, 93, 91, 89, 87, 85, 83, 81, 79, 77, 75, 73, 71, 69, 67, 65, - 63, 61, 59, 57, 55, 53, 51, 49, 47, 45, 43, 41, 39, 37, 35, 33, - 31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); - - __m512i br01 = _mm512_permutex2var_epi8(bgra0, mask0, bgra1); - __m512i ga01 = _mm512_permutex2var_epi8(bgra0, mask1, bgra1); - __m512i br23 = _mm512_permutex2var_epi8(bgra2, mask0, bgra3); - __m512i ga23 = _mm512_permutex2var_epi8(bgra2, mask1, bgra3); - - a = v_uint8x64(_mm512_permutex2var_epi8(br01, mask0, br23)); - c = v_uint8x64(_mm512_permutex2var_epi8(br01, mask1, br23)); - b = v_uint8x64(_mm512_permutex2var_epi8(ga01, mask0, ga23)); - d = v_uint8x64(_mm512_permutex2var_epi8(ga01, mask1, ga23)); -#else - __m512i mask = _mm512_set4_epi32(0x0f0b0703, 0x0e0a0602, 0x0d090501, 0x0c080400); - __m512i b0g0r0a0 = _mm512_shuffle_epi8(bgra0, mask); - __m512i b1g1r1a1 = _mm512_shuffle_epi8(bgra1, mask); - __m512i b2g2r2a2 = _mm512_shuffle_epi8(bgra2, mask); - __m512i b3g3r3a3 = _mm512_shuffle_epi8(bgra3, mask); - - __m512i mask0 = _v512_set_epu32(30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); - __m512i mask1 = _v512_set_epu32(31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); - - __m512i br01 = _mm512_permutex2var_epi32(b0g0r0a0, mask0, b1g1r1a1); - __m512i ga01 = _mm512_permutex2var_epi32(b0g0r0a0, mask1, b1g1r1a1); - __m512i br23 = _mm512_permutex2var_epi32(b2g2r2a2, mask0, b3g3r3a3); - __m512i ga23 = _mm512_permutex2var_epi32(b2g2r2a2, mask1, b3g3r3a3); - - a = v_uint8x64(_mm512_permutex2var_epi32(br01, mask0, br23)); - c = v_uint8x64(_mm512_permutex2var_epi32(br01, mask1, br23)); - b = v_uint8x64(_mm512_permutex2var_epi32(ga01, mask0, ga23)); - d = v_uint8x64(_mm512_permutex2var_epi32(ga01, mask1, ga23)); -#endif -} - -inline void v_load_deinterleave( const ushort* ptr, v_uint16x32& a, v_uint16x32& b, v_uint16x32& c, v_uint16x32& d ) -{ - __m512i bgra0 = _mm512_loadu_si512((const __m512i*)ptr); - __m512i bgra1 = _mm512_loadu_si512((const __m512i*)(ptr + 32)); - __m512i bgra2 = _mm512_loadu_si512((const __m512i*)(ptr + 64)); - __m512i bgra3 = _mm512_loadu_si512((const __m512i*)(ptr + 96)); - - __m512i mask0 = _v512_set_epu16(62, 60, 58, 56, 54, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32, - 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); - __m512i mask1 = _v512_set_epu16(63, 61, 59, 57, 55, 53, 51, 49, 47, 45, 43, 41, 39, 37, 35, 33, - 31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); - - __m512i br01 = _mm512_permutex2var_epi16(bgra0, mask0, bgra1); - __m512i ga01 = _mm512_permutex2var_epi16(bgra0, mask1, bgra1); - __m512i br23 = _mm512_permutex2var_epi16(bgra2, mask0, bgra3); - __m512i ga23 = _mm512_permutex2var_epi16(bgra2, mask1, bgra3); - - a = v_uint16x32(_mm512_permutex2var_epi16(br01, mask0, br23)); - c = v_uint16x32(_mm512_permutex2var_epi16(br01, mask1, br23)); - b = v_uint16x32(_mm512_permutex2var_epi16(ga01, mask0, ga23)); - d = v_uint16x32(_mm512_permutex2var_epi16(ga01, mask1, ga23)); -} - -inline void v_load_deinterleave( const unsigned* ptr, v_uint32x16& a, v_uint32x16& b, v_uint32x16& c, v_uint32x16& d ) -{ - __m512i bgra0 = _mm512_loadu_si512((const __m512i*)ptr); - __m512i bgra1 = _mm512_loadu_si512((const __m512i*)(ptr + 16)); - __m512i bgra2 = _mm512_loadu_si512((const __m512i*)(ptr + 32)); - __m512i bgra3 = _mm512_loadu_si512((const __m512i*)(ptr + 48)); - - __m512i mask0 = _v512_set_epu32(30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); - __m512i mask1 = _v512_set_epu32(31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); - - __m512i br01 = _mm512_permutex2var_epi32(bgra0, mask0, bgra1); - __m512i ga01 = _mm512_permutex2var_epi32(bgra0, mask1, bgra1); - __m512i br23 = _mm512_permutex2var_epi32(bgra2, mask0, bgra3); - __m512i ga23 = _mm512_permutex2var_epi32(bgra2, mask1, bgra3); - - a = v_uint32x16(_mm512_permutex2var_epi32(br01, mask0, br23)); - c = v_uint32x16(_mm512_permutex2var_epi32(br01, mask1, br23)); - b = v_uint32x16(_mm512_permutex2var_epi32(ga01, mask0, ga23)); - d = v_uint32x16(_mm512_permutex2var_epi32(ga01, mask1, ga23)); -} - -inline void v_load_deinterleave( const uint64* ptr, v_uint64x8& a, v_uint64x8& b, v_uint64x8& c, v_uint64x8& d ) -{ - __m512i bgra0 = _mm512_loadu_si512((const __m512i*)ptr); - __m512i bgra1 = _mm512_loadu_si512((const __m512i*)(ptr + 8)); - __m512i bgra2 = _mm512_loadu_si512((const __m512i*)(ptr + 16)); - __m512i bgra3 = _mm512_loadu_si512((const __m512i*)(ptr + 24)); - - __m512i mask0 = _v512_set_epu64(14, 12, 10, 8, 6, 4, 2, 0); - __m512i mask1 = _v512_set_epu64(15, 13, 11, 9, 7, 5, 3, 1); - - __m512i br01 = _mm512_permutex2var_epi64(bgra0, mask0, bgra1); - __m512i ga01 = _mm512_permutex2var_epi64(bgra0, mask1, bgra1); - __m512i br23 = _mm512_permutex2var_epi64(bgra2, mask0, bgra3); - __m512i ga23 = _mm512_permutex2var_epi64(bgra2, mask1, bgra3); - - a = v_uint64x8(_mm512_permutex2var_epi64(br01, mask0, br23)); - c = v_uint64x8(_mm512_permutex2var_epi64(br01, mask1, br23)); - b = v_uint64x8(_mm512_permutex2var_epi64(ga01, mask0, ga23)); - d = v_uint64x8(_mm512_permutex2var_epi64(ga01, mask1, ga23)); -} - -///////////////////////////// store interleave ///////////////////////////////////// - -inline void v_store_interleave( uchar* ptr, const v_uint8x64& x, const v_uint8x64& y, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - v_uint8x64 low, high; - v_zip(x, y, low, high); - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm512_stream_si512((__m512i*)ptr, low.val); - _mm512_stream_si512((__m512i*)(ptr + 64), high.val); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm512_store_si512((__m512i*)ptr, low.val); - _mm512_store_si512((__m512i*)(ptr + 64), high.val); - } - else - { - _mm512_storeu_si512((__m512i*)ptr, low.val); - _mm512_storeu_si512((__m512i*)(ptr + 64), high.val); - } -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x32& x, const v_uint16x32& y, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - v_uint16x32 low, high; - v_zip(x, y, low, high); - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm512_stream_si512((__m512i*)ptr, low.val); - _mm512_stream_si512((__m512i*)(ptr + 32), high.val); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm512_store_si512((__m512i*)ptr, low.val); - _mm512_store_si512((__m512i*)(ptr + 32), high.val); - } - else - { - _mm512_storeu_si512((__m512i*)ptr, low.val); - _mm512_storeu_si512((__m512i*)(ptr + 32), high.val); - } -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x16& x, const v_uint32x16& y, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - v_uint32x16 low, high; - v_zip(x, y, low, high); - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm512_stream_si512((__m512i*)ptr, low.val); - _mm512_stream_si512((__m512i*)(ptr + 16), high.val); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm512_store_si512((__m512i*)ptr, low.val); - _mm512_store_si512((__m512i*)(ptr + 16), high.val); - } - else - { - _mm512_storeu_si512((__m512i*)ptr, low.val); - _mm512_storeu_si512((__m512i*)(ptr + 16), high.val); - } -} - -inline void v_store_interleave( uint64* ptr, const v_uint64x8& x, const v_uint64x8& y, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - v_uint64x8 low, high; - v_zip(x, y, low, high); - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm512_stream_si512((__m512i*)ptr, low.val); - _mm512_stream_si512((__m512i*)(ptr + 8), high.val); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm512_store_si512((__m512i*)ptr, low.val); - _mm512_store_si512((__m512i*)(ptr + 8), high.val); - } - else - { - _mm512_storeu_si512((__m512i*)ptr, low.val); - _mm512_storeu_si512((__m512i*)(ptr + 8), high.val); - } -} - -inline void v_store_interleave( uchar* ptr, const v_uint8x64& a, const v_uint8x64& b, const v_uint8x64& c, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ -#if CV_AVX_512VBMI - __m512i mask0 = _v512_set_epu8(127, 84, 20, 126, 83, 19, 125, 82, 18, 124, 81, 17, 123, 80, 16, 122, - 79, 15, 121, 78, 14, 120, 77, 13, 119, 76, 12, 118, 75, 11, 117, 74, - 10, 116, 73, 9, 115, 72, 8, 114, 71, 7, 113, 70, 6, 112, 69, 5, - 111, 68, 4, 110, 67, 3, 109, 66, 2, 108, 65, 1, 107, 64, 0, 106); - __m512i mask1 = _v512_set_epu8( 21, 42, 105, 20, 41, 104, 19, 40, 103, 18, 39, 102, 17, 38, 101, 16, - 37, 100, 15, 36, 99, 14, 35, 98, 13, 34, 97, 12, 33, 96, 11, 32, - 95, 10, 31, 94, 9, 30, 93, 8, 29, 92, 7, 28, 91, 6, 27, 90, - 5, 26, 89, 4, 25, 88, 3, 24, 87, 2, 23, 86, 1, 22, 85, 0); - __m512i mask2 = _v512_set_epu8(106, 127, 63, 105, 126, 62, 104, 125, 61, 103, 124, 60, 102, 123, 59, 101, - 122, 58, 100, 121, 57, 99, 120, 56, 98, 119, 55, 97, 118, 54, 96, 117, - 53, 95, 116, 52, 94, 115, 51, 93, 114, 50, 92, 113, 49, 91, 112, 48, - 90, 111, 47, 89, 110, 46, 88, 109, 45, 87, 108, 44, 86, 107, 43, 85); - __m512i r2g0r0 = _mm512_permutex2var_epi8(b.val, mask0, c.val); - __m512i b0r1b1 = _mm512_permutex2var_epi8(a.val, mask1, c.val); - __m512i g1b2g2 = _mm512_permutex2var_epi8(a.val, mask2, b.val); - - __m512i bgr0 = _mm512_mask_blend_epi8(0x9249249249249249, r2g0r0, b0r1b1); - __m512i bgr1 = _mm512_mask_blend_epi8(0x9249249249249249, b0r1b1, g1b2g2); - __m512i bgr2 = _mm512_mask_blend_epi8(0x9249249249249249, g1b2g2, r2g0r0); -#else - __m512i g1g0 = _mm512_shuffle_epi8(b.val, _mm512_set4_epi32(0x0e0f0c0d, 0x0a0b0809, 0x06070405, 0x02030001)); - __m512i b0g0 = _mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, a.val, g1g0); - __m512i r0b1 = _mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, c.val, a.val); - __m512i g1r1 = _mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, g1g0, c.val); - - __m512i mask0 = _v512_set_epu16(42, 10, 31, 41, 9, 30, 40, 8, 29, 39, 7, 28, 38, 6, 27, 37, - 5, 26, 36, 4, 25, 35, 3, 24, 34, 2, 23, 33, 1, 22, 32, 0); - __m512i mask1 = _v512_set_epu16(21, 52, 41, 20, 51, 40, 19, 50, 39, 18, 49, 38, 17, 48, 37, 16, - 47, 36, 15, 46, 35, 14, 45, 34, 13, 44, 33, 12, 43, 32, 11, 42); - __m512i mask2 = _v512_set_epu16(63, 31, 20, 62, 30, 19, 61, 29, 18, 60, 28, 17, 59, 27, 16, 58, - 26, 15, 57, 25, 14, 56, 24, 13, 55, 23, 12, 54, 22, 11, 53, 21); - __m512i b0g0b2 = _mm512_permutex2var_epi16(b0g0, mask0, r0b1); - __m512i r1b1r0 = _mm512_permutex2var_epi16(b0g0, mask1, g1r1); - __m512i g2r2g1 = _mm512_permutex2var_epi16(r0b1, mask2, g1r1); - - __m512i bgr0 = _mm512_mask_blend_epi16(0x24924924, b0g0b2, r1b1r0); - __m512i bgr1 = _mm512_mask_blend_epi16(0x24924924, r1b1r0, g2r2g1); - __m512i bgr2 = _mm512_mask_blend_epi16(0x24924924, g2r2g1, b0g0b2); -#endif - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm512_stream_si512((__m512i*)ptr, bgr0); - _mm512_stream_si512((__m512i*)(ptr + 64), bgr1); - _mm512_stream_si512((__m512i*)(ptr + 128), bgr2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm512_store_si512((__m512i*)ptr, bgr0); - _mm512_store_si512((__m512i*)(ptr + 64), bgr1); - _mm512_store_si512((__m512i*)(ptr + 128), bgr2); - } - else - { - _mm512_storeu_si512((__m512i*)ptr, bgr0); - _mm512_storeu_si512((__m512i*)(ptr + 64), bgr1); - _mm512_storeu_si512((__m512i*)(ptr + 128), bgr2); - } -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x32& a, const v_uint16x32& b, const v_uint16x32& c, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m512i mask0 = _v512_set_epu16(42, 10, 31, 41, 9, 30, 40, 8, 29, 39, 7, 28, 38, 6, 27, 37, - 5, 26, 36, 4, 25, 35, 3, 24, 34, 2, 23, 33, 1, 22, 32, 0); - __m512i mask1 = _v512_set_epu16(21, 52, 41, 20, 51, 40, 19, 50, 39, 18, 49, 38, 17, 48, 37, 16, - 47, 36, 15, 46, 35, 14, 45, 34, 13, 44, 33, 12, 43, 32, 11, 42); - __m512i mask2 = _v512_set_epu16(63, 31, 20, 62, 30, 19, 61, 29, 18, 60, 28, 17, 59, 27, 16, 58, - 26, 15, 57, 25, 14, 56, 24, 13, 55, 23, 12, 54, 22, 11, 53, 21); - __m512i b0g0b2 = _mm512_permutex2var_epi16(a.val, mask0, b.val); - __m512i r1b1r0 = _mm512_permutex2var_epi16(a.val, mask1, c.val); - __m512i g2r2g1 = _mm512_permutex2var_epi16(b.val, mask2, c.val); - - __m512i bgr0 = _mm512_mask_blend_epi16(0x24924924, b0g0b2, r1b1r0); - __m512i bgr1 = _mm512_mask_blend_epi16(0x24924924, r1b1r0, g2r2g1); - __m512i bgr2 = _mm512_mask_blend_epi16(0x24924924, g2r2g1, b0g0b2); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm512_stream_si512((__m512i*)ptr, bgr0); - _mm512_stream_si512((__m512i*)(ptr + 32), bgr1); - _mm512_stream_si512((__m512i*)(ptr + 64), bgr2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm512_store_si512((__m512i*)ptr, bgr0); - _mm512_store_si512((__m512i*)(ptr + 32), bgr1); - _mm512_store_si512((__m512i*)(ptr + 64), bgr2); - } - else - { - _mm512_storeu_si512((__m512i*)ptr, bgr0); - _mm512_storeu_si512((__m512i*)(ptr + 32), bgr1); - _mm512_storeu_si512((__m512i*)(ptr + 64), bgr2); - } -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x16& a, const v_uint32x16& b, const v_uint32x16& c, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m512i mask0 = _v512_set_epu32(26, 31, 15, 25, 30, 14, 24, 29, 13, 23, 28, 12, 22, 27, 11, 21); - __m512i mask1 = _v512_set_epu32(31, 10, 25, 30, 9, 24, 29, 8, 23, 28, 7, 22, 27, 6, 21, 26); - __m512i g1b2g2 = _mm512_permutex2var_epi32(a.val, mask0, b.val); - __m512i r2r1b1 = _mm512_permutex2var_epi32(a.val, mask1, c.val); - - __m512i bgr0 = _mm512_mask_expand_epi32(_mm512_mask_expand_epi32(_mm512_maskz_expand_epi32(0x9249, a.val), 0x2492, b.val), 0x4924, c.val); - __m512i bgr1 = _mm512_mask_blend_epi32(0x9249, r2r1b1, g1b2g2); - __m512i bgr2 = _mm512_mask_blend_epi32(0x9249, g1b2g2, r2r1b1); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm512_stream_si512((__m512i*)ptr, bgr0); - _mm512_stream_si512((__m512i*)(ptr + 16), bgr1); - _mm512_stream_si512((__m512i*)(ptr + 32), bgr2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm512_store_si512((__m512i*)ptr, bgr0); - _mm512_store_si512((__m512i*)(ptr + 16), bgr1); - _mm512_store_si512((__m512i*)(ptr + 32), bgr2); - } - else - { - _mm512_storeu_si512((__m512i*)ptr, bgr0); - _mm512_storeu_si512((__m512i*)(ptr + 16), bgr1); - _mm512_storeu_si512((__m512i*)(ptr + 32), bgr2); - } -} - -inline void v_store_interleave( uint64* ptr, const v_uint64x8& a, const v_uint64x8& b, const v_uint64x8& c, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m512i mask0 = _v512_set_epu64( 5, 12, 7, 4, 11, 6, 3, 10); - __m512i mask1 = _v512_set_epu64(15, 7, 4, 14, 6, 3, 13, 5); - __m512i r1b1b2 = _mm512_permutex2var_epi64(a.val, mask0, c.val); - __m512i g2r2g1 = _mm512_permutex2var_epi64(b.val, mask1, c.val); - - __m512i bgr0 = _mm512_mask_expand_epi64(_mm512_mask_expand_epi64(_mm512_maskz_expand_epi64(0x49, a.val), 0x92, b.val), 0x24, c.val); - __m512i bgr1 = _mm512_mask_blend_epi64(0xdb, g2r2g1, r1b1b2); - __m512i bgr2 = _mm512_mask_blend_epi64(0xdb, r1b1b2, g2r2g1); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm512_stream_si512((__m512i*)ptr, bgr0); - _mm512_stream_si512((__m512i*)(ptr + 8), bgr1); - _mm512_stream_si512((__m512i*)(ptr + 16), bgr2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm512_store_si512((__m512i*)ptr, bgr0); - _mm512_store_si512((__m512i*)(ptr + 8), bgr1); - _mm512_store_si512((__m512i*)(ptr + 16), bgr2); - } - else - { - _mm512_storeu_si512((__m512i*)ptr, bgr0); - _mm512_storeu_si512((__m512i*)(ptr + 8), bgr1); - _mm512_storeu_si512((__m512i*)(ptr + 16), bgr2); - } -} - -inline void v_store_interleave( uchar* ptr, const v_uint8x64& a, const v_uint8x64& b, - const v_uint8x64& c, const v_uint8x64& d, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - v_uint8x64 br01, br23, ga01, ga23; - v_zip(a, c, br01, br23); - v_zip(b, d, ga01, ga23); - v_uint8x64 bgra0, bgra1, bgra2, bgra3; - v_zip(br01, ga01, bgra0, bgra1); - v_zip(br23, ga23, bgra2, bgra3); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm512_stream_si512((__m512i*)ptr, bgra0.val); - _mm512_stream_si512((__m512i*)(ptr + 64), bgra1.val); - _mm512_stream_si512((__m512i*)(ptr + 128), bgra2.val); - _mm512_stream_si512((__m512i*)(ptr + 192), bgra3.val); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm512_store_si512((__m512i*)ptr, bgra0.val); - _mm512_store_si512((__m512i*)(ptr + 64), bgra1.val); - _mm512_store_si512((__m512i*)(ptr + 128), bgra2.val); - _mm512_store_si512((__m512i*)(ptr + 192), bgra3.val); - } - else - { - _mm512_storeu_si512((__m512i*)ptr, bgra0.val); - _mm512_storeu_si512((__m512i*)(ptr + 64), bgra1.val); - _mm512_storeu_si512((__m512i*)(ptr + 128), bgra2.val); - _mm512_storeu_si512((__m512i*)(ptr + 192), bgra3.val); - } -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x32& a, const v_uint16x32& b, - const v_uint16x32& c, const v_uint16x32& d, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - v_uint16x32 br01, br23, ga01, ga23; - v_zip(a, c, br01, br23); - v_zip(b, d, ga01, ga23); - v_uint16x32 bgra0, bgra1, bgra2, bgra3; - v_zip(br01, ga01, bgra0, bgra1); - v_zip(br23, ga23, bgra2, bgra3); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm512_stream_si512((__m512i*)ptr, bgra0.val); - _mm512_stream_si512((__m512i*)(ptr + 32), bgra1.val); - _mm512_stream_si512((__m512i*)(ptr + 64), bgra2.val); - _mm512_stream_si512((__m512i*)(ptr + 96), bgra3.val); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm512_store_si512((__m512i*)ptr, bgra0.val); - _mm512_store_si512((__m512i*)(ptr + 32), bgra1.val); - _mm512_store_si512((__m512i*)(ptr + 64), bgra2.val); - _mm512_store_si512((__m512i*)(ptr + 96), bgra3.val); - } - else - { - _mm512_storeu_si512((__m512i*)ptr, bgra0.val); - _mm512_storeu_si512((__m512i*)(ptr + 32), bgra1.val); - _mm512_storeu_si512((__m512i*)(ptr + 64), bgra2.val); - _mm512_storeu_si512((__m512i*)(ptr + 96), bgra3.val); - } -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x16& a, const v_uint32x16& b, - const v_uint32x16& c, const v_uint32x16& d, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - v_uint32x16 br01, br23, ga01, ga23; - v_zip(a, c, br01, br23); - v_zip(b, d, ga01, ga23); - v_uint32x16 bgra0, bgra1, bgra2, bgra3; - v_zip(br01, ga01, bgra0, bgra1); - v_zip(br23, ga23, bgra2, bgra3); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm512_stream_si512((__m512i*)ptr, bgra0.val); - _mm512_stream_si512((__m512i*)(ptr + 16), bgra1.val); - _mm512_stream_si512((__m512i*)(ptr + 32), bgra2.val); - _mm512_stream_si512((__m512i*)(ptr + 48), bgra3.val); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm512_store_si512((__m512i*)ptr, bgra0.val); - _mm512_store_si512((__m512i*)(ptr + 16), bgra1.val); - _mm512_store_si512((__m512i*)(ptr + 32), bgra2.val); - _mm512_store_si512((__m512i*)(ptr + 48), bgra3.val); - } - else - { - _mm512_storeu_si512((__m512i*)ptr, bgra0.val); - _mm512_storeu_si512((__m512i*)(ptr + 16), bgra1.val); - _mm512_storeu_si512((__m512i*)(ptr + 32), bgra2.val); - _mm512_storeu_si512((__m512i*)(ptr + 48), bgra3.val); - } -} - -inline void v_store_interleave( uint64* ptr, const v_uint64x8& a, const v_uint64x8& b, - const v_uint64x8& c, const v_uint64x8& d, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - v_uint64x8 br01, br23, ga01, ga23; - v_zip(a, c, br01, br23); - v_zip(b, d, ga01, ga23); - v_uint64x8 bgra0, bgra1, bgra2, bgra3; - v_zip(br01, ga01, bgra0, bgra1); - v_zip(br23, ga23, bgra2, bgra3); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm512_stream_si512((__m512i*)ptr, bgra0.val); - _mm512_stream_si512((__m512i*)(ptr + 8), bgra1.val); - _mm512_stream_si512((__m512i*)(ptr + 16), bgra2.val); - _mm512_stream_si512((__m512i*)(ptr + 24), bgra3.val); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm512_store_si512((__m512i*)ptr, bgra0.val); - _mm512_store_si512((__m512i*)(ptr + 8), bgra1.val); - _mm512_store_si512((__m512i*)(ptr + 16), bgra2.val); - _mm512_store_si512((__m512i*)(ptr + 24), bgra3.val); - } - else - { - _mm512_storeu_si512((__m512i*)ptr, bgra0.val); - _mm512_storeu_si512((__m512i*)(ptr + 8), bgra1.val); - _mm512_storeu_si512((__m512i*)(ptr + 16), bgra2.val); - _mm512_storeu_si512((__m512i*)(ptr + 24), bgra3.val); - } -} - -#define OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(_Tpvec0, _Tp0, suffix0, _Tpvec1, _Tp1, suffix1) \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0 ) \ -{ \ - _Tpvec1 a1, b1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ -} \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0 ) \ -{ \ - _Tpvec1 a1, b1, c1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ - c0 = v_reinterpret_as_##suffix0(c1); \ -} \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0, _Tpvec0& d0 ) \ -{ \ - _Tpvec1 a1, b1, c1, d1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1, d1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ - c0 = v_reinterpret_as_##suffix0(c1); \ - d0 = v_reinterpret_as_##suffix0(d1); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - hal::StoreMode mode=hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, mode); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, const _Tpvec0& c0, \ - hal::StoreMode mode=hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, c1, mode); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - const _Tpvec0& c0, const _Tpvec0& d0, \ - hal::StoreMode mode=hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ - _Tpvec1 d1 = v_reinterpret_as_##suffix1(d0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, c1, d1, mode); \ -} - -OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(v_int8x64, schar, s8, v_uint8x64, uchar, u8) -OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(v_int16x32, short, s16, v_uint16x32, ushort, u16) -OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(v_int32x16, int, s32, v_uint32x16, unsigned, u32) -OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(v_float32x16, float, f32, v_uint32x16, unsigned, u32) -OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(v_int64x8, int64, s64, v_uint64x8, uint64, u64) -OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(v_float64x8, double, f64, v_uint64x8, uint64, u64) - -////////// Mask and checks ///////// - -/** Mask **/ -inline int64 v_signmask(const v_int8x64& a) { return (int64)_mm512_movepi8_mask(a.val); } -inline int v_signmask(const v_int16x32& a) { return (int)_mm512_cmp_epi16_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_LT); } -inline int v_signmask(const v_int32x16& a) { return (int)_mm512_cmp_epi32_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_LT); } -inline int v_signmask(const v_int64x8& a) { return (int)_mm512_cmp_epi64_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_LT); } - -inline int64 v_signmask(const v_uint8x64& a) { return v_signmask(v_reinterpret_as_s8(a)); } -inline int v_signmask(const v_uint16x32& a) { return v_signmask(v_reinterpret_as_s16(a)); } -inline int v_signmask(const v_uint32x16& a) { return v_signmask(v_reinterpret_as_s32(a)); } -inline int v_signmask(const v_uint64x8& a) { return v_signmask(v_reinterpret_as_s64(a)); } -inline int v_signmask(const v_float32x16& a) { return v_signmask(v_reinterpret_as_s32(a)); } -inline int v_signmask(const v_float64x8& a) { return v_signmask(v_reinterpret_as_s64(a)); } - -/** Checks **/ -inline bool v_check_all(const v_int8x64& a) { return !(bool)_mm512_cmp_epi8_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_NLT); } -inline bool v_check_any(const v_int8x64& a) { return (bool)_mm512_movepi8_mask(a.val); } -inline bool v_check_all(const v_int16x32& a) { return !(bool)_mm512_cmp_epi16_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_NLT); } -inline bool v_check_any(const v_int16x32& a) { return (bool)_mm512_cmp_epi16_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_LT); } -inline bool v_check_all(const v_int32x16& a) { return !(bool)_mm512_cmp_epi32_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_NLT); } -inline bool v_check_any(const v_int32x16& a) { return (bool)_mm512_cmp_epi32_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_LT); } -inline bool v_check_all(const v_int64x8& a) { return !(bool)_mm512_cmp_epi64_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_NLT); } -inline bool v_check_any(const v_int64x8& a) { return (bool)_mm512_cmp_epi64_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_LT); } - -inline bool v_check_all(const v_float32x16& a) { return v_check_all(v_reinterpret_as_s32(a)); } -inline bool v_check_any(const v_float32x16& a) { return v_check_any(v_reinterpret_as_s32(a)); } -inline bool v_check_all(const v_float64x8& a) { return v_check_all(v_reinterpret_as_s64(a)); } -inline bool v_check_any(const v_float64x8& a) { return v_check_any(v_reinterpret_as_s64(a)); } -inline bool v_check_all(const v_uint8x64& a) { return v_check_all(v_reinterpret_as_s8(a)); } -inline bool v_check_all(const v_uint16x32& a) { return v_check_all(v_reinterpret_as_s16(a)); } -inline bool v_check_all(const v_uint32x16& a) { return v_check_all(v_reinterpret_as_s32(a)); } -inline bool v_check_all(const v_uint64x8& a) { return v_check_all(v_reinterpret_as_s64(a)); } -inline bool v_check_any(const v_uint8x64& a) { return v_check_any(v_reinterpret_as_s8(a)); } -inline bool v_check_any(const v_uint16x32& a) { return v_check_any(v_reinterpret_as_s16(a)); } -inline bool v_check_any(const v_uint32x16& a) { return v_check_any(v_reinterpret_as_s32(a)); } -inline bool v_check_any(const v_uint64x8& a) { return v_check_any(v_reinterpret_as_s64(a)); } - -inline int v_scan_forward(const v_int8x64& a) -{ - int64 mask = _mm512_movepi8_mask(a.val); - int mask32 = (int)mask; - return mask != 0 ? mask32 != 0 ? trailingZeros32(mask32) : 32 + trailingZeros32((int)(mask >> 32)) : 0; -} -inline int v_scan_forward(const v_uint8x64& a) { return v_scan_forward(v_reinterpret_as_s8(a)); } -inline int v_scan_forward(const v_int16x32& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))); } -inline int v_scan_forward(const v_uint16x32& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))); } -inline int v_scan_forward(const v_int32x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))) / 2; } -inline int v_scan_forward(const v_uint32x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))) / 2; } -inline int v_scan_forward(const v_float32x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))) / 2; } -inline int v_scan_forward(const v_int64x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))) / 4; } -inline int v_scan_forward(const v_uint64x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))) / 4; } -inline int v_scan_forward(const v_float64x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))) / 4; } - -inline void v512_cleanup() { _mm256_zeroall(); } - -#include "intrin_math.hpp" -inline v_float32x16 v_exp(const v_float32x16& x) { return v_exp_default_32f(x); } -inline v_float32x16 v_log(const v_float32x16& x) { return v_log_default_32f(x); } -inline void v_sincos(const v_float32x16& x, v_float32x16& s, v_float32x16& c) { v_sincos_default_32f(x, s, c); } -inline v_float32x16 v_sin(const v_float32x16& x) { return v_sin_default_32f(x); } -inline v_float32x16 v_cos(const v_float32x16& x) { return v_cos_default_32f(x); } -inline v_float32x16 v_erf(const v_float32x16& x) { return v_erf_default_32f(x); } - -inline v_float64x8 v_exp(const v_float64x8& x) { return v_exp_default_64f(x); } -inline v_float64x8 v_log(const v_float64x8& x) { return v_log_default_64f(x); } -inline void v_sincos(const v_float64x8& x, v_float64x8& s, v_float64x8& c) { v_sincos_default_64f(x, s, c); } -inline v_float64x8 v_sin(const v_float64x8& x) { return v_sin_default_64f(x); } -inline v_float64x8 v_cos(const v_float64x8& x) { return v_cos_default_64f(x); } - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} // cv:: - -#endif // OPENCV_HAL_INTRIN_AVX_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +#ifndef OPENCV_HAL_INTRIN_AVX512_HPP +#define OPENCV_HAL_INTRIN_AVX512_HPP + +#if defined(_MSC_VER) && (_MSC_VER < 1920/*MSVS2019*/) +# pragma warning(disable:4146) // unary minus operator applied to unsigned type, result still unsigned +# pragma warning(disable:4309) // 'argument': truncation of constant value +# pragma warning(disable:4310) // cast truncates constant value +#endif + +#define CVT_ROUND_MODES_IMPLEMENTED 0 + +#define CV_SIMD512 1 +#define CV_SIMD512_64F 1 +#define CV_SIMD512_FP16 0 // no native operations with FP16 type. Only load/store from float32x8 are available (if CV_FP16 == 1) + +#define _v512_set_epu64(a7, a6, a5, a4, a3, a2, a1, a0) _mm512_set_epi64((int64)(a7),(int64)(a6),(int64)(a5),(int64)(a4),(int64)(a3),(int64)(a2),(int64)(a1),(int64)(a0)) +#define _v512_set_epu32(a15, a14, a13, a12, a11, a10, a9, a8, a7, a6, a5, a4, a3, a2, a1, a0) \ + _mm512_set_epi64(((int64)(a15)<<32)|(int64)(a14), ((int64)(a13)<<32)|(int64)(a12), ((int64)(a11)<<32)|(int64)(a10), ((int64)( a9)<<32)|(int64)( a8), \ + ((int64)( a7)<<32)|(int64)( a6), ((int64)( a5)<<32)|(int64)( a4), ((int64)( a3)<<32)|(int64)( a2), ((int64)( a1)<<32)|(int64)( a0)) +#define _v512_set_epu16(a31, a30, a29, a28, a27, a26, a25, a24, a23, a22, a21, a20, a19, a18, a17, a16, \ + a15, a14, a13, a12, a11, a10, a9, a8, a7, a6, a5, a4, a3, a2, a1, a0) \ + _v512_set_epu32(((unsigned)(a31)<<16)|(unsigned)(a30), ((unsigned)(a29)<<16)|(unsigned)(a28), ((unsigned)(a27)<<16)|(unsigned)(a26), ((unsigned)(a25)<<16)|(unsigned)(a24), \ + ((unsigned)(a23)<<16)|(unsigned)(a22), ((unsigned)(a21)<<16)|(unsigned)(a20), ((unsigned)(a19)<<16)|(unsigned)(a18), ((unsigned)(a17)<<16)|(unsigned)(a16), \ + ((unsigned)(a15)<<16)|(unsigned)(a14), ((unsigned)(a13)<<16)|(unsigned)(a12), ((unsigned)(a11)<<16)|(unsigned)(a10), ((unsigned)( a9)<<16)|(unsigned)( a8), \ + ((unsigned)( a7)<<16)|(unsigned)( a6), ((unsigned)( a5)<<16)|(unsigned)( a4), ((unsigned)( a3)<<16)|(unsigned)( a2), ((unsigned)( a1)<<16)|(unsigned)( a0)) +#define _v512_set_epu8(a63, a62, a61, a60, a59, a58, a57, a56, a55, a54, a53, a52, a51, a50, a49, a48, \ + a47, a46, a45, a44, a43, a42, a41, a40, a39, a38, a37, a36, a35, a34, a33, a32, \ + a31, a30, a29, a28, a27, a26, a25, a24, a23, a22, a21, a20, a19, a18, a17, a16, \ + a15, a14, a13, a12, a11, a10, a9, a8, a7, a6, a5, a4, a3, a2, a1, a0) \ + _v512_set_epu32(((unsigned)(a63)<<24)|((unsigned)(a62)<<16)|((unsigned)(a61)<<8)|(unsigned)(a60),((unsigned)(a59)<<24)|((unsigned)(a58)<<16)|((unsigned)(a57)<<8)|(unsigned)(a56), \ + ((unsigned)(a55)<<24)|((unsigned)(a54)<<16)|((unsigned)(a53)<<8)|(unsigned)(a52),((unsigned)(a51)<<24)|((unsigned)(a50)<<16)|((unsigned)(a49)<<8)|(unsigned)(a48), \ + ((unsigned)(a47)<<24)|((unsigned)(a46)<<16)|((unsigned)(a45)<<8)|(unsigned)(a44),((unsigned)(a43)<<24)|((unsigned)(a42)<<16)|((unsigned)(a41)<<8)|(unsigned)(a40), \ + ((unsigned)(a39)<<24)|((unsigned)(a38)<<16)|((unsigned)(a37)<<8)|(unsigned)(a36),((unsigned)(a35)<<24)|((unsigned)(a34)<<16)|((unsigned)(a33)<<8)|(unsigned)(a32), \ + ((unsigned)(a31)<<24)|((unsigned)(a30)<<16)|((unsigned)(a29)<<8)|(unsigned)(a28),((unsigned)(a27)<<24)|((unsigned)(a26)<<16)|((unsigned)(a25)<<8)|(unsigned)(a24), \ + ((unsigned)(a23)<<24)|((unsigned)(a22)<<16)|((unsigned)(a21)<<8)|(unsigned)(a20),((unsigned)(a19)<<24)|((unsigned)(a18)<<16)|((unsigned)(a17)<<8)|(unsigned)(a16), \ + ((unsigned)(a15)<<24)|((unsigned)(a14)<<16)|((unsigned)(a13)<<8)|(unsigned)(a12),((unsigned)(a11)<<24)|((unsigned)(a10)<<16)|((unsigned)( a9)<<8)|(unsigned)( a8), \ + ((unsigned)( a7)<<24)|((unsigned)( a6)<<16)|((unsigned)( a5)<<8)|(unsigned)( a4),((unsigned)( a3)<<24)|((unsigned)( a2)<<16)|((unsigned)( a1)<<8)|(unsigned)( a0)) +#define _v512_set_epi8(a63, a62, a61, a60, a59, a58, a57, a56, a55, a54, a53, a52, a51, a50, a49, a48, \ + a47, a46, a45, a44, a43, a42, a41, a40, a39, a38, a37, a36, a35, a34, a33, a32, \ + a31, a30, a29, a28, a27, a26, a25, a24, a23, a22, a21, a20, a19, a18, a17, a16, \ + a15, a14, a13, a12, a11, a10, a9, a8, a7, a6, a5, a4, a3, a2, a1, a0) \ + _v512_set_epu8((uchar)(a63), (uchar)(a62), (uchar)(a61), (uchar)(a60), (uchar)(a59), (uchar)(a58), (uchar)(a57), (uchar)(a56), \ + (uchar)(a55), (uchar)(a54), (uchar)(a53), (uchar)(a52), (uchar)(a51), (uchar)(a50), (uchar)(a49), (uchar)(a48), \ + (uchar)(a47), (uchar)(a46), (uchar)(a45), (uchar)(a44), (uchar)(a43), (uchar)(a42), (uchar)(a41), (uchar)(a40), \ + (uchar)(a39), (uchar)(a38), (uchar)(a37), (uchar)(a36), (uchar)(a35), (uchar)(a34), (uchar)(a33), (uchar)(a32), \ + (uchar)(a31), (uchar)(a30), (uchar)(a29), (uchar)(a28), (uchar)(a27), (uchar)(a26), (uchar)(a25), (uchar)(a24), \ + (uchar)(a23), (uchar)(a22), (uchar)(a21), (uchar)(a20), (uchar)(a19), (uchar)(a18), (uchar)(a17), (uchar)(a16), \ + (uchar)(a15), (uchar)(a14), (uchar)(a13), (uchar)(a12), (uchar)(a11), (uchar)(a10), (uchar)( a9), (uchar)( a8), \ + (uchar)( a7), (uchar)( a6), (uchar)( a5), (uchar)( a4), (uchar)( a3), (uchar)( a2), (uchar)( a1), (uchar)( a0)) + +#ifndef _mm512_cvtpd_pslo +#ifdef _mm512_zextsi256_si512 +#define _mm512_cvtpd_pslo(a) _mm512_zextps256_ps512(_mm512_cvtpd_ps(a)) +#else +//if preferred way to extend with zeros is unavailable +#define _mm512_cvtpd_pslo(a) _mm512_castps256_ps512(_mm512_cvtpd_ps(a)) +#endif +#endif +///////// Utils //////////// + +namespace +{ + +inline __m512i _v512_combine(const __m256i& lo, const __m256i& hi) +{ return _mm512_inserti32x8(_mm512_castsi256_si512(lo), hi, 1); } + +inline __m512 _v512_combine(const __m256& lo, const __m256& hi) +{ return _mm512_insertf32x8(_mm512_castps256_ps512(lo), hi, 1); } + +inline __m512d _v512_combine(const __m256d& lo, const __m256d& hi) +{ return _mm512_insertf64x4(_mm512_castpd256_pd512(lo), hi, 1); } + +inline int _v_cvtsi512_si32(const __m512i& a) +{ return _mm_cvtsi128_si32(_mm512_castsi512_si128(a)); } + +inline __m256i _v512_extract_high(const __m512i& v) +{ return _mm512_extracti32x8_epi32(v, 1); } + +inline __m256 _v512_extract_high(const __m512& v) +{ return _mm512_extractf32x8_ps(v, 1); } + +inline __m256d _v512_extract_high(const __m512d& v) +{ return _mm512_extractf64x4_pd(v, 1); } + +inline __m256i _v512_extract_low(const __m512i& v) +{ return _mm512_castsi512_si256(v); } + +inline __m256 _v512_extract_low(const __m512& v) +{ return _mm512_castps512_ps256(v); } + +inline __m256d _v512_extract_low(const __m512d& v) +{ return _mm512_castpd512_pd256(v); } + +inline __m512i _v512_insert(const __m512i& a, const __m256i& b) +{ return _mm512_inserti32x8(a, b, 0); } + +inline __m512 _v512_insert(const __m512& a, const __m256& b) +{ return _mm512_insertf32x8(a, b, 0); } + +inline __m512d _v512_insert(const __m512d& a, const __m256d& b) +{ return _mm512_insertf64x4(a, b, 0); } + +} + +namespace cv +{ + +//! @cond IGNORED + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +///////// Types //////////// + +struct v_uint8x64 +{ + typedef uchar lane_type; + enum { nlanes = 64 }; + __m512i val; + + explicit v_uint8x64(__m512i v) : val(v) {} + v_uint8x64(uchar v0, uchar v1, uchar v2, uchar v3, + uchar v4, uchar v5, uchar v6, uchar v7, + uchar v8, uchar v9, uchar v10, uchar v11, + uchar v12, uchar v13, uchar v14, uchar v15, + uchar v16, uchar v17, uchar v18, uchar v19, + uchar v20, uchar v21, uchar v22, uchar v23, + uchar v24, uchar v25, uchar v26, uchar v27, + uchar v28, uchar v29, uchar v30, uchar v31, + uchar v32, uchar v33, uchar v34, uchar v35, + uchar v36, uchar v37, uchar v38, uchar v39, + uchar v40, uchar v41, uchar v42, uchar v43, + uchar v44, uchar v45, uchar v46, uchar v47, + uchar v48, uchar v49, uchar v50, uchar v51, + uchar v52, uchar v53, uchar v54, uchar v55, + uchar v56, uchar v57, uchar v58, uchar v59, + uchar v60, uchar v61, uchar v62, uchar v63) + { + val = _v512_set_epu8(v63, v62, v61, v60, v59, v58, v57, v56, v55, v54, v53, v52, v51, v50, v49, v48, + v47, v46, v45, v44, v43, v42, v41, v40, v39, v38, v37, v36, v35, v34, v33, v32, + v31, v30, v29, v28, v27, v26, v25, v24, v23, v22, v21, v20, v19, v18, v17, v16, + v15, v14, v13, v12, v11, v10, v9, v8, v7, v6, v5, v4, v3, v2, v1, v0); + } + v_uint8x64() {} + + static inline v_uint8x64 zero() { return v_uint8x64(_mm512_setzero_si512()); } + + uchar get0() const { return (uchar)_v_cvtsi512_si32(val); } +}; + +struct v_int8x64 +{ + typedef schar lane_type; + enum { nlanes = 64 }; + __m512i val; + + explicit v_int8x64(__m512i v) : val(v) {} + v_int8x64(schar v0, schar v1, schar v2, schar v3, + schar v4, schar v5, schar v6, schar v7, + schar v8, schar v9, schar v10, schar v11, + schar v12, schar v13, schar v14, schar v15, + schar v16, schar v17, schar v18, schar v19, + schar v20, schar v21, schar v22, schar v23, + schar v24, schar v25, schar v26, schar v27, + schar v28, schar v29, schar v30, schar v31, + schar v32, schar v33, schar v34, schar v35, + schar v36, schar v37, schar v38, schar v39, + schar v40, schar v41, schar v42, schar v43, + schar v44, schar v45, schar v46, schar v47, + schar v48, schar v49, schar v50, schar v51, + schar v52, schar v53, schar v54, schar v55, + schar v56, schar v57, schar v58, schar v59, + schar v60, schar v61, schar v62, schar v63) + { + val = _v512_set_epi8(v63, v62, v61, v60, v59, v58, v57, v56, v55, v54, v53, v52, v51, v50, v49, v48, + v47, v46, v45, v44, v43, v42, v41, v40, v39, v38, v37, v36, v35, v34, v33, v32, + v31, v30, v29, v28, v27, v26, v25, v24, v23, v22, v21, v20, v19, v18, v17, v16, + v15, v14, v13, v12, v11, v10, v9, v8, v7, v6, v5, v4, v3, v2, v1, v0); + } + v_int8x64() {} + + static inline v_int8x64 zero() { return v_int8x64(_mm512_setzero_si512()); } + + schar get0() const { return (schar)_v_cvtsi512_si32(val); } +}; + +struct v_uint16x32 +{ + typedef ushort lane_type; + enum { nlanes = 32 }; + __m512i val; + + explicit v_uint16x32(__m512i v) : val(v) {} + v_uint16x32(ushort v0, ushort v1, ushort v2, ushort v3, + ushort v4, ushort v5, ushort v6, ushort v7, + ushort v8, ushort v9, ushort v10, ushort v11, + ushort v12, ushort v13, ushort v14, ushort v15, + ushort v16, ushort v17, ushort v18, ushort v19, + ushort v20, ushort v21, ushort v22, ushort v23, + ushort v24, ushort v25, ushort v26, ushort v27, + ushort v28, ushort v29, ushort v30, ushort v31) + { + val = _v512_set_epu16(v31, v30, v29, v28, v27, v26, v25, v24, v23, v22, v21, v20, v19, v18, v17, v16, + v15, v14, v13, v12, v11, v10, v9, v8, v7, v6, v5, v4, v3, v2, v1, v0); + } + v_uint16x32() {} + + static inline v_uint16x32 zero() { return v_uint16x32(_mm512_setzero_si512()); } + + ushort get0() const { return (ushort)_v_cvtsi512_si32(val); } +}; + +struct v_int16x32 +{ + typedef short lane_type; + enum { nlanes = 32 }; + __m512i val; + + explicit v_int16x32(__m512i v) : val(v) {} + v_int16x32(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7, + short v8, short v9, short v10, short v11, short v12, short v13, short v14, short v15, + short v16, short v17, short v18, short v19, short v20, short v21, short v22, short v23, + short v24, short v25, short v26, short v27, short v28, short v29, short v30, short v31) + { + val = _v512_set_epu16((ushort)v31, (ushort)v30, (ushort)v29, (ushort)v28, (ushort)v27, (ushort)v26, (ushort)v25, (ushort)v24, + (ushort)v23, (ushort)v22, (ushort)v21, (ushort)v20, (ushort)v19, (ushort)v18, (ushort)v17, (ushort)v16, + (ushort)v15, (ushort)v14, (ushort)v13, (ushort)v12, (ushort)v11, (ushort)v10, (ushort)v9 , (ushort)v8, + (ushort)v7 , (ushort)v6 , (ushort)v5 , (ushort)v4 , (ushort)v3 , (ushort)v2 , (ushort)v1 , (ushort)v0); + } + v_int16x32() {} + + static inline v_int16x32 zero() { return v_int16x32(_mm512_setzero_si512()); } + + short get0() const { return (short)_v_cvtsi512_si32(val); } +}; + +struct v_uint32x16 +{ + typedef unsigned lane_type; + enum { nlanes = 16 }; + __m512i val; + + explicit v_uint32x16(__m512i v) : val(v) {} + v_uint32x16(unsigned v0, unsigned v1, unsigned v2, unsigned v3, + unsigned v4, unsigned v5, unsigned v6, unsigned v7, + unsigned v8, unsigned v9, unsigned v10, unsigned v11, + unsigned v12, unsigned v13, unsigned v14, unsigned v15) + { + val = _mm512_setr_epi32((int)v0, (int)v1, (int)v2, (int)v3, (int)v4, (int)v5, (int)v6, (int)v7, + (int)v8, (int)v9, (int)v10, (int)v11, (int)v12, (int)v13, (int)v14, (int)v15); + } + v_uint32x16() {} + + static inline v_uint32x16 zero() { return v_uint32x16(_mm512_setzero_si512()); } + + unsigned get0() const { return (unsigned)_v_cvtsi512_si32(val); } +}; + +struct v_int32x16 +{ + typedef int lane_type; + enum { nlanes = 16 }; + __m512i val; + + explicit v_int32x16(__m512i v) : val(v) {} + v_int32x16(int v0, int v1, int v2, int v3, int v4, int v5, int v6, int v7, + int v8, int v9, int v10, int v11, int v12, int v13, int v14, int v15) + { + val = _mm512_setr_epi32(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15); + } + v_int32x16() {} + + static inline v_int32x16 zero() { return v_int32x16(_mm512_setzero_si512()); } + + int get0() const { return _v_cvtsi512_si32(val); } +}; + +struct v_float32x16 +{ + typedef float lane_type; + enum { nlanes = 16 }; + __m512 val; + + explicit v_float32x16(__m512 v) : val(v) {} + v_float32x16(float v0, float v1, float v2, float v3, float v4, float v5, float v6, float v7, + float v8, float v9, float v10, float v11, float v12, float v13, float v14, float v15) + { + val = _mm512_setr_ps(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15); + } + v_float32x16() {} + + static inline v_float32x16 zero() { return v_float32x16(_mm512_setzero_ps()); } + + float get0() const { return _mm_cvtss_f32(_mm512_castps512_ps128(val)); } +}; + +struct v_uint64x8 +{ + typedef uint64 lane_type; + enum { nlanes = 8 }; + __m512i val; + + explicit v_uint64x8(__m512i v) : val(v) {} + v_uint64x8(uint64 v0, uint64 v1, uint64 v2, uint64 v3, uint64 v4, uint64 v5, uint64 v6, uint64 v7) + { val = _mm512_setr_epi64((int64)v0, (int64)v1, (int64)v2, (int64)v3, (int64)v4, (int64)v5, (int64)v6, (int64)v7); } + v_uint64x8() {} + + static inline v_uint64x8 zero() { return v_uint64x8(_mm512_setzero_si512()); } + + uint64 get0() const + { + #if defined __x86_64__ || defined _M_X64 + return (uint64)_mm_cvtsi128_si64(_mm512_castsi512_si128(val)); + #else + int a = _mm_cvtsi128_si32(_mm512_castsi512_si128(val)); + int b = _mm_cvtsi128_si32(_mm512_castsi512_si128(_mm512_srli_epi64(val, 32))); + return (unsigned)a | ((uint64)(unsigned)b << 32); + #endif + } +}; + +struct v_int64x8 +{ + typedef int64 lane_type; + enum { nlanes = 8 }; + __m512i val; + + explicit v_int64x8(__m512i v) : val(v) {} + v_int64x8(int64 v0, int64 v1, int64 v2, int64 v3, int64 v4, int64 v5, int64 v6, int64 v7) + { val = _mm512_setr_epi64(v0, v1, v2, v3, v4, v5, v6, v7); } + v_int64x8() {} + + static inline v_int64x8 zero() { return v_int64x8(_mm512_setzero_si512()); } + + int64 get0() const + { + #if defined __x86_64__ || defined _M_X64 + return (int64)_mm_cvtsi128_si64(_mm512_castsi512_si128(val)); + #else + int a = _mm_cvtsi128_si32(_mm512_castsi512_si128(val)); + int b = _mm_cvtsi128_si32(_mm512_castsi512_si128(_mm512_srli_epi64(val, 32))); + return (int64)((unsigned)a | ((uint64)(unsigned)b << 32)); + #endif + } +}; + +struct v_float64x8 +{ + typedef double lane_type; + enum { nlanes = 8 }; + __m512d val; + + explicit v_float64x8(__m512d v) : val(v) {} + v_float64x8(double v0, double v1, double v2, double v3, double v4, double v5, double v6, double v7) + { val = _mm512_setr_pd(v0, v1, v2, v3, v4, v5, v6, v7); } + v_float64x8() {} + + static inline v_float64x8 zero() { return v_float64x8(_mm512_setzero_pd()); } + + double get0() const { return _mm_cvtsd_f64(_mm512_castpd512_pd128(val)); } +}; + +//////////////// Load and store operations /////////////// + +#define OPENCV_HAL_IMPL_AVX512_LOADSTORE(_Tpvec, _Tp) \ + inline _Tpvec v512_load(const _Tp* ptr) \ + { return _Tpvec(_mm512_loadu_si512((const __m512i*)ptr)); } \ + inline _Tpvec v512_load_aligned(const _Tp* ptr) \ + { return _Tpvec(_mm512_load_si512((const __m512i*)ptr)); } \ + inline _Tpvec v512_load_low(const _Tp* ptr) \ + { \ + __m256i v256 = _mm256_loadu_si256((const __m256i*)ptr); \ + return _Tpvec(_mm512_castsi256_si512(v256)); \ + } \ + inline _Tpvec v512_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ + { \ + __m256i vlo = _mm256_loadu_si256((const __m256i*)ptr0); \ + __m256i vhi = _mm256_loadu_si256((const __m256i*)ptr1); \ + return _Tpvec(_v512_combine(vlo, vhi)); \ + } \ + inline void v_store(_Tp* ptr, const _Tpvec& a) \ + { _mm512_storeu_si512((__m512i*)ptr, a.val); } \ + inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ + { _mm512_store_si512((__m512i*)ptr, a.val); } \ + inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ + { _mm512_stream_si512((__m512i*)ptr, a.val); } \ + inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ + { \ + if( mode == hal::STORE_UNALIGNED ) \ + _mm512_storeu_si512((__m512i*)ptr, a.val); \ + else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ + _mm512_stream_si512((__m512i*)ptr, a.val); \ + else \ + _mm512_store_si512((__m512i*)ptr, a.val); \ + } \ + inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ + { _mm256_storeu_si256((__m256i*)ptr, _v512_extract_low(a.val)); } \ + inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ + { _mm256_storeu_si256((__m256i*)ptr, _v512_extract_high(a.val)); } + +OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_uint8x64, uchar) +OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_int8x64, schar) +OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_uint16x32, ushort) +OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_int16x32, short) +OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_uint32x16, unsigned) +OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_int32x16, int) +OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_uint64x8, uint64) +OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_int64x8, int64) + +#define OPENCV_HAL_IMPL_AVX512_LOADSTORE_FLT(_Tpvec, _Tp, suffix, halfreg) \ + inline _Tpvec v512_load(const _Tp* ptr) \ + { return _Tpvec(_mm512_loadu_##suffix(ptr)); } \ + inline _Tpvec v512_load_aligned(const _Tp* ptr) \ + { return _Tpvec(_mm512_load_##suffix(ptr)); } \ + inline _Tpvec v512_load_low(const _Tp* ptr) \ + { \ + return _Tpvec(_mm512_cast##suffix##256_##suffix##512 \ + (_mm256_loadu_##suffix(ptr))); \ + } \ + inline _Tpvec v512_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ + { \ + halfreg vlo = _mm256_loadu_##suffix(ptr0); \ + halfreg vhi = _mm256_loadu_##suffix(ptr1); \ + return _Tpvec(_v512_combine(vlo, vhi)); \ + } \ + inline void v_store(_Tp* ptr, const _Tpvec& a) \ + { _mm512_storeu_##suffix(ptr, a.val); } \ + inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ + { _mm512_store_##suffix(ptr, a.val); } \ + inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ + { _mm512_stream_##suffix(ptr, a.val); } \ + inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ + { \ + if( mode == hal::STORE_UNALIGNED ) \ + _mm512_storeu_##suffix(ptr, a.val); \ + else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ + _mm512_stream_##suffix(ptr, a.val); \ + else \ + _mm512_store_##suffix(ptr, a.val); \ + } \ + inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ + { _mm256_storeu_##suffix(ptr, _v512_extract_low(a.val)); } \ + inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ + { _mm256_storeu_##suffix(ptr, _v512_extract_high(a.val)); } + +OPENCV_HAL_IMPL_AVX512_LOADSTORE_FLT(v_float32x16, float, ps, __m256) +OPENCV_HAL_IMPL_AVX512_LOADSTORE_FLT(v_float64x8, double, pd, __m256d) + +#define OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, _Tpvecf, suffix, cast) \ + inline _Tpvec v_reinterpret_as_##suffix(const _Tpvecf& a) \ + { return _Tpvec(cast(a.val)); } + +#define OPENCV_HAL_IMPL_AVX512_INIT(_Tpvec, _Tp, suffix, ssuffix, ctype_s) \ + inline _Tpvec v512_setzero_##suffix() \ + { return _Tpvec(_mm512_setzero_si512()); } \ + inline _Tpvec v512_setall_##suffix(_Tp v) \ + { return _Tpvec(_mm512_set1_##ssuffix((ctype_s)v)); } \ + template <> inline _Tpvec v_setzero_() \ + { return v512_setzero_##suffix(); } \ + template <> inline _Tpvec v_setall_(_Tp v) \ + { return v512_setall_##suffix(v); } \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint8x64, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int8x64, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint16x32, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int16x32, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint32x16, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int32x16, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint64x8, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int64x8, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_float32x16, suffix, _mm512_castps_si512) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_float64x8, suffix, _mm512_castpd_si512) + +OPENCV_HAL_IMPL_AVX512_INIT(v_uint8x64, uchar, u8, epi8, char) +OPENCV_HAL_IMPL_AVX512_INIT(v_int8x64, schar, s8, epi8, char) +OPENCV_HAL_IMPL_AVX512_INIT(v_uint16x32, ushort, u16, epi16, short) +OPENCV_HAL_IMPL_AVX512_INIT(v_int16x32, short, s16, epi16, short) +OPENCV_HAL_IMPL_AVX512_INIT(v_uint32x16, unsigned, u32, epi32, int) +OPENCV_HAL_IMPL_AVX512_INIT(v_int32x16, int, s32, epi32, int) +OPENCV_HAL_IMPL_AVX512_INIT(v_uint64x8, uint64, u64, epi64, int64) +OPENCV_HAL_IMPL_AVX512_INIT(v_int64x8, int64, s64, epi64, int64) + +#define OPENCV_HAL_IMPL_AVX512_INIT_FLT(_Tpvec, _Tp, suffix, zsuffix, cast) \ + inline _Tpvec v512_setzero_##suffix() \ + { return _Tpvec(_mm512_setzero_##zsuffix()); } \ + inline _Tpvec v512_setall_##suffix(_Tp v) \ + { return _Tpvec(_mm512_set1_##zsuffix(v)); } \ + template <> inline _Tpvec v_setzero_() \ + { return v512_setzero_##suffix(); } \ + template <> inline _Tpvec v_setall_(_Tp v) \ + { return v512_setall_##suffix(v); } \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint8x64, suffix, cast) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int8x64, suffix, cast) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint16x32, suffix, cast) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int16x32, suffix, cast) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint32x16, suffix, cast) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int32x16, suffix, cast) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint64x8, suffix, cast) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int64x8, suffix, cast) + +OPENCV_HAL_IMPL_AVX512_INIT_FLT(v_float32x16, float, f32, ps, _mm512_castsi512_ps) +OPENCV_HAL_IMPL_AVX512_INIT_FLT(v_float64x8, double, f64, pd, _mm512_castsi512_pd) + +inline v_float32x16 v_reinterpret_as_f32(const v_float32x16& a) +{ return a; } +inline v_float32x16 v_reinterpret_as_f32(const v_float64x8& a) +{ return v_float32x16(_mm512_castpd_ps(a.val)); } + +inline v_float64x8 v_reinterpret_as_f64(const v_float64x8& a) +{ return a; } +inline v_float64x8 v_reinterpret_as_f64(const v_float32x16& a) +{ return v_float64x8(_mm512_castps_pd(a.val)); } + +// FP16 +inline v_float32x16 v512_load_expand(const hfloat* ptr) +{ + return v_float32x16(_mm512_cvtph_ps(_mm256_loadu_si256((const __m256i*)ptr))); +} + +inline void v_pack_store(hfloat* ptr, const v_float32x16& a) +{ + __m256i ah = _mm512_cvtps_ph(a.val, 0); + _mm256_storeu_si256((__m256i*)ptr, ah); +} + +/* Recombine & ZIP */ +inline void v_zip(const v_int8x64& a, const v_int8x64& b, v_int8x64& ab0, v_int8x64& ab1) +{ +#if CV_AVX_512VBMI + __m512i mask0 = _v512_set_epu8( 95, 31, 94, 30, 93, 29, 92, 28, 91, 27, 90, 26, 89, 25, 88, 24, + 87, 23, 86, 22, 85, 21, 84, 20, 83, 19, 82, 18, 81, 17, 80, 16, + 79, 15, 78, 14, 77, 13, 76, 12, 75, 11, 74, 10, 73, 9, 72, 8, + 71, 7, 70, 6, 69, 5, 68, 4, 67, 3, 66, 2, 65, 1, 64, 0); + ab0 = v_int8x64(_mm512_permutex2var_epi8(a.val, mask0, b.val)); + __m512i mask1 = _v512_set_epu8(127, 63, 126, 62, 125, 61, 124, 60, 123, 59, 122, 58, 121, 57, 120, 56, + 119, 55, 118, 54, 117, 53, 116, 52, 115, 51, 114, 50, 113, 49, 112, 48, + 111, 47, 110, 46, 109, 45, 108, 44, 107, 43, 106, 42, 105, 41, 104, 40, + 103, 39, 102, 38, 101, 37, 100, 36, 99, 35, 98, 34, 97, 33, 96, 32); + ab1 = v_int8x64(_mm512_permutex2var_epi8(a.val, mask1, b.val)); +#else + __m512i low = _mm512_unpacklo_epi8(a.val, b.val); + __m512i high = _mm512_unpackhi_epi8(a.val, b.val); + ab0 = v_int8x64(_mm512_permutex2var_epi64(low, _v512_set_epu64(11, 10, 3, 2, 9, 8, 1, 0), high)); + ab1 = v_int8x64(_mm512_permutex2var_epi64(low, _v512_set_epu64(15, 14, 7, 6, 13, 12, 5, 4), high)); +#endif +} +inline void v_zip(const v_int16x32& a, const v_int16x32& b, v_int16x32& ab0, v_int16x32& ab1) +{ + __m512i mask0 = _v512_set_epu16(47, 15, 46, 14, 45, 13, 44, 12, 43, 11, 42, 10, 41, 9, 40, 8, + 39, 7, 38, 6, 37, 5, 36, 4, 35, 3, 34, 2, 33, 1, 32, 0); + ab0 = v_int16x32(_mm512_permutex2var_epi16(a.val, mask0, b.val)); + __m512i mask1 = _v512_set_epu16(63, 31, 62, 30, 61, 29, 60, 28, 59, 27, 58, 26, 57, 25, 56, 24, + 55, 23, 54, 22, 53, 21, 52, 20, 51, 19, 50, 18, 49, 17, 48, 16); + ab1 = v_int16x32(_mm512_permutex2var_epi16(a.val, mask1, b.val)); +} +inline void v_zip(const v_int32x16& a, const v_int32x16& b, v_int32x16& ab0, v_int32x16& ab1) +{ + __m512i mask0 = _v512_set_epu32(23, 7, 22, 6, 21, 5, 20, 4, 19, 3, 18, 2, 17, 1, 16, 0); + ab0 = v_int32x16(_mm512_permutex2var_epi32(a.val, mask0, b.val)); + __m512i mask1 = _v512_set_epu32(31, 15, 30, 14, 29, 13, 28, 12, 27, 11, 26, 10, 25, 9, 24, 8); + ab1 = v_int32x16(_mm512_permutex2var_epi32(a.val, mask1, b.val)); +} +inline void v_zip(const v_int64x8& a, const v_int64x8& b, v_int64x8& ab0, v_int64x8& ab1) +{ + __m512i mask0 = _v512_set_epu64(11, 3, 10, 2, 9, 1, 8, 0); + ab0 = v_int64x8(_mm512_permutex2var_epi64(a.val, mask0, b.val)); + __m512i mask1 = _v512_set_epu64(15, 7, 14, 6, 13, 5, 12, 4); + ab1 = v_int64x8(_mm512_permutex2var_epi64(a.val, mask1, b.val)); +} + +inline void v_zip(const v_uint8x64& a, const v_uint8x64& b, v_uint8x64& ab0, v_uint8x64& ab1) +{ + v_int8x64 i0, i1; + v_zip(v_reinterpret_as_s8(a), v_reinterpret_as_s8(b), i0, i1); + ab0 = v_reinterpret_as_u8(i0); + ab1 = v_reinterpret_as_u8(i1); +} +inline void v_zip(const v_uint16x32& a, const v_uint16x32& b, v_uint16x32& ab0, v_uint16x32& ab1) +{ + v_int16x32 i0, i1; + v_zip(v_reinterpret_as_s16(a), v_reinterpret_as_s16(b), i0, i1); + ab0 = v_reinterpret_as_u16(i0); + ab1 = v_reinterpret_as_u16(i1); +} +inline void v_zip(const v_uint32x16& a, const v_uint32x16& b, v_uint32x16& ab0, v_uint32x16& ab1) +{ + v_int32x16 i0, i1; + v_zip(v_reinterpret_as_s32(a), v_reinterpret_as_s32(b), i0, i1); + ab0 = v_reinterpret_as_u32(i0); + ab1 = v_reinterpret_as_u32(i1); +} +inline void v_zip(const v_uint64x8& a, const v_uint64x8& b, v_uint64x8& ab0, v_uint64x8& ab1) +{ + v_int64x8 i0, i1; + v_zip(v_reinterpret_as_s64(a), v_reinterpret_as_s64(b), i0, i1); + ab0 = v_reinterpret_as_u64(i0); + ab1 = v_reinterpret_as_u64(i1); +} +inline void v_zip(const v_float32x16& a, const v_float32x16& b, v_float32x16& ab0, v_float32x16& ab1) +{ + v_int32x16 i0, i1; + v_zip(v_reinterpret_as_s32(a), v_reinterpret_as_s32(b), i0, i1); + ab0 = v_reinterpret_as_f32(i0); + ab1 = v_reinterpret_as_f32(i1); +} +inline void v_zip(const v_float64x8& a, const v_float64x8& b, v_float64x8& ab0, v_float64x8& ab1) +{ + v_int64x8 i0, i1; + v_zip(v_reinterpret_as_s64(a), v_reinterpret_as_s64(b), i0, i1); + ab0 = v_reinterpret_as_f64(i0); + ab1 = v_reinterpret_as_f64(i1); +} + +#define OPENCV_HAL_IMPL_AVX512_COMBINE(_Tpvec, suffix) \ + inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(_v512_combine(_v512_extract_low(a.val), _v512_extract_low(b.val))); } \ + inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(_v512_insert(b.val, _v512_extract_high(a.val))); } \ + inline void v_recombine(const _Tpvec& a, const _Tpvec& b, \ + _Tpvec& c, _Tpvec& d) \ + { \ + c.val = _v512_combine(_v512_extract_low(a.val),_v512_extract_low(b.val)); \ + d.val = _v512_insert(b.val,_v512_extract_high(a.val)); \ + } + + +OPENCV_HAL_IMPL_AVX512_COMBINE(v_uint8x64, epi8) +OPENCV_HAL_IMPL_AVX512_COMBINE(v_int8x64, epi8) +OPENCV_HAL_IMPL_AVX512_COMBINE(v_uint16x32, epi16) +OPENCV_HAL_IMPL_AVX512_COMBINE(v_int16x32, epi16) +OPENCV_HAL_IMPL_AVX512_COMBINE(v_uint32x16, epi32) +OPENCV_HAL_IMPL_AVX512_COMBINE(v_int32x16, epi32) +OPENCV_HAL_IMPL_AVX512_COMBINE(v_uint64x8, epi64) +OPENCV_HAL_IMPL_AVX512_COMBINE(v_int64x8, epi64) +OPENCV_HAL_IMPL_AVX512_COMBINE(v_float32x16, ps) +OPENCV_HAL_IMPL_AVX512_COMBINE(v_float64x8, pd) + +////////// Arithmetic, bitwise and comparison operations ///////// + +/* Element-wise binary and unary operations */ + +/** Non-saturating arithmetics **/ +#define OPENCV_HAL_IMPL_AVX512_BIN_FUNC(func, _Tpvec, intrin) \ + inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(intrin(a.val, b.val)); } + +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_add_wrap, v_uint8x64, _mm512_add_epi8) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_add_wrap, v_int8x64, _mm512_add_epi8) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_add_wrap, v_uint16x32, _mm512_add_epi16) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_add_wrap, v_int16x32, _mm512_add_epi16) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_sub_wrap, v_uint8x64, _mm512_sub_epi8) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_sub_wrap, v_int8x64, _mm512_sub_epi8) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_sub_wrap, v_uint16x32, _mm512_sub_epi16) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_sub_wrap, v_int16x32, _mm512_sub_epi16) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_mul_wrap, v_uint16x32, _mm512_mullo_epi16) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_mul_wrap, v_int16x32, _mm512_mullo_epi16) + +inline v_uint8x64 v_mul_wrap(const v_uint8x64& a, const v_uint8x64& b) +{ + __m512i ad = _mm512_srai_epi16(a.val, 8); + __m512i bd = _mm512_srai_epi16(b.val, 8); + __m512i p0 = _mm512_mullo_epi16(a.val, b.val); // even + __m512i p1 = _mm512_slli_epi16(_mm512_mullo_epi16(ad, bd), 8); // odd + return v_uint8x64(_mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, p0, p1)); +} +inline v_int8x64 v_mul_wrap(const v_int8x64& a, const v_int8x64& b) +{ + return v_reinterpret_as_s8(v_mul_wrap(v_reinterpret_as_u8(a), v_reinterpret_as_u8(b))); +} + +#define OPENCV_HAL_IMPL_AVX512_BIN_OP(bin_op, _Tpvec, intrin) \ + inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(intrin(a.val, b.val)); } + +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_uint32x16, _mm512_add_epi32) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_uint32x16, _mm512_sub_epi32) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_int32x16, _mm512_add_epi32) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_int32x16, _mm512_sub_epi32) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_uint64x8, _mm512_add_epi64) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_uint64x8, _mm512_sub_epi64) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_int64x8, _mm512_add_epi64) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_int64x8, _mm512_sub_epi64) + +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_mul, v_uint32x16, _mm512_mullo_epi32) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_mul, v_int32x16, _mm512_mullo_epi32) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_mul, v_uint64x8, _mm512_mullo_epi64) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_mul, v_int64x8, _mm512_mullo_epi64) + +/** Saturating arithmetics **/ +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_uint8x64, _mm512_adds_epu8) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_uint8x64, _mm512_subs_epu8) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_int8x64, _mm512_adds_epi8) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_int8x64, _mm512_subs_epi8) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_uint16x32, _mm512_adds_epu16) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_uint16x32, _mm512_subs_epu16) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_int16x32, _mm512_adds_epi16) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_int16x32, _mm512_subs_epi16) + +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_float32x16, _mm512_add_ps) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_float32x16, _mm512_sub_ps) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_mul, v_float32x16, _mm512_mul_ps) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_div, v_float32x16, _mm512_div_ps) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_float64x8, _mm512_add_pd) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_float64x8, _mm512_sub_pd) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_mul, v_float64x8, _mm512_mul_pd) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_div, v_float64x8, _mm512_div_pd) + +// saturating multiply +inline v_uint8x64 v_mul(const v_uint8x64& a, const v_uint8x64& b) +{ + v_uint16x32 c, d; + v_mul_expand(a, b, c, d); + return v_pack(c, d); +} +inline v_int8x64 v_mul(const v_int8x64& a, const v_int8x64& b) +{ + v_int16x32 c, d; + v_mul_expand(a, b, c, d); + return v_pack(c, d); +} +inline v_uint16x32 v_mul(const v_uint16x32& a, const v_uint16x32& b) +{ + __m512i pl = _mm512_mullo_epi16(a.val, b.val); + __m512i ph = _mm512_mulhi_epu16(a.val, b.val); + __m512i p0 = _mm512_unpacklo_epi16(pl, ph); + __m512i p1 = _mm512_unpackhi_epi16(pl, ph); + + const __m512i m = _mm512_set1_epi32(65535); + return v_uint16x32(_mm512_packus_epi32(_mm512_min_epu32(p0, m), _mm512_min_epu32(p1, m))); +} +inline v_int16x32 v_mul(const v_int16x32& a, const v_int16x32& b) +{ + __m512i pl = _mm512_mullo_epi16(a.val, b.val); + __m512i ph = _mm512_mulhi_epi16(a.val, b.val); + __m512i p0 = _mm512_unpacklo_epi16(pl, ph); + __m512i p1 = _mm512_unpackhi_epi16(pl, ph); + return v_int16x32(_mm512_packs_epi32(p0, p1)); +} + +inline v_int16x32 v_mul_hi(const v_int16x32& a, const v_int16x32& b) { return v_int16x32(_mm512_mulhi_epi16(a.val, b.val)); } +inline v_uint16x32 v_mul_hi(const v_uint16x32& a, const v_uint16x32& b) { return v_uint16x32(_mm512_mulhi_epu16(a.val, b.val)); } + +// Multiply and expand +inline void v_mul_expand(const v_uint8x64& a, const v_uint8x64& b, + v_uint16x32& c, v_uint16x32& d) +{ + v_uint16x32 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c = v_mul_wrap(a0, b0); + d = v_mul_wrap(a1, b1); +} + +inline void v_mul_expand(const v_int8x64& a, const v_int8x64& b, + v_int16x32& c, v_int16x32& d) +{ + v_int16x32 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c = v_mul_wrap(a0, b0); + d = v_mul_wrap(a1, b1); +} + +inline void v_mul_expand(const v_int16x32& a, const v_int16x32& b, + v_int32x16& c, v_int32x16& d) +{ + v_int16x32 v0, v1; + v_zip(v_mul_wrap(a, b), v_mul_hi(a, b), v0, v1); + + c = v_reinterpret_as_s32(v0); + d = v_reinterpret_as_s32(v1); +} + +inline void v_mul_expand(const v_uint16x32& a, const v_uint16x32& b, + v_uint32x16& c, v_uint32x16& d) +{ + v_uint16x32 v0, v1; + v_zip(v_mul_wrap(a, b), v_mul_hi(a, b), v0, v1); + + c = v_reinterpret_as_u32(v0); + d = v_reinterpret_as_u32(v1); +} + +inline void v_mul_expand(const v_uint32x16& a, const v_uint32x16& b, + v_uint64x8& c, v_uint64x8& d) +{ + v_zip(v_uint64x8(_mm512_mul_epu32(a.val, b.val)), + v_uint64x8(_mm512_mul_epu32(_mm512_srli_epi64(a.val, 32), _mm512_srli_epi64(b.val, 32))), c, d); +} + +inline void v_mul_expand(const v_int32x16& a, const v_int32x16& b, + v_int64x8& c, v_int64x8& d) +{ + v_zip(v_int64x8(_mm512_mul_epi32(a.val, b.val)), + v_int64x8(_mm512_mul_epi32(_mm512_srli_epi64(a.val, 32), _mm512_srli_epi64(b.val, 32))), c, d); +} + +/** Bitwise shifts **/ +#define OPENCV_HAL_IMPL_AVX512_SHIFT_OP(_Tpuvec, _Tpsvec, suffix) \ + inline _Tpuvec v_shl(const _Tpuvec& a, int imm) \ + { return _Tpuvec(_mm512_slli_##suffix(a.val, imm)); } \ + inline _Tpsvec v_shl(const _Tpsvec& a, int imm) \ + { return _Tpsvec(_mm512_slli_##suffix(a.val, imm)); } \ + inline _Tpuvec v_shr(const _Tpuvec& a, int imm) \ + { return _Tpuvec(_mm512_srli_##suffix(a.val, imm)); } \ + inline _Tpsvec v_shr(const _Tpsvec& a, int imm) \ + { return _Tpsvec(_mm512_srai_##suffix(a.val, imm)); } \ + template \ + inline _Tpuvec v_shl(const _Tpuvec& a) \ + { return _Tpuvec(_mm512_slli_##suffix(a.val, imm)); } \ + template \ + inline _Tpsvec v_shl(const _Tpsvec& a) \ + { return _Tpsvec(_mm512_slli_##suffix(a.val, imm)); } \ + template \ + inline _Tpuvec v_shr(const _Tpuvec& a) \ + { return _Tpuvec(_mm512_srli_##suffix(a.val, imm)); } \ + template \ + inline _Tpsvec v_shr(const _Tpsvec& a) \ + { return _Tpsvec(_mm512_srai_##suffix(a.val, imm)); } + +OPENCV_HAL_IMPL_AVX512_SHIFT_OP(v_uint16x32, v_int16x32, epi16) +OPENCV_HAL_IMPL_AVX512_SHIFT_OP(v_uint32x16, v_int32x16, epi32) +OPENCV_HAL_IMPL_AVX512_SHIFT_OP(v_uint64x8, v_int64x8, epi64) + + +/** Bitwise logic **/ +#define OPENCV_HAL_IMPL_AVX512_LOGIC_OP(_Tpvec, suffix, not_const) \ + OPENCV_HAL_IMPL_AVX512_BIN_OP(v_and, _Tpvec, _mm512_and_##suffix) \ + OPENCV_HAL_IMPL_AVX512_BIN_OP(v_or, _Tpvec, _mm512_or_##suffix) \ + OPENCV_HAL_IMPL_AVX512_BIN_OP(v_xor, _Tpvec, _mm512_xor_##suffix) \ + inline _Tpvec v_not(const _Tpvec& a) \ + { return _Tpvec(_mm512_xor_##suffix(a.val, not_const)); } + +OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_uint8x64, si512, _mm512_set1_epi32(-1)) +OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_int8x64, si512, _mm512_set1_epi32(-1)) +OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_uint16x32, si512, _mm512_set1_epi32(-1)) +OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_int16x32, si512, _mm512_set1_epi32(-1)) +OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_uint32x16, si512, _mm512_set1_epi32(-1)) +OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_int32x16, si512, _mm512_set1_epi32(-1)) +OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_uint64x8, si512, _mm512_set1_epi64(-1)) +OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_int64x8, si512, _mm512_set1_epi64(-1)) +OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_float32x16, ps, _mm512_castsi512_ps(_mm512_set1_epi32(-1))) +OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_float64x8, pd, _mm512_castsi512_pd(_mm512_set1_epi32(-1))) + +/** Select **/ +#define OPENCV_HAL_IMPL_AVX512_SELECT(_Tpvec, suffix, zsuf) \ + inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(_mm512_mask_blend_##suffix(_mm512_cmp_##suffix##_mask(mask.val, _mm512_setzero_##zsuf(), _MM_CMPINT_EQ), a.val, b.val)); } + +OPENCV_HAL_IMPL_AVX512_SELECT(v_uint8x64, epi8, si512) +OPENCV_HAL_IMPL_AVX512_SELECT(v_int8x64, epi8, si512) +OPENCV_HAL_IMPL_AVX512_SELECT(v_uint16x32, epi16, si512) +OPENCV_HAL_IMPL_AVX512_SELECT(v_int16x32, epi16, si512) +OPENCV_HAL_IMPL_AVX512_SELECT(v_uint32x16, epi32, si512) +OPENCV_HAL_IMPL_AVX512_SELECT(v_int32x16, epi32, si512) +OPENCV_HAL_IMPL_AVX512_SELECT(v_uint64x8, epi64, si512) +OPENCV_HAL_IMPL_AVX512_SELECT(v_int64x8, epi64, si512) +OPENCV_HAL_IMPL_AVX512_SELECT(v_float32x16, ps, ps) +OPENCV_HAL_IMPL_AVX512_SELECT(v_float64x8, pd, pd) + +/** Comparison **/ +#define OPENCV_HAL_IMPL_AVX512_CMP_INT(bin_op, imm8, _Tpvec, sufcmp, sufset, tval) \ + inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(_mm512_maskz_set1_##sufset(_mm512_cmp_##sufcmp##_mask(a.val, b.val, imm8), tval)); } + +#define OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(_Tpvec, sufcmp, sufset, tval) \ + OPENCV_HAL_IMPL_AVX512_CMP_INT(v_eq, _MM_CMPINT_EQ, _Tpvec, sufcmp, sufset, tval) \ + OPENCV_HAL_IMPL_AVX512_CMP_INT(v_ne, _MM_CMPINT_NE, _Tpvec, sufcmp, sufset, tval) \ + OPENCV_HAL_IMPL_AVX512_CMP_INT(v_lt, _MM_CMPINT_LT, _Tpvec, sufcmp, sufset, tval) \ + OPENCV_HAL_IMPL_AVX512_CMP_INT(v_gt, _MM_CMPINT_NLE, _Tpvec, sufcmp, sufset, tval) \ + OPENCV_HAL_IMPL_AVX512_CMP_INT(v_le, _MM_CMPINT_LE, _Tpvec, sufcmp, sufset, tval) \ + OPENCV_HAL_IMPL_AVX512_CMP_INT(v_ge, _MM_CMPINT_NLT, _Tpvec, sufcmp, sufset, tval) + +OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_uint8x64, epu8, epi8, (char)-1) +OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_int8x64, epi8, epi8, (char)-1) +OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_uint16x32, epu16, epi16, (short)-1) +OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_int16x32, epi16, epi16, (short)-1) +OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_uint32x16, epu32, epi32, (int)-1) +OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_int32x16, epi32, epi32, (int)-1) +OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_uint64x8, epu64, epi64, (int64)-1) +OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_int64x8, epi64, epi64, (int64)-1) + +#define OPENCV_HAL_IMPL_AVX512_CMP_FLT(bin_op, imm8, _Tpvec, sufcmp, sufset, tval) \ + inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(_mm512_castsi512_##sufcmp(_mm512_maskz_set1_##sufset(_mm512_cmp_##sufcmp##_mask(a.val, b.val, imm8), tval))); } + +#define OPENCV_HAL_IMPL_AVX512_CMP_OP_FLT(_Tpvec, sufcmp, sufset, tval) \ + OPENCV_HAL_IMPL_AVX512_CMP_FLT(v_eq, _CMP_EQ_OQ, _Tpvec, sufcmp, sufset, tval) \ + OPENCV_HAL_IMPL_AVX512_CMP_FLT(v_ne, _CMP_NEQ_OQ, _Tpvec, sufcmp, sufset, tval) \ + OPENCV_HAL_IMPL_AVX512_CMP_FLT(v_lt, _CMP_LT_OQ, _Tpvec, sufcmp, sufset, tval) \ + OPENCV_HAL_IMPL_AVX512_CMP_FLT(v_gt, _CMP_GT_OQ, _Tpvec, sufcmp, sufset, tval) \ + OPENCV_HAL_IMPL_AVX512_CMP_FLT(v_le, _CMP_LE_OQ, _Tpvec, sufcmp, sufset, tval) \ + OPENCV_HAL_IMPL_AVX512_CMP_FLT(v_ge, _CMP_GE_OQ, _Tpvec, sufcmp, sufset, tval) + +OPENCV_HAL_IMPL_AVX512_CMP_OP_FLT(v_float32x16, ps, epi32, (int)-1) +OPENCV_HAL_IMPL_AVX512_CMP_OP_FLT(v_float64x8, pd, epi64, (int64)-1) + +inline v_float32x16 v_not_nan(const v_float32x16& a) +{ return v_float32x16(_mm512_castsi512_ps(_mm512_maskz_set1_epi32(_mm512_cmp_ps_mask(a.val, a.val, _CMP_ORD_Q), (int)-1))); } +inline v_float64x8 v_not_nan(const v_float64x8& a) +{ return v_float64x8(_mm512_castsi512_pd(_mm512_maskz_set1_epi64(_mm512_cmp_pd_mask(a.val, a.val, _CMP_ORD_Q), (int64)-1))); } + +/** min/max **/ +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_uint8x64, _mm512_min_epu8) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_uint8x64, _mm512_max_epu8) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_int8x64, _mm512_min_epi8) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_int8x64, _mm512_max_epi8) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_uint16x32, _mm512_min_epu16) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_uint16x32, _mm512_max_epu16) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_int16x32, _mm512_min_epi16) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_int16x32, _mm512_max_epi16) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_uint32x16, _mm512_min_epu32) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_uint32x16, _mm512_max_epu32) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_int32x16, _mm512_min_epi32) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_int32x16, _mm512_max_epi32) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_uint64x8, _mm512_min_epu64) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_uint64x8, _mm512_max_epu64) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_int64x8, _mm512_min_epi64) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_int64x8, _mm512_max_epi64) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_float32x16, _mm512_min_ps) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_float32x16, _mm512_max_ps) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_float64x8, _mm512_min_pd) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_float64x8, _mm512_max_pd) + +/** Rotate **/ +namespace { + template + struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64&, const v_int8x64&) { return v_int8x64(); }}; + template + struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64& a, const v_int8x64& b) + { + return v_int8x64(_mm512_or_si512(_mm512_srli_epi32(_mm512_alignr_epi32(b.val, a.val, imm32 ), imm4 *8), + _mm512_slli_epi32(_mm512_alignr_epi32(b.val, a.val, imm32 + 1), (4-imm4)*8))); + }}; + template + struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64& a, const v_int8x64& b) + { + return v_int8x64(_mm512_or_si512(_mm512_srli_epi32(_mm512_alignr_epi32(b.val, a.val, 15), imm4 *8), + _mm512_slli_epi32( b.val, (4-imm4)*8))); + }}; + template + struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64&, const v_int8x64& b) + { + return v_int8x64(_mm512_or_si512(_mm512_srli_epi32(_mm512_alignr_epi32(_mm512_setzero_si512(), b.val, imm32 - 16), imm4 *8), + _mm512_slli_epi32(_mm512_alignr_epi32(_mm512_setzero_si512(), b.val, imm32 - 15), (4-imm4)*8))); + }}; + template + struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64&, const v_int8x64& b) + { return v_int8x64(_mm512_srli_epi32(_mm512_alignr_epi32(_mm512_setzero_si512(), b.val, 15), imm4*8)); }}; + template + struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64& a, const v_int8x64& b) + { return v_int8x64(_mm512_alignr_epi32(b.val, a.val, imm32)); }}; + template<> + struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64& a, const v_int8x64&) { return a; }}; + template + struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64&, const v_int8x64& b) + { return v_int8x64(_mm512_alignr_epi32(_mm512_setzero_si512(), b.val, imm32 - 16)); }}; + template<> + struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64&, const v_int8x64& b) { return b; }}; + template<> + struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64&, const v_int8x64&) { return v_int8x64(); }}; +} +template inline v_int8x64 v_rotate_right(const v_int8x64& a, const v_int8x64& b) +{ + return imm >= 128 ? v_int8x64() : +#if CV_AVX_512VBMI + v_int8x64(_mm512_permutex2var_epi8(a.val, + _v512_set_epu8(0x3f + imm, 0x3e + imm, 0x3d + imm, 0x3c + imm, 0x3b + imm, 0x3a + imm, 0x39 + imm, 0x38 + imm, + 0x37 + imm, 0x36 + imm, 0x35 + imm, 0x34 + imm, 0x33 + imm, 0x32 + imm, 0x31 + imm, 0x30 + imm, + 0x2f + imm, 0x2e + imm, 0x2d + imm, 0x2c + imm, 0x2b + imm, 0x2a + imm, 0x29 + imm, 0x28 + imm, + 0x27 + imm, 0x26 + imm, 0x25 + imm, 0x24 + imm, 0x23 + imm, 0x22 + imm, 0x21 + imm, 0x20 + imm, + 0x1f + imm, 0x1e + imm, 0x1d + imm, 0x1c + imm, 0x1b + imm, 0x1a + imm, 0x19 + imm, 0x18 + imm, + 0x17 + imm, 0x16 + imm, 0x15 + imm, 0x14 + imm, 0x13 + imm, 0x12 + imm, 0x11 + imm, 0x10 + imm, + 0x0f + imm, 0x0e + imm, 0x0d + imm, 0x0c + imm, 0x0b + imm, 0x0a + imm, 0x09 + imm, 0x08 + imm, + 0x07 + imm, 0x06 + imm, 0x05 + imm, 0x04 + imm, 0x03 + imm, 0x02 + imm, 0x01 + imm, 0x00 + imm), b.val)); +#else + _v_rotate_right 15), imm/4>::eval(a, b); +#endif +} +template +inline v_int8x64 v_rotate_left(const v_int8x64& a, const v_int8x64& b) +{ + if (imm == 0) return a; + if (imm == 64) return b; + if (imm >= 128) return v_int8x64(); +#if CV_AVX_512VBMI + return v_int8x64(_mm512_permutex2var_epi8(b.val, + _v512_set_epi8(0x7f - imm,0x7e - imm,0x7d - imm,0x7c - imm,0x7b - imm,0x7a - imm,0x79 - imm,0x78 - imm, + 0x77 - imm,0x76 - imm,0x75 - imm,0x74 - imm,0x73 - imm,0x72 - imm,0x71 - imm,0x70 - imm, + 0x6f - imm,0x6e - imm,0x6d - imm,0x6c - imm,0x6b - imm,0x6a - imm,0x69 - imm,0x68 - imm, + 0x67 - imm,0x66 - imm,0x65 - imm,0x64 - imm,0x63 - imm,0x62 - imm,0x61 - imm,0x60 - imm, + 0x5f - imm,0x5e - imm,0x5d - imm,0x5c - imm,0x5b - imm,0x5a - imm,0x59 - imm,0x58 - imm, + 0x57 - imm,0x56 - imm,0x55 - imm,0x54 - imm,0x53 - imm,0x52 - imm,0x51 - imm,0x50 - imm, + 0x4f - imm,0x4e - imm,0x4d - imm,0x4c - imm,0x4b - imm,0x4a - imm,0x49 - imm,0x48 - imm, + 0x47 - imm,0x46 - imm,0x45 - imm,0x44 - imm,0x43 - imm,0x42 - imm,0x41 - imm,0x40 - imm), a.val)); +#else + return imm < 64 ? v_rotate_right<64 - imm>(b, a) : v_rotate_right<128 - imm>(v512_setzero_s8(), b); +#endif +} +template +inline v_int8x64 v_rotate_right(const v_int8x64& a) +{ + if (imm == 0) return a; + if (imm >= 64) return v_int8x64(); +#if CV_AVX_512VBMI + return v_int8x64(_mm512_maskz_permutexvar_epi8(0xFFFFFFFFFFFFFFFF >> imm, + _v512_set_epu8(0x3f + imm,0x3e + imm,0x3d + imm,0x3c + imm,0x3b + imm,0x3a + imm,0x39 + imm,0x38 + imm, + 0x37 + imm,0x36 + imm,0x35 + imm,0x34 + imm,0x33 + imm,0x32 + imm,0x31 + imm,0x30 + imm, + 0x2f + imm,0x2e + imm,0x2d + imm,0x2c + imm,0x2b + imm,0x2a + imm,0x29 + imm,0x28 + imm, + 0x27 + imm,0x26 + imm,0x25 + imm,0x24 + imm,0x23 + imm,0x22 + imm,0x21 + imm,0x20 + imm, + 0x1f + imm,0x1e + imm,0x1d + imm,0x1c + imm,0x1b + imm,0x1a + imm,0x19 + imm,0x18 + imm, + 0x17 + imm,0x16 + imm,0x15 + imm,0x14 + imm,0x13 + imm,0x12 + imm,0x11 + imm,0x10 + imm, + 0x0f + imm,0x0e + imm,0x0d + imm,0x0c + imm,0x0b + imm,0x0a + imm,0x09 + imm,0x08 + imm, + 0x07 + imm,0x06 + imm,0x05 + imm,0x04 + imm,0x03 + imm,0x02 + imm,0x01 + imm,0x00 + imm), a.val)); +#else + return v_rotate_right(a, v512_setzero_s8()); +#endif +} +template +inline v_int8x64 v_rotate_left(const v_int8x64& a) +{ + if (imm == 0) return a; + if (imm >= 64) return v_int8x64(); +#if CV_AVX_512VBMI + return v_int8x64(_mm512_maskz_permutexvar_epi8(0xFFFFFFFFFFFFFFFF << imm, + _v512_set_epi8(0x3f - imm,0x3e - imm,0x3d - imm,0x3c - imm,0x3b - imm,0x3a - imm,0x39 - imm,0x38 - imm, + 0x37 - imm,0x36 - imm,0x35 - imm,0x34 - imm,0x33 - imm,0x32 - imm,0x31 - imm,0x30 - imm, + 0x2f - imm,0x2e - imm,0x2d - imm,0x2c - imm,0x2b - imm,0x2a - imm,0x29 - imm,0x28 - imm, + 0x27 - imm,0x26 - imm,0x25 - imm,0x24 - imm,0x23 - imm,0x22 - imm,0x21 - imm,0x20 - imm, + 0x1f - imm,0x1e - imm,0x1d - imm,0x1c - imm,0x1b - imm,0x1a - imm,0x19 - imm,0x18 - imm, + 0x17 - imm,0x16 - imm,0x15 - imm,0x14 - imm,0x13 - imm,0x12 - imm,0x11 - imm,0x10 - imm, + 0x0f - imm,0x0e - imm,0x0d - imm,0x0c - imm,0x0b - imm,0x0a - imm,0x09 - imm,0x08 - imm, + 0x07 - imm,0x06 - imm,0x05 - imm,0x04 - imm,0x03 - imm,0x02 - imm,0x01 - imm,0x00 - imm), a.val)); +#else + return v_rotate_right<64 - imm>(v512_setzero_s8(), a); +#endif +} + +#define OPENCV_HAL_IMPL_AVX512_ROTATE_PM(_Tpvec, suffix) \ +template inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ +{ return v_reinterpret_as_##suffix(v_rotate_left(v_reinterpret_as_s8(a), v_reinterpret_as_s8(b))); } \ +template inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ +{ return v_reinterpret_as_##suffix(v_rotate_right(v_reinterpret_as_s8(a), v_reinterpret_as_s8(b))); } \ +template inline _Tpvec v_rotate_left(const _Tpvec& a) \ +{ return v_reinterpret_as_##suffix(v_rotate_left(v_reinterpret_as_s8(a))); } \ +template inline _Tpvec v_rotate_right(const _Tpvec& a) \ +{ return v_reinterpret_as_##suffix(v_rotate_right(v_reinterpret_as_s8(a))); } + +#define OPENCV_HAL_IMPL_AVX512_ROTATE_EC(_Tpvec, suffix) \ +template \ +inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ +{ \ + enum { SHIFT2 = (_Tpvec::nlanes - imm) }; \ + enum { MASK = ((1 << _Tpvec::nlanes) - 1) }; \ + if (imm == 0) return a; \ + if (imm == _Tpvec::nlanes) return b; \ + if (imm >= 2*_Tpvec::nlanes) return _Tpvec::zero(); \ + return _Tpvec(_mm512_mask_expand_##suffix(_mm512_maskz_compress_##suffix((MASK << SHIFT2)&MASK, b.val), (MASK << (imm))&MASK, a.val)); \ +} \ +template \ +inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ +{ \ + enum { SHIFT2 = (_Tpvec::nlanes - imm) }; \ + enum { MASK = ((1 << _Tpvec::nlanes) - 1) }; \ + if (imm == 0) return a; \ + if (imm == _Tpvec::nlanes) return b; \ + if (imm >= 2*_Tpvec::nlanes) return _Tpvec::zero(); \ + return _Tpvec(_mm512_mask_expand_##suffix(_mm512_maskz_compress_##suffix((MASK << (imm))&MASK, a.val), (MASK << SHIFT2)&MASK, b.val)); \ +} \ +template \ +inline _Tpvec v_rotate_left(const _Tpvec& a) \ +{ \ + if (imm == 0) return a; \ + if (imm >= _Tpvec::nlanes) return _Tpvec::zero(); \ + return _Tpvec(_mm512_maskz_expand_##suffix((1 << _Tpvec::nlanes) - (1 << (imm)), a.val)); \ +} \ +template \ +inline _Tpvec v_rotate_right(const _Tpvec& a) \ +{ \ + if (imm == 0) return a; \ + if (imm >= _Tpvec::nlanes) return _Tpvec::zero(); \ + return _Tpvec(_mm512_maskz_compress_##suffix((1 << _Tpvec::nlanes) - (1 << (imm)), a.val)); \ +} + +OPENCV_HAL_IMPL_AVX512_ROTATE_PM(v_uint8x64, u8) +OPENCV_HAL_IMPL_AVX512_ROTATE_PM(v_uint16x32, u16) +OPENCV_HAL_IMPL_AVX512_ROTATE_PM(v_int16x32, s16) +OPENCV_HAL_IMPL_AVX512_ROTATE_EC(v_uint32x16, epi32) +OPENCV_HAL_IMPL_AVX512_ROTATE_EC(v_int32x16, epi32) +OPENCV_HAL_IMPL_AVX512_ROTATE_EC(v_uint64x8, epi64) +OPENCV_HAL_IMPL_AVX512_ROTATE_EC(v_int64x8, epi64) +OPENCV_HAL_IMPL_AVX512_ROTATE_EC(v_float32x16, ps) +OPENCV_HAL_IMPL_AVX512_ROTATE_EC(v_float64x8, pd) + +/** Reverse **/ +inline v_uint8x64 v_reverse(const v_uint8x64 &a) +{ +#if CV_AVX_512VBMI + static const __m512i perm = _mm512_set_epi32( + 0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f, + 0x10111213, 0x14151617, 0x18191a1b, 0x1c1d1e1f, + 0x20212223, 0x24252627, 0x28292a2b, 0x2c2d2e2f, + 0x30313233, 0x34353637, 0x38393a3b, 0x3c3d3e3f); + return v_uint8x64(_mm512_permutexvar_epi8(perm, a.val)); +#else + static const __m512i shuf = _mm512_set_epi32( + 0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f, + 0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f, + 0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f, + 0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f); + static const __m512i perm = _mm512_set_epi64(1, 0, 3, 2, 5, 4, 7, 6); + __m512i vec = _mm512_shuffle_epi8(a.val, shuf); + return v_uint8x64(_mm512_permutexvar_epi64(perm, vec)); +#endif +} + +inline v_int8x64 v_reverse(const v_int8x64 &a) +{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } + +inline v_uint16x32 v_reverse(const v_uint16x32 &a) +{ +#if CV_AVX_512VBMI + static const __m512i perm = _mm512_set_epi32( + 0x00000001, 0x00020003, 0x00040005, 0x00060007, + 0x00080009, 0x000a000b, 0x000c000d, 0x000e000f, + 0x00100011, 0x00120013, 0x00140015, 0x00160017, + 0x00180019, 0x001a001b, 0x001c001d, 0x001e001f); + return v_uint16x32(_mm512_permutexvar_epi16(perm, a.val)); +#else + static const __m512i shuf = _mm512_set_epi32( + 0x01000302, 0x05040706, 0x09080b0a, 0x0d0c0f0e, + 0x01000302, 0x05040706, 0x09080b0a, 0x0d0c0f0e, + 0x01000302, 0x05040706, 0x09080b0a, 0x0d0c0f0e, + 0x01000302, 0x05040706, 0x09080b0a, 0x0d0c0f0e); + static const __m512i perm = _mm512_set_epi64(1, 0, 3, 2, 5, 4, 7, 6); + __m512i vec = _mm512_shuffle_epi8(a.val, shuf); + return v_uint16x32(_mm512_permutexvar_epi64(perm, vec)); +#endif +} + +inline v_int16x32 v_reverse(const v_int16x32 &a) +{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } + +inline v_uint32x16 v_reverse(const v_uint32x16 &a) +{ + static const __m512i perm = _mm512_set_epi32(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,14, 15); + return v_uint32x16(_mm512_permutexvar_epi32(perm, a.val)); +} + +inline v_int32x16 v_reverse(const v_int32x16 &a) +{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_float32x16 v_reverse(const v_float32x16 &a) +{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_uint64x8 v_reverse(const v_uint64x8 &a) +{ + static const __m512i perm = _mm512_set_epi64(0, 1, 2, 3, 4, 5, 6, 7); + return v_uint64x8(_mm512_permutexvar_epi64(perm, a.val)); +} + +inline v_int64x8 v_reverse(const v_int64x8 &a) +{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } + +inline v_float64x8 v_reverse(const v_float64x8 &a) +{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } + +////////// Reduce ///////// + +/** Reduce **/ +#define OPENCV_HAL_IMPL_AVX512_REDUCE_ADD64(a, b) a + b +#define OPENCV_HAL_IMPL_AVX512_REDUCE_8(sctype, func, _Tpvec, ifunc, scop) \ + inline sctype v_reduce_##func(const _Tpvec& a) \ + { __m256i half = _mm256_##ifunc(_v512_extract_low(a.val), _v512_extract_high(a.val)); \ + sctype CV_DECL_ALIGNED(64) idx[2]; \ + _mm_store_si128((__m128i*)idx, _mm_##ifunc(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1))); \ + return scop(idx[0], idx[1]); } +OPENCV_HAL_IMPL_AVX512_REDUCE_8(uint64, min, v_uint64x8, min_epu64, min) +OPENCV_HAL_IMPL_AVX512_REDUCE_8(uint64, max, v_uint64x8, max_epu64, max) +OPENCV_HAL_IMPL_AVX512_REDUCE_8(uint64, sum, v_uint64x8, add_epi64, OPENCV_HAL_IMPL_AVX512_REDUCE_ADD64) +OPENCV_HAL_IMPL_AVX512_REDUCE_8(int64, min, v_int64x8, min_epi64, min) +OPENCV_HAL_IMPL_AVX512_REDUCE_8(int64, max, v_int64x8, max_epi64, max) +OPENCV_HAL_IMPL_AVX512_REDUCE_8(int64, sum, v_int64x8, add_epi64, OPENCV_HAL_IMPL_AVX512_REDUCE_ADD64) + +#define OPENCV_HAL_IMPL_AVX512_REDUCE_8F(func, ifunc, scop) \ + inline double v_reduce_##func(const v_float64x8& a) \ + { __m256d half = _mm256_##ifunc(_v512_extract_low(a.val), _v512_extract_high(a.val)); \ + double CV_DECL_ALIGNED(64) idx[2]; \ + _mm_store_pd(idx, _mm_##ifunc(_mm256_castpd256_pd128(half), _mm256_extractf128_pd(half, 1))); \ + return scop(idx[0], idx[1]); } +OPENCV_HAL_IMPL_AVX512_REDUCE_8F(min, min_pd, min) +OPENCV_HAL_IMPL_AVX512_REDUCE_8F(max, max_pd, max) +OPENCV_HAL_IMPL_AVX512_REDUCE_8F(sum, add_pd, OPENCV_HAL_IMPL_AVX512_REDUCE_ADD64) + +#define OPENCV_HAL_IMPL_AVX512_REDUCE_16(sctype, func, _Tpvec, ifunc) \ + inline sctype v_reduce_##func(const _Tpvec& a) \ + { __m256i half = _mm256_##ifunc(_v512_extract_low(a.val), _v512_extract_high(a.val)); \ + __m128i quarter = _mm_##ifunc(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1)); \ + quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 8)); \ + quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 4)); \ + return (sctype)_mm_cvtsi128_si32(quarter); } +OPENCV_HAL_IMPL_AVX512_REDUCE_16(uint, min, v_uint32x16, min_epu32) +OPENCV_HAL_IMPL_AVX512_REDUCE_16(uint, max, v_uint32x16, max_epu32) +OPENCV_HAL_IMPL_AVX512_REDUCE_16(int, min, v_int32x16, min_epi32) +OPENCV_HAL_IMPL_AVX512_REDUCE_16(int, max, v_int32x16, max_epi32) + +#define OPENCV_HAL_IMPL_AVX512_REDUCE_16F(func, ifunc) \ + inline float v_reduce_##func(const v_float32x16& a) \ + { __m256 half = _mm256_##ifunc(_v512_extract_low(a.val), _v512_extract_high(a.val)); \ + __m128 quarter = _mm_##ifunc(_mm256_castps256_ps128(half), _mm256_extractf128_ps(half, 1)); \ + quarter = _mm_##ifunc(quarter, _mm_permute_ps(quarter, _MM_SHUFFLE(0, 0, 3, 2))); \ + quarter = _mm_##ifunc(quarter, _mm_permute_ps(quarter, _MM_SHUFFLE(0, 0, 0, 1))); \ + return _mm_cvtss_f32(quarter); } +OPENCV_HAL_IMPL_AVX512_REDUCE_16F(min, min_ps) +OPENCV_HAL_IMPL_AVX512_REDUCE_16F(max, max_ps) + +inline float v_reduce_sum(const v_float32x16& a) +{ + __m256 half = _mm256_add_ps(_v512_extract_low(a.val), _v512_extract_high(a.val)); + __m128 quarter = _mm_add_ps(_mm256_castps256_ps128(half), _mm256_extractf128_ps(half, 1)); + quarter = _mm_hadd_ps(quarter, quarter); + return _mm_cvtss_f32(_mm_hadd_ps(quarter, quarter)); +} +inline int v_reduce_sum(const v_int32x16& a) +{ + __m256i half = _mm256_add_epi32(_v512_extract_low(a.val), _v512_extract_high(a.val)); + __m128i quarter = _mm_add_epi32(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1)); + quarter = _mm_hadd_epi32(quarter, quarter); + return _mm_cvtsi128_si32(_mm_hadd_epi32(quarter, quarter)); +} +inline uint v_reduce_sum(const v_uint32x16& a) +{ return (uint)v_reduce_sum(v_reinterpret_as_s32(a)); } + +#define OPENCV_HAL_IMPL_AVX512_REDUCE_32(sctype, func, _Tpvec, ifunc) \ + inline sctype v_reduce_##func(const _Tpvec& a) \ + { __m256i half = _mm256_##ifunc(_v512_extract_low(a.val), _v512_extract_high(a.val)); \ + __m128i quarter = _mm_##ifunc(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1)); \ + quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 8)); \ + quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 4)); \ + quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 2)); \ + return (sctype)_mm_cvtsi128_si32(quarter); } +OPENCV_HAL_IMPL_AVX512_REDUCE_32(ushort, min, v_uint16x32, min_epu16) +OPENCV_HAL_IMPL_AVX512_REDUCE_32(ushort, max, v_uint16x32, max_epu16) +OPENCV_HAL_IMPL_AVX512_REDUCE_32(short, min, v_int16x32, min_epi16) +OPENCV_HAL_IMPL_AVX512_REDUCE_32(short, max, v_int16x32, max_epi16) + +inline int v_reduce_sum(const v_int16x32& a) +{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } +inline uint v_reduce_sum(const v_uint16x32& a) +{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } + +#define OPENCV_HAL_IMPL_AVX512_REDUCE_64(sctype, func, _Tpvec, ifunc) \ + inline sctype v_reduce_##func(const _Tpvec& a) \ + { __m256i half = _mm256_##ifunc(_v512_extract_low(a.val), _v512_extract_high(a.val)); \ + __m128i quarter = _mm_##ifunc(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1)); \ + quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 8)); \ + quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 4)); \ + quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 2)); \ + quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 1)); \ + return (sctype)_mm_cvtsi128_si32(quarter); } +OPENCV_HAL_IMPL_AVX512_REDUCE_64(uchar, min, v_uint8x64, min_epu8) +OPENCV_HAL_IMPL_AVX512_REDUCE_64(uchar, max, v_uint8x64, max_epu8) +OPENCV_HAL_IMPL_AVX512_REDUCE_64(schar, min, v_int8x64, min_epi8) +OPENCV_HAL_IMPL_AVX512_REDUCE_64(schar, max, v_int8x64, max_epi8) + +#define OPENCV_HAL_IMPL_AVX512_REDUCE_64_SUM(sctype, _Tpvec, suffix) \ + inline sctype v_reduce_sum(const _Tpvec& a) \ + { __m512i a16 = _mm512_add_epi16(_mm512_cvt##suffix##_epi16(_v512_extract_low(a.val)), \ + _mm512_cvt##suffix##_epi16(_v512_extract_high(a.val))); \ + a16 = _mm512_cvtepi16_epi32(_mm256_add_epi16(_v512_extract_low(a16), _v512_extract_high(a16))); \ + __m256i a8 = _mm256_add_epi32(_v512_extract_low(a16), _v512_extract_high(a16)); \ + __m128i a4 = _mm_add_epi32(_mm256_castsi256_si128(a8), _mm256_extracti128_si256(a8, 1)); \ + a4 = _mm_hadd_epi32(a4, a4); \ + return (sctype)_mm_cvtsi128_si32(_mm_hadd_epi32(a4, a4)); } +OPENCV_HAL_IMPL_AVX512_REDUCE_64_SUM(uint, v_uint8x64, epu8) +OPENCV_HAL_IMPL_AVX512_REDUCE_64_SUM(int, v_int8x64, epi8) + +inline v_float32x16 v_reduce_sum4(const v_float32x16& a, const v_float32x16& b, + const v_float32x16& c, const v_float32x16& d) +{ + __m256 abl = _mm256_hadd_ps(_v512_extract_low(a.val), _v512_extract_low(b.val)); + __m256 abh = _mm256_hadd_ps(_v512_extract_high(a.val), _v512_extract_high(b.val)); + __m256 cdl = _mm256_hadd_ps(_v512_extract_low(c.val), _v512_extract_low(d.val)); + __m256 cdh = _mm256_hadd_ps(_v512_extract_high(c.val), _v512_extract_high(d.val)); + return v_float32x16(_v512_combine(_mm256_hadd_ps(abl, cdl), _mm256_hadd_ps(abh, cdh))); +} + +inline unsigned v_reduce_sad(const v_uint8x64& a, const v_uint8x64& b) +{ + __m512i val = _mm512_sad_epu8(a.val, b.val); + __m256i half = _mm256_add_epi32(_v512_extract_low(val), _v512_extract_high(val)); + __m128i quarter = _mm_add_epi32(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1)); + return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(quarter, _mm_unpackhi_epi64(quarter, quarter))); +} +inline unsigned v_reduce_sad(const v_int8x64& a, const v_int8x64& b) +{ + __m512i val = _mm512_set1_epi8(-128); + val = _mm512_sad_epu8(_mm512_add_epi8(a.val, val), _mm512_add_epi8(b.val, val)); + __m256i half = _mm256_add_epi32(_v512_extract_low(val), _v512_extract_high(val)); + __m128i quarter = _mm_add_epi32(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1)); + return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(quarter, _mm_unpackhi_epi64(quarter, quarter))); +} +inline unsigned v_reduce_sad(const v_uint16x32& a, const v_uint16x32& b) +{ return v_reduce_sum(v_add_wrap(v_sub(a, b), v_sub(b, a))); } +inline unsigned v_reduce_sad(const v_int16x32& a, const v_int16x32& b) +{ return v_reduce_sum(v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b)))); } +inline unsigned v_reduce_sad(const v_uint32x16& a, const v_uint32x16& b) +{ return v_reduce_sum(v_sub(v_max(a, b), v_min(a, b))); } +inline unsigned v_reduce_sad(const v_int32x16& a, const v_int32x16& b) +{ return v_reduce_sum(v_reinterpret_as_u32(v_sub(v_max(a, b), v_min(a, b)))); } +inline float v_reduce_sad(const v_float32x16& a, const v_float32x16& b) +{ return v_reduce_sum(v_and(v_sub(a, b), v_float32x16(_mm512_castsi512_ps(_mm512_set1_epi32(0x7fffffff))))); } +inline double v_reduce_sad(const v_float64x8& a, const v_float64x8& b) +{ return v_reduce_sum(v_and(v_sub(a, b), v_float64x8(_mm512_castsi512_pd(_mm512_set1_epi64(0x7fffffffffffffff))))); } + +/** Popcount **/ +inline v_uint8x64 v_popcount(const v_int8x64& a) +{ +#if CV_AVX_512BITALG + return v_uint8x64(_mm512_popcnt_epi8(a.val)); +#elif CV_AVX_512VBMI + __m512i _popcnt_table0 = _v512_set_epu8(7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3, + 5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1, + 5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1, + 4, 3, 3, 2, 3, 2, 2, 1, 3, 2, 2, 1, 2, 1, 1, 0); + __m512i _popcnt_table1 = _v512_set_epu8(7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3, + 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, + 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, + 5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1); + return v_uint8x64(_mm512_sub_epi8(_mm512_permutex2var_epi8(_popcnt_table0, a.val, _popcnt_table1), _mm512_movm_epi8(_mm512_movepi8_mask(a.val)))); +#else + __m512i _popcnt_table = _mm512_set4_epi32(0x04030302, 0x03020201, 0x03020201, 0x02010100); + __m512i _popcnt_mask = _mm512_set1_epi8(0x0F); + + return v_uint8x64(_mm512_add_epi8(_mm512_shuffle_epi8(_popcnt_table, _mm512_and_si512( a.val, _popcnt_mask)), + _mm512_shuffle_epi8(_popcnt_table, _mm512_and_si512(_mm512_srli_epi16(a.val, 4), _popcnt_mask)))); +#endif +} +inline v_uint16x32 v_popcount(const v_int16x32& a) +{ +#if CV_AVX_512BITALG + return v_uint16x32(_mm512_popcnt_epi16(a.val)); +#elif CV_AVX_512VPOPCNTDQ + __m512i zero = _mm512_setzero_si512(); + return v_uint16x32(_mm512_packs_epi32(_mm512_popcnt_epi32(_mm512_unpacklo_epi16(a.val, zero)), + _mm512_popcnt_epi32(_mm512_unpackhi_epi16(a.val, zero)))); +#else + v_uint8x64 p = v_popcount(v_reinterpret_as_s8(a)); + p = v_add(p, v_rotate_right<1>(p)); + return v_and(v_reinterpret_as_u16(p), v512_setall_u16(0x00ff)); +#endif +} +inline v_uint32x16 v_popcount(const v_int32x16& a) +{ +#if CV_AVX_512VPOPCNTDQ + return v_uint32x16(_mm512_popcnt_epi32(a.val)); +#else + v_uint8x64 p = v_popcount(v_reinterpret_as_s8(a)); + p = v_add(p, v_rotate_right<1>(p)); + p = v_add(p, v_rotate_right<2>(p)); + return v_and(v_reinterpret_as_u32(p), v512_setall_u32(0x000000ff)); +#endif +} +inline v_uint64x8 v_popcount(const v_int64x8& a) +{ +#if CV_AVX_512VPOPCNTDQ + return v_uint64x8(_mm512_popcnt_epi64(a.val)); +#else + return v_uint64x8(_mm512_sad_epu8(v_popcount(v_reinterpret_as_s8(a)).val, _mm512_setzero_si512())); +#endif +} + + +inline v_uint8x64 v_popcount(const v_uint8x64& a) { return v_popcount(v_reinterpret_as_s8 (a)); } +inline v_uint16x32 v_popcount(const v_uint16x32& a) { return v_popcount(v_reinterpret_as_s16(a)); } +inline v_uint32x16 v_popcount(const v_uint32x16& a) { return v_popcount(v_reinterpret_as_s32(a)); } +inline v_uint64x8 v_popcount(const v_uint64x8& a) { return v_popcount(v_reinterpret_as_s64(a)); } + + +////////// Other math ///////// + +/** Some frequent operations **/ +#if CV_FMA3 +#define OPENCV_HAL_IMPL_AVX512_MULADD(_Tpvec, suffix) \ + inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ + { return _Tpvec(_mm512_fmadd_##suffix(a.val, b.val, c.val)); } \ + inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ + { return _Tpvec(_mm512_fmadd_##suffix(a.val, b.val, c.val)); } +#else +#define OPENCV_HAL_IMPL_AVX512_MULADD(_Tpvec, suffix) \ + inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ + { return _Tpvec(_mm512_add_##suffix(_mm512_mul_##suffix(a.val, b.val), c.val)); } \ + inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ + { return _Tpvec(_mm512_add_##suffix(_mm512_mul_##suffix(a.val, b.val), c.val)); } +#endif + +#define OPENCV_HAL_IMPL_AVX512_MISC(_Tpvec, suffix) \ + inline _Tpvec v_sqrt(const _Tpvec& x) \ + { return _Tpvec(_mm512_sqrt_##suffix(x.val)); } \ + inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ + { return v_fma(a, a, v_mul(b, b)); } \ + inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ + { return v_sqrt(v_fma(a, a, v_mul(b, b))); } + +OPENCV_HAL_IMPL_AVX512_MULADD(v_float32x16, ps) +OPENCV_HAL_IMPL_AVX512_MULADD(v_float64x8, pd) +OPENCV_HAL_IMPL_AVX512_MISC(v_float32x16, ps) +OPENCV_HAL_IMPL_AVX512_MISC(v_float64x8, pd) + +inline v_int32x16 v_fma(const v_int32x16& a, const v_int32x16& b, const v_int32x16& c) +{ return v_add(v_mul(a, b), c); } +inline v_int32x16 v_muladd(const v_int32x16& a, const v_int32x16& b, const v_int32x16& c) +{ return v_fma(a, b, c); } + +inline v_float32x16 v_invsqrt(const v_float32x16& x) +{ +#if CV_AVX_512ER + return v_float32x16(_mm512_rsqrt28_ps(x.val)); +#else + v_float32x16 half = v_mul(x, v512_setall_f32(0.5)); + v_float32x16 t = v_float32x16(_mm512_rsqrt14_ps(x.val)); + t = v_mul(t, v_sub(v512_setall_f32(1.5), v_mul(v_mul(t, t), half))); + return t; +#endif +} + +inline v_float64x8 v_invsqrt(const v_float64x8& x) +{ +#if CV_AVX_512ER + return v_float64x8(_mm512_rsqrt28_pd(x.val)); +#else + return v_div(v512_setall_f64(1.), v_sqrt(x)); +// v_float64x8 half = x * v512_setall_f64(0.5); +// v_float64x8 t = v_float64x8(_mm512_rsqrt14_pd(x.val)); +// t *= v512_setall_f64(1.5) - ((t * t) * half); +// t *= v512_setall_f64(1.5) - ((t * t) * half); +// return t; +#endif +} + +/** Absolute values **/ +#define OPENCV_HAL_IMPL_AVX512_ABS(_Tpvec, _Tpuvec, suffix) \ + inline _Tpuvec v_abs(const _Tpvec& x) \ + { return _Tpuvec(_mm512_abs_##suffix(x.val)); } + +OPENCV_HAL_IMPL_AVX512_ABS(v_int8x64, v_uint8x64, epi8) +OPENCV_HAL_IMPL_AVX512_ABS(v_int16x32, v_uint16x32, epi16) +OPENCV_HAL_IMPL_AVX512_ABS(v_int32x16, v_uint32x16, epi32) +OPENCV_HAL_IMPL_AVX512_ABS(v_int64x8, v_uint64x8, epi64) + +inline v_float32x16 v_abs(const v_float32x16& x) +{ +#ifdef _mm512_abs_pd + return v_float32x16(_mm512_abs_ps(x.val)); +#else + return v_float32x16(_mm512_castsi512_ps(_mm512_and_si512(_mm512_castps_si512(x.val), + _v512_set_epu64(0x7FFFFFFF7FFFFFFF, 0x7FFFFFFF7FFFFFFF, 0x7FFFFFFF7FFFFFFF, 0x7FFFFFFF7FFFFFFF, + 0x7FFFFFFF7FFFFFFF, 0x7FFFFFFF7FFFFFFF, 0x7FFFFFFF7FFFFFFF, 0x7FFFFFFF7FFFFFFF)))); +#endif +} + +inline v_float64x8 v_abs(const v_float64x8& x) +{ +#ifdef _mm512_abs_pd + #if defined __GNUC__ && (__GNUC__ < 7 || (__GNUC__ == 7 && __GNUC_MINOR__ <= 3) || (__GNUC__ == 8 && __GNUC_MINOR__ <= 2)) + // Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=87476 + return v_float64x8(_mm512_abs_pd(_mm512_castpd_ps(x.val))); + #else + return v_float64x8(_mm512_abs_pd(x.val)); + #endif +#else + return v_float64x8(_mm512_castsi512_pd(_mm512_and_si512(_mm512_castpd_si512(x.val), + _v512_set_epu64(0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, + 0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF)))); +#endif +} + +/** Absolute difference **/ +inline v_uint8x64 v_absdiff(const v_uint8x64& a, const v_uint8x64& b) +{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } +inline v_uint16x32 v_absdiff(const v_uint16x32& a, const v_uint16x32& b) +{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } +inline v_uint32x16 v_absdiff(const v_uint32x16& a, const v_uint32x16& b) +{ return v_sub(v_max(a, b), v_min(a, b)); } + +inline v_uint8x64 v_absdiff(const v_int8x64& a, const v_int8x64& b) +{ + v_int8x64 d = v_sub_wrap(a, b); + v_int8x64 m = v_lt(a, b); + return v_reinterpret_as_u8(v_sub_wrap(v_xor(d, m), m)); +} + +inline v_uint16x32 v_absdiff(const v_int16x32& a, const v_int16x32& b) +{ return v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))); } + +inline v_uint32x16 v_absdiff(const v_int32x16& a, const v_int32x16& b) +{ + v_int32x16 d = v_sub(a, b); + v_int32x16 m = v_lt(a, b); + return v_reinterpret_as_u32(v_sub(v_xor(d, m), m)); +} + +inline v_float32x16 v_absdiff(const v_float32x16& a, const v_float32x16& b) +{ return v_abs(v_sub(a, b)); } + +inline v_float64x8 v_absdiff(const v_float64x8& a, const v_float64x8& b) +{ return v_abs(v_sub(a, b)); } + +/** Saturating absolute difference **/ +inline v_int8x64 v_absdiffs(const v_int8x64& a, const v_int8x64& b) +{ + v_int8x64 d = v_sub(a, b); + v_int8x64 m = v_lt(a, b); + return v_sub(v_xor(d, m), m); +} +inline v_int16x32 v_absdiffs(const v_int16x32& a, const v_int16x32& b) +{ return v_sub(v_max(a, b), v_min(a, b)); } + +////////// Conversions ///////// + +/** Rounding **/ +inline v_int32x16 v_round(const v_float32x16& a) +{ return v_int32x16(_mm512_cvtps_epi32(a.val)); } + +inline v_int32x16 v_round(const v_float64x8& a) +{ return v_int32x16(_mm512_castsi256_si512(_mm512_cvtpd_epi32(a.val))); } + +inline v_int32x16 v_round(const v_float64x8& a, const v_float64x8& b) +{ return v_int32x16(_v512_combine(_mm512_cvtpd_epi32(a.val), _mm512_cvtpd_epi32(b.val))); } + +inline v_int32x16 v_trunc(const v_float32x16& a) +{ return v_int32x16(_mm512_cvttps_epi32(a.val)); } + +inline v_int32x16 v_trunc(const v_float64x8& a) +{ return v_int32x16(_mm512_castsi256_si512(_mm512_cvttpd_epi32(a.val))); } + +#if CVT_ROUND_MODES_IMPLEMENTED +inline v_int32x16 v_floor(const v_float32x16& a) +{ return v_int32x16(_mm512_cvt_roundps_epi32(a.val, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC)); } + +inline v_int32x16 v_floor(const v_float64x8& a) +{ return v_int32x16(_mm512_castsi256_si512(_mm512_cvt_roundpd_epi32(a.val, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC))); } + +inline v_int32x16 v_ceil(const v_float32x16& a) +{ return v_int32x16(_mm512_cvt_roundps_epi32(a.val, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC)); } + +inline v_int32x16 v_ceil(const v_float64x8& a) +{ return v_int32x16(_mm512_castsi256_si512(_mm512_cvt_roundpd_epi32(a.val, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC))); } +#else +inline v_int32x16 v_floor(const v_float32x16& a) +{ return v_int32x16(_mm512_cvtps_epi32(_mm512_roundscale_ps(a.val, 1))); } + +inline v_int32x16 v_floor(const v_float64x8& a) +{ return v_int32x16(_mm512_castsi256_si512(_mm512_cvtpd_epi32(_mm512_roundscale_pd(a.val, 1)))); } + +inline v_int32x16 v_ceil(const v_float32x16& a) +{ return v_int32x16(_mm512_cvtps_epi32(_mm512_roundscale_ps(a.val, 2))); } + +inline v_int32x16 v_ceil(const v_float64x8& a) +{ return v_int32x16(_mm512_castsi256_si512(_mm512_cvtpd_epi32(_mm512_roundscale_pd(a.val, 2)))); } +#endif + +/** To float **/ +inline v_float32x16 v_cvt_f32(const v_int32x16& a) +{ return v_float32x16(_mm512_cvtepi32_ps(a.val)); } + +inline v_float32x16 v_cvt_f32(const v_float64x8& a) +{ return v_float32x16(_mm512_cvtpd_pslo(a.val)); } + +inline v_float32x16 v_cvt_f32(const v_float64x8& a, const v_float64x8& b) +{ return v_float32x16(_v512_combine(_mm512_cvtpd_ps(a.val), _mm512_cvtpd_ps(b.val))); } + +inline v_float64x8 v_cvt_f64(const v_int32x16& a) +{ return v_float64x8(_mm512_cvtepi32_pd(_v512_extract_low(a.val))); } + +inline v_float64x8 v_cvt_f64_high(const v_int32x16& a) +{ return v_float64x8(_mm512_cvtepi32_pd(_v512_extract_high(a.val))); } + +inline v_float64x8 v_cvt_f64(const v_float32x16& a) +{ return v_float64x8(_mm512_cvtps_pd(_v512_extract_low(a.val))); } + +inline v_float64x8 v_cvt_f64_high(const v_float32x16& a) +{ return v_float64x8(_mm512_cvtps_pd(_v512_extract_high(a.val))); } + +// from (Mysticial and wim) https://stackoverflow.com/q/41144668 +inline v_float64x8 v_cvt_f64(const v_int64x8& v) +{ +#if CV_AVX_512DQ + return v_float64x8(_mm512_cvtepi64_pd(v.val)); +#else + // constants encoded as floating-point + __m512i magic_i_lo = _mm512_set1_epi64(0x4330000000000000); // 2^52 + __m512i magic_i_hi32 = _mm512_set1_epi64(0x4530000080000000); // 2^84 + 2^63 + __m512i magic_i_all = _mm512_set1_epi64(0x4530000080100000); // 2^84 + 2^63 + 2^52 + __m512d magic_d_all = _mm512_castsi512_pd(magic_i_all); + + // Blend the 32 lowest significant bits of v with magic_int_lo + __m512i v_lo = _mm512_mask_blend_epi32(0x5555, magic_i_lo, v.val); + // Extract the 32 most significant bits of v + __m512i v_hi = _mm512_srli_epi64(v.val, 32); + // Flip the msb of v_hi and blend with 0x45300000 + v_hi = _mm512_xor_si512(v_hi, magic_i_hi32); + // Compute in double precision + __m512d v_hi_dbl = _mm512_sub_pd(_mm512_castsi512_pd(v_hi), magic_d_all); + // (v_hi - magic_d_all) + v_lo Do not assume associativity of floating point addition + __m512d result = _mm512_add_pd(v_hi_dbl, _mm512_castsi512_pd(v_lo)); + return v_float64x8(result); +#endif +} + +////////////// Lookup table access //////////////////// + +inline v_int8x64 v512_lut(const schar* tab, const int* idx) +{ + __m128i p0 = _mm512_cvtepi32_epi8(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx ), (const int *)tab, 1)); + __m128i p1 = _mm512_cvtepi32_epi8(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx + 1), (const int *)tab, 1)); + __m128i p2 = _mm512_cvtepi32_epi8(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx + 2), (const int *)tab, 1)); + __m128i p3 = _mm512_cvtepi32_epi8(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx + 3), (const int *)tab, 1)); + return v_int8x64(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_castsi128_si512(p0), p1, 1), p2, 2), p3, 3)); +} +inline v_int8x64 v512_lut_pairs(const schar* tab, const int* idx) +{ + __m256i p0 = _mm512_cvtepi32_epi16(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx ), (const int *)tab, 1)); + __m256i p1 = _mm512_cvtepi32_epi16(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx + 1), (const int *)tab, 1)); + return v_int8x64(_v512_combine(p0, p1)); +} +inline v_int8x64 v512_lut_quads(const schar* tab, const int* idx) +{ + return v_int8x64(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx), (const int *)tab, 1)); +} +inline v_uint8x64 v512_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v512_lut((const schar *)tab, idx)); } +inline v_uint8x64 v512_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v512_lut_pairs((const schar *)tab, idx)); } +inline v_uint8x64 v512_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v512_lut_quads((const schar *)tab, idx)); } + +inline v_int16x32 v512_lut(const short* tab, const int* idx) +{ + __m256i p0 = _mm512_cvtepi32_epi16(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx ), (const int *)tab, 2)); + __m256i p1 = _mm512_cvtepi32_epi16(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx + 1), (const int *)tab, 2)); + return v_int16x32(_v512_combine(p0, p1)); +} +inline v_int16x32 v512_lut_pairs(const short* tab, const int* idx) +{ + return v_int16x32(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx), (const int *)tab, 2)); +} +inline v_int16x32 v512_lut_quads(const short* tab, const int* idx) +{ +#if defined(__GNUC__) + return v_int16x32(_mm512_i32gather_epi64(_mm256_loadu_si256((const __m256i*)idx), (const long long int*)tab, 2)); +#else + return v_int16x32(_mm512_i32gather_epi64(_mm256_loadu_si256((const __m256i*)idx), (const int64*)tab, 2)); +#endif +} +inline v_uint16x32 v512_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v512_lut((const short *)tab, idx)); } +inline v_uint16x32 v512_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v512_lut_pairs((const short *)tab, idx)); } +inline v_uint16x32 v512_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v512_lut_quads((const short *)tab, idx)); } + +inline v_int32x16 v512_lut(const int* tab, const int* idx) +{ + return v_int32x16(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx), tab, 4)); +} +inline v_int32x16 v512_lut_pairs(const int* tab, const int* idx) +{ +#if defined(__GNUC__) + return v_int32x16(_mm512_i32gather_epi64(_mm256_loadu_si256((const __m256i*)idx), (const long long int*)tab, 4)); +#else + return v_int32x16(_mm512_i32gather_epi64(_mm256_loadu_si256((const __m256i*)idx), (const int64*)tab, 4)); +#endif +} +inline v_int32x16 v512_lut_quads(const int* tab, const int* idx) +{ + return v_int32x16(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_castsi128_si512( + _mm_loadu_si128((const __m128i*)(tab + idx[0]))), + _mm_loadu_si128((const __m128i*)(tab + idx[1])), 1), + _mm_loadu_si128((const __m128i*)(tab + idx[2])), 2), + _mm_loadu_si128((const __m128i*)(tab + idx[3])), 3)); +} +inline v_uint32x16 v512_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v512_lut((const int *)tab, idx)); } +inline v_uint32x16 v512_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v512_lut_pairs((const int *)tab, idx)); } +inline v_uint32x16 v512_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v512_lut_quads((const int *)tab, idx)); } + +inline v_int64x8 v512_lut(const int64* tab, const int* idx) +{ +#if defined(__GNUC__) + return v_int64x8(_mm512_i32gather_epi64(_mm256_loadu_si256((const __m256i*)idx), (const long long int*)tab, 8)); +#else + return v_int64x8(_mm512_i32gather_epi64(_mm256_loadu_si256((const __m256i*)idx), tab , 8)); +#endif +} +inline v_int64x8 v512_lut_pairs(const int64* tab, const int* idx) +{ + return v_int64x8(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_castsi128_si512( + _mm_loadu_si128((const __m128i*)(tab + idx[0]))), + _mm_loadu_si128((const __m128i*)(tab + idx[1])), 1), + _mm_loadu_si128((const __m128i*)(tab + idx[2])), 2), + _mm_loadu_si128((const __m128i*)(tab + idx[3])), 3)); +} +inline v_uint64x8 v512_lut(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v512_lut((const int64 *)tab, idx)); } +inline v_uint64x8 v512_lut_pairs(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v512_lut_pairs((const int64 *)tab, idx)); } + +inline v_float32x16 v512_lut(const float* tab, const int* idx) +{ + return v_float32x16(_mm512_i32gather_ps(_mm512_loadu_si512((const __m512i*)idx), tab, 4)); +} +inline v_float32x16 v512_lut_pairs(const float* tab, const int* idx) { return v_reinterpret_as_f32(v512_lut_pairs((const int *)tab, idx)); } +inline v_float32x16 v512_lut_quads(const float* tab, const int* idx) { return v_reinterpret_as_f32(v512_lut_quads((const int *)tab, idx)); } + +inline v_float64x8 v512_lut(const double* tab, const int* idx) +{ + return v_float64x8(_mm512_i32gather_pd(_mm256_loadu_si256((const __m256i*)idx), tab, 8)); +} +inline v_float64x8 v512_lut_pairs(const double* tab, const int* idx) +{ + return v_float64x8(_mm512_insertf64x2(_mm512_insertf64x2(_mm512_insertf64x2(_mm512_castpd128_pd512( + _mm_loadu_pd(tab + idx[0])), + _mm_loadu_pd(tab + idx[1]), 1), + _mm_loadu_pd(tab + idx[2]), 2), + _mm_loadu_pd(tab + idx[3]), 3)); +} + +inline v_int32x16 v_lut(const int* tab, const v_int32x16& idxvec) +{ + return v_int32x16(_mm512_i32gather_epi32(idxvec.val, tab, 4)); +} + +inline v_uint32x16 v_lut(const unsigned* tab, const v_int32x16& idxvec) +{ + return v_reinterpret_as_u32(v_lut((const int *)tab, idxvec)); +} + +inline v_float32x16 v_lut(const float* tab, const v_int32x16& idxvec) +{ + return v_float32x16(_mm512_i32gather_ps(idxvec.val, tab, 4)); +} + +inline v_float64x8 v_lut(const double* tab, const v_int32x16& idxvec) +{ + return v_float64x8(_mm512_i32gather_pd(_v512_extract_low(idxvec.val), tab, 8)); +} + +inline void v_lut_deinterleave(const float* tab, const v_int32x16& idxvec, v_float32x16& x, v_float32x16& y) +{ + x.val = _mm512_i32gather_ps(idxvec.val, tab, 4); + y.val = _mm512_i32gather_ps(idxvec.val, &tab[1], 4); +} + +inline void v_lut_deinterleave(const double* tab, const v_int32x16& idxvec, v_float64x8& x, v_float64x8& y) +{ + x.val = _mm512_i32gather_pd(_v512_extract_low(idxvec.val), tab, 8); + y.val = _mm512_i32gather_pd(_v512_extract_low(idxvec.val), &tab[1], 8); +} + +inline v_int8x64 v_interleave_pairs(const v_int8x64& vec) +{ + return v_int8x64(_mm512_shuffle_epi8(vec.val, _mm512_set4_epi32(0x0f0d0e0c, 0x0b090a08, 0x07050604, 0x03010200))); +} +inline v_uint8x64 v_interleave_pairs(const v_uint8x64& vec) { return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } +inline v_int8x64 v_interleave_quads(const v_int8x64& vec) +{ + return v_int8x64(_mm512_shuffle_epi8(vec.val, _mm512_set4_epi32(0x0f0b0e0a, 0x0d090c08, 0x07030602, 0x05010400))); +} +inline v_uint8x64 v_interleave_quads(const v_uint8x64& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } + +inline v_int16x32 v_interleave_pairs(const v_int16x32& vec) +{ + return v_int16x32(_mm512_shuffle_epi8(vec.val, _mm512_set4_epi32(0x0f0e0b0a, 0x0d0c0908, 0x07060302, 0x05040100))); +} +inline v_uint16x32 v_interleave_pairs(const v_uint16x32& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } +inline v_int16x32 v_interleave_quads(const v_int16x32& vec) +{ + return v_int16x32(_mm512_shuffle_epi8(vec.val, _mm512_set4_epi32(0x0f0e0706, 0x0d0c0504, 0x0b0a0302, 0x09080100))); +} +inline v_uint16x32 v_interleave_quads(const v_uint16x32& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } + +inline v_int32x16 v_interleave_pairs(const v_int32x16& vec) +{ + return v_int32x16(_mm512_shuffle_epi32(vec.val, _MM_PERM_ACBD)); +} +inline v_uint32x16 v_interleave_pairs(const v_uint32x16& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } +inline v_float32x16 v_interleave_pairs(const v_float32x16& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } + +inline v_int8x64 v_pack_triplets(const v_int8x64& vec) +{ + return v_int8x64(_mm512_permutexvar_epi32(_v512_set_epu64(0x0000000f0000000f, 0x0000000f0000000f, 0x0000000e0000000d, 0x0000000c0000000a, + 0x0000000900000008, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000), + _mm512_shuffle_epi8(vec.val, _mm512_set4_epi32(0xffffff0f, 0x0e0d0c0a, 0x09080605, 0x04020100)))); +} +inline v_uint8x64 v_pack_triplets(const v_uint8x64& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } + +inline v_int16x32 v_pack_triplets(const v_int16x32& vec) +{ + return v_int16x32(_mm512_permutexvar_epi16(_v512_set_epu64(0x001f001f001f001f, 0x001f001f001f001f, 0x001e001d001c001a, 0x0019001800160015, + 0x0014001200110010, 0x000e000d000c000a, 0x0009000800060005, 0x0004000200010000), vec.val)); +} +inline v_uint16x32 v_pack_triplets(const v_uint16x32& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } + +inline v_int32x16 v_pack_triplets(const v_int32x16& vec) +{ + return v_int32x16(_mm512_permutexvar_epi32(_v512_set_epu64(0x0000000f0000000f, 0x0000000f0000000f, 0x0000000e0000000d, 0x0000000c0000000a, + 0x0000000900000008, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000), vec.val)); +} +inline v_uint32x16 v_pack_triplets(const v_uint32x16& vec) { return v_reinterpret_as_u32(v_pack_triplets(v_reinterpret_as_s32(vec))); } +inline v_float32x16 v_pack_triplets(const v_float32x16& vec) +{ + return v_float32x16(_mm512_permutexvar_ps(_v512_set_epu64(0x0000000f0000000f, 0x0000000f0000000f, 0x0000000e0000000d, 0x0000000c0000000a, + 0x0000000900000008, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000), vec.val)); +} + +////////// Matrix operations ///////// + +//////// Dot Product //////// + +// 16 >> 32 +inline v_int32x16 v_dotprod(const v_int16x32& a, const v_int16x32& b) +{ return v_int32x16(_mm512_madd_epi16(a.val, b.val)); } +inline v_int32x16 v_dotprod(const v_int16x32& a, const v_int16x32& b, const v_int32x16& c) +{ return v_add(v_dotprod(a, b), c); } + +// 32 >> 64 +inline v_int64x8 v_dotprod(const v_int32x16& a, const v_int32x16& b) +{ + __m512i even = _mm512_mul_epi32(a.val, b.val); + __m512i odd = _mm512_mul_epi32(_mm512_srli_epi64(a.val, 32), _mm512_srli_epi64(b.val, 32)); + return v_int64x8(_mm512_add_epi64(even, odd)); +} +inline v_int64x8 v_dotprod(const v_int32x16& a, const v_int32x16& b, const v_int64x8& c) +{ return v_add(v_dotprod(a, b), c); } + +// 8 >> 32 +inline v_uint32x16 v_dotprod_expand(const v_uint8x64& a, const v_uint8x64& b) +{ + __m512i even_a = _mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, a.val, _mm512_setzero_si512()); + __m512i odd_a = _mm512_srli_epi16(a.val, 8); + + __m512i even_b = _mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, b.val, _mm512_setzero_si512()); + __m512i odd_b = _mm512_srli_epi16(b.val, 8); + + __m512i prod0 = _mm512_madd_epi16(even_a, even_b); + __m512i prod1 = _mm512_madd_epi16(odd_a, odd_b); + return v_uint32x16(_mm512_add_epi32(prod0, prod1)); +} +inline v_uint32x16 v_dotprod_expand(const v_uint8x64& a, const v_uint8x64& b, const v_uint32x16& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int32x16 v_dotprod_expand(const v_int8x64& a, const v_int8x64& b) +{ + __m512i even_a = _mm512_srai_epi16(_mm512_bslli_epi128(a.val, 1), 8); + __m512i odd_a = _mm512_srai_epi16(a.val, 8); + + __m512i even_b = _mm512_srai_epi16(_mm512_bslli_epi128(b.val, 1), 8); + __m512i odd_b = _mm512_srai_epi16(b.val, 8); + + __m512i prod0 = _mm512_madd_epi16(even_a, even_b); + __m512i prod1 = _mm512_madd_epi16(odd_a, odd_b); + return v_int32x16(_mm512_add_epi32(prod0, prod1)); +} +inline v_int32x16 v_dotprod_expand(const v_int8x64& a, const v_int8x64& b, const v_int32x16& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 16 >> 64 +inline v_uint64x8 v_dotprod_expand(const v_uint16x32& a, const v_uint16x32& b) +{ + __m512i mullo = _mm512_mullo_epi16(a.val, b.val); + __m512i mulhi = _mm512_mulhi_epu16(a.val, b.val); + __m512i mul0 = _mm512_unpacklo_epi16(mullo, mulhi); + __m512i mul1 = _mm512_unpackhi_epi16(mullo, mulhi); + + __m512i p02 = _mm512_mask_blend_epi32(0xAAAA, mul0, _mm512_setzero_si512()); + __m512i p13 = _mm512_srli_epi64(mul0, 32); + __m512i p46 = _mm512_mask_blend_epi32(0xAAAA, mul1, _mm512_setzero_si512()); + __m512i p57 = _mm512_srli_epi64(mul1, 32); + + __m512i p15_ = _mm512_add_epi64(p02, p13); + __m512i p9d_ = _mm512_add_epi64(p46, p57); + + return v_uint64x8(_mm512_add_epi64( + _mm512_unpacklo_epi64(p15_, p9d_), + _mm512_unpackhi_epi64(p15_, p9d_) + )); +} +inline v_uint64x8 v_dotprod_expand(const v_uint16x32& a, const v_uint16x32& b, const v_uint64x8& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int64x8 v_dotprod_expand(const v_int16x32& a, const v_int16x32& b) +{ + __m512i prod = _mm512_madd_epi16(a.val, b.val); + __m512i even = _mm512_srai_epi64(_mm512_bslli_epi128(prod, 4), 32); + __m512i odd = _mm512_srai_epi64(prod, 32); + return v_int64x8(_mm512_add_epi64(even, odd)); +} +inline v_int64x8 v_dotprod_expand(const v_int16x32& a, const v_int16x32& b, const v_int64x8& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 32 >> 64f +inline v_float64x8 v_dotprod_expand(const v_int32x16& a, const v_int32x16& b) +{ return v_cvt_f64(v_dotprod(a, b)); } +inline v_float64x8 v_dotprod_expand(const v_int32x16& a, const v_int32x16& b, const v_float64x8& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +//////// Fast Dot Product //////// + +// 16 >> 32 +inline v_int32x16 v_dotprod_fast(const v_int16x32& a, const v_int16x32& b) +{ return v_dotprod(a, b); } +inline v_int32x16 v_dotprod_fast(const v_int16x32& a, const v_int16x32& b, const v_int32x16& c) +{ return v_dotprod(a, b, c); } + +// 32 >> 64 +inline v_int64x8 v_dotprod_fast(const v_int32x16& a, const v_int32x16& b) +{ return v_dotprod(a, b); } +inline v_int64x8 v_dotprod_fast(const v_int32x16& a, const v_int32x16& b, const v_int64x8& c) +{ return v_dotprod(a, b, c); } + +// 8 >> 32 +inline v_uint32x16 v_dotprod_expand_fast(const v_uint8x64& a, const v_uint8x64& b) +{ return v_dotprod_expand(a, b); } +inline v_uint32x16 v_dotprod_expand_fast(const v_uint8x64& a, const v_uint8x64& b, const v_uint32x16& c) +{ return v_dotprod_expand(a, b, c); } + +inline v_int32x16 v_dotprod_expand_fast(const v_int8x64& a, const v_int8x64& b) +{ return v_dotprod_expand(a, b); } +inline v_int32x16 v_dotprod_expand_fast(const v_int8x64& a, const v_int8x64& b, const v_int32x16& c) +{ return v_dotprod_expand(a, b, c); } + +// 16 >> 64 +inline v_uint64x8 v_dotprod_expand_fast(const v_uint16x32& a, const v_uint16x32& b) +{ + __m512i mullo = _mm512_mullo_epi16(a.val, b.val); + __m512i mulhi = _mm512_mulhi_epu16(a.val, b.val); + __m512i mul0 = _mm512_unpacklo_epi16(mullo, mulhi); + __m512i mul1 = _mm512_unpackhi_epi16(mullo, mulhi); + + __m512i p02 = _mm512_mask_blend_epi32(0xAAAA, mul0, _mm512_setzero_si512()); + __m512i p13 = _mm512_srli_epi64(mul0, 32); + __m512i p46 = _mm512_mask_blend_epi32(0xAAAA, mul1, _mm512_setzero_si512()); + __m512i p57 = _mm512_srli_epi64(mul1, 32); + + __m512i p15_ = _mm512_add_epi64(p02, p13); + __m512i p9d_ = _mm512_add_epi64(p46, p57); + return v_uint64x8(_mm512_add_epi64(p15_, p9d_)); +} +inline v_uint64x8 v_dotprod_expand_fast(const v_uint16x32& a, const v_uint16x32& b, const v_uint64x8& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +inline v_int64x8 v_dotprod_expand_fast(const v_int16x32& a, const v_int16x32& b) +{ return v_dotprod_expand(a, b); } +inline v_int64x8 v_dotprod_expand_fast(const v_int16x32& a, const v_int16x32& b, const v_int64x8& c) +{ return v_dotprod_expand(a, b, c); } + +// 32 >> 64f +inline v_float64x8 v_dotprod_expand_fast(const v_int32x16& a, const v_int32x16& b) +{ return v_dotprod_expand(a, b); } +inline v_float64x8 v_dotprod_expand_fast(const v_int32x16& a, const v_int32x16& b, const v_float64x8& c) +{ return v_add(v_dotprod_expand(a, b), c); } + + +#define OPENCV_HAL_AVX512_SPLAT2_PS(a, im) \ + v_float32x16(_mm512_permute_ps(a.val, _MM_SHUFFLE(im, im, im, im))) + +inline v_float32x16 v_matmul(const v_float32x16& v, + const v_float32x16& m0, const v_float32x16& m1, + const v_float32x16& m2, const v_float32x16& m3) +{ + v_float32x16 v04 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 0); + v_float32x16 v15 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 1); + v_float32x16 v26 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 2); + v_float32x16 v37 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 3); + return v_fma(v04, m0, v_fma(v15, m1, v_fma(v26, m2, v_mul(v37, m3)))); +} + +inline v_float32x16 v_matmuladd(const v_float32x16& v, + const v_float32x16& m0, const v_float32x16& m1, + const v_float32x16& m2, const v_float32x16& a) +{ + v_float32x16 v04 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 0); + v_float32x16 v15 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 1); + v_float32x16 v26 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 2); + return v_fma(v04, m0, v_fma(v15, m1, v_fma(v26, m2, a))); +} + +#define OPENCV_HAL_IMPL_AVX512_TRANSPOSE4x4(_Tpvec, suffix, cast_from, cast_to) \ + inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ + const _Tpvec& a2, const _Tpvec& a3, \ + _Tpvec& b0, _Tpvec& b1, _Tpvec& b2, _Tpvec& b3) \ + { \ + __m512i t0 = cast_from(_mm512_unpacklo_##suffix(a0.val, a1.val)); \ + __m512i t1 = cast_from(_mm512_unpacklo_##suffix(a2.val, a3.val)); \ + __m512i t2 = cast_from(_mm512_unpackhi_##suffix(a0.val, a1.val)); \ + __m512i t3 = cast_from(_mm512_unpackhi_##suffix(a2.val, a3.val)); \ + b0.val = cast_to(_mm512_unpacklo_epi64(t0, t1)); \ + b1.val = cast_to(_mm512_unpackhi_epi64(t0, t1)); \ + b2.val = cast_to(_mm512_unpacklo_epi64(t2, t3)); \ + b3.val = cast_to(_mm512_unpackhi_epi64(t2, t3)); \ + } + +OPENCV_HAL_IMPL_AVX512_TRANSPOSE4x4(v_uint32x16, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_AVX512_TRANSPOSE4x4(v_int32x16, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_AVX512_TRANSPOSE4x4(v_float32x16, ps, _mm512_castps_si512, _mm512_castsi512_ps) + +//////////////// Value reordering /////////////// + +/* Expand */ +#define OPENCV_HAL_IMPL_AVX512_EXPAND(_Tpvec, _Tpwvec, _Tp, intrin) \ + inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ + { \ + b0.val = intrin(_v512_extract_low(a.val)); \ + b1.val = intrin(_v512_extract_high(a.val)); \ + } \ + inline _Tpwvec v_expand_low(const _Tpvec& a) \ + { return _Tpwvec(intrin(_v512_extract_low(a.val))); } \ + inline _Tpwvec v_expand_high(const _Tpvec& a) \ + { return _Tpwvec(intrin(_v512_extract_high(a.val))); } \ + inline _Tpwvec v512_load_expand(const _Tp* ptr) \ + { \ + __m256i a = _mm256_loadu_si256((const __m256i*)ptr); \ + return _Tpwvec(intrin(a)); \ + } + +OPENCV_HAL_IMPL_AVX512_EXPAND(v_uint8x64, v_uint16x32, uchar, _mm512_cvtepu8_epi16) +OPENCV_HAL_IMPL_AVX512_EXPAND(v_int8x64, v_int16x32, schar, _mm512_cvtepi8_epi16) +OPENCV_HAL_IMPL_AVX512_EXPAND(v_uint16x32, v_uint32x16, ushort, _mm512_cvtepu16_epi32) +OPENCV_HAL_IMPL_AVX512_EXPAND(v_int16x32, v_int32x16, short, _mm512_cvtepi16_epi32) +OPENCV_HAL_IMPL_AVX512_EXPAND(v_uint32x16, v_uint64x8, unsigned, _mm512_cvtepu32_epi64) +OPENCV_HAL_IMPL_AVX512_EXPAND(v_int32x16, v_int64x8, int, _mm512_cvtepi32_epi64) + +#define OPENCV_HAL_IMPL_AVX512_EXPAND_Q(_Tpvec, _Tp, intrin) \ + inline _Tpvec v512_load_expand_q(const _Tp* ptr) \ + { \ + __m128i a = _mm_loadu_si128((const __m128i*)ptr); \ + return _Tpvec(intrin(a)); \ + } + +OPENCV_HAL_IMPL_AVX512_EXPAND_Q(v_uint32x16, uchar, _mm512_cvtepu8_epi32) +OPENCV_HAL_IMPL_AVX512_EXPAND_Q(v_int32x16, schar, _mm512_cvtepi8_epi32) + +/* pack */ +// 16 +inline v_int8x64 v_pack(const v_int16x32& a, const v_int16x32& b) +{ return v_int8x64(_mm512_permutexvar_epi64(_v512_set_epu64(7, 5, 3, 1, 6, 4, 2, 0), _mm512_packs_epi16(a.val, b.val))); } + +inline v_uint8x64 v_pack(const v_uint16x32& a, const v_uint16x32& b) +{ + const __m512i t = _mm512_set1_epi16(255); + return v_uint8x64(_v512_combine(_mm512_cvtepi16_epi8(_mm512_min_epu16(a.val, t)), _mm512_cvtepi16_epi8(_mm512_min_epu16(b.val, t)))); +} + +inline v_uint8x64 v_pack_u(const v_int16x32& a, const v_int16x32& b) +{ + return v_uint8x64(_mm512_permutexvar_epi64(_v512_set_epu64(7, 5, 3, 1, 6, 4, 2, 0), _mm512_packus_epi16(a.val, b.val))); +} + +inline void v_pack_store(schar* ptr, const v_int16x32& a) +{ v_store_low(ptr, v_pack(a, a)); } + +inline void v_pack_store(uchar* ptr, const v_uint16x32& a) +{ + const __m512i m = _mm512_set1_epi16(255); + _mm256_storeu_si256((__m256i*)ptr, _mm512_cvtepi16_epi8(_mm512_min_epu16(a.val, m))); +} + +inline void v_pack_u_store(uchar* ptr, const v_int16x32& a) +{ v_store_low(ptr, v_pack_u(a, a)); } + +template inline +v_uint8x64 v_rshr_pack(const v_uint16x32& a, const v_uint16x32& b) +{ + // we assume that n > 0, and so the shifted 16-bit values can be treated as signed numbers. + v_uint16x32 delta = v512_setall_u16((short)(1 << (n-1))); + return v_pack_u(v_reinterpret_as_s16(v_shr(v_add(a, delta), n)), + v_reinterpret_as_s16(v_shr(v_add(b, delta), n))); +} + +template inline +void v_rshr_pack_store(uchar* ptr, const v_uint16x32& a) +{ + v_uint16x32 delta = v512_setall_u16((short)(1 << (n-1))); + v_pack_u_store(ptr, v_reinterpret_as_s16(v_shr(v_add(a, delta), n))); +} + +template inline +v_uint8x64 v_rshr_pack_u(const v_int16x32& a, const v_int16x32& b) +{ + v_int16x32 delta = v512_setall_s16((short)(1 << (n-1))); + return v_pack_u(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); +} + +template inline +void v_rshr_pack_u_store(uchar* ptr, const v_int16x32& a) +{ + v_int16x32 delta = v512_setall_s16((short)(1 << (n-1))); + v_pack_u_store(ptr, v_shr(v_add(a, delta), n)); +} + +template inline +v_int8x64 v_rshr_pack(const v_int16x32& a, const v_int16x32& b) +{ + v_int16x32 delta = v512_setall_s16((short)(1 << (n-1))); + return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); +} + +template inline +void v_rshr_pack_store(schar* ptr, const v_int16x32& a) +{ + v_int16x32 delta = v512_setall_s16((short)(1 << (n-1))); + v_pack_store(ptr, v_shr(v_add(a, delta), n)); +} + +// 32 +inline v_int16x32 v_pack(const v_int32x16& a, const v_int32x16& b) +{ return v_int16x32(_mm512_permutexvar_epi64(_v512_set_epu64(7, 5, 3, 1, 6, 4, 2, 0), _mm512_packs_epi32(a.val, b.val))); } + +inline v_uint16x32 v_pack(const v_uint32x16& a, const v_uint32x16& b) +{ + const __m512i m = _mm512_set1_epi32(65535); + return v_uint16x32(_v512_combine(_mm512_cvtepi32_epi16(_mm512_min_epu32(a.val, m)), _mm512_cvtepi32_epi16(_mm512_min_epu32(b.val, m)))); +} + +inline v_uint16x32 v_pack_u(const v_int32x16& a, const v_int32x16& b) +{ return v_uint16x32(_mm512_permutexvar_epi64(_v512_set_epu64(7, 5, 3, 1, 6, 4, 2, 0), _mm512_packus_epi32(a.val, b.val))); } + +inline void v_pack_store(short* ptr, const v_int32x16& a) +{ v_store_low(ptr, v_pack(a, a)); } + +inline void v_pack_store(ushort* ptr, const v_uint32x16& a) +{ + const __m512i m = _mm512_set1_epi32(65535); + _mm256_storeu_si256((__m256i*)ptr, _mm512_cvtepi32_epi16(_mm512_min_epu32(a.val, m))); +} + +inline void v_pack_u_store(ushort* ptr, const v_int32x16& a) +{ v_store_low(ptr, v_pack_u(a, a)); } + + +template inline +v_uint16x32 v_rshr_pack(const v_uint32x16& a, const v_uint32x16& b) +{ + v_uint32x16 delta = v512_setall_u32(1 << (n-1)); + return v_pack_u(v_reinterpret_as_s32(v_shr(v_add(a, delta), n)), + v_reinterpret_as_s32(v_shr(v_add(b, delta), n))); +} + +template inline +void v_rshr_pack_store(ushort* ptr, const v_uint32x16& a) +{ + v_uint32x16 delta = v512_setall_u32(1 << (n-1)); + v_pack_u_store(ptr, v_reinterpret_as_s32(v_shr(v_add(a, delta), n))); +} + +template inline +v_uint16x32 v_rshr_pack_u(const v_int32x16& a, const v_int32x16& b) +{ + v_int32x16 delta = v512_setall_s32(1 << (n-1)); + return v_pack_u(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); +} + +template inline +void v_rshr_pack_u_store(ushort* ptr, const v_int32x16& a) +{ + v_int32x16 delta = v512_setall_s32(1 << (n-1)); + v_pack_u_store(ptr, v_shr(v_add(a, delta), n)); +} + +template inline +v_int16x32 v_rshr_pack(const v_int32x16& a, const v_int32x16& b) +{ + v_int32x16 delta = v512_setall_s32(1 << (n-1)); + return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); +} + +template inline +void v_rshr_pack_store(short* ptr, const v_int32x16& a) +{ + v_int32x16 delta = v512_setall_s32(1 << (n-1)); + v_pack_store(ptr, v_shr(v_add(a, delta), n)); +} + +// 64 +// Non-saturating pack +inline v_uint32x16 v_pack(const v_uint64x8& a, const v_uint64x8& b) +{ return v_uint32x16(_v512_combine(_mm512_cvtepi64_epi32(a.val), _mm512_cvtepi64_epi32(b.val))); } + +inline v_int32x16 v_pack(const v_int64x8& a, const v_int64x8& b) +{ return v_reinterpret_as_s32(v_pack(v_reinterpret_as_u64(a), v_reinterpret_as_u64(b))); } + +inline void v_pack_store(unsigned* ptr, const v_uint64x8& a) +{ _mm256_storeu_si256((__m256i*)ptr, _mm512_cvtepi64_epi32(a.val)); } + +inline void v_pack_store(int* ptr, const v_int64x8& b) +{ v_pack_store((unsigned*)ptr, v_reinterpret_as_u64(b)); } + +template inline +v_uint32x16 v_rshr_pack(const v_uint64x8& a, const v_uint64x8& b) +{ + v_uint64x8 delta = v512_setall_u64((uint64)1 << (n-1)); + return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); +} + +template inline +void v_rshr_pack_store(unsigned* ptr, const v_uint64x8& a) +{ + v_uint64x8 delta = v512_setall_u64((uint64)1 << (n-1)); + v_pack_store(ptr, v_shr(v_add(a, delta), n)); +} + +template inline +v_int32x16 v_rshr_pack(const v_int64x8& a, const v_int64x8& b) +{ + v_int64x8 delta = v512_setall_s64((int64)1 << (n-1)); + return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); +} + +template inline +void v_rshr_pack_store(int* ptr, const v_int64x8& a) +{ + v_int64x8 delta = v512_setall_s64((int64)1 << (n-1)); + v_pack_store(ptr, v_shr(v_add(a, delta), n)); +} + +// pack boolean +inline v_uint8x64 v_pack_b(const v_uint16x32& a, const v_uint16x32& b) +{ return v_uint8x64(_mm512_permutexvar_epi64(_v512_set_epu64(7, 5, 3, 1, 6, 4, 2, 0), _mm512_packs_epi16(a.val, b.val))); } + +inline v_uint8x64 v_pack_b(const v_uint32x16& a, const v_uint32x16& b, + const v_uint32x16& c, const v_uint32x16& d) +{ + __m512i ab = _mm512_packs_epi32(a.val, b.val); + __m512i cd = _mm512_packs_epi32(c.val, d.val); + + return v_uint8x64(_mm512_permutexvar_epi32(_v512_set_epu32(15, 11, 7, 3, 14, 10, 6, 2, 13, 9, 5, 1, 12, 8, 4, 0), _mm512_packs_epi16(ab, cd))); +} + +inline v_uint8x64 v_pack_b(const v_uint64x8& a, const v_uint64x8& b, const v_uint64x8& c, + const v_uint64x8& d, const v_uint64x8& e, const v_uint64x8& f, + const v_uint64x8& g, const v_uint64x8& h) +{ + __m512i ab = _mm512_packs_epi32(a.val, b.val); + __m512i cd = _mm512_packs_epi32(c.val, d.val); + __m512i ef = _mm512_packs_epi32(e.val, f.val); + __m512i gh = _mm512_packs_epi32(g.val, h.val); + + __m512i abcd = _mm512_packs_epi32(ab, cd); + __m512i efgh = _mm512_packs_epi32(ef, gh); + + return v_uint8x64(_mm512_permutexvar_epi16(_v512_set_epu16(31, 23, 15, 7, 30, 22, 14, 6, 29, 21, 13, 5, 28, 20, 12, 4, + 27, 19, 11, 3, 26, 18, 10, 2, 25, 17, 9, 1, 24, 16, 8, 0), _mm512_packs_epi16(abcd, efgh))); +} + +/* Recombine */ +// its up there with load and store operations + +/* Extract */ +#define OPENCV_HAL_IMPL_AVX512_EXTRACT(_Tpvec) \ + template \ + inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \ + { return v_rotate_right(a, b); } + +OPENCV_HAL_IMPL_AVX512_EXTRACT(v_uint8x64) +OPENCV_HAL_IMPL_AVX512_EXTRACT(v_int8x64) +OPENCV_HAL_IMPL_AVX512_EXTRACT(v_uint16x32) +OPENCV_HAL_IMPL_AVX512_EXTRACT(v_int16x32) +OPENCV_HAL_IMPL_AVX512_EXTRACT(v_uint32x16) +OPENCV_HAL_IMPL_AVX512_EXTRACT(v_int32x16) +OPENCV_HAL_IMPL_AVX512_EXTRACT(v_uint64x8) +OPENCV_HAL_IMPL_AVX512_EXTRACT(v_int64x8) +OPENCV_HAL_IMPL_AVX512_EXTRACT(v_float32x16) +OPENCV_HAL_IMPL_AVX512_EXTRACT(v_float64x8) + +#define OPENCV_HAL_IMPL_AVX512_EXTRACT_N(_Tpvec, _Tp) \ +template inline _Tp v_extract_n(_Tpvec v) { return v_rotate_right(v).get0(); } + +OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_uint8x64, uchar) +OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_int8x64, schar) +OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_uint16x32, ushort) +OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_int16x32, short) +OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_uint32x16, uint) +OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_int32x16, int) +OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_uint64x8, uint64) +OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_int64x8, int64) +OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_float32x16, float) +OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_float64x8, double) + +template +inline v_uint32x16 v_broadcast_element(v_uint32x16 a) +{ + static const __m512i perm = _mm512_set1_epi32((char)i); + return v_uint32x16(_mm512_permutexvar_epi32(perm, a.val)); +} + +template +inline v_int32x16 v_broadcast_element(const v_int32x16 &a) +{ return v_reinterpret_as_s32(v_broadcast_element(v_reinterpret_as_u32(a))); } + +template +inline v_float32x16 v_broadcast_element(const v_float32x16 &a) +{ return v_reinterpret_as_f32(v_broadcast_element(v_reinterpret_as_u32(a))); } + + +///////////////////// load deinterleave ///////////////////////////// + +inline void v_load_deinterleave( const uchar* ptr, v_uint8x64& a, v_uint8x64& b ) +{ + __m512i ab0 = _mm512_loadu_si512((const __m512i*)ptr); + __m512i ab1 = _mm512_loadu_si512((const __m512i*)(ptr + 64)); +#if CV_AVX_512VBMI + __m512i mask0 = _v512_set_epu8(126, 124, 122, 120, 118, 116, 114, 112, 110, 108, 106, 104, 102, 100, 98, 96, + 94, 92, 90, 88, 86, 84, 82, 80, 78, 76, 74, 72, 70, 68, 66, 64, + 62, 60, 58, 56, 54, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32, + 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); + __m512i mask1 = _v512_set_epu8(127, 125, 123, 121, 119, 117, 115, 113, 111, 109, 107, 105, 103, 101, 99, 97, + 95, 93, 91, 89, 87, 85, 83, 81, 79, 77, 75, 73, 71, 69, 67, 65, + 63, 61, 59, 57, 55, 53, 51, 49, 47, 45, 43, 41, 39, 37, 35, 33, + 31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); + a = v_uint8x64(_mm512_permutex2var_epi8(ab0, mask0, ab1)); + b = v_uint8x64(_mm512_permutex2var_epi8(ab0, mask1, ab1)); +#else + __m512i mask0 = _mm512_set4_epi32(0x0f0d0b09, 0x07050301, 0x0e0c0a08, 0x06040200); + __m512i a0b0 = _mm512_shuffle_epi8(ab0, mask0); + __m512i a1b1 = _mm512_shuffle_epi8(ab1, mask0); + __m512i mask1 = _v512_set_epu64(14, 12, 10, 8, 6, 4, 2, 0); + __m512i mask2 = _v512_set_epu64(15, 13, 11, 9, 7, 5, 3, 1); + a = v_uint8x64(_mm512_permutex2var_epi64(a0b0, mask1, a1b1)); + b = v_uint8x64(_mm512_permutex2var_epi64(a0b0, mask2, a1b1)); +#endif +} + +inline void v_load_deinterleave( const ushort* ptr, v_uint16x32& a, v_uint16x32& b ) +{ + __m512i ab0 = _mm512_loadu_si512((const __m512i*)ptr); + __m512i ab1 = _mm512_loadu_si512((const __m512i*)(ptr + 32)); + __m512i mask0 = _v512_set_epu16(62, 60, 58, 56, 54, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32, + 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); + __m512i mask1 = _v512_set_epu16(63, 61, 59, 57, 55, 53, 51, 49, 47, 45, 43, 41, 39, 37, 35, 33, + 31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); + a = v_uint16x32(_mm512_permutex2var_epi16(ab0, mask0, ab1)); + b = v_uint16x32(_mm512_permutex2var_epi16(ab0, mask1, ab1)); +} + +inline void v_load_deinterleave( const unsigned* ptr, v_uint32x16& a, v_uint32x16& b ) +{ + __m512i ab0 = _mm512_loadu_si512((const __m512i*)ptr); + __m512i ab1 = _mm512_loadu_si512((const __m512i*)(ptr + 16)); + __m512i mask0 = _v512_set_epu32(30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); + __m512i mask1 = _v512_set_epu32(31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); + a = v_uint32x16(_mm512_permutex2var_epi32(ab0, mask0, ab1)); + b = v_uint32x16(_mm512_permutex2var_epi32(ab0, mask1, ab1)); +} + +inline void v_load_deinterleave( const uint64* ptr, v_uint64x8& a, v_uint64x8& b ) +{ + __m512i ab0 = _mm512_loadu_si512((const __m512i*)ptr); + __m512i ab1 = _mm512_loadu_si512((const __m512i*)(ptr + 8)); + __m512i mask0 = _v512_set_epu64(14, 12, 10, 8, 6, 4, 2, 0); + __m512i mask1 = _v512_set_epu64(15, 13, 11, 9, 7, 5, 3, 1); + a = v_uint64x8(_mm512_permutex2var_epi64(ab0, mask0, ab1)); + b = v_uint64x8(_mm512_permutex2var_epi64(ab0, mask1, ab1)); +} + +inline void v_load_deinterleave( const uchar* ptr, v_uint8x64& a, v_uint8x64& b, v_uint8x64& c ) +{ + __m512i bgr0 = _mm512_loadu_si512((const __m512i*)ptr); + __m512i bgr1 = _mm512_loadu_si512((const __m512i*)(ptr + 64)); + __m512i bgr2 = _mm512_loadu_si512((const __m512i*)(ptr + 128)); + +#if CV_AVX_512VBMI2 + __m512i mask0 = _v512_set_epu8(126, 123, 120, 117, 114, 111, 108, 105, 102, 99, 96, 93, 90, 87, 84, 81, + 78, 75, 72, 69, 66, 63, 60, 57, 54, 51, 48, 45, 42, 39, 36, 33, + 30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 0, 62, 59, 56, 53, 50, + 47, 44, 41, 38, 35, 32, 29, 26, 23, 20, 17, 14, 11, 8, 5, 2); + __m512i r0b01 = _mm512_permutex2var_epi8(bgr0, mask0, bgr1); + __m512i b1g12 = _mm512_permutex2var_epi8(bgr1, mask0, bgr2); + __m512i r12b2 = _mm512_permutex2var_epi8(bgr1, + _v512_set_epu8(125, 122, 119, 116, 113, 110, 107, 104, 101, 98, 95, 92, 89, 86, 83, 80, + 77, 74, 71, 68, 65, 127, 124, 121, 118, 115, 112, 109, 106, 103, 100, 97, + 94, 91, 88, 85, 82, 79, 76, 73, 70, 67, 64, 61, 58, 55, 52, 49, + 46, 43, 40, 37, 34, 31, 28, 25, 22, 19, 16, 13, 10, 7, 4, 1), bgr2); + a = v_uint8x64(_mm512_mask_compress_epi8(r12b2, 0xffffffffffe00000, r0b01)); + b = v_uint8x64(_mm512_mask_compress_epi8(b1g12, 0x2492492492492492, bgr0)); + c = v_uint8x64(_mm512_mask_expand_epi8(r0b01, 0xffffffffffe00000, r12b2)); +#elif CV_AVX_512VBMI + __m512i b0g0b1 = _mm512_mask_blend_epi8(0xb6db6db6db6db6db, bgr1, bgr0); + __m512i g1r1g2 = _mm512_mask_blend_epi8(0xb6db6db6db6db6db, bgr2, bgr1); + __m512i r2b2r0 = _mm512_mask_blend_epi8(0xb6db6db6db6db6db, bgr0, bgr2); + a = v_uint8x64(_mm512_permutex2var_epi8(b0g0b1, _v512_set_epu8(125, 122, 119, 116, 113, 110, 107, 104, 101, 98, 95, 92, 89, 86, 83, 80, + 77, 74, 71, 68, 65, 63, 61, 60, 58, 57, 55, 54, 52, 51, 49, 48, + 46, 45, 43, 42, 40, 39, 37, 36, 34, 33, 31, 30, 28, 27, 25, 24, + 23, 21, 20, 18, 17, 15, 14, 12, 11, 9, 8, 6, 5, 3, 2, 0), bgr2)); + b = v_uint8x64(_mm512_permutex2var_epi8(g1r1g2, _v512_set_epu8( 63, 61, 60, 58, 57, 55, 54, 52, 51, 49, 48, 46, 45, 43, 42, 40, + 39, 37, 36, 34, 33, 31, 30, 28, 27, 25, 24, 23, 21, 20, 18, 17, + 15, 14, 12, 11, 9, 8, 6, 5, 3, 2, 0, 126, 123, 120, 117, 114, + 111, 108, 105, 102, 99, 96, 93, 90, 87, 84, 81, 78, 75, 72, 69, 66), bgr0)); + c = v_uint8x64(_mm512_permutex2var_epi8(r2b2r0, _v512_set_epu8( 63, 60, 57, 54, 51, 48, 45, 42, 39, 36, 33, 30, 27, 24, 21, 18, + 15, 12, 9, 6, 3, 0, 125, 122, 119, 116, 113, 110, 107, 104, 101, 98, + 95, 92, 89, 86, 83, 80, 77, 74, 71, 68, 65, 62, 59, 56, 53, 50, + 47, 44, 41, 38, 35, 32, 29, 26, 23, 20, 17, 14, 11, 8, 5, 2), bgr1)); +#else + __m512i mask0 = _v512_set_epu16(61, 58, 55, 52, 49, 46, 43, 40, 37, 34, 63, 60, 57, 54, 51, 48, + 45, 42, 39, 36, 33, 30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 0); + __m512i b01g1 = _mm512_permutex2var_epi16(bgr0, mask0, bgr1); + __m512i r12b2 = _mm512_permutex2var_epi16(bgr1, mask0, bgr2); + __m512i g20r0 = _mm512_permutex2var_epi16(bgr2, mask0, bgr0); + + __m512i b0g0 = _mm512_mask_blend_epi32(0xf800, b01g1, r12b2); + __m512i r0b1 = _mm512_permutex2var_epi16(bgr1, _v512_set_epu16(42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 29, 26, 23, 20, 17, + 14, 11, 8, 5, 2, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43), g20r0); + __m512i g1r1 = _mm512_alignr_epi32(r12b2, g20r0, 11); + a = v_uint8x64(_mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, b0g0, r0b1)); + c = v_uint8x64(_mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, r0b1, g1r1)); + b = v_uint8x64(_mm512_shuffle_epi8(_mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, g1r1, b0g0), _mm512_set4_epi32(0x0e0f0c0d, 0x0a0b0809, 0x06070405, 0x02030001))); +#endif +} + +inline void v_load_deinterleave( const ushort* ptr, v_uint16x32& a, v_uint16x32& b, v_uint16x32& c ) +{ + __m512i bgr0 = _mm512_loadu_si512((const __m512i*)ptr); + __m512i bgr1 = _mm512_loadu_si512((const __m512i*)(ptr + 32)); + __m512i bgr2 = _mm512_loadu_si512((const __m512i*)(ptr + 64)); + + __m512i mask0 = _v512_set_epu16(61, 58, 55, 52, 49, 46, 43, 40, 37, 34, 63, 60, 57, 54, 51, 48, + 45, 42, 39, 36, 33, 30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 0); + __m512i b01g1 = _mm512_permutex2var_epi16(bgr0, mask0, bgr1); + __m512i r12b2 = _mm512_permutex2var_epi16(bgr1, mask0, bgr2); + __m512i g20r0 = _mm512_permutex2var_epi16(bgr2, mask0, bgr0); + + a = v_uint16x32(_mm512_mask_blend_epi32(0xf800, b01g1, r12b2)); + b = v_uint16x32(_mm512_permutex2var_epi16(bgr1, _v512_set_epu16(42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 29, 26, 23, 20, 17, + 14, 11, 8, 5, 2, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43), g20r0)); + c = v_uint16x32(_mm512_alignr_epi32(r12b2, g20r0, 11)); +} + +inline void v_load_deinterleave( const unsigned* ptr, v_uint32x16& a, v_uint32x16& b, v_uint32x16& c ) +{ + __m512i bgr0 = _mm512_loadu_si512((const __m512i*)ptr); + __m512i bgr1 = _mm512_loadu_si512((const __m512i*)(ptr + 16)); + __m512i bgr2 = _mm512_loadu_si512((const __m512i*)(ptr + 32)); + + __m512i mask0 = _v512_set_epu32(29, 26, 23, 20, 17, 30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 0); + __m512i b01r1 = _mm512_permutex2var_epi32(bgr0, mask0, bgr1); + __m512i g12b2 = _mm512_permutex2var_epi32(bgr1, mask0, bgr2); + __m512i r20g0 = _mm512_permutex2var_epi32(bgr2, mask0, bgr0); + + a = v_uint32x16(_mm512_mask_blend_epi32(0xf800, b01r1, g12b2)); + b = v_uint32x16(_mm512_alignr_epi32(g12b2, r20g0, 11)); + c = v_uint32x16(_mm512_permutex2var_epi32(bgr1, _v512_set_epu32(21, 20, 19, 18, 17, 16, 13, 10, 7, 4, 1, 26, 25, 24, 23, 22), r20g0)); +} + +inline void v_load_deinterleave( const uint64* ptr, v_uint64x8& a, v_uint64x8& b, v_uint64x8& c ) +{ + __m512i bgr0 = _mm512_loadu_si512((const __m512i*)ptr); + __m512i bgr1 = _mm512_loadu_si512((const __m512i*)(ptr + 8)); + __m512i bgr2 = _mm512_loadu_si512((const __m512i*)(ptr + 16)); + + __m512i mask0 = _v512_set_epu64(13, 10, 15, 12, 9, 6, 3, 0); + __m512i b01g1 = _mm512_permutex2var_epi64(bgr0, mask0, bgr1); + __m512i r12b2 = _mm512_permutex2var_epi64(bgr1, mask0, bgr2); + __m512i g20r0 = _mm512_permutex2var_epi64(bgr2, mask0, bgr0); + + a = v_uint64x8(_mm512_mask_blend_epi64(0xc0, b01g1, r12b2)); + c = v_uint64x8(_mm512_alignr_epi64(r12b2, g20r0, 6)); + b = v_uint64x8(_mm512_permutex2var_epi64(bgr1, _v512_set_epu64(10, 9, 8, 5, 2, 13, 12, 11), g20r0)); +} + +inline void v_load_deinterleave( const uchar* ptr, v_uint8x64& a, v_uint8x64& b, v_uint8x64& c, v_uint8x64& d ) +{ + __m512i bgra0 = _mm512_loadu_si512((const __m512i*)ptr); + __m512i bgra1 = _mm512_loadu_si512((const __m512i*)(ptr + 64)); + __m512i bgra2 = _mm512_loadu_si512((const __m512i*)(ptr + 128)); + __m512i bgra3 = _mm512_loadu_si512((const __m512i*)(ptr + 192)); + +#if CV_AVX_512VBMI + __m512i mask0 = _v512_set_epu8(126, 124, 122, 120, 118, 116, 114, 112, 110, 108, 106, 104, 102, 100, 98, 96, + 94, 92, 90, 88, 86, 84, 82, 80, 78, 76, 74, 72, 70, 68, 66, 64, + 62, 60, 58, 56, 54, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32, + 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); + __m512i mask1 = _v512_set_epu8(127, 125, 123, 121, 119, 117, 115, 113, 111, 109, 107, 105, 103, 101, 99, 97, + 95, 93, 91, 89, 87, 85, 83, 81, 79, 77, 75, 73, 71, 69, 67, 65, + 63, 61, 59, 57, 55, 53, 51, 49, 47, 45, 43, 41, 39, 37, 35, 33, + 31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); + + __m512i br01 = _mm512_permutex2var_epi8(bgra0, mask0, bgra1); + __m512i ga01 = _mm512_permutex2var_epi8(bgra0, mask1, bgra1); + __m512i br23 = _mm512_permutex2var_epi8(bgra2, mask0, bgra3); + __m512i ga23 = _mm512_permutex2var_epi8(bgra2, mask1, bgra3); + + a = v_uint8x64(_mm512_permutex2var_epi8(br01, mask0, br23)); + c = v_uint8x64(_mm512_permutex2var_epi8(br01, mask1, br23)); + b = v_uint8x64(_mm512_permutex2var_epi8(ga01, mask0, ga23)); + d = v_uint8x64(_mm512_permutex2var_epi8(ga01, mask1, ga23)); +#else + __m512i mask = _mm512_set4_epi32(0x0f0b0703, 0x0e0a0602, 0x0d090501, 0x0c080400); + __m512i b0g0r0a0 = _mm512_shuffle_epi8(bgra0, mask); + __m512i b1g1r1a1 = _mm512_shuffle_epi8(bgra1, mask); + __m512i b2g2r2a2 = _mm512_shuffle_epi8(bgra2, mask); + __m512i b3g3r3a3 = _mm512_shuffle_epi8(bgra3, mask); + + __m512i mask0 = _v512_set_epu32(30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); + __m512i mask1 = _v512_set_epu32(31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); + + __m512i br01 = _mm512_permutex2var_epi32(b0g0r0a0, mask0, b1g1r1a1); + __m512i ga01 = _mm512_permutex2var_epi32(b0g0r0a0, mask1, b1g1r1a1); + __m512i br23 = _mm512_permutex2var_epi32(b2g2r2a2, mask0, b3g3r3a3); + __m512i ga23 = _mm512_permutex2var_epi32(b2g2r2a2, mask1, b3g3r3a3); + + a = v_uint8x64(_mm512_permutex2var_epi32(br01, mask0, br23)); + c = v_uint8x64(_mm512_permutex2var_epi32(br01, mask1, br23)); + b = v_uint8x64(_mm512_permutex2var_epi32(ga01, mask0, ga23)); + d = v_uint8x64(_mm512_permutex2var_epi32(ga01, mask1, ga23)); +#endif +} + +inline void v_load_deinterleave( const ushort* ptr, v_uint16x32& a, v_uint16x32& b, v_uint16x32& c, v_uint16x32& d ) +{ + __m512i bgra0 = _mm512_loadu_si512((const __m512i*)ptr); + __m512i bgra1 = _mm512_loadu_si512((const __m512i*)(ptr + 32)); + __m512i bgra2 = _mm512_loadu_si512((const __m512i*)(ptr + 64)); + __m512i bgra3 = _mm512_loadu_si512((const __m512i*)(ptr + 96)); + + __m512i mask0 = _v512_set_epu16(62, 60, 58, 56, 54, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32, + 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); + __m512i mask1 = _v512_set_epu16(63, 61, 59, 57, 55, 53, 51, 49, 47, 45, 43, 41, 39, 37, 35, 33, + 31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); + + __m512i br01 = _mm512_permutex2var_epi16(bgra0, mask0, bgra1); + __m512i ga01 = _mm512_permutex2var_epi16(bgra0, mask1, bgra1); + __m512i br23 = _mm512_permutex2var_epi16(bgra2, mask0, bgra3); + __m512i ga23 = _mm512_permutex2var_epi16(bgra2, mask1, bgra3); + + a = v_uint16x32(_mm512_permutex2var_epi16(br01, mask0, br23)); + c = v_uint16x32(_mm512_permutex2var_epi16(br01, mask1, br23)); + b = v_uint16x32(_mm512_permutex2var_epi16(ga01, mask0, ga23)); + d = v_uint16x32(_mm512_permutex2var_epi16(ga01, mask1, ga23)); +} + +inline void v_load_deinterleave( const unsigned* ptr, v_uint32x16& a, v_uint32x16& b, v_uint32x16& c, v_uint32x16& d ) +{ + __m512i bgra0 = _mm512_loadu_si512((const __m512i*)ptr); + __m512i bgra1 = _mm512_loadu_si512((const __m512i*)(ptr + 16)); + __m512i bgra2 = _mm512_loadu_si512((const __m512i*)(ptr + 32)); + __m512i bgra3 = _mm512_loadu_si512((const __m512i*)(ptr + 48)); + + __m512i mask0 = _v512_set_epu32(30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); + __m512i mask1 = _v512_set_epu32(31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); + + __m512i br01 = _mm512_permutex2var_epi32(bgra0, mask0, bgra1); + __m512i ga01 = _mm512_permutex2var_epi32(bgra0, mask1, bgra1); + __m512i br23 = _mm512_permutex2var_epi32(bgra2, mask0, bgra3); + __m512i ga23 = _mm512_permutex2var_epi32(bgra2, mask1, bgra3); + + a = v_uint32x16(_mm512_permutex2var_epi32(br01, mask0, br23)); + c = v_uint32x16(_mm512_permutex2var_epi32(br01, mask1, br23)); + b = v_uint32x16(_mm512_permutex2var_epi32(ga01, mask0, ga23)); + d = v_uint32x16(_mm512_permutex2var_epi32(ga01, mask1, ga23)); +} + +inline void v_load_deinterleave( const uint64* ptr, v_uint64x8& a, v_uint64x8& b, v_uint64x8& c, v_uint64x8& d ) +{ + __m512i bgra0 = _mm512_loadu_si512((const __m512i*)ptr); + __m512i bgra1 = _mm512_loadu_si512((const __m512i*)(ptr + 8)); + __m512i bgra2 = _mm512_loadu_si512((const __m512i*)(ptr + 16)); + __m512i bgra3 = _mm512_loadu_si512((const __m512i*)(ptr + 24)); + + __m512i mask0 = _v512_set_epu64(14, 12, 10, 8, 6, 4, 2, 0); + __m512i mask1 = _v512_set_epu64(15, 13, 11, 9, 7, 5, 3, 1); + + __m512i br01 = _mm512_permutex2var_epi64(bgra0, mask0, bgra1); + __m512i ga01 = _mm512_permutex2var_epi64(bgra0, mask1, bgra1); + __m512i br23 = _mm512_permutex2var_epi64(bgra2, mask0, bgra3); + __m512i ga23 = _mm512_permutex2var_epi64(bgra2, mask1, bgra3); + + a = v_uint64x8(_mm512_permutex2var_epi64(br01, mask0, br23)); + c = v_uint64x8(_mm512_permutex2var_epi64(br01, mask1, br23)); + b = v_uint64x8(_mm512_permutex2var_epi64(ga01, mask0, ga23)); + d = v_uint64x8(_mm512_permutex2var_epi64(ga01, mask1, ga23)); +} + +///////////////////////////// store interleave ///////////////////////////////////// + +inline void v_store_interleave( uchar* ptr, const v_uint8x64& x, const v_uint8x64& y, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + v_uint8x64 low, high; + v_zip(x, y, low, high); + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm512_stream_si512((__m512i*)ptr, low.val); + _mm512_stream_si512((__m512i*)(ptr + 64), high.val); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm512_store_si512((__m512i*)ptr, low.val); + _mm512_store_si512((__m512i*)(ptr + 64), high.val); + } + else + { + _mm512_storeu_si512((__m512i*)ptr, low.val); + _mm512_storeu_si512((__m512i*)(ptr + 64), high.val); + } +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x32& x, const v_uint16x32& y, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + v_uint16x32 low, high; + v_zip(x, y, low, high); + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm512_stream_si512((__m512i*)ptr, low.val); + _mm512_stream_si512((__m512i*)(ptr + 32), high.val); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm512_store_si512((__m512i*)ptr, low.val); + _mm512_store_si512((__m512i*)(ptr + 32), high.val); + } + else + { + _mm512_storeu_si512((__m512i*)ptr, low.val); + _mm512_storeu_si512((__m512i*)(ptr + 32), high.val); + } +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x16& x, const v_uint32x16& y, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + v_uint32x16 low, high; + v_zip(x, y, low, high); + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm512_stream_si512((__m512i*)ptr, low.val); + _mm512_stream_si512((__m512i*)(ptr + 16), high.val); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm512_store_si512((__m512i*)ptr, low.val); + _mm512_store_si512((__m512i*)(ptr + 16), high.val); + } + else + { + _mm512_storeu_si512((__m512i*)ptr, low.val); + _mm512_storeu_si512((__m512i*)(ptr + 16), high.val); + } +} + +inline void v_store_interleave( uint64* ptr, const v_uint64x8& x, const v_uint64x8& y, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + v_uint64x8 low, high; + v_zip(x, y, low, high); + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm512_stream_si512((__m512i*)ptr, low.val); + _mm512_stream_si512((__m512i*)(ptr + 8), high.val); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm512_store_si512((__m512i*)ptr, low.val); + _mm512_store_si512((__m512i*)(ptr + 8), high.val); + } + else + { + _mm512_storeu_si512((__m512i*)ptr, low.val); + _mm512_storeu_si512((__m512i*)(ptr + 8), high.val); + } +} + +inline void v_store_interleave( uchar* ptr, const v_uint8x64& a, const v_uint8x64& b, const v_uint8x64& c, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ +#if CV_AVX_512VBMI + __m512i mask0 = _v512_set_epu8(127, 84, 20, 126, 83, 19, 125, 82, 18, 124, 81, 17, 123, 80, 16, 122, + 79, 15, 121, 78, 14, 120, 77, 13, 119, 76, 12, 118, 75, 11, 117, 74, + 10, 116, 73, 9, 115, 72, 8, 114, 71, 7, 113, 70, 6, 112, 69, 5, + 111, 68, 4, 110, 67, 3, 109, 66, 2, 108, 65, 1, 107, 64, 0, 106); + __m512i mask1 = _v512_set_epu8( 21, 42, 105, 20, 41, 104, 19, 40, 103, 18, 39, 102, 17, 38, 101, 16, + 37, 100, 15, 36, 99, 14, 35, 98, 13, 34, 97, 12, 33, 96, 11, 32, + 95, 10, 31, 94, 9, 30, 93, 8, 29, 92, 7, 28, 91, 6, 27, 90, + 5, 26, 89, 4, 25, 88, 3, 24, 87, 2, 23, 86, 1, 22, 85, 0); + __m512i mask2 = _v512_set_epu8(106, 127, 63, 105, 126, 62, 104, 125, 61, 103, 124, 60, 102, 123, 59, 101, + 122, 58, 100, 121, 57, 99, 120, 56, 98, 119, 55, 97, 118, 54, 96, 117, + 53, 95, 116, 52, 94, 115, 51, 93, 114, 50, 92, 113, 49, 91, 112, 48, + 90, 111, 47, 89, 110, 46, 88, 109, 45, 87, 108, 44, 86, 107, 43, 85); + __m512i r2g0r0 = _mm512_permutex2var_epi8(b.val, mask0, c.val); + __m512i b0r1b1 = _mm512_permutex2var_epi8(a.val, mask1, c.val); + __m512i g1b2g2 = _mm512_permutex2var_epi8(a.val, mask2, b.val); + + __m512i bgr0 = _mm512_mask_blend_epi8(0x9249249249249249, r2g0r0, b0r1b1); + __m512i bgr1 = _mm512_mask_blend_epi8(0x9249249249249249, b0r1b1, g1b2g2); + __m512i bgr2 = _mm512_mask_blend_epi8(0x9249249249249249, g1b2g2, r2g0r0); +#else + __m512i g1g0 = _mm512_shuffle_epi8(b.val, _mm512_set4_epi32(0x0e0f0c0d, 0x0a0b0809, 0x06070405, 0x02030001)); + __m512i b0g0 = _mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, a.val, g1g0); + __m512i r0b1 = _mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, c.val, a.val); + __m512i g1r1 = _mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, g1g0, c.val); + + __m512i mask0 = _v512_set_epu16(42, 10, 31, 41, 9, 30, 40, 8, 29, 39, 7, 28, 38, 6, 27, 37, + 5, 26, 36, 4, 25, 35, 3, 24, 34, 2, 23, 33, 1, 22, 32, 0); + __m512i mask1 = _v512_set_epu16(21, 52, 41, 20, 51, 40, 19, 50, 39, 18, 49, 38, 17, 48, 37, 16, + 47, 36, 15, 46, 35, 14, 45, 34, 13, 44, 33, 12, 43, 32, 11, 42); + __m512i mask2 = _v512_set_epu16(63, 31, 20, 62, 30, 19, 61, 29, 18, 60, 28, 17, 59, 27, 16, 58, + 26, 15, 57, 25, 14, 56, 24, 13, 55, 23, 12, 54, 22, 11, 53, 21); + __m512i b0g0b2 = _mm512_permutex2var_epi16(b0g0, mask0, r0b1); + __m512i r1b1r0 = _mm512_permutex2var_epi16(b0g0, mask1, g1r1); + __m512i g2r2g1 = _mm512_permutex2var_epi16(r0b1, mask2, g1r1); + + __m512i bgr0 = _mm512_mask_blend_epi16(0x24924924, b0g0b2, r1b1r0); + __m512i bgr1 = _mm512_mask_blend_epi16(0x24924924, r1b1r0, g2r2g1); + __m512i bgr2 = _mm512_mask_blend_epi16(0x24924924, g2r2g1, b0g0b2); +#endif + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm512_stream_si512((__m512i*)ptr, bgr0); + _mm512_stream_si512((__m512i*)(ptr + 64), bgr1); + _mm512_stream_si512((__m512i*)(ptr + 128), bgr2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm512_store_si512((__m512i*)ptr, bgr0); + _mm512_store_si512((__m512i*)(ptr + 64), bgr1); + _mm512_store_si512((__m512i*)(ptr + 128), bgr2); + } + else + { + _mm512_storeu_si512((__m512i*)ptr, bgr0); + _mm512_storeu_si512((__m512i*)(ptr + 64), bgr1); + _mm512_storeu_si512((__m512i*)(ptr + 128), bgr2); + } +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x32& a, const v_uint16x32& b, const v_uint16x32& c, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m512i mask0 = _v512_set_epu16(42, 10, 31, 41, 9, 30, 40, 8, 29, 39, 7, 28, 38, 6, 27, 37, + 5, 26, 36, 4, 25, 35, 3, 24, 34, 2, 23, 33, 1, 22, 32, 0); + __m512i mask1 = _v512_set_epu16(21, 52, 41, 20, 51, 40, 19, 50, 39, 18, 49, 38, 17, 48, 37, 16, + 47, 36, 15, 46, 35, 14, 45, 34, 13, 44, 33, 12, 43, 32, 11, 42); + __m512i mask2 = _v512_set_epu16(63, 31, 20, 62, 30, 19, 61, 29, 18, 60, 28, 17, 59, 27, 16, 58, + 26, 15, 57, 25, 14, 56, 24, 13, 55, 23, 12, 54, 22, 11, 53, 21); + __m512i b0g0b2 = _mm512_permutex2var_epi16(a.val, mask0, b.val); + __m512i r1b1r0 = _mm512_permutex2var_epi16(a.val, mask1, c.val); + __m512i g2r2g1 = _mm512_permutex2var_epi16(b.val, mask2, c.val); + + __m512i bgr0 = _mm512_mask_blend_epi16(0x24924924, b0g0b2, r1b1r0); + __m512i bgr1 = _mm512_mask_blend_epi16(0x24924924, r1b1r0, g2r2g1); + __m512i bgr2 = _mm512_mask_blend_epi16(0x24924924, g2r2g1, b0g0b2); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm512_stream_si512((__m512i*)ptr, bgr0); + _mm512_stream_si512((__m512i*)(ptr + 32), bgr1); + _mm512_stream_si512((__m512i*)(ptr + 64), bgr2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm512_store_si512((__m512i*)ptr, bgr0); + _mm512_store_si512((__m512i*)(ptr + 32), bgr1); + _mm512_store_si512((__m512i*)(ptr + 64), bgr2); + } + else + { + _mm512_storeu_si512((__m512i*)ptr, bgr0); + _mm512_storeu_si512((__m512i*)(ptr + 32), bgr1); + _mm512_storeu_si512((__m512i*)(ptr + 64), bgr2); + } +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x16& a, const v_uint32x16& b, const v_uint32x16& c, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m512i mask0 = _v512_set_epu32(26, 31, 15, 25, 30, 14, 24, 29, 13, 23, 28, 12, 22, 27, 11, 21); + __m512i mask1 = _v512_set_epu32(31, 10, 25, 30, 9, 24, 29, 8, 23, 28, 7, 22, 27, 6, 21, 26); + __m512i g1b2g2 = _mm512_permutex2var_epi32(a.val, mask0, b.val); + __m512i r2r1b1 = _mm512_permutex2var_epi32(a.val, mask1, c.val); + + __m512i bgr0 = _mm512_mask_expand_epi32(_mm512_mask_expand_epi32(_mm512_maskz_expand_epi32(0x9249, a.val), 0x2492, b.val), 0x4924, c.val); + __m512i bgr1 = _mm512_mask_blend_epi32(0x9249, r2r1b1, g1b2g2); + __m512i bgr2 = _mm512_mask_blend_epi32(0x9249, g1b2g2, r2r1b1); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm512_stream_si512((__m512i*)ptr, bgr0); + _mm512_stream_si512((__m512i*)(ptr + 16), bgr1); + _mm512_stream_si512((__m512i*)(ptr + 32), bgr2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm512_store_si512((__m512i*)ptr, bgr0); + _mm512_store_si512((__m512i*)(ptr + 16), bgr1); + _mm512_store_si512((__m512i*)(ptr + 32), bgr2); + } + else + { + _mm512_storeu_si512((__m512i*)ptr, bgr0); + _mm512_storeu_si512((__m512i*)(ptr + 16), bgr1); + _mm512_storeu_si512((__m512i*)(ptr + 32), bgr2); + } +} + +inline void v_store_interleave( uint64* ptr, const v_uint64x8& a, const v_uint64x8& b, const v_uint64x8& c, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m512i mask0 = _v512_set_epu64( 5, 12, 7, 4, 11, 6, 3, 10); + __m512i mask1 = _v512_set_epu64(15, 7, 4, 14, 6, 3, 13, 5); + __m512i r1b1b2 = _mm512_permutex2var_epi64(a.val, mask0, c.val); + __m512i g2r2g1 = _mm512_permutex2var_epi64(b.val, mask1, c.val); + + __m512i bgr0 = _mm512_mask_expand_epi64(_mm512_mask_expand_epi64(_mm512_maskz_expand_epi64(0x49, a.val), 0x92, b.val), 0x24, c.val); + __m512i bgr1 = _mm512_mask_blend_epi64(0xdb, g2r2g1, r1b1b2); + __m512i bgr2 = _mm512_mask_blend_epi64(0xdb, r1b1b2, g2r2g1); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm512_stream_si512((__m512i*)ptr, bgr0); + _mm512_stream_si512((__m512i*)(ptr + 8), bgr1); + _mm512_stream_si512((__m512i*)(ptr + 16), bgr2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm512_store_si512((__m512i*)ptr, bgr0); + _mm512_store_si512((__m512i*)(ptr + 8), bgr1); + _mm512_store_si512((__m512i*)(ptr + 16), bgr2); + } + else + { + _mm512_storeu_si512((__m512i*)ptr, bgr0); + _mm512_storeu_si512((__m512i*)(ptr + 8), bgr1); + _mm512_storeu_si512((__m512i*)(ptr + 16), bgr2); + } +} + +inline void v_store_interleave( uchar* ptr, const v_uint8x64& a, const v_uint8x64& b, + const v_uint8x64& c, const v_uint8x64& d, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + v_uint8x64 br01, br23, ga01, ga23; + v_zip(a, c, br01, br23); + v_zip(b, d, ga01, ga23); + v_uint8x64 bgra0, bgra1, bgra2, bgra3; + v_zip(br01, ga01, bgra0, bgra1); + v_zip(br23, ga23, bgra2, bgra3); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm512_stream_si512((__m512i*)ptr, bgra0.val); + _mm512_stream_si512((__m512i*)(ptr + 64), bgra1.val); + _mm512_stream_si512((__m512i*)(ptr + 128), bgra2.val); + _mm512_stream_si512((__m512i*)(ptr + 192), bgra3.val); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm512_store_si512((__m512i*)ptr, bgra0.val); + _mm512_store_si512((__m512i*)(ptr + 64), bgra1.val); + _mm512_store_si512((__m512i*)(ptr + 128), bgra2.val); + _mm512_store_si512((__m512i*)(ptr + 192), bgra3.val); + } + else + { + _mm512_storeu_si512((__m512i*)ptr, bgra0.val); + _mm512_storeu_si512((__m512i*)(ptr + 64), bgra1.val); + _mm512_storeu_si512((__m512i*)(ptr + 128), bgra2.val); + _mm512_storeu_si512((__m512i*)(ptr + 192), bgra3.val); + } +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x32& a, const v_uint16x32& b, + const v_uint16x32& c, const v_uint16x32& d, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + v_uint16x32 br01, br23, ga01, ga23; + v_zip(a, c, br01, br23); + v_zip(b, d, ga01, ga23); + v_uint16x32 bgra0, bgra1, bgra2, bgra3; + v_zip(br01, ga01, bgra0, bgra1); + v_zip(br23, ga23, bgra2, bgra3); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm512_stream_si512((__m512i*)ptr, bgra0.val); + _mm512_stream_si512((__m512i*)(ptr + 32), bgra1.val); + _mm512_stream_si512((__m512i*)(ptr + 64), bgra2.val); + _mm512_stream_si512((__m512i*)(ptr + 96), bgra3.val); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm512_store_si512((__m512i*)ptr, bgra0.val); + _mm512_store_si512((__m512i*)(ptr + 32), bgra1.val); + _mm512_store_si512((__m512i*)(ptr + 64), bgra2.val); + _mm512_store_si512((__m512i*)(ptr + 96), bgra3.val); + } + else + { + _mm512_storeu_si512((__m512i*)ptr, bgra0.val); + _mm512_storeu_si512((__m512i*)(ptr + 32), bgra1.val); + _mm512_storeu_si512((__m512i*)(ptr + 64), bgra2.val); + _mm512_storeu_si512((__m512i*)(ptr + 96), bgra3.val); + } +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x16& a, const v_uint32x16& b, + const v_uint32x16& c, const v_uint32x16& d, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + v_uint32x16 br01, br23, ga01, ga23; + v_zip(a, c, br01, br23); + v_zip(b, d, ga01, ga23); + v_uint32x16 bgra0, bgra1, bgra2, bgra3; + v_zip(br01, ga01, bgra0, bgra1); + v_zip(br23, ga23, bgra2, bgra3); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm512_stream_si512((__m512i*)ptr, bgra0.val); + _mm512_stream_si512((__m512i*)(ptr + 16), bgra1.val); + _mm512_stream_si512((__m512i*)(ptr + 32), bgra2.val); + _mm512_stream_si512((__m512i*)(ptr + 48), bgra3.val); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm512_store_si512((__m512i*)ptr, bgra0.val); + _mm512_store_si512((__m512i*)(ptr + 16), bgra1.val); + _mm512_store_si512((__m512i*)(ptr + 32), bgra2.val); + _mm512_store_si512((__m512i*)(ptr + 48), bgra3.val); + } + else + { + _mm512_storeu_si512((__m512i*)ptr, bgra0.val); + _mm512_storeu_si512((__m512i*)(ptr + 16), bgra1.val); + _mm512_storeu_si512((__m512i*)(ptr + 32), bgra2.val); + _mm512_storeu_si512((__m512i*)(ptr + 48), bgra3.val); + } +} + +inline void v_store_interleave( uint64* ptr, const v_uint64x8& a, const v_uint64x8& b, + const v_uint64x8& c, const v_uint64x8& d, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + v_uint64x8 br01, br23, ga01, ga23; + v_zip(a, c, br01, br23); + v_zip(b, d, ga01, ga23); + v_uint64x8 bgra0, bgra1, bgra2, bgra3; + v_zip(br01, ga01, bgra0, bgra1); + v_zip(br23, ga23, bgra2, bgra3); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm512_stream_si512((__m512i*)ptr, bgra0.val); + _mm512_stream_si512((__m512i*)(ptr + 8), bgra1.val); + _mm512_stream_si512((__m512i*)(ptr + 16), bgra2.val); + _mm512_stream_si512((__m512i*)(ptr + 24), bgra3.val); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm512_store_si512((__m512i*)ptr, bgra0.val); + _mm512_store_si512((__m512i*)(ptr + 8), bgra1.val); + _mm512_store_si512((__m512i*)(ptr + 16), bgra2.val); + _mm512_store_si512((__m512i*)(ptr + 24), bgra3.val); + } + else + { + _mm512_storeu_si512((__m512i*)ptr, bgra0.val); + _mm512_storeu_si512((__m512i*)(ptr + 8), bgra1.val); + _mm512_storeu_si512((__m512i*)(ptr + 16), bgra2.val); + _mm512_storeu_si512((__m512i*)(ptr + 24), bgra3.val); + } +} + +#define OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(_Tpvec0, _Tp0, suffix0, _Tpvec1, _Tp1, suffix1) \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0 ) \ +{ \ + _Tpvec1 a1, b1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ +} \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0 ) \ +{ \ + _Tpvec1 a1, b1, c1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ + c0 = v_reinterpret_as_##suffix0(c1); \ +} \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0, _Tpvec0& d0 ) \ +{ \ + _Tpvec1 a1, b1, c1, d1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1, d1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ + c0 = v_reinterpret_as_##suffix0(c1); \ + d0 = v_reinterpret_as_##suffix0(d1); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + hal::StoreMode mode=hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, mode); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, const _Tpvec0& c0, \ + hal::StoreMode mode=hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, c1, mode); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + const _Tpvec0& c0, const _Tpvec0& d0, \ + hal::StoreMode mode=hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ + _Tpvec1 d1 = v_reinterpret_as_##suffix1(d0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, c1, d1, mode); \ +} + +OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(v_int8x64, schar, s8, v_uint8x64, uchar, u8) +OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(v_int16x32, short, s16, v_uint16x32, ushort, u16) +OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(v_int32x16, int, s32, v_uint32x16, unsigned, u32) +OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(v_float32x16, float, f32, v_uint32x16, unsigned, u32) +OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(v_int64x8, int64, s64, v_uint64x8, uint64, u64) +OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(v_float64x8, double, f64, v_uint64x8, uint64, u64) + +////////// Mask and checks ///////// + +/** Mask **/ +inline int64 v_signmask(const v_int8x64& a) { return (int64)_mm512_movepi8_mask(a.val); } +inline int v_signmask(const v_int16x32& a) { return (int)_mm512_cmp_epi16_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_LT); } +inline int v_signmask(const v_int32x16& a) { return (int)_mm512_cmp_epi32_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_LT); } +inline int v_signmask(const v_int64x8& a) { return (int)_mm512_cmp_epi64_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_LT); } + +inline int64 v_signmask(const v_uint8x64& a) { return v_signmask(v_reinterpret_as_s8(a)); } +inline int v_signmask(const v_uint16x32& a) { return v_signmask(v_reinterpret_as_s16(a)); } +inline int v_signmask(const v_uint32x16& a) { return v_signmask(v_reinterpret_as_s32(a)); } +inline int v_signmask(const v_uint64x8& a) { return v_signmask(v_reinterpret_as_s64(a)); } +inline int v_signmask(const v_float32x16& a) { return v_signmask(v_reinterpret_as_s32(a)); } +inline int v_signmask(const v_float64x8& a) { return v_signmask(v_reinterpret_as_s64(a)); } + +/** Checks **/ +inline bool v_check_all(const v_int8x64& a) { return !(bool)_mm512_cmp_epi8_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_NLT); } +inline bool v_check_any(const v_int8x64& a) { return (bool)_mm512_movepi8_mask(a.val); } +inline bool v_check_all(const v_int16x32& a) { return !(bool)_mm512_cmp_epi16_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_NLT); } +inline bool v_check_any(const v_int16x32& a) { return (bool)_mm512_cmp_epi16_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_LT); } +inline bool v_check_all(const v_int32x16& a) { return !(bool)_mm512_cmp_epi32_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_NLT); } +inline bool v_check_any(const v_int32x16& a) { return (bool)_mm512_cmp_epi32_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_LT); } +inline bool v_check_all(const v_int64x8& a) { return !(bool)_mm512_cmp_epi64_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_NLT); } +inline bool v_check_any(const v_int64x8& a) { return (bool)_mm512_cmp_epi64_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_LT); } + +inline bool v_check_all(const v_float32x16& a) { return v_check_all(v_reinterpret_as_s32(a)); } +inline bool v_check_any(const v_float32x16& a) { return v_check_any(v_reinterpret_as_s32(a)); } +inline bool v_check_all(const v_float64x8& a) { return v_check_all(v_reinterpret_as_s64(a)); } +inline bool v_check_any(const v_float64x8& a) { return v_check_any(v_reinterpret_as_s64(a)); } +inline bool v_check_all(const v_uint8x64& a) { return v_check_all(v_reinterpret_as_s8(a)); } +inline bool v_check_all(const v_uint16x32& a) { return v_check_all(v_reinterpret_as_s16(a)); } +inline bool v_check_all(const v_uint32x16& a) { return v_check_all(v_reinterpret_as_s32(a)); } +inline bool v_check_all(const v_uint64x8& a) { return v_check_all(v_reinterpret_as_s64(a)); } +inline bool v_check_any(const v_uint8x64& a) { return v_check_any(v_reinterpret_as_s8(a)); } +inline bool v_check_any(const v_uint16x32& a) { return v_check_any(v_reinterpret_as_s16(a)); } +inline bool v_check_any(const v_uint32x16& a) { return v_check_any(v_reinterpret_as_s32(a)); } +inline bool v_check_any(const v_uint64x8& a) { return v_check_any(v_reinterpret_as_s64(a)); } + +inline int v_scan_forward(const v_int8x64& a) +{ + int64 mask = _mm512_movepi8_mask(a.val); + int mask32 = (int)mask; + return mask != 0 ? mask32 != 0 ? trailingZeros32(mask32) : 32 + trailingZeros32((int)(mask >> 32)) : 0; +} +inline int v_scan_forward(const v_uint8x64& a) { return v_scan_forward(v_reinterpret_as_s8(a)); } +inline int v_scan_forward(const v_int16x32& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))); } +inline int v_scan_forward(const v_uint16x32& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))); } +inline int v_scan_forward(const v_int32x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))) / 2; } +inline int v_scan_forward(const v_uint32x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))) / 2; } +inline int v_scan_forward(const v_float32x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))) / 2; } +inline int v_scan_forward(const v_int64x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))) / 4; } +inline int v_scan_forward(const v_uint64x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))) / 4; } +inline int v_scan_forward(const v_float64x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))) / 4; } + +inline void v512_cleanup() { _mm256_zeroall(); } + +#include "intrin_math.hpp" +inline v_float32x16 v_exp(const v_float32x16& x) { return v_exp_default_32f(x); } +inline v_float32x16 v_log(const v_float32x16& x) { return v_log_default_32f(x); } +inline void v_sincos(const v_float32x16& x, v_float32x16& s, v_float32x16& c) { v_sincos_default_32f(x, s, c); } +inline v_float32x16 v_sin(const v_float32x16& x) { return v_sin_default_32f(x); } +inline v_float32x16 v_cos(const v_float32x16& x) { return v_cos_default_32f(x); } +inline v_float32x16 v_erf(const v_float32x16& x) { return v_erf_default_32f(x); } + +inline v_float64x8 v_exp(const v_float64x8& x) { return v_exp_default_64f(x); } +inline v_float64x8 v_log(const v_float64x8& x) { return v_log_default_64f(x); } +inline void v_sincos(const v_float64x8& x, v_float64x8& s, v_float64x8& c) { v_sincos_default_64f(x, s, c); } +inline v_float64x8 v_sin(const v_float64x8& x) { return v_sin_default_64f(x); } +inline v_float64x8 v_cos(const v_float64x8& x) { return v_cos_default_64f(x); } + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} // cv:: + +#endif // OPENCV_HAL_INTRIN_AVX_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_cpp.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_cpp.hpp index 3e5d484145..1b2462c642 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_cpp.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_cpp.hpp @@ -1,3373 +1,3373 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_HAL_INTRIN_CPP_HPP -#define OPENCV_HAL_INTRIN_CPP_HPP - -#include -#include -#include -#include "opencv2/core/utility.hpp" -#include "opencv2/core/saturate.hpp" - -//! @cond IGNORED -#define CV_SIMD128_CPP 1 -#if defined(CV_FORCE_SIMD128_CPP) -#define CV_SIMD128 1 -#define CV_SIMD128_64F 1 -#endif -#if defined(CV_DOXYGEN) -#define CV_SIMD128 1 -#define CV_SIMD128_64F 1 -#define CV_SIMD256 1 -#define CV_SIMD256_64F 1 -#define CV_SIMD512 1 -#define CV_SIMD512_64F 1 -#else -#define CV_SIMD256 0 // Explicitly disable SIMD256 and SIMD512 support for scalar intrinsic implementation -#define CV_SIMD512 0 // to avoid warnings during compilation -#endif -//! @endcond - -namespace cv -{ - -#ifndef CV_DOXYGEN -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN -#endif - -/** @addtogroup core_hal_intrin - -"Universal intrinsics" is a types and functions set intended to simplify vectorization of code on -different platforms. Currently a few different SIMD extensions on different architectures are supported. -128 bit registers of various types support is implemented for a wide range of architectures -including x86(__SSE/SSE2/SSE4.2__), ARM(__NEON__), PowerPC(__VSX__), MIPS(__MSA__). -256 bit long registers are supported on x86(__AVX2__) and 512 bit long registers are supported on x86(__AVX512__). -In case when there is no SIMD extension available during compilation, fallback C++ implementation of intrinsics -will be chosen and code will work as expected although it could be slower. - -### Types - -There are several types representing packed values vector registers, each type is -implemented as a structure based on a one SIMD register. - -- cv::v_uint8 and cv::v_int8: 8-bit integer values (unsigned/signed) - char -- cv::v_uint16 and cv::v_int16: 16-bit integer values (unsigned/signed) - short -- cv::v_uint32 and cv::v_int32: 32-bit integer values (unsigned/signed) - int -- cv::v_uint64 and cv::v_int64: 64-bit integer values (unsigned/signed) - int64 -- cv::v_float32: 32-bit floating point values (signed) - float -- cv::v_float64: 64-bit floating point values (signed) - double - -Exact bit length(and value quantity) of listed types is compile time deduced and depends on architecture SIMD -capabilities chosen as available during compilation of the library. All the types contains __nlanes__ enumeration -to check for exact value quantity of the type. - -In case the exact bit length of the type is important it is possible to use specific fixed length register types. - -There are several types representing 128-bit registers. - -- cv::v_uint8x16 and cv::v_int8x16: sixteen 8-bit integer values (unsigned/signed) - char -- cv::v_uint16x8 and cv::v_int16x8: eight 16-bit integer values (unsigned/signed) - short -- cv::v_uint32x4 and cv::v_int32x4: four 32-bit integer values (unsigned/signed) - int -- cv::v_uint64x2 and cv::v_int64x2: two 64-bit integer values (unsigned/signed) - int64 -- cv::v_float32x4: four 32-bit floating point values (signed) - float -- cv::v_float64x2: two 64-bit floating point values (signed) - double - -There are several types representing 256-bit registers. - -- cv::v_uint8x32 and cv::v_int8x32: thirty two 8-bit integer values (unsigned/signed) - char -- cv::v_uint16x16 and cv::v_int16x16: sixteen 16-bit integer values (unsigned/signed) - short -- cv::v_uint32x8 and cv::v_int32x8: eight 32-bit integer values (unsigned/signed) - int -- cv::v_uint64x4 and cv::v_int64x4: four 64-bit integer values (unsigned/signed) - int64 -- cv::v_float32x8: eight 32-bit floating point values (signed) - float -- cv::v_float64x4: four 64-bit floating point values (signed) - double - -@note -256 bit registers at the moment implemented for AVX2 SIMD extension only, if you want to use this type directly, -don't forget to check the CV_SIMD256 preprocessor definition: -@code -#if CV_SIMD256 -//... -#endif -@endcode - -There are several types representing 512-bit registers. - -- cv::v_uint8x64 and cv::v_int8x64: sixty four 8-bit integer values (unsigned/signed) - char -- cv::v_uint16x32 and cv::v_int16x32: thirty two 16-bit integer values (unsigned/signed) - short -- cv::v_uint32x16 and cv::v_int32x16: sixteen 32-bit integer values (unsigned/signed) - int -- cv::v_uint64x8 and cv::v_int64x8: eight 64-bit integer values (unsigned/signed) - int64 -- cv::v_float32x16: sixteen 32-bit floating point values (signed) - float -- cv::v_float64x8: eight 64-bit floating point values (signed) - double -@note -512 bit registers at the moment implemented for AVX512 SIMD extension only, if you want to use this type directly, -don't forget to check the CV_SIMD512 preprocessor definition. - -@note -cv::v_float64x2 is not implemented in NEON variant, if you want to use this type, don't forget to -check the CV_SIMD128_64F preprocessor definition. - -### Load and store operations - -These operations allow to set contents of the register explicitly or by loading it from some memory -block and to save contents of the register to memory block. - -There are variable size register load operations that provide result of maximum available size -depending on chosen platform capabilities. -- Constructors: -@ref v_reg::v_reg(const _Tp *ptr) "from memory", -- Other create methods: -vx_setall_s8, vx_setall_u8, ..., -vx_setzero_u8, vx_setzero_s8, ... -- Memory load operations: -vx_load, vx_load_aligned, vx_load_low, vx_load_halves, -- Memory operations with expansion of values: -vx_load_expand, vx_load_expand_q - -Also there are fixed size register load/store operations. - -For 128 bit registers -- Constructors: -@ref v_reg::v_reg(const _Tp *ptr) "from memory", -@ref v_reg::v_reg(_Tp s0, _Tp s1) "from two values", ... -- Other create methods: -@ref v_setall_s8, @ref v_setall_u8, ..., -@ref v_setzero_u8, @ref v_setzero_s8, ... -- Memory load operations: -@ref v_load, @ref v_load_aligned, @ref v_load_low, @ref v_load_halves, -- Memory operations with expansion of values: -@ref v_load_expand, @ref v_load_expand_q - -For 256 bit registers(check CV_SIMD256 preprocessor definition) -- Constructors: -@ref v_reg::v_reg(const _Tp *ptr) "from memory", -@ref v_reg::v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3) "from four values", ... -- Other create methods: -@ref v256_setall_s8, @ref v256_setall_u8, ..., -@ref v256_setzero_u8, @ref v256_setzero_s8, ... -- Memory load operations: -@ref v256_load, @ref v256_load_aligned, @ref v256_load_low, @ref v256_load_halves, -- Memory operations with expansion of values: -@ref v256_load_expand, @ref v256_load_expand_q - -For 512 bit registers(check CV_SIMD512 preprocessor definition) -- Constructors: -@ref v_reg::v_reg(const _Tp *ptr) "from memory", -@ref v_reg::v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3, _Tp s4, _Tp s5, _Tp s6, _Tp s7) "from eight values", ... -- Other create methods: -@ref v512_setall_s8, @ref v512_setall_u8, ..., -@ref v512_setzero_u8, @ref v512_setzero_s8, ... -- Memory load operations: -@ref v512_load, @ref v512_load_aligned, @ref v512_load_low, @ref v512_load_halves, -- Memory operations with expansion of values: -@ref v512_load_expand, @ref v512_load_expand_q - -Store to memory operations are similar across different platform capabilities: -@ref v_store, @ref v_store_aligned, -@ref v_store_high, @ref v_store_low - -### Value reordering - -These operations allow to reorder or recombine elements in one or multiple vectors. - -- Interleave, deinterleave (2, 3 and 4 channels): @ref v_load_deinterleave, @ref v_store_interleave -- Expand: @ref v_expand, @ref v_expand_low, @ref v_expand_high -- Pack: @ref v_pack, @ref v_pack_u, @ref v_pack_b, @ref v_rshr_pack, @ref v_rshr_pack_u, -@ref v_pack_store, @ref v_pack_u_store, @ref v_rshr_pack_store, @ref v_rshr_pack_u_store -- Recombine: @ref v_zip, @ref v_recombine, @ref v_combine_low, @ref v_combine_high -- Reverse: @ref v_reverse -- Extract: @ref v_extract - - -### Arithmetic, bitwise and comparison operations - -Element-wise binary and unary operations. - -- Arithmetics: -@ref v_add(const v_reg &a, const v_reg &b) "+", -@ref v_sub(const v_reg &a, const v_reg &b) "-", -@ref v_mul(const v_reg &a, const v_reg &b) "*", -@ref v_div(const v_reg &a, const v_reg &b) "/", -@ref v_mul_expand - -- Non-saturating arithmetics: @ref v_add_wrap, @ref v_sub_wrap - -- Bitwise shifts: -@ref v_shl(const v_reg &a, int s) "<<", -@ref v_shr(const v_reg &a, int s) ">>", -@ref v_shl, @ref v_shr - -- Bitwise logic: -@ref v_and(const v_reg &a, const v_reg &b) "&", -@ref v_or(const v_reg &a, const v_reg &b) "|", -@ref v_xor(const v_reg &a, const v_reg &b) "^", -@ref v_not(const v_reg &a) "~" - -- Comparison: -@ref v_gt(const v_reg &a, const v_reg &b) ">", -@ref v_ge(const v_reg &a, const v_reg &b) ">=", -@ref v_lt(const v_reg &a, const v_reg &b) "<", -@ref v_le(const v_reg &a, const v_reg &b) "<=", -@ref v_eq(const v_reg &a, const v_reg &b) "==", -@ref v_ne(const v_reg &a, const v_reg &b) "!=" - -- min/max: @ref v_min, @ref v_max - -### Reduce and mask - -Most of these operations return only one value. - -- Reduce: @ref v_reduce_min, @ref v_reduce_max, @ref v_reduce_sum, @ref v_popcount -- Mask: @ref v_signmask, @ref v_check_all, @ref v_check_any, @ref v_select - -### Other math - -- Some frequent operations: @ref v_sqrt, @ref v_invsqrt, @ref v_magnitude, @ref v_sqr_magnitude, @ref v_exp, @ref v_log, - @ref v_erf, @ref v_sin, @ref v_cos -- Absolute values: @ref v_abs, @ref v_absdiff, @ref v_absdiffs - -### Conversions - -Different type conversions and casts: - -- Rounding: @ref v_round, @ref v_floor, @ref v_ceil, @ref v_trunc, -- To float: @ref v_cvt_f32, @ref v_cvt_f64 -- Reinterpret: @ref v_reinterpret_as_u8, @ref v_reinterpret_as_s8, ... - -### Matrix operations - -In these operations vectors represent matrix rows/columns: @ref v_dotprod, @ref v_dotprod_fast, -@ref v_dotprod_expand, @ref v_dotprod_expand_fast, @ref v_matmul, @ref v_transpose4x4 - -### Usability - -Most operations are implemented only for some subset of the available types, following matrices -shows the applicability of different operations to the types. - -Regular integers: - -| Operations\\Types | uint 8 | int 8 | uint 16 | int 16 | uint 32 | int 32 | -|-------------------|:-:|:-:|:-:|:-:|:-:|:-:| -|load, store | x | x | x | x | x | x | -|interleave | x | x | x | x | x | x | -|expand | x | x | x | x | x | x | -|expand_low | x | x | x | x | x | x | -|expand_high | x | x | x | x | x | x | -|expand_q | x | x | | | | | -|add, sub | x | x | x | x | x | x | -|add_wrap, sub_wrap | x | x | x | x | | | -|mul_wrap | x | x | x | x | | | -|mul | x | x | x | x | x | x | -|mul_expand | x | x | x | x | x | | -|compare | x | x | x | x | x | x | -|shift | | | x | x | x | x | -|dotprod | | | | x | | x | -|dotprod_fast | | | | x | | x | -|dotprod_expand | x | x | x | x | | x | -|dotprod_expand_fast| x | x | x | x | | x | -|logical | x | x | x | x | x | x | -|min, max | x | x | x | x | x | x | -|absdiff | x | x | x | x | x | x | -|absdiffs | | x | | x | | | -|reduce | x | x | x | x | x | x | -|mask | x | x | x | x | x | x | -|pack | x | x | x | x | x | x | -|pack_u | x | | x | | | | -|pack_b | x | | | | | | -|unpack | x | x | x | x | x | x | -|extract | x | x | x | x | x | x | -|rotate (lanes) | x | x | x | x | x | x | -|cvt_flt32 | | | | | | x | -|cvt_flt64 | | | | | | x | -|transpose4x4 | | | | | x | x | -|reverse | x | x | x | x | x | x | -|extract_n | x | x | x | x | x | x | -|broadcast_element | | | | | x | x | - -Big integers: - -| Operations\\Types | uint 64 | int 64 | -|-------------------|:-:|:-:| -|load, store | x | x | -|add, sub | x | x | -|shift | x | x | -|logical | x | x | -|reverse | x | x | -|extract | x | x | -|rotate (lanes) | x | x | -|cvt_flt64 | | x | -|extract_n | x | x | - -Floating point: - -| Operations\\Types | float 32 | float 64 | -|-------------------|:-:|:-:| -|load, store | x | x | -|interleave | x | | -|add, sub | x | x | -|mul | x | x | -|div | x | x | -|compare | x | x | -|min, max | x | x | -|absdiff | x | x | -|reduce | x | | -|mask | x | x | -|unpack | x | x | -|cvt_flt32 | | x | -|cvt_flt64 | x | | -|sqrt, abs | x | x | -|float math | x | x | -|transpose4x4 | x | | -|extract | x | x | -|rotate (lanes) | x | x | -|reverse | x | x | -|extract_n | x | x | -|broadcast_element | x | | -|exp | x | x | -|log | x | x | -|sin, cos | x | x | - - @{ */ - -template struct v_reg -{ -//! @cond IGNORED - typedef _Tp lane_type; - enum { nlanes = n }; -// !@endcond - - /** @brief Constructor - - Initializes register with data from memory - @param ptr pointer to memory block with data for register */ - explicit v_reg(const _Tp* ptr) { for( int i = 0; i < n; i++ ) s[i] = ptr[i]; } - - /** @brief Constructor - - Initializes register with two 64-bit values */ - v_reg(_Tp s0, _Tp s1) { s[0] = s0; s[1] = s1; } - - /** @brief Constructor - - Initializes register with four 32-bit values */ - v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3) { s[0] = s0; s[1] = s1; s[2] = s2; s[3] = s3; } - - /** @brief Constructor - - Initializes register with eight 16-bit values */ - v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3, - _Tp s4, _Tp s5, _Tp s6, _Tp s7) - { - s[0] = s0; s[1] = s1; s[2] = s2; s[3] = s3; - s[4] = s4; s[5] = s5; s[6] = s6; s[7] = s7; - } - - /** @brief Constructor - - Initializes register with sixteen 8-bit values */ - v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3, - _Tp s4, _Tp s5, _Tp s6, _Tp s7, - _Tp s8, _Tp s9, _Tp s10, _Tp s11, - _Tp s12, _Tp s13, _Tp s14, _Tp s15) - { - s[0] = s0; s[1] = s1; s[2] = s2; s[3] = s3; - s[4] = s4; s[5] = s5; s[6] = s6; s[7] = s7; - s[8] = s8; s[9] = s9; s[10] = s10; s[11] = s11; - s[12] = s12; s[13] = s13; s[14] = s14; s[15] = s15; - } - - /** @brief Default constructor - - Does not initialize anything*/ - v_reg() {} - - /** @brief Copy constructor */ - v_reg(const v_reg<_Tp, n> & r) - { - for( int i = 0; i < n; i++ ) - s[i] = r.s[i]; - } - /** @brief Access first value - - Returns value of the first lane according to register type, for example: - @code{.cpp} - v_int32x4 r(1, 2, 3, 4); - int v = r.get0(); // returns 1 - v_uint64x2 r(1, 2); - uint64_t v = r.get0(); // returns 1 - @endcode - */ - _Tp get0() const { return s[0]; } - -//! @cond IGNORED - _Tp get(const int i) const { return s[i]; } - v_reg<_Tp, n> high() const - { - v_reg<_Tp, n> c; - int i; - for( i = 0; i < n/2; i++ ) - { - c.s[i] = s[i+(n/2)]; - c.s[i+(n/2)] = 0; - } - return c; - } - - static v_reg<_Tp, n> zero() - { - v_reg<_Tp, n> c; - for( int i = 0; i < n; i++ ) - c.s[i] = (_Tp)0; - return c; - } - - static v_reg<_Tp, n> all(_Tp s) - { - v_reg<_Tp, n> c; - for( int i = 0; i < n; i++ ) - c.s[i] = s; - return c; - } - - template v_reg<_Tp2, n2> reinterpret_as() const - { - size_t bytes = std::min(sizeof(_Tp2)*n2, sizeof(_Tp)*n); - v_reg<_Tp2, n2> c; - std::memcpy(&c.s[0], &s[0], bytes); - return c; - } - - v_reg& operator=(const v_reg<_Tp, n> & r) - { - for( int i = 0; i < n; i++ ) - s[i] = r.s[i]; - return *this; - } - - _Tp s[n]; -//! @endcond -}; - -/** @brief Sixteen 8-bit unsigned integer values */ -typedef v_reg v_uint8x16; -/** @brief Sixteen 8-bit signed integer values */ -typedef v_reg v_int8x16; -/** @brief Eight 16-bit unsigned integer values */ -typedef v_reg v_uint16x8; -/** @brief Eight 16-bit signed integer values */ -typedef v_reg v_int16x8; -/** @brief Four 32-bit unsigned integer values */ -typedef v_reg v_uint32x4; -/** @brief Four 32-bit signed integer values */ -typedef v_reg v_int32x4; -/** @brief Four 32-bit floating point values (single precision) */ -typedef v_reg v_float32x4; -/** @brief Two 64-bit floating point values (double precision) */ -typedef v_reg v_float64x2; -/** @brief Two 64-bit unsigned integer values */ -typedef v_reg v_uint64x2; -/** @brief Two 64-bit signed integer values */ -typedef v_reg v_int64x2; - -#if CV_SIMD256 -/** @brief Thirty two 8-bit unsigned integer values */ -typedef v_reg v_uint8x32; -/** @brief Thirty two 8-bit signed integer values */ -typedef v_reg v_int8x32; -/** @brief Sixteen 16-bit unsigned integer values */ -typedef v_reg v_uint16x16; -/** @brief Sixteen 16-bit signed integer values */ -typedef v_reg v_int16x16; -/** @brief Eight 32-bit unsigned integer values */ -typedef v_reg v_uint32x8; -/** @brief Eight 32-bit signed integer values */ -typedef v_reg v_int32x8; -/** @brief Eight 32-bit floating point values (single precision) */ -typedef v_reg v_float32x8; -/** @brief Four 64-bit floating point values (double precision) */ -typedef v_reg v_float64x4; -/** @brief Four 64-bit unsigned integer values */ -typedef v_reg v_uint64x4; -/** @brief Four 64-bit signed integer values */ -typedef v_reg v_int64x4; -#endif - -#if CV_SIMD512 -/** @brief Sixty four 8-bit unsigned integer values */ -typedef v_reg v_uint8x64; -/** @brief Sixty four 8-bit signed integer values */ -typedef v_reg v_int8x64; -/** @brief Thirty two 16-bit unsigned integer values */ -typedef v_reg v_uint16x32; -/** @brief Thirty two 16-bit signed integer values */ -typedef v_reg v_int16x32; -/** @brief Sixteen 32-bit unsigned integer values */ -typedef v_reg v_uint32x16; -/** @brief Sixteen 32-bit signed integer values */ -typedef v_reg v_int32x16; -/** @brief Sixteen 32-bit floating point values (single precision) */ -typedef v_reg v_float32x16; -/** @brief Eight 64-bit floating point values (double precision) */ -typedef v_reg v_float64x8; -/** @brief Eight 64-bit unsigned integer values */ -typedef v_reg v_uint64x8; -/** @brief Eight 64-bit signed integer values */ -typedef v_reg v_int64x8; -#endif - -enum { - simd128_width = 16, -#if CV_SIMD256 - simd256_width = 32, -#endif -#if CV_SIMD512 - simd512_width = 64, - simdmax_width = simd512_width -#elif CV_SIMD256 - simdmax_width = simd256_width -#else - simdmax_width = simd128_width -#endif -}; - -/** @brief Add values - -For all types. */ -template CV_INLINE v_reg<_Tp, n> v_add(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); - -/** @brief Subtract values - -For all types. */ -template CV_INLINE v_reg<_Tp, n> v_sub(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); - -/** @brief Multiply values - -For 16- and 32-bit integer types and floating types. */ -template CV_INLINE v_reg<_Tp, n> v_mul(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); - -/** @brief Divide values - -For floating types only. */ -template CV_INLINE v_reg<_Tp, n> v_div(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); - - -/** @brief Bitwise AND - -Only for integer types. */ -template CV_INLINE v_reg<_Tp, n> v_and(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); - -/** @brief Bitwise OR - -Only for integer types. */ -template CV_INLINE v_reg<_Tp, n> v_or(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); - -/** @brief Bitwise XOR - -Only for integer types.*/ -template CV_INLINE v_reg<_Tp, n> v_xor(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); - -/** @brief Bitwise NOT - -Only for integer types.*/ -template CV_INLINE v_reg<_Tp, n> v_not(const v_reg<_Tp, n>& a); - - -#ifndef CV_DOXYGEN - -#define CV__HAL_INTRIN_EXPAND_WITH_INTEGER_TYPES(macro_name, ...) \ -__CV_EXPAND(macro_name(uchar, __VA_ARGS__)) \ -__CV_EXPAND(macro_name(schar, __VA_ARGS__)) \ -__CV_EXPAND(macro_name(ushort, __VA_ARGS__)) \ -__CV_EXPAND(macro_name(short, __VA_ARGS__)) \ -__CV_EXPAND(macro_name(unsigned, __VA_ARGS__)) \ -__CV_EXPAND(macro_name(int, __VA_ARGS__)) \ -__CV_EXPAND(macro_name(uint64, __VA_ARGS__)) \ -__CV_EXPAND(macro_name(int64, __VA_ARGS__)) \ - -#define CV__HAL_INTRIN_EXPAND_WITH_FP_TYPES(macro_name, ...) \ -__CV_EXPAND(macro_name(float, __VA_ARGS__)) \ -__CV_EXPAND(macro_name(double, __VA_ARGS__)) \ - -#define CV__HAL_INTRIN_EXPAND_WITH_ALL_TYPES(macro_name, ...) \ -CV__HAL_INTRIN_EXPAND_WITH_INTEGER_TYPES(macro_name, __VA_ARGS__) \ -CV__HAL_INTRIN_EXPAND_WITH_FP_TYPES(macro_name, __VA_ARGS__) \ - -#define CV__HAL_INTRIN_IMPL_BIN_OP_(_Tp, bin_op, func) \ -template inline \ -v_reg<_Tp, n> func(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ -{ \ - v_reg<_Tp, n> c; \ - for( int i = 0; i < n; i++ ) \ - c.s[i] = saturate_cast<_Tp>(a.s[i] bin_op b.s[i]); \ - return c; \ -} - -#define CV__HAL_INTRIN_IMPL_BIN_OP(bin_op, func) CV__HAL_INTRIN_EXPAND_WITH_ALL_TYPES(CV__HAL_INTRIN_IMPL_BIN_OP_, bin_op, func) - -CV__HAL_INTRIN_IMPL_BIN_OP(+, v_add) -CV__HAL_INTRIN_IMPL_BIN_OP(-, v_sub) -CV__HAL_INTRIN_IMPL_BIN_OP(*, v_mul) -CV__HAL_INTRIN_EXPAND_WITH_FP_TYPES(CV__HAL_INTRIN_IMPL_BIN_OP_, /, v_div) - -#define CV__HAL_INTRIN_IMPL_BIT_OP_(_Tp, bit_op, func) \ -template CV_INLINE \ -v_reg<_Tp, n> func(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ -{ \ - v_reg<_Tp, n> c; \ - typedef typename V_TypeTraits<_Tp>::int_type itype; \ - for( int i = 0; i < n; i++ ) \ - c.s[i] = V_TypeTraits<_Tp>::reinterpret_from_int((itype)(V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) bit_op \ - V_TypeTraits<_Tp>::reinterpret_int(b.s[i]))); \ - return c; \ -} - -#define CV__HAL_INTRIN_IMPL_BIT_OP(bit_op, func) \ -CV__HAL_INTRIN_EXPAND_WITH_INTEGER_TYPES(CV__HAL_INTRIN_IMPL_BIT_OP_, bit_op, func) \ -CV__HAL_INTRIN_EXPAND_WITH_FP_TYPES(CV__HAL_INTRIN_IMPL_BIT_OP_, bit_op, func) /* TODO: FIXIT remove this after masks refactoring */ - - -CV__HAL_INTRIN_IMPL_BIT_OP(&, v_and) -CV__HAL_INTRIN_IMPL_BIT_OP(|, v_or) -CV__HAL_INTRIN_IMPL_BIT_OP(^, v_xor) - -#define CV__HAL_INTRIN_IMPL_BITWISE_NOT_(_Tp, dummy, dummy2) \ -template CV_INLINE \ -v_reg<_Tp, n> v_not(const v_reg<_Tp, n>& a) \ -{ \ - v_reg<_Tp, n> c; \ - for( int i = 0; i < n; i++ ) \ - c.s[i] = V_TypeTraits<_Tp>::reinterpret_from_int(~V_TypeTraits<_Tp>::reinterpret_int(a.s[i])); \ - return c; \ -} \ - -CV__HAL_INTRIN_EXPAND_WITH_INTEGER_TYPES(CV__HAL_INTRIN_IMPL_BITWISE_NOT_, ~, v_not) - -#endif // !CV_DOXYGEN - - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_MATH_FUNC(func, cfunc, _Tp2) \ -template inline v_reg<_Tp2, n> func(const v_reg<_Tp, n>& a) \ -{ \ - v_reg<_Tp2, n> c; \ - for( int i = 0; i < n; i++ ) \ - c.s[i] = cfunc(a.s[i]); \ - return c; \ -} - -/** @brief Square root of elements - -Only for floating point types.*/ -OPENCV_HAL_IMPL_MATH_FUNC(v_sqrt, std::sqrt, _Tp) - -/** - * @brief Exponential \f$ e^x \f$ of elements - * - * Only for floating point types. Core implementation steps: - * 1. Decompose Input: Convert the input to \f$ 2^{x \cdot \log_2e} \f$ and split its exponential into integer and fractional parts: - * \f$ x \cdot \log_2e = n + f \f$, where \f$ n \f$ is the integer part and \f$ f \f$ is the fractional part. - * 2. Compute \f$ 2^n \f$: Calculated by shifting the bits. - * 3. Adjust Fractional Part: Compute \f$ f \cdot \ln2 \f$ to convert the fractional part to base \f$ e \f$. - * \f$ C1 \f$ and \f$ C2 \f$ are used to adjust the fractional part. - * 4. Polynomial Approximation for \f$ e^{f \cdot \ln2} \f$: The closer the fractional part is to 0, the more accurate the result. - * - For float16 and float32, use a Taylor Series with 6 terms. - * - For float64, use Pade Polynomials Approximation with 4 terms. - * 5. Combine Results: Multiply the two parts together to get the final result: - * \f$ e^x = 2^n \cdot e^{f \cdot \ln2} \f$. - * - * @note The precision of the calculation depends on the implementation and the data type of the input vector. - */ -OPENCV_HAL_IMPL_MATH_FUNC(v_exp, std::exp, _Tp) -#define OPENCV_HAL_MATH_HAVE_EXP 1 - -/** - * @brief Natural logarithm \f$ \log(x) \f$ of elements - * - * Only for floating point types. Core implementation steps: - * 1. Decompose Input: Use binary representation to decompose the input into mantissa part \f$ m \f$ and exponent part \f$ e \f$. Such that \f$ \log(x) = \log(m \cdot 2^e) = \log(m) + e \cdot \ln(2) \f$. - * 2. Adjust Mantissa and Exponent Parts: If the mantissa is less than \f$ \sqrt{0.5} \f$, adjust the exponent and mantissa to ensure the mantissa is in the range \f$ (\sqrt{0.5}, \sqrt{2}) \f$ for better approximation. - * 3. Polynomial Approximation for \f$ \log(m) \f$: The closer the \f$ m \f$ is to 1, the more accurate the result. - * - For float16 and float32, use a Taylor Series with 9 terms. - * - For float64, use Pade Polynomials Approximation with 6 terms. - * 4. Combine Results: Add the two parts together to get the final result. - * - * @note The precision of the calculation depends on the implementation and the data type of the input. - * - * @note Similar to the behavior of std::log(), \f$ \ln(0) = -\infty \f$. - */ -OPENCV_HAL_IMPL_MATH_FUNC(v_log, std::log, _Tp) - -/** - * @brief Error function. - * - * @note Support FP32 precision for now. - */ -OPENCV_HAL_IMPL_MATH_FUNC(v_erf, std::erf, _Tp) - -/** - * @brief Compute sine \f$ sin(x) \f$ and cosine \f$ cos(x) \f$ of elements at the same time - * - * Only for floating point types. Core implementation steps: - * 1. Input Normalization: Scale the periodicity from 2π to 4 and reduce the angle to the range \f$ [0, \frac{\pi}{4}] \f$ using periodicity and trigonometric identities. - * 2. Polynomial Approximation for \f$ sin(x) \f$ and \f$ cos(x) \f$: - * - For float16 and float32, use a Taylor series with 4 terms for sine and 5 terms for cosine. - * - For float64, use a Taylor series with 7 terms for sine and 8 terms for cosine. - * 3. Select Results: select and convert the final sine and cosine values for the original input angle. - * - * @note The precision of the calculation depends on the implementation and the data type of the input vector. - */ -template -inline void v_sincos(const v_reg<_Tp, n>& x, v_reg<_Tp, n>& s, v_reg<_Tp, n>& c) -{ - for( int i = 0; i < n; i++ ) - { - s.s[i] = std::sin(x.s[i]); - c.s[i] = std::cos(x.s[i]); - } -} - -/** - * @brief Sine \f$ sin(x) \f$ of elements - * - * Only for floating point types. Core implementation the same as @ref v_sincos. - */ -OPENCV_HAL_IMPL_MATH_FUNC(v_sin, std::sin, _Tp) - -/** - * @brief Cosine \f$ cos(x) \f$ of elements - * - * Only for floating point types. Core implementation the same as @ref v_sincos. - */ -OPENCV_HAL_IMPL_MATH_FUNC(v_cos, std::cos, _Tp) - -/** @brief Absolute value of elements - -Only for floating point types.*/ -OPENCV_HAL_IMPL_MATH_FUNC(v_abs, (typename V_TypeTraits<_Tp>::abs_type)std::abs, - typename V_TypeTraits<_Tp>::abs_type) - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_MINMAX_FUNC(func, cfunc) \ -template inline v_reg<_Tp, n> func(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ -{ \ - v_reg<_Tp, n> c; \ - for( int i = 0; i < n; i++ ) \ - c.s[i] = cfunc(a.s[i], b.s[i]); \ - return c; \ -} - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_REDUCE_MINMAX_FUNC(func, cfunc) \ -template inline _Tp func(const v_reg<_Tp, n>& a) \ -{ \ - _Tp c = a.s[0]; \ - for( int i = 1; i < n; i++ ) \ - c = cfunc(c, a.s[i]); \ - return c; \ -} - -/** @brief Choose min values for each pair - -Scheme: -@code -{A1 A2 ...} -{B1 B2 ...} --------------- -{min(A1,B1) min(A2,B2) ...} -@endcode -For all types except 64-bit integer. */ -OPENCV_HAL_IMPL_MINMAX_FUNC(v_min, std::min) - -/** @brief Choose max values for each pair - -Scheme: -@code -{A1 A2 ...} -{B1 B2 ...} --------------- -{max(A1,B1) max(A2,B2) ...} -@endcode -For all types except 64-bit integer. */ -OPENCV_HAL_IMPL_MINMAX_FUNC(v_max, std::max) - -/** @brief Find one min value - -Scheme: -@code -{A1 A2 A3 ...} => min(A1,A2,A3,...) -@endcode -For all types except 64-bit integer and 64-bit floating point types. */ -OPENCV_HAL_IMPL_REDUCE_MINMAX_FUNC(v_reduce_min, std::min) - -/** @brief Find one max value - -Scheme: -@code -{A1 A2 A3 ...} => max(A1,A2,A3,...) -@endcode -For all types except 64-bit integer and 64-bit floating point types. */ -OPENCV_HAL_IMPL_REDUCE_MINMAX_FUNC(v_reduce_max, std::max) - -static const unsigned char popCountTable[] = -{ - 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, -}; -/** @brief Count the 1 bits in the vector lanes and return result as corresponding unsigned type - -Scheme: -@code -{A1 A2 A3 ...} => {popcount(A1), popcount(A2), popcount(A3), ...} -@endcode -For all integer types. */ -template -inline v_reg::abs_type, n> v_popcount(const v_reg<_Tp, n>& a) -{ - v_reg::abs_type, n> b = v_reg::abs_type, n>::zero(); - for (int i = 0; i < n*(int)sizeof(_Tp); i++) - b.s[i/sizeof(_Tp)] += popCountTable[v_reinterpret_as_u8(a).s[i]]; - return b; -} - - -//! @cond IGNORED -template -inline void v_minmax( const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, - v_reg<_Tp, n>& minval, v_reg<_Tp, n>& maxval ) -{ - for( int i = 0; i < n; i++ ) - { - minval.s[i] = std::min(a.s[i], b.s[i]); - maxval.s[i] = std::max(a.s[i], b.s[i]); - } -} -//! @endcond - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_CMP_OP(cmp_op, func) \ -template \ -inline v_reg<_Tp, n> func(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ -{ \ - typedef typename V_TypeTraits<_Tp>::int_type itype; \ - v_reg<_Tp, n> c; \ - for( int i = 0; i < n; i++ ) \ - c.s[i] = V_TypeTraits<_Tp>::reinterpret_from_int((itype)-(int)(a.s[i] cmp_op b.s[i])); \ - return c; \ -} - -/** @brief Less-than comparison - -For all types except 64-bit integer values. */ -OPENCV_HAL_IMPL_CMP_OP(<, v_lt) - -/** @brief Greater-than comparison - -For all types except 64-bit integer values. */ -OPENCV_HAL_IMPL_CMP_OP(>, v_gt) - -/** @brief Less-than or equal comparison - -For all types except 64-bit integer values. */ -OPENCV_HAL_IMPL_CMP_OP(<=, v_le) - -/** @brief Greater-than or equal comparison - -For all types except 64-bit integer values. */ -OPENCV_HAL_IMPL_CMP_OP(>=, v_ge) - -/** @brief Equal comparison */ -OPENCV_HAL_IMPL_CMP_OP(==, v_eq) - -/** @brief Not equal comparison */ -OPENCV_HAL_IMPL_CMP_OP(!=, v_ne) - -template -inline v_reg v_not_nan(const v_reg& a) -{ - typedef typename V_TypeTraits::int_type itype; - v_reg c; - for (int i = 0; i < n; i++) - c.s[i] = V_TypeTraits::reinterpret_from_int((itype)-(int)(a.s[i] == a.s[i])); - return c; -} -template -inline v_reg v_not_nan(const v_reg& a) -{ - typedef typename V_TypeTraits::int_type itype; - v_reg c; - for (int i = 0; i < n; i++) - c.s[i] = V_TypeTraits::reinterpret_from_int((itype)-(int)(a.s[i] == a.s[i])); - return c; -} - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_ARITHM_OP(func, bin_op, cast_op, _Tp2) \ -template \ -inline v_reg<_Tp2, n> func(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ -{ \ - typedef _Tp2 rtype; \ - v_reg c; \ - for( int i = 0; i < n; i++ ) \ - c.s[i] = cast_op(a.s[i] bin_op b.s[i]); \ - return c; \ -} - -/** @brief Add values without saturation - -For 8- and 16-bit integer values. */ -OPENCV_HAL_IMPL_ARITHM_OP(v_add_wrap, +, (_Tp), _Tp) - -/** @brief Subtract values without saturation - -For 8- and 16-bit integer values. */ -OPENCV_HAL_IMPL_ARITHM_OP(v_sub_wrap, -, (_Tp), _Tp) - -/** @brief Multiply values without saturation - -For 8- and 16-bit integer values. */ -OPENCV_HAL_IMPL_ARITHM_OP(v_mul_wrap, *, (_Tp), _Tp) - -//! @cond IGNORED -template inline T _absdiff(T a, T b) -{ - return a > b ? a - b : b - a; -} -//! @endcond - -/** @brief Absolute difference - -Returns \f$ |a - b| \f$ converted to corresponding unsigned type. -Example: -@code{.cpp} -v_int32x4 a, b; // {1, 2, 3, 4} and {4, 3, 2, 1} -v_uint32x4 c = v_absdiff(a, b); // result is {3, 1, 1, 3} -@endcode -For 8-, 16-, 32-bit integer source types. */ -template -inline v_reg::abs_type, n> v_absdiff(const v_reg<_Tp, n>& a, const v_reg<_Tp, n> & b) -{ - typedef typename V_TypeTraits<_Tp>::abs_type rtype; - v_reg c; - const rtype mask = (rtype)(std::numeric_limits<_Tp>::is_signed ? (1 << (sizeof(rtype)*8 - 1)) : 0); - for( int i = 0; i < n; i++ ) - { - rtype ua = a.s[i] ^ mask; - rtype ub = b.s[i] ^ mask; - c.s[i] = _absdiff(ua, ub); - } - return c; -} - -/** @overload - -For 32-bit floating point values */ -template inline v_reg v_absdiff(const v_reg& a, const v_reg& b) -{ - v_reg c; - for( int i = 0; i < c.nlanes; i++ ) - c.s[i] = _absdiff(a.s[i], b.s[i]); - return c; -} - -/** @overload - -For 64-bit floating point values */ -template inline v_reg v_absdiff(const v_reg& a, const v_reg& b) -{ - v_reg c; - for( int i = 0; i < c.nlanes; i++ ) - c.s[i] = _absdiff(a.s[i], b.s[i]); - return c; -} - -/** @brief Saturating absolute difference - -Returns \f$ saturate(|a - b|) \f$ . -For 8-, 16-bit signed integer source types. */ -template -inline v_reg<_Tp, n> v_absdiffs(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ - v_reg<_Tp, n> c; - for( int i = 0; i < n; i++) - c.s[i] = saturate_cast<_Tp>(std::abs(a.s[i] - b.s[i])); - return c; -} - -/** @brief Inversed square root - -Returns \f$ 1/sqrt(a) \f$ -For floating point types only. */ -template -inline v_reg<_Tp, n> v_invsqrt(const v_reg<_Tp, n>& a) -{ - v_reg<_Tp, n> c; - for( int i = 0; i < n; i++ ) - c.s[i] = 1.f/std::sqrt(a.s[i]); - return c; -} - -/** @brief Magnitude - -Returns \f$ sqrt(a^2 + b^2) \f$ -For floating point types only. */ -template -inline v_reg<_Tp, n> v_magnitude(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ - v_reg<_Tp, n> c; - for( int i = 0; i < n; i++ ) - c.s[i] = std::sqrt(a.s[i]*a.s[i] + b.s[i]*b.s[i]); - return c; -} - -/** @brief Square of the magnitude - -Returns \f$ a^2 + b^2 \f$ -For floating point types only. */ -template -inline v_reg<_Tp, n> v_sqr_magnitude(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ - v_reg<_Tp, n> c; - for( int i = 0; i < n; i++ ) - c.s[i] = a.s[i]*a.s[i] + b.s[i]*b.s[i]; - return c; -} - -/** @brief Multiply and add - - Returns \f$ a*b + c \f$ - For floating point types and signed 32bit int only. */ -template -inline v_reg<_Tp, n> v_fma(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, - const v_reg<_Tp, n>& c) -{ - v_reg<_Tp, n> d; - for( int i = 0; i < n; i++ ) - d.s[i] = a.s[i]*b.s[i] + c.s[i]; - return d; -} - -/** @brief A synonym for v_fma */ -template -inline v_reg<_Tp, n> v_muladd(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, - const v_reg<_Tp, n>& c) -{ - return v_fma(a, b, c); -} - -/** @brief Dot product of elements - -Multiply values in two registers and sum adjacent result pairs. - -Scheme: -@code - {A1 A2 ...} // 16-bit -x {B1 B2 ...} // 16-bit -------------- -{A1B1+A2B2 ...} // 32-bit - -@endcode -*/ -template inline v_reg::w_type, n/2> -v_dotprod(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ - typedef typename V_TypeTraits<_Tp>::w_type w_type; - v_reg c; - for( int i = 0; i < (n/2); i++ ) - c.s[i] = (w_type)a.s[i*2]*b.s[i*2] + (w_type)a.s[i*2+1]*b.s[i*2+1]; - return c; -} - -/** @brief Dot product of elements - -Same as cv::v_dotprod, but add a third element to the sum of adjacent pairs. -Scheme: -@code - {A1 A2 ...} // 16-bit -x {B1 B2 ...} // 16-bit -------------- - {A1B1+A2B2+C1 ...} // 32-bit -@endcode -*/ -template inline v_reg::w_type, n/2> -v_dotprod(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, - const v_reg::w_type, n / 2>& c) -{ - typedef typename V_TypeTraits<_Tp>::w_type w_type; - v_reg s; - for( int i = 0; i < (n/2); i++ ) - s.s[i] = (w_type)a.s[i*2]*b.s[i*2] + (w_type)a.s[i*2+1]*b.s[i*2+1] + c.s[i]; - return s; -} - -/** @brief Fast Dot product of elements - -Same as cv::v_dotprod, but it may perform unorder sum between result pairs in some platforms, -this intrinsic can be used if the sum among all lanes is only matters -and also it should be yielding better performance on the affected platforms. - -*/ -template inline v_reg::w_type, n/2> -v_dotprod_fast(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ return v_dotprod(a, b); } - -/** @brief Fast Dot product of elements - -Same as cv::v_dotprod_fast, but add a third element to the sum of adjacent pairs. -*/ -template inline v_reg::w_type, n/2> -v_dotprod_fast(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, - const v_reg::w_type, n / 2>& c) -{ return v_dotprod(a, b, c); } - -/** @brief Dot product of elements and expand - -Multiply values in two registers and expand the sum of adjacent result pairs. - -Scheme: -@code - {A1 A2 A3 A4 ...} // 8-bit -x {B1 B2 B3 B4 ...} // 8-bit -------------- - {A1B1+A2B2+A3B3+A4B4 ...} // 32-bit - -@endcode -*/ -template inline v_reg::q_type, n/4> -v_dotprod_expand(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ - typedef typename V_TypeTraits<_Tp>::q_type q_type; - v_reg s; - for( int i = 0; i < (n/4); i++ ) - s.s[i] = (q_type)a.s[i*4 ]*b.s[i*4 ] + (q_type)a.s[i*4 + 1]*b.s[i*4 + 1] + - (q_type)a.s[i*4 + 2]*b.s[i*4 + 2] + (q_type)a.s[i*4 + 3]*b.s[i*4 + 3]; - return s; -} - -/** @brief Dot product of elements - -Same as cv::v_dotprod_expand, but add a third element to the sum of adjacent pairs. -Scheme: -@code - {A1 A2 A3 A4 ...} // 8-bit -x {B1 B2 B3 B4 ...} // 8-bit -------------- - {A1B1+A2B2+A3B3+A4B4+C1 ...} // 32-bit -@endcode -*/ -template inline v_reg::q_type, n/4> -v_dotprod_expand(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, - const v_reg::q_type, n / 4>& c) -{ - typedef typename V_TypeTraits<_Tp>::q_type q_type; - v_reg s; - for( int i = 0; i < (n/4); i++ ) - s.s[i] = (q_type)a.s[i*4 ]*b.s[i*4 ] + (q_type)a.s[i*4 + 1]*b.s[i*4 + 1] + - (q_type)a.s[i*4 + 2]*b.s[i*4 + 2] + (q_type)a.s[i*4 + 3]*b.s[i*4 + 3] + c.s[i]; - return s; -} - -/** @brief Fast Dot product of elements and expand - -Multiply values in two registers and expand the sum of adjacent result pairs. - -Same as cv::v_dotprod_expand, but it may perform unorder sum between result pairs in some platforms, -this intrinsic can be used if the sum among all lanes is only matters -and also it should be yielding better performance on the affected platforms. - -*/ -template inline v_reg::q_type, n/4> -v_dotprod_expand_fast(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ return v_dotprod_expand(a, b); } - -/** @brief Fast Dot product of elements - -Same as cv::v_dotprod_expand_fast, but add a third element to the sum of adjacent pairs. -*/ -template inline v_reg::q_type, n/4> -v_dotprod_expand_fast(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, - const v_reg::q_type, n / 4>& c) -{ return v_dotprod_expand(a, b, c); } - -/** @brief Multiply and expand - -Multiply values two registers and store results in two registers with wider pack type. -Scheme: -@code - {A B C D} // 32-bit -x {E F G H} // 32-bit ---------------- -{AE BF} // 64-bit - {CG DH} // 64-bit -@endcode -Example: -@code{.cpp} -v_uint32x4 a, b; // {1,2,3,4} and {2,2,2,2} -v_uint64x2 c, d; // results -v_mul_expand(a, b, c, d); // c, d = {2,4}, {6, 8} -@endcode -Implemented only for 16- and unsigned 32-bit source types (v_int16x8, v_uint16x8, v_uint32x4). -*/ -template inline void v_mul_expand(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, - v_reg::w_type, n/2>& c, - v_reg::w_type, n/2>& d) -{ - typedef typename V_TypeTraits<_Tp>::w_type w_type; - for( int i = 0; i < (n/2); i++ ) - { - c.s[i] = (w_type)a.s[i]*b.s[i]; - d.s[i] = (w_type)a.s[i+(n/2)]*b.s[i+(n/2)]; - } -} - -/** @brief Multiply and extract high part - -Multiply values two registers and store high part of the results. -Implemented only for 16-bit source types (v_int16x8, v_uint16x8). Returns \f$ a*b >> 16 \f$ -*/ -template inline v_reg<_Tp, n> v_mul_hi(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ - typedef typename V_TypeTraits<_Tp>::w_type w_type; - v_reg<_Tp, n> c; - for (int i = 0; i < n; i++) - c.s[i] = (_Tp)(((w_type)a.s[i] * b.s[i]) >> sizeof(_Tp)*8); - return c; -} - -//! @cond IGNORED -template inline void v_hsum(const v_reg<_Tp, n>& a, - v_reg::w_type, n/2>& c) -{ - typedef typename V_TypeTraits<_Tp>::w_type w_type; - for( int i = 0; i < (n/2); i++ ) - { - c.s[i] = (w_type)a.s[i*2] + a.s[i*2+1]; - } -} -//! @endcond - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_SHIFT_OP(shift_op, func) \ -template inline v_reg<_Tp, n> func(const v_reg<_Tp, n>& a, int imm) \ -{ \ - v_reg<_Tp, n> c; \ - for( int i = 0; i < n; i++ ) \ - c.s[i] = (_Tp)(a.s[i] shift_op imm); \ - return c; \ -} - -/** @brief Bitwise shift left - -For 16-, 32- and 64-bit integer values. */ -OPENCV_HAL_IMPL_SHIFT_OP(<<, v_shl) - -/** @brief Bitwise shift right - -For 16-, 32- and 64-bit integer values. */ -OPENCV_HAL_IMPL_SHIFT_OP(>>, v_shr) - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_ROTATE_SHIFT_OP(suffix,opA,opB) \ -template inline v_reg<_Tp, n> v_rotate_##suffix(const v_reg<_Tp, n>& a) \ -{ \ - v_reg<_Tp, n> b; \ - for (int i = 0; i < n; i++) \ - { \ - int sIndex = i opA imm; \ - if (0 <= sIndex && sIndex < n) \ - { \ - b.s[i] = a.s[sIndex]; \ - } \ - else \ - { \ - b.s[i] = 0; \ - } \ - } \ - return b; \ -} \ -template inline v_reg<_Tp, n> v_rotate_##suffix(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ -{ \ - v_reg<_Tp, n> c; \ - for (int i = 0; i < n; i++) \ - { \ - int aIndex = i opA imm; \ - int bIndex = i opA imm opB n; \ - if (0 <= bIndex && bIndex < n) \ - { \ - c.s[i] = b.s[bIndex]; \ - } \ - else if (0 <= aIndex && aIndex < n) \ - { \ - c.s[i] = a.s[aIndex]; \ - } \ - else \ - { \ - c.s[i] = 0; \ - } \ - } \ - return c; \ -} - -/** @brief Element shift left among vector - -For all type */ -OPENCV_HAL_IMPL_ROTATE_SHIFT_OP(left, -, +) - -/** @brief Element shift right among vector - -For all type */ -OPENCV_HAL_IMPL_ROTATE_SHIFT_OP(right, +, -) - -/** @brief Sum packed values - -Scheme: -@code -{A1 A2 A3 ...} => sum{A1,A2,A3,...} -@endcode -*/ -template inline typename V_TypeTraits<_Tp>::sum_type v_reduce_sum(const v_reg<_Tp, n>& a) -{ - typename V_TypeTraits<_Tp>::sum_type c = a.s[0]; - for( int i = 1; i < n; i++ ) - c += a.s[i]; - return c; -} - -/** @brief Sums all elements of each input vector, returns the vector of sums - - Scheme: - @code - result[0] = a[0] + a[1] + a[2] + a[3] - result[1] = b[0] + b[1] + b[2] + b[3] - result[2] = c[0] + c[1] + c[2] + c[3] - result[3] = d[0] + d[1] + d[2] + d[3] - @endcode -*/ -template inline v_reg v_reduce_sum4(const v_reg& a, const v_reg& b, - const v_reg& c, const v_reg& d) -{ - v_reg r; - for(int i = 0; i < (n/4); i++) - { - r.s[i*4 + 0] = a.s[i*4 + 0] + a.s[i*4 + 1] + a.s[i*4 + 2] + a.s[i*4 + 3]; - r.s[i*4 + 1] = b.s[i*4 + 0] + b.s[i*4 + 1] + b.s[i*4 + 2] + b.s[i*4 + 3]; - r.s[i*4 + 2] = c.s[i*4 + 0] + c.s[i*4 + 1] + c.s[i*4 + 2] + c.s[i*4 + 3]; - r.s[i*4 + 3] = d.s[i*4 + 0] + d.s[i*4 + 1] + d.s[i*4 + 2] + d.s[i*4 + 3]; - } - return r; -} - -/** @brief Sum absolute differences of values - -Scheme: -@code -{A1 A2 A3 ...} {B1 B2 B3 ...} => sum{ABS(A1-B1),abs(A2-B2),abs(A3-B3),...} -@endcode -For all types except 64-bit types.*/ -template inline typename V_TypeTraits< typename V_TypeTraits<_Tp>::abs_type >::sum_type v_reduce_sad(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ - typename V_TypeTraits< typename V_TypeTraits<_Tp>::abs_type >::sum_type c = _absdiff(a.s[0], b.s[0]); - for (int i = 1; i < n; i++) - c += _absdiff(a.s[i], b.s[i]); - return c; -} - -/** @brief Get negative values mask -@deprecated v_signmask depends on a lane count heavily and therefore isn't universal enough - -Returned value is a bit mask with bits set to 1 on places corresponding to negative packed values indexes. -Example: -@code{.cpp} -v_int32x4 r; // set to {-1, -1, 1, 1} -int mask = v_signmask(r); // mask = 3 <== 00000000 00000000 00000000 00000011 -@endcode -*/ -template inline int v_signmask(const v_reg<_Tp, n>& a) -{ - int mask = 0; - for( int i = 0; i < n; i++ ) - mask |= (V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) < 0) << i; - return mask; -} - -/** @brief Get first negative lane index - -Returned value is an index of first negative lane (undefined for input of all positive values) -Example: -@code{.cpp} -v_int32x4 r; // set to {0, 0, -1, -1} -int idx = v_heading_zeros(r); // idx = 2 -@endcode -*/ -template inline int v_scan_forward(const v_reg<_Tp, n>& a) -{ - for (int i = 0; i < n; i++) - if(V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) < 0) - return i; - return 0; -} - -/** @brief Check if all packed values are less than zero - -Unsigned values will be casted to signed: `uchar 254 => char -2`. -*/ -template inline bool v_check_all(const v_reg<_Tp, n>& a) -{ - for( int i = 0; i < n; i++ ) - if( V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) >= 0 ) - return false; - return true; -} - -/** @brief Check if any of packed values is less than zero - -Unsigned values will be casted to signed: `uchar 254 => char -2`. -*/ -template inline bool v_check_any(const v_reg<_Tp, n>& a) -{ - for( int i = 0; i < n; i++ ) - if( V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) < 0 ) - return true; - return false; -} - -/** @brief Per-element select (blend operation) - -Return value will be built by combining values _a_ and _b_ using the following scheme: - result[i] = mask[i] ? a[i] : b[i]; - -@note: _mask_ element values are restricted to these values: -- 0: select element from _b_ -- 0xff/0xffff/etc: select element from _a_ -(fully compatible with bitwise-based operator) -*/ -template inline v_reg<_Tp, n> v_select(const v_reg<_Tp, n>& mask, - const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ - typedef V_TypeTraits<_Tp> Traits; - typedef typename Traits::int_type int_type; - v_reg<_Tp, n> c; - for( int i = 0; i < n; i++ ) - { - int_type m = Traits::reinterpret_int(mask.s[i]); - CV_DbgAssert(m == 0 || m == (~(int_type)0)); // restrict mask values: 0 or 0xff/0xffff/etc - c.s[i] = m ? a.s[i] : b.s[i]; - } - return c; -} - -/** @brief Expand values to the wider pack type - -Copy contents of register to two registers with 2x wider pack type. -Scheme: -@code - int32x4 int64x2 int64x2 -{A B C D} ==> {A B} , {C D} -@endcode */ -template inline void v_expand(const v_reg<_Tp, n>& a, - v_reg::w_type, n/2>& b0, - v_reg::w_type, n/2>& b1) -{ - for( int i = 0; i < (n/2); i++ ) - { - b0.s[i] = a.s[i]; - b1.s[i] = a.s[i+(n/2)]; - } -} - -/** @brief Expand lower values to the wider pack type - -Same as cv::v_expand, but return lower half of the vector. - -Scheme: -@code - int32x4 int64x2 -{A B C D} ==> {A B} -@endcode */ -template -inline v_reg::w_type, n/2> -v_expand_low(const v_reg<_Tp, n>& a) -{ - v_reg::w_type, n/2> b; - for( int i = 0; i < (n/2); i++ ) - b.s[i] = a.s[i]; - return b; -} - -/** @brief Expand higher values to the wider pack type - -Same as cv::v_expand_low, but expand higher half of the vector instead. - -Scheme: -@code - int32x4 int64x2 -{A B C D} ==> {C D} -@endcode */ -template -inline v_reg::w_type, n/2> -v_expand_high(const v_reg<_Tp, n>& a) -{ - v_reg::w_type, n/2> b; - for( int i = 0; i < (n/2); i++ ) - b.s[i] = a.s[i+(n/2)]; - return b; -} - -//! @cond IGNORED -template inline v_reg::int_type, n> - v_reinterpret_as_int(const v_reg<_Tp, n>& a) -{ - v_reg::int_type, n> c; - for( int i = 0; i < n; i++ ) - c.s[i] = V_TypeTraits<_Tp>::reinterpret_int(a.s[i]); - return c; -} - -template inline v_reg::uint_type, n> - v_reinterpret_as_uint(const v_reg<_Tp, n>& a) -{ - v_reg::uint_type, n> c; - for( int i = 0; i < n; i++ ) - c.s[i] = V_TypeTraits<_Tp>::reinterpret_uint(a.s[i]); - return c; -} -//! @endcond - -/** @brief Interleave two vectors - -Scheme: -@code - {A1 A2 A3 A4} - {B1 B2 B3 B4} ---------------- - {A1 B1 A2 B2} and {A3 B3 A4 B4} -@endcode -For all types except 64-bit. -*/ -template inline void v_zip( const v_reg<_Tp, n>& a0, const v_reg<_Tp, n>& a1, - v_reg<_Tp, n>& b0, v_reg<_Tp, n>& b1 ) -{ - int i; - for( i = 0; i < n/2; i++ ) - { - b0.s[i*2] = a0.s[i]; - b0.s[i*2+1] = a1.s[i]; - } - for( ; i < n; i++ ) - { - b1.s[i*2-n] = a0.s[i]; - b1.s[i*2-n+1] = a1.s[i]; - } -} - -/** @brief Load register contents from memory - -@param ptr pointer to memory block with data -@return register object - -@note Returned type will be detected from passed pointer type, for example uchar ==> cv::v_uint8x16, int ==> cv::v_int32x4, etc. - -@note Use vx_load version to get maximum available register length result - -@note Alignment requirement: -if CV_STRONG_ALIGNMENT=1 then passed pointer must be aligned (`sizeof(lane type)` should be enough). -Do not cast pointer types without runtime check for pointer alignment (like `uchar*` => `int*`). - */ -template -inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_load(const _Tp* ptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - return v_reg<_Tp, simd128_width / sizeof(_Tp)>(ptr); -} - -#if CV_SIMD256 -/** @brief Load 256-bit length register contents from memory - -@param ptr pointer to memory block with data -@return register object - -@note Returned type will be detected from passed pointer type, for example uchar ==> cv::v_uint8x32, int ==> cv::v_int32x8, etc. - -@note Check CV_SIMD256 preprocessor definition prior to use. -Use vx_load version to get maximum available register length result - -@note Alignment requirement: -if CV_STRONG_ALIGNMENT=1 then passed pointer must be aligned (`sizeof(lane type)` should be enough). -Do not cast pointer types without runtime check for pointer alignment (like `uchar*` => `int*`). - */ -template -inline v_reg<_Tp, simd256_width / sizeof(_Tp)> v256_load(const _Tp* ptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - return v_reg<_Tp, simd256_width / sizeof(_Tp)>(ptr); -} -#endif - -#if CV_SIMD512 -/** @brief Load 512-bit length register contents from memory - -@param ptr pointer to memory block with data -@return register object - -@note Returned type will be detected from passed pointer type, for example uchar ==> cv::v_uint8x64, int ==> cv::v_int32x16, etc. - -@note Check CV_SIMD512 preprocessor definition prior to use. -Use vx_load version to get maximum available register length result - -@note Alignment requirement: -if CV_STRONG_ALIGNMENT=1 then passed pointer must be aligned (`sizeof(lane type)` should be enough). -Do not cast pointer types without runtime check for pointer alignment (like `uchar*` => `int*`). - */ -template -inline v_reg<_Tp, simd512_width / sizeof(_Tp)> v512_load(const _Tp* ptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - return v_reg<_Tp, simd512_width / sizeof(_Tp)>(ptr); -} -#endif - -/** @brief Load register contents from memory (aligned) - -similar to cv::v_load, but source memory block should be aligned (to 16-byte boundary in case of SIMD128, 32-byte - SIMD256, etc) - -@note Use vx_load_aligned version to get maximum available register length result -*/ -template -inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_load_aligned(const _Tp* ptr) -{ - CV_Assert(isAligned)>(ptr)); - return v_reg<_Tp, simd128_width / sizeof(_Tp)>(ptr); -} - -#if CV_SIMD256 -/** @brief Load register contents from memory (aligned) - -similar to cv::v256_load, but source memory block should be aligned (to 32-byte boundary in case of SIMD256, 64-byte - SIMD512, etc) - -@note Check CV_SIMD256 preprocessor definition prior to use. -Use vx_load_aligned version to get maximum available register length result -*/ -template -inline v_reg<_Tp, simd256_width / sizeof(_Tp)> v256_load_aligned(const _Tp* ptr) -{ - CV_Assert(isAligned)>(ptr)); - return v_reg<_Tp, simd256_width / sizeof(_Tp)>(ptr); -} -#endif - -#if CV_SIMD512 -/** @brief Load register contents from memory (aligned) - -similar to cv::v512_load, but source memory block should be aligned (to 64-byte boundary in case of SIMD512, etc) - -@note Check CV_SIMD512 preprocessor definition prior to use. -Use vx_load_aligned version to get maximum available register length result -*/ -template -inline v_reg<_Tp, simd512_width / sizeof(_Tp)> v512_load_aligned(const _Tp* ptr) -{ - CV_Assert(isAligned)>(ptr)); - return v_reg<_Tp, simd512_width / sizeof(_Tp)>(ptr); -} -#endif - -/** @brief Load 64-bits of data to lower part (high part is undefined). - -@param ptr memory block containing data for first half (0..n/2) - -@code{.cpp} -int lo[2] = { 1, 2 }; -v_int32x4 r = v_load_low(lo); -@endcode - -@note Use vx_load_low version to get maximum available register length result -*/ -template -inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_load_low(const _Tp* ptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - v_reg<_Tp, simd128_width / sizeof(_Tp)> c; - for( int i = 0; i < c.nlanes/2; i++ ) - { - c.s[i] = ptr[i]; - } - return c; -} - -#if CV_SIMD256 -/** @brief Load 128-bits of data to lower part (high part is undefined). - -@param ptr memory block containing data for first half (0..n/2) - -@code{.cpp} -int lo[4] = { 1, 2, 3, 4 }; -v_int32x8 r = v256_load_low(lo); -@endcode - -@note Check CV_SIMD256 preprocessor definition prior to use. -Use vx_load_low version to get maximum available register length result -*/ -template -inline v_reg<_Tp, simd256_width / sizeof(_Tp)> v256_load_low(const _Tp* ptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - v_reg<_Tp, simd256_width / sizeof(_Tp)> c; - for (int i = 0; i < c.nlanes / 2; i++) - { - c.s[i] = ptr[i]; - } - return c; -} -#endif - -#if CV_SIMD512 -/** @brief Load 256-bits of data to lower part (high part is undefined). - -@param ptr memory block containing data for first half (0..n/2) - -@code{.cpp} -int lo[8] = { 1, 2, 3, 4, 5, 6, 7, 8 }; -v_int32x16 r = v512_load_low(lo); -@endcode - -@note Check CV_SIMD512 preprocessor definition prior to use. -Use vx_load_low version to get maximum available register length result -*/ -template -inline v_reg<_Tp, simd512_width / sizeof(_Tp)> v512_load_low(const _Tp* ptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - v_reg<_Tp, simd512_width / sizeof(_Tp)> c; - for (int i = 0; i < c.nlanes / 2; i++) - { - c.s[i] = ptr[i]; - } - return c; -} -#endif - -/** @brief Load register contents from two memory blocks - -@param loptr memory block containing data for first half (0..n/2) -@param hiptr memory block containing data for second half (n/2..n) - -@code{.cpp} -int lo[2] = { 1, 2 }, hi[2] = { 3, 4 }; -v_int32x4 r = v_load_halves(lo, hi); -@endcode - -@note Use vx_load_halves version to get maximum available register length result -*/ -template -inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_load_halves(const _Tp* loptr, const _Tp* hiptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(loptr)); - CV_Assert(isAligned(hiptr)); -#endif - v_reg<_Tp, simd128_width / sizeof(_Tp)> c; - for( int i = 0; i < c.nlanes/2; i++ ) - { - c.s[i] = loptr[i]; - c.s[i+c.nlanes/2] = hiptr[i]; - } - return c; -} - -#if CV_SIMD256 -/** @brief Load register contents from two memory blocks - -@param loptr memory block containing data for first half (0..n/2) -@param hiptr memory block containing data for second half (n/2..n) - -@code{.cpp} -int lo[4] = { 1, 2, 3, 4 }, hi[4] = { 5, 6, 7, 8 }; -v_int32x8 r = v256_load_halves(lo, hi); -@endcode - -@note Check CV_SIMD256 preprocessor definition prior to use. -Use vx_load_halves version to get maximum available register length result -*/ -template -inline v_reg<_Tp, simd256_width / sizeof(_Tp)> v256_load_halves(const _Tp* loptr, const _Tp* hiptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(loptr)); - CV_Assert(isAligned(hiptr)); -#endif - v_reg<_Tp, simd256_width / sizeof(_Tp)> c; - for (int i = 0; i < c.nlanes / 2; i++) - { - c.s[i] = loptr[i]; - c.s[i + c.nlanes / 2] = hiptr[i]; - } - return c; -} -#endif - -#if CV_SIMD512 -/** @brief Load register contents from two memory blocks - -@param loptr memory block containing data for first half (0..n/2) -@param hiptr memory block containing data for second half (n/2..n) - -@code{.cpp} -int lo[4] = { 1, 2, 3, 4, 5, 6, 7, 8 }, hi[4] = { 9, 10, 11, 12, 13, 14, 15, 16 }; -v_int32x16 r = v512_load_halves(lo, hi); -@endcode - -@note Check CV_SIMD512 preprocessor definition prior to use. -Use vx_load_halves version to get maximum available register length result -*/ -template -inline v_reg<_Tp, simd512_width / sizeof(_Tp)> v512_load_halves(const _Tp* loptr, const _Tp* hiptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(loptr)); - CV_Assert(isAligned(hiptr)); -#endif - v_reg<_Tp, simd512_width / sizeof(_Tp)> c; - for (int i = 0; i < c.nlanes / 2; i++) - { - c.s[i] = loptr[i]; - c.s[i + c.nlanes / 2] = hiptr[i]; - } - return c; -} -#endif - -/** @brief Load register contents from memory with double expand - -Same as cv::v_load, but result pack type will be 2x wider than memory type. - -@code{.cpp} -short buf[4] = {1, 2, 3, 4}; // type is int16 -v_int32x4 r = v_load_expand(buf); // r = {1, 2, 3, 4} - type is int32 -@endcode -For 8-, 16-, 32-bit integer source types. - -@note Use vx_load_expand version to get maximum available register length result -*/ -template -inline v_reg::w_type, simd128_width / sizeof(typename V_TypeTraits<_Tp>::w_type)> -v_load_expand(const _Tp* ptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - typedef typename V_TypeTraits<_Tp>::w_type w_type; - v_reg c; - for( int i = 0; i < c.nlanes; i++ ) - { - c.s[i] = ptr[i]; - } - return c; -} - -#if CV_SIMD256 -/** @brief Load register contents from memory with double expand - -Same as cv::v256_load, but result pack type will be 2x wider than memory type. - -@code{.cpp} -short buf[8] = {1, 2, 3, 4, 5, 6, 7, 8}; // type is int16 -v_int32x8 r = v256_load_expand(buf); // r = {1, 2, 3, 4, 5, 6, 7, 8} - type is int32 -@endcode -For 8-, 16-, 32-bit integer source types. - -@note Check CV_SIMD256 preprocessor definition prior to use. -Use vx_load_expand version to get maximum available register length result -*/ -template -inline v_reg::w_type, simd256_width / sizeof(typename V_TypeTraits<_Tp>::w_type)> -v256_load_expand(const _Tp* ptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - typedef typename V_TypeTraits<_Tp>::w_type w_type; - v_reg c; - for (int i = 0; i < c.nlanes; i++) - { - c.s[i] = ptr[i]; - } - return c; -} -#endif - -#if CV_SIMD512 -/** @brief Load register contents from memory with double expand - -Same as cv::v512_load, but result pack type will be 2x wider than memory type. - -@code{.cpp} -short buf[8] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; // type is int16 -v_int32x16 r = v512_load_expand(buf); // r = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16} - type is int32 -@endcode -For 8-, 16-, 32-bit integer source types. - -@note Check CV_SIMD512 preprocessor definition prior to use. -Use vx_load_expand version to get maximum available register length result -*/ -template -inline v_reg::w_type, simd512_width / sizeof(typename V_TypeTraits<_Tp>::w_type)> -v512_load_expand(const _Tp* ptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - typedef typename V_TypeTraits<_Tp>::w_type w_type; - v_reg c; - for (int i = 0; i < c.nlanes; i++) - { - c.s[i] = ptr[i]; - } - return c; -} -#endif - -/** @brief Load register contents from memory with quad expand - -Same as cv::v_load_expand, but result type is 4 times wider than source. -@code{.cpp} -char buf[4] = {1, 2, 3, 4}; // type is int8 -v_int32x4 r = v_load_expand_q(buf); // r = {1, 2, 3, 4} - type is int32 -@endcode -For 8-bit integer source types. - -@note Use vx_load_expand_q version to get maximum available register length result -*/ -template -inline v_reg::q_type, simd128_width / sizeof(typename V_TypeTraits<_Tp>::q_type)> -v_load_expand_q(const _Tp* ptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - typedef typename V_TypeTraits<_Tp>::q_type q_type; - v_reg c; - for( int i = 0; i < c.nlanes; i++ ) - { - c.s[i] = ptr[i]; - } - return c; -} - -#if CV_SIMD256 -/** @brief Load register contents from memory with quad expand - -Same as cv::v256_load_expand, but result type is 4 times wider than source. -@code{.cpp} -char buf[8] = {1, 2, 3, 4, 5, 6, 7, 8}; // type is int8 -v_int32x8 r = v256_load_expand_q(buf); // r = {1, 2, 3, 4, 5, 6, 7, 8} - type is int32 -@endcode -For 8-bit integer source types. - -@note Check CV_SIMD256 preprocessor definition prior to use. -Use vx_load_expand_q version to get maximum available register length result -*/ -template -inline v_reg::q_type, simd256_width / sizeof(typename V_TypeTraits<_Tp>::q_type)> -v256_load_expand_q(const _Tp* ptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - typedef typename V_TypeTraits<_Tp>::q_type q_type; - v_reg c; - for (int i = 0; i < c.nlanes; i++) - { - c.s[i] = ptr[i]; - } - return c; -} -#endif - -#if CV_SIMD512 -/** @brief Load register contents from memory with quad expand - -Same as cv::v512_load_expand, but result type is 4 times wider than source. -@code{.cpp} -char buf[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; // type is int8 -v_int32x16 r = v512_load_expand_q(buf); // r = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16} - type is int32 -@endcode -For 8-bit integer source types. - -@note Check CV_SIMD512 preprocessor definition prior to use. -Use vx_load_expand_q version to get maximum available register length result -*/ -template -inline v_reg::q_type, simd512_width / sizeof(typename V_TypeTraits<_Tp>::q_type)> -v512_load_expand_q(const _Tp* ptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - typedef typename V_TypeTraits<_Tp>::q_type q_type; - v_reg c; - for (int i = 0; i < c.nlanes; i++) - { - c.s[i] = ptr[i]; - } - return c; -} -#endif - -/** @brief Load and deinterleave (2 channels) - -Load data from memory deinterleave and store to 2 registers. -Scheme: -@code -{A1 B1 A2 B2 ...} ==> {A1 A2 ...}, {B1 B2 ...} -@endcode -For all types except 64-bit. */ -template inline void v_load_deinterleave(const _Tp* ptr, v_reg<_Tp, n>& a, - v_reg<_Tp, n>& b) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - int i, i2; - for( i = i2 = 0; i < n; i++, i2 += 2 ) - { - a.s[i] = ptr[i2]; - b.s[i] = ptr[i2+1]; - } -} - -/** @brief Load and deinterleave (3 channels) - -Load data from memory deinterleave and store to 3 registers. -Scheme: -@code -{A1 B1 C1 A2 B2 C2 ...} ==> {A1 A2 ...}, {B1 B2 ...}, {C1 C2 ...} -@endcode -For all types except 64-bit. */ -template inline void v_load_deinterleave(const _Tp* ptr, v_reg<_Tp, n>& a, - v_reg<_Tp, n>& b, v_reg<_Tp, n>& c) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - int i, i3; - for( i = i3 = 0; i < n; i++, i3 += 3 ) - { - a.s[i] = ptr[i3]; - b.s[i] = ptr[i3+1]; - c.s[i] = ptr[i3+2]; - } -} - -/** @brief Load and deinterleave (4 channels) - -Load data from memory deinterleave and store to 4 registers. -Scheme: -@code -{A1 B1 C1 D1 A2 B2 C2 D2 ...} ==> {A1 A2 ...}, {B1 B2 ...}, {C1 C2 ...}, {D1 D2 ...} -@endcode -For all types except 64-bit. */ -template -inline void v_load_deinterleave(const _Tp* ptr, v_reg<_Tp, n>& a, - v_reg<_Tp, n>& b, v_reg<_Tp, n>& c, - v_reg<_Tp, n>& d) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - int i, i4; - for( i = i4 = 0; i < n; i++, i4 += 4 ) - { - a.s[i] = ptr[i4]; - b.s[i] = ptr[i4+1]; - c.s[i] = ptr[i4+2]; - d.s[i] = ptr[i4+3]; - } -} - -/** @brief Interleave and store (2 channels) - -Interleave and store data from 2 registers to memory. -Scheme: -@code -{A1 A2 ...}, {B1 B2 ...} ==> {A1 B1 A2 B2 ...} -@endcode -For all types except 64-bit. */ -template -inline void v_store_interleave( _Tp* ptr, const v_reg<_Tp, n>& a, - const v_reg<_Tp, n>& b, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - int i, i2; - for( i = i2 = 0; i < n; i++, i2 += 2 ) - { - ptr[i2] = a.s[i]; - ptr[i2+1] = b.s[i]; - } -} - -/** @brief Interleave and store (3 channels) - -Interleave and store data from 3 registers to memory. -Scheme: -@code -{A1 A2 ...}, {B1 B2 ...}, {C1 C2 ...} ==> {A1 B1 C1 A2 B2 C2 ...} -@endcode -For all types except 64-bit. */ -template -inline void v_store_interleave( _Tp* ptr, const v_reg<_Tp, n>& a, - const v_reg<_Tp, n>& b, const v_reg<_Tp, n>& c, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - int i, i3; - for( i = i3 = 0; i < n; i++, i3 += 3 ) - { - ptr[i3] = a.s[i]; - ptr[i3+1] = b.s[i]; - ptr[i3+2] = c.s[i]; - } -} - -/** @brief Interleave and store (4 channels) - -Interleave and store data from 4 registers to memory. -Scheme: -@code -{A1 A2 ...}, {B1 B2 ...}, {C1 C2 ...}, {D1 D2 ...} ==> {A1 B1 C1 D1 A2 B2 C2 D2 ...} -@endcode -For all types except 64-bit. */ -template inline void v_store_interleave( _Tp* ptr, const v_reg<_Tp, n>& a, - const v_reg<_Tp, n>& b, const v_reg<_Tp, n>& c, - const v_reg<_Tp, n>& d, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - int i, i4; - for( i = i4 = 0; i < n; i++, i4 += 4 ) - { - ptr[i4] = a.s[i]; - ptr[i4+1] = b.s[i]; - ptr[i4+2] = c.s[i]; - ptr[i4+3] = d.s[i]; - } -} - -/** @brief Store data to memory - -Store register contents to memory. -Scheme: -@code - REG {A B C D} ==> MEM {A B C D} -@endcode -Pointer can be unaligned. */ -template -inline void v_store(_Tp* ptr, const v_reg<_Tp, n>& a) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - for( int i = 0; i < n; i++ ) - ptr[i] = a.s[i]; -} - -template -inline void v_store(_Tp* ptr, const v_reg<_Tp, n>& a, hal::StoreMode /*mode*/) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - v_store(ptr, a); -} - -/** @brief Store data to memory (lower half) - -Store lower half of register contents to memory. -Scheme: -@code - REG {A B C D} ==> MEM {A B} -@endcode */ -template -inline void v_store_low(_Tp* ptr, const v_reg<_Tp, n>& a) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - for( int i = 0; i < (n/2); i++ ) - ptr[i] = a.s[i]; -} - -/** @brief Store data to memory (higher half) - -Store higher half of register contents to memory. -Scheme: -@code - REG {A B C D} ==> MEM {C D} -@endcode */ -template -inline void v_store_high(_Tp* ptr, const v_reg<_Tp, n>& a) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - for( int i = 0; i < (n/2); i++ ) - ptr[i] = a.s[i+(n/2)]; -} - -/** @brief Store data to memory (aligned) - -Store register contents to memory. -Scheme: -@code - REG {A B C D} ==> MEM {A B C D} -@endcode -Pointer __should__ be aligned by 16-byte boundary. */ -template -inline void v_store_aligned(_Tp* ptr, const v_reg<_Tp, n>& a) -{ - CV_Assert(isAligned)>(ptr)); - v_store(ptr, a); -} - -template -inline void v_store_aligned_nocache(_Tp* ptr, const v_reg<_Tp, n>& a) -{ - CV_Assert(isAligned)>(ptr)); - v_store(ptr, a); -} - -template -inline void v_store_aligned(_Tp* ptr, const v_reg<_Tp, n>& a, hal::StoreMode /*mode*/) -{ - CV_Assert(isAligned)>(ptr)); - v_store(ptr, a); -} - -/** @brief Combine vector from first elements of two vectors - -Scheme: -@code - {A1 A2 A3 A4} - {B1 B2 B3 B4} ---------------- - {A1 A2 B1 B2} -@endcode -For all types except 64-bit. */ -template -inline v_reg<_Tp, n> v_combine_low(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ - v_reg<_Tp, n> c; - for( int i = 0; i < (n/2); i++ ) - { - c.s[i] = a.s[i]; - c.s[i+(n/2)] = b.s[i]; - } - return c; -} - -/** @brief Combine vector from last elements of two vectors - -Scheme: -@code - {A1 A2 A3 A4} - {B1 B2 B3 B4} ---------------- - {A3 A4 B3 B4} -@endcode -For all types except 64-bit. */ -template -inline v_reg<_Tp, n> v_combine_high(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ - v_reg<_Tp, n> c; - for( int i = 0; i < (n/2); i++ ) - { - c.s[i] = a.s[i+(n/2)]; - c.s[i+(n/2)] = b.s[i+(n/2)]; - } - return c; -} - -/** @brief Combine two vectors from lower and higher parts of two other vectors - -@code{.cpp} -low = cv::v_combine_low(a, b); -high = cv::v_combine_high(a, b); -@endcode */ -template -inline void v_recombine(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, - v_reg<_Tp, n>& low, v_reg<_Tp, n>& high) -{ - for( int i = 0; i < (n/2); i++ ) - { - low.s[i] = a.s[i]; - low.s[i+(n/2)] = b.s[i]; - high.s[i] = a.s[i+(n/2)]; - high.s[i+(n/2)] = b.s[i+(n/2)]; - } -} - -/** @brief Vector reverse order - -Reverse the order of the vector -Scheme: -@code - REG {A1 ... An} ==> REG {An ... A1} -@endcode -For all types. */ -template -inline v_reg<_Tp, n> v_reverse(const v_reg<_Tp, n>& a) -{ - v_reg<_Tp, n> c; - for( int i = 0; i < n; i++ ) - c.s[i] = a.s[n-i-1]; - return c; -} - -/** @brief Vector extract - -Scheme: -@code - {A1 A2 A3 A4} - {B1 B2 B3 B4} -======================== -shift = 1 {A2 A3 A4 B1} -shift = 2 {A3 A4 B1 B2} -shift = 3 {A4 B1 B2 B3} -@endcode -Restriction: 0 <= shift < nlanes - -Usage: -@code -v_int32x4 a, b, c; -c = v_extract<2>(a, b); -@endcode -For all types. */ -template -inline v_reg<_Tp, n> v_extract(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ - v_reg<_Tp, n> r; - const int shift = n - s; - int i = 0; - for (; i < shift; ++i) - r.s[i] = a.s[i+s]; - for (; i < n; ++i) - r.s[i] = b.s[i-shift]; - return r; -} - -/** @brief Vector extract - -Scheme: -Return the s-th element of v. -Restriction: 0 <= s < nlanes - -Usage: -@code -v_int32x4 a; -int r; -r = v_extract_n<2>(a); -@endcode -For all types. */ -template -inline _Tp v_extract_n(const v_reg<_Tp, n>& v) -{ - CV_DbgAssert(s >= 0 && s < n); - return v.s[s]; -} - -/** @brief Broadcast i-th element of vector - -Scheme: -@code -{ v[0] v[1] v[2] ... v[SZ] } => { v[i], v[i], v[i] ... v[i] } -@endcode -Restriction: 0 <= i < nlanes -Supported types: 32-bit integers and floats (s32/u32/f32) - */ -template -inline v_reg<_Tp, n> v_broadcast_element(const v_reg<_Tp, n>& a) -{ - CV_DbgAssert(i >= 0 && i < n); - return v_reg<_Tp, n>::all(a.s[i]); -} - -/** @brief Round elements - -Rounds each value. Input type is float vector ==> output type is int vector. -@note Only for floating point types. -*/ -template inline v_reg v_round(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - c.s[i] = cvRound(a.s[i]); - return c; -} - -/** @overload */ -template inline v_reg v_round(const v_reg& a, const v_reg& b) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - { - c.s[i] = cvRound(a.s[i]); - c.s[i+n] = cvRound(b.s[i]); - } - return c; -} - -/** @brief Floor elements - -Floor each value. Input type is float vector ==> output type is int vector. -@note Only for floating point types. -*/ -template inline v_reg v_floor(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - c.s[i] = cvFloor(a.s[i]); - return c; -} - -/** @brief Ceil elements - -Ceil each value. Input type is float vector ==> output type is int vector. -@note Only for floating point types. -*/ -template inline v_reg v_ceil(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - c.s[i] = cvCeil(a.s[i]); - return c; -} - -/** @brief Truncate elements - -Truncate each value. Input type is float vector ==> output type is int vector. -@note Only for floating point types. -*/ -template inline v_reg v_trunc(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - c.s[i] = (int)(a.s[i]); - return c; -} - -/** @overload */ -template inline v_reg v_round(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - { - c.s[i] = cvRound(a.s[i]); - c.s[i+n] = 0; - } - return c; -} - -/** @overload */ -template inline v_reg v_floor(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - { - c.s[i] = cvFloor(a.s[i]); - c.s[i+n] = 0; - } - return c; -} - -/** @overload */ -template inline v_reg v_ceil(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - { - c.s[i] = cvCeil(a.s[i]); - c.s[i+n] = 0; - } - return c; -} - -/** @overload */ -template inline v_reg v_trunc(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - { - c.s[i] = (int)(a.s[i]); - c.s[i+n] = 0; - } - return c; -} - -/** @brief Convert to float - -Supported input type is cv::v_int32. */ -template inline v_reg v_cvt_f32(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - c.s[i] = (float)a.s[i]; - return c; -} - -/** @brief Convert lower half to float - -Supported input type is cv::v_float64. */ -template inline v_reg v_cvt_f32(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - { - c.s[i] = (float)a.s[i]; - c.s[i+n] = 0; - } - return c; -} - -/** @brief Convert to float - -Supported input type is cv::v_float64. */ -template inline v_reg v_cvt_f32(const v_reg& a, const v_reg& b) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - { - c.s[i] = (float)a.s[i]; - c.s[i+n] = (float)b.s[i]; - } - return c; -} - -/** @brief Convert lower half to double - -Supported input type is cv::v_int32. */ -template CV_INLINE v_reg v_cvt_f64(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < (n/2); i++ ) - c.s[i] = (double)a.s[i]; - return c; -} - -/** @brief Convert to double high part of vector - -Supported input type is cv::v_int32. */ -template CV_INLINE v_reg v_cvt_f64_high(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < (n/2); i++ ) - c.s[i] = (double)a.s[i + (n/2)]; - return c; -} - -/** @brief Convert lower half to double - -Supported input type is cv::v_float32. */ -template CV_INLINE v_reg v_cvt_f64(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < (n/2); i++ ) - c.s[i] = (double)a.s[i]; - return c; -} - -/** @brief Convert to double high part of vector - -Supported input type is cv::v_float32. */ -template CV_INLINE v_reg v_cvt_f64_high(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < (n/2); i++ ) - c.s[i] = (double)a.s[i + (n/2)]; - return c; -} - -/** @brief Convert to double - -Supported input type is cv::v_int64. */ -template CV_INLINE v_reg v_cvt_f64(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - c.s[i] = (double)a.s[i]; - return c; -} - - -template inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_lut(const _Tp* tab, const int* idx) -{ - v_reg<_Tp, simd128_width / sizeof(_Tp)> c; - for (int i = 0; i < c.nlanes; i++) - c.s[i] = tab[idx[i]]; - return c; -} -template inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_lut_pairs(const _Tp* tab, const int* idx) -{ - v_reg<_Tp, simd128_width / sizeof(_Tp)> c; - for (int i = 0; i < c.nlanes; i++) - c.s[i] = tab[idx[i / 2] + i % 2]; - return c; -} -template inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_lut_quads(const _Tp* tab, const int* idx) -{ - v_reg<_Tp, simd128_width / sizeof(_Tp)> c; - for (int i = 0; i < c.nlanes; i++) - c.s[i] = tab[idx[i / 4] + i % 4]; - return c; -} - -template inline v_reg v_lut(const int* tab, const v_reg& idx) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - c.s[i] = tab[idx.s[i]]; - return c; -} - -template inline v_reg v_lut(const unsigned* tab, const v_reg& idx) -{ - v_reg c; - for (int i = 0; i < n; i++) - c.s[i] = tab[idx.s[i]]; - return c; -} - -template inline v_reg v_lut(const float* tab, const v_reg& idx) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - c.s[i] = tab[idx.s[i]]; - return c; -} - -template inline v_reg v_lut(const double* tab, const v_reg& idx) -{ - v_reg c; - for( int i = 0; i < n/2; i++ ) - c.s[i] = tab[idx.s[i]]; - return c; -} - - -template inline void v_lut_deinterleave(const float* tab, const v_reg& idx, - v_reg& x, v_reg& y) -{ - for( int i = 0; i < n; i++ ) - { - int j = idx.s[i]; - x.s[i] = tab[j]; - y.s[i] = tab[j+1]; - } -} - -template inline void v_lut_deinterleave(const double* tab, const v_reg& idx, - v_reg& x, v_reg& y) -{ - for( int i = 0; i < n; i++ ) - { - int j = idx.s[i]; - x.s[i] = tab[j]; - y.s[i] = tab[j+1]; - } -} - -template inline v_reg<_Tp, n> v_interleave_pairs(const v_reg<_Tp, n>& vec) -{ - v_reg<_Tp, n> c; - for (int i = 0; i < n/4; i++) - { - c.s[4*i ] = vec.s[4*i ]; - c.s[4*i+1] = vec.s[4*i+2]; - c.s[4*i+2] = vec.s[4*i+1]; - c.s[4*i+3] = vec.s[4*i+3]; - } - return c; -} - -template inline v_reg<_Tp, n> v_interleave_quads(const v_reg<_Tp, n>& vec) -{ - v_reg<_Tp, n> c; - for (int i = 0; i < n/8; i++) - { - c.s[8*i ] = vec.s[8*i ]; - c.s[8*i+1] = vec.s[8*i+4]; - c.s[8*i+2] = vec.s[8*i+1]; - c.s[8*i+3] = vec.s[8*i+5]; - c.s[8*i+4] = vec.s[8*i+2]; - c.s[8*i+5] = vec.s[8*i+6]; - c.s[8*i+6] = vec.s[8*i+3]; - c.s[8*i+7] = vec.s[8*i+7]; - } - return c; -} - -template inline v_reg<_Tp, n> v_pack_triplets(const v_reg<_Tp, n>& vec) -{ - v_reg<_Tp, n> c; - for (int i = 0; i < n/4; i++) - { - c.s[3*i ] = vec.s[4*i ]; - c.s[3*i+1] = vec.s[4*i+1]; - c.s[3*i+2] = vec.s[4*i+2]; - } - return c; -} - -/** @brief Transpose 4x4 matrix - -Scheme: -@code -a0 {A1 A2 A3 A4} -a1 {B1 B2 B3 B4} -a2 {C1 C2 C3 C4} -a3 {D1 D2 D3 D4} -=============== -b0 {A1 B1 C1 D1} -b1 {A2 B2 C2 D2} -b2 {A3 B3 C3 D3} -b3 {A4 B4 C4 D4} -@endcode -*/ -template -inline void v_transpose4x4( v_reg<_Tp, n>& a0, const v_reg<_Tp, n>& a1, - const v_reg<_Tp, n>& a2, const v_reg<_Tp, n>& a3, - v_reg<_Tp, n>& b0, v_reg<_Tp, n>& b1, - v_reg<_Tp, n>& b2, v_reg<_Tp, n>& b3 ) -{ - for (int i = 0; i < n / 4; i++) - { - b0.s[0 + i*4] = a0.s[0 + i*4]; b0.s[1 + i*4] = a1.s[0 + i*4]; - b0.s[2 + i*4] = a2.s[0 + i*4]; b0.s[3 + i*4] = a3.s[0 + i*4]; - b1.s[0 + i*4] = a0.s[1 + i*4]; b1.s[1 + i*4] = a1.s[1 + i*4]; - b1.s[2 + i*4] = a2.s[1 + i*4]; b1.s[3 + i*4] = a3.s[1 + i*4]; - b2.s[0 + i*4] = a0.s[2 + i*4]; b2.s[1 + i*4] = a1.s[2 + i*4]; - b2.s[2 + i*4] = a2.s[2 + i*4]; b2.s[3 + i*4] = a3.s[2 + i*4]; - b3.s[0 + i*4] = a0.s[3 + i*4]; b3.s[1 + i*4] = a1.s[3 + i*4]; - b3.s[2 + i*4] = a2.s[3 + i*4]; b3.s[3 + i*4] = a3.s[3 + i*4]; - } -} - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_C_INIT_ZERO(_Tpvec, prefix, suffix) \ -inline _Tpvec prefix##_setzero_##suffix() { return _Tpvec::zero(); } \ -template <> inline _Tpvec v_setzero_() { return _Tpvec::zero(); } - -//! @name Init with zero -//! @{ -//! @brief Create new vector with zero elements -OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint8x16, v, u8) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_int8x16, v, s8) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint16x8, v, u16) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_int16x8, v, s16) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint32x4, v, u32) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_int32x4, v, s32) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_float32x4, v, f32) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_float64x2, v, f64) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint64x2, v, u64) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_int64x2, v, s64) - -#if CV_SIMD256 -OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint8x32, v256, u8) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_int8x32, v256, s8) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint16x16, v256, u16) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_int16x16, v256, s16) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint32x8, v256, u32) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_int32x8, v256, s32) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_float32x8, v256, f32) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_float64x4, v256, f64) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint64x4, v256, u64) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_int64x4, v256, s64) -#endif - -#if CV_SIMD512 -OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint8x64, v512, u8) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_int8x64, v512, s8) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint16x32, v512, u16) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_int16x32, v512, s16) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint32x16, v512, u32) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_int32x16, v512, s32) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_float32x16, v512, f32) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_float64x8, v512, f64) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint64x8, v512, u64) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_int64x8, v512, s64) -#endif -//! @} - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_C_INIT_VAL(_Tpvec, _Tp, prefix, suffix) \ -inline _Tpvec prefix##_setall_##suffix(_Tp val) { return _Tpvec::all(val); } \ -template <> inline _Tpvec v_setall_(_Tp val) { return _Tpvec::all(val); } - -//! @name Init with value -//! @{ -//! @brief Create new vector with elements set to a specific value -OPENCV_HAL_IMPL_C_INIT_VAL(v_uint8x16, uchar, v, u8) -OPENCV_HAL_IMPL_C_INIT_VAL(v_int8x16, schar, v, s8) -OPENCV_HAL_IMPL_C_INIT_VAL(v_uint16x8, ushort, v, u16) -OPENCV_HAL_IMPL_C_INIT_VAL(v_int16x8, short, v, s16) -OPENCV_HAL_IMPL_C_INIT_VAL(v_uint32x4, unsigned, v, u32) -OPENCV_HAL_IMPL_C_INIT_VAL(v_int32x4, int, v, s32) -OPENCV_HAL_IMPL_C_INIT_VAL(v_float32x4, float, v, f32) -OPENCV_HAL_IMPL_C_INIT_VAL(v_float64x2, double, v, f64) -OPENCV_HAL_IMPL_C_INIT_VAL(v_uint64x2, uint64, v, u64) -OPENCV_HAL_IMPL_C_INIT_VAL(v_int64x2, int64, v, s64) - -#if CV_SIMD256 -OPENCV_HAL_IMPL_C_INIT_VAL(v_uint8x32, uchar, v256, u8) -OPENCV_HAL_IMPL_C_INIT_VAL(v_int8x32, schar, v256, s8) -OPENCV_HAL_IMPL_C_INIT_VAL(v_uint16x16, ushort, v256, u16) -OPENCV_HAL_IMPL_C_INIT_VAL(v_int16x16, short, v256, s16) -OPENCV_HAL_IMPL_C_INIT_VAL(v_uint32x8, unsigned, v256, u32) -OPENCV_HAL_IMPL_C_INIT_VAL(v_int32x8, int, v256, s32) -OPENCV_HAL_IMPL_C_INIT_VAL(v_float32x8, float, v256, f32) -OPENCV_HAL_IMPL_C_INIT_VAL(v_float64x4, double, v256, f64) -OPENCV_HAL_IMPL_C_INIT_VAL(v_uint64x4, uint64, v256, u64) -OPENCV_HAL_IMPL_C_INIT_VAL(v_int64x4, int64, v256, s64) -#endif - -#if CV_SIMD512 -OPENCV_HAL_IMPL_C_INIT_VAL(v_uint8x64, uchar, v512, u8) -OPENCV_HAL_IMPL_C_INIT_VAL(v_int8x64, schar, v512, s8) -OPENCV_HAL_IMPL_C_INIT_VAL(v_uint16x32, ushort, v512, u16) -OPENCV_HAL_IMPL_C_INIT_VAL(v_int16x32, short, v512, s16) -OPENCV_HAL_IMPL_C_INIT_VAL(v_uint32x16, unsigned, v512, u32) -OPENCV_HAL_IMPL_C_INIT_VAL(v_int32x16, int, v512, s32) -OPENCV_HAL_IMPL_C_INIT_VAL(v_float32x16, float, v512, f32) -OPENCV_HAL_IMPL_C_INIT_VAL(v_float64x8, double, v512, f64) -OPENCV_HAL_IMPL_C_INIT_VAL(v_uint64x8, uint64, v512, u64) -OPENCV_HAL_IMPL_C_INIT_VAL(v_int64x8, int64, v512, s64) -#endif -//! @} - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_C_REINTERPRET(_Tp, suffix) \ -template inline v_reg<_Tp, n0*sizeof(_Tp0)/sizeof(_Tp)> \ - v_reinterpret_as_##suffix(const v_reg<_Tp0, n0>& a) \ -{ return a.template reinterpret_as<_Tp, n0*sizeof(_Tp0)/sizeof(_Tp)>(); } - -//! @name Reinterpret -//! @{ -//! @brief Convert vector to different type without modifying underlying data. -OPENCV_HAL_IMPL_C_REINTERPRET(uchar, u8) -OPENCV_HAL_IMPL_C_REINTERPRET(schar, s8) -OPENCV_HAL_IMPL_C_REINTERPRET(ushort, u16) -OPENCV_HAL_IMPL_C_REINTERPRET(short, s16) -OPENCV_HAL_IMPL_C_REINTERPRET(unsigned, u32) -OPENCV_HAL_IMPL_C_REINTERPRET(int, s32) -OPENCV_HAL_IMPL_C_REINTERPRET(float, f32) -OPENCV_HAL_IMPL_C_REINTERPRET(double, f64) -OPENCV_HAL_IMPL_C_REINTERPRET(uint64, u64) -OPENCV_HAL_IMPL_C_REINTERPRET(int64, s64) -//! @} - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_C_SHIFTL(_Tp) \ -template inline v_reg<_Tp, n> v_shl(const v_reg<_Tp, n>& a) \ -{ return v_shl(a, shift); } - -//! @name Left shift -//! @{ -//! @brief Shift left -OPENCV_HAL_IMPL_C_SHIFTL(ushort) -OPENCV_HAL_IMPL_C_SHIFTL(short) -OPENCV_HAL_IMPL_C_SHIFTL(unsigned) -OPENCV_HAL_IMPL_C_SHIFTL(int) -OPENCV_HAL_IMPL_C_SHIFTL(uint64) -OPENCV_HAL_IMPL_C_SHIFTL(int64) -//! @} - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_C_SHIFTR(_Tp) \ -template inline v_reg<_Tp, n> v_shr(const v_reg<_Tp, n>& a) \ -{ return v_shr(a, shift); } - -//! @name Right shift -//! @{ -//! @brief Shift right -OPENCV_HAL_IMPL_C_SHIFTR(ushort) -OPENCV_HAL_IMPL_C_SHIFTR(short) -OPENCV_HAL_IMPL_C_SHIFTR(unsigned) -OPENCV_HAL_IMPL_C_SHIFTR(int) -OPENCV_HAL_IMPL_C_SHIFTR(uint64) -OPENCV_HAL_IMPL_C_SHIFTR(int64) -//! @} - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_C_RSHIFTR(_Tp) \ -template inline v_reg<_Tp, n> v_rshr(const v_reg<_Tp, n>& a) \ -{ \ - v_reg<_Tp, n> c; \ - for( int i = 0; i < n; i++ ) \ - c.s[i] = (_Tp)((a.s[i] + ((_Tp)1 << (shift - 1))) >> shift); \ - return c; \ -} - -//! @name Rounding shift -//! @{ -//! @brief Rounding shift right -OPENCV_HAL_IMPL_C_RSHIFTR(ushort) -OPENCV_HAL_IMPL_C_RSHIFTR(short) -OPENCV_HAL_IMPL_C_RSHIFTR(unsigned) -OPENCV_HAL_IMPL_C_RSHIFTR(int) -OPENCV_HAL_IMPL_C_RSHIFTR(uint64) -OPENCV_HAL_IMPL_C_RSHIFTR(int64) -//! @} - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_C_PACK(_Tp, _Tpn, pack_suffix, cast) \ -template inline v_reg<_Tpn, 2*n> v_##pack_suffix(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ -{ \ - v_reg<_Tpn, 2*n> c; \ - for( int i = 0; i < n; i++ ) \ - { \ - c.s[i] = cast<_Tpn>(a.s[i]); \ - c.s[i+n] = cast<_Tpn>(b.s[i]); \ - } \ - return c; \ -} - -//! @name Pack -//! @{ -//! @brief Pack values from two vectors to one -//! -//! Return vector type have twice more elements than input vector types. Variant with _u_ suffix also -//! converts to corresponding unsigned type. -//! -//! - pack: for 16-, 32- and 64-bit integer input types -//! - pack_u: for 16- and 32-bit signed integer input types -//! -//! @note All variants except 64-bit use saturation. -OPENCV_HAL_IMPL_C_PACK(ushort, uchar, pack, saturate_cast) -OPENCV_HAL_IMPL_C_PACK(short, schar, pack, saturate_cast) -OPENCV_HAL_IMPL_C_PACK(unsigned, ushort, pack, saturate_cast) -OPENCV_HAL_IMPL_C_PACK(int, short, pack, saturate_cast) -OPENCV_HAL_IMPL_C_PACK(uint64, unsigned, pack, static_cast) -OPENCV_HAL_IMPL_C_PACK(int64, int, pack, static_cast) -OPENCV_HAL_IMPL_C_PACK(short, uchar, pack_u, saturate_cast) -OPENCV_HAL_IMPL_C_PACK(int, ushort, pack_u, saturate_cast) -//! @} - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_C_RSHR_PACK(_Tp, _Tpn, pack_suffix, cast) \ -template inline v_reg<_Tpn, 2*n> v_rshr_##pack_suffix(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ -{ \ - v_reg<_Tpn, 2*n> c; \ - for( int i = 0; i < n; i++ ) \ - { \ - c.s[i] = cast<_Tpn>((a.s[i] + ((_Tp)1 << (shift - 1))) >> shift); \ - c.s[i+n] = cast<_Tpn>((b.s[i] + ((_Tp)1 << (shift - 1))) >> shift); \ - } \ - return c; \ -} - -//! @name Pack with rounding shift -//! @{ -//! @brief Pack values from two vectors to one with rounding shift -//! -//! Values from the input vectors will be shifted right by _n_ bits with rounding, converted to narrower -//! type and returned in the result vector. Variant with _u_ suffix converts to unsigned type. -//! -//! - pack: for 16-, 32- and 64-bit integer input types -//! - pack_u: for 16- and 32-bit signed integer input types -//! -//! @note All variants except 64-bit use saturation. -OPENCV_HAL_IMPL_C_RSHR_PACK(ushort, uchar, pack, saturate_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK(short, schar, pack, saturate_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK(unsigned, ushort, pack, saturate_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK(int, short, pack, saturate_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK(uint64, unsigned, pack, static_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK(int64, int, pack, static_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK(short, uchar, pack_u, saturate_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK(int, ushort, pack_u, saturate_cast) -//! @} - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_C_PACK_STORE(_Tp, _Tpn, pack_suffix, cast) \ -template inline void v_##pack_suffix##_store(_Tpn* ptr, const v_reg<_Tp, n>& a) \ -{ \ - for( int i = 0; i < n; i++ ) \ - ptr[i] = cast<_Tpn>(a.s[i]); \ -} - -//! @name Pack and store -//! @{ -//! @brief Store values from the input vector into memory with pack -//! -//! Values will be stored into memory with conversion to narrower type. -//! Variant with _u_ suffix converts to corresponding unsigned type. -//! -//! - pack: for 16-, 32- and 64-bit integer input types -//! - pack_u: for 16- and 32-bit signed integer input types -//! -//! @note All variants except 64-bit use saturation. -OPENCV_HAL_IMPL_C_PACK_STORE(ushort, uchar, pack, saturate_cast) -OPENCV_HAL_IMPL_C_PACK_STORE(short, schar, pack, saturate_cast) -OPENCV_HAL_IMPL_C_PACK_STORE(unsigned, ushort, pack, saturate_cast) -OPENCV_HAL_IMPL_C_PACK_STORE(int, short, pack, saturate_cast) -OPENCV_HAL_IMPL_C_PACK_STORE(uint64, unsigned, pack, static_cast) -OPENCV_HAL_IMPL_C_PACK_STORE(int64, int, pack, static_cast) -OPENCV_HAL_IMPL_C_PACK_STORE(short, uchar, pack_u, saturate_cast) -OPENCV_HAL_IMPL_C_PACK_STORE(int, ushort, pack_u, saturate_cast) -//! @} - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(_Tp, _Tpn, pack_suffix, cast) \ -template inline void v_rshr_##pack_suffix##_store(_Tpn* ptr, const v_reg<_Tp, n>& a) \ -{ \ - for( int i = 0; i < n; i++ ) \ - ptr[i] = cast<_Tpn>((a.s[i] + ((_Tp)1 << (shift - 1))) >> shift); \ -} - -//! @name Pack and store with rounding shift -//! @{ -//! @brief Store values from the input vector into memory with pack -//! -//! Values will be shifted _n_ bits right with rounding, converted to narrower type and stored into -//! memory. Variant with _u_ suffix converts to unsigned type. -//! -//! - pack: for 16-, 32- and 64-bit integer input types -//! - pack_u: for 16- and 32-bit signed integer input types -//! -//! @note All variants except 64-bit use saturation. -OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(ushort, uchar, pack, saturate_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(short, schar, pack, saturate_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(unsigned, ushort, pack, saturate_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(int, short, pack, saturate_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(uint64, unsigned, pack, static_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(int64, int, pack, static_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(short, uchar, pack_u, saturate_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(int, ushort, pack_u, saturate_cast) -//! @} - -//! @cond IGNORED -template -inline void _pack_b(_Tpm* mptr, const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ - for (int i = 0; i < n; ++i) - { - mptr[i] = (_Tpm)a.s[i]; - mptr[i + n] = (_Tpm)b.s[i]; - } -} -//! @endcond - -//! @name Pack boolean values -//! @{ -//! @brief Pack boolean values from multiple vectors to one unsigned 8-bit integer vector -//! -//! @note Must provide valid boolean values to guarantee same result for all architectures. - -/** @brief -//! For 16-bit boolean values - -Scheme: -@code -a {0xFFFF 0 0 0xFFFF 0 0xFFFF 0xFFFF 0} -b {0xFFFF 0 0xFFFF 0 0 0xFFFF 0 0xFFFF} -=============== -{ - 0xFF 0 0 0xFF 0 0xFF 0xFF 0 - 0xFF 0 0xFF 0 0 0xFF 0 0xFF -} -@endcode */ - -template inline v_reg v_pack_b(const v_reg& a, const v_reg& b) -{ - v_reg mask; - _pack_b(mask.s, a, b); - return mask; -} - -/** @overload -For 32-bit boolean values - -Scheme: -@code -a {0xFFFF.. 0 0 0xFFFF..} -b {0 0xFFFF.. 0xFFFF.. 0} -c {0xFFFF.. 0 0xFFFF.. 0} -d {0 0xFFFF.. 0 0xFFFF..} -=============== -{ - 0xFF 0 0 0xFF 0 0xFF 0xFF 0 - 0xFF 0 0xFF 0 0 0xFF 0 0xFF -} -@endcode */ - -template inline v_reg v_pack_b(const v_reg& a, const v_reg& b, - const v_reg& c, const v_reg& d) -{ - v_reg mask; - _pack_b(mask.s, a, b); - _pack_b(mask.s + 2*n, c, d); - return mask; -} - -/** @overload -For 64-bit boolean values - -Scheme: -@code -a {0xFFFF.. 0} -b {0 0xFFFF..} -c {0xFFFF.. 0} -d {0 0xFFFF..} - -e {0xFFFF.. 0} -f {0xFFFF.. 0} -g {0 0xFFFF..} -h {0 0xFFFF..} -=============== -{ - 0xFF 0 0 0xFF 0xFF 0 0 0xFF - 0xFF 0 0xFF 0 0 0xFF 0 0xFF -} -@endcode */ -template inline v_reg v_pack_b(const v_reg& a, const v_reg& b, - const v_reg& c, const v_reg& d, - const v_reg& e, const v_reg& f, - const v_reg& g, const v_reg& h) -{ - v_reg mask; - _pack_b(mask.s, a, b); - _pack_b(mask.s + 2*n, c, d); - _pack_b(mask.s + 4*n, e, f); - _pack_b(mask.s + 6*n, g, h); - return mask; -} -//! @} - -/** @brief Matrix multiplication - -Scheme: -@code -{A0 A1 A2 A3} |V0| -{B0 B1 B2 B3} |V1| -{C0 C1 C2 C3} |V2| -{D0 D1 D2 D3} x |V3| -==================== -{R0 R1 R2 R3}, where: -R0 = A0V0 + B0V1 + C0V2 + D0V3, -R1 = A1V0 + B1V1 + C1V2 + D1V3 -... -@endcode -*/ -template -inline v_reg v_matmul(const v_reg& v, - const v_reg& a, const v_reg& b, - const v_reg& c, const v_reg& d) -{ - v_reg res; - for (int i = 0; i < n / 4; i++) - { - res.s[0 + i*4] = v.s[0 + i*4] * a.s[0 + i*4] + v.s[1 + i*4] * b.s[0 + i*4] + v.s[2 + i*4] * c.s[0 + i*4] + v.s[3 + i*4] * d.s[0 + i*4]; - res.s[1 + i*4] = v.s[0 + i*4] * a.s[1 + i*4] + v.s[1 + i*4] * b.s[1 + i*4] + v.s[2 + i*4] * c.s[1 + i*4] + v.s[3 + i*4] * d.s[1 + i*4]; - res.s[2 + i*4] = v.s[0 + i*4] * a.s[2 + i*4] + v.s[1 + i*4] * b.s[2 + i*4] + v.s[2 + i*4] * c.s[2 + i*4] + v.s[3 + i*4] * d.s[2 + i*4]; - res.s[3 + i*4] = v.s[0 + i*4] * a.s[3 + i*4] + v.s[1 + i*4] * b.s[3 + i*4] + v.s[2 + i*4] * c.s[3 + i*4] + v.s[3 + i*4] * d.s[3 + i*4]; - } - return res; -} - -/** @brief Matrix multiplication and add - -Scheme: -@code -{A0 A1 A2 A3} |V0| |D0| -{B0 B1 B2 B3} |V1| |D1| -{C0 C1 C2 C3} x |V2| + |D2| -==================== |D3| -{R0 R1 R2 R3}, where: -R0 = A0V0 + B0V1 + C0V2 + D0, -R1 = A1V0 + B1V1 + C1V2 + D1 -... -@endcode -*/ -template -inline v_reg v_matmuladd(const v_reg& v, - const v_reg& a, const v_reg& b, - const v_reg& c, const v_reg& d) -{ - v_reg res; - for (int i = 0; i < n / 4; i++) - { - res.s[0 + i * 4] = v.s[0 + i * 4] * a.s[0 + i * 4] + v.s[1 + i * 4] * b.s[0 + i * 4] + v.s[2 + i * 4] * c.s[0 + i * 4] + d.s[0 + i * 4]; - res.s[1 + i * 4] = v.s[0 + i * 4] * a.s[1 + i * 4] + v.s[1 + i * 4] * b.s[1 + i * 4] + v.s[2 + i * 4] * c.s[1 + i * 4] + d.s[1 + i * 4]; - res.s[2 + i * 4] = v.s[0 + i * 4] * a.s[2 + i * 4] + v.s[1 + i * 4] * b.s[2 + i * 4] + v.s[2 + i * 4] * c.s[2 + i * 4] + d.s[2 + i * 4]; - res.s[3 + i * 4] = v.s[0 + i * 4] * a.s[3 + i * 4] + v.s[1 + i * 4] * b.s[3 + i * 4] + v.s[2 + i * 4] * c.s[3 + i * 4] + d.s[3 + i * 4]; - } - return res; -} - - -template inline v_reg v_dotprod_expand(const v_reg& a, const v_reg& b) -{ return v_fma(v_cvt_f64(a), v_cvt_f64(b), v_mul(v_cvt_f64_high(a), v_cvt_f64_high(b))); } -template inline v_reg v_dotprod_expand(const v_reg& a, const v_reg& b, - const v_reg& c) -{ return v_fma(v_cvt_f64(a), v_cvt_f64(b), v_fma(v_cvt_f64_high(a), v_cvt_f64_high(b), c)); } - -template inline v_reg v_dotprod_expand_fast(const v_reg& a, const v_reg& b) -{ return v_dotprod_expand(a, b); } -template inline v_reg v_dotprod_expand_fast(const v_reg& a, const v_reg& b, - const v_reg& c) -{ return v_dotprod_expand(a, b, c); } - -////// FP16 support /////// - -inline v_reg -v_load_expand(const hfloat* ptr) -{ - v_reg v; - for( int i = 0; i < v.nlanes; i++ ) - { - v.s[i] = ptr[i]; - } - return v; -} -#if CV_SIMD256 -inline v_reg -v256_load_expand(const hfloat* ptr) -{ - v_reg v; - for (int i = 0; i < v.nlanes; i++) - { - v.s[i] = ptr[i]; - } - return v; -} -#endif -#if CV_SIMD512 -inline v_reg -v512_load_expand(const hfloat* ptr) -{ - v_reg v; - for (int i = 0; i < v.nlanes; i++) - { - v.s[i] = ptr[i]; - } - return v; -} -#endif - -template inline void -v_pack_store(hfloat* ptr, const v_reg& v) -{ - for( int i = 0; i < v.nlanes; i++ ) - { - ptr[i] = hfloat(v.s[i]); - } -} - -inline void v_cleanup() {} -#if CV_SIMD256 -inline void v256_cleanup() {} -#endif -#if CV_SIMD512 -inline void v512_cleanup() {} -#endif - -//! @} - -#ifndef CV_DOXYGEN -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END -#endif -} - -#if !defined(CV_DOXYGEN) -#undef CV_SIMD256 -#undef CV_SIMD512 -#endif - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_HAL_INTRIN_CPP_HPP +#define OPENCV_HAL_INTRIN_CPP_HPP + +#include +#include +#include +#include "opencv2/core/utility.hpp" +#include "opencv2/core/saturate.hpp" + +//! @cond IGNORED +#define CV_SIMD128_CPP 1 +#if defined(CV_FORCE_SIMD128_CPP) +#define CV_SIMD128 1 +#define CV_SIMD128_64F 1 +#endif +#if defined(CV_DOXYGEN) +#define CV_SIMD128 1 +#define CV_SIMD128_64F 1 +#define CV_SIMD256 1 +#define CV_SIMD256_64F 1 +#define CV_SIMD512 1 +#define CV_SIMD512_64F 1 +#else +#define CV_SIMD256 0 // Explicitly disable SIMD256 and SIMD512 support for scalar intrinsic implementation +#define CV_SIMD512 0 // to avoid warnings during compilation +#endif +//! @endcond + +namespace cv +{ + +#ifndef CV_DOXYGEN +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN +#endif + +/** @addtogroup core_hal_intrin + +"Universal intrinsics" is a types and functions set intended to simplify vectorization of code on +different platforms. Currently a few different SIMD extensions on different architectures are supported. +128 bit registers of various types support is implemented for a wide range of architectures +including x86(__SSE/SSE2/SSE4.2__), ARM(__NEON__), PowerPC(__VSX__), MIPS(__MSA__). +256 bit long registers are supported on x86(__AVX2__) and 512 bit long registers are supported on x86(__AVX512__). +In case when there is no SIMD extension available during compilation, fallback C++ implementation of intrinsics +will be chosen and code will work as expected although it could be slower. + +### Types + +There are several types representing packed values vector registers, each type is +implemented as a structure based on a one SIMD register. + +- cv::v_uint8 and cv::v_int8: 8-bit integer values (unsigned/signed) - char +- cv::v_uint16 and cv::v_int16: 16-bit integer values (unsigned/signed) - short +- cv::v_uint32 and cv::v_int32: 32-bit integer values (unsigned/signed) - int +- cv::v_uint64 and cv::v_int64: 64-bit integer values (unsigned/signed) - int64 +- cv::v_float32: 32-bit floating point values (signed) - float +- cv::v_float64: 64-bit floating point values (signed) - double + +Exact bit length(and value quantity) of listed types is compile time deduced and depends on architecture SIMD +capabilities chosen as available during compilation of the library. All the types contains __nlanes__ enumeration +to check for exact value quantity of the type. + +In case the exact bit length of the type is important it is possible to use specific fixed length register types. + +There are several types representing 128-bit registers. + +- cv::v_uint8x16 and cv::v_int8x16: sixteen 8-bit integer values (unsigned/signed) - char +- cv::v_uint16x8 and cv::v_int16x8: eight 16-bit integer values (unsigned/signed) - short +- cv::v_uint32x4 and cv::v_int32x4: four 32-bit integer values (unsigned/signed) - int +- cv::v_uint64x2 and cv::v_int64x2: two 64-bit integer values (unsigned/signed) - int64 +- cv::v_float32x4: four 32-bit floating point values (signed) - float +- cv::v_float64x2: two 64-bit floating point values (signed) - double + +There are several types representing 256-bit registers. + +- cv::v_uint8x32 and cv::v_int8x32: thirty two 8-bit integer values (unsigned/signed) - char +- cv::v_uint16x16 and cv::v_int16x16: sixteen 16-bit integer values (unsigned/signed) - short +- cv::v_uint32x8 and cv::v_int32x8: eight 32-bit integer values (unsigned/signed) - int +- cv::v_uint64x4 and cv::v_int64x4: four 64-bit integer values (unsigned/signed) - int64 +- cv::v_float32x8: eight 32-bit floating point values (signed) - float +- cv::v_float64x4: four 64-bit floating point values (signed) - double + +@note +256 bit registers at the moment implemented for AVX2 SIMD extension only, if you want to use this type directly, +don't forget to check the CV_SIMD256 preprocessor definition: +@code +#if CV_SIMD256 +//... +#endif +@endcode + +There are several types representing 512-bit registers. + +- cv::v_uint8x64 and cv::v_int8x64: sixty four 8-bit integer values (unsigned/signed) - char +- cv::v_uint16x32 and cv::v_int16x32: thirty two 16-bit integer values (unsigned/signed) - short +- cv::v_uint32x16 and cv::v_int32x16: sixteen 32-bit integer values (unsigned/signed) - int +- cv::v_uint64x8 and cv::v_int64x8: eight 64-bit integer values (unsigned/signed) - int64 +- cv::v_float32x16: sixteen 32-bit floating point values (signed) - float +- cv::v_float64x8: eight 64-bit floating point values (signed) - double +@note +512 bit registers at the moment implemented for AVX512 SIMD extension only, if you want to use this type directly, +don't forget to check the CV_SIMD512 preprocessor definition. + +@note +cv::v_float64x2 is not implemented in NEON variant, if you want to use this type, don't forget to +check the CV_SIMD128_64F preprocessor definition. + +### Load and store operations + +These operations allow to set contents of the register explicitly or by loading it from some memory +block and to save contents of the register to memory block. + +There are variable size register load operations that provide result of maximum available size +depending on chosen platform capabilities. +- Constructors: +@ref v_reg::v_reg(const _Tp *ptr) "from memory", +- Other create methods: +vx_setall_s8, vx_setall_u8, ..., +vx_setzero_u8, vx_setzero_s8, ... +- Memory load operations: +vx_load, vx_load_aligned, vx_load_low, vx_load_halves, +- Memory operations with expansion of values: +vx_load_expand, vx_load_expand_q + +Also there are fixed size register load/store operations. + +For 128 bit registers +- Constructors: +@ref v_reg::v_reg(const _Tp *ptr) "from memory", +@ref v_reg::v_reg(_Tp s0, _Tp s1) "from two values", ... +- Other create methods: +@ref v_setall_s8, @ref v_setall_u8, ..., +@ref v_setzero_u8, @ref v_setzero_s8, ... +- Memory load operations: +@ref v_load, @ref v_load_aligned, @ref v_load_low, @ref v_load_halves, +- Memory operations with expansion of values: +@ref v_load_expand, @ref v_load_expand_q + +For 256 bit registers(check CV_SIMD256 preprocessor definition) +- Constructors: +@ref v_reg::v_reg(const _Tp *ptr) "from memory", +@ref v_reg::v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3) "from four values", ... +- Other create methods: +@ref v256_setall_s8, @ref v256_setall_u8, ..., +@ref v256_setzero_u8, @ref v256_setzero_s8, ... +- Memory load operations: +@ref v256_load, @ref v256_load_aligned, @ref v256_load_low, @ref v256_load_halves, +- Memory operations with expansion of values: +@ref v256_load_expand, @ref v256_load_expand_q + +For 512 bit registers(check CV_SIMD512 preprocessor definition) +- Constructors: +@ref v_reg::v_reg(const _Tp *ptr) "from memory", +@ref v_reg::v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3, _Tp s4, _Tp s5, _Tp s6, _Tp s7) "from eight values", ... +- Other create methods: +@ref v512_setall_s8, @ref v512_setall_u8, ..., +@ref v512_setzero_u8, @ref v512_setzero_s8, ... +- Memory load operations: +@ref v512_load, @ref v512_load_aligned, @ref v512_load_low, @ref v512_load_halves, +- Memory operations with expansion of values: +@ref v512_load_expand, @ref v512_load_expand_q + +Store to memory operations are similar across different platform capabilities: +@ref v_store, @ref v_store_aligned, +@ref v_store_high, @ref v_store_low + +### Value reordering + +These operations allow to reorder or recombine elements in one or multiple vectors. + +- Interleave, deinterleave (2, 3 and 4 channels): @ref v_load_deinterleave, @ref v_store_interleave +- Expand: @ref v_expand, @ref v_expand_low, @ref v_expand_high +- Pack: @ref v_pack, @ref v_pack_u, @ref v_pack_b, @ref v_rshr_pack, @ref v_rshr_pack_u, +@ref v_pack_store, @ref v_pack_u_store, @ref v_rshr_pack_store, @ref v_rshr_pack_u_store +- Recombine: @ref v_zip, @ref v_recombine, @ref v_combine_low, @ref v_combine_high +- Reverse: @ref v_reverse +- Extract: @ref v_extract + + +### Arithmetic, bitwise and comparison operations + +Element-wise binary and unary operations. + +- Arithmetics: +@ref v_add(const v_reg &a, const v_reg &b) "+", +@ref v_sub(const v_reg &a, const v_reg &b) "-", +@ref v_mul(const v_reg &a, const v_reg &b) "*", +@ref v_div(const v_reg &a, const v_reg &b) "/", +@ref v_mul_expand + +- Non-saturating arithmetics: @ref v_add_wrap, @ref v_sub_wrap + +- Bitwise shifts: +@ref v_shl(const v_reg &a, int s) "<<", +@ref v_shr(const v_reg &a, int s) ">>", +@ref v_shl, @ref v_shr + +- Bitwise logic: +@ref v_and(const v_reg &a, const v_reg &b) "&", +@ref v_or(const v_reg &a, const v_reg &b) "|", +@ref v_xor(const v_reg &a, const v_reg &b) "^", +@ref v_not(const v_reg &a) "~" + +- Comparison: +@ref v_gt(const v_reg &a, const v_reg &b) ">", +@ref v_ge(const v_reg &a, const v_reg &b) ">=", +@ref v_lt(const v_reg &a, const v_reg &b) "<", +@ref v_le(const v_reg &a, const v_reg &b) "<=", +@ref v_eq(const v_reg &a, const v_reg &b) "==", +@ref v_ne(const v_reg &a, const v_reg &b) "!=" + +- min/max: @ref v_min, @ref v_max + +### Reduce and mask + +Most of these operations return only one value. + +- Reduce: @ref v_reduce_min, @ref v_reduce_max, @ref v_reduce_sum, @ref v_popcount +- Mask: @ref v_signmask, @ref v_check_all, @ref v_check_any, @ref v_select + +### Other math + +- Some frequent operations: @ref v_sqrt, @ref v_invsqrt, @ref v_magnitude, @ref v_sqr_magnitude, @ref v_exp, @ref v_log, + @ref v_erf, @ref v_sin, @ref v_cos +- Absolute values: @ref v_abs, @ref v_absdiff, @ref v_absdiffs + +### Conversions + +Different type conversions and casts: + +- Rounding: @ref v_round, @ref v_floor, @ref v_ceil, @ref v_trunc, +- To float: @ref v_cvt_f32, @ref v_cvt_f64 +- Reinterpret: @ref v_reinterpret_as_u8, @ref v_reinterpret_as_s8, ... + +### Matrix operations + +In these operations vectors represent matrix rows/columns: @ref v_dotprod, @ref v_dotprod_fast, +@ref v_dotprod_expand, @ref v_dotprod_expand_fast, @ref v_matmul, @ref v_transpose4x4 + +### Usability + +Most operations are implemented only for some subset of the available types, following matrices +shows the applicability of different operations to the types. + +Regular integers: + +| Operations\\Types | uint 8 | int 8 | uint 16 | int 16 | uint 32 | int 32 | +|-------------------|:-:|:-:|:-:|:-:|:-:|:-:| +|load, store | x | x | x | x | x | x | +|interleave | x | x | x | x | x | x | +|expand | x | x | x | x | x | x | +|expand_low | x | x | x | x | x | x | +|expand_high | x | x | x | x | x | x | +|expand_q | x | x | | | | | +|add, sub | x | x | x | x | x | x | +|add_wrap, sub_wrap | x | x | x | x | | | +|mul_wrap | x | x | x | x | | | +|mul | x | x | x | x | x | x | +|mul_expand | x | x | x | x | x | | +|compare | x | x | x | x | x | x | +|shift | | | x | x | x | x | +|dotprod | | | | x | | x | +|dotprod_fast | | | | x | | x | +|dotprod_expand | x | x | x | x | | x | +|dotprod_expand_fast| x | x | x | x | | x | +|logical | x | x | x | x | x | x | +|min, max | x | x | x | x | x | x | +|absdiff | x | x | x | x | x | x | +|absdiffs | | x | | x | | | +|reduce | x | x | x | x | x | x | +|mask | x | x | x | x | x | x | +|pack | x | x | x | x | x | x | +|pack_u | x | | x | | | | +|pack_b | x | | | | | | +|unpack | x | x | x | x | x | x | +|extract | x | x | x | x | x | x | +|rotate (lanes) | x | x | x | x | x | x | +|cvt_flt32 | | | | | | x | +|cvt_flt64 | | | | | | x | +|transpose4x4 | | | | | x | x | +|reverse | x | x | x | x | x | x | +|extract_n | x | x | x | x | x | x | +|broadcast_element | | | | | x | x | + +Big integers: + +| Operations\\Types | uint 64 | int 64 | +|-------------------|:-:|:-:| +|load, store | x | x | +|add, sub | x | x | +|shift | x | x | +|logical | x | x | +|reverse | x | x | +|extract | x | x | +|rotate (lanes) | x | x | +|cvt_flt64 | | x | +|extract_n | x | x | + +Floating point: + +| Operations\\Types | float 32 | float 64 | +|-------------------|:-:|:-:| +|load, store | x | x | +|interleave | x | | +|add, sub | x | x | +|mul | x | x | +|div | x | x | +|compare | x | x | +|min, max | x | x | +|absdiff | x | x | +|reduce | x | | +|mask | x | x | +|unpack | x | x | +|cvt_flt32 | | x | +|cvt_flt64 | x | | +|sqrt, abs | x | x | +|float math | x | x | +|transpose4x4 | x | | +|extract | x | x | +|rotate (lanes) | x | x | +|reverse | x | x | +|extract_n | x | x | +|broadcast_element | x | | +|exp | x | x | +|log | x | x | +|sin, cos | x | x | + + @{ */ + +template struct v_reg +{ +//! @cond IGNORED + typedef _Tp lane_type; + enum { nlanes = n }; +// !@endcond + + /** @brief Constructor + + Initializes register with data from memory + @param ptr pointer to memory block with data for register */ + explicit v_reg(const _Tp* ptr) { for( int i = 0; i < n; i++ ) s[i] = ptr[i]; } + + /** @brief Constructor + + Initializes register with two 64-bit values */ + v_reg(_Tp s0, _Tp s1) { s[0] = s0; s[1] = s1; } + + /** @brief Constructor + + Initializes register with four 32-bit values */ + v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3) { s[0] = s0; s[1] = s1; s[2] = s2; s[3] = s3; } + + /** @brief Constructor + + Initializes register with eight 16-bit values */ + v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3, + _Tp s4, _Tp s5, _Tp s6, _Tp s7) + { + s[0] = s0; s[1] = s1; s[2] = s2; s[3] = s3; + s[4] = s4; s[5] = s5; s[6] = s6; s[7] = s7; + } + + /** @brief Constructor + + Initializes register with sixteen 8-bit values */ + v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3, + _Tp s4, _Tp s5, _Tp s6, _Tp s7, + _Tp s8, _Tp s9, _Tp s10, _Tp s11, + _Tp s12, _Tp s13, _Tp s14, _Tp s15) + { + s[0] = s0; s[1] = s1; s[2] = s2; s[3] = s3; + s[4] = s4; s[5] = s5; s[6] = s6; s[7] = s7; + s[8] = s8; s[9] = s9; s[10] = s10; s[11] = s11; + s[12] = s12; s[13] = s13; s[14] = s14; s[15] = s15; + } + + /** @brief Default constructor + + Does not initialize anything*/ + v_reg() {} + + /** @brief Copy constructor */ + v_reg(const v_reg<_Tp, n> & r) + { + for( int i = 0; i < n; i++ ) + s[i] = r.s[i]; + } + /** @brief Access first value + + Returns value of the first lane according to register type, for example: + @code{.cpp} + v_int32x4 r(1, 2, 3, 4); + int v = r.get0(); // returns 1 + v_uint64x2 r(1, 2); + uint64_t v = r.get0(); // returns 1 + @endcode + */ + _Tp get0() const { return s[0]; } + +//! @cond IGNORED + _Tp get(const int i) const { return s[i]; } + v_reg<_Tp, n> high() const + { + v_reg<_Tp, n> c; + int i; + for( i = 0; i < n/2; i++ ) + { + c.s[i] = s[i+(n/2)]; + c.s[i+(n/2)] = 0; + } + return c; + } + + static v_reg<_Tp, n> zero() + { + v_reg<_Tp, n> c; + for( int i = 0; i < n; i++ ) + c.s[i] = (_Tp)0; + return c; + } + + static v_reg<_Tp, n> all(_Tp s) + { + v_reg<_Tp, n> c; + for( int i = 0; i < n; i++ ) + c.s[i] = s; + return c; + } + + template v_reg<_Tp2, n2> reinterpret_as() const + { + size_t bytes = std::min(sizeof(_Tp2)*n2, sizeof(_Tp)*n); + v_reg<_Tp2, n2> c; + std::memcpy(&c.s[0], &s[0], bytes); + return c; + } + + v_reg& operator=(const v_reg<_Tp, n> & r) + { + for( int i = 0; i < n; i++ ) + s[i] = r.s[i]; + return *this; + } + + _Tp s[n]; +//! @endcond +}; + +/** @brief Sixteen 8-bit unsigned integer values */ +typedef v_reg v_uint8x16; +/** @brief Sixteen 8-bit signed integer values */ +typedef v_reg v_int8x16; +/** @brief Eight 16-bit unsigned integer values */ +typedef v_reg v_uint16x8; +/** @brief Eight 16-bit signed integer values */ +typedef v_reg v_int16x8; +/** @brief Four 32-bit unsigned integer values */ +typedef v_reg v_uint32x4; +/** @brief Four 32-bit signed integer values */ +typedef v_reg v_int32x4; +/** @brief Four 32-bit floating point values (single precision) */ +typedef v_reg v_float32x4; +/** @brief Two 64-bit floating point values (double precision) */ +typedef v_reg v_float64x2; +/** @brief Two 64-bit unsigned integer values */ +typedef v_reg v_uint64x2; +/** @brief Two 64-bit signed integer values */ +typedef v_reg v_int64x2; + +#if CV_SIMD256 +/** @brief Thirty two 8-bit unsigned integer values */ +typedef v_reg v_uint8x32; +/** @brief Thirty two 8-bit signed integer values */ +typedef v_reg v_int8x32; +/** @brief Sixteen 16-bit unsigned integer values */ +typedef v_reg v_uint16x16; +/** @brief Sixteen 16-bit signed integer values */ +typedef v_reg v_int16x16; +/** @brief Eight 32-bit unsigned integer values */ +typedef v_reg v_uint32x8; +/** @brief Eight 32-bit signed integer values */ +typedef v_reg v_int32x8; +/** @brief Eight 32-bit floating point values (single precision) */ +typedef v_reg v_float32x8; +/** @brief Four 64-bit floating point values (double precision) */ +typedef v_reg v_float64x4; +/** @brief Four 64-bit unsigned integer values */ +typedef v_reg v_uint64x4; +/** @brief Four 64-bit signed integer values */ +typedef v_reg v_int64x4; +#endif + +#if CV_SIMD512 +/** @brief Sixty four 8-bit unsigned integer values */ +typedef v_reg v_uint8x64; +/** @brief Sixty four 8-bit signed integer values */ +typedef v_reg v_int8x64; +/** @brief Thirty two 16-bit unsigned integer values */ +typedef v_reg v_uint16x32; +/** @brief Thirty two 16-bit signed integer values */ +typedef v_reg v_int16x32; +/** @brief Sixteen 32-bit unsigned integer values */ +typedef v_reg v_uint32x16; +/** @brief Sixteen 32-bit signed integer values */ +typedef v_reg v_int32x16; +/** @brief Sixteen 32-bit floating point values (single precision) */ +typedef v_reg v_float32x16; +/** @brief Eight 64-bit floating point values (double precision) */ +typedef v_reg v_float64x8; +/** @brief Eight 64-bit unsigned integer values */ +typedef v_reg v_uint64x8; +/** @brief Eight 64-bit signed integer values */ +typedef v_reg v_int64x8; +#endif + +enum { + simd128_width = 16, +#if CV_SIMD256 + simd256_width = 32, +#endif +#if CV_SIMD512 + simd512_width = 64, + simdmax_width = simd512_width +#elif CV_SIMD256 + simdmax_width = simd256_width +#else + simdmax_width = simd128_width +#endif +}; + +/** @brief Add values + +For all types. */ +template CV_INLINE v_reg<_Tp, n> v_add(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); + +/** @brief Subtract values + +For all types. */ +template CV_INLINE v_reg<_Tp, n> v_sub(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); + +/** @brief Multiply values + +For 16- and 32-bit integer types and floating types. */ +template CV_INLINE v_reg<_Tp, n> v_mul(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); + +/** @brief Divide values + +For floating types only. */ +template CV_INLINE v_reg<_Tp, n> v_div(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); + + +/** @brief Bitwise AND + +Only for integer types. */ +template CV_INLINE v_reg<_Tp, n> v_and(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); + +/** @brief Bitwise OR + +Only for integer types. */ +template CV_INLINE v_reg<_Tp, n> v_or(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); + +/** @brief Bitwise XOR + +Only for integer types.*/ +template CV_INLINE v_reg<_Tp, n> v_xor(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); + +/** @brief Bitwise NOT + +Only for integer types.*/ +template CV_INLINE v_reg<_Tp, n> v_not(const v_reg<_Tp, n>& a); + + +#ifndef CV_DOXYGEN + +#define CV__HAL_INTRIN_EXPAND_WITH_INTEGER_TYPES(macro_name, ...) \ +__CV_EXPAND(macro_name(uchar, __VA_ARGS__)) \ +__CV_EXPAND(macro_name(schar, __VA_ARGS__)) \ +__CV_EXPAND(macro_name(ushort, __VA_ARGS__)) \ +__CV_EXPAND(macro_name(short, __VA_ARGS__)) \ +__CV_EXPAND(macro_name(unsigned, __VA_ARGS__)) \ +__CV_EXPAND(macro_name(int, __VA_ARGS__)) \ +__CV_EXPAND(macro_name(uint64, __VA_ARGS__)) \ +__CV_EXPAND(macro_name(int64, __VA_ARGS__)) \ + +#define CV__HAL_INTRIN_EXPAND_WITH_FP_TYPES(macro_name, ...) \ +__CV_EXPAND(macro_name(float, __VA_ARGS__)) \ +__CV_EXPAND(macro_name(double, __VA_ARGS__)) \ + +#define CV__HAL_INTRIN_EXPAND_WITH_ALL_TYPES(macro_name, ...) \ +CV__HAL_INTRIN_EXPAND_WITH_INTEGER_TYPES(macro_name, __VA_ARGS__) \ +CV__HAL_INTRIN_EXPAND_WITH_FP_TYPES(macro_name, __VA_ARGS__) \ + +#define CV__HAL_INTRIN_IMPL_BIN_OP_(_Tp, bin_op, func) \ +template inline \ +v_reg<_Tp, n> func(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ +{ \ + v_reg<_Tp, n> c; \ + for( int i = 0; i < n; i++ ) \ + c.s[i] = saturate_cast<_Tp>(a.s[i] bin_op b.s[i]); \ + return c; \ +} + +#define CV__HAL_INTRIN_IMPL_BIN_OP(bin_op, func) CV__HAL_INTRIN_EXPAND_WITH_ALL_TYPES(CV__HAL_INTRIN_IMPL_BIN_OP_, bin_op, func) + +CV__HAL_INTRIN_IMPL_BIN_OP(+, v_add) +CV__HAL_INTRIN_IMPL_BIN_OP(-, v_sub) +CV__HAL_INTRIN_IMPL_BIN_OP(*, v_mul) +CV__HAL_INTRIN_EXPAND_WITH_FP_TYPES(CV__HAL_INTRIN_IMPL_BIN_OP_, /, v_div) + +#define CV__HAL_INTRIN_IMPL_BIT_OP_(_Tp, bit_op, func) \ +template CV_INLINE \ +v_reg<_Tp, n> func(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ +{ \ + v_reg<_Tp, n> c; \ + typedef typename V_TypeTraits<_Tp>::int_type itype; \ + for( int i = 0; i < n; i++ ) \ + c.s[i] = V_TypeTraits<_Tp>::reinterpret_from_int((itype)(V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) bit_op \ + V_TypeTraits<_Tp>::reinterpret_int(b.s[i]))); \ + return c; \ +} + +#define CV__HAL_INTRIN_IMPL_BIT_OP(bit_op, func) \ +CV__HAL_INTRIN_EXPAND_WITH_INTEGER_TYPES(CV__HAL_INTRIN_IMPL_BIT_OP_, bit_op, func) \ +CV__HAL_INTRIN_EXPAND_WITH_FP_TYPES(CV__HAL_INTRIN_IMPL_BIT_OP_, bit_op, func) /* TODO: FIXIT remove this after masks refactoring */ + + +CV__HAL_INTRIN_IMPL_BIT_OP(&, v_and) +CV__HAL_INTRIN_IMPL_BIT_OP(|, v_or) +CV__HAL_INTRIN_IMPL_BIT_OP(^, v_xor) + +#define CV__HAL_INTRIN_IMPL_BITWISE_NOT_(_Tp, dummy, dummy2) \ +template CV_INLINE \ +v_reg<_Tp, n> v_not(const v_reg<_Tp, n>& a) \ +{ \ + v_reg<_Tp, n> c; \ + for( int i = 0; i < n; i++ ) \ + c.s[i] = V_TypeTraits<_Tp>::reinterpret_from_int(~V_TypeTraits<_Tp>::reinterpret_int(a.s[i])); \ + return c; \ +} \ + +CV__HAL_INTRIN_EXPAND_WITH_INTEGER_TYPES(CV__HAL_INTRIN_IMPL_BITWISE_NOT_, ~, v_not) + +#endif // !CV_DOXYGEN + + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_MATH_FUNC(func, cfunc, _Tp2) \ +template inline v_reg<_Tp2, n> func(const v_reg<_Tp, n>& a) \ +{ \ + v_reg<_Tp2, n> c; \ + for( int i = 0; i < n; i++ ) \ + c.s[i] = cfunc(a.s[i]); \ + return c; \ +} + +/** @brief Square root of elements + +Only for floating point types.*/ +OPENCV_HAL_IMPL_MATH_FUNC(v_sqrt, std::sqrt, _Tp) + +/** + * @brief Exponential \f$ e^x \f$ of elements + * + * Only for floating point types. Core implementation steps: + * 1. Decompose Input: Convert the input to \f$ 2^{x \cdot \log_2e} \f$ and split its exponential into integer and fractional parts: + * \f$ x \cdot \log_2e = n + f \f$, where \f$ n \f$ is the integer part and \f$ f \f$ is the fractional part. + * 2. Compute \f$ 2^n \f$: Calculated by shifting the bits. + * 3. Adjust Fractional Part: Compute \f$ f \cdot \ln2 \f$ to convert the fractional part to base \f$ e \f$. + * \f$ C1 \f$ and \f$ C2 \f$ are used to adjust the fractional part. + * 4. Polynomial Approximation for \f$ e^{f \cdot \ln2} \f$: The closer the fractional part is to 0, the more accurate the result. + * - For float16 and float32, use a Taylor Series with 6 terms. + * - For float64, use Pade Polynomials Approximation with 4 terms. + * 5. Combine Results: Multiply the two parts together to get the final result: + * \f$ e^x = 2^n \cdot e^{f \cdot \ln2} \f$. + * + * @note The precision of the calculation depends on the implementation and the data type of the input vector. + */ +OPENCV_HAL_IMPL_MATH_FUNC(v_exp, std::exp, _Tp) +#define OPENCV_HAL_MATH_HAVE_EXP 1 + +/** + * @brief Natural logarithm \f$ \log(x) \f$ of elements + * + * Only for floating point types. Core implementation steps: + * 1. Decompose Input: Use binary representation to decompose the input into mantissa part \f$ m \f$ and exponent part \f$ e \f$. Such that \f$ \log(x) = \log(m \cdot 2^e) = \log(m) + e \cdot \ln(2) \f$. + * 2. Adjust Mantissa and Exponent Parts: If the mantissa is less than \f$ \sqrt{0.5} \f$, adjust the exponent and mantissa to ensure the mantissa is in the range \f$ (\sqrt{0.5}, \sqrt{2}) \f$ for better approximation. + * 3. Polynomial Approximation for \f$ \log(m) \f$: The closer the \f$ m \f$ is to 1, the more accurate the result. + * - For float16 and float32, use a Taylor Series with 9 terms. + * - For float64, use Pade Polynomials Approximation with 6 terms. + * 4. Combine Results: Add the two parts together to get the final result. + * + * @note The precision of the calculation depends on the implementation and the data type of the input. + * + * @note Similar to the behavior of std::log(), \f$ \ln(0) = -\infty \f$. + */ +OPENCV_HAL_IMPL_MATH_FUNC(v_log, std::log, _Tp) + +/** + * @brief Error function. + * + * @note Support FP32 precision for now. + */ +OPENCV_HAL_IMPL_MATH_FUNC(v_erf, std::erf, _Tp) + +/** + * @brief Compute sine \f$ sin(x) \f$ and cosine \f$ cos(x) \f$ of elements at the same time + * + * Only for floating point types. Core implementation steps: + * 1. Input Normalization: Scale the periodicity from 2π to 4 and reduce the angle to the range \f$ [0, \frac{\pi}{4}] \f$ using periodicity and trigonometric identities. + * 2. Polynomial Approximation for \f$ sin(x) \f$ and \f$ cos(x) \f$: + * - For float16 and float32, use a Taylor series with 4 terms for sine and 5 terms for cosine. + * - For float64, use a Taylor series with 7 terms for sine and 8 terms for cosine. + * 3. Select Results: select and convert the final sine and cosine values for the original input angle. + * + * @note The precision of the calculation depends on the implementation and the data type of the input vector. + */ +template +inline void v_sincos(const v_reg<_Tp, n>& x, v_reg<_Tp, n>& s, v_reg<_Tp, n>& c) +{ + for( int i = 0; i < n; i++ ) + { + s.s[i] = std::sin(x.s[i]); + c.s[i] = std::cos(x.s[i]); + } +} + +/** + * @brief Sine \f$ sin(x) \f$ of elements + * + * Only for floating point types. Core implementation the same as @ref v_sincos. + */ +OPENCV_HAL_IMPL_MATH_FUNC(v_sin, std::sin, _Tp) + +/** + * @brief Cosine \f$ cos(x) \f$ of elements + * + * Only for floating point types. Core implementation the same as @ref v_sincos. + */ +OPENCV_HAL_IMPL_MATH_FUNC(v_cos, std::cos, _Tp) + +/** @brief Absolute value of elements + +Only for floating point types.*/ +OPENCV_HAL_IMPL_MATH_FUNC(v_abs, (typename V_TypeTraits<_Tp>::abs_type)std::abs, + typename V_TypeTraits<_Tp>::abs_type) + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_MINMAX_FUNC(func, cfunc) \ +template inline v_reg<_Tp, n> func(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ +{ \ + v_reg<_Tp, n> c; \ + for( int i = 0; i < n; i++ ) \ + c.s[i] = cfunc(a.s[i], b.s[i]); \ + return c; \ +} + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_REDUCE_MINMAX_FUNC(func, cfunc) \ +template inline _Tp func(const v_reg<_Tp, n>& a) \ +{ \ + _Tp c = a.s[0]; \ + for( int i = 1; i < n; i++ ) \ + c = cfunc(c, a.s[i]); \ + return c; \ +} + +/** @brief Choose min values for each pair + +Scheme: +@code +{A1 A2 ...} +{B1 B2 ...} +-------------- +{min(A1,B1) min(A2,B2) ...} +@endcode +For all types except 64-bit integer. */ +OPENCV_HAL_IMPL_MINMAX_FUNC(v_min, std::min) + +/** @brief Choose max values for each pair + +Scheme: +@code +{A1 A2 ...} +{B1 B2 ...} +-------------- +{max(A1,B1) max(A2,B2) ...} +@endcode +For all types except 64-bit integer. */ +OPENCV_HAL_IMPL_MINMAX_FUNC(v_max, std::max) + +/** @brief Find one min value + +Scheme: +@code +{A1 A2 A3 ...} => min(A1,A2,A3,...) +@endcode +For all types except 64-bit integer and 64-bit floating point types. */ +OPENCV_HAL_IMPL_REDUCE_MINMAX_FUNC(v_reduce_min, std::min) + +/** @brief Find one max value + +Scheme: +@code +{A1 A2 A3 ...} => max(A1,A2,A3,...) +@endcode +For all types except 64-bit integer and 64-bit floating point types. */ +OPENCV_HAL_IMPL_REDUCE_MINMAX_FUNC(v_reduce_max, std::max) + +static const unsigned char popCountTable[] = +{ + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, +}; +/** @brief Count the 1 bits in the vector lanes and return result as corresponding unsigned type + +Scheme: +@code +{A1 A2 A3 ...} => {popcount(A1), popcount(A2), popcount(A3), ...} +@endcode +For all integer types. */ +template +inline v_reg::abs_type, n> v_popcount(const v_reg<_Tp, n>& a) +{ + v_reg::abs_type, n> b = v_reg::abs_type, n>::zero(); + for (int i = 0; i < n*(int)sizeof(_Tp); i++) + b.s[i/sizeof(_Tp)] += popCountTable[v_reinterpret_as_u8(a).s[i]]; + return b; +} + + +//! @cond IGNORED +template +inline void v_minmax( const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, + v_reg<_Tp, n>& minval, v_reg<_Tp, n>& maxval ) +{ + for( int i = 0; i < n; i++ ) + { + minval.s[i] = std::min(a.s[i], b.s[i]); + maxval.s[i] = std::max(a.s[i], b.s[i]); + } +} +//! @endcond + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_CMP_OP(cmp_op, func) \ +template \ +inline v_reg<_Tp, n> func(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ +{ \ + typedef typename V_TypeTraits<_Tp>::int_type itype; \ + v_reg<_Tp, n> c; \ + for( int i = 0; i < n; i++ ) \ + c.s[i] = V_TypeTraits<_Tp>::reinterpret_from_int((itype)-(int)(a.s[i] cmp_op b.s[i])); \ + return c; \ +} + +/** @brief Less-than comparison + +For all types except 64-bit integer values. */ +OPENCV_HAL_IMPL_CMP_OP(<, v_lt) + +/** @brief Greater-than comparison + +For all types except 64-bit integer values. */ +OPENCV_HAL_IMPL_CMP_OP(>, v_gt) + +/** @brief Less-than or equal comparison + +For all types except 64-bit integer values. */ +OPENCV_HAL_IMPL_CMP_OP(<=, v_le) + +/** @brief Greater-than or equal comparison + +For all types except 64-bit integer values. */ +OPENCV_HAL_IMPL_CMP_OP(>=, v_ge) + +/** @brief Equal comparison */ +OPENCV_HAL_IMPL_CMP_OP(==, v_eq) + +/** @brief Not equal comparison */ +OPENCV_HAL_IMPL_CMP_OP(!=, v_ne) + +template +inline v_reg v_not_nan(const v_reg& a) +{ + typedef typename V_TypeTraits::int_type itype; + v_reg c; + for (int i = 0; i < n; i++) + c.s[i] = V_TypeTraits::reinterpret_from_int((itype)-(int)(a.s[i] == a.s[i])); + return c; +} +template +inline v_reg v_not_nan(const v_reg& a) +{ + typedef typename V_TypeTraits::int_type itype; + v_reg c; + for (int i = 0; i < n; i++) + c.s[i] = V_TypeTraits::reinterpret_from_int((itype)-(int)(a.s[i] == a.s[i])); + return c; +} + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_ARITHM_OP(func, bin_op, cast_op, _Tp2) \ +template \ +inline v_reg<_Tp2, n> func(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ +{ \ + typedef _Tp2 rtype; \ + v_reg c; \ + for( int i = 0; i < n; i++ ) \ + c.s[i] = cast_op(a.s[i] bin_op b.s[i]); \ + return c; \ +} + +/** @brief Add values without saturation + +For 8- and 16-bit integer values. */ +OPENCV_HAL_IMPL_ARITHM_OP(v_add_wrap, +, (_Tp), _Tp) + +/** @brief Subtract values without saturation + +For 8- and 16-bit integer values. */ +OPENCV_HAL_IMPL_ARITHM_OP(v_sub_wrap, -, (_Tp), _Tp) + +/** @brief Multiply values without saturation + +For 8- and 16-bit integer values. */ +OPENCV_HAL_IMPL_ARITHM_OP(v_mul_wrap, *, (_Tp), _Tp) + +//! @cond IGNORED +template inline T _absdiff(T a, T b) +{ + return a > b ? a - b : b - a; +} +//! @endcond + +/** @brief Absolute difference + +Returns \f$ |a - b| \f$ converted to corresponding unsigned type. +Example: +@code{.cpp} +v_int32x4 a, b; // {1, 2, 3, 4} and {4, 3, 2, 1} +v_uint32x4 c = v_absdiff(a, b); // result is {3, 1, 1, 3} +@endcode +For 8-, 16-, 32-bit integer source types. */ +template +inline v_reg::abs_type, n> v_absdiff(const v_reg<_Tp, n>& a, const v_reg<_Tp, n> & b) +{ + typedef typename V_TypeTraits<_Tp>::abs_type rtype; + v_reg c; + const rtype mask = (rtype)(std::numeric_limits<_Tp>::is_signed ? (1 << (sizeof(rtype)*8 - 1)) : 0); + for( int i = 0; i < n; i++ ) + { + rtype ua = a.s[i] ^ mask; + rtype ub = b.s[i] ^ mask; + c.s[i] = _absdiff(ua, ub); + } + return c; +} + +/** @overload + +For 32-bit floating point values */ +template inline v_reg v_absdiff(const v_reg& a, const v_reg& b) +{ + v_reg c; + for( int i = 0; i < c.nlanes; i++ ) + c.s[i] = _absdiff(a.s[i], b.s[i]); + return c; +} + +/** @overload + +For 64-bit floating point values */ +template inline v_reg v_absdiff(const v_reg& a, const v_reg& b) +{ + v_reg c; + for( int i = 0; i < c.nlanes; i++ ) + c.s[i] = _absdiff(a.s[i], b.s[i]); + return c; +} + +/** @brief Saturating absolute difference + +Returns \f$ saturate(|a - b|) \f$ . +For 8-, 16-bit signed integer source types. */ +template +inline v_reg<_Tp, n> v_absdiffs(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ + v_reg<_Tp, n> c; + for( int i = 0; i < n; i++) + c.s[i] = saturate_cast<_Tp>(std::abs(a.s[i] - b.s[i])); + return c; +} + +/** @brief Inversed square root + +Returns \f$ 1/sqrt(a) \f$ +For floating point types only. */ +template +inline v_reg<_Tp, n> v_invsqrt(const v_reg<_Tp, n>& a) +{ + v_reg<_Tp, n> c; + for( int i = 0; i < n; i++ ) + c.s[i] = 1.f/std::sqrt(a.s[i]); + return c; +} + +/** @brief Magnitude + +Returns \f$ sqrt(a^2 + b^2) \f$ +For floating point types only. */ +template +inline v_reg<_Tp, n> v_magnitude(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ + v_reg<_Tp, n> c; + for( int i = 0; i < n; i++ ) + c.s[i] = std::sqrt(a.s[i]*a.s[i] + b.s[i]*b.s[i]); + return c; +} + +/** @brief Square of the magnitude + +Returns \f$ a^2 + b^2 \f$ +For floating point types only. */ +template +inline v_reg<_Tp, n> v_sqr_magnitude(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ + v_reg<_Tp, n> c; + for( int i = 0; i < n; i++ ) + c.s[i] = a.s[i]*a.s[i] + b.s[i]*b.s[i]; + return c; +} + +/** @brief Multiply and add + + Returns \f$ a*b + c \f$ + For floating point types and signed 32bit int only. */ +template +inline v_reg<_Tp, n> v_fma(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, + const v_reg<_Tp, n>& c) +{ + v_reg<_Tp, n> d; + for( int i = 0; i < n; i++ ) + d.s[i] = a.s[i]*b.s[i] + c.s[i]; + return d; +} + +/** @brief A synonym for v_fma */ +template +inline v_reg<_Tp, n> v_muladd(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, + const v_reg<_Tp, n>& c) +{ + return v_fma(a, b, c); +} + +/** @brief Dot product of elements + +Multiply values in two registers and sum adjacent result pairs. + +Scheme: +@code + {A1 A2 ...} // 16-bit +x {B1 B2 ...} // 16-bit +------------- +{A1B1+A2B2 ...} // 32-bit + +@endcode +*/ +template inline v_reg::w_type, n/2> +v_dotprod(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ + typedef typename V_TypeTraits<_Tp>::w_type w_type; + v_reg c; + for( int i = 0; i < (n/2); i++ ) + c.s[i] = (w_type)a.s[i*2]*b.s[i*2] + (w_type)a.s[i*2+1]*b.s[i*2+1]; + return c; +} + +/** @brief Dot product of elements + +Same as cv::v_dotprod, but add a third element to the sum of adjacent pairs. +Scheme: +@code + {A1 A2 ...} // 16-bit +x {B1 B2 ...} // 16-bit +------------- + {A1B1+A2B2+C1 ...} // 32-bit +@endcode +*/ +template inline v_reg::w_type, n/2> +v_dotprod(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, + const v_reg::w_type, n / 2>& c) +{ + typedef typename V_TypeTraits<_Tp>::w_type w_type; + v_reg s; + for( int i = 0; i < (n/2); i++ ) + s.s[i] = (w_type)a.s[i*2]*b.s[i*2] + (w_type)a.s[i*2+1]*b.s[i*2+1] + c.s[i]; + return s; +} + +/** @brief Fast Dot product of elements + +Same as cv::v_dotprod, but it may perform unorder sum between result pairs in some platforms, +this intrinsic can be used if the sum among all lanes is only matters +and also it should be yielding better performance on the affected platforms. + +*/ +template inline v_reg::w_type, n/2> +v_dotprod_fast(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ return v_dotprod(a, b); } + +/** @brief Fast Dot product of elements + +Same as cv::v_dotprod_fast, but add a third element to the sum of adjacent pairs. +*/ +template inline v_reg::w_type, n/2> +v_dotprod_fast(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, + const v_reg::w_type, n / 2>& c) +{ return v_dotprod(a, b, c); } + +/** @brief Dot product of elements and expand + +Multiply values in two registers and expand the sum of adjacent result pairs. + +Scheme: +@code + {A1 A2 A3 A4 ...} // 8-bit +x {B1 B2 B3 B4 ...} // 8-bit +------------- + {A1B1+A2B2+A3B3+A4B4 ...} // 32-bit + +@endcode +*/ +template inline v_reg::q_type, n/4> +v_dotprod_expand(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ + typedef typename V_TypeTraits<_Tp>::q_type q_type; + v_reg s; + for( int i = 0; i < (n/4); i++ ) + s.s[i] = (q_type)a.s[i*4 ]*b.s[i*4 ] + (q_type)a.s[i*4 + 1]*b.s[i*4 + 1] + + (q_type)a.s[i*4 + 2]*b.s[i*4 + 2] + (q_type)a.s[i*4 + 3]*b.s[i*4 + 3]; + return s; +} + +/** @brief Dot product of elements + +Same as cv::v_dotprod_expand, but add a third element to the sum of adjacent pairs. +Scheme: +@code + {A1 A2 A3 A4 ...} // 8-bit +x {B1 B2 B3 B4 ...} // 8-bit +------------- + {A1B1+A2B2+A3B3+A4B4+C1 ...} // 32-bit +@endcode +*/ +template inline v_reg::q_type, n/4> +v_dotprod_expand(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, + const v_reg::q_type, n / 4>& c) +{ + typedef typename V_TypeTraits<_Tp>::q_type q_type; + v_reg s; + for( int i = 0; i < (n/4); i++ ) + s.s[i] = (q_type)a.s[i*4 ]*b.s[i*4 ] + (q_type)a.s[i*4 + 1]*b.s[i*4 + 1] + + (q_type)a.s[i*4 + 2]*b.s[i*4 + 2] + (q_type)a.s[i*4 + 3]*b.s[i*4 + 3] + c.s[i]; + return s; +} + +/** @brief Fast Dot product of elements and expand + +Multiply values in two registers and expand the sum of adjacent result pairs. + +Same as cv::v_dotprod_expand, but it may perform unorder sum between result pairs in some platforms, +this intrinsic can be used if the sum among all lanes is only matters +and also it should be yielding better performance on the affected platforms. + +*/ +template inline v_reg::q_type, n/4> +v_dotprod_expand_fast(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ return v_dotprod_expand(a, b); } + +/** @brief Fast Dot product of elements + +Same as cv::v_dotprod_expand_fast, but add a third element to the sum of adjacent pairs. +*/ +template inline v_reg::q_type, n/4> +v_dotprod_expand_fast(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, + const v_reg::q_type, n / 4>& c) +{ return v_dotprod_expand(a, b, c); } + +/** @brief Multiply and expand + +Multiply values two registers and store results in two registers with wider pack type. +Scheme: +@code + {A B C D} // 32-bit +x {E F G H} // 32-bit +--------------- +{AE BF} // 64-bit + {CG DH} // 64-bit +@endcode +Example: +@code{.cpp} +v_uint32x4 a, b; // {1,2,3,4} and {2,2,2,2} +v_uint64x2 c, d; // results +v_mul_expand(a, b, c, d); // c, d = {2,4}, {6, 8} +@endcode +Implemented only for 16- and unsigned 32-bit source types (v_int16x8, v_uint16x8, v_uint32x4). +*/ +template inline void v_mul_expand(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, + v_reg::w_type, n/2>& c, + v_reg::w_type, n/2>& d) +{ + typedef typename V_TypeTraits<_Tp>::w_type w_type; + for( int i = 0; i < (n/2); i++ ) + { + c.s[i] = (w_type)a.s[i]*b.s[i]; + d.s[i] = (w_type)a.s[i+(n/2)]*b.s[i+(n/2)]; + } +} + +/** @brief Multiply and extract high part + +Multiply values two registers and store high part of the results. +Implemented only for 16-bit source types (v_int16x8, v_uint16x8). Returns \f$ a*b >> 16 \f$ +*/ +template inline v_reg<_Tp, n> v_mul_hi(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ + typedef typename V_TypeTraits<_Tp>::w_type w_type; + v_reg<_Tp, n> c; + for (int i = 0; i < n; i++) + c.s[i] = (_Tp)(((w_type)a.s[i] * b.s[i]) >> sizeof(_Tp)*8); + return c; +} + +//! @cond IGNORED +template inline void v_hsum(const v_reg<_Tp, n>& a, + v_reg::w_type, n/2>& c) +{ + typedef typename V_TypeTraits<_Tp>::w_type w_type; + for( int i = 0; i < (n/2); i++ ) + { + c.s[i] = (w_type)a.s[i*2] + a.s[i*2+1]; + } +} +//! @endcond + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_SHIFT_OP(shift_op, func) \ +template inline v_reg<_Tp, n> func(const v_reg<_Tp, n>& a, int imm) \ +{ \ + v_reg<_Tp, n> c; \ + for( int i = 0; i < n; i++ ) \ + c.s[i] = (_Tp)(a.s[i] shift_op imm); \ + return c; \ +} + +/** @brief Bitwise shift left + +For 16-, 32- and 64-bit integer values. */ +OPENCV_HAL_IMPL_SHIFT_OP(<<, v_shl) + +/** @brief Bitwise shift right + +For 16-, 32- and 64-bit integer values. */ +OPENCV_HAL_IMPL_SHIFT_OP(>>, v_shr) + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_ROTATE_SHIFT_OP(suffix,opA,opB) \ +template inline v_reg<_Tp, n> v_rotate_##suffix(const v_reg<_Tp, n>& a) \ +{ \ + v_reg<_Tp, n> b; \ + for (int i = 0; i < n; i++) \ + { \ + int sIndex = i opA imm; \ + if (0 <= sIndex && sIndex < n) \ + { \ + b.s[i] = a.s[sIndex]; \ + } \ + else \ + { \ + b.s[i] = 0; \ + } \ + } \ + return b; \ +} \ +template inline v_reg<_Tp, n> v_rotate_##suffix(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ +{ \ + v_reg<_Tp, n> c; \ + for (int i = 0; i < n; i++) \ + { \ + int aIndex = i opA imm; \ + int bIndex = i opA imm opB n; \ + if (0 <= bIndex && bIndex < n) \ + { \ + c.s[i] = b.s[bIndex]; \ + } \ + else if (0 <= aIndex && aIndex < n) \ + { \ + c.s[i] = a.s[aIndex]; \ + } \ + else \ + { \ + c.s[i] = 0; \ + } \ + } \ + return c; \ +} + +/** @brief Element shift left among vector + +For all type */ +OPENCV_HAL_IMPL_ROTATE_SHIFT_OP(left, -, +) + +/** @brief Element shift right among vector + +For all type */ +OPENCV_HAL_IMPL_ROTATE_SHIFT_OP(right, +, -) + +/** @brief Sum packed values + +Scheme: +@code +{A1 A2 A3 ...} => sum{A1,A2,A3,...} +@endcode +*/ +template inline typename V_TypeTraits<_Tp>::sum_type v_reduce_sum(const v_reg<_Tp, n>& a) +{ + typename V_TypeTraits<_Tp>::sum_type c = a.s[0]; + for( int i = 1; i < n; i++ ) + c += a.s[i]; + return c; +} + +/** @brief Sums all elements of each input vector, returns the vector of sums + + Scheme: + @code + result[0] = a[0] + a[1] + a[2] + a[3] + result[1] = b[0] + b[1] + b[2] + b[3] + result[2] = c[0] + c[1] + c[2] + c[3] + result[3] = d[0] + d[1] + d[2] + d[3] + @endcode +*/ +template inline v_reg v_reduce_sum4(const v_reg& a, const v_reg& b, + const v_reg& c, const v_reg& d) +{ + v_reg r; + for(int i = 0; i < (n/4); i++) + { + r.s[i*4 + 0] = a.s[i*4 + 0] + a.s[i*4 + 1] + a.s[i*4 + 2] + a.s[i*4 + 3]; + r.s[i*4 + 1] = b.s[i*4 + 0] + b.s[i*4 + 1] + b.s[i*4 + 2] + b.s[i*4 + 3]; + r.s[i*4 + 2] = c.s[i*4 + 0] + c.s[i*4 + 1] + c.s[i*4 + 2] + c.s[i*4 + 3]; + r.s[i*4 + 3] = d.s[i*4 + 0] + d.s[i*4 + 1] + d.s[i*4 + 2] + d.s[i*4 + 3]; + } + return r; +} + +/** @brief Sum absolute differences of values + +Scheme: +@code +{A1 A2 A3 ...} {B1 B2 B3 ...} => sum{ABS(A1-B1),abs(A2-B2),abs(A3-B3),...} +@endcode +For all types except 64-bit types.*/ +template inline typename V_TypeTraits< typename V_TypeTraits<_Tp>::abs_type >::sum_type v_reduce_sad(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ + typename V_TypeTraits< typename V_TypeTraits<_Tp>::abs_type >::sum_type c = _absdiff(a.s[0], b.s[0]); + for (int i = 1; i < n; i++) + c += _absdiff(a.s[i], b.s[i]); + return c; +} + +/** @brief Get negative values mask +@deprecated v_signmask depends on a lane count heavily and therefore isn't universal enough + +Returned value is a bit mask with bits set to 1 on places corresponding to negative packed values indexes. +Example: +@code{.cpp} +v_int32x4 r; // set to {-1, -1, 1, 1} +int mask = v_signmask(r); // mask = 3 <== 00000000 00000000 00000000 00000011 +@endcode +*/ +template inline int v_signmask(const v_reg<_Tp, n>& a) +{ + int mask = 0; + for( int i = 0; i < n; i++ ) + mask |= (V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) < 0) << i; + return mask; +} + +/** @brief Get first negative lane index + +Returned value is an index of first negative lane (undefined for input of all positive values) +Example: +@code{.cpp} +v_int32x4 r; // set to {0, 0, -1, -1} +int idx = v_heading_zeros(r); // idx = 2 +@endcode +*/ +template inline int v_scan_forward(const v_reg<_Tp, n>& a) +{ + for (int i = 0; i < n; i++) + if(V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) < 0) + return i; + return 0; +} + +/** @brief Check if all packed values are less than zero + +Unsigned values will be casted to signed: `uchar 254 => char -2`. +*/ +template inline bool v_check_all(const v_reg<_Tp, n>& a) +{ + for( int i = 0; i < n; i++ ) + if( V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) >= 0 ) + return false; + return true; +} + +/** @brief Check if any of packed values is less than zero + +Unsigned values will be casted to signed: `uchar 254 => char -2`. +*/ +template inline bool v_check_any(const v_reg<_Tp, n>& a) +{ + for( int i = 0; i < n; i++ ) + if( V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) < 0 ) + return true; + return false; +} + +/** @brief Per-element select (blend operation) + +Return value will be built by combining values _a_ and _b_ using the following scheme: + result[i] = mask[i] ? a[i] : b[i]; + +@note: _mask_ element values are restricted to these values: +- 0: select element from _b_ +- 0xff/0xffff/etc: select element from _a_ +(fully compatible with bitwise-based operator) +*/ +template inline v_reg<_Tp, n> v_select(const v_reg<_Tp, n>& mask, + const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ + typedef V_TypeTraits<_Tp> Traits; + typedef typename Traits::int_type int_type; + v_reg<_Tp, n> c; + for( int i = 0; i < n; i++ ) + { + int_type m = Traits::reinterpret_int(mask.s[i]); + CV_DbgAssert(m == 0 || m == (~(int_type)0)); // restrict mask values: 0 or 0xff/0xffff/etc + c.s[i] = m ? a.s[i] : b.s[i]; + } + return c; +} + +/** @brief Expand values to the wider pack type + +Copy contents of register to two registers with 2x wider pack type. +Scheme: +@code + int32x4 int64x2 int64x2 +{A B C D} ==> {A B} , {C D} +@endcode */ +template inline void v_expand(const v_reg<_Tp, n>& a, + v_reg::w_type, n/2>& b0, + v_reg::w_type, n/2>& b1) +{ + for( int i = 0; i < (n/2); i++ ) + { + b0.s[i] = a.s[i]; + b1.s[i] = a.s[i+(n/2)]; + } +} + +/** @brief Expand lower values to the wider pack type + +Same as cv::v_expand, but return lower half of the vector. + +Scheme: +@code + int32x4 int64x2 +{A B C D} ==> {A B} +@endcode */ +template +inline v_reg::w_type, n/2> +v_expand_low(const v_reg<_Tp, n>& a) +{ + v_reg::w_type, n/2> b; + for( int i = 0; i < (n/2); i++ ) + b.s[i] = a.s[i]; + return b; +} + +/** @brief Expand higher values to the wider pack type + +Same as cv::v_expand_low, but expand higher half of the vector instead. + +Scheme: +@code + int32x4 int64x2 +{A B C D} ==> {C D} +@endcode */ +template +inline v_reg::w_type, n/2> +v_expand_high(const v_reg<_Tp, n>& a) +{ + v_reg::w_type, n/2> b; + for( int i = 0; i < (n/2); i++ ) + b.s[i] = a.s[i+(n/2)]; + return b; +} + +//! @cond IGNORED +template inline v_reg::int_type, n> + v_reinterpret_as_int(const v_reg<_Tp, n>& a) +{ + v_reg::int_type, n> c; + for( int i = 0; i < n; i++ ) + c.s[i] = V_TypeTraits<_Tp>::reinterpret_int(a.s[i]); + return c; +} + +template inline v_reg::uint_type, n> + v_reinterpret_as_uint(const v_reg<_Tp, n>& a) +{ + v_reg::uint_type, n> c; + for( int i = 0; i < n; i++ ) + c.s[i] = V_TypeTraits<_Tp>::reinterpret_uint(a.s[i]); + return c; +} +//! @endcond + +/** @brief Interleave two vectors + +Scheme: +@code + {A1 A2 A3 A4} + {B1 B2 B3 B4} +--------------- + {A1 B1 A2 B2} and {A3 B3 A4 B4} +@endcode +For all types except 64-bit. +*/ +template inline void v_zip( const v_reg<_Tp, n>& a0, const v_reg<_Tp, n>& a1, + v_reg<_Tp, n>& b0, v_reg<_Tp, n>& b1 ) +{ + int i; + for( i = 0; i < n/2; i++ ) + { + b0.s[i*2] = a0.s[i]; + b0.s[i*2+1] = a1.s[i]; + } + for( ; i < n; i++ ) + { + b1.s[i*2-n] = a0.s[i]; + b1.s[i*2-n+1] = a1.s[i]; + } +} + +/** @brief Load register contents from memory + +@param ptr pointer to memory block with data +@return register object + +@note Returned type will be detected from passed pointer type, for example uchar ==> cv::v_uint8x16, int ==> cv::v_int32x4, etc. + +@note Use vx_load version to get maximum available register length result + +@note Alignment requirement: +if CV_STRONG_ALIGNMENT=1 then passed pointer must be aligned (`sizeof(lane type)` should be enough). +Do not cast pointer types without runtime check for pointer alignment (like `uchar*` => `int*`). + */ +template +inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_load(const _Tp* ptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + return v_reg<_Tp, simd128_width / sizeof(_Tp)>(ptr); +} + +#if CV_SIMD256 +/** @brief Load 256-bit length register contents from memory + +@param ptr pointer to memory block with data +@return register object + +@note Returned type will be detected from passed pointer type, for example uchar ==> cv::v_uint8x32, int ==> cv::v_int32x8, etc. + +@note Check CV_SIMD256 preprocessor definition prior to use. +Use vx_load version to get maximum available register length result + +@note Alignment requirement: +if CV_STRONG_ALIGNMENT=1 then passed pointer must be aligned (`sizeof(lane type)` should be enough). +Do not cast pointer types without runtime check for pointer alignment (like `uchar*` => `int*`). + */ +template +inline v_reg<_Tp, simd256_width / sizeof(_Tp)> v256_load(const _Tp* ptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + return v_reg<_Tp, simd256_width / sizeof(_Tp)>(ptr); +} +#endif + +#if CV_SIMD512 +/** @brief Load 512-bit length register contents from memory + +@param ptr pointer to memory block with data +@return register object + +@note Returned type will be detected from passed pointer type, for example uchar ==> cv::v_uint8x64, int ==> cv::v_int32x16, etc. + +@note Check CV_SIMD512 preprocessor definition prior to use. +Use vx_load version to get maximum available register length result + +@note Alignment requirement: +if CV_STRONG_ALIGNMENT=1 then passed pointer must be aligned (`sizeof(lane type)` should be enough). +Do not cast pointer types without runtime check for pointer alignment (like `uchar*` => `int*`). + */ +template +inline v_reg<_Tp, simd512_width / sizeof(_Tp)> v512_load(const _Tp* ptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + return v_reg<_Tp, simd512_width / sizeof(_Tp)>(ptr); +} +#endif + +/** @brief Load register contents from memory (aligned) + +similar to cv::v_load, but source memory block should be aligned (to 16-byte boundary in case of SIMD128, 32-byte - SIMD256, etc) + +@note Use vx_load_aligned version to get maximum available register length result +*/ +template +inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_load_aligned(const _Tp* ptr) +{ + CV_Assert(isAligned)>(ptr)); + return v_reg<_Tp, simd128_width / sizeof(_Tp)>(ptr); +} + +#if CV_SIMD256 +/** @brief Load register contents from memory (aligned) + +similar to cv::v256_load, but source memory block should be aligned (to 32-byte boundary in case of SIMD256, 64-byte - SIMD512, etc) + +@note Check CV_SIMD256 preprocessor definition prior to use. +Use vx_load_aligned version to get maximum available register length result +*/ +template +inline v_reg<_Tp, simd256_width / sizeof(_Tp)> v256_load_aligned(const _Tp* ptr) +{ + CV_Assert(isAligned)>(ptr)); + return v_reg<_Tp, simd256_width / sizeof(_Tp)>(ptr); +} +#endif + +#if CV_SIMD512 +/** @brief Load register contents from memory (aligned) + +similar to cv::v512_load, but source memory block should be aligned (to 64-byte boundary in case of SIMD512, etc) + +@note Check CV_SIMD512 preprocessor definition prior to use. +Use vx_load_aligned version to get maximum available register length result +*/ +template +inline v_reg<_Tp, simd512_width / sizeof(_Tp)> v512_load_aligned(const _Tp* ptr) +{ + CV_Assert(isAligned)>(ptr)); + return v_reg<_Tp, simd512_width / sizeof(_Tp)>(ptr); +} +#endif + +/** @brief Load 64-bits of data to lower part (high part is undefined). + +@param ptr memory block containing data for first half (0..n/2) + +@code{.cpp} +int lo[2] = { 1, 2 }; +v_int32x4 r = v_load_low(lo); +@endcode + +@note Use vx_load_low version to get maximum available register length result +*/ +template +inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_load_low(const _Tp* ptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + v_reg<_Tp, simd128_width / sizeof(_Tp)> c; + for( int i = 0; i < c.nlanes/2; i++ ) + { + c.s[i] = ptr[i]; + } + return c; +} + +#if CV_SIMD256 +/** @brief Load 128-bits of data to lower part (high part is undefined). + +@param ptr memory block containing data for first half (0..n/2) + +@code{.cpp} +int lo[4] = { 1, 2, 3, 4 }; +v_int32x8 r = v256_load_low(lo); +@endcode + +@note Check CV_SIMD256 preprocessor definition prior to use. +Use vx_load_low version to get maximum available register length result +*/ +template +inline v_reg<_Tp, simd256_width / sizeof(_Tp)> v256_load_low(const _Tp* ptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + v_reg<_Tp, simd256_width / sizeof(_Tp)> c; + for (int i = 0; i < c.nlanes / 2; i++) + { + c.s[i] = ptr[i]; + } + return c; +} +#endif + +#if CV_SIMD512 +/** @brief Load 256-bits of data to lower part (high part is undefined). + +@param ptr memory block containing data for first half (0..n/2) + +@code{.cpp} +int lo[8] = { 1, 2, 3, 4, 5, 6, 7, 8 }; +v_int32x16 r = v512_load_low(lo); +@endcode + +@note Check CV_SIMD512 preprocessor definition prior to use. +Use vx_load_low version to get maximum available register length result +*/ +template +inline v_reg<_Tp, simd512_width / sizeof(_Tp)> v512_load_low(const _Tp* ptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + v_reg<_Tp, simd512_width / sizeof(_Tp)> c; + for (int i = 0; i < c.nlanes / 2; i++) + { + c.s[i] = ptr[i]; + } + return c; +} +#endif + +/** @brief Load register contents from two memory blocks + +@param loptr memory block containing data for first half (0..n/2) +@param hiptr memory block containing data for second half (n/2..n) + +@code{.cpp} +int lo[2] = { 1, 2 }, hi[2] = { 3, 4 }; +v_int32x4 r = v_load_halves(lo, hi); +@endcode + +@note Use vx_load_halves version to get maximum available register length result +*/ +template +inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_load_halves(const _Tp* loptr, const _Tp* hiptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(loptr)); + CV_Assert(isAligned(hiptr)); +#endif + v_reg<_Tp, simd128_width / sizeof(_Tp)> c; + for( int i = 0; i < c.nlanes/2; i++ ) + { + c.s[i] = loptr[i]; + c.s[i+c.nlanes/2] = hiptr[i]; + } + return c; +} + +#if CV_SIMD256 +/** @brief Load register contents from two memory blocks + +@param loptr memory block containing data for first half (0..n/2) +@param hiptr memory block containing data for second half (n/2..n) + +@code{.cpp} +int lo[4] = { 1, 2, 3, 4 }, hi[4] = { 5, 6, 7, 8 }; +v_int32x8 r = v256_load_halves(lo, hi); +@endcode + +@note Check CV_SIMD256 preprocessor definition prior to use. +Use vx_load_halves version to get maximum available register length result +*/ +template +inline v_reg<_Tp, simd256_width / sizeof(_Tp)> v256_load_halves(const _Tp* loptr, const _Tp* hiptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(loptr)); + CV_Assert(isAligned(hiptr)); +#endif + v_reg<_Tp, simd256_width / sizeof(_Tp)> c; + for (int i = 0; i < c.nlanes / 2; i++) + { + c.s[i] = loptr[i]; + c.s[i + c.nlanes / 2] = hiptr[i]; + } + return c; +} +#endif + +#if CV_SIMD512 +/** @brief Load register contents from two memory blocks + +@param loptr memory block containing data for first half (0..n/2) +@param hiptr memory block containing data for second half (n/2..n) + +@code{.cpp} +int lo[4] = { 1, 2, 3, 4, 5, 6, 7, 8 }, hi[4] = { 9, 10, 11, 12, 13, 14, 15, 16 }; +v_int32x16 r = v512_load_halves(lo, hi); +@endcode + +@note Check CV_SIMD512 preprocessor definition prior to use. +Use vx_load_halves version to get maximum available register length result +*/ +template +inline v_reg<_Tp, simd512_width / sizeof(_Tp)> v512_load_halves(const _Tp* loptr, const _Tp* hiptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(loptr)); + CV_Assert(isAligned(hiptr)); +#endif + v_reg<_Tp, simd512_width / sizeof(_Tp)> c; + for (int i = 0; i < c.nlanes / 2; i++) + { + c.s[i] = loptr[i]; + c.s[i + c.nlanes / 2] = hiptr[i]; + } + return c; +} +#endif + +/** @brief Load register contents from memory with double expand + +Same as cv::v_load, but result pack type will be 2x wider than memory type. + +@code{.cpp} +short buf[4] = {1, 2, 3, 4}; // type is int16 +v_int32x4 r = v_load_expand(buf); // r = {1, 2, 3, 4} - type is int32 +@endcode +For 8-, 16-, 32-bit integer source types. + +@note Use vx_load_expand version to get maximum available register length result +*/ +template +inline v_reg::w_type, simd128_width / sizeof(typename V_TypeTraits<_Tp>::w_type)> +v_load_expand(const _Tp* ptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + typedef typename V_TypeTraits<_Tp>::w_type w_type; + v_reg c; + for( int i = 0; i < c.nlanes; i++ ) + { + c.s[i] = ptr[i]; + } + return c; +} + +#if CV_SIMD256 +/** @brief Load register contents from memory with double expand + +Same as cv::v256_load, but result pack type will be 2x wider than memory type. + +@code{.cpp} +short buf[8] = {1, 2, 3, 4, 5, 6, 7, 8}; // type is int16 +v_int32x8 r = v256_load_expand(buf); // r = {1, 2, 3, 4, 5, 6, 7, 8} - type is int32 +@endcode +For 8-, 16-, 32-bit integer source types. + +@note Check CV_SIMD256 preprocessor definition prior to use. +Use vx_load_expand version to get maximum available register length result +*/ +template +inline v_reg::w_type, simd256_width / sizeof(typename V_TypeTraits<_Tp>::w_type)> +v256_load_expand(const _Tp* ptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + typedef typename V_TypeTraits<_Tp>::w_type w_type; + v_reg c; + for (int i = 0; i < c.nlanes; i++) + { + c.s[i] = ptr[i]; + } + return c; +} +#endif + +#if CV_SIMD512 +/** @brief Load register contents from memory with double expand + +Same as cv::v512_load, but result pack type will be 2x wider than memory type. + +@code{.cpp} +short buf[8] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; // type is int16 +v_int32x16 r = v512_load_expand(buf); // r = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16} - type is int32 +@endcode +For 8-, 16-, 32-bit integer source types. + +@note Check CV_SIMD512 preprocessor definition prior to use. +Use vx_load_expand version to get maximum available register length result +*/ +template +inline v_reg::w_type, simd512_width / sizeof(typename V_TypeTraits<_Tp>::w_type)> +v512_load_expand(const _Tp* ptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + typedef typename V_TypeTraits<_Tp>::w_type w_type; + v_reg c; + for (int i = 0; i < c.nlanes; i++) + { + c.s[i] = ptr[i]; + } + return c; +} +#endif + +/** @brief Load register contents from memory with quad expand + +Same as cv::v_load_expand, but result type is 4 times wider than source. +@code{.cpp} +char buf[4] = {1, 2, 3, 4}; // type is int8 +v_int32x4 r = v_load_expand_q(buf); // r = {1, 2, 3, 4} - type is int32 +@endcode +For 8-bit integer source types. + +@note Use vx_load_expand_q version to get maximum available register length result +*/ +template +inline v_reg::q_type, simd128_width / sizeof(typename V_TypeTraits<_Tp>::q_type)> +v_load_expand_q(const _Tp* ptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + typedef typename V_TypeTraits<_Tp>::q_type q_type; + v_reg c; + for( int i = 0; i < c.nlanes; i++ ) + { + c.s[i] = ptr[i]; + } + return c; +} + +#if CV_SIMD256 +/** @brief Load register contents from memory with quad expand + +Same as cv::v256_load_expand, but result type is 4 times wider than source. +@code{.cpp} +char buf[8] = {1, 2, 3, 4, 5, 6, 7, 8}; // type is int8 +v_int32x8 r = v256_load_expand_q(buf); // r = {1, 2, 3, 4, 5, 6, 7, 8} - type is int32 +@endcode +For 8-bit integer source types. + +@note Check CV_SIMD256 preprocessor definition prior to use. +Use vx_load_expand_q version to get maximum available register length result +*/ +template +inline v_reg::q_type, simd256_width / sizeof(typename V_TypeTraits<_Tp>::q_type)> +v256_load_expand_q(const _Tp* ptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + typedef typename V_TypeTraits<_Tp>::q_type q_type; + v_reg c; + for (int i = 0; i < c.nlanes; i++) + { + c.s[i] = ptr[i]; + } + return c; +} +#endif + +#if CV_SIMD512 +/** @brief Load register contents from memory with quad expand + +Same as cv::v512_load_expand, but result type is 4 times wider than source. +@code{.cpp} +char buf[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; // type is int8 +v_int32x16 r = v512_load_expand_q(buf); // r = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16} - type is int32 +@endcode +For 8-bit integer source types. + +@note Check CV_SIMD512 preprocessor definition prior to use. +Use vx_load_expand_q version to get maximum available register length result +*/ +template +inline v_reg::q_type, simd512_width / sizeof(typename V_TypeTraits<_Tp>::q_type)> +v512_load_expand_q(const _Tp* ptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + typedef typename V_TypeTraits<_Tp>::q_type q_type; + v_reg c; + for (int i = 0; i < c.nlanes; i++) + { + c.s[i] = ptr[i]; + } + return c; +} +#endif + +/** @brief Load and deinterleave (2 channels) + +Load data from memory deinterleave and store to 2 registers. +Scheme: +@code +{A1 B1 A2 B2 ...} ==> {A1 A2 ...}, {B1 B2 ...} +@endcode +For all types except 64-bit. */ +template inline void v_load_deinterleave(const _Tp* ptr, v_reg<_Tp, n>& a, + v_reg<_Tp, n>& b) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + int i, i2; + for( i = i2 = 0; i < n; i++, i2 += 2 ) + { + a.s[i] = ptr[i2]; + b.s[i] = ptr[i2+1]; + } +} + +/** @brief Load and deinterleave (3 channels) + +Load data from memory deinterleave and store to 3 registers. +Scheme: +@code +{A1 B1 C1 A2 B2 C2 ...} ==> {A1 A2 ...}, {B1 B2 ...}, {C1 C2 ...} +@endcode +For all types except 64-bit. */ +template inline void v_load_deinterleave(const _Tp* ptr, v_reg<_Tp, n>& a, + v_reg<_Tp, n>& b, v_reg<_Tp, n>& c) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + int i, i3; + for( i = i3 = 0; i < n; i++, i3 += 3 ) + { + a.s[i] = ptr[i3]; + b.s[i] = ptr[i3+1]; + c.s[i] = ptr[i3+2]; + } +} + +/** @brief Load and deinterleave (4 channels) + +Load data from memory deinterleave and store to 4 registers. +Scheme: +@code +{A1 B1 C1 D1 A2 B2 C2 D2 ...} ==> {A1 A2 ...}, {B1 B2 ...}, {C1 C2 ...}, {D1 D2 ...} +@endcode +For all types except 64-bit. */ +template +inline void v_load_deinterleave(const _Tp* ptr, v_reg<_Tp, n>& a, + v_reg<_Tp, n>& b, v_reg<_Tp, n>& c, + v_reg<_Tp, n>& d) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + int i, i4; + for( i = i4 = 0; i < n; i++, i4 += 4 ) + { + a.s[i] = ptr[i4]; + b.s[i] = ptr[i4+1]; + c.s[i] = ptr[i4+2]; + d.s[i] = ptr[i4+3]; + } +} + +/** @brief Interleave and store (2 channels) + +Interleave and store data from 2 registers to memory. +Scheme: +@code +{A1 A2 ...}, {B1 B2 ...} ==> {A1 B1 A2 B2 ...} +@endcode +For all types except 64-bit. */ +template +inline void v_store_interleave( _Tp* ptr, const v_reg<_Tp, n>& a, + const v_reg<_Tp, n>& b, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + int i, i2; + for( i = i2 = 0; i < n; i++, i2 += 2 ) + { + ptr[i2] = a.s[i]; + ptr[i2+1] = b.s[i]; + } +} + +/** @brief Interleave and store (3 channels) + +Interleave and store data from 3 registers to memory. +Scheme: +@code +{A1 A2 ...}, {B1 B2 ...}, {C1 C2 ...} ==> {A1 B1 C1 A2 B2 C2 ...} +@endcode +For all types except 64-bit. */ +template +inline void v_store_interleave( _Tp* ptr, const v_reg<_Tp, n>& a, + const v_reg<_Tp, n>& b, const v_reg<_Tp, n>& c, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + int i, i3; + for( i = i3 = 0; i < n; i++, i3 += 3 ) + { + ptr[i3] = a.s[i]; + ptr[i3+1] = b.s[i]; + ptr[i3+2] = c.s[i]; + } +} + +/** @brief Interleave and store (4 channels) + +Interleave and store data from 4 registers to memory. +Scheme: +@code +{A1 A2 ...}, {B1 B2 ...}, {C1 C2 ...}, {D1 D2 ...} ==> {A1 B1 C1 D1 A2 B2 C2 D2 ...} +@endcode +For all types except 64-bit. */ +template inline void v_store_interleave( _Tp* ptr, const v_reg<_Tp, n>& a, + const v_reg<_Tp, n>& b, const v_reg<_Tp, n>& c, + const v_reg<_Tp, n>& d, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + int i, i4; + for( i = i4 = 0; i < n; i++, i4 += 4 ) + { + ptr[i4] = a.s[i]; + ptr[i4+1] = b.s[i]; + ptr[i4+2] = c.s[i]; + ptr[i4+3] = d.s[i]; + } +} + +/** @brief Store data to memory + +Store register contents to memory. +Scheme: +@code + REG {A B C D} ==> MEM {A B C D} +@endcode +Pointer can be unaligned. */ +template +inline void v_store(_Tp* ptr, const v_reg<_Tp, n>& a) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + for( int i = 0; i < n; i++ ) + ptr[i] = a.s[i]; +} + +template +inline void v_store(_Tp* ptr, const v_reg<_Tp, n>& a, hal::StoreMode /*mode*/) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + v_store(ptr, a); +} + +/** @brief Store data to memory (lower half) + +Store lower half of register contents to memory. +Scheme: +@code + REG {A B C D} ==> MEM {A B} +@endcode */ +template +inline void v_store_low(_Tp* ptr, const v_reg<_Tp, n>& a) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + for( int i = 0; i < (n/2); i++ ) + ptr[i] = a.s[i]; +} + +/** @brief Store data to memory (higher half) + +Store higher half of register contents to memory. +Scheme: +@code + REG {A B C D} ==> MEM {C D} +@endcode */ +template +inline void v_store_high(_Tp* ptr, const v_reg<_Tp, n>& a) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + for( int i = 0; i < (n/2); i++ ) + ptr[i] = a.s[i+(n/2)]; +} + +/** @brief Store data to memory (aligned) + +Store register contents to memory. +Scheme: +@code + REG {A B C D} ==> MEM {A B C D} +@endcode +Pointer __should__ be aligned by 16-byte boundary. */ +template +inline void v_store_aligned(_Tp* ptr, const v_reg<_Tp, n>& a) +{ + CV_Assert(isAligned)>(ptr)); + v_store(ptr, a); +} + +template +inline void v_store_aligned_nocache(_Tp* ptr, const v_reg<_Tp, n>& a) +{ + CV_Assert(isAligned)>(ptr)); + v_store(ptr, a); +} + +template +inline void v_store_aligned(_Tp* ptr, const v_reg<_Tp, n>& a, hal::StoreMode /*mode*/) +{ + CV_Assert(isAligned)>(ptr)); + v_store(ptr, a); +} + +/** @brief Combine vector from first elements of two vectors + +Scheme: +@code + {A1 A2 A3 A4} + {B1 B2 B3 B4} +--------------- + {A1 A2 B1 B2} +@endcode +For all types except 64-bit. */ +template +inline v_reg<_Tp, n> v_combine_low(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ + v_reg<_Tp, n> c; + for( int i = 0; i < (n/2); i++ ) + { + c.s[i] = a.s[i]; + c.s[i+(n/2)] = b.s[i]; + } + return c; +} + +/** @brief Combine vector from last elements of two vectors + +Scheme: +@code + {A1 A2 A3 A4} + {B1 B2 B3 B4} +--------------- + {A3 A4 B3 B4} +@endcode +For all types except 64-bit. */ +template +inline v_reg<_Tp, n> v_combine_high(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ + v_reg<_Tp, n> c; + for( int i = 0; i < (n/2); i++ ) + { + c.s[i] = a.s[i+(n/2)]; + c.s[i+(n/2)] = b.s[i+(n/2)]; + } + return c; +} + +/** @brief Combine two vectors from lower and higher parts of two other vectors + +@code{.cpp} +low = cv::v_combine_low(a, b); +high = cv::v_combine_high(a, b); +@endcode */ +template +inline void v_recombine(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, + v_reg<_Tp, n>& low, v_reg<_Tp, n>& high) +{ + for( int i = 0; i < (n/2); i++ ) + { + low.s[i] = a.s[i]; + low.s[i+(n/2)] = b.s[i]; + high.s[i] = a.s[i+(n/2)]; + high.s[i+(n/2)] = b.s[i+(n/2)]; + } +} + +/** @brief Vector reverse order + +Reverse the order of the vector +Scheme: +@code + REG {A1 ... An} ==> REG {An ... A1} +@endcode +For all types. */ +template +inline v_reg<_Tp, n> v_reverse(const v_reg<_Tp, n>& a) +{ + v_reg<_Tp, n> c; + for( int i = 0; i < n; i++ ) + c.s[i] = a.s[n-i-1]; + return c; +} + +/** @brief Vector extract + +Scheme: +@code + {A1 A2 A3 A4} + {B1 B2 B3 B4} +======================== +shift = 1 {A2 A3 A4 B1} +shift = 2 {A3 A4 B1 B2} +shift = 3 {A4 B1 B2 B3} +@endcode +Restriction: 0 <= shift < nlanes + +Usage: +@code +v_int32x4 a, b, c; +c = v_extract<2>(a, b); +@endcode +For all types. */ +template +inline v_reg<_Tp, n> v_extract(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ + v_reg<_Tp, n> r; + const int shift = n - s; + int i = 0; + for (; i < shift; ++i) + r.s[i] = a.s[i+s]; + for (; i < n; ++i) + r.s[i] = b.s[i-shift]; + return r; +} + +/** @brief Vector extract + +Scheme: +Return the s-th element of v. +Restriction: 0 <= s < nlanes + +Usage: +@code +v_int32x4 a; +int r; +r = v_extract_n<2>(a); +@endcode +For all types. */ +template +inline _Tp v_extract_n(const v_reg<_Tp, n>& v) +{ + CV_DbgAssert(s >= 0 && s < n); + return v.s[s]; +} + +/** @brief Broadcast i-th element of vector + +Scheme: +@code +{ v[0] v[1] v[2] ... v[SZ] } => { v[i], v[i], v[i] ... v[i] } +@endcode +Restriction: 0 <= i < nlanes +Supported types: 32-bit integers and floats (s32/u32/f32) + */ +template +inline v_reg<_Tp, n> v_broadcast_element(const v_reg<_Tp, n>& a) +{ + CV_DbgAssert(i >= 0 && i < n); + return v_reg<_Tp, n>::all(a.s[i]); +} + +/** @brief Round elements + +Rounds each value. Input type is float vector ==> output type is int vector. +@note Only for floating point types. +*/ +template inline v_reg v_round(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + c.s[i] = cvRound(a.s[i]); + return c; +} + +/** @overload */ +template inline v_reg v_round(const v_reg& a, const v_reg& b) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + { + c.s[i] = cvRound(a.s[i]); + c.s[i+n] = cvRound(b.s[i]); + } + return c; +} + +/** @brief Floor elements + +Floor each value. Input type is float vector ==> output type is int vector. +@note Only for floating point types. +*/ +template inline v_reg v_floor(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + c.s[i] = cvFloor(a.s[i]); + return c; +} + +/** @brief Ceil elements + +Ceil each value. Input type is float vector ==> output type is int vector. +@note Only for floating point types. +*/ +template inline v_reg v_ceil(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + c.s[i] = cvCeil(a.s[i]); + return c; +} + +/** @brief Truncate elements + +Truncate each value. Input type is float vector ==> output type is int vector. +@note Only for floating point types. +*/ +template inline v_reg v_trunc(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + c.s[i] = (int)(a.s[i]); + return c; +} + +/** @overload */ +template inline v_reg v_round(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + { + c.s[i] = cvRound(a.s[i]); + c.s[i+n] = 0; + } + return c; +} + +/** @overload */ +template inline v_reg v_floor(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + { + c.s[i] = cvFloor(a.s[i]); + c.s[i+n] = 0; + } + return c; +} + +/** @overload */ +template inline v_reg v_ceil(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + { + c.s[i] = cvCeil(a.s[i]); + c.s[i+n] = 0; + } + return c; +} + +/** @overload */ +template inline v_reg v_trunc(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + { + c.s[i] = (int)(a.s[i]); + c.s[i+n] = 0; + } + return c; +} + +/** @brief Convert to float + +Supported input type is cv::v_int32. */ +template inline v_reg v_cvt_f32(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + c.s[i] = (float)a.s[i]; + return c; +} + +/** @brief Convert lower half to float + +Supported input type is cv::v_float64. */ +template inline v_reg v_cvt_f32(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + { + c.s[i] = (float)a.s[i]; + c.s[i+n] = 0; + } + return c; +} + +/** @brief Convert to float + +Supported input type is cv::v_float64. */ +template inline v_reg v_cvt_f32(const v_reg& a, const v_reg& b) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + { + c.s[i] = (float)a.s[i]; + c.s[i+n] = (float)b.s[i]; + } + return c; +} + +/** @brief Convert lower half to double + +Supported input type is cv::v_int32. */ +template CV_INLINE v_reg v_cvt_f64(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < (n/2); i++ ) + c.s[i] = (double)a.s[i]; + return c; +} + +/** @brief Convert to double high part of vector + +Supported input type is cv::v_int32. */ +template CV_INLINE v_reg v_cvt_f64_high(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < (n/2); i++ ) + c.s[i] = (double)a.s[i + (n/2)]; + return c; +} + +/** @brief Convert lower half to double + +Supported input type is cv::v_float32. */ +template CV_INLINE v_reg v_cvt_f64(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < (n/2); i++ ) + c.s[i] = (double)a.s[i]; + return c; +} + +/** @brief Convert to double high part of vector + +Supported input type is cv::v_float32. */ +template CV_INLINE v_reg v_cvt_f64_high(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < (n/2); i++ ) + c.s[i] = (double)a.s[i + (n/2)]; + return c; +} + +/** @brief Convert to double + +Supported input type is cv::v_int64. */ +template CV_INLINE v_reg v_cvt_f64(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + c.s[i] = (double)a.s[i]; + return c; +} + + +template inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_lut(const _Tp* tab, const int* idx) +{ + v_reg<_Tp, simd128_width / sizeof(_Tp)> c; + for (int i = 0; i < c.nlanes; i++) + c.s[i] = tab[idx[i]]; + return c; +} +template inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_lut_pairs(const _Tp* tab, const int* idx) +{ + v_reg<_Tp, simd128_width / sizeof(_Tp)> c; + for (int i = 0; i < c.nlanes; i++) + c.s[i] = tab[idx[i / 2] + i % 2]; + return c; +} +template inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_lut_quads(const _Tp* tab, const int* idx) +{ + v_reg<_Tp, simd128_width / sizeof(_Tp)> c; + for (int i = 0; i < c.nlanes; i++) + c.s[i] = tab[idx[i / 4] + i % 4]; + return c; +} + +template inline v_reg v_lut(const int* tab, const v_reg& idx) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + c.s[i] = tab[idx.s[i]]; + return c; +} + +template inline v_reg v_lut(const unsigned* tab, const v_reg& idx) +{ + v_reg c; + for (int i = 0; i < n; i++) + c.s[i] = tab[idx.s[i]]; + return c; +} + +template inline v_reg v_lut(const float* tab, const v_reg& idx) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + c.s[i] = tab[idx.s[i]]; + return c; +} + +template inline v_reg v_lut(const double* tab, const v_reg& idx) +{ + v_reg c; + for( int i = 0; i < n/2; i++ ) + c.s[i] = tab[idx.s[i]]; + return c; +} + + +template inline void v_lut_deinterleave(const float* tab, const v_reg& idx, + v_reg& x, v_reg& y) +{ + for( int i = 0; i < n; i++ ) + { + int j = idx.s[i]; + x.s[i] = tab[j]; + y.s[i] = tab[j+1]; + } +} + +template inline void v_lut_deinterleave(const double* tab, const v_reg& idx, + v_reg& x, v_reg& y) +{ + for( int i = 0; i < n; i++ ) + { + int j = idx.s[i]; + x.s[i] = tab[j]; + y.s[i] = tab[j+1]; + } +} + +template inline v_reg<_Tp, n> v_interleave_pairs(const v_reg<_Tp, n>& vec) +{ + v_reg<_Tp, n> c; + for (int i = 0; i < n/4; i++) + { + c.s[4*i ] = vec.s[4*i ]; + c.s[4*i+1] = vec.s[4*i+2]; + c.s[4*i+2] = vec.s[4*i+1]; + c.s[4*i+3] = vec.s[4*i+3]; + } + return c; +} + +template inline v_reg<_Tp, n> v_interleave_quads(const v_reg<_Tp, n>& vec) +{ + v_reg<_Tp, n> c; + for (int i = 0; i < n/8; i++) + { + c.s[8*i ] = vec.s[8*i ]; + c.s[8*i+1] = vec.s[8*i+4]; + c.s[8*i+2] = vec.s[8*i+1]; + c.s[8*i+3] = vec.s[8*i+5]; + c.s[8*i+4] = vec.s[8*i+2]; + c.s[8*i+5] = vec.s[8*i+6]; + c.s[8*i+6] = vec.s[8*i+3]; + c.s[8*i+7] = vec.s[8*i+7]; + } + return c; +} + +template inline v_reg<_Tp, n> v_pack_triplets(const v_reg<_Tp, n>& vec) +{ + v_reg<_Tp, n> c; + for (int i = 0; i < n/4; i++) + { + c.s[3*i ] = vec.s[4*i ]; + c.s[3*i+1] = vec.s[4*i+1]; + c.s[3*i+2] = vec.s[4*i+2]; + } + return c; +} + +/** @brief Transpose 4x4 matrix + +Scheme: +@code +a0 {A1 A2 A3 A4} +a1 {B1 B2 B3 B4} +a2 {C1 C2 C3 C4} +a3 {D1 D2 D3 D4} +=============== +b0 {A1 B1 C1 D1} +b1 {A2 B2 C2 D2} +b2 {A3 B3 C3 D3} +b3 {A4 B4 C4 D4} +@endcode +*/ +template +inline void v_transpose4x4( v_reg<_Tp, n>& a0, const v_reg<_Tp, n>& a1, + const v_reg<_Tp, n>& a2, const v_reg<_Tp, n>& a3, + v_reg<_Tp, n>& b0, v_reg<_Tp, n>& b1, + v_reg<_Tp, n>& b2, v_reg<_Tp, n>& b3 ) +{ + for (int i = 0; i < n / 4; i++) + { + b0.s[0 + i*4] = a0.s[0 + i*4]; b0.s[1 + i*4] = a1.s[0 + i*4]; + b0.s[2 + i*4] = a2.s[0 + i*4]; b0.s[3 + i*4] = a3.s[0 + i*4]; + b1.s[0 + i*4] = a0.s[1 + i*4]; b1.s[1 + i*4] = a1.s[1 + i*4]; + b1.s[2 + i*4] = a2.s[1 + i*4]; b1.s[3 + i*4] = a3.s[1 + i*4]; + b2.s[0 + i*4] = a0.s[2 + i*4]; b2.s[1 + i*4] = a1.s[2 + i*4]; + b2.s[2 + i*4] = a2.s[2 + i*4]; b2.s[3 + i*4] = a3.s[2 + i*4]; + b3.s[0 + i*4] = a0.s[3 + i*4]; b3.s[1 + i*4] = a1.s[3 + i*4]; + b3.s[2 + i*4] = a2.s[3 + i*4]; b3.s[3 + i*4] = a3.s[3 + i*4]; + } +} + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_C_INIT_ZERO(_Tpvec, prefix, suffix) \ +inline _Tpvec prefix##_setzero_##suffix() { return _Tpvec::zero(); } \ +template <> inline _Tpvec v_setzero_() { return _Tpvec::zero(); } + +//! @name Init with zero +//! @{ +//! @brief Create new vector with zero elements +OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint8x16, v, u8) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_int8x16, v, s8) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint16x8, v, u16) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_int16x8, v, s16) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint32x4, v, u32) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_int32x4, v, s32) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_float32x4, v, f32) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_float64x2, v, f64) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint64x2, v, u64) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_int64x2, v, s64) + +#if CV_SIMD256 +OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint8x32, v256, u8) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_int8x32, v256, s8) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint16x16, v256, u16) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_int16x16, v256, s16) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint32x8, v256, u32) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_int32x8, v256, s32) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_float32x8, v256, f32) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_float64x4, v256, f64) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint64x4, v256, u64) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_int64x4, v256, s64) +#endif + +#if CV_SIMD512 +OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint8x64, v512, u8) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_int8x64, v512, s8) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint16x32, v512, u16) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_int16x32, v512, s16) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint32x16, v512, u32) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_int32x16, v512, s32) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_float32x16, v512, f32) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_float64x8, v512, f64) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint64x8, v512, u64) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_int64x8, v512, s64) +#endif +//! @} + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_C_INIT_VAL(_Tpvec, _Tp, prefix, suffix) \ +inline _Tpvec prefix##_setall_##suffix(_Tp val) { return _Tpvec::all(val); } \ +template <> inline _Tpvec v_setall_(_Tp val) { return _Tpvec::all(val); } + +//! @name Init with value +//! @{ +//! @brief Create new vector with elements set to a specific value +OPENCV_HAL_IMPL_C_INIT_VAL(v_uint8x16, uchar, v, u8) +OPENCV_HAL_IMPL_C_INIT_VAL(v_int8x16, schar, v, s8) +OPENCV_HAL_IMPL_C_INIT_VAL(v_uint16x8, ushort, v, u16) +OPENCV_HAL_IMPL_C_INIT_VAL(v_int16x8, short, v, s16) +OPENCV_HAL_IMPL_C_INIT_VAL(v_uint32x4, unsigned, v, u32) +OPENCV_HAL_IMPL_C_INIT_VAL(v_int32x4, int, v, s32) +OPENCV_HAL_IMPL_C_INIT_VAL(v_float32x4, float, v, f32) +OPENCV_HAL_IMPL_C_INIT_VAL(v_float64x2, double, v, f64) +OPENCV_HAL_IMPL_C_INIT_VAL(v_uint64x2, uint64, v, u64) +OPENCV_HAL_IMPL_C_INIT_VAL(v_int64x2, int64, v, s64) + +#if CV_SIMD256 +OPENCV_HAL_IMPL_C_INIT_VAL(v_uint8x32, uchar, v256, u8) +OPENCV_HAL_IMPL_C_INIT_VAL(v_int8x32, schar, v256, s8) +OPENCV_HAL_IMPL_C_INIT_VAL(v_uint16x16, ushort, v256, u16) +OPENCV_HAL_IMPL_C_INIT_VAL(v_int16x16, short, v256, s16) +OPENCV_HAL_IMPL_C_INIT_VAL(v_uint32x8, unsigned, v256, u32) +OPENCV_HAL_IMPL_C_INIT_VAL(v_int32x8, int, v256, s32) +OPENCV_HAL_IMPL_C_INIT_VAL(v_float32x8, float, v256, f32) +OPENCV_HAL_IMPL_C_INIT_VAL(v_float64x4, double, v256, f64) +OPENCV_HAL_IMPL_C_INIT_VAL(v_uint64x4, uint64, v256, u64) +OPENCV_HAL_IMPL_C_INIT_VAL(v_int64x4, int64, v256, s64) +#endif + +#if CV_SIMD512 +OPENCV_HAL_IMPL_C_INIT_VAL(v_uint8x64, uchar, v512, u8) +OPENCV_HAL_IMPL_C_INIT_VAL(v_int8x64, schar, v512, s8) +OPENCV_HAL_IMPL_C_INIT_VAL(v_uint16x32, ushort, v512, u16) +OPENCV_HAL_IMPL_C_INIT_VAL(v_int16x32, short, v512, s16) +OPENCV_HAL_IMPL_C_INIT_VAL(v_uint32x16, unsigned, v512, u32) +OPENCV_HAL_IMPL_C_INIT_VAL(v_int32x16, int, v512, s32) +OPENCV_HAL_IMPL_C_INIT_VAL(v_float32x16, float, v512, f32) +OPENCV_HAL_IMPL_C_INIT_VAL(v_float64x8, double, v512, f64) +OPENCV_HAL_IMPL_C_INIT_VAL(v_uint64x8, uint64, v512, u64) +OPENCV_HAL_IMPL_C_INIT_VAL(v_int64x8, int64, v512, s64) +#endif +//! @} + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_C_REINTERPRET(_Tp, suffix) \ +template inline v_reg<_Tp, n0*sizeof(_Tp0)/sizeof(_Tp)> \ + v_reinterpret_as_##suffix(const v_reg<_Tp0, n0>& a) \ +{ return a.template reinterpret_as<_Tp, n0*sizeof(_Tp0)/sizeof(_Tp)>(); } + +//! @name Reinterpret +//! @{ +//! @brief Convert vector to different type without modifying underlying data. +OPENCV_HAL_IMPL_C_REINTERPRET(uchar, u8) +OPENCV_HAL_IMPL_C_REINTERPRET(schar, s8) +OPENCV_HAL_IMPL_C_REINTERPRET(ushort, u16) +OPENCV_HAL_IMPL_C_REINTERPRET(short, s16) +OPENCV_HAL_IMPL_C_REINTERPRET(unsigned, u32) +OPENCV_HAL_IMPL_C_REINTERPRET(int, s32) +OPENCV_HAL_IMPL_C_REINTERPRET(float, f32) +OPENCV_HAL_IMPL_C_REINTERPRET(double, f64) +OPENCV_HAL_IMPL_C_REINTERPRET(uint64, u64) +OPENCV_HAL_IMPL_C_REINTERPRET(int64, s64) +//! @} + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_C_SHIFTL(_Tp) \ +template inline v_reg<_Tp, n> v_shl(const v_reg<_Tp, n>& a) \ +{ return v_shl(a, shift); } + +//! @name Left shift +//! @{ +//! @brief Shift left +OPENCV_HAL_IMPL_C_SHIFTL(ushort) +OPENCV_HAL_IMPL_C_SHIFTL(short) +OPENCV_HAL_IMPL_C_SHIFTL(unsigned) +OPENCV_HAL_IMPL_C_SHIFTL(int) +OPENCV_HAL_IMPL_C_SHIFTL(uint64) +OPENCV_HAL_IMPL_C_SHIFTL(int64) +//! @} + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_C_SHIFTR(_Tp) \ +template inline v_reg<_Tp, n> v_shr(const v_reg<_Tp, n>& a) \ +{ return v_shr(a, shift); } + +//! @name Right shift +//! @{ +//! @brief Shift right +OPENCV_HAL_IMPL_C_SHIFTR(ushort) +OPENCV_HAL_IMPL_C_SHIFTR(short) +OPENCV_HAL_IMPL_C_SHIFTR(unsigned) +OPENCV_HAL_IMPL_C_SHIFTR(int) +OPENCV_HAL_IMPL_C_SHIFTR(uint64) +OPENCV_HAL_IMPL_C_SHIFTR(int64) +//! @} + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_C_RSHIFTR(_Tp) \ +template inline v_reg<_Tp, n> v_rshr(const v_reg<_Tp, n>& a) \ +{ \ + v_reg<_Tp, n> c; \ + for( int i = 0; i < n; i++ ) \ + c.s[i] = (_Tp)((a.s[i] + ((_Tp)1 << (shift - 1))) >> shift); \ + return c; \ +} + +//! @name Rounding shift +//! @{ +//! @brief Rounding shift right +OPENCV_HAL_IMPL_C_RSHIFTR(ushort) +OPENCV_HAL_IMPL_C_RSHIFTR(short) +OPENCV_HAL_IMPL_C_RSHIFTR(unsigned) +OPENCV_HAL_IMPL_C_RSHIFTR(int) +OPENCV_HAL_IMPL_C_RSHIFTR(uint64) +OPENCV_HAL_IMPL_C_RSHIFTR(int64) +//! @} + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_C_PACK(_Tp, _Tpn, pack_suffix, cast) \ +template inline v_reg<_Tpn, 2*n> v_##pack_suffix(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ +{ \ + v_reg<_Tpn, 2*n> c; \ + for( int i = 0; i < n; i++ ) \ + { \ + c.s[i] = cast<_Tpn>(a.s[i]); \ + c.s[i+n] = cast<_Tpn>(b.s[i]); \ + } \ + return c; \ +} + +//! @name Pack +//! @{ +//! @brief Pack values from two vectors to one +//! +//! Return vector type have twice more elements than input vector types. Variant with _u_ suffix also +//! converts to corresponding unsigned type. +//! +//! - pack: for 16-, 32- and 64-bit integer input types +//! - pack_u: for 16- and 32-bit signed integer input types +//! +//! @note All variants except 64-bit use saturation. +OPENCV_HAL_IMPL_C_PACK(ushort, uchar, pack, saturate_cast) +OPENCV_HAL_IMPL_C_PACK(short, schar, pack, saturate_cast) +OPENCV_HAL_IMPL_C_PACK(unsigned, ushort, pack, saturate_cast) +OPENCV_HAL_IMPL_C_PACK(int, short, pack, saturate_cast) +OPENCV_HAL_IMPL_C_PACK(uint64, unsigned, pack, static_cast) +OPENCV_HAL_IMPL_C_PACK(int64, int, pack, static_cast) +OPENCV_HAL_IMPL_C_PACK(short, uchar, pack_u, saturate_cast) +OPENCV_HAL_IMPL_C_PACK(int, ushort, pack_u, saturate_cast) +//! @} + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_C_RSHR_PACK(_Tp, _Tpn, pack_suffix, cast) \ +template inline v_reg<_Tpn, 2*n> v_rshr_##pack_suffix(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ +{ \ + v_reg<_Tpn, 2*n> c; \ + for( int i = 0; i < n; i++ ) \ + { \ + c.s[i] = cast<_Tpn>((a.s[i] + ((_Tp)1 << (shift - 1))) >> shift); \ + c.s[i+n] = cast<_Tpn>((b.s[i] + ((_Tp)1 << (shift - 1))) >> shift); \ + } \ + return c; \ +} + +//! @name Pack with rounding shift +//! @{ +//! @brief Pack values from two vectors to one with rounding shift +//! +//! Values from the input vectors will be shifted right by _n_ bits with rounding, converted to narrower +//! type and returned in the result vector. Variant with _u_ suffix converts to unsigned type. +//! +//! - pack: for 16-, 32- and 64-bit integer input types +//! - pack_u: for 16- and 32-bit signed integer input types +//! +//! @note All variants except 64-bit use saturation. +OPENCV_HAL_IMPL_C_RSHR_PACK(ushort, uchar, pack, saturate_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK(short, schar, pack, saturate_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK(unsigned, ushort, pack, saturate_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK(int, short, pack, saturate_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK(uint64, unsigned, pack, static_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK(int64, int, pack, static_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK(short, uchar, pack_u, saturate_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK(int, ushort, pack_u, saturate_cast) +//! @} + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_C_PACK_STORE(_Tp, _Tpn, pack_suffix, cast) \ +template inline void v_##pack_suffix##_store(_Tpn* ptr, const v_reg<_Tp, n>& a) \ +{ \ + for( int i = 0; i < n; i++ ) \ + ptr[i] = cast<_Tpn>(a.s[i]); \ +} + +//! @name Pack and store +//! @{ +//! @brief Store values from the input vector into memory with pack +//! +//! Values will be stored into memory with conversion to narrower type. +//! Variant with _u_ suffix converts to corresponding unsigned type. +//! +//! - pack: for 16-, 32- and 64-bit integer input types +//! - pack_u: for 16- and 32-bit signed integer input types +//! +//! @note All variants except 64-bit use saturation. +OPENCV_HAL_IMPL_C_PACK_STORE(ushort, uchar, pack, saturate_cast) +OPENCV_HAL_IMPL_C_PACK_STORE(short, schar, pack, saturate_cast) +OPENCV_HAL_IMPL_C_PACK_STORE(unsigned, ushort, pack, saturate_cast) +OPENCV_HAL_IMPL_C_PACK_STORE(int, short, pack, saturate_cast) +OPENCV_HAL_IMPL_C_PACK_STORE(uint64, unsigned, pack, static_cast) +OPENCV_HAL_IMPL_C_PACK_STORE(int64, int, pack, static_cast) +OPENCV_HAL_IMPL_C_PACK_STORE(short, uchar, pack_u, saturate_cast) +OPENCV_HAL_IMPL_C_PACK_STORE(int, ushort, pack_u, saturate_cast) +//! @} + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(_Tp, _Tpn, pack_suffix, cast) \ +template inline void v_rshr_##pack_suffix##_store(_Tpn* ptr, const v_reg<_Tp, n>& a) \ +{ \ + for( int i = 0; i < n; i++ ) \ + ptr[i] = cast<_Tpn>((a.s[i] + ((_Tp)1 << (shift - 1))) >> shift); \ +} + +//! @name Pack and store with rounding shift +//! @{ +//! @brief Store values from the input vector into memory with pack +//! +//! Values will be shifted _n_ bits right with rounding, converted to narrower type and stored into +//! memory. Variant with _u_ suffix converts to unsigned type. +//! +//! - pack: for 16-, 32- and 64-bit integer input types +//! - pack_u: for 16- and 32-bit signed integer input types +//! +//! @note All variants except 64-bit use saturation. +OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(ushort, uchar, pack, saturate_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(short, schar, pack, saturate_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(unsigned, ushort, pack, saturate_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(int, short, pack, saturate_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(uint64, unsigned, pack, static_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(int64, int, pack, static_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(short, uchar, pack_u, saturate_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(int, ushort, pack_u, saturate_cast) +//! @} + +//! @cond IGNORED +template +inline void _pack_b(_Tpm* mptr, const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ + for (int i = 0; i < n; ++i) + { + mptr[i] = (_Tpm)a.s[i]; + mptr[i + n] = (_Tpm)b.s[i]; + } +} +//! @endcond + +//! @name Pack boolean values +//! @{ +//! @brief Pack boolean values from multiple vectors to one unsigned 8-bit integer vector +//! +//! @note Must provide valid boolean values to guarantee same result for all architectures. + +/** @brief +//! For 16-bit boolean values + +Scheme: +@code +a {0xFFFF 0 0 0xFFFF 0 0xFFFF 0xFFFF 0} +b {0xFFFF 0 0xFFFF 0 0 0xFFFF 0 0xFFFF} +=============== +{ + 0xFF 0 0 0xFF 0 0xFF 0xFF 0 + 0xFF 0 0xFF 0 0 0xFF 0 0xFF +} +@endcode */ + +template inline v_reg v_pack_b(const v_reg& a, const v_reg& b) +{ + v_reg mask; + _pack_b(mask.s, a, b); + return mask; +} + +/** @overload +For 32-bit boolean values + +Scheme: +@code +a {0xFFFF.. 0 0 0xFFFF..} +b {0 0xFFFF.. 0xFFFF.. 0} +c {0xFFFF.. 0 0xFFFF.. 0} +d {0 0xFFFF.. 0 0xFFFF..} +=============== +{ + 0xFF 0 0 0xFF 0 0xFF 0xFF 0 + 0xFF 0 0xFF 0 0 0xFF 0 0xFF +} +@endcode */ + +template inline v_reg v_pack_b(const v_reg& a, const v_reg& b, + const v_reg& c, const v_reg& d) +{ + v_reg mask; + _pack_b(mask.s, a, b); + _pack_b(mask.s + 2*n, c, d); + return mask; +} + +/** @overload +For 64-bit boolean values + +Scheme: +@code +a {0xFFFF.. 0} +b {0 0xFFFF..} +c {0xFFFF.. 0} +d {0 0xFFFF..} + +e {0xFFFF.. 0} +f {0xFFFF.. 0} +g {0 0xFFFF..} +h {0 0xFFFF..} +=============== +{ + 0xFF 0 0 0xFF 0xFF 0 0 0xFF + 0xFF 0 0xFF 0 0 0xFF 0 0xFF +} +@endcode */ +template inline v_reg v_pack_b(const v_reg& a, const v_reg& b, + const v_reg& c, const v_reg& d, + const v_reg& e, const v_reg& f, + const v_reg& g, const v_reg& h) +{ + v_reg mask; + _pack_b(mask.s, a, b); + _pack_b(mask.s + 2*n, c, d); + _pack_b(mask.s + 4*n, e, f); + _pack_b(mask.s + 6*n, g, h); + return mask; +} +//! @} + +/** @brief Matrix multiplication + +Scheme: +@code +{A0 A1 A2 A3} |V0| +{B0 B1 B2 B3} |V1| +{C0 C1 C2 C3} |V2| +{D0 D1 D2 D3} x |V3| +==================== +{R0 R1 R2 R3}, where: +R0 = A0V0 + B0V1 + C0V2 + D0V3, +R1 = A1V0 + B1V1 + C1V2 + D1V3 +... +@endcode +*/ +template +inline v_reg v_matmul(const v_reg& v, + const v_reg& a, const v_reg& b, + const v_reg& c, const v_reg& d) +{ + v_reg res; + for (int i = 0; i < n / 4; i++) + { + res.s[0 + i*4] = v.s[0 + i*4] * a.s[0 + i*4] + v.s[1 + i*4] * b.s[0 + i*4] + v.s[2 + i*4] * c.s[0 + i*4] + v.s[3 + i*4] * d.s[0 + i*4]; + res.s[1 + i*4] = v.s[0 + i*4] * a.s[1 + i*4] + v.s[1 + i*4] * b.s[1 + i*4] + v.s[2 + i*4] * c.s[1 + i*4] + v.s[3 + i*4] * d.s[1 + i*4]; + res.s[2 + i*4] = v.s[0 + i*4] * a.s[2 + i*4] + v.s[1 + i*4] * b.s[2 + i*4] + v.s[2 + i*4] * c.s[2 + i*4] + v.s[3 + i*4] * d.s[2 + i*4]; + res.s[3 + i*4] = v.s[0 + i*4] * a.s[3 + i*4] + v.s[1 + i*4] * b.s[3 + i*4] + v.s[2 + i*4] * c.s[3 + i*4] + v.s[3 + i*4] * d.s[3 + i*4]; + } + return res; +} + +/** @brief Matrix multiplication and add + +Scheme: +@code +{A0 A1 A2 A3} |V0| |D0| +{B0 B1 B2 B3} |V1| |D1| +{C0 C1 C2 C3} x |V2| + |D2| +==================== |D3| +{R0 R1 R2 R3}, where: +R0 = A0V0 + B0V1 + C0V2 + D0, +R1 = A1V0 + B1V1 + C1V2 + D1 +... +@endcode +*/ +template +inline v_reg v_matmuladd(const v_reg& v, + const v_reg& a, const v_reg& b, + const v_reg& c, const v_reg& d) +{ + v_reg res; + for (int i = 0; i < n / 4; i++) + { + res.s[0 + i * 4] = v.s[0 + i * 4] * a.s[0 + i * 4] + v.s[1 + i * 4] * b.s[0 + i * 4] + v.s[2 + i * 4] * c.s[0 + i * 4] + d.s[0 + i * 4]; + res.s[1 + i * 4] = v.s[0 + i * 4] * a.s[1 + i * 4] + v.s[1 + i * 4] * b.s[1 + i * 4] + v.s[2 + i * 4] * c.s[1 + i * 4] + d.s[1 + i * 4]; + res.s[2 + i * 4] = v.s[0 + i * 4] * a.s[2 + i * 4] + v.s[1 + i * 4] * b.s[2 + i * 4] + v.s[2 + i * 4] * c.s[2 + i * 4] + d.s[2 + i * 4]; + res.s[3 + i * 4] = v.s[0 + i * 4] * a.s[3 + i * 4] + v.s[1 + i * 4] * b.s[3 + i * 4] + v.s[2 + i * 4] * c.s[3 + i * 4] + d.s[3 + i * 4]; + } + return res; +} + + +template inline v_reg v_dotprod_expand(const v_reg& a, const v_reg& b) +{ return v_fma(v_cvt_f64(a), v_cvt_f64(b), v_mul(v_cvt_f64_high(a), v_cvt_f64_high(b))); } +template inline v_reg v_dotprod_expand(const v_reg& a, const v_reg& b, + const v_reg& c) +{ return v_fma(v_cvt_f64(a), v_cvt_f64(b), v_fma(v_cvt_f64_high(a), v_cvt_f64_high(b), c)); } + +template inline v_reg v_dotprod_expand_fast(const v_reg& a, const v_reg& b) +{ return v_dotprod_expand(a, b); } +template inline v_reg v_dotprod_expand_fast(const v_reg& a, const v_reg& b, + const v_reg& c) +{ return v_dotprod_expand(a, b, c); } + +////// FP16 support /////// + +inline v_reg +v_load_expand(const hfloat* ptr) +{ + v_reg v; + for( int i = 0; i < v.nlanes; i++ ) + { + v.s[i] = ptr[i]; + } + return v; +} +#if CV_SIMD256 +inline v_reg +v256_load_expand(const hfloat* ptr) +{ + v_reg v; + for (int i = 0; i < v.nlanes; i++) + { + v.s[i] = ptr[i]; + } + return v; +} +#endif +#if CV_SIMD512 +inline v_reg +v512_load_expand(const hfloat* ptr) +{ + v_reg v; + for (int i = 0; i < v.nlanes; i++) + { + v.s[i] = ptr[i]; + } + return v; +} +#endif + +template inline void +v_pack_store(hfloat* ptr, const v_reg& v) +{ + for( int i = 0; i < v.nlanes; i++ ) + { + ptr[i] = hfloat(v.s[i]); + } +} + +inline void v_cleanup() {} +#if CV_SIMD256 +inline void v256_cleanup() {} +#endif +#if CV_SIMD512 +inline void v512_cleanup() {} +#endif + +//! @} + +#ifndef CV_DOXYGEN +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END +#endif +} + +#if !defined(CV_DOXYGEN) +#undef CV_SIMD256 +#undef CV_SIMD512 +#endif + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_forward.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_forward.hpp index 28f67cc9ef..524574c6d8 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_forward.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_forward.hpp @@ -1,191 +1,191 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -#ifndef CV__SIMD_FORWARD -#error "Need to pre-define forward width" -#endif - -namespace cv -{ - -//! @cond IGNORED - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -/** Types **/ -#if CV__SIMD_FORWARD == 1024 -// [todo] 1024 -#error "1024-long ops not implemented yet" -#elif CV__SIMD_FORWARD == 512 -// 512 -#define __CV_VX(fun) v512_##fun -#define __CV_V_UINT8 v_uint8x64 -#define __CV_V_INT8 v_int8x64 -#define __CV_V_UINT16 v_uint16x32 -#define __CV_V_INT16 v_int16x32 -#define __CV_V_UINT32 v_uint32x16 -#define __CV_V_INT32 v_int32x16 -#define __CV_V_UINT64 v_uint64x8 -#define __CV_V_INT64 v_int64x8 -#define __CV_V_FLOAT32 v_float32x16 -#define __CV_V_FLOAT64 v_float64x8 -struct v_uint8x64; -struct v_int8x64; -struct v_uint16x32; -struct v_int16x32; -struct v_uint32x16; -struct v_int32x16; -struct v_uint64x8; -struct v_int64x8; -struct v_float32x16; -struct v_float64x8; -#elif CV__SIMD_FORWARD == 256 -// 256 -#define __CV_VX(fun) v256_##fun -#define __CV_V_UINT8 v_uint8x32 -#define __CV_V_INT8 v_int8x32 -#define __CV_V_UINT16 v_uint16x16 -#define __CV_V_INT16 v_int16x16 -#define __CV_V_UINT32 v_uint32x8 -#define __CV_V_INT32 v_int32x8 -#define __CV_V_UINT64 v_uint64x4 -#define __CV_V_INT64 v_int64x4 -#define __CV_V_FLOAT32 v_float32x8 -#define __CV_V_FLOAT64 v_float64x4 -struct v_uint8x32; -struct v_int8x32; -struct v_uint16x16; -struct v_int16x16; -struct v_uint32x8; -struct v_int32x8; -struct v_uint64x4; -struct v_int64x4; -struct v_float32x8; -struct v_float64x4; -#else -// 128 -#define __CV_VX(fun) v_##fun -#define __CV_V_UINT8 v_uint8x16 -#define __CV_V_INT8 v_int8x16 -#define __CV_V_UINT16 v_uint16x8 -#define __CV_V_INT16 v_int16x8 -#define __CV_V_UINT32 v_uint32x4 -#define __CV_V_INT32 v_int32x4 -#define __CV_V_UINT64 v_uint64x2 -#define __CV_V_INT64 v_int64x2 -#define __CV_V_FLOAT32 v_float32x4 -#define __CV_V_FLOAT64 v_float64x2 -struct v_uint8x16; -struct v_int8x16; -struct v_uint16x8; -struct v_int16x8; -struct v_uint32x4; -struct v_int32x4; -struct v_uint64x2; -struct v_int64x2; -struct v_float32x4; -struct v_float64x2; -#endif - -/** Value reordering **/ - -// Expansion -void v_expand(const __CV_V_UINT8&, __CV_V_UINT16&, __CV_V_UINT16&); -void v_expand(const __CV_V_INT8&, __CV_V_INT16&, __CV_V_INT16&); -void v_expand(const __CV_V_UINT16&, __CV_V_UINT32&, __CV_V_UINT32&); -void v_expand(const __CV_V_INT16&, __CV_V_INT32&, __CV_V_INT32&); -void v_expand(const __CV_V_UINT32&, __CV_V_UINT64&, __CV_V_UINT64&); -void v_expand(const __CV_V_INT32&, __CV_V_INT64&, __CV_V_INT64&); -// Low Expansion -__CV_V_UINT16 v_expand_low(const __CV_V_UINT8&); -__CV_V_INT16 v_expand_low(const __CV_V_INT8&); -__CV_V_UINT32 v_expand_low(const __CV_V_UINT16&); -__CV_V_INT32 v_expand_low(const __CV_V_INT16&); -__CV_V_UINT64 v_expand_low(const __CV_V_UINT32&); -__CV_V_INT64 v_expand_low(const __CV_V_INT32&); -// High Expansion -__CV_V_UINT16 v_expand_high(const __CV_V_UINT8&); -__CV_V_INT16 v_expand_high(const __CV_V_INT8&); -__CV_V_UINT32 v_expand_high(const __CV_V_UINT16&); -__CV_V_INT32 v_expand_high(const __CV_V_INT16&); -__CV_V_UINT64 v_expand_high(const __CV_V_UINT32&); -__CV_V_INT64 v_expand_high(const __CV_V_INT32&); -// Load & Low Expansion -__CV_V_UINT16 __CV_VX(load_expand)(const uchar*); -__CV_V_INT16 __CV_VX(load_expand)(const schar*); -__CV_V_UINT32 __CV_VX(load_expand)(const ushort*); -__CV_V_INT32 __CV_VX(load_expand)(const short*); -__CV_V_UINT64 __CV_VX(load_expand)(const uint*); -__CV_V_INT64 __CV_VX(load_expand)(const int*); -// Load lower 8-bit and expand into 32-bit -__CV_V_UINT32 __CV_VX(load_expand_q)(const uchar*); -__CV_V_INT32 __CV_VX(load_expand_q)(const schar*); - -// Saturating Pack -__CV_V_UINT8 v_pack(const __CV_V_UINT16&, const __CV_V_UINT16&); -__CV_V_INT8 v_pack(const __CV_V_INT16&, const __CV_V_INT16&); -__CV_V_UINT16 v_pack(const __CV_V_UINT32&, const __CV_V_UINT32&); -__CV_V_INT16 v_pack(const __CV_V_INT32&, const __CV_V_INT32&); -// Non-saturating Pack -__CV_V_UINT32 v_pack(const __CV_V_UINT64&, const __CV_V_UINT64&); -__CV_V_INT32 v_pack(const __CV_V_INT64&, const __CV_V_INT64&); -// Pack signed integers with unsigned saturation -__CV_V_UINT8 v_pack_u(const __CV_V_INT16&, const __CV_V_INT16&); -__CV_V_UINT16 v_pack_u(const __CV_V_INT32&, const __CV_V_INT32&); - -/** Arithmetic, bitwise and comparison operations **/ - -// Non-saturating multiply -#if CV_VSX -template -Tvec v_mul_wrap(const Tvec& a, const Tvec& b); -#else -__CV_V_UINT8 v_mul_wrap(const __CV_V_UINT8&, const __CV_V_UINT8&); -__CV_V_INT8 v_mul_wrap(const __CV_V_INT8&, const __CV_V_INT8&); -__CV_V_UINT16 v_mul_wrap(const __CV_V_UINT16&, const __CV_V_UINT16&); -__CV_V_INT16 v_mul_wrap(const __CV_V_INT16&, const __CV_V_INT16&); -#endif - -// Multiply and expand -#if CV_VSX -template -void v_mul_expand(const Tvec& a, const Tvec& b, Twvec& c, Twvec& d); -#else -void v_mul_expand(const __CV_V_UINT8&, const __CV_V_UINT8&, __CV_V_UINT16&, __CV_V_UINT16&); -void v_mul_expand(const __CV_V_INT8&, const __CV_V_INT8&, __CV_V_INT16&, __CV_V_INT16&); -void v_mul_expand(const __CV_V_UINT16&, const __CV_V_UINT16&, __CV_V_UINT32&, __CV_V_UINT32&); -void v_mul_expand(const __CV_V_INT16&, const __CV_V_INT16&, __CV_V_INT32&, __CV_V_INT32&); -void v_mul_expand(const __CV_V_UINT32&, const __CV_V_UINT32&, __CV_V_UINT64&, __CV_V_UINT64&); -void v_mul_expand(const __CV_V_INT32&, const __CV_V_INT32&, __CV_V_INT64&, __CV_V_INT64&); -#endif - -// Conversions -__CV_V_FLOAT32 v_cvt_f32(const __CV_V_INT32& a); -__CV_V_FLOAT32 v_cvt_f32(const __CV_V_FLOAT64& a); -__CV_V_FLOAT32 v_cvt_f32(const __CV_V_FLOAT64& a, const __CV_V_FLOAT64& b); -__CV_V_FLOAT64 v_cvt_f64(const __CV_V_INT32& a); -__CV_V_FLOAT64 v_cvt_f64_high(const __CV_V_INT32& a); -__CV_V_FLOAT64 v_cvt_f64(const __CV_V_FLOAT32& a); -__CV_V_FLOAT64 v_cvt_f64_high(const __CV_V_FLOAT32& a); -__CV_V_FLOAT64 v_cvt_f64(const __CV_V_INT64& a); - -/** Cleanup **/ -#undef CV__SIMD_FORWARD -#undef __CV_VX -#undef __CV_V_UINT8 -#undef __CV_V_INT8 -#undef __CV_V_UINT16 -#undef __CV_V_INT16 -#undef __CV_V_UINT32 -#undef __CV_V_INT32 -#undef __CV_V_UINT64 -#undef __CV_V_INT64 -#undef __CV_V_FLOAT32 -#undef __CV_V_FLOAT64 - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} // cv:: +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +#ifndef CV__SIMD_FORWARD +#error "Need to pre-define forward width" +#endif + +namespace cv +{ + +//! @cond IGNORED + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +/** Types **/ +#if CV__SIMD_FORWARD == 1024 +// [todo] 1024 +#error "1024-long ops not implemented yet" +#elif CV__SIMD_FORWARD == 512 +// 512 +#define __CV_VX(fun) v512_##fun +#define __CV_V_UINT8 v_uint8x64 +#define __CV_V_INT8 v_int8x64 +#define __CV_V_UINT16 v_uint16x32 +#define __CV_V_INT16 v_int16x32 +#define __CV_V_UINT32 v_uint32x16 +#define __CV_V_INT32 v_int32x16 +#define __CV_V_UINT64 v_uint64x8 +#define __CV_V_INT64 v_int64x8 +#define __CV_V_FLOAT32 v_float32x16 +#define __CV_V_FLOAT64 v_float64x8 +struct v_uint8x64; +struct v_int8x64; +struct v_uint16x32; +struct v_int16x32; +struct v_uint32x16; +struct v_int32x16; +struct v_uint64x8; +struct v_int64x8; +struct v_float32x16; +struct v_float64x8; +#elif CV__SIMD_FORWARD == 256 +// 256 +#define __CV_VX(fun) v256_##fun +#define __CV_V_UINT8 v_uint8x32 +#define __CV_V_INT8 v_int8x32 +#define __CV_V_UINT16 v_uint16x16 +#define __CV_V_INT16 v_int16x16 +#define __CV_V_UINT32 v_uint32x8 +#define __CV_V_INT32 v_int32x8 +#define __CV_V_UINT64 v_uint64x4 +#define __CV_V_INT64 v_int64x4 +#define __CV_V_FLOAT32 v_float32x8 +#define __CV_V_FLOAT64 v_float64x4 +struct v_uint8x32; +struct v_int8x32; +struct v_uint16x16; +struct v_int16x16; +struct v_uint32x8; +struct v_int32x8; +struct v_uint64x4; +struct v_int64x4; +struct v_float32x8; +struct v_float64x4; +#else +// 128 +#define __CV_VX(fun) v_##fun +#define __CV_V_UINT8 v_uint8x16 +#define __CV_V_INT8 v_int8x16 +#define __CV_V_UINT16 v_uint16x8 +#define __CV_V_INT16 v_int16x8 +#define __CV_V_UINT32 v_uint32x4 +#define __CV_V_INT32 v_int32x4 +#define __CV_V_UINT64 v_uint64x2 +#define __CV_V_INT64 v_int64x2 +#define __CV_V_FLOAT32 v_float32x4 +#define __CV_V_FLOAT64 v_float64x2 +struct v_uint8x16; +struct v_int8x16; +struct v_uint16x8; +struct v_int16x8; +struct v_uint32x4; +struct v_int32x4; +struct v_uint64x2; +struct v_int64x2; +struct v_float32x4; +struct v_float64x2; +#endif + +/** Value reordering **/ + +// Expansion +void v_expand(const __CV_V_UINT8&, __CV_V_UINT16&, __CV_V_UINT16&); +void v_expand(const __CV_V_INT8&, __CV_V_INT16&, __CV_V_INT16&); +void v_expand(const __CV_V_UINT16&, __CV_V_UINT32&, __CV_V_UINT32&); +void v_expand(const __CV_V_INT16&, __CV_V_INT32&, __CV_V_INT32&); +void v_expand(const __CV_V_UINT32&, __CV_V_UINT64&, __CV_V_UINT64&); +void v_expand(const __CV_V_INT32&, __CV_V_INT64&, __CV_V_INT64&); +// Low Expansion +__CV_V_UINT16 v_expand_low(const __CV_V_UINT8&); +__CV_V_INT16 v_expand_low(const __CV_V_INT8&); +__CV_V_UINT32 v_expand_low(const __CV_V_UINT16&); +__CV_V_INT32 v_expand_low(const __CV_V_INT16&); +__CV_V_UINT64 v_expand_low(const __CV_V_UINT32&); +__CV_V_INT64 v_expand_low(const __CV_V_INT32&); +// High Expansion +__CV_V_UINT16 v_expand_high(const __CV_V_UINT8&); +__CV_V_INT16 v_expand_high(const __CV_V_INT8&); +__CV_V_UINT32 v_expand_high(const __CV_V_UINT16&); +__CV_V_INT32 v_expand_high(const __CV_V_INT16&); +__CV_V_UINT64 v_expand_high(const __CV_V_UINT32&); +__CV_V_INT64 v_expand_high(const __CV_V_INT32&); +// Load & Low Expansion +__CV_V_UINT16 __CV_VX(load_expand)(const uchar*); +__CV_V_INT16 __CV_VX(load_expand)(const schar*); +__CV_V_UINT32 __CV_VX(load_expand)(const ushort*); +__CV_V_INT32 __CV_VX(load_expand)(const short*); +__CV_V_UINT64 __CV_VX(load_expand)(const uint*); +__CV_V_INT64 __CV_VX(load_expand)(const int*); +// Load lower 8-bit and expand into 32-bit +__CV_V_UINT32 __CV_VX(load_expand_q)(const uchar*); +__CV_V_INT32 __CV_VX(load_expand_q)(const schar*); + +// Saturating Pack +__CV_V_UINT8 v_pack(const __CV_V_UINT16&, const __CV_V_UINT16&); +__CV_V_INT8 v_pack(const __CV_V_INT16&, const __CV_V_INT16&); +__CV_V_UINT16 v_pack(const __CV_V_UINT32&, const __CV_V_UINT32&); +__CV_V_INT16 v_pack(const __CV_V_INT32&, const __CV_V_INT32&); +// Non-saturating Pack +__CV_V_UINT32 v_pack(const __CV_V_UINT64&, const __CV_V_UINT64&); +__CV_V_INT32 v_pack(const __CV_V_INT64&, const __CV_V_INT64&); +// Pack signed integers with unsigned saturation +__CV_V_UINT8 v_pack_u(const __CV_V_INT16&, const __CV_V_INT16&); +__CV_V_UINT16 v_pack_u(const __CV_V_INT32&, const __CV_V_INT32&); + +/** Arithmetic, bitwise and comparison operations **/ + +// Non-saturating multiply +#if CV_VSX +template +Tvec v_mul_wrap(const Tvec& a, const Tvec& b); +#else +__CV_V_UINT8 v_mul_wrap(const __CV_V_UINT8&, const __CV_V_UINT8&); +__CV_V_INT8 v_mul_wrap(const __CV_V_INT8&, const __CV_V_INT8&); +__CV_V_UINT16 v_mul_wrap(const __CV_V_UINT16&, const __CV_V_UINT16&); +__CV_V_INT16 v_mul_wrap(const __CV_V_INT16&, const __CV_V_INT16&); +#endif + +// Multiply and expand +#if CV_VSX +template +void v_mul_expand(const Tvec& a, const Tvec& b, Twvec& c, Twvec& d); +#else +void v_mul_expand(const __CV_V_UINT8&, const __CV_V_UINT8&, __CV_V_UINT16&, __CV_V_UINT16&); +void v_mul_expand(const __CV_V_INT8&, const __CV_V_INT8&, __CV_V_INT16&, __CV_V_INT16&); +void v_mul_expand(const __CV_V_UINT16&, const __CV_V_UINT16&, __CV_V_UINT32&, __CV_V_UINT32&); +void v_mul_expand(const __CV_V_INT16&, const __CV_V_INT16&, __CV_V_INT32&, __CV_V_INT32&); +void v_mul_expand(const __CV_V_UINT32&, const __CV_V_UINT32&, __CV_V_UINT64&, __CV_V_UINT64&); +void v_mul_expand(const __CV_V_INT32&, const __CV_V_INT32&, __CV_V_INT64&, __CV_V_INT64&); +#endif + +// Conversions +__CV_V_FLOAT32 v_cvt_f32(const __CV_V_INT32& a); +__CV_V_FLOAT32 v_cvt_f32(const __CV_V_FLOAT64& a); +__CV_V_FLOAT32 v_cvt_f32(const __CV_V_FLOAT64& a, const __CV_V_FLOAT64& b); +__CV_V_FLOAT64 v_cvt_f64(const __CV_V_INT32& a); +__CV_V_FLOAT64 v_cvt_f64_high(const __CV_V_INT32& a); +__CV_V_FLOAT64 v_cvt_f64(const __CV_V_FLOAT32& a); +__CV_V_FLOAT64 v_cvt_f64_high(const __CV_V_FLOAT32& a); +__CV_V_FLOAT64 v_cvt_f64(const __CV_V_INT64& a); + +/** Cleanup **/ +#undef CV__SIMD_FORWARD +#undef __CV_VX +#undef __CV_V_UINT8 +#undef __CV_V_INT8 +#undef __CV_V_UINT16 +#undef __CV_V_INT16 +#undef __CV_V_UINT32 +#undef __CV_V_INT32 +#undef __CV_V_UINT64 +#undef __CV_V_INT64 +#undef __CV_V_FLOAT32 +#undef __CV_V_FLOAT64 + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} // cv:: diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_lasx.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_lasx.hpp index 3661b7ef32..6f53a5f9bf 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_lasx.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_lasx.hpp @@ -1,3036 +1,3036 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -#ifndef OPENCV_HAL_INTRIN_LASX_HPP -#define OPENCV_HAL_INTRIN_LASX_HPP - -#include -#include - -#define CV_SIMD256 1 -#define CV_SIMD256_64F 1 -#define CV_SIMD256_FP16 0 - -namespace cv -{ - -//! @cond IGNORED - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -///////// Utils //////////// - -inline __m256i _v256_setr_b(char v0, char v1, char v2, char v3, char v4, char v5, char v6, char v7, char v8, char v9, - char v10, char v11, char v12, char v13, char v14, char v15, char v16, char v17, char v18, char v19, - char v20, char v21, char v22, char v23, char v24, char v25, char v26, char v27, char v28, char v29, - char v30, char v31) -{ - return (__m256i)v32i8{ v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, - v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, - v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, - v30, v31 }; -} - -inline __m256i _v256_set_b(char v0, char v1, char v2, char v3, char v4, char v5, char v6, char v7, char v8, char v9, - char v10, char v11, char v12, char v13, char v14, char v15, char v16, char v17, char v18, char v19, - char v20, char v21, char v22, char v23, char v24, char v25, char v26, char v27, char v28, char v29, - char v30, char v31) -{ - return (__m256i)v32i8{ v31, v30, - v29, v28, v27, v26, v25, v24, v23, v22, v21, v20, - v19, v18, v17, v16, v15, v14, v13, v12, v11, v10, - v9, v8, v7, v6, v5, v4, v3, v2, v1, v0 }; -} - -inline __m256i _v256_setr_h(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7, - short v8, short v9, short v10, short v11, short v12, short v13, short v14, short v15) -{ - return (__m256i)v16i16{ v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; -} - -inline __m256i _v256_setr_w(int v0, int v1, int v2, int v3, int v4, int v5, int v6, int v7) -{ - return (__m256i)v8i32{ v0, v1, v2, v3, v4, v5, v6, v7 }; -} - -inline __m256i _v256_set_w(int v0, int v1, int v2, int v3, int v4, int v5, int v6, int v7) -{ - return (__m256i)v8i32{ v7, v6, v5, v4, v3, v2, v1, v0 }; -} - -inline __m256i _v256_setall_w(int v0) -{ - return (__m256i)v8i32{ v0, v0, v0, v0, v0, v0, v0, v0 }; -} - -inline __m256i _v256_setr_d(int64 v0, int64 v1, int64 v2, int64 v3) -{ - return (__m256i)v4i64{ v0, v1, v2, v3 }; -} - -inline __m256i _v256_set_d(int64 v0, int64 v1, int64 v2, int64 v3) -{ - return (__m256i)v4i64{ v3, v2, v1, v0 }; -} - -inline __m256 _v256_setr_ps(float v0, float v1, float v2, float v3, float v4, float v5, float v6, float v7) -{ - return (__m256)v8f32{ v0, v1, v2, v3, v4, v5, v6, v7 }; -} - -inline __m256 _v256_setall_ps(float f32) -{ - return (__m256)v8f32{ f32, f32, f32, f32, f32, f32, f32, f32 }; -} - -inline __m256d _v256_setr_pd(double v0, double v1, double v2, double v3) -{ - return (__m256d)v4f64{ v0, v1, v2, v3 }; -} - -inline __m256d _v256_setall_pd(double f64) -{ - return (__m256d)v4f64{ f64, f64, f64, f64 }; -} - -inline __m256i _lasx_packus_h(const __m256i& a, const __m256i& b) -{ - return __lasx_xvssrarni_bu_h(b, a, 0); -} - -inline __m256i _lasx_packs_h(const __m256i& a, const __m256i& b) -{ - return __lasx_xvssrarni_b_h(b, a, 0); -} - -inline __m256i _lasx_packus_w(const __m256i& a, const __m256i& b) -{ - return __lasx_xvssrarni_hu_w(b, a, 0); -} - -inline __m256i _lasx_packs_w(const __m256i& a, const __m256i& b) -{ - return __lasx_xvssrarni_h_w(b, a, 0); -} - -inline __m256i _v256_combine(const __m128i& lo, const __m128i& hi) -{ return __lasx_xvpermi_q(*((__m256i*)&lo), *((__m256i*)&hi), 0x02); } - -inline __m256 _v256_combine(const __m128& lo, const __m128& hi) -{ return __m256(__lasx_xvpermi_q(*((__m256i*)&lo), *((__m256i*)&hi), 0x02)); } - -inline __m256d _v256_combine(const __m128d& lo, const __m128d& hi) -{ return __m256d(__lasx_xvpermi_q(*((__m256i*)&lo), *((__m256i*)&hi), 0x02)); } - -inline __m256i _v256_shuffle_odd_64(const __m256i& v) -{ return __lasx_xvpermi_d(v, 0xd8); } - -inline __m256d _v256_shuffle_odd_64(const __m256d& v) -{ return __m256d(__lasx_xvpermi_d(*((__m256i*)&v), 0xd8)); } - -//LASX: only use for permute WITHOUT zero clearing -template -inline __m256i _v256_permute2x128(const __m256i& a, const __m256i& b) -{ return __lasx_xvpermi_q(a, b, imm); } - -template -inline __m256 _v256_permute2x128(const __m256& a, const __m256& b) -{ return __m256(__lasx_xvpermi_q(*((__m256i*)&a), *((__m256i*)&b), imm)); } - -template -inline __m256d _v256_permute2x128(const __m256d& a, const __m256d& b) -{ return __m256d(__lasx_xvpermi_q(*((__m256i*)&a), *((__m256i*)&b), imm)); } - -template -inline _Tpvec v256_permute2x128(const _Tpvec& a, const _Tpvec& b) -{ return _Tpvec(_v256_permute2x128(a.val, b.val)); } - -template -inline __m256i _v256_permute4x64(const __m256i& a) -{ return __lasx_xvpermi_d(a, imm); } - -template -inline __m256d _v256_permute4x64(const __m256d& a) -{ return __m256d(__lasx_xvpermi_d(*((__m256i*)&a), imm)); } - -template -inline _Tpvec v256_permute4x64(const _Tpvec& a) -{ return _Tpvec(_v256_permute4x64(a.val)); } - -inline __m128i _v256_extract_high(const __m256i& v) -{ __m256i temp256i = __lasx_xvpermi_d(v, 0x4E); - return *((__m128i*)&temp256i); } - -inline __m128 _v256_extract_high(const __m256& v) -{ return __m128(_v256_extract_high(*((__m256i*)&v))); } - -inline __m128d _v256_extract_high(const __m256d& v) -{ return __m128d(_v256_extract_high(*((__m256i*)&v))); } - -inline __m128i _v256_extract_low(const __m256i& v) -{ return *((__m128i*)&v); } - -inline __m128 _v256_extract_low(const __m256& v) -{ return __m128(_v256_extract_low(*((__m256i*)&v))); } - -inline __m128d _v256_extract_low(const __m256d& v) -{ return __m128d(_v256_extract_low(*((__m256i*)&v))); } - -inline __m256i _v256_packs_epu32(const __m256i& a, const __m256i& b) -{ - return __lasx_xvssrlrni_hu_w(b, a, 0); -} - -template -inline int _v256_extract_b(const __m256i& a) -{ - int des[1] = {0}; - __lasx_xvstelm_b(a, des, 0, i); - return des[0]; -} - -template -inline int _v256_extract_h(const __m256i& a) -{ - int des[1] = {0}; - __lasx_xvstelm_h(a, des, 0, i); - return des[0]; -} - -template -inline int _v256_extract_w(const __m256i& a) -{ - return __lasx_xvpickve2gr_w(a, i); -} - -template -inline int64 _v256_extract_d(const __m256i& a) -{ - return __lasx_xvpickve2gr_d(a, i); -} - -///////// Types //////////// - -struct v_uint8x32 -{ - typedef uchar lane_type; - enum { nlanes = 32 }; - __m256i val; - - explicit v_uint8x32(__m256i v) : val(v) {} - v_uint8x32(uchar v0, uchar v1, uchar v2, uchar v3, - uchar v4, uchar v5, uchar v6, uchar v7, - uchar v8, uchar v9, uchar v10, uchar v11, - uchar v12, uchar v13, uchar v14, uchar v15, - uchar v16, uchar v17, uchar v18, uchar v19, - uchar v20, uchar v21, uchar v22, uchar v23, - uchar v24, uchar v25, uchar v26, uchar v27, - uchar v28, uchar v29, uchar v30, uchar v31) - { - val = _v256_setr_b((char)v0, (char)v1, (char)v2, (char)v3, - (char)v4, (char)v5, (char)v6 , (char)v7, (char)v8, (char)v9, - (char)v10, (char)v11, (char)v12, (char)v13, (char)v14, (char)v15, - (char)v16, (char)v17, (char)v18, (char)v19, (char)v20, (char)v21, - (char)v22, (char)v23, (char)v24, (char)v25, (char)v26, (char)v27, - (char)v28, (char)v29, (char)v30, (char)v31); - } - /* coverity[uninit_ctor]: suppress warning */ - v_uint8x32() {} - - uchar get0() const { - uchar des[1] = {0}; - __lasx_xvstelm_b(val, des, 0, 0); - return des[0]; - } -}; - -struct v_int8x32 -{ - typedef schar lane_type; - enum { nlanes = 32 }; - __m256i val; - - explicit v_int8x32(__m256i v) : val(v) {} - v_int8x32(schar v0, schar v1, schar v2, schar v3, - schar v4, schar v5, schar v6, schar v7, - schar v8, schar v9, schar v10, schar v11, - schar v12, schar v13, schar v14, schar v15, - schar v16, schar v17, schar v18, schar v19, - schar v20, schar v21, schar v22, schar v23, - schar v24, schar v25, schar v26, schar v27, - schar v28, schar v29, schar v30, schar v31) - { - val = _v256_setr_b(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, - v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, - v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31); - } - /* coverity[uninit_ctor]: suppress warning */ - v_int8x32() {} - - schar get0() const { - schar des[1] = {0}; - __lasx_xvstelm_b(val, des, 0, 0); - return des[0]; - } -}; - -struct v_uint16x16 -{ - typedef ushort lane_type; - enum { nlanes = 16 }; - __m256i val; - - explicit v_uint16x16(__m256i v) : val(v) {} - v_uint16x16(ushort v0, ushort v1, ushort v2, ushort v3, - ushort v4, ushort v5, ushort v6, ushort v7, - ushort v8, ushort v9, ushort v10, ushort v11, - ushort v12, ushort v13, ushort v14, ushort v15) - { - val = _v256_setr_h((short)v0, (short)v1, (short)v2, (short)v3, - (short)v4, (short)v5, (short)v6, (short)v7, (short)v8, (short)v9, - (short)v10, (short)v11, (short)v12, (short)v13, (short)v14, (short)v15); - } - /* coverity[uninit_ctor]: suppress warning */ - v_uint16x16() {} - - ushort get0() const { - ushort des[1] = {0}; - __lasx_xvstelm_h(val, des, 0, 0); - return des[0]; - } -}; - -struct v_int16x16 -{ - typedef short lane_type; - enum { nlanes = 16 }; - __m256i val; - - explicit v_int16x16(__m256i v) : val(v) {} - v_int16x16(short v0, short v1, short v2, short v3, - short v4, short v5, short v6, short v7, - short v8, short v9, short v10, short v11, - short v12, short v13, short v14, short v15) - { - val = _v256_setr_h(v0, v1, v2, v3, v4, v5, v6, v7, - v8, v9, v10, v11, v12, v13, v14, v15); - } - /* coverity[uninit_ctor]: suppress warning */ - v_int16x16() {} - - short get0() const { - short des[1] = {0}; - __lasx_xvstelm_h(val, des, 0, 0); - return des[0]; - } -}; - -struct v_uint32x8 -{ - typedef unsigned lane_type; - enum { nlanes = 8 }; - __m256i val; - - explicit v_uint32x8(__m256i v) : val(v) {} - v_uint32x8(unsigned v0, unsigned v1, unsigned v2, unsigned v3, - unsigned v4, unsigned v5, unsigned v6, unsigned v7) - { - val = _v256_setr_w((unsigned)v0, (unsigned)v1, (unsigned)v2, - (unsigned)v3, (unsigned)v4, (unsigned)v5, (unsigned)v6, (unsigned)v7); - } - /* coverity[uninit_ctor]: suppress warning */ - v_uint32x8() {} - - unsigned get0() const { return __lasx_xvpickve2gr_wu(val, 0); } -}; - -struct v_int32x8 -{ - typedef int lane_type; - enum { nlanes = 8 }; - __m256i val; - - explicit v_int32x8(__m256i v) : val(v) {} - v_int32x8(int v0, int v1, int v2, int v3, - int v4, int v5, int v6, int v7) - { - val = _v256_setr_w(v0, v1, v2, v3, v4, v5, v6, v7); - } - /* coverity[uninit_ctor]: suppress warning */ - v_int32x8() {} - - int get0() const { return __lasx_xvpickve2gr_w(val, 0); } -}; - -struct v_float32x8 -{ - typedef float lane_type; - enum { nlanes = 8 }; - __m256 val; - - explicit v_float32x8(__m256 v) : val(v) {} - explicit v_float32x8(__m256i v) { val = *((__m256*)&v); } - v_float32x8(float v0, float v1, float v2, float v3, - float v4, float v5, float v6, float v7) - { - val = _v256_setr_ps(v0, v1, v2, v3, v4, v5, v6, v7); - } - /* coverity[uninit_ctor]: suppress warning */ - v_float32x8() {} - - float get0() const { - float des[1] = {0}; - __lasx_xvstelm_w(*((__m256i*)&val), des, 0, 0); - return des[0]; - } - - int get0toint() const { - int des[1] = {0}; - __lasx_xvstelm_w(*((__m256i*)&val), des, 0, 0); - return des[0]; - } -}; - -struct v_uint64x4 -{ - typedef uint64 lane_type; - enum { nlanes = 4 }; - __m256i val; - - explicit v_uint64x4(__m256i v) : val(v) {} - v_uint64x4(uint64 v0, uint64 v1, uint64 v2, uint64 v3) - { val = _v256_setr_d((int64)v0, (int64)v1, (int64)v2, (int64)v3); } - /* coverity[uninit_ctor]: suppress warning */ - v_uint64x4() {} - - uint64 get0() const - { - return __lasx_xvpickve2gr_du(val, 0); - } -}; - -struct v_int64x4 -{ - typedef int64 lane_type; - enum { nlanes = 4 }; - __m256i val; - - explicit v_int64x4(__m256i v) : val(v) {} - v_int64x4(int64 v0, int64 v1, int64 v2, int64 v3) - { val = _v256_setr_d(v0, v1, v2, v3); } - /* coverity[uninit_ctor]: suppress warning */ - v_int64x4() {} - - int64 get0() const - { - return __lasx_xvpickve2gr_d(val, 0); - } -}; - -struct v_float64x4 -{ - typedef double lane_type; - enum { nlanes = 4 }; - __m256d val; - - explicit v_float64x4(__m256d v) : val(v) {} - explicit v_float64x4(__m256i v) { val = *((__m256d*)&v); } - v_float64x4(double v0, double v1, double v2, double v3) - { val = _v256_setr_pd(v0, v1, v2, v3); } - /* coverity[uninit_ctor]: suppress warning */ - v_float64x4() {} - - double get0() const { - double des[1] = {0}; - __lasx_xvstelm_d(*((__m256i*)&val), des, 0, 0); - return des[0]; - } - - int64 get0toint64() const { - int64 des[1] = {0}; - __lasx_xvstelm_d(*((__m256i*)&val), des, 0, 0); - return des[0]; - } -}; - -//////////////// Load and store operations /////////////// - -#define OPENCV_HAL_IMPL_LASX_LOADSTORE(_Tpvec, _Tp) \ - inline _Tpvec v256_load(const _Tp* ptr) \ - { return _Tpvec(__lasx_xvld(ptr, 0)); } \ - inline _Tpvec v256_load_aligned(const _Tp* ptr) \ - { return _Tpvec(__lasx_xvld(ptr, 0)); } \ - inline _Tpvec v256_load_low(const _Tp* ptr) \ - { \ - __m128i v128 = __lsx_vld(ptr, 0); \ - return _Tpvec(*((__m256i*)&v128)); \ - } \ - inline _Tpvec v256_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ - { \ - __m128i vlo = __lsx_vld(ptr0, 0); \ - __m128i vhi = __lsx_vld(ptr1, 0); \ - return _Tpvec(_v256_combine(vlo, vhi)); \ - } \ - inline void v_store(_Tp* ptr, const _Tpvec& a) \ - { __lasx_xvst(a.val, ptr, 0); } \ - inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ - { __lasx_xvst(a.val, ptr, 0); } \ - inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ - { __lasx_xvst(a.val, ptr, 0); } \ - inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ - { \ - if( mode == hal::STORE_UNALIGNED ) \ - __lasx_xvst(a.val, ptr, 0); \ - else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ - __lasx_xvst(a.val, ptr, 0); \ - else \ - __lasx_xvst(a.val, ptr, 0); \ - } \ - inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vst(_v256_extract_low(a.val), ptr, 0); } \ - inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vst(_v256_extract_high(a.val), ptr, 0); } - -OPENCV_HAL_IMPL_LASX_LOADSTORE(v_uint8x32, uchar) -OPENCV_HAL_IMPL_LASX_LOADSTORE(v_int8x32, schar) -OPENCV_HAL_IMPL_LASX_LOADSTORE(v_uint16x16, ushort) -OPENCV_HAL_IMPL_LASX_LOADSTORE(v_int16x16, short) -OPENCV_HAL_IMPL_LASX_LOADSTORE(v_uint32x8, unsigned) -OPENCV_HAL_IMPL_LASX_LOADSTORE(v_int32x8, int) -OPENCV_HAL_IMPL_LASX_LOADSTORE(v_uint64x4, uint64) -OPENCV_HAL_IMPL_LASX_LOADSTORE(v_int64x4, int64) - - -#define OPENCV_HAL_IMPL_LASX_LOADSTORE_FLT(_Tpvec, _Tp, halfreg) \ - inline _Tpvec v256_load(const _Tp* ptr) \ - { return _Tpvec(__lasx_xvld(ptr, 0)); } \ - inline _Tpvec v256_load_aligned(const _Tp* ptr) \ - { return _Tpvec(__lasx_xvld(ptr, 0)); } \ - inline _Tpvec v256_load_low(const _Tp* ptr) \ - { \ - __m128i v128 = __lsx_vld(ptr, 0); \ - return _Tpvec(*((__m256i*)&v128)); \ - } \ - inline _Tpvec v256_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ - { \ - halfreg vlo = __lsx_vld(ptr0, 0); \ - halfreg vhi = __lsx_vld(ptr1, 0); \ - return _Tpvec(_v256_combine(vlo, vhi)); \ - } \ - inline void v_store(_Tp* ptr, const _Tpvec& a) \ - { __lasx_xvst(a.val, ptr, 0); } \ - inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ - { __lasx_xvst(a.val, ptr, 0); } \ - inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ - { __lasx_xvst(a.val, ptr, 0); } \ - inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ - { \ - if( mode == hal::STORE_UNALIGNED ) \ - __lasx_xvst(a.val, ptr, 0); \ - else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ - __lasx_xvst(a.val, ptr, 0); \ - else \ - __lasx_xvst(a.val, ptr, 0); \ - } \ - inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vst(_v256_extract_low(a.val), ptr, 0); } \ - inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vst(_v256_extract_high(a.val), ptr, 0); } - -OPENCV_HAL_IMPL_LASX_LOADSTORE_FLT(v_float32x8, float, __m128i) -OPENCV_HAL_IMPL_LASX_LOADSTORE_FLT(v_float64x4, double, __m128i) - - -inline __m256i _lasx_256_castps_si256(const __m256& v) -{ return __m256i(v); } - -inline __m256i _lasx_256_castpd_si256(const __m256d& v) -{ return __m256i(v); } - -#define OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, _Tpvecf, suffix, cast) \ - inline _Tpvec v_reinterpret_as_##suffix(const _Tpvecf& a) \ - { return _Tpvec(cast(a.val)); } - -#define OPENCV_HAL_IMPL_LASX_INIT(_Tpvec, _Tp, suffix, ssuffix, ctype_s) \ - inline _Tpvec v256_setzero_##suffix() \ - { return _Tpvec(__lasx_xvreplgr2vr_d(0)); } \ - inline _Tpvec v256_setall_##suffix(_Tp v) \ - { return _Tpvec(__lasx_xvreplgr2vr_##ssuffix((ctype_s)v)); } \ - template <> inline _Tpvec v_setzero_() \ - { return v256_setzero_##suffix(); } \ - template <> inline _Tpvec v_setall_(_Tp v) \ - { return v256_setall_##suffix(v); } \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint8x32, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int8x32, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint16x16, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int16x16, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint32x8, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int32x8, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint64x4, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int64x4, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_float32x8, suffix, _lasx_256_castps_si256) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_float64x4, suffix, _lasx_256_castpd_si256) - -OPENCV_HAL_IMPL_LASX_INIT(v_uint8x32, uchar, u8, b, int) -OPENCV_HAL_IMPL_LASX_INIT(v_int8x32, schar, s8, b, int) -OPENCV_HAL_IMPL_LASX_INIT(v_uint16x16, ushort, u16, h, int) -OPENCV_HAL_IMPL_LASX_INIT(v_int16x16, short, s16, h, int) -OPENCV_HAL_IMPL_LASX_INIT(v_uint32x8, unsigned, u32, w, int) -OPENCV_HAL_IMPL_LASX_INIT(v_int32x8, int, s32, w, int) -OPENCV_HAL_IMPL_LASX_INIT(v_uint64x4, uint64, u64, d, long int) -OPENCV_HAL_IMPL_LASX_INIT(v_int64x4, int64, s64, d, long int) - - -inline __m256 _lasx_256_castsi256_ps(const __m256i &v) -{ return __m256(v); } - -inline __m256d _lasx_256_castsi256_pd(const __m256i &v) -{ return __m256d(v); } - -#define OPENCV_HAL_IMPL_LASX_INIT_FLT(_Tpvec, _Tp, suffix, zsuffix, cast) \ - inline _Tpvec v256_setzero_##suffix() \ - { return _Tpvec(__lasx_xvreplgr2vr_d(0)); } \ - inline _Tpvec v256_setall_##suffix(_Tp v) \ - { return _Tpvec(_v256_setall_##zsuffix(v)); } \ - template <> inline _Tpvec v_setzero_() \ - { return v256_setzero_##suffix(); } \ - template <> inline _Tpvec v_setall_(_Tp v) \ - { return v256_setall_##suffix(v); } \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint8x32, suffix, cast) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int8x32, suffix, cast) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint16x16, suffix, cast) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int16x16, suffix, cast) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint32x8, suffix, cast) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int32x8, suffix, cast) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint64x4, suffix, cast) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int64x4, suffix, cast) - -OPENCV_HAL_IMPL_LASX_INIT_FLT(v_float32x8, float, f32, ps, _lasx_256_castsi256_ps) -OPENCV_HAL_IMPL_LASX_INIT_FLT(v_float64x4, double, f64, pd, _lasx_256_castsi256_pd) - -inline v_float32x8 v_reinterpret_as_f32(const v_float32x8& a) -{ return a; } -inline v_float32x8 v_reinterpret_as_f32(const v_float64x4& a) -{ return v_float32x8(_lasx_256_castps_si256(__m256(a.val))); } - -inline v_float64x4 v_reinterpret_as_f64(const v_float64x4& a) -{ return a; } -inline v_float64x4 v_reinterpret_as_f64(const v_float32x8& a) -{ return v_float64x4(_lasx_256_castpd_si256(__m256d(a.val))); } - - -//////////////// Variant Value reordering /////////////// - -// unpacks -#define OPENCV_HAL_IMPL_LASX_UNPACK(_Tpvec, suffix) \ - inline _Tpvec v256_unpacklo(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(__lasx_xvilvl_##suffix(__m256i(b.val), __m256i(a.val))); } \ - inline _Tpvec v256_unpackhi(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(__lasx_xvilvh_##suffix(__m256i(b.val), __m256i(a.val))); } - -OPENCV_HAL_IMPL_LASX_UNPACK(v_uint8x32, b) -OPENCV_HAL_IMPL_LASX_UNPACK(v_int8x32, b) -OPENCV_HAL_IMPL_LASX_UNPACK(v_uint16x16, h) -OPENCV_HAL_IMPL_LASX_UNPACK(v_int16x16, h) -OPENCV_HAL_IMPL_LASX_UNPACK(v_uint32x8, w) -OPENCV_HAL_IMPL_LASX_UNPACK(v_int32x8, w) -OPENCV_HAL_IMPL_LASX_UNPACK(v_uint64x4, d) -OPENCV_HAL_IMPL_LASX_UNPACK(v_int64x4, d) -OPENCV_HAL_IMPL_LASX_UNPACK(v_float32x8, w) -OPENCV_HAL_IMPL_LASX_UNPACK(v_float64x4, d) - - -// shuffle -// todo: emulate 64bit -#define OPENCV_HAL_IMPL_LASX_SHUFFLE(_Tpvec, intrin) \ - template \ - inline _Tpvec v256_shuffle(const _Tpvec& a) \ - { return _Tpvec(__lasx_xvshuf4i_##intrin(a.val, m)); } - -OPENCV_HAL_IMPL_LASX_SHUFFLE(v_uint32x8, w) -OPENCV_HAL_IMPL_LASX_SHUFFLE(v_int32x8, w) - -template -inline v_float32x8 v256_shuffle(const v_float32x8 &a) -{ return v_float32x8(__lasx_xvshuf4i_w(*((__m256i*)&a.val), m)); } - -template -inline v_float64x4 v256_shuffle(const v_float64x4 &a) -{ - const int m1 = m & 0b1; - const int m2 = m & 0b10; - const int m3 = m & 0b100; - const int m4 = m & 0b1000; - const int m5 = m2 << 1; - const int m6 = m3 << 2; - const int m7 = m4 << 3; - const int m8 = m1 & m5 & m6 & m7; - - return v_float64x4(__lasx_xvshuf4i_d(*((__m256i*)&a.val), *((__m256i*)&a.val), m8)); -} - -template -inline void v256_zip(const _Tpvec& a, const _Tpvec& b, _Tpvec& ab0, _Tpvec& ab1) -{ - ab0 = v256_unpacklo(a, b); - ab1 = v256_unpackhi(a, b); -} - -template -inline _Tpvec v256_combine_diagonal(const _Tpvec& a, const _Tpvec& b) -{ return _Tpvec(__lasx_xvpermi_q(a.val, b.val, 0x12)); } - -inline v_float32x8 v256_combine_diagonal(const v_float32x8& a, const v_float32x8& b) -{ return v_float32x8(__lasx_xvpermi_q(a.val, b.val, 0x12)); } - -inline v_float64x4 v256_combine_diagonal(const v_float64x4& a, const v_float64x4& b) -{ return v_float64x4(__lasx_xvpermi_q(a.val, b.val, 0x12)); } - -template -inline _Tpvec v256_alignr_128(const _Tpvec& a, const _Tpvec& b) -{ return v256_permute2x128<0x03>(a, b); } - -inline __m256i _v256_alignr_b(const __m256i &a, const __m256i &b, const int imm) -{ - if (imm == 8) { - return __lasx_xvshuf4i_d(b, a, 0x9); // b.d1 a.d0 b.d3 a.d2 - } else { - __m256i byteIndex = _v256_setr_b(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); - return __lasx_xvshuf_b(a, b, __lasx_xvadd_b(__lasx_xvreplgr2vr_b(imm), byteIndex)); - } -} - -template -inline _Tpvec v256_alignr_64(const _Tpvec& a, const _Tpvec& b) -{ return _Tpvec(_v256_alignr_b(a.val, b.val, 8)); } -inline v_float64x4 v256_alignr_64(const v_float64x4& a, const v_float64x4& b) -{ return v_float64x4(__lasx_xvshuf4i_d(b.val, a.val, 0x9)); } // b.d1 a.d0 b.d3 a.d2 -// todo: emulate float32 - -template -inline _Tpvec v256_swap_halves(const _Tpvec& a) -{ return v256_permute2x128<1>(a, a); } - -template -inline _Tpvec v256_reverse_64(const _Tpvec& a) -{ return v256_permute4x64<0x1b>(a); } - - -// ZIP -#define OPENCV_HAL_IMPL_LASX_ZIP(_Tpvec) \ - inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ - { return v256_permute2x128<0x02>(a, b); } \ - inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ - { return v256_permute2x128<0x13>(a, b); } \ - inline void v_recombine(const _Tpvec& a, const _Tpvec& b, \ - _Tpvec& c, _Tpvec& d) \ - { \ - _Tpvec a1b0 = v256_alignr_128(a, b); \ - c = v256_combine_diagonal(a, a1b0); \ - d = v256_combine_diagonal(a1b0, b); \ - } \ - inline void v_zip(const _Tpvec& a, const _Tpvec& b, \ - _Tpvec& ab0, _Tpvec& ab1) \ - { \ - _Tpvec ab0ab2, ab1ab3; \ - v256_zip(a, b, ab0ab2, ab1ab3); \ - v_recombine(ab0ab2, ab1ab3, ab0, ab1); \ - } - -OPENCV_HAL_IMPL_LASX_ZIP(v_uint8x32) -OPENCV_HAL_IMPL_LASX_ZIP(v_int8x32) -OPENCV_HAL_IMPL_LASX_ZIP(v_uint16x16) -OPENCV_HAL_IMPL_LASX_ZIP(v_int16x16) -OPENCV_HAL_IMPL_LASX_ZIP(v_uint32x8) -OPENCV_HAL_IMPL_LASX_ZIP(v_int32x8) -OPENCV_HAL_IMPL_LASX_ZIP(v_uint64x4) -OPENCV_HAL_IMPL_LASX_ZIP(v_int64x4) -OPENCV_HAL_IMPL_LASX_ZIP(v_float32x8) -OPENCV_HAL_IMPL_LASX_ZIP(v_float64x4) - -////////// Arithmetic, bitwise and comparison operations ///////// - -/** Arithmetics **/ -#define OPENCV_HAL_IMPL_LASX_BIN_OP(bin_op, _Tpvec, intrin) \ - inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(intrin(a.val, b.val)); } - -OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_uint8x32, __lasx_xvsadd_bu) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_uint8x32, __lasx_xvssub_bu) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_int8x32, __lasx_xvsadd_b) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_int8x32, __lasx_xvssub_b) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_uint16x16, __lasx_xvsadd_hu) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_uint16x16, __lasx_xvssub_hu) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_int16x16, __lasx_xvsadd_h) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_int16x16, __lasx_xvssub_h) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_uint32x8, __lasx_xvadd_w) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_uint32x8, __lasx_xvsub_w) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_mul, v_uint32x8, __lasx_xvmul_w) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_int32x8, __lasx_xvadd_w) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_int32x8, __lasx_xvsub_w) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_mul, v_int32x8, __lasx_xvmul_w) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_uint64x4, __lasx_xvadd_d) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_uint64x4, __lasx_xvsub_d) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_int64x4, __lasx_xvadd_d) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_int64x4, __lasx_xvsub_d) - -OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_float32x8, __lasx_xvfadd_s) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_float32x8, __lasx_xvfsub_s) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_mul, v_float32x8, __lasx_xvfmul_s) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_div, v_float32x8, __lasx_xvfdiv_s) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_float64x4, __lasx_xvfadd_d) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_float64x4, __lasx_xvfsub_d) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_mul, v_float64x4, __lasx_xvfmul_d) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_div, v_float64x4, __lasx_xvfdiv_d) - -// saturating multiply 8-bit, 16-bit -inline v_uint8x32 v_mul(const v_uint8x32& a, const v_uint8x32& b) -{ - v_uint16x16 c, d; - v_mul_expand(a, b, c, d); - return v_pack(c, d); -} -inline v_int8x32 v_mul(const v_int8x32& a, const v_int8x32& b) -{ - v_int16x16 c, d; - v_mul_expand(a, b, c, d); - return v_pack(c, d); -} -inline v_uint16x16 v_mul(const v_uint16x16& a, const v_uint16x16& b) -{ - __m256i pl = __lasx_xvmul_h(a.val, b.val); - __m256i ph = __lasx_xvmuh_hu(a.val, b.val); - __m256i p0 = __lasx_xvilvl_h(ph, pl); - __m256i p1 = __lasx_xvilvh_h(ph, pl); - return v_uint16x16(_v256_packs_epu32(p0, p1)); -} -inline v_int16x16 v_mul(const v_int16x16& a, const v_int16x16& b) -{ - __m256i pl = __lasx_xvmul_h(a.val, b.val); - __m256i ph = __lasx_xvmuh_h(a.val, b.val); - __m256i p0 = __lasx_xvilvl_h(ph, pl); - __m256i p1 = __lasx_xvilvh_h(ph, pl); - return v_int16x16(_lasx_packs_w(p0, p1)); -} - -/** Non-saturating arithmetics **/ - -#define OPENCV_HAL_IMPL_LASX_BIN_FUNC(func, _Tpvec, intrin) \ - inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(intrin(a.val, b.val)); } - -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_add_wrap, v_uint8x32, __lasx_xvadd_b) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_add_wrap, v_int8x32, __lasx_xvadd_b) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_add_wrap, v_uint16x16, __lasx_xvadd_h) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_add_wrap, v_int16x16, __lasx_xvadd_h) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_sub_wrap, v_uint8x32, __lasx_xvsub_b) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_sub_wrap, v_int8x32, __lasx_xvsub_b) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_sub_wrap, v_uint16x16, __lasx_xvsub_h) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_sub_wrap, v_int16x16, __lasx_xvsub_h) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_mul_wrap, v_uint16x16, __lasx_xvmul_h) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_mul_wrap, v_int16x16, __lasx_xvmul_h) - -inline v_uint8x32 v_mul_wrap(const v_uint8x32& a, const v_uint8x32& b) -{ - __m256i p0 = __lasx_xvmulwev_h_bu(a.val, b.val); - __m256i p1 = __lasx_xvmulwod_h_bu(a.val, b.val); - return v_uint8x32(__lasx_xvpackev_b(p1, p0)); -} - -inline v_int8x32 v_mul_wrap(const v_int8x32& a, const v_int8x32& b) -{ - return v_reinterpret_as_s8(v_mul_wrap(v_reinterpret_as_u8(a), v_reinterpret_as_u8(b))); -} - -// Multiply and expand -inline void v_mul_expand(const v_uint8x32& a, const v_uint8x32& b, - v_uint16x16& c, v_uint16x16& d) -{ - v_uint16x16 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c = v_mul_wrap(a0, b0); - d = v_mul_wrap(a1, b1); -} - -inline void v_mul_expand(const v_int8x32& a, const v_int8x32& b, - v_int16x16& c, v_int16x16& d) -{ - v_int16x16 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c = v_mul_wrap(a0, b0); - d = v_mul_wrap(a1, b1); -} - -inline void v_mul_expand(const v_int16x16& a, const v_int16x16& b, - v_int32x8& c, v_int32x8& d) -{ - v_int16x16 vhi = v_int16x16(__lasx_xvmuh_h(a.val, b.val)); - - v_int16x16 v0, v1; - v_zip(v_mul_wrap(a, b), vhi, v0, v1); - - c = v_reinterpret_as_s32(v0); - d = v_reinterpret_as_s32(v1); -} - -inline void v_mul_expand(const v_uint16x16& a, const v_uint16x16& b, - v_uint32x8& c, v_uint32x8& d) -{ - v_uint16x16 vhi = v_uint16x16(__lasx_xvmuh_hu(a.val, b.val)); - - v_uint16x16 v0, v1; - v_zip(v_mul_wrap(a, b), vhi, v0, v1); - - c = v_reinterpret_as_u32(v0); - d = v_reinterpret_as_u32(v1); -} - -inline void v_mul_expand(const v_uint32x8& a, const v_uint32x8& b, - v_uint64x4& c, v_uint64x4& d) -{ - __m256i v0 = __lasx_xvmulwev_d_wu(a.val, b.val); - __m256i v1 = __lasx_xvmulwod_d_wu(a.val, b.val); - v_zip(v_uint64x4(v0), v_uint64x4(v1), c, d); -} - -inline v_int16x16 v_mul_hi(const v_int16x16& a, const v_int16x16& b) { return v_int16x16(__lasx_xvmuh_h(a.val, b.val)); } -inline v_uint16x16 v_mul_hi(const v_uint16x16& a, const v_uint16x16& b) { return v_uint16x16(__lasx_xvmuh_hu(a.val, b.val)); } - -/** Bitwise shifts **/ -#define OPENCV_HAL_IMPL_LASX_SHIFT_OP(_Tpuvec, _Tpsvec, suffix, srai) \ - inline _Tpuvec v_shl(const _Tpuvec& a, int imm) \ - { return _Tpuvec(__lasx_xvsll_##suffix(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ - inline _Tpsvec v_shl(const _Tpsvec& a, int imm) \ - { return _Tpsvec(__lasx_xvsll_##suffix(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ - inline _Tpuvec v_shr(const _Tpuvec& a, int imm) \ - { return _Tpuvec(__lasx_xvsrl_##suffix(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ - inline _Tpsvec v_shr(const _Tpsvec& a, int imm) \ - { return _Tpsvec(srai(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ - template \ - inline _Tpuvec v_shl(const _Tpuvec& a) \ - { return _Tpuvec(__lasx_xvsll_##suffix(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ - template \ - inline _Tpsvec v_shl(const _Tpsvec& a) \ - { return _Tpsvec(__lasx_xvsll_##suffix(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ - template \ - inline _Tpuvec v_shr(const _Tpuvec& a) \ - { return _Tpuvec(__lasx_xvsrl_##suffix(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ - template \ - inline _Tpsvec v_shr(const _Tpsvec& a) \ - { return _Tpsvec(srai(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } - -OPENCV_HAL_IMPL_LASX_SHIFT_OP(v_uint16x16, v_int16x16, h, __lasx_xvsra_h) -OPENCV_HAL_IMPL_LASX_SHIFT_OP(v_uint32x8, v_int32x8, w, __lasx_xvsra_w) -OPENCV_HAL_IMPL_LASX_SHIFT_OP(v_uint64x4, v_int64x4, d, __lasx_xvsra_d) - - -/** Bitwise logic **/ -#define OPENCV_HAL_IMPL_LASX_LOGIC_OP(_Tpvec, suffix, not_const) \ - OPENCV_HAL_IMPL_LASX_BIN_OP(v_and, _Tpvec, __lasx_xvand_##suffix) \ - OPENCV_HAL_IMPL_LASX_BIN_OP(v_or, _Tpvec, __lasx_xvor_##suffix) \ - OPENCV_HAL_IMPL_LASX_BIN_OP(v_xor, _Tpvec, __lasx_xvxor_##suffix) \ - inline _Tpvec v_not(const _Tpvec& a) \ - { return _Tpvec(__lasx_xvnori_b(a.val, 0)); } - -OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_uint8x32, v, __lasx_xvreplgr2vr_w(-1)) -OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_int8x32, v, __lasx_xvreplgr2vr_w(-1)) -OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_uint16x16, v, __lasx_xvreplgr2vr_w(-1)) -OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_int16x16, v, __lasx_xvreplgr2vr_w(-1)) -OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_uint32x8, v, __lasx_xvreplgr2vr_w(-1)) -OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_int32x8, v, __lasx_xvreplgr2vr_w(-1)) -OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_uint64x4, v, __lasx_xvreplgr2vr_d(-1)) -OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_int64x4, v, __lasx_xvreplgr2vr_d(-1)) - -#define OPENCV_HAL_IMPL_LASX_FLOAT_BIN_OP(bin_op, _Tpvec, intrin, cast) \ - inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(intrin(*((__m256i*)(&a.val)), *((__m256i*)(&b.val)))); } - -#define OPENCV_HAL_IMPL_LASX_FLOAT_LOGIC_OP(_Tpvec, suffix, not_const, cast) \ - OPENCV_HAL_IMPL_LASX_FLOAT_BIN_OP(v_and, _Tpvec, __lasx_xvand_##suffix, cast) \ - OPENCV_HAL_IMPL_LASX_FLOAT_BIN_OP(v_or, _Tpvec, __lasx_xvor_##suffix, cast) \ - OPENCV_HAL_IMPL_LASX_FLOAT_BIN_OP(v_xor, _Tpvec, __lasx_xvxor_##suffix, cast) \ - inline _Tpvec v_not(const _Tpvec& a) \ - { return _Tpvec(__lasx_xvxor_##suffix(*((__m256i*)(&a.val)), not_const)); } - -OPENCV_HAL_IMPL_LASX_FLOAT_LOGIC_OP(v_float32x8, v, __lasx_xvreplgr2vr_w(-1), _lasx_256_castsi256_ps) -OPENCV_HAL_IMPL_LASX_FLOAT_LOGIC_OP(v_float64x4, v, __lasx_xvreplgr2vr_d(-1), _lasx_256_castsi256_pd) - -/** Select **/ -#define OPENCV_HAL_IMPL_LASX_SELECT(_Tpvec) \ - inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(__lasx_xvbitsel_v(b.val, a.val, mask.val)); } - -OPENCV_HAL_IMPL_LASX_SELECT(v_uint8x32) -OPENCV_HAL_IMPL_LASX_SELECT(v_int8x32) -OPENCV_HAL_IMPL_LASX_SELECT(v_uint16x16) -OPENCV_HAL_IMPL_LASX_SELECT(v_int16x16) -OPENCV_HAL_IMPL_LASX_SELECT(v_uint32x8) -OPENCV_HAL_IMPL_LASX_SELECT(v_int32x8) - -inline v_float32x8 v_select(const v_float32x8 &mask, const v_float32x8 &a, const v_float32x8 &b) -{ return v_float32x8(__lasx_xvbitsel_v(*((__m256i*)&b.val), *((__m256i*)&a.val), *((__m256i*)&mask.val))); } - -inline v_float64x4 v_select(const v_float64x4 &mask, const v_float64x4 &a, const v_float64x4 &b) -{ return v_float64x4(__lasx_xvbitsel_v(*((__m256i*)&b.val), *((__m256i*)&a.val), *((__m256i*)&mask.val))); } - -/** Comparison **/ -#define OPENCV_HAL_IMPL_LASX_CMP_OP_OV(_Tpvec) \ - inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ - { return v_not(v_eq(a, b)); } \ - inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ - { return v_gt(b, a); } \ - inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ - { return v_not(v_lt(a, b)); } \ - inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ - { return v_ge(b, a); } - -#define OPENCV_HAL_IMPL_LASX_CMP_OP_INT(_Tpuvec, _Tpsvec, suffix, usuffix) \ - inline _Tpuvec v_eq(const _Tpuvec& a, const _Tpuvec& b) \ - { return _Tpuvec(__lasx_xvseq_##suffix(a.val, b.val)); } \ - inline _Tpuvec v_gt(const _Tpuvec& a, const _Tpuvec& b) \ - { \ - return _Tpuvec(__lasx_xvslt_##usuffix(b.val, a.val)); \ - } \ - inline _Tpsvec v_eq(const _Tpsvec& a, const _Tpsvec& b) \ - { return _Tpsvec(__lasx_xvseq_##suffix(a.val, b.val)); } \ - inline _Tpsvec v_gt(const _Tpsvec& a, const _Tpsvec& b) \ - { return _Tpsvec(__lasx_xvslt_##suffix(b.val, a.val)); } \ - OPENCV_HAL_IMPL_LASX_CMP_OP_OV(_Tpuvec) \ - OPENCV_HAL_IMPL_LASX_CMP_OP_OV(_Tpsvec) - -OPENCV_HAL_IMPL_LASX_CMP_OP_INT(v_uint8x32, v_int8x32, b, bu) -OPENCV_HAL_IMPL_LASX_CMP_OP_INT(v_uint16x16, v_int16x16, h, hu) -OPENCV_HAL_IMPL_LASX_CMP_OP_INT(v_uint32x8, v_int32x8, w, wu) - -#define OPENCV_HAL_IMPL_LASX_CMP_OP_64BIT(_Tpvec, suffix) \ - inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(__lasx_xvseq_##suffix(a.val, b.val)); } \ - inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ - { return v_not(v_eq(a, b)); } - -OPENCV_HAL_IMPL_LASX_CMP_OP_64BIT(v_uint64x4, d) -OPENCV_HAL_IMPL_LASX_CMP_OP_64BIT(v_int64x4, d) - -#define OPENCV_HAL_IMPL_LASX_CMP_FLT(bin_op, suffix, _Tpvec, ssuffix) \ - inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(__lasx_##suffix##_##ssuffix(a.val, b.val)); } - -#define OPENCV_HAL_IMPL_LASX_CMP_OP_FLT(_Tpvec, ssuffix) \ - OPENCV_HAL_IMPL_LASX_CMP_FLT(v_eq, xvfcmp_ceq, _Tpvec, ssuffix) \ - OPENCV_HAL_IMPL_LASX_CMP_FLT(v_ne, xvfcmp_cne, _Tpvec, ssuffix) \ - OPENCV_HAL_IMPL_LASX_CMP_FLT(v_lt, xvfcmp_clt, _Tpvec, ssuffix) \ - OPENCV_HAL_IMPL_LASX_CMP_FLT(v_le, xvfcmp_cle, _Tpvec, ssuffix) - -OPENCV_HAL_IMPL_LASX_CMP_OP_FLT(v_float32x8, s) -OPENCV_HAL_IMPL_LASX_CMP_OP_FLT(v_float64x4, d) - -inline v_float32x8 v_gt(const v_float32x8 &a, const v_float32x8 &b) -{ return v_float32x8(__lasx_xvfcmp_clt_s(b.val, a.val)); } - -inline v_float32x8 v_ge(const v_float32x8 &a, const v_float32x8 &b) -{ return v_float32x8(__lasx_xvfcmp_cle_s(b.val, a.val)); } - -inline v_float64x4 v_gt(const v_float64x4 &a, const v_float64x4 &b) -{ return v_float64x4(__lasx_xvfcmp_clt_d(b.val, a.val)); } - -inline v_float64x4 v_ge(const v_float64x4 &a, const v_float64x4 &b) -{ return v_float64x4(__lasx_xvfcmp_cle_d(b.val, a.val)); } - -inline v_float32x8 v_not_nan(const v_float32x8& a) -{ return v_float32x8(__lasx_xvfcmp_cor_s(a.val, a.val)); } -inline v_float64x4 v_not_nan(const v_float64x4& a) -{ return v_float64x4(__lasx_xvfcmp_cor_d(a.val, a.val)); } - -/** min/max **/ -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_uint8x32, __lasx_xvmin_bu) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_uint8x32, __lasx_xvmax_bu) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_int8x32, __lasx_xvmin_b) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_int8x32, __lasx_xvmax_b) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_uint16x16, __lasx_xvmin_hu) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_uint16x16, __lasx_xvmax_hu) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_int16x16, __lasx_xvmin_h) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_int16x16, __lasx_xvmax_h) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_uint32x8, __lasx_xvmin_wu) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_uint32x8, __lasx_xvmax_wu) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_int32x8, __lasx_xvmin_w) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_int32x8, __lasx_xvmax_w) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_float32x8, __lasx_xvfmin_s) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_float32x8, __lasx_xvfmax_s) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_float64x4, __lasx_xvfmin_d) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_float64x4, __lasx_xvfmax_d) - -/** Rotate **/ -template -inline v_uint8x32 v_rotate_left(const v_uint8x32& a, const v_uint8x32& b) -{ - enum {IMM_R = (16 - imm) & 0xFF}; - enum {IMM_R2 = (32 - imm) & 0xFF}; - - if (imm == 0) return a; - if (imm == 32) return b; - if (imm > 32) return v_uint8x32(); - - __m256i swap = _v256_permute2x128<0x21>(a.val, b.val); - if (imm == 16) return v_uint8x32(swap); - if (imm < 16) return v_uint8x32(_v256_alignr_b(a.val, swap, IMM_R)); - return v_uint8x32(_v256_alignr_b(swap, b.val, IMM_R2)); // imm < 32 -} - -template -inline v_uint8x32 v_rotate_right(const v_uint8x32& a, const v_uint8x32& b) -{ - enum {IMM_L = (imm - 16) & 0xFF}; - - if (imm == 0) return a; - if (imm == 32) return b; - if (imm > 32) return v_uint8x32(); - - __m256i swap = _v256_permute2x128<0x03>(a.val, b.val); - if (imm == 16) return v_uint8x32(swap); - if (imm < 16) return v_uint8x32(_v256_alignr_b(swap, a.val, imm)); - return v_uint8x32(_v256_alignr_b(b.val, swap, IMM_L)); -} - -template -inline v_uint8x32 v_rotate_left(const v_uint8x32& a) -{ - enum {IMM_L = ((imm - 16) & 0xFF) > 31 ? 31 : ((imm - 16) & 0xFF)}; - enum {IMM_R = (16 - imm) & 0xFF}; - - if (imm == 0) return a; - if (imm > 32) return v_uint8x32(); - - // ESAC control[3] ? [127:0] = 0 - __m256i vzero = __lasx_xvreplgr2vr_w(0); - __m256i swapz = __lasx_xvpermi_q(a.val, vzero, 0x20);; - if (imm == 16) return v_uint8x32(swapz); - if (imm < 16) return v_uint8x32(_v256_alignr_b(a.val, swapz, IMM_R)); - return v_uint8x32(__lasx_xvbsll_v(swapz, IMM_L)); -} - -template -inline v_uint8x32 v_rotate_right(const v_uint8x32& a) -{ - enum {IMM_L = ((imm - 16) & 0xFF) > 31 ? 31 : ((imm - 16) & 0xFF)}; - - if (imm == 0) return a; - if (imm > 32) return v_uint8x32(); - - // ESAC control[3] ? [127:0] = 0 - __m256i vzero = __lasx_xvreplgr2vr_w(0); - __m256i swapz = __lasx_xvpermi_q(vzero, a.val, 0x21);; - if (imm == 16) return v_uint8x32(swapz); - if (imm < 16) return v_uint8x32(_v256_alignr_b(swapz, a.val, imm)); - return v_uint8x32(__lasx_xvbsrl_v(swapz, IMM_L)); -} - -#define OPENCV_HAL_IMPL_LASX_ROTATE_CAST(intrin, _Tpvec, cast) \ - template \ - inline _Tpvec intrin(const _Tpvec& a, const _Tpvec& b) \ - { \ - enum {IMMxW = imm * sizeof(typename _Tpvec::lane_type)}; \ - v_uint8x32 ret = intrin(v_reinterpret_as_u8(a), \ - v_reinterpret_as_u8(b)); \ - return _Tpvec(cast(ret.val)); \ - } \ - template \ - inline _Tpvec intrin(const _Tpvec& a) \ - { \ - enum {IMMxW = imm * sizeof(typename _Tpvec::lane_type)}; \ - v_uint8x32 ret = intrin(v_reinterpret_as_u8(a)); \ - return _Tpvec(cast(ret.val)); \ - } - -#define OPENCV_HAL_IMPL_LASX_ROTATE(_Tpvec) \ - OPENCV_HAL_IMPL_LASX_ROTATE_CAST(v_rotate_left, _Tpvec, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LASX_ROTATE_CAST(v_rotate_right, _Tpvec, OPENCV_HAL_NOP) - -OPENCV_HAL_IMPL_LASX_ROTATE(v_int8x32) -OPENCV_HAL_IMPL_LASX_ROTATE(v_uint16x16) -OPENCV_HAL_IMPL_LASX_ROTATE(v_int16x16) -OPENCV_HAL_IMPL_LASX_ROTATE(v_uint32x8) -OPENCV_HAL_IMPL_LASX_ROTATE(v_int32x8) -OPENCV_HAL_IMPL_LASX_ROTATE(v_uint64x4) -OPENCV_HAL_IMPL_LASX_ROTATE(v_int64x4) - -OPENCV_HAL_IMPL_LASX_ROTATE_CAST(v_rotate_left, v_float32x8, _lasx_256_castsi256_ps) -OPENCV_HAL_IMPL_LASX_ROTATE_CAST(v_rotate_right, v_float32x8, _lasx_256_castsi256_ps) -OPENCV_HAL_IMPL_LASX_ROTATE_CAST(v_rotate_left, v_float64x4, _lasx_256_castsi256_pd) -OPENCV_HAL_IMPL_LASX_ROTATE_CAST(v_rotate_right, v_float64x4, _lasx_256_castsi256_pd) - -/** Reverse **/ -inline v_uint8x32 v_reverse(const v_uint8x32 &a) -{ - static const __m256i perm = _v256_setr_b( - 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, - 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); - __m256i vec = __lasx_xvshuf_b(a.val, a.val, perm); - return v_uint8x32(__lasx_xvpermi_q(vec, vec, 1)); -} - -inline v_int8x32 v_reverse(const v_int8x32 &a) -{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } - -inline v_uint16x16 v_reverse(const v_uint16x16 &a) -{ - __m256i vec = __lasx_xvshuf4i_h(a.val, 0x1B); - vec = __lasx_xvshuf4i_w(vec, 0x4E); - return v_uint16x16(__lasx_xvpermi_d(vec, 0x4E)); -} - -inline v_int16x16 v_reverse(const v_int16x16 &a) -{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } - -inline v_uint32x8 v_reverse(const v_uint32x8 &a) -{ - __m256i vec = __lasx_xvshuf4i_w(a.val, 0x1B); - return v_uint32x8(__lasx_xvpermi_d(vec, 0x4E)); -} - -inline v_int32x8 v_reverse(const v_int32x8 &a) -{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_float32x8 v_reverse(const v_float32x8 &a) -{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_uint64x4 v_reverse(const v_uint64x4 &a) -{ - return v_uint64x4(__lasx_xvpermi_d(a.val, 0x1b)); -} - -inline v_int64x4 v_reverse(const v_int64x4 &a) -{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } - -inline v_float64x4 v_reverse(const v_float64x4 &a) -{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } - -////////// Reduce and mask ///////// - -/** Reduce **/ -// this function is return a[0]+a[1]+...+a[31] -inline unsigned v_reduce_sum(const v_uint8x32& a) -{ - __m256i t1 = __lasx_xvhaddw_hu_bu(a.val, a.val); - __m256i t2 = __lasx_xvhaddw_wu_hu(t1, t1); - __m256i t3 = __lasx_xvhaddw_du_wu(t2, t2); - __m256i t4 = __lasx_xvhaddw_qu_du(t3, t3); - return (unsigned)(((v8u32)t4)[0]+((v8u32)t4)[4]); -} - -inline int v_reduce_sum(const v_int8x32& a) -{ - __m256i t1 = __lasx_xvhaddw_h_b(a.val, a.val); - __m256i t2 = __lasx_xvhaddw_w_h(t1, t1); - __m256i t3 = __lasx_xvhaddw_d_w(t2, t2); - __m256i t4 = __lasx_xvhaddw_q_d(t3, t3); - return (int)(((v8i32)t4)[0]+((v8i32)t4)[4]); -} - -#define OPENCV_HAL_IMPL_LASX_REDUCE_32(_Tpvec, sctype, func, intrin) \ - inline sctype v_reduce_##func(const _Tpvec& a) \ - { \ - __m128i val = intrin(_v256_extract_low(a.val), _v256_extract_high(a.val)); \ - val = intrin(val, __lsx_vbsrl_v(val,8)); \ - val = intrin(val, __lsx_vbsrl_v(val,4)); \ - val = intrin(val, __lsx_vbsrl_v(val,2)); \ - val = intrin(val, __lsx_vbsrl_v(val,1)); \ - return (sctype)__lsx_vpickve2gr_w(val, 0); \ - } - -OPENCV_HAL_IMPL_LASX_REDUCE_32(v_uint8x32, uchar, min, __lsx_vmin_bu) -OPENCV_HAL_IMPL_LASX_REDUCE_32(v_int8x32, schar, min, __lsx_vmin_b) -OPENCV_HAL_IMPL_LASX_REDUCE_32(v_uint8x32, uchar, max, __lsx_vmax_bu) -OPENCV_HAL_IMPL_LASX_REDUCE_32(v_int8x32, schar, max, __lsx_vmax_b) - -#define OPENCV_HAL_IMPL_LASX_REDUCE_16(_Tpvec, sctype, func, intrin) \ - inline sctype v_reduce_##func(const _Tpvec& a) \ - { \ - __m128i v0 = _v256_extract_low(a.val); \ - __m128i v1 = _v256_extract_high(a.val); \ - v0 = intrin(v0, v1); \ - v0 = intrin(v0, __lsx_vbsrl_v(v0, 8)); \ - v0 = intrin(v0, __lsx_vbsrl_v(v0, 4)); \ - v0 = intrin(v0, __lsx_vbsrl_v(v0, 2)); \ - return (sctype) __lsx_vpickve2gr_w(v0, 0); \ - } - -OPENCV_HAL_IMPL_LASX_REDUCE_16(v_uint16x16, ushort, min, __lsx_vmin_hu) -OPENCV_HAL_IMPL_LASX_REDUCE_16(v_int16x16, short, min, __lsx_vmin_h) -OPENCV_HAL_IMPL_LASX_REDUCE_16(v_uint16x16, ushort, max, __lsx_vmax_hu) -OPENCV_HAL_IMPL_LASX_REDUCE_16(v_int16x16, short, max, __lsx_vmax_h) - -#define OPENCV_HAL_IMPL_LASX_REDUCE_8(_Tpvec, sctype, func, intrin) \ - inline sctype v_reduce_##func(const _Tpvec& a) \ - { \ - __m128i v0 = _v256_extract_low(a.val); \ - __m128i v1 = _v256_extract_high(a.val); \ - v0 = intrin(v0, v1); \ - v0 = intrin(v0, __lsx_vbsrl_v(v0, 8)); \ - v0 = intrin(v0, __lsx_vbsrl_v(v0, 4)); \ - return (sctype) __lsx_vpickve2gr_w(v0, 0); \ - } - -OPENCV_HAL_IMPL_LASX_REDUCE_8(v_uint32x8, unsigned, min, __lsx_vmin_wu) -OPENCV_HAL_IMPL_LASX_REDUCE_8(v_int32x8, int, min, __lsx_vmin_w) -OPENCV_HAL_IMPL_LASX_REDUCE_8(v_uint32x8, unsigned, max, __lsx_vmax_wu) -OPENCV_HAL_IMPL_LASX_REDUCE_8(v_int32x8, int, max, __lsx_vmax_w) - -#define OPENCV_HAL_IMPL_LASX_REDUCE_FLT(func, intrin) \ - inline float v_reduce_##func(const v_float32x8& a) \ - { \ - __m128 v0 = _v256_extract_low(a.val); \ - __m128 v1 = _v256_extract_high(a.val); \ - v0 = intrin(v0, v1); \ - v0 = intrin(v0, __m128(__lsx_vpermi_w(*((__m128i*)&v0), *((__m128i*)&v0), 0x0e))); \ - v0 = intrin(v0, __m128(__lsx_vpermi_w(*((__m128i*)&v0), *((__m128i*)&v0), 0x01))); \ - float *fvalue = (float*)&v0; \ - return fvalue[0]; \ - } - -OPENCV_HAL_IMPL_LASX_REDUCE_FLT(min, __lsx_vfmin_s) -OPENCV_HAL_IMPL_LASX_REDUCE_FLT(max, __lsx_vfmax_s) - -inline int v_reduce_sum(const v_int32x8& a) -{ - __m256i t1 = __lasx_xvhaddw_d_w(a.val, a.val); - __m256i t2 = __lasx_xvhaddw_q_d(t1, t1); - return (int)(((v8i32)t2)[0]+((v8i32)t2)[4]); -} - -inline unsigned v_reduce_sum(const v_uint32x8& a) -{ return v_reduce_sum(v_reinterpret_as_s32(a)); } - -inline int v_reduce_sum(const v_int16x16& a) -{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } -inline unsigned v_reduce_sum(const v_uint16x16& a) -{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } - -inline float v_reduce_sum(const v_float32x8& a) -{ - float result = 0; - float *pa = (float*)&a; - for (int i = 0; i < 2; ++i) { - result += pa[i*4] + pa[i*4+1] + pa[i*4+2] + pa[i*4+3]; - } - return result; -} - -inline uint64 v_reduce_sum(const v_uint64x4& a) -{ - __m256i t0 = __lasx_xvhaddw_qu_du(a.val, a.val); - return (uint64)(((v4u64)t0)[0] + ((v4u64)t0)[2]); -} -inline int64 v_reduce_sum(const v_int64x4& a) -{ - __m256i t0 = __lasx_xvhaddw_q_d(a.val, a.val); - return (int64)(((v4i64)t0)[0] + ((v4i64)t0)[2]); -} -inline double v_reduce_sum(const v_float64x4& a) -{ - double *pa = (double*)&a; - return pa[0] + pa[1] + pa[2] + pa[3]; -} - -inline v_float32x8 v_reduce_sum4(const v_float32x8& a, const v_float32x8& b, - const v_float32x8& c, const v_float32x8& d) -{ - float *pa = (float*)&a; - float *pb = (float*)&b; - float *pc = (float*)&c; - float *pd = (float*)&d; - - float v0 = pa[0] + pa[1] + pa[2] + pa[3]; - float v1 = pb[0] + pb[1] + pb[2] + pb[3]; - float v2 = pc[0] + pc[1] + pc[2] + pc[3]; - float v3 = pd[0] + pd[1] + pd[2] + pd[3]; - float v4 = pa[4] + pa[5] + pa[6] + pa[7]; - float v5 = pb[4] + pb[5] + pb[6] + pb[7]; - float v6 = pc[4] + pc[5] + pc[6] + pc[7]; - float v7 = pd[4] + pd[5] + pd[6] + pd[7]; - return v_float32x8(v0, v1, v2, v3, v4, v5, v6, v7); -} - -inline unsigned v_reduce_sad(const v_uint8x32& a, const v_uint8x32& b) -{ - __m256i t0 = __lasx_xvabsd_bu(a.val, b.val); - __m256i t1 = __lasx_xvhaddw_hu_bu(t0, t0); - __m256i t2 = __lasx_xvhaddw_wu_hu(t1, t1); - __m256i t3 = __lasx_xvhaddw_du_wu(t2, t2); - __m256i t4 = __lasx_xvhaddw_qu_du(t3, t3); - return (unsigned)(((v8u32)t4)[0]+((v8u32)t4)[4]); -} -inline unsigned v_reduce_sad(const v_int8x32& a, const v_int8x32& b) -{ - __m256i t0 = __lasx_xvabsd_b(a.val, b.val); - __m256i t1 = __lasx_xvhaddw_hu_bu(t0, t0); - __m256i t2 = __lasx_xvhaddw_wu_hu(t1, t1); - __m256i t3 = __lasx_xvhaddw_du_wu(t2, t2); - __m256i t4 = __lasx_xvhaddw_qu_du(t3, t3); - return (unsigned)(((v8u32)t4)[0]+((v8u32)t4)[4]); -} -inline unsigned v_reduce_sad(const v_uint16x16& a, const v_uint16x16& b) -{ - v_uint32x8 l, h; - v_expand(v_add_wrap(v_sub(a, b), v_sub(b, a)), l, h); - return v_reduce_sum(v_add(l, h)); -} -inline unsigned v_reduce_sad(const v_int16x16& a, const v_int16x16& b) -{ - v_uint32x8 l, h; - v_expand(v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))), l, h); - return v_reduce_sum(v_add(l, h)); -} -inline unsigned v_reduce_sad(const v_uint32x8& a, const v_uint32x8& b) -{ - return v_reduce_sum(v_sub(v_max(a, b), v_min(a, b))); -} -inline unsigned v_reduce_sad(const v_int32x8& a, const v_int32x8& b) -{ - v_int32x8 m = v_lt(a, b); - return v_reduce_sum(v_reinterpret_as_u32(v_sub(v_xor(v_sub(a, b), m), m))); -} -inline float v_reduce_sad(const v_float32x8& a, const v_float32x8& b) -{ - v_float32x8 a_b = v_sub(a, b); - return v_reduce_sum(v_float32x8(*((__m256i*)&a_b.val) & __lasx_xvreplgr2vr_w(0x7fffffff))); -} - -/** Popcount **/ -inline v_uint8x32 v_popcount(const v_uint8x32& a) -{ return v_uint8x32(__lasx_xvpcnt_b(a.val)); } -inline v_uint16x16 v_popcount(const v_uint16x16& a) -{ return v_uint16x16(__lasx_xvpcnt_h(a.val)); } -inline v_uint32x8 v_popcount(const v_uint32x8& a) -{ return v_uint32x8(__lasx_xvpcnt_w(a.val)); } -inline v_uint64x4 v_popcount(const v_uint64x4& a) -{ return v_uint64x4(__lasx_xvpcnt_d(a.val)); } -inline v_uint8x32 v_popcount(const v_int8x32& a) -{ return v_popcount(v_reinterpret_as_u8(a)); } -inline v_uint16x16 v_popcount(const v_int16x16& a) -{ return v_popcount(v_reinterpret_as_u16(a)); } -inline v_uint32x8 v_popcount(const v_int32x8& a) -{ return v_popcount(v_reinterpret_as_u32(a)); } -inline v_uint64x4 v_popcount(const v_int64x4& a) -{ return v_popcount(v_reinterpret_as_u64(a)); } - -inline int v_signmask(const v_int8x32& a) -{ - __m256i result = __lasx_xvmskltz_b(a.val); - int mask = __lasx_xvpickve2gr_w(result, 0); - mask |= (__lasx_xvpickve2gr_w(result, 4) << 16); - return mask; -} -inline int v_signmask(const v_uint8x32& a) -{ return v_signmask(v_reinterpret_as_s8(a)); } - -inline int v_signmask(const v_int16x16& a) -{ return v_signmask(v_pack(a, a)) & 0xFFFF; } -inline int v_signmask(const v_uint16x16& a) -{ return v_signmask(v_reinterpret_as_s16(a)); } - -inline int v_signmask(const v_int32x8& a) -{ - __m256i result = __lasx_xvmskltz_w(a.val); - int mask = __lasx_xvpickve2gr_w(result, 0); - mask |= (__lasx_xvpickve2gr_w(result, 4) << 4); - return mask; -} -inline int v_signmask(const v_uint32x8& a) -{ return v_signmask(*(v_int32x8*)(&a)); } - -inline int v_signmask(const v_int64x4& a) -{ - __m256i result = __lasx_xvmskltz_d(a.val); - int mask = __lasx_xvpickve2gr_d(result, 0); - mask |= (__lasx_xvpickve2gr_w(result, 4) << 2); - return mask; -} -inline int v_signmask(const v_uint64x4& a) -{ return v_signmask(v_reinterpret_as_s64(a)); } - -inline int v_signmask(const v_float32x8& a) -{ return v_signmask(*(v_int32x8*)(&a)); } - -inline int v_signmask(const v_float64x4& a) -{ return v_signmask(*(v_int64x4*)(&a)); } - -inline int v_scan_forward(const v_int8x32& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } -inline int v_scan_forward(const v_uint8x32& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } -inline int v_scan_forward(const v_int16x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } -inline int v_scan_forward(const v_uint16x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } -inline int v_scan_forward(const v_int32x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_uint32x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_float32x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_int64x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } -inline int v_scan_forward(const v_uint64x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } -inline int v_scan_forward(const v_float64x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } - -/** Checks **/ -#define OPENCV_HAL_IMPL_LASX_CHECK(_Tpvec, allmask) \ - inline bool v_check_all(const _Tpvec& a) { return v_signmask(a) == allmask; } \ - inline bool v_check_any(const _Tpvec& a) { return v_signmask(a) != 0; } -OPENCV_HAL_IMPL_LASX_CHECK(v_uint8x32, -1) -OPENCV_HAL_IMPL_LASX_CHECK(v_int8x32, -1) -OPENCV_HAL_IMPL_LASX_CHECK(v_uint32x8, 255) -OPENCV_HAL_IMPL_LASX_CHECK(v_int32x8, 255) -OPENCV_HAL_IMPL_LASX_CHECK(v_uint64x4, 15) -OPENCV_HAL_IMPL_LASX_CHECK(v_int64x4, 15) -OPENCV_HAL_IMPL_LASX_CHECK(v_float32x8, 255) -OPENCV_HAL_IMPL_LASX_CHECK(v_float64x4, 15) - -#define OPENCV_HAL_IMPL_LASX_CHECK_SHORT(_Tpvec) \ - inline bool v_check_all(const _Tpvec& a) { return (v_signmask(v_reinterpret_as_s8(a)) & 0xaaaaaaaa) == 0xaaaaaaaa; } \ - inline bool v_check_any(const _Tpvec& a) { return (v_signmask(v_reinterpret_as_s8(a)) & 0xaaaaaaaa) != 0; } -OPENCV_HAL_IMPL_LASX_CHECK_SHORT(v_uint16x16) -OPENCV_HAL_IMPL_LASX_CHECK_SHORT(v_int16x16) - -////////// Other math ///////// - -/** Some frequent operations **/ -#define OPENCV_HAL_IMPL_LASX_MULADD(_Tpvec, suffix) \ - inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ - { return _Tpvec(__lasx_xvfmadd_##suffix(a.val, b.val, c.val)); } \ - inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ - { return _Tpvec(__lasx_xvfmadd_##suffix(a.val, b.val, c.val)); } \ - inline _Tpvec v_sqrt(const _Tpvec& x) \ - { return _Tpvec(__lasx_xvfsqrt_##suffix(x.val)); } \ - inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ - { return v_fma(a, a, v_mul(b, b)); } \ - inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ - { return v_sqrt(v_fma(a, a, v_mul(b, b))); } - -OPENCV_HAL_IMPL_LASX_MULADD(v_float32x8, s) -OPENCV_HAL_IMPL_LASX_MULADD(v_float64x4, d) - -inline v_int32x8 v_fma(const v_int32x8& a, const v_int32x8& b, const v_int32x8& c) -{ - return v_int32x8(__lasx_xvmadd_w(c.val, a.val, b.val)); -} - -inline v_int32x8 v_muladd(const v_int32x8& a, const v_int32x8& b, const v_int32x8& c) -{ - return v_fma(a, b, c); -} - -inline v_float32x8 v_invsqrt(const v_float32x8& x) -{ return v_float32x8(__lasx_xvfrsqrt_s(x.val)); } - -inline v_float64x4 v_invsqrt(const v_float64x4& x) -{ return v_float64x4(__lasx_xvfrsqrt_d(x.val)); } - -/** Absolute values **/ -#define OPENCV_HAL_IMPL_LASX_ABS(_Tpvec, suffix) \ - inline v_u##_Tpvec v_abs(const v_##_Tpvec& x) \ - { return v_u##_Tpvec(__lasx_xvabsd_##suffix(x.val, __lasx_xvreplgr2vr_w(0))); } - -OPENCV_HAL_IMPL_LASX_ABS(int8x32, b) -OPENCV_HAL_IMPL_LASX_ABS(int16x16, h) -OPENCV_HAL_IMPL_LASX_ABS(int32x8, w) - -inline v_float32x8 v_abs(const v_float32x8& x) -{ return v_float32x8(*((__m256i*)&x) & __lasx_xvreplgr2vr_w(0x7fffffff)); } -inline v_float64x4 v_abs(const v_float64x4& x) -{ return v_float64x4(*((__m256i*)&x) & __lasx_xvreplgr2vr_d(0x7fffffffffffffff)); } - -/** Absolute difference **/ -inline v_uint8x32 v_absdiff(const v_uint8x32& a, const v_uint8x32& b) -{ return (v_uint8x32)__lasx_xvabsd_bu(a.val, b.val); } -inline v_uint16x16 v_absdiff(const v_uint16x16& a, const v_uint16x16& b) -{ return (v_uint16x16)__lasx_xvabsd_hu(a.val, b.val); } -inline v_uint32x8 v_absdiff(const v_uint32x8& a, const v_uint32x8& b) -{ return (v_uint32x8)__lasx_xvabsd_wu(a.val, b.val); } - -inline v_uint8x32 v_absdiff(const v_int8x32& a, const v_int8x32& b) -{ return (v_uint8x32)__lasx_xvabsd_b(a.val, b.val); } -inline v_uint16x16 v_absdiff(const v_int16x16& a, const v_int16x16& b) -{ return (v_uint16x16)__lasx_xvabsd_h(a.val, b.val); } -inline v_uint32x8 v_absdiff(const v_int32x8& a, const v_int32x8& b) -{ return (v_uint32x8)__lasx_xvabsd_w(a.val, b.val); } - -inline v_float32x8 v_absdiff(const v_float32x8& a, const v_float32x8& b) -{ return v_abs(v_sub(a, b)); } - -inline v_float64x4 v_absdiff(const v_float64x4& a, const v_float64x4& b) -{ return v_abs(v_sub(a, b)); } - -/** Saturating absolute difference **/ -inline v_int8x32 v_absdiffs(const v_int8x32& a, const v_int8x32& b) -{ - v_int8x32 d = v_sub(a, b); - v_int8x32 m = v_lt(a, b); - return v_sub(v_xor(d, m), m); -} -inline v_int16x16 v_absdiffs(const v_int16x16& a, const v_int16x16& b) -{ return v_sub(v_max(a, b), v_min(a, b)); } - -////////// Conversions ///////// - -/** Rounding **/ -inline v_int32x8 v_round(const v_float32x8& a) -{ return v_int32x8(__lasx_xvftint_w_s(a.val)); } - -inline v_int32x8 v_round(const v_float64x4& a) -{ __m256i t = __lasx_xvftint_w_d(a.val, a.val); - return v_int32x8(__lasx_xvpermi_d(t, 0x88)); } - -inline v_int32x8 v_round(const v_float64x4& a, const v_float64x4& b) -{ - __m256i abi = __lasx_xvftint_w_d(b.val, a.val); - return v_int32x8(__lasx_xvpermi_d(abi, 0b11011000)); //3120 -} - -inline v_int32x8 v_trunc(const v_float32x8& a) -{ return v_int32x8(__lasx_xvftintrz_w_s(a.val)); } - -inline v_int32x8 v_trunc(const v_float64x4& a) -{ __m256i t = __lasx_xvftintrz_w_d(a.val, a.val); - return v_int32x8(__lasx_xvpermi_d(t, 0x88)); } - -inline v_int32x8 v_floor(const v_float32x8& a) -{ return v_int32x8(__lasx_xvftintrz_w_s(__m256(__lasx_xvfrintrm_s(a.val)))); } - -inline v_int32x8 v_floor(const v_float64x4& a) -{ return v_trunc(v_float64x4(__lasx_xvfrintrm_d(a.val))); } - -inline v_int32x8 v_ceil(const v_float32x8& a) -{ return v_int32x8(__lasx_xvftintrz_w_s(__m256(__lasx_xvfrintrp_s(a.val)))); } - -inline v_int32x8 v_ceil(const v_float64x4& a) -{ return v_trunc(v_float64x4(__lasx_xvfrintrp_d(a.val))); } - -/** To float **/ -inline v_float32x8 v_cvt_f32(const v_int32x8& a) -{ return v_float32x8(__lasx_xvffint_s_w(a.val)); } - -inline v_float32x8 v_cvt_f32(const v_float64x4& a) -{ return v_float32x8(__lasx_xvpermi_d(__lasx_xvfcvt_s_d(a.val, a.val), 0x88)); } - -inline v_float32x8 v_cvt_f32(const v_float64x4& a, const v_float64x4& b) -{ - __m256 abf = __lasx_xvfcvt_s_d(a.val, b.val); //warnning: order of a,b is diff from instruction xvfcvt.s.d - return v_float32x8(__lasx_xvpermi_d(abf, 0x8D)); -} - -inline v_float64x4 v_cvt_f64(const v_int32x8& a) -{ - __m256i alow = __lasx_xvpermi_d(a.val, 0x10); - return v_float64x4(__lasx_xvffintl_d_w(alow)); -} - -inline v_float64x4 v_cvt_f64_high(const v_int32x8& a) -{ - __m256i ahigh = __lasx_xvpermi_d(a.val, 0x32); - return v_float64x4(__lasx_xvffintl_d_w(ahigh)); -} - -inline v_float64x4 v_cvt_f64(const v_float32x8& a) -{ - __m256i alow = __lasx_xvpermi_d(a.val, 0x10); - return v_float64x4(__lasx_xvfcvtl_d_s((__m256)alow)); -} - -inline v_float64x4 v_cvt_f64_high(const v_float32x8& a) -{ - __m256i ahigh = __lasx_xvpermi_d(a.val, 0x32); - return v_float64x4(__lasx_xvfcvtl_d_s((__m256)ahigh)); -} - -inline v_float64x4 v_cvt_f64(const v_int64x4& v) -{ return v_float64x4(__lasx_xvffint_d_l(v.val)); } - -////////////// Lookup table access //////////////////// - -inline v_int8x32 v256_lut(const schar* tab, const int* idx) -{ - return v_int8x32(_v256_setr_b(tab[idx[ 0]], tab[idx[ 1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], tab[idx[ 5]], - tab[idx[ 6]], tab[idx[ 7]], tab[idx[ 8]], tab[idx[ 9]], tab[idx[10]], tab[idx[11]], - tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]], tab[idx[16]], tab[idx[17]], - tab[idx[18]], tab[idx[19]], tab[idx[20]], tab[idx[21]], tab[idx[22]], tab[idx[23]], - tab[idx[24]], tab[idx[25]], tab[idx[26]], tab[idx[27]], tab[idx[28]], tab[idx[29]], - tab[idx[30]], tab[idx[31]])); -} -inline v_int8x32 v256_lut_pairs(const schar* tab, const int* idx) -{ - return v_int8x32(_v256_setr_h(*(const short*)(tab + idx[ 0]), *(const short*)(tab + idx[ 1]), *(const short*)(tab + idx[ 2]), - *(const short*)(tab + idx[ 3]), *(const short*)(tab + idx[ 4]), *(const short*)(tab + idx[ 5]), - *(const short*)(tab + idx[ 6]), *(const short*)(tab + idx[ 7]), *(const short*)(tab + idx[ 8]), - *(const short*)(tab + idx[ 9]), *(const short*)(tab + idx[10]), *(const short*)(tab + idx[11]), - *(const short*)(tab + idx[12]), *(const short*)(tab + idx[13]), *(const short*)(tab + idx[14]), - *(const short*)(tab + idx[15]))); -} -inline v_int8x32 v256_lut_quads(const schar* tab, const int* idx) -{ - return v_int8x32(_v256_setr_w(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), - *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]), - *(const int*)(tab + idx[4]), *(const int*)(tab + idx[5]), - *(const int*)(tab + idx[6]), *(const int*)(tab + idx[7]))); -} -inline v_uint8x32 v256_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v256_lut((const schar *)tab, idx)); } -inline v_uint8x32 v256_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v256_lut_pairs((const schar *)tab, idx)); } -inline v_uint8x32 v256_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v256_lut_quads((const schar *)tab, idx)); } - -inline v_int16x16 v256_lut(const short* tab, const int* idx) -{ - return v_int16x16(_v256_setr_h(tab[idx[ 0]], tab[idx[ 1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], - tab[idx[ 5]], tab[idx[ 6]], tab[idx[ 7]], tab[idx[ 8]], tab[idx[ 9]], - tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], - tab[idx[15]])); -} -inline v_int16x16 v256_lut_pairs(const short* tab, const int* idx) -{ - return v_int16x16(_v256_setr_w(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), - *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]), - *(const int*)(tab + idx[4]), *(const int*)(tab + idx[5]), - *(const int*)(tab + idx[6]), *(const int*)(tab + idx[7]) )); -} -inline v_int16x16 v256_lut_quads(const short* tab, const int* idx) -{ - return v_int16x16(_v256_setr_d(*(const long long int*)(tab + idx[0]), *(const long long int*)(tab + idx[1]), - *(const long long int*)(tab + idx[2]), *(const long long int*)(tab + idx[3]) )); - -} -inline v_uint16x16 v256_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v256_lut((const short *)tab, idx)); } -inline v_uint16x16 v256_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v256_lut_pairs((const short *)tab, idx)); } -inline v_uint16x16 v256_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v256_lut_quads((const short *)tab, idx)); } - -inline v_int32x8 v256_lut(const int* tab, const int* idx) -{ - return v_int32x8(_v256_setr_w(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), - *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]), - *(const int*)(tab + idx[4]), *(const int*)(tab + idx[5]), - *(const int*)(tab + idx[6]), *(const int*)(tab + idx[7]) )); -} -inline v_int32x8 v256_lut_pairs(const int* tab, const int* idx) -{ - return v_int32x8(_v256_setr_d(*(const long long int*)(tab + idx[0]), *(const long long int*)(tab + idx[1]), - *(const long long int*)(tab + idx[2]), *(const long long int*)(tab + idx[3]) )); -} -inline v_int32x8 v256_lut_quads(const int* tab, const int* idx) -{ - return v_int32x8(_v256_combine(__lsx_vld(tab + idx[0], 0), __lsx_vld(tab + idx[1], 0))); -} -inline v_uint32x8 v256_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v256_lut((const int *)tab, idx)); } -inline v_uint32x8 v256_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v256_lut_pairs((const int *)tab, idx)); } -inline v_uint32x8 v256_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v256_lut_quads((const int *)tab, idx)); } - -inline v_int64x4 v256_lut(const int64* tab, const int* idx) -{ - return v_int64x4(_v256_setr_d(*(const long long int*)(tab + idx[0]), *(const long long int*)(tab + idx[1]), - *(const long long int*)(tab + idx[2]), *(const long long int*)(tab + idx[3]) )); -} -inline v_int64x4 v256_lut_pairs(const int64* tab, const int* idx) -{ - return v_int64x4(_v256_combine(__lsx_vld(tab + idx[0], 0), __lsx_vld(tab + idx[1], 0))); -} -inline v_uint64x4 v256_lut(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v256_lut((const int64 *)tab, idx)); } -inline v_uint64x4 v256_lut_pairs(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v256_lut_pairs((const int64 *)tab, idx)); } - -inline v_float32x8 v256_lut(const float* tab, const int* idx) -{ - return v_float32x8(_v256_setr_ps(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], - tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]])); -} -inline v_float32x8 v256_lut_pairs(const float* tab, const int* idx) { return v_reinterpret_as_f32(v256_lut_pairs((const int *)tab, idx)); } -inline v_float32x8 v256_lut_quads(const float* tab, const int* idx) { return v_reinterpret_as_f32(v256_lut_quads((const int *)tab, idx)); } - -inline v_float64x4 v256_lut(const double* tab, const int* idx) -{ - return v_float64x4(_v256_setr_pd(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]])); -} -inline v_float64x4 v256_lut_pairs(const double* tab, const int* idx) -{ return v_float64x4(_v256_combine(__lsx_vld(tab + idx[0], 0), __lsx_vld(tab + idx[1], 0))); } - -inline v_int32x8 v_lut(const int* tab, const v_int32x8& idxvec) -{ - int *idx = (int*)&idxvec.val; - return v256_lut(tab, idx); -} - -inline v_uint32x8 v_lut(const unsigned* tab, const v_int32x8& idxvec) -{ - return v_reinterpret_as_u32(v_lut((const int *)tab, idxvec)); -} - -inline v_float32x8 v_lut(const float* tab, const v_int32x8& idxvec) -{ - const int *idx = (const int*)&idxvec.val; - return v256_lut(tab, idx); -} - -inline v_float64x4 v_lut(const double* tab, const v_int32x8& idxvec) -{ - const int *idx = (const int*)&idxvec.val; - return v256_lut(tab, idx); -} - -inline void v_lut_deinterleave(const float* tab, const v_int32x8& idxvec, v_float32x8& x, v_float32x8& y) -{ - const int *idx = (const int*)&idxvec.val; - __m128i xy01, xy45, xy23, xy67; - xy01 = __lsx_vld(tab + idx[0], 0); - xy01 = __lsx_vextrins_d(xy01, __lsx_vld(tab + idx[1], 0), 0x10); - xy45 = __lsx_vld(tab + idx[4], 0); - xy45 = __lsx_vextrins_d(xy45, __lsx_vld(tab + idx[5], 0), 0x10); - __m256i xy0145 = _v256_combine(xy01, xy45); - xy23 = __lsx_vld(tab + idx[2], 0); - xy23 = __lsx_vextrins_d(xy23, __lsx_vld(tab + idx[3], 0), 0x10); - xy67 = __lsx_vld(tab + idx[6], 0); - xy67 = __lsx_vextrins_d(xy67, __lsx_vld(tab + idx[7], 0), 0x10); - __m256i xy2367 = _v256_combine(xy23, xy67); - - __m256i xxyy0145 = __lasx_xvilvl_w(xy2367, xy0145); - __m256i xxyy2367 = __lasx_xvilvh_w(xy2367, xy0145); - - x = v_float32x8(__lasx_xvilvl_w(xxyy2367, xxyy0145)); - y = v_float32x8(__lasx_xvilvh_w(xxyy2367, xxyy0145)); -} - -inline void v_lut_deinterleave(const double* tab, const v_int32x8& idxvec, v_float64x4& x, v_float64x4& y) -{ - //int CV_DECL_ALIGNED(32) idx[4]; - const int *idx = (const int*)&idxvec.val; - __m128i xy0 = __lsx_vld(tab + idx[0], 0); - __m128i xy2 = __lsx_vld(tab + idx[2], 0); - __m128i xy1 = __lsx_vld(tab + idx[1], 0); - __m128i xy3 = __lsx_vld(tab + idx[3], 0); - __m256i xy02 = _v256_combine(xy0, xy2); - __m256i xy13 = _v256_combine(xy1, xy3); - - x = v_float64x4(__lasx_xvilvl_d(xy13, xy02)); - y = v_float64x4(__lasx_xvilvh_d(xy13, xy02)); -} - -inline v_int8x32 v_interleave_pairs(const v_int8x32& vec) -{ - return v_int8x32(__lasx_xvshuf_b(vec.val, vec.val, - _v256_set_d(0x0f0d0e0c0b090a08, 0x0705060403010200, 0x0f0d0e0c0b090a08, 0x0705060403010200))); -} -inline v_uint8x32 v_interleave_pairs(const v_uint8x32& vec) -{ return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } -inline v_int8x32 v_interleave_quads(const v_int8x32& vec) -{ - return v_int8x32(__lasx_xvshuf_b(vec.val, vec.val, - _v256_set_d(0x0f0b0e0a0d090c08, 0x0703060205010400, 0x0f0b0e0a0d090c08, 0x0703060205010400))); -} -inline v_uint8x32 v_interleave_quads(const v_uint8x32& vec) -{ return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } - -inline v_int16x16 v_interleave_pairs(const v_int16x16& vec) -{ - return v_int16x16(__lasx_xvshuf_b(vec.val, vec.val, - _v256_set_d(0x0f0e0b0a0d0c0908, 0x0706030205040100, 0x0f0e0b0a0d0c0908, 0x0706030205040100))); -} -inline v_uint16x16 v_interleave_pairs(const v_uint16x16& vec) -{ return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } -inline v_int16x16 v_interleave_quads(const v_int16x16& vec) -{ - return v_int16x16(__lasx_xvshuf_b(vec.val, vec.val, - _v256_set_d(0x0f0e07060d0c0504, 0x0b0a030209080100, 0x0f0e07060d0c0504, 0x0b0a030209080100))); -} -inline v_uint16x16 v_interleave_quads(const v_uint16x16& vec) -{ return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } - -inline v_int32x8 v_interleave_pairs(const v_int32x8& vec) -{ - return v_int32x8(__lasx_xvshuf4i_w(vec.val, 0xd8)); -} -inline v_uint32x8 v_interleave_pairs(const v_uint32x8& vec) -{ return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } -inline v_float32x8 v_interleave_pairs(const v_float32x8& vec) -{ return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } - -inline v_int8x32 v_pack_triplets(const v_int8x32& vec) -{ - __m256i vzero = __lasx_xvreplgr2vr_w(0); - __m256i t1 = __lasx_xvshuf_b(vzero, vec.val, - _v256_set_d(0x1211100f0e0d0c0a, 0x0908060504020100, 0x1211100f0e0d0c0a, 0x0908060504020100)); - return v_int8x32(__lasx_xvperm_w(t1, - _v256_set_d(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); -} -inline v_uint8x32 v_pack_triplets(const v_uint8x32& vec) -{ return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } - -inline v_int16x16 v_pack_triplets(const v_int16x16& vec) -{ - __m256i vzero = __lasx_xvreplgr2vr_w(0); - __m256i t1 = __lasx_xvshuf_b(vzero, vec.val, - _v256_set_d(0x11100f0e0d0c0b0a, 0x0908050403020100, 0x11100f0e0d0c0b0a, 0x0908050403020100)); - return v_int16x16(__lasx_xvperm_w(t1, - _v256_set_d(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); -} -inline v_uint16x16 v_pack_triplets(const v_uint16x16& vec) -{ return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } - -inline v_int32x8 v_pack_triplets(const v_int32x8& vec) -{ - return v_int32x8(__lasx_xvperm_w(vec.val, - _v256_set_d(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); -} -inline v_uint32x8 v_pack_triplets(const v_uint32x8& vec) -{ return v_reinterpret_as_u32(v_pack_triplets(v_reinterpret_as_s32(vec))); } -inline v_float32x8 v_pack_triplets(const v_float32x8& vec) -{ - return v_float32x8(__lasx_xvperm_w(*(__m256i*)(&vec.val), - _v256_set_d(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); -} - -////////// Matrix operations ///////// - -//////// Dot Product //////// - -// 16 >> 32 -inline v_int32x8 v_dotprod(const v_int16x16& a, const v_int16x16& b) -{ return v_int32x8(__lasx_xvadd_w(__lasx_xvmulwev_w_h(a.val, b.val), __lasx_xvmulwod_w_h(a.val, b.val))); } - -inline v_int32x8 v_dotprod(const v_int16x16& a, const v_int16x16& b, const v_int32x8& c) -{ return v_add(v_dotprod(a, b), c); } - -// 32 >> 64 -inline v_int64x4 v_dotprod(const v_int32x8& a, const v_int32x8& b) -{ - __m256i even = __lasx_xvmulwev_d_w(a.val, b.val); - return v_int64x4(__lasx_xvmaddwod_d_w(even, a.val, b.val)); -} -inline v_int64x4 v_dotprod(const v_int32x8& a, const v_int32x8& b, const v_int64x4& c) -{ - __m256i even = __lasx_xvmaddwev_d_w(c.val, a.val, b.val); - return v_int64x4(__lasx_xvmaddwod_d_w(even, a.val, b.val)); -} - -// 8 >> 32 -inline v_uint32x8 v_dotprod_expand(const v_uint8x32& a, const v_uint8x32& b) -{ - __m256i even = __lasx_xvmulwev_h_bu(a.val, b.val); - __m256i odd = __lasx_xvmulwod_h_bu(a.val, b.val); - __m256i prod0 = __lasx_xvhaddw_wu_hu(even, even); - __m256i prod1 = __lasx_xvhaddw_wu_hu(odd, odd); - return v_uint32x8(__lasx_xvadd_w(prod0, prod1)); -} -inline v_uint32x8 v_dotprod_expand(const v_uint8x32& a, const v_uint8x32& b, const v_uint32x8& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int32x8 v_dotprod_expand(const v_int8x32& a, const v_int8x32& b) -{ - __m256i even = __lasx_xvmulwev_h_b(a.val, b.val); - __m256i odd = __lasx_xvmulwod_h_b(a.val, b.val); - __m256i prod0 = __lasx_xvhaddw_w_h(even, even); - __m256i prod1 = __lasx_xvhaddw_w_h(odd, odd); - return v_int32x8(__lasx_xvadd_w(prod0, prod1)); -} -inline v_int32x8 v_dotprod_expand(const v_int8x32& a, const v_int8x32& b, const v_int32x8& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 16 >> 64 -inline v_uint64x4 v_dotprod_expand(const v_uint16x16& a, const v_uint16x16& b) -{ - __m256i even = __lasx_xvmulwev_w_hu(a.val, b.val); - __m256i odd = __lasx_xvmulwod_w_hu(a.val, b.val); - __m256i prod0 = __lasx_xvhaddw_du_wu(even, even); - __m256i prod1 = __lasx_xvhaddw_du_wu(odd, odd); - return v_uint64x4(__lasx_xvadd_d(prod0, prod1)); -} -inline v_uint64x4 v_dotprod_expand(const v_uint16x16& a, const v_uint16x16& b, const v_uint64x4& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int64x4 v_dotprod_expand(const v_int16x16& a, const v_int16x16& b) -{ - __m256i even = __lasx_xvmulwev_w_h(a.val, b.val); - __m256i odd = __lasx_xvmulwod_w_h(a.val, b.val); - __m256i prod0 = __lasx_xvhaddw_d_w(even, even); - __m256i prod1 = __lasx_xvhaddw_d_w(odd, odd); - return v_int64x4(__lasx_xvadd_d(prod0, prod1)); -} - -inline v_int64x4 v_dotprod_expand(const v_int16x16& a, const v_int16x16& b, const v_int64x4& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 32 >> 64f -inline v_float64x4 v_dotprod_expand(const v_int32x8& a, const v_int32x8& b) -{ return v_cvt_f64(v_dotprod(a, b)); } -inline v_float64x4 v_dotprod_expand(const v_int32x8& a, const v_int32x8& b, const v_float64x4& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -//////// Fast Dot Product //////// - -// 16 >> 32 -inline v_int32x8 v_dotprod_fast(const v_int16x16& a, const v_int16x16& b) -{ return v_dotprod(a, b); } -inline v_int32x8 v_dotprod_fast(const v_int16x16& a, const v_int16x16& b, const v_int32x8& c) -{ return v_dotprod(a, b, c); } - -// 32 >> 64 -inline v_int64x4 v_dotprod_fast(const v_int32x8& a, const v_int32x8& b) -{ return v_dotprod(a, b); } -inline v_int64x4 v_dotprod_fast(const v_int32x8& a, const v_int32x8& b, const v_int64x4& c) -{ return v_dotprod(a, b, c); } - -// 8 >> 32 -inline v_uint32x8 v_dotprod_expand_fast(const v_uint8x32& a, const v_uint8x32& b) -{ return v_dotprod_expand(a, b); } -inline v_uint32x8 v_dotprod_expand_fast(const v_uint8x32& a, const v_uint8x32& b, const v_uint32x8& c) -{ return v_dotprod_expand(a, b, c); } - -inline v_int32x8 v_dotprod_expand_fast(const v_int8x32& a, const v_int8x32& b) -{ return v_dotprod_expand(a, b); } -inline v_int32x8 v_dotprod_expand_fast(const v_int8x32& a, const v_int8x32& b, const v_int32x8& c) -{ return v_dotprod_expand(a, b, c); } - -// 16 >> 64 -inline v_uint64x4 v_dotprod_expand_fast(const v_uint16x16& a, const v_uint16x16& b) -{ - __m256i even = __lasx_xvmulwev_w_hu(a.val, b.val); - __m256i odd = __lasx_xvmulwod_w_hu(a.val, b.val); - __m256i prod0 = __lasx_xvhaddw_du_wu(even, even); - __m256i prod1 = __lasx_xvhaddw_du_wu(odd, odd); - return v_uint64x4(__lasx_xvadd_d(__lasx_xvilvl_d(prod1, prod0), __lasx_xvilvh_d(prod1, prod0))); -} -inline v_uint64x4 v_dotprod_expand_fast(const v_uint16x16& a, const v_uint16x16& b, const v_uint64x4& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -inline v_int64x4 v_dotprod_expand_fast(const v_int16x16& a, const v_int16x16& b) -{ - __m256i prod = __lasx_xvadd_w(__lasx_xvmulwev_w_h(a.val, b.val), __lasx_xvmulwod_w_h(a.val, b.val)); - __m256i sign = __lasx_xvsrai_w(prod, 31); - __m256i lo = __lasx_xvilvl_w(sign, prod); - __m256i hi = __lasx_xvilvh_w(sign, prod); - return v_int64x4(__lasx_xvadd_d(lo, hi)); -} -inline v_int64x4 v_dotprod_expand_fast(const v_int16x16& a, const v_int16x16& b, const v_int64x4& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -// 32 >> 64f -inline v_float64x4 v_dotprod_expand_fast(const v_int32x8& a, const v_int32x8& b) -{ return v_dotprod_expand(a, b); } -inline v_float64x4 v_dotprod_expand_fast(const v_int32x8& a, const v_int32x8& b, const v_float64x4& c) -{ return v_dotprod_expand(a, b, c); } - - -#define OPENCV_HAL_LASX_SPLAT2_PS(a, im) \ - v_float32x8(__lasx_xvpermi_w(a.val, a.val, im)) - -inline v_float32x8 v_matmul(const v_float32x8& v, const v_float32x8& m0, - const v_float32x8& m1, const v_float32x8& m2, - const v_float32x8& m3) -{ - v_float32x8 v04 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0); - v_float32x8 v15 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0x55); - v_float32x8 v26 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0xAA); - v_float32x8 v37 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0xFF); - return v_fma(v04, m0, v_fma(v15, m1, v_fma(v26, m2, v_mul(v37, m3)))); -} - -inline v_float32x8 v_matmuladd(const v_float32x8& v, const v_float32x8& m0, - const v_float32x8& m1, const v_float32x8& m2, - const v_float32x8& a) -{ - v_float32x8 v04 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0); - v_float32x8 v15 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0x55); - v_float32x8 v26 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0xAA); - return v_fma(v04, m0, v_fma(v15, m1, v_fma(v26, m2, a))); -} - - -#define OPENCV_HAL_IMPL_LASX_TRANSPOSE4x4(_Tpvec, cast_from, cast_to) \ - inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ - const _Tpvec& a2, const _Tpvec& a3, \ - _Tpvec& b0, _Tpvec& b1, _Tpvec& b2, _Tpvec& b3) \ - { \ - __m256i t0 = cast_from(__lasx_xvilvl_w(a1.val, a0.val)); \ - __m256i t1 = cast_from(__lasx_xvilvl_w(a3.val, a2.val)); \ - __m256i t2 = cast_from(__lasx_xvilvh_w(a1.val, a0.val)); \ - __m256i t3 = cast_from(__lasx_xvilvh_w(a3.val, a2.val)); \ - b0.val = cast_to(__lasx_xvilvl_d(t1, t0)); \ - b1.val = cast_to(__lasx_xvilvh_d(t1, t0)); \ - b2.val = cast_to(__lasx_xvilvl_d(t3, t2)); \ - b3.val = cast_to(__lasx_xvilvh_d(t3, t2)); \ - } - -OPENCV_HAL_IMPL_LASX_TRANSPOSE4x4(v_uint32x8, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_LASX_TRANSPOSE4x4(v_int32x8, OPENCV_HAL_NOP, OPENCV_HAL_NOP) - -inline void v_transpose4x4(const v_float32x8 &a0, const v_float32x8 &a1, - const v_float32x8 &a2, const v_float32x8 &a3, - v_float32x8 &b0, v_float32x8 &b1, v_float32x8 &b2, v_float32x8 &b3) -{ - __m256i t0 = __lasx_xvilvl_w(__m256i(a1.val), __m256i(a0.val)); - __m256i t1 = __lasx_xvilvl_w(__m256i(a3.val), __m256i(a2.val)); - __m256i t2 = __lasx_xvilvh_w(__m256i(a1.val), __m256i(a0.val)); - __m256i t3 = __lasx_xvilvh_w(__m256i(a3.val), __m256i(a2.val)); - b0.val = __m256(__lasx_xvilvl_d(t1, t0)); - b1.val = __m256(__lasx_xvilvh_d(t1, t0)); - b2.val = __m256(__lasx_xvilvl_d(t3, t2)); - b3.val = __m256(__lasx_xvilvh_d(t3, t2)); -} - -//////////////// Value reordering /////////////// - -/* Expand */ -#define OPENCV_HAL_IMPL_LASX_EXPAND(_Tpvec, _Tpwvec, _Tp, intrin) \ - inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ - { \ - b0.val = intrin(a.val); \ - b1.val = intrin(__lasx_xvpermi_q(a.val, a.val, 0x11)); \ - } \ - inline _Tpwvec v_expand_low(const _Tpvec& a) \ - { return _Tpwvec(intrin(a.val)); } \ - inline _Tpwvec v_expand_high(const _Tpvec& a) \ - { return _Tpwvec(intrin(__lasx_xvpermi_q(a.val, a.val, 0x11))); } \ - inline _Tpwvec v256_load_expand(const _Tp* ptr) \ - { \ - __m128i a = __lsx_vld(ptr, 0); \ - return _Tpwvec(intrin(*((__m256i*)&a))); \ - } - -OPENCV_HAL_IMPL_LASX_EXPAND(v_uint8x32, v_uint16x16, uchar, __lasx_vext2xv_hu_bu) -OPENCV_HAL_IMPL_LASX_EXPAND(v_int8x32, v_int16x16, schar, __lasx_vext2xv_h_b) -OPENCV_HAL_IMPL_LASX_EXPAND(v_uint16x16, v_uint32x8, ushort, __lasx_vext2xv_wu_hu) -OPENCV_HAL_IMPL_LASX_EXPAND(v_int16x16, v_int32x8, short, __lasx_vext2xv_w_h) -OPENCV_HAL_IMPL_LASX_EXPAND(v_uint32x8, v_uint64x4, unsigned, __lasx_vext2xv_du_wu) -OPENCV_HAL_IMPL_LASX_EXPAND(v_int32x8, v_int64x4, int, __lasx_vext2xv_d_w) - -#define OPENCV_HAL_IMPL_LASX_EXPAND_Q(_Tpvec, _Tp, intrin) \ - inline _Tpvec v256_load_expand_q(const _Tp* ptr) \ - { \ - __m128i a = __lsx_vld(ptr, 0); \ - return _Tpvec(intrin(*((__m256i*)&a))); \ - } - -OPENCV_HAL_IMPL_LASX_EXPAND_Q(v_uint32x8, uchar, __lasx_vext2xv_wu_bu) -OPENCV_HAL_IMPL_LASX_EXPAND_Q(v_int32x8, schar, __lasx_vext2xv_w_b) - -/* pack */ -// 16 -inline v_int8x32 v_pack(const v_int16x16& a, const v_int16x16& b) -{ return v_int8x32(_v256_shuffle_odd_64(_lasx_packs_h(a.val, b.val))); } - -inline v_uint8x32 v_pack(const v_uint16x16& a, const v_uint16x16& b) -{ return v_uint8x32(_v256_shuffle_odd_64(__lasx_xvssrlrni_bu_h(b.val, a.val, 0))); } - -inline v_uint8x32 v_pack_u(const v_int16x16& a, const v_int16x16& b) -{ - return v_uint8x32(_v256_shuffle_odd_64(_lasx_packus_h(a.val, b.val))); -} - -inline void v_pack_store(schar* ptr, const v_int16x16& a) -{ v_store_low(ptr, v_pack(a, a)); } - -inline void v_pack_store(uchar *ptr, const v_uint16x16& a) -{ v_store_low(ptr, v_pack(a, a)); } - -inline void v_pack_u_store(uchar* ptr, const v_int16x16& a) -{ v_store_low(ptr, v_pack_u(a, a)); } - -template inline -v_uint8x32 v_rshr_pack(const v_uint16x16& a, const v_uint16x16& b) -{ - __m256i res = __lasx_xvssrlrni_bu_h(b.val, a.val, n); - return v_uint8x32(_v256_shuffle_odd_64(res)); -} - -template inline -void v_rshr_pack_store(uchar* ptr, const v_uint16x16& a) -{ - __m256i res = __lasx_xvssrlrni_bu_h(a.val, a.val, n); - __lasx_xvstelm_d(res, ptr, 0, 0); - __lasx_xvstelm_d(res, ptr, 8, 2); -} - -template inline -v_uint8x32 v_rshr_pack_u(const v_int16x16& a, const v_int16x16& b) -{ - __m256i res = __lasx_xvssrarni_bu_h(b.val, a.val, n); - return v_uint8x32(_v256_shuffle_odd_64(res)); -} - -template inline -void v_rshr_pack_u_store(uchar* ptr, const v_int16x16& a) -{ - __m256i res = __lasx_xvssrarni_bu_h(a.val, a.val, n); - __lasx_xvstelm_d(res, ptr, 0, 0); - __lasx_xvstelm_d(res, ptr, 8, 2); -} - -template inline -v_int8x32 v_rshr_pack(const v_int16x16& a, const v_int16x16& b) -{ - __m256i res = __lasx_xvssrarni_b_h(b.val, a.val, n); - return v_int8x32(_v256_shuffle_odd_64(res)); -} - -template inline -void v_rshr_pack_store(schar* ptr, const v_int16x16& a) -{ - __m256i res = __lasx_xvssrarni_b_h(a.val, a.val, n); - __lasx_xvstelm_d(res, ptr, 0, 0); - __lasx_xvstelm_d(res, ptr, 8, 2); -} - -// 32 -inline v_int16x16 v_pack(const v_int32x8& a, const v_int32x8& b) -{ return v_int16x16(_v256_shuffle_odd_64(_lasx_packs_w(a.val, b.val))); } - -inline v_uint16x16 v_pack(const v_uint32x8& a, const v_uint32x8& b) -{ return v_uint16x16(_v256_shuffle_odd_64(_v256_packs_epu32(a.val, b.val))); } - -inline v_uint16x16 v_pack_u(const v_int32x8& a, const v_int32x8& b) -{ return v_uint16x16(_v256_shuffle_odd_64(_lasx_packus_w(a.val, b.val))); } - -inline void v_pack_store(short* ptr, const v_int32x8& a) -{ v_store_low(ptr, v_pack(a, a)); } - -inline void v_pack_store(ushort* ptr, const v_uint32x8& a) -{ - __m256i res = __lasx_xvssrlrni_hu_w(a.val, a.val, 0); - __lasx_xvstelm_d(res, ptr, 0, 0); - __lasx_xvstelm_d(res, ptr, 8, 2); -} - -inline void v_pack_u_store(ushort* ptr, const v_int32x8& a) -{ v_store_low(ptr, v_pack_u(a, a)); } - -template inline -v_uint16x16 v_rshr_pack(const v_uint32x8& a, const v_uint32x8& b) -{ return v_uint16x16(_v256_shuffle_odd_64(__lasx_xvssrlrni_hu_w(b.val, a.val, n))); } - -template inline -void v_rshr_pack_store(ushort* ptr, const v_uint32x8& a) -{ - __m256i res = __lasx_xvssrlrni_hu_w(a.val, a.val, n); - __lasx_xvstelm_d(res, ptr, 0, 0); - __lasx_xvstelm_d(res, ptr, 8, 2); -} - -template inline -v_uint16x16 v_rshr_pack_u(const v_int32x8& a, const v_int32x8& b) -{ return v_uint16x16(_v256_shuffle_odd_64(__lasx_xvssrarni_hu_w(b.val, a.val, n))); } - -template inline -void v_rshr_pack_u_store(ushort* ptr, const v_int32x8& a) -{ - __m256i res = __lasx_xvssrarni_hu_w(a.val, a.val, n); - __lasx_xvstelm_d(res, ptr, 0, 0); - __lasx_xvstelm_d(res, ptr, 8, 2); -} - -template inline -v_int16x16 v_rshr_pack(const v_int32x8& a, const v_int32x8& b) -{ return v_int16x16(_v256_shuffle_odd_64(__lasx_xvssrarni_h_w(b.val, a.val, n))); } - -template inline -void v_rshr_pack_store(short* ptr, const v_int32x8& a) -{ - __m256i res = __lasx_xvssrarni_h_w(a.val, a.val, n); - __lasx_xvstelm_d(res, ptr, 0, 0); - __lasx_xvstelm_d(res, ptr, 8, 2); -} - -// 64 -// Non-saturating pack -inline v_uint32x8 v_pack(const v_uint64x4& a, const v_uint64x4& b) -{ - __m256i ab = __lasx_xvpickev_w(b.val, a.val); - return v_uint32x8(_v256_shuffle_odd_64(ab)); -} - -inline v_int32x8 v_pack(const v_int64x4& a, const v_int64x4& b) -{ return v_reinterpret_as_s32(v_pack(v_reinterpret_as_u64(a), v_reinterpret_as_u64(b))); } - -inline void v_pack_store(unsigned* ptr, const v_uint64x4& a) -{ - __m256i a0 = __lasx_xvshuf4i_w(a.val, 0x08); - v_store_low(ptr, v_uint32x8(_v256_shuffle_odd_64(a0))); -} - -inline void v_pack_store(int* ptr, const v_int64x4& b) -{ v_pack_store((unsigned*)ptr, v_reinterpret_as_u64(b)); } - -template inline -v_uint32x8 v_rshr_pack(const v_uint64x4& a, const v_uint64x4& b) -{ return v_uint32x8(_v256_shuffle_odd_64(__lasx_xvsrlrni_w_d(b.val, a.val, n))); } - -template inline -void v_rshr_pack_store(unsigned* ptr, const v_uint64x4& a) -{ - __m256i res = __lasx_xvsrlrni_w_d(a.val, a.val, n); - __lasx_xvstelm_d(res, ptr, 0, 0); - __lasx_xvstelm_d(res, ptr, 8, 2); -} - -template inline -v_int32x8 v_rshr_pack(const v_int64x4& a, const v_int64x4& b) -{ return v_int32x8(_v256_shuffle_odd_64(__lasx_xvsrarni_w_d(b.val, a.val, n))); } - -template inline -void v_rshr_pack_store(int* ptr, const v_int64x4& a) -{ - __m256i res = __lasx_xvsrarni_w_d(a.val, a.val, n); - __lasx_xvstelm_d(res, ptr, 0, 0); - __lasx_xvstelm_d(res, ptr, 8, 2); -} - -// pack boolean -inline v_uint8x32 v_pack_b(const v_uint16x16& a, const v_uint16x16& b) -{ - __m256i ab = _lasx_packs_h(a.val, b.val); - return v_uint8x32(_v256_shuffle_odd_64(ab)); -} - -inline v_uint8x32 v_pack_b(const v_uint32x8& a, const v_uint32x8& b, - const v_uint32x8& c, const v_uint32x8& d) -{ - __m256i ab = _lasx_packs_w(a.val, b.val); - __m256i cd = _lasx_packs_w(c.val, d.val); - - __m256i abcd = _v256_shuffle_odd_64(_lasx_packs_h(ab, cd)); - return v_uint8x32(__lasx_xvshuf4i_w(abcd, 0xd8)); -} - -inline v_uint8x32 v_pack_b(const v_uint64x4& a, const v_uint64x4& b, const v_uint64x4& c, - const v_uint64x4& d, const v_uint64x4& e, const v_uint64x4& f, - const v_uint64x4& g, const v_uint64x4& h) -{ - __m256i ab = _lasx_packs_w(a.val, b.val); - __m256i cd = _lasx_packs_w(c.val, d.val); - __m256i ef = _lasx_packs_w(e.val, f.val); - __m256i gh = _lasx_packs_w(g.val, h.val); - - __m256i abcd = _lasx_packs_w(ab, cd); - __m256i efgh = _lasx_packs_w(ef, gh); - __m256i pkall = _v256_shuffle_odd_64(_lasx_packs_h(abcd, efgh)); - - __m256i rev = _v256_alignr_b(pkall, pkall, 8); - return v_uint8x32(__lasx_xvilvl_h(rev, pkall)); -} - -/* Recombine */ -// its up there with load and store operations - -/* Extract */ -#define OPENCV_HAL_IMPL_LASX_EXTRACT(_Tpvec) \ - template \ - inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \ - { return v_rotate_right(a, b); } - -OPENCV_HAL_IMPL_LASX_EXTRACT(v_uint8x32) -OPENCV_HAL_IMPL_LASX_EXTRACT(v_int8x32) -OPENCV_HAL_IMPL_LASX_EXTRACT(v_uint16x16) -OPENCV_HAL_IMPL_LASX_EXTRACT(v_int16x16) -OPENCV_HAL_IMPL_LASX_EXTRACT(v_uint32x8) -OPENCV_HAL_IMPL_LASX_EXTRACT(v_int32x8) -OPENCV_HAL_IMPL_LASX_EXTRACT(v_uint64x4) -OPENCV_HAL_IMPL_LASX_EXTRACT(v_int64x4) -OPENCV_HAL_IMPL_LASX_EXTRACT(v_float32x8) -OPENCV_HAL_IMPL_LASX_EXTRACT(v_float64x4) - -template -inline uchar v_extract_n(v_uint8x32 a) -{ - return (uchar)_v256_extract_b(a.val); -} - -template -inline schar v_extract_n(v_int8x32 a) -{ - return (schar)v_extract_n(v_reinterpret_as_u8(a)); -} - -template -inline ushort v_extract_n(v_uint16x16 a) -{ - return (ushort)_v256_extract_h(a.val); -} - -template -inline short v_extract_n(v_int16x16 a) -{ - return (short)v_extract_n(v_reinterpret_as_u16(a)); -} - -template -inline uint v_extract_n(v_uint32x8 a) -{ - return (uint)_v256_extract_w(a.val); -} - -template -inline int v_extract_n(v_int32x8 a) -{ - return (int)v_extract_n(v_reinterpret_as_u32(a)); -} - -template -inline uint64 v_extract_n(v_uint64x4 a) -{ - return (uint64)_v256_extract_d(a.val); -} - -template -inline int64 v_extract_n(v_int64x4 v) -{ - return (int64)v_extract_n(v_reinterpret_as_u64(v)); -} - -template -inline float v_extract_n(v_float32x8 v) -{ - union { uint iv; float fv; } d; - d.iv = v_extract_n(v_reinterpret_as_u32(v)); - return d.fv; -} - -template -inline double v_extract_n(v_float64x4 v) -{ - union { uint64 iv; double dv; } d; - d.iv = v_extract_n(v_reinterpret_as_u64(v)); - return d.dv; -} - -template -inline v_uint32x8 v_broadcast_element(v_uint32x8 a) -{ - static const __m256i perm = __lasx_xvreplgr2vr_w((char)i); - return v_uint32x8(__lasx_xvperm_w(a.val, perm)); -} - -template -inline v_int32x8 v_broadcast_element(const v_int32x8 &a) -{ return v_reinterpret_as_s32(v_broadcast_element(v_reinterpret_as_u32(a))); } - -template -inline v_float32x8 v_broadcast_element(const v_float32x8 &a) -{ return v_reinterpret_as_f32(v_broadcast_element(v_reinterpret_as_u32(a))); } - -///////////////////// load deinterleave ///////////////////////////// - -inline void v_load_deinterleave(const uchar* ptr, v_uint8x32& a, v_uint8x32& b) -{ - __m256i t0 = __lasx_xvld(ptr, 0); - __m256i t1 = __lasx_xvld(ptr, 32); - - __m256i p0 = __lasx_xvpickev_b(t1, t0); - __m256i p1 = __lasx_xvpickod_b(t1, t0); - - a.val = __lasx_xvpermi_d(p0, 0xd8); - b.val = __lasx_xvpermi_d(p1, 0xd8); -} - -inline void v_load_deinterleave( const ushort* ptr, v_uint16x16& a, v_uint16x16& b ) -{ - __m256i t0 = __lasx_xvld(ptr, 0); - __m256i t1 = __lasx_xvld(ptr, 32); - - __m256i p0 = __lasx_xvpickev_h(t1, t0); - __m256i p1 = __lasx_xvpickod_h(t1, t0); - - a.val = __lasx_xvpermi_d(p0, 0xd8); - b.val = __lasx_xvpermi_d(p1, 0xd8); -} - -inline void v_load_deinterleave( const unsigned* ptr, v_uint32x8& a, v_uint32x8& b ) -{ - __m256i t0 = __lasx_xvld(ptr, 0); - __m256i t1 = __lasx_xvld(ptr, 32); - - __m256i p0 = __lasx_xvpickev_w(t1, t0); - __m256i p1 = __lasx_xvpickod_w(t1, t0); - - a.val = __lasx_xvpermi_d(p0, 0xd8); - b.val = __lasx_xvpermi_d(p1, 0xd8); -} - -inline void v_load_deinterleave( const uint64* ptr, v_uint64x4& a, v_uint64x4& b ) -{ - __m256i ab0 = __lasx_xvld(ptr, 0); - __m256i ab1 = __lasx_xvld(ptr, 32); - - __m256i pl = __lasx_xvpermi_q(ab0, ab1, 0x02); - __m256i ph = __lasx_xvpermi_q(ab0, ab1, 0x13); - __m256i a0 = __lasx_xvilvl_d(ph, pl); - __m256i b0 = __lasx_xvilvh_d(ph, pl); - a = v_uint64x4(a0); - b = v_uint64x4(b0); -} - -inline void v_load_deinterleave( const uchar* ptr, v_uint8x32& a, v_uint8x32& b, v_uint8x32& c ) -{ - __m256i bgr0 = __lasx_xvld(ptr, 0); - __m256i bgr1 = __lasx_xvld(ptr, 32); - __m256i bgr2 = __lasx_xvld(ptr, 64); - - __m256i s02_low = __lasx_xvpermi_q(bgr0, bgr2, 0x02); - __m256i s02_high = __lasx_xvpermi_q(bgr0, bgr2, 0x13); - - const __m256i m0 = _v256_setr_b(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, - 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); - const __m256i m1 = _v256_setr_b(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, - -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); - - __m256i b0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(s02_low, s02_high, m0), bgr1, m1); - __m256i g0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(s02_high, s02_low, m1), bgr1, m0); - __m256i r0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(bgr1, s02_low, m0), s02_high, m1); - - const __m256i - sh_b = _v256_setr_b(0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13, - 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13), - sh_g = _v256_setr_b(1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, - 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14), - sh_r = _v256_setr_b(2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, - 2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15); - b0 = __lasx_xvshuf_b(b0, b0, sh_b); - g0 = __lasx_xvshuf_b(g0, g0, sh_g); - r0 = __lasx_xvshuf_b(r0, r0, sh_r); - - a = v_uint8x32(b0); - b = v_uint8x32(g0); - c = v_uint8x32(r0); -} - -inline void v_load_deinterleave( const ushort* ptr, v_uint16x16& a, v_uint16x16& b, v_uint16x16& c ) -{ - __m256i bgr0 = __lasx_xvld(ptr, 0); - __m256i bgr1 = __lasx_xvld(ptr, 32); - __m256i bgr2 = __lasx_xvld(ptr, 64); - - __m256i s02_low = __lasx_xvpermi_q(bgr0, bgr2, 0x02); - __m256i s02_high = __lasx_xvpermi_q(bgr0, bgr2, 0x13); - - const __m256i m0 = _v256_setr_b(0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, - 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0); - const __m256i m1 = _v256_setr_b(0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, - -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0); - __m256i b0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(s02_low, s02_high, m0), bgr1, m1); - __m256i g0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(bgr1, s02_low, m0), s02_high, m1); - __m256i r0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(s02_high, s02_low, m1), bgr1, m0); - const __m256i sh_b = _v256_setr_b(0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, - 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11); - const __m256i sh_g = _v256_setr_b(2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, - 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 0, 1, 6, 7, 12, 13); - const __m256i sh_r = _v256_setr_b(4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, - 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15); - b0 = __lasx_xvshuf_b(b0, b0, sh_b); - g0 = __lasx_xvshuf_b(g0, g0, sh_g); - r0 = __lasx_xvshuf_b(r0, r0, sh_r); - - a = v_uint16x16(b0); - b = v_uint16x16(g0); - c = v_uint16x16(r0); -} - -inline void v_load_deinterleave( const unsigned* ptr, v_uint32x8& a, v_uint32x8& b, v_uint32x8& c ) -{ - __m256i bgr0 = __lasx_xvld(ptr, 0); - __m256i bgr1 = __lasx_xvld(ptr, 32); - __m256i bgr2 = __lasx_xvld(ptr, 64); - - __m256i s02_low = __lasx_xvpermi_q(bgr0, bgr2, 0x02); - __m256i s02_high = __lasx_xvpermi_q(bgr0, bgr2, 0x13); - - __m256i m24 = _v256_set_w(0, 0, -1, 0, 0, -1, 0, 0); - __m256i m92 = _v256_set_w(-1, 0, 0, -1, 0, 0, -1, 0); - __m256i b0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(s02_low, s02_high, m24), bgr1, m92); - __m256i g0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(s02_high, s02_low, m92), bgr1, m24); - __m256i r0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(bgr1, s02_low, m24), s02_high, m92); - - b0 = __lasx_xvshuf4i_w(b0, 0x6c); - g0 = __lasx_xvshuf4i_w(g0, 0xb1); - r0 = __lasx_xvshuf4i_w(r0, 0xc6); - - a = v_uint32x8(b0); - b = v_uint32x8(g0); - c = v_uint32x8(r0); -} - -inline void v_load_deinterleave( const uint64* ptr, v_uint64x4& a, v_uint64x4& b, v_uint64x4& c ) -{ - __m256i bgr0 = __lasx_xvld(ptr, 0); - __m256i bgr1 = __lasx_xvld(ptr, 32); - __m256i bgr2 = __lasx_xvld(ptr, 64); - - __m256i s01 = __lasx_xvpermi_q(bgr0, bgr1, 0x12); // get bgr0 low 128 and bgr1 high 128 - __m256i s12 = __lasx_xvpermi_q(bgr1, bgr2, 0x12); - __m256i s20r = __lasx_xvpermi_d(__lasx_xvpermi_q(bgr2, bgr0, 0x12), 0x1b); - __m256i b0 = __lasx_xvilvl_d(s20r, s01); - __m256i g0 = _v256_alignr_b(s12, s01, 8); - __m256i r0 = __lasx_xvilvh_d(s12, s20r); - - a = v_uint64x4(b0); - b = v_uint64x4(g0); - c = v_uint64x4(r0); -} - -inline void v_load_deinterleave(const uchar* ptr, v_uint8x32& a, v_uint8x32& b, v_uint8x32& c, v_uint8x32& d) -{ - __m256i t0 = __lasx_xvld(ptr, 0); - __m256i t1 = __lasx_xvld(ptr, 32); - __m256i t2 = __lasx_xvld(ptr, 64); - __m256i t3 = __lasx_xvld(ptr, 96); - - const __m256i sh = _v256_setr_w(0, 4, 1, 5, 2, 6, 3, 7); - __m256i ac_lo = __lasx_xvpickev_b(t1, t0); - __m256i bd_lo = __lasx_xvpickod_b(t1, t0); - __m256i ac_hi = __lasx_xvpickev_b(t3, t2); - __m256i bd_hi = __lasx_xvpickod_b(t3, t2); - - __m256i a_pre = __lasx_xvpickev_b(ac_hi, ac_lo); - __m256i c_pre = __lasx_xvpickod_b(ac_hi, ac_lo); - __m256i b_pre = __lasx_xvpickev_b(bd_hi, bd_lo); - __m256i d_pre = __lasx_xvpickod_b(bd_hi, bd_lo); - - a.val = __lasx_xvperm_w(a_pre, sh); - b.val = __lasx_xvperm_w(b_pre, sh); - c.val = __lasx_xvperm_w(c_pre, sh); - d.val = __lasx_xvperm_w(d_pre, sh); -} - -inline void v_load_deinterleave(const ushort* ptr, v_uint16x16& a, v_uint16x16& b, v_uint16x16& c, v_uint16x16& d) -{ - __m256i t0 = __lasx_xvld(ptr, 0); - __m256i t1 = __lasx_xvld(ptr, 32); - __m256i t2 = __lasx_xvld(ptr, 64); - __m256i t3 = __lasx_xvld(ptr, 96); - - const __m256i sh = _v256_setr_w(0, 4, 1, 5, 2, 6, 3, 7); - __m256i ac_lo = __lasx_xvpickev_h(t1, t0); - __m256i bd_lo = __lasx_xvpickod_h(t1, t0); - __m256i ac_hi = __lasx_xvpickev_h(t3, t2); - __m256i bd_hi = __lasx_xvpickod_h(t3, t2); - - __m256i a_pre = __lasx_xvpickev_h(ac_hi, ac_lo); - __m256i c_pre = __lasx_xvpickod_h(ac_hi, ac_lo); - __m256i b_pre = __lasx_xvpickev_h(bd_hi, bd_lo); - __m256i d_pre = __lasx_xvpickod_h(bd_hi, bd_lo); - - a.val = __lasx_xvperm_w(a_pre, sh); - b.val = __lasx_xvperm_w(b_pre, sh); - c.val = __lasx_xvperm_w(c_pre, sh); - d.val = __lasx_xvperm_w(d_pre, sh); -} - -inline void v_load_deinterleave( const unsigned* ptr, v_uint32x8& a, v_uint32x8& b, v_uint32x8& c, v_uint32x8& d ) -{ - __m256i p0 = __lasx_xvld(ptr, 0); - __m256i p1 = __lasx_xvld(ptr, 32); - __m256i p2 = __lasx_xvld(ptr, 64); - __m256i p3 = __lasx_xvld(ptr, 96); - - __m256i p01l = __lasx_xvilvl_w(p1, p0); - __m256i p01h = __lasx_xvilvh_w(p1, p0); - __m256i p23l = __lasx_xvilvl_w(p3, p2); - __m256i p23h = __lasx_xvilvh_w(p3, p2); - - __m256i pll = __lasx_xvpermi_q(p01l, p23l, 0x02); - __m256i plh = __lasx_xvpermi_q(p01l, p23l, 0x13); - __m256i phl = __lasx_xvpermi_q(p01h, p23h, 0x02); - __m256i phh = __lasx_xvpermi_q(p01h, p23h, 0x13); - - __m256i b0 = __lasx_xvilvl_w(plh, pll); - __m256i g0 = __lasx_xvilvh_w(plh, pll); - __m256i r0 = __lasx_xvilvl_w(phh, phl); - __m256i a0 = __lasx_xvilvh_w(phh, phl); - - a = v_uint32x8(b0); - b = v_uint32x8(g0); - c = v_uint32x8(r0); - d = v_uint32x8(a0); -} - -inline void v_load_deinterleave( const uint64* ptr, v_uint64x4& a, v_uint64x4& b, v_uint64x4& c, v_uint64x4& d ) -{ - __m256i bgra0 = __lasx_xvld(ptr, 0); - __m256i bgra1 = __lasx_xvld(ptr, 32); - __m256i bgra2 = __lasx_xvld(ptr, 64); - __m256i bgra3 = __lasx_xvld(ptr, 96); - - __m256i l02 = __lasx_xvpermi_q(bgra0, bgra2, 0x02); - __m256i h02 = __lasx_xvpermi_q(bgra0, bgra2, 0x13); - __m256i l13 = __lasx_xvpermi_q(bgra1, bgra3, 0x02); - __m256i h13 = __lasx_xvpermi_q(bgra1, bgra3, 0x13); - - __m256i b0 = __lasx_xvilvl_d(l13, l02); - __m256i g0 = __lasx_xvilvh_d(l13, l02); - __m256i r0 = __lasx_xvilvl_d(h13, h02); - __m256i a0 = __lasx_xvilvh_d(h13, h02); - - a = v_uint64x4(b0); - b = v_uint64x4(g0); - c = v_uint64x4(r0); - d = v_uint64x4(a0); -} - -///////////////////////////// store interleave ///////////////////////////////////// - -inline void v_store_interleave( uchar* ptr, const v_uint8x32& x, const v_uint8x32& y, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) -{ - __m256i xy_l = __lasx_xvilvl_b(y.val, x.val); - __m256i xy_h = __lasx_xvilvh_b(y.val, x.val); - - __m256i xy0 = __lasx_xvpermi_q(xy_h, xy_l, 0 + 2*16); - __m256i xy1 = __lasx_xvpermi_q(xy_h, xy_l, 1 + 3*16); - - __lasx_xvst(xy0, (__m256i*)ptr, 0); - __lasx_xvst(xy1, (__m256i*)ptr, 32*1); -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x16& x, const v_uint16x16& y, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) -{ - __m256i xy_l = __lasx_xvilvl_h(y.val, x.val); - __m256i xy_h = __lasx_xvilvh_h(y.val, x.val); - - __m256i xy0 = __lasx_xvpermi_q(xy_h, xy_l, 0 + 2*16); - __m256i xy1 = __lasx_xvpermi_q(xy_h, xy_l, 1 + 3*16); - - __lasx_xvst(xy0, (__m256i*)ptr, 0); - __lasx_xvst(xy1, (__m256i*)ptr, 16*2); -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x8& x, const v_uint32x8& y, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) -{ - __m256i xy_l = __lasx_xvilvl_w(y.val, x.val); - __m256i xy_h = __lasx_xvilvh_w(y.val, x.val); - - __m256i xy0 = __lasx_xvpermi_q(xy_h, xy_l, 0 + 2*16); - __m256i xy1 = __lasx_xvpermi_q(xy_h, xy_l, 1 + 3*16); - - __lasx_xvst(xy0, (__m256i*)ptr, 0); - __lasx_xvst(xy1, (__m256i*)ptr, 8*4); -} - -inline void v_store_interleave( uint64* ptr, const v_uint64x4& x, const v_uint64x4& y, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) -{ - __m256i xy_l = __lasx_xvilvl_d(y.val, x.val); - __m256i xy_h = __lasx_xvilvh_d(y.val, x.val); - - __m256i xy0 = __lasx_xvpermi_q(xy_h, xy_l, 0 + 2*16); - __m256i xy1 = __lasx_xvpermi_q(xy_h, xy_l, 1 + 3*16); - - __lasx_xvst(xy0, (__m256i*)ptr, 0); - __lasx_xvst(xy1, (__m256i*)ptr, 4*8); -} - -inline void v_store_interleave( uchar* ptr, const v_uint8x32& a, const v_uint8x32& b, const v_uint8x32& c, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) -{ - const __m256i sh_b = _v256_setr_b( - 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5, - 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5); - const __m256i sh_g = _v256_setr_b( - 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, - 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10); - const __m256i sh_r = _v256_setr_b( - 10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, - 10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15); - - __m256i b0 = __lasx_xvshuf_b(a.val, a.val, sh_b); - __m256i g0 = __lasx_xvshuf_b(b.val, b.val, sh_g); - __m256i r0 = __lasx_xvshuf_b(c.val, c.val, sh_r); - - const __m256i m0 = _v256_setr_b(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, - 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); - const __m256i m1 = _v256_setr_b(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, - 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0); - - __m256i p0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(b0, g0, m0), r0, m1); - __m256i p1 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(g0, r0, m0), b0, m1); - __m256i p2 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(r0, b0, m0), g0, m1); - - __m256i bgr0 = __lasx_xvpermi_q(p1, p0, 0 + 2*16); - __m256i bgr1 = __lasx_xvpermi_q(p0, p2, 0 + 3*16); - __m256i bgr2 = __lasx_xvpermi_q(p2, p1, 1 + 3*16); - - __lasx_xvst(bgr0, (__m256i*)ptr, 0); - __lasx_xvst(bgr1, (__m256i*)ptr, 32); - __lasx_xvst(bgr2, (__m256i*)ptr, 64); -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x16& a, const v_uint16x16& b, const v_uint16x16& c, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) -{ - const __m256i sh_b = _v256_setr_b( - 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, - 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11); - const __m256i sh_g = _v256_setr_b( - 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, - 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5); - const __m256i sh_r = _v256_setr_b( - 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, - 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15); - - __m256i b0 = __lasx_xvshuf_b(a.val, a.val, sh_b); - __m256i g0 = __lasx_xvshuf_b(b.val, b.val, sh_g); - __m256i r0 = __lasx_xvshuf_b(c.val, c.val, sh_r); - - const __m256i m0 = _v256_setr_b(0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, - 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0); - const __m256i m1 = _v256_setr_b(0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, - -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0); - - __m256i p0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(b0, g0, m0), r0, m1); - __m256i p1 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(g0, r0, m0), b0, m1); - __m256i p2 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(r0, b0, m0), g0, m1); - - __m256i bgr0 = __lasx_xvpermi_q(p2, p0, 0 + 2*16); - __m256i bgr2 = __lasx_xvpermi_q(p2, p0, 1 + 3*16); - - __lasx_xvst(bgr0, (__m256i*)ptr, 0); - __lasx_xvst(p1, (__m256i*)ptr, 16*2); - __lasx_xvst(bgr2, (__m256i*)ptr, 32*2); -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x8& a, const v_uint32x8& b, const v_uint32x8& c, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) -{ - __m256i b0 = __lasx_xvshuf4i_w(a.val, 0x6c); - __m256i g0 = __lasx_xvshuf4i_w(b.val, 0xb1); - __m256i r0 = __lasx_xvshuf4i_w(c.val, 0xc6); - - __m256i bitmask_1 = _v256_set_w(-1, 0, 0, -1, 0, 0, -1, 0); - __m256i bitmask_2 = _v256_set_w(0, 0, -1, 0, 0, -1, 0, 0); - - __m256i p0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(b0, g0, bitmask_1), r0, bitmask_2); - __m256i p1 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(g0, r0, bitmask_1), b0, bitmask_2); - __m256i p2 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(r0, b0, bitmask_1), g0, bitmask_2); - - __m256i bgr0 = __lasx_xvpermi_q(p1, p0, 0 + 2*16); - __m256i bgr2 = __lasx_xvpermi_q(p1, p0, 1 + 3*16); - - __lasx_xvst(bgr0, (__m256i*)ptr, 0); - __lasx_xvst(p2, (__m256i*)ptr, 8*4); - __lasx_xvst(bgr2, (__m256i*)ptr, 16*4); -} - -inline void v_store_interleave( uint64* ptr, const v_uint64x4& a, const v_uint64x4& b, const v_uint64x4& c, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) -{ - __m256i s01 = __lasx_xvilvl_d(b.val, a.val); - __m256i s12 = __lasx_xvilvh_d(c.val, b.val); - __m256i s20 = __lasx_xvpermi_w(a.val, c.val, 0xe4); - - __m256i bgr0 = __lasx_xvpermi_q(s20, s01, 0 + 2*16); - __m256i bgr1 = __lasx_xvpermi_q(s01, s12, 0x30); - __m256i bgr2 = __lasx_xvpermi_q(s12, s20, 1 + 3*16); - - __lasx_xvst(bgr0, (__m256i*)ptr, 0); - __lasx_xvst(bgr1, (__m256i*)ptr, 4*8); - __lasx_xvst(bgr2, (__m256i*)ptr, 8*8); -} - -inline void v_store_interleave( uchar* ptr, const v_uint8x32& a, const v_uint8x32& b, - const v_uint8x32& c, const v_uint8x32& d, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) -{ - __m256i bg0 = __lasx_xvilvl_b(b.val, a.val); - __m256i bg1 = __lasx_xvilvh_b(b.val, a.val); - __m256i ra0 = __lasx_xvilvl_b(d.val, c.val); - __m256i ra1 = __lasx_xvilvh_b(d.val, c.val); - - __m256i bgra0_ = __lasx_xvilvl_h(ra0, bg0); - __m256i bgra1_ = __lasx_xvilvh_h(ra0, bg0); - __m256i bgra2_ = __lasx_xvilvl_h(ra1, bg1); - __m256i bgra3_ = __lasx_xvilvh_h(ra1, bg1); - - __m256i bgra0 = __lasx_xvpermi_q(bgra1_, bgra0_, 0 + 2*16); - __m256i bgra2 = __lasx_xvpermi_q(bgra1_, bgra0_, 1 + 3*16); - __m256i bgra1 = __lasx_xvpermi_q(bgra3_, bgra2_, 0 + 2*16); - __m256i bgra3 = __lasx_xvpermi_q(bgra3_, bgra2_, 1 + 3*16); - - __lasx_xvst(bgra0, (__m256i*)ptr, 0); - __lasx_xvst(bgra1, (__m256i*)ptr, 32); - __lasx_xvst(bgra2, (__m256i*)ptr, 64); - __lasx_xvst(bgra3, (__m256i*)ptr, 96); -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x16& a, const v_uint16x16& b, - const v_uint16x16& c, const v_uint16x16& d, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) -{ - __m256i bg0 = __lasx_xvilvl_h(b.val, a.val); - __m256i bg1 = __lasx_xvilvh_h(b.val, a.val); - __m256i ra0 = __lasx_xvilvl_h(d.val, c.val); - __m256i ra1 = __lasx_xvilvh_h(d.val, c.val); - - __m256i bgra0_ = __lasx_xvilvl_w(ra0, bg0); - __m256i bgra1_ = __lasx_xvilvh_w(ra0, bg0); - __m256i bgra2_ = __lasx_xvilvl_w(ra1, bg1); - __m256i bgra3_ = __lasx_xvilvh_w(ra1, bg1); - - __m256i bgra0 = __lasx_xvpermi_q(bgra1_, bgra0_, 0 + 2*16); - __m256i bgra2 = __lasx_xvpermi_q(bgra1_, bgra0_, 1 + 3*16); - __m256i bgra1 = __lasx_xvpermi_q(bgra3_, bgra2_, 0 + 2*16); - __m256i bgra3 = __lasx_xvpermi_q(bgra3_, bgra2_, 1 + 3*16); - - __lasx_xvst(bgra0, (__m256i*)ptr, 0); - __lasx_xvst(bgra1, (__m256i*)ptr, 16*2); - __lasx_xvst(bgra2, (__m256i*)ptr, 32*2); - __lasx_xvst(bgra3, (__m256i*)ptr, 48*2); -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x8& a, const v_uint32x8& b, - const v_uint32x8& c, const v_uint32x8& d, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) -{ - __m256i bg0 = __lasx_xvilvl_w(b.val, a.val); - __m256i bg1 = __lasx_xvilvh_w(b.val, a.val); - __m256i ra0 = __lasx_xvilvl_w(d.val, c.val); - __m256i ra1 = __lasx_xvilvh_w(d.val, c.val); - - __m256i bgra0_ = __lasx_xvilvl_d(ra0, bg0); - __m256i bgra1_ = __lasx_xvilvh_d(ra0, bg0); - __m256i bgra2_ = __lasx_xvilvl_d(ra1, bg1); - __m256i bgra3_ = __lasx_xvilvh_d(ra1, bg1); - - __m256i bgra0 = __lasx_xvpermi_q(bgra1_, bgra0_, 0 + 2*16); - __m256i bgra2 = __lasx_xvpermi_q(bgra1_, bgra0_, 1 + 3*16); - __m256i bgra1 = __lasx_xvpermi_q(bgra3_, bgra2_, 0 + 2*16); - __m256i bgra3 = __lasx_xvpermi_q(bgra3_, bgra2_, 1 + 3*16); - - __lasx_xvst(bgra0, (__m256i*)ptr, 0); - __lasx_xvst(bgra1, (__m256i*)ptr, 8*4); - __lasx_xvst(bgra2, (__m256i*)ptr, 16*4); - __lasx_xvst(bgra3, (__m256i*)ptr, 24*4); -} - -inline void v_store_interleave( uint64* ptr, const v_uint64x4& a, const v_uint64x4& b, - const v_uint64x4& c, const v_uint64x4& d, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) -{ - __m256i bg0 = __lasx_xvilvl_d(b.val, a.val); - __m256i bg1 = __lasx_xvilvh_d(b.val, a.val); - __m256i ra0 = __lasx_xvilvl_d(d.val, c.val); - __m256i ra1 = __lasx_xvilvh_d(d.val, c.val); - - __m256i bgra0 = __lasx_xvpermi_q(ra0, bg0, 0 + 2*16); - __m256i bgra1 = __lasx_xvpermi_q(ra1, bg1, 0 + 2*16); - __m256i bgra2 = __lasx_xvpermi_q(ra0, bg0, 1 + 3*16); - __m256i bgra3 = __lasx_xvpermi_q(ra1, bg1, 1 + 3*16); - - __lasx_xvst(bgra0, (__m256i*)ptr, 0); - __lasx_xvst(bgra1, (__m256i*)(ptr), 4*8); - __lasx_xvst(bgra2, (__m256i*)(ptr), 8*8); - __lasx_xvst(bgra3, (__m256i*)(ptr), 12*8); -} - - -#define OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(_Tpvec0, _Tp0, suffix0, _Tpvec1, _Tp1, suffix1) \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0 ) \ -{ \ - _Tpvec1 a1, b1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ -} \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0 ) \ -{ \ - _Tpvec1 a1, b1, c1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ - c0 = v_reinterpret_as_##suffix0(c1); \ -} \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0, _Tpvec0& d0 ) \ -{ \ - _Tpvec1 a1, b1, c1, d1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1, d1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ - c0 = v_reinterpret_as_##suffix0(c1); \ - d0 = v_reinterpret_as_##suffix0(d1); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - v_store_interleave((_Tp1*)ptr, a1, b1/*, mode*/); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, const _Tpvec0& c0, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, c1/*, mode*/); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - const _Tpvec0& c0, const _Tpvec0& d0, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ - _Tpvec1 d1 = v_reinterpret_as_##suffix1(d0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, c1, d1/*, mode*/); \ -} - -OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(v_int8x32, schar, s8, v_uint8x32, uchar, u8) -OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(v_int16x16, short, s16, v_uint16x16, ushort, u16) -OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(v_int32x8, int, s32, v_uint32x8, unsigned, u32) -OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(v_float32x8, float, f32, v_uint32x8, unsigned, u32) -OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(v_int64x4, int64, s64, v_uint64x4, uint64, u64) -OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(v_float64x4, double, f64, v_uint64x4, uint64, u64) - -// -// FP16 -// - -inline v_float32x8 v256_load_expand(const hfloat* ptr) -{ -#if CV_FP16 - //1-load128, 2-permi, 3-cvt - return v_float32x8(__lasx_xvfcvtl_s_h(__lasx_xvpermi_d(__lsx_vld((const __m128i*)ptr, 0), 0x10))); -#else - float CV_DECL_ALIGNED(32) buf[8]; - for (int i = 0; i < 8; i++) - buf[i] = (float)ptr[i]; - return v256_load_aligned(buf); -#endif -} - -inline void v_pack_store(hfloat* ptr, const v_float32x8& a) -{ -#if CV_FP16 - __m256i ah = __lasx_xvfcvt_h_s(a.val, a.val); - __lsx_vst((_m128i)ah, ptr, 0); -#else - float CV_DECL_ALIGNED(32) buf[8]; - v_store_aligned(buf, a); - for (int i = 0; i < 8; i++) - ptr[i] = hfloat(buf[i]); -#endif -} - -// -// end of FP16 -// - -inline void v256_cleanup() {} - -#include "intrin_math.hpp" -inline v_float32x8 v_exp(const v_float32x8& x) { return v_exp_default_32f(x); } -inline v_float32x8 v_log(const v_float32x8& x) { return v_log_default_32f(x); } -inline void v_sincos(const v_float32x8& x, v_float32x8& s, v_float32x8& c) { v_sincos_default_32f(x, s, c); } -inline v_float32x8 v_sin(const v_float32x8& x) { return v_sin_default_32f(x); } -inline v_float32x8 v_cos(const v_float32x8& x) { return v_cos_default_32f(x); } -inline v_float32x8 v_erf(const v_float32x8& x) { return v_erf_default_32f(x); } - -inline v_float64x4 v_exp(const v_float64x4& x) { return v_exp_default_64f(x); } -inline v_float64x4 v_log(const v_float64x4& x) { return v_log_default_64f(x); } -inline void v_sincos(const v_float64x4& x, v_float64x4& s, v_float64x4& c) { v_sincos_default_64f(x, s, c); } -inline v_float64x4 v_sin(const v_float64x4& x) { return v_sin_default_64f(x); } -inline v_float64x4 v_cos(const v_float64x4& x) { return v_cos_default_64f(x); } - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} // cv:: - -#endif // OPENCV_HAL_INTRIN_LASX_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +#ifndef OPENCV_HAL_INTRIN_LASX_HPP +#define OPENCV_HAL_INTRIN_LASX_HPP + +#include +#include + +#define CV_SIMD256 1 +#define CV_SIMD256_64F 1 +#define CV_SIMD256_FP16 0 + +namespace cv +{ + +//! @cond IGNORED + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +///////// Utils //////////// + +inline __m256i _v256_setr_b(char v0, char v1, char v2, char v3, char v4, char v5, char v6, char v7, char v8, char v9, + char v10, char v11, char v12, char v13, char v14, char v15, char v16, char v17, char v18, char v19, + char v20, char v21, char v22, char v23, char v24, char v25, char v26, char v27, char v28, char v29, + char v30, char v31) +{ + return (__m256i)v32i8{ v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, + v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, + v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, + v30, v31 }; +} + +inline __m256i _v256_set_b(char v0, char v1, char v2, char v3, char v4, char v5, char v6, char v7, char v8, char v9, + char v10, char v11, char v12, char v13, char v14, char v15, char v16, char v17, char v18, char v19, + char v20, char v21, char v22, char v23, char v24, char v25, char v26, char v27, char v28, char v29, + char v30, char v31) +{ + return (__m256i)v32i8{ v31, v30, + v29, v28, v27, v26, v25, v24, v23, v22, v21, v20, + v19, v18, v17, v16, v15, v14, v13, v12, v11, v10, + v9, v8, v7, v6, v5, v4, v3, v2, v1, v0 }; +} + +inline __m256i _v256_setr_h(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7, + short v8, short v9, short v10, short v11, short v12, short v13, short v14, short v15) +{ + return (__m256i)v16i16{ v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; +} + +inline __m256i _v256_setr_w(int v0, int v1, int v2, int v3, int v4, int v5, int v6, int v7) +{ + return (__m256i)v8i32{ v0, v1, v2, v3, v4, v5, v6, v7 }; +} + +inline __m256i _v256_set_w(int v0, int v1, int v2, int v3, int v4, int v5, int v6, int v7) +{ + return (__m256i)v8i32{ v7, v6, v5, v4, v3, v2, v1, v0 }; +} + +inline __m256i _v256_setall_w(int v0) +{ + return (__m256i)v8i32{ v0, v0, v0, v0, v0, v0, v0, v0 }; +} + +inline __m256i _v256_setr_d(int64 v0, int64 v1, int64 v2, int64 v3) +{ + return (__m256i)v4i64{ v0, v1, v2, v3 }; +} + +inline __m256i _v256_set_d(int64 v0, int64 v1, int64 v2, int64 v3) +{ + return (__m256i)v4i64{ v3, v2, v1, v0 }; +} + +inline __m256 _v256_setr_ps(float v0, float v1, float v2, float v3, float v4, float v5, float v6, float v7) +{ + return (__m256)v8f32{ v0, v1, v2, v3, v4, v5, v6, v7 }; +} + +inline __m256 _v256_setall_ps(float f32) +{ + return (__m256)v8f32{ f32, f32, f32, f32, f32, f32, f32, f32 }; +} + +inline __m256d _v256_setr_pd(double v0, double v1, double v2, double v3) +{ + return (__m256d)v4f64{ v0, v1, v2, v3 }; +} + +inline __m256d _v256_setall_pd(double f64) +{ + return (__m256d)v4f64{ f64, f64, f64, f64 }; +} + +inline __m256i _lasx_packus_h(const __m256i& a, const __m256i& b) +{ + return __lasx_xvssrarni_bu_h(b, a, 0); +} + +inline __m256i _lasx_packs_h(const __m256i& a, const __m256i& b) +{ + return __lasx_xvssrarni_b_h(b, a, 0); +} + +inline __m256i _lasx_packus_w(const __m256i& a, const __m256i& b) +{ + return __lasx_xvssrarni_hu_w(b, a, 0); +} + +inline __m256i _lasx_packs_w(const __m256i& a, const __m256i& b) +{ + return __lasx_xvssrarni_h_w(b, a, 0); +} + +inline __m256i _v256_combine(const __m128i& lo, const __m128i& hi) +{ return __lasx_xvpermi_q(*((__m256i*)&lo), *((__m256i*)&hi), 0x02); } + +inline __m256 _v256_combine(const __m128& lo, const __m128& hi) +{ return __m256(__lasx_xvpermi_q(*((__m256i*)&lo), *((__m256i*)&hi), 0x02)); } + +inline __m256d _v256_combine(const __m128d& lo, const __m128d& hi) +{ return __m256d(__lasx_xvpermi_q(*((__m256i*)&lo), *((__m256i*)&hi), 0x02)); } + +inline __m256i _v256_shuffle_odd_64(const __m256i& v) +{ return __lasx_xvpermi_d(v, 0xd8); } + +inline __m256d _v256_shuffle_odd_64(const __m256d& v) +{ return __m256d(__lasx_xvpermi_d(*((__m256i*)&v), 0xd8)); } + +//LASX: only use for permute WITHOUT zero clearing +template +inline __m256i _v256_permute2x128(const __m256i& a, const __m256i& b) +{ return __lasx_xvpermi_q(a, b, imm); } + +template +inline __m256 _v256_permute2x128(const __m256& a, const __m256& b) +{ return __m256(__lasx_xvpermi_q(*((__m256i*)&a), *((__m256i*)&b), imm)); } + +template +inline __m256d _v256_permute2x128(const __m256d& a, const __m256d& b) +{ return __m256d(__lasx_xvpermi_q(*((__m256i*)&a), *((__m256i*)&b), imm)); } + +template +inline _Tpvec v256_permute2x128(const _Tpvec& a, const _Tpvec& b) +{ return _Tpvec(_v256_permute2x128(a.val, b.val)); } + +template +inline __m256i _v256_permute4x64(const __m256i& a) +{ return __lasx_xvpermi_d(a, imm); } + +template +inline __m256d _v256_permute4x64(const __m256d& a) +{ return __m256d(__lasx_xvpermi_d(*((__m256i*)&a), imm)); } + +template +inline _Tpvec v256_permute4x64(const _Tpvec& a) +{ return _Tpvec(_v256_permute4x64(a.val)); } + +inline __m128i _v256_extract_high(const __m256i& v) +{ __m256i temp256i = __lasx_xvpermi_d(v, 0x4E); + return *((__m128i*)&temp256i); } + +inline __m128 _v256_extract_high(const __m256& v) +{ return __m128(_v256_extract_high(*((__m256i*)&v))); } + +inline __m128d _v256_extract_high(const __m256d& v) +{ return __m128d(_v256_extract_high(*((__m256i*)&v))); } + +inline __m128i _v256_extract_low(const __m256i& v) +{ return *((__m128i*)&v); } + +inline __m128 _v256_extract_low(const __m256& v) +{ return __m128(_v256_extract_low(*((__m256i*)&v))); } + +inline __m128d _v256_extract_low(const __m256d& v) +{ return __m128d(_v256_extract_low(*((__m256i*)&v))); } + +inline __m256i _v256_packs_epu32(const __m256i& a, const __m256i& b) +{ + return __lasx_xvssrlrni_hu_w(b, a, 0); +} + +template +inline int _v256_extract_b(const __m256i& a) +{ + int des[1] = {0}; + __lasx_xvstelm_b(a, des, 0, i); + return des[0]; +} + +template +inline int _v256_extract_h(const __m256i& a) +{ + int des[1] = {0}; + __lasx_xvstelm_h(a, des, 0, i); + return des[0]; +} + +template +inline int _v256_extract_w(const __m256i& a) +{ + return __lasx_xvpickve2gr_w(a, i); +} + +template +inline int64 _v256_extract_d(const __m256i& a) +{ + return __lasx_xvpickve2gr_d(a, i); +} + +///////// Types //////////// + +struct v_uint8x32 +{ + typedef uchar lane_type; + enum { nlanes = 32 }; + __m256i val; + + explicit v_uint8x32(__m256i v) : val(v) {} + v_uint8x32(uchar v0, uchar v1, uchar v2, uchar v3, + uchar v4, uchar v5, uchar v6, uchar v7, + uchar v8, uchar v9, uchar v10, uchar v11, + uchar v12, uchar v13, uchar v14, uchar v15, + uchar v16, uchar v17, uchar v18, uchar v19, + uchar v20, uchar v21, uchar v22, uchar v23, + uchar v24, uchar v25, uchar v26, uchar v27, + uchar v28, uchar v29, uchar v30, uchar v31) + { + val = _v256_setr_b((char)v0, (char)v1, (char)v2, (char)v3, + (char)v4, (char)v5, (char)v6 , (char)v7, (char)v8, (char)v9, + (char)v10, (char)v11, (char)v12, (char)v13, (char)v14, (char)v15, + (char)v16, (char)v17, (char)v18, (char)v19, (char)v20, (char)v21, + (char)v22, (char)v23, (char)v24, (char)v25, (char)v26, (char)v27, + (char)v28, (char)v29, (char)v30, (char)v31); + } + /* coverity[uninit_ctor]: suppress warning */ + v_uint8x32() {} + + uchar get0() const { + uchar des[1] = {0}; + __lasx_xvstelm_b(val, des, 0, 0); + return des[0]; + } +}; + +struct v_int8x32 +{ + typedef schar lane_type; + enum { nlanes = 32 }; + __m256i val; + + explicit v_int8x32(__m256i v) : val(v) {} + v_int8x32(schar v0, schar v1, schar v2, schar v3, + schar v4, schar v5, schar v6, schar v7, + schar v8, schar v9, schar v10, schar v11, + schar v12, schar v13, schar v14, schar v15, + schar v16, schar v17, schar v18, schar v19, + schar v20, schar v21, schar v22, schar v23, + schar v24, schar v25, schar v26, schar v27, + schar v28, schar v29, schar v30, schar v31) + { + val = _v256_setr_b(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, + v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, + v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31); + } + /* coverity[uninit_ctor]: suppress warning */ + v_int8x32() {} + + schar get0() const { + schar des[1] = {0}; + __lasx_xvstelm_b(val, des, 0, 0); + return des[0]; + } +}; + +struct v_uint16x16 +{ + typedef ushort lane_type; + enum { nlanes = 16 }; + __m256i val; + + explicit v_uint16x16(__m256i v) : val(v) {} + v_uint16x16(ushort v0, ushort v1, ushort v2, ushort v3, + ushort v4, ushort v5, ushort v6, ushort v7, + ushort v8, ushort v9, ushort v10, ushort v11, + ushort v12, ushort v13, ushort v14, ushort v15) + { + val = _v256_setr_h((short)v0, (short)v1, (short)v2, (short)v3, + (short)v4, (short)v5, (short)v6, (short)v7, (short)v8, (short)v9, + (short)v10, (short)v11, (short)v12, (short)v13, (short)v14, (short)v15); + } + /* coverity[uninit_ctor]: suppress warning */ + v_uint16x16() {} + + ushort get0() const { + ushort des[1] = {0}; + __lasx_xvstelm_h(val, des, 0, 0); + return des[0]; + } +}; + +struct v_int16x16 +{ + typedef short lane_type; + enum { nlanes = 16 }; + __m256i val; + + explicit v_int16x16(__m256i v) : val(v) {} + v_int16x16(short v0, short v1, short v2, short v3, + short v4, short v5, short v6, short v7, + short v8, short v9, short v10, short v11, + short v12, short v13, short v14, short v15) + { + val = _v256_setr_h(v0, v1, v2, v3, v4, v5, v6, v7, + v8, v9, v10, v11, v12, v13, v14, v15); + } + /* coverity[uninit_ctor]: suppress warning */ + v_int16x16() {} + + short get0() const { + short des[1] = {0}; + __lasx_xvstelm_h(val, des, 0, 0); + return des[0]; + } +}; + +struct v_uint32x8 +{ + typedef unsigned lane_type; + enum { nlanes = 8 }; + __m256i val; + + explicit v_uint32x8(__m256i v) : val(v) {} + v_uint32x8(unsigned v0, unsigned v1, unsigned v2, unsigned v3, + unsigned v4, unsigned v5, unsigned v6, unsigned v7) + { + val = _v256_setr_w((unsigned)v0, (unsigned)v1, (unsigned)v2, + (unsigned)v3, (unsigned)v4, (unsigned)v5, (unsigned)v6, (unsigned)v7); + } + /* coverity[uninit_ctor]: suppress warning */ + v_uint32x8() {} + + unsigned get0() const { return __lasx_xvpickve2gr_wu(val, 0); } +}; + +struct v_int32x8 +{ + typedef int lane_type; + enum { nlanes = 8 }; + __m256i val; + + explicit v_int32x8(__m256i v) : val(v) {} + v_int32x8(int v0, int v1, int v2, int v3, + int v4, int v5, int v6, int v7) + { + val = _v256_setr_w(v0, v1, v2, v3, v4, v5, v6, v7); + } + /* coverity[uninit_ctor]: suppress warning */ + v_int32x8() {} + + int get0() const { return __lasx_xvpickve2gr_w(val, 0); } +}; + +struct v_float32x8 +{ + typedef float lane_type; + enum { nlanes = 8 }; + __m256 val; + + explicit v_float32x8(__m256 v) : val(v) {} + explicit v_float32x8(__m256i v) { val = *((__m256*)&v); } + v_float32x8(float v0, float v1, float v2, float v3, + float v4, float v5, float v6, float v7) + { + val = _v256_setr_ps(v0, v1, v2, v3, v4, v5, v6, v7); + } + /* coverity[uninit_ctor]: suppress warning */ + v_float32x8() {} + + float get0() const { + float des[1] = {0}; + __lasx_xvstelm_w(*((__m256i*)&val), des, 0, 0); + return des[0]; + } + + int get0toint() const { + int des[1] = {0}; + __lasx_xvstelm_w(*((__m256i*)&val), des, 0, 0); + return des[0]; + } +}; + +struct v_uint64x4 +{ + typedef uint64 lane_type; + enum { nlanes = 4 }; + __m256i val; + + explicit v_uint64x4(__m256i v) : val(v) {} + v_uint64x4(uint64 v0, uint64 v1, uint64 v2, uint64 v3) + { val = _v256_setr_d((int64)v0, (int64)v1, (int64)v2, (int64)v3); } + /* coverity[uninit_ctor]: suppress warning */ + v_uint64x4() {} + + uint64 get0() const + { + return __lasx_xvpickve2gr_du(val, 0); + } +}; + +struct v_int64x4 +{ + typedef int64 lane_type; + enum { nlanes = 4 }; + __m256i val; + + explicit v_int64x4(__m256i v) : val(v) {} + v_int64x4(int64 v0, int64 v1, int64 v2, int64 v3) + { val = _v256_setr_d(v0, v1, v2, v3); } + /* coverity[uninit_ctor]: suppress warning */ + v_int64x4() {} + + int64 get0() const + { + return __lasx_xvpickve2gr_d(val, 0); + } +}; + +struct v_float64x4 +{ + typedef double lane_type; + enum { nlanes = 4 }; + __m256d val; + + explicit v_float64x4(__m256d v) : val(v) {} + explicit v_float64x4(__m256i v) { val = *((__m256d*)&v); } + v_float64x4(double v0, double v1, double v2, double v3) + { val = _v256_setr_pd(v0, v1, v2, v3); } + /* coverity[uninit_ctor]: suppress warning */ + v_float64x4() {} + + double get0() const { + double des[1] = {0}; + __lasx_xvstelm_d(*((__m256i*)&val), des, 0, 0); + return des[0]; + } + + int64 get0toint64() const { + int64 des[1] = {0}; + __lasx_xvstelm_d(*((__m256i*)&val), des, 0, 0); + return des[0]; + } +}; + +//////////////// Load and store operations /////////////// + +#define OPENCV_HAL_IMPL_LASX_LOADSTORE(_Tpvec, _Tp) \ + inline _Tpvec v256_load(const _Tp* ptr) \ + { return _Tpvec(__lasx_xvld(ptr, 0)); } \ + inline _Tpvec v256_load_aligned(const _Tp* ptr) \ + { return _Tpvec(__lasx_xvld(ptr, 0)); } \ + inline _Tpvec v256_load_low(const _Tp* ptr) \ + { \ + __m128i v128 = __lsx_vld(ptr, 0); \ + return _Tpvec(*((__m256i*)&v128)); \ + } \ + inline _Tpvec v256_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ + { \ + __m128i vlo = __lsx_vld(ptr0, 0); \ + __m128i vhi = __lsx_vld(ptr1, 0); \ + return _Tpvec(_v256_combine(vlo, vhi)); \ + } \ + inline void v_store(_Tp* ptr, const _Tpvec& a) \ + { __lasx_xvst(a.val, ptr, 0); } \ + inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ + { __lasx_xvst(a.val, ptr, 0); } \ + inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ + { __lasx_xvst(a.val, ptr, 0); } \ + inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ + { \ + if( mode == hal::STORE_UNALIGNED ) \ + __lasx_xvst(a.val, ptr, 0); \ + else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ + __lasx_xvst(a.val, ptr, 0); \ + else \ + __lasx_xvst(a.val, ptr, 0); \ + } \ + inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vst(_v256_extract_low(a.val), ptr, 0); } \ + inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vst(_v256_extract_high(a.val), ptr, 0); } + +OPENCV_HAL_IMPL_LASX_LOADSTORE(v_uint8x32, uchar) +OPENCV_HAL_IMPL_LASX_LOADSTORE(v_int8x32, schar) +OPENCV_HAL_IMPL_LASX_LOADSTORE(v_uint16x16, ushort) +OPENCV_HAL_IMPL_LASX_LOADSTORE(v_int16x16, short) +OPENCV_HAL_IMPL_LASX_LOADSTORE(v_uint32x8, unsigned) +OPENCV_HAL_IMPL_LASX_LOADSTORE(v_int32x8, int) +OPENCV_HAL_IMPL_LASX_LOADSTORE(v_uint64x4, uint64) +OPENCV_HAL_IMPL_LASX_LOADSTORE(v_int64x4, int64) + + +#define OPENCV_HAL_IMPL_LASX_LOADSTORE_FLT(_Tpvec, _Tp, halfreg) \ + inline _Tpvec v256_load(const _Tp* ptr) \ + { return _Tpvec(__lasx_xvld(ptr, 0)); } \ + inline _Tpvec v256_load_aligned(const _Tp* ptr) \ + { return _Tpvec(__lasx_xvld(ptr, 0)); } \ + inline _Tpvec v256_load_low(const _Tp* ptr) \ + { \ + __m128i v128 = __lsx_vld(ptr, 0); \ + return _Tpvec(*((__m256i*)&v128)); \ + } \ + inline _Tpvec v256_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ + { \ + halfreg vlo = __lsx_vld(ptr0, 0); \ + halfreg vhi = __lsx_vld(ptr1, 0); \ + return _Tpvec(_v256_combine(vlo, vhi)); \ + } \ + inline void v_store(_Tp* ptr, const _Tpvec& a) \ + { __lasx_xvst(a.val, ptr, 0); } \ + inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ + { __lasx_xvst(a.val, ptr, 0); } \ + inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ + { __lasx_xvst(a.val, ptr, 0); } \ + inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ + { \ + if( mode == hal::STORE_UNALIGNED ) \ + __lasx_xvst(a.val, ptr, 0); \ + else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ + __lasx_xvst(a.val, ptr, 0); \ + else \ + __lasx_xvst(a.val, ptr, 0); \ + } \ + inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vst(_v256_extract_low(a.val), ptr, 0); } \ + inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vst(_v256_extract_high(a.val), ptr, 0); } + +OPENCV_HAL_IMPL_LASX_LOADSTORE_FLT(v_float32x8, float, __m128i) +OPENCV_HAL_IMPL_LASX_LOADSTORE_FLT(v_float64x4, double, __m128i) + + +inline __m256i _lasx_256_castps_si256(const __m256& v) +{ return __m256i(v); } + +inline __m256i _lasx_256_castpd_si256(const __m256d& v) +{ return __m256i(v); } + +#define OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, _Tpvecf, suffix, cast) \ + inline _Tpvec v_reinterpret_as_##suffix(const _Tpvecf& a) \ + { return _Tpvec(cast(a.val)); } + +#define OPENCV_HAL_IMPL_LASX_INIT(_Tpvec, _Tp, suffix, ssuffix, ctype_s) \ + inline _Tpvec v256_setzero_##suffix() \ + { return _Tpvec(__lasx_xvreplgr2vr_d(0)); } \ + inline _Tpvec v256_setall_##suffix(_Tp v) \ + { return _Tpvec(__lasx_xvreplgr2vr_##ssuffix((ctype_s)v)); } \ + template <> inline _Tpvec v_setzero_() \ + { return v256_setzero_##suffix(); } \ + template <> inline _Tpvec v_setall_(_Tp v) \ + { return v256_setall_##suffix(v); } \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint8x32, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int8x32, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint16x16, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int16x16, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint32x8, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int32x8, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint64x4, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int64x4, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_float32x8, suffix, _lasx_256_castps_si256) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_float64x4, suffix, _lasx_256_castpd_si256) + +OPENCV_HAL_IMPL_LASX_INIT(v_uint8x32, uchar, u8, b, int) +OPENCV_HAL_IMPL_LASX_INIT(v_int8x32, schar, s8, b, int) +OPENCV_HAL_IMPL_LASX_INIT(v_uint16x16, ushort, u16, h, int) +OPENCV_HAL_IMPL_LASX_INIT(v_int16x16, short, s16, h, int) +OPENCV_HAL_IMPL_LASX_INIT(v_uint32x8, unsigned, u32, w, int) +OPENCV_HAL_IMPL_LASX_INIT(v_int32x8, int, s32, w, int) +OPENCV_HAL_IMPL_LASX_INIT(v_uint64x4, uint64, u64, d, long int) +OPENCV_HAL_IMPL_LASX_INIT(v_int64x4, int64, s64, d, long int) + + +inline __m256 _lasx_256_castsi256_ps(const __m256i &v) +{ return __m256(v); } + +inline __m256d _lasx_256_castsi256_pd(const __m256i &v) +{ return __m256d(v); } + +#define OPENCV_HAL_IMPL_LASX_INIT_FLT(_Tpvec, _Tp, suffix, zsuffix, cast) \ + inline _Tpvec v256_setzero_##suffix() \ + { return _Tpvec(__lasx_xvreplgr2vr_d(0)); } \ + inline _Tpvec v256_setall_##suffix(_Tp v) \ + { return _Tpvec(_v256_setall_##zsuffix(v)); } \ + template <> inline _Tpvec v_setzero_() \ + { return v256_setzero_##suffix(); } \ + template <> inline _Tpvec v_setall_(_Tp v) \ + { return v256_setall_##suffix(v); } \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint8x32, suffix, cast) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int8x32, suffix, cast) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint16x16, suffix, cast) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int16x16, suffix, cast) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint32x8, suffix, cast) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int32x8, suffix, cast) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint64x4, suffix, cast) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int64x4, suffix, cast) + +OPENCV_HAL_IMPL_LASX_INIT_FLT(v_float32x8, float, f32, ps, _lasx_256_castsi256_ps) +OPENCV_HAL_IMPL_LASX_INIT_FLT(v_float64x4, double, f64, pd, _lasx_256_castsi256_pd) + +inline v_float32x8 v_reinterpret_as_f32(const v_float32x8& a) +{ return a; } +inline v_float32x8 v_reinterpret_as_f32(const v_float64x4& a) +{ return v_float32x8(_lasx_256_castps_si256(__m256(a.val))); } + +inline v_float64x4 v_reinterpret_as_f64(const v_float64x4& a) +{ return a; } +inline v_float64x4 v_reinterpret_as_f64(const v_float32x8& a) +{ return v_float64x4(_lasx_256_castpd_si256(__m256d(a.val))); } + + +//////////////// Variant Value reordering /////////////// + +// unpacks +#define OPENCV_HAL_IMPL_LASX_UNPACK(_Tpvec, suffix) \ + inline _Tpvec v256_unpacklo(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(__lasx_xvilvl_##suffix(__m256i(b.val), __m256i(a.val))); } \ + inline _Tpvec v256_unpackhi(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(__lasx_xvilvh_##suffix(__m256i(b.val), __m256i(a.val))); } + +OPENCV_HAL_IMPL_LASX_UNPACK(v_uint8x32, b) +OPENCV_HAL_IMPL_LASX_UNPACK(v_int8x32, b) +OPENCV_HAL_IMPL_LASX_UNPACK(v_uint16x16, h) +OPENCV_HAL_IMPL_LASX_UNPACK(v_int16x16, h) +OPENCV_HAL_IMPL_LASX_UNPACK(v_uint32x8, w) +OPENCV_HAL_IMPL_LASX_UNPACK(v_int32x8, w) +OPENCV_HAL_IMPL_LASX_UNPACK(v_uint64x4, d) +OPENCV_HAL_IMPL_LASX_UNPACK(v_int64x4, d) +OPENCV_HAL_IMPL_LASX_UNPACK(v_float32x8, w) +OPENCV_HAL_IMPL_LASX_UNPACK(v_float64x4, d) + + +// shuffle +// todo: emulate 64bit +#define OPENCV_HAL_IMPL_LASX_SHUFFLE(_Tpvec, intrin) \ + template \ + inline _Tpvec v256_shuffle(const _Tpvec& a) \ + { return _Tpvec(__lasx_xvshuf4i_##intrin(a.val, m)); } + +OPENCV_HAL_IMPL_LASX_SHUFFLE(v_uint32x8, w) +OPENCV_HAL_IMPL_LASX_SHUFFLE(v_int32x8, w) + +template +inline v_float32x8 v256_shuffle(const v_float32x8 &a) +{ return v_float32x8(__lasx_xvshuf4i_w(*((__m256i*)&a.val), m)); } + +template +inline v_float64x4 v256_shuffle(const v_float64x4 &a) +{ + const int m1 = m & 0b1; + const int m2 = m & 0b10; + const int m3 = m & 0b100; + const int m4 = m & 0b1000; + const int m5 = m2 << 1; + const int m6 = m3 << 2; + const int m7 = m4 << 3; + const int m8 = m1 & m5 & m6 & m7; + + return v_float64x4(__lasx_xvshuf4i_d(*((__m256i*)&a.val), *((__m256i*)&a.val), m8)); +} + +template +inline void v256_zip(const _Tpvec& a, const _Tpvec& b, _Tpvec& ab0, _Tpvec& ab1) +{ + ab0 = v256_unpacklo(a, b); + ab1 = v256_unpackhi(a, b); +} + +template +inline _Tpvec v256_combine_diagonal(const _Tpvec& a, const _Tpvec& b) +{ return _Tpvec(__lasx_xvpermi_q(a.val, b.val, 0x12)); } + +inline v_float32x8 v256_combine_diagonal(const v_float32x8& a, const v_float32x8& b) +{ return v_float32x8(__lasx_xvpermi_q(a.val, b.val, 0x12)); } + +inline v_float64x4 v256_combine_diagonal(const v_float64x4& a, const v_float64x4& b) +{ return v_float64x4(__lasx_xvpermi_q(a.val, b.val, 0x12)); } + +template +inline _Tpvec v256_alignr_128(const _Tpvec& a, const _Tpvec& b) +{ return v256_permute2x128<0x03>(a, b); } + +inline __m256i _v256_alignr_b(const __m256i &a, const __m256i &b, const int imm) +{ + if (imm == 8) { + return __lasx_xvshuf4i_d(b, a, 0x9); // b.d1 a.d0 b.d3 a.d2 + } else { + __m256i byteIndex = _v256_setr_b(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); + return __lasx_xvshuf_b(a, b, __lasx_xvadd_b(__lasx_xvreplgr2vr_b(imm), byteIndex)); + } +} + +template +inline _Tpvec v256_alignr_64(const _Tpvec& a, const _Tpvec& b) +{ return _Tpvec(_v256_alignr_b(a.val, b.val, 8)); } +inline v_float64x4 v256_alignr_64(const v_float64x4& a, const v_float64x4& b) +{ return v_float64x4(__lasx_xvshuf4i_d(b.val, a.val, 0x9)); } // b.d1 a.d0 b.d3 a.d2 +// todo: emulate float32 + +template +inline _Tpvec v256_swap_halves(const _Tpvec& a) +{ return v256_permute2x128<1>(a, a); } + +template +inline _Tpvec v256_reverse_64(const _Tpvec& a) +{ return v256_permute4x64<0x1b>(a); } + + +// ZIP +#define OPENCV_HAL_IMPL_LASX_ZIP(_Tpvec) \ + inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ + { return v256_permute2x128<0x02>(a, b); } \ + inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ + { return v256_permute2x128<0x13>(a, b); } \ + inline void v_recombine(const _Tpvec& a, const _Tpvec& b, \ + _Tpvec& c, _Tpvec& d) \ + { \ + _Tpvec a1b0 = v256_alignr_128(a, b); \ + c = v256_combine_diagonal(a, a1b0); \ + d = v256_combine_diagonal(a1b0, b); \ + } \ + inline void v_zip(const _Tpvec& a, const _Tpvec& b, \ + _Tpvec& ab0, _Tpvec& ab1) \ + { \ + _Tpvec ab0ab2, ab1ab3; \ + v256_zip(a, b, ab0ab2, ab1ab3); \ + v_recombine(ab0ab2, ab1ab3, ab0, ab1); \ + } + +OPENCV_HAL_IMPL_LASX_ZIP(v_uint8x32) +OPENCV_HAL_IMPL_LASX_ZIP(v_int8x32) +OPENCV_HAL_IMPL_LASX_ZIP(v_uint16x16) +OPENCV_HAL_IMPL_LASX_ZIP(v_int16x16) +OPENCV_HAL_IMPL_LASX_ZIP(v_uint32x8) +OPENCV_HAL_IMPL_LASX_ZIP(v_int32x8) +OPENCV_HAL_IMPL_LASX_ZIP(v_uint64x4) +OPENCV_HAL_IMPL_LASX_ZIP(v_int64x4) +OPENCV_HAL_IMPL_LASX_ZIP(v_float32x8) +OPENCV_HAL_IMPL_LASX_ZIP(v_float64x4) + +////////// Arithmetic, bitwise and comparison operations ///////// + +/** Arithmetics **/ +#define OPENCV_HAL_IMPL_LASX_BIN_OP(bin_op, _Tpvec, intrin) \ + inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(intrin(a.val, b.val)); } + +OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_uint8x32, __lasx_xvsadd_bu) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_uint8x32, __lasx_xvssub_bu) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_int8x32, __lasx_xvsadd_b) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_int8x32, __lasx_xvssub_b) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_uint16x16, __lasx_xvsadd_hu) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_uint16x16, __lasx_xvssub_hu) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_int16x16, __lasx_xvsadd_h) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_int16x16, __lasx_xvssub_h) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_uint32x8, __lasx_xvadd_w) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_uint32x8, __lasx_xvsub_w) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_mul, v_uint32x8, __lasx_xvmul_w) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_int32x8, __lasx_xvadd_w) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_int32x8, __lasx_xvsub_w) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_mul, v_int32x8, __lasx_xvmul_w) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_uint64x4, __lasx_xvadd_d) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_uint64x4, __lasx_xvsub_d) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_int64x4, __lasx_xvadd_d) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_int64x4, __lasx_xvsub_d) + +OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_float32x8, __lasx_xvfadd_s) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_float32x8, __lasx_xvfsub_s) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_mul, v_float32x8, __lasx_xvfmul_s) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_div, v_float32x8, __lasx_xvfdiv_s) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_float64x4, __lasx_xvfadd_d) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_float64x4, __lasx_xvfsub_d) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_mul, v_float64x4, __lasx_xvfmul_d) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_div, v_float64x4, __lasx_xvfdiv_d) + +// saturating multiply 8-bit, 16-bit +inline v_uint8x32 v_mul(const v_uint8x32& a, const v_uint8x32& b) +{ + v_uint16x16 c, d; + v_mul_expand(a, b, c, d); + return v_pack(c, d); +} +inline v_int8x32 v_mul(const v_int8x32& a, const v_int8x32& b) +{ + v_int16x16 c, d; + v_mul_expand(a, b, c, d); + return v_pack(c, d); +} +inline v_uint16x16 v_mul(const v_uint16x16& a, const v_uint16x16& b) +{ + __m256i pl = __lasx_xvmul_h(a.val, b.val); + __m256i ph = __lasx_xvmuh_hu(a.val, b.val); + __m256i p0 = __lasx_xvilvl_h(ph, pl); + __m256i p1 = __lasx_xvilvh_h(ph, pl); + return v_uint16x16(_v256_packs_epu32(p0, p1)); +} +inline v_int16x16 v_mul(const v_int16x16& a, const v_int16x16& b) +{ + __m256i pl = __lasx_xvmul_h(a.val, b.val); + __m256i ph = __lasx_xvmuh_h(a.val, b.val); + __m256i p0 = __lasx_xvilvl_h(ph, pl); + __m256i p1 = __lasx_xvilvh_h(ph, pl); + return v_int16x16(_lasx_packs_w(p0, p1)); +} + +/** Non-saturating arithmetics **/ + +#define OPENCV_HAL_IMPL_LASX_BIN_FUNC(func, _Tpvec, intrin) \ + inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(intrin(a.val, b.val)); } + +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_add_wrap, v_uint8x32, __lasx_xvadd_b) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_add_wrap, v_int8x32, __lasx_xvadd_b) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_add_wrap, v_uint16x16, __lasx_xvadd_h) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_add_wrap, v_int16x16, __lasx_xvadd_h) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_sub_wrap, v_uint8x32, __lasx_xvsub_b) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_sub_wrap, v_int8x32, __lasx_xvsub_b) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_sub_wrap, v_uint16x16, __lasx_xvsub_h) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_sub_wrap, v_int16x16, __lasx_xvsub_h) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_mul_wrap, v_uint16x16, __lasx_xvmul_h) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_mul_wrap, v_int16x16, __lasx_xvmul_h) + +inline v_uint8x32 v_mul_wrap(const v_uint8x32& a, const v_uint8x32& b) +{ + __m256i p0 = __lasx_xvmulwev_h_bu(a.val, b.val); + __m256i p1 = __lasx_xvmulwod_h_bu(a.val, b.val); + return v_uint8x32(__lasx_xvpackev_b(p1, p0)); +} + +inline v_int8x32 v_mul_wrap(const v_int8x32& a, const v_int8x32& b) +{ + return v_reinterpret_as_s8(v_mul_wrap(v_reinterpret_as_u8(a), v_reinterpret_as_u8(b))); +} + +// Multiply and expand +inline void v_mul_expand(const v_uint8x32& a, const v_uint8x32& b, + v_uint16x16& c, v_uint16x16& d) +{ + v_uint16x16 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c = v_mul_wrap(a0, b0); + d = v_mul_wrap(a1, b1); +} + +inline void v_mul_expand(const v_int8x32& a, const v_int8x32& b, + v_int16x16& c, v_int16x16& d) +{ + v_int16x16 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c = v_mul_wrap(a0, b0); + d = v_mul_wrap(a1, b1); +} + +inline void v_mul_expand(const v_int16x16& a, const v_int16x16& b, + v_int32x8& c, v_int32x8& d) +{ + v_int16x16 vhi = v_int16x16(__lasx_xvmuh_h(a.val, b.val)); + + v_int16x16 v0, v1; + v_zip(v_mul_wrap(a, b), vhi, v0, v1); + + c = v_reinterpret_as_s32(v0); + d = v_reinterpret_as_s32(v1); +} + +inline void v_mul_expand(const v_uint16x16& a, const v_uint16x16& b, + v_uint32x8& c, v_uint32x8& d) +{ + v_uint16x16 vhi = v_uint16x16(__lasx_xvmuh_hu(a.val, b.val)); + + v_uint16x16 v0, v1; + v_zip(v_mul_wrap(a, b), vhi, v0, v1); + + c = v_reinterpret_as_u32(v0); + d = v_reinterpret_as_u32(v1); +} + +inline void v_mul_expand(const v_uint32x8& a, const v_uint32x8& b, + v_uint64x4& c, v_uint64x4& d) +{ + __m256i v0 = __lasx_xvmulwev_d_wu(a.val, b.val); + __m256i v1 = __lasx_xvmulwod_d_wu(a.val, b.val); + v_zip(v_uint64x4(v0), v_uint64x4(v1), c, d); +} + +inline v_int16x16 v_mul_hi(const v_int16x16& a, const v_int16x16& b) { return v_int16x16(__lasx_xvmuh_h(a.val, b.val)); } +inline v_uint16x16 v_mul_hi(const v_uint16x16& a, const v_uint16x16& b) { return v_uint16x16(__lasx_xvmuh_hu(a.val, b.val)); } + +/** Bitwise shifts **/ +#define OPENCV_HAL_IMPL_LASX_SHIFT_OP(_Tpuvec, _Tpsvec, suffix, srai) \ + inline _Tpuvec v_shl(const _Tpuvec& a, int imm) \ + { return _Tpuvec(__lasx_xvsll_##suffix(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ + inline _Tpsvec v_shl(const _Tpsvec& a, int imm) \ + { return _Tpsvec(__lasx_xvsll_##suffix(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ + inline _Tpuvec v_shr(const _Tpuvec& a, int imm) \ + { return _Tpuvec(__lasx_xvsrl_##suffix(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ + inline _Tpsvec v_shr(const _Tpsvec& a, int imm) \ + { return _Tpsvec(srai(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ + template \ + inline _Tpuvec v_shl(const _Tpuvec& a) \ + { return _Tpuvec(__lasx_xvsll_##suffix(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ + template \ + inline _Tpsvec v_shl(const _Tpsvec& a) \ + { return _Tpsvec(__lasx_xvsll_##suffix(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ + template \ + inline _Tpuvec v_shr(const _Tpuvec& a) \ + { return _Tpuvec(__lasx_xvsrl_##suffix(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ + template \ + inline _Tpsvec v_shr(const _Tpsvec& a) \ + { return _Tpsvec(srai(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } + +OPENCV_HAL_IMPL_LASX_SHIFT_OP(v_uint16x16, v_int16x16, h, __lasx_xvsra_h) +OPENCV_HAL_IMPL_LASX_SHIFT_OP(v_uint32x8, v_int32x8, w, __lasx_xvsra_w) +OPENCV_HAL_IMPL_LASX_SHIFT_OP(v_uint64x4, v_int64x4, d, __lasx_xvsra_d) + + +/** Bitwise logic **/ +#define OPENCV_HAL_IMPL_LASX_LOGIC_OP(_Tpvec, suffix, not_const) \ + OPENCV_HAL_IMPL_LASX_BIN_OP(v_and, _Tpvec, __lasx_xvand_##suffix) \ + OPENCV_HAL_IMPL_LASX_BIN_OP(v_or, _Tpvec, __lasx_xvor_##suffix) \ + OPENCV_HAL_IMPL_LASX_BIN_OP(v_xor, _Tpvec, __lasx_xvxor_##suffix) \ + inline _Tpvec v_not(const _Tpvec& a) \ + { return _Tpvec(__lasx_xvnori_b(a.val, 0)); } + +OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_uint8x32, v, __lasx_xvreplgr2vr_w(-1)) +OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_int8x32, v, __lasx_xvreplgr2vr_w(-1)) +OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_uint16x16, v, __lasx_xvreplgr2vr_w(-1)) +OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_int16x16, v, __lasx_xvreplgr2vr_w(-1)) +OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_uint32x8, v, __lasx_xvreplgr2vr_w(-1)) +OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_int32x8, v, __lasx_xvreplgr2vr_w(-1)) +OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_uint64x4, v, __lasx_xvreplgr2vr_d(-1)) +OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_int64x4, v, __lasx_xvreplgr2vr_d(-1)) + +#define OPENCV_HAL_IMPL_LASX_FLOAT_BIN_OP(bin_op, _Tpvec, intrin, cast) \ + inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(intrin(*((__m256i*)(&a.val)), *((__m256i*)(&b.val)))); } + +#define OPENCV_HAL_IMPL_LASX_FLOAT_LOGIC_OP(_Tpvec, suffix, not_const, cast) \ + OPENCV_HAL_IMPL_LASX_FLOAT_BIN_OP(v_and, _Tpvec, __lasx_xvand_##suffix, cast) \ + OPENCV_HAL_IMPL_LASX_FLOAT_BIN_OP(v_or, _Tpvec, __lasx_xvor_##suffix, cast) \ + OPENCV_HAL_IMPL_LASX_FLOAT_BIN_OP(v_xor, _Tpvec, __lasx_xvxor_##suffix, cast) \ + inline _Tpvec v_not(const _Tpvec& a) \ + { return _Tpvec(__lasx_xvxor_##suffix(*((__m256i*)(&a.val)), not_const)); } + +OPENCV_HAL_IMPL_LASX_FLOAT_LOGIC_OP(v_float32x8, v, __lasx_xvreplgr2vr_w(-1), _lasx_256_castsi256_ps) +OPENCV_HAL_IMPL_LASX_FLOAT_LOGIC_OP(v_float64x4, v, __lasx_xvreplgr2vr_d(-1), _lasx_256_castsi256_pd) + +/** Select **/ +#define OPENCV_HAL_IMPL_LASX_SELECT(_Tpvec) \ + inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(__lasx_xvbitsel_v(b.val, a.val, mask.val)); } + +OPENCV_HAL_IMPL_LASX_SELECT(v_uint8x32) +OPENCV_HAL_IMPL_LASX_SELECT(v_int8x32) +OPENCV_HAL_IMPL_LASX_SELECT(v_uint16x16) +OPENCV_HAL_IMPL_LASX_SELECT(v_int16x16) +OPENCV_HAL_IMPL_LASX_SELECT(v_uint32x8) +OPENCV_HAL_IMPL_LASX_SELECT(v_int32x8) + +inline v_float32x8 v_select(const v_float32x8 &mask, const v_float32x8 &a, const v_float32x8 &b) +{ return v_float32x8(__lasx_xvbitsel_v(*((__m256i*)&b.val), *((__m256i*)&a.val), *((__m256i*)&mask.val))); } + +inline v_float64x4 v_select(const v_float64x4 &mask, const v_float64x4 &a, const v_float64x4 &b) +{ return v_float64x4(__lasx_xvbitsel_v(*((__m256i*)&b.val), *((__m256i*)&a.val), *((__m256i*)&mask.val))); } + +/** Comparison **/ +#define OPENCV_HAL_IMPL_LASX_CMP_OP_OV(_Tpvec) \ + inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ + { return v_not(v_eq(a, b)); } \ + inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ + { return v_gt(b, a); } \ + inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ + { return v_not(v_lt(a, b)); } \ + inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ + { return v_ge(b, a); } + +#define OPENCV_HAL_IMPL_LASX_CMP_OP_INT(_Tpuvec, _Tpsvec, suffix, usuffix) \ + inline _Tpuvec v_eq(const _Tpuvec& a, const _Tpuvec& b) \ + { return _Tpuvec(__lasx_xvseq_##suffix(a.val, b.val)); } \ + inline _Tpuvec v_gt(const _Tpuvec& a, const _Tpuvec& b) \ + { \ + return _Tpuvec(__lasx_xvslt_##usuffix(b.val, a.val)); \ + } \ + inline _Tpsvec v_eq(const _Tpsvec& a, const _Tpsvec& b) \ + { return _Tpsvec(__lasx_xvseq_##suffix(a.val, b.val)); } \ + inline _Tpsvec v_gt(const _Tpsvec& a, const _Tpsvec& b) \ + { return _Tpsvec(__lasx_xvslt_##suffix(b.val, a.val)); } \ + OPENCV_HAL_IMPL_LASX_CMP_OP_OV(_Tpuvec) \ + OPENCV_HAL_IMPL_LASX_CMP_OP_OV(_Tpsvec) + +OPENCV_HAL_IMPL_LASX_CMP_OP_INT(v_uint8x32, v_int8x32, b, bu) +OPENCV_HAL_IMPL_LASX_CMP_OP_INT(v_uint16x16, v_int16x16, h, hu) +OPENCV_HAL_IMPL_LASX_CMP_OP_INT(v_uint32x8, v_int32x8, w, wu) + +#define OPENCV_HAL_IMPL_LASX_CMP_OP_64BIT(_Tpvec, suffix) \ + inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(__lasx_xvseq_##suffix(a.val, b.val)); } \ + inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ + { return v_not(v_eq(a, b)); } + +OPENCV_HAL_IMPL_LASX_CMP_OP_64BIT(v_uint64x4, d) +OPENCV_HAL_IMPL_LASX_CMP_OP_64BIT(v_int64x4, d) + +#define OPENCV_HAL_IMPL_LASX_CMP_FLT(bin_op, suffix, _Tpvec, ssuffix) \ + inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(__lasx_##suffix##_##ssuffix(a.val, b.val)); } + +#define OPENCV_HAL_IMPL_LASX_CMP_OP_FLT(_Tpvec, ssuffix) \ + OPENCV_HAL_IMPL_LASX_CMP_FLT(v_eq, xvfcmp_ceq, _Tpvec, ssuffix) \ + OPENCV_HAL_IMPL_LASX_CMP_FLT(v_ne, xvfcmp_cne, _Tpvec, ssuffix) \ + OPENCV_HAL_IMPL_LASX_CMP_FLT(v_lt, xvfcmp_clt, _Tpvec, ssuffix) \ + OPENCV_HAL_IMPL_LASX_CMP_FLT(v_le, xvfcmp_cle, _Tpvec, ssuffix) + +OPENCV_HAL_IMPL_LASX_CMP_OP_FLT(v_float32x8, s) +OPENCV_HAL_IMPL_LASX_CMP_OP_FLT(v_float64x4, d) + +inline v_float32x8 v_gt(const v_float32x8 &a, const v_float32x8 &b) +{ return v_float32x8(__lasx_xvfcmp_clt_s(b.val, a.val)); } + +inline v_float32x8 v_ge(const v_float32x8 &a, const v_float32x8 &b) +{ return v_float32x8(__lasx_xvfcmp_cle_s(b.val, a.val)); } + +inline v_float64x4 v_gt(const v_float64x4 &a, const v_float64x4 &b) +{ return v_float64x4(__lasx_xvfcmp_clt_d(b.val, a.val)); } + +inline v_float64x4 v_ge(const v_float64x4 &a, const v_float64x4 &b) +{ return v_float64x4(__lasx_xvfcmp_cle_d(b.val, a.val)); } + +inline v_float32x8 v_not_nan(const v_float32x8& a) +{ return v_float32x8(__lasx_xvfcmp_cor_s(a.val, a.val)); } +inline v_float64x4 v_not_nan(const v_float64x4& a) +{ return v_float64x4(__lasx_xvfcmp_cor_d(a.val, a.val)); } + +/** min/max **/ +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_uint8x32, __lasx_xvmin_bu) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_uint8x32, __lasx_xvmax_bu) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_int8x32, __lasx_xvmin_b) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_int8x32, __lasx_xvmax_b) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_uint16x16, __lasx_xvmin_hu) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_uint16x16, __lasx_xvmax_hu) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_int16x16, __lasx_xvmin_h) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_int16x16, __lasx_xvmax_h) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_uint32x8, __lasx_xvmin_wu) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_uint32x8, __lasx_xvmax_wu) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_int32x8, __lasx_xvmin_w) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_int32x8, __lasx_xvmax_w) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_float32x8, __lasx_xvfmin_s) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_float32x8, __lasx_xvfmax_s) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_float64x4, __lasx_xvfmin_d) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_float64x4, __lasx_xvfmax_d) + +/** Rotate **/ +template +inline v_uint8x32 v_rotate_left(const v_uint8x32& a, const v_uint8x32& b) +{ + enum {IMM_R = (16 - imm) & 0xFF}; + enum {IMM_R2 = (32 - imm) & 0xFF}; + + if (imm == 0) return a; + if (imm == 32) return b; + if (imm > 32) return v_uint8x32(); + + __m256i swap = _v256_permute2x128<0x21>(a.val, b.val); + if (imm == 16) return v_uint8x32(swap); + if (imm < 16) return v_uint8x32(_v256_alignr_b(a.val, swap, IMM_R)); + return v_uint8x32(_v256_alignr_b(swap, b.val, IMM_R2)); // imm < 32 +} + +template +inline v_uint8x32 v_rotate_right(const v_uint8x32& a, const v_uint8x32& b) +{ + enum {IMM_L = (imm - 16) & 0xFF}; + + if (imm == 0) return a; + if (imm == 32) return b; + if (imm > 32) return v_uint8x32(); + + __m256i swap = _v256_permute2x128<0x03>(a.val, b.val); + if (imm == 16) return v_uint8x32(swap); + if (imm < 16) return v_uint8x32(_v256_alignr_b(swap, a.val, imm)); + return v_uint8x32(_v256_alignr_b(b.val, swap, IMM_L)); +} + +template +inline v_uint8x32 v_rotate_left(const v_uint8x32& a) +{ + enum {IMM_L = ((imm - 16) & 0xFF) > 31 ? 31 : ((imm - 16) & 0xFF)}; + enum {IMM_R = (16 - imm) & 0xFF}; + + if (imm == 0) return a; + if (imm > 32) return v_uint8x32(); + + // ESAC control[3] ? [127:0] = 0 + __m256i vzero = __lasx_xvreplgr2vr_w(0); + __m256i swapz = __lasx_xvpermi_q(a.val, vzero, 0x20);; + if (imm == 16) return v_uint8x32(swapz); + if (imm < 16) return v_uint8x32(_v256_alignr_b(a.val, swapz, IMM_R)); + return v_uint8x32(__lasx_xvbsll_v(swapz, IMM_L)); +} + +template +inline v_uint8x32 v_rotate_right(const v_uint8x32& a) +{ + enum {IMM_L = ((imm - 16) & 0xFF) > 31 ? 31 : ((imm - 16) & 0xFF)}; + + if (imm == 0) return a; + if (imm > 32) return v_uint8x32(); + + // ESAC control[3] ? [127:0] = 0 + __m256i vzero = __lasx_xvreplgr2vr_w(0); + __m256i swapz = __lasx_xvpermi_q(vzero, a.val, 0x21);; + if (imm == 16) return v_uint8x32(swapz); + if (imm < 16) return v_uint8x32(_v256_alignr_b(swapz, a.val, imm)); + return v_uint8x32(__lasx_xvbsrl_v(swapz, IMM_L)); +} + +#define OPENCV_HAL_IMPL_LASX_ROTATE_CAST(intrin, _Tpvec, cast) \ + template \ + inline _Tpvec intrin(const _Tpvec& a, const _Tpvec& b) \ + { \ + enum {IMMxW = imm * sizeof(typename _Tpvec::lane_type)}; \ + v_uint8x32 ret = intrin(v_reinterpret_as_u8(a), \ + v_reinterpret_as_u8(b)); \ + return _Tpvec(cast(ret.val)); \ + } \ + template \ + inline _Tpvec intrin(const _Tpvec& a) \ + { \ + enum {IMMxW = imm * sizeof(typename _Tpvec::lane_type)}; \ + v_uint8x32 ret = intrin(v_reinterpret_as_u8(a)); \ + return _Tpvec(cast(ret.val)); \ + } + +#define OPENCV_HAL_IMPL_LASX_ROTATE(_Tpvec) \ + OPENCV_HAL_IMPL_LASX_ROTATE_CAST(v_rotate_left, _Tpvec, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LASX_ROTATE_CAST(v_rotate_right, _Tpvec, OPENCV_HAL_NOP) + +OPENCV_HAL_IMPL_LASX_ROTATE(v_int8x32) +OPENCV_HAL_IMPL_LASX_ROTATE(v_uint16x16) +OPENCV_HAL_IMPL_LASX_ROTATE(v_int16x16) +OPENCV_HAL_IMPL_LASX_ROTATE(v_uint32x8) +OPENCV_HAL_IMPL_LASX_ROTATE(v_int32x8) +OPENCV_HAL_IMPL_LASX_ROTATE(v_uint64x4) +OPENCV_HAL_IMPL_LASX_ROTATE(v_int64x4) + +OPENCV_HAL_IMPL_LASX_ROTATE_CAST(v_rotate_left, v_float32x8, _lasx_256_castsi256_ps) +OPENCV_HAL_IMPL_LASX_ROTATE_CAST(v_rotate_right, v_float32x8, _lasx_256_castsi256_ps) +OPENCV_HAL_IMPL_LASX_ROTATE_CAST(v_rotate_left, v_float64x4, _lasx_256_castsi256_pd) +OPENCV_HAL_IMPL_LASX_ROTATE_CAST(v_rotate_right, v_float64x4, _lasx_256_castsi256_pd) + +/** Reverse **/ +inline v_uint8x32 v_reverse(const v_uint8x32 &a) +{ + static const __m256i perm = _v256_setr_b( + 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, + 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); + __m256i vec = __lasx_xvshuf_b(a.val, a.val, perm); + return v_uint8x32(__lasx_xvpermi_q(vec, vec, 1)); +} + +inline v_int8x32 v_reverse(const v_int8x32 &a) +{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } + +inline v_uint16x16 v_reverse(const v_uint16x16 &a) +{ + __m256i vec = __lasx_xvshuf4i_h(a.val, 0x1B); + vec = __lasx_xvshuf4i_w(vec, 0x4E); + return v_uint16x16(__lasx_xvpermi_d(vec, 0x4E)); +} + +inline v_int16x16 v_reverse(const v_int16x16 &a) +{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } + +inline v_uint32x8 v_reverse(const v_uint32x8 &a) +{ + __m256i vec = __lasx_xvshuf4i_w(a.val, 0x1B); + return v_uint32x8(__lasx_xvpermi_d(vec, 0x4E)); +} + +inline v_int32x8 v_reverse(const v_int32x8 &a) +{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_float32x8 v_reverse(const v_float32x8 &a) +{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_uint64x4 v_reverse(const v_uint64x4 &a) +{ + return v_uint64x4(__lasx_xvpermi_d(a.val, 0x1b)); +} + +inline v_int64x4 v_reverse(const v_int64x4 &a) +{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } + +inline v_float64x4 v_reverse(const v_float64x4 &a) +{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } + +////////// Reduce and mask ///////// + +/** Reduce **/ +// this function is return a[0]+a[1]+...+a[31] +inline unsigned v_reduce_sum(const v_uint8x32& a) +{ + __m256i t1 = __lasx_xvhaddw_hu_bu(a.val, a.val); + __m256i t2 = __lasx_xvhaddw_wu_hu(t1, t1); + __m256i t3 = __lasx_xvhaddw_du_wu(t2, t2); + __m256i t4 = __lasx_xvhaddw_qu_du(t3, t3); + return (unsigned)(((v8u32)t4)[0]+((v8u32)t4)[4]); +} + +inline int v_reduce_sum(const v_int8x32& a) +{ + __m256i t1 = __lasx_xvhaddw_h_b(a.val, a.val); + __m256i t2 = __lasx_xvhaddw_w_h(t1, t1); + __m256i t3 = __lasx_xvhaddw_d_w(t2, t2); + __m256i t4 = __lasx_xvhaddw_q_d(t3, t3); + return (int)(((v8i32)t4)[0]+((v8i32)t4)[4]); +} + +#define OPENCV_HAL_IMPL_LASX_REDUCE_32(_Tpvec, sctype, func, intrin) \ + inline sctype v_reduce_##func(const _Tpvec& a) \ + { \ + __m128i val = intrin(_v256_extract_low(a.val), _v256_extract_high(a.val)); \ + val = intrin(val, __lsx_vbsrl_v(val,8)); \ + val = intrin(val, __lsx_vbsrl_v(val,4)); \ + val = intrin(val, __lsx_vbsrl_v(val,2)); \ + val = intrin(val, __lsx_vbsrl_v(val,1)); \ + return (sctype)__lsx_vpickve2gr_w(val, 0); \ + } + +OPENCV_HAL_IMPL_LASX_REDUCE_32(v_uint8x32, uchar, min, __lsx_vmin_bu) +OPENCV_HAL_IMPL_LASX_REDUCE_32(v_int8x32, schar, min, __lsx_vmin_b) +OPENCV_HAL_IMPL_LASX_REDUCE_32(v_uint8x32, uchar, max, __lsx_vmax_bu) +OPENCV_HAL_IMPL_LASX_REDUCE_32(v_int8x32, schar, max, __lsx_vmax_b) + +#define OPENCV_HAL_IMPL_LASX_REDUCE_16(_Tpvec, sctype, func, intrin) \ + inline sctype v_reduce_##func(const _Tpvec& a) \ + { \ + __m128i v0 = _v256_extract_low(a.val); \ + __m128i v1 = _v256_extract_high(a.val); \ + v0 = intrin(v0, v1); \ + v0 = intrin(v0, __lsx_vbsrl_v(v0, 8)); \ + v0 = intrin(v0, __lsx_vbsrl_v(v0, 4)); \ + v0 = intrin(v0, __lsx_vbsrl_v(v0, 2)); \ + return (sctype) __lsx_vpickve2gr_w(v0, 0); \ + } + +OPENCV_HAL_IMPL_LASX_REDUCE_16(v_uint16x16, ushort, min, __lsx_vmin_hu) +OPENCV_HAL_IMPL_LASX_REDUCE_16(v_int16x16, short, min, __lsx_vmin_h) +OPENCV_HAL_IMPL_LASX_REDUCE_16(v_uint16x16, ushort, max, __lsx_vmax_hu) +OPENCV_HAL_IMPL_LASX_REDUCE_16(v_int16x16, short, max, __lsx_vmax_h) + +#define OPENCV_HAL_IMPL_LASX_REDUCE_8(_Tpvec, sctype, func, intrin) \ + inline sctype v_reduce_##func(const _Tpvec& a) \ + { \ + __m128i v0 = _v256_extract_low(a.val); \ + __m128i v1 = _v256_extract_high(a.val); \ + v0 = intrin(v0, v1); \ + v0 = intrin(v0, __lsx_vbsrl_v(v0, 8)); \ + v0 = intrin(v0, __lsx_vbsrl_v(v0, 4)); \ + return (sctype) __lsx_vpickve2gr_w(v0, 0); \ + } + +OPENCV_HAL_IMPL_LASX_REDUCE_8(v_uint32x8, unsigned, min, __lsx_vmin_wu) +OPENCV_HAL_IMPL_LASX_REDUCE_8(v_int32x8, int, min, __lsx_vmin_w) +OPENCV_HAL_IMPL_LASX_REDUCE_8(v_uint32x8, unsigned, max, __lsx_vmax_wu) +OPENCV_HAL_IMPL_LASX_REDUCE_8(v_int32x8, int, max, __lsx_vmax_w) + +#define OPENCV_HAL_IMPL_LASX_REDUCE_FLT(func, intrin) \ + inline float v_reduce_##func(const v_float32x8& a) \ + { \ + __m128 v0 = _v256_extract_low(a.val); \ + __m128 v1 = _v256_extract_high(a.val); \ + v0 = intrin(v0, v1); \ + v0 = intrin(v0, __m128(__lsx_vpermi_w(*((__m128i*)&v0), *((__m128i*)&v0), 0x0e))); \ + v0 = intrin(v0, __m128(__lsx_vpermi_w(*((__m128i*)&v0), *((__m128i*)&v0), 0x01))); \ + float *fvalue = (float*)&v0; \ + return fvalue[0]; \ + } + +OPENCV_HAL_IMPL_LASX_REDUCE_FLT(min, __lsx_vfmin_s) +OPENCV_HAL_IMPL_LASX_REDUCE_FLT(max, __lsx_vfmax_s) + +inline int v_reduce_sum(const v_int32x8& a) +{ + __m256i t1 = __lasx_xvhaddw_d_w(a.val, a.val); + __m256i t2 = __lasx_xvhaddw_q_d(t1, t1); + return (int)(((v8i32)t2)[0]+((v8i32)t2)[4]); +} + +inline unsigned v_reduce_sum(const v_uint32x8& a) +{ return v_reduce_sum(v_reinterpret_as_s32(a)); } + +inline int v_reduce_sum(const v_int16x16& a) +{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } +inline unsigned v_reduce_sum(const v_uint16x16& a) +{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } + +inline float v_reduce_sum(const v_float32x8& a) +{ + float result = 0; + float *pa = (float*)&a; + for (int i = 0; i < 2; ++i) { + result += pa[i*4] + pa[i*4+1] + pa[i*4+2] + pa[i*4+3]; + } + return result; +} + +inline uint64 v_reduce_sum(const v_uint64x4& a) +{ + __m256i t0 = __lasx_xvhaddw_qu_du(a.val, a.val); + return (uint64)(((v4u64)t0)[0] + ((v4u64)t0)[2]); +} +inline int64 v_reduce_sum(const v_int64x4& a) +{ + __m256i t0 = __lasx_xvhaddw_q_d(a.val, a.val); + return (int64)(((v4i64)t0)[0] + ((v4i64)t0)[2]); +} +inline double v_reduce_sum(const v_float64x4& a) +{ + double *pa = (double*)&a; + return pa[0] + pa[1] + pa[2] + pa[3]; +} + +inline v_float32x8 v_reduce_sum4(const v_float32x8& a, const v_float32x8& b, + const v_float32x8& c, const v_float32x8& d) +{ + float *pa = (float*)&a; + float *pb = (float*)&b; + float *pc = (float*)&c; + float *pd = (float*)&d; + + float v0 = pa[0] + pa[1] + pa[2] + pa[3]; + float v1 = pb[0] + pb[1] + pb[2] + pb[3]; + float v2 = pc[0] + pc[1] + pc[2] + pc[3]; + float v3 = pd[0] + pd[1] + pd[2] + pd[3]; + float v4 = pa[4] + pa[5] + pa[6] + pa[7]; + float v5 = pb[4] + pb[5] + pb[6] + pb[7]; + float v6 = pc[4] + pc[5] + pc[6] + pc[7]; + float v7 = pd[4] + pd[5] + pd[6] + pd[7]; + return v_float32x8(v0, v1, v2, v3, v4, v5, v6, v7); +} + +inline unsigned v_reduce_sad(const v_uint8x32& a, const v_uint8x32& b) +{ + __m256i t0 = __lasx_xvabsd_bu(a.val, b.val); + __m256i t1 = __lasx_xvhaddw_hu_bu(t0, t0); + __m256i t2 = __lasx_xvhaddw_wu_hu(t1, t1); + __m256i t3 = __lasx_xvhaddw_du_wu(t2, t2); + __m256i t4 = __lasx_xvhaddw_qu_du(t3, t3); + return (unsigned)(((v8u32)t4)[0]+((v8u32)t4)[4]); +} +inline unsigned v_reduce_sad(const v_int8x32& a, const v_int8x32& b) +{ + __m256i t0 = __lasx_xvabsd_b(a.val, b.val); + __m256i t1 = __lasx_xvhaddw_hu_bu(t0, t0); + __m256i t2 = __lasx_xvhaddw_wu_hu(t1, t1); + __m256i t3 = __lasx_xvhaddw_du_wu(t2, t2); + __m256i t4 = __lasx_xvhaddw_qu_du(t3, t3); + return (unsigned)(((v8u32)t4)[0]+((v8u32)t4)[4]); +} +inline unsigned v_reduce_sad(const v_uint16x16& a, const v_uint16x16& b) +{ + v_uint32x8 l, h; + v_expand(v_add_wrap(v_sub(a, b), v_sub(b, a)), l, h); + return v_reduce_sum(v_add(l, h)); +} +inline unsigned v_reduce_sad(const v_int16x16& a, const v_int16x16& b) +{ + v_uint32x8 l, h; + v_expand(v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))), l, h); + return v_reduce_sum(v_add(l, h)); +} +inline unsigned v_reduce_sad(const v_uint32x8& a, const v_uint32x8& b) +{ + return v_reduce_sum(v_sub(v_max(a, b), v_min(a, b))); +} +inline unsigned v_reduce_sad(const v_int32x8& a, const v_int32x8& b) +{ + v_int32x8 m = v_lt(a, b); + return v_reduce_sum(v_reinterpret_as_u32(v_sub(v_xor(v_sub(a, b), m), m))); +} +inline float v_reduce_sad(const v_float32x8& a, const v_float32x8& b) +{ + v_float32x8 a_b = v_sub(a, b); + return v_reduce_sum(v_float32x8(*((__m256i*)&a_b.val) & __lasx_xvreplgr2vr_w(0x7fffffff))); +} + +/** Popcount **/ +inline v_uint8x32 v_popcount(const v_uint8x32& a) +{ return v_uint8x32(__lasx_xvpcnt_b(a.val)); } +inline v_uint16x16 v_popcount(const v_uint16x16& a) +{ return v_uint16x16(__lasx_xvpcnt_h(a.val)); } +inline v_uint32x8 v_popcount(const v_uint32x8& a) +{ return v_uint32x8(__lasx_xvpcnt_w(a.val)); } +inline v_uint64x4 v_popcount(const v_uint64x4& a) +{ return v_uint64x4(__lasx_xvpcnt_d(a.val)); } +inline v_uint8x32 v_popcount(const v_int8x32& a) +{ return v_popcount(v_reinterpret_as_u8(a)); } +inline v_uint16x16 v_popcount(const v_int16x16& a) +{ return v_popcount(v_reinterpret_as_u16(a)); } +inline v_uint32x8 v_popcount(const v_int32x8& a) +{ return v_popcount(v_reinterpret_as_u32(a)); } +inline v_uint64x4 v_popcount(const v_int64x4& a) +{ return v_popcount(v_reinterpret_as_u64(a)); } + +inline int v_signmask(const v_int8x32& a) +{ + __m256i result = __lasx_xvmskltz_b(a.val); + int mask = __lasx_xvpickve2gr_w(result, 0); + mask |= (__lasx_xvpickve2gr_w(result, 4) << 16); + return mask; +} +inline int v_signmask(const v_uint8x32& a) +{ return v_signmask(v_reinterpret_as_s8(a)); } + +inline int v_signmask(const v_int16x16& a) +{ return v_signmask(v_pack(a, a)) & 0xFFFF; } +inline int v_signmask(const v_uint16x16& a) +{ return v_signmask(v_reinterpret_as_s16(a)); } + +inline int v_signmask(const v_int32x8& a) +{ + __m256i result = __lasx_xvmskltz_w(a.val); + int mask = __lasx_xvpickve2gr_w(result, 0); + mask |= (__lasx_xvpickve2gr_w(result, 4) << 4); + return mask; +} +inline int v_signmask(const v_uint32x8& a) +{ return v_signmask(*(v_int32x8*)(&a)); } + +inline int v_signmask(const v_int64x4& a) +{ + __m256i result = __lasx_xvmskltz_d(a.val); + int mask = __lasx_xvpickve2gr_d(result, 0); + mask |= (__lasx_xvpickve2gr_w(result, 4) << 2); + return mask; +} +inline int v_signmask(const v_uint64x4& a) +{ return v_signmask(v_reinterpret_as_s64(a)); } + +inline int v_signmask(const v_float32x8& a) +{ return v_signmask(*(v_int32x8*)(&a)); } + +inline int v_signmask(const v_float64x4& a) +{ return v_signmask(*(v_int64x4*)(&a)); } + +inline int v_scan_forward(const v_int8x32& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } +inline int v_scan_forward(const v_uint8x32& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } +inline int v_scan_forward(const v_int16x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } +inline int v_scan_forward(const v_uint16x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } +inline int v_scan_forward(const v_int32x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_uint32x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_float32x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_int64x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } +inline int v_scan_forward(const v_uint64x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } +inline int v_scan_forward(const v_float64x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } + +/** Checks **/ +#define OPENCV_HAL_IMPL_LASX_CHECK(_Tpvec, allmask) \ + inline bool v_check_all(const _Tpvec& a) { return v_signmask(a) == allmask; } \ + inline bool v_check_any(const _Tpvec& a) { return v_signmask(a) != 0; } +OPENCV_HAL_IMPL_LASX_CHECK(v_uint8x32, -1) +OPENCV_HAL_IMPL_LASX_CHECK(v_int8x32, -1) +OPENCV_HAL_IMPL_LASX_CHECK(v_uint32x8, 255) +OPENCV_HAL_IMPL_LASX_CHECK(v_int32x8, 255) +OPENCV_HAL_IMPL_LASX_CHECK(v_uint64x4, 15) +OPENCV_HAL_IMPL_LASX_CHECK(v_int64x4, 15) +OPENCV_HAL_IMPL_LASX_CHECK(v_float32x8, 255) +OPENCV_HAL_IMPL_LASX_CHECK(v_float64x4, 15) + +#define OPENCV_HAL_IMPL_LASX_CHECK_SHORT(_Tpvec) \ + inline bool v_check_all(const _Tpvec& a) { return (v_signmask(v_reinterpret_as_s8(a)) & 0xaaaaaaaa) == 0xaaaaaaaa; } \ + inline bool v_check_any(const _Tpvec& a) { return (v_signmask(v_reinterpret_as_s8(a)) & 0xaaaaaaaa) != 0; } +OPENCV_HAL_IMPL_LASX_CHECK_SHORT(v_uint16x16) +OPENCV_HAL_IMPL_LASX_CHECK_SHORT(v_int16x16) + +////////// Other math ///////// + +/** Some frequent operations **/ +#define OPENCV_HAL_IMPL_LASX_MULADD(_Tpvec, suffix) \ + inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ + { return _Tpvec(__lasx_xvfmadd_##suffix(a.val, b.val, c.val)); } \ + inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ + { return _Tpvec(__lasx_xvfmadd_##suffix(a.val, b.val, c.val)); } \ + inline _Tpvec v_sqrt(const _Tpvec& x) \ + { return _Tpvec(__lasx_xvfsqrt_##suffix(x.val)); } \ + inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ + { return v_fma(a, a, v_mul(b, b)); } \ + inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ + { return v_sqrt(v_fma(a, a, v_mul(b, b))); } + +OPENCV_HAL_IMPL_LASX_MULADD(v_float32x8, s) +OPENCV_HAL_IMPL_LASX_MULADD(v_float64x4, d) + +inline v_int32x8 v_fma(const v_int32x8& a, const v_int32x8& b, const v_int32x8& c) +{ + return v_int32x8(__lasx_xvmadd_w(c.val, a.val, b.val)); +} + +inline v_int32x8 v_muladd(const v_int32x8& a, const v_int32x8& b, const v_int32x8& c) +{ + return v_fma(a, b, c); +} + +inline v_float32x8 v_invsqrt(const v_float32x8& x) +{ return v_float32x8(__lasx_xvfrsqrt_s(x.val)); } + +inline v_float64x4 v_invsqrt(const v_float64x4& x) +{ return v_float64x4(__lasx_xvfrsqrt_d(x.val)); } + +/** Absolute values **/ +#define OPENCV_HAL_IMPL_LASX_ABS(_Tpvec, suffix) \ + inline v_u##_Tpvec v_abs(const v_##_Tpvec& x) \ + { return v_u##_Tpvec(__lasx_xvabsd_##suffix(x.val, __lasx_xvreplgr2vr_w(0))); } + +OPENCV_HAL_IMPL_LASX_ABS(int8x32, b) +OPENCV_HAL_IMPL_LASX_ABS(int16x16, h) +OPENCV_HAL_IMPL_LASX_ABS(int32x8, w) + +inline v_float32x8 v_abs(const v_float32x8& x) +{ return v_float32x8(*((__m256i*)&x) & __lasx_xvreplgr2vr_w(0x7fffffff)); } +inline v_float64x4 v_abs(const v_float64x4& x) +{ return v_float64x4(*((__m256i*)&x) & __lasx_xvreplgr2vr_d(0x7fffffffffffffff)); } + +/** Absolute difference **/ +inline v_uint8x32 v_absdiff(const v_uint8x32& a, const v_uint8x32& b) +{ return (v_uint8x32)__lasx_xvabsd_bu(a.val, b.val); } +inline v_uint16x16 v_absdiff(const v_uint16x16& a, const v_uint16x16& b) +{ return (v_uint16x16)__lasx_xvabsd_hu(a.val, b.val); } +inline v_uint32x8 v_absdiff(const v_uint32x8& a, const v_uint32x8& b) +{ return (v_uint32x8)__lasx_xvabsd_wu(a.val, b.val); } + +inline v_uint8x32 v_absdiff(const v_int8x32& a, const v_int8x32& b) +{ return (v_uint8x32)__lasx_xvabsd_b(a.val, b.val); } +inline v_uint16x16 v_absdiff(const v_int16x16& a, const v_int16x16& b) +{ return (v_uint16x16)__lasx_xvabsd_h(a.val, b.val); } +inline v_uint32x8 v_absdiff(const v_int32x8& a, const v_int32x8& b) +{ return (v_uint32x8)__lasx_xvabsd_w(a.val, b.val); } + +inline v_float32x8 v_absdiff(const v_float32x8& a, const v_float32x8& b) +{ return v_abs(v_sub(a, b)); } + +inline v_float64x4 v_absdiff(const v_float64x4& a, const v_float64x4& b) +{ return v_abs(v_sub(a, b)); } + +/** Saturating absolute difference **/ +inline v_int8x32 v_absdiffs(const v_int8x32& a, const v_int8x32& b) +{ + v_int8x32 d = v_sub(a, b); + v_int8x32 m = v_lt(a, b); + return v_sub(v_xor(d, m), m); +} +inline v_int16x16 v_absdiffs(const v_int16x16& a, const v_int16x16& b) +{ return v_sub(v_max(a, b), v_min(a, b)); } + +////////// Conversions ///////// + +/** Rounding **/ +inline v_int32x8 v_round(const v_float32x8& a) +{ return v_int32x8(__lasx_xvftint_w_s(a.val)); } + +inline v_int32x8 v_round(const v_float64x4& a) +{ __m256i t = __lasx_xvftint_w_d(a.val, a.val); + return v_int32x8(__lasx_xvpermi_d(t, 0x88)); } + +inline v_int32x8 v_round(const v_float64x4& a, const v_float64x4& b) +{ + __m256i abi = __lasx_xvftint_w_d(b.val, a.val); + return v_int32x8(__lasx_xvpermi_d(abi, 0b11011000)); //3120 +} + +inline v_int32x8 v_trunc(const v_float32x8& a) +{ return v_int32x8(__lasx_xvftintrz_w_s(a.val)); } + +inline v_int32x8 v_trunc(const v_float64x4& a) +{ __m256i t = __lasx_xvftintrz_w_d(a.val, a.val); + return v_int32x8(__lasx_xvpermi_d(t, 0x88)); } + +inline v_int32x8 v_floor(const v_float32x8& a) +{ return v_int32x8(__lasx_xvftintrz_w_s(__m256(__lasx_xvfrintrm_s(a.val)))); } + +inline v_int32x8 v_floor(const v_float64x4& a) +{ return v_trunc(v_float64x4(__lasx_xvfrintrm_d(a.val))); } + +inline v_int32x8 v_ceil(const v_float32x8& a) +{ return v_int32x8(__lasx_xvftintrz_w_s(__m256(__lasx_xvfrintrp_s(a.val)))); } + +inline v_int32x8 v_ceil(const v_float64x4& a) +{ return v_trunc(v_float64x4(__lasx_xvfrintrp_d(a.val))); } + +/** To float **/ +inline v_float32x8 v_cvt_f32(const v_int32x8& a) +{ return v_float32x8(__lasx_xvffint_s_w(a.val)); } + +inline v_float32x8 v_cvt_f32(const v_float64x4& a) +{ return v_float32x8(__lasx_xvpermi_d(__lasx_xvfcvt_s_d(a.val, a.val), 0x88)); } + +inline v_float32x8 v_cvt_f32(const v_float64x4& a, const v_float64x4& b) +{ + __m256 abf = __lasx_xvfcvt_s_d(a.val, b.val); //warnning: order of a,b is diff from instruction xvfcvt.s.d + return v_float32x8(__lasx_xvpermi_d(abf, 0x8D)); +} + +inline v_float64x4 v_cvt_f64(const v_int32x8& a) +{ + __m256i alow = __lasx_xvpermi_d(a.val, 0x10); + return v_float64x4(__lasx_xvffintl_d_w(alow)); +} + +inline v_float64x4 v_cvt_f64_high(const v_int32x8& a) +{ + __m256i ahigh = __lasx_xvpermi_d(a.val, 0x32); + return v_float64x4(__lasx_xvffintl_d_w(ahigh)); +} + +inline v_float64x4 v_cvt_f64(const v_float32x8& a) +{ + __m256i alow = __lasx_xvpermi_d(a.val, 0x10); + return v_float64x4(__lasx_xvfcvtl_d_s((__m256)alow)); +} + +inline v_float64x4 v_cvt_f64_high(const v_float32x8& a) +{ + __m256i ahigh = __lasx_xvpermi_d(a.val, 0x32); + return v_float64x4(__lasx_xvfcvtl_d_s((__m256)ahigh)); +} + +inline v_float64x4 v_cvt_f64(const v_int64x4& v) +{ return v_float64x4(__lasx_xvffint_d_l(v.val)); } + +////////////// Lookup table access //////////////////// + +inline v_int8x32 v256_lut(const schar* tab, const int* idx) +{ + return v_int8x32(_v256_setr_b(tab[idx[ 0]], tab[idx[ 1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], tab[idx[ 5]], + tab[idx[ 6]], tab[idx[ 7]], tab[idx[ 8]], tab[idx[ 9]], tab[idx[10]], tab[idx[11]], + tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]], tab[idx[16]], tab[idx[17]], + tab[idx[18]], tab[idx[19]], tab[idx[20]], tab[idx[21]], tab[idx[22]], tab[idx[23]], + tab[idx[24]], tab[idx[25]], tab[idx[26]], tab[idx[27]], tab[idx[28]], tab[idx[29]], + tab[idx[30]], tab[idx[31]])); +} +inline v_int8x32 v256_lut_pairs(const schar* tab, const int* idx) +{ + return v_int8x32(_v256_setr_h(*(const short*)(tab + idx[ 0]), *(const short*)(tab + idx[ 1]), *(const short*)(tab + idx[ 2]), + *(const short*)(tab + idx[ 3]), *(const short*)(tab + idx[ 4]), *(const short*)(tab + idx[ 5]), + *(const short*)(tab + idx[ 6]), *(const short*)(tab + idx[ 7]), *(const short*)(tab + idx[ 8]), + *(const short*)(tab + idx[ 9]), *(const short*)(tab + idx[10]), *(const short*)(tab + idx[11]), + *(const short*)(tab + idx[12]), *(const short*)(tab + idx[13]), *(const short*)(tab + idx[14]), + *(const short*)(tab + idx[15]))); +} +inline v_int8x32 v256_lut_quads(const schar* tab, const int* idx) +{ + return v_int8x32(_v256_setr_w(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), + *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]), + *(const int*)(tab + idx[4]), *(const int*)(tab + idx[5]), + *(const int*)(tab + idx[6]), *(const int*)(tab + idx[7]))); +} +inline v_uint8x32 v256_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v256_lut((const schar *)tab, idx)); } +inline v_uint8x32 v256_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v256_lut_pairs((const schar *)tab, idx)); } +inline v_uint8x32 v256_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v256_lut_quads((const schar *)tab, idx)); } + +inline v_int16x16 v256_lut(const short* tab, const int* idx) +{ + return v_int16x16(_v256_setr_h(tab[idx[ 0]], tab[idx[ 1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], + tab[idx[ 5]], tab[idx[ 6]], tab[idx[ 7]], tab[idx[ 8]], tab[idx[ 9]], + tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], + tab[idx[15]])); +} +inline v_int16x16 v256_lut_pairs(const short* tab, const int* idx) +{ + return v_int16x16(_v256_setr_w(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), + *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]), + *(const int*)(tab + idx[4]), *(const int*)(tab + idx[5]), + *(const int*)(tab + idx[6]), *(const int*)(tab + idx[7]) )); +} +inline v_int16x16 v256_lut_quads(const short* tab, const int* idx) +{ + return v_int16x16(_v256_setr_d(*(const long long int*)(tab + idx[0]), *(const long long int*)(tab + idx[1]), + *(const long long int*)(tab + idx[2]), *(const long long int*)(tab + idx[3]) )); + +} +inline v_uint16x16 v256_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v256_lut((const short *)tab, idx)); } +inline v_uint16x16 v256_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v256_lut_pairs((const short *)tab, idx)); } +inline v_uint16x16 v256_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v256_lut_quads((const short *)tab, idx)); } + +inline v_int32x8 v256_lut(const int* tab, const int* idx) +{ + return v_int32x8(_v256_setr_w(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), + *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]), + *(const int*)(tab + idx[4]), *(const int*)(tab + idx[5]), + *(const int*)(tab + idx[6]), *(const int*)(tab + idx[7]) )); +} +inline v_int32x8 v256_lut_pairs(const int* tab, const int* idx) +{ + return v_int32x8(_v256_setr_d(*(const long long int*)(tab + idx[0]), *(const long long int*)(tab + idx[1]), + *(const long long int*)(tab + idx[2]), *(const long long int*)(tab + idx[3]) )); +} +inline v_int32x8 v256_lut_quads(const int* tab, const int* idx) +{ + return v_int32x8(_v256_combine(__lsx_vld(tab + idx[0], 0), __lsx_vld(tab + idx[1], 0))); +} +inline v_uint32x8 v256_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v256_lut((const int *)tab, idx)); } +inline v_uint32x8 v256_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v256_lut_pairs((const int *)tab, idx)); } +inline v_uint32x8 v256_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v256_lut_quads((const int *)tab, idx)); } + +inline v_int64x4 v256_lut(const int64* tab, const int* idx) +{ + return v_int64x4(_v256_setr_d(*(const long long int*)(tab + idx[0]), *(const long long int*)(tab + idx[1]), + *(const long long int*)(tab + idx[2]), *(const long long int*)(tab + idx[3]) )); +} +inline v_int64x4 v256_lut_pairs(const int64* tab, const int* idx) +{ + return v_int64x4(_v256_combine(__lsx_vld(tab + idx[0], 0), __lsx_vld(tab + idx[1], 0))); +} +inline v_uint64x4 v256_lut(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v256_lut((const int64 *)tab, idx)); } +inline v_uint64x4 v256_lut_pairs(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v256_lut_pairs((const int64 *)tab, idx)); } + +inline v_float32x8 v256_lut(const float* tab, const int* idx) +{ + return v_float32x8(_v256_setr_ps(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], + tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]])); +} +inline v_float32x8 v256_lut_pairs(const float* tab, const int* idx) { return v_reinterpret_as_f32(v256_lut_pairs((const int *)tab, idx)); } +inline v_float32x8 v256_lut_quads(const float* tab, const int* idx) { return v_reinterpret_as_f32(v256_lut_quads((const int *)tab, idx)); } + +inline v_float64x4 v256_lut(const double* tab, const int* idx) +{ + return v_float64x4(_v256_setr_pd(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]])); +} +inline v_float64x4 v256_lut_pairs(const double* tab, const int* idx) +{ return v_float64x4(_v256_combine(__lsx_vld(tab + idx[0], 0), __lsx_vld(tab + idx[1], 0))); } + +inline v_int32x8 v_lut(const int* tab, const v_int32x8& idxvec) +{ + int *idx = (int*)&idxvec.val; + return v256_lut(tab, idx); +} + +inline v_uint32x8 v_lut(const unsigned* tab, const v_int32x8& idxvec) +{ + return v_reinterpret_as_u32(v_lut((const int *)tab, idxvec)); +} + +inline v_float32x8 v_lut(const float* tab, const v_int32x8& idxvec) +{ + const int *idx = (const int*)&idxvec.val; + return v256_lut(tab, idx); +} + +inline v_float64x4 v_lut(const double* tab, const v_int32x8& idxvec) +{ + const int *idx = (const int*)&idxvec.val; + return v256_lut(tab, idx); +} + +inline void v_lut_deinterleave(const float* tab, const v_int32x8& idxvec, v_float32x8& x, v_float32x8& y) +{ + const int *idx = (const int*)&idxvec.val; + __m128i xy01, xy45, xy23, xy67; + xy01 = __lsx_vld(tab + idx[0], 0); + xy01 = __lsx_vextrins_d(xy01, __lsx_vld(tab + idx[1], 0), 0x10); + xy45 = __lsx_vld(tab + idx[4], 0); + xy45 = __lsx_vextrins_d(xy45, __lsx_vld(tab + idx[5], 0), 0x10); + __m256i xy0145 = _v256_combine(xy01, xy45); + xy23 = __lsx_vld(tab + idx[2], 0); + xy23 = __lsx_vextrins_d(xy23, __lsx_vld(tab + idx[3], 0), 0x10); + xy67 = __lsx_vld(tab + idx[6], 0); + xy67 = __lsx_vextrins_d(xy67, __lsx_vld(tab + idx[7], 0), 0x10); + __m256i xy2367 = _v256_combine(xy23, xy67); + + __m256i xxyy0145 = __lasx_xvilvl_w(xy2367, xy0145); + __m256i xxyy2367 = __lasx_xvilvh_w(xy2367, xy0145); + + x = v_float32x8(__lasx_xvilvl_w(xxyy2367, xxyy0145)); + y = v_float32x8(__lasx_xvilvh_w(xxyy2367, xxyy0145)); +} + +inline void v_lut_deinterleave(const double* tab, const v_int32x8& idxvec, v_float64x4& x, v_float64x4& y) +{ + //int CV_DECL_ALIGNED(32) idx[4]; + const int *idx = (const int*)&idxvec.val; + __m128i xy0 = __lsx_vld(tab + idx[0], 0); + __m128i xy2 = __lsx_vld(tab + idx[2], 0); + __m128i xy1 = __lsx_vld(tab + idx[1], 0); + __m128i xy3 = __lsx_vld(tab + idx[3], 0); + __m256i xy02 = _v256_combine(xy0, xy2); + __m256i xy13 = _v256_combine(xy1, xy3); + + x = v_float64x4(__lasx_xvilvl_d(xy13, xy02)); + y = v_float64x4(__lasx_xvilvh_d(xy13, xy02)); +} + +inline v_int8x32 v_interleave_pairs(const v_int8x32& vec) +{ + return v_int8x32(__lasx_xvshuf_b(vec.val, vec.val, + _v256_set_d(0x0f0d0e0c0b090a08, 0x0705060403010200, 0x0f0d0e0c0b090a08, 0x0705060403010200))); +} +inline v_uint8x32 v_interleave_pairs(const v_uint8x32& vec) +{ return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } +inline v_int8x32 v_interleave_quads(const v_int8x32& vec) +{ + return v_int8x32(__lasx_xvshuf_b(vec.val, vec.val, + _v256_set_d(0x0f0b0e0a0d090c08, 0x0703060205010400, 0x0f0b0e0a0d090c08, 0x0703060205010400))); +} +inline v_uint8x32 v_interleave_quads(const v_uint8x32& vec) +{ return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } + +inline v_int16x16 v_interleave_pairs(const v_int16x16& vec) +{ + return v_int16x16(__lasx_xvshuf_b(vec.val, vec.val, + _v256_set_d(0x0f0e0b0a0d0c0908, 0x0706030205040100, 0x0f0e0b0a0d0c0908, 0x0706030205040100))); +} +inline v_uint16x16 v_interleave_pairs(const v_uint16x16& vec) +{ return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } +inline v_int16x16 v_interleave_quads(const v_int16x16& vec) +{ + return v_int16x16(__lasx_xvshuf_b(vec.val, vec.val, + _v256_set_d(0x0f0e07060d0c0504, 0x0b0a030209080100, 0x0f0e07060d0c0504, 0x0b0a030209080100))); +} +inline v_uint16x16 v_interleave_quads(const v_uint16x16& vec) +{ return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } + +inline v_int32x8 v_interleave_pairs(const v_int32x8& vec) +{ + return v_int32x8(__lasx_xvshuf4i_w(vec.val, 0xd8)); +} +inline v_uint32x8 v_interleave_pairs(const v_uint32x8& vec) +{ return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } +inline v_float32x8 v_interleave_pairs(const v_float32x8& vec) +{ return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } + +inline v_int8x32 v_pack_triplets(const v_int8x32& vec) +{ + __m256i vzero = __lasx_xvreplgr2vr_w(0); + __m256i t1 = __lasx_xvshuf_b(vzero, vec.val, + _v256_set_d(0x1211100f0e0d0c0a, 0x0908060504020100, 0x1211100f0e0d0c0a, 0x0908060504020100)); + return v_int8x32(__lasx_xvperm_w(t1, + _v256_set_d(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); +} +inline v_uint8x32 v_pack_triplets(const v_uint8x32& vec) +{ return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } + +inline v_int16x16 v_pack_triplets(const v_int16x16& vec) +{ + __m256i vzero = __lasx_xvreplgr2vr_w(0); + __m256i t1 = __lasx_xvshuf_b(vzero, vec.val, + _v256_set_d(0x11100f0e0d0c0b0a, 0x0908050403020100, 0x11100f0e0d0c0b0a, 0x0908050403020100)); + return v_int16x16(__lasx_xvperm_w(t1, + _v256_set_d(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); +} +inline v_uint16x16 v_pack_triplets(const v_uint16x16& vec) +{ return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } + +inline v_int32x8 v_pack_triplets(const v_int32x8& vec) +{ + return v_int32x8(__lasx_xvperm_w(vec.val, + _v256_set_d(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); +} +inline v_uint32x8 v_pack_triplets(const v_uint32x8& vec) +{ return v_reinterpret_as_u32(v_pack_triplets(v_reinterpret_as_s32(vec))); } +inline v_float32x8 v_pack_triplets(const v_float32x8& vec) +{ + return v_float32x8(__lasx_xvperm_w(*(__m256i*)(&vec.val), + _v256_set_d(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); +} + +////////// Matrix operations ///////// + +//////// Dot Product //////// + +// 16 >> 32 +inline v_int32x8 v_dotprod(const v_int16x16& a, const v_int16x16& b) +{ return v_int32x8(__lasx_xvadd_w(__lasx_xvmulwev_w_h(a.val, b.val), __lasx_xvmulwod_w_h(a.val, b.val))); } + +inline v_int32x8 v_dotprod(const v_int16x16& a, const v_int16x16& b, const v_int32x8& c) +{ return v_add(v_dotprod(a, b), c); } + +// 32 >> 64 +inline v_int64x4 v_dotprod(const v_int32x8& a, const v_int32x8& b) +{ + __m256i even = __lasx_xvmulwev_d_w(a.val, b.val); + return v_int64x4(__lasx_xvmaddwod_d_w(even, a.val, b.val)); +} +inline v_int64x4 v_dotprod(const v_int32x8& a, const v_int32x8& b, const v_int64x4& c) +{ + __m256i even = __lasx_xvmaddwev_d_w(c.val, a.val, b.val); + return v_int64x4(__lasx_xvmaddwod_d_w(even, a.val, b.val)); +} + +// 8 >> 32 +inline v_uint32x8 v_dotprod_expand(const v_uint8x32& a, const v_uint8x32& b) +{ + __m256i even = __lasx_xvmulwev_h_bu(a.val, b.val); + __m256i odd = __lasx_xvmulwod_h_bu(a.val, b.val); + __m256i prod0 = __lasx_xvhaddw_wu_hu(even, even); + __m256i prod1 = __lasx_xvhaddw_wu_hu(odd, odd); + return v_uint32x8(__lasx_xvadd_w(prod0, prod1)); +} +inline v_uint32x8 v_dotprod_expand(const v_uint8x32& a, const v_uint8x32& b, const v_uint32x8& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int32x8 v_dotprod_expand(const v_int8x32& a, const v_int8x32& b) +{ + __m256i even = __lasx_xvmulwev_h_b(a.val, b.val); + __m256i odd = __lasx_xvmulwod_h_b(a.val, b.val); + __m256i prod0 = __lasx_xvhaddw_w_h(even, even); + __m256i prod1 = __lasx_xvhaddw_w_h(odd, odd); + return v_int32x8(__lasx_xvadd_w(prod0, prod1)); +} +inline v_int32x8 v_dotprod_expand(const v_int8x32& a, const v_int8x32& b, const v_int32x8& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 16 >> 64 +inline v_uint64x4 v_dotprod_expand(const v_uint16x16& a, const v_uint16x16& b) +{ + __m256i even = __lasx_xvmulwev_w_hu(a.val, b.val); + __m256i odd = __lasx_xvmulwod_w_hu(a.val, b.val); + __m256i prod0 = __lasx_xvhaddw_du_wu(even, even); + __m256i prod1 = __lasx_xvhaddw_du_wu(odd, odd); + return v_uint64x4(__lasx_xvadd_d(prod0, prod1)); +} +inline v_uint64x4 v_dotprod_expand(const v_uint16x16& a, const v_uint16x16& b, const v_uint64x4& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int64x4 v_dotprod_expand(const v_int16x16& a, const v_int16x16& b) +{ + __m256i even = __lasx_xvmulwev_w_h(a.val, b.val); + __m256i odd = __lasx_xvmulwod_w_h(a.val, b.val); + __m256i prod0 = __lasx_xvhaddw_d_w(even, even); + __m256i prod1 = __lasx_xvhaddw_d_w(odd, odd); + return v_int64x4(__lasx_xvadd_d(prod0, prod1)); +} + +inline v_int64x4 v_dotprod_expand(const v_int16x16& a, const v_int16x16& b, const v_int64x4& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 32 >> 64f +inline v_float64x4 v_dotprod_expand(const v_int32x8& a, const v_int32x8& b) +{ return v_cvt_f64(v_dotprod(a, b)); } +inline v_float64x4 v_dotprod_expand(const v_int32x8& a, const v_int32x8& b, const v_float64x4& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +//////// Fast Dot Product //////// + +// 16 >> 32 +inline v_int32x8 v_dotprod_fast(const v_int16x16& a, const v_int16x16& b) +{ return v_dotprod(a, b); } +inline v_int32x8 v_dotprod_fast(const v_int16x16& a, const v_int16x16& b, const v_int32x8& c) +{ return v_dotprod(a, b, c); } + +// 32 >> 64 +inline v_int64x4 v_dotprod_fast(const v_int32x8& a, const v_int32x8& b) +{ return v_dotprod(a, b); } +inline v_int64x4 v_dotprod_fast(const v_int32x8& a, const v_int32x8& b, const v_int64x4& c) +{ return v_dotprod(a, b, c); } + +// 8 >> 32 +inline v_uint32x8 v_dotprod_expand_fast(const v_uint8x32& a, const v_uint8x32& b) +{ return v_dotprod_expand(a, b); } +inline v_uint32x8 v_dotprod_expand_fast(const v_uint8x32& a, const v_uint8x32& b, const v_uint32x8& c) +{ return v_dotprod_expand(a, b, c); } + +inline v_int32x8 v_dotprod_expand_fast(const v_int8x32& a, const v_int8x32& b) +{ return v_dotprod_expand(a, b); } +inline v_int32x8 v_dotprod_expand_fast(const v_int8x32& a, const v_int8x32& b, const v_int32x8& c) +{ return v_dotprod_expand(a, b, c); } + +// 16 >> 64 +inline v_uint64x4 v_dotprod_expand_fast(const v_uint16x16& a, const v_uint16x16& b) +{ + __m256i even = __lasx_xvmulwev_w_hu(a.val, b.val); + __m256i odd = __lasx_xvmulwod_w_hu(a.val, b.val); + __m256i prod0 = __lasx_xvhaddw_du_wu(even, even); + __m256i prod1 = __lasx_xvhaddw_du_wu(odd, odd); + return v_uint64x4(__lasx_xvadd_d(__lasx_xvilvl_d(prod1, prod0), __lasx_xvilvh_d(prod1, prod0))); +} +inline v_uint64x4 v_dotprod_expand_fast(const v_uint16x16& a, const v_uint16x16& b, const v_uint64x4& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +inline v_int64x4 v_dotprod_expand_fast(const v_int16x16& a, const v_int16x16& b) +{ + __m256i prod = __lasx_xvadd_w(__lasx_xvmulwev_w_h(a.val, b.val), __lasx_xvmulwod_w_h(a.val, b.val)); + __m256i sign = __lasx_xvsrai_w(prod, 31); + __m256i lo = __lasx_xvilvl_w(sign, prod); + __m256i hi = __lasx_xvilvh_w(sign, prod); + return v_int64x4(__lasx_xvadd_d(lo, hi)); +} +inline v_int64x4 v_dotprod_expand_fast(const v_int16x16& a, const v_int16x16& b, const v_int64x4& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +// 32 >> 64f +inline v_float64x4 v_dotprod_expand_fast(const v_int32x8& a, const v_int32x8& b) +{ return v_dotprod_expand(a, b); } +inline v_float64x4 v_dotprod_expand_fast(const v_int32x8& a, const v_int32x8& b, const v_float64x4& c) +{ return v_dotprod_expand(a, b, c); } + + +#define OPENCV_HAL_LASX_SPLAT2_PS(a, im) \ + v_float32x8(__lasx_xvpermi_w(a.val, a.val, im)) + +inline v_float32x8 v_matmul(const v_float32x8& v, const v_float32x8& m0, + const v_float32x8& m1, const v_float32x8& m2, + const v_float32x8& m3) +{ + v_float32x8 v04 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0); + v_float32x8 v15 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0x55); + v_float32x8 v26 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0xAA); + v_float32x8 v37 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0xFF); + return v_fma(v04, m0, v_fma(v15, m1, v_fma(v26, m2, v_mul(v37, m3)))); +} + +inline v_float32x8 v_matmuladd(const v_float32x8& v, const v_float32x8& m0, + const v_float32x8& m1, const v_float32x8& m2, + const v_float32x8& a) +{ + v_float32x8 v04 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0); + v_float32x8 v15 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0x55); + v_float32x8 v26 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0xAA); + return v_fma(v04, m0, v_fma(v15, m1, v_fma(v26, m2, a))); +} + + +#define OPENCV_HAL_IMPL_LASX_TRANSPOSE4x4(_Tpvec, cast_from, cast_to) \ + inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ + const _Tpvec& a2, const _Tpvec& a3, \ + _Tpvec& b0, _Tpvec& b1, _Tpvec& b2, _Tpvec& b3) \ + { \ + __m256i t0 = cast_from(__lasx_xvilvl_w(a1.val, a0.val)); \ + __m256i t1 = cast_from(__lasx_xvilvl_w(a3.val, a2.val)); \ + __m256i t2 = cast_from(__lasx_xvilvh_w(a1.val, a0.val)); \ + __m256i t3 = cast_from(__lasx_xvilvh_w(a3.val, a2.val)); \ + b0.val = cast_to(__lasx_xvilvl_d(t1, t0)); \ + b1.val = cast_to(__lasx_xvilvh_d(t1, t0)); \ + b2.val = cast_to(__lasx_xvilvl_d(t3, t2)); \ + b3.val = cast_to(__lasx_xvilvh_d(t3, t2)); \ + } + +OPENCV_HAL_IMPL_LASX_TRANSPOSE4x4(v_uint32x8, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_LASX_TRANSPOSE4x4(v_int32x8, OPENCV_HAL_NOP, OPENCV_HAL_NOP) + +inline void v_transpose4x4(const v_float32x8 &a0, const v_float32x8 &a1, + const v_float32x8 &a2, const v_float32x8 &a3, + v_float32x8 &b0, v_float32x8 &b1, v_float32x8 &b2, v_float32x8 &b3) +{ + __m256i t0 = __lasx_xvilvl_w(__m256i(a1.val), __m256i(a0.val)); + __m256i t1 = __lasx_xvilvl_w(__m256i(a3.val), __m256i(a2.val)); + __m256i t2 = __lasx_xvilvh_w(__m256i(a1.val), __m256i(a0.val)); + __m256i t3 = __lasx_xvilvh_w(__m256i(a3.val), __m256i(a2.val)); + b0.val = __m256(__lasx_xvilvl_d(t1, t0)); + b1.val = __m256(__lasx_xvilvh_d(t1, t0)); + b2.val = __m256(__lasx_xvilvl_d(t3, t2)); + b3.val = __m256(__lasx_xvilvh_d(t3, t2)); +} + +//////////////// Value reordering /////////////// + +/* Expand */ +#define OPENCV_HAL_IMPL_LASX_EXPAND(_Tpvec, _Tpwvec, _Tp, intrin) \ + inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ + { \ + b0.val = intrin(a.val); \ + b1.val = intrin(__lasx_xvpermi_q(a.val, a.val, 0x11)); \ + } \ + inline _Tpwvec v_expand_low(const _Tpvec& a) \ + { return _Tpwvec(intrin(a.val)); } \ + inline _Tpwvec v_expand_high(const _Tpvec& a) \ + { return _Tpwvec(intrin(__lasx_xvpermi_q(a.val, a.val, 0x11))); } \ + inline _Tpwvec v256_load_expand(const _Tp* ptr) \ + { \ + __m128i a = __lsx_vld(ptr, 0); \ + return _Tpwvec(intrin(*((__m256i*)&a))); \ + } + +OPENCV_HAL_IMPL_LASX_EXPAND(v_uint8x32, v_uint16x16, uchar, __lasx_vext2xv_hu_bu) +OPENCV_HAL_IMPL_LASX_EXPAND(v_int8x32, v_int16x16, schar, __lasx_vext2xv_h_b) +OPENCV_HAL_IMPL_LASX_EXPAND(v_uint16x16, v_uint32x8, ushort, __lasx_vext2xv_wu_hu) +OPENCV_HAL_IMPL_LASX_EXPAND(v_int16x16, v_int32x8, short, __lasx_vext2xv_w_h) +OPENCV_HAL_IMPL_LASX_EXPAND(v_uint32x8, v_uint64x4, unsigned, __lasx_vext2xv_du_wu) +OPENCV_HAL_IMPL_LASX_EXPAND(v_int32x8, v_int64x4, int, __lasx_vext2xv_d_w) + +#define OPENCV_HAL_IMPL_LASX_EXPAND_Q(_Tpvec, _Tp, intrin) \ + inline _Tpvec v256_load_expand_q(const _Tp* ptr) \ + { \ + __m128i a = __lsx_vld(ptr, 0); \ + return _Tpvec(intrin(*((__m256i*)&a))); \ + } + +OPENCV_HAL_IMPL_LASX_EXPAND_Q(v_uint32x8, uchar, __lasx_vext2xv_wu_bu) +OPENCV_HAL_IMPL_LASX_EXPAND_Q(v_int32x8, schar, __lasx_vext2xv_w_b) + +/* pack */ +// 16 +inline v_int8x32 v_pack(const v_int16x16& a, const v_int16x16& b) +{ return v_int8x32(_v256_shuffle_odd_64(_lasx_packs_h(a.val, b.val))); } + +inline v_uint8x32 v_pack(const v_uint16x16& a, const v_uint16x16& b) +{ return v_uint8x32(_v256_shuffle_odd_64(__lasx_xvssrlrni_bu_h(b.val, a.val, 0))); } + +inline v_uint8x32 v_pack_u(const v_int16x16& a, const v_int16x16& b) +{ + return v_uint8x32(_v256_shuffle_odd_64(_lasx_packus_h(a.val, b.val))); +} + +inline void v_pack_store(schar* ptr, const v_int16x16& a) +{ v_store_low(ptr, v_pack(a, a)); } + +inline void v_pack_store(uchar *ptr, const v_uint16x16& a) +{ v_store_low(ptr, v_pack(a, a)); } + +inline void v_pack_u_store(uchar* ptr, const v_int16x16& a) +{ v_store_low(ptr, v_pack_u(a, a)); } + +template inline +v_uint8x32 v_rshr_pack(const v_uint16x16& a, const v_uint16x16& b) +{ + __m256i res = __lasx_xvssrlrni_bu_h(b.val, a.val, n); + return v_uint8x32(_v256_shuffle_odd_64(res)); +} + +template inline +void v_rshr_pack_store(uchar* ptr, const v_uint16x16& a) +{ + __m256i res = __lasx_xvssrlrni_bu_h(a.val, a.val, n); + __lasx_xvstelm_d(res, ptr, 0, 0); + __lasx_xvstelm_d(res, ptr, 8, 2); +} + +template inline +v_uint8x32 v_rshr_pack_u(const v_int16x16& a, const v_int16x16& b) +{ + __m256i res = __lasx_xvssrarni_bu_h(b.val, a.val, n); + return v_uint8x32(_v256_shuffle_odd_64(res)); +} + +template inline +void v_rshr_pack_u_store(uchar* ptr, const v_int16x16& a) +{ + __m256i res = __lasx_xvssrarni_bu_h(a.val, a.val, n); + __lasx_xvstelm_d(res, ptr, 0, 0); + __lasx_xvstelm_d(res, ptr, 8, 2); +} + +template inline +v_int8x32 v_rshr_pack(const v_int16x16& a, const v_int16x16& b) +{ + __m256i res = __lasx_xvssrarni_b_h(b.val, a.val, n); + return v_int8x32(_v256_shuffle_odd_64(res)); +} + +template inline +void v_rshr_pack_store(schar* ptr, const v_int16x16& a) +{ + __m256i res = __lasx_xvssrarni_b_h(a.val, a.val, n); + __lasx_xvstelm_d(res, ptr, 0, 0); + __lasx_xvstelm_d(res, ptr, 8, 2); +} + +// 32 +inline v_int16x16 v_pack(const v_int32x8& a, const v_int32x8& b) +{ return v_int16x16(_v256_shuffle_odd_64(_lasx_packs_w(a.val, b.val))); } + +inline v_uint16x16 v_pack(const v_uint32x8& a, const v_uint32x8& b) +{ return v_uint16x16(_v256_shuffle_odd_64(_v256_packs_epu32(a.val, b.val))); } + +inline v_uint16x16 v_pack_u(const v_int32x8& a, const v_int32x8& b) +{ return v_uint16x16(_v256_shuffle_odd_64(_lasx_packus_w(a.val, b.val))); } + +inline void v_pack_store(short* ptr, const v_int32x8& a) +{ v_store_low(ptr, v_pack(a, a)); } + +inline void v_pack_store(ushort* ptr, const v_uint32x8& a) +{ + __m256i res = __lasx_xvssrlrni_hu_w(a.val, a.val, 0); + __lasx_xvstelm_d(res, ptr, 0, 0); + __lasx_xvstelm_d(res, ptr, 8, 2); +} + +inline void v_pack_u_store(ushort* ptr, const v_int32x8& a) +{ v_store_low(ptr, v_pack_u(a, a)); } + +template inline +v_uint16x16 v_rshr_pack(const v_uint32x8& a, const v_uint32x8& b) +{ return v_uint16x16(_v256_shuffle_odd_64(__lasx_xvssrlrni_hu_w(b.val, a.val, n))); } + +template inline +void v_rshr_pack_store(ushort* ptr, const v_uint32x8& a) +{ + __m256i res = __lasx_xvssrlrni_hu_w(a.val, a.val, n); + __lasx_xvstelm_d(res, ptr, 0, 0); + __lasx_xvstelm_d(res, ptr, 8, 2); +} + +template inline +v_uint16x16 v_rshr_pack_u(const v_int32x8& a, const v_int32x8& b) +{ return v_uint16x16(_v256_shuffle_odd_64(__lasx_xvssrarni_hu_w(b.val, a.val, n))); } + +template inline +void v_rshr_pack_u_store(ushort* ptr, const v_int32x8& a) +{ + __m256i res = __lasx_xvssrarni_hu_w(a.val, a.val, n); + __lasx_xvstelm_d(res, ptr, 0, 0); + __lasx_xvstelm_d(res, ptr, 8, 2); +} + +template inline +v_int16x16 v_rshr_pack(const v_int32x8& a, const v_int32x8& b) +{ return v_int16x16(_v256_shuffle_odd_64(__lasx_xvssrarni_h_w(b.val, a.val, n))); } + +template inline +void v_rshr_pack_store(short* ptr, const v_int32x8& a) +{ + __m256i res = __lasx_xvssrarni_h_w(a.val, a.val, n); + __lasx_xvstelm_d(res, ptr, 0, 0); + __lasx_xvstelm_d(res, ptr, 8, 2); +} + +// 64 +// Non-saturating pack +inline v_uint32x8 v_pack(const v_uint64x4& a, const v_uint64x4& b) +{ + __m256i ab = __lasx_xvpickev_w(b.val, a.val); + return v_uint32x8(_v256_shuffle_odd_64(ab)); +} + +inline v_int32x8 v_pack(const v_int64x4& a, const v_int64x4& b) +{ return v_reinterpret_as_s32(v_pack(v_reinterpret_as_u64(a), v_reinterpret_as_u64(b))); } + +inline void v_pack_store(unsigned* ptr, const v_uint64x4& a) +{ + __m256i a0 = __lasx_xvshuf4i_w(a.val, 0x08); + v_store_low(ptr, v_uint32x8(_v256_shuffle_odd_64(a0))); +} + +inline void v_pack_store(int* ptr, const v_int64x4& b) +{ v_pack_store((unsigned*)ptr, v_reinterpret_as_u64(b)); } + +template inline +v_uint32x8 v_rshr_pack(const v_uint64x4& a, const v_uint64x4& b) +{ return v_uint32x8(_v256_shuffle_odd_64(__lasx_xvsrlrni_w_d(b.val, a.val, n))); } + +template inline +void v_rshr_pack_store(unsigned* ptr, const v_uint64x4& a) +{ + __m256i res = __lasx_xvsrlrni_w_d(a.val, a.val, n); + __lasx_xvstelm_d(res, ptr, 0, 0); + __lasx_xvstelm_d(res, ptr, 8, 2); +} + +template inline +v_int32x8 v_rshr_pack(const v_int64x4& a, const v_int64x4& b) +{ return v_int32x8(_v256_shuffle_odd_64(__lasx_xvsrarni_w_d(b.val, a.val, n))); } + +template inline +void v_rshr_pack_store(int* ptr, const v_int64x4& a) +{ + __m256i res = __lasx_xvsrarni_w_d(a.val, a.val, n); + __lasx_xvstelm_d(res, ptr, 0, 0); + __lasx_xvstelm_d(res, ptr, 8, 2); +} + +// pack boolean +inline v_uint8x32 v_pack_b(const v_uint16x16& a, const v_uint16x16& b) +{ + __m256i ab = _lasx_packs_h(a.val, b.val); + return v_uint8x32(_v256_shuffle_odd_64(ab)); +} + +inline v_uint8x32 v_pack_b(const v_uint32x8& a, const v_uint32x8& b, + const v_uint32x8& c, const v_uint32x8& d) +{ + __m256i ab = _lasx_packs_w(a.val, b.val); + __m256i cd = _lasx_packs_w(c.val, d.val); + + __m256i abcd = _v256_shuffle_odd_64(_lasx_packs_h(ab, cd)); + return v_uint8x32(__lasx_xvshuf4i_w(abcd, 0xd8)); +} + +inline v_uint8x32 v_pack_b(const v_uint64x4& a, const v_uint64x4& b, const v_uint64x4& c, + const v_uint64x4& d, const v_uint64x4& e, const v_uint64x4& f, + const v_uint64x4& g, const v_uint64x4& h) +{ + __m256i ab = _lasx_packs_w(a.val, b.val); + __m256i cd = _lasx_packs_w(c.val, d.val); + __m256i ef = _lasx_packs_w(e.val, f.val); + __m256i gh = _lasx_packs_w(g.val, h.val); + + __m256i abcd = _lasx_packs_w(ab, cd); + __m256i efgh = _lasx_packs_w(ef, gh); + __m256i pkall = _v256_shuffle_odd_64(_lasx_packs_h(abcd, efgh)); + + __m256i rev = _v256_alignr_b(pkall, pkall, 8); + return v_uint8x32(__lasx_xvilvl_h(rev, pkall)); +} + +/* Recombine */ +// its up there with load and store operations + +/* Extract */ +#define OPENCV_HAL_IMPL_LASX_EXTRACT(_Tpvec) \ + template \ + inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \ + { return v_rotate_right(a, b); } + +OPENCV_HAL_IMPL_LASX_EXTRACT(v_uint8x32) +OPENCV_HAL_IMPL_LASX_EXTRACT(v_int8x32) +OPENCV_HAL_IMPL_LASX_EXTRACT(v_uint16x16) +OPENCV_HAL_IMPL_LASX_EXTRACT(v_int16x16) +OPENCV_HAL_IMPL_LASX_EXTRACT(v_uint32x8) +OPENCV_HAL_IMPL_LASX_EXTRACT(v_int32x8) +OPENCV_HAL_IMPL_LASX_EXTRACT(v_uint64x4) +OPENCV_HAL_IMPL_LASX_EXTRACT(v_int64x4) +OPENCV_HAL_IMPL_LASX_EXTRACT(v_float32x8) +OPENCV_HAL_IMPL_LASX_EXTRACT(v_float64x4) + +template +inline uchar v_extract_n(v_uint8x32 a) +{ + return (uchar)_v256_extract_b(a.val); +} + +template +inline schar v_extract_n(v_int8x32 a) +{ + return (schar)v_extract_n(v_reinterpret_as_u8(a)); +} + +template +inline ushort v_extract_n(v_uint16x16 a) +{ + return (ushort)_v256_extract_h(a.val); +} + +template +inline short v_extract_n(v_int16x16 a) +{ + return (short)v_extract_n(v_reinterpret_as_u16(a)); +} + +template +inline uint v_extract_n(v_uint32x8 a) +{ + return (uint)_v256_extract_w(a.val); +} + +template +inline int v_extract_n(v_int32x8 a) +{ + return (int)v_extract_n(v_reinterpret_as_u32(a)); +} + +template +inline uint64 v_extract_n(v_uint64x4 a) +{ + return (uint64)_v256_extract_d(a.val); +} + +template +inline int64 v_extract_n(v_int64x4 v) +{ + return (int64)v_extract_n(v_reinterpret_as_u64(v)); +} + +template +inline float v_extract_n(v_float32x8 v) +{ + union { uint iv; float fv; } d; + d.iv = v_extract_n(v_reinterpret_as_u32(v)); + return d.fv; +} + +template +inline double v_extract_n(v_float64x4 v) +{ + union { uint64 iv; double dv; } d; + d.iv = v_extract_n(v_reinterpret_as_u64(v)); + return d.dv; +} + +template +inline v_uint32x8 v_broadcast_element(v_uint32x8 a) +{ + static const __m256i perm = __lasx_xvreplgr2vr_w((char)i); + return v_uint32x8(__lasx_xvperm_w(a.val, perm)); +} + +template +inline v_int32x8 v_broadcast_element(const v_int32x8 &a) +{ return v_reinterpret_as_s32(v_broadcast_element(v_reinterpret_as_u32(a))); } + +template +inline v_float32x8 v_broadcast_element(const v_float32x8 &a) +{ return v_reinterpret_as_f32(v_broadcast_element(v_reinterpret_as_u32(a))); } + +///////////////////// load deinterleave ///////////////////////////// + +inline void v_load_deinterleave(const uchar* ptr, v_uint8x32& a, v_uint8x32& b) +{ + __m256i t0 = __lasx_xvld(ptr, 0); + __m256i t1 = __lasx_xvld(ptr, 32); + + __m256i p0 = __lasx_xvpickev_b(t1, t0); + __m256i p1 = __lasx_xvpickod_b(t1, t0); + + a.val = __lasx_xvpermi_d(p0, 0xd8); + b.val = __lasx_xvpermi_d(p1, 0xd8); +} + +inline void v_load_deinterleave( const ushort* ptr, v_uint16x16& a, v_uint16x16& b ) +{ + __m256i t0 = __lasx_xvld(ptr, 0); + __m256i t1 = __lasx_xvld(ptr, 32); + + __m256i p0 = __lasx_xvpickev_h(t1, t0); + __m256i p1 = __lasx_xvpickod_h(t1, t0); + + a.val = __lasx_xvpermi_d(p0, 0xd8); + b.val = __lasx_xvpermi_d(p1, 0xd8); +} + +inline void v_load_deinterleave( const unsigned* ptr, v_uint32x8& a, v_uint32x8& b ) +{ + __m256i t0 = __lasx_xvld(ptr, 0); + __m256i t1 = __lasx_xvld(ptr, 32); + + __m256i p0 = __lasx_xvpickev_w(t1, t0); + __m256i p1 = __lasx_xvpickod_w(t1, t0); + + a.val = __lasx_xvpermi_d(p0, 0xd8); + b.val = __lasx_xvpermi_d(p1, 0xd8); +} + +inline void v_load_deinterleave( const uint64* ptr, v_uint64x4& a, v_uint64x4& b ) +{ + __m256i ab0 = __lasx_xvld(ptr, 0); + __m256i ab1 = __lasx_xvld(ptr, 32); + + __m256i pl = __lasx_xvpermi_q(ab0, ab1, 0x02); + __m256i ph = __lasx_xvpermi_q(ab0, ab1, 0x13); + __m256i a0 = __lasx_xvilvl_d(ph, pl); + __m256i b0 = __lasx_xvilvh_d(ph, pl); + a = v_uint64x4(a0); + b = v_uint64x4(b0); +} + +inline void v_load_deinterleave( const uchar* ptr, v_uint8x32& a, v_uint8x32& b, v_uint8x32& c ) +{ + __m256i bgr0 = __lasx_xvld(ptr, 0); + __m256i bgr1 = __lasx_xvld(ptr, 32); + __m256i bgr2 = __lasx_xvld(ptr, 64); + + __m256i s02_low = __lasx_xvpermi_q(bgr0, bgr2, 0x02); + __m256i s02_high = __lasx_xvpermi_q(bgr0, bgr2, 0x13); + + const __m256i m0 = _v256_setr_b(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, + 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); + const __m256i m1 = _v256_setr_b(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, + -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); + + __m256i b0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(s02_low, s02_high, m0), bgr1, m1); + __m256i g0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(s02_high, s02_low, m1), bgr1, m0); + __m256i r0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(bgr1, s02_low, m0), s02_high, m1); + + const __m256i + sh_b = _v256_setr_b(0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13, + 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13), + sh_g = _v256_setr_b(1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, + 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14), + sh_r = _v256_setr_b(2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, + 2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15); + b0 = __lasx_xvshuf_b(b0, b0, sh_b); + g0 = __lasx_xvshuf_b(g0, g0, sh_g); + r0 = __lasx_xvshuf_b(r0, r0, sh_r); + + a = v_uint8x32(b0); + b = v_uint8x32(g0); + c = v_uint8x32(r0); +} + +inline void v_load_deinterleave( const ushort* ptr, v_uint16x16& a, v_uint16x16& b, v_uint16x16& c ) +{ + __m256i bgr0 = __lasx_xvld(ptr, 0); + __m256i bgr1 = __lasx_xvld(ptr, 32); + __m256i bgr2 = __lasx_xvld(ptr, 64); + + __m256i s02_low = __lasx_xvpermi_q(bgr0, bgr2, 0x02); + __m256i s02_high = __lasx_xvpermi_q(bgr0, bgr2, 0x13); + + const __m256i m0 = _v256_setr_b(0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, + 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0); + const __m256i m1 = _v256_setr_b(0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, + -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0); + __m256i b0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(s02_low, s02_high, m0), bgr1, m1); + __m256i g0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(bgr1, s02_low, m0), s02_high, m1); + __m256i r0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(s02_high, s02_low, m1), bgr1, m0); + const __m256i sh_b = _v256_setr_b(0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, + 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11); + const __m256i sh_g = _v256_setr_b(2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, + 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 0, 1, 6, 7, 12, 13); + const __m256i sh_r = _v256_setr_b(4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, + 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15); + b0 = __lasx_xvshuf_b(b0, b0, sh_b); + g0 = __lasx_xvshuf_b(g0, g0, sh_g); + r0 = __lasx_xvshuf_b(r0, r0, sh_r); + + a = v_uint16x16(b0); + b = v_uint16x16(g0); + c = v_uint16x16(r0); +} + +inline void v_load_deinterleave( const unsigned* ptr, v_uint32x8& a, v_uint32x8& b, v_uint32x8& c ) +{ + __m256i bgr0 = __lasx_xvld(ptr, 0); + __m256i bgr1 = __lasx_xvld(ptr, 32); + __m256i bgr2 = __lasx_xvld(ptr, 64); + + __m256i s02_low = __lasx_xvpermi_q(bgr0, bgr2, 0x02); + __m256i s02_high = __lasx_xvpermi_q(bgr0, bgr2, 0x13); + + __m256i m24 = _v256_set_w(0, 0, -1, 0, 0, -1, 0, 0); + __m256i m92 = _v256_set_w(-1, 0, 0, -1, 0, 0, -1, 0); + __m256i b0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(s02_low, s02_high, m24), bgr1, m92); + __m256i g0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(s02_high, s02_low, m92), bgr1, m24); + __m256i r0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(bgr1, s02_low, m24), s02_high, m92); + + b0 = __lasx_xvshuf4i_w(b0, 0x6c); + g0 = __lasx_xvshuf4i_w(g0, 0xb1); + r0 = __lasx_xvshuf4i_w(r0, 0xc6); + + a = v_uint32x8(b0); + b = v_uint32x8(g0); + c = v_uint32x8(r0); +} + +inline void v_load_deinterleave( const uint64* ptr, v_uint64x4& a, v_uint64x4& b, v_uint64x4& c ) +{ + __m256i bgr0 = __lasx_xvld(ptr, 0); + __m256i bgr1 = __lasx_xvld(ptr, 32); + __m256i bgr2 = __lasx_xvld(ptr, 64); + + __m256i s01 = __lasx_xvpermi_q(bgr0, bgr1, 0x12); // get bgr0 low 128 and bgr1 high 128 + __m256i s12 = __lasx_xvpermi_q(bgr1, bgr2, 0x12); + __m256i s20r = __lasx_xvpermi_d(__lasx_xvpermi_q(bgr2, bgr0, 0x12), 0x1b); + __m256i b0 = __lasx_xvilvl_d(s20r, s01); + __m256i g0 = _v256_alignr_b(s12, s01, 8); + __m256i r0 = __lasx_xvilvh_d(s12, s20r); + + a = v_uint64x4(b0); + b = v_uint64x4(g0); + c = v_uint64x4(r0); +} + +inline void v_load_deinterleave(const uchar* ptr, v_uint8x32& a, v_uint8x32& b, v_uint8x32& c, v_uint8x32& d) +{ + __m256i t0 = __lasx_xvld(ptr, 0); + __m256i t1 = __lasx_xvld(ptr, 32); + __m256i t2 = __lasx_xvld(ptr, 64); + __m256i t3 = __lasx_xvld(ptr, 96); + + const __m256i sh = _v256_setr_w(0, 4, 1, 5, 2, 6, 3, 7); + __m256i ac_lo = __lasx_xvpickev_b(t1, t0); + __m256i bd_lo = __lasx_xvpickod_b(t1, t0); + __m256i ac_hi = __lasx_xvpickev_b(t3, t2); + __m256i bd_hi = __lasx_xvpickod_b(t3, t2); + + __m256i a_pre = __lasx_xvpickev_b(ac_hi, ac_lo); + __m256i c_pre = __lasx_xvpickod_b(ac_hi, ac_lo); + __m256i b_pre = __lasx_xvpickev_b(bd_hi, bd_lo); + __m256i d_pre = __lasx_xvpickod_b(bd_hi, bd_lo); + + a.val = __lasx_xvperm_w(a_pre, sh); + b.val = __lasx_xvperm_w(b_pre, sh); + c.val = __lasx_xvperm_w(c_pre, sh); + d.val = __lasx_xvperm_w(d_pre, sh); +} + +inline void v_load_deinterleave(const ushort* ptr, v_uint16x16& a, v_uint16x16& b, v_uint16x16& c, v_uint16x16& d) +{ + __m256i t0 = __lasx_xvld(ptr, 0); + __m256i t1 = __lasx_xvld(ptr, 32); + __m256i t2 = __lasx_xvld(ptr, 64); + __m256i t3 = __lasx_xvld(ptr, 96); + + const __m256i sh = _v256_setr_w(0, 4, 1, 5, 2, 6, 3, 7); + __m256i ac_lo = __lasx_xvpickev_h(t1, t0); + __m256i bd_lo = __lasx_xvpickod_h(t1, t0); + __m256i ac_hi = __lasx_xvpickev_h(t3, t2); + __m256i bd_hi = __lasx_xvpickod_h(t3, t2); + + __m256i a_pre = __lasx_xvpickev_h(ac_hi, ac_lo); + __m256i c_pre = __lasx_xvpickod_h(ac_hi, ac_lo); + __m256i b_pre = __lasx_xvpickev_h(bd_hi, bd_lo); + __m256i d_pre = __lasx_xvpickod_h(bd_hi, bd_lo); + + a.val = __lasx_xvperm_w(a_pre, sh); + b.val = __lasx_xvperm_w(b_pre, sh); + c.val = __lasx_xvperm_w(c_pre, sh); + d.val = __lasx_xvperm_w(d_pre, sh); +} + +inline void v_load_deinterleave( const unsigned* ptr, v_uint32x8& a, v_uint32x8& b, v_uint32x8& c, v_uint32x8& d ) +{ + __m256i p0 = __lasx_xvld(ptr, 0); + __m256i p1 = __lasx_xvld(ptr, 32); + __m256i p2 = __lasx_xvld(ptr, 64); + __m256i p3 = __lasx_xvld(ptr, 96); + + __m256i p01l = __lasx_xvilvl_w(p1, p0); + __m256i p01h = __lasx_xvilvh_w(p1, p0); + __m256i p23l = __lasx_xvilvl_w(p3, p2); + __m256i p23h = __lasx_xvilvh_w(p3, p2); + + __m256i pll = __lasx_xvpermi_q(p01l, p23l, 0x02); + __m256i plh = __lasx_xvpermi_q(p01l, p23l, 0x13); + __m256i phl = __lasx_xvpermi_q(p01h, p23h, 0x02); + __m256i phh = __lasx_xvpermi_q(p01h, p23h, 0x13); + + __m256i b0 = __lasx_xvilvl_w(plh, pll); + __m256i g0 = __lasx_xvilvh_w(plh, pll); + __m256i r0 = __lasx_xvilvl_w(phh, phl); + __m256i a0 = __lasx_xvilvh_w(phh, phl); + + a = v_uint32x8(b0); + b = v_uint32x8(g0); + c = v_uint32x8(r0); + d = v_uint32x8(a0); +} + +inline void v_load_deinterleave( const uint64* ptr, v_uint64x4& a, v_uint64x4& b, v_uint64x4& c, v_uint64x4& d ) +{ + __m256i bgra0 = __lasx_xvld(ptr, 0); + __m256i bgra1 = __lasx_xvld(ptr, 32); + __m256i bgra2 = __lasx_xvld(ptr, 64); + __m256i bgra3 = __lasx_xvld(ptr, 96); + + __m256i l02 = __lasx_xvpermi_q(bgra0, bgra2, 0x02); + __m256i h02 = __lasx_xvpermi_q(bgra0, bgra2, 0x13); + __m256i l13 = __lasx_xvpermi_q(bgra1, bgra3, 0x02); + __m256i h13 = __lasx_xvpermi_q(bgra1, bgra3, 0x13); + + __m256i b0 = __lasx_xvilvl_d(l13, l02); + __m256i g0 = __lasx_xvilvh_d(l13, l02); + __m256i r0 = __lasx_xvilvl_d(h13, h02); + __m256i a0 = __lasx_xvilvh_d(h13, h02); + + a = v_uint64x4(b0); + b = v_uint64x4(g0); + c = v_uint64x4(r0); + d = v_uint64x4(a0); +} + +///////////////////////////// store interleave ///////////////////////////////////// + +inline void v_store_interleave( uchar* ptr, const v_uint8x32& x, const v_uint8x32& y, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) +{ + __m256i xy_l = __lasx_xvilvl_b(y.val, x.val); + __m256i xy_h = __lasx_xvilvh_b(y.val, x.val); + + __m256i xy0 = __lasx_xvpermi_q(xy_h, xy_l, 0 + 2*16); + __m256i xy1 = __lasx_xvpermi_q(xy_h, xy_l, 1 + 3*16); + + __lasx_xvst(xy0, (__m256i*)ptr, 0); + __lasx_xvst(xy1, (__m256i*)ptr, 32*1); +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x16& x, const v_uint16x16& y, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) +{ + __m256i xy_l = __lasx_xvilvl_h(y.val, x.val); + __m256i xy_h = __lasx_xvilvh_h(y.val, x.val); + + __m256i xy0 = __lasx_xvpermi_q(xy_h, xy_l, 0 + 2*16); + __m256i xy1 = __lasx_xvpermi_q(xy_h, xy_l, 1 + 3*16); + + __lasx_xvst(xy0, (__m256i*)ptr, 0); + __lasx_xvst(xy1, (__m256i*)ptr, 16*2); +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x8& x, const v_uint32x8& y, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) +{ + __m256i xy_l = __lasx_xvilvl_w(y.val, x.val); + __m256i xy_h = __lasx_xvilvh_w(y.val, x.val); + + __m256i xy0 = __lasx_xvpermi_q(xy_h, xy_l, 0 + 2*16); + __m256i xy1 = __lasx_xvpermi_q(xy_h, xy_l, 1 + 3*16); + + __lasx_xvst(xy0, (__m256i*)ptr, 0); + __lasx_xvst(xy1, (__m256i*)ptr, 8*4); +} + +inline void v_store_interleave( uint64* ptr, const v_uint64x4& x, const v_uint64x4& y, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) +{ + __m256i xy_l = __lasx_xvilvl_d(y.val, x.val); + __m256i xy_h = __lasx_xvilvh_d(y.val, x.val); + + __m256i xy0 = __lasx_xvpermi_q(xy_h, xy_l, 0 + 2*16); + __m256i xy1 = __lasx_xvpermi_q(xy_h, xy_l, 1 + 3*16); + + __lasx_xvst(xy0, (__m256i*)ptr, 0); + __lasx_xvst(xy1, (__m256i*)ptr, 4*8); +} + +inline void v_store_interleave( uchar* ptr, const v_uint8x32& a, const v_uint8x32& b, const v_uint8x32& c, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) +{ + const __m256i sh_b = _v256_setr_b( + 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5, + 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5); + const __m256i sh_g = _v256_setr_b( + 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, + 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10); + const __m256i sh_r = _v256_setr_b( + 10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, + 10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15); + + __m256i b0 = __lasx_xvshuf_b(a.val, a.val, sh_b); + __m256i g0 = __lasx_xvshuf_b(b.val, b.val, sh_g); + __m256i r0 = __lasx_xvshuf_b(c.val, c.val, sh_r); + + const __m256i m0 = _v256_setr_b(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, + 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); + const __m256i m1 = _v256_setr_b(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, + 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0); + + __m256i p0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(b0, g0, m0), r0, m1); + __m256i p1 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(g0, r0, m0), b0, m1); + __m256i p2 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(r0, b0, m0), g0, m1); + + __m256i bgr0 = __lasx_xvpermi_q(p1, p0, 0 + 2*16); + __m256i bgr1 = __lasx_xvpermi_q(p0, p2, 0 + 3*16); + __m256i bgr2 = __lasx_xvpermi_q(p2, p1, 1 + 3*16); + + __lasx_xvst(bgr0, (__m256i*)ptr, 0); + __lasx_xvst(bgr1, (__m256i*)ptr, 32); + __lasx_xvst(bgr2, (__m256i*)ptr, 64); +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x16& a, const v_uint16x16& b, const v_uint16x16& c, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) +{ + const __m256i sh_b = _v256_setr_b( + 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, + 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11); + const __m256i sh_g = _v256_setr_b( + 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, + 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5); + const __m256i sh_r = _v256_setr_b( + 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, + 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15); + + __m256i b0 = __lasx_xvshuf_b(a.val, a.val, sh_b); + __m256i g0 = __lasx_xvshuf_b(b.val, b.val, sh_g); + __m256i r0 = __lasx_xvshuf_b(c.val, c.val, sh_r); + + const __m256i m0 = _v256_setr_b(0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, + 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0); + const __m256i m1 = _v256_setr_b(0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, + -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0); + + __m256i p0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(b0, g0, m0), r0, m1); + __m256i p1 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(g0, r0, m0), b0, m1); + __m256i p2 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(r0, b0, m0), g0, m1); + + __m256i bgr0 = __lasx_xvpermi_q(p2, p0, 0 + 2*16); + __m256i bgr2 = __lasx_xvpermi_q(p2, p0, 1 + 3*16); + + __lasx_xvst(bgr0, (__m256i*)ptr, 0); + __lasx_xvst(p1, (__m256i*)ptr, 16*2); + __lasx_xvst(bgr2, (__m256i*)ptr, 32*2); +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x8& a, const v_uint32x8& b, const v_uint32x8& c, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) +{ + __m256i b0 = __lasx_xvshuf4i_w(a.val, 0x6c); + __m256i g0 = __lasx_xvshuf4i_w(b.val, 0xb1); + __m256i r0 = __lasx_xvshuf4i_w(c.val, 0xc6); + + __m256i bitmask_1 = _v256_set_w(-1, 0, 0, -1, 0, 0, -1, 0); + __m256i bitmask_2 = _v256_set_w(0, 0, -1, 0, 0, -1, 0, 0); + + __m256i p0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(b0, g0, bitmask_1), r0, bitmask_2); + __m256i p1 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(g0, r0, bitmask_1), b0, bitmask_2); + __m256i p2 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(r0, b0, bitmask_1), g0, bitmask_2); + + __m256i bgr0 = __lasx_xvpermi_q(p1, p0, 0 + 2*16); + __m256i bgr2 = __lasx_xvpermi_q(p1, p0, 1 + 3*16); + + __lasx_xvst(bgr0, (__m256i*)ptr, 0); + __lasx_xvst(p2, (__m256i*)ptr, 8*4); + __lasx_xvst(bgr2, (__m256i*)ptr, 16*4); +} + +inline void v_store_interleave( uint64* ptr, const v_uint64x4& a, const v_uint64x4& b, const v_uint64x4& c, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) +{ + __m256i s01 = __lasx_xvilvl_d(b.val, a.val); + __m256i s12 = __lasx_xvilvh_d(c.val, b.val); + __m256i s20 = __lasx_xvpermi_w(a.val, c.val, 0xe4); + + __m256i bgr0 = __lasx_xvpermi_q(s20, s01, 0 + 2*16); + __m256i bgr1 = __lasx_xvpermi_q(s01, s12, 0x30); + __m256i bgr2 = __lasx_xvpermi_q(s12, s20, 1 + 3*16); + + __lasx_xvst(bgr0, (__m256i*)ptr, 0); + __lasx_xvst(bgr1, (__m256i*)ptr, 4*8); + __lasx_xvst(bgr2, (__m256i*)ptr, 8*8); +} + +inline void v_store_interleave( uchar* ptr, const v_uint8x32& a, const v_uint8x32& b, + const v_uint8x32& c, const v_uint8x32& d, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) +{ + __m256i bg0 = __lasx_xvilvl_b(b.val, a.val); + __m256i bg1 = __lasx_xvilvh_b(b.val, a.val); + __m256i ra0 = __lasx_xvilvl_b(d.val, c.val); + __m256i ra1 = __lasx_xvilvh_b(d.val, c.val); + + __m256i bgra0_ = __lasx_xvilvl_h(ra0, bg0); + __m256i bgra1_ = __lasx_xvilvh_h(ra0, bg0); + __m256i bgra2_ = __lasx_xvilvl_h(ra1, bg1); + __m256i bgra3_ = __lasx_xvilvh_h(ra1, bg1); + + __m256i bgra0 = __lasx_xvpermi_q(bgra1_, bgra0_, 0 + 2*16); + __m256i bgra2 = __lasx_xvpermi_q(bgra1_, bgra0_, 1 + 3*16); + __m256i bgra1 = __lasx_xvpermi_q(bgra3_, bgra2_, 0 + 2*16); + __m256i bgra3 = __lasx_xvpermi_q(bgra3_, bgra2_, 1 + 3*16); + + __lasx_xvst(bgra0, (__m256i*)ptr, 0); + __lasx_xvst(bgra1, (__m256i*)ptr, 32); + __lasx_xvst(bgra2, (__m256i*)ptr, 64); + __lasx_xvst(bgra3, (__m256i*)ptr, 96); +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x16& a, const v_uint16x16& b, + const v_uint16x16& c, const v_uint16x16& d, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) +{ + __m256i bg0 = __lasx_xvilvl_h(b.val, a.val); + __m256i bg1 = __lasx_xvilvh_h(b.val, a.val); + __m256i ra0 = __lasx_xvilvl_h(d.val, c.val); + __m256i ra1 = __lasx_xvilvh_h(d.val, c.val); + + __m256i bgra0_ = __lasx_xvilvl_w(ra0, bg0); + __m256i bgra1_ = __lasx_xvilvh_w(ra0, bg0); + __m256i bgra2_ = __lasx_xvilvl_w(ra1, bg1); + __m256i bgra3_ = __lasx_xvilvh_w(ra1, bg1); + + __m256i bgra0 = __lasx_xvpermi_q(bgra1_, bgra0_, 0 + 2*16); + __m256i bgra2 = __lasx_xvpermi_q(bgra1_, bgra0_, 1 + 3*16); + __m256i bgra1 = __lasx_xvpermi_q(bgra3_, bgra2_, 0 + 2*16); + __m256i bgra3 = __lasx_xvpermi_q(bgra3_, bgra2_, 1 + 3*16); + + __lasx_xvst(bgra0, (__m256i*)ptr, 0); + __lasx_xvst(bgra1, (__m256i*)ptr, 16*2); + __lasx_xvst(bgra2, (__m256i*)ptr, 32*2); + __lasx_xvst(bgra3, (__m256i*)ptr, 48*2); +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x8& a, const v_uint32x8& b, + const v_uint32x8& c, const v_uint32x8& d, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) +{ + __m256i bg0 = __lasx_xvilvl_w(b.val, a.val); + __m256i bg1 = __lasx_xvilvh_w(b.val, a.val); + __m256i ra0 = __lasx_xvilvl_w(d.val, c.val); + __m256i ra1 = __lasx_xvilvh_w(d.val, c.val); + + __m256i bgra0_ = __lasx_xvilvl_d(ra0, bg0); + __m256i bgra1_ = __lasx_xvilvh_d(ra0, bg0); + __m256i bgra2_ = __lasx_xvilvl_d(ra1, bg1); + __m256i bgra3_ = __lasx_xvilvh_d(ra1, bg1); + + __m256i bgra0 = __lasx_xvpermi_q(bgra1_, bgra0_, 0 + 2*16); + __m256i bgra2 = __lasx_xvpermi_q(bgra1_, bgra0_, 1 + 3*16); + __m256i bgra1 = __lasx_xvpermi_q(bgra3_, bgra2_, 0 + 2*16); + __m256i bgra3 = __lasx_xvpermi_q(bgra3_, bgra2_, 1 + 3*16); + + __lasx_xvst(bgra0, (__m256i*)ptr, 0); + __lasx_xvst(bgra1, (__m256i*)ptr, 8*4); + __lasx_xvst(bgra2, (__m256i*)ptr, 16*4); + __lasx_xvst(bgra3, (__m256i*)ptr, 24*4); +} + +inline void v_store_interleave( uint64* ptr, const v_uint64x4& a, const v_uint64x4& b, + const v_uint64x4& c, const v_uint64x4& d, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) +{ + __m256i bg0 = __lasx_xvilvl_d(b.val, a.val); + __m256i bg1 = __lasx_xvilvh_d(b.val, a.val); + __m256i ra0 = __lasx_xvilvl_d(d.val, c.val); + __m256i ra1 = __lasx_xvilvh_d(d.val, c.val); + + __m256i bgra0 = __lasx_xvpermi_q(ra0, bg0, 0 + 2*16); + __m256i bgra1 = __lasx_xvpermi_q(ra1, bg1, 0 + 2*16); + __m256i bgra2 = __lasx_xvpermi_q(ra0, bg0, 1 + 3*16); + __m256i bgra3 = __lasx_xvpermi_q(ra1, bg1, 1 + 3*16); + + __lasx_xvst(bgra0, (__m256i*)ptr, 0); + __lasx_xvst(bgra1, (__m256i*)(ptr), 4*8); + __lasx_xvst(bgra2, (__m256i*)(ptr), 8*8); + __lasx_xvst(bgra3, (__m256i*)(ptr), 12*8); +} + + +#define OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(_Tpvec0, _Tp0, suffix0, _Tpvec1, _Tp1, suffix1) \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0 ) \ +{ \ + _Tpvec1 a1, b1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ +} \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0 ) \ +{ \ + _Tpvec1 a1, b1, c1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ + c0 = v_reinterpret_as_##suffix0(c1); \ +} \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0, _Tpvec0& d0 ) \ +{ \ + _Tpvec1 a1, b1, c1, d1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1, d1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ + c0 = v_reinterpret_as_##suffix0(c1); \ + d0 = v_reinterpret_as_##suffix0(d1); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + v_store_interleave((_Tp1*)ptr, a1, b1/*, mode*/); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, const _Tpvec0& c0, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, c1/*, mode*/); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + const _Tpvec0& c0, const _Tpvec0& d0, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ + _Tpvec1 d1 = v_reinterpret_as_##suffix1(d0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, c1, d1/*, mode*/); \ +} + +OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(v_int8x32, schar, s8, v_uint8x32, uchar, u8) +OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(v_int16x16, short, s16, v_uint16x16, ushort, u16) +OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(v_int32x8, int, s32, v_uint32x8, unsigned, u32) +OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(v_float32x8, float, f32, v_uint32x8, unsigned, u32) +OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(v_int64x4, int64, s64, v_uint64x4, uint64, u64) +OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(v_float64x4, double, f64, v_uint64x4, uint64, u64) + +// +// FP16 +// + +inline v_float32x8 v256_load_expand(const hfloat* ptr) +{ +#if CV_FP16 + //1-load128, 2-permi, 3-cvt + return v_float32x8(__lasx_xvfcvtl_s_h(__lasx_xvpermi_d(__lsx_vld((const __m128i*)ptr, 0), 0x10))); +#else + float CV_DECL_ALIGNED(32) buf[8]; + for (int i = 0; i < 8; i++) + buf[i] = (float)ptr[i]; + return v256_load_aligned(buf); +#endif +} + +inline void v_pack_store(hfloat* ptr, const v_float32x8& a) +{ +#if CV_FP16 + __m256i ah = __lasx_xvfcvt_h_s(a.val, a.val); + __lsx_vst((_m128i)ah, ptr, 0); +#else + float CV_DECL_ALIGNED(32) buf[8]; + v_store_aligned(buf, a); + for (int i = 0; i < 8; i++) + ptr[i] = hfloat(buf[i]); +#endif +} + +// +// end of FP16 +// + +inline void v256_cleanup() {} + +#include "intrin_math.hpp" +inline v_float32x8 v_exp(const v_float32x8& x) { return v_exp_default_32f(x); } +inline v_float32x8 v_log(const v_float32x8& x) { return v_log_default_32f(x); } +inline void v_sincos(const v_float32x8& x, v_float32x8& s, v_float32x8& c) { v_sincos_default_32f(x, s, c); } +inline v_float32x8 v_sin(const v_float32x8& x) { return v_sin_default_32f(x); } +inline v_float32x8 v_cos(const v_float32x8& x) { return v_cos_default_32f(x); } +inline v_float32x8 v_erf(const v_float32x8& x) { return v_erf_default_32f(x); } + +inline v_float64x4 v_exp(const v_float64x4& x) { return v_exp_default_64f(x); } +inline v_float64x4 v_log(const v_float64x4& x) { return v_log_default_64f(x); } +inline void v_sincos(const v_float64x4& x, v_float64x4& s, v_float64x4& c) { v_sincos_default_64f(x, s, c); } +inline v_float64x4 v_sin(const v_float64x4& x) { return v_sin_default_64f(x); } +inline v_float64x4 v_cos(const v_float64x4& x) { return v_cos_default_64f(x); } + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} // cv:: + +#endif // OPENCV_HAL_INTRIN_LASX_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_lsx.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_lsx.hpp index a2f23d6abe..e89c9e5a47 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_lsx.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_lsx.hpp @@ -1,2546 +1,2546 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -#ifndef OPENCV_HAL_INTRIN_LSX_HPP -#define OPENCV_HAL_INTRIN_LSX_HPP - -#include - -#define CV_SIMD128 1 -#define CV_SIMD128_64F 1 -#define CV_SIMD128_FP16 0 - -namespace cv -{ - -//! @cond IGNORED - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -/////////// Utils //////// - -inline __m128i _v128_setr_b(char v0, char v1, char v2, char v3, char v4, char v5, char v6, - char v7, char v8, char v9, char v10, char v11, char v12, char v13, char v14, char v15) -{ - return (__m128i)v16i8{ v0, v1, v2, v3, v4, v5, v6, v7, - v8, v9, v10, v11, v12, v13, v14, v15 }; -} - -inline __m128i _v128_set_b(char v0, char v1, char v2, char v3, char v4, char v5, char v6, - char v7, char v8, char v9, char v10, char v11, char v12, char v13, char v14, char v15) -{ - return (__m128i)v16i8{ v15, v14, v13, v12, v11, v10, v9, v8, - v7, v6, v5, v4, v3, v2, v1, v0 }; -} - -inline __m128i _v128_setr_h(short v0, short v1, short v2, short v3, short v4, short v5, - short v6, short v7) -{ - return (__m128i)v8i16{ v0, v1, v2, v3, v4, v5, v6, v7 }; -} - -inline __m128i _v128_setr_w(int v0, int v1, int v2, int v3) -{ - return (__m128i)v4i32{ v0, v1, v2, v3 }; -} - -inline __m128i _v128_set_w(int v0, int v1, int v2, int v3) -{ - return (__m128i)v4i32{ v3, v2, v1, v0 }; -} - -inline __m128i _v128_setall_w(int v0) -{ - return __lsx_vreplgr2vr_w(v0); -} - -inline __m128i _v128_setr_d(int64 v0, int64 v1) -{ - return (__m128i)v2i64{ v0, v1 }; -} - -inline __m128i _v128_set_d(int64 v0, int64 v1) -{ - return (__m128i)v2i64{ v1, v0 }; -} - -inline __m128 _v128_setr_ps(float v0, float v1, float v2, float v3) -{ - return (__m128)v4f32{ v0, v1, v2, v3 }; -} - -inline __m128 _v128_setall_ps(float v0) -{ - return (__m128)v4f32{ v0, v0, v0, v0 }; -} - -inline __m128d _v128_setr_pd(double v0, double v1) -{ - return (__m128d)v2f64{ v0, v1 }; -} - -inline __m128d _v128_setall_pd(double v0) -{ - return (__m128d)v2f64{ v0, v0 }; -} - -inline __m128i _lsx_packus_h(const __m128i& a, const __m128i& b) -{ - return __lsx_vssrarni_bu_h(b, a, 0); -} - -inline __m128i _lsx_packs_h(const __m128i& a, const __m128i& b) -{ - return __lsx_vssrarni_b_h(b, a, 0); -} - -inline __m128i _lsx_packus_w(const __m128i& a, const __m128i& b) -{ - return __lsx_vssrarni_hu_w(b, a, 0); -} - -/////// Types /////// - -struct v_uint8x16 -{ - typedef uchar lane_type; - enum { nlanes = 16}; - - v_uint8x16() {} - explicit v_uint8x16(__m128i v): val(v) {} - v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, - uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) - { - val = _v128_setr_b(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15); - } - - uchar get0() const - { - return (uchar)__lsx_vpickve2gr_bu(val, 0); - } - - __m128i val; -}; - -struct v_int8x16 -{ - typedef schar lane_type; - enum { nlanes = 16 }; - - v_int8x16() {} - explicit v_int8x16(__m128i v) : val(v) {} - v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, - schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) - { - val = _v128_setr_b(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15); - } - - schar get0() const - { - return (schar)__lsx_vpickve2gr_b(val, 0); - } - - __m128i val; -}; - -struct v_uint16x8 -{ - typedef ushort lane_type; - enum { nlanes = 8 }; - - v_uint16x8() {} - explicit v_uint16x8(__m128i v) : val(v) {} - v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) - { - val = _v128_setr_h(v0, v1, v2, v3, v4, v5, v6, v7); - } - - ushort get0() const - { - return (ushort)__lsx_vpickve2gr_hu(val, 0); - } - - __m128i val; -}; - -struct v_int16x8 -{ - typedef short lane_type; - enum { nlanes = 8 }; - - v_int16x8() {} - explicit v_int16x8(__m128i v) : val(v) {} - v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) - { - val = _v128_setr_h(v0, v1, v2, v3, v4, v5, v6, v7); - } - - short get0() const - { - return (short)__lsx_vpickve2gr_h(val, 0); - } - - __m128i val; -}; - -struct v_uint32x4 -{ - typedef unsigned lane_type; - enum { nlanes = 4 }; - - v_uint32x4() {} - explicit v_uint32x4(__m128i v) : val(v) {} - v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) - { - val = _v128_setr_w(v0, v1, v2, v3); - } - - unsigned get0() const - { - return (unsigned)__lsx_vpickve2gr_wu(val, 0); - } - - __m128i val; -}; - -struct v_int32x4 -{ - typedef int lane_type; - enum { nlanes = 4 }; - - v_int32x4() {} - explicit v_int32x4(__m128i v) : val(v) {} - v_int32x4(int v0, int v1, int v2, int v3) - { - val = _v128_setr_w(v0, v1, v2, v3); - } - - int get0() const - { - return (int)__lsx_vpickve2gr_w(val, 0); - } - - __m128i val; -}; - -struct v_float32x4 -{ - typedef float lane_type; - enum { nlanes = 4}; - - v_float32x4() {} - explicit v_float32x4(__m128 v) : val(v) {} - explicit v_float32x4(__m128i v) { val = *((__m128*)&v); } - v_float32x4(float v0, float v1, float v2, float v3) - { - val = _v128_setr_ps(v0, v1, v2, v3); - } - - float get0() const - { - union { int iv; float fv; } d; - d.iv = __lsx_vpickve2gr_w(val, 0); - return d.fv; - } - - int get0toint() const - { - __m128i result = __lsx_vftintrz_w_s(val); - return (int)__lsx_vpickve2gr_w(result, 0); - } - - __m128 val; -}; - -struct v_uint64x2 -{ - typedef uint64 lane_type; - enum { nlanes = 2}; - - v_uint64x2() {} - explicit v_uint64x2(__m128i v) : val(v) {} - v_uint64x2(uint64 v0, uint64 v1) - { - val = _v128_setr_d(v0, v1); - } - - uint64 get0() const - { - return __lsx_vpickve2gr_du(val, 0); - } - - __m128i val; -}; - -struct v_int64x2 -{ - typedef int64 lane_type; - enum { nlanes = 2}; - - v_int64x2() {} - explicit v_int64x2(__m128i v) : val(v) {} - v_int64x2(int64 v0, int64 v1) - { - val = _v128_setr_d(v0, v1); - } - - uint64 get0() const - { - return __lsx_vpickve2gr_d(val, 0); - } - - __m128i val; -}; - -struct v_float64x2 -{ - typedef double lane_type; - enum { nlanes = 2}; - - v_float64x2() {} - explicit v_float64x2(__m128d v) : val(v) {} - explicit v_float64x2(__m128i v) { val = *((__m128d*)&v); } - v_float64x2(double v0, double v1) - { - val = _v128_setr_pd(v0, v1); - } - - double get0() const - { - union { int64 iv; double fv; } d; - d.iv = __lsx_vpickve2gr_d(val, 0); - return d.fv; - } - - int64 get0toint64() const - { - __m128i result = __lsx_vftintrz_l_d(val); - return (int64)__lsx_vpickve2gr_d(result, 0); - } - - __m128d val; -}; - -////////////// Load and store operations ///////// - -#define OPENCV_HAL_IMPL_LSX_LOADSTORE(_Tpvec, _Tp) \ - inline _Tpvec v_load(const _Tp* ptr) \ - { return _Tpvec(__lsx_vld(ptr, 0)); } \ - inline _Tpvec v_load_aligned(const _Tp* ptr) \ - { return _Tpvec(__lsx_vld(ptr, 0)); } \ - inline _Tpvec v_load_low(const _Tp* ptr) \ - { return _Tpvec(__lsx_vldrepl_d(ptr, 0)); } \ - inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ - { \ - __m128i vl = __lsx_vldrepl_d(ptr0, 0); \ - __m128i vh = __lsx_vldrepl_d(ptr1, 0); \ - return _Tpvec(__lsx_vilvl_d(vh, vl)); \ - } \ - inline void v_store(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vst(a.val, ptr, 0); } \ - inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vst(a.val, ptr, 0); } \ - inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vst(a.val, ptr, 0); } \ - inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode)\ - { \ - if ( mode == hal::STORE_UNALIGNED) \ - __lsx_vst(a.val, ptr, 0); \ - else if ( mode == hal::STORE_ALIGNED_NOCACHE) \ - __lsx_vst(a.val, ptr, 0); \ - else \ - __lsx_vst(a.val, ptr, 0); \ - } \ - inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vstelm_d(a.val, ptr, 0, 0); } \ - inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vstelm_d(a.val, ptr, 0, 1); } \ - -OPENCV_HAL_IMPL_LSX_LOADSTORE(v_uint8x16, uchar) -OPENCV_HAL_IMPL_LSX_LOADSTORE(v_int8x16, schar) -OPENCV_HAL_IMPL_LSX_LOADSTORE(v_uint16x8, ushort) -OPENCV_HAL_IMPL_LSX_LOADSTORE(v_int16x8, short) -OPENCV_HAL_IMPL_LSX_LOADSTORE(v_uint32x4, unsigned) -OPENCV_HAL_IMPL_LSX_LOADSTORE(v_int32x4, int) -OPENCV_HAL_IMPL_LSX_LOADSTORE(v_uint64x2, uint64) -OPENCV_HAL_IMPL_LSX_LOADSTORE(v_int64x2, int64) - -#define OPENCV_HAL_IMPL_LSX_LOADSTORE_FLT(_Tpvec, _Tp, halfreg) \ - inline _Tpvec v_load(const _Tp* ptr) \ - { return _Tpvec((halfreg)__lsx_vld(ptr, 0)); } \ - inline _Tpvec v_load_aligned(const _Tp* ptr) \ - { return _Tpvec((halfreg)__lsx_vld(ptr, 0)); } \ - inline _Tpvec v_load_low(const _Tp* ptr) \ - { return _Tpvec((halfreg)__lsx_vldrepl_d(ptr, 0)); } \ - inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ - { \ - __m128i vl = __lsx_vldrepl_d(ptr0, 0); \ - __m128i vh = __lsx_vldrepl_d(ptr1, 0); \ - return _Tpvec((halfreg)__lsx_vilvl_d(vh, vl)); \ - } \ - inline void v_store(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vst((__m128i)a.val, ptr, 0); } \ - inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vst((__m128i)a.val, ptr, 0); } \ - inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vst((__m128i)a.val, ptr, 0); } \ - inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode)\ - { \ - if( mode == hal::STORE_UNALIGNED) \ - __lsx_vst((__m128i)a.val, ptr, 0); \ - else if( mode == hal::STORE_ALIGNED_NOCACHE) \ - __lsx_vst((__m128i)a.val, ptr, 0); \ - else \ - __lsx_vst((__m128i)a.val, ptr, 0); \ - } \ - inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vstelm_d((__m128i)a.val, ptr, 0, 0); } \ - inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vstelm_d((__m128i)a.val, ptr, 0, 1); } \ - -OPENCV_HAL_IMPL_LSX_LOADSTORE_FLT(v_float32x4, float, __m128) -OPENCV_HAL_IMPL_LSX_LOADSTORE_FLT(v_float64x2, double, __m128d) - -inline __m128i _lsx_128_castps_si128(const __m128& v) -{ return __m128i(v); } - -inline __m128i _lsx_128_castpd_si128(const __m128d& v) -{ return __m128i(v); } - -#define OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, _Tpvecf, suffix, cast) \ - inline _Tpvec v_reinterpret_as_##suffix(const _Tpvecf& a) \ - { return _Tpvec(cast(a.val)); } - -#define OPENCV_HAL_IMPL_LSX_INIT(_Tpvec, _Tp, suffix, ssuffix, ctype_s) \ - inline _Tpvec v_setzero_##suffix() \ - { return _Tpvec(__lsx_vldi(0)); } \ - inline _Tpvec v_setall_##suffix(_Tp v) \ - { return _Tpvec(__lsx_vreplgr2vr_##ssuffix((ctype_s)v)); } \ - template <> inline _Tpvec v_setzero_() \ - { return v_setzero_##suffix(); } \ - template <> inline _Tpvec v_setall_(_Tp v) \ - { return v_setall_##suffix(v); } \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint8x16, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int8x16, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint16x8, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int16x8, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint32x4, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int32x4, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint64x2, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int64x2, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_float32x4, suffix, _lsx_128_castps_si128) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_float64x2, suffix, _lsx_128_castpd_si128) \ - -OPENCV_HAL_IMPL_LSX_INIT(v_uint8x16, uchar, u8, b, int) -OPENCV_HAL_IMPL_LSX_INIT(v_int8x16, schar, s8, b, int) -OPENCV_HAL_IMPL_LSX_INIT(v_uint16x8, ushort, u16, h, int) -OPENCV_HAL_IMPL_LSX_INIT(v_int16x8, short, s16, h, int) -OPENCV_HAL_IMPL_LSX_INIT(v_uint32x4, unsigned, u32, w, int) -OPENCV_HAL_IMPL_LSX_INIT(v_int32x4, int, s32, w, int) -OPENCV_HAL_IMPL_LSX_INIT(v_uint64x2, uint64, u64, d, long int) -OPENCV_HAL_IMPL_LSX_INIT(v_int64x2, int64, s64, d, long int) - -inline __m128 _lsx_128_castsi128_ps(const __m128i &v) -{ return __m128(v); } - -inline __m128d _lsx_128_castsi128_pd(const __m128i &v) -{ return __m128d(v); } - -#define OPENCV_HAL_IMPL_LSX_INIT_FLT(_Tpvec, _Tp, suffix, zsuffix, cast) \ - inline _Tpvec v_setzero_##suffix() \ - { return _Tpvec(__lsx_vldi(0)); } \ - inline _Tpvec v_setall_##suffix(_Tp v) \ - { return _Tpvec(_v128_setall_##zsuffix(v)); } \ - template <> inline _Tpvec v_setzero_() \ - { return v_setzero_##suffix(); } \ - template <> inline _Tpvec v_setall_(_Tp v) \ - { return v_setall_##suffix(v); } \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint8x16, suffix, cast) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int8x16, suffix, cast) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint16x8, suffix, cast) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int16x8, suffix, cast) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint32x4, suffix, cast) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int32x4, suffix, cast) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint64x2, suffix, cast) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int64x2, suffix, cast) \ - -OPENCV_HAL_IMPL_LSX_INIT_FLT(v_float32x4, float, f32, ps, _lsx_128_castsi128_ps) -OPENCV_HAL_IMPL_LSX_INIT_FLT(v_float64x2, double, f64, pd, _lsx_128_castsi128_pd) - -inline v_float32x4 v_reinterpret_as_f32(const v_float32x4& a) -{ return a; } -inline v_float32x4 v_reinterpret_as_f32(const v_float64x2& a) -{ return v_float32x4(_lsx_128_castps_si128(__m128(a.val))); } - -inline v_float64x2 v_reinterpret_as_f64(const v_float64x2& a) -{ return a; } -inline v_float64x2 v_reinterpret_as_f64(const v_float32x4& a) -{ return v_float64x2(_lsx_128_castpd_si128(__m128d(a.val))); } - -//////////////// Variant Value reordering /////////////// - -// unpacks -#define OPENCV_HAL_IMPL_LSX_UNPACK(_Tpvec, suffix) \ - inline _Tpvec v128_unpacklo(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(__lsx_vilvl_##suffix(__m128i(b.val), __m128i(a.val))); } \ - inline _Tpvec v128_unpackhi(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(__lsx_vilvh_##suffix(__m128i(b.val), __m128i(a.val))); } \ - -OPENCV_HAL_IMPL_LSX_UNPACK(v_uint8x16, b) -OPENCV_HAL_IMPL_LSX_UNPACK(v_int8x16, b) -OPENCV_HAL_IMPL_LSX_UNPACK(v_uint16x8, h) -OPENCV_HAL_IMPL_LSX_UNPACK(v_int16x8, h) -OPENCV_HAL_IMPL_LSX_UNPACK(v_uint32x4, w) -OPENCV_HAL_IMPL_LSX_UNPACK(v_int32x4, w) -OPENCV_HAL_IMPL_LSX_UNPACK(v_uint64x2, d) -OPENCV_HAL_IMPL_LSX_UNPACK(v_int64x2, d) -OPENCV_HAL_IMPL_LSX_UNPACK(v_float32x4, w) -OPENCV_HAL_IMPL_LSX_UNPACK(v_float64x2, d) - -//ZIP -#define OPENCV_HAL_IMPL_LSX_ZIP(_Tpvec) \ - inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ - { return (_Tpvec)__lsx_vilvl_d((__m128i)b.val, (__m128i)a.val); } \ - inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ - { return (_Tpvec)__lsx_vilvh_d((__m128i)b.val, (__m128i)a.val); } \ - inline void v_recombine(const _Tpvec& a, const _Tpvec& b, \ - _Tpvec& c, _Tpvec& d) \ - { \ - __m128i a1 = (__m128i)a.val, b1 = (__m128i)b.val; \ - c = _Tpvec(__lsx_vilvl_d(b1, a1)); \ - d = _Tpvec(__lsx_vilvh_d(b1, a1)); \ - } \ - inline void v_zip(const _Tpvec& a, const _Tpvec& b, \ - _Tpvec& ab0, _Tpvec& ab1) \ - { \ - ab0 = v128_unpacklo(a, b); \ - ab1 = v128_unpackhi(a, b); \ - } - -OPENCV_HAL_IMPL_LSX_ZIP(v_uint8x16) -OPENCV_HAL_IMPL_LSX_ZIP(v_int8x16) -OPENCV_HAL_IMPL_LSX_ZIP(v_uint16x8) -OPENCV_HAL_IMPL_LSX_ZIP(v_int16x8) -OPENCV_HAL_IMPL_LSX_ZIP(v_uint32x4) -OPENCV_HAL_IMPL_LSX_ZIP(v_int32x4) -OPENCV_HAL_IMPL_LSX_ZIP(v_uint64x2) -OPENCV_HAL_IMPL_LSX_ZIP(v_int64x2) -OPENCV_HAL_IMPL_LSX_ZIP(v_float32x4) -OPENCV_HAL_IMPL_LSX_ZIP(v_float64x2) - -////////// Arithmetic, bitwise and comparison operations ///////// - -/** Arithmetics **/ -#define OPENCV_HAL_IMPL_LSX_BIN_OP(bin_op, _Tpvec, intrin) \ - inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(intrin(a.val, b.val)); } - -OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_uint8x16, __lsx_vsadd_bu) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_uint8x16, __lsx_vssub_bu) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_int8x16, __lsx_vsadd_b) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_int8x16, __lsx_vssub_b) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_uint16x8, __lsx_vsadd_hu) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_uint16x8, __lsx_vssub_hu) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_int16x8, __lsx_vsadd_h) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_int16x8, __lsx_vssub_h) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_uint32x4, __lsx_vadd_w) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_uint32x4, __lsx_vsub_w) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_mul, v_uint32x4, __lsx_vmul_w) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_int32x4, __lsx_vadd_w) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_int32x4, __lsx_vsub_w) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_mul, v_int32x4, __lsx_vmul_w) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_uint64x2, __lsx_vadd_d) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_uint64x2, __lsx_vsub_d) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_int64x2, __lsx_vadd_d) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_int64x2, __lsx_vsub_d) - -OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_float32x4, __lsx_vfadd_s) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_float32x4, __lsx_vfsub_s) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_mul, v_float32x4, __lsx_vfmul_s) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_div, v_float32x4, __lsx_vfdiv_s) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_float64x2, __lsx_vfadd_d) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_float64x2, __lsx_vfsub_d) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_mul, v_float64x2, __lsx_vfmul_d) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_div, v_float64x2, __lsx_vfdiv_d) - -// saturating multiply 8-bit, 16-bit -inline v_uint8x16 v_mul(const v_uint8x16& a, const v_uint8x16& b) -{ - v_uint16x8 c, d; - v_mul_expand(a, b, c, d); - return v_pack(c, d); -} -inline v_int8x16 v_mul(const v_int8x16& a, const v_int8x16& b) -{ - v_int16x8 c, d; - v_mul_expand(a, b, c, d); - return v_pack(c, d); -} -inline v_uint16x8 v_mul(const v_uint16x8& a, const v_uint16x8& b) -{ - __m128i a0 = a.val, b0 = b.val; - __m128i pev = __lsx_vmulwev_w_hu(a0, b0); - __m128i pod = __lsx_vmulwod_w_hu(a0, b0); - __m128i pl = __lsx_vilvl_w(pod, pev); - __m128i ph = __lsx_vilvh_w(pod, pev); - return (v_uint16x8)__lsx_vssrlrni_hu_w(ph, pl, 0); -} -inline v_int16x8 v_mul(const v_int16x8& a, const v_int16x8& b) -{ - __m128i a0 = a.val, b0 = b.val; - __m128i pev = __lsx_vmulwev_w_h(a0, b0); - __m128i pod = __lsx_vmulwod_w_h(a0, b0); - __m128i pl = __lsx_vilvl_w(pod, pev); - __m128i ph = __lsx_vilvh_w(pod, pev); - return (v_int16x8)__lsx_vssrarni_h_w(ph, pl, 0); -} - -/** Non-saturating arithmetics **/ - -#define OPENCV_HAL_IMPL_LSX_BIN_FUNC(func, _Tpvec, intrin) \ - inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(intrin(a.val, b.val)); } \ - -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_add_wrap, v_uint8x16, __lsx_vadd_b) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_add_wrap, v_int8x16, __lsx_vadd_b) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_add_wrap, v_uint16x8, __lsx_vadd_h) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_add_wrap, v_int16x8, __lsx_vadd_h) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_sub_wrap, v_uint8x16, __lsx_vsub_b) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_sub_wrap, v_int8x16, __lsx_vsub_b) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_sub_wrap, v_uint16x8, __lsx_vsub_h) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_sub_wrap, v_int16x8, __lsx_vsub_h) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_mul_wrap, v_uint16x8, __lsx_vmul_h) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_mul_wrap, v_int16x8, __lsx_vmul_h) - -inline v_uint8x16 v_mul_wrap(const v_uint8x16& a, const v_uint8x16& b) -{ - __m128i a0 = a.val, b0 = b.val; - __m128i p0 = __lsx_vmulwev_h_bu(a0, b0); - __m128i p1 = __lsx_vmulwod_h_bu(a0, b0); - return v_uint8x16(__lsx_vpackev_b(p1, p0)); -} - -inline v_int8x16 v_mul_wrap(const v_int8x16& a, const v_int8x16& b) -{ - return v_reinterpret_as_s8(v_mul_wrap(v_reinterpret_as_u8(a), v_reinterpret_as_u8(b))); -} - -// Multiply and expand -inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b, - v_uint16x8& c, v_uint16x8& d) -{ - __m128i a0 = a.val, b0 = b.val; - __m128i p0 = __lsx_vmulwev_h_bu(a0, b0); - __m128i p1 = __lsx_vmulwod_h_bu(a0, b0); - c.val = __lsx_vilvl_h(p1, p0); - d.val = __lsx_vilvh_h(p1, p0); -} -inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b, - v_int16x8& c, v_int16x8& d) -{ - __m128i a0 = a.val, b0 = b.val; - __m128i p0 = __lsx_vmulwev_h_b(a0, b0); - __m128i p1 = __lsx_vmulwod_h_b(a0, b0); - c.val = __lsx_vilvl_h(p1, p0); - d.val = __lsx_vilvh_h(p1, p0); -} -inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, - v_int32x4& c, v_int32x4& d) -{ - __m128i a0 = a.val, b0 = b.val; - __m128i p0 = __lsx_vmulwev_w_h(a0, b0); - __m128i p1 = __lsx_vmulwod_w_h(a0, b0); - c.val = __lsx_vilvl_w(p1, p0); - d.val = __lsx_vilvh_w(p1, p0); -} -inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, - v_uint32x4& c, v_uint32x4& d) -{ - __m128i a0 = a.val, b0 = b.val; - __m128i p0 = __lsx_vmulwev_w_hu(a0, b0); - __m128i p1 = __lsx_vmulwod_w_hu(a0, b0); - c.val = __lsx_vilvl_w(p1, p0); - d.val = __lsx_vilvh_w(p1, p0); -} -inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, - v_uint64x2& c, v_uint64x2& d) -{ - __m128i a0 = a.val, b0 = b.val; - __m128i p0 = __lsx_vmulwev_d_wu(a0, b0); - __m128i p1 = __lsx_vmulwod_d_wu(a0, b0); - c.val = __lsx_vilvl_d(p1, p0); - d.val = __lsx_vilvh_d(p1, p0); -} -inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) -{ return v_int16x8(__lsx_vmuh_h(a.val, b.val)); } -inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) -{ return v_uint16x8(__lsx_vmuh_hu(a.val, b.val)); } - -/** Bitwise shifts **/ -#define OPENCV_HAL_IMPL_LSX_SHIFT_OP(_Tpuvec, _Tpsvec, suffix, srai) \ - inline _Tpuvec v_shl(const _Tpuvec& a, int imm) \ - { return _Tpuvec(__lsx_vsll_##suffix(a.val, __lsx_vreplgr2vr_##suffix(imm))); } \ - inline _Tpsvec v_shl(const _Tpsvec& a, int imm) \ - { return _Tpsvec(__lsx_vsll_##suffix(a.val, __lsx_vreplgr2vr_##suffix(imm))); } \ - inline _Tpuvec v_shr(const _Tpuvec& a, int imm) \ - { return _Tpuvec(__lsx_vsrl_##suffix(a.val, __lsx_vreplgr2vr_##suffix(imm))); } \ - inline _Tpsvec v_shr(const _Tpsvec& a, int imm) \ - { return _Tpsvec(srai(a.val, __lsx_vreplgr2vr_##suffix(imm))); } \ - template \ - inline _Tpuvec v_shl(const _Tpuvec& a) \ - { return _Tpuvec(__lsx_vslli_##suffix(a.val, imm)); } \ - template \ - inline _Tpsvec v_shl(const _Tpsvec& a) \ - { return _Tpsvec(__lsx_vslli_##suffix(a.val, imm)); } \ - template \ - inline _Tpuvec v_shr(const _Tpuvec& a) \ - { return _Tpuvec(__lsx_vsrli_##suffix(a.val, imm)); } \ - template \ - inline _Tpsvec v_shr(const _Tpsvec& a) \ - { return _Tpsvec(__lsx_vsrai_##suffix(a.val, imm)); } \ - -OPENCV_HAL_IMPL_LSX_SHIFT_OP(v_uint16x8, v_int16x8, h, __lsx_vsra_h) -OPENCV_HAL_IMPL_LSX_SHIFT_OP(v_uint32x4, v_int32x4, w, __lsx_vsra_w) -OPENCV_HAL_IMPL_LSX_SHIFT_OP(v_uint64x2, v_int64x2, d, __lsx_vsra_d) - -/** Bitwise logic **/ -#define OPENCV_HAL_IMPL_LSX_LOGIC_OP(_Tpvec, suffix) \ - OPENCV_HAL_IMPL_LSX_BIN_OP(v_and, _Tpvec, __lsx_vand_##suffix) \ - OPENCV_HAL_IMPL_LSX_BIN_OP(v_or, _Tpvec, __lsx_vor_##suffix) \ - OPENCV_HAL_IMPL_LSX_BIN_OP(v_xor, _Tpvec, __lsx_vxor_##suffix) \ - inline _Tpvec v_not(const _Tpvec& a) \ - { return _Tpvec(__lsx_vnori_b(a.val, 0)); } \ - -OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_uint8x16, v) -OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_int8x16, v) -OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_uint16x8, v) -OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_int16x8, v) -OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_uint32x4, v) -OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_int32x4, v) -OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_uint64x2, v) -OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_int64x2, v) - -#define OPENCV_HAL_IMPL_LSX_FLOAT_BIN_OP(bin_op, _Tpvec, intrin, cast) \ - inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(intrin((__m128i)(a.val), (__m128i)(b.val))); } - -#define OPENCV_HAL_IMPL_LSX_FLOAT_LOGIC_OP(_Tpvec, cast) \ - OPENCV_HAL_IMPL_LSX_FLOAT_BIN_OP(v_and, _Tpvec, __lsx_vand_v, cast) \ - OPENCV_HAL_IMPL_LSX_FLOAT_BIN_OP(v_or, _Tpvec, __lsx_vor_v, cast) \ - OPENCV_HAL_IMPL_LSX_FLOAT_BIN_OP(v_xor, _Tpvec, __lsx_vxor_v, cast) \ - inline _Tpvec v_not(const _Tpvec& a) \ - { return _Tpvec(__lsx_vnori_b((__m128i)(a.val), 0)); } \ - -OPENCV_HAL_IMPL_LSX_FLOAT_LOGIC_OP(v_float32x4, _lsx_128_castsi128_ps) -OPENCV_HAL_IMPL_LSX_FLOAT_LOGIC_OP(v_float64x2, _lsx_128_castsi128_pd) - -/** Select **/ -#define OPENCV_HAL_IMPL_LSX_SELECT(_Tpvec) \ - inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(__lsx_vbitsel_v(b.val, a.val, mask.val)); } \ - -OPENCV_HAL_IMPL_LSX_SELECT(v_uint8x16) -OPENCV_HAL_IMPL_LSX_SELECT(v_int8x16) -OPENCV_HAL_IMPL_LSX_SELECT(v_uint16x8) -OPENCV_HAL_IMPL_LSX_SELECT(v_int16x8) -OPENCV_HAL_IMPL_LSX_SELECT(v_uint32x4) -OPENCV_HAL_IMPL_LSX_SELECT(v_int32x4) - -inline v_float32x4 v_select(const v_float32x4 &mask, const v_float32x4 &a, const v_float32x4 &b) -{ return v_float32x4(__lsx_vbitsel_v((__m128i)b.val, (__m128i)a.val, (__m128i)mask.val)); } -inline v_float64x2 v_select(const v_float64x2 &mask, const v_float64x2 &a, const v_float64x2 &b) -{ return v_float64x2(__lsx_vbitsel_v((__m128i)b.val, (__m128i)a.val, (__m128i)mask.val)); } - -/** Comparison **/ -#define OPENCV_HAL_IMPL_LSX_CMP_OP_OV(_Tpvec) \ - inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ - { return v_not(v_eq(a, b)); } \ - inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ - { return v_gt(b, a); } \ - inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ - { return v_not(v_lt(a, b)); } \ - inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ - { return v_ge(b, a); } \ - -#define OPENCV_HAL_IMPL_LSX_CMP_OP_INT(_Tpuvec, _Tpsvec, suffix, usuffix) \ - inline _Tpuvec v_eq(const _Tpuvec& a, const _Tpuvec& b) \ - { return _Tpuvec(__lsx_vseq_##suffix(a.val, b.val)); } \ - inline _Tpuvec v_gt(const _Tpuvec& a, const _Tpuvec& b) \ - { return _Tpuvec(__lsx_vslt_##usuffix(b.val, a.val)); } \ - inline _Tpsvec v_eq(const _Tpsvec& a, const _Tpsvec& b) \ - { return _Tpsvec(__lsx_vseq_##suffix(a.val, b.val)); } \ - inline _Tpsvec v_gt(const _Tpsvec& a, const _Tpsvec& b) \ - { return _Tpsvec(__lsx_vslt_##suffix(b.val, a.val)); } \ - OPENCV_HAL_IMPL_LSX_CMP_OP_OV(_Tpuvec) \ - OPENCV_HAL_IMPL_LSX_CMP_OP_OV(_Tpsvec) - -OPENCV_HAL_IMPL_LSX_CMP_OP_INT(v_uint8x16, v_int8x16, b, bu) -OPENCV_HAL_IMPL_LSX_CMP_OP_INT(v_uint16x8, v_int16x8, h, hu) -OPENCV_HAL_IMPL_LSX_CMP_OP_INT(v_uint32x4, v_int32x4, w, wu) - -#define OPENCV_HAL_IMPL_LSX_CMP_OP_64BIT(_Tpvec, suffix) \ - inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(__lsx_vseq_##suffix(a.val, b.val)); } \ - inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ - { return v_not(v_eq(a, b)); } - -OPENCV_HAL_IMPL_LSX_CMP_OP_64BIT(v_uint64x2, d) -OPENCV_HAL_IMPL_LSX_CMP_OP_64BIT(v_int64x2, d) - -#define OPENCV_HAL_IMPL_LSX_CMP_FLT(bin_op, suffix, _Tpvec, ssuffix) \ - inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(__lsx_##suffix##_##ssuffix(a.val, b.val)); } \ - -#define OPENCV_HAL_IMPL_LSX_CMP_OP_FLT(_Tpvec, ssuffix) \ - OPENCV_HAL_IMPL_LSX_CMP_FLT(v_eq, vfcmp_ceq, _Tpvec, ssuffix) \ - OPENCV_HAL_IMPL_LSX_CMP_FLT(v_ne, vfcmp_cne, _Tpvec, ssuffix) \ - OPENCV_HAL_IMPL_LSX_CMP_FLT(v_lt, vfcmp_clt, _Tpvec, ssuffix) \ - OPENCV_HAL_IMPL_LSX_CMP_FLT(v_le, vfcmp_cle, _Tpvec, ssuffix) \ - -OPENCV_HAL_IMPL_LSX_CMP_OP_FLT(v_float32x4, s) -OPENCV_HAL_IMPL_LSX_CMP_OP_FLT(v_float64x2, d) - -inline v_float32x4 v_gt(const v_float32x4 &a, const v_float32x4 &b) -{ return v_float32x4(__lsx_vfcmp_clt_s(b.val, a.val)); } - -inline v_float32x4 v_ge(const v_float32x4 &a, const v_float32x4 &b) -{ return v_float32x4(__lsx_vfcmp_cle_s(b.val, a.val)); } - -inline v_float64x2 v_gt(const v_float64x2 &a, const v_float64x2 &b) -{ return v_float64x2(__lsx_vfcmp_clt_d(b.val, a.val)); } - -inline v_float64x2 v_ge(const v_float64x2 &a, const v_float64x2 &b) -{ return v_float64x2(__lsx_vfcmp_cle_d(b.val, a.val)); } - -inline v_float32x4 v_not_nan(const v_float32x4& a) -{ return v_float32x4(__lsx_vfcmp_cor_s(a.val, a.val)); } - -inline v_float64x2 v_not_nan(const v_float64x2& a) -{ return v_float64x2(__lsx_vfcmp_cor_d(a.val, a.val)); } - -/** min/max **/ -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_uint8x16, __lsx_vmin_bu) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_uint8x16, __lsx_vmax_bu) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_int8x16, __lsx_vmin_b) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_int8x16, __lsx_vmax_b) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_uint16x8, __lsx_vmin_hu) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_uint16x8, __lsx_vmax_hu) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_int16x8, __lsx_vmin_h) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_int16x8, __lsx_vmax_h) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_uint32x4, __lsx_vmin_wu) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_uint32x4, __lsx_vmax_wu) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_int32x4, __lsx_vmin_w) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_int32x4, __lsx_vmax_w) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_float32x4, __lsx_vfmin_s) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_float32x4, __lsx_vfmax_s) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_float64x2, __lsx_vfmin_d) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_float64x2, __lsx_vfmax_d) - -template 16)), - bool is_first = (imm == 0), - bool is_half = (imm == 8), - bool is_second = (imm == 16), - bool is_other = (((imm > 0) && (imm < 8)) || ((imm > 8) && (imm < 16)))> -class v_lsx_palignr_u8_class; - -template -class v_lsx_palignr_u8_class; - -template -class v_lsx_palignr_u8_class -{ -public: - inline __m128i operator()(const __m128i& a, const __m128i& b) const - { - CV_UNUSED(b); - return a; - } -}; - -template -class v_lsx_palignr_u8_class -{ -public: - inline __m128i operator()(const __m128i& a, const __m128i& b) const - { - return __lsx_vshuf4i_d(a, b, 0x9); - } -}; - -template -class v_lsx_palignr_u8_class -{ -public: - inline __m128i operator()(const __m128i& a, const __m128i& b) const - { - CV_UNUSED(a); - return b; - } -}; - -template -class v_lsx_palignr_u8_class -{ -public: - inline __m128i operator()(const __m128i& a, const __m128i& b) const - { - enum { imm2 = (sizeof(__m128i) - imm) }; - return __lsx_vor_v(__lsx_vbsrl_v(a, imm), __lsx_vbsll_v(b, imm2)); - } -}; - -template -inline __m128i v_lsx_palignr_u8(const __m128i& a, const __m128i& b) -{ - CV_StaticAssert((imm >= 0) && (imm <= 16), "Invalid imm for v_lsx_palignr_u8"); - return v_lsx_palignr_u8_class()(a, b); -} -/** Rotate **/ -#define OPENCV_HAL_IMPL_LSX_ROTATE_CAST(_Tpvec, cast) \ - template \ - inline _Tpvec v_rotate_right(const _Tpvec &a) \ - { \ - enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type))}; \ - __m128i ret = __lsx_vbsrl_v((__m128i)a.val, imm2); \ - return _Tpvec(cast(ret)); \ - } \ - template \ - inline _Tpvec v_rotate_left(const _Tpvec &a) \ - { \ - enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type))}; \ - __m128i ret = __lsx_vbsll_v((__m128i)a.val, imm2); \ - return _Tpvec(cast(ret)); \ - } \ - template \ - inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ - { \ - enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type))}; \ - return _Tpvec(cast(v_lsx_palignr_u8((__m128i)a.val, (__m128i)b.val))); \ - } \ - template \ - inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ - { \ - enum { imm2 = ((_Tpvec::nlanes - imm) * sizeof(typename _Tpvec::lane_type))}; \ - return _Tpvec(cast(v_lsx_palignr_u8((__m128i)b.val, (__m128i)a.val))); \ - } - -OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_uint8x16, OPENCV_HAL_NOP) \ -OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_int8x16, OPENCV_HAL_NOP) \ -OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_uint16x8, OPENCV_HAL_NOP) \ -OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_int16x8, OPENCV_HAL_NOP) \ -OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_uint32x4, OPENCV_HAL_NOP) \ -OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_int32x4, OPENCV_HAL_NOP) \ -OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_uint64x2, OPENCV_HAL_NOP) \ -OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_int64x2, OPENCV_HAL_NOP) \ - -OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_float32x4, _lsx_128_castsi128_ps) -OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_float64x2, _lsx_128_castsi128_pd) - -/** Rverse **/ -inline v_uint8x16 v_reverse(const v_uint8x16 &a) -{ - __m128i vec = __lsx_vshuf4i_b(a.val, 0x1B); - return v_uint8x16(__lsx_vshuf4i_w(vec, 0x1B)); -} - -inline v_int8x16 v_reverse(const v_int8x16 &a) -{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } - -inline v_uint16x8 v_reverse(const v_uint16x8 &a) -{ - __m128i vec = __lsx_vshuf4i_h(a.val, 0x1B); - return v_uint16x8(__lsx_vshuf4i_w(vec, 0x4E)); -} - -inline v_int16x8 v_reverse(const v_int16x8 &a) -{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } - -inline v_uint32x4 v_reverse(const v_uint32x4 &a) -{ return v_uint32x4(__lsx_vshuf4i_w(a.val, 0x1B)); } - -inline v_int32x4 v_reverse(const v_int32x4 &a) -{ return v_int32x4(__lsx_vshuf4i_w(a.val, 0x1B)); } - -inline v_uint64x2 v_reverse(const v_uint64x2 &a) -{ return v_uint64x2(__lsx_vshuf4i_w(a.val, 0x4E)); } - -inline v_int64x2 v_reverse(const v_int64x2 &a) -{ return v_int64x2(__lsx_vshuf4i_w(a.val, 0x4E)); } - -inline v_float32x4 v_reverse(const v_float32x4 &a) -{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_float64x2 v_reverse(const v_float64x2 &a) -{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } - -////////////// Reduce and mask //////////// - -/** Reduce **/ -// this function is return a[0]+a[1]+...+a[31] -inline unsigned v_reduce_sum(const v_uint8x16& a) -{ - __m128i t1 = __lsx_vhaddw_hu_bu(a.val, a.val); - __m128i t2 = __lsx_vhaddw_wu_hu(t1, t1); - __m128i t3 = __lsx_vhaddw_du_wu(t2, t2); - __m128i t4 = __lsx_vhaddw_qu_du(t3, t3); - return (unsigned)__lsx_vpickve2gr_w(t4, 0); -} - -inline int v_reduce_sum(const v_int8x16 &a) -{ - __m128i t1 = __lsx_vhaddw_h_b(a.val, a.val); - __m128i t2 = __lsx_vhaddw_w_h(t1, t1); - __m128i t3 = __lsx_vhaddw_d_w(t2, t2); - __m128i t4 = __lsx_vhaddw_q_d(t3, t3); - return (int)__lsx_vpickve2gr_w(t4, 0); -} - -#define OPENCV_HAL_IMPL_LSX_REDUCE_16(_Tpvec, sctype, func, intrin) \ - inline sctype v_reduce_##func(const _Tpvec& a) \ - { \ - __m128i val = intrin(a.val, __lsx_vbsrl_v(a.val, 8)); \ - val = intrin(val, __lsx_vbsrl_v(val, 4)); \ - val = intrin(val, __lsx_vbsrl_v(val, 2)); \ - val = intrin(val, __lsx_vbsrl_v(val, 1)); \ - return (sctype)__lsx_vpickve2gr_b(val, 0); \ - } - -OPENCV_HAL_IMPL_LSX_REDUCE_16(v_uint8x16, uchar, min, __lsx_vmin_bu) -OPENCV_HAL_IMPL_LSX_REDUCE_16(v_uint8x16, uchar, max, __lsx_vmax_bu) -OPENCV_HAL_IMPL_LSX_REDUCE_16(v_int8x16, schar, min, __lsx_vmin_b) -OPENCV_HAL_IMPL_LSX_REDUCE_16(v_int8x16, schar, max, __lsx_vmax_b) - -#define OPENCV_HAL_IMPL_LSX_REDUCE_8(_Tpvec, sctype, func, intrin) \ - inline sctype v_reduce_##func(const _Tpvec &a) \ - { \ - __m128i val = intrin(a.val, __lsx_vbsrl_v(a.val, 8)); \ - val = intrin(val, __lsx_vbsrl_v(val, 4)); \ - val = intrin(val, __lsx_vbsrl_v(val, 2)); \ - return (sctype)__lsx_vpickve2gr_h(val, 0); \ - } - -OPENCV_HAL_IMPL_LSX_REDUCE_8(v_uint16x8, ushort, min, __lsx_vmin_hu) -OPENCV_HAL_IMPL_LSX_REDUCE_8(v_uint16x8, ushort, max, __lsx_vmax_hu) -OPENCV_HAL_IMPL_LSX_REDUCE_8(v_int16x8, short, min, __lsx_vmin_h) -OPENCV_HAL_IMPL_LSX_REDUCE_8(v_int16x8, short, max, __lsx_vmax_h) - -#define OPENCV_HAL_IMPL_LSX_REDUCE_4(_Tpvec, sctype, func, intrin) \ - inline sctype v_reduce_##func(const _Tpvec &a) \ - { \ - __m128i val = intrin(a.val, __lsx_vbsrl_v(a.val, 8)); \ - val = intrin(val, __lsx_vbsrl_v(val, 4)); \ - return (sctype)__lsx_vpickve2gr_w(val, 0); \ - } - -OPENCV_HAL_IMPL_LSX_REDUCE_4(v_uint32x4, unsigned, min, __lsx_vmin_wu) -OPENCV_HAL_IMPL_LSX_REDUCE_4(v_uint32x4, unsigned, max, __lsx_vmax_wu) -OPENCV_HAL_IMPL_LSX_REDUCE_4(v_int32x4, int, min, __lsx_vmin_w) -OPENCV_HAL_IMPL_LSX_REDUCE_4(v_int32x4, int, max, __lsx_vmax_w) - -#define OPENCV_HAL_IMPL_LSX_REDUCE_FLT(func, intrin) \ - inline float v_reduce_##func(const v_float32x4 &a) \ - { \ - __m128 val = a.val; \ - val = intrin(val, (__m128)__lsx_vbsrl_v((__m128i)val, 8)); \ - val = intrin(val, (__m128)__lsx_vbsrl_v((__m128i)val, 4)); \ - float *fval = (float*)&val; \ - return fval[0]; \ - } - -OPENCV_HAL_IMPL_LSX_REDUCE_FLT(min, __lsx_vfmin_s) -OPENCV_HAL_IMPL_LSX_REDUCE_FLT(max, __lsx_vfmax_s) - -inline int v_reduce_sum(const v_int32x4 &a) -{ - __m128i t1 = __lsx_vhaddw_d_w(a.val, a.val); - __m128i t2 = __lsx_vhaddw_q_d(t1, t1); - return (int)__lsx_vpickve2gr_w(t2, 0); -} - -inline unsigned v_reduce_sum(const v_uint32x4 &a) -{ - __m128i t1 = __lsx_vhaddw_du_wu(a.val, a.val); - __m128i t2 = __lsx_vhaddw_qu_du(t1, t1); - return (int)__lsx_vpickve2gr_w(t2, 0); -} - -inline int v_reduce_sum(const v_int16x8 &a) -{ - __m128i t1 = __lsx_vhaddw_w_h(a.val, a.val); - __m128i t2 = __lsx_vhaddw_d_w(t1, t1); - __m128i t3 = __lsx_vhaddw_q_d(t2, t2); - return (int)__lsx_vpickve2gr_w(t3, 0); -} - -inline unsigned v_reduce_sum(const v_uint16x8 &a) -{ - __m128i t1 = __lsx_vhaddw_wu_hu(a.val, a.val); - __m128i t2 = __lsx_vhaddw_du_wu(t1, t1); - __m128i t3 = __lsx_vhaddw_qu_du(t2, t2); - return (int)__lsx_vpickve2gr_w(t3, 0); -} - -inline float v_reduce_sum(const v_float32x4 &a) -{ - __m128i val = (__m128i)a.val; - val = __lsx_vbsrl_v(val, 8); - __m128 result = __lsx_vfadd_s(a.val, (__m128)val); - float *pa = (float*)&result; - return (float)(pa[0] + pa[1]); -} - -inline uint64 v_reduce_sum(const v_uint64x2 &a) -{ - __m128i t0 = __lsx_vhaddw_qu_du(a.val, a.val); - return (uint64)__lsx_vpickve2gr_du(t0, 0); -} - -inline int64 v_reduce_sum(const v_int64x2 &a) -{ - __m128i t0 = __lsx_vhaddw_q_d(a.val, a.val); - return (int64)__lsx_vpickve2gr_d(t0, 0); -} - -inline double v_reduce_sum(const v_float64x2 &a) -{ - double *pa = (double*)&a; - return pa[0] + pa[1]; -} - -inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, - const v_float32x4& c, const v_float32x4& d) -{ - __m128i a0 = (__m128i)a.val; - __m128i b0 = (__m128i)b.val; - __m128i c0 = (__m128i)c.val; - __m128i d0 = (__m128i)d.val; - __m128i ac_l = __lsx_vilvl_w(c0, a0); - __m128i ac_h = __lsx_vilvh_w(c0, a0); - __m128i bd_l = __lsx_vilvl_w(d0, b0); - __m128i bd_h = __lsx_vilvh_w(d0, b0); - __m128 ac = __lsx_vfadd_s((__m128)ac_l, (__m128)ac_h); - __m128 bd = __lsx_vfadd_s((__m128)bd_l, (__m128)bd_h); - return v_float32x4(__lsx_vfadd_s((__m128)__lsx_vilvl_w((__m128i)bd, (__m128i)ac), - (__m128)__lsx_vilvh_w((__m128i)bd, (__m128i)ac))); -} - -inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b) -{ - __m128i t0 = __lsx_vabsd_b(a.val, b.val); - __m128i t1 = __lsx_vhaddw_hu_bu(t0, t0); - __m128i t2 = __lsx_vhaddw_wu_hu(t1, t1); - __m128i t3 = __lsx_vhaddw_du_wu(t2, t2); - __m128i t4 = __lsx_vhaddw_qu_du(t3, t3); - return (unsigned)__lsx_vpickve2gr_w(t4, 0); -} - -inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b) -{ - __m128i t0 = __lsx_vabsd_bu(a.val, b.val); - __m128i t1 = __lsx_vhaddw_hu_bu(t0, t0); - __m128i t2 = __lsx_vhaddw_wu_hu(t1, t1); - __m128i t3 = __lsx_vhaddw_du_wu(t2, t2); - __m128i t4 = __lsx_vhaddw_qu_du(t3, t3); - return (unsigned)__lsx_vpickve2gr_w(t4, 0); -} - -inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b) -{ - __m128i t0 = __lsx_vabsd_hu(a.val, b.val); - __m128i t1 = __lsx_vhaddw_wu_hu(t0, t0); - __m128i t2 = __lsx_vhaddw_du_wu(t1, t1); - __m128i t3 = __lsx_vhaddw_qu_du(t2, t2); - return (unsigned)__lsx_vpickve2gr_w(t3, 0); -} - -inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b) -{ - __m128i t0 = __lsx_vabsd_h(a.val, b.val); - __m128i t1 = __lsx_vhaddw_wu_hu(t0, t0); - __m128i t2 = __lsx_vhaddw_du_wu(t1, t1); - __m128i t3 = __lsx_vhaddw_qu_du(t2, t2); - return (unsigned)__lsx_vpickve2gr_w(t3, 0); -} - -inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b) -{ - __m128i t0 = __lsx_vabsd_wu(a.val, b.val); - __m128i t1 = __lsx_vhaddw_du_wu(t0, t0); - __m128i t2 = __lsx_vhaddw_qu_du(t1, t1); - return (unsigned)__lsx_vpickve2gr_w(t2, 0); -} - -inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b) -{ - __m128i t0 = __lsx_vabsd_w(a.val, b.val); - __m128i t1 = __lsx_vhaddw_du_wu(t0, t0); - __m128i t2 = __lsx_vhaddw_qu_du(t1, t1); - return (unsigned)__lsx_vpickve2gr_w(t2, 0); -} - -inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) -{ - v_float32x4 a_b = v_sub(a, b); - return v_reduce_sum(v_float32x4((__m128i)a_b.val & __lsx_vreplgr2vr_w(0x7fffffff))); -} - -/** Popcount **/ -#define OPENCV_HAL_IMPL_LSX_POPCOUNT(_Tpvec, _Tp, suffix) \ -inline _Tpvec v_popcount(const _Tp& a) \ -{ return _Tpvec(__lsx_vpcnt_##suffix(a.val)); } - -OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint8x16, v_uint8x16, b); -OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint8x16, v_int8x16, b); -OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint16x8, v_uint16x8, h); -OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint16x8, v_int16x8, h); -OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint32x4, v_uint32x4, w); -OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint32x4, v_int32x4, w); -OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint64x2, v_uint64x2, d); -OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint64x2, v_int64x2, d); - -/** Mask **/ -#define OPENCV_HAL_IMPL_REINTERPRET_INT(ft, tt) \ -inline tt reinterpret_int(ft x) { union {ft l; tt i;} v; v.l = x; return v.i; } -OPENCV_HAL_IMPL_REINTERPRET_INT(uchar, schar) -OPENCV_HAL_IMPL_REINTERPRET_INT(schar, schar) -OPENCV_HAL_IMPL_REINTERPRET_INT(ushort, short) -OPENCV_HAL_IMPL_REINTERPRET_INT(short, short) -OPENCV_HAL_IMPL_REINTERPRET_INT(unsigned, int) -OPENCV_HAL_IMPL_REINTERPRET_INT(int, int) -OPENCV_HAL_IMPL_REINTERPRET_INT(float, int) -OPENCV_HAL_IMPL_REINTERPRET_INT(uint64, int64) -OPENCV_HAL_IMPL_REINTERPRET_INT(int64, int64) -OPENCV_HAL_IMPL_REINTERPRET_INT(double, int64) - -inline int v_signmask(const v_int8x16& a) -{ - __m128i result = __lsx_vmskltz_b(a.val); - return __lsx_vpickve2gr_w(result, 0); -} -inline int v_signmask(const v_uint8x16& a) -{ return v_signmask(v_reinterpret_as_s8(a)) ;} - -inline int v_signmask(const v_int16x8 &a) -{ - __m128i result = __lsx_vmskltz_h(a.val); - return __lsx_vpickve2gr_w(result, 0); -} -inline int v_signmask(const v_uint16x8 &a) -{ return v_signmask(v_reinterpret_as_s16(a)); } - -inline int v_signmask(const v_uint32x4& a) -{ - __m128i result = __lsx_vmskltz_w(a.val); - return __lsx_vpickve2gr_w(result, 0); -} -inline int v_signmask(const v_int32x4& a) -{ return v_signmask(v_reinterpret_as_u32(a)); } - -inline int v_signmask(const v_uint64x2& a) -{ - __m128i result = __lsx_vmskltz_d(a.val); - return __lsx_vpickve2gr_w(result, 0); -} -inline int v_signmask(const v_int64x2& a) -{ return v_signmask(v_reinterpret_as_u64(a)); } - -inline int v_signmask(const v_float32x4& a) -{ return v_signmask(*(v_int32x4*)(&a)); } - -inline int v_signmask(const v_float64x2& a) -{ return v_signmask(*(v_int64x2*)(&a)); } - -inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } -inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } -inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } -inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } -inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } -inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } -inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } - -/** Checks **/ -#define OPENCV_HAL_IMPL_LSX_CHECK(_Tpvec, allmask) \ - inline bool v_check_all(const _Tpvec& a) { return v_signmask(a) == allmask; } \ - inline bool v_check_any(const _Tpvec& a) { return v_signmask(a) != 0; } -OPENCV_HAL_IMPL_LSX_CHECK(v_uint8x16, 65535) -OPENCV_HAL_IMPL_LSX_CHECK(v_int8x16, 65535) -OPENCV_HAL_IMPL_LSX_CHECK(v_uint16x8, 255); -OPENCV_HAL_IMPL_LSX_CHECK(v_int16x8, 255); -OPENCV_HAL_IMPL_LSX_CHECK(v_uint32x4, 15) -OPENCV_HAL_IMPL_LSX_CHECK(v_int32x4, 15) -OPENCV_HAL_IMPL_LSX_CHECK(v_uint64x2, 3) -OPENCV_HAL_IMPL_LSX_CHECK(v_int64x2, 3) -OPENCV_HAL_IMPL_LSX_CHECK(v_float32x4, 15) -OPENCV_HAL_IMPL_LSX_CHECK(v_float64x2, 3) - -///////////// Other math ///////////// - -/** Some frequent operations **/ -#define OPENCV_HAL_IMPL_LSX_MULADD(_Tpvec, suffix) \ - inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ - { return _Tpvec(__lsx_vfmadd_##suffix(a.val, b.val, c.val)); } \ - inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec &b, const _Tpvec& c) \ - { return _Tpvec(__lsx_vfmadd_##suffix(a.val, b.val, c.val)); } \ - inline _Tpvec v_sqrt(const _Tpvec& x) \ - { return _Tpvec(__lsx_vfsqrt_##suffix(x.val)); } \ - inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ - { return v_fma(a, a, v_mul(b, b)); } \ - inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ - { return v_sqrt(v_fma(a, a, v_mul(b, b))); } - -OPENCV_HAL_IMPL_LSX_MULADD(v_float32x4, s) -OPENCV_HAL_IMPL_LSX_MULADD(v_float64x2, d) - -inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ return v_int32x4(__lsx_vmadd_w(c.val, a.val, b.val)); } - -inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ return v_fma(a, b, c); } - -inline v_float32x4 v_invsqrt(const v_float32x4& x) -{ - return v_float32x4(__lsx_vfrsqrt_s(x.val)); -} - -inline v_float64x2 v_invsqrt(const v_float64x2& x) -{ - return v_float64x2(__lsx_vfrsqrt_d(x.val)); -} - -/** Absolute values **/ -#define OPENCV_HAL_IMPL_LSX_ABS(_Tpvec, suffix) \ - inline v_u##_Tpvec v_abs(const v_##_Tpvec& x) \ - { return v_u##_Tpvec(__lsx_vabsd_##suffix(x.val, __lsx_vldi(0))); } - -OPENCV_HAL_IMPL_LSX_ABS(int8x16, b) -OPENCV_HAL_IMPL_LSX_ABS(int16x8, h) -OPENCV_HAL_IMPL_LSX_ABS(int32x4, w) - -inline v_float32x4 v_abs(const v_float32x4& x) -{ return v_float32x4(*((__m128i*)&x) & __lsx_vreplgr2vr_w(0x7fffffff)); } -inline v_float64x2 v_abs(const v_float64x2& x) -{ return v_float64x2(*((__m128i*)&x) & __lsx_vreplgr2vr_d(0x7fffffffffffffff)); } - -/** Absolute difference **/ - -inline v_uint8x16 v_absdiff(const v_uint8x16& a, const v_uint8x16& b) -{ return (v_uint8x16)__lsx_vabsd_bu(a.val, b.val); } -inline v_uint16x8 v_absdiff(const v_uint16x8& a, const v_uint16x8& b) -{ return (v_uint16x8)__lsx_vabsd_hu(a.val, b.val); } -inline v_uint32x4 v_absdiff(const v_uint32x4& a, const v_uint32x4& b) -{ return (v_uint32x4)__lsx_vabsd_wu(a.val, b.val); } - -inline v_uint8x16 v_absdiff(const v_int8x16& a, const v_int8x16& b) -{ return (v_uint8x16)__lsx_vabsd_b(a.val, b.val); } -inline v_uint16x8 v_absdiff(const v_int16x8& a, const v_int16x8& b) -{ return (v_uint16x8)__lsx_vabsd_h(a.val, b.val); } -inline v_uint32x4 v_absdiff(const v_int32x4& a, const v_int32x4& b) -{ return (v_uint32x4)__lsx_vabsd_w(a.val, b.val); } - -inline v_float32x4 v_absdiff(const v_float32x4& a, const v_float32x4& b) -{ return v_abs(v_sub(a, b)); } - -inline v_float64x2 v_absdiff(const v_float64x2& a, const v_float64x2& b) -{ return v_abs(v_sub(a, b)); } - -/** Saturating absolute difference **/ -inline v_int8x16 v_absdiffs(const v_int8x16& a, const v_int8x16& b) -{ - v_int8x16 d = v_sub(a, b); - v_int8x16 m = v_lt(a, b); - return v_sub(v_xor(d, m), m); -} -inline v_int16x8 v_absdiffs(const v_int16x8& a, const v_int16x8& b) -{ return v_sub(v_max(a, b), v_min(a, b)); } - -///////// Conversions ///////// - -/** Rounding **/ -inline v_int32x4 v_round(const v_float32x4& a) -{ return v_int32x4(__lsx_vftint_w_s(a.val)); } - -inline v_int32x4 v_round(const v_float64x2& a) -{ return v_int32x4(__lsx_vftint_w_d(a.val, a.val)); } - -inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) -{ return v_int32x4(__lsx_vftint_w_d(b.val, a.val)); } - -inline v_int32x4 v_trunc(const v_float32x4& a) -{ return v_int32x4(__lsx_vftintrz_w_s(a.val)); } - -inline v_int32x4 v_trunc(const v_float64x2& a) -{ return v_int32x4(__lsx_vftintrz_w_d(a.val, a.val)); } - -inline v_int32x4 v_floor(const v_float32x4& a) -{ return v_int32x4(__lsx_vftintrz_w_s(__m128(__lsx_vfrintrm_s(a.val)))); } - -inline v_int32x4 v_floor(const v_float64x2& a) -{ return v_trunc(v_float64x2(__lsx_vfrintrm_d(a.val))); } - -inline v_int32x4 v_ceil(const v_float32x4& a) -{ return v_int32x4(__lsx_vftintrz_w_s(__m128(__lsx_vfrintrp_s(a.val)))); } - -inline v_int32x4 v_ceil(const v_float64x2& a) -{ return v_trunc(v_float64x2(__lsx_vfrintrp_d(a.val))); } - -/** To float **/ -inline v_float32x4 v_cvt_f32(const v_int32x4& a) -{ return v_float32x4(__lsx_vffint_s_w(a.val)); } - -inline v_float32x4 v_cvt_f32(const v_float64x2& a) -{ return v_float32x4(__lsx_vfcvt_s_d(a.val, a.val)); } - -inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) -{ return v_float32x4(__lsx_vfcvt_s_d(b.val, a.val)); } - -inline v_float64x2 v_cvt_f64(const v_int32x4& a) -{ return v_float64x2(__lsx_vffintl_d_w(a.val)); } - -inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) -{ return v_float64x2(__lsx_vffinth_d_w(a.val)); } - -inline v_float64x2 v_cvt_f64(const v_float32x4& a) -{ return v_float64x2(__lsx_vfcvtl_d_s(a.val)); } - -inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) -{ return v_float64x2(__lsx_vfcvth_d_s(a.val)); } - -inline v_float64x2 v_cvt_f64(const v_int64x2& v) -{ return v_float64x2(__lsx_vffint_d_l(v.val)); } - - -//////////////// Lookup table access //////////////// -inline v_int8x16 v_lut(const schar* tab, const int* idx) -{ - return v_int8x16(_v128_setr_b(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], - tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]], tab[idx[8]], - tab[idx[9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], - tab[idx[14]], tab[idx[15]])); -} - -inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx) -{ - return v_int8x16(_v128_setr_h(*(const short*)(tab + idx[0]), *(const short*)(tab + idx[1]), - *(const short*)(tab + idx[2]), *(const short*)(tab + idx[3]), *(const short*)(tab + idx[4]), - *(const short*)(tab + idx[5]), *(const short*)(tab + idx[6]), *(const short*)(tab + idx[7]))); -} - -inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) -{ - return v_int8x16(_v128_setr_w(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), - *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]))); -} - -inline v_uint8x16 v_lut(const uchar* tab, const int* idx) -{ return v_reinterpret_as_u8(v_lut((const schar*)tab, idx)); } -inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) -{ return v_reinterpret_as_u8(v_lut_pairs((const schar*)tab, idx)); } -inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) -{ return v_reinterpret_as_u8(v_lut_quads((const schar*)tab, idx)); } - -inline v_int16x8 v_lut(const short* tab, const int* idx) -{ - return v_int16x8(_v128_setr_h(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], - tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]])); -} -inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) -{ - return v_int16x8(_v128_setr_w(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), - *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]))); -} -inline v_int16x8 v_lut_quads(const short* tab, const int* idx) -{ - return v_int16x8(_v128_setr_d(*(const int64_t*)(tab + idx[0]), *(const int64_t*)(tab + idx[1]))); -} - -inline v_uint16x8 v_lut(const ushort* tab, const int* idx) -{ return v_reinterpret_as_u16(v_lut((const short *)tab, idx)); } -inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) -{ return v_reinterpret_as_u16(v_lut_pairs((const short *)tab, idx)); } -inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) -{ return v_reinterpret_as_u16(v_lut_quads((const short *)tab, idx)); } - -inline v_int32x4 v_lut(const int* tab, const int* idx) -{ - return v_int32x4(_v128_setr_w(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]])); -} -inline v_int32x4 v_lut_pairs(const int *tab, const int* idx) -{ - return v_int32x4(_v128_setr_d(*(const int64_t*)(tab + idx[0]), *(const int64_t*)(tab + idx[1]))); -} -inline v_int32x4 v_lut_quads(const int* tab, const int* idx) -{ - return v_int32x4(__lsx_vld(tab + idx[0], 0)); -} - -inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((const int *)tab, idx)); } -inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((const int *)tab, idx)); } -inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((const int *)tab, idx)); } - -inline v_int64x2 v_lut(const int64_t* tab, const int *idx) -{ - return v_int64x2(_v128_setr_d(tab[idx[0]], tab[idx[1]])); -} -inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) -{ - return v_int64x2(__lsx_vld(tab + idx[0], 0)); -} - -inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } -inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } - -inline v_float32x4 v_lut(const float* tab, const int* idx) -{ - return v_float32x4(_v128_setr_ps(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]])); -} -inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) -{ - return v_float32x4((__m128)_v128_setr_pd(*(const double*)(tab + idx[0]), *(const double*)(tab + idx[1]))); -} -inline v_float32x4 v_lut_quads(const float* tab, const int* idx) -{ - return v_float32x4((__m128)__lsx_vld(tab + idx[0], 0)); -} - -inline v_float64x2 v_lut(const double* tab, const int* idx) -{ - return v_float64x2(_v128_setr_pd(tab[idx[0]], tab[idx[1]])); -} -inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) -{ - return v_float64x2((__m128d)__lsx_vld(tab + idx[0], 0)); -} - -inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) -{ - int *idx = (int*)&idxvec.val; - return v_lut(tab, idx); -} - -inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) -{ - return v_reinterpret_as_u32(v_lut((const int *)tab, idxvec)); -} - -inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) -{ - const int *idx = (const int*)&idxvec.val; - return v_lut(tab, idx); -} - -inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) -{ - const int *idx = (const int*)&idxvec.val; - return v_lut(tab, idx); -} - -inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) -{ - const int *idx = (const int*)&idxvec.val; - __m128i xy0 = __lsx_vld(tab + idx[0], 0); - __m128i xy1 = __lsx_vld(tab + idx[1], 0); - __m128i xy2 = __lsx_vld(tab + idx[2], 0); - __m128i xy3 = __lsx_vld(tab + idx[3], 0); - __m128i xy01 = __lsx_vilvl_d(xy1, xy0); - __m128i xy23 = __lsx_vilvl_d(xy3, xy2); - __m128i xxyy02 = __lsx_vilvl_w(xy23, xy01); - __m128i xxyy13 = __lsx_vilvh_w(xy23, xy01); - x = v_float32x4((__m128)__lsx_vilvl_w(xxyy13, xxyy02)); - y = v_float32x4((__m128)__lsx_vilvh_w(xxyy13, xxyy02)); -} - -inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) -{ - const int* idx = (const int*)&idxvec.val; - __m128i xy0 = __lsx_vld(tab + idx[0], 0); - __m128i xy1 = __lsx_vld(tab + idx[1], 0); - x = v_float64x2((__m128d)__lsx_vilvl_d(xy1, xy0)); - y = v_float64x2((__m128d)__lsx_vilvh_d(xy1, xy0)); -} - -inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) -{ - return v_int8x16(__lsx_vshuf_b(vec.val, vec.val, - _v128_setr_d(0x0705060403010200, 0x0f0d0e0c0b090a08))); -} -inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) -{ return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } -inline v_int8x16 v_interleave_quads(const v_int8x16& vec) -{ - return v_int8x16(__lsx_vshuf_b(vec.val, vec.val, - _v128_setr_d(0x0703060205010400, 0x0f0b0e0a0d090c08))); -} -inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) -{ return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) -{ - return v_int16x8(__lsx_vshuf_b(vec.val, vec.val, - _v128_setr_d(0x0706030205040100, 0x0f0e0b0a0d0c0908))); -} -inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) -{ return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } -inline v_int16x8 v_interleave_quads(const v_int16x8& vec) -{ - return v_int16x8(__lsx_vshuf_b(vec.val, vec.val, - _v128_setr_d(0x0b0a030209080100, 0x0f0e07060d0c0504))); -} -inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) -{ return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) -{ - return v_int32x4(__lsx_vshuf4i_w(vec.val, 0xd8)); -} -inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) -{ return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } - -inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) -{ return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } - -inline v_int8x16 v_pack_triplets(const v_int8x16& vec) -{ - __m128i zero = __lsx_vldi(0); - return v_int8x16(__lsx_vshuf_b(zero, vec.val, - _v128_set_d(0x1211100f0e0d0c0a, 0x0908060504020100))); -} -inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) -{ return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_pack_triplets(const v_int16x8& vec) -{ - __m128i zero = __lsx_vldi(0); - return v_int16x8(__lsx_vshuf_b(zero, vec.val, - _v128_set_d(0x11100f0e0d0c0b0a, 0x0908050403020100))); -} -inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) -{ return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } -inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } -inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } - -//////////// Matrix operations ///////// - -/////////// Dot Product ///////// - -// 16 >> 32 -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) -{ - __m128i x = a.val, y = b.val; - return v_int32x4(__lsx_vmaddwod_w_h(__lsx_vmulwev_w_h(x, y), x, y)); -} -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ - __m128i x = a.val, y = b.val, z = c.val; - __m128i t = __lsx_vmaddwev_w_h(z, x, y); - return v_int32x4(__lsx_vmaddwod_w_h(t, x, y)); -} - -// 32 >> 64 -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) -{ - __m128i x = a.val, y = b.val; - return v_int64x2(__lsx_vmaddwod_d_w(__lsx_vmulwev_d_w(x, y), x, y)); -} -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ - __m128i x = a.val, y = b.val, z = c.val; - __m128i t = __lsx_vmaddwev_d_w(z, x, y); - return v_int64x2(__lsx_vmaddwod_d_w(t, x, y)); -} - -// 8 >> 32 -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) -{ - __m128i x = a.val, y = b.val; - __m128i even = __lsx_vmulwev_h_bu(x, y); - __m128i odd = __lsx_vmulwod_h_bu(x, y); - __m128i prod0 = __lsx_vhaddw_wu_hu(even, even); - __m128i prod1 = __lsx_vhaddw_wu_hu(odd, odd); - return v_uint32x4(__lsx_vadd_w(prod0, prod1)); -} - -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) -{ return v_add(v_dotprod_expand(a, b), c) ;} - -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) -{ - __m128i x = a.val, y = b.val; - __m128i even = __lsx_vmulwev_h_b(x, y); - __m128i odd = __lsx_vmulwod_h_b(x, y); - __m128i prod0 = __lsx_vhaddw_w_h(even, even); - __m128i prod1 = __lsx_vhaddw_w_h(odd, odd); - return v_int32x4(__lsx_vadd_w(prod0, prod1)); -} -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) -{ - __m128i x = a.val, y = b.val; - __m128i even = __lsx_vmulwev_w_hu(x, y); - __m128i odd = __lsx_vmulwod_w_hu(x, y); - __m128i prod0 = __lsx_vhaddw_du_wu(even, even); - __m128i prod1 = __lsx_vhaddw_du_wu(odd, odd); - return v_uint64x2(__lsx_vadd_d(prod0, prod1)); -} -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) -{ - __m128i x = a.val, y = b.val; - __m128i even = __lsx_vmulwev_w_h(x, y); - __m128i odd = __lsx_vmulwod_w_h(x, y); - __m128i prod0 = __lsx_vhaddw_d_w(even, even); - __m128i prod1 = __lsx_vhaddw_d_w(odd, odd); - return v_int64x2(__lsx_vadd_d(prod0, prod1)); -} -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -//32 >> 64f -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) -{ return v_cvt_f64(v_dotprod(a, b)); } -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - - -///////// Fast Dot Product ////// - -// 16 >> 32 -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) -{ return v_dotprod(a, b); } -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ return v_dotprod(a, b, c); } - -// 32 >> 64 -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) -{ return v_dotprod(a, b); } -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ return v_dotprod(a, b, c); } - -// 8 >> 32 -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) -{ return v_dotprod_expand(a, b); } -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) -{ return v_dotprod_expand(a, b, c); } - -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) -{ return v_dotprod_expand(a, b); } -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) -{ return v_dotprod_expand(a, b, c); } - -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) -{ - __m128i x = a.val, y = b.val; - __m128i even = __lsx_vmulwev_w_hu(x, y); - __m128i odd = __lsx_vmulwod_w_hu(x, y); - __m128i prod0 = __lsx_vhaddw_du_wu(even, even); - __m128i prod1 = __lsx_vhaddw_du_wu(odd, odd); - return v_uint64x2(__lsx_vilvl_d(__lsx_vhaddw_qu_du(prod0, prod0), __lsx_vhaddw_qu_du(prod1, prod1))); -} -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) -{ - __m128i x = a.val, y = b.val; - __m128i prod = __lsx_vmaddwod_w_h(__lsx_vmulwev_w_h(x, y), x, y); - __m128i sign = __lsx_vsrai_w(prod, 31); - __m128i lo = __lsx_vilvl_w(sign, prod); - __m128i hi = __lsx_vilvh_w(sign, prod); - return v_int64x2(__lsx_vadd_d(lo, hi)); -} -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -// 32 >> 64f -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) -{ return v_dotprod_expand(a, b); } -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) -{ return v_dotprod_expand(a, b, c); } - -inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, const v_float32x4& m3) -{ - __m128i x = (__m128i)v.val; - __m128 v0 = __lsx_vfmul_s((__m128)__lsx_vshuf4i_w(x, 0x0), m0.val); - __m128 v1 = __lsx_vfmul_s((__m128)__lsx_vshuf4i_w(x, 0x55), m1.val); - __m128 v2 = __lsx_vfmul_s((__m128)__lsx_vshuf4i_w(x, 0xAA), m2.val); - __m128 v3 = __lsx_vfmul_s((__m128)__lsx_vshuf4i_w(x, 0xFF), m3.val); - - return v_float32x4(__lsx_vfadd_s(__lsx_vfadd_s(v0, v1), __lsx_vfadd_s(v2, v3))); -} - -inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, const v_float32x4& a) -{ - __m128i x = (__m128i)v.val; - __m128 v0 = __lsx_vfmul_s((__m128)__lsx_vshuf4i_w(x, 0x0), m0.val); - __m128 v1 = __lsx_vfmul_s((__m128)__lsx_vshuf4i_w(x, 0x55), m1.val); - __m128 v2 = __lsx_vfmadd_s((__m128)__lsx_vshuf4i_w(x, 0xAA), m2.val, a.val); - - return v_float32x4(__lsx_vfadd_s(__lsx_vfadd_s(v0, v1), v2)); -} - -#define OPENCV_HAL_IMPL_LSX_TRANSPOSE4X4(_Tpvec, cast_from, cast_to) \ - inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ - const _Tpvec& a2, const _Tpvec& a3, \ - _Tpvec& b0, _Tpvec& b1, _Tpvec& b2, _Tpvec& b3) \ - { \ - __m128i t0 = cast_from(__lsx_vilvl_w(a1.val, a0.val)); \ - __m128i t1 = cast_from(__lsx_vilvl_w(a3.val, a2.val)); \ - __m128i t2 = cast_from(__lsx_vilvh_w(a1.val, a0.val)); \ - __m128i t3 = cast_from(__lsx_vilvh_w(a3.val, a2.val)); \ - b0.val = cast_to(__lsx_vilvl_d(t1, t0)); \ - b1.val = cast_to(__lsx_vilvh_d(t1, t0)); \ - b2.val = cast_to(__lsx_vilvl_d(t3, t2)); \ - b3.val = cast_to(__lsx_vilvh_d(t3, t2)); \ - } - -OPENCV_HAL_IMPL_LSX_TRANSPOSE4X4(v_uint32x4, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_LSX_TRANSPOSE4X4(v_int32x4, OPENCV_HAL_NOP, OPENCV_HAL_NOP) - -inline void v_transpose4x4(const v_float32x4& a0, const v_float32x4& a1, - const v_float32x4& a2, const v_float32x4& a3, - v_float32x4& b0, v_float32x4& b1, v_float32x4& b2, v_float32x4& b3) -{ - __m128i vec0 = (__m128i)a0.val, vec1 = (__m128i)a1.val; - __m128i vec2 = (__m128i)a2.val, vec3 = (__m128i)a3.val; - __m128i t0 = __lsx_vilvl_w(vec1, vec0); - __m128i t1 = __lsx_vilvl_w(vec3, vec2); - __m128i t2 = __lsx_vilvh_w(vec1, vec0); - __m128i t3 = __lsx_vilvh_w(vec3, vec2); - b0.val = __m128(__lsx_vilvl_d(t1, t0)); - b1.val = __m128(__lsx_vilvh_d(t1, t0)); - b2.val = __m128(__lsx_vilvl_d(t3, t2)); - b3.val = __m128(__lsx_vilvh_d(t3, t2)); -} - -////////////////// Value reordering //////////////// - -/* Expand */ -#define OPENCV_HAL_IMPL_LSX_EXPAND(_Tpvec, _Tpwvec, _Tp, intrin_lo, intrin_hi) \ - inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ - { \ - b0.val = intrin_lo(a.val, 0); \ - b1.val = intrin_hi(a.val); \ - } \ - inline _Tpwvec v_expand_low(const _Tpvec& a) \ - { return _Tpwvec(intrin_lo(a.val, 0)); } \ - inline _Tpwvec v_expand_high(const _Tpvec& a) \ - { return _Tpwvec(intrin_hi(a.val)); } \ - inline _Tpwvec v_load_expand(const _Tp* ptr) \ - { \ - __m128i a = __lsx_vld(ptr, 0); \ - return _Tpwvec(intrin_lo(a, 0)); \ - } - -OPENCV_HAL_IMPL_LSX_EXPAND(v_uint8x16, v_uint16x8, uchar, __lsx_vsllwil_hu_bu, __lsx_vexth_hu_bu) -OPENCV_HAL_IMPL_LSX_EXPAND(v_int8x16, v_int16x8, schar, __lsx_vsllwil_h_b, __lsx_vexth_h_b) -OPENCV_HAL_IMPL_LSX_EXPAND(v_uint16x8, v_uint32x4, ushort, __lsx_vsllwil_wu_hu, __lsx_vexth_wu_hu) -OPENCV_HAL_IMPL_LSX_EXPAND(v_int16x8, v_int32x4, short, __lsx_vsllwil_w_h, __lsx_vexth_w_h) -OPENCV_HAL_IMPL_LSX_EXPAND(v_uint32x4, v_uint64x2, unsigned, __lsx_vsllwil_du_wu, __lsx_vexth_du_wu) -OPENCV_HAL_IMPL_LSX_EXPAND(v_int32x4, v_int64x2, int, __lsx_vsllwil_d_w, __lsx_vexth_d_w) - -#define OPENCV_HAL_IMPL_LSX_EXPAND_Q(_Tpvec, _Tp, intrin_lo, intrin_hi) \ - inline _Tpvec v_load_expand_q(const _Tp* ptr) \ - { \ - __m128i a = __lsx_vld(ptr, 0); \ - __m128i b = intrin_lo(a, 0); \ - return _Tpvec(intrin_hi(b, 0)); \ - } - -OPENCV_HAL_IMPL_LSX_EXPAND_Q(v_uint32x4, uchar, __lsx_vsllwil_hu_bu, __lsx_vsllwil_wu_hu) -OPENCV_HAL_IMPL_LSX_EXPAND_Q(v_int32x4, schar, __lsx_vsllwil_h_b, __lsx_vsllwil_w_h) - -/* pack */ -// 16 -inline v_int8x16 v_pack(const v_int16x8& a, const v_int16x8& b) -{ return v_int8x16(_lsx_packs_h(a.val, b.val)); } - -inline v_uint8x16 v_pack(const v_uint16x8& a, const v_uint16x8& b) -{ return v_uint8x16(__lsx_vssrlrni_bu_h(b.val, a.val, 0)); } - -inline v_uint8x16 v_pack_u(const v_int16x8& a, const v_int16x8& b) -{ return v_uint8x16(_lsx_packus_h(a.val, b.val)); } - -inline void v_pack_store(schar* ptr, const v_int16x8& a) -{ v_store_low(ptr, v_pack(a, a)); } - -inline void v_pack_store(uchar* ptr, const v_uint16x8& a) -{ v_store_low(ptr, v_pack(a, a)); } - -inline void v_pack_u_store(uchar* ptr, const v_int16x8& a) -{ v_store_low(ptr, v_pack_u(a, a)); } - -template inline -v_uint8x16 v_rshr_pack(const v_uint16x8& a, const v_uint16x8& b) -{ return v_uint8x16(__lsx_vssrlrni_bu_h(b.val, a.val, n)); } - -template inline -void v_rshr_pack_store(uchar* ptr, const v_uint16x8& a) -{ __lsx_vstelm_d(__lsx_vssrlrni_bu_h(a.val, a.val, n), ptr, 0, 0); } - -template inline -v_uint8x16 v_rshr_pack_u(const v_int16x8& a, const v_int16x8& b) -{ return v_uint8x16(__lsx_vssrarni_bu_h(b.val, a.val, n)); } - -template inline -void v_rshr_pack_u_store(uchar* ptr, const v_int16x8& a) -{ __lsx_vstelm_d(__lsx_vssrarni_bu_h(a.val, a.val, n), ptr, 0, 0); } - -template inline -v_int8x16 v_rshr_pack(const v_int16x8& a, const v_int16x8& b) -{ return v_int8x16(__lsx_vssrarni_b_h(b.val, a.val, n)); } - -template inline -void v_rshr_pack_store(schar* ptr, const v_int16x8& a) -{ __lsx_vstelm_d(__lsx_vssrarni_b_h(a.val, a.val, n), ptr, 0, 0); } - -//32 -inline v_int16x8 v_pack(const v_int32x4& a, const v_int32x4& b) -{ return v_int16x8(__lsx_vssrarni_h_w(b.val, a.val, 0)); } - -inline v_uint16x8 v_pack(const v_uint32x4& a, const v_uint32x4& b) -{ return v_uint16x8(__lsx_vssrlrni_hu_w(b.val, a.val, 0)); } - -inline v_uint16x8 v_pack_u(const v_int32x4& a, const v_int32x4& b) -{ return v_uint16x8(__lsx_vssrarni_hu_w(b.val, a.val, 0)); } - -inline void v_pack_store(short* ptr, const v_int32x4& a) -{ v_store_low(ptr, v_pack(a, a)); } - -inline void v_pack_store(ushort *ptr, const v_uint32x4& a) -{ __lsx_vstelm_d(__lsx_vssrlrni_hu_w(a.val, a.val, 0), ptr, 0, 0); } - -inline void v_pack_u_store(ushort* ptr, const v_int32x4& a) -{ __lsx_vstelm_d(__lsx_vssrarni_hu_w(a.val, a.val, 0), ptr, 0, 0); } - -template inline -v_uint16x8 v_rshr_pack(const v_uint32x4& a, const v_uint32x4& b) -{ return v_uint16x8(__lsx_vssrlrni_hu_w(b.val, a.val, n)); } - -template inline -void v_rshr_pack_store(ushort* ptr, const v_uint32x4& a) -{ __lsx_vstelm_d(__lsx_vssrlrni_hu_w(a.val, a.val, n), ptr, 0, 0); } - -template inline -v_uint16x8 v_rshr_pack_u(const v_int32x4& a, const v_int32x4& b) -{ return v_uint16x8(__lsx_vssrarni_hu_w(b.val, a.val, n)); } - -template inline -void v_rshr_pack_u_store(ushort* ptr, const v_int32x4& a) -{ __lsx_vstelm_d(__lsx_vssrarni_hu_w(a.val, a.val, n), ptr, 0, 0); } - -template inline -v_int16x8 v_rshr_pack(const v_int32x4& a, const v_int32x4& b) -{ return v_int16x8(__lsx_vssrarni_h_w(b.val, a.val, n)); } - -template inline -void v_rshr_pack_store(short* ptr, const v_int32x4& a) -{ __lsx_vstelm_d(__lsx_vssrarni_h_w(a.val, a.val, n), ptr, 0, 0); } - -// 64 -// Non-saturaing pack -inline v_uint32x4 v_pack(const v_uint64x2& a, const v_uint64x2& b) -{ return v_uint32x4(__lsx_vpickev_w(b.val, a.val)); } - -inline v_int32x4 v_pack(const v_int64x2& a, const v_int64x2& b) -{ return v_reinterpret_as_s32(v_pack(v_reinterpret_as_u64(a), v_reinterpret_as_u64(b))); } - -inline void v_pack_store(unsigned* ptr, const v_uint64x2& a) -{ __lsx_vstelm_d(__lsx_vshuf4i_w(a.val, 0x08), ptr, 0, 0); } - -inline void v_pack_store(int *ptr, const v_int64x2& a) -{ v_pack_store((unsigned*)ptr, v_reinterpret_as_u64(a)); } - -template inline -v_uint32x4 v_rshr_pack(const v_uint64x2& a, const v_uint64x2& b) -{ return v_uint32x4(__lsx_vsrlrni_w_d(b.val, a.val, n)); } - -template inline -void v_rshr_pack_store(unsigned* ptr, const v_uint64x2& a) -{ __lsx_vstelm_d(__lsx_vsrlrni_w_d(a.val, a.val, n), ptr, 0, 0); } - -template inline -v_int32x4 v_rshr_pack(const v_int64x2& a, const v_int64x2& b) -{ return v_int32x4(__lsx_vsrarni_w_d(b.val, a.val, n)); } - -template inline -void v_rshr_pack_store(int* ptr, const v_int64x2& a) -{ __lsx_vstelm_d(__lsx_vsrarni_w_d(a.val, a.val, n), ptr, 0, 0); } - -// pack boolean -inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) -{ return v_uint8x16(__lsx_vssrarni_b_h(b.val, a.val, 0)); } - -inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, - const v_uint32x4& c, const v_uint32x4& d) -{ - __m128i ab = __lsx_vssrarni_h_w(b.val, a.val, 0); - __m128i cd = __lsx_vssrarni_h_w(d.val, c.val, 0); - return v_uint8x16(__lsx_vssrarni_b_h(cd, ab, 0)); -} - -inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, - const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, - const v_uint64x2& g, const v_uint64x2& h) -{ - __m128i ab = __lsx_vssrarni_w_d(b.val, a.val, 0); - __m128i cd = __lsx_vssrarni_w_d(d.val, c.val, 0); - __m128i ef = __lsx_vssrarni_w_d(f.val, e.val, 0); - __m128i gh = __lsx_vssrarni_w_d(h.val, g.val, 0); - - __m128i abcd = __lsx_vssrarni_h_w(cd, ab, 0); - __m128i efgh = __lsx_vssrarni_h_w(gh, ef, 0); - return v_uint8x16(__lsx_vssrarni_b_h(efgh, abcd, 0)); -} - -/* Recombine */ -// its up there with load and store operations - -/* Extract */ -#define OPENCV_HAL_IMPL_LSX_EXTRACT(_Tpvec) \ - template \ - inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \ - { return v_rotate_right(a, b); } - -OPENCV_HAL_IMPL_LSX_EXTRACT(v_uint8x16) -OPENCV_HAL_IMPL_LSX_EXTRACT(v_int8x16) -OPENCV_HAL_IMPL_LSX_EXTRACT(v_uint16x8) -OPENCV_HAL_IMPL_LSX_EXTRACT(v_int16x8) -OPENCV_HAL_IMPL_LSX_EXTRACT(v_uint32x4) -OPENCV_HAL_IMPL_LSX_EXTRACT(v_int32x4) -OPENCV_HAL_IMPL_LSX_EXTRACT(v_uint64x2) -OPENCV_HAL_IMPL_LSX_EXTRACT(v_int64x2) -OPENCV_HAL_IMPL_LSX_EXTRACT(v_float32x4) -OPENCV_HAL_IMPL_LSX_EXTRACT(v_float64x2) - -#define OPENCV_HAL_IMPL_LSX_EXTRACT_N(_Tpvec, _Twvec, intrin) \ -template \ -inline _Twvec v_extract_n(const _Tpvec& a) \ -{ return (_Twvec)intrin(a.val, i); } - -OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_uint8x16, uchar, __lsx_vpickve2gr_b) -OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_int8x16, schar, __lsx_vpickve2gr_b) -OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_uint16x8, ushort, __lsx_vpickve2gr_h) -OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_int16x8, short, __lsx_vpickve2gr_h) -OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_uint32x4, uint, __lsx_vpickve2gr_w) -OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_int32x4, int, __lsx_vpickve2gr_w) -OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_uint64x2, uint64, __lsx_vpickve2gr_d) -OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_int64x2, int64, __lsx_vpickve2gr_d) - -template -inline float v_extract_n(const v_float32x4& v) -{ - union { uint iv; float fv; } d; - d.iv = __lsx_vpickve2gr_w(v.val, i); - return d.fv; -} - -template -inline double v_extract_n(const v_float64x2& v) -{ - union { uint64 iv; double dv; } d; - d.iv = __lsx_vpickve2gr_d(v.val, i); - return d.dv; -} - -template -inline v_uint32x4 v_broadcast_element(const v_uint32x4& a) -{ return v_uint32x4(__lsx_vreplvei_w(a.val, i)); } - -template -inline v_int32x4 v_broadcast_element(const v_int32x4& a) -{ return v_int32x4(__lsx_vreplvei_w(a.val, i)); } - -template -inline v_float32x4 v_broadcast_element(const v_float32x4& a) -{ return v_float32x4((__m128)__lsx_vreplvei_w((__m128i)a.val, i)); } - -/////////////////// load deinterleave ////////////////////////////// - -inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b) -{ - __m128i t0 = __lsx_vld(ptr, 0); - __m128i t1 = __lsx_vld(ptr, 16); - - a.val = __lsx_vpickev_b(t1, t0); - b.val = __lsx_vpickod_b(t1, t0); -} - -inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b) -{ - __m128i t0 = __lsx_vld(ptr, 0); - __m128i t1 = __lsx_vld(ptr, 16); - a.val = __lsx_vpickev_h(t1, t0); - b.val = __lsx_vpickod_h(t1, t0); -} - -inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b) -{ - __m128i t0 = __lsx_vld(ptr, 0); - __m128i t1 = __lsx_vld(ptr, 16); - a.val = __lsx_vpickev_w(t1, t0); - b.val = __lsx_vpickod_w(t1, t0); -} - -inline void v_load_deinterleave(const uint64* ptr, v_uint64x2& a, v_uint64x2& b) -{ - __m128i t0 = __lsx_vld(ptr, 0); - __m128i t1 = __lsx_vld(ptr, 16); - a.val = __lsx_vilvl_d(t1, t0); - b.val = __lsx_vilvh_d(t1, t0); -} - -inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c) -{ - __m128i t0 = __lsx_vld(ptr, 0); - __m128i t1 = __lsx_vld(ptr, 16); - __m128i t2 = __lsx_vld(ptr, 32); - const __m128i shuff0 = _v128_setr_b(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0); - const __m128i shuff1 = _v128_setr_b(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); - __m128i a0 = __lsx_vbitsel_v(t0, t1, shuff0); - __m128i b0 = __lsx_vbitsel_v(t1, t0, shuff1); - __m128i c0 = __lsx_vbitsel_v(t1, t0, shuff0); - const __m128i shuff_a = _v128_setr_b(0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 17, 20, 23, 26, 29); - const __m128i shuff_b = _v128_setr_b(1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30); - const __m128i shuff_c = _v128_setr_b(2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31); - - a.val = __lsx_vshuf_b(t2, a0, shuff_a); - b.val = __lsx_vshuf_b(t2, b0, shuff_b); - c.val = __lsx_vshuf_b(t2, c0, shuff_c); -} - -inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c) -{ - __m128i t0 = __lsx_vld(ptr, 0); - __m128i t1 = __lsx_vld(ptr, 16); - __m128i t2 = __lsx_vld(ptr, 32); - const __m128i shuff0 = _v128_setr_h(0, 0, -1, 0, 0, -1, 0, 0); - const __m128i shuff1 = _v128_setr_h(0, -1, 0, 0, -1, 0, 0, -1); - - __m128i a0 = __lsx_vbitsel_v(t0, t1, shuff1); - __m128i b0 = __lsx_vbitsel_v(t0, t1, shuff0); - __m128i c0 = __lsx_vbitsel_v(t1, t0, shuff0); - - const __m128i shuff_a = _v128_setr_b(0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 20, 21, 26, 27); - const __m128i shuff_b = _v128_setr_b(2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 16, 17, 22, 23, 28, 29); - const __m128i shuff_c = _v128_setr_b(4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 18, 19, 24, 25, 30, 31); - - a.val = __lsx_vshuf_b(t2, a0, shuff_a); - b.val = __lsx_vshuf_b(t2, b0, shuff_b); - c.val = __lsx_vshuf_b(t2, c0, shuff_c); -} - -inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c) -{ - __m128i t0 = __lsx_vld(ptr, 0); - __m128i t1 = __lsx_vld(ptr, 16); - __m128i t2 = __lsx_vld(ptr, 32); - - __m128i a0 = __lsx_vpermi_w(t1, t0, 0xAC); - __m128i b0 = __lsx_vpermi_w(t1, t0, 0xC5); - __m128i c0 = __lsx_vpermi_w(t1, t0, 0x5A); - - a.val = __lsx_vextrins_w(a0, t2, 0x31); - b0 = __lsx_vshuf4i_w(b0, 0x38); - c0 = __lsx_vshuf4i_w(c0, 0x8); - b.val = __lsx_vextrins_w(b0, t2, 0x32); - c.val = __lsx_vpermi_w(t2, c0, 0xC4); -} - -inline void v_load_deinterleave(const uint64* ptr, v_uint64x2& a, v_uint64x2& b, v_uint64x2& c) -{ - __m128i t0 = __lsx_vld(ptr, 0); - __m128i t1 = __lsx_vld(ptr, 16); - __m128i t2 = __lsx_vld(ptr, 32); - - a.val = __lsx_vshuf4i_d(t0, t1, 0xC); - b.val = __lsx_vshuf4i_d(t0, t2, 0x9); - c.val = __lsx_vshuf4i_d(t1, t2, 0xC); -} - -inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c, v_uint8x16& d) -{ - __m128i t0 = __lsx_vld(ptr, 0); - __m128i t1 = __lsx_vld(ptr, 16); - __m128i t2 = __lsx_vld(ptr, 32); - __m128i t3 = __lsx_vld(ptr, 48); - - __m128i ac_lo = __lsx_vpickev_b(t1, t0); - __m128i bd_lo = __lsx_vpickod_b(t1, t0); - __m128i ac_hi = __lsx_vpickev_b(t3, t2); - __m128i bd_hi = __lsx_vpickod_b(t3, t2); - - a.val = __lsx_vpickev_b(ac_hi, ac_lo); - c.val = __lsx_vpickod_b(ac_hi, ac_lo); - b.val = __lsx_vpickev_b(bd_hi, bd_lo); - d.val = __lsx_vpickod_b(bd_hi, bd_lo); -} - -inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c, v_uint16x8& d) -{ - __m128i t0 = __lsx_vld(ptr, 0); - __m128i t1 = __lsx_vld(ptr, 16); - __m128i t2 = __lsx_vld(ptr, 32); - __m128i t3 = __lsx_vld(ptr, 48); - - __m128i ac_lo = __lsx_vpickev_h(t1, t0); - __m128i bd_lo = __lsx_vpickod_h(t1, t0); - __m128i ac_hi = __lsx_vpickev_h(t3, t2); - __m128i bd_hi = __lsx_vpickod_h(t3, t2); - - a.val = __lsx_vpickev_h(ac_hi, ac_lo); - c.val = __lsx_vpickod_h(ac_hi, ac_lo); - b.val = __lsx_vpickev_h(bd_hi, bd_lo); - d.val = __lsx_vpickod_h(bd_hi, bd_lo); -} - -inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c, v_uint32x4& d) -{ - __m128i p0 = __lsx_vld(ptr, 0); - __m128i p1 = __lsx_vld(ptr, 16); - __m128i p2 = __lsx_vld(ptr, 32); - __m128i p3 = __lsx_vld(ptr, 48); - - __m128i t0 = __lsx_vilvl_w(p1, p0); - __m128i t1 = __lsx_vilvl_w(p3, p2); - __m128i t2 = __lsx_vilvh_w(p1, p0); - __m128i t3 = __lsx_vilvh_w(p3, p2); - a.val = __lsx_vilvl_d(t1, t0); - b.val = __lsx_vilvh_d(t1, t0); - c.val = __lsx_vilvl_d(t3, t2); - d.val = __lsx_vilvh_d(t3, t2); -} - -inline void v_load_deinterleave(const uint64* ptr, v_uint64x2& a, v_uint64x2& b, v_uint64x2& c, v_uint64x2& d) -{ - __m128i t0 = __lsx_vld(ptr, 0); - __m128i t1 = __lsx_vld(ptr, 16); - __m128i t2 = __lsx_vld(ptr, 32); - __m128i t3 = __lsx_vld(ptr, 48); - - a.val = __lsx_vilvl_d(t2, t0); - b.val = __lsx_vilvh_d(t2, t0); - c.val = __lsx_vilvl_d(t3, t1); - d.val = __lsx_vilvh_d(t3, t1); -} - -////////////////////////// store interleave //////////////////////////////// - -inline void v_store_interleave(uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - __m128i v0 = __lsx_vilvl_b(b.val, a.val); - __m128i v1 = __lsx_vilvh_b(b.val, a.val); - - __lsx_vst(v0, ptr, 0); - __lsx_vst(v1, ptr, 16); -} - -inline void v_store_interleave(ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - __m128i v0 = __lsx_vilvl_h(b.val, a.val); - __m128i v1 = __lsx_vilvh_h(b.val, a.val); - - __lsx_vst(v0, ptr, 0); - __lsx_vst(v1, ptr, 16); -} - -inline void v_store_interleave(unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - __m128i v0 = __lsx_vilvl_w(b.val, a.val); - __m128i v1 = __lsx_vilvh_w(b.val, a.val); - - __lsx_vst(v0, ptr, 0); - __lsx_vst(v1, ptr, 16); -} - -inline void v_store_interleave(uint64* ptr, const v_uint64x2& a, const v_uint64x2& b, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - __m128i v0 = __lsx_vilvl_d(b.val, a.val); - __m128i v1 = __lsx_vilvh_d(b.val, a.val); - - __lsx_vst(v0, ptr, 0); - __lsx_vst(v1, ptr, 16); -} - -inline void v_store_interleave(uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, const v_uint8x16& c, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - __m128i ab_lo = __lsx_vilvl_b(b.val, a.val); - __m128i ab_hi = __lsx_vilvh_b(b.val, a.val); - __m128i v_c = c.val; - const __m128i shuff0 = _v128_setr_b(0, 1, 16, 2, 3, 17, 4, 5, 18, 6, 7, 19, 8, 9, 20, 10); - const __m128i shuff1 = _v128_setr_b(11, 21, 12, 13, 22, 14, 15, 23, 0, 0, 0, 0, 0, 0, 0, 0); - const __m128i shuff2 = _v128_setr_b(0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 24, 18, 19, 25, 20, 21); - const __m128i shuff3 = _v128_setr_b(26, 6, 7, 27, 8, 9, 28, 10, 11, 29, 12, 13, 30, 14, 15, 31); - __m128i abc = __lsx_vpermi_w(v_c, ab_hi, 0xE4); - - __m128i dst0 = __lsx_vshuf_b(v_c, ab_lo, shuff0); - __m128i dst1 = __lsx_vshuf_b(v_c, ab_lo, shuff1); - __m128i dst2 = __lsx_vshuf_b(v_c, ab_hi, shuff3); - dst1 = __lsx_vshuf_b(abc, dst1, shuff2); - - __lsx_vst(dst0, ptr, 0); - __lsx_vst(dst1, ptr, 16); - __lsx_vst(dst2, ptr, 32); -} - -inline void v_store_interleave(ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, const v_uint16x8& c, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - __m128i ab_lo = __lsx_vilvl_h(b.val, a.val); - __m128i ab_hi = __lsx_vilvh_h(b.val, a.val); - __m128i v_c = c.val; - const __m128i shuff0 = _v128_setr_b(0, 1, 2, 3, 16, 17, 4, 5, 6, 7, 18, 19, 8, 9, 10, 11); - const __m128i shuff1 = _v128_setr_b(20, 21, 12, 13, 14, 15, 22, 23, 0, 0, 0, 0, 0, 0, 0, 0); - const __m128i shuff2 = _v128_setr_b(0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 24, 25, 20, 21); - const __m128i shuff3 = _v128_setr_b(6, 7, 26, 27, 8, 9, 10, 11, 28, 29, 12, 13, 14, 15, 30, 31); - __m128i abc = __lsx_vpermi_w(v_c, ab_hi, 0xE4); - - __m128i dst0 = __lsx_vshuf_b(v_c, ab_lo, shuff0); - __m128i dst1 = __lsx_vshuf_b(v_c, ab_lo, shuff1); - __m128i dst2 = __lsx_vshuf_b(v_c, ab_hi, shuff3); - dst1 = __lsx_vshuf_b(abc, dst1, shuff2); - - __lsx_vst(dst0, ptr, 0); - __lsx_vst(dst1, ptr, 16); - __lsx_vst(dst2, ptr, 32); -} - -inline void v_store_interleave(unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, const v_uint32x4& c, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - __m128i v_c = c.val; - __m128i ab_lo = __lsx_vilvl_w(b.val, a.val); //a0 b0 a1 b1 - __m128i ab_hi = __lsx_vilvh_w(b.val, a.val); //a2 b2 a3 b3 - __m128i bc_od = __lsx_vpackod_w(v_c, b.val); // b1 c1 b3 c3 - - __m128i dst0 = __lsx_vshuf4i_w(ab_lo, 0xB4); //a0 b0 b1 a1 - __m128i dst1 = __lsx_vilvl_d(ab_hi, bc_od); //b1 c1 a2 b2 - __m128i dst2 = __lsx_vpermi_w(bc_od, ab_hi, 0xE8); //a2, a3, b3, c3 - - dst0 = __lsx_vextrins_w(dst0, v_c, 0x20); - dst2 = __lsx_vextrins_w(dst2, v_c, 0x2); - __lsx_vst(dst0, ptr, 0); //a0 b0 c0 a1 - __lsx_vst(dst1, ptr, 16); //b1 c1 a2 b2 - __lsx_vst(dst2, ptr, 32); //c2 a3 b3 c3 -} - -inline void v_store_interleave(uint64* ptr, const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - __m128i dst0 = __lsx_vilvl_d(b.val, a.val); - __m128i dst1 = __lsx_vpermi_w(a.val, c.val, 0xE4); - __m128i dst2 = __lsx_vilvh_d(c.val, b.val); - - __lsx_vst(dst0, ptr, 0); - __lsx_vst(dst1, ptr, 16); - __lsx_vst(dst2, ptr, 32); -} - -inline void v_store_interleave(uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, - const v_uint8x16& c, const v_uint8x16& d, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - __m128i ab_lo = __lsx_vilvl_b(b.val, a.val); - __m128i ab_hi = __lsx_vilvh_b(b.val, a.val); - __m128i cd_lo = __lsx_vilvl_b(d.val, c.val); - __m128i cd_hi = __lsx_vilvh_b(d.val, c.val); - - __m128i dst0 = __lsx_vilvl_h(cd_lo, ab_lo); - __m128i dst1 = __lsx_vilvh_h(cd_lo, ab_lo); - __m128i dst2 = __lsx_vilvl_h(cd_hi, ab_hi); - __m128i dst3 = __lsx_vilvh_h(cd_hi, ab_hi); - - __lsx_vst(dst0, ptr, 0); - __lsx_vst(dst1, ptr, 16); - __lsx_vst(dst2, ptr, 32); - __lsx_vst(dst3, ptr, 48); -} - -inline void v_store_interleave(ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, - const v_uint16x8& c, const v_uint16x8& d, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - __m128i ab_lo = __lsx_vilvl_h(b.val, a.val); - __m128i ab_hi = __lsx_vilvh_h(b.val, a.val); - __m128i cd_lo = __lsx_vilvl_h(d.val, c.val); - __m128i cd_hi = __lsx_vilvh_h(d.val, c.val); - - __m128i dst0 = __lsx_vilvl_w(cd_lo, ab_lo); - __m128i dst1 = __lsx_vilvh_w(cd_lo, ab_lo); - __m128i dst2 = __lsx_vilvl_w(cd_hi, ab_hi); - __m128i dst3 = __lsx_vilvh_w(cd_hi, ab_hi); - - __lsx_vst(dst0, ptr, 0); - __lsx_vst(dst1, ptr, 16); - __lsx_vst(dst2, ptr, 32); - __lsx_vst(dst3, ptr, 48); -} - -inline void v_store_interleave(unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, - const v_uint32x4& c, const v_uint32x4& d, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - __m128i ab_lo = __lsx_vilvl_w(b.val, a.val); - __m128i ab_hi = __lsx_vilvh_w(b.val, a.val); - __m128i cd_lo = __lsx_vilvl_w(d.val, c.val); - __m128i cd_hi = __lsx_vilvh_w(d.val, c.val); - - __m128i dst0 = __lsx_vilvl_d(cd_lo, ab_lo); - __m128i dst1 = __lsx_vilvh_d(cd_lo, ab_lo); - __m128i dst2 = __lsx_vilvl_d(cd_hi, ab_hi); - __m128i dst3 = __lsx_vilvh_d(cd_hi, ab_hi); - - __lsx_vst(dst0, ptr, 0); - __lsx_vst(dst1, ptr, 16); - __lsx_vst(dst2, ptr, 32); - __lsx_vst(dst3, ptr, 48); -} - -inline void v_store_interleave(uint64* ptr, const v_uint64x2& a, const v_uint64x2& b, - const v_uint64x2& c, const v_uint64x2& d, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - __m128i dst0 = __lsx_vilvl_d(b.val, a.val); - __m128i dst2 = __lsx_vilvh_d(b.val, a.val); - __m128i dst1 = __lsx_vilvl_d(d.val, c.val); - __m128i dst3 = __lsx_vilvh_d(d.val, c.val); - - __lsx_vst(dst0, ptr, 0); - __lsx_vst(dst1, ptr, 16); - __lsx_vst(dst2, ptr, 32); - __lsx_vst(dst3, ptr, 48); -} - -#define OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(_Tpvec0, _Tp0, suffix0, _Tpvec1, _Tp1, suffix1) \ -inline void v_load_deinterleave(const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0) \ -{ \ - _Tpvec1 a1, b1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ -} \ -inline void v_load_deinterleave(const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0) \ -{ \ - _Tpvec1 a1, b1, c1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ - c0 = v_reinterpret_as_##suffix0(c1); \ -} \ -inline void v_load_deinterleave(const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, \ - _Tpvec0& c0, _Tpvec0& d0) \ -{ \ - _Tpvec1 a1, b1, c1, d1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1, d1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ - c0 = v_reinterpret_as_##suffix0(c1); \ - d0 = v_reinterpret_as_##suffix0(d1); \ -} \ -inline void v_store_interleave(_Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - v_store_interleave((_Tp1*)ptr, a1, b1); \ -} \ -inline void v_store_interleave(_Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, const _Tpvec0& c0,\ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, c1); \ -} \ -inline void v_store_interleave(_Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - const _Tpvec0& c0, const _Tpvec0& d0, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ - _Tpvec1 d1 = v_reinterpret_as_##suffix1(d0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, c1, d1); \ -} - -OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(v_int8x16, schar, s8, v_uint8x16, uchar, u8) -OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(v_int16x8, short, s16, v_uint16x8, ushort, u16) -OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(v_int32x4, int, s32, v_uint32x4, unsigned, u32) -OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(v_float32x4, float, f32, v_uint32x4, unsigned, u32) -OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(v_int64x2, int64, s64, v_uint64x2, uint64, u64) -OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(v_float64x2, double, f64, v_uint64x2, uint64, u64) - -// -// FP16 -// - -inline v_float32x4 v_load_expand(const hfloat* ptr) -{ -#if CV_FP16 - return v_float32x4(__lsx_vfcvtl_s_h((__m128)__lsx_vld(ptr, 0))); -#else - float CV_DECL_ALIGNED(32) buf[4]; - for (int i = 0; i < 4; i++) - buf[i] = (float)ptr[i]; - return v_float32x4((__m128)__lsx_vld(buf, 0)); -#endif -} - -inline void v_pack_store(hfloat* ptr, const v_float32x4& a) -{ -#if CV_FP16 - __m128i res = (__m218i)__lsx_vfcvt_h_s(a.val, a.val); - __lsx_vstelm_d(res, ptr, 0, 0); -#else - float CV_DECL_ALIGNED(32) buf[4]; - v_store_aligned(buf, a); - for (int i = 0; i < 4; i++) - ptr[i] = hfloat(buf[i]); -#endif -} - -// -// end of FP16 -// - -inline void v_cleanup() {} - -#include "intrin_math.hpp" -inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } -inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } -inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } -inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } -inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } -inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } - -inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } -inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } -inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } -inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } -inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} // cv:: - -#endif // OPENCV_HAL_INTRIN_LSX_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +#ifndef OPENCV_HAL_INTRIN_LSX_HPP +#define OPENCV_HAL_INTRIN_LSX_HPP + +#include + +#define CV_SIMD128 1 +#define CV_SIMD128_64F 1 +#define CV_SIMD128_FP16 0 + +namespace cv +{ + +//! @cond IGNORED + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +/////////// Utils //////// + +inline __m128i _v128_setr_b(char v0, char v1, char v2, char v3, char v4, char v5, char v6, + char v7, char v8, char v9, char v10, char v11, char v12, char v13, char v14, char v15) +{ + return (__m128i)v16i8{ v0, v1, v2, v3, v4, v5, v6, v7, + v8, v9, v10, v11, v12, v13, v14, v15 }; +} + +inline __m128i _v128_set_b(char v0, char v1, char v2, char v3, char v4, char v5, char v6, + char v7, char v8, char v9, char v10, char v11, char v12, char v13, char v14, char v15) +{ + return (__m128i)v16i8{ v15, v14, v13, v12, v11, v10, v9, v8, + v7, v6, v5, v4, v3, v2, v1, v0 }; +} + +inline __m128i _v128_setr_h(short v0, short v1, short v2, short v3, short v4, short v5, + short v6, short v7) +{ + return (__m128i)v8i16{ v0, v1, v2, v3, v4, v5, v6, v7 }; +} + +inline __m128i _v128_setr_w(int v0, int v1, int v2, int v3) +{ + return (__m128i)v4i32{ v0, v1, v2, v3 }; +} + +inline __m128i _v128_set_w(int v0, int v1, int v2, int v3) +{ + return (__m128i)v4i32{ v3, v2, v1, v0 }; +} + +inline __m128i _v128_setall_w(int v0) +{ + return __lsx_vreplgr2vr_w(v0); +} + +inline __m128i _v128_setr_d(int64 v0, int64 v1) +{ + return (__m128i)v2i64{ v0, v1 }; +} + +inline __m128i _v128_set_d(int64 v0, int64 v1) +{ + return (__m128i)v2i64{ v1, v0 }; +} + +inline __m128 _v128_setr_ps(float v0, float v1, float v2, float v3) +{ + return (__m128)v4f32{ v0, v1, v2, v3 }; +} + +inline __m128 _v128_setall_ps(float v0) +{ + return (__m128)v4f32{ v0, v0, v0, v0 }; +} + +inline __m128d _v128_setr_pd(double v0, double v1) +{ + return (__m128d)v2f64{ v0, v1 }; +} + +inline __m128d _v128_setall_pd(double v0) +{ + return (__m128d)v2f64{ v0, v0 }; +} + +inline __m128i _lsx_packus_h(const __m128i& a, const __m128i& b) +{ + return __lsx_vssrarni_bu_h(b, a, 0); +} + +inline __m128i _lsx_packs_h(const __m128i& a, const __m128i& b) +{ + return __lsx_vssrarni_b_h(b, a, 0); +} + +inline __m128i _lsx_packus_w(const __m128i& a, const __m128i& b) +{ + return __lsx_vssrarni_hu_w(b, a, 0); +} + +/////// Types /////// + +struct v_uint8x16 +{ + typedef uchar lane_type; + enum { nlanes = 16}; + + v_uint8x16() {} + explicit v_uint8x16(__m128i v): val(v) {} + v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, + uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) + { + val = _v128_setr_b(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15); + } + + uchar get0() const + { + return (uchar)__lsx_vpickve2gr_bu(val, 0); + } + + __m128i val; +}; + +struct v_int8x16 +{ + typedef schar lane_type; + enum { nlanes = 16 }; + + v_int8x16() {} + explicit v_int8x16(__m128i v) : val(v) {} + v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, + schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) + { + val = _v128_setr_b(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15); + } + + schar get0() const + { + return (schar)__lsx_vpickve2gr_b(val, 0); + } + + __m128i val; +}; + +struct v_uint16x8 +{ + typedef ushort lane_type; + enum { nlanes = 8 }; + + v_uint16x8() {} + explicit v_uint16x8(__m128i v) : val(v) {} + v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) + { + val = _v128_setr_h(v0, v1, v2, v3, v4, v5, v6, v7); + } + + ushort get0() const + { + return (ushort)__lsx_vpickve2gr_hu(val, 0); + } + + __m128i val; +}; + +struct v_int16x8 +{ + typedef short lane_type; + enum { nlanes = 8 }; + + v_int16x8() {} + explicit v_int16x8(__m128i v) : val(v) {} + v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) + { + val = _v128_setr_h(v0, v1, v2, v3, v4, v5, v6, v7); + } + + short get0() const + { + return (short)__lsx_vpickve2gr_h(val, 0); + } + + __m128i val; +}; + +struct v_uint32x4 +{ + typedef unsigned lane_type; + enum { nlanes = 4 }; + + v_uint32x4() {} + explicit v_uint32x4(__m128i v) : val(v) {} + v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) + { + val = _v128_setr_w(v0, v1, v2, v3); + } + + unsigned get0() const + { + return (unsigned)__lsx_vpickve2gr_wu(val, 0); + } + + __m128i val; +}; + +struct v_int32x4 +{ + typedef int lane_type; + enum { nlanes = 4 }; + + v_int32x4() {} + explicit v_int32x4(__m128i v) : val(v) {} + v_int32x4(int v0, int v1, int v2, int v3) + { + val = _v128_setr_w(v0, v1, v2, v3); + } + + int get0() const + { + return (int)__lsx_vpickve2gr_w(val, 0); + } + + __m128i val; +}; + +struct v_float32x4 +{ + typedef float lane_type; + enum { nlanes = 4}; + + v_float32x4() {} + explicit v_float32x4(__m128 v) : val(v) {} + explicit v_float32x4(__m128i v) { val = *((__m128*)&v); } + v_float32x4(float v0, float v1, float v2, float v3) + { + val = _v128_setr_ps(v0, v1, v2, v3); + } + + float get0() const + { + union { int iv; float fv; } d; + d.iv = __lsx_vpickve2gr_w(val, 0); + return d.fv; + } + + int get0toint() const + { + __m128i result = __lsx_vftintrz_w_s(val); + return (int)__lsx_vpickve2gr_w(result, 0); + } + + __m128 val; +}; + +struct v_uint64x2 +{ + typedef uint64 lane_type; + enum { nlanes = 2}; + + v_uint64x2() {} + explicit v_uint64x2(__m128i v) : val(v) {} + v_uint64x2(uint64 v0, uint64 v1) + { + val = _v128_setr_d(v0, v1); + } + + uint64 get0() const + { + return __lsx_vpickve2gr_du(val, 0); + } + + __m128i val; +}; + +struct v_int64x2 +{ + typedef int64 lane_type; + enum { nlanes = 2}; + + v_int64x2() {} + explicit v_int64x2(__m128i v) : val(v) {} + v_int64x2(int64 v0, int64 v1) + { + val = _v128_setr_d(v0, v1); + } + + uint64 get0() const + { + return __lsx_vpickve2gr_d(val, 0); + } + + __m128i val; +}; + +struct v_float64x2 +{ + typedef double lane_type; + enum { nlanes = 2}; + + v_float64x2() {} + explicit v_float64x2(__m128d v) : val(v) {} + explicit v_float64x2(__m128i v) { val = *((__m128d*)&v); } + v_float64x2(double v0, double v1) + { + val = _v128_setr_pd(v0, v1); + } + + double get0() const + { + union { int64 iv; double fv; } d; + d.iv = __lsx_vpickve2gr_d(val, 0); + return d.fv; + } + + int64 get0toint64() const + { + __m128i result = __lsx_vftintrz_l_d(val); + return (int64)__lsx_vpickve2gr_d(result, 0); + } + + __m128d val; +}; + +////////////// Load and store operations ///////// + +#define OPENCV_HAL_IMPL_LSX_LOADSTORE(_Tpvec, _Tp) \ + inline _Tpvec v_load(const _Tp* ptr) \ + { return _Tpvec(__lsx_vld(ptr, 0)); } \ + inline _Tpvec v_load_aligned(const _Tp* ptr) \ + { return _Tpvec(__lsx_vld(ptr, 0)); } \ + inline _Tpvec v_load_low(const _Tp* ptr) \ + { return _Tpvec(__lsx_vldrepl_d(ptr, 0)); } \ + inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ + { \ + __m128i vl = __lsx_vldrepl_d(ptr0, 0); \ + __m128i vh = __lsx_vldrepl_d(ptr1, 0); \ + return _Tpvec(__lsx_vilvl_d(vh, vl)); \ + } \ + inline void v_store(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vst(a.val, ptr, 0); } \ + inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vst(a.val, ptr, 0); } \ + inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vst(a.val, ptr, 0); } \ + inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode)\ + { \ + if ( mode == hal::STORE_UNALIGNED) \ + __lsx_vst(a.val, ptr, 0); \ + else if ( mode == hal::STORE_ALIGNED_NOCACHE) \ + __lsx_vst(a.val, ptr, 0); \ + else \ + __lsx_vst(a.val, ptr, 0); \ + } \ + inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vstelm_d(a.val, ptr, 0, 0); } \ + inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vstelm_d(a.val, ptr, 0, 1); } \ + +OPENCV_HAL_IMPL_LSX_LOADSTORE(v_uint8x16, uchar) +OPENCV_HAL_IMPL_LSX_LOADSTORE(v_int8x16, schar) +OPENCV_HAL_IMPL_LSX_LOADSTORE(v_uint16x8, ushort) +OPENCV_HAL_IMPL_LSX_LOADSTORE(v_int16x8, short) +OPENCV_HAL_IMPL_LSX_LOADSTORE(v_uint32x4, unsigned) +OPENCV_HAL_IMPL_LSX_LOADSTORE(v_int32x4, int) +OPENCV_HAL_IMPL_LSX_LOADSTORE(v_uint64x2, uint64) +OPENCV_HAL_IMPL_LSX_LOADSTORE(v_int64x2, int64) + +#define OPENCV_HAL_IMPL_LSX_LOADSTORE_FLT(_Tpvec, _Tp, halfreg) \ + inline _Tpvec v_load(const _Tp* ptr) \ + { return _Tpvec((halfreg)__lsx_vld(ptr, 0)); } \ + inline _Tpvec v_load_aligned(const _Tp* ptr) \ + { return _Tpvec((halfreg)__lsx_vld(ptr, 0)); } \ + inline _Tpvec v_load_low(const _Tp* ptr) \ + { return _Tpvec((halfreg)__lsx_vldrepl_d(ptr, 0)); } \ + inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ + { \ + __m128i vl = __lsx_vldrepl_d(ptr0, 0); \ + __m128i vh = __lsx_vldrepl_d(ptr1, 0); \ + return _Tpvec((halfreg)__lsx_vilvl_d(vh, vl)); \ + } \ + inline void v_store(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vst((__m128i)a.val, ptr, 0); } \ + inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vst((__m128i)a.val, ptr, 0); } \ + inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vst((__m128i)a.val, ptr, 0); } \ + inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode)\ + { \ + if( mode == hal::STORE_UNALIGNED) \ + __lsx_vst((__m128i)a.val, ptr, 0); \ + else if( mode == hal::STORE_ALIGNED_NOCACHE) \ + __lsx_vst((__m128i)a.val, ptr, 0); \ + else \ + __lsx_vst((__m128i)a.val, ptr, 0); \ + } \ + inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vstelm_d((__m128i)a.val, ptr, 0, 0); } \ + inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vstelm_d((__m128i)a.val, ptr, 0, 1); } \ + +OPENCV_HAL_IMPL_LSX_LOADSTORE_FLT(v_float32x4, float, __m128) +OPENCV_HAL_IMPL_LSX_LOADSTORE_FLT(v_float64x2, double, __m128d) + +inline __m128i _lsx_128_castps_si128(const __m128& v) +{ return __m128i(v); } + +inline __m128i _lsx_128_castpd_si128(const __m128d& v) +{ return __m128i(v); } + +#define OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, _Tpvecf, suffix, cast) \ + inline _Tpvec v_reinterpret_as_##suffix(const _Tpvecf& a) \ + { return _Tpvec(cast(a.val)); } + +#define OPENCV_HAL_IMPL_LSX_INIT(_Tpvec, _Tp, suffix, ssuffix, ctype_s) \ + inline _Tpvec v_setzero_##suffix() \ + { return _Tpvec(__lsx_vldi(0)); } \ + inline _Tpvec v_setall_##suffix(_Tp v) \ + { return _Tpvec(__lsx_vreplgr2vr_##ssuffix((ctype_s)v)); } \ + template <> inline _Tpvec v_setzero_() \ + { return v_setzero_##suffix(); } \ + template <> inline _Tpvec v_setall_(_Tp v) \ + { return v_setall_##suffix(v); } \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint8x16, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int8x16, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint16x8, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int16x8, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint32x4, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int32x4, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint64x2, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int64x2, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_float32x4, suffix, _lsx_128_castps_si128) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_float64x2, suffix, _lsx_128_castpd_si128) \ + +OPENCV_HAL_IMPL_LSX_INIT(v_uint8x16, uchar, u8, b, int) +OPENCV_HAL_IMPL_LSX_INIT(v_int8x16, schar, s8, b, int) +OPENCV_HAL_IMPL_LSX_INIT(v_uint16x8, ushort, u16, h, int) +OPENCV_HAL_IMPL_LSX_INIT(v_int16x8, short, s16, h, int) +OPENCV_HAL_IMPL_LSX_INIT(v_uint32x4, unsigned, u32, w, int) +OPENCV_HAL_IMPL_LSX_INIT(v_int32x4, int, s32, w, int) +OPENCV_HAL_IMPL_LSX_INIT(v_uint64x2, uint64, u64, d, long int) +OPENCV_HAL_IMPL_LSX_INIT(v_int64x2, int64, s64, d, long int) + +inline __m128 _lsx_128_castsi128_ps(const __m128i &v) +{ return __m128(v); } + +inline __m128d _lsx_128_castsi128_pd(const __m128i &v) +{ return __m128d(v); } + +#define OPENCV_HAL_IMPL_LSX_INIT_FLT(_Tpvec, _Tp, suffix, zsuffix, cast) \ + inline _Tpvec v_setzero_##suffix() \ + { return _Tpvec(__lsx_vldi(0)); } \ + inline _Tpvec v_setall_##suffix(_Tp v) \ + { return _Tpvec(_v128_setall_##zsuffix(v)); } \ + template <> inline _Tpvec v_setzero_() \ + { return v_setzero_##suffix(); } \ + template <> inline _Tpvec v_setall_(_Tp v) \ + { return v_setall_##suffix(v); } \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint8x16, suffix, cast) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int8x16, suffix, cast) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint16x8, suffix, cast) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int16x8, suffix, cast) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint32x4, suffix, cast) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int32x4, suffix, cast) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint64x2, suffix, cast) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int64x2, suffix, cast) \ + +OPENCV_HAL_IMPL_LSX_INIT_FLT(v_float32x4, float, f32, ps, _lsx_128_castsi128_ps) +OPENCV_HAL_IMPL_LSX_INIT_FLT(v_float64x2, double, f64, pd, _lsx_128_castsi128_pd) + +inline v_float32x4 v_reinterpret_as_f32(const v_float32x4& a) +{ return a; } +inline v_float32x4 v_reinterpret_as_f32(const v_float64x2& a) +{ return v_float32x4(_lsx_128_castps_si128(__m128(a.val))); } + +inline v_float64x2 v_reinterpret_as_f64(const v_float64x2& a) +{ return a; } +inline v_float64x2 v_reinterpret_as_f64(const v_float32x4& a) +{ return v_float64x2(_lsx_128_castpd_si128(__m128d(a.val))); } + +//////////////// Variant Value reordering /////////////// + +// unpacks +#define OPENCV_HAL_IMPL_LSX_UNPACK(_Tpvec, suffix) \ + inline _Tpvec v128_unpacklo(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(__lsx_vilvl_##suffix(__m128i(b.val), __m128i(a.val))); } \ + inline _Tpvec v128_unpackhi(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(__lsx_vilvh_##suffix(__m128i(b.val), __m128i(a.val))); } \ + +OPENCV_HAL_IMPL_LSX_UNPACK(v_uint8x16, b) +OPENCV_HAL_IMPL_LSX_UNPACK(v_int8x16, b) +OPENCV_HAL_IMPL_LSX_UNPACK(v_uint16x8, h) +OPENCV_HAL_IMPL_LSX_UNPACK(v_int16x8, h) +OPENCV_HAL_IMPL_LSX_UNPACK(v_uint32x4, w) +OPENCV_HAL_IMPL_LSX_UNPACK(v_int32x4, w) +OPENCV_HAL_IMPL_LSX_UNPACK(v_uint64x2, d) +OPENCV_HAL_IMPL_LSX_UNPACK(v_int64x2, d) +OPENCV_HAL_IMPL_LSX_UNPACK(v_float32x4, w) +OPENCV_HAL_IMPL_LSX_UNPACK(v_float64x2, d) + +//ZIP +#define OPENCV_HAL_IMPL_LSX_ZIP(_Tpvec) \ + inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ + { return (_Tpvec)__lsx_vilvl_d((__m128i)b.val, (__m128i)a.val); } \ + inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ + { return (_Tpvec)__lsx_vilvh_d((__m128i)b.val, (__m128i)a.val); } \ + inline void v_recombine(const _Tpvec& a, const _Tpvec& b, \ + _Tpvec& c, _Tpvec& d) \ + { \ + __m128i a1 = (__m128i)a.val, b1 = (__m128i)b.val; \ + c = _Tpvec(__lsx_vilvl_d(b1, a1)); \ + d = _Tpvec(__lsx_vilvh_d(b1, a1)); \ + } \ + inline void v_zip(const _Tpvec& a, const _Tpvec& b, \ + _Tpvec& ab0, _Tpvec& ab1) \ + { \ + ab0 = v128_unpacklo(a, b); \ + ab1 = v128_unpackhi(a, b); \ + } + +OPENCV_HAL_IMPL_LSX_ZIP(v_uint8x16) +OPENCV_HAL_IMPL_LSX_ZIP(v_int8x16) +OPENCV_HAL_IMPL_LSX_ZIP(v_uint16x8) +OPENCV_HAL_IMPL_LSX_ZIP(v_int16x8) +OPENCV_HAL_IMPL_LSX_ZIP(v_uint32x4) +OPENCV_HAL_IMPL_LSX_ZIP(v_int32x4) +OPENCV_HAL_IMPL_LSX_ZIP(v_uint64x2) +OPENCV_HAL_IMPL_LSX_ZIP(v_int64x2) +OPENCV_HAL_IMPL_LSX_ZIP(v_float32x4) +OPENCV_HAL_IMPL_LSX_ZIP(v_float64x2) + +////////// Arithmetic, bitwise and comparison operations ///////// + +/** Arithmetics **/ +#define OPENCV_HAL_IMPL_LSX_BIN_OP(bin_op, _Tpvec, intrin) \ + inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(intrin(a.val, b.val)); } + +OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_uint8x16, __lsx_vsadd_bu) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_uint8x16, __lsx_vssub_bu) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_int8x16, __lsx_vsadd_b) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_int8x16, __lsx_vssub_b) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_uint16x8, __lsx_vsadd_hu) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_uint16x8, __lsx_vssub_hu) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_int16x8, __lsx_vsadd_h) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_int16x8, __lsx_vssub_h) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_uint32x4, __lsx_vadd_w) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_uint32x4, __lsx_vsub_w) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_mul, v_uint32x4, __lsx_vmul_w) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_int32x4, __lsx_vadd_w) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_int32x4, __lsx_vsub_w) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_mul, v_int32x4, __lsx_vmul_w) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_uint64x2, __lsx_vadd_d) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_uint64x2, __lsx_vsub_d) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_int64x2, __lsx_vadd_d) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_int64x2, __lsx_vsub_d) + +OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_float32x4, __lsx_vfadd_s) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_float32x4, __lsx_vfsub_s) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_mul, v_float32x4, __lsx_vfmul_s) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_div, v_float32x4, __lsx_vfdiv_s) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_float64x2, __lsx_vfadd_d) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_float64x2, __lsx_vfsub_d) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_mul, v_float64x2, __lsx_vfmul_d) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_div, v_float64x2, __lsx_vfdiv_d) + +// saturating multiply 8-bit, 16-bit +inline v_uint8x16 v_mul(const v_uint8x16& a, const v_uint8x16& b) +{ + v_uint16x8 c, d; + v_mul_expand(a, b, c, d); + return v_pack(c, d); +} +inline v_int8x16 v_mul(const v_int8x16& a, const v_int8x16& b) +{ + v_int16x8 c, d; + v_mul_expand(a, b, c, d); + return v_pack(c, d); +} +inline v_uint16x8 v_mul(const v_uint16x8& a, const v_uint16x8& b) +{ + __m128i a0 = a.val, b0 = b.val; + __m128i pev = __lsx_vmulwev_w_hu(a0, b0); + __m128i pod = __lsx_vmulwod_w_hu(a0, b0); + __m128i pl = __lsx_vilvl_w(pod, pev); + __m128i ph = __lsx_vilvh_w(pod, pev); + return (v_uint16x8)__lsx_vssrlrni_hu_w(ph, pl, 0); +} +inline v_int16x8 v_mul(const v_int16x8& a, const v_int16x8& b) +{ + __m128i a0 = a.val, b0 = b.val; + __m128i pev = __lsx_vmulwev_w_h(a0, b0); + __m128i pod = __lsx_vmulwod_w_h(a0, b0); + __m128i pl = __lsx_vilvl_w(pod, pev); + __m128i ph = __lsx_vilvh_w(pod, pev); + return (v_int16x8)__lsx_vssrarni_h_w(ph, pl, 0); +} + +/** Non-saturating arithmetics **/ + +#define OPENCV_HAL_IMPL_LSX_BIN_FUNC(func, _Tpvec, intrin) \ + inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(intrin(a.val, b.val)); } \ + +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_add_wrap, v_uint8x16, __lsx_vadd_b) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_add_wrap, v_int8x16, __lsx_vadd_b) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_add_wrap, v_uint16x8, __lsx_vadd_h) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_add_wrap, v_int16x8, __lsx_vadd_h) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_sub_wrap, v_uint8x16, __lsx_vsub_b) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_sub_wrap, v_int8x16, __lsx_vsub_b) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_sub_wrap, v_uint16x8, __lsx_vsub_h) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_sub_wrap, v_int16x8, __lsx_vsub_h) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_mul_wrap, v_uint16x8, __lsx_vmul_h) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_mul_wrap, v_int16x8, __lsx_vmul_h) + +inline v_uint8x16 v_mul_wrap(const v_uint8x16& a, const v_uint8x16& b) +{ + __m128i a0 = a.val, b0 = b.val; + __m128i p0 = __lsx_vmulwev_h_bu(a0, b0); + __m128i p1 = __lsx_vmulwod_h_bu(a0, b0); + return v_uint8x16(__lsx_vpackev_b(p1, p0)); +} + +inline v_int8x16 v_mul_wrap(const v_int8x16& a, const v_int8x16& b) +{ + return v_reinterpret_as_s8(v_mul_wrap(v_reinterpret_as_u8(a), v_reinterpret_as_u8(b))); +} + +// Multiply and expand +inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b, + v_uint16x8& c, v_uint16x8& d) +{ + __m128i a0 = a.val, b0 = b.val; + __m128i p0 = __lsx_vmulwev_h_bu(a0, b0); + __m128i p1 = __lsx_vmulwod_h_bu(a0, b0); + c.val = __lsx_vilvl_h(p1, p0); + d.val = __lsx_vilvh_h(p1, p0); +} +inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b, + v_int16x8& c, v_int16x8& d) +{ + __m128i a0 = a.val, b0 = b.val; + __m128i p0 = __lsx_vmulwev_h_b(a0, b0); + __m128i p1 = __lsx_vmulwod_h_b(a0, b0); + c.val = __lsx_vilvl_h(p1, p0); + d.val = __lsx_vilvh_h(p1, p0); +} +inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, + v_int32x4& c, v_int32x4& d) +{ + __m128i a0 = a.val, b0 = b.val; + __m128i p0 = __lsx_vmulwev_w_h(a0, b0); + __m128i p1 = __lsx_vmulwod_w_h(a0, b0); + c.val = __lsx_vilvl_w(p1, p0); + d.val = __lsx_vilvh_w(p1, p0); +} +inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, + v_uint32x4& c, v_uint32x4& d) +{ + __m128i a0 = a.val, b0 = b.val; + __m128i p0 = __lsx_vmulwev_w_hu(a0, b0); + __m128i p1 = __lsx_vmulwod_w_hu(a0, b0); + c.val = __lsx_vilvl_w(p1, p0); + d.val = __lsx_vilvh_w(p1, p0); +} +inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, + v_uint64x2& c, v_uint64x2& d) +{ + __m128i a0 = a.val, b0 = b.val; + __m128i p0 = __lsx_vmulwev_d_wu(a0, b0); + __m128i p1 = __lsx_vmulwod_d_wu(a0, b0); + c.val = __lsx_vilvl_d(p1, p0); + d.val = __lsx_vilvh_d(p1, p0); +} +inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) +{ return v_int16x8(__lsx_vmuh_h(a.val, b.val)); } +inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) +{ return v_uint16x8(__lsx_vmuh_hu(a.val, b.val)); } + +/** Bitwise shifts **/ +#define OPENCV_HAL_IMPL_LSX_SHIFT_OP(_Tpuvec, _Tpsvec, suffix, srai) \ + inline _Tpuvec v_shl(const _Tpuvec& a, int imm) \ + { return _Tpuvec(__lsx_vsll_##suffix(a.val, __lsx_vreplgr2vr_##suffix(imm))); } \ + inline _Tpsvec v_shl(const _Tpsvec& a, int imm) \ + { return _Tpsvec(__lsx_vsll_##suffix(a.val, __lsx_vreplgr2vr_##suffix(imm))); } \ + inline _Tpuvec v_shr(const _Tpuvec& a, int imm) \ + { return _Tpuvec(__lsx_vsrl_##suffix(a.val, __lsx_vreplgr2vr_##suffix(imm))); } \ + inline _Tpsvec v_shr(const _Tpsvec& a, int imm) \ + { return _Tpsvec(srai(a.val, __lsx_vreplgr2vr_##suffix(imm))); } \ + template \ + inline _Tpuvec v_shl(const _Tpuvec& a) \ + { return _Tpuvec(__lsx_vslli_##suffix(a.val, imm)); } \ + template \ + inline _Tpsvec v_shl(const _Tpsvec& a) \ + { return _Tpsvec(__lsx_vslli_##suffix(a.val, imm)); } \ + template \ + inline _Tpuvec v_shr(const _Tpuvec& a) \ + { return _Tpuvec(__lsx_vsrli_##suffix(a.val, imm)); } \ + template \ + inline _Tpsvec v_shr(const _Tpsvec& a) \ + { return _Tpsvec(__lsx_vsrai_##suffix(a.val, imm)); } \ + +OPENCV_HAL_IMPL_LSX_SHIFT_OP(v_uint16x8, v_int16x8, h, __lsx_vsra_h) +OPENCV_HAL_IMPL_LSX_SHIFT_OP(v_uint32x4, v_int32x4, w, __lsx_vsra_w) +OPENCV_HAL_IMPL_LSX_SHIFT_OP(v_uint64x2, v_int64x2, d, __lsx_vsra_d) + +/** Bitwise logic **/ +#define OPENCV_HAL_IMPL_LSX_LOGIC_OP(_Tpvec, suffix) \ + OPENCV_HAL_IMPL_LSX_BIN_OP(v_and, _Tpvec, __lsx_vand_##suffix) \ + OPENCV_HAL_IMPL_LSX_BIN_OP(v_or, _Tpvec, __lsx_vor_##suffix) \ + OPENCV_HAL_IMPL_LSX_BIN_OP(v_xor, _Tpvec, __lsx_vxor_##suffix) \ + inline _Tpvec v_not(const _Tpvec& a) \ + { return _Tpvec(__lsx_vnori_b(a.val, 0)); } \ + +OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_uint8x16, v) +OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_int8x16, v) +OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_uint16x8, v) +OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_int16x8, v) +OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_uint32x4, v) +OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_int32x4, v) +OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_uint64x2, v) +OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_int64x2, v) + +#define OPENCV_HAL_IMPL_LSX_FLOAT_BIN_OP(bin_op, _Tpvec, intrin, cast) \ + inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(intrin((__m128i)(a.val), (__m128i)(b.val))); } + +#define OPENCV_HAL_IMPL_LSX_FLOAT_LOGIC_OP(_Tpvec, cast) \ + OPENCV_HAL_IMPL_LSX_FLOAT_BIN_OP(v_and, _Tpvec, __lsx_vand_v, cast) \ + OPENCV_HAL_IMPL_LSX_FLOAT_BIN_OP(v_or, _Tpvec, __lsx_vor_v, cast) \ + OPENCV_HAL_IMPL_LSX_FLOAT_BIN_OP(v_xor, _Tpvec, __lsx_vxor_v, cast) \ + inline _Tpvec v_not(const _Tpvec& a) \ + { return _Tpvec(__lsx_vnori_b((__m128i)(a.val), 0)); } \ + +OPENCV_HAL_IMPL_LSX_FLOAT_LOGIC_OP(v_float32x4, _lsx_128_castsi128_ps) +OPENCV_HAL_IMPL_LSX_FLOAT_LOGIC_OP(v_float64x2, _lsx_128_castsi128_pd) + +/** Select **/ +#define OPENCV_HAL_IMPL_LSX_SELECT(_Tpvec) \ + inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(__lsx_vbitsel_v(b.val, a.val, mask.val)); } \ + +OPENCV_HAL_IMPL_LSX_SELECT(v_uint8x16) +OPENCV_HAL_IMPL_LSX_SELECT(v_int8x16) +OPENCV_HAL_IMPL_LSX_SELECT(v_uint16x8) +OPENCV_HAL_IMPL_LSX_SELECT(v_int16x8) +OPENCV_HAL_IMPL_LSX_SELECT(v_uint32x4) +OPENCV_HAL_IMPL_LSX_SELECT(v_int32x4) + +inline v_float32x4 v_select(const v_float32x4 &mask, const v_float32x4 &a, const v_float32x4 &b) +{ return v_float32x4(__lsx_vbitsel_v((__m128i)b.val, (__m128i)a.val, (__m128i)mask.val)); } +inline v_float64x2 v_select(const v_float64x2 &mask, const v_float64x2 &a, const v_float64x2 &b) +{ return v_float64x2(__lsx_vbitsel_v((__m128i)b.val, (__m128i)a.val, (__m128i)mask.val)); } + +/** Comparison **/ +#define OPENCV_HAL_IMPL_LSX_CMP_OP_OV(_Tpvec) \ + inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ + { return v_not(v_eq(a, b)); } \ + inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ + { return v_gt(b, a); } \ + inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ + { return v_not(v_lt(a, b)); } \ + inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ + { return v_ge(b, a); } \ + +#define OPENCV_HAL_IMPL_LSX_CMP_OP_INT(_Tpuvec, _Tpsvec, suffix, usuffix) \ + inline _Tpuvec v_eq(const _Tpuvec& a, const _Tpuvec& b) \ + { return _Tpuvec(__lsx_vseq_##suffix(a.val, b.val)); } \ + inline _Tpuvec v_gt(const _Tpuvec& a, const _Tpuvec& b) \ + { return _Tpuvec(__lsx_vslt_##usuffix(b.val, a.val)); } \ + inline _Tpsvec v_eq(const _Tpsvec& a, const _Tpsvec& b) \ + { return _Tpsvec(__lsx_vseq_##suffix(a.val, b.val)); } \ + inline _Tpsvec v_gt(const _Tpsvec& a, const _Tpsvec& b) \ + { return _Tpsvec(__lsx_vslt_##suffix(b.val, a.val)); } \ + OPENCV_HAL_IMPL_LSX_CMP_OP_OV(_Tpuvec) \ + OPENCV_HAL_IMPL_LSX_CMP_OP_OV(_Tpsvec) + +OPENCV_HAL_IMPL_LSX_CMP_OP_INT(v_uint8x16, v_int8x16, b, bu) +OPENCV_HAL_IMPL_LSX_CMP_OP_INT(v_uint16x8, v_int16x8, h, hu) +OPENCV_HAL_IMPL_LSX_CMP_OP_INT(v_uint32x4, v_int32x4, w, wu) + +#define OPENCV_HAL_IMPL_LSX_CMP_OP_64BIT(_Tpvec, suffix) \ + inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(__lsx_vseq_##suffix(a.val, b.val)); } \ + inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ + { return v_not(v_eq(a, b)); } + +OPENCV_HAL_IMPL_LSX_CMP_OP_64BIT(v_uint64x2, d) +OPENCV_HAL_IMPL_LSX_CMP_OP_64BIT(v_int64x2, d) + +#define OPENCV_HAL_IMPL_LSX_CMP_FLT(bin_op, suffix, _Tpvec, ssuffix) \ + inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(__lsx_##suffix##_##ssuffix(a.val, b.val)); } \ + +#define OPENCV_HAL_IMPL_LSX_CMP_OP_FLT(_Tpvec, ssuffix) \ + OPENCV_HAL_IMPL_LSX_CMP_FLT(v_eq, vfcmp_ceq, _Tpvec, ssuffix) \ + OPENCV_HAL_IMPL_LSX_CMP_FLT(v_ne, vfcmp_cne, _Tpvec, ssuffix) \ + OPENCV_HAL_IMPL_LSX_CMP_FLT(v_lt, vfcmp_clt, _Tpvec, ssuffix) \ + OPENCV_HAL_IMPL_LSX_CMP_FLT(v_le, vfcmp_cle, _Tpvec, ssuffix) \ + +OPENCV_HAL_IMPL_LSX_CMP_OP_FLT(v_float32x4, s) +OPENCV_HAL_IMPL_LSX_CMP_OP_FLT(v_float64x2, d) + +inline v_float32x4 v_gt(const v_float32x4 &a, const v_float32x4 &b) +{ return v_float32x4(__lsx_vfcmp_clt_s(b.val, a.val)); } + +inline v_float32x4 v_ge(const v_float32x4 &a, const v_float32x4 &b) +{ return v_float32x4(__lsx_vfcmp_cle_s(b.val, a.val)); } + +inline v_float64x2 v_gt(const v_float64x2 &a, const v_float64x2 &b) +{ return v_float64x2(__lsx_vfcmp_clt_d(b.val, a.val)); } + +inline v_float64x2 v_ge(const v_float64x2 &a, const v_float64x2 &b) +{ return v_float64x2(__lsx_vfcmp_cle_d(b.val, a.val)); } + +inline v_float32x4 v_not_nan(const v_float32x4& a) +{ return v_float32x4(__lsx_vfcmp_cor_s(a.val, a.val)); } + +inline v_float64x2 v_not_nan(const v_float64x2& a) +{ return v_float64x2(__lsx_vfcmp_cor_d(a.val, a.val)); } + +/** min/max **/ +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_uint8x16, __lsx_vmin_bu) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_uint8x16, __lsx_vmax_bu) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_int8x16, __lsx_vmin_b) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_int8x16, __lsx_vmax_b) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_uint16x8, __lsx_vmin_hu) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_uint16x8, __lsx_vmax_hu) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_int16x8, __lsx_vmin_h) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_int16x8, __lsx_vmax_h) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_uint32x4, __lsx_vmin_wu) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_uint32x4, __lsx_vmax_wu) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_int32x4, __lsx_vmin_w) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_int32x4, __lsx_vmax_w) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_float32x4, __lsx_vfmin_s) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_float32x4, __lsx_vfmax_s) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_float64x2, __lsx_vfmin_d) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_float64x2, __lsx_vfmax_d) + +template 16)), + bool is_first = (imm == 0), + bool is_half = (imm == 8), + bool is_second = (imm == 16), + bool is_other = (((imm > 0) && (imm < 8)) || ((imm > 8) && (imm < 16)))> +class v_lsx_palignr_u8_class; + +template +class v_lsx_palignr_u8_class; + +template +class v_lsx_palignr_u8_class +{ +public: + inline __m128i operator()(const __m128i& a, const __m128i& b) const + { + CV_UNUSED(b); + return a; + } +}; + +template +class v_lsx_palignr_u8_class +{ +public: + inline __m128i operator()(const __m128i& a, const __m128i& b) const + { + return __lsx_vshuf4i_d(a, b, 0x9); + } +}; + +template +class v_lsx_palignr_u8_class +{ +public: + inline __m128i operator()(const __m128i& a, const __m128i& b) const + { + CV_UNUSED(a); + return b; + } +}; + +template +class v_lsx_palignr_u8_class +{ +public: + inline __m128i operator()(const __m128i& a, const __m128i& b) const + { + enum { imm2 = (sizeof(__m128i) - imm) }; + return __lsx_vor_v(__lsx_vbsrl_v(a, imm), __lsx_vbsll_v(b, imm2)); + } +}; + +template +inline __m128i v_lsx_palignr_u8(const __m128i& a, const __m128i& b) +{ + CV_StaticAssert((imm >= 0) && (imm <= 16), "Invalid imm for v_lsx_palignr_u8"); + return v_lsx_palignr_u8_class()(a, b); +} +/** Rotate **/ +#define OPENCV_HAL_IMPL_LSX_ROTATE_CAST(_Tpvec, cast) \ + template \ + inline _Tpvec v_rotate_right(const _Tpvec &a) \ + { \ + enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type))}; \ + __m128i ret = __lsx_vbsrl_v((__m128i)a.val, imm2); \ + return _Tpvec(cast(ret)); \ + } \ + template \ + inline _Tpvec v_rotate_left(const _Tpvec &a) \ + { \ + enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type))}; \ + __m128i ret = __lsx_vbsll_v((__m128i)a.val, imm2); \ + return _Tpvec(cast(ret)); \ + } \ + template \ + inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ + { \ + enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type))}; \ + return _Tpvec(cast(v_lsx_palignr_u8((__m128i)a.val, (__m128i)b.val))); \ + } \ + template \ + inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ + { \ + enum { imm2 = ((_Tpvec::nlanes - imm) * sizeof(typename _Tpvec::lane_type))}; \ + return _Tpvec(cast(v_lsx_palignr_u8((__m128i)b.val, (__m128i)a.val))); \ + } + +OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_uint8x16, OPENCV_HAL_NOP) \ +OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_int8x16, OPENCV_HAL_NOP) \ +OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_uint16x8, OPENCV_HAL_NOP) \ +OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_int16x8, OPENCV_HAL_NOP) \ +OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_uint32x4, OPENCV_HAL_NOP) \ +OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_int32x4, OPENCV_HAL_NOP) \ +OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_uint64x2, OPENCV_HAL_NOP) \ +OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_int64x2, OPENCV_HAL_NOP) \ + +OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_float32x4, _lsx_128_castsi128_ps) +OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_float64x2, _lsx_128_castsi128_pd) + +/** Rverse **/ +inline v_uint8x16 v_reverse(const v_uint8x16 &a) +{ + __m128i vec = __lsx_vshuf4i_b(a.val, 0x1B); + return v_uint8x16(__lsx_vshuf4i_w(vec, 0x1B)); +} + +inline v_int8x16 v_reverse(const v_int8x16 &a) +{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } + +inline v_uint16x8 v_reverse(const v_uint16x8 &a) +{ + __m128i vec = __lsx_vshuf4i_h(a.val, 0x1B); + return v_uint16x8(__lsx_vshuf4i_w(vec, 0x4E)); +} + +inline v_int16x8 v_reverse(const v_int16x8 &a) +{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } + +inline v_uint32x4 v_reverse(const v_uint32x4 &a) +{ return v_uint32x4(__lsx_vshuf4i_w(a.val, 0x1B)); } + +inline v_int32x4 v_reverse(const v_int32x4 &a) +{ return v_int32x4(__lsx_vshuf4i_w(a.val, 0x1B)); } + +inline v_uint64x2 v_reverse(const v_uint64x2 &a) +{ return v_uint64x2(__lsx_vshuf4i_w(a.val, 0x4E)); } + +inline v_int64x2 v_reverse(const v_int64x2 &a) +{ return v_int64x2(__lsx_vshuf4i_w(a.val, 0x4E)); } + +inline v_float32x4 v_reverse(const v_float32x4 &a) +{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_float64x2 v_reverse(const v_float64x2 &a) +{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } + +////////////// Reduce and mask //////////// + +/** Reduce **/ +// this function is return a[0]+a[1]+...+a[31] +inline unsigned v_reduce_sum(const v_uint8x16& a) +{ + __m128i t1 = __lsx_vhaddw_hu_bu(a.val, a.val); + __m128i t2 = __lsx_vhaddw_wu_hu(t1, t1); + __m128i t3 = __lsx_vhaddw_du_wu(t2, t2); + __m128i t4 = __lsx_vhaddw_qu_du(t3, t3); + return (unsigned)__lsx_vpickve2gr_w(t4, 0); +} + +inline int v_reduce_sum(const v_int8x16 &a) +{ + __m128i t1 = __lsx_vhaddw_h_b(a.val, a.val); + __m128i t2 = __lsx_vhaddw_w_h(t1, t1); + __m128i t3 = __lsx_vhaddw_d_w(t2, t2); + __m128i t4 = __lsx_vhaddw_q_d(t3, t3); + return (int)__lsx_vpickve2gr_w(t4, 0); +} + +#define OPENCV_HAL_IMPL_LSX_REDUCE_16(_Tpvec, sctype, func, intrin) \ + inline sctype v_reduce_##func(const _Tpvec& a) \ + { \ + __m128i val = intrin(a.val, __lsx_vbsrl_v(a.val, 8)); \ + val = intrin(val, __lsx_vbsrl_v(val, 4)); \ + val = intrin(val, __lsx_vbsrl_v(val, 2)); \ + val = intrin(val, __lsx_vbsrl_v(val, 1)); \ + return (sctype)__lsx_vpickve2gr_b(val, 0); \ + } + +OPENCV_HAL_IMPL_LSX_REDUCE_16(v_uint8x16, uchar, min, __lsx_vmin_bu) +OPENCV_HAL_IMPL_LSX_REDUCE_16(v_uint8x16, uchar, max, __lsx_vmax_bu) +OPENCV_HAL_IMPL_LSX_REDUCE_16(v_int8x16, schar, min, __lsx_vmin_b) +OPENCV_HAL_IMPL_LSX_REDUCE_16(v_int8x16, schar, max, __lsx_vmax_b) + +#define OPENCV_HAL_IMPL_LSX_REDUCE_8(_Tpvec, sctype, func, intrin) \ + inline sctype v_reduce_##func(const _Tpvec &a) \ + { \ + __m128i val = intrin(a.val, __lsx_vbsrl_v(a.val, 8)); \ + val = intrin(val, __lsx_vbsrl_v(val, 4)); \ + val = intrin(val, __lsx_vbsrl_v(val, 2)); \ + return (sctype)__lsx_vpickve2gr_h(val, 0); \ + } + +OPENCV_HAL_IMPL_LSX_REDUCE_8(v_uint16x8, ushort, min, __lsx_vmin_hu) +OPENCV_HAL_IMPL_LSX_REDUCE_8(v_uint16x8, ushort, max, __lsx_vmax_hu) +OPENCV_HAL_IMPL_LSX_REDUCE_8(v_int16x8, short, min, __lsx_vmin_h) +OPENCV_HAL_IMPL_LSX_REDUCE_8(v_int16x8, short, max, __lsx_vmax_h) + +#define OPENCV_HAL_IMPL_LSX_REDUCE_4(_Tpvec, sctype, func, intrin) \ + inline sctype v_reduce_##func(const _Tpvec &a) \ + { \ + __m128i val = intrin(a.val, __lsx_vbsrl_v(a.val, 8)); \ + val = intrin(val, __lsx_vbsrl_v(val, 4)); \ + return (sctype)__lsx_vpickve2gr_w(val, 0); \ + } + +OPENCV_HAL_IMPL_LSX_REDUCE_4(v_uint32x4, unsigned, min, __lsx_vmin_wu) +OPENCV_HAL_IMPL_LSX_REDUCE_4(v_uint32x4, unsigned, max, __lsx_vmax_wu) +OPENCV_HAL_IMPL_LSX_REDUCE_4(v_int32x4, int, min, __lsx_vmin_w) +OPENCV_HAL_IMPL_LSX_REDUCE_4(v_int32x4, int, max, __lsx_vmax_w) + +#define OPENCV_HAL_IMPL_LSX_REDUCE_FLT(func, intrin) \ + inline float v_reduce_##func(const v_float32x4 &a) \ + { \ + __m128 val = a.val; \ + val = intrin(val, (__m128)__lsx_vbsrl_v((__m128i)val, 8)); \ + val = intrin(val, (__m128)__lsx_vbsrl_v((__m128i)val, 4)); \ + float *fval = (float*)&val; \ + return fval[0]; \ + } + +OPENCV_HAL_IMPL_LSX_REDUCE_FLT(min, __lsx_vfmin_s) +OPENCV_HAL_IMPL_LSX_REDUCE_FLT(max, __lsx_vfmax_s) + +inline int v_reduce_sum(const v_int32x4 &a) +{ + __m128i t1 = __lsx_vhaddw_d_w(a.val, a.val); + __m128i t2 = __lsx_vhaddw_q_d(t1, t1); + return (int)__lsx_vpickve2gr_w(t2, 0); +} + +inline unsigned v_reduce_sum(const v_uint32x4 &a) +{ + __m128i t1 = __lsx_vhaddw_du_wu(a.val, a.val); + __m128i t2 = __lsx_vhaddw_qu_du(t1, t1); + return (int)__lsx_vpickve2gr_w(t2, 0); +} + +inline int v_reduce_sum(const v_int16x8 &a) +{ + __m128i t1 = __lsx_vhaddw_w_h(a.val, a.val); + __m128i t2 = __lsx_vhaddw_d_w(t1, t1); + __m128i t3 = __lsx_vhaddw_q_d(t2, t2); + return (int)__lsx_vpickve2gr_w(t3, 0); +} + +inline unsigned v_reduce_sum(const v_uint16x8 &a) +{ + __m128i t1 = __lsx_vhaddw_wu_hu(a.val, a.val); + __m128i t2 = __lsx_vhaddw_du_wu(t1, t1); + __m128i t3 = __lsx_vhaddw_qu_du(t2, t2); + return (int)__lsx_vpickve2gr_w(t3, 0); +} + +inline float v_reduce_sum(const v_float32x4 &a) +{ + __m128i val = (__m128i)a.val; + val = __lsx_vbsrl_v(val, 8); + __m128 result = __lsx_vfadd_s(a.val, (__m128)val); + float *pa = (float*)&result; + return (float)(pa[0] + pa[1]); +} + +inline uint64 v_reduce_sum(const v_uint64x2 &a) +{ + __m128i t0 = __lsx_vhaddw_qu_du(a.val, a.val); + return (uint64)__lsx_vpickve2gr_du(t0, 0); +} + +inline int64 v_reduce_sum(const v_int64x2 &a) +{ + __m128i t0 = __lsx_vhaddw_q_d(a.val, a.val); + return (int64)__lsx_vpickve2gr_d(t0, 0); +} + +inline double v_reduce_sum(const v_float64x2 &a) +{ + double *pa = (double*)&a; + return pa[0] + pa[1]; +} + +inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, + const v_float32x4& c, const v_float32x4& d) +{ + __m128i a0 = (__m128i)a.val; + __m128i b0 = (__m128i)b.val; + __m128i c0 = (__m128i)c.val; + __m128i d0 = (__m128i)d.val; + __m128i ac_l = __lsx_vilvl_w(c0, a0); + __m128i ac_h = __lsx_vilvh_w(c0, a0); + __m128i bd_l = __lsx_vilvl_w(d0, b0); + __m128i bd_h = __lsx_vilvh_w(d0, b0); + __m128 ac = __lsx_vfadd_s((__m128)ac_l, (__m128)ac_h); + __m128 bd = __lsx_vfadd_s((__m128)bd_l, (__m128)bd_h); + return v_float32x4(__lsx_vfadd_s((__m128)__lsx_vilvl_w((__m128i)bd, (__m128i)ac), + (__m128)__lsx_vilvh_w((__m128i)bd, (__m128i)ac))); +} + +inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b) +{ + __m128i t0 = __lsx_vabsd_b(a.val, b.val); + __m128i t1 = __lsx_vhaddw_hu_bu(t0, t0); + __m128i t2 = __lsx_vhaddw_wu_hu(t1, t1); + __m128i t3 = __lsx_vhaddw_du_wu(t2, t2); + __m128i t4 = __lsx_vhaddw_qu_du(t3, t3); + return (unsigned)__lsx_vpickve2gr_w(t4, 0); +} + +inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b) +{ + __m128i t0 = __lsx_vabsd_bu(a.val, b.val); + __m128i t1 = __lsx_vhaddw_hu_bu(t0, t0); + __m128i t2 = __lsx_vhaddw_wu_hu(t1, t1); + __m128i t3 = __lsx_vhaddw_du_wu(t2, t2); + __m128i t4 = __lsx_vhaddw_qu_du(t3, t3); + return (unsigned)__lsx_vpickve2gr_w(t4, 0); +} + +inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b) +{ + __m128i t0 = __lsx_vabsd_hu(a.val, b.val); + __m128i t1 = __lsx_vhaddw_wu_hu(t0, t0); + __m128i t2 = __lsx_vhaddw_du_wu(t1, t1); + __m128i t3 = __lsx_vhaddw_qu_du(t2, t2); + return (unsigned)__lsx_vpickve2gr_w(t3, 0); +} + +inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b) +{ + __m128i t0 = __lsx_vabsd_h(a.val, b.val); + __m128i t1 = __lsx_vhaddw_wu_hu(t0, t0); + __m128i t2 = __lsx_vhaddw_du_wu(t1, t1); + __m128i t3 = __lsx_vhaddw_qu_du(t2, t2); + return (unsigned)__lsx_vpickve2gr_w(t3, 0); +} + +inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b) +{ + __m128i t0 = __lsx_vabsd_wu(a.val, b.val); + __m128i t1 = __lsx_vhaddw_du_wu(t0, t0); + __m128i t2 = __lsx_vhaddw_qu_du(t1, t1); + return (unsigned)__lsx_vpickve2gr_w(t2, 0); +} + +inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b) +{ + __m128i t0 = __lsx_vabsd_w(a.val, b.val); + __m128i t1 = __lsx_vhaddw_du_wu(t0, t0); + __m128i t2 = __lsx_vhaddw_qu_du(t1, t1); + return (unsigned)__lsx_vpickve2gr_w(t2, 0); +} + +inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) +{ + v_float32x4 a_b = v_sub(a, b); + return v_reduce_sum(v_float32x4((__m128i)a_b.val & __lsx_vreplgr2vr_w(0x7fffffff))); +} + +/** Popcount **/ +#define OPENCV_HAL_IMPL_LSX_POPCOUNT(_Tpvec, _Tp, suffix) \ +inline _Tpvec v_popcount(const _Tp& a) \ +{ return _Tpvec(__lsx_vpcnt_##suffix(a.val)); } + +OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint8x16, v_uint8x16, b); +OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint8x16, v_int8x16, b); +OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint16x8, v_uint16x8, h); +OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint16x8, v_int16x8, h); +OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint32x4, v_uint32x4, w); +OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint32x4, v_int32x4, w); +OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint64x2, v_uint64x2, d); +OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint64x2, v_int64x2, d); + +/** Mask **/ +#define OPENCV_HAL_IMPL_REINTERPRET_INT(ft, tt) \ +inline tt reinterpret_int(ft x) { union {ft l; tt i;} v; v.l = x; return v.i; } +OPENCV_HAL_IMPL_REINTERPRET_INT(uchar, schar) +OPENCV_HAL_IMPL_REINTERPRET_INT(schar, schar) +OPENCV_HAL_IMPL_REINTERPRET_INT(ushort, short) +OPENCV_HAL_IMPL_REINTERPRET_INT(short, short) +OPENCV_HAL_IMPL_REINTERPRET_INT(unsigned, int) +OPENCV_HAL_IMPL_REINTERPRET_INT(int, int) +OPENCV_HAL_IMPL_REINTERPRET_INT(float, int) +OPENCV_HAL_IMPL_REINTERPRET_INT(uint64, int64) +OPENCV_HAL_IMPL_REINTERPRET_INT(int64, int64) +OPENCV_HAL_IMPL_REINTERPRET_INT(double, int64) + +inline int v_signmask(const v_int8x16& a) +{ + __m128i result = __lsx_vmskltz_b(a.val); + return __lsx_vpickve2gr_w(result, 0); +} +inline int v_signmask(const v_uint8x16& a) +{ return v_signmask(v_reinterpret_as_s8(a)) ;} + +inline int v_signmask(const v_int16x8 &a) +{ + __m128i result = __lsx_vmskltz_h(a.val); + return __lsx_vpickve2gr_w(result, 0); +} +inline int v_signmask(const v_uint16x8 &a) +{ return v_signmask(v_reinterpret_as_s16(a)); } + +inline int v_signmask(const v_uint32x4& a) +{ + __m128i result = __lsx_vmskltz_w(a.val); + return __lsx_vpickve2gr_w(result, 0); +} +inline int v_signmask(const v_int32x4& a) +{ return v_signmask(v_reinterpret_as_u32(a)); } + +inline int v_signmask(const v_uint64x2& a) +{ + __m128i result = __lsx_vmskltz_d(a.val); + return __lsx_vpickve2gr_w(result, 0); +} +inline int v_signmask(const v_int64x2& a) +{ return v_signmask(v_reinterpret_as_u64(a)); } + +inline int v_signmask(const v_float32x4& a) +{ return v_signmask(*(v_int32x4*)(&a)); } + +inline int v_signmask(const v_float64x2& a) +{ return v_signmask(*(v_int64x2*)(&a)); } + +inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } +inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } +inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } +inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } +inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } +inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } +inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } + +/** Checks **/ +#define OPENCV_HAL_IMPL_LSX_CHECK(_Tpvec, allmask) \ + inline bool v_check_all(const _Tpvec& a) { return v_signmask(a) == allmask; } \ + inline bool v_check_any(const _Tpvec& a) { return v_signmask(a) != 0; } +OPENCV_HAL_IMPL_LSX_CHECK(v_uint8x16, 65535) +OPENCV_HAL_IMPL_LSX_CHECK(v_int8x16, 65535) +OPENCV_HAL_IMPL_LSX_CHECK(v_uint16x8, 255); +OPENCV_HAL_IMPL_LSX_CHECK(v_int16x8, 255); +OPENCV_HAL_IMPL_LSX_CHECK(v_uint32x4, 15) +OPENCV_HAL_IMPL_LSX_CHECK(v_int32x4, 15) +OPENCV_HAL_IMPL_LSX_CHECK(v_uint64x2, 3) +OPENCV_HAL_IMPL_LSX_CHECK(v_int64x2, 3) +OPENCV_HAL_IMPL_LSX_CHECK(v_float32x4, 15) +OPENCV_HAL_IMPL_LSX_CHECK(v_float64x2, 3) + +///////////// Other math ///////////// + +/** Some frequent operations **/ +#define OPENCV_HAL_IMPL_LSX_MULADD(_Tpvec, suffix) \ + inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ + { return _Tpvec(__lsx_vfmadd_##suffix(a.val, b.val, c.val)); } \ + inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec &b, const _Tpvec& c) \ + { return _Tpvec(__lsx_vfmadd_##suffix(a.val, b.val, c.val)); } \ + inline _Tpvec v_sqrt(const _Tpvec& x) \ + { return _Tpvec(__lsx_vfsqrt_##suffix(x.val)); } \ + inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ + { return v_fma(a, a, v_mul(b, b)); } \ + inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ + { return v_sqrt(v_fma(a, a, v_mul(b, b))); } + +OPENCV_HAL_IMPL_LSX_MULADD(v_float32x4, s) +OPENCV_HAL_IMPL_LSX_MULADD(v_float64x2, d) + +inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ return v_int32x4(__lsx_vmadd_w(c.val, a.val, b.val)); } + +inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ return v_fma(a, b, c); } + +inline v_float32x4 v_invsqrt(const v_float32x4& x) +{ + return v_float32x4(__lsx_vfrsqrt_s(x.val)); +} + +inline v_float64x2 v_invsqrt(const v_float64x2& x) +{ + return v_float64x2(__lsx_vfrsqrt_d(x.val)); +} + +/** Absolute values **/ +#define OPENCV_HAL_IMPL_LSX_ABS(_Tpvec, suffix) \ + inline v_u##_Tpvec v_abs(const v_##_Tpvec& x) \ + { return v_u##_Tpvec(__lsx_vabsd_##suffix(x.val, __lsx_vldi(0))); } + +OPENCV_HAL_IMPL_LSX_ABS(int8x16, b) +OPENCV_HAL_IMPL_LSX_ABS(int16x8, h) +OPENCV_HAL_IMPL_LSX_ABS(int32x4, w) + +inline v_float32x4 v_abs(const v_float32x4& x) +{ return v_float32x4(*((__m128i*)&x) & __lsx_vreplgr2vr_w(0x7fffffff)); } +inline v_float64x2 v_abs(const v_float64x2& x) +{ return v_float64x2(*((__m128i*)&x) & __lsx_vreplgr2vr_d(0x7fffffffffffffff)); } + +/** Absolute difference **/ + +inline v_uint8x16 v_absdiff(const v_uint8x16& a, const v_uint8x16& b) +{ return (v_uint8x16)__lsx_vabsd_bu(a.val, b.val); } +inline v_uint16x8 v_absdiff(const v_uint16x8& a, const v_uint16x8& b) +{ return (v_uint16x8)__lsx_vabsd_hu(a.val, b.val); } +inline v_uint32x4 v_absdiff(const v_uint32x4& a, const v_uint32x4& b) +{ return (v_uint32x4)__lsx_vabsd_wu(a.val, b.val); } + +inline v_uint8x16 v_absdiff(const v_int8x16& a, const v_int8x16& b) +{ return (v_uint8x16)__lsx_vabsd_b(a.val, b.val); } +inline v_uint16x8 v_absdiff(const v_int16x8& a, const v_int16x8& b) +{ return (v_uint16x8)__lsx_vabsd_h(a.val, b.val); } +inline v_uint32x4 v_absdiff(const v_int32x4& a, const v_int32x4& b) +{ return (v_uint32x4)__lsx_vabsd_w(a.val, b.val); } + +inline v_float32x4 v_absdiff(const v_float32x4& a, const v_float32x4& b) +{ return v_abs(v_sub(a, b)); } + +inline v_float64x2 v_absdiff(const v_float64x2& a, const v_float64x2& b) +{ return v_abs(v_sub(a, b)); } + +/** Saturating absolute difference **/ +inline v_int8x16 v_absdiffs(const v_int8x16& a, const v_int8x16& b) +{ + v_int8x16 d = v_sub(a, b); + v_int8x16 m = v_lt(a, b); + return v_sub(v_xor(d, m), m); +} +inline v_int16x8 v_absdiffs(const v_int16x8& a, const v_int16x8& b) +{ return v_sub(v_max(a, b), v_min(a, b)); } + +///////// Conversions ///////// + +/** Rounding **/ +inline v_int32x4 v_round(const v_float32x4& a) +{ return v_int32x4(__lsx_vftint_w_s(a.val)); } + +inline v_int32x4 v_round(const v_float64x2& a) +{ return v_int32x4(__lsx_vftint_w_d(a.val, a.val)); } + +inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) +{ return v_int32x4(__lsx_vftint_w_d(b.val, a.val)); } + +inline v_int32x4 v_trunc(const v_float32x4& a) +{ return v_int32x4(__lsx_vftintrz_w_s(a.val)); } + +inline v_int32x4 v_trunc(const v_float64x2& a) +{ return v_int32x4(__lsx_vftintrz_w_d(a.val, a.val)); } + +inline v_int32x4 v_floor(const v_float32x4& a) +{ return v_int32x4(__lsx_vftintrz_w_s(__m128(__lsx_vfrintrm_s(a.val)))); } + +inline v_int32x4 v_floor(const v_float64x2& a) +{ return v_trunc(v_float64x2(__lsx_vfrintrm_d(a.val))); } + +inline v_int32x4 v_ceil(const v_float32x4& a) +{ return v_int32x4(__lsx_vftintrz_w_s(__m128(__lsx_vfrintrp_s(a.val)))); } + +inline v_int32x4 v_ceil(const v_float64x2& a) +{ return v_trunc(v_float64x2(__lsx_vfrintrp_d(a.val))); } + +/** To float **/ +inline v_float32x4 v_cvt_f32(const v_int32x4& a) +{ return v_float32x4(__lsx_vffint_s_w(a.val)); } + +inline v_float32x4 v_cvt_f32(const v_float64x2& a) +{ return v_float32x4(__lsx_vfcvt_s_d(a.val, a.val)); } + +inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) +{ return v_float32x4(__lsx_vfcvt_s_d(b.val, a.val)); } + +inline v_float64x2 v_cvt_f64(const v_int32x4& a) +{ return v_float64x2(__lsx_vffintl_d_w(a.val)); } + +inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) +{ return v_float64x2(__lsx_vffinth_d_w(a.val)); } + +inline v_float64x2 v_cvt_f64(const v_float32x4& a) +{ return v_float64x2(__lsx_vfcvtl_d_s(a.val)); } + +inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) +{ return v_float64x2(__lsx_vfcvth_d_s(a.val)); } + +inline v_float64x2 v_cvt_f64(const v_int64x2& v) +{ return v_float64x2(__lsx_vffint_d_l(v.val)); } + + +//////////////// Lookup table access //////////////// +inline v_int8x16 v_lut(const schar* tab, const int* idx) +{ + return v_int8x16(_v128_setr_b(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], + tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]], tab[idx[8]], + tab[idx[9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], + tab[idx[14]], tab[idx[15]])); +} + +inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx) +{ + return v_int8x16(_v128_setr_h(*(const short*)(tab + idx[0]), *(const short*)(tab + idx[1]), + *(const short*)(tab + idx[2]), *(const short*)(tab + idx[3]), *(const short*)(tab + idx[4]), + *(const short*)(tab + idx[5]), *(const short*)(tab + idx[6]), *(const short*)(tab + idx[7]))); +} + +inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) +{ + return v_int8x16(_v128_setr_w(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), + *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]))); +} + +inline v_uint8x16 v_lut(const uchar* tab, const int* idx) +{ return v_reinterpret_as_u8(v_lut((const schar*)tab, idx)); } +inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) +{ return v_reinterpret_as_u8(v_lut_pairs((const schar*)tab, idx)); } +inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) +{ return v_reinterpret_as_u8(v_lut_quads((const schar*)tab, idx)); } + +inline v_int16x8 v_lut(const short* tab, const int* idx) +{ + return v_int16x8(_v128_setr_h(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], + tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]])); +} +inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) +{ + return v_int16x8(_v128_setr_w(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), + *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]))); +} +inline v_int16x8 v_lut_quads(const short* tab, const int* idx) +{ + return v_int16x8(_v128_setr_d(*(const int64_t*)(tab + idx[0]), *(const int64_t*)(tab + idx[1]))); +} + +inline v_uint16x8 v_lut(const ushort* tab, const int* idx) +{ return v_reinterpret_as_u16(v_lut((const short *)tab, idx)); } +inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) +{ return v_reinterpret_as_u16(v_lut_pairs((const short *)tab, idx)); } +inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) +{ return v_reinterpret_as_u16(v_lut_quads((const short *)tab, idx)); } + +inline v_int32x4 v_lut(const int* tab, const int* idx) +{ + return v_int32x4(_v128_setr_w(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]])); +} +inline v_int32x4 v_lut_pairs(const int *tab, const int* idx) +{ + return v_int32x4(_v128_setr_d(*(const int64_t*)(tab + idx[0]), *(const int64_t*)(tab + idx[1]))); +} +inline v_int32x4 v_lut_quads(const int* tab, const int* idx) +{ + return v_int32x4(__lsx_vld(tab + idx[0], 0)); +} + +inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((const int *)tab, idx)); } +inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((const int *)tab, idx)); } +inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((const int *)tab, idx)); } + +inline v_int64x2 v_lut(const int64_t* tab, const int *idx) +{ + return v_int64x2(_v128_setr_d(tab[idx[0]], tab[idx[1]])); +} +inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) +{ + return v_int64x2(__lsx_vld(tab + idx[0], 0)); +} + +inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } +inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } + +inline v_float32x4 v_lut(const float* tab, const int* idx) +{ + return v_float32x4(_v128_setr_ps(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]])); +} +inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) +{ + return v_float32x4((__m128)_v128_setr_pd(*(const double*)(tab + idx[0]), *(const double*)(tab + idx[1]))); +} +inline v_float32x4 v_lut_quads(const float* tab, const int* idx) +{ + return v_float32x4((__m128)__lsx_vld(tab + idx[0], 0)); +} + +inline v_float64x2 v_lut(const double* tab, const int* idx) +{ + return v_float64x2(_v128_setr_pd(tab[idx[0]], tab[idx[1]])); +} +inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) +{ + return v_float64x2((__m128d)__lsx_vld(tab + idx[0], 0)); +} + +inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) +{ + int *idx = (int*)&idxvec.val; + return v_lut(tab, idx); +} + +inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) +{ + return v_reinterpret_as_u32(v_lut((const int *)tab, idxvec)); +} + +inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) +{ + const int *idx = (const int*)&idxvec.val; + return v_lut(tab, idx); +} + +inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) +{ + const int *idx = (const int*)&idxvec.val; + return v_lut(tab, idx); +} + +inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) +{ + const int *idx = (const int*)&idxvec.val; + __m128i xy0 = __lsx_vld(tab + idx[0], 0); + __m128i xy1 = __lsx_vld(tab + idx[1], 0); + __m128i xy2 = __lsx_vld(tab + idx[2], 0); + __m128i xy3 = __lsx_vld(tab + idx[3], 0); + __m128i xy01 = __lsx_vilvl_d(xy1, xy0); + __m128i xy23 = __lsx_vilvl_d(xy3, xy2); + __m128i xxyy02 = __lsx_vilvl_w(xy23, xy01); + __m128i xxyy13 = __lsx_vilvh_w(xy23, xy01); + x = v_float32x4((__m128)__lsx_vilvl_w(xxyy13, xxyy02)); + y = v_float32x4((__m128)__lsx_vilvh_w(xxyy13, xxyy02)); +} + +inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) +{ + const int* idx = (const int*)&idxvec.val; + __m128i xy0 = __lsx_vld(tab + idx[0], 0); + __m128i xy1 = __lsx_vld(tab + idx[1], 0); + x = v_float64x2((__m128d)__lsx_vilvl_d(xy1, xy0)); + y = v_float64x2((__m128d)__lsx_vilvh_d(xy1, xy0)); +} + +inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) +{ + return v_int8x16(__lsx_vshuf_b(vec.val, vec.val, + _v128_setr_d(0x0705060403010200, 0x0f0d0e0c0b090a08))); +} +inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) +{ return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } +inline v_int8x16 v_interleave_quads(const v_int8x16& vec) +{ + return v_int8x16(__lsx_vshuf_b(vec.val, vec.val, + _v128_setr_d(0x0703060205010400, 0x0f0b0e0a0d090c08))); +} +inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) +{ return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) +{ + return v_int16x8(__lsx_vshuf_b(vec.val, vec.val, + _v128_setr_d(0x0706030205040100, 0x0f0e0b0a0d0c0908))); +} +inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) +{ return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } +inline v_int16x8 v_interleave_quads(const v_int16x8& vec) +{ + return v_int16x8(__lsx_vshuf_b(vec.val, vec.val, + _v128_setr_d(0x0b0a030209080100, 0x0f0e07060d0c0504))); +} +inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) +{ return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) +{ + return v_int32x4(__lsx_vshuf4i_w(vec.val, 0xd8)); +} +inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) +{ return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } + +inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) +{ return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } + +inline v_int8x16 v_pack_triplets(const v_int8x16& vec) +{ + __m128i zero = __lsx_vldi(0); + return v_int8x16(__lsx_vshuf_b(zero, vec.val, + _v128_set_d(0x1211100f0e0d0c0a, 0x0908060504020100))); +} +inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) +{ return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_pack_triplets(const v_int16x8& vec) +{ + __m128i zero = __lsx_vldi(0); + return v_int16x8(__lsx_vshuf_b(zero, vec.val, + _v128_set_d(0x11100f0e0d0c0b0a, 0x0908050403020100))); +} +inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) +{ return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } +inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } +inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } + +//////////// Matrix operations ///////// + +/////////// Dot Product ///////// + +// 16 >> 32 +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) +{ + __m128i x = a.val, y = b.val; + return v_int32x4(__lsx_vmaddwod_w_h(__lsx_vmulwev_w_h(x, y), x, y)); +} +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ + __m128i x = a.val, y = b.val, z = c.val; + __m128i t = __lsx_vmaddwev_w_h(z, x, y); + return v_int32x4(__lsx_vmaddwod_w_h(t, x, y)); +} + +// 32 >> 64 +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) +{ + __m128i x = a.val, y = b.val; + return v_int64x2(__lsx_vmaddwod_d_w(__lsx_vmulwev_d_w(x, y), x, y)); +} +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ + __m128i x = a.val, y = b.val, z = c.val; + __m128i t = __lsx_vmaddwev_d_w(z, x, y); + return v_int64x2(__lsx_vmaddwod_d_w(t, x, y)); +} + +// 8 >> 32 +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) +{ + __m128i x = a.val, y = b.val; + __m128i even = __lsx_vmulwev_h_bu(x, y); + __m128i odd = __lsx_vmulwod_h_bu(x, y); + __m128i prod0 = __lsx_vhaddw_wu_hu(even, even); + __m128i prod1 = __lsx_vhaddw_wu_hu(odd, odd); + return v_uint32x4(__lsx_vadd_w(prod0, prod1)); +} + +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) +{ return v_add(v_dotprod_expand(a, b), c) ;} + +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) +{ + __m128i x = a.val, y = b.val; + __m128i even = __lsx_vmulwev_h_b(x, y); + __m128i odd = __lsx_vmulwod_h_b(x, y); + __m128i prod0 = __lsx_vhaddw_w_h(even, even); + __m128i prod1 = __lsx_vhaddw_w_h(odd, odd); + return v_int32x4(__lsx_vadd_w(prod0, prod1)); +} +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) +{ + __m128i x = a.val, y = b.val; + __m128i even = __lsx_vmulwev_w_hu(x, y); + __m128i odd = __lsx_vmulwod_w_hu(x, y); + __m128i prod0 = __lsx_vhaddw_du_wu(even, even); + __m128i prod1 = __lsx_vhaddw_du_wu(odd, odd); + return v_uint64x2(__lsx_vadd_d(prod0, prod1)); +} +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) +{ + __m128i x = a.val, y = b.val; + __m128i even = __lsx_vmulwev_w_h(x, y); + __m128i odd = __lsx_vmulwod_w_h(x, y); + __m128i prod0 = __lsx_vhaddw_d_w(even, even); + __m128i prod1 = __lsx_vhaddw_d_w(odd, odd); + return v_int64x2(__lsx_vadd_d(prod0, prod1)); +} +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +//32 >> 64f +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) +{ return v_cvt_f64(v_dotprod(a, b)); } +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + + +///////// Fast Dot Product ////// + +// 16 >> 32 +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) +{ return v_dotprod(a, b); } +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ return v_dotprod(a, b, c); } + +// 32 >> 64 +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) +{ return v_dotprod(a, b); } +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ return v_dotprod(a, b, c); } + +// 8 >> 32 +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) +{ return v_dotprod_expand(a, b); } +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) +{ return v_dotprod_expand(a, b, c); } + +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) +{ return v_dotprod_expand(a, b); } +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) +{ return v_dotprod_expand(a, b, c); } + +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) +{ + __m128i x = a.val, y = b.val; + __m128i even = __lsx_vmulwev_w_hu(x, y); + __m128i odd = __lsx_vmulwod_w_hu(x, y); + __m128i prod0 = __lsx_vhaddw_du_wu(even, even); + __m128i prod1 = __lsx_vhaddw_du_wu(odd, odd); + return v_uint64x2(__lsx_vilvl_d(__lsx_vhaddw_qu_du(prod0, prod0), __lsx_vhaddw_qu_du(prod1, prod1))); +} +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) +{ + __m128i x = a.val, y = b.val; + __m128i prod = __lsx_vmaddwod_w_h(__lsx_vmulwev_w_h(x, y), x, y); + __m128i sign = __lsx_vsrai_w(prod, 31); + __m128i lo = __lsx_vilvl_w(sign, prod); + __m128i hi = __lsx_vilvh_w(sign, prod); + return v_int64x2(__lsx_vadd_d(lo, hi)); +} +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +// 32 >> 64f +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) +{ return v_dotprod_expand(a, b); } +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) +{ return v_dotprod_expand(a, b, c); } + +inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, const v_float32x4& m3) +{ + __m128i x = (__m128i)v.val; + __m128 v0 = __lsx_vfmul_s((__m128)__lsx_vshuf4i_w(x, 0x0), m0.val); + __m128 v1 = __lsx_vfmul_s((__m128)__lsx_vshuf4i_w(x, 0x55), m1.val); + __m128 v2 = __lsx_vfmul_s((__m128)__lsx_vshuf4i_w(x, 0xAA), m2.val); + __m128 v3 = __lsx_vfmul_s((__m128)__lsx_vshuf4i_w(x, 0xFF), m3.val); + + return v_float32x4(__lsx_vfadd_s(__lsx_vfadd_s(v0, v1), __lsx_vfadd_s(v2, v3))); +} + +inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, const v_float32x4& a) +{ + __m128i x = (__m128i)v.val; + __m128 v0 = __lsx_vfmul_s((__m128)__lsx_vshuf4i_w(x, 0x0), m0.val); + __m128 v1 = __lsx_vfmul_s((__m128)__lsx_vshuf4i_w(x, 0x55), m1.val); + __m128 v2 = __lsx_vfmadd_s((__m128)__lsx_vshuf4i_w(x, 0xAA), m2.val, a.val); + + return v_float32x4(__lsx_vfadd_s(__lsx_vfadd_s(v0, v1), v2)); +} + +#define OPENCV_HAL_IMPL_LSX_TRANSPOSE4X4(_Tpvec, cast_from, cast_to) \ + inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ + const _Tpvec& a2, const _Tpvec& a3, \ + _Tpvec& b0, _Tpvec& b1, _Tpvec& b2, _Tpvec& b3) \ + { \ + __m128i t0 = cast_from(__lsx_vilvl_w(a1.val, a0.val)); \ + __m128i t1 = cast_from(__lsx_vilvl_w(a3.val, a2.val)); \ + __m128i t2 = cast_from(__lsx_vilvh_w(a1.val, a0.val)); \ + __m128i t3 = cast_from(__lsx_vilvh_w(a3.val, a2.val)); \ + b0.val = cast_to(__lsx_vilvl_d(t1, t0)); \ + b1.val = cast_to(__lsx_vilvh_d(t1, t0)); \ + b2.val = cast_to(__lsx_vilvl_d(t3, t2)); \ + b3.val = cast_to(__lsx_vilvh_d(t3, t2)); \ + } + +OPENCV_HAL_IMPL_LSX_TRANSPOSE4X4(v_uint32x4, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_LSX_TRANSPOSE4X4(v_int32x4, OPENCV_HAL_NOP, OPENCV_HAL_NOP) + +inline void v_transpose4x4(const v_float32x4& a0, const v_float32x4& a1, + const v_float32x4& a2, const v_float32x4& a3, + v_float32x4& b0, v_float32x4& b1, v_float32x4& b2, v_float32x4& b3) +{ + __m128i vec0 = (__m128i)a0.val, vec1 = (__m128i)a1.val; + __m128i vec2 = (__m128i)a2.val, vec3 = (__m128i)a3.val; + __m128i t0 = __lsx_vilvl_w(vec1, vec0); + __m128i t1 = __lsx_vilvl_w(vec3, vec2); + __m128i t2 = __lsx_vilvh_w(vec1, vec0); + __m128i t3 = __lsx_vilvh_w(vec3, vec2); + b0.val = __m128(__lsx_vilvl_d(t1, t0)); + b1.val = __m128(__lsx_vilvh_d(t1, t0)); + b2.val = __m128(__lsx_vilvl_d(t3, t2)); + b3.val = __m128(__lsx_vilvh_d(t3, t2)); +} + +////////////////// Value reordering //////////////// + +/* Expand */ +#define OPENCV_HAL_IMPL_LSX_EXPAND(_Tpvec, _Tpwvec, _Tp, intrin_lo, intrin_hi) \ + inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ + { \ + b0.val = intrin_lo(a.val, 0); \ + b1.val = intrin_hi(a.val); \ + } \ + inline _Tpwvec v_expand_low(const _Tpvec& a) \ + { return _Tpwvec(intrin_lo(a.val, 0)); } \ + inline _Tpwvec v_expand_high(const _Tpvec& a) \ + { return _Tpwvec(intrin_hi(a.val)); } \ + inline _Tpwvec v_load_expand(const _Tp* ptr) \ + { \ + __m128i a = __lsx_vld(ptr, 0); \ + return _Tpwvec(intrin_lo(a, 0)); \ + } + +OPENCV_HAL_IMPL_LSX_EXPAND(v_uint8x16, v_uint16x8, uchar, __lsx_vsllwil_hu_bu, __lsx_vexth_hu_bu) +OPENCV_HAL_IMPL_LSX_EXPAND(v_int8x16, v_int16x8, schar, __lsx_vsllwil_h_b, __lsx_vexth_h_b) +OPENCV_HAL_IMPL_LSX_EXPAND(v_uint16x8, v_uint32x4, ushort, __lsx_vsllwil_wu_hu, __lsx_vexth_wu_hu) +OPENCV_HAL_IMPL_LSX_EXPAND(v_int16x8, v_int32x4, short, __lsx_vsllwil_w_h, __lsx_vexth_w_h) +OPENCV_HAL_IMPL_LSX_EXPAND(v_uint32x4, v_uint64x2, unsigned, __lsx_vsllwil_du_wu, __lsx_vexth_du_wu) +OPENCV_HAL_IMPL_LSX_EXPAND(v_int32x4, v_int64x2, int, __lsx_vsllwil_d_w, __lsx_vexth_d_w) + +#define OPENCV_HAL_IMPL_LSX_EXPAND_Q(_Tpvec, _Tp, intrin_lo, intrin_hi) \ + inline _Tpvec v_load_expand_q(const _Tp* ptr) \ + { \ + __m128i a = __lsx_vld(ptr, 0); \ + __m128i b = intrin_lo(a, 0); \ + return _Tpvec(intrin_hi(b, 0)); \ + } + +OPENCV_HAL_IMPL_LSX_EXPAND_Q(v_uint32x4, uchar, __lsx_vsllwil_hu_bu, __lsx_vsllwil_wu_hu) +OPENCV_HAL_IMPL_LSX_EXPAND_Q(v_int32x4, schar, __lsx_vsllwil_h_b, __lsx_vsllwil_w_h) + +/* pack */ +// 16 +inline v_int8x16 v_pack(const v_int16x8& a, const v_int16x8& b) +{ return v_int8x16(_lsx_packs_h(a.val, b.val)); } + +inline v_uint8x16 v_pack(const v_uint16x8& a, const v_uint16x8& b) +{ return v_uint8x16(__lsx_vssrlrni_bu_h(b.val, a.val, 0)); } + +inline v_uint8x16 v_pack_u(const v_int16x8& a, const v_int16x8& b) +{ return v_uint8x16(_lsx_packus_h(a.val, b.val)); } + +inline void v_pack_store(schar* ptr, const v_int16x8& a) +{ v_store_low(ptr, v_pack(a, a)); } + +inline void v_pack_store(uchar* ptr, const v_uint16x8& a) +{ v_store_low(ptr, v_pack(a, a)); } + +inline void v_pack_u_store(uchar* ptr, const v_int16x8& a) +{ v_store_low(ptr, v_pack_u(a, a)); } + +template inline +v_uint8x16 v_rshr_pack(const v_uint16x8& a, const v_uint16x8& b) +{ return v_uint8x16(__lsx_vssrlrni_bu_h(b.val, a.val, n)); } + +template inline +void v_rshr_pack_store(uchar* ptr, const v_uint16x8& a) +{ __lsx_vstelm_d(__lsx_vssrlrni_bu_h(a.val, a.val, n), ptr, 0, 0); } + +template inline +v_uint8x16 v_rshr_pack_u(const v_int16x8& a, const v_int16x8& b) +{ return v_uint8x16(__lsx_vssrarni_bu_h(b.val, a.val, n)); } + +template inline +void v_rshr_pack_u_store(uchar* ptr, const v_int16x8& a) +{ __lsx_vstelm_d(__lsx_vssrarni_bu_h(a.val, a.val, n), ptr, 0, 0); } + +template inline +v_int8x16 v_rshr_pack(const v_int16x8& a, const v_int16x8& b) +{ return v_int8x16(__lsx_vssrarni_b_h(b.val, a.val, n)); } + +template inline +void v_rshr_pack_store(schar* ptr, const v_int16x8& a) +{ __lsx_vstelm_d(__lsx_vssrarni_b_h(a.val, a.val, n), ptr, 0, 0); } + +//32 +inline v_int16x8 v_pack(const v_int32x4& a, const v_int32x4& b) +{ return v_int16x8(__lsx_vssrarni_h_w(b.val, a.val, 0)); } + +inline v_uint16x8 v_pack(const v_uint32x4& a, const v_uint32x4& b) +{ return v_uint16x8(__lsx_vssrlrni_hu_w(b.val, a.val, 0)); } + +inline v_uint16x8 v_pack_u(const v_int32x4& a, const v_int32x4& b) +{ return v_uint16x8(__lsx_vssrarni_hu_w(b.val, a.val, 0)); } + +inline void v_pack_store(short* ptr, const v_int32x4& a) +{ v_store_low(ptr, v_pack(a, a)); } + +inline void v_pack_store(ushort *ptr, const v_uint32x4& a) +{ __lsx_vstelm_d(__lsx_vssrlrni_hu_w(a.val, a.val, 0), ptr, 0, 0); } + +inline void v_pack_u_store(ushort* ptr, const v_int32x4& a) +{ __lsx_vstelm_d(__lsx_vssrarni_hu_w(a.val, a.val, 0), ptr, 0, 0); } + +template inline +v_uint16x8 v_rshr_pack(const v_uint32x4& a, const v_uint32x4& b) +{ return v_uint16x8(__lsx_vssrlrni_hu_w(b.val, a.val, n)); } + +template inline +void v_rshr_pack_store(ushort* ptr, const v_uint32x4& a) +{ __lsx_vstelm_d(__lsx_vssrlrni_hu_w(a.val, a.val, n), ptr, 0, 0); } + +template inline +v_uint16x8 v_rshr_pack_u(const v_int32x4& a, const v_int32x4& b) +{ return v_uint16x8(__lsx_vssrarni_hu_w(b.val, a.val, n)); } + +template inline +void v_rshr_pack_u_store(ushort* ptr, const v_int32x4& a) +{ __lsx_vstelm_d(__lsx_vssrarni_hu_w(a.val, a.val, n), ptr, 0, 0); } + +template inline +v_int16x8 v_rshr_pack(const v_int32x4& a, const v_int32x4& b) +{ return v_int16x8(__lsx_vssrarni_h_w(b.val, a.val, n)); } + +template inline +void v_rshr_pack_store(short* ptr, const v_int32x4& a) +{ __lsx_vstelm_d(__lsx_vssrarni_h_w(a.val, a.val, n), ptr, 0, 0); } + +// 64 +// Non-saturaing pack +inline v_uint32x4 v_pack(const v_uint64x2& a, const v_uint64x2& b) +{ return v_uint32x4(__lsx_vpickev_w(b.val, a.val)); } + +inline v_int32x4 v_pack(const v_int64x2& a, const v_int64x2& b) +{ return v_reinterpret_as_s32(v_pack(v_reinterpret_as_u64(a), v_reinterpret_as_u64(b))); } + +inline void v_pack_store(unsigned* ptr, const v_uint64x2& a) +{ __lsx_vstelm_d(__lsx_vshuf4i_w(a.val, 0x08), ptr, 0, 0); } + +inline void v_pack_store(int *ptr, const v_int64x2& a) +{ v_pack_store((unsigned*)ptr, v_reinterpret_as_u64(a)); } + +template inline +v_uint32x4 v_rshr_pack(const v_uint64x2& a, const v_uint64x2& b) +{ return v_uint32x4(__lsx_vsrlrni_w_d(b.val, a.val, n)); } + +template inline +void v_rshr_pack_store(unsigned* ptr, const v_uint64x2& a) +{ __lsx_vstelm_d(__lsx_vsrlrni_w_d(a.val, a.val, n), ptr, 0, 0); } + +template inline +v_int32x4 v_rshr_pack(const v_int64x2& a, const v_int64x2& b) +{ return v_int32x4(__lsx_vsrarni_w_d(b.val, a.val, n)); } + +template inline +void v_rshr_pack_store(int* ptr, const v_int64x2& a) +{ __lsx_vstelm_d(__lsx_vsrarni_w_d(a.val, a.val, n), ptr, 0, 0); } + +// pack boolean +inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) +{ return v_uint8x16(__lsx_vssrarni_b_h(b.val, a.val, 0)); } + +inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, + const v_uint32x4& c, const v_uint32x4& d) +{ + __m128i ab = __lsx_vssrarni_h_w(b.val, a.val, 0); + __m128i cd = __lsx_vssrarni_h_w(d.val, c.val, 0); + return v_uint8x16(__lsx_vssrarni_b_h(cd, ab, 0)); +} + +inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, + const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, + const v_uint64x2& g, const v_uint64x2& h) +{ + __m128i ab = __lsx_vssrarni_w_d(b.val, a.val, 0); + __m128i cd = __lsx_vssrarni_w_d(d.val, c.val, 0); + __m128i ef = __lsx_vssrarni_w_d(f.val, e.val, 0); + __m128i gh = __lsx_vssrarni_w_d(h.val, g.val, 0); + + __m128i abcd = __lsx_vssrarni_h_w(cd, ab, 0); + __m128i efgh = __lsx_vssrarni_h_w(gh, ef, 0); + return v_uint8x16(__lsx_vssrarni_b_h(efgh, abcd, 0)); +} + +/* Recombine */ +// its up there with load and store operations + +/* Extract */ +#define OPENCV_HAL_IMPL_LSX_EXTRACT(_Tpvec) \ + template \ + inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \ + { return v_rotate_right(a, b); } + +OPENCV_HAL_IMPL_LSX_EXTRACT(v_uint8x16) +OPENCV_HAL_IMPL_LSX_EXTRACT(v_int8x16) +OPENCV_HAL_IMPL_LSX_EXTRACT(v_uint16x8) +OPENCV_HAL_IMPL_LSX_EXTRACT(v_int16x8) +OPENCV_HAL_IMPL_LSX_EXTRACT(v_uint32x4) +OPENCV_HAL_IMPL_LSX_EXTRACT(v_int32x4) +OPENCV_HAL_IMPL_LSX_EXTRACT(v_uint64x2) +OPENCV_HAL_IMPL_LSX_EXTRACT(v_int64x2) +OPENCV_HAL_IMPL_LSX_EXTRACT(v_float32x4) +OPENCV_HAL_IMPL_LSX_EXTRACT(v_float64x2) + +#define OPENCV_HAL_IMPL_LSX_EXTRACT_N(_Tpvec, _Twvec, intrin) \ +template \ +inline _Twvec v_extract_n(const _Tpvec& a) \ +{ return (_Twvec)intrin(a.val, i); } + +OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_uint8x16, uchar, __lsx_vpickve2gr_b) +OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_int8x16, schar, __lsx_vpickve2gr_b) +OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_uint16x8, ushort, __lsx_vpickve2gr_h) +OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_int16x8, short, __lsx_vpickve2gr_h) +OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_uint32x4, uint, __lsx_vpickve2gr_w) +OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_int32x4, int, __lsx_vpickve2gr_w) +OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_uint64x2, uint64, __lsx_vpickve2gr_d) +OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_int64x2, int64, __lsx_vpickve2gr_d) + +template +inline float v_extract_n(const v_float32x4& v) +{ + union { uint iv; float fv; } d; + d.iv = __lsx_vpickve2gr_w(v.val, i); + return d.fv; +} + +template +inline double v_extract_n(const v_float64x2& v) +{ + union { uint64 iv; double dv; } d; + d.iv = __lsx_vpickve2gr_d(v.val, i); + return d.dv; +} + +template +inline v_uint32x4 v_broadcast_element(const v_uint32x4& a) +{ return v_uint32x4(__lsx_vreplvei_w(a.val, i)); } + +template +inline v_int32x4 v_broadcast_element(const v_int32x4& a) +{ return v_int32x4(__lsx_vreplvei_w(a.val, i)); } + +template +inline v_float32x4 v_broadcast_element(const v_float32x4& a) +{ return v_float32x4((__m128)__lsx_vreplvei_w((__m128i)a.val, i)); } + +/////////////////// load deinterleave ////////////////////////////// + +inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b) +{ + __m128i t0 = __lsx_vld(ptr, 0); + __m128i t1 = __lsx_vld(ptr, 16); + + a.val = __lsx_vpickev_b(t1, t0); + b.val = __lsx_vpickod_b(t1, t0); +} + +inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b) +{ + __m128i t0 = __lsx_vld(ptr, 0); + __m128i t1 = __lsx_vld(ptr, 16); + a.val = __lsx_vpickev_h(t1, t0); + b.val = __lsx_vpickod_h(t1, t0); +} + +inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b) +{ + __m128i t0 = __lsx_vld(ptr, 0); + __m128i t1 = __lsx_vld(ptr, 16); + a.val = __lsx_vpickev_w(t1, t0); + b.val = __lsx_vpickod_w(t1, t0); +} + +inline void v_load_deinterleave(const uint64* ptr, v_uint64x2& a, v_uint64x2& b) +{ + __m128i t0 = __lsx_vld(ptr, 0); + __m128i t1 = __lsx_vld(ptr, 16); + a.val = __lsx_vilvl_d(t1, t0); + b.val = __lsx_vilvh_d(t1, t0); +} + +inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c) +{ + __m128i t0 = __lsx_vld(ptr, 0); + __m128i t1 = __lsx_vld(ptr, 16); + __m128i t2 = __lsx_vld(ptr, 32); + const __m128i shuff0 = _v128_setr_b(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0); + const __m128i shuff1 = _v128_setr_b(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); + __m128i a0 = __lsx_vbitsel_v(t0, t1, shuff0); + __m128i b0 = __lsx_vbitsel_v(t1, t0, shuff1); + __m128i c0 = __lsx_vbitsel_v(t1, t0, shuff0); + const __m128i shuff_a = _v128_setr_b(0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 17, 20, 23, 26, 29); + const __m128i shuff_b = _v128_setr_b(1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30); + const __m128i shuff_c = _v128_setr_b(2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31); + + a.val = __lsx_vshuf_b(t2, a0, shuff_a); + b.val = __lsx_vshuf_b(t2, b0, shuff_b); + c.val = __lsx_vshuf_b(t2, c0, shuff_c); +} + +inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c) +{ + __m128i t0 = __lsx_vld(ptr, 0); + __m128i t1 = __lsx_vld(ptr, 16); + __m128i t2 = __lsx_vld(ptr, 32); + const __m128i shuff0 = _v128_setr_h(0, 0, -1, 0, 0, -1, 0, 0); + const __m128i shuff1 = _v128_setr_h(0, -1, 0, 0, -1, 0, 0, -1); + + __m128i a0 = __lsx_vbitsel_v(t0, t1, shuff1); + __m128i b0 = __lsx_vbitsel_v(t0, t1, shuff0); + __m128i c0 = __lsx_vbitsel_v(t1, t0, shuff0); + + const __m128i shuff_a = _v128_setr_b(0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 20, 21, 26, 27); + const __m128i shuff_b = _v128_setr_b(2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 16, 17, 22, 23, 28, 29); + const __m128i shuff_c = _v128_setr_b(4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 18, 19, 24, 25, 30, 31); + + a.val = __lsx_vshuf_b(t2, a0, shuff_a); + b.val = __lsx_vshuf_b(t2, b0, shuff_b); + c.val = __lsx_vshuf_b(t2, c0, shuff_c); +} + +inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c) +{ + __m128i t0 = __lsx_vld(ptr, 0); + __m128i t1 = __lsx_vld(ptr, 16); + __m128i t2 = __lsx_vld(ptr, 32); + + __m128i a0 = __lsx_vpermi_w(t1, t0, 0xAC); + __m128i b0 = __lsx_vpermi_w(t1, t0, 0xC5); + __m128i c0 = __lsx_vpermi_w(t1, t0, 0x5A); + + a.val = __lsx_vextrins_w(a0, t2, 0x31); + b0 = __lsx_vshuf4i_w(b0, 0x38); + c0 = __lsx_vshuf4i_w(c0, 0x8); + b.val = __lsx_vextrins_w(b0, t2, 0x32); + c.val = __lsx_vpermi_w(t2, c0, 0xC4); +} + +inline void v_load_deinterleave(const uint64* ptr, v_uint64x2& a, v_uint64x2& b, v_uint64x2& c) +{ + __m128i t0 = __lsx_vld(ptr, 0); + __m128i t1 = __lsx_vld(ptr, 16); + __m128i t2 = __lsx_vld(ptr, 32); + + a.val = __lsx_vshuf4i_d(t0, t1, 0xC); + b.val = __lsx_vshuf4i_d(t0, t2, 0x9); + c.val = __lsx_vshuf4i_d(t1, t2, 0xC); +} + +inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c, v_uint8x16& d) +{ + __m128i t0 = __lsx_vld(ptr, 0); + __m128i t1 = __lsx_vld(ptr, 16); + __m128i t2 = __lsx_vld(ptr, 32); + __m128i t3 = __lsx_vld(ptr, 48); + + __m128i ac_lo = __lsx_vpickev_b(t1, t0); + __m128i bd_lo = __lsx_vpickod_b(t1, t0); + __m128i ac_hi = __lsx_vpickev_b(t3, t2); + __m128i bd_hi = __lsx_vpickod_b(t3, t2); + + a.val = __lsx_vpickev_b(ac_hi, ac_lo); + c.val = __lsx_vpickod_b(ac_hi, ac_lo); + b.val = __lsx_vpickev_b(bd_hi, bd_lo); + d.val = __lsx_vpickod_b(bd_hi, bd_lo); +} + +inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c, v_uint16x8& d) +{ + __m128i t0 = __lsx_vld(ptr, 0); + __m128i t1 = __lsx_vld(ptr, 16); + __m128i t2 = __lsx_vld(ptr, 32); + __m128i t3 = __lsx_vld(ptr, 48); + + __m128i ac_lo = __lsx_vpickev_h(t1, t0); + __m128i bd_lo = __lsx_vpickod_h(t1, t0); + __m128i ac_hi = __lsx_vpickev_h(t3, t2); + __m128i bd_hi = __lsx_vpickod_h(t3, t2); + + a.val = __lsx_vpickev_h(ac_hi, ac_lo); + c.val = __lsx_vpickod_h(ac_hi, ac_lo); + b.val = __lsx_vpickev_h(bd_hi, bd_lo); + d.val = __lsx_vpickod_h(bd_hi, bd_lo); +} + +inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c, v_uint32x4& d) +{ + __m128i p0 = __lsx_vld(ptr, 0); + __m128i p1 = __lsx_vld(ptr, 16); + __m128i p2 = __lsx_vld(ptr, 32); + __m128i p3 = __lsx_vld(ptr, 48); + + __m128i t0 = __lsx_vilvl_w(p1, p0); + __m128i t1 = __lsx_vilvl_w(p3, p2); + __m128i t2 = __lsx_vilvh_w(p1, p0); + __m128i t3 = __lsx_vilvh_w(p3, p2); + a.val = __lsx_vilvl_d(t1, t0); + b.val = __lsx_vilvh_d(t1, t0); + c.val = __lsx_vilvl_d(t3, t2); + d.val = __lsx_vilvh_d(t3, t2); +} + +inline void v_load_deinterleave(const uint64* ptr, v_uint64x2& a, v_uint64x2& b, v_uint64x2& c, v_uint64x2& d) +{ + __m128i t0 = __lsx_vld(ptr, 0); + __m128i t1 = __lsx_vld(ptr, 16); + __m128i t2 = __lsx_vld(ptr, 32); + __m128i t3 = __lsx_vld(ptr, 48); + + a.val = __lsx_vilvl_d(t2, t0); + b.val = __lsx_vilvh_d(t2, t0); + c.val = __lsx_vilvl_d(t3, t1); + d.val = __lsx_vilvh_d(t3, t1); +} + +////////////////////////// store interleave //////////////////////////////// + +inline void v_store_interleave(uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + __m128i v0 = __lsx_vilvl_b(b.val, a.val); + __m128i v1 = __lsx_vilvh_b(b.val, a.val); + + __lsx_vst(v0, ptr, 0); + __lsx_vst(v1, ptr, 16); +} + +inline void v_store_interleave(ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + __m128i v0 = __lsx_vilvl_h(b.val, a.val); + __m128i v1 = __lsx_vilvh_h(b.val, a.val); + + __lsx_vst(v0, ptr, 0); + __lsx_vst(v1, ptr, 16); +} + +inline void v_store_interleave(unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + __m128i v0 = __lsx_vilvl_w(b.val, a.val); + __m128i v1 = __lsx_vilvh_w(b.val, a.val); + + __lsx_vst(v0, ptr, 0); + __lsx_vst(v1, ptr, 16); +} + +inline void v_store_interleave(uint64* ptr, const v_uint64x2& a, const v_uint64x2& b, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + __m128i v0 = __lsx_vilvl_d(b.val, a.val); + __m128i v1 = __lsx_vilvh_d(b.val, a.val); + + __lsx_vst(v0, ptr, 0); + __lsx_vst(v1, ptr, 16); +} + +inline void v_store_interleave(uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, const v_uint8x16& c, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + __m128i ab_lo = __lsx_vilvl_b(b.val, a.val); + __m128i ab_hi = __lsx_vilvh_b(b.val, a.val); + __m128i v_c = c.val; + const __m128i shuff0 = _v128_setr_b(0, 1, 16, 2, 3, 17, 4, 5, 18, 6, 7, 19, 8, 9, 20, 10); + const __m128i shuff1 = _v128_setr_b(11, 21, 12, 13, 22, 14, 15, 23, 0, 0, 0, 0, 0, 0, 0, 0); + const __m128i shuff2 = _v128_setr_b(0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 24, 18, 19, 25, 20, 21); + const __m128i shuff3 = _v128_setr_b(26, 6, 7, 27, 8, 9, 28, 10, 11, 29, 12, 13, 30, 14, 15, 31); + __m128i abc = __lsx_vpermi_w(v_c, ab_hi, 0xE4); + + __m128i dst0 = __lsx_vshuf_b(v_c, ab_lo, shuff0); + __m128i dst1 = __lsx_vshuf_b(v_c, ab_lo, shuff1); + __m128i dst2 = __lsx_vshuf_b(v_c, ab_hi, shuff3); + dst1 = __lsx_vshuf_b(abc, dst1, shuff2); + + __lsx_vst(dst0, ptr, 0); + __lsx_vst(dst1, ptr, 16); + __lsx_vst(dst2, ptr, 32); +} + +inline void v_store_interleave(ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, const v_uint16x8& c, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + __m128i ab_lo = __lsx_vilvl_h(b.val, a.val); + __m128i ab_hi = __lsx_vilvh_h(b.val, a.val); + __m128i v_c = c.val; + const __m128i shuff0 = _v128_setr_b(0, 1, 2, 3, 16, 17, 4, 5, 6, 7, 18, 19, 8, 9, 10, 11); + const __m128i shuff1 = _v128_setr_b(20, 21, 12, 13, 14, 15, 22, 23, 0, 0, 0, 0, 0, 0, 0, 0); + const __m128i shuff2 = _v128_setr_b(0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 24, 25, 20, 21); + const __m128i shuff3 = _v128_setr_b(6, 7, 26, 27, 8, 9, 10, 11, 28, 29, 12, 13, 14, 15, 30, 31); + __m128i abc = __lsx_vpermi_w(v_c, ab_hi, 0xE4); + + __m128i dst0 = __lsx_vshuf_b(v_c, ab_lo, shuff0); + __m128i dst1 = __lsx_vshuf_b(v_c, ab_lo, shuff1); + __m128i dst2 = __lsx_vshuf_b(v_c, ab_hi, shuff3); + dst1 = __lsx_vshuf_b(abc, dst1, shuff2); + + __lsx_vst(dst0, ptr, 0); + __lsx_vst(dst1, ptr, 16); + __lsx_vst(dst2, ptr, 32); +} + +inline void v_store_interleave(unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, const v_uint32x4& c, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + __m128i v_c = c.val; + __m128i ab_lo = __lsx_vilvl_w(b.val, a.val); //a0 b0 a1 b1 + __m128i ab_hi = __lsx_vilvh_w(b.val, a.val); //a2 b2 a3 b3 + __m128i bc_od = __lsx_vpackod_w(v_c, b.val); // b1 c1 b3 c3 + + __m128i dst0 = __lsx_vshuf4i_w(ab_lo, 0xB4); //a0 b0 b1 a1 + __m128i dst1 = __lsx_vilvl_d(ab_hi, bc_od); //b1 c1 a2 b2 + __m128i dst2 = __lsx_vpermi_w(bc_od, ab_hi, 0xE8); //a2, a3, b3, c3 + + dst0 = __lsx_vextrins_w(dst0, v_c, 0x20); + dst2 = __lsx_vextrins_w(dst2, v_c, 0x2); + __lsx_vst(dst0, ptr, 0); //a0 b0 c0 a1 + __lsx_vst(dst1, ptr, 16); //b1 c1 a2 b2 + __lsx_vst(dst2, ptr, 32); //c2 a3 b3 c3 +} + +inline void v_store_interleave(uint64* ptr, const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + __m128i dst0 = __lsx_vilvl_d(b.val, a.val); + __m128i dst1 = __lsx_vpermi_w(a.val, c.val, 0xE4); + __m128i dst2 = __lsx_vilvh_d(c.val, b.val); + + __lsx_vst(dst0, ptr, 0); + __lsx_vst(dst1, ptr, 16); + __lsx_vst(dst2, ptr, 32); +} + +inline void v_store_interleave(uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, + const v_uint8x16& c, const v_uint8x16& d, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + __m128i ab_lo = __lsx_vilvl_b(b.val, a.val); + __m128i ab_hi = __lsx_vilvh_b(b.val, a.val); + __m128i cd_lo = __lsx_vilvl_b(d.val, c.val); + __m128i cd_hi = __lsx_vilvh_b(d.val, c.val); + + __m128i dst0 = __lsx_vilvl_h(cd_lo, ab_lo); + __m128i dst1 = __lsx_vilvh_h(cd_lo, ab_lo); + __m128i dst2 = __lsx_vilvl_h(cd_hi, ab_hi); + __m128i dst3 = __lsx_vilvh_h(cd_hi, ab_hi); + + __lsx_vst(dst0, ptr, 0); + __lsx_vst(dst1, ptr, 16); + __lsx_vst(dst2, ptr, 32); + __lsx_vst(dst3, ptr, 48); +} + +inline void v_store_interleave(ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, + const v_uint16x8& c, const v_uint16x8& d, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + __m128i ab_lo = __lsx_vilvl_h(b.val, a.val); + __m128i ab_hi = __lsx_vilvh_h(b.val, a.val); + __m128i cd_lo = __lsx_vilvl_h(d.val, c.val); + __m128i cd_hi = __lsx_vilvh_h(d.val, c.val); + + __m128i dst0 = __lsx_vilvl_w(cd_lo, ab_lo); + __m128i dst1 = __lsx_vilvh_w(cd_lo, ab_lo); + __m128i dst2 = __lsx_vilvl_w(cd_hi, ab_hi); + __m128i dst3 = __lsx_vilvh_w(cd_hi, ab_hi); + + __lsx_vst(dst0, ptr, 0); + __lsx_vst(dst1, ptr, 16); + __lsx_vst(dst2, ptr, 32); + __lsx_vst(dst3, ptr, 48); +} + +inline void v_store_interleave(unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, + const v_uint32x4& c, const v_uint32x4& d, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + __m128i ab_lo = __lsx_vilvl_w(b.val, a.val); + __m128i ab_hi = __lsx_vilvh_w(b.val, a.val); + __m128i cd_lo = __lsx_vilvl_w(d.val, c.val); + __m128i cd_hi = __lsx_vilvh_w(d.val, c.val); + + __m128i dst0 = __lsx_vilvl_d(cd_lo, ab_lo); + __m128i dst1 = __lsx_vilvh_d(cd_lo, ab_lo); + __m128i dst2 = __lsx_vilvl_d(cd_hi, ab_hi); + __m128i dst3 = __lsx_vilvh_d(cd_hi, ab_hi); + + __lsx_vst(dst0, ptr, 0); + __lsx_vst(dst1, ptr, 16); + __lsx_vst(dst2, ptr, 32); + __lsx_vst(dst3, ptr, 48); +} + +inline void v_store_interleave(uint64* ptr, const v_uint64x2& a, const v_uint64x2& b, + const v_uint64x2& c, const v_uint64x2& d, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + __m128i dst0 = __lsx_vilvl_d(b.val, a.val); + __m128i dst2 = __lsx_vilvh_d(b.val, a.val); + __m128i dst1 = __lsx_vilvl_d(d.val, c.val); + __m128i dst3 = __lsx_vilvh_d(d.val, c.val); + + __lsx_vst(dst0, ptr, 0); + __lsx_vst(dst1, ptr, 16); + __lsx_vst(dst2, ptr, 32); + __lsx_vst(dst3, ptr, 48); +} + +#define OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(_Tpvec0, _Tp0, suffix0, _Tpvec1, _Tp1, suffix1) \ +inline void v_load_deinterleave(const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0) \ +{ \ + _Tpvec1 a1, b1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ +} \ +inline void v_load_deinterleave(const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0) \ +{ \ + _Tpvec1 a1, b1, c1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ + c0 = v_reinterpret_as_##suffix0(c1); \ +} \ +inline void v_load_deinterleave(const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, \ + _Tpvec0& c0, _Tpvec0& d0) \ +{ \ + _Tpvec1 a1, b1, c1, d1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1, d1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ + c0 = v_reinterpret_as_##suffix0(c1); \ + d0 = v_reinterpret_as_##suffix0(d1); \ +} \ +inline void v_store_interleave(_Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + v_store_interleave((_Tp1*)ptr, a1, b1); \ +} \ +inline void v_store_interleave(_Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, const _Tpvec0& c0,\ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, c1); \ +} \ +inline void v_store_interleave(_Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + const _Tpvec0& c0, const _Tpvec0& d0, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ + _Tpvec1 d1 = v_reinterpret_as_##suffix1(d0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, c1, d1); \ +} + +OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(v_int8x16, schar, s8, v_uint8x16, uchar, u8) +OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(v_int16x8, short, s16, v_uint16x8, ushort, u16) +OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(v_int32x4, int, s32, v_uint32x4, unsigned, u32) +OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(v_float32x4, float, f32, v_uint32x4, unsigned, u32) +OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(v_int64x2, int64, s64, v_uint64x2, uint64, u64) +OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(v_float64x2, double, f64, v_uint64x2, uint64, u64) + +// +// FP16 +// + +inline v_float32x4 v_load_expand(const hfloat* ptr) +{ +#if CV_FP16 + return v_float32x4(__lsx_vfcvtl_s_h((__m128)__lsx_vld(ptr, 0))); +#else + float CV_DECL_ALIGNED(32) buf[4]; + for (int i = 0; i < 4; i++) + buf[i] = (float)ptr[i]; + return v_float32x4((__m128)__lsx_vld(buf, 0)); +#endif +} + +inline void v_pack_store(hfloat* ptr, const v_float32x4& a) +{ +#if CV_FP16 + __m128i res = (__m218i)__lsx_vfcvt_h_s(a.val, a.val); + __lsx_vstelm_d(res, ptr, 0, 0); +#else + float CV_DECL_ALIGNED(32) buf[4]; + v_store_aligned(buf, a); + for (int i = 0; i < 4; i++) + ptr[i] = hfloat(buf[i]); +#endif +} + +// +// end of FP16 +// + +inline void v_cleanup() {} + +#include "intrin_math.hpp" +inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } +inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } +inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } +inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } +inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } +inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } + +inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } +inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } +inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } +inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } +inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} // cv:: + +#endif // OPENCV_HAL_INTRIN_LSX_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_math.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_math.hpp index b7e649e744..b6912a7a8a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_math.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_math.hpp @@ -1,687 +1,687 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - - -/* Universal Intrinsics implementation of sin, cos, exp and log - - Inspired by Intel Approximate Math library, and based on the - corresponding algorithms of the cephes math library -*/ - -/* Copyright (C) 2010,2011 RJVB - extensions */ -/* Copyright (C) 2011 Julien Pommier - - 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. - - (this is the zlib license) -*/ -#ifndef OPENCV_HAL_INTRIN_MATH_HPP -#define OPENCV_HAL_INTRIN_MATH_HPP - -//! @name Exponential -//! @{ -// Implementation is the same as float32 vector. -template -inline _TpVec16F v_exp_default_16f(const _TpVec16F &x) { - const _TpVec16F _vexp_lo_f16 = v_setall_<_TpVec16F>(-10.7421875f); - const _TpVec16F _vexp_hi_f16 = v_setall_<_TpVec16F>(11.f); - const _TpVec16F _vexp_half_fp16 = v_setall_<_TpVec16F>(0.5f); - const _TpVec16F _vexp_one_fp16 = v_setall_<_TpVec16F>(1.f); - const _TpVec16F _vexp_LOG2EF_f16 = v_setall_<_TpVec16F>(1.44269504088896341f); - const _TpVec16F _vexp_C1_f16 = v_setall_<_TpVec16F>(-6.93359375E-1f); - const _TpVec16F _vexp_C2_f16 = v_setall_<_TpVec16F>(2.12194440E-4f); - const _TpVec16F _vexp_p0_f16 = v_setall_<_TpVec16F>(1.9875691500E-4f); - const _TpVec16F _vexp_p1_f16 = v_setall_<_TpVec16F>(1.3981999507E-3f); - const _TpVec16F _vexp_p2_f16 = v_setall_<_TpVec16F>(8.3334519073E-3f); - const _TpVec16F _vexp_p3_f16 = v_setall_<_TpVec16F>(4.1665795894E-2f); - const _TpVec16F _vexp_p4_f16 = v_setall_<_TpVec16F>(1.6666665459E-1f); - const _TpVec16F _vexp_p5_f16 = v_setall_<_TpVec16F>(5.0000001201E-1f); - - _TpVec16F _vexp_, _vexp_x, _vexp_y, _vexp_xx; - _TpVec16S _vexp_mm; - const _TpVec16S _vexp_bias_s16 = v_setall_<_TpVec16S>((short)0xf); - - // compute exponential of x - _vexp_x = v_max(x, _vexp_lo_f16); - _vexp_x = v_min(_vexp_x, _vexp_hi_f16); - - _vexp_ = v_fma(_vexp_x, _vexp_LOG2EF_f16, _vexp_half_fp16); - _vexp_mm = v_floor(_vexp_); - _vexp_ = v_cvt_f16(_vexp_mm); - _vexp_mm = v_add(_vexp_mm, _vexp_bias_s16); - _vexp_mm = v_shl(_vexp_mm, 10); - - _vexp_x = v_fma(_vexp_, _vexp_C1_f16, _vexp_x); - _vexp_x = v_fma(_vexp_, _vexp_C2_f16, _vexp_x); - _vexp_xx = v_mul(_vexp_x, _vexp_x); - - _vexp_y = v_fma(_vexp_x, _vexp_p0_f16, _vexp_p1_f16); - _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p2_f16); - _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p3_f16); - _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p4_f16); - _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p5_f16); - - _vexp_y = v_fma(_vexp_y, _vexp_xx, _vexp_x); - _vexp_y = v_add(_vexp_y, _vexp_one_fp16); - _vexp_y = v_mul(_vexp_y, v_reinterpret_as_f16(_vexp_mm)); - - // exp(NAN) -> NAN - _TpVec16F mask_not_nan = v_not_nan(x); - return v_select(mask_not_nan, _vexp_y, v_reinterpret_as_f16(v_setall_<_TpVec16S>((short)0x7e00))); -} - -template -inline _TpVec32F v_exp_default_32f(const _TpVec32F &x) { - const _TpVec32F _vexp_lo_f32 = v_setall_<_TpVec32F>(-88.3762626647949f); - const _TpVec32F _vexp_hi_f32 = v_setall_<_TpVec32F>(89.f); - const _TpVec32F _vexp_half_fp32 = v_setall_<_TpVec32F>(0.5f); - const _TpVec32F _vexp_one_fp32 = v_setall_<_TpVec32F>(1.f); - const _TpVec32F _vexp_LOG2EF_f32 = v_setall_<_TpVec32F>(1.44269504088896341f); - const _TpVec32F _vexp_C1_f32 = v_setall_<_TpVec32F>(-6.93359375E-1f); - const _TpVec32F _vexp_C2_f32 = v_setall_<_TpVec32F>(2.12194440E-4f); - const _TpVec32F _vexp_p0_f32 = v_setall_<_TpVec32F>(1.9875691500E-4f); - const _TpVec32F _vexp_p1_f32 = v_setall_<_TpVec32F>(1.3981999507E-3f); - const _TpVec32F _vexp_p2_f32 = v_setall_<_TpVec32F>(8.3334519073E-3f); - const _TpVec32F _vexp_p3_f32 = v_setall_<_TpVec32F>(4.1665795894E-2f); - const _TpVec32F _vexp_p4_f32 = v_setall_<_TpVec32F>(1.6666665459E-1f); - const _TpVec32F _vexp_p5_f32 = v_setall_<_TpVec32F>(5.0000001201E-1f); - - _TpVec32F _vexp_, _vexp_x, _vexp_y, _vexp_xx; - _TpVec32S _vexp_mm; - const _TpVec32S _vexp_bias_s32 = v_setall_<_TpVec32S>((int)0x7f); - - // compute exponential of x - _vexp_x = v_max(x, _vexp_lo_f32); - _vexp_x = v_min(_vexp_x, _vexp_hi_f32); - - _vexp_ = v_fma(_vexp_x, _vexp_LOG2EF_f32, _vexp_half_fp32); - _vexp_mm = v_floor(_vexp_); - _vexp_ = v_cvt_f32(_vexp_mm); - _vexp_mm = v_add(_vexp_mm, _vexp_bias_s32); - _vexp_mm = v_shl(_vexp_mm, 23); - - _vexp_x = v_fma(_vexp_, _vexp_C1_f32, _vexp_x); - _vexp_x = v_fma(_vexp_, _vexp_C2_f32, _vexp_x); - _vexp_xx = v_mul(_vexp_x, _vexp_x); - - _vexp_y = v_fma(_vexp_x, _vexp_p0_f32, _vexp_p1_f32); - _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p2_f32); - _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p3_f32); - _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p4_f32); - _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p5_f32); - - _vexp_y = v_fma(_vexp_y, _vexp_xx, _vexp_x); - _vexp_y = v_add(_vexp_y, _vexp_one_fp32); - _vexp_y = v_mul(_vexp_y, v_reinterpret_as_f32(_vexp_mm)); - - // exp(NAN) -> NAN - _TpVec32F mask_not_nan = v_not_nan(x); - return v_select(mask_not_nan, _vexp_y, v_reinterpret_as_f32(v_setall_<_TpVec32S>((int)0x7fc00000))); -} - -template -inline _TpVec64F v_exp_default_64f(const _TpVec64F &x) { - const _TpVec64F _vexp_lo_f64 = v_setall_<_TpVec64F>(-709.43613930310391424428); - const _TpVec64F _vexp_hi_f64 = v_setall_<_TpVec64F>(710.); - const _TpVec64F _vexp_half_f64 = v_setall_<_TpVec64F>(0.5); - const _TpVec64F _vexp_one_f64 = v_setall_<_TpVec64F>(1.0); - const _TpVec64F _vexp_two_f64 = v_setall_<_TpVec64F>(2.0); - const _TpVec64F _vexp_LOG2EF_f64 = v_setall_<_TpVec64F>(1.44269504088896340736); - const _TpVec64F _vexp_C1_f64 = v_setall_<_TpVec64F>(-6.93145751953125E-1); - const _TpVec64F _vexp_C2_f64 = v_setall_<_TpVec64F>(-1.42860682030941723212E-6); - const _TpVec64F _vexp_p0_f64 = v_setall_<_TpVec64F>(1.26177193074810590878E-4); - const _TpVec64F _vexp_p1_f64 = v_setall_<_TpVec64F>(3.02994407707441961300E-2); - const _TpVec64F _vexp_p2_f64 = v_setall_<_TpVec64F>(9.99999999999999999910E-1); - const _TpVec64F _vexp_q0_f64 = v_setall_<_TpVec64F>(3.00198505138664455042E-6); - const _TpVec64F _vexp_q1_f64 = v_setall_<_TpVec64F>(2.52448340349684104192E-3); - const _TpVec64F _vexp_q2_f64 = v_setall_<_TpVec64F>(2.27265548208155028766E-1); - const _TpVec64F _vexp_q3_f64 = v_setall_<_TpVec64F>(2.00000000000000000009E0); - - _TpVec64F _vexp_, _vexp_x, _vexp_y, _vexp_z, _vexp_xx; - _TpVec64S _vexp_mm; - const _TpVec64S _vexp_bias_s64 = v_setall_<_TpVec64S>((int64)0x3ff); - - // compute exponential of x - _vexp_x = v_max(x, _vexp_lo_f64); - _vexp_x = v_min(_vexp_x, _vexp_hi_f64); - - _vexp_ = v_fma(_vexp_x, _vexp_LOG2EF_f64, _vexp_half_f64); - _vexp_mm = v_expand_low(v_floor(_vexp_)); - _vexp_ = v_cvt_f64(_vexp_mm); - _vexp_mm = v_add(_vexp_mm, _vexp_bias_s64); - _vexp_mm = v_shl(_vexp_mm, 52); - - _vexp_x = v_fma(_vexp_, _vexp_C1_f64, _vexp_x); - _vexp_x = v_fma(_vexp_, _vexp_C2_f64, _vexp_x); - _vexp_xx = v_mul(_vexp_x, _vexp_x); - - _vexp_y = v_fma(_vexp_xx, _vexp_p0_f64, _vexp_p1_f64); - _vexp_y = v_fma(_vexp_y, _vexp_xx, _vexp_p2_f64); - _vexp_y = v_mul(_vexp_y, _vexp_x); - - _vexp_z = v_fma(_vexp_xx, _vexp_q0_f64, _vexp_q1_f64); - _vexp_z = v_fma(_vexp_xx, _vexp_z, _vexp_q2_f64); - _vexp_z = v_fma(_vexp_xx, _vexp_z, _vexp_q3_f64); - - _vexp_z = v_div(_vexp_y, v_sub(_vexp_z, _vexp_y)); - _vexp_z = v_fma(_vexp_two_f64, _vexp_z, _vexp_one_f64); - _vexp_z = v_mul(_vexp_z, v_reinterpret_as_f64(_vexp_mm)); - - // exp(NAN) -> NAN - _TpVec64F mask_not_nan = v_not_nan(x); - return v_select(mask_not_nan, _vexp_z, v_reinterpret_as_f64(v_setall_<_TpVec64S>((int64)0x7FF8000000000000))); -} -//! @} - -//! @name Natural Logarithm -//! @{ -template -inline _TpVec16F v_log_default_16f(const _TpVec16F &x) { - const _TpVec16F _vlog_one_fp16 = v_setall_<_TpVec16F>(1.0f); - const _TpVec16F _vlog_SQRTHF_fp16 = v_setall_<_TpVec16F>(0.707106781186547524f); - const _TpVec16F _vlog_q1_fp16 = v_setall_<_TpVec16F>(-2.12194440E-4f); - const _TpVec16F _vlog_q2_fp16 = v_setall_<_TpVec16F>(0.693359375f); - const _TpVec16F _vlog_p0_fp16 = v_setall_<_TpVec16F>(7.0376836292E-2f); - const _TpVec16F _vlog_p1_fp16 = v_setall_<_TpVec16F>(-1.1514610310E-1f); - const _TpVec16F _vlog_p2_fp16 = v_setall_<_TpVec16F>(1.1676998740E-1f); - const _TpVec16F _vlog_p3_fp16 = v_setall_<_TpVec16F>(-1.2420140846E-1f); - const _TpVec16F _vlog_p4_fp16 = v_setall_<_TpVec16F>(1.4249322787E-1f); - const _TpVec16F _vlog_p5_fp16 = v_setall_<_TpVec16F>(-1.6668057665E-1f); - const _TpVec16F _vlog_p6_fp16 = v_setall_<_TpVec16F>(2.0000714765E-1f); - const _TpVec16F _vlog_p7_fp16 = v_setall_<_TpVec16F>(-2.4999993993E-1f); - const _TpVec16F _vlog_p8_fp16 = v_setall_<_TpVec16F>(3.3333331174E-1f); - - _TpVec16F _vlog_x, _vlog_e, _vlog_y, _vlog_z, _vlog_tmp; - _TpVec16S _vlog_ux, _vlog_emm0; - const _TpVec16S _vlog_inv_mant_mask_s16 = v_setall_<_TpVec16S>((short)~0x7c00); - - _vlog_ux = v_reinterpret_as_s16(x); - _vlog_emm0 = v_shr(_vlog_ux, 10); - - _vlog_ux = v_and(_vlog_ux, _vlog_inv_mant_mask_s16); - _vlog_ux = v_or(_vlog_ux, v_reinterpret_as_s16(v_setall_<_TpVec16F>(0.5f))); - _vlog_x = v_reinterpret_as_f16(_vlog_ux); - - _vlog_emm0 = v_sub(_vlog_emm0, v_setall_<_TpVec16S>((short)0xf)); - _vlog_e = v_cvt_f16(_vlog_emm0); - - _vlog_e = v_add(_vlog_e, _vlog_one_fp16); - - _TpVec16F _vlog_mask = v_lt(_vlog_x, _vlog_SQRTHF_fp16); - _vlog_tmp = v_and(_vlog_x, _vlog_mask); - _vlog_x = v_sub(_vlog_x, _vlog_one_fp16); - _vlog_e = v_sub(_vlog_e, v_and(_vlog_one_fp16, _vlog_mask)); - _vlog_x = v_add(_vlog_x, _vlog_tmp); - - _vlog_z = v_mul(_vlog_x, _vlog_x); - - _vlog_y = v_fma(_vlog_p0_fp16, _vlog_x, _vlog_p1_fp16); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p2_fp16); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p3_fp16); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p4_fp16); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p5_fp16); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p6_fp16); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p7_fp16); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p8_fp16); - _vlog_y = v_mul(_vlog_y, _vlog_x); - _vlog_y = v_mul(_vlog_y, _vlog_z); - - _vlog_y = v_fma(_vlog_e, _vlog_q1_fp16, _vlog_y); - - _vlog_y = v_sub(_vlog_y, v_mul(_vlog_z, v_setall_<_TpVec16F>(0.5f))); - - _vlog_x = v_add(_vlog_x, _vlog_y); - _vlog_x = v_fma(_vlog_e, _vlog_q2_fp16, _vlog_x); - // log(0) -> -INF - _TpVec16F mask_zero = v_eq(x, v_setzero_<_TpVec16F>()); - _vlog_x = v_select(mask_zero, v_reinterpret_as_f16(v_setall_<_TpVec16S>((short)0xfc00)), _vlog_x); - // log(NEG), log(NAN) -> NAN - _TpVec16F mask_not_nan = v_ge(x, v_setzero_<_TpVec16F>()); - _vlog_x = v_select(mask_not_nan, _vlog_x, v_reinterpret_as_f16(v_setall_<_TpVec16S>((short)0x7e00))); - // log(INF) -> INF - _TpVec16F mask_inf = v_eq(x, v_reinterpret_as_f16(v_setall_<_TpVec16S>((short)0x7c00))); - _vlog_x = v_select(mask_inf, x, _vlog_x); - return _vlog_x; -} - -template -inline _TpVec32F v_log_default_32f(const _TpVec32F &x) { - const _TpVec32F _vlog_one_fp32 = v_setall_<_TpVec32F>(1.0f); - const _TpVec32F _vlog_SQRTHF_fp32 = v_setall_<_TpVec32F>(0.707106781186547524f); - const _TpVec32F _vlog_q1_fp32 = v_setall_<_TpVec32F>(-2.12194440E-4f); - const _TpVec32F _vlog_q2_fp32 = v_setall_<_TpVec32F>(0.693359375f); - const _TpVec32F _vlog_p0_fp32 = v_setall_<_TpVec32F>(7.0376836292E-2f); - const _TpVec32F _vlog_p1_fp32 = v_setall_<_TpVec32F>(-1.1514610310E-1f); - const _TpVec32F _vlog_p2_fp32 = v_setall_<_TpVec32F>(1.1676998740E-1f); - const _TpVec32F _vlog_p3_fp32 = v_setall_<_TpVec32F>(-1.2420140846E-1f); - const _TpVec32F _vlog_p4_fp32 = v_setall_<_TpVec32F>(1.4249322787E-1f); - const _TpVec32F _vlog_p5_fp32 = v_setall_<_TpVec32F>(-1.6668057665E-1f); - const _TpVec32F _vlog_p6_fp32 = v_setall_<_TpVec32F>(2.0000714765E-1f); - const _TpVec32F _vlog_p7_fp32 = v_setall_<_TpVec32F>(-2.4999993993E-1f); - const _TpVec32F _vlog_p8_fp32 = v_setall_<_TpVec32F>(3.3333331174E-1f); - - _TpVec32F _vlog_x, _vlog_e, _vlog_y, _vlog_z, _vlog_tmp; - _TpVec32S _vlog_ux, _vlog_emm0; - const _TpVec32S _vlog_inv_mant_mask_s32 = v_setall_<_TpVec32S>((int)~0x7f800000); - - _vlog_ux = v_reinterpret_as_s32(x); - _vlog_emm0 = v_shr(_vlog_ux, 23); - - _vlog_ux = v_and(_vlog_ux, _vlog_inv_mant_mask_s32); - _vlog_ux = v_or(_vlog_ux, v_reinterpret_as_s32(v_setall_<_TpVec32F>(0.5f))); - _vlog_x = v_reinterpret_as_f32(_vlog_ux); - - _vlog_emm0 = v_sub(_vlog_emm0, v_setall_<_TpVec32S>((int)0x7f)); - _vlog_e = v_cvt_f32(_vlog_emm0); - - _vlog_e = v_add(_vlog_e, _vlog_one_fp32); - - _TpVec32F _vlog_mask = v_lt(_vlog_x, _vlog_SQRTHF_fp32); - _vlog_tmp = v_and(_vlog_x, _vlog_mask); - _vlog_x = v_sub(_vlog_x, _vlog_one_fp32); - _vlog_e = v_sub(_vlog_e, v_and(_vlog_one_fp32, _vlog_mask)); - _vlog_x = v_add(_vlog_x, _vlog_tmp); - - _vlog_z = v_mul(_vlog_x, _vlog_x); - - _vlog_y = v_fma(_vlog_p0_fp32, _vlog_x, _vlog_p1_fp32); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p2_fp32); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p3_fp32); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p4_fp32); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p5_fp32); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p6_fp32); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p7_fp32); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p8_fp32); - _vlog_y = v_mul(_vlog_y, _vlog_x); - _vlog_y = v_mul(_vlog_y, _vlog_z); - - _vlog_y = v_fma(_vlog_e, _vlog_q1_fp32, _vlog_y); - - _vlog_y = v_sub(_vlog_y, v_mul(_vlog_z, v_setall_<_TpVec32F>(0.5f))); - - _vlog_x = v_add(_vlog_x, _vlog_y); - _vlog_x = v_fma(_vlog_e, _vlog_q2_fp32, _vlog_x); - // log(0) -> -INF - _TpVec32F mask_zero = v_eq(x, v_setzero_<_TpVec32F>()); - _vlog_x = v_select(mask_zero, v_reinterpret_as_f32(v_setall_<_TpVec32S>((int)0xff800000)), _vlog_x); - // log(NEG), log(NAN) -> NAN - _TpVec32F mask_not_nan = v_ge(x, v_setzero_<_TpVec32F>()); - _vlog_x = v_select(mask_not_nan, _vlog_x, v_reinterpret_as_f32(v_setall_<_TpVec32S>((int)0x7fc00000))); - // log(INF) -> INF - _TpVec32F mask_inf = v_eq(x, v_reinterpret_as_f32(v_setall_<_TpVec32S>((int)0x7f800000))); - _vlog_x = v_select(mask_inf, x, _vlog_x); - return _vlog_x; -} - -template -inline _TpVec64F v_log_default_64f(const _TpVec64F &x) { - const _TpVec64F _vlog_one_fp64 = v_setall_<_TpVec64F>(1.0); - const _TpVec64F _vlog_SQRTHF_fp64 = v_setall_<_TpVec64F>(0.7071067811865475244); - const _TpVec64F _vlog_p0_fp64 = v_setall_<_TpVec64F>(1.01875663804580931796E-4); - const _TpVec64F _vlog_p1_fp64 = v_setall_<_TpVec64F>(4.97494994976747001425E-1); - const _TpVec64F _vlog_p2_fp64 = v_setall_<_TpVec64F>(4.70579119878881725854); - const _TpVec64F _vlog_p3_fp64 = v_setall_<_TpVec64F>(1.44989225341610930846E1); - const _TpVec64F _vlog_p4_fp64 = v_setall_<_TpVec64F>(1.79368678507819816313E1); - const _TpVec64F _vlog_p5_fp64 = v_setall_<_TpVec64F>(7.70838733755885391666); - const _TpVec64F _vlog_q0_fp64 = v_setall_<_TpVec64F>(1.12873587189167450590E1); - const _TpVec64F _vlog_q1_fp64 = v_setall_<_TpVec64F>(4.52279145837532221105E1); - const _TpVec64F _vlog_q2_fp64 = v_setall_<_TpVec64F>(8.29875266912776603211E1); - const _TpVec64F _vlog_q3_fp64 = v_setall_<_TpVec64F>(7.11544750618563894466E1); - const _TpVec64F _vlog_q4_fp64 = v_setall_<_TpVec64F>(2.31251620126765340583E1); - - const _TpVec64F _vlog_C0_fp64 = v_setall_<_TpVec64F>(2.121944400546905827679e-4); - const _TpVec64F _vlog_C1_fp64 = v_setall_<_TpVec64F>(0.693359375); - - _TpVec64F _vlog_x, _vlog_e, _vlog_y, _vlog_z, _vlog_tmp, _vlog_xx; - _TpVec64S _vlog_ux, _vlog_emm0; - const _TpVec64S _vlog_inv_mant_mask_s64 = v_setall_<_TpVec64S>((int64)~0x7ff0000000000000); - - _vlog_ux = v_reinterpret_as_s64(x); - _vlog_emm0 = v_shr(_vlog_ux, 52); - - _vlog_ux = v_and(_vlog_ux, _vlog_inv_mant_mask_s64); - _vlog_ux = v_or(_vlog_ux, v_reinterpret_as_s64(v_setall_<_TpVec64F>(0.5))); - _vlog_x = v_reinterpret_as_f64(_vlog_ux); - - _vlog_emm0 = v_sub(_vlog_emm0, v_setall_<_TpVec64S>((int64)0x3ff)); - _vlog_e = v_cvt_f64(_vlog_emm0); - - _vlog_e = v_add(_vlog_e, _vlog_one_fp64); - - _TpVec64F _vlog_mask = v_lt(_vlog_x, _vlog_SQRTHF_fp64); - _vlog_tmp = v_and(_vlog_x, _vlog_mask); - _vlog_x = v_sub(_vlog_x, _vlog_one_fp64); - _vlog_e = v_sub(_vlog_e, v_and(_vlog_one_fp64, _vlog_mask)); - _vlog_x = v_add(_vlog_x, _vlog_tmp); - - _vlog_xx = v_mul(_vlog_x, _vlog_x); - - _vlog_y = v_fma(_vlog_p0_fp64, _vlog_x, _vlog_p1_fp64); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p2_fp64); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p3_fp64); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p4_fp64); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p5_fp64); - _vlog_y = v_mul(_vlog_y, _vlog_x); - _vlog_y = v_mul(_vlog_y, _vlog_xx); - - _vlog_z = v_add(_vlog_x, _vlog_q0_fp64); - _vlog_z = v_fma(_vlog_z, _vlog_x, _vlog_q1_fp64); - _vlog_z = v_fma(_vlog_z, _vlog_x, _vlog_q2_fp64); - _vlog_z = v_fma(_vlog_z, _vlog_x, _vlog_q3_fp64); - _vlog_z = v_fma(_vlog_z, _vlog_x, _vlog_q4_fp64); - - _vlog_z = v_div(_vlog_y, _vlog_z); - _vlog_z = v_sub(_vlog_z, v_mul(_vlog_e, _vlog_C0_fp64)); - _vlog_z = v_sub(_vlog_z, v_mul(_vlog_xx, v_setall_<_TpVec64F>(0.5))); - - _vlog_z = v_add(_vlog_z, _vlog_x); - _vlog_z = v_fma(_vlog_e, _vlog_C1_fp64, _vlog_z); - - // log(0) -> -INF - _TpVec64F mask_zero = v_eq(x, v_setzero_<_TpVec64F>()); - _vlog_z = v_select(mask_zero, v_reinterpret_as_f64(v_setall_<_TpVec64S>((int64)0xfff0000000000000)), _vlog_z); - // log(NEG), log(NAN) -> NAN - _TpVec64F mask_not_nan = v_ge(x, v_setzero_<_TpVec64F>()); - _vlog_z = v_select(mask_not_nan, _vlog_z, v_reinterpret_as_f64(v_setall_<_TpVec64S>((int64)0x7ff8000000000000))); - // log(INF) -> INF - _TpVec64F mask_inf = v_eq(x, v_reinterpret_as_f64(v_setall_<_TpVec64S>((int64)0x7ff0000000000000))); - _vlog_z = v_select(mask_inf, x, _vlog_z); - return _vlog_z; -} -//! @} - -//! @name Sine and Cosine -//! @{ -template -inline void v_sincos_default_16f(const _TpVec16F &x, _TpVec16F &ysin, _TpVec16F &ycos) { - const _TpVec16F v_cephes_FOPI = v_setall_<_TpVec16F>(hfloat(1.27323954473516f)); // 4 / M_PI - const _TpVec16F v_minus_DP1 = v_setall_<_TpVec16F>(hfloat(-0.78515625f)); - const _TpVec16F v_minus_DP2 = v_setall_<_TpVec16F>(hfloat(-2.4187564849853515625E-4f)); - const _TpVec16F v_minus_DP3 = v_setall_<_TpVec16F>(hfloat(-3.77489497744594108E-8f)); - const _TpVec16F v_sincof_p0 = v_setall_<_TpVec16F>(hfloat(-1.9515295891E-4f)); - const _TpVec16F v_sincof_p1 = v_setall_<_TpVec16F>(hfloat(8.3321608736E-3f)); - const _TpVec16F v_sincof_p2 = v_setall_<_TpVec16F>(hfloat(-1.6666654611E-1f)); - const _TpVec16F v_coscof_p0 = v_setall_<_TpVec16F>(hfloat(2.443315711809948E-5f)); - const _TpVec16F v_coscof_p1 = v_setall_<_TpVec16F>(hfloat(-1.388731625493765E-3f)); - const _TpVec16F v_coscof_p2 = v_setall_<_TpVec16F>(hfloat(4.166664568298827E-2f)); - const _TpVec16F v_nan = v_reinterpret_as_f16(v_setall_<_TpVec16S>((short)0x7e00)); - const _TpVec16F v_neg_zero = v_setall_<_TpVec16F>(hfloat(-0.f)); - - _TpVec16F _vx, _vy, sign_mask_sin, sign_mask_cos; - _TpVec16S emm2; - - sign_mask_sin = v_lt(x, v_setzero_<_TpVec16F>()); - _vx = v_abs(x); - _vy = v_mul(_vx, v_cephes_FOPI); - - emm2 = v_trunc(_vy); - emm2 = v_add(emm2, v_setall_<_TpVec16S>((short)1)); - emm2 = v_and(emm2, v_setall_<_TpVec16S>((short)~1)); - _vy = v_cvt_f16(emm2); - - _TpVec16F poly_mask = v_reinterpret_as_f16(v_eq(v_and(emm2, v_setall_<_TpVec16S>((short)2)), v_setall_<_TpVec16S>((short)0))); - - _vx = v_fma(_vy, v_minus_DP1, _vx); - _vx = v_fma(_vy, v_minus_DP2, _vx); - _vx = v_fma(_vy, v_minus_DP3, _vx); - - sign_mask_sin = v_xor(sign_mask_sin, v_reinterpret_as_f16(v_eq(v_and(emm2, v_setall_<_TpVec16S>((short)4)), v_setall_<_TpVec16S>((short)0)))); - sign_mask_cos = v_reinterpret_as_f16(v_eq(v_and(v_sub(emm2, v_setall_<_TpVec16S>((short)2)), v_setall_<_TpVec16S>((short)4)), v_setall_<_TpVec16S>((short)0))); - - _TpVec16F _vxx = v_mul(_vx, _vx); - _TpVec16F y1, y2; - - y1 = v_fma(v_coscof_p0, _vxx, v_coscof_p1); - y1 = v_fma(y1, _vxx, v_coscof_p2); - y1 = v_fma(y1, _vxx, v_setall_<_TpVec16F>(hfloat(-0.5f))); - y1 = v_fma(y1, _vxx, v_setall_<_TpVec16F>(hfloat(1.f))); - - y2 = v_fma(v_sincof_p0, _vxx, v_sincof_p1); - y2 = v_fma(y2, _vxx, v_sincof_p2); - y2 = v_mul(y2, _vxx); - y2 = v_fma(y2, _vx, _vx); - - ysin = v_select(poly_mask, y2, y1); - ycos = v_select(poly_mask, y1, y2); - ysin = v_select(sign_mask_sin, ysin, v_xor(v_neg_zero, ysin)); - ycos = v_select(sign_mask_cos, v_xor(v_neg_zero, ycos), ycos); - - // sincos(NAN) -> NAN, sincos(±INF) -> NAN - _TpVec16F mask_inf = v_eq(_vx, v_reinterpret_as_f16(v_setall_<_TpVec16S>((short)0x7c00))); - _TpVec16F mask_nan = v_or(mask_inf, v_ne(x, x)); - ysin = v_select(mask_nan, v_nan, ysin); - ycos = v_select(mask_nan, v_nan, ycos); -} - -template -inline _TpVec16F v_sin_default_16f(const _TpVec16F &x) { - _TpVec16F ysin, ycos; - v_sincos_default_16f<_TpVec16F, _TpVec16S>(x, ysin, ycos); - return ysin; -} - -template -inline _TpVec16F v_cos_default_16f(const _TpVec16F &x) { - _TpVec16F ysin, ycos; - v_sincos_default_16f<_TpVec16F, _TpVec16S>(x, ysin, ycos); - return ycos; -} - - -template -inline void v_sincos_default_32f(const _TpVec32F &x, _TpVec32F &ysin, _TpVec32F &ycos) { - const _TpVec32F v_cephes_FOPI = v_setall_<_TpVec32F>(1.27323954473516f); // 4 / M_PI - const _TpVec32F v_minus_DP1 = v_setall_<_TpVec32F>(-0.78515625f); - const _TpVec32F v_minus_DP2 = v_setall_<_TpVec32F>(-2.4187564849853515625E-4f); - const _TpVec32F v_minus_DP3 = v_setall_<_TpVec32F>(-3.77489497744594108E-8f); - const _TpVec32F v_sincof_p0 = v_setall_<_TpVec32F>(-1.9515295891E-4f); - const _TpVec32F v_sincof_p1 = v_setall_<_TpVec32F>(8.3321608736E-3f); - const _TpVec32F v_sincof_p2 = v_setall_<_TpVec32F>(-1.6666654611E-1f); - const _TpVec32F v_coscof_p0 = v_setall_<_TpVec32F>(2.443315711809948E-5f); - const _TpVec32F v_coscof_p1 = v_setall_<_TpVec32F>(-1.388731625493765E-3f); - const _TpVec32F v_coscof_p2 = v_setall_<_TpVec32F>(4.166664568298827E-2f); - const _TpVec32F v_nan = v_reinterpret_as_f32(v_setall_<_TpVec32S>((int)0x7fc00000)); - const _TpVec32F v_neg_zero = v_setall_<_TpVec32F>(-0.f); - - _TpVec32F _vx, _vy, sign_mask_sin, sign_mask_cos; - _TpVec32S emm2; - - sign_mask_sin = v_lt(x, v_setzero_<_TpVec32F>()); - _vx = v_abs(x); - _vy = v_mul(_vx, v_cephes_FOPI); - - emm2 = v_trunc(_vy); - emm2 = v_add(emm2, v_setall_<_TpVec32S>(1)); - emm2 = v_and(emm2, v_setall_<_TpVec32S>(~1)); - _vy = v_cvt_f32(emm2); - - _TpVec32F poly_mask = v_reinterpret_as_f32(v_eq(v_and(emm2, v_setall_<_TpVec32S>(2)), v_setall_<_TpVec32S>(0))); - - _vx = v_fma(_vy, v_minus_DP1, _vx); - _vx = v_fma(_vy, v_minus_DP2, _vx); - _vx = v_fma(_vy, v_minus_DP3, _vx); - - sign_mask_sin = v_xor(sign_mask_sin, v_reinterpret_as_f32(v_eq(v_and(emm2, v_setall_<_TpVec32S>(4)), v_setall_<_TpVec32S>(0)))); - sign_mask_cos = v_reinterpret_as_f32(v_eq(v_and(v_sub(emm2, v_setall_<_TpVec32S>(2)), v_setall_<_TpVec32S>(4)), v_setall_<_TpVec32S>(0))); - - _TpVec32F _vxx = v_mul(_vx, _vx); - _TpVec32F y1, y2; - - y1 = v_fma(v_coscof_p0, _vxx, v_coscof_p1); - y1 = v_fma(y1, _vxx, v_coscof_p2); - y1 = v_fma(y1, _vxx, v_setall_<_TpVec32F>(-0.5f)); - y1 = v_fma(y1, _vxx, v_setall_<_TpVec32F>(1.f)); - - y2 = v_fma(v_sincof_p0, _vxx, v_sincof_p1); - y2 = v_fma(y2, _vxx, v_sincof_p2); - y2 = v_mul(y2, _vxx); - y2 = v_fma(y2, _vx, _vx); - - ysin = v_select(poly_mask, y2, y1); - ycos = v_select(poly_mask, y1, y2); - ysin = v_select(sign_mask_sin, ysin, v_xor(v_neg_zero, ysin)); - ycos = v_select(sign_mask_cos, v_xor(v_neg_zero, ycos), ycos); - - // sincos(NAN) -> NAN, sincos(±INF) -> NAN - _TpVec32F mask_inf = v_eq(_vx, v_reinterpret_as_f32(v_setall_<_TpVec32S>((int)0x7f800000))); - _TpVec32F mask_nan = v_or(mask_inf, v_ne(x, x)); - ysin = v_select(mask_nan, v_nan, ysin); - ycos = v_select(mask_nan, v_nan, ycos); -} - -template -inline _TpVec32F v_sin_default_32f(const _TpVec32F &x) { - _TpVec32F ysin, ycos; - v_sincos_default_32f<_TpVec32F, _TpVec32S>(x, ysin, ycos); - return ysin; -} - -template -inline _TpVec32F v_cos_default_32f(const _TpVec32F &x) { - _TpVec32F ysin, ycos; - v_sincos_default_32f<_TpVec32F, _TpVec32S>(x, ysin, ycos); - return ycos; -} - -template -inline void v_sincos_default_64f(const _TpVec64F &x, _TpVec64F &ysin, _TpVec64F &ycos) { - const _TpVec64F v_cephes_FOPI = v_setall_<_TpVec64F>(1.2732395447351626861510701069801148); // 4 / M_PI - const _TpVec64F v_minus_DP1 = v_setall_<_TpVec64F>(-7.853981554508209228515625E-1); - const _TpVec64F v_minus_DP2 = v_setall_<_TpVec64F>(-7.94662735614792836714E-9); - const _TpVec64F v_minus_DP3 = v_setall_<_TpVec64F>(-3.06161699786838294307E-17); - const _TpVec64F v_sin_C1 = v_setall_<_TpVec64F>(1.58962301576546568060E-10); - const _TpVec64F v_sin_C2 = v_setall_<_TpVec64F>(-2.50507477628578072866E-8); - const _TpVec64F v_sin_C3 = v_setall_<_TpVec64F>(2.75573136213857245213E-6); - const _TpVec64F v_sin_C4 = v_setall_<_TpVec64F>(-1.98412698295895385996E-4); - const _TpVec64F v_sin_C5 = v_setall_<_TpVec64F>(8.33333333332211858878E-3); - const _TpVec64F v_sin_C6 = v_setall_<_TpVec64F>(-1.66666666666666307295E-1); - const _TpVec64F v_cos_C1 = v_setall_<_TpVec64F>(-1.13585365213876817300E-11); - const _TpVec64F v_cos_C2 = v_setall_<_TpVec64F>(2.08757008419747316778E-9); - const _TpVec64F v_cos_C3 = v_setall_<_TpVec64F>(-2.75573141792967388112E-7); - const _TpVec64F v_cos_C4 = v_setall_<_TpVec64F>(2.48015872888517045348E-5); - const _TpVec64F v_cos_C5 = v_setall_<_TpVec64F>(-1.38888888888730564116E-3); - const _TpVec64F v_cos_C6 = v_setall_<_TpVec64F>(4.16666666666665929218E-2); - const _TpVec64F v_nan = v_reinterpret_as_f64(v_setall_<_TpVec64S>((int64)0x7ff8000000000000)); - const _TpVec64F v_neg_zero = v_setall_<_TpVec64F>(-0.0); - - _TpVec64F _vx, _vy, sign_mask_sin, sign_mask_cos; - _TpVec64S emm2; - - sign_mask_sin = v_lt(x, v_setzero_<_TpVec64F>()); - _vx = v_abs(x); - _vy = v_mul(_vx, v_cephes_FOPI); - - emm2 = v_expand_low(v_trunc(_vy)); - emm2 = v_add(emm2, v_setall_<_TpVec64S>((int64)1)); - emm2 = v_and(emm2, v_setall_<_TpVec64S>((int64)~1)); - _vy = v_cvt_f64(emm2); - - _TpVec64F poly_mask = v_reinterpret_as_f64(v_eq(v_and(emm2, v_setall_<_TpVec64S>((int64)2)), v_setall_<_TpVec64S>((int64)0))); - - _vx = v_fma(_vy, v_minus_DP1, _vx); - _vx = v_fma(_vy, v_minus_DP2, _vx); - _vx = v_fma(_vy, v_minus_DP3, _vx); - - sign_mask_sin = v_xor(sign_mask_sin, v_reinterpret_as_f64(v_eq(v_and(emm2, v_setall_<_TpVec64S>((int64)4)), v_setall_<_TpVec64S>((int64)0)))); - sign_mask_cos = v_reinterpret_as_f64(v_eq(v_and(v_sub(emm2, v_setall_<_TpVec64S>((int64)2)), v_setall_<_TpVec64S>((int64)4)), v_setall_<_TpVec64S>((int64)0))); - - _TpVec64F _vxx = v_mul(_vx, _vx); - _TpVec64F y1, y2; - - y1 = v_fma(v_cos_C1, _vxx, v_cos_C2); - y1 = v_fma(y1, _vxx, v_cos_C3); - y1 = v_fma(y1, _vxx, v_cos_C4); - y1 = v_fma(y1, _vxx, v_cos_C5); - y1 = v_fma(y1, _vxx, v_cos_C6); - y1 = v_fma(y1, _vxx, v_setall_<_TpVec64F>(-0.5)); - y1 = v_fma(y1, _vxx, v_setall_<_TpVec64F>(1.0)); - - y2 = v_fma(v_sin_C1, _vxx, v_sin_C2); - y2 = v_fma(y2, _vxx, v_sin_C3); - y2 = v_fma(y2, _vxx, v_sin_C4); - y2 = v_fma(y2, _vxx, v_sin_C5); - y2 = v_fma(y2, _vxx, v_sin_C6); - y2 = v_mul(y2, _vxx); - y2 = v_fma(y2, _vx, _vx); - - ysin = v_select(poly_mask, y2, y1); - ycos = v_select(poly_mask, y1, y2); - ysin = v_select(sign_mask_sin, ysin, v_xor(v_neg_zero, ysin)); - ycos = v_select(sign_mask_cos, v_xor(v_neg_zero, ycos), ycos); - - // sincos(NAN) -> NAN, sincos(±INF) -> NAN - _TpVec64F mask_inf = v_eq(_vx, v_reinterpret_as_f64(v_setall_<_TpVec64S>((int64)0x7ff0000000000000))); - _TpVec64F mask_nan = v_or(mask_inf, v_ne(x, x)); - ysin = v_select(mask_nan, v_nan, ysin); - ycos = v_select(mask_nan, v_nan, ycos); -} - -template -inline _TpVec64F v_sin_default_64f(const _TpVec64F &x) { - _TpVec64F ysin, ycos; - v_sincos_default_64f<_TpVec64F, _TpVec64S>(x, ysin, ycos); - return ysin; -} - -template -inline _TpVec64F v_cos_default_64f(const _TpVec64F &x) { - _TpVec64F ysin, ycos; - v_sincos_default_64f<_TpVec64F, _TpVec64S>(x, ysin, ycos); - return ycos; -} -//! @} - - -/* This implementation is derived from the approximation approach of Error Function (Erf) from PyTorch - https://github.com/pytorch/pytorch/blob/9c50ecc84b9a6e699a7f058891b889aafbf976c7/aten/src/ATen/cpu/vec/vec512/vec512_float.h#L189-L220 -*/ - -//! @name Error Function -//! @{ -template -inline _TpVec32F v_erf_default_32f(const _TpVec32F &v) { - const _TpVec32F coef0 = v_setall_<_TpVec32F>(0.3275911f), - coef1 = v_setall_<_TpVec32F>(1.061405429f), - coef2 = v_setall_<_TpVec32F>(-1.453152027f), - coef3 = v_setall_<_TpVec32F>(1.421413741f), - coef4 = v_setall_<_TpVec32F>(-0.284496736f), - coef5 = v_setall_<_TpVec32F>(0.254829592f), - ones = v_setall_<_TpVec32F>(1.0f), - neg_zeros = v_setall_<_TpVec32F>(-0.f); - _TpVec32F t = v_abs(v); - // sign(v) - _TpVec32F sign_mask = v_and(neg_zeros, v); - - t = v_div(ones, v_fma(coef0, t, ones)); - _TpVec32F r = v_fma(coef1, t, coef2); - r = v_fma(r, t, coef3); - r = v_fma(r, t, coef4); - r = v_fma(r, t, coef5); - // - v * v - _TpVec32F v2 = v_mul(v, v); - _TpVec32F mv2 = v_xor(neg_zeros, v2); - // - exp(- v * v) - _TpVec32F exp = v_exp_default_32f<_TpVec32F, _TpVec32S>(mv2); - _TpVec32F neg_exp = v_xor(neg_zeros, exp); - _TpVec32F res = v_mul(t, neg_exp); - res = v_fma(r, res, ones); - return v_xor(sign_mask, res); -} -//! @} - -#endif // OPENCV_HAL_INTRIN_MATH_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + + +/* Universal Intrinsics implementation of sin, cos, exp and log + + Inspired by Intel Approximate Math library, and based on the + corresponding algorithms of the cephes math library +*/ + +/* Copyright (C) 2010,2011 RJVB - extensions */ +/* Copyright (C) 2011 Julien Pommier + + 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. + + (this is the zlib license) +*/ +#ifndef OPENCV_HAL_INTRIN_MATH_HPP +#define OPENCV_HAL_INTRIN_MATH_HPP + +//! @name Exponential +//! @{ +// Implementation is the same as float32 vector. +template +inline _TpVec16F v_exp_default_16f(const _TpVec16F &x) { + const _TpVec16F _vexp_lo_f16 = v_setall_<_TpVec16F>(-10.7421875f); + const _TpVec16F _vexp_hi_f16 = v_setall_<_TpVec16F>(11.f); + const _TpVec16F _vexp_half_fp16 = v_setall_<_TpVec16F>(0.5f); + const _TpVec16F _vexp_one_fp16 = v_setall_<_TpVec16F>(1.f); + const _TpVec16F _vexp_LOG2EF_f16 = v_setall_<_TpVec16F>(1.44269504088896341f); + const _TpVec16F _vexp_C1_f16 = v_setall_<_TpVec16F>(-6.93359375E-1f); + const _TpVec16F _vexp_C2_f16 = v_setall_<_TpVec16F>(2.12194440E-4f); + const _TpVec16F _vexp_p0_f16 = v_setall_<_TpVec16F>(1.9875691500E-4f); + const _TpVec16F _vexp_p1_f16 = v_setall_<_TpVec16F>(1.3981999507E-3f); + const _TpVec16F _vexp_p2_f16 = v_setall_<_TpVec16F>(8.3334519073E-3f); + const _TpVec16F _vexp_p3_f16 = v_setall_<_TpVec16F>(4.1665795894E-2f); + const _TpVec16F _vexp_p4_f16 = v_setall_<_TpVec16F>(1.6666665459E-1f); + const _TpVec16F _vexp_p5_f16 = v_setall_<_TpVec16F>(5.0000001201E-1f); + + _TpVec16F _vexp_, _vexp_x, _vexp_y, _vexp_xx; + _TpVec16S _vexp_mm; + const _TpVec16S _vexp_bias_s16 = v_setall_<_TpVec16S>((short)0xf); + + // compute exponential of x + _vexp_x = v_max(x, _vexp_lo_f16); + _vexp_x = v_min(_vexp_x, _vexp_hi_f16); + + _vexp_ = v_fma(_vexp_x, _vexp_LOG2EF_f16, _vexp_half_fp16); + _vexp_mm = v_floor(_vexp_); + _vexp_ = v_cvt_f16(_vexp_mm); + _vexp_mm = v_add(_vexp_mm, _vexp_bias_s16); + _vexp_mm = v_shl(_vexp_mm, 10); + + _vexp_x = v_fma(_vexp_, _vexp_C1_f16, _vexp_x); + _vexp_x = v_fma(_vexp_, _vexp_C2_f16, _vexp_x); + _vexp_xx = v_mul(_vexp_x, _vexp_x); + + _vexp_y = v_fma(_vexp_x, _vexp_p0_f16, _vexp_p1_f16); + _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p2_f16); + _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p3_f16); + _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p4_f16); + _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p5_f16); + + _vexp_y = v_fma(_vexp_y, _vexp_xx, _vexp_x); + _vexp_y = v_add(_vexp_y, _vexp_one_fp16); + _vexp_y = v_mul(_vexp_y, v_reinterpret_as_f16(_vexp_mm)); + + // exp(NAN) -> NAN + _TpVec16F mask_not_nan = v_not_nan(x); + return v_select(mask_not_nan, _vexp_y, v_reinterpret_as_f16(v_setall_<_TpVec16S>((short)0x7e00))); +} + +template +inline _TpVec32F v_exp_default_32f(const _TpVec32F &x) { + const _TpVec32F _vexp_lo_f32 = v_setall_<_TpVec32F>(-88.3762626647949f); + const _TpVec32F _vexp_hi_f32 = v_setall_<_TpVec32F>(89.f); + const _TpVec32F _vexp_half_fp32 = v_setall_<_TpVec32F>(0.5f); + const _TpVec32F _vexp_one_fp32 = v_setall_<_TpVec32F>(1.f); + const _TpVec32F _vexp_LOG2EF_f32 = v_setall_<_TpVec32F>(1.44269504088896341f); + const _TpVec32F _vexp_C1_f32 = v_setall_<_TpVec32F>(-6.93359375E-1f); + const _TpVec32F _vexp_C2_f32 = v_setall_<_TpVec32F>(2.12194440E-4f); + const _TpVec32F _vexp_p0_f32 = v_setall_<_TpVec32F>(1.9875691500E-4f); + const _TpVec32F _vexp_p1_f32 = v_setall_<_TpVec32F>(1.3981999507E-3f); + const _TpVec32F _vexp_p2_f32 = v_setall_<_TpVec32F>(8.3334519073E-3f); + const _TpVec32F _vexp_p3_f32 = v_setall_<_TpVec32F>(4.1665795894E-2f); + const _TpVec32F _vexp_p4_f32 = v_setall_<_TpVec32F>(1.6666665459E-1f); + const _TpVec32F _vexp_p5_f32 = v_setall_<_TpVec32F>(5.0000001201E-1f); + + _TpVec32F _vexp_, _vexp_x, _vexp_y, _vexp_xx; + _TpVec32S _vexp_mm; + const _TpVec32S _vexp_bias_s32 = v_setall_<_TpVec32S>((int)0x7f); + + // compute exponential of x + _vexp_x = v_max(x, _vexp_lo_f32); + _vexp_x = v_min(_vexp_x, _vexp_hi_f32); + + _vexp_ = v_fma(_vexp_x, _vexp_LOG2EF_f32, _vexp_half_fp32); + _vexp_mm = v_floor(_vexp_); + _vexp_ = v_cvt_f32(_vexp_mm); + _vexp_mm = v_add(_vexp_mm, _vexp_bias_s32); + _vexp_mm = v_shl(_vexp_mm, 23); + + _vexp_x = v_fma(_vexp_, _vexp_C1_f32, _vexp_x); + _vexp_x = v_fma(_vexp_, _vexp_C2_f32, _vexp_x); + _vexp_xx = v_mul(_vexp_x, _vexp_x); + + _vexp_y = v_fma(_vexp_x, _vexp_p0_f32, _vexp_p1_f32); + _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p2_f32); + _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p3_f32); + _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p4_f32); + _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p5_f32); + + _vexp_y = v_fma(_vexp_y, _vexp_xx, _vexp_x); + _vexp_y = v_add(_vexp_y, _vexp_one_fp32); + _vexp_y = v_mul(_vexp_y, v_reinterpret_as_f32(_vexp_mm)); + + // exp(NAN) -> NAN + _TpVec32F mask_not_nan = v_not_nan(x); + return v_select(mask_not_nan, _vexp_y, v_reinterpret_as_f32(v_setall_<_TpVec32S>((int)0x7fc00000))); +} + +template +inline _TpVec64F v_exp_default_64f(const _TpVec64F &x) { + const _TpVec64F _vexp_lo_f64 = v_setall_<_TpVec64F>(-709.43613930310391424428); + const _TpVec64F _vexp_hi_f64 = v_setall_<_TpVec64F>(710.); + const _TpVec64F _vexp_half_f64 = v_setall_<_TpVec64F>(0.5); + const _TpVec64F _vexp_one_f64 = v_setall_<_TpVec64F>(1.0); + const _TpVec64F _vexp_two_f64 = v_setall_<_TpVec64F>(2.0); + const _TpVec64F _vexp_LOG2EF_f64 = v_setall_<_TpVec64F>(1.44269504088896340736); + const _TpVec64F _vexp_C1_f64 = v_setall_<_TpVec64F>(-6.93145751953125E-1); + const _TpVec64F _vexp_C2_f64 = v_setall_<_TpVec64F>(-1.42860682030941723212E-6); + const _TpVec64F _vexp_p0_f64 = v_setall_<_TpVec64F>(1.26177193074810590878E-4); + const _TpVec64F _vexp_p1_f64 = v_setall_<_TpVec64F>(3.02994407707441961300E-2); + const _TpVec64F _vexp_p2_f64 = v_setall_<_TpVec64F>(9.99999999999999999910E-1); + const _TpVec64F _vexp_q0_f64 = v_setall_<_TpVec64F>(3.00198505138664455042E-6); + const _TpVec64F _vexp_q1_f64 = v_setall_<_TpVec64F>(2.52448340349684104192E-3); + const _TpVec64F _vexp_q2_f64 = v_setall_<_TpVec64F>(2.27265548208155028766E-1); + const _TpVec64F _vexp_q3_f64 = v_setall_<_TpVec64F>(2.00000000000000000009E0); + + _TpVec64F _vexp_, _vexp_x, _vexp_y, _vexp_z, _vexp_xx; + _TpVec64S _vexp_mm; + const _TpVec64S _vexp_bias_s64 = v_setall_<_TpVec64S>((int64)0x3ff); + + // compute exponential of x + _vexp_x = v_max(x, _vexp_lo_f64); + _vexp_x = v_min(_vexp_x, _vexp_hi_f64); + + _vexp_ = v_fma(_vexp_x, _vexp_LOG2EF_f64, _vexp_half_f64); + _vexp_mm = v_expand_low(v_floor(_vexp_)); + _vexp_ = v_cvt_f64(_vexp_mm); + _vexp_mm = v_add(_vexp_mm, _vexp_bias_s64); + _vexp_mm = v_shl(_vexp_mm, 52); + + _vexp_x = v_fma(_vexp_, _vexp_C1_f64, _vexp_x); + _vexp_x = v_fma(_vexp_, _vexp_C2_f64, _vexp_x); + _vexp_xx = v_mul(_vexp_x, _vexp_x); + + _vexp_y = v_fma(_vexp_xx, _vexp_p0_f64, _vexp_p1_f64); + _vexp_y = v_fma(_vexp_y, _vexp_xx, _vexp_p2_f64); + _vexp_y = v_mul(_vexp_y, _vexp_x); + + _vexp_z = v_fma(_vexp_xx, _vexp_q0_f64, _vexp_q1_f64); + _vexp_z = v_fma(_vexp_xx, _vexp_z, _vexp_q2_f64); + _vexp_z = v_fma(_vexp_xx, _vexp_z, _vexp_q3_f64); + + _vexp_z = v_div(_vexp_y, v_sub(_vexp_z, _vexp_y)); + _vexp_z = v_fma(_vexp_two_f64, _vexp_z, _vexp_one_f64); + _vexp_z = v_mul(_vexp_z, v_reinterpret_as_f64(_vexp_mm)); + + // exp(NAN) -> NAN + _TpVec64F mask_not_nan = v_not_nan(x); + return v_select(mask_not_nan, _vexp_z, v_reinterpret_as_f64(v_setall_<_TpVec64S>((int64)0x7FF8000000000000))); +} +//! @} + +//! @name Natural Logarithm +//! @{ +template +inline _TpVec16F v_log_default_16f(const _TpVec16F &x) { + const _TpVec16F _vlog_one_fp16 = v_setall_<_TpVec16F>(1.0f); + const _TpVec16F _vlog_SQRTHF_fp16 = v_setall_<_TpVec16F>(0.707106781186547524f); + const _TpVec16F _vlog_q1_fp16 = v_setall_<_TpVec16F>(-2.12194440E-4f); + const _TpVec16F _vlog_q2_fp16 = v_setall_<_TpVec16F>(0.693359375f); + const _TpVec16F _vlog_p0_fp16 = v_setall_<_TpVec16F>(7.0376836292E-2f); + const _TpVec16F _vlog_p1_fp16 = v_setall_<_TpVec16F>(-1.1514610310E-1f); + const _TpVec16F _vlog_p2_fp16 = v_setall_<_TpVec16F>(1.1676998740E-1f); + const _TpVec16F _vlog_p3_fp16 = v_setall_<_TpVec16F>(-1.2420140846E-1f); + const _TpVec16F _vlog_p4_fp16 = v_setall_<_TpVec16F>(1.4249322787E-1f); + const _TpVec16F _vlog_p5_fp16 = v_setall_<_TpVec16F>(-1.6668057665E-1f); + const _TpVec16F _vlog_p6_fp16 = v_setall_<_TpVec16F>(2.0000714765E-1f); + const _TpVec16F _vlog_p7_fp16 = v_setall_<_TpVec16F>(-2.4999993993E-1f); + const _TpVec16F _vlog_p8_fp16 = v_setall_<_TpVec16F>(3.3333331174E-1f); + + _TpVec16F _vlog_x, _vlog_e, _vlog_y, _vlog_z, _vlog_tmp; + _TpVec16S _vlog_ux, _vlog_emm0; + const _TpVec16S _vlog_inv_mant_mask_s16 = v_setall_<_TpVec16S>((short)~0x7c00); + + _vlog_ux = v_reinterpret_as_s16(x); + _vlog_emm0 = v_shr(_vlog_ux, 10); + + _vlog_ux = v_and(_vlog_ux, _vlog_inv_mant_mask_s16); + _vlog_ux = v_or(_vlog_ux, v_reinterpret_as_s16(v_setall_<_TpVec16F>(0.5f))); + _vlog_x = v_reinterpret_as_f16(_vlog_ux); + + _vlog_emm0 = v_sub(_vlog_emm0, v_setall_<_TpVec16S>((short)0xf)); + _vlog_e = v_cvt_f16(_vlog_emm0); + + _vlog_e = v_add(_vlog_e, _vlog_one_fp16); + + _TpVec16F _vlog_mask = v_lt(_vlog_x, _vlog_SQRTHF_fp16); + _vlog_tmp = v_and(_vlog_x, _vlog_mask); + _vlog_x = v_sub(_vlog_x, _vlog_one_fp16); + _vlog_e = v_sub(_vlog_e, v_and(_vlog_one_fp16, _vlog_mask)); + _vlog_x = v_add(_vlog_x, _vlog_tmp); + + _vlog_z = v_mul(_vlog_x, _vlog_x); + + _vlog_y = v_fma(_vlog_p0_fp16, _vlog_x, _vlog_p1_fp16); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p2_fp16); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p3_fp16); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p4_fp16); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p5_fp16); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p6_fp16); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p7_fp16); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p8_fp16); + _vlog_y = v_mul(_vlog_y, _vlog_x); + _vlog_y = v_mul(_vlog_y, _vlog_z); + + _vlog_y = v_fma(_vlog_e, _vlog_q1_fp16, _vlog_y); + + _vlog_y = v_sub(_vlog_y, v_mul(_vlog_z, v_setall_<_TpVec16F>(0.5f))); + + _vlog_x = v_add(_vlog_x, _vlog_y); + _vlog_x = v_fma(_vlog_e, _vlog_q2_fp16, _vlog_x); + // log(0) -> -INF + _TpVec16F mask_zero = v_eq(x, v_setzero_<_TpVec16F>()); + _vlog_x = v_select(mask_zero, v_reinterpret_as_f16(v_setall_<_TpVec16S>((short)0xfc00)), _vlog_x); + // log(NEG), log(NAN) -> NAN + _TpVec16F mask_not_nan = v_ge(x, v_setzero_<_TpVec16F>()); + _vlog_x = v_select(mask_not_nan, _vlog_x, v_reinterpret_as_f16(v_setall_<_TpVec16S>((short)0x7e00))); + // log(INF) -> INF + _TpVec16F mask_inf = v_eq(x, v_reinterpret_as_f16(v_setall_<_TpVec16S>((short)0x7c00))); + _vlog_x = v_select(mask_inf, x, _vlog_x); + return _vlog_x; +} + +template +inline _TpVec32F v_log_default_32f(const _TpVec32F &x) { + const _TpVec32F _vlog_one_fp32 = v_setall_<_TpVec32F>(1.0f); + const _TpVec32F _vlog_SQRTHF_fp32 = v_setall_<_TpVec32F>(0.707106781186547524f); + const _TpVec32F _vlog_q1_fp32 = v_setall_<_TpVec32F>(-2.12194440E-4f); + const _TpVec32F _vlog_q2_fp32 = v_setall_<_TpVec32F>(0.693359375f); + const _TpVec32F _vlog_p0_fp32 = v_setall_<_TpVec32F>(7.0376836292E-2f); + const _TpVec32F _vlog_p1_fp32 = v_setall_<_TpVec32F>(-1.1514610310E-1f); + const _TpVec32F _vlog_p2_fp32 = v_setall_<_TpVec32F>(1.1676998740E-1f); + const _TpVec32F _vlog_p3_fp32 = v_setall_<_TpVec32F>(-1.2420140846E-1f); + const _TpVec32F _vlog_p4_fp32 = v_setall_<_TpVec32F>(1.4249322787E-1f); + const _TpVec32F _vlog_p5_fp32 = v_setall_<_TpVec32F>(-1.6668057665E-1f); + const _TpVec32F _vlog_p6_fp32 = v_setall_<_TpVec32F>(2.0000714765E-1f); + const _TpVec32F _vlog_p7_fp32 = v_setall_<_TpVec32F>(-2.4999993993E-1f); + const _TpVec32F _vlog_p8_fp32 = v_setall_<_TpVec32F>(3.3333331174E-1f); + + _TpVec32F _vlog_x, _vlog_e, _vlog_y, _vlog_z, _vlog_tmp; + _TpVec32S _vlog_ux, _vlog_emm0; + const _TpVec32S _vlog_inv_mant_mask_s32 = v_setall_<_TpVec32S>((int)~0x7f800000); + + _vlog_ux = v_reinterpret_as_s32(x); + _vlog_emm0 = v_shr(_vlog_ux, 23); + + _vlog_ux = v_and(_vlog_ux, _vlog_inv_mant_mask_s32); + _vlog_ux = v_or(_vlog_ux, v_reinterpret_as_s32(v_setall_<_TpVec32F>(0.5f))); + _vlog_x = v_reinterpret_as_f32(_vlog_ux); + + _vlog_emm0 = v_sub(_vlog_emm0, v_setall_<_TpVec32S>((int)0x7f)); + _vlog_e = v_cvt_f32(_vlog_emm0); + + _vlog_e = v_add(_vlog_e, _vlog_one_fp32); + + _TpVec32F _vlog_mask = v_lt(_vlog_x, _vlog_SQRTHF_fp32); + _vlog_tmp = v_and(_vlog_x, _vlog_mask); + _vlog_x = v_sub(_vlog_x, _vlog_one_fp32); + _vlog_e = v_sub(_vlog_e, v_and(_vlog_one_fp32, _vlog_mask)); + _vlog_x = v_add(_vlog_x, _vlog_tmp); + + _vlog_z = v_mul(_vlog_x, _vlog_x); + + _vlog_y = v_fma(_vlog_p0_fp32, _vlog_x, _vlog_p1_fp32); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p2_fp32); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p3_fp32); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p4_fp32); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p5_fp32); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p6_fp32); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p7_fp32); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p8_fp32); + _vlog_y = v_mul(_vlog_y, _vlog_x); + _vlog_y = v_mul(_vlog_y, _vlog_z); + + _vlog_y = v_fma(_vlog_e, _vlog_q1_fp32, _vlog_y); + + _vlog_y = v_sub(_vlog_y, v_mul(_vlog_z, v_setall_<_TpVec32F>(0.5f))); + + _vlog_x = v_add(_vlog_x, _vlog_y); + _vlog_x = v_fma(_vlog_e, _vlog_q2_fp32, _vlog_x); + // log(0) -> -INF + _TpVec32F mask_zero = v_eq(x, v_setzero_<_TpVec32F>()); + _vlog_x = v_select(mask_zero, v_reinterpret_as_f32(v_setall_<_TpVec32S>((int)0xff800000)), _vlog_x); + // log(NEG), log(NAN) -> NAN + _TpVec32F mask_not_nan = v_ge(x, v_setzero_<_TpVec32F>()); + _vlog_x = v_select(mask_not_nan, _vlog_x, v_reinterpret_as_f32(v_setall_<_TpVec32S>((int)0x7fc00000))); + // log(INF) -> INF + _TpVec32F mask_inf = v_eq(x, v_reinterpret_as_f32(v_setall_<_TpVec32S>((int)0x7f800000))); + _vlog_x = v_select(mask_inf, x, _vlog_x); + return _vlog_x; +} + +template +inline _TpVec64F v_log_default_64f(const _TpVec64F &x) { + const _TpVec64F _vlog_one_fp64 = v_setall_<_TpVec64F>(1.0); + const _TpVec64F _vlog_SQRTHF_fp64 = v_setall_<_TpVec64F>(0.7071067811865475244); + const _TpVec64F _vlog_p0_fp64 = v_setall_<_TpVec64F>(1.01875663804580931796E-4); + const _TpVec64F _vlog_p1_fp64 = v_setall_<_TpVec64F>(4.97494994976747001425E-1); + const _TpVec64F _vlog_p2_fp64 = v_setall_<_TpVec64F>(4.70579119878881725854); + const _TpVec64F _vlog_p3_fp64 = v_setall_<_TpVec64F>(1.44989225341610930846E1); + const _TpVec64F _vlog_p4_fp64 = v_setall_<_TpVec64F>(1.79368678507819816313E1); + const _TpVec64F _vlog_p5_fp64 = v_setall_<_TpVec64F>(7.70838733755885391666); + const _TpVec64F _vlog_q0_fp64 = v_setall_<_TpVec64F>(1.12873587189167450590E1); + const _TpVec64F _vlog_q1_fp64 = v_setall_<_TpVec64F>(4.52279145837532221105E1); + const _TpVec64F _vlog_q2_fp64 = v_setall_<_TpVec64F>(8.29875266912776603211E1); + const _TpVec64F _vlog_q3_fp64 = v_setall_<_TpVec64F>(7.11544750618563894466E1); + const _TpVec64F _vlog_q4_fp64 = v_setall_<_TpVec64F>(2.31251620126765340583E1); + + const _TpVec64F _vlog_C0_fp64 = v_setall_<_TpVec64F>(2.121944400546905827679e-4); + const _TpVec64F _vlog_C1_fp64 = v_setall_<_TpVec64F>(0.693359375); + + _TpVec64F _vlog_x, _vlog_e, _vlog_y, _vlog_z, _vlog_tmp, _vlog_xx; + _TpVec64S _vlog_ux, _vlog_emm0; + const _TpVec64S _vlog_inv_mant_mask_s64 = v_setall_<_TpVec64S>((int64)~0x7ff0000000000000); + + _vlog_ux = v_reinterpret_as_s64(x); + _vlog_emm0 = v_shr(_vlog_ux, 52); + + _vlog_ux = v_and(_vlog_ux, _vlog_inv_mant_mask_s64); + _vlog_ux = v_or(_vlog_ux, v_reinterpret_as_s64(v_setall_<_TpVec64F>(0.5))); + _vlog_x = v_reinterpret_as_f64(_vlog_ux); + + _vlog_emm0 = v_sub(_vlog_emm0, v_setall_<_TpVec64S>((int64)0x3ff)); + _vlog_e = v_cvt_f64(_vlog_emm0); + + _vlog_e = v_add(_vlog_e, _vlog_one_fp64); + + _TpVec64F _vlog_mask = v_lt(_vlog_x, _vlog_SQRTHF_fp64); + _vlog_tmp = v_and(_vlog_x, _vlog_mask); + _vlog_x = v_sub(_vlog_x, _vlog_one_fp64); + _vlog_e = v_sub(_vlog_e, v_and(_vlog_one_fp64, _vlog_mask)); + _vlog_x = v_add(_vlog_x, _vlog_tmp); + + _vlog_xx = v_mul(_vlog_x, _vlog_x); + + _vlog_y = v_fma(_vlog_p0_fp64, _vlog_x, _vlog_p1_fp64); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p2_fp64); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p3_fp64); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p4_fp64); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p5_fp64); + _vlog_y = v_mul(_vlog_y, _vlog_x); + _vlog_y = v_mul(_vlog_y, _vlog_xx); + + _vlog_z = v_add(_vlog_x, _vlog_q0_fp64); + _vlog_z = v_fma(_vlog_z, _vlog_x, _vlog_q1_fp64); + _vlog_z = v_fma(_vlog_z, _vlog_x, _vlog_q2_fp64); + _vlog_z = v_fma(_vlog_z, _vlog_x, _vlog_q3_fp64); + _vlog_z = v_fma(_vlog_z, _vlog_x, _vlog_q4_fp64); + + _vlog_z = v_div(_vlog_y, _vlog_z); + _vlog_z = v_sub(_vlog_z, v_mul(_vlog_e, _vlog_C0_fp64)); + _vlog_z = v_sub(_vlog_z, v_mul(_vlog_xx, v_setall_<_TpVec64F>(0.5))); + + _vlog_z = v_add(_vlog_z, _vlog_x); + _vlog_z = v_fma(_vlog_e, _vlog_C1_fp64, _vlog_z); + + // log(0) -> -INF + _TpVec64F mask_zero = v_eq(x, v_setzero_<_TpVec64F>()); + _vlog_z = v_select(mask_zero, v_reinterpret_as_f64(v_setall_<_TpVec64S>((int64)0xfff0000000000000)), _vlog_z); + // log(NEG), log(NAN) -> NAN + _TpVec64F mask_not_nan = v_ge(x, v_setzero_<_TpVec64F>()); + _vlog_z = v_select(mask_not_nan, _vlog_z, v_reinterpret_as_f64(v_setall_<_TpVec64S>((int64)0x7ff8000000000000))); + // log(INF) -> INF + _TpVec64F mask_inf = v_eq(x, v_reinterpret_as_f64(v_setall_<_TpVec64S>((int64)0x7ff0000000000000))); + _vlog_z = v_select(mask_inf, x, _vlog_z); + return _vlog_z; +} +//! @} + +//! @name Sine and Cosine +//! @{ +template +inline void v_sincos_default_16f(const _TpVec16F &x, _TpVec16F &ysin, _TpVec16F &ycos) { + const _TpVec16F v_cephes_FOPI = v_setall_<_TpVec16F>(hfloat(1.27323954473516f)); // 4 / M_PI + const _TpVec16F v_minus_DP1 = v_setall_<_TpVec16F>(hfloat(-0.78515625f)); + const _TpVec16F v_minus_DP2 = v_setall_<_TpVec16F>(hfloat(-2.4187564849853515625E-4f)); + const _TpVec16F v_minus_DP3 = v_setall_<_TpVec16F>(hfloat(-3.77489497744594108E-8f)); + const _TpVec16F v_sincof_p0 = v_setall_<_TpVec16F>(hfloat(-1.9515295891E-4f)); + const _TpVec16F v_sincof_p1 = v_setall_<_TpVec16F>(hfloat(8.3321608736E-3f)); + const _TpVec16F v_sincof_p2 = v_setall_<_TpVec16F>(hfloat(-1.6666654611E-1f)); + const _TpVec16F v_coscof_p0 = v_setall_<_TpVec16F>(hfloat(2.443315711809948E-5f)); + const _TpVec16F v_coscof_p1 = v_setall_<_TpVec16F>(hfloat(-1.388731625493765E-3f)); + const _TpVec16F v_coscof_p2 = v_setall_<_TpVec16F>(hfloat(4.166664568298827E-2f)); + const _TpVec16F v_nan = v_reinterpret_as_f16(v_setall_<_TpVec16S>((short)0x7e00)); + const _TpVec16F v_neg_zero = v_setall_<_TpVec16F>(hfloat(-0.f)); + + _TpVec16F _vx, _vy, sign_mask_sin, sign_mask_cos; + _TpVec16S emm2; + + sign_mask_sin = v_lt(x, v_setzero_<_TpVec16F>()); + _vx = v_abs(x); + _vy = v_mul(_vx, v_cephes_FOPI); + + emm2 = v_trunc(_vy); + emm2 = v_add(emm2, v_setall_<_TpVec16S>((short)1)); + emm2 = v_and(emm2, v_setall_<_TpVec16S>((short)~1)); + _vy = v_cvt_f16(emm2); + + _TpVec16F poly_mask = v_reinterpret_as_f16(v_eq(v_and(emm2, v_setall_<_TpVec16S>((short)2)), v_setall_<_TpVec16S>((short)0))); + + _vx = v_fma(_vy, v_minus_DP1, _vx); + _vx = v_fma(_vy, v_minus_DP2, _vx); + _vx = v_fma(_vy, v_minus_DP3, _vx); + + sign_mask_sin = v_xor(sign_mask_sin, v_reinterpret_as_f16(v_eq(v_and(emm2, v_setall_<_TpVec16S>((short)4)), v_setall_<_TpVec16S>((short)0)))); + sign_mask_cos = v_reinterpret_as_f16(v_eq(v_and(v_sub(emm2, v_setall_<_TpVec16S>((short)2)), v_setall_<_TpVec16S>((short)4)), v_setall_<_TpVec16S>((short)0))); + + _TpVec16F _vxx = v_mul(_vx, _vx); + _TpVec16F y1, y2; + + y1 = v_fma(v_coscof_p0, _vxx, v_coscof_p1); + y1 = v_fma(y1, _vxx, v_coscof_p2); + y1 = v_fma(y1, _vxx, v_setall_<_TpVec16F>(hfloat(-0.5f))); + y1 = v_fma(y1, _vxx, v_setall_<_TpVec16F>(hfloat(1.f))); + + y2 = v_fma(v_sincof_p0, _vxx, v_sincof_p1); + y2 = v_fma(y2, _vxx, v_sincof_p2); + y2 = v_mul(y2, _vxx); + y2 = v_fma(y2, _vx, _vx); + + ysin = v_select(poly_mask, y2, y1); + ycos = v_select(poly_mask, y1, y2); + ysin = v_select(sign_mask_sin, ysin, v_xor(v_neg_zero, ysin)); + ycos = v_select(sign_mask_cos, v_xor(v_neg_zero, ycos), ycos); + + // sincos(NAN) -> NAN, sincos(±INF) -> NAN + _TpVec16F mask_inf = v_eq(_vx, v_reinterpret_as_f16(v_setall_<_TpVec16S>((short)0x7c00))); + _TpVec16F mask_nan = v_or(mask_inf, v_ne(x, x)); + ysin = v_select(mask_nan, v_nan, ysin); + ycos = v_select(mask_nan, v_nan, ycos); +} + +template +inline _TpVec16F v_sin_default_16f(const _TpVec16F &x) { + _TpVec16F ysin, ycos; + v_sincos_default_16f<_TpVec16F, _TpVec16S>(x, ysin, ycos); + return ysin; +} + +template +inline _TpVec16F v_cos_default_16f(const _TpVec16F &x) { + _TpVec16F ysin, ycos; + v_sincos_default_16f<_TpVec16F, _TpVec16S>(x, ysin, ycos); + return ycos; +} + + +template +inline void v_sincos_default_32f(const _TpVec32F &x, _TpVec32F &ysin, _TpVec32F &ycos) { + const _TpVec32F v_cephes_FOPI = v_setall_<_TpVec32F>(1.27323954473516f); // 4 / M_PI + const _TpVec32F v_minus_DP1 = v_setall_<_TpVec32F>(-0.78515625f); + const _TpVec32F v_minus_DP2 = v_setall_<_TpVec32F>(-2.4187564849853515625E-4f); + const _TpVec32F v_minus_DP3 = v_setall_<_TpVec32F>(-3.77489497744594108E-8f); + const _TpVec32F v_sincof_p0 = v_setall_<_TpVec32F>(-1.9515295891E-4f); + const _TpVec32F v_sincof_p1 = v_setall_<_TpVec32F>(8.3321608736E-3f); + const _TpVec32F v_sincof_p2 = v_setall_<_TpVec32F>(-1.6666654611E-1f); + const _TpVec32F v_coscof_p0 = v_setall_<_TpVec32F>(2.443315711809948E-5f); + const _TpVec32F v_coscof_p1 = v_setall_<_TpVec32F>(-1.388731625493765E-3f); + const _TpVec32F v_coscof_p2 = v_setall_<_TpVec32F>(4.166664568298827E-2f); + const _TpVec32F v_nan = v_reinterpret_as_f32(v_setall_<_TpVec32S>((int)0x7fc00000)); + const _TpVec32F v_neg_zero = v_setall_<_TpVec32F>(-0.f); + + _TpVec32F _vx, _vy, sign_mask_sin, sign_mask_cos; + _TpVec32S emm2; + + sign_mask_sin = v_lt(x, v_setzero_<_TpVec32F>()); + _vx = v_abs(x); + _vy = v_mul(_vx, v_cephes_FOPI); + + emm2 = v_trunc(_vy); + emm2 = v_add(emm2, v_setall_<_TpVec32S>(1)); + emm2 = v_and(emm2, v_setall_<_TpVec32S>(~1)); + _vy = v_cvt_f32(emm2); + + _TpVec32F poly_mask = v_reinterpret_as_f32(v_eq(v_and(emm2, v_setall_<_TpVec32S>(2)), v_setall_<_TpVec32S>(0))); + + _vx = v_fma(_vy, v_minus_DP1, _vx); + _vx = v_fma(_vy, v_minus_DP2, _vx); + _vx = v_fma(_vy, v_minus_DP3, _vx); + + sign_mask_sin = v_xor(sign_mask_sin, v_reinterpret_as_f32(v_eq(v_and(emm2, v_setall_<_TpVec32S>(4)), v_setall_<_TpVec32S>(0)))); + sign_mask_cos = v_reinterpret_as_f32(v_eq(v_and(v_sub(emm2, v_setall_<_TpVec32S>(2)), v_setall_<_TpVec32S>(4)), v_setall_<_TpVec32S>(0))); + + _TpVec32F _vxx = v_mul(_vx, _vx); + _TpVec32F y1, y2; + + y1 = v_fma(v_coscof_p0, _vxx, v_coscof_p1); + y1 = v_fma(y1, _vxx, v_coscof_p2); + y1 = v_fma(y1, _vxx, v_setall_<_TpVec32F>(-0.5f)); + y1 = v_fma(y1, _vxx, v_setall_<_TpVec32F>(1.f)); + + y2 = v_fma(v_sincof_p0, _vxx, v_sincof_p1); + y2 = v_fma(y2, _vxx, v_sincof_p2); + y2 = v_mul(y2, _vxx); + y2 = v_fma(y2, _vx, _vx); + + ysin = v_select(poly_mask, y2, y1); + ycos = v_select(poly_mask, y1, y2); + ysin = v_select(sign_mask_sin, ysin, v_xor(v_neg_zero, ysin)); + ycos = v_select(sign_mask_cos, v_xor(v_neg_zero, ycos), ycos); + + // sincos(NAN) -> NAN, sincos(±INF) -> NAN + _TpVec32F mask_inf = v_eq(_vx, v_reinterpret_as_f32(v_setall_<_TpVec32S>((int)0x7f800000))); + _TpVec32F mask_nan = v_or(mask_inf, v_ne(x, x)); + ysin = v_select(mask_nan, v_nan, ysin); + ycos = v_select(mask_nan, v_nan, ycos); +} + +template +inline _TpVec32F v_sin_default_32f(const _TpVec32F &x) { + _TpVec32F ysin, ycos; + v_sincos_default_32f<_TpVec32F, _TpVec32S>(x, ysin, ycos); + return ysin; +} + +template +inline _TpVec32F v_cos_default_32f(const _TpVec32F &x) { + _TpVec32F ysin, ycos; + v_sincos_default_32f<_TpVec32F, _TpVec32S>(x, ysin, ycos); + return ycos; +} + +template +inline void v_sincos_default_64f(const _TpVec64F &x, _TpVec64F &ysin, _TpVec64F &ycos) { + const _TpVec64F v_cephes_FOPI = v_setall_<_TpVec64F>(1.2732395447351626861510701069801148); // 4 / M_PI + const _TpVec64F v_minus_DP1 = v_setall_<_TpVec64F>(-7.853981554508209228515625E-1); + const _TpVec64F v_minus_DP2 = v_setall_<_TpVec64F>(-7.94662735614792836714E-9); + const _TpVec64F v_minus_DP3 = v_setall_<_TpVec64F>(-3.06161699786838294307E-17); + const _TpVec64F v_sin_C1 = v_setall_<_TpVec64F>(1.58962301576546568060E-10); + const _TpVec64F v_sin_C2 = v_setall_<_TpVec64F>(-2.50507477628578072866E-8); + const _TpVec64F v_sin_C3 = v_setall_<_TpVec64F>(2.75573136213857245213E-6); + const _TpVec64F v_sin_C4 = v_setall_<_TpVec64F>(-1.98412698295895385996E-4); + const _TpVec64F v_sin_C5 = v_setall_<_TpVec64F>(8.33333333332211858878E-3); + const _TpVec64F v_sin_C6 = v_setall_<_TpVec64F>(-1.66666666666666307295E-1); + const _TpVec64F v_cos_C1 = v_setall_<_TpVec64F>(-1.13585365213876817300E-11); + const _TpVec64F v_cos_C2 = v_setall_<_TpVec64F>(2.08757008419747316778E-9); + const _TpVec64F v_cos_C3 = v_setall_<_TpVec64F>(-2.75573141792967388112E-7); + const _TpVec64F v_cos_C4 = v_setall_<_TpVec64F>(2.48015872888517045348E-5); + const _TpVec64F v_cos_C5 = v_setall_<_TpVec64F>(-1.38888888888730564116E-3); + const _TpVec64F v_cos_C6 = v_setall_<_TpVec64F>(4.16666666666665929218E-2); + const _TpVec64F v_nan = v_reinterpret_as_f64(v_setall_<_TpVec64S>((int64)0x7ff8000000000000)); + const _TpVec64F v_neg_zero = v_setall_<_TpVec64F>(-0.0); + + _TpVec64F _vx, _vy, sign_mask_sin, sign_mask_cos; + _TpVec64S emm2; + + sign_mask_sin = v_lt(x, v_setzero_<_TpVec64F>()); + _vx = v_abs(x); + _vy = v_mul(_vx, v_cephes_FOPI); + + emm2 = v_expand_low(v_trunc(_vy)); + emm2 = v_add(emm2, v_setall_<_TpVec64S>((int64)1)); + emm2 = v_and(emm2, v_setall_<_TpVec64S>((int64)~1)); + _vy = v_cvt_f64(emm2); + + _TpVec64F poly_mask = v_reinterpret_as_f64(v_eq(v_and(emm2, v_setall_<_TpVec64S>((int64)2)), v_setall_<_TpVec64S>((int64)0))); + + _vx = v_fma(_vy, v_minus_DP1, _vx); + _vx = v_fma(_vy, v_minus_DP2, _vx); + _vx = v_fma(_vy, v_minus_DP3, _vx); + + sign_mask_sin = v_xor(sign_mask_sin, v_reinterpret_as_f64(v_eq(v_and(emm2, v_setall_<_TpVec64S>((int64)4)), v_setall_<_TpVec64S>((int64)0)))); + sign_mask_cos = v_reinterpret_as_f64(v_eq(v_and(v_sub(emm2, v_setall_<_TpVec64S>((int64)2)), v_setall_<_TpVec64S>((int64)4)), v_setall_<_TpVec64S>((int64)0))); + + _TpVec64F _vxx = v_mul(_vx, _vx); + _TpVec64F y1, y2; + + y1 = v_fma(v_cos_C1, _vxx, v_cos_C2); + y1 = v_fma(y1, _vxx, v_cos_C3); + y1 = v_fma(y1, _vxx, v_cos_C4); + y1 = v_fma(y1, _vxx, v_cos_C5); + y1 = v_fma(y1, _vxx, v_cos_C6); + y1 = v_fma(y1, _vxx, v_setall_<_TpVec64F>(-0.5)); + y1 = v_fma(y1, _vxx, v_setall_<_TpVec64F>(1.0)); + + y2 = v_fma(v_sin_C1, _vxx, v_sin_C2); + y2 = v_fma(y2, _vxx, v_sin_C3); + y2 = v_fma(y2, _vxx, v_sin_C4); + y2 = v_fma(y2, _vxx, v_sin_C5); + y2 = v_fma(y2, _vxx, v_sin_C6); + y2 = v_mul(y2, _vxx); + y2 = v_fma(y2, _vx, _vx); + + ysin = v_select(poly_mask, y2, y1); + ycos = v_select(poly_mask, y1, y2); + ysin = v_select(sign_mask_sin, ysin, v_xor(v_neg_zero, ysin)); + ycos = v_select(sign_mask_cos, v_xor(v_neg_zero, ycos), ycos); + + // sincos(NAN) -> NAN, sincos(±INF) -> NAN + _TpVec64F mask_inf = v_eq(_vx, v_reinterpret_as_f64(v_setall_<_TpVec64S>((int64)0x7ff0000000000000))); + _TpVec64F mask_nan = v_or(mask_inf, v_ne(x, x)); + ysin = v_select(mask_nan, v_nan, ysin); + ycos = v_select(mask_nan, v_nan, ycos); +} + +template +inline _TpVec64F v_sin_default_64f(const _TpVec64F &x) { + _TpVec64F ysin, ycos; + v_sincos_default_64f<_TpVec64F, _TpVec64S>(x, ysin, ycos); + return ysin; +} + +template +inline _TpVec64F v_cos_default_64f(const _TpVec64F &x) { + _TpVec64F ysin, ycos; + v_sincos_default_64f<_TpVec64F, _TpVec64S>(x, ysin, ycos); + return ycos; +} +//! @} + + +/* This implementation is derived from the approximation approach of Error Function (Erf) from PyTorch + https://github.com/pytorch/pytorch/blob/9c50ecc84b9a6e699a7f058891b889aafbf976c7/aten/src/ATen/cpu/vec/vec512/vec512_float.h#L189-L220 +*/ + +//! @name Error Function +//! @{ +template +inline _TpVec32F v_erf_default_32f(const _TpVec32F &v) { + const _TpVec32F coef0 = v_setall_<_TpVec32F>(0.3275911f), + coef1 = v_setall_<_TpVec32F>(1.061405429f), + coef2 = v_setall_<_TpVec32F>(-1.453152027f), + coef3 = v_setall_<_TpVec32F>(1.421413741f), + coef4 = v_setall_<_TpVec32F>(-0.284496736f), + coef5 = v_setall_<_TpVec32F>(0.254829592f), + ones = v_setall_<_TpVec32F>(1.0f), + neg_zeros = v_setall_<_TpVec32F>(-0.f); + _TpVec32F t = v_abs(v); + // sign(v) + _TpVec32F sign_mask = v_and(neg_zeros, v); + + t = v_div(ones, v_fma(coef0, t, ones)); + _TpVec32F r = v_fma(coef1, t, coef2); + r = v_fma(r, t, coef3); + r = v_fma(r, t, coef4); + r = v_fma(r, t, coef5); + // - v * v + _TpVec32F v2 = v_mul(v, v); + _TpVec32F mv2 = v_xor(neg_zeros, v2); + // - exp(- v * v) + _TpVec32F exp = v_exp_default_32f<_TpVec32F, _TpVec32S>(mv2); + _TpVec32F neg_exp = v_xor(neg_zeros, exp); + _TpVec32F res = v_mul(t, neg_exp); + res = v_fma(r, res, ones); + return v_xor(sign_mask, res); +} +//! @} + +#endif // OPENCV_HAL_INTRIN_MATH_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_msa.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_msa.hpp index 3917faa292..98b753c42e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_msa.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_msa.hpp @@ -1,1886 +1,1886 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_HAL_INTRIN_MSA_HPP -#define OPENCV_HAL_INTRIN_MSA_HPP - -#include -#include "opencv2/core/utility.hpp" - -namespace cv -{ - -//! @cond IGNORED -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -#define CV_SIMD128 1 - -//MSA implements 128-bit wide vector registers shared with the 64-bit wide floating-point unit registers. -//MSA and FPU can not be both present, unless the FPU has 64-bit floating-point registers. -#define CV_SIMD128_64F 1 - -struct v_uint8x16 -{ - typedef uchar lane_type; - enum { nlanes = 16 }; - - v_uint8x16() {} - explicit v_uint8x16(v16u8 v) : val(v) {} - v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, - uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) - { - uchar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; - val = msa_ld1q_u8(v); - } - - uchar get0() const - { - return msa_getq_lane_u8(val, 0); - } - - v16u8 val; -}; - -struct v_int8x16 -{ - typedef schar lane_type; - enum { nlanes = 16 }; - - v_int8x16() {} - explicit v_int8x16(v16i8 v) : val(v) {} - v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, - schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) - { - schar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; - val = msa_ld1q_s8(v); - } - - schar get0() const - { - return msa_getq_lane_s8(val, 0); - } - - v16i8 val; -}; - -struct v_uint16x8 -{ - typedef ushort lane_type; - enum { nlanes = 8 }; - - v_uint16x8() {} - explicit v_uint16x8(v8u16 v) : val(v) {} - v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) - { - ushort v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; - val = msa_ld1q_u16(v); - } - - ushort get0() const - { - return msa_getq_lane_u16(val, 0); - } - - v8u16 val; -}; - -struct v_int16x8 -{ - typedef short lane_type; - enum { nlanes = 8 }; - - v_int16x8() {} - explicit v_int16x8(v8i16 v) : val(v) {} - v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) - { - short v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; - val = msa_ld1q_s16(v); - } - - short get0() const - { - return msa_getq_lane_s16(val, 0); - } - - v8i16 val; -}; - -struct v_uint32x4 -{ - typedef unsigned int lane_type; - enum { nlanes = 4 }; - - v_uint32x4() {} - explicit v_uint32x4(v4u32 v) : val(v) {} - v_uint32x4(unsigned int v0, unsigned int v1, unsigned int v2, unsigned int v3) - { - unsigned int v[] = {v0, v1, v2, v3}; - val = msa_ld1q_u32(v); - } - - unsigned int get0() const - { - return msa_getq_lane_u32(val, 0); - } - - v4u32 val; -}; - -struct v_int32x4 -{ - typedef int lane_type; - enum { nlanes = 4 }; - - v_int32x4() {} - explicit v_int32x4(v4i32 v) : val(v) {} - v_int32x4(int v0, int v1, int v2, int v3) - { - int v[] = {v0, v1, v2, v3}; - val = msa_ld1q_s32(v); - } - - int get0() const - { - return msa_getq_lane_s32(val, 0); - } - - v4i32 val; -}; - -struct v_float32x4 -{ - typedef float lane_type; - enum { nlanes = 4 }; - - v_float32x4() {} - explicit v_float32x4(v4f32 v) : val(v) {} - v_float32x4(float v0, float v1, float v2, float v3) - { - float v[] = {v0, v1, v2, v3}; - val = msa_ld1q_f32(v); - } - - float get0() const - { - return msa_getq_lane_f32(val, 0); - } - - v4f32 val; -}; - -struct v_uint64x2 -{ - typedef uint64 lane_type; - enum { nlanes = 2 }; - - v_uint64x2() {} - explicit v_uint64x2(v2u64 v) : val(v) {} - v_uint64x2(uint64 v0, uint64 v1) - { - uint64 v[] = {v0, v1}; - val = msa_ld1q_u64(v); - } - - uint64 get0() const - { - return msa_getq_lane_u64(val, 0); - } - - v2u64 val; -}; - -struct v_int64x2 -{ - typedef int64 lane_type; - enum { nlanes = 2 }; - - v_int64x2() {} - explicit v_int64x2(v2i64 v) : val(v) {} - v_int64x2(int64 v0, int64 v1) - { - int64 v[] = {v0, v1}; - val = msa_ld1q_s64(v); - } - - int64 get0() const - { - return msa_getq_lane_s64(val, 0); - } - - v2i64 val; -}; - -struct v_float64x2 -{ - typedef double lane_type; - enum { nlanes = 2 }; - - v_float64x2() {} - explicit v_float64x2(v2f64 v) : val(v) {} - v_float64x2(double v0, double v1) - { - double v[] = {v0, v1}; - val = msa_ld1q_f64(v); - } - - double get0() const - { - return msa_getq_lane_f64(val, 0); - } - - v2f64 val; -}; - -#define OPENCV_HAL_IMPL_MSA_INIT(_Tpv, _Tp, suffix) \ -inline v_##_Tpv v_setzero_##suffix() { return v_##_Tpv(msa_dupq_n_##suffix((_Tp)0)); } \ -inline v_##_Tpv v_setall_##suffix(_Tp v) { return v_##_Tpv(msa_dupq_n_##suffix(v)); } \ -template <> inline v_##_Tpv v_setzero_() { return v_setzero_##suffix(); } \ -template <> inline v_##_Tpv v_setall_(_Tp v) { return v_setall_##suffix(v); } \ -inline v_uint8x16 v_reinterpret_as_u8(const v_##_Tpv& v) { return v_uint8x16(MSA_TPV_REINTERPRET(v16u8, v.val)); } \ -inline v_int8x16 v_reinterpret_as_s8(const v_##_Tpv& v) { return v_int8x16(MSA_TPV_REINTERPRET(v16i8, v.val)); } \ -inline v_uint16x8 v_reinterpret_as_u16(const v_##_Tpv& v) { return v_uint16x8(MSA_TPV_REINTERPRET(v8u16, v.val)); } \ -inline v_int16x8 v_reinterpret_as_s16(const v_##_Tpv& v) { return v_int16x8(MSA_TPV_REINTERPRET(v8i16, v.val)); } \ -inline v_uint32x4 v_reinterpret_as_u32(const v_##_Tpv& v) { return v_uint32x4(MSA_TPV_REINTERPRET(v4u32, v.val)); } \ -inline v_int32x4 v_reinterpret_as_s32(const v_##_Tpv& v) { return v_int32x4(MSA_TPV_REINTERPRET(v4i32, v.val)); } \ -inline v_uint64x2 v_reinterpret_as_u64(const v_##_Tpv& v) { return v_uint64x2(MSA_TPV_REINTERPRET(v2u64, v.val)); } \ -inline v_int64x2 v_reinterpret_as_s64(const v_##_Tpv& v) { return v_int64x2(MSA_TPV_REINTERPRET(v2i64, v.val)); } \ -inline v_float32x4 v_reinterpret_as_f32(const v_##_Tpv& v) { return v_float32x4(MSA_TPV_REINTERPRET(v4f32, v.val)); } \ -inline v_float64x2 v_reinterpret_as_f64(const v_##_Tpv& v) { return v_float64x2(MSA_TPV_REINTERPRET(v2f64, v.val)); } - -OPENCV_HAL_IMPL_MSA_INIT(uint8x16, uchar, u8) -OPENCV_HAL_IMPL_MSA_INIT(int8x16, schar, s8) -OPENCV_HAL_IMPL_MSA_INIT(uint16x8, ushort, u16) -OPENCV_HAL_IMPL_MSA_INIT(int16x8, short, s16) -OPENCV_HAL_IMPL_MSA_INIT(uint32x4, unsigned int, u32) -OPENCV_HAL_IMPL_MSA_INIT(int32x4, int, s32) -OPENCV_HAL_IMPL_MSA_INIT(uint64x2, uint64, u64) -OPENCV_HAL_IMPL_MSA_INIT(int64x2, int64, s64) -OPENCV_HAL_IMPL_MSA_INIT(float32x4, float, f32) -OPENCV_HAL_IMPL_MSA_INIT(float64x2, double, f64) - -#define OPENCV_HAL_IMPL_MSA_PACK(_Tpvec, _Tpwvec, pack, mov, rshr) \ -inline _Tpvec v_##pack(const _Tpwvec& a, const _Tpwvec& b) \ -{ \ - return _Tpvec(mov(a.val, b.val)); \ -} \ -template inline \ -_Tpvec v_rshr_##pack(const _Tpwvec& a, const _Tpwvec& b) \ -{ \ - return _Tpvec(rshr(a.val, b.val, n)); \ -} - -OPENCV_HAL_IMPL_MSA_PACK(v_uint8x16, v_uint16x8, pack, msa_qpack_u16, msa_qrpackr_u16) -OPENCV_HAL_IMPL_MSA_PACK(v_int8x16, v_int16x8, pack, msa_qpack_s16, msa_qrpackr_s16) -OPENCV_HAL_IMPL_MSA_PACK(v_uint16x8, v_uint32x4, pack, msa_qpack_u32, msa_qrpackr_u32) -OPENCV_HAL_IMPL_MSA_PACK(v_int16x8, v_int32x4, pack, msa_qpack_s32, msa_qrpackr_s32) -OPENCV_HAL_IMPL_MSA_PACK(v_uint32x4, v_uint64x2, pack, msa_pack_u64, msa_rpackr_u64) -OPENCV_HAL_IMPL_MSA_PACK(v_int32x4, v_int64x2, pack, msa_pack_s64, msa_rpackr_s64) -OPENCV_HAL_IMPL_MSA_PACK(v_uint8x16, v_int16x8, pack_u, msa_qpacku_s16, msa_qrpackru_s16) -OPENCV_HAL_IMPL_MSA_PACK(v_uint16x8, v_int32x4, pack_u, msa_qpacku_s32, msa_qrpackru_s32) - -#define OPENCV_HAL_IMPL_MSA_PACK_STORE(_Tpvec, _Tp, hreg, suffix, _Tpwvec, pack, mov, rshr) \ -inline void v_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ -{ \ - hreg a1 = mov(a.val); \ - msa_st1_##suffix(ptr, a1); \ -} \ -template inline \ -void v_rshr_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ -{ \ - hreg a1 = rshr(a.val, n); \ - msa_st1_##suffix(ptr, a1); \ -} - -OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint8x16, uchar, v8u8, u8, v_uint16x8, pack, msa_qmovn_u16, msa_qrshrn_n_u16) -OPENCV_HAL_IMPL_MSA_PACK_STORE(v_int8x16, schar, v8i8, s8, v_int16x8, pack, msa_qmovn_s16, msa_qrshrn_n_s16) -OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint16x8, ushort, v4u16, u16, v_uint32x4, pack, msa_qmovn_u32, msa_qrshrn_n_u32) -OPENCV_HAL_IMPL_MSA_PACK_STORE(v_int16x8, short, v4i16, s16, v_int32x4, pack, msa_qmovn_s32, msa_qrshrn_n_s32) -OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint32x4, unsigned, v2u32, u32, v_uint64x2, pack, msa_movn_u64, msa_rshrn_n_u64) -OPENCV_HAL_IMPL_MSA_PACK_STORE(v_int32x4, int, v2i32, s32, v_int64x2, pack, msa_movn_s64, msa_rshrn_n_s64) -OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint8x16, uchar, v8u8, u8, v_int16x8, pack_u, msa_qmovun_s16, msa_qrshrun_n_s16) -OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint16x8, ushort, v4u16, u16, v_int32x4, pack_u, msa_qmovun_s32, msa_qrshrun_n_s32) - -// pack boolean -inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) -{ - return v_uint8x16(msa_pack_u16(a.val, b.val)); -} - -inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, - const v_uint32x4& c, const v_uint32x4& d) -{ - return v_uint8x16(msa_pack_u16(msa_pack_u32(a.val, b.val), msa_pack_u32(c.val, d.val))); -} - -inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, - const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, - const v_uint64x2& g, const v_uint64x2& h) -{ - v8u16 abcd = msa_pack_u32(msa_pack_u64(a.val, b.val), msa_pack_u64(c.val, d.val)); - v8u16 efgh = msa_pack_u32(msa_pack_u64(e.val, f.val), msa_pack_u64(g.val, h.val)); - return v_uint8x16(msa_pack_u16(abcd, efgh)); -} - -inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, - const v_float32x4& m3) -{ - v4f32 v0 = v.val; - v4f32 res = msa_mulq_lane_f32(m0.val, v0, 0); - res = msa_mlaq_lane_f32(res, m1.val, v0, 1); - res = msa_mlaq_lane_f32(res, m2.val, v0, 2); - res = msa_mlaq_lane_f32(res, m3.val, v0, 3); - return v_float32x4(res); -} - -inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, - const v_float32x4& a) -{ - v4f32 v0 = v.val; - v4f32 res = msa_mulq_lane_f32(m0.val, v0, 0); - res = msa_mlaq_lane_f32(res, m1.val, v0, 1); - res = msa_mlaq_lane_f32(res, m2.val, v0, 2); - res = msa_addq_f32(res, a.val); - return v_float32x4(res); -} - -#define OPENCV_HAL_IMPL_MSA_BIN_OP(bin_op, _Tpvec, intrin) \ -inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(intrin(a.val, b.val)); \ -} - -OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_uint8x16, msa_qaddq_u8) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_uint8x16, msa_qsubq_u8) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_int8x16, msa_qaddq_s8) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_int8x16, msa_qsubq_s8) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_uint16x8, msa_qaddq_u16) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_uint16x8, msa_qsubq_u16) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_int16x8, msa_qaddq_s16) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_int16x8, msa_qsubq_s16) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_int32x4, msa_addq_s32) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_int32x4, msa_subq_s32) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_mul, v_int32x4, msa_mulq_s32) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_uint32x4, msa_addq_u32) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_uint32x4, msa_subq_u32) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_mul, v_uint32x4, msa_mulq_u32) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_float32x4, msa_addq_f32) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_float32x4, msa_subq_f32) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_mul, v_float32x4, msa_mulq_f32) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_int64x2, msa_addq_s64) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_int64x2, msa_subq_s64) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_uint64x2, msa_addq_u64) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_uint64x2, msa_subq_u64) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_div, v_float32x4, msa_divq_f32) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_float64x2, msa_addq_f64) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_float64x2, msa_subq_f64) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_mul, v_float64x2, msa_mulq_f64) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_div, v_float64x2, msa_divq_f64) - -// saturating multiply 8-bit, 16-bit -#define OPENCV_HAL_IMPL_MSA_MUL_SAT(_Tpvec, _Tpwvec) \ -inline _Tpvec v_mul(const _Tpvec& a, const _Tpvec& b) \ -{ \ - _Tpwvec c, d; \ - v_mul_expand(a, b, c, d); \ - return v_pack(c, d); \ -} - -OPENCV_HAL_IMPL_MSA_MUL_SAT(v_int8x16, v_int16x8) -OPENCV_HAL_IMPL_MSA_MUL_SAT(v_uint8x16, v_uint16x8) -OPENCV_HAL_IMPL_MSA_MUL_SAT(v_int16x8, v_int32x4) -OPENCV_HAL_IMPL_MSA_MUL_SAT(v_uint16x8, v_uint32x4) - -// Multiply and expand -inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b, - v_int16x8& c, v_int16x8& d) -{ - v16i8 a_lo, a_hi, b_lo, b_hi; - - ILVRL_B2_SB(a.val, msa_dupq_n_s8(0), a_lo, a_hi); - ILVRL_B2_SB(b.val, msa_dupq_n_s8(0), b_lo, b_hi); - c.val = msa_mulq_s16(msa_paddlq_s8(a_lo), msa_paddlq_s8(b_lo)); - d.val = msa_mulq_s16(msa_paddlq_s8(a_hi), msa_paddlq_s8(b_hi)); -} - -inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b, - v_uint16x8& c, v_uint16x8& d) -{ - v16u8 a_lo, a_hi, b_lo, b_hi; - - ILVRL_B2_UB(a.val, msa_dupq_n_u8(0), a_lo, a_hi); - ILVRL_B2_UB(b.val, msa_dupq_n_u8(0), b_lo, b_hi); - c.val = msa_mulq_u16(msa_paddlq_u8(a_lo), msa_paddlq_u8(b_lo)); - d.val = msa_mulq_u16(msa_paddlq_u8(a_hi), msa_paddlq_u8(b_hi)); -} - -inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, - v_int32x4& c, v_int32x4& d) -{ - v8i16 a_lo, a_hi, b_lo, b_hi; - - ILVRL_H2_SH(a.val, msa_dupq_n_s16(0), a_lo, a_hi); - ILVRL_H2_SH(b.val, msa_dupq_n_s16(0), b_lo, b_hi); - c.val = msa_mulq_s32(msa_paddlq_s16(a_lo), msa_paddlq_s16(b_lo)); - d.val = msa_mulq_s32(msa_paddlq_s16(a_hi), msa_paddlq_s16(b_hi)); -} - -inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, - v_uint32x4& c, v_uint32x4& d) -{ - v8u16 a_lo, a_hi, b_lo, b_hi; - - ILVRL_H2_UH(a.val, msa_dupq_n_u16(0), a_lo, a_hi); - ILVRL_H2_UH(b.val, msa_dupq_n_u16(0), b_lo, b_hi); - c.val = msa_mulq_u32(msa_paddlq_u16(a_lo), msa_paddlq_u16(b_lo)); - d.val = msa_mulq_u32(msa_paddlq_u16(a_hi), msa_paddlq_u16(b_hi)); -} - -inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, - v_uint64x2& c, v_uint64x2& d) -{ - v4u32 a_lo, a_hi, b_lo, b_hi; - - ILVRL_W2_UW(a.val, msa_dupq_n_u32(0), a_lo, a_hi); - ILVRL_W2_UW(b.val, msa_dupq_n_u32(0), b_lo, b_hi); - c.val = msa_mulq_u64(msa_paddlq_u32(a_lo), msa_paddlq_u32(b_lo)); - d.val = msa_mulq_u64(msa_paddlq_u32(a_hi), msa_paddlq_u32(b_hi)); -} - -inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) -{ - v8i16 a_lo, a_hi, b_lo, b_hi; - - ILVRL_H2_SH(a.val, msa_dupq_n_s16(0), a_lo, a_hi); - ILVRL_H2_SH(b.val, msa_dupq_n_s16(0), b_lo, b_hi); - - return v_int16x8(msa_packr_s32(msa_mulq_s32(msa_paddlq_s16(a_lo), msa_paddlq_s16(b_lo)), - msa_mulq_s32(msa_paddlq_s16(a_hi), msa_paddlq_s16(b_hi)), 16)); -} - -inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) -{ - v8u16 a_lo, a_hi, b_lo, b_hi; - - ILVRL_H2_UH(a.val, msa_dupq_n_u16(0), a_lo, a_hi); - ILVRL_H2_UH(b.val, msa_dupq_n_u16(0), b_lo, b_hi); - - return v_uint16x8(msa_packr_u32(msa_mulq_u32(msa_paddlq_u16(a_lo), msa_paddlq_u16(b_lo)), - msa_mulq_u32(msa_paddlq_u16(a_hi), msa_paddlq_u16(b_hi)), 16)); -} - -//////// Dot Product //////// - -// 16 >> 32 -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) -{ return v_int32x4(msa_dotp_s_w(a.val, b.val)); } -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ return v_int32x4(msa_dpadd_s_w(c.val , a.val, b.val)); } - -// 32 >> 64 -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) -{ return v_int64x2(msa_dotp_s_d(a.val, b.val)); } -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ return v_int64x2(msa_dpadd_s_d(c.val , a.val, b.val)); } - -// 8 >> 32 -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) -{ - v8u16 even_a = msa_shrq_n_u16(msa_shlq_n_u16(MSA_TPV_REINTERPRET(v8u16, a.val), 8), 8); - v8u16 odd_a = msa_shrq_n_u16(MSA_TPV_REINTERPRET(v8u16, a.val), 8); - v8u16 even_b = msa_shrq_n_u16(msa_shlq_n_u16(MSA_TPV_REINTERPRET(v8u16, b.val), 8), 8); - v8u16 odd_b = msa_shrq_n_u16(MSA_TPV_REINTERPRET(v8u16, b.val), 8); - v4u32 prod = msa_dotp_u_w(even_a, even_b); - return v_uint32x4(msa_dpadd_u_w(prod, odd_a, odd_b)); -} -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) -{ - v8u16 even_a = msa_shrq_n_u16(msa_shlq_n_u16(MSA_TPV_REINTERPRET(v8u16, a.val), 8), 8); - v8u16 odd_a = msa_shrq_n_u16(MSA_TPV_REINTERPRET(v8u16, a.val), 8); - v8u16 even_b = msa_shrq_n_u16(msa_shlq_n_u16(MSA_TPV_REINTERPRET(v8u16, b.val), 8), 8); - v8u16 odd_b = msa_shrq_n_u16(MSA_TPV_REINTERPRET(v8u16, b.val), 8); - v4u32 prod = msa_dpadd_u_w(c.val, even_a, even_b); - return v_uint32x4(msa_dpadd_u_w(prod, odd_a, odd_b)); -} - -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) -{ - v8i16 prod = msa_dotp_s_h(a.val, b.val); - return v_int32x4(msa_hadd_s32(prod, prod)); -} -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, - const v_int32x4& c) -{ return v_dotprod_expand(a, b) + c; } - -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) -{ - v4u32 even_a = msa_shrq_n_u32(msa_shlq_n_u32(MSA_TPV_REINTERPRET(v4u32, a.val), 16), 16); - v4u32 odd_a = msa_shrq_n_u32(MSA_TPV_REINTERPRET(v4u32, a.val), 16); - v4u32 even_b = msa_shrq_n_u32(msa_shlq_n_u32(MSA_TPV_REINTERPRET(v4u32, b.val), 16), 16); - v4u32 odd_b = msa_shrq_n_u32(MSA_TPV_REINTERPRET(v4u32, b.val), 16); - v2u64 prod = msa_dotp_u_d(even_a, even_b); - return v_uint64x2(msa_dpadd_u_d(prod, odd_a, odd_b)); -} -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, - const v_uint64x2& c) -{ - v4u32 even_a = msa_shrq_n_u32(msa_shlq_n_u32(MSA_TPV_REINTERPRET(v4u32, a.val), 16), 16); - v4u32 odd_a = msa_shrq_n_u32(MSA_TPV_REINTERPRET(v4u32, a.val), 16); - v4u32 even_b = msa_shrq_n_u32(msa_shlq_n_u32(MSA_TPV_REINTERPRET(v4u32, b.val), 16), 16); - v4u32 odd_b = msa_shrq_n_u32(MSA_TPV_REINTERPRET(v4u32, b.val), 16); - v2u64 prod = msa_dpadd_u_d(c.val, even_a, even_b); - return v_uint64x2(msa_dpadd_u_d(prod, odd_a, odd_b)); -} - -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) -{ - v4i32 prod = msa_dotp_s_w(a.val, b.val); - return v_int64x2(msa_hadd_s64(prod, prod)); -} -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 32 >> 64f -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) -{ return v_cvt_f64(v_dotprod(a, b)); } -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - - -//////// Fast Dot Product //////// - -// 16 >> 32 -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) -{ return v_dotprod(a, b); } -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ return v_dotprod(a, b, c); } - -// 32 >> 64 -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) -{ return v_dotprod(a, b); } -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ return v_dotprod(a, b, c); } - -// 8 >> 32 -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) -{ return v_dotprod_expand(a, b); } -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) -{ return v_dotprod_expand(a, b, c); } -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) -{ return v_dotprod_expand(a, b); } -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) -{ return v_dotprod_expand(a, b, c); } - -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) -{ return v_dotprod_expand(a, b); } -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) -{ return v_dotprod_expand(a, b, c); } -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) -{ return v_dotprod_expand(a, b); } -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) -{ return v_dotprod_expand(a, b, c); } - -// 32 >> 64f -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) -{ return v_dotprod_expand(a, b); } -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) -{ return v_dotprod_expand(a, b, c); } - -#define OPENCV_HAL_IMPL_MSA_LOGIC_OP(_Tpvec, _Tpv, suffix) \ -OPENCV_HAL_IMPL_MSA_BIN_OP(v_and, _Tpvec, msa_andq_##suffix) \ -OPENCV_HAL_IMPL_MSA_BIN_OP(v_or, _Tpvec, msa_orrq_##suffix) \ -OPENCV_HAL_IMPL_MSA_BIN_OP(v_xor, _Tpvec, msa_eorq_##suffix) \ -inline _Tpvec v_not(const _Tpvec& a) \ -{ \ - return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_mvnq_u8(MSA_TPV_REINTERPRET(v16u8, a.val)))); \ -} - -OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_uint8x16, v16u8, u8) -OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_int8x16, v16i8, s8) -OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_uint16x8, v8u16, u16) -OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_int16x8, v8i16, s16) -OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_uint32x4, v4u32, u32) -OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_int32x4, v4i32, s32) -OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_uint64x2, v2u64, u64) -OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_int64x2, v2i64, s64) - -#define OPENCV_HAL_IMPL_MSA_FLT_BIT_OP(bin_op, intrin) \ -inline v_float32x4 bin_op(const v_float32x4& a, const v_float32x4& b) \ -{ \ - return v_float32x4(MSA_TPV_REINTERPRET(v4f32, intrin(MSA_TPV_REINTERPRET(v4i32, a.val), MSA_TPV_REINTERPRET(v4i32, b.val)))); \ -} - -OPENCV_HAL_IMPL_MSA_FLT_BIT_OP(v_and, msa_andq_s32) -OPENCV_HAL_IMPL_MSA_FLT_BIT_OP(v_or, msa_orrq_s32) -OPENCV_HAL_IMPL_MSA_FLT_BIT_OP(v_xor, msa_eorq_s32) - -inline v_float32x4 v_not(const v_float32x4& a) -{ - return v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_mvnq_s32(MSA_TPV_REINTERPRET(v4i32, a.val)))); -} - -/* v_abs */ -#define OPENCV_HAL_IMPL_MSA_ABS(_Tpuvec, _Tpsvec, usuffix, ssuffix) \ -inline _Tpuvec v_abs(const _Tpsvec& a) \ -{ \ - return v_reinterpret_as_##usuffix(_Tpsvec(msa_absq_##ssuffix(a.val))); \ -} - -OPENCV_HAL_IMPL_MSA_ABS(v_uint8x16, v_int8x16, u8, s8) -OPENCV_HAL_IMPL_MSA_ABS(v_uint16x8, v_int16x8, u16, s16) -OPENCV_HAL_IMPL_MSA_ABS(v_uint32x4, v_int32x4, u32, s32) - -/* v_abs(float), v_sqrt, v_invsqrt */ -#define OPENCV_HAL_IMPL_MSA_BASIC_FUNC(_Tpvec, func, intrin) \ -inline _Tpvec func(const _Tpvec& a) \ -{ \ - return _Tpvec(intrin(a.val)); \ -} - -OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float32x4, v_abs, msa_absq_f32) -OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float64x2, v_abs, msa_absq_f64) -OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float32x4, v_sqrt, msa_sqrtq_f32) -OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float32x4, v_invsqrt, msa_rsqrtq_f32) -OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float64x2, v_sqrt, msa_sqrtq_f64) -OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float64x2, v_invsqrt, msa_rsqrtq_f64) - -#define OPENCV_HAL_IMPL_MSA_DBL_BIT_OP(bin_op, intrin) \ -inline v_float64x2 bin_op(const v_float64x2& a, const v_float64x2& b) \ -{ \ - return v_float64x2(MSA_TPV_REINTERPRET(v2f64, intrin(MSA_TPV_REINTERPRET(v2i64, a.val), MSA_TPV_REINTERPRET(v2i64, b.val)))); \ -} - -OPENCV_HAL_IMPL_MSA_DBL_BIT_OP(v_and, msa_andq_s64) -OPENCV_HAL_IMPL_MSA_DBL_BIT_OP(v_or, msa_orrq_s64) -OPENCV_HAL_IMPL_MSA_DBL_BIT_OP(v_xor, msa_eorq_s64) - -inline v_float64x2 v_not(const v_float64x2& a) -{ - return v_float64x2(MSA_TPV_REINTERPRET(v2f64, msa_mvnq_s32(MSA_TPV_REINTERPRET(v4i32, a.val)))); -} - -// TODO: exp, log, sin, cos - -#define OPENCV_HAL_IMPL_MSA_BIN_FUNC(_Tpvec, func, intrin) \ -inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(intrin(a.val, b.val)); \ -} - -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_min, msa_minq_u8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_max, msa_maxq_u8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_min, msa_minq_s8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_max, msa_maxq_s8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_min, msa_minq_u16) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_max, msa_maxq_u16) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_min, msa_minq_s16) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_max, msa_maxq_s16) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint32x4, v_min, msa_minq_u32) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint32x4, v_max, msa_maxq_u32) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int32x4, v_min, msa_minq_s32) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int32x4, v_max, msa_maxq_s32) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float32x4, v_min, msa_minq_f32) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float32x4, v_max, msa_maxq_f32) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float64x2, v_min, msa_minq_f64) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float64x2, v_max, msa_maxq_f64) - -#define OPENCV_HAL_IMPL_MSA_INT_CMP_OP(_Tpvec, _Tpv, suffix, not_suffix) \ -inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_ceqq_##suffix(a.val, b.val))); } \ -inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_mvnq_##not_suffix(msa_ceqq_##suffix(a.val, b.val)))); } \ -inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_cltq_##suffix(a.val, b.val))); } \ -inline _Tpvec v_gt(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_cgtq_##suffix(a.val, b.val))); } \ -inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_cleq_##suffix(a.val, b.val))); } \ -inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_cgeq_##suffix(a.val, b.val))); } - -OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_uint8x16, v16u8, u8, u8) -OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_int8x16, v16i8, s8, u8) -OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_uint16x8, v8u16, u16, u16) -OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_int16x8, v8i16, s16, u16) -OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_uint32x4, v4u32, u32, u32) -OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_int32x4, v4i32, s32, u32) -OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_float32x4, v4f32, f32, u32) -OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_uint64x2, v2u64, u64, u64) -OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_int64x2, v2i64, s64, u64) -OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_float64x2, v2f64, f64, u64) - -inline v_float32x4 v_not_nan(const v_float32x4& a) -{ return v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_ceqq_f32(a.val, a.val))); } -inline v_float64x2 v_not_nan(const v_float64x2& a) -{ return v_float64x2(MSA_TPV_REINTERPRET(v2f64, msa_ceqq_f64(a.val, a.val))); } - -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_add_wrap, msa_addq_u8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_add_wrap, msa_addq_s8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_add_wrap, msa_addq_u16) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_add_wrap, msa_addq_s16) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_sub_wrap, msa_subq_u8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_sub_wrap, msa_subq_s8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_sub_wrap, msa_subq_u16) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_sub_wrap, msa_subq_s16) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_mul_wrap, msa_mulq_u8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_mul_wrap, msa_mulq_s8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_mul_wrap, msa_mulq_u16) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_mul_wrap, msa_mulq_s16) - -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_absdiff, msa_abdq_u8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_absdiff, msa_abdq_u16) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint32x4, v_absdiff, msa_abdq_u32) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float32x4, v_absdiff, msa_abdq_f32) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float64x2, v_absdiff, msa_abdq_f64) - -/** Saturating absolute difference **/ -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_absdiffs, msa_qabdq_s8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_absdiffs, msa_qabdq_s16) - -#define OPENCV_HAL_IMPL_MSA_BIN_FUNC2(_Tpvec, _Tpvec2, _Tpv, func, intrin) \ -inline _Tpvec2 func(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec2(MSA_TPV_REINTERPRET(_Tpv, intrin(a.val, b.val))); \ -} - -OPENCV_HAL_IMPL_MSA_BIN_FUNC2(v_int8x16, v_uint8x16, v16u8, v_absdiff, msa_abdq_s8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC2(v_int16x8, v_uint16x8, v8u16, v_absdiff, msa_abdq_s16) -OPENCV_HAL_IMPL_MSA_BIN_FUNC2(v_int32x4, v_uint32x4, v4u32, v_absdiff, msa_abdq_s32) - -/* v_magnitude, v_sqr_magnitude, v_fma, v_muladd */ -inline v_float32x4 v_magnitude(const v_float32x4& a, const v_float32x4& b) -{ - v_float32x4 x(msa_mlaq_f32(msa_mulq_f32(a.val, a.val), b.val, b.val)); - return v_sqrt(x); -} - -inline v_float32x4 v_sqr_magnitude(const v_float32x4& a, const v_float32x4& b) -{ - return v_float32x4(msa_mlaq_f32(msa_mulq_f32(a.val, a.val), b.val, b.val)); -} - -inline v_float32x4 v_fma(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) -{ - return v_float32x4(msa_mlaq_f32(c.val, a.val, b.val)); -} - -inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ - return v_int32x4(msa_mlaq_s32(c.val, a.val, b.val)); -} - -inline v_float32x4 v_muladd(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) -{ - return v_fma(a, b, c); -} - -inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ - return v_fma(a, b, c); -} - -inline v_float64x2 v_magnitude(const v_float64x2& a, const v_float64x2& b) -{ - v_float64x2 x(msa_mlaq_f64(msa_mulq_f64(a.val, a.val), b.val, b.val)); - return v_sqrt(x); -} - -inline v_float64x2 v_sqr_magnitude(const v_float64x2& a, const v_float64x2& b) -{ - return v_float64x2(msa_mlaq_f64(msa_mulq_f64(a.val, a.val), b.val, b.val)); -} - -inline v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) -{ - return v_float64x2(msa_mlaq_f64(c.val, a.val, b.val)); -} - -inline v_float64x2 v_muladd(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) -{ - return v_fma(a, b, c); -} - -// trade efficiency for convenience -#define OPENCV_HAL_IMPL_MSA_SHIFT_OP(_Tpvec, suffix, _Tps, ssuffix) \ -inline _Tpvec v_shl(const _Tpvec& a, int n) \ -{ return _Tpvec(msa_shlq_##suffix(a.val, msa_dupq_n_##ssuffix((_Tps)n))); } \ -inline _Tpvec v_shr(const _Tpvec& a, int n) \ -{ return _Tpvec(msa_shrq_##suffix(a.val, msa_dupq_n_##ssuffix((_Tps)n))); } \ -template inline _Tpvec v_shl(const _Tpvec& a) \ -{ return _Tpvec(msa_shlq_n_##suffix(a.val, n)); } \ -template inline _Tpvec v_shr(const _Tpvec& a) \ -{ return _Tpvec(msa_shrq_n_##suffix(a.val, n)); } \ -template inline _Tpvec v_rshr(const _Tpvec& a) \ -{ return _Tpvec(msa_rshrq_n_##suffix(a.val, n)); } - -OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_uint8x16, u8, schar, s8) -OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_int8x16, s8, schar, s8) -OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_uint16x8, u16, short, s16) -OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_int16x8, s16, short, s16) -OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_uint32x4, u32, int, s32) -OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_int32x4, s32, int, s32) -OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_uint64x2, u64, int64, s64) -OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_int64x2, s64, int64, s64) - -/* v_rotate_right, v_rotate_left */ -#define OPENCV_HAL_IMPL_MSA_ROTATE_OP(_Tpvec, _Tpv, _Tpvs, suffix) \ -template inline _Tpvec v_rotate_right(const _Tpvec& a) \ -{ \ - return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##suffix(0), n))); \ -} \ -template inline _Tpvec v_rotate_left(const _Tpvec& a) \ -{ \ - return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(msa_dupq_n_##suffix(0), MSA_TPV_REINTERPRET(_Tpvs, a.val), _Tpvec::nlanes - n))); \ -} \ -template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a) \ -{ \ - return a; \ -} \ -template inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), MSA_TPV_REINTERPRET(_Tpvs, b.val), n))); \ -} \ -template inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(MSA_TPV_REINTERPRET(_Tpvs, b.val), MSA_TPV_REINTERPRET(_Tpvs, a.val), _Tpvec::nlanes - n))); \ -} \ -template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a, const _Tpvec& b) \ -{ \ - CV_UNUSED(b); \ - return a; \ -} - -OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_uint8x16, v16u8, v16i8, s8) -OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_int8x16, v16i8, v16i8, s8) -OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_uint16x8, v8u16, v8i16, s16) -OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_int16x8, v8i16, v8i16, s16) -OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_uint32x4, v4u32, v4i32, s32) -OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_int32x4, v4i32, v4i32, s32) -OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_float32x4, v4f32, v4i32, s32) -OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_uint64x2, v2u64, v2i64, s64) -OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_int64x2, v2i64, v2i64, s64) -OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_float64x2, v2f64, v2i64, s64) - -#define OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(_Tpvec, _Tp, suffix) \ -inline _Tpvec v_load(const _Tp* ptr) \ -{ return _Tpvec(msa_ld1q_##suffix(ptr)); } \ -inline _Tpvec v_load_aligned(const _Tp* ptr) \ -{ return _Tpvec(msa_ld1q_##suffix(ptr)); } \ -inline _Tpvec v_load_low(const _Tp* ptr) \ -{ return _Tpvec(msa_combine_##suffix(msa_ld1_##suffix(ptr), msa_dup_n_##suffix((_Tp)0))); } \ -inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ -{ return _Tpvec(msa_combine_##suffix(msa_ld1_##suffix(ptr0), msa_ld1_##suffix(ptr1))); } \ -inline void v_store(_Tp* ptr, const _Tpvec& a) \ -{ msa_st1q_##suffix(ptr, a.val); } \ -inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ -{ msa_st1q_##suffix(ptr, a.val); } \ -inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ -{ msa_st1q_##suffix(ptr, a.val); } \ -inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ -{ msa_st1q_##suffix(ptr, a.val); } \ -inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ -{ \ - int n = _Tpvec::nlanes; \ - for( int i = 0; i < (n/2); i++ ) \ - ptr[i] = a.val[i]; \ -} \ -inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ -{ \ - int n = _Tpvec::nlanes; \ - for( int i = 0; i < (n/2); i++ ) \ - ptr[i] = a.val[i+(n/2)]; \ -} - -OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_uint8x16, uchar, u8) -OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_int8x16, schar, s8) -OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_uint16x8, ushort, u16) -OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_int16x8, short, s16) -OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_uint32x4, unsigned, u32) -OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_int32x4, int, s32) -OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_uint64x2, uint64, u64) -OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_int64x2, int64, s64) -OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_float32x4, float, f32) -OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_float64x2, double, f64) - - -/** Reverse **/ -inline v_uint8x16 v_reverse(const v_uint8x16 &a) -{ - v_uint8x16 c = v_uint8x16((v16u8)__builtin_msa_vshf_b((v16i8)((v2i64){0x08090A0B0C0D0E0F, 0x0001020304050607}), msa_dupq_n_s8(0), (v16i8)a.val)); - return c; -} - -inline v_int8x16 v_reverse(const v_int8x16 &a) -{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } - -inline v_uint16x8 v_reverse(const v_uint16x8 &a) -{ - v_uint16x8 c = v_uint16x8((v8u16)__builtin_msa_vshf_h((v8i16)((v2i64){0x0004000500060007, 0x0000000100020003}), msa_dupq_n_s16(0), (v8i16)a.val)); - return c; -} - -inline v_int16x8 v_reverse(const v_int16x8 &a) -{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } - -inline v_uint32x4 v_reverse(const v_uint32x4 &a) -{ - v_uint32x4 c; - c.val[0] = a.val[3]; - c.val[1] = a.val[2]; - c.val[2] = a.val[1]; - c.val[3] = a.val[0]; - return c; -} - -inline v_int32x4 v_reverse(const v_int32x4 &a) -{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_float32x4 v_reverse(const v_float32x4 &a) -{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_uint64x2 v_reverse(const v_uint64x2 &a) -{ - v_uint64x2 c; - c.val[0] = a.val[1]; - c.val[1] = a.val[0]; - return c; -} - -inline v_int64x2 v_reverse(const v_int64x2 &a) -{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } - -inline v_float64x2 v_reverse(const v_float64x2 &a) -{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } - - -#define OPENCV_HAL_IMPL_MSA_REDUCE_OP_8U(func, cfunc) \ -inline unsigned short v_reduce_##func(const v_uint16x8& a) \ -{ \ - v8u16 a_lo, a_hi; \ - ILVRL_H2_UH(a.val, msa_dupq_n_u16(0), a_lo, a_hi); \ - v4u32 b = msa_##func##q_u32(msa_paddlq_u16(a_lo), msa_paddlq_u16(a_hi)); \ - v4u32 b_lo, b_hi; \ - ILVRL_W2_UW(b, msa_dupq_n_u32(0), b_lo, b_hi); \ - v2u64 c = msa_##func##q_u64(msa_paddlq_u32(b_lo), msa_paddlq_u32(b_hi)); \ - return (unsigned short)cfunc(c[0], c[1]); \ -} - -OPENCV_HAL_IMPL_MSA_REDUCE_OP_8U(max, std::max) -OPENCV_HAL_IMPL_MSA_REDUCE_OP_8U(min, std::min) - -#define OPENCV_HAL_IMPL_MSA_REDUCE_OP_8S(func, cfunc) \ -inline short v_reduce_##func(const v_int16x8& a) \ -{ \ - v8i16 a_lo, a_hi; \ - ILVRL_H2_SH(a.val, msa_dupq_n_s16(0), a_lo, a_hi); \ - v4i32 b = msa_##func##q_s32(msa_paddlq_s16(a_lo), msa_paddlq_s16(a_hi)); \ - v4i32 b_lo, b_hi; \ - ILVRL_W2_SW(b, msa_dupq_n_s32(0), b_lo, b_hi); \ - v2i64 c = msa_##func##q_s64(msa_paddlq_s32(b_lo), msa_paddlq_s32(b_hi)); \ - return (short)cfunc(c[0], c[1]); \ -} - -OPENCV_HAL_IMPL_MSA_REDUCE_OP_8S(max, std::max) -OPENCV_HAL_IMPL_MSA_REDUCE_OP_8S(min, std::min) - -#define OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(_Tpvec, scalartype, func, cfunc) \ -inline scalartype v_reduce_##func(const _Tpvec& a) \ -{ \ - return (scalartype)cfunc(cfunc(a.val[0], a.val[1]), cfunc(a.val[2], a.val[3])); \ -} - -OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_uint32x4, unsigned, max, std::max) -OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_uint32x4, unsigned, min, std::min) -OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_int32x4, int, max, std::max) -OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_int32x4, int, min, std::min) -OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_float32x4, float, max, std::max) -OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_float32x4, float, min, std::min) - - -#define OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(_Tpvec, scalartype, _Tpvec2, func) \ -inline scalartype v_reduce_##func(const _Tpvec& a) \ -{ \ - _Tpvec2 a1, a2; \ - v_expand(a, a1, a2); \ - return (scalartype)v_reduce_##func(v_##func(a1, a2)); \ -} - -OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(v_uint8x16, uchar, v_uint16x8, min) -OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(v_uint8x16, uchar, v_uint16x8, max) -OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(v_int8x16, char, v_int16x8, min) -OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(v_int8x16, char, v_int16x8, max) - - - -#define OPENCV_HAL_IMPL_MSA_REDUCE_SUM(_Tpvec, scalartype, suffix) \ -inline scalartype v_reduce_sum(const _Tpvec& a) \ -{ \ - return (scalartype)msa_sum_##suffix(a.val); \ -} - -OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_uint8x16, unsigned short, u8) -OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_int8x16, short, s8) -OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_uint16x8, unsigned, u16) -OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_int16x8, int, s16) -OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_uint32x4, uint64_t, u32) -OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_int32x4, int64_t, s32) -OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_float32x4, float, f32) - -inline uint64 v_reduce_sum(const v_uint64x2& a) -{ return (uint64)(msa_getq_lane_u64(a.val, 0) + msa_getq_lane_u64(a.val, 1)); } -inline int64 v_reduce_sum(const v_int64x2& a) -{ return (int64)(msa_getq_lane_s64(a.val, 0) + msa_getq_lane_s64(a.val, 1)); } -inline double v_reduce_sum(const v_float64x2& a) -{ - return msa_getq_lane_f64(a.val, 0) + msa_getq_lane_f64(a.val, 1); -} - -/* v_reduce_sum4, v_reduce_sad */ -inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, - const v_float32x4& c, const v_float32x4& d) -{ - v4f32 u0 = msa_addq_f32(MSA_TPV_REINTERPRET(v4f32, msa_ilvevq_s32(MSA_TPV_REINTERPRET(v4i32, b.val), MSA_TPV_REINTERPRET(v4i32, a.val))), - MSA_TPV_REINTERPRET(v4f32, msa_ilvodq_s32(MSA_TPV_REINTERPRET(v4i32, b.val), MSA_TPV_REINTERPRET(v4i32, a.val)))); // a0+a1 b0+b1 a2+a3 b2+b3 - v4f32 u1 = msa_addq_f32(MSA_TPV_REINTERPRET(v4f32, msa_ilvevq_s32(MSA_TPV_REINTERPRET(v4i32, d.val), MSA_TPV_REINTERPRET(v4i32, c.val))), - MSA_TPV_REINTERPRET(v4f32, msa_ilvodq_s32(MSA_TPV_REINTERPRET(v4i32, d.val), MSA_TPV_REINTERPRET(v4i32, c.val)))); // c0+c1 d0+d1 c2+c3 d2+d3 - - return v_float32x4(msa_addq_f32(MSA_TPV_REINTERPRET(v4f32, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, u1), MSA_TPV_REINTERPRET(v2i64, u0))), - MSA_TPV_REINTERPRET(v4f32, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, u1), MSA_TPV_REINTERPRET(v2i64, u0))))); -} - -inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b) -{ - v16u8 t0 = msa_abdq_u8(a.val, b.val); - v8u16 t1 = msa_paddlq_u8(t0); - v4u32 t2 = msa_paddlq_u16(t1); - return msa_sum_u32(t2); -} -inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b) -{ - v16u8 t0 = MSA_TPV_REINTERPRET(v16u8, msa_abdq_s8(a.val, b.val)); - v8u16 t1 = msa_paddlq_u8(t0); - v4u32 t2 = msa_paddlq_u16(t1); - return msa_sum_u32(t2); -} -inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b) -{ - v8u16 t0 = msa_abdq_u16(a.val, b.val); - v4u32 t1 = msa_paddlq_u16(t0); - return msa_sum_u32(t1); -} -inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b) -{ - v8u16 t0 = MSA_TPV_REINTERPRET(v8u16, msa_abdq_s16(a.val, b.val)); - v4u32 t1 = msa_paddlq_u16(t0); - return msa_sum_u32(t1); -} -inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b) -{ - v4u32 t0 = msa_abdq_u32(a.val, b.val); - return msa_sum_u32(t0); -} -inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b) -{ - v4u32 t0 = MSA_TPV_REINTERPRET(v4u32, msa_abdq_s32(a.val, b.val)); - return msa_sum_u32(t0); -} -inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) -{ - v4f32 t0 = msa_abdq_f32(a.val, b.val); - return msa_sum_f32(t0); -} - -/* v_popcount */ -#define OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE8(_Tpvec) \ -inline v_uint8x16 v_popcount(const _Tpvec& a) \ -{ \ - v16u8 t = MSA_TPV_REINTERPRET(v16u8, msa_cntq_s8(MSA_TPV_REINTERPRET(v16i8, a.val))); \ - return v_uint8x16(t); \ -} -OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE8(v_uint8x16) -OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE8(v_int8x16) - -#define OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE16(_Tpvec) \ -inline v_uint16x8 v_popcount(const _Tpvec& a) \ -{ \ - v8u16 t = MSA_TPV_REINTERPRET(v8u16, msa_cntq_s16(MSA_TPV_REINTERPRET(v8i16, a.val))); \ - return v_uint16x8(t); \ -} -OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE16(v_uint16x8) -OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE16(v_int16x8) - -#define OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE32(_Tpvec) \ -inline v_uint32x4 v_popcount(const _Tpvec& a) \ -{ \ - v4u32 t = MSA_TPV_REINTERPRET(v4u32, msa_cntq_s32(MSA_TPV_REINTERPRET(v4i32, a.val))); \ - return v_uint32x4(t); \ -} -OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE32(v_uint32x4) -OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE32(v_int32x4) - -#define OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE64(_Tpvec) \ -inline v_uint64x2 v_popcount(const _Tpvec& a) \ -{ \ - v2u64 t = MSA_TPV_REINTERPRET(v2u64, msa_cntq_s64(MSA_TPV_REINTERPRET(v2i64, a.val))); \ - return v_uint64x2(t); \ -} -OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE64(v_uint64x2) -OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE64(v_int64x2) - -inline int v_signmask(const v_uint8x16& a) -{ - v8i8 m0 = msa_create_s8(CV_BIG_UINT(0x0706050403020100)); - v16u8 v0 = msa_shlq_u8(msa_shrq_n_u8(a.val, 7), msa_combine_s8(m0, m0)); - v8u16 v1 = msa_paddlq_u8(v0); - v4u32 v2 = msa_paddlq_u16(v1); - v2u64 v3 = msa_paddlq_u32(v2); - return (int)msa_getq_lane_u64(v3, 0) + ((int)msa_getq_lane_u64(v3, 1) << 8); -} -inline int v_signmask(const v_int8x16& a) -{ return v_signmask(v_reinterpret_as_u8(a)); } - -inline int v_signmask(const v_uint16x8& a) -{ - v4i16 m0 = msa_create_s16(CV_BIG_UINT(0x0003000200010000)); - v8u16 v0 = msa_shlq_u16(msa_shrq_n_u16(a.val, 15), msa_combine_s16(m0, m0)); - v4u32 v1 = msa_paddlq_u16(v0); - v2u64 v2 = msa_paddlq_u32(v1); - return (int)msa_getq_lane_u64(v2, 0) + ((int)msa_getq_lane_u64(v2, 1) << 4); -} -inline int v_signmask(const v_int16x8& a) -{ return v_signmask(v_reinterpret_as_u16(a)); } - -inline int v_signmask(const v_uint32x4& a) -{ - v2i32 m0 = msa_create_s32(CV_BIG_UINT(0x0000000100000000)); - v4u32 v0 = msa_shlq_u32(msa_shrq_n_u32(a.val, 31), msa_combine_s32(m0, m0)); - v2u64 v1 = msa_paddlq_u32(v0); - return (int)msa_getq_lane_u64(v1, 0) + ((int)msa_getq_lane_u64(v1, 1) << 2); -} -inline int v_signmask(const v_int32x4& a) -{ return v_signmask(v_reinterpret_as_u32(a)); } -inline int v_signmask(const v_float32x4& a) -{ return v_signmask(v_reinterpret_as_u32(a)); } - -inline int v_signmask(const v_uint64x2& a) -{ - v2u64 v0 = msa_shrq_n_u64(a.val, 63); - return (int)msa_getq_lane_u64(v0, 0) + ((int)msa_getq_lane_u64(v0, 1) << 1); -} -inline int v_signmask(const v_int64x2& a) -{ return v_signmask(v_reinterpret_as_u64(a)); } -inline int v_signmask(const v_float64x2& a) -{ return v_signmask(v_reinterpret_as_u64(a)); } - -inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(a)); } - -#define OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(_Tpvec, _Tpvec2, suffix, shift) \ -inline bool v_check_all(const v_##_Tpvec& a) \ -{ \ - _Tpvec2 v0 = msa_shrq_n_##suffix(msa_mvnq_##suffix(a.val), shift); \ - v2u64 v1 = MSA_TPV_REINTERPRET(v2u64, v0); \ - return (msa_getq_lane_u64(v1, 0) | msa_getq_lane_u64(v1, 1)) == 0; \ -} \ -inline bool v_check_any(const v_##_Tpvec& a) \ -{ \ - _Tpvec2 v0 = msa_shrq_n_##suffix(a.val, shift); \ - v2u64 v1 = MSA_TPV_REINTERPRET(v2u64, v0); \ - return (msa_getq_lane_u64(v1, 0) | msa_getq_lane_u64(v1, 1)) != 0; \ -} - -OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(uint8x16, v16u8, u8, 7) -OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(uint16x8, v8u16, u16, 15) -OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(uint32x4, v4u32, u32, 31) -OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(uint64x2, v2u64, u64, 63) - -inline bool v_check_all(const v_int8x16& a) -{ return v_check_all(v_reinterpret_as_u8(a)); } -inline bool v_check_all(const v_int16x8& a) -{ return v_check_all(v_reinterpret_as_u16(a)); } -inline bool v_check_all(const v_int32x4& a) -{ return v_check_all(v_reinterpret_as_u32(a)); } -inline bool v_check_all(const v_float32x4& a) -{ return v_check_all(v_reinterpret_as_u32(a)); } - -inline bool v_check_any(const v_int8x16& a) -{ return v_check_any(v_reinterpret_as_u8(a)); } -inline bool v_check_any(const v_int16x8& a) -{ return v_check_any(v_reinterpret_as_u16(a)); } -inline bool v_check_any(const v_int32x4& a) -{ return v_check_any(v_reinterpret_as_u32(a)); } -inline bool v_check_any(const v_float32x4& a) -{ return v_check_any(v_reinterpret_as_u32(a)); } - -inline bool v_check_all(const v_int64x2& a) -{ return v_check_all(v_reinterpret_as_u64(a)); } -inline bool v_check_all(const v_float64x2& a) -{ return v_check_all(v_reinterpret_as_u64(a)); } -inline bool v_check_any(const v_int64x2& a) -{ return v_check_any(v_reinterpret_as_u64(a)); } -inline bool v_check_any(const v_float64x2& a) -{ return v_check_any(v_reinterpret_as_u64(a)); } - -/* v_select */ -#define OPENCV_HAL_IMPL_MSA_SELECT(_Tpvec, _Tpv, _Tpvu) \ -inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_bslq_u8(MSA_TPV_REINTERPRET(_Tpvu, mask.val), \ - MSA_TPV_REINTERPRET(_Tpvu, b.val), MSA_TPV_REINTERPRET(_Tpvu, a.val)))); \ -} - -OPENCV_HAL_IMPL_MSA_SELECT(v_uint8x16, v16u8, v16u8) -OPENCV_HAL_IMPL_MSA_SELECT(v_int8x16, v16i8, v16u8) -OPENCV_HAL_IMPL_MSA_SELECT(v_uint16x8, v8u16, v16u8) -OPENCV_HAL_IMPL_MSA_SELECT(v_int16x8, v8i16, v16u8) -OPENCV_HAL_IMPL_MSA_SELECT(v_uint32x4, v4u32, v16u8) -OPENCV_HAL_IMPL_MSA_SELECT(v_int32x4, v4i32, v16u8) -OPENCV_HAL_IMPL_MSA_SELECT(v_float32x4, v4f32, v16u8) -OPENCV_HAL_IMPL_MSA_SELECT(v_float64x2, v2f64, v16u8) - -#define OPENCV_HAL_IMPL_MSA_EXPAND(_Tpvec, _Tpwvec, _Tp, suffix, ssuffix, _Tpv, _Tpvs) \ -inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ -{ \ - _Tpv a_lo = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##ssuffix(0))); \ - _Tpv a_hi = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##ssuffix(0))); \ - b0.val = msa_paddlq_##suffix(a_lo); \ - b1.val = msa_paddlq_##suffix(a_hi); \ -} \ -inline _Tpwvec v_expand_low(const _Tpvec& a) \ -{ \ - _Tpv a_lo = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##ssuffix(0))); \ - return _Tpwvec(msa_paddlq_##suffix(a_lo)); \ -} \ -inline _Tpwvec v_expand_high(const _Tpvec& a) \ -{ \ - _Tpv a_hi = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##ssuffix(0))); \ - return _Tpwvec(msa_paddlq_##suffix(a_hi)); \ -} \ -inline _Tpwvec v_load_expand(const _Tp* ptr) \ -{ \ - return _Tpwvec(msa_movl_##suffix(msa_ld1_##suffix(ptr))); \ -} - -OPENCV_HAL_IMPL_MSA_EXPAND(v_uint8x16, v_uint16x8, uchar, u8, s8, v16u8, v16i8) -OPENCV_HAL_IMPL_MSA_EXPAND(v_int8x16, v_int16x8, schar, s8, s8, v16i8, v16i8) -OPENCV_HAL_IMPL_MSA_EXPAND(v_uint16x8, v_uint32x4, ushort, u16, s16, v8u16, v8i16) -OPENCV_HAL_IMPL_MSA_EXPAND(v_int16x8, v_int32x4, short, s16, s16, v8i16, v8i16) -OPENCV_HAL_IMPL_MSA_EXPAND(v_uint32x4, v_uint64x2, uint, u32, s32, v4u32, v4i32) -OPENCV_HAL_IMPL_MSA_EXPAND(v_int32x4, v_int64x2, int, s32, s32, v4i32, v4i32) - -inline v_uint32x4 v_load_expand_q(const uchar* ptr) -{ - return v_uint32x4((v4u32){ptr[0], ptr[1], ptr[2], ptr[3]}); -} - -inline v_int32x4 v_load_expand_q(const schar* ptr) -{ - return v_int32x4((v4i32){ptr[0], ptr[1], ptr[2], ptr[3]}); -} - -/* v_zip, v_combine_low, v_combine_high, v_recombine */ -#define OPENCV_HAL_IMPL_MSA_UNPACKS(_Tpvec, _Tpv, _Tpvs, ssuffix) \ -inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) \ -{ \ - b0.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a1.val), MSA_TPV_REINTERPRET(_Tpvs, a0.val))); \ - b1.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a1.val), MSA_TPV_REINTERPRET(_Tpvs, a0.val))); \ -} \ -inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, b.val), MSA_TPV_REINTERPRET(v2i64, a.val)))); \ -} \ -inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, b.val), MSA_TPV_REINTERPRET(v2i64, a.val)))); \ -} \ -inline void v_recombine(const _Tpvec& a, const _Tpvec& b, _Tpvec& c, _Tpvec& d) \ -{ \ - c.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, b.val), MSA_TPV_REINTERPRET(v2i64, a.val))); \ - d.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, b.val), MSA_TPV_REINTERPRET(v2i64, a.val))); \ -} - -OPENCV_HAL_IMPL_MSA_UNPACKS(v_uint8x16, v16u8, v16i8, s8) -OPENCV_HAL_IMPL_MSA_UNPACKS(v_int8x16, v16i8, v16i8, s8) -OPENCV_HAL_IMPL_MSA_UNPACKS(v_uint16x8, v8u16, v8i16, s16) -OPENCV_HAL_IMPL_MSA_UNPACKS(v_int16x8, v8i16, v8i16, s16) -OPENCV_HAL_IMPL_MSA_UNPACKS(v_uint32x4, v4u32, v4i32, s32) -OPENCV_HAL_IMPL_MSA_UNPACKS(v_int32x4, v4i32, v4i32, s32) -OPENCV_HAL_IMPL_MSA_UNPACKS(v_float32x4, v4f32, v4i32, s32) -OPENCV_HAL_IMPL_MSA_UNPACKS(v_float64x2, v2f64, v2i64, s64) - -/* v_extract */ -#define OPENCV_HAL_IMPL_MSA_EXTRACT(_Tpvec, _Tpv, _Tpvs, suffix) \ -template \ -inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), MSA_TPV_REINTERPRET(_Tpvs, b.val), s))); \ -} - -OPENCV_HAL_IMPL_MSA_EXTRACT(v_uint8x16, v16u8, v16i8, s8) -OPENCV_HAL_IMPL_MSA_EXTRACT(v_int8x16, v16i8, v16i8, s8) -OPENCV_HAL_IMPL_MSA_EXTRACT(v_uint16x8, v8u16, v8i16, s16) -OPENCV_HAL_IMPL_MSA_EXTRACT(v_int16x8, v8i16, v8i16, s16) -OPENCV_HAL_IMPL_MSA_EXTRACT(v_uint32x4, v4u32, v4i32, s32) -OPENCV_HAL_IMPL_MSA_EXTRACT(v_int32x4, v4i32, v4i32, s32) -OPENCV_HAL_IMPL_MSA_EXTRACT(v_uint64x2, v2u64, v2i64, s64) -OPENCV_HAL_IMPL_MSA_EXTRACT(v_int64x2, v2i64, v2i64, s64) -OPENCV_HAL_IMPL_MSA_EXTRACT(v_float32x4, v4f32, v4i32, s32) -OPENCV_HAL_IMPL_MSA_EXTRACT(v_float64x2, v2f64, v2i64, s64) - -/* v_round, v_floor, v_ceil, v_trunc */ -inline v_int32x4 v_round(const v_float32x4& a) -{ - return v_int32x4(msa_cvttintq_s32_f32(a.val)); -} - -inline v_int32x4 v_floor(const v_float32x4& a) -{ - v4i32 a1 = msa_cvttintq_s32_f32(a.val); - return v_int32x4(msa_addq_s32(a1, MSA_TPV_REINTERPRET(v4i32, msa_cgtq_f32(msa_cvtfintq_f32_s32(a1), a.val)))); -} - -inline v_int32x4 v_ceil(const v_float32x4& a) -{ - v4i32 a1 = msa_cvttintq_s32_f32(a.val); - return v_int32x4(msa_subq_s32(a1, MSA_TPV_REINTERPRET(v4i32, msa_cgtq_f32(a.val, msa_cvtfintq_f32_s32(a1))))); -} - -inline v_int32x4 v_trunc(const v_float32x4& a) -{ - return v_int32x4(msa_cvttruncq_s32_f32(a.val)); -} - -inline v_int32x4 v_round(const v_float64x2& a) -{ - return v_int32x4(msa_pack_s64(msa_cvttintq_s64_f64(a.val), msa_dupq_n_s64(0))); -} - -inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) -{ - return v_int32x4(msa_pack_s64(msa_cvttintq_s64_f64(a.val), msa_cvttintq_s64_f64(b.val))); -} - -inline v_int32x4 v_floor(const v_float64x2& a) -{ - v2f64 a1 = msa_cvtrintq_f64(a.val); - return v_int32x4(msa_pack_s64(msa_addq_s64(msa_cvttruncq_s64_f64(a1), MSA_TPV_REINTERPRET(v2i64, msa_cgtq_f64(a1, a.val))), msa_dupq_n_s64(0))); -} - -inline v_int32x4 v_ceil(const v_float64x2& a) -{ - v2f64 a1 = msa_cvtrintq_f64(a.val); - return v_int32x4(msa_pack_s64(msa_subq_s64(msa_cvttruncq_s64_f64(a1), MSA_TPV_REINTERPRET(v2i64, msa_cgtq_f64(a.val, a1))), msa_dupq_n_s64(0))); -} - -inline v_int32x4 v_trunc(const v_float64x2& a) -{ - return v_int32x4(msa_pack_s64(msa_cvttruncq_s64_f64(a.val), msa_dupq_n_s64(0))); -} - -#define OPENCV_HAL_IMPL_MSA_TRANSPOSE4x4(_Tpvec, _Tpv, _Tpvs, ssuffix) \ -inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ - const _Tpvec& a2, const _Tpvec& a3, \ - _Tpvec& b0, _Tpvec& b1, \ - _Tpvec& b2, _Tpvec& b3) \ -{ \ - _Tpv t00 = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a1.val), MSA_TPV_REINTERPRET(_Tpvs, a0.val))); \ - _Tpv t01 = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a1.val), MSA_TPV_REINTERPRET(_Tpvs, a0.val))); \ - _Tpv t10 = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a3.val), MSA_TPV_REINTERPRET(_Tpvs, a2.val))); \ - _Tpv t11 = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a3.val), MSA_TPV_REINTERPRET(_Tpvs, a2.val))); \ - b0.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, t10), MSA_TPV_REINTERPRET(v2i64, t00))); \ - b1.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, t10), MSA_TPV_REINTERPRET(v2i64, t00))); \ - b2.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, t11), MSA_TPV_REINTERPRET(v2i64, t01))); \ - b3.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, t11), MSA_TPV_REINTERPRET(v2i64, t01))); \ -} - -OPENCV_HAL_IMPL_MSA_TRANSPOSE4x4(v_uint32x4, v4u32, v4i32, s32) -OPENCV_HAL_IMPL_MSA_TRANSPOSE4x4(v_int32x4, v4i32, v4i32, s32) -OPENCV_HAL_IMPL_MSA_TRANSPOSE4x4(v_float32x4, v4f32, v4i32, s32) - -#define OPENCV_HAL_IMPL_MSA_INTERLEAVED(_Tpvec, _Tp, suffix) \ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b) \ -{ \ - msa_ld2q_##suffix(ptr, &a.val, &b.val); \ -} \ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, v_##_Tpvec& c) \ -{ \ - msa_ld3q_##suffix(ptr, &a.val, &b.val, &c.val); \ -} \ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, \ - v_##_Tpvec& c, v_##_Tpvec& d) \ -{ \ - msa_ld4q_##suffix(ptr, &a.val, &b.val, &c.val, &d.val); \ -} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - msa_st2q_##suffix(ptr, a.val, b.val); \ -} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ - const v_##_Tpvec& c, hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - msa_st3q_##suffix(ptr, a.val, b.val, c.val); \ -} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ - const v_##_Tpvec& c, const v_##_Tpvec& d, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ -{ \ - msa_st4q_##suffix(ptr, a.val, b.val, c.val, d.val); \ -} - -OPENCV_HAL_IMPL_MSA_INTERLEAVED(uint8x16, uchar, u8) -OPENCV_HAL_IMPL_MSA_INTERLEAVED(int8x16, schar, s8) -OPENCV_HAL_IMPL_MSA_INTERLEAVED(uint16x8, ushort, u16) -OPENCV_HAL_IMPL_MSA_INTERLEAVED(int16x8, short, s16) -OPENCV_HAL_IMPL_MSA_INTERLEAVED(uint32x4, unsigned, u32) -OPENCV_HAL_IMPL_MSA_INTERLEAVED(int32x4, int, s32) -OPENCV_HAL_IMPL_MSA_INTERLEAVED(float32x4, float, f32) -OPENCV_HAL_IMPL_MSA_INTERLEAVED(uint64x2, uint64, u64) -OPENCV_HAL_IMPL_MSA_INTERLEAVED(int64x2, int64, s64) -OPENCV_HAL_IMPL_MSA_INTERLEAVED(float64x2, double, f64) - -/* v_cvt_f32, v_cvt_f64, v_cvt_f64_high */ -inline v_float32x4 v_cvt_f32(const v_int32x4& a) -{ - return v_float32x4(msa_cvtfintq_f32_s32(a.val)); -} - -inline v_float32x4 v_cvt_f32(const v_float64x2& a) -{ - return v_float32x4(msa_cvtfq_f32_f64(a.val, msa_dupq_n_f64(0.0f))); -} - -inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) -{ - return v_float32x4(msa_cvtfq_f32_f64(a.val, b.val)); -} - -inline v_float64x2 v_cvt_f64(const v_int32x4& a) -{ - return v_float64x2(msa_cvtflq_f64_f32(msa_cvtfintq_f32_s32(a.val))); -} - -inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) -{ - return v_float64x2(msa_cvtfhq_f64_f32(msa_cvtfintq_f32_s32(a.val))); -} - -inline v_float64x2 v_cvt_f64(const v_float32x4& a) -{ - return v_float64x2(msa_cvtflq_f64_f32(a.val)); -} - -inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) -{ - return v_float64x2(msa_cvtfhq_f64_f32(a.val)); -} - -inline v_float64x2 v_cvt_f64(const v_int64x2& a) -{ - return v_float64x2(msa_cvtfintq_f64_s64(a.val)); -} - -////////////// Lookup table access //////////////////// -inline v_int8x16 v_lut(const schar* tab, const int* idx) -{ - schar CV_DECL_ALIGNED(32) elems[16] = - { - tab[idx[ 0]], - tab[idx[ 1]], - tab[idx[ 2]], - tab[idx[ 3]], - tab[idx[ 4]], - tab[idx[ 5]], - tab[idx[ 6]], - tab[idx[ 7]], - tab[idx[ 8]], - tab[idx[ 9]], - tab[idx[10]], - tab[idx[11]], - tab[idx[12]], - tab[idx[13]], - tab[idx[14]], - tab[idx[15]] - }; - return v_int8x16(msa_ld1q_s8(elems)); -} -inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx) -{ - schar CV_DECL_ALIGNED(32) elems[16] = - { - tab[idx[0]], - tab[idx[0] + 1], - tab[idx[1]], - tab[idx[1] + 1], - tab[idx[2]], - tab[idx[2] + 1], - tab[idx[3]], - tab[idx[3] + 1], - tab[idx[4]], - tab[idx[4] + 1], - tab[idx[5]], - tab[idx[5] + 1], - tab[idx[6]], - tab[idx[6] + 1], - tab[idx[7]], - tab[idx[7] + 1] - }; - return v_int8x16(msa_ld1q_s8(elems)); -} -inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) -{ - schar CV_DECL_ALIGNED(32) elems[16] = - { - tab[idx[0]], - tab[idx[0] + 1], - tab[idx[0] + 2], - tab[idx[0] + 3], - tab[idx[1]], - tab[idx[1] + 1], - tab[idx[1] + 2], - tab[idx[1] + 3], - tab[idx[2]], - tab[idx[2] + 1], - tab[idx[2] + 2], - tab[idx[2] + 3], - tab[idx[3]], - tab[idx[3] + 1], - tab[idx[3] + 2], - tab[idx[3] + 3] - }; - return v_int8x16(msa_ld1q_s8(elems)); -} -inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((schar*)tab, idx)); } -inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((schar*)tab, idx)); } -inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((schar*)tab, idx)); } - - -inline v_int16x8 v_lut(const short* tab, const int* idx) -{ - short CV_DECL_ALIGNED(32) elems[8] = - { - tab[idx[0]], - tab[idx[1]], - tab[idx[2]], - tab[idx[3]], - tab[idx[4]], - tab[idx[5]], - tab[idx[6]], - tab[idx[7]] - }; - return v_int16x8(msa_ld1q_s16(elems)); -} -inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) -{ - short CV_DECL_ALIGNED(32) elems[8] = - { - tab[idx[0]], - tab[idx[0] + 1], - tab[idx[1]], - tab[idx[1] + 1], - tab[idx[2]], - tab[idx[2] + 1], - tab[idx[3]], - tab[idx[3] + 1] - }; - return v_int16x8(msa_ld1q_s16(elems)); -} -inline v_int16x8 v_lut_quads(const short* tab, const int* idx) -{ - return v_int16x8(msa_combine_s16(msa_ld1_s16(tab + idx[0]), msa_ld1_s16(tab + idx[1]))); -} -inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((short*)tab, idx)); } -inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((short*)tab, idx)); } -inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((short*)tab, idx)); } - -inline v_int32x4 v_lut(const int* tab, const int* idx) -{ - int CV_DECL_ALIGNED(32) elems[4] = - { - tab[idx[0]], - tab[idx[1]], - tab[idx[2]], - tab[idx[3]] - }; - return v_int32x4(msa_ld1q_s32(elems)); -} -inline v_int32x4 v_lut_pairs(const int* tab, const int* idx) -{ - return v_int32x4(msa_combine_s32(msa_ld1_s32(tab + idx[0]), msa_ld1_s32(tab + idx[1]))); -} -inline v_int32x4 v_lut_quads(const int* tab, const int* idx) -{ - return v_int32x4(msa_ld1q_s32(tab + idx[0])); -} -inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((int*)tab, idx)); } -inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((int*)tab, idx)); } -inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((int*)tab, idx)); } - -inline v_int64x2 v_lut(const int64_t* tab, const int* idx) -{ - return v_int64x2(msa_combine_s64(msa_create_s64(tab[idx[0]]), msa_create_s64(tab[idx[1]]))); -} -inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) -{ - return v_int64x2(msa_ld1q_s64(tab + idx[0])); -} -inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } -inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } - -inline v_float32x4 v_lut(const float* tab, const int* idx) -{ - float CV_DECL_ALIGNED(32) elems[4] = - { - tab[idx[0]], - tab[idx[1]], - tab[idx[2]], - tab[idx[3]] - }; - return v_float32x4(msa_ld1q_f32(elems)); -} -inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) -{ - uint64 CV_DECL_ALIGNED(32) elems[2] = - { - *(uint64*)(tab + idx[0]), - *(uint64*)(tab + idx[1]) - }; - return v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_ld1q_u64(elems))); -} -inline v_float32x4 v_lut_quads(const float* tab, const int* idx) -{ - return v_float32x4(msa_ld1q_f32(tab + idx[0])); -} - -inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) -{ - int CV_DECL_ALIGNED(32) idx[4]; - v_store_aligned(idx, idxvec); - - return v_int32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); -} - -inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) -{ - unsigned CV_DECL_ALIGNED(32) elems[4] = - { - tab[msa_getq_lane_s32(idxvec.val, 0)], - tab[msa_getq_lane_s32(idxvec.val, 1)], - tab[msa_getq_lane_s32(idxvec.val, 2)], - tab[msa_getq_lane_s32(idxvec.val, 3)] - }; - return v_uint32x4(msa_ld1q_u32(elems)); -} - -inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) -{ - int CV_DECL_ALIGNED(32) idx[4]; - v_store_aligned(idx, idxvec); - - return v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); -} - -inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) -{ - int CV_DECL_ALIGNED(32) idx[4]; - v_store_aligned(idx, idxvec); - - v4f32 xy02 = msa_combine_f32(msa_ld1_f32(tab + idx[0]), msa_ld1_f32(tab + idx[2])); - v4f32 xy13 = msa_combine_f32(msa_ld1_f32(tab + idx[1]), msa_ld1_f32(tab + idx[3])); - x = v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_ilvevq_s32(MSA_TPV_REINTERPRET(v4i32, xy13), MSA_TPV_REINTERPRET(v4i32, xy02)))); - y = v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_ilvodq_s32(MSA_TPV_REINTERPRET(v4i32, xy13), MSA_TPV_REINTERPRET(v4i32, xy02)))); -} - -inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) -{ - v_int8x16 c = v_int8x16(__builtin_msa_vshf_b((v16i8)((v2i64){0x0705060403010200, 0x0F0D0E0C0B090A08}), msa_dupq_n_s8(0), vec.val)); - return c; -} -inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) -{ return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } -inline v_int8x16 v_interleave_quads(const v_int8x16& vec) -{ - v_int8x16 c = v_int8x16(__builtin_msa_vshf_b((v16i8)((v2i64){0x0703060205010400, 0x0F0B0E0A0D090C08}), msa_dupq_n_s8(0), vec.val)); - return c; -} -inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) -{ - v_int16x8 c = v_int16x8(__builtin_msa_vshf_h((v8i16)((v2i64){0x0003000100020000, 0x0007000500060004}), msa_dupq_n_s16(0), vec.val)); - return c; -} - -inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } - -inline v_int16x8 v_interleave_quads(const v_int16x8& vec) -{ - v_int16x8 c = v_int16x8(__builtin_msa_vshf_h((v8i16)((v2i64){0x0005000100040000, 0x0007000300060002}), msa_dupq_n_s16(0), vec.val)); - return c; -} - -inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) -{ - v_int32x4 c; - c.val[0] = vec.val[0]; - c.val[1] = vec.val[2]; - c.val[2] = vec.val[1]; - c.val[3] = vec.val[3]; - return c; -} - -inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } -inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } - -inline v_int8x16 v_pack_triplets(const v_int8x16& vec) -{ - v_int8x16 c = v_int8x16(__builtin_msa_vshf_b((v16i8)((v2i64){0x0908060504020100, 0x131211100E0D0C0A}), msa_dupq_n_s8(0), vec.val)); - return c; -} - -inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_pack_triplets(const v_int16x8& vec) -{ - v_int16x8 c = v_int16x8(__builtin_msa_vshf_h((v8i16)((v2i64){0x0004000200010000, 0x0009000800060005}), msa_dupq_n_s16(0), vec.val)); - return c; -} - -inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } -inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } -inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } -inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } - -inline v_float64x2 v_lut(const double* tab, const int* idx) -{ - double CV_DECL_ALIGNED(32) elems[2] = - { - tab[idx[0]], - tab[idx[1]] - }; - return v_float64x2(msa_ld1q_f64(elems)); -} - -inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) -{ - return v_float64x2(msa_ld1q_f64(tab + idx[0])); -} - -inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) -{ - int CV_DECL_ALIGNED(32) idx[4]; - v_store_aligned(idx, idxvec); - - return v_float64x2(tab[idx[0]], tab[idx[1]]); -} - -inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) -{ - int CV_DECL_ALIGNED(32) idx[4]; - v_store_aligned(idx, idxvec); - - v2f64 xy0 = msa_ld1q_f64(tab + idx[0]); - v2f64 xy1 = msa_ld1q_f64(tab + idx[1]); - x = v_float64x2(MSA_TPV_REINTERPRET(v2f64, msa_ilvevq_s64(MSA_TPV_REINTERPRET(v2i64, xy1), MSA_TPV_REINTERPRET(v2i64, xy0)))); - y = v_float64x2(MSA_TPV_REINTERPRET(v2f64, msa_ilvodq_s64(MSA_TPV_REINTERPRET(v2i64, xy1), MSA_TPV_REINTERPRET(v2i64, xy0)))); -} - -template -inline typename _Tp::lane_type v_extract_n(const _Tp& a) -{ - return v_rotate_right(a).get0(); -} - -template -inline v_uint32x4 v_broadcast_element(const v_uint32x4& a) -{ - return v_setall_u32(v_extract_n(a)); -} -template -inline v_int32x4 v_broadcast_element(const v_int32x4& a) -{ - return v_setall_s32(v_extract_n(a)); -} -template -inline v_float32x4 v_broadcast_element(const v_float32x4& a) -{ - return v_setall_f32(v_extract_n(a)); -} - -////// FP16 support /////// -#if CV_FP16 -inline v_float32x4 v_load_expand(const hfloat* ptr) -{ -#ifndef msa_ld1_f16 - v4f16 v = (v4f16)msa_ld1_s16((const short*)ptr); -#else - v4f16 v = msa_ld1_f16((const __fp16*)ptr); -#endif - return v_float32x4(msa_cvt_f32_f16(v)); -} - -inline void v_pack_store(hfloat* ptr, const v_float32x4& v) -{ - v4f16 hv = msa_cvt_f16_f32(v.val); - -#ifndef msa_st1_f16 - msa_st1_s16((short*)ptr, (int16x4_t)hv); -#else - msa_st1_f16((__fp16*)ptr, hv); -#endif -} -#else -inline v_float32x4 v_load_expand(const hfloat* ptr) -{ - float buf[4]; - for( int i = 0; i < 4; i++ ) - buf[i] = (float)ptr[i]; - return v_load(buf); -} - -inline void v_pack_store(hfloat* ptr, const v_float32x4& v) -{ - float buf[4]; - v_store(buf, v); - for( int i = 0; i < 4; i++ ) - ptr[i] = (hfloat)buf[i]; -} -#endif - -inline void v_cleanup() {} - -#include "intrin_math.hpp" -inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } -inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } -inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } -inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } -inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } -inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } - -inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } -inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } -inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } -inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } -inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} - -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_HAL_INTRIN_MSA_HPP +#define OPENCV_HAL_INTRIN_MSA_HPP + +#include +#include "opencv2/core/utility.hpp" + +namespace cv +{ + +//! @cond IGNORED +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +#define CV_SIMD128 1 + +//MSA implements 128-bit wide vector registers shared with the 64-bit wide floating-point unit registers. +//MSA and FPU can not be both present, unless the FPU has 64-bit floating-point registers. +#define CV_SIMD128_64F 1 + +struct v_uint8x16 +{ + typedef uchar lane_type; + enum { nlanes = 16 }; + + v_uint8x16() {} + explicit v_uint8x16(v16u8 v) : val(v) {} + v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, + uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) + { + uchar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; + val = msa_ld1q_u8(v); + } + + uchar get0() const + { + return msa_getq_lane_u8(val, 0); + } + + v16u8 val; +}; + +struct v_int8x16 +{ + typedef schar lane_type; + enum { nlanes = 16 }; + + v_int8x16() {} + explicit v_int8x16(v16i8 v) : val(v) {} + v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, + schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) + { + schar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; + val = msa_ld1q_s8(v); + } + + schar get0() const + { + return msa_getq_lane_s8(val, 0); + } + + v16i8 val; +}; + +struct v_uint16x8 +{ + typedef ushort lane_type; + enum { nlanes = 8 }; + + v_uint16x8() {} + explicit v_uint16x8(v8u16 v) : val(v) {} + v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) + { + ushort v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; + val = msa_ld1q_u16(v); + } + + ushort get0() const + { + return msa_getq_lane_u16(val, 0); + } + + v8u16 val; +}; + +struct v_int16x8 +{ + typedef short lane_type; + enum { nlanes = 8 }; + + v_int16x8() {} + explicit v_int16x8(v8i16 v) : val(v) {} + v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) + { + short v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; + val = msa_ld1q_s16(v); + } + + short get0() const + { + return msa_getq_lane_s16(val, 0); + } + + v8i16 val; +}; + +struct v_uint32x4 +{ + typedef unsigned int lane_type; + enum { nlanes = 4 }; + + v_uint32x4() {} + explicit v_uint32x4(v4u32 v) : val(v) {} + v_uint32x4(unsigned int v0, unsigned int v1, unsigned int v2, unsigned int v3) + { + unsigned int v[] = {v0, v1, v2, v3}; + val = msa_ld1q_u32(v); + } + + unsigned int get0() const + { + return msa_getq_lane_u32(val, 0); + } + + v4u32 val; +}; + +struct v_int32x4 +{ + typedef int lane_type; + enum { nlanes = 4 }; + + v_int32x4() {} + explicit v_int32x4(v4i32 v) : val(v) {} + v_int32x4(int v0, int v1, int v2, int v3) + { + int v[] = {v0, v1, v2, v3}; + val = msa_ld1q_s32(v); + } + + int get0() const + { + return msa_getq_lane_s32(val, 0); + } + + v4i32 val; +}; + +struct v_float32x4 +{ + typedef float lane_type; + enum { nlanes = 4 }; + + v_float32x4() {} + explicit v_float32x4(v4f32 v) : val(v) {} + v_float32x4(float v0, float v1, float v2, float v3) + { + float v[] = {v0, v1, v2, v3}; + val = msa_ld1q_f32(v); + } + + float get0() const + { + return msa_getq_lane_f32(val, 0); + } + + v4f32 val; +}; + +struct v_uint64x2 +{ + typedef uint64 lane_type; + enum { nlanes = 2 }; + + v_uint64x2() {} + explicit v_uint64x2(v2u64 v) : val(v) {} + v_uint64x2(uint64 v0, uint64 v1) + { + uint64 v[] = {v0, v1}; + val = msa_ld1q_u64(v); + } + + uint64 get0() const + { + return msa_getq_lane_u64(val, 0); + } + + v2u64 val; +}; + +struct v_int64x2 +{ + typedef int64 lane_type; + enum { nlanes = 2 }; + + v_int64x2() {} + explicit v_int64x2(v2i64 v) : val(v) {} + v_int64x2(int64 v0, int64 v1) + { + int64 v[] = {v0, v1}; + val = msa_ld1q_s64(v); + } + + int64 get0() const + { + return msa_getq_lane_s64(val, 0); + } + + v2i64 val; +}; + +struct v_float64x2 +{ + typedef double lane_type; + enum { nlanes = 2 }; + + v_float64x2() {} + explicit v_float64x2(v2f64 v) : val(v) {} + v_float64x2(double v0, double v1) + { + double v[] = {v0, v1}; + val = msa_ld1q_f64(v); + } + + double get0() const + { + return msa_getq_lane_f64(val, 0); + } + + v2f64 val; +}; + +#define OPENCV_HAL_IMPL_MSA_INIT(_Tpv, _Tp, suffix) \ +inline v_##_Tpv v_setzero_##suffix() { return v_##_Tpv(msa_dupq_n_##suffix((_Tp)0)); } \ +inline v_##_Tpv v_setall_##suffix(_Tp v) { return v_##_Tpv(msa_dupq_n_##suffix(v)); } \ +template <> inline v_##_Tpv v_setzero_() { return v_setzero_##suffix(); } \ +template <> inline v_##_Tpv v_setall_(_Tp v) { return v_setall_##suffix(v); } \ +inline v_uint8x16 v_reinterpret_as_u8(const v_##_Tpv& v) { return v_uint8x16(MSA_TPV_REINTERPRET(v16u8, v.val)); } \ +inline v_int8x16 v_reinterpret_as_s8(const v_##_Tpv& v) { return v_int8x16(MSA_TPV_REINTERPRET(v16i8, v.val)); } \ +inline v_uint16x8 v_reinterpret_as_u16(const v_##_Tpv& v) { return v_uint16x8(MSA_TPV_REINTERPRET(v8u16, v.val)); } \ +inline v_int16x8 v_reinterpret_as_s16(const v_##_Tpv& v) { return v_int16x8(MSA_TPV_REINTERPRET(v8i16, v.val)); } \ +inline v_uint32x4 v_reinterpret_as_u32(const v_##_Tpv& v) { return v_uint32x4(MSA_TPV_REINTERPRET(v4u32, v.val)); } \ +inline v_int32x4 v_reinterpret_as_s32(const v_##_Tpv& v) { return v_int32x4(MSA_TPV_REINTERPRET(v4i32, v.val)); } \ +inline v_uint64x2 v_reinterpret_as_u64(const v_##_Tpv& v) { return v_uint64x2(MSA_TPV_REINTERPRET(v2u64, v.val)); } \ +inline v_int64x2 v_reinterpret_as_s64(const v_##_Tpv& v) { return v_int64x2(MSA_TPV_REINTERPRET(v2i64, v.val)); } \ +inline v_float32x4 v_reinterpret_as_f32(const v_##_Tpv& v) { return v_float32x4(MSA_TPV_REINTERPRET(v4f32, v.val)); } \ +inline v_float64x2 v_reinterpret_as_f64(const v_##_Tpv& v) { return v_float64x2(MSA_TPV_REINTERPRET(v2f64, v.val)); } + +OPENCV_HAL_IMPL_MSA_INIT(uint8x16, uchar, u8) +OPENCV_HAL_IMPL_MSA_INIT(int8x16, schar, s8) +OPENCV_HAL_IMPL_MSA_INIT(uint16x8, ushort, u16) +OPENCV_HAL_IMPL_MSA_INIT(int16x8, short, s16) +OPENCV_HAL_IMPL_MSA_INIT(uint32x4, unsigned int, u32) +OPENCV_HAL_IMPL_MSA_INIT(int32x4, int, s32) +OPENCV_HAL_IMPL_MSA_INIT(uint64x2, uint64, u64) +OPENCV_HAL_IMPL_MSA_INIT(int64x2, int64, s64) +OPENCV_HAL_IMPL_MSA_INIT(float32x4, float, f32) +OPENCV_HAL_IMPL_MSA_INIT(float64x2, double, f64) + +#define OPENCV_HAL_IMPL_MSA_PACK(_Tpvec, _Tpwvec, pack, mov, rshr) \ +inline _Tpvec v_##pack(const _Tpwvec& a, const _Tpwvec& b) \ +{ \ + return _Tpvec(mov(a.val, b.val)); \ +} \ +template inline \ +_Tpvec v_rshr_##pack(const _Tpwvec& a, const _Tpwvec& b) \ +{ \ + return _Tpvec(rshr(a.val, b.val, n)); \ +} + +OPENCV_HAL_IMPL_MSA_PACK(v_uint8x16, v_uint16x8, pack, msa_qpack_u16, msa_qrpackr_u16) +OPENCV_HAL_IMPL_MSA_PACK(v_int8x16, v_int16x8, pack, msa_qpack_s16, msa_qrpackr_s16) +OPENCV_HAL_IMPL_MSA_PACK(v_uint16x8, v_uint32x4, pack, msa_qpack_u32, msa_qrpackr_u32) +OPENCV_HAL_IMPL_MSA_PACK(v_int16x8, v_int32x4, pack, msa_qpack_s32, msa_qrpackr_s32) +OPENCV_HAL_IMPL_MSA_PACK(v_uint32x4, v_uint64x2, pack, msa_pack_u64, msa_rpackr_u64) +OPENCV_HAL_IMPL_MSA_PACK(v_int32x4, v_int64x2, pack, msa_pack_s64, msa_rpackr_s64) +OPENCV_HAL_IMPL_MSA_PACK(v_uint8x16, v_int16x8, pack_u, msa_qpacku_s16, msa_qrpackru_s16) +OPENCV_HAL_IMPL_MSA_PACK(v_uint16x8, v_int32x4, pack_u, msa_qpacku_s32, msa_qrpackru_s32) + +#define OPENCV_HAL_IMPL_MSA_PACK_STORE(_Tpvec, _Tp, hreg, suffix, _Tpwvec, pack, mov, rshr) \ +inline void v_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ +{ \ + hreg a1 = mov(a.val); \ + msa_st1_##suffix(ptr, a1); \ +} \ +template inline \ +void v_rshr_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ +{ \ + hreg a1 = rshr(a.val, n); \ + msa_st1_##suffix(ptr, a1); \ +} + +OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint8x16, uchar, v8u8, u8, v_uint16x8, pack, msa_qmovn_u16, msa_qrshrn_n_u16) +OPENCV_HAL_IMPL_MSA_PACK_STORE(v_int8x16, schar, v8i8, s8, v_int16x8, pack, msa_qmovn_s16, msa_qrshrn_n_s16) +OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint16x8, ushort, v4u16, u16, v_uint32x4, pack, msa_qmovn_u32, msa_qrshrn_n_u32) +OPENCV_HAL_IMPL_MSA_PACK_STORE(v_int16x8, short, v4i16, s16, v_int32x4, pack, msa_qmovn_s32, msa_qrshrn_n_s32) +OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint32x4, unsigned, v2u32, u32, v_uint64x2, pack, msa_movn_u64, msa_rshrn_n_u64) +OPENCV_HAL_IMPL_MSA_PACK_STORE(v_int32x4, int, v2i32, s32, v_int64x2, pack, msa_movn_s64, msa_rshrn_n_s64) +OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint8x16, uchar, v8u8, u8, v_int16x8, pack_u, msa_qmovun_s16, msa_qrshrun_n_s16) +OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint16x8, ushort, v4u16, u16, v_int32x4, pack_u, msa_qmovun_s32, msa_qrshrun_n_s32) + +// pack boolean +inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) +{ + return v_uint8x16(msa_pack_u16(a.val, b.val)); +} + +inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, + const v_uint32x4& c, const v_uint32x4& d) +{ + return v_uint8x16(msa_pack_u16(msa_pack_u32(a.val, b.val), msa_pack_u32(c.val, d.val))); +} + +inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, + const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, + const v_uint64x2& g, const v_uint64x2& h) +{ + v8u16 abcd = msa_pack_u32(msa_pack_u64(a.val, b.val), msa_pack_u64(c.val, d.val)); + v8u16 efgh = msa_pack_u32(msa_pack_u64(e.val, f.val), msa_pack_u64(g.val, h.val)); + return v_uint8x16(msa_pack_u16(abcd, efgh)); +} + +inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, + const v_float32x4& m3) +{ + v4f32 v0 = v.val; + v4f32 res = msa_mulq_lane_f32(m0.val, v0, 0); + res = msa_mlaq_lane_f32(res, m1.val, v0, 1); + res = msa_mlaq_lane_f32(res, m2.val, v0, 2); + res = msa_mlaq_lane_f32(res, m3.val, v0, 3); + return v_float32x4(res); +} + +inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, + const v_float32x4& a) +{ + v4f32 v0 = v.val; + v4f32 res = msa_mulq_lane_f32(m0.val, v0, 0); + res = msa_mlaq_lane_f32(res, m1.val, v0, 1); + res = msa_mlaq_lane_f32(res, m2.val, v0, 2); + res = msa_addq_f32(res, a.val); + return v_float32x4(res); +} + +#define OPENCV_HAL_IMPL_MSA_BIN_OP(bin_op, _Tpvec, intrin) \ +inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(intrin(a.val, b.val)); \ +} + +OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_uint8x16, msa_qaddq_u8) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_uint8x16, msa_qsubq_u8) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_int8x16, msa_qaddq_s8) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_int8x16, msa_qsubq_s8) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_uint16x8, msa_qaddq_u16) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_uint16x8, msa_qsubq_u16) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_int16x8, msa_qaddq_s16) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_int16x8, msa_qsubq_s16) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_int32x4, msa_addq_s32) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_int32x4, msa_subq_s32) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_mul, v_int32x4, msa_mulq_s32) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_uint32x4, msa_addq_u32) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_uint32x4, msa_subq_u32) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_mul, v_uint32x4, msa_mulq_u32) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_float32x4, msa_addq_f32) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_float32x4, msa_subq_f32) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_mul, v_float32x4, msa_mulq_f32) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_int64x2, msa_addq_s64) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_int64x2, msa_subq_s64) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_uint64x2, msa_addq_u64) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_uint64x2, msa_subq_u64) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_div, v_float32x4, msa_divq_f32) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_float64x2, msa_addq_f64) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_float64x2, msa_subq_f64) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_mul, v_float64x2, msa_mulq_f64) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_div, v_float64x2, msa_divq_f64) + +// saturating multiply 8-bit, 16-bit +#define OPENCV_HAL_IMPL_MSA_MUL_SAT(_Tpvec, _Tpwvec) \ +inline _Tpvec v_mul(const _Tpvec& a, const _Tpvec& b) \ +{ \ + _Tpwvec c, d; \ + v_mul_expand(a, b, c, d); \ + return v_pack(c, d); \ +} + +OPENCV_HAL_IMPL_MSA_MUL_SAT(v_int8x16, v_int16x8) +OPENCV_HAL_IMPL_MSA_MUL_SAT(v_uint8x16, v_uint16x8) +OPENCV_HAL_IMPL_MSA_MUL_SAT(v_int16x8, v_int32x4) +OPENCV_HAL_IMPL_MSA_MUL_SAT(v_uint16x8, v_uint32x4) + +// Multiply and expand +inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b, + v_int16x8& c, v_int16x8& d) +{ + v16i8 a_lo, a_hi, b_lo, b_hi; + + ILVRL_B2_SB(a.val, msa_dupq_n_s8(0), a_lo, a_hi); + ILVRL_B2_SB(b.val, msa_dupq_n_s8(0), b_lo, b_hi); + c.val = msa_mulq_s16(msa_paddlq_s8(a_lo), msa_paddlq_s8(b_lo)); + d.val = msa_mulq_s16(msa_paddlq_s8(a_hi), msa_paddlq_s8(b_hi)); +} + +inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b, + v_uint16x8& c, v_uint16x8& d) +{ + v16u8 a_lo, a_hi, b_lo, b_hi; + + ILVRL_B2_UB(a.val, msa_dupq_n_u8(0), a_lo, a_hi); + ILVRL_B2_UB(b.val, msa_dupq_n_u8(0), b_lo, b_hi); + c.val = msa_mulq_u16(msa_paddlq_u8(a_lo), msa_paddlq_u8(b_lo)); + d.val = msa_mulq_u16(msa_paddlq_u8(a_hi), msa_paddlq_u8(b_hi)); +} + +inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, + v_int32x4& c, v_int32x4& d) +{ + v8i16 a_lo, a_hi, b_lo, b_hi; + + ILVRL_H2_SH(a.val, msa_dupq_n_s16(0), a_lo, a_hi); + ILVRL_H2_SH(b.val, msa_dupq_n_s16(0), b_lo, b_hi); + c.val = msa_mulq_s32(msa_paddlq_s16(a_lo), msa_paddlq_s16(b_lo)); + d.val = msa_mulq_s32(msa_paddlq_s16(a_hi), msa_paddlq_s16(b_hi)); +} + +inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, + v_uint32x4& c, v_uint32x4& d) +{ + v8u16 a_lo, a_hi, b_lo, b_hi; + + ILVRL_H2_UH(a.val, msa_dupq_n_u16(0), a_lo, a_hi); + ILVRL_H2_UH(b.val, msa_dupq_n_u16(0), b_lo, b_hi); + c.val = msa_mulq_u32(msa_paddlq_u16(a_lo), msa_paddlq_u16(b_lo)); + d.val = msa_mulq_u32(msa_paddlq_u16(a_hi), msa_paddlq_u16(b_hi)); +} + +inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, + v_uint64x2& c, v_uint64x2& d) +{ + v4u32 a_lo, a_hi, b_lo, b_hi; + + ILVRL_W2_UW(a.val, msa_dupq_n_u32(0), a_lo, a_hi); + ILVRL_W2_UW(b.val, msa_dupq_n_u32(0), b_lo, b_hi); + c.val = msa_mulq_u64(msa_paddlq_u32(a_lo), msa_paddlq_u32(b_lo)); + d.val = msa_mulq_u64(msa_paddlq_u32(a_hi), msa_paddlq_u32(b_hi)); +} + +inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) +{ + v8i16 a_lo, a_hi, b_lo, b_hi; + + ILVRL_H2_SH(a.val, msa_dupq_n_s16(0), a_lo, a_hi); + ILVRL_H2_SH(b.val, msa_dupq_n_s16(0), b_lo, b_hi); + + return v_int16x8(msa_packr_s32(msa_mulq_s32(msa_paddlq_s16(a_lo), msa_paddlq_s16(b_lo)), + msa_mulq_s32(msa_paddlq_s16(a_hi), msa_paddlq_s16(b_hi)), 16)); +} + +inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) +{ + v8u16 a_lo, a_hi, b_lo, b_hi; + + ILVRL_H2_UH(a.val, msa_dupq_n_u16(0), a_lo, a_hi); + ILVRL_H2_UH(b.val, msa_dupq_n_u16(0), b_lo, b_hi); + + return v_uint16x8(msa_packr_u32(msa_mulq_u32(msa_paddlq_u16(a_lo), msa_paddlq_u16(b_lo)), + msa_mulq_u32(msa_paddlq_u16(a_hi), msa_paddlq_u16(b_hi)), 16)); +} + +//////// Dot Product //////// + +// 16 >> 32 +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) +{ return v_int32x4(msa_dotp_s_w(a.val, b.val)); } +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ return v_int32x4(msa_dpadd_s_w(c.val , a.val, b.val)); } + +// 32 >> 64 +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) +{ return v_int64x2(msa_dotp_s_d(a.val, b.val)); } +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ return v_int64x2(msa_dpadd_s_d(c.val , a.val, b.val)); } + +// 8 >> 32 +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) +{ + v8u16 even_a = msa_shrq_n_u16(msa_shlq_n_u16(MSA_TPV_REINTERPRET(v8u16, a.val), 8), 8); + v8u16 odd_a = msa_shrq_n_u16(MSA_TPV_REINTERPRET(v8u16, a.val), 8); + v8u16 even_b = msa_shrq_n_u16(msa_shlq_n_u16(MSA_TPV_REINTERPRET(v8u16, b.val), 8), 8); + v8u16 odd_b = msa_shrq_n_u16(MSA_TPV_REINTERPRET(v8u16, b.val), 8); + v4u32 prod = msa_dotp_u_w(even_a, even_b); + return v_uint32x4(msa_dpadd_u_w(prod, odd_a, odd_b)); +} +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) +{ + v8u16 even_a = msa_shrq_n_u16(msa_shlq_n_u16(MSA_TPV_REINTERPRET(v8u16, a.val), 8), 8); + v8u16 odd_a = msa_shrq_n_u16(MSA_TPV_REINTERPRET(v8u16, a.val), 8); + v8u16 even_b = msa_shrq_n_u16(msa_shlq_n_u16(MSA_TPV_REINTERPRET(v8u16, b.val), 8), 8); + v8u16 odd_b = msa_shrq_n_u16(MSA_TPV_REINTERPRET(v8u16, b.val), 8); + v4u32 prod = msa_dpadd_u_w(c.val, even_a, even_b); + return v_uint32x4(msa_dpadd_u_w(prod, odd_a, odd_b)); +} + +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) +{ + v8i16 prod = msa_dotp_s_h(a.val, b.val); + return v_int32x4(msa_hadd_s32(prod, prod)); +} +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, + const v_int32x4& c) +{ return v_dotprod_expand(a, b) + c; } + +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) +{ + v4u32 even_a = msa_shrq_n_u32(msa_shlq_n_u32(MSA_TPV_REINTERPRET(v4u32, a.val), 16), 16); + v4u32 odd_a = msa_shrq_n_u32(MSA_TPV_REINTERPRET(v4u32, a.val), 16); + v4u32 even_b = msa_shrq_n_u32(msa_shlq_n_u32(MSA_TPV_REINTERPRET(v4u32, b.val), 16), 16); + v4u32 odd_b = msa_shrq_n_u32(MSA_TPV_REINTERPRET(v4u32, b.val), 16); + v2u64 prod = msa_dotp_u_d(even_a, even_b); + return v_uint64x2(msa_dpadd_u_d(prod, odd_a, odd_b)); +} +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, + const v_uint64x2& c) +{ + v4u32 even_a = msa_shrq_n_u32(msa_shlq_n_u32(MSA_TPV_REINTERPRET(v4u32, a.val), 16), 16); + v4u32 odd_a = msa_shrq_n_u32(MSA_TPV_REINTERPRET(v4u32, a.val), 16); + v4u32 even_b = msa_shrq_n_u32(msa_shlq_n_u32(MSA_TPV_REINTERPRET(v4u32, b.val), 16), 16); + v4u32 odd_b = msa_shrq_n_u32(MSA_TPV_REINTERPRET(v4u32, b.val), 16); + v2u64 prod = msa_dpadd_u_d(c.val, even_a, even_b); + return v_uint64x2(msa_dpadd_u_d(prod, odd_a, odd_b)); +} + +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) +{ + v4i32 prod = msa_dotp_s_w(a.val, b.val); + return v_int64x2(msa_hadd_s64(prod, prod)); +} +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 32 >> 64f +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) +{ return v_cvt_f64(v_dotprod(a, b)); } +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + + +//////// Fast Dot Product //////// + +// 16 >> 32 +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) +{ return v_dotprod(a, b); } +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ return v_dotprod(a, b, c); } + +// 32 >> 64 +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) +{ return v_dotprod(a, b); } +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ return v_dotprod(a, b, c); } + +// 8 >> 32 +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) +{ return v_dotprod_expand(a, b); } +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) +{ return v_dotprod_expand(a, b, c); } +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) +{ return v_dotprod_expand(a, b); } +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) +{ return v_dotprod_expand(a, b, c); } + +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) +{ return v_dotprod_expand(a, b); } +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) +{ return v_dotprod_expand(a, b, c); } +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) +{ return v_dotprod_expand(a, b); } +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) +{ return v_dotprod_expand(a, b, c); } + +// 32 >> 64f +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) +{ return v_dotprod_expand(a, b); } +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) +{ return v_dotprod_expand(a, b, c); } + +#define OPENCV_HAL_IMPL_MSA_LOGIC_OP(_Tpvec, _Tpv, suffix) \ +OPENCV_HAL_IMPL_MSA_BIN_OP(v_and, _Tpvec, msa_andq_##suffix) \ +OPENCV_HAL_IMPL_MSA_BIN_OP(v_or, _Tpvec, msa_orrq_##suffix) \ +OPENCV_HAL_IMPL_MSA_BIN_OP(v_xor, _Tpvec, msa_eorq_##suffix) \ +inline _Tpvec v_not(const _Tpvec& a) \ +{ \ + return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_mvnq_u8(MSA_TPV_REINTERPRET(v16u8, a.val)))); \ +} + +OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_uint8x16, v16u8, u8) +OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_int8x16, v16i8, s8) +OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_uint16x8, v8u16, u16) +OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_int16x8, v8i16, s16) +OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_uint32x4, v4u32, u32) +OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_int32x4, v4i32, s32) +OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_uint64x2, v2u64, u64) +OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_int64x2, v2i64, s64) + +#define OPENCV_HAL_IMPL_MSA_FLT_BIT_OP(bin_op, intrin) \ +inline v_float32x4 bin_op(const v_float32x4& a, const v_float32x4& b) \ +{ \ + return v_float32x4(MSA_TPV_REINTERPRET(v4f32, intrin(MSA_TPV_REINTERPRET(v4i32, a.val), MSA_TPV_REINTERPRET(v4i32, b.val)))); \ +} + +OPENCV_HAL_IMPL_MSA_FLT_BIT_OP(v_and, msa_andq_s32) +OPENCV_HAL_IMPL_MSA_FLT_BIT_OP(v_or, msa_orrq_s32) +OPENCV_HAL_IMPL_MSA_FLT_BIT_OP(v_xor, msa_eorq_s32) + +inline v_float32x4 v_not(const v_float32x4& a) +{ + return v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_mvnq_s32(MSA_TPV_REINTERPRET(v4i32, a.val)))); +} + +/* v_abs */ +#define OPENCV_HAL_IMPL_MSA_ABS(_Tpuvec, _Tpsvec, usuffix, ssuffix) \ +inline _Tpuvec v_abs(const _Tpsvec& a) \ +{ \ + return v_reinterpret_as_##usuffix(_Tpsvec(msa_absq_##ssuffix(a.val))); \ +} + +OPENCV_HAL_IMPL_MSA_ABS(v_uint8x16, v_int8x16, u8, s8) +OPENCV_HAL_IMPL_MSA_ABS(v_uint16x8, v_int16x8, u16, s16) +OPENCV_HAL_IMPL_MSA_ABS(v_uint32x4, v_int32x4, u32, s32) + +/* v_abs(float), v_sqrt, v_invsqrt */ +#define OPENCV_HAL_IMPL_MSA_BASIC_FUNC(_Tpvec, func, intrin) \ +inline _Tpvec func(const _Tpvec& a) \ +{ \ + return _Tpvec(intrin(a.val)); \ +} + +OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float32x4, v_abs, msa_absq_f32) +OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float64x2, v_abs, msa_absq_f64) +OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float32x4, v_sqrt, msa_sqrtq_f32) +OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float32x4, v_invsqrt, msa_rsqrtq_f32) +OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float64x2, v_sqrt, msa_sqrtq_f64) +OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float64x2, v_invsqrt, msa_rsqrtq_f64) + +#define OPENCV_HAL_IMPL_MSA_DBL_BIT_OP(bin_op, intrin) \ +inline v_float64x2 bin_op(const v_float64x2& a, const v_float64x2& b) \ +{ \ + return v_float64x2(MSA_TPV_REINTERPRET(v2f64, intrin(MSA_TPV_REINTERPRET(v2i64, a.val), MSA_TPV_REINTERPRET(v2i64, b.val)))); \ +} + +OPENCV_HAL_IMPL_MSA_DBL_BIT_OP(v_and, msa_andq_s64) +OPENCV_HAL_IMPL_MSA_DBL_BIT_OP(v_or, msa_orrq_s64) +OPENCV_HAL_IMPL_MSA_DBL_BIT_OP(v_xor, msa_eorq_s64) + +inline v_float64x2 v_not(const v_float64x2& a) +{ + return v_float64x2(MSA_TPV_REINTERPRET(v2f64, msa_mvnq_s32(MSA_TPV_REINTERPRET(v4i32, a.val)))); +} + +// TODO: exp, log, sin, cos + +#define OPENCV_HAL_IMPL_MSA_BIN_FUNC(_Tpvec, func, intrin) \ +inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(intrin(a.val, b.val)); \ +} + +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_min, msa_minq_u8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_max, msa_maxq_u8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_min, msa_minq_s8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_max, msa_maxq_s8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_min, msa_minq_u16) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_max, msa_maxq_u16) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_min, msa_minq_s16) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_max, msa_maxq_s16) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint32x4, v_min, msa_minq_u32) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint32x4, v_max, msa_maxq_u32) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int32x4, v_min, msa_minq_s32) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int32x4, v_max, msa_maxq_s32) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float32x4, v_min, msa_minq_f32) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float32x4, v_max, msa_maxq_f32) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float64x2, v_min, msa_minq_f64) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float64x2, v_max, msa_maxq_f64) + +#define OPENCV_HAL_IMPL_MSA_INT_CMP_OP(_Tpvec, _Tpv, suffix, not_suffix) \ +inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_ceqq_##suffix(a.val, b.val))); } \ +inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_mvnq_##not_suffix(msa_ceqq_##suffix(a.val, b.val)))); } \ +inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_cltq_##suffix(a.val, b.val))); } \ +inline _Tpvec v_gt(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_cgtq_##suffix(a.val, b.val))); } \ +inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_cleq_##suffix(a.val, b.val))); } \ +inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_cgeq_##suffix(a.val, b.val))); } + +OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_uint8x16, v16u8, u8, u8) +OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_int8x16, v16i8, s8, u8) +OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_uint16x8, v8u16, u16, u16) +OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_int16x8, v8i16, s16, u16) +OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_uint32x4, v4u32, u32, u32) +OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_int32x4, v4i32, s32, u32) +OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_float32x4, v4f32, f32, u32) +OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_uint64x2, v2u64, u64, u64) +OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_int64x2, v2i64, s64, u64) +OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_float64x2, v2f64, f64, u64) + +inline v_float32x4 v_not_nan(const v_float32x4& a) +{ return v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_ceqq_f32(a.val, a.val))); } +inline v_float64x2 v_not_nan(const v_float64x2& a) +{ return v_float64x2(MSA_TPV_REINTERPRET(v2f64, msa_ceqq_f64(a.val, a.val))); } + +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_add_wrap, msa_addq_u8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_add_wrap, msa_addq_s8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_add_wrap, msa_addq_u16) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_add_wrap, msa_addq_s16) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_sub_wrap, msa_subq_u8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_sub_wrap, msa_subq_s8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_sub_wrap, msa_subq_u16) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_sub_wrap, msa_subq_s16) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_mul_wrap, msa_mulq_u8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_mul_wrap, msa_mulq_s8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_mul_wrap, msa_mulq_u16) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_mul_wrap, msa_mulq_s16) + +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_absdiff, msa_abdq_u8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_absdiff, msa_abdq_u16) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint32x4, v_absdiff, msa_abdq_u32) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float32x4, v_absdiff, msa_abdq_f32) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float64x2, v_absdiff, msa_abdq_f64) + +/** Saturating absolute difference **/ +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_absdiffs, msa_qabdq_s8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_absdiffs, msa_qabdq_s16) + +#define OPENCV_HAL_IMPL_MSA_BIN_FUNC2(_Tpvec, _Tpvec2, _Tpv, func, intrin) \ +inline _Tpvec2 func(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec2(MSA_TPV_REINTERPRET(_Tpv, intrin(a.val, b.val))); \ +} + +OPENCV_HAL_IMPL_MSA_BIN_FUNC2(v_int8x16, v_uint8x16, v16u8, v_absdiff, msa_abdq_s8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC2(v_int16x8, v_uint16x8, v8u16, v_absdiff, msa_abdq_s16) +OPENCV_HAL_IMPL_MSA_BIN_FUNC2(v_int32x4, v_uint32x4, v4u32, v_absdiff, msa_abdq_s32) + +/* v_magnitude, v_sqr_magnitude, v_fma, v_muladd */ +inline v_float32x4 v_magnitude(const v_float32x4& a, const v_float32x4& b) +{ + v_float32x4 x(msa_mlaq_f32(msa_mulq_f32(a.val, a.val), b.val, b.val)); + return v_sqrt(x); +} + +inline v_float32x4 v_sqr_magnitude(const v_float32x4& a, const v_float32x4& b) +{ + return v_float32x4(msa_mlaq_f32(msa_mulq_f32(a.val, a.val), b.val, b.val)); +} + +inline v_float32x4 v_fma(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) +{ + return v_float32x4(msa_mlaq_f32(c.val, a.val, b.val)); +} + +inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ + return v_int32x4(msa_mlaq_s32(c.val, a.val, b.val)); +} + +inline v_float32x4 v_muladd(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) +{ + return v_fma(a, b, c); +} + +inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ + return v_fma(a, b, c); +} + +inline v_float64x2 v_magnitude(const v_float64x2& a, const v_float64x2& b) +{ + v_float64x2 x(msa_mlaq_f64(msa_mulq_f64(a.val, a.val), b.val, b.val)); + return v_sqrt(x); +} + +inline v_float64x2 v_sqr_magnitude(const v_float64x2& a, const v_float64x2& b) +{ + return v_float64x2(msa_mlaq_f64(msa_mulq_f64(a.val, a.val), b.val, b.val)); +} + +inline v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) +{ + return v_float64x2(msa_mlaq_f64(c.val, a.val, b.val)); +} + +inline v_float64x2 v_muladd(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) +{ + return v_fma(a, b, c); +} + +// trade efficiency for convenience +#define OPENCV_HAL_IMPL_MSA_SHIFT_OP(_Tpvec, suffix, _Tps, ssuffix) \ +inline _Tpvec v_shl(const _Tpvec& a, int n) \ +{ return _Tpvec(msa_shlq_##suffix(a.val, msa_dupq_n_##ssuffix((_Tps)n))); } \ +inline _Tpvec v_shr(const _Tpvec& a, int n) \ +{ return _Tpvec(msa_shrq_##suffix(a.val, msa_dupq_n_##ssuffix((_Tps)n))); } \ +template inline _Tpvec v_shl(const _Tpvec& a) \ +{ return _Tpvec(msa_shlq_n_##suffix(a.val, n)); } \ +template inline _Tpvec v_shr(const _Tpvec& a) \ +{ return _Tpvec(msa_shrq_n_##suffix(a.val, n)); } \ +template inline _Tpvec v_rshr(const _Tpvec& a) \ +{ return _Tpvec(msa_rshrq_n_##suffix(a.val, n)); } + +OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_uint8x16, u8, schar, s8) +OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_int8x16, s8, schar, s8) +OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_uint16x8, u16, short, s16) +OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_int16x8, s16, short, s16) +OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_uint32x4, u32, int, s32) +OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_int32x4, s32, int, s32) +OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_uint64x2, u64, int64, s64) +OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_int64x2, s64, int64, s64) + +/* v_rotate_right, v_rotate_left */ +#define OPENCV_HAL_IMPL_MSA_ROTATE_OP(_Tpvec, _Tpv, _Tpvs, suffix) \ +template inline _Tpvec v_rotate_right(const _Tpvec& a) \ +{ \ + return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##suffix(0), n))); \ +} \ +template inline _Tpvec v_rotate_left(const _Tpvec& a) \ +{ \ + return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(msa_dupq_n_##suffix(0), MSA_TPV_REINTERPRET(_Tpvs, a.val), _Tpvec::nlanes - n))); \ +} \ +template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a) \ +{ \ + return a; \ +} \ +template inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), MSA_TPV_REINTERPRET(_Tpvs, b.val), n))); \ +} \ +template inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(MSA_TPV_REINTERPRET(_Tpvs, b.val), MSA_TPV_REINTERPRET(_Tpvs, a.val), _Tpvec::nlanes - n))); \ +} \ +template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a, const _Tpvec& b) \ +{ \ + CV_UNUSED(b); \ + return a; \ +} + +OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_uint8x16, v16u8, v16i8, s8) +OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_int8x16, v16i8, v16i8, s8) +OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_uint16x8, v8u16, v8i16, s16) +OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_int16x8, v8i16, v8i16, s16) +OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_uint32x4, v4u32, v4i32, s32) +OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_int32x4, v4i32, v4i32, s32) +OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_float32x4, v4f32, v4i32, s32) +OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_uint64x2, v2u64, v2i64, s64) +OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_int64x2, v2i64, v2i64, s64) +OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_float64x2, v2f64, v2i64, s64) + +#define OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(_Tpvec, _Tp, suffix) \ +inline _Tpvec v_load(const _Tp* ptr) \ +{ return _Tpvec(msa_ld1q_##suffix(ptr)); } \ +inline _Tpvec v_load_aligned(const _Tp* ptr) \ +{ return _Tpvec(msa_ld1q_##suffix(ptr)); } \ +inline _Tpvec v_load_low(const _Tp* ptr) \ +{ return _Tpvec(msa_combine_##suffix(msa_ld1_##suffix(ptr), msa_dup_n_##suffix((_Tp)0))); } \ +inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ +{ return _Tpvec(msa_combine_##suffix(msa_ld1_##suffix(ptr0), msa_ld1_##suffix(ptr1))); } \ +inline void v_store(_Tp* ptr, const _Tpvec& a) \ +{ msa_st1q_##suffix(ptr, a.val); } \ +inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ +{ msa_st1q_##suffix(ptr, a.val); } \ +inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ +{ msa_st1q_##suffix(ptr, a.val); } \ +inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ +{ msa_st1q_##suffix(ptr, a.val); } \ +inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ +{ \ + int n = _Tpvec::nlanes; \ + for( int i = 0; i < (n/2); i++ ) \ + ptr[i] = a.val[i]; \ +} \ +inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ +{ \ + int n = _Tpvec::nlanes; \ + for( int i = 0; i < (n/2); i++ ) \ + ptr[i] = a.val[i+(n/2)]; \ +} + +OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_uint8x16, uchar, u8) +OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_int8x16, schar, s8) +OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_uint16x8, ushort, u16) +OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_int16x8, short, s16) +OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_uint32x4, unsigned, u32) +OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_int32x4, int, s32) +OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_uint64x2, uint64, u64) +OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_int64x2, int64, s64) +OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_float32x4, float, f32) +OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_float64x2, double, f64) + + +/** Reverse **/ +inline v_uint8x16 v_reverse(const v_uint8x16 &a) +{ + v_uint8x16 c = v_uint8x16((v16u8)__builtin_msa_vshf_b((v16i8)((v2i64){0x08090A0B0C0D0E0F, 0x0001020304050607}), msa_dupq_n_s8(0), (v16i8)a.val)); + return c; +} + +inline v_int8x16 v_reverse(const v_int8x16 &a) +{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } + +inline v_uint16x8 v_reverse(const v_uint16x8 &a) +{ + v_uint16x8 c = v_uint16x8((v8u16)__builtin_msa_vshf_h((v8i16)((v2i64){0x0004000500060007, 0x0000000100020003}), msa_dupq_n_s16(0), (v8i16)a.val)); + return c; +} + +inline v_int16x8 v_reverse(const v_int16x8 &a) +{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } + +inline v_uint32x4 v_reverse(const v_uint32x4 &a) +{ + v_uint32x4 c; + c.val[0] = a.val[3]; + c.val[1] = a.val[2]; + c.val[2] = a.val[1]; + c.val[3] = a.val[0]; + return c; +} + +inline v_int32x4 v_reverse(const v_int32x4 &a) +{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_float32x4 v_reverse(const v_float32x4 &a) +{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_uint64x2 v_reverse(const v_uint64x2 &a) +{ + v_uint64x2 c; + c.val[0] = a.val[1]; + c.val[1] = a.val[0]; + return c; +} + +inline v_int64x2 v_reverse(const v_int64x2 &a) +{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } + +inline v_float64x2 v_reverse(const v_float64x2 &a) +{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } + + +#define OPENCV_HAL_IMPL_MSA_REDUCE_OP_8U(func, cfunc) \ +inline unsigned short v_reduce_##func(const v_uint16x8& a) \ +{ \ + v8u16 a_lo, a_hi; \ + ILVRL_H2_UH(a.val, msa_dupq_n_u16(0), a_lo, a_hi); \ + v4u32 b = msa_##func##q_u32(msa_paddlq_u16(a_lo), msa_paddlq_u16(a_hi)); \ + v4u32 b_lo, b_hi; \ + ILVRL_W2_UW(b, msa_dupq_n_u32(0), b_lo, b_hi); \ + v2u64 c = msa_##func##q_u64(msa_paddlq_u32(b_lo), msa_paddlq_u32(b_hi)); \ + return (unsigned short)cfunc(c[0], c[1]); \ +} + +OPENCV_HAL_IMPL_MSA_REDUCE_OP_8U(max, std::max) +OPENCV_HAL_IMPL_MSA_REDUCE_OP_8U(min, std::min) + +#define OPENCV_HAL_IMPL_MSA_REDUCE_OP_8S(func, cfunc) \ +inline short v_reduce_##func(const v_int16x8& a) \ +{ \ + v8i16 a_lo, a_hi; \ + ILVRL_H2_SH(a.val, msa_dupq_n_s16(0), a_lo, a_hi); \ + v4i32 b = msa_##func##q_s32(msa_paddlq_s16(a_lo), msa_paddlq_s16(a_hi)); \ + v4i32 b_lo, b_hi; \ + ILVRL_W2_SW(b, msa_dupq_n_s32(0), b_lo, b_hi); \ + v2i64 c = msa_##func##q_s64(msa_paddlq_s32(b_lo), msa_paddlq_s32(b_hi)); \ + return (short)cfunc(c[0], c[1]); \ +} + +OPENCV_HAL_IMPL_MSA_REDUCE_OP_8S(max, std::max) +OPENCV_HAL_IMPL_MSA_REDUCE_OP_8S(min, std::min) + +#define OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(_Tpvec, scalartype, func, cfunc) \ +inline scalartype v_reduce_##func(const _Tpvec& a) \ +{ \ + return (scalartype)cfunc(cfunc(a.val[0], a.val[1]), cfunc(a.val[2], a.val[3])); \ +} + +OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_uint32x4, unsigned, max, std::max) +OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_uint32x4, unsigned, min, std::min) +OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_int32x4, int, max, std::max) +OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_int32x4, int, min, std::min) +OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_float32x4, float, max, std::max) +OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_float32x4, float, min, std::min) + + +#define OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(_Tpvec, scalartype, _Tpvec2, func) \ +inline scalartype v_reduce_##func(const _Tpvec& a) \ +{ \ + _Tpvec2 a1, a2; \ + v_expand(a, a1, a2); \ + return (scalartype)v_reduce_##func(v_##func(a1, a2)); \ +} + +OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(v_uint8x16, uchar, v_uint16x8, min) +OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(v_uint8x16, uchar, v_uint16x8, max) +OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(v_int8x16, char, v_int16x8, min) +OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(v_int8x16, char, v_int16x8, max) + + + +#define OPENCV_HAL_IMPL_MSA_REDUCE_SUM(_Tpvec, scalartype, suffix) \ +inline scalartype v_reduce_sum(const _Tpvec& a) \ +{ \ + return (scalartype)msa_sum_##suffix(a.val); \ +} + +OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_uint8x16, unsigned short, u8) +OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_int8x16, short, s8) +OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_uint16x8, unsigned, u16) +OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_int16x8, int, s16) +OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_uint32x4, uint64_t, u32) +OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_int32x4, int64_t, s32) +OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_float32x4, float, f32) + +inline uint64 v_reduce_sum(const v_uint64x2& a) +{ return (uint64)(msa_getq_lane_u64(a.val, 0) + msa_getq_lane_u64(a.val, 1)); } +inline int64 v_reduce_sum(const v_int64x2& a) +{ return (int64)(msa_getq_lane_s64(a.val, 0) + msa_getq_lane_s64(a.val, 1)); } +inline double v_reduce_sum(const v_float64x2& a) +{ + return msa_getq_lane_f64(a.val, 0) + msa_getq_lane_f64(a.val, 1); +} + +/* v_reduce_sum4, v_reduce_sad */ +inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, + const v_float32x4& c, const v_float32x4& d) +{ + v4f32 u0 = msa_addq_f32(MSA_TPV_REINTERPRET(v4f32, msa_ilvevq_s32(MSA_TPV_REINTERPRET(v4i32, b.val), MSA_TPV_REINTERPRET(v4i32, a.val))), + MSA_TPV_REINTERPRET(v4f32, msa_ilvodq_s32(MSA_TPV_REINTERPRET(v4i32, b.val), MSA_TPV_REINTERPRET(v4i32, a.val)))); // a0+a1 b0+b1 a2+a3 b2+b3 + v4f32 u1 = msa_addq_f32(MSA_TPV_REINTERPRET(v4f32, msa_ilvevq_s32(MSA_TPV_REINTERPRET(v4i32, d.val), MSA_TPV_REINTERPRET(v4i32, c.val))), + MSA_TPV_REINTERPRET(v4f32, msa_ilvodq_s32(MSA_TPV_REINTERPRET(v4i32, d.val), MSA_TPV_REINTERPRET(v4i32, c.val)))); // c0+c1 d0+d1 c2+c3 d2+d3 + + return v_float32x4(msa_addq_f32(MSA_TPV_REINTERPRET(v4f32, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, u1), MSA_TPV_REINTERPRET(v2i64, u0))), + MSA_TPV_REINTERPRET(v4f32, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, u1), MSA_TPV_REINTERPRET(v2i64, u0))))); +} + +inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b) +{ + v16u8 t0 = msa_abdq_u8(a.val, b.val); + v8u16 t1 = msa_paddlq_u8(t0); + v4u32 t2 = msa_paddlq_u16(t1); + return msa_sum_u32(t2); +} +inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b) +{ + v16u8 t0 = MSA_TPV_REINTERPRET(v16u8, msa_abdq_s8(a.val, b.val)); + v8u16 t1 = msa_paddlq_u8(t0); + v4u32 t2 = msa_paddlq_u16(t1); + return msa_sum_u32(t2); +} +inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b) +{ + v8u16 t0 = msa_abdq_u16(a.val, b.val); + v4u32 t1 = msa_paddlq_u16(t0); + return msa_sum_u32(t1); +} +inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b) +{ + v8u16 t0 = MSA_TPV_REINTERPRET(v8u16, msa_abdq_s16(a.val, b.val)); + v4u32 t1 = msa_paddlq_u16(t0); + return msa_sum_u32(t1); +} +inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b) +{ + v4u32 t0 = msa_abdq_u32(a.val, b.val); + return msa_sum_u32(t0); +} +inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b) +{ + v4u32 t0 = MSA_TPV_REINTERPRET(v4u32, msa_abdq_s32(a.val, b.val)); + return msa_sum_u32(t0); +} +inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) +{ + v4f32 t0 = msa_abdq_f32(a.val, b.val); + return msa_sum_f32(t0); +} + +/* v_popcount */ +#define OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE8(_Tpvec) \ +inline v_uint8x16 v_popcount(const _Tpvec& a) \ +{ \ + v16u8 t = MSA_TPV_REINTERPRET(v16u8, msa_cntq_s8(MSA_TPV_REINTERPRET(v16i8, a.val))); \ + return v_uint8x16(t); \ +} +OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE8(v_uint8x16) +OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE8(v_int8x16) + +#define OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE16(_Tpvec) \ +inline v_uint16x8 v_popcount(const _Tpvec& a) \ +{ \ + v8u16 t = MSA_TPV_REINTERPRET(v8u16, msa_cntq_s16(MSA_TPV_REINTERPRET(v8i16, a.val))); \ + return v_uint16x8(t); \ +} +OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE16(v_uint16x8) +OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE16(v_int16x8) + +#define OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE32(_Tpvec) \ +inline v_uint32x4 v_popcount(const _Tpvec& a) \ +{ \ + v4u32 t = MSA_TPV_REINTERPRET(v4u32, msa_cntq_s32(MSA_TPV_REINTERPRET(v4i32, a.val))); \ + return v_uint32x4(t); \ +} +OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE32(v_uint32x4) +OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE32(v_int32x4) + +#define OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE64(_Tpvec) \ +inline v_uint64x2 v_popcount(const _Tpvec& a) \ +{ \ + v2u64 t = MSA_TPV_REINTERPRET(v2u64, msa_cntq_s64(MSA_TPV_REINTERPRET(v2i64, a.val))); \ + return v_uint64x2(t); \ +} +OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE64(v_uint64x2) +OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE64(v_int64x2) + +inline int v_signmask(const v_uint8x16& a) +{ + v8i8 m0 = msa_create_s8(CV_BIG_UINT(0x0706050403020100)); + v16u8 v0 = msa_shlq_u8(msa_shrq_n_u8(a.val, 7), msa_combine_s8(m0, m0)); + v8u16 v1 = msa_paddlq_u8(v0); + v4u32 v2 = msa_paddlq_u16(v1); + v2u64 v3 = msa_paddlq_u32(v2); + return (int)msa_getq_lane_u64(v3, 0) + ((int)msa_getq_lane_u64(v3, 1) << 8); +} +inline int v_signmask(const v_int8x16& a) +{ return v_signmask(v_reinterpret_as_u8(a)); } + +inline int v_signmask(const v_uint16x8& a) +{ + v4i16 m0 = msa_create_s16(CV_BIG_UINT(0x0003000200010000)); + v8u16 v0 = msa_shlq_u16(msa_shrq_n_u16(a.val, 15), msa_combine_s16(m0, m0)); + v4u32 v1 = msa_paddlq_u16(v0); + v2u64 v2 = msa_paddlq_u32(v1); + return (int)msa_getq_lane_u64(v2, 0) + ((int)msa_getq_lane_u64(v2, 1) << 4); +} +inline int v_signmask(const v_int16x8& a) +{ return v_signmask(v_reinterpret_as_u16(a)); } + +inline int v_signmask(const v_uint32x4& a) +{ + v2i32 m0 = msa_create_s32(CV_BIG_UINT(0x0000000100000000)); + v4u32 v0 = msa_shlq_u32(msa_shrq_n_u32(a.val, 31), msa_combine_s32(m0, m0)); + v2u64 v1 = msa_paddlq_u32(v0); + return (int)msa_getq_lane_u64(v1, 0) + ((int)msa_getq_lane_u64(v1, 1) << 2); +} +inline int v_signmask(const v_int32x4& a) +{ return v_signmask(v_reinterpret_as_u32(a)); } +inline int v_signmask(const v_float32x4& a) +{ return v_signmask(v_reinterpret_as_u32(a)); } + +inline int v_signmask(const v_uint64x2& a) +{ + v2u64 v0 = msa_shrq_n_u64(a.val, 63); + return (int)msa_getq_lane_u64(v0, 0) + ((int)msa_getq_lane_u64(v0, 1) << 1); +} +inline int v_signmask(const v_int64x2& a) +{ return v_signmask(v_reinterpret_as_u64(a)); } +inline int v_signmask(const v_float64x2& a) +{ return v_signmask(v_reinterpret_as_u64(a)); } + +inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(a)); } + +#define OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(_Tpvec, _Tpvec2, suffix, shift) \ +inline bool v_check_all(const v_##_Tpvec& a) \ +{ \ + _Tpvec2 v0 = msa_shrq_n_##suffix(msa_mvnq_##suffix(a.val), shift); \ + v2u64 v1 = MSA_TPV_REINTERPRET(v2u64, v0); \ + return (msa_getq_lane_u64(v1, 0) | msa_getq_lane_u64(v1, 1)) == 0; \ +} \ +inline bool v_check_any(const v_##_Tpvec& a) \ +{ \ + _Tpvec2 v0 = msa_shrq_n_##suffix(a.val, shift); \ + v2u64 v1 = MSA_TPV_REINTERPRET(v2u64, v0); \ + return (msa_getq_lane_u64(v1, 0) | msa_getq_lane_u64(v1, 1)) != 0; \ +} + +OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(uint8x16, v16u8, u8, 7) +OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(uint16x8, v8u16, u16, 15) +OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(uint32x4, v4u32, u32, 31) +OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(uint64x2, v2u64, u64, 63) + +inline bool v_check_all(const v_int8x16& a) +{ return v_check_all(v_reinterpret_as_u8(a)); } +inline bool v_check_all(const v_int16x8& a) +{ return v_check_all(v_reinterpret_as_u16(a)); } +inline bool v_check_all(const v_int32x4& a) +{ return v_check_all(v_reinterpret_as_u32(a)); } +inline bool v_check_all(const v_float32x4& a) +{ return v_check_all(v_reinterpret_as_u32(a)); } + +inline bool v_check_any(const v_int8x16& a) +{ return v_check_any(v_reinterpret_as_u8(a)); } +inline bool v_check_any(const v_int16x8& a) +{ return v_check_any(v_reinterpret_as_u16(a)); } +inline bool v_check_any(const v_int32x4& a) +{ return v_check_any(v_reinterpret_as_u32(a)); } +inline bool v_check_any(const v_float32x4& a) +{ return v_check_any(v_reinterpret_as_u32(a)); } + +inline bool v_check_all(const v_int64x2& a) +{ return v_check_all(v_reinterpret_as_u64(a)); } +inline bool v_check_all(const v_float64x2& a) +{ return v_check_all(v_reinterpret_as_u64(a)); } +inline bool v_check_any(const v_int64x2& a) +{ return v_check_any(v_reinterpret_as_u64(a)); } +inline bool v_check_any(const v_float64x2& a) +{ return v_check_any(v_reinterpret_as_u64(a)); } + +/* v_select */ +#define OPENCV_HAL_IMPL_MSA_SELECT(_Tpvec, _Tpv, _Tpvu) \ +inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_bslq_u8(MSA_TPV_REINTERPRET(_Tpvu, mask.val), \ + MSA_TPV_REINTERPRET(_Tpvu, b.val), MSA_TPV_REINTERPRET(_Tpvu, a.val)))); \ +} + +OPENCV_HAL_IMPL_MSA_SELECT(v_uint8x16, v16u8, v16u8) +OPENCV_HAL_IMPL_MSA_SELECT(v_int8x16, v16i8, v16u8) +OPENCV_HAL_IMPL_MSA_SELECT(v_uint16x8, v8u16, v16u8) +OPENCV_HAL_IMPL_MSA_SELECT(v_int16x8, v8i16, v16u8) +OPENCV_HAL_IMPL_MSA_SELECT(v_uint32x4, v4u32, v16u8) +OPENCV_HAL_IMPL_MSA_SELECT(v_int32x4, v4i32, v16u8) +OPENCV_HAL_IMPL_MSA_SELECT(v_float32x4, v4f32, v16u8) +OPENCV_HAL_IMPL_MSA_SELECT(v_float64x2, v2f64, v16u8) + +#define OPENCV_HAL_IMPL_MSA_EXPAND(_Tpvec, _Tpwvec, _Tp, suffix, ssuffix, _Tpv, _Tpvs) \ +inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ +{ \ + _Tpv a_lo = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##ssuffix(0))); \ + _Tpv a_hi = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##ssuffix(0))); \ + b0.val = msa_paddlq_##suffix(a_lo); \ + b1.val = msa_paddlq_##suffix(a_hi); \ +} \ +inline _Tpwvec v_expand_low(const _Tpvec& a) \ +{ \ + _Tpv a_lo = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##ssuffix(0))); \ + return _Tpwvec(msa_paddlq_##suffix(a_lo)); \ +} \ +inline _Tpwvec v_expand_high(const _Tpvec& a) \ +{ \ + _Tpv a_hi = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##ssuffix(0))); \ + return _Tpwvec(msa_paddlq_##suffix(a_hi)); \ +} \ +inline _Tpwvec v_load_expand(const _Tp* ptr) \ +{ \ + return _Tpwvec(msa_movl_##suffix(msa_ld1_##suffix(ptr))); \ +} + +OPENCV_HAL_IMPL_MSA_EXPAND(v_uint8x16, v_uint16x8, uchar, u8, s8, v16u8, v16i8) +OPENCV_HAL_IMPL_MSA_EXPAND(v_int8x16, v_int16x8, schar, s8, s8, v16i8, v16i8) +OPENCV_HAL_IMPL_MSA_EXPAND(v_uint16x8, v_uint32x4, ushort, u16, s16, v8u16, v8i16) +OPENCV_HAL_IMPL_MSA_EXPAND(v_int16x8, v_int32x4, short, s16, s16, v8i16, v8i16) +OPENCV_HAL_IMPL_MSA_EXPAND(v_uint32x4, v_uint64x2, uint, u32, s32, v4u32, v4i32) +OPENCV_HAL_IMPL_MSA_EXPAND(v_int32x4, v_int64x2, int, s32, s32, v4i32, v4i32) + +inline v_uint32x4 v_load_expand_q(const uchar* ptr) +{ + return v_uint32x4((v4u32){ptr[0], ptr[1], ptr[2], ptr[3]}); +} + +inline v_int32x4 v_load_expand_q(const schar* ptr) +{ + return v_int32x4((v4i32){ptr[0], ptr[1], ptr[2], ptr[3]}); +} + +/* v_zip, v_combine_low, v_combine_high, v_recombine */ +#define OPENCV_HAL_IMPL_MSA_UNPACKS(_Tpvec, _Tpv, _Tpvs, ssuffix) \ +inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) \ +{ \ + b0.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a1.val), MSA_TPV_REINTERPRET(_Tpvs, a0.val))); \ + b1.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a1.val), MSA_TPV_REINTERPRET(_Tpvs, a0.val))); \ +} \ +inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, b.val), MSA_TPV_REINTERPRET(v2i64, a.val)))); \ +} \ +inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, b.val), MSA_TPV_REINTERPRET(v2i64, a.val)))); \ +} \ +inline void v_recombine(const _Tpvec& a, const _Tpvec& b, _Tpvec& c, _Tpvec& d) \ +{ \ + c.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, b.val), MSA_TPV_REINTERPRET(v2i64, a.val))); \ + d.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, b.val), MSA_TPV_REINTERPRET(v2i64, a.val))); \ +} + +OPENCV_HAL_IMPL_MSA_UNPACKS(v_uint8x16, v16u8, v16i8, s8) +OPENCV_HAL_IMPL_MSA_UNPACKS(v_int8x16, v16i8, v16i8, s8) +OPENCV_HAL_IMPL_MSA_UNPACKS(v_uint16x8, v8u16, v8i16, s16) +OPENCV_HAL_IMPL_MSA_UNPACKS(v_int16x8, v8i16, v8i16, s16) +OPENCV_HAL_IMPL_MSA_UNPACKS(v_uint32x4, v4u32, v4i32, s32) +OPENCV_HAL_IMPL_MSA_UNPACKS(v_int32x4, v4i32, v4i32, s32) +OPENCV_HAL_IMPL_MSA_UNPACKS(v_float32x4, v4f32, v4i32, s32) +OPENCV_HAL_IMPL_MSA_UNPACKS(v_float64x2, v2f64, v2i64, s64) + +/* v_extract */ +#define OPENCV_HAL_IMPL_MSA_EXTRACT(_Tpvec, _Tpv, _Tpvs, suffix) \ +template \ +inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), MSA_TPV_REINTERPRET(_Tpvs, b.val), s))); \ +} + +OPENCV_HAL_IMPL_MSA_EXTRACT(v_uint8x16, v16u8, v16i8, s8) +OPENCV_HAL_IMPL_MSA_EXTRACT(v_int8x16, v16i8, v16i8, s8) +OPENCV_HAL_IMPL_MSA_EXTRACT(v_uint16x8, v8u16, v8i16, s16) +OPENCV_HAL_IMPL_MSA_EXTRACT(v_int16x8, v8i16, v8i16, s16) +OPENCV_HAL_IMPL_MSA_EXTRACT(v_uint32x4, v4u32, v4i32, s32) +OPENCV_HAL_IMPL_MSA_EXTRACT(v_int32x4, v4i32, v4i32, s32) +OPENCV_HAL_IMPL_MSA_EXTRACT(v_uint64x2, v2u64, v2i64, s64) +OPENCV_HAL_IMPL_MSA_EXTRACT(v_int64x2, v2i64, v2i64, s64) +OPENCV_HAL_IMPL_MSA_EXTRACT(v_float32x4, v4f32, v4i32, s32) +OPENCV_HAL_IMPL_MSA_EXTRACT(v_float64x2, v2f64, v2i64, s64) + +/* v_round, v_floor, v_ceil, v_trunc */ +inline v_int32x4 v_round(const v_float32x4& a) +{ + return v_int32x4(msa_cvttintq_s32_f32(a.val)); +} + +inline v_int32x4 v_floor(const v_float32x4& a) +{ + v4i32 a1 = msa_cvttintq_s32_f32(a.val); + return v_int32x4(msa_addq_s32(a1, MSA_TPV_REINTERPRET(v4i32, msa_cgtq_f32(msa_cvtfintq_f32_s32(a1), a.val)))); +} + +inline v_int32x4 v_ceil(const v_float32x4& a) +{ + v4i32 a1 = msa_cvttintq_s32_f32(a.val); + return v_int32x4(msa_subq_s32(a1, MSA_TPV_REINTERPRET(v4i32, msa_cgtq_f32(a.val, msa_cvtfintq_f32_s32(a1))))); +} + +inline v_int32x4 v_trunc(const v_float32x4& a) +{ + return v_int32x4(msa_cvttruncq_s32_f32(a.val)); +} + +inline v_int32x4 v_round(const v_float64x2& a) +{ + return v_int32x4(msa_pack_s64(msa_cvttintq_s64_f64(a.val), msa_dupq_n_s64(0))); +} + +inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) +{ + return v_int32x4(msa_pack_s64(msa_cvttintq_s64_f64(a.val), msa_cvttintq_s64_f64(b.val))); +} + +inline v_int32x4 v_floor(const v_float64x2& a) +{ + v2f64 a1 = msa_cvtrintq_f64(a.val); + return v_int32x4(msa_pack_s64(msa_addq_s64(msa_cvttruncq_s64_f64(a1), MSA_TPV_REINTERPRET(v2i64, msa_cgtq_f64(a1, a.val))), msa_dupq_n_s64(0))); +} + +inline v_int32x4 v_ceil(const v_float64x2& a) +{ + v2f64 a1 = msa_cvtrintq_f64(a.val); + return v_int32x4(msa_pack_s64(msa_subq_s64(msa_cvttruncq_s64_f64(a1), MSA_TPV_REINTERPRET(v2i64, msa_cgtq_f64(a.val, a1))), msa_dupq_n_s64(0))); +} + +inline v_int32x4 v_trunc(const v_float64x2& a) +{ + return v_int32x4(msa_pack_s64(msa_cvttruncq_s64_f64(a.val), msa_dupq_n_s64(0))); +} + +#define OPENCV_HAL_IMPL_MSA_TRANSPOSE4x4(_Tpvec, _Tpv, _Tpvs, ssuffix) \ +inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ + const _Tpvec& a2, const _Tpvec& a3, \ + _Tpvec& b0, _Tpvec& b1, \ + _Tpvec& b2, _Tpvec& b3) \ +{ \ + _Tpv t00 = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a1.val), MSA_TPV_REINTERPRET(_Tpvs, a0.val))); \ + _Tpv t01 = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a1.val), MSA_TPV_REINTERPRET(_Tpvs, a0.val))); \ + _Tpv t10 = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a3.val), MSA_TPV_REINTERPRET(_Tpvs, a2.val))); \ + _Tpv t11 = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a3.val), MSA_TPV_REINTERPRET(_Tpvs, a2.val))); \ + b0.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, t10), MSA_TPV_REINTERPRET(v2i64, t00))); \ + b1.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, t10), MSA_TPV_REINTERPRET(v2i64, t00))); \ + b2.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, t11), MSA_TPV_REINTERPRET(v2i64, t01))); \ + b3.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, t11), MSA_TPV_REINTERPRET(v2i64, t01))); \ +} + +OPENCV_HAL_IMPL_MSA_TRANSPOSE4x4(v_uint32x4, v4u32, v4i32, s32) +OPENCV_HAL_IMPL_MSA_TRANSPOSE4x4(v_int32x4, v4i32, v4i32, s32) +OPENCV_HAL_IMPL_MSA_TRANSPOSE4x4(v_float32x4, v4f32, v4i32, s32) + +#define OPENCV_HAL_IMPL_MSA_INTERLEAVED(_Tpvec, _Tp, suffix) \ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b) \ +{ \ + msa_ld2q_##suffix(ptr, &a.val, &b.val); \ +} \ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, v_##_Tpvec& c) \ +{ \ + msa_ld3q_##suffix(ptr, &a.val, &b.val, &c.val); \ +} \ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, \ + v_##_Tpvec& c, v_##_Tpvec& d) \ +{ \ + msa_ld4q_##suffix(ptr, &a.val, &b.val, &c.val, &d.val); \ +} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + msa_st2q_##suffix(ptr, a.val, b.val); \ +} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ + const v_##_Tpvec& c, hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + msa_st3q_##suffix(ptr, a.val, b.val, c.val); \ +} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ + const v_##_Tpvec& c, const v_##_Tpvec& d, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ +{ \ + msa_st4q_##suffix(ptr, a.val, b.val, c.val, d.val); \ +} + +OPENCV_HAL_IMPL_MSA_INTERLEAVED(uint8x16, uchar, u8) +OPENCV_HAL_IMPL_MSA_INTERLEAVED(int8x16, schar, s8) +OPENCV_HAL_IMPL_MSA_INTERLEAVED(uint16x8, ushort, u16) +OPENCV_HAL_IMPL_MSA_INTERLEAVED(int16x8, short, s16) +OPENCV_HAL_IMPL_MSA_INTERLEAVED(uint32x4, unsigned, u32) +OPENCV_HAL_IMPL_MSA_INTERLEAVED(int32x4, int, s32) +OPENCV_HAL_IMPL_MSA_INTERLEAVED(float32x4, float, f32) +OPENCV_HAL_IMPL_MSA_INTERLEAVED(uint64x2, uint64, u64) +OPENCV_HAL_IMPL_MSA_INTERLEAVED(int64x2, int64, s64) +OPENCV_HAL_IMPL_MSA_INTERLEAVED(float64x2, double, f64) + +/* v_cvt_f32, v_cvt_f64, v_cvt_f64_high */ +inline v_float32x4 v_cvt_f32(const v_int32x4& a) +{ + return v_float32x4(msa_cvtfintq_f32_s32(a.val)); +} + +inline v_float32x4 v_cvt_f32(const v_float64x2& a) +{ + return v_float32x4(msa_cvtfq_f32_f64(a.val, msa_dupq_n_f64(0.0f))); +} + +inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) +{ + return v_float32x4(msa_cvtfq_f32_f64(a.val, b.val)); +} + +inline v_float64x2 v_cvt_f64(const v_int32x4& a) +{ + return v_float64x2(msa_cvtflq_f64_f32(msa_cvtfintq_f32_s32(a.val))); +} + +inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) +{ + return v_float64x2(msa_cvtfhq_f64_f32(msa_cvtfintq_f32_s32(a.val))); +} + +inline v_float64x2 v_cvt_f64(const v_float32x4& a) +{ + return v_float64x2(msa_cvtflq_f64_f32(a.val)); +} + +inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) +{ + return v_float64x2(msa_cvtfhq_f64_f32(a.val)); +} + +inline v_float64x2 v_cvt_f64(const v_int64x2& a) +{ + return v_float64x2(msa_cvtfintq_f64_s64(a.val)); +} + +////////////// Lookup table access //////////////////// +inline v_int8x16 v_lut(const schar* tab, const int* idx) +{ + schar CV_DECL_ALIGNED(32) elems[16] = + { + tab[idx[ 0]], + tab[idx[ 1]], + tab[idx[ 2]], + tab[idx[ 3]], + tab[idx[ 4]], + tab[idx[ 5]], + tab[idx[ 6]], + tab[idx[ 7]], + tab[idx[ 8]], + tab[idx[ 9]], + tab[idx[10]], + tab[idx[11]], + tab[idx[12]], + tab[idx[13]], + tab[idx[14]], + tab[idx[15]] + }; + return v_int8x16(msa_ld1q_s8(elems)); +} +inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx) +{ + schar CV_DECL_ALIGNED(32) elems[16] = + { + tab[idx[0]], + tab[idx[0] + 1], + tab[idx[1]], + tab[idx[1] + 1], + tab[idx[2]], + tab[idx[2] + 1], + tab[idx[3]], + tab[idx[3] + 1], + tab[idx[4]], + tab[idx[4] + 1], + tab[idx[5]], + tab[idx[5] + 1], + tab[idx[6]], + tab[idx[6] + 1], + tab[idx[7]], + tab[idx[7] + 1] + }; + return v_int8x16(msa_ld1q_s8(elems)); +} +inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) +{ + schar CV_DECL_ALIGNED(32) elems[16] = + { + tab[idx[0]], + tab[idx[0] + 1], + tab[idx[0] + 2], + tab[idx[0] + 3], + tab[idx[1]], + tab[idx[1] + 1], + tab[idx[1] + 2], + tab[idx[1] + 3], + tab[idx[2]], + tab[idx[2] + 1], + tab[idx[2] + 2], + tab[idx[2] + 3], + tab[idx[3]], + tab[idx[3] + 1], + tab[idx[3] + 2], + tab[idx[3] + 3] + }; + return v_int8x16(msa_ld1q_s8(elems)); +} +inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((schar*)tab, idx)); } +inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((schar*)tab, idx)); } +inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((schar*)tab, idx)); } + + +inline v_int16x8 v_lut(const short* tab, const int* idx) +{ + short CV_DECL_ALIGNED(32) elems[8] = + { + tab[idx[0]], + tab[idx[1]], + tab[idx[2]], + tab[idx[3]], + tab[idx[4]], + tab[idx[5]], + tab[idx[6]], + tab[idx[7]] + }; + return v_int16x8(msa_ld1q_s16(elems)); +} +inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) +{ + short CV_DECL_ALIGNED(32) elems[8] = + { + tab[idx[0]], + tab[idx[0] + 1], + tab[idx[1]], + tab[idx[1] + 1], + tab[idx[2]], + tab[idx[2] + 1], + tab[idx[3]], + tab[idx[3] + 1] + }; + return v_int16x8(msa_ld1q_s16(elems)); +} +inline v_int16x8 v_lut_quads(const short* tab, const int* idx) +{ + return v_int16x8(msa_combine_s16(msa_ld1_s16(tab + idx[0]), msa_ld1_s16(tab + idx[1]))); +} +inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((short*)tab, idx)); } +inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((short*)tab, idx)); } +inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((short*)tab, idx)); } + +inline v_int32x4 v_lut(const int* tab, const int* idx) +{ + int CV_DECL_ALIGNED(32) elems[4] = + { + tab[idx[0]], + tab[idx[1]], + tab[idx[2]], + tab[idx[3]] + }; + return v_int32x4(msa_ld1q_s32(elems)); +} +inline v_int32x4 v_lut_pairs(const int* tab, const int* idx) +{ + return v_int32x4(msa_combine_s32(msa_ld1_s32(tab + idx[0]), msa_ld1_s32(tab + idx[1]))); +} +inline v_int32x4 v_lut_quads(const int* tab, const int* idx) +{ + return v_int32x4(msa_ld1q_s32(tab + idx[0])); +} +inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((int*)tab, idx)); } +inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((int*)tab, idx)); } +inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((int*)tab, idx)); } + +inline v_int64x2 v_lut(const int64_t* tab, const int* idx) +{ + return v_int64x2(msa_combine_s64(msa_create_s64(tab[idx[0]]), msa_create_s64(tab[idx[1]]))); +} +inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) +{ + return v_int64x2(msa_ld1q_s64(tab + idx[0])); +} +inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } +inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } + +inline v_float32x4 v_lut(const float* tab, const int* idx) +{ + float CV_DECL_ALIGNED(32) elems[4] = + { + tab[idx[0]], + tab[idx[1]], + tab[idx[2]], + tab[idx[3]] + }; + return v_float32x4(msa_ld1q_f32(elems)); +} +inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) +{ + uint64 CV_DECL_ALIGNED(32) elems[2] = + { + *(uint64*)(tab + idx[0]), + *(uint64*)(tab + idx[1]) + }; + return v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_ld1q_u64(elems))); +} +inline v_float32x4 v_lut_quads(const float* tab, const int* idx) +{ + return v_float32x4(msa_ld1q_f32(tab + idx[0])); +} + +inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) +{ + int CV_DECL_ALIGNED(32) idx[4]; + v_store_aligned(idx, idxvec); + + return v_int32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); +} + +inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) +{ + unsigned CV_DECL_ALIGNED(32) elems[4] = + { + tab[msa_getq_lane_s32(idxvec.val, 0)], + tab[msa_getq_lane_s32(idxvec.val, 1)], + tab[msa_getq_lane_s32(idxvec.val, 2)], + tab[msa_getq_lane_s32(idxvec.val, 3)] + }; + return v_uint32x4(msa_ld1q_u32(elems)); +} + +inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) +{ + int CV_DECL_ALIGNED(32) idx[4]; + v_store_aligned(idx, idxvec); + + return v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); +} + +inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) +{ + int CV_DECL_ALIGNED(32) idx[4]; + v_store_aligned(idx, idxvec); + + v4f32 xy02 = msa_combine_f32(msa_ld1_f32(tab + idx[0]), msa_ld1_f32(tab + idx[2])); + v4f32 xy13 = msa_combine_f32(msa_ld1_f32(tab + idx[1]), msa_ld1_f32(tab + idx[3])); + x = v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_ilvevq_s32(MSA_TPV_REINTERPRET(v4i32, xy13), MSA_TPV_REINTERPRET(v4i32, xy02)))); + y = v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_ilvodq_s32(MSA_TPV_REINTERPRET(v4i32, xy13), MSA_TPV_REINTERPRET(v4i32, xy02)))); +} + +inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) +{ + v_int8x16 c = v_int8x16(__builtin_msa_vshf_b((v16i8)((v2i64){0x0705060403010200, 0x0F0D0E0C0B090A08}), msa_dupq_n_s8(0), vec.val)); + return c; +} +inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) +{ return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } +inline v_int8x16 v_interleave_quads(const v_int8x16& vec) +{ + v_int8x16 c = v_int8x16(__builtin_msa_vshf_b((v16i8)((v2i64){0x0703060205010400, 0x0F0B0E0A0D090C08}), msa_dupq_n_s8(0), vec.val)); + return c; +} +inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) +{ + v_int16x8 c = v_int16x8(__builtin_msa_vshf_h((v8i16)((v2i64){0x0003000100020000, 0x0007000500060004}), msa_dupq_n_s16(0), vec.val)); + return c; +} + +inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } + +inline v_int16x8 v_interleave_quads(const v_int16x8& vec) +{ + v_int16x8 c = v_int16x8(__builtin_msa_vshf_h((v8i16)((v2i64){0x0005000100040000, 0x0007000300060002}), msa_dupq_n_s16(0), vec.val)); + return c; +} + +inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) +{ + v_int32x4 c; + c.val[0] = vec.val[0]; + c.val[1] = vec.val[2]; + c.val[2] = vec.val[1]; + c.val[3] = vec.val[3]; + return c; +} + +inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } +inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } + +inline v_int8x16 v_pack_triplets(const v_int8x16& vec) +{ + v_int8x16 c = v_int8x16(__builtin_msa_vshf_b((v16i8)((v2i64){0x0908060504020100, 0x131211100E0D0C0A}), msa_dupq_n_s8(0), vec.val)); + return c; +} + +inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_pack_triplets(const v_int16x8& vec) +{ + v_int16x8 c = v_int16x8(__builtin_msa_vshf_h((v8i16)((v2i64){0x0004000200010000, 0x0009000800060005}), msa_dupq_n_s16(0), vec.val)); + return c; +} + +inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } +inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } +inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } +inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } + +inline v_float64x2 v_lut(const double* tab, const int* idx) +{ + double CV_DECL_ALIGNED(32) elems[2] = + { + tab[idx[0]], + tab[idx[1]] + }; + return v_float64x2(msa_ld1q_f64(elems)); +} + +inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) +{ + return v_float64x2(msa_ld1q_f64(tab + idx[0])); +} + +inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) +{ + int CV_DECL_ALIGNED(32) idx[4]; + v_store_aligned(idx, idxvec); + + return v_float64x2(tab[idx[0]], tab[idx[1]]); +} + +inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) +{ + int CV_DECL_ALIGNED(32) idx[4]; + v_store_aligned(idx, idxvec); + + v2f64 xy0 = msa_ld1q_f64(tab + idx[0]); + v2f64 xy1 = msa_ld1q_f64(tab + idx[1]); + x = v_float64x2(MSA_TPV_REINTERPRET(v2f64, msa_ilvevq_s64(MSA_TPV_REINTERPRET(v2i64, xy1), MSA_TPV_REINTERPRET(v2i64, xy0)))); + y = v_float64x2(MSA_TPV_REINTERPRET(v2f64, msa_ilvodq_s64(MSA_TPV_REINTERPRET(v2i64, xy1), MSA_TPV_REINTERPRET(v2i64, xy0)))); +} + +template +inline typename _Tp::lane_type v_extract_n(const _Tp& a) +{ + return v_rotate_right(a).get0(); +} + +template +inline v_uint32x4 v_broadcast_element(const v_uint32x4& a) +{ + return v_setall_u32(v_extract_n(a)); +} +template +inline v_int32x4 v_broadcast_element(const v_int32x4& a) +{ + return v_setall_s32(v_extract_n(a)); +} +template +inline v_float32x4 v_broadcast_element(const v_float32x4& a) +{ + return v_setall_f32(v_extract_n(a)); +} + +////// FP16 support /////// +#if CV_FP16 +inline v_float32x4 v_load_expand(const hfloat* ptr) +{ +#ifndef msa_ld1_f16 + v4f16 v = (v4f16)msa_ld1_s16((const short*)ptr); +#else + v4f16 v = msa_ld1_f16((const __fp16*)ptr); +#endif + return v_float32x4(msa_cvt_f32_f16(v)); +} + +inline void v_pack_store(hfloat* ptr, const v_float32x4& v) +{ + v4f16 hv = msa_cvt_f16_f32(v.val); + +#ifndef msa_st1_f16 + msa_st1_s16((short*)ptr, (int16x4_t)hv); +#else + msa_st1_f16((__fp16*)ptr, hv); +#endif +} +#else +inline v_float32x4 v_load_expand(const hfloat* ptr) +{ + float buf[4]; + for( int i = 0; i < 4; i++ ) + buf[i] = (float)ptr[i]; + return v_load(buf); +} + +inline void v_pack_store(hfloat* ptr, const v_float32x4& v) +{ + float buf[4]; + v_store(buf, v); + for( int i = 0; i < 4; i++ ) + ptr[i] = (hfloat)buf[i]; +} +#endif + +inline void v_cleanup() {} + +#include "intrin_math.hpp" +inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } +inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } +inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } +inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } +inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } +inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } + +inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } +inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } +inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } +inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } +inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_neon.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_neon.hpp index 64fb7d73bc..eb10edfc44 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_neon.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_neon.hpp @@ -1,2679 +1,2679 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_HAL_INTRIN_NEON_HPP -#define OPENCV_HAL_INTRIN_NEON_HPP - -#include -#include "opencv2/core/utility.hpp" - -namespace cv -{ - -//! @cond IGNORED - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -#define CV_SIMD128 1 -#if defined(__aarch64__) || defined(_M_ARM64) -#define CV_SIMD128_64F 1 -#else -#define CV_SIMD128_64F 0 -#endif - -// The following macro checks if the code is being compiled for the -// AArch64 execution state of Armv8, to enable the 128-bit -// intrinsics. The macro `__ARM_64BIT_STATE` is the one recommended by -// the Arm C Language Extension (ACLE) specifications [1] to check the -// availability of 128-bit intrinsics, and it is supporrted by clang -// and gcc. The macro `_M_ARM64` is the equivalent one for Microsoft -// Visual Studio [2] . -// -// [1] https://developer.arm.com/documentation/101028/0012/13--Advanced-SIMD--Neon--intrinsics -// [2] https://docs.microsoft.com/en-us/cpp/preprocessor/predefined-macros -#if defined(__ARM_64BIT_STATE) || defined(_M_ARM64) -#define CV_NEON_AARCH64 1 -#else -#define CV_NEON_AARCH64 0 -#endif - - -//////////// Utils //////////// - -#if CV_SIMD128_64F -#define OPENCV_HAL_IMPL_NEON_UNZIP(_Tpv, _Tpvx2, suffix) \ - inline void _v128_unzip(const _Tpv& a, const _Tpv& b, _Tpv& c, _Tpv& d) \ - { c = vuzp1q_##suffix(a, b); d = vuzp2q_##suffix(a, b); } -#define OPENCV_HAL_IMPL_NEON_UNZIP_L(_Tpv, _Tpvx2, suffix) \ - inline void _v128_unzip(const _Tpv&a, const _Tpv&b, _Tpv& c, _Tpv& d) \ - { c = vuzp1_##suffix(a, b); d = vuzp2_##suffix(a, b); } -#else -#define OPENCV_HAL_IMPL_NEON_UNZIP(_Tpv, _Tpvx2, suffix) \ - inline void _v128_unzip(const _Tpv& a, const _Tpv& b, _Tpv& c, _Tpv& d) \ - { _Tpvx2 ab = vuzpq_##suffix(a, b); c = ab.val[0]; d = ab.val[1]; } -#define OPENCV_HAL_IMPL_NEON_UNZIP_L(_Tpv, _Tpvx2, suffix) \ - inline void _v128_unzip(const _Tpv& a, const _Tpv& b, _Tpv& c, _Tpv& d) \ - { _Tpvx2 ab = vuzp_##suffix(a, b); c = ab.val[0]; d = ab.val[1]; } -#endif - -#if CV_SIMD128_64F -#define OPENCV_HAL_IMPL_NEON_REINTERPRET(_Tpv, suffix) \ - template static inline \ - _Tpv vreinterpretq_##suffix##_f64(T a) { return (_Tpv) a; } \ - template static inline \ - float64x2_t vreinterpretq_f64_##suffix(T a) { return (float64x2_t) a; } -#else -#define OPENCV_HAL_IMPL_NEON_REINTERPRET(_Tpv, suffix) -#endif - -#define OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(_Tpv, _Tpvl, suffix) \ - OPENCV_HAL_IMPL_NEON_UNZIP(_Tpv##_t, _Tpv##x2_t, suffix) \ - OPENCV_HAL_IMPL_NEON_UNZIP_L(_Tpvl##_t, _Tpvl##x2_t, suffix) \ - OPENCV_HAL_IMPL_NEON_REINTERPRET(_Tpv##_t, suffix) - -#define OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX_I64(_Tpv, _Tpvl, suffix) \ - OPENCV_HAL_IMPL_NEON_REINTERPRET(_Tpv##_t, suffix) - -#define OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX_F64(_Tpv, _Tpvl, suffix) \ - OPENCV_HAL_IMPL_NEON_UNZIP(_Tpv##_t, _Tpv##x2_t, suffix) - -OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(uint8x16, uint8x8, u8) -OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(int8x16, int8x8, s8) -OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(uint16x8, uint16x4, u16) -OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(int16x8, int16x4, s16) -OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(uint32x4, uint32x2, u32) -OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(int32x4, int32x2, s32) -OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(float32x4, float32x2, f32) -OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX_I64(uint64x2, uint64x1, u64) -OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX_I64(int64x2, int64x1, s64) -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX_F64(float64x2, float64x1,f64) -#endif - -//////////// Compatibility layer //////////// -template struct VTraits { - static inline int vlanes() { return T::nlanes; } - enum { max_nlanes = T::nlanes, nlanes = T::nlanes }; - using lane_type = typename T::lane_type; -}; - -template -inline typename VTraits::lane_type v_get0(const T& v) \ -{ \ - return v.get0(); \ -} -//////////// Types //////////// - -struct v_uint8x16 -{ - v_uint8x16() {} - explicit v_uint8x16(uint8x16_t v) : val(v) {} - v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, - uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) - { - uchar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; - val = vld1q_u8(v); - } - uint8x16_t val; - -private: - friend struct VTraits; - enum { nlanes = 16 }; - typedef uchar lane_type; - - friend typename VTraits::lane_type v_get0(const v_uint8x16& v); - uchar get0() const - { - return vgetq_lane_u8(val, 0); - } -}; - -struct v_int8x16 -{ - v_int8x16() {} - explicit v_int8x16(int8x16_t v) : val(v) {} - v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, - schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) - { - schar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; - val = vld1q_s8(v); - } - int8x16_t val; - -private: - friend struct VTraits; - enum { nlanes = 16 }; - typedef schar lane_type; - - friend typename VTraits::lane_type v_get0(const v_int8x16& v); - schar get0() const - { - return vgetq_lane_s8(val, 0); - } -}; - -struct v_uint16x8 -{ - v_uint16x8() {} - explicit v_uint16x8(uint16x8_t v) : val(v) {} - v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) - { - ushort v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; - val = vld1q_u16(v); - } - uint16x8_t val; - -private: - friend struct VTraits; - enum { nlanes = 8 }; - typedef ushort lane_type; - - friend typename VTraits::lane_type v_get0(const v_uint16x8& v); - ushort get0() const - { - return vgetq_lane_u16(val, 0); - } -}; - -struct v_int16x8 -{ - v_int16x8() {} - explicit v_int16x8(int16x8_t v) : val(v) {} - v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) - { - short v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; - val = vld1q_s16(v); - } - int16x8_t val; - -private: - friend struct VTraits; - enum { nlanes = 8 }; - typedef short lane_type; - - friend typename VTraits::lane_type v_get0(const v_int16x8& v); - short get0() const - { - return vgetq_lane_s16(val, 0); - } -}; - -struct v_uint32x4 -{ - v_uint32x4() {} - explicit v_uint32x4(uint32x4_t v) : val(v) {} - v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) - { - unsigned v[] = {v0, v1, v2, v3}; - val = vld1q_u32(v); - } - uint32x4_t val; - -private: - friend struct VTraits; - enum { nlanes = 4 }; - typedef unsigned lane_type; - - friend typename VTraits::lane_type v_get0(const v_uint32x4& v); - unsigned get0() const - { - return vgetq_lane_u32(val, 0); - } -}; - -struct v_int32x4 -{ - v_int32x4() {} - explicit v_int32x4(int32x4_t v) : val(v) {} - v_int32x4(int v0, int v1, int v2, int v3) - { - int v[] = {v0, v1, v2, v3}; - val = vld1q_s32(v); - } - int32x4_t val; - -private: - friend struct VTraits; - enum { nlanes = 4 }; - typedef int lane_type; - - friend typename VTraits::lane_type v_get0(const v_int32x4& v); - int get0() const - { - return vgetq_lane_s32(val, 0); - } -}; - -struct v_float32x4 -{ - v_float32x4() {} - explicit v_float32x4(float32x4_t v) : val(v) {} - v_float32x4(float v0, float v1, float v2, float v3) - { - float v[] = {v0, v1, v2, v3}; - val = vld1q_f32(v); - } - float32x4_t val; - -private: - friend struct VTraits; - enum { nlanes = 4 }; - typedef float lane_type; - - friend typename VTraits::lane_type v_get0(const v_float32x4& v); - float get0() const - { - return vgetq_lane_f32(val, 0); - } -}; - -struct v_uint64x2 -{ - v_uint64x2() {} - explicit v_uint64x2(uint64x2_t v) : val(v) {} - v_uint64x2(uint64 v0, uint64 v1) - { - uint64 v[] = {v0, v1}; - val = vld1q_u64(v); - } - uint64x2_t val; -private: - friend struct VTraits; - enum { nlanes = 2 }; - typedef uint64 lane_type; - - friend typename VTraits::lane_type v_get0(const v_uint64x2& v); - uint64 get0() const - { - return vgetq_lane_u64(val, 0); - } -}; - -struct v_int64x2 -{ - v_int64x2() {} - explicit v_int64x2(int64x2_t v) : val(v) {} - v_int64x2(int64 v0, int64 v1) - { - int64 v[] = {v0, v1}; - val = vld1q_s64(v); - } - int64x2_t val; - -private: - friend struct VTraits; - enum { nlanes = 2 }; - typedef int64 lane_type; - - friend typename VTraits::lane_type v_get0(const v_int64x2& v); - int64 get0() const - { - return vgetq_lane_s64(val, 0); - } -}; - -#if CV_SIMD128_64F -struct v_float64x2 -{ - v_float64x2() {} - explicit v_float64x2(float64x2_t v) : val(v) {} - v_float64x2(double v0, double v1) - { - double v[] = {v0, v1}; - val = vld1q_f64(v); - } - - float64x2_t val; -private: - friend struct VTraits; - enum { nlanes = 2 }; - typedef double lane_type; - - friend typename VTraits::lane_type v_get0(const v_float64x2& v); - double get0() const - { - return vgetq_lane_f64(val, 0); - } -}; -#endif - -#define OPENCV_HAL_IMPL_NEON_INIT(_Tpv, _Tp, suffix) \ -inline v_##_Tpv v_setzero_##suffix() { return v_##_Tpv(vdupq_n_##suffix((_Tp)0)); } \ -inline v_##_Tpv v_setall_##suffix(_Tp v) { return v_##_Tpv(vdupq_n_##suffix(v)); } \ -template <> inline v_##_Tpv v_setzero_() { return v_setzero_##suffix(); } \ -template <> inline v_##_Tpv v_setall_(_Tp v) { return v_setall_##suffix(v); } \ -inline _Tpv##_t vreinterpretq_##suffix##_##suffix(_Tpv##_t v) { return v; } \ -inline v_uint8x16 v_reinterpret_as_u8(const v_##_Tpv& v) { return v_uint8x16(vreinterpretq_u8_##suffix(v.val)); } \ -inline v_int8x16 v_reinterpret_as_s8(const v_##_Tpv& v) { return v_int8x16(vreinterpretq_s8_##suffix(v.val)); } \ -inline v_uint16x8 v_reinterpret_as_u16(const v_##_Tpv& v) { return v_uint16x8(vreinterpretq_u16_##suffix(v.val)); } \ -inline v_int16x8 v_reinterpret_as_s16(const v_##_Tpv& v) { return v_int16x8(vreinterpretq_s16_##suffix(v.val)); } \ -inline v_uint32x4 v_reinterpret_as_u32(const v_##_Tpv& v) { return v_uint32x4(vreinterpretq_u32_##suffix(v.val)); } \ -inline v_int32x4 v_reinterpret_as_s32(const v_##_Tpv& v) { return v_int32x4(vreinterpretq_s32_##suffix(v.val)); } \ -inline v_uint64x2 v_reinterpret_as_u64(const v_##_Tpv& v) { return v_uint64x2(vreinterpretq_u64_##suffix(v.val)); } \ -inline v_int64x2 v_reinterpret_as_s64(const v_##_Tpv& v) { return v_int64x2(vreinterpretq_s64_##suffix(v.val)); } \ -inline v_float32x4 v_reinterpret_as_f32(const v_##_Tpv& v) { return v_float32x4(vreinterpretq_f32_##suffix(v.val)); } - -OPENCV_HAL_IMPL_NEON_INIT(uint8x16, uchar, u8) -OPENCV_HAL_IMPL_NEON_INIT(int8x16, schar, s8) -OPENCV_HAL_IMPL_NEON_INIT(uint16x8, ushort, u16) -OPENCV_HAL_IMPL_NEON_INIT(int16x8, short, s16) -OPENCV_HAL_IMPL_NEON_INIT(uint32x4, unsigned, u32) -OPENCV_HAL_IMPL_NEON_INIT(int32x4, int, s32) -OPENCV_HAL_IMPL_NEON_INIT(uint64x2, uint64, u64) -OPENCV_HAL_IMPL_NEON_INIT(int64x2, int64, s64) -OPENCV_HAL_IMPL_NEON_INIT(float32x4, float, f32) -#if CV_SIMD128_64F -#define OPENCV_HAL_IMPL_NEON_INIT_64(_Tpv, suffix) \ -inline v_float64x2 v_reinterpret_as_f64(const v_##_Tpv& v) { return v_float64x2(vreinterpretq_f64_##suffix(v.val)); } -OPENCV_HAL_IMPL_NEON_INIT(float64x2, double, f64) -OPENCV_HAL_IMPL_NEON_INIT_64(uint8x16, u8) -OPENCV_HAL_IMPL_NEON_INIT_64(int8x16, s8) -OPENCV_HAL_IMPL_NEON_INIT_64(uint16x8, u16) -OPENCV_HAL_IMPL_NEON_INIT_64(int16x8, s16) -OPENCV_HAL_IMPL_NEON_INIT_64(uint32x4, u32) -OPENCV_HAL_IMPL_NEON_INIT_64(int32x4, s32) -OPENCV_HAL_IMPL_NEON_INIT_64(uint64x2, u64) -OPENCV_HAL_IMPL_NEON_INIT_64(int64x2, s64) -OPENCV_HAL_IMPL_NEON_INIT_64(float32x4, f32) -OPENCV_HAL_IMPL_NEON_INIT_64(float64x2, f64) -#endif - -#define OPENCV_HAL_IMPL_NEON_PACK(_Tpvec, _Tp, hreg, suffix, _Tpwvec, pack, mov, rshr) \ -inline _Tpvec v_##pack(const _Tpwvec& a, const _Tpwvec& b) \ -{ \ - hreg a1 = mov(a.val), b1 = mov(b.val); \ - return _Tpvec(vcombine_##suffix(a1, b1)); \ -} \ -inline void v_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ -{ \ - hreg a1 = mov(a.val); \ - vst1_##suffix(ptr, a1); \ -} \ -template inline \ -_Tpvec v_rshr_##pack(const _Tpwvec& a, const _Tpwvec& b) \ -{ \ - hreg a1 = rshr(a.val, n); \ - hreg b1 = rshr(b.val, n); \ - return _Tpvec(vcombine_##suffix(a1, b1)); \ -} \ -template inline \ -void v_rshr_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ -{ \ - hreg a1 = rshr(a.val, n); \ - vst1_##suffix(ptr, a1); \ -} - -OPENCV_HAL_IMPL_NEON_PACK(v_uint8x16, uchar, uint8x8_t, u8, v_uint16x8, pack, vqmovn_u16, vqrshrn_n_u16) -OPENCV_HAL_IMPL_NEON_PACK(v_int8x16, schar, int8x8_t, s8, v_int16x8, pack, vqmovn_s16, vqrshrn_n_s16) -OPENCV_HAL_IMPL_NEON_PACK(v_uint16x8, ushort, uint16x4_t, u16, v_uint32x4, pack, vqmovn_u32, vqrshrn_n_u32) -OPENCV_HAL_IMPL_NEON_PACK(v_int16x8, short, int16x4_t, s16, v_int32x4, pack, vqmovn_s32, vqrshrn_n_s32) -OPENCV_HAL_IMPL_NEON_PACK(v_uint32x4, unsigned, uint32x2_t, u32, v_uint64x2, pack, vmovn_u64, vrshrn_n_u64) -OPENCV_HAL_IMPL_NEON_PACK(v_int32x4, int, int32x2_t, s32, v_int64x2, pack, vmovn_s64, vrshrn_n_s64) - -OPENCV_HAL_IMPL_NEON_PACK(v_uint8x16, uchar, uint8x8_t, u8, v_int16x8, pack_u, vqmovun_s16, vqrshrun_n_s16) -OPENCV_HAL_IMPL_NEON_PACK(v_uint16x8, ushort, uint16x4_t, u16, v_int32x4, pack_u, vqmovun_s32, vqrshrun_n_s32) - -// pack boolean -inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) -{ - uint8x16_t ab = vcombine_u8(vmovn_u16(a.val), vmovn_u16(b.val)); - return v_uint8x16(ab); -} - -inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, - const v_uint32x4& c, const v_uint32x4& d) -{ - uint16x8_t nab = vcombine_u16(vmovn_u32(a.val), vmovn_u32(b.val)); - uint16x8_t ncd = vcombine_u16(vmovn_u32(c.val), vmovn_u32(d.val)); - return v_uint8x16(vcombine_u8(vmovn_u16(nab), vmovn_u16(ncd))); -} - -inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, - const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, - const v_uint64x2& g, const v_uint64x2& h) -{ - uint32x4_t ab = vcombine_u32(vmovn_u64(a.val), vmovn_u64(b.val)); - uint32x4_t cd = vcombine_u32(vmovn_u64(c.val), vmovn_u64(d.val)); - uint32x4_t ef = vcombine_u32(vmovn_u64(e.val), vmovn_u64(f.val)); - uint32x4_t gh = vcombine_u32(vmovn_u64(g.val), vmovn_u64(h.val)); - - uint16x8_t abcd = vcombine_u16(vmovn_u32(ab), vmovn_u32(cd)); - uint16x8_t efgh = vcombine_u16(vmovn_u32(ef), vmovn_u32(gh)); - return v_uint8x16(vcombine_u8(vmovn_u16(abcd), vmovn_u16(efgh))); -} - -inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, - const v_float32x4& m3) -{ - float32x2_t vl = vget_low_f32(v.val), vh = vget_high_f32(v.val); - float32x4_t res = vmulq_lane_f32(m0.val, vl, 0); - res = vmlaq_lane_f32(res, m1.val, vl, 1); - res = vmlaq_lane_f32(res, m2.val, vh, 0); - res = vmlaq_lane_f32(res, m3.val, vh, 1); - return v_float32x4(res); -} - -inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, - const v_float32x4& a) -{ - float32x2_t vl = vget_low_f32(v.val), vh = vget_high_f32(v.val); - float32x4_t res = vmulq_lane_f32(m0.val, vl, 0); - res = vmlaq_lane_f32(res, m1.val, vl, 1); - res = vmlaq_lane_f32(res, m2.val, vh, 0); - res = vaddq_f32(res, a.val); - return v_float32x4(res); -} - -#define OPENCV_HAL_IMPL_NEON_BIN_OP(bin_op, _Tpvec, intrin) \ -inline _Tpvec bin_op (const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(intrin(a.val, b.val)); \ -} - -OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_uint8x16, vqaddq_u8) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_uint8x16, vqsubq_u8) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_int8x16, vqaddq_s8) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_int8x16, vqsubq_s8) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_uint16x8, vqaddq_u16) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_uint16x8, vqsubq_u16) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_int16x8, vqaddq_s16) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_int16x8, vqsubq_s16) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_int32x4, vaddq_s32) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_int32x4, vsubq_s32) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_mul, v_int32x4, vmulq_s32) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_uint32x4, vaddq_u32) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_uint32x4, vsubq_u32) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_mul, v_uint32x4, vmulq_u32) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_float32x4, vaddq_f32) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_float32x4, vsubq_f32) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_mul, v_float32x4, vmulq_f32) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_int64x2, vaddq_s64) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_int64x2, vsubq_s64) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_uint64x2, vaddq_u64) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_uint64x2, vsubq_u64) -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_BIN_OP(v_div, v_float32x4, vdivq_f32) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_float64x2, vaddq_f64) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_float64x2, vsubq_f64) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_mul, v_float64x2, vmulq_f64) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_div, v_float64x2, vdivq_f64) -#else -inline v_float32x4 v_div (const v_float32x4& a, const v_float32x4& b) -{ - float32x4_t reciprocal = vrecpeq_f32(b.val); - reciprocal = vmulq_f32(vrecpsq_f32(b.val, reciprocal), reciprocal); - reciprocal = vmulq_f32(vrecpsq_f32(b.val, reciprocal), reciprocal); - return v_float32x4(vmulq_f32(a.val, reciprocal)); -} -#endif - -// saturating multiply 8-bit, 16-bit -#define OPENCV_HAL_IMPL_NEON_MUL_SAT(_Tpvec, _Tpwvec) \ - inline _Tpvec v_mul (const _Tpvec& a, const _Tpvec& b) \ - { \ - _Tpwvec c, d; \ - v_mul_expand(a, b, c, d); \ - return v_pack(c, d); \ - } - -OPENCV_HAL_IMPL_NEON_MUL_SAT(v_int8x16, v_int16x8) -OPENCV_HAL_IMPL_NEON_MUL_SAT(v_uint8x16, v_uint16x8) -OPENCV_HAL_IMPL_NEON_MUL_SAT(v_int16x8, v_int32x4) -OPENCV_HAL_IMPL_NEON_MUL_SAT(v_uint16x8, v_uint32x4) - -// Multiply and expand -inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b, - v_int16x8& c, v_int16x8& d) -{ - c.val = vmull_s8(vget_low_s8(a.val), vget_low_s8(b.val)); -#if CV_NEON_AARCH64 - d.val = vmull_high_s8(a.val, b.val); -#else // #if CV_NEON_AARCH64 - d.val = vmull_s8(vget_high_s8(a.val), vget_high_s8(b.val)); -#endif // #if CV_NEON_AARCH64 -} - -inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b, - v_uint16x8& c, v_uint16x8& d) -{ - c.val = vmull_u8(vget_low_u8(a.val), vget_low_u8(b.val)); -#if CV_NEON_AARCH64 - d.val = vmull_high_u8(a.val, b.val); -#else // #if CV_NEON_AARCH64 - d.val = vmull_u8(vget_high_u8(a.val), vget_high_u8(b.val)); -#endif // #if CV_NEON_AARCH64 -} - -inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, - v_int32x4& c, v_int32x4& d) -{ - c.val = vmull_s16(vget_low_s16(a.val), vget_low_s16(b.val)); -#if CV_NEON_AARCH64 - d.val = vmull_high_s16(a.val, b.val); -#else // #if CV_NEON_AARCH64 - d.val = vmull_s16(vget_high_s16(a.val), vget_high_s16(b.val)); -#endif // #if CV_NEON_AARCH64 -} - -inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, - v_uint32x4& c, v_uint32x4& d) -{ - c.val = vmull_u16(vget_low_u16(a.val), vget_low_u16(b.val)); -#if CV_NEON_AARCH64 - d.val = vmull_high_u16(a.val, b.val); -#else // #if CV_NEON_AARCH64 - d.val = vmull_u16(vget_high_u16(a.val), vget_high_u16(b.val)); -#endif // #if CV_NEON_AARCH64 -} - -inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, - v_uint64x2& c, v_uint64x2& d) -{ - c.val = vmull_u32(vget_low_u32(a.val), vget_low_u32(b.val)); -#if CV_NEON_AARCH64 - d.val = vmull_high_u32(a.val, b.val); -#else // #if CV_NEON_AARCH64 - d.val = vmull_u32(vget_high_u32(a.val), vget_high_u32(b.val)); -#endif // #if CV_NEON_AARCH64 -} - -inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) -{ -#if CV_NEON_AARCH64 - int32x4_t c = vmull_high_s16(a.val, b.val); -#else // #if CV_NEON_AARCH64 - int32x4_t c = vmull_s16(vget_high_s16(a.val), vget_high_s16(b.val)); -#endif // #if CV_NEON_AARCH64 - return v_int16x8(vcombine_s16( - vshrn_n_s32(vmull_s16( vget_low_s16(a.val), vget_low_s16(b.val)), 16), - vshrn_n_s32(c, 16) - )); -} -inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) -{ -#if CV_NEON_AARCH64 - uint32x4_t c = vmull_high_u16(a.val, b.val); -#else // #if CV_NEON_AARCH64 - uint32x4_t c = vmull_u16(vget_high_u16(a.val), vget_high_u16(b.val)); -#endif // #if CV_NEON_AARCH64 - return v_uint16x8(vcombine_u16( - vshrn_n_u32(vmull_u16( vget_low_u16(a.val), vget_low_u16(b.val)), 16), - vshrn_n_u32(c, 16) - )); -} - -//////// Dot Product //////// - -// 16 >> 32 -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) -{ - int16x8_t uzp1, uzp2; - _v128_unzip(a.val, b.val, uzp1, uzp2); - int16x4_t a0 = vget_low_s16(uzp1); - int16x4_t b0 = vget_high_s16(uzp1); - int16x4_t a1 = vget_low_s16(uzp2); - int16x4_t b1 = vget_high_s16(uzp2); - int32x4_t p = vmull_s16(a0, b0); - return v_int32x4(vmlal_s16(p, a1, b1)); -} -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ - int16x8_t uzp1, uzp2; - _v128_unzip(a.val, b.val, uzp1, uzp2); - int16x4_t a0 = vget_low_s16(uzp1); - int16x4_t b0 = vget_high_s16(uzp1); - int16x4_t a1 = vget_low_s16(uzp2); - int16x4_t b1 = vget_high_s16(uzp2); - int32x4_t p = vmlal_s16(c.val, a0, b0); - return v_int32x4(vmlal_s16(p, a1, b1)); -} - -// 32 >> 64 -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) -{ - int32x4_t uzp1, uzp2; - _v128_unzip(a.val, b.val, uzp1, uzp2); - int32x2_t a0 = vget_low_s32(uzp1); - int32x2_t b0 = vget_high_s32(uzp1); - int32x2_t a1 = vget_low_s32(uzp2); - int32x2_t b1 = vget_high_s32(uzp2); - int64x2_t p = vmull_s32(a0, b0); - return v_int64x2(vmlal_s32(p, a1, b1)); -} -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ - int32x4_t uzp1, uzp2; - _v128_unzip(a.val, b.val, uzp1, uzp2); - int32x2_t a0 = vget_low_s32(uzp1); - int32x2_t b0 = vget_high_s32(uzp1); - int32x2_t a1 = vget_low_s32(uzp2); - int32x2_t b1 = vget_high_s32(uzp2); - int64x2_t p = vmlal_s32(c.val, a0, b0); - return v_int64x2(vmlal_s32(p, a1, b1)); -} - -// 8 >> 32 -#ifdef CV_NEON_DOT -#define OPENCV_HAL_IMPL_NEON_DOT_PRODUCT_OP(_Tpvec1, _Tpvec2, suffix) \ -inline _Tpvec1 v_dotprod_expand(const _Tpvec2& a, const _Tpvec2& b) \ -{ \ - return _Tpvec1(vdotq_##suffix(vdupq_n_##suffix(0), a.val, b.val));\ -} \ -inline _Tpvec1 v_dotprod_expand(const _Tpvec2& a, const _Tpvec2& b, const _Tpvec1& c) \ -{ \ - return _Tpvec1(vdotq_##suffix(c.val, a.val, b.val)); \ -} - -OPENCV_HAL_IMPL_NEON_DOT_PRODUCT_OP(v_uint32x4, v_uint8x16, u32) -OPENCV_HAL_IMPL_NEON_DOT_PRODUCT_OP(v_int32x4, v_int8x16, s32) -#else -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) -{ - const uint8x16_t zero = vreinterpretq_u8_u32(vdupq_n_u32(0)); - const uint8x16_t mask = vreinterpretq_u8_u32(vdupq_n_u32(0x00FF00FF)); - const uint16x8_t zero32 = vreinterpretq_u16_u32(vdupq_n_u32(0)); - const uint16x8_t mask32 = vreinterpretq_u16_u32(vdupq_n_u32(0x0000FFFF)); - - uint16x8_t even = vmulq_u16(vreinterpretq_u16_u8(vbslq_u8(mask, a.val, zero)), - vreinterpretq_u16_u8(vbslq_u8(mask, b.val, zero))); - uint16x8_t odd = vmulq_u16(vshrq_n_u16(vreinterpretq_u16_u8(a.val), 8), - vshrq_n_u16(vreinterpretq_u16_u8(b.val), 8)); - - uint32x4_t s0 = vaddq_u32(vreinterpretq_u32_u16(vbslq_u16(mask32, even, zero32)), - vreinterpretq_u32_u16(vbslq_u16(mask32, odd, zero32))); - uint32x4_t s1 = vaddq_u32(vshrq_n_u32(vreinterpretq_u32_u16(even), 16), - vshrq_n_u32(vreinterpretq_u32_u16(odd), 16)); - return v_uint32x4(vaddq_u32(s0, s1)); -} -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, - const v_uint32x4& c) -{ - return v_add(v_dotprod_expand(a, b), c); -} - -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) -{ - int16x8_t p0 = vmull_s8(vget_low_s8(a.val), vget_low_s8(b.val)); - int16x8_t p1 = vmull_s8(vget_high_s8(a.val), vget_high_s8(b.val)); - int16x8_t uzp1, uzp2; - _v128_unzip(p0, p1, uzp1, uzp2); - int16x8_t sum = vaddq_s16(uzp1, uzp2); - int16x4_t uzpl1, uzpl2; - _v128_unzip(vget_low_s16(sum), vget_high_s16(sum), uzpl1, uzpl2); - return v_int32x4(vaddl_s16(uzpl1, uzpl2)); -} -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, - const v_int32x4& c) -{ - return v_add(v_dotprod_expand(a, b), c); -} -#endif -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) -{ - const uint16x8_t zero = vreinterpretq_u16_u32(vdupq_n_u32(0)); - const uint16x8_t mask = vreinterpretq_u16_u32(vdupq_n_u32(0x0000FFFF)); - - uint32x4_t even = vmulq_u32(vreinterpretq_u32_u16(vbslq_u16(mask, a.val, zero)), - vreinterpretq_u32_u16(vbslq_u16(mask, b.val, zero))); - uint32x4_t odd = vmulq_u32(vshrq_n_u32(vreinterpretq_u32_u16(a.val), 16), - vshrq_n_u32(vreinterpretq_u32_u16(b.val), 16)); - uint32x4_t uzp1, uzp2; - _v128_unzip(even, odd, uzp1, uzp2); - uint64x2_t s0 = vaddl_u32(vget_low_u32(uzp1), vget_high_u32(uzp1)); - uint64x2_t s1 = vaddl_u32(vget_low_u32(uzp2), vget_high_u32(uzp2)); - return v_uint64x2(vaddq_u64(s0, s1)); -} -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) -{ - int32x4_t p0 = vmull_s16(vget_low_s16(a.val), vget_low_s16(b.val)); - int32x4_t p1 = vmull_s16(vget_high_s16(a.val), vget_high_s16(b.val)); - - int32x4_t uzp1, uzp2; - _v128_unzip(p0, p1, uzp1, uzp2); - int32x4_t sum = vaddq_s32(uzp1, uzp2); - - int32x2_t uzpl1, uzpl2; - _v128_unzip(vget_low_s32(sum), vget_high_s32(sum), uzpl1, uzpl2); - return v_int64x2(vaddl_s32(uzpl1, uzpl2)); -} -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, - const v_int64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 32 >> 64f -#if CV_SIMD128_64F -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) -{ return v_cvt_f64(v_dotprod(a, b)); } -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, - const v_float64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } -#endif - -//////// Fast Dot Product //////// - -// 16 >> 32 -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) -{ -#if CV_NEON_AARCH64 - int32x4_t p = vmull_s16(vget_low_s16(a.val), vget_low_s16(b.val)); - return v_int32x4(vmlal_high_s16(p, a.val, b.val)); -#else - int16x4_t a0 = vget_low_s16(a.val); - int16x4_t a1 = vget_high_s16(a.val); - int16x4_t b0 = vget_low_s16(b.val); - int16x4_t b1 = vget_high_s16(b.val); - int32x4_t p = vmull_s16(a0, b0); - return v_int32x4(vmlal_s16(p, a1, b1)); -#endif -} -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ -#if CV_NEON_AARCH64 - int32x4_t p = vmlal_s16(c.val, vget_low_s16(a.val), vget_low_s16(b.val)); - return v_int32x4(vmlal_high_s16(p, a.val, b.val)); -#else - int16x4_t a0 = vget_low_s16(a.val); - int16x4_t a1 = vget_high_s16(a.val); - int16x4_t b0 = vget_low_s16(b.val); - int16x4_t b1 = vget_high_s16(b.val); - int32x4_t p = vmlal_s16(c.val, a0, b0); - return v_int32x4(vmlal_s16(p, a1, b1)); -#endif -} - -// 32 >> 64 -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) -{ -#if CV_NEON_AARCH64 - int64x2_t p = vmull_s32(vget_low_s32(a.val), vget_low_s32(b.val)); - return v_int64x2(vmlal_high_s32(p, a.val, b.val)); -#else - int32x2_t a0 = vget_low_s32(a.val); - int32x2_t a1 = vget_high_s32(a.val); - int32x2_t b0 = vget_low_s32(b.val); - int32x2_t b1 = vget_high_s32(b.val); - int64x2_t p = vmull_s32(a0, b0); - return v_int64x2(vmlal_s32(p, a1, b1)); -#endif -} -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ -#if CV_NEON_AARCH64 - int64x2_t p = vmlal_s32(c.val, vget_low_s32(a.val), vget_low_s32(b.val)); - return v_int64x2(vmlal_high_s32(p, a.val, b.val)); -#else - int32x2_t a0 = vget_low_s32(a.val); - int32x2_t a1 = vget_high_s32(a.val); - int32x2_t b0 = vget_low_s32(b.val); - int32x2_t b1 = vget_high_s32(b.val); - int64x2_t p = vmlal_s32(c.val, a0, b0); - return v_int64x2(vmlal_s32(p, a1, b1)); -#endif -} - -// 8 >> 32 -#ifdef CV_NEON_DOT -#define OPENCV_HAL_IMPL_NEON_DOT_PRODUCT_FAST_OP(_Tpvec1, _Tpvec2, suffix) \ -inline _Tpvec1 v_dotprod_expand_fast(const _Tpvec2& a, const _Tpvec2& b) \ -{ \ - return v_dotprod_expand(a, b); \ -} \ -inline _Tpvec1 v_dotprod_expand_fast(const _Tpvec2& a, const _Tpvec2& b, const _Tpvec1& c) \ -{ \ - return v_dotprod_expand(a, b, c); \ -} - -OPENCV_HAL_IMPL_NEON_DOT_PRODUCT_FAST_OP(v_uint32x4, v_uint8x16, u32) -OPENCV_HAL_IMPL_NEON_DOT_PRODUCT_FAST_OP(v_int32x4, v_int8x16, s32) -#else -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) -{ - uint16x8_t p0 = vmull_u8(vget_low_u8(a.val), vget_low_u8(b.val)); - uint16x8_t p1 = vmull_u8(vget_high_u8(a.val), vget_high_u8(b.val)); - uint32x4_t s0 = vaddl_u16(vget_low_u16(p0), vget_low_u16(p1)); - uint32x4_t s1 = vaddl_u16(vget_high_u16(p0), vget_high_u16(p1)); - return v_uint32x4(vaddq_u32(s0, s1)); -} -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) -{ - return v_add(v_dotprod_expand_fast(a, b), c); -} - -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) -{ - int16x8_t prod = vmull_s8(vget_low_s8(a.val), vget_low_s8(b.val)); - prod = vmlal_s8(prod, vget_high_s8(a.val), vget_high_s8(b.val)); - return v_int32x4(vaddl_s16(vget_low_s16(prod), vget_high_s16(prod))); -} -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) -{ - return v_add(v_dotprod_expand_fast(a, b), c); -} -#endif - -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) -{ - uint32x4_t p0 = vmull_u16(vget_low_u16(a.val), vget_low_u16(b.val)); - uint32x4_t p1 = vmull_u16(vget_high_u16(a.val), vget_high_u16(b.val)); - uint64x2_t s0 = vaddl_u32(vget_low_u32(p0), vget_high_u32(p0)); - uint64x2_t s1 = vaddl_u32(vget_low_u32(p1), vget_high_u32(p1)); - return v_uint64x2(vaddq_u64(s0, s1)); -} -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) -{ - int32x4_t prod = vmull_s16(vget_low_s16(a.val), vget_low_s16(b.val)); - prod = vmlal_s16(prod, vget_high_s16(a.val), vget_high_s16(b.val)); - return v_int64x2(vaddl_s32(vget_low_s32(prod), vget_high_s32(prod))); -} -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -// 32 >> 64f -#if CV_SIMD128_64F -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) -{ return v_cvt_f64(v_dotprod_fast(a, b)); } -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } -#endif - - -#define OPENCV_HAL_IMPL_NEON_LOGIC_OP(_Tpvec, suffix) \ - OPENCV_HAL_IMPL_NEON_BIN_OP(v_and, _Tpvec, vandq_##suffix) \ - OPENCV_HAL_IMPL_NEON_BIN_OP(v_or, _Tpvec, vorrq_##suffix) \ - OPENCV_HAL_IMPL_NEON_BIN_OP(v_xor, _Tpvec, veorq_##suffix) \ - inline _Tpvec v_not (const _Tpvec& a) \ - { \ - return _Tpvec(vreinterpretq_##suffix##_u8(vmvnq_u8(vreinterpretq_u8_##suffix(a.val)))); \ - } - -OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_uint8x16, u8) -OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_int8x16, s8) -OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_uint16x8, u16) -OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_int16x8, s16) -OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_uint32x4, u32) -OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_int32x4, s32) -OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_uint64x2, u64) -OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_int64x2, s64) - -#define OPENCV_HAL_IMPL_NEON_FLT_BIT_OP(bin_op, intrin) \ -inline v_float32x4 bin_op (const v_float32x4& a, const v_float32x4& b) \ -{ \ - return v_float32x4(vreinterpretq_f32_s32(intrin(vreinterpretq_s32_f32(a.val), vreinterpretq_s32_f32(b.val)))); \ -} - -OPENCV_HAL_IMPL_NEON_FLT_BIT_OP(v_and, vandq_s32) -OPENCV_HAL_IMPL_NEON_FLT_BIT_OP(v_or, vorrq_s32) -OPENCV_HAL_IMPL_NEON_FLT_BIT_OP(v_xor, veorq_s32) - -inline v_float32x4 v_not (const v_float32x4& a) -{ - return v_float32x4(vreinterpretq_f32_s32(vmvnq_s32(vreinterpretq_s32_f32(a.val)))); -} - -#if CV_SIMD128_64F -inline v_float32x4 v_sqrt(const v_float32x4& x) -{ - return v_float32x4(vsqrtq_f32(x.val)); -} - -inline v_float32x4 v_invsqrt(const v_float32x4& x) -{ - v_float32x4 one = v_setall_f32(1.0f); - return v_div(one, v_sqrt(x)); -} -#else -inline v_float32x4 v_sqrt(const v_float32x4& x) -{ - float32x4_t x1 = vmaxq_f32(x.val, vdupq_n_f32(FLT_MIN)); - float32x4_t e = vrsqrteq_f32(x1); - e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(x1, e), e), e); - e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(x1, e), e), e); - return v_float32x4(vmulq_f32(x.val, e)); -} - -inline v_float32x4 v_invsqrt(const v_float32x4& x) -{ - float32x4_t e = vrsqrteq_f32(x.val); - e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(x.val, e), e), e); - e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(x.val, e), e), e); - return v_float32x4(e); -} -#endif - -#define OPENCV_HAL_IMPL_NEON_ABS(_Tpuvec, _Tpsvec, usuffix, ssuffix) \ -inline _Tpuvec v_abs(const _Tpsvec& a) { return v_reinterpret_as_##usuffix(_Tpsvec(vabsq_##ssuffix(a.val))); } - -OPENCV_HAL_IMPL_NEON_ABS(v_uint8x16, v_int8x16, u8, s8) -OPENCV_HAL_IMPL_NEON_ABS(v_uint16x8, v_int16x8, u16, s16) -OPENCV_HAL_IMPL_NEON_ABS(v_uint32x4, v_int32x4, u32, s32) - -inline v_float32x4 v_abs(v_float32x4 x) -{ return v_float32x4(vabsq_f32(x.val)); } - -#if CV_SIMD128_64F -#define OPENCV_HAL_IMPL_NEON_DBL_BIT_OP(bin_op, intrin) \ -inline v_float64x2 bin_op (const v_float64x2& a, const v_float64x2& b) \ -{ \ - return v_float64x2(vreinterpretq_f64_s64(intrin(vreinterpretq_s64_f64(a.val), vreinterpretq_s64_f64(b.val)))); \ -} - -OPENCV_HAL_IMPL_NEON_DBL_BIT_OP(v_and, vandq_s64) -OPENCV_HAL_IMPL_NEON_DBL_BIT_OP(v_or, vorrq_s64) -OPENCV_HAL_IMPL_NEON_DBL_BIT_OP(v_xor, veorq_s64) - -inline v_float64x2 v_not (const v_float64x2& a) -{ - return v_float64x2(vreinterpretq_f64_s32(vmvnq_s32(vreinterpretq_s32_f64(a.val)))); -} - -inline v_float64x2 v_sqrt(const v_float64x2& x) -{ - return v_float64x2(vsqrtq_f64(x.val)); -} - -inline v_float64x2 v_invsqrt(const v_float64x2& x) -{ - v_float64x2 one = v_setall_f64(1.0f); - return v_div(one, v_sqrt(x)); -} - -inline v_float64x2 v_abs(v_float64x2 x) -{ return v_float64x2(vabsq_f64(x.val)); } -#endif - -// TODO: exp, log, sin, cos - -#define OPENCV_HAL_IMPL_NEON_BIN_FUNC(_Tpvec, func, intrin) \ -inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(intrin(a.val, b.val)); \ -} - -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_min, vminq_u8) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_max, vmaxq_u8) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_min, vminq_s8) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_max, vmaxq_s8) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_min, vminq_u16) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_max, vmaxq_u16) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_min, vminq_s16) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_max, vmaxq_s16) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint32x4, v_min, vminq_u32) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint32x4, v_max, vmaxq_u32) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int32x4, v_min, vminq_s32) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int32x4, v_max, vmaxq_s32) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float32x4, v_min, vminq_f32) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float32x4, v_max, vmaxq_f32) -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float64x2, v_min, vminq_f64) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float64x2, v_max, vmaxq_f64) -#endif - -#define OPENCV_HAL_IMPL_NEON_INT_CMP_OP(_Tpvec, cast, suffix, not_suffix) \ -inline _Tpvec v_eq (const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(cast(vceqq_##suffix(a.val, b.val))); } \ -inline _Tpvec v_ne (const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(cast(vmvnq_##not_suffix(vceqq_##suffix(a.val, b.val)))); } \ -inline _Tpvec v_lt (const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(cast(vcltq_##suffix(a.val, b.val))); } \ -inline _Tpvec v_gt (const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(cast(vcgtq_##suffix(a.val, b.val))); } \ -inline _Tpvec v_le (const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(cast(vcleq_##suffix(a.val, b.val))); } \ -inline _Tpvec v_ge (const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(cast(vcgeq_##suffix(a.val, b.val))); } - -OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_uint8x16, OPENCV_HAL_NOP, u8, u8) -OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_int8x16, vreinterpretq_s8_u8, s8, u8) -OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_uint16x8, OPENCV_HAL_NOP, u16, u16) -OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_int16x8, vreinterpretq_s16_u16, s16, u16) -OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_uint32x4, OPENCV_HAL_NOP, u32, u32) -OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_int32x4, vreinterpretq_s32_u32, s32, u32) -OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_float32x4, vreinterpretq_f32_u32, f32, u32) -#if defined(__aarch64__) || defined(_M_ARM64) -static inline uint64x2_t vmvnq_u64(uint64x2_t a) -{ - uint64x2_t vx = vreinterpretq_u64_u32(vdupq_n_u32(0xFFFFFFFF)); - return veorq_u64(a, vx); -} -//OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_uint64x2, OPENCV_HAL_NOP, u64, u64) -//OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_int64x2, vreinterpretq_s64_u64, s64, u64) -static inline v_uint64x2 v_eq (const v_uint64x2& a, const v_uint64x2& b) -{ return v_uint64x2(vceqq_u64(a.val, b.val)); } -static inline v_uint64x2 v_ne (const v_uint64x2& a, const v_uint64x2& b) -{ return v_uint64x2(vmvnq_u64(vceqq_u64(a.val, b.val))); } -static inline v_int64x2 v_eq (const v_int64x2& a, const v_int64x2& b) -{ return v_int64x2(vreinterpretq_s64_u64(vceqq_s64(a.val, b.val))); } -static inline v_int64x2 v_ne (const v_int64x2& a, const v_int64x2& b) -{ return v_int64x2(vreinterpretq_s64_u64(vmvnq_u64(vceqq_s64(a.val, b.val)))); } -#else -static inline v_uint64x2 v_eq (const v_uint64x2& a, const v_uint64x2& b) -{ - uint32x4_t cmp = vceqq_u32(vreinterpretq_u32_u64(a.val), vreinterpretq_u32_u64(b.val)); - uint32x4_t swapped = vrev64q_u32(cmp); - return v_uint64x2(vreinterpretq_u64_u32(vandq_u32(cmp, swapped))); -} -static inline v_uint64x2 v_ne (const v_uint64x2& a, const v_uint64x2& b) -{ - uint32x4_t cmp = vceqq_u32(vreinterpretq_u32_u64(a.val), vreinterpretq_u32_u64(b.val)); - uint32x4_t swapped = vrev64q_u32(cmp); - uint64x2_t v_eq = vreinterpretq_u64_u32(vandq_u32(cmp, swapped)); - uint64x2_t vx = vreinterpretq_u64_u32(vdupq_n_u32(0xFFFFFFFF)); - return v_uint64x2(veorq_u64(v_eq, vx)); -} -static inline v_int64x2 v_eq (const v_int64x2& a, const v_int64x2& b) -{ - return v_reinterpret_as_s64(v_eq(v_reinterpret_as_u64(a), v_reinterpret_as_u64(b))); -} -static inline v_int64x2 v_ne (const v_int64x2& a, const v_int64x2& b) -{ - return v_reinterpret_as_s64(v_ne(v_reinterpret_as_u64(a), v_reinterpret_as_u64(b))); -} -#endif -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_float64x2, vreinterpretq_f64_u64, f64, u64) -#endif - -inline v_float32x4 v_not_nan(const v_float32x4& a) -{ return v_float32x4(vreinterpretq_f32_u32(vceqq_f32(a.val, a.val))); } -#if CV_SIMD128_64F -inline v_float64x2 v_not_nan(const v_float64x2& a) -{ return v_float64x2(vreinterpretq_f64_u64(vceqq_f64(a.val, a.val))); } -#endif - -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_add_wrap, vaddq_u8) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_add_wrap, vaddq_s8) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_add_wrap, vaddq_u16) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_add_wrap, vaddq_s16) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_sub_wrap, vsubq_u8) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_sub_wrap, vsubq_s8) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_sub_wrap, vsubq_u16) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_sub_wrap, vsubq_s16) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_mul_wrap, vmulq_u8) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_mul_wrap, vmulq_s8) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_mul_wrap, vmulq_u16) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_mul_wrap, vmulq_s16) - -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_absdiff, vabdq_u8) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_absdiff, vabdq_u16) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint32x4, v_absdiff, vabdq_u32) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float32x4, v_absdiff, vabdq_f32) -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float64x2, v_absdiff, vabdq_f64) -#endif - -/** Saturating absolute difference **/ -inline v_int8x16 v_absdiffs(const v_int8x16& a, const v_int8x16& b) -{ return v_int8x16(vqabsq_s8(vqsubq_s8(a.val, b.val))); } -inline v_int16x8 v_absdiffs(const v_int16x8& a, const v_int16x8& b) -{ return v_int16x8(vqabsq_s16(vqsubq_s16(a.val, b.val))); } - -#define OPENCV_HAL_IMPL_NEON_BIN_FUNC2(_Tpvec, _Tpvec2, cast, func, intrin) \ -inline _Tpvec2 func(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec2(cast(intrin(a.val, b.val))); \ -} - -OPENCV_HAL_IMPL_NEON_BIN_FUNC2(v_int8x16, v_uint8x16, vreinterpretq_u8_s8, v_absdiff, vabdq_s8) -OPENCV_HAL_IMPL_NEON_BIN_FUNC2(v_int16x8, v_uint16x8, vreinterpretq_u16_s16, v_absdiff, vabdq_s16) -OPENCV_HAL_IMPL_NEON_BIN_FUNC2(v_int32x4, v_uint32x4, vreinterpretq_u32_s32, v_absdiff, vabdq_s32) - -inline v_float32x4 v_magnitude(const v_float32x4& a, const v_float32x4& b) -{ - v_float32x4 x(vmlaq_f32(vmulq_f32(a.val, a.val), b.val, b.val)); - return v_sqrt(x); -} - -inline v_float32x4 v_sqr_magnitude(const v_float32x4& a, const v_float32x4& b) -{ - return v_float32x4(vmlaq_f32(vmulq_f32(a.val, a.val), b.val, b.val)); -} - -inline v_float32x4 v_fma(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) -{ -#if CV_SIMD128_64F - // ARMv8, which adds support for 64-bit floating-point (so CV_SIMD128_64F is defined), - // also adds FMA support both for single- and double-precision floating-point vectors - return v_float32x4(vfmaq_f32(c.val, a.val, b.val)); -#else - return v_float32x4(vmlaq_f32(c.val, a.val, b.val)); -#endif -} - -inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ - return v_int32x4(vmlaq_s32(c.val, a.val, b.val)); -} - -inline v_float32x4 v_muladd(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) -{ - return v_fma(a, b, c); -} - -inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ - return v_fma(a, b, c); -} - -#if CV_SIMD128_64F -inline v_float64x2 v_magnitude(const v_float64x2& a, const v_float64x2& b) -{ - v_float64x2 x(vaddq_f64(vmulq_f64(a.val, a.val), vmulq_f64(b.val, b.val))); - return v_sqrt(x); -} - -inline v_float64x2 v_sqr_magnitude(const v_float64x2& a, const v_float64x2& b) -{ - return v_float64x2(vaddq_f64(vmulq_f64(a.val, a.val), vmulq_f64(b.val, b.val))); -} - -inline v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) -{ - return v_float64x2(vfmaq_f64(c.val, a.val, b.val)); -} - -inline v_float64x2 v_muladd(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) -{ - return v_fma(a, b, c); -} -#endif - -// trade efficiency for convenience -#define OPENCV_HAL_IMPL_NEON_SHIFT_OP(_Tpvec, suffix, _Tps, ssuffix) \ -inline _Tpvec v_shl (const _Tpvec& a, int n) \ -{ return _Tpvec(vshlq_##suffix(a.val, vdupq_n_##ssuffix((_Tps)n))); } \ -inline _Tpvec v_shr (const _Tpvec& a, int n) \ -{ return _Tpvec(vshlq_##suffix(a.val, vdupq_n_##ssuffix((_Tps)-n))); } \ -template inline _Tpvec v_shl(const _Tpvec& a) \ -{ return _Tpvec(vshlq_n_##suffix(a.val, n)); } \ -template inline _Tpvec v_shr(const _Tpvec& a) \ -{ return _Tpvec(vshrq_n_##suffix(a.val, n)); } \ -template inline _Tpvec v_rshr(const _Tpvec& a) \ -{ return _Tpvec(vrshrq_n_##suffix(a.val, n)); } - -OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_uint8x16, u8, schar, s8) -OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_int8x16, s8, schar, s8) -OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_uint16x8, u16, short, s16) -OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_int16x8, s16, short, s16) -OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_uint32x4, u32, int, s32) -OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_int32x4, s32, int, s32) -OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_uint64x2, u64, int64, s64) -OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_int64x2, s64, int64, s64) - -#define OPENCV_HAL_IMPL_NEON_ROTATE_OP(_Tpvec, suffix) \ -template inline _Tpvec v_rotate_right(const _Tpvec& a) \ -{ return _Tpvec(vextq_##suffix(a.val, vdupq_n_##suffix(0), n)); } \ -template inline _Tpvec v_rotate_left(const _Tpvec& a) \ -{ return _Tpvec(vextq_##suffix(vdupq_n_##suffix(0), a.val, VTraits<_Tpvec>::nlanes - n)); } \ -template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a) \ -{ return a; } \ -template inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(vextq_##suffix(a.val, b.val, n)); } \ -template inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(vextq_##suffix(b.val, a.val, VTraits<_Tpvec>::nlanes - n)); } \ -template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a, const _Tpvec& b) \ -{ CV_UNUSED(b); return a; } - -OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_uint8x16, u8) -OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_int8x16, s8) -OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_uint16x8, u16) -OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_int16x8, s16) -OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_uint32x4, u32) -OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_int32x4, s32) -OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_float32x4, f32) -OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_uint64x2, u64) -OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_int64x2, s64) -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_float64x2, f64) -#endif - -#if defined(__clang__) && defined(__aarch64__) -// avoid LD2 instruction. details: https://github.com/opencv/opencv/issues/14863 -#define OPENCV_HAL_IMPL_NEON_LOAD_LOW_OP(_Tpvec, _Tp, suffix) \ -inline _Tpvec v_load_low(const _Tp* ptr) \ -{ \ -typedef uint64 CV_DECL_ALIGNED(1) unaligned_uint64; \ -uint64 v = *(unaligned_uint64*)ptr; \ -return _Tpvec(v_reinterpret_as_##suffix(v_uint64x2(v, (uint64)123456))); \ -} -#else -#define OPENCV_HAL_IMPL_NEON_LOAD_LOW_OP(_Tpvec, _Tp, suffix) \ -inline _Tpvec v_load_low(const _Tp* ptr) \ -{ return _Tpvec(vcombine_##suffix(vld1_##suffix(ptr), vdup_n_##suffix((_Tp)0))); } -#endif - -#define OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(_Tpvec, _Tp, suffix) \ -inline _Tpvec v_load(const _Tp* ptr) \ -{ return _Tpvec(vld1q_##suffix(ptr)); } \ -inline _Tpvec v_load_aligned(const _Tp* ptr) \ -{ return _Tpvec(vld1q_##suffix(ptr)); } \ -OPENCV_HAL_IMPL_NEON_LOAD_LOW_OP(_Tpvec, _Tp, suffix) \ -inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ -{ return _Tpvec(vcombine_##suffix(vld1_##suffix(ptr0), vld1_##suffix(ptr1))); } \ -inline void v_store(_Tp* ptr, const _Tpvec& a) \ -{ vst1q_##suffix(ptr, a.val); } \ -inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ -{ vst1q_##suffix(ptr, a.val); } \ -inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ -{ vst1q_##suffix(ptr, a.val); } \ -inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ -{ vst1q_##suffix(ptr, a.val); } \ -inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ -{ vst1_##suffix(ptr, vget_low_##suffix(a.val)); } \ -inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ -{ vst1_##suffix(ptr, vget_high_##suffix(a.val)); } - -OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_uint8x16, uchar, u8) -OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_int8x16, schar, s8) -OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_uint16x8, ushort, u16) -OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_int16x8, short, s16) -OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_uint32x4, unsigned, u32) -OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_int32x4, int, s32) -OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_uint64x2, uint64, u64) -OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_int64x2, int64, s64) -OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_float32x4, float, f32) -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_float64x2, double, f64) -#endif - -inline unsigned v_reduce_sum(const v_uint8x16& a) -{ -#if CV_NEON_AARCH64 - uint16_t t0 = vaddlvq_u8(a.val); - return t0; -#else // #if CV_NEON_AARCH64 - uint32x4_t t0 = vpaddlq_u16(vpaddlq_u8(a.val)); - uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); - return vget_lane_u32(vpadd_u32(t1, t1), 0); -#endif // #if CV_NEON_AARCH64 -} -inline int v_reduce_sum(const v_int8x16& a) -{ -#if CV_NEON_AARCH64 - int16_t t0 = vaddlvq_s8(a.val); - return t0; -#else // #if CV_NEON_AARCH64 - int32x4_t t0 = vpaddlq_s16(vpaddlq_s8(a.val)); - int32x2_t t1 = vpadd_s32(vget_low_s32(t0), vget_high_s32(t0)); - return vget_lane_s32(vpadd_s32(t1, t1), 0); -#endif // #if CV_NEON_AARCH64 -} -inline unsigned v_reduce_sum(const v_uint16x8& a) -{ -#if CV_NEON_AARCH64 - uint32_t t0 = vaddlvq_u16(a.val); - return t0; -#else // #if CV_NEON_AARCH64 - uint32x4_t t0 = vpaddlq_u16(a.val); - uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); - return vget_lane_u32(vpadd_u32(t1, t1), 0); -#endif // #if CV_NEON_AARCH64 -} -inline int v_reduce_sum(const v_int16x8& a) -{ -#if CV_NEON_AARCH64 - int32_t t0 = vaddlvq_s16(a.val); - return t0; -#else // #if CV_NEON_AARCH64 - int32x4_t t0 = vpaddlq_s16(a.val); - int32x2_t t1 = vpadd_s32(vget_low_s32(t0), vget_high_s32(t0)); - return vget_lane_s32(vpadd_s32(t1, t1), 0); -#endif // #if CV_NEON_AARCH64 -} - -#if CV_NEON_AARCH64 -#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \ -inline scalartype v_reduce_##func(const _Tpvec& a) \ -{ \ - return v##vectorfunc##vq_##suffix(a.val); \ -} -#else // #if CV_NEON_AARCH64 -#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \ -inline scalartype v_reduce_##func(const _Tpvec& a) \ -{ \ - _Tpnvec##_t a0 = vp##vectorfunc##_##suffix(vget_low_##suffix(a.val), vget_high_##suffix(a.val)); \ - a0 = vp##vectorfunc##_##suffix(a0, a0); \ - a0 = vp##vectorfunc##_##suffix(a0, a0); \ - return (scalartype)vget_lane_##suffix(vp##vectorfunc##_##suffix(a0, a0),0); \ -} -#endif // #if CV_NEON_AARCH64 - -OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(v_uint8x16, uint8x8, uchar, max, max, u8) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(v_uint8x16, uint8x8, uchar, min, min, u8) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(v_int8x16, int8x8, schar, max, max, s8) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(v_int8x16, int8x8, schar, min, min, s8) - -#if CV_NEON_AARCH64 -#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \ -inline scalartype v_reduce_##func(const _Tpvec& a) \ -{ \ - return v##vectorfunc##vq_##suffix(a.val); \ -} -#else // #if CV_NEON_AARCH64 -#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \ -inline scalartype v_reduce_##func(const _Tpvec& a) \ -{ \ - _Tpnvec##_t a0 = vp##vectorfunc##_##suffix(vget_low_##suffix(a.val), vget_high_##suffix(a.val)); \ - a0 = vp##vectorfunc##_##suffix(a0, a0); \ - return (scalartype)vget_lane_##suffix(vp##vectorfunc##_##suffix(a0, a0),0); \ -} -#endif // #if CV_NEON_AARCH64 - -OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_uint16x8, uint16x4, ushort, max, max, u16) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_uint16x8, uint16x4, ushort, min, min, u16) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_int16x8, int16x4, short, max, max, s16) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_int16x8, int16x4, short, min, min, s16) - -#if CV_NEON_AARCH64 -#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \ -inline scalartype v_reduce_##func(const _Tpvec& a) \ -{ \ - return v##vectorfunc##vq_##suffix(a.val); \ -} -#else // #if CV_NEON_AARCH64 -#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \ -inline scalartype v_reduce_##func(const _Tpvec& a) \ -{ \ - _Tpnvec##_t a0 = vp##vectorfunc##_##suffix(vget_low_##suffix(a.val), vget_high_##suffix(a.val)); \ - return (scalartype)vget_lane_##suffix(vp##vectorfunc##_##suffix(a0, vget_high_##suffix(a.val)),0); \ -} -#endif // #if CV_NEON_AARCH64 - -OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_uint32x4, uint32x2, unsigned, sum, add, u32) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_uint32x4, uint32x2, unsigned, max, max, u32) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_uint32x4, uint32x2, unsigned, min, min, u32) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_int32x4, int32x2, int, sum, add, s32) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_int32x4, int32x2, int, max, max, s32) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_int32x4, int32x2, int, min, min, s32) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_float32x4, float32x2, float, sum, add, f32) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_float32x4, float32x2, float, max, max, f32) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_float32x4, float32x2, float, min, min, f32) - -inline uint64 v_reduce_sum(const v_uint64x2& a) -{ -#if CV_NEON_AARCH64 - return vaddvq_u64(a.val); -#else // #if CV_NEON_AARCH64 - return vget_lane_u64(vadd_u64(vget_low_u64(a.val), vget_high_u64(a.val)),0); -#endif // #if CV_NEON_AARCH64 -} -inline int64 v_reduce_sum(const v_int64x2& a) -{ -#if CV_NEON_AARCH64 - return vaddvq_s64(a.val); -#else // #if CV_NEON_AARCH64 - return vget_lane_s64(vadd_s64(vget_low_s64(a.val), vget_high_s64(a.val)),0); -#endif // #if CV_NEON_AARCH64 -} -#if CV_SIMD128_64F -inline double v_reduce_sum(const v_float64x2& a) -{ - return vaddvq_f64(a.val); -} -#endif - -inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, - const v_float32x4& c, const v_float32x4& d) -{ -#if CV_NEON_AARCH64 - float32x4_t ab = vpaddq_f32(a.val, b.val); // a0+a1 a2+a3 b0+b1 b2+b3 - float32x4_t cd = vpaddq_f32(c.val, d.val); // c0+c1 d0+d1 c2+c3 d2+d3 - return v_float32x4(vpaddq_f32(ab, cd)); // sumA sumB sumC sumD -#else // #if CV_NEON_AARCH64 - float32x4x2_t ab = vtrnq_f32(a.val, b.val); - float32x4x2_t cd = vtrnq_f32(c.val, d.val); - - float32x4_t u0 = vaddq_f32(ab.val[0], ab.val[1]); // a0+a1 b0+b1 a2+a3 b2+b3 - float32x4_t u1 = vaddq_f32(cd.val[0], cd.val[1]); // c0+c1 d0+d1 c2+c3 d2+d3 - - float32x4_t v0 = vcombine_f32(vget_low_f32(u0), vget_low_f32(u1)); - float32x4_t v1 = vcombine_f32(vget_high_f32(u0), vget_high_f32(u1)); - - return v_float32x4(vaddq_f32(v0, v1)); -#endif // #if CV_NEON_AARCH64 -} - -inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b) -{ -#if CV_NEON_AARCH64 - uint8x16_t t0 = vabdq_u8(a.val, b.val); - uint16_t t1 = vaddlvq_u8(t0); - return t1; -#else // #if CV_NEON_AARCH64 - uint32x4_t t0 = vpaddlq_u16(vpaddlq_u8(vabdq_u8(a.val, b.val))); - uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); - return vget_lane_u32(vpadd_u32(t1, t1), 0); -#endif // #if CV_NEON_AARCH64 -} -inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b) -{ -#if CV_NEON_AARCH64 - uint8x16_t t0 = vreinterpretq_u8_s8(vabdq_s8(a.val, b.val)); - uint16_t t1 = vaddlvq_u8(t0); - return t1; -#else // #if CV_NEON_AARCH64 - uint32x4_t t0 = vpaddlq_u16(vpaddlq_u8(vreinterpretq_u8_s8(vabdq_s8(a.val, b.val)))); - uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); - return vget_lane_u32(vpadd_u32(t1, t1), 0); -#endif // #if CV_NEON_AARCH64 -} -inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b) -{ -#if CV_NEON_AARCH64 - uint16x8_t t0 = vabdq_u16(a.val, b.val); - uint32_t t1 = vaddlvq_u16(t0); - return t1; -#else // #if CV_NEON_AARCH64 - uint32x4_t t0 = vpaddlq_u16(vabdq_u16(a.val, b.val)); - uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); - return vget_lane_u32(vpadd_u32(t1, t1), 0); -#endif // #if CV_NEON_AARCH64 -} -inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b) -{ -#if CV_NEON_AARCH64 - uint16x8_t t0 = vreinterpretq_u16_s16(vabdq_s16(a.val, b.val)); - uint32_t t1 = vaddlvq_u16(t0); - return t1; -#else // #if CV_NEON_AARCH64 - uint32x4_t t0 = vpaddlq_u16(vreinterpretq_u16_s16(vabdq_s16(a.val, b.val))); - uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); - return vget_lane_u32(vpadd_u32(t1, t1), 0); -#endif // #if CV_NEON_AARCH64 -} -inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b) -{ -#if CV_NEON_AARCH64 - uint32x4_t t0 = vabdq_u32(a.val, b.val); - uint32_t t1 = vaddvq_u32(t0); - return t1; -#else // #if CV_NEON_AARCH64 - uint32x4_t t0 = vabdq_u32(a.val, b.val); - uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); - return vget_lane_u32(vpadd_u32(t1, t1), 0); -#endif // #if CV_NEON_AARCH64 -} -inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b) -{ -#if CV_NEON_AARCH64 - uint32x4_t t0 = vreinterpretq_u32_s32(vabdq_s32(a.val, b.val)); - uint32_t t1 = vaddvq_u32(t0); - return t1; -#else // #if CV_NEON_AARCH64 - uint32x4_t t0 = vreinterpretq_u32_s32(vabdq_s32(a.val, b.val)); - uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); - return vget_lane_u32(vpadd_u32(t1, t1), 0); -#endif // #if CV_NEON_AARCH64 -} -inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) -{ -#if CV_NEON_AARCH64 - float32x4_t t0 = vabdq_f32(a.val, b.val); - return vaddvq_f32(t0); -#else // #if CV_NEON_AARCH64 - float32x4_t t0 = vabdq_f32(a.val, b.val); - float32x2_t t1 = vpadd_f32(vget_low_f32(t0), vget_high_f32(t0)); - return vget_lane_f32(vpadd_f32(t1, t1), 0); -#endif // #if CV_NEON_AARCH64 -} - -inline v_uint8x16 v_popcount(const v_uint8x16& a) -{ return v_uint8x16(vcntq_u8(a.val)); } -inline v_uint8x16 v_popcount(const v_int8x16& a) -{ return v_uint8x16(vcntq_u8(vreinterpretq_u8_s8(a.val))); } -inline v_uint16x8 v_popcount(const v_uint16x8& a) -{ return v_uint16x8(vpaddlq_u8(vcntq_u8(vreinterpretq_u8_u16(a.val)))); } -inline v_uint16x8 v_popcount(const v_int16x8& a) -{ return v_uint16x8(vpaddlq_u8(vcntq_u8(vreinterpretq_u8_s16(a.val)))); } -inline v_uint32x4 v_popcount(const v_uint32x4& a) -{ return v_uint32x4(vpaddlq_u16(vpaddlq_u8(vcntq_u8(vreinterpretq_u8_u32(a.val))))); } -inline v_uint32x4 v_popcount(const v_int32x4& a) -{ return v_uint32x4(vpaddlq_u16(vpaddlq_u8(vcntq_u8(vreinterpretq_u8_s32(a.val))))); } -inline v_uint64x2 v_popcount(const v_uint64x2& a) -{ return v_uint64x2(vpaddlq_u32(vpaddlq_u16(vpaddlq_u8(vcntq_u8(vreinterpretq_u8_u64(a.val)))))); } -inline v_uint64x2 v_popcount(const v_int64x2& a) -{ return v_uint64x2(vpaddlq_u32(vpaddlq_u16(vpaddlq_u8(vcntq_u8(vreinterpretq_u8_s64(a.val)))))); } - -inline int v_signmask(const v_uint8x16& a) -{ -#if CV_NEON_AARCH64 - const int8x16_t signPosition = {0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7}; - const uint8x16_t byteOrder = {0,8,1,9,2,10,3,11,4,12,5,13,6,14,7,15}; - uint8x16_t v0 = vshlq_u8(vshrq_n_u8(a.val, 7), signPosition); - uint8x16_t v1 = vqtbl1q_u8(v0, byteOrder); - uint32_t t0 = vaddlvq_u16(vreinterpretq_u16_u8(v1)); - return t0; -#else // #if CV_NEON_AARCH64 - int8x8_t m0 = vcreate_s8(CV_BIG_UINT(0x0706050403020100)); - uint8x16_t v0 = vshlq_u8(vshrq_n_u8(a.val, 7), vcombine_s8(m0, m0)); - uint64x2_t v1 = vpaddlq_u32(vpaddlq_u16(vpaddlq_u8(v0))); - return (int)vgetq_lane_u64(v1, 0) + ((int)vgetq_lane_u64(v1, 1) << 8); -#endif // #if CV_NEON_AARCH64 -} - -inline int v_signmask(const v_int8x16& a) -{ return v_signmask(v_reinterpret_as_u8(a)); } - -inline int v_signmask(const v_uint16x8& a) -{ -#if CV_NEON_AARCH64 - const int16x8_t signPosition = {0,1,2,3,4,5,6,7}; - uint16x8_t v0 = vshlq_u16(vshrq_n_u16(a.val, 15), signPosition); - uint32_t t0 = vaddlvq_u16(v0); - return t0; -#else // #if CV_NEON_AARCH64 - int16x4_t m0 = vcreate_s16(CV_BIG_UINT(0x0003000200010000)); - uint16x8_t v0 = vshlq_u16(vshrq_n_u16(a.val, 15), vcombine_s16(m0, m0)); - uint64x2_t v1 = vpaddlq_u32(vpaddlq_u16(v0)); - return (int)vgetq_lane_u64(v1, 0) + ((int)vgetq_lane_u64(v1, 1) << 4); -#endif // #if CV_NEON_AARCH64 -} -inline int v_signmask(const v_int16x8& a) -{ return v_signmask(v_reinterpret_as_u16(a)); } - -inline int v_signmask(const v_uint32x4& a) -{ -#if CV_NEON_AARCH64 - const int32x4_t signPosition = {0,1,2,3}; - uint32x4_t v0 = vshlq_u32(vshrq_n_u32(a.val, 31), signPosition); - uint32_t t0 = vaddvq_u32(v0); - return t0; -#else // #if CV_NEON_AARCH64 - int32x2_t m0 = vcreate_s32(CV_BIG_UINT(0x0000000100000000)); - uint32x4_t v0 = vshlq_u32(vshrq_n_u32(a.val, 31), vcombine_s32(m0, m0)); - uint64x2_t v1 = vpaddlq_u32(v0); - return (int)vgetq_lane_u64(v1, 0) + ((int)vgetq_lane_u64(v1, 1) << 2); -#endif // #if CV_NEON_AARCH64 -} -inline int v_signmask(const v_int32x4& a) -{ return v_signmask(v_reinterpret_as_u32(a)); } -inline int v_signmask(const v_float32x4& a) -{ return v_signmask(v_reinterpret_as_u32(a)); } -inline int v_signmask(const v_uint64x2& a) -{ -#if CV_NEON_AARCH64 - const int64x2_t signPosition = {0,1}; - uint64x2_t v0 = vshlq_u64(vshrq_n_u64(a.val, 63), signPosition); - int t0 = (int)vaddvq_u64(v0); - return t0; -#else // #if CV_NEON_AARCH64 - int64x1_t m0 = vdup_n_s64(0); - uint64x2_t v0 = vshlq_u64(vshrq_n_u64(a.val, 63), vcombine_s64(m0, m0)); - return (int)vgetq_lane_u64(v0, 0) + ((int)vgetq_lane_u64(v0, 1) << 1); -#endif // #if CV_NEON_AARCH64 -} -inline int v_signmask(const v_int64x2& a) -{ return v_signmask(v_reinterpret_as_u64(a)); } -#if CV_SIMD128_64F -inline int v_signmask(const v_float64x2& a) -{ return v_signmask(v_reinterpret_as_u64(a)); } -#endif - -inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(a)); } -#if CV_SIMD128_64F -inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(a)); } -#endif - -#if CV_NEON_AARCH64 - #define OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(_Tpvec, suffix, shift) \ - inline bool v_check_all(const v_##_Tpvec& a) \ - { \ - return (vminvq_##suffix(a.val) >> shift) != 0; \ - } \ - inline bool v_check_any(const v_##_Tpvec& a) \ - { \ - return (vmaxvq_##suffix(a.val) >> shift) != 0; \ - } -#else // #if CV_NEON_AARCH64 - #define OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(_Tpvec, suffix, shift) \ - inline bool v_check_all(const v_##_Tpvec& a) \ - { \ - _Tpvec##_t v0 = vshrq_n_##suffix(vmvnq_##suffix(a.val), shift); \ - uint64x2_t v1 = vreinterpretq_u64_##suffix(v0); \ - return (vgetq_lane_u64(v1, 0) | vgetq_lane_u64(v1, 1)) == 0; \ - } \ - inline bool v_check_any(const v_##_Tpvec& a) \ - { \ - _Tpvec##_t v0 = vshrq_n_##suffix(a.val, shift); \ - uint64x2_t v1 = vreinterpretq_u64_##suffix(v0); \ - return (vgetq_lane_u64(v1, 0) | vgetq_lane_u64(v1, 1)) != 0; \ - } -#endif // #if CV_NEON_AARCH64 - -OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(uint8x16, u8, 7) -OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(uint16x8, u16, 15) -OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(uint32x4, u32, 31) - -inline bool v_check_all(const v_uint64x2& a) -{ - uint64x2_t v0 = vshrq_n_u64(a.val, 63); - return (vgetq_lane_u64(v0, 0) & vgetq_lane_u64(v0, 1)) == 1; -} -inline bool v_check_any(const v_uint64x2& a) -{ - uint64x2_t v0 = vshrq_n_u64(a.val, 63); - return (vgetq_lane_u64(v0, 0) | vgetq_lane_u64(v0, 1)) != 0; -} - -inline bool v_check_all(const v_int8x16& a) -{ return v_check_all(v_reinterpret_as_u8(a)); } -inline bool v_check_all(const v_int16x8& a) -{ return v_check_all(v_reinterpret_as_u16(a)); } -inline bool v_check_all(const v_int32x4& a) -{ return v_check_all(v_reinterpret_as_u32(a)); } -inline bool v_check_all(const v_float32x4& a) -{ return v_check_all(v_reinterpret_as_u32(a)); } - -inline bool v_check_any(const v_int8x16& a) -{ return v_check_any(v_reinterpret_as_u8(a)); } -inline bool v_check_any(const v_int16x8& a) -{ return v_check_any(v_reinterpret_as_u16(a)); } -inline bool v_check_any(const v_int32x4& a) -{ return v_check_any(v_reinterpret_as_u32(a)); } -inline bool v_check_any(const v_float32x4& a) -{ return v_check_any(v_reinterpret_as_u32(a)); } - -inline bool v_check_all(const v_int64x2& a) -{ return v_check_all(v_reinterpret_as_u64(a)); } -inline bool v_check_any(const v_int64x2& a) -{ return v_check_any(v_reinterpret_as_u64(a)); } -#if CV_SIMD128_64F -inline bool v_check_all(const v_float64x2& a) -{ return v_check_all(v_reinterpret_as_u64(a)); } -inline bool v_check_any(const v_float64x2& a) -{ return v_check_any(v_reinterpret_as_u64(a)); } -#endif - -#define OPENCV_HAL_IMPL_NEON_SELECT(_Tpvec, suffix, usuffix) \ -inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(vbslq_##suffix(vreinterpretq_##usuffix##_##suffix(mask.val), a.val, b.val)); \ -} - -OPENCV_HAL_IMPL_NEON_SELECT(v_uint8x16, u8, u8) -OPENCV_HAL_IMPL_NEON_SELECT(v_int8x16, s8, u8) -OPENCV_HAL_IMPL_NEON_SELECT(v_uint16x8, u16, u16) -OPENCV_HAL_IMPL_NEON_SELECT(v_int16x8, s16, u16) -OPENCV_HAL_IMPL_NEON_SELECT(v_uint32x4, u32, u32) -OPENCV_HAL_IMPL_NEON_SELECT(v_int32x4, s32, u32) -OPENCV_HAL_IMPL_NEON_SELECT(v_float32x4, f32, u32) -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_SELECT(v_float64x2, f64, u64) -#endif - -#if CV_NEON_AARCH64 -#define OPENCV_HAL_IMPL_NEON_EXPAND(_Tpvec, _Tpwvec, _Tp, suffix) \ -inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ -{ \ - b0.val = vmovl_##suffix(vget_low_##suffix(a.val)); \ - b1.val = vmovl_high_##suffix(a.val); \ -} \ -inline _Tpwvec v_expand_low(const _Tpvec& a) \ -{ \ - return _Tpwvec(vmovl_##suffix(vget_low_##suffix(a.val))); \ -} \ -inline _Tpwvec v_expand_high(const _Tpvec& a) \ -{ \ - return _Tpwvec(vmovl_high_##suffix(a.val)); \ -} \ -inline _Tpwvec v_load_expand(const _Tp* ptr) \ -{ \ - return _Tpwvec(vmovl_##suffix(vld1_##suffix(ptr))); \ -} -#else -#define OPENCV_HAL_IMPL_NEON_EXPAND(_Tpvec, _Tpwvec, _Tp, suffix) \ -inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ -{ \ - b0.val = vmovl_##suffix(vget_low_##suffix(a.val)); \ - b1.val = vmovl_##suffix(vget_high_##suffix(a.val)); \ -} \ -inline _Tpwvec v_expand_low(const _Tpvec& a) \ -{ \ - return _Tpwvec(vmovl_##suffix(vget_low_##suffix(a.val))); \ -} \ -inline _Tpwvec v_expand_high(const _Tpvec& a) \ -{ \ - return _Tpwvec(vmovl_##suffix(vget_high_##suffix(a.val))); \ -} \ -inline _Tpwvec v_load_expand(const _Tp* ptr) \ -{ \ - return _Tpwvec(vmovl_##suffix(vld1_##suffix(ptr))); \ -} -#endif - -OPENCV_HAL_IMPL_NEON_EXPAND(v_uint8x16, v_uint16x8, uchar, u8) -OPENCV_HAL_IMPL_NEON_EXPAND(v_int8x16, v_int16x8, schar, s8) -OPENCV_HAL_IMPL_NEON_EXPAND(v_uint16x8, v_uint32x4, ushort, u16) -OPENCV_HAL_IMPL_NEON_EXPAND(v_int16x8, v_int32x4, short, s16) -OPENCV_HAL_IMPL_NEON_EXPAND(v_uint32x4, v_uint64x2, uint, u32) -OPENCV_HAL_IMPL_NEON_EXPAND(v_int32x4, v_int64x2, int, s32) - -inline v_uint32x4 v_load_expand_q(const uchar* ptr) -{ - typedef unsigned int CV_DECL_ALIGNED(1) unaligned_uint; - uint8x8_t v0 = vcreate_u8(*(unaligned_uint*)ptr); - uint16x4_t v1 = vget_low_u16(vmovl_u8(v0)); - return v_uint32x4(vmovl_u16(v1)); -} - -inline v_int32x4 v_load_expand_q(const schar* ptr) -{ - typedef unsigned int CV_DECL_ALIGNED(1) unaligned_uint; - int8x8_t v0 = vcreate_s8(*(unaligned_uint*)ptr); - int16x4_t v1 = vget_low_s16(vmovl_s8(v0)); - return v_int32x4(vmovl_s16(v1)); -} - -#if defined(__aarch64__) || defined(_M_ARM64) -#define OPENCV_HAL_IMPL_NEON_UNPACKS(_Tpvec, suffix) \ -inline void v_zip(const v_##_Tpvec& a0, const v_##_Tpvec& a1, v_##_Tpvec& b0, v_##_Tpvec& b1) \ -{ \ - b0.val = vzip1q_##suffix(a0.val, a1.val); \ - b1.val = vzip2q_##suffix(a0.val, a1.val); \ -} \ -inline v_##_Tpvec v_combine_low(const v_##_Tpvec& a, const v_##_Tpvec& b) \ -{ \ - return v_##_Tpvec(vcombine_##suffix(vget_low_##suffix(a.val), vget_low_##suffix(b.val))); \ -} \ -inline v_##_Tpvec v_combine_high(const v_##_Tpvec& a, const v_##_Tpvec& b) \ -{ \ - return v_##_Tpvec(vcombine_##suffix(vget_high_##suffix(a.val), vget_high_##suffix(b.val))); \ -} \ -inline void v_recombine(const v_##_Tpvec& a, const v_##_Tpvec& b, v_##_Tpvec& c, v_##_Tpvec& d) \ -{ \ - c.val = vcombine_##suffix(vget_low_##suffix(a.val), vget_low_##suffix(b.val)); \ - d.val = vcombine_##suffix(vget_high_##suffix(a.val), vget_high_##suffix(b.val)); \ -} -#else -#define OPENCV_HAL_IMPL_NEON_UNPACKS(_Tpvec, suffix) \ -inline void v_zip(const v_##_Tpvec& a0, const v_##_Tpvec& a1, v_##_Tpvec& b0, v_##_Tpvec& b1) \ -{ \ - _Tpvec##x2_t p = vzipq_##suffix(a0.val, a1.val); \ - b0.val = p.val[0]; \ - b1.val = p.val[1]; \ -} \ -inline v_##_Tpvec v_combine_low(const v_##_Tpvec& a, const v_##_Tpvec& b) \ -{ \ - return v_##_Tpvec(vcombine_##suffix(vget_low_##suffix(a.val), vget_low_##suffix(b.val))); \ -} \ -inline v_##_Tpvec v_combine_high(const v_##_Tpvec& a, const v_##_Tpvec& b) \ -{ \ - return v_##_Tpvec(vcombine_##suffix(vget_high_##suffix(a.val), vget_high_##suffix(b.val))); \ -} \ -inline void v_recombine(const v_##_Tpvec& a, const v_##_Tpvec& b, v_##_Tpvec& c, v_##_Tpvec& d) \ -{ \ - c.val = vcombine_##suffix(vget_low_##suffix(a.val), vget_low_##suffix(b.val)); \ - d.val = vcombine_##suffix(vget_high_##suffix(a.val), vget_high_##suffix(b.val)); \ -} -#endif - -OPENCV_HAL_IMPL_NEON_UNPACKS(uint8x16, u8) -OPENCV_HAL_IMPL_NEON_UNPACKS(int8x16, s8) -OPENCV_HAL_IMPL_NEON_UNPACKS(uint16x8, u16) -OPENCV_HAL_IMPL_NEON_UNPACKS(int16x8, s16) -OPENCV_HAL_IMPL_NEON_UNPACKS(uint32x4, u32) -OPENCV_HAL_IMPL_NEON_UNPACKS(int32x4, s32) -OPENCV_HAL_IMPL_NEON_UNPACKS(float32x4, f32) -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_UNPACKS(float64x2, f64) -#endif - -inline v_uint8x16 v_reverse(const v_uint8x16 &a) -{ - uint8x16_t vec = vrev64q_u8(a.val); - return v_uint8x16(vextq_u8(vec, vec, 8)); -} - -inline v_int8x16 v_reverse(const v_int8x16 &a) -{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } - -inline v_uint16x8 v_reverse(const v_uint16x8 &a) -{ - uint16x8_t vec = vrev64q_u16(a.val); - return v_uint16x8(vextq_u16(vec, vec, 4)); -} - -inline v_int16x8 v_reverse(const v_int16x8 &a) -{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } - -inline v_uint32x4 v_reverse(const v_uint32x4 &a) -{ - uint32x4_t vec = vrev64q_u32(a.val); - return v_uint32x4(vextq_u32(vec, vec, 2)); -} - -inline v_int32x4 v_reverse(const v_int32x4 &a) -{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_float32x4 v_reverse(const v_float32x4 &a) -{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_uint64x2 v_reverse(const v_uint64x2 &a) -{ - uint64x2_t vec = a.val; - uint64x1_t vec_lo = vget_low_u64(vec); - uint64x1_t vec_hi = vget_high_u64(vec); - return v_uint64x2(vcombine_u64(vec_hi, vec_lo)); -} - -inline v_int64x2 v_reverse(const v_int64x2 &a) -{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } - -#if CV_SIMD128_64F -inline v_float64x2 v_reverse(const v_float64x2 &a) -{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } -#endif - -#define OPENCV_HAL_IMPL_NEON_EXTRACT(_Tpvec, suffix) \ -template \ -inline v_##_Tpvec v_extract(const v_##_Tpvec& a, const v_##_Tpvec& b) \ -{ \ - return v_##_Tpvec(vextq_##suffix(a.val, b.val, s)); \ -} - -OPENCV_HAL_IMPL_NEON_EXTRACT(uint8x16, u8) -OPENCV_HAL_IMPL_NEON_EXTRACT(int8x16, s8) -OPENCV_HAL_IMPL_NEON_EXTRACT(uint16x8, u16) -OPENCV_HAL_IMPL_NEON_EXTRACT(int16x8, s16) -OPENCV_HAL_IMPL_NEON_EXTRACT(uint32x4, u32) -OPENCV_HAL_IMPL_NEON_EXTRACT(int32x4, s32) -OPENCV_HAL_IMPL_NEON_EXTRACT(uint64x2, u64) -OPENCV_HAL_IMPL_NEON_EXTRACT(int64x2, s64) -OPENCV_HAL_IMPL_NEON_EXTRACT(float32x4, f32) -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_EXTRACT(float64x2, f64) -#endif - -#define OPENCV_HAL_IMPL_NEON_EXTRACT_N(_Tpvec, _Tp, suffix) \ -template inline _Tp v_extract_n(_Tpvec v) { return vgetq_lane_##suffix(v.val, i); } - -OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_uint8x16, uchar, u8) -OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_int8x16, schar, s8) -OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_uint16x8, ushort, u16) -OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_int16x8, short, s16) -OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_uint32x4, uint, u32) -OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_int32x4, int, s32) -OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_uint64x2, uint64, u64) -OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_int64x2, int64, s64) -OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_float32x4, float, f32) -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_float64x2, double, f64) -#endif - -#define OPENCV_HAL_IMPL_NEON_BROADCAST(_Tpvec, _Tp, suffix) \ -template inline _Tpvec v_broadcast_element(_Tpvec v) { _Tp t = v_extract_n(v); return v_setall_##suffix(t); } - -OPENCV_HAL_IMPL_NEON_BROADCAST(v_uint8x16, uchar, u8) -OPENCV_HAL_IMPL_NEON_BROADCAST(v_int8x16, schar, s8) -OPENCV_HAL_IMPL_NEON_BROADCAST(v_uint16x8, ushort, u16) -OPENCV_HAL_IMPL_NEON_BROADCAST(v_int16x8, short, s16) -OPENCV_HAL_IMPL_NEON_BROADCAST(v_uint32x4, uint, u32) -OPENCV_HAL_IMPL_NEON_BROADCAST(v_int32x4, int, s32) -OPENCV_HAL_IMPL_NEON_BROADCAST(v_uint64x2, uint64, u64) -OPENCV_HAL_IMPL_NEON_BROADCAST(v_int64x2, int64, s64) -OPENCV_HAL_IMPL_NEON_BROADCAST(v_float32x4, float, f32) -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_BROADCAST(v_float64x2, double, f64) -#endif - -#if CV_SIMD128_64F -inline v_int32x4 v_round(const v_float32x4& a) -{ - float32x4_t a_ = a.val; - int32x4_t result; -#if defined _MSC_VER - result = vcvtnq_s32_f32(a_); -#else - __asm__ ("fcvtns %0.4s, %1.4s" - : "=w"(result) - : "w"(a_) - : /* No clobbers */); -#endif - return v_int32x4(result); -} -#else -inline v_int32x4 v_round(const v_float32x4& a) -{ - // See https://github.com/opencv/opencv/pull/24271#issuecomment-1867318007 - float32x4_t delta = vdupq_n_f32(12582912.0f); - return v_int32x4(vcvtq_s32_f32(vsubq_f32(vaddq_f32(a.val, delta), delta))); -} -#endif -inline v_int32x4 v_floor(const v_float32x4& a) -{ - int32x4_t a1 = vcvtq_s32_f32(a.val); - uint32x4_t mask = vcgtq_f32(vcvtq_f32_s32(a1), a.val); - return v_int32x4(vaddq_s32(a1, vreinterpretq_s32_u32(mask))); -} - -inline v_int32x4 v_ceil(const v_float32x4& a) -{ - int32x4_t a1 = vcvtq_s32_f32(a.val); - uint32x4_t mask = vcgtq_f32(a.val, vcvtq_f32_s32(a1)); - return v_int32x4(vsubq_s32(a1, vreinterpretq_s32_u32(mask))); -} - -inline v_int32x4 v_trunc(const v_float32x4& a) -{ return v_int32x4(vcvtq_s32_f32(a.val)); } - -#if CV_SIMD128_64F -inline v_int32x4 v_round(const v_float64x2& a) -{ - static const int32x2_t zero = vdup_n_s32(0); - return v_int32x4(vcombine_s32(vmovn_s64(vcvtnq_s64_f64(a.val)), zero)); -} - -inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) -{ - return v_int32x4(vcombine_s32(vmovn_s64(vcvtnq_s64_f64(a.val)), vmovn_s64(vcvtnq_s64_f64(b.val)))); -} - -inline v_int32x4 v_floor(const v_float64x2& a) -{ - static const int32x2_t zero = vdup_n_s32(0); - int64x2_t a1 = vcvtq_s64_f64(a.val); - uint64x2_t mask = vcgtq_f64(vcvtq_f64_s64(a1), a.val); - a1 = vaddq_s64(a1, vreinterpretq_s64_u64(mask)); - return v_int32x4(vcombine_s32(vmovn_s64(a1), zero)); -} - -inline v_int32x4 v_ceil(const v_float64x2& a) -{ - static const int32x2_t zero = vdup_n_s32(0); - int64x2_t a1 = vcvtq_s64_f64(a.val); - uint64x2_t mask = vcgtq_f64(a.val, vcvtq_f64_s64(a1)); - a1 = vsubq_s64(a1, vreinterpretq_s64_u64(mask)); - return v_int32x4(vcombine_s32(vmovn_s64(a1), zero)); -} - -inline v_int32x4 v_trunc(const v_float64x2& a) -{ - static const int32x2_t zero = vdup_n_s32(0); - return v_int32x4(vcombine_s32(vmovn_s64(vcvtaq_s64_f64(a.val)), zero)); -} -#endif - -#if CV_NEON_AARCH64 -#define OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(_Tpvec, suffix) \ -inline void v_transpose4x4(const v_##_Tpvec& a0, const v_##_Tpvec& a1, \ - const v_##_Tpvec& a2, const v_##_Tpvec& a3, \ - v_##_Tpvec& b0, v_##_Tpvec& b1, \ - v_##_Tpvec& b2, v_##_Tpvec& b3) \ -{ \ - /* -- Pass 1: 64b transpose */ \ - _Tpvec##_t t0 = vreinterpretq_##suffix##32_##suffix##64( \ - vtrn1q_##suffix##64(vreinterpretq_##suffix##64_##suffix##32(a0.val), \ - vreinterpretq_##suffix##64_##suffix##32(a2.val))); \ - _Tpvec##_t t1 = vreinterpretq_##suffix##32_##suffix##64( \ - vtrn1q_##suffix##64(vreinterpretq_##suffix##64_##suffix##32(a1.val), \ - vreinterpretq_##suffix##64_##suffix##32(a3.val))); \ - _Tpvec##_t t2 = vreinterpretq_##suffix##32_##suffix##64( \ - vtrn2q_##suffix##64(vreinterpretq_##suffix##64_##suffix##32(a0.val), \ - vreinterpretq_##suffix##64_##suffix##32(a2.val))); \ - _Tpvec##_t t3 = vreinterpretq_##suffix##32_##suffix##64( \ - vtrn2q_##suffix##64(vreinterpretq_##suffix##64_##suffix##32(a1.val), \ - vreinterpretq_##suffix##64_##suffix##32(a3.val))); \ - /* -- Pass 2: 32b transpose */ \ - b0.val = vtrn1q_##suffix##32(t0, t1); \ - b1.val = vtrn2q_##suffix##32(t0, t1); \ - b2.val = vtrn1q_##suffix##32(t2, t3); \ - b3.val = vtrn2q_##suffix##32(t2, t3); \ -} - -OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(uint32x4, u) -OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(int32x4, s) -OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(float32x4, f) -#else // #if CV_NEON_AARCH64 -#define OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(_Tpvec, suffix) \ -inline void v_transpose4x4(const v_##_Tpvec& a0, const v_##_Tpvec& a1, \ - const v_##_Tpvec& a2, const v_##_Tpvec& a3, \ - v_##_Tpvec& b0, v_##_Tpvec& b1, \ - v_##_Tpvec& b2, v_##_Tpvec& b3) \ -{ \ - /* m00 m01 m02 m03 */ \ - /* m10 m11 m12 m13 */ \ - /* m20 m21 m22 m23 */ \ - /* m30 m31 m32 m33 */ \ - _Tpvec##x2_t t0 = vtrnq_##suffix(a0.val, a1.val); \ - _Tpvec##x2_t t1 = vtrnq_##suffix(a2.val, a3.val); \ - /* m00 m10 m02 m12 */ \ - /* m01 m11 m03 m13 */ \ - /* m20 m30 m22 m32 */ \ - /* m21 m31 m23 m33 */ \ - b0.val = vcombine_##suffix(vget_low_##suffix(t0.val[0]), vget_low_##suffix(t1.val[0])); \ - b1.val = vcombine_##suffix(vget_low_##suffix(t0.val[1]), vget_low_##suffix(t1.val[1])); \ - b2.val = vcombine_##suffix(vget_high_##suffix(t0.val[0]), vget_high_##suffix(t1.val[0])); \ - b3.val = vcombine_##suffix(vget_high_##suffix(t0.val[1]), vget_high_##suffix(t1.val[1])); \ -} - -OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(uint32x4, u32) -OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(int32x4, s32) -OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(float32x4, f32) -#endif // #if CV_NEON_AARCH64 - -#define OPENCV_HAL_IMPL_NEON_INTERLEAVED(_Tpvec, _Tp, suffix) \ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b) \ -{ \ - _Tpvec##x2_t v = vld2q_##suffix(ptr); \ - a.val = v.val[0]; \ - b.val = v.val[1]; \ -} \ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, v_##_Tpvec& c) \ -{ \ - _Tpvec##x3_t v = vld3q_##suffix(ptr); \ - a.val = v.val[0]; \ - b.val = v.val[1]; \ - c.val = v.val[2]; \ -} \ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, \ - v_##_Tpvec& c, v_##_Tpvec& d) \ -{ \ - _Tpvec##x4_t v = vld4q_##suffix(ptr); \ - a.val = v.val[0]; \ - b.val = v.val[1]; \ - c.val = v.val[2]; \ - d.val = v.val[3]; \ -} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - _Tpvec##x2_t v; \ - v.val[0] = a.val; \ - v.val[1] = b.val; \ - vst2q_##suffix(ptr, v); \ -} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ - const v_##_Tpvec& c, hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - _Tpvec##x3_t v; \ - v.val[0] = a.val; \ - v.val[1] = b.val; \ - v.val[2] = c.val; \ - vst3q_##suffix(ptr, v); \ -} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ - const v_##_Tpvec& c, const v_##_Tpvec& d, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec##x4_t v; \ - v.val[0] = a.val; \ - v.val[1] = b.val; \ - v.val[2] = c.val; \ - v.val[3] = d.val; \ - vst4q_##suffix(ptr, v); \ -} - -#define OPENCV_HAL_IMPL_NEON_INTERLEAVED_INT64(tp, suffix) \ -inline void v_load_deinterleave( const tp* ptr, v_##tp##x2& a, v_##tp##x2& b ) \ -{ \ - tp##x1_t a0 = vld1_##suffix(ptr); \ - tp##x1_t b0 = vld1_##suffix(ptr + 1); \ - tp##x1_t a1 = vld1_##suffix(ptr + 2); \ - tp##x1_t b1 = vld1_##suffix(ptr + 3); \ - a = v_##tp##x2(vcombine_##suffix(a0, a1)); \ - b = v_##tp##x2(vcombine_##suffix(b0, b1)); \ -} \ - \ -inline void v_load_deinterleave( const tp* ptr, v_##tp##x2& a, \ - v_##tp##x2& b, v_##tp##x2& c ) \ -{ \ - tp##x1_t a0 = vld1_##suffix(ptr); \ - tp##x1_t b0 = vld1_##suffix(ptr + 1); \ - tp##x1_t c0 = vld1_##suffix(ptr + 2); \ - tp##x1_t a1 = vld1_##suffix(ptr + 3); \ - tp##x1_t b1 = vld1_##suffix(ptr + 4); \ - tp##x1_t c1 = vld1_##suffix(ptr + 5); \ - a = v_##tp##x2(vcombine_##suffix(a0, a1)); \ - b = v_##tp##x2(vcombine_##suffix(b0, b1)); \ - c = v_##tp##x2(vcombine_##suffix(c0, c1)); \ -} \ - \ -inline void v_load_deinterleave( const tp* ptr, v_##tp##x2& a, v_##tp##x2& b, \ - v_##tp##x2& c, v_##tp##x2& d ) \ -{ \ - tp##x1_t a0 = vld1_##suffix(ptr); \ - tp##x1_t b0 = vld1_##suffix(ptr + 1); \ - tp##x1_t c0 = vld1_##suffix(ptr + 2); \ - tp##x1_t d0 = vld1_##suffix(ptr + 3); \ - tp##x1_t a1 = vld1_##suffix(ptr + 4); \ - tp##x1_t b1 = vld1_##suffix(ptr + 5); \ - tp##x1_t c1 = vld1_##suffix(ptr + 6); \ - tp##x1_t d1 = vld1_##suffix(ptr + 7); \ - a = v_##tp##x2(vcombine_##suffix(a0, a1)); \ - b = v_##tp##x2(vcombine_##suffix(b0, b1)); \ - c = v_##tp##x2(vcombine_##suffix(c0, c1)); \ - d = v_##tp##x2(vcombine_##suffix(d0, d1)); \ -} \ - \ -inline void v_store_interleave( tp* ptr, const v_##tp##x2& a, const v_##tp##x2& b, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - vst1_##suffix(ptr, vget_low_##suffix(a.val)); \ - vst1_##suffix(ptr + 1, vget_low_##suffix(b.val)); \ - vst1_##suffix(ptr + 2, vget_high_##suffix(a.val)); \ - vst1_##suffix(ptr + 3, vget_high_##suffix(b.val)); \ -} \ - \ -inline void v_store_interleave( tp* ptr, const v_##tp##x2& a, \ - const v_##tp##x2& b, const v_##tp##x2& c, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - vst1_##suffix(ptr, vget_low_##suffix(a.val)); \ - vst1_##suffix(ptr + 1, vget_low_##suffix(b.val)); \ - vst1_##suffix(ptr + 2, vget_low_##suffix(c.val)); \ - vst1_##suffix(ptr + 3, vget_high_##suffix(a.val)); \ - vst1_##suffix(ptr + 4, vget_high_##suffix(b.val)); \ - vst1_##suffix(ptr + 5, vget_high_##suffix(c.val)); \ -} \ - \ -inline void v_store_interleave( tp* ptr, const v_##tp##x2& a, const v_##tp##x2& b, \ - const v_##tp##x2& c, const v_##tp##x2& d, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - vst1_##suffix(ptr, vget_low_##suffix(a.val)); \ - vst1_##suffix(ptr + 1, vget_low_##suffix(b.val)); \ - vst1_##suffix(ptr + 2, vget_low_##suffix(c.val)); \ - vst1_##suffix(ptr + 3, vget_low_##suffix(d.val)); \ - vst1_##suffix(ptr + 4, vget_high_##suffix(a.val)); \ - vst1_##suffix(ptr + 5, vget_high_##suffix(b.val)); \ - vst1_##suffix(ptr + 6, vget_high_##suffix(c.val)); \ - vst1_##suffix(ptr + 7, vget_high_##suffix(d.val)); \ -} - -OPENCV_HAL_IMPL_NEON_INTERLEAVED(uint8x16, uchar, u8) -OPENCV_HAL_IMPL_NEON_INTERLEAVED(int8x16, schar, s8) -OPENCV_HAL_IMPL_NEON_INTERLEAVED(uint16x8, ushort, u16) -OPENCV_HAL_IMPL_NEON_INTERLEAVED(int16x8, short, s16) -OPENCV_HAL_IMPL_NEON_INTERLEAVED(uint32x4, unsigned, u32) -OPENCV_HAL_IMPL_NEON_INTERLEAVED(int32x4, int, s32) -OPENCV_HAL_IMPL_NEON_INTERLEAVED(float32x4, float, f32) -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_INTERLEAVED(float64x2, double, f64) -#endif - -OPENCV_HAL_IMPL_NEON_INTERLEAVED_INT64(int64, s64) -OPENCV_HAL_IMPL_NEON_INTERLEAVED_INT64(uint64, u64) - -inline v_float32x4 v_cvt_f32(const v_int32x4& a) -{ - return v_float32x4(vcvtq_f32_s32(a.val)); -} - -#if CV_SIMD128_64F -inline v_float32x4 v_cvt_f32(const v_float64x2& a) -{ - float32x2_t zero = vdup_n_f32(0.0f); - return v_float32x4(vcombine_f32(vcvt_f32_f64(a.val), zero)); -} - -inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) -{ - return v_float32x4(vcombine_f32(vcvt_f32_f64(a.val), vcvt_f32_f64(b.val))); -} - -inline v_float64x2 v_cvt_f64(const v_int32x4& a) -{ - return v_float64x2(vcvt_f64_f32(vcvt_f32_s32(vget_low_s32(a.val)))); -} - -inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) -{ - return v_float64x2(vcvt_f64_f32(vcvt_f32_s32(vget_high_s32(a.val)))); -} - -inline v_float64x2 v_cvt_f64(const v_float32x4& a) -{ - return v_float64x2(vcvt_f64_f32(vget_low_f32(a.val))); -} - -inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) -{ - return v_float64x2(vcvt_f64_f32(vget_high_f32(a.val))); -} - -inline v_float64x2 v_cvt_f64(const v_int64x2& a) -{ return v_float64x2(vcvtq_f64_s64(a.val)); } - -#endif - -////////////// Lookup table access //////////////////// - -inline v_int8x16 v_lut(const schar* tab, const int* idx) -{ - schar CV_DECL_ALIGNED(32) elems[16] = - { - tab[idx[ 0]], - tab[idx[ 1]], - tab[idx[ 2]], - tab[idx[ 3]], - tab[idx[ 4]], - tab[idx[ 5]], - tab[idx[ 6]], - tab[idx[ 7]], - tab[idx[ 8]], - tab[idx[ 9]], - tab[idx[10]], - tab[idx[11]], - tab[idx[12]], - tab[idx[13]], - tab[idx[14]], - tab[idx[15]] - }; - return v_int8x16(vld1q_s8(elems)); -} -inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx) -{ - schar CV_DECL_ALIGNED(32) elems[16] = - { - tab[idx[0]], - tab[idx[0] + 1], - tab[idx[1]], - tab[idx[1] + 1], - tab[idx[2]], - tab[idx[2] + 1], - tab[idx[3]], - tab[idx[3] + 1], - tab[idx[4]], - tab[idx[4] + 1], - tab[idx[5]], - tab[idx[5] + 1], - tab[idx[6]], - tab[idx[6] + 1], - tab[idx[7]], - tab[idx[7] + 1] - }; - return v_int8x16(vld1q_s8(elems)); -} -inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) -{ - schar CV_DECL_ALIGNED(32) elems[16] = - { - tab[idx[0]], - tab[idx[0] + 1], - tab[idx[0] + 2], - tab[idx[0] + 3], - tab[idx[1]], - tab[idx[1] + 1], - tab[idx[1] + 2], - tab[idx[1] + 3], - tab[idx[2]], - tab[idx[2] + 1], - tab[idx[2] + 2], - tab[idx[2] + 3], - tab[idx[3]], - tab[idx[3] + 1], - tab[idx[3] + 2], - tab[idx[3] + 3] - }; - return v_int8x16(vld1q_s8(elems)); -} -inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((schar*)tab, idx)); } -inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((schar*)tab, idx)); } -inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((schar*)tab, idx)); } - -inline v_int16x8 v_lut(const short* tab, const int* idx) -{ - short CV_DECL_ALIGNED(32) elems[8] = - { - tab[idx[0]], - tab[idx[1]], - tab[idx[2]], - tab[idx[3]], - tab[idx[4]], - tab[idx[5]], - tab[idx[6]], - tab[idx[7]] - }; - return v_int16x8(vld1q_s16(elems)); -} -inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) -{ - short CV_DECL_ALIGNED(32) elems[8] = - { - tab[idx[0]], - tab[idx[0] + 1], - tab[idx[1]], - tab[idx[1] + 1], - tab[idx[2]], - tab[idx[2] + 1], - tab[idx[3]], - tab[idx[3] + 1] - }; - return v_int16x8(vld1q_s16(elems)); -} -inline v_int16x8 v_lut_quads(const short* tab, const int* idx) -{ - return v_int16x8(vcombine_s16(vld1_s16(tab + idx[0]), vld1_s16(tab + idx[1]))); -} -inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((short*)tab, idx)); } -inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((short*)tab, idx)); } -inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((short*)tab, idx)); } - -inline v_int32x4 v_lut(const int* tab, const int* idx) -{ - int CV_DECL_ALIGNED(32) elems[4] = - { - tab[idx[0]], - tab[idx[1]], - tab[idx[2]], - tab[idx[3]] - }; - return v_int32x4(vld1q_s32(elems)); -} -inline v_int32x4 v_lut_pairs(const int* tab, const int* idx) -{ - return v_int32x4(vcombine_s32(vld1_s32(tab + idx[0]), vld1_s32(tab + idx[1]))); -} -inline v_int32x4 v_lut_quads(const int* tab, const int* idx) -{ - return v_int32x4(vld1q_s32(tab + idx[0])); -} -inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((int*)tab, idx)); } -inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((int*)tab, idx)); } -inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((int*)tab, idx)); } - -inline v_int64x2 v_lut(const int64_t* tab, const int* idx) -{ - return v_int64x2(vcombine_s64(vcreate_s64(tab[idx[0]]), vcreate_s64(tab[idx[1]]))); -} -inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) -{ - return v_int64x2(vld1q_s64(tab + idx[0])); -} -inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } -inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } - -inline v_float32x4 v_lut(const float* tab, const int* idx) -{ - float CV_DECL_ALIGNED(32) elems[4] = - { - tab[idx[0]], - tab[idx[1]], - tab[idx[2]], - tab[idx[3]] - }; - return v_float32x4(vld1q_f32(elems)); -} -inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) -{ - typedef uint64 CV_DECL_ALIGNED(1) unaligned_uint64; - - uint64 CV_DECL_ALIGNED(32) elems[2] = - { - *(unaligned_uint64*)(tab + idx[0]), - *(unaligned_uint64*)(tab + idx[1]) - }; - return v_float32x4(vreinterpretq_f32_u64(vld1q_u64(elems))); -} -inline v_float32x4 v_lut_quads(const float* tab, const int* idx) -{ - return v_float32x4(vld1q_f32(tab + idx[0])); -} - -inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) -{ - int CV_DECL_ALIGNED(32) elems[4] = - { - tab[vgetq_lane_s32(idxvec.val, 0)], - tab[vgetq_lane_s32(idxvec.val, 1)], - tab[vgetq_lane_s32(idxvec.val, 2)], - tab[vgetq_lane_s32(idxvec.val, 3)] - }; - return v_int32x4(vld1q_s32(elems)); -} - -inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) -{ - unsigned CV_DECL_ALIGNED(32) elems[4] = - { - tab[vgetq_lane_s32(idxvec.val, 0)], - tab[vgetq_lane_s32(idxvec.val, 1)], - tab[vgetq_lane_s32(idxvec.val, 2)], - tab[vgetq_lane_s32(idxvec.val, 3)] - }; - return v_uint32x4(vld1q_u32(elems)); -} - -inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) -{ - float CV_DECL_ALIGNED(32) elems[4] = - { - tab[vgetq_lane_s32(idxvec.val, 0)], - tab[vgetq_lane_s32(idxvec.val, 1)], - tab[vgetq_lane_s32(idxvec.val, 2)], - tab[vgetq_lane_s32(idxvec.val, 3)] - }; - return v_float32x4(vld1q_f32(elems)); -} - -inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) -{ - /*int CV_DECL_ALIGNED(32) idx[4]; - v_store(idx, idxvec); - - float32x4_t xy02 = vcombine_f32(vld1_f32(tab + idx[0]), vld1_f32(tab + idx[2])); - float32x4_t xy13 = vcombine_f32(vld1_f32(tab + idx[1]), vld1_f32(tab + idx[3])); - - float32x4x2_t xxyy = vuzpq_f32(xy02, xy13); - x = v_float32x4(xxyy.val[0]); - y = v_float32x4(xxyy.val[1]);*/ - int CV_DECL_ALIGNED(32) idx[4]; - v_store_aligned(idx, idxvec); - - x = v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); - y = v_float32x4(tab[idx[0]+1], tab[idx[1]+1], tab[idx[2]+1], tab[idx[3]+1]); -} - -inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) -{ - return v_int8x16(vcombine_s8(vtbl1_s8(vget_low_s8(vec.val), vcreate_s8(0x0705060403010200)), vtbl1_s8(vget_high_s8(vec.val), vcreate_s8(0x0705060403010200)))); -} -inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } -inline v_int8x16 v_interleave_quads(const v_int8x16& vec) -{ - return v_int8x16(vcombine_s8(vtbl1_s8(vget_low_s8(vec.val), vcreate_s8(0x0703060205010400)), vtbl1_s8(vget_high_s8(vec.val), vcreate_s8(0x0703060205010400)))); -} -inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) -{ - return v_int16x8(vreinterpretq_s16_s8(vcombine_s8(vtbl1_s8(vget_low_s8(vreinterpretq_s8_s16(vec.val)), vcreate_s8(0x0706030205040100)), vtbl1_s8(vget_high_s8(vreinterpretq_s8_s16(vec.val)), vcreate_s8(0x0706030205040100))))); -} -inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } -inline v_int16x8 v_interleave_quads(const v_int16x8& vec) -{ - int16x4x2_t res = vzip_s16(vget_low_s16(vec.val), vget_high_s16(vec.val)); - return v_int16x8(vcombine_s16(res.val[0], res.val[1])); -} -inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) -{ - int32x2x2_t res = vzip_s32(vget_low_s32(vec.val), vget_high_s32(vec.val)); - return v_int32x4(vcombine_s32(res.val[0], res.val[1])); -} -inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } -inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } - -inline v_int8x16 v_pack_triplets(const v_int8x16& vec) -{ - return v_int8x16(vextq_s8(vcombine_s8(vtbl1_s8(vget_low_s8(vec.val), vcreate_s8(0x0605040201000000)), vtbl1_s8(vget_high_s8(vec.val), vcreate_s8(0x0807060504020100))), vdupq_n_s8(0), 2)); -} -inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_pack_triplets(const v_int16x8& vec) -{ - return v_int16x8(vreinterpretq_s16_s8(vextq_s8(vcombine_s8(vtbl1_s8(vget_low_s8(vreinterpretq_s8_s16(vec.val)), vcreate_s8(0x0504030201000000)), vget_high_s8(vreinterpretq_s8_s16(vec.val))), vdupq_n_s8(0), 2))); -} -inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } -inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } -inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } - -#if CV_SIMD128_64F -inline v_float64x2 v_lut(const double* tab, const int* idx) -{ - double CV_DECL_ALIGNED(32) elems[2] = - { - tab[idx[0]], - tab[idx[1]] - }; - return v_float64x2(vld1q_f64(elems)); -} - -inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) -{ - return v_float64x2(vld1q_f64(tab + idx[0])); -} - -inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) -{ - double CV_DECL_ALIGNED(32) elems[2] = - { - tab[vgetq_lane_s32(idxvec.val, 0)], - tab[vgetq_lane_s32(idxvec.val, 1)], - }; - return v_float64x2(vld1q_f64(elems)); -} - -inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) -{ - int CV_DECL_ALIGNED(32) idx[4]; - v_store_aligned(idx, idxvec); - - x = v_float64x2(tab[idx[0]], tab[idx[1]]); - y = v_float64x2(tab[idx[0]+1], tab[idx[1]+1]); -} -#endif - -////// FP16 support /////// -#if CV_FP16 -inline v_float32x4 v_load_expand(const hfloat* ptr) -{ - float16x4_t v = - #ifndef vld1_f16 // APPLE compiler defines vld1_f16 as macro - (float16x4_t)vld1_s16((const short*)ptr); - #else - vld1_f16((const __fp16*)ptr); - #endif - return v_float32x4(vcvt_f32_f16(v)); -} - -inline void v_pack_store(hfloat* ptr, const v_float32x4& v) -{ - float16x4_t hv = vcvt_f16_f32(v.val); - - #ifndef vst1_f16 // APPLE compiler defines vst1_f16 as macro - vst1_s16((short*)ptr, (int16x4_t)hv); - #else - vst1_f16((__fp16*)ptr, hv); - #endif -} -#else -inline v_float32x4 v_load_expand(const hfloat* ptr) -{ - const int N = 4; - float buf[N]; - for( int i = 0; i < N; i++ ) buf[i] = (float)ptr[i]; - return v_load(buf); -} - -inline void v_pack_store(hfloat* ptr, const v_float32x4& v) -{ - const int N = 4; - float buf[N]; - v_store(buf, v); - for( int i = 0; i < N; i++ ) ptr[i] = hfloat(buf[i]); -} -#endif - -inline void v_cleanup() {} - -#include "intrin_math.hpp" -#if defined(CV_SIMD_FP16) && CV_SIMD_FP16 -inline v_float16x8 v_exp(const v_float16x8& x) { return v_exp_default_16f(x); } -inline v_float16x8 v_log(const v_float16x8& x) { return v_log_default_16f(x); } -inline void v_sincos(const v_float16x8& x, v_float16x8& s, v_float16x8& c) { v_sincos_default_16f(x, s, c); } -inline v_float16x8 v_sin(const v_float16x8& x) { return v_sin_default_16f(x); } -inline v_float16x8 v_cos(const v_float16x8& x) { return v_cos_default_16f(x); } -#endif -inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } -inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } -inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } -inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } -inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } -inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } -#if CV_SIMD128_64F -inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } -inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } -inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } -inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } -inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } -#endif - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_HAL_INTRIN_NEON_HPP +#define OPENCV_HAL_INTRIN_NEON_HPP + +#include +#include "opencv2/core/utility.hpp" + +namespace cv +{ + +//! @cond IGNORED + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +#define CV_SIMD128 1 +#if defined(__aarch64__) || defined(_M_ARM64) +#define CV_SIMD128_64F 1 +#else +#define CV_SIMD128_64F 0 +#endif + +// The following macro checks if the code is being compiled for the +// AArch64 execution state of Armv8, to enable the 128-bit +// intrinsics. The macro `__ARM_64BIT_STATE` is the one recommended by +// the Arm C Language Extension (ACLE) specifications [1] to check the +// availability of 128-bit intrinsics, and it is supporrted by clang +// and gcc. The macro `_M_ARM64` is the equivalent one for Microsoft +// Visual Studio [2] . +// +// [1] https://developer.arm.com/documentation/101028/0012/13--Advanced-SIMD--Neon--intrinsics +// [2] https://docs.microsoft.com/en-us/cpp/preprocessor/predefined-macros +#if defined(__ARM_64BIT_STATE) || defined(_M_ARM64) +#define CV_NEON_AARCH64 1 +#else +#define CV_NEON_AARCH64 0 +#endif + + +//////////// Utils //////////// + +#if CV_SIMD128_64F +#define OPENCV_HAL_IMPL_NEON_UNZIP(_Tpv, _Tpvx2, suffix) \ + inline void _v128_unzip(const _Tpv& a, const _Tpv& b, _Tpv& c, _Tpv& d) \ + { c = vuzp1q_##suffix(a, b); d = vuzp2q_##suffix(a, b); } +#define OPENCV_HAL_IMPL_NEON_UNZIP_L(_Tpv, _Tpvx2, suffix) \ + inline void _v128_unzip(const _Tpv&a, const _Tpv&b, _Tpv& c, _Tpv& d) \ + { c = vuzp1_##suffix(a, b); d = vuzp2_##suffix(a, b); } +#else +#define OPENCV_HAL_IMPL_NEON_UNZIP(_Tpv, _Tpvx2, suffix) \ + inline void _v128_unzip(const _Tpv& a, const _Tpv& b, _Tpv& c, _Tpv& d) \ + { _Tpvx2 ab = vuzpq_##suffix(a, b); c = ab.val[0]; d = ab.val[1]; } +#define OPENCV_HAL_IMPL_NEON_UNZIP_L(_Tpv, _Tpvx2, suffix) \ + inline void _v128_unzip(const _Tpv& a, const _Tpv& b, _Tpv& c, _Tpv& d) \ + { _Tpvx2 ab = vuzp_##suffix(a, b); c = ab.val[0]; d = ab.val[1]; } +#endif + +#if CV_SIMD128_64F +#define OPENCV_HAL_IMPL_NEON_REINTERPRET(_Tpv, suffix) \ + template static inline \ + _Tpv vreinterpretq_##suffix##_f64(T a) { return (_Tpv) a; } \ + template static inline \ + float64x2_t vreinterpretq_f64_##suffix(T a) { return (float64x2_t) a; } +#else +#define OPENCV_HAL_IMPL_NEON_REINTERPRET(_Tpv, suffix) +#endif + +#define OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(_Tpv, _Tpvl, suffix) \ + OPENCV_HAL_IMPL_NEON_UNZIP(_Tpv##_t, _Tpv##x2_t, suffix) \ + OPENCV_HAL_IMPL_NEON_UNZIP_L(_Tpvl##_t, _Tpvl##x2_t, suffix) \ + OPENCV_HAL_IMPL_NEON_REINTERPRET(_Tpv##_t, suffix) + +#define OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX_I64(_Tpv, _Tpvl, suffix) \ + OPENCV_HAL_IMPL_NEON_REINTERPRET(_Tpv##_t, suffix) + +#define OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX_F64(_Tpv, _Tpvl, suffix) \ + OPENCV_HAL_IMPL_NEON_UNZIP(_Tpv##_t, _Tpv##x2_t, suffix) + +OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(uint8x16, uint8x8, u8) +OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(int8x16, int8x8, s8) +OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(uint16x8, uint16x4, u16) +OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(int16x8, int16x4, s16) +OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(uint32x4, uint32x2, u32) +OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(int32x4, int32x2, s32) +OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(float32x4, float32x2, f32) +OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX_I64(uint64x2, uint64x1, u64) +OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX_I64(int64x2, int64x1, s64) +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX_F64(float64x2, float64x1,f64) +#endif + +//////////// Compatibility layer //////////// +template struct VTraits { + static inline int vlanes() { return T::nlanes; } + enum { max_nlanes = T::nlanes, nlanes = T::nlanes }; + using lane_type = typename T::lane_type; +}; + +template +inline typename VTraits::lane_type v_get0(const T& v) \ +{ \ + return v.get0(); \ +} +//////////// Types //////////// + +struct v_uint8x16 +{ + v_uint8x16() {} + explicit v_uint8x16(uint8x16_t v) : val(v) {} + v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, + uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) + { + uchar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; + val = vld1q_u8(v); + } + uint8x16_t val; + +private: + friend struct VTraits; + enum { nlanes = 16 }; + typedef uchar lane_type; + + friend typename VTraits::lane_type v_get0(const v_uint8x16& v); + uchar get0() const + { + return vgetq_lane_u8(val, 0); + } +}; + +struct v_int8x16 +{ + v_int8x16() {} + explicit v_int8x16(int8x16_t v) : val(v) {} + v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, + schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) + { + schar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; + val = vld1q_s8(v); + } + int8x16_t val; + +private: + friend struct VTraits; + enum { nlanes = 16 }; + typedef schar lane_type; + + friend typename VTraits::lane_type v_get0(const v_int8x16& v); + schar get0() const + { + return vgetq_lane_s8(val, 0); + } +}; + +struct v_uint16x8 +{ + v_uint16x8() {} + explicit v_uint16x8(uint16x8_t v) : val(v) {} + v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) + { + ushort v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; + val = vld1q_u16(v); + } + uint16x8_t val; + +private: + friend struct VTraits; + enum { nlanes = 8 }; + typedef ushort lane_type; + + friend typename VTraits::lane_type v_get0(const v_uint16x8& v); + ushort get0() const + { + return vgetq_lane_u16(val, 0); + } +}; + +struct v_int16x8 +{ + v_int16x8() {} + explicit v_int16x8(int16x8_t v) : val(v) {} + v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) + { + short v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; + val = vld1q_s16(v); + } + int16x8_t val; + +private: + friend struct VTraits; + enum { nlanes = 8 }; + typedef short lane_type; + + friend typename VTraits::lane_type v_get0(const v_int16x8& v); + short get0() const + { + return vgetq_lane_s16(val, 0); + } +}; + +struct v_uint32x4 +{ + v_uint32x4() {} + explicit v_uint32x4(uint32x4_t v) : val(v) {} + v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) + { + unsigned v[] = {v0, v1, v2, v3}; + val = vld1q_u32(v); + } + uint32x4_t val; + +private: + friend struct VTraits; + enum { nlanes = 4 }; + typedef unsigned lane_type; + + friend typename VTraits::lane_type v_get0(const v_uint32x4& v); + unsigned get0() const + { + return vgetq_lane_u32(val, 0); + } +}; + +struct v_int32x4 +{ + v_int32x4() {} + explicit v_int32x4(int32x4_t v) : val(v) {} + v_int32x4(int v0, int v1, int v2, int v3) + { + int v[] = {v0, v1, v2, v3}; + val = vld1q_s32(v); + } + int32x4_t val; + +private: + friend struct VTraits; + enum { nlanes = 4 }; + typedef int lane_type; + + friend typename VTraits::lane_type v_get0(const v_int32x4& v); + int get0() const + { + return vgetq_lane_s32(val, 0); + } +}; + +struct v_float32x4 +{ + v_float32x4() {} + explicit v_float32x4(float32x4_t v) : val(v) {} + v_float32x4(float v0, float v1, float v2, float v3) + { + float v[] = {v0, v1, v2, v3}; + val = vld1q_f32(v); + } + float32x4_t val; + +private: + friend struct VTraits; + enum { nlanes = 4 }; + typedef float lane_type; + + friend typename VTraits::lane_type v_get0(const v_float32x4& v); + float get0() const + { + return vgetq_lane_f32(val, 0); + } +}; + +struct v_uint64x2 +{ + v_uint64x2() {} + explicit v_uint64x2(uint64x2_t v) : val(v) {} + v_uint64x2(uint64 v0, uint64 v1) + { + uint64 v[] = {v0, v1}; + val = vld1q_u64(v); + } + uint64x2_t val; +private: + friend struct VTraits; + enum { nlanes = 2 }; + typedef uint64 lane_type; + + friend typename VTraits::lane_type v_get0(const v_uint64x2& v); + uint64 get0() const + { + return vgetq_lane_u64(val, 0); + } +}; + +struct v_int64x2 +{ + v_int64x2() {} + explicit v_int64x2(int64x2_t v) : val(v) {} + v_int64x2(int64 v0, int64 v1) + { + int64 v[] = {v0, v1}; + val = vld1q_s64(v); + } + int64x2_t val; + +private: + friend struct VTraits; + enum { nlanes = 2 }; + typedef int64 lane_type; + + friend typename VTraits::lane_type v_get0(const v_int64x2& v); + int64 get0() const + { + return vgetq_lane_s64(val, 0); + } +}; + +#if CV_SIMD128_64F +struct v_float64x2 +{ + v_float64x2() {} + explicit v_float64x2(float64x2_t v) : val(v) {} + v_float64x2(double v0, double v1) + { + double v[] = {v0, v1}; + val = vld1q_f64(v); + } + + float64x2_t val; +private: + friend struct VTraits; + enum { nlanes = 2 }; + typedef double lane_type; + + friend typename VTraits::lane_type v_get0(const v_float64x2& v); + double get0() const + { + return vgetq_lane_f64(val, 0); + } +}; +#endif + +#define OPENCV_HAL_IMPL_NEON_INIT(_Tpv, _Tp, suffix) \ +inline v_##_Tpv v_setzero_##suffix() { return v_##_Tpv(vdupq_n_##suffix((_Tp)0)); } \ +inline v_##_Tpv v_setall_##suffix(_Tp v) { return v_##_Tpv(vdupq_n_##suffix(v)); } \ +template <> inline v_##_Tpv v_setzero_() { return v_setzero_##suffix(); } \ +template <> inline v_##_Tpv v_setall_(_Tp v) { return v_setall_##suffix(v); } \ +inline _Tpv##_t vreinterpretq_##suffix##_##suffix(_Tpv##_t v) { return v; } \ +inline v_uint8x16 v_reinterpret_as_u8(const v_##_Tpv& v) { return v_uint8x16(vreinterpretq_u8_##suffix(v.val)); } \ +inline v_int8x16 v_reinterpret_as_s8(const v_##_Tpv& v) { return v_int8x16(vreinterpretq_s8_##suffix(v.val)); } \ +inline v_uint16x8 v_reinterpret_as_u16(const v_##_Tpv& v) { return v_uint16x8(vreinterpretq_u16_##suffix(v.val)); } \ +inline v_int16x8 v_reinterpret_as_s16(const v_##_Tpv& v) { return v_int16x8(vreinterpretq_s16_##suffix(v.val)); } \ +inline v_uint32x4 v_reinterpret_as_u32(const v_##_Tpv& v) { return v_uint32x4(vreinterpretq_u32_##suffix(v.val)); } \ +inline v_int32x4 v_reinterpret_as_s32(const v_##_Tpv& v) { return v_int32x4(vreinterpretq_s32_##suffix(v.val)); } \ +inline v_uint64x2 v_reinterpret_as_u64(const v_##_Tpv& v) { return v_uint64x2(vreinterpretq_u64_##suffix(v.val)); } \ +inline v_int64x2 v_reinterpret_as_s64(const v_##_Tpv& v) { return v_int64x2(vreinterpretq_s64_##suffix(v.val)); } \ +inline v_float32x4 v_reinterpret_as_f32(const v_##_Tpv& v) { return v_float32x4(vreinterpretq_f32_##suffix(v.val)); } + +OPENCV_HAL_IMPL_NEON_INIT(uint8x16, uchar, u8) +OPENCV_HAL_IMPL_NEON_INIT(int8x16, schar, s8) +OPENCV_HAL_IMPL_NEON_INIT(uint16x8, ushort, u16) +OPENCV_HAL_IMPL_NEON_INIT(int16x8, short, s16) +OPENCV_HAL_IMPL_NEON_INIT(uint32x4, unsigned, u32) +OPENCV_HAL_IMPL_NEON_INIT(int32x4, int, s32) +OPENCV_HAL_IMPL_NEON_INIT(uint64x2, uint64, u64) +OPENCV_HAL_IMPL_NEON_INIT(int64x2, int64, s64) +OPENCV_HAL_IMPL_NEON_INIT(float32x4, float, f32) +#if CV_SIMD128_64F +#define OPENCV_HAL_IMPL_NEON_INIT_64(_Tpv, suffix) \ +inline v_float64x2 v_reinterpret_as_f64(const v_##_Tpv& v) { return v_float64x2(vreinterpretq_f64_##suffix(v.val)); } +OPENCV_HAL_IMPL_NEON_INIT(float64x2, double, f64) +OPENCV_HAL_IMPL_NEON_INIT_64(uint8x16, u8) +OPENCV_HAL_IMPL_NEON_INIT_64(int8x16, s8) +OPENCV_HAL_IMPL_NEON_INIT_64(uint16x8, u16) +OPENCV_HAL_IMPL_NEON_INIT_64(int16x8, s16) +OPENCV_HAL_IMPL_NEON_INIT_64(uint32x4, u32) +OPENCV_HAL_IMPL_NEON_INIT_64(int32x4, s32) +OPENCV_HAL_IMPL_NEON_INIT_64(uint64x2, u64) +OPENCV_HAL_IMPL_NEON_INIT_64(int64x2, s64) +OPENCV_HAL_IMPL_NEON_INIT_64(float32x4, f32) +OPENCV_HAL_IMPL_NEON_INIT_64(float64x2, f64) +#endif + +#define OPENCV_HAL_IMPL_NEON_PACK(_Tpvec, _Tp, hreg, suffix, _Tpwvec, pack, mov, rshr) \ +inline _Tpvec v_##pack(const _Tpwvec& a, const _Tpwvec& b) \ +{ \ + hreg a1 = mov(a.val), b1 = mov(b.val); \ + return _Tpvec(vcombine_##suffix(a1, b1)); \ +} \ +inline void v_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ +{ \ + hreg a1 = mov(a.val); \ + vst1_##suffix(ptr, a1); \ +} \ +template inline \ +_Tpvec v_rshr_##pack(const _Tpwvec& a, const _Tpwvec& b) \ +{ \ + hreg a1 = rshr(a.val, n); \ + hreg b1 = rshr(b.val, n); \ + return _Tpvec(vcombine_##suffix(a1, b1)); \ +} \ +template inline \ +void v_rshr_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ +{ \ + hreg a1 = rshr(a.val, n); \ + vst1_##suffix(ptr, a1); \ +} + +OPENCV_HAL_IMPL_NEON_PACK(v_uint8x16, uchar, uint8x8_t, u8, v_uint16x8, pack, vqmovn_u16, vqrshrn_n_u16) +OPENCV_HAL_IMPL_NEON_PACK(v_int8x16, schar, int8x8_t, s8, v_int16x8, pack, vqmovn_s16, vqrshrn_n_s16) +OPENCV_HAL_IMPL_NEON_PACK(v_uint16x8, ushort, uint16x4_t, u16, v_uint32x4, pack, vqmovn_u32, vqrshrn_n_u32) +OPENCV_HAL_IMPL_NEON_PACK(v_int16x8, short, int16x4_t, s16, v_int32x4, pack, vqmovn_s32, vqrshrn_n_s32) +OPENCV_HAL_IMPL_NEON_PACK(v_uint32x4, unsigned, uint32x2_t, u32, v_uint64x2, pack, vmovn_u64, vrshrn_n_u64) +OPENCV_HAL_IMPL_NEON_PACK(v_int32x4, int, int32x2_t, s32, v_int64x2, pack, vmovn_s64, vrshrn_n_s64) + +OPENCV_HAL_IMPL_NEON_PACK(v_uint8x16, uchar, uint8x8_t, u8, v_int16x8, pack_u, vqmovun_s16, vqrshrun_n_s16) +OPENCV_HAL_IMPL_NEON_PACK(v_uint16x8, ushort, uint16x4_t, u16, v_int32x4, pack_u, vqmovun_s32, vqrshrun_n_s32) + +// pack boolean +inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) +{ + uint8x16_t ab = vcombine_u8(vmovn_u16(a.val), vmovn_u16(b.val)); + return v_uint8x16(ab); +} + +inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, + const v_uint32x4& c, const v_uint32x4& d) +{ + uint16x8_t nab = vcombine_u16(vmovn_u32(a.val), vmovn_u32(b.val)); + uint16x8_t ncd = vcombine_u16(vmovn_u32(c.val), vmovn_u32(d.val)); + return v_uint8x16(vcombine_u8(vmovn_u16(nab), vmovn_u16(ncd))); +} + +inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, + const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, + const v_uint64x2& g, const v_uint64x2& h) +{ + uint32x4_t ab = vcombine_u32(vmovn_u64(a.val), vmovn_u64(b.val)); + uint32x4_t cd = vcombine_u32(vmovn_u64(c.val), vmovn_u64(d.val)); + uint32x4_t ef = vcombine_u32(vmovn_u64(e.val), vmovn_u64(f.val)); + uint32x4_t gh = vcombine_u32(vmovn_u64(g.val), vmovn_u64(h.val)); + + uint16x8_t abcd = vcombine_u16(vmovn_u32(ab), vmovn_u32(cd)); + uint16x8_t efgh = vcombine_u16(vmovn_u32(ef), vmovn_u32(gh)); + return v_uint8x16(vcombine_u8(vmovn_u16(abcd), vmovn_u16(efgh))); +} + +inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, + const v_float32x4& m3) +{ + float32x2_t vl = vget_low_f32(v.val), vh = vget_high_f32(v.val); + float32x4_t res = vmulq_lane_f32(m0.val, vl, 0); + res = vmlaq_lane_f32(res, m1.val, vl, 1); + res = vmlaq_lane_f32(res, m2.val, vh, 0); + res = vmlaq_lane_f32(res, m3.val, vh, 1); + return v_float32x4(res); +} + +inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, + const v_float32x4& a) +{ + float32x2_t vl = vget_low_f32(v.val), vh = vget_high_f32(v.val); + float32x4_t res = vmulq_lane_f32(m0.val, vl, 0); + res = vmlaq_lane_f32(res, m1.val, vl, 1); + res = vmlaq_lane_f32(res, m2.val, vh, 0); + res = vaddq_f32(res, a.val); + return v_float32x4(res); +} + +#define OPENCV_HAL_IMPL_NEON_BIN_OP(bin_op, _Tpvec, intrin) \ +inline _Tpvec bin_op (const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(intrin(a.val, b.val)); \ +} + +OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_uint8x16, vqaddq_u8) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_uint8x16, vqsubq_u8) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_int8x16, vqaddq_s8) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_int8x16, vqsubq_s8) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_uint16x8, vqaddq_u16) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_uint16x8, vqsubq_u16) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_int16x8, vqaddq_s16) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_int16x8, vqsubq_s16) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_int32x4, vaddq_s32) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_int32x4, vsubq_s32) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_mul, v_int32x4, vmulq_s32) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_uint32x4, vaddq_u32) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_uint32x4, vsubq_u32) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_mul, v_uint32x4, vmulq_u32) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_float32x4, vaddq_f32) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_float32x4, vsubq_f32) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_mul, v_float32x4, vmulq_f32) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_int64x2, vaddq_s64) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_int64x2, vsubq_s64) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_uint64x2, vaddq_u64) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_uint64x2, vsubq_u64) +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_BIN_OP(v_div, v_float32x4, vdivq_f32) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_float64x2, vaddq_f64) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_float64x2, vsubq_f64) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_mul, v_float64x2, vmulq_f64) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_div, v_float64x2, vdivq_f64) +#else +inline v_float32x4 v_div (const v_float32x4& a, const v_float32x4& b) +{ + float32x4_t reciprocal = vrecpeq_f32(b.val); + reciprocal = vmulq_f32(vrecpsq_f32(b.val, reciprocal), reciprocal); + reciprocal = vmulq_f32(vrecpsq_f32(b.val, reciprocal), reciprocal); + return v_float32x4(vmulq_f32(a.val, reciprocal)); +} +#endif + +// saturating multiply 8-bit, 16-bit +#define OPENCV_HAL_IMPL_NEON_MUL_SAT(_Tpvec, _Tpwvec) \ + inline _Tpvec v_mul (const _Tpvec& a, const _Tpvec& b) \ + { \ + _Tpwvec c, d; \ + v_mul_expand(a, b, c, d); \ + return v_pack(c, d); \ + } + +OPENCV_HAL_IMPL_NEON_MUL_SAT(v_int8x16, v_int16x8) +OPENCV_HAL_IMPL_NEON_MUL_SAT(v_uint8x16, v_uint16x8) +OPENCV_HAL_IMPL_NEON_MUL_SAT(v_int16x8, v_int32x4) +OPENCV_HAL_IMPL_NEON_MUL_SAT(v_uint16x8, v_uint32x4) + +// Multiply and expand +inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b, + v_int16x8& c, v_int16x8& d) +{ + c.val = vmull_s8(vget_low_s8(a.val), vget_low_s8(b.val)); +#if CV_NEON_AARCH64 + d.val = vmull_high_s8(a.val, b.val); +#else // #if CV_NEON_AARCH64 + d.val = vmull_s8(vget_high_s8(a.val), vget_high_s8(b.val)); +#endif // #if CV_NEON_AARCH64 +} + +inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b, + v_uint16x8& c, v_uint16x8& d) +{ + c.val = vmull_u8(vget_low_u8(a.val), vget_low_u8(b.val)); +#if CV_NEON_AARCH64 + d.val = vmull_high_u8(a.val, b.val); +#else // #if CV_NEON_AARCH64 + d.val = vmull_u8(vget_high_u8(a.val), vget_high_u8(b.val)); +#endif // #if CV_NEON_AARCH64 +} + +inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, + v_int32x4& c, v_int32x4& d) +{ + c.val = vmull_s16(vget_low_s16(a.val), vget_low_s16(b.val)); +#if CV_NEON_AARCH64 + d.val = vmull_high_s16(a.val, b.val); +#else // #if CV_NEON_AARCH64 + d.val = vmull_s16(vget_high_s16(a.val), vget_high_s16(b.val)); +#endif // #if CV_NEON_AARCH64 +} + +inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, + v_uint32x4& c, v_uint32x4& d) +{ + c.val = vmull_u16(vget_low_u16(a.val), vget_low_u16(b.val)); +#if CV_NEON_AARCH64 + d.val = vmull_high_u16(a.val, b.val); +#else // #if CV_NEON_AARCH64 + d.val = vmull_u16(vget_high_u16(a.val), vget_high_u16(b.val)); +#endif // #if CV_NEON_AARCH64 +} + +inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, + v_uint64x2& c, v_uint64x2& d) +{ + c.val = vmull_u32(vget_low_u32(a.val), vget_low_u32(b.val)); +#if CV_NEON_AARCH64 + d.val = vmull_high_u32(a.val, b.val); +#else // #if CV_NEON_AARCH64 + d.val = vmull_u32(vget_high_u32(a.val), vget_high_u32(b.val)); +#endif // #if CV_NEON_AARCH64 +} + +inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) +{ +#if CV_NEON_AARCH64 + int32x4_t c = vmull_high_s16(a.val, b.val); +#else // #if CV_NEON_AARCH64 + int32x4_t c = vmull_s16(vget_high_s16(a.val), vget_high_s16(b.val)); +#endif // #if CV_NEON_AARCH64 + return v_int16x8(vcombine_s16( + vshrn_n_s32(vmull_s16( vget_low_s16(a.val), vget_low_s16(b.val)), 16), + vshrn_n_s32(c, 16) + )); +} +inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) +{ +#if CV_NEON_AARCH64 + uint32x4_t c = vmull_high_u16(a.val, b.val); +#else // #if CV_NEON_AARCH64 + uint32x4_t c = vmull_u16(vget_high_u16(a.val), vget_high_u16(b.val)); +#endif // #if CV_NEON_AARCH64 + return v_uint16x8(vcombine_u16( + vshrn_n_u32(vmull_u16( vget_low_u16(a.val), vget_low_u16(b.val)), 16), + vshrn_n_u32(c, 16) + )); +} + +//////// Dot Product //////// + +// 16 >> 32 +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) +{ + int16x8_t uzp1, uzp2; + _v128_unzip(a.val, b.val, uzp1, uzp2); + int16x4_t a0 = vget_low_s16(uzp1); + int16x4_t b0 = vget_high_s16(uzp1); + int16x4_t a1 = vget_low_s16(uzp2); + int16x4_t b1 = vget_high_s16(uzp2); + int32x4_t p = vmull_s16(a0, b0); + return v_int32x4(vmlal_s16(p, a1, b1)); +} +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ + int16x8_t uzp1, uzp2; + _v128_unzip(a.val, b.val, uzp1, uzp2); + int16x4_t a0 = vget_low_s16(uzp1); + int16x4_t b0 = vget_high_s16(uzp1); + int16x4_t a1 = vget_low_s16(uzp2); + int16x4_t b1 = vget_high_s16(uzp2); + int32x4_t p = vmlal_s16(c.val, a0, b0); + return v_int32x4(vmlal_s16(p, a1, b1)); +} + +// 32 >> 64 +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) +{ + int32x4_t uzp1, uzp2; + _v128_unzip(a.val, b.val, uzp1, uzp2); + int32x2_t a0 = vget_low_s32(uzp1); + int32x2_t b0 = vget_high_s32(uzp1); + int32x2_t a1 = vget_low_s32(uzp2); + int32x2_t b1 = vget_high_s32(uzp2); + int64x2_t p = vmull_s32(a0, b0); + return v_int64x2(vmlal_s32(p, a1, b1)); +} +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ + int32x4_t uzp1, uzp2; + _v128_unzip(a.val, b.val, uzp1, uzp2); + int32x2_t a0 = vget_low_s32(uzp1); + int32x2_t b0 = vget_high_s32(uzp1); + int32x2_t a1 = vget_low_s32(uzp2); + int32x2_t b1 = vget_high_s32(uzp2); + int64x2_t p = vmlal_s32(c.val, a0, b0); + return v_int64x2(vmlal_s32(p, a1, b1)); +} + +// 8 >> 32 +#ifdef CV_NEON_DOT +#define OPENCV_HAL_IMPL_NEON_DOT_PRODUCT_OP(_Tpvec1, _Tpvec2, suffix) \ +inline _Tpvec1 v_dotprod_expand(const _Tpvec2& a, const _Tpvec2& b) \ +{ \ + return _Tpvec1(vdotq_##suffix(vdupq_n_##suffix(0), a.val, b.val));\ +} \ +inline _Tpvec1 v_dotprod_expand(const _Tpvec2& a, const _Tpvec2& b, const _Tpvec1& c) \ +{ \ + return _Tpvec1(vdotq_##suffix(c.val, a.val, b.val)); \ +} + +OPENCV_HAL_IMPL_NEON_DOT_PRODUCT_OP(v_uint32x4, v_uint8x16, u32) +OPENCV_HAL_IMPL_NEON_DOT_PRODUCT_OP(v_int32x4, v_int8x16, s32) +#else +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) +{ + const uint8x16_t zero = vreinterpretq_u8_u32(vdupq_n_u32(0)); + const uint8x16_t mask = vreinterpretq_u8_u32(vdupq_n_u32(0x00FF00FF)); + const uint16x8_t zero32 = vreinterpretq_u16_u32(vdupq_n_u32(0)); + const uint16x8_t mask32 = vreinterpretq_u16_u32(vdupq_n_u32(0x0000FFFF)); + + uint16x8_t even = vmulq_u16(vreinterpretq_u16_u8(vbslq_u8(mask, a.val, zero)), + vreinterpretq_u16_u8(vbslq_u8(mask, b.val, zero))); + uint16x8_t odd = vmulq_u16(vshrq_n_u16(vreinterpretq_u16_u8(a.val), 8), + vshrq_n_u16(vreinterpretq_u16_u8(b.val), 8)); + + uint32x4_t s0 = vaddq_u32(vreinterpretq_u32_u16(vbslq_u16(mask32, even, zero32)), + vreinterpretq_u32_u16(vbslq_u16(mask32, odd, zero32))); + uint32x4_t s1 = vaddq_u32(vshrq_n_u32(vreinterpretq_u32_u16(even), 16), + vshrq_n_u32(vreinterpretq_u32_u16(odd), 16)); + return v_uint32x4(vaddq_u32(s0, s1)); +} +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, + const v_uint32x4& c) +{ + return v_add(v_dotprod_expand(a, b), c); +} + +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) +{ + int16x8_t p0 = vmull_s8(vget_low_s8(a.val), vget_low_s8(b.val)); + int16x8_t p1 = vmull_s8(vget_high_s8(a.val), vget_high_s8(b.val)); + int16x8_t uzp1, uzp2; + _v128_unzip(p0, p1, uzp1, uzp2); + int16x8_t sum = vaddq_s16(uzp1, uzp2); + int16x4_t uzpl1, uzpl2; + _v128_unzip(vget_low_s16(sum), vget_high_s16(sum), uzpl1, uzpl2); + return v_int32x4(vaddl_s16(uzpl1, uzpl2)); +} +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, + const v_int32x4& c) +{ + return v_add(v_dotprod_expand(a, b), c); +} +#endif +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) +{ + const uint16x8_t zero = vreinterpretq_u16_u32(vdupq_n_u32(0)); + const uint16x8_t mask = vreinterpretq_u16_u32(vdupq_n_u32(0x0000FFFF)); + + uint32x4_t even = vmulq_u32(vreinterpretq_u32_u16(vbslq_u16(mask, a.val, zero)), + vreinterpretq_u32_u16(vbslq_u16(mask, b.val, zero))); + uint32x4_t odd = vmulq_u32(vshrq_n_u32(vreinterpretq_u32_u16(a.val), 16), + vshrq_n_u32(vreinterpretq_u32_u16(b.val), 16)); + uint32x4_t uzp1, uzp2; + _v128_unzip(even, odd, uzp1, uzp2); + uint64x2_t s0 = vaddl_u32(vget_low_u32(uzp1), vget_high_u32(uzp1)); + uint64x2_t s1 = vaddl_u32(vget_low_u32(uzp2), vget_high_u32(uzp2)); + return v_uint64x2(vaddq_u64(s0, s1)); +} +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) +{ + int32x4_t p0 = vmull_s16(vget_low_s16(a.val), vget_low_s16(b.val)); + int32x4_t p1 = vmull_s16(vget_high_s16(a.val), vget_high_s16(b.val)); + + int32x4_t uzp1, uzp2; + _v128_unzip(p0, p1, uzp1, uzp2); + int32x4_t sum = vaddq_s32(uzp1, uzp2); + + int32x2_t uzpl1, uzpl2; + _v128_unzip(vget_low_s32(sum), vget_high_s32(sum), uzpl1, uzpl2); + return v_int64x2(vaddl_s32(uzpl1, uzpl2)); +} +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, + const v_int64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 32 >> 64f +#if CV_SIMD128_64F +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) +{ return v_cvt_f64(v_dotprod(a, b)); } +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, + const v_float64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } +#endif + +//////// Fast Dot Product //////// + +// 16 >> 32 +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) +{ +#if CV_NEON_AARCH64 + int32x4_t p = vmull_s16(vget_low_s16(a.val), vget_low_s16(b.val)); + return v_int32x4(vmlal_high_s16(p, a.val, b.val)); +#else + int16x4_t a0 = vget_low_s16(a.val); + int16x4_t a1 = vget_high_s16(a.val); + int16x4_t b0 = vget_low_s16(b.val); + int16x4_t b1 = vget_high_s16(b.val); + int32x4_t p = vmull_s16(a0, b0); + return v_int32x4(vmlal_s16(p, a1, b1)); +#endif +} +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ +#if CV_NEON_AARCH64 + int32x4_t p = vmlal_s16(c.val, vget_low_s16(a.val), vget_low_s16(b.val)); + return v_int32x4(vmlal_high_s16(p, a.val, b.val)); +#else + int16x4_t a0 = vget_low_s16(a.val); + int16x4_t a1 = vget_high_s16(a.val); + int16x4_t b0 = vget_low_s16(b.val); + int16x4_t b1 = vget_high_s16(b.val); + int32x4_t p = vmlal_s16(c.val, a0, b0); + return v_int32x4(vmlal_s16(p, a1, b1)); +#endif +} + +// 32 >> 64 +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) +{ +#if CV_NEON_AARCH64 + int64x2_t p = vmull_s32(vget_low_s32(a.val), vget_low_s32(b.val)); + return v_int64x2(vmlal_high_s32(p, a.val, b.val)); +#else + int32x2_t a0 = vget_low_s32(a.val); + int32x2_t a1 = vget_high_s32(a.val); + int32x2_t b0 = vget_low_s32(b.val); + int32x2_t b1 = vget_high_s32(b.val); + int64x2_t p = vmull_s32(a0, b0); + return v_int64x2(vmlal_s32(p, a1, b1)); +#endif +} +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ +#if CV_NEON_AARCH64 + int64x2_t p = vmlal_s32(c.val, vget_low_s32(a.val), vget_low_s32(b.val)); + return v_int64x2(vmlal_high_s32(p, a.val, b.val)); +#else + int32x2_t a0 = vget_low_s32(a.val); + int32x2_t a1 = vget_high_s32(a.val); + int32x2_t b0 = vget_low_s32(b.val); + int32x2_t b1 = vget_high_s32(b.val); + int64x2_t p = vmlal_s32(c.val, a0, b0); + return v_int64x2(vmlal_s32(p, a1, b1)); +#endif +} + +// 8 >> 32 +#ifdef CV_NEON_DOT +#define OPENCV_HAL_IMPL_NEON_DOT_PRODUCT_FAST_OP(_Tpvec1, _Tpvec2, suffix) \ +inline _Tpvec1 v_dotprod_expand_fast(const _Tpvec2& a, const _Tpvec2& b) \ +{ \ + return v_dotprod_expand(a, b); \ +} \ +inline _Tpvec1 v_dotprod_expand_fast(const _Tpvec2& a, const _Tpvec2& b, const _Tpvec1& c) \ +{ \ + return v_dotprod_expand(a, b, c); \ +} + +OPENCV_HAL_IMPL_NEON_DOT_PRODUCT_FAST_OP(v_uint32x4, v_uint8x16, u32) +OPENCV_HAL_IMPL_NEON_DOT_PRODUCT_FAST_OP(v_int32x4, v_int8x16, s32) +#else +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) +{ + uint16x8_t p0 = vmull_u8(vget_low_u8(a.val), vget_low_u8(b.val)); + uint16x8_t p1 = vmull_u8(vget_high_u8(a.val), vget_high_u8(b.val)); + uint32x4_t s0 = vaddl_u16(vget_low_u16(p0), vget_low_u16(p1)); + uint32x4_t s1 = vaddl_u16(vget_high_u16(p0), vget_high_u16(p1)); + return v_uint32x4(vaddq_u32(s0, s1)); +} +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) +{ + return v_add(v_dotprod_expand_fast(a, b), c); +} + +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) +{ + int16x8_t prod = vmull_s8(vget_low_s8(a.val), vget_low_s8(b.val)); + prod = vmlal_s8(prod, vget_high_s8(a.val), vget_high_s8(b.val)); + return v_int32x4(vaddl_s16(vget_low_s16(prod), vget_high_s16(prod))); +} +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) +{ + return v_add(v_dotprod_expand_fast(a, b), c); +} +#endif + +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) +{ + uint32x4_t p0 = vmull_u16(vget_low_u16(a.val), vget_low_u16(b.val)); + uint32x4_t p1 = vmull_u16(vget_high_u16(a.val), vget_high_u16(b.val)); + uint64x2_t s0 = vaddl_u32(vget_low_u32(p0), vget_high_u32(p0)); + uint64x2_t s1 = vaddl_u32(vget_low_u32(p1), vget_high_u32(p1)); + return v_uint64x2(vaddq_u64(s0, s1)); +} +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) +{ + int32x4_t prod = vmull_s16(vget_low_s16(a.val), vget_low_s16(b.val)); + prod = vmlal_s16(prod, vget_high_s16(a.val), vget_high_s16(b.val)); + return v_int64x2(vaddl_s32(vget_low_s32(prod), vget_high_s32(prod))); +} +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +// 32 >> 64f +#if CV_SIMD128_64F +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) +{ return v_cvt_f64(v_dotprod_fast(a, b)); } +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } +#endif + + +#define OPENCV_HAL_IMPL_NEON_LOGIC_OP(_Tpvec, suffix) \ + OPENCV_HAL_IMPL_NEON_BIN_OP(v_and, _Tpvec, vandq_##suffix) \ + OPENCV_HAL_IMPL_NEON_BIN_OP(v_or, _Tpvec, vorrq_##suffix) \ + OPENCV_HAL_IMPL_NEON_BIN_OP(v_xor, _Tpvec, veorq_##suffix) \ + inline _Tpvec v_not (const _Tpvec& a) \ + { \ + return _Tpvec(vreinterpretq_##suffix##_u8(vmvnq_u8(vreinterpretq_u8_##suffix(a.val)))); \ + } + +OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_uint8x16, u8) +OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_int8x16, s8) +OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_uint16x8, u16) +OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_int16x8, s16) +OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_uint32x4, u32) +OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_int32x4, s32) +OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_uint64x2, u64) +OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_int64x2, s64) + +#define OPENCV_HAL_IMPL_NEON_FLT_BIT_OP(bin_op, intrin) \ +inline v_float32x4 bin_op (const v_float32x4& a, const v_float32x4& b) \ +{ \ + return v_float32x4(vreinterpretq_f32_s32(intrin(vreinterpretq_s32_f32(a.val), vreinterpretq_s32_f32(b.val)))); \ +} + +OPENCV_HAL_IMPL_NEON_FLT_BIT_OP(v_and, vandq_s32) +OPENCV_HAL_IMPL_NEON_FLT_BIT_OP(v_or, vorrq_s32) +OPENCV_HAL_IMPL_NEON_FLT_BIT_OP(v_xor, veorq_s32) + +inline v_float32x4 v_not (const v_float32x4& a) +{ + return v_float32x4(vreinterpretq_f32_s32(vmvnq_s32(vreinterpretq_s32_f32(a.val)))); +} + +#if CV_SIMD128_64F +inline v_float32x4 v_sqrt(const v_float32x4& x) +{ + return v_float32x4(vsqrtq_f32(x.val)); +} + +inline v_float32x4 v_invsqrt(const v_float32x4& x) +{ + v_float32x4 one = v_setall_f32(1.0f); + return v_div(one, v_sqrt(x)); +} +#else +inline v_float32x4 v_sqrt(const v_float32x4& x) +{ + float32x4_t x1 = vmaxq_f32(x.val, vdupq_n_f32(FLT_MIN)); + float32x4_t e = vrsqrteq_f32(x1); + e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(x1, e), e), e); + e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(x1, e), e), e); + return v_float32x4(vmulq_f32(x.val, e)); +} + +inline v_float32x4 v_invsqrt(const v_float32x4& x) +{ + float32x4_t e = vrsqrteq_f32(x.val); + e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(x.val, e), e), e); + e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(x.val, e), e), e); + return v_float32x4(e); +} +#endif + +#define OPENCV_HAL_IMPL_NEON_ABS(_Tpuvec, _Tpsvec, usuffix, ssuffix) \ +inline _Tpuvec v_abs(const _Tpsvec& a) { return v_reinterpret_as_##usuffix(_Tpsvec(vabsq_##ssuffix(a.val))); } + +OPENCV_HAL_IMPL_NEON_ABS(v_uint8x16, v_int8x16, u8, s8) +OPENCV_HAL_IMPL_NEON_ABS(v_uint16x8, v_int16x8, u16, s16) +OPENCV_HAL_IMPL_NEON_ABS(v_uint32x4, v_int32x4, u32, s32) + +inline v_float32x4 v_abs(v_float32x4 x) +{ return v_float32x4(vabsq_f32(x.val)); } + +#if CV_SIMD128_64F +#define OPENCV_HAL_IMPL_NEON_DBL_BIT_OP(bin_op, intrin) \ +inline v_float64x2 bin_op (const v_float64x2& a, const v_float64x2& b) \ +{ \ + return v_float64x2(vreinterpretq_f64_s64(intrin(vreinterpretq_s64_f64(a.val), vreinterpretq_s64_f64(b.val)))); \ +} + +OPENCV_HAL_IMPL_NEON_DBL_BIT_OP(v_and, vandq_s64) +OPENCV_HAL_IMPL_NEON_DBL_BIT_OP(v_or, vorrq_s64) +OPENCV_HAL_IMPL_NEON_DBL_BIT_OP(v_xor, veorq_s64) + +inline v_float64x2 v_not (const v_float64x2& a) +{ + return v_float64x2(vreinterpretq_f64_s32(vmvnq_s32(vreinterpretq_s32_f64(a.val)))); +} + +inline v_float64x2 v_sqrt(const v_float64x2& x) +{ + return v_float64x2(vsqrtq_f64(x.val)); +} + +inline v_float64x2 v_invsqrt(const v_float64x2& x) +{ + v_float64x2 one = v_setall_f64(1.0f); + return v_div(one, v_sqrt(x)); +} + +inline v_float64x2 v_abs(v_float64x2 x) +{ return v_float64x2(vabsq_f64(x.val)); } +#endif + +// TODO: exp, log, sin, cos + +#define OPENCV_HAL_IMPL_NEON_BIN_FUNC(_Tpvec, func, intrin) \ +inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(intrin(a.val, b.val)); \ +} + +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_min, vminq_u8) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_max, vmaxq_u8) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_min, vminq_s8) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_max, vmaxq_s8) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_min, vminq_u16) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_max, vmaxq_u16) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_min, vminq_s16) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_max, vmaxq_s16) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint32x4, v_min, vminq_u32) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint32x4, v_max, vmaxq_u32) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int32x4, v_min, vminq_s32) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int32x4, v_max, vmaxq_s32) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float32x4, v_min, vminq_f32) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float32x4, v_max, vmaxq_f32) +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float64x2, v_min, vminq_f64) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float64x2, v_max, vmaxq_f64) +#endif + +#define OPENCV_HAL_IMPL_NEON_INT_CMP_OP(_Tpvec, cast, suffix, not_suffix) \ +inline _Tpvec v_eq (const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(cast(vceqq_##suffix(a.val, b.val))); } \ +inline _Tpvec v_ne (const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(cast(vmvnq_##not_suffix(vceqq_##suffix(a.val, b.val)))); } \ +inline _Tpvec v_lt (const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(cast(vcltq_##suffix(a.val, b.val))); } \ +inline _Tpvec v_gt (const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(cast(vcgtq_##suffix(a.val, b.val))); } \ +inline _Tpvec v_le (const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(cast(vcleq_##suffix(a.val, b.val))); } \ +inline _Tpvec v_ge (const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(cast(vcgeq_##suffix(a.val, b.val))); } + +OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_uint8x16, OPENCV_HAL_NOP, u8, u8) +OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_int8x16, vreinterpretq_s8_u8, s8, u8) +OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_uint16x8, OPENCV_HAL_NOP, u16, u16) +OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_int16x8, vreinterpretq_s16_u16, s16, u16) +OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_uint32x4, OPENCV_HAL_NOP, u32, u32) +OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_int32x4, vreinterpretq_s32_u32, s32, u32) +OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_float32x4, vreinterpretq_f32_u32, f32, u32) +#if defined(__aarch64__) || defined(_M_ARM64) +static inline uint64x2_t vmvnq_u64(uint64x2_t a) +{ + uint64x2_t vx = vreinterpretq_u64_u32(vdupq_n_u32(0xFFFFFFFF)); + return veorq_u64(a, vx); +} +//OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_uint64x2, OPENCV_HAL_NOP, u64, u64) +//OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_int64x2, vreinterpretq_s64_u64, s64, u64) +static inline v_uint64x2 v_eq (const v_uint64x2& a, const v_uint64x2& b) +{ return v_uint64x2(vceqq_u64(a.val, b.val)); } +static inline v_uint64x2 v_ne (const v_uint64x2& a, const v_uint64x2& b) +{ return v_uint64x2(vmvnq_u64(vceqq_u64(a.val, b.val))); } +static inline v_int64x2 v_eq (const v_int64x2& a, const v_int64x2& b) +{ return v_int64x2(vreinterpretq_s64_u64(vceqq_s64(a.val, b.val))); } +static inline v_int64x2 v_ne (const v_int64x2& a, const v_int64x2& b) +{ return v_int64x2(vreinterpretq_s64_u64(vmvnq_u64(vceqq_s64(a.val, b.val)))); } +#else +static inline v_uint64x2 v_eq (const v_uint64x2& a, const v_uint64x2& b) +{ + uint32x4_t cmp = vceqq_u32(vreinterpretq_u32_u64(a.val), vreinterpretq_u32_u64(b.val)); + uint32x4_t swapped = vrev64q_u32(cmp); + return v_uint64x2(vreinterpretq_u64_u32(vandq_u32(cmp, swapped))); +} +static inline v_uint64x2 v_ne (const v_uint64x2& a, const v_uint64x2& b) +{ + uint32x4_t cmp = vceqq_u32(vreinterpretq_u32_u64(a.val), vreinterpretq_u32_u64(b.val)); + uint32x4_t swapped = vrev64q_u32(cmp); + uint64x2_t v_eq = vreinterpretq_u64_u32(vandq_u32(cmp, swapped)); + uint64x2_t vx = vreinterpretq_u64_u32(vdupq_n_u32(0xFFFFFFFF)); + return v_uint64x2(veorq_u64(v_eq, vx)); +} +static inline v_int64x2 v_eq (const v_int64x2& a, const v_int64x2& b) +{ + return v_reinterpret_as_s64(v_eq(v_reinterpret_as_u64(a), v_reinterpret_as_u64(b))); +} +static inline v_int64x2 v_ne (const v_int64x2& a, const v_int64x2& b) +{ + return v_reinterpret_as_s64(v_ne(v_reinterpret_as_u64(a), v_reinterpret_as_u64(b))); +} +#endif +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_float64x2, vreinterpretq_f64_u64, f64, u64) +#endif + +inline v_float32x4 v_not_nan(const v_float32x4& a) +{ return v_float32x4(vreinterpretq_f32_u32(vceqq_f32(a.val, a.val))); } +#if CV_SIMD128_64F +inline v_float64x2 v_not_nan(const v_float64x2& a) +{ return v_float64x2(vreinterpretq_f64_u64(vceqq_f64(a.val, a.val))); } +#endif + +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_add_wrap, vaddq_u8) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_add_wrap, vaddq_s8) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_add_wrap, vaddq_u16) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_add_wrap, vaddq_s16) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_sub_wrap, vsubq_u8) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_sub_wrap, vsubq_s8) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_sub_wrap, vsubq_u16) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_sub_wrap, vsubq_s16) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_mul_wrap, vmulq_u8) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_mul_wrap, vmulq_s8) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_mul_wrap, vmulq_u16) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_mul_wrap, vmulq_s16) + +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_absdiff, vabdq_u8) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_absdiff, vabdq_u16) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint32x4, v_absdiff, vabdq_u32) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float32x4, v_absdiff, vabdq_f32) +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float64x2, v_absdiff, vabdq_f64) +#endif + +/** Saturating absolute difference **/ +inline v_int8x16 v_absdiffs(const v_int8x16& a, const v_int8x16& b) +{ return v_int8x16(vqabsq_s8(vqsubq_s8(a.val, b.val))); } +inline v_int16x8 v_absdiffs(const v_int16x8& a, const v_int16x8& b) +{ return v_int16x8(vqabsq_s16(vqsubq_s16(a.val, b.val))); } + +#define OPENCV_HAL_IMPL_NEON_BIN_FUNC2(_Tpvec, _Tpvec2, cast, func, intrin) \ +inline _Tpvec2 func(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec2(cast(intrin(a.val, b.val))); \ +} + +OPENCV_HAL_IMPL_NEON_BIN_FUNC2(v_int8x16, v_uint8x16, vreinterpretq_u8_s8, v_absdiff, vabdq_s8) +OPENCV_HAL_IMPL_NEON_BIN_FUNC2(v_int16x8, v_uint16x8, vreinterpretq_u16_s16, v_absdiff, vabdq_s16) +OPENCV_HAL_IMPL_NEON_BIN_FUNC2(v_int32x4, v_uint32x4, vreinterpretq_u32_s32, v_absdiff, vabdq_s32) + +inline v_float32x4 v_magnitude(const v_float32x4& a, const v_float32x4& b) +{ + v_float32x4 x(vmlaq_f32(vmulq_f32(a.val, a.val), b.val, b.val)); + return v_sqrt(x); +} + +inline v_float32x4 v_sqr_magnitude(const v_float32x4& a, const v_float32x4& b) +{ + return v_float32x4(vmlaq_f32(vmulq_f32(a.val, a.val), b.val, b.val)); +} + +inline v_float32x4 v_fma(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) +{ +#if CV_SIMD128_64F + // ARMv8, which adds support for 64-bit floating-point (so CV_SIMD128_64F is defined), + // also adds FMA support both for single- and double-precision floating-point vectors + return v_float32x4(vfmaq_f32(c.val, a.val, b.val)); +#else + return v_float32x4(vmlaq_f32(c.val, a.val, b.val)); +#endif +} + +inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ + return v_int32x4(vmlaq_s32(c.val, a.val, b.val)); +} + +inline v_float32x4 v_muladd(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) +{ + return v_fma(a, b, c); +} + +inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ + return v_fma(a, b, c); +} + +#if CV_SIMD128_64F +inline v_float64x2 v_magnitude(const v_float64x2& a, const v_float64x2& b) +{ + v_float64x2 x(vaddq_f64(vmulq_f64(a.val, a.val), vmulq_f64(b.val, b.val))); + return v_sqrt(x); +} + +inline v_float64x2 v_sqr_magnitude(const v_float64x2& a, const v_float64x2& b) +{ + return v_float64x2(vaddq_f64(vmulq_f64(a.val, a.val), vmulq_f64(b.val, b.val))); +} + +inline v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) +{ + return v_float64x2(vfmaq_f64(c.val, a.val, b.val)); +} + +inline v_float64x2 v_muladd(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) +{ + return v_fma(a, b, c); +} +#endif + +// trade efficiency for convenience +#define OPENCV_HAL_IMPL_NEON_SHIFT_OP(_Tpvec, suffix, _Tps, ssuffix) \ +inline _Tpvec v_shl (const _Tpvec& a, int n) \ +{ return _Tpvec(vshlq_##suffix(a.val, vdupq_n_##ssuffix((_Tps)n))); } \ +inline _Tpvec v_shr (const _Tpvec& a, int n) \ +{ return _Tpvec(vshlq_##suffix(a.val, vdupq_n_##ssuffix((_Tps)-n))); } \ +template inline _Tpvec v_shl(const _Tpvec& a) \ +{ return _Tpvec(vshlq_n_##suffix(a.val, n)); } \ +template inline _Tpvec v_shr(const _Tpvec& a) \ +{ return _Tpvec(vshrq_n_##suffix(a.val, n)); } \ +template inline _Tpvec v_rshr(const _Tpvec& a) \ +{ return _Tpvec(vrshrq_n_##suffix(a.val, n)); } + +OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_uint8x16, u8, schar, s8) +OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_int8x16, s8, schar, s8) +OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_uint16x8, u16, short, s16) +OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_int16x8, s16, short, s16) +OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_uint32x4, u32, int, s32) +OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_int32x4, s32, int, s32) +OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_uint64x2, u64, int64, s64) +OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_int64x2, s64, int64, s64) + +#define OPENCV_HAL_IMPL_NEON_ROTATE_OP(_Tpvec, suffix) \ +template inline _Tpvec v_rotate_right(const _Tpvec& a) \ +{ return _Tpvec(vextq_##suffix(a.val, vdupq_n_##suffix(0), n)); } \ +template inline _Tpvec v_rotate_left(const _Tpvec& a) \ +{ return _Tpvec(vextq_##suffix(vdupq_n_##suffix(0), a.val, VTraits<_Tpvec>::nlanes - n)); } \ +template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a) \ +{ return a; } \ +template inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(vextq_##suffix(a.val, b.val, n)); } \ +template inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(vextq_##suffix(b.val, a.val, VTraits<_Tpvec>::nlanes - n)); } \ +template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a, const _Tpvec& b) \ +{ CV_UNUSED(b); return a; } + +OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_uint8x16, u8) +OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_int8x16, s8) +OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_uint16x8, u16) +OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_int16x8, s16) +OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_uint32x4, u32) +OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_int32x4, s32) +OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_float32x4, f32) +OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_uint64x2, u64) +OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_int64x2, s64) +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_float64x2, f64) +#endif + +#if defined(__clang__) && defined(__aarch64__) +// avoid LD2 instruction. details: https://github.com/opencv/opencv/issues/14863 +#define OPENCV_HAL_IMPL_NEON_LOAD_LOW_OP(_Tpvec, _Tp, suffix) \ +inline _Tpvec v_load_low(const _Tp* ptr) \ +{ \ +typedef uint64 CV_DECL_ALIGNED(1) unaligned_uint64; \ +uint64 v = *(unaligned_uint64*)ptr; \ +return _Tpvec(v_reinterpret_as_##suffix(v_uint64x2(v, (uint64)123456))); \ +} +#else +#define OPENCV_HAL_IMPL_NEON_LOAD_LOW_OP(_Tpvec, _Tp, suffix) \ +inline _Tpvec v_load_low(const _Tp* ptr) \ +{ return _Tpvec(vcombine_##suffix(vld1_##suffix(ptr), vdup_n_##suffix((_Tp)0))); } +#endif + +#define OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(_Tpvec, _Tp, suffix) \ +inline _Tpvec v_load(const _Tp* ptr) \ +{ return _Tpvec(vld1q_##suffix(ptr)); } \ +inline _Tpvec v_load_aligned(const _Tp* ptr) \ +{ return _Tpvec(vld1q_##suffix(ptr)); } \ +OPENCV_HAL_IMPL_NEON_LOAD_LOW_OP(_Tpvec, _Tp, suffix) \ +inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ +{ return _Tpvec(vcombine_##suffix(vld1_##suffix(ptr0), vld1_##suffix(ptr1))); } \ +inline void v_store(_Tp* ptr, const _Tpvec& a) \ +{ vst1q_##suffix(ptr, a.val); } \ +inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ +{ vst1q_##suffix(ptr, a.val); } \ +inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ +{ vst1q_##suffix(ptr, a.val); } \ +inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ +{ vst1q_##suffix(ptr, a.val); } \ +inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ +{ vst1_##suffix(ptr, vget_low_##suffix(a.val)); } \ +inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ +{ vst1_##suffix(ptr, vget_high_##suffix(a.val)); } + +OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_uint8x16, uchar, u8) +OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_int8x16, schar, s8) +OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_uint16x8, ushort, u16) +OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_int16x8, short, s16) +OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_uint32x4, unsigned, u32) +OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_int32x4, int, s32) +OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_uint64x2, uint64, u64) +OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_int64x2, int64, s64) +OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_float32x4, float, f32) +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_float64x2, double, f64) +#endif + +inline unsigned v_reduce_sum(const v_uint8x16& a) +{ +#if CV_NEON_AARCH64 + uint16_t t0 = vaddlvq_u8(a.val); + return t0; +#else // #if CV_NEON_AARCH64 + uint32x4_t t0 = vpaddlq_u16(vpaddlq_u8(a.val)); + uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); + return vget_lane_u32(vpadd_u32(t1, t1), 0); +#endif // #if CV_NEON_AARCH64 +} +inline int v_reduce_sum(const v_int8x16& a) +{ +#if CV_NEON_AARCH64 + int16_t t0 = vaddlvq_s8(a.val); + return t0; +#else // #if CV_NEON_AARCH64 + int32x4_t t0 = vpaddlq_s16(vpaddlq_s8(a.val)); + int32x2_t t1 = vpadd_s32(vget_low_s32(t0), vget_high_s32(t0)); + return vget_lane_s32(vpadd_s32(t1, t1), 0); +#endif // #if CV_NEON_AARCH64 +} +inline unsigned v_reduce_sum(const v_uint16x8& a) +{ +#if CV_NEON_AARCH64 + uint32_t t0 = vaddlvq_u16(a.val); + return t0; +#else // #if CV_NEON_AARCH64 + uint32x4_t t0 = vpaddlq_u16(a.val); + uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); + return vget_lane_u32(vpadd_u32(t1, t1), 0); +#endif // #if CV_NEON_AARCH64 +} +inline int v_reduce_sum(const v_int16x8& a) +{ +#if CV_NEON_AARCH64 + int32_t t0 = vaddlvq_s16(a.val); + return t0; +#else // #if CV_NEON_AARCH64 + int32x4_t t0 = vpaddlq_s16(a.val); + int32x2_t t1 = vpadd_s32(vget_low_s32(t0), vget_high_s32(t0)); + return vget_lane_s32(vpadd_s32(t1, t1), 0); +#endif // #if CV_NEON_AARCH64 +} + +#if CV_NEON_AARCH64 +#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \ +inline scalartype v_reduce_##func(const _Tpvec& a) \ +{ \ + return v##vectorfunc##vq_##suffix(a.val); \ +} +#else // #if CV_NEON_AARCH64 +#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \ +inline scalartype v_reduce_##func(const _Tpvec& a) \ +{ \ + _Tpnvec##_t a0 = vp##vectorfunc##_##suffix(vget_low_##suffix(a.val), vget_high_##suffix(a.val)); \ + a0 = vp##vectorfunc##_##suffix(a0, a0); \ + a0 = vp##vectorfunc##_##suffix(a0, a0); \ + return (scalartype)vget_lane_##suffix(vp##vectorfunc##_##suffix(a0, a0),0); \ +} +#endif // #if CV_NEON_AARCH64 + +OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(v_uint8x16, uint8x8, uchar, max, max, u8) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(v_uint8x16, uint8x8, uchar, min, min, u8) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(v_int8x16, int8x8, schar, max, max, s8) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(v_int8x16, int8x8, schar, min, min, s8) + +#if CV_NEON_AARCH64 +#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \ +inline scalartype v_reduce_##func(const _Tpvec& a) \ +{ \ + return v##vectorfunc##vq_##suffix(a.val); \ +} +#else // #if CV_NEON_AARCH64 +#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \ +inline scalartype v_reduce_##func(const _Tpvec& a) \ +{ \ + _Tpnvec##_t a0 = vp##vectorfunc##_##suffix(vget_low_##suffix(a.val), vget_high_##suffix(a.val)); \ + a0 = vp##vectorfunc##_##suffix(a0, a0); \ + return (scalartype)vget_lane_##suffix(vp##vectorfunc##_##suffix(a0, a0),0); \ +} +#endif // #if CV_NEON_AARCH64 + +OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_uint16x8, uint16x4, ushort, max, max, u16) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_uint16x8, uint16x4, ushort, min, min, u16) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_int16x8, int16x4, short, max, max, s16) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_int16x8, int16x4, short, min, min, s16) + +#if CV_NEON_AARCH64 +#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \ +inline scalartype v_reduce_##func(const _Tpvec& a) \ +{ \ + return v##vectorfunc##vq_##suffix(a.val); \ +} +#else // #if CV_NEON_AARCH64 +#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \ +inline scalartype v_reduce_##func(const _Tpvec& a) \ +{ \ + _Tpnvec##_t a0 = vp##vectorfunc##_##suffix(vget_low_##suffix(a.val), vget_high_##suffix(a.val)); \ + return (scalartype)vget_lane_##suffix(vp##vectorfunc##_##suffix(a0, vget_high_##suffix(a.val)),0); \ +} +#endif // #if CV_NEON_AARCH64 + +OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_uint32x4, uint32x2, unsigned, sum, add, u32) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_uint32x4, uint32x2, unsigned, max, max, u32) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_uint32x4, uint32x2, unsigned, min, min, u32) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_int32x4, int32x2, int, sum, add, s32) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_int32x4, int32x2, int, max, max, s32) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_int32x4, int32x2, int, min, min, s32) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_float32x4, float32x2, float, sum, add, f32) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_float32x4, float32x2, float, max, max, f32) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_float32x4, float32x2, float, min, min, f32) + +inline uint64 v_reduce_sum(const v_uint64x2& a) +{ +#if CV_NEON_AARCH64 + return vaddvq_u64(a.val); +#else // #if CV_NEON_AARCH64 + return vget_lane_u64(vadd_u64(vget_low_u64(a.val), vget_high_u64(a.val)),0); +#endif // #if CV_NEON_AARCH64 +} +inline int64 v_reduce_sum(const v_int64x2& a) +{ +#if CV_NEON_AARCH64 + return vaddvq_s64(a.val); +#else // #if CV_NEON_AARCH64 + return vget_lane_s64(vadd_s64(vget_low_s64(a.val), vget_high_s64(a.val)),0); +#endif // #if CV_NEON_AARCH64 +} +#if CV_SIMD128_64F +inline double v_reduce_sum(const v_float64x2& a) +{ + return vaddvq_f64(a.val); +} +#endif + +inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, + const v_float32x4& c, const v_float32x4& d) +{ +#if CV_NEON_AARCH64 + float32x4_t ab = vpaddq_f32(a.val, b.val); // a0+a1 a2+a3 b0+b1 b2+b3 + float32x4_t cd = vpaddq_f32(c.val, d.val); // c0+c1 d0+d1 c2+c3 d2+d3 + return v_float32x4(vpaddq_f32(ab, cd)); // sumA sumB sumC sumD +#else // #if CV_NEON_AARCH64 + float32x4x2_t ab = vtrnq_f32(a.val, b.val); + float32x4x2_t cd = vtrnq_f32(c.val, d.val); + + float32x4_t u0 = vaddq_f32(ab.val[0], ab.val[1]); // a0+a1 b0+b1 a2+a3 b2+b3 + float32x4_t u1 = vaddq_f32(cd.val[0], cd.val[1]); // c0+c1 d0+d1 c2+c3 d2+d3 + + float32x4_t v0 = vcombine_f32(vget_low_f32(u0), vget_low_f32(u1)); + float32x4_t v1 = vcombine_f32(vget_high_f32(u0), vget_high_f32(u1)); + + return v_float32x4(vaddq_f32(v0, v1)); +#endif // #if CV_NEON_AARCH64 +} + +inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b) +{ +#if CV_NEON_AARCH64 + uint8x16_t t0 = vabdq_u8(a.val, b.val); + uint16_t t1 = vaddlvq_u8(t0); + return t1; +#else // #if CV_NEON_AARCH64 + uint32x4_t t0 = vpaddlq_u16(vpaddlq_u8(vabdq_u8(a.val, b.val))); + uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); + return vget_lane_u32(vpadd_u32(t1, t1), 0); +#endif // #if CV_NEON_AARCH64 +} +inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b) +{ +#if CV_NEON_AARCH64 + uint8x16_t t0 = vreinterpretq_u8_s8(vabdq_s8(a.val, b.val)); + uint16_t t1 = vaddlvq_u8(t0); + return t1; +#else // #if CV_NEON_AARCH64 + uint32x4_t t0 = vpaddlq_u16(vpaddlq_u8(vreinterpretq_u8_s8(vabdq_s8(a.val, b.val)))); + uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); + return vget_lane_u32(vpadd_u32(t1, t1), 0); +#endif // #if CV_NEON_AARCH64 +} +inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b) +{ +#if CV_NEON_AARCH64 + uint16x8_t t0 = vabdq_u16(a.val, b.val); + uint32_t t1 = vaddlvq_u16(t0); + return t1; +#else // #if CV_NEON_AARCH64 + uint32x4_t t0 = vpaddlq_u16(vabdq_u16(a.val, b.val)); + uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); + return vget_lane_u32(vpadd_u32(t1, t1), 0); +#endif // #if CV_NEON_AARCH64 +} +inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b) +{ +#if CV_NEON_AARCH64 + uint16x8_t t0 = vreinterpretq_u16_s16(vabdq_s16(a.val, b.val)); + uint32_t t1 = vaddlvq_u16(t0); + return t1; +#else // #if CV_NEON_AARCH64 + uint32x4_t t0 = vpaddlq_u16(vreinterpretq_u16_s16(vabdq_s16(a.val, b.val))); + uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); + return vget_lane_u32(vpadd_u32(t1, t1), 0); +#endif // #if CV_NEON_AARCH64 +} +inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b) +{ +#if CV_NEON_AARCH64 + uint32x4_t t0 = vabdq_u32(a.val, b.val); + uint32_t t1 = vaddvq_u32(t0); + return t1; +#else // #if CV_NEON_AARCH64 + uint32x4_t t0 = vabdq_u32(a.val, b.val); + uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); + return vget_lane_u32(vpadd_u32(t1, t1), 0); +#endif // #if CV_NEON_AARCH64 +} +inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b) +{ +#if CV_NEON_AARCH64 + uint32x4_t t0 = vreinterpretq_u32_s32(vabdq_s32(a.val, b.val)); + uint32_t t1 = vaddvq_u32(t0); + return t1; +#else // #if CV_NEON_AARCH64 + uint32x4_t t0 = vreinterpretq_u32_s32(vabdq_s32(a.val, b.val)); + uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); + return vget_lane_u32(vpadd_u32(t1, t1), 0); +#endif // #if CV_NEON_AARCH64 +} +inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) +{ +#if CV_NEON_AARCH64 + float32x4_t t0 = vabdq_f32(a.val, b.val); + return vaddvq_f32(t0); +#else // #if CV_NEON_AARCH64 + float32x4_t t0 = vabdq_f32(a.val, b.val); + float32x2_t t1 = vpadd_f32(vget_low_f32(t0), vget_high_f32(t0)); + return vget_lane_f32(vpadd_f32(t1, t1), 0); +#endif // #if CV_NEON_AARCH64 +} + +inline v_uint8x16 v_popcount(const v_uint8x16& a) +{ return v_uint8x16(vcntq_u8(a.val)); } +inline v_uint8x16 v_popcount(const v_int8x16& a) +{ return v_uint8x16(vcntq_u8(vreinterpretq_u8_s8(a.val))); } +inline v_uint16x8 v_popcount(const v_uint16x8& a) +{ return v_uint16x8(vpaddlq_u8(vcntq_u8(vreinterpretq_u8_u16(a.val)))); } +inline v_uint16x8 v_popcount(const v_int16x8& a) +{ return v_uint16x8(vpaddlq_u8(vcntq_u8(vreinterpretq_u8_s16(a.val)))); } +inline v_uint32x4 v_popcount(const v_uint32x4& a) +{ return v_uint32x4(vpaddlq_u16(vpaddlq_u8(vcntq_u8(vreinterpretq_u8_u32(a.val))))); } +inline v_uint32x4 v_popcount(const v_int32x4& a) +{ return v_uint32x4(vpaddlq_u16(vpaddlq_u8(vcntq_u8(vreinterpretq_u8_s32(a.val))))); } +inline v_uint64x2 v_popcount(const v_uint64x2& a) +{ return v_uint64x2(vpaddlq_u32(vpaddlq_u16(vpaddlq_u8(vcntq_u8(vreinterpretq_u8_u64(a.val)))))); } +inline v_uint64x2 v_popcount(const v_int64x2& a) +{ return v_uint64x2(vpaddlq_u32(vpaddlq_u16(vpaddlq_u8(vcntq_u8(vreinterpretq_u8_s64(a.val)))))); } + +inline int v_signmask(const v_uint8x16& a) +{ +#if CV_NEON_AARCH64 + const int8x16_t signPosition = {0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7}; + const uint8x16_t byteOrder = {0,8,1,9,2,10,3,11,4,12,5,13,6,14,7,15}; + uint8x16_t v0 = vshlq_u8(vshrq_n_u8(a.val, 7), signPosition); + uint8x16_t v1 = vqtbl1q_u8(v0, byteOrder); + uint32_t t0 = vaddlvq_u16(vreinterpretq_u16_u8(v1)); + return t0; +#else // #if CV_NEON_AARCH64 + int8x8_t m0 = vcreate_s8(CV_BIG_UINT(0x0706050403020100)); + uint8x16_t v0 = vshlq_u8(vshrq_n_u8(a.val, 7), vcombine_s8(m0, m0)); + uint64x2_t v1 = vpaddlq_u32(vpaddlq_u16(vpaddlq_u8(v0))); + return (int)vgetq_lane_u64(v1, 0) + ((int)vgetq_lane_u64(v1, 1) << 8); +#endif // #if CV_NEON_AARCH64 +} + +inline int v_signmask(const v_int8x16& a) +{ return v_signmask(v_reinterpret_as_u8(a)); } + +inline int v_signmask(const v_uint16x8& a) +{ +#if CV_NEON_AARCH64 + const int16x8_t signPosition = {0,1,2,3,4,5,6,7}; + uint16x8_t v0 = vshlq_u16(vshrq_n_u16(a.val, 15), signPosition); + uint32_t t0 = vaddlvq_u16(v0); + return t0; +#else // #if CV_NEON_AARCH64 + int16x4_t m0 = vcreate_s16(CV_BIG_UINT(0x0003000200010000)); + uint16x8_t v0 = vshlq_u16(vshrq_n_u16(a.val, 15), vcombine_s16(m0, m0)); + uint64x2_t v1 = vpaddlq_u32(vpaddlq_u16(v0)); + return (int)vgetq_lane_u64(v1, 0) + ((int)vgetq_lane_u64(v1, 1) << 4); +#endif // #if CV_NEON_AARCH64 +} +inline int v_signmask(const v_int16x8& a) +{ return v_signmask(v_reinterpret_as_u16(a)); } + +inline int v_signmask(const v_uint32x4& a) +{ +#if CV_NEON_AARCH64 + const int32x4_t signPosition = {0,1,2,3}; + uint32x4_t v0 = vshlq_u32(vshrq_n_u32(a.val, 31), signPosition); + uint32_t t0 = vaddvq_u32(v0); + return t0; +#else // #if CV_NEON_AARCH64 + int32x2_t m0 = vcreate_s32(CV_BIG_UINT(0x0000000100000000)); + uint32x4_t v0 = vshlq_u32(vshrq_n_u32(a.val, 31), vcombine_s32(m0, m0)); + uint64x2_t v1 = vpaddlq_u32(v0); + return (int)vgetq_lane_u64(v1, 0) + ((int)vgetq_lane_u64(v1, 1) << 2); +#endif // #if CV_NEON_AARCH64 +} +inline int v_signmask(const v_int32x4& a) +{ return v_signmask(v_reinterpret_as_u32(a)); } +inline int v_signmask(const v_float32x4& a) +{ return v_signmask(v_reinterpret_as_u32(a)); } +inline int v_signmask(const v_uint64x2& a) +{ +#if CV_NEON_AARCH64 + const int64x2_t signPosition = {0,1}; + uint64x2_t v0 = vshlq_u64(vshrq_n_u64(a.val, 63), signPosition); + int t0 = (int)vaddvq_u64(v0); + return t0; +#else // #if CV_NEON_AARCH64 + int64x1_t m0 = vdup_n_s64(0); + uint64x2_t v0 = vshlq_u64(vshrq_n_u64(a.val, 63), vcombine_s64(m0, m0)); + return (int)vgetq_lane_u64(v0, 0) + ((int)vgetq_lane_u64(v0, 1) << 1); +#endif // #if CV_NEON_AARCH64 +} +inline int v_signmask(const v_int64x2& a) +{ return v_signmask(v_reinterpret_as_u64(a)); } +#if CV_SIMD128_64F +inline int v_signmask(const v_float64x2& a) +{ return v_signmask(v_reinterpret_as_u64(a)); } +#endif + +inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(a)); } +#if CV_SIMD128_64F +inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(a)); } +#endif + +#if CV_NEON_AARCH64 + #define OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(_Tpvec, suffix, shift) \ + inline bool v_check_all(const v_##_Tpvec& a) \ + { \ + return (vminvq_##suffix(a.val) >> shift) != 0; \ + } \ + inline bool v_check_any(const v_##_Tpvec& a) \ + { \ + return (vmaxvq_##suffix(a.val) >> shift) != 0; \ + } +#else // #if CV_NEON_AARCH64 + #define OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(_Tpvec, suffix, shift) \ + inline bool v_check_all(const v_##_Tpvec& a) \ + { \ + _Tpvec##_t v0 = vshrq_n_##suffix(vmvnq_##suffix(a.val), shift); \ + uint64x2_t v1 = vreinterpretq_u64_##suffix(v0); \ + return (vgetq_lane_u64(v1, 0) | vgetq_lane_u64(v1, 1)) == 0; \ + } \ + inline bool v_check_any(const v_##_Tpvec& a) \ + { \ + _Tpvec##_t v0 = vshrq_n_##suffix(a.val, shift); \ + uint64x2_t v1 = vreinterpretq_u64_##suffix(v0); \ + return (vgetq_lane_u64(v1, 0) | vgetq_lane_u64(v1, 1)) != 0; \ + } +#endif // #if CV_NEON_AARCH64 + +OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(uint8x16, u8, 7) +OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(uint16x8, u16, 15) +OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(uint32x4, u32, 31) + +inline bool v_check_all(const v_uint64x2& a) +{ + uint64x2_t v0 = vshrq_n_u64(a.val, 63); + return (vgetq_lane_u64(v0, 0) & vgetq_lane_u64(v0, 1)) == 1; +} +inline bool v_check_any(const v_uint64x2& a) +{ + uint64x2_t v0 = vshrq_n_u64(a.val, 63); + return (vgetq_lane_u64(v0, 0) | vgetq_lane_u64(v0, 1)) != 0; +} + +inline bool v_check_all(const v_int8x16& a) +{ return v_check_all(v_reinterpret_as_u8(a)); } +inline bool v_check_all(const v_int16x8& a) +{ return v_check_all(v_reinterpret_as_u16(a)); } +inline bool v_check_all(const v_int32x4& a) +{ return v_check_all(v_reinterpret_as_u32(a)); } +inline bool v_check_all(const v_float32x4& a) +{ return v_check_all(v_reinterpret_as_u32(a)); } + +inline bool v_check_any(const v_int8x16& a) +{ return v_check_any(v_reinterpret_as_u8(a)); } +inline bool v_check_any(const v_int16x8& a) +{ return v_check_any(v_reinterpret_as_u16(a)); } +inline bool v_check_any(const v_int32x4& a) +{ return v_check_any(v_reinterpret_as_u32(a)); } +inline bool v_check_any(const v_float32x4& a) +{ return v_check_any(v_reinterpret_as_u32(a)); } + +inline bool v_check_all(const v_int64x2& a) +{ return v_check_all(v_reinterpret_as_u64(a)); } +inline bool v_check_any(const v_int64x2& a) +{ return v_check_any(v_reinterpret_as_u64(a)); } +#if CV_SIMD128_64F +inline bool v_check_all(const v_float64x2& a) +{ return v_check_all(v_reinterpret_as_u64(a)); } +inline bool v_check_any(const v_float64x2& a) +{ return v_check_any(v_reinterpret_as_u64(a)); } +#endif + +#define OPENCV_HAL_IMPL_NEON_SELECT(_Tpvec, suffix, usuffix) \ +inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(vbslq_##suffix(vreinterpretq_##usuffix##_##suffix(mask.val), a.val, b.val)); \ +} + +OPENCV_HAL_IMPL_NEON_SELECT(v_uint8x16, u8, u8) +OPENCV_HAL_IMPL_NEON_SELECT(v_int8x16, s8, u8) +OPENCV_HAL_IMPL_NEON_SELECT(v_uint16x8, u16, u16) +OPENCV_HAL_IMPL_NEON_SELECT(v_int16x8, s16, u16) +OPENCV_HAL_IMPL_NEON_SELECT(v_uint32x4, u32, u32) +OPENCV_HAL_IMPL_NEON_SELECT(v_int32x4, s32, u32) +OPENCV_HAL_IMPL_NEON_SELECT(v_float32x4, f32, u32) +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_SELECT(v_float64x2, f64, u64) +#endif + +#if CV_NEON_AARCH64 +#define OPENCV_HAL_IMPL_NEON_EXPAND(_Tpvec, _Tpwvec, _Tp, suffix) \ +inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ +{ \ + b0.val = vmovl_##suffix(vget_low_##suffix(a.val)); \ + b1.val = vmovl_high_##suffix(a.val); \ +} \ +inline _Tpwvec v_expand_low(const _Tpvec& a) \ +{ \ + return _Tpwvec(vmovl_##suffix(vget_low_##suffix(a.val))); \ +} \ +inline _Tpwvec v_expand_high(const _Tpvec& a) \ +{ \ + return _Tpwvec(vmovl_high_##suffix(a.val)); \ +} \ +inline _Tpwvec v_load_expand(const _Tp* ptr) \ +{ \ + return _Tpwvec(vmovl_##suffix(vld1_##suffix(ptr))); \ +} +#else +#define OPENCV_HAL_IMPL_NEON_EXPAND(_Tpvec, _Tpwvec, _Tp, suffix) \ +inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ +{ \ + b0.val = vmovl_##suffix(vget_low_##suffix(a.val)); \ + b1.val = vmovl_##suffix(vget_high_##suffix(a.val)); \ +} \ +inline _Tpwvec v_expand_low(const _Tpvec& a) \ +{ \ + return _Tpwvec(vmovl_##suffix(vget_low_##suffix(a.val))); \ +} \ +inline _Tpwvec v_expand_high(const _Tpvec& a) \ +{ \ + return _Tpwvec(vmovl_##suffix(vget_high_##suffix(a.val))); \ +} \ +inline _Tpwvec v_load_expand(const _Tp* ptr) \ +{ \ + return _Tpwvec(vmovl_##suffix(vld1_##suffix(ptr))); \ +} +#endif + +OPENCV_HAL_IMPL_NEON_EXPAND(v_uint8x16, v_uint16x8, uchar, u8) +OPENCV_HAL_IMPL_NEON_EXPAND(v_int8x16, v_int16x8, schar, s8) +OPENCV_HAL_IMPL_NEON_EXPAND(v_uint16x8, v_uint32x4, ushort, u16) +OPENCV_HAL_IMPL_NEON_EXPAND(v_int16x8, v_int32x4, short, s16) +OPENCV_HAL_IMPL_NEON_EXPAND(v_uint32x4, v_uint64x2, uint, u32) +OPENCV_HAL_IMPL_NEON_EXPAND(v_int32x4, v_int64x2, int, s32) + +inline v_uint32x4 v_load_expand_q(const uchar* ptr) +{ + typedef unsigned int CV_DECL_ALIGNED(1) unaligned_uint; + uint8x8_t v0 = vcreate_u8(*(unaligned_uint*)ptr); + uint16x4_t v1 = vget_low_u16(vmovl_u8(v0)); + return v_uint32x4(vmovl_u16(v1)); +} + +inline v_int32x4 v_load_expand_q(const schar* ptr) +{ + typedef unsigned int CV_DECL_ALIGNED(1) unaligned_uint; + int8x8_t v0 = vcreate_s8(*(unaligned_uint*)ptr); + int16x4_t v1 = vget_low_s16(vmovl_s8(v0)); + return v_int32x4(vmovl_s16(v1)); +} + +#if defined(__aarch64__) || defined(_M_ARM64) +#define OPENCV_HAL_IMPL_NEON_UNPACKS(_Tpvec, suffix) \ +inline void v_zip(const v_##_Tpvec& a0, const v_##_Tpvec& a1, v_##_Tpvec& b0, v_##_Tpvec& b1) \ +{ \ + b0.val = vzip1q_##suffix(a0.val, a1.val); \ + b1.val = vzip2q_##suffix(a0.val, a1.val); \ +} \ +inline v_##_Tpvec v_combine_low(const v_##_Tpvec& a, const v_##_Tpvec& b) \ +{ \ + return v_##_Tpvec(vcombine_##suffix(vget_low_##suffix(a.val), vget_low_##suffix(b.val))); \ +} \ +inline v_##_Tpvec v_combine_high(const v_##_Tpvec& a, const v_##_Tpvec& b) \ +{ \ + return v_##_Tpvec(vcombine_##suffix(vget_high_##suffix(a.val), vget_high_##suffix(b.val))); \ +} \ +inline void v_recombine(const v_##_Tpvec& a, const v_##_Tpvec& b, v_##_Tpvec& c, v_##_Tpvec& d) \ +{ \ + c.val = vcombine_##suffix(vget_low_##suffix(a.val), vget_low_##suffix(b.val)); \ + d.val = vcombine_##suffix(vget_high_##suffix(a.val), vget_high_##suffix(b.val)); \ +} +#else +#define OPENCV_HAL_IMPL_NEON_UNPACKS(_Tpvec, suffix) \ +inline void v_zip(const v_##_Tpvec& a0, const v_##_Tpvec& a1, v_##_Tpvec& b0, v_##_Tpvec& b1) \ +{ \ + _Tpvec##x2_t p = vzipq_##suffix(a0.val, a1.val); \ + b0.val = p.val[0]; \ + b1.val = p.val[1]; \ +} \ +inline v_##_Tpvec v_combine_low(const v_##_Tpvec& a, const v_##_Tpvec& b) \ +{ \ + return v_##_Tpvec(vcombine_##suffix(vget_low_##suffix(a.val), vget_low_##suffix(b.val))); \ +} \ +inline v_##_Tpvec v_combine_high(const v_##_Tpvec& a, const v_##_Tpvec& b) \ +{ \ + return v_##_Tpvec(vcombine_##suffix(vget_high_##suffix(a.val), vget_high_##suffix(b.val))); \ +} \ +inline void v_recombine(const v_##_Tpvec& a, const v_##_Tpvec& b, v_##_Tpvec& c, v_##_Tpvec& d) \ +{ \ + c.val = vcombine_##suffix(vget_low_##suffix(a.val), vget_low_##suffix(b.val)); \ + d.val = vcombine_##suffix(vget_high_##suffix(a.val), vget_high_##suffix(b.val)); \ +} +#endif + +OPENCV_HAL_IMPL_NEON_UNPACKS(uint8x16, u8) +OPENCV_HAL_IMPL_NEON_UNPACKS(int8x16, s8) +OPENCV_HAL_IMPL_NEON_UNPACKS(uint16x8, u16) +OPENCV_HAL_IMPL_NEON_UNPACKS(int16x8, s16) +OPENCV_HAL_IMPL_NEON_UNPACKS(uint32x4, u32) +OPENCV_HAL_IMPL_NEON_UNPACKS(int32x4, s32) +OPENCV_HAL_IMPL_NEON_UNPACKS(float32x4, f32) +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_UNPACKS(float64x2, f64) +#endif + +inline v_uint8x16 v_reverse(const v_uint8x16 &a) +{ + uint8x16_t vec = vrev64q_u8(a.val); + return v_uint8x16(vextq_u8(vec, vec, 8)); +} + +inline v_int8x16 v_reverse(const v_int8x16 &a) +{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } + +inline v_uint16x8 v_reverse(const v_uint16x8 &a) +{ + uint16x8_t vec = vrev64q_u16(a.val); + return v_uint16x8(vextq_u16(vec, vec, 4)); +} + +inline v_int16x8 v_reverse(const v_int16x8 &a) +{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } + +inline v_uint32x4 v_reverse(const v_uint32x4 &a) +{ + uint32x4_t vec = vrev64q_u32(a.val); + return v_uint32x4(vextq_u32(vec, vec, 2)); +} + +inline v_int32x4 v_reverse(const v_int32x4 &a) +{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_float32x4 v_reverse(const v_float32x4 &a) +{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_uint64x2 v_reverse(const v_uint64x2 &a) +{ + uint64x2_t vec = a.val; + uint64x1_t vec_lo = vget_low_u64(vec); + uint64x1_t vec_hi = vget_high_u64(vec); + return v_uint64x2(vcombine_u64(vec_hi, vec_lo)); +} + +inline v_int64x2 v_reverse(const v_int64x2 &a) +{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } + +#if CV_SIMD128_64F +inline v_float64x2 v_reverse(const v_float64x2 &a) +{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } +#endif + +#define OPENCV_HAL_IMPL_NEON_EXTRACT(_Tpvec, suffix) \ +template \ +inline v_##_Tpvec v_extract(const v_##_Tpvec& a, const v_##_Tpvec& b) \ +{ \ + return v_##_Tpvec(vextq_##suffix(a.val, b.val, s)); \ +} + +OPENCV_HAL_IMPL_NEON_EXTRACT(uint8x16, u8) +OPENCV_HAL_IMPL_NEON_EXTRACT(int8x16, s8) +OPENCV_HAL_IMPL_NEON_EXTRACT(uint16x8, u16) +OPENCV_HAL_IMPL_NEON_EXTRACT(int16x8, s16) +OPENCV_HAL_IMPL_NEON_EXTRACT(uint32x4, u32) +OPENCV_HAL_IMPL_NEON_EXTRACT(int32x4, s32) +OPENCV_HAL_IMPL_NEON_EXTRACT(uint64x2, u64) +OPENCV_HAL_IMPL_NEON_EXTRACT(int64x2, s64) +OPENCV_HAL_IMPL_NEON_EXTRACT(float32x4, f32) +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_EXTRACT(float64x2, f64) +#endif + +#define OPENCV_HAL_IMPL_NEON_EXTRACT_N(_Tpvec, _Tp, suffix) \ +template inline _Tp v_extract_n(_Tpvec v) { return vgetq_lane_##suffix(v.val, i); } + +OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_uint8x16, uchar, u8) +OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_int8x16, schar, s8) +OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_uint16x8, ushort, u16) +OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_int16x8, short, s16) +OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_uint32x4, uint, u32) +OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_int32x4, int, s32) +OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_uint64x2, uint64, u64) +OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_int64x2, int64, s64) +OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_float32x4, float, f32) +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_float64x2, double, f64) +#endif + +#define OPENCV_HAL_IMPL_NEON_BROADCAST(_Tpvec, _Tp, suffix) \ +template inline _Tpvec v_broadcast_element(_Tpvec v) { _Tp t = v_extract_n(v); return v_setall_##suffix(t); } + +OPENCV_HAL_IMPL_NEON_BROADCAST(v_uint8x16, uchar, u8) +OPENCV_HAL_IMPL_NEON_BROADCAST(v_int8x16, schar, s8) +OPENCV_HAL_IMPL_NEON_BROADCAST(v_uint16x8, ushort, u16) +OPENCV_HAL_IMPL_NEON_BROADCAST(v_int16x8, short, s16) +OPENCV_HAL_IMPL_NEON_BROADCAST(v_uint32x4, uint, u32) +OPENCV_HAL_IMPL_NEON_BROADCAST(v_int32x4, int, s32) +OPENCV_HAL_IMPL_NEON_BROADCAST(v_uint64x2, uint64, u64) +OPENCV_HAL_IMPL_NEON_BROADCAST(v_int64x2, int64, s64) +OPENCV_HAL_IMPL_NEON_BROADCAST(v_float32x4, float, f32) +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_BROADCAST(v_float64x2, double, f64) +#endif + +#if CV_SIMD128_64F +inline v_int32x4 v_round(const v_float32x4& a) +{ + float32x4_t a_ = a.val; + int32x4_t result; +#if defined _MSC_VER + result = vcvtnq_s32_f32(a_); +#else + __asm__ ("fcvtns %0.4s, %1.4s" + : "=w"(result) + : "w"(a_) + : /* No clobbers */); +#endif + return v_int32x4(result); +} +#else +inline v_int32x4 v_round(const v_float32x4& a) +{ + // See https://github.com/opencv/opencv/pull/24271#issuecomment-1867318007 + float32x4_t delta = vdupq_n_f32(12582912.0f); + return v_int32x4(vcvtq_s32_f32(vsubq_f32(vaddq_f32(a.val, delta), delta))); +} +#endif +inline v_int32x4 v_floor(const v_float32x4& a) +{ + int32x4_t a1 = vcvtq_s32_f32(a.val); + uint32x4_t mask = vcgtq_f32(vcvtq_f32_s32(a1), a.val); + return v_int32x4(vaddq_s32(a1, vreinterpretq_s32_u32(mask))); +} + +inline v_int32x4 v_ceil(const v_float32x4& a) +{ + int32x4_t a1 = vcvtq_s32_f32(a.val); + uint32x4_t mask = vcgtq_f32(a.val, vcvtq_f32_s32(a1)); + return v_int32x4(vsubq_s32(a1, vreinterpretq_s32_u32(mask))); +} + +inline v_int32x4 v_trunc(const v_float32x4& a) +{ return v_int32x4(vcvtq_s32_f32(a.val)); } + +#if CV_SIMD128_64F +inline v_int32x4 v_round(const v_float64x2& a) +{ + static const int32x2_t zero = vdup_n_s32(0); + return v_int32x4(vcombine_s32(vmovn_s64(vcvtnq_s64_f64(a.val)), zero)); +} + +inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) +{ + return v_int32x4(vcombine_s32(vmovn_s64(vcvtnq_s64_f64(a.val)), vmovn_s64(vcvtnq_s64_f64(b.val)))); +} + +inline v_int32x4 v_floor(const v_float64x2& a) +{ + static const int32x2_t zero = vdup_n_s32(0); + int64x2_t a1 = vcvtq_s64_f64(a.val); + uint64x2_t mask = vcgtq_f64(vcvtq_f64_s64(a1), a.val); + a1 = vaddq_s64(a1, vreinterpretq_s64_u64(mask)); + return v_int32x4(vcombine_s32(vmovn_s64(a1), zero)); +} + +inline v_int32x4 v_ceil(const v_float64x2& a) +{ + static const int32x2_t zero = vdup_n_s32(0); + int64x2_t a1 = vcvtq_s64_f64(a.val); + uint64x2_t mask = vcgtq_f64(a.val, vcvtq_f64_s64(a1)); + a1 = vsubq_s64(a1, vreinterpretq_s64_u64(mask)); + return v_int32x4(vcombine_s32(vmovn_s64(a1), zero)); +} + +inline v_int32x4 v_trunc(const v_float64x2& a) +{ + static const int32x2_t zero = vdup_n_s32(0); + return v_int32x4(vcombine_s32(vmovn_s64(vcvtaq_s64_f64(a.val)), zero)); +} +#endif + +#if CV_NEON_AARCH64 +#define OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(_Tpvec, suffix) \ +inline void v_transpose4x4(const v_##_Tpvec& a0, const v_##_Tpvec& a1, \ + const v_##_Tpvec& a2, const v_##_Tpvec& a3, \ + v_##_Tpvec& b0, v_##_Tpvec& b1, \ + v_##_Tpvec& b2, v_##_Tpvec& b3) \ +{ \ + /* -- Pass 1: 64b transpose */ \ + _Tpvec##_t t0 = vreinterpretq_##suffix##32_##suffix##64( \ + vtrn1q_##suffix##64(vreinterpretq_##suffix##64_##suffix##32(a0.val), \ + vreinterpretq_##suffix##64_##suffix##32(a2.val))); \ + _Tpvec##_t t1 = vreinterpretq_##suffix##32_##suffix##64( \ + vtrn1q_##suffix##64(vreinterpretq_##suffix##64_##suffix##32(a1.val), \ + vreinterpretq_##suffix##64_##suffix##32(a3.val))); \ + _Tpvec##_t t2 = vreinterpretq_##suffix##32_##suffix##64( \ + vtrn2q_##suffix##64(vreinterpretq_##suffix##64_##suffix##32(a0.val), \ + vreinterpretq_##suffix##64_##suffix##32(a2.val))); \ + _Tpvec##_t t3 = vreinterpretq_##suffix##32_##suffix##64( \ + vtrn2q_##suffix##64(vreinterpretq_##suffix##64_##suffix##32(a1.val), \ + vreinterpretq_##suffix##64_##suffix##32(a3.val))); \ + /* -- Pass 2: 32b transpose */ \ + b0.val = vtrn1q_##suffix##32(t0, t1); \ + b1.val = vtrn2q_##suffix##32(t0, t1); \ + b2.val = vtrn1q_##suffix##32(t2, t3); \ + b3.val = vtrn2q_##suffix##32(t2, t3); \ +} + +OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(uint32x4, u) +OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(int32x4, s) +OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(float32x4, f) +#else // #if CV_NEON_AARCH64 +#define OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(_Tpvec, suffix) \ +inline void v_transpose4x4(const v_##_Tpvec& a0, const v_##_Tpvec& a1, \ + const v_##_Tpvec& a2, const v_##_Tpvec& a3, \ + v_##_Tpvec& b0, v_##_Tpvec& b1, \ + v_##_Tpvec& b2, v_##_Tpvec& b3) \ +{ \ + /* m00 m01 m02 m03 */ \ + /* m10 m11 m12 m13 */ \ + /* m20 m21 m22 m23 */ \ + /* m30 m31 m32 m33 */ \ + _Tpvec##x2_t t0 = vtrnq_##suffix(a0.val, a1.val); \ + _Tpvec##x2_t t1 = vtrnq_##suffix(a2.val, a3.val); \ + /* m00 m10 m02 m12 */ \ + /* m01 m11 m03 m13 */ \ + /* m20 m30 m22 m32 */ \ + /* m21 m31 m23 m33 */ \ + b0.val = vcombine_##suffix(vget_low_##suffix(t0.val[0]), vget_low_##suffix(t1.val[0])); \ + b1.val = vcombine_##suffix(vget_low_##suffix(t0.val[1]), vget_low_##suffix(t1.val[1])); \ + b2.val = vcombine_##suffix(vget_high_##suffix(t0.val[0]), vget_high_##suffix(t1.val[0])); \ + b3.val = vcombine_##suffix(vget_high_##suffix(t0.val[1]), vget_high_##suffix(t1.val[1])); \ +} + +OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(uint32x4, u32) +OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(int32x4, s32) +OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(float32x4, f32) +#endif // #if CV_NEON_AARCH64 + +#define OPENCV_HAL_IMPL_NEON_INTERLEAVED(_Tpvec, _Tp, suffix) \ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b) \ +{ \ + _Tpvec##x2_t v = vld2q_##suffix(ptr); \ + a.val = v.val[0]; \ + b.val = v.val[1]; \ +} \ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, v_##_Tpvec& c) \ +{ \ + _Tpvec##x3_t v = vld3q_##suffix(ptr); \ + a.val = v.val[0]; \ + b.val = v.val[1]; \ + c.val = v.val[2]; \ +} \ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, \ + v_##_Tpvec& c, v_##_Tpvec& d) \ +{ \ + _Tpvec##x4_t v = vld4q_##suffix(ptr); \ + a.val = v.val[0]; \ + b.val = v.val[1]; \ + c.val = v.val[2]; \ + d.val = v.val[3]; \ +} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + _Tpvec##x2_t v; \ + v.val[0] = a.val; \ + v.val[1] = b.val; \ + vst2q_##suffix(ptr, v); \ +} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ + const v_##_Tpvec& c, hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + _Tpvec##x3_t v; \ + v.val[0] = a.val; \ + v.val[1] = b.val; \ + v.val[2] = c.val; \ + vst3q_##suffix(ptr, v); \ +} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ + const v_##_Tpvec& c, const v_##_Tpvec& d, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec##x4_t v; \ + v.val[0] = a.val; \ + v.val[1] = b.val; \ + v.val[2] = c.val; \ + v.val[3] = d.val; \ + vst4q_##suffix(ptr, v); \ +} + +#define OPENCV_HAL_IMPL_NEON_INTERLEAVED_INT64(tp, suffix) \ +inline void v_load_deinterleave( const tp* ptr, v_##tp##x2& a, v_##tp##x2& b ) \ +{ \ + tp##x1_t a0 = vld1_##suffix(ptr); \ + tp##x1_t b0 = vld1_##suffix(ptr + 1); \ + tp##x1_t a1 = vld1_##suffix(ptr + 2); \ + tp##x1_t b1 = vld1_##suffix(ptr + 3); \ + a = v_##tp##x2(vcombine_##suffix(a0, a1)); \ + b = v_##tp##x2(vcombine_##suffix(b0, b1)); \ +} \ + \ +inline void v_load_deinterleave( const tp* ptr, v_##tp##x2& a, \ + v_##tp##x2& b, v_##tp##x2& c ) \ +{ \ + tp##x1_t a0 = vld1_##suffix(ptr); \ + tp##x1_t b0 = vld1_##suffix(ptr + 1); \ + tp##x1_t c0 = vld1_##suffix(ptr + 2); \ + tp##x1_t a1 = vld1_##suffix(ptr + 3); \ + tp##x1_t b1 = vld1_##suffix(ptr + 4); \ + tp##x1_t c1 = vld1_##suffix(ptr + 5); \ + a = v_##tp##x2(vcombine_##suffix(a0, a1)); \ + b = v_##tp##x2(vcombine_##suffix(b0, b1)); \ + c = v_##tp##x2(vcombine_##suffix(c0, c1)); \ +} \ + \ +inline void v_load_deinterleave( const tp* ptr, v_##tp##x2& a, v_##tp##x2& b, \ + v_##tp##x2& c, v_##tp##x2& d ) \ +{ \ + tp##x1_t a0 = vld1_##suffix(ptr); \ + tp##x1_t b0 = vld1_##suffix(ptr + 1); \ + tp##x1_t c0 = vld1_##suffix(ptr + 2); \ + tp##x1_t d0 = vld1_##suffix(ptr + 3); \ + tp##x1_t a1 = vld1_##suffix(ptr + 4); \ + tp##x1_t b1 = vld1_##suffix(ptr + 5); \ + tp##x1_t c1 = vld1_##suffix(ptr + 6); \ + tp##x1_t d1 = vld1_##suffix(ptr + 7); \ + a = v_##tp##x2(vcombine_##suffix(a0, a1)); \ + b = v_##tp##x2(vcombine_##suffix(b0, b1)); \ + c = v_##tp##x2(vcombine_##suffix(c0, c1)); \ + d = v_##tp##x2(vcombine_##suffix(d0, d1)); \ +} \ + \ +inline void v_store_interleave( tp* ptr, const v_##tp##x2& a, const v_##tp##x2& b, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + vst1_##suffix(ptr, vget_low_##suffix(a.val)); \ + vst1_##suffix(ptr + 1, vget_low_##suffix(b.val)); \ + vst1_##suffix(ptr + 2, vget_high_##suffix(a.val)); \ + vst1_##suffix(ptr + 3, vget_high_##suffix(b.val)); \ +} \ + \ +inline void v_store_interleave( tp* ptr, const v_##tp##x2& a, \ + const v_##tp##x2& b, const v_##tp##x2& c, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + vst1_##suffix(ptr, vget_low_##suffix(a.val)); \ + vst1_##suffix(ptr + 1, vget_low_##suffix(b.val)); \ + vst1_##suffix(ptr + 2, vget_low_##suffix(c.val)); \ + vst1_##suffix(ptr + 3, vget_high_##suffix(a.val)); \ + vst1_##suffix(ptr + 4, vget_high_##suffix(b.val)); \ + vst1_##suffix(ptr + 5, vget_high_##suffix(c.val)); \ +} \ + \ +inline void v_store_interleave( tp* ptr, const v_##tp##x2& a, const v_##tp##x2& b, \ + const v_##tp##x2& c, const v_##tp##x2& d, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + vst1_##suffix(ptr, vget_low_##suffix(a.val)); \ + vst1_##suffix(ptr + 1, vget_low_##suffix(b.val)); \ + vst1_##suffix(ptr + 2, vget_low_##suffix(c.val)); \ + vst1_##suffix(ptr + 3, vget_low_##suffix(d.val)); \ + vst1_##suffix(ptr + 4, vget_high_##suffix(a.val)); \ + vst1_##suffix(ptr + 5, vget_high_##suffix(b.val)); \ + vst1_##suffix(ptr + 6, vget_high_##suffix(c.val)); \ + vst1_##suffix(ptr + 7, vget_high_##suffix(d.val)); \ +} + +OPENCV_HAL_IMPL_NEON_INTERLEAVED(uint8x16, uchar, u8) +OPENCV_HAL_IMPL_NEON_INTERLEAVED(int8x16, schar, s8) +OPENCV_HAL_IMPL_NEON_INTERLEAVED(uint16x8, ushort, u16) +OPENCV_HAL_IMPL_NEON_INTERLEAVED(int16x8, short, s16) +OPENCV_HAL_IMPL_NEON_INTERLEAVED(uint32x4, unsigned, u32) +OPENCV_HAL_IMPL_NEON_INTERLEAVED(int32x4, int, s32) +OPENCV_HAL_IMPL_NEON_INTERLEAVED(float32x4, float, f32) +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_INTERLEAVED(float64x2, double, f64) +#endif + +OPENCV_HAL_IMPL_NEON_INTERLEAVED_INT64(int64, s64) +OPENCV_HAL_IMPL_NEON_INTERLEAVED_INT64(uint64, u64) + +inline v_float32x4 v_cvt_f32(const v_int32x4& a) +{ + return v_float32x4(vcvtq_f32_s32(a.val)); +} + +#if CV_SIMD128_64F +inline v_float32x4 v_cvt_f32(const v_float64x2& a) +{ + float32x2_t zero = vdup_n_f32(0.0f); + return v_float32x4(vcombine_f32(vcvt_f32_f64(a.val), zero)); +} + +inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) +{ + return v_float32x4(vcombine_f32(vcvt_f32_f64(a.val), vcvt_f32_f64(b.val))); +} + +inline v_float64x2 v_cvt_f64(const v_int32x4& a) +{ + return v_float64x2(vcvt_f64_f32(vcvt_f32_s32(vget_low_s32(a.val)))); +} + +inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) +{ + return v_float64x2(vcvt_f64_f32(vcvt_f32_s32(vget_high_s32(a.val)))); +} + +inline v_float64x2 v_cvt_f64(const v_float32x4& a) +{ + return v_float64x2(vcvt_f64_f32(vget_low_f32(a.val))); +} + +inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) +{ + return v_float64x2(vcvt_f64_f32(vget_high_f32(a.val))); +} + +inline v_float64x2 v_cvt_f64(const v_int64x2& a) +{ return v_float64x2(vcvtq_f64_s64(a.val)); } + +#endif + +////////////// Lookup table access //////////////////// + +inline v_int8x16 v_lut(const schar* tab, const int* idx) +{ + schar CV_DECL_ALIGNED(32) elems[16] = + { + tab[idx[ 0]], + tab[idx[ 1]], + tab[idx[ 2]], + tab[idx[ 3]], + tab[idx[ 4]], + tab[idx[ 5]], + tab[idx[ 6]], + tab[idx[ 7]], + tab[idx[ 8]], + tab[idx[ 9]], + tab[idx[10]], + tab[idx[11]], + tab[idx[12]], + tab[idx[13]], + tab[idx[14]], + tab[idx[15]] + }; + return v_int8x16(vld1q_s8(elems)); +} +inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx) +{ + schar CV_DECL_ALIGNED(32) elems[16] = + { + tab[idx[0]], + tab[idx[0] + 1], + tab[idx[1]], + tab[idx[1] + 1], + tab[idx[2]], + tab[idx[2] + 1], + tab[idx[3]], + tab[idx[3] + 1], + tab[idx[4]], + tab[idx[4] + 1], + tab[idx[5]], + tab[idx[5] + 1], + tab[idx[6]], + tab[idx[6] + 1], + tab[idx[7]], + tab[idx[7] + 1] + }; + return v_int8x16(vld1q_s8(elems)); +} +inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) +{ + schar CV_DECL_ALIGNED(32) elems[16] = + { + tab[idx[0]], + tab[idx[0] + 1], + tab[idx[0] + 2], + tab[idx[0] + 3], + tab[idx[1]], + tab[idx[1] + 1], + tab[idx[1] + 2], + tab[idx[1] + 3], + tab[idx[2]], + tab[idx[2] + 1], + tab[idx[2] + 2], + tab[idx[2] + 3], + tab[idx[3]], + tab[idx[3] + 1], + tab[idx[3] + 2], + tab[idx[3] + 3] + }; + return v_int8x16(vld1q_s8(elems)); +} +inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((schar*)tab, idx)); } +inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((schar*)tab, idx)); } +inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((schar*)tab, idx)); } + +inline v_int16x8 v_lut(const short* tab, const int* idx) +{ + short CV_DECL_ALIGNED(32) elems[8] = + { + tab[idx[0]], + tab[idx[1]], + tab[idx[2]], + tab[idx[3]], + tab[idx[4]], + tab[idx[5]], + tab[idx[6]], + tab[idx[7]] + }; + return v_int16x8(vld1q_s16(elems)); +} +inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) +{ + short CV_DECL_ALIGNED(32) elems[8] = + { + tab[idx[0]], + tab[idx[0] + 1], + tab[idx[1]], + tab[idx[1] + 1], + tab[idx[2]], + tab[idx[2] + 1], + tab[idx[3]], + tab[idx[3] + 1] + }; + return v_int16x8(vld1q_s16(elems)); +} +inline v_int16x8 v_lut_quads(const short* tab, const int* idx) +{ + return v_int16x8(vcombine_s16(vld1_s16(tab + idx[0]), vld1_s16(tab + idx[1]))); +} +inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((short*)tab, idx)); } +inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((short*)tab, idx)); } +inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((short*)tab, idx)); } + +inline v_int32x4 v_lut(const int* tab, const int* idx) +{ + int CV_DECL_ALIGNED(32) elems[4] = + { + tab[idx[0]], + tab[idx[1]], + tab[idx[2]], + tab[idx[3]] + }; + return v_int32x4(vld1q_s32(elems)); +} +inline v_int32x4 v_lut_pairs(const int* tab, const int* idx) +{ + return v_int32x4(vcombine_s32(vld1_s32(tab + idx[0]), vld1_s32(tab + idx[1]))); +} +inline v_int32x4 v_lut_quads(const int* tab, const int* idx) +{ + return v_int32x4(vld1q_s32(tab + idx[0])); +} +inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((int*)tab, idx)); } +inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((int*)tab, idx)); } +inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((int*)tab, idx)); } + +inline v_int64x2 v_lut(const int64_t* tab, const int* idx) +{ + return v_int64x2(vcombine_s64(vcreate_s64(tab[idx[0]]), vcreate_s64(tab[idx[1]]))); +} +inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) +{ + return v_int64x2(vld1q_s64(tab + idx[0])); +} +inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } +inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } + +inline v_float32x4 v_lut(const float* tab, const int* idx) +{ + float CV_DECL_ALIGNED(32) elems[4] = + { + tab[idx[0]], + tab[idx[1]], + tab[idx[2]], + tab[idx[3]] + }; + return v_float32x4(vld1q_f32(elems)); +} +inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) +{ + typedef uint64 CV_DECL_ALIGNED(1) unaligned_uint64; + + uint64 CV_DECL_ALIGNED(32) elems[2] = + { + *(unaligned_uint64*)(tab + idx[0]), + *(unaligned_uint64*)(tab + idx[1]) + }; + return v_float32x4(vreinterpretq_f32_u64(vld1q_u64(elems))); +} +inline v_float32x4 v_lut_quads(const float* tab, const int* idx) +{ + return v_float32x4(vld1q_f32(tab + idx[0])); +} + +inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) +{ + int CV_DECL_ALIGNED(32) elems[4] = + { + tab[vgetq_lane_s32(idxvec.val, 0)], + tab[vgetq_lane_s32(idxvec.val, 1)], + tab[vgetq_lane_s32(idxvec.val, 2)], + tab[vgetq_lane_s32(idxvec.val, 3)] + }; + return v_int32x4(vld1q_s32(elems)); +} + +inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) +{ + unsigned CV_DECL_ALIGNED(32) elems[4] = + { + tab[vgetq_lane_s32(idxvec.val, 0)], + tab[vgetq_lane_s32(idxvec.val, 1)], + tab[vgetq_lane_s32(idxvec.val, 2)], + tab[vgetq_lane_s32(idxvec.val, 3)] + }; + return v_uint32x4(vld1q_u32(elems)); +} + +inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) +{ + float CV_DECL_ALIGNED(32) elems[4] = + { + tab[vgetq_lane_s32(idxvec.val, 0)], + tab[vgetq_lane_s32(idxvec.val, 1)], + tab[vgetq_lane_s32(idxvec.val, 2)], + tab[vgetq_lane_s32(idxvec.val, 3)] + }; + return v_float32x4(vld1q_f32(elems)); +} + +inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) +{ + /*int CV_DECL_ALIGNED(32) idx[4]; + v_store(idx, idxvec); + + float32x4_t xy02 = vcombine_f32(vld1_f32(tab + idx[0]), vld1_f32(tab + idx[2])); + float32x4_t xy13 = vcombine_f32(vld1_f32(tab + idx[1]), vld1_f32(tab + idx[3])); + + float32x4x2_t xxyy = vuzpq_f32(xy02, xy13); + x = v_float32x4(xxyy.val[0]); + y = v_float32x4(xxyy.val[1]);*/ + int CV_DECL_ALIGNED(32) idx[4]; + v_store_aligned(idx, idxvec); + + x = v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); + y = v_float32x4(tab[idx[0]+1], tab[idx[1]+1], tab[idx[2]+1], tab[idx[3]+1]); +} + +inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) +{ + return v_int8x16(vcombine_s8(vtbl1_s8(vget_low_s8(vec.val), vcreate_s8(0x0705060403010200)), vtbl1_s8(vget_high_s8(vec.val), vcreate_s8(0x0705060403010200)))); +} +inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } +inline v_int8x16 v_interleave_quads(const v_int8x16& vec) +{ + return v_int8x16(vcombine_s8(vtbl1_s8(vget_low_s8(vec.val), vcreate_s8(0x0703060205010400)), vtbl1_s8(vget_high_s8(vec.val), vcreate_s8(0x0703060205010400)))); +} +inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) +{ + return v_int16x8(vreinterpretq_s16_s8(vcombine_s8(vtbl1_s8(vget_low_s8(vreinterpretq_s8_s16(vec.val)), vcreate_s8(0x0706030205040100)), vtbl1_s8(vget_high_s8(vreinterpretq_s8_s16(vec.val)), vcreate_s8(0x0706030205040100))))); +} +inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } +inline v_int16x8 v_interleave_quads(const v_int16x8& vec) +{ + int16x4x2_t res = vzip_s16(vget_low_s16(vec.val), vget_high_s16(vec.val)); + return v_int16x8(vcombine_s16(res.val[0], res.val[1])); +} +inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) +{ + int32x2x2_t res = vzip_s32(vget_low_s32(vec.val), vget_high_s32(vec.val)); + return v_int32x4(vcombine_s32(res.val[0], res.val[1])); +} +inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } +inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } + +inline v_int8x16 v_pack_triplets(const v_int8x16& vec) +{ + return v_int8x16(vextq_s8(vcombine_s8(vtbl1_s8(vget_low_s8(vec.val), vcreate_s8(0x0605040201000000)), vtbl1_s8(vget_high_s8(vec.val), vcreate_s8(0x0807060504020100))), vdupq_n_s8(0), 2)); +} +inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_pack_triplets(const v_int16x8& vec) +{ + return v_int16x8(vreinterpretq_s16_s8(vextq_s8(vcombine_s8(vtbl1_s8(vget_low_s8(vreinterpretq_s8_s16(vec.val)), vcreate_s8(0x0504030201000000)), vget_high_s8(vreinterpretq_s8_s16(vec.val))), vdupq_n_s8(0), 2))); +} +inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } +inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } +inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } + +#if CV_SIMD128_64F +inline v_float64x2 v_lut(const double* tab, const int* idx) +{ + double CV_DECL_ALIGNED(32) elems[2] = + { + tab[idx[0]], + tab[idx[1]] + }; + return v_float64x2(vld1q_f64(elems)); +} + +inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) +{ + return v_float64x2(vld1q_f64(tab + idx[0])); +} + +inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) +{ + double CV_DECL_ALIGNED(32) elems[2] = + { + tab[vgetq_lane_s32(idxvec.val, 0)], + tab[vgetq_lane_s32(idxvec.val, 1)], + }; + return v_float64x2(vld1q_f64(elems)); +} + +inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) +{ + int CV_DECL_ALIGNED(32) idx[4]; + v_store_aligned(idx, idxvec); + + x = v_float64x2(tab[idx[0]], tab[idx[1]]); + y = v_float64x2(tab[idx[0]+1], tab[idx[1]+1]); +} +#endif + +////// FP16 support /////// +#if CV_FP16 +inline v_float32x4 v_load_expand(const hfloat* ptr) +{ + float16x4_t v = + #ifndef vld1_f16 // APPLE compiler defines vld1_f16 as macro + (float16x4_t)vld1_s16((const short*)ptr); + #else + vld1_f16((const __fp16*)ptr); + #endif + return v_float32x4(vcvt_f32_f16(v)); +} + +inline void v_pack_store(hfloat* ptr, const v_float32x4& v) +{ + float16x4_t hv = vcvt_f16_f32(v.val); + + #ifndef vst1_f16 // APPLE compiler defines vst1_f16 as macro + vst1_s16((short*)ptr, (int16x4_t)hv); + #else + vst1_f16((__fp16*)ptr, hv); + #endif +} +#else +inline v_float32x4 v_load_expand(const hfloat* ptr) +{ + const int N = 4; + float buf[N]; + for( int i = 0; i < N; i++ ) buf[i] = (float)ptr[i]; + return v_load(buf); +} + +inline void v_pack_store(hfloat* ptr, const v_float32x4& v) +{ + const int N = 4; + float buf[N]; + v_store(buf, v); + for( int i = 0; i < N; i++ ) ptr[i] = hfloat(buf[i]); +} +#endif + +inline void v_cleanup() {} + +#include "intrin_math.hpp" +#if defined(CV_SIMD_FP16) && CV_SIMD_FP16 +inline v_float16x8 v_exp(const v_float16x8& x) { return v_exp_default_16f(x); } +inline v_float16x8 v_log(const v_float16x8& x) { return v_log_default_16f(x); } +inline void v_sincos(const v_float16x8& x, v_float16x8& s, v_float16x8& c) { v_sincos_default_16f(x, s, c); } +inline v_float16x8 v_sin(const v_float16x8& x) { return v_sin_default_16f(x); } +inline v_float16x8 v_cos(const v_float16x8& x) { return v_cos_default_16f(x); } +#endif +inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } +inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } +inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } +inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } +inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } +inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } +#if CV_SIMD128_64F +inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } +inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } +inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } +inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } +inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } +#endif + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_rvv071.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_rvv071.hpp index 146335dc01..bcd2662082 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_rvv071.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_rvv071.hpp @@ -1,2888 +1,2888 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -// Copyright (C) 2015, PingTouGe Semiconductor Co., Ltd., all rights reserved. - -#ifndef OPENCV_HAL_INTRIN_RISCVV_HPP -#define OPENCV_HAL_INTRIN_RISCVV_HPP - -#include -#include -#include "opencv2/core/utility.hpp" - -namespace cv -{ - -//! @cond IGNORED - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -#define CV_SIMD128 1 -#define CV_SIMD128_64F 1 -//////////// Types //////////// -struct v_uint8x16 -{ - typedef uchar lane_type; - enum { nlanes = 16 }; - - v_uint8x16() {} - explicit v_uint8x16(vuint8m1_t v) : val(v) {} - v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, - uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) - { - uchar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; - val = (vuint8m1_t)vle8_v_u8m1((unsigned char*)v, 16); - } - uchar get0() const - { - return vmv_x_s_u8m1_u8(val); - } - - vuint8m1_t val; -}; - -struct v_int8x16 -{ - typedef schar lane_type; - enum { nlanes = 16 }; - - v_int8x16() {} - explicit v_int8x16(vint8m1_t v) : val(v) {} - v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, - schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) - { - schar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; - val = (vint8m1_t)vle8_v_i8m1((schar*)v, 16); - } - schar get0() const - { - return vmv_x_s_i8m1_i8(val); - } - - vint8m1_t val; -}; - -struct v_uint16x8 -{ - typedef ushort lane_type; - enum { nlanes = 8 }; - - v_uint16x8() {} - explicit v_uint16x8(vuint16m1_t v) : val(v) {} - v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) - { - ushort v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; - val = (vuint16m1_t)vle16_v_u16m1((unsigned short*)v, 8); - } - ushort get0() const - { - return vmv_x_s_u16m1_u16(val); - } - - vuint16m1_t val; -}; - -struct v_int16x8 -{ - typedef short lane_type; - enum { nlanes = 8 }; - - v_int16x8() {} - explicit v_int16x8(vint16m1_t v) : val(v) {} - v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) - { - short v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; - val = (vint16m1_t)vle16_v_i16m1((signed short*)v, 8); - } - short get0() const - { - return vmv_x_s_i16m1_i16(val); - } - - vint16m1_t val; -}; - -struct v_uint32x4 -{ - typedef unsigned lane_type; - enum { nlanes = 4 }; - - v_uint32x4() {} - explicit v_uint32x4(vuint32m1_t v) : val(v) {} - v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) - { - unsigned v[] = {v0, v1, v2, v3}; - val = (vuint32m1_t)vle32_v_u32m1((unsigned int*)v, 4); - } - unsigned get0() const - { - return vmv_x_s_u32m1_u32(val); - } - - vuint32m1_t val; -}; - -struct v_int32x4 -{ - typedef int lane_type; - enum { nlanes = 4 }; - - v_int32x4() {} - explicit v_int32x4(vint32m1_t v) : val(v) {} - v_int32x4(int v0, int v1, int v2, int v3) - { - int v[] = {v0, v1, v2, v3}; - val = (vint32m1_t)vle32_v_i32m1((signed int*)v, 4); - } - int get0() const - { - return vmv_x_s_i32m1_i32(val); - } - vint32m1_t val; -}; - -struct v_float32x4 -{ - typedef float lane_type; - enum { nlanes = 4 }; - - v_float32x4() {} - explicit v_float32x4(vfloat32m1_t v) : val(v) {} - v_float32x4(float v0, float v1, float v2, float v3) - { - float v[] = {v0, v1, v2, v3}; - val = (vfloat32m1_t)vle32_v_f32m1((float*)v, 4); - } - float get0() const - { - return vfmv_f_s_f32m1_f32(val); - } - vfloat32m1_t val; -}; - -struct v_uint64x2 -{ - typedef uint64 lane_type; - enum { nlanes = 2 }; - - v_uint64x2() {} - explicit v_uint64x2(vuint64m1_t v) : val(v) {} - v_uint64x2(uint64 v0, uint64 v1) - { - uint64 v[] = {v0, v1}; - val = (vuint64m1_t)vle64_v_u64m1((unsigned long*)v, 2); - } - uint64 get0() const - { - return vmv_x_s_u64m1_u64(val); - } - vuint64m1_t val; -}; - -struct v_int64x2 -{ - typedef int64 lane_type; - enum { nlanes = 2 }; - - v_int64x2() {} - explicit v_int64x2(vint64m1_t v) : val(v) {} - v_int64x2(int64 v0, int64 v1) - { - int64 v[] = {v0, v1}; - val = (vint64m1_t)vle64_v_i64m1((long*)v, 2); - } - int64 get0() const - { - return vmv_x_s_i64m1_i64(val); - } - vint64m1_t val; -}; - -struct v_float64x2 -{ - typedef double lane_type; - enum { nlanes = 2 }; - - v_float64x2() {} - explicit v_float64x2(vfloat64m1_t v) : val(v) {} - v_float64x2(double v0, double v1) - { - double v[] = {v0, v1}; - val = (vfloat64m1_t)vle64_v_f64m1((double*)v, 2); - } - double get0() const - { - return vfmv_f_s_f64m1_f64(val); - } - vfloat64m1_t val; -}; -/* -#define OPENCV_HAL_IMPL_RISCVV_INIT(_Tpv, _Tp, suffix) \ -inline _Tp##m1_t vreinterpret_v_##suffix##m1_##suffix##m1(_Tp##m1_t v) { return v; } \ -inline v_uint8x16 v_reinterpret_as_u8(const v_##_Tpv& v) { return v_uint8x16((vuint8m1_t)(v.val)); } \ -inline v_int8x16 v_reinterpret_as_s8(const v_##_Tpv& v) { return v_int8x16((vint8m1_t)(v.val)); } \ -inline v_uint16x8 v_reinterpret_as_u16(const v_##_Tpv& v) { return v_uint16x8((vuint16m1_t)(v.val)); } \ -inline v_int16x8 v_reinterpret_as_s16(const v_##_Tpv& v) { return v_int16x8(vreinterpret_v_i8m1_i16m1(v.val)); } \ -inline v_uint32x4 v_reinterpret_as_u32(const v_##_Tpv& v) { return v_uint32x4((vuint32m1_t)(v.val)); } \ -inline v_int32x4 v_reinterpret_as_s32(const v_##_Tpv& v) { return v_int32x4((vint32m1_t)(v.val)); } \ -inline v_uint64x2 v_reinterpret_as_u64(const v_##_Tpv& v) { return v_uint64x2((vuint64m1_t)(v.val)); } \ -inline v_int64x2 v_reinterpret_as_s64(const v_##_Tpv& v) { return v_int64x2((vint64m1_t)(v.val)); } \ -inline v_float32x4 v_reinterpret_as_f32(const v_##_Tpv& v) { return v_float32x4((vfloat32m1_t)(v.val)); }\ -inline v_float64x2 v_reinterpret_as_f64(const v_##_Tpv& v) { return v_float64x2((vfloat64m1_t)(v.val)); } - - -OPENCV_HAL_IMPL_RISCVV_INIT(uint8x16, vuint8, u8) -OPENCV_HAL_IMPL_RISCVV_INIT(int8x16, vint8, i8) -OPENCV_HAL_IMPL_RISCVV_INIT(uint16x8, vuint16, u16) -OPENCV_HAL_IMPL_RISCVV_INIT(int16x8, vint16, i16) -OPENCV_HAL_IMPL_RISCVV_INIT(uint32x4, vuint32, u32) -OPENCV_HAL_IMPL_RISCVV_INIT(int32x4, vint32, i32) -OPENCV_HAL_IMPL_RISCVV_INIT(uint64x2, vuint64, u64) -OPENCV_HAL_IMPL_RISCVV_INIT(int64x2, vint64, i64) -OPENCV_HAL_IMPL_RISCVV_INIT(float64x2, vfloat64, f64) -OPENCV_HAL_IMPL_RISCVV_INIT(float32x4, vfloat32, f32) -*/ -inline v_uint8x16 v_reinterpret_as_u8(const v_uint8x16& v) { return v_uint8x16(v.val); } -inline v_int8x16 v_reinterpret_as_s8(const v_uint8x16& v) { return v_int8x16(vreinterpret_v_u8m1_i8m1(v.val)); } -inline v_uint16x8 v_reinterpret_as_u16(const v_uint8x16& v) { return v_uint16x8(vreinterpret_v_u8m1_u16m1(v.val)); } -inline v_int16x8 v_reinterpret_as_s16(const v_uint8x16& v) { return v_int16x8(vreinterpret_v_u16m1_i16m1(vreinterpret_v_u8m1_u16m1(v.val))); } -inline v_uint32x4 v_reinterpret_as_u32(const v_uint8x16& v) { return v_uint32x4(vreinterpret_v_u8m1_u32m1(v.val)); } -inline v_int32x4 v_reinterpret_as_s32(const v_uint8x16& v) { return v_int32x4(vreinterpret_v_u32m1_i32m1(vreinterpret_v_u8m1_u32m1(v.val))); } -inline v_uint64x2 v_reinterpret_as_u64(const v_uint8x16& v) { return v_uint64x2(vreinterpret_v_u8m1_u64m1(v.val)); } -inline v_int64x2 v_reinterpret_as_s64(const v_uint8x16& v) { return v_int64x2(vreinterpret_v_u64m1_i64m1(vreinterpret_v_u8m1_u64m1(v.val))); } -inline v_float32x4 v_reinterpret_as_f32(const v_uint8x16& v) { return v_float32x4(vreinterpret_v_u32m1_f32m1(vreinterpret_v_u8m1_u32m1(v.val))); } -inline v_float64x2 v_reinterpret_as_f64(const v_uint8x16& v) { return v_float64x2(vreinterpret_v_u64m1_f64m1(vreinterpret_v_u8m1_u64m1(v.val))); } - -inline v_uint8x16 v_reinterpret_as_u8(const v_int8x16& v) { return v_uint8x16(vreinterpret_v_i8m1_u8m1(v.val)); } -inline v_int8x16 v_reinterpret_as_s8(const v_int8x16& v) { return v_int8x16(v.val); } -inline v_uint16x8 v_reinterpret_as_u16(const v_int8x16& v) { return v_uint16x8(vreinterpret_v_u8m1_u16m1(vreinterpret_v_i8m1_u8m1(v.val))); } -inline v_int16x8 v_reinterpret_as_s16(const v_int8x16& v) { return v_int16x8(vreinterpret_v_i8m1_i16m1(v.val)); } -inline v_uint32x4 v_reinterpret_as_u32(const v_int8x16& v) { return v_uint32x4(vreinterpret_v_u8m1_u32m1(vreinterpret_v_i8m1_u8m1(v.val))); } -inline v_int32x4 v_reinterpret_as_s32(const v_int8x16& v) { return v_int32x4(vreinterpret_v_i8m1_i32m1(v.val)); } -inline v_uint64x2 v_reinterpret_as_u64(const v_int8x16& v) { return v_uint64x2(vreinterpret_v_u8m1_u64m1(vreinterpret_v_i8m1_u8m1(v.val))); } -inline v_int64x2 v_reinterpret_as_s64(const v_int8x16& v) { return v_int64x2(vreinterpret_v_i8m1_i64m1(v.val)); } -inline v_float32x4 v_reinterpret_as_f32(const v_int8x16& v) { return v_float32x4(vreinterpret_v_i32m1_f32m1(vreinterpret_v_i8m1_i32m1(v.val))); } -inline v_float64x2 v_reinterpret_as_f64(const v_int8x16& v) { return v_float64x2(vreinterpret_v_i64m1_f64m1(vreinterpret_v_i8m1_i64m1(v.val))); } - -inline v_uint8x16 v_reinterpret_as_u8(const v_uint16x8& v) { return v_uint8x16(vreinterpret_v_u16m1_u8m1(v.val)); } -inline v_int8x16 v_reinterpret_as_s8(const v_uint16x8& v) { return v_int8x16(vreinterpret_v_i16m1_i8m1(vreinterpret_v_u16m1_i16m1(v.val))); } -inline v_uint16x8 v_reinterpret_as_u16(const v_uint16x8& v) { return v_uint16x8(v.val); } -inline v_int16x8 v_reinterpret_as_s16(const v_uint16x8& v) { return v_int16x8(vreinterpret_v_u16m1_i16m1(v.val)); } -inline v_uint32x4 v_reinterpret_as_u32(const v_uint16x8& v) { return v_uint32x4(vreinterpret_v_u16m1_u32m1(v.val)); } -inline v_int32x4 v_reinterpret_as_s32(const v_uint16x8& v) { return v_int32x4(vreinterpret_v_u32m1_i32m1(vreinterpret_v_u16m1_u32m1(v.val))); } -inline v_uint64x2 v_reinterpret_as_u64(const v_uint16x8& v) { return v_uint64x2(vreinterpret_v_u16m1_u64m1(v.val)); } -inline v_int64x2 v_reinterpret_as_s64(const v_uint16x8& v) { return v_int64x2(vreinterpret_v_u64m1_i64m1(vreinterpret_v_u16m1_u64m1(v.val))); } -inline v_float32x4 v_reinterpret_as_f32(const v_uint16x8& v) { return v_float32x4(vreinterpret_v_u32m1_f32m1(vreinterpret_v_u16m1_u32m1(v.val))); } -inline v_float64x2 v_reinterpret_as_f64(const v_uint16x8& v) { return v_float64x2(vreinterpret_v_u64m1_f64m1(vreinterpret_v_u16m1_u64m1(v.val))); } - -inline v_uint8x16 v_reinterpret_as_u8(const v_int16x8& v) { return v_uint8x16(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i16m1_i8m1(v.val))); } -inline v_int8x16 v_reinterpret_as_s8(const v_int16x8& v) { return v_int8x16(vreinterpret_v_i16m1_i8m1(v.val)); } -inline v_uint16x8 v_reinterpret_as_u16(const v_int16x8& v) { return v_uint16x8(vreinterpret_v_i16m1_u16m1(v.val)); } -inline v_int16x8 v_reinterpret_as_s16(const v_int16x8& v) { return v_int16x8(v.val); } -inline v_uint32x4 v_reinterpret_as_u32(const v_int16x8& v) { return v_uint32x4(vreinterpret_v_u16m1_u32m1(vreinterpret_v_i16m1_u16m1(v.val))); } -inline v_int32x4 v_reinterpret_as_s32(const v_int16x8& v) { return v_int32x4(vreinterpret_v_i16m1_i32m1(v.val)); } -inline v_uint64x2 v_reinterpret_as_u64(const v_int16x8& v) { return v_uint64x2(vreinterpret_v_u16m1_u64m1(vreinterpret_v_i16m1_u16m1(v.val))); } -inline v_int64x2 v_reinterpret_as_s64(const v_int16x8& v) { return v_int64x2(vreinterpret_v_i16m1_i64m1(v.val)); } -inline v_float32x4 v_reinterpret_as_f32(const v_int16x8& v) { return v_float32x4(vreinterpret_v_i32m1_f32m1(vreinterpret_v_i16m1_i32m1(v.val))); } -inline v_float64x2 v_reinterpret_as_f64(const v_int16x8& v) { return v_float64x2(vreinterpret_v_i64m1_f64m1(vreinterpret_v_i16m1_i64m1(v.val))); } - -inline v_uint8x16 v_reinterpret_as_u8(const v_uint32x4& v) { return v_uint8x16(vreinterpret_v_u32m1_u8m1(v.val)); } -inline v_int8x16 v_reinterpret_as_s8(const v_uint32x4& v) { return v_int8x16(vreinterpret_v_i32m1_i8m1(vreinterpret_v_u32m1_i32m1(v.val))); } -inline v_uint16x8 v_reinterpret_as_u16(const v_uint32x4& v) { return v_uint16x8(vreinterpret_v_u32m1_u16m1(v.val)); } -inline v_int16x8 v_reinterpret_as_s16(const v_uint32x4& v) { return v_int16x8(vreinterpret_v_i32m1_i16m1(vreinterpret_v_u32m1_i32m1(v.val))); } -inline v_uint32x4 v_reinterpret_as_u32(const v_uint32x4& v) { return v_uint32x4(v.val); } -inline v_int32x4 v_reinterpret_as_s32(const v_uint32x4& v) { return v_int32x4(vreinterpret_v_u32m1_i32m1(v.val)); } -inline v_uint64x2 v_reinterpret_as_u64(const v_uint32x4& v) { return v_uint64x2(vreinterpret_v_u32m1_u64m1(v.val)); } -inline v_int64x2 v_reinterpret_as_s64(const v_uint32x4& v) { return v_int64x2(vreinterpret_v_u64m1_i64m1(vreinterpret_v_u32m1_u64m1(v.val))); } -inline v_float32x4 v_reinterpret_as_f32(const v_uint32x4& v) { return v_float32x4(vreinterpret_v_u32m1_f32m1(v.val)); } -inline v_float64x2 v_reinterpret_as_f64(const v_uint32x4& v) { return v_float64x2(vreinterpret_v_u64m1_f64m1(vreinterpret_v_u32m1_u64m1(v.val))); } - -inline v_uint8x16 v_reinterpret_as_u8(const v_int32x4& v) { return v_uint8x16(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i32m1_i8m1(v.val))); } -inline v_int8x16 v_reinterpret_as_s8(const v_int32x4& v) { return v_int8x16(vreinterpret_v_i32m1_i8m1(v.val)); } -inline v_uint16x8 v_reinterpret_as_u16(const v_int32x4& v) { return v_uint16x8(vreinterpret_v_u32m1_u16m1(vreinterpret_v_i32m1_u32m1(v.val))); } -inline v_int16x8 v_reinterpret_as_s16(const v_int32x4& v) { return v_int16x8(vreinterpret_v_i32m1_i16m1(v.val)); } -inline v_uint32x4 v_reinterpret_as_u32(const v_int32x4& v) { return v_uint32x4(vreinterpret_v_i32m1_u32m1(v.val)); } -inline v_int32x4 v_reinterpret_as_s32(const v_int32x4& v) { return v_int32x4(v.val); } -inline v_uint64x2 v_reinterpret_as_u64(const v_int32x4& v) { return v_uint64x2(vreinterpret_v_u32m1_u64m1(vreinterpret_v_i32m1_u32m1(v.val))); } -inline v_int64x2 v_reinterpret_as_s64(const v_int32x4& v) { return v_int64x2(vreinterpret_v_i32m1_i64m1(v.val)); } -inline v_float32x4 v_reinterpret_as_f32(const v_int32x4& v) { return v_float32x4(vreinterpret_v_i32m1_f32m1(v.val)); } -inline v_float64x2 v_reinterpret_as_f64(const v_int32x4& v) { return v_float64x2(vreinterpret_v_i64m1_f64m1(vreinterpret_v_i32m1_i64m1(v.val))); } - -inline v_uint8x16 v_reinterpret_as_u8(const v_uint64x2& v) { return v_uint8x16(vreinterpret_v_u64m1_u8m1(v.val)); } -inline v_int8x16 v_reinterpret_as_s8(const v_uint64x2& v) { return v_int8x16(vreinterpret_v_i64m1_i8m1(vreinterpret_v_u64m1_i64m1(v.val))); } -inline v_uint16x8 v_reinterpret_as_u16(const v_uint64x2& v) { return v_uint16x8(vreinterpret_v_u64m1_u16m1(v.val)); } -inline v_int16x8 v_reinterpret_as_s16(const v_uint64x2& v) { return v_int16x8(vreinterpret_v_i64m1_i16m1(vreinterpret_v_u64m1_i64m1(v.val))); } -inline v_uint32x4 v_reinterpret_as_u32(const v_uint64x2& v) { return v_uint32x4(vreinterpret_v_u64m1_u32m1(v.val)); } -inline v_int32x4 v_reinterpret_as_s32(const v_uint64x2& v) { return v_int32x4(vreinterpret_v_i64m1_i32m1(vreinterpret_v_u64m1_i64m1(v.val))); } -inline v_uint64x2 v_reinterpret_as_u64(const v_uint64x2& v) { return v_uint64x2(v.val); } -inline v_int64x2 v_reinterpret_as_s64(const v_uint64x2& v) { return v_int64x2(vreinterpret_v_u64m1_i64m1(v.val)); } -inline v_float32x4 v_reinterpret_as_f32(const v_uint64x2& v) { return v_float32x4(vreinterpret_v_u32m1_f32m1(vreinterpret_v_u64m1_u32m1(v.val))); } -inline v_float64x2 v_reinterpret_as_f64(const v_uint64x2& v) { return v_float64x2(vreinterpret_v_u64m1_f64m1(v.val)); } - -inline v_uint8x16 v_reinterpret_as_u8(const v_int64x2& v) { return v_uint8x16(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i64m1_i8m1(v.val))); } -inline v_int8x16 v_reinterpret_as_s8(const v_int64x2& v) { return v_int8x16(vreinterpret_v_i64m1_i8m1(v.val)); } -inline v_uint16x8 v_reinterpret_as_u16(const v_int64x2& v) { return v_uint16x8(vreinterpret_v_u64m1_u16m1(vreinterpret_v_i64m1_u64m1(v.val))); } -inline v_int16x8 v_reinterpret_as_s16(const v_int64x2& v) { return v_int16x8(vreinterpret_v_i64m1_i16m1(v.val)); } -inline v_uint32x4 v_reinterpret_as_u32(const v_int64x2& v) { return v_uint32x4(vreinterpret_v_u64m1_u32m1(vreinterpret_v_i64m1_u64m1(v.val))); } -inline v_int32x4 v_reinterpret_as_s32(const v_int64x2& v) { return v_int32x4(vreinterpret_v_i64m1_i32m1(v.val)); } -inline v_uint64x2 v_reinterpret_as_u64(const v_int64x2& v) { return v_uint64x2(vreinterpret_v_i64m1_u64m1(v.val)); } -inline v_int64x2 v_reinterpret_as_s64(const v_int64x2& v) { return v_int64x2(v.val); } -inline v_float32x4 v_reinterpret_as_f32(const v_int64x2& v) { return v_float32x4(vreinterpret_v_i32m1_f32m1(vreinterpret_v_i64m1_i32m1(v.val))); } -inline v_float64x2 v_reinterpret_as_f64(const v_int64x2& v) { return v_float64x2(vreinterpret_v_i64m1_f64m1(v.val)); } - -inline v_uint8x16 v_reinterpret_as_u8(const v_float32x4& v) { return v_uint8x16(vreinterpret_v_u32m1_u8m1(vreinterpret_v_f32m1_u32m1(v.val))); } -inline v_int8x16 v_reinterpret_as_s8(const v_float32x4& v) { return v_int8x16(vreinterpret_v_i32m1_i8m1(vreinterpret_v_f32m1_i32m1(v.val))); } -inline v_uint16x8 v_reinterpret_as_u16(const v_float32x4& v) { return v_uint16x8(vreinterpret_v_u32m1_u16m1(vreinterpret_v_f32m1_u32m1(v.val))); } -inline v_int16x8 v_reinterpret_as_s16(const v_float32x4& v) { return v_int16x8(vreinterpret_v_i32m1_i16m1(vreinterpret_v_f32m1_i32m1(v.val))); } -inline v_uint32x4 v_reinterpret_as_u32(const v_float32x4& v) { return v_uint32x4(vreinterpret_v_f32m1_u32m1(v.val)); } -inline v_int32x4 v_reinterpret_as_s32(const v_float32x4& v) { return v_int32x4(vreinterpret_v_f32m1_i32m1(v.val)); } -inline v_uint64x2 v_reinterpret_as_u64(const v_float32x4& v) { return v_uint64x2(vreinterpret_v_u32m1_u64m1(vreinterpret_v_f32m1_u32m1(v.val))); } -inline v_int64x2 v_reinterpret_as_s64(const v_float32x4& v) { return v_int64x2(vreinterpret_v_i32m1_i64m1(vreinterpret_v_f32m1_i32m1(v.val))); } -inline v_float32x4 v_reinterpret_as_f32(const v_float32x4& v) { return v_float32x4(v.val); } -inline v_float64x2 v_reinterpret_as_f64(const v_float32x4& v) { return v_float64x2(vreinterpret_v_i64m1_f64m1(vreinterpret_v_i32m1_i64m1(vreinterpret_v_f32m1_i32m1(v.val)))); } - -inline v_uint8x16 v_reinterpret_as_u8(const v_float64x2& v) { return v_uint8x16(vreinterpret_v_u64m1_u8m1(vreinterpret_v_f64m1_u64m1(v.val))); } -inline v_int8x16 v_reinterpret_as_s8(const v_float64x2& v) { return v_int8x16(vreinterpret_v_i64m1_i8m1(vreinterpret_v_f64m1_i64m1(v.val))); } -inline v_uint16x8 v_reinterpret_as_u16(const v_float64x2& v) { return v_uint16x8(vreinterpret_v_u64m1_u16m1(vreinterpret_v_f64m1_u64m1(v.val))); } -inline v_int16x8 v_reinterpret_as_s16(const v_float64x2& v) { return v_int16x8(vreinterpret_v_i64m1_i16m1(vreinterpret_v_f64m1_i64m1(v.val))); } -inline v_uint32x4 v_reinterpret_as_u32(const v_float64x2& v) { return v_uint32x4(vreinterpret_v_u64m1_u32m1(vreinterpret_v_f64m1_u64m1(v.val))); } -inline v_int32x4 v_reinterpret_as_s32(const v_float64x2& v) { return v_int32x4(vreinterpret_v_i64m1_i32m1(vreinterpret_v_f64m1_i64m1(v.val))); } -inline v_uint64x2 v_reinterpret_as_u64(const v_float64x2& v) { return v_uint64x2(vreinterpret_v_f64m1_u64m1(v.val)); } -inline v_int64x2 v_reinterpret_as_s64(const v_float64x2& v) { return v_int64x2(vreinterpret_v_f64m1_i64m1(v.val)); } -inline v_float32x4 v_reinterpret_as_f32(const v_float64x2& v) { return v_float32x4(vreinterpret_v_i32m1_f32m1(vreinterpret_v_i64m1_i32m1(vreinterpret_v_f64m1_i64m1(v.val)))); } -inline v_float64x2 v_reinterpret_as_f64(const v_float64x2& v) { return v_float64x2(v.val); } - -#define OPENCV_HAL_IMPL_RISCVV_INIT_SET(__Tp, _Tp, suffix, len, num) \ -inline v_##_Tp##x##num v_setzero_##suffix() { return v_##_Tp##x##num(vmv_v_x_##len##m1(0, num)); } \ -inline v_##_Tp##x##num v_setall_##suffix(__Tp v) { return v_##_Tp##x##num(vmv_v_x_##len##m1(v, num)); } \ -template <> inline v_##_Tp##x##num v_setzero_() { return v_setzero_##suffix(); } \ -template <> inline v_##_Tp##x##num v_setall_(__Tp v) { return v_setall_##suffix(v); } - -OPENCV_HAL_IMPL_RISCVV_INIT_SET(uchar, uint8, u8, u8, 16) -OPENCV_HAL_IMPL_RISCVV_INIT_SET(schar, int8, s8, i8, 16) -OPENCV_HAL_IMPL_RISCVV_INIT_SET(ushort, uint16, u16, u16, 8) -OPENCV_HAL_IMPL_RISCVV_INIT_SET(short, int16, s16, i16, 8) -OPENCV_HAL_IMPL_RISCVV_INIT_SET(unsigned int, uint32, u32, u32, 4) -OPENCV_HAL_IMPL_RISCVV_INIT_SET(int, int32, s32, i32, 4) -OPENCV_HAL_IMPL_RISCVV_INIT_SET(unsigned long, uint64, u64, u64, 2) -OPENCV_HAL_IMPL_RISCVV_INIT_SET(long, int64, s64, i64, 2) -inline v_float32x4 v_setzero_f32() { return v_float32x4(vfmv_v_f_f32m1(0, 4)); } -inline v_float32x4 v_setall_f32(float v) { return v_float32x4(vfmv_v_f_f32m1(v, 4)); } - -inline v_float64x2 v_setzero_f64() { return v_float64x2(vfmv_v_f_f64m1(0, 2)); } -inline v_float64x2 v_setall_f64(double v) { return v_float64x2(vfmv_v_f_f64m1(v, 2)); } - -template <> inline v_float32x4 v_setzero_() { return v_setzero_f32(); } -template <> inline v_float32x4 v_setall_(float v) { return v_setall_f32(v); } - -template <> inline v_float64x2 v_setzero_() { return v_setzero_f64(); } -template <> inline v_float64x2 v_setall_(double v) { return v_setall_f64(v); } - -#define OPENCV_HAL_IMPL_RISCVV_BIN_OP(bin_op, _Tpvec, intrin) \ -inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(intrin(a.val, b.val)); \ -} - -#define OPENCV_HAL_IMPL_RISCVV_BIN_OPN(bin_op, _Tpvec, intrin, num) \ -inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(intrin(a.val, b.val, num)); \ -} - -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_uint8x16, vsaddu_vv_u8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_uint8x16, vssubu_vv_u8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_int8x16, vsadd_vv_i8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_int8x16, vssub_vv_i8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_uint16x8, vsaddu_vv_u16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_uint16x8, vssubu_vv_u16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_int16x8, vsadd_vv_i16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_int16x8, vssub_vv_i16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_int32x4, vadd_vv_i32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_int32x4, vsub_vv_i32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_mul, v_int32x4, vmul_vv_i32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_uint32x4, vadd_vv_u32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_uint32x4, vsub_vv_u32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_mul, v_uint32x4, vmul_vv_u32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_int64x2, vadd_vv_i64m1, 2) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_int64x2, vsub_vv_i64m1, 2) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_uint64x2, vadd_vv_u64m1, 2) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_uint64x2, vsub_vv_u64m1, 2) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_float32x4, vfadd_vv_f32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_float32x4, vfsub_vv_f32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_mul, v_float32x4, vfmul_vv_f32m1, 4) -inline v_float32x4 v_div(const v_float32x4& a, const v_float32x4& b) -{ - return v_float32x4(vfdiv_vv_f32m1(a.val, b.val, 4)); -} - -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_float64x2, vfadd_vv_f64m1, 2) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_float64x2, vfsub_vv_f64m1, 2) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_mul, v_float64x2, vfmul_vv_f64m1, 2) -inline v_float64x2 v_div(const v_float64x2& a, const v_float64x2& b) -{ - return v_float64x2(vfdiv_vv_f64m1(a.val, b.val, 2)); -} -// TODO: exp, log, sin, cos - -#define OPENCV_HAL_IMPL_RISCVV_BIN_FUNC(_Tpvec, func, intrin) \ -inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(intrin(a.val, b.val)); \ -} - -#define OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(_Tpvec, func, intrin, num) \ -inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(intrin(a.val, b.val, num)); \ -} -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint8x16, v_min, vminu_vv_u8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint8x16, v_max, vmaxu_vv_u8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int8x16, v_min, vmin_vv_i8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int8x16, v_max, vmax_vv_i8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint16x8, v_min, vminu_vv_u16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint16x8, v_max, vmaxu_vv_u16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int16x8, v_min, vmin_vv_i16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int16x8, v_max, vmax_vv_i16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint32x4, v_min, vminu_vv_u32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint32x4, v_max, vmaxu_vv_u32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int32x4, v_min, vmin_vv_i32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int32x4, v_max, vmax_vv_i32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_float32x4, v_min, vfmin_vv_f32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_float32x4, v_max, vfmax_vv_f32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_float64x2, v_min, vfmin_vv_f64m1, 2) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_float64x2, v_max, vfmax_vv_f64m1, 2) - -inline v_float32x4 v_sqrt(const v_float32x4& x) -{ - return v_float32x4(vfsqrt_v_f32m1(x.val, 4)); -} - -inline v_float32x4 v_invsqrt(const v_float32x4& x) -{ - return v_float32x4(vfrdiv_vf_f32m1(vfsqrt_v_f32m1(x.val, 4), 1, 4)); -} - -inline v_float32x4 v_magnitude(const v_float32x4& a, const v_float32x4& b) -{ - v_float32x4 x(vfmacc_vv_f32m1(vfmul_vv_f32m1(a.val, a.val, 4), b.val, b.val, 4)); - return v_sqrt(x); -} - -inline v_float32x4 v_sqr_magnitude(const v_float32x4& a, const v_float32x4& b) -{ - return v_float32x4(vfmacc_vv_f32m1(vfmul_vv_f32m1(a.val, a.val, 4), b.val, b.val, 4)); -} - -inline v_float32x4 v_fma(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) -{ - return v_float32x4(vfmadd_vv_f32m1(a.val, b.val, c.val, 4)); -} - -inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ - return v_int32x4(vmadd_vv_i32m1(a.val, b.val, c.val, 4)); -} - -inline v_float32x4 v_muladd(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) -{ - return v_fma(a, b, c); -} - -inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ - return v_fma(a, b, c); -} - -inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, - const v_float32x4& m3) -{ - vfloat32m1_t res = vfmul_vv_f32m1(m0.val, vrgather_vx_f32m1(v.val, 0, 4), 4);//vmuli_f32(m0.val, v.val, 0); - res = vfmacc_vv_f32m1(res, vrgather_vx_f32m1(v.val, 1, 4), m1.val, 4);//vmulai_f32(res, m1.val, v.val, 1); - res = vfmacc_vv_f32m1(res, vrgather_vx_f32m1(v.val, 2, 4), m2.val, 4);//vmulai_f32(res, m1.val, v.val, 1); - res = vfmacc_vv_f32m1(res, vrgather_vx_f32m1(v.val, 3, 4), m3.val, 4);//vmulai_f32(res, m1.val, v.val, 1); - return v_float32x4(res); -} - -inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, - const v_float32x4& a) -{ - vfloat32m1_t res = vfmul_vv_f32m1(m0.val, vrgather_vx_f32m1(v.val, 0, 4), 4);//vmuli_f32(m0.val, v.val, 0); - res = vfmacc_vv_f32m1(res, vrgather_vx_f32m1(v.val, 1, 4), m1.val, 4);//vmulai_f32(res, m1.val, v.val, 1); - res = vfmacc_vv_f32m1(res, vrgather_vx_f32m1(v.val, 2, 4), m2.val, 4);//vmulai_f32(res, m1.val, v.val, 1); - res = vfadd_vv_f32m1(res, a.val, 4);//vmulai_f32(res, m1.val, v.val, 1); - return v_float32x4(res); -} - -inline v_float64x2 v_sqrt(const v_float64x2& x) -{ - return v_float64x2(vfsqrt_v_f64m1(x.val, 2)); -} - -inline v_float64x2 v_invsqrt(const v_float64x2& x) -{ - return v_float64x2(vfrdiv_vf_f64m1(vfsqrt_v_f64m1(x.val, 2), 1, 2)); -} - -inline v_float64x2 v_magnitude(const v_float64x2& a, const v_float64x2& b) -{ - v_float64x2 x(vfmacc_vv_f64m1(vfmul_vv_f64m1(a.val, a.val, 2), b.val, b.val, 2)); - return v_sqrt(x); -} - -inline v_float64x2 v_sqr_magnitude(const v_float64x2& a, const v_float64x2& b) -{ - return v_float64x2(vfmacc_vv_f64m1(vfmul_vv_f64m1(a.val, a.val, 2), b.val, b.val, 2)); -} - -inline v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) -{ - return v_float64x2(vfmadd_vv_f64m1(a.val, b.val, c.val, 2)); -} - -inline v_float64x2 v_muladd(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) -{ - return v_fma(a, b, c); -} - -#define OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(_Tpvec, suffix, num) \ - OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_and, _Tpvec, vand_vv_##suffix, num) \ - OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_or, _Tpvec, vor_vv_##suffix, num) \ - OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_xor, _Tpvec, vxor_vv_##suffix, num) \ - inline _Tpvec v_not(const _Tpvec & a) \ - { \ - return _Tpvec(vnot_v_##suffix(a.val, num)); \ - } - -OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_uint8x16, u8m1, 16) -OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_uint16x8, u16m1, 8) -OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_uint32x4, u32m1, 4) -OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_uint64x2, u64m1, 2) -OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_int8x16, i8m1, 16) -OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_int16x8, i16m1, 8) -OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_int32x4, i32m1, 4) -OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_int64x2, i64m1, 2) - -#define OPENCV_HAL_IMPL_RISCVV_FLT_BIT_OP(bin_op, intrin) \ -inline v_float32x4 bin_op(const v_float32x4& a, const v_float32x4& b) \ -{ \ - return v_float32x4(vreinterpret_v_i32m1_f32m1(intrin(vreinterpret_v_f32m1_i32m1(a.val), vreinterpret_v_f32m1_i32m1(b.val), 4))); \ -} - -OPENCV_HAL_IMPL_RISCVV_FLT_BIT_OP(v_and, vand_vv_i32m1) -OPENCV_HAL_IMPL_RISCVV_FLT_BIT_OP(v_or, vor_vv_i32m1) -OPENCV_HAL_IMPL_RISCVV_FLT_BIT_OP(v_xor, vxor_vv_i32m1) - -inline v_float32x4 v_not(const v_float32x4& a) -{ - return v_float32x4(vreinterpret_v_i32m1_f32m1(vnot_v_i32m1(vreinterpret_v_f32m1_i32m1(a.val), 4))); -} - -#define OPENCV_HAL_IMPL_RISCVV_FLT_64BIT_OP(bin_op, intrin) \ -inline v_float64x2 bin_op(const v_float64x2& a, const v_float64x2& b) \ -{ \ - return v_float64x2(vreinterpret_v_i64m1_f64m1(intrin(vreinterpret_v_f64m1_i64m1(a.val), vreinterpret_v_f64m1_i64m1(b.val), 2))); \ -} - -OPENCV_HAL_IMPL_RISCVV_FLT_64BIT_OP(v_and, vand_vv_i64m1) -OPENCV_HAL_IMPL_RISCVV_FLT_64BIT_OP(v_or, vor_vv_i64m1) -OPENCV_HAL_IMPL_RISCVV_FLT_64BIT_OP(v_xor, vxor_vv_i64m1) - -inline v_float64x2 v_not(const v_float64x2& a) -{ - return v_float64x2(vreinterpret_v_i64m1_f64m1(vnot_v_i64m1(vreinterpret_v_f64m1_i64m1(a.val), 2))); -} -inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) -{ - return v_int16x8(vmulh_vv_i16m1(a.val, b.val, 8)); -} -inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) -{ - return v_uint16x8(vmulhu_vv_u16m1(a.val, b.val, 8)); -} - -//#define OPENCV_HAL_IMPL_RISCVV_ABS(_Tpuvec, _Tpsvec, usuffix, ssuffix) \ -//inline _Tpuvec v_abs(const _Tpsvec& a) { \ -// E##xm1_t mask=vmflt_vf_e32xm1_f32m1(x.val, 0.0, 4); - -//OPENCV_HAL_IMPL_RISCVV_ABS(v_uint8x16, v_int8x16, u8, s8) -//OPENCV_HAL_IMPL_RISCVV_ABS(v_uint16x8, v_int16x8, u16, s16) -//OPENCV_HAL_IMPL_RISCVV_ABS(v_uint32x4, v_int32x4, u32, s32) - -inline v_uint32x4 v_abs(v_int32x4 x) -{ - vbool32_t mask=vmslt_vx_i32m1_b32(x.val, 0, 4); - return v_uint32x4(vreinterpret_v_i32m1_u32m1(vrsub_vx_i32m1_m(mask, x.val, x.val, 0, 4))); -} - -inline v_uint16x8 v_abs(v_int16x8 x) -{ - vbool16_t mask=vmslt_vx_i16m1_b16(x.val, 0, 8); - return v_uint16x8(vreinterpret_v_i16m1_u16m1(vrsub_vx_i16m1_m(mask, x.val, x.val, 0, 8))); -} - -inline v_uint8x16 v_abs(v_int8x16 x) -{ - vbool8_t mask=vmslt_vx_i8m1_b8(x.val, 0, 16); - return v_uint8x16(vreinterpret_v_i8m1_u8m1(vrsub_vx_i8m1_m(mask, x.val, x.val, 0, 16))); -} - -inline v_float32x4 v_abs(v_float32x4 x) -{ - return (v_float32x4)vfsgnjx_vv_f32m1(x.val, x.val, 4); -} - -inline v_float64x2 v_abs(v_float64x2 x) -{ - return (v_float64x2)vfsgnjx_vv_f64m1(x.val, x.val, 2); -} - -inline v_float32x4 v_absdiff(const v_float32x4& a, const v_float32x4& b) -{ - vfloat32m1_t ret = vfsub_vv_f32m1(a.val, b.val, 4); - return (v_float32x4)vfsgnjx_vv_f32m1(ret, ret, 4); -} - -inline v_float64x2 v_absdiff(const v_float64x2& a, const v_float64x2& b) -{ - vfloat64m1_t ret = vfsub_vv_f64m1(a.val, b.val, 2); - return (v_float64x2)vfsgnjx_vv_f64m1(ret, ret, 2); -} - -#define OPENCV_HAL_IMPL_RISCVV_ABSDIFF_U(bit, num) \ -inline v_uint##bit##x##num v_absdiff(v_uint##bit##x##num a, v_uint##bit##x##num b){ \ - vuint##bit##m1_t vmax = vmaxu_vv_u##bit##m1(a.val, b.val, num); \ - vuint##bit##m1_t vmin = vminu_vv_u##bit##m1(a.val, b.val, num); \ - return v_uint##bit##x##num(vsub_vv_u##bit##m1(vmax, vmin, num));\ -} - -OPENCV_HAL_IMPL_RISCVV_ABSDIFF_U(8, 16) -OPENCV_HAL_IMPL_RISCVV_ABSDIFF_U(16, 8) -OPENCV_HAL_IMPL_RISCVV_ABSDIFF_U(32, 4) - -/** Saturating absolute difference **/ -inline v_int8x16 v_absdiffs(v_int8x16 a, v_int8x16 b){ - vint8m1_t vmax = vmax_vv_i8m1(a.val, b.val, 16); - vint8m1_t vmin = vmin_vv_i8m1(a.val, b.val, 16); - return v_int8x16(vssub_vv_i8m1(vmax, vmin, 16)); -} -inline v_int16x8 v_absdiffs(v_int16x8 a, v_int16x8 b){ - vint16m1_t vmax = vmax_vv_i16m1(a.val, b.val, 8); - vint16m1_t vmin = vmin_vv_i16m1(a.val, b.val, 8); - return v_int16x8(vssub_vv_i16m1(vmax, vmin, 8)); -} - -#define OPENCV_HAL_IMPL_RISCVV_ABSDIFF(_Tpvec, _Tpv, num) \ -inline v_uint##_Tpvec v_absdiff(v_int##_Tpvec a, v_int##_Tpvec b){ \ - vint##_Tpv##_t max = vmax_vv_i##_Tpv(a.val, b.val, num);\ - vint##_Tpv##_t min = vmin_vv_i##_Tpv(a.val, b.val, num);\ - return v_uint##_Tpvec(vreinterpret_v_i##_Tpv##_u##_Tpv(vsub_vv_i##_Tpv(max, min, num))); \ -} - -OPENCV_HAL_IMPL_RISCVV_ABSDIFF(8x16, 8m1, 16) -OPENCV_HAL_IMPL_RISCVV_ABSDIFF(16x8, 16m1, 8) -OPENCV_HAL_IMPL_RISCVV_ABSDIFF(32x4, 32m1, 4) - -// Multiply and expand -inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b, - v_int16x8& c, v_int16x8& d) -{ - vint16m2_t res = vundefined_i16m2(); - res = vwmul_vv_i16m2(a.val, b.val, 16); - c.val = vget_v_i16m2_i16m1(res, 0); - d.val = vget_v_i16m2_i16m1(res, 1); -} - -inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b, - v_uint16x8& c, v_uint16x8& d) -{ - vuint16m2_t res = vundefined_u16m2(); - res = vwmulu_vv_u16m2(a.val, b.val, 16); - c.val = vget_v_u16m2_u16m1(res, 0); - d.val = vget_v_u16m2_u16m1(res, 1); -} - -inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, - v_int32x4& c, v_int32x4& d) -{ - vint32m2_t res = vundefined_i32m2(); - res = vwmul_vv_i32m2(a.val, b.val, 8); - c.val = vget_v_i32m2_i32m1(res, 0); - d.val = vget_v_i32m2_i32m1(res, 1); -} - -inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, - v_uint32x4& c, v_uint32x4& d) -{ - vuint32m2_t res = vundefined_u32m2(); - res = vwmulu_vv_u32m2(a.val, b.val, 8); - c.val = vget_v_u32m2_u32m1(res, 0); - d.val = vget_v_u32m2_u32m1(res, 1); -} - -inline void v_mul_expand(const v_int32x4& a, const v_int32x4& b, - v_int64x2& c, v_int64x2& d) -{ - vint64m2_t res = vundefined_i64m2(); - res = vwmul_vv_i64m2(a.val, b.val, 4); - c.val = vget_v_i64m2_i64m1(res, 0); - d.val = vget_v_i64m2_i64m1(res, 1); -} - -inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, - v_uint64x2& c, v_uint64x2& d) -{ - vuint64m2_t res = vundefined_u64m2(); - res = vwmulu_vv_u64m2(a.val, b.val, 4); - c.val = vget_v_u64m2_u64m1(res, 0); - d.val = vget_v_u64m2_u64m1(res, 1); -} - -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint8x16, v_add_wrap, vadd_vv_u8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int8x16, v_add_wrap, vadd_vv_i8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint16x8, v_add_wrap, vadd_vv_u16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int16x8, v_add_wrap, vadd_vv_i16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint8x16, v_sub_wrap, vsub_vv_u8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int8x16, v_sub_wrap, vsub_vv_i8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint16x8, v_sub_wrap, vsub_vv_u16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int16x8, v_sub_wrap, vsub_vv_i16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint8x16, v_mul_wrap, vmul_vv_u8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int8x16, v_mul_wrap, vmul_vv_i8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint16x8, v_mul_wrap, vmul_vv_u16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int16x8, v_mul_wrap, vmul_vv_i16m1, 8) -//////// Dot Product //////// -// 16 >> 32 -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) -{ - vuint32m2_t vindex = vundefined_u32m2(); - vuint32m1_t vindex0 = vid_v_u32m1(4); - vindex0 = vsll_vx_u32m1(vindex0, 1, 4); - vindex = vset_v_u32m1_u32m2(vindex, 0, vindex0); - vindex = vset_v_u32m1_u32m2(vindex, 1, vadd_vx_u32m1(vindex0, 1, 4)); - vint32m2_t res = vundefined_i32m2(); - res = vwmul_vv_i32m2(a.val, b.val, 8); - res = vrgather_vv_i32m2(res, vindex, 8); - return v_int32x4(vadd_vv_i32m1(vget_v_i32m2_i32m1(res, 0), vget_v_i32m2_i32m1(res, 1), 4)); -} -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ - vuint32m2_t vindex = vundefined_u32m2(); - vuint32m1_t vindex0 = vid_v_u32m1(4); - vindex0 = vsll_vx_u32m1(vindex0, 1, 4); - vindex = vset_v_u32m1_u32m2(vindex, 0, vindex0); - vindex = vset_v_u32m1_u32m2(vindex, 1, vadd_vx_u32m1(vindex0, 1, 4)); - vint32m2_t res = vundefined_i32m2(); - res = vwmul_vv_i32m2(a.val, b.val, 8); - res = vrgather_vv_i32m2(res, vindex, 8); - return v_int32x4(vadd_vv_i32m1(vadd_vv_i32m1(vget_v_i32m2_i32m1(res, 0),vget_v_i32m2_i32m1(res, 1), 4), c.val, 4)); -} - -// 32 >> 64 -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) -{ - vuint64m2_t vindex = vundefined_u64m2(); - vuint64m1_t vindex0 = vid_v_u64m1(2); - vindex0 = vsll_vx_u64m1(vindex0, 1, 2); - vindex = vset_v_u64m1_u64m2(vindex, 0, vindex0); - vindex = vset_v_u64m1_u64m2(vindex, 1, vadd_vx_u64m1(vindex0, 1, 2)); - vint64m2_t res = vundefined_i64m2(); - res = vwmul_vv_i64m2(a.val, b.val, 4); - res = vrgather_vv_i64m2(res, vindex, 4); - return v_int64x2(vadd_vv_i64m1(vget_v_i64m2_i64m1(res, 0), vget_v_i64m2_i64m1(res, 1), 2)); -} -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ - vuint64m2_t vindex = vundefined_u64m2(); - vuint64m1_t vindex0 = vid_v_u64m1(2); - vindex0 = vsll_vx_u64m1(vindex0, 1, 2); - vindex = vset_v_u64m1_u64m2(vindex, 0, vindex0); - vindex = vset_v_u64m1_u64m2(vindex, 1, vadd_vx_u64m1(vindex0, 1, 2)); - vint64m2_t res = vundefined_i64m2(); - res = vwmul_vv_i64m2(a.val, b.val, 4); - res = vrgather_vv_i64m2(res, vindex, 4); - return v_int64x2(vadd_vv_i64m1(vadd_vv_i64m1(vget_v_i64m2_i64m1(res, 0), vget_v_i64m2_i64m1(res, 1), 2), c.val, 2)); -} - -// 8 >> 32 -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) -{ - vuint32m4_t vindex32 = vundefined_u32m4(); - vuint32m1_t vindex0 = vid_v_u32m1(4); - vindex0 = vsll_vx_u32m1(vindex0, 2, 4); - vindex32 = vset_v_u32m1_u32m4(vindex32, 0, vindex0); - vindex32 = vset_v_u32m1_u32m4(vindex32, 1, vadd_vx_u32m1(vindex0, 1, 4)); - vindex32 = vset_v_u32m1_u32m4(vindex32, 2, vadd_vx_u32m1(vindex0, 2, 4)); - vindex32 = vset_v_u32m1_u32m4(vindex32, 3, vadd_vx_u32m1(vindex0, 3, 4)); - vuint16m2_t vindex = vnsrl_wx_u16m2(vindex32, 0, 16); - vuint16m2_t v1 = vundefined_u16m2(); - vuint32m2_t v2 = vundefined_u32m2(); - v1 = vwmulu_vv_u16m2(a.val, b.val, 16); - v1 = vrgather_vv_u16m2(v1, vindex, 16); - v2 = vwaddu_vv_u32m2(vget_v_u16m2_u16m1(v1, 0), vget_v_u16m2_u16m1(v1, 1), 8); - return v_uint32x4(vadd_vv_u32m1(vget_v_u32m2_u32m1(v2, 0), vget_v_u32m2_u32m1(v2, 1), 4)); -} - -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, - const v_uint32x4& c) -{ - vuint32m4_t vindex32 = vundefined_u32m4(); - vuint32m1_t vindex0 = vid_v_u32m1(4); - vindex0 = vsll_vx_u32m1(vindex0, 2, 4); - vindex32 = vset_v_u32m1_u32m4(vindex32, 0, vindex0); - vindex32 = vset_v_u32m1_u32m4(vindex32, 1, vadd_vx_u32m1(vindex0, 1, 4)); - vindex32 = vset_v_u32m1_u32m4(vindex32, 2, vadd_vx_u32m1(vindex0, 2, 4)); - vindex32 = vset_v_u32m1_u32m4(vindex32, 3, vadd_vx_u32m1(vindex0, 3, 4)); - vuint16m2_t vindex = vnsrl_wx_u16m2(vindex32, 0, 16); - vuint16m2_t v1 = vundefined_u16m2(); - vuint32m2_t v2 = vundefined_u32m2(); - v1 = vwmulu_vv_u16m2(a.val, b.val, 16); - v1 = vrgather_vv_u16m2(v1, vindex, 16); - v2 = vwaddu_vv_u32m2(vget_v_u16m2_u16m1(v1, 0), vget_v_u16m2_u16m1(v1, 1), 8); - return v_uint32x4(vadd_vv_u32m1(vadd_vv_u32m1(vget_v_u32m2_u32m1(v2, 0), vget_v_u32m2_u32m1(v2, 1), 4), c.val, 4)); -} - -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) -{ - vuint32m4_t vindex32 = vundefined_u32m4(); - vuint32m1_t vindex0 = vid_v_u32m1(4); - vindex0 = vsll_vx_u32m1(vindex0, 2, 4); - vindex32 = vset_v_u32m1_u32m4(vindex32, 0, vindex0); - vindex32 = vset_v_u32m1_u32m4(vindex32, 1, vadd_vx_u32m1(vindex0, 1, 4)); - vindex32 = vset_v_u32m1_u32m4(vindex32, 2, vadd_vx_u32m1(vindex0, 2, 4)); - vindex32 = vset_v_u32m1_u32m4(vindex32, 3, vadd_vx_u32m1(vindex0, 3, 4)); - vuint16m2_t vindex = vnsrl_wx_u16m2(vindex32, 0, 16); - vint16m2_t v1 = vundefined_i16m2(); - vint32m2_t v2 = vundefined_i32m2(); - v1 = vwmul_vv_i16m2(a.val, b.val, 16); - v1 = vrgather_vv_i16m2(v1, vindex, 16); - v2 = vwadd_vv_i32m2(vget_v_i16m2_i16m1(v1, 0), vget_v_i16m2_i16m1(v1, 1), 8); - return v_int32x4(vadd_vv_i32m1(vget_v_i32m2_i32m1(v2, 0), vget_v_i32m2_i32m1(v2, 1), 4)); -} - -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, - const v_int32x4& c) -{ - vuint32m4_t vindex32 = vundefined_u32m4(); - vuint32m1_t vindex0 = vid_v_u32m1(4); - vindex0 = vsll_vx_u32m1(vindex0, 2, 4); - vindex32 = vset_v_u32m1_u32m4(vindex32, 0, vindex0); - vindex32 = vset_v_u32m1_u32m4(vindex32, 1, vadd_vx_u32m1(vindex0, 1, 4)); - vindex32 = vset_v_u32m1_u32m4(vindex32, 2, vadd_vx_u32m1(vindex0, 2, 4)); - vindex32 = vset_v_u32m1_u32m4(vindex32, 3, vadd_vx_u32m1(vindex0, 3, 4)); - vuint16m2_t vindex = vnsrl_wx_u16m2(vindex32, 0, 16); - vint16m2_t v1 = vundefined_i16m2(); - vint32m2_t v2 = vundefined_i32m2(); - v1 = vwmul_vv_i16m2(a.val, b.val, 16); - v1 = vrgather_vv_i16m2(v1, vindex, 16); - v2 = vwadd_vv_i32m2(vget_v_i16m2_i16m1(v1, 0), vget_v_i16m2_i16m1(v1, 1), 8); - return v_int32x4(vadd_vv_i32m1(vadd_vv_i32m1(vget_v_i32m2_i32m1(v2, 0), vget_v_i32m2_i32m1(v2, 1), 4), c.val, 4)); -} - -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) -{ - vuint64m4_t vindex64 = vundefined_u64m4(); - vuint64m1_t vindex0 = vid_v_u64m1(2); - vindex0 = vsll_vx_u64m1(vindex0, 2, 2); - vindex64 = vset_v_u64m1_u64m4(vindex64, 0, vindex0); - vindex64 = vset_v_u64m1_u64m4(vindex64, 1, vadd_vx_u64m1(vindex0, 1, 2)); - vindex64 = vset_v_u64m1_u64m4(vindex64, 2, vadd_vx_u64m1(vindex0, 2, 2)); - vindex64 = vset_v_u64m1_u64m4(vindex64, 3, vadd_vx_u64m1(vindex0, 3, 2)); - vuint32m2_t vindex = vnsrl_wx_u32m2(vindex64, 0, 8); - vuint32m2_t v1 = vundefined_u32m2(); - vuint64m2_t v2 = vundefined_u64m2(); - v1 = vwmulu_vv_u32m2(a.val, b.val, 8); - v1 = vrgather_vv_u32m2(v1, vindex, 8); - v2 = vwaddu_vv_u64m2(vget_v_u32m2_u32m1(v1, 0), vget_v_u32m2_u32m1(v1, 1), 4); - return v_uint64x2(vadd_vv_u64m1(vget_v_u64m2_u64m1(v2, 0), vget_v_u64m2_u64m1(v2, 1), 2)); -} - -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, - const v_uint64x2& c) -{ - vuint64m4_t vindex64 = vundefined_u64m4(); - vuint64m1_t vindex0 = vid_v_u64m1(2); - vindex0 = vsll_vx_u64m1(vindex0, 2, 2); - vindex64 = vset_v_u64m1_u64m4(vindex64, 0, vindex0); - vindex64 = vset_v_u64m1_u64m4(vindex64, 1, vadd_vx_u64m1(vindex0, 1, 2)); - vindex64 = vset_v_u64m1_u64m4(vindex64, 2, vadd_vx_u64m1(vindex0, 2, 2)); - vindex64 = vset_v_u64m1_u64m4(vindex64, 3, vadd_vx_u64m1(vindex0, 3, 2)); - vuint32m2_t vindex = vnsrl_wx_u32m2(vindex64, 0, 8); - vuint32m2_t v1 = vundefined_u32m2(); - vuint64m2_t v2 = vundefined_u64m2(); - v1 = vwmulu_vv_u32m2(a.val, b.val, 8); - v1 = vrgather_vv_u32m2(v1, vindex, 8); - v2 = vwaddu_vv_u64m2(vget_v_u32m2_u32m1(v1, 0), vget_v_u32m2_u32m1(v1, 1), 4); - return v_uint64x2(vadd_vv_u64m1(vadd_vv_u64m1(vget_v_u64m2_u64m1(v2, 0), vget_v_u64m2_u64m1(v2, 1), 2), c.val, 2)); -} - -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) -{ - vuint64m4_t vindex64 = vundefined_u64m4(); - vuint64m1_t vindex0 = vid_v_u64m1(2); - vindex0 = vsll_vx_u64m1(vindex0, 2, 2); - vindex64 = vset_v_u64m1_u64m4(vindex64, 0, vindex0); - vindex64 = vset_v_u64m1_u64m4(vindex64, 1, vadd_vx_u64m1(vindex0, 1, 2)); - vindex64 = vset_v_u64m1_u64m4(vindex64, 2, vadd_vx_u64m1(vindex0, 2, 2)); - vindex64 = vset_v_u64m1_u64m4(vindex64, 3, vadd_vx_u64m1(vindex0, 3, 2)); - vuint32m2_t vindex = vnsrl_wx_u32m2(vindex64, 0, 8); - vint32m2_t v1 = vundefined_i32m2(); - vint64m2_t v2 = vundefined_i64m2(); - v1 = vwmul_vv_i32m2(a.val, b.val, 8); - v1 = vrgather_vv_i32m2(v1, vindex, 8); - v2 = vwadd_vv_i64m2(vget_v_i32m2_i32m1(v1, 0), vget_v_i32m2_i32m1(v1, 1), 4); - return v_int64x2(vadd_vv_i64m1(vget_v_i64m2_i64m1(v2, 0), vget_v_i64m2_i64m1(v2, 1), 2)); -} - -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, - const v_int64x2& c) -{ - vuint64m4_t vindex64 = vundefined_u64m4(); - vuint64m1_t vindex0 = vid_v_u64m1(2); - vindex0 = vsll_vx_u64m1(vindex0, 2, 2); - vindex64 = vset_v_u64m1_u64m4(vindex64, 0, vindex0); - vindex64 = vset_v_u64m1_u64m4(vindex64, 1, vadd_vx_u64m1(vindex0, 1, 2)); - vindex64 = vset_v_u64m1_u64m4(vindex64, 2, vadd_vx_u64m1(vindex0, 2, 2)); - vindex64 = vset_v_u64m1_u64m4(vindex64, 3, vadd_vx_u64m1(vindex0, 3, 2)); - vuint32m2_t vindex = vnsrl_wx_u32m2(vindex64, 0, 8); - vint32m2_t v1 = vundefined_i32m2(); - vint64m2_t v2 = vundefined_i64m2(); - v1 = vwmul_vv_i32m2(a.val, b.val, 8); - v1 = vrgather_vv_i32m2(v1, vindex, 8); - v2 = vwadd_vv_i64m2(vget_v_i32m2_i32m1(v1, 0), vget_v_i32m2_i32m1(v1, 1), 4); - return v_int64x2(vadd_vv_i64m1(vadd_vv_i64m1(vget_v_i64m2_i64m1(v2, 0), vget_v_i64m2_i64m1(v2, 1), 2), c.val, 2)); -} - -//////// Fast Dot Product //////// -// 16 >> 32 -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) -{ - vint32m2_t v1 = vundefined_i32m2(); - v1 = vwmul_vv_i32m2(a.val, b.val, 8); - return v_int32x4(vadd_vv_i32m1(vget_v_i32m2_i32m1(v1, 0), vget_v_i32m2_i32m1(v1, 1), 4)); -} - -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ - vint32m2_t v1 = vundefined_i32m2(); - v1 = vwmul_vv_i32m2(a.val, b.val, 8); - return v_int32x4(vadd_vv_i32m1(vadd_vv_i32m1(vget_v_i32m2_i32m1(v1, 0), vget_v_i32m2_i32m1(v1, 1), 4), c.val, 4)); -} - -// 32 >> 64 -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) -{ - vint64m2_t v1 = vundefined_i64m2(); - v1 = vwmul_vv_i64m2(a.val, b.val, 4); - return v_int64x2(vadd_vv_i64m1(vget_v_i64m2_i64m1(v1, 0), vget_v_i64m2_i64m1(v1, 1), 2)); -} -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ - vint64m2_t v1 = vundefined_i64m2(); - v1 = vwmul_vv_i64m2(a.val, b.val, 8); - return v_int64x2(vadd_vv_i64m1(vadd_vv_i64m1(vget_v_i64m2_i64m1(v1, 0), vget_v_i64m2_i64m1(v1, 1), 4), c.val, 4)); -} - -// 8 >> 32 -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) -{ - vuint16m2_t v1 = vundefined_u16m2(); - vuint32m2_t v2 = vundefined_u32m2(); - v1 = vwmulu_vv_u16m2(a.val, b.val, 16); - v2 = vwaddu_vv_u32m2(vget_v_u16m2_u16m1(v1, 0), vget_v_u16m2_u16m1(v1, 1), 8); - return v_uint32x4(vadd_vv_u32m1(vget_v_u32m2_u32m1(v2, 0), vget_v_u32m2_u32m1(v2, 1), 4)); -} - -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) -{ - vuint16m2_t v1 = vundefined_u16m2(); - vuint32m2_t v2 = vundefined_u32m2(); - v1 = vwmulu_vv_u16m2(a.val, b.val, 16); - v2 = vwaddu_vv_u32m2(vget_v_u16m2_u16m1(v1, 0), vget_v_u16m2_u16m1(v1, 1), 8); - return v_uint32x4(vadd_vv_u32m1(vadd_vv_u32m1(vget_v_u32m2_u32m1(v2, 0), vget_v_u32m2_u32m1(v2, 1), 4), c.val, 4)); -} - -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) -{ - vint16m2_t v1 = vundefined_i16m2(); - vint32m2_t v2 = vundefined_i32m2(); - v1 = vwmul_vv_i16m2(a.val, b.val, 16); - v2 = vwadd_vv_i32m2(vget_v_i16m2_i16m1(v1, 0), vget_v_i16m2_i16m1(v1, 1), 8); - return v_int32x4(vadd_vv_i32m1(vget_v_i32m2_i32m1(v2, 0), vget_v_i32m2_i32m1(v2, 1), 4)); -} -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) -{ - vint16m2_t v1 = vundefined_i16m2(); - vint32m2_t v2 = vundefined_i32m2(); - v1 = vwmul_vv_i16m2(a.val, b.val, 16); - v2 = vwadd_vv_i32m2(vget_v_i16m2_i16m1(v1, 0), vget_v_i16m2_i16m1(v1, 1), 8); - return v_int32x4(vadd_vv_i32m1(vadd_vv_i32m1(vget_v_i32m2_i32m1(v2, 0), vget_v_i32m2_i32m1(v2, 1), 4), c.val, 4)); -} - -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) -{ - vuint32m2_t v1 = vundefined_u32m2(); - vuint64m2_t v2 = vundefined_u64m2(); - v1 = vwmulu_vv_u32m2(a.val, b.val, 8); - v2 = vwaddu_vv_u64m2(vget_v_u32m2_u32m1(v1, 0), vget_v_u32m2_u32m1(v1, 1), 4); - return v_uint64x2(vadd_vv_u64m1(vget_v_u64m2_u64m1(v2, 0), vget_v_u64m2_u64m1(v2, 1), 2)); -} -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) -{ - vuint32m2_t v1 = vundefined_u32m2(); - vuint64m2_t v2 = vundefined_u64m2(); - v1 = vwmulu_vv_u32m2(a.val, b.val, 8); - v2 = vwaddu_vv_u64m2(vget_v_u32m2_u32m1(v1, 0), vget_v_u32m2_u32m1(v1, 1), 4); - return v_uint64x2(vadd_vv_u64m1(vadd_vv_u64m1(vget_v_u64m2_u64m1(v2, 0), vget_v_u64m2_u64m1(v2, 1), 2), c.val, 2)); -} - -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) -{ - vint32m2_t v1 = vundefined_i32m2(); - vint64m2_t v2 = vundefined_i64m2(); - v1 = vwmul_vv_i32m2(a.val, b.val, 8); - v2 = vwadd_vv_i64m2(vget_v_i32m2_i32m1(v1, 0), vget_v_i32m2_i32m1(v1, 1), 4); - return v_int64x2(vadd_vv_i64m1(vget_v_i64m2_i64m1(v2, 0), vget_v_i64m2_i64m1(v2, 1), 2)); -} -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) -{ - vint32m2_t v1 = vundefined_i32m2(); - vint64m2_t v2 = vundefined_i64m2(); - v1 = vwmul_vv_i32m2(a.val, b.val, 8); - v2 = vwadd_vv_i64m2(vget_v_i32m2_i32m1(v1, 0), vget_v_i32m2_i32m1(v1, 1), 4); - return v_int64x2(vadd_vv_i64m1(vadd_vv_i64m1(vget_v_i64m2_i64m1(v2, 0), vget_v_i64m2_i64m1(v2, 1), 2), c.val, 2)); -} - - -#define OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(_Tpvec, _Tpvec2, len, scalartype, func, intrin, num) \ -inline scalartype v_reduce_##func(const v_##_Tpvec##x##num& a) \ -{\ - v##_Tpvec2##m1_t val = vmv_v_x_##len##m1(0, num); \ - val = intrin(val, a.val, val, num); \ - return vmv_x_s_##len##m1_##len(val); \ -} - - -#define OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(_Tpvec, _Tpvec2, scalartype, func, funcu, num, scalerfunc) \ -inline scalartype v_reduce_##func(const v_##_Tpvec##x##num& a) \ -{\ - v##_Tpvec##m1_t val = vundefined_##_Tpvec2##m1(); \ - val = v##funcu##_vs_##_Tpvec2##m1_##_Tpvec2##m1(val, a.val, a.val, num); \ - return scalerfunc(val); \ -} -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(int8, int16, i16, int, sum, vwredsum_vs_i8m1_i16m1, 16) -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(int16, int32, i32, int, sum, vwredsum_vs_i16m1_i32m1, 8) -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(int32, int64, i64, int, sum, vwredsum_vs_i32m1_i64m1, 4) -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(uint8, uint16, u16, unsigned, sum, vwredsumu_vs_u8m1_u16m1, 16) -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(uint16, uint32, u32, unsigned, sum, vwredsumu_vs_u16m1_u32m1, 8) -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(uint32, uint64, u64, unsigned, sum, vwredsumu_vs_u32m1_u64m1, 4) -inline float v_reduce_sum(const v_float32x4& a) \ -{\ - vfloat32m1_t val = vfmv_v_f_f32m1(0.0, 4); \ - val = vfredosum_vs_f32m1_f32m1(val, a.val, val, 4); \ - return vfmv_f_s_f32m1_f32(val); \ -} -inline double v_reduce_sum(const v_float64x2& a) \ -{\ - vfloat64m1_t val = vfmv_v_f_f64m1(0.0, 2); \ - val = vfredosum_vs_f64m1_f64m1(val, a.val, val, 2); \ - return vfmv_f_s_f64m1_f64(val); \ -} -inline uint64 v_reduce_sum(const v_uint64x2& a) -{ vuint64m1_t res = vundefined_u64m1(); return vmv_x_s_u64m1_u64(vredsum_vs_u64m1_u64m1(res, a.val, vmv_v_x_u64m1(0, 2), 2)); } - -inline int64 v_reduce_sum(const v_int64x2& a) -{ vint64m1_t res = vundefined_i64m1(); return vmv_x_s_i64m1_i64(vredsum_vs_i64m1_i64m1(res, a.val, vmv_v_x_i64m1(0, 2), 2)); } - -#define OPENCV_HAL_IMPL_RISCVV_REDUCE_OP(func) \ -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(int8, i8, int, func, red##func, 16, vmv_x_s_i8m1_i8) \ -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(int16, i16, int, func, red##func, 8, vmv_x_s_i16m1_i16) \ -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(int32, i32, int, func, red##func, 4, vmv_x_s_i32m1_i32) \ -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(int64, i64, int, func, red##func, 2, vmv_x_s_i64m1_i64) \ -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(uint8, u8, unsigned, func, red##func##u, 16, vmv_x_s_u8m1_u8) \ -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(uint16, u16, unsigned, func, red##func##u, 8, vmv_x_s_u16m1_u16) \ -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(uint32, u32, unsigned, func, red##func##u, 4, vmv_x_s_u32m1_u32) \ -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(float32, f32, float, func, fred##func, 4, vfmv_f_s_f32m1_f32) -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP(max) -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP(min) - -inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, - const v_float32x4& c, const v_float32x4& d) -{ - vfloat32m1_t a0 = vfmv_v_f_f32m1(0.0, 4); - vfloat32m1_t b0 = vfmv_v_f_f32m1(0.0, 4); - vfloat32m1_t c0 = vfmv_v_f_f32m1(0.0, 4); - vfloat32m1_t d0 = vfmv_v_f_f32m1(0.0, 4); - a0 = vfredosum_vs_f32m1_f32m1(a0, a.val, a0, 4); - b0 = vfredosum_vs_f32m1_f32m1(b0, b.val, b0, 4); - c0 = vfredosum_vs_f32m1_f32m1(c0, c.val, c0, 4); - d0 = vfredosum_vs_f32m1_f32m1(d0, d.val, d0, 4); - vfloat32m1_t res; - res = vslideup_vx_f32m1(a0, b0, 1, 4); - res = vslideup_vx_f32m1(res, c0, 2, 4); - res = vslideup_vx_f32m1(res, d0, 3, 4); - return v_float32x4(res); -} - -inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) -{ - vfloat32m1_t a0 = vfmv_v_f_f32m1(0.0, 4); - vfloat32m1_t x = vfsub_vv_f32m1(a.val, b.val, 4); - vbool32_t mask=vmflt_vf_f32m1_b32(x, 0, 4); - vfloat32m1_t val = vfrsub_vf_f32m1_m(mask, x, x, 0, 4); - a0 = vfredosum_vs_f32m1_f32m1(a0, val, a0, 4); - return vfmv_f_s_f32m1_f32(a0); -} - -#define OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(_Tpvec, _Tpvec2) \ -inline unsigned v_reduce_sad(const _Tpvec& a, const _Tpvec&b){ \ - _Tpvec2 x = v_absdiff(a, b); \ - return v_reduce_sum(x); \ -} - -OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(v_int8x16, v_uint8x16) -OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(v_uint8x16, v_uint8x16) -OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(v_int16x8, v_uint16x8) -OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(v_uint16x8, v_uint16x8) -OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(v_int32x4, v_uint32x4) -OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(v_uint32x4, v_uint32x4) - -#define OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(_Tpvec, _Tp, _T, num, uv) \ -inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ -{ \ - vbool##_T##_t mask = vmseq_vv_##_Tp##_b##_T(a.val, b.val, num); \ - return _Tpvec(vmerge_vxm_##_Tp(mask, vmv_v_x_##_Tp(0, num), -1, num)); \ -} \ -inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ -{ \ - vbool##_T##_t mask = vmsne_vv_##_Tp##_b##_T(a.val, b.val, num); \ - return _Tpvec(vmerge_vxm_##_Tp(mask, vmv_v_x_##_Tp(0, num), -1, num)); \ -} \ -inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ -{ \ - vbool##_T##_t mask = vmslt##uv##_Tp##_b##_T(a.val, b.val, num); \ - return _Tpvec(vmerge_vxm_##_Tp(mask, vmv_v_x_##_Tp(0, num), -1, num)); \ -} \ -inline _Tpvec v_gt(const _Tpvec& a, const _Tpvec& b) \ -{ \ - vbool##_T##_t mask = vmslt##uv##_Tp##_b##_T(b.val, a.val, num); \ - return _Tpvec(vmerge_vxm_##_Tp(mask, vmv_v_x_##_Tp(0, num), -1, num)); \ -} \ -inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ -{ \ - vbool##_T##_t mask = vmsle##uv##_Tp##_b##_T(a.val, b.val, num); \ - return _Tpvec(vmerge_vxm_##_Tp(mask, vmv_v_x_##_Tp(0, num), -1, num)); \ -} \ -inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ -{ \ - vbool##_T##_t mask = vmsle##uv##_Tp##_b##_T(b.val, a.val, num); \ - return _Tpvec(vmerge_vxm_##_Tp(mask, vmv_v_x_##_Tp(0, num), -1, num)); \ -} \ - -OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_int8x16, i8m1, 8, 16, _vv_) -OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_int16x8, i16m1, 16, 8, _vv_) -OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_int32x4, i32m1, 32, 4, _vv_) -OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_int64x2, i64m1, 64, 2, _vv_) -OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_uint8x16, u8m1, 8, 16, u_vv_) -OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_uint16x8, u16m1, 16, 8, u_vv_) -OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_uint32x4, u32m1, 32, 4, u_vv_) -OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_uint64x2, u64m1, 64, 2, u_vv_) - -//TODO: == -inline v_float32x4 v_eq(const v_float32x4& a, const v_float32x4& b) -{ - vbool32_t mask = vmfeq_vv_f32m1_b32(a.val, b.val, 4); - vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); - return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); -} -inline v_float32x4 v_ne(const v_float32x4& a, const v_float32x4& b) -{ - vbool32_t mask = vmfne_vv_f32m1_b32(a.val, b.val, 4); - vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); - return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); -} -inline v_float32x4 v_lt(const v_float32x4& a, const v_float32x4& b) -{ - vbool32_t mask = vmflt_vv_f32m1_b32(a.val, b.val, 4); - vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); - return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); -} -inline v_float32x4 v_le(const v_float32x4& a, const v_float32x4& b) -{ - vbool32_t mask = vmfle_vv_f32m1_b32(a.val, b.val, 4); - vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); - return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); -} -inline v_float32x4 v_gt(const v_float32x4& a, const v_float32x4& b) -{ - vbool32_t mask = vmfgt_vv_f32m1_b32(a.val, b.val, 4); - vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); - return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); -} -inline v_float32x4 v_ge(const v_float32x4& a, const v_float32x4& b) -{ - vbool32_t mask = vmfge_vv_f32m1_b32(a.val, b.val, 4); - vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); - return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); -}/**/ -inline v_float32x4 v_not_nan(const v_float32x4& a) -{ - vbool32_t mask = vmfeq_vv_f32m1_b32(a.val, a.val, 4); - vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); - return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); -} - -//TODO: == -inline v_float64x2 v_eq(const v_float64x2& a, const v_float64x2& b) -{ - vbool64_t mask = vmfeq_vv_f64m1_b64(a.val, b.val, 2); - vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); - return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); -} -inline v_float64x2 v_ne(const v_float64x2& a, const v_float64x2& b) -{ - vbool64_t mask = vmfne_vv_f64m1_b64(a.val, b.val, 2); - vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); - return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); -} -inline v_float64x2 v_lt(const v_float64x2& a, const v_float64x2& b) -{ - vbool64_t mask = vmflt_vv_f64m1_b64(a.val, b.val, 2); - vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); - return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); -} -inline v_float64x2 v_le(const v_float64x2& a, const v_float64x2& b) -{ - vbool64_t mask = vmfle_vv_f64m1_b64(a.val, b.val, 2); - vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); - return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); -} -inline v_float64x2 v_gt(const v_float64x2& a, const v_float64x2& b) -{ - vbool64_t mask = vmfgt_vv_f64m1_b64(a.val, b.val, 2); - vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); - return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); -} -inline v_float64x2 v_ge(const v_float64x2& a, const v_float64x2& b) -{ - vbool64_t mask = vmfge_vv_f64m1_b64(a.val, b.val, 2); - vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); - return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); -}/**/ -inline v_float64x2 v_not_nan(const v_float64x2& a) -{ - vbool64_t mask = vmfeq_vv_f64m1_b64(a.val, a.val, 2); - vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); - return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); -} -#define OPENCV_HAL_IMPL_RISCVV_TRANSPOSE4x4(_Tp, _T) \ -inline void v_transpose4x4(const v_##_Tp##32x4& a0, const v_##_Tp##32x4& a1, \ - const v_##_Tp##32x4& a2, const v_##_Tp##32x4& a3, \ - v_##_Tp##32x4& b0, v_##_Tp##32x4& b1, \ - v_##_Tp##32x4& b2, v_##_Tp##32x4& b3) \ -{ \ - vuint32m4_t vindex = vundefined_u32m4(); \ - vuint32m1_t vindex0 = vid_v_u32m1(4); \ - vindex0 = vsll_vx_u32m1(vindex0, 2, 4); \ - vindex = vset_v_u32m1_u32m4(vindex, 0, vindex0); \ - vindex = vset_v_u32m1_u32m4(vindex, 1, vadd_vx_u32m1(vindex0, 1, 4)); \ - vindex = vset_v_u32m1_u32m4(vindex, 2, vadd_vx_u32m1(vindex0, 2, 4)); \ - vindex = vset_v_u32m1_u32m4(vindex, 3, vadd_vx_u32m1(vindex0, 3, 4)); \ - v##_Tp##32m4_t val = vundefined_##_T##m4(); \ - val = vset_v_##_T##m1_##_T##m4(val, 0, a0.val); \ - val = vset_v_##_T##m1_##_T##m4(val, 1, a1.val); \ - val = vset_v_##_T##m1_##_T##m4(val, 2, a2.val); \ - val = vset_v_##_T##m1_##_T##m4(val, 3, a3.val); \ - val = vrgather_vv_##_T##m4(val, vindex, 16); \ - b0.val = vget_v_##_T##m4_##_T##m1(val, 0); \ - b1.val = vget_v_##_T##m4_##_T##m1(val, 1); \ - b2.val = vget_v_##_T##m4_##_T##m1(val, 2); \ - b3.val = vget_v_##_T##m4_##_T##m1(val, 3); \ -} -OPENCV_HAL_IMPL_RISCVV_TRANSPOSE4x4(uint, u32) -OPENCV_HAL_IMPL_RISCVV_TRANSPOSE4x4(int, i32) -OPENCV_HAL_IMPL_RISCVV_TRANSPOSE4x4(float, f32) - - -#define OPENCV_HAL_IMPL_RISCVV_SHIFT_LEFT(_Tpvec, suffix, _T, num) \ -inline _Tpvec v_shl(const _Tpvec& a, int n) \ -{ return _Tpvec((vsll_vx_##_T##m1(a.val, n, num))); } \ -template inline _Tpvec v_shl(const _Tpvec& a) \ -{ return _Tpvec((vsll_vx_##_T##m1(a.val, n, num))); } - -#define OPENCV_HAL_IMPL_RISCVV_SHIFT_RIGHT(_Tpvec, suffix, _T, num, intric) \ -inline _Tpvec v_shr(const _Tpvec& a, int n) \ -{ return _Tpvec((v##intric##_vx_##_T##m1(a.val, n, num))); } \ -template inline _Tpvec v_shr(const _Tpvec& a) \ -{ return _Tpvec((v##intric##_vx_##_T##m1(a.val, n, num))); }\ -template inline _Tpvec v_rshr(const _Tpvec& a) \ -{ return _Tpvec((v##intric##_vx_##_T##m1(vadd_vx_##_T##m1(a.val, 1<<(n-1), num), n, num))); } - -// trade efficiency for convenience -#define OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(suffix, _T, num, intrin) \ -OPENCV_HAL_IMPL_RISCVV_SHIFT_LEFT(v_##suffix##x##num, suffix, _T, num) \ -OPENCV_HAL_IMPL_RISCVV_SHIFT_RIGHT(v_##suffix##x##num, suffix, _T, num, intrin) - -OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(uint8, u8, 16, srl) -OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(uint16, u16, 8, srl) -OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(uint32, u32, 4, srl) -OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(uint64, u64, 2, srl) -OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(int8, i8, 16, sra) -OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(int16, i16, 8, sra) -OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(int32, i32, 4, sra) -OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(int64, i64, 2, sra) - -#if 0 -#define VUP4(n) {0, 1, 2, 3} -#define VUP8(n) {0, 1, 2, 3, 4, 5, 6, 7} -#define VUP16(n) {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15} -#define VUP2(n) {0, 1} -#endif -#define OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(_Tpvec, suffix, _T, num, num2, vmv, len) \ -template inline _Tpvec v_rotate_left(const _Tpvec& a) \ -{ \ - suffix##m1_t tmp = vmv##_##_T##m1(0, num);\ - tmp = vslideup_vx_##_T##m1_m(vmset_m_##len(num), tmp, a.val, n, num);\ - return _Tpvec(tmp);\ -} \ -template inline _Tpvec v_rotate_right(const _Tpvec& a) \ -{ \ - suffix##m1_t res = vundefined_##_T##m1(); \ - return _Tpvec(vslidedown_vx_##_T##m1(res, a.val, n, num));\ -} \ -template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a) \ -{ return a; } \ -template inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ -{ \ - suffix##m2_t tmp = vundefined_##_T##m2(); \ - suffix##m2_t res = vundefined_##_T##m2(); \ - tmp = vset_v_##_T##m1_##_T##m2(tmp, 0, a.val); \ - tmp = vset_v_##_T##m1_##_T##m2(tmp, 1, b.val); \ - res = vslidedown_vx_##_T##m2(res, tmp, n, num2);\ - return _Tpvec(vget_v_##_T##m2_##_T##m1(res, 0));\ -} \ -template inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ -{ \ - suffix##m2_t tmp = vundefined_##_T##m2(); \ - suffix##m2_t res = vundefined_##_T##m2(); \ - tmp = vset_v_##_T##m1_##_T##m2(tmp, 0, b.val); \ - tmp = vset_v_##_T##m1_##_T##m2(tmp, 1, a.val); \ - res = vslideup_vx_##_T##m2(res, tmp, n, num2);\ - return _Tpvec(vget_v_##_T##m2_##_T##m1(res, 1));\ -} \ -template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a, const _Tpvec& b) \ -{ \ - CV_UNUSED(b); return a; \ -} - -OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_uint8x16, vuint8, u8, 16, 32, vmv_v_x, b8) -OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_int8x16, vint8, i8, 16, 32, vmv_v_x, b8) -OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_uint16x8, vuint16, u16, 8, 16, vmv_v_x, b16) -OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_int16x8, vint16, i16, 8, 16, vmv_v_x, b16) -OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_uint32x4, vuint32, u32, 4, 8, vmv_v_x, b32) -OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_int32x4, vint32, i32, 4, 8, vmv_v_x, b32) -OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_uint64x2, vuint64, u64, 2, 4, vmv_v_x, b64) -OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_int64x2, vint64, i64, 2, 4, vmv_v_x, b64) -OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_float32x4, vfloat32, f32, 4, 8, vfmv_v_f, b32) -OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_float64x2, vfloat64, f64, 2, 4, vfmv_v_f, b64) - -#if 1 -#define vreinterpret_v_i8m1_i8m1 -#define vreinterpret_v_u8m1_u8m1 -#define OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(_Tpvec, _Tp, _Tp2, len, hnum, num, elemsize, ldst_len, ldst_type) \ -inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ -{ \ - _Tp2##_t res = vundefined_##len(); \ - _Tp2##_t res1 = vundefined_##len(); \ - res = vreinterpret_v_##ldst_len##_##len(vle8_v_##ldst_len((ldst_type *)ptr0, 8)); \ - res1 = vreinterpret_v_##ldst_len##_##len(vle8_v_##ldst_len((ldst_type *)ptr1, 8)); \ - res = vslideup_vx_##len(res, res1, hnum, num); \ - return _Tpvec(res); } \ -inline _Tpvec v_load_low(const _Tp* ptr) \ -{ return _Tpvec(vreinterpret_v_##ldst_len##_##len(vle8_v_##ldst_len((ldst_type *)ptr, 8))); }\ -inline _Tpvec v_load_aligned(const _Tp* ptr) \ -{ return _Tpvec(vreinterpret_v_##ldst_len##_##len(vle8_v_##ldst_len((ldst_type *)ptr, 16))); } \ -inline _Tpvec v_load(const _Tp* ptr) \ -{ return _Tpvec(vle##elemsize##_v_##len(ptr, num)); } \ -inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ -{ vse8_v_##ldst_len((ldst_type *)ptr, vreinterpret_v_##len##_##ldst_len(a.val), 8);}\ -inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ -{ \ - _Tp2##_t a0 = vundefined_##len(); \ - a0 = vslidedown_vx_##len(a0, a.val, hnum, num); \ - vse8_v_##ldst_len((ldst_type *)ptr, vreinterpret_v_##len##_##ldst_len(a0), 8);}\ -inline void v_store(_Tp* ptr, const _Tpvec& a) \ -{ vse##elemsize##_v_##len(ptr, a.val, num); } \ -inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ -{ vse8_v_##ldst_len((ldst_type *)ptr, vreinterpret_v_##len##_##ldst_len(a.val), 16); } \ -inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ -{ vse8_v_##ldst_len((ldst_type *)ptr, vreinterpret_v_##len##_##ldst_len(a.val), 16); } \ -inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ -{ vse8_v_##ldst_len((ldst_type *)ptr, vreinterpret_v_##len##_##ldst_len(a.val), 16); } - -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint8x16, uchar, vuint8m1, u8m1, 8, 16, 8, u8m1, uchar) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int8x16, schar, vint8m1, i8m1, 8, 16, 8, i8m1, schar) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint16x8, ushort, vuint16m1, u16m1, 4, 8, 16, u8m1, uchar) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int16x8, short, vint16m1, i16m1, 4, 8, 16, i8m1, schar) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint32x4, unsigned, vuint32m1, u32m1, 2, 4, 32, u8m1, uchar) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int32x4, int, vint32m1, i32m1, 2, 4, 32, i8m1, schar) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint64x2, unsigned long, vuint64m1, u64m1, 1, 2, 64, u8m1, uchar) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int64x2, long, vint64m1, i64m1, 1, 2, 64, i8m1, schar) - -#define OPENCV_HAL_IMPL_RISCVV_LOADSTORE_FLOAT_OP(_Tpvec, _Tp, _Tp2, len, hnum, num, elemsize) \ -inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ -{ \ - _Tp2##_t res = vundefined_##len(); \ - _Tp2##_t res1 = vundefined_##len(); \ - res = vreinterpret_v_u##elemsize##m1_##len(vreinterpret_v_u8m1_u##elemsize##m1(vle8_v_u8m1((uchar *)ptr0, 8))); \ - res1 = vreinterpret_v_u##elemsize##m1_##len(vreinterpret_v_u8m1_u##elemsize##m1(vle8_v_u8m1((uchar *)ptr1, 8))); \ - res = vslideup_vx_##len(res, res1, hnum, num); \ - return _Tpvec(res); } \ -inline _Tpvec v_load_low(const _Tp* ptr) \ -{ return _Tpvec(vreinterpret_v_u##elemsize##m1_##len(vreinterpret_v_u8m1_u##elemsize##m1(vle8_v_u8m1((uchar *)ptr, 8)))); }\ -inline _Tpvec v_load_aligned(const _Tp* ptr) \ -{ return _Tpvec(vreinterpret_v_u##elemsize##m1_##len(vreinterpret_v_u8m1_u##elemsize##m1(vle8_v_u8m1((uchar *)ptr, 16)))); } \ -inline _Tpvec v_load(const _Tp* ptr) \ -{ return _Tpvec(vle##elemsize##_v_##len(ptr, num)); } \ -inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ -{ vse8_v_u8m1((uchar *)ptr, vreinterpret_v_u##elemsize##m1_u8m1(vreinterpret_v_##len##_u##elemsize##m1(a.val)), 8);}\ -inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ -{ \ - _Tp2##_t a0 = vundefined_##len(); \ - a0 = vslidedown_vx_##len(a0, a.val, hnum, num); \ - vse8_v_u8m1((uchar *)ptr, vreinterpret_v_u##elemsize##m1_u8m1(vreinterpret_v_##len##_u##elemsize##m1(a0)), 8);}\ -inline void v_store(_Tp* ptr, const _Tpvec& a) \ -{ vse##elemsize##_v_##len(ptr, a.val, num); } \ -inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ -{ vse8_v_u8m1((uchar *)ptr, vreinterpret_v_u##elemsize##m1_u8m1(vreinterpret_v_##len##_u##elemsize##m1(a.val)), 16); } \ -inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ -{ vse8_v_u8m1((uchar *)ptr, vreinterpret_v_u##elemsize##m1_u8m1(vreinterpret_v_##len##_u##elemsize##m1(a.val)), 16); } \ -inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ -{ vse8_v_u8m1((uchar *)ptr, vreinterpret_v_u##elemsize##m1_u8m1(vreinterpret_v_##len##_u##elemsize##m1(a.val)), 16); } -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_FLOAT_OP(v_float32x4, float, vfloat32m1, f32m1, 2, 4, 32) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_FLOAT_OP(v_float64x2, double, vfloat64m1, f64m1, 1, 2, 64) - -#else - -#define OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(_Tpvec, _Tp, _Tp2, len, hnum, num, elemsize) \ -inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ -{ \ - _Tp2##_t res, res1; \ - res = vle##elemsize##_v_##len(ptr0, hnum); \ - res1 = vle##elemsize##_v_##len(ptr1, hnum); \ - res = vslideup_vx_##len(res, res1, hnum, num); \ - return _Tpvec(res); } \ -inline _Tpvec v_load_low(const _Tp* ptr) \ -{ return _Tpvec(vle##elemsize##_v_##len(ptr, hnum)); }\ -inline _Tpvec v_load_aligned(const _Tp* ptr) \ -{ return _Tpvec(vle##elemsize##_v_##len(ptr, num)); } \ -inline _Tpvec v_load(const _Tp* ptr) \ -{ return _Tpvec((_Tp2##_t)vle##elemsize##_v_##len((const _Tp *)ptr, num)); } \ -inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ -{ vse##elemsize##_v_##len(ptr, a.val, hnum);}\ -inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ -{ \ - _Tp2##_t a0; \ - a0 = vslidedown_vx_##len(a0, a.val, hnum, num); \ - vse##elemsize##_v_##len(ptr, a0, hnum);}\ -inline void v_store(_Tp* ptr, const _Tpvec& a) \ -{ vse##elemsize##_v_##len(ptr, a.val, num); } \ -inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ -{ vse##elemsize##_v_##len(ptr, a.val, num); } \ -inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ -{ vse##elemsize##_v_##len(ptr, a.val, num); } \ -inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ -{ vse##elemsize##_v_##len(ptr, a.val, num); } - -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint8x16, uchar, vuint8m1, u8m1, 8, 16, 8) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int8x16, schar, vint8m1, i8m1, 8, 16, 8) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint16x8, ushort, vuint16m1, u16m1, 4, 8, 16) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int16x8, short, vint16m1, i16m1, 4, 8, 16) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint32x4, unsigned, vuint32m1, u32m1, 2, 4, 32) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int32x4, int, vint32m1, i32m1, 2, 4, 32) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint64x2, unsigned long, vuint64m1, u64m1, 1, 2, 64) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int64x2, long, vint64m1, i64m1, 1, 2, 64) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_float32x4, float, vfloat32m1, f32m1, 2, 4, 32) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_float64x2, double, vfloat64m1, f64m1, 1, 2, 64) - -#endif - -////////////// Lookup table access //////////////////// - -inline v_int8x16 v_lut(const schar* tab, const int* idx) -{ -#if 0 - schar CV_DECL_ALIGNED(32) elems[16] = - { - tab[idx[ 0]], - tab[idx[ 1]], - tab[idx[ 2]], - tab[idx[ 3]], - tab[idx[ 4]], - tab[idx[ 5]], - tab[idx[ 6]], - tab[idx[ 7]], - tab[idx[ 8]], - tab[idx[ 9]], - tab[idx[10]], - tab[idx[11]], - tab[idx[12]], - tab[idx[13]], - tab[idx[14]], - tab[idx[15]] - }; - return v_int8x16(vle8_v_i8m1(elems, 16)); -#else -#if __riscv_v == 7000 - return v_int8x16(vnclip_wx_i8m1(vnclip_wx_i16m2(vlxb_v_i32m4((const int *)tab, vle32_v_u32m4((unsigned int *)idx, 16), 16), 0, 16), 0, 16)); -#else - return v_int8x16(vloxei32_v_i8m1(tab, vle32_v_u32m4((unsigned int *)idx, 16), 16)); -#endif -#endif -} - -inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx){ -#if 0 - schar CV_DECL_ALIGNED(32) elems[16] = - { - tab[idx[0]], - tab[idx[0] + 1], - tab[idx[1]], - tab[idx[1] + 1], - tab[idx[2]], - tab[idx[2] + 1], - tab[idx[3]], - tab[idx[3] + 1], - tab[idx[4]], - tab[idx[4] + 1], - tab[idx[5]], - tab[idx[5] + 1], - tab[idx[6]], - tab[idx[6] + 1], - tab[idx[7]], - tab[idx[7] + 1] - }; - return v_int8x16(vle8_v_i8m1(elems, 16)); -#else - vuint32m4_t seq, index; - vuint32m4_t vidx = vle32_v_u32m4((unsigned int *)idx, 8); - seq = vid_v_u32m4(16); - index = vsrl_vx_u32m4(seq, 1, 16); - vidx = vrgather_vv_u32m4(vidx, index, 16); - index = vadd_vv_u32m4(vand_vx_u32m4(seq, 1, 16), vidx, 16); -#if __riscv_v == 7000 - return v_int8x16(vnclip_wx_i8m1(vnclip_wx_i16m2(vlxb_v_i32m4((const int *)tab, index, 16), 0, 16), 0, 16)); -#else - return v_int8x16(vloxei32_v_i8m1(tab, index, 16)); -#endif -#endif -} -inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) -{ -#if 0 - schar CV_DECL_ALIGNED(32) elems[16] = - { - tab[idx[0]], - tab[idx[0] + 1], - tab[idx[0] + 2], - tab[idx[0] + 3], - tab[idx[1]], - tab[idx[1] + 1], - tab[idx[1] + 2], - tab[idx[1] + 3], - tab[idx[2]], - tab[idx[2] + 1], - tab[idx[2] + 2], - tab[idx[2] + 3], - tab[idx[3]], - tab[idx[3] + 1], - tab[idx[3] + 2], - tab[idx[3] + 3] - }; - return v_int8x16(vle8_v_i8m1(elems, 16)); -#else - vuint32m4_t seq, index; - vuint32m4_t vidx = vle32_v_u32m4((unsigned int *)idx, 4); - seq = vid_v_u32m4(16); - index = vsrl_vx_u32m4(seq, 2, 16); - vidx = vrgather_vv_u32m4(vidx, index, 16); - seq = vset_v_u32m1_u32m4(seq, 1, vget_v_u32m4_u32m1(seq, 0)); - seq = vset_v_u32m1_u32m4(seq, 2, vget_v_u32m4_u32m1(seq, 0)); - seq = vset_v_u32m1_u32m4(seq, 3, vget_v_u32m4_u32m1(seq, 0)); - index = vadd_vv_u32m4(seq, vidx, 16); -#if __riscv_v == 7000 - return v_int8x16(vnclip_wx_i8m1(vnclip_wx_i16m2(vlxb_v_i32m4((const int *)tab, index, 16), 0, 16), 0, 16)); -#else - return v_int8x16(vloxei32_v_i8m1(tab, index, 16)); -#endif -#endif -} - -inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((schar*)tab, idx)); } -inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((schar*)tab, idx)); } -inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((schar*)tab, idx)); } - -inline v_int16x8 v_lut(const short* tab, const int* idx) -{ -#if 0 - short CV_DECL_ALIGNED(32) elems[8] = - { - tab[idx[0]], - tab[idx[1]], - tab[idx[2]], - tab[idx[3]], - tab[idx[4]], - tab[idx[5]], - tab[idx[6]], - tab[idx[7]] - }; - return v_int16x8(vle16_v_i16m1(elems, 8)); -#else -#if __riscv_v == 7000 - return v_int16x8(vnclip_wx_i16m1(vlxh_v_i32m2((const int *)tab, vsll_vx_u32m2(vle32_v_u32m2((unsigned int *)idx, 8), 1, 8), 8), 0, 8)); -#else - return v_int16x8(vloxei32_v_i16m1(tab, vsll_vx_u32m2(vle32_v_u32m2((unsigned int *)idx, 8), 1, 8), 8)); -#endif -#endif -} -inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) -{ -#if 0 - short CV_DECL_ALIGNED(32) elems[8] = - { - tab[idx[0]], - tab[idx[0] + 1], - tab[idx[1]], - tab[idx[1] + 1], - tab[idx[2]], - tab[idx[2] + 1], - tab[idx[3]], - tab[idx[3] + 1] - }; - return v_int16x8(vle16_v_i16m1(elems, 8)); -#else - vuint32m2_t seq, index; - vuint32m2_t vidx = vle32_v_u32m2((unsigned int *)idx, 4); - seq = vid_v_u32m2(8); - index = vsrl_vx_u32m2(seq, 1, 8); - vidx = vrgather_vv_u32m2(vidx, index, 8); - index = vsll_vx_u32m2(vadd_vv_u32m2(vand_vx_u32m2(seq, 1, 8), vidx, 8), 1, 8); -#if __riscv_v == 7000 - return v_int16x8(vnclip_wx_i16m1(vlxh_v_i32m2((const int *)tab, index, 8), 0, 8)); -#else - return v_int16x8(vloxei32_v_i16m1(tab, index, 8)); -#endif -#endif -} -inline v_int16x8 v_lut_quads(const short* tab, const int* idx) -{ -#if 0 - short CV_DECL_ALIGNED(32) elems[8] = - { - tab[idx[0]], - tab[idx[0] + 1], - tab[idx[0] + 2], - tab[idx[0] + 3], - tab[idx[1]], - tab[idx[1] + 1], - tab[idx[1] + 2], - tab[idx[1] + 3] - }; - return v_int16x8(vle16_v_i16m1(elems, 8)); -#else - vuint32m2_t seq, index; - vuint32m2_t vidx = vle32_v_u32m2((unsigned int *)idx, 2); - seq = vid_v_u32m2(8); - index = vsrl_vx_u32m2(seq, 2, 8); - vidx = vrgather_vv_u32m2(vidx, index, 8); - seq = vset_v_u32m1_u32m2(seq, 1, vget_v_u32m2_u32m1(seq, 0)); - index = vsll_vx_u32m2(vadd_vv_u32m2(seq, vidx, 8), 1, 8); -#if __riscv_v == 7000 - return v_int16x8(vnclip_wx_i16m1(vlxh_v_i32m2((const int *)tab, index, 8), 0, 8)); -#else - return v_int16x8(vloxei32_v_i16m1(tab, index, 8)); -#endif -#endif -} -inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((short*)tab, idx)); } -inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((short*)tab, idx)); } -inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((short*)tab, idx)); } - -inline v_int32x4 v_lut(const int* tab, const int* idx) -{ -#if 0 - int CV_DECL_ALIGNED(32) elems[4] = - { - tab[idx[0]], - tab[idx[1]], - tab[idx[2]], - tab[idx[3]] - }; - return v_int32x4(vle32_v_i32m1(elems, 4)); -#else - return v_int32x4(vloxei32_v_i32m1(tab, vsll_vx_u32m1(vle32_v_u32m1((unsigned int *)idx, 4), 2, 4), 4)); -#endif -} -inline v_int32x4 v_lut_pairs(const int* tab, const int* idx) -{ -#if 0 - int CV_DECL_ALIGNED(32) elems[4] = - { - tab[idx[0]], - tab[idx[0] + 1], - tab[idx[1]], - tab[idx[1] + 1] - }; - return v_int32x4(vle32_v_i32m1(elems, 4)); -#else - vuint32m1_t seq, index; - vuint32m1_t vidx = vle32_v_u32m1((unsigned int *)idx, 2); - seq = vid_v_u32m1(4); - index = vsrl_vx_u32m1(seq, 1, 4); - vidx = vrgather_vv_u32m1(vidx, index, 4); - index = vsll_vx_u32m1(vadd_vv_u32m1(vand_vx_u32m1(seq, 1, 4), vidx, 4), 2, 4); - return v_int32x4(vloxei32_v_i32m1(tab, index, 4)); -#endif -} -inline v_int32x4 v_lut_quads(const int* tab, const int* idx) -{ - return v_int32x4(vle32_v_i32m1(tab+idx[0], 4)); -} -inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((int*)tab, idx)); } -inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((int*)tab, idx)); } -inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((int*)tab, idx)); } - -inline v_int64x2 v_lut(const int64_t* tab, const int* idx) -{ - //vint64m1_t res = {tab[idx[0]], tab[idx[1]]}; - return v_int64x2(vloxei64_v_i64m1(tab, vsll_vx_u64m1(vget_v_u64m2_u64m1(vwaddu_vx_u64m2(vle32_v_u32m1((uint32_t*)idx, 2), 0, 2), 0), 3, 2), 2)); -} -inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) -{ - return v_int64x2(vle64_v_i64m1(tab+idx[0], 2)); -} - -inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) -{ - //vuint64m1_t res = {tab[idx[0]], tab[idx[1]]}; - return v_uint64x2(vloxei64_v_u64m1(tab, vsll_vx_u64m1(vget_v_u64m2_u64m1(vwaddu_vx_u64m2(vle32_v_u32m1((uint32_t*)idx, 2), 0, 2), 0), 3, 2), 2)); -} -inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) -{ - return v_uint64x2(vle64_v_u64m1(tab+idx[0], 2)); -} - -inline v_float32x4 v_lut(const float* tab, const int* idx) -{ -#if 0 - float CV_DECL_ALIGNED(32) elems[4] = - { - tab[idx[0]], - tab[idx[1]], - tab[idx[2]], - tab[idx[3]] - }; - return v_float32x4(vle32_v_f32m1(elems, 4)); -#else - return v_float32x4(vloxei32_v_f32m1(tab, vsll_vx_u32m1(vle32_v_u32m1((unsigned int *)idx, 4), 2, 4), 4)); -#endif -} -inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) -{ -#if 0 - float CV_DECL_ALIGNED(32) elems[4] = - { - tab[idx[0]], - tab[idx[0]+1], - tab[idx[1]], - tab[idx[1]+1] - }; - return v_float32x4(vle32_v_f32m1(elems, 4)); -#else - vuint32m1_t seq, index; - vuint32m1_t vidx = vle32_v_u32m1((unsigned int *)idx, 2); - seq = vid_v_u32m1(4); - index = vsrl_vx_u32m1(seq, 1, 4); - vidx = vrgather_vv_u32m1(vidx, index, 4); - index = vsll_vx_u32m1(vadd_vv_u32m1(vand_vx_u32m1(seq, 1, 4), vidx, 4), 2, 4); - return v_float32x4(vloxei32_v_f32m1(tab, index, 4)); -#endif -} -inline v_float32x4 v_lut_quads(const float* tab, const int* idx) -{ - return v_float32x4(vle32_v_f32m1(tab + idx[0], 4)); -} -inline v_float64x2 v_lut(const double* tab, const int* idx) -{ - //vfloat64m1_t res = {tab[idx[0]], tab[idx[1]]}; - return v_float64x2(vloxei64_v_f64m1(tab, vsll_vx_u64m1(vget_v_u64m2_u64m1(vwaddu_vx_u64m2(vle32_v_u32m1((uint32_t*)idx, 2), 0, 2), 0), 3, 2), 2)); -} -inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) -{ - return v_float64x2(vle64_v_f64m1(tab+idx[0], 2)); -} - -inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) -{ - /*int CV_DECL_ALIGNED(32) elems[4] = - { - tab[idxvec.val[0]], - tab[idxvec.val[1]], - tab[idxvec.val[2]], - tab[idxvec.val[3]] - };*/ - return v_int32x4(vloxei32_v_i32m1(tab, vsll_vx_u32m1(vreinterpret_v_i32m1_u32m1(idxvec.val), 2, 4), 4)); -} - -inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) -{ - /*unsigned CV_DECL_ALIGNED(32) elems[4] = - { - tab[idxvec.val[0]], - tab[idxvec.val[1]], - tab[idxvec.val[2]], - tab[idxvec.val[3]] - };*/ - return v_uint32x4(vloxei32_v_u32m1(tab, vsll_vx_u32m1(vreinterpret_v_i32m1_u32m1(idxvec.val), 2, 4), 4)); -} - -inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) -{ - /*float CV_DECL_ALIGNED(32) elems[4] = - { - tab[idxvec.val[0]], - tab[idxvec.val[1]], - tab[idxvec.val[2]], - tab[idxvec.val[3]] - };*/ - return v_float32x4(vloxei32_v_f32m1(tab, vsll_vx_u32m1(vreinterpret_v_i32m1_u32m1(idxvec.val), 2, 4), 4)); -} -inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) -{ - //vfloat64m1_t res = {tab[idxvec.val[0]], tab[idxvec.val[1]]}; - return v_float64x2(vloxei64_v_f64m1(tab, vsll_vx_u64m1(vreinterpret_v_i64m1_u64m1(vget_v_i64m2_i64m1(vwadd_vx_i64m2(idxvec.val, 0, 2), 0)), 3, 2), 2)); -} -inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) -{ - vint32m1_t index = vmul_vx_i32m1(idxvec.val, 4, 4); - //vint32m1_t index_y = vadd_vx_i32m1(index_x, 4, 4); - - //x.val = vlxe_v_f32m1(tab, index_x, 4); - //y.val = vlxe_v_f32m1(tab, index_y, 4); - vloxseg2ei32_v_f32m1(&x.val, &y.val, tab, vreinterpret_v_i32m1_u32m1(index), 4); -} - -inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) -{ - int CV_DECL_ALIGNED(32) idx[4]; - v_store_aligned(idx, idxvec); - - x = v_float64x2(tab[idx[0]], tab[idx[1]]); - y = v_float64x2(tab[idx[0]+1], tab[idx[1]+1]); -} - -#define OPENCV_HAL_IMPL_RISCVV_PACKS(_Tp, _Tp2, _T2, num2, _T1, num, intrin, shr, _Type, elemsize) \ -inline v_##_Tp##x##num v_pack(const v_##_Tp2##x##num2& a, const v_##_Tp2##x##num2& b) \ -{ \ - v##_Tp2##m2_t tmp = vundefined_##_T2##m2(); \ - tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 0, a.val); \ - tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 1, b.val); \ - return v_##_Tp##x##num(shr##_##_T1##m1(tmp, 0, num)); \ -}\ -template inline \ -v_##_Tp##x##num v_rshr_pack(const v_##_Tp2##x##num2& a, const v_##_Tp2##x##num2& b) \ -{ \ - v##_Tp2##m2_t tmp = vundefined_##_T2##m2(); \ - tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 0, a.val); \ - tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 1, b.val); \ - return v_##_Tp##x##num(intrin##_##_T1##m1(tmp, n, num)); \ -}\ -inline void v_pack_store(_Type* ptr, const v_##_Tp2##x##num2& a) \ -{ \ - v##_Tp2##m2_t tmp = vundefined_##_T2##m2(); \ - tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 0, a.val); \ - tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 1, vmv_v_x_##_T2##m1(0, num2)); \ - asm("" ::: "memory"); \ - vse##elemsize##_v_##_T1##m1(ptr, shr##_##_T1##m1(tmp, 0, num), num2); \ -}\ -template inline \ -void v_rshr_pack_store(_Type* ptr, const v_##_Tp2##x##num2& a) \ -{ \ - v##_Tp2##m2_t tmp = vundefined_##_T2##m2(); \ - tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 0, a.val); \ - tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 1, vmv_v_x_##_T2##m1(0, num2)); \ - vse##elemsize##_v_##_T1##m1(ptr, intrin##_##_T1##m1(tmp, n, num), num2); \ -} -OPENCV_HAL_IMPL_RISCVV_PACKS(int8, int16, i16, 8, i8, 16, vnclip_wx, vnclip_wx, signed char, 8) -OPENCV_HAL_IMPL_RISCVV_PACKS(int16, int32, i32, 4, i16, 8, vnclip_wx, vnclip_wx, signed short, 16) -OPENCV_HAL_IMPL_RISCVV_PACKS(int32, int64, i64, 2, i32, 4, vnclip_wx, vnsra_wx, int, 32) -OPENCV_HAL_IMPL_RISCVV_PACKS(uint8, uint16, u16, 8, u8, 16, vnclipu_wx, vnclipu_wx, unsigned char, 8) -OPENCV_HAL_IMPL_RISCVV_PACKS(uint16, uint32, u32, 4, u16, 8, vnclipu_wx, vnclipu_wx, unsigned short, 16) -OPENCV_HAL_IMPL_RISCVV_PACKS(uint32, uint64, u64, 2, u32, 4, vnclipu_wx, vnsrl_wx, unsigned int, 32) - -// pack boolean -inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) -{ - vuint16m2_t tmp = vundefined_u16m2(); \ - tmp = vset_v_u16m1_u16m2(tmp, 0, a.val); \ - tmp = vset_v_u16m1_u16m2(tmp, 1, b.val); \ - return v_uint8x16(vnsrl_wx_u8m1(tmp, 0, 16)); -} - -inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, - const v_uint32x4& c, const v_uint32x4& d) -{ - vuint32m4_t vabcd = vundefined_u32m4(); \ - vuint16m2_t v16 = vundefined_u16m2(); \ - vabcd = vset_v_u32m1_u32m4(vabcd, 0, a.val); \ - vabcd = vset_v_u32m1_u32m4(vabcd, 1, b.val); \ - vabcd = vset_v_u32m1_u32m4(vabcd, 2, c.val); \ - vabcd = vset_v_u32m1_u32m4(vabcd, 3, d.val); \ - v16 = vnsrl_wx_u16m2(vabcd, 0, 16); - return v_uint8x16(vnsrl_wx_u8m1(v16, 0, 16)); -} - -inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, - const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, - const v_uint64x2& g, const v_uint64x2& h) -{ - vuint64m8_t v64 = vundefined_u64m8(); \ - vuint32m4_t v32 = vundefined_u32m4(); \ - vuint16m2_t v16 = vundefined_u16m2(); \ - v64 = vset_v_u64m1_u64m8(v64, 0, a.val); \ - v64 = vset_v_u64m1_u64m8(v64, 1, b.val); \ - v64 = vset_v_u64m1_u64m8(v64, 2, c.val); \ - v64 = vset_v_u64m1_u64m8(v64, 3, d.val); \ - v64 = vset_v_u64m1_u64m8(v64, 4, e.val); \ - v64 = vset_v_u64m1_u64m8(v64, 5, f.val); \ - v64 = vset_v_u64m1_u64m8(v64, 6, g.val); \ - v64 = vset_v_u64m1_u64m8(v64, 7, h.val); \ - v32 = vnsrl_wx_u32m4(v64, 0, 16); - v16 = vnsrl_wx_u16m2(v32, 0, 16); - return v_uint8x16(vnsrl_wx_u8m1(v16, 0, 16)); -} - -//inline v_uint8x16 v_pack_u(const v_int16x8& a, const v_int16x8& b) \ -//{ \ -// int16xm2_u tmp; \ -// tmp.m1[0] = (vint16m1_t)a.val; \ -// tmp.m1[1] = (vint16m1_t)b.val; \ -// e8xm1_t mask = (e8xm1_t)vmsge_vx_e16xm2_i16m2(tmp.v, 0, 16);\ -// return v_uint8x16(vnclipuvi_mask_u8m1_u16m2(vmv_v_x_u8m1(0, 16), (vuint16m2_t)tmp.v, 0, mask, 16)); -//} - -#define OPENCV_HAL_IMPL_RISCVV_PACK_U(tp1, num1, tp2, num2, _Tp) \ -inline v_uint##tp1##x##num1 v_pack_u(const v_int##tp2##x##num2& a, const v_int##tp2##x##num2& b) \ -{ \ - vint##tp2##m2_t tmp = vundefined_##i##tp2##m2(); \ - tmp = vset_v_##i##tp2##m1_##i##tp2##m2(tmp, 0, a.val); \ - tmp = vset_v_##i##tp2##m1_##i##tp2##m2(tmp, 1, b.val); \ - vint##tp2##m2_t val = vmax_vx_i##tp2##m2(tmp, 0, num1);\ - return v_uint##tp1##x##num1(vnclipu_wx_u##tp1##m1(vreinterpret_v_i##tp2##m2_u##tp2##m2(val), 0, num1)); \ -} \ -inline void v_pack_u_store(_Tp* ptr, const v_int##tp2##x##num2& a) \ -{ \ - vint##tp2##m2_t tmp = vundefined_##i##tp2##m2(); \ - tmp = vset_v_##i##tp2##m1_##i##tp2##m2(tmp, 0, a.val); \ - vint##tp2##m2_t val = vmax_vx_i##tp2##m2(tmp, 0, num1);\ - return vse##tp1##_v_u##tp1##m1(ptr, vnclipu_wx_u##tp1##m1(vreinterpret_v_i##tp2##m2_u##tp2##m2(val), 0, num1), num2); \ -} \ -template inline \ -v_uint##tp1##x##num1 v_rshr_pack_u(const v_int##tp2##x##num2& a, const v_int##tp2##x##num2& b) \ -{ \ - vint##tp2##m2_t tmp = vundefined_##i##tp2##m2(); \ - tmp = vset_v_##i##tp2##m1_##i##tp2##m2(tmp, 0, a.val); \ - tmp = vset_v_##i##tp2##m1_##i##tp2##m2(tmp, 1, b.val); \ - vint##tp2##m2_t val = vmax_vx_i##tp2##m2(tmp, 0, num1);\ - return v_uint##tp1##x##num1(vnclipu_wx_u##tp1##m1(vreinterpret_v_i##tp2##m2_u##tp2##m2(val), n, num1)); \ -} \ -template inline \ -void v_rshr_pack_u_store(_Tp* ptr, const v_int##tp2##x##num2& a) \ -{ \ - vint##tp2##m2_t tmp = vundefined_##i##tp2##m2(); \ - tmp = vset_v_##i##tp2##m1_##i##tp2##m2(tmp, 0, a.val); \ - vint##tp2##m2_t val_ = vmax_vx_i##tp2##m2(tmp, 0, num1);\ - vuint##tp1##m1_t val = vnclipu_wx_u##tp1##m1(vreinterpret_v_i##tp2##m2_u##tp2##m2(val_), n, num1); \ - return vse##tp1##_v_u##tp1##m1(ptr, val, num2);\ -} -OPENCV_HAL_IMPL_RISCVV_PACK_U(8, 16, 16, 8, unsigned char ) -OPENCV_HAL_IMPL_RISCVV_PACK_U(16, 8, 32, 4, unsigned short) - - -// saturating multiply 8-bit, 16-bit -#define OPENCV_HAL_IMPL_RISCVV_MUL_SAT(_Tpvec, num, mul, cvt) \ - inline _Tpvec v_mul(const _Tpvec& a, const _Tpvec& b) \ - { \ - auto res = mul(a.val, b.val, num); \ - return _Tpvec(cvt(res, 0, num)); \ - } - -OPENCV_HAL_IMPL_RISCVV_MUL_SAT(v_int8x16, 16, vwmul_vv_i16m2, vnclip_wx_i8m1) -OPENCV_HAL_IMPL_RISCVV_MUL_SAT(v_uint8x16, 16, vwmulu_vv_u16m2, vnclipu_wx_u8m1) -OPENCV_HAL_IMPL_RISCVV_MUL_SAT(v_int16x8, 32, vwmul_vv_i32m2, vnclip_wx_i16m1) -OPENCV_HAL_IMPL_RISCVV_MUL_SAT(v_uint16x8, 32, vwmulu_vv_u32m2, vnclipu_wx_u16m1) - - -static const signed char popCountTable[256] = -{ - 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, -}; - -inline vuint8m1_t vcnt_u8(vuint8m1_t val){ -#if __riscv_v == 7000 - vuint8m1_t v0 = vand_vx_u8m1(val, 1, 16); - return vadd_vv_u8m1(vloxei8_v_u8m1((unsigned char*)popCountTable, vsrl_vx_u8m1(val, 1, 16), 16), v0, 16); -#else - return vloxei8_v_u8m1((unsigned char*)popCountTable, val, 16); -#endif -} - -inline v_uint8x16 -v_popcount(const v_uint8x16& a) -{ - return v_uint8x16(vcnt_u8(a.val)); -} - -inline v_uint8x16 -v_popcount(const v_int8x16& a) -{ - return v_uint8x16(vcnt_u8(vreinterpret_v_i8m1_u8m1(a.val))); -} - -inline v_uint16x8 -v_popcount(const v_uint16x8& a) -{ - vuint8m1_t tmp = vcnt_u8(vreinterpret_v_u16m1_u8m1(a.val)); - vuint8m1_t seq = vid_v_u8m1(8); - vuint8m1_t index = vsll_vx_u8m1(seq, 1, 8); - return v_uint16x8(vget_v_u16m2_u16m1(vwaddu_vv_u16m2(vrgather_vv_u8m1(tmp, index, 8), vrgather_vv_u8m1(tmp, vadd_vx_u8m1(index, 1, 8), 8), 8), 0)); -} - -inline v_uint16x8 -v_popcount(const v_int16x8& a) -{ - vuint8m1_t tmp = vcnt_u8(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i16m1_i8m1(a.val))); - vuint8m1_t seq = vid_v_u8m1(8); - vuint8m1_t index = vsll_vx_u8m1(seq, 1, 8); - return v_uint16x8(vget_v_u16m2_u16m1(vwaddu_vv_u16m2(vrgather_vv_u8m1(tmp, index, 8), vrgather_vv_u8m1(tmp, vadd_vx_u8m1(index, 1, 8), 8), 8), 0)); -} - -inline v_uint32x4 -v_popcount(const v_uint32x4& a) -{ - vuint8m1_t tmp = vcnt_u8(vreinterpret_v_u32m1_u8m1(a.val)); - vuint8m1_t seq = vid_v_u8m1(8); - vuint8m1_t index = vsll_vx_u8m1(seq, 1, 8); - vuint8m1_t sum = vadd_vv_u8m1(vrgather_vv_u8m1(tmp, index, 8), vrgather_vv_u8m1(tmp, vadd_vx_u8m1(index, 1, 8), 8), 8); - return v_uint32x4(vget_v_u32m4_u32m1(vwaddu_vx_u32m4(vwaddu_vv_u16m2(vrgather_vv_u8m1(sum, index, 4), vrgather_vv_u8m1(sum, vadd_vx_u8m1(index, 1, 4), 4), 4), 0, 4), 0)); -} - -inline v_uint32x4 -v_popcount(const v_int32x4& a) -{ - vuint8m1_t tmp = vcnt_u8(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i32m1_i8m1(a.val))); - vuint8m1_t seq = vid_v_u8m1(8); - vuint8m1_t index = vsll_vx_u8m1(seq, 1, 8); - vuint8m1_t sum = vadd_vv_u8m1(vrgather_vv_u8m1(tmp, index, 8), vrgather_vv_u8m1(tmp, vadd_vx_u8m1(index, 1, 8), 8), 8); - return v_uint32x4(vget_v_u32m4_u32m1(vwaddu_vx_u32m4(vwaddu_vv_u16m2(vrgather_vv_u8m1(sum, index, 4), vrgather_vv_u8m1(sum, vadd_vx_u8m1(index, 1, 4), 4), 4), 0, 4), 0)); -} - -inline v_uint64x2 -v_popcount(const v_uint64x2& a) -{ - vuint8m1_t tmp = vcnt_u8(vreinterpret_v_u64m1_u8m1(a.val)); - vuint16m2_t tmp16 = vwaddu_vx_u16m2(tmp, 0, 16); - vuint16m1_t res1 = vundefined_u16m1(); - vuint16m1_t res2 = vundefined_u16m1(); - res1 = vredsum_vs_u16m1_u16m1(res1, vget_v_u16m2_u16m1(tmp16, 0), vmv_v_x_u16m1(0, 8), 8); - res2 = vredsum_vs_u16m1_u16m1(res2, vget_v_u16m2_u16m1(tmp16, 1), vmv_v_x_u16m1(0, 8), 8); - return v_uint64x2((unsigned long)vmv_x_s_u16m1_u16(res1), (unsigned long)vmv_x_s_u16m1_u16(res2)); -} - -inline v_uint64x2 -v_popcount(const v_int64x2& a) -{ - vuint8m1_t tmp = vcnt_u8(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i64m1_i8m1(a.val))); - vuint16m2_t tmp16 = vwaddu_vx_u16m2(tmp, 0, 16); - vuint16m1_t res1 = vundefined_u16m1(), res2 = vundefined_u16m1(); - res1 = vredsum_vs_u16m1_u16m1(res1, vget_v_u16m2_u16m1(tmp16, 0), vmv_v_x_u16m1(0, 8), 8); - res2 = vredsum_vs_u16m1_u16m1(res2, vget_v_u16m2_u16m1(tmp16, 1), vmv_v_x_u16m1(0, 8), 8); - return v_uint64x2((unsigned long)vmv_x_s_u16m1_u16(res1), (unsigned long)vmv_x_s_u16m1_u16(res2)); -} - -#define SMASK 1, 2, 4, 8, 16, 32, 64, 128 -inline int v_signmask(const v_uint8x16& a) -{ - vuint16m1_t res = vundefined_u16m1(); - vuint8m1_t id = vid_v_u8m1(16); - vuint16m2_t num = vsll_vv_u16m2(vmv_v_x_u16m2(1, 16), vwaddu_vx_u16m2(id, 0, 16), 16); - vuint8m1_t t0 = vsrl_vx_u8m1(a.val, 7, 16); - vbool8_t mask = vmseq_vx_u8m1_b8(t0, 1, 16); - res = vredsum_vs_u16m2_u16m1_m(mask, res, num, vmv_v_x_u16m1(0, 8), 16); - return vmv_x_s_u16m1_u16(res); -} -inline int v_signmask(const v_int8x16& a) -{ - vuint16m1_t res = vundefined_u16m1(); - vuint8m1_t id = vid_v_u8m1(16); - vuint16m2_t num = vsll_vv_u16m2(vmv_v_x_u16m2(1, 16), vwaddu_vx_u16m2(id, 0, 16), 16); - vbool8_t mask = vmslt_vx_i8m1_b8(a.val, 0, 16); - res = vredsum_vs_u16m2_u16m1_m(mask, res, num, vmv_v_x_u16m1(0, 8), 16); - return vmv_x_s_u16m1_u16(res); -} - -inline int v_signmask(const v_int16x8& a) -{ - vuint16m1_t res = vundefined_u16m1(); - vuint16m1_t id = vid_v_u16m1(8); - vuint16m1_t num = vsll_vv_u16m1(vmv_v_x_u16m1(1, 8), id, 8); - vbool16_t mask = vmslt_vx_i16m1_b16(a.val, 0, 8); - res = vredsum_vs_u16m1_u16m1_m(mask, res, num, vmv_v_x_u16m1(0, 8), 16); - return vmv_x_s_u16m1_u16(res); -} -inline int v_signmask(const v_uint16x8& a) -{ - vuint16m1_t res = vundefined_u16m1(); - vuint16m1_t id = vid_v_u16m1(8); - vuint16m1_t num = vsll_vv_u16m1(vmv_v_x_u16m1(1, 8), id, 8); - vuint16m1_t t0 = vsrl_vx_u16m1(a.val, 15, 8); - vbool16_t mask = vmseq_vx_u16m1_b16(t0, 1, 8); - res = vredsum_vs_u16m1_u16m1_m(mask, res, num, vmv_v_x_u16m1(0, 8), 8); - return vmv_x_s_u16m1_u16(res); -} -inline int v_signmask(const v_int32x4& a) -{ - vuint32m1_t res = vundefined_u32m1(); - vuint32m1_t id = vid_v_u32m1(4); - vuint32m1_t num = vsll_vv_u32m1(vmv_v_x_u32m1(1, 4), id, 4); - vbool32_t mask = vmslt_vx_i32m1_b32(a.val, 0, 4); - res = vredsum_vs_u32m1_u32m1_m(mask, res, num, vmv_v_x_u32m1(0, 4), 4); - return vmv_x_s_u32m1_u32(res); -} -inline int v_signmask(const v_uint32x4& a) -{ - vuint32m1_t res = vundefined_u32m1(); - vuint32m1_t id = vid_v_u32m1(4); - vuint32m1_t num = vsll_vv_u32m1(vmv_v_x_u32m1(1, 4), id, 4); - vuint32m1_t t0 = vsrl_vx_u32m1(a.val, 31, 4); - vbool32_t mask = vmseq_vx_u32m1_b32(t0, 1, 4); - res = vredsum_vs_u32m1_u32m1_m(mask, res, num, vmv_v_x_u32m1(0, 4), 4); - return vmv_x_s_u32m1_u32(res); -} -inline int v_signmask(const v_uint64x2& a) -{ - vuint64m1_t res = vundefined_u64m1(); - vuint64m1_t id = vid_v_u64m1(2); - vuint64m1_t num = vsll_vv_u64m1(vmv_v_x_u64m1(1, 2), id, 2); - vuint64m1_t t0 = vsrl_vx_u64m1(a.val, 63, 2); - vbool64_t mask = vmseq_vx_u64m1_b64(t0, 1, 2); - res = vredsum_vs_u64m1_u64m1_m(mask, res, num, vmv_v_x_u64m1(0, 2), 2); - return vmv_x_s_u64m1_u64(res); -} -inline int v_signmask(const v_int64x2& a) -{ return v_signmask(v_reinterpret_as_u64(a)); } -inline int v_signmask(const v_float64x2& a) -{ return v_signmask(v_reinterpret_as_u64(a)); } -inline int v_signmask(const v_float32x4& a) -{ - return v_signmask(v_reinterpret_as_u32(a)); - /* - vuint32m1_t res; - vuint32m1_t id = vid_v_u32m1(4); - vuint32m1_t num = vsll_vv_u32m1(vmv_v_x_u32m1(1, 4), id, 4); - vbool32_t mask = vmflt_vf_f32m1_b32(a.val, 0, 4); - res = vredsum_vs_u32m1_u32m1_m(mask, res, num, vmv_v_x_u32m1(0, 4), 4); - return vmv_x_s_u32m1_u32(res);*/ -} - -inline int v_scan_forward(const v_int8x16& a) { -int val = v_signmask(a); -if(val==0) return 0; -else return trailingZeros32(val); } -inline int v_scan_forward(const v_uint8x16& a) { -int val = v_signmask(a); -if(val==0) return 0; -else return trailingZeros32(val); } -inline int v_scan_forward(const v_int16x8& a) { -int val = v_signmask(a); -if(val==0) return 0; -else return trailingZeros32(val); } -inline int v_scan_forward(const v_uint16x8& a) { -int val = v_signmask(a); -if(val==0) return 0; -else return trailingZeros32(val); } -inline int v_scan_forward(const v_int32x4& a) { -int val = v_signmask(a); -if(val==0) return 0; -else return trailingZeros32(val); } -inline int v_scan_forward(const v_uint32x4& a) { -int val = v_signmask(a); -if(val==0) return 0; -else return trailingZeros32(val); } -inline int v_scan_forward(const v_float32x4& a) { -int val = v_signmask(a); -if(val==0) return 0; -else return trailingZeros32(val); } -inline int v_scan_forward(const v_int64x2& a) { -int val = v_signmask(a); -if(val==0) return 0; -else return trailingZeros32(val); } -inline int v_scan_forward(const v_uint64x2& a) { -int val = v_signmask(a); -if(val==0) return 0; -else return trailingZeros32(val); } - -#define OPENCV_HAL_IMPL_RISCVV_CHECK_ALLANY(_Tpvec, suffix, _T, shift, num, mask_b) \ -inline bool v_check_all(const v_##_Tpvec& a) \ -{ \ - suffix##m1_t v0 = vsrl_vx_##_T(vnot_v_##_T(a.val, num), shift, num); \ - return (vcpop_m_##mask_b(vmseq_vx_##_T##_##mask_b(v0, 1, num), num)) == 0; \ -} \ -inline bool v_check_any(const v_##_Tpvec& a) \ -{ \ - suffix##m1_t v0 = vsrl_vx_##_T(a.val, shift, num); \ - return (vcpop_m_##mask_b(vmseq_vx_##_T##_##mask_b(v0, 1, num), num)) != 0; \ -} - -OPENCV_HAL_IMPL_RISCVV_CHECK_ALLANY(uint8x16, vuint8, u8m1, 7, 16, b8) -OPENCV_HAL_IMPL_RISCVV_CHECK_ALLANY(uint16x8, vuint16, u16m1, 15, 8, b16) -OPENCV_HAL_IMPL_RISCVV_CHECK_ALLANY(uint32x4, vuint32, u32m1, 31, 4, b32) -OPENCV_HAL_IMPL_RISCVV_CHECK_ALLANY(uint64x2, vuint64, u64m1, 63, 2, b64) - -inline bool v_check_all(const v_int8x16& a) -{ return v_check_all(v_reinterpret_as_u8(a)); } -inline bool v_check_all(const v_int16x8& a) -{ return v_check_all(v_reinterpret_as_u16(a)); } -inline bool v_check_all(const v_int32x4& a) -{ return v_check_all(v_reinterpret_as_u32(a)); } -inline bool v_check_all(const v_float32x4& a) -{ return v_check_all(v_reinterpret_as_u32(a)); } -inline bool v_check_all(const v_int64x2& a) -{ return v_check_all(v_reinterpret_as_u64(a)); } -inline bool v_check_all(const v_float64x2& a) -{ return v_check_all(v_reinterpret_as_u64(a)); } - -inline bool v_check_any(const v_int8x16& a) -{ return v_check_any(v_reinterpret_as_u8(a)); } -inline bool v_check_any(const v_int16x8& a) -{ return v_check_any(v_reinterpret_as_u16(a)); } -inline bool v_check_any(const v_int32x4& a) -{ return v_check_any(v_reinterpret_as_u32(a)); } -inline bool v_check_any(const v_float32x4& a) -{ return v_check_any(v_reinterpret_as_u32(a)); } -inline bool v_check_any(const v_int64x2& a) -{ return v_check_any(v_reinterpret_as_u64(a)); } -inline bool v_check_any(const v_float64x2& a) -{ return v_check_any(v_reinterpret_as_u64(a)); } - -#define OPENCV_HAL_IMPL_RISCVV_SELECT(_Tpvec, suffix, _Tpvec2, num, mask_func) \ -inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(vmerge_vvm_##suffix(mask_func(mask.val, 0, num), b.val, a.val, num)); \ -} - -OPENCV_HAL_IMPL_RISCVV_SELECT(v_int8x16, i8m1, vbool8_t, 16, vmsne_vx_i8m1_b8) -OPENCV_HAL_IMPL_RISCVV_SELECT(v_int16x8, i16m1, vbool16_t, 8, vmsne_vx_i16m1_b16) -OPENCV_HAL_IMPL_RISCVV_SELECT(v_int32x4, i32m1, vbool32_t, 4, vmsne_vx_i32m1_b32) -OPENCV_HAL_IMPL_RISCVV_SELECT(v_uint8x16, u8m1, vbool8_t, 16, vmsne_vx_u8m1_b8) -OPENCV_HAL_IMPL_RISCVV_SELECT(v_uint16x8, u16m1, vbool16_t, 8, vmsne_vx_u16m1_b16) -OPENCV_HAL_IMPL_RISCVV_SELECT(v_uint32x4, u32m1, vbool32_t, 4, vmsne_vx_u32m1_b32) -inline v_float32x4 v_select(const v_float32x4& mask, const v_float32x4& a, const v_float32x4& b) -{ - return v_float32x4(vmerge_vvm_f32m1(vmfne_vf_f32m1_b32(mask.val, 0, 4), b.val, a.val, 4)); -} -inline v_float64x2 v_select(const v_float64x2& mask, const v_float64x2& a, const v_float64x2& b) -{ - return v_float64x2(vmerge_vvm_f64m1(vmfne_vf_f64m1_b64(mask.val, 0, 2), b.val, a.val, 2)); -} - -#define OPENCV_HAL_IMPL_RISCVV_EXPAND(add, _Tpvec, _Tpwvec, _Tp, _Tp1, num1, _Tp2, num2, _T1, _T2, num3) \ -inline void v_expand(const _Tpvec& a, v_##_Tpwvec& b0, v_##_Tpwvec& b1) \ -{ \ - _T1##_t b = vw##add##_vx_##_Tp2##m2(a.val, 0, num1); \ - b0.val = vget_v_##_Tp2##m2_##_Tp2##m1(b, 0); \ - b1.val = vget_v_##_Tp2##m2_##_Tp2##m1(b, 1); \ -} \ -inline v_##_Tpwvec v_expand_low(const _Tpvec& a) \ -{ \ - _T1##_t b = vw##add##_vx_##_Tp2##m2(a.val, 0, num2); \ - return v_##_Tpwvec(vget_v_##_Tp2##m2_##_Tp2##m1(b, 0)); \ -} \ -inline v_##_Tpwvec v_expand_high(const _Tpvec& a) \ -{ \ - _T1##_t b = vw##add##_vx_##_Tp2##m2(a.val, 0, num1); \ - return v_##_Tpwvec(vget_v_##_Tp2##m2_##_Tp2##m1(b, 1)); \ -} \ -inline v_##_Tpwvec v_load_expand(const _Tp* ptr) \ -{ \ - _T2##_t val = vle##num3##_v_##_Tp1(ptr, num2); \ - _T1##_t b = vw##add##_vx_##_Tp2##m2(val, 0, num2); \ - return v_##_Tpwvec(vget_v_##_Tp2##m2_##_Tp2##m1(b, 0)); \ -} - -OPENCV_HAL_IMPL_RISCVV_EXPAND(addu, v_uint8x16, uint16x8, uchar, u8m1, 16, u16, 8, vuint16m2, vuint8m1, 8) -OPENCV_HAL_IMPL_RISCVV_EXPAND(addu, v_uint16x8, uint32x4, ushort, u16m1, 8, u32, 4, vuint32m2, vuint16m1, 16) -OPENCV_HAL_IMPL_RISCVV_EXPAND(addu, v_uint32x4, uint64x2, uint, u32m1, 4, u64, 2, vuint64m2, vuint32m1, 32) -OPENCV_HAL_IMPL_RISCVV_EXPAND(add, v_int8x16, int16x8, schar, i8m1, 16, i16, 8, vint16m2, vint8m1, 8) -OPENCV_HAL_IMPL_RISCVV_EXPAND(add, v_int16x8, int32x4, short, i16m1, 8, i32, 4, vint32m2, vint16m1, 16) -OPENCV_HAL_IMPL_RISCVV_EXPAND(add, v_int32x4, int64x2, int, i32m1, 4, i64, 2, vint64m2, vint32m1, 32) - -inline v_uint32x4 v_load_expand_q(const uchar* ptr) -{ - vuint16m2_t b = vundefined_u16m2(); - vuint32m2_t c = vundefined_u32m2(); - vuint8m1_t val = vle8_v_u8m1(ptr, 4); \ - b = vwaddu_vv_u16m2(val, vmv_v_x_u8m1(0, 4), 4); \ - c = vwaddu_vv_u32m2(vget_v_u16m2_u16m1(b, 0), vmv_v_x_u16m1(0, 4), 4); \ - return v_uint32x4(vget_v_u32m2_u32m1(c, 0)); -} - -inline v_int32x4 v_load_expand_q(const schar* ptr) -{ - vint16m2_t b = vundefined_i16m2(); - vint32m2_t c = vundefined_i32m2(); - vint8m1_t val = vle8_v_i8m1(ptr, 4); \ - b = vwadd_vv_i16m2(val, vmv_v_x_i8m1(0, 4), 4); \ - c = vwadd_vv_i32m2(vget_v_i16m2_i16m1(b, 0), vmv_v_x_i16m1(0, 4), 4); \ - return v_int32x4(vget_v_i32m2_i32m1(c, 0)); -} -#define VITL_16 {0x11011000, 0x13031202, 0x15051404, 0x17071606, 0x19091808, 0x1B0B1A0A, 0x1D0D1C0C, 0x1F0F1E0E} -#define VITL_8 {0x00080000, 0x00090001, 0x000A0002, 0x000B0003, 0x000C0004, 0x000D0005, 0x000E0006, 0x000F0007} -#define VITL_4 {0x00000000, 0x00000004, 0x00000001, 0x00000005, 0x00000002, 0x00000006, 0x00000003, 0x00000007} -#define VITL_2 {0, 0, 2, 0, 1, 0, 3, 0} - -#define OPENCV_HAL_IMPL_RISCVV_UNPACKS(_Tpvec, _Tp, _T, _UTp, _UT, num, num2, len, numh, refunc) \ -inline void v_zip(const v_##_Tpvec& a0, const v_##_Tpvec& a1, v_##_Tpvec& b0, v_##_Tpvec& b1) \ -{ \ - v##_Tp##m2_t tmp = vundefined_##_T##m2();\ - tmp = vset_v_##_T##m1_##_T##m2(tmp, 0, a0.val); \ - tmp = vset_v_##_T##m1_##_T##m2(tmp, 1, a1.val); \ - unsigned mdata[] = VITL_##num; \ - vuint32m2_t mask = vle32_v_u32m2(mdata, 8); \ - tmp = (v##_Tp##m2_t)vrgather_vv_##_T##m2((v##_Tp##m2_t)tmp, refunc(mask), num2); \ - b0.val = vget_v_##_T##m2_##_T##m1(tmp, 0); \ - b1.val = vget_v_##_T##m2_##_T##m1(tmp, 1); \ -} \ -inline v_##_Tpvec v_combine_low(const v_##_Tpvec& a, const v_##_Tpvec& b) \ -{ \ - v##_Tp##m1_t b0 = vslideup_vx_##_T##m1_m(vmset_m_##len(num), a.val, b.val, numh, num); \ - return v_##_Tpvec(b0);\ -} \ -inline v_##_Tpvec v_combine_high(const v_##_Tpvec& a, const v_##_Tpvec& b) \ -{ \ - v##_Tp##m1_t b0 = vundefined_##_T##m1(); \ - v##_Tp##m1_t a0 = vundefined_##_T##m1(); \ - v##_Tp##m1_t b1 = vundefined_##_T##m1(); \ - b0 = vslidedown_vx_##_T##m1(b0, b.val, numh, num); \ - a0 = vslidedown_vx_##_T##m1(a0, a.val, numh, num); \ - b1 = vslideup_vx_##_T##m1_m(vmset_m_##len(num), a0, b0, numh, num); \ - return v_##_Tpvec(b1);\ -} \ -inline void v_recombine(const v_##_Tpvec& a, const v_##_Tpvec& b, v_##_Tpvec& c, v_##_Tpvec& d) \ -{ \ - v##_Tp##m1_t b0 = vundefined_##_T##m1(); \ - v##_Tp##m1_t a0 = vundefined_##_T##m1(); \ - c.val = vslideup_vx_##_T##m1_m(vmset_m_##len(num), a.val, b.val, numh, num); \ - b0 = vslidedown_vx_##_T##m1(b0, b.val, numh, num); \ - a0 = vslidedown_vx_##_T##m1(a0, a.val, numh, num); \ - d.val = vslideup_vx_##_T##m1_m(vmset_m_##len(num), a0, b0, numh, num); \ -} - -OPENCV_HAL_IMPL_RISCVV_UNPACKS(uint8x16, uint8, u8, uint8, u8, 16, 32, b8, 8, vreinterpret_v_u32m2_u8m2) -OPENCV_HAL_IMPL_RISCVV_UNPACKS(int8x16, int8, i8, uint8, u8, 16, 32, b8, 8, vreinterpret_v_u32m2_u8m2) -OPENCV_HAL_IMPL_RISCVV_UNPACKS(uint16x8, uint16, u16, uint16, u16, 8, 16, b16, 4, vreinterpret_v_u32m2_u16m2) -OPENCV_HAL_IMPL_RISCVV_UNPACKS(int16x8, int16, i16, uint16, u16, 8, 16, b16, 4, vreinterpret_v_u32m2_u16m2) -OPENCV_HAL_IMPL_RISCVV_UNPACKS(uint32x4, uint32, u32, uint32, u32, 4, 8, b32, 2,) -OPENCV_HAL_IMPL_RISCVV_UNPACKS(int32x4, int32, i32, uint32, u32, 4, 8, b32, 2,) -OPENCV_HAL_IMPL_RISCVV_UNPACKS(float32x4, float32, f32, uint32, u32, 4, 8, b32, 2,) -OPENCV_HAL_IMPL_RISCVV_UNPACKS(float64x2, float64, f64, uint64, u64, 2, 4, b64, 1, vreinterpret_v_u32m2_u64m2) - -inline v_uint8x16 v_reverse(const v_uint8x16 &a) -{ - return v_uint8x16(vrgather_vv_u8m1(a.val, vrsub_vx_u8m1(vid_v_u8m1(16), 15, 16), 16)); -} -inline v_int8x16 v_reverse(const v_int8x16 &a) -{ - return v_int8x16(vrgather_vv_i8m1(a.val, vrsub_vx_u8m1(vid_v_u8m1(16), 15, 16), 16)); -} - -inline v_uint16x8 v_reverse(const v_uint16x8 &a) -{ - return v_uint16x8(vrgather_vv_u16m1(a.val, vrsub_vx_u16m1(vid_v_u16m1(8), 7, 8), 8)); -} - -inline v_int16x8 v_reverse(const v_int16x8 &a) -{ - return v_int16x8(vrgather_vv_i16m1(a.val, vrsub_vx_u16m1(vid_v_u16m1(8), 7, 8), 8)); -} -inline v_uint32x4 v_reverse(const v_uint32x4 &a) -{ - return v_uint32x4(vrgather_vv_u32m1(a.val, vrsub_vx_u32m1(vid_v_u32m1(4), 3, 4), 4)); -} - -inline v_int32x4 v_reverse(const v_int32x4 &a) -{ - return v_int32x4(vrgather_vv_i32m1(a.val, vrsub_vx_u32m1(vid_v_u32m1(4), 3, 4), 4)); -} - -inline v_float32x4 v_reverse(const v_float32x4 &a) -{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_uint64x2 v_reverse(const v_uint64x2 &a) -{ - return v_uint64x2(vrgather_vv_u64m1(a.val, vrsub_vx_u64m1(vid_v_u64m1(2), 1, 2), 2)); -} - -inline v_int64x2 v_reverse(const v_int64x2 &a) -{ - return v_int64x2(vrgather_vv_i64m1(a.val, vrsub_vx_u64m1(vid_v_u64m1(2), 1, 2), 2)); -} - -inline v_float64x2 v_reverse(const v_float64x2 &a) -{ - return v_float64x2(vrgather_vv_f64m1(a.val, vrsub_vx_u64m1(vid_v_u64m1(2), 1, 2), 2)); -} - -#define OPENCV_HAL_IMPL_RISCVV_EXTRACT(_Tpvec, suffix, size) \ -template \ -inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \ -{ return v_rotate_right(a, b);} -OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_uint8x16, u8, 0) -OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_int8x16, s8, 0) -OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_uint16x8, u16, 1) -OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_int16x8, s16, 1) -OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_uint32x4, u32, 2) -OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_int32x4, s32, 2) -OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_uint64x2, u64, 3) -OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_int64x2, s64, 3) -OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_float32x4, f32, 2) -OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_float64x2, f64, 3) - - -#define OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(_Tpvec, _Tp, suffix, vtype, _vtype, num, mvfunc) \ -template inline _Tp v_extract_n(_Tpvec v) { vtype tmp = vundefined_##_vtype(); return mvfunc(vslidedown_vx_##_vtype(tmp, v.val, i, num)); } - -OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_uint8x16, uchar, u8, vuint8m1_t, u8m1, 16, vmv_x_s_u8m1_u8) -OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_int8x16, schar, s8, vint8m1_t, i8m1, 16, vmv_x_s_i8m1_i8) -OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_uint16x8, ushort, u16, vuint16m1_t, u16m1, 8, vmv_x_s_u16m1_u16) -OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_int16x8, short, s16, vint16m1_t, i16m1, 8, vmv_x_s_i16m1_i16) -OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_uint32x4, uint, u32, vuint32m1_t, u32m1, 4, vmv_x_s_u32m1_u32) -OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_int32x4, int, s32, vint32m1_t, i32m1, 4, vmv_x_s_i32m1_i32) -OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_uint64x2, uint64, u64, vuint64m1_t, u64m1, 2, vmv_x_s_u64m1_u64) -OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_int64x2, int64, s64, vint64m1_t, i64m1, 2, vmv_x_s_i64m1_i64) -OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_float32x4, float, f32, vfloat32m1_t, f32m1, 4, vfmv_f_s_f32m1_f32) -OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_float64x2, double, f64, vfloat64m1_t, f64m1, 2, vfmv_f_s_f64m1_f64) - -#define OPENCV_HAL_IMPL_RISCVV_BROADCAST(_Tpvec, _Tp, num) \ -template inline _Tpvec v_broadcast_element(_Tpvec v) { return _Tpvec(vrgather_vx_##_Tp##m1(v.val, i, num)); } - -OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_uint8x16, u8, 16) -OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_int8x16, i8, 16) -OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_uint16x8, u16, 8) -OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_int16x8, i16, 8) -OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_uint32x4, u32, 4) -OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_int32x4, i32, 4) -OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_uint64x2, u64, 2) -OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_int64x2, i64, 2) -OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_float32x4, f32, 4) - -inline void __builtin_riscv_fsrm(int val) -{ - asm("csrw frm, %0\n\t" - : - :"r"(val)); - return; -} - -inline void barrier1(void *arg) { - __asm__ __volatile__("" : : "r" (arg) : "memory"); -} - -inline v_int32x4 v_round(const v_float32x4& a) -{ - __builtin_riscv_fsrm(0); - vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(a.val), 0x7f800000, 4); - barrier1(&nan); - vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); - vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), a.val, 4); - __builtin_riscv_fsrm(0); - return v_int32x4(val); -} -inline v_int32x4 v_floor(const v_float32x4& a) -{ - __builtin_riscv_fsrm(2); - vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(a.val), 0x7f800000, 4); - barrier1(&nan); - vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); - vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), a.val, 4); - __builtin_riscv_fsrm(0); - return v_int32x4(val); -} - -inline v_int32x4 v_ceil(const v_float32x4& a) -{ - __builtin_riscv_fsrm(3); - vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(a.val), 0x7f800000, 4); - barrier1(&nan); - vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); - vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), a.val, 4); - __builtin_riscv_fsrm(0); - return v_int32x4(val); -} - -inline v_int32x4 v_trunc(const v_float32x4& a) -{ - __builtin_riscv_fsrm(1); - vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(a.val), 0x7f800000, 4); - barrier1(&nan); - vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); - vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), a.val, 4); - __builtin_riscv_fsrm(0); - return v_int32x4(val); -} - -inline v_int32x4 v_round(const v_float64x2& a) -{ - __builtin_riscv_fsrm(0); - vfloat64m2_t _val = vundefined_f64m2(); - _val = vset_v_f64m1_f64m2(_val, 0, a.val); - //_val = vset_f64m2(_val, 1, a.val); - _val = vset_v_f64m1_f64m2(_val, 1, vfmv_v_f_f64m1(0, 2)); - barrier1(&_val); - vint32m1_t val = vfncvt_x_f_w_i32m1(_val, 4); - __builtin_riscv_fsrm(0); - return v_int32x4(val); -} -inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) -{ - __builtin_riscv_fsrm(0); - vfloat64m2_t _val = vundefined_f64m2(); - _val = vset_v_f64m1_f64m2(_val, 0, a.val); - _val = vset_v_f64m1_f64m2(_val, 1, b.val); - barrier1(&_val); - vint32m1_t val = vfncvt_x_f_w_i32m1(_val, 4); - __builtin_riscv_fsrm(0); - return v_int32x4(val); -} -inline v_int32x4 v_floor(const v_float64x2& a) -{ - __builtin_riscv_fsrm(2); - vfloat64m2_t _val = vundefined_f64m2(); - _val = vset_v_f64m1_f64m2(_val, 0, a.val); - vfloat32m1_t aval = vfncvt_f_f_w_f32m1(_val, 2); - vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(aval), 0x7f800000, 4); - barrier1(&nan); - vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); - vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), aval, 4); - __builtin_riscv_fsrm(0); - return v_int32x4(val); -} - -inline v_int32x4 v_ceil(const v_float64x2& a) -{ - __builtin_riscv_fsrm(3); - vfloat64m2_t _val = vundefined_f64m2(); - _val = vset_v_f64m1_f64m2(_val, 0, a.val); - vfloat32m1_t aval = vfncvt_f_f_w_f32m1(_val, 2); - vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(aval), 0x7f800000, 4); - barrier1(&nan); - vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); - vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), aval, 4); - __builtin_riscv_fsrm(0); - return v_int32x4(val); -} - -inline v_int32x4 v_trunc(const v_float64x2& a) -{ - __builtin_riscv_fsrm(1); - vfloat64m2_t _val = vundefined_f64m2(); - _val = vset_v_f64m1_f64m2(_val, 0, a.val); - vfloat32m1_t aval = vfncvt_f_f_w_f32m1(_val, 2); - vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(aval), 0x7f800000, 4); - barrier1(&nan); - vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); - vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), aval, 4); - __builtin_riscv_fsrm(0); - return v_int32x4(val); -} - -#define OPENCV_HAL_IMPL_RISCVV_LOAD_DEINTERLEAVED(intrin, _Tpvec, num, _Tp, _T, elemsize) \ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec##x##num& a, v_##_Tpvec##x##num& b) \ -{ \ - intrin##2e##elemsize##_v_##_T##m1(&a.val, &b.val, ptr, num); \ -} \ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec##x##num& a, v_##_Tpvec##x##num& b, v_##_Tpvec##x##num& c) \ -{ \ - intrin##3e##elemsize##_v_##_T##m1(&a.val, &b.val, &c.val, ptr, num); \ -}\ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec##x##num& a, v_##_Tpvec##x##num& b, \ - v_##_Tpvec##x##num& c, v_##_Tpvec##x##num& d) \ -{ \ - intrin##4e##elemsize##_v_##_T##m1(&a.val, &b.val, &c.val, &d.val, ptr, num); \ -} \ - -#define OPENCV_HAL_IMPL_RISCVV_STORE_INTERLEAVED(intrin, _Tpvec, num, _Tp, _T, elemsize) \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec##x##num& a, const v_##_Tpvec##x##num& b, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - intrin##2e##elemsize##_v_##_T##m1(ptr, a.val, b.val, num); \ -} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec##x##num& a, const v_##_Tpvec##x##num& b, \ - const v_##_Tpvec##x##num& c, hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - intrin##3e##elemsize##_v_##_T##m1(ptr, a.val, b.val, c.val, num); \ -} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec##x##num& a, const v_##_Tpvec##x##num& b, \ - const v_##_Tpvec##x##num& c, const v_##_Tpvec##x##num& d, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ -{ \ - intrin##4e##elemsize##_v_##_T##m1(ptr, a.val, b.val, c.val, d.val, num); \ -} - -#define OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(_Tpvec, _Tp, num, ld, st, _T, elemsize) \ -OPENCV_HAL_IMPL_RISCVV_LOAD_DEINTERLEAVED(ld, _Tpvec, num, _Tp, _T, elemsize) \ -OPENCV_HAL_IMPL_RISCVV_STORE_INTERLEAVED(st, _Tpvec, num, _Tp, _T, elemsize) - -//OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(uint8, uchar, ) -OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(int8, schar, 16, vlseg, vsseg, i8, 8) -OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(int16, short, 8, vlseg, vsseg, i16, 16) -OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(int32, int, 4, vlseg, vsseg, i32, 32) - -OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(uint8, unsigned char, 16, vlseg, vsseg, u8, 8) -OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(uint16, unsigned short, 8, vlseg, vsseg, u16, 16) -OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(uint32, unsigned int, 4, vlseg, vsseg, u32, 32) - -#define OPENCV_HAL_IMPL_RISCVV_INTERLEAVED_(_Tpvec, _Tp, num, _T, _esize) \ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec##x##num& a, v_##_Tpvec##x##num& b) \ -{ vlseg2e##_esize##_v_##_T##m1(&a.val, &b.val, ptr, num);} \ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec##x##num& a, v_##_Tpvec##x##num& b, v_##_Tpvec##x##num& c) \ -{ vlseg3e##_esize##_v_##_T##m1(&a.val, &b.val, &c.val, ptr, num);}\ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec##x##num& a, v_##_Tpvec##x##num& b, \ - v_##_Tpvec##x##num& c, v_##_Tpvec##x##num& d) \ -{ vlseg4e##_esize##_v_##_T##m1(&a.val, &b.val, &c.val, &d.val, ptr, num);} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec##x##num& a, const v_##_Tpvec##x##num& b, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ vsseg2e##_esize##_v_##_T##m1(ptr, a.val, b.val, num);} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec##x##num& a, const v_##_Tpvec##x##num& b, \ - const v_##_Tpvec##x##num& c, hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ vsseg3e##_esize##_v_##_T##m1(ptr, a.val, b.val, c.val, num);} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec##x##num& a, const v_##_Tpvec##x##num& b, \ - const v_##_Tpvec##x##num& c, const v_##_Tpvec##x##num& d, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ -{ vsseg4e##_esize##_v_##_T##m1(ptr, a.val, b.val, c.val, d.val, num);} - -OPENCV_HAL_IMPL_RISCVV_INTERLEAVED_(float32, float, 4, f32, 32) -OPENCV_HAL_IMPL_RISCVV_INTERLEAVED_(float64, double, 2, f64, 64) - -OPENCV_HAL_IMPL_RISCVV_INTERLEAVED_(uint64, unsigned long, 2, u64, 64) -OPENCV_HAL_IMPL_RISCVV_INTERLEAVED_(int64, long, 2, i64, 64) - -inline v_float32x4 v_cvt_f32(const v_int32x4& a) -{ - return v_float32x4(vfcvt_f_x_v_f32m1(a.val, 4)); -} - -#if CV_SIMD128_64F -inline v_float32x4 v_cvt_f32(const v_float64x2& a) -{ - vfloat64m2_t _val = vundefined_f64m2(); - _val = vset_v_f64m1_f64m2(_val, 0, a.val); - vfloat32m1_t aval = vfncvt_f_f_w_f32m1(_val, 2); - return v_float32x4(aval); -} - -inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) -{ - vfloat64m2_t _val = vundefined_f64m2(); - _val = vset_v_f64m1_f64m2(_val, 0, a.val); - _val = vset_v_f64m1_f64m2(_val, 1, b.val); - vfloat32m1_t aval = vfncvt_f_f_w_f32m1(_val, 4); - return v_float32x4(aval); -} - -inline v_float64x2 v_cvt_f64(const v_int32x4& a) -{ - vfloat32m1_t val = vfcvt_f_x_v_f32m1(a.val, 4); - vfloat64m2_t _val = vfwcvt_f_f_v_f64m2(val, 4); - return v_float64x2(vget_v_f64m2_f64m1(_val, 0)); -} - -inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) -{ - vfloat32m1_t val = vfcvt_f_x_v_f32m1(a.val, 4); - vfloat64m2_t _val = vfwcvt_f_f_v_f64m2(val, 4); - return v_float64x2(vget_v_f64m2_f64m1(_val, 1)); -} - -inline v_float64x2 v_cvt_f64(const v_float32x4& a) -{ - vfloat64m2_t _val = vfwcvt_f_f_v_f64m2(a.val, 4); - return v_float64x2(vget_v_f64m2_f64m1(_val, 0)); -} - -inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) -{ - vfloat64m2_t _val = vfwcvt_f_f_v_f64m2(a.val, 4); - return v_float64x2(vget_v_f64m2_f64m1(_val, 1)); -} - -inline v_float64x2 v_cvt_f64(const v_int64x2& a) -{ - return v_float64x2(vfcvt_f_x_v_f64m1(a.val, 2)); -} - -#endif -inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) -{ - uint64 mdata[2] = {0x0705060403010200, 0x0F0D0E0C0B090A08}; - vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); - return v_int8x16(vrgather_vv_i8m1(vec.val, vreinterpret_v_u64m1_u8m1(m0), 16)); -} -inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) -{ - return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); -} - -inline v_int8x16 v_interleave_quads(const v_int8x16& vec) -{ - uint64 mdata[2] = {0x0703060205010400, 0x0F0B0E0A0D090C08}; - vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); - return v_int8x16(vrgather_vv_i8m1(vec.val, vreinterpret_v_u64m1_u8m1(m0), 16)); -} -inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) -{ - return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); -} - -inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) -{ - uint64 mdata[2] = {0x0706030205040100, 0x0F0E0B0A0D0C0908}; - vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); - return v_int16x8(vreinterpret_v_i8m1_i16m1(vreinterpret_v_u8m1_i8m1(vrgather_vv_u8m1(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i16m1_i8m1(vec.val)), vreinterpret_v_u64m1_u8m1(m0), 16)))); -} -inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } -inline v_int16x8 v_interleave_quads(const v_int16x8& vec) -{ - uint64 mdata[2] = {0x0B0A030209080100, 0x0F0E07060D0C0504}; - vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); - return v_int16x8(vreinterpret_v_i8m1_i16m1(vreinterpret_v_u8m1_i8m1(vrgather_vv_u8m1(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i16m1_i8m1(vec.val)), vreinterpret_v_u64m1_u8m1(m0), 16)))); -} -inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) -{ - uint64 mdata[2] = {0x0B0A090803020100, 0x0F0E0D0C07060504}; - vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); - return v_int32x4(vreinterpret_v_i8m1_i32m1(vreinterpret_v_u8m1_i8m1(vrgather_vv_u8m1(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i32m1_i8m1(vec.val)), vreinterpret_v_u64m1_u8m1(m0), 16)))); -} -inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } -inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } -inline v_int8x16 v_pack_triplets(const v_int8x16& vec) -{ - uint64 mdata[2] = {0x0908060504020100, 0xFFFFFFFF0E0D0C0A}; - vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); - return v_int8x16(vreinterpret_v_u8m1_i8m1(vrgather_vv_u8m1(vreinterpret_v_i8m1_u8m1(vec.val), vreinterpret_v_u64m1_u8m1(m0), 16))); -} -inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_pack_triplets(const v_int16x8& vec) -{ - uint64 mdata[2] = {0x0908050403020100, 0xFFFFFFFF0D0C0B0A}; - vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); - return v_int16x8(vreinterpret_v_i8m1_i16m1(vreinterpret_v_u8m1_i8m1(vrgather_vv_u8m1(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i16m1_i8m1(vec.val)), vreinterpret_v_u64m1_u8m1(m0), 16)))); -} -inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } -inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } -inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } - -#if CV_SIMD128_64F -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) -{ return v_cvt_f64(v_dotprod(a, b)); } -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, - const v_float64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) -{ - vint64m2_t v1 = vwmul_vv_i64m2(a.val, b.val, 4); - vfloat64m1_t res = vfcvt_f_x_v_f64m1(vadd_vv_i64m1(vget_v_i64m2_i64m1(v1, 0), vget_v_i64m2_i64m1(v1, 1), 2), 2); - return v_float64x2(res); -} -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) -{ v_float64x2 res = v_dotprod_expand_fast(a, b); - return v_add(res, c); } -#endif -////// FP16 support /////// -#if __riscv_v == 7000 -inline v_float32x4 v_load_expand(const hfloat* ptr) -{ - vfloat16m1_t v = vle16_v_f16m1((__fp16*)ptr, 4); - vfloat32m2_t v32 = vfwcvt_f_f_v_f32m2(v, 4); - return v_float32x4(vget_v_f32m2_f32m1(v32, 0)); -} - -inline void v_pack_store(hfloat* ptr, const v_float32x4& v) -{ - vfloat32m2_t v32 = vundefined_f32m2(); - v32 = vset_v_f32m1_f32m2(v32, 0, v.val); - vfloat16m1_t hv = vfncvt_f_f_w_f16m1(v32, 4); - vse16_v_f16m1((__fp16*)ptr, hv, 4); -} -#else -inline v_float32x4 v_load_expand(const hfloat* ptr) -{ - vfloat16mf2_t v = vle16_v_f16mf2((__fp16*)ptr, 4); - vfloat32m1_t v32 = vfwcvt_f_f_v_f32m1(v, 4); - return v_float32x4(v32); -} - -inline void v_pack_store(hfloat* ptr, const v_float32x4& v) -{ - //vfloat32m2_t v32 = vundefined_f32m2(); - //v32 = vset_f32m2(v32, 0, v.val); - vfloat16mf2_t hv = vfncvt_f_f_w_f16mf2(v.val, 4); - vse16_v_f16mf2((__fp16*)ptr, hv, 4); -} -#endif - -inline void v_cleanup() {} - -#include "intrin_math.hpp" -inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } -inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } -inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } -inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } -inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } -inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } - -inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } -inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } -inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } -inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } -inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +// Copyright (C) 2015, PingTouGe Semiconductor Co., Ltd., all rights reserved. + +#ifndef OPENCV_HAL_INTRIN_RISCVV_HPP +#define OPENCV_HAL_INTRIN_RISCVV_HPP + +#include +#include +#include "opencv2/core/utility.hpp" + +namespace cv +{ + +//! @cond IGNORED + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +#define CV_SIMD128 1 +#define CV_SIMD128_64F 1 +//////////// Types //////////// +struct v_uint8x16 +{ + typedef uchar lane_type; + enum { nlanes = 16 }; + + v_uint8x16() {} + explicit v_uint8x16(vuint8m1_t v) : val(v) {} + v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, + uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) + { + uchar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; + val = (vuint8m1_t)vle8_v_u8m1((unsigned char*)v, 16); + } + uchar get0() const + { + return vmv_x_s_u8m1_u8(val); + } + + vuint8m1_t val; +}; + +struct v_int8x16 +{ + typedef schar lane_type; + enum { nlanes = 16 }; + + v_int8x16() {} + explicit v_int8x16(vint8m1_t v) : val(v) {} + v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, + schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) + { + schar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; + val = (vint8m1_t)vle8_v_i8m1((schar*)v, 16); + } + schar get0() const + { + return vmv_x_s_i8m1_i8(val); + } + + vint8m1_t val; +}; + +struct v_uint16x8 +{ + typedef ushort lane_type; + enum { nlanes = 8 }; + + v_uint16x8() {} + explicit v_uint16x8(vuint16m1_t v) : val(v) {} + v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) + { + ushort v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; + val = (vuint16m1_t)vle16_v_u16m1((unsigned short*)v, 8); + } + ushort get0() const + { + return vmv_x_s_u16m1_u16(val); + } + + vuint16m1_t val; +}; + +struct v_int16x8 +{ + typedef short lane_type; + enum { nlanes = 8 }; + + v_int16x8() {} + explicit v_int16x8(vint16m1_t v) : val(v) {} + v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) + { + short v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; + val = (vint16m1_t)vle16_v_i16m1((signed short*)v, 8); + } + short get0() const + { + return vmv_x_s_i16m1_i16(val); + } + + vint16m1_t val; +}; + +struct v_uint32x4 +{ + typedef unsigned lane_type; + enum { nlanes = 4 }; + + v_uint32x4() {} + explicit v_uint32x4(vuint32m1_t v) : val(v) {} + v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) + { + unsigned v[] = {v0, v1, v2, v3}; + val = (vuint32m1_t)vle32_v_u32m1((unsigned int*)v, 4); + } + unsigned get0() const + { + return vmv_x_s_u32m1_u32(val); + } + + vuint32m1_t val; +}; + +struct v_int32x4 +{ + typedef int lane_type; + enum { nlanes = 4 }; + + v_int32x4() {} + explicit v_int32x4(vint32m1_t v) : val(v) {} + v_int32x4(int v0, int v1, int v2, int v3) + { + int v[] = {v0, v1, v2, v3}; + val = (vint32m1_t)vle32_v_i32m1((signed int*)v, 4); + } + int get0() const + { + return vmv_x_s_i32m1_i32(val); + } + vint32m1_t val; +}; + +struct v_float32x4 +{ + typedef float lane_type; + enum { nlanes = 4 }; + + v_float32x4() {} + explicit v_float32x4(vfloat32m1_t v) : val(v) {} + v_float32x4(float v0, float v1, float v2, float v3) + { + float v[] = {v0, v1, v2, v3}; + val = (vfloat32m1_t)vle32_v_f32m1((float*)v, 4); + } + float get0() const + { + return vfmv_f_s_f32m1_f32(val); + } + vfloat32m1_t val; +}; + +struct v_uint64x2 +{ + typedef uint64 lane_type; + enum { nlanes = 2 }; + + v_uint64x2() {} + explicit v_uint64x2(vuint64m1_t v) : val(v) {} + v_uint64x2(uint64 v0, uint64 v1) + { + uint64 v[] = {v0, v1}; + val = (vuint64m1_t)vle64_v_u64m1((unsigned long*)v, 2); + } + uint64 get0() const + { + return vmv_x_s_u64m1_u64(val); + } + vuint64m1_t val; +}; + +struct v_int64x2 +{ + typedef int64 lane_type; + enum { nlanes = 2 }; + + v_int64x2() {} + explicit v_int64x2(vint64m1_t v) : val(v) {} + v_int64x2(int64 v0, int64 v1) + { + int64 v[] = {v0, v1}; + val = (vint64m1_t)vle64_v_i64m1((long*)v, 2); + } + int64 get0() const + { + return vmv_x_s_i64m1_i64(val); + } + vint64m1_t val; +}; + +struct v_float64x2 +{ + typedef double lane_type; + enum { nlanes = 2 }; + + v_float64x2() {} + explicit v_float64x2(vfloat64m1_t v) : val(v) {} + v_float64x2(double v0, double v1) + { + double v[] = {v0, v1}; + val = (vfloat64m1_t)vle64_v_f64m1((double*)v, 2); + } + double get0() const + { + return vfmv_f_s_f64m1_f64(val); + } + vfloat64m1_t val; +}; +/* +#define OPENCV_HAL_IMPL_RISCVV_INIT(_Tpv, _Tp, suffix) \ +inline _Tp##m1_t vreinterpret_v_##suffix##m1_##suffix##m1(_Tp##m1_t v) { return v; } \ +inline v_uint8x16 v_reinterpret_as_u8(const v_##_Tpv& v) { return v_uint8x16((vuint8m1_t)(v.val)); } \ +inline v_int8x16 v_reinterpret_as_s8(const v_##_Tpv& v) { return v_int8x16((vint8m1_t)(v.val)); } \ +inline v_uint16x8 v_reinterpret_as_u16(const v_##_Tpv& v) { return v_uint16x8((vuint16m1_t)(v.val)); } \ +inline v_int16x8 v_reinterpret_as_s16(const v_##_Tpv& v) { return v_int16x8(vreinterpret_v_i8m1_i16m1(v.val)); } \ +inline v_uint32x4 v_reinterpret_as_u32(const v_##_Tpv& v) { return v_uint32x4((vuint32m1_t)(v.val)); } \ +inline v_int32x4 v_reinterpret_as_s32(const v_##_Tpv& v) { return v_int32x4((vint32m1_t)(v.val)); } \ +inline v_uint64x2 v_reinterpret_as_u64(const v_##_Tpv& v) { return v_uint64x2((vuint64m1_t)(v.val)); } \ +inline v_int64x2 v_reinterpret_as_s64(const v_##_Tpv& v) { return v_int64x2((vint64m1_t)(v.val)); } \ +inline v_float32x4 v_reinterpret_as_f32(const v_##_Tpv& v) { return v_float32x4((vfloat32m1_t)(v.val)); }\ +inline v_float64x2 v_reinterpret_as_f64(const v_##_Tpv& v) { return v_float64x2((vfloat64m1_t)(v.val)); } + + +OPENCV_HAL_IMPL_RISCVV_INIT(uint8x16, vuint8, u8) +OPENCV_HAL_IMPL_RISCVV_INIT(int8x16, vint8, i8) +OPENCV_HAL_IMPL_RISCVV_INIT(uint16x8, vuint16, u16) +OPENCV_HAL_IMPL_RISCVV_INIT(int16x8, vint16, i16) +OPENCV_HAL_IMPL_RISCVV_INIT(uint32x4, vuint32, u32) +OPENCV_HAL_IMPL_RISCVV_INIT(int32x4, vint32, i32) +OPENCV_HAL_IMPL_RISCVV_INIT(uint64x2, vuint64, u64) +OPENCV_HAL_IMPL_RISCVV_INIT(int64x2, vint64, i64) +OPENCV_HAL_IMPL_RISCVV_INIT(float64x2, vfloat64, f64) +OPENCV_HAL_IMPL_RISCVV_INIT(float32x4, vfloat32, f32) +*/ +inline v_uint8x16 v_reinterpret_as_u8(const v_uint8x16& v) { return v_uint8x16(v.val); } +inline v_int8x16 v_reinterpret_as_s8(const v_uint8x16& v) { return v_int8x16(vreinterpret_v_u8m1_i8m1(v.val)); } +inline v_uint16x8 v_reinterpret_as_u16(const v_uint8x16& v) { return v_uint16x8(vreinterpret_v_u8m1_u16m1(v.val)); } +inline v_int16x8 v_reinterpret_as_s16(const v_uint8x16& v) { return v_int16x8(vreinterpret_v_u16m1_i16m1(vreinterpret_v_u8m1_u16m1(v.val))); } +inline v_uint32x4 v_reinterpret_as_u32(const v_uint8x16& v) { return v_uint32x4(vreinterpret_v_u8m1_u32m1(v.val)); } +inline v_int32x4 v_reinterpret_as_s32(const v_uint8x16& v) { return v_int32x4(vreinterpret_v_u32m1_i32m1(vreinterpret_v_u8m1_u32m1(v.val))); } +inline v_uint64x2 v_reinterpret_as_u64(const v_uint8x16& v) { return v_uint64x2(vreinterpret_v_u8m1_u64m1(v.val)); } +inline v_int64x2 v_reinterpret_as_s64(const v_uint8x16& v) { return v_int64x2(vreinterpret_v_u64m1_i64m1(vreinterpret_v_u8m1_u64m1(v.val))); } +inline v_float32x4 v_reinterpret_as_f32(const v_uint8x16& v) { return v_float32x4(vreinterpret_v_u32m1_f32m1(vreinterpret_v_u8m1_u32m1(v.val))); } +inline v_float64x2 v_reinterpret_as_f64(const v_uint8x16& v) { return v_float64x2(vreinterpret_v_u64m1_f64m1(vreinterpret_v_u8m1_u64m1(v.val))); } + +inline v_uint8x16 v_reinterpret_as_u8(const v_int8x16& v) { return v_uint8x16(vreinterpret_v_i8m1_u8m1(v.val)); } +inline v_int8x16 v_reinterpret_as_s8(const v_int8x16& v) { return v_int8x16(v.val); } +inline v_uint16x8 v_reinterpret_as_u16(const v_int8x16& v) { return v_uint16x8(vreinterpret_v_u8m1_u16m1(vreinterpret_v_i8m1_u8m1(v.val))); } +inline v_int16x8 v_reinterpret_as_s16(const v_int8x16& v) { return v_int16x8(vreinterpret_v_i8m1_i16m1(v.val)); } +inline v_uint32x4 v_reinterpret_as_u32(const v_int8x16& v) { return v_uint32x4(vreinterpret_v_u8m1_u32m1(vreinterpret_v_i8m1_u8m1(v.val))); } +inline v_int32x4 v_reinterpret_as_s32(const v_int8x16& v) { return v_int32x4(vreinterpret_v_i8m1_i32m1(v.val)); } +inline v_uint64x2 v_reinterpret_as_u64(const v_int8x16& v) { return v_uint64x2(vreinterpret_v_u8m1_u64m1(vreinterpret_v_i8m1_u8m1(v.val))); } +inline v_int64x2 v_reinterpret_as_s64(const v_int8x16& v) { return v_int64x2(vreinterpret_v_i8m1_i64m1(v.val)); } +inline v_float32x4 v_reinterpret_as_f32(const v_int8x16& v) { return v_float32x4(vreinterpret_v_i32m1_f32m1(vreinterpret_v_i8m1_i32m1(v.val))); } +inline v_float64x2 v_reinterpret_as_f64(const v_int8x16& v) { return v_float64x2(vreinterpret_v_i64m1_f64m1(vreinterpret_v_i8m1_i64m1(v.val))); } + +inline v_uint8x16 v_reinterpret_as_u8(const v_uint16x8& v) { return v_uint8x16(vreinterpret_v_u16m1_u8m1(v.val)); } +inline v_int8x16 v_reinterpret_as_s8(const v_uint16x8& v) { return v_int8x16(vreinterpret_v_i16m1_i8m1(vreinterpret_v_u16m1_i16m1(v.val))); } +inline v_uint16x8 v_reinterpret_as_u16(const v_uint16x8& v) { return v_uint16x8(v.val); } +inline v_int16x8 v_reinterpret_as_s16(const v_uint16x8& v) { return v_int16x8(vreinterpret_v_u16m1_i16m1(v.val)); } +inline v_uint32x4 v_reinterpret_as_u32(const v_uint16x8& v) { return v_uint32x4(vreinterpret_v_u16m1_u32m1(v.val)); } +inline v_int32x4 v_reinterpret_as_s32(const v_uint16x8& v) { return v_int32x4(vreinterpret_v_u32m1_i32m1(vreinterpret_v_u16m1_u32m1(v.val))); } +inline v_uint64x2 v_reinterpret_as_u64(const v_uint16x8& v) { return v_uint64x2(vreinterpret_v_u16m1_u64m1(v.val)); } +inline v_int64x2 v_reinterpret_as_s64(const v_uint16x8& v) { return v_int64x2(vreinterpret_v_u64m1_i64m1(vreinterpret_v_u16m1_u64m1(v.val))); } +inline v_float32x4 v_reinterpret_as_f32(const v_uint16x8& v) { return v_float32x4(vreinterpret_v_u32m1_f32m1(vreinterpret_v_u16m1_u32m1(v.val))); } +inline v_float64x2 v_reinterpret_as_f64(const v_uint16x8& v) { return v_float64x2(vreinterpret_v_u64m1_f64m1(vreinterpret_v_u16m1_u64m1(v.val))); } + +inline v_uint8x16 v_reinterpret_as_u8(const v_int16x8& v) { return v_uint8x16(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i16m1_i8m1(v.val))); } +inline v_int8x16 v_reinterpret_as_s8(const v_int16x8& v) { return v_int8x16(vreinterpret_v_i16m1_i8m1(v.val)); } +inline v_uint16x8 v_reinterpret_as_u16(const v_int16x8& v) { return v_uint16x8(vreinterpret_v_i16m1_u16m1(v.val)); } +inline v_int16x8 v_reinterpret_as_s16(const v_int16x8& v) { return v_int16x8(v.val); } +inline v_uint32x4 v_reinterpret_as_u32(const v_int16x8& v) { return v_uint32x4(vreinterpret_v_u16m1_u32m1(vreinterpret_v_i16m1_u16m1(v.val))); } +inline v_int32x4 v_reinterpret_as_s32(const v_int16x8& v) { return v_int32x4(vreinterpret_v_i16m1_i32m1(v.val)); } +inline v_uint64x2 v_reinterpret_as_u64(const v_int16x8& v) { return v_uint64x2(vreinterpret_v_u16m1_u64m1(vreinterpret_v_i16m1_u16m1(v.val))); } +inline v_int64x2 v_reinterpret_as_s64(const v_int16x8& v) { return v_int64x2(vreinterpret_v_i16m1_i64m1(v.val)); } +inline v_float32x4 v_reinterpret_as_f32(const v_int16x8& v) { return v_float32x4(vreinterpret_v_i32m1_f32m1(vreinterpret_v_i16m1_i32m1(v.val))); } +inline v_float64x2 v_reinterpret_as_f64(const v_int16x8& v) { return v_float64x2(vreinterpret_v_i64m1_f64m1(vreinterpret_v_i16m1_i64m1(v.val))); } + +inline v_uint8x16 v_reinterpret_as_u8(const v_uint32x4& v) { return v_uint8x16(vreinterpret_v_u32m1_u8m1(v.val)); } +inline v_int8x16 v_reinterpret_as_s8(const v_uint32x4& v) { return v_int8x16(vreinterpret_v_i32m1_i8m1(vreinterpret_v_u32m1_i32m1(v.val))); } +inline v_uint16x8 v_reinterpret_as_u16(const v_uint32x4& v) { return v_uint16x8(vreinterpret_v_u32m1_u16m1(v.val)); } +inline v_int16x8 v_reinterpret_as_s16(const v_uint32x4& v) { return v_int16x8(vreinterpret_v_i32m1_i16m1(vreinterpret_v_u32m1_i32m1(v.val))); } +inline v_uint32x4 v_reinterpret_as_u32(const v_uint32x4& v) { return v_uint32x4(v.val); } +inline v_int32x4 v_reinterpret_as_s32(const v_uint32x4& v) { return v_int32x4(vreinterpret_v_u32m1_i32m1(v.val)); } +inline v_uint64x2 v_reinterpret_as_u64(const v_uint32x4& v) { return v_uint64x2(vreinterpret_v_u32m1_u64m1(v.val)); } +inline v_int64x2 v_reinterpret_as_s64(const v_uint32x4& v) { return v_int64x2(vreinterpret_v_u64m1_i64m1(vreinterpret_v_u32m1_u64m1(v.val))); } +inline v_float32x4 v_reinterpret_as_f32(const v_uint32x4& v) { return v_float32x4(vreinterpret_v_u32m1_f32m1(v.val)); } +inline v_float64x2 v_reinterpret_as_f64(const v_uint32x4& v) { return v_float64x2(vreinterpret_v_u64m1_f64m1(vreinterpret_v_u32m1_u64m1(v.val))); } + +inline v_uint8x16 v_reinterpret_as_u8(const v_int32x4& v) { return v_uint8x16(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i32m1_i8m1(v.val))); } +inline v_int8x16 v_reinterpret_as_s8(const v_int32x4& v) { return v_int8x16(vreinterpret_v_i32m1_i8m1(v.val)); } +inline v_uint16x8 v_reinterpret_as_u16(const v_int32x4& v) { return v_uint16x8(vreinterpret_v_u32m1_u16m1(vreinterpret_v_i32m1_u32m1(v.val))); } +inline v_int16x8 v_reinterpret_as_s16(const v_int32x4& v) { return v_int16x8(vreinterpret_v_i32m1_i16m1(v.val)); } +inline v_uint32x4 v_reinterpret_as_u32(const v_int32x4& v) { return v_uint32x4(vreinterpret_v_i32m1_u32m1(v.val)); } +inline v_int32x4 v_reinterpret_as_s32(const v_int32x4& v) { return v_int32x4(v.val); } +inline v_uint64x2 v_reinterpret_as_u64(const v_int32x4& v) { return v_uint64x2(vreinterpret_v_u32m1_u64m1(vreinterpret_v_i32m1_u32m1(v.val))); } +inline v_int64x2 v_reinterpret_as_s64(const v_int32x4& v) { return v_int64x2(vreinterpret_v_i32m1_i64m1(v.val)); } +inline v_float32x4 v_reinterpret_as_f32(const v_int32x4& v) { return v_float32x4(vreinterpret_v_i32m1_f32m1(v.val)); } +inline v_float64x2 v_reinterpret_as_f64(const v_int32x4& v) { return v_float64x2(vreinterpret_v_i64m1_f64m1(vreinterpret_v_i32m1_i64m1(v.val))); } + +inline v_uint8x16 v_reinterpret_as_u8(const v_uint64x2& v) { return v_uint8x16(vreinterpret_v_u64m1_u8m1(v.val)); } +inline v_int8x16 v_reinterpret_as_s8(const v_uint64x2& v) { return v_int8x16(vreinterpret_v_i64m1_i8m1(vreinterpret_v_u64m1_i64m1(v.val))); } +inline v_uint16x8 v_reinterpret_as_u16(const v_uint64x2& v) { return v_uint16x8(vreinterpret_v_u64m1_u16m1(v.val)); } +inline v_int16x8 v_reinterpret_as_s16(const v_uint64x2& v) { return v_int16x8(vreinterpret_v_i64m1_i16m1(vreinterpret_v_u64m1_i64m1(v.val))); } +inline v_uint32x4 v_reinterpret_as_u32(const v_uint64x2& v) { return v_uint32x4(vreinterpret_v_u64m1_u32m1(v.val)); } +inline v_int32x4 v_reinterpret_as_s32(const v_uint64x2& v) { return v_int32x4(vreinterpret_v_i64m1_i32m1(vreinterpret_v_u64m1_i64m1(v.val))); } +inline v_uint64x2 v_reinterpret_as_u64(const v_uint64x2& v) { return v_uint64x2(v.val); } +inline v_int64x2 v_reinterpret_as_s64(const v_uint64x2& v) { return v_int64x2(vreinterpret_v_u64m1_i64m1(v.val)); } +inline v_float32x4 v_reinterpret_as_f32(const v_uint64x2& v) { return v_float32x4(vreinterpret_v_u32m1_f32m1(vreinterpret_v_u64m1_u32m1(v.val))); } +inline v_float64x2 v_reinterpret_as_f64(const v_uint64x2& v) { return v_float64x2(vreinterpret_v_u64m1_f64m1(v.val)); } + +inline v_uint8x16 v_reinterpret_as_u8(const v_int64x2& v) { return v_uint8x16(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i64m1_i8m1(v.val))); } +inline v_int8x16 v_reinterpret_as_s8(const v_int64x2& v) { return v_int8x16(vreinterpret_v_i64m1_i8m1(v.val)); } +inline v_uint16x8 v_reinterpret_as_u16(const v_int64x2& v) { return v_uint16x8(vreinterpret_v_u64m1_u16m1(vreinterpret_v_i64m1_u64m1(v.val))); } +inline v_int16x8 v_reinterpret_as_s16(const v_int64x2& v) { return v_int16x8(vreinterpret_v_i64m1_i16m1(v.val)); } +inline v_uint32x4 v_reinterpret_as_u32(const v_int64x2& v) { return v_uint32x4(vreinterpret_v_u64m1_u32m1(vreinterpret_v_i64m1_u64m1(v.val))); } +inline v_int32x4 v_reinterpret_as_s32(const v_int64x2& v) { return v_int32x4(vreinterpret_v_i64m1_i32m1(v.val)); } +inline v_uint64x2 v_reinterpret_as_u64(const v_int64x2& v) { return v_uint64x2(vreinterpret_v_i64m1_u64m1(v.val)); } +inline v_int64x2 v_reinterpret_as_s64(const v_int64x2& v) { return v_int64x2(v.val); } +inline v_float32x4 v_reinterpret_as_f32(const v_int64x2& v) { return v_float32x4(vreinterpret_v_i32m1_f32m1(vreinterpret_v_i64m1_i32m1(v.val))); } +inline v_float64x2 v_reinterpret_as_f64(const v_int64x2& v) { return v_float64x2(vreinterpret_v_i64m1_f64m1(v.val)); } + +inline v_uint8x16 v_reinterpret_as_u8(const v_float32x4& v) { return v_uint8x16(vreinterpret_v_u32m1_u8m1(vreinterpret_v_f32m1_u32m1(v.val))); } +inline v_int8x16 v_reinterpret_as_s8(const v_float32x4& v) { return v_int8x16(vreinterpret_v_i32m1_i8m1(vreinterpret_v_f32m1_i32m1(v.val))); } +inline v_uint16x8 v_reinterpret_as_u16(const v_float32x4& v) { return v_uint16x8(vreinterpret_v_u32m1_u16m1(vreinterpret_v_f32m1_u32m1(v.val))); } +inline v_int16x8 v_reinterpret_as_s16(const v_float32x4& v) { return v_int16x8(vreinterpret_v_i32m1_i16m1(vreinterpret_v_f32m1_i32m1(v.val))); } +inline v_uint32x4 v_reinterpret_as_u32(const v_float32x4& v) { return v_uint32x4(vreinterpret_v_f32m1_u32m1(v.val)); } +inline v_int32x4 v_reinterpret_as_s32(const v_float32x4& v) { return v_int32x4(vreinterpret_v_f32m1_i32m1(v.val)); } +inline v_uint64x2 v_reinterpret_as_u64(const v_float32x4& v) { return v_uint64x2(vreinterpret_v_u32m1_u64m1(vreinterpret_v_f32m1_u32m1(v.val))); } +inline v_int64x2 v_reinterpret_as_s64(const v_float32x4& v) { return v_int64x2(vreinterpret_v_i32m1_i64m1(vreinterpret_v_f32m1_i32m1(v.val))); } +inline v_float32x4 v_reinterpret_as_f32(const v_float32x4& v) { return v_float32x4(v.val); } +inline v_float64x2 v_reinterpret_as_f64(const v_float32x4& v) { return v_float64x2(vreinterpret_v_i64m1_f64m1(vreinterpret_v_i32m1_i64m1(vreinterpret_v_f32m1_i32m1(v.val)))); } + +inline v_uint8x16 v_reinterpret_as_u8(const v_float64x2& v) { return v_uint8x16(vreinterpret_v_u64m1_u8m1(vreinterpret_v_f64m1_u64m1(v.val))); } +inline v_int8x16 v_reinterpret_as_s8(const v_float64x2& v) { return v_int8x16(vreinterpret_v_i64m1_i8m1(vreinterpret_v_f64m1_i64m1(v.val))); } +inline v_uint16x8 v_reinterpret_as_u16(const v_float64x2& v) { return v_uint16x8(vreinterpret_v_u64m1_u16m1(vreinterpret_v_f64m1_u64m1(v.val))); } +inline v_int16x8 v_reinterpret_as_s16(const v_float64x2& v) { return v_int16x8(vreinterpret_v_i64m1_i16m1(vreinterpret_v_f64m1_i64m1(v.val))); } +inline v_uint32x4 v_reinterpret_as_u32(const v_float64x2& v) { return v_uint32x4(vreinterpret_v_u64m1_u32m1(vreinterpret_v_f64m1_u64m1(v.val))); } +inline v_int32x4 v_reinterpret_as_s32(const v_float64x2& v) { return v_int32x4(vreinterpret_v_i64m1_i32m1(vreinterpret_v_f64m1_i64m1(v.val))); } +inline v_uint64x2 v_reinterpret_as_u64(const v_float64x2& v) { return v_uint64x2(vreinterpret_v_f64m1_u64m1(v.val)); } +inline v_int64x2 v_reinterpret_as_s64(const v_float64x2& v) { return v_int64x2(vreinterpret_v_f64m1_i64m1(v.val)); } +inline v_float32x4 v_reinterpret_as_f32(const v_float64x2& v) { return v_float32x4(vreinterpret_v_i32m1_f32m1(vreinterpret_v_i64m1_i32m1(vreinterpret_v_f64m1_i64m1(v.val)))); } +inline v_float64x2 v_reinterpret_as_f64(const v_float64x2& v) { return v_float64x2(v.val); } + +#define OPENCV_HAL_IMPL_RISCVV_INIT_SET(__Tp, _Tp, suffix, len, num) \ +inline v_##_Tp##x##num v_setzero_##suffix() { return v_##_Tp##x##num(vmv_v_x_##len##m1(0, num)); } \ +inline v_##_Tp##x##num v_setall_##suffix(__Tp v) { return v_##_Tp##x##num(vmv_v_x_##len##m1(v, num)); } \ +template <> inline v_##_Tp##x##num v_setzero_() { return v_setzero_##suffix(); } \ +template <> inline v_##_Tp##x##num v_setall_(__Tp v) { return v_setall_##suffix(v); } + +OPENCV_HAL_IMPL_RISCVV_INIT_SET(uchar, uint8, u8, u8, 16) +OPENCV_HAL_IMPL_RISCVV_INIT_SET(schar, int8, s8, i8, 16) +OPENCV_HAL_IMPL_RISCVV_INIT_SET(ushort, uint16, u16, u16, 8) +OPENCV_HAL_IMPL_RISCVV_INIT_SET(short, int16, s16, i16, 8) +OPENCV_HAL_IMPL_RISCVV_INIT_SET(unsigned int, uint32, u32, u32, 4) +OPENCV_HAL_IMPL_RISCVV_INIT_SET(int, int32, s32, i32, 4) +OPENCV_HAL_IMPL_RISCVV_INIT_SET(unsigned long, uint64, u64, u64, 2) +OPENCV_HAL_IMPL_RISCVV_INIT_SET(long, int64, s64, i64, 2) +inline v_float32x4 v_setzero_f32() { return v_float32x4(vfmv_v_f_f32m1(0, 4)); } +inline v_float32x4 v_setall_f32(float v) { return v_float32x4(vfmv_v_f_f32m1(v, 4)); } + +inline v_float64x2 v_setzero_f64() { return v_float64x2(vfmv_v_f_f64m1(0, 2)); } +inline v_float64x2 v_setall_f64(double v) { return v_float64x2(vfmv_v_f_f64m1(v, 2)); } + +template <> inline v_float32x4 v_setzero_() { return v_setzero_f32(); } +template <> inline v_float32x4 v_setall_(float v) { return v_setall_f32(v); } + +template <> inline v_float64x2 v_setzero_() { return v_setzero_f64(); } +template <> inline v_float64x2 v_setall_(double v) { return v_setall_f64(v); } + +#define OPENCV_HAL_IMPL_RISCVV_BIN_OP(bin_op, _Tpvec, intrin) \ +inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(intrin(a.val, b.val)); \ +} + +#define OPENCV_HAL_IMPL_RISCVV_BIN_OPN(bin_op, _Tpvec, intrin, num) \ +inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(intrin(a.val, b.val, num)); \ +} + +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_uint8x16, vsaddu_vv_u8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_uint8x16, vssubu_vv_u8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_int8x16, vsadd_vv_i8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_int8x16, vssub_vv_i8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_uint16x8, vsaddu_vv_u16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_uint16x8, vssubu_vv_u16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_int16x8, vsadd_vv_i16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_int16x8, vssub_vv_i16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_int32x4, vadd_vv_i32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_int32x4, vsub_vv_i32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_mul, v_int32x4, vmul_vv_i32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_uint32x4, vadd_vv_u32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_uint32x4, vsub_vv_u32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_mul, v_uint32x4, vmul_vv_u32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_int64x2, vadd_vv_i64m1, 2) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_int64x2, vsub_vv_i64m1, 2) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_uint64x2, vadd_vv_u64m1, 2) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_uint64x2, vsub_vv_u64m1, 2) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_float32x4, vfadd_vv_f32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_float32x4, vfsub_vv_f32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_mul, v_float32x4, vfmul_vv_f32m1, 4) +inline v_float32x4 v_div(const v_float32x4& a, const v_float32x4& b) +{ + return v_float32x4(vfdiv_vv_f32m1(a.val, b.val, 4)); +} + +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_float64x2, vfadd_vv_f64m1, 2) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_float64x2, vfsub_vv_f64m1, 2) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_mul, v_float64x2, vfmul_vv_f64m1, 2) +inline v_float64x2 v_div(const v_float64x2& a, const v_float64x2& b) +{ + return v_float64x2(vfdiv_vv_f64m1(a.val, b.val, 2)); +} +// TODO: exp, log, sin, cos + +#define OPENCV_HAL_IMPL_RISCVV_BIN_FUNC(_Tpvec, func, intrin) \ +inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(intrin(a.val, b.val)); \ +} + +#define OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(_Tpvec, func, intrin, num) \ +inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(intrin(a.val, b.val, num)); \ +} +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint8x16, v_min, vminu_vv_u8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint8x16, v_max, vmaxu_vv_u8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int8x16, v_min, vmin_vv_i8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int8x16, v_max, vmax_vv_i8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint16x8, v_min, vminu_vv_u16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint16x8, v_max, vmaxu_vv_u16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int16x8, v_min, vmin_vv_i16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int16x8, v_max, vmax_vv_i16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint32x4, v_min, vminu_vv_u32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint32x4, v_max, vmaxu_vv_u32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int32x4, v_min, vmin_vv_i32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int32x4, v_max, vmax_vv_i32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_float32x4, v_min, vfmin_vv_f32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_float32x4, v_max, vfmax_vv_f32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_float64x2, v_min, vfmin_vv_f64m1, 2) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_float64x2, v_max, vfmax_vv_f64m1, 2) + +inline v_float32x4 v_sqrt(const v_float32x4& x) +{ + return v_float32x4(vfsqrt_v_f32m1(x.val, 4)); +} + +inline v_float32x4 v_invsqrt(const v_float32x4& x) +{ + return v_float32x4(vfrdiv_vf_f32m1(vfsqrt_v_f32m1(x.val, 4), 1, 4)); +} + +inline v_float32x4 v_magnitude(const v_float32x4& a, const v_float32x4& b) +{ + v_float32x4 x(vfmacc_vv_f32m1(vfmul_vv_f32m1(a.val, a.val, 4), b.val, b.val, 4)); + return v_sqrt(x); +} + +inline v_float32x4 v_sqr_magnitude(const v_float32x4& a, const v_float32x4& b) +{ + return v_float32x4(vfmacc_vv_f32m1(vfmul_vv_f32m1(a.val, a.val, 4), b.val, b.val, 4)); +} + +inline v_float32x4 v_fma(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) +{ + return v_float32x4(vfmadd_vv_f32m1(a.val, b.val, c.val, 4)); +} + +inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ + return v_int32x4(vmadd_vv_i32m1(a.val, b.val, c.val, 4)); +} + +inline v_float32x4 v_muladd(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) +{ + return v_fma(a, b, c); +} + +inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ + return v_fma(a, b, c); +} + +inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, + const v_float32x4& m3) +{ + vfloat32m1_t res = vfmul_vv_f32m1(m0.val, vrgather_vx_f32m1(v.val, 0, 4), 4);//vmuli_f32(m0.val, v.val, 0); + res = vfmacc_vv_f32m1(res, vrgather_vx_f32m1(v.val, 1, 4), m1.val, 4);//vmulai_f32(res, m1.val, v.val, 1); + res = vfmacc_vv_f32m1(res, vrgather_vx_f32m1(v.val, 2, 4), m2.val, 4);//vmulai_f32(res, m1.val, v.val, 1); + res = vfmacc_vv_f32m1(res, vrgather_vx_f32m1(v.val, 3, 4), m3.val, 4);//vmulai_f32(res, m1.val, v.val, 1); + return v_float32x4(res); +} + +inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, + const v_float32x4& a) +{ + vfloat32m1_t res = vfmul_vv_f32m1(m0.val, vrgather_vx_f32m1(v.val, 0, 4), 4);//vmuli_f32(m0.val, v.val, 0); + res = vfmacc_vv_f32m1(res, vrgather_vx_f32m1(v.val, 1, 4), m1.val, 4);//vmulai_f32(res, m1.val, v.val, 1); + res = vfmacc_vv_f32m1(res, vrgather_vx_f32m1(v.val, 2, 4), m2.val, 4);//vmulai_f32(res, m1.val, v.val, 1); + res = vfadd_vv_f32m1(res, a.val, 4);//vmulai_f32(res, m1.val, v.val, 1); + return v_float32x4(res); +} + +inline v_float64x2 v_sqrt(const v_float64x2& x) +{ + return v_float64x2(vfsqrt_v_f64m1(x.val, 2)); +} + +inline v_float64x2 v_invsqrt(const v_float64x2& x) +{ + return v_float64x2(vfrdiv_vf_f64m1(vfsqrt_v_f64m1(x.val, 2), 1, 2)); +} + +inline v_float64x2 v_magnitude(const v_float64x2& a, const v_float64x2& b) +{ + v_float64x2 x(vfmacc_vv_f64m1(vfmul_vv_f64m1(a.val, a.val, 2), b.val, b.val, 2)); + return v_sqrt(x); +} + +inline v_float64x2 v_sqr_magnitude(const v_float64x2& a, const v_float64x2& b) +{ + return v_float64x2(vfmacc_vv_f64m1(vfmul_vv_f64m1(a.val, a.val, 2), b.val, b.val, 2)); +} + +inline v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) +{ + return v_float64x2(vfmadd_vv_f64m1(a.val, b.val, c.val, 2)); +} + +inline v_float64x2 v_muladd(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) +{ + return v_fma(a, b, c); +} + +#define OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(_Tpvec, suffix, num) \ + OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_and, _Tpvec, vand_vv_##suffix, num) \ + OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_or, _Tpvec, vor_vv_##suffix, num) \ + OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_xor, _Tpvec, vxor_vv_##suffix, num) \ + inline _Tpvec v_not(const _Tpvec & a) \ + { \ + return _Tpvec(vnot_v_##suffix(a.val, num)); \ + } + +OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_uint8x16, u8m1, 16) +OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_uint16x8, u16m1, 8) +OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_uint32x4, u32m1, 4) +OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_uint64x2, u64m1, 2) +OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_int8x16, i8m1, 16) +OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_int16x8, i16m1, 8) +OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_int32x4, i32m1, 4) +OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_int64x2, i64m1, 2) + +#define OPENCV_HAL_IMPL_RISCVV_FLT_BIT_OP(bin_op, intrin) \ +inline v_float32x4 bin_op(const v_float32x4& a, const v_float32x4& b) \ +{ \ + return v_float32x4(vreinterpret_v_i32m1_f32m1(intrin(vreinterpret_v_f32m1_i32m1(a.val), vreinterpret_v_f32m1_i32m1(b.val), 4))); \ +} + +OPENCV_HAL_IMPL_RISCVV_FLT_BIT_OP(v_and, vand_vv_i32m1) +OPENCV_HAL_IMPL_RISCVV_FLT_BIT_OP(v_or, vor_vv_i32m1) +OPENCV_HAL_IMPL_RISCVV_FLT_BIT_OP(v_xor, vxor_vv_i32m1) + +inline v_float32x4 v_not(const v_float32x4& a) +{ + return v_float32x4(vreinterpret_v_i32m1_f32m1(vnot_v_i32m1(vreinterpret_v_f32m1_i32m1(a.val), 4))); +} + +#define OPENCV_HAL_IMPL_RISCVV_FLT_64BIT_OP(bin_op, intrin) \ +inline v_float64x2 bin_op(const v_float64x2& a, const v_float64x2& b) \ +{ \ + return v_float64x2(vreinterpret_v_i64m1_f64m1(intrin(vreinterpret_v_f64m1_i64m1(a.val), vreinterpret_v_f64m1_i64m1(b.val), 2))); \ +} + +OPENCV_HAL_IMPL_RISCVV_FLT_64BIT_OP(v_and, vand_vv_i64m1) +OPENCV_HAL_IMPL_RISCVV_FLT_64BIT_OP(v_or, vor_vv_i64m1) +OPENCV_HAL_IMPL_RISCVV_FLT_64BIT_OP(v_xor, vxor_vv_i64m1) + +inline v_float64x2 v_not(const v_float64x2& a) +{ + return v_float64x2(vreinterpret_v_i64m1_f64m1(vnot_v_i64m1(vreinterpret_v_f64m1_i64m1(a.val), 2))); +} +inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) +{ + return v_int16x8(vmulh_vv_i16m1(a.val, b.val, 8)); +} +inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) +{ + return v_uint16x8(vmulhu_vv_u16m1(a.val, b.val, 8)); +} + +//#define OPENCV_HAL_IMPL_RISCVV_ABS(_Tpuvec, _Tpsvec, usuffix, ssuffix) \ +//inline _Tpuvec v_abs(const _Tpsvec& a) { \ +// E##xm1_t mask=vmflt_vf_e32xm1_f32m1(x.val, 0.0, 4); + +//OPENCV_HAL_IMPL_RISCVV_ABS(v_uint8x16, v_int8x16, u8, s8) +//OPENCV_HAL_IMPL_RISCVV_ABS(v_uint16x8, v_int16x8, u16, s16) +//OPENCV_HAL_IMPL_RISCVV_ABS(v_uint32x4, v_int32x4, u32, s32) + +inline v_uint32x4 v_abs(v_int32x4 x) +{ + vbool32_t mask=vmslt_vx_i32m1_b32(x.val, 0, 4); + return v_uint32x4(vreinterpret_v_i32m1_u32m1(vrsub_vx_i32m1_m(mask, x.val, x.val, 0, 4))); +} + +inline v_uint16x8 v_abs(v_int16x8 x) +{ + vbool16_t mask=vmslt_vx_i16m1_b16(x.val, 0, 8); + return v_uint16x8(vreinterpret_v_i16m1_u16m1(vrsub_vx_i16m1_m(mask, x.val, x.val, 0, 8))); +} + +inline v_uint8x16 v_abs(v_int8x16 x) +{ + vbool8_t mask=vmslt_vx_i8m1_b8(x.val, 0, 16); + return v_uint8x16(vreinterpret_v_i8m1_u8m1(vrsub_vx_i8m1_m(mask, x.val, x.val, 0, 16))); +} + +inline v_float32x4 v_abs(v_float32x4 x) +{ + return (v_float32x4)vfsgnjx_vv_f32m1(x.val, x.val, 4); +} + +inline v_float64x2 v_abs(v_float64x2 x) +{ + return (v_float64x2)vfsgnjx_vv_f64m1(x.val, x.val, 2); +} + +inline v_float32x4 v_absdiff(const v_float32x4& a, const v_float32x4& b) +{ + vfloat32m1_t ret = vfsub_vv_f32m1(a.val, b.val, 4); + return (v_float32x4)vfsgnjx_vv_f32m1(ret, ret, 4); +} + +inline v_float64x2 v_absdiff(const v_float64x2& a, const v_float64x2& b) +{ + vfloat64m1_t ret = vfsub_vv_f64m1(a.val, b.val, 2); + return (v_float64x2)vfsgnjx_vv_f64m1(ret, ret, 2); +} + +#define OPENCV_HAL_IMPL_RISCVV_ABSDIFF_U(bit, num) \ +inline v_uint##bit##x##num v_absdiff(v_uint##bit##x##num a, v_uint##bit##x##num b){ \ + vuint##bit##m1_t vmax = vmaxu_vv_u##bit##m1(a.val, b.val, num); \ + vuint##bit##m1_t vmin = vminu_vv_u##bit##m1(a.val, b.val, num); \ + return v_uint##bit##x##num(vsub_vv_u##bit##m1(vmax, vmin, num));\ +} + +OPENCV_HAL_IMPL_RISCVV_ABSDIFF_U(8, 16) +OPENCV_HAL_IMPL_RISCVV_ABSDIFF_U(16, 8) +OPENCV_HAL_IMPL_RISCVV_ABSDIFF_U(32, 4) + +/** Saturating absolute difference **/ +inline v_int8x16 v_absdiffs(v_int8x16 a, v_int8x16 b){ + vint8m1_t vmax = vmax_vv_i8m1(a.val, b.val, 16); + vint8m1_t vmin = vmin_vv_i8m1(a.val, b.val, 16); + return v_int8x16(vssub_vv_i8m1(vmax, vmin, 16)); +} +inline v_int16x8 v_absdiffs(v_int16x8 a, v_int16x8 b){ + vint16m1_t vmax = vmax_vv_i16m1(a.val, b.val, 8); + vint16m1_t vmin = vmin_vv_i16m1(a.val, b.val, 8); + return v_int16x8(vssub_vv_i16m1(vmax, vmin, 8)); +} + +#define OPENCV_HAL_IMPL_RISCVV_ABSDIFF(_Tpvec, _Tpv, num) \ +inline v_uint##_Tpvec v_absdiff(v_int##_Tpvec a, v_int##_Tpvec b){ \ + vint##_Tpv##_t max = vmax_vv_i##_Tpv(a.val, b.val, num);\ + vint##_Tpv##_t min = vmin_vv_i##_Tpv(a.val, b.val, num);\ + return v_uint##_Tpvec(vreinterpret_v_i##_Tpv##_u##_Tpv(vsub_vv_i##_Tpv(max, min, num))); \ +} + +OPENCV_HAL_IMPL_RISCVV_ABSDIFF(8x16, 8m1, 16) +OPENCV_HAL_IMPL_RISCVV_ABSDIFF(16x8, 16m1, 8) +OPENCV_HAL_IMPL_RISCVV_ABSDIFF(32x4, 32m1, 4) + +// Multiply and expand +inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b, + v_int16x8& c, v_int16x8& d) +{ + vint16m2_t res = vundefined_i16m2(); + res = vwmul_vv_i16m2(a.val, b.val, 16); + c.val = vget_v_i16m2_i16m1(res, 0); + d.val = vget_v_i16m2_i16m1(res, 1); +} + +inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b, + v_uint16x8& c, v_uint16x8& d) +{ + vuint16m2_t res = vundefined_u16m2(); + res = vwmulu_vv_u16m2(a.val, b.val, 16); + c.val = vget_v_u16m2_u16m1(res, 0); + d.val = vget_v_u16m2_u16m1(res, 1); +} + +inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, + v_int32x4& c, v_int32x4& d) +{ + vint32m2_t res = vundefined_i32m2(); + res = vwmul_vv_i32m2(a.val, b.val, 8); + c.val = vget_v_i32m2_i32m1(res, 0); + d.val = vget_v_i32m2_i32m1(res, 1); +} + +inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, + v_uint32x4& c, v_uint32x4& d) +{ + vuint32m2_t res = vundefined_u32m2(); + res = vwmulu_vv_u32m2(a.val, b.val, 8); + c.val = vget_v_u32m2_u32m1(res, 0); + d.val = vget_v_u32m2_u32m1(res, 1); +} + +inline void v_mul_expand(const v_int32x4& a, const v_int32x4& b, + v_int64x2& c, v_int64x2& d) +{ + vint64m2_t res = vundefined_i64m2(); + res = vwmul_vv_i64m2(a.val, b.val, 4); + c.val = vget_v_i64m2_i64m1(res, 0); + d.val = vget_v_i64m2_i64m1(res, 1); +} + +inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, + v_uint64x2& c, v_uint64x2& d) +{ + vuint64m2_t res = vundefined_u64m2(); + res = vwmulu_vv_u64m2(a.val, b.val, 4); + c.val = vget_v_u64m2_u64m1(res, 0); + d.val = vget_v_u64m2_u64m1(res, 1); +} + +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint8x16, v_add_wrap, vadd_vv_u8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int8x16, v_add_wrap, vadd_vv_i8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint16x8, v_add_wrap, vadd_vv_u16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int16x8, v_add_wrap, vadd_vv_i16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint8x16, v_sub_wrap, vsub_vv_u8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int8x16, v_sub_wrap, vsub_vv_i8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint16x8, v_sub_wrap, vsub_vv_u16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int16x8, v_sub_wrap, vsub_vv_i16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint8x16, v_mul_wrap, vmul_vv_u8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int8x16, v_mul_wrap, vmul_vv_i8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint16x8, v_mul_wrap, vmul_vv_u16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int16x8, v_mul_wrap, vmul_vv_i16m1, 8) +//////// Dot Product //////// +// 16 >> 32 +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) +{ + vuint32m2_t vindex = vundefined_u32m2(); + vuint32m1_t vindex0 = vid_v_u32m1(4); + vindex0 = vsll_vx_u32m1(vindex0, 1, 4); + vindex = vset_v_u32m1_u32m2(vindex, 0, vindex0); + vindex = vset_v_u32m1_u32m2(vindex, 1, vadd_vx_u32m1(vindex0, 1, 4)); + vint32m2_t res = vundefined_i32m2(); + res = vwmul_vv_i32m2(a.val, b.val, 8); + res = vrgather_vv_i32m2(res, vindex, 8); + return v_int32x4(vadd_vv_i32m1(vget_v_i32m2_i32m1(res, 0), vget_v_i32m2_i32m1(res, 1), 4)); +} +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ + vuint32m2_t vindex = vundefined_u32m2(); + vuint32m1_t vindex0 = vid_v_u32m1(4); + vindex0 = vsll_vx_u32m1(vindex0, 1, 4); + vindex = vset_v_u32m1_u32m2(vindex, 0, vindex0); + vindex = vset_v_u32m1_u32m2(vindex, 1, vadd_vx_u32m1(vindex0, 1, 4)); + vint32m2_t res = vundefined_i32m2(); + res = vwmul_vv_i32m2(a.val, b.val, 8); + res = vrgather_vv_i32m2(res, vindex, 8); + return v_int32x4(vadd_vv_i32m1(vadd_vv_i32m1(vget_v_i32m2_i32m1(res, 0),vget_v_i32m2_i32m1(res, 1), 4), c.val, 4)); +} + +// 32 >> 64 +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) +{ + vuint64m2_t vindex = vundefined_u64m2(); + vuint64m1_t vindex0 = vid_v_u64m1(2); + vindex0 = vsll_vx_u64m1(vindex0, 1, 2); + vindex = vset_v_u64m1_u64m2(vindex, 0, vindex0); + vindex = vset_v_u64m1_u64m2(vindex, 1, vadd_vx_u64m1(vindex0, 1, 2)); + vint64m2_t res = vundefined_i64m2(); + res = vwmul_vv_i64m2(a.val, b.val, 4); + res = vrgather_vv_i64m2(res, vindex, 4); + return v_int64x2(vadd_vv_i64m1(vget_v_i64m2_i64m1(res, 0), vget_v_i64m2_i64m1(res, 1), 2)); +} +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ + vuint64m2_t vindex = vundefined_u64m2(); + vuint64m1_t vindex0 = vid_v_u64m1(2); + vindex0 = vsll_vx_u64m1(vindex0, 1, 2); + vindex = vset_v_u64m1_u64m2(vindex, 0, vindex0); + vindex = vset_v_u64m1_u64m2(vindex, 1, vadd_vx_u64m1(vindex0, 1, 2)); + vint64m2_t res = vundefined_i64m2(); + res = vwmul_vv_i64m2(a.val, b.val, 4); + res = vrgather_vv_i64m2(res, vindex, 4); + return v_int64x2(vadd_vv_i64m1(vadd_vv_i64m1(vget_v_i64m2_i64m1(res, 0), vget_v_i64m2_i64m1(res, 1), 2), c.val, 2)); +} + +// 8 >> 32 +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) +{ + vuint32m4_t vindex32 = vundefined_u32m4(); + vuint32m1_t vindex0 = vid_v_u32m1(4); + vindex0 = vsll_vx_u32m1(vindex0, 2, 4); + vindex32 = vset_v_u32m1_u32m4(vindex32, 0, vindex0); + vindex32 = vset_v_u32m1_u32m4(vindex32, 1, vadd_vx_u32m1(vindex0, 1, 4)); + vindex32 = vset_v_u32m1_u32m4(vindex32, 2, vadd_vx_u32m1(vindex0, 2, 4)); + vindex32 = vset_v_u32m1_u32m4(vindex32, 3, vadd_vx_u32m1(vindex0, 3, 4)); + vuint16m2_t vindex = vnsrl_wx_u16m2(vindex32, 0, 16); + vuint16m2_t v1 = vundefined_u16m2(); + vuint32m2_t v2 = vundefined_u32m2(); + v1 = vwmulu_vv_u16m2(a.val, b.val, 16); + v1 = vrgather_vv_u16m2(v1, vindex, 16); + v2 = vwaddu_vv_u32m2(vget_v_u16m2_u16m1(v1, 0), vget_v_u16m2_u16m1(v1, 1), 8); + return v_uint32x4(vadd_vv_u32m1(vget_v_u32m2_u32m1(v2, 0), vget_v_u32m2_u32m1(v2, 1), 4)); +} + +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, + const v_uint32x4& c) +{ + vuint32m4_t vindex32 = vundefined_u32m4(); + vuint32m1_t vindex0 = vid_v_u32m1(4); + vindex0 = vsll_vx_u32m1(vindex0, 2, 4); + vindex32 = vset_v_u32m1_u32m4(vindex32, 0, vindex0); + vindex32 = vset_v_u32m1_u32m4(vindex32, 1, vadd_vx_u32m1(vindex0, 1, 4)); + vindex32 = vset_v_u32m1_u32m4(vindex32, 2, vadd_vx_u32m1(vindex0, 2, 4)); + vindex32 = vset_v_u32m1_u32m4(vindex32, 3, vadd_vx_u32m1(vindex0, 3, 4)); + vuint16m2_t vindex = vnsrl_wx_u16m2(vindex32, 0, 16); + vuint16m2_t v1 = vundefined_u16m2(); + vuint32m2_t v2 = vundefined_u32m2(); + v1 = vwmulu_vv_u16m2(a.val, b.val, 16); + v1 = vrgather_vv_u16m2(v1, vindex, 16); + v2 = vwaddu_vv_u32m2(vget_v_u16m2_u16m1(v1, 0), vget_v_u16m2_u16m1(v1, 1), 8); + return v_uint32x4(vadd_vv_u32m1(vadd_vv_u32m1(vget_v_u32m2_u32m1(v2, 0), vget_v_u32m2_u32m1(v2, 1), 4), c.val, 4)); +} + +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) +{ + vuint32m4_t vindex32 = vundefined_u32m4(); + vuint32m1_t vindex0 = vid_v_u32m1(4); + vindex0 = vsll_vx_u32m1(vindex0, 2, 4); + vindex32 = vset_v_u32m1_u32m4(vindex32, 0, vindex0); + vindex32 = vset_v_u32m1_u32m4(vindex32, 1, vadd_vx_u32m1(vindex0, 1, 4)); + vindex32 = vset_v_u32m1_u32m4(vindex32, 2, vadd_vx_u32m1(vindex0, 2, 4)); + vindex32 = vset_v_u32m1_u32m4(vindex32, 3, vadd_vx_u32m1(vindex0, 3, 4)); + vuint16m2_t vindex = vnsrl_wx_u16m2(vindex32, 0, 16); + vint16m2_t v1 = vundefined_i16m2(); + vint32m2_t v2 = vundefined_i32m2(); + v1 = vwmul_vv_i16m2(a.val, b.val, 16); + v1 = vrgather_vv_i16m2(v1, vindex, 16); + v2 = vwadd_vv_i32m2(vget_v_i16m2_i16m1(v1, 0), vget_v_i16m2_i16m1(v1, 1), 8); + return v_int32x4(vadd_vv_i32m1(vget_v_i32m2_i32m1(v2, 0), vget_v_i32m2_i32m1(v2, 1), 4)); +} + +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, + const v_int32x4& c) +{ + vuint32m4_t vindex32 = vundefined_u32m4(); + vuint32m1_t vindex0 = vid_v_u32m1(4); + vindex0 = vsll_vx_u32m1(vindex0, 2, 4); + vindex32 = vset_v_u32m1_u32m4(vindex32, 0, vindex0); + vindex32 = vset_v_u32m1_u32m4(vindex32, 1, vadd_vx_u32m1(vindex0, 1, 4)); + vindex32 = vset_v_u32m1_u32m4(vindex32, 2, vadd_vx_u32m1(vindex0, 2, 4)); + vindex32 = vset_v_u32m1_u32m4(vindex32, 3, vadd_vx_u32m1(vindex0, 3, 4)); + vuint16m2_t vindex = vnsrl_wx_u16m2(vindex32, 0, 16); + vint16m2_t v1 = vundefined_i16m2(); + vint32m2_t v2 = vundefined_i32m2(); + v1 = vwmul_vv_i16m2(a.val, b.val, 16); + v1 = vrgather_vv_i16m2(v1, vindex, 16); + v2 = vwadd_vv_i32m2(vget_v_i16m2_i16m1(v1, 0), vget_v_i16m2_i16m1(v1, 1), 8); + return v_int32x4(vadd_vv_i32m1(vadd_vv_i32m1(vget_v_i32m2_i32m1(v2, 0), vget_v_i32m2_i32m1(v2, 1), 4), c.val, 4)); +} + +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) +{ + vuint64m4_t vindex64 = vundefined_u64m4(); + vuint64m1_t vindex0 = vid_v_u64m1(2); + vindex0 = vsll_vx_u64m1(vindex0, 2, 2); + vindex64 = vset_v_u64m1_u64m4(vindex64, 0, vindex0); + vindex64 = vset_v_u64m1_u64m4(vindex64, 1, vadd_vx_u64m1(vindex0, 1, 2)); + vindex64 = vset_v_u64m1_u64m4(vindex64, 2, vadd_vx_u64m1(vindex0, 2, 2)); + vindex64 = vset_v_u64m1_u64m4(vindex64, 3, vadd_vx_u64m1(vindex0, 3, 2)); + vuint32m2_t vindex = vnsrl_wx_u32m2(vindex64, 0, 8); + vuint32m2_t v1 = vundefined_u32m2(); + vuint64m2_t v2 = vundefined_u64m2(); + v1 = vwmulu_vv_u32m2(a.val, b.val, 8); + v1 = vrgather_vv_u32m2(v1, vindex, 8); + v2 = vwaddu_vv_u64m2(vget_v_u32m2_u32m1(v1, 0), vget_v_u32m2_u32m1(v1, 1), 4); + return v_uint64x2(vadd_vv_u64m1(vget_v_u64m2_u64m1(v2, 0), vget_v_u64m2_u64m1(v2, 1), 2)); +} + +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, + const v_uint64x2& c) +{ + vuint64m4_t vindex64 = vundefined_u64m4(); + vuint64m1_t vindex0 = vid_v_u64m1(2); + vindex0 = vsll_vx_u64m1(vindex0, 2, 2); + vindex64 = vset_v_u64m1_u64m4(vindex64, 0, vindex0); + vindex64 = vset_v_u64m1_u64m4(vindex64, 1, vadd_vx_u64m1(vindex0, 1, 2)); + vindex64 = vset_v_u64m1_u64m4(vindex64, 2, vadd_vx_u64m1(vindex0, 2, 2)); + vindex64 = vset_v_u64m1_u64m4(vindex64, 3, vadd_vx_u64m1(vindex0, 3, 2)); + vuint32m2_t vindex = vnsrl_wx_u32m2(vindex64, 0, 8); + vuint32m2_t v1 = vundefined_u32m2(); + vuint64m2_t v2 = vundefined_u64m2(); + v1 = vwmulu_vv_u32m2(a.val, b.val, 8); + v1 = vrgather_vv_u32m2(v1, vindex, 8); + v2 = vwaddu_vv_u64m2(vget_v_u32m2_u32m1(v1, 0), vget_v_u32m2_u32m1(v1, 1), 4); + return v_uint64x2(vadd_vv_u64m1(vadd_vv_u64m1(vget_v_u64m2_u64m1(v2, 0), vget_v_u64m2_u64m1(v2, 1), 2), c.val, 2)); +} + +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) +{ + vuint64m4_t vindex64 = vundefined_u64m4(); + vuint64m1_t vindex0 = vid_v_u64m1(2); + vindex0 = vsll_vx_u64m1(vindex0, 2, 2); + vindex64 = vset_v_u64m1_u64m4(vindex64, 0, vindex0); + vindex64 = vset_v_u64m1_u64m4(vindex64, 1, vadd_vx_u64m1(vindex0, 1, 2)); + vindex64 = vset_v_u64m1_u64m4(vindex64, 2, vadd_vx_u64m1(vindex0, 2, 2)); + vindex64 = vset_v_u64m1_u64m4(vindex64, 3, vadd_vx_u64m1(vindex0, 3, 2)); + vuint32m2_t vindex = vnsrl_wx_u32m2(vindex64, 0, 8); + vint32m2_t v1 = vundefined_i32m2(); + vint64m2_t v2 = vundefined_i64m2(); + v1 = vwmul_vv_i32m2(a.val, b.val, 8); + v1 = vrgather_vv_i32m2(v1, vindex, 8); + v2 = vwadd_vv_i64m2(vget_v_i32m2_i32m1(v1, 0), vget_v_i32m2_i32m1(v1, 1), 4); + return v_int64x2(vadd_vv_i64m1(vget_v_i64m2_i64m1(v2, 0), vget_v_i64m2_i64m1(v2, 1), 2)); +} + +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, + const v_int64x2& c) +{ + vuint64m4_t vindex64 = vundefined_u64m4(); + vuint64m1_t vindex0 = vid_v_u64m1(2); + vindex0 = vsll_vx_u64m1(vindex0, 2, 2); + vindex64 = vset_v_u64m1_u64m4(vindex64, 0, vindex0); + vindex64 = vset_v_u64m1_u64m4(vindex64, 1, vadd_vx_u64m1(vindex0, 1, 2)); + vindex64 = vset_v_u64m1_u64m4(vindex64, 2, vadd_vx_u64m1(vindex0, 2, 2)); + vindex64 = vset_v_u64m1_u64m4(vindex64, 3, vadd_vx_u64m1(vindex0, 3, 2)); + vuint32m2_t vindex = vnsrl_wx_u32m2(vindex64, 0, 8); + vint32m2_t v1 = vundefined_i32m2(); + vint64m2_t v2 = vundefined_i64m2(); + v1 = vwmul_vv_i32m2(a.val, b.val, 8); + v1 = vrgather_vv_i32m2(v1, vindex, 8); + v2 = vwadd_vv_i64m2(vget_v_i32m2_i32m1(v1, 0), vget_v_i32m2_i32m1(v1, 1), 4); + return v_int64x2(vadd_vv_i64m1(vadd_vv_i64m1(vget_v_i64m2_i64m1(v2, 0), vget_v_i64m2_i64m1(v2, 1), 2), c.val, 2)); +} + +//////// Fast Dot Product //////// +// 16 >> 32 +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) +{ + vint32m2_t v1 = vundefined_i32m2(); + v1 = vwmul_vv_i32m2(a.val, b.val, 8); + return v_int32x4(vadd_vv_i32m1(vget_v_i32m2_i32m1(v1, 0), vget_v_i32m2_i32m1(v1, 1), 4)); +} + +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ + vint32m2_t v1 = vundefined_i32m2(); + v1 = vwmul_vv_i32m2(a.val, b.val, 8); + return v_int32x4(vadd_vv_i32m1(vadd_vv_i32m1(vget_v_i32m2_i32m1(v1, 0), vget_v_i32m2_i32m1(v1, 1), 4), c.val, 4)); +} + +// 32 >> 64 +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) +{ + vint64m2_t v1 = vundefined_i64m2(); + v1 = vwmul_vv_i64m2(a.val, b.val, 4); + return v_int64x2(vadd_vv_i64m1(vget_v_i64m2_i64m1(v1, 0), vget_v_i64m2_i64m1(v1, 1), 2)); +} +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ + vint64m2_t v1 = vundefined_i64m2(); + v1 = vwmul_vv_i64m2(a.val, b.val, 8); + return v_int64x2(vadd_vv_i64m1(vadd_vv_i64m1(vget_v_i64m2_i64m1(v1, 0), vget_v_i64m2_i64m1(v1, 1), 4), c.val, 4)); +} + +// 8 >> 32 +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) +{ + vuint16m2_t v1 = vundefined_u16m2(); + vuint32m2_t v2 = vundefined_u32m2(); + v1 = vwmulu_vv_u16m2(a.val, b.val, 16); + v2 = vwaddu_vv_u32m2(vget_v_u16m2_u16m1(v1, 0), vget_v_u16m2_u16m1(v1, 1), 8); + return v_uint32x4(vadd_vv_u32m1(vget_v_u32m2_u32m1(v2, 0), vget_v_u32m2_u32m1(v2, 1), 4)); +} + +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) +{ + vuint16m2_t v1 = vundefined_u16m2(); + vuint32m2_t v2 = vundefined_u32m2(); + v1 = vwmulu_vv_u16m2(a.val, b.val, 16); + v2 = vwaddu_vv_u32m2(vget_v_u16m2_u16m1(v1, 0), vget_v_u16m2_u16m1(v1, 1), 8); + return v_uint32x4(vadd_vv_u32m1(vadd_vv_u32m1(vget_v_u32m2_u32m1(v2, 0), vget_v_u32m2_u32m1(v2, 1), 4), c.val, 4)); +} + +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) +{ + vint16m2_t v1 = vundefined_i16m2(); + vint32m2_t v2 = vundefined_i32m2(); + v1 = vwmul_vv_i16m2(a.val, b.val, 16); + v2 = vwadd_vv_i32m2(vget_v_i16m2_i16m1(v1, 0), vget_v_i16m2_i16m1(v1, 1), 8); + return v_int32x4(vadd_vv_i32m1(vget_v_i32m2_i32m1(v2, 0), vget_v_i32m2_i32m1(v2, 1), 4)); +} +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) +{ + vint16m2_t v1 = vundefined_i16m2(); + vint32m2_t v2 = vundefined_i32m2(); + v1 = vwmul_vv_i16m2(a.val, b.val, 16); + v2 = vwadd_vv_i32m2(vget_v_i16m2_i16m1(v1, 0), vget_v_i16m2_i16m1(v1, 1), 8); + return v_int32x4(vadd_vv_i32m1(vadd_vv_i32m1(vget_v_i32m2_i32m1(v2, 0), vget_v_i32m2_i32m1(v2, 1), 4), c.val, 4)); +} + +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) +{ + vuint32m2_t v1 = vundefined_u32m2(); + vuint64m2_t v2 = vundefined_u64m2(); + v1 = vwmulu_vv_u32m2(a.val, b.val, 8); + v2 = vwaddu_vv_u64m2(vget_v_u32m2_u32m1(v1, 0), vget_v_u32m2_u32m1(v1, 1), 4); + return v_uint64x2(vadd_vv_u64m1(vget_v_u64m2_u64m1(v2, 0), vget_v_u64m2_u64m1(v2, 1), 2)); +} +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) +{ + vuint32m2_t v1 = vundefined_u32m2(); + vuint64m2_t v2 = vundefined_u64m2(); + v1 = vwmulu_vv_u32m2(a.val, b.val, 8); + v2 = vwaddu_vv_u64m2(vget_v_u32m2_u32m1(v1, 0), vget_v_u32m2_u32m1(v1, 1), 4); + return v_uint64x2(vadd_vv_u64m1(vadd_vv_u64m1(vget_v_u64m2_u64m1(v2, 0), vget_v_u64m2_u64m1(v2, 1), 2), c.val, 2)); +} + +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) +{ + vint32m2_t v1 = vundefined_i32m2(); + vint64m2_t v2 = vundefined_i64m2(); + v1 = vwmul_vv_i32m2(a.val, b.val, 8); + v2 = vwadd_vv_i64m2(vget_v_i32m2_i32m1(v1, 0), vget_v_i32m2_i32m1(v1, 1), 4); + return v_int64x2(vadd_vv_i64m1(vget_v_i64m2_i64m1(v2, 0), vget_v_i64m2_i64m1(v2, 1), 2)); +} +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) +{ + vint32m2_t v1 = vundefined_i32m2(); + vint64m2_t v2 = vundefined_i64m2(); + v1 = vwmul_vv_i32m2(a.val, b.val, 8); + v2 = vwadd_vv_i64m2(vget_v_i32m2_i32m1(v1, 0), vget_v_i32m2_i32m1(v1, 1), 4); + return v_int64x2(vadd_vv_i64m1(vadd_vv_i64m1(vget_v_i64m2_i64m1(v2, 0), vget_v_i64m2_i64m1(v2, 1), 2), c.val, 2)); +} + + +#define OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(_Tpvec, _Tpvec2, len, scalartype, func, intrin, num) \ +inline scalartype v_reduce_##func(const v_##_Tpvec##x##num& a) \ +{\ + v##_Tpvec2##m1_t val = vmv_v_x_##len##m1(0, num); \ + val = intrin(val, a.val, val, num); \ + return vmv_x_s_##len##m1_##len(val); \ +} + + +#define OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(_Tpvec, _Tpvec2, scalartype, func, funcu, num, scalerfunc) \ +inline scalartype v_reduce_##func(const v_##_Tpvec##x##num& a) \ +{\ + v##_Tpvec##m1_t val = vundefined_##_Tpvec2##m1(); \ + val = v##funcu##_vs_##_Tpvec2##m1_##_Tpvec2##m1(val, a.val, a.val, num); \ + return scalerfunc(val); \ +} +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(int8, int16, i16, int, sum, vwredsum_vs_i8m1_i16m1, 16) +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(int16, int32, i32, int, sum, vwredsum_vs_i16m1_i32m1, 8) +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(int32, int64, i64, int, sum, vwredsum_vs_i32m1_i64m1, 4) +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(uint8, uint16, u16, unsigned, sum, vwredsumu_vs_u8m1_u16m1, 16) +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(uint16, uint32, u32, unsigned, sum, vwredsumu_vs_u16m1_u32m1, 8) +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(uint32, uint64, u64, unsigned, sum, vwredsumu_vs_u32m1_u64m1, 4) +inline float v_reduce_sum(const v_float32x4& a) \ +{\ + vfloat32m1_t val = vfmv_v_f_f32m1(0.0, 4); \ + val = vfredosum_vs_f32m1_f32m1(val, a.val, val, 4); \ + return vfmv_f_s_f32m1_f32(val); \ +} +inline double v_reduce_sum(const v_float64x2& a) \ +{\ + vfloat64m1_t val = vfmv_v_f_f64m1(0.0, 2); \ + val = vfredosum_vs_f64m1_f64m1(val, a.val, val, 2); \ + return vfmv_f_s_f64m1_f64(val); \ +} +inline uint64 v_reduce_sum(const v_uint64x2& a) +{ vuint64m1_t res = vundefined_u64m1(); return vmv_x_s_u64m1_u64(vredsum_vs_u64m1_u64m1(res, a.val, vmv_v_x_u64m1(0, 2), 2)); } + +inline int64 v_reduce_sum(const v_int64x2& a) +{ vint64m1_t res = vundefined_i64m1(); return vmv_x_s_i64m1_i64(vredsum_vs_i64m1_i64m1(res, a.val, vmv_v_x_i64m1(0, 2), 2)); } + +#define OPENCV_HAL_IMPL_RISCVV_REDUCE_OP(func) \ +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(int8, i8, int, func, red##func, 16, vmv_x_s_i8m1_i8) \ +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(int16, i16, int, func, red##func, 8, vmv_x_s_i16m1_i16) \ +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(int32, i32, int, func, red##func, 4, vmv_x_s_i32m1_i32) \ +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(int64, i64, int, func, red##func, 2, vmv_x_s_i64m1_i64) \ +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(uint8, u8, unsigned, func, red##func##u, 16, vmv_x_s_u8m1_u8) \ +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(uint16, u16, unsigned, func, red##func##u, 8, vmv_x_s_u16m1_u16) \ +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(uint32, u32, unsigned, func, red##func##u, 4, vmv_x_s_u32m1_u32) \ +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(float32, f32, float, func, fred##func, 4, vfmv_f_s_f32m1_f32) +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP(max) +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP(min) + +inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, + const v_float32x4& c, const v_float32x4& d) +{ + vfloat32m1_t a0 = vfmv_v_f_f32m1(0.0, 4); + vfloat32m1_t b0 = vfmv_v_f_f32m1(0.0, 4); + vfloat32m1_t c0 = vfmv_v_f_f32m1(0.0, 4); + vfloat32m1_t d0 = vfmv_v_f_f32m1(0.0, 4); + a0 = vfredosum_vs_f32m1_f32m1(a0, a.val, a0, 4); + b0 = vfredosum_vs_f32m1_f32m1(b0, b.val, b0, 4); + c0 = vfredosum_vs_f32m1_f32m1(c0, c.val, c0, 4); + d0 = vfredosum_vs_f32m1_f32m1(d0, d.val, d0, 4); + vfloat32m1_t res; + res = vslideup_vx_f32m1(a0, b0, 1, 4); + res = vslideup_vx_f32m1(res, c0, 2, 4); + res = vslideup_vx_f32m1(res, d0, 3, 4); + return v_float32x4(res); +} + +inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) +{ + vfloat32m1_t a0 = vfmv_v_f_f32m1(0.0, 4); + vfloat32m1_t x = vfsub_vv_f32m1(a.val, b.val, 4); + vbool32_t mask=vmflt_vf_f32m1_b32(x, 0, 4); + vfloat32m1_t val = vfrsub_vf_f32m1_m(mask, x, x, 0, 4); + a0 = vfredosum_vs_f32m1_f32m1(a0, val, a0, 4); + return vfmv_f_s_f32m1_f32(a0); +} + +#define OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(_Tpvec, _Tpvec2) \ +inline unsigned v_reduce_sad(const _Tpvec& a, const _Tpvec&b){ \ + _Tpvec2 x = v_absdiff(a, b); \ + return v_reduce_sum(x); \ +} + +OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(v_int8x16, v_uint8x16) +OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(v_uint8x16, v_uint8x16) +OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(v_int16x8, v_uint16x8) +OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(v_uint16x8, v_uint16x8) +OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(v_int32x4, v_uint32x4) +OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(v_uint32x4, v_uint32x4) + +#define OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(_Tpvec, _Tp, _T, num, uv) \ +inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ +{ \ + vbool##_T##_t mask = vmseq_vv_##_Tp##_b##_T(a.val, b.val, num); \ + return _Tpvec(vmerge_vxm_##_Tp(mask, vmv_v_x_##_Tp(0, num), -1, num)); \ +} \ +inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ +{ \ + vbool##_T##_t mask = vmsne_vv_##_Tp##_b##_T(a.val, b.val, num); \ + return _Tpvec(vmerge_vxm_##_Tp(mask, vmv_v_x_##_Tp(0, num), -1, num)); \ +} \ +inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ +{ \ + vbool##_T##_t mask = vmslt##uv##_Tp##_b##_T(a.val, b.val, num); \ + return _Tpvec(vmerge_vxm_##_Tp(mask, vmv_v_x_##_Tp(0, num), -1, num)); \ +} \ +inline _Tpvec v_gt(const _Tpvec& a, const _Tpvec& b) \ +{ \ + vbool##_T##_t mask = vmslt##uv##_Tp##_b##_T(b.val, a.val, num); \ + return _Tpvec(vmerge_vxm_##_Tp(mask, vmv_v_x_##_Tp(0, num), -1, num)); \ +} \ +inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ +{ \ + vbool##_T##_t mask = vmsle##uv##_Tp##_b##_T(a.val, b.val, num); \ + return _Tpvec(vmerge_vxm_##_Tp(mask, vmv_v_x_##_Tp(0, num), -1, num)); \ +} \ +inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ +{ \ + vbool##_T##_t mask = vmsle##uv##_Tp##_b##_T(b.val, a.val, num); \ + return _Tpvec(vmerge_vxm_##_Tp(mask, vmv_v_x_##_Tp(0, num), -1, num)); \ +} \ + +OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_int8x16, i8m1, 8, 16, _vv_) +OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_int16x8, i16m1, 16, 8, _vv_) +OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_int32x4, i32m1, 32, 4, _vv_) +OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_int64x2, i64m1, 64, 2, _vv_) +OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_uint8x16, u8m1, 8, 16, u_vv_) +OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_uint16x8, u16m1, 16, 8, u_vv_) +OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_uint32x4, u32m1, 32, 4, u_vv_) +OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_uint64x2, u64m1, 64, 2, u_vv_) + +//TODO: == +inline v_float32x4 v_eq(const v_float32x4& a, const v_float32x4& b) +{ + vbool32_t mask = vmfeq_vv_f32m1_b32(a.val, b.val, 4); + vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); + return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); +} +inline v_float32x4 v_ne(const v_float32x4& a, const v_float32x4& b) +{ + vbool32_t mask = vmfne_vv_f32m1_b32(a.val, b.val, 4); + vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); + return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); +} +inline v_float32x4 v_lt(const v_float32x4& a, const v_float32x4& b) +{ + vbool32_t mask = vmflt_vv_f32m1_b32(a.val, b.val, 4); + vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); + return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); +} +inline v_float32x4 v_le(const v_float32x4& a, const v_float32x4& b) +{ + vbool32_t mask = vmfle_vv_f32m1_b32(a.val, b.val, 4); + vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); + return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); +} +inline v_float32x4 v_gt(const v_float32x4& a, const v_float32x4& b) +{ + vbool32_t mask = vmfgt_vv_f32m1_b32(a.val, b.val, 4); + vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); + return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); +} +inline v_float32x4 v_ge(const v_float32x4& a, const v_float32x4& b) +{ + vbool32_t mask = vmfge_vv_f32m1_b32(a.val, b.val, 4); + vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); + return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); +}/**/ +inline v_float32x4 v_not_nan(const v_float32x4& a) +{ + vbool32_t mask = vmfeq_vv_f32m1_b32(a.val, a.val, 4); + vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); + return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); +} + +//TODO: == +inline v_float64x2 v_eq(const v_float64x2& a, const v_float64x2& b) +{ + vbool64_t mask = vmfeq_vv_f64m1_b64(a.val, b.val, 2); + vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); + return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); +} +inline v_float64x2 v_ne(const v_float64x2& a, const v_float64x2& b) +{ + vbool64_t mask = vmfne_vv_f64m1_b64(a.val, b.val, 2); + vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); + return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); +} +inline v_float64x2 v_lt(const v_float64x2& a, const v_float64x2& b) +{ + vbool64_t mask = vmflt_vv_f64m1_b64(a.val, b.val, 2); + vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); + return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); +} +inline v_float64x2 v_le(const v_float64x2& a, const v_float64x2& b) +{ + vbool64_t mask = vmfle_vv_f64m1_b64(a.val, b.val, 2); + vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); + return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); +} +inline v_float64x2 v_gt(const v_float64x2& a, const v_float64x2& b) +{ + vbool64_t mask = vmfgt_vv_f64m1_b64(a.val, b.val, 2); + vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); + return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); +} +inline v_float64x2 v_ge(const v_float64x2& a, const v_float64x2& b) +{ + vbool64_t mask = vmfge_vv_f64m1_b64(a.val, b.val, 2); + vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); + return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); +}/**/ +inline v_float64x2 v_not_nan(const v_float64x2& a) +{ + vbool64_t mask = vmfeq_vv_f64m1_b64(a.val, a.val, 2); + vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); + return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); +} +#define OPENCV_HAL_IMPL_RISCVV_TRANSPOSE4x4(_Tp, _T) \ +inline void v_transpose4x4(const v_##_Tp##32x4& a0, const v_##_Tp##32x4& a1, \ + const v_##_Tp##32x4& a2, const v_##_Tp##32x4& a3, \ + v_##_Tp##32x4& b0, v_##_Tp##32x4& b1, \ + v_##_Tp##32x4& b2, v_##_Tp##32x4& b3) \ +{ \ + vuint32m4_t vindex = vundefined_u32m4(); \ + vuint32m1_t vindex0 = vid_v_u32m1(4); \ + vindex0 = vsll_vx_u32m1(vindex0, 2, 4); \ + vindex = vset_v_u32m1_u32m4(vindex, 0, vindex0); \ + vindex = vset_v_u32m1_u32m4(vindex, 1, vadd_vx_u32m1(vindex0, 1, 4)); \ + vindex = vset_v_u32m1_u32m4(vindex, 2, vadd_vx_u32m1(vindex0, 2, 4)); \ + vindex = vset_v_u32m1_u32m4(vindex, 3, vadd_vx_u32m1(vindex0, 3, 4)); \ + v##_Tp##32m4_t val = vundefined_##_T##m4(); \ + val = vset_v_##_T##m1_##_T##m4(val, 0, a0.val); \ + val = vset_v_##_T##m1_##_T##m4(val, 1, a1.val); \ + val = vset_v_##_T##m1_##_T##m4(val, 2, a2.val); \ + val = vset_v_##_T##m1_##_T##m4(val, 3, a3.val); \ + val = vrgather_vv_##_T##m4(val, vindex, 16); \ + b0.val = vget_v_##_T##m4_##_T##m1(val, 0); \ + b1.val = vget_v_##_T##m4_##_T##m1(val, 1); \ + b2.val = vget_v_##_T##m4_##_T##m1(val, 2); \ + b3.val = vget_v_##_T##m4_##_T##m1(val, 3); \ +} +OPENCV_HAL_IMPL_RISCVV_TRANSPOSE4x4(uint, u32) +OPENCV_HAL_IMPL_RISCVV_TRANSPOSE4x4(int, i32) +OPENCV_HAL_IMPL_RISCVV_TRANSPOSE4x4(float, f32) + + +#define OPENCV_HAL_IMPL_RISCVV_SHIFT_LEFT(_Tpvec, suffix, _T, num) \ +inline _Tpvec v_shl(const _Tpvec& a, int n) \ +{ return _Tpvec((vsll_vx_##_T##m1(a.val, n, num))); } \ +template inline _Tpvec v_shl(const _Tpvec& a) \ +{ return _Tpvec((vsll_vx_##_T##m1(a.val, n, num))); } + +#define OPENCV_HAL_IMPL_RISCVV_SHIFT_RIGHT(_Tpvec, suffix, _T, num, intric) \ +inline _Tpvec v_shr(const _Tpvec& a, int n) \ +{ return _Tpvec((v##intric##_vx_##_T##m1(a.val, n, num))); } \ +template inline _Tpvec v_shr(const _Tpvec& a) \ +{ return _Tpvec((v##intric##_vx_##_T##m1(a.val, n, num))); }\ +template inline _Tpvec v_rshr(const _Tpvec& a) \ +{ return _Tpvec((v##intric##_vx_##_T##m1(vadd_vx_##_T##m1(a.val, 1<<(n-1), num), n, num))); } + +// trade efficiency for convenience +#define OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(suffix, _T, num, intrin) \ +OPENCV_HAL_IMPL_RISCVV_SHIFT_LEFT(v_##suffix##x##num, suffix, _T, num) \ +OPENCV_HAL_IMPL_RISCVV_SHIFT_RIGHT(v_##suffix##x##num, suffix, _T, num, intrin) + +OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(uint8, u8, 16, srl) +OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(uint16, u16, 8, srl) +OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(uint32, u32, 4, srl) +OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(uint64, u64, 2, srl) +OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(int8, i8, 16, sra) +OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(int16, i16, 8, sra) +OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(int32, i32, 4, sra) +OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(int64, i64, 2, sra) + +#if 0 +#define VUP4(n) {0, 1, 2, 3} +#define VUP8(n) {0, 1, 2, 3, 4, 5, 6, 7} +#define VUP16(n) {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15} +#define VUP2(n) {0, 1} +#endif +#define OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(_Tpvec, suffix, _T, num, num2, vmv, len) \ +template inline _Tpvec v_rotate_left(const _Tpvec& a) \ +{ \ + suffix##m1_t tmp = vmv##_##_T##m1(0, num);\ + tmp = vslideup_vx_##_T##m1_m(vmset_m_##len(num), tmp, a.val, n, num);\ + return _Tpvec(tmp);\ +} \ +template inline _Tpvec v_rotate_right(const _Tpvec& a) \ +{ \ + suffix##m1_t res = vundefined_##_T##m1(); \ + return _Tpvec(vslidedown_vx_##_T##m1(res, a.val, n, num));\ +} \ +template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a) \ +{ return a; } \ +template inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ +{ \ + suffix##m2_t tmp = vundefined_##_T##m2(); \ + suffix##m2_t res = vundefined_##_T##m2(); \ + tmp = vset_v_##_T##m1_##_T##m2(tmp, 0, a.val); \ + tmp = vset_v_##_T##m1_##_T##m2(tmp, 1, b.val); \ + res = vslidedown_vx_##_T##m2(res, tmp, n, num2);\ + return _Tpvec(vget_v_##_T##m2_##_T##m1(res, 0));\ +} \ +template inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ +{ \ + suffix##m2_t tmp = vundefined_##_T##m2(); \ + suffix##m2_t res = vundefined_##_T##m2(); \ + tmp = vset_v_##_T##m1_##_T##m2(tmp, 0, b.val); \ + tmp = vset_v_##_T##m1_##_T##m2(tmp, 1, a.val); \ + res = vslideup_vx_##_T##m2(res, tmp, n, num2);\ + return _Tpvec(vget_v_##_T##m2_##_T##m1(res, 1));\ +} \ +template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a, const _Tpvec& b) \ +{ \ + CV_UNUSED(b); return a; \ +} + +OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_uint8x16, vuint8, u8, 16, 32, vmv_v_x, b8) +OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_int8x16, vint8, i8, 16, 32, vmv_v_x, b8) +OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_uint16x8, vuint16, u16, 8, 16, vmv_v_x, b16) +OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_int16x8, vint16, i16, 8, 16, vmv_v_x, b16) +OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_uint32x4, vuint32, u32, 4, 8, vmv_v_x, b32) +OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_int32x4, vint32, i32, 4, 8, vmv_v_x, b32) +OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_uint64x2, vuint64, u64, 2, 4, vmv_v_x, b64) +OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_int64x2, vint64, i64, 2, 4, vmv_v_x, b64) +OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_float32x4, vfloat32, f32, 4, 8, vfmv_v_f, b32) +OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_float64x2, vfloat64, f64, 2, 4, vfmv_v_f, b64) + +#if 1 +#define vreinterpret_v_i8m1_i8m1 +#define vreinterpret_v_u8m1_u8m1 +#define OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(_Tpvec, _Tp, _Tp2, len, hnum, num, elemsize, ldst_len, ldst_type) \ +inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ +{ \ + _Tp2##_t res = vundefined_##len(); \ + _Tp2##_t res1 = vundefined_##len(); \ + res = vreinterpret_v_##ldst_len##_##len(vle8_v_##ldst_len((ldst_type *)ptr0, 8)); \ + res1 = vreinterpret_v_##ldst_len##_##len(vle8_v_##ldst_len((ldst_type *)ptr1, 8)); \ + res = vslideup_vx_##len(res, res1, hnum, num); \ + return _Tpvec(res); } \ +inline _Tpvec v_load_low(const _Tp* ptr) \ +{ return _Tpvec(vreinterpret_v_##ldst_len##_##len(vle8_v_##ldst_len((ldst_type *)ptr, 8))); }\ +inline _Tpvec v_load_aligned(const _Tp* ptr) \ +{ return _Tpvec(vreinterpret_v_##ldst_len##_##len(vle8_v_##ldst_len((ldst_type *)ptr, 16))); } \ +inline _Tpvec v_load(const _Tp* ptr) \ +{ return _Tpvec(vle##elemsize##_v_##len(ptr, num)); } \ +inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ +{ vse8_v_##ldst_len((ldst_type *)ptr, vreinterpret_v_##len##_##ldst_len(a.val), 8);}\ +inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ +{ \ + _Tp2##_t a0 = vundefined_##len(); \ + a0 = vslidedown_vx_##len(a0, a.val, hnum, num); \ + vse8_v_##ldst_len((ldst_type *)ptr, vreinterpret_v_##len##_##ldst_len(a0), 8);}\ +inline void v_store(_Tp* ptr, const _Tpvec& a) \ +{ vse##elemsize##_v_##len(ptr, a.val, num); } \ +inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ +{ vse8_v_##ldst_len((ldst_type *)ptr, vreinterpret_v_##len##_##ldst_len(a.val), 16); } \ +inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ +{ vse8_v_##ldst_len((ldst_type *)ptr, vreinterpret_v_##len##_##ldst_len(a.val), 16); } \ +inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ +{ vse8_v_##ldst_len((ldst_type *)ptr, vreinterpret_v_##len##_##ldst_len(a.val), 16); } + +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint8x16, uchar, vuint8m1, u8m1, 8, 16, 8, u8m1, uchar) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int8x16, schar, vint8m1, i8m1, 8, 16, 8, i8m1, schar) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint16x8, ushort, vuint16m1, u16m1, 4, 8, 16, u8m1, uchar) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int16x8, short, vint16m1, i16m1, 4, 8, 16, i8m1, schar) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint32x4, unsigned, vuint32m1, u32m1, 2, 4, 32, u8m1, uchar) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int32x4, int, vint32m1, i32m1, 2, 4, 32, i8m1, schar) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint64x2, unsigned long, vuint64m1, u64m1, 1, 2, 64, u8m1, uchar) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int64x2, long, vint64m1, i64m1, 1, 2, 64, i8m1, schar) + +#define OPENCV_HAL_IMPL_RISCVV_LOADSTORE_FLOAT_OP(_Tpvec, _Tp, _Tp2, len, hnum, num, elemsize) \ +inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ +{ \ + _Tp2##_t res = vundefined_##len(); \ + _Tp2##_t res1 = vundefined_##len(); \ + res = vreinterpret_v_u##elemsize##m1_##len(vreinterpret_v_u8m1_u##elemsize##m1(vle8_v_u8m1((uchar *)ptr0, 8))); \ + res1 = vreinterpret_v_u##elemsize##m1_##len(vreinterpret_v_u8m1_u##elemsize##m1(vle8_v_u8m1((uchar *)ptr1, 8))); \ + res = vslideup_vx_##len(res, res1, hnum, num); \ + return _Tpvec(res); } \ +inline _Tpvec v_load_low(const _Tp* ptr) \ +{ return _Tpvec(vreinterpret_v_u##elemsize##m1_##len(vreinterpret_v_u8m1_u##elemsize##m1(vle8_v_u8m1((uchar *)ptr, 8)))); }\ +inline _Tpvec v_load_aligned(const _Tp* ptr) \ +{ return _Tpvec(vreinterpret_v_u##elemsize##m1_##len(vreinterpret_v_u8m1_u##elemsize##m1(vle8_v_u8m1((uchar *)ptr, 16)))); } \ +inline _Tpvec v_load(const _Tp* ptr) \ +{ return _Tpvec(vle##elemsize##_v_##len(ptr, num)); } \ +inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ +{ vse8_v_u8m1((uchar *)ptr, vreinterpret_v_u##elemsize##m1_u8m1(vreinterpret_v_##len##_u##elemsize##m1(a.val)), 8);}\ +inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ +{ \ + _Tp2##_t a0 = vundefined_##len(); \ + a0 = vslidedown_vx_##len(a0, a.val, hnum, num); \ + vse8_v_u8m1((uchar *)ptr, vreinterpret_v_u##elemsize##m1_u8m1(vreinterpret_v_##len##_u##elemsize##m1(a0)), 8);}\ +inline void v_store(_Tp* ptr, const _Tpvec& a) \ +{ vse##elemsize##_v_##len(ptr, a.val, num); } \ +inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ +{ vse8_v_u8m1((uchar *)ptr, vreinterpret_v_u##elemsize##m1_u8m1(vreinterpret_v_##len##_u##elemsize##m1(a.val)), 16); } \ +inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ +{ vse8_v_u8m1((uchar *)ptr, vreinterpret_v_u##elemsize##m1_u8m1(vreinterpret_v_##len##_u##elemsize##m1(a.val)), 16); } \ +inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ +{ vse8_v_u8m1((uchar *)ptr, vreinterpret_v_u##elemsize##m1_u8m1(vreinterpret_v_##len##_u##elemsize##m1(a.val)), 16); } +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_FLOAT_OP(v_float32x4, float, vfloat32m1, f32m1, 2, 4, 32) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_FLOAT_OP(v_float64x2, double, vfloat64m1, f64m1, 1, 2, 64) + +#else + +#define OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(_Tpvec, _Tp, _Tp2, len, hnum, num, elemsize) \ +inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ +{ \ + _Tp2##_t res, res1; \ + res = vle##elemsize##_v_##len(ptr0, hnum); \ + res1 = vle##elemsize##_v_##len(ptr1, hnum); \ + res = vslideup_vx_##len(res, res1, hnum, num); \ + return _Tpvec(res); } \ +inline _Tpvec v_load_low(const _Tp* ptr) \ +{ return _Tpvec(vle##elemsize##_v_##len(ptr, hnum)); }\ +inline _Tpvec v_load_aligned(const _Tp* ptr) \ +{ return _Tpvec(vle##elemsize##_v_##len(ptr, num)); } \ +inline _Tpvec v_load(const _Tp* ptr) \ +{ return _Tpvec((_Tp2##_t)vle##elemsize##_v_##len((const _Tp *)ptr, num)); } \ +inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ +{ vse##elemsize##_v_##len(ptr, a.val, hnum);}\ +inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ +{ \ + _Tp2##_t a0; \ + a0 = vslidedown_vx_##len(a0, a.val, hnum, num); \ + vse##elemsize##_v_##len(ptr, a0, hnum);}\ +inline void v_store(_Tp* ptr, const _Tpvec& a) \ +{ vse##elemsize##_v_##len(ptr, a.val, num); } \ +inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ +{ vse##elemsize##_v_##len(ptr, a.val, num); } \ +inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ +{ vse##elemsize##_v_##len(ptr, a.val, num); } \ +inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ +{ vse##elemsize##_v_##len(ptr, a.val, num); } + +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint8x16, uchar, vuint8m1, u8m1, 8, 16, 8) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int8x16, schar, vint8m1, i8m1, 8, 16, 8) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint16x8, ushort, vuint16m1, u16m1, 4, 8, 16) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int16x8, short, vint16m1, i16m1, 4, 8, 16) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint32x4, unsigned, vuint32m1, u32m1, 2, 4, 32) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int32x4, int, vint32m1, i32m1, 2, 4, 32) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint64x2, unsigned long, vuint64m1, u64m1, 1, 2, 64) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int64x2, long, vint64m1, i64m1, 1, 2, 64) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_float32x4, float, vfloat32m1, f32m1, 2, 4, 32) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_float64x2, double, vfloat64m1, f64m1, 1, 2, 64) + +#endif + +////////////// Lookup table access //////////////////// + +inline v_int8x16 v_lut(const schar* tab, const int* idx) +{ +#if 0 + schar CV_DECL_ALIGNED(32) elems[16] = + { + tab[idx[ 0]], + tab[idx[ 1]], + tab[idx[ 2]], + tab[idx[ 3]], + tab[idx[ 4]], + tab[idx[ 5]], + tab[idx[ 6]], + tab[idx[ 7]], + tab[idx[ 8]], + tab[idx[ 9]], + tab[idx[10]], + tab[idx[11]], + tab[idx[12]], + tab[idx[13]], + tab[idx[14]], + tab[idx[15]] + }; + return v_int8x16(vle8_v_i8m1(elems, 16)); +#else +#if __riscv_v == 7000 + return v_int8x16(vnclip_wx_i8m1(vnclip_wx_i16m2(vlxb_v_i32m4((const int *)tab, vle32_v_u32m4((unsigned int *)idx, 16), 16), 0, 16), 0, 16)); +#else + return v_int8x16(vloxei32_v_i8m1(tab, vle32_v_u32m4((unsigned int *)idx, 16), 16)); +#endif +#endif +} + +inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx){ +#if 0 + schar CV_DECL_ALIGNED(32) elems[16] = + { + tab[idx[0]], + tab[idx[0] + 1], + tab[idx[1]], + tab[idx[1] + 1], + tab[idx[2]], + tab[idx[2] + 1], + tab[idx[3]], + tab[idx[3] + 1], + tab[idx[4]], + tab[idx[4] + 1], + tab[idx[5]], + tab[idx[5] + 1], + tab[idx[6]], + tab[idx[6] + 1], + tab[idx[7]], + tab[idx[7] + 1] + }; + return v_int8x16(vle8_v_i8m1(elems, 16)); +#else + vuint32m4_t seq, index; + vuint32m4_t vidx = vle32_v_u32m4((unsigned int *)idx, 8); + seq = vid_v_u32m4(16); + index = vsrl_vx_u32m4(seq, 1, 16); + vidx = vrgather_vv_u32m4(vidx, index, 16); + index = vadd_vv_u32m4(vand_vx_u32m4(seq, 1, 16), vidx, 16); +#if __riscv_v == 7000 + return v_int8x16(vnclip_wx_i8m1(vnclip_wx_i16m2(vlxb_v_i32m4((const int *)tab, index, 16), 0, 16), 0, 16)); +#else + return v_int8x16(vloxei32_v_i8m1(tab, index, 16)); +#endif +#endif +} +inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) +{ +#if 0 + schar CV_DECL_ALIGNED(32) elems[16] = + { + tab[idx[0]], + tab[idx[0] + 1], + tab[idx[0] + 2], + tab[idx[0] + 3], + tab[idx[1]], + tab[idx[1] + 1], + tab[idx[1] + 2], + tab[idx[1] + 3], + tab[idx[2]], + tab[idx[2] + 1], + tab[idx[2] + 2], + tab[idx[2] + 3], + tab[idx[3]], + tab[idx[3] + 1], + tab[idx[3] + 2], + tab[idx[3] + 3] + }; + return v_int8x16(vle8_v_i8m1(elems, 16)); +#else + vuint32m4_t seq, index; + vuint32m4_t vidx = vle32_v_u32m4((unsigned int *)idx, 4); + seq = vid_v_u32m4(16); + index = vsrl_vx_u32m4(seq, 2, 16); + vidx = vrgather_vv_u32m4(vidx, index, 16); + seq = vset_v_u32m1_u32m4(seq, 1, vget_v_u32m4_u32m1(seq, 0)); + seq = vset_v_u32m1_u32m4(seq, 2, vget_v_u32m4_u32m1(seq, 0)); + seq = vset_v_u32m1_u32m4(seq, 3, vget_v_u32m4_u32m1(seq, 0)); + index = vadd_vv_u32m4(seq, vidx, 16); +#if __riscv_v == 7000 + return v_int8x16(vnclip_wx_i8m1(vnclip_wx_i16m2(vlxb_v_i32m4((const int *)tab, index, 16), 0, 16), 0, 16)); +#else + return v_int8x16(vloxei32_v_i8m1(tab, index, 16)); +#endif +#endif +} + +inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((schar*)tab, idx)); } +inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((schar*)tab, idx)); } +inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((schar*)tab, idx)); } + +inline v_int16x8 v_lut(const short* tab, const int* idx) +{ +#if 0 + short CV_DECL_ALIGNED(32) elems[8] = + { + tab[idx[0]], + tab[idx[1]], + tab[idx[2]], + tab[idx[3]], + tab[idx[4]], + tab[idx[5]], + tab[idx[6]], + tab[idx[7]] + }; + return v_int16x8(vle16_v_i16m1(elems, 8)); +#else +#if __riscv_v == 7000 + return v_int16x8(vnclip_wx_i16m1(vlxh_v_i32m2((const int *)tab, vsll_vx_u32m2(vle32_v_u32m2((unsigned int *)idx, 8), 1, 8), 8), 0, 8)); +#else + return v_int16x8(vloxei32_v_i16m1(tab, vsll_vx_u32m2(vle32_v_u32m2((unsigned int *)idx, 8), 1, 8), 8)); +#endif +#endif +} +inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) +{ +#if 0 + short CV_DECL_ALIGNED(32) elems[8] = + { + tab[idx[0]], + tab[idx[0] + 1], + tab[idx[1]], + tab[idx[1] + 1], + tab[idx[2]], + tab[idx[2] + 1], + tab[idx[3]], + tab[idx[3] + 1] + }; + return v_int16x8(vle16_v_i16m1(elems, 8)); +#else + vuint32m2_t seq, index; + vuint32m2_t vidx = vle32_v_u32m2((unsigned int *)idx, 4); + seq = vid_v_u32m2(8); + index = vsrl_vx_u32m2(seq, 1, 8); + vidx = vrgather_vv_u32m2(vidx, index, 8); + index = vsll_vx_u32m2(vadd_vv_u32m2(vand_vx_u32m2(seq, 1, 8), vidx, 8), 1, 8); +#if __riscv_v == 7000 + return v_int16x8(vnclip_wx_i16m1(vlxh_v_i32m2((const int *)tab, index, 8), 0, 8)); +#else + return v_int16x8(vloxei32_v_i16m1(tab, index, 8)); +#endif +#endif +} +inline v_int16x8 v_lut_quads(const short* tab, const int* idx) +{ +#if 0 + short CV_DECL_ALIGNED(32) elems[8] = + { + tab[idx[0]], + tab[idx[0] + 1], + tab[idx[0] + 2], + tab[idx[0] + 3], + tab[idx[1]], + tab[idx[1] + 1], + tab[idx[1] + 2], + tab[idx[1] + 3] + }; + return v_int16x8(vle16_v_i16m1(elems, 8)); +#else + vuint32m2_t seq, index; + vuint32m2_t vidx = vle32_v_u32m2((unsigned int *)idx, 2); + seq = vid_v_u32m2(8); + index = vsrl_vx_u32m2(seq, 2, 8); + vidx = vrgather_vv_u32m2(vidx, index, 8); + seq = vset_v_u32m1_u32m2(seq, 1, vget_v_u32m2_u32m1(seq, 0)); + index = vsll_vx_u32m2(vadd_vv_u32m2(seq, vidx, 8), 1, 8); +#if __riscv_v == 7000 + return v_int16x8(vnclip_wx_i16m1(vlxh_v_i32m2((const int *)tab, index, 8), 0, 8)); +#else + return v_int16x8(vloxei32_v_i16m1(tab, index, 8)); +#endif +#endif +} +inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((short*)tab, idx)); } +inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((short*)tab, idx)); } +inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((short*)tab, idx)); } + +inline v_int32x4 v_lut(const int* tab, const int* idx) +{ +#if 0 + int CV_DECL_ALIGNED(32) elems[4] = + { + tab[idx[0]], + tab[idx[1]], + tab[idx[2]], + tab[idx[3]] + }; + return v_int32x4(vle32_v_i32m1(elems, 4)); +#else + return v_int32x4(vloxei32_v_i32m1(tab, vsll_vx_u32m1(vle32_v_u32m1((unsigned int *)idx, 4), 2, 4), 4)); +#endif +} +inline v_int32x4 v_lut_pairs(const int* tab, const int* idx) +{ +#if 0 + int CV_DECL_ALIGNED(32) elems[4] = + { + tab[idx[0]], + tab[idx[0] + 1], + tab[idx[1]], + tab[idx[1] + 1] + }; + return v_int32x4(vle32_v_i32m1(elems, 4)); +#else + vuint32m1_t seq, index; + vuint32m1_t vidx = vle32_v_u32m1((unsigned int *)idx, 2); + seq = vid_v_u32m1(4); + index = vsrl_vx_u32m1(seq, 1, 4); + vidx = vrgather_vv_u32m1(vidx, index, 4); + index = vsll_vx_u32m1(vadd_vv_u32m1(vand_vx_u32m1(seq, 1, 4), vidx, 4), 2, 4); + return v_int32x4(vloxei32_v_i32m1(tab, index, 4)); +#endif +} +inline v_int32x4 v_lut_quads(const int* tab, const int* idx) +{ + return v_int32x4(vle32_v_i32m1(tab+idx[0], 4)); +} +inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((int*)tab, idx)); } +inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((int*)tab, idx)); } +inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((int*)tab, idx)); } + +inline v_int64x2 v_lut(const int64_t* tab, const int* idx) +{ + //vint64m1_t res = {tab[idx[0]], tab[idx[1]]}; + return v_int64x2(vloxei64_v_i64m1(tab, vsll_vx_u64m1(vget_v_u64m2_u64m1(vwaddu_vx_u64m2(vle32_v_u32m1((uint32_t*)idx, 2), 0, 2), 0), 3, 2), 2)); +} +inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) +{ + return v_int64x2(vle64_v_i64m1(tab+idx[0], 2)); +} + +inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) +{ + //vuint64m1_t res = {tab[idx[0]], tab[idx[1]]}; + return v_uint64x2(vloxei64_v_u64m1(tab, vsll_vx_u64m1(vget_v_u64m2_u64m1(vwaddu_vx_u64m2(vle32_v_u32m1((uint32_t*)idx, 2), 0, 2), 0), 3, 2), 2)); +} +inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) +{ + return v_uint64x2(vle64_v_u64m1(tab+idx[0], 2)); +} + +inline v_float32x4 v_lut(const float* tab, const int* idx) +{ +#if 0 + float CV_DECL_ALIGNED(32) elems[4] = + { + tab[idx[0]], + tab[idx[1]], + tab[idx[2]], + tab[idx[3]] + }; + return v_float32x4(vle32_v_f32m1(elems, 4)); +#else + return v_float32x4(vloxei32_v_f32m1(tab, vsll_vx_u32m1(vle32_v_u32m1((unsigned int *)idx, 4), 2, 4), 4)); +#endif +} +inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) +{ +#if 0 + float CV_DECL_ALIGNED(32) elems[4] = + { + tab[idx[0]], + tab[idx[0]+1], + tab[idx[1]], + tab[idx[1]+1] + }; + return v_float32x4(vle32_v_f32m1(elems, 4)); +#else + vuint32m1_t seq, index; + vuint32m1_t vidx = vle32_v_u32m1((unsigned int *)idx, 2); + seq = vid_v_u32m1(4); + index = vsrl_vx_u32m1(seq, 1, 4); + vidx = vrgather_vv_u32m1(vidx, index, 4); + index = vsll_vx_u32m1(vadd_vv_u32m1(vand_vx_u32m1(seq, 1, 4), vidx, 4), 2, 4); + return v_float32x4(vloxei32_v_f32m1(tab, index, 4)); +#endif +} +inline v_float32x4 v_lut_quads(const float* tab, const int* idx) +{ + return v_float32x4(vle32_v_f32m1(tab + idx[0], 4)); +} +inline v_float64x2 v_lut(const double* tab, const int* idx) +{ + //vfloat64m1_t res = {tab[idx[0]], tab[idx[1]]}; + return v_float64x2(vloxei64_v_f64m1(tab, vsll_vx_u64m1(vget_v_u64m2_u64m1(vwaddu_vx_u64m2(vle32_v_u32m1((uint32_t*)idx, 2), 0, 2), 0), 3, 2), 2)); +} +inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) +{ + return v_float64x2(vle64_v_f64m1(tab+idx[0], 2)); +} + +inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) +{ + /*int CV_DECL_ALIGNED(32) elems[4] = + { + tab[idxvec.val[0]], + tab[idxvec.val[1]], + tab[idxvec.val[2]], + tab[idxvec.val[3]] + };*/ + return v_int32x4(vloxei32_v_i32m1(tab, vsll_vx_u32m1(vreinterpret_v_i32m1_u32m1(idxvec.val), 2, 4), 4)); +} + +inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) +{ + /*unsigned CV_DECL_ALIGNED(32) elems[4] = + { + tab[idxvec.val[0]], + tab[idxvec.val[1]], + tab[idxvec.val[2]], + tab[idxvec.val[3]] + };*/ + return v_uint32x4(vloxei32_v_u32m1(tab, vsll_vx_u32m1(vreinterpret_v_i32m1_u32m1(idxvec.val), 2, 4), 4)); +} + +inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) +{ + /*float CV_DECL_ALIGNED(32) elems[4] = + { + tab[idxvec.val[0]], + tab[idxvec.val[1]], + tab[idxvec.val[2]], + tab[idxvec.val[3]] + };*/ + return v_float32x4(vloxei32_v_f32m1(tab, vsll_vx_u32m1(vreinterpret_v_i32m1_u32m1(idxvec.val), 2, 4), 4)); +} +inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) +{ + //vfloat64m1_t res = {tab[idxvec.val[0]], tab[idxvec.val[1]]}; + return v_float64x2(vloxei64_v_f64m1(tab, vsll_vx_u64m1(vreinterpret_v_i64m1_u64m1(vget_v_i64m2_i64m1(vwadd_vx_i64m2(idxvec.val, 0, 2), 0)), 3, 2), 2)); +} +inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) +{ + vint32m1_t index = vmul_vx_i32m1(idxvec.val, 4, 4); + //vint32m1_t index_y = vadd_vx_i32m1(index_x, 4, 4); + + //x.val = vlxe_v_f32m1(tab, index_x, 4); + //y.val = vlxe_v_f32m1(tab, index_y, 4); + vloxseg2ei32_v_f32m1(&x.val, &y.val, tab, vreinterpret_v_i32m1_u32m1(index), 4); +} + +inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) +{ + int CV_DECL_ALIGNED(32) idx[4]; + v_store_aligned(idx, idxvec); + + x = v_float64x2(tab[idx[0]], tab[idx[1]]); + y = v_float64x2(tab[idx[0]+1], tab[idx[1]+1]); +} + +#define OPENCV_HAL_IMPL_RISCVV_PACKS(_Tp, _Tp2, _T2, num2, _T1, num, intrin, shr, _Type, elemsize) \ +inline v_##_Tp##x##num v_pack(const v_##_Tp2##x##num2& a, const v_##_Tp2##x##num2& b) \ +{ \ + v##_Tp2##m2_t tmp = vundefined_##_T2##m2(); \ + tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 0, a.val); \ + tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 1, b.val); \ + return v_##_Tp##x##num(shr##_##_T1##m1(tmp, 0, num)); \ +}\ +template inline \ +v_##_Tp##x##num v_rshr_pack(const v_##_Tp2##x##num2& a, const v_##_Tp2##x##num2& b) \ +{ \ + v##_Tp2##m2_t tmp = vundefined_##_T2##m2(); \ + tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 0, a.val); \ + tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 1, b.val); \ + return v_##_Tp##x##num(intrin##_##_T1##m1(tmp, n, num)); \ +}\ +inline void v_pack_store(_Type* ptr, const v_##_Tp2##x##num2& a) \ +{ \ + v##_Tp2##m2_t tmp = vundefined_##_T2##m2(); \ + tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 0, a.val); \ + tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 1, vmv_v_x_##_T2##m1(0, num2)); \ + asm("" ::: "memory"); \ + vse##elemsize##_v_##_T1##m1(ptr, shr##_##_T1##m1(tmp, 0, num), num2); \ +}\ +template inline \ +void v_rshr_pack_store(_Type* ptr, const v_##_Tp2##x##num2& a) \ +{ \ + v##_Tp2##m2_t tmp = vundefined_##_T2##m2(); \ + tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 0, a.val); \ + tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 1, vmv_v_x_##_T2##m1(0, num2)); \ + vse##elemsize##_v_##_T1##m1(ptr, intrin##_##_T1##m1(tmp, n, num), num2); \ +} +OPENCV_HAL_IMPL_RISCVV_PACKS(int8, int16, i16, 8, i8, 16, vnclip_wx, vnclip_wx, signed char, 8) +OPENCV_HAL_IMPL_RISCVV_PACKS(int16, int32, i32, 4, i16, 8, vnclip_wx, vnclip_wx, signed short, 16) +OPENCV_HAL_IMPL_RISCVV_PACKS(int32, int64, i64, 2, i32, 4, vnclip_wx, vnsra_wx, int, 32) +OPENCV_HAL_IMPL_RISCVV_PACKS(uint8, uint16, u16, 8, u8, 16, vnclipu_wx, vnclipu_wx, unsigned char, 8) +OPENCV_HAL_IMPL_RISCVV_PACKS(uint16, uint32, u32, 4, u16, 8, vnclipu_wx, vnclipu_wx, unsigned short, 16) +OPENCV_HAL_IMPL_RISCVV_PACKS(uint32, uint64, u64, 2, u32, 4, vnclipu_wx, vnsrl_wx, unsigned int, 32) + +// pack boolean +inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) +{ + vuint16m2_t tmp = vundefined_u16m2(); \ + tmp = vset_v_u16m1_u16m2(tmp, 0, a.val); \ + tmp = vset_v_u16m1_u16m2(tmp, 1, b.val); \ + return v_uint8x16(vnsrl_wx_u8m1(tmp, 0, 16)); +} + +inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, + const v_uint32x4& c, const v_uint32x4& d) +{ + vuint32m4_t vabcd = vundefined_u32m4(); \ + vuint16m2_t v16 = vundefined_u16m2(); \ + vabcd = vset_v_u32m1_u32m4(vabcd, 0, a.val); \ + vabcd = vset_v_u32m1_u32m4(vabcd, 1, b.val); \ + vabcd = vset_v_u32m1_u32m4(vabcd, 2, c.val); \ + vabcd = vset_v_u32m1_u32m4(vabcd, 3, d.val); \ + v16 = vnsrl_wx_u16m2(vabcd, 0, 16); + return v_uint8x16(vnsrl_wx_u8m1(v16, 0, 16)); +} + +inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, + const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, + const v_uint64x2& g, const v_uint64x2& h) +{ + vuint64m8_t v64 = vundefined_u64m8(); \ + vuint32m4_t v32 = vundefined_u32m4(); \ + vuint16m2_t v16 = vundefined_u16m2(); \ + v64 = vset_v_u64m1_u64m8(v64, 0, a.val); \ + v64 = vset_v_u64m1_u64m8(v64, 1, b.val); \ + v64 = vset_v_u64m1_u64m8(v64, 2, c.val); \ + v64 = vset_v_u64m1_u64m8(v64, 3, d.val); \ + v64 = vset_v_u64m1_u64m8(v64, 4, e.val); \ + v64 = vset_v_u64m1_u64m8(v64, 5, f.val); \ + v64 = vset_v_u64m1_u64m8(v64, 6, g.val); \ + v64 = vset_v_u64m1_u64m8(v64, 7, h.val); \ + v32 = vnsrl_wx_u32m4(v64, 0, 16); + v16 = vnsrl_wx_u16m2(v32, 0, 16); + return v_uint8x16(vnsrl_wx_u8m1(v16, 0, 16)); +} + +//inline v_uint8x16 v_pack_u(const v_int16x8& a, const v_int16x8& b) \ +//{ \ +// int16xm2_u tmp; \ +// tmp.m1[0] = (vint16m1_t)a.val; \ +// tmp.m1[1] = (vint16m1_t)b.val; \ +// e8xm1_t mask = (e8xm1_t)vmsge_vx_e16xm2_i16m2(tmp.v, 0, 16);\ +// return v_uint8x16(vnclipuvi_mask_u8m1_u16m2(vmv_v_x_u8m1(0, 16), (vuint16m2_t)tmp.v, 0, mask, 16)); +//} + +#define OPENCV_HAL_IMPL_RISCVV_PACK_U(tp1, num1, tp2, num2, _Tp) \ +inline v_uint##tp1##x##num1 v_pack_u(const v_int##tp2##x##num2& a, const v_int##tp2##x##num2& b) \ +{ \ + vint##tp2##m2_t tmp = vundefined_##i##tp2##m2(); \ + tmp = vset_v_##i##tp2##m1_##i##tp2##m2(tmp, 0, a.val); \ + tmp = vset_v_##i##tp2##m1_##i##tp2##m2(tmp, 1, b.val); \ + vint##tp2##m2_t val = vmax_vx_i##tp2##m2(tmp, 0, num1);\ + return v_uint##tp1##x##num1(vnclipu_wx_u##tp1##m1(vreinterpret_v_i##tp2##m2_u##tp2##m2(val), 0, num1)); \ +} \ +inline void v_pack_u_store(_Tp* ptr, const v_int##tp2##x##num2& a) \ +{ \ + vint##tp2##m2_t tmp = vundefined_##i##tp2##m2(); \ + tmp = vset_v_##i##tp2##m1_##i##tp2##m2(tmp, 0, a.val); \ + vint##tp2##m2_t val = vmax_vx_i##tp2##m2(tmp, 0, num1);\ + return vse##tp1##_v_u##tp1##m1(ptr, vnclipu_wx_u##tp1##m1(vreinterpret_v_i##tp2##m2_u##tp2##m2(val), 0, num1), num2); \ +} \ +template inline \ +v_uint##tp1##x##num1 v_rshr_pack_u(const v_int##tp2##x##num2& a, const v_int##tp2##x##num2& b) \ +{ \ + vint##tp2##m2_t tmp = vundefined_##i##tp2##m2(); \ + tmp = vset_v_##i##tp2##m1_##i##tp2##m2(tmp, 0, a.val); \ + tmp = vset_v_##i##tp2##m1_##i##tp2##m2(tmp, 1, b.val); \ + vint##tp2##m2_t val = vmax_vx_i##tp2##m2(tmp, 0, num1);\ + return v_uint##tp1##x##num1(vnclipu_wx_u##tp1##m1(vreinterpret_v_i##tp2##m2_u##tp2##m2(val), n, num1)); \ +} \ +template inline \ +void v_rshr_pack_u_store(_Tp* ptr, const v_int##tp2##x##num2& a) \ +{ \ + vint##tp2##m2_t tmp = vundefined_##i##tp2##m2(); \ + tmp = vset_v_##i##tp2##m1_##i##tp2##m2(tmp, 0, a.val); \ + vint##tp2##m2_t val_ = vmax_vx_i##tp2##m2(tmp, 0, num1);\ + vuint##tp1##m1_t val = vnclipu_wx_u##tp1##m1(vreinterpret_v_i##tp2##m2_u##tp2##m2(val_), n, num1); \ + return vse##tp1##_v_u##tp1##m1(ptr, val, num2);\ +} +OPENCV_HAL_IMPL_RISCVV_PACK_U(8, 16, 16, 8, unsigned char ) +OPENCV_HAL_IMPL_RISCVV_PACK_U(16, 8, 32, 4, unsigned short) + + +// saturating multiply 8-bit, 16-bit +#define OPENCV_HAL_IMPL_RISCVV_MUL_SAT(_Tpvec, num, mul, cvt) \ + inline _Tpvec v_mul(const _Tpvec& a, const _Tpvec& b) \ + { \ + auto res = mul(a.val, b.val, num); \ + return _Tpvec(cvt(res, 0, num)); \ + } + +OPENCV_HAL_IMPL_RISCVV_MUL_SAT(v_int8x16, 16, vwmul_vv_i16m2, vnclip_wx_i8m1) +OPENCV_HAL_IMPL_RISCVV_MUL_SAT(v_uint8x16, 16, vwmulu_vv_u16m2, vnclipu_wx_u8m1) +OPENCV_HAL_IMPL_RISCVV_MUL_SAT(v_int16x8, 32, vwmul_vv_i32m2, vnclip_wx_i16m1) +OPENCV_HAL_IMPL_RISCVV_MUL_SAT(v_uint16x8, 32, vwmulu_vv_u32m2, vnclipu_wx_u16m1) + + +static const signed char popCountTable[256] = +{ + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, +}; + +inline vuint8m1_t vcnt_u8(vuint8m1_t val){ +#if __riscv_v == 7000 + vuint8m1_t v0 = vand_vx_u8m1(val, 1, 16); + return vadd_vv_u8m1(vloxei8_v_u8m1((unsigned char*)popCountTable, vsrl_vx_u8m1(val, 1, 16), 16), v0, 16); +#else + return vloxei8_v_u8m1((unsigned char*)popCountTable, val, 16); +#endif +} + +inline v_uint8x16 +v_popcount(const v_uint8x16& a) +{ + return v_uint8x16(vcnt_u8(a.val)); +} + +inline v_uint8x16 +v_popcount(const v_int8x16& a) +{ + return v_uint8x16(vcnt_u8(vreinterpret_v_i8m1_u8m1(a.val))); +} + +inline v_uint16x8 +v_popcount(const v_uint16x8& a) +{ + vuint8m1_t tmp = vcnt_u8(vreinterpret_v_u16m1_u8m1(a.val)); + vuint8m1_t seq = vid_v_u8m1(8); + vuint8m1_t index = vsll_vx_u8m1(seq, 1, 8); + return v_uint16x8(vget_v_u16m2_u16m1(vwaddu_vv_u16m2(vrgather_vv_u8m1(tmp, index, 8), vrgather_vv_u8m1(tmp, vadd_vx_u8m1(index, 1, 8), 8), 8), 0)); +} + +inline v_uint16x8 +v_popcount(const v_int16x8& a) +{ + vuint8m1_t tmp = vcnt_u8(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i16m1_i8m1(a.val))); + vuint8m1_t seq = vid_v_u8m1(8); + vuint8m1_t index = vsll_vx_u8m1(seq, 1, 8); + return v_uint16x8(vget_v_u16m2_u16m1(vwaddu_vv_u16m2(vrgather_vv_u8m1(tmp, index, 8), vrgather_vv_u8m1(tmp, vadd_vx_u8m1(index, 1, 8), 8), 8), 0)); +} + +inline v_uint32x4 +v_popcount(const v_uint32x4& a) +{ + vuint8m1_t tmp = vcnt_u8(vreinterpret_v_u32m1_u8m1(a.val)); + vuint8m1_t seq = vid_v_u8m1(8); + vuint8m1_t index = vsll_vx_u8m1(seq, 1, 8); + vuint8m1_t sum = vadd_vv_u8m1(vrgather_vv_u8m1(tmp, index, 8), vrgather_vv_u8m1(tmp, vadd_vx_u8m1(index, 1, 8), 8), 8); + return v_uint32x4(vget_v_u32m4_u32m1(vwaddu_vx_u32m4(vwaddu_vv_u16m2(vrgather_vv_u8m1(sum, index, 4), vrgather_vv_u8m1(sum, vadd_vx_u8m1(index, 1, 4), 4), 4), 0, 4), 0)); +} + +inline v_uint32x4 +v_popcount(const v_int32x4& a) +{ + vuint8m1_t tmp = vcnt_u8(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i32m1_i8m1(a.val))); + vuint8m1_t seq = vid_v_u8m1(8); + vuint8m1_t index = vsll_vx_u8m1(seq, 1, 8); + vuint8m1_t sum = vadd_vv_u8m1(vrgather_vv_u8m1(tmp, index, 8), vrgather_vv_u8m1(tmp, vadd_vx_u8m1(index, 1, 8), 8), 8); + return v_uint32x4(vget_v_u32m4_u32m1(vwaddu_vx_u32m4(vwaddu_vv_u16m2(vrgather_vv_u8m1(sum, index, 4), vrgather_vv_u8m1(sum, vadd_vx_u8m1(index, 1, 4), 4), 4), 0, 4), 0)); +} + +inline v_uint64x2 +v_popcount(const v_uint64x2& a) +{ + vuint8m1_t tmp = vcnt_u8(vreinterpret_v_u64m1_u8m1(a.val)); + vuint16m2_t tmp16 = vwaddu_vx_u16m2(tmp, 0, 16); + vuint16m1_t res1 = vundefined_u16m1(); + vuint16m1_t res2 = vundefined_u16m1(); + res1 = vredsum_vs_u16m1_u16m1(res1, vget_v_u16m2_u16m1(tmp16, 0), vmv_v_x_u16m1(0, 8), 8); + res2 = vredsum_vs_u16m1_u16m1(res2, vget_v_u16m2_u16m1(tmp16, 1), vmv_v_x_u16m1(0, 8), 8); + return v_uint64x2((unsigned long)vmv_x_s_u16m1_u16(res1), (unsigned long)vmv_x_s_u16m1_u16(res2)); +} + +inline v_uint64x2 +v_popcount(const v_int64x2& a) +{ + vuint8m1_t tmp = vcnt_u8(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i64m1_i8m1(a.val))); + vuint16m2_t tmp16 = vwaddu_vx_u16m2(tmp, 0, 16); + vuint16m1_t res1 = vundefined_u16m1(), res2 = vundefined_u16m1(); + res1 = vredsum_vs_u16m1_u16m1(res1, vget_v_u16m2_u16m1(tmp16, 0), vmv_v_x_u16m1(0, 8), 8); + res2 = vredsum_vs_u16m1_u16m1(res2, vget_v_u16m2_u16m1(tmp16, 1), vmv_v_x_u16m1(0, 8), 8); + return v_uint64x2((unsigned long)vmv_x_s_u16m1_u16(res1), (unsigned long)vmv_x_s_u16m1_u16(res2)); +} + +#define SMASK 1, 2, 4, 8, 16, 32, 64, 128 +inline int v_signmask(const v_uint8x16& a) +{ + vuint16m1_t res = vundefined_u16m1(); + vuint8m1_t id = vid_v_u8m1(16); + vuint16m2_t num = vsll_vv_u16m2(vmv_v_x_u16m2(1, 16), vwaddu_vx_u16m2(id, 0, 16), 16); + vuint8m1_t t0 = vsrl_vx_u8m1(a.val, 7, 16); + vbool8_t mask = vmseq_vx_u8m1_b8(t0, 1, 16); + res = vredsum_vs_u16m2_u16m1_m(mask, res, num, vmv_v_x_u16m1(0, 8), 16); + return vmv_x_s_u16m1_u16(res); +} +inline int v_signmask(const v_int8x16& a) +{ + vuint16m1_t res = vundefined_u16m1(); + vuint8m1_t id = vid_v_u8m1(16); + vuint16m2_t num = vsll_vv_u16m2(vmv_v_x_u16m2(1, 16), vwaddu_vx_u16m2(id, 0, 16), 16); + vbool8_t mask = vmslt_vx_i8m1_b8(a.val, 0, 16); + res = vredsum_vs_u16m2_u16m1_m(mask, res, num, vmv_v_x_u16m1(0, 8), 16); + return vmv_x_s_u16m1_u16(res); +} + +inline int v_signmask(const v_int16x8& a) +{ + vuint16m1_t res = vundefined_u16m1(); + vuint16m1_t id = vid_v_u16m1(8); + vuint16m1_t num = vsll_vv_u16m1(vmv_v_x_u16m1(1, 8), id, 8); + vbool16_t mask = vmslt_vx_i16m1_b16(a.val, 0, 8); + res = vredsum_vs_u16m1_u16m1_m(mask, res, num, vmv_v_x_u16m1(0, 8), 16); + return vmv_x_s_u16m1_u16(res); +} +inline int v_signmask(const v_uint16x8& a) +{ + vuint16m1_t res = vundefined_u16m1(); + vuint16m1_t id = vid_v_u16m1(8); + vuint16m1_t num = vsll_vv_u16m1(vmv_v_x_u16m1(1, 8), id, 8); + vuint16m1_t t0 = vsrl_vx_u16m1(a.val, 15, 8); + vbool16_t mask = vmseq_vx_u16m1_b16(t0, 1, 8); + res = vredsum_vs_u16m1_u16m1_m(mask, res, num, vmv_v_x_u16m1(0, 8), 8); + return vmv_x_s_u16m1_u16(res); +} +inline int v_signmask(const v_int32x4& a) +{ + vuint32m1_t res = vundefined_u32m1(); + vuint32m1_t id = vid_v_u32m1(4); + vuint32m1_t num = vsll_vv_u32m1(vmv_v_x_u32m1(1, 4), id, 4); + vbool32_t mask = vmslt_vx_i32m1_b32(a.val, 0, 4); + res = vredsum_vs_u32m1_u32m1_m(mask, res, num, vmv_v_x_u32m1(0, 4), 4); + return vmv_x_s_u32m1_u32(res); +} +inline int v_signmask(const v_uint32x4& a) +{ + vuint32m1_t res = vundefined_u32m1(); + vuint32m1_t id = vid_v_u32m1(4); + vuint32m1_t num = vsll_vv_u32m1(vmv_v_x_u32m1(1, 4), id, 4); + vuint32m1_t t0 = vsrl_vx_u32m1(a.val, 31, 4); + vbool32_t mask = vmseq_vx_u32m1_b32(t0, 1, 4); + res = vredsum_vs_u32m1_u32m1_m(mask, res, num, vmv_v_x_u32m1(0, 4), 4); + return vmv_x_s_u32m1_u32(res); +} +inline int v_signmask(const v_uint64x2& a) +{ + vuint64m1_t res = vundefined_u64m1(); + vuint64m1_t id = vid_v_u64m1(2); + vuint64m1_t num = vsll_vv_u64m1(vmv_v_x_u64m1(1, 2), id, 2); + vuint64m1_t t0 = vsrl_vx_u64m1(a.val, 63, 2); + vbool64_t mask = vmseq_vx_u64m1_b64(t0, 1, 2); + res = vredsum_vs_u64m1_u64m1_m(mask, res, num, vmv_v_x_u64m1(0, 2), 2); + return vmv_x_s_u64m1_u64(res); +} +inline int v_signmask(const v_int64x2& a) +{ return v_signmask(v_reinterpret_as_u64(a)); } +inline int v_signmask(const v_float64x2& a) +{ return v_signmask(v_reinterpret_as_u64(a)); } +inline int v_signmask(const v_float32x4& a) +{ + return v_signmask(v_reinterpret_as_u32(a)); + /* + vuint32m1_t res; + vuint32m1_t id = vid_v_u32m1(4); + vuint32m1_t num = vsll_vv_u32m1(vmv_v_x_u32m1(1, 4), id, 4); + vbool32_t mask = vmflt_vf_f32m1_b32(a.val, 0, 4); + res = vredsum_vs_u32m1_u32m1_m(mask, res, num, vmv_v_x_u32m1(0, 4), 4); + return vmv_x_s_u32m1_u32(res);*/ +} + +inline int v_scan_forward(const v_int8x16& a) { +int val = v_signmask(a); +if(val==0) return 0; +else return trailingZeros32(val); } +inline int v_scan_forward(const v_uint8x16& a) { +int val = v_signmask(a); +if(val==0) return 0; +else return trailingZeros32(val); } +inline int v_scan_forward(const v_int16x8& a) { +int val = v_signmask(a); +if(val==0) return 0; +else return trailingZeros32(val); } +inline int v_scan_forward(const v_uint16x8& a) { +int val = v_signmask(a); +if(val==0) return 0; +else return trailingZeros32(val); } +inline int v_scan_forward(const v_int32x4& a) { +int val = v_signmask(a); +if(val==0) return 0; +else return trailingZeros32(val); } +inline int v_scan_forward(const v_uint32x4& a) { +int val = v_signmask(a); +if(val==0) return 0; +else return trailingZeros32(val); } +inline int v_scan_forward(const v_float32x4& a) { +int val = v_signmask(a); +if(val==0) return 0; +else return trailingZeros32(val); } +inline int v_scan_forward(const v_int64x2& a) { +int val = v_signmask(a); +if(val==0) return 0; +else return trailingZeros32(val); } +inline int v_scan_forward(const v_uint64x2& a) { +int val = v_signmask(a); +if(val==0) return 0; +else return trailingZeros32(val); } + +#define OPENCV_HAL_IMPL_RISCVV_CHECK_ALLANY(_Tpvec, suffix, _T, shift, num, mask_b) \ +inline bool v_check_all(const v_##_Tpvec& a) \ +{ \ + suffix##m1_t v0 = vsrl_vx_##_T(vnot_v_##_T(a.val, num), shift, num); \ + return (vcpop_m_##mask_b(vmseq_vx_##_T##_##mask_b(v0, 1, num), num)) == 0; \ +} \ +inline bool v_check_any(const v_##_Tpvec& a) \ +{ \ + suffix##m1_t v0 = vsrl_vx_##_T(a.val, shift, num); \ + return (vcpop_m_##mask_b(vmseq_vx_##_T##_##mask_b(v0, 1, num), num)) != 0; \ +} + +OPENCV_HAL_IMPL_RISCVV_CHECK_ALLANY(uint8x16, vuint8, u8m1, 7, 16, b8) +OPENCV_HAL_IMPL_RISCVV_CHECK_ALLANY(uint16x8, vuint16, u16m1, 15, 8, b16) +OPENCV_HAL_IMPL_RISCVV_CHECK_ALLANY(uint32x4, vuint32, u32m1, 31, 4, b32) +OPENCV_HAL_IMPL_RISCVV_CHECK_ALLANY(uint64x2, vuint64, u64m1, 63, 2, b64) + +inline bool v_check_all(const v_int8x16& a) +{ return v_check_all(v_reinterpret_as_u8(a)); } +inline bool v_check_all(const v_int16x8& a) +{ return v_check_all(v_reinterpret_as_u16(a)); } +inline bool v_check_all(const v_int32x4& a) +{ return v_check_all(v_reinterpret_as_u32(a)); } +inline bool v_check_all(const v_float32x4& a) +{ return v_check_all(v_reinterpret_as_u32(a)); } +inline bool v_check_all(const v_int64x2& a) +{ return v_check_all(v_reinterpret_as_u64(a)); } +inline bool v_check_all(const v_float64x2& a) +{ return v_check_all(v_reinterpret_as_u64(a)); } + +inline bool v_check_any(const v_int8x16& a) +{ return v_check_any(v_reinterpret_as_u8(a)); } +inline bool v_check_any(const v_int16x8& a) +{ return v_check_any(v_reinterpret_as_u16(a)); } +inline bool v_check_any(const v_int32x4& a) +{ return v_check_any(v_reinterpret_as_u32(a)); } +inline bool v_check_any(const v_float32x4& a) +{ return v_check_any(v_reinterpret_as_u32(a)); } +inline bool v_check_any(const v_int64x2& a) +{ return v_check_any(v_reinterpret_as_u64(a)); } +inline bool v_check_any(const v_float64x2& a) +{ return v_check_any(v_reinterpret_as_u64(a)); } + +#define OPENCV_HAL_IMPL_RISCVV_SELECT(_Tpvec, suffix, _Tpvec2, num, mask_func) \ +inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(vmerge_vvm_##suffix(mask_func(mask.val, 0, num), b.val, a.val, num)); \ +} + +OPENCV_HAL_IMPL_RISCVV_SELECT(v_int8x16, i8m1, vbool8_t, 16, vmsne_vx_i8m1_b8) +OPENCV_HAL_IMPL_RISCVV_SELECT(v_int16x8, i16m1, vbool16_t, 8, vmsne_vx_i16m1_b16) +OPENCV_HAL_IMPL_RISCVV_SELECT(v_int32x4, i32m1, vbool32_t, 4, vmsne_vx_i32m1_b32) +OPENCV_HAL_IMPL_RISCVV_SELECT(v_uint8x16, u8m1, vbool8_t, 16, vmsne_vx_u8m1_b8) +OPENCV_HAL_IMPL_RISCVV_SELECT(v_uint16x8, u16m1, vbool16_t, 8, vmsne_vx_u16m1_b16) +OPENCV_HAL_IMPL_RISCVV_SELECT(v_uint32x4, u32m1, vbool32_t, 4, vmsne_vx_u32m1_b32) +inline v_float32x4 v_select(const v_float32x4& mask, const v_float32x4& a, const v_float32x4& b) +{ + return v_float32x4(vmerge_vvm_f32m1(vmfne_vf_f32m1_b32(mask.val, 0, 4), b.val, a.val, 4)); +} +inline v_float64x2 v_select(const v_float64x2& mask, const v_float64x2& a, const v_float64x2& b) +{ + return v_float64x2(vmerge_vvm_f64m1(vmfne_vf_f64m1_b64(mask.val, 0, 2), b.val, a.val, 2)); +} + +#define OPENCV_HAL_IMPL_RISCVV_EXPAND(add, _Tpvec, _Tpwvec, _Tp, _Tp1, num1, _Tp2, num2, _T1, _T2, num3) \ +inline void v_expand(const _Tpvec& a, v_##_Tpwvec& b0, v_##_Tpwvec& b1) \ +{ \ + _T1##_t b = vw##add##_vx_##_Tp2##m2(a.val, 0, num1); \ + b0.val = vget_v_##_Tp2##m2_##_Tp2##m1(b, 0); \ + b1.val = vget_v_##_Tp2##m2_##_Tp2##m1(b, 1); \ +} \ +inline v_##_Tpwvec v_expand_low(const _Tpvec& a) \ +{ \ + _T1##_t b = vw##add##_vx_##_Tp2##m2(a.val, 0, num2); \ + return v_##_Tpwvec(vget_v_##_Tp2##m2_##_Tp2##m1(b, 0)); \ +} \ +inline v_##_Tpwvec v_expand_high(const _Tpvec& a) \ +{ \ + _T1##_t b = vw##add##_vx_##_Tp2##m2(a.val, 0, num1); \ + return v_##_Tpwvec(vget_v_##_Tp2##m2_##_Tp2##m1(b, 1)); \ +} \ +inline v_##_Tpwvec v_load_expand(const _Tp* ptr) \ +{ \ + _T2##_t val = vle##num3##_v_##_Tp1(ptr, num2); \ + _T1##_t b = vw##add##_vx_##_Tp2##m2(val, 0, num2); \ + return v_##_Tpwvec(vget_v_##_Tp2##m2_##_Tp2##m1(b, 0)); \ +} + +OPENCV_HAL_IMPL_RISCVV_EXPAND(addu, v_uint8x16, uint16x8, uchar, u8m1, 16, u16, 8, vuint16m2, vuint8m1, 8) +OPENCV_HAL_IMPL_RISCVV_EXPAND(addu, v_uint16x8, uint32x4, ushort, u16m1, 8, u32, 4, vuint32m2, vuint16m1, 16) +OPENCV_HAL_IMPL_RISCVV_EXPAND(addu, v_uint32x4, uint64x2, uint, u32m1, 4, u64, 2, vuint64m2, vuint32m1, 32) +OPENCV_HAL_IMPL_RISCVV_EXPAND(add, v_int8x16, int16x8, schar, i8m1, 16, i16, 8, vint16m2, vint8m1, 8) +OPENCV_HAL_IMPL_RISCVV_EXPAND(add, v_int16x8, int32x4, short, i16m1, 8, i32, 4, vint32m2, vint16m1, 16) +OPENCV_HAL_IMPL_RISCVV_EXPAND(add, v_int32x4, int64x2, int, i32m1, 4, i64, 2, vint64m2, vint32m1, 32) + +inline v_uint32x4 v_load_expand_q(const uchar* ptr) +{ + vuint16m2_t b = vundefined_u16m2(); + vuint32m2_t c = vundefined_u32m2(); + vuint8m1_t val = vle8_v_u8m1(ptr, 4); \ + b = vwaddu_vv_u16m2(val, vmv_v_x_u8m1(0, 4), 4); \ + c = vwaddu_vv_u32m2(vget_v_u16m2_u16m1(b, 0), vmv_v_x_u16m1(0, 4), 4); \ + return v_uint32x4(vget_v_u32m2_u32m1(c, 0)); +} + +inline v_int32x4 v_load_expand_q(const schar* ptr) +{ + vint16m2_t b = vundefined_i16m2(); + vint32m2_t c = vundefined_i32m2(); + vint8m1_t val = vle8_v_i8m1(ptr, 4); \ + b = vwadd_vv_i16m2(val, vmv_v_x_i8m1(0, 4), 4); \ + c = vwadd_vv_i32m2(vget_v_i16m2_i16m1(b, 0), vmv_v_x_i16m1(0, 4), 4); \ + return v_int32x4(vget_v_i32m2_i32m1(c, 0)); +} +#define VITL_16 {0x11011000, 0x13031202, 0x15051404, 0x17071606, 0x19091808, 0x1B0B1A0A, 0x1D0D1C0C, 0x1F0F1E0E} +#define VITL_8 {0x00080000, 0x00090001, 0x000A0002, 0x000B0003, 0x000C0004, 0x000D0005, 0x000E0006, 0x000F0007} +#define VITL_4 {0x00000000, 0x00000004, 0x00000001, 0x00000005, 0x00000002, 0x00000006, 0x00000003, 0x00000007} +#define VITL_2 {0, 0, 2, 0, 1, 0, 3, 0} + +#define OPENCV_HAL_IMPL_RISCVV_UNPACKS(_Tpvec, _Tp, _T, _UTp, _UT, num, num2, len, numh, refunc) \ +inline void v_zip(const v_##_Tpvec& a0, const v_##_Tpvec& a1, v_##_Tpvec& b0, v_##_Tpvec& b1) \ +{ \ + v##_Tp##m2_t tmp = vundefined_##_T##m2();\ + tmp = vset_v_##_T##m1_##_T##m2(tmp, 0, a0.val); \ + tmp = vset_v_##_T##m1_##_T##m2(tmp, 1, a1.val); \ + unsigned mdata[] = VITL_##num; \ + vuint32m2_t mask = vle32_v_u32m2(mdata, 8); \ + tmp = (v##_Tp##m2_t)vrgather_vv_##_T##m2((v##_Tp##m2_t)tmp, refunc(mask), num2); \ + b0.val = vget_v_##_T##m2_##_T##m1(tmp, 0); \ + b1.val = vget_v_##_T##m2_##_T##m1(tmp, 1); \ +} \ +inline v_##_Tpvec v_combine_low(const v_##_Tpvec& a, const v_##_Tpvec& b) \ +{ \ + v##_Tp##m1_t b0 = vslideup_vx_##_T##m1_m(vmset_m_##len(num), a.val, b.val, numh, num); \ + return v_##_Tpvec(b0);\ +} \ +inline v_##_Tpvec v_combine_high(const v_##_Tpvec& a, const v_##_Tpvec& b) \ +{ \ + v##_Tp##m1_t b0 = vundefined_##_T##m1(); \ + v##_Tp##m1_t a0 = vundefined_##_T##m1(); \ + v##_Tp##m1_t b1 = vundefined_##_T##m1(); \ + b0 = vslidedown_vx_##_T##m1(b0, b.val, numh, num); \ + a0 = vslidedown_vx_##_T##m1(a0, a.val, numh, num); \ + b1 = vslideup_vx_##_T##m1_m(vmset_m_##len(num), a0, b0, numh, num); \ + return v_##_Tpvec(b1);\ +} \ +inline void v_recombine(const v_##_Tpvec& a, const v_##_Tpvec& b, v_##_Tpvec& c, v_##_Tpvec& d) \ +{ \ + v##_Tp##m1_t b0 = vundefined_##_T##m1(); \ + v##_Tp##m1_t a0 = vundefined_##_T##m1(); \ + c.val = vslideup_vx_##_T##m1_m(vmset_m_##len(num), a.val, b.val, numh, num); \ + b0 = vslidedown_vx_##_T##m1(b0, b.val, numh, num); \ + a0 = vslidedown_vx_##_T##m1(a0, a.val, numh, num); \ + d.val = vslideup_vx_##_T##m1_m(vmset_m_##len(num), a0, b0, numh, num); \ +} + +OPENCV_HAL_IMPL_RISCVV_UNPACKS(uint8x16, uint8, u8, uint8, u8, 16, 32, b8, 8, vreinterpret_v_u32m2_u8m2) +OPENCV_HAL_IMPL_RISCVV_UNPACKS(int8x16, int8, i8, uint8, u8, 16, 32, b8, 8, vreinterpret_v_u32m2_u8m2) +OPENCV_HAL_IMPL_RISCVV_UNPACKS(uint16x8, uint16, u16, uint16, u16, 8, 16, b16, 4, vreinterpret_v_u32m2_u16m2) +OPENCV_HAL_IMPL_RISCVV_UNPACKS(int16x8, int16, i16, uint16, u16, 8, 16, b16, 4, vreinterpret_v_u32m2_u16m2) +OPENCV_HAL_IMPL_RISCVV_UNPACKS(uint32x4, uint32, u32, uint32, u32, 4, 8, b32, 2,) +OPENCV_HAL_IMPL_RISCVV_UNPACKS(int32x4, int32, i32, uint32, u32, 4, 8, b32, 2,) +OPENCV_HAL_IMPL_RISCVV_UNPACKS(float32x4, float32, f32, uint32, u32, 4, 8, b32, 2,) +OPENCV_HAL_IMPL_RISCVV_UNPACKS(float64x2, float64, f64, uint64, u64, 2, 4, b64, 1, vreinterpret_v_u32m2_u64m2) + +inline v_uint8x16 v_reverse(const v_uint8x16 &a) +{ + return v_uint8x16(vrgather_vv_u8m1(a.val, vrsub_vx_u8m1(vid_v_u8m1(16), 15, 16), 16)); +} +inline v_int8x16 v_reverse(const v_int8x16 &a) +{ + return v_int8x16(vrgather_vv_i8m1(a.val, vrsub_vx_u8m1(vid_v_u8m1(16), 15, 16), 16)); +} + +inline v_uint16x8 v_reverse(const v_uint16x8 &a) +{ + return v_uint16x8(vrgather_vv_u16m1(a.val, vrsub_vx_u16m1(vid_v_u16m1(8), 7, 8), 8)); +} + +inline v_int16x8 v_reverse(const v_int16x8 &a) +{ + return v_int16x8(vrgather_vv_i16m1(a.val, vrsub_vx_u16m1(vid_v_u16m1(8), 7, 8), 8)); +} +inline v_uint32x4 v_reverse(const v_uint32x4 &a) +{ + return v_uint32x4(vrgather_vv_u32m1(a.val, vrsub_vx_u32m1(vid_v_u32m1(4), 3, 4), 4)); +} + +inline v_int32x4 v_reverse(const v_int32x4 &a) +{ + return v_int32x4(vrgather_vv_i32m1(a.val, vrsub_vx_u32m1(vid_v_u32m1(4), 3, 4), 4)); +} + +inline v_float32x4 v_reverse(const v_float32x4 &a) +{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_uint64x2 v_reverse(const v_uint64x2 &a) +{ + return v_uint64x2(vrgather_vv_u64m1(a.val, vrsub_vx_u64m1(vid_v_u64m1(2), 1, 2), 2)); +} + +inline v_int64x2 v_reverse(const v_int64x2 &a) +{ + return v_int64x2(vrgather_vv_i64m1(a.val, vrsub_vx_u64m1(vid_v_u64m1(2), 1, 2), 2)); +} + +inline v_float64x2 v_reverse(const v_float64x2 &a) +{ + return v_float64x2(vrgather_vv_f64m1(a.val, vrsub_vx_u64m1(vid_v_u64m1(2), 1, 2), 2)); +} + +#define OPENCV_HAL_IMPL_RISCVV_EXTRACT(_Tpvec, suffix, size) \ +template \ +inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \ +{ return v_rotate_right(a, b);} +OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_uint8x16, u8, 0) +OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_int8x16, s8, 0) +OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_uint16x8, u16, 1) +OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_int16x8, s16, 1) +OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_uint32x4, u32, 2) +OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_int32x4, s32, 2) +OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_uint64x2, u64, 3) +OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_int64x2, s64, 3) +OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_float32x4, f32, 2) +OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_float64x2, f64, 3) + + +#define OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(_Tpvec, _Tp, suffix, vtype, _vtype, num, mvfunc) \ +template inline _Tp v_extract_n(_Tpvec v) { vtype tmp = vundefined_##_vtype(); return mvfunc(vslidedown_vx_##_vtype(tmp, v.val, i, num)); } + +OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_uint8x16, uchar, u8, vuint8m1_t, u8m1, 16, vmv_x_s_u8m1_u8) +OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_int8x16, schar, s8, vint8m1_t, i8m1, 16, vmv_x_s_i8m1_i8) +OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_uint16x8, ushort, u16, vuint16m1_t, u16m1, 8, vmv_x_s_u16m1_u16) +OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_int16x8, short, s16, vint16m1_t, i16m1, 8, vmv_x_s_i16m1_i16) +OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_uint32x4, uint, u32, vuint32m1_t, u32m1, 4, vmv_x_s_u32m1_u32) +OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_int32x4, int, s32, vint32m1_t, i32m1, 4, vmv_x_s_i32m1_i32) +OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_uint64x2, uint64, u64, vuint64m1_t, u64m1, 2, vmv_x_s_u64m1_u64) +OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_int64x2, int64, s64, vint64m1_t, i64m1, 2, vmv_x_s_i64m1_i64) +OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_float32x4, float, f32, vfloat32m1_t, f32m1, 4, vfmv_f_s_f32m1_f32) +OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_float64x2, double, f64, vfloat64m1_t, f64m1, 2, vfmv_f_s_f64m1_f64) + +#define OPENCV_HAL_IMPL_RISCVV_BROADCAST(_Tpvec, _Tp, num) \ +template inline _Tpvec v_broadcast_element(_Tpvec v) { return _Tpvec(vrgather_vx_##_Tp##m1(v.val, i, num)); } + +OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_uint8x16, u8, 16) +OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_int8x16, i8, 16) +OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_uint16x8, u16, 8) +OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_int16x8, i16, 8) +OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_uint32x4, u32, 4) +OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_int32x4, i32, 4) +OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_uint64x2, u64, 2) +OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_int64x2, i64, 2) +OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_float32x4, f32, 4) + +inline void __builtin_riscv_fsrm(int val) +{ + asm("csrw frm, %0\n\t" + : + :"r"(val)); + return; +} + +inline void barrier1(void *arg) { + __asm__ __volatile__("" : : "r" (arg) : "memory"); +} + +inline v_int32x4 v_round(const v_float32x4& a) +{ + __builtin_riscv_fsrm(0); + vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(a.val), 0x7f800000, 4); + barrier1(&nan); + vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); + vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), a.val, 4); + __builtin_riscv_fsrm(0); + return v_int32x4(val); +} +inline v_int32x4 v_floor(const v_float32x4& a) +{ + __builtin_riscv_fsrm(2); + vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(a.val), 0x7f800000, 4); + barrier1(&nan); + vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); + vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), a.val, 4); + __builtin_riscv_fsrm(0); + return v_int32x4(val); +} + +inline v_int32x4 v_ceil(const v_float32x4& a) +{ + __builtin_riscv_fsrm(3); + vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(a.val), 0x7f800000, 4); + barrier1(&nan); + vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); + vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), a.val, 4); + __builtin_riscv_fsrm(0); + return v_int32x4(val); +} + +inline v_int32x4 v_trunc(const v_float32x4& a) +{ + __builtin_riscv_fsrm(1); + vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(a.val), 0x7f800000, 4); + barrier1(&nan); + vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); + vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), a.val, 4); + __builtin_riscv_fsrm(0); + return v_int32x4(val); +} + +inline v_int32x4 v_round(const v_float64x2& a) +{ + __builtin_riscv_fsrm(0); + vfloat64m2_t _val = vundefined_f64m2(); + _val = vset_v_f64m1_f64m2(_val, 0, a.val); + //_val = vset_f64m2(_val, 1, a.val); + _val = vset_v_f64m1_f64m2(_val, 1, vfmv_v_f_f64m1(0, 2)); + barrier1(&_val); + vint32m1_t val = vfncvt_x_f_w_i32m1(_val, 4); + __builtin_riscv_fsrm(0); + return v_int32x4(val); +} +inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) +{ + __builtin_riscv_fsrm(0); + vfloat64m2_t _val = vundefined_f64m2(); + _val = vset_v_f64m1_f64m2(_val, 0, a.val); + _val = vset_v_f64m1_f64m2(_val, 1, b.val); + barrier1(&_val); + vint32m1_t val = vfncvt_x_f_w_i32m1(_val, 4); + __builtin_riscv_fsrm(0); + return v_int32x4(val); +} +inline v_int32x4 v_floor(const v_float64x2& a) +{ + __builtin_riscv_fsrm(2); + vfloat64m2_t _val = vundefined_f64m2(); + _val = vset_v_f64m1_f64m2(_val, 0, a.val); + vfloat32m1_t aval = vfncvt_f_f_w_f32m1(_val, 2); + vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(aval), 0x7f800000, 4); + barrier1(&nan); + vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); + vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), aval, 4); + __builtin_riscv_fsrm(0); + return v_int32x4(val); +} + +inline v_int32x4 v_ceil(const v_float64x2& a) +{ + __builtin_riscv_fsrm(3); + vfloat64m2_t _val = vundefined_f64m2(); + _val = vset_v_f64m1_f64m2(_val, 0, a.val); + vfloat32m1_t aval = vfncvt_f_f_w_f32m1(_val, 2); + vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(aval), 0x7f800000, 4); + barrier1(&nan); + vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); + vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), aval, 4); + __builtin_riscv_fsrm(0); + return v_int32x4(val); +} + +inline v_int32x4 v_trunc(const v_float64x2& a) +{ + __builtin_riscv_fsrm(1); + vfloat64m2_t _val = vundefined_f64m2(); + _val = vset_v_f64m1_f64m2(_val, 0, a.val); + vfloat32m1_t aval = vfncvt_f_f_w_f32m1(_val, 2); + vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(aval), 0x7f800000, 4); + barrier1(&nan); + vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); + vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), aval, 4); + __builtin_riscv_fsrm(0); + return v_int32x4(val); +} + +#define OPENCV_HAL_IMPL_RISCVV_LOAD_DEINTERLEAVED(intrin, _Tpvec, num, _Tp, _T, elemsize) \ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec##x##num& a, v_##_Tpvec##x##num& b) \ +{ \ + intrin##2e##elemsize##_v_##_T##m1(&a.val, &b.val, ptr, num); \ +} \ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec##x##num& a, v_##_Tpvec##x##num& b, v_##_Tpvec##x##num& c) \ +{ \ + intrin##3e##elemsize##_v_##_T##m1(&a.val, &b.val, &c.val, ptr, num); \ +}\ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec##x##num& a, v_##_Tpvec##x##num& b, \ + v_##_Tpvec##x##num& c, v_##_Tpvec##x##num& d) \ +{ \ + intrin##4e##elemsize##_v_##_T##m1(&a.val, &b.val, &c.val, &d.val, ptr, num); \ +} \ + +#define OPENCV_HAL_IMPL_RISCVV_STORE_INTERLEAVED(intrin, _Tpvec, num, _Tp, _T, elemsize) \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec##x##num& a, const v_##_Tpvec##x##num& b, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + intrin##2e##elemsize##_v_##_T##m1(ptr, a.val, b.val, num); \ +} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec##x##num& a, const v_##_Tpvec##x##num& b, \ + const v_##_Tpvec##x##num& c, hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + intrin##3e##elemsize##_v_##_T##m1(ptr, a.val, b.val, c.val, num); \ +} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec##x##num& a, const v_##_Tpvec##x##num& b, \ + const v_##_Tpvec##x##num& c, const v_##_Tpvec##x##num& d, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ +{ \ + intrin##4e##elemsize##_v_##_T##m1(ptr, a.val, b.val, c.val, d.val, num); \ +} + +#define OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(_Tpvec, _Tp, num, ld, st, _T, elemsize) \ +OPENCV_HAL_IMPL_RISCVV_LOAD_DEINTERLEAVED(ld, _Tpvec, num, _Tp, _T, elemsize) \ +OPENCV_HAL_IMPL_RISCVV_STORE_INTERLEAVED(st, _Tpvec, num, _Tp, _T, elemsize) + +//OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(uint8, uchar, ) +OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(int8, schar, 16, vlseg, vsseg, i8, 8) +OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(int16, short, 8, vlseg, vsseg, i16, 16) +OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(int32, int, 4, vlseg, vsseg, i32, 32) + +OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(uint8, unsigned char, 16, vlseg, vsseg, u8, 8) +OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(uint16, unsigned short, 8, vlseg, vsseg, u16, 16) +OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(uint32, unsigned int, 4, vlseg, vsseg, u32, 32) + +#define OPENCV_HAL_IMPL_RISCVV_INTERLEAVED_(_Tpvec, _Tp, num, _T, _esize) \ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec##x##num& a, v_##_Tpvec##x##num& b) \ +{ vlseg2e##_esize##_v_##_T##m1(&a.val, &b.val, ptr, num);} \ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec##x##num& a, v_##_Tpvec##x##num& b, v_##_Tpvec##x##num& c) \ +{ vlseg3e##_esize##_v_##_T##m1(&a.val, &b.val, &c.val, ptr, num);}\ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec##x##num& a, v_##_Tpvec##x##num& b, \ + v_##_Tpvec##x##num& c, v_##_Tpvec##x##num& d) \ +{ vlseg4e##_esize##_v_##_T##m1(&a.val, &b.val, &c.val, &d.val, ptr, num);} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec##x##num& a, const v_##_Tpvec##x##num& b, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ vsseg2e##_esize##_v_##_T##m1(ptr, a.val, b.val, num);} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec##x##num& a, const v_##_Tpvec##x##num& b, \ + const v_##_Tpvec##x##num& c, hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ vsseg3e##_esize##_v_##_T##m1(ptr, a.val, b.val, c.val, num);} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec##x##num& a, const v_##_Tpvec##x##num& b, \ + const v_##_Tpvec##x##num& c, const v_##_Tpvec##x##num& d, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ +{ vsseg4e##_esize##_v_##_T##m1(ptr, a.val, b.val, c.val, d.val, num);} + +OPENCV_HAL_IMPL_RISCVV_INTERLEAVED_(float32, float, 4, f32, 32) +OPENCV_HAL_IMPL_RISCVV_INTERLEAVED_(float64, double, 2, f64, 64) + +OPENCV_HAL_IMPL_RISCVV_INTERLEAVED_(uint64, unsigned long, 2, u64, 64) +OPENCV_HAL_IMPL_RISCVV_INTERLEAVED_(int64, long, 2, i64, 64) + +inline v_float32x4 v_cvt_f32(const v_int32x4& a) +{ + return v_float32x4(vfcvt_f_x_v_f32m1(a.val, 4)); +} + +#if CV_SIMD128_64F +inline v_float32x4 v_cvt_f32(const v_float64x2& a) +{ + vfloat64m2_t _val = vundefined_f64m2(); + _val = vset_v_f64m1_f64m2(_val, 0, a.val); + vfloat32m1_t aval = vfncvt_f_f_w_f32m1(_val, 2); + return v_float32x4(aval); +} + +inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) +{ + vfloat64m2_t _val = vundefined_f64m2(); + _val = vset_v_f64m1_f64m2(_val, 0, a.val); + _val = vset_v_f64m1_f64m2(_val, 1, b.val); + vfloat32m1_t aval = vfncvt_f_f_w_f32m1(_val, 4); + return v_float32x4(aval); +} + +inline v_float64x2 v_cvt_f64(const v_int32x4& a) +{ + vfloat32m1_t val = vfcvt_f_x_v_f32m1(a.val, 4); + vfloat64m2_t _val = vfwcvt_f_f_v_f64m2(val, 4); + return v_float64x2(vget_v_f64m2_f64m1(_val, 0)); +} + +inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) +{ + vfloat32m1_t val = vfcvt_f_x_v_f32m1(a.val, 4); + vfloat64m2_t _val = vfwcvt_f_f_v_f64m2(val, 4); + return v_float64x2(vget_v_f64m2_f64m1(_val, 1)); +} + +inline v_float64x2 v_cvt_f64(const v_float32x4& a) +{ + vfloat64m2_t _val = vfwcvt_f_f_v_f64m2(a.val, 4); + return v_float64x2(vget_v_f64m2_f64m1(_val, 0)); +} + +inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) +{ + vfloat64m2_t _val = vfwcvt_f_f_v_f64m2(a.val, 4); + return v_float64x2(vget_v_f64m2_f64m1(_val, 1)); +} + +inline v_float64x2 v_cvt_f64(const v_int64x2& a) +{ + return v_float64x2(vfcvt_f_x_v_f64m1(a.val, 2)); +} + +#endif +inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) +{ + uint64 mdata[2] = {0x0705060403010200, 0x0F0D0E0C0B090A08}; + vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); + return v_int8x16(vrgather_vv_i8m1(vec.val, vreinterpret_v_u64m1_u8m1(m0), 16)); +} +inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) +{ + return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); +} + +inline v_int8x16 v_interleave_quads(const v_int8x16& vec) +{ + uint64 mdata[2] = {0x0703060205010400, 0x0F0B0E0A0D090C08}; + vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); + return v_int8x16(vrgather_vv_i8m1(vec.val, vreinterpret_v_u64m1_u8m1(m0), 16)); +} +inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) +{ + return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); +} + +inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) +{ + uint64 mdata[2] = {0x0706030205040100, 0x0F0E0B0A0D0C0908}; + vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); + return v_int16x8(vreinterpret_v_i8m1_i16m1(vreinterpret_v_u8m1_i8m1(vrgather_vv_u8m1(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i16m1_i8m1(vec.val)), vreinterpret_v_u64m1_u8m1(m0), 16)))); +} +inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } +inline v_int16x8 v_interleave_quads(const v_int16x8& vec) +{ + uint64 mdata[2] = {0x0B0A030209080100, 0x0F0E07060D0C0504}; + vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); + return v_int16x8(vreinterpret_v_i8m1_i16m1(vreinterpret_v_u8m1_i8m1(vrgather_vv_u8m1(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i16m1_i8m1(vec.val)), vreinterpret_v_u64m1_u8m1(m0), 16)))); +} +inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) +{ + uint64 mdata[2] = {0x0B0A090803020100, 0x0F0E0D0C07060504}; + vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); + return v_int32x4(vreinterpret_v_i8m1_i32m1(vreinterpret_v_u8m1_i8m1(vrgather_vv_u8m1(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i32m1_i8m1(vec.val)), vreinterpret_v_u64m1_u8m1(m0), 16)))); +} +inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } +inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } +inline v_int8x16 v_pack_triplets(const v_int8x16& vec) +{ + uint64 mdata[2] = {0x0908060504020100, 0xFFFFFFFF0E0D0C0A}; + vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); + return v_int8x16(vreinterpret_v_u8m1_i8m1(vrgather_vv_u8m1(vreinterpret_v_i8m1_u8m1(vec.val), vreinterpret_v_u64m1_u8m1(m0), 16))); +} +inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_pack_triplets(const v_int16x8& vec) +{ + uint64 mdata[2] = {0x0908050403020100, 0xFFFFFFFF0D0C0B0A}; + vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); + return v_int16x8(vreinterpret_v_i8m1_i16m1(vreinterpret_v_u8m1_i8m1(vrgather_vv_u8m1(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i16m1_i8m1(vec.val)), vreinterpret_v_u64m1_u8m1(m0), 16)))); +} +inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } +inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } +inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } + +#if CV_SIMD128_64F +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) +{ return v_cvt_f64(v_dotprod(a, b)); } +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, + const v_float64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) +{ + vint64m2_t v1 = vwmul_vv_i64m2(a.val, b.val, 4); + vfloat64m1_t res = vfcvt_f_x_v_f64m1(vadd_vv_i64m1(vget_v_i64m2_i64m1(v1, 0), vget_v_i64m2_i64m1(v1, 1), 2), 2); + return v_float64x2(res); +} +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) +{ v_float64x2 res = v_dotprod_expand_fast(a, b); + return v_add(res, c); } +#endif +////// FP16 support /////// +#if __riscv_v == 7000 +inline v_float32x4 v_load_expand(const hfloat* ptr) +{ + vfloat16m1_t v = vle16_v_f16m1((__fp16*)ptr, 4); + vfloat32m2_t v32 = vfwcvt_f_f_v_f32m2(v, 4); + return v_float32x4(vget_v_f32m2_f32m1(v32, 0)); +} + +inline void v_pack_store(hfloat* ptr, const v_float32x4& v) +{ + vfloat32m2_t v32 = vundefined_f32m2(); + v32 = vset_v_f32m1_f32m2(v32, 0, v.val); + vfloat16m1_t hv = vfncvt_f_f_w_f16m1(v32, 4); + vse16_v_f16m1((__fp16*)ptr, hv, 4); +} +#else +inline v_float32x4 v_load_expand(const hfloat* ptr) +{ + vfloat16mf2_t v = vle16_v_f16mf2((__fp16*)ptr, 4); + vfloat32m1_t v32 = vfwcvt_f_f_v_f32m1(v, 4); + return v_float32x4(v32); +} + +inline void v_pack_store(hfloat* ptr, const v_float32x4& v) +{ + //vfloat32m2_t v32 = vundefined_f32m2(); + //v32 = vset_f32m2(v32, 0, v.val); + vfloat16mf2_t hv = vfncvt_f_f_w_f16mf2(v.val, 4); + vse16_v_f16mf2((__fp16*)ptr, hv, 4); +} +#endif + +inline void v_cleanup() {} + +#include "intrin_math.hpp" +inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } +inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } +inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } +inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } +inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } +inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } + +inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } +inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } +inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } +inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } +inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_rvv_scalable.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_rvv_scalable.hpp index b6ce2d7f47..b97b041d44 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_rvv_scalable.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_rvv_scalable.hpp @@ -1,2153 +1,2153 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -// The original implementation is contributed by HAN Liutong. -// Copyright (C) 2022, Institute of Software, Chinese Academy of Sciences. - -#ifndef OPENCV_HAL_INTRIN_RVV_SCALABLE_HPP -#define OPENCV_HAL_INTRIN_RVV_SCALABLE_HPP - -#include - -#if defined(__GNUC__) && !defined(__clang__) -// FIXIT: eliminate massive warnigs from templates -// GCC from 'rvv-next': riscv64-unknown-linux-gnu-g++ (g42df3464463) 12.0.1 20220505 (prerelease) -// doesn't work: #pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wignored-attributes" -#endif - -#ifndef CV_RVV_MAX_VLEN -#define CV_RVV_MAX_VLEN 1024 -#endif - -namespace cv -{ - -//! @cond IGNORED - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -#define CV_SIMD_SCALABLE 1 -#define CV_SIMD_SCALABLE_64F 1 - -using v_uint8 = vuint8m2_t; -using v_int8 = vint8m2_t; -using v_uint16 = vuint16m2_t; -using v_int16 = vint16m2_t; -using v_uint32 = vuint32m2_t; -using v_int32 = vint32m2_t; -using v_uint64 = vuint64m2_t; -using v_int64 = vint64m2_t; - -using v_float32 = vfloat32m2_t; -#if CV_SIMD_SCALABLE_64F -using v_float64 = vfloat64m2_t; -#endif - -using uchar = unsigned char; -using schar = signed char; -using ushort = unsigned short; -using uint = unsigned int; -using uint64 = unsigned long int; -using int64 = long int; - - -template -struct VTraits; - -#define OPENCV_HAL_IMPL_RVV_TRAITS(REG, TYP, SUF, SZ) \ -template <> \ -struct VTraits \ -{ \ - static inline int vlanes() { return __riscv_vsetvlmax_##SUF(); } \ - using lane_type = TYP; \ - static const int max_nlanes = CV_RVV_MAX_VLEN/SZ; \ -}; - -OPENCV_HAL_IMPL_RVV_TRAITS(vint8m1_t, int8_t, e8m1, 8) -OPENCV_HAL_IMPL_RVV_TRAITS(vint8m2_t, int8_t, e8m2, 8) -OPENCV_HAL_IMPL_RVV_TRAITS(vint8m4_t, int8_t, e8m4, 8) -OPENCV_HAL_IMPL_RVV_TRAITS(vint8m8_t, int8_t, e8m8, 8) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint8m1_t, uint8_t, e8m1, 8) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint8m2_t, uint8_t, e8m2, 8) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint8m4_t, uint8_t, e8m4, 8) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint8m8_t, uint8_t, e8m8, 8) - -OPENCV_HAL_IMPL_RVV_TRAITS(vint16m1_t, int16_t, e16m1, 16) -OPENCV_HAL_IMPL_RVV_TRAITS(vint16m2_t, int16_t, e16m2, 16) -OPENCV_HAL_IMPL_RVV_TRAITS(vint16m4_t, int16_t, e16m4, 16) -OPENCV_HAL_IMPL_RVV_TRAITS(vint16m8_t, int16_t, e16m8, 16) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint16m1_t, uint16_t, e16m1, 16) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint16m2_t, uint16_t, e16m2, 16) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint16m4_t, uint16_t, e16m4, 16) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint16m8_t, uint16_t, e16m8, 16) - -OPENCV_HAL_IMPL_RVV_TRAITS(vint32m1_t, int32_t, e32m1, 32) -OPENCV_HAL_IMPL_RVV_TRAITS(vint32m2_t, int32_t, e32m2, 32) -OPENCV_HAL_IMPL_RVV_TRAITS(vint32m4_t, int32_t, e32m4, 32) -OPENCV_HAL_IMPL_RVV_TRAITS(vint32m8_t, int32_t, e32m8, 32) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint32m1_t, uint32_t, e32m1, 32) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint32m2_t, uint32_t, e32m2, 32) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint32m4_t, uint32_t, e32m4, 32) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint32m8_t, uint32_t, e32m8, 32) - -OPENCV_HAL_IMPL_RVV_TRAITS(vint64m1_t, int64_t, e64m1, 64) -OPENCV_HAL_IMPL_RVV_TRAITS(vint64m2_t, int64_t, e64m2, 64) -OPENCV_HAL_IMPL_RVV_TRAITS(vint64m4_t, int64_t, e64m4, 64) -OPENCV_HAL_IMPL_RVV_TRAITS(vint64m8_t, int64_t, e64m8, 64) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint64m1_t, uint64_t, e64m1, 64) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint64m2_t, uint64_t, e64m2, 64) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint64m4_t, uint64_t, e64m4, 64) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint64m8_t, uint64_t, e64m8, 64) - -OPENCV_HAL_IMPL_RVV_TRAITS(vfloat32m1_t, float, e32m1, 32) -OPENCV_HAL_IMPL_RVV_TRAITS(vfloat32m2_t, float, e32m2, 32) -OPENCV_HAL_IMPL_RVV_TRAITS(vfloat32m4_t, float, e32m4, 32) -OPENCV_HAL_IMPL_RVV_TRAITS(vfloat32m8_t, float, e32m8, 32) - -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_TRAITS(vfloat64m1_t, double, e64m1, 64) -OPENCV_HAL_IMPL_RVV_TRAITS(vfloat64m2_t, double, e64m2, 64) -OPENCV_HAL_IMPL_RVV_TRAITS(vfloat64m4_t, double, e64m4, 64) -OPENCV_HAL_IMPL_RVV_TRAITS(vfloat64m8_t, double, e64m8, 64) -#endif - - -// LLVM/Clang defines "overloaded intrinsics" e.g. 'vand(op1, op2)' -// GCC does not have these functions, so we need to implement them manually -// We implement only selected subset required to build current state of the code -// Included inside namespace cv:: -// #ifndef __riscv_v_intrinsic_overloading -// #include "intrin_rvv_compat_overloaded.hpp" -// #endif // __riscv_v_intrinsic_overloading - - -//////////// get0 //////////// -#define OPENCV_HAL_IMPL_RVV_GRT0_INT(_Tpvec, _Tp) \ -inline _Tp v_get0(const v_##_Tpvec& v) \ -{ \ - return __riscv_vmv_x(v); \ -} - -OPENCV_HAL_IMPL_RVV_GRT0_INT(uint8, uchar) -OPENCV_HAL_IMPL_RVV_GRT0_INT(int8, schar) -OPENCV_HAL_IMPL_RVV_GRT0_INT(uint16, ushort) -OPENCV_HAL_IMPL_RVV_GRT0_INT(int16, short) -OPENCV_HAL_IMPL_RVV_GRT0_INT(uint32, unsigned) -OPENCV_HAL_IMPL_RVV_GRT0_INT(int32, int) -OPENCV_HAL_IMPL_RVV_GRT0_INT(uint64, uint64) -OPENCV_HAL_IMPL_RVV_GRT0_INT(int64, int64) - -inline float v_get0(const v_float32& v) \ -{ \ - return __riscv_vfmv_f(v); \ -} -#if CV_SIMD_SCALABLE_64F -inline double v_get0(const v_float64& v) \ -{ \ - return __riscv_vfmv_f(v); \ -} -#endif - -//////////// Initial //////////// - -#define OPENCV_HAL_IMPL_RVV_INIT_INTEGER(_Tpvec, _Tp, suffix1, suffix2, vl) \ -inline v_##_Tpvec v_setzero_##suffix1() \ -{ \ - return __riscv_vmv_v_x_##suffix2##m2(0, vl); \ -} \ -inline v_##_Tpvec v_setall_##suffix1(_Tp v) \ -{ \ - return __riscv_vmv_v_x_##suffix2##m2(v, vl); \ -} \ -template <> inline v_##_Tpvec v_setzero_() \ -{ \ - return v_setzero_##suffix1(); \ -} \ -template <> inline v_##_Tpvec v_setall_(_Tp v) \ -{ \ - return v_setall_##suffix1(v); \ -} - -OPENCV_HAL_IMPL_RVV_INIT_INTEGER(uint8, uchar, u8, u8, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INIT_INTEGER(int8, schar, s8, i8, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INIT_INTEGER(uint16, ushort, u16, u16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INIT_INTEGER(int16, short, s16, i16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INIT_INTEGER(uint32, uint, u32, u32, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INIT_INTEGER(int32, int, s32, i32, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INIT_INTEGER(uint64, uint64, u64, u64, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INIT_INTEGER(int64, int64, s64, i64, VTraits::vlanes()) - -#define OPENCV_HAL_IMPL_RVV_INIT_FP(_Tpv, _Tp, suffix, vl) \ -inline v_##_Tpv v_setzero_##suffix() \ -{ \ - return __riscv_vfmv_v_f_##suffix##m2(0, vl); \ -} \ -inline v_##_Tpv v_setall_##suffix(_Tp v) \ -{ \ - return __riscv_vfmv_v_f_##suffix##m2(v, vl); \ -} \ -template <> inline v_##_Tpv v_setzero_() \ -{ \ - return v_setzero_##suffix(); \ -} \ -template <> inline v_##_Tpv v_setall_(_Tp v) \ -{ \ - return v_setall_##suffix(v); \ -} - -OPENCV_HAL_IMPL_RVV_INIT_FP(float32, float, f32, VTraits::vlanes()) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_INIT_FP(float64, double, f64, VTraits::vlanes()) -#endif - -//////////// Reinterpret //////////// -#define OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(_Tpvec1, suffix1) \ -inline v_##_Tpvec1 v_reinterpret_as_##suffix1(const v_##_Tpvec1& v) \ -{ \ - return v;\ -} -OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(uint8, u8) -OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(uint16, u16) -OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(uint32, u32) -OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(uint64, u64) -OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(int8, s8) -OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(int16, s16) -OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(int32, s32) -OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(int64, s64) -OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(float32, f32) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(float64, f64) -#endif -// TODO: can be simplified by using overloaded RV intrinsic -#define OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(_Tpvec1, _Tpvec2, suffix1, suffix2, nsuffix1, nsuffix2) \ -inline v_##_Tpvec1 v_reinterpret_as_##suffix1(const v_##_Tpvec2& v) \ -{ \ - return v_##_Tpvec1(__riscv_vreinterpret_v_##nsuffix2##m2_##nsuffix1##m2(v));\ -} \ -inline v_##_Tpvec2 v_reinterpret_as_##suffix2(const v_##_Tpvec1& v) \ -{ \ - return v_##_Tpvec2(__riscv_vreinterpret_v_##nsuffix1##m2_##nsuffix2##m2(v));\ -} - -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint8, int8, u8, s8, u8, i8) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint16, int16, u16, s16, u16, i16) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint32, int32, u32, s32, u32, i32) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint32, float32, u32, f32, u32, f32) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int32, float32, s32, f32, i32, f32) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint64, int64, u64, s64, u64, i64) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint64, float64, u64, f64, u64, f64) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int64, float64, s64, f64, i64, f64) -#endif -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint8, uint16, u8, u16, u8, u16) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint8, uint32, u8, u32, u8, u32) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint8, uint64, u8, u64, u8, u64) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint16, uint32, u16, u32, u16, u32) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint16, uint64, u16, u64, u16, u64) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint32, uint64, u32, u64, u32, u64) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int8, int16, s8, s16, i8, i16) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int8, int32, s8, s32, i8, i32) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int8, int64, s8, s64, i8, i64) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int16, int32, s16, s32, i16, i32) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int16, int64, s16, s64, i16, i64) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int32, int64, s32, s64, i32, i64) - - -#define OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(_Tpvec1, _Tpvec2, suffix1, suffix2, nsuffix1, nsuffix2, width1, width2) \ -inline v_##_Tpvec1 v_reinterpret_as_##suffix1(const v_##_Tpvec2& v) \ -{ \ - return __riscv_vreinterpret_v_##nsuffix1##width2##m2_##nsuffix1##width1##m2(__riscv_vreinterpret_v_##nsuffix2##width2##m2_##nsuffix1##width2##m2(v));\ -} \ -inline v_##_Tpvec2 v_reinterpret_as_##suffix2(const v_##_Tpvec1& v) \ -{ \ - return __riscv_vreinterpret_v_##nsuffix1##width2##m2_##nsuffix2##width2##m2(__riscv_vreinterpret_v_##nsuffix1##width1##m2_##nsuffix1##width2##m2(v));\ -} - -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint8, int16, u8, s16, u, i, 8, 16) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint8, int32, u8, s32, u, i, 8, 32) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint8, int64, u8, s64, u, i, 8, 64) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint16, int8, u16, s8, u, i, 16, 8) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint16, int32, u16, s32, u, i, 16, 32) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint16, int64, u16, s64, u, i, 16, 64) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint32, int8, u32, s8, u, i, 32, 8) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint32, int16, u32, s16, u, i, 32, 16) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint32, int64, u32, s64, u, i, 32, 64) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint64, int8, u64, s8, u, i, 64, 8) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint64, int16, u64, s16, u, i, 64, 16) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint64, int32, u64, s32, u, i, 64, 32) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint8, float32, u8, f32, u, f, 8, 32) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint16, float32, u16, f32, u, f, 16, 32) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint64, float32, u64, f32, u, f, 64, 32) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(int8, float32, s8, f32, i, f, 8, 32) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(int16, float32, s16, f32, i, f, 16, 32) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(int64, float32, s64, f32, i, f, 64, 32) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint8, float64, u8, f64, u, f, 8, 64) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint16, float64, u16, f64, u, f, 16, 64) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint32, float64, u32, f64, u, f, 32, 64) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(int8, float64, s8, f64, i, f, 8, 64) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(int16, float64, s16, f64, i, f, 16, 64) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(int32, float64, s32, f64, i, f, 32, 64) -// Three times reinterpret -inline v_float32 v_reinterpret_as_f32(const v_float64& v) \ -{ \ - return __riscv_vreinterpret_v_u32m2_f32m2(__riscv_vreinterpret_v_u64m2_u32m2(__riscv_vreinterpret_v_f64m2_u64m2(v)));\ -} - -inline v_float64 v_reinterpret_as_f64(const v_float32& v) \ -{ \ - return __riscv_vreinterpret_v_u64m2_f64m2(__riscv_vreinterpret_v_u32m2_u64m2(__riscv_vreinterpret_v_f32m2_u32m2(v)));\ -} -#endif - -//////////// Extract ////////////// - -#define OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(_Tpvec, _Tp, vl) \ -template \ -inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b, int i = s) \ -{ \ - return __riscv_vslideup(__riscv_vslidedown(a, i, vl), b, VTraits<_Tpvec>::vlanes() - i, vl); \ -} \ -template inline _Tp v_extract_n(_Tpvec v, int i = s) \ -{ \ - return __riscv_vmv_x(__riscv_vslidedown(v, i, vl)); \ -} - -OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_uint8, uchar, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_int8, schar, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_uint16, ushort, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_int16, short, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_uint32, unsigned int, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_int32, int, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_uint64, uint64, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_int64, int64, VTraits::vlanes()) - -#define OPENCV_HAL_IMPL_RVV_EXTRACT_FP(_Tpvec, _Tp, vl) \ -template \ -inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b, int i = s) \ -{ \ - return __riscv_vslideup(__riscv_vslidedown(a, i, vl), b, VTraits<_Tpvec>::vlanes() - i, vl); \ -} \ -template inline _Tp v_extract_n(_Tpvec v, int i = s) \ -{ \ - return __riscv_vfmv_f(__riscv_vslidedown(v, i, vl)); \ -} - -OPENCV_HAL_IMPL_RVV_EXTRACT_FP(v_float32, float, VTraits::vlanes()) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_EXTRACT_FP(v_float64, double, VTraits::vlanes()) -#endif - -#define OPENCV_HAL_IMPL_RVV_EXTRACT(_Tpvec, _Tp, vl) \ -inline _Tp v_extract_highest(_Tpvec v) \ -{ \ - return v_extract_n(v, vl-1); \ -} - -OPENCV_HAL_IMPL_RVV_EXTRACT(v_uint8, uchar, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT(v_int8, schar, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT(v_uint16, ushort, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT(v_int16, short, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT(v_uint32, unsigned int, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT(v_int32, int, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT(v_uint64, uint64, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT(v_int64, int64, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT(v_float32, float, VTraits::vlanes()) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_EXTRACT(v_float64, double, VTraits::vlanes()) -#endif - - -////////////// Load/Store ////////////// -#define OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(_Tpvec, _nTpvec, _Tp, hvl, vl, width, suffix) \ -inline _Tpvec v_load(const _Tp* ptr) \ -{ \ - return __riscv_vle##width##_v_##suffix##m2(ptr, vl); \ -} \ -inline _Tpvec v_load_aligned(const _Tp* ptr) \ -{ \ - return __riscv_vle##width##_v_##suffix##m2(ptr, vl); \ -} \ -inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ -{ \ - __riscv_vse##width##_v_##suffix##m2(ptr, a, vl); \ -} \ -inline _Tpvec v_load_low(const _Tp* ptr) \ -{ \ - return __riscv_vle##width##_v_##suffix##m2(ptr, hvl); \ -} \ -inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ -{ \ - return __riscv_vslideup(__riscv_vle##width##_v_##suffix##m2(ptr0, hvl), __riscv_vle##width##_v_##suffix##m2(ptr1, hvl), hvl, vl); \ -} \ -inline void v_store(_Tp* ptr, const _Tpvec& a) \ -{ \ - __riscv_vse##width(ptr, a, vl); \ -} \ -inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ -{ \ - __riscv_vse##width(ptr, a, vl); \ -} \ -inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ -{ \ - __riscv_vse##width(ptr, a, vl); \ -} \ -inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ -{ \ - __riscv_vse##width(ptr, a, hvl); \ -} \ -inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ -{ \ - __riscv_vse##width(ptr, __riscv_vslidedown_vx_##suffix##m2(a, hvl, vl), hvl); \ -} \ -template \ -_Tpvec v_load_##suffix(Targs... nScalars) \ -{ \ - return v_load({nScalars...}); \ -} - - -OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_uint8, vuint8m2_t, uchar, VTraits::vlanes() / 2, VTraits::vlanes(), 8, u8) -OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_int8, vint8m2_t, schar, VTraits::vlanes() / 2, VTraits::vlanes(), 8, i8) -OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_uint16, vuint16m2_t, ushort, VTraits::vlanes() / 2, VTraits::vlanes(), 16, u16) -OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_int16, vint16m2_t, short, VTraits::vlanes() / 2, VTraits::vlanes(), 16, i16) -OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_uint32, vuint32m2_t, unsigned int, VTraits::vlanes() / 2, VTraits::vlanes(), 32, u32) -OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_int32, vint32m2_t, int, VTraits::vlanes() / 2, VTraits::vlanes(), 32, i32) -OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_uint64, vuint64m2_t, uint64, VTraits::vlanes() / 2, VTraits::vlanes(), 64, u64) -OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_int64, vint64m2_t, int64, VTraits::vlanes() / 2, VTraits::vlanes(), 64, i64) -OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_float32, vfloat32m2_t, float, VTraits::vlanes() /2 , VTraits::vlanes(), 32, f32) - -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_float64, vfloat64m2_t, double, VTraits::vlanes() / 2, VTraits::vlanes(), 64, f64) -#endif - -////////////// Lookup table access //////////////////// -#define OPENCV_HAL_IMPL_RVV_LUT(_Tpvec, _Tp, suffix) \ -inline _Tpvec v_lut(const _Tp* tab, const int* idx) \ -{ \ - auto vidx = __riscv_vmul(__riscv_vreinterpret_u32##suffix(__riscv_vle32_v_i32##suffix(idx, VTraits<_Tpvec>::vlanes())), sizeof(_Tp), VTraits<_Tpvec>::vlanes()); \ - return __riscv_vloxei32(tab, vidx, VTraits<_Tpvec>::vlanes()); \ -} -OPENCV_HAL_IMPL_RVV_LUT(v_int8, schar, m8) -OPENCV_HAL_IMPL_RVV_LUT(v_int16, short, m4) -OPENCV_HAL_IMPL_RVV_LUT(v_int32, int, m2) -OPENCV_HAL_IMPL_RVV_LUT(v_int64, int64_t, m1) -OPENCV_HAL_IMPL_RVV_LUT(v_float32, float, m2) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_LUT(v_float64, double, m1) -#endif - -#define OPENCV_HAL_IMPL_RVV_LUT_PAIRS(_Tpvec, _Tp, suffix1, suffix2, v_trunc) \ -inline _Tpvec v_lut_pairs(const _Tp* tab, const int* idx) \ -{ \ - auto v0 = __riscv_vle32_v_u32##suffix1((unsigned*)idx, VTraits<_Tpvec>::vlanes()/2); \ - auto v1 = __riscv_vadd(v0, 1, VTraits<_Tpvec>::vlanes()/2); \ - auto w0 = __riscv_vwcvtu_x(v0, VTraits<_Tpvec>::vlanes()/2); \ - auto w1 = __riscv_vwcvtu_x(v1, VTraits<_Tpvec>::vlanes()/2); \ - auto sh1 = __riscv_vslide1up(v_trunc(__riscv_vreinterpret_u32##suffix2(w1)),0, VTraits<_Tpvec>::vlanes()); \ - auto vid = __riscv_vor(sh1, v_trunc(__riscv_vreinterpret_u32##suffix2(w0)), VTraits<_Tpvec>::vlanes()); \ - auto vidx = __riscv_vmul(vid, sizeof(_Tp), VTraits<_Tpvec>::vlanes()); \ - return __riscv_vloxei32(tab, vidx, VTraits<_Tpvec>::vlanes()); \ -} -OPENCV_HAL_IMPL_RVV_LUT_PAIRS(v_int8, schar, m4, m8, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_RVV_LUT_PAIRS(v_int16, short, m2, m4, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_RVV_LUT_PAIRS(v_int32, int, m1, m2, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_RVV_LUT_PAIRS(v_float32, float, m1, m2, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_RVV_LUT_PAIRS(v_int64, int64_t, m1, m2, __riscv_vlmul_trunc_u32m1) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_LUT_PAIRS(v_float64, double, m1, m2, __riscv_vlmul_trunc_u32m1) -#endif - - -#define OPENCV_HAL_IMPL_RVV_LUT_QUADS(_Tpvec, _Tp, suffix0, suffix1, suffix2, v_trunc) \ -inline _Tpvec v_lut_quads(const _Tp* tab, const int* idx) \ -{ \ - auto v0 = __riscv_vle32_v_u32##suffix0((unsigned*)idx, VTraits<_Tpvec>::vlanes()/4); \ - auto v1 = __riscv_vadd(v0, 1, VTraits<_Tpvec>::vlanes()/4); \ - auto v2 = __riscv_vadd(v0, 2, VTraits<_Tpvec>::vlanes()/4); \ - auto v3 = __riscv_vadd(v0, 3, VTraits<_Tpvec>::vlanes()/4); \ - auto w0 = __riscv_vwcvtu_x(v0, VTraits<_Tpvec>::vlanes()/4); \ - auto w1 = __riscv_vwcvtu_x(v1, VTraits<_Tpvec>::vlanes()/4); \ - auto w2 = __riscv_vwcvtu_x(v2, VTraits<_Tpvec>::vlanes()/4); \ - auto w3 = __riscv_vwcvtu_x(v3, VTraits<_Tpvec>::vlanes()/4); \ - auto sh2 = __riscv_vslide1up(__riscv_vreinterpret_u32##suffix1(w2),0, VTraits<_Tpvec>::vlanes()/2); \ - auto sh3 = __riscv_vslide1up(__riscv_vreinterpret_u32##suffix1(w3),0, VTraits<_Tpvec>::vlanes()/2); \ - auto vid0 = __riscv_vor(sh2, __riscv_vreinterpret_u32##suffix1(w0), VTraits<_Tpvec>::vlanes()/2); \ - auto vid1 = __riscv_vor(sh3, __riscv_vreinterpret_u32##suffix1(w1), VTraits<_Tpvec>::vlanes()/2); \ - auto wid0 = __riscv_vwcvtu_x(v_trunc(vid0), VTraits<_Tpvec>::vlanes()/2); \ - auto wid1 = __riscv_vwcvtu_x(v_trunc(vid1), VTraits<_Tpvec>::vlanes()/2); \ - auto shwid1 = __riscv_vslide1up(__riscv_vreinterpret_u32##suffix2(wid1),0, VTraits<_Tpvec>::vlanes()); \ - auto vid = __riscv_vor(shwid1, __riscv_vreinterpret_u32##suffix2(wid0), VTraits<_Tpvec>::vlanes()); \ - auto vidx = __riscv_vmul(vid, sizeof(_Tp), VTraits<_Tpvec>::vlanes()); \ - return __riscv_vloxei32(tab, vidx, VTraits<_Tpvec>::vlanes()); \ -} -OPENCV_HAL_IMPL_RVV_LUT_QUADS(v_int8, schar, m2, m4, m8, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_RVV_LUT_QUADS(v_int16, short, m1 , m2, m4, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_RVV_LUT_QUADS(v_int32, int, m1, m2, m2, __riscv_vlmul_trunc_u32m1) -OPENCV_HAL_IMPL_RVV_LUT_QUADS(v_float32, float, m1, m2, m2, __riscv_vlmul_trunc_u32m1) - -#define OPENCV_HAL_IMPL_RVV_LUT_VEC(_Tpvec, _Tp) \ -inline _Tpvec v_lut(const _Tp* tab, const v_int32& vidx) \ -{ \ - v_uint32 vidx_ = __riscv_vmul(__riscv_vreinterpret_u32m2(vidx), sizeof(_Tp), VTraits::vlanes()); \ - return __riscv_vloxei32(tab, vidx_, VTraits<_Tpvec>::vlanes()); \ -} -OPENCV_HAL_IMPL_RVV_LUT_VEC(v_float32, float) -OPENCV_HAL_IMPL_RVV_LUT_VEC(v_int32, int) -OPENCV_HAL_IMPL_RVV_LUT_VEC(v_uint32, unsigned) - -#if CV_SIMD_SCALABLE_64F -inline v_float64 v_lut(const double* tab, const v_int32& vidx) \ -{ \ - vuint32m1_t vidx_ = __riscv_vmul(__riscv_vlmul_trunc_u32m1(__riscv_vreinterpret_u32m2(vidx)), sizeof(double), VTraits::vlanes()); \ - return __riscv_vloxei32(tab, vidx_, VTraits::vlanes()); \ -} -#endif - - -inline v_uint8 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((schar*)tab, idx)); } -inline v_uint8 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((schar*)tab, idx)); } -inline v_uint8 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((schar*)tab, idx)); } -inline v_uint16 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((short*)tab, idx)); } -inline v_uint16 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((short*)tab, idx)); } -inline v_uint16 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((short*)tab, idx)); } -inline v_uint32 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((int*)tab, idx)); } -inline v_uint32 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((int*)tab, idx)); } -inline v_uint32 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((int*)tab, idx)); } -inline v_uint64 v_lut(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } -inline v_uint64 v_lut_pairs(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } - -////////////// Pack boolean //////////////////// -inline v_uint8 v_pack_b(const v_uint16& a, const v_uint16& b) -{ - return __riscv_vnsrl(__riscv_vset(__riscv_vlmul_ext_v_u16m2_u16m4(a),1,b), 0, VTraits::vlanes()); -} - -inline v_uint8 v_pack_b(const v_uint32& a, const v_uint32& b, - const v_uint32& c, const v_uint32& d) -{ - - return __riscv_vnsrl(__riscv_vnsrl(__riscv_vset(__riscv_vset(__riscv_vset(__riscv_vlmul_ext_u32m8(a),1,b),2,c),3,d), 0, VTraits::vlanes()), 0, VTraits::vlanes()); -} - -inline v_uint8 v_pack_b(const v_uint64& a, const v_uint64& b, const v_uint64& c, - const v_uint64& d, const v_uint64& e, const v_uint64& f, - const v_uint64& g, const v_uint64& h) -{ - vuint8m1_t t0 = __riscv_vnsrl(__riscv_vnsrl(__riscv_vnsrl(__riscv_vset(__riscv_vset(__riscv_vset(__riscv_vlmul_ext_u64m8(a),1,b),2,c),3,d), 0, VTraits::vlanes()), 0, VTraits::vlanes()), 0, VTraits::vlanes()); - vuint8m1_t t1 = __riscv_vnsrl(__riscv_vnsrl(__riscv_vnsrl(__riscv_vset(__riscv_vset(__riscv_vset(__riscv_vlmul_ext_u64m8(e),1,f),2,g),3,h), 0, VTraits::vlanes()), 0, VTraits::vlanes()), 0, VTraits::vlanes()); - - return __riscv_vset(__riscv_vlmul_ext_u8m2(t0), 1, t1); -} - -////////////// Arithmetics ////////////// -#define OPENCV_HAL_IMPL_RVV_BIN_OP(_Tpvec, ocv_intrin, rvv_intrin) \ -inline _Tpvec v_##ocv_intrin(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return rvv_intrin(a, b, VTraits<_Tpvec>::vlanes()); \ -} - -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint8, add, __riscv_vsaddu) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint8, sub, __riscv_vssubu) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int8, add, __riscv_vsadd) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int8, sub, __riscv_vssub) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint16, add, __riscv_vsaddu) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint16, sub, __riscv_vssubu) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int16, add, __riscv_vsadd) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int16, sub, __riscv_vssub) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint32, add, __riscv_vadd) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint32, sub, __riscv_vsub) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint32, mul, __riscv_vmul) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int32, add, __riscv_vadd) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int32, sub, __riscv_vsub) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int32, mul, __riscv_vmul) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_float32, add, __riscv_vfadd) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_float32, sub, __riscv_vfsub) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_float32, mul, __riscv_vfmul) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_float32, div, __riscv_vfdiv) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint64, add, __riscv_vadd) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint64, sub, __riscv_vsub) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int64, add, __riscv_vadd) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int64, sub, __riscv_vsub) - -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_BIN_OP(v_float64, add, __riscv_vfadd) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_float64, sub, __riscv_vfsub) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_float64, mul, __riscv_vfmul) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_float64, div, __riscv_vfdiv) -#endif - -#define OPENCV_HAL_IMPL_RVV_BIN_MADD(_Tpvec, rvv_add) \ -template \ -inline _Tpvec v_add(const _Tpvec& f1, const _Tpvec& f2, const Args&... vf) { \ - return v_add(rvv_add(f1, f2, VTraits<_Tpvec>::vlanes()), vf...); \ -} -#define OPENCV_HAL_IMPL_RVV_BIN_MMUL(_Tpvec, rvv_mul) \ -template \ -inline _Tpvec v_mul(const _Tpvec& f1, const _Tpvec& f2, const Args&... vf) { \ - return v_mul(rvv_mul(f1, f2, VTraits<_Tpvec>::vlanes()), vf...); \ -} -OPENCV_HAL_IMPL_RVV_BIN_MADD(v_uint8, __riscv_vsaddu) -OPENCV_HAL_IMPL_RVV_BIN_MADD(v_int8, __riscv_vsadd) -OPENCV_HAL_IMPL_RVV_BIN_MADD(v_uint16, __riscv_vsaddu) -OPENCV_HAL_IMPL_RVV_BIN_MADD(v_int16, __riscv_vsadd) -OPENCV_HAL_IMPL_RVV_BIN_MADD(v_uint32, __riscv_vadd) -OPENCV_HAL_IMPL_RVV_BIN_MADD(v_int32, __riscv_vadd) -OPENCV_HAL_IMPL_RVV_BIN_MADD(v_float32, __riscv_vfadd) -OPENCV_HAL_IMPL_RVV_BIN_MADD(v_uint64, __riscv_vadd) -OPENCV_HAL_IMPL_RVV_BIN_MADD(v_int64, __riscv_vadd) - -OPENCV_HAL_IMPL_RVV_BIN_MMUL(v_uint32, __riscv_vmul) -OPENCV_HAL_IMPL_RVV_BIN_MMUL(v_int32, __riscv_vmul) -OPENCV_HAL_IMPL_RVV_BIN_MMUL(v_float32, __riscv_vfmul) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_BIN_MADD(v_float64, __riscv_vfadd) -OPENCV_HAL_IMPL_RVV_BIN_MMUL(v_float64, __riscv_vfmul) -#endif - -#define OPENCV_HAL_IMPL_RVV_MUL_EXPAND(_Tpvec, _Tpwvec, _TpwvecM2, suffix, wmul) \ -inline void v_mul_expand(const _Tpvec& a, const _Tpvec& b, _Tpwvec& c, _Tpwvec& d) \ -{ \ - _TpwvecM2 temp = wmul(a, b, VTraits<_Tpvec>::vlanes()); \ - c = __riscv_vget_##suffix##m2(temp, 0); \ - d = __riscv_vget_##suffix##m2(temp, 1); \ -} - -OPENCV_HAL_IMPL_RVV_MUL_EXPAND(v_uint8, v_uint16, vuint16m4_t, u16, __riscv_vwmulu) -OPENCV_HAL_IMPL_RVV_MUL_EXPAND(v_int8, v_int16, vint16m4_t, i16, __riscv_vwmul) -OPENCV_HAL_IMPL_RVV_MUL_EXPAND(v_uint16, v_uint32, vuint32m4_t, u32, __riscv_vwmulu) -OPENCV_HAL_IMPL_RVV_MUL_EXPAND(v_int16, v_int32, vint32m4_t, i32, __riscv_vwmul) -OPENCV_HAL_IMPL_RVV_MUL_EXPAND(v_uint32, v_uint64, vuint64m4_t, u64, __riscv_vwmulu) - -inline v_int16 v_mul_hi(const v_int16& a, const v_int16& b) -{ - return __riscv_vmulh(a, b, VTraits::vlanes()); -} -inline v_uint16 v_mul_hi(const v_uint16& a, const v_uint16& b) -{ - return __riscv_vmulhu(a, b, VTraits::vlanes()); -} - -////////////// Arithmetics (wrap)////////////// -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint8, add_wrap, __riscv_vadd) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int8, add_wrap, __riscv_vadd) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint16, add_wrap, __riscv_vadd) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int16, add_wrap, __riscv_vadd) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint8, sub_wrap, __riscv_vsub) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int8, sub_wrap, __riscv_vsub) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint16, sub_wrap, __riscv_vsub) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int16, sub_wrap, __riscv_vsub) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint8, mul_wrap, __riscv_vmul) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int8, mul_wrap, __riscv_vmul) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint16, mul_wrap, __riscv_vmul) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int16, mul_wrap, __riscv_vmul) - -//////// Saturating Multiply //////// -#define OPENCV_HAL_IMPL_RVV_MUL_SAT(_Tpvec, _clip, _wmul) \ -inline _Tpvec v_mul(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _clip(_wmul(a, b, VTraits<_Tpvec>::vlanes()), 0, 0, VTraits<_Tpvec>::vlanes()); \ -} \ -template \ -inline _Tpvec v_mul(const _Tpvec& a1, const _Tpvec& a2, const Args&... va) { \ - return v_mul(_clip(_wmul(a1, a2, VTraits<_Tpvec>::vlanes()), 0, 0, VTraits<_Tpvec>::vlanes()), va...); \ -} - -OPENCV_HAL_IMPL_RVV_MUL_SAT(v_uint8, __riscv_vnclipu, __riscv_vwmulu) -OPENCV_HAL_IMPL_RVV_MUL_SAT(v_int8, __riscv_vnclip, __riscv_vwmul) -OPENCV_HAL_IMPL_RVV_MUL_SAT(v_uint16, __riscv_vnclipu, __riscv_vwmulu) -OPENCV_HAL_IMPL_RVV_MUL_SAT(v_int16, __riscv_vnclip, __riscv_vwmul) - -////////////// Bitwise logic ////////////// - -#define OPENCV_HAL_IMPL_RVV_LOGIC_OP(_Tpvec, vl) \ -inline _Tpvec v_and(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return __riscv_vand(a, b, vl); \ -} \ -inline _Tpvec v_or(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return __riscv_vor(a, b, vl); \ -} \ -inline _Tpvec v_xor(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return __riscv_vxor(a, b, vl); \ -} \ -inline _Tpvec v_not (const _Tpvec& a) \ -{ \ - return __riscv_vnot(a, vl); \ -} - -OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_uint8, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_int8, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_uint16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_int16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_uint32, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_int32, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_uint64, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_int64, VTraits::vlanes()) - -#define OPENCV_HAL_IMPL_RVV_FLT_BIT_OP(intrin) \ -inline v_float32 intrin (const v_float32& a, const v_float32& b) \ -{ \ - return __riscv_vreinterpret_f32m2(intrin(__riscv_vreinterpret_i32m2(a), __riscv_vreinterpret_i32m2(b))); \ -} -OPENCV_HAL_IMPL_RVV_FLT_BIT_OP(v_and) -OPENCV_HAL_IMPL_RVV_FLT_BIT_OP(v_or) -OPENCV_HAL_IMPL_RVV_FLT_BIT_OP(v_xor) - -inline v_float32 v_not (const v_float32& a) \ -{ \ - return __riscv_vreinterpret_f32m2(v_not(__riscv_vreinterpret_i32m2(a))); \ -} - -#if CV_SIMD_SCALABLE_64F -#define OPENCV_HAL_IMPL_RVV_FLT64_BIT_OP(intrin) \ -inline v_float64 intrin (const v_float64& a, const v_float64& b) \ -{ \ - return __riscv_vreinterpret_f64m2(intrin(__riscv_vreinterpret_i64m2(a), __riscv_vreinterpret_i64m2(b))); \ -} -OPENCV_HAL_IMPL_RVV_FLT64_BIT_OP(v_and) -OPENCV_HAL_IMPL_RVV_FLT64_BIT_OP(v_or) -OPENCV_HAL_IMPL_RVV_FLT64_BIT_OP(v_xor) - -inline v_float64 v_not (const v_float64& a) \ -{ \ - return __riscv_vreinterpret_f64m2(v_not(__riscv_vreinterpret_i64m2(a))); \ -} -#endif - - -////////////// Bitwise shifts ////////////// -/* Usage -1. v_shl(vec); -2. v_shl(vec, N); // instead of vec << N, when N is non-constant. -*/ - -#define OPENCV_HAL_IMPL_RVV_UNSIGNED_SHIFT_OP(_Tpvec, vl) \ -template inline _Tpvec v_shl(const _Tpvec& a, int n = s) \ -{ \ - return _Tpvec(__riscv_vsll(a, uint8_t(n), vl)); \ -} \ -template inline _Tpvec v_shr(const _Tpvec& a, int n = s) \ -{ \ - return _Tpvec(__riscv_vsrl(a, uint8_t(n), vl)); \ -} - -#define OPENCV_HAL_IMPL_RVV_SIGNED_SHIFT_OP(_Tpvec, vl) \ -template inline _Tpvec v_shl(const _Tpvec& a, int n = s) \ -{ \ - return _Tpvec(__riscv_vsll(a, uint8_t(n), vl)); \ -} \ -template inline _Tpvec v_shr(const _Tpvec& a, int n = s) \ -{ \ - return _Tpvec(__riscv_vsra(a, uint8_t(n), vl)); \ -} - -OPENCV_HAL_IMPL_RVV_UNSIGNED_SHIFT_OP(v_uint16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_UNSIGNED_SHIFT_OP(v_uint32, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_UNSIGNED_SHIFT_OP(v_uint64, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_SIGNED_SHIFT_OP(v_int16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_SIGNED_SHIFT_OP(v_int32, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_SIGNED_SHIFT_OP(v_int64, VTraits::vlanes()) - -////////////// Comparison ////////////// -#define OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, op, intrin, suffix) \ -inline _Tpvec v_##op(const _Tpvec& a, const _Tpvec& b) \ -{ \ - size_t VLEN = VTraits<_Tpvec>::vlanes(); \ - uint64_t ones = -1; \ - return __riscv_vmerge(__riscv_vmv_v_x_##suffix##m2(0, VLEN), ones, intrin(a, b, VLEN), VLEN); \ -} - -#define OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, op, intrin, suffix) \ -inline _Tpvec v_##op (const _Tpvec& a, const _Tpvec& b) \ -{ \ - size_t VLEN = VTraits<_Tpvec>::vlanes(); \ - union { uint64_t u; VTraits<_Tpvec>::lane_type d; } ones; \ - ones.u = -1; \ - auto diff = intrin(a, b, VLEN); \ - auto z = __riscv_vfmv_v_f_##suffix##m2(0, VLEN); \ - auto res = __riscv_vfmerge(z, ones.d, diff, VLEN); \ - return _Tpvec(res); \ -} //TODO - -#define OPENCV_HAL_IMPL_RVV_UNSIGNED_CMP(_Tpvec, suffix) \ -OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, eq, __riscv_vmseq, suffix) \ -OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, ne, __riscv_vmsne, suffix) \ -OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, lt, __riscv_vmsltu, suffix) \ -OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, gt, __riscv_vmsgtu, suffix) \ -OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, le, __riscv_vmsleu, suffix) \ -OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, ge, __riscv_vmsgeu, suffix) - -#define OPENCV_HAL_IMPL_RVV_SIGNED_CMP(_Tpvec, suffix) \ -OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, eq, __riscv_vmseq, suffix) \ -OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, ne, __riscv_vmsne, suffix) \ -OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, lt, __riscv_vmslt, suffix) \ -OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, gt, __riscv_vmsgt, suffix) \ -OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, le, __riscv_vmsle, suffix) \ -OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, ge, __riscv_vmsge, suffix) - -#define OPENCV_HAL_IMPL_RVV_FLOAT_CMP(_Tpvec, suffix) \ -OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, eq, __riscv_vmfeq, suffix) \ -OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, ne, __riscv_vmfne, suffix) \ -OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, lt, __riscv_vmflt, suffix) \ -OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, gt, __riscv_vmfgt, suffix) \ -OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, le, __riscv_vmfle, suffix) \ -OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, ge, __riscv_vmfge, suffix) - - -OPENCV_HAL_IMPL_RVV_UNSIGNED_CMP(v_uint8, u8) -OPENCV_HAL_IMPL_RVV_UNSIGNED_CMP(v_uint16, u16) -OPENCV_HAL_IMPL_RVV_UNSIGNED_CMP(v_uint32, u32) -OPENCV_HAL_IMPL_RVV_UNSIGNED_CMP(v_uint64, u64) -OPENCV_HAL_IMPL_RVV_SIGNED_CMP(v_int8, i8) -OPENCV_HAL_IMPL_RVV_SIGNED_CMP(v_int16, i16) -OPENCV_HAL_IMPL_RVV_SIGNED_CMP(v_int32, i32) -OPENCV_HAL_IMPL_RVV_SIGNED_CMP(v_int64, i64) -OPENCV_HAL_IMPL_RVV_FLOAT_CMP(v_float32, f32) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_FLOAT_CMP(v_float64, f64) -#endif - -inline v_float32 v_not_nan(const v_float32& a) -{ return v_eq(a, a); } - -#if CV_SIMD_SCALABLE_64F -inline v_float64 v_not_nan(const v_float64& a) -{ return v_eq(a, a); } -#endif - -////////////// Min/Max ////////////// - -#define OPENCV_HAL_IMPL_RVV_BIN_FUNC(_Tpvec, func, intrin, vl) \ -inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return intrin(a, b, vl); \ -} - -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_uint8, v_min, __riscv_vminu, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_uint8, v_max, __riscv_vmaxu, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_int8, v_min, __riscv_vmin, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_int8, v_max, __riscv_vmax, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_uint16, v_min, __riscv_vminu, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_uint16, v_max, __riscv_vmaxu, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_int16, v_min, __riscv_vmin, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_int16, v_max, __riscv_vmax, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_uint32, v_min, __riscv_vminu, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_uint32, v_max, __riscv_vmaxu, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_int32, v_min, __riscv_vmin, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_int32, v_max, __riscv_vmax, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_float32, v_min, __riscv_vfmin, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_float32, v_max, __riscv_vfmax, VTraits::vlanes()) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_float64, v_min, __riscv_vfmin, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_float64, v_max, __riscv_vfmax, VTraits::vlanes()) -#endif - -////////////// Transpose4x4 ////////////// -#define OPENCV_HAL_IMPL_RVV_ZIP4(_Tpvec, _wTpvec, suffix, convert2u, convert) \ -inline void v_zip4(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) { \ - int vl = 4; \ - _wTpvec temp = __riscv_vreinterpret_##suffix##m4(convert2u( \ - __riscv_vor(__riscv_vzext_vf2(convert(a0), vl), \ - __riscv_vreinterpret_u64m4(__riscv_vslide1up(__riscv_vreinterpret_u32m4(__riscv_vzext_vf2(convert(a1), vl)), 0, vl*2)), \ - vl))); \ - b0 = __riscv_vget_##suffix##m2(temp, 0); \ - b1 = __riscv_vget_##suffix##m2(__riscv_vrgather(temp, __riscv_vadd(__riscv_vid_v_u32m4(vl), 4, vl)/*{4,5,6,7} */, vl) ,0); \ -} - -OPENCV_HAL_IMPL_RVV_ZIP4(v_uint32, vuint32m4_t, u32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_RVV_ZIP4(v_int32, vint32m4_t, i32, __riscv_vreinterpret_u32m4, __riscv_vreinterpret_u32m2) -OPENCV_HAL_IMPL_RVV_ZIP4(v_float32, vfloat32m4_t, f32, __riscv_vreinterpret_u32m4, __riscv_vreinterpret_u32m2) - - -#define OPENCV_HAL_IMPL_RVV_TRANSPOSE4x4(_Tpvec, suffix) \ -inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, const _Tpvec& a2, const _Tpvec& a3, _Tpvec& b0, _Tpvec& b1, _Tpvec& b2, _Tpvec& b3) { \ - _Tpvec t0,t1,t2,t3; \ - v_zip4(a0, a2, t0, t2); \ - v_zip4(a1, a3, t1, t3); \ - v_zip4(t0, t1, b0, b1); \ - v_zip4(t2, t3, b2, b3); \ -} - -OPENCV_HAL_IMPL_RVV_TRANSPOSE4x4(v_uint32, u32) -OPENCV_HAL_IMPL_RVV_TRANSPOSE4x4(v_int32, i32) -OPENCV_HAL_IMPL_RVV_TRANSPOSE4x4(v_float32, f32) - -////////////// Reduce ////////////// - -#define OPENCV_HAL_IMPL_RVV_REDUCE_SUM(_Tpvec, _wTpvec, _nwTpvec, scalartype, wsuffix, vl, red) \ -inline scalartype v_reduce_sum(const _Tpvec& a) \ -{ \ - _nwTpvec zero = __riscv_vmv_v_x_##wsuffix##m1(0, vl); \ - _nwTpvec res = __riscv_vmv_v_x_##wsuffix##m1(0, vl); \ - res = __riscv_v##red(a, zero, vl); \ - return (scalartype)__riscv_vmv_x(res); \ -} -OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_uint8, v_uint16, vuint16m1_t, unsigned, u16, VTraits::vlanes(), wredsumu) -OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_int8, v_int16, vint16m1_t, int, i16, VTraits::vlanes(), wredsum) -OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_uint16, v_uint32, vuint32m1_t, unsigned, u32, VTraits::vlanes(), wredsumu) -OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_int16, v_int32, vint32m1_t, int, i32, VTraits::vlanes(), wredsum) -OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_uint32, v_uint64, vuint64m1_t, unsigned, u64, VTraits::vlanes(), wredsumu) -OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_int32, v_int64, vint64m1_t, int, i64, VTraits::vlanes(), wredsum) -OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_uint64, v_uint64, vuint64m1_t, uint64, u64, VTraits::vlanes(), redsum) -OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_int64, v_int64, vint64m1_t, int64, i64, VTraits::vlanes(), redsum) - - -#define OPENCV_HAL_IMPL_RVV_REDUCE_SUM_FP(_Tpvec, _wTpvec, _nwTpvec, scalartype, wsuffix, vl) \ -inline scalartype v_reduce_sum(const _Tpvec& a) \ -{ \ - _nwTpvec zero = __riscv_vfmv_v_f_##wsuffix##m1(0, vl); \ - _nwTpvec res = __riscv_vfmv_v_f_##wsuffix##m1(0, vl); \ - res = __riscv_vfredusum(a, zero, vl); \ - return (scalartype)__riscv_vfmv_f(res); \ -} -OPENCV_HAL_IMPL_RVV_REDUCE_SUM_FP(v_float32, v_float32, vfloat32m1_t, float, f32, VTraits::vlanes()) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_REDUCE_SUM_FP(v_float64, v_float64, vfloat64m1_t, float, f64, VTraits::vlanes()) -#endif - -#define OPENCV_HAL_IMPL_RVV_REDUCE(_Tpvec, _nTpvec, func, scalartype, suffix, vl, red) \ -inline scalartype v_reduce_##func(const _Tpvec& a) \ -{ \ - _nTpvec narrowM1 = __riscv_vlmul_trunc_##suffix##m1(a); \ - return (scalartype)__riscv_vmv_x(__riscv_v##red(a, narrowM1, vl)); \ -} - -#define OPENCV_HAL_IMPL_RVV_REDUCE_FP(_Tpvec, _nTpvec, func, scalartype, suffix, vl, red) \ -inline scalartype v_reduce_##func(const _Tpvec& a) \ -{ \ - _nTpvec narrowM1 = __riscv_vlmul_trunc_##suffix##m1(a); \ - return (scalartype)__riscv_vfmv_f(__riscv_v##red(a, narrowM1, vl)); \ -} - -OPENCV_HAL_IMPL_RVV_REDUCE(v_uint8, vuint8m1_t, min, uchar, u8, VTraits::vlanes(), redminu) -OPENCV_HAL_IMPL_RVV_REDUCE(v_int8, vint8m1_t, min, schar, i8, VTraits::vlanes(), redmin) -OPENCV_HAL_IMPL_RVV_REDUCE(v_uint16, vuint16m1_t, min, ushort, u16, VTraits::vlanes(), redminu) -OPENCV_HAL_IMPL_RVV_REDUCE(v_int16, vint16m1_t, min, short, i16, VTraits::vlanes(), redmin) -OPENCV_HAL_IMPL_RVV_REDUCE(v_uint32, vuint32m1_t, min, unsigned, u32, VTraits::vlanes(), redminu) -OPENCV_HAL_IMPL_RVV_REDUCE(v_int32, vint32m1_t, min, int, i32, VTraits::vlanes(), redmin) -OPENCV_HAL_IMPL_RVV_REDUCE_FP(v_float32, vfloat32m1_t, min, float, f32, VTraits::vlanes(), fredmin) -OPENCV_HAL_IMPL_RVV_REDUCE(v_uint8, vuint8m1_t, max, uchar, u8, VTraits::vlanes(), redmaxu) -OPENCV_HAL_IMPL_RVV_REDUCE(v_int8, vint8m1_t, max, schar, i8, VTraits::vlanes(), redmax) -OPENCV_HAL_IMPL_RVV_REDUCE(v_uint16, vuint16m1_t, max, ushort, u16, VTraits::vlanes(), redmaxu) -OPENCV_HAL_IMPL_RVV_REDUCE(v_int16, vint16m1_t, max, short, i16, VTraits::vlanes(), redmax) -OPENCV_HAL_IMPL_RVV_REDUCE(v_uint32, vuint32m1_t, max, unsigned, u32, VTraits::vlanes(), redmaxu) -OPENCV_HAL_IMPL_RVV_REDUCE(v_int32, vint32m1_t, max, int, i32, VTraits::vlanes(), redmax) -OPENCV_HAL_IMPL_RVV_REDUCE_FP(v_float32, vfloat32m1_t, max, float, f32, VTraits::vlanes(), fredmax) - -inline v_float32 v_reduce_sum4(const v_float32& a, const v_float32& b, - const v_float32& c, const v_float32& d) -{ - // 0000 1111 2222 3333 .... - vuint64m4_t vid1 = __riscv_vid_v_u64m4(VTraits::vlanes()); - vuint16m4_t t1 = __riscv_vreinterpret_u16m4(vid1); - vuint16m4_t t2 = __riscv_vslide1up(t1, 0, VTraits::vlanes()); - vuint16m4_t t3 = __riscv_vslide1up(t2, 0, VTraits::vlanes()); - vuint16m4_t t4 = __riscv_vslide1up(t3, 0, VTraits::vlanes()); - t1 = __riscv_vor( - __riscv_vor(t1, t2, VTraits::vlanes()), - __riscv_vor(t3, t4, VTraits::vlanes()), - VTraits::vlanes() - ); - - // index for transpose4X4 - vuint16m4_t vidx0 = __riscv_vmul(t1, 12, VTraits::vlanes()); - vidx0 = __riscv_vadd(vidx0, __riscv_vid_v_u16m4(VTraits::vlanes()), VTraits::vlanes()); - vuint16m4_t vidx1 = __riscv_vadd(vidx0, 4, VTraits::vlanes()); - vuint16m4_t vidx2 = __riscv_vadd(vidx0, 8, VTraits::vlanes()); - vuint16m4_t vidx3 = __riscv_vadd(vidx0, 12, VTraits::vlanes()); - - // zip - vuint32m4_t tempA = __riscv_vreinterpret_u32m4( \ - __riscv_vor(__riscv_vzext_vf2(__riscv_vreinterpret_u32m2(a), VTraits::vlanes()), \ - __riscv_vreinterpret_u64m4(__riscv_vslide1up(__riscv_vreinterpret_u32m4(__riscv_vzext_vf2(__riscv_vreinterpret_u32m2(c), VTraits::vlanes())), 0, VTraits::vlanes())), \ - VTraits::vlanes())); \ - vuint32m4_t tempB = __riscv_vreinterpret_u32m4( \ - __riscv_vor(__riscv_vzext_vf2(__riscv_vreinterpret_u32m2(b), VTraits::vlanes()), \ - __riscv_vreinterpret_u64m4(__riscv_vslide1up(__riscv_vreinterpret_u32m4(__riscv_vzext_vf2(__riscv_vreinterpret_u32m2(d), VTraits::vlanes())), 0, VTraits::vlanes())), \ - VTraits::vlanes())); \ - vfloat32m8_t temp = __riscv_vreinterpret_f32m8(__riscv_vreinterpret_u32m8( \ - __riscv_vor(__riscv_vzext_vf2(tempA, VTraits::vlanes()), \ - __riscv_vreinterpret_u64m8(__riscv_vslide1up(__riscv_vreinterpret_u32m8(__riscv_vzext_vf2(tempB, VTraits::vlanes())), 0, VTraits::vlanes())), \ - VTraits::vlanes()))); - - // transpose - vfloat32m2_t b0 = __riscv_vlmul_trunc_f32m2(__riscv_vrgatherei16(temp, vidx0, VTraits::vlanes())); - vfloat32m2_t b1 = __riscv_vlmul_trunc_f32m2(__riscv_vrgatherei16(temp, vidx1, VTraits::vlanes())); - vfloat32m2_t b2 = __riscv_vlmul_trunc_f32m2(__riscv_vrgatherei16(temp, vidx2, VTraits::vlanes())); - vfloat32m2_t b3 = __riscv_vlmul_trunc_f32m2(__riscv_vrgatherei16(temp, vidx3, VTraits::vlanes())); - - // vector add - v_float32 res = __riscv_vfadd( - __riscv_vfadd(b0, b1, VTraits::vlanes()), - __riscv_vfadd(b2, b3, VTraits::vlanes()), - VTraits::vlanes() - ); - return res; -} - -////////////// Square-Root ////////////// - -inline v_float32 v_sqrt(const v_float32& x) -{ - return __riscv_vfsqrt(x, VTraits::vlanes()); -} - -inline v_float32 v_invsqrt(const v_float32& x) -{ - v_float32 one = v_setall_f32(1.0f); - return v_div(one, v_sqrt(x)); -} - -#if CV_SIMD_SCALABLE_64F -inline v_float64 v_sqrt(const v_float64& x) -{ - return __riscv_vfsqrt(x, VTraits::vlanes()); -} - -inline v_float64 v_invsqrt(const v_float64& x) -{ - v_float64 one = v_setall_f64(1.0f); - return v_div(one, v_sqrt(x)); -} -#endif - -inline v_float32 v_magnitude(const v_float32& a, const v_float32& b) -{ - v_float32 x = __riscv_vfmacc(__riscv_vfmul(a, a, VTraits::vlanes()), b, b, VTraits::vlanes()); - return v_sqrt(x); -} - -inline v_float32 v_sqr_magnitude(const v_float32& a, const v_float32& b) -{ - return v_float32(__riscv_vfmacc(__riscv_vfmul(a, a, VTraits::vlanes()), b, b, VTraits::vlanes())); -} - -#if CV_SIMD_SCALABLE_64F -inline v_float64 v_magnitude(const v_float64& a, const v_float64& b) -{ - v_float64 x = __riscv_vfmacc(__riscv_vfmul(a, a, VTraits::vlanes()), b, b, VTraits::vlanes()); - return v_sqrt(x); -} - -inline v_float64 v_sqr_magnitude(const v_float64& a, const v_float64& b) -{ - return __riscv_vfmacc(__riscv_vfmul(a, a, VTraits::vlanes()), b, b, VTraits::vlanes()); -} -#endif - -////////////// Multiply-Add ////////////// - -inline v_float32 v_fma(const v_float32& a, const v_float32& b, const v_float32& c) -{ - return __riscv_vfmacc(c, a, b, VTraits::vlanes()); -} -inline v_int32 v_fma(const v_int32& a, const v_int32& b, const v_int32& c) -{ - return __riscv_vmacc(c, a, b, VTraits::vlanes()); -} - -inline v_float32 v_muladd(const v_float32& a, const v_float32& b, const v_float32& c) -{ - return v_fma(a, b, c); -} - -inline v_int32 v_muladd(const v_int32& a, const v_int32& b, const v_int32& c) -{ - return v_fma(a, b, c); -} - -#if CV_SIMD_SCALABLE_64F -inline v_float64 v_fma(const v_float64& a, const v_float64& b, const v_float64& c) -{ - return __riscv_vfmacc_vv_f64m2(c, a, b, VTraits::vlanes()); -} - -inline v_float64 v_muladd(const v_float64& a, const v_float64& b, const v_float64& c) -{ - return v_fma(a, b, c); -} -#endif - -////////////// Check all/any ////////////// - -#define OPENCV_HAL_IMPL_RVV_CHECK_ALLANY(_Tpvec, vl) \ -inline bool v_check_all(const _Tpvec& a) \ -{ \ - return (int)__riscv_vcpop(__riscv_vmslt(a, 0, vl), vl) == vl; \ -} \ -inline bool v_check_any(const _Tpvec& a) \ -{ \ - return (int)__riscv_vcpop(__riscv_vmslt(a, 0, vl), vl) != 0; \ -} - -OPENCV_HAL_IMPL_RVV_CHECK_ALLANY(v_int8, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_CHECK_ALLANY(v_int16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_CHECK_ALLANY(v_int32, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_CHECK_ALLANY(v_int64, VTraits::vlanes()) - - -inline bool v_check_all(const v_uint8& a) -{ return v_check_all(v_reinterpret_as_s8(a)); } -inline bool v_check_any(const v_uint8& a) -{ return v_check_any(v_reinterpret_as_s8(a)); } - -inline bool v_check_all(const v_uint16& a) -{ return v_check_all(v_reinterpret_as_s16(a)); } -inline bool v_check_any(const v_uint16& a) -{ return v_check_any(v_reinterpret_as_s16(a)); } - -inline bool v_check_all(const v_uint32& a) -{ return v_check_all(v_reinterpret_as_s32(a)); } -inline bool v_check_any(const v_uint32& a) -{ return v_check_any(v_reinterpret_as_s32(a)); } - -inline bool v_check_all(const v_float32& a) -{ return v_check_all(v_reinterpret_as_s32(a)); } -inline bool v_check_any(const v_float32& a) -{ return v_check_any(v_reinterpret_as_s32(a)); } - -inline bool v_check_all(const v_uint64& a) -{ return v_check_all(v_reinterpret_as_s64(a)); } -inline bool v_check_any(const v_uint64& a) -{ return v_check_any(v_reinterpret_as_s64(a)); } - -#if CV_SIMD_SCALABLE_64F -inline bool v_check_all(const v_float64& a) -{ return v_check_all(v_reinterpret_as_s64(a)); } -inline bool v_check_any(const v_float64& a) -{ return v_check_any(v_reinterpret_as_s64(a)); } -#endif - -////////////// abs ////////////// - -#define OPENCV_HAL_IMPL_RVV_ABSDIFF(_Tpvec, abs) \ -inline _Tpvec v_##abs(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return v_sub(v_max(a, b), v_min(a, b)); \ -} - -OPENCV_HAL_IMPL_RVV_ABSDIFF(v_uint8, absdiff) -OPENCV_HAL_IMPL_RVV_ABSDIFF(v_uint16, absdiff) -OPENCV_HAL_IMPL_RVV_ABSDIFF(v_uint32, absdiff) -OPENCV_HAL_IMPL_RVV_ABSDIFF(v_float32, absdiff) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_ABSDIFF(v_float64, absdiff) -#endif -OPENCV_HAL_IMPL_RVV_ABSDIFF(v_int8, absdiffs) -OPENCV_HAL_IMPL_RVV_ABSDIFF(v_int16, absdiffs) - -#define OPENCV_HAL_IMPL_RVV_ABSDIFF_S(_Tpvec, _rTpvec, width) \ -inline _rTpvec v_absdiff(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return __riscv_vnclipu(__riscv_vreinterpret_u##width##m4(__riscv_vwsub_vv(v_max(a, b), v_min(a, b), VTraits<_Tpvec>::vlanes())), 0, 0, VTraits<_Tpvec>::vlanes()); \ -} - -OPENCV_HAL_IMPL_RVV_ABSDIFF_S(v_int8, v_uint8, 16) -OPENCV_HAL_IMPL_RVV_ABSDIFF_S(v_int16, v_uint16, 32) -OPENCV_HAL_IMPL_RVV_ABSDIFF_S(v_int32, v_uint32, 64) - -#define OPENCV_HAL_IMPL_RVV_ABS(_Tprvec, _Tpvec, suffix) \ -inline _Tprvec v_abs(const _Tpvec& a) \ -{ \ - return v_absdiff(a, v_setzero_##suffix()); \ -} - -OPENCV_HAL_IMPL_RVV_ABS(v_uint8, v_int8, s8) -OPENCV_HAL_IMPL_RVV_ABS(v_uint16, v_int16, s16) -OPENCV_HAL_IMPL_RVV_ABS(v_uint32, v_int32, s32) -OPENCV_HAL_IMPL_RVV_ABS(v_float32, v_float32, f32) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_ABS(v_float64, v_float64, f64) -#endif - - -#define OPENCV_HAL_IMPL_RVV_REDUCE_SAD(_Tpvec, scalartype) \ -inline scalartype v_reduce_sad(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return v_reduce_sum(v_absdiff(a, b)); \ -} - -OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_uint8, unsigned) -OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_int8, unsigned) -OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_uint16, unsigned) -OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_int16, unsigned) -OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_uint32, unsigned) -OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_int32, unsigned) -OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_float32, float) - -////////////// Select ////////////// - -#define OPENCV_HAL_IMPL_RVV_SELECT(_Tpvec, vl) \ -inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ -{ \ - return __riscv_vmerge(b, a, __riscv_vmsne(mask, 0, vl), vl); \ -} - -OPENCV_HAL_IMPL_RVV_SELECT(v_uint8, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_SELECT(v_uint16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_SELECT(v_uint32, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_SELECT(v_int8, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_SELECT(v_int16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_SELECT(v_int32, VTraits::vlanes()) - -inline v_float32 v_select(const v_float32& mask, const v_float32& a, const v_float32& b) \ -{ \ - return __riscv_vmerge(b, a, __riscv_vmfne(mask, 0, VTraits::vlanes()), VTraits::vlanes()); \ -} - -#if CV_SIMD_SCALABLE_64F -inline v_float64 v_select(const v_float64& mask, const v_float64& a, const v_float64& b) \ -{ \ - return __riscv_vmerge(b, a, __riscv_vmfne(mask, 0, VTraits::vlanes()), VTraits::vlanes()); \ -} -#endif - -////////////// Rotate shift ////////////// - -#define OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(_Tpvec, suffix, vl) \ -template inline _Tpvec v_rotate_right(const _Tpvec& a) \ -{ \ - return __riscv_vslidedown(a, n, vl); \ -} \ -template inline _Tpvec v_rotate_left(const _Tpvec& a) \ -{ \ - return __riscv_vslideup(__riscv_vmv_v_x_##suffix##m2(0, vl), a, n, vl); \ -} \ -template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a) \ -{ return a; } \ -template inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return __riscv_vslideup(__riscv_vslidedown(a, n, vl), b, VTraits<_Tpvec>::vlanes() - n, vl); \ -} \ -template inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return __riscv_vslideup(__riscv_vslidedown(b, VTraits<_Tpvec>::vlanes() - n, vl), a, n, vl); \ -} \ -template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a, const _Tpvec& b) \ -{ CV_UNUSED(b); return a; } - -OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_uint8, u8, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_int8, i8, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_uint16, u16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_int16, i16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_uint32, u32, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_int32, i32, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_uint64, u64, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_int64, i64, VTraits::vlanes()) - -#define OPENCV_HAL_IMPL_RVV_ROTATE_FP(_Tpvec, suffix, vl) \ -template inline _Tpvec v_rotate_right(const _Tpvec& a) \ -{ \ - return __riscv_vslidedown(a, n, vl); \ -} \ -template inline _Tpvec v_rotate_left(const _Tpvec& a) \ -{ \ - return __riscv_vslideup(__riscv_vfmv_v_f_##suffix##m2(0, vl), a, n, vl); \ -} \ -template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a) \ -{ return a; } \ -template inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return __riscv_vslideup(__riscv_vslidedown(a, n, vl), b, VTraits<_Tpvec>::vlanes() - n, vl); \ -} \ -template inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return __riscv_vslideup(__riscv_vslidedown(b, VTraits<_Tpvec>::vlanes() - n, vl), a, n, vl); \ -} \ -template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a, const _Tpvec& b) \ -{ CV_UNUSED(b); return a; } - -OPENCV_HAL_IMPL_RVV_ROTATE_FP(v_float32, f32, VTraits::vlanes()) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_ROTATE_FP(v_float64, f64, VTraits::vlanes()) -#endif - -////////////// Convert to float ////////////// -inline v_float32 v_cvt_f32(const v_int32& a) -{ - return __riscv_vfcvt_f_x_v_f32m2(a, VTraits::vlanes()); -} - -#if CV_SIMD_SCALABLE_64F -inline v_float32 v_cvt_f32(const v_float64& a) -{ - return __riscv_vfncvt_f(__riscv_vlmul_ext_f64m4(a), VTraits::vlanes()); -} - -inline v_float32 v_cvt_f32(const v_float64& a, const v_float64& b) -{ - return __riscv_vfncvt_f(__riscv_vset(__riscv_vlmul_ext_f64m4(a),1,b), VTraits::vlanes()); -} - -inline v_float64 v_cvt_f64(const v_int32& a) -{ - return __riscv_vget_f64m2(__riscv_vfwcvt_f(a, VTraits::vlanes()), 0); -} - -inline v_float64 v_cvt_f64_high(const v_int32& a) -{ - return __riscv_vget_f64m2(__riscv_vfwcvt_f(a, VTraits::vlanes()), 1); -} - -inline v_float64 v_cvt_f64(const v_float32& a) -{ - return __riscv_vget_f64m2(__riscv_vfwcvt_f(a, VTraits::vlanes()), 0); -} - -inline v_float64 v_cvt_f64_high(const v_float32& a) -{ - return __riscv_vget_f64m2(__riscv_vfwcvt_f(a, VTraits::vlanes()), 1); -} - -inline v_float64 v_cvt_f64(const v_int64& a) -{ - return __riscv_vfcvt_f(a, VTraits::vlanes()); -} -#endif - -//////////// Broadcast ////////////// - -#define OPENCV_HAL_IMPL_RVV_BROADCAST(_Tpvec, suffix) \ -template inline _Tpvec v_broadcast_element(_Tpvec v, int i = s) \ -{ \ - return v_setall_##suffix(v_extract_n(v, i)); \ -} \ -inline _Tpvec v_broadcast_highest(_Tpvec v) \ -{ \ - return v_setall_##suffix(v_extract_n(v, VTraits<_Tpvec>::vlanes()-1)); \ -} - -OPENCV_HAL_IMPL_RVV_BROADCAST(v_uint32, u32) -OPENCV_HAL_IMPL_RVV_BROADCAST(v_int32, s32) -OPENCV_HAL_IMPL_RVV_BROADCAST(v_float32, f32) - - -////////////// Reverse ////////////// -#define OPENCV_HAL_IMPL_RVV_REVERSE(_Tpvec, width) \ -inline _Tpvec v_reverse(const _Tpvec& a) \ -{ \ - vuint##width##m2_t vidx = __riscv_vrsub(__riscv_vid_v_u##width##m2(VTraits<_Tpvec>::vlanes()), VTraits<_Tpvec>::vlanes()-1, VTraits<_Tpvec>::vlanes()); \ - return __riscv_vrgather(a, vidx, VTraits<_Tpvec>::vlanes()); \ -} -OPENCV_HAL_IMPL_RVV_REVERSE(v_uint8, 8) -OPENCV_HAL_IMPL_RVV_REVERSE(v_int8, 8) -OPENCV_HAL_IMPL_RVV_REVERSE(v_uint16, 16) -OPENCV_HAL_IMPL_RVV_REVERSE(v_int16, 16) -OPENCV_HAL_IMPL_RVV_REVERSE(v_uint32, 32) -OPENCV_HAL_IMPL_RVV_REVERSE(v_int32, 32) -OPENCV_HAL_IMPL_RVV_REVERSE(v_float32, 32) -OPENCV_HAL_IMPL_RVV_REVERSE(v_uint64, 64) -OPENCV_HAL_IMPL_RVV_REVERSE(v_int64, 64) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_REVERSE(v_float64, 64) -#endif - -//////////// Value reordering //////////// - -#define OPENCV_HAL_IMPL_RVV_EXPAND(_Tp, _Tpwvec, _Tpwvec_m2, _Tpvec, width, suffix, suffix2, cvt) \ -inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ -{ \ - _Tpwvec_m2 temp = cvt(a, VTraits<_Tpvec>::vlanes()); \ - b0 = __riscv_vget_##suffix##m2(temp, 0); \ - b1 = __riscv_vget_##suffix##m2(temp, 1); \ -} \ -inline _Tpwvec v_expand_low(const _Tpvec& a) \ -{ \ - _Tpwvec_m2 temp = cvt(a, VTraits<_Tpvec>::vlanes()); \ - return __riscv_vget_##suffix##m2(temp, 0); \ -} \ -inline _Tpwvec v_expand_high(const _Tpvec& a) \ -{ \ - _Tpwvec_m2 temp = cvt(a, VTraits<_Tpvec>::vlanes()); \ - return __riscv_vget_##suffix##m2(temp, 1); \ -} \ -inline _Tpwvec v_load_expand(const _Tp* ptr) \ -{ \ - return cvt(__riscv_vle##width##_v_##suffix2##m1(ptr, VTraits<_Tpvec>::vlanes()), VTraits<_Tpvec>::vlanes()); \ -} - -OPENCV_HAL_IMPL_RVV_EXPAND(uchar, v_uint16, vuint16m4_t, v_uint8, 8, u16, u8, __riscv_vwcvtu_x) -OPENCV_HAL_IMPL_RVV_EXPAND(schar, v_int16, vint16m4_t, v_int8, 8, i16, i8, __riscv_vwcvt_x) -OPENCV_HAL_IMPL_RVV_EXPAND(ushort, v_uint32, vuint32m4_t, v_uint16, 16, u32, u16, __riscv_vwcvtu_x) -OPENCV_HAL_IMPL_RVV_EXPAND(short, v_int32, vint32m4_t, v_int16, 16, i32, i16, __riscv_vwcvt_x) -OPENCV_HAL_IMPL_RVV_EXPAND(uint, v_uint64, vuint64m4_t, v_uint32, 32, u64, u32, __riscv_vwcvtu_x) -OPENCV_HAL_IMPL_RVV_EXPAND(int, v_int64, vint64m4_t, v_int32, 32, i64, i32, __riscv_vwcvt_x) - -inline v_uint32 v_load_expand_q(const uchar* ptr) -{ - return __riscv_vwcvtu_x(__riscv_vwcvtu_x(__riscv_vle8_v_u8mf2(ptr, VTraits::vlanes()), VTraits::vlanes()), VTraits::vlanes()); -} - -inline v_int32 v_load_expand_q(const schar* ptr) -{ - return __riscv_vwcvt_x(__riscv_vwcvt_x(__riscv_vle8_v_i8mf2(ptr, VTraits::vlanes()), VTraits::vlanes()), VTraits::vlanes()); -} - -#define OPENCV_HAL_IMPL_RVV_PACK(_Tpvec, _Tp, _wTpvec, hwidth, hsuffix, suffix, rshr, shr) \ -inline _Tpvec v_pack(const _wTpvec& a, const _wTpvec& b) \ -{ \ - return shr(__riscv_vset(__riscv_vlmul_ext_##suffix##m4(a), 1, b), 0, 0, VTraits<_Tpvec>::vlanes()); \ -} \ -inline void v_pack_store(_Tp* ptr, const _wTpvec& a) \ -{ \ - __riscv_vse##hwidth##_v_##hsuffix##m1(ptr, shr(a, 0, 0, VTraits<_Tpvec>::vlanes()), VTraits<_wTpvec>::vlanes()); \ -} \ -template inline \ -_Tpvec v_rshr_pack(const _wTpvec& a, const _wTpvec& b, int N = n) \ -{ \ - return rshr(__riscv_vset(__riscv_vlmul_ext_##suffix##m4(a), 1, b), N, 0, VTraits<_Tpvec>::vlanes()); \ -} \ -template inline \ -void v_rshr_pack_store(_Tp* ptr, const _wTpvec& a, int N = n) \ -{ \ - __riscv_vse##hwidth##_v_##hsuffix##m1(ptr, rshr(a, N, 0, VTraits<_Tpvec>::vlanes()), VTraits<_wTpvec>::vlanes()); \ -} - -#define OPENCV_HAL_IMPL_RVV_PACK_32(_Tpvec, _Tp, _wTpvec, hwidth, hsuffix, suffix, rshr, shr) \ -inline _Tpvec v_pack(const _wTpvec& a, const _wTpvec& b) \ -{ \ - return shr(__riscv_vset(__riscv_vlmul_ext_##suffix##m4(a), 1, b), 0, VTraits<_Tpvec>::vlanes()); \ -} \ -inline void v_pack_store(_Tp* ptr, const _wTpvec& a) \ -{ \ - __riscv_vse##hwidth##_v_##hsuffix##m1(ptr, shr(a, 0, VTraits<_Tpvec>::vlanes()), VTraits<_wTpvec>::vlanes()); \ -} \ -template inline \ -_Tpvec v_rshr_pack(const _wTpvec& a, const _wTpvec& b, int N = n) \ -{ \ - return rshr(__riscv_vset(__riscv_vlmul_ext_##suffix##m4(a), 1, b), N, 0, VTraits<_Tpvec>::vlanes()); \ -} \ -template inline \ -void v_rshr_pack_store(_Tp* ptr, const _wTpvec& a, int N = n) \ -{ \ - __riscv_vse##hwidth##_v_##hsuffix##m1(ptr, rshr(a, N, 0, VTraits<_Tpvec>::vlanes()), VTraits<_wTpvec>::vlanes()); \ -} - -OPENCV_HAL_IMPL_RVV_PACK(v_uint8, uchar, v_uint16, 8, u8, u16, __riscv_vnclipu, __riscv_vnclipu) -OPENCV_HAL_IMPL_RVV_PACK(v_int8, schar, v_int16, 8, i8, i16, __riscv_vnclip, __riscv_vnclip) -OPENCV_HAL_IMPL_RVV_PACK(v_uint16, ushort, v_uint32, 16, u16, u32, __riscv_vnclipu, __riscv_vnclipu) -OPENCV_HAL_IMPL_RVV_PACK(v_int16, short, v_int32, 16, i16, i32, __riscv_vnclip, __riscv_vnclip) -OPENCV_HAL_IMPL_RVV_PACK_32(v_uint32, unsigned, v_uint64, 32, u32, u64, __riscv_vnclipu, __riscv_vnsrl) -OPENCV_HAL_IMPL_RVV_PACK_32(v_int32, int, v_int64, 32, i32, i64, __riscv_vnclip, __riscv_vnsra) - -#define OPENCV_HAL_IMPL_RVV_PACK_U(_Tpvec, _Tp, _wTpvec, _wTp, hwidth, width, hsuffix, suffix, cast, hvl, vl) \ -inline _Tpvec v_pack_u(const _wTpvec& a, const _wTpvec& b) \ -{ \ - return __riscv_vnclipu(cast(__riscv_vmax(__riscv_vset(__riscv_vlmul_ext_##suffix##m4(a), 1, b), 0, vl)), 0, 0, vl); \ -} \ -inline void v_pack_u_store(_Tp* ptr, const _wTpvec& a) \ -{ \ - __riscv_vse##hwidth##_v_##hsuffix##m1(ptr, __riscv_vnclipu(__riscv_vreinterpret_u##width##m2(__riscv_vmax(a, 0, vl)), 0, 0, vl), hvl); \ -} \ -template inline \ -_Tpvec v_rshr_pack_u(const _wTpvec& a, const _wTpvec& b, int n = N) \ -{ \ - return __riscv_vnclipu(cast(__riscv_vmax(__riscv_vset(__riscv_vlmul_ext_##suffix##m4(a), 1, b), 0, vl)), n, 0, vl); \ -} \ -template inline \ -void v_rshr_pack_u_store(_Tp* ptr, const _wTpvec& a, int n = N) \ -{ \ - __riscv_vse##hwidth##_v_##hsuffix##m1(ptr, __riscv_vnclipu(__riscv_vreinterpret_u##width##m2(__riscv_vmax(a, 0, vl)), n, 0, vl), hvl); \ -} - -OPENCV_HAL_IMPL_RVV_PACK_U(v_uint8, uchar, v_int16, short, 8, 16, u8, i16, __riscv_vreinterpret_v_i16m4_u16m4, VTraits::vlanes(), VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_PACK_U(v_uint16, ushort, v_int32, int, 16, 32, u16, i32, __riscv_vreinterpret_v_i32m4_u32m4, VTraits::vlanes(), VTraits::vlanes()) - - -/* void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) - a0 = {A1 A2 A3 A4} - a1 = {B1 B2 B3 B4} ---------------- - {A1 B1 A2 B2} and {A3 B3 A4 B4} -*/ - -#define OPENCV_HAL_IMPL_RVV_ZIP(_Tpvec, _wTpvec, suffix, width, width2, convert2um2, convert2um1) \ -inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) { \ - _wTpvec temp = __riscv_vreinterpret_##suffix##m4(convert2um2( \ - __riscv_vor(__riscv_vzext_vf2(convert2um1(a0), VTraits<_Tpvec>::vlanes()*2), \ - __riscv_vreinterpret_u##width2##m4(__riscv_vslide1up(__riscv_vreinterpret_u##width##m4(__riscv_vzext_vf2(convert2um1(a1), VTraits<_Tpvec>::vlanes()*2)), 0, VTraits<_Tpvec>::vlanes()*2)), \ - VTraits<_Tpvec>::vlanes()))); \ - b0 = __riscv_vget_##suffix##m2(temp, 0); \ - b1 = __riscv_vget_##suffix##m2(temp, 1); \ -} -OPENCV_HAL_IMPL_RVV_ZIP(v_uint8, vuint8m4_t, u8, 8, 16, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_RVV_ZIP(v_int8, vint8m4_t, i8, 8, 16, __riscv_vreinterpret_u8m4, __riscv_vreinterpret_u8m2) -OPENCV_HAL_IMPL_RVV_ZIP(v_uint16, vuint16m4_t, u16, 16, 32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_RVV_ZIP(v_int16, vint16m4_t, i16, 16, 32, __riscv_vreinterpret_u16m4, __riscv_vreinterpret_u16m2) -OPENCV_HAL_IMPL_RVV_ZIP(v_uint32, vuint32m4_t, u32, 32, 64, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_RVV_ZIP(v_int32, vint32m4_t, i32, 32, 64, __riscv_vreinterpret_u32m4, __riscv_vreinterpret_u32m2) -OPENCV_HAL_IMPL_RVV_ZIP(v_float32, vfloat32m4_t, f32, 32, 64, __riscv_vreinterpret_u32m4, __riscv_vreinterpret_u32m2) - -#if CV_SIMD_SCALABLE_64F -inline void v_zip(const v_float64& a0, const v_float64& a1, v_float64& b0, v_float64& b1) { \ - vuint16mf2_t idx0 = __riscv_vid_v_u16mf2(VTraits::vlanes()); - vuint16mf2_t idx1 = __riscv_vadd(idx0, VTraits::vlanes(), VTraits::vlanes()); - vuint16m1_t idx = __riscv_vreinterpret_u16m1(( \ - __riscv_vor(__riscv_vzext_vf2(idx0, VTraits::vlanes()), \ - __riscv_vreinterpret_u32m1(__riscv_vslide1up(__riscv_vreinterpret_u16m1(__riscv_vzext_vf2(idx1, VTraits::vlanes())), 0, VTraits::vlanes())), \ - VTraits::vlanes()))); -#if 0 - vfloat64m4_t temp = __riscv_vcreate_v_f64m2_f64m4(a0, a1); -#else // TODO: clean up when RVV Intrinsic is frozen. - vfloat64m4_t temp = __riscv_vlmul_ext_f64m4(a0); - temp = __riscv_vset(temp, 1, a1); -#endif - temp = __riscv_vrgatherei16(temp, idx, VTraits::vlanes()*2); - b0 = __riscv_vget_f64m2(temp, 0); \ - b1 = __riscv_vget_f64m2(temp, 1); \ -} -#endif - -#define OPENCV_HAL_IMPL_RVV_UNPACKS(_Tpvec, width) \ -inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return __riscv_vslideup(a, b, VTraits<_Tpvec>::vlanes()/2, VTraits<_Tpvec>::vlanes());\ -} \ -inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return __riscv_vslideup( \ - __riscv_vslidedown(a, VTraits<_Tpvec>::vlanes()/2, VTraits<_Tpvec>::vlanes()), \ - __riscv_vslidedown(b, VTraits<_Tpvec>::vlanes()/2, VTraits<_Tpvec>::vlanes()), \ - VTraits<_Tpvec>::vlanes()/2, \ - VTraits<_Tpvec>::vlanes()); \ -} \ -inline void v_recombine(const _Tpvec& a, const _Tpvec& b, _Tpvec& c, _Tpvec& d) \ -{ \ - c = v_combine_low(a, b); \ - d = v_combine_high(a, b); \ -} - -OPENCV_HAL_IMPL_RVV_UNPACKS(v_uint8, 8) -OPENCV_HAL_IMPL_RVV_UNPACKS(v_int8, 8) -OPENCV_HAL_IMPL_RVV_UNPACKS(v_uint16, 16) -OPENCV_HAL_IMPL_RVV_UNPACKS(v_int16, 16) -OPENCV_HAL_IMPL_RVV_UNPACKS(v_uint32, 32) -OPENCV_HAL_IMPL_RVV_UNPACKS(v_int32, 32) -OPENCV_HAL_IMPL_RVV_UNPACKS(v_float32, 32) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_UNPACKS(v_float64, 64) -#endif - -#define OPENCV_HAL_IMPL_RVV_INTERLEAVED(_Tpvec, _Tp, suffix, width, hwidth, vl) \ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b) \ -{ \ - a = __riscv_vlse##width##_v_##suffix##m2(ptr , sizeof(_Tp)*2, VTraits::vlanes()); \ - b = __riscv_vlse##width##_v_##suffix##m2(ptr+1, sizeof(_Tp)*2, VTraits::vlanes()); \ -}\ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, v_##_Tpvec& c) \ -{ \ - a = __riscv_vlse##width##_v_##suffix##m2(ptr , sizeof(_Tp)*3, VTraits::vlanes()); \ - b = __riscv_vlse##width##_v_##suffix##m2(ptr+1, sizeof(_Tp)*3, VTraits::vlanes()); \ - c = __riscv_vlse##width##_v_##suffix##m2(ptr+2, sizeof(_Tp)*3, VTraits::vlanes()); \ -} \ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, \ - v_##_Tpvec& c, v_##_Tpvec& d) \ -{ \ - \ - a = __riscv_vlse##width##_v_##suffix##m2(ptr , sizeof(_Tp)*4, VTraits::vlanes()); \ - b = __riscv_vlse##width##_v_##suffix##m2(ptr+1, sizeof(_Tp)*4, VTraits::vlanes()); \ - c = __riscv_vlse##width##_v_##suffix##m2(ptr+2, sizeof(_Tp)*4, VTraits::vlanes()); \ - d = __riscv_vlse##width##_v_##suffix##m2(ptr+3, sizeof(_Tp)*4, VTraits::vlanes()); \ -} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - __riscv_vsse##width(ptr, sizeof(_Tp)*2, a, VTraits::vlanes()); \ - __riscv_vsse##width(ptr+1, sizeof(_Tp)*2, b, VTraits::vlanes()); \ -} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ - const v_##_Tpvec& c, hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - __riscv_vsse##width(ptr, sizeof(_Tp)*3, a, VTraits::vlanes()); \ - __riscv_vsse##width(ptr+1, sizeof(_Tp)*3, b, VTraits::vlanes()); \ - __riscv_vsse##width(ptr+2, sizeof(_Tp)*3, c, VTraits::vlanes()); \ -} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ - const v_##_Tpvec& c, const v_##_Tpvec& d, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ -{ \ - __riscv_vsse##width(ptr, sizeof(_Tp)*4, a, VTraits::vlanes()); \ - __riscv_vsse##width(ptr+1, sizeof(_Tp)*4, b, VTraits::vlanes()); \ - __riscv_vsse##width(ptr+2, sizeof(_Tp)*4, c, VTraits::vlanes()); \ - __riscv_vsse##width(ptr+3, sizeof(_Tp)*4, d, VTraits::vlanes()); \ -} - -OPENCV_HAL_IMPL_RVV_INTERLEAVED(uint8, uchar, u8, 8, 4, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INTERLEAVED(int8, schar, i8, 8, 4, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INTERLEAVED(uint16, ushort, u16, 16, 8, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INTERLEAVED(int16, short, i16, 16, 8, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INTERLEAVED(uint32, unsigned, u32, 32, 16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INTERLEAVED(int32, int, i32, 32, 16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INTERLEAVED(float32, float, f32, 32, 16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INTERLEAVED(uint64, uint64, u64, 64, 32, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INTERLEAVED(int64, int64, i64, 64, 32, VTraits::vlanes()) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_INTERLEAVED(float64, double, f64, 64, 32, VTraits::vlanes()) -#endif - -static uint64_t idx_interleave_pairs[] = { \ - 0x0705060403010200, 0x0f0d0e0c0b090a08, 0x1715161413111210, 0x1f1d1e1c1b191a18, \ - 0x2725262423212220, 0x2f2d2e2c2b292a28, 0x3735363433313230, 0x3f3d3e3c3b393a38, \ - 0x4745464443414240, 0x4f4d4e4c4b494a48, 0x5755565453515250, 0x5f5d5e5c5b595a58, \ - 0x6765666463616260, 0x6f6d6e6c6b696a68, 0x7775767473717270, 0x7f7d7e7c7b797a78}; - -static uint64_t idx_interleave_quads[] = { \ - 0x0703060205010400, 0x0f0b0e0a0d090c08, 0x1713161215111410, 0x1f1b1e1a1d191c18, \ - 0x2723262225212420, 0x2f2b2e2a2d292c28, 0x3733363235313430, 0x3f3b3e3a3d393c38, \ - 0x4743464245414440, 0x4f4b4e4a4d494c48, 0x5753565255515450, 0x5f5b5e5a5d595c58, \ - 0x6763666265616460, 0x6f6b6e6a6d696c68, 0x7773767275717470, 0x7f7b7e7a7d797c78}; - -#define OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ_NOEXPEND(_Tpvec, func) \ -inline _Tpvec v_interleave_##func(const _Tpvec& vec) { \ - CV_CheckLE(VTraits<_Tpvec>::vlanes(), VTraits<_Tpvec>::max_nlanes, "RVV implementation only supports VLEN in the range [128, 1024]"); \ - vuint8m2_t vidx = __riscv_vundefined_u8m2();\ - vidx = __riscv_vreinterpret_u8m2(__riscv_vle64_v_u64m2(idx_interleave_##func, 16)); \ - return __riscv_vrgather(vec, vidx, VTraits::vlanes()); \ -} -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ_NOEXPEND(v_uint8, pairs) -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ_NOEXPEND(v_int8, pairs) -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ_NOEXPEND(v_uint8, quads) -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ_NOEXPEND(v_int8, quads) - -#define OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(_Tpvec, width, vzext_vfx, func) \ -inline _Tpvec v_interleave_##func(const _Tpvec& vec) { \ - CV_CheckLE(VTraits<_Tpvec>::vlanes(), VTraits<_Tpvec>::max_nlanes, "RVV implementation only supports VLEN in the range [128, 1024]"); \ - vuint##width##m2_t vidx = __riscv_vundefined_u##width##m2();\ - vidx = __riscv_vget_u##width##m2(vzext_vfx(__riscv_vreinterpret_u8m2(__riscv_vle64_v_u64m2(idx_interleave_##func, 16)), VTraits::vlanes()), 0); \ - return __riscv_vrgather(vec, vidx, VTraits<_Tpvec>::vlanes()); \ -} - -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_uint16, 16, __riscv_vzext_vf2, pairs) -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_int16, 16, __riscv_vzext_vf2, pairs) -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_uint32, 32, __riscv_vzext_vf4, pairs) -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_int32, 32, __riscv_vzext_vf4, pairs) -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_float32, 32, __riscv_vzext_vf4, pairs) - -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_uint16, 16, __riscv_vzext_vf2, quads) -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_int16, 16, __riscv_vzext_vf2, quads) -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_uint32, 32, __riscv_vzext_vf4, quads) -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_int32, 32, __riscv_vzext_vf4, quads) -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_float32, 32, __riscv_vzext_vf4, quads) - -//////////// PopCount ////////// -static const unsigned char popCountTable[256] = -{ - 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, -}; -#define OPENCV_HAL_IMPL_RVV_HADD(_Tpvec, _Tpvec2, _Tm2, width, width2, suffix, add) \ -static inline _Tpvec2 v_hadd(_Tpvec a) { \ - vuint##width2##m2_t oneX2 = __riscv_vmv_v_x_u##width2##m2(1, VTraits::vlanes()); \ - vuint##width##m2_t one = __riscv_vreinterpret_u##width##m2(oneX2); \ - _Tm2 res = add(a, __riscv_vslide1down(a, 0, VTraits::vlanes()), VTraits::vlanes()); \ - return __riscv_vget_##suffix##m2(__riscv_vcompress(res, __riscv_vmseq(one, 1, VTraits::vlanes()), VTraits::vlanes()), 0); \ -} -OPENCV_HAL_IMPL_RVV_HADD(v_uint8, v_uint16, vuint16m4_t, 8, 16, u16, __riscv_vwaddu_vv) -OPENCV_HAL_IMPL_RVV_HADD(v_uint16, v_uint32, vuint32m4_t, 16, 32, u32, __riscv_vwaddu_vv) -OPENCV_HAL_IMPL_RVV_HADD(v_uint32, v_uint64, vuint64m4_t, 32, 64, u64, __riscv_vwaddu_vv) -OPENCV_HAL_IMPL_RVV_HADD(v_int8, v_int16, vint16m4_t, 8, 16, i16, __riscv_vwadd_vv) -OPENCV_HAL_IMPL_RVV_HADD(v_int16, v_int32, vint32m4_t, 16, 32, i32, __riscv_vwadd_vv) -OPENCV_HAL_IMPL_RVV_HADD(v_int32, v_int64, vint64m4_t, 32, 64, i64, __riscv_vwadd_vv) - -OPENCV_HAL_IMPL_RVV_HADD(vint32m4_t, v_int32, vint32m4_t, 16, 32, i32, __riscv_vadd) -OPENCV_HAL_IMPL_RVV_HADD(vint64m4_t, v_int64, vint64m4_t, 32, 64, i64, __riscv_vadd) - -inline v_uint8 v_popcount(const v_uint8& a) -{ - return __riscv_vloxei8(popCountTable, a, VTraits::vlanes()); -} -inline v_uint16 v_popcount(const v_uint16& a) -{ - return v_hadd(v_popcount(__riscv_vreinterpret_u8m2(a))); -} -inline v_uint32 v_popcount(const v_uint32& a) -{ - return v_hadd(v_hadd(v_popcount(__riscv_vreinterpret_u8m2(a)))); -} -inline v_uint64 v_popcount(const v_uint64& a) -{ - return v_hadd(v_hadd(v_hadd(v_popcount(__riscv_vreinterpret_u8m2(a))))); -} - -inline v_uint8 v_popcount(const v_int8& a) -{ - return v_popcount(v_abs(a));\ -} -inline v_uint16 v_popcount(const v_int16& a) -{ - return v_popcount(v_abs(a));\ -} -inline v_uint32 v_popcount(const v_int32& a) -{ - return v_popcount(v_abs(a));\ -} -inline v_uint64 v_popcount(const v_int64& a) -{ - // max(0 - a) is used, since v_abs does not support 64-bit integers. - return v_popcount(v_reinterpret_as_u64(__riscv_vmax(a, v_sub(v_setzero_s64(), a), VTraits::vlanes()))); -} - - -//////////// SignMask //////////// -#define OPENCV_HAL_IMPL_RVV_SIGNMASK_OP(_Tpvec) \ -inline int v_signmask(const _Tpvec& a) \ -{ \ - uint8_t ans[4] = {0}; \ - __riscv_vsm(ans, __riscv_vmslt(a, 0, VTraits<_Tpvec>::vlanes()), VTraits<_Tpvec>::vlanes()); \ - return *(reinterpret_cast(ans)) & (((__int128_t)1 << VTraits<_Tpvec>::vlanes()) - 1); \ -} \ -inline int v_scan_forward(const _Tpvec& a) \ -{ \ - return (int)__riscv_vfirst(__riscv_vmslt(a, 0, VTraits<_Tpvec>::vlanes()), VTraits<_Tpvec>::vlanes()); \ -} - -OPENCV_HAL_IMPL_RVV_SIGNMASK_OP(v_int8) -OPENCV_HAL_IMPL_RVV_SIGNMASK_OP(v_int16) -OPENCV_HAL_IMPL_RVV_SIGNMASK_OP(v_int32) -OPENCV_HAL_IMPL_RVV_SIGNMASK_OP(v_int64) - -inline int64 v_signmask(const v_uint8& a) -{ return v_signmask(v_reinterpret_as_s8(a)); } -inline int64 v_signmask(const v_uint16& a) -{ return v_signmask(v_reinterpret_as_s16(a)); } -inline int v_signmask(const v_uint32& a) -{ return v_signmask(v_reinterpret_as_s32(a)); } -inline int v_signmask(const v_float32& a) -{ return v_signmask(v_reinterpret_as_s32(a)); } -inline int v_signmask(const v_uint64& a) -{ return v_signmask(v_reinterpret_as_s64(a)); } -#if CV_SIMD_SCALABLE_64F -inline int v_signmask(const v_float64& a) -{ return v_signmask(v_reinterpret_as_s64(a)); } -#endif - -//////////// Scan forward //////////// -inline int v_scan_forward(const v_uint8& a) -{ return v_scan_forward(v_reinterpret_as_s8(a)); } -inline int v_scan_forward(const v_uint16& a) -{ return v_scan_forward(v_reinterpret_as_s16(a)); } -inline int v_scan_forward(const v_uint32& a) -{ return v_scan_forward(v_reinterpret_as_s32(a)); } -inline int v_scan_forward(const v_float32& a) -{ return v_scan_forward(v_reinterpret_as_s32(a)); } -inline int v_scan_forward(const v_uint64& a) -{ return v_scan_forward(v_reinterpret_as_s64(a)); } -#if CV_SIMD_SCALABLE_64F -inline int v_scan_forward(const v_float64& a) -{ return v_scan_forward(v_reinterpret_as_s64(a)); } -#endif - -//////////// Pack triplets //////////// -// {A0, A1, A2, A3, B0, B1, B2, B3, C0 ...} --> {A0, A1, A2, B0, B1, B2, C0 ...} -// mask: {0,0,0,1, ...} -> {T,T,T,F, ...} -#define OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(_Tpvec, v_trunc) \ -inline _Tpvec v_pack_triplets(const _Tpvec& vec) { \ - size_t vl = VTraits::vlanes(); \ - vuint32m2_t one = __riscv_vmv_v_x_u32m2(1, VTraits::vlanes()); \ - vuint8m2_t zero = __riscv_vmv_v_x_u8m2(0, vl); \ - vuint8m2_t mask = __riscv_vreinterpret_u8m2(one); \ - return __riscv_vcompress(vec, __riscv_vmseq(v_trunc(__riscv_vslideup(zero, mask, 3, vl)), 0, vl), VTraits<_Tpvec>::vlanes()); \ -} - -OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_uint8, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_int8, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_uint16, __riscv_vlmul_trunc_u8m1) -OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_int16, __riscv_vlmul_trunc_u8m1) -OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_uint32, __riscv_vlmul_trunc_u8mf2) -OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_int32, __riscv_vlmul_trunc_u8mf2) -OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_float32, __riscv_vlmul_trunc_u8mf2) -OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_uint64, __riscv_vlmul_trunc_u8mf4) -OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_int64, __riscv_vlmul_trunc_u8mf4) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_float64, __riscv_vlmul_trunc_u8mf4) -#endif - - -////// FP16 support /////// - -#if defined(__riscv_zfh) && __riscv_zfh -inline v_float32 v_load_expand(const hfloat* ptr) -{ - return __riscv_vfwcvt_f(__riscv_vle16_v_f16m1((_Float16*)ptr, VTraits::vlanes()) ,VTraits::vlanes());; -} - -inline void v_pack_store(hfloat* ptr, const v_float32& v) -{ - __riscv_vse16_v_f16m1((_Float16*)ptr, __riscv_vfncvt_f_f_w_f16m1(v, VTraits::vlanes()), VTraits::vlanes()); -} -#else -inline v_float32 v_load_expand(const hfloat* ptr) -{ - float buf[32]; - for( int i = 0; i < VTraits::vlanes(); i++ ) buf[i] = (float)ptr[i]; - return v_load(buf); -} - -inline void v_pack_store(hfloat* ptr, const v_float32& v) -{ - float buf[32]; - v_store(buf, v); - for( int i = 0; i < VTraits::vlanes(); i++ ) ptr[i] = hfloat(buf[i]); -} -#endif -////////////// Rounding ////////////// -inline v_int32 v_round(const v_float32& a) -{ - // return vfcvt_x(vfadd(a, 1e-6, VTraits::vlanes()), VTraits::vlanes()); - return __riscv_vfcvt_x(a, VTraits::vlanes()); -} - -inline v_int32 v_floor(const v_float32& a) -{ - return __riscv_vfcvt_x(__riscv_vfsub(a, 0.5f - 1e-5, VTraits::vlanes()), VTraits::vlanes()); - // return vfcvt_x(a, VTraits::vlanes()); -} - -inline v_int32 v_ceil(const v_float32& a) -{ - return __riscv_vfcvt_x(__riscv_vfadd(a, 0.5f - 1e-5, VTraits::vlanes()), VTraits::vlanes()); -} - -inline v_int32 v_trunc(const v_float32& a) -{ - return __riscv_vfcvt_rtz_x(a, VTraits::vlanes()); -} -#if CV_SIMD_SCALABLE_64F -inline v_int32 v_round(const v_float64& a) -{ - return __riscv_vfncvt_x(__riscv_vlmul_ext_f64m4(a), VTraits::vlanes()); -} - -inline v_int32 v_round(const v_float64& a, const v_float64& b) -{ - // return vfncvt_x(vset(vlmul_ext_f64m2(vfadd(a, 1e-6, VTraits::vlanes())), 1, b), VTraits::vlanes()); - // Fix https://github.com/opencv/opencv/issues/24746 - return __riscv_vfncvt_x(__riscv_vset(__riscv_vlmul_ext_f64m4(a), 1, b), VTraits::vlanes()); -} - -inline v_int32 v_floor(const v_float64& a) -{ - return __riscv_vfncvt_x(__riscv_vlmul_ext_f64m4(__riscv_vfsub(a, 0.5f - 1e-6, VTraits::vlanes())), VTraits::vlanes()); -} - -inline v_int32 v_ceil(const v_float64& a) -{ - return __riscv_vfncvt_x(__riscv_vlmul_ext_f64m4(__riscv_vfadd(a, 0.5f - 1e-6, VTraits::vlanes())), VTraits::vlanes()); -} - -inline v_int32 v_trunc(const v_float64& a) -{ - return __riscv_vfncvt_rtz_x(__riscv_vlmul_ext_f64m4(a), VTraits::vlanes()); -} -#endif - -//////// Dot Product //////// - -// 16 >> 32 -inline v_int32 v_dotprod(const v_int16& a, const v_int16& b) -{ - vint32m4_t temp1 = __riscv_vwmul(a, b, VTraits::vlanes()); - return v_hadd(temp1); -} - -inline v_int32 v_dotprod(const v_int16& a, const v_int16& b, const v_int32& c) -{ - vint32m4_t temp1 = __riscv_vwmul(a, b, VTraits::vlanes()); - return __riscv_vadd(v_hadd(temp1), c, VTraits::vlanes()); -} - -// 32 >> 64 -inline v_int64 v_dotprod(const v_int32& a, const v_int32& b) -{ - vuint64m2_t one64 = __riscv_vmv_v_x_u64m2(1, VTraits::vlanes()); \ - vuint32m2_t one32 = __riscv_vreinterpret_u32m2(one64); \ - vbool16_t mask = __riscv_vmseq(one32, 1, VTraits::vlanes()); \ - vint64m4_t temp1 = __riscv_vwmul(a, b, VTraits::vlanes()); \ - vint64m4_t temp2 = __riscv_vslide1down(temp1, 0, VTraits::vlanes()); - vint64m4_t res = __riscv_vadd(temp1, temp2, VTraits::vlanes()); - res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ - return __riscv_vlmul_trunc_i64m2(res); \ -} -inline v_int64 v_dotprod(const v_int32& a, const v_int32& b, const v_int64& c) -{ - vuint64m2_t one64 = __riscv_vmv_v_x_u64m2(1, VTraits::vlanes()); \ - vuint32m2_t one32 = __riscv_vreinterpret_u32m2(one64); \ - vbool16_t mask = __riscv_vmseq(one32, 1, VTraits::vlanes()); \ - vint64m4_t temp1 = __riscv_vwmul(a, b, VTraits::vlanes()); \ - vint64m4_t temp2 = __riscv_vslide1down(temp1, 0, VTraits::vlanes()); - vint64m4_t res = __riscv_vadd(temp1, temp2, VTraits::vlanes()); - res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ - return __riscv_vadd(__riscv_vlmul_trunc_i64m2(res), c, VTraits::vlanes()); \ -} - -// 8 >> 32 -inline v_uint32 v_dotprod_expand(const v_uint8& a, const v_uint8& b) -{ - vuint32m2_t one32 = __riscv_vmv_v_x_u32m2(1, VTraits::vlanes()); \ - vuint8m2_t one8 = __riscv_vreinterpret_u8m2(one32); \ - vbool4_t mask = __riscv_vmseq(one8, 1, VTraits::vlanes()); \ - vuint16m4_t t0 = __riscv_vwmulu(a, b, VTraits::vlanes()); \ - vuint16m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); - vuint16m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); - vuint16m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); - vuint32m8_t res = __riscv_vadd(__riscv_vwaddu_vv(t2, t3, VTraits::vlanes()), __riscv_vwaddu_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); - res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ - return __riscv_vlmul_trunc_u32m2(res); -} - -inline v_uint32 v_dotprod_expand(const v_uint8& a, const v_uint8& b, - const v_uint32& c) -{ - vuint32m2_t one32 = __riscv_vmv_v_x_u32m2(1, VTraits::vlanes()); \ - vuint8m2_t one8 = __riscv_vreinterpret_u8m2(one32); \ - vbool4_t mask = __riscv_vmseq(one8, 1, VTraits::vlanes()); \ - vuint16m4_t t0 = __riscv_vwmulu(a, b, VTraits::vlanes()); \ - vuint16m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); - vuint16m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); - vuint16m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); - vuint32m8_t res = __riscv_vadd(__riscv_vwaddu_vv(t2, t3, VTraits::vlanes()), __riscv_vwaddu_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); - res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ - return __riscv_vadd(__riscv_vlmul_trunc_u32m2(res), c, VTraits::vlanes()); -} - -inline v_int32 v_dotprod_expand(const v_int8& a, const v_int8& b) -{ - vuint32m2_t one32 = __riscv_vmv_v_x_u32m2(1, VTraits::vlanes()); \ - vuint8m2_t one8 = __riscv_vreinterpret_u8m2(one32); \ - vbool4_t mask = __riscv_vmseq(one8, 1, VTraits::vlanes()); \ - vint16m4_t t0 = __riscv_vwmul(a, b, VTraits::vlanes()); \ - vint16m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); - vint16m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); - vint16m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); - vint32m8_t res = __riscv_vadd(__riscv_vwadd_vv(t2, t3, VTraits::vlanes()), __riscv_vwadd_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); - res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ - return __riscv_vlmul_trunc_i32m2(res); -} - -inline v_int32 v_dotprod_expand(const v_int8& a, const v_int8& b, - const v_int32& c) -{ - vuint32m2_t one32 = __riscv_vmv_v_x_u32m2(1, VTraits::vlanes()); \ - vuint8m2_t one8 = __riscv_vreinterpret_u8m2(one32); \ - vbool4_t mask = __riscv_vmseq(one8, 1, VTraits::vlanes()); \ - vint16m4_t t0 = __riscv_vwmul(a, b, VTraits::vlanes()); \ - vint16m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); - vint16m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); - vint16m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); - vint32m8_t res = __riscv_vadd(__riscv_vwadd_vv(t2, t3, VTraits::vlanes()), __riscv_vwadd_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); - res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ - return __riscv_vadd(__riscv_vlmul_trunc_i32m2(res), c, VTraits::vlanes()); -} - - -// // 16 >> 64 -inline v_uint64 v_dotprod_expand(const v_uint16& a, const v_uint16& b) -{ - vuint64m2_t one64 = __riscv_vmv_v_x_u64m2(1, VTraits::vlanes()); \ - vuint16m2_t one16 = __riscv_vreinterpret_u16m2(one64); \ - vbool8_t mask = __riscv_vmseq(one16, 1, VTraits::vlanes()); \ - vuint32m4_t t0 = __riscv_vwmulu(a, b, VTraits::vlanes()); \ - vuint32m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); - vuint32m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); - vuint32m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); - vuint64m8_t res = __riscv_vadd(__riscv_vwaddu_vv(t2, t3, VTraits::vlanes()), __riscv_vwaddu_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); - res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ - return __riscv_vlmul_trunc_u64m2(res); -} -inline v_uint64 v_dotprod_expand(const v_uint16& a, const v_uint16& b, const v_uint64& c) -{ - vuint64m2_t one64 = __riscv_vmv_v_x_u64m2(1, VTraits::vlanes()); \ - vuint16m2_t one16 = __riscv_vreinterpret_u16m2(one64); \ - vbool8_t mask = __riscv_vmseq(one16, 1, VTraits::vlanes()); \ - vuint32m4_t t0 = __riscv_vwmulu(a, b, VTraits::vlanes()); \ - vuint32m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); - vuint32m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); - vuint32m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); - vuint64m8_t res = __riscv_vadd(__riscv_vwaddu_vv(t2, t3, VTraits::vlanes()), __riscv_vwaddu_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); - res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ - return __riscv_vadd(__riscv_vlmul_trunc_u64m2(res), c, VTraits::vlanes()); -} - -inline v_int64 v_dotprod_expand(const v_int16& a, const v_int16& b) -{ - vuint64m2_t one64 = __riscv_vmv_v_x_u64m2(1, VTraits::vlanes()); \ - vuint16m2_t one16 = __riscv_vreinterpret_u16m2(one64); \ - vbool8_t mask = __riscv_vmseq(one16, 1, VTraits::vlanes()); \ - vint32m4_t t0 = __riscv_vwmul(a, b, VTraits::vlanes()); \ - vint32m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); - vint32m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); - vint32m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); - vint64m8_t res = __riscv_vadd(__riscv_vwadd_vv(t2, t3, VTraits::vlanes()), __riscv_vwadd_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); - res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ - return __riscv_vlmul_trunc_i64m2(res); -} -inline v_int64 v_dotprod_expand(const v_int16& a, const v_int16& b, - const v_int64& c) -{ - vuint64m2_t one64 = __riscv_vmv_v_x_u64m2(1, VTraits::vlanes()); \ - vuint16m2_t one16 = __riscv_vreinterpret_u16m2(one64); \ - vbool8_t mask = __riscv_vmseq(one16, 1, VTraits::vlanes()); \ - vint32m4_t t0 = __riscv_vwmul(a, b, VTraits::vlanes()); \ - vint32m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); - vint32m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); - vint32m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); - vint64m8_t res = __riscv_vadd(__riscv_vwadd_vv(t2, t3, VTraits::vlanes()), __riscv_vwadd_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); - res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ - return __riscv_vadd(__riscv_vlmul_trunc_i64m2(res), c, VTraits::vlanes()); -} - -// // 32 >> 64f -#if CV_SIMD_SCALABLE_64F -inline v_float64 v_dotprod_expand(const v_int32& a, const v_int32& b) -{ return v_cvt_f64(v_dotprod(a, b)); } -inline v_float64 v_dotprod_expand(const v_int32& a, const v_int32& b, - const v_float64& c) -{ return v_add(v_dotprod_expand(a, b) , c); } -#endif - -//////// Fast Dot Product //////// -// 16 >> 32 -inline v_int32 v_dotprod_fast(const v_int16& a, const v_int16& b) -{ - vint32m1_t zero = __riscv_vmv_v_x_i32m1(0, VTraits::vlanes()); - return __riscv_vset(__riscv_vmv_v_x_i32m2(0, VTraits::vlanes()), 0, __riscv_vredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())); -} -inline v_int32 v_dotprod_fast(const v_int16& a, const v_int16& b, const v_int32& c) -{ - vint32m1_t zero = __riscv_vmv_v_x_i32m1(0, VTraits::vlanes()); - return __riscv_vadd(c, __riscv_vset(__riscv_vmv_v_x_i32m2(0, VTraits::vlanes()), 0, __riscv_vredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())), VTraits::vlanes()); -} - -// 32 >> 64 -inline v_int64 v_dotprod_fast(const v_int32& a, const v_int32& b) -{ - vint64m1_t zero = __riscv_vmv_v_x_i64m1(0, VTraits::vlanes()); - return __riscv_vset(__riscv_vmv_v_x_i64m2(0, VTraits::vlanes()), 0, __riscv_vredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())); -} -inline v_int64 v_dotprod_fast(const v_int32& a, const v_int32& b, const v_int64& c) -{ - vint64m1_t zero = __riscv_vmv_v_x_i64m1(0, VTraits::vlanes()); - return __riscv_vadd(c, __riscv_vset(__riscv_vmv_v_x_i64m2(0, VTraits::vlanes()), 0, __riscv_vredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())), VTraits::vlanes()); -} - - -// 8 >> 32 -inline v_uint32 v_dotprod_expand_fast(const v_uint8& a, const v_uint8& b) -{ - vuint32m1_t zero = __riscv_vmv_v_x_u32m1(0, VTraits::vlanes()); - auto res = __riscv_vwredsumu_tu(zero, __riscv_vwmulu(a, b, VTraits::vlanes()), zero, VTraits::vlanes()); - return __riscv_vset(__riscv_vmv_v_x_u32m2(0, VTraits::vlanes()), 0, res); -} -inline v_uint32 v_dotprod_expand_fast(const v_uint8& a, const v_uint8& b, const v_uint32& c) -{ - vuint32m1_t zero = __riscv_vmv_v_x_u32m1(0, VTraits::vlanes()); - auto res = __riscv_vwredsumu_tu(zero, __riscv_vwmulu(a, b, VTraits::vlanes()), zero, VTraits::vlanes()); - return __riscv_vadd(c, __riscv_vset(__riscv_vmv_v_x_u32m2(0, VTraits::vlanes()), 0, res), VTraits::vlanes()); -} -inline v_int32 v_dotprod_expand_fast(const v_int8& a, const v_int8& b) -{ - vint32m1_t zero = __riscv_vmv_v_x_i32m1(0, VTraits::vlanes()); - return __riscv_vset(__riscv_vmv_v_x_i32m2(0, VTraits::vlanes()), 0, __riscv_vwredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())); -} -inline v_int32 v_dotprod_expand_fast(const v_int8& a, const v_int8& b, const v_int32& c) -{ - vint32m1_t zero = __riscv_vmv_v_x_i32m1(0, VTraits::vlanes()); - return __riscv_vadd(c, __riscv_vset(__riscv_vmv_v_x_i32m2(0, VTraits::vlanes()), 0, __riscv_vwredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())), VTraits::vlanes()); -} - -// 16 >> 64 -inline v_uint64 v_dotprod_expand_fast(const v_uint16& a, const v_uint16& b) -{ - vuint64m1_t zero = __riscv_vmv_v_x_u64m1(0, VTraits::vlanes()); - return __riscv_vset(__riscv_vmv_v_x_u64m2(0, VTraits::vlanes()), 0, __riscv_vwredsumu_tu(zero, __riscv_vwmulu(a, b, VTraits::vlanes()), zero, VTraits::vlanes())); -} -inline v_uint64 v_dotprod_expand_fast(const v_uint16& a, const v_uint16& b, const v_uint64& c) -{ - vuint64m1_t zero = __riscv_vmv_v_x_u64m1(0, VTraits::vlanes()); - return __riscv_vadd(c, __riscv_vset(__riscv_vmv_v_x_u64m2(0, VTraits::vlanes()), 0, __riscv_vwredsumu_tu(zero, __riscv_vwmulu(a, b, VTraits::vlanes()), zero, VTraits::vlanes())), VTraits::vlanes()); -} -inline v_int64 v_dotprod_expand_fast(const v_int16& a, const v_int16& b) -{ - vint64m1_t zero = __riscv_vmv_v_x_i64m1(0, VTraits::vlanes()); - return __riscv_vset(__riscv_vmv_v_x_i64m2(0, VTraits::vlanes()), 0, __riscv_vwredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())); -} -inline v_int64 v_dotprod_expand_fast(const v_int16& a, const v_int16& b, const v_int64& c) -{ - vint64m1_t zero = __riscv_vmv_v_x_i64m1(0, VTraits::vlanes()); - return __riscv_vadd(c, __riscv_vset(__riscv_vmv_v_x_i64m2(0, VTraits::vlanes()), 0, __riscv_vwredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())), VTraits::vlanes()); -} - -// 32 >> 64f -#if CV_SIMD_SCALABLE_64F -inline v_float64 v_dotprod_expand_fast(const v_int32& a, const v_int32& b) -{ return v_cvt_f64(v_dotprod_fast(a, b)); } -inline v_float64 v_dotprod_expand_fast(const v_int32& a, const v_int32& b, const v_float64& c) -{ return v_add(v_dotprod_expand_fast(a, b) , c); } -#endif - -// TODO: only 128 bit now. -inline v_float32 v_matmul(const v_float32& v, const v_float32& mat0, - const v_float32& mat1, const v_float32& mat2, - const v_float32& mat3) -{ - vfloat32m2_t res; - res = __riscv_vfmul_vf_f32m2(mat0, v_extract_n(v, 0), VTraits::vlanes()); - res = __riscv_vfmacc_vf_f32m2(res, v_extract_n(v, 1), mat1, VTraits::vlanes()); - res = __riscv_vfmacc_vf_f32m2(res, v_extract_n(v, 2), mat2, VTraits::vlanes()); - res = __riscv_vfmacc_vf_f32m2(res, v_extract_n(v, 3), mat3, VTraits::vlanes()); - return res; -} - -// TODO: only 128 bit now. -inline v_float32 v_matmuladd(const v_float32& v, const v_float32& mat0, - const v_float32& mat1, const v_float32& mat2, - const v_float32& a) -{ - vfloat32m2_t res = __riscv_vfmul_vf_f32m2(mat0, v_extract_n(v,0), VTraits::vlanes()); - res = __riscv_vfmacc_vf_f32m2(res, v_extract_n(v,1), mat1, VTraits::vlanes()); - res = __riscv_vfmacc_vf_f32m2(res, v_extract_n(v,2), mat2, VTraits::vlanes()); - return __riscv_vfadd(res, a, VTraits::vlanes()); -} - -inline void v_cleanup() {} - -#include "intrin_math.hpp" -inline v_float32 v_exp(const v_float32& x) { return v_exp_default_32f(x); } -inline v_float32 v_log(const v_float32& x) { return v_log_default_32f(x); } -inline void v_sincos(const v_float32& x, v_float32& s, v_float32& c) { v_sincos_default_32f(x, s, c); } -inline v_float32 v_sin(const v_float32& x) { return v_sin_default_32f(x); } -inline v_float32 v_cos(const v_float32& x) { return v_cos_default_32f(x); } -inline v_float32 v_erf(const v_float32& x) { return v_erf_default_32f(x); } - -inline v_float64 v_exp(const v_float64& x) { return v_exp_default_64f(x); } -inline v_float64 v_log(const v_float64& x) { return v_log_default_64f(x); } -inline void v_sincos(const v_float64& x, v_float64& s, v_float64& c) { v_sincos_default_64f(x, s, c); } -inline v_float64 v_sin(const v_float64& x) { return v_sin_default_64f(x); } -inline v_float64 v_cos(const v_float64& x) { return v_cos_default_64f(x); } - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} //namespace cv - -#endif //OPENCV_HAL_INTRIN_RVV_SCALABLE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +// The original implementation is contributed by HAN Liutong. +// Copyright (C) 2022, Institute of Software, Chinese Academy of Sciences. + +#ifndef OPENCV_HAL_INTRIN_RVV_SCALABLE_HPP +#define OPENCV_HAL_INTRIN_RVV_SCALABLE_HPP + +#include + +#if defined(__GNUC__) && !defined(__clang__) +// FIXIT: eliminate massive warnigs from templates +// GCC from 'rvv-next': riscv64-unknown-linux-gnu-g++ (g42df3464463) 12.0.1 20220505 (prerelease) +// doesn't work: #pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wignored-attributes" +#endif + +#ifndef CV_RVV_MAX_VLEN +#define CV_RVV_MAX_VLEN 1024 +#endif + +namespace cv +{ + +//! @cond IGNORED + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +#define CV_SIMD_SCALABLE 1 +#define CV_SIMD_SCALABLE_64F 1 + +using v_uint8 = vuint8m2_t; +using v_int8 = vint8m2_t; +using v_uint16 = vuint16m2_t; +using v_int16 = vint16m2_t; +using v_uint32 = vuint32m2_t; +using v_int32 = vint32m2_t; +using v_uint64 = vuint64m2_t; +using v_int64 = vint64m2_t; + +using v_float32 = vfloat32m2_t; +#if CV_SIMD_SCALABLE_64F +using v_float64 = vfloat64m2_t; +#endif + +using uchar = unsigned char; +using schar = signed char; +using ushort = unsigned short; +using uint = unsigned int; +using uint64 = unsigned long int; +using int64 = long int; + + +template +struct VTraits; + +#define OPENCV_HAL_IMPL_RVV_TRAITS(REG, TYP, SUF, SZ) \ +template <> \ +struct VTraits \ +{ \ + static inline int vlanes() { return __riscv_vsetvlmax_##SUF(); } \ + using lane_type = TYP; \ + static const int max_nlanes = CV_RVV_MAX_VLEN/SZ; \ +}; + +OPENCV_HAL_IMPL_RVV_TRAITS(vint8m1_t, int8_t, e8m1, 8) +OPENCV_HAL_IMPL_RVV_TRAITS(vint8m2_t, int8_t, e8m2, 8) +OPENCV_HAL_IMPL_RVV_TRAITS(vint8m4_t, int8_t, e8m4, 8) +OPENCV_HAL_IMPL_RVV_TRAITS(vint8m8_t, int8_t, e8m8, 8) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint8m1_t, uint8_t, e8m1, 8) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint8m2_t, uint8_t, e8m2, 8) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint8m4_t, uint8_t, e8m4, 8) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint8m8_t, uint8_t, e8m8, 8) + +OPENCV_HAL_IMPL_RVV_TRAITS(vint16m1_t, int16_t, e16m1, 16) +OPENCV_HAL_IMPL_RVV_TRAITS(vint16m2_t, int16_t, e16m2, 16) +OPENCV_HAL_IMPL_RVV_TRAITS(vint16m4_t, int16_t, e16m4, 16) +OPENCV_HAL_IMPL_RVV_TRAITS(vint16m8_t, int16_t, e16m8, 16) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint16m1_t, uint16_t, e16m1, 16) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint16m2_t, uint16_t, e16m2, 16) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint16m4_t, uint16_t, e16m4, 16) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint16m8_t, uint16_t, e16m8, 16) + +OPENCV_HAL_IMPL_RVV_TRAITS(vint32m1_t, int32_t, e32m1, 32) +OPENCV_HAL_IMPL_RVV_TRAITS(vint32m2_t, int32_t, e32m2, 32) +OPENCV_HAL_IMPL_RVV_TRAITS(vint32m4_t, int32_t, e32m4, 32) +OPENCV_HAL_IMPL_RVV_TRAITS(vint32m8_t, int32_t, e32m8, 32) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint32m1_t, uint32_t, e32m1, 32) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint32m2_t, uint32_t, e32m2, 32) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint32m4_t, uint32_t, e32m4, 32) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint32m8_t, uint32_t, e32m8, 32) + +OPENCV_HAL_IMPL_RVV_TRAITS(vint64m1_t, int64_t, e64m1, 64) +OPENCV_HAL_IMPL_RVV_TRAITS(vint64m2_t, int64_t, e64m2, 64) +OPENCV_HAL_IMPL_RVV_TRAITS(vint64m4_t, int64_t, e64m4, 64) +OPENCV_HAL_IMPL_RVV_TRAITS(vint64m8_t, int64_t, e64m8, 64) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint64m1_t, uint64_t, e64m1, 64) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint64m2_t, uint64_t, e64m2, 64) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint64m4_t, uint64_t, e64m4, 64) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint64m8_t, uint64_t, e64m8, 64) + +OPENCV_HAL_IMPL_RVV_TRAITS(vfloat32m1_t, float, e32m1, 32) +OPENCV_HAL_IMPL_RVV_TRAITS(vfloat32m2_t, float, e32m2, 32) +OPENCV_HAL_IMPL_RVV_TRAITS(vfloat32m4_t, float, e32m4, 32) +OPENCV_HAL_IMPL_RVV_TRAITS(vfloat32m8_t, float, e32m8, 32) + +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_TRAITS(vfloat64m1_t, double, e64m1, 64) +OPENCV_HAL_IMPL_RVV_TRAITS(vfloat64m2_t, double, e64m2, 64) +OPENCV_HAL_IMPL_RVV_TRAITS(vfloat64m4_t, double, e64m4, 64) +OPENCV_HAL_IMPL_RVV_TRAITS(vfloat64m8_t, double, e64m8, 64) +#endif + + +// LLVM/Clang defines "overloaded intrinsics" e.g. 'vand(op1, op2)' +// GCC does not have these functions, so we need to implement them manually +// We implement only selected subset required to build current state of the code +// Included inside namespace cv:: +// #ifndef __riscv_v_intrinsic_overloading +// #include "intrin_rvv_compat_overloaded.hpp" +// #endif // __riscv_v_intrinsic_overloading + + +//////////// get0 //////////// +#define OPENCV_HAL_IMPL_RVV_GRT0_INT(_Tpvec, _Tp) \ +inline _Tp v_get0(const v_##_Tpvec& v) \ +{ \ + return __riscv_vmv_x(v); \ +} + +OPENCV_HAL_IMPL_RVV_GRT0_INT(uint8, uchar) +OPENCV_HAL_IMPL_RVV_GRT0_INT(int8, schar) +OPENCV_HAL_IMPL_RVV_GRT0_INT(uint16, ushort) +OPENCV_HAL_IMPL_RVV_GRT0_INT(int16, short) +OPENCV_HAL_IMPL_RVV_GRT0_INT(uint32, unsigned) +OPENCV_HAL_IMPL_RVV_GRT0_INT(int32, int) +OPENCV_HAL_IMPL_RVV_GRT0_INT(uint64, uint64) +OPENCV_HAL_IMPL_RVV_GRT0_INT(int64, int64) + +inline float v_get0(const v_float32& v) \ +{ \ + return __riscv_vfmv_f(v); \ +} +#if CV_SIMD_SCALABLE_64F +inline double v_get0(const v_float64& v) \ +{ \ + return __riscv_vfmv_f(v); \ +} +#endif + +//////////// Initial //////////// + +#define OPENCV_HAL_IMPL_RVV_INIT_INTEGER(_Tpvec, _Tp, suffix1, suffix2, vl) \ +inline v_##_Tpvec v_setzero_##suffix1() \ +{ \ + return __riscv_vmv_v_x_##suffix2##m2(0, vl); \ +} \ +inline v_##_Tpvec v_setall_##suffix1(_Tp v) \ +{ \ + return __riscv_vmv_v_x_##suffix2##m2(v, vl); \ +} \ +template <> inline v_##_Tpvec v_setzero_() \ +{ \ + return v_setzero_##suffix1(); \ +} \ +template <> inline v_##_Tpvec v_setall_(_Tp v) \ +{ \ + return v_setall_##suffix1(v); \ +} + +OPENCV_HAL_IMPL_RVV_INIT_INTEGER(uint8, uchar, u8, u8, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INIT_INTEGER(int8, schar, s8, i8, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INIT_INTEGER(uint16, ushort, u16, u16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INIT_INTEGER(int16, short, s16, i16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INIT_INTEGER(uint32, uint, u32, u32, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INIT_INTEGER(int32, int, s32, i32, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INIT_INTEGER(uint64, uint64, u64, u64, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INIT_INTEGER(int64, int64, s64, i64, VTraits::vlanes()) + +#define OPENCV_HAL_IMPL_RVV_INIT_FP(_Tpv, _Tp, suffix, vl) \ +inline v_##_Tpv v_setzero_##suffix() \ +{ \ + return __riscv_vfmv_v_f_##suffix##m2(0, vl); \ +} \ +inline v_##_Tpv v_setall_##suffix(_Tp v) \ +{ \ + return __riscv_vfmv_v_f_##suffix##m2(v, vl); \ +} \ +template <> inline v_##_Tpv v_setzero_() \ +{ \ + return v_setzero_##suffix(); \ +} \ +template <> inline v_##_Tpv v_setall_(_Tp v) \ +{ \ + return v_setall_##suffix(v); \ +} + +OPENCV_HAL_IMPL_RVV_INIT_FP(float32, float, f32, VTraits::vlanes()) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_INIT_FP(float64, double, f64, VTraits::vlanes()) +#endif + +//////////// Reinterpret //////////// +#define OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(_Tpvec1, suffix1) \ +inline v_##_Tpvec1 v_reinterpret_as_##suffix1(const v_##_Tpvec1& v) \ +{ \ + return v;\ +} +OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(uint8, u8) +OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(uint16, u16) +OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(uint32, u32) +OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(uint64, u64) +OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(int8, s8) +OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(int16, s16) +OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(int32, s32) +OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(int64, s64) +OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(float32, f32) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(float64, f64) +#endif +// TODO: can be simplified by using overloaded RV intrinsic +#define OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(_Tpvec1, _Tpvec2, suffix1, suffix2, nsuffix1, nsuffix2) \ +inline v_##_Tpvec1 v_reinterpret_as_##suffix1(const v_##_Tpvec2& v) \ +{ \ + return v_##_Tpvec1(__riscv_vreinterpret_v_##nsuffix2##m2_##nsuffix1##m2(v));\ +} \ +inline v_##_Tpvec2 v_reinterpret_as_##suffix2(const v_##_Tpvec1& v) \ +{ \ + return v_##_Tpvec2(__riscv_vreinterpret_v_##nsuffix1##m2_##nsuffix2##m2(v));\ +} + +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint8, int8, u8, s8, u8, i8) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint16, int16, u16, s16, u16, i16) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint32, int32, u32, s32, u32, i32) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint32, float32, u32, f32, u32, f32) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int32, float32, s32, f32, i32, f32) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint64, int64, u64, s64, u64, i64) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint64, float64, u64, f64, u64, f64) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int64, float64, s64, f64, i64, f64) +#endif +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint8, uint16, u8, u16, u8, u16) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint8, uint32, u8, u32, u8, u32) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint8, uint64, u8, u64, u8, u64) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint16, uint32, u16, u32, u16, u32) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint16, uint64, u16, u64, u16, u64) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint32, uint64, u32, u64, u32, u64) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int8, int16, s8, s16, i8, i16) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int8, int32, s8, s32, i8, i32) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int8, int64, s8, s64, i8, i64) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int16, int32, s16, s32, i16, i32) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int16, int64, s16, s64, i16, i64) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int32, int64, s32, s64, i32, i64) + + +#define OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(_Tpvec1, _Tpvec2, suffix1, suffix2, nsuffix1, nsuffix2, width1, width2) \ +inline v_##_Tpvec1 v_reinterpret_as_##suffix1(const v_##_Tpvec2& v) \ +{ \ + return __riscv_vreinterpret_v_##nsuffix1##width2##m2_##nsuffix1##width1##m2(__riscv_vreinterpret_v_##nsuffix2##width2##m2_##nsuffix1##width2##m2(v));\ +} \ +inline v_##_Tpvec2 v_reinterpret_as_##suffix2(const v_##_Tpvec1& v) \ +{ \ + return __riscv_vreinterpret_v_##nsuffix1##width2##m2_##nsuffix2##width2##m2(__riscv_vreinterpret_v_##nsuffix1##width1##m2_##nsuffix1##width2##m2(v));\ +} + +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint8, int16, u8, s16, u, i, 8, 16) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint8, int32, u8, s32, u, i, 8, 32) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint8, int64, u8, s64, u, i, 8, 64) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint16, int8, u16, s8, u, i, 16, 8) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint16, int32, u16, s32, u, i, 16, 32) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint16, int64, u16, s64, u, i, 16, 64) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint32, int8, u32, s8, u, i, 32, 8) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint32, int16, u32, s16, u, i, 32, 16) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint32, int64, u32, s64, u, i, 32, 64) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint64, int8, u64, s8, u, i, 64, 8) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint64, int16, u64, s16, u, i, 64, 16) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint64, int32, u64, s32, u, i, 64, 32) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint8, float32, u8, f32, u, f, 8, 32) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint16, float32, u16, f32, u, f, 16, 32) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint64, float32, u64, f32, u, f, 64, 32) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(int8, float32, s8, f32, i, f, 8, 32) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(int16, float32, s16, f32, i, f, 16, 32) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(int64, float32, s64, f32, i, f, 64, 32) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint8, float64, u8, f64, u, f, 8, 64) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint16, float64, u16, f64, u, f, 16, 64) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint32, float64, u32, f64, u, f, 32, 64) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(int8, float64, s8, f64, i, f, 8, 64) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(int16, float64, s16, f64, i, f, 16, 64) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(int32, float64, s32, f64, i, f, 32, 64) +// Three times reinterpret +inline v_float32 v_reinterpret_as_f32(const v_float64& v) \ +{ \ + return __riscv_vreinterpret_v_u32m2_f32m2(__riscv_vreinterpret_v_u64m2_u32m2(__riscv_vreinterpret_v_f64m2_u64m2(v)));\ +} + +inline v_float64 v_reinterpret_as_f64(const v_float32& v) \ +{ \ + return __riscv_vreinterpret_v_u64m2_f64m2(__riscv_vreinterpret_v_u32m2_u64m2(__riscv_vreinterpret_v_f32m2_u32m2(v)));\ +} +#endif + +//////////// Extract ////////////// + +#define OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(_Tpvec, _Tp, vl) \ +template \ +inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b, int i = s) \ +{ \ + return __riscv_vslideup(__riscv_vslidedown(a, i, vl), b, VTraits<_Tpvec>::vlanes() - i, vl); \ +} \ +template inline _Tp v_extract_n(_Tpvec v, int i = s) \ +{ \ + return __riscv_vmv_x(__riscv_vslidedown(v, i, vl)); \ +} + +OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_uint8, uchar, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_int8, schar, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_uint16, ushort, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_int16, short, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_uint32, unsigned int, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_int32, int, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_uint64, uint64, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_int64, int64, VTraits::vlanes()) + +#define OPENCV_HAL_IMPL_RVV_EXTRACT_FP(_Tpvec, _Tp, vl) \ +template \ +inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b, int i = s) \ +{ \ + return __riscv_vslideup(__riscv_vslidedown(a, i, vl), b, VTraits<_Tpvec>::vlanes() - i, vl); \ +} \ +template inline _Tp v_extract_n(_Tpvec v, int i = s) \ +{ \ + return __riscv_vfmv_f(__riscv_vslidedown(v, i, vl)); \ +} + +OPENCV_HAL_IMPL_RVV_EXTRACT_FP(v_float32, float, VTraits::vlanes()) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_EXTRACT_FP(v_float64, double, VTraits::vlanes()) +#endif + +#define OPENCV_HAL_IMPL_RVV_EXTRACT(_Tpvec, _Tp, vl) \ +inline _Tp v_extract_highest(_Tpvec v) \ +{ \ + return v_extract_n(v, vl-1); \ +} + +OPENCV_HAL_IMPL_RVV_EXTRACT(v_uint8, uchar, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT(v_int8, schar, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT(v_uint16, ushort, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT(v_int16, short, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT(v_uint32, unsigned int, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT(v_int32, int, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT(v_uint64, uint64, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT(v_int64, int64, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT(v_float32, float, VTraits::vlanes()) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_EXTRACT(v_float64, double, VTraits::vlanes()) +#endif + + +////////////// Load/Store ////////////// +#define OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(_Tpvec, _nTpvec, _Tp, hvl, vl, width, suffix) \ +inline _Tpvec v_load(const _Tp* ptr) \ +{ \ + return __riscv_vle##width##_v_##suffix##m2(ptr, vl); \ +} \ +inline _Tpvec v_load_aligned(const _Tp* ptr) \ +{ \ + return __riscv_vle##width##_v_##suffix##m2(ptr, vl); \ +} \ +inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ +{ \ + __riscv_vse##width##_v_##suffix##m2(ptr, a, vl); \ +} \ +inline _Tpvec v_load_low(const _Tp* ptr) \ +{ \ + return __riscv_vle##width##_v_##suffix##m2(ptr, hvl); \ +} \ +inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ +{ \ + return __riscv_vslideup(__riscv_vle##width##_v_##suffix##m2(ptr0, hvl), __riscv_vle##width##_v_##suffix##m2(ptr1, hvl), hvl, vl); \ +} \ +inline void v_store(_Tp* ptr, const _Tpvec& a) \ +{ \ + __riscv_vse##width(ptr, a, vl); \ +} \ +inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ +{ \ + __riscv_vse##width(ptr, a, vl); \ +} \ +inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ +{ \ + __riscv_vse##width(ptr, a, vl); \ +} \ +inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ +{ \ + __riscv_vse##width(ptr, a, hvl); \ +} \ +inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ +{ \ + __riscv_vse##width(ptr, __riscv_vslidedown_vx_##suffix##m2(a, hvl, vl), hvl); \ +} \ +template \ +_Tpvec v_load_##suffix(Targs... nScalars) \ +{ \ + return v_load({nScalars...}); \ +} + + +OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_uint8, vuint8m2_t, uchar, VTraits::vlanes() / 2, VTraits::vlanes(), 8, u8) +OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_int8, vint8m2_t, schar, VTraits::vlanes() / 2, VTraits::vlanes(), 8, i8) +OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_uint16, vuint16m2_t, ushort, VTraits::vlanes() / 2, VTraits::vlanes(), 16, u16) +OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_int16, vint16m2_t, short, VTraits::vlanes() / 2, VTraits::vlanes(), 16, i16) +OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_uint32, vuint32m2_t, unsigned int, VTraits::vlanes() / 2, VTraits::vlanes(), 32, u32) +OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_int32, vint32m2_t, int, VTraits::vlanes() / 2, VTraits::vlanes(), 32, i32) +OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_uint64, vuint64m2_t, uint64, VTraits::vlanes() / 2, VTraits::vlanes(), 64, u64) +OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_int64, vint64m2_t, int64, VTraits::vlanes() / 2, VTraits::vlanes(), 64, i64) +OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_float32, vfloat32m2_t, float, VTraits::vlanes() /2 , VTraits::vlanes(), 32, f32) + +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_float64, vfloat64m2_t, double, VTraits::vlanes() / 2, VTraits::vlanes(), 64, f64) +#endif + +////////////// Lookup table access //////////////////// +#define OPENCV_HAL_IMPL_RVV_LUT(_Tpvec, _Tp, suffix) \ +inline _Tpvec v_lut(const _Tp* tab, const int* idx) \ +{ \ + auto vidx = __riscv_vmul(__riscv_vreinterpret_u32##suffix(__riscv_vle32_v_i32##suffix(idx, VTraits<_Tpvec>::vlanes())), sizeof(_Tp), VTraits<_Tpvec>::vlanes()); \ + return __riscv_vloxei32(tab, vidx, VTraits<_Tpvec>::vlanes()); \ +} +OPENCV_HAL_IMPL_RVV_LUT(v_int8, schar, m8) +OPENCV_HAL_IMPL_RVV_LUT(v_int16, short, m4) +OPENCV_HAL_IMPL_RVV_LUT(v_int32, int, m2) +OPENCV_HAL_IMPL_RVV_LUT(v_int64, int64_t, m1) +OPENCV_HAL_IMPL_RVV_LUT(v_float32, float, m2) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_LUT(v_float64, double, m1) +#endif + +#define OPENCV_HAL_IMPL_RVV_LUT_PAIRS(_Tpvec, _Tp, suffix1, suffix2, v_trunc) \ +inline _Tpvec v_lut_pairs(const _Tp* tab, const int* idx) \ +{ \ + auto v0 = __riscv_vle32_v_u32##suffix1((unsigned*)idx, VTraits<_Tpvec>::vlanes()/2); \ + auto v1 = __riscv_vadd(v0, 1, VTraits<_Tpvec>::vlanes()/2); \ + auto w0 = __riscv_vwcvtu_x(v0, VTraits<_Tpvec>::vlanes()/2); \ + auto w1 = __riscv_vwcvtu_x(v1, VTraits<_Tpvec>::vlanes()/2); \ + auto sh1 = __riscv_vslide1up(v_trunc(__riscv_vreinterpret_u32##suffix2(w1)),0, VTraits<_Tpvec>::vlanes()); \ + auto vid = __riscv_vor(sh1, v_trunc(__riscv_vreinterpret_u32##suffix2(w0)), VTraits<_Tpvec>::vlanes()); \ + auto vidx = __riscv_vmul(vid, sizeof(_Tp), VTraits<_Tpvec>::vlanes()); \ + return __riscv_vloxei32(tab, vidx, VTraits<_Tpvec>::vlanes()); \ +} +OPENCV_HAL_IMPL_RVV_LUT_PAIRS(v_int8, schar, m4, m8, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_RVV_LUT_PAIRS(v_int16, short, m2, m4, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_RVV_LUT_PAIRS(v_int32, int, m1, m2, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_RVV_LUT_PAIRS(v_float32, float, m1, m2, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_RVV_LUT_PAIRS(v_int64, int64_t, m1, m2, __riscv_vlmul_trunc_u32m1) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_LUT_PAIRS(v_float64, double, m1, m2, __riscv_vlmul_trunc_u32m1) +#endif + + +#define OPENCV_HAL_IMPL_RVV_LUT_QUADS(_Tpvec, _Tp, suffix0, suffix1, suffix2, v_trunc) \ +inline _Tpvec v_lut_quads(const _Tp* tab, const int* idx) \ +{ \ + auto v0 = __riscv_vle32_v_u32##suffix0((unsigned*)idx, VTraits<_Tpvec>::vlanes()/4); \ + auto v1 = __riscv_vadd(v0, 1, VTraits<_Tpvec>::vlanes()/4); \ + auto v2 = __riscv_vadd(v0, 2, VTraits<_Tpvec>::vlanes()/4); \ + auto v3 = __riscv_vadd(v0, 3, VTraits<_Tpvec>::vlanes()/4); \ + auto w0 = __riscv_vwcvtu_x(v0, VTraits<_Tpvec>::vlanes()/4); \ + auto w1 = __riscv_vwcvtu_x(v1, VTraits<_Tpvec>::vlanes()/4); \ + auto w2 = __riscv_vwcvtu_x(v2, VTraits<_Tpvec>::vlanes()/4); \ + auto w3 = __riscv_vwcvtu_x(v3, VTraits<_Tpvec>::vlanes()/4); \ + auto sh2 = __riscv_vslide1up(__riscv_vreinterpret_u32##suffix1(w2),0, VTraits<_Tpvec>::vlanes()/2); \ + auto sh3 = __riscv_vslide1up(__riscv_vreinterpret_u32##suffix1(w3),0, VTraits<_Tpvec>::vlanes()/2); \ + auto vid0 = __riscv_vor(sh2, __riscv_vreinterpret_u32##suffix1(w0), VTraits<_Tpvec>::vlanes()/2); \ + auto vid1 = __riscv_vor(sh3, __riscv_vreinterpret_u32##suffix1(w1), VTraits<_Tpvec>::vlanes()/2); \ + auto wid0 = __riscv_vwcvtu_x(v_trunc(vid0), VTraits<_Tpvec>::vlanes()/2); \ + auto wid1 = __riscv_vwcvtu_x(v_trunc(vid1), VTraits<_Tpvec>::vlanes()/2); \ + auto shwid1 = __riscv_vslide1up(__riscv_vreinterpret_u32##suffix2(wid1),0, VTraits<_Tpvec>::vlanes()); \ + auto vid = __riscv_vor(shwid1, __riscv_vreinterpret_u32##suffix2(wid0), VTraits<_Tpvec>::vlanes()); \ + auto vidx = __riscv_vmul(vid, sizeof(_Tp), VTraits<_Tpvec>::vlanes()); \ + return __riscv_vloxei32(tab, vidx, VTraits<_Tpvec>::vlanes()); \ +} +OPENCV_HAL_IMPL_RVV_LUT_QUADS(v_int8, schar, m2, m4, m8, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_RVV_LUT_QUADS(v_int16, short, m1 , m2, m4, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_RVV_LUT_QUADS(v_int32, int, m1, m2, m2, __riscv_vlmul_trunc_u32m1) +OPENCV_HAL_IMPL_RVV_LUT_QUADS(v_float32, float, m1, m2, m2, __riscv_vlmul_trunc_u32m1) + +#define OPENCV_HAL_IMPL_RVV_LUT_VEC(_Tpvec, _Tp) \ +inline _Tpvec v_lut(const _Tp* tab, const v_int32& vidx) \ +{ \ + v_uint32 vidx_ = __riscv_vmul(__riscv_vreinterpret_u32m2(vidx), sizeof(_Tp), VTraits::vlanes()); \ + return __riscv_vloxei32(tab, vidx_, VTraits<_Tpvec>::vlanes()); \ +} +OPENCV_HAL_IMPL_RVV_LUT_VEC(v_float32, float) +OPENCV_HAL_IMPL_RVV_LUT_VEC(v_int32, int) +OPENCV_HAL_IMPL_RVV_LUT_VEC(v_uint32, unsigned) + +#if CV_SIMD_SCALABLE_64F +inline v_float64 v_lut(const double* tab, const v_int32& vidx) \ +{ \ + vuint32m1_t vidx_ = __riscv_vmul(__riscv_vlmul_trunc_u32m1(__riscv_vreinterpret_u32m2(vidx)), sizeof(double), VTraits::vlanes()); \ + return __riscv_vloxei32(tab, vidx_, VTraits::vlanes()); \ +} +#endif + + +inline v_uint8 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((schar*)tab, idx)); } +inline v_uint8 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((schar*)tab, idx)); } +inline v_uint8 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((schar*)tab, idx)); } +inline v_uint16 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((short*)tab, idx)); } +inline v_uint16 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((short*)tab, idx)); } +inline v_uint16 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((short*)tab, idx)); } +inline v_uint32 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((int*)tab, idx)); } +inline v_uint32 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((int*)tab, idx)); } +inline v_uint32 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((int*)tab, idx)); } +inline v_uint64 v_lut(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } +inline v_uint64 v_lut_pairs(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } + +////////////// Pack boolean //////////////////// +inline v_uint8 v_pack_b(const v_uint16& a, const v_uint16& b) +{ + return __riscv_vnsrl(__riscv_vset(__riscv_vlmul_ext_v_u16m2_u16m4(a),1,b), 0, VTraits::vlanes()); +} + +inline v_uint8 v_pack_b(const v_uint32& a, const v_uint32& b, + const v_uint32& c, const v_uint32& d) +{ + + return __riscv_vnsrl(__riscv_vnsrl(__riscv_vset(__riscv_vset(__riscv_vset(__riscv_vlmul_ext_u32m8(a),1,b),2,c),3,d), 0, VTraits::vlanes()), 0, VTraits::vlanes()); +} + +inline v_uint8 v_pack_b(const v_uint64& a, const v_uint64& b, const v_uint64& c, + const v_uint64& d, const v_uint64& e, const v_uint64& f, + const v_uint64& g, const v_uint64& h) +{ + vuint8m1_t t0 = __riscv_vnsrl(__riscv_vnsrl(__riscv_vnsrl(__riscv_vset(__riscv_vset(__riscv_vset(__riscv_vlmul_ext_u64m8(a),1,b),2,c),3,d), 0, VTraits::vlanes()), 0, VTraits::vlanes()), 0, VTraits::vlanes()); + vuint8m1_t t1 = __riscv_vnsrl(__riscv_vnsrl(__riscv_vnsrl(__riscv_vset(__riscv_vset(__riscv_vset(__riscv_vlmul_ext_u64m8(e),1,f),2,g),3,h), 0, VTraits::vlanes()), 0, VTraits::vlanes()), 0, VTraits::vlanes()); + + return __riscv_vset(__riscv_vlmul_ext_u8m2(t0), 1, t1); +} + +////////////// Arithmetics ////////////// +#define OPENCV_HAL_IMPL_RVV_BIN_OP(_Tpvec, ocv_intrin, rvv_intrin) \ +inline _Tpvec v_##ocv_intrin(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return rvv_intrin(a, b, VTraits<_Tpvec>::vlanes()); \ +} + +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint8, add, __riscv_vsaddu) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint8, sub, __riscv_vssubu) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int8, add, __riscv_vsadd) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int8, sub, __riscv_vssub) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint16, add, __riscv_vsaddu) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint16, sub, __riscv_vssubu) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int16, add, __riscv_vsadd) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int16, sub, __riscv_vssub) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint32, add, __riscv_vadd) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint32, sub, __riscv_vsub) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint32, mul, __riscv_vmul) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int32, add, __riscv_vadd) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int32, sub, __riscv_vsub) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int32, mul, __riscv_vmul) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_float32, add, __riscv_vfadd) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_float32, sub, __riscv_vfsub) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_float32, mul, __riscv_vfmul) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_float32, div, __riscv_vfdiv) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint64, add, __riscv_vadd) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint64, sub, __riscv_vsub) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int64, add, __riscv_vadd) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int64, sub, __riscv_vsub) + +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_BIN_OP(v_float64, add, __riscv_vfadd) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_float64, sub, __riscv_vfsub) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_float64, mul, __riscv_vfmul) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_float64, div, __riscv_vfdiv) +#endif + +#define OPENCV_HAL_IMPL_RVV_BIN_MADD(_Tpvec, rvv_add) \ +template \ +inline _Tpvec v_add(const _Tpvec& f1, const _Tpvec& f2, const Args&... vf) { \ + return v_add(rvv_add(f1, f2, VTraits<_Tpvec>::vlanes()), vf...); \ +} +#define OPENCV_HAL_IMPL_RVV_BIN_MMUL(_Tpvec, rvv_mul) \ +template \ +inline _Tpvec v_mul(const _Tpvec& f1, const _Tpvec& f2, const Args&... vf) { \ + return v_mul(rvv_mul(f1, f2, VTraits<_Tpvec>::vlanes()), vf...); \ +} +OPENCV_HAL_IMPL_RVV_BIN_MADD(v_uint8, __riscv_vsaddu) +OPENCV_HAL_IMPL_RVV_BIN_MADD(v_int8, __riscv_vsadd) +OPENCV_HAL_IMPL_RVV_BIN_MADD(v_uint16, __riscv_vsaddu) +OPENCV_HAL_IMPL_RVV_BIN_MADD(v_int16, __riscv_vsadd) +OPENCV_HAL_IMPL_RVV_BIN_MADD(v_uint32, __riscv_vadd) +OPENCV_HAL_IMPL_RVV_BIN_MADD(v_int32, __riscv_vadd) +OPENCV_HAL_IMPL_RVV_BIN_MADD(v_float32, __riscv_vfadd) +OPENCV_HAL_IMPL_RVV_BIN_MADD(v_uint64, __riscv_vadd) +OPENCV_HAL_IMPL_RVV_BIN_MADD(v_int64, __riscv_vadd) + +OPENCV_HAL_IMPL_RVV_BIN_MMUL(v_uint32, __riscv_vmul) +OPENCV_HAL_IMPL_RVV_BIN_MMUL(v_int32, __riscv_vmul) +OPENCV_HAL_IMPL_RVV_BIN_MMUL(v_float32, __riscv_vfmul) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_BIN_MADD(v_float64, __riscv_vfadd) +OPENCV_HAL_IMPL_RVV_BIN_MMUL(v_float64, __riscv_vfmul) +#endif + +#define OPENCV_HAL_IMPL_RVV_MUL_EXPAND(_Tpvec, _Tpwvec, _TpwvecM2, suffix, wmul) \ +inline void v_mul_expand(const _Tpvec& a, const _Tpvec& b, _Tpwvec& c, _Tpwvec& d) \ +{ \ + _TpwvecM2 temp = wmul(a, b, VTraits<_Tpvec>::vlanes()); \ + c = __riscv_vget_##suffix##m2(temp, 0); \ + d = __riscv_vget_##suffix##m2(temp, 1); \ +} + +OPENCV_HAL_IMPL_RVV_MUL_EXPAND(v_uint8, v_uint16, vuint16m4_t, u16, __riscv_vwmulu) +OPENCV_HAL_IMPL_RVV_MUL_EXPAND(v_int8, v_int16, vint16m4_t, i16, __riscv_vwmul) +OPENCV_HAL_IMPL_RVV_MUL_EXPAND(v_uint16, v_uint32, vuint32m4_t, u32, __riscv_vwmulu) +OPENCV_HAL_IMPL_RVV_MUL_EXPAND(v_int16, v_int32, vint32m4_t, i32, __riscv_vwmul) +OPENCV_HAL_IMPL_RVV_MUL_EXPAND(v_uint32, v_uint64, vuint64m4_t, u64, __riscv_vwmulu) + +inline v_int16 v_mul_hi(const v_int16& a, const v_int16& b) +{ + return __riscv_vmulh(a, b, VTraits::vlanes()); +} +inline v_uint16 v_mul_hi(const v_uint16& a, const v_uint16& b) +{ + return __riscv_vmulhu(a, b, VTraits::vlanes()); +} + +////////////// Arithmetics (wrap)////////////// +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint8, add_wrap, __riscv_vadd) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int8, add_wrap, __riscv_vadd) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint16, add_wrap, __riscv_vadd) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int16, add_wrap, __riscv_vadd) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint8, sub_wrap, __riscv_vsub) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int8, sub_wrap, __riscv_vsub) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint16, sub_wrap, __riscv_vsub) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int16, sub_wrap, __riscv_vsub) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint8, mul_wrap, __riscv_vmul) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int8, mul_wrap, __riscv_vmul) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint16, mul_wrap, __riscv_vmul) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int16, mul_wrap, __riscv_vmul) + +//////// Saturating Multiply //////// +#define OPENCV_HAL_IMPL_RVV_MUL_SAT(_Tpvec, _clip, _wmul) \ +inline _Tpvec v_mul(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _clip(_wmul(a, b, VTraits<_Tpvec>::vlanes()), 0, 0, VTraits<_Tpvec>::vlanes()); \ +} \ +template \ +inline _Tpvec v_mul(const _Tpvec& a1, const _Tpvec& a2, const Args&... va) { \ + return v_mul(_clip(_wmul(a1, a2, VTraits<_Tpvec>::vlanes()), 0, 0, VTraits<_Tpvec>::vlanes()), va...); \ +} + +OPENCV_HAL_IMPL_RVV_MUL_SAT(v_uint8, __riscv_vnclipu, __riscv_vwmulu) +OPENCV_HAL_IMPL_RVV_MUL_SAT(v_int8, __riscv_vnclip, __riscv_vwmul) +OPENCV_HAL_IMPL_RVV_MUL_SAT(v_uint16, __riscv_vnclipu, __riscv_vwmulu) +OPENCV_HAL_IMPL_RVV_MUL_SAT(v_int16, __riscv_vnclip, __riscv_vwmul) + +////////////// Bitwise logic ////////////// + +#define OPENCV_HAL_IMPL_RVV_LOGIC_OP(_Tpvec, vl) \ +inline _Tpvec v_and(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return __riscv_vand(a, b, vl); \ +} \ +inline _Tpvec v_or(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return __riscv_vor(a, b, vl); \ +} \ +inline _Tpvec v_xor(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return __riscv_vxor(a, b, vl); \ +} \ +inline _Tpvec v_not (const _Tpvec& a) \ +{ \ + return __riscv_vnot(a, vl); \ +} + +OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_uint8, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_int8, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_uint16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_int16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_uint32, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_int32, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_uint64, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_int64, VTraits::vlanes()) + +#define OPENCV_HAL_IMPL_RVV_FLT_BIT_OP(intrin) \ +inline v_float32 intrin (const v_float32& a, const v_float32& b) \ +{ \ + return __riscv_vreinterpret_f32m2(intrin(__riscv_vreinterpret_i32m2(a), __riscv_vreinterpret_i32m2(b))); \ +} +OPENCV_HAL_IMPL_RVV_FLT_BIT_OP(v_and) +OPENCV_HAL_IMPL_RVV_FLT_BIT_OP(v_or) +OPENCV_HAL_IMPL_RVV_FLT_BIT_OP(v_xor) + +inline v_float32 v_not (const v_float32& a) \ +{ \ + return __riscv_vreinterpret_f32m2(v_not(__riscv_vreinterpret_i32m2(a))); \ +} + +#if CV_SIMD_SCALABLE_64F +#define OPENCV_HAL_IMPL_RVV_FLT64_BIT_OP(intrin) \ +inline v_float64 intrin (const v_float64& a, const v_float64& b) \ +{ \ + return __riscv_vreinterpret_f64m2(intrin(__riscv_vreinterpret_i64m2(a), __riscv_vreinterpret_i64m2(b))); \ +} +OPENCV_HAL_IMPL_RVV_FLT64_BIT_OP(v_and) +OPENCV_HAL_IMPL_RVV_FLT64_BIT_OP(v_or) +OPENCV_HAL_IMPL_RVV_FLT64_BIT_OP(v_xor) + +inline v_float64 v_not (const v_float64& a) \ +{ \ + return __riscv_vreinterpret_f64m2(v_not(__riscv_vreinterpret_i64m2(a))); \ +} +#endif + + +////////////// Bitwise shifts ////////////// +/* Usage +1. v_shl(vec); +2. v_shl(vec, N); // instead of vec << N, when N is non-constant. +*/ + +#define OPENCV_HAL_IMPL_RVV_UNSIGNED_SHIFT_OP(_Tpvec, vl) \ +template inline _Tpvec v_shl(const _Tpvec& a, int n = s) \ +{ \ + return _Tpvec(__riscv_vsll(a, uint8_t(n), vl)); \ +} \ +template inline _Tpvec v_shr(const _Tpvec& a, int n = s) \ +{ \ + return _Tpvec(__riscv_vsrl(a, uint8_t(n), vl)); \ +} + +#define OPENCV_HAL_IMPL_RVV_SIGNED_SHIFT_OP(_Tpvec, vl) \ +template inline _Tpvec v_shl(const _Tpvec& a, int n = s) \ +{ \ + return _Tpvec(__riscv_vsll(a, uint8_t(n), vl)); \ +} \ +template inline _Tpvec v_shr(const _Tpvec& a, int n = s) \ +{ \ + return _Tpvec(__riscv_vsra(a, uint8_t(n), vl)); \ +} + +OPENCV_HAL_IMPL_RVV_UNSIGNED_SHIFT_OP(v_uint16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_UNSIGNED_SHIFT_OP(v_uint32, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_UNSIGNED_SHIFT_OP(v_uint64, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_SIGNED_SHIFT_OP(v_int16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_SIGNED_SHIFT_OP(v_int32, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_SIGNED_SHIFT_OP(v_int64, VTraits::vlanes()) + +////////////// Comparison ////////////// +#define OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, op, intrin, suffix) \ +inline _Tpvec v_##op(const _Tpvec& a, const _Tpvec& b) \ +{ \ + size_t VLEN = VTraits<_Tpvec>::vlanes(); \ + uint64_t ones = -1; \ + return __riscv_vmerge(__riscv_vmv_v_x_##suffix##m2(0, VLEN), ones, intrin(a, b, VLEN), VLEN); \ +} + +#define OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, op, intrin, suffix) \ +inline _Tpvec v_##op (const _Tpvec& a, const _Tpvec& b) \ +{ \ + size_t VLEN = VTraits<_Tpvec>::vlanes(); \ + union { uint64_t u; VTraits<_Tpvec>::lane_type d; } ones; \ + ones.u = -1; \ + auto diff = intrin(a, b, VLEN); \ + auto z = __riscv_vfmv_v_f_##suffix##m2(0, VLEN); \ + auto res = __riscv_vfmerge(z, ones.d, diff, VLEN); \ + return _Tpvec(res); \ +} //TODO + +#define OPENCV_HAL_IMPL_RVV_UNSIGNED_CMP(_Tpvec, suffix) \ +OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, eq, __riscv_vmseq, suffix) \ +OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, ne, __riscv_vmsne, suffix) \ +OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, lt, __riscv_vmsltu, suffix) \ +OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, gt, __riscv_vmsgtu, suffix) \ +OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, le, __riscv_vmsleu, suffix) \ +OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, ge, __riscv_vmsgeu, suffix) + +#define OPENCV_HAL_IMPL_RVV_SIGNED_CMP(_Tpvec, suffix) \ +OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, eq, __riscv_vmseq, suffix) \ +OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, ne, __riscv_vmsne, suffix) \ +OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, lt, __riscv_vmslt, suffix) \ +OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, gt, __riscv_vmsgt, suffix) \ +OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, le, __riscv_vmsle, suffix) \ +OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, ge, __riscv_vmsge, suffix) + +#define OPENCV_HAL_IMPL_RVV_FLOAT_CMP(_Tpvec, suffix) \ +OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, eq, __riscv_vmfeq, suffix) \ +OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, ne, __riscv_vmfne, suffix) \ +OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, lt, __riscv_vmflt, suffix) \ +OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, gt, __riscv_vmfgt, suffix) \ +OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, le, __riscv_vmfle, suffix) \ +OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, ge, __riscv_vmfge, suffix) + + +OPENCV_HAL_IMPL_RVV_UNSIGNED_CMP(v_uint8, u8) +OPENCV_HAL_IMPL_RVV_UNSIGNED_CMP(v_uint16, u16) +OPENCV_HAL_IMPL_RVV_UNSIGNED_CMP(v_uint32, u32) +OPENCV_HAL_IMPL_RVV_UNSIGNED_CMP(v_uint64, u64) +OPENCV_HAL_IMPL_RVV_SIGNED_CMP(v_int8, i8) +OPENCV_HAL_IMPL_RVV_SIGNED_CMP(v_int16, i16) +OPENCV_HAL_IMPL_RVV_SIGNED_CMP(v_int32, i32) +OPENCV_HAL_IMPL_RVV_SIGNED_CMP(v_int64, i64) +OPENCV_HAL_IMPL_RVV_FLOAT_CMP(v_float32, f32) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_FLOAT_CMP(v_float64, f64) +#endif + +inline v_float32 v_not_nan(const v_float32& a) +{ return v_eq(a, a); } + +#if CV_SIMD_SCALABLE_64F +inline v_float64 v_not_nan(const v_float64& a) +{ return v_eq(a, a); } +#endif + +////////////// Min/Max ////////////// + +#define OPENCV_HAL_IMPL_RVV_BIN_FUNC(_Tpvec, func, intrin, vl) \ +inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return intrin(a, b, vl); \ +} + +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_uint8, v_min, __riscv_vminu, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_uint8, v_max, __riscv_vmaxu, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_int8, v_min, __riscv_vmin, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_int8, v_max, __riscv_vmax, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_uint16, v_min, __riscv_vminu, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_uint16, v_max, __riscv_vmaxu, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_int16, v_min, __riscv_vmin, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_int16, v_max, __riscv_vmax, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_uint32, v_min, __riscv_vminu, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_uint32, v_max, __riscv_vmaxu, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_int32, v_min, __riscv_vmin, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_int32, v_max, __riscv_vmax, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_float32, v_min, __riscv_vfmin, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_float32, v_max, __riscv_vfmax, VTraits::vlanes()) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_float64, v_min, __riscv_vfmin, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_float64, v_max, __riscv_vfmax, VTraits::vlanes()) +#endif + +////////////// Transpose4x4 ////////////// +#define OPENCV_HAL_IMPL_RVV_ZIP4(_Tpvec, _wTpvec, suffix, convert2u, convert) \ +inline void v_zip4(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) { \ + int vl = 4; \ + _wTpvec temp = __riscv_vreinterpret_##suffix##m4(convert2u( \ + __riscv_vor(__riscv_vzext_vf2(convert(a0), vl), \ + __riscv_vreinterpret_u64m4(__riscv_vslide1up(__riscv_vreinterpret_u32m4(__riscv_vzext_vf2(convert(a1), vl)), 0, vl*2)), \ + vl))); \ + b0 = __riscv_vget_##suffix##m2(temp, 0); \ + b1 = __riscv_vget_##suffix##m2(__riscv_vrgather(temp, __riscv_vadd(__riscv_vid_v_u32m4(vl), 4, vl)/*{4,5,6,7} */, vl) ,0); \ +} + +OPENCV_HAL_IMPL_RVV_ZIP4(v_uint32, vuint32m4_t, u32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_RVV_ZIP4(v_int32, vint32m4_t, i32, __riscv_vreinterpret_u32m4, __riscv_vreinterpret_u32m2) +OPENCV_HAL_IMPL_RVV_ZIP4(v_float32, vfloat32m4_t, f32, __riscv_vreinterpret_u32m4, __riscv_vreinterpret_u32m2) + + +#define OPENCV_HAL_IMPL_RVV_TRANSPOSE4x4(_Tpvec, suffix) \ +inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, const _Tpvec& a2, const _Tpvec& a3, _Tpvec& b0, _Tpvec& b1, _Tpvec& b2, _Tpvec& b3) { \ + _Tpvec t0,t1,t2,t3; \ + v_zip4(a0, a2, t0, t2); \ + v_zip4(a1, a3, t1, t3); \ + v_zip4(t0, t1, b0, b1); \ + v_zip4(t2, t3, b2, b3); \ +} + +OPENCV_HAL_IMPL_RVV_TRANSPOSE4x4(v_uint32, u32) +OPENCV_HAL_IMPL_RVV_TRANSPOSE4x4(v_int32, i32) +OPENCV_HAL_IMPL_RVV_TRANSPOSE4x4(v_float32, f32) + +////////////// Reduce ////////////// + +#define OPENCV_HAL_IMPL_RVV_REDUCE_SUM(_Tpvec, _wTpvec, _nwTpvec, scalartype, wsuffix, vl, red) \ +inline scalartype v_reduce_sum(const _Tpvec& a) \ +{ \ + _nwTpvec zero = __riscv_vmv_v_x_##wsuffix##m1(0, vl); \ + _nwTpvec res = __riscv_vmv_v_x_##wsuffix##m1(0, vl); \ + res = __riscv_v##red(a, zero, vl); \ + return (scalartype)__riscv_vmv_x(res); \ +} +OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_uint8, v_uint16, vuint16m1_t, unsigned, u16, VTraits::vlanes(), wredsumu) +OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_int8, v_int16, vint16m1_t, int, i16, VTraits::vlanes(), wredsum) +OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_uint16, v_uint32, vuint32m1_t, unsigned, u32, VTraits::vlanes(), wredsumu) +OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_int16, v_int32, vint32m1_t, int, i32, VTraits::vlanes(), wredsum) +OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_uint32, v_uint64, vuint64m1_t, unsigned, u64, VTraits::vlanes(), wredsumu) +OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_int32, v_int64, vint64m1_t, int, i64, VTraits::vlanes(), wredsum) +OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_uint64, v_uint64, vuint64m1_t, uint64, u64, VTraits::vlanes(), redsum) +OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_int64, v_int64, vint64m1_t, int64, i64, VTraits::vlanes(), redsum) + + +#define OPENCV_HAL_IMPL_RVV_REDUCE_SUM_FP(_Tpvec, _wTpvec, _nwTpvec, scalartype, wsuffix, vl) \ +inline scalartype v_reduce_sum(const _Tpvec& a) \ +{ \ + _nwTpvec zero = __riscv_vfmv_v_f_##wsuffix##m1(0, vl); \ + _nwTpvec res = __riscv_vfmv_v_f_##wsuffix##m1(0, vl); \ + res = __riscv_vfredusum(a, zero, vl); \ + return (scalartype)__riscv_vfmv_f(res); \ +} +OPENCV_HAL_IMPL_RVV_REDUCE_SUM_FP(v_float32, v_float32, vfloat32m1_t, float, f32, VTraits::vlanes()) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_REDUCE_SUM_FP(v_float64, v_float64, vfloat64m1_t, float, f64, VTraits::vlanes()) +#endif + +#define OPENCV_HAL_IMPL_RVV_REDUCE(_Tpvec, _nTpvec, func, scalartype, suffix, vl, red) \ +inline scalartype v_reduce_##func(const _Tpvec& a) \ +{ \ + _nTpvec narrowM1 = __riscv_vlmul_trunc_##suffix##m1(a); \ + return (scalartype)__riscv_vmv_x(__riscv_v##red(a, narrowM1, vl)); \ +} + +#define OPENCV_HAL_IMPL_RVV_REDUCE_FP(_Tpvec, _nTpvec, func, scalartype, suffix, vl, red) \ +inline scalartype v_reduce_##func(const _Tpvec& a) \ +{ \ + _nTpvec narrowM1 = __riscv_vlmul_trunc_##suffix##m1(a); \ + return (scalartype)__riscv_vfmv_f(__riscv_v##red(a, narrowM1, vl)); \ +} + +OPENCV_HAL_IMPL_RVV_REDUCE(v_uint8, vuint8m1_t, min, uchar, u8, VTraits::vlanes(), redminu) +OPENCV_HAL_IMPL_RVV_REDUCE(v_int8, vint8m1_t, min, schar, i8, VTraits::vlanes(), redmin) +OPENCV_HAL_IMPL_RVV_REDUCE(v_uint16, vuint16m1_t, min, ushort, u16, VTraits::vlanes(), redminu) +OPENCV_HAL_IMPL_RVV_REDUCE(v_int16, vint16m1_t, min, short, i16, VTraits::vlanes(), redmin) +OPENCV_HAL_IMPL_RVV_REDUCE(v_uint32, vuint32m1_t, min, unsigned, u32, VTraits::vlanes(), redminu) +OPENCV_HAL_IMPL_RVV_REDUCE(v_int32, vint32m1_t, min, int, i32, VTraits::vlanes(), redmin) +OPENCV_HAL_IMPL_RVV_REDUCE_FP(v_float32, vfloat32m1_t, min, float, f32, VTraits::vlanes(), fredmin) +OPENCV_HAL_IMPL_RVV_REDUCE(v_uint8, vuint8m1_t, max, uchar, u8, VTraits::vlanes(), redmaxu) +OPENCV_HAL_IMPL_RVV_REDUCE(v_int8, vint8m1_t, max, schar, i8, VTraits::vlanes(), redmax) +OPENCV_HAL_IMPL_RVV_REDUCE(v_uint16, vuint16m1_t, max, ushort, u16, VTraits::vlanes(), redmaxu) +OPENCV_HAL_IMPL_RVV_REDUCE(v_int16, vint16m1_t, max, short, i16, VTraits::vlanes(), redmax) +OPENCV_HAL_IMPL_RVV_REDUCE(v_uint32, vuint32m1_t, max, unsigned, u32, VTraits::vlanes(), redmaxu) +OPENCV_HAL_IMPL_RVV_REDUCE(v_int32, vint32m1_t, max, int, i32, VTraits::vlanes(), redmax) +OPENCV_HAL_IMPL_RVV_REDUCE_FP(v_float32, vfloat32m1_t, max, float, f32, VTraits::vlanes(), fredmax) + +inline v_float32 v_reduce_sum4(const v_float32& a, const v_float32& b, + const v_float32& c, const v_float32& d) +{ + // 0000 1111 2222 3333 .... + vuint64m4_t vid1 = __riscv_vid_v_u64m4(VTraits::vlanes()); + vuint16m4_t t1 = __riscv_vreinterpret_u16m4(vid1); + vuint16m4_t t2 = __riscv_vslide1up(t1, 0, VTraits::vlanes()); + vuint16m4_t t3 = __riscv_vslide1up(t2, 0, VTraits::vlanes()); + vuint16m4_t t4 = __riscv_vslide1up(t3, 0, VTraits::vlanes()); + t1 = __riscv_vor( + __riscv_vor(t1, t2, VTraits::vlanes()), + __riscv_vor(t3, t4, VTraits::vlanes()), + VTraits::vlanes() + ); + + // index for transpose4X4 + vuint16m4_t vidx0 = __riscv_vmul(t1, 12, VTraits::vlanes()); + vidx0 = __riscv_vadd(vidx0, __riscv_vid_v_u16m4(VTraits::vlanes()), VTraits::vlanes()); + vuint16m4_t vidx1 = __riscv_vadd(vidx0, 4, VTraits::vlanes()); + vuint16m4_t vidx2 = __riscv_vadd(vidx0, 8, VTraits::vlanes()); + vuint16m4_t vidx3 = __riscv_vadd(vidx0, 12, VTraits::vlanes()); + + // zip + vuint32m4_t tempA = __riscv_vreinterpret_u32m4( \ + __riscv_vor(__riscv_vzext_vf2(__riscv_vreinterpret_u32m2(a), VTraits::vlanes()), \ + __riscv_vreinterpret_u64m4(__riscv_vslide1up(__riscv_vreinterpret_u32m4(__riscv_vzext_vf2(__riscv_vreinterpret_u32m2(c), VTraits::vlanes())), 0, VTraits::vlanes())), \ + VTraits::vlanes())); \ + vuint32m4_t tempB = __riscv_vreinterpret_u32m4( \ + __riscv_vor(__riscv_vzext_vf2(__riscv_vreinterpret_u32m2(b), VTraits::vlanes()), \ + __riscv_vreinterpret_u64m4(__riscv_vslide1up(__riscv_vreinterpret_u32m4(__riscv_vzext_vf2(__riscv_vreinterpret_u32m2(d), VTraits::vlanes())), 0, VTraits::vlanes())), \ + VTraits::vlanes())); \ + vfloat32m8_t temp = __riscv_vreinterpret_f32m8(__riscv_vreinterpret_u32m8( \ + __riscv_vor(__riscv_vzext_vf2(tempA, VTraits::vlanes()), \ + __riscv_vreinterpret_u64m8(__riscv_vslide1up(__riscv_vreinterpret_u32m8(__riscv_vzext_vf2(tempB, VTraits::vlanes())), 0, VTraits::vlanes())), \ + VTraits::vlanes()))); + + // transpose + vfloat32m2_t b0 = __riscv_vlmul_trunc_f32m2(__riscv_vrgatherei16(temp, vidx0, VTraits::vlanes())); + vfloat32m2_t b1 = __riscv_vlmul_trunc_f32m2(__riscv_vrgatherei16(temp, vidx1, VTraits::vlanes())); + vfloat32m2_t b2 = __riscv_vlmul_trunc_f32m2(__riscv_vrgatherei16(temp, vidx2, VTraits::vlanes())); + vfloat32m2_t b3 = __riscv_vlmul_trunc_f32m2(__riscv_vrgatherei16(temp, vidx3, VTraits::vlanes())); + + // vector add + v_float32 res = __riscv_vfadd( + __riscv_vfadd(b0, b1, VTraits::vlanes()), + __riscv_vfadd(b2, b3, VTraits::vlanes()), + VTraits::vlanes() + ); + return res; +} + +////////////// Square-Root ////////////// + +inline v_float32 v_sqrt(const v_float32& x) +{ + return __riscv_vfsqrt(x, VTraits::vlanes()); +} + +inline v_float32 v_invsqrt(const v_float32& x) +{ + v_float32 one = v_setall_f32(1.0f); + return v_div(one, v_sqrt(x)); +} + +#if CV_SIMD_SCALABLE_64F +inline v_float64 v_sqrt(const v_float64& x) +{ + return __riscv_vfsqrt(x, VTraits::vlanes()); +} + +inline v_float64 v_invsqrt(const v_float64& x) +{ + v_float64 one = v_setall_f64(1.0f); + return v_div(one, v_sqrt(x)); +} +#endif + +inline v_float32 v_magnitude(const v_float32& a, const v_float32& b) +{ + v_float32 x = __riscv_vfmacc(__riscv_vfmul(a, a, VTraits::vlanes()), b, b, VTraits::vlanes()); + return v_sqrt(x); +} + +inline v_float32 v_sqr_magnitude(const v_float32& a, const v_float32& b) +{ + return v_float32(__riscv_vfmacc(__riscv_vfmul(a, a, VTraits::vlanes()), b, b, VTraits::vlanes())); +} + +#if CV_SIMD_SCALABLE_64F +inline v_float64 v_magnitude(const v_float64& a, const v_float64& b) +{ + v_float64 x = __riscv_vfmacc(__riscv_vfmul(a, a, VTraits::vlanes()), b, b, VTraits::vlanes()); + return v_sqrt(x); +} + +inline v_float64 v_sqr_magnitude(const v_float64& a, const v_float64& b) +{ + return __riscv_vfmacc(__riscv_vfmul(a, a, VTraits::vlanes()), b, b, VTraits::vlanes()); +} +#endif + +////////////// Multiply-Add ////////////// + +inline v_float32 v_fma(const v_float32& a, const v_float32& b, const v_float32& c) +{ + return __riscv_vfmacc(c, a, b, VTraits::vlanes()); +} +inline v_int32 v_fma(const v_int32& a, const v_int32& b, const v_int32& c) +{ + return __riscv_vmacc(c, a, b, VTraits::vlanes()); +} + +inline v_float32 v_muladd(const v_float32& a, const v_float32& b, const v_float32& c) +{ + return v_fma(a, b, c); +} + +inline v_int32 v_muladd(const v_int32& a, const v_int32& b, const v_int32& c) +{ + return v_fma(a, b, c); +} + +#if CV_SIMD_SCALABLE_64F +inline v_float64 v_fma(const v_float64& a, const v_float64& b, const v_float64& c) +{ + return __riscv_vfmacc_vv_f64m2(c, a, b, VTraits::vlanes()); +} + +inline v_float64 v_muladd(const v_float64& a, const v_float64& b, const v_float64& c) +{ + return v_fma(a, b, c); +} +#endif + +////////////// Check all/any ////////////// + +#define OPENCV_HAL_IMPL_RVV_CHECK_ALLANY(_Tpvec, vl) \ +inline bool v_check_all(const _Tpvec& a) \ +{ \ + return (int)__riscv_vcpop(__riscv_vmslt(a, 0, vl), vl) == vl; \ +} \ +inline bool v_check_any(const _Tpvec& a) \ +{ \ + return (int)__riscv_vcpop(__riscv_vmslt(a, 0, vl), vl) != 0; \ +} + +OPENCV_HAL_IMPL_RVV_CHECK_ALLANY(v_int8, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_CHECK_ALLANY(v_int16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_CHECK_ALLANY(v_int32, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_CHECK_ALLANY(v_int64, VTraits::vlanes()) + + +inline bool v_check_all(const v_uint8& a) +{ return v_check_all(v_reinterpret_as_s8(a)); } +inline bool v_check_any(const v_uint8& a) +{ return v_check_any(v_reinterpret_as_s8(a)); } + +inline bool v_check_all(const v_uint16& a) +{ return v_check_all(v_reinterpret_as_s16(a)); } +inline bool v_check_any(const v_uint16& a) +{ return v_check_any(v_reinterpret_as_s16(a)); } + +inline bool v_check_all(const v_uint32& a) +{ return v_check_all(v_reinterpret_as_s32(a)); } +inline bool v_check_any(const v_uint32& a) +{ return v_check_any(v_reinterpret_as_s32(a)); } + +inline bool v_check_all(const v_float32& a) +{ return v_check_all(v_reinterpret_as_s32(a)); } +inline bool v_check_any(const v_float32& a) +{ return v_check_any(v_reinterpret_as_s32(a)); } + +inline bool v_check_all(const v_uint64& a) +{ return v_check_all(v_reinterpret_as_s64(a)); } +inline bool v_check_any(const v_uint64& a) +{ return v_check_any(v_reinterpret_as_s64(a)); } + +#if CV_SIMD_SCALABLE_64F +inline bool v_check_all(const v_float64& a) +{ return v_check_all(v_reinterpret_as_s64(a)); } +inline bool v_check_any(const v_float64& a) +{ return v_check_any(v_reinterpret_as_s64(a)); } +#endif + +////////////// abs ////////////// + +#define OPENCV_HAL_IMPL_RVV_ABSDIFF(_Tpvec, abs) \ +inline _Tpvec v_##abs(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return v_sub(v_max(a, b), v_min(a, b)); \ +} + +OPENCV_HAL_IMPL_RVV_ABSDIFF(v_uint8, absdiff) +OPENCV_HAL_IMPL_RVV_ABSDIFF(v_uint16, absdiff) +OPENCV_HAL_IMPL_RVV_ABSDIFF(v_uint32, absdiff) +OPENCV_HAL_IMPL_RVV_ABSDIFF(v_float32, absdiff) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_ABSDIFF(v_float64, absdiff) +#endif +OPENCV_HAL_IMPL_RVV_ABSDIFF(v_int8, absdiffs) +OPENCV_HAL_IMPL_RVV_ABSDIFF(v_int16, absdiffs) + +#define OPENCV_HAL_IMPL_RVV_ABSDIFF_S(_Tpvec, _rTpvec, width) \ +inline _rTpvec v_absdiff(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return __riscv_vnclipu(__riscv_vreinterpret_u##width##m4(__riscv_vwsub_vv(v_max(a, b), v_min(a, b), VTraits<_Tpvec>::vlanes())), 0, 0, VTraits<_Tpvec>::vlanes()); \ +} + +OPENCV_HAL_IMPL_RVV_ABSDIFF_S(v_int8, v_uint8, 16) +OPENCV_HAL_IMPL_RVV_ABSDIFF_S(v_int16, v_uint16, 32) +OPENCV_HAL_IMPL_RVV_ABSDIFF_S(v_int32, v_uint32, 64) + +#define OPENCV_HAL_IMPL_RVV_ABS(_Tprvec, _Tpvec, suffix) \ +inline _Tprvec v_abs(const _Tpvec& a) \ +{ \ + return v_absdiff(a, v_setzero_##suffix()); \ +} + +OPENCV_HAL_IMPL_RVV_ABS(v_uint8, v_int8, s8) +OPENCV_HAL_IMPL_RVV_ABS(v_uint16, v_int16, s16) +OPENCV_HAL_IMPL_RVV_ABS(v_uint32, v_int32, s32) +OPENCV_HAL_IMPL_RVV_ABS(v_float32, v_float32, f32) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_ABS(v_float64, v_float64, f64) +#endif + + +#define OPENCV_HAL_IMPL_RVV_REDUCE_SAD(_Tpvec, scalartype) \ +inline scalartype v_reduce_sad(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return v_reduce_sum(v_absdiff(a, b)); \ +} + +OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_uint8, unsigned) +OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_int8, unsigned) +OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_uint16, unsigned) +OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_int16, unsigned) +OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_uint32, unsigned) +OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_int32, unsigned) +OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_float32, float) + +////////////// Select ////////////// + +#define OPENCV_HAL_IMPL_RVV_SELECT(_Tpvec, vl) \ +inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ +{ \ + return __riscv_vmerge(b, a, __riscv_vmsne(mask, 0, vl), vl); \ +} + +OPENCV_HAL_IMPL_RVV_SELECT(v_uint8, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_SELECT(v_uint16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_SELECT(v_uint32, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_SELECT(v_int8, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_SELECT(v_int16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_SELECT(v_int32, VTraits::vlanes()) + +inline v_float32 v_select(const v_float32& mask, const v_float32& a, const v_float32& b) \ +{ \ + return __riscv_vmerge(b, a, __riscv_vmfne(mask, 0, VTraits::vlanes()), VTraits::vlanes()); \ +} + +#if CV_SIMD_SCALABLE_64F +inline v_float64 v_select(const v_float64& mask, const v_float64& a, const v_float64& b) \ +{ \ + return __riscv_vmerge(b, a, __riscv_vmfne(mask, 0, VTraits::vlanes()), VTraits::vlanes()); \ +} +#endif + +////////////// Rotate shift ////////////// + +#define OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(_Tpvec, suffix, vl) \ +template inline _Tpvec v_rotate_right(const _Tpvec& a) \ +{ \ + return __riscv_vslidedown(a, n, vl); \ +} \ +template inline _Tpvec v_rotate_left(const _Tpvec& a) \ +{ \ + return __riscv_vslideup(__riscv_vmv_v_x_##suffix##m2(0, vl), a, n, vl); \ +} \ +template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a) \ +{ return a; } \ +template inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return __riscv_vslideup(__riscv_vslidedown(a, n, vl), b, VTraits<_Tpvec>::vlanes() - n, vl); \ +} \ +template inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return __riscv_vslideup(__riscv_vslidedown(b, VTraits<_Tpvec>::vlanes() - n, vl), a, n, vl); \ +} \ +template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a, const _Tpvec& b) \ +{ CV_UNUSED(b); return a; } + +OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_uint8, u8, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_int8, i8, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_uint16, u16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_int16, i16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_uint32, u32, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_int32, i32, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_uint64, u64, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_int64, i64, VTraits::vlanes()) + +#define OPENCV_HAL_IMPL_RVV_ROTATE_FP(_Tpvec, suffix, vl) \ +template inline _Tpvec v_rotate_right(const _Tpvec& a) \ +{ \ + return __riscv_vslidedown(a, n, vl); \ +} \ +template inline _Tpvec v_rotate_left(const _Tpvec& a) \ +{ \ + return __riscv_vslideup(__riscv_vfmv_v_f_##suffix##m2(0, vl), a, n, vl); \ +} \ +template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a) \ +{ return a; } \ +template inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return __riscv_vslideup(__riscv_vslidedown(a, n, vl), b, VTraits<_Tpvec>::vlanes() - n, vl); \ +} \ +template inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return __riscv_vslideup(__riscv_vslidedown(b, VTraits<_Tpvec>::vlanes() - n, vl), a, n, vl); \ +} \ +template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a, const _Tpvec& b) \ +{ CV_UNUSED(b); return a; } + +OPENCV_HAL_IMPL_RVV_ROTATE_FP(v_float32, f32, VTraits::vlanes()) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_ROTATE_FP(v_float64, f64, VTraits::vlanes()) +#endif + +////////////// Convert to float ////////////// +inline v_float32 v_cvt_f32(const v_int32& a) +{ + return __riscv_vfcvt_f_x_v_f32m2(a, VTraits::vlanes()); +} + +#if CV_SIMD_SCALABLE_64F +inline v_float32 v_cvt_f32(const v_float64& a) +{ + return __riscv_vfncvt_f(__riscv_vlmul_ext_f64m4(a), VTraits::vlanes()); +} + +inline v_float32 v_cvt_f32(const v_float64& a, const v_float64& b) +{ + return __riscv_vfncvt_f(__riscv_vset(__riscv_vlmul_ext_f64m4(a),1,b), VTraits::vlanes()); +} + +inline v_float64 v_cvt_f64(const v_int32& a) +{ + return __riscv_vget_f64m2(__riscv_vfwcvt_f(a, VTraits::vlanes()), 0); +} + +inline v_float64 v_cvt_f64_high(const v_int32& a) +{ + return __riscv_vget_f64m2(__riscv_vfwcvt_f(a, VTraits::vlanes()), 1); +} + +inline v_float64 v_cvt_f64(const v_float32& a) +{ + return __riscv_vget_f64m2(__riscv_vfwcvt_f(a, VTraits::vlanes()), 0); +} + +inline v_float64 v_cvt_f64_high(const v_float32& a) +{ + return __riscv_vget_f64m2(__riscv_vfwcvt_f(a, VTraits::vlanes()), 1); +} + +inline v_float64 v_cvt_f64(const v_int64& a) +{ + return __riscv_vfcvt_f(a, VTraits::vlanes()); +} +#endif + +//////////// Broadcast ////////////// + +#define OPENCV_HAL_IMPL_RVV_BROADCAST(_Tpvec, suffix) \ +template inline _Tpvec v_broadcast_element(_Tpvec v, int i = s) \ +{ \ + return v_setall_##suffix(v_extract_n(v, i)); \ +} \ +inline _Tpvec v_broadcast_highest(_Tpvec v) \ +{ \ + return v_setall_##suffix(v_extract_n(v, VTraits<_Tpvec>::vlanes()-1)); \ +} + +OPENCV_HAL_IMPL_RVV_BROADCAST(v_uint32, u32) +OPENCV_HAL_IMPL_RVV_BROADCAST(v_int32, s32) +OPENCV_HAL_IMPL_RVV_BROADCAST(v_float32, f32) + + +////////////// Reverse ////////////// +#define OPENCV_HAL_IMPL_RVV_REVERSE(_Tpvec, width) \ +inline _Tpvec v_reverse(const _Tpvec& a) \ +{ \ + vuint##width##m2_t vidx = __riscv_vrsub(__riscv_vid_v_u##width##m2(VTraits<_Tpvec>::vlanes()), VTraits<_Tpvec>::vlanes()-1, VTraits<_Tpvec>::vlanes()); \ + return __riscv_vrgather(a, vidx, VTraits<_Tpvec>::vlanes()); \ +} +OPENCV_HAL_IMPL_RVV_REVERSE(v_uint8, 8) +OPENCV_HAL_IMPL_RVV_REVERSE(v_int8, 8) +OPENCV_HAL_IMPL_RVV_REVERSE(v_uint16, 16) +OPENCV_HAL_IMPL_RVV_REVERSE(v_int16, 16) +OPENCV_HAL_IMPL_RVV_REVERSE(v_uint32, 32) +OPENCV_HAL_IMPL_RVV_REVERSE(v_int32, 32) +OPENCV_HAL_IMPL_RVV_REVERSE(v_float32, 32) +OPENCV_HAL_IMPL_RVV_REVERSE(v_uint64, 64) +OPENCV_HAL_IMPL_RVV_REVERSE(v_int64, 64) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_REVERSE(v_float64, 64) +#endif + +//////////// Value reordering //////////// + +#define OPENCV_HAL_IMPL_RVV_EXPAND(_Tp, _Tpwvec, _Tpwvec_m2, _Tpvec, width, suffix, suffix2, cvt) \ +inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ +{ \ + _Tpwvec_m2 temp = cvt(a, VTraits<_Tpvec>::vlanes()); \ + b0 = __riscv_vget_##suffix##m2(temp, 0); \ + b1 = __riscv_vget_##suffix##m2(temp, 1); \ +} \ +inline _Tpwvec v_expand_low(const _Tpvec& a) \ +{ \ + _Tpwvec_m2 temp = cvt(a, VTraits<_Tpvec>::vlanes()); \ + return __riscv_vget_##suffix##m2(temp, 0); \ +} \ +inline _Tpwvec v_expand_high(const _Tpvec& a) \ +{ \ + _Tpwvec_m2 temp = cvt(a, VTraits<_Tpvec>::vlanes()); \ + return __riscv_vget_##suffix##m2(temp, 1); \ +} \ +inline _Tpwvec v_load_expand(const _Tp* ptr) \ +{ \ + return cvt(__riscv_vle##width##_v_##suffix2##m1(ptr, VTraits<_Tpvec>::vlanes()), VTraits<_Tpvec>::vlanes()); \ +} + +OPENCV_HAL_IMPL_RVV_EXPAND(uchar, v_uint16, vuint16m4_t, v_uint8, 8, u16, u8, __riscv_vwcvtu_x) +OPENCV_HAL_IMPL_RVV_EXPAND(schar, v_int16, vint16m4_t, v_int8, 8, i16, i8, __riscv_vwcvt_x) +OPENCV_HAL_IMPL_RVV_EXPAND(ushort, v_uint32, vuint32m4_t, v_uint16, 16, u32, u16, __riscv_vwcvtu_x) +OPENCV_HAL_IMPL_RVV_EXPAND(short, v_int32, vint32m4_t, v_int16, 16, i32, i16, __riscv_vwcvt_x) +OPENCV_HAL_IMPL_RVV_EXPAND(uint, v_uint64, vuint64m4_t, v_uint32, 32, u64, u32, __riscv_vwcvtu_x) +OPENCV_HAL_IMPL_RVV_EXPAND(int, v_int64, vint64m4_t, v_int32, 32, i64, i32, __riscv_vwcvt_x) + +inline v_uint32 v_load_expand_q(const uchar* ptr) +{ + return __riscv_vwcvtu_x(__riscv_vwcvtu_x(__riscv_vle8_v_u8mf2(ptr, VTraits::vlanes()), VTraits::vlanes()), VTraits::vlanes()); +} + +inline v_int32 v_load_expand_q(const schar* ptr) +{ + return __riscv_vwcvt_x(__riscv_vwcvt_x(__riscv_vle8_v_i8mf2(ptr, VTraits::vlanes()), VTraits::vlanes()), VTraits::vlanes()); +} + +#define OPENCV_HAL_IMPL_RVV_PACK(_Tpvec, _Tp, _wTpvec, hwidth, hsuffix, suffix, rshr, shr) \ +inline _Tpvec v_pack(const _wTpvec& a, const _wTpvec& b) \ +{ \ + return shr(__riscv_vset(__riscv_vlmul_ext_##suffix##m4(a), 1, b), 0, 0, VTraits<_Tpvec>::vlanes()); \ +} \ +inline void v_pack_store(_Tp* ptr, const _wTpvec& a) \ +{ \ + __riscv_vse##hwidth##_v_##hsuffix##m1(ptr, shr(a, 0, 0, VTraits<_Tpvec>::vlanes()), VTraits<_wTpvec>::vlanes()); \ +} \ +template inline \ +_Tpvec v_rshr_pack(const _wTpvec& a, const _wTpvec& b, int N = n) \ +{ \ + return rshr(__riscv_vset(__riscv_vlmul_ext_##suffix##m4(a), 1, b), N, 0, VTraits<_Tpvec>::vlanes()); \ +} \ +template inline \ +void v_rshr_pack_store(_Tp* ptr, const _wTpvec& a, int N = n) \ +{ \ + __riscv_vse##hwidth##_v_##hsuffix##m1(ptr, rshr(a, N, 0, VTraits<_Tpvec>::vlanes()), VTraits<_wTpvec>::vlanes()); \ +} + +#define OPENCV_HAL_IMPL_RVV_PACK_32(_Tpvec, _Tp, _wTpvec, hwidth, hsuffix, suffix, rshr, shr) \ +inline _Tpvec v_pack(const _wTpvec& a, const _wTpvec& b) \ +{ \ + return shr(__riscv_vset(__riscv_vlmul_ext_##suffix##m4(a), 1, b), 0, VTraits<_Tpvec>::vlanes()); \ +} \ +inline void v_pack_store(_Tp* ptr, const _wTpvec& a) \ +{ \ + __riscv_vse##hwidth##_v_##hsuffix##m1(ptr, shr(a, 0, VTraits<_Tpvec>::vlanes()), VTraits<_wTpvec>::vlanes()); \ +} \ +template inline \ +_Tpvec v_rshr_pack(const _wTpvec& a, const _wTpvec& b, int N = n) \ +{ \ + return rshr(__riscv_vset(__riscv_vlmul_ext_##suffix##m4(a), 1, b), N, 0, VTraits<_Tpvec>::vlanes()); \ +} \ +template inline \ +void v_rshr_pack_store(_Tp* ptr, const _wTpvec& a, int N = n) \ +{ \ + __riscv_vse##hwidth##_v_##hsuffix##m1(ptr, rshr(a, N, 0, VTraits<_Tpvec>::vlanes()), VTraits<_wTpvec>::vlanes()); \ +} + +OPENCV_HAL_IMPL_RVV_PACK(v_uint8, uchar, v_uint16, 8, u8, u16, __riscv_vnclipu, __riscv_vnclipu) +OPENCV_HAL_IMPL_RVV_PACK(v_int8, schar, v_int16, 8, i8, i16, __riscv_vnclip, __riscv_vnclip) +OPENCV_HAL_IMPL_RVV_PACK(v_uint16, ushort, v_uint32, 16, u16, u32, __riscv_vnclipu, __riscv_vnclipu) +OPENCV_HAL_IMPL_RVV_PACK(v_int16, short, v_int32, 16, i16, i32, __riscv_vnclip, __riscv_vnclip) +OPENCV_HAL_IMPL_RVV_PACK_32(v_uint32, unsigned, v_uint64, 32, u32, u64, __riscv_vnclipu, __riscv_vnsrl) +OPENCV_HAL_IMPL_RVV_PACK_32(v_int32, int, v_int64, 32, i32, i64, __riscv_vnclip, __riscv_vnsra) + +#define OPENCV_HAL_IMPL_RVV_PACK_U(_Tpvec, _Tp, _wTpvec, _wTp, hwidth, width, hsuffix, suffix, cast, hvl, vl) \ +inline _Tpvec v_pack_u(const _wTpvec& a, const _wTpvec& b) \ +{ \ + return __riscv_vnclipu(cast(__riscv_vmax(__riscv_vset(__riscv_vlmul_ext_##suffix##m4(a), 1, b), 0, vl)), 0, 0, vl); \ +} \ +inline void v_pack_u_store(_Tp* ptr, const _wTpvec& a) \ +{ \ + __riscv_vse##hwidth##_v_##hsuffix##m1(ptr, __riscv_vnclipu(__riscv_vreinterpret_u##width##m2(__riscv_vmax(a, 0, vl)), 0, 0, vl), hvl); \ +} \ +template inline \ +_Tpvec v_rshr_pack_u(const _wTpvec& a, const _wTpvec& b, int n = N) \ +{ \ + return __riscv_vnclipu(cast(__riscv_vmax(__riscv_vset(__riscv_vlmul_ext_##suffix##m4(a), 1, b), 0, vl)), n, 0, vl); \ +} \ +template inline \ +void v_rshr_pack_u_store(_Tp* ptr, const _wTpvec& a, int n = N) \ +{ \ + __riscv_vse##hwidth##_v_##hsuffix##m1(ptr, __riscv_vnclipu(__riscv_vreinterpret_u##width##m2(__riscv_vmax(a, 0, vl)), n, 0, vl), hvl); \ +} + +OPENCV_HAL_IMPL_RVV_PACK_U(v_uint8, uchar, v_int16, short, 8, 16, u8, i16, __riscv_vreinterpret_v_i16m4_u16m4, VTraits::vlanes(), VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_PACK_U(v_uint16, ushort, v_int32, int, 16, 32, u16, i32, __riscv_vreinterpret_v_i32m4_u32m4, VTraits::vlanes(), VTraits::vlanes()) + + +/* void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) + a0 = {A1 A2 A3 A4} + a1 = {B1 B2 B3 B4} +--------------- + {A1 B1 A2 B2} and {A3 B3 A4 B4} +*/ + +#define OPENCV_HAL_IMPL_RVV_ZIP(_Tpvec, _wTpvec, suffix, width, width2, convert2um2, convert2um1) \ +inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) { \ + _wTpvec temp = __riscv_vreinterpret_##suffix##m4(convert2um2( \ + __riscv_vor(__riscv_vzext_vf2(convert2um1(a0), VTraits<_Tpvec>::vlanes()*2), \ + __riscv_vreinterpret_u##width2##m4(__riscv_vslide1up(__riscv_vreinterpret_u##width##m4(__riscv_vzext_vf2(convert2um1(a1), VTraits<_Tpvec>::vlanes()*2)), 0, VTraits<_Tpvec>::vlanes()*2)), \ + VTraits<_Tpvec>::vlanes()))); \ + b0 = __riscv_vget_##suffix##m2(temp, 0); \ + b1 = __riscv_vget_##suffix##m2(temp, 1); \ +} +OPENCV_HAL_IMPL_RVV_ZIP(v_uint8, vuint8m4_t, u8, 8, 16, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_RVV_ZIP(v_int8, vint8m4_t, i8, 8, 16, __riscv_vreinterpret_u8m4, __riscv_vreinterpret_u8m2) +OPENCV_HAL_IMPL_RVV_ZIP(v_uint16, vuint16m4_t, u16, 16, 32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_RVV_ZIP(v_int16, vint16m4_t, i16, 16, 32, __riscv_vreinterpret_u16m4, __riscv_vreinterpret_u16m2) +OPENCV_HAL_IMPL_RVV_ZIP(v_uint32, vuint32m4_t, u32, 32, 64, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_RVV_ZIP(v_int32, vint32m4_t, i32, 32, 64, __riscv_vreinterpret_u32m4, __riscv_vreinterpret_u32m2) +OPENCV_HAL_IMPL_RVV_ZIP(v_float32, vfloat32m4_t, f32, 32, 64, __riscv_vreinterpret_u32m4, __riscv_vreinterpret_u32m2) + +#if CV_SIMD_SCALABLE_64F +inline void v_zip(const v_float64& a0, const v_float64& a1, v_float64& b0, v_float64& b1) { \ + vuint16mf2_t idx0 = __riscv_vid_v_u16mf2(VTraits::vlanes()); + vuint16mf2_t idx1 = __riscv_vadd(idx0, VTraits::vlanes(), VTraits::vlanes()); + vuint16m1_t idx = __riscv_vreinterpret_u16m1(( \ + __riscv_vor(__riscv_vzext_vf2(idx0, VTraits::vlanes()), \ + __riscv_vreinterpret_u32m1(__riscv_vslide1up(__riscv_vreinterpret_u16m1(__riscv_vzext_vf2(idx1, VTraits::vlanes())), 0, VTraits::vlanes())), \ + VTraits::vlanes()))); +#if 0 + vfloat64m4_t temp = __riscv_vcreate_v_f64m2_f64m4(a0, a1); +#else // TODO: clean up when RVV Intrinsic is frozen. + vfloat64m4_t temp = __riscv_vlmul_ext_f64m4(a0); + temp = __riscv_vset(temp, 1, a1); +#endif + temp = __riscv_vrgatherei16(temp, idx, VTraits::vlanes()*2); + b0 = __riscv_vget_f64m2(temp, 0); \ + b1 = __riscv_vget_f64m2(temp, 1); \ +} +#endif + +#define OPENCV_HAL_IMPL_RVV_UNPACKS(_Tpvec, width) \ +inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return __riscv_vslideup(a, b, VTraits<_Tpvec>::vlanes()/2, VTraits<_Tpvec>::vlanes());\ +} \ +inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return __riscv_vslideup( \ + __riscv_vslidedown(a, VTraits<_Tpvec>::vlanes()/2, VTraits<_Tpvec>::vlanes()), \ + __riscv_vslidedown(b, VTraits<_Tpvec>::vlanes()/2, VTraits<_Tpvec>::vlanes()), \ + VTraits<_Tpvec>::vlanes()/2, \ + VTraits<_Tpvec>::vlanes()); \ +} \ +inline void v_recombine(const _Tpvec& a, const _Tpvec& b, _Tpvec& c, _Tpvec& d) \ +{ \ + c = v_combine_low(a, b); \ + d = v_combine_high(a, b); \ +} + +OPENCV_HAL_IMPL_RVV_UNPACKS(v_uint8, 8) +OPENCV_HAL_IMPL_RVV_UNPACKS(v_int8, 8) +OPENCV_HAL_IMPL_RVV_UNPACKS(v_uint16, 16) +OPENCV_HAL_IMPL_RVV_UNPACKS(v_int16, 16) +OPENCV_HAL_IMPL_RVV_UNPACKS(v_uint32, 32) +OPENCV_HAL_IMPL_RVV_UNPACKS(v_int32, 32) +OPENCV_HAL_IMPL_RVV_UNPACKS(v_float32, 32) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_UNPACKS(v_float64, 64) +#endif + +#define OPENCV_HAL_IMPL_RVV_INTERLEAVED(_Tpvec, _Tp, suffix, width, hwidth, vl) \ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b) \ +{ \ + a = __riscv_vlse##width##_v_##suffix##m2(ptr , sizeof(_Tp)*2, VTraits::vlanes()); \ + b = __riscv_vlse##width##_v_##suffix##m2(ptr+1, sizeof(_Tp)*2, VTraits::vlanes()); \ +}\ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, v_##_Tpvec& c) \ +{ \ + a = __riscv_vlse##width##_v_##suffix##m2(ptr , sizeof(_Tp)*3, VTraits::vlanes()); \ + b = __riscv_vlse##width##_v_##suffix##m2(ptr+1, sizeof(_Tp)*3, VTraits::vlanes()); \ + c = __riscv_vlse##width##_v_##suffix##m2(ptr+2, sizeof(_Tp)*3, VTraits::vlanes()); \ +} \ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, \ + v_##_Tpvec& c, v_##_Tpvec& d) \ +{ \ + \ + a = __riscv_vlse##width##_v_##suffix##m2(ptr , sizeof(_Tp)*4, VTraits::vlanes()); \ + b = __riscv_vlse##width##_v_##suffix##m2(ptr+1, sizeof(_Tp)*4, VTraits::vlanes()); \ + c = __riscv_vlse##width##_v_##suffix##m2(ptr+2, sizeof(_Tp)*4, VTraits::vlanes()); \ + d = __riscv_vlse##width##_v_##suffix##m2(ptr+3, sizeof(_Tp)*4, VTraits::vlanes()); \ +} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + __riscv_vsse##width(ptr, sizeof(_Tp)*2, a, VTraits::vlanes()); \ + __riscv_vsse##width(ptr+1, sizeof(_Tp)*2, b, VTraits::vlanes()); \ +} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ + const v_##_Tpvec& c, hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + __riscv_vsse##width(ptr, sizeof(_Tp)*3, a, VTraits::vlanes()); \ + __riscv_vsse##width(ptr+1, sizeof(_Tp)*3, b, VTraits::vlanes()); \ + __riscv_vsse##width(ptr+2, sizeof(_Tp)*3, c, VTraits::vlanes()); \ +} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ + const v_##_Tpvec& c, const v_##_Tpvec& d, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ +{ \ + __riscv_vsse##width(ptr, sizeof(_Tp)*4, a, VTraits::vlanes()); \ + __riscv_vsse##width(ptr+1, sizeof(_Tp)*4, b, VTraits::vlanes()); \ + __riscv_vsse##width(ptr+2, sizeof(_Tp)*4, c, VTraits::vlanes()); \ + __riscv_vsse##width(ptr+3, sizeof(_Tp)*4, d, VTraits::vlanes()); \ +} + +OPENCV_HAL_IMPL_RVV_INTERLEAVED(uint8, uchar, u8, 8, 4, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INTERLEAVED(int8, schar, i8, 8, 4, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INTERLEAVED(uint16, ushort, u16, 16, 8, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INTERLEAVED(int16, short, i16, 16, 8, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INTERLEAVED(uint32, unsigned, u32, 32, 16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INTERLEAVED(int32, int, i32, 32, 16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INTERLEAVED(float32, float, f32, 32, 16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INTERLEAVED(uint64, uint64, u64, 64, 32, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INTERLEAVED(int64, int64, i64, 64, 32, VTraits::vlanes()) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_INTERLEAVED(float64, double, f64, 64, 32, VTraits::vlanes()) +#endif + +static uint64_t idx_interleave_pairs[] = { \ + 0x0705060403010200, 0x0f0d0e0c0b090a08, 0x1715161413111210, 0x1f1d1e1c1b191a18, \ + 0x2725262423212220, 0x2f2d2e2c2b292a28, 0x3735363433313230, 0x3f3d3e3c3b393a38, \ + 0x4745464443414240, 0x4f4d4e4c4b494a48, 0x5755565453515250, 0x5f5d5e5c5b595a58, \ + 0x6765666463616260, 0x6f6d6e6c6b696a68, 0x7775767473717270, 0x7f7d7e7c7b797a78}; + +static uint64_t idx_interleave_quads[] = { \ + 0x0703060205010400, 0x0f0b0e0a0d090c08, 0x1713161215111410, 0x1f1b1e1a1d191c18, \ + 0x2723262225212420, 0x2f2b2e2a2d292c28, 0x3733363235313430, 0x3f3b3e3a3d393c38, \ + 0x4743464245414440, 0x4f4b4e4a4d494c48, 0x5753565255515450, 0x5f5b5e5a5d595c58, \ + 0x6763666265616460, 0x6f6b6e6a6d696c68, 0x7773767275717470, 0x7f7b7e7a7d797c78}; + +#define OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ_NOEXPEND(_Tpvec, func) \ +inline _Tpvec v_interleave_##func(const _Tpvec& vec) { \ + CV_CheckLE(VTraits<_Tpvec>::vlanes(), VTraits<_Tpvec>::max_nlanes, "RVV implementation only supports VLEN in the range [128, 1024]"); \ + vuint8m2_t vidx = __riscv_vundefined_u8m2();\ + vidx = __riscv_vreinterpret_u8m2(__riscv_vle64_v_u64m2(idx_interleave_##func, 16)); \ + return __riscv_vrgather(vec, vidx, VTraits::vlanes()); \ +} +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ_NOEXPEND(v_uint8, pairs) +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ_NOEXPEND(v_int8, pairs) +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ_NOEXPEND(v_uint8, quads) +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ_NOEXPEND(v_int8, quads) + +#define OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(_Tpvec, width, vzext_vfx, func) \ +inline _Tpvec v_interleave_##func(const _Tpvec& vec) { \ + CV_CheckLE(VTraits<_Tpvec>::vlanes(), VTraits<_Tpvec>::max_nlanes, "RVV implementation only supports VLEN in the range [128, 1024]"); \ + vuint##width##m2_t vidx = __riscv_vundefined_u##width##m2();\ + vidx = __riscv_vget_u##width##m2(vzext_vfx(__riscv_vreinterpret_u8m2(__riscv_vle64_v_u64m2(idx_interleave_##func, 16)), VTraits::vlanes()), 0); \ + return __riscv_vrgather(vec, vidx, VTraits<_Tpvec>::vlanes()); \ +} + +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_uint16, 16, __riscv_vzext_vf2, pairs) +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_int16, 16, __riscv_vzext_vf2, pairs) +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_uint32, 32, __riscv_vzext_vf4, pairs) +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_int32, 32, __riscv_vzext_vf4, pairs) +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_float32, 32, __riscv_vzext_vf4, pairs) + +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_uint16, 16, __riscv_vzext_vf2, quads) +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_int16, 16, __riscv_vzext_vf2, quads) +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_uint32, 32, __riscv_vzext_vf4, quads) +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_int32, 32, __riscv_vzext_vf4, quads) +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_float32, 32, __riscv_vzext_vf4, quads) + +//////////// PopCount ////////// +static const unsigned char popCountTable[256] = +{ + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, +}; +#define OPENCV_HAL_IMPL_RVV_HADD(_Tpvec, _Tpvec2, _Tm2, width, width2, suffix, add) \ +static inline _Tpvec2 v_hadd(_Tpvec a) { \ + vuint##width2##m2_t oneX2 = __riscv_vmv_v_x_u##width2##m2(1, VTraits::vlanes()); \ + vuint##width##m2_t one = __riscv_vreinterpret_u##width##m2(oneX2); \ + _Tm2 res = add(a, __riscv_vslide1down(a, 0, VTraits::vlanes()), VTraits::vlanes()); \ + return __riscv_vget_##suffix##m2(__riscv_vcompress(res, __riscv_vmseq(one, 1, VTraits::vlanes()), VTraits::vlanes()), 0); \ +} +OPENCV_HAL_IMPL_RVV_HADD(v_uint8, v_uint16, vuint16m4_t, 8, 16, u16, __riscv_vwaddu_vv) +OPENCV_HAL_IMPL_RVV_HADD(v_uint16, v_uint32, vuint32m4_t, 16, 32, u32, __riscv_vwaddu_vv) +OPENCV_HAL_IMPL_RVV_HADD(v_uint32, v_uint64, vuint64m4_t, 32, 64, u64, __riscv_vwaddu_vv) +OPENCV_HAL_IMPL_RVV_HADD(v_int8, v_int16, vint16m4_t, 8, 16, i16, __riscv_vwadd_vv) +OPENCV_HAL_IMPL_RVV_HADD(v_int16, v_int32, vint32m4_t, 16, 32, i32, __riscv_vwadd_vv) +OPENCV_HAL_IMPL_RVV_HADD(v_int32, v_int64, vint64m4_t, 32, 64, i64, __riscv_vwadd_vv) + +OPENCV_HAL_IMPL_RVV_HADD(vint32m4_t, v_int32, vint32m4_t, 16, 32, i32, __riscv_vadd) +OPENCV_HAL_IMPL_RVV_HADD(vint64m4_t, v_int64, vint64m4_t, 32, 64, i64, __riscv_vadd) + +inline v_uint8 v_popcount(const v_uint8& a) +{ + return __riscv_vloxei8(popCountTable, a, VTraits::vlanes()); +} +inline v_uint16 v_popcount(const v_uint16& a) +{ + return v_hadd(v_popcount(__riscv_vreinterpret_u8m2(a))); +} +inline v_uint32 v_popcount(const v_uint32& a) +{ + return v_hadd(v_hadd(v_popcount(__riscv_vreinterpret_u8m2(a)))); +} +inline v_uint64 v_popcount(const v_uint64& a) +{ + return v_hadd(v_hadd(v_hadd(v_popcount(__riscv_vreinterpret_u8m2(a))))); +} + +inline v_uint8 v_popcount(const v_int8& a) +{ + return v_popcount(v_abs(a));\ +} +inline v_uint16 v_popcount(const v_int16& a) +{ + return v_popcount(v_abs(a));\ +} +inline v_uint32 v_popcount(const v_int32& a) +{ + return v_popcount(v_abs(a));\ +} +inline v_uint64 v_popcount(const v_int64& a) +{ + // max(0 - a) is used, since v_abs does not support 64-bit integers. + return v_popcount(v_reinterpret_as_u64(__riscv_vmax(a, v_sub(v_setzero_s64(), a), VTraits::vlanes()))); +} + + +//////////// SignMask //////////// +#define OPENCV_HAL_IMPL_RVV_SIGNMASK_OP(_Tpvec) \ +inline int v_signmask(const _Tpvec& a) \ +{ \ + uint8_t ans[4] = {0}; \ + __riscv_vsm(ans, __riscv_vmslt(a, 0, VTraits<_Tpvec>::vlanes()), VTraits<_Tpvec>::vlanes()); \ + return *(reinterpret_cast(ans)) & (((__int128_t)1 << VTraits<_Tpvec>::vlanes()) - 1); \ +} \ +inline int v_scan_forward(const _Tpvec& a) \ +{ \ + return (int)__riscv_vfirst(__riscv_vmslt(a, 0, VTraits<_Tpvec>::vlanes()), VTraits<_Tpvec>::vlanes()); \ +} + +OPENCV_HAL_IMPL_RVV_SIGNMASK_OP(v_int8) +OPENCV_HAL_IMPL_RVV_SIGNMASK_OP(v_int16) +OPENCV_HAL_IMPL_RVV_SIGNMASK_OP(v_int32) +OPENCV_HAL_IMPL_RVV_SIGNMASK_OP(v_int64) + +inline int64 v_signmask(const v_uint8& a) +{ return v_signmask(v_reinterpret_as_s8(a)); } +inline int64 v_signmask(const v_uint16& a) +{ return v_signmask(v_reinterpret_as_s16(a)); } +inline int v_signmask(const v_uint32& a) +{ return v_signmask(v_reinterpret_as_s32(a)); } +inline int v_signmask(const v_float32& a) +{ return v_signmask(v_reinterpret_as_s32(a)); } +inline int v_signmask(const v_uint64& a) +{ return v_signmask(v_reinterpret_as_s64(a)); } +#if CV_SIMD_SCALABLE_64F +inline int v_signmask(const v_float64& a) +{ return v_signmask(v_reinterpret_as_s64(a)); } +#endif + +//////////// Scan forward //////////// +inline int v_scan_forward(const v_uint8& a) +{ return v_scan_forward(v_reinterpret_as_s8(a)); } +inline int v_scan_forward(const v_uint16& a) +{ return v_scan_forward(v_reinterpret_as_s16(a)); } +inline int v_scan_forward(const v_uint32& a) +{ return v_scan_forward(v_reinterpret_as_s32(a)); } +inline int v_scan_forward(const v_float32& a) +{ return v_scan_forward(v_reinterpret_as_s32(a)); } +inline int v_scan_forward(const v_uint64& a) +{ return v_scan_forward(v_reinterpret_as_s64(a)); } +#if CV_SIMD_SCALABLE_64F +inline int v_scan_forward(const v_float64& a) +{ return v_scan_forward(v_reinterpret_as_s64(a)); } +#endif + +//////////// Pack triplets //////////// +// {A0, A1, A2, A3, B0, B1, B2, B3, C0 ...} --> {A0, A1, A2, B0, B1, B2, C0 ...} +// mask: {0,0,0,1, ...} -> {T,T,T,F, ...} +#define OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(_Tpvec, v_trunc) \ +inline _Tpvec v_pack_triplets(const _Tpvec& vec) { \ + size_t vl = VTraits::vlanes(); \ + vuint32m2_t one = __riscv_vmv_v_x_u32m2(1, VTraits::vlanes()); \ + vuint8m2_t zero = __riscv_vmv_v_x_u8m2(0, vl); \ + vuint8m2_t mask = __riscv_vreinterpret_u8m2(one); \ + return __riscv_vcompress(vec, __riscv_vmseq(v_trunc(__riscv_vslideup(zero, mask, 3, vl)), 0, vl), VTraits<_Tpvec>::vlanes()); \ +} + +OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_uint8, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_int8, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_uint16, __riscv_vlmul_trunc_u8m1) +OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_int16, __riscv_vlmul_trunc_u8m1) +OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_uint32, __riscv_vlmul_trunc_u8mf2) +OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_int32, __riscv_vlmul_trunc_u8mf2) +OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_float32, __riscv_vlmul_trunc_u8mf2) +OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_uint64, __riscv_vlmul_trunc_u8mf4) +OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_int64, __riscv_vlmul_trunc_u8mf4) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_float64, __riscv_vlmul_trunc_u8mf4) +#endif + + +////// FP16 support /////// + +#if defined(__riscv_zfh) && __riscv_zfh +inline v_float32 v_load_expand(const hfloat* ptr) +{ + return __riscv_vfwcvt_f(__riscv_vle16_v_f16m1((_Float16*)ptr, VTraits::vlanes()) ,VTraits::vlanes());; +} + +inline void v_pack_store(hfloat* ptr, const v_float32& v) +{ + __riscv_vse16_v_f16m1((_Float16*)ptr, __riscv_vfncvt_f_f_w_f16m1(v, VTraits::vlanes()), VTraits::vlanes()); +} +#else +inline v_float32 v_load_expand(const hfloat* ptr) +{ + float buf[32]; + for( int i = 0; i < VTraits::vlanes(); i++ ) buf[i] = (float)ptr[i]; + return v_load(buf); +} + +inline void v_pack_store(hfloat* ptr, const v_float32& v) +{ + float buf[32]; + v_store(buf, v); + for( int i = 0; i < VTraits::vlanes(); i++ ) ptr[i] = hfloat(buf[i]); +} +#endif +////////////// Rounding ////////////// +inline v_int32 v_round(const v_float32& a) +{ + // return vfcvt_x(vfadd(a, 1e-6, VTraits::vlanes()), VTraits::vlanes()); + return __riscv_vfcvt_x(a, VTraits::vlanes()); +} + +inline v_int32 v_floor(const v_float32& a) +{ + return __riscv_vfcvt_x(__riscv_vfsub(a, 0.5f - 1e-5, VTraits::vlanes()), VTraits::vlanes()); + // return vfcvt_x(a, VTraits::vlanes()); +} + +inline v_int32 v_ceil(const v_float32& a) +{ + return __riscv_vfcvt_x(__riscv_vfadd(a, 0.5f - 1e-5, VTraits::vlanes()), VTraits::vlanes()); +} + +inline v_int32 v_trunc(const v_float32& a) +{ + return __riscv_vfcvt_rtz_x(a, VTraits::vlanes()); +} +#if CV_SIMD_SCALABLE_64F +inline v_int32 v_round(const v_float64& a) +{ + return __riscv_vfncvt_x(__riscv_vlmul_ext_f64m4(a), VTraits::vlanes()); +} + +inline v_int32 v_round(const v_float64& a, const v_float64& b) +{ + // return vfncvt_x(vset(vlmul_ext_f64m2(vfadd(a, 1e-6, VTraits::vlanes())), 1, b), VTraits::vlanes()); + // Fix https://github.com/opencv/opencv/issues/24746 + return __riscv_vfncvt_x(__riscv_vset(__riscv_vlmul_ext_f64m4(a), 1, b), VTraits::vlanes()); +} + +inline v_int32 v_floor(const v_float64& a) +{ + return __riscv_vfncvt_x(__riscv_vlmul_ext_f64m4(__riscv_vfsub(a, 0.5f - 1e-6, VTraits::vlanes())), VTraits::vlanes()); +} + +inline v_int32 v_ceil(const v_float64& a) +{ + return __riscv_vfncvt_x(__riscv_vlmul_ext_f64m4(__riscv_vfadd(a, 0.5f - 1e-6, VTraits::vlanes())), VTraits::vlanes()); +} + +inline v_int32 v_trunc(const v_float64& a) +{ + return __riscv_vfncvt_rtz_x(__riscv_vlmul_ext_f64m4(a), VTraits::vlanes()); +} +#endif + +//////// Dot Product //////// + +// 16 >> 32 +inline v_int32 v_dotprod(const v_int16& a, const v_int16& b) +{ + vint32m4_t temp1 = __riscv_vwmul(a, b, VTraits::vlanes()); + return v_hadd(temp1); +} + +inline v_int32 v_dotprod(const v_int16& a, const v_int16& b, const v_int32& c) +{ + vint32m4_t temp1 = __riscv_vwmul(a, b, VTraits::vlanes()); + return __riscv_vadd(v_hadd(temp1), c, VTraits::vlanes()); +} + +// 32 >> 64 +inline v_int64 v_dotprod(const v_int32& a, const v_int32& b) +{ + vuint64m2_t one64 = __riscv_vmv_v_x_u64m2(1, VTraits::vlanes()); \ + vuint32m2_t one32 = __riscv_vreinterpret_u32m2(one64); \ + vbool16_t mask = __riscv_vmseq(one32, 1, VTraits::vlanes()); \ + vint64m4_t temp1 = __riscv_vwmul(a, b, VTraits::vlanes()); \ + vint64m4_t temp2 = __riscv_vslide1down(temp1, 0, VTraits::vlanes()); + vint64m4_t res = __riscv_vadd(temp1, temp2, VTraits::vlanes()); + res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ + return __riscv_vlmul_trunc_i64m2(res); \ +} +inline v_int64 v_dotprod(const v_int32& a, const v_int32& b, const v_int64& c) +{ + vuint64m2_t one64 = __riscv_vmv_v_x_u64m2(1, VTraits::vlanes()); \ + vuint32m2_t one32 = __riscv_vreinterpret_u32m2(one64); \ + vbool16_t mask = __riscv_vmseq(one32, 1, VTraits::vlanes()); \ + vint64m4_t temp1 = __riscv_vwmul(a, b, VTraits::vlanes()); \ + vint64m4_t temp2 = __riscv_vslide1down(temp1, 0, VTraits::vlanes()); + vint64m4_t res = __riscv_vadd(temp1, temp2, VTraits::vlanes()); + res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ + return __riscv_vadd(__riscv_vlmul_trunc_i64m2(res), c, VTraits::vlanes()); \ +} + +// 8 >> 32 +inline v_uint32 v_dotprod_expand(const v_uint8& a, const v_uint8& b) +{ + vuint32m2_t one32 = __riscv_vmv_v_x_u32m2(1, VTraits::vlanes()); \ + vuint8m2_t one8 = __riscv_vreinterpret_u8m2(one32); \ + vbool4_t mask = __riscv_vmseq(one8, 1, VTraits::vlanes()); \ + vuint16m4_t t0 = __riscv_vwmulu(a, b, VTraits::vlanes()); \ + vuint16m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); + vuint16m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); + vuint16m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); + vuint32m8_t res = __riscv_vadd(__riscv_vwaddu_vv(t2, t3, VTraits::vlanes()), __riscv_vwaddu_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); + res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ + return __riscv_vlmul_trunc_u32m2(res); +} + +inline v_uint32 v_dotprod_expand(const v_uint8& a, const v_uint8& b, + const v_uint32& c) +{ + vuint32m2_t one32 = __riscv_vmv_v_x_u32m2(1, VTraits::vlanes()); \ + vuint8m2_t one8 = __riscv_vreinterpret_u8m2(one32); \ + vbool4_t mask = __riscv_vmseq(one8, 1, VTraits::vlanes()); \ + vuint16m4_t t0 = __riscv_vwmulu(a, b, VTraits::vlanes()); \ + vuint16m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); + vuint16m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); + vuint16m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); + vuint32m8_t res = __riscv_vadd(__riscv_vwaddu_vv(t2, t3, VTraits::vlanes()), __riscv_vwaddu_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); + res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ + return __riscv_vadd(__riscv_vlmul_trunc_u32m2(res), c, VTraits::vlanes()); +} + +inline v_int32 v_dotprod_expand(const v_int8& a, const v_int8& b) +{ + vuint32m2_t one32 = __riscv_vmv_v_x_u32m2(1, VTraits::vlanes()); \ + vuint8m2_t one8 = __riscv_vreinterpret_u8m2(one32); \ + vbool4_t mask = __riscv_vmseq(one8, 1, VTraits::vlanes()); \ + vint16m4_t t0 = __riscv_vwmul(a, b, VTraits::vlanes()); \ + vint16m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); + vint16m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); + vint16m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); + vint32m8_t res = __riscv_vadd(__riscv_vwadd_vv(t2, t3, VTraits::vlanes()), __riscv_vwadd_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); + res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ + return __riscv_vlmul_trunc_i32m2(res); +} + +inline v_int32 v_dotprod_expand(const v_int8& a, const v_int8& b, + const v_int32& c) +{ + vuint32m2_t one32 = __riscv_vmv_v_x_u32m2(1, VTraits::vlanes()); \ + vuint8m2_t one8 = __riscv_vreinterpret_u8m2(one32); \ + vbool4_t mask = __riscv_vmseq(one8, 1, VTraits::vlanes()); \ + vint16m4_t t0 = __riscv_vwmul(a, b, VTraits::vlanes()); \ + vint16m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); + vint16m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); + vint16m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); + vint32m8_t res = __riscv_vadd(__riscv_vwadd_vv(t2, t3, VTraits::vlanes()), __riscv_vwadd_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); + res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ + return __riscv_vadd(__riscv_vlmul_trunc_i32m2(res), c, VTraits::vlanes()); +} + + +// // 16 >> 64 +inline v_uint64 v_dotprod_expand(const v_uint16& a, const v_uint16& b) +{ + vuint64m2_t one64 = __riscv_vmv_v_x_u64m2(1, VTraits::vlanes()); \ + vuint16m2_t one16 = __riscv_vreinterpret_u16m2(one64); \ + vbool8_t mask = __riscv_vmseq(one16, 1, VTraits::vlanes()); \ + vuint32m4_t t0 = __riscv_vwmulu(a, b, VTraits::vlanes()); \ + vuint32m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); + vuint32m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); + vuint32m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); + vuint64m8_t res = __riscv_vadd(__riscv_vwaddu_vv(t2, t3, VTraits::vlanes()), __riscv_vwaddu_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); + res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ + return __riscv_vlmul_trunc_u64m2(res); +} +inline v_uint64 v_dotprod_expand(const v_uint16& a, const v_uint16& b, const v_uint64& c) +{ + vuint64m2_t one64 = __riscv_vmv_v_x_u64m2(1, VTraits::vlanes()); \ + vuint16m2_t one16 = __riscv_vreinterpret_u16m2(one64); \ + vbool8_t mask = __riscv_vmseq(one16, 1, VTraits::vlanes()); \ + vuint32m4_t t0 = __riscv_vwmulu(a, b, VTraits::vlanes()); \ + vuint32m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); + vuint32m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); + vuint32m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); + vuint64m8_t res = __riscv_vadd(__riscv_vwaddu_vv(t2, t3, VTraits::vlanes()), __riscv_vwaddu_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); + res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ + return __riscv_vadd(__riscv_vlmul_trunc_u64m2(res), c, VTraits::vlanes()); +} + +inline v_int64 v_dotprod_expand(const v_int16& a, const v_int16& b) +{ + vuint64m2_t one64 = __riscv_vmv_v_x_u64m2(1, VTraits::vlanes()); \ + vuint16m2_t one16 = __riscv_vreinterpret_u16m2(one64); \ + vbool8_t mask = __riscv_vmseq(one16, 1, VTraits::vlanes()); \ + vint32m4_t t0 = __riscv_vwmul(a, b, VTraits::vlanes()); \ + vint32m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); + vint32m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); + vint32m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); + vint64m8_t res = __riscv_vadd(__riscv_vwadd_vv(t2, t3, VTraits::vlanes()), __riscv_vwadd_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); + res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ + return __riscv_vlmul_trunc_i64m2(res); +} +inline v_int64 v_dotprod_expand(const v_int16& a, const v_int16& b, + const v_int64& c) +{ + vuint64m2_t one64 = __riscv_vmv_v_x_u64m2(1, VTraits::vlanes()); \ + vuint16m2_t one16 = __riscv_vreinterpret_u16m2(one64); \ + vbool8_t mask = __riscv_vmseq(one16, 1, VTraits::vlanes()); \ + vint32m4_t t0 = __riscv_vwmul(a, b, VTraits::vlanes()); \ + vint32m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); + vint32m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); + vint32m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); + vint64m8_t res = __riscv_vadd(__riscv_vwadd_vv(t2, t3, VTraits::vlanes()), __riscv_vwadd_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); + res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ + return __riscv_vadd(__riscv_vlmul_trunc_i64m2(res), c, VTraits::vlanes()); +} + +// // 32 >> 64f +#if CV_SIMD_SCALABLE_64F +inline v_float64 v_dotprod_expand(const v_int32& a, const v_int32& b) +{ return v_cvt_f64(v_dotprod(a, b)); } +inline v_float64 v_dotprod_expand(const v_int32& a, const v_int32& b, + const v_float64& c) +{ return v_add(v_dotprod_expand(a, b) , c); } +#endif + +//////// Fast Dot Product //////// +// 16 >> 32 +inline v_int32 v_dotprod_fast(const v_int16& a, const v_int16& b) +{ + vint32m1_t zero = __riscv_vmv_v_x_i32m1(0, VTraits::vlanes()); + return __riscv_vset(__riscv_vmv_v_x_i32m2(0, VTraits::vlanes()), 0, __riscv_vredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())); +} +inline v_int32 v_dotprod_fast(const v_int16& a, const v_int16& b, const v_int32& c) +{ + vint32m1_t zero = __riscv_vmv_v_x_i32m1(0, VTraits::vlanes()); + return __riscv_vadd(c, __riscv_vset(__riscv_vmv_v_x_i32m2(0, VTraits::vlanes()), 0, __riscv_vredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())), VTraits::vlanes()); +} + +// 32 >> 64 +inline v_int64 v_dotprod_fast(const v_int32& a, const v_int32& b) +{ + vint64m1_t zero = __riscv_vmv_v_x_i64m1(0, VTraits::vlanes()); + return __riscv_vset(__riscv_vmv_v_x_i64m2(0, VTraits::vlanes()), 0, __riscv_vredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())); +} +inline v_int64 v_dotprod_fast(const v_int32& a, const v_int32& b, const v_int64& c) +{ + vint64m1_t zero = __riscv_vmv_v_x_i64m1(0, VTraits::vlanes()); + return __riscv_vadd(c, __riscv_vset(__riscv_vmv_v_x_i64m2(0, VTraits::vlanes()), 0, __riscv_vredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())), VTraits::vlanes()); +} + + +// 8 >> 32 +inline v_uint32 v_dotprod_expand_fast(const v_uint8& a, const v_uint8& b) +{ + vuint32m1_t zero = __riscv_vmv_v_x_u32m1(0, VTraits::vlanes()); + auto res = __riscv_vwredsumu_tu(zero, __riscv_vwmulu(a, b, VTraits::vlanes()), zero, VTraits::vlanes()); + return __riscv_vset(__riscv_vmv_v_x_u32m2(0, VTraits::vlanes()), 0, res); +} +inline v_uint32 v_dotprod_expand_fast(const v_uint8& a, const v_uint8& b, const v_uint32& c) +{ + vuint32m1_t zero = __riscv_vmv_v_x_u32m1(0, VTraits::vlanes()); + auto res = __riscv_vwredsumu_tu(zero, __riscv_vwmulu(a, b, VTraits::vlanes()), zero, VTraits::vlanes()); + return __riscv_vadd(c, __riscv_vset(__riscv_vmv_v_x_u32m2(0, VTraits::vlanes()), 0, res), VTraits::vlanes()); +} +inline v_int32 v_dotprod_expand_fast(const v_int8& a, const v_int8& b) +{ + vint32m1_t zero = __riscv_vmv_v_x_i32m1(0, VTraits::vlanes()); + return __riscv_vset(__riscv_vmv_v_x_i32m2(0, VTraits::vlanes()), 0, __riscv_vwredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())); +} +inline v_int32 v_dotprod_expand_fast(const v_int8& a, const v_int8& b, const v_int32& c) +{ + vint32m1_t zero = __riscv_vmv_v_x_i32m1(0, VTraits::vlanes()); + return __riscv_vadd(c, __riscv_vset(__riscv_vmv_v_x_i32m2(0, VTraits::vlanes()), 0, __riscv_vwredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())), VTraits::vlanes()); +} + +// 16 >> 64 +inline v_uint64 v_dotprod_expand_fast(const v_uint16& a, const v_uint16& b) +{ + vuint64m1_t zero = __riscv_vmv_v_x_u64m1(0, VTraits::vlanes()); + return __riscv_vset(__riscv_vmv_v_x_u64m2(0, VTraits::vlanes()), 0, __riscv_vwredsumu_tu(zero, __riscv_vwmulu(a, b, VTraits::vlanes()), zero, VTraits::vlanes())); +} +inline v_uint64 v_dotprod_expand_fast(const v_uint16& a, const v_uint16& b, const v_uint64& c) +{ + vuint64m1_t zero = __riscv_vmv_v_x_u64m1(0, VTraits::vlanes()); + return __riscv_vadd(c, __riscv_vset(__riscv_vmv_v_x_u64m2(0, VTraits::vlanes()), 0, __riscv_vwredsumu_tu(zero, __riscv_vwmulu(a, b, VTraits::vlanes()), zero, VTraits::vlanes())), VTraits::vlanes()); +} +inline v_int64 v_dotprod_expand_fast(const v_int16& a, const v_int16& b) +{ + vint64m1_t zero = __riscv_vmv_v_x_i64m1(0, VTraits::vlanes()); + return __riscv_vset(__riscv_vmv_v_x_i64m2(0, VTraits::vlanes()), 0, __riscv_vwredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())); +} +inline v_int64 v_dotprod_expand_fast(const v_int16& a, const v_int16& b, const v_int64& c) +{ + vint64m1_t zero = __riscv_vmv_v_x_i64m1(0, VTraits::vlanes()); + return __riscv_vadd(c, __riscv_vset(__riscv_vmv_v_x_i64m2(0, VTraits::vlanes()), 0, __riscv_vwredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())), VTraits::vlanes()); +} + +// 32 >> 64f +#if CV_SIMD_SCALABLE_64F +inline v_float64 v_dotprod_expand_fast(const v_int32& a, const v_int32& b) +{ return v_cvt_f64(v_dotprod_fast(a, b)); } +inline v_float64 v_dotprod_expand_fast(const v_int32& a, const v_int32& b, const v_float64& c) +{ return v_add(v_dotprod_expand_fast(a, b) , c); } +#endif + +// TODO: only 128 bit now. +inline v_float32 v_matmul(const v_float32& v, const v_float32& mat0, + const v_float32& mat1, const v_float32& mat2, + const v_float32& mat3) +{ + vfloat32m2_t res; + res = __riscv_vfmul_vf_f32m2(mat0, v_extract_n(v, 0), VTraits::vlanes()); + res = __riscv_vfmacc_vf_f32m2(res, v_extract_n(v, 1), mat1, VTraits::vlanes()); + res = __riscv_vfmacc_vf_f32m2(res, v_extract_n(v, 2), mat2, VTraits::vlanes()); + res = __riscv_vfmacc_vf_f32m2(res, v_extract_n(v, 3), mat3, VTraits::vlanes()); + return res; +} + +// TODO: only 128 bit now. +inline v_float32 v_matmuladd(const v_float32& v, const v_float32& mat0, + const v_float32& mat1, const v_float32& mat2, + const v_float32& a) +{ + vfloat32m2_t res = __riscv_vfmul_vf_f32m2(mat0, v_extract_n(v,0), VTraits::vlanes()); + res = __riscv_vfmacc_vf_f32m2(res, v_extract_n(v,1), mat1, VTraits::vlanes()); + res = __riscv_vfmacc_vf_f32m2(res, v_extract_n(v,2), mat2, VTraits::vlanes()); + return __riscv_vfadd(res, a, VTraits::vlanes()); +} + +inline void v_cleanup() {} + +#include "intrin_math.hpp" +inline v_float32 v_exp(const v_float32& x) { return v_exp_default_32f(x); } +inline v_float32 v_log(const v_float32& x) { return v_log_default_32f(x); } +inline void v_sincos(const v_float32& x, v_float32& s, v_float32& c) { v_sincos_default_32f(x, s, c); } +inline v_float32 v_sin(const v_float32& x) { return v_sin_default_32f(x); } +inline v_float32 v_cos(const v_float32& x) { return v_cos_default_32f(x); } +inline v_float32 v_erf(const v_float32& x) { return v_erf_default_32f(x); } + +inline v_float64 v_exp(const v_float64& x) { return v_exp_default_64f(x); } +inline v_float64 v_log(const v_float64& x) { return v_log_default_64f(x); } +inline void v_sincos(const v_float64& x, v_float64& s, v_float64& c) { v_sincos_default_64f(x, s, c); } +inline v_float64 v_sin(const v_float64& x) { return v_sin_default_64f(x); } +inline v_float64 v_cos(const v_float64& x) { return v_cos_default_64f(x); } + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} //namespace cv + +#endif //OPENCV_HAL_INTRIN_RVV_SCALABLE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_sse.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_sse.hpp index 369cd2fbc6..88ce25737b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_sse.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_sse.hpp @@ -1,3483 +1,3483 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_HAL_SSE_HPP -#define OPENCV_HAL_SSE_HPP - -#include -#include "opencv2/core/utility.hpp" - -#define CV_SIMD128 1 -#define CV_SIMD128_64F 1 -#define CV_SIMD128_FP16 0 // no native operations with FP16 type. - -namespace cv -{ - -//! @cond IGNORED - -// -// Compilation troubleshooting: -// - MSVC: error C2719: 'a': formal parameter with requested alignment of 16 won't be aligned -// Replace parameter declaration to const reference: -// -v_int32x4 a -// +const v_int32x4& a -// - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -///////// Types //////////// - -struct v_uint8x16 -{ - typedef uchar lane_type; - typedef __m128i vector_type; - enum { nlanes = 16 }; - - /* coverity[uninit_ctor]: suppress warning */ - v_uint8x16() {} - explicit v_uint8x16(__m128i v) : val(v) {} - v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, - uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) - { - val = _mm_setr_epi8((char)v0, (char)v1, (char)v2, (char)v3, - (char)v4, (char)v5, (char)v6, (char)v7, - (char)v8, (char)v9, (char)v10, (char)v11, - (char)v12, (char)v13, (char)v14, (char)v15); - } - - uchar get0() const - { - return (uchar)_mm_cvtsi128_si32(val); - } - - __m128i val; -}; - -struct v_int8x16 -{ - typedef schar lane_type; - typedef __m128i vector_type; - enum { nlanes = 16 }; - - /* coverity[uninit_ctor]: suppress warning */ - v_int8x16() {} - explicit v_int8x16(__m128i v) : val(v) {} - v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, - schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) - { - val = _mm_setr_epi8((char)v0, (char)v1, (char)v2, (char)v3, - (char)v4, (char)v5, (char)v6, (char)v7, - (char)v8, (char)v9, (char)v10, (char)v11, - (char)v12, (char)v13, (char)v14, (char)v15); - } - - schar get0() const - { - return (schar)_mm_cvtsi128_si32(val); - } - - __m128i val; -}; - -struct v_uint16x8 -{ - typedef ushort lane_type; - typedef __m128i vector_type; - enum { nlanes = 8 }; - - /* coverity[uninit_ctor]: suppress warning */ - v_uint16x8() {} - explicit v_uint16x8(__m128i v) : val(v) {} - v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) - { - val = _mm_setr_epi16((short)v0, (short)v1, (short)v2, (short)v3, - (short)v4, (short)v5, (short)v6, (short)v7); - } - - ushort get0() const - { - return (ushort)_mm_cvtsi128_si32(val); - } - - __m128i val; -}; - -struct v_int16x8 -{ - typedef short lane_type; - typedef __m128i vector_type; - enum { nlanes = 8 }; - - /* coverity[uninit_ctor]: suppress warning */ - v_int16x8() {} - explicit v_int16x8(__m128i v) : val(v) {} - v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) - { - val = _mm_setr_epi16((short)v0, (short)v1, (short)v2, (short)v3, - (short)v4, (short)v5, (short)v6, (short)v7); - } - - short get0() const - { - return (short)_mm_cvtsi128_si32(val); - } - - __m128i val; -}; - -struct v_uint32x4 -{ - typedef unsigned lane_type; - typedef __m128i vector_type; - enum { nlanes = 4 }; - - /* coverity[uninit_ctor]: suppress warning */ - v_uint32x4() {} - explicit v_uint32x4(__m128i v) : val(v) {} - v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) - { - val = _mm_setr_epi32((int)v0, (int)v1, (int)v2, (int)v3); - } - - unsigned get0() const - { - return (unsigned)_mm_cvtsi128_si32(val); - } - - __m128i val; -}; - -struct v_int32x4 -{ - typedef int lane_type; - typedef __m128i vector_type; - enum { nlanes = 4 }; - - /* coverity[uninit_ctor]: suppress warning */ - v_int32x4() {} - explicit v_int32x4(__m128i v) : val(v) {} - v_int32x4(int v0, int v1, int v2, int v3) - { - val = _mm_setr_epi32(v0, v1, v2, v3); - } - - int get0() const - { - return _mm_cvtsi128_si32(val); - } - - __m128i val; -}; - -struct v_float32x4 -{ - typedef float lane_type; - typedef __m128 vector_type; - enum { nlanes = 4 }; - - /* coverity[uninit_ctor]: suppress warning */ - v_float32x4() {} - explicit v_float32x4(__m128 v) : val(v) {} - v_float32x4(float v0, float v1, float v2, float v3) - { - val = _mm_setr_ps(v0, v1, v2, v3); - } - - float get0() const - { - return _mm_cvtss_f32(val); - } - - __m128 val; -}; - -struct v_uint64x2 -{ - typedef uint64 lane_type; - typedef __m128i vector_type; - enum { nlanes = 2 }; - - /* coverity[uninit_ctor]: suppress warning */ - v_uint64x2() {} - explicit v_uint64x2(__m128i v) : val(v) {} - v_uint64x2(uint64 v0, uint64 v1) - { -#if defined(_MSC_VER) && _MSC_VER >= 1920/*MSVS 2019*/ && defined(_M_X64) && !defined(__clang__) - val = _mm_setr_epi64x((int64_t)v0, (int64_t)v1); -#elif defined(__GNUC__) - val = _mm_setr_epi64((__m64)v0, (__m64)v1); -#else - val = _mm_setr_epi32((int)v0, (int)(v0 >> 32), (int)v1, (int)(v1 >> 32)); -#endif - } - - uint64 get0() const - { - #if !defined(__x86_64__) && !defined(_M_X64) - int a = _mm_cvtsi128_si32(val); - int b = _mm_cvtsi128_si32(_mm_srli_epi64(val, 32)); - return (unsigned)a | ((uint64)(unsigned)b << 32); - #else - return (uint64)_mm_cvtsi128_si64(val); - #endif - } - - __m128i val; -}; - -struct v_int64x2 -{ - typedef int64 lane_type; - typedef __m128i vector_type; - enum { nlanes = 2 }; - - /* coverity[uninit_ctor]: suppress warning */ - v_int64x2() {} - explicit v_int64x2(__m128i v) : val(v) {} - v_int64x2(int64 v0, int64 v1) - { -#if defined(_MSC_VER) && _MSC_VER >= 1920/*MSVS 2019*/ && defined(_M_X64) && !defined(__clang__) - val = _mm_setr_epi64x((int64_t)v0, (int64_t)v1); -#elif defined(__GNUC__) - val = _mm_setr_epi64((__m64)v0, (__m64)v1); -#else - val = _mm_setr_epi32((int)v0, (int)(v0 >> 32), (int)v1, (int)(v1 >> 32)); -#endif - } - - int64 get0() const - { - #if !defined(__x86_64__) && !defined(_M_X64) - int a = _mm_cvtsi128_si32(val); - int b = _mm_cvtsi128_si32(_mm_srli_epi64(val, 32)); - return (int64)((unsigned)a | ((uint64)(unsigned)b << 32)); - #else - return _mm_cvtsi128_si64(val); - #endif - } - - __m128i val; -}; - -struct v_float64x2 -{ - typedef double lane_type; - typedef __m128d vector_type; - enum { nlanes = 2 }; - - /* coverity[uninit_ctor]: suppress warning */ - v_float64x2() {} - explicit v_float64x2(__m128d v) : val(v) {} - v_float64x2(double v0, double v1) - { - val = _mm_setr_pd(v0, v1); - } - - double get0() const - { - return _mm_cvtsd_f64(val); - } - - __m128d val; -}; - -namespace hal_sse_internal -{ - template - to_sse_type v_sse_reinterpret_as(const from_sse_type& val); - -#define OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(to_sse_type, from_sse_type, sse_cast_intrin) \ - template<> inline \ - to_sse_type v_sse_reinterpret_as(const from_sse_type& a) \ - { return sse_cast_intrin(a); } - - OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128i, __m128i, OPENCV_HAL_NOP) - OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128i, __m128, _mm_castps_si128) - OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128i, __m128d, _mm_castpd_si128) - OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128, __m128i, _mm_castsi128_ps) - OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128, __m128, OPENCV_HAL_NOP) - OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128, __m128d, _mm_castpd_ps) - OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128d, __m128i, _mm_castsi128_pd) - OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128d, __m128, _mm_castps_pd) - OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128d, __m128d, OPENCV_HAL_NOP) -} - -#define OPENCV_HAL_IMPL_SSE_INITVEC(_Tpvec, _Tp, suffix, zsuffix, ssuffix, _Tps, cast) \ -inline _Tpvec v_setzero_##suffix() { return _Tpvec(_mm_setzero_##zsuffix()); } \ -inline _Tpvec v_setall_##suffix(_Tp v) { return _Tpvec(_mm_set1_##ssuffix((_Tps)v)); } \ -template <> inline _Tpvec v_setzero_() { return v_setzero_##suffix(); } \ -template <> inline _Tpvec v_setall_(_Tp v) { return v_setall_##suffix(v); } \ -template inline _Tpvec v_reinterpret_as_##suffix(const _Tpvec0& a) \ -{ return _Tpvec(cast(a.val)); } - -OPENCV_HAL_IMPL_SSE_INITVEC(v_uint8x16, uchar, u8, si128, epi8, schar, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_INITVEC(v_int8x16, schar, s8, si128, epi8, schar, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_INITVEC(v_uint16x8, ushort, u16, si128, epi16, short, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_INITVEC(v_int16x8, short, s16, si128, epi16, short, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_INITVEC(v_uint32x4, unsigned, u32, si128, epi32, int, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_INITVEC(v_int32x4, int, s32, si128, epi32, int, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_INITVEC(v_float32x4, float, f32, ps, ps, float, _mm_castsi128_ps) -OPENCV_HAL_IMPL_SSE_INITVEC(v_float64x2, double, f64, pd, pd, double, _mm_castsi128_pd) - -inline v_uint64x2 v_setzero_u64() { return v_uint64x2(_mm_setzero_si128()); } -inline v_int64x2 v_setzero_s64() { return v_int64x2(_mm_setzero_si128()); } -inline v_uint64x2 v_setall_u64(uint64 val) { return v_uint64x2(val, val); } -inline v_int64x2 v_setall_s64(int64 val) { return v_int64x2(val, val); } - -template <> inline v_uint64x2 v_setzero_() { return v_setzero_u64(); } -template <> inline v_int64x2 v_setzero_() { return v_setzero_s64(); } -template <> inline v_uint64x2 v_setall_(uint64 val) { return v_setall_u64(val); } -template <> inline v_int64x2 v_setall_(int64 val) { return v_setall_s64(val); } - -template inline -v_uint64x2 v_reinterpret_as_u64(const _Tpvec& a) { return v_uint64x2(a.val); } -template inline -v_int64x2 v_reinterpret_as_s64(const _Tpvec& a) { return v_int64x2(a.val); } -inline v_float32x4 v_reinterpret_as_f32(const v_uint64x2& a) -{ return v_float32x4(_mm_castsi128_ps(a.val)); } -inline v_float32x4 v_reinterpret_as_f32(const v_int64x2& a) -{ return v_float32x4(_mm_castsi128_ps(a.val)); } -inline v_float64x2 v_reinterpret_as_f64(const v_uint64x2& a) -{ return v_float64x2(_mm_castsi128_pd(a.val)); } -inline v_float64x2 v_reinterpret_as_f64(const v_int64x2& a) -{ return v_float64x2(_mm_castsi128_pd(a.val)); } - -#define OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(_Tpvec, suffix) \ -inline _Tpvec v_reinterpret_as_##suffix(const v_float32x4& a) \ -{ return _Tpvec(_mm_castps_si128(a.val)); } \ -inline _Tpvec v_reinterpret_as_##suffix(const v_float64x2& a) \ -{ return _Tpvec(_mm_castpd_si128(a.val)); } - -OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_uint8x16, u8) -OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_int8x16, s8) -OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_uint16x8, u16) -OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_int16x8, s16) -OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_uint32x4, u32) -OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_int32x4, s32) -OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_uint64x2, u64) -OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_int64x2, s64) - -inline v_float32x4 v_reinterpret_as_f32(const v_float32x4& a) {return a; } -inline v_float64x2 v_reinterpret_as_f64(const v_float64x2& a) {return a; } -inline v_float32x4 v_reinterpret_as_f32(const v_float64x2& a) {return v_float32x4(_mm_castpd_ps(a.val)); } -inline v_float64x2 v_reinterpret_as_f64(const v_float32x4& a) {return v_float64x2(_mm_castps_pd(a.val)); } - -//////////////// PACK /////////////// -inline v_uint8x16 v_pack(const v_uint16x8& a, const v_uint16x8& b) -{ - __m128i delta = _mm_set1_epi16(255); - return v_uint8x16(_mm_packus_epi16(_mm_subs_epu16(a.val, _mm_subs_epu16(a.val, delta)), - _mm_subs_epu16(b.val, _mm_subs_epu16(b.val, delta)))); -} - -inline void v_pack_store(uchar* ptr, const v_uint16x8& a) -{ - __m128i delta = _mm_set1_epi16(255); - __m128i a1 = _mm_subs_epu16(a.val, _mm_subs_epu16(a.val, delta)); - _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi16(a1, a1)); -} - -inline v_uint8x16 v_pack_u(const v_int16x8& a, const v_int16x8& b) -{ return v_uint8x16(_mm_packus_epi16(a.val, b.val)); } - -inline void v_pack_u_store(uchar* ptr, const v_int16x8& a) -{ _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi16(a.val, a.val)); } - -template inline -v_uint8x16 v_rshr_pack(const v_uint16x8& a, const v_uint16x8& b) -{ - // we assume that n > 0, and so the shifted 16-bit values can be treated as signed numbers. - __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); - return v_uint8x16(_mm_packus_epi16(_mm_srli_epi16(_mm_adds_epu16(a.val, delta), n), - _mm_srli_epi16(_mm_adds_epu16(b.val, delta), n))); -} - -template inline -void v_rshr_pack_store(uchar* ptr, const v_uint16x8& a) -{ - __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); - __m128i a1 = _mm_srli_epi16(_mm_adds_epu16(a.val, delta), n); - _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi16(a1, a1)); -} - -template inline -v_uint8x16 v_rshr_pack_u(const v_int16x8& a, const v_int16x8& b) -{ - __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); - return v_uint8x16(_mm_packus_epi16(_mm_srai_epi16(_mm_adds_epi16(a.val, delta), n), - _mm_srai_epi16(_mm_adds_epi16(b.val, delta), n))); -} - -template inline -void v_rshr_pack_u_store(uchar* ptr, const v_int16x8& a) -{ - __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); - __m128i a1 = _mm_srai_epi16(_mm_adds_epi16(a.val, delta), n); - _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi16(a1, a1)); -} - -inline v_int8x16 v_pack(const v_int16x8& a, const v_int16x8& b) -{ return v_int8x16(_mm_packs_epi16(a.val, b.val)); } - -inline void v_pack_store(schar* ptr, const v_int16x8& a) -{ _mm_storel_epi64((__m128i*)ptr, _mm_packs_epi16(a.val, a.val)); } - -template inline -v_int8x16 v_rshr_pack(const v_int16x8& a, const v_int16x8& b) -{ - // we assume that n > 0, and so the shifted 16-bit values can be treated as signed numbers. - __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); - return v_int8x16(_mm_packs_epi16(_mm_srai_epi16(_mm_adds_epi16(a.val, delta), n), - _mm_srai_epi16(_mm_adds_epi16(b.val, delta), n))); -} -template inline -void v_rshr_pack_store(schar* ptr, const v_int16x8& a) -{ - // we assume that n > 0, and so the shifted 16-bit values can be treated as signed numbers. - __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); - __m128i a1 = _mm_srai_epi16(_mm_adds_epi16(a.val, delta), n); - _mm_storel_epi64((__m128i*)ptr, _mm_packs_epi16(a1, a1)); -} - - -// byte-wise "mask ? a : b" -inline __m128i v_select_si128(__m128i mask, __m128i a, __m128i b) -{ -#if CV_SSE4_1 - return _mm_blendv_epi8(b, a, mask); -#else - return _mm_xor_si128(b, _mm_and_si128(_mm_xor_si128(a, b), mask)); -#endif -} - -inline v_uint16x8 v_pack(const v_uint32x4& a, const v_uint32x4& b) -{ return v_uint16x8(_v128_packs_epu32(a.val, b.val)); } - -inline void v_pack_store(ushort* ptr, const v_uint32x4& a) -{ - __m128i z = _mm_setzero_si128(), maxval32 = _mm_set1_epi32(65535), delta32 = _mm_set1_epi32(32768); - __m128i a1 = _mm_sub_epi32(v_select_si128(_mm_cmpgt_epi32(z, a.val), maxval32, a.val), delta32); - __m128i r = _mm_packs_epi32(a1, a1); - _mm_storel_epi64((__m128i*)ptr, _mm_sub_epi16(r, _mm_set1_epi16(-32768))); -} - -template inline -v_uint16x8 v_rshr_pack(const v_uint32x4& a, const v_uint32x4& b) -{ - __m128i delta = _mm_set1_epi32(1 << (n-1)), delta32 = _mm_set1_epi32(32768); - __m128i a1 = _mm_sub_epi32(_mm_srli_epi32(_mm_add_epi32(a.val, delta), n), delta32); - __m128i b1 = _mm_sub_epi32(_mm_srli_epi32(_mm_add_epi32(b.val, delta), n), delta32); - return v_uint16x8(_mm_sub_epi16(_mm_packs_epi32(a1, b1), _mm_set1_epi16(-32768))); -} - -template inline -void v_rshr_pack_store(ushort* ptr, const v_uint32x4& a) -{ - __m128i delta = _mm_set1_epi32(1 << (n-1)), delta32 = _mm_set1_epi32(32768); - __m128i a1 = _mm_sub_epi32(_mm_srli_epi32(_mm_add_epi32(a.val, delta), n), delta32); - __m128i a2 = _mm_sub_epi16(_mm_packs_epi32(a1, a1), _mm_set1_epi16(-32768)); - _mm_storel_epi64((__m128i*)ptr, a2); -} - -inline v_uint16x8 v_pack_u(const v_int32x4& a, const v_int32x4& b) -{ -#if CV_SSE4_1 - return v_uint16x8(_mm_packus_epi32(a.val, b.val)); -#else - __m128i delta32 = _mm_set1_epi32(32768); - - // preliminary saturate negative values to zero - __m128i a1 = _mm_and_si128(a.val, _mm_cmpgt_epi32(a.val, _mm_set1_epi32(0))); - __m128i b1 = _mm_and_si128(b.val, _mm_cmpgt_epi32(b.val, _mm_set1_epi32(0))); - - __m128i r = _mm_packs_epi32(_mm_sub_epi32(a1, delta32), _mm_sub_epi32(b1, delta32)); - return v_uint16x8(_mm_sub_epi16(r, _mm_set1_epi16(-32768))); -#endif -} - -inline void v_pack_u_store(ushort* ptr, const v_int32x4& a) -{ -#if CV_SSE4_1 - _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi32(a.val, a.val)); -#else - __m128i delta32 = _mm_set1_epi32(32768); - __m128i a1 = _mm_sub_epi32(a.val, delta32); - __m128i r = _mm_sub_epi16(_mm_packs_epi32(a1, a1), _mm_set1_epi16(-32768)); - _mm_storel_epi64((__m128i*)ptr, r); -#endif -} - -template inline -v_uint16x8 v_rshr_pack_u(const v_int32x4& a, const v_int32x4& b) -{ -#if CV_SSE4_1 - __m128i delta = _mm_set1_epi32(1 << (n - 1)); - return v_uint16x8(_mm_packus_epi32(_mm_srai_epi32(_mm_add_epi32(a.val, delta), n), - _mm_srai_epi32(_mm_add_epi32(b.val, delta), n))); -#else - __m128i delta = _mm_set1_epi32(1 << (n-1)), delta32 = _mm_set1_epi32(32768); - __m128i a1 = _mm_sub_epi32(_mm_srai_epi32(_mm_add_epi32(a.val, delta), n), delta32); - __m128i a2 = _mm_sub_epi16(_mm_packs_epi32(a1, a1), _mm_set1_epi16(-32768)); - __m128i b1 = _mm_sub_epi32(_mm_srai_epi32(_mm_add_epi32(b.val, delta), n), delta32); - __m128i b2 = _mm_sub_epi16(_mm_packs_epi32(b1, b1), _mm_set1_epi16(-32768)); - return v_uint16x8(_mm_unpacklo_epi64(a2, b2)); -#endif -} - -template inline -void v_rshr_pack_u_store(ushort* ptr, const v_int32x4& a) -{ -#if CV_SSE4_1 - __m128i delta = _mm_set1_epi32(1 << (n - 1)); - __m128i a1 = _mm_srai_epi32(_mm_add_epi32(a.val, delta), n); - _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi32(a1, a1)); -#else - __m128i delta = _mm_set1_epi32(1 << (n-1)), delta32 = _mm_set1_epi32(32768); - __m128i a1 = _mm_sub_epi32(_mm_srai_epi32(_mm_add_epi32(a.val, delta), n), delta32); - __m128i a2 = _mm_sub_epi16(_mm_packs_epi32(a1, a1), _mm_set1_epi16(-32768)); - _mm_storel_epi64((__m128i*)ptr, a2); -#endif -} - -inline v_int16x8 v_pack(const v_int32x4& a, const v_int32x4& b) -{ return v_int16x8(_mm_packs_epi32(a.val, b.val)); } - -inline void v_pack_store(short* ptr, const v_int32x4& a) -{ - _mm_storel_epi64((__m128i*)ptr, _mm_packs_epi32(a.val, a.val)); -} - -template inline -v_int16x8 v_rshr_pack(const v_int32x4& a, const v_int32x4& b) -{ - __m128i delta = _mm_set1_epi32(1 << (n-1)); - return v_int16x8(_mm_packs_epi32(_mm_srai_epi32(_mm_add_epi32(a.val, delta), n), - _mm_srai_epi32(_mm_add_epi32(b.val, delta), n))); -} - -template inline -void v_rshr_pack_store(short* ptr, const v_int32x4& a) -{ - __m128i delta = _mm_set1_epi32(1 << (n-1)); - __m128i a1 = _mm_srai_epi32(_mm_add_epi32(a.val, delta), n); - _mm_storel_epi64((__m128i*)ptr, _mm_packs_epi32(a1, a1)); -} - - -// [a0 0 | b0 0] [a1 0 | b1 0] -inline v_uint32x4 v_pack(const v_uint64x2& a, const v_uint64x2& b) -{ - __m128i v0 = _mm_unpacklo_epi32(a.val, b.val); // a0 a1 0 0 - __m128i v1 = _mm_unpackhi_epi32(a.val, b.val); // b0 b1 0 0 - return v_uint32x4(_mm_unpacklo_epi32(v0, v1)); -} - -inline void v_pack_store(unsigned* ptr, const v_uint64x2& a) -{ - __m128i a1 = _mm_shuffle_epi32(a.val, _MM_SHUFFLE(0, 2, 2, 0)); - _mm_storel_epi64((__m128i*)ptr, a1); -} - -// [a0 0 | b0 0] [a1 0 | b1 0] -inline v_int32x4 v_pack(const v_int64x2& a, const v_int64x2& b) -{ - __m128i v0 = _mm_unpacklo_epi32(a.val, b.val); // a0 a1 0 0 - __m128i v1 = _mm_unpackhi_epi32(a.val, b.val); // b0 b1 0 0 - return v_int32x4(_mm_unpacklo_epi32(v0, v1)); -} - -inline void v_pack_store(int* ptr, const v_int64x2& a) -{ - __m128i a1 = _mm_shuffle_epi32(a.val, _MM_SHUFFLE(0, 2, 2, 0)); - _mm_storel_epi64((__m128i*)ptr, a1); -} - -template inline -v_uint32x4 v_rshr_pack(const v_uint64x2& a, const v_uint64x2& b) -{ - uint64 delta = (uint64)1 << (n-1); - v_uint64x2 delta2(delta, delta); - __m128i a1 = _mm_srli_epi64(_mm_add_epi64(a.val, delta2.val), n); - __m128i b1 = _mm_srli_epi64(_mm_add_epi64(b.val, delta2.val), n); - __m128i v0 = _mm_unpacklo_epi32(a1, b1); // a0 a1 0 0 - __m128i v1 = _mm_unpackhi_epi32(a1, b1); // b0 b1 0 0 - return v_uint32x4(_mm_unpacklo_epi32(v0, v1)); -} - -template inline -void v_rshr_pack_store(unsigned* ptr, const v_uint64x2& a) -{ - uint64 delta = (uint64)1 << (n-1); - v_uint64x2 delta2(delta, delta); - __m128i a1 = _mm_srli_epi64(_mm_add_epi64(a.val, delta2.val), n); - __m128i a2 = _mm_shuffle_epi32(a1, _MM_SHUFFLE(0, 2, 2, 0)); - _mm_storel_epi64((__m128i*)ptr, a2); -} - -inline __m128i v_sign_epi64(__m128i a) -{ - return _mm_shuffle_epi32(_mm_srai_epi32(a, 31), _MM_SHUFFLE(3, 3, 1, 1)); // x m0 | x m1 -} - -inline __m128i v_srai_epi64(__m128i a, int imm) -{ - __m128i smask = v_sign_epi64(a); - return _mm_xor_si128(_mm_srli_epi64(_mm_xor_si128(a, smask), imm), smask); -} - -template inline -v_int32x4 v_rshr_pack(const v_int64x2& a, const v_int64x2& b) -{ - int64 delta = (int64)1 << (n-1); - v_int64x2 delta2(delta, delta); - __m128i a1 = v_srai_epi64(_mm_add_epi64(a.val, delta2.val), n); - __m128i b1 = v_srai_epi64(_mm_add_epi64(b.val, delta2.val), n); - __m128i v0 = _mm_unpacklo_epi32(a1, b1); // a0 a1 0 0 - __m128i v1 = _mm_unpackhi_epi32(a1, b1); // b0 b1 0 0 - return v_int32x4(_mm_unpacklo_epi32(v0, v1)); -} - -template inline -void v_rshr_pack_store(int* ptr, const v_int64x2& a) -{ - int64 delta = (int64)1 << (n-1); - v_int64x2 delta2(delta, delta); - __m128i a1 = v_srai_epi64(_mm_add_epi64(a.val, delta2.val), n); - __m128i a2 = _mm_shuffle_epi32(a1, _MM_SHUFFLE(0, 2, 2, 0)); - _mm_storel_epi64((__m128i*)ptr, a2); -} - -// pack boolean -inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) -{ - __m128i ab = _mm_packs_epi16(a.val, b.val); - return v_uint8x16(ab); -} - -inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, - const v_uint32x4& c, const v_uint32x4& d) -{ - __m128i ab = _mm_packs_epi32(a.val, b.val); - __m128i cd = _mm_packs_epi32(c.val, d.val); - return v_uint8x16(_mm_packs_epi16(ab, cd)); -} - -inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, - const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, - const v_uint64x2& g, const v_uint64x2& h) -{ - __m128i ab = _mm_packs_epi32(a.val, b.val); - __m128i cd = _mm_packs_epi32(c.val, d.val); - __m128i ef = _mm_packs_epi32(e.val, f.val); - __m128i gh = _mm_packs_epi32(g.val, h.val); - - __m128i abcd = _mm_packs_epi32(ab, cd); - __m128i efgh = _mm_packs_epi32(ef, gh); - return v_uint8x16(_mm_packs_epi16(abcd, efgh)); -} - -inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, - const v_float32x4& m3) -{ - __m128 v0 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(0, 0, 0, 0)), m0.val); - __m128 v1 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(1, 1, 1, 1)), m1.val); - __m128 v2 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(2, 2, 2, 2)), m2.val); - __m128 v3 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(3, 3, 3, 3)), m3.val); - - return v_float32x4(_mm_add_ps(_mm_add_ps(v0, v1), _mm_add_ps(v2, v3))); -} - -inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, - const v_float32x4& a) -{ - __m128 v0 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(0, 0, 0, 0)), m0.val); - __m128 v1 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(1, 1, 1, 1)), m1.val); - __m128 v2 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(2, 2, 2, 2)), m2.val); - - return v_float32x4(_mm_add_ps(_mm_add_ps(v0, v1), _mm_add_ps(v2, a.val))); -} - -#define OPENCV_HAL_IMPL_SSE_BIN_OP(bin_op, _Tpvec, intrin) \ - inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ - { \ - return _Tpvec(intrin(a.val, b.val)); \ - } - -OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_uint8x16, _mm_adds_epu8) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_uint8x16, _mm_subs_epu8) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_int8x16, _mm_adds_epi8) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_int8x16, _mm_subs_epi8) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_uint16x8, _mm_adds_epu16) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_uint16x8, _mm_subs_epu16) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_int16x8, _mm_adds_epi16) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_int16x8, _mm_subs_epi16) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_uint32x4, _mm_add_epi32) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_uint32x4, _mm_sub_epi32) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_mul, v_uint32x4, _v128_mullo_epi32) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_int32x4, _mm_add_epi32) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_int32x4, _mm_sub_epi32) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_mul, v_int32x4, _v128_mullo_epi32) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_float32x4, _mm_add_ps) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_float32x4, _mm_sub_ps) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_mul, v_float32x4, _mm_mul_ps) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_div, v_float32x4, _mm_div_ps) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_float64x2, _mm_add_pd) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_float64x2, _mm_sub_pd) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_mul, v_float64x2, _mm_mul_pd) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_div, v_float64x2, _mm_div_pd) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_uint64x2, _mm_add_epi64) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_uint64x2, _mm_sub_epi64) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_int64x2, _mm_add_epi64) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_int64x2, _mm_sub_epi64) - -// saturating multiply 8-bit, 16-bit -#define OPENCV_HAL_IMPL_SSE_MUL_SAT(_Tpvec, _Tpwvec) \ - inline _Tpvec v_mul(const _Tpvec& a, const _Tpvec& b) \ - { \ - _Tpwvec c, d; \ - v_mul_expand(a, b, c, d); \ - return v_pack(c, d); \ - } - -OPENCV_HAL_IMPL_SSE_MUL_SAT(v_uint8x16, v_uint16x8) -OPENCV_HAL_IMPL_SSE_MUL_SAT(v_int8x16, v_int16x8) -OPENCV_HAL_IMPL_SSE_MUL_SAT(v_uint16x8, v_uint32x4) -OPENCV_HAL_IMPL_SSE_MUL_SAT(v_int16x8, v_int32x4) - -// Multiply and expand -inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b, - v_uint16x8& c, v_uint16x8& d) -{ - v_uint16x8 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c = v_mul_wrap(a0, b0); - d = v_mul_wrap(a1, b1); -} - -inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b, - v_int16x8& c, v_int16x8& d) -{ - v_int16x8 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c = v_mul_wrap(a0, b0); - d = v_mul_wrap(a1, b1); -} - -inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, - v_int32x4& c, v_int32x4& d) -{ - __m128i v0 = _mm_mullo_epi16(a.val, b.val); - __m128i v1 = _mm_mulhi_epi16(a.val, b.val); - c.val = _mm_unpacklo_epi16(v0, v1); - d.val = _mm_unpackhi_epi16(v0, v1); -} - -inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, - v_uint32x4& c, v_uint32x4& d) -{ - __m128i v0 = _mm_mullo_epi16(a.val, b.val); - __m128i v1 = _mm_mulhi_epu16(a.val, b.val); - c.val = _mm_unpacklo_epi16(v0, v1); - d.val = _mm_unpackhi_epi16(v0, v1); -} - -inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, - v_uint64x2& c, v_uint64x2& d) -{ - __m128i c0 = _mm_mul_epu32(a.val, b.val); - __m128i c1 = _mm_mul_epu32(_mm_srli_epi64(a.val, 32), _mm_srli_epi64(b.val, 32)); - c.val = _mm_unpacklo_epi64(c0, c1); - d.val = _mm_unpackhi_epi64(c0, c1); -} - -inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) { return v_int16x8(_mm_mulhi_epi16(a.val, b.val)); } -inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) { return v_uint16x8(_mm_mulhi_epu16(a.val, b.val)); } - -//////// Dot Product //////// - -// 16 >> 32 -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) -{ return v_int32x4(_mm_madd_epi16(a.val, b.val)); } -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ return v_add(v_dotprod(a, b), c); } - -// 32 >> 64 -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) -{ -#if CV_SSE4_1 - __m128i even = _mm_mul_epi32(a.val, b.val); - __m128i odd = _mm_mul_epi32(_mm_srli_epi64(a.val, 32), _mm_srli_epi64(b.val, 32)); - return v_int64x2(_mm_add_epi64(even, odd)); -#else - __m128i even_u = _mm_mul_epu32(a.val, b.val); - __m128i odd_u = _mm_mul_epu32(_mm_srli_epi64(a.val, 32), _mm_srli_epi64(b.val, 32)); - // convert unsigned to signed high multiplication (from: Agner Fog(veclib) and H S Warren: Hacker's delight, 2003, p. 132) - __m128i a_sign = _mm_srai_epi32(a.val, 31); - __m128i b_sign = _mm_srai_epi32(b.val, 31); - // |x * sign of x - __m128i axb = _mm_and_si128(a.val, b_sign); - __m128i bxa = _mm_and_si128(b.val, a_sign); - // sum of sign corrections - __m128i ssum = _mm_add_epi32(bxa, axb); - __m128i even_ssum = _mm_slli_epi64(ssum, 32); - __m128i odd_ssum = _mm_and_si128(ssum, _mm_set_epi32(-1, 0, -1, 0)); - // convert to signed and prod - return v_int64x2(_mm_add_epi64(_mm_sub_epi64(even_u, even_ssum), _mm_sub_epi64(odd_u, odd_ssum))); -#endif -} -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ return v_add(v_dotprod(a, b), c); } - -// 8 >> 32 -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) -{ - __m128i a0 = _mm_srli_epi16(_mm_slli_si128(a.val, 1), 8); // even - __m128i a1 = _mm_srli_epi16(a.val, 8); // odd - __m128i b0 = _mm_srli_epi16(_mm_slli_si128(b.val, 1), 8); - __m128i b1 = _mm_srli_epi16(b.val, 8); - __m128i p0 = _mm_madd_epi16(a0, b0); - __m128i p1 = _mm_madd_epi16(a1, b1); - return v_uint32x4(_mm_add_epi32(p0, p1)); -} -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) -{ - __m128i a0 = _mm_srai_epi16(_mm_slli_si128(a.val, 1), 8); // even - __m128i a1 = _mm_srai_epi16(a.val, 8); // odd - __m128i b0 = _mm_srai_epi16(_mm_slli_si128(b.val, 1), 8); - __m128i b1 = _mm_srai_epi16(b.val, 8); - __m128i p0 = _mm_madd_epi16(a0, b0); - __m128i p1 = _mm_madd_epi16(a1, b1); - return v_int32x4(_mm_add_epi32(p0, p1)); -} -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) -{ - v_uint32x4 c, d; - v_mul_expand(a, b, c, d); - - v_uint64x2 c0, c1, d0, d1; - v_expand(c, c0, c1); - v_expand(d, d0, d1); - - c0 = v_add(c0, c1); d0 = v_add(d0, d1); - return v_uint64x2(_mm_add_epi64( - _mm_unpacklo_epi64(c0.val, d0.val), - _mm_unpackhi_epi64(c0.val, d0.val) - )); -} -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) -{ - v_int32x4 prod = v_dotprod(a, b); - v_int64x2 c, d; - v_expand(prod, c, d); - return v_int64x2(_mm_add_epi64( - _mm_unpacklo_epi64(c.val, d.val), - _mm_unpackhi_epi64(c.val, d.val) - )); -} -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 32 >> 64f -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) -{ -#if CV_SSE4_1 - return v_cvt_f64(v_dotprod(a, b)); -#else - v_float64x2 c = v_mul(v_cvt_f64(a), v_cvt_f64(b)); - v_float64x2 d = v_mul(v_cvt_f64_high(a), v_cvt_f64_high(b)); - - return v_float64x2(_mm_add_pd( - _mm_unpacklo_pd(c.val, d.val), - _mm_unpackhi_pd(c.val, d.val) - )); -#endif -} -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -//////// Fast Dot Product //////// - -// 16 >> 32 -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) -{ return v_dotprod(a, b); } -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ return v_add(v_dotprod(a, b), c); } - -// 32 >> 64 -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) -{ return v_dotprod(a, b); } -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ return v_add(v_dotprod_fast(a, b), c); } - -// 8 >> 32 -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) -{ - __m128i a0 = v_expand_low(a).val; - __m128i a1 = v_expand_high(a).val; - __m128i b0 = v_expand_low(b).val; - __m128i b1 = v_expand_high(b).val; - __m128i p0 = _mm_madd_epi16(a0, b0); - __m128i p1 = _mm_madd_epi16(a1, b1); - return v_uint32x4(_mm_add_epi32(p0, p1)); -} -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) -{ -#if CV_SSE4_1 - __m128i a0 = _mm_cvtepi8_epi16(a.val); - __m128i a1 = v_expand_high(a).val; - __m128i b0 = _mm_cvtepi8_epi16(b.val); - __m128i b1 = v_expand_high(b).val; - __m128i p0 = _mm_madd_epi16(a0, b0); - __m128i p1 = _mm_madd_epi16(a1, b1); - return v_int32x4(_mm_add_epi32(p0, p1)); -#else - return v_dotprod_expand(a, b); -#endif -} -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) -{ - v_uint32x4 c, d; - v_mul_expand(a, b, c, d); - - v_uint64x2 c0, c1, d0, d1; - v_expand(c, c0, c1); - v_expand(d, d0, d1); - - c0 = v_add(c0, c1); d0 = v_add(d0, d1); - return v_add(c0, d0); -} -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) -{ - v_int32x4 prod = v_dotprod(a, b); - v_int64x2 c, d; - v_expand(prod, c, d); - return v_add(c, d); -} -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -// 32 >> 64f -v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c); -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) -{ return v_fma(v_cvt_f64(a), v_cvt_f64(b), v_mul(v_cvt_f64_high(a), v_cvt_f64_high(b))); } -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) -{ return v_fma(v_cvt_f64(a), v_cvt_f64(b), v_fma(v_cvt_f64_high(a), v_cvt_f64_high(b), c)); } - -#define OPENCV_HAL_IMPL_SSE_LOGIC_OP(_Tpvec, suffix, not_const) \ - OPENCV_HAL_IMPL_SSE_BIN_OP(v_and, _Tpvec, _mm_and_##suffix) \ - OPENCV_HAL_IMPL_SSE_BIN_OP(v_or, _Tpvec, _mm_or_##suffix) \ - OPENCV_HAL_IMPL_SSE_BIN_OP(v_xor, _Tpvec, _mm_xor_##suffix) \ - inline _Tpvec v_not(const _Tpvec& a) \ - { \ - return _Tpvec(_mm_xor_##suffix(a.val, not_const)); \ - } - -OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_uint8x16, si128, _mm_set1_epi32(-1)) -OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_int8x16, si128, _mm_set1_epi32(-1)) -OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_uint16x8, si128, _mm_set1_epi32(-1)) -OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_int16x8, si128, _mm_set1_epi32(-1)) -OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_uint32x4, si128, _mm_set1_epi32(-1)) -OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_int32x4, si128, _mm_set1_epi32(-1)) -OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_uint64x2, si128, _mm_set1_epi32(-1)) -OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_int64x2, si128, _mm_set1_epi32(-1)) -OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_float32x4, ps, _mm_castsi128_ps(_mm_set1_epi32(-1))) -OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_float64x2, pd, _mm_castsi128_pd(_mm_set1_epi32(-1))) - -inline v_float32x4 v_sqrt(const v_float32x4& x) -{ return v_float32x4(_mm_sqrt_ps(x.val)); } - -inline v_float32x4 v_invsqrt(const v_float32x4& x) -{ - const __m128 _0_5 = _mm_set1_ps(0.5f), _1_5 = _mm_set1_ps(1.5f); - __m128 t = x.val; - __m128 h = _mm_mul_ps(t, _0_5); - t = _mm_rsqrt_ps(t); - t = _mm_mul_ps(t, _mm_sub_ps(_1_5, _mm_mul_ps(_mm_mul_ps(t, t), h))); - return v_float32x4(t); -} - -inline v_float64x2 v_sqrt(const v_float64x2& x) -{ return v_float64x2(_mm_sqrt_pd(x.val)); } - -inline v_float64x2 v_invsqrt(const v_float64x2& x) -{ - const __m128d v_1 = _mm_set1_pd(1.); - return v_float64x2(_mm_div_pd(v_1, _mm_sqrt_pd(x.val))); -} - -#define OPENCV_HAL_IMPL_SSE_ABS_INT_FUNC(_Tpuvec, _Tpsvec, func, suffix, subWidth) \ -inline _Tpuvec v_abs(const _Tpsvec& x) \ -{ return _Tpuvec(_mm_##func##_ep##suffix(x.val, _mm_sub_ep##subWidth(_mm_setzero_si128(), x.val))); } - -OPENCV_HAL_IMPL_SSE_ABS_INT_FUNC(v_uint8x16, v_int8x16, min, u8, i8) -OPENCV_HAL_IMPL_SSE_ABS_INT_FUNC(v_uint16x8, v_int16x8, max, i16, i16) -inline v_uint32x4 v_abs(const v_int32x4& x) -{ - __m128i s = _mm_srli_epi32(x.val, 31); - __m128i f = _mm_srai_epi32(x.val, 31); - return v_uint32x4(_mm_add_epi32(_mm_xor_si128(x.val, f), s)); -} -inline v_float32x4 v_abs(const v_float32x4& x) -{ return v_float32x4(_mm_and_ps(x.val, _mm_castsi128_ps(_mm_set1_epi32(0x7fffffff)))); } -inline v_float64x2 v_abs(const v_float64x2& x) -{ - return v_float64x2(_mm_and_pd(x.val, - _mm_castsi128_pd(_mm_srli_epi64(_mm_set1_epi32(-1), 1)))); -} - -// TODO: exp, log, sin, cos - -#define OPENCV_HAL_IMPL_SSE_BIN_FUNC(_Tpvec, func, intrin) \ -inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(intrin(a.val, b.val)); \ -} - -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint8x16, v_min, _mm_min_epu8) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint8x16, v_max, _mm_max_epu8) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int16x8, v_min, _mm_min_epi16) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int16x8, v_max, _mm_max_epi16) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_float32x4, v_min, _mm_min_ps) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_float32x4, v_max, _mm_max_ps) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_float64x2, v_min, _mm_min_pd) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_float64x2, v_max, _mm_max_pd) - -inline v_int8x16 v_min(const v_int8x16& a, const v_int8x16& b) -{ -#if CV_SSE4_1 - return v_int8x16(_mm_min_epi8(a.val, b.val)); -#else - __m128i delta = _mm_set1_epi8((char)-128); - return v_int8x16(_mm_xor_si128(delta, _mm_min_epu8(_mm_xor_si128(a.val, delta), - _mm_xor_si128(b.val, delta)))); -#endif -} -inline v_int8x16 v_max(const v_int8x16& a, const v_int8x16& b) -{ -#if CV_SSE4_1 - return v_int8x16(_mm_max_epi8(a.val, b.val)); -#else - __m128i delta = _mm_set1_epi8((char)-128); - return v_int8x16(_mm_xor_si128(delta, _mm_max_epu8(_mm_xor_si128(a.val, delta), - _mm_xor_si128(b.val, delta)))); -#endif -} -inline v_uint16x8 v_min(const v_uint16x8& a, const v_uint16x8& b) -{ -#if CV_SSE4_1 - return v_uint16x8(_mm_min_epu16(a.val, b.val)); -#else - return v_uint16x8(_mm_subs_epu16(a.val, _mm_subs_epu16(a.val, b.val))); -#endif -} -inline v_uint16x8 v_max(const v_uint16x8& a, const v_uint16x8& b) -{ -#if CV_SSE4_1 - return v_uint16x8(_mm_max_epu16(a.val, b.val)); -#else - return v_uint16x8(_mm_adds_epu16(_mm_subs_epu16(a.val, b.val), b.val)); -#endif -} -inline v_uint32x4 v_min(const v_uint32x4& a, const v_uint32x4& b) -{ -#if CV_SSE4_1 - return v_uint32x4(_mm_min_epu32(a.val, b.val)); -#else - __m128i delta = _mm_set1_epi32((int)0x80000000); - __m128i mask = _mm_cmpgt_epi32(_mm_xor_si128(a.val, delta), _mm_xor_si128(b.val, delta)); - return v_uint32x4(v_select_si128(mask, b.val, a.val)); -#endif -} -inline v_uint32x4 v_max(const v_uint32x4& a, const v_uint32x4& b) -{ -#if CV_SSE4_1 - return v_uint32x4(_mm_max_epu32(a.val, b.val)); -#else - __m128i delta = _mm_set1_epi32((int)0x80000000); - __m128i mask = _mm_cmpgt_epi32(_mm_xor_si128(a.val, delta), _mm_xor_si128(b.val, delta)); - return v_uint32x4(v_select_si128(mask, a.val, b.val)); -#endif -} -inline v_int32x4 v_min(const v_int32x4& a, const v_int32x4& b) -{ -#if CV_SSE4_1 - return v_int32x4(_mm_min_epi32(a.val, b.val)); -#else - return v_int32x4(v_select_si128(_mm_cmpgt_epi32(a.val, b.val), b.val, a.val)); -#endif -} -inline v_int32x4 v_max(const v_int32x4& a, const v_int32x4& b) -{ -#if CV_SSE4_1 - return v_int32x4(_mm_max_epi32(a.val, b.val)); -#else - return v_int32x4(v_select_si128(_mm_cmpgt_epi32(a.val, b.val), a.val, b.val)); -#endif -} - -#define OPENCV_HAL_IMPL_SSE_INT_CMP_OP(_Tpuvec, _Tpsvec, suffix, sbit) \ -inline _Tpuvec v_eq(const _Tpuvec& a, const _Tpuvec& b) \ -{ return _Tpuvec(_mm_cmpeq_##suffix(a.val, b.val)); } \ -inline _Tpuvec v_ne(const _Tpuvec& a, const _Tpuvec& b) \ -{ \ - __m128i not_mask = _mm_set1_epi32(-1); \ - return _Tpuvec(_mm_xor_si128(_mm_cmpeq_##suffix(a.val, b.val), not_mask)); \ -} \ -inline _Tpsvec v_eq(const _Tpsvec& a, const _Tpsvec& b) \ -{ return _Tpsvec(_mm_cmpeq_##suffix(a.val, b.val)); } \ -inline _Tpsvec v_ne(const _Tpsvec& a, const _Tpsvec& b) \ -{ \ - __m128i not_mask = _mm_set1_epi32(-1); \ - return _Tpsvec(_mm_xor_si128(_mm_cmpeq_##suffix(a.val, b.val), not_mask)); \ -} \ -inline _Tpuvec v_lt(const _Tpuvec& a, const _Tpuvec& b) \ -{ \ - __m128i smask = _mm_set1_##suffix(sbit); \ - return _Tpuvec(_mm_cmpgt_##suffix(_mm_xor_si128(b.val, smask), _mm_xor_si128(a.val, smask))); \ -} \ -inline _Tpuvec v_gt(const _Tpuvec& a, const _Tpuvec& b) \ -{ \ - __m128i smask = _mm_set1_##suffix(sbit); \ - return _Tpuvec(_mm_cmpgt_##suffix(_mm_xor_si128(a.val, smask), _mm_xor_si128(b.val, smask))); \ -} \ -inline _Tpuvec v_le(const _Tpuvec& a, const _Tpuvec& b) \ -{ \ - __m128i smask = _mm_set1_##suffix(sbit); \ - __m128i not_mask = _mm_set1_epi32(-1); \ - __m128i res = _mm_cmpgt_##suffix(_mm_xor_si128(a.val, smask), _mm_xor_si128(b.val, smask)); \ - return _Tpuvec(_mm_xor_si128(res, not_mask)); \ -} \ -inline _Tpuvec v_ge(const _Tpuvec& a, const _Tpuvec& b) \ -{ \ - __m128i smask = _mm_set1_##suffix(sbit); \ - __m128i not_mask = _mm_set1_epi32(-1); \ - __m128i res = _mm_cmpgt_##suffix(_mm_xor_si128(b.val, smask), _mm_xor_si128(a.val, smask)); \ - return _Tpuvec(_mm_xor_si128(res, not_mask)); \ -} \ -inline _Tpsvec v_lt(const _Tpsvec& a, const _Tpsvec& b) \ -{ \ - return _Tpsvec(_mm_cmpgt_##suffix(b.val, a.val)); \ -} \ -inline _Tpsvec v_gt(const _Tpsvec& a, const _Tpsvec& b) \ -{ \ - return _Tpsvec(_mm_cmpgt_##suffix(a.val, b.val)); \ -} \ -inline _Tpsvec v_le(const _Tpsvec& a, const _Tpsvec& b) \ -{ \ - __m128i not_mask = _mm_set1_epi32(-1); \ - return _Tpsvec(_mm_xor_si128(_mm_cmpgt_##suffix(a.val, b.val), not_mask)); \ -} \ -inline _Tpsvec v_ge(const _Tpsvec& a, const _Tpsvec& b) \ -{ \ - __m128i not_mask = _mm_set1_epi32(-1); \ - return _Tpsvec(_mm_xor_si128(_mm_cmpgt_##suffix(b.val, a.val), not_mask)); \ -} - -OPENCV_HAL_IMPL_SSE_INT_CMP_OP(v_uint8x16, v_int8x16, epi8, (char)-128) -OPENCV_HAL_IMPL_SSE_INT_CMP_OP(v_uint16x8, v_int16x8, epi16, (short)-32768) -OPENCV_HAL_IMPL_SSE_INT_CMP_OP(v_uint32x4, v_int32x4, epi32, (int)0x80000000) - -#define OPENCV_HAL_IMPL_SSE_FLT_CMP_OP(_Tpvec, suffix) \ -inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(_mm_cmpeq_##suffix(a.val, b.val)); } \ -inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(_mm_cmpneq_##suffix(a.val, b.val)); } \ -inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(_mm_cmplt_##suffix(a.val, b.val)); } \ -inline _Tpvec v_gt(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(_mm_cmpgt_##suffix(a.val, b.val)); } \ -inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(_mm_cmple_##suffix(a.val, b.val)); } \ -inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(_mm_cmpge_##suffix(a.val, b.val)); } - -OPENCV_HAL_IMPL_SSE_FLT_CMP_OP(v_float32x4, ps) -OPENCV_HAL_IMPL_SSE_FLT_CMP_OP(v_float64x2, pd) - -#if CV_SSE4_1 -#define OPENCV_HAL_IMPL_SSE_64BIT_CMP_OP(_Tpvec) \ -inline _Tpvec v_eq (const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(_mm_cmpeq_epi64(a.val, b.val)); } \ -inline _Tpvec v_ne (const _Tpvec& a, const _Tpvec& b) \ -{ return v_not(v_eq(a, b)); } -#else -#define OPENCV_HAL_IMPL_SSE_64BIT_CMP_OP(_Tpvec) \ -inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ -{ __m128i cmp = _mm_cmpeq_epi32(a.val, b.val); \ - return _Tpvec(_mm_and_si128(cmp, _mm_shuffle_epi32(cmp, _MM_SHUFFLE(2, 3, 0, 1)))); } \ -inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ -{ return v_not(v_eq(a, b)); } -#endif - -OPENCV_HAL_IMPL_SSE_64BIT_CMP_OP(v_uint64x2) -OPENCV_HAL_IMPL_SSE_64BIT_CMP_OP(v_int64x2) - -inline v_float32x4 v_not_nan(const v_float32x4& a) -{ return v_float32x4(_mm_cmpord_ps(a.val, a.val)); } -inline v_float64x2 v_not_nan(const v_float64x2& a) -{ return v_float64x2(_mm_cmpord_pd(a.val, a.val)); } - -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint8x16, v_add_wrap, _mm_add_epi8) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int8x16, v_add_wrap, _mm_add_epi8) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint16x8, v_add_wrap, _mm_add_epi16) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int16x8, v_add_wrap, _mm_add_epi16) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint8x16, v_sub_wrap, _mm_sub_epi8) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int8x16, v_sub_wrap, _mm_sub_epi8) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint16x8, v_sub_wrap, _mm_sub_epi16) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int16x8, v_sub_wrap, _mm_sub_epi16) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint16x8, v_mul_wrap, _mm_mullo_epi16) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int16x8, v_mul_wrap, _mm_mullo_epi16) - -inline v_uint8x16 v_mul_wrap(const v_uint8x16& a, const v_uint8x16& b) -{ - __m128i ad = _mm_srai_epi16(a.val, 8); - __m128i bd = _mm_srai_epi16(b.val, 8); - __m128i p0 = _mm_mullo_epi16(a.val, b.val); // even - __m128i p1 = _mm_slli_epi16(_mm_mullo_epi16(ad, bd), 8); // odd - const __m128i b01 = _mm_set1_epi32(0xFF00FF00); - return v_uint8x16(_v128_blendv_epi8(p0, p1, b01)); -} -inline v_int8x16 v_mul_wrap(const v_int8x16& a, const v_int8x16& b) -{ - return v_reinterpret_as_s8(v_mul_wrap(v_reinterpret_as_u8(a), v_reinterpret_as_u8(b))); -} - -/** Absolute difference **/ - -inline v_uint8x16 v_absdiff(const v_uint8x16& a, const v_uint8x16& b) -{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } -inline v_uint16x8 v_absdiff(const v_uint16x8& a, const v_uint16x8& b) -{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } -inline v_uint32x4 v_absdiff(const v_uint32x4& a, const v_uint32x4& b) -{ return v_sub(v_max(a, b), v_min(a, b)); } - -inline v_uint8x16 v_absdiff(const v_int8x16& a, const v_int8x16& b) -{ - v_int8x16 d = v_sub_wrap(a, b); - v_int8x16 m = v_lt(a, b); - return v_reinterpret_as_u8(v_sub_wrap(v_xor(d, m), m)); -} -inline v_uint16x8 v_absdiff(const v_int16x8& a, const v_int16x8& b) -{ - return v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))); -} -inline v_uint32x4 v_absdiff(const v_int32x4& a, const v_int32x4& b) -{ - v_int32x4 d = v_sub(a, b); - v_int32x4 m = v_lt(a, b); - return v_reinterpret_as_u32(v_sub(v_xor(d, m), m)); -} - -/** Saturating absolute difference **/ -inline v_int8x16 v_absdiffs(const v_int8x16& a, const v_int8x16& b) -{ - v_int8x16 d = v_sub(a, b); - v_int8x16 m = v_lt(a, b); - return v_sub(v_xor(d, m), m); - } -inline v_int16x8 v_absdiffs(const v_int16x8& a, const v_int16x8& b) -{ return v_sub(v_max(a, b), v_min(a, b)); } - - -inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ - return v_add(v_mul(a, b), c); -} - -inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ - return v_fma(a, b, c); -} - -inline v_float32x4 v_fma(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) -{ -#if CV_FMA3 - return v_float32x4(_mm_fmadd_ps(a.val, b.val, c.val)); -#else - return v_float32x4(_mm_add_ps(_mm_mul_ps(a.val, b.val), c.val)); -#endif -} - -inline v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) -{ -#if CV_FMA3 - return v_float64x2(_mm_fmadd_pd(a.val, b.val, c.val)); -#else - return v_float64x2(_mm_add_pd(_mm_mul_pd(a.val, b.val), c.val)); -#endif -} - -#define OPENCV_HAL_IMPL_SSE_MISC_FLT_OP(_Tpvec, _Tp, _Tpreg, suffix, absmask_vec) \ -inline _Tpvec v_absdiff(const _Tpvec& a, const _Tpvec& b) \ -{ \ - _Tpreg absmask = _mm_castsi128_##suffix(absmask_vec); \ - return _Tpvec(_mm_and_##suffix(_mm_sub_##suffix(a.val, b.val), absmask)); \ -} \ -inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ -{ \ - _Tpvec res = v_fma(a, a, v_mul(b, b)); \ - return _Tpvec(_mm_sqrt_##suffix(res.val)); \ -} \ -inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return v_fma(a, a, v_mul(b, b)); \ -} \ -inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ -{ \ - return v_fma(a, b, c); \ -} - -OPENCV_HAL_IMPL_SSE_MISC_FLT_OP(v_float32x4, float, __m128, ps, _mm_set1_epi32((int)0x7fffffff)) -OPENCV_HAL_IMPL_SSE_MISC_FLT_OP(v_float64x2, double, __m128d, pd, _mm_srli_epi64(_mm_set1_epi32(-1), 1)) - -#define OPENCV_HAL_IMPL_SSE_SHIFT_OP(_Tpuvec, _Tpsvec, suffix, srai) \ -inline _Tpuvec v_shl(const _Tpuvec& a, int imm) \ -{ \ - return _Tpuvec(_mm_slli_##suffix(a.val, imm)); \ -} \ -inline _Tpsvec v_shl(const _Tpsvec& a, int imm) \ -{ \ - return _Tpsvec(_mm_slli_##suffix(a.val, imm)); \ -} \ -inline _Tpuvec v_shr(const _Tpuvec& a, int imm) \ -{ \ - return _Tpuvec(_mm_srli_##suffix(a.val, imm)); \ -} \ -inline _Tpsvec v_shr(const _Tpsvec& a, int imm) \ -{ \ - return _Tpsvec(srai(a.val, imm)); \ -} \ -template \ -inline _Tpuvec v_shl(const _Tpuvec& a) \ -{ \ - return _Tpuvec(_mm_slli_##suffix(a.val, imm)); \ -} \ -template \ -inline _Tpsvec v_shl(const _Tpsvec& a) \ -{ \ - return _Tpsvec(_mm_slli_##suffix(a.val, imm)); \ -} \ -template \ -inline _Tpuvec v_shr(const _Tpuvec& a) \ -{ \ - return _Tpuvec(_mm_srli_##suffix(a.val, imm)); \ -} \ -template \ -inline _Tpsvec v_shr(const _Tpsvec& a) \ -{ \ - return _Tpsvec(srai(a.val, imm)); \ -} - -OPENCV_HAL_IMPL_SSE_SHIFT_OP(v_uint16x8, v_int16x8, epi16, _mm_srai_epi16) -OPENCV_HAL_IMPL_SSE_SHIFT_OP(v_uint32x4, v_int32x4, epi32, _mm_srai_epi32) -OPENCV_HAL_IMPL_SSE_SHIFT_OP(v_uint64x2, v_int64x2, epi64, v_srai_epi64) - -namespace hal_sse_internal -{ - template 16)), - bool is_first = (imm == 0), - bool is_half = (imm == 8), - bool is_second = (imm == 16), - bool is_other = (((imm > 0) && (imm < 8)) || ((imm > 8) && (imm < 16)))> - class v_sse_palignr_u8_class; - - template - class v_sse_palignr_u8_class; - - template - class v_sse_palignr_u8_class - { - public: - inline __m128i operator()(const __m128i& a, const __m128i&) const - { - return a; - } - }; - - template - class v_sse_palignr_u8_class - { - public: - inline __m128i operator()(const __m128i& a, const __m128i& b) const - { - return _mm_unpacklo_epi64(_mm_unpackhi_epi64(a, a), b); - } - }; - - template - class v_sse_palignr_u8_class - { - public: - inline __m128i operator()(const __m128i&, const __m128i& b) const - { - return b; - } - }; - - template - class v_sse_palignr_u8_class - { -#if CV_SSSE3 - public: - inline __m128i operator()(const __m128i& a, const __m128i& b) const - { - return _mm_alignr_epi8(b, a, imm); - } -#else - public: - inline __m128i operator()(const __m128i& a, const __m128i& b) const - { - enum { imm2 = (sizeof(__m128i) - imm) }; - return _mm_or_si128(_mm_srli_si128(a, imm), _mm_slli_si128(b, imm2)); - } -#endif - }; - - template - inline __m128i v_sse_palignr_u8(const __m128i& a, const __m128i& b) - { - CV_StaticAssert((imm >= 0) && (imm <= 16), "Invalid imm for v_sse_palignr_u8."); - return v_sse_palignr_u8_class()(a, b); - } -} - -template -inline _Tpvec v_rotate_right(const _Tpvec &a) -{ - using namespace hal_sse_internal; - enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type)) }; - return _Tpvec(v_sse_reinterpret_as( - _mm_srli_si128( - v_sse_reinterpret_as<__m128i>(a.val), imm2))); -} - -template -inline _Tpvec v_rotate_left(const _Tpvec &a) -{ - using namespace hal_sse_internal; - enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type)) }; - return _Tpvec(v_sse_reinterpret_as( - _mm_slli_si128( - v_sse_reinterpret_as<__m128i>(a.val), imm2))); -} - -template -inline _Tpvec v_rotate_right(const _Tpvec &a, const _Tpvec &b) -{ - using namespace hal_sse_internal; - enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type)) }; - return _Tpvec(v_sse_reinterpret_as( - v_sse_palignr_u8( - v_sse_reinterpret_as<__m128i>(a.val), - v_sse_reinterpret_as<__m128i>(b.val)))); -} - -template -inline _Tpvec v_rotate_left(const _Tpvec &a, const _Tpvec &b) -{ - using namespace hal_sse_internal; - enum { imm2 = ((_Tpvec::nlanes - imm) * sizeof(typename _Tpvec::lane_type)) }; - return _Tpvec(v_sse_reinterpret_as( - v_sse_palignr_u8( - v_sse_reinterpret_as<__m128i>(b.val), - v_sse_reinterpret_as<__m128i>(a.val)))); -} - -#define OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(_Tpvec, _Tp) \ -inline _Tpvec v_load(const _Tp* ptr) \ -{ return _Tpvec(_mm_loadu_si128((const __m128i*)ptr)); } \ -inline _Tpvec v_load_aligned(const _Tp* ptr) \ -{ return _Tpvec(_mm_load_si128((const __m128i*)ptr)); } \ -inline _Tpvec v_load_low(const _Tp* ptr) \ -{ return _Tpvec(_mm_loadl_epi64((const __m128i*)ptr)); } \ -inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ -{ \ - return _Tpvec(_mm_unpacklo_epi64(_mm_loadl_epi64((const __m128i*)ptr0), \ - _mm_loadl_epi64((const __m128i*)ptr1))); \ -} \ -inline void v_store(_Tp* ptr, const _Tpvec& a) \ -{ _mm_storeu_si128((__m128i*)ptr, a.val); } \ -inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ -{ _mm_store_si128((__m128i*)ptr, a.val); } \ -inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ -{ _mm_stream_si128((__m128i*)ptr, a.val); } \ -inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ -{ \ - if( mode == hal::STORE_UNALIGNED ) \ - _mm_storeu_si128((__m128i*)ptr, a.val); \ - else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ - _mm_stream_si128((__m128i*)ptr, a.val); \ - else \ - _mm_store_si128((__m128i*)ptr, a.val); \ -} \ -inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ -{ _mm_storel_epi64((__m128i*)ptr, a.val); } \ -inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ -{ _mm_storel_epi64((__m128i*)ptr, _mm_unpackhi_epi64(a.val, a.val)); } - -OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_uint8x16, uchar) -OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_int8x16, schar) -OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_uint16x8, ushort) -OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_int16x8, short) -OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_uint32x4, unsigned) -OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_int32x4, int) -OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_uint64x2, uint64) -OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_int64x2, int64) - -#define OPENCV_HAL_IMPL_SSE_LOADSTORE_FLT_OP(_Tpvec, _Tp, suffix) \ -inline _Tpvec v_load(const _Tp* ptr) \ -{ return _Tpvec(_mm_loadu_##suffix(ptr)); } \ -inline _Tpvec v_load_aligned(const _Tp* ptr) \ -{ return _Tpvec(_mm_load_##suffix(ptr)); } \ -inline _Tpvec v_load_low(const _Tp* ptr) \ -{ return _Tpvec(_mm_castsi128_##suffix(_mm_loadl_epi64((const __m128i*)ptr))); } \ -inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ -{ \ - return _Tpvec(_mm_castsi128_##suffix( \ - _mm_unpacklo_epi64(_mm_loadl_epi64((const __m128i*)ptr0), \ - _mm_loadl_epi64((const __m128i*)ptr1)))); \ -} \ -inline void v_store(_Tp* ptr, const _Tpvec& a) \ -{ _mm_storeu_##suffix(ptr, a.val); } \ -inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ -{ _mm_store_##suffix(ptr, a.val); } \ -inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ -{ _mm_stream_##suffix(ptr, a.val); } \ -inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ -{ \ - if( mode == hal::STORE_UNALIGNED ) \ - _mm_storeu_##suffix(ptr, a.val); \ - else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ - _mm_stream_##suffix(ptr, a.val); \ - else \ - _mm_store_##suffix(ptr, a.val); \ -} \ -inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ -{ _mm_storel_epi64((__m128i*)ptr, _mm_cast##suffix##_si128(a.val)); } \ -inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ -{ \ - __m128i a1 = _mm_cast##suffix##_si128(a.val); \ - _mm_storel_epi64((__m128i*)ptr, _mm_unpackhi_epi64(a1, a1)); \ -} - -OPENCV_HAL_IMPL_SSE_LOADSTORE_FLT_OP(v_float32x4, float, ps) -OPENCV_HAL_IMPL_SSE_LOADSTORE_FLT_OP(v_float64x2, double, pd) - -inline unsigned v_reduce_sum(const v_uint8x16& a) -{ - __m128i half = _mm_sad_epu8(a.val, _mm_setzero_si128()); - return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(half, _mm_unpackhi_epi64(half, half))); -} -inline int v_reduce_sum(const v_int8x16& a) -{ - __m128i half = _mm_set1_epi8((schar)-128); - half = _mm_sad_epu8(_mm_xor_si128(a.val, half), _mm_setzero_si128()); - return _mm_cvtsi128_si32(_mm_add_epi32(half, _mm_unpackhi_epi64(half, half))) - 2048; -} -#define OPENCV_HAL_IMPL_SSE_REDUCE_OP_16(func) \ -inline schar v_reduce_##func(const v_int8x16& a) \ -{ \ - __m128i val = a.val; \ - __m128i smask = _mm_set1_epi8((schar)-128); \ - val = _mm_xor_si128(val, smask); \ - val = _mm_##func##_epu8(val, _mm_srli_si128(val,8)); \ - val = _mm_##func##_epu8(val, _mm_srli_si128(val,4)); \ - val = _mm_##func##_epu8(val, _mm_srli_si128(val,2)); \ - val = _mm_##func##_epu8(val, _mm_srli_si128(val,1)); \ - return (schar)_mm_cvtsi128_si32(val) ^ (schar)-128; \ -} \ -inline uchar v_reduce_##func(const v_uint8x16& a) \ -{ \ - __m128i val = a.val; \ - val = _mm_##func##_epu8(val, _mm_srli_si128(val,8)); \ - val = _mm_##func##_epu8(val, _mm_srli_si128(val,4)); \ - val = _mm_##func##_epu8(val, _mm_srli_si128(val,2)); \ - val = _mm_##func##_epu8(val, _mm_srli_si128(val,1)); \ - return (uchar)_mm_cvtsi128_si32(val); \ -} -OPENCV_HAL_IMPL_SSE_REDUCE_OP_16(max) -OPENCV_HAL_IMPL_SSE_REDUCE_OP_16(min) - -#define OPENCV_HAL_IMPL_SSE_REDUCE_OP_8(_Tpvec, scalartype, func, suffix, sbit) \ -inline scalartype v_reduce_##func(const v_##_Tpvec& a) \ -{ \ - __m128i val = a.val; \ - val = _mm_##func##_##suffix(val, _mm_srli_si128(val,8)); \ - val = _mm_##func##_##suffix(val, _mm_srli_si128(val,4)); \ - val = _mm_##func##_##suffix(val, _mm_srli_si128(val,2)); \ - return (scalartype)_mm_cvtsi128_si32(val); \ -} \ -inline unsigned scalartype v_reduce_##func(const v_u##_Tpvec& a) \ -{ \ - __m128i val = a.val; \ - __m128i smask = _mm_set1_epi16(sbit); \ - val = _mm_xor_si128(val, smask); \ - val = _mm_##func##_##suffix(val, _mm_srli_si128(val,8)); \ - val = _mm_##func##_##suffix(val, _mm_srli_si128(val,4)); \ - val = _mm_##func##_##suffix(val, _mm_srli_si128(val,2)); \ - return (unsigned scalartype)(_mm_cvtsi128_si32(val) ^ sbit); \ -} -OPENCV_HAL_IMPL_SSE_REDUCE_OP_8(int16x8, short, max, epi16, (short)-32768) -OPENCV_HAL_IMPL_SSE_REDUCE_OP_8(int16x8, short, min, epi16, (short)-32768) - -#define OPENCV_HAL_IMPL_SSE_REDUCE_OP_4_SUM(_Tpvec, scalartype, regtype, suffix, cast_from, cast_to, extract) \ -inline scalartype v_reduce_sum(const _Tpvec& a) \ -{ \ - regtype val = a.val; \ - val = _mm_add_##suffix(val, cast_to(_mm_srli_si128(cast_from(val), 8))); \ - val = _mm_add_##suffix(val, cast_to(_mm_srli_si128(cast_from(val), 4))); \ - return (scalartype)_mm_cvt##extract(val); \ -} - -#define OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(_Tpvec, scalartype, func, scalar_func) \ -inline scalartype v_reduce_##func(const _Tpvec& a) \ -{ \ - scalartype CV_DECL_ALIGNED(16) buf[4]; \ - v_store_aligned(buf, a); \ - scalartype s0 = scalar_func(buf[0], buf[1]); \ - scalartype s1 = scalar_func(buf[2], buf[3]); \ - return scalar_func(s0, s1); \ -} - -OPENCV_HAL_IMPL_SSE_REDUCE_OP_4_SUM(v_uint32x4, unsigned, __m128i, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP, si128_si32) -OPENCV_HAL_IMPL_SSE_REDUCE_OP_4_SUM(v_int32x4, int, __m128i, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP, si128_si32) -OPENCV_HAL_IMPL_SSE_REDUCE_OP_4_SUM(v_float32x4, float, __m128, ps, _mm_castps_si128, _mm_castsi128_ps, ss_f32) - -inline int v_reduce_sum(const v_int16x8& a) -{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } -inline unsigned v_reduce_sum(const v_uint16x8& a) -{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } - -inline uint64 v_reduce_sum(const v_uint64x2& a) -{ - uint64 CV_DECL_ALIGNED(32) idx[2]; - v_store_aligned(idx, a); - return idx[0] + idx[1]; -} -inline int64 v_reduce_sum(const v_int64x2& a) -{ - int64 CV_DECL_ALIGNED(32) idx[2]; - v_store_aligned(idx, a); - return idx[0] + idx[1]; -} -inline double v_reduce_sum(const v_float64x2& a) -{ - double CV_DECL_ALIGNED(32) idx[2]; - v_store_aligned(idx, a); - return idx[0] + idx[1]; -} - -inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, - const v_float32x4& c, const v_float32x4& d) -{ -#if CV_SSE3 - __m128 ab = _mm_hadd_ps(a.val, b.val); - __m128 cd = _mm_hadd_ps(c.val, d.val); - return v_float32x4(_mm_hadd_ps(ab, cd)); -#else - __m128 ac = _mm_add_ps(_mm_unpacklo_ps(a.val, c.val), _mm_unpackhi_ps(a.val, c.val)); - __m128 bd = _mm_add_ps(_mm_unpacklo_ps(b.val, d.val), _mm_unpackhi_ps(b.val, d.val)); - return v_float32x4(_mm_add_ps(_mm_unpacklo_ps(ac, bd), _mm_unpackhi_ps(ac, bd))); -#endif -} - -OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_uint32x4, unsigned, max, std::max) -OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_uint32x4, unsigned, min, std::min) -OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_int32x4, int, max, std::max) -OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_int32x4, int, min, std::min) -OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_float32x4, float, max, std::max) -OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_float32x4, float, min, std::min) - -inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b) -{ - __m128i half = _mm_sad_epu8(a.val, b.val); - return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(half, _mm_unpackhi_epi64(half, half))); -} -inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b) -{ - __m128i half = _mm_set1_epi8(0x7f); - half = _mm_sad_epu8(_mm_add_epi8(a.val, half), _mm_add_epi8(b.val, half)); - return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(half, _mm_unpackhi_epi64(half, half))); -} -inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b) -{ - v_uint32x4 l, h; - v_expand(v_absdiff(a, b), l, h); - return v_reduce_sum(v_add(l, h)); -} -inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b) -{ - v_uint32x4 l, h; - v_expand(v_absdiff(a, b), l, h); - return v_reduce_sum(v_add(l, h)); -} -inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b) -{ - return v_reduce_sum(v_absdiff(a, b)); -} -inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b) -{ - return v_reduce_sum(v_absdiff(a, b)); -} -inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) -{ - return v_reduce_sum(v_absdiff(a, b)); -} - -inline v_uint8x16 v_popcount(const v_uint8x16& a) -{ - __m128i m1 = _mm_set1_epi32(0x55555555); - __m128i m2 = _mm_set1_epi32(0x33333333); - __m128i m4 = _mm_set1_epi32(0x0f0f0f0f); - __m128i p = a.val; - p = _mm_add_epi32(_mm_and_si128(_mm_srli_epi32(p, 1), m1), _mm_and_si128(p, m1)); - p = _mm_add_epi32(_mm_and_si128(_mm_srli_epi32(p, 2), m2), _mm_and_si128(p, m2)); - p = _mm_add_epi32(_mm_and_si128(_mm_srli_epi32(p, 4), m4), _mm_and_si128(p, m4)); - return v_uint8x16(p); -} -inline v_uint16x8 v_popcount(const v_uint16x8& a) -{ - v_uint8x16 p = v_popcount(v_reinterpret_as_u8(a)); - p = v_add(p, v_rotate_right<1>(p)); - return v_and(v_reinterpret_as_u16(p), v_setall_u16(0x00ff)); -} -inline v_uint32x4 v_popcount(const v_uint32x4& a) -{ - v_uint8x16 p = v_popcount(v_reinterpret_as_u8(a)); - p = v_add(p, v_rotate_right<1>(p)); - p = v_add(p, v_rotate_right<2>(p)); - return v_and(v_reinterpret_as_u32(p), v_setall_u32(0x000000ff)); -} -inline v_uint64x2 v_popcount(const v_uint64x2& a) -{ - return v_uint64x2(_mm_sad_epu8(v_popcount(v_reinterpret_as_u8(a)).val, _mm_setzero_si128())); -} -inline v_uint8x16 v_popcount(const v_int8x16& a) -{ return v_popcount(v_reinterpret_as_u8(a)); } -inline v_uint16x8 v_popcount(const v_int16x8& a) -{ return v_popcount(v_reinterpret_as_u16(a)); } -inline v_uint32x4 v_popcount(const v_int32x4& a) -{ return v_popcount(v_reinterpret_as_u32(a)); } -inline v_uint64x2 v_popcount(const v_int64x2& a) -{ return v_popcount(v_reinterpret_as_u64(a)); } - -#define OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(_Tpvec, suffix, cast_op, allmask) \ -inline int v_signmask(const _Tpvec& a) { return _mm_movemask_##suffix(cast_op(a.val)); } \ -inline bool v_check_all(const _Tpvec& a) { return _mm_movemask_##suffix(cast_op(a.val)) == allmask; } \ -inline bool v_check_any(const _Tpvec& a) { return _mm_movemask_##suffix(cast_op(a.val)) != 0; } -OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_uint8x16, epi8, OPENCV_HAL_NOP, 65535) -OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_int8x16, epi8, OPENCV_HAL_NOP, 65535) -OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_uint32x4, ps, _mm_castsi128_ps, 15) -OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_int32x4, ps, _mm_castsi128_ps, 15) -OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_uint64x2, pd, _mm_castsi128_pd, 3) -OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_int64x2, pd, _mm_castsi128_pd, 3) -OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_float32x4, ps, OPENCV_HAL_NOP, 15) -OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_float64x2, pd, OPENCV_HAL_NOP, 3) - -#define OPENCV_HAL_IMPL_SSE_CHECK_SIGNS_SHORT(_Tpvec) \ -inline int v_signmask(const _Tpvec& a) { return _mm_movemask_epi8(_mm_packs_epi16(a.val, a.val)) & 255; } \ -inline bool v_check_all(const _Tpvec& a) { return (_mm_movemask_epi8(a.val) & 0xaaaa) == 0xaaaa; } \ -inline bool v_check_any(const _Tpvec& a) { return (_mm_movemask_epi8(a.val) & 0xaaaa) != 0; } -OPENCV_HAL_IMPL_SSE_CHECK_SIGNS_SHORT(v_uint16x8) -OPENCV_HAL_IMPL_SSE_CHECK_SIGNS_SHORT(v_int16x8) - -inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } -inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } -inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } -inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } -inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } -inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } -inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } - -#if CV_SSE4_1 -#define OPENCV_HAL_IMPL_SSE_SELECT(_Tpvec, cast_ret, cast, suffix) \ -inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(cast_ret(_mm_blendv_##suffix(cast(b.val), cast(a.val), cast(mask.val)))); \ -} - -OPENCV_HAL_IMPL_SSE_SELECT(v_uint8x16, OPENCV_HAL_NOP, OPENCV_HAL_NOP, epi8) -OPENCV_HAL_IMPL_SSE_SELECT(v_int8x16, OPENCV_HAL_NOP, OPENCV_HAL_NOP, epi8) -OPENCV_HAL_IMPL_SSE_SELECT(v_uint16x8, OPENCV_HAL_NOP, OPENCV_HAL_NOP, epi8) -OPENCV_HAL_IMPL_SSE_SELECT(v_int16x8, OPENCV_HAL_NOP, OPENCV_HAL_NOP, epi8) -OPENCV_HAL_IMPL_SSE_SELECT(v_uint32x4, _mm_castps_si128, _mm_castsi128_ps, ps) -OPENCV_HAL_IMPL_SSE_SELECT(v_int32x4, _mm_castps_si128, _mm_castsi128_ps, ps) -// OPENCV_HAL_IMPL_SSE_SELECT(v_uint64x2, TBD, TBD, pd) -// OPENCV_HAL_IMPL_SSE_SELECT(v_int64x2, TBD, TBD, ps) -OPENCV_HAL_IMPL_SSE_SELECT(v_float32x4, OPENCV_HAL_NOP, OPENCV_HAL_NOP, ps) -OPENCV_HAL_IMPL_SSE_SELECT(v_float64x2, OPENCV_HAL_NOP, OPENCV_HAL_NOP, pd) - -#else // CV_SSE4_1 - -#define OPENCV_HAL_IMPL_SSE_SELECT(_Tpvec, suffix) \ -inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(_mm_xor_##suffix(b.val, _mm_and_##suffix(_mm_xor_##suffix(b.val, a.val), mask.val))); \ -} - -OPENCV_HAL_IMPL_SSE_SELECT(v_uint8x16, si128) -OPENCV_HAL_IMPL_SSE_SELECT(v_int8x16, si128) -OPENCV_HAL_IMPL_SSE_SELECT(v_uint16x8, si128) -OPENCV_HAL_IMPL_SSE_SELECT(v_int16x8, si128) -OPENCV_HAL_IMPL_SSE_SELECT(v_uint32x4, si128) -OPENCV_HAL_IMPL_SSE_SELECT(v_int32x4, si128) -// OPENCV_HAL_IMPL_SSE_SELECT(v_uint64x2, si128) -// OPENCV_HAL_IMPL_SSE_SELECT(v_int64x2, si128) -OPENCV_HAL_IMPL_SSE_SELECT(v_float32x4, ps) -OPENCV_HAL_IMPL_SSE_SELECT(v_float64x2, pd) -#endif - -/* Expand */ -#define OPENCV_HAL_IMPL_SSE_EXPAND(_Tpvec, _Tpwvec, _Tp, intrin) \ - inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ - { \ - b0.val = intrin(a.val); \ - b1.val = __CV_CAT(intrin, _high)(a.val); \ - } \ - inline _Tpwvec v_expand_low(const _Tpvec& a) \ - { return _Tpwvec(intrin(a.val)); } \ - inline _Tpwvec v_expand_high(const _Tpvec& a) \ - { return _Tpwvec(__CV_CAT(intrin, _high)(a.val)); } \ - inline _Tpwvec v_load_expand(const _Tp* ptr) \ - { \ - __m128i a = _mm_loadl_epi64((const __m128i*)ptr); \ - return _Tpwvec(intrin(a)); \ - } - -OPENCV_HAL_IMPL_SSE_EXPAND(v_uint8x16, v_uint16x8, uchar, _v128_cvtepu8_epi16) -OPENCV_HAL_IMPL_SSE_EXPAND(v_int8x16, v_int16x8, schar, _v128_cvtepi8_epi16) -OPENCV_HAL_IMPL_SSE_EXPAND(v_uint16x8, v_uint32x4, ushort, _v128_cvtepu16_epi32) -OPENCV_HAL_IMPL_SSE_EXPAND(v_int16x8, v_int32x4, short, _v128_cvtepi16_epi32) -OPENCV_HAL_IMPL_SSE_EXPAND(v_uint32x4, v_uint64x2, unsigned, _v128_cvtepu32_epi64) -OPENCV_HAL_IMPL_SSE_EXPAND(v_int32x4, v_int64x2, int, _v128_cvtepi32_epi64) - -#define OPENCV_HAL_IMPL_SSE_EXPAND_Q(_Tpvec, _Tp, intrin) \ - inline _Tpvec v_load_expand_q(const _Tp* ptr) \ - { \ - typedef int CV_DECL_ALIGNED(1) unaligned_int; \ - __m128i a = _mm_cvtsi32_si128(*(const unaligned_int*)ptr); \ - return _Tpvec(intrin(a)); \ - } - -OPENCV_HAL_IMPL_SSE_EXPAND_Q(v_uint32x4, uchar, _v128_cvtepu8_epi32) -OPENCV_HAL_IMPL_SSE_EXPAND_Q(v_int32x4, schar, _v128_cvtepi8_epi32) - -#define OPENCV_HAL_IMPL_SSE_UNPACKS(_Tpvec, suffix, cast_from, cast_to) \ -inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) \ -{ \ - b0.val = _mm_unpacklo_##suffix(a0.val, a1.val); \ - b1.val = _mm_unpackhi_##suffix(a0.val, a1.val); \ -} \ -inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ -{ \ - __m128i a1 = cast_from(a.val), b1 = cast_from(b.val); \ - return _Tpvec(cast_to(_mm_unpacklo_epi64(a1, b1))); \ -} \ -inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ -{ \ - __m128i a1 = cast_from(a.val), b1 = cast_from(b.val); \ - return _Tpvec(cast_to(_mm_unpackhi_epi64(a1, b1))); \ -} \ -inline void v_recombine(const _Tpvec& a, const _Tpvec& b, _Tpvec& c, _Tpvec& d) \ -{ \ - __m128i a1 = cast_from(a.val), b1 = cast_from(b.val); \ - c.val = cast_to(_mm_unpacklo_epi64(a1, b1)); \ - d.val = cast_to(_mm_unpackhi_epi64(a1, b1)); \ -} - -OPENCV_HAL_IMPL_SSE_UNPACKS(v_uint8x16, epi8, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_UNPACKS(v_int8x16, epi8, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_UNPACKS(v_uint16x8, epi16, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_UNPACKS(v_int16x8, epi16, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_UNPACKS(v_uint32x4, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_UNPACKS(v_int32x4, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_UNPACKS(v_float32x4, ps, _mm_castps_si128, _mm_castsi128_ps) -OPENCV_HAL_IMPL_SSE_UNPACKS(v_float64x2, pd, _mm_castpd_si128, _mm_castsi128_pd) - -inline v_uint8x16 v_reverse(const v_uint8x16 &a) -{ -#if CV_SSSE3 - static const __m128i perm = _mm_setr_epi8(15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); - return v_uint8x16(_mm_shuffle_epi8(a.val, perm)); -#else - uchar CV_DECL_ALIGNED(32) d[16]; - v_store_aligned(d, a); - return v_uint8x16(d[15], d[14], d[13], d[12], d[11], d[10], d[9], d[8], d[7], d[6], d[5], d[4], d[3], d[2], d[1], d[0]); -#endif -} - -inline v_int8x16 v_reverse(const v_int8x16 &a) -{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } - -inline v_uint16x8 v_reverse(const v_uint16x8 &a) -{ -#if CV_SSSE3 - static const __m128i perm = _mm_setr_epi8(14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1); - return v_uint16x8(_mm_shuffle_epi8(a.val, perm)); -#else - __m128i r = _mm_shuffle_epi32(a.val, _MM_SHUFFLE(0, 1, 2, 3)); - r = _mm_shufflelo_epi16(r, _MM_SHUFFLE(2, 3, 0, 1)); - r = _mm_shufflehi_epi16(r, _MM_SHUFFLE(2, 3, 0, 1)); - return v_uint16x8(r); -#endif -} - -inline v_int16x8 v_reverse(const v_int16x8 &a) -{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } - -inline v_uint32x4 v_reverse(const v_uint32x4 &a) -{ - return v_uint32x4(_mm_shuffle_epi32(a.val, _MM_SHUFFLE(0, 1, 2, 3))); -} - -inline v_int32x4 v_reverse(const v_int32x4 &a) -{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_float32x4 v_reverse(const v_float32x4 &a) -{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_uint64x2 v_reverse(const v_uint64x2 &a) -{ - return v_uint64x2(_mm_shuffle_epi32(a.val, _MM_SHUFFLE(1, 0, 3, 2))); -} - -inline v_int64x2 v_reverse(const v_int64x2 &a) -{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } - -inline v_float64x2 v_reverse(const v_float64x2 &a) -{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } - -template -inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) -{ - return v_rotate_right(a, b); -} - -inline v_int32x4 v_round(const v_float32x4& a) -{ return v_int32x4(_mm_cvtps_epi32(a.val)); } - -inline v_int32x4 v_floor(const v_float32x4& a) -{ - __m128i a1 = _mm_cvtps_epi32(a.val); - __m128i mask = _mm_castps_si128(_mm_cmpgt_ps(_mm_cvtepi32_ps(a1), a.val)); - return v_int32x4(_mm_add_epi32(a1, mask)); -} - -inline v_int32x4 v_ceil(const v_float32x4& a) -{ - __m128i a1 = _mm_cvtps_epi32(a.val); - __m128i mask = _mm_castps_si128(_mm_cmpgt_ps(a.val, _mm_cvtepi32_ps(a1))); - return v_int32x4(_mm_sub_epi32(a1, mask)); -} - -inline v_int32x4 v_trunc(const v_float32x4& a) -{ return v_int32x4(_mm_cvttps_epi32(a.val)); } - -inline v_int32x4 v_round(const v_float64x2& a) -{ return v_int32x4(_mm_cvtpd_epi32(a.val)); } - -inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) -{ - __m128i ai = _mm_cvtpd_epi32(a.val), bi = _mm_cvtpd_epi32(b.val); - return v_int32x4(_mm_unpacklo_epi64(ai, bi)); -} - -inline v_int32x4 v_floor(const v_float64x2& a) -{ - __m128i a1 = _mm_cvtpd_epi32(a.val); - __m128i mask = _mm_castpd_si128(_mm_cmpgt_pd(_mm_cvtepi32_pd(a1), a.val)); - mask = _mm_srli_si128(_mm_slli_si128(mask, 4), 8); // m0 m0 m1 m1 => m0 m1 0 0 - return v_int32x4(_mm_add_epi32(a1, mask)); -} - -inline v_int32x4 v_ceil(const v_float64x2& a) -{ - __m128i a1 = _mm_cvtpd_epi32(a.val); - __m128i mask = _mm_castpd_si128(_mm_cmpgt_pd(a.val, _mm_cvtepi32_pd(a1))); - mask = _mm_srli_si128(_mm_slli_si128(mask, 4), 8); // m0 m0 m1 m1 => m0 m1 0 0 - return v_int32x4(_mm_sub_epi32(a1, mask)); -} - -inline v_int32x4 v_trunc(const v_float64x2& a) -{ return v_int32x4(_mm_cvttpd_epi32(a.val)); } - -#define OPENCV_HAL_IMPL_SSE_TRANSPOSE4x4(_Tpvec, suffix, cast_from, cast_to) \ -inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ - const _Tpvec& a2, const _Tpvec& a3, \ - _Tpvec& b0, _Tpvec& b1, \ - _Tpvec& b2, _Tpvec& b3) \ -{ \ - __m128i t0 = cast_from(_mm_unpacklo_##suffix(a0.val, a1.val)); \ - __m128i t1 = cast_from(_mm_unpacklo_##suffix(a2.val, a3.val)); \ - __m128i t2 = cast_from(_mm_unpackhi_##suffix(a0.val, a1.val)); \ - __m128i t3 = cast_from(_mm_unpackhi_##suffix(a2.val, a3.val)); \ -\ - b0.val = cast_to(_mm_unpacklo_epi64(t0, t1)); \ - b1.val = cast_to(_mm_unpackhi_epi64(t0, t1)); \ - b2.val = cast_to(_mm_unpacklo_epi64(t2, t3)); \ - b3.val = cast_to(_mm_unpackhi_epi64(t2, t3)); \ -} - -OPENCV_HAL_IMPL_SSE_TRANSPOSE4x4(v_uint32x4, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_TRANSPOSE4x4(v_int32x4, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_TRANSPOSE4x4(v_float32x4, ps, _mm_castps_si128, _mm_castsi128_ps) - -// load deinterleave -inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b) -{ - __m128i t00 = _mm_loadu_si128((const __m128i*)ptr); - __m128i t01 = _mm_loadu_si128((const __m128i*)(ptr + 16)); - - __m128i t10 = _mm_unpacklo_epi8(t00, t01); - __m128i t11 = _mm_unpackhi_epi8(t00, t01); - - __m128i t20 = _mm_unpacklo_epi8(t10, t11); - __m128i t21 = _mm_unpackhi_epi8(t10, t11); - - __m128i t30 = _mm_unpacklo_epi8(t20, t21); - __m128i t31 = _mm_unpackhi_epi8(t20, t21); - - a.val = _mm_unpacklo_epi8(t30, t31); - b.val = _mm_unpackhi_epi8(t30, t31); -} - -inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c) -{ -#if CV_SSE4_1 - const __m128i m0 = _mm_setr_epi8(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0); - const __m128i m1 = _mm_setr_epi8(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); - __m128i s0 = _mm_loadu_si128((const __m128i*)ptr); - __m128i s1 = _mm_loadu_si128((const __m128i*)(ptr + 16)); - __m128i s2 = _mm_loadu_si128((const __m128i*)(ptr + 32)); - __m128i a0 = _mm_blendv_epi8(_mm_blendv_epi8(s0, s1, m0), s2, m1); - __m128i b0 = _mm_blendv_epi8(_mm_blendv_epi8(s1, s2, m0), s0, m1); - __m128i c0 = _mm_blendv_epi8(_mm_blendv_epi8(s2, s0, m0), s1, m1); - const __m128i sh_b = _mm_setr_epi8(0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13); - const __m128i sh_g = _mm_setr_epi8(1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14); - const __m128i sh_r = _mm_setr_epi8(2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15); - a0 = _mm_shuffle_epi8(a0, sh_b); - b0 = _mm_shuffle_epi8(b0, sh_g); - c0 = _mm_shuffle_epi8(c0, sh_r); - a.val = a0; - b.val = b0; - c.val = c0; -#elif CV_SSSE3 - const __m128i m0 = _mm_setr_epi8(0, 3, 6, 9, 12, 15, 1, 4, 7, 10, 13, 2, 5, 8, 11, 14); - const __m128i m1 = _mm_alignr_epi8(m0, m0, 11); - const __m128i m2 = _mm_alignr_epi8(m0, m0, 6); - - __m128i t0 = _mm_loadu_si128((const __m128i*)ptr); - __m128i t1 = _mm_loadu_si128((const __m128i*)(ptr + 16)); - __m128i t2 = _mm_loadu_si128((const __m128i*)(ptr + 32)); - - __m128i s0 = _mm_shuffle_epi8(t0, m0); - __m128i s1 = _mm_shuffle_epi8(t1, m1); - __m128i s2 = _mm_shuffle_epi8(t2, m2); - - t0 = _mm_alignr_epi8(s1, _mm_slli_si128(s0, 10), 5); - a.val = _mm_alignr_epi8(s2, t0, 5); - - t1 = _mm_alignr_epi8(_mm_srli_si128(s1, 5), _mm_slli_si128(s0, 5), 6); - b.val = _mm_alignr_epi8(_mm_srli_si128(s2, 5), t1, 5); - - t2 = _mm_alignr_epi8(_mm_srli_si128(s2, 10), s1, 11); - c.val = _mm_alignr_epi8(t2, s0, 11); -#else - __m128i t00 = _mm_loadu_si128((const __m128i*)ptr); - __m128i t01 = _mm_loadu_si128((const __m128i*)(ptr + 16)); - __m128i t02 = _mm_loadu_si128((const __m128i*)(ptr + 32)); - - __m128i t10 = _mm_unpacklo_epi8(t00, _mm_unpackhi_epi64(t01, t01)); - __m128i t11 = _mm_unpacklo_epi8(_mm_unpackhi_epi64(t00, t00), t02); - __m128i t12 = _mm_unpacklo_epi8(t01, _mm_unpackhi_epi64(t02, t02)); - - __m128i t20 = _mm_unpacklo_epi8(t10, _mm_unpackhi_epi64(t11, t11)); - __m128i t21 = _mm_unpacklo_epi8(_mm_unpackhi_epi64(t10, t10), t12); - __m128i t22 = _mm_unpacklo_epi8(t11, _mm_unpackhi_epi64(t12, t12)); - - __m128i t30 = _mm_unpacklo_epi8(t20, _mm_unpackhi_epi64(t21, t21)); - __m128i t31 = _mm_unpacklo_epi8(_mm_unpackhi_epi64(t20, t20), t22); - __m128i t32 = _mm_unpacklo_epi8(t21, _mm_unpackhi_epi64(t22, t22)); - - a.val = _mm_unpacklo_epi8(t30, _mm_unpackhi_epi64(t31, t31)); - b.val = _mm_unpacklo_epi8(_mm_unpackhi_epi64(t30, t30), t32); - c.val = _mm_unpacklo_epi8(t31, _mm_unpackhi_epi64(t32, t32)); -#endif -} - -inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c, v_uint8x16& d) -{ - __m128i u0 = _mm_loadu_si128((const __m128i*)ptr); // a0 b0 c0 d0 a1 b1 c1 d1 ... - __m128i u1 = _mm_loadu_si128((const __m128i*)(ptr + 16)); // a4 b4 c4 d4 ... - __m128i u2 = _mm_loadu_si128((const __m128i*)(ptr + 32)); // a8 b8 c8 d8 ... - __m128i u3 = _mm_loadu_si128((const __m128i*)(ptr + 48)); // a12 b12 c12 d12 ... - - __m128i v0 = _mm_unpacklo_epi8(u0, u2); // a0 a8 b0 b8 ... - __m128i v1 = _mm_unpackhi_epi8(u0, u2); // a2 a10 b2 b10 ... - __m128i v2 = _mm_unpacklo_epi8(u1, u3); // a4 a12 b4 b12 ... - __m128i v3 = _mm_unpackhi_epi8(u1, u3); // a6 a14 b6 b14 ... - - u0 = _mm_unpacklo_epi8(v0, v2); // a0 a4 a8 a12 ... - u1 = _mm_unpacklo_epi8(v1, v3); // a2 a6 a10 a14 ... - u2 = _mm_unpackhi_epi8(v0, v2); // a1 a5 a9 a13 ... - u3 = _mm_unpackhi_epi8(v1, v3); // a3 a7 a11 a15 ... - - v0 = _mm_unpacklo_epi8(u0, u1); // a0 a2 a4 a6 ... - v1 = _mm_unpacklo_epi8(u2, u3); // a1 a3 a5 a7 ... - v2 = _mm_unpackhi_epi8(u0, u1); // c0 c2 c4 c6 ... - v3 = _mm_unpackhi_epi8(u2, u3); // c1 c3 c5 c7 ... - - a.val = _mm_unpacklo_epi8(v0, v1); - b.val = _mm_unpackhi_epi8(v0, v1); - c.val = _mm_unpacklo_epi8(v2, v3); - d.val = _mm_unpackhi_epi8(v2, v3); -} - -inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b) -{ - __m128i v0 = _mm_loadu_si128((__m128i*)(ptr)); // a0 b0 a1 b1 a2 b2 a3 b3 - __m128i v1 = _mm_loadu_si128((__m128i*)(ptr + 8)); // a4 b4 a5 b5 a6 b6 a7 b7 - - __m128i v2 = _mm_unpacklo_epi16(v0, v1); // a0 a4 b0 b4 a1 a5 b1 b5 - __m128i v3 = _mm_unpackhi_epi16(v0, v1); // a2 a6 b2 b6 a3 a7 b3 b7 - __m128i v4 = _mm_unpacklo_epi16(v2, v3); // a0 a2 a4 a6 b0 b2 b4 b6 - __m128i v5 = _mm_unpackhi_epi16(v2, v3); // a1 a3 a5 a7 b1 b3 b5 b7 - - a.val = _mm_unpacklo_epi16(v4, v5); // a0 a1 a2 a3 a4 a5 a6 a7 - b.val = _mm_unpackhi_epi16(v4, v5); // b0 b1 ab b3 b4 b5 b6 b7 -} - -inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c) -{ -#if CV_SSE4_1 - __m128i v0 = _mm_loadu_si128((__m128i*)(ptr)); - __m128i v1 = _mm_loadu_si128((__m128i*)(ptr + 8)); - __m128i v2 = _mm_loadu_si128((__m128i*)(ptr + 16)); - __m128i a0 = _mm_blend_epi16(_mm_blend_epi16(v0, v1, 0x92), v2, 0x24); - __m128i b0 = _mm_blend_epi16(_mm_blend_epi16(v2, v0, 0x92), v1, 0x24); - __m128i c0 = _mm_blend_epi16(_mm_blend_epi16(v1, v2, 0x92), v0, 0x24); - - const __m128i sh_a = _mm_setr_epi8(0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11); - const __m128i sh_b = _mm_setr_epi8(2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 0, 1, 6, 7, 12, 13); - const __m128i sh_c = _mm_setr_epi8(4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15); - a0 = _mm_shuffle_epi8(a0, sh_a); - b0 = _mm_shuffle_epi8(b0, sh_b); - c0 = _mm_shuffle_epi8(c0, sh_c); - - a.val = a0; - b.val = b0; - c.val = c0; -#else - __m128i t00 = _mm_loadu_si128((const __m128i*)ptr); - __m128i t01 = _mm_loadu_si128((const __m128i*)(ptr + 8)); - __m128i t02 = _mm_loadu_si128((const __m128i*)(ptr + 16)); - - __m128i t10 = _mm_unpacklo_epi16(t00, _mm_unpackhi_epi64(t01, t01)); - __m128i t11 = _mm_unpacklo_epi16(_mm_unpackhi_epi64(t00, t00), t02); - __m128i t12 = _mm_unpacklo_epi16(t01, _mm_unpackhi_epi64(t02, t02)); - - __m128i t20 = _mm_unpacklo_epi16(t10, _mm_unpackhi_epi64(t11, t11)); - __m128i t21 = _mm_unpacklo_epi16(_mm_unpackhi_epi64(t10, t10), t12); - __m128i t22 = _mm_unpacklo_epi16(t11, _mm_unpackhi_epi64(t12, t12)); - - a.val = _mm_unpacklo_epi16(t20, _mm_unpackhi_epi64(t21, t21)); - b.val = _mm_unpacklo_epi16(_mm_unpackhi_epi64(t20, t20), t22); - c.val = _mm_unpacklo_epi16(t21, _mm_unpackhi_epi64(t22, t22)); -#endif -} - -inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c, v_uint16x8& d) -{ - __m128i u0 = _mm_loadu_si128((const __m128i*)ptr); // a0 b0 c0 d0 a1 b1 c1 d1 - __m128i u1 = _mm_loadu_si128((const __m128i*)(ptr + 8)); // a2 b2 c2 d2 ... - __m128i u2 = _mm_loadu_si128((const __m128i*)(ptr + 16)); // a4 b4 c4 d4 ... - __m128i u3 = _mm_loadu_si128((const __m128i*)(ptr + 24)); // a6 b6 c6 d6 ... - - __m128i v0 = _mm_unpacklo_epi16(u0, u2); // a0 a4 b0 b4 ... - __m128i v1 = _mm_unpackhi_epi16(u0, u2); // a1 a5 b1 b5 ... - __m128i v2 = _mm_unpacklo_epi16(u1, u3); // a2 a6 b2 b6 ... - __m128i v3 = _mm_unpackhi_epi16(u1, u3); // a3 a7 b3 b7 ... - - u0 = _mm_unpacklo_epi16(v0, v2); // a0 a2 a4 a6 ... - u1 = _mm_unpacklo_epi16(v1, v3); // a1 a3 a5 a7 ... - u2 = _mm_unpackhi_epi16(v0, v2); // c0 c2 c4 c6 ... - u3 = _mm_unpackhi_epi16(v1, v3); // c1 c3 c5 c7 ... - - a.val = _mm_unpacklo_epi16(u0, u1); - b.val = _mm_unpackhi_epi16(u0, u1); - c.val = _mm_unpacklo_epi16(u2, u3); - d.val = _mm_unpackhi_epi16(u2, u3); -} - -inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b) -{ - __m128i v0 = _mm_loadu_si128((__m128i*)(ptr)); // a0 b0 a1 b1 - __m128i v1 = _mm_loadu_si128((__m128i*)(ptr + 4)); // a2 b2 a3 b3 - - __m128i v2 = _mm_unpacklo_epi32(v0, v1); // a0 a2 b0 b2 - __m128i v3 = _mm_unpackhi_epi32(v0, v1); // a1 a3 b1 b3 - - a.val = _mm_unpacklo_epi32(v2, v3); // a0 a1 a2 a3 - b.val = _mm_unpackhi_epi32(v2, v3); // b0 b1 ab b3 -} - -inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c) -{ - __m128i t00 = _mm_loadu_si128((const __m128i*)ptr); - __m128i t01 = _mm_loadu_si128((const __m128i*)(ptr + 4)); - __m128i t02 = _mm_loadu_si128((const __m128i*)(ptr + 8)); - - __m128i t10 = _mm_unpacklo_epi32(t00, _mm_unpackhi_epi64(t01, t01)); - __m128i t11 = _mm_unpacklo_epi32(_mm_unpackhi_epi64(t00, t00), t02); - __m128i t12 = _mm_unpacklo_epi32(t01, _mm_unpackhi_epi64(t02, t02)); - - a.val = _mm_unpacklo_epi32(t10, _mm_unpackhi_epi64(t11, t11)); - b.val = _mm_unpacklo_epi32(_mm_unpackhi_epi64(t10, t10), t12); - c.val = _mm_unpacklo_epi32(t11, _mm_unpackhi_epi64(t12, t12)); -} - -inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c, v_uint32x4& d) -{ - v_uint32x4 s0(_mm_loadu_si128((const __m128i*)ptr)); // a0 b0 c0 d0 - v_uint32x4 s1(_mm_loadu_si128((const __m128i*)(ptr + 4))); // a1 b1 c1 d1 - v_uint32x4 s2(_mm_loadu_si128((const __m128i*)(ptr + 8))); // a2 b2 c2 d2 - v_uint32x4 s3(_mm_loadu_si128((const __m128i*)(ptr + 12))); // a3 b3 c3 d3 - - v_transpose4x4(s0, s1, s2, s3, a, b, c, d); -} - -inline void v_load_deinterleave(const float* ptr, v_float32x4& a, v_float32x4& b) -{ - __m128 u0 = _mm_loadu_ps(ptr); // a0 b0 a1 b1 - __m128 u1 = _mm_loadu_ps((ptr + 4)); // a2 b2 a3 b3 - - a.val = _mm_shuffle_ps(u0, u1, _MM_SHUFFLE(2, 0, 2, 0)); // a0 a1 a2 a3 - b.val = _mm_shuffle_ps(u0, u1, _MM_SHUFFLE(3, 1, 3, 1)); // b0 b1 ab b3 -} - -inline void v_load_deinterleave(const float* ptr, v_float32x4& a, v_float32x4& b, v_float32x4& c) -{ - __m128 t0 = _mm_loadu_ps(ptr + 0); - __m128 t1 = _mm_loadu_ps(ptr + 4); - __m128 t2 = _mm_loadu_ps(ptr + 8); - - __m128 at12 = _mm_shuffle_ps(t1, t2, _MM_SHUFFLE(0, 1, 0, 2)); - a.val = _mm_shuffle_ps(t0, at12, _MM_SHUFFLE(2, 0, 3, 0)); - - __m128 bt01 = _mm_shuffle_ps(t0, t1, _MM_SHUFFLE(0, 0, 0, 1)); - __m128 bt12 = _mm_shuffle_ps(t1, t2, _MM_SHUFFLE(0, 2, 0, 3)); - b.val = _mm_shuffle_ps(bt01, bt12, _MM_SHUFFLE(2, 0, 2, 0)); - - __m128 ct01 = _mm_shuffle_ps(t0, t1, _MM_SHUFFLE(0, 1, 0, 2)); - c.val = _mm_shuffle_ps(ct01, t2, _MM_SHUFFLE(3, 0, 2, 0)); -} - -inline void v_load_deinterleave(const float* ptr, v_float32x4& a, v_float32x4& b, v_float32x4& c, v_float32x4& d) -{ - __m128 t0 = _mm_loadu_ps(ptr + 0); - __m128 t1 = _mm_loadu_ps(ptr + 4); - __m128 t2 = _mm_loadu_ps(ptr + 8); - __m128 t3 = _mm_loadu_ps(ptr + 12); - __m128 t02lo = _mm_unpacklo_ps(t0, t2); - __m128 t13lo = _mm_unpacklo_ps(t1, t3); - __m128 t02hi = _mm_unpackhi_ps(t0, t2); - __m128 t13hi = _mm_unpackhi_ps(t1, t3); - a.val = _mm_unpacklo_ps(t02lo, t13lo); - b.val = _mm_unpackhi_ps(t02lo, t13lo); - c.val = _mm_unpacklo_ps(t02hi, t13hi); - d.val = _mm_unpackhi_ps(t02hi, t13hi); -} - -inline void v_load_deinterleave(const uint64 *ptr, v_uint64x2& a, v_uint64x2& b) -{ - __m128i t0 = _mm_loadu_si128((const __m128i*)ptr); - __m128i t1 = _mm_loadu_si128((const __m128i*)(ptr + 2)); - - a = v_uint64x2(_mm_unpacklo_epi64(t0, t1)); - b = v_uint64x2(_mm_unpackhi_epi64(t0, t1)); -} - -inline void v_load_deinterleave(const uint64 *ptr, v_uint64x2& a, v_uint64x2& b, v_uint64x2& c) -{ - __m128i t0 = _mm_loadu_si128((const __m128i*)ptr); // a0, b0 - __m128i t1 = _mm_loadu_si128((const __m128i*)(ptr + 2)); // c0, a1 - __m128i t2 = _mm_loadu_si128((const __m128i*)(ptr + 4)); // b1, c1 - - t1 = _mm_shuffle_epi32(t1, 0x4e); // a1, c0 - - a = v_uint64x2(_mm_unpacklo_epi64(t0, t1)); - b = v_uint64x2(_mm_unpacklo_epi64(_mm_unpackhi_epi64(t0, t0), t2)); - c = v_uint64x2(_mm_unpackhi_epi64(t1, t2)); -} - -inline void v_load_deinterleave(const uint64 *ptr, v_uint64x2& a, - v_uint64x2& b, v_uint64x2& c, v_uint64x2& d) -{ - __m128i t0 = _mm_loadu_si128((const __m128i*)ptr); // a0 b0 - __m128i t1 = _mm_loadu_si128((const __m128i*)(ptr + 2)); // c0 d0 - __m128i t2 = _mm_loadu_si128((const __m128i*)(ptr + 4)); // a1 b1 - __m128i t3 = _mm_loadu_si128((const __m128i*)(ptr + 6)); // c1 d1 - - a = v_uint64x2(_mm_unpacklo_epi64(t0, t2)); - b = v_uint64x2(_mm_unpackhi_epi64(t0, t2)); - c = v_uint64x2(_mm_unpacklo_epi64(t1, t3)); - d = v_uint64x2(_mm_unpackhi_epi64(t1, t3)); -} - -// store interleave - -inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, - hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - __m128i v0 = _mm_unpacklo_epi8(a.val, b.val); - __m128i v1 = _mm_unpackhi_epi8(a.val, b.val); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_si128((__m128i*)(ptr), v0); - _mm_stream_si128((__m128i*)(ptr + 16), v1); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_si128((__m128i*)(ptr), v0); - _mm_store_si128((__m128i*)(ptr + 16), v1); - } - else - { - _mm_storeu_si128((__m128i*)(ptr), v0); - _mm_storeu_si128((__m128i*)(ptr + 16), v1); - } -} - -inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, - const v_uint8x16& c, hal::StoreMode mode = hal::STORE_UNALIGNED) -{ -#if CV_SSE4_1 - const __m128i sh_a = _mm_setr_epi8(0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5); - const __m128i sh_b = _mm_setr_epi8(5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10); - const __m128i sh_c = _mm_setr_epi8(10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15); - __m128i a0 = _mm_shuffle_epi8(a.val, sh_a); - __m128i b0 = _mm_shuffle_epi8(b.val, sh_b); - __m128i c0 = _mm_shuffle_epi8(c.val, sh_c); - - const __m128i m0 = _mm_setr_epi8(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0); - const __m128i m1 = _mm_setr_epi8(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); - __m128i v0 = _mm_blendv_epi8(_mm_blendv_epi8(a0, b0, m1), c0, m0); - __m128i v1 = _mm_blendv_epi8(_mm_blendv_epi8(b0, c0, m1), a0, m0); - __m128i v2 = _mm_blendv_epi8(_mm_blendv_epi8(c0, a0, m1), b0, m0); -#elif CV_SSSE3 - const __m128i m0 = _mm_setr_epi8(0, 6, 11, 1, 7, 12, 2, 8, 13, 3, 9, 14, 4, 10, 15, 5); - const __m128i m1 = _mm_setr_epi8(5, 11, 0, 6, 12, 1, 7, 13, 2, 8, 14, 3, 9, 15, 4, 10); - const __m128i m2 = _mm_setr_epi8(10, 0, 5, 11, 1, 6, 12, 2, 7, 13, 3, 8, 14, 4, 9, 15); - - __m128i t0 = _mm_alignr_epi8(b.val, _mm_slli_si128(a.val, 10), 5); - t0 = _mm_alignr_epi8(c.val, t0, 5); - __m128i v0 = _mm_shuffle_epi8(t0, m0); - - __m128i t1 = _mm_alignr_epi8(_mm_srli_si128(b.val, 5), _mm_slli_si128(a.val, 5), 6); - t1 = _mm_alignr_epi8(_mm_srli_si128(c.val, 5), t1, 5); - __m128i v1 = _mm_shuffle_epi8(t1, m1); - - __m128i t2 = _mm_alignr_epi8(_mm_srli_si128(c.val, 10), b.val, 11); - t2 = _mm_alignr_epi8(t2, a.val, 11); - __m128i v2 = _mm_shuffle_epi8(t2, m2); -#else - __m128i z = _mm_setzero_si128(); - __m128i ab0 = _mm_unpacklo_epi8(a.val, b.val); - __m128i ab1 = _mm_unpackhi_epi8(a.val, b.val); - __m128i c0 = _mm_unpacklo_epi8(c.val, z); - __m128i c1 = _mm_unpackhi_epi8(c.val, z); - - __m128i p00 = _mm_unpacklo_epi16(ab0, c0); - __m128i p01 = _mm_unpackhi_epi16(ab0, c0); - __m128i p02 = _mm_unpacklo_epi16(ab1, c1); - __m128i p03 = _mm_unpackhi_epi16(ab1, c1); - - __m128i p10 = _mm_unpacklo_epi32(p00, p01); - __m128i p11 = _mm_unpackhi_epi32(p00, p01); - __m128i p12 = _mm_unpacklo_epi32(p02, p03); - __m128i p13 = _mm_unpackhi_epi32(p02, p03); - - __m128i p20 = _mm_unpacklo_epi64(p10, p11); - __m128i p21 = _mm_unpackhi_epi64(p10, p11); - __m128i p22 = _mm_unpacklo_epi64(p12, p13); - __m128i p23 = _mm_unpackhi_epi64(p12, p13); - - p20 = _mm_slli_si128(p20, 1); - p22 = _mm_slli_si128(p22, 1); - - __m128i p30 = _mm_slli_epi64(_mm_unpacklo_epi32(p20, p21), 8); - __m128i p31 = _mm_srli_epi64(_mm_unpackhi_epi32(p20, p21), 8); - __m128i p32 = _mm_slli_epi64(_mm_unpacklo_epi32(p22, p23), 8); - __m128i p33 = _mm_srli_epi64(_mm_unpackhi_epi32(p22, p23), 8); - - __m128i p40 = _mm_unpacklo_epi64(p30, p31); - __m128i p41 = _mm_unpackhi_epi64(p30, p31); - __m128i p42 = _mm_unpacklo_epi64(p32, p33); - __m128i p43 = _mm_unpackhi_epi64(p32, p33); - - __m128i v0 = _mm_or_si128(_mm_srli_si128(p40, 2), _mm_slli_si128(p41, 10)); - __m128i v1 = _mm_or_si128(_mm_srli_si128(p41, 6), _mm_slli_si128(p42, 6)); - __m128i v2 = _mm_or_si128(_mm_srli_si128(p42, 10), _mm_slli_si128(p43, 2)); -#endif - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_si128((__m128i*)(ptr), v0); - _mm_stream_si128((__m128i*)(ptr + 16), v1); - _mm_stream_si128((__m128i*)(ptr + 32), v2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_si128((__m128i*)(ptr), v0); - _mm_store_si128((__m128i*)(ptr + 16), v1); - _mm_store_si128((__m128i*)(ptr + 32), v2); - } - else - { - _mm_storeu_si128((__m128i*)(ptr), v0); - _mm_storeu_si128((__m128i*)(ptr + 16), v1); - _mm_storeu_si128((__m128i*)(ptr + 32), v2); - } -} - -inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, - const v_uint8x16& c, const v_uint8x16& d, - hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - // a0 a1 a2 a3 .... - // b0 b1 b2 b3 .... - // c0 c1 c2 c3 .... - // d0 d1 d2 d3 .... - __m128i u0 = _mm_unpacklo_epi8(a.val, c.val); // a0 c0 a1 c1 ... - __m128i u1 = _mm_unpackhi_epi8(a.val, c.val); // a8 c8 a9 c9 ... - __m128i u2 = _mm_unpacklo_epi8(b.val, d.val); // b0 d0 b1 d1 ... - __m128i u3 = _mm_unpackhi_epi8(b.val, d.val); // b8 d8 b9 d9 ... - - __m128i v0 = _mm_unpacklo_epi8(u0, u2); // a0 b0 c0 d0 ... - __m128i v1 = _mm_unpackhi_epi8(u0, u2); // a4 b4 c4 d4 ... - __m128i v2 = _mm_unpacklo_epi8(u1, u3); // a8 b8 c8 d8 ... - __m128i v3 = _mm_unpackhi_epi8(u1, u3); // a12 b12 c12 d12 ... - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_si128((__m128i*)(ptr), v0); - _mm_stream_si128((__m128i*)(ptr + 16), v1); - _mm_stream_si128((__m128i*)(ptr + 32), v2); - _mm_stream_si128((__m128i*)(ptr + 48), v3); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_si128((__m128i*)(ptr), v0); - _mm_store_si128((__m128i*)(ptr + 16), v1); - _mm_store_si128((__m128i*)(ptr + 32), v2); - _mm_store_si128((__m128i*)(ptr + 48), v3); - } - else - { - _mm_storeu_si128((__m128i*)(ptr), v0); - _mm_storeu_si128((__m128i*)(ptr + 16), v1); - _mm_storeu_si128((__m128i*)(ptr + 32), v2); - _mm_storeu_si128((__m128i*)(ptr + 48), v3); - } -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, - hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - __m128i v0 = _mm_unpacklo_epi16(a.val, b.val); - __m128i v1 = _mm_unpackhi_epi16(a.val, b.val); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_si128((__m128i*)(ptr), v0); - _mm_stream_si128((__m128i*)(ptr + 8), v1); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_si128((__m128i*)(ptr), v0); - _mm_store_si128((__m128i*)(ptr + 8), v1); - } - else - { - _mm_storeu_si128((__m128i*)(ptr), v0); - _mm_storeu_si128((__m128i*)(ptr + 8), v1); - } -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, - const v_uint16x8& b, const v_uint16x8& c, - hal::StoreMode mode = hal::STORE_UNALIGNED) -{ -#if CV_SSE4_1 - const __m128i sh_a = _mm_setr_epi8(0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11); - const __m128i sh_b = _mm_setr_epi8(10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5); - const __m128i sh_c = _mm_setr_epi8(4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15); - __m128i a0 = _mm_shuffle_epi8(a.val, sh_a); - __m128i b0 = _mm_shuffle_epi8(b.val, sh_b); - __m128i c0 = _mm_shuffle_epi8(c.val, sh_c); - - __m128i v0 = _mm_blend_epi16(_mm_blend_epi16(a0, b0, 0x92), c0, 0x24); - __m128i v1 = _mm_blend_epi16(_mm_blend_epi16(c0, a0, 0x92), b0, 0x24); - __m128i v2 = _mm_blend_epi16(_mm_blend_epi16(b0, c0, 0x92), a0, 0x24); -#else - __m128i z = _mm_setzero_si128(); - __m128i ab0 = _mm_unpacklo_epi16(a.val, b.val); - __m128i ab1 = _mm_unpackhi_epi16(a.val, b.val); - __m128i c0 = _mm_unpacklo_epi16(c.val, z); - __m128i c1 = _mm_unpackhi_epi16(c.val, z); - - __m128i p10 = _mm_unpacklo_epi32(ab0, c0); - __m128i p11 = _mm_unpackhi_epi32(ab0, c0); - __m128i p12 = _mm_unpacklo_epi32(ab1, c1); - __m128i p13 = _mm_unpackhi_epi32(ab1, c1); - - __m128i p20 = _mm_unpacklo_epi64(p10, p11); - __m128i p21 = _mm_unpackhi_epi64(p10, p11); - __m128i p22 = _mm_unpacklo_epi64(p12, p13); - __m128i p23 = _mm_unpackhi_epi64(p12, p13); - - p20 = _mm_slli_si128(p20, 2); - p22 = _mm_slli_si128(p22, 2); - - __m128i p30 = _mm_unpacklo_epi64(p20, p21); - __m128i p31 = _mm_unpackhi_epi64(p20, p21); - __m128i p32 = _mm_unpacklo_epi64(p22, p23); - __m128i p33 = _mm_unpackhi_epi64(p22, p23); - - __m128i v0 = _mm_or_si128(_mm_srli_si128(p30, 2), _mm_slli_si128(p31, 10)); - __m128i v1 = _mm_or_si128(_mm_srli_si128(p31, 6), _mm_slli_si128(p32, 6)); - __m128i v2 = _mm_or_si128(_mm_srli_si128(p32, 10), _mm_slli_si128(p33, 2)); -#endif - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_si128((__m128i*)(ptr), v0); - _mm_stream_si128((__m128i*)(ptr + 8), v1); - _mm_stream_si128((__m128i*)(ptr + 16), v2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_si128((__m128i*)(ptr), v0); - _mm_store_si128((__m128i*)(ptr + 8), v1); - _mm_store_si128((__m128i*)(ptr + 16), v2); - } - else - { - _mm_storeu_si128((__m128i*)(ptr), v0); - _mm_storeu_si128((__m128i*)(ptr + 8), v1); - _mm_storeu_si128((__m128i*)(ptr + 16), v2); - } -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, - const v_uint16x8& c, const v_uint16x8& d, - hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - // a0 a1 a2 a3 .... - // b0 b1 b2 b3 .... - // c0 c1 c2 c3 .... - // d0 d1 d2 d3 .... - __m128i u0 = _mm_unpacklo_epi16(a.val, c.val); // a0 c0 a1 c1 ... - __m128i u1 = _mm_unpackhi_epi16(a.val, c.val); // a4 c4 a5 c5 ... - __m128i u2 = _mm_unpacklo_epi16(b.val, d.val); // b0 d0 b1 d1 ... - __m128i u3 = _mm_unpackhi_epi16(b.val, d.val); // b4 d4 b5 d5 ... - - __m128i v0 = _mm_unpacklo_epi16(u0, u2); // a0 b0 c0 d0 ... - __m128i v1 = _mm_unpackhi_epi16(u0, u2); // a2 b2 c2 d2 ... - __m128i v2 = _mm_unpacklo_epi16(u1, u3); // a4 b4 c4 d4 ... - __m128i v3 = _mm_unpackhi_epi16(u1, u3); // a6 b6 c6 d6 ... - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_si128((__m128i*)(ptr), v0); - _mm_stream_si128((__m128i*)(ptr + 8), v1); - _mm_stream_si128((__m128i*)(ptr + 16), v2); - _mm_stream_si128((__m128i*)(ptr + 24), v3); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_si128((__m128i*)(ptr), v0); - _mm_store_si128((__m128i*)(ptr + 8), v1); - _mm_store_si128((__m128i*)(ptr + 16), v2); - _mm_store_si128((__m128i*)(ptr + 24), v3); - } - else - { - _mm_storeu_si128((__m128i*)(ptr), v0); - _mm_storeu_si128((__m128i*)(ptr + 8), v1); - _mm_storeu_si128((__m128i*)(ptr + 16), v2); - _mm_storeu_si128((__m128i*)(ptr + 24), v3); - } -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, - hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - __m128i v0 = _mm_unpacklo_epi32(a.val, b.val); - __m128i v1 = _mm_unpackhi_epi32(a.val, b.val); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_si128((__m128i*)(ptr), v0); - _mm_stream_si128((__m128i*)(ptr + 4), v1); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_si128((__m128i*)(ptr), v0); - _mm_store_si128((__m128i*)(ptr + 4), v1); - } - else - { - _mm_storeu_si128((__m128i*)(ptr), v0); - _mm_storeu_si128((__m128i*)(ptr + 4), v1); - } -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, - const v_uint32x4& c, hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - v_uint32x4 z = v_setzero_u32(), u0, u1, u2, u3; - v_transpose4x4(a, b, c, z, u0, u1, u2, u3); - - __m128i v0 = _mm_or_si128(u0.val, _mm_slli_si128(u1.val, 12)); - __m128i v1 = _mm_or_si128(_mm_srli_si128(u1.val, 4), _mm_slli_si128(u2.val, 8)); - __m128i v2 = _mm_or_si128(_mm_srli_si128(u2.val, 8), _mm_slli_si128(u3.val, 4)); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_si128((__m128i*)(ptr), v0); - _mm_stream_si128((__m128i*)(ptr + 4), v1); - _mm_stream_si128((__m128i*)(ptr + 8), v2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_si128((__m128i*)(ptr), v0); - _mm_store_si128((__m128i*)(ptr + 4), v1); - _mm_store_si128((__m128i*)(ptr + 8), v2); - } - else - { - _mm_storeu_si128((__m128i*)(ptr), v0); - _mm_storeu_si128((__m128i*)(ptr + 4), v1); - _mm_storeu_si128((__m128i*)(ptr + 8), v2); - } -} - -inline void v_store_interleave(unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, - const v_uint32x4& c, const v_uint32x4& d, - hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - v_uint32x4 v0, v1, v2, v3; - v_transpose4x4(a, b, c, d, v0, v1, v2, v3); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_si128((__m128i*)(ptr), v0.val); - _mm_stream_si128((__m128i*)(ptr + 4), v1.val); - _mm_stream_si128((__m128i*)(ptr + 8), v2.val); - _mm_stream_si128((__m128i*)(ptr + 12), v3.val); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_si128((__m128i*)(ptr), v0.val); - _mm_store_si128((__m128i*)(ptr + 4), v1.val); - _mm_store_si128((__m128i*)(ptr + 8), v2.val); - _mm_store_si128((__m128i*)(ptr + 12), v3.val); - } - else - { - _mm_storeu_si128((__m128i*)(ptr), v0.val); - _mm_storeu_si128((__m128i*)(ptr + 4), v1.val); - _mm_storeu_si128((__m128i*)(ptr + 8), v2.val); - _mm_storeu_si128((__m128i*)(ptr + 12), v3.val); - } -} - -// 2-channel, float only -inline void v_store_interleave(float* ptr, const v_float32x4& a, const v_float32x4& b, - hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - __m128 v0 = _mm_unpacklo_ps(a.val, b.val); // a0 b0 a1 b1 - __m128 v1 = _mm_unpackhi_ps(a.val, b.val); // a2 b2 a3 b3 - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_ps(ptr, v0); - _mm_stream_ps(ptr + 4, v1); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_ps(ptr, v0); - _mm_store_ps(ptr + 4, v1); - } - else - { - _mm_storeu_ps(ptr, v0); - _mm_storeu_ps(ptr + 4, v1); - } -} - -inline void v_store_interleave(float* ptr, const v_float32x4& a, const v_float32x4& b, - const v_float32x4& c, hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - __m128 u0 = _mm_shuffle_ps(a.val, b.val, _MM_SHUFFLE(0, 0, 0, 0)); - __m128 u1 = _mm_shuffle_ps(c.val, a.val, _MM_SHUFFLE(1, 1, 0, 0)); - __m128 v0 = _mm_shuffle_ps(u0, u1, _MM_SHUFFLE(2, 0, 2, 0)); - __m128 u2 = _mm_shuffle_ps(b.val, c.val, _MM_SHUFFLE(1, 1, 1, 1)); - __m128 u3 = _mm_shuffle_ps(a.val, b.val, _MM_SHUFFLE(2, 2, 2, 2)); - __m128 v1 = _mm_shuffle_ps(u2, u3, _MM_SHUFFLE(2, 0, 2, 0)); - __m128 u4 = _mm_shuffle_ps(c.val, a.val, _MM_SHUFFLE(3, 3, 2, 2)); - __m128 u5 = _mm_shuffle_ps(b.val, c.val, _MM_SHUFFLE(3, 3, 3, 3)); - __m128 v2 = _mm_shuffle_ps(u4, u5, _MM_SHUFFLE(2, 0, 2, 0)); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_ps(ptr, v0); - _mm_stream_ps(ptr + 4, v1); - _mm_stream_ps(ptr + 8, v2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_ps(ptr, v0); - _mm_store_ps(ptr + 4, v1); - _mm_store_ps(ptr + 8, v2); - } - else - { - _mm_storeu_ps(ptr, v0); - _mm_storeu_ps(ptr + 4, v1); - _mm_storeu_ps(ptr + 8, v2); - } -} - -inline void v_store_interleave(float* ptr, const v_float32x4& a, const v_float32x4& b, - const v_float32x4& c, const v_float32x4& d, - hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - __m128 u0 = _mm_unpacklo_ps(a.val, c.val); - __m128 u1 = _mm_unpacklo_ps(b.val, d.val); - __m128 u2 = _mm_unpackhi_ps(a.val, c.val); - __m128 u3 = _mm_unpackhi_ps(b.val, d.val); - __m128 v0 = _mm_unpacklo_ps(u0, u1); - __m128 v2 = _mm_unpacklo_ps(u2, u3); - __m128 v1 = _mm_unpackhi_ps(u0, u1); - __m128 v3 = _mm_unpackhi_ps(u2, u3); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_ps(ptr, v0); - _mm_stream_ps(ptr + 4, v1); - _mm_stream_ps(ptr + 8, v2); - _mm_stream_ps(ptr + 12, v3); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_ps(ptr, v0); - _mm_store_ps(ptr + 4, v1); - _mm_store_ps(ptr + 8, v2); - _mm_store_ps(ptr + 12, v3); - } - else - { - _mm_storeu_ps(ptr, v0); - _mm_storeu_ps(ptr + 4, v1); - _mm_storeu_ps(ptr + 8, v2); - _mm_storeu_ps(ptr + 12, v3); - } -} - -inline void v_store_interleave(uint64 *ptr, const v_uint64x2& a, const v_uint64x2& b, - hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - __m128i v0 = _mm_unpacklo_epi64(a.val, b.val); - __m128i v1 = _mm_unpackhi_epi64(a.val, b.val); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_si128((__m128i*)(ptr), v0); - _mm_stream_si128((__m128i*)(ptr + 2), v1); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_si128((__m128i*)(ptr), v0); - _mm_store_si128((__m128i*)(ptr + 2), v1); - } - else - { - _mm_storeu_si128((__m128i*)(ptr), v0); - _mm_storeu_si128((__m128i*)(ptr + 2), v1); - } -} - -inline void v_store_interleave(uint64 *ptr, const v_uint64x2& a, const v_uint64x2& b, - const v_uint64x2& c, hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - __m128i v0 = _mm_unpacklo_epi64(a.val, b.val); - __m128i v1 = _mm_unpacklo_epi64(c.val, _mm_unpackhi_epi64(a.val, a.val)); - __m128i v2 = _mm_unpackhi_epi64(b.val, c.val); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_si128((__m128i*)(ptr), v0); - _mm_stream_si128((__m128i*)(ptr + 2), v1); - _mm_stream_si128((__m128i*)(ptr + 4), v2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_si128((__m128i*)(ptr), v0); - _mm_store_si128((__m128i*)(ptr + 2), v1); - _mm_store_si128((__m128i*)(ptr + 4), v2); - } - else - { - _mm_storeu_si128((__m128i*)(ptr), v0); - _mm_storeu_si128((__m128i*)(ptr + 2), v1); - _mm_storeu_si128((__m128i*)(ptr + 4), v2); - } -} - -inline void v_store_interleave(uint64 *ptr, const v_uint64x2& a, const v_uint64x2& b, - const v_uint64x2& c, const v_uint64x2& d, - hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - __m128i v0 = _mm_unpacklo_epi64(a.val, b.val); - __m128i v1 = _mm_unpacklo_epi64(c.val, d.val); - __m128i v2 = _mm_unpackhi_epi64(a.val, b.val); - __m128i v3 = _mm_unpackhi_epi64(c.val, d.val); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_si128((__m128i*)(ptr), v0); - _mm_stream_si128((__m128i*)(ptr + 2), v1); - _mm_stream_si128((__m128i*)(ptr + 4), v2); - _mm_stream_si128((__m128i*)(ptr + 6), v3); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_si128((__m128i*)(ptr), v0); - _mm_store_si128((__m128i*)(ptr + 2), v1); - _mm_store_si128((__m128i*)(ptr + 4), v2); - _mm_store_si128((__m128i*)(ptr + 6), v3); - } - else - { - _mm_storeu_si128((__m128i*)(ptr), v0); - _mm_storeu_si128((__m128i*)(ptr + 2), v1); - _mm_storeu_si128((__m128i*)(ptr + 4), v2); - _mm_storeu_si128((__m128i*)(ptr + 6), v3); - } -} - -#define OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(_Tpvec0, _Tp0, suffix0, _Tpvec1, _Tp1, suffix1) \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0 ) \ -{ \ - _Tpvec1 a1, b1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ -} \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0 ) \ -{ \ - _Tpvec1 a1, b1, c1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ - c0 = v_reinterpret_as_##suffix0(c1); \ -} \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0, _Tpvec0& d0 ) \ -{ \ - _Tpvec1 a1, b1, c1, d1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1, d1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ - c0 = v_reinterpret_as_##suffix0(c1); \ - d0 = v_reinterpret_as_##suffix0(d1); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - hal::StoreMode mode = hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, mode); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - const _Tpvec0& c0, hal::StoreMode mode = hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, c1, mode); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - const _Tpvec0& c0, const _Tpvec0& d0, \ - hal::StoreMode mode = hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ - _Tpvec1 d1 = v_reinterpret_as_##suffix1(d0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, c1, d1, mode); \ -} - -OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(v_int8x16, schar, s8, v_uint8x16, uchar, u8) -OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(v_int16x8, short, s16, v_uint16x8, ushort, u16) -OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(v_int32x4, int, s32, v_uint32x4, unsigned, u32) -OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(v_int64x2, int64, s64, v_uint64x2, uint64, u64) -OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(v_float64x2, double, f64, v_uint64x2, uint64, u64) - -inline v_float32x4 v_cvt_f32(const v_int32x4& a) -{ - return v_float32x4(_mm_cvtepi32_ps(a.val)); -} - -inline v_float32x4 v_cvt_f32(const v_float64x2& a) -{ - return v_float32x4(_mm_cvtpd_ps(a.val)); -} - -inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) -{ - return v_float32x4(_mm_movelh_ps(_mm_cvtpd_ps(a.val), _mm_cvtpd_ps(b.val))); -} - -inline v_float64x2 v_cvt_f64(const v_int32x4& a) -{ - return v_float64x2(_mm_cvtepi32_pd(a.val)); -} - -inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) -{ - return v_float64x2(_mm_cvtepi32_pd(_mm_srli_si128(a.val,8))); -} - -inline v_float64x2 v_cvt_f64(const v_float32x4& a) -{ - return v_float64x2(_mm_cvtps_pd(a.val)); -} - -inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) -{ - return v_float64x2(_mm_cvtps_pd(_mm_movehl_ps(a.val, a.val))); -} - -// from (Mysticial and wim) https://stackoverflow.com/q/41144668 -inline v_float64x2 v_cvt_f64(const v_int64x2& v) -{ - // constants encoded as floating-point - __m128i magic_i_hi32 = _mm_set1_epi64x(0x4530000080000000); // 2^84 + 2^63 - __m128i magic_i_all = _mm_set1_epi64x(0x4530000080100000); // 2^84 + 2^63 + 2^52 - __m128d magic_d_all = _mm_castsi128_pd(magic_i_all); - // Blend the 32 lowest significant bits of v with magic_int_lo -#if CV_SSE4_1 - __m128i magic_i_lo = _mm_set1_epi64x(0x4330000000000000); // 2^52 - __m128i v_lo = _mm_blend_epi16(v.val, magic_i_lo, 0xcc); -#else - __m128i magic_i_lo = _mm_set1_epi32(0x43300000); // 2^52 - __m128i v_lo = _mm_unpacklo_epi32(_mm_shuffle_epi32(v.val, _MM_SHUFFLE(0, 0, 2, 0)), magic_i_lo); -#endif - // Extract the 32 most significant bits of v - __m128i v_hi = _mm_srli_epi64(v.val, 32); - // Flip the msb of v_hi and blend with 0x45300000 - v_hi = _mm_xor_si128(v_hi, magic_i_hi32); - // Compute in double precision - __m128d v_hi_dbl = _mm_sub_pd(_mm_castsi128_pd(v_hi), magic_d_all); - // (v_hi - magic_d_all) + v_lo Do not assume associativity of floating point addition - __m128d result = _mm_add_pd(v_hi_dbl, _mm_castsi128_pd(v_lo)); - return v_float64x2(result); -} - -////////////// Lookup table access //////////////////// - -inline v_int8x16 v_lut(const schar* tab, const int* idx) -{ -#if defined(_MSC_VER) - return v_int8x16(_mm_setr_epi8(tab[idx[0]], tab[idx[1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], tab[idx[ 5]], tab[idx[ 6]], tab[idx[ 7]], - tab[idx[8]], tab[idx[9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]])); -#else - return v_int8x16(_mm_setr_epi64( - _mm_setr_pi8(tab[idx[0]], tab[idx[1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], tab[idx[ 5]], tab[idx[ 6]], tab[idx[ 7]]), - _mm_setr_pi8(tab[idx[8]], tab[idx[9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]]) - )); -#endif -} -inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx) -{ -#if defined(_MSC_VER) - return v_int8x16(_mm_setr_epi16(*(const short*)(tab + idx[0]), *(const short*)(tab + idx[1]), *(const short*)(tab + idx[2]), *(const short*)(tab + idx[3]), - *(const short*)(tab + idx[4]), *(const short*)(tab + idx[5]), *(const short*)(tab + idx[6]), *(const short*)(tab + idx[7]))); -#else - return v_int8x16(_mm_setr_epi64( - _mm_setr_pi16(*(const short*)(tab + idx[0]), *(const short*)(tab + idx[1]), *(const short*)(tab + idx[2]), *(const short*)(tab + idx[3])), - _mm_setr_pi16(*(const short*)(tab + idx[4]), *(const short*)(tab + idx[5]), *(const short*)(tab + idx[6]), *(const short*)(tab + idx[7])) - )); -#endif -} -inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) -{ -#if defined(_MSC_VER) - return v_int8x16(_mm_setr_epi32(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), - *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]))); -#else - return v_int8x16(_mm_setr_epi64( - _mm_setr_pi32(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1])), - _mm_setr_pi32(*(const int*)(tab + idx[2]), *(const int*)(tab + idx[3])) - )); -#endif -} -inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((const schar *)tab, idx)); } -inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((const schar *)tab, idx)); } -inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((const schar *)tab, idx)); } - -inline v_int16x8 v_lut(const short* tab, const int* idx) -{ -#if defined(_MSC_VER) - return v_int16x8(_mm_setr_epi16(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], - tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]])); -#else - return v_int16x8(_mm_setr_epi64( - _mm_setr_pi16(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]), - _mm_setr_pi16(tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]]) - )); -#endif -} -inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) -{ -#if defined(_MSC_VER) - return v_int16x8(_mm_setr_epi32(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), - *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]))); -#else - return v_int16x8(_mm_setr_epi64( - _mm_setr_pi32(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1])), - _mm_setr_pi32(*(const int*)(tab + idx[2]), *(const int*)(tab + idx[3])) - )); -#endif -} -inline v_int16x8 v_lut_quads(const short* tab, const int* idx) -{ - return v_int16x8(_mm_set_epi64x(*(const int64_t*)(tab + idx[1]), *(const int64_t*)(tab + idx[0]))); -} -inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((const short *)tab, idx)); } -inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((const short *)tab, idx)); } -inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((const short *)tab, idx)); } - -inline v_int32x4 v_lut(const int* tab, const int* idx) -{ -#if defined(_MSC_VER) - return v_int32x4(_mm_setr_epi32(tab[idx[0]], tab[idx[1]], - tab[idx[2]], tab[idx[3]])); -#else - return v_int32x4(_mm_setr_epi64( - _mm_setr_pi32(tab[idx[0]], tab[idx[1]]), - _mm_setr_pi32(tab[idx[2]], tab[idx[3]]) - )); -#endif -} -inline v_int32x4 v_lut_pairs(const int* tab, const int* idx) -{ - return v_int32x4(_mm_set_epi64x(*(const int64_t*)(tab + idx[1]), *(const int64_t*)(tab + idx[0]))); -} -inline v_int32x4 v_lut_quads(const int* tab, const int* idx) -{ - return v_int32x4(_mm_loadu_si128((const __m128i*)(tab + idx[0]))); -} -inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((const int *)tab, idx)); } -inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((const int *)tab, idx)); } -inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((const int *)tab, idx)); } - -inline v_int64x2 v_lut(const int64_t* tab, const int* idx) -{ - return v_int64x2(_mm_set_epi64x(tab[idx[1]], tab[idx[0]])); -} -inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) -{ - return v_int64x2(_mm_loadu_si128((const __m128i*)(tab + idx[0]))); -} -inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } -inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } - -inline v_float32x4 v_lut(const float* tab, const int* idx) -{ - return v_float32x4(_mm_setr_ps(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]])); -} -inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) { return v_reinterpret_as_f32(v_lut_pairs((const int *)tab, idx)); } -inline v_float32x4 v_lut_quads(const float* tab, const int* idx) { return v_reinterpret_as_f32(v_lut_quads((const int *)tab, idx)); } - -inline v_float64x2 v_lut(const double* tab, const int* idx) -{ - return v_float64x2(_mm_setr_pd(tab[idx[0]], tab[idx[1]])); -} -inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) { return v_float64x2(_mm_castsi128_pd(_mm_loadu_si128((const __m128i*)(tab + idx[0])))); } - -inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) -{ - int CV_DECL_ALIGNED(32) idx[4]; - v_store_aligned(idx, idxvec); - return v_int32x4(_mm_setr_epi32(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]])); -} - -inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) -{ - return v_reinterpret_as_u32(v_lut((const int *)tab, idxvec)); -} - -inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) -{ - int CV_DECL_ALIGNED(32) idx[4]; - v_store_aligned(idx, idxvec); - return v_float32x4(_mm_setr_ps(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]])); -} - -inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) -{ - int idx[2]; - v_store_low(idx, idxvec); - return v_float64x2(_mm_setr_pd(tab[idx[0]], tab[idx[1]])); -} - -// loads pairs from the table and deinterleaves them, e.g. returns: -// x = (tab[idxvec[0], tab[idxvec[1]], tab[idxvec[2]], tab[idxvec[3]]), -// y = (tab[idxvec[0]+1], tab[idxvec[1]+1], tab[idxvec[2]+1], tab[idxvec[3]+1]) -// note that the indices are float's indices, not the float-pair indices. -// in theory, this function can be used to implement bilinear interpolation, -// when idxvec are the offsets within the image. -inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) -{ - int CV_DECL_ALIGNED(32) idx[4]; - v_store_aligned(idx, idxvec); - __m128 z = _mm_setzero_ps(); - __m128 xy01 = _mm_loadl_pi(z, (__m64*)(tab + idx[0])); - __m128 xy23 = _mm_loadl_pi(z, (__m64*)(tab + idx[2])); - xy01 = _mm_loadh_pi(xy01, (__m64*)(tab + idx[1])); - xy23 = _mm_loadh_pi(xy23, (__m64*)(tab + idx[3])); - __m128 xxyy02 = _mm_unpacklo_ps(xy01, xy23); - __m128 xxyy13 = _mm_unpackhi_ps(xy01, xy23); - x = v_float32x4(_mm_unpacklo_ps(xxyy02, xxyy13)); - y = v_float32x4(_mm_unpackhi_ps(xxyy02, xxyy13)); -} - -inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) -{ - int idx[2]; - v_store_low(idx, idxvec); - __m128d xy0 = _mm_loadu_pd(tab + idx[0]); - __m128d xy1 = _mm_loadu_pd(tab + idx[1]); - x = v_float64x2(_mm_unpacklo_pd(xy0, xy1)); - y = v_float64x2(_mm_unpackhi_pd(xy0, xy1)); -} - -inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) -{ -#if CV_SSSE3 - return v_int8x16(_mm_shuffle_epi8(vec.val, _mm_set_epi64x(0x0f0d0e0c0b090a08, 0x0705060403010200))); -#else - __m128i a = _mm_shufflelo_epi16(vec.val, _MM_SHUFFLE(3, 1, 2, 0)); - a = _mm_shufflehi_epi16(a, _MM_SHUFFLE(3, 1, 2, 0)); - a = _mm_shuffle_epi32(a, _MM_SHUFFLE(3, 1, 2, 0)); - return v_int8x16(_mm_unpacklo_epi8(a, _mm_unpackhi_epi64(a, a))); -#endif -} -inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } -inline v_int8x16 v_interleave_quads(const v_int8x16& vec) -{ -#if CV_SSSE3 - return v_int8x16(_mm_shuffle_epi8(vec.val, _mm_set_epi64x(0x0f0b0e0a0d090c08, 0x0703060205010400))); -#else - __m128i a = _mm_shuffle_epi32(vec.val, _MM_SHUFFLE(3, 1, 2, 0)); - return v_int8x16(_mm_unpacklo_epi8(a, _mm_unpackhi_epi64(a, a))); -#endif -} -inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) -{ -#if CV_SSSE3 - return v_int16x8(_mm_shuffle_epi8(vec.val, _mm_set_epi64x(0x0f0e0b0a0d0c0908, 0x0706030205040100))); -#else - __m128i a = _mm_shufflelo_epi16(vec.val, _MM_SHUFFLE(3, 1, 2, 0)); - return v_int16x8(_mm_shufflehi_epi16(a, _MM_SHUFFLE(3, 1, 2, 0))); -#endif -} -inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } -inline v_int16x8 v_interleave_quads(const v_int16x8& vec) -{ -#if CV_SSSE3 - return v_int16x8(_mm_shuffle_epi8(vec.val, _mm_set_epi64x(0x0f0e07060d0c0504, 0x0b0a030209080100))); -#else - return v_int16x8(_mm_unpacklo_epi16(vec.val, _mm_unpackhi_epi64(vec.val, vec.val))); -#endif -} -inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) -{ - return v_int32x4(_mm_shuffle_epi32(vec.val, _MM_SHUFFLE(3, 1, 2, 0))); -} -inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } -inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } - -inline v_int8x16 v_pack_triplets(const v_int8x16& vec) -{ -#if CV_SSSE3 - return v_int8x16(_mm_shuffle_epi8(vec.val, _mm_set_epi64x(0xffffff0f0e0d0c0a, 0x0908060504020100))); -#else - __m128i mask = _mm_set1_epi64x(0x00000000FFFFFFFF); - __m128i a = _mm_srli_si128(_mm_or_si128(_mm_andnot_si128(mask, vec.val), _mm_and_si128(mask, _mm_sll_epi32(vec.val, _mm_set_epi64x(0, 8)))), 1); - return v_int8x16(_mm_srli_si128(_mm_shufflelo_epi16(a, _MM_SHUFFLE(2, 1, 0, 3)), 2)); -#endif -} -inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_pack_triplets(const v_int16x8& vec) -{ -#if CV_SSSE3 - return v_int16x8(_mm_shuffle_epi8(vec.val, _mm_set_epi64x(0xffff0f0e0d0c0b0a, 0x0908050403020100))); -#else - return v_int16x8(_mm_srli_si128(_mm_shufflelo_epi16(vec.val, _MM_SHUFFLE(2, 1, 0, 3)), 2)); -#endif -} -inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } -inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } -inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } - -template -inline uchar v_extract_n(const v_uint8x16& v) -{ -#if CV_SSE4_1 - return (uchar)_mm_extract_epi8(v.val, i); -#else - return v_rotate_right(v).get0(); -#endif -} - -template -inline schar v_extract_n(const v_int8x16& v) -{ - return (schar)v_extract_n(v_reinterpret_as_u8(v)); -} - -template -inline ushort v_extract_n(const v_uint16x8& v) -{ - return (ushort)_mm_extract_epi16(v.val, i); -} - -template -inline short v_extract_n(const v_int16x8& v) -{ - return (short)v_extract_n(v_reinterpret_as_u16(v)); -} - -template -inline uint v_extract_n(const v_uint32x4& v) -{ -#if CV_SSE4_1 - return (uint)_mm_extract_epi32(v.val, i); -#else - return v_rotate_right(v).get0(); -#endif -} - -template -inline int v_extract_n(const v_int32x4& v) -{ - return (int)v_extract_n(v_reinterpret_as_u32(v)); -} - -template -inline uint64 v_extract_n(const v_uint64x2& v) -{ -#ifdef CV__SIMD_NATIVE_mm_extract_epi64 - return (uint64)_v128_extract_epi64(v.val); -#else - return v_rotate_right(v).get0(); -#endif -} - -template -inline int64 v_extract_n(const v_int64x2& v) -{ - return (int64)v_extract_n(v_reinterpret_as_u64(v)); -} - -template -inline float v_extract_n(const v_float32x4& v) -{ - union { uint iv; float fv; } d; - d.iv = v_extract_n(v_reinterpret_as_u32(v)); - return d.fv; -} - -template -inline double v_extract_n(const v_float64x2& v) -{ - union { uint64 iv; double dv; } d; - d.iv = v_extract_n(v_reinterpret_as_u64(v)); - return d.dv; -} - -template -inline v_int32x4 v_broadcast_element(const v_int32x4& v) -{ - return v_int32x4(_mm_shuffle_epi32(v.val, _MM_SHUFFLE(i,i,i,i))); -} - -template -inline v_uint32x4 v_broadcast_element(const v_uint32x4& v) -{ - return v_uint32x4(_mm_shuffle_epi32(v.val, _MM_SHUFFLE(i,i,i,i))); -} - -template -inline v_float32x4 v_broadcast_element(const v_float32x4& v) -{ - return v_float32x4(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE((char)i,(char)i,(char)i,(char)i))); -} - -////////////// FP16 support /////////////////////////// - -inline v_float32x4 v_load_expand(const hfloat* ptr) -{ -#if CV_FP16 - return v_float32x4(_mm_cvtph_ps(_mm_loadu_si128((const __m128i*)ptr))); -#else - const __m128i z = _mm_setzero_si128(), delta = _mm_set1_epi32(0x38000000); - const __m128i signmask = _mm_set1_epi32(0x80000000), maxexp = _mm_set1_epi32(0x7c000000); - const __m128 deltaf = _mm_castsi128_ps(_mm_set1_epi32(0x38800000)); - __m128i bits = _mm_unpacklo_epi16(z, _mm_loadl_epi64((const __m128i*)ptr)); // h << 16 - __m128i e = _mm_and_si128(bits, maxexp), sign = _mm_and_si128(bits, signmask); - __m128i t = _mm_add_epi32(_mm_srli_epi32(_mm_xor_si128(bits, sign), 3), delta); // ((h & 0x7fff) << 13) + delta - __m128i zt = _mm_castps_si128(_mm_sub_ps(_mm_castsi128_ps(_mm_add_epi32(t, _mm_set1_epi32(1 << 23))), deltaf)); - - t = _mm_add_epi32(t, _mm_and_si128(delta, _mm_cmpeq_epi32(maxexp, e))); - __m128i zmask = _mm_cmpeq_epi32(e, z); - __m128i ft = v_select_si128(zmask, zt, t); - return v_float32x4(_mm_castsi128_ps(_mm_or_si128(ft, sign))); -#endif -} - -inline void v_pack_store(hfloat* ptr, const v_float32x4& v) -{ -#if CV_FP16 - __m128i fp16_value = _mm_cvtps_ph(v.val, 0); - _mm_storel_epi64((__m128i*)ptr, fp16_value); -#else - const __m128i signmask = _mm_set1_epi32(0x80000000); - const __m128i rval = _mm_set1_epi32(0x3f000000); - - __m128i t = _mm_castps_si128(v.val); - __m128i sign = _mm_srai_epi32(_mm_and_si128(t, signmask), 16); - t = _mm_andnot_si128(signmask, t); - - __m128i finitemask = _mm_cmpgt_epi32(_mm_set1_epi32(0x47800000), t); - __m128i isnan = _mm_cmpgt_epi32(t, _mm_set1_epi32(0x7f800000)); - __m128i naninf = v_select_si128(isnan, _mm_set1_epi32(0x7e00), _mm_set1_epi32(0x7c00)); - __m128i tinymask = _mm_cmpgt_epi32(_mm_set1_epi32(0x38800000), t); - __m128i tt = _mm_castps_si128(_mm_add_ps(_mm_castsi128_ps(t), _mm_castsi128_ps(rval))); - tt = _mm_sub_epi32(tt, rval); - __m128i odd = _mm_and_si128(_mm_srli_epi32(t, 13), _mm_set1_epi32(1)); - __m128i nt = _mm_add_epi32(t, _mm_set1_epi32(0xc8000fff)); - nt = _mm_srli_epi32(_mm_add_epi32(nt, odd), 13); - t = v_select_si128(tinymask, tt, nt); - t = v_select_si128(finitemask, t, naninf); - t = _mm_or_si128(t, sign); - t = _mm_packs_epi32(t, t); - _mm_storel_epi64((__m128i*)ptr, t); -#endif -} - -inline void v_cleanup() {} - -#include "intrin_math.hpp" -inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } -inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } -inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } -inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } -inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } -inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } - -inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } -inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } -inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } -inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } -inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } - - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_HAL_SSE_HPP +#define OPENCV_HAL_SSE_HPP + +#include +#include "opencv2/core/utility.hpp" + +#define CV_SIMD128 1 +#define CV_SIMD128_64F 1 +#define CV_SIMD128_FP16 0 // no native operations with FP16 type. + +namespace cv +{ + +//! @cond IGNORED + +// +// Compilation troubleshooting: +// - MSVC: error C2719: 'a': formal parameter with requested alignment of 16 won't be aligned +// Replace parameter declaration to const reference: +// -v_int32x4 a +// +const v_int32x4& a +// + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +///////// Types //////////// + +struct v_uint8x16 +{ + typedef uchar lane_type; + typedef __m128i vector_type; + enum { nlanes = 16 }; + + /* coverity[uninit_ctor]: suppress warning */ + v_uint8x16() {} + explicit v_uint8x16(__m128i v) : val(v) {} + v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, + uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) + { + val = _mm_setr_epi8((char)v0, (char)v1, (char)v2, (char)v3, + (char)v4, (char)v5, (char)v6, (char)v7, + (char)v8, (char)v9, (char)v10, (char)v11, + (char)v12, (char)v13, (char)v14, (char)v15); + } + + uchar get0() const + { + return (uchar)_mm_cvtsi128_si32(val); + } + + __m128i val; +}; + +struct v_int8x16 +{ + typedef schar lane_type; + typedef __m128i vector_type; + enum { nlanes = 16 }; + + /* coverity[uninit_ctor]: suppress warning */ + v_int8x16() {} + explicit v_int8x16(__m128i v) : val(v) {} + v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, + schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) + { + val = _mm_setr_epi8((char)v0, (char)v1, (char)v2, (char)v3, + (char)v4, (char)v5, (char)v6, (char)v7, + (char)v8, (char)v9, (char)v10, (char)v11, + (char)v12, (char)v13, (char)v14, (char)v15); + } + + schar get0() const + { + return (schar)_mm_cvtsi128_si32(val); + } + + __m128i val; +}; + +struct v_uint16x8 +{ + typedef ushort lane_type; + typedef __m128i vector_type; + enum { nlanes = 8 }; + + /* coverity[uninit_ctor]: suppress warning */ + v_uint16x8() {} + explicit v_uint16x8(__m128i v) : val(v) {} + v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) + { + val = _mm_setr_epi16((short)v0, (short)v1, (short)v2, (short)v3, + (short)v4, (short)v5, (short)v6, (short)v7); + } + + ushort get0() const + { + return (ushort)_mm_cvtsi128_si32(val); + } + + __m128i val; +}; + +struct v_int16x8 +{ + typedef short lane_type; + typedef __m128i vector_type; + enum { nlanes = 8 }; + + /* coverity[uninit_ctor]: suppress warning */ + v_int16x8() {} + explicit v_int16x8(__m128i v) : val(v) {} + v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) + { + val = _mm_setr_epi16((short)v0, (short)v1, (short)v2, (short)v3, + (short)v4, (short)v5, (short)v6, (short)v7); + } + + short get0() const + { + return (short)_mm_cvtsi128_si32(val); + } + + __m128i val; +}; + +struct v_uint32x4 +{ + typedef unsigned lane_type; + typedef __m128i vector_type; + enum { nlanes = 4 }; + + /* coverity[uninit_ctor]: suppress warning */ + v_uint32x4() {} + explicit v_uint32x4(__m128i v) : val(v) {} + v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) + { + val = _mm_setr_epi32((int)v0, (int)v1, (int)v2, (int)v3); + } + + unsigned get0() const + { + return (unsigned)_mm_cvtsi128_si32(val); + } + + __m128i val; +}; + +struct v_int32x4 +{ + typedef int lane_type; + typedef __m128i vector_type; + enum { nlanes = 4 }; + + /* coverity[uninit_ctor]: suppress warning */ + v_int32x4() {} + explicit v_int32x4(__m128i v) : val(v) {} + v_int32x4(int v0, int v1, int v2, int v3) + { + val = _mm_setr_epi32(v0, v1, v2, v3); + } + + int get0() const + { + return _mm_cvtsi128_si32(val); + } + + __m128i val; +}; + +struct v_float32x4 +{ + typedef float lane_type; + typedef __m128 vector_type; + enum { nlanes = 4 }; + + /* coverity[uninit_ctor]: suppress warning */ + v_float32x4() {} + explicit v_float32x4(__m128 v) : val(v) {} + v_float32x4(float v0, float v1, float v2, float v3) + { + val = _mm_setr_ps(v0, v1, v2, v3); + } + + float get0() const + { + return _mm_cvtss_f32(val); + } + + __m128 val; +}; + +struct v_uint64x2 +{ + typedef uint64 lane_type; + typedef __m128i vector_type; + enum { nlanes = 2 }; + + /* coverity[uninit_ctor]: suppress warning */ + v_uint64x2() {} + explicit v_uint64x2(__m128i v) : val(v) {} + v_uint64x2(uint64 v0, uint64 v1) + { +#if defined(_MSC_VER) && _MSC_VER >= 1920/*MSVS 2019*/ && defined(_M_X64) && !defined(__clang__) + val = _mm_setr_epi64x((int64_t)v0, (int64_t)v1); +#elif defined(__GNUC__) + val = _mm_setr_epi64((__m64)v0, (__m64)v1); +#else + val = _mm_setr_epi32((int)v0, (int)(v0 >> 32), (int)v1, (int)(v1 >> 32)); +#endif + } + + uint64 get0() const + { + #if !defined(__x86_64__) && !defined(_M_X64) + int a = _mm_cvtsi128_si32(val); + int b = _mm_cvtsi128_si32(_mm_srli_epi64(val, 32)); + return (unsigned)a | ((uint64)(unsigned)b << 32); + #else + return (uint64)_mm_cvtsi128_si64(val); + #endif + } + + __m128i val; +}; + +struct v_int64x2 +{ + typedef int64 lane_type; + typedef __m128i vector_type; + enum { nlanes = 2 }; + + /* coverity[uninit_ctor]: suppress warning */ + v_int64x2() {} + explicit v_int64x2(__m128i v) : val(v) {} + v_int64x2(int64 v0, int64 v1) + { +#if defined(_MSC_VER) && _MSC_VER >= 1920/*MSVS 2019*/ && defined(_M_X64) && !defined(__clang__) + val = _mm_setr_epi64x((int64_t)v0, (int64_t)v1); +#elif defined(__GNUC__) + val = _mm_setr_epi64((__m64)v0, (__m64)v1); +#else + val = _mm_setr_epi32((int)v0, (int)(v0 >> 32), (int)v1, (int)(v1 >> 32)); +#endif + } + + int64 get0() const + { + #if !defined(__x86_64__) && !defined(_M_X64) + int a = _mm_cvtsi128_si32(val); + int b = _mm_cvtsi128_si32(_mm_srli_epi64(val, 32)); + return (int64)((unsigned)a | ((uint64)(unsigned)b << 32)); + #else + return _mm_cvtsi128_si64(val); + #endif + } + + __m128i val; +}; + +struct v_float64x2 +{ + typedef double lane_type; + typedef __m128d vector_type; + enum { nlanes = 2 }; + + /* coverity[uninit_ctor]: suppress warning */ + v_float64x2() {} + explicit v_float64x2(__m128d v) : val(v) {} + v_float64x2(double v0, double v1) + { + val = _mm_setr_pd(v0, v1); + } + + double get0() const + { + return _mm_cvtsd_f64(val); + } + + __m128d val; +}; + +namespace hal_sse_internal +{ + template + to_sse_type v_sse_reinterpret_as(const from_sse_type& val); + +#define OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(to_sse_type, from_sse_type, sse_cast_intrin) \ + template<> inline \ + to_sse_type v_sse_reinterpret_as(const from_sse_type& a) \ + { return sse_cast_intrin(a); } + + OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128i, __m128i, OPENCV_HAL_NOP) + OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128i, __m128, _mm_castps_si128) + OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128i, __m128d, _mm_castpd_si128) + OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128, __m128i, _mm_castsi128_ps) + OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128, __m128, OPENCV_HAL_NOP) + OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128, __m128d, _mm_castpd_ps) + OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128d, __m128i, _mm_castsi128_pd) + OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128d, __m128, _mm_castps_pd) + OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128d, __m128d, OPENCV_HAL_NOP) +} + +#define OPENCV_HAL_IMPL_SSE_INITVEC(_Tpvec, _Tp, suffix, zsuffix, ssuffix, _Tps, cast) \ +inline _Tpvec v_setzero_##suffix() { return _Tpvec(_mm_setzero_##zsuffix()); } \ +inline _Tpvec v_setall_##suffix(_Tp v) { return _Tpvec(_mm_set1_##ssuffix((_Tps)v)); } \ +template <> inline _Tpvec v_setzero_() { return v_setzero_##suffix(); } \ +template <> inline _Tpvec v_setall_(_Tp v) { return v_setall_##suffix(v); } \ +template inline _Tpvec v_reinterpret_as_##suffix(const _Tpvec0& a) \ +{ return _Tpvec(cast(a.val)); } + +OPENCV_HAL_IMPL_SSE_INITVEC(v_uint8x16, uchar, u8, si128, epi8, schar, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_INITVEC(v_int8x16, schar, s8, si128, epi8, schar, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_INITVEC(v_uint16x8, ushort, u16, si128, epi16, short, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_INITVEC(v_int16x8, short, s16, si128, epi16, short, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_INITVEC(v_uint32x4, unsigned, u32, si128, epi32, int, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_INITVEC(v_int32x4, int, s32, si128, epi32, int, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_INITVEC(v_float32x4, float, f32, ps, ps, float, _mm_castsi128_ps) +OPENCV_HAL_IMPL_SSE_INITVEC(v_float64x2, double, f64, pd, pd, double, _mm_castsi128_pd) + +inline v_uint64x2 v_setzero_u64() { return v_uint64x2(_mm_setzero_si128()); } +inline v_int64x2 v_setzero_s64() { return v_int64x2(_mm_setzero_si128()); } +inline v_uint64x2 v_setall_u64(uint64 val) { return v_uint64x2(val, val); } +inline v_int64x2 v_setall_s64(int64 val) { return v_int64x2(val, val); } + +template <> inline v_uint64x2 v_setzero_() { return v_setzero_u64(); } +template <> inline v_int64x2 v_setzero_() { return v_setzero_s64(); } +template <> inline v_uint64x2 v_setall_(uint64 val) { return v_setall_u64(val); } +template <> inline v_int64x2 v_setall_(int64 val) { return v_setall_s64(val); } + +template inline +v_uint64x2 v_reinterpret_as_u64(const _Tpvec& a) { return v_uint64x2(a.val); } +template inline +v_int64x2 v_reinterpret_as_s64(const _Tpvec& a) { return v_int64x2(a.val); } +inline v_float32x4 v_reinterpret_as_f32(const v_uint64x2& a) +{ return v_float32x4(_mm_castsi128_ps(a.val)); } +inline v_float32x4 v_reinterpret_as_f32(const v_int64x2& a) +{ return v_float32x4(_mm_castsi128_ps(a.val)); } +inline v_float64x2 v_reinterpret_as_f64(const v_uint64x2& a) +{ return v_float64x2(_mm_castsi128_pd(a.val)); } +inline v_float64x2 v_reinterpret_as_f64(const v_int64x2& a) +{ return v_float64x2(_mm_castsi128_pd(a.val)); } + +#define OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(_Tpvec, suffix) \ +inline _Tpvec v_reinterpret_as_##suffix(const v_float32x4& a) \ +{ return _Tpvec(_mm_castps_si128(a.val)); } \ +inline _Tpvec v_reinterpret_as_##suffix(const v_float64x2& a) \ +{ return _Tpvec(_mm_castpd_si128(a.val)); } + +OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_uint8x16, u8) +OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_int8x16, s8) +OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_uint16x8, u16) +OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_int16x8, s16) +OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_uint32x4, u32) +OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_int32x4, s32) +OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_uint64x2, u64) +OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_int64x2, s64) + +inline v_float32x4 v_reinterpret_as_f32(const v_float32x4& a) {return a; } +inline v_float64x2 v_reinterpret_as_f64(const v_float64x2& a) {return a; } +inline v_float32x4 v_reinterpret_as_f32(const v_float64x2& a) {return v_float32x4(_mm_castpd_ps(a.val)); } +inline v_float64x2 v_reinterpret_as_f64(const v_float32x4& a) {return v_float64x2(_mm_castps_pd(a.val)); } + +//////////////// PACK /////////////// +inline v_uint8x16 v_pack(const v_uint16x8& a, const v_uint16x8& b) +{ + __m128i delta = _mm_set1_epi16(255); + return v_uint8x16(_mm_packus_epi16(_mm_subs_epu16(a.val, _mm_subs_epu16(a.val, delta)), + _mm_subs_epu16(b.val, _mm_subs_epu16(b.val, delta)))); +} + +inline void v_pack_store(uchar* ptr, const v_uint16x8& a) +{ + __m128i delta = _mm_set1_epi16(255); + __m128i a1 = _mm_subs_epu16(a.val, _mm_subs_epu16(a.val, delta)); + _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi16(a1, a1)); +} + +inline v_uint8x16 v_pack_u(const v_int16x8& a, const v_int16x8& b) +{ return v_uint8x16(_mm_packus_epi16(a.val, b.val)); } + +inline void v_pack_u_store(uchar* ptr, const v_int16x8& a) +{ _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi16(a.val, a.val)); } + +template inline +v_uint8x16 v_rshr_pack(const v_uint16x8& a, const v_uint16x8& b) +{ + // we assume that n > 0, and so the shifted 16-bit values can be treated as signed numbers. + __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); + return v_uint8x16(_mm_packus_epi16(_mm_srli_epi16(_mm_adds_epu16(a.val, delta), n), + _mm_srli_epi16(_mm_adds_epu16(b.val, delta), n))); +} + +template inline +void v_rshr_pack_store(uchar* ptr, const v_uint16x8& a) +{ + __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); + __m128i a1 = _mm_srli_epi16(_mm_adds_epu16(a.val, delta), n); + _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi16(a1, a1)); +} + +template inline +v_uint8x16 v_rshr_pack_u(const v_int16x8& a, const v_int16x8& b) +{ + __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); + return v_uint8x16(_mm_packus_epi16(_mm_srai_epi16(_mm_adds_epi16(a.val, delta), n), + _mm_srai_epi16(_mm_adds_epi16(b.val, delta), n))); +} + +template inline +void v_rshr_pack_u_store(uchar* ptr, const v_int16x8& a) +{ + __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); + __m128i a1 = _mm_srai_epi16(_mm_adds_epi16(a.val, delta), n); + _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi16(a1, a1)); +} + +inline v_int8x16 v_pack(const v_int16x8& a, const v_int16x8& b) +{ return v_int8x16(_mm_packs_epi16(a.val, b.val)); } + +inline void v_pack_store(schar* ptr, const v_int16x8& a) +{ _mm_storel_epi64((__m128i*)ptr, _mm_packs_epi16(a.val, a.val)); } + +template inline +v_int8x16 v_rshr_pack(const v_int16x8& a, const v_int16x8& b) +{ + // we assume that n > 0, and so the shifted 16-bit values can be treated as signed numbers. + __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); + return v_int8x16(_mm_packs_epi16(_mm_srai_epi16(_mm_adds_epi16(a.val, delta), n), + _mm_srai_epi16(_mm_adds_epi16(b.val, delta), n))); +} +template inline +void v_rshr_pack_store(schar* ptr, const v_int16x8& a) +{ + // we assume that n > 0, and so the shifted 16-bit values can be treated as signed numbers. + __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); + __m128i a1 = _mm_srai_epi16(_mm_adds_epi16(a.val, delta), n); + _mm_storel_epi64((__m128i*)ptr, _mm_packs_epi16(a1, a1)); +} + + +// byte-wise "mask ? a : b" +inline __m128i v_select_si128(__m128i mask, __m128i a, __m128i b) +{ +#if CV_SSE4_1 + return _mm_blendv_epi8(b, a, mask); +#else + return _mm_xor_si128(b, _mm_and_si128(_mm_xor_si128(a, b), mask)); +#endif +} + +inline v_uint16x8 v_pack(const v_uint32x4& a, const v_uint32x4& b) +{ return v_uint16x8(_v128_packs_epu32(a.val, b.val)); } + +inline void v_pack_store(ushort* ptr, const v_uint32x4& a) +{ + __m128i z = _mm_setzero_si128(), maxval32 = _mm_set1_epi32(65535), delta32 = _mm_set1_epi32(32768); + __m128i a1 = _mm_sub_epi32(v_select_si128(_mm_cmpgt_epi32(z, a.val), maxval32, a.val), delta32); + __m128i r = _mm_packs_epi32(a1, a1); + _mm_storel_epi64((__m128i*)ptr, _mm_sub_epi16(r, _mm_set1_epi16(-32768))); +} + +template inline +v_uint16x8 v_rshr_pack(const v_uint32x4& a, const v_uint32x4& b) +{ + __m128i delta = _mm_set1_epi32(1 << (n-1)), delta32 = _mm_set1_epi32(32768); + __m128i a1 = _mm_sub_epi32(_mm_srli_epi32(_mm_add_epi32(a.val, delta), n), delta32); + __m128i b1 = _mm_sub_epi32(_mm_srli_epi32(_mm_add_epi32(b.val, delta), n), delta32); + return v_uint16x8(_mm_sub_epi16(_mm_packs_epi32(a1, b1), _mm_set1_epi16(-32768))); +} + +template inline +void v_rshr_pack_store(ushort* ptr, const v_uint32x4& a) +{ + __m128i delta = _mm_set1_epi32(1 << (n-1)), delta32 = _mm_set1_epi32(32768); + __m128i a1 = _mm_sub_epi32(_mm_srli_epi32(_mm_add_epi32(a.val, delta), n), delta32); + __m128i a2 = _mm_sub_epi16(_mm_packs_epi32(a1, a1), _mm_set1_epi16(-32768)); + _mm_storel_epi64((__m128i*)ptr, a2); +} + +inline v_uint16x8 v_pack_u(const v_int32x4& a, const v_int32x4& b) +{ +#if CV_SSE4_1 + return v_uint16x8(_mm_packus_epi32(a.val, b.val)); +#else + __m128i delta32 = _mm_set1_epi32(32768); + + // preliminary saturate negative values to zero + __m128i a1 = _mm_and_si128(a.val, _mm_cmpgt_epi32(a.val, _mm_set1_epi32(0))); + __m128i b1 = _mm_and_si128(b.val, _mm_cmpgt_epi32(b.val, _mm_set1_epi32(0))); + + __m128i r = _mm_packs_epi32(_mm_sub_epi32(a1, delta32), _mm_sub_epi32(b1, delta32)); + return v_uint16x8(_mm_sub_epi16(r, _mm_set1_epi16(-32768))); +#endif +} + +inline void v_pack_u_store(ushort* ptr, const v_int32x4& a) +{ +#if CV_SSE4_1 + _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi32(a.val, a.val)); +#else + __m128i delta32 = _mm_set1_epi32(32768); + __m128i a1 = _mm_sub_epi32(a.val, delta32); + __m128i r = _mm_sub_epi16(_mm_packs_epi32(a1, a1), _mm_set1_epi16(-32768)); + _mm_storel_epi64((__m128i*)ptr, r); +#endif +} + +template inline +v_uint16x8 v_rshr_pack_u(const v_int32x4& a, const v_int32x4& b) +{ +#if CV_SSE4_1 + __m128i delta = _mm_set1_epi32(1 << (n - 1)); + return v_uint16x8(_mm_packus_epi32(_mm_srai_epi32(_mm_add_epi32(a.val, delta), n), + _mm_srai_epi32(_mm_add_epi32(b.val, delta), n))); +#else + __m128i delta = _mm_set1_epi32(1 << (n-1)), delta32 = _mm_set1_epi32(32768); + __m128i a1 = _mm_sub_epi32(_mm_srai_epi32(_mm_add_epi32(a.val, delta), n), delta32); + __m128i a2 = _mm_sub_epi16(_mm_packs_epi32(a1, a1), _mm_set1_epi16(-32768)); + __m128i b1 = _mm_sub_epi32(_mm_srai_epi32(_mm_add_epi32(b.val, delta), n), delta32); + __m128i b2 = _mm_sub_epi16(_mm_packs_epi32(b1, b1), _mm_set1_epi16(-32768)); + return v_uint16x8(_mm_unpacklo_epi64(a2, b2)); +#endif +} + +template inline +void v_rshr_pack_u_store(ushort* ptr, const v_int32x4& a) +{ +#if CV_SSE4_1 + __m128i delta = _mm_set1_epi32(1 << (n - 1)); + __m128i a1 = _mm_srai_epi32(_mm_add_epi32(a.val, delta), n); + _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi32(a1, a1)); +#else + __m128i delta = _mm_set1_epi32(1 << (n-1)), delta32 = _mm_set1_epi32(32768); + __m128i a1 = _mm_sub_epi32(_mm_srai_epi32(_mm_add_epi32(a.val, delta), n), delta32); + __m128i a2 = _mm_sub_epi16(_mm_packs_epi32(a1, a1), _mm_set1_epi16(-32768)); + _mm_storel_epi64((__m128i*)ptr, a2); +#endif +} + +inline v_int16x8 v_pack(const v_int32x4& a, const v_int32x4& b) +{ return v_int16x8(_mm_packs_epi32(a.val, b.val)); } + +inline void v_pack_store(short* ptr, const v_int32x4& a) +{ + _mm_storel_epi64((__m128i*)ptr, _mm_packs_epi32(a.val, a.val)); +} + +template inline +v_int16x8 v_rshr_pack(const v_int32x4& a, const v_int32x4& b) +{ + __m128i delta = _mm_set1_epi32(1 << (n-1)); + return v_int16x8(_mm_packs_epi32(_mm_srai_epi32(_mm_add_epi32(a.val, delta), n), + _mm_srai_epi32(_mm_add_epi32(b.val, delta), n))); +} + +template inline +void v_rshr_pack_store(short* ptr, const v_int32x4& a) +{ + __m128i delta = _mm_set1_epi32(1 << (n-1)); + __m128i a1 = _mm_srai_epi32(_mm_add_epi32(a.val, delta), n); + _mm_storel_epi64((__m128i*)ptr, _mm_packs_epi32(a1, a1)); +} + + +// [a0 0 | b0 0] [a1 0 | b1 0] +inline v_uint32x4 v_pack(const v_uint64x2& a, const v_uint64x2& b) +{ + __m128i v0 = _mm_unpacklo_epi32(a.val, b.val); // a0 a1 0 0 + __m128i v1 = _mm_unpackhi_epi32(a.val, b.val); // b0 b1 0 0 + return v_uint32x4(_mm_unpacklo_epi32(v0, v1)); +} + +inline void v_pack_store(unsigned* ptr, const v_uint64x2& a) +{ + __m128i a1 = _mm_shuffle_epi32(a.val, _MM_SHUFFLE(0, 2, 2, 0)); + _mm_storel_epi64((__m128i*)ptr, a1); +} + +// [a0 0 | b0 0] [a1 0 | b1 0] +inline v_int32x4 v_pack(const v_int64x2& a, const v_int64x2& b) +{ + __m128i v0 = _mm_unpacklo_epi32(a.val, b.val); // a0 a1 0 0 + __m128i v1 = _mm_unpackhi_epi32(a.val, b.val); // b0 b1 0 0 + return v_int32x4(_mm_unpacklo_epi32(v0, v1)); +} + +inline void v_pack_store(int* ptr, const v_int64x2& a) +{ + __m128i a1 = _mm_shuffle_epi32(a.val, _MM_SHUFFLE(0, 2, 2, 0)); + _mm_storel_epi64((__m128i*)ptr, a1); +} + +template inline +v_uint32x4 v_rshr_pack(const v_uint64x2& a, const v_uint64x2& b) +{ + uint64 delta = (uint64)1 << (n-1); + v_uint64x2 delta2(delta, delta); + __m128i a1 = _mm_srli_epi64(_mm_add_epi64(a.val, delta2.val), n); + __m128i b1 = _mm_srli_epi64(_mm_add_epi64(b.val, delta2.val), n); + __m128i v0 = _mm_unpacklo_epi32(a1, b1); // a0 a1 0 0 + __m128i v1 = _mm_unpackhi_epi32(a1, b1); // b0 b1 0 0 + return v_uint32x4(_mm_unpacklo_epi32(v0, v1)); +} + +template inline +void v_rshr_pack_store(unsigned* ptr, const v_uint64x2& a) +{ + uint64 delta = (uint64)1 << (n-1); + v_uint64x2 delta2(delta, delta); + __m128i a1 = _mm_srli_epi64(_mm_add_epi64(a.val, delta2.val), n); + __m128i a2 = _mm_shuffle_epi32(a1, _MM_SHUFFLE(0, 2, 2, 0)); + _mm_storel_epi64((__m128i*)ptr, a2); +} + +inline __m128i v_sign_epi64(__m128i a) +{ + return _mm_shuffle_epi32(_mm_srai_epi32(a, 31), _MM_SHUFFLE(3, 3, 1, 1)); // x m0 | x m1 +} + +inline __m128i v_srai_epi64(__m128i a, int imm) +{ + __m128i smask = v_sign_epi64(a); + return _mm_xor_si128(_mm_srli_epi64(_mm_xor_si128(a, smask), imm), smask); +} + +template inline +v_int32x4 v_rshr_pack(const v_int64x2& a, const v_int64x2& b) +{ + int64 delta = (int64)1 << (n-1); + v_int64x2 delta2(delta, delta); + __m128i a1 = v_srai_epi64(_mm_add_epi64(a.val, delta2.val), n); + __m128i b1 = v_srai_epi64(_mm_add_epi64(b.val, delta2.val), n); + __m128i v0 = _mm_unpacklo_epi32(a1, b1); // a0 a1 0 0 + __m128i v1 = _mm_unpackhi_epi32(a1, b1); // b0 b1 0 0 + return v_int32x4(_mm_unpacklo_epi32(v0, v1)); +} + +template inline +void v_rshr_pack_store(int* ptr, const v_int64x2& a) +{ + int64 delta = (int64)1 << (n-1); + v_int64x2 delta2(delta, delta); + __m128i a1 = v_srai_epi64(_mm_add_epi64(a.val, delta2.val), n); + __m128i a2 = _mm_shuffle_epi32(a1, _MM_SHUFFLE(0, 2, 2, 0)); + _mm_storel_epi64((__m128i*)ptr, a2); +} + +// pack boolean +inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) +{ + __m128i ab = _mm_packs_epi16(a.val, b.val); + return v_uint8x16(ab); +} + +inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, + const v_uint32x4& c, const v_uint32x4& d) +{ + __m128i ab = _mm_packs_epi32(a.val, b.val); + __m128i cd = _mm_packs_epi32(c.val, d.val); + return v_uint8x16(_mm_packs_epi16(ab, cd)); +} + +inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, + const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, + const v_uint64x2& g, const v_uint64x2& h) +{ + __m128i ab = _mm_packs_epi32(a.val, b.val); + __m128i cd = _mm_packs_epi32(c.val, d.val); + __m128i ef = _mm_packs_epi32(e.val, f.val); + __m128i gh = _mm_packs_epi32(g.val, h.val); + + __m128i abcd = _mm_packs_epi32(ab, cd); + __m128i efgh = _mm_packs_epi32(ef, gh); + return v_uint8x16(_mm_packs_epi16(abcd, efgh)); +} + +inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, + const v_float32x4& m3) +{ + __m128 v0 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(0, 0, 0, 0)), m0.val); + __m128 v1 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(1, 1, 1, 1)), m1.val); + __m128 v2 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(2, 2, 2, 2)), m2.val); + __m128 v3 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(3, 3, 3, 3)), m3.val); + + return v_float32x4(_mm_add_ps(_mm_add_ps(v0, v1), _mm_add_ps(v2, v3))); +} + +inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, + const v_float32x4& a) +{ + __m128 v0 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(0, 0, 0, 0)), m0.val); + __m128 v1 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(1, 1, 1, 1)), m1.val); + __m128 v2 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(2, 2, 2, 2)), m2.val); + + return v_float32x4(_mm_add_ps(_mm_add_ps(v0, v1), _mm_add_ps(v2, a.val))); +} + +#define OPENCV_HAL_IMPL_SSE_BIN_OP(bin_op, _Tpvec, intrin) \ + inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ + { \ + return _Tpvec(intrin(a.val, b.val)); \ + } + +OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_uint8x16, _mm_adds_epu8) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_uint8x16, _mm_subs_epu8) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_int8x16, _mm_adds_epi8) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_int8x16, _mm_subs_epi8) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_uint16x8, _mm_adds_epu16) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_uint16x8, _mm_subs_epu16) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_int16x8, _mm_adds_epi16) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_int16x8, _mm_subs_epi16) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_uint32x4, _mm_add_epi32) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_uint32x4, _mm_sub_epi32) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_mul, v_uint32x4, _v128_mullo_epi32) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_int32x4, _mm_add_epi32) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_int32x4, _mm_sub_epi32) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_mul, v_int32x4, _v128_mullo_epi32) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_float32x4, _mm_add_ps) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_float32x4, _mm_sub_ps) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_mul, v_float32x4, _mm_mul_ps) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_div, v_float32x4, _mm_div_ps) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_float64x2, _mm_add_pd) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_float64x2, _mm_sub_pd) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_mul, v_float64x2, _mm_mul_pd) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_div, v_float64x2, _mm_div_pd) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_uint64x2, _mm_add_epi64) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_uint64x2, _mm_sub_epi64) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_int64x2, _mm_add_epi64) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_int64x2, _mm_sub_epi64) + +// saturating multiply 8-bit, 16-bit +#define OPENCV_HAL_IMPL_SSE_MUL_SAT(_Tpvec, _Tpwvec) \ + inline _Tpvec v_mul(const _Tpvec& a, const _Tpvec& b) \ + { \ + _Tpwvec c, d; \ + v_mul_expand(a, b, c, d); \ + return v_pack(c, d); \ + } + +OPENCV_HAL_IMPL_SSE_MUL_SAT(v_uint8x16, v_uint16x8) +OPENCV_HAL_IMPL_SSE_MUL_SAT(v_int8x16, v_int16x8) +OPENCV_HAL_IMPL_SSE_MUL_SAT(v_uint16x8, v_uint32x4) +OPENCV_HAL_IMPL_SSE_MUL_SAT(v_int16x8, v_int32x4) + +// Multiply and expand +inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b, + v_uint16x8& c, v_uint16x8& d) +{ + v_uint16x8 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c = v_mul_wrap(a0, b0); + d = v_mul_wrap(a1, b1); +} + +inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b, + v_int16x8& c, v_int16x8& d) +{ + v_int16x8 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c = v_mul_wrap(a0, b0); + d = v_mul_wrap(a1, b1); +} + +inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, + v_int32x4& c, v_int32x4& d) +{ + __m128i v0 = _mm_mullo_epi16(a.val, b.val); + __m128i v1 = _mm_mulhi_epi16(a.val, b.val); + c.val = _mm_unpacklo_epi16(v0, v1); + d.val = _mm_unpackhi_epi16(v0, v1); +} + +inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, + v_uint32x4& c, v_uint32x4& d) +{ + __m128i v0 = _mm_mullo_epi16(a.val, b.val); + __m128i v1 = _mm_mulhi_epu16(a.val, b.val); + c.val = _mm_unpacklo_epi16(v0, v1); + d.val = _mm_unpackhi_epi16(v0, v1); +} + +inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, + v_uint64x2& c, v_uint64x2& d) +{ + __m128i c0 = _mm_mul_epu32(a.val, b.val); + __m128i c1 = _mm_mul_epu32(_mm_srli_epi64(a.val, 32), _mm_srli_epi64(b.val, 32)); + c.val = _mm_unpacklo_epi64(c0, c1); + d.val = _mm_unpackhi_epi64(c0, c1); +} + +inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) { return v_int16x8(_mm_mulhi_epi16(a.val, b.val)); } +inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) { return v_uint16x8(_mm_mulhi_epu16(a.val, b.val)); } + +//////// Dot Product //////// + +// 16 >> 32 +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) +{ return v_int32x4(_mm_madd_epi16(a.val, b.val)); } +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ return v_add(v_dotprod(a, b), c); } + +// 32 >> 64 +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) +{ +#if CV_SSE4_1 + __m128i even = _mm_mul_epi32(a.val, b.val); + __m128i odd = _mm_mul_epi32(_mm_srli_epi64(a.val, 32), _mm_srli_epi64(b.val, 32)); + return v_int64x2(_mm_add_epi64(even, odd)); +#else + __m128i even_u = _mm_mul_epu32(a.val, b.val); + __m128i odd_u = _mm_mul_epu32(_mm_srli_epi64(a.val, 32), _mm_srli_epi64(b.val, 32)); + // convert unsigned to signed high multiplication (from: Agner Fog(veclib) and H S Warren: Hacker's delight, 2003, p. 132) + __m128i a_sign = _mm_srai_epi32(a.val, 31); + __m128i b_sign = _mm_srai_epi32(b.val, 31); + // |x * sign of x + __m128i axb = _mm_and_si128(a.val, b_sign); + __m128i bxa = _mm_and_si128(b.val, a_sign); + // sum of sign corrections + __m128i ssum = _mm_add_epi32(bxa, axb); + __m128i even_ssum = _mm_slli_epi64(ssum, 32); + __m128i odd_ssum = _mm_and_si128(ssum, _mm_set_epi32(-1, 0, -1, 0)); + // convert to signed and prod + return v_int64x2(_mm_add_epi64(_mm_sub_epi64(even_u, even_ssum), _mm_sub_epi64(odd_u, odd_ssum))); +#endif +} +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ return v_add(v_dotprod(a, b), c); } + +// 8 >> 32 +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) +{ + __m128i a0 = _mm_srli_epi16(_mm_slli_si128(a.val, 1), 8); // even + __m128i a1 = _mm_srli_epi16(a.val, 8); // odd + __m128i b0 = _mm_srli_epi16(_mm_slli_si128(b.val, 1), 8); + __m128i b1 = _mm_srli_epi16(b.val, 8); + __m128i p0 = _mm_madd_epi16(a0, b0); + __m128i p1 = _mm_madd_epi16(a1, b1); + return v_uint32x4(_mm_add_epi32(p0, p1)); +} +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) +{ + __m128i a0 = _mm_srai_epi16(_mm_slli_si128(a.val, 1), 8); // even + __m128i a1 = _mm_srai_epi16(a.val, 8); // odd + __m128i b0 = _mm_srai_epi16(_mm_slli_si128(b.val, 1), 8); + __m128i b1 = _mm_srai_epi16(b.val, 8); + __m128i p0 = _mm_madd_epi16(a0, b0); + __m128i p1 = _mm_madd_epi16(a1, b1); + return v_int32x4(_mm_add_epi32(p0, p1)); +} +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) +{ + v_uint32x4 c, d; + v_mul_expand(a, b, c, d); + + v_uint64x2 c0, c1, d0, d1; + v_expand(c, c0, c1); + v_expand(d, d0, d1); + + c0 = v_add(c0, c1); d0 = v_add(d0, d1); + return v_uint64x2(_mm_add_epi64( + _mm_unpacklo_epi64(c0.val, d0.val), + _mm_unpackhi_epi64(c0.val, d0.val) + )); +} +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) +{ + v_int32x4 prod = v_dotprod(a, b); + v_int64x2 c, d; + v_expand(prod, c, d); + return v_int64x2(_mm_add_epi64( + _mm_unpacklo_epi64(c.val, d.val), + _mm_unpackhi_epi64(c.val, d.val) + )); +} +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 32 >> 64f +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) +{ +#if CV_SSE4_1 + return v_cvt_f64(v_dotprod(a, b)); +#else + v_float64x2 c = v_mul(v_cvt_f64(a), v_cvt_f64(b)); + v_float64x2 d = v_mul(v_cvt_f64_high(a), v_cvt_f64_high(b)); + + return v_float64x2(_mm_add_pd( + _mm_unpacklo_pd(c.val, d.val), + _mm_unpackhi_pd(c.val, d.val) + )); +#endif +} +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +//////// Fast Dot Product //////// + +// 16 >> 32 +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) +{ return v_dotprod(a, b); } +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ return v_add(v_dotprod(a, b), c); } + +// 32 >> 64 +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) +{ return v_dotprod(a, b); } +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ return v_add(v_dotprod_fast(a, b), c); } + +// 8 >> 32 +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) +{ + __m128i a0 = v_expand_low(a).val; + __m128i a1 = v_expand_high(a).val; + __m128i b0 = v_expand_low(b).val; + __m128i b1 = v_expand_high(b).val; + __m128i p0 = _mm_madd_epi16(a0, b0); + __m128i p1 = _mm_madd_epi16(a1, b1); + return v_uint32x4(_mm_add_epi32(p0, p1)); +} +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) +{ +#if CV_SSE4_1 + __m128i a0 = _mm_cvtepi8_epi16(a.val); + __m128i a1 = v_expand_high(a).val; + __m128i b0 = _mm_cvtepi8_epi16(b.val); + __m128i b1 = v_expand_high(b).val; + __m128i p0 = _mm_madd_epi16(a0, b0); + __m128i p1 = _mm_madd_epi16(a1, b1); + return v_int32x4(_mm_add_epi32(p0, p1)); +#else + return v_dotprod_expand(a, b); +#endif +} +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) +{ + v_uint32x4 c, d; + v_mul_expand(a, b, c, d); + + v_uint64x2 c0, c1, d0, d1; + v_expand(c, c0, c1); + v_expand(d, d0, d1); + + c0 = v_add(c0, c1); d0 = v_add(d0, d1); + return v_add(c0, d0); +} +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) +{ + v_int32x4 prod = v_dotprod(a, b); + v_int64x2 c, d; + v_expand(prod, c, d); + return v_add(c, d); +} +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +// 32 >> 64f +v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c); +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) +{ return v_fma(v_cvt_f64(a), v_cvt_f64(b), v_mul(v_cvt_f64_high(a), v_cvt_f64_high(b))); } +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) +{ return v_fma(v_cvt_f64(a), v_cvt_f64(b), v_fma(v_cvt_f64_high(a), v_cvt_f64_high(b), c)); } + +#define OPENCV_HAL_IMPL_SSE_LOGIC_OP(_Tpvec, suffix, not_const) \ + OPENCV_HAL_IMPL_SSE_BIN_OP(v_and, _Tpvec, _mm_and_##suffix) \ + OPENCV_HAL_IMPL_SSE_BIN_OP(v_or, _Tpvec, _mm_or_##suffix) \ + OPENCV_HAL_IMPL_SSE_BIN_OP(v_xor, _Tpvec, _mm_xor_##suffix) \ + inline _Tpvec v_not(const _Tpvec& a) \ + { \ + return _Tpvec(_mm_xor_##suffix(a.val, not_const)); \ + } + +OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_uint8x16, si128, _mm_set1_epi32(-1)) +OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_int8x16, si128, _mm_set1_epi32(-1)) +OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_uint16x8, si128, _mm_set1_epi32(-1)) +OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_int16x8, si128, _mm_set1_epi32(-1)) +OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_uint32x4, si128, _mm_set1_epi32(-1)) +OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_int32x4, si128, _mm_set1_epi32(-1)) +OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_uint64x2, si128, _mm_set1_epi32(-1)) +OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_int64x2, si128, _mm_set1_epi32(-1)) +OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_float32x4, ps, _mm_castsi128_ps(_mm_set1_epi32(-1))) +OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_float64x2, pd, _mm_castsi128_pd(_mm_set1_epi32(-1))) + +inline v_float32x4 v_sqrt(const v_float32x4& x) +{ return v_float32x4(_mm_sqrt_ps(x.val)); } + +inline v_float32x4 v_invsqrt(const v_float32x4& x) +{ + const __m128 _0_5 = _mm_set1_ps(0.5f), _1_5 = _mm_set1_ps(1.5f); + __m128 t = x.val; + __m128 h = _mm_mul_ps(t, _0_5); + t = _mm_rsqrt_ps(t); + t = _mm_mul_ps(t, _mm_sub_ps(_1_5, _mm_mul_ps(_mm_mul_ps(t, t), h))); + return v_float32x4(t); +} + +inline v_float64x2 v_sqrt(const v_float64x2& x) +{ return v_float64x2(_mm_sqrt_pd(x.val)); } + +inline v_float64x2 v_invsqrt(const v_float64x2& x) +{ + const __m128d v_1 = _mm_set1_pd(1.); + return v_float64x2(_mm_div_pd(v_1, _mm_sqrt_pd(x.val))); +} + +#define OPENCV_HAL_IMPL_SSE_ABS_INT_FUNC(_Tpuvec, _Tpsvec, func, suffix, subWidth) \ +inline _Tpuvec v_abs(const _Tpsvec& x) \ +{ return _Tpuvec(_mm_##func##_ep##suffix(x.val, _mm_sub_ep##subWidth(_mm_setzero_si128(), x.val))); } + +OPENCV_HAL_IMPL_SSE_ABS_INT_FUNC(v_uint8x16, v_int8x16, min, u8, i8) +OPENCV_HAL_IMPL_SSE_ABS_INT_FUNC(v_uint16x8, v_int16x8, max, i16, i16) +inline v_uint32x4 v_abs(const v_int32x4& x) +{ + __m128i s = _mm_srli_epi32(x.val, 31); + __m128i f = _mm_srai_epi32(x.val, 31); + return v_uint32x4(_mm_add_epi32(_mm_xor_si128(x.val, f), s)); +} +inline v_float32x4 v_abs(const v_float32x4& x) +{ return v_float32x4(_mm_and_ps(x.val, _mm_castsi128_ps(_mm_set1_epi32(0x7fffffff)))); } +inline v_float64x2 v_abs(const v_float64x2& x) +{ + return v_float64x2(_mm_and_pd(x.val, + _mm_castsi128_pd(_mm_srli_epi64(_mm_set1_epi32(-1), 1)))); +} + +// TODO: exp, log, sin, cos + +#define OPENCV_HAL_IMPL_SSE_BIN_FUNC(_Tpvec, func, intrin) \ +inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(intrin(a.val, b.val)); \ +} + +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint8x16, v_min, _mm_min_epu8) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint8x16, v_max, _mm_max_epu8) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int16x8, v_min, _mm_min_epi16) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int16x8, v_max, _mm_max_epi16) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_float32x4, v_min, _mm_min_ps) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_float32x4, v_max, _mm_max_ps) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_float64x2, v_min, _mm_min_pd) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_float64x2, v_max, _mm_max_pd) + +inline v_int8x16 v_min(const v_int8x16& a, const v_int8x16& b) +{ +#if CV_SSE4_1 + return v_int8x16(_mm_min_epi8(a.val, b.val)); +#else + __m128i delta = _mm_set1_epi8((char)-128); + return v_int8x16(_mm_xor_si128(delta, _mm_min_epu8(_mm_xor_si128(a.val, delta), + _mm_xor_si128(b.val, delta)))); +#endif +} +inline v_int8x16 v_max(const v_int8x16& a, const v_int8x16& b) +{ +#if CV_SSE4_1 + return v_int8x16(_mm_max_epi8(a.val, b.val)); +#else + __m128i delta = _mm_set1_epi8((char)-128); + return v_int8x16(_mm_xor_si128(delta, _mm_max_epu8(_mm_xor_si128(a.val, delta), + _mm_xor_si128(b.val, delta)))); +#endif +} +inline v_uint16x8 v_min(const v_uint16x8& a, const v_uint16x8& b) +{ +#if CV_SSE4_1 + return v_uint16x8(_mm_min_epu16(a.val, b.val)); +#else + return v_uint16x8(_mm_subs_epu16(a.val, _mm_subs_epu16(a.val, b.val))); +#endif +} +inline v_uint16x8 v_max(const v_uint16x8& a, const v_uint16x8& b) +{ +#if CV_SSE4_1 + return v_uint16x8(_mm_max_epu16(a.val, b.val)); +#else + return v_uint16x8(_mm_adds_epu16(_mm_subs_epu16(a.val, b.val), b.val)); +#endif +} +inline v_uint32x4 v_min(const v_uint32x4& a, const v_uint32x4& b) +{ +#if CV_SSE4_1 + return v_uint32x4(_mm_min_epu32(a.val, b.val)); +#else + __m128i delta = _mm_set1_epi32((int)0x80000000); + __m128i mask = _mm_cmpgt_epi32(_mm_xor_si128(a.val, delta), _mm_xor_si128(b.val, delta)); + return v_uint32x4(v_select_si128(mask, b.val, a.val)); +#endif +} +inline v_uint32x4 v_max(const v_uint32x4& a, const v_uint32x4& b) +{ +#if CV_SSE4_1 + return v_uint32x4(_mm_max_epu32(a.val, b.val)); +#else + __m128i delta = _mm_set1_epi32((int)0x80000000); + __m128i mask = _mm_cmpgt_epi32(_mm_xor_si128(a.val, delta), _mm_xor_si128(b.val, delta)); + return v_uint32x4(v_select_si128(mask, a.val, b.val)); +#endif +} +inline v_int32x4 v_min(const v_int32x4& a, const v_int32x4& b) +{ +#if CV_SSE4_1 + return v_int32x4(_mm_min_epi32(a.val, b.val)); +#else + return v_int32x4(v_select_si128(_mm_cmpgt_epi32(a.val, b.val), b.val, a.val)); +#endif +} +inline v_int32x4 v_max(const v_int32x4& a, const v_int32x4& b) +{ +#if CV_SSE4_1 + return v_int32x4(_mm_max_epi32(a.val, b.val)); +#else + return v_int32x4(v_select_si128(_mm_cmpgt_epi32(a.val, b.val), a.val, b.val)); +#endif +} + +#define OPENCV_HAL_IMPL_SSE_INT_CMP_OP(_Tpuvec, _Tpsvec, suffix, sbit) \ +inline _Tpuvec v_eq(const _Tpuvec& a, const _Tpuvec& b) \ +{ return _Tpuvec(_mm_cmpeq_##suffix(a.val, b.val)); } \ +inline _Tpuvec v_ne(const _Tpuvec& a, const _Tpuvec& b) \ +{ \ + __m128i not_mask = _mm_set1_epi32(-1); \ + return _Tpuvec(_mm_xor_si128(_mm_cmpeq_##suffix(a.val, b.val), not_mask)); \ +} \ +inline _Tpsvec v_eq(const _Tpsvec& a, const _Tpsvec& b) \ +{ return _Tpsvec(_mm_cmpeq_##suffix(a.val, b.val)); } \ +inline _Tpsvec v_ne(const _Tpsvec& a, const _Tpsvec& b) \ +{ \ + __m128i not_mask = _mm_set1_epi32(-1); \ + return _Tpsvec(_mm_xor_si128(_mm_cmpeq_##suffix(a.val, b.val), not_mask)); \ +} \ +inline _Tpuvec v_lt(const _Tpuvec& a, const _Tpuvec& b) \ +{ \ + __m128i smask = _mm_set1_##suffix(sbit); \ + return _Tpuvec(_mm_cmpgt_##suffix(_mm_xor_si128(b.val, smask), _mm_xor_si128(a.val, smask))); \ +} \ +inline _Tpuvec v_gt(const _Tpuvec& a, const _Tpuvec& b) \ +{ \ + __m128i smask = _mm_set1_##suffix(sbit); \ + return _Tpuvec(_mm_cmpgt_##suffix(_mm_xor_si128(a.val, smask), _mm_xor_si128(b.val, smask))); \ +} \ +inline _Tpuvec v_le(const _Tpuvec& a, const _Tpuvec& b) \ +{ \ + __m128i smask = _mm_set1_##suffix(sbit); \ + __m128i not_mask = _mm_set1_epi32(-1); \ + __m128i res = _mm_cmpgt_##suffix(_mm_xor_si128(a.val, smask), _mm_xor_si128(b.val, smask)); \ + return _Tpuvec(_mm_xor_si128(res, not_mask)); \ +} \ +inline _Tpuvec v_ge(const _Tpuvec& a, const _Tpuvec& b) \ +{ \ + __m128i smask = _mm_set1_##suffix(sbit); \ + __m128i not_mask = _mm_set1_epi32(-1); \ + __m128i res = _mm_cmpgt_##suffix(_mm_xor_si128(b.val, smask), _mm_xor_si128(a.val, smask)); \ + return _Tpuvec(_mm_xor_si128(res, not_mask)); \ +} \ +inline _Tpsvec v_lt(const _Tpsvec& a, const _Tpsvec& b) \ +{ \ + return _Tpsvec(_mm_cmpgt_##suffix(b.val, a.val)); \ +} \ +inline _Tpsvec v_gt(const _Tpsvec& a, const _Tpsvec& b) \ +{ \ + return _Tpsvec(_mm_cmpgt_##suffix(a.val, b.val)); \ +} \ +inline _Tpsvec v_le(const _Tpsvec& a, const _Tpsvec& b) \ +{ \ + __m128i not_mask = _mm_set1_epi32(-1); \ + return _Tpsvec(_mm_xor_si128(_mm_cmpgt_##suffix(a.val, b.val), not_mask)); \ +} \ +inline _Tpsvec v_ge(const _Tpsvec& a, const _Tpsvec& b) \ +{ \ + __m128i not_mask = _mm_set1_epi32(-1); \ + return _Tpsvec(_mm_xor_si128(_mm_cmpgt_##suffix(b.val, a.val), not_mask)); \ +} + +OPENCV_HAL_IMPL_SSE_INT_CMP_OP(v_uint8x16, v_int8x16, epi8, (char)-128) +OPENCV_HAL_IMPL_SSE_INT_CMP_OP(v_uint16x8, v_int16x8, epi16, (short)-32768) +OPENCV_HAL_IMPL_SSE_INT_CMP_OP(v_uint32x4, v_int32x4, epi32, (int)0x80000000) + +#define OPENCV_HAL_IMPL_SSE_FLT_CMP_OP(_Tpvec, suffix) \ +inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(_mm_cmpeq_##suffix(a.val, b.val)); } \ +inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(_mm_cmpneq_##suffix(a.val, b.val)); } \ +inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(_mm_cmplt_##suffix(a.val, b.val)); } \ +inline _Tpvec v_gt(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(_mm_cmpgt_##suffix(a.val, b.val)); } \ +inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(_mm_cmple_##suffix(a.val, b.val)); } \ +inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(_mm_cmpge_##suffix(a.val, b.val)); } + +OPENCV_HAL_IMPL_SSE_FLT_CMP_OP(v_float32x4, ps) +OPENCV_HAL_IMPL_SSE_FLT_CMP_OP(v_float64x2, pd) + +#if CV_SSE4_1 +#define OPENCV_HAL_IMPL_SSE_64BIT_CMP_OP(_Tpvec) \ +inline _Tpvec v_eq (const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(_mm_cmpeq_epi64(a.val, b.val)); } \ +inline _Tpvec v_ne (const _Tpvec& a, const _Tpvec& b) \ +{ return v_not(v_eq(a, b)); } +#else +#define OPENCV_HAL_IMPL_SSE_64BIT_CMP_OP(_Tpvec) \ +inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ +{ __m128i cmp = _mm_cmpeq_epi32(a.val, b.val); \ + return _Tpvec(_mm_and_si128(cmp, _mm_shuffle_epi32(cmp, _MM_SHUFFLE(2, 3, 0, 1)))); } \ +inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ +{ return v_not(v_eq(a, b)); } +#endif + +OPENCV_HAL_IMPL_SSE_64BIT_CMP_OP(v_uint64x2) +OPENCV_HAL_IMPL_SSE_64BIT_CMP_OP(v_int64x2) + +inline v_float32x4 v_not_nan(const v_float32x4& a) +{ return v_float32x4(_mm_cmpord_ps(a.val, a.val)); } +inline v_float64x2 v_not_nan(const v_float64x2& a) +{ return v_float64x2(_mm_cmpord_pd(a.val, a.val)); } + +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint8x16, v_add_wrap, _mm_add_epi8) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int8x16, v_add_wrap, _mm_add_epi8) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint16x8, v_add_wrap, _mm_add_epi16) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int16x8, v_add_wrap, _mm_add_epi16) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint8x16, v_sub_wrap, _mm_sub_epi8) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int8x16, v_sub_wrap, _mm_sub_epi8) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint16x8, v_sub_wrap, _mm_sub_epi16) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int16x8, v_sub_wrap, _mm_sub_epi16) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint16x8, v_mul_wrap, _mm_mullo_epi16) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int16x8, v_mul_wrap, _mm_mullo_epi16) + +inline v_uint8x16 v_mul_wrap(const v_uint8x16& a, const v_uint8x16& b) +{ + __m128i ad = _mm_srai_epi16(a.val, 8); + __m128i bd = _mm_srai_epi16(b.val, 8); + __m128i p0 = _mm_mullo_epi16(a.val, b.val); // even + __m128i p1 = _mm_slli_epi16(_mm_mullo_epi16(ad, bd), 8); // odd + const __m128i b01 = _mm_set1_epi32(0xFF00FF00); + return v_uint8x16(_v128_blendv_epi8(p0, p1, b01)); +} +inline v_int8x16 v_mul_wrap(const v_int8x16& a, const v_int8x16& b) +{ + return v_reinterpret_as_s8(v_mul_wrap(v_reinterpret_as_u8(a), v_reinterpret_as_u8(b))); +} + +/** Absolute difference **/ + +inline v_uint8x16 v_absdiff(const v_uint8x16& a, const v_uint8x16& b) +{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } +inline v_uint16x8 v_absdiff(const v_uint16x8& a, const v_uint16x8& b) +{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } +inline v_uint32x4 v_absdiff(const v_uint32x4& a, const v_uint32x4& b) +{ return v_sub(v_max(a, b), v_min(a, b)); } + +inline v_uint8x16 v_absdiff(const v_int8x16& a, const v_int8x16& b) +{ + v_int8x16 d = v_sub_wrap(a, b); + v_int8x16 m = v_lt(a, b); + return v_reinterpret_as_u8(v_sub_wrap(v_xor(d, m), m)); +} +inline v_uint16x8 v_absdiff(const v_int16x8& a, const v_int16x8& b) +{ + return v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))); +} +inline v_uint32x4 v_absdiff(const v_int32x4& a, const v_int32x4& b) +{ + v_int32x4 d = v_sub(a, b); + v_int32x4 m = v_lt(a, b); + return v_reinterpret_as_u32(v_sub(v_xor(d, m), m)); +} + +/** Saturating absolute difference **/ +inline v_int8x16 v_absdiffs(const v_int8x16& a, const v_int8x16& b) +{ + v_int8x16 d = v_sub(a, b); + v_int8x16 m = v_lt(a, b); + return v_sub(v_xor(d, m), m); + } +inline v_int16x8 v_absdiffs(const v_int16x8& a, const v_int16x8& b) +{ return v_sub(v_max(a, b), v_min(a, b)); } + + +inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ + return v_add(v_mul(a, b), c); +} + +inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ + return v_fma(a, b, c); +} + +inline v_float32x4 v_fma(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) +{ +#if CV_FMA3 + return v_float32x4(_mm_fmadd_ps(a.val, b.val, c.val)); +#else + return v_float32x4(_mm_add_ps(_mm_mul_ps(a.val, b.val), c.val)); +#endif +} + +inline v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) +{ +#if CV_FMA3 + return v_float64x2(_mm_fmadd_pd(a.val, b.val, c.val)); +#else + return v_float64x2(_mm_add_pd(_mm_mul_pd(a.val, b.val), c.val)); +#endif +} + +#define OPENCV_HAL_IMPL_SSE_MISC_FLT_OP(_Tpvec, _Tp, _Tpreg, suffix, absmask_vec) \ +inline _Tpvec v_absdiff(const _Tpvec& a, const _Tpvec& b) \ +{ \ + _Tpreg absmask = _mm_castsi128_##suffix(absmask_vec); \ + return _Tpvec(_mm_and_##suffix(_mm_sub_##suffix(a.val, b.val), absmask)); \ +} \ +inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ +{ \ + _Tpvec res = v_fma(a, a, v_mul(b, b)); \ + return _Tpvec(_mm_sqrt_##suffix(res.val)); \ +} \ +inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return v_fma(a, a, v_mul(b, b)); \ +} \ +inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ +{ \ + return v_fma(a, b, c); \ +} + +OPENCV_HAL_IMPL_SSE_MISC_FLT_OP(v_float32x4, float, __m128, ps, _mm_set1_epi32((int)0x7fffffff)) +OPENCV_HAL_IMPL_SSE_MISC_FLT_OP(v_float64x2, double, __m128d, pd, _mm_srli_epi64(_mm_set1_epi32(-1), 1)) + +#define OPENCV_HAL_IMPL_SSE_SHIFT_OP(_Tpuvec, _Tpsvec, suffix, srai) \ +inline _Tpuvec v_shl(const _Tpuvec& a, int imm) \ +{ \ + return _Tpuvec(_mm_slli_##suffix(a.val, imm)); \ +} \ +inline _Tpsvec v_shl(const _Tpsvec& a, int imm) \ +{ \ + return _Tpsvec(_mm_slli_##suffix(a.val, imm)); \ +} \ +inline _Tpuvec v_shr(const _Tpuvec& a, int imm) \ +{ \ + return _Tpuvec(_mm_srli_##suffix(a.val, imm)); \ +} \ +inline _Tpsvec v_shr(const _Tpsvec& a, int imm) \ +{ \ + return _Tpsvec(srai(a.val, imm)); \ +} \ +template \ +inline _Tpuvec v_shl(const _Tpuvec& a) \ +{ \ + return _Tpuvec(_mm_slli_##suffix(a.val, imm)); \ +} \ +template \ +inline _Tpsvec v_shl(const _Tpsvec& a) \ +{ \ + return _Tpsvec(_mm_slli_##suffix(a.val, imm)); \ +} \ +template \ +inline _Tpuvec v_shr(const _Tpuvec& a) \ +{ \ + return _Tpuvec(_mm_srli_##suffix(a.val, imm)); \ +} \ +template \ +inline _Tpsvec v_shr(const _Tpsvec& a) \ +{ \ + return _Tpsvec(srai(a.val, imm)); \ +} + +OPENCV_HAL_IMPL_SSE_SHIFT_OP(v_uint16x8, v_int16x8, epi16, _mm_srai_epi16) +OPENCV_HAL_IMPL_SSE_SHIFT_OP(v_uint32x4, v_int32x4, epi32, _mm_srai_epi32) +OPENCV_HAL_IMPL_SSE_SHIFT_OP(v_uint64x2, v_int64x2, epi64, v_srai_epi64) + +namespace hal_sse_internal +{ + template 16)), + bool is_first = (imm == 0), + bool is_half = (imm == 8), + bool is_second = (imm == 16), + bool is_other = (((imm > 0) && (imm < 8)) || ((imm > 8) && (imm < 16)))> + class v_sse_palignr_u8_class; + + template + class v_sse_palignr_u8_class; + + template + class v_sse_palignr_u8_class + { + public: + inline __m128i operator()(const __m128i& a, const __m128i&) const + { + return a; + } + }; + + template + class v_sse_palignr_u8_class + { + public: + inline __m128i operator()(const __m128i& a, const __m128i& b) const + { + return _mm_unpacklo_epi64(_mm_unpackhi_epi64(a, a), b); + } + }; + + template + class v_sse_palignr_u8_class + { + public: + inline __m128i operator()(const __m128i&, const __m128i& b) const + { + return b; + } + }; + + template + class v_sse_palignr_u8_class + { +#if CV_SSSE3 + public: + inline __m128i operator()(const __m128i& a, const __m128i& b) const + { + return _mm_alignr_epi8(b, a, imm); + } +#else + public: + inline __m128i operator()(const __m128i& a, const __m128i& b) const + { + enum { imm2 = (sizeof(__m128i) - imm) }; + return _mm_or_si128(_mm_srli_si128(a, imm), _mm_slli_si128(b, imm2)); + } +#endif + }; + + template + inline __m128i v_sse_palignr_u8(const __m128i& a, const __m128i& b) + { + CV_StaticAssert((imm >= 0) && (imm <= 16), "Invalid imm for v_sse_palignr_u8."); + return v_sse_palignr_u8_class()(a, b); + } +} + +template +inline _Tpvec v_rotate_right(const _Tpvec &a) +{ + using namespace hal_sse_internal; + enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type)) }; + return _Tpvec(v_sse_reinterpret_as( + _mm_srli_si128( + v_sse_reinterpret_as<__m128i>(a.val), imm2))); +} + +template +inline _Tpvec v_rotate_left(const _Tpvec &a) +{ + using namespace hal_sse_internal; + enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type)) }; + return _Tpvec(v_sse_reinterpret_as( + _mm_slli_si128( + v_sse_reinterpret_as<__m128i>(a.val), imm2))); +} + +template +inline _Tpvec v_rotate_right(const _Tpvec &a, const _Tpvec &b) +{ + using namespace hal_sse_internal; + enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type)) }; + return _Tpvec(v_sse_reinterpret_as( + v_sse_palignr_u8( + v_sse_reinterpret_as<__m128i>(a.val), + v_sse_reinterpret_as<__m128i>(b.val)))); +} + +template +inline _Tpvec v_rotate_left(const _Tpvec &a, const _Tpvec &b) +{ + using namespace hal_sse_internal; + enum { imm2 = ((_Tpvec::nlanes - imm) * sizeof(typename _Tpvec::lane_type)) }; + return _Tpvec(v_sse_reinterpret_as( + v_sse_palignr_u8( + v_sse_reinterpret_as<__m128i>(b.val), + v_sse_reinterpret_as<__m128i>(a.val)))); +} + +#define OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(_Tpvec, _Tp) \ +inline _Tpvec v_load(const _Tp* ptr) \ +{ return _Tpvec(_mm_loadu_si128((const __m128i*)ptr)); } \ +inline _Tpvec v_load_aligned(const _Tp* ptr) \ +{ return _Tpvec(_mm_load_si128((const __m128i*)ptr)); } \ +inline _Tpvec v_load_low(const _Tp* ptr) \ +{ return _Tpvec(_mm_loadl_epi64((const __m128i*)ptr)); } \ +inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ +{ \ + return _Tpvec(_mm_unpacklo_epi64(_mm_loadl_epi64((const __m128i*)ptr0), \ + _mm_loadl_epi64((const __m128i*)ptr1))); \ +} \ +inline void v_store(_Tp* ptr, const _Tpvec& a) \ +{ _mm_storeu_si128((__m128i*)ptr, a.val); } \ +inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ +{ _mm_store_si128((__m128i*)ptr, a.val); } \ +inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ +{ _mm_stream_si128((__m128i*)ptr, a.val); } \ +inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ +{ \ + if( mode == hal::STORE_UNALIGNED ) \ + _mm_storeu_si128((__m128i*)ptr, a.val); \ + else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ + _mm_stream_si128((__m128i*)ptr, a.val); \ + else \ + _mm_store_si128((__m128i*)ptr, a.val); \ +} \ +inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ +{ _mm_storel_epi64((__m128i*)ptr, a.val); } \ +inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ +{ _mm_storel_epi64((__m128i*)ptr, _mm_unpackhi_epi64(a.val, a.val)); } + +OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_uint8x16, uchar) +OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_int8x16, schar) +OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_uint16x8, ushort) +OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_int16x8, short) +OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_uint32x4, unsigned) +OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_int32x4, int) +OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_uint64x2, uint64) +OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_int64x2, int64) + +#define OPENCV_HAL_IMPL_SSE_LOADSTORE_FLT_OP(_Tpvec, _Tp, suffix) \ +inline _Tpvec v_load(const _Tp* ptr) \ +{ return _Tpvec(_mm_loadu_##suffix(ptr)); } \ +inline _Tpvec v_load_aligned(const _Tp* ptr) \ +{ return _Tpvec(_mm_load_##suffix(ptr)); } \ +inline _Tpvec v_load_low(const _Tp* ptr) \ +{ return _Tpvec(_mm_castsi128_##suffix(_mm_loadl_epi64((const __m128i*)ptr))); } \ +inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ +{ \ + return _Tpvec(_mm_castsi128_##suffix( \ + _mm_unpacklo_epi64(_mm_loadl_epi64((const __m128i*)ptr0), \ + _mm_loadl_epi64((const __m128i*)ptr1)))); \ +} \ +inline void v_store(_Tp* ptr, const _Tpvec& a) \ +{ _mm_storeu_##suffix(ptr, a.val); } \ +inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ +{ _mm_store_##suffix(ptr, a.val); } \ +inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ +{ _mm_stream_##suffix(ptr, a.val); } \ +inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ +{ \ + if( mode == hal::STORE_UNALIGNED ) \ + _mm_storeu_##suffix(ptr, a.val); \ + else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ + _mm_stream_##suffix(ptr, a.val); \ + else \ + _mm_store_##suffix(ptr, a.val); \ +} \ +inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ +{ _mm_storel_epi64((__m128i*)ptr, _mm_cast##suffix##_si128(a.val)); } \ +inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ +{ \ + __m128i a1 = _mm_cast##suffix##_si128(a.val); \ + _mm_storel_epi64((__m128i*)ptr, _mm_unpackhi_epi64(a1, a1)); \ +} + +OPENCV_HAL_IMPL_SSE_LOADSTORE_FLT_OP(v_float32x4, float, ps) +OPENCV_HAL_IMPL_SSE_LOADSTORE_FLT_OP(v_float64x2, double, pd) + +inline unsigned v_reduce_sum(const v_uint8x16& a) +{ + __m128i half = _mm_sad_epu8(a.val, _mm_setzero_si128()); + return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(half, _mm_unpackhi_epi64(half, half))); +} +inline int v_reduce_sum(const v_int8x16& a) +{ + __m128i half = _mm_set1_epi8((schar)-128); + half = _mm_sad_epu8(_mm_xor_si128(a.val, half), _mm_setzero_si128()); + return _mm_cvtsi128_si32(_mm_add_epi32(half, _mm_unpackhi_epi64(half, half))) - 2048; +} +#define OPENCV_HAL_IMPL_SSE_REDUCE_OP_16(func) \ +inline schar v_reduce_##func(const v_int8x16& a) \ +{ \ + __m128i val = a.val; \ + __m128i smask = _mm_set1_epi8((schar)-128); \ + val = _mm_xor_si128(val, smask); \ + val = _mm_##func##_epu8(val, _mm_srli_si128(val,8)); \ + val = _mm_##func##_epu8(val, _mm_srli_si128(val,4)); \ + val = _mm_##func##_epu8(val, _mm_srli_si128(val,2)); \ + val = _mm_##func##_epu8(val, _mm_srli_si128(val,1)); \ + return (schar)_mm_cvtsi128_si32(val) ^ (schar)-128; \ +} \ +inline uchar v_reduce_##func(const v_uint8x16& a) \ +{ \ + __m128i val = a.val; \ + val = _mm_##func##_epu8(val, _mm_srli_si128(val,8)); \ + val = _mm_##func##_epu8(val, _mm_srli_si128(val,4)); \ + val = _mm_##func##_epu8(val, _mm_srli_si128(val,2)); \ + val = _mm_##func##_epu8(val, _mm_srli_si128(val,1)); \ + return (uchar)_mm_cvtsi128_si32(val); \ +} +OPENCV_HAL_IMPL_SSE_REDUCE_OP_16(max) +OPENCV_HAL_IMPL_SSE_REDUCE_OP_16(min) + +#define OPENCV_HAL_IMPL_SSE_REDUCE_OP_8(_Tpvec, scalartype, func, suffix, sbit) \ +inline scalartype v_reduce_##func(const v_##_Tpvec& a) \ +{ \ + __m128i val = a.val; \ + val = _mm_##func##_##suffix(val, _mm_srli_si128(val,8)); \ + val = _mm_##func##_##suffix(val, _mm_srli_si128(val,4)); \ + val = _mm_##func##_##suffix(val, _mm_srli_si128(val,2)); \ + return (scalartype)_mm_cvtsi128_si32(val); \ +} \ +inline unsigned scalartype v_reduce_##func(const v_u##_Tpvec& a) \ +{ \ + __m128i val = a.val; \ + __m128i smask = _mm_set1_epi16(sbit); \ + val = _mm_xor_si128(val, smask); \ + val = _mm_##func##_##suffix(val, _mm_srli_si128(val,8)); \ + val = _mm_##func##_##suffix(val, _mm_srli_si128(val,4)); \ + val = _mm_##func##_##suffix(val, _mm_srli_si128(val,2)); \ + return (unsigned scalartype)(_mm_cvtsi128_si32(val) ^ sbit); \ +} +OPENCV_HAL_IMPL_SSE_REDUCE_OP_8(int16x8, short, max, epi16, (short)-32768) +OPENCV_HAL_IMPL_SSE_REDUCE_OP_8(int16x8, short, min, epi16, (short)-32768) + +#define OPENCV_HAL_IMPL_SSE_REDUCE_OP_4_SUM(_Tpvec, scalartype, regtype, suffix, cast_from, cast_to, extract) \ +inline scalartype v_reduce_sum(const _Tpvec& a) \ +{ \ + regtype val = a.val; \ + val = _mm_add_##suffix(val, cast_to(_mm_srli_si128(cast_from(val), 8))); \ + val = _mm_add_##suffix(val, cast_to(_mm_srli_si128(cast_from(val), 4))); \ + return (scalartype)_mm_cvt##extract(val); \ +} + +#define OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(_Tpvec, scalartype, func, scalar_func) \ +inline scalartype v_reduce_##func(const _Tpvec& a) \ +{ \ + scalartype CV_DECL_ALIGNED(16) buf[4]; \ + v_store_aligned(buf, a); \ + scalartype s0 = scalar_func(buf[0], buf[1]); \ + scalartype s1 = scalar_func(buf[2], buf[3]); \ + return scalar_func(s0, s1); \ +} + +OPENCV_HAL_IMPL_SSE_REDUCE_OP_4_SUM(v_uint32x4, unsigned, __m128i, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP, si128_si32) +OPENCV_HAL_IMPL_SSE_REDUCE_OP_4_SUM(v_int32x4, int, __m128i, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP, si128_si32) +OPENCV_HAL_IMPL_SSE_REDUCE_OP_4_SUM(v_float32x4, float, __m128, ps, _mm_castps_si128, _mm_castsi128_ps, ss_f32) + +inline int v_reduce_sum(const v_int16x8& a) +{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } +inline unsigned v_reduce_sum(const v_uint16x8& a) +{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } + +inline uint64 v_reduce_sum(const v_uint64x2& a) +{ + uint64 CV_DECL_ALIGNED(32) idx[2]; + v_store_aligned(idx, a); + return idx[0] + idx[1]; +} +inline int64 v_reduce_sum(const v_int64x2& a) +{ + int64 CV_DECL_ALIGNED(32) idx[2]; + v_store_aligned(idx, a); + return idx[0] + idx[1]; +} +inline double v_reduce_sum(const v_float64x2& a) +{ + double CV_DECL_ALIGNED(32) idx[2]; + v_store_aligned(idx, a); + return idx[0] + idx[1]; +} + +inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, + const v_float32x4& c, const v_float32x4& d) +{ +#if CV_SSE3 + __m128 ab = _mm_hadd_ps(a.val, b.val); + __m128 cd = _mm_hadd_ps(c.val, d.val); + return v_float32x4(_mm_hadd_ps(ab, cd)); +#else + __m128 ac = _mm_add_ps(_mm_unpacklo_ps(a.val, c.val), _mm_unpackhi_ps(a.val, c.val)); + __m128 bd = _mm_add_ps(_mm_unpacklo_ps(b.val, d.val), _mm_unpackhi_ps(b.val, d.val)); + return v_float32x4(_mm_add_ps(_mm_unpacklo_ps(ac, bd), _mm_unpackhi_ps(ac, bd))); +#endif +} + +OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_uint32x4, unsigned, max, std::max) +OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_uint32x4, unsigned, min, std::min) +OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_int32x4, int, max, std::max) +OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_int32x4, int, min, std::min) +OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_float32x4, float, max, std::max) +OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_float32x4, float, min, std::min) + +inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b) +{ + __m128i half = _mm_sad_epu8(a.val, b.val); + return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(half, _mm_unpackhi_epi64(half, half))); +} +inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b) +{ + __m128i half = _mm_set1_epi8(0x7f); + half = _mm_sad_epu8(_mm_add_epi8(a.val, half), _mm_add_epi8(b.val, half)); + return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(half, _mm_unpackhi_epi64(half, half))); +} +inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b) +{ + v_uint32x4 l, h; + v_expand(v_absdiff(a, b), l, h); + return v_reduce_sum(v_add(l, h)); +} +inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b) +{ + v_uint32x4 l, h; + v_expand(v_absdiff(a, b), l, h); + return v_reduce_sum(v_add(l, h)); +} +inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b) +{ + return v_reduce_sum(v_absdiff(a, b)); +} +inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b) +{ + return v_reduce_sum(v_absdiff(a, b)); +} +inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) +{ + return v_reduce_sum(v_absdiff(a, b)); +} + +inline v_uint8x16 v_popcount(const v_uint8x16& a) +{ + __m128i m1 = _mm_set1_epi32(0x55555555); + __m128i m2 = _mm_set1_epi32(0x33333333); + __m128i m4 = _mm_set1_epi32(0x0f0f0f0f); + __m128i p = a.val; + p = _mm_add_epi32(_mm_and_si128(_mm_srli_epi32(p, 1), m1), _mm_and_si128(p, m1)); + p = _mm_add_epi32(_mm_and_si128(_mm_srli_epi32(p, 2), m2), _mm_and_si128(p, m2)); + p = _mm_add_epi32(_mm_and_si128(_mm_srli_epi32(p, 4), m4), _mm_and_si128(p, m4)); + return v_uint8x16(p); +} +inline v_uint16x8 v_popcount(const v_uint16x8& a) +{ + v_uint8x16 p = v_popcount(v_reinterpret_as_u8(a)); + p = v_add(p, v_rotate_right<1>(p)); + return v_and(v_reinterpret_as_u16(p), v_setall_u16(0x00ff)); +} +inline v_uint32x4 v_popcount(const v_uint32x4& a) +{ + v_uint8x16 p = v_popcount(v_reinterpret_as_u8(a)); + p = v_add(p, v_rotate_right<1>(p)); + p = v_add(p, v_rotate_right<2>(p)); + return v_and(v_reinterpret_as_u32(p), v_setall_u32(0x000000ff)); +} +inline v_uint64x2 v_popcount(const v_uint64x2& a) +{ + return v_uint64x2(_mm_sad_epu8(v_popcount(v_reinterpret_as_u8(a)).val, _mm_setzero_si128())); +} +inline v_uint8x16 v_popcount(const v_int8x16& a) +{ return v_popcount(v_reinterpret_as_u8(a)); } +inline v_uint16x8 v_popcount(const v_int16x8& a) +{ return v_popcount(v_reinterpret_as_u16(a)); } +inline v_uint32x4 v_popcount(const v_int32x4& a) +{ return v_popcount(v_reinterpret_as_u32(a)); } +inline v_uint64x2 v_popcount(const v_int64x2& a) +{ return v_popcount(v_reinterpret_as_u64(a)); } + +#define OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(_Tpvec, suffix, cast_op, allmask) \ +inline int v_signmask(const _Tpvec& a) { return _mm_movemask_##suffix(cast_op(a.val)); } \ +inline bool v_check_all(const _Tpvec& a) { return _mm_movemask_##suffix(cast_op(a.val)) == allmask; } \ +inline bool v_check_any(const _Tpvec& a) { return _mm_movemask_##suffix(cast_op(a.val)) != 0; } +OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_uint8x16, epi8, OPENCV_HAL_NOP, 65535) +OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_int8x16, epi8, OPENCV_HAL_NOP, 65535) +OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_uint32x4, ps, _mm_castsi128_ps, 15) +OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_int32x4, ps, _mm_castsi128_ps, 15) +OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_uint64x2, pd, _mm_castsi128_pd, 3) +OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_int64x2, pd, _mm_castsi128_pd, 3) +OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_float32x4, ps, OPENCV_HAL_NOP, 15) +OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_float64x2, pd, OPENCV_HAL_NOP, 3) + +#define OPENCV_HAL_IMPL_SSE_CHECK_SIGNS_SHORT(_Tpvec) \ +inline int v_signmask(const _Tpvec& a) { return _mm_movemask_epi8(_mm_packs_epi16(a.val, a.val)) & 255; } \ +inline bool v_check_all(const _Tpvec& a) { return (_mm_movemask_epi8(a.val) & 0xaaaa) == 0xaaaa; } \ +inline bool v_check_any(const _Tpvec& a) { return (_mm_movemask_epi8(a.val) & 0xaaaa) != 0; } +OPENCV_HAL_IMPL_SSE_CHECK_SIGNS_SHORT(v_uint16x8) +OPENCV_HAL_IMPL_SSE_CHECK_SIGNS_SHORT(v_int16x8) + +inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } +inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } +inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } +inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } +inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } +inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } +inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } + +#if CV_SSE4_1 +#define OPENCV_HAL_IMPL_SSE_SELECT(_Tpvec, cast_ret, cast, suffix) \ +inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(cast_ret(_mm_blendv_##suffix(cast(b.val), cast(a.val), cast(mask.val)))); \ +} + +OPENCV_HAL_IMPL_SSE_SELECT(v_uint8x16, OPENCV_HAL_NOP, OPENCV_HAL_NOP, epi8) +OPENCV_HAL_IMPL_SSE_SELECT(v_int8x16, OPENCV_HAL_NOP, OPENCV_HAL_NOP, epi8) +OPENCV_HAL_IMPL_SSE_SELECT(v_uint16x8, OPENCV_HAL_NOP, OPENCV_HAL_NOP, epi8) +OPENCV_HAL_IMPL_SSE_SELECT(v_int16x8, OPENCV_HAL_NOP, OPENCV_HAL_NOP, epi8) +OPENCV_HAL_IMPL_SSE_SELECT(v_uint32x4, _mm_castps_si128, _mm_castsi128_ps, ps) +OPENCV_HAL_IMPL_SSE_SELECT(v_int32x4, _mm_castps_si128, _mm_castsi128_ps, ps) +// OPENCV_HAL_IMPL_SSE_SELECT(v_uint64x2, TBD, TBD, pd) +// OPENCV_HAL_IMPL_SSE_SELECT(v_int64x2, TBD, TBD, ps) +OPENCV_HAL_IMPL_SSE_SELECT(v_float32x4, OPENCV_HAL_NOP, OPENCV_HAL_NOP, ps) +OPENCV_HAL_IMPL_SSE_SELECT(v_float64x2, OPENCV_HAL_NOP, OPENCV_HAL_NOP, pd) + +#else // CV_SSE4_1 + +#define OPENCV_HAL_IMPL_SSE_SELECT(_Tpvec, suffix) \ +inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(_mm_xor_##suffix(b.val, _mm_and_##suffix(_mm_xor_##suffix(b.val, a.val), mask.val))); \ +} + +OPENCV_HAL_IMPL_SSE_SELECT(v_uint8x16, si128) +OPENCV_HAL_IMPL_SSE_SELECT(v_int8x16, si128) +OPENCV_HAL_IMPL_SSE_SELECT(v_uint16x8, si128) +OPENCV_HAL_IMPL_SSE_SELECT(v_int16x8, si128) +OPENCV_HAL_IMPL_SSE_SELECT(v_uint32x4, si128) +OPENCV_HAL_IMPL_SSE_SELECT(v_int32x4, si128) +// OPENCV_HAL_IMPL_SSE_SELECT(v_uint64x2, si128) +// OPENCV_HAL_IMPL_SSE_SELECT(v_int64x2, si128) +OPENCV_HAL_IMPL_SSE_SELECT(v_float32x4, ps) +OPENCV_HAL_IMPL_SSE_SELECT(v_float64x2, pd) +#endif + +/* Expand */ +#define OPENCV_HAL_IMPL_SSE_EXPAND(_Tpvec, _Tpwvec, _Tp, intrin) \ + inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ + { \ + b0.val = intrin(a.val); \ + b1.val = __CV_CAT(intrin, _high)(a.val); \ + } \ + inline _Tpwvec v_expand_low(const _Tpvec& a) \ + { return _Tpwvec(intrin(a.val)); } \ + inline _Tpwvec v_expand_high(const _Tpvec& a) \ + { return _Tpwvec(__CV_CAT(intrin, _high)(a.val)); } \ + inline _Tpwvec v_load_expand(const _Tp* ptr) \ + { \ + __m128i a = _mm_loadl_epi64((const __m128i*)ptr); \ + return _Tpwvec(intrin(a)); \ + } + +OPENCV_HAL_IMPL_SSE_EXPAND(v_uint8x16, v_uint16x8, uchar, _v128_cvtepu8_epi16) +OPENCV_HAL_IMPL_SSE_EXPAND(v_int8x16, v_int16x8, schar, _v128_cvtepi8_epi16) +OPENCV_HAL_IMPL_SSE_EXPAND(v_uint16x8, v_uint32x4, ushort, _v128_cvtepu16_epi32) +OPENCV_HAL_IMPL_SSE_EXPAND(v_int16x8, v_int32x4, short, _v128_cvtepi16_epi32) +OPENCV_HAL_IMPL_SSE_EXPAND(v_uint32x4, v_uint64x2, unsigned, _v128_cvtepu32_epi64) +OPENCV_HAL_IMPL_SSE_EXPAND(v_int32x4, v_int64x2, int, _v128_cvtepi32_epi64) + +#define OPENCV_HAL_IMPL_SSE_EXPAND_Q(_Tpvec, _Tp, intrin) \ + inline _Tpvec v_load_expand_q(const _Tp* ptr) \ + { \ + typedef int CV_DECL_ALIGNED(1) unaligned_int; \ + __m128i a = _mm_cvtsi32_si128(*(const unaligned_int*)ptr); \ + return _Tpvec(intrin(a)); \ + } + +OPENCV_HAL_IMPL_SSE_EXPAND_Q(v_uint32x4, uchar, _v128_cvtepu8_epi32) +OPENCV_HAL_IMPL_SSE_EXPAND_Q(v_int32x4, schar, _v128_cvtepi8_epi32) + +#define OPENCV_HAL_IMPL_SSE_UNPACKS(_Tpvec, suffix, cast_from, cast_to) \ +inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) \ +{ \ + b0.val = _mm_unpacklo_##suffix(a0.val, a1.val); \ + b1.val = _mm_unpackhi_##suffix(a0.val, a1.val); \ +} \ +inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ +{ \ + __m128i a1 = cast_from(a.val), b1 = cast_from(b.val); \ + return _Tpvec(cast_to(_mm_unpacklo_epi64(a1, b1))); \ +} \ +inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ +{ \ + __m128i a1 = cast_from(a.val), b1 = cast_from(b.val); \ + return _Tpvec(cast_to(_mm_unpackhi_epi64(a1, b1))); \ +} \ +inline void v_recombine(const _Tpvec& a, const _Tpvec& b, _Tpvec& c, _Tpvec& d) \ +{ \ + __m128i a1 = cast_from(a.val), b1 = cast_from(b.val); \ + c.val = cast_to(_mm_unpacklo_epi64(a1, b1)); \ + d.val = cast_to(_mm_unpackhi_epi64(a1, b1)); \ +} + +OPENCV_HAL_IMPL_SSE_UNPACKS(v_uint8x16, epi8, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_UNPACKS(v_int8x16, epi8, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_UNPACKS(v_uint16x8, epi16, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_UNPACKS(v_int16x8, epi16, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_UNPACKS(v_uint32x4, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_UNPACKS(v_int32x4, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_UNPACKS(v_float32x4, ps, _mm_castps_si128, _mm_castsi128_ps) +OPENCV_HAL_IMPL_SSE_UNPACKS(v_float64x2, pd, _mm_castpd_si128, _mm_castsi128_pd) + +inline v_uint8x16 v_reverse(const v_uint8x16 &a) +{ +#if CV_SSSE3 + static const __m128i perm = _mm_setr_epi8(15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); + return v_uint8x16(_mm_shuffle_epi8(a.val, perm)); +#else + uchar CV_DECL_ALIGNED(32) d[16]; + v_store_aligned(d, a); + return v_uint8x16(d[15], d[14], d[13], d[12], d[11], d[10], d[9], d[8], d[7], d[6], d[5], d[4], d[3], d[2], d[1], d[0]); +#endif +} + +inline v_int8x16 v_reverse(const v_int8x16 &a) +{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } + +inline v_uint16x8 v_reverse(const v_uint16x8 &a) +{ +#if CV_SSSE3 + static const __m128i perm = _mm_setr_epi8(14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1); + return v_uint16x8(_mm_shuffle_epi8(a.val, perm)); +#else + __m128i r = _mm_shuffle_epi32(a.val, _MM_SHUFFLE(0, 1, 2, 3)); + r = _mm_shufflelo_epi16(r, _MM_SHUFFLE(2, 3, 0, 1)); + r = _mm_shufflehi_epi16(r, _MM_SHUFFLE(2, 3, 0, 1)); + return v_uint16x8(r); +#endif +} + +inline v_int16x8 v_reverse(const v_int16x8 &a) +{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } + +inline v_uint32x4 v_reverse(const v_uint32x4 &a) +{ + return v_uint32x4(_mm_shuffle_epi32(a.val, _MM_SHUFFLE(0, 1, 2, 3))); +} + +inline v_int32x4 v_reverse(const v_int32x4 &a) +{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_float32x4 v_reverse(const v_float32x4 &a) +{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_uint64x2 v_reverse(const v_uint64x2 &a) +{ + return v_uint64x2(_mm_shuffle_epi32(a.val, _MM_SHUFFLE(1, 0, 3, 2))); +} + +inline v_int64x2 v_reverse(const v_int64x2 &a) +{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } + +inline v_float64x2 v_reverse(const v_float64x2 &a) +{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } + +template +inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) +{ + return v_rotate_right(a, b); +} + +inline v_int32x4 v_round(const v_float32x4& a) +{ return v_int32x4(_mm_cvtps_epi32(a.val)); } + +inline v_int32x4 v_floor(const v_float32x4& a) +{ + __m128i a1 = _mm_cvtps_epi32(a.val); + __m128i mask = _mm_castps_si128(_mm_cmpgt_ps(_mm_cvtepi32_ps(a1), a.val)); + return v_int32x4(_mm_add_epi32(a1, mask)); +} + +inline v_int32x4 v_ceil(const v_float32x4& a) +{ + __m128i a1 = _mm_cvtps_epi32(a.val); + __m128i mask = _mm_castps_si128(_mm_cmpgt_ps(a.val, _mm_cvtepi32_ps(a1))); + return v_int32x4(_mm_sub_epi32(a1, mask)); +} + +inline v_int32x4 v_trunc(const v_float32x4& a) +{ return v_int32x4(_mm_cvttps_epi32(a.val)); } + +inline v_int32x4 v_round(const v_float64x2& a) +{ return v_int32x4(_mm_cvtpd_epi32(a.val)); } + +inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) +{ + __m128i ai = _mm_cvtpd_epi32(a.val), bi = _mm_cvtpd_epi32(b.val); + return v_int32x4(_mm_unpacklo_epi64(ai, bi)); +} + +inline v_int32x4 v_floor(const v_float64x2& a) +{ + __m128i a1 = _mm_cvtpd_epi32(a.val); + __m128i mask = _mm_castpd_si128(_mm_cmpgt_pd(_mm_cvtepi32_pd(a1), a.val)); + mask = _mm_srli_si128(_mm_slli_si128(mask, 4), 8); // m0 m0 m1 m1 => m0 m1 0 0 + return v_int32x4(_mm_add_epi32(a1, mask)); +} + +inline v_int32x4 v_ceil(const v_float64x2& a) +{ + __m128i a1 = _mm_cvtpd_epi32(a.val); + __m128i mask = _mm_castpd_si128(_mm_cmpgt_pd(a.val, _mm_cvtepi32_pd(a1))); + mask = _mm_srli_si128(_mm_slli_si128(mask, 4), 8); // m0 m0 m1 m1 => m0 m1 0 0 + return v_int32x4(_mm_sub_epi32(a1, mask)); +} + +inline v_int32x4 v_trunc(const v_float64x2& a) +{ return v_int32x4(_mm_cvttpd_epi32(a.val)); } + +#define OPENCV_HAL_IMPL_SSE_TRANSPOSE4x4(_Tpvec, suffix, cast_from, cast_to) \ +inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ + const _Tpvec& a2, const _Tpvec& a3, \ + _Tpvec& b0, _Tpvec& b1, \ + _Tpvec& b2, _Tpvec& b3) \ +{ \ + __m128i t0 = cast_from(_mm_unpacklo_##suffix(a0.val, a1.val)); \ + __m128i t1 = cast_from(_mm_unpacklo_##suffix(a2.val, a3.val)); \ + __m128i t2 = cast_from(_mm_unpackhi_##suffix(a0.val, a1.val)); \ + __m128i t3 = cast_from(_mm_unpackhi_##suffix(a2.val, a3.val)); \ +\ + b0.val = cast_to(_mm_unpacklo_epi64(t0, t1)); \ + b1.val = cast_to(_mm_unpackhi_epi64(t0, t1)); \ + b2.val = cast_to(_mm_unpacklo_epi64(t2, t3)); \ + b3.val = cast_to(_mm_unpackhi_epi64(t2, t3)); \ +} + +OPENCV_HAL_IMPL_SSE_TRANSPOSE4x4(v_uint32x4, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_TRANSPOSE4x4(v_int32x4, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_TRANSPOSE4x4(v_float32x4, ps, _mm_castps_si128, _mm_castsi128_ps) + +// load deinterleave +inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b) +{ + __m128i t00 = _mm_loadu_si128((const __m128i*)ptr); + __m128i t01 = _mm_loadu_si128((const __m128i*)(ptr + 16)); + + __m128i t10 = _mm_unpacklo_epi8(t00, t01); + __m128i t11 = _mm_unpackhi_epi8(t00, t01); + + __m128i t20 = _mm_unpacklo_epi8(t10, t11); + __m128i t21 = _mm_unpackhi_epi8(t10, t11); + + __m128i t30 = _mm_unpacklo_epi8(t20, t21); + __m128i t31 = _mm_unpackhi_epi8(t20, t21); + + a.val = _mm_unpacklo_epi8(t30, t31); + b.val = _mm_unpackhi_epi8(t30, t31); +} + +inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c) +{ +#if CV_SSE4_1 + const __m128i m0 = _mm_setr_epi8(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0); + const __m128i m1 = _mm_setr_epi8(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); + __m128i s0 = _mm_loadu_si128((const __m128i*)ptr); + __m128i s1 = _mm_loadu_si128((const __m128i*)(ptr + 16)); + __m128i s2 = _mm_loadu_si128((const __m128i*)(ptr + 32)); + __m128i a0 = _mm_blendv_epi8(_mm_blendv_epi8(s0, s1, m0), s2, m1); + __m128i b0 = _mm_blendv_epi8(_mm_blendv_epi8(s1, s2, m0), s0, m1); + __m128i c0 = _mm_blendv_epi8(_mm_blendv_epi8(s2, s0, m0), s1, m1); + const __m128i sh_b = _mm_setr_epi8(0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13); + const __m128i sh_g = _mm_setr_epi8(1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14); + const __m128i sh_r = _mm_setr_epi8(2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15); + a0 = _mm_shuffle_epi8(a0, sh_b); + b0 = _mm_shuffle_epi8(b0, sh_g); + c0 = _mm_shuffle_epi8(c0, sh_r); + a.val = a0; + b.val = b0; + c.val = c0; +#elif CV_SSSE3 + const __m128i m0 = _mm_setr_epi8(0, 3, 6, 9, 12, 15, 1, 4, 7, 10, 13, 2, 5, 8, 11, 14); + const __m128i m1 = _mm_alignr_epi8(m0, m0, 11); + const __m128i m2 = _mm_alignr_epi8(m0, m0, 6); + + __m128i t0 = _mm_loadu_si128((const __m128i*)ptr); + __m128i t1 = _mm_loadu_si128((const __m128i*)(ptr + 16)); + __m128i t2 = _mm_loadu_si128((const __m128i*)(ptr + 32)); + + __m128i s0 = _mm_shuffle_epi8(t0, m0); + __m128i s1 = _mm_shuffle_epi8(t1, m1); + __m128i s2 = _mm_shuffle_epi8(t2, m2); + + t0 = _mm_alignr_epi8(s1, _mm_slli_si128(s0, 10), 5); + a.val = _mm_alignr_epi8(s2, t0, 5); + + t1 = _mm_alignr_epi8(_mm_srli_si128(s1, 5), _mm_slli_si128(s0, 5), 6); + b.val = _mm_alignr_epi8(_mm_srli_si128(s2, 5), t1, 5); + + t2 = _mm_alignr_epi8(_mm_srli_si128(s2, 10), s1, 11); + c.val = _mm_alignr_epi8(t2, s0, 11); +#else + __m128i t00 = _mm_loadu_si128((const __m128i*)ptr); + __m128i t01 = _mm_loadu_si128((const __m128i*)(ptr + 16)); + __m128i t02 = _mm_loadu_si128((const __m128i*)(ptr + 32)); + + __m128i t10 = _mm_unpacklo_epi8(t00, _mm_unpackhi_epi64(t01, t01)); + __m128i t11 = _mm_unpacklo_epi8(_mm_unpackhi_epi64(t00, t00), t02); + __m128i t12 = _mm_unpacklo_epi8(t01, _mm_unpackhi_epi64(t02, t02)); + + __m128i t20 = _mm_unpacklo_epi8(t10, _mm_unpackhi_epi64(t11, t11)); + __m128i t21 = _mm_unpacklo_epi8(_mm_unpackhi_epi64(t10, t10), t12); + __m128i t22 = _mm_unpacklo_epi8(t11, _mm_unpackhi_epi64(t12, t12)); + + __m128i t30 = _mm_unpacklo_epi8(t20, _mm_unpackhi_epi64(t21, t21)); + __m128i t31 = _mm_unpacklo_epi8(_mm_unpackhi_epi64(t20, t20), t22); + __m128i t32 = _mm_unpacklo_epi8(t21, _mm_unpackhi_epi64(t22, t22)); + + a.val = _mm_unpacklo_epi8(t30, _mm_unpackhi_epi64(t31, t31)); + b.val = _mm_unpacklo_epi8(_mm_unpackhi_epi64(t30, t30), t32); + c.val = _mm_unpacklo_epi8(t31, _mm_unpackhi_epi64(t32, t32)); +#endif +} + +inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c, v_uint8x16& d) +{ + __m128i u0 = _mm_loadu_si128((const __m128i*)ptr); // a0 b0 c0 d0 a1 b1 c1 d1 ... + __m128i u1 = _mm_loadu_si128((const __m128i*)(ptr + 16)); // a4 b4 c4 d4 ... + __m128i u2 = _mm_loadu_si128((const __m128i*)(ptr + 32)); // a8 b8 c8 d8 ... + __m128i u3 = _mm_loadu_si128((const __m128i*)(ptr + 48)); // a12 b12 c12 d12 ... + + __m128i v0 = _mm_unpacklo_epi8(u0, u2); // a0 a8 b0 b8 ... + __m128i v1 = _mm_unpackhi_epi8(u0, u2); // a2 a10 b2 b10 ... + __m128i v2 = _mm_unpacklo_epi8(u1, u3); // a4 a12 b4 b12 ... + __m128i v3 = _mm_unpackhi_epi8(u1, u3); // a6 a14 b6 b14 ... + + u0 = _mm_unpacklo_epi8(v0, v2); // a0 a4 a8 a12 ... + u1 = _mm_unpacklo_epi8(v1, v3); // a2 a6 a10 a14 ... + u2 = _mm_unpackhi_epi8(v0, v2); // a1 a5 a9 a13 ... + u3 = _mm_unpackhi_epi8(v1, v3); // a3 a7 a11 a15 ... + + v0 = _mm_unpacklo_epi8(u0, u1); // a0 a2 a4 a6 ... + v1 = _mm_unpacklo_epi8(u2, u3); // a1 a3 a5 a7 ... + v2 = _mm_unpackhi_epi8(u0, u1); // c0 c2 c4 c6 ... + v3 = _mm_unpackhi_epi8(u2, u3); // c1 c3 c5 c7 ... + + a.val = _mm_unpacklo_epi8(v0, v1); + b.val = _mm_unpackhi_epi8(v0, v1); + c.val = _mm_unpacklo_epi8(v2, v3); + d.val = _mm_unpackhi_epi8(v2, v3); +} + +inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b) +{ + __m128i v0 = _mm_loadu_si128((__m128i*)(ptr)); // a0 b0 a1 b1 a2 b2 a3 b3 + __m128i v1 = _mm_loadu_si128((__m128i*)(ptr + 8)); // a4 b4 a5 b5 a6 b6 a7 b7 + + __m128i v2 = _mm_unpacklo_epi16(v0, v1); // a0 a4 b0 b4 a1 a5 b1 b5 + __m128i v3 = _mm_unpackhi_epi16(v0, v1); // a2 a6 b2 b6 a3 a7 b3 b7 + __m128i v4 = _mm_unpacklo_epi16(v2, v3); // a0 a2 a4 a6 b0 b2 b4 b6 + __m128i v5 = _mm_unpackhi_epi16(v2, v3); // a1 a3 a5 a7 b1 b3 b5 b7 + + a.val = _mm_unpacklo_epi16(v4, v5); // a0 a1 a2 a3 a4 a5 a6 a7 + b.val = _mm_unpackhi_epi16(v4, v5); // b0 b1 ab b3 b4 b5 b6 b7 +} + +inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c) +{ +#if CV_SSE4_1 + __m128i v0 = _mm_loadu_si128((__m128i*)(ptr)); + __m128i v1 = _mm_loadu_si128((__m128i*)(ptr + 8)); + __m128i v2 = _mm_loadu_si128((__m128i*)(ptr + 16)); + __m128i a0 = _mm_blend_epi16(_mm_blend_epi16(v0, v1, 0x92), v2, 0x24); + __m128i b0 = _mm_blend_epi16(_mm_blend_epi16(v2, v0, 0x92), v1, 0x24); + __m128i c0 = _mm_blend_epi16(_mm_blend_epi16(v1, v2, 0x92), v0, 0x24); + + const __m128i sh_a = _mm_setr_epi8(0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11); + const __m128i sh_b = _mm_setr_epi8(2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 0, 1, 6, 7, 12, 13); + const __m128i sh_c = _mm_setr_epi8(4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15); + a0 = _mm_shuffle_epi8(a0, sh_a); + b0 = _mm_shuffle_epi8(b0, sh_b); + c0 = _mm_shuffle_epi8(c0, sh_c); + + a.val = a0; + b.val = b0; + c.val = c0; +#else + __m128i t00 = _mm_loadu_si128((const __m128i*)ptr); + __m128i t01 = _mm_loadu_si128((const __m128i*)(ptr + 8)); + __m128i t02 = _mm_loadu_si128((const __m128i*)(ptr + 16)); + + __m128i t10 = _mm_unpacklo_epi16(t00, _mm_unpackhi_epi64(t01, t01)); + __m128i t11 = _mm_unpacklo_epi16(_mm_unpackhi_epi64(t00, t00), t02); + __m128i t12 = _mm_unpacklo_epi16(t01, _mm_unpackhi_epi64(t02, t02)); + + __m128i t20 = _mm_unpacklo_epi16(t10, _mm_unpackhi_epi64(t11, t11)); + __m128i t21 = _mm_unpacklo_epi16(_mm_unpackhi_epi64(t10, t10), t12); + __m128i t22 = _mm_unpacklo_epi16(t11, _mm_unpackhi_epi64(t12, t12)); + + a.val = _mm_unpacklo_epi16(t20, _mm_unpackhi_epi64(t21, t21)); + b.val = _mm_unpacklo_epi16(_mm_unpackhi_epi64(t20, t20), t22); + c.val = _mm_unpacklo_epi16(t21, _mm_unpackhi_epi64(t22, t22)); +#endif +} + +inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c, v_uint16x8& d) +{ + __m128i u0 = _mm_loadu_si128((const __m128i*)ptr); // a0 b0 c0 d0 a1 b1 c1 d1 + __m128i u1 = _mm_loadu_si128((const __m128i*)(ptr + 8)); // a2 b2 c2 d2 ... + __m128i u2 = _mm_loadu_si128((const __m128i*)(ptr + 16)); // a4 b4 c4 d4 ... + __m128i u3 = _mm_loadu_si128((const __m128i*)(ptr + 24)); // a6 b6 c6 d6 ... + + __m128i v0 = _mm_unpacklo_epi16(u0, u2); // a0 a4 b0 b4 ... + __m128i v1 = _mm_unpackhi_epi16(u0, u2); // a1 a5 b1 b5 ... + __m128i v2 = _mm_unpacklo_epi16(u1, u3); // a2 a6 b2 b6 ... + __m128i v3 = _mm_unpackhi_epi16(u1, u3); // a3 a7 b3 b7 ... + + u0 = _mm_unpacklo_epi16(v0, v2); // a0 a2 a4 a6 ... + u1 = _mm_unpacklo_epi16(v1, v3); // a1 a3 a5 a7 ... + u2 = _mm_unpackhi_epi16(v0, v2); // c0 c2 c4 c6 ... + u3 = _mm_unpackhi_epi16(v1, v3); // c1 c3 c5 c7 ... + + a.val = _mm_unpacklo_epi16(u0, u1); + b.val = _mm_unpackhi_epi16(u0, u1); + c.val = _mm_unpacklo_epi16(u2, u3); + d.val = _mm_unpackhi_epi16(u2, u3); +} + +inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b) +{ + __m128i v0 = _mm_loadu_si128((__m128i*)(ptr)); // a0 b0 a1 b1 + __m128i v1 = _mm_loadu_si128((__m128i*)(ptr + 4)); // a2 b2 a3 b3 + + __m128i v2 = _mm_unpacklo_epi32(v0, v1); // a0 a2 b0 b2 + __m128i v3 = _mm_unpackhi_epi32(v0, v1); // a1 a3 b1 b3 + + a.val = _mm_unpacklo_epi32(v2, v3); // a0 a1 a2 a3 + b.val = _mm_unpackhi_epi32(v2, v3); // b0 b1 ab b3 +} + +inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c) +{ + __m128i t00 = _mm_loadu_si128((const __m128i*)ptr); + __m128i t01 = _mm_loadu_si128((const __m128i*)(ptr + 4)); + __m128i t02 = _mm_loadu_si128((const __m128i*)(ptr + 8)); + + __m128i t10 = _mm_unpacklo_epi32(t00, _mm_unpackhi_epi64(t01, t01)); + __m128i t11 = _mm_unpacklo_epi32(_mm_unpackhi_epi64(t00, t00), t02); + __m128i t12 = _mm_unpacklo_epi32(t01, _mm_unpackhi_epi64(t02, t02)); + + a.val = _mm_unpacklo_epi32(t10, _mm_unpackhi_epi64(t11, t11)); + b.val = _mm_unpacklo_epi32(_mm_unpackhi_epi64(t10, t10), t12); + c.val = _mm_unpacklo_epi32(t11, _mm_unpackhi_epi64(t12, t12)); +} + +inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c, v_uint32x4& d) +{ + v_uint32x4 s0(_mm_loadu_si128((const __m128i*)ptr)); // a0 b0 c0 d0 + v_uint32x4 s1(_mm_loadu_si128((const __m128i*)(ptr + 4))); // a1 b1 c1 d1 + v_uint32x4 s2(_mm_loadu_si128((const __m128i*)(ptr + 8))); // a2 b2 c2 d2 + v_uint32x4 s3(_mm_loadu_si128((const __m128i*)(ptr + 12))); // a3 b3 c3 d3 + + v_transpose4x4(s0, s1, s2, s3, a, b, c, d); +} + +inline void v_load_deinterleave(const float* ptr, v_float32x4& a, v_float32x4& b) +{ + __m128 u0 = _mm_loadu_ps(ptr); // a0 b0 a1 b1 + __m128 u1 = _mm_loadu_ps((ptr + 4)); // a2 b2 a3 b3 + + a.val = _mm_shuffle_ps(u0, u1, _MM_SHUFFLE(2, 0, 2, 0)); // a0 a1 a2 a3 + b.val = _mm_shuffle_ps(u0, u1, _MM_SHUFFLE(3, 1, 3, 1)); // b0 b1 ab b3 +} + +inline void v_load_deinterleave(const float* ptr, v_float32x4& a, v_float32x4& b, v_float32x4& c) +{ + __m128 t0 = _mm_loadu_ps(ptr + 0); + __m128 t1 = _mm_loadu_ps(ptr + 4); + __m128 t2 = _mm_loadu_ps(ptr + 8); + + __m128 at12 = _mm_shuffle_ps(t1, t2, _MM_SHUFFLE(0, 1, 0, 2)); + a.val = _mm_shuffle_ps(t0, at12, _MM_SHUFFLE(2, 0, 3, 0)); + + __m128 bt01 = _mm_shuffle_ps(t0, t1, _MM_SHUFFLE(0, 0, 0, 1)); + __m128 bt12 = _mm_shuffle_ps(t1, t2, _MM_SHUFFLE(0, 2, 0, 3)); + b.val = _mm_shuffle_ps(bt01, bt12, _MM_SHUFFLE(2, 0, 2, 0)); + + __m128 ct01 = _mm_shuffle_ps(t0, t1, _MM_SHUFFLE(0, 1, 0, 2)); + c.val = _mm_shuffle_ps(ct01, t2, _MM_SHUFFLE(3, 0, 2, 0)); +} + +inline void v_load_deinterleave(const float* ptr, v_float32x4& a, v_float32x4& b, v_float32x4& c, v_float32x4& d) +{ + __m128 t0 = _mm_loadu_ps(ptr + 0); + __m128 t1 = _mm_loadu_ps(ptr + 4); + __m128 t2 = _mm_loadu_ps(ptr + 8); + __m128 t3 = _mm_loadu_ps(ptr + 12); + __m128 t02lo = _mm_unpacklo_ps(t0, t2); + __m128 t13lo = _mm_unpacklo_ps(t1, t3); + __m128 t02hi = _mm_unpackhi_ps(t0, t2); + __m128 t13hi = _mm_unpackhi_ps(t1, t3); + a.val = _mm_unpacklo_ps(t02lo, t13lo); + b.val = _mm_unpackhi_ps(t02lo, t13lo); + c.val = _mm_unpacklo_ps(t02hi, t13hi); + d.val = _mm_unpackhi_ps(t02hi, t13hi); +} + +inline void v_load_deinterleave(const uint64 *ptr, v_uint64x2& a, v_uint64x2& b) +{ + __m128i t0 = _mm_loadu_si128((const __m128i*)ptr); + __m128i t1 = _mm_loadu_si128((const __m128i*)(ptr + 2)); + + a = v_uint64x2(_mm_unpacklo_epi64(t0, t1)); + b = v_uint64x2(_mm_unpackhi_epi64(t0, t1)); +} + +inline void v_load_deinterleave(const uint64 *ptr, v_uint64x2& a, v_uint64x2& b, v_uint64x2& c) +{ + __m128i t0 = _mm_loadu_si128((const __m128i*)ptr); // a0, b0 + __m128i t1 = _mm_loadu_si128((const __m128i*)(ptr + 2)); // c0, a1 + __m128i t2 = _mm_loadu_si128((const __m128i*)(ptr + 4)); // b1, c1 + + t1 = _mm_shuffle_epi32(t1, 0x4e); // a1, c0 + + a = v_uint64x2(_mm_unpacklo_epi64(t0, t1)); + b = v_uint64x2(_mm_unpacklo_epi64(_mm_unpackhi_epi64(t0, t0), t2)); + c = v_uint64x2(_mm_unpackhi_epi64(t1, t2)); +} + +inline void v_load_deinterleave(const uint64 *ptr, v_uint64x2& a, + v_uint64x2& b, v_uint64x2& c, v_uint64x2& d) +{ + __m128i t0 = _mm_loadu_si128((const __m128i*)ptr); // a0 b0 + __m128i t1 = _mm_loadu_si128((const __m128i*)(ptr + 2)); // c0 d0 + __m128i t2 = _mm_loadu_si128((const __m128i*)(ptr + 4)); // a1 b1 + __m128i t3 = _mm_loadu_si128((const __m128i*)(ptr + 6)); // c1 d1 + + a = v_uint64x2(_mm_unpacklo_epi64(t0, t2)); + b = v_uint64x2(_mm_unpackhi_epi64(t0, t2)); + c = v_uint64x2(_mm_unpacklo_epi64(t1, t3)); + d = v_uint64x2(_mm_unpackhi_epi64(t1, t3)); +} + +// store interleave + +inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, + hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + __m128i v0 = _mm_unpacklo_epi8(a.val, b.val); + __m128i v1 = _mm_unpackhi_epi8(a.val, b.val); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_si128((__m128i*)(ptr), v0); + _mm_stream_si128((__m128i*)(ptr + 16), v1); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_si128((__m128i*)(ptr), v0); + _mm_store_si128((__m128i*)(ptr + 16), v1); + } + else + { + _mm_storeu_si128((__m128i*)(ptr), v0); + _mm_storeu_si128((__m128i*)(ptr + 16), v1); + } +} + +inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, + const v_uint8x16& c, hal::StoreMode mode = hal::STORE_UNALIGNED) +{ +#if CV_SSE4_1 + const __m128i sh_a = _mm_setr_epi8(0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5); + const __m128i sh_b = _mm_setr_epi8(5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10); + const __m128i sh_c = _mm_setr_epi8(10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15); + __m128i a0 = _mm_shuffle_epi8(a.val, sh_a); + __m128i b0 = _mm_shuffle_epi8(b.val, sh_b); + __m128i c0 = _mm_shuffle_epi8(c.val, sh_c); + + const __m128i m0 = _mm_setr_epi8(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0); + const __m128i m1 = _mm_setr_epi8(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); + __m128i v0 = _mm_blendv_epi8(_mm_blendv_epi8(a0, b0, m1), c0, m0); + __m128i v1 = _mm_blendv_epi8(_mm_blendv_epi8(b0, c0, m1), a0, m0); + __m128i v2 = _mm_blendv_epi8(_mm_blendv_epi8(c0, a0, m1), b0, m0); +#elif CV_SSSE3 + const __m128i m0 = _mm_setr_epi8(0, 6, 11, 1, 7, 12, 2, 8, 13, 3, 9, 14, 4, 10, 15, 5); + const __m128i m1 = _mm_setr_epi8(5, 11, 0, 6, 12, 1, 7, 13, 2, 8, 14, 3, 9, 15, 4, 10); + const __m128i m2 = _mm_setr_epi8(10, 0, 5, 11, 1, 6, 12, 2, 7, 13, 3, 8, 14, 4, 9, 15); + + __m128i t0 = _mm_alignr_epi8(b.val, _mm_slli_si128(a.val, 10), 5); + t0 = _mm_alignr_epi8(c.val, t0, 5); + __m128i v0 = _mm_shuffle_epi8(t0, m0); + + __m128i t1 = _mm_alignr_epi8(_mm_srli_si128(b.val, 5), _mm_slli_si128(a.val, 5), 6); + t1 = _mm_alignr_epi8(_mm_srli_si128(c.val, 5), t1, 5); + __m128i v1 = _mm_shuffle_epi8(t1, m1); + + __m128i t2 = _mm_alignr_epi8(_mm_srli_si128(c.val, 10), b.val, 11); + t2 = _mm_alignr_epi8(t2, a.val, 11); + __m128i v2 = _mm_shuffle_epi8(t2, m2); +#else + __m128i z = _mm_setzero_si128(); + __m128i ab0 = _mm_unpacklo_epi8(a.val, b.val); + __m128i ab1 = _mm_unpackhi_epi8(a.val, b.val); + __m128i c0 = _mm_unpacklo_epi8(c.val, z); + __m128i c1 = _mm_unpackhi_epi8(c.val, z); + + __m128i p00 = _mm_unpacklo_epi16(ab0, c0); + __m128i p01 = _mm_unpackhi_epi16(ab0, c0); + __m128i p02 = _mm_unpacklo_epi16(ab1, c1); + __m128i p03 = _mm_unpackhi_epi16(ab1, c1); + + __m128i p10 = _mm_unpacklo_epi32(p00, p01); + __m128i p11 = _mm_unpackhi_epi32(p00, p01); + __m128i p12 = _mm_unpacklo_epi32(p02, p03); + __m128i p13 = _mm_unpackhi_epi32(p02, p03); + + __m128i p20 = _mm_unpacklo_epi64(p10, p11); + __m128i p21 = _mm_unpackhi_epi64(p10, p11); + __m128i p22 = _mm_unpacklo_epi64(p12, p13); + __m128i p23 = _mm_unpackhi_epi64(p12, p13); + + p20 = _mm_slli_si128(p20, 1); + p22 = _mm_slli_si128(p22, 1); + + __m128i p30 = _mm_slli_epi64(_mm_unpacklo_epi32(p20, p21), 8); + __m128i p31 = _mm_srli_epi64(_mm_unpackhi_epi32(p20, p21), 8); + __m128i p32 = _mm_slli_epi64(_mm_unpacklo_epi32(p22, p23), 8); + __m128i p33 = _mm_srli_epi64(_mm_unpackhi_epi32(p22, p23), 8); + + __m128i p40 = _mm_unpacklo_epi64(p30, p31); + __m128i p41 = _mm_unpackhi_epi64(p30, p31); + __m128i p42 = _mm_unpacklo_epi64(p32, p33); + __m128i p43 = _mm_unpackhi_epi64(p32, p33); + + __m128i v0 = _mm_or_si128(_mm_srli_si128(p40, 2), _mm_slli_si128(p41, 10)); + __m128i v1 = _mm_or_si128(_mm_srli_si128(p41, 6), _mm_slli_si128(p42, 6)); + __m128i v2 = _mm_or_si128(_mm_srli_si128(p42, 10), _mm_slli_si128(p43, 2)); +#endif + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_si128((__m128i*)(ptr), v0); + _mm_stream_si128((__m128i*)(ptr + 16), v1); + _mm_stream_si128((__m128i*)(ptr + 32), v2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_si128((__m128i*)(ptr), v0); + _mm_store_si128((__m128i*)(ptr + 16), v1); + _mm_store_si128((__m128i*)(ptr + 32), v2); + } + else + { + _mm_storeu_si128((__m128i*)(ptr), v0); + _mm_storeu_si128((__m128i*)(ptr + 16), v1); + _mm_storeu_si128((__m128i*)(ptr + 32), v2); + } +} + +inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, + const v_uint8x16& c, const v_uint8x16& d, + hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + // a0 a1 a2 a3 .... + // b0 b1 b2 b3 .... + // c0 c1 c2 c3 .... + // d0 d1 d2 d3 .... + __m128i u0 = _mm_unpacklo_epi8(a.val, c.val); // a0 c0 a1 c1 ... + __m128i u1 = _mm_unpackhi_epi8(a.val, c.val); // a8 c8 a9 c9 ... + __m128i u2 = _mm_unpacklo_epi8(b.val, d.val); // b0 d0 b1 d1 ... + __m128i u3 = _mm_unpackhi_epi8(b.val, d.val); // b8 d8 b9 d9 ... + + __m128i v0 = _mm_unpacklo_epi8(u0, u2); // a0 b0 c0 d0 ... + __m128i v1 = _mm_unpackhi_epi8(u0, u2); // a4 b4 c4 d4 ... + __m128i v2 = _mm_unpacklo_epi8(u1, u3); // a8 b8 c8 d8 ... + __m128i v3 = _mm_unpackhi_epi8(u1, u3); // a12 b12 c12 d12 ... + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_si128((__m128i*)(ptr), v0); + _mm_stream_si128((__m128i*)(ptr + 16), v1); + _mm_stream_si128((__m128i*)(ptr + 32), v2); + _mm_stream_si128((__m128i*)(ptr + 48), v3); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_si128((__m128i*)(ptr), v0); + _mm_store_si128((__m128i*)(ptr + 16), v1); + _mm_store_si128((__m128i*)(ptr + 32), v2); + _mm_store_si128((__m128i*)(ptr + 48), v3); + } + else + { + _mm_storeu_si128((__m128i*)(ptr), v0); + _mm_storeu_si128((__m128i*)(ptr + 16), v1); + _mm_storeu_si128((__m128i*)(ptr + 32), v2); + _mm_storeu_si128((__m128i*)(ptr + 48), v3); + } +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, + hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + __m128i v0 = _mm_unpacklo_epi16(a.val, b.val); + __m128i v1 = _mm_unpackhi_epi16(a.val, b.val); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_si128((__m128i*)(ptr), v0); + _mm_stream_si128((__m128i*)(ptr + 8), v1); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_si128((__m128i*)(ptr), v0); + _mm_store_si128((__m128i*)(ptr + 8), v1); + } + else + { + _mm_storeu_si128((__m128i*)(ptr), v0); + _mm_storeu_si128((__m128i*)(ptr + 8), v1); + } +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, + const v_uint16x8& b, const v_uint16x8& c, + hal::StoreMode mode = hal::STORE_UNALIGNED) +{ +#if CV_SSE4_1 + const __m128i sh_a = _mm_setr_epi8(0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11); + const __m128i sh_b = _mm_setr_epi8(10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5); + const __m128i sh_c = _mm_setr_epi8(4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15); + __m128i a0 = _mm_shuffle_epi8(a.val, sh_a); + __m128i b0 = _mm_shuffle_epi8(b.val, sh_b); + __m128i c0 = _mm_shuffle_epi8(c.val, sh_c); + + __m128i v0 = _mm_blend_epi16(_mm_blend_epi16(a0, b0, 0x92), c0, 0x24); + __m128i v1 = _mm_blend_epi16(_mm_blend_epi16(c0, a0, 0x92), b0, 0x24); + __m128i v2 = _mm_blend_epi16(_mm_blend_epi16(b0, c0, 0x92), a0, 0x24); +#else + __m128i z = _mm_setzero_si128(); + __m128i ab0 = _mm_unpacklo_epi16(a.val, b.val); + __m128i ab1 = _mm_unpackhi_epi16(a.val, b.val); + __m128i c0 = _mm_unpacklo_epi16(c.val, z); + __m128i c1 = _mm_unpackhi_epi16(c.val, z); + + __m128i p10 = _mm_unpacklo_epi32(ab0, c0); + __m128i p11 = _mm_unpackhi_epi32(ab0, c0); + __m128i p12 = _mm_unpacklo_epi32(ab1, c1); + __m128i p13 = _mm_unpackhi_epi32(ab1, c1); + + __m128i p20 = _mm_unpacklo_epi64(p10, p11); + __m128i p21 = _mm_unpackhi_epi64(p10, p11); + __m128i p22 = _mm_unpacklo_epi64(p12, p13); + __m128i p23 = _mm_unpackhi_epi64(p12, p13); + + p20 = _mm_slli_si128(p20, 2); + p22 = _mm_slli_si128(p22, 2); + + __m128i p30 = _mm_unpacklo_epi64(p20, p21); + __m128i p31 = _mm_unpackhi_epi64(p20, p21); + __m128i p32 = _mm_unpacklo_epi64(p22, p23); + __m128i p33 = _mm_unpackhi_epi64(p22, p23); + + __m128i v0 = _mm_or_si128(_mm_srli_si128(p30, 2), _mm_slli_si128(p31, 10)); + __m128i v1 = _mm_or_si128(_mm_srli_si128(p31, 6), _mm_slli_si128(p32, 6)); + __m128i v2 = _mm_or_si128(_mm_srli_si128(p32, 10), _mm_slli_si128(p33, 2)); +#endif + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_si128((__m128i*)(ptr), v0); + _mm_stream_si128((__m128i*)(ptr + 8), v1); + _mm_stream_si128((__m128i*)(ptr + 16), v2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_si128((__m128i*)(ptr), v0); + _mm_store_si128((__m128i*)(ptr + 8), v1); + _mm_store_si128((__m128i*)(ptr + 16), v2); + } + else + { + _mm_storeu_si128((__m128i*)(ptr), v0); + _mm_storeu_si128((__m128i*)(ptr + 8), v1); + _mm_storeu_si128((__m128i*)(ptr + 16), v2); + } +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, + const v_uint16x8& c, const v_uint16x8& d, + hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + // a0 a1 a2 a3 .... + // b0 b1 b2 b3 .... + // c0 c1 c2 c3 .... + // d0 d1 d2 d3 .... + __m128i u0 = _mm_unpacklo_epi16(a.val, c.val); // a0 c0 a1 c1 ... + __m128i u1 = _mm_unpackhi_epi16(a.val, c.val); // a4 c4 a5 c5 ... + __m128i u2 = _mm_unpacklo_epi16(b.val, d.val); // b0 d0 b1 d1 ... + __m128i u3 = _mm_unpackhi_epi16(b.val, d.val); // b4 d4 b5 d5 ... + + __m128i v0 = _mm_unpacklo_epi16(u0, u2); // a0 b0 c0 d0 ... + __m128i v1 = _mm_unpackhi_epi16(u0, u2); // a2 b2 c2 d2 ... + __m128i v2 = _mm_unpacklo_epi16(u1, u3); // a4 b4 c4 d4 ... + __m128i v3 = _mm_unpackhi_epi16(u1, u3); // a6 b6 c6 d6 ... + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_si128((__m128i*)(ptr), v0); + _mm_stream_si128((__m128i*)(ptr + 8), v1); + _mm_stream_si128((__m128i*)(ptr + 16), v2); + _mm_stream_si128((__m128i*)(ptr + 24), v3); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_si128((__m128i*)(ptr), v0); + _mm_store_si128((__m128i*)(ptr + 8), v1); + _mm_store_si128((__m128i*)(ptr + 16), v2); + _mm_store_si128((__m128i*)(ptr + 24), v3); + } + else + { + _mm_storeu_si128((__m128i*)(ptr), v0); + _mm_storeu_si128((__m128i*)(ptr + 8), v1); + _mm_storeu_si128((__m128i*)(ptr + 16), v2); + _mm_storeu_si128((__m128i*)(ptr + 24), v3); + } +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, + hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + __m128i v0 = _mm_unpacklo_epi32(a.val, b.val); + __m128i v1 = _mm_unpackhi_epi32(a.val, b.val); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_si128((__m128i*)(ptr), v0); + _mm_stream_si128((__m128i*)(ptr + 4), v1); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_si128((__m128i*)(ptr), v0); + _mm_store_si128((__m128i*)(ptr + 4), v1); + } + else + { + _mm_storeu_si128((__m128i*)(ptr), v0); + _mm_storeu_si128((__m128i*)(ptr + 4), v1); + } +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, + const v_uint32x4& c, hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + v_uint32x4 z = v_setzero_u32(), u0, u1, u2, u3; + v_transpose4x4(a, b, c, z, u0, u1, u2, u3); + + __m128i v0 = _mm_or_si128(u0.val, _mm_slli_si128(u1.val, 12)); + __m128i v1 = _mm_or_si128(_mm_srli_si128(u1.val, 4), _mm_slli_si128(u2.val, 8)); + __m128i v2 = _mm_or_si128(_mm_srli_si128(u2.val, 8), _mm_slli_si128(u3.val, 4)); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_si128((__m128i*)(ptr), v0); + _mm_stream_si128((__m128i*)(ptr + 4), v1); + _mm_stream_si128((__m128i*)(ptr + 8), v2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_si128((__m128i*)(ptr), v0); + _mm_store_si128((__m128i*)(ptr + 4), v1); + _mm_store_si128((__m128i*)(ptr + 8), v2); + } + else + { + _mm_storeu_si128((__m128i*)(ptr), v0); + _mm_storeu_si128((__m128i*)(ptr + 4), v1); + _mm_storeu_si128((__m128i*)(ptr + 8), v2); + } +} + +inline void v_store_interleave(unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, + const v_uint32x4& c, const v_uint32x4& d, + hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + v_uint32x4 v0, v1, v2, v3; + v_transpose4x4(a, b, c, d, v0, v1, v2, v3); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_si128((__m128i*)(ptr), v0.val); + _mm_stream_si128((__m128i*)(ptr + 4), v1.val); + _mm_stream_si128((__m128i*)(ptr + 8), v2.val); + _mm_stream_si128((__m128i*)(ptr + 12), v3.val); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_si128((__m128i*)(ptr), v0.val); + _mm_store_si128((__m128i*)(ptr + 4), v1.val); + _mm_store_si128((__m128i*)(ptr + 8), v2.val); + _mm_store_si128((__m128i*)(ptr + 12), v3.val); + } + else + { + _mm_storeu_si128((__m128i*)(ptr), v0.val); + _mm_storeu_si128((__m128i*)(ptr + 4), v1.val); + _mm_storeu_si128((__m128i*)(ptr + 8), v2.val); + _mm_storeu_si128((__m128i*)(ptr + 12), v3.val); + } +} + +// 2-channel, float only +inline void v_store_interleave(float* ptr, const v_float32x4& a, const v_float32x4& b, + hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + __m128 v0 = _mm_unpacklo_ps(a.val, b.val); // a0 b0 a1 b1 + __m128 v1 = _mm_unpackhi_ps(a.val, b.val); // a2 b2 a3 b3 + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_ps(ptr, v0); + _mm_stream_ps(ptr + 4, v1); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_ps(ptr, v0); + _mm_store_ps(ptr + 4, v1); + } + else + { + _mm_storeu_ps(ptr, v0); + _mm_storeu_ps(ptr + 4, v1); + } +} + +inline void v_store_interleave(float* ptr, const v_float32x4& a, const v_float32x4& b, + const v_float32x4& c, hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + __m128 u0 = _mm_shuffle_ps(a.val, b.val, _MM_SHUFFLE(0, 0, 0, 0)); + __m128 u1 = _mm_shuffle_ps(c.val, a.val, _MM_SHUFFLE(1, 1, 0, 0)); + __m128 v0 = _mm_shuffle_ps(u0, u1, _MM_SHUFFLE(2, 0, 2, 0)); + __m128 u2 = _mm_shuffle_ps(b.val, c.val, _MM_SHUFFLE(1, 1, 1, 1)); + __m128 u3 = _mm_shuffle_ps(a.val, b.val, _MM_SHUFFLE(2, 2, 2, 2)); + __m128 v1 = _mm_shuffle_ps(u2, u3, _MM_SHUFFLE(2, 0, 2, 0)); + __m128 u4 = _mm_shuffle_ps(c.val, a.val, _MM_SHUFFLE(3, 3, 2, 2)); + __m128 u5 = _mm_shuffle_ps(b.val, c.val, _MM_SHUFFLE(3, 3, 3, 3)); + __m128 v2 = _mm_shuffle_ps(u4, u5, _MM_SHUFFLE(2, 0, 2, 0)); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_ps(ptr, v0); + _mm_stream_ps(ptr + 4, v1); + _mm_stream_ps(ptr + 8, v2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_ps(ptr, v0); + _mm_store_ps(ptr + 4, v1); + _mm_store_ps(ptr + 8, v2); + } + else + { + _mm_storeu_ps(ptr, v0); + _mm_storeu_ps(ptr + 4, v1); + _mm_storeu_ps(ptr + 8, v2); + } +} + +inline void v_store_interleave(float* ptr, const v_float32x4& a, const v_float32x4& b, + const v_float32x4& c, const v_float32x4& d, + hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + __m128 u0 = _mm_unpacklo_ps(a.val, c.val); + __m128 u1 = _mm_unpacklo_ps(b.val, d.val); + __m128 u2 = _mm_unpackhi_ps(a.val, c.val); + __m128 u3 = _mm_unpackhi_ps(b.val, d.val); + __m128 v0 = _mm_unpacklo_ps(u0, u1); + __m128 v2 = _mm_unpacklo_ps(u2, u3); + __m128 v1 = _mm_unpackhi_ps(u0, u1); + __m128 v3 = _mm_unpackhi_ps(u2, u3); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_ps(ptr, v0); + _mm_stream_ps(ptr + 4, v1); + _mm_stream_ps(ptr + 8, v2); + _mm_stream_ps(ptr + 12, v3); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_ps(ptr, v0); + _mm_store_ps(ptr + 4, v1); + _mm_store_ps(ptr + 8, v2); + _mm_store_ps(ptr + 12, v3); + } + else + { + _mm_storeu_ps(ptr, v0); + _mm_storeu_ps(ptr + 4, v1); + _mm_storeu_ps(ptr + 8, v2); + _mm_storeu_ps(ptr + 12, v3); + } +} + +inline void v_store_interleave(uint64 *ptr, const v_uint64x2& a, const v_uint64x2& b, + hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + __m128i v0 = _mm_unpacklo_epi64(a.val, b.val); + __m128i v1 = _mm_unpackhi_epi64(a.val, b.val); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_si128((__m128i*)(ptr), v0); + _mm_stream_si128((__m128i*)(ptr + 2), v1); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_si128((__m128i*)(ptr), v0); + _mm_store_si128((__m128i*)(ptr + 2), v1); + } + else + { + _mm_storeu_si128((__m128i*)(ptr), v0); + _mm_storeu_si128((__m128i*)(ptr + 2), v1); + } +} + +inline void v_store_interleave(uint64 *ptr, const v_uint64x2& a, const v_uint64x2& b, + const v_uint64x2& c, hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + __m128i v0 = _mm_unpacklo_epi64(a.val, b.val); + __m128i v1 = _mm_unpacklo_epi64(c.val, _mm_unpackhi_epi64(a.val, a.val)); + __m128i v2 = _mm_unpackhi_epi64(b.val, c.val); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_si128((__m128i*)(ptr), v0); + _mm_stream_si128((__m128i*)(ptr + 2), v1); + _mm_stream_si128((__m128i*)(ptr + 4), v2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_si128((__m128i*)(ptr), v0); + _mm_store_si128((__m128i*)(ptr + 2), v1); + _mm_store_si128((__m128i*)(ptr + 4), v2); + } + else + { + _mm_storeu_si128((__m128i*)(ptr), v0); + _mm_storeu_si128((__m128i*)(ptr + 2), v1); + _mm_storeu_si128((__m128i*)(ptr + 4), v2); + } +} + +inline void v_store_interleave(uint64 *ptr, const v_uint64x2& a, const v_uint64x2& b, + const v_uint64x2& c, const v_uint64x2& d, + hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + __m128i v0 = _mm_unpacklo_epi64(a.val, b.val); + __m128i v1 = _mm_unpacklo_epi64(c.val, d.val); + __m128i v2 = _mm_unpackhi_epi64(a.val, b.val); + __m128i v3 = _mm_unpackhi_epi64(c.val, d.val); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_si128((__m128i*)(ptr), v0); + _mm_stream_si128((__m128i*)(ptr + 2), v1); + _mm_stream_si128((__m128i*)(ptr + 4), v2); + _mm_stream_si128((__m128i*)(ptr + 6), v3); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_si128((__m128i*)(ptr), v0); + _mm_store_si128((__m128i*)(ptr + 2), v1); + _mm_store_si128((__m128i*)(ptr + 4), v2); + _mm_store_si128((__m128i*)(ptr + 6), v3); + } + else + { + _mm_storeu_si128((__m128i*)(ptr), v0); + _mm_storeu_si128((__m128i*)(ptr + 2), v1); + _mm_storeu_si128((__m128i*)(ptr + 4), v2); + _mm_storeu_si128((__m128i*)(ptr + 6), v3); + } +} + +#define OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(_Tpvec0, _Tp0, suffix0, _Tpvec1, _Tp1, suffix1) \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0 ) \ +{ \ + _Tpvec1 a1, b1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ +} \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0 ) \ +{ \ + _Tpvec1 a1, b1, c1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ + c0 = v_reinterpret_as_##suffix0(c1); \ +} \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0, _Tpvec0& d0 ) \ +{ \ + _Tpvec1 a1, b1, c1, d1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1, d1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ + c0 = v_reinterpret_as_##suffix0(c1); \ + d0 = v_reinterpret_as_##suffix0(d1); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + hal::StoreMode mode = hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, mode); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + const _Tpvec0& c0, hal::StoreMode mode = hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, c1, mode); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + const _Tpvec0& c0, const _Tpvec0& d0, \ + hal::StoreMode mode = hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ + _Tpvec1 d1 = v_reinterpret_as_##suffix1(d0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, c1, d1, mode); \ +} + +OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(v_int8x16, schar, s8, v_uint8x16, uchar, u8) +OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(v_int16x8, short, s16, v_uint16x8, ushort, u16) +OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(v_int32x4, int, s32, v_uint32x4, unsigned, u32) +OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(v_int64x2, int64, s64, v_uint64x2, uint64, u64) +OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(v_float64x2, double, f64, v_uint64x2, uint64, u64) + +inline v_float32x4 v_cvt_f32(const v_int32x4& a) +{ + return v_float32x4(_mm_cvtepi32_ps(a.val)); +} + +inline v_float32x4 v_cvt_f32(const v_float64x2& a) +{ + return v_float32x4(_mm_cvtpd_ps(a.val)); +} + +inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) +{ + return v_float32x4(_mm_movelh_ps(_mm_cvtpd_ps(a.val), _mm_cvtpd_ps(b.val))); +} + +inline v_float64x2 v_cvt_f64(const v_int32x4& a) +{ + return v_float64x2(_mm_cvtepi32_pd(a.val)); +} + +inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) +{ + return v_float64x2(_mm_cvtepi32_pd(_mm_srli_si128(a.val,8))); +} + +inline v_float64x2 v_cvt_f64(const v_float32x4& a) +{ + return v_float64x2(_mm_cvtps_pd(a.val)); +} + +inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) +{ + return v_float64x2(_mm_cvtps_pd(_mm_movehl_ps(a.val, a.val))); +} + +// from (Mysticial and wim) https://stackoverflow.com/q/41144668 +inline v_float64x2 v_cvt_f64(const v_int64x2& v) +{ + // constants encoded as floating-point + __m128i magic_i_hi32 = _mm_set1_epi64x(0x4530000080000000); // 2^84 + 2^63 + __m128i magic_i_all = _mm_set1_epi64x(0x4530000080100000); // 2^84 + 2^63 + 2^52 + __m128d magic_d_all = _mm_castsi128_pd(magic_i_all); + // Blend the 32 lowest significant bits of v with magic_int_lo +#if CV_SSE4_1 + __m128i magic_i_lo = _mm_set1_epi64x(0x4330000000000000); // 2^52 + __m128i v_lo = _mm_blend_epi16(v.val, magic_i_lo, 0xcc); +#else + __m128i magic_i_lo = _mm_set1_epi32(0x43300000); // 2^52 + __m128i v_lo = _mm_unpacklo_epi32(_mm_shuffle_epi32(v.val, _MM_SHUFFLE(0, 0, 2, 0)), magic_i_lo); +#endif + // Extract the 32 most significant bits of v + __m128i v_hi = _mm_srli_epi64(v.val, 32); + // Flip the msb of v_hi and blend with 0x45300000 + v_hi = _mm_xor_si128(v_hi, magic_i_hi32); + // Compute in double precision + __m128d v_hi_dbl = _mm_sub_pd(_mm_castsi128_pd(v_hi), magic_d_all); + // (v_hi - magic_d_all) + v_lo Do not assume associativity of floating point addition + __m128d result = _mm_add_pd(v_hi_dbl, _mm_castsi128_pd(v_lo)); + return v_float64x2(result); +} + +////////////// Lookup table access //////////////////// + +inline v_int8x16 v_lut(const schar* tab, const int* idx) +{ +#if defined(_MSC_VER) + return v_int8x16(_mm_setr_epi8(tab[idx[0]], tab[idx[1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], tab[idx[ 5]], tab[idx[ 6]], tab[idx[ 7]], + tab[idx[8]], tab[idx[9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]])); +#else + return v_int8x16(_mm_setr_epi64( + _mm_setr_pi8(tab[idx[0]], tab[idx[1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], tab[idx[ 5]], tab[idx[ 6]], tab[idx[ 7]]), + _mm_setr_pi8(tab[idx[8]], tab[idx[9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]]) + )); +#endif +} +inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx) +{ +#if defined(_MSC_VER) + return v_int8x16(_mm_setr_epi16(*(const short*)(tab + idx[0]), *(const short*)(tab + idx[1]), *(const short*)(tab + idx[2]), *(const short*)(tab + idx[3]), + *(const short*)(tab + idx[4]), *(const short*)(tab + idx[5]), *(const short*)(tab + idx[6]), *(const short*)(tab + idx[7]))); +#else + return v_int8x16(_mm_setr_epi64( + _mm_setr_pi16(*(const short*)(tab + idx[0]), *(const short*)(tab + idx[1]), *(const short*)(tab + idx[2]), *(const short*)(tab + idx[3])), + _mm_setr_pi16(*(const short*)(tab + idx[4]), *(const short*)(tab + idx[5]), *(const short*)(tab + idx[6]), *(const short*)(tab + idx[7])) + )); +#endif +} +inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) +{ +#if defined(_MSC_VER) + return v_int8x16(_mm_setr_epi32(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), + *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]))); +#else + return v_int8x16(_mm_setr_epi64( + _mm_setr_pi32(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1])), + _mm_setr_pi32(*(const int*)(tab + idx[2]), *(const int*)(tab + idx[3])) + )); +#endif +} +inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((const schar *)tab, idx)); } +inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((const schar *)tab, idx)); } +inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((const schar *)tab, idx)); } + +inline v_int16x8 v_lut(const short* tab, const int* idx) +{ +#if defined(_MSC_VER) + return v_int16x8(_mm_setr_epi16(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], + tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]])); +#else + return v_int16x8(_mm_setr_epi64( + _mm_setr_pi16(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]), + _mm_setr_pi16(tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]]) + )); +#endif +} +inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) +{ +#if defined(_MSC_VER) + return v_int16x8(_mm_setr_epi32(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), + *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]))); +#else + return v_int16x8(_mm_setr_epi64( + _mm_setr_pi32(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1])), + _mm_setr_pi32(*(const int*)(tab + idx[2]), *(const int*)(tab + idx[3])) + )); +#endif +} +inline v_int16x8 v_lut_quads(const short* tab, const int* idx) +{ + return v_int16x8(_mm_set_epi64x(*(const int64_t*)(tab + idx[1]), *(const int64_t*)(tab + idx[0]))); +} +inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((const short *)tab, idx)); } +inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((const short *)tab, idx)); } +inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((const short *)tab, idx)); } + +inline v_int32x4 v_lut(const int* tab, const int* idx) +{ +#if defined(_MSC_VER) + return v_int32x4(_mm_setr_epi32(tab[idx[0]], tab[idx[1]], + tab[idx[2]], tab[idx[3]])); +#else + return v_int32x4(_mm_setr_epi64( + _mm_setr_pi32(tab[idx[0]], tab[idx[1]]), + _mm_setr_pi32(tab[idx[2]], tab[idx[3]]) + )); +#endif +} +inline v_int32x4 v_lut_pairs(const int* tab, const int* idx) +{ + return v_int32x4(_mm_set_epi64x(*(const int64_t*)(tab + idx[1]), *(const int64_t*)(tab + idx[0]))); +} +inline v_int32x4 v_lut_quads(const int* tab, const int* idx) +{ + return v_int32x4(_mm_loadu_si128((const __m128i*)(tab + idx[0]))); +} +inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((const int *)tab, idx)); } +inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((const int *)tab, idx)); } +inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((const int *)tab, idx)); } + +inline v_int64x2 v_lut(const int64_t* tab, const int* idx) +{ + return v_int64x2(_mm_set_epi64x(tab[idx[1]], tab[idx[0]])); +} +inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) +{ + return v_int64x2(_mm_loadu_si128((const __m128i*)(tab + idx[0]))); +} +inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } +inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } + +inline v_float32x4 v_lut(const float* tab, const int* idx) +{ + return v_float32x4(_mm_setr_ps(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]])); +} +inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) { return v_reinterpret_as_f32(v_lut_pairs((const int *)tab, idx)); } +inline v_float32x4 v_lut_quads(const float* tab, const int* idx) { return v_reinterpret_as_f32(v_lut_quads((const int *)tab, idx)); } + +inline v_float64x2 v_lut(const double* tab, const int* idx) +{ + return v_float64x2(_mm_setr_pd(tab[idx[0]], tab[idx[1]])); +} +inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) { return v_float64x2(_mm_castsi128_pd(_mm_loadu_si128((const __m128i*)(tab + idx[0])))); } + +inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) +{ + int CV_DECL_ALIGNED(32) idx[4]; + v_store_aligned(idx, idxvec); + return v_int32x4(_mm_setr_epi32(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]])); +} + +inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) +{ + return v_reinterpret_as_u32(v_lut((const int *)tab, idxvec)); +} + +inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) +{ + int CV_DECL_ALIGNED(32) idx[4]; + v_store_aligned(idx, idxvec); + return v_float32x4(_mm_setr_ps(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]])); +} + +inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) +{ + int idx[2]; + v_store_low(idx, idxvec); + return v_float64x2(_mm_setr_pd(tab[idx[0]], tab[idx[1]])); +} + +// loads pairs from the table and deinterleaves them, e.g. returns: +// x = (tab[idxvec[0], tab[idxvec[1]], tab[idxvec[2]], tab[idxvec[3]]), +// y = (tab[idxvec[0]+1], tab[idxvec[1]+1], tab[idxvec[2]+1], tab[idxvec[3]+1]) +// note that the indices are float's indices, not the float-pair indices. +// in theory, this function can be used to implement bilinear interpolation, +// when idxvec are the offsets within the image. +inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) +{ + int CV_DECL_ALIGNED(32) idx[4]; + v_store_aligned(idx, idxvec); + __m128 z = _mm_setzero_ps(); + __m128 xy01 = _mm_loadl_pi(z, (__m64*)(tab + idx[0])); + __m128 xy23 = _mm_loadl_pi(z, (__m64*)(tab + idx[2])); + xy01 = _mm_loadh_pi(xy01, (__m64*)(tab + idx[1])); + xy23 = _mm_loadh_pi(xy23, (__m64*)(tab + idx[3])); + __m128 xxyy02 = _mm_unpacklo_ps(xy01, xy23); + __m128 xxyy13 = _mm_unpackhi_ps(xy01, xy23); + x = v_float32x4(_mm_unpacklo_ps(xxyy02, xxyy13)); + y = v_float32x4(_mm_unpackhi_ps(xxyy02, xxyy13)); +} + +inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) +{ + int idx[2]; + v_store_low(idx, idxvec); + __m128d xy0 = _mm_loadu_pd(tab + idx[0]); + __m128d xy1 = _mm_loadu_pd(tab + idx[1]); + x = v_float64x2(_mm_unpacklo_pd(xy0, xy1)); + y = v_float64x2(_mm_unpackhi_pd(xy0, xy1)); +} + +inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) +{ +#if CV_SSSE3 + return v_int8x16(_mm_shuffle_epi8(vec.val, _mm_set_epi64x(0x0f0d0e0c0b090a08, 0x0705060403010200))); +#else + __m128i a = _mm_shufflelo_epi16(vec.val, _MM_SHUFFLE(3, 1, 2, 0)); + a = _mm_shufflehi_epi16(a, _MM_SHUFFLE(3, 1, 2, 0)); + a = _mm_shuffle_epi32(a, _MM_SHUFFLE(3, 1, 2, 0)); + return v_int8x16(_mm_unpacklo_epi8(a, _mm_unpackhi_epi64(a, a))); +#endif +} +inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } +inline v_int8x16 v_interleave_quads(const v_int8x16& vec) +{ +#if CV_SSSE3 + return v_int8x16(_mm_shuffle_epi8(vec.val, _mm_set_epi64x(0x0f0b0e0a0d090c08, 0x0703060205010400))); +#else + __m128i a = _mm_shuffle_epi32(vec.val, _MM_SHUFFLE(3, 1, 2, 0)); + return v_int8x16(_mm_unpacklo_epi8(a, _mm_unpackhi_epi64(a, a))); +#endif +} +inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) +{ +#if CV_SSSE3 + return v_int16x8(_mm_shuffle_epi8(vec.val, _mm_set_epi64x(0x0f0e0b0a0d0c0908, 0x0706030205040100))); +#else + __m128i a = _mm_shufflelo_epi16(vec.val, _MM_SHUFFLE(3, 1, 2, 0)); + return v_int16x8(_mm_shufflehi_epi16(a, _MM_SHUFFLE(3, 1, 2, 0))); +#endif +} +inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } +inline v_int16x8 v_interleave_quads(const v_int16x8& vec) +{ +#if CV_SSSE3 + return v_int16x8(_mm_shuffle_epi8(vec.val, _mm_set_epi64x(0x0f0e07060d0c0504, 0x0b0a030209080100))); +#else + return v_int16x8(_mm_unpacklo_epi16(vec.val, _mm_unpackhi_epi64(vec.val, vec.val))); +#endif +} +inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) +{ + return v_int32x4(_mm_shuffle_epi32(vec.val, _MM_SHUFFLE(3, 1, 2, 0))); +} +inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } +inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } + +inline v_int8x16 v_pack_triplets(const v_int8x16& vec) +{ +#if CV_SSSE3 + return v_int8x16(_mm_shuffle_epi8(vec.val, _mm_set_epi64x(0xffffff0f0e0d0c0a, 0x0908060504020100))); +#else + __m128i mask = _mm_set1_epi64x(0x00000000FFFFFFFF); + __m128i a = _mm_srli_si128(_mm_or_si128(_mm_andnot_si128(mask, vec.val), _mm_and_si128(mask, _mm_sll_epi32(vec.val, _mm_set_epi64x(0, 8)))), 1); + return v_int8x16(_mm_srli_si128(_mm_shufflelo_epi16(a, _MM_SHUFFLE(2, 1, 0, 3)), 2)); +#endif +} +inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_pack_triplets(const v_int16x8& vec) +{ +#if CV_SSSE3 + return v_int16x8(_mm_shuffle_epi8(vec.val, _mm_set_epi64x(0xffff0f0e0d0c0b0a, 0x0908050403020100))); +#else + return v_int16x8(_mm_srli_si128(_mm_shufflelo_epi16(vec.val, _MM_SHUFFLE(2, 1, 0, 3)), 2)); +#endif +} +inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } +inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } +inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } + +template +inline uchar v_extract_n(const v_uint8x16& v) +{ +#if CV_SSE4_1 + return (uchar)_mm_extract_epi8(v.val, i); +#else + return v_rotate_right(v).get0(); +#endif +} + +template +inline schar v_extract_n(const v_int8x16& v) +{ + return (schar)v_extract_n(v_reinterpret_as_u8(v)); +} + +template +inline ushort v_extract_n(const v_uint16x8& v) +{ + return (ushort)_mm_extract_epi16(v.val, i); +} + +template +inline short v_extract_n(const v_int16x8& v) +{ + return (short)v_extract_n(v_reinterpret_as_u16(v)); +} + +template +inline uint v_extract_n(const v_uint32x4& v) +{ +#if CV_SSE4_1 + return (uint)_mm_extract_epi32(v.val, i); +#else + return v_rotate_right(v).get0(); +#endif +} + +template +inline int v_extract_n(const v_int32x4& v) +{ + return (int)v_extract_n(v_reinterpret_as_u32(v)); +} + +template +inline uint64 v_extract_n(const v_uint64x2& v) +{ +#ifdef CV__SIMD_NATIVE_mm_extract_epi64 + return (uint64)_v128_extract_epi64(v.val); +#else + return v_rotate_right(v).get0(); +#endif +} + +template +inline int64 v_extract_n(const v_int64x2& v) +{ + return (int64)v_extract_n(v_reinterpret_as_u64(v)); +} + +template +inline float v_extract_n(const v_float32x4& v) +{ + union { uint iv; float fv; } d; + d.iv = v_extract_n(v_reinterpret_as_u32(v)); + return d.fv; +} + +template +inline double v_extract_n(const v_float64x2& v) +{ + union { uint64 iv; double dv; } d; + d.iv = v_extract_n(v_reinterpret_as_u64(v)); + return d.dv; +} + +template +inline v_int32x4 v_broadcast_element(const v_int32x4& v) +{ + return v_int32x4(_mm_shuffle_epi32(v.val, _MM_SHUFFLE(i,i,i,i))); +} + +template +inline v_uint32x4 v_broadcast_element(const v_uint32x4& v) +{ + return v_uint32x4(_mm_shuffle_epi32(v.val, _MM_SHUFFLE(i,i,i,i))); +} + +template +inline v_float32x4 v_broadcast_element(const v_float32x4& v) +{ + return v_float32x4(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE((char)i,(char)i,(char)i,(char)i))); +} + +////////////// FP16 support /////////////////////////// + +inline v_float32x4 v_load_expand(const hfloat* ptr) +{ +#if CV_FP16 + return v_float32x4(_mm_cvtph_ps(_mm_loadu_si128((const __m128i*)ptr))); +#else + const __m128i z = _mm_setzero_si128(), delta = _mm_set1_epi32(0x38000000); + const __m128i signmask = _mm_set1_epi32(0x80000000), maxexp = _mm_set1_epi32(0x7c000000); + const __m128 deltaf = _mm_castsi128_ps(_mm_set1_epi32(0x38800000)); + __m128i bits = _mm_unpacklo_epi16(z, _mm_loadl_epi64((const __m128i*)ptr)); // h << 16 + __m128i e = _mm_and_si128(bits, maxexp), sign = _mm_and_si128(bits, signmask); + __m128i t = _mm_add_epi32(_mm_srli_epi32(_mm_xor_si128(bits, sign), 3), delta); // ((h & 0x7fff) << 13) + delta + __m128i zt = _mm_castps_si128(_mm_sub_ps(_mm_castsi128_ps(_mm_add_epi32(t, _mm_set1_epi32(1 << 23))), deltaf)); + + t = _mm_add_epi32(t, _mm_and_si128(delta, _mm_cmpeq_epi32(maxexp, e))); + __m128i zmask = _mm_cmpeq_epi32(e, z); + __m128i ft = v_select_si128(zmask, zt, t); + return v_float32x4(_mm_castsi128_ps(_mm_or_si128(ft, sign))); +#endif +} + +inline void v_pack_store(hfloat* ptr, const v_float32x4& v) +{ +#if CV_FP16 + __m128i fp16_value = _mm_cvtps_ph(v.val, 0); + _mm_storel_epi64((__m128i*)ptr, fp16_value); +#else + const __m128i signmask = _mm_set1_epi32(0x80000000); + const __m128i rval = _mm_set1_epi32(0x3f000000); + + __m128i t = _mm_castps_si128(v.val); + __m128i sign = _mm_srai_epi32(_mm_and_si128(t, signmask), 16); + t = _mm_andnot_si128(signmask, t); + + __m128i finitemask = _mm_cmpgt_epi32(_mm_set1_epi32(0x47800000), t); + __m128i isnan = _mm_cmpgt_epi32(t, _mm_set1_epi32(0x7f800000)); + __m128i naninf = v_select_si128(isnan, _mm_set1_epi32(0x7e00), _mm_set1_epi32(0x7c00)); + __m128i tinymask = _mm_cmpgt_epi32(_mm_set1_epi32(0x38800000), t); + __m128i tt = _mm_castps_si128(_mm_add_ps(_mm_castsi128_ps(t), _mm_castsi128_ps(rval))); + tt = _mm_sub_epi32(tt, rval); + __m128i odd = _mm_and_si128(_mm_srli_epi32(t, 13), _mm_set1_epi32(1)); + __m128i nt = _mm_add_epi32(t, _mm_set1_epi32(0xc8000fff)); + nt = _mm_srli_epi32(_mm_add_epi32(nt, odd), 13); + t = v_select_si128(tinymask, tt, nt); + t = v_select_si128(finitemask, t, naninf); + t = _mm_or_si128(t, sign); + t = _mm_packs_epi32(t, t); + _mm_storel_epi64((__m128i*)ptr, t); +#endif +} + +inline void v_cleanup() {} + +#include "intrin_math.hpp" +inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } +inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } +inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } +inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } +inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } +inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } + +inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } +inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } +inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } +inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } +inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } + + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_sse_em.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_sse_em.hpp index 6fb088161a..654f9c7a34 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_sse_em.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_sse_em.hpp @@ -1,180 +1,180 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -#ifndef OPENCV_HAL_INTRIN_SSE_EM_HPP -#define OPENCV_HAL_INTRIN_SSE_EM_HPP - -namespace cv -{ - -//! @cond IGNORED - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -#define OPENCV_HAL_SSE_WRAP_1(fun, tp) \ - inline tp _v128_##fun(const tp& a) \ - { return _mm_##fun(a); } - -#define OPENCV_HAL_SSE_WRAP_2(fun, tp) \ - inline tp _v128_##fun(const tp& a, const tp& b) \ - { return _mm_##fun(a, b); } - -#define OPENCV_HAL_SSE_WRAP_3(fun, tp) \ - inline tp _v128_##fun(const tp& a, const tp& b, const tp& c) \ - { return _mm_##fun(a, b, c); } - -///////////////////////////// XOP ///////////////////////////// - -// [todo] define CV_XOP -#if 1 // CV_XOP -inline __m128i _v128_comgt_epu32(const __m128i& a, const __m128i& b) -{ - const __m128i delta = _mm_set1_epi32((int)0x80000000); - return _mm_cmpgt_epi32(_mm_xor_si128(a, delta), _mm_xor_si128(b, delta)); -} -// wrapping XOP -#else -OPENCV_HAL_SSE_WRAP_2(_v128_comgt_epu32, __m128i) -#endif // !CV_XOP - -///////////////////////////// SSE4.1 ///////////////////////////// - -#if !CV_SSE4_1 - -/** Swizzle **/ -inline __m128i _v128_blendv_epi8(const __m128i& a, const __m128i& b, const __m128i& mask) -{ return _mm_xor_si128(a, _mm_and_si128(_mm_xor_si128(b, a), mask)); } - -/** Convert **/ -// 8 >> 16 -inline __m128i _v128_cvtepu8_epi16(const __m128i& a) -{ - const __m128i z = _mm_setzero_si128(); - return _mm_unpacklo_epi8(a, z); -} -inline __m128i _v128_cvtepi8_epi16(const __m128i& a) -{ return _mm_srai_epi16(_mm_unpacklo_epi8(a, a), 8); } -// 8 >> 32 -inline __m128i _v128_cvtepu8_epi32(const __m128i& a) -{ - const __m128i z = _mm_setzero_si128(); - return _mm_unpacklo_epi16(_mm_unpacklo_epi8(a, z), z); -} -inline __m128i _v128_cvtepi8_epi32(const __m128i& a) -{ - __m128i r = _mm_unpacklo_epi8(a, a); - r = _mm_unpacklo_epi8(r, r); - return _mm_srai_epi32(r, 24); -} -// 16 >> 32 -inline __m128i _v128_cvtepu16_epi32(const __m128i& a) -{ - const __m128i z = _mm_setzero_si128(); - return _mm_unpacklo_epi16(a, z); -} -inline __m128i _v128_cvtepi16_epi32(const __m128i& a) -{ return _mm_srai_epi32(_mm_unpacklo_epi16(a, a), 16); } -// 32 >> 64 -inline __m128i _v128_cvtepu32_epi64(const __m128i& a) -{ - const __m128i z = _mm_setzero_si128(); - return _mm_unpacklo_epi32(a, z); -} -inline __m128i _v128_cvtepi32_epi64(const __m128i& a) -{ return _mm_unpacklo_epi32(a, _mm_srai_epi32(a, 31)); } - -/** Arithmetic **/ -inline __m128i _v128_mullo_epi32(const __m128i& a, const __m128i& b) -{ - __m128i c0 = _mm_mul_epu32(a, b); - __m128i c1 = _mm_mul_epu32(_mm_srli_epi64(a, 32), _mm_srli_epi64(b, 32)); - __m128i d0 = _mm_unpacklo_epi32(c0, c1); - __m128i d1 = _mm_unpackhi_epi32(c0, c1); - return _mm_unpacklo_epi64(d0, d1); -} - -/** Math **/ -inline __m128i _v128_min_epu32(const __m128i& a, const __m128i& b) -{ return _v128_blendv_epi8(a, b, _v128_comgt_epu32(a, b)); } - -// wrapping SSE4.1 -#else -OPENCV_HAL_SSE_WRAP_1(cvtepu8_epi16, __m128i) -OPENCV_HAL_SSE_WRAP_1(cvtepi8_epi16, __m128i) -OPENCV_HAL_SSE_WRAP_1(cvtepu8_epi32, __m128i) -OPENCV_HAL_SSE_WRAP_1(cvtepi8_epi32, __m128i) -OPENCV_HAL_SSE_WRAP_1(cvtepu16_epi32, __m128i) -OPENCV_HAL_SSE_WRAP_1(cvtepi16_epi32, __m128i) -OPENCV_HAL_SSE_WRAP_1(cvtepu32_epi64, __m128i) -OPENCV_HAL_SSE_WRAP_1(cvtepi32_epi64, __m128i) -OPENCV_HAL_SSE_WRAP_2(min_epu32, __m128i) -OPENCV_HAL_SSE_WRAP_2(mullo_epi32, __m128i) -OPENCV_HAL_SSE_WRAP_3(blendv_epi8, __m128i) -#endif // !CV_SSE4_1 - -///////////////////////////// Revolutionary ///////////////////////////// - -/** Convert **/ -// 16 << 8 -inline __m128i _v128_cvtepu8_epi16_high(const __m128i& a) -{ - const __m128i z = _mm_setzero_si128(); - return _mm_unpackhi_epi8(a, z); -} -inline __m128i _v128_cvtepi8_epi16_high(const __m128i& a) -{ return _mm_srai_epi16(_mm_unpackhi_epi8(a, a), 8); } -// 32 << 16 -inline __m128i _v128_cvtepu16_epi32_high(const __m128i& a) -{ - const __m128i z = _mm_setzero_si128(); - return _mm_unpackhi_epi16(a, z); -} -inline __m128i _v128_cvtepi16_epi32_high(const __m128i& a) -{ return _mm_srai_epi32(_mm_unpackhi_epi16(a, a), 16); } -// 64 << 32 -inline __m128i _v128_cvtepu32_epi64_high(const __m128i& a) -{ - const __m128i z = _mm_setzero_si128(); - return _mm_unpackhi_epi32(a, z); -} -inline __m128i _v128_cvtepi32_epi64_high(const __m128i& a) -{ return _mm_unpackhi_epi32(a, _mm_srai_epi32(a, 31)); } - -/** Miscellaneous **/ -inline __m128i _v128_packs_epu32(const __m128i& a, const __m128i& b) -{ - const __m128i m = _mm_set1_epi32(65535); - __m128i am = _v128_min_epu32(a, m); - __m128i bm = _v128_min_epu32(b, m); -#if CV_SSE4_1 - return _mm_packus_epi32(am, bm); -#else - const __m128i d = _mm_set1_epi32(32768), nd = _mm_set1_epi16(-32768); - am = _mm_sub_epi32(am, d); - bm = _mm_sub_epi32(bm, d); - am = _mm_packs_epi32(am, bm); - return _mm_sub_epi16(am, nd); -#endif -} - -template -inline int64 _v128_extract_epi64(const __m128i& a) -{ -#if defined(CV__SIMD_HAVE_mm_extract_epi64) || (CV_SSE4_1 && (defined(__x86_64__)/*GCC*/ || defined(_M_X64)/*MSVC*/)) -#define CV__SIMD_NATIVE_mm_extract_epi64 1 - return _mm_extract_epi64(a, i); -#else - CV_DECL_ALIGNED(16) int64 tmp[2]; - _mm_store_si128((__m128i*)tmp, a); - return tmp[i]; -#endif -} - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} // cv:: - -#endif // OPENCV_HAL_INTRIN_SSE_EM_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +#ifndef OPENCV_HAL_INTRIN_SSE_EM_HPP +#define OPENCV_HAL_INTRIN_SSE_EM_HPP + +namespace cv +{ + +//! @cond IGNORED + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +#define OPENCV_HAL_SSE_WRAP_1(fun, tp) \ + inline tp _v128_##fun(const tp& a) \ + { return _mm_##fun(a); } + +#define OPENCV_HAL_SSE_WRAP_2(fun, tp) \ + inline tp _v128_##fun(const tp& a, const tp& b) \ + { return _mm_##fun(a, b); } + +#define OPENCV_HAL_SSE_WRAP_3(fun, tp) \ + inline tp _v128_##fun(const tp& a, const tp& b, const tp& c) \ + { return _mm_##fun(a, b, c); } + +///////////////////////////// XOP ///////////////////////////// + +// [todo] define CV_XOP +#if 1 // CV_XOP +inline __m128i _v128_comgt_epu32(const __m128i& a, const __m128i& b) +{ + const __m128i delta = _mm_set1_epi32((int)0x80000000); + return _mm_cmpgt_epi32(_mm_xor_si128(a, delta), _mm_xor_si128(b, delta)); +} +// wrapping XOP +#else +OPENCV_HAL_SSE_WRAP_2(_v128_comgt_epu32, __m128i) +#endif // !CV_XOP + +///////////////////////////// SSE4.1 ///////////////////////////// + +#if !CV_SSE4_1 + +/** Swizzle **/ +inline __m128i _v128_blendv_epi8(const __m128i& a, const __m128i& b, const __m128i& mask) +{ return _mm_xor_si128(a, _mm_and_si128(_mm_xor_si128(b, a), mask)); } + +/** Convert **/ +// 8 >> 16 +inline __m128i _v128_cvtepu8_epi16(const __m128i& a) +{ + const __m128i z = _mm_setzero_si128(); + return _mm_unpacklo_epi8(a, z); +} +inline __m128i _v128_cvtepi8_epi16(const __m128i& a) +{ return _mm_srai_epi16(_mm_unpacklo_epi8(a, a), 8); } +// 8 >> 32 +inline __m128i _v128_cvtepu8_epi32(const __m128i& a) +{ + const __m128i z = _mm_setzero_si128(); + return _mm_unpacklo_epi16(_mm_unpacklo_epi8(a, z), z); +} +inline __m128i _v128_cvtepi8_epi32(const __m128i& a) +{ + __m128i r = _mm_unpacklo_epi8(a, a); + r = _mm_unpacklo_epi8(r, r); + return _mm_srai_epi32(r, 24); +} +// 16 >> 32 +inline __m128i _v128_cvtepu16_epi32(const __m128i& a) +{ + const __m128i z = _mm_setzero_si128(); + return _mm_unpacklo_epi16(a, z); +} +inline __m128i _v128_cvtepi16_epi32(const __m128i& a) +{ return _mm_srai_epi32(_mm_unpacklo_epi16(a, a), 16); } +// 32 >> 64 +inline __m128i _v128_cvtepu32_epi64(const __m128i& a) +{ + const __m128i z = _mm_setzero_si128(); + return _mm_unpacklo_epi32(a, z); +} +inline __m128i _v128_cvtepi32_epi64(const __m128i& a) +{ return _mm_unpacklo_epi32(a, _mm_srai_epi32(a, 31)); } + +/** Arithmetic **/ +inline __m128i _v128_mullo_epi32(const __m128i& a, const __m128i& b) +{ + __m128i c0 = _mm_mul_epu32(a, b); + __m128i c1 = _mm_mul_epu32(_mm_srli_epi64(a, 32), _mm_srli_epi64(b, 32)); + __m128i d0 = _mm_unpacklo_epi32(c0, c1); + __m128i d1 = _mm_unpackhi_epi32(c0, c1); + return _mm_unpacklo_epi64(d0, d1); +} + +/** Math **/ +inline __m128i _v128_min_epu32(const __m128i& a, const __m128i& b) +{ return _v128_blendv_epi8(a, b, _v128_comgt_epu32(a, b)); } + +// wrapping SSE4.1 +#else +OPENCV_HAL_SSE_WRAP_1(cvtepu8_epi16, __m128i) +OPENCV_HAL_SSE_WRAP_1(cvtepi8_epi16, __m128i) +OPENCV_HAL_SSE_WRAP_1(cvtepu8_epi32, __m128i) +OPENCV_HAL_SSE_WRAP_1(cvtepi8_epi32, __m128i) +OPENCV_HAL_SSE_WRAP_1(cvtepu16_epi32, __m128i) +OPENCV_HAL_SSE_WRAP_1(cvtepi16_epi32, __m128i) +OPENCV_HAL_SSE_WRAP_1(cvtepu32_epi64, __m128i) +OPENCV_HAL_SSE_WRAP_1(cvtepi32_epi64, __m128i) +OPENCV_HAL_SSE_WRAP_2(min_epu32, __m128i) +OPENCV_HAL_SSE_WRAP_2(mullo_epi32, __m128i) +OPENCV_HAL_SSE_WRAP_3(blendv_epi8, __m128i) +#endif // !CV_SSE4_1 + +///////////////////////////// Revolutionary ///////////////////////////// + +/** Convert **/ +// 16 << 8 +inline __m128i _v128_cvtepu8_epi16_high(const __m128i& a) +{ + const __m128i z = _mm_setzero_si128(); + return _mm_unpackhi_epi8(a, z); +} +inline __m128i _v128_cvtepi8_epi16_high(const __m128i& a) +{ return _mm_srai_epi16(_mm_unpackhi_epi8(a, a), 8); } +// 32 << 16 +inline __m128i _v128_cvtepu16_epi32_high(const __m128i& a) +{ + const __m128i z = _mm_setzero_si128(); + return _mm_unpackhi_epi16(a, z); +} +inline __m128i _v128_cvtepi16_epi32_high(const __m128i& a) +{ return _mm_srai_epi32(_mm_unpackhi_epi16(a, a), 16); } +// 64 << 32 +inline __m128i _v128_cvtepu32_epi64_high(const __m128i& a) +{ + const __m128i z = _mm_setzero_si128(); + return _mm_unpackhi_epi32(a, z); +} +inline __m128i _v128_cvtepi32_epi64_high(const __m128i& a) +{ return _mm_unpackhi_epi32(a, _mm_srai_epi32(a, 31)); } + +/** Miscellaneous **/ +inline __m128i _v128_packs_epu32(const __m128i& a, const __m128i& b) +{ + const __m128i m = _mm_set1_epi32(65535); + __m128i am = _v128_min_epu32(a, m); + __m128i bm = _v128_min_epu32(b, m); +#if CV_SSE4_1 + return _mm_packus_epi32(am, bm); +#else + const __m128i d = _mm_set1_epi32(32768), nd = _mm_set1_epi16(-32768); + am = _mm_sub_epi32(am, d); + bm = _mm_sub_epi32(bm, d); + am = _mm_packs_epi32(am, bm); + return _mm_sub_epi16(am, nd); +#endif +} + +template +inline int64 _v128_extract_epi64(const __m128i& a) +{ +#if defined(CV__SIMD_HAVE_mm_extract_epi64) || (CV_SSE4_1 && (defined(__x86_64__)/*GCC*/ || defined(_M_X64)/*MSVC*/)) +#define CV__SIMD_NATIVE_mm_extract_epi64 1 + return _mm_extract_epi64(a, i); +#else + CV_DECL_ALIGNED(16) int64 tmp[2]; + _mm_store_si128((__m128i*)tmp, a); + return tmp[i]; +#endif +} + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} // cv:: + +#endif // OPENCV_HAL_INTRIN_SSE_EM_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_vsx.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_vsx.hpp index 2157e1e870..b0e2a3472b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_vsx.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_vsx.hpp @@ -1,1619 +1,1619 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -#ifndef OPENCV_HAL_VSX_HPP -#define OPENCV_HAL_VSX_HPP - -#include -#include "opencv2/core/utility.hpp" - -#define CV_SIMD128 1 -#define CV_SIMD128_64F 1 - -namespace cv -{ - -//! @cond IGNORED - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -///////// Types //////////// - -struct v_uint8x16 -{ - typedef uchar lane_type; - enum { nlanes = 16 }; - vec_uchar16 val; - - explicit v_uint8x16(const vec_uchar16& v) : val(v) - {} - v_uint8x16() - {} - v_uint8x16(vec_bchar16 v) : val(vec_uchar16_c(v)) - {} - v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, - uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) - : val(vec_uchar16_set(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15)) - {} - - static inline v_uint8x16 zero() { return v_uint8x16(vec_uchar16_z); } - - uchar get0() const - { return vec_extract(val, 0); } -}; - -struct v_int8x16 -{ - typedef schar lane_type; - enum { nlanes = 16 }; - vec_char16 val; - - explicit v_int8x16(const vec_char16& v) : val(v) - {} - v_int8x16() - {} - v_int8x16(vec_bchar16 v) : val(vec_char16_c(v)) - {} - v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, - schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) - : val(vec_char16_set(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15)) - {} - - static inline v_int8x16 zero() { return v_int8x16(vec_char16_z); } - - schar get0() const - { return vec_extract(val, 0); } -}; - -struct v_uint16x8 -{ - typedef ushort lane_type; - enum { nlanes = 8 }; - vec_ushort8 val; - - explicit v_uint16x8(const vec_ushort8& v) : val(v) - {} - v_uint16x8() - {} - v_uint16x8(vec_bshort8 v) : val(vec_ushort8_c(v)) - {} - v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) - : val(vec_ushort8_set(v0, v1, v2, v3, v4, v5, v6, v7)) - {} - - static inline v_uint16x8 zero() { return v_uint16x8(vec_ushort8_z); } - - ushort get0() const - { return vec_extract(val, 0); } -}; - -struct v_int16x8 -{ - typedef short lane_type; - enum { nlanes = 8 }; - vec_short8 val; - - explicit v_int16x8(const vec_short8& v) : val(v) - {} - v_int16x8() - {} - v_int16x8(vec_bshort8 v) : val(vec_short8_c(v)) - {} - v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) - : val(vec_short8_set(v0, v1, v2, v3, v4, v5, v6, v7)) - {} - - static inline v_int16x8 zero() { return v_int16x8(vec_short8_z); } - - short get0() const - { return vec_extract(val, 0); } -}; - -struct v_uint32x4 -{ - typedef unsigned lane_type; - enum { nlanes = 4 }; - vec_uint4 val; - - explicit v_uint32x4(const vec_uint4& v) : val(v) - {} - v_uint32x4() - {} - v_uint32x4(vec_bint4 v) : val(vec_uint4_c(v)) - {} - v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) : val(vec_uint4_set(v0, v1, v2, v3)) - {} - - static inline v_uint32x4 zero() { return v_uint32x4(vec_uint4_z); } - - uint get0() const - { return vec_extract(val, 0); } -}; - -struct v_int32x4 -{ - typedef int lane_type; - enum { nlanes = 4 }; - vec_int4 val; - - explicit v_int32x4(const vec_int4& v) : val(v) - {} - v_int32x4() - {} - v_int32x4(vec_bint4 v) : val(vec_int4_c(v)) - {} - v_int32x4(int v0, int v1, int v2, int v3) : val(vec_int4_set(v0, v1, v2, v3)) - {} - - static inline v_int32x4 zero() { return v_int32x4(vec_int4_z); } - - int get0() const - { return vec_extract(val, 0); } -}; - -struct v_float32x4 -{ - typedef float lane_type; - enum { nlanes = 4 }; - vec_float4 val; - - explicit v_float32x4(const vec_float4& v) : val(v) - {} - v_float32x4() - {} - v_float32x4(vec_bint4 v) : val(vec_float4_c(v)) - {} - v_float32x4(float v0, float v1, float v2, float v3) : val(vec_float4_set(v0, v1, v2, v3)) - {} - - static inline v_float32x4 zero() { return v_float32x4(vec_float4_z); } - - float get0() const - { return vec_extract(val, 0); } -}; - -struct v_uint64x2 -{ - typedef uint64 lane_type; - enum { nlanes = 2 }; - vec_udword2 val; - - explicit v_uint64x2(const vec_udword2& v) : val(v) - {} - v_uint64x2() - {} - v_uint64x2(vec_bdword2 v) : val(vec_udword2_c(v)) - {} - v_uint64x2(uint64 v0, uint64 v1) : val(vec_udword2_set(v0, v1)) - {} - - static inline v_uint64x2 zero() { return v_uint64x2(vec_udword2_z); } - - uint64 get0() const - { return vec_extract(val, 0); } -}; - -struct v_int64x2 -{ - typedef int64 lane_type; - enum { nlanes = 2 }; - vec_dword2 val; - - explicit v_int64x2(const vec_dword2& v) : val(v) - {} - v_int64x2() - {} - v_int64x2(vec_bdword2 v) : val(vec_dword2_c(v)) - {} - v_int64x2(int64 v0, int64 v1) : val(vec_dword2_set(v0, v1)) - {} - - static inline v_int64x2 zero() { return v_int64x2(vec_dword2_z); } - - int64 get0() const - { return vec_extract(val, 0); } -}; - -struct v_float64x2 -{ - typedef double lane_type; - enum { nlanes = 2 }; - vec_double2 val; - - explicit v_float64x2(const vec_double2& v) : val(v) - {} - v_float64x2() - {} - v_float64x2(vec_bdword2 v) : val(vec_double2_c(v)) - {} - v_float64x2(double v0, double v1) : val(vec_double2_set(v0, v1)) - {} - - static inline v_float64x2 zero() { return v_float64x2(vec_double2_z); } - - double get0() const - { return vec_extract(val, 0); } -}; - -#define OPENCV_HAL_IMPL_VSX_EXTRACT_N(_Tpvec, _Tp) \ -template inline _Tp v_extract_n(VSX_UNUSED(_Tpvec v)) { return vec_extract(v.val, i); } - -OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_uint8x16, uchar) -OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_int8x16, schar) -OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_uint16x8, ushort) -OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_int16x8, short) -OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_uint32x4, uint) -OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_int32x4, int) -OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_uint64x2, uint64) -OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_int64x2, int64) -OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_float32x4, float) -OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_float64x2, double) - -//////////////// Load and store operations /////////////// - -/* - * clang-5 aborted during parse "vec_xxx_c" only if it's - * inside a function template which is defined by preprocessor macro. - * - * if vec_xxx_c defined as C++ cast, clang-5 will pass it -*/ -#define OPENCV_HAL_IMPL_VSX_INITVEC(_Tpvec, _Tp, suffix, cast) \ -inline _Tpvec v_setzero_##suffix() { return _Tpvec(vec_splats((_Tp)0)); } \ -inline _Tpvec v_setall_##suffix(_Tp v) { return _Tpvec(vec_splats((_Tp)v));} \ -template <> inline _Tpvec v_setzero_() { return v_setzero_##suffix(); } \ -template <> inline _Tpvec v_setall_(_Tp v) { return v_setall_##suffix(_Tp v); } \ -template inline _Tpvec v_reinterpret_as_##suffix(const _Tpvec0 &a) \ -{ return _Tpvec((cast)a.val); } - -OPENCV_HAL_IMPL_VSX_INITVEC(v_uint8x16, uchar, u8, vec_uchar16) -OPENCV_HAL_IMPL_VSX_INITVEC(v_int8x16, schar, s8, vec_char16) -OPENCV_HAL_IMPL_VSX_INITVEC(v_uint16x8, ushort, u16, vec_ushort8) -OPENCV_HAL_IMPL_VSX_INITVEC(v_int16x8, short, s16, vec_short8) -OPENCV_HAL_IMPL_VSX_INITVEC(v_uint32x4, uint, u32, vec_uint4) -OPENCV_HAL_IMPL_VSX_INITVEC(v_int32x4, int, s32, vec_int4) -OPENCV_HAL_IMPL_VSX_INITVEC(v_uint64x2, uint64, u64, vec_udword2) -OPENCV_HAL_IMPL_VSX_INITVEC(v_int64x2, int64, s64, vec_dword2) -OPENCV_HAL_IMPL_VSX_INITVEC(v_float32x4, float, f32, vec_float4) -OPENCV_HAL_IMPL_VSX_INITVEC(v_float64x2, double, f64, vec_double2) - -#define OPENCV_HAL_IMPL_VSX_LOADSTORE_C(_Tpvec, _Tp, ld, ld_a, st, st_a) \ -inline _Tpvec v_load(const _Tp* ptr) \ -{ return _Tpvec(ld(0, ptr)); } \ -inline _Tpvec v_load_aligned(VSX_UNUSED(const _Tp* ptr)) \ -{ return _Tpvec(ld_a(0, ptr)); } \ -inline _Tpvec v_load_low(const _Tp* ptr) \ -{ return _Tpvec(vec_ld_l8(ptr)); } \ -inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ -{ return _Tpvec(vec_mergesqh(vec_ld_l8(ptr0), vec_ld_l8(ptr1))); } \ -inline void v_store(_Tp* ptr, const _Tpvec& a) \ -{ st(a.val, 0, ptr); } \ -inline void v_store_aligned(VSX_UNUSED(_Tp* ptr), const _Tpvec& a) \ -{ st_a(a.val, 0, ptr); } \ -inline void v_store_aligned_nocache(VSX_UNUSED(_Tp* ptr), const _Tpvec& a) \ -{ st_a(a.val, 0, ptr); } \ -inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ -{ if(mode == hal::STORE_UNALIGNED) st(a.val, 0, ptr); else st_a(a.val, 0, ptr); } \ -inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ -{ vec_st_l8(a.val, ptr); } \ -inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ -{ vec_st_h8(a.val, ptr); } - -// working around gcc bug for aligned ld/st -// if runtime check for vec_ld/st fail we failback to unaligned ld/st -// https://github.com/opencv/opencv/issues/13211 -#ifdef CV_COMPILER_VSX_BROKEN_ALIGNED - #define OPENCV_HAL_IMPL_VSX_LOADSTORE(_Tpvec, _Tp) \ - OPENCV_HAL_IMPL_VSX_LOADSTORE_C(_Tpvec, _Tp, vsx_ld, vsx_ld, vsx_st, vsx_st) -#else - #define OPENCV_HAL_IMPL_VSX_LOADSTORE(_Tpvec, _Tp) \ - OPENCV_HAL_IMPL_VSX_LOADSTORE_C(_Tpvec, _Tp, vsx_ld, vec_ld, vsx_st, vec_st) -#endif - -OPENCV_HAL_IMPL_VSX_LOADSTORE(v_uint8x16, uchar) -OPENCV_HAL_IMPL_VSX_LOADSTORE(v_int8x16, schar) -OPENCV_HAL_IMPL_VSX_LOADSTORE(v_uint16x8, ushort) -OPENCV_HAL_IMPL_VSX_LOADSTORE(v_int16x8, short) -OPENCV_HAL_IMPL_VSX_LOADSTORE(v_uint32x4, uint) -OPENCV_HAL_IMPL_VSX_LOADSTORE(v_int32x4, int) -OPENCV_HAL_IMPL_VSX_LOADSTORE(v_float32x4, float) - -OPENCV_HAL_IMPL_VSX_LOADSTORE_C(v_float64x2, double, vsx_ld, vsx_ld, vsx_st, vsx_st) -OPENCV_HAL_IMPL_VSX_LOADSTORE_C(v_uint64x2, uint64, vsx_ld2, vsx_ld2, vsx_st2, vsx_st2) -OPENCV_HAL_IMPL_VSX_LOADSTORE_C(v_int64x2, int64, vsx_ld2, vsx_ld2, vsx_st2, vsx_st2) - -//////////////// Value reordering /////////////// - -/* de&interleave */ -#define OPENCV_HAL_IMPL_VSX_INTERLEAVE(_Tp, _Tpvec) \ -inline void v_load_deinterleave(const _Tp* ptr, _Tpvec& a, _Tpvec& b) \ -{ vec_ld_deinterleave(ptr, a.val, b.val);} \ -inline void v_load_deinterleave(const _Tp* ptr, _Tpvec& a, \ - _Tpvec& b, _Tpvec& c) \ -{ vec_ld_deinterleave(ptr, a.val, b.val, c.val); } \ -inline void v_load_deinterleave(const _Tp* ptr, _Tpvec& a, _Tpvec& b, \ - _Tpvec& c, _Tpvec& d) \ -{ vec_ld_deinterleave(ptr, a.val, b.val, c.val, d.val); } \ -inline void v_store_interleave(_Tp* ptr, const _Tpvec& a, const _Tpvec& b, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ vec_st_interleave(a.val, b.val, ptr); } \ -inline void v_store_interleave(_Tp* ptr, const _Tpvec& a, \ - const _Tpvec& b, const _Tpvec& c, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ vec_st_interleave(a.val, b.val, c.val, ptr); } \ -inline void v_store_interleave(_Tp* ptr, const _Tpvec& a, const _Tpvec& b, \ - const _Tpvec& c, const _Tpvec& d, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ vec_st_interleave(a.val, b.val, c.val, d.val, ptr); } - -OPENCV_HAL_IMPL_VSX_INTERLEAVE(uchar, v_uint8x16) -OPENCV_HAL_IMPL_VSX_INTERLEAVE(schar, v_int8x16) -OPENCV_HAL_IMPL_VSX_INTERLEAVE(ushort, v_uint16x8) -OPENCV_HAL_IMPL_VSX_INTERLEAVE(short, v_int16x8) -OPENCV_HAL_IMPL_VSX_INTERLEAVE(uint, v_uint32x4) -OPENCV_HAL_IMPL_VSX_INTERLEAVE(int, v_int32x4) -OPENCV_HAL_IMPL_VSX_INTERLEAVE(float, v_float32x4) -OPENCV_HAL_IMPL_VSX_INTERLEAVE(double, v_float64x2) -OPENCV_HAL_IMPL_VSX_INTERLEAVE(int64, v_int64x2) -OPENCV_HAL_IMPL_VSX_INTERLEAVE(uint64, v_uint64x2) - -/* Expand */ -#define OPENCV_HAL_IMPL_VSX_EXPAND(_Tpvec, _Tpwvec, _Tp, fl, fh) \ -inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ -{ \ - b0.val = fh(a.val); \ - b1.val = fl(a.val); \ -} \ -inline _Tpwvec v_expand_low(const _Tpvec& a) \ -{ return _Tpwvec(fh(a.val)); } \ -inline _Tpwvec v_expand_high(const _Tpvec& a) \ -{ return _Tpwvec(fl(a.val)); } \ -inline _Tpwvec v_load_expand(const _Tp* ptr) \ -{ return _Tpwvec(fh(vec_ld_l8(ptr))); } - -OPENCV_HAL_IMPL_VSX_EXPAND(v_uint8x16, v_uint16x8, uchar, vec_unpacklu, vec_unpackhu) -OPENCV_HAL_IMPL_VSX_EXPAND(v_int8x16, v_int16x8, schar, vec_unpackl, vec_unpackh) -OPENCV_HAL_IMPL_VSX_EXPAND(v_uint16x8, v_uint32x4, ushort, vec_unpacklu, vec_unpackhu) -OPENCV_HAL_IMPL_VSX_EXPAND(v_int16x8, v_int32x4, short, vec_unpackl, vec_unpackh) -OPENCV_HAL_IMPL_VSX_EXPAND(v_uint32x4, v_uint64x2, uint, vec_unpacklu, vec_unpackhu) -OPENCV_HAL_IMPL_VSX_EXPAND(v_int32x4, v_int64x2, int, vec_unpackl, vec_unpackh) - -/* Load and zero expand a 4 byte value into the second dword, first is don't care. */ -#if !defined(CV_COMPILER_VSX_BROKEN_ASM) - #define _LXSIWZX(out, ptr, T) __asm__ ("lxsiwzx %x0, 0, %1\r\n" : "=wa"(out) : "r" (ptr) : "memory"); -#else - /* This is compiler-agnostic, but will introduce an unneeded splat on the critical path. */ - #define _LXSIWZX(out, ptr, T) out = (T)vec_udword2_sp(*(uint32_t*)(ptr)); -#endif - -inline v_uint32x4 v_load_expand_q(const uchar* ptr) -{ - // Zero-extend the extra 24B instead of unpacking. Usually faster in small kernel - // Likewise note, value is zero extended and upper 4 bytes are zero'ed. - vec_uchar16 pmu = {8, 12, 12, 12, 9, 12, 12, 12, 10, 12, 12, 12, 11, 12, 12, 12}; - vec_uchar16 out; - - _LXSIWZX(out, ptr, vec_uchar16); - out = vec_perm(out, out, pmu); - return v_uint32x4((vec_uint4)out); -} - -inline v_int32x4 v_load_expand_q(const schar* ptr) -{ - vec_char16 out; - vec_short8 outs; - vec_int4 outw; - - _LXSIWZX(out, ptr, vec_char16); - outs = vec_unpackl(out); - outw = vec_unpackh(outs); - return v_int32x4(outw); -} - -/* pack */ -#define OPENCV_HAL_IMPL_VSX_PACK(_Tpvec, _Tp, _Tpwvec, _Tpvn, _Tpdel, sfnc, pkfnc, addfnc, pack) \ -inline _Tpvec v_##pack(const _Tpwvec& a, const _Tpwvec& b) \ -{ \ - return _Tpvec(pkfnc(a.val, b.val)); \ -} \ -inline void v_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ -{ \ - vec_st_l8(pkfnc(a.val, a.val), ptr); \ -} \ -template \ -inline _Tpvec v_rshr_##pack(const _Tpwvec& a, const _Tpwvec& b) \ -{ \ - const __vector _Tpvn vn = vec_splats((_Tpvn)n); \ - const __vector _Tpdel delta = vec_splats((_Tpdel)((_Tpdel)1 << (n-1))); \ - return _Tpvec(pkfnc(sfnc(addfnc(a.val, delta), vn), sfnc(addfnc(b.val, delta), vn))); \ -} \ -template \ -inline void v_rshr_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ -{ \ - const __vector _Tpvn vn = vec_splats((_Tpvn)n); \ - const __vector _Tpdel delta = vec_splats((_Tpdel)((_Tpdel)1 << (n-1))); \ - vec_st_l8(pkfnc(sfnc(addfnc(a.val, delta), vn), delta), ptr); \ -} - -OPENCV_HAL_IMPL_VSX_PACK(v_uint8x16, uchar, v_uint16x8, unsigned short, unsigned short, - vec_sr, vec_packs, vec_adds, pack) -OPENCV_HAL_IMPL_VSX_PACK(v_int8x16, schar, v_int16x8, unsigned short, short, - vec_sra, vec_packs, vec_adds, pack) - -OPENCV_HAL_IMPL_VSX_PACK(v_uint16x8, ushort, v_uint32x4, unsigned int, unsigned int, - vec_sr, vec_packs, vec_add, pack) -OPENCV_HAL_IMPL_VSX_PACK(v_int16x8, short, v_int32x4, unsigned int, int, - vec_sra, vec_packs, vec_add, pack) - -OPENCV_HAL_IMPL_VSX_PACK(v_uint32x4, uint, v_uint64x2, unsigned long long, unsigned long long, - vec_sr, vec_pack, vec_add, pack) -OPENCV_HAL_IMPL_VSX_PACK(v_int32x4, int, v_int64x2, unsigned long long, long long, - vec_sra, vec_pack, vec_add, pack) - -OPENCV_HAL_IMPL_VSX_PACK(v_uint8x16, uchar, v_int16x8, unsigned short, short, - vec_sra, vec_packsu, vec_adds, pack_u) -OPENCV_HAL_IMPL_VSX_PACK(v_uint16x8, ushort, v_int32x4, unsigned int, int, - vec_sra, vec_packsu, vec_add, pack_u) -// Following variant is not implemented on other platforms: -//OPENCV_HAL_IMPL_VSX_PACK(v_uint32x4, uint, v_int64x2, unsigned long long, long long, -// vec_sra, vec_packsu, vec_add, pack_u) - -// pack boolean -inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) -{ - vec_uchar16 ab = vec_pack(a.val, b.val); - return v_uint8x16(ab); -} - -inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, - const v_uint32x4& c, const v_uint32x4& d) -{ - vec_ushort8 ab = vec_pack(a.val, b.val); - vec_ushort8 cd = vec_pack(c.val, d.val); - return v_uint8x16(vec_pack(ab, cd)); -} - -inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, - const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, - const v_uint64x2& g, const v_uint64x2& h) -{ - vec_uint4 ab = vec_pack(a.val, b.val); - vec_uint4 cd = vec_pack(c.val, d.val); - vec_uint4 ef = vec_pack(e.val, f.val); - vec_uint4 gh = vec_pack(g.val, h.val); - - vec_ushort8 abcd = vec_pack(ab, cd); - vec_ushort8 efgh = vec_pack(ef, gh); - return v_uint8x16(vec_pack(abcd, efgh)); -} - -/* Recombine */ -template -inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) -{ - b0.val = vec_mergeh(a0.val, a1.val); - b1.val = vec_mergel(a0.val, a1.val); -} - -template -inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) -{ return _Tpvec(vec_mergesql(a.val, b.val)); } - -template -inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) -{ return _Tpvec(vec_mergesqh(a.val, b.val)); } - -template -inline void v_recombine(const _Tpvec& a, const _Tpvec& b, _Tpvec& c, _Tpvec& d) -{ - c.val = vec_mergesqh(a.val, b.val); - d.val = vec_mergesql(a.val, b.val); -} - -////////// Arithmetic, bitwise and comparison operations ///////// - -/* Element-wise binary and unary operations */ -/** Arithmetics **/ -#define OPENCV_HAL_IMPL_VSX_BIN_OP(bin_op, _Tpvec, intrin) \ -inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(intrin(a.val, b.val)); } - -OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_uint8x16, vec_adds) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_uint8x16, vec_subs) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_int8x16, vec_adds) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_int8x16, vec_subs) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_uint16x8, vec_adds) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_uint16x8, vec_subs) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_int16x8, vec_adds) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_int16x8, vec_subs) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_uint32x4, vec_add) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_uint32x4, vec_sub) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_mul, v_uint32x4, vec_mul) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_int32x4, vec_add) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_int32x4, vec_sub) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_mul, v_int32x4, vec_mul) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_float32x4, vec_add) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_float32x4, vec_sub) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_mul, v_float32x4, vec_mul) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_div, v_float32x4, vec_div) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_float64x2, vec_add) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_float64x2, vec_sub) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_mul, v_float64x2, vec_mul) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_div, v_float64x2, vec_div) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_uint64x2, vec_add) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_uint64x2, vec_sub) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_int64x2, vec_add) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_int64x2, vec_sub) - -// saturating multiply -#define OPENCV_HAL_IMPL_VSX_MUL_SAT(_Tpvec, _Tpwvec) \ - inline _Tpvec v_mul(const _Tpvec& a, const _Tpvec& b) \ - { \ - _Tpwvec c, d; \ - v_mul_expand(a, b, c, d); \ - return v_pack(c, d); \ - } - -OPENCV_HAL_IMPL_VSX_MUL_SAT(v_int8x16, v_int16x8) -OPENCV_HAL_IMPL_VSX_MUL_SAT(v_uint8x16, v_uint16x8) -OPENCV_HAL_IMPL_VSX_MUL_SAT(v_int16x8, v_int32x4) -OPENCV_HAL_IMPL_VSX_MUL_SAT(v_uint16x8, v_uint32x4) - -template -inline void v_mul_expand(const Tvec& a, const Tvec& b, Twvec& c, Twvec& d) -{ - Twvec p0 = Twvec(vec_mule(a.val, b.val)); - Twvec p1 = Twvec(vec_mulo(a.val, b.val)); - v_zip(p0, p1, c, d); -} - -inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) -{ - vec_int4 p0 = vec_mule(a.val, b.val); - vec_int4 p1 = vec_mulo(a.val, b.val); - static const vec_uchar16 perm = {2, 3, 18, 19, 6, 7, 22, 23, 10, 11, 26, 27, 14, 15, 30, 31}; - return v_int16x8(vec_perm(vec_short8_c(p0), vec_short8_c(p1), perm)); -} -inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) -{ - vec_uint4 p0 = vec_mule(a.val, b.val); - vec_uint4 p1 = vec_mulo(a.val, b.val); - static const vec_uchar16 perm = {2, 3, 18, 19, 6, 7, 22, 23, 10, 11, 26, 27, 14, 15, 30, 31}; - return v_uint16x8(vec_perm(vec_ushort8_c(p0), vec_ushort8_c(p1), perm)); -} - -/** Non-saturating arithmetics **/ -#define OPENCV_HAL_IMPL_VSX_BIN_FUNC(func, intrin) \ -template \ -inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(intrin(a.val, b.val)); } - -OPENCV_HAL_IMPL_VSX_BIN_FUNC(v_add_wrap, vec_add) -OPENCV_HAL_IMPL_VSX_BIN_FUNC(v_sub_wrap, vec_sub) -OPENCV_HAL_IMPL_VSX_BIN_FUNC(v_mul_wrap, vec_mul) - -/** Bitwise shifts **/ -#define OPENCV_HAL_IMPL_VSX_SHIFT_OP(_Tpvec, shr, splfunc) \ -inline _Tpvec v_shl(const _Tpvec& a, int imm) \ -{ return _Tpvec(vec_sl(a.val, splfunc(imm))); } \ -inline _Tpvec v_shr(const _Tpvec& a, int imm) \ -{ return _Tpvec(shr(a.val, splfunc(imm))); } \ -template inline _Tpvec v_shl(const _Tpvec& a) \ -{ return _Tpvec(vec_sl(a.val, splfunc(imm))); } \ -template inline _Tpvec v_shr(const _Tpvec& a) \ -{ return _Tpvec(shr(a.val, splfunc(imm))); } - -OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_uint8x16, vec_sr, vec_uchar16_sp) -OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_uint16x8, vec_sr, vec_ushort8_sp) -OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_uint32x4, vec_sr, vec_uint4_sp) -OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_uint64x2, vec_sr, vec_udword2_sp) -// algebraic right shift -OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_int8x16, vec_sra, vec_uchar16_sp) -OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_int16x8, vec_sra, vec_ushort8_sp) -OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_int32x4, vec_sra, vec_uint4_sp) -OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_int64x2, vec_sra, vec_udword2_sp) - -/** Bitwise logic **/ -#define OPENCV_HAL_IMPL_VSX_LOGIC_OP(_Tpvec) \ -OPENCV_HAL_IMPL_VSX_BIN_OP(v_and, _Tpvec, vec_and) \ -OPENCV_HAL_IMPL_VSX_BIN_OP(v_or, _Tpvec, vec_or) \ -OPENCV_HAL_IMPL_VSX_BIN_OP(v_xor, _Tpvec, vec_xor) \ -inline _Tpvec v_not(const _Tpvec& a) \ -{ return _Tpvec(vec_not(a.val)); } - -OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_uint8x16) -OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_int8x16) -OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_uint16x8) -OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_int16x8) -OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_uint32x4) -OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_int32x4) -OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_uint64x2) -OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_int64x2) -OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_float32x4) -OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_float64x2) - -/** Bitwise select **/ -#define OPENCV_HAL_IMPL_VSX_SELECT(_Tpvec, cast) \ -inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(vec_sel(b.val, a.val, cast(mask.val))); } - -OPENCV_HAL_IMPL_VSX_SELECT(v_uint8x16, vec_bchar16_c) -OPENCV_HAL_IMPL_VSX_SELECT(v_int8x16, vec_bchar16_c) -OPENCV_HAL_IMPL_VSX_SELECT(v_uint16x8, vec_bshort8_c) -OPENCV_HAL_IMPL_VSX_SELECT(v_int16x8, vec_bshort8_c) -OPENCV_HAL_IMPL_VSX_SELECT(v_uint32x4, vec_bint4_c) -OPENCV_HAL_IMPL_VSX_SELECT(v_int32x4, vec_bint4_c) -OPENCV_HAL_IMPL_VSX_SELECT(v_float32x4, vec_bint4_c) -OPENCV_HAL_IMPL_VSX_SELECT(v_float64x2, vec_bdword2_c) - -/** Comparison **/ -#define OPENCV_HAL_IMPL_VSX_INT_CMP_OP(_Tpvec) \ -inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(vec_cmpeq(a.val, b.val)); } \ -inline _Tpvec V_ne(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(vec_cmpne(a.val, b.val)); } \ -inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(vec_cmplt(a.val, b.val)); } \ -inline _Tpvec V_gt(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(vec_cmpgt(a.val, b.val)); } \ -inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(vec_cmple(a.val, b.val)); } \ -inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(vec_cmpge(a.val, b.val)); } - -OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_uint8x16) -OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_int8x16) -OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_uint16x8) -OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_int16x8) -OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_uint32x4) -OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_int32x4) -OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_float32x4) -OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_float64x2) -OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_uint64x2) -OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_int64x2) - -inline v_float32x4 v_not_nan(const v_float32x4& a) -{ return v_float32x4(vec_cmpeq(a.val, a.val)); } -inline v_float64x2 v_not_nan(const v_float64x2& a) -{ return v_float64x2(vec_cmpeq(a.val, a.val)); } - -/** min/max **/ -OPENCV_HAL_IMPL_VSX_BIN_FUNC(v_min, vec_min) -OPENCV_HAL_IMPL_VSX_BIN_FUNC(v_max, vec_max) - -/** Rotate **/ -#define OPENCV_IMPL_VSX_ROTATE(_Tpvec, suffix, shf, cast) \ -template \ -inline _Tpvec v_rotate_##suffix(const _Tpvec& a) \ -{ \ - const int wd = imm * sizeof(typename _Tpvec::lane_type); \ - if (wd > 15) \ - return _Tpvec::zero(); \ - return _Tpvec((cast)shf(vec_uchar16_c(a.val), vec_uchar16_sp(wd << 3))); \ -} - -#define OPENCV_IMPL_VSX_ROTATE_LR(_Tpvec, cast) \ -OPENCV_IMPL_VSX_ROTATE(_Tpvec, left, vec_slo, cast) \ -OPENCV_IMPL_VSX_ROTATE(_Tpvec, right, vec_sro, cast) - -OPENCV_IMPL_VSX_ROTATE_LR(v_uint8x16, vec_uchar16) -OPENCV_IMPL_VSX_ROTATE_LR(v_int8x16, vec_char16) -OPENCV_IMPL_VSX_ROTATE_LR(v_uint16x8, vec_ushort8) -OPENCV_IMPL_VSX_ROTATE_LR(v_int16x8, vec_short8) -OPENCV_IMPL_VSX_ROTATE_LR(v_uint32x4, vec_uint4) -OPENCV_IMPL_VSX_ROTATE_LR(v_int32x4, vec_int4) -OPENCV_IMPL_VSX_ROTATE_LR(v_float32x4, vec_float4) -OPENCV_IMPL_VSX_ROTATE_LR(v_uint64x2, vec_udword2) -OPENCV_IMPL_VSX_ROTATE_LR(v_int64x2, vec_dword2) -OPENCV_IMPL_VSX_ROTATE_LR(v_float64x2, vec_double2) - -template -inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) -{ - enum { CV_SHIFT = 16 - imm * (sizeof(typename _Tpvec::lane_type)) }; - if (CV_SHIFT == 16) - return a; -#ifdef __IBMCPP__ - return _Tpvec(vec_sld(b.val, a.val, CV_SHIFT & 15)); -#else - return _Tpvec(vec_sld(b.val, a.val, CV_SHIFT)); -#endif -} - -template -inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) -{ - enum { CV_SHIFT = imm * (sizeof(typename _Tpvec::lane_type)) }; - if (CV_SHIFT == 16) - return b; - return _Tpvec(vec_sld(a.val, b.val, CV_SHIFT)); -} - -#define OPENCV_IMPL_VSX_ROTATE_64_2RG(_Tpvec, suffix, rg1, rg2) \ -template \ -inline _Tpvec v_rotate_##suffix(const _Tpvec& a, const _Tpvec& b) \ -{ \ - if (imm == 1) \ - return _Tpvec(vec_permi(rg1.val, rg2.val, 2)); \ - return imm ? b : a; \ -} - -#define OPENCV_IMPL_VSX_ROTATE_64_2RG_LR(_Tpvec) \ -OPENCV_IMPL_VSX_ROTATE_64_2RG(_Tpvec, left, b, a) \ -OPENCV_IMPL_VSX_ROTATE_64_2RG(_Tpvec, right, a, b) - -OPENCV_IMPL_VSX_ROTATE_64_2RG_LR(v_float64x2) -OPENCV_IMPL_VSX_ROTATE_64_2RG_LR(v_uint64x2) -OPENCV_IMPL_VSX_ROTATE_64_2RG_LR(v_int64x2) - -/* Reverse */ -inline v_uint8x16 v_reverse(const v_uint8x16 &a) -{ - static const vec_uchar16 perm = {15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; - vec_uchar16 vec = (vec_uchar16)a.val; - return v_uint8x16(vec_perm(vec, vec, perm)); -} - -inline v_int8x16 v_reverse(const v_int8x16 &a) -{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } - -inline v_uint16x8 v_reverse(const v_uint16x8 &a) -{ - static const vec_uchar16 perm = {14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1}; - vec_uchar16 vec = (vec_uchar16)a.val; - return v_reinterpret_as_u16(v_uint8x16(vec_perm(vec, vec, perm))); -} - -inline v_int16x8 v_reverse(const v_int16x8 &a) -{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } - -inline v_uint32x4 v_reverse(const v_uint32x4 &a) -{ - static const vec_uchar16 perm = {12, 13, 14, 15, 8, 9, 10, 11, 4, 5, 6, 7, 0, 1, 2, 3}; - vec_uchar16 vec = (vec_uchar16)a.val; - return v_reinterpret_as_u32(v_uint8x16(vec_perm(vec, vec, perm))); -} - -inline v_int32x4 v_reverse(const v_int32x4 &a) -{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_float32x4 v_reverse(const v_float32x4 &a) -{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_uint64x2 v_reverse(const v_uint64x2 &a) -{ - static const vec_uchar16 perm = {8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7}; - vec_uchar16 vec = (vec_uchar16)a.val; - return v_reinterpret_as_u64(v_uint8x16(vec_perm(vec, vec, perm))); -} - -inline v_int64x2 v_reverse(const v_int64x2 &a) -{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } - -inline v_float64x2 v_reverse(const v_float64x2 &a) -{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } - -/* Extract */ -template -inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) -{ return v_rotate_right(a, b); } - -////////// Reduce and mask ///////// - -/** Reduce **/ -inline uint v_reduce_sum(const v_uint8x16& a) -{ - const vec_uint4 zero4 = vec_uint4_z; - vec_uint4 sum4 = vec_sum4s(a.val, zero4); - return (uint)vec_extract(vec_sums(vec_int4_c(sum4), vec_int4_c(zero4)), 3); -} -inline int v_reduce_sum(const v_int8x16& a) -{ - const vec_int4 zero4 = vec_int4_z; - vec_int4 sum4 = vec_sum4s(a.val, zero4); - return (int)vec_extract(vec_sums(sum4, zero4), 3); -} -inline int v_reduce_sum(const v_int16x8& a) -{ - const vec_int4 zero = vec_int4_z; - return saturate_cast(vec_extract(vec_sums(vec_sum4s(a.val, zero), zero), 3)); -} -inline uint v_reduce_sum(const v_uint16x8& a) -{ - const vec_int4 v4 = vec_int4_c(vec_unpackhu(vec_adds(a.val, vec_sld(a.val, a.val, 8)))); - return saturate_cast(vec_extract(vec_sums(v4, vec_int4_z), 3)); -} - -#define OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(_Tpvec, _Tpvec2, scalartype, suffix, func) \ -inline scalartype v_reduce_##suffix(const _Tpvec& a) \ -{ \ - const _Tpvec2 rs = func(a.val, vec_sld(a.val, a.val, 8)); \ - return vec_extract(func(rs, vec_sld(rs, rs, 4)), 0); \ -} -OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_uint32x4, vec_uint4, uint, sum, vec_add) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_uint32x4, vec_uint4, uint, max, vec_max) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_uint32x4, vec_uint4, uint, min, vec_min) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_int32x4, vec_int4, int, sum, vec_add) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_int32x4, vec_int4, int, max, vec_max) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_int32x4, vec_int4, int, min, vec_min) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_float32x4, vec_float4, float, sum, vec_add) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_float32x4, vec_float4, float, max, vec_max) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_float32x4, vec_float4, float, min, vec_min) - -inline uint64 v_reduce_sum(const v_uint64x2& a) -{ - return vec_extract(vec_add(a.val, vec_permi(a.val, a.val, 3)), 0); -} -inline int64 v_reduce_sum(const v_int64x2& a) -{ - return vec_extract(vec_add(a.val, vec_permi(a.val, a.val, 3)), 0); -} -inline double v_reduce_sum(const v_float64x2& a) -{ - return vec_extract(vec_add(a.val, vec_permi(a.val, a.val, 3)), 0); -} - -#define OPENCV_HAL_IMPL_VSX_REDUCE_OP_8(_Tpvec, _Tpvec2, scalartype, suffix, func) \ -inline scalartype v_reduce_##suffix(const _Tpvec& a) \ -{ \ - _Tpvec2 rs = func(a.val, vec_sld(a.val, a.val, 8)); \ - rs = func(rs, vec_sld(rs, rs, 4)); \ - return vec_extract(func(rs, vec_sld(rs, rs, 2)), 0); \ -} -OPENCV_HAL_IMPL_VSX_REDUCE_OP_8(v_uint16x8, vec_ushort8, ushort, max, vec_max) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_8(v_uint16x8, vec_ushort8, ushort, min, vec_min) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_8(v_int16x8, vec_short8, short, max, vec_max) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_8(v_int16x8, vec_short8, short, min, vec_min) - -#define OPENCV_HAL_IMPL_VSX_REDUCE_OP_16(_Tpvec, _Tpvec2, scalartype, suffix, func) \ -inline scalartype v_reduce_##suffix(const _Tpvec& a) \ -{ \ - _Tpvec2 rs = func(a.val, vec_sld(a.val, a.val, 8)); \ - rs = func(rs, vec_sld(rs, rs, 4)); \ - rs = func(rs, vec_sld(rs, rs, 2)); \ - return vec_extract(func(rs, vec_sld(rs, rs, 1)), 0); \ -} -OPENCV_HAL_IMPL_VSX_REDUCE_OP_16(v_uint8x16, vec_uchar16, uchar, max, vec_max) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_16(v_uint8x16, vec_uchar16, uchar, min, vec_min) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_16(v_int8x16, vec_char16, schar, max, vec_max) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_16(v_int8x16, vec_char16, schar, min, vec_min) - -inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, - const v_float32x4& c, const v_float32x4& d) -{ - vec_float4 ac = vec_add(vec_mergel(a.val, c.val), vec_mergeh(a.val, c.val)); - ac = vec_add(ac, vec_sld(ac, ac, 8)); - - vec_float4 bd = vec_add(vec_mergel(b.val, d.val), vec_mergeh(b.val, d.val)); - bd = vec_add(bd, vec_sld(bd, bd, 8)); - return v_float32x4(vec_mergeh(ac, bd)); -} - -inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b) -{ - const vec_uint4 zero4 = vec_uint4_z; - vec_uint4 sum4 = vec_sum4s(vec_absd(a.val, b.val), zero4); - return (unsigned)vec_extract(vec_sums(vec_int4_c(sum4), vec_int4_c(zero4)), 3); -} -inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b) -{ - const vec_int4 zero4 = vec_int4_z; - vec_char16 ad = vec_abss(vec_subs(a.val, b.val)); - vec_int4 sum4 = vec_sum4s(ad, zero4); - return (unsigned)vec_extract(vec_sums(sum4, zero4), 3); -} -inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b) -{ - vec_ushort8 ad = vec_absd(a.val, b.val); - VSX_UNUSED(vec_int4) sum = vec_sums(vec_int4_c(vec_unpackhu(ad)) + vec_int4_c(vec_unpacklu(ad)), vec_int4_z); - return (unsigned)vec_extract(sum, 3); -} -inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b) -{ - const vec_int4 zero4 = vec_int4_z; - vec_short8 ad = vec_abss(vec_subs(a.val, b.val)); - vec_int4 sum4 = vec_sum4s(ad, zero4); - return (unsigned)vec_extract(vec_sums(sum4, zero4), 3); -} -inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b) -{ - const vec_uint4 ad = vec_absd(a.val, b.val); - const vec_uint4 rd = vec_add(ad, vec_sld(ad, ad, 8)); - return vec_extract(vec_add(rd, vec_sld(rd, rd, 4)), 0); -} -inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b) -{ - vec_int4 ad = vec_abss(vec_sub(a.val, b.val)); - return (unsigned)vec_extract(vec_sums(ad, vec_int4_z), 3); -} -inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) -{ - const vec_float4 ad = vec_abs(vec_sub(a.val, b.val)); - const vec_float4 rd = vec_add(ad, vec_sld(ad, ad, 8)); - return vec_extract(vec_add(rd, vec_sld(rd, rd, 4)), 0); -} - -/** Popcount **/ -inline v_uint8x16 v_popcount(const v_uint8x16& a) -{ return v_uint8x16(vec_popcntu(a.val)); } -inline v_uint8x16 v_popcount(const v_int8x16& a) -{ return v_uint8x16(vec_popcntu(a.val)); } -inline v_uint16x8 v_popcount(const v_uint16x8& a) -{ return v_uint16x8(vec_popcntu(a.val)); } -inline v_uint16x8 v_popcount(const v_int16x8& a) -{ return v_uint16x8(vec_popcntu(a.val)); } -inline v_uint32x4 v_popcount(const v_uint32x4& a) -{ return v_uint32x4(vec_popcntu(a.val)); } -inline v_uint32x4 v_popcount(const v_int32x4& a) -{ return v_uint32x4(vec_popcntu(a.val)); } -inline v_uint64x2 v_popcount(const v_uint64x2& a) -{ return v_uint64x2(vec_popcntu(a.val)); } -inline v_uint64x2 v_popcount(const v_int64x2& a) -{ return v_uint64x2(vec_popcntu(a.val)); } - -/** Mask **/ -inline int v_signmask(const v_uint8x16& a) -{ - static const vec_uchar16 qperm = {120, 112, 104, 96, 88, 80, 72, 64, 56, 48, 40, 32, 24, 16, 8, 0}; - return vec_extract((vec_int4)vec_vbpermq(v_reinterpret_as_u8(a).val, qperm), 2); -} -inline int v_signmask(const v_int8x16& a) -{ return v_signmask(v_reinterpret_as_u8(a)); } - -inline int v_signmask(const v_int16x8& a) -{ - static const vec_uchar16 qperm = {112, 96, 80, 64, 48, 32, 16, 0, 128, 128, 128, 128, 128, 128, 128, 128}; - return vec_extract((vec_int4)vec_vbpermq(v_reinterpret_as_u8(a).val, qperm), 2); -} -inline int v_signmask(const v_uint16x8& a) -{ return v_signmask(v_reinterpret_as_s16(a)); } - -inline int v_signmask(const v_int32x4& a) -{ - static const vec_uchar16 qperm = {96, 64, 32, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}; - return vec_extract((vec_int4)vec_vbpermq(v_reinterpret_as_u8(a).val, qperm), 2); -} -inline int v_signmask(const v_uint32x4& a) -{ return v_signmask(v_reinterpret_as_s32(a)); } -inline int v_signmask(const v_float32x4& a) -{ return v_signmask(v_reinterpret_as_s32(a)); } - -inline int v_signmask(const v_int64x2& a) -{ - VSX_UNUSED(const vec_dword2) sv = vec_sr(a.val, vec_udword2_sp(63)); - return (int)vec_extract(sv, 0) | (int)vec_extract(sv, 1) << 1; -} -inline int v_signmask(const v_uint64x2& a) -{ return v_signmask(v_reinterpret_as_s64(a)); } -inline int v_signmask(const v_float64x2& a) -{ return v_signmask(v_reinterpret_as_s64(a)); } - -inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(a)); } - -template -inline bool v_check_all(const _Tpvec& a) -{ return vec_all_lt(a.val, _Tpvec::zero().val); } -inline bool v_check_all(const v_uint8x16& a) -{ return v_check_all(v_reinterpret_as_s8(a)); } -inline bool v_check_all(const v_uint16x8& a) -{ return v_check_all(v_reinterpret_as_s16(a)); } -inline bool v_check_all(const v_uint32x4& a) -{ return v_check_all(v_reinterpret_as_s32(a)); } -inline bool v_check_all(const v_uint64x2& a) -{ return v_check_all(v_reinterpret_as_s64(a)); } -inline bool v_check_all(const v_float32x4& a) -{ return v_check_all(v_reinterpret_as_s32(a)); } -inline bool v_check_all(const v_float64x2& a) -{ return v_check_all(v_reinterpret_as_s64(a)); } - -template -inline bool v_check_any(const _Tpvec& a) -{ return vec_any_lt(a.val, _Tpvec::zero().val); } -inline bool v_check_any(const v_uint8x16& a) -{ return v_check_any(v_reinterpret_as_s8(a)); } -inline bool v_check_any(const v_uint16x8& a) -{ return v_check_any(v_reinterpret_as_s16(a)); } -inline bool v_check_any(const v_uint32x4& a) -{ return v_check_any(v_reinterpret_as_s32(a)); } -inline bool v_check_any(const v_uint64x2& a) -{ return v_check_any(v_reinterpret_as_s64(a)); } -inline bool v_check_any(const v_float32x4& a) -{ return v_check_any(v_reinterpret_as_s32(a)); } -inline bool v_check_any(const v_float64x2& a) -{ return v_check_any(v_reinterpret_as_s64(a)); } - -////////// Other math ///////// - -/** Some frequent operations **/ -inline v_float32x4 v_sqrt(const v_float32x4& x) -{ return v_float32x4(vec_sqrt(x.val)); } -inline v_float64x2 v_sqrt(const v_float64x2& x) -{ return v_float64x2(vec_sqrt(x.val)); } - -inline v_float32x4 v_invsqrt(const v_float32x4& x) -{ return v_float32x4(vec_rsqrt(x.val)); } -inline v_float64x2 v_invsqrt(const v_float64x2& x) -{ return v_float64x2(vec_rsqrt(x.val)); } - -#define OPENCV_HAL_IMPL_VSX_MULADD(_Tpvec) \ -inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(vec_sqrt(vec_madd(a.val, a.val, vec_mul(b.val, b.val)))); } \ -inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(vec_madd(a.val, a.val, vec_mul(b.val, b.val))); } \ -inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ -{ return _Tpvec(vec_madd(a.val, b.val, c.val)); } \ -inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ -{ return _Tpvec(vec_madd(a.val, b.val, c.val)); } - -OPENCV_HAL_IMPL_VSX_MULADD(v_float32x4) -OPENCV_HAL_IMPL_VSX_MULADD(v_float64x2) - -inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ return v_add(v_mul(a, b), c); } - -// TODO: exp, log, sin, cos - -/** Absolute values **/ -inline v_uint8x16 v_abs(const v_int8x16& x) -{ return v_uint8x16(vec_uchar16_c(vec_abs(x.val))); } - -inline v_uint16x8 v_abs(const v_int16x8& x) -{ return v_uint16x8(vec_ushort8_c(vec_abs(x.val))); } - -inline v_uint32x4 v_abs(const v_int32x4& x) -{ return v_uint32x4(vec_uint4_c(vec_abs(x.val))); } - -inline v_float32x4 v_abs(const v_float32x4& x) -{ return v_float32x4(vec_abs(x.val)); } - -inline v_float64x2 v_abs(const v_float64x2& x) -{ return v_float64x2(vec_abs(x.val)); } - -/** Absolute difference **/ -// unsigned -OPENCV_HAL_IMPL_VSX_BIN_FUNC(v_absdiff, vec_absd) - -inline v_uint8x16 v_absdiff(const v_int8x16& a, const v_int8x16& b) -{ return v_reinterpret_as_u8(v_sub_wrap(v_max(a, b), v_min(a, b))); } -inline v_uint16x8 v_absdiff(const v_int16x8& a, const v_int16x8& b) -{ return v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))); } -inline v_uint32x4 v_absdiff(const v_int32x4& a, const v_int32x4& b) -{ return v_reinterpret_as_u32(v_sub(v_max(a, b), v_min(a, b))); } - -inline v_float32x4 v_absdiff(const v_float32x4& a, const v_float32x4& b) -{ return v_abs(v_sub(a, b)); } -inline v_float64x2 v_absdiff(const v_float64x2& a, const v_float64x2& b) -{ return v_abs(v_sub(a, b)); } - -/** Absolute difference for signed integers **/ -inline v_int8x16 v_absdiffs(const v_int8x16& a, const v_int8x16& b) -{ return v_int8x16(vec_abss(vec_subs(a.val, b.val))); } -inline v_int16x8 v_absdiffs(const v_int16x8& a, const v_int16x8& b) -{ return v_int16x8(vec_abss(vec_subs(a.val, b.val))); } - -////////// Conversions ///////// - -/** Rounding **/ -inline v_int32x4 v_round(const v_float32x4& a) -{ return v_int32x4(vec_cts(vec_rint(a.val))); } - -inline v_int32x4 v_round(const v_float64x2& a) -{ return v_int32x4(vec_mergesqo(vec_ctso(vec_rint(a.val)), vec_int4_z)); } - -inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) -{ return v_int32x4(vec_mergesqo(vec_ctso(vec_rint(a.val)), vec_ctso(vec_rint(b.val)))); } - -inline v_int32x4 v_floor(const v_float32x4& a) -{ return v_int32x4(vec_cts(vec_floor(a.val))); } - -inline v_int32x4 v_floor(const v_float64x2& a) -{ return v_int32x4(vec_mergesqo(vec_ctso(vec_floor(a.val)), vec_int4_z)); } - -inline v_int32x4 v_ceil(const v_float32x4& a) -{ return v_int32x4(vec_cts(vec_ceil(a.val))); } - -inline v_int32x4 v_ceil(const v_float64x2& a) -{ return v_int32x4(vec_mergesqo(vec_ctso(vec_ceil(a.val)), vec_int4_z)); } - -inline v_int32x4 v_trunc(const v_float32x4& a) -{ return v_int32x4(vec_cts(a.val)); } - -inline v_int32x4 v_trunc(const v_float64x2& a) -{ return v_int32x4(vec_mergesqo(vec_ctso(a.val), vec_int4_z)); } - -/** To float **/ -inline v_float32x4 v_cvt_f32(const v_int32x4& a) -{ return v_float32x4(vec_ctf(a.val)); } - -inline v_float32x4 v_cvt_f32(const v_float64x2& a) -{ return v_float32x4(vec_mergesqo(vec_cvfo(a.val), vec_float4_z)); } - -inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) -{ return v_float32x4(vec_mergesqo(vec_cvfo(a.val), vec_cvfo(b.val))); } - -inline v_float64x2 v_cvt_f64(const v_int32x4& a) -{ return v_float64x2(vec_ctdo(vec_mergeh(a.val, a.val))); } - -inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) -{ return v_float64x2(vec_ctdo(vec_mergel(a.val, a.val))); } - -inline v_float64x2 v_cvt_f64(const v_float32x4& a) -{ return v_float64x2(vec_cvfo(vec_mergeh(a.val, a.val))); } - -inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) -{ return v_float64x2(vec_cvfo(vec_mergel(a.val, a.val))); } - -inline v_float64x2 v_cvt_f64(const v_int64x2& a) -{ return v_float64x2(vec_ctd(a.val)); } - -////////////// Lookup table access //////////////////// - -inline v_int8x16 v_lut(const schar* tab, const int* idx) -{ - return v_int8x16(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]], - tab[idx[8]], tab[idx[9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]]); -} -inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx) -{ - return v_reinterpret_as_s8(v_int16x8(*(const short*)(tab+idx[0]), *(const short*)(tab+idx[1]), *(const short*)(tab+idx[2]), *(const short*)(tab+idx[3]), - *(const short*)(tab+idx[4]), *(const short*)(tab+idx[5]), *(const short*)(tab+idx[6]), *(const short*)(tab+idx[7]))); -} -inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) -{ - return v_reinterpret_as_s8(v_int32x4(*(const int*)(tab+idx[0]), *(const int*)(tab+idx[1]), *(const int*)(tab+idx[2]), *(const int*)(tab+idx[3]))); -} -inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((const schar*)tab, idx)); } -inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((const schar*)tab, idx)); } -inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((const schar*)tab, idx)); } - -inline v_int16x8 v_lut(const short* tab, const int* idx) -{ - return v_int16x8(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]]); -} -inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) -{ - return v_reinterpret_as_s16(v_int32x4(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]))); -} -inline v_int16x8 v_lut_quads(const short* tab, const int* idx) -{ - return v_reinterpret_as_s16(v_int64x2(*(const int64*)(tab + idx[0]), *(const int64*)(tab + idx[1]))); -} -inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((const short*)tab, idx)); } -inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((const short*)tab, idx)); } -inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((const short*)tab, idx)); } - -inline v_int32x4 v_lut(const int* tab, const int* idx) -{ - return v_int32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); -} -inline v_int32x4 v_lut_pairs(const int* tab, const int* idx) -{ - return v_reinterpret_as_s32(v_int64x2(*(const int64*)(tab + idx[0]), *(const int64*)(tab + idx[1]))); -} -inline v_int32x4 v_lut_quads(const int* tab, const int* idx) -{ - return v_int32x4(vsx_ld(0, tab + idx[0])); -} -inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((const int*)tab, idx)); } -inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((const int*)tab, idx)); } -inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((const int*)tab, idx)); } - -inline v_int64x2 v_lut(const int64_t* tab, const int* idx) -{ - return v_int64x2(tab[idx[0]], tab[idx[1]]); -} -inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) -{ - return v_int64x2(vsx_ld2(0, tab + idx[0])); -} -inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } -inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } - -inline v_float32x4 v_lut(const float* tab, const int* idx) -{ - return v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); -} -inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) { return v_reinterpret_as_f32(v_lut_pairs((const int*)tab, idx)); } -inline v_float32x4 v_lut_quads(const float* tab, const int* idx) { return v_load(tab + *idx); } - -inline v_float64x2 v_lut(const double* tab, const int* idx) -{ - return v_float64x2(tab[idx[0]], tab[idx[1]]); -} -inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) { return v_load(tab + *idx); } - -inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) -{ - const int idx[4] = { - vec_extract(idxvec.val, 0), - vec_extract(idxvec.val, 1), - vec_extract(idxvec.val, 2), - vec_extract(idxvec.val, 3) - }; - return v_int32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); -} - -inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) -{ - const int idx[4] = { - vec_extract(idxvec.val, 0), - vec_extract(idxvec.val, 1), - vec_extract(idxvec.val, 2), - vec_extract(idxvec.val, 3) - }; - return v_uint32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); -} - -inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) -{ - const int idx[4] = { - vec_extract(idxvec.val, 0), - vec_extract(idxvec.val, 1), - vec_extract(idxvec.val, 2), - vec_extract(idxvec.val, 3) - }; - return v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); -} - -inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) -{ - const int idx[2] = { - vec_extract(idxvec.val, 0), - vec_extract(idxvec.val, 1) - }; - return v_float64x2(tab[idx[0]], tab[idx[1]]); -} - -inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) -{ - vec_float4 xy0 = vec_ld_l8(tab + vec_extract(idxvec.val, 0)); - vec_float4 xy1 = vec_ld_l8(tab + vec_extract(idxvec.val, 1)); - vec_float4 xy2 = vec_ld_l8(tab + vec_extract(idxvec.val, 2)); - vec_float4 xy3 = vec_ld_l8(tab + vec_extract(idxvec.val, 3)); - vec_float4 xy02 = vec_mergeh(xy0, xy2); // x0, x2, y0, y2 - vec_float4 xy13 = vec_mergeh(xy1, xy3); // x1, x3, y1, y3 - x.val = vec_mergeh(xy02, xy13); - y.val = vec_mergel(xy02, xy13); -} -inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) -{ - vec_double2 xy0 = vsx_ld(vec_extract(idxvec.val, 0), tab); - vec_double2 xy1 = vsx_ld(vec_extract(idxvec.val, 1), tab); - x.val = vec_mergeh(xy0, xy1); - y.val = vec_mergel(xy0, xy1); -} - -inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) -{ - static const vec_uchar16 perm = {0, 2, 1, 3, 4, 6, 5, 7, 8, 10, 9, 11, 12, 14, 13, 15}; - return v_int8x16(vec_perm(vec.val, vec.val, perm)); -} -inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) -{ return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } - -inline v_int8x16 v_interleave_quads(const v_int8x16& vec) -{ - static const vec_uchar16 perm = {0, 4, 1, 5, 2, 6, 3, 7, 8, 12, 9, 13, 10, 14, 11, 15}; - return v_int8x16(vec_perm(vec.val, vec.val, perm)); -} -inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) -{ return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) -{ - static const vec_uchar16 perm = {0,1, 4,5, 2,3, 6,7, 8,9, 12,13, 10,11, 14,15}; - return v_int16x8(vec_perm(vec.val, vec.val, perm)); -} -inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) -{ return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } - -inline v_int16x8 v_interleave_quads(const v_int16x8& vec) -{ - static const vec_uchar16 perm = {0,1, 8,9, 2,3, 10,11, 4,5, 12,13, 6,7, 14,15}; - return v_int16x8(vec_perm(vec.val, vec.val, perm)); -} -inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) -{ return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) -{ - static const vec_uchar16 perm = {0,1,2,3, 8,9,10,11, 4,5,6,7, 12,13,14,15}; - return v_int32x4(vec_perm(vec.val, vec.val, perm)); -} -inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) -{ return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } -inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) -{ return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } - -inline v_int8x16 v_pack_triplets(const v_int8x16& vec) -{ - static const vec_uchar16 perm = {0, 1, 2, 4, 5, 6, 8, 9, 10, 12, 13, 14, 15, 15, 15, 15}; - return v_int8x16(vec_perm(vec.val, vec.val, perm)); -} -inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) -{ return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_pack_triplets(const v_int16x8& vec) -{ - static const vec_uchar16 perm = {0,1, 2,3, 4,5, 8,9, 10,11, 12,13, 14,15, 14,15}; - return v_int16x8(vec_perm(vec.val, vec.val, perm)); -} -inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) -{ return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_pack_triplets(const v_int32x4& vec) -{ return vec; } -inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) -{ return vec; } -inline v_float32x4 v_pack_triplets(const v_float32x4& vec) -{ return vec; } - -/////// FP16 support //////// - -inline v_float32x4 v_load_expand(const hfloat* ptr) -{ - vec_ushort8 vf16 = vec_ld_l8((const ushort*)ptr); -#if CV_VSX3 && defined(vec_extract_fp_from_shorth) - return v_float32x4(vec_extract_fp_from_shorth(vf16)); -#elif CV_VSX3 && !defined(CV_COMPILER_VSX_BROKEN_ASM) - vec_float4 vf32; - __asm__ __volatile__ ("xvcvhpsp %x0,%x1" : "=wa" (vf32) : "wa" (vec_mergeh(vf16, vf16))); - return v_float32x4(vf32); -#else - const vec_int4 z = vec_int4_z, delta = vec_int4_sp(0x38000000); - const vec_int4 signmask = vec_int4_sp(0x80000000); - const vec_int4 maxexp = vec_int4_sp(0x7c000000); - const vec_float4 deltaf = vec_float4_c(vec_int4_sp(0x38800000)); - - vec_int4 bits = vec_int4_c(vec_mergeh(vec_short8_c(z), vec_short8_c(vf16))); - vec_int4 e = vec_and(bits, maxexp), sign = vec_and(bits, signmask); - vec_int4 t = vec_add(vec_sr(vec_xor(bits, sign), vec_uint4_sp(3)), delta); // ((h & 0x7fff) << 13) + delta - vec_int4 zt = vec_int4_c(vec_sub(vec_float4_c(vec_add(t, vec_int4_sp(1 << 23))), deltaf)); - - t = vec_add(t, vec_and(delta, vec_cmpeq(maxexp, e))); - vec_bint4 zmask = vec_cmpeq(e, z); - vec_int4 ft = vec_sel(t, zt, zmask); - return v_float32x4(vec_float4_c(vec_or(ft, sign))); -#endif -} - -inline void v_pack_store(hfloat* ptr, const v_float32x4& v) -{ -// fixme: Is there any builtin op or intrinsic that cover "xvcvsphp"? -#if CV_VSX3 && !defined(CV_COMPILER_VSX_BROKEN_ASM) - vec_ushort8 vf16; - __asm__ __volatile__ ("xvcvsphp %x0,%x1" : "=wa" (vf16) : "wa" (v.val)); - vec_st_l8(vec_mergesqe(vf16, vf16), ptr); -#else - const vec_int4 signmask = vec_int4_sp(0x80000000); - const vec_int4 rval = vec_int4_sp(0x3f000000); - - vec_int4 t = vec_int4_c(v.val); - vec_int4 sign = vec_sra(vec_and(t, signmask), vec_uint4_sp(16)); - t = vec_and(vec_nor(signmask, signmask), t); - - vec_bint4 finitemask = vec_cmpgt(vec_int4_sp(0x47800000), t); - vec_bint4 isnan = vec_cmpgt(t, vec_int4_sp(0x7f800000)); - vec_int4 naninf = vec_sel(vec_int4_sp(0x7c00), vec_int4_sp(0x7e00), isnan); - vec_bint4 tinymask = vec_cmpgt(vec_int4_sp(0x38800000), t); - vec_int4 tt = vec_int4_c(vec_add(vec_float4_c(t), vec_float4_c(rval))); - tt = vec_sub(tt, rval); - vec_int4 odd = vec_and(vec_sr(t, vec_uint4_sp(13)), vec_int4_sp(1)); - vec_int4 nt = vec_add(t, vec_int4_sp(0xc8000fff)); - nt = vec_sr(vec_add(nt, odd), vec_uint4_sp(13)); - t = vec_sel(nt, tt, tinymask); - t = vec_sel(naninf, t, finitemask); - t = vec_or(t, sign); - vec_st_l8(vec_packs(t, t), ptr); -#endif -} - -inline void v_cleanup() {} - - -/** Reinterpret **/ -/** its up there with load and store operations **/ - -////////// Matrix operations ///////// - -//////// Dot Product //////// -// 16 >> 32 -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) -{ return v_int32x4(vec_msum(a.val, b.val, vec_int4_z)); } -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ return v_int32x4(vec_msum(a.val, b.val, c.val)); } - -// 32 >> 64 -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) -{ - vec_dword2 even = vec_mule(a.val, b.val); - vec_dword2 odd = vec_mulo(a.val, b.val); - return v_int64x2(vec_add(even, odd)); -} -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ return v_add(v_dotprod(a, b), c); } - -// 8 >> 32 -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) -{ return v_uint32x4(vec_msum(a.val, b.val, c.val)); } -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) -{ return v_uint32x4(vec_msum(a.val, b.val, vec_uint4_z)); } - -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) -{ - const vec_ushort8 eight = vec_ushort8_sp(8); - vec_short8 a0 = vec_sra((vec_short8)vec_sld(a.val, a.val, 1), eight); // even - vec_short8 a1 = vec_sra((vec_short8)a.val, eight); // odd - vec_short8 b0 = vec_sra((vec_short8)vec_sld(b.val, b.val, 1), eight); - vec_short8 b1 = vec_sra((vec_short8)b.val, eight); - return v_int32x4(vec_msum(a0, b0, vec_msum(a1, b1, vec_int4_z))); -} - -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) -{ - const vec_ushort8 eight = vec_ushort8_sp(8); - vec_short8 a0 = vec_sra((vec_short8)vec_sld(a.val, a.val, 1), eight); // even - vec_short8 a1 = vec_sra((vec_short8)a.val, eight); // odd - vec_short8 b0 = vec_sra((vec_short8)vec_sld(b.val, b.val, 1), eight); - vec_short8 b1 = vec_sra((vec_short8)b.val, eight); - return v_int32x4(vec_msum(a0, b0, vec_msum(a1, b1, c.val))); -} - -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) -{ - const vec_uint4 zero = vec_uint4_z; - vec_uint4 even = vec_mule(a.val, b.val); - vec_uint4 odd = vec_mulo(a.val, b.val); - vec_udword2 e0 = (vec_udword2)vec_mergee(even, zero); - vec_udword2 e1 = (vec_udword2)vec_mergeo(even, zero); - vec_udword2 o0 = (vec_udword2)vec_mergee(odd, zero); - vec_udword2 o1 = (vec_udword2)vec_mergeo(odd, zero); - vec_udword2 s0 = vec_add(e0, o0); - vec_udword2 s1 = vec_add(e1, o1); - return v_uint64x2(vec_add(s0, s1)); -} -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) -{ - v_int32x4 prod = v_dotprod(a, b); - v_int64x2 c, d; - v_expand(prod, c, d); - return v_int64x2(vec_add(vec_mergeh(c.val, d.val), vec_mergel(c.val, d.val))); -} -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 32 >> 64f -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) -{ return v_cvt_f64(v_dotprod(a, b)); } -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -//////// Fast Dot Product //////// - -// 16 >> 32 -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) -{ return v_dotprod(a, b); } -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ return v_int32x4(vec_msum(a.val, b.val, vec_int4_z)) + c; } -// 32 >> 64 -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) -{ return v_dotprod(a, b); } -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ return v_dotprod(a, b, c); } - -// 8 >> 32 -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) -{ return v_dotprod_expand(a, b); } -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) -{ return v_uint32x4(vec_msum(a.val, b.val, vec_uint4_z)) + c; } - -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) -{ - vec_short8 a0 = vec_unpackh(a.val); - vec_short8 a1 = vec_unpackl(a.val); - vec_short8 b0 = vec_unpackh(b.val); - vec_short8 b1 = vec_unpackl(b.val); - return v_int32x4(vec_msum(a0, b0, vec_msum(a1, b1, vec_int4_z))); -} -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) -{ return v_dotprod_expand(a, b); } -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) -{ return v_dotprod_expand(a, b, c); } - -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) -{ - v_int32x4 prod = v_dotprod(a, b); - v_int64x2 c, d; - v_expand(prod, c, d); - return v_add(c, d); -} -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -// 32 >> 64f -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) -{ return v_dotprod_expand(a, b); } -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) -{ return v_dotprod_expand(a, b, c); } - -inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, - const v_float32x4& m3) -{ - const vec_float4 v0 = vec_splat(v.val, 0); - const vec_float4 v1 = vec_splat(v.val, 1); - const vec_float4 v2 = vec_splat(v.val, 2); - VSX_UNUSED(const vec_float4) v3 = vec_splat(v.val, 3); - return v_float32x4(vec_madd(v0, m0.val, vec_madd(v1, m1.val, vec_madd(v2, m2.val, vec_mul(v3, m3.val))))); -} - -inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, - const v_float32x4& a) -{ - const vec_float4 v0 = vec_splat(v.val, 0); - const vec_float4 v1 = vec_splat(v.val, 1); - const vec_float4 v2 = vec_splat(v.val, 2); - return v_float32x4(vec_madd(v0, m0.val, vec_madd(v1, m1.val, vec_madd(v2, m2.val, a.val)))); -} - -#define OPENCV_HAL_IMPL_VSX_TRANSPOSE4x4(_Tpvec, _Tpvec2) \ -inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ - const _Tpvec& a2, const _Tpvec& a3, \ - _Tpvec& b0, _Tpvec& b1, _Tpvec& b2, _Tpvec& b3) \ -{ \ - _Tpvec2 a02 = vec_mergeh(a0.val, a2.val); \ - _Tpvec2 a13 = vec_mergeh(a1.val, a3.val); \ - b0.val = vec_mergeh(a02, a13); \ - b1.val = vec_mergel(a02, a13); \ - a02 = vec_mergel(a0.val, a2.val); \ - a13 = vec_mergel(a1.val, a3.val); \ - b2.val = vec_mergeh(a02, a13); \ - b3.val = vec_mergel(a02, a13); \ -} -OPENCV_HAL_IMPL_VSX_TRANSPOSE4x4(v_uint32x4, vec_uint4) -OPENCV_HAL_IMPL_VSX_TRANSPOSE4x4(v_int32x4, vec_int4) -OPENCV_HAL_IMPL_VSX_TRANSPOSE4x4(v_float32x4, vec_float4) - -template -inline Tvec v_broadcast_element(const Tvec& v) -{ return Tvec(vec_splat(v.val, i)); } - -#include "intrin_math.hpp" -inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } -inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } -inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } -inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } -inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } -inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } - -inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } -inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } -inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } -inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } -inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} - -#endif // OPENCV_HAL_VSX_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +#ifndef OPENCV_HAL_VSX_HPP +#define OPENCV_HAL_VSX_HPP + +#include +#include "opencv2/core/utility.hpp" + +#define CV_SIMD128 1 +#define CV_SIMD128_64F 1 + +namespace cv +{ + +//! @cond IGNORED + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +///////// Types //////////// + +struct v_uint8x16 +{ + typedef uchar lane_type; + enum { nlanes = 16 }; + vec_uchar16 val; + + explicit v_uint8x16(const vec_uchar16& v) : val(v) + {} + v_uint8x16() + {} + v_uint8x16(vec_bchar16 v) : val(vec_uchar16_c(v)) + {} + v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, + uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) + : val(vec_uchar16_set(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15)) + {} + + static inline v_uint8x16 zero() { return v_uint8x16(vec_uchar16_z); } + + uchar get0() const + { return vec_extract(val, 0); } +}; + +struct v_int8x16 +{ + typedef schar lane_type; + enum { nlanes = 16 }; + vec_char16 val; + + explicit v_int8x16(const vec_char16& v) : val(v) + {} + v_int8x16() + {} + v_int8x16(vec_bchar16 v) : val(vec_char16_c(v)) + {} + v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, + schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) + : val(vec_char16_set(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15)) + {} + + static inline v_int8x16 zero() { return v_int8x16(vec_char16_z); } + + schar get0() const + { return vec_extract(val, 0); } +}; + +struct v_uint16x8 +{ + typedef ushort lane_type; + enum { nlanes = 8 }; + vec_ushort8 val; + + explicit v_uint16x8(const vec_ushort8& v) : val(v) + {} + v_uint16x8() + {} + v_uint16x8(vec_bshort8 v) : val(vec_ushort8_c(v)) + {} + v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) + : val(vec_ushort8_set(v0, v1, v2, v3, v4, v5, v6, v7)) + {} + + static inline v_uint16x8 zero() { return v_uint16x8(vec_ushort8_z); } + + ushort get0() const + { return vec_extract(val, 0); } +}; + +struct v_int16x8 +{ + typedef short lane_type; + enum { nlanes = 8 }; + vec_short8 val; + + explicit v_int16x8(const vec_short8& v) : val(v) + {} + v_int16x8() + {} + v_int16x8(vec_bshort8 v) : val(vec_short8_c(v)) + {} + v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) + : val(vec_short8_set(v0, v1, v2, v3, v4, v5, v6, v7)) + {} + + static inline v_int16x8 zero() { return v_int16x8(vec_short8_z); } + + short get0() const + { return vec_extract(val, 0); } +}; + +struct v_uint32x4 +{ + typedef unsigned lane_type; + enum { nlanes = 4 }; + vec_uint4 val; + + explicit v_uint32x4(const vec_uint4& v) : val(v) + {} + v_uint32x4() + {} + v_uint32x4(vec_bint4 v) : val(vec_uint4_c(v)) + {} + v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) : val(vec_uint4_set(v0, v1, v2, v3)) + {} + + static inline v_uint32x4 zero() { return v_uint32x4(vec_uint4_z); } + + uint get0() const + { return vec_extract(val, 0); } +}; + +struct v_int32x4 +{ + typedef int lane_type; + enum { nlanes = 4 }; + vec_int4 val; + + explicit v_int32x4(const vec_int4& v) : val(v) + {} + v_int32x4() + {} + v_int32x4(vec_bint4 v) : val(vec_int4_c(v)) + {} + v_int32x4(int v0, int v1, int v2, int v3) : val(vec_int4_set(v0, v1, v2, v3)) + {} + + static inline v_int32x4 zero() { return v_int32x4(vec_int4_z); } + + int get0() const + { return vec_extract(val, 0); } +}; + +struct v_float32x4 +{ + typedef float lane_type; + enum { nlanes = 4 }; + vec_float4 val; + + explicit v_float32x4(const vec_float4& v) : val(v) + {} + v_float32x4() + {} + v_float32x4(vec_bint4 v) : val(vec_float4_c(v)) + {} + v_float32x4(float v0, float v1, float v2, float v3) : val(vec_float4_set(v0, v1, v2, v3)) + {} + + static inline v_float32x4 zero() { return v_float32x4(vec_float4_z); } + + float get0() const + { return vec_extract(val, 0); } +}; + +struct v_uint64x2 +{ + typedef uint64 lane_type; + enum { nlanes = 2 }; + vec_udword2 val; + + explicit v_uint64x2(const vec_udword2& v) : val(v) + {} + v_uint64x2() + {} + v_uint64x2(vec_bdword2 v) : val(vec_udword2_c(v)) + {} + v_uint64x2(uint64 v0, uint64 v1) : val(vec_udword2_set(v0, v1)) + {} + + static inline v_uint64x2 zero() { return v_uint64x2(vec_udword2_z); } + + uint64 get0() const + { return vec_extract(val, 0); } +}; + +struct v_int64x2 +{ + typedef int64 lane_type; + enum { nlanes = 2 }; + vec_dword2 val; + + explicit v_int64x2(const vec_dword2& v) : val(v) + {} + v_int64x2() + {} + v_int64x2(vec_bdword2 v) : val(vec_dword2_c(v)) + {} + v_int64x2(int64 v0, int64 v1) : val(vec_dword2_set(v0, v1)) + {} + + static inline v_int64x2 zero() { return v_int64x2(vec_dword2_z); } + + int64 get0() const + { return vec_extract(val, 0); } +}; + +struct v_float64x2 +{ + typedef double lane_type; + enum { nlanes = 2 }; + vec_double2 val; + + explicit v_float64x2(const vec_double2& v) : val(v) + {} + v_float64x2() + {} + v_float64x2(vec_bdword2 v) : val(vec_double2_c(v)) + {} + v_float64x2(double v0, double v1) : val(vec_double2_set(v0, v1)) + {} + + static inline v_float64x2 zero() { return v_float64x2(vec_double2_z); } + + double get0() const + { return vec_extract(val, 0); } +}; + +#define OPENCV_HAL_IMPL_VSX_EXTRACT_N(_Tpvec, _Tp) \ +template inline _Tp v_extract_n(VSX_UNUSED(_Tpvec v)) { return vec_extract(v.val, i); } + +OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_uint8x16, uchar) +OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_int8x16, schar) +OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_uint16x8, ushort) +OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_int16x8, short) +OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_uint32x4, uint) +OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_int32x4, int) +OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_uint64x2, uint64) +OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_int64x2, int64) +OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_float32x4, float) +OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_float64x2, double) + +//////////////// Load and store operations /////////////// + +/* + * clang-5 aborted during parse "vec_xxx_c" only if it's + * inside a function template which is defined by preprocessor macro. + * + * if vec_xxx_c defined as C++ cast, clang-5 will pass it +*/ +#define OPENCV_HAL_IMPL_VSX_INITVEC(_Tpvec, _Tp, suffix, cast) \ +inline _Tpvec v_setzero_##suffix() { return _Tpvec(vec_splats((_Tp)0)); } \ +inline _Tpvec v_setall_##suffix(_Tp v) { return _Tpvec(vec_splats((_Tp)v));} \ +template <> inline _Tpvec v_setzero_() { return v_setzero_##suffix(); } \ +template <> inline _Tpvec v_setall_(_Tp v) { return v_setall_##suffix(_Tp v); } \ +template inline _Tpvec v_reinterpret_as_##suffix(const _Tpvec0 &a) \ +{ return _Tpvec((cast)a.val); } + +OPENCV_HAL_IMPL_VSX_INITVEC(v_uint8x16, uchar, u8, vec_uchar16) +OPENCV_HAL_IMPL_VSX_INITVEC(v_int8x16, schar, s8, vec_char16) +OPENCV_HAL_IMPL_VSX_INITVEC(v_uint16x8, ushort, u16, vec_ushort8) +OPENCV_HAL_IMPL_VSX_INITVEC(v_int16x8, short, s16, vec_short8) +OPENCV_HAL_IMPL_VSX_INITVEC(v_uint32x4, uint, u32, vec_uint4) +OPENCV_HAL_IMPL_VSX_INITVEC(v_int32x4, int, s32, vec_int4) +OPENCV_HAL_IMPL_VSX_INITVEC(v_uint64x2, uint64, u64, vec_udword2) +OPENCV_HAL_IMPL_VSX_INITVEC(v_int64x2, int64, s64, vec_dword2) +OPENCV_HAL_IMPL_VSX_INITVEC(v_float32x4, float, f32, vec_float4) +OPENCV_HAL_IMPL_VSX_INITVEC(v_float64x2, double, f64, vec_double2) + +#define OPENCV_HAL_IMPL_VSX_LOADSTORE_C(_Tpvec, _Tp, ld, ld_a, st, st_a) \ +inline _Tpvec v_load(const _Tp* ptr) \ +{ return _Tpvec(ld(0, ptr)); } \ +inline _Tpvec v_load_aligned(VSX_UNUSED(const _Tp* ptr)) \ +{ return _Tpvec(ld_a(0, ptr)); } \ +inline _Tpvec v_load_low(const _Tp* ptr) \ +{ return _Tpvec(vec_ld_l8(ptr)); } \ +inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ +{ return _Tpvec(vec_mergesqh(vec_ld_l8(ptr0), vec_ld_l8(ptr1))); } \ +inline void v_store(_Tp* ptr, const _Tpvec& a) \ +{ st(a.val, 0, ptr); } \ +inline void v_store_aligned(VSX_UNUSED(_Tp* ptr), const _Tpvec& a) \ +{ st_a(a.val, 0, ptr); } \ +inline void v_store_aligned_nocache(VSX_UNUSED(_Tp* ptr), const _Tpvec& a) \ +{ st_a(a.val, 0, ptr); } \ +inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ +{ if(mode == hal::STORE_UNALIGNED) st(a.val, 0, ptr); else st_a(a.val, 0, ptr); } \ +inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ +{ vec_st_l8(a.val, ptr); } \ +inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ +{ vec_st_h8(a.val, ptr); } + +// working around gcc bug for aligned ld/st +// if runtime check for vec_ld/st fail we failback to unaligned ld/st +// https://github.com/opencv/opencv/issues/13211 +#ifdef CV_COMPILER_VSX_BROKEN_ALIGNED + #define OPENCV_HAL_IMPL_VSX_LOADSTORE(_Tpvec, _Tp) \ + OPENCV_HAL_IMPL_VSX_LOADSTORE_C(_Tpvec, _Tp, vsx_ld, vsx_ld, vsx_st, vsx_st) +#else + #define OPENCV_HAL_IMPL_VSX_LOADSTORE(_Tpvec, _Tp) \ + OPENCV_HAL_IMPL_VSX_LOADSTORE_C(_Tpvec, _Tp, vsx_ld, vec_ld, vsx_st, vec_st) +#endif + +OPENCV_HAL_IMPL_VSX_LOADSTORE(v_uint8x16, uchar) +OPENCV_HAL_IMPL_VSX_LOADSTORE(v_int8x16, schar) +OPENCV_HAL_IMPL_VSX_LOADSTORE(v_uint16x8, ushort) +OPENCV_HAL_IMPL_VSX_LOADSTORE(v_int16x8, short) +OPENCV_HAL_IMPL_VSX_LOADSTORE(v_uint32x4, uint) +OPENCV_HAL_IMPL_VSX_LOADSTORE(v_int32x4, int) +OPENCV_HAL_IMPL_VSX_LOADSTORE(v_float32x4, float) + +OPENCV_HAL_IMPL_VSX_LOADSTORE_C(v_float64x2, double, vsx_ld, vsx_ld, vsx_st, vsx_st) +OPENCV_HAL_IMPL_VSX_LOADSTORE_C(v_uint64x2, uint64, vsx_ld2, vsx_ld2, vsx_st2, vsx_st2) +OPENCV_HAL_IMPL_VSX_LOADSTORE_C(v_int64x2, int64, vsx_ld2, vsx_ld2, vsx_st2, vsx_st2) + +//////////////// Value reordering /////////////// + +/* de&interleave */ +#define OPENCV_HAL_IMPL_VSX_INTERLEAVE(_Tp, _Tpvec) \ +inline void v_load_deinterleave(const _Tp* ptr, _Tpvec& a, _Tpvec& b) \ +{ vec_ld_deinterleave(ptr, a.val, b.val);} \ +inline void v_load_deinterleave(const _Tp* ptr, _Tpvec& a, \ + _Tpvec& b, _Tpvec& c) \ +{ vec_ld_deinterleave(ptr, a.val, b.val, c.val); } \ +inline void v_load_deinterleave(const _Tp* ptr, _Tpvec& a, _Tpvec& b, \ + _Tpvec& c, _Tpvec& d) \ +{ vec_ld_deinterleave(ptr, a.val, b.val, c.val, d.val); } \ +inline void v_store_interleave(_Tp* ptr, const _Tpvec& a, const _Tpvec& b, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ vec_st_interleave(a.val, b.val, ptr); } \ +inline void v_store_interleave(_Tp* ptr, const _Tpvec& a, \ + const _Tpvec& b, const _Tpvec& c, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ vec_st_interleave(a.val, b.val, c.val, ptr); } \ +inline void v_store_interleave(_Tp* ptr, const _Tpvec& a, const _Tpvec& b, \ + const _Tpvec& c, const _Tpvec& d, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ vec_st_interleave(a.val, b.val, c.val, d.val, ptr); } + +OPENCV_HAL_IMPL_VSX_INTERLEAVE(uchar, v_uint8x16) +OPENCV_HAL_IMPL_VSX_INTERLEAVE(schar, v_int8x16) +OPENCV_HAL_IMPL_VSX_INTERLEAVE(ushort, v_uint16x8) +OPENCV_HAL_IMPL_VSX_INTERLEAVE(short, v_int16x8) +OPENCV_HAL_IMPL_VSX_INTERLEAVE(uint, v_uint32x4) +OPENCV_HAL_IMPL_VSX_INTERLEAVE(int, v_int32x4) +OPENCV_HAL_IMPL_VSX_INTERLEAVE(float, v_float32x4) +OPENCV_HAL_IMPL_VSX_INTERLEAVE(double, v_float64x2) +OPENCV_HAL_IMPL_VSX_INTERLEAVE(int64, v_int64x2) +OPENCV_HAL_IMPL_VSX_INTERLEAVE(uint64, v_uint64x2) + +/* Expand */ +#define OPENCV_HAL_IMPL_VSX_EXPAND(_Tpvec, _Tpwvec, _Tp, fl, fh) \ +inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ +{ \ + b0.val = fh(a.val); \ + b1.val = fl(a.val); \ +} \ +inline _Tpwvec v_expand_low(const _Tpvec& a) \ +{ return _Tpwvec(fh(a.val)); } \ +inline _Tpwvec v_expand_high(const _Tpvec& a) \ +{ return _Tpwvec(fl(a.val)); } \ +inline _Tpwvec v_load_expand(const _Tp* ptr) \ +{ return _Tpwvec(fh(vec_ld_l8(ptr))); } + +OPENCV_HAL_IMPL_VSX_EXPAND(v_uint8x16, v_uint16x8, uchar, vec_unpacklu, vec_unpackhu) +OPENCV_HAL_IMPL_VSX_EXPAND(v_int8x16, v_int16x8, schar, vec_unpackl, vec_unpackh) +OPENCV_HAL_IMPL_VSX_EXPAND(v_uint16x8, v_uint32x4, ushort, vec_unpacklu, vec_unpackhu) +OPENCV_HAL_IMPL_VSX_EXPAND(v_int16x8, v_int32x4, short, vec_unpackl, vec_unpackh) +OPENCV_HAL_IMPL_VSX_EXPAND(v_uint32x4, v_uint64x2, uint, vec_unpacklu, vec_unpackhu) +OPENCV_HAL_IMPL_VSX_EXPAND(v_int32x4, v_int64x2, int, vec_unpackl, vec_unpackh) + +/* Load and zero expand a 4 byte value into the second dword, first is don't care. */ +#if !defined(CV_COMPILER_VSX_BROKEN_ASM) + #define _LXSIWZX(out, ptr, T) __asm__ ("lxsiwzx %x0, 0, %1\r\n" : "=wa"(out) : "r" (ptr) : "memory"); +#else + /* This is compiler-agnostic, but will introduce an unneeded splat on the critical path. */ + #define _LXSIWZX(out, ptr, T) out = (T)vec_udword2_sp(*(uint32_t*)(ptr)); +#endif + +inline v_uint32x4 v_load_expand_q(const uchar* ptr) +{ + // Zero-extend the extra 24B instead of unpacking. Usually faster in small kernel + // Likewise note, value is zero extended and upper 4 bytes are zero'ed. + vec_uchar16 pmu = {8, 12, 12, 12, 9, 12, 12, 12, 10, 12, 12, 12, 11, 12, 12, 12}; + vec_uchar16 out; + + _LXSIWZX(out, ptr, vec_uchar16); + out = vec_perm(out, out, pmu); + return v_uint32x4((vec_uint4)out); +} + +inline v_int32x4 v_load_expand_q(const schar* ptr) +{ + vec_char16 out; + vec_short8 outs; + vec_int4 outw; + + _LXSIWZX(out, ptr, vec_char16); + outs = vec_unpackl(out); + outw = vec_unpackh(outs); + return v_int32x4(outw); +} + +/* pack */ +#define OPENCV_HAL_IMPL_VSX_PACK(_Tpvec, _Tp, _Tpwvec, _Tpvn, _Tpdel, sfnc, pkfnc, addfnc, pack) \ +inline _Tpvec v_##pack(const _Tpwvec& a, const _Tpwvec& b) \ +{ \ + return _Tpvec(pkfnc(a.val, b.val)); \ +} \ +inline void v_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ +{ \ + vec_st_l8(pkfnc(a.val, a.val), ptr); \ +} \ +template \ +inline _Tpvec v_rshr_##pack(const _Tpwvec& a, const _Tpwvec& b) \ +{ \ + const __vector _Tpvn vn = vec_splats((_Tpvn)n); \ + const __vector _Tpdel delta = vec_splats((_Tpdel)((_Tpdel)1 << (n-1))); \ + return _Tpvec(pkfnc(sfnc(addfnc(a.val, delta), vn), sfnc(addfnc(b.val, delta), vn))); \ +} \ +template \ +inline void v_rshr_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ +{ \ + const __vector _Tpvn vn = vec_splats((_Tpvn)n); \ + const __vector _Tpdel delta = vec_splats((_Tpdel)((_Tpdel)1 << (n-1))); \ + vec_st_l8(pkfnc(sfnc(addfnc(a.val, delta), vn), delta), ptr); \ +} + +OPENCV_HAL_IMPL_VSX_PACK(v_uint8x16, uchar, v_uint16x8, unsigned short, unsigned short, + vec_sr, vec_packs, vec_adds, pack) +OPENCV_HAL_IMPL_VSX_PACK(v_int8x16, schar, v_int16x8, unsigned short, short, + vec_sra, vec_packs, vec_adds, pack) + +OPENCV_HAL_IMPL_VSX_PACK(v_uint16x8, ushort, v_uint32x4, unsigned int, unsigned int, + vec_sr, vec_packs, vec_add, pack) +OPENCV_HAL_IMPL_VSX_PACK(v_int16x8, short, v_int32x4, unsigned int, int, + vec_sra, vec_packs, vec_add, pack) + +OPENCV_HAL_IMPL_VSX_PACK(v_uint32x4, uint, v_uint64x2, unsigned long long, unsigned long long, + vec_sr, vec_pack, vec_add, pack) +OPENCV_HAL_IMPL_VSX_PACK(v_int32x4, int, v_int64x2, unsigned long long, long long, + vec_sra, vec_pack, vec_add, pack) + +OPENCV_HAL_IMPL_VSX_PACK(v_uint8x16, uchar, v_int16x8, unsigned short, short, + vec_sra, vec_packsu, vec_adds, pack_u) +OPENCV_HAL_IMPL_VSX_PACK(v_uint16x8, ushort, v_int32x4, unsigned int, int, + vec_sra, vec_packsu, vec_add, pack_u) +// Following variant is not implemented on other platforms: +//OPENCV_HAL_IMPL_VSX_PACK(v_uint32x4, uint, v_int64x2, unsigned long long, long long, +// vec_sra, vec_packsu, vec_add, pack_u) + +// pack boolean +inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) +{ + vec_uchar16 ab = vec_pack(a.val, b.val); + return v_uint8x16(ab); +} + +inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, + const v_uint32x4& c, const v_uint32x4& d) +{ + vec_ushort8 ab = vec_pack(a.val, b.val); + vec_ushort8 cd = vec_pack(c.val, d.val); + return v_uint8x16(vec_pack(ab, cd)); +} + +inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, + const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, + const v_uint64x2& g, const v_uint64x2& h) +{ + vec_uint4 ab = vec_pack(a.val, b.val); + vec_uint4 cd = vec_pack(c.val, d.val); + vec_uint4 ef = vec_pack(e.val, f.val); + vec_uint4 gh = vec_pack(g.val, h.val); + + vec_ushort8 abcd = vec_pack(ab, cd); + vec_ushort8 efgh = vec_pack(ef, gh); + return v_uint8x16(vec_pack(abcd, efgh)); +} + +/* Recombine */ +template +inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) +{ + b0.val = vec_mergeh(a0.val, a1.val); + b1.val = vec_mergel(a0.val, a1.val); +} + +template +inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) +{ return _Tpvec(vec_mergesql(a.val, b.val)); } + +template +inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) +{ return _Tpvec(vec_mergesqh(a.val, b.val)); } + +template +inline void v_recombine(const _Tpvec& a, const _Tpvec& b, _Tpvec& c, _Tpvec& d) +{ + c.val = vec_mergesqh(a.val, b.val); + d.val = vec_mergesql(a.val, b.val); +} + +////////// Arithmetic, bitwise and comparison operations ///////// + +/* Element-wise binary and unary operations */ +/** Arithmetics **/ +#define OPENCV_HAL_IMPL_VSX_BIN_OP(bin_op, _Tpvec, intrin) \ +inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(intrin(a.val, b.val)); } + +OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_uint8x16, vec_adds) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_uint8x16, vec_subs) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_int8x16, vec_adds) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_int8x16, vec_subs) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_uint16x8, vec_adds) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_uint16x8, vec_subs) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_int16x8, vec_adds) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_int16x8, vec_subs) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_uint32x4, vec_add) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_uint32x4, vec_sub) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_mul, v_uint32x4, vec_mul) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_int32x4, vec_add) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_int32x4, vec_sub) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_mul, v_int32x4, vec_mul) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_float32x4, vec_add) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_float32x4, vec_sub) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_mul, v_float32x4, vec_mul) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_div, v_float32x4, vec_div) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_float64x2, vec_add) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_float64x2, vec_sub) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_mul, v_float64x2, vec_mul) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_div, v_float64x2, vec_div) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_uint64x2, vec_add) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_uint64x2, vec_sub) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_int64x2, vec_add) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_int64x2, vec_sub) + +// saturating multiply +#define OPENCV_HAL_IMPL_VSX_MUL_SAT(_Tpvec, _Tpwvec) \ + inline _Tpvec v_mul(const _Tpvec& a, const _Tpvec& b) \ + { \ + _Tpwvec c, d; \ + v_mul_expand(a, b, c, d); \ + return v_pack(c, d); \ + } + +OPENCV_HAL_IMPL_VSX_MUL_SAT(v_int8x16, v_int16x8) +OPENCV_HAL_IMPL_VSX_MUL_SAT(v_uint8x16, v_uint16x8) +OPENCV_HAL_IMPL_VSX_MUL_SAT(v_int16x8, v_int32x4) +OPENCV_HAL_IMPL_VSX_MUL_SAT(v_uint16x8, v_uint32x4) + +template +inline void v_mul_expand(const Tvec& a, const Tvec& b, Twvec& c, Twvec& d) +{ + Twvec p0 = Twvec(vec_mule(a.val, b.val)); + Twvec p1 = Twvec(vec_mulo(a.val, b.val)); + v_zip(p0, p1, c, d); +} + +inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) +{ + vec_int4 p0 = vec_mule(a.val, b.val); + vec_int4 p1 = vec_mulo(a.val, b.val); + static const vec_uchar16 perm = {2, 3, 18, 19, 6, 7, 22, 23, 10, 11, 26, 27, 14, 15, 30, 31}; + return v_int16x8(vec_perm(vec_short8_c(p0), vec_short8_c(p1), perm)); +} +inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) +{ + vec_uint4 p0 = vec_mule(a.val, b.val); + vec_uint4 p1 = vec_mulo(a.val, b.val); + static const vec_uchar16 perm = {2, 3, 18, 19, 6, 7, 22, 23, 10, 11, 26, 27, 14, 15, 30, 31}; + return v_uint16x8(vec_perm(vec_ushort8_c(p0), vec_ushort8_c(p1), perm)); +} + +/** Non-saturating arithmetics **/ +#define OPENCV_HAL_IMPL_VSX_BIN_FUNC(func, intrin) \ +template \ +inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(intrin(a.val, b.val)); } + +OPENCV_HAL_IMPL_VSX_BIN_FUNC(v_add_wrap, vec_add) +OPENCV_HAL_IMPL_VSX_BIN_FUNC(v_sub_wrap, vec_sub) +OPENCV_HAL_IMPL_VSX_BIN_FUNC(v_mul_wrap, vec_mul) + +/** Bitwise shifts **/ +#define OPENCV_HAL_IMPL_VSX_SHIFT_OP(_Tpvec, shr, splfunc) \ +inline _Tpvec v_shl(const _Tpvec& a, int imm) \ +{ return _Tpvec(vec_sl(a.val, splfunc(imm))); } \ +inline _Tpvec v_shr(const _Tpvec& a, int imm) \ +{ return _Tpvec(shr(a.val, splfunc(imm))); } \ +template inline _Tpvec v_shl(const _Tpvec& a) \ +{ return _Tpvec(vec_sl(a.val, splfunc(imm))); } \ +template inline _Tpvec v_shr(const _Tpvec& a) \ +{ return _Tpvec(shr(a.val, splfunc(imm))); } + +OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_uint8x16, vec_sr, vec_uchar16_sp) +OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_uint16x8, vec_sr, vec_ushort8_sp) +OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_uint32x4, vec_sr, vec_uint4_sp) +OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_uint64x2, vec_sr, vec_udword2_sp) +// algebraic right shift +OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_int8x16, vec_sra, vec_uchar16_sp) +OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_int16x8, vec_sra, vec_ushort8_sp) +OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_int32x4, vec_sra, vec_uint4_sp) +OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_int64x2, vec_sra, vec_udword2_sp) + +/** Bitwise logic **/ +#define OPENCV_HAL_IMPL_VSX_LOGIC_OP(_Tpvec) \ +OPENCV_HAL_IMPL_VSX_BIN_OP(v_and, _Tpvec, vec_and) \ +OPENCV_HAL_IMPL_VSX_BIN_OP(v_or, _Tpvec, vec_or) \ +OPENCV_HAL_IMPL_VSX_BIN_OP(v_xor, _Tpvec, vec_xor) \ +inline _Tpvec v_not(const _Tpvec& a) \ +{ return _Tpvec(vec_not(a.val)); } + +OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_uint8x16) +OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_int8x16) +OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_uint16x8) +OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_int16x8) +OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_uint32x4) +OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_int32x4) +OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_uint64x2) +OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_int64x2) +OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_float32x4) +OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_float64x2) + +/** Bitwise select **/ +#define OPENCV_HAL_IMPL_VSX_SELECT(_Tpvec, cast) \ +inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(vec_sel(b.val, a.val, cast(mask.val))); } + +OPENCV_HAL_IMPL_VSX_SELECT(v_uint8x16, vec_bchar16_c) +OPENCV_HAL_IMPL_VSX_SELECT(v_int8x16, vec_bchar16_c) +OPENCV_HAL_IMPL_VSX_SELECT(v_uint16x8, vec_bshort8_c) +OPENCV_HAL_IMPL_VSX_SELECT(v_int16x8, vec_bshort8_c) +OPENCV_HAL_IMPL_VSX_SELECT(v_uint32x4, vec_bint4_c) +OPENCV_HAL_IMPL_VSX_SELECT(v_int32x4, vec_bint4_c) +OPENCV_HAL_IMPL_VSX_SELECT(v_float32x4, vec_bint4_c) +OPENCV_HAL_IMPL_VSX_SELECT(v_float64x2, vec_bdword2_c) + +/** Comparison **/ +#define OPENCV_HAL_IMPL_VSX_INT_CMP_OP(_Tpvec) \ +inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(vec_cmpeq(a.val, b.val)); } \ +inline _Tpvec V_ne(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(vec_cmpne(a.val, b.val)); } \ +inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(vec_cmplt(a.val, b.val)); } \ +inline _Tpvec V_gt(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(vec_cmpgt(a.val, b.val)); } \ +inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(vec_cmple(a.val, b.val)); } \ +inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(vec_cmpge(a.val, b.val)); } + +OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_uint8x16) +OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_int8x16) +OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_uint16x8) +OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_int16x8) +OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_uint32x4) +OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_int32x4) +OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_float32x4) +OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_float64x2) +OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_uint64x2) +OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_int64x2) + +inline v_float32x4 v_not_nan(const v_float32x4& a) +{ return v_float32x4(vec_cmpeq(a.val, a.val)); } +inline v_float64x2 v_not_nan(const v_float64x2& a) +{ return v_float64x2(vec_cmpeq(a.val, a.val)); } + +/** min/max **/ +OPENCV_HAL_IMPL_VSX_BIN_FUNC(v_min, vec_min) +OPENCV_HAL_IMPL_VSX_BIN_FUNC(v_max, vec_max) + +/** Rotate **/ +#define OPENCV_IMPL_VSX_ROTATE(_Tpvec, suffix, shf, cast) \ +template \ +inline _Tpvec v_rotate_##suffix(const _Tpvec& a) \ +{ \ + const int wd = imm * sizeof(typename _Tpvec::lane_type); \ + if (wd > 15) \ + return _Tpvec::zero(); \ + return _Tpvec((cast)shf(vec_uchar16_c(a.val), vec_uchar16_sp(wd << 3))); \ +} + +#define OPENCV_IMPL_VSX_ROTATE_LR(_Tpvec, cast) \ +OPENCV_IMPL_VSX_ROTATE(_Tpvec, left, vec_slo, cast) \ +OPENCV_IMPL_VSX_ROTATE(_Tpvec, right, vec_sro, cast) + +OPENCV_IMPL_VSX_ROTATE_LR(v_uint8x16, vec_uchar16) +OPENCV_IMPL_VSX_ROTATE_LR(v_int8x16, vec_char16) +OPENCV_IMPL_VSX_ROTATE_LR(v_uint16x8, vec_ushort8) +OPENCV_IMPL_VSX_ROTATE_LR(v_int16x8, vec_short8) +OPENCV_IMPL_VSX_ROTATE_LR(v_uint32x4, vec_uint4) +OPENCV_IMPL_VSX_ROTATE_LR(v_int32x4, vec_int4) +OPENCV_IMPL_VSX_ROTATE_LR(v_float32x4, vec_float4) +OPENCV_IMPL_VSX_ROTATE_LR(v_uint64x2, vec_udword2) +OPENCV_IMPL_VSX_ROTATE_LR(v_int64x2, vec_dword2) +OPENCV_IMPL_VSX_ROTATE_LR(v_float64x2, vec_double2) + +template +inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) +{ + enum { CV_SHIFT = 16 - imm * (sizeof(typename _Tpvec::lane_type)) }; + if (CV_SHIFT == 16) + return a; +#ifdef __IBMCPP__ + return _Tpvec(vec_sld(b.val, a.val, CV_SHIFT & 15)); +#else + return _Tpvec(vec_sld(b.val, a.val, CV_SHIFT)); +#endif +} + +template +inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) +{ + enum { CV_SHIFT = imm * (sizeof(typename _Tpvec::lane_type)) }; + if (CV_SHIFT == 16) + return b; + return _Tpvec(vec_sld(a.val, b.val, CV_SHIFT)); +} + +#define OPENCV_IMPL_VSX_ROTATE_64_2RG(_Tpvec, suffix, rg1, rg2) \ +template \ +inline _Tpvec v_rotate_##suffix(const _Tpvec& a, const _Tpvec& b) \ +{ \ + if (imm == 1) \ + return _Tpvec(vec_permi(rg1.val, rg2.val, 2)); \ + return imm ? b : a; \ +} + +#define OPENCV_IMPL_VSX_ROTATE_64_2RG_LR(_Tpvec) \ +OPENCV_IMPL_VSX_ROTATE_64_2RG(_Tpvec, left, b, a) \ +OPENCV_IMPL_VSX_ROTATE_64_2RG(_Tpvec, right, a, b) + +OPENCV_IMPL_VSX_ROTATE_64_2RG_LR(v_float64x2) +OPENCV_IMPL_VSX_ROTATE_64_2RG_LR(v_uint64x2) +OPENCV_IMPL_VSX_ROTATE_64_2RG_LR(v_int64x2) + +/* Reverse */ +inline v_uint8x16 v_reverse(const v_uint8x16 &a) +{ + static const vec_uchar16 perm = {15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; + vec_uchar16 vec = (vec_uchar16)a.val; + return v_uint8x16(vec_perm(vec, vec, perm)); +} + +inline v_int8x16 v_reverse(const v_int8x16 &a) +{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } + +inline v_uint16x8 v_reverse(const v_uint16x8 &a) +{ + static const vec_uchar16 perm = {14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1}; + vec_uchar16 vec = (vec_uchar16)a.val; + return v_reinterpret_as_u16(v_uint8x16(vec_perm(vec, vec, perm))); +} + +inline v_int16x8 v_reverse(const v_int16x8 &a) +{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } + +inline v_uint32x4 v_reverse(const v_uint32x4 &a) +{ + static const vec_uchar16 perm = {12, 13, 14, 15, 8, 9, 10, 11, 4, 5, 6, 7, 0, 1, 2, 3}; + vec_uchar16 vec = (vec_uchar16)a.val; + return v_reinterpret_as_u32(v_uint8x16(vec_perm(vec, vec, perm))); +} + +inline v_int32x4 v_reverse(const v_int32x4 &a) +{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_float32x4 v_reverse(const v_float32x4 &a) +{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_uint64x2 v_reverse(const v_uint64x2 &a) +{ + static const vec_uchar16 perm = {8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7}; + vec_uchar16 vec = (vec_uchar16)a.val; + return v_reinterpret_as_u64(v_uint8x16(vec_perm(vec, vec, perm))); +} + +inline v_int64x2 v_reverse(const v_int64x2 &a) +{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } + +inline v_float64x2 v_reverse(const v_float64x2 &a) +{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } + +/* Extract */ +template +inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) +{ return v_rotate_right(a, b); } + +////////// Reduce and mask ///////// + +/** Reduce **/ +inline uint v_reduce_sum(const v_uint8x16& a) +{ + const vec_uint4 zero4 = vec_uint4_z; + vec_uint4 sum4 = vec_sum4s(a.val, zero4); + return (uint)vec_extract(vec_sums(vec_int4_c(sum4), vec_int4_c(zero4)), 3); +} +inline int v_reduce_sum(const v_int8x16& a) +{ + const vec_int4 zero4 = vec_int4_z; + vec_int4 sum4 = vec_sum4s(a.val, zero4); + return (int)vec_extract(vec_sums(sum4, zero4), 3); +} +inline int v_reduce_sum(const v_int16x8& a) +{ + const vec_int4 zero = vec_int4_z; + return saturate_cast(vec_extract(vec_sums(vec_sum4s(a.val, zero), zero), 3)); +} +inline uint v_reduce_sum(const v_uint16x8& a) +{ + const vec_int4 v4 = vec_int4_c(vec_unpackhu(vec_adds(a.val, vec_sld(a.val, a.val, 8)))); + return saturate_cast(vec_extract(vec_sums(v4, vec_int4_z), 3)); +} + +#define OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(_Tpvec, _Tpvec2, scalartype, suffix, func) \ +inline scalartype v_reduce_##suffix(const _Tpvec& a) \ +{ \ + const _Tpvec2 rs = func(a.val, vec_sld(a.val, a.val, 8)); \ + return vec_extract(func(rs, vec_sld(rs, rs, 4)), 0); \ +} +OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_uint32x4, vec_uint4, uint, sum, vec_add) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_uint32x4, vec_uint4, uint, max, vec_max) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_uint32x4, vec_uint4, uint, min, vec_min) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_int32x4, vec_int4, int, sum, vec_add) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_int32x4, vec_int4, int, max, vec_max) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_int32x4, vec_int4, int, min, vec_min) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_float32x4, vec_float4, float, sum, vec_add) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_float32x4, vec_float4, float, max, vec_max) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_float32x4, vec_float4, float, min, vec_min) + +inline uint64 v_reduce_sum(const v_uint64x2& a) +{ + return vec_extract(vec_add(a.val, vec_permi(a.val, a.val, 3)), 0); +} +inline int64 v_reduce_sum(const v_int64x2& a) +{ + return vec_extract(vec_add(a.val, vec_permi(a.val, a.val, 3)), 0); +} +inline double v_reduce_sum(const v_float64x2& a) +{ + return vec_extract(vec_add(a.val, vec_permi(a.val, a.val, 3)), 0); +} + +#define OPENCV_HAL_IMPL_VSX_REDUCE_OP_8(_Tpvec, _Tpvec2, scalartype, suffix, func) \ +inline scalartype v_reduce_##suffix(const _Tpvec& a) \ +{ \ + _Tpvec2 rs = func(a.val, vec_sld(a.val, a.val, 8)); \ + rs = func(rs, vec_sld(rs, rs, 4)); \ + return vec_extract(func(rs, vec_sld(rs, rs, 2)), 0); \ +} +OPENCV_HAL_IMPL_VSX_REDUCE_OP_8(v_uint16x8, vec_ushort8, ushort, max, vec_max) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_8(v_uint16x8, vec_ushort8, ushort, min, vec_min) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_8(v_int16x8, vec_short8, short, max, vec_max) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_8(v_int16x8, vec_short8, short, min, vec_min) + +#define OPENCV_HAL_IMPL_VSX_REDUCE_OP_16(_Tpvec, _Tpvec2, scalartype, suffix, func) \ +inline scalartype v_reduce_##suffix(const _Tpvec& a) \ +{ \ + _Tpvec2 rs = func(a.val, vec_sld(a.val, a.val, 8)); \ + rs = func(rs, vec_sld(rs, rs, 4)); \ + rs = func(rs, vec_sld(rs, rs, 2)); \ + return vec_extract(func(rs, vec_sld(rs, rs, 1)), 0); \ +} +OPENCV_HAL_IMPL_VSX_REDUCE_OP_16(v_uint8x16, vec_uchar16, uchar, max, vec_max) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_16(v_uint8x16, vec_uchar16, uchar, min, vec_min) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_16(v_int8x16, vec_char16, schar, max, vec_max) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_16(v_int8x16, vec_char16, schar, min, vec_min) + +inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, + const v_float32x4& c, const v_float32x4& d) +{ + vec_float4 ac = vec_add(vec_mergel(a.val, c.val), vec_mergeh(a.val, c.val)); + ac = vec_add(ac, vec_sld(ac, ac, 8)); + + vec_float4 bd = vec_add(vec_mergel(b.val, d.val), vec_mergeh(b.val, d.val)); + bd = vec_add(bd, vec_sld(bd, bd, 8)); + return v_float32x4(vec_mergeh(ac, bd)); +} + +inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b) +{ + const vec_uint4 zero4 = vec_uint4_z; + vec_uint4 sum4 = vec_sum4s(vec_absd(a.val, b.val), zero4); + return (unsigned)vec_extract(vec_sums(vec_int4_c(sum4), vec_int4_c(zero4)), 3); +} +inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b) +{ + const vec_int4 zero4 = vec_int4_z; + vec_char16 ad = vec_abss(vec_subs(a.val, b.val)); + vec_int4 sum4 = vec_sum4s(ad, zero4); + return (unsigned)vec_extract(vec_sums(sum4, zero4), 3); +} +inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b) +{ + vec_ushort8 ad = vec_absd(a.val, b.val); + VSX_UNUSED(vec_int4) sum = vec_sums(vec_int4_c(vec_unpackhu(ad)) + vec_int4_c(vec_unpacklu(ad)), vec_int4_z); + return (unsigned)vec_extract(sum, 3); +} +inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b) +{ + const vec_int4 zero4 = vec_int4_z; + vec_short8 ad = vec_abss(vec_subs(a.val, b.val)); + vec_int4 sum4 = vec_sum4s(ad, zero4); + return (unsigned)vec_extract(vec_sums(sum4, zero4), 3); +} +inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b) +{ + const vec_uint4 ad = vec_absd(a.val, b.val); + const vec_uint4 rd = vec_add(ad, vec_sld(ad, ad, 8)); + return vec_extract(vec_add(rd, vec_sld(rd, rd, 4)), 0); +} +inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b) +{ + vec_int4 ad = vec_abss(vec_sub(a.val, b.val)); + return (unsigned)vec_extract(vec_sums(ad, vec_int4_z), 3); +} +inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) +{ + const vec_float4 ad = vec_abs(vec_sub(a.val, b.val)); + const vec_float4 rd = vec_add(ad, vec_sld(ad, ad, 8)); + return vec_extract(vec_add(rd, vec_sld(rd, rd, 4)), 0); +} + +/** Popcount **/ +inline v_uint8x16 v_popcount(const v_uint8x16& a) +{ return v_uint8x16(vec_popcntu(a.val)); } +inline v_uint8x16 v_popcount(const v_int8x16& a) +{ return v_uint8x16(vec_popcntu(a.val)); } +inline v_uint16x8 v_popcount(const v_uint16x8& a) +{ return v_uint16x8(vec_popcntu(a.val)); } +inline v_uint16x8 v_popcount(const v_int16x8& a) +{ return v_uint16x8(vec_popcntu(a.val)); } +inline v_uint32x4 v_popcount(const v_uint32x4& a) +{ return v_uint32x4(vec_popcntu(a.val)); } +inline v_uint32x4 v_popcount(const v_int32x4& a) +{ return v_uint32x4(vec_popcntu(a.val)); } +inline v_uint64x2 v_popcount(const v_uint64x2& a) +{ return v_uint64x2(vec_popcntu(a.val)); } +inline v_uint64x2 v_popcount(const v_int64x2& a) +{ return v_uint64x2(vec_popcntu(a.val)); } + +/** Mask **/ +inline int v_signmask(const v_uint8x16& a) +{ + static const vec_uchar16 qperm = {120, 112, 104, 96, 88, 80, 72, 64, 56, 48, 40, 32, 24, 16, 8, 0}; + return vec_extract((vec_int4)vec_vbpermq(v_reinterpret_as_u8(a).val, qperm), 2); +} +inline int v_signmask(const v_int8x16& a) +{ return v_signmask(v_reinterpret_as_u8(a)); } + +inline int v_signmask(const v_int16x8& a) +{ + static const vec_uchar16 qperm = {112, 96, 80, 64, 48, 32, 16, 0, 128, 128, 128, 128, 128, 128, 128, 128}; + return vec_extract((vec_int4)vec_vbpermq(v_reinterpret_as_u8(a).val, qperm), 2); +} +inline int v_signmask(const v_uint16x8& a) +{ return v_signmask(v_reinterpret_as_s16(a)); } + +inline int v_signmask(const v_int32x4& a) +{ + static const vec_uchar16 qperm = {96, 64, 32, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}; + return vec_extract((vec_int4)vec_vbpermq(v_reinterpret_as_u8(a).val, qperm), 2); +} +inline int v_signmask(const v_uint32x4& a) +{ return v_signmask(v_reinterpret_as_s32(a)); } +inline int v_signmask(const v_float32x4& a) +{ return v_signmask(v_reinterpret_as_s32(a)); } + +inline int v_signmask(const v_int64x2& a) +{ + VSX_UNUSED(const vec_dword2) sv = vec_sr(a.val, vec_udword2_sp(63)); + return (int)vec_extract(sv, 0) | (int)vec_extract(sv, 1) << 1; +} +inline int v_signmask(const v_uint64x2& a) +{ return v_signmask(v_reinterpret_as_s64(a)); } +inline int v_signmask(const v_float64x2& a) +{ return v_signmask(v_reinterpret_as_s64(a)); } + +inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(a)); } + +template +inline bool v_check_all(const _Tpvec& a) +{ return vec_all_lt(a.val, _Tpvec::zero().val); } +inline bool v_check_all(const v_uint8x16& a) +{ return v_check_all(v_reinterpret_as_s8(a)); } +inline bool v_check_all(const v_uint16x8& a) +{ return v_check_all(v_reinterpret_as_s16(a)); } +inline bool v_check_all(const v_uint32x4& a) +{ return v_check_all(v_reinterpret_as_s32(a)); } +inline bool v_check_all(const v_uint64x2& a) +{ return v_check_all(v_reinterpret_as_s64(a)); } +inline bool v_check_all(const v_float32x4& a) +{ return v_check_all(v_reinterpret_as_s32(a)); } +inline bool v_check_all(const v_float64x2& a) +{ return v_check_all(v_reinterpret_as_s64(a)); } + +template +inline bool v_check_any(const _Tpvec& a) +{ return vec_any_lt(a.val, _Tpvec::zero().val); } +inline bool v_check_any(const v_uint8x16& a) +{ return v_check_any(v_reinterpret_as_s8(a)); } +inline bool v_check_any(const v_uint16x8& a) +{ return v_check_any(v_reinterpret_as_s16(a)); } +inline bool v_check_any(const v_uint32x4& a) +{ return v_check_any(v_reinterpret_as_s32(a)); } +inline bool v_check_any(const v_uint64x2& a) +{ return v_check_any(v_reinterpret_as_s64(a)); } +inline bool v_check_any(const v_float32x4& a) +{ return v_check_any(v_reinterpret_as_s32(a)); } +inline bool v_check_any(const v_float64x2& a) +{ return v_check_any(v_reinterpret_as_s64(a)); } + +////////// Other math ///////// + +/** Some frequent operations **/ +inline v_float32x4 v_sqrt(const v_float32x4& x) +{ return v_float32x4(vec_sqrt(x.val)); } +inline v_float64x2 v_sqrt(const v_float64x2& x) +{ return v_float64x2(vec_sqrt(x.val)); } + +inline v_float32x4 v_invsqrt(const v_float32x4& x) +{ return v_float32x4(vec_rsqrt(x.val)); } +inline v_float64x2 v_invsqrt(const v_float64x2& x) +{ return v_float64x2(vec_rsqrt(x.val)); } + +#define OPENCV_HAL_IMPL_VSX_MULADD(_Tpvec) \ +inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(vec_sqrt(vec_madd(a.val, a.val, vec_mul(b.val, b.val)))); } \ +inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(vec_madd(a.val, a.val, vec_mul(b.val, b.val))); } \ +inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ +{ return _Tpvec(vec_madd(a.val, b.val, c.val)); } \ +inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ +{ return _Tpvec(vec_madd(a.val, b.val, c.val)); } + +OPENCV_HAL_IMPL_VSX_MULADD(v_float32x4) +OPENCV_HAL_IMPL_VSX_MULADD(v_float64x2) + +inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ return v_add(v_mul(a, b), c); } + +// TODO: exp, log, sin, cos + +/** Absolute values **/ +inline v_uint8x16 v_abs(const v_int8x16& x) +{ return v_uint8x16(vec_uchar16_c(vec_abs(x.val))); } + +inline v_uint16x8 v_abs(const v_int16x8& x) +{ return v_uint16x8(vec_ushort8_c(vec_abs(x.val))); } + +inline v_uint32x4 v_abs(const v_int32x4& x) +{ return v_uint32x4(vec_uint4_c(vec_abs(x.val))); } + +inline v_float32x4 v_abs(const v_float32x4& x) +{ return v_float32x4(vec_abs(x.val)); } + +inline v_float64x2 v_abs(const v_float64x2& x) +{ return v_float64x2(vec_abs(x.val)); } + +/** Absolute difference **/ +// unsigned +OPENCV_HAL_IMPL_VSX_BIN_FUNC(v_absdiff, vec_absd) + +inline v_uint8x16 v_absdiff(const v_int8x16& a, const v_int8x16& b) +{ return v_reinterpret_as_u8(v_sub_wrap(v_max(a, b), v_min(a, b))); } +inline v_uint16x8 v_absdiff(const v_int16x8& a, const v_int16x8& b) +{ return v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))); } +inline v_uint32x4 v_absdiff(const v_int32x4& a, const v_int32x4& b) +{ return v_reinterpret_as_u32(v_sub(v_max(a, b), v_min(a, b))); } + +inline v_float32x4 v_absdiff(const v_float32x4& a, const v_float32x4& b) +{ return v_abs(v_sub(a, b)); } +inline v_float64x2 v_absdiff(const v_float64x2& a, const v_float64x2& b) +{ return v_abs(v_sub(a, b)); } + +/** Absolute difference for signed integers **/ +inline v_int8x16 v_absdiffs(const v_int8x16& a, const v_int8x16& b) +{ return v_int8x16(vec_abss(vec_subs(a.val, b.val))); } +inline v_int16x8 v_absdiffs(const v_int16x8& a, const v_int16x8& b) +{ return v_int16x8(vec_abss(vec_subs(a.val, b.val))); } + +////////// Conversions ///////// + +/** Rounding **/ +inline v_int32x4 v_round(const v_float32x4& a) +{ return v_int32x4(vec_cts(vec_rint(a.val))); } + +inline v_int32x4 v_round(const v_float64x2& a) +{ return v_int32x4(vec_mergesqo(vec_ctso(vec_rint(a.val)), vec_int4_z)); } + +inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) +{ return v_int32x4(vec_mergesqo(vec_ctso(vec_rint(a.val)), vec_ctso(vec_rint(b.val)))); } + +inline v_int32x4 v_floor(const v_float32x4& a) +{ return v_int32x4(vec_cts(vec_floor(a.val))); } + +inline v_int32x4 v_floor(const v_float64x2& a) +{ return v_int32x4(vec_mergesqo(vec_ctso(vec_floor(a.val)), vec_int4_z)); } + +inline v_int32x4 v_ceil(const v_float32x4& a) +{ return v_int32x4(vec_cts(vec_ceil(a.val))); } + +inline v_int32x4 v_ceil(const v_float64x2& a) +{ return v_int32x4(vec_mergesqo(vec_ctso(vec_ceil(a.val)), vec_int4_z)); } + +inline v_int32x4 v_trunc(const v_float32x4& a) +{ return v_int32x4(vec_cts(a.val)); } + +inline v_int32x4 v_trunc(const v_float64x2& a) +{ return v_int32x4(vec_mergesqo(vec_ctso(a.val), vec_int4_z)); } + +/** To float **/ +inline v_float32x4 v_cvt_f32(const v_int32x4& a) +{ return v_float32x4(vec_ctf(a.val)); } + +inline v_float32x4 v_cvt_f32(const v_float64x2& a) +{ return v_float32x4(vec_mergesqo(vec_cvfo(a.val), vec_float4_z)); } + +inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) +{ return v_float32x4(vec_mergesqo(vec_cvfo(a.val), vec_cvfo(b.val))); } + +inline v_float64x2 v_cvt_f64(const v_int32x4& a) +{ return v_float64x2(vec_ctdo(vec_mergeh(a.val, a.val))); } + +inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) +{ return v_float64x2(vec_ctdo(vec_mergel(a.val, a.val))); } + +inline v_float64x2 v_cvt_f64(const v_float32x4& a) +{ return v_float64x2(vec_cvfo(vec_mergeh(a.val, a.val))); } + +inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) +{ return v_float64x2(vec_cvfo(vec_mergel(a.val, a.val))); } + +inline v_float64x2 v_cvt_f64(const v_int64x2& a) +{ return v_float64x2(vec_ctd(a.val)); } + +////////////// Lookup table access //////////////////// + +inline v_int8x16 v_lut(const schar* tab, const int* idx) +{ + return v_int8x16(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]], + tab[idx[8]], tab[idx[9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]]); +} +inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx) +{ + return v_reinterpret_as_s8(v_int16x8(*(const short*)(tab+idx[0]), *(const short*)(tab+idx[1]), *(const short*)(tab+idx[2]), *(const short*)(tab+idx[3]), + *(const short*)(tab+idx[4]), *(const short*)(tab+idx[5]), *(const short*)(tab+idx[6]), *(const short*)(tab+idx[7]))); +} +inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) +{ + return v_reinterpret_as_s8(v_int32x4(*(const int*)(tab+idx[0]), *(const int*)(tab+idx[1]), *(const int*)(tab+idx[2]), *(const int*)(tab+idx[3]))); +} +inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((const schar*)tab, idx)); } +inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((const schar*)tab, idx)); } +inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((const schar*)tab, idx)); } + +inline v_int16x8 v_lut(const short* tab, const int* idx) +{ + return v_int16x8(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]]); +} +inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) +{ + return v_reinterpret_as_s16(v_int32x4(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]))); +} +inline v_int16x8 v_lut_quads(const short* tab, const int* idx) +{ + return v_reinterpret_as_s16(v_int64x2(*(const int64*)(tab + idx[0]), *(const int64*)(tab + idx[1]))); +} +inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((const short*)tab, idx)); } +inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((const short*)tab, idx)); } +inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((const short*)tab, idx)); } + +inline v_int32x4 v_lut(const int* tab, const int* idx) +{ + return v_int32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); +} +inline v_int32x4 v_lut_pairs(const int* tab, const int* idx) +{ + return v_reinterpret_as_s32(v_int64x2(*(const int64*)(tab + idx[0]), *(const int64*)(tab + idx[1]))); +} +inline v_int32x4 v_lut_quads(const int* tab, const int* idx) +{ + return v_int32x4(vsx_ld(0, tab + idx[0])); +} +inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((const int*)tab, idx)); } +inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((const int*)tab, idx)); } +inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((const int*)tab, idx)); } + +inline v_int64x2 v_lut(const int64_t* tab, const int* idx) +{ + return v_int64x2(tab[idx[0]], tab[idx[1]]); +} +inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) +{ + return v_int64x2(vsx_ld2(0, tab + idx[0])); +} +inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } +inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } + +inline v_float32x4 v_lut(const float* tab, const int* idx) +{ + return v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); +} +inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) { return v_reinterpret_as_f32(v_lut_pairs((const int*)tab, idx)); } +inline v_float32x4 v_lut_quads(const float* tab, const int* idx) { return v_load(tab + *idx); } + +inline v_float64x2 v_lut(const double* tab, const int* idx) +{ + return v_float64x2(tab[idx[0]], tab[idx[1]]); +} +inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) { return v_load(tab + *idx); } + +inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) +{ + const int idx[4] = { + vec_extract(idxvec.val, 0), + vec_extract(idxvec.val, 1), + vec_extract(idxvec.val, 2), + vec_extract(idxvec.val, 3) + }; + return v_int32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); +} + +inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) +{ + const int idx[4] = { + vec_extract(idxvec.val, 0), + vec_extract(idxvec.val, 1), + vec_extract(idxvec.val, 2), + vec_extract(idxvec.val, 3) + }; + return v_uint32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); +} + +inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) +{ + const int idx[4] = { + vec_extract(idxvec.val, 0), + vec_extract(idxvec.val, 1), + vec_extract(idxvec.val, 2), + vec_extract(idxvec.val, 3) + }; + return v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); +} + +inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) +{ + const int idx[2] = { + vec_extract(idxvec.val, 0), + vec_extract(idxvec.val, 1) + }; + return v_float64x2(tab[idx[0]], tab[idx[1]]); +} + +inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) +{ + vec_float4 xy0 = vec_ld_l8(tab + vec_extract(idxvec.val, 0)); + vec_float4 xy1 = vec_ld_l8(tab + vec_extract(idxvec.val, 1)); + vec_float4 xy2 = vec_ld_l8(tab + vec_extract(idxvec.val, 2)); + vec_float4 xy3 = vec_ld_l8(tab + vec_extract(idxvec.val, 3)); + vec_float4 xy02 = vec_mergeh(xy0, xy2); // x0, x2, y0, y2 + vec_float4 xy13 = vec_mergeh(xy1, xy3); // x1, x3, y1, y3 + x.val = vec_mergeh(xy02, xy13); + y.val = vec_mergel(xy02, xy13); +} +inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) +{ + vec_double2 xy0 = vsx_ld(vec_extract(idxvec.val, 0), tab); + vec_double2 xy1 = vsx_ld(vec_extract(idxvec.val, 1), tab); + x.val = vec_mergeh(xy0, xy1); + y.val = vec_mergel(xy0, xy1); +} + +inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) +{ + static const vec_uchar16 perm = {0, 2, 1, 3, 4, 6, 5, 7, 8, 10, 9, 11, 12, 14, 13, 15}; + return v_int8x16(vec_perm(vec.val, vec.val, perm)); +} +inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) +{ return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } + +inline v_int8x16 v_interleave_quads(const v_int8x16& vec) +{ + static const vec_uchar16 perm = {0, 4, 1, 5, 2, 6, 3, 7, 8, 12, 9, 13, 10, 14, 11, 15}; + return v_int8x16(vec_perm(vec.val, vec.val, perm)); +} +inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) +{ return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) +{ + static const vec_uchar16 perm = {0,1, 4,5, 2,3, 6,7, 8,9, 12,13, 10,11, 14,15}; + return v_int16x8(vec_perm(vec.val, vec.val, perm)); +} +inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) +{ return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } + +inline v_int16x8 v_interleave_quads(const v_int16x8& vec) +{ + static const vec_uchar16 perm = {0,1, 8,9, 2,3, 10,11, 4,5, 12,13, 6,7, 14,15}; + return v_int16x8(vec_perm(vec.val, vec.val, perm)); +} +inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) +{ return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) +{ + static const vec_uchar16 perm = {0,1,2,3, 8,9,10,11, 4,5,6,7, 12,13,14,15}; + return v_int32x4(vec_perm(vec.val, vec.val, perm)); +} +inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) +{ return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } +inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) +{ return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } + +inline v_int8x16 v_pack_triplets(const v_int8x16& vec) +{ + static const vec_uchar16 perm = {0, 1, 2, 4, 5, 6, 8, 9, 10, 12, 13, 14, 15, 15, 15, 15}; + return v_int8x16(vec_perm(vec.val, vec.val, perm)); +} +inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) +{ return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_pack_triplets(const v_int16x8& vec) +{ + static const vec_uchar16 perm = {0,1, 2,3, 4,5, 8,9, 10,11, 12,13, 14,15, 14,15}; + return v_int16x8(vec_perm(vec.val, vec.val, perm)); +} +inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) +{ return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_pack_triplets(const v_int32x4& vec) +{ return vec; } +inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) +{ return vec; } +inline v_float32x4 v_pack_triplets(const v_float32x4& vec) +{ return vec; } + +/////// FP16 support //////// + +inline v_float32x4 v_load_expand(const hfloat* ptr) +{ + vec_ushort8 vf16 = vec_ld_l8((const ushort*)ptr); +#if CV_VSX3 && defined(vec_extract_fp_from_shorth) + return v_float32x4(vec_extract_fp_from_shorth(vf16)); +#elif CV_VSX3 && !defined(CV_COMPILER_VSX_BROKEN_ASM) + vec_float4 vf32; + __asm__ __volatile__ ("xvcvhpsp %x0,%x1" : "=wa" (vf32) : "wa" (vec_mergeh(vf16, vf16))); + return v_float32x4(vf32); +#else + const vec_int4 z = vec_int4_z, delta = vec_int4_sp(0x38000000); + const vec_int4 signmask = vec_int4_sp(0x80000000); + const vec_int4 maxexp = vec_int4_sp(0x7c000000); + const vec_float4 deltaf = vec_float4_c(vec_int4_sp(0x38800000)); + + vec_int4 bits = vec_int4_c(vec_mergeh(vec_short8_c(z), vec_short8_c(vf16))); + vec_int4 e = vec_and(bits, maxexp), sign = vec_and(bits, signmask); + vec_int4 t = vec_add(vec_sr(vec_xor(bits, sign), vec_uint4_sp(3)), delta); // ((h & 0x7fff) << 13) + delta + vec_int4 zt = vec_int4_c(vec_sub(vec_float4_c(vec_add(t, vec_int4_sp(1 << 23))), deltaf)); + + t = vec_add(t, vec_and(delta, vec_cmpeq(maxexp, e))); + vec_bint4 zmask = vec_cmpeq(e, z); + vec_int4 ft = vec_sel(t, zt, zmask); + return v_float32x4(vec_float4_c(vec_or(ft, sign))); +#endif +} + +inline void v_pack_store(hfloat* ptr, const v_float32x4& v) +{ +// fixme: Is there any builtin op or intrinsic that cover "xvcvsphp"? +#if CV_VSX3 && !defined(CV_COMPILER_VSX_BROKEN_ASM) + vec_ushort8 vf16; + __asm__ __volatile__ ("xvcvsphp %x0,%x1" : "=wa" (vf16) : "wa" (v.val)); + vec_st_l8(vec_mergesqe(vf16, vf16), ptr); +#else + const vec_int4 signmask = vec_int4_sp(0x80000000); + const vec_int4 rval = vec_int4_sp(0x3f000000); + + vec_int4 t = vec_int4_c(v.val); + vec_int4 sign = vec_sra(vec_and(t, signmask), vec_uint4_sp(16)); + t = vec_and(vec_nor(signmask, signmask), t); + + vec_bint4 finitemask = vec_cmpgt(vec_int4_sp(0x47800000), t); + vec_bint4 isnan = vec_cmpgt(t, vec_int4_sp(0x7f800000)); + vec_int4 naninf = vec_sel(vec_int4_sp(0x7c00), vec_int4_sp(0x7e00), isnan); + vec_bint4 tinymask = vec_cmpgt(vec_int4_sp(0x38800000), t); + vec_int4 tt = vec_int4_c(vec_add(vec_float4_c(t), vec_float4_c(rval))); + tt = vec_sub(tt, rval); + vec_int4 odd = vec_and(vec_sr(t, vec_uint4_sp(13)), vec_int4_sp(1)); + vec_int4 nt = vec_add(t, vec_int4_sp(0xc8000fff)); + nt = vec_sr(vec_add(nt, odd), vec_uint4_sp(13)); + t = vec_sel(nt, tt, tinymask); + t = vec_sel(naninf, t, finitemask); + t = vec_or(t, sign); + vec_st_l8(vec_packs(t, t), ptr); +#endif +} + +inline void v_cleanup() {} + + +/** Reinterpret **/ +/** its up there with load and store operations **/ + +////////// Matrix operations ///////// + +//////// Dot Product //////// +// 16 >> 32 +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) +{ return v_int32x4(vec_msum(a.val, b.val, vec_int4_z)); } +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ return v_int32x4(vec_msum(a.val, b.val, c.val)); } + +// 32 >> 64 +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) +{ + vec_dword2 even = vec_mule(a.val, b.val); + vec_dword2 odd = vec_mulo(a.val, b.val); + return v_int64x2(vec_add(even, odd)); +} +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ return v_add(v_dotprod(a, b), c); } + +// 8 >> 32 +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) +{ return v_uint32x4(vec_msum(a.val, b.val, c.val)); } +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) +{ return v_uint32x4(vec_msum(a.val, b.val, vec_uint4_z)); } + +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) +{ + const vec_ushort8 eight = vec_ushort8_sp(8); + vec_short8 a0 = vec_sra((vec_short8)vec_sld(a.val, a.val, 1), eight); // even + vec_short8 a1 = vec_sra((vec_short8)a.val, eight); // odd + vec_short8 b0 = vec_sra((vec_short8)vec_sld(b.val, b.val, 1), eight); + vec_short8 b1 = vec_sra((vec_short8)b.val, eight); + return v_int32x4(vec_msum(a0, b0, vec_msum(a1, b1, vec_int4_z))); +} + +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) +{ + const vec_ushort8 eight = vec_ushort8_sp(8); + vec_short8 a0 = vec_sra((vec_short8)vec_sld(a.val, a.val, 1), eight); // even + vec_short8 a1 = vec_sra((vec_short8)a.val, eight); // odd + vec_short8 b0 = vec_sra((vec_short8)vec_sld(b.val, b.val, 1), eight); + vec_short8 b1 = vec_sra((vec_short8)b.val, eight); + return v_int32x4(vec_msum(a0, b0, vec_msum(a1, b1, c.val))); +} + +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) +{ + const vec_uint4 zero = vec_uint4_z; + vec_uint4 even = vec_mule(a.val, b.val); + vec_uint4 odd = vec_mulo(a.val, b.val); + vec_udword2 e0 = (vec_udword2)vec_mergee(even, zero); + vec_udword2 e1 = (vec_udword2)vec_mergeo(even, zero); + vec_udword2 o0 = (vec_udword2)vec_mergee(odd, zero); + vec_udword2 o1 = (vec_udword2)vec_mergeo(odd, zero); + vec_udword2 s0 = vec_add(e0, o0); + vec_udword2 s1 = vec_add(e1, o1); + return v_uint64x2(vec_add(s0, s1)); +} +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) +{ + v_int32x4 prod = v_dotprod(a, b); + v_int64x2 c, d; + v_expand(prod, c, d); + return v_int64x2(vec_add(vec_mergeh(c.val, d.val), vec_mergel(c.val, d.val))); +} +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 32 >> 64f +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) +{ return v_cvt_f64(v_dotprod(a, b)); } +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +//////// Fast Dot Product //////// + +// 16 >> 32 +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) +{ return v_dotprod(a, b); } +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ return v_int32x4(vec_msum(a.val, b.val, vec_int4_z)) + c; } +// 32 >> 64 +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) +{ return v_dotprod(a, b); } +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ return v_dotprod(a, b, c); } + +// 8 >> 32 +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) +{ return v_dotprod_expand(a, b); } +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) +{ return v_uint32x4(vec_msum(a.val, b.val, vec_uint4_z)) + c; } + +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) +{ + vec_short8 a0 = vec_unpackh(a.val); + vec_short8 a1 = vec_unpackl(a.val); + vec_short8 b0 = vec_unpackh(b.val); + vec_short8 b1 = vec_unpackl(b.val); + return v_int32x4(vec_msum(a0, b0, vec_msum(a1, b1, vec_int4_z))); +} +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) +{ return v_dotprod_expand(a, b); } +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) +{ return v_dotprod_expand(a, b, c); } + +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) +{ + v_int32x4 prod = v_dotprod(a, b); + v_int64x2 c, d; + v_expand(prod, c, d); + return v_add(c, d); +} +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +// 32 >> 64f +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) +{ return v_dotprod_expand(a, b); } +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) +{ return v_dotprod_expand(a, b, c); } + +inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, + const v_float32x4& m3) +{ + const vec_float4 v0 = vec_splat(v.val, 0); + const vec_float4 v1 = vec_splat(v.val, 1); + const vec_float4 v2 = vec_splat(v.val, 2); + VSX_UNUSED(const vec_float4) v3 = vec_splat(v.val, 3); + return v_float32x4(vec_madd(v0, m0.val, vec_madd(v1, m1.val, vec_madd(v2, m2.val, vec_mul(v3, m3.val))))); +} + +inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, + const v_float32x4& a) +{ + const vec_float4 v0 = vec_splat(v.val, 0); + const vec_float4 v1 = vec_splat(v.val, 1); + const vec_float4 v2 = vec_splat(v.val, 2); + return v_float32x4(vec_madd(v0, m0.val, vec_madd(v1, m1.val, vec_madd(v2, m2.val, a.val)))); +} + +#define OPENCV_HAL_IMPL_VSX_TRANSPOSE4x4(_Tpvec, _Tpvec2) \ +inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ + const _Tpvec& a2, const _Tpvec& a3, \ + _Tpvec& b0, _Tpvec& b1, _Tpvec& b2, _Tpvec& b3) \ +{ \ + _Tpvec2 a02 = vec_mergeh(a0.val, a2.val); \ + _Tpvec2 a13 = vec_mergeh(a1.val, a3.val); \ + b0.val = vec_mergeh(a02, a13); \ + b1.val = vec_mergel(a02, a13); \ + a02 = vec_mergel(a0.val, a2.val); \ + a13 = vec_mergel(a1.val, a3.val); \ + b2.val = vec_mergeh(a02, a13); \ + b3.val = vec_mergel(a02, a13); \ +} +OPENCV_HAL_IMPL_VSX_TRANSPOSE4x4(v_uint32x4, vec_uint4) +OPENCV_HAL_IMPL_VSX_TRANSPOSE4x4(v_int32x4, vec_int4) +OPENCV_HAL_IMPL_VSX_TRANSPOSE4x4(v_float32x4, vec_float4) + +template +inline Tvec v_broadcast_element(const Tvec& v) +{ return Tvec(vec_splat(v.val, i)); } + +#include "intrin_math.hpp" +inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } +inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } +inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } +inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } +inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } +inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } + +inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } +inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } +inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } +inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } +inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} + +#endif // OPENCV_HAL_VSX_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_wasm.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_wasm.hpp index 7c4d8e05df..d8d27edb3a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_wasm.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_wasm.hpp @@ -1,2801 +1,2801 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_HAL_INTRIN_WASM_HPP -#define OPENCV_HAL_INTRIN_WASM_HPP - -#include -#include -#include -#include "opencv2/core/saturate.hpp" - - -// Emscripten v2.0.13 (latest officially supported, as of 07/30/2024): -// __EMSCRIPTEN_major__, __EMSCRIPTEN_minor__ and __EMSCRIPTEN_tiny__ are defined via commandline in -// https://github.com/emscripten-core/emscripten/blob/1690a5802cd1241adc9714fb7fa2f633d38860dc/tools/shared.py#L506-L515 -// -// See https://github.com/opencv/opencv/pull/25909 -#ifndef __EMSCRIPTEN_major__ -#include -#endif - -#define CV_SIMD128 1 -#define CV_SIMD128_64F 0 // Now all implementation of f64 use fallback, so disable it. -#define CV_SIMD128_FP16 0 - -namespace cv -{ - -//! @cond IGNORED - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -#if (__EMSCRIPTEN_major__ * 1000000 + __EMSCRIPTEN_minor__ * 1000 + __EMSCRIPTEN_tiny__) < (1038046) -// handle renames: https://github.com/emscripten-core/emscripten/pull/9440 (https://github.com/emscripten-core/emscripten/commit/755d5b46cb84d0aa120c10981b11d05646c29673) -#define wasm_i32x4_trunc_saturate_f32x4 wasm_trunc_saturate_i32x4_f32x4 -#define wasm_u32x4_trunc_saturate_f32x4 wasm_trunc_saturate_u32x4_f32x4 -#define wasm_i64x2_trunc_saturate_f64x2 wasm_trunc_saturate_i64x2_f64x2 -#define wasm_u64x2_trunc_saturate_f64x2 wasm_trunc_saturate_u64x2_f64x2 -#define wasm_f32x4_convert_i32x4 wasm_convert_f32x4_i32x4 -#define wasm_f32x4_convert_u32x4 wasm_convert_f32x4_u32x4 -#define wasm_f64x2_convert_i64x2 wasm_convert_f64x2_i64x2 -#define wasm_f64x2_convert_u64x2 wasm_convert_f64x2_u64x2 -#endif // COMPATIBILITY: <1.38.46 - -///////// Types /////////// - -struct v_uint8x16 -{ - typedef uchar lane_type; - typedef v128_t vector_type; - enum { nlanes = 16 }; - - v_uint8x16() {} - explicit v_uint8x16(v128_t v) : val(v) {} - v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, - uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) - { - uchar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; - val = wasm_v128_load(v); - } - - uchar get0() const - { - return (uchar)wasm_i8x16_extract_lane(val, 0); - } - - v128_t val; -}; - -struct v_int8x16 -{ - typedef schar lane_type; - typedef v128_t vector_type; - enum { nlanes = 16 }; - - v_int8x16() {} - explicit v_int8x16(v128_t v) : val(v) {} - v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, - schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) - { - schar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; - val = wasm_v128_load(v); - } - - schar get0() const - { - return wasm_i8x16_extract_lane(val, 0); - } - - v128_t val; -}; - -struct v_uint16x8 -{ - typedef ushort lane_type; - typedef v128_t vector_type; - enum { nlanes = 8 }; - - v_uint16x8() {} - explicit v_uint16x8(v128_t v) : val(v) {} - v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) - { - ushort v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; - val = wasm_v128_load(v); - } - - ushort get0() const - { - return (ushort)wasm_i16x8_extract_lane(val, 0); // wasm_u16x8_extract_lane() unimplemented yet - } - - v128_t val; -}; - -struct v_int16x8 -{ - typedef short lane_type; - typedef v128_t vector_type; - enum { nlanes = 8 }; - - v_int16x8() {} - explicit v_int16x8(v128_t v) : val(v) {} - v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) - { - short v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; - val = wasm_v128_load(v); - } - - short get0() const - { - return wasm_i16x8_extract_lane(val, 0); - } - - v128_t val; -}; - -struct v_uint32x4 -{ - typedef unsigned lane_type; - typedef v128_t vector_type; - enum { nlanes = 4 }; - - v_uint32x4() {} - explicit v_uint32x4(v128_t v) : val(v) {} - v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) - { - unsigned v[] = {v0, v1, v2, v3}; - val = wasm_v128_load(v); - } - - unsigned get0() const - { - return (unsigned)wasm_i32x4_extract_lane(val, 0); - } - - v128_t val; -}; - -struct v_int32x4 -{ - typedef int lane_type; - typedef v128_t vector_type; - enum { nlanes = 4 }; - - v_int32x4() {} - explicit v_int32x4(v128_t v) : val(v) {} - v_int32x4(int v0, int v1, int v2, int v3) - { - int v[] = {v0, v1, v2, v3}; - val = wasm_v128_load(v); - } - - int get0() const - { - return wasm_i32x4_extract_lane(val, 0); - } - - v128_t val; -}; - -struct v_float32x4 -{ - typedef float lane_type; - typedef v128_t vector_type; - enum { nlanes = 4 }; - - v_float32x4() {} - explicit v_float32x4(v128_t v) : val(v) {} - v_float32x4(float v0, float v1, float v2, float v3) - { - float v[] = {v0, v1, v2, v3}; - val = wasm_v128_load(v); - } - - float get0() const - { - return wasm_f32x4_extract_lane(val, 0); - } - - v128_t val; -}; - -struct v_uint64x2 -{ - typedef uint64 lane_type; - typedef v128_t vector_type; - enum { nlanes = 2 }; - - v_uint64x2() {} - explicit v_uint64x2(v128_t v) : val(v) {} - v_uint64x2(uint64 v0, uint64 v1) - { - uint64 v[] = {v0, v1}; - val = wasm_v128_load(v); - } - - uint64 get0() const - { - return (uint64)wasm_i64x2_extract_lane(val, 0); - } - - v128_t val; -}; - -struct v_int64x2 -{ - typedef int64 lane_type; - typedef v128_t vector_type; - enum { nlanes = 2 }; - - v_int64x2() {} - explicit v_int64x2(v128_t v) : val(v) {} - v_int64x2(int64 v0, int64 v1) - { - int64 v[] = {v0, v1}; - val = wasm_v128_load(v); - } - - int64 get0() const - { - return wasm_i64x2_extract_lane(val, 0); - } - - v128_t val; -}; - -struct v_float64x2 -{ - typedef double lane_type; - typedef v128_t vector_type; - enum { nlanes = 2 }; - - v_float64x2() {} - explicit v_float64x2(v128_t v) : val(v) {} - v_float64x2(double v0, double v1) - { - double v[] = {v0, v1}; - val = wasm_v128_load(v); - } - - double get0() const - { - return wasm_f64x2_extract_lane(val, 0); - } - - v128_t val; -}; - -namespace -{ -#define OPENCV_HAL_IMPL_REINTERPRET_INT(ft, tt) \ -inline tt reinterpret_int(ft x) { union { ft l; tt i; } v; v.l = x; return v.i; } -OPENCV_HAL_IMPL_REINTERPRET_INT(uchar, schar) -OPENCV_HAL_IMPL_REINTERPRET_INT(schar, schar) -OPENCV_HAL_IMPL_REINTERPRET_INT(ushort, short) -OPENCV_HAL_IMPL_REINTERPRET_INT(short, short) -OPENCV_HAL_IMPL_REINTERPRET_INT(unsigned, int) -OPENCV_HAL_IMPL_REINTERPRET_INT(int, int) -OPENCV_HAL_IMPL_REINTERPRET_INT(float, int) -OPENCV_HAL_IMPL_REINTERPRET_INT(uint64, int64) -OPENCV_HAL_IMPL_REINTERPRET_INT(int64, int64) -OPENCV_HAL_IMPL_REINTERPRET_INT(double, int64) - -static const unsigned char popCountTable[] = -{ - 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, -}; -} // namespace - -static v128_t wasm_unpacklo_i8x16(v128_t a, v128_t b) { - return wasm_i8x16_shuffle(a, b, 0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23); -} - -static v128_t wasm_unpacklo_i16x8(v128_t a, v128_t b) { - return wasm_i8x16_shuffle(a, b, 0,1,16,17,2,3,18,19,4,5,20,21,6,7,22,23); -} - -static v128_t wasm_unpacklo_i32x4(v128_t a, v128_t b) { - return wasm_i8x16_shuffle(a, b, 0,1,2,3,16,17,18,19,4,5,6,7,20,21,22,23); -} - -static v128_t wasm_unpacklo_i64x2(v128_t a, v128_t b) { - return wasm_i8x16_shuffle(a, b, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); -} - -static v128_t wasm_unpackhi_i8x16(v128_t a, v128_t b) { - return wasm_i8x16_shuffle(a, b, 8,24,9,25,10,26,11,27,12,28,13,29,14,30,15,31); -} - -static v128_t wasm_unpackhi_i16x8(v128_t a, v128_t b) { - return wasm_i8x16_shuffle(a, b, 8,9,24,25,10,11,26,27,12,13,28,29,14,15,30,31); -} - -static v128_t wasm_unpackhi_i32x4(v128_t a, v128_t b) { - return wasm_i8x16_shuffle(a, b, 8,9,10,11,24,25,26,27,12,13,14,15,28,29,30,31); -} - -static v128_t wasm_unpackhi_i64x2(v128_t a, v128_t b) { - return wasm_i8x16_shuffle(a, b, 8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31); -} - -/** Convert **/ -// 8 >> 16 -inline v128_t v128_cvtu8x16_i16x8(const v128_t& a) -{ - const v128_t z = wasm_i8x16_splat(0); - return wasm_unpacklo_i8x16(a, z); -} -inline v128_t v128_cvti8x16_i16x8(const v128_t& a) -{ return wasm_i16x8_shr(wasm_unpacklo_i8x16(a, a), 8); } -// 8 >> 32 -inline v128_t v128_cvtu8x16_i32x4(const v128_t& a) -{ - const v128_t z = wasm_i8x16_splat(0); - return wasm_unpacklo_i16x8(wasm_unpacklo_i8x16(a, z), z); -} -inline v128_t v128_cvti8x16_i32x4(const v128_t& a) -{ - v128_t r = wasm_unpacklo_i8x16(a, a); - r = wasm_unpacklo_i8x16(r, r); - return wasm_i32x4_shr(r, 24); -} -// 16 >> 32 -inline v128_t v128_cvtu16x8_i32x4(const v128_t& a) -{ - const v128_t z = wasm_i8x16_splat(0); - return wasm_unpacklo_i16x8(a, z); -} -inline v128_t v128_cvti16x8_i32x4(const v128_t& a) -{ return wasm_i32x4_shr(wasm_unpacklo_i16x8(a, a), 16); } -// 32 >> 64 -inline v128_t v128_cvtu32x4_i64x2(const v128_t& a) -{ - const v128_t z = wasm_i8x16_splat(0); - return wasm_unpacklo_i32x4(a, z); -} -inline v128_t v128_cvti32x4_i64x2(const v128_t& a) -{ return wasm_unpacklo_i32x4(a, wasm_i32x4_shr(a, 31)); } - -// 16 << 8 -inline v128_t v128_cvtu8x16_i16x8_high(const v128_t& a) -{ - const v128_t z = wasm_i8x16_splat(0); - return wasm_unpackhi_i8x16(a, z); -} -inline v128_t v128_cvti8x16_i16x8_high(const v128_t& a) -{ return wasm_i16x8_shr(wasm_unpackhi_i8x16(a, a), 8); } -// 32 << 16 -inline v128_t v128_cvtu16x8_i32x4_high(const v128_t& a) -{ - const v128_t z = wasm_i8x16_splat(0); - return wasm_unpackhi_i16x8(a, z); -} -inline v128_t v128_cvti16x8_i32x4_high(const v128_t& a) -{ return wasm_i32x4_shr(wasm_unpackhi_i16x8(a, a), 16); } -// 64 << 32 -inline v128_t v128_cvtu32x4_i64x2_high(const v128_t& a) -{ - const v128_t z = wasm_i8x16_splat(0); - return wasm_unpackhi_i32x4(a, z); -} -inline v128_t v128_cvti32x4_i64x2_high(const v128_t& a) -{ return wasm_unpackhi_i32x4(a, wasm_i32x4_shr(a, 31)); } - -#define OPENCV_HAL_IMPL_WASM_INITVEC(_Tpvec, _Tp, suffix, zsuffix, _Tps) \ -inline _Tpvec v_setzero_##suffix() { return _Tpvec(wasm_##zsuffix##_splat((_Tps)0)); } \ -inline _Tpvec v_setall_##suffix(_Tp v) { return _Tpvec(wasm_##zsuffix##_splat((_Tps)v)); } \ -template <> inline _Tpvec v_setzero_() { return v_setzero_##suffix(); } \ -template <> inline _Tpvec v_setall_(_Tp v) { return v_setall_##suffix(v); } \ -template inline _Tpvec v_reinterpret_as_##suffix(const _Tpvec0& a) \ -{ return _Tpvec(a.val); } - -OPENCV_HAL_IMPL_WASM_INITVEC(v_uint8x16, uchar, u8, i8x16, schar) -OPENCV_HAL_IMPL_WASM_INITVEC(v_int8x16, schar, s8, i8x16, schar) -OPENCV_HAL_IMPL_WASM_INITVEC(v_uint16x8, ushort, u16, i16x8, short) -OPENCV_HAL_IMPL_WASM_INITVEC(v_int16x8, short, s16, i16x8, short) -OPENCV_HAL_IMPL_WASM_INITVEC(v_uint32x4, unsigned, u32, i32x4, int) -OPENCV_HAL_IMPL_WASM_INITVEC(v_int32x4, int, s32, i32x4, int) -OPENCV_HAL_IMPL_WASM_INITVEC(v_float32x4, float, f32, f32x4, float) -OPENCV_HAL_IMPL_WASM_INITVEC(v_uint64x2, uint64, u64, i64x2, int64) -OPENCV_HAL_IMPL_WASM_INITVEC(v_int64x2, int64, s64, i64x2, int64) -OPENCV_HAL_IMPL_WASM_INITVEC(v_float64x2, double, f64, f64x2, double) - -//////////////// PACK /////////////// -inline v_uint8x16 v_pack(const v_uint16x8& a, const v_uint16x8& b) -{ - v128_t maxval = wasm_i16x8_splat(255); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_u16x8_gt(a.val, maxval)); - v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_u16x8_gt(b.val, maxval)); - return v_uint8x16(wasm_i8x16_shuffle(a1, b1, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); -} -inline v_int8x16 v_pack(const v_int16x8& a, const v_int16x8& b) -{ - v128_t maxval = wasm_i16x8_splat(127); - v128_t minval = wasm_i16x8_splat(-128); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i16x8_gt(a.val, maxval)); - v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_i16x8_gt(b.val, maxval)); - v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i16x8_lt(a1, minval)); - v128_t b2 = wasm_v128_bitselect(minval, b1, wasm_i16x8_lt(b1, minval)); - return v_int8x16(wasm_i8x16_shuffle(a2, b2, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); -} -inline v_uint16x8 v_pack(const v_uint32x4& a, const v_uint32x4& b) -{ - v128_t maxval = wasm_i32x4_splat(65535); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_u32x4_gt(a.val, maxval)); - v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_u32x4_gt(b.val, maxval)); - return v_uint16x8(wasm_i8x16_shuffle(a1, b1, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29)); -} -inline v_int16x8 v_pack(const v_int32x4& a, const v_int32x4& b) -{ - v128_t maxval = wasm_i32x4_splat(32767); - v128_t minval = wasm_i32x4_splat(-32768); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i32x4_gt(a.val, maxval)); - v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_i32x4_gt(b.val, maxval)); - v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i32x4_lt(a1, minval)); - v128_t b2 = wasm_v128_bitselect(minval, b1, wasm_i32x4_lt(b1, minval)); - return v_int16x8(wasm_i8x16_shuffle(a2, b2, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29)); -} -inline v_uint32x4 v_pack(const v_uint64x2& a, const v_uint64x2& b) -{ - return v_uint32x4(wasm_i8x16_shuffle(a.val, b.val, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27)); -} -inline v_int32x4 v_pack(const v_int64x2& a, const v_int64x2& b) -{ - return v_int32x4(wasm_i8x16_shuffle(a.val, b.val, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27)); -} -inline v_uint8x16 v_pack_u(const v_int16x8& a, const v_int16x8& b) -{ - v128_t maxval = wasm_i16x8_splat(255); - v128_t minval = wasm_i16x8_splat(0); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i16x8_gt(a.val, maxval)); - v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_i16x8_gt(b.val, maxval)); - v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i16x8_lt(a1, minval)); - v128_t b2 = wasm_v128_bitselect(minval, b1, wasm_i16x8_lt(b1, minval)); - return v_uint8x16(wasm_i8x16_shuffle(a2, b2, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); -} -inline v_uint16x8 v_pack_u(const v_int32x4& a, const v_int32x4& b) -{ - v128_t maxval = wasm_i32x4_splat(65535); - v128_t minval = wasm_i32x4_splat(0); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i32x4_gt(a.val, maxval)); - v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_i32x4_gt(b.val, maxval)); - v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i32x4_lt(a1, minval)); - v128_t b2 = wasm_v128_bitselect(minval, b1, wasm_i32x4_lt(b1, minval)); - return v_uint16x8(wasm_i8x16_shuffle(a2, b2, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29)); -} - -template -inline v_uint8x16 v_rshr_pack(const v_uint16x8& a, const v_uint16x8& b) -{ - v128_t delta = wasm_i16x8_splat(((short)1 << (n-1))); - v128_t a1 = wasm_u16x8_shr(wasm_i16x8_add(a.val, delta), n); - v128_t b1 = wasm_u16x8_shr(wasm_i16x8_add(b.val, delta), n); - v128_t maxval = wasm_i16x8_splat(255); - v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_u16x8_gt(a1, maxval)); - v128_t b2 = wasm_v128_bitselect(maxval, b1, wasm_u16x8_gt(b1, maxval)); - return v_uint8x16(wasm_i8x16_shuffle(a2, b2, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); -} -template -inline v_int8x16 v_rshr_pack(const v_int16x8& a, const v_int16x8& b) -{ - v128_t delta = wasm_i16x8_splat(((short)1 << (n-1))); - v128_t a1 = wasm_i16x8_shr(wasm_i16x8_add(a.val, delta), n); - v128_t b1 = wasm_i16x8_shr(wasm_i16x8_add(b.val, delta), n); - v128_t maxval = wasm_i16x8_splat(127); - v128_t minval = wasm_i16x8_splat(-128); - v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i16x8_gt(a1, maxval)); - v128_t b2 = wasm_v128_bitselect(maxval, b1, wasm_i16x8_gt(b1, maxval)); - v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i16x8_lt(a1, minval)); - v128_t b3 = wasm_v128_bitselect(minval, b2, wasm_i16x8_lt(b1, minval)); - return v_int8x16(wasm_i8x16_shuffle(a3, b3, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); -} -template -inline v_uint16x8 v_rshr_pack(const v_uint32x4& a, const v_uint32x4& b) -{ - v128_t delta = wasm_i32x4_splat(((int)1 << (n-1))); - v128_t a1 = wasm_u32x4_shr(wasm_i32x4_add(a.val, delta), n); - v128_t b1 = wasm_u32x4_shr(wasm_i32x4_add(b.val, delta), n); - v128_t maxval = wasm_i32x4_splat(65535); - v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_u32x4_gt(a1, maxval)); - v128_t b2 = wasm_v128_bitselect(maxval, b1, wasm_u32x4_gt(b1, maxval)); - return v_uint16x8(wasm_i8x16_shuffle(a2, b2, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29)); -} -template -inline v_int16x8 v_rshr_pack(const v_int32x4& a, const v_int32x4& b) -{ - v128_t delta = wasm_i32x4_splat(((int)1 << (n-1))); - v128_t a1 = wasm_i32x4_shr(wasm_i32x4_add(a.val, delta), n); - v128_t b1 = wasm_i32x4_shr(wasm_i32x4_add(b.val, delta), n); - v128_t maxval = wasm_i32x4_splat(32767); - v128_t minval = wasm_i16x8_splat(-32768); - v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i32x4_gt(a1, maxval)); - v128_t b2 = wasm_v128_bitselect(maxval, b1, wasm_i32x4_gt(b1, maxval)); - v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i32x4_lt(a1, minval)); - v128_t b3 = wasm_v128_bitselect(minval, b2, wasm_i32x4_lt(b1, minval)); - return v_int16x8(wasm_i8x16_shuffle(a3, b3, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29)); -} -template -inline v_uint32x4 v_rshr_pack(const v_uint64x2& a, const v_uint64x2& b) -{ - v128_t delta = wasm_i64x2_splat(((int64)1 << (n-1))); - v128_t a1 = wasm_u64x2_shr(wasm_i64x2_add(a.val, delta), n); - v128_t b1 = wasm_u64x2_shr(wasm_i64x2_add(b.val, delta), n); - return v_uint32x4(wasm_i8x16_shuffle(a1, b1, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27)); -} -template -inline v_int32x4 v_rshr_pack(const v_int64x2& a, const v_int64x2& b) -{ - v128_t delta = wasm_i64x2_splat(((int64)1 << (n-1))); - v128_t a1 = wasm_i64x2_shr(wasm_i64x2_add(a.val, delta), n); - v128_t b1 = wasm_i64x2_shr(wasm_i64x2_add(b.val, delta), n); - return v_int32x4(wasm_i8x16_shuffle(a1, b1, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27)); -} -template -inline v_uint8x16 v_rshr_pack_u(const v_int16x8& a, const v_int16x8& b) -{ - v128_t delta = wasm_i16x8_splat(((short)1 << (n-1))); - v128_t a1 = wasm_i16x8_shr(wasm_i16x8_add(a.val, delta), n); - v128_t b1 = wasm_i16x8_shr(wasm_i16x8_add(b.val, delta), n); - v128_t maxval = wasm_i16x8_splat(255); - v128_t minval = wasm_i16x8_splat(0); - v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i16x8_gt(a1, maxval)); - v128_t b2 = wasm_v128_bitselect(maxval, b1, wasm_i16x8_gt(b1, maxval)); - v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i16x8_lt(a1, minval)); - v128_t b3 = wasm_v128_bitselect(minval, b2, wasm_i16x8_lt(b1, minval)); - return v_uint8x16(wasm_i8x16_shuffle(a3, b3, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); -} -template -inline v_uint16x8 v_rshr_pack_u(const v_int32x4& a, const v_int32x4& b) -{ - v128_t delta = wasm_i32x4_splat(((int)1 << (n-1))); - v128_t a1 = wasm_i32x4_shr(wasm_i32x4_add(a.val, delta), n); - v128_t b1 = wasm_i32x4_shr(wasm_i32x4_add(b.val, delta), n); - v128_t maxval = wasm_i32x4_splat(65535); - v128_t minval = wasm_i16x8_splat(0); - v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i32x4_gt(a1, maxval)); - v128_t b2 = wasm_v128_bitselect(maxval, b1, wasm_i32x4_gt(b1, maxval)); - v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i32x4_lt(a1, minval)); - v128_t b3 = wasm_v128_bitselect(minval, b2, wasm_i32x4_lt(b1, minval)); - return v_uint16x8(wasm_i8x16_shuffle(a3, b3, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29)); -} - -inline void v_pack_store(uchar* ptr, const v_uint16x8& a) -{ - v128_t maxval = wasm_i16x8_splat(255); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_u16x8_gt(a.val, maxval)); - v128_t r = wasm_i8x16_shuffle(a1, a1, 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14); - uchar t_ptr[16]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<8; ++i) { - ptr[i] = t_ptr[i]; - } -} -inline void v_pack_store(schar* ptr, const v_int16x8& a) -{ - v128_t maxval = wasm_i16x8_splat(127); - v128_t minval = wasm_i16x8_splat(-128); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i16x8_gt(a.val, maxval)); - v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i16x8_lt(a1, minval)); - v128_t r = wasm_i8x16_shuffle(a2, a2, 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14); - schar t_ptr[16]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<8; ++i) { - ptr[i] = t_ptr[i]; - } -} -inline void v_pack_store(ushort* ptr, const v_uint32x4& a) -{ - v128_t maxval = wasm_i32x4_splat(65535); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_u32x4_gt(a.val, maxval)); - v128_t r = wasm_i8x16_shuffle(a1, a1, 0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13); - ushort t_ptr[8]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<4; ++i) { - ptr[i] = t_ptr[i]; - } -} -inline void v_pack_store(short* ptr, const v_int32x4& a) -{ - v128_t maxval = wasm_i32x4_splat(32767); - v128_t minval = wasm_i32x4_splat(-32768); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i32x4_gt(a.val, maxval)); - v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i32x4_lt(a1, minval)); - v128_t r = wasm_i8x16_shuffle(a2, a2, 0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13); - short t_ptr[8]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<4; ++i) { - ptr[i] = t_ptr[i]; - } -} -inline void v_pack_store(unsigned* ptr, const v_uint64x2& a) -{ - v128_t r = wasm_i8x16_shuffle(a.val, a.val, 0,1,2,3,8,9,10,11,0,1,2,3,8,9,10,11); - unsigned t_ptr[4]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<2; ++i) { - ptr[i] = t_ptr[i]; - } -} -inline void v_pack_store(int* ptr, const v_int64x2& a) -{ - v128_t r = wasm_i8x16_shuffle(a.val, a.val, 0,1,2,3,8,9,10,11,0,1,2,3,8,9,10,11); - int t_ptr[4]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<2; ++i) { - ptr[i] = t_ptr[i]; - } -} -inline void v_pack_u_store(uchar* ptr, const v_int16x8& a) -{ - v128_t maxval = wasm_i16x8_splat(255); - v128_t minval = wasm_i16x8_splat(0); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i16x8_gt(a.val, maxval)); - v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i16x8_lt(a1, minval)); - v128_t r = wasm_i8x16_shuffle(a2, a2, 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14); - uchar t_ptr[16]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<8; ++i) { - ptr[i] = t_ptr[i]; - } -} -inline void v_pack_u_store(ushort* ptr, const v_int32x4& a) -{ - v128_t maxval = wasm_i32x4_splat(65535); - v128_t minval = wasm_i32x4_splat(0); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i32x4_gt(a.val, maxval)); - v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i32x4_lt(a1, minval)); - v128_t r = wasm_i8x16_shuffle(a2, a2, 0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13); - ushort t_ptr[8]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<4; ++i) { - ptr[i] = t_ptr[i]; - } -} - -template -inline void v_rshr_pack_store(uchar* ptr, const v_uint16x8& a) -{ - v128_t delta = wasm_i16x8_splat((short)(1 << (n-1))); - v128_t a1 = wasm_u16x8_shr(wasm_i16x8_add(a.val, delta), n); - v128_t maxval = wasm_i16x8_splat(255); - v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_u16x8_gt(a1, maxval)); - v128_t r = wasm_i8x16_shuffle(a2, a2, 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14); - uchar t_ptr[16]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<8; ++i) { - ptr[i] = t_ptr[i]; - } -} -template -inline void v_rshr_pack_store(schar* ptr, const v_int16x8& a) -{ - v128_t delta = wasm_i16x8_splat(((short)1 << (n-1))); - v128_t a1 = wasm_i16x8_shr(wasm_i16x8_add(a.val, delta), n); - v128_t maxval = wasm_i16x8_splat(127); - v128_t minval = wasm_i16x8_splat(-128); - v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i16x8_gt(a1, maxval)); - v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i16x8_lt(a1, minval)); - v128_t r = wasm_i8x16_shuffle(a3, a3, 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14); - schar t_ptr[16]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<8; ++i) { - ptr[i] = t_ptr[i]; - } -} -template -inline void v_rshr_pack_store(ushort* ptr, const v_uint32x4& a) -{ - v128_t delta = wasm_i32x4_splat(((int)1 << (n-1))); - v128_t a1 = wasm_u32x4_shr(wasm_i32x4_add(a.val, delta), n); - v128_t maxval = wasm_i32x4_splat(65535); - v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_u32x4_gt(a1, maxval)); - v128_t r = wasm_i8x16_shuffle(a2, a2, 0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13); - ushort t_ptr[8]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<4; ++i) { - ptr[i] = t_ptr[i]; - } -} -template -inline void v_rshr_pack_store(short* ptr, const v_int32x4& a) -{ - v128_t delta = wasm_i32x4_splat(((int)1 << (n-1))); - v128_t a1 = wasm_i32x4_shr(wasm_i32x4_add(a.val, delta), n); - v128_t maxval = wasm_i32x4_splat(32767); - v128_t minval = wasm_i32x4_splat(-32768); - v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i32x4_gt(a1, maxval)); - v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i32x4_lt(a1, minval)); - v128_t r = wasm_i8x16_shuffle(a3, a3, 0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13); - short t_ptr[8]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<4; ++i) { - ptr[i] = t_ptr[i]; - } -} -template -inline void v_rshr_pack_store(unsigned* ptr, const v_uint64x2& a) -{ - v128_t delta = wasm_i64x2_splat(((int64)1 << (n-1))); - v128_t a1 = wasm_u64x2_shr(wasm_i64x2_add(a.val, delta), n); - v128_t r = wasm_i8x16_shuffle(a1, a1, 0,1,2,3,8,9,10,11,0,1,2,3,8,9,10,11); - unsigned t_ptr[4]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<2; ++i) { - ptr[i] = t_ptr[i]; - } -} -template -inline void v_rshr_pack_store(int* ptr, const v_int64x2& a) -{ - v128_t delta = wasm_i64x2_splat(((int64)1 << (n-1))); - v128_t a1 = wasm_i64x2_shr(wasm_i64x2_add(a.val, delta), n); - v128_t r = wasm_i8x16_shuffle(a1, a1, 0,1,2,3,8,9,10,11,0,1,2,3,8,9,10,11); - int t_ptr[4]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<2; ++i) { - ptr[i] = t_ptr[i]; - } -} -template -inline void v_rshr_pack_u_store(uchar* ptr, const v_int16x8& a) -{ - v128_t delta = wasm_i16x8_splat(((short)1 << (n-1))); - v128_t a1 = wasm_i16x8_shr(wasm_i16x8_add(a.val, delta), n); - v128_t maxval = wasm_i16x8_splat(255); - v128_t minval = wasm_i16x8_splat(0); - v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i16x8_gt(a1, maxval)); - v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i16x8_lt(a1, minval)); - v128_t r = wasm_i8x16_shuffle(a3, a3, 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14); - uchar t_ptr[16]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<8; ++i) { - ptr[i] = t_ptr[i]; - } -} -template -inline void v_rshr_pack_u_store(ushort* ptr, const v_int32x4& a) -{ - v128_t delta = wasm_i32x4_splat(((int)1 << (n-1))); - v128_t a1 = wasm_i32x4_shr(wasm_i32x4_add(a.val, delta), n); - v128_t maxval = wasm_i32x4_splat(65535); - v128_t minval = wasm_i32x4_splat(0); - v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i32x4_gt(a1, maxval)); - v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i32x4_lt(a1, minval)); - v128_t r = wasm_i8x16_shuffle(a3, a3, 0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13); - ushort t_ptr[8]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<4; ++i) { - ptr[i] = t_ptr[i]; - } -} - -inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) -{ - v128_t maxval = wasm_i16x8_splat(255); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_u16x8_gt(a.val, maxval)); - v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_u16x8_gt(b.val, maxval)); - return v_uint8x16(wasm_i8x16_shuffle(a1, b1, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); -} - -inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, - const v_uint32x4& c, const v_uint32x4& d) -{ - v128_t maxval = wasm_i32x4_splat(255); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_u32x4_gt(a.val, maxval)); - v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_u32x4_gt(b.val, maxval)); - v128_t c1 = wasm_v128_bitselect(maxval, c.val, wasm_u32x4_gt(c.val, maxval)); - v128_t d1 = wasm_v128_bitselect(maxval, d.val, wasm_u32x4_gt(d.val, maxval)); - v128_t ab = wasm_i8x16_shuffle(a1, b1, 0,4,8,12,16,20,24,28,0,4,8,12,16,20,24,28); - v128_t cd = wasm_i8x16_shuffle(c1, d1, 0,4,8,12,16,20,24,28,0,4,8,12,16,20,24,28); - return v_uint8x16(wasm_i8x16_shuffle(ab, cd, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23)); -} - -inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, - const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, - const v_uint64x2& g, const v_uint64x2& h) -{ - v128_t maxval = wasm_i32x4_splat(255); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, ((__u64x2)(a.val) > (__u64x2)maxval)); - v128_t b1 = wasm_v128_bitselect(maxval, b.val, ((__u64x2)(b.val) > (__u64x2)maxval)); - v128_t c1 = wasm_v128_bitselect(maxval, c.val, ((__u64x2)(c.val) > (__u64x2)maxval)); - v128_t d1 = wasm_v128_bitselect(maxval, d.val, ((__u64x2)(d.val) > (__u64x2)maxval)); - v128_t e1 = wasm_v128_bitselect(maxval, e.val, ((__u64x2)(e.val) > (__u64x2)maxval)); - v128_t f1 = wasm_v128_bitselect(maxval, f.val, ((__u64x2)(f.val) > (__u64x2)maxval)); - v128_t g1 = wasm_v128_bitselect(maxval, g.val, ((__u64x2)(g.val) > (__u64x2)maxval)); - v128_t h1 = wasm_v128_bitselect(maxval, h.val, ((__u64x2)(h.val) > (__u64x2)maxval)); - v128_t ab = wasm_i8x16_shuffle(a1, b1, 0,8,16,24,0,8,16,24,0,8,16,24,0,8,16,24); - v128_t cd = wasm_i8x16_shuffle(c1, d1, 0,8,16,24,0,8,16,24,0,8,16,24,0,8,16,24); - v128_t ef = wasm_i8x16_shuffle(e1, f1, 0,8,16,24,0,8,16,24,0,8,16,24,0,8,16,24); - v128_t gh = wasm_i8x16_shuffle(g1, h1, 0,8,16,24,0,8,16,24,0,8,16,24,0,8,16,24); - v128_t abcd = wasm_i8x16_shuffle(ab, cd, 0,1,2,3,16,17,18,19,0,1,2,3,16,17,18,19); - v128_t efgh = wasm_i8x16_shuffle(ef, gh, 0,1,2,3,16,17,18,19,0,1,2,3,16,17,18,19); - return v_uint8x16(wasm_i8x16_shuffle(abcd, efgh, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23)); -} - -inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, - const v_float32x4& m3) -{ - v128_t v0 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 0)); - v128_t v1 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 1)); - v128_t v2 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 2)); - v128_t v3 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 3)); - v0 = wasm_f32x4_mul(v0, m0.val); - v1 = wasm_f32x4_mul(v1, m1.val); - v2 = wasm_f32x4_mul(v2, m2.val); - v3 = wasm_f32x4_mul(v3, m3.val); - - return v_float32x4(wasm_f32x4_add(wasm_f32x4_add(v0, v1), wasm_f32x4_add(v2, v3))); -} - -inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, - const v_float32x4& a) -{ - v128_t v0 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 0)); - v128_t v1 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 1)); - v128_t v2 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 2)); - v0 = wasm_f32x4_mul(v0, m0.val); - v1 = wasm_f32x4_mul(v1, m1.val); - v2 = wasm_f32x4_mul(v2, m2.val); - - return v_float32x4(wasm_f32x4_add(wasm_f32x4_add(v0, v1), wasm_f32x4_add(v2, a.val))); -} - -#define OPENCV_HAL_IMPL_WASM_BIN_OP(bin_op, _Tpvec, intrin) \ -inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(intrin(a.val, b.val)); \ -} - -OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_uint8x16, wasm_u8x16_add_saturate) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_uint8x16, wasm_u8x16_sub_saturate) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_int8x16, wasm_i8x16_add_saturate) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_int8x16, wasm_i8x16_sub_saturate) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_uint16x8, wasm_u16x8_add_saturate) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_uint16x8, wasm_u16x8_sub_saturate) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_int16x8, wasm_i16x8_add_saturate) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_int16x8, wasm_i16x8_sub_saturate) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_uint32x4, wasm_i32x4_add) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_uint32x4, wasm_i32x4_sub) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_mul, v_uint32x4, wasm_i32x4_mul) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_int32x4, wasm_i32x4_add) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_int32x4, wasm_i32x4_sub) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_mul, v_int32x4, wasm_i32x4_mul) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_float32x4, wasm_f32x4_add) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_float32x4, wasm_f32x4_sub) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_mul, v_float32x4, wasm_f32x4_mul) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_div, v_float32x4, wasm_f32x4_div) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_uint64x2, wasm_i64x2_add) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_uint64x2, wasm_i64x2_sub) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_int64x2, wasm_i64x2_add) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_int64x2, wasm_i64x2_sub) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_float64x2, wasm_f64x2_add) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_float64x2, wasm_f64x2_sub) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_mul, v_float64x2, wasm_f64x2_mul) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_div, v_float64x2, wasm_f64x2_div) - -// saturating multiply 8-bit, 16-bit -#define OPENCV_HAL_IMPL_WASM_MUL_SAT(_Tpvec, _Tpwvec) \ -inline _Tpvec v_mul(const _Tpvec& a, const _Tpvec& b) \ -{ \ - _Tpwvec c, d; \ - v_mul_expand(a, b, c, d); \ - return v_pack(c, d); \ -} - -OPENCV_HAL_IMPL_WASM_MUL_SAT(v_uint8x16, v_uint16x8) -OPENCV_HAL_IMPL_WASM_MUL_SAT(v_int8x16, v_int16x8) -OPENCV_HAL_IMPL_WASM_MUL_SAT(v_uint16x8, v_uint32x4) -OPENCV_HAL_IMPL_WASM_MUL_SAT(v_int16x8, v_int32x4) - -// Multiply and expand -inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b, - v_uint16x8& c, v_uint16x8& d) -{ - v_uint16x8 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c = v_mul_wrap(a0, b0); - d = v_mul_wrap(a1, b1); -} - -inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b, - v_int16x8& c, v_int16x8& d) -{ - v_int16x8 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c = v_mul_wrap(a0, b0); - d = v_mul_wrap(a1, b1); -} - -inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, - v_int32x4& c, v_int32x4& d) -{ - v_int32x4 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c.val = wasm_i32x4_mul(a0.val, b0.val); - d.val = wasm_i32x4_mul(a1.val, b1.val); -} - -inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, - v_uint32x4& c, v_uint32x4& d) -{ - v_uint32x4 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c.val = wasm_i32x4_mul(a0.val, b0.val); - d.val = wasm_i32x4_mul(a1.val, b1.val); -} - -inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, - v_uint64x2& c, v_uint64x2& d) -{ - v_uint64x2 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c.val = ((__u64x2)(a0.val) * (__u64x2)(b0.val)); - d.val = ((__u64x2)(a1.val) * (__u64x2)(b1.val)); -} - -inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) -{ - v_int32x4 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - v128_t c = wasm_i32x4_mul(a0.val, b0.val); - v128_t d = wasm_i32x4_mul(a1.val, b1.val); - return v_int16x8(wasm_i8x16_shuffle(c, d, 2,3,6,7,10,11,14,15,18,19,22,23,26,27,30,31)); -} -inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) -{ - v_uint32x4 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - v128_t c = wasm_i32x4_mul(a0.val, b0.val); - v128_t d = wasm_i32x4_mul(a1.val, b1.val); - return v_uint16x8(wasm_i8x16_shuffle(c, d, 2,3,6,7,10,11,14,15,18,19,22,23,26,27,30,31)); -} - -//////// Dot Product //////// - -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) -{ - v128_t a0 = wasm_i32x4_shr(wasm_i32x4_shl(a.val, 16), 16); - v128_t a1 = wasm_i32x4_shr(a.val, 16); - v128_t b0 = wasm_i32x4_shr(wasm_i32x4_shl(b.val, 16), 16); - v128_t b1 = wasm_i32x4_shr(b.val, 16); - v128_t c = wasm_i32x4_mul(a0, b0); - v128_t d = wasm_i32x4_mul(a1, b1); - return v_int32x4(wasm_i32x4_add(c, d)); -} - -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ return v_add(v_dotprod(a, b), c); } - -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) -{ - v128_t a0 = wasm_i64x2_shr(wasm_i64x2_shl(a.val, 32), 32); - v128_t a1 = wasm_i64x2_shr(a.val, 32); - v128_t b0 = wasm_i64x2_shr(wasm_i64x2_shl(b.val, 32), 32); - v128_t b1 = wasm_i64x2_shr(b.val, 32); - v128_t c = (v128_t)((__i64x2)a0 * (__i64x2)b0); - v128_t d = (v128_t)((__i64x2)a1 * (__i64x2)b1); - return v_int64x2(wasm_i64x2_add(c, d)); -} -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ - return v_add(v_dotprod(a, b), c); -} - -// 8 >> 32 -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) -{ - v128_t a0 = wasm_u16x8_shr(wasm_i16x8_shl(a.val, 8), 8); - v128_t a1 = wasm_u16x8_shr(a.val, 8); - v128_t b0 = wasm_u16x8_shr(wasm_i16x8_shl(b.val, 8), 8); - v128_t b1 = wasm_u16x8_shr(b.val, 8); - return v_uint32x4((v_add( - v_dotprod(v_int16x8(a0), v_int16x8(b0)), - v_dotprod(v_int16x8(a1), v_int16x8(b1)))).val - ); -} -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) -{ - v128_t a0 = wasm_i16x8_shr(wasm_i16x8_shl(a.val, 8), 8); - v128_t a1 = wasm_i16x8_shr(a.val, 8); - v128_t b0 = wasm_i16x8_shr(wasm_i16x8_shl(b.val, 8), 8); - v128_t b1 = wasm_i16x8_shr(b.val, 8); - return v_int32x4(v_add( - v_dotprod(v_int16x8(a0), v_int16x8(b0)), - v_dotprod(v_int16x8(a1), v_int16x8(b1)) - )); -} -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) -{ - v128_t a0 = wasm_u32x4_shr(wasm_i32x4_shl(a.val, 16), 16); - v128_t a1 = wasm_u32x4_shr(a.val, 16); - v128_t b0 = wasm_u32x4_shr(wasm_i32x4_shl(b.val, 16), 16); - v128_t b1 = wasm_u32x4_shr(b.val, 16); - return v_uint64x2((v_add( - v_dotprod(v_int32x4(a0), v_int32x4(b0)), - v_dotprod(v_int32x4(a1), v_int32x4(b1))).val - )); -} -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) -{ - v128_t a0 = wasm_i32x4_shr(wasm_i32x4_shl(a.val, 16), 16); - v128_t a1 = wasm_i32x4_shr(a.val, 16); - v128_t b0 = wasm_i32x4_shr(wasm_i32x4_shl(b.val, 16), 16); - v128_t b1 = wasm_i32x4_shr(b.val, 16); - return v_int64x2((v_add( - v_dotprod(v_int32x4(a0), v_int32x4(b0)), - v_dotprod(v_int32x4(a1), v_int32x4(b1))) - )); -} - -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 32 >> 64f -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) -{ return v_cvt_f64(v_dotprod(a, b)); } -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -//////// Fast Dot Product //////// - -// 16 >> 32 -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) -{ return v_dotprod(a, b); } -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ return v_dotprod(a, b, c); } - -// 32 >> 64 -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) -{ return v_dotprod(a, b); } -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ return v_dotprod(a, b, c); } - -// 8 >> 32 -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) -{ return v_dotprod_expand(a, b); } -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) -{ return v_dotprod_expand(a, b, c); } -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) -{ return v_dotprod_expand(a, b); } -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) -{ return v_dotprod_expand(a, b, c); } - -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) -{ return v_dotprod_expand(a, b); } -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) -{ return v_dotprod_expand(a, b, c); } -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) -{ return v_dotprod_expand(a, b); } -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) -{ return v_dotprod_expand(a, b, c); } - -// 32 >> 64f -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) -{ return v_dotprod_expand(a, b); } -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) -{ return v_dotprod_expand(a, b, c); } - -#define OPENCV_HAL_IMPL_WASM_LOGIC_OP(_Tpvec) \ -OPENCV_HAL_IMPL_WASM_BIN_OP(v_and, _Tpvec, wasm_v128_and) \ -OPENCV_HAL_IMPL_WASM_BIN_OP(v_or, _Tpvec, wasm_v128_or) \ -OPENCV_HAL_IMPL_WASM_BIN_OP(v_xor, _Tpvec, wasm_v128_xor) \ -inline _Tpvec v_not(const _Tpvec& a) \ -{ \ - return _Tpvec(wasm_v128_not(a.val)); \ -} - -OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_uint8x16) -OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_int8x16) -OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_uint16x8) -OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_int16x8) -OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_uint32x4) -OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_int32x4) -OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_uint64x2) -OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_int64x2) -OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_float32x4) -OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_float64x2) - -inline v_float32x4 v_sqrt(const v_float32x4& x) -{ - return v_float32x4(wasm_f32x4_sqrt(x.val)); -} - -inline v_float32x4 v_invsqrt(const v_float32x4& x) -{ - const v128_t _1_0 = wasm_f32x4_splat(1.0); - return v_float32x4(wasm_f32x4_div(_1_0, wasm_f32x4_sqrt(x.val))); -} - -inline v_float64x2 v_sqrt(const v_float64x2& x) -{ - return v_float64x2(wasm_f64x2_sqrt(x.val)); -} - -inline v_float64x2 v_invsqrt(const v_float64x2& x) -{ - const v128_t _1_0 = wasm_f64x2_splat(1.0); - return v_float64x2(wasm_f64x2_div(_1_0, wasm_f64x2_sqrt(x.val))); -} - -#define OPENCV_HAL_IMPL_WASM_ABS_INT_FUNC(_Tpuvec, _Tpsvec, suffix, zsuffix, shiftWidth) \ -inline _Tpuvec v_abs(const _Tpsvec& x) \ -{ \ - v128_t s = wasm_##suffix##_shr(x.val, shiftWidth); \ - v128_t f = wasm_##zsuffix##_shr(x.val, shiftWidth); \ - return _Tpuvec(wasm_##zsuffix##_add(wasm_v128_xor(x.val, f), s)); \ -} - -OPENCV_HAL_IMPL_WASM_ABS_INT_FUNC(v_uint8x16, v_int8x16, u8x16, i8x16, 7) -OPENCV_HAL_IMPL_WASM_ABS_INT_FUNC(v_uint16x8, v_int16x8, u16x8, i16x8, 15) -OPENCV_HAL_IMPL_WASM_ABS_INT_FUNC(v_uint32x4, v_int32x4, u32x4, i32x4, 31) - -inline v_float32x4 v_abs(const v_float32x4& x) -{ return v_float32x4(wasm_f32x4_abs(x.val)); } -inline v_float64x2 v_abs(const v_float64x2& x) -{ - return v_float64x2(wasm_f64x2_abs(x.val)); -} - -// TODO: exp, log, sin, cos - -#define OPENCV_HAL_IMPL_WASM_BIN_FUNC(_Tpvec, func, intrin) \ -inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(intrin(a.val, b.val)); \ -} - -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_float32x4, v_min, wasm_f32x4_min) -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_float32x4, v_max, wasm_f32x4_max) -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_float64x2, v_min, wasm_f64x2_min) -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_float64x2, v_max, wasm_f64x2_max) - -#define OPENCV_HAL_IMPL_WASM_MINMAX_S_INIT_FUNC(_Tpvec, suffix) \ -inline _Tpvec v_min(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(wasm_v128_bitselect(b.val, a.val, wasm_##suffix##_gt(a.val, b.val))); \ -} \ -inline _Tpvec v_max(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(wasm_v128_bitselect(a.val, b.val, wasm_##suffix##_gt(a.val, b.val))); \ -} - -OPENCV_HAL_IMPL_WASM_MINMAX_S_INIT_FUNC(v_int8x16, i8x16) -OPENCV_HAL_IMPL_WASM_MINMAX_S_INIT_FUNC(v_int16x8, i16x8) -OPENCV_HAL_IMPL_WASM_MINMAX_S_INIT_FUNC(v_int32x4, i32x4) - -#define OPENCV_HAL_IMPL_WASM_MINMAX_U_INIT_FUNC(_Tpvec, suffix, deltaNum) \ -inline _Tpvec v_min(const _Tpvec& a, const _Tpvec& b) \ -{ \ - v128_t delta = wasm_##suffix##_splat(deltaNum); \ - v128_t mask = wasm_##suffix##_gt(wasm_v128_xor(a.val, delta), wasm_v128_xor(b.val, delta)); \ - return _Tpvec(wasm_v128_bitselect(b.val, a.val, mask)); \ -} \ -inline _Tpvec v_max(const _Tpvec& a, const _Tpvec& b) \ -{ \ - v128_t delta = wasm_##suffix##_splat(deltaNum); \ - v128_t mask = wasm_##suffix##_gt(wasm_v128_xor(a.val, delta), wasm_v128_xor(b.val, delta)); \ - return _Tpvec(wasm_v128_bitselect(a.val, b.val, mask)); \ -} - -OPENCV_HAL_IMPL_WASM_MINMAX_U_INIT_FUNC(v_uint8x16, i8x16, (schar)0x80) -OPENCV_HAL_IMPL_WASM_MINMAX_U_INIT_FUNC(v_uint16x8, i16x8, (short)0x8000) -OPENCV_HAL_IMPL_WASM_MINMAX_U_INIT_FUNC(v_uint32x4, i32x4, (int)0x80000000) - -#define OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(_Tpvec, suffix, esuffix) \ -inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(wasm_##esuffix##_eq(a.val, b.val)); } \ -inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(wasm_##esuffix##_ne(a.val, b.val)); } \ -inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(wasm_##suffix##_lt(a.val, b.val)); } \ -inline _Tpvec v_gt(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(wasm_##suffix##_gt(a.val, b.val)); } \ -inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(wasm_##suffix##_le(a.val, b.val)); } \ -inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(wasm_##suffix##_ge(a.val, b.val)); } - -OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_uint8x16, u8x16, i8x16) -OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_int8x16, i8x16, i8x16) -OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_uint16x8, u16x8, i16x8) -OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_int16x8, i16x8, i16x8) -OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_uint32x4, u32x4, i32x4) -OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_int32x4, i32x4, i32x4) -OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_float32x4, f32x4, f32x4) -OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_float64x2, f64x2, f64x2) - -#define OPENCV_HAL_IMPL_WASM_64BIT_CMP_OP(_Tpvec, cast) \ -inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ -{ return cast(v_eq(v_reinterpret_as_f64(a), v_reinterpret_as_f64(b))); } \ -inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ -{ return cast(v_ne(v_reinterpret_as_f64(a), v_reinterpret_as_f64(b))); } - -OPENCV_HAL_IMPL_WASM_64BIT_CMP_OP(v_uint64x2, v_reinterpret_as_u64) -OPENCV_HAL_IMPL_WASM_64BIT_CMP_OP(v_int64x2, v_reinterpret_as_s64) - -inline v_float32x4 v_not_nan(const v_float32x4& a) -{ - v128_t z = wasm_i32x4_splat(0x7fffffff); - v128_t t = wasm_i32x4_splat(0x7f800000); - return v_float32x4(wasm_u32x4_lt(wasm_v128_and(a.val, z), t)); -} -inline v_float64x2 v_not_nan(const v_float64x2& a) -{ - v128_t z = wasm_i64x2_splat(0x7fffffffffffffff); - v128_t t = wasm_i64x2_splat(0x7ff0000000000000); - return v_float64x2((__u64x2)(wasm_v128_and(a.val, z)) < (__u64x2)t); -} - -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint8x16, v_add_wrap, wasm_i8x16_add) -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int8x16, v_add_wrap, wasm_i8x16_add) -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint16x8, v_add_wrap, wasm_i16x8_add) -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int16x8, v_add_wrap, wasm_i16x8_add) -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint8x16, v_sub_wrap, wasm_i8x16_sub) -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int8x16, v_sub_wrap, wasm_i8x16_sub) -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint16x8, v_sub_wrap, wasm_i16x8_sub) -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int16x8, v_sub_wrap, wasm_i16x8_sub) -#if (__EMSCRIPTEN_major__ * 1000000 + __EMSCRIPTEN_minor__ * 1000 + __EMSCRIPTEN_tiny__) >= (1039012) -// details: https://github.com/opencv/opencv/issues/18097 ( https://github.com/emscripten-core/emscripten/issues/12018 ) -// 1.39.12: https://github.com/emscripten-core/emscripten/commit/cd801d0f110facfd694212a3c8b2ed2ffcd630e2 -inline v_uint8x16 v_mul_wrap(const v_uint8x16& a, const v_uint8x16& b) -{ - uchar a_[16], b_[16]; - wasm_v128_store(a_, a.val); - wasm_v128_store(b_, b.val); - for (int i = 0; i < 16; i++) - a_[i] = (uchar)(a_[i] * b_[i]); - return v_uint8x16(wasm_v128_load(a_)); -} -inline v_int8x16 v_mul_wrap(const v_int8x16& a, const v_int8x16& b) -{ - schar a_[16], b_[16]; - wasm_v128_store(a_, a.val); - wasm_v128_store(b_, b.val); - for (int i = 0; i < 16; i++) - a_[i] = (schar)(a_[i] * b_[i]); - return v_int8x16(wasm_v128_load(a_)); -} -#else -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint8x16, v_mul_wrap, wasm_i8x16_mul) -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int8x16, v_mul_wrap, wasm_i8x16_mul) -#endif -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint16x8, v_mul_wrap, wasm_i16x8_mul) -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int16x8, v_mul_wrap, wasm_i16x8_mul) - - -/** Absolute difference **/ - -inline v_uint8x16 v_absdiff(const v_uint8x16& a, const v_uint8x16& b) -{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } -inline v_uint16x8 v_absdiff(const v_uint16x8& a, const v_uint16x8& b) -{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } -inline v_uint32x4 v_absdiff(const v_uint32x4& a, const v_uint32x4& b) -{ return v_sub(v_max(a, b), v_min(a, b)); } - -inline v_uint8x16 v_absdiff(const v_int8x16& a, const v_int8x16& b) -{ - v_int8x16 d = v_sub_wrap(a, b); - v_int8x16 m = v_lt(a, b); - return v_reinterpret_as_u8(v_sub_wrap(v_xor(d, m), m)); -} -inline v_uint16x8 v_absdiff(const v_int16x8& a, const v_int16x8& b) -{ - return v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))); -} -inline v_uint32x4 v_absdiff(const v_int32x4& a, const v_int32x4& b) -{ - v_int32x4 d = v_sub(a, b); - v_int32x4 m = v_lt(a, b); - return v_reinterpret_as_u32(v_sub(v_xor(d, m), m)); -} - -/** Saturating absolute difference **/ -inline v_int8x16 v_absdiffs(const v_int8x16& a, const v_int8x16& b) -{ - v_int8x16 d = v_sub(a, b); - v_int8x16 m = v_lt(a, b); - return v_sub(v_xor(d, m), m); - } -inline v_int16x8 v_absdiffs(const v_int16x8& a, const v_int16x8& b) -{ return v_sub(v_max(a, b), v_min(a, b)); } - - -inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ - return v_add(v_mul(a, b), c); -} - -inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ - return v_fma(a, b, c); -} - -inline v_float32x4 v_fma(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) -{ - return v_add(v_mul(a, b), c); -} - -inline v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) -{ - return v_add(v_mul(a, b), c); -} - -inline v_float32x4 v_absdiff(const v_float32x4& a, const v_float32x4& b) -{ - v128_t absmask_vec = wasm_i32x4_splat(0x7fffffff); - return v_float32x4(wasm_v128_and(wasm_f32x4_sub(a.val, b.val), absmask_vec)); -} -inline v_float64x2 v_absdiff(const v_float64x2& a, const v_float64x2& b) -{ - v128_t absmask_vec = wasm_u64x2_shr(wasm_i32x4_splat(-1), 1); - return v_float64x2(wasm_v128_and(wasm_f64x2_sub(a.val, b.val), absmask_vec)); -} - -#define OPENCV_HAL_IMPL_WASM_MISC_FLT_OP(_Tpvec, suffix) \ -inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ -{ \ - v128_t a_Square = wasm_##suffix##_mul(a.val, a.val); \ - v128_t b_Square = wasm_##suffix##_mul(b.val, b.val); \ - return _Tpvec(wasm_##suffix##_sqrt(wasm_##suffix##_add(a_Square, b_Square))); \ -} \ -inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ -{ \ - v128_t a_Square = wasm_##suffix##_mul(a.val, a.val); \ - v128_t b_Square = wasm_##suffix##_mul(b.val, b.val); \ - return _Tpvec(wasm_##suffix##_add(a_Square, b_Square)); \ -} \ -inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ -{ \ - return _Tpvec(wasm_##suffix##_add(wasm_##suffix##_mul(a.val, b.val), c.val)); \ -} - -OPENCV_HAL_IMPL_WASM_MISC_FLT_OP(v_float32x4, f32x4) -OPENCV_HAL_IMPL_WASM_MISC_FLT_OP(v_float64x2, f64x2) - -#define OPENCV_HAL_IMPL_WASM_SHIFT_OP(_Tpuvec, _Tpsvec, suffix, ssuffix) \ -inline _Tpuvec v_shl(const _Tpuvec& a, int imm) \ -{ \ - return _Tpuvec(wasm_##suffix##_shl(a.val, imm)); \ -} \ -inline _Tpsvec v_shl(const _Tpsvec& a, int imm) \ -{ \ - return _Tpsvec(wasm_##suffix##_shl(a.val, imm)); \ -} \ -inline _Tpuvec v_shr(const _Tpuvec& a, int imm) \ -{ \ - return _Tpuvec(wasm_##ssuffix##_shr(a.val, imm)); \ -} \ -inline _Tpsvec v_shr(const _Tpsvec& a, int imm) \ -{ \ - return _Tpsvec(wasm_##suffix##_shr(a.val, imm)); \ -} \ -template \ -inline _Tpuvec v_shl(const _Tpuvec& a) \ -{ \ - return _Tpuvec(wasm_##suffix##_shl(a.val, imm)); \ -} \ -template \ -inline _Tpsvec v_shl(const _Tpsvec& a) \ -{ \ - return _Tpsvec(wasm_##suffix##_shl(a.val, imm)); \ -} \ -template \ -inline _Tpuvec v_shr(const _Tpuvec& a) \ -{ \ - return _Tpuvec(wasm_##ssuffix##_shr(a.val, imm)); \ -} \ -template \ -inline _Tpsvec v_shr(const _Tpsvec& a) \ -{ \ - return _Tpsvec(wasm_##suffix##_shr(a.val, imm)); \ -} - -OPENCV_HAL_IMPL_WASM_SHIFT_OP(v_uint8x16, v_int8x16, i8x16, u8x16) -OPENCV_HAL_IMPL_WASM_SHIFT_OP(v_uint16x8, v_int16x8, i16x8, u16x8) -OPENCV_HAL_IMPL_WASM_SHIFT_OP(v_uint32x4, v_int32x4, i32x4, u32x4) -OPENCV_HAL_IMPL_WASM_SHIFT_OP(v_uint64x2, v_int64x2, i64x2, u64x2) - -namespace hal_wasm_internal -{ - template 16)), - bool is_first = (imm == 0), - bool is_second = (imm == 16), - bool is_other = (((imm > 0) && (imm < 16)))> - class v_wasm_palignr_u8_class; - - template - class v_wasm_palignr_u8_class; - - template - class v_wasm_palignr_u8_class - { - public: - inline v128_t operator()(const v128_t& a, const v128_t&) const - { - return a; - } - }; - - template - class v_wasm_palignr_u8_class - { - public: - inline v128_t operator()(const v128_t&, const v128_t& b) const - { - return b; - } - }; - - template - class v_wasm_palignr_u8_class - { - public: - inline v128_t operator()(const v128_t& a, const v128_t& b) const - { - enum { imm2 = (sizeof(v128_t) - imm) }; - return wasm_i8x16_shuffle(a, b, - imm, imm+1, imm+2, imm+3, - imm+4, imm+5, imm+6, imm+7, - imm+8, imm+9, imm+10, imm+11, - imm+12, imm+13, imm+14, imm+15); - } - }; - - template - inline v128_t v_wasm_palignr_u8(const v128_t& a, const v128_t& b) - { - CV_StaticAssert((imm >= 0) && (imm <= 16), "Invalid imm for v_wasm_palignr_u8."); - return v_wasm_palignr_u8_class()(a, b); - } -} - -template -inline _Tpvec v_rotate_right(const _Tpvec &a) -{ - using namespace hal_wasm_internal; - enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type)) }; - v128_t z = wasm_i8x16_splat(0); - return _Tpvec(v_wasm_palignr_u8(a.val, z)); -} - -template -inline _Tpvec v_rotate_left(const _Tpvec &a) -{ - using namespace hal_wasm_internal; - enum { imm2 = ((_Tpvec::nlanes - imm) * sizeof(typename _Tpvec::lane_type)) }; - v128_t z = wasm_i8x16_splat(0); - return _Tpvec(v_wasm_palignr_u8(z, a.val)); -} - -template -inline _Tpvec v_rotate_right(const _Tpvec &a, const _Tpvec &b) -{ - using namespace hal_wasm_internal; - enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type)) }; - return _Tpvec(v_wasm_palignr_u8(a.val, b.val)); -} - -template -inline _Tpvec v_rotate_left(const _Tpvec &a, const _Tpvec &b) -{ - using namespace hal_wasm_internal; - enum { imm2 = ((_Tpvec::nlanes - imm) * sizeof(typename _Tpvec::lane_type)) }; - return _Tpvec(v_wasm_palignr_u8(b.val, a.val)); -} - -#define OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(_Tpvec, _Tp) \ -inline _Tpvec v_load(const _Tp* ptr) \ -{ return _Tpvec(wasm_v128_load(ptr)); } \ -inline _Tpvec v_load_aligned(const _Tp* ptr) \ -{ return _Tpvec(wasm_v128_load(ptr)); } \ -inline _Tpvec v_load_low(const _Tp* ptr) \ -{ \ - _Tp tmp[_Tpvec::nlanes] = {0}; \ - for (int i=0; i<_Tpvec::nlanes/2; ++i) { \ - tmp[i] = ptr[i]; \ - } \ - return _Tpvec(wasm_v128_load(tmp)); \ -} \ -inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ -{ \ - _Tp tmp[_Tpvec::nlanes]; \ - for (int i=0; i<_Tpvec::nlanes/2; ++i) { \ - tmp[i] = ptr0[i]; \ - tmp[i+_Tpvec::nlanes/2] = ptr1[i]; \ - } \ - return _Tpvec(wasm_v128_load(tmp)); \ -} \ -inline void v_store(_Tp* ptr, const _Tpvec& a) \ -{ wasm_v128_store(ptr, a.val); } \ -inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ -{ wasm_v128_store(ptr, a.val); } \ -inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ -{ wasm_v128_store(ptr, a.val); } \ -inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ -{ \ - wasm_v128_store(ptr, a.val); \ -} \ -inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ -{ \ - _Tpvec::lane_type a_[_Tpvec::nlanes]; \ - wasm_v128_store(a_, a.val); \ - for (int i = 0; i < (_Tpvec::nlanes / 2); i++) \ - ptr[i] = a_[i]; \ -} \ -inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ -{ \ - _Tpvec::lane_type a_[_Tpvec::nlanes]; \ - wasm_v128_store(a_, a.val); \ - for (int i = 0; i < (_Tpvec::nlanes / 2); i++) \ - ptr[i] = a_[i + (_Tpvec::nlanes / 2)]; \ -} - -OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_uint8x16, uchar) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_int8x16, schar) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_uint16x8, ushort) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_int16x8, short) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_uint32x4, unsigned) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_int32x4, int) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_uint64x2, uint64) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_int64x2, int64) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_float32x4, float) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_float64x2, double) - - -/** Reverse **/ -inline v_uint8x16 v_reverse(const v_uint8x16 &a) -{ return v_uint8x16(wasm_i8x16_shuffle(a.val, a.val, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)); } - -inline v_int8x16 v_reverse(const v_int8x16 &a) -{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } - -inline v_uint16x8 v_reverse(const v_uint16x8 &a) -{ return v_uint16x8(wasm_i8x16_shuffle(a.val, a.val, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1)); } - -inline v_int16x8 v_reverse(const v_int16x8 &a) -{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } - -inline v_uint32x4 v_reverse(const v_uint32x4 &a) -{ return v_uint32x4(wasm_i8x16_shuffle(a.val, a.val, 12, 13, 14, 15, 8, 9, 10, 11, 4, 5, 6, 7, 0, 1, 2, 3)); } - -inline v_int32x4 v_reverse(const v_int32x4 &a) -{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_float32x4 v_reverse(const v_float32x4 &a) -{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_uint64x2 v_reverse(const v_uint64x2 &a) -{ return v_uint64x2(wasm_i8x16_shuffle(a.val, a.val, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7)); } - -inline v_int64x2 v_reverse(const v_int64x2 &a) -{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } - -inline v_float64x2 v_reverse(const v_float64x2 &a) -{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } - - -#define OPENCV_HAL_IMPL_WASM_REDUCE_OP_4_SUM(_Tpvec, scalartype, regtype, suffix, esuffix) \ -inline scalartype v_reduce_sum(const _Tpvec& a) \ -{ \ - regtype val = a.val; \ - val = wasm_##suffix##_add(val, wasm_i8x16_shuffle(val, val, 8,9,10,11,12,13,14,15,0,1,2,3,4,5,6,7)); \ - val = wasm_##suffix##_add(val, wasm_i8x16_shuffle(val, val, 4,5,6,7,8,9,10,11,12,13,14,15,0,1,2,3)); \ - return (scalartype)wasm_##esuffix##_extract_lane(val, 0); \ -} - -OPENCV_HAL_IMPL_WASM_REDUCE_OP_4_SUM(v_uint32x4, unsigned, v128_t, i32x4, i32x4) -OPENCV_HAL_IMPL_WASM_REDUCE_OP_4_SUM(v_int32x4, int, v128_t, i32x4, i32x4) -OPENCV_HAL_IMPL_WASM_REDUCE_OP_4_SUM(v_float32x4, float, v128_t, f32x4, f32x4) - -// To do: Optimize v_reduce_sum with wasm intrin. -// Now use fallback implementation as there is no widening op in wasm intrin. - -#define OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(_Tpvec, scalartype) \ -inline scalartype v_reduce_sum(const _Tpvec& a) \ -{ \ - _Tpvec::lane_type a_[_Tpvec::nlanes]; \ - wasm_v128_store(a_, a.val); \ - scalartype c = a_[0]; \ - for (int i = 1; i < _Tpvec::nlanes; i++) \ - c += a_[i]; \ - return c; \ -} - -OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(v_uint8x16, unsigned) -OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(v_int8x16, int) -OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(v_uint16x8, unsigned) -OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(v_int16x8, int) - - -#define OPENCV_HAL_IMPL_WASM_REDUCE_OP_2_SUM(_Tpvec, scalartype, regtype, suffix, esuffix) \ -inline scalartype v_reduce_sum(const _Tpvec& a) \ -{ \ - regtype val = a.val; \ - val = wasm_##suffix##_add(val, wasm_i8x16_shuffle(val, val, 8,9,10,11,12,13,14,15,0,1,2,3,4,5,6,7)); \ - return (scalartype)wasm_##esuffix##_extract_lane(val, 0); \ -} -OPENCV_HAL_IMPL_WASM_REDUCE_OP_2_SUM(v_uint64x2, uint64, v128_t, i64x2, i64x2) -OPENCV_HAL_IMPL_WASM_REDUCE_OP_2_SUM(v_int64x2, int64, v128_t, i64x2, i64x2) -OPENCV_HAL_IMPL_WASM_REDUCE_OP_2_SUM(v_float64x2, double, v128_t, f64x2,f64x2) - -inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, - const v_float32x4& c, const v_float32x4& d) -{ - v128_t ac = wasm_f32x4_add(wasm_unpacklo_i32x4(a.val, c.val), wasm_unpackhi_i32x4(a.val, c.val)); - v128_t bd = wasm_f32x4_add(wasm_unpacklo_i32x4(b.val, d.val), wasm_unpackhi_i32x4(b.val, d.val)); - return v_float32x4(wasm_f32x4_add(wasm_unpacklo_i32x4(ac, bd), wasm_unpackhi_i32x4(ac, bd))); -} - -#define OPENCV_HAL_IMPL_WASM_REDUCE_OP(_Tpvec, scalartype, func, scalar_func) \ -inline scalartype v_reduce_##func(const _Tpvec& a) \ -{ \ - scalartype buf[_Tpvec::nlanes]; \ - v_store(buf, a); \ - scalartype tmp = buf[0]; \ - for (int i=1; i<_Tpvec::nlanes; ++i) { \ - tmp = scalar_func(tmp, buf[i]); \ - } \ - return tmp; \ -} - -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_uint8x16, uchar, max, std::max) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_uint8x16, uchar, min, std::min) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_int8x16, schar, max, std::max) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_int8x16, schar, min, std::min) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_uint16x8, ushort, max, std::max) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_uint16x8, ushort, min, std::min) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_int16x8, short, max, std::max) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_int16x8, short, min, std::min) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_uint32x4, unsigned, max, std::max) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_uint32x4, unsigned, min, std::min) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_int32x4, int, max, std::max) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_int32x4, int, min, std::min) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_float32x4, float, max, std::max) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_float32x4, float, min, std::min) - -inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b) -{ - v_uint16x8 l16, h16; - v_uint32x4 l16_l32, l16_h32, h16_l32, h16_h32; - v_expand(v_absdiff(a, b), l16, h16); - v_expand(l16, l16_l32, l16_h32); - v_expand(h16, h16_l32, h16_h32); - return v_reduce_sum(v_add(v_add(l16_l32, l16_h32), v_add(h16_l32, h16_h32))); -} -inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b) -{ - v_uint16x8 l16, h16; - v_uint32x4 l16_l32, l16_h32, h16_l32, h16_h32; - v_expand(v_absdiff(a, b), l16, h16); - v_expand(l16, l16_l32, l16_h32); - v_expand(h16, h16_l32, h16_h32); - return v_reduce_sum(v_add(v_add(l16_l32, l16_h32), v_add(h16_l32, h16_h32))); -} -inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b) -{ - v_uint32x4 l, h; - v_expand(v_absdiff(a, b), l, h); - return v_reduce_sum(v_add(l, h)); -} -inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b) -{ - v_uint32x4 l, h; - v_expand(v_absdiff(a, b), l, h); - return v_reduce_sum(v_add(l, h)); -} -inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b) -{ - return v_reduce_sum(v_absdiff(a, b)); -} -inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b) -{ - return v_reduce_sum(v_absdiff(a, b)); -} -inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) -{ - return v_reduce_sum(v_absdiff(a, b)); -} - -inline v_uint8x16 v_popcount(const v_uint8x16& a) -{ - v128_t m1 = wasm_i32x4_splat(0x55555555); - v128_t m2 = wasm_i32x4_splat(0x33333333); - v128_t m4 = wasm_i32x4_splat(0x0f0f0f0f); - v128_t p = a.val; - p = wasm_i32x4_add(wasm_v128_and(wasm_u32x4_shr(p, 1), m1), wasm_v128_and(p, m1)); - p = wasm_i32x4_add(wasm_v128_and(wasm_u32x4_shr(p, 2), m2), wasm_v128_and(p, m2)); - p = wasm_i32x4_add(wasm_v128_and(wasm_u32x4_shr(p, 4), m4), wasm_v128_and(p, m4)); - return v_uint8x16(p); -} -inline v_uint16x8 v_popcount(const v_uint16x8& a) -{ - v_uint8x16 p = v_popcount(v_reinterpret_as_u8(a)); - p = v_add(p, v_rotate_right<1>(p)); - return v_and(v_reinterpret_as_u16(p), v_setall_u16(0x00ff)); -} -inline v_uint32x4 v_popcount(const v_uint32x4& a) -{ - v_uint8x16 p = v_popcount(v_reinterpret_as_u8(a)); - p = v_add(p, v_rotate_right<1>(p)); - p = v_add(p, v_rotate_right<2>(p)); - return v_and(v_reinterpret_as_u32(p), v_setall_u32(0x000000ff)); -} -inline v_uint64x2 v_popcount(const v_uint64x2& a) -{ - uint64 a_[2], b_[2] = { 0 }; - wasm_v128_store(a_, a.val); - for (int i = 0; i < 16; i++) - b_[i / 8] += popCountTable[((uint8_t*)a_)[i]]; - return v_uint64x2(wasm_v128_load(b_)); -} -inline v_uint8x16 v_popcount(const v_int8x16& a) -{ return v_popcount(v_reinterpret_as_u8(a)); } -inline v_uint16x8 v_popcount(const v_int16x8& a) -{ return v_popcount(v_reinterpret_as_u16(a)); } -inline v_uint32x4 v_popcount(const v_int32x4& a) -{ return v_popcount(v_reinterpret_as_u32(a)); } -inline v_uint64x2 v_popcount(const v_int64x2& a) -{ return v_popcount(v_reinterpret_as_u64(a)); } - -#define OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(_Tpvec, suffix, scalarType) \ -inline int v_signmask(const _Tpvec& a) \ -{ \ - _Tpvec::lane_type a_[_Tpvec::nlanes]; \ - wasm_v128_store(a_, a.val); \ - int mask = 0; \ - for (int i = 0; i < _Tpvec::nlanes; i++) \ - mask |= (reinterpret_int(a_[i]) < 0) << i; \ - return mask; \ -} \ -inline bool v_check_all(const _Tpvec& a) \ -{ return wasm_i8x16_all_true(wasm_##suffix##_lt(a.val, wasm_##suffix##_splat(0))); } \ -inline bool v_check_any(const _Tpvec& a) \ -{ return wasm_i8x16_any_true(wasm_##suffix##_lt(a.val, wasm_##suffix##_splat(0)));; } - -OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_uint8x16, i8x16, schar) -OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_int8x16, i8x16, schar) -OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_uint16x8, i16x8, short) -OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_int16x8, i16x8, short) -OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_uint32x4, i32x4, int) -OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_int32x4, i32x4, int) -OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_float32x4, i32x4, float) -OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_float64x2, f64x2, double) - -#define OPENCV_HAL_IMPL_WASM_CHECK_ALL_ANY(_Tpvec, suffix, esuffix) \ -inline bool v_check_all(const _Tpvec& a) \ -{ \ - v128_t masked = v_reinterpret_as_##esuffix(a).val; \ - masked = wasm_i32x4_replace_lane(masked, 0, 0xffffffff); \ - masked = wasm_i32x4_replace_lane(masked, 2, 0xffffffff); \ - return wasm_i8x16_all_true(wasm_##suffix##_lt(masked, wasm_##suffix##_splat(0))); \ -} \ -inline bool v_check_any(const _Tpvec& a) \ -{ \ - v128_t masked = v_reinterpret_as_##esuffix(a).val; \ - masked = wasm_i32x4_replace_lane(masked, 0, 0x0); \ - masked = wasm_i32x4_replace_lane(masked, 2, 0x0); \ - return wasm_i8x16_any_true(wasm_##suffix##_lt(masked, wasm_##suffix##_splat(0))); \ -} \ - -OPENCV_HAL_IMPL_WASM_CHECK_ALL_ANY(v_int64x2, i32x4, s32) -OPENCV_HAL_IMPL_WASM_CHECK_ALL_ANY(v_uint64x2, i32x4, u32) - - -inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } -inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } -inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } -inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } -inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } -inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } -inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } - -#define OPENCV_HAL_IMPL_WASM_SELECT(_Tpvec) \ -inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(wasm_v128_bitselect(a.val, b.val, mask.val)); \ -} - -OPENCV_HAL_IMPL_WASM_SELECT(v_uint8x16) -OPENCV_HAL_IMPL_WASM_SELECT(v_int8x16) -OPENCV_HAL_IMPL_WASM_SELECT(v_uint16x8) -OPENCV_HAL_IMPL_WASM_SELECT(v_int16x8) -OPENCV_HAL_IMPL_WASM_SELECT(v_uint32x4) -OPENCV_HAL_IMPL_WASM_SELECT(v_int32x4) -OPENCV_HAL_IMPL_WASM_SELECT(v_uint64x2) -OPENCV_HAL_IMPL_WASM_SELECT(v_int64x2) -OPENCV_HAL_IMPL_WASM_SELECT(v_float32x4) -OPENCV_HAL_IMPL_WASM_SELECT(v_float64x2) - -#define OPENCV_HAL_IMPL_WASM_EXPAND(_Tpvec, _Tpwvec, _Tp, intrin) \ -inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ -{ \ - b0.val = intrin(a.val); \ - b1.val = __CV_CAT(intrin, _high)(a.val); \ -} \ -inline _Tpwvec v_expand_low(const _Tpvec& a) \ -{ return _Tpwvec(intrin(a.val)); } \ -inline _Tpwvec v_expand_high(const _Tpvec& a) \ -{ return _Tpwvec(__CV_CAT(intrin, _high)(a.val)); } \ -inline _Tpwvec v_load_expand(const _Tp* ptr) \ -{ \ - v128_t a = wasm_v128_load(ptr); \ - return _Tpwvec(intrin(a)); \ -} - -OPENCV_HAL_IMPL_WASM_EXPAND(v_uint8x16, v_uint16x8, uchar, v128_cvtu8x16_i16x8) -OPENCV_HAL_IMPL_WASM_EXPAND(v_int8x16, v_int16x8, schar, v128_cvti8x16_i16x8) -OPENCV_HAL_IMPL_WASM_EXPAND(v_uint16x8, v_uint32x4, ushort, v128_cvtu16x8_i32x4) -OPENCV_HAL_IMPL_WASM_EXPAND(v_int16x8, v_int32x4, short, v128_cvti16x8_i32x4) -OPENCV_HAL_IMPL_WASM_EXPAND(v_uint32x4, v_uint64x2, unsigned, v128_cvtu32x4_i64x2) -OPENCV_HAL_IMPL_WASM_EXPAND(v_int32x4, v_int64x2, int, v128_cvti32x4_i64x2) - -#define OPENCV_HAL_IMPL_WASM_EXPAND_Q(_Tpvec, _Tp, intrin) \ -inline _Tpvec v_load_expand_q(const _Tp* ptr) \ -{ \ - v128_t a = wasm_v128_load(ptr); \ - return _Tpvec(intrin(a)); \ -} - -OPENCV_HAL_IMPL_WASM_EXPAND_Q(v_uint32x4, uchar, v128_cvtu8x16_i32x4) -OPENCV_HAL_IMPL_WASM_EXPAND_Q(v_int32x4, schar, v128_cvti8x16_i32x4) - -#define OPENCV_HAL_IMPL_WASM_UNPACKS(_Tpvec, suffix) \ -inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) \ -{ \ - b0.val = wasm_unpacklo_##suffix(a0.val, a1.val); \ - b1.val = wasm_unpackhi_##suffix(a0.val, a1.val); \ -} \ -inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(wasm_unpacklo_i64x2(a.val, b.val)); \ -} \ -inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(wasm_unpackhi_i64x2(a.val, b.val)); \ -} \ -inline void v_recombine(const _Tpvec& a, const _Tpvec& b, _Tpvec& c, _Tpvec& d) \ -{ \ - c.val = wasm_unpacklo_i64x2(a.val, b.val); \ - d.val = wasm_unpackhi_i64x2(a.val, b.val); \ -} - -OPENCV_HAL_IMPL_WASM_UNPACKS(v_uint8x16, i8x16) -OPENCV_HAL_IMPL_WASM_UNPACKS(v_int8x16, i8x16) -OPENCV_HAL_IMPL_WASM_UNPACKS(v_uint16x8, i16x8) -OPENCV_HAL_IMPL_WASM_UNPACKS(v_int16x8, i16x8) -OPENCV_HAL_IMPL_WASM_UNPACKS(v_uint32x4, i32x4) -OPENCV_HAL_IMPL_WASM_UNPACKS(v_int32x4, i32x4) -OPENCV_HAL_IMPL_WASM_UNPACKS(v_float32x4, i32x4) -OPENCV_HAL_IMPL_WASM_UNPACKS(v_float64x2, i64x2) - -template -inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) -{ - return v_rotate_right(a, b); -} - -inline v_int32x4 v_round(const v_float32x4& a) -{ - v128_t h = wasm_f32x4_splat(0.5); - return v_int32x4(wasm_i32x4_trunc_saturate_f32x4(wasm_f32x4_add(a.val, h))); -} - -inline v_int32x4 v_floor(const v_float32x4& a) -{ - v128_t a1 = wasm_i32x4_trunc_saturate_f32x4(a.val); - v128_t mask = wasm_f32x4_lt(a.val, wasm_f32x4_convert_i32x4(a1)); - return v_int32x4(wasm_i32x4_add(a1, mask)); -} - -inline v_int32x4 v_ceil(const v_float32x4& a) -{ - v128_t a1 = wasm_i32x4_trunc_saturate_f32x4(a.val); - v128_t mask = wasm_f32x4_gt(a.val, wasm_f32x4_convert_i32x4(a1)); - return v_int32x4(wasm_i32x4_sub(a1, mask)); -} - -inline v_int32x4 v_trunc(const v_float32x4& a) -{ return v_int32x4(wasm_i32x4_trunc_saturate_f32x4(a.val)); } - -#define OPENCV_HAL_IMPL_WASM_MATH_FUNC(func, cfunc) \ -inline v_int32x4 func(const v_float64x2& a) \ -{ \ - double a_[2]; \ - wasm_v128_store(a_, a.val); \ - int c_[4]; \ - c_[0] = cfunc(a_[0]); \ - c_[1] = cfunc(a_[1]); \ - c_[2] = 0; \ - c_[3] = 0; \ - return v_int32x4(wasm_v128_load(c_)); \ -} - -OPENCV_HAL_IMPL_WASM_MATH_FUNC(v_round, cvRound) -OPENCV_HAL_IMPL_WASM_MATH_FUNC(v_floor, cvFloor) -OPENCV_HAL_IMPL_WASM_MATH_FUNC(v_ceil, cvCeil) -OPENCV_HAL_IMPL_WASM_MATH_FUNC(v_trunc, int) - -inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) -{ - double a_[2], b_[2]; - wasm_v128_store(a_, a.val); - wasm_v128_store(b_, b.val); - int c_[4]; - c_[0] = cvRound(a_[0]); - c_[1] = cvRound(a_[1]); - c_[2] = cvRound(b_[0]); - c_[3] = cvRound(b_[1]); - return v_int32x4(wasm_v128_load(c_)); -} - -#define OPENCV_HAL_IMPL_WASM_TRANSPOSE4x4(_Tpvec, suffix) \ -inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ - const _Tpvec& a2, const _Tpvec& a3, \ - _Tpvec& b0, _Tpvec& b1, \ - _Tpvec& b2, _Tpvec& b3) \ -{ \ - v128_t t0 = wasm_unpacklo_##suffix(a0.val, a1.val); \ - v128_t t1 = wasm_unpacklo_##suffix(a2.val, a3.val); \ - v128_t t2 = wasm_unpackhi_##suffix(a0.val, a1.val); \ - v128_t t3 = wasm_unpackhi_##suffix(a2.val, a3.val); \ -\ - b0.val = wasm_unpacklo_i64x2(t0, t1); \ - b1.val = wasm_unpackhi_i64x2(t0, t1); \ - b2.val = wasm_unpacklo_i64x2(t2, t3); \ - b3.val = wasm_unpackhi_i64x2(t2, t3); \ -} - -OPENCV_HAL_IMPL_WASM_TRANSPOSE4x4(v_uint32x4, i32x4) -OPENCV_HAL_IMPL_WASM_TRANSPOSE4x4(v_int32x4, i32x4) -OPENCV_HAL_IMPL_WASM_TRANSPOSE4x4(v_float32x4, i32x4) - -// load deinterleave -inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b) -{ - v128_t t00 = wasm_v128_load(ptr); - v128_t t01 = wasm_v128_load(ptr + 16); - - a.val = wasm_i8x16_shuffle(t00, t01, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30); - b.val = wasm_i8x16_shuffle(t00, t01, 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31); -} - -inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c) -{ - v128_t t00 = wasm_v128_load(ptr); - v128_t t01 = wasm_v128_load(ptr + 16); - v128_t t02 = wasm_v128_load(ptr + 32); - - v128_t t10 = wasm_i8x16_shuffle(t00, t01, 0,3,6,9,12,15,18,21,24,27,30,1,2,4,5,7); - v128_t t11 = wasm_i8x16_shuffle(t00, t01, 1,4,7,10,13,16,19,22,25,28,31,0,2,3,5,6); - v128_t t12 = wasm_i8x16_shuffle(t00, t01, 2,5,8,11,14,17,20,23,26,29,0,1,3,4,6,7); - - a.val = wasm_i8x16_shuffle(t10, t02, 0,1,2,3,4,5,6,7,8,9,10,17,20,23,26,29); - b.val = wasm_i8x16_shuffle(t11, t02, 0,1,2,3,4,5,6,7,8,9,10,18,21,24,27,30); - c.val = wasm_i8x16_shuffle(t12, t02, 0,1,2,3,4,5,6,7,8,9,16,19,22,25,28,31); -} - -inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c, v_uint8x16& d) -{ - v128_t u0 = wasm_v128_load(ptr); // a0 b0 c0 d0 a1 b1 c1 d1 ... - v128_t u1 = wasm_v128_load(ptr + 16); // a4 b4 c4 d4 ... - v128_t u2 = wasm_v128_load(ptr + 32); // a8 b8 c8 d8 ... - v128_t u3 = wasm_v128_load(ptr + 48); // a12 b12 c12 d12 ... - - v128_t v0 = wasm_i8x16_shuffle(u0, u1, 0,4,8,12,16,20,24,28,1,5,9,13,17,21,25,29); - v128_t v1 = wasm_i8x16_shuffle(u2, u3, 0,4,8,12,16,20,24,28,1,5,9,13,17,21,25,29); - v128_t v2 = wasm_i8x16_shuffle(u0, u1, 2,6,10,14,18,22,26,30,3,7,11,15,19,23,27,31); - v128_t v3 = wasm_i8x16_shuffle(u2, u3, 2,6,10,14,18,22,26,30,3,7,11,15,19,23,27,31); - - a.val = wasm_i8x16_shuffle(v0, v1, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); - b.val = wasm_i8x16_shuffle(v0, v1, 8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31); - c.val = wasm_i8x16_shuffle(v2, v3, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); - d.val = wasm_i8x16_shuffle(v2, v3, 8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31); -} - -inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b) -{ - v128_t v0 = wasm_v128_load(ptr); // a0 b0 a1 b1 a2 b2 a3 b3 - v128_t v1 = wasm_v128_load(ptr + 8); // a4 b4 a5 b5 a6 b6 a7 b7 - - a.val = wasm_i8x16_shuffle(v0, v1, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29); // a0 a1 a2 a3 a4 a5 a6 a7 - b.val = wasm_i8x16_shuffle(v0, v1, 2,3,6,7,10,11,14,15,18,19,22,23,26,27,30,31); // b0 b1 ab b3 b4 b5 b6 b7 -} - -inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c) -{ - v128_t t00 = wasm_v128_load(ptr); // a0 b0 c0 a1 b1 c1 a2 b2 - v128_t t01 = wasm_v128_load(ptr + 8); // c2 a3 b3 c3 a4 b4 c4 a5 - v128_t t02 = wasm_v128_load(ptr + 16); // b5 c5 a6 b6 c6 a7 b7 c7 - - v128_t t10 = wasm_i8x16_shuffle(t00, t01, 0,1,6,7,12,13,18,19,24,25,30,31,2,3,4,5); - v128_t t11 = wasm_i8x16_shuffle(t00, t01, 2,3,8,9,14,15,20,21,26,27,0,1,4,5,6,7); - v128_t t12 = wasm_i8x16_shuffle(t00, t01, 4,5,10,11,16,17,22,23,28,29,0,1,2,3,6,7); - - a.val = wasm_i8x16_shuffle(t10, t02, 0,1,2,3,4,5,6,7,8,9,10,11,20,21,26,27); - b.val = wasm_i8x16_shuffle(t11, t02, 0,1,2,3,4,5,6,7,8,9,16,17,22,23,28,29); - c.val = wasm_i8x16_shuffle(t12, t02, 0,1,2,3,4,5,6,7,8,9,18,19,24,25,30,31); -} - -inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c, v_uint16x8& d) -{ - v128_t u0 = wasm_v128_load(ptr); // a0 b0 c0 d0 a1 b1 c1 d1 - v128_t u1 = wasm_v128_load(ptr + 8); // a2 b2 c2 d2 ... - v128_t u2 = wasm_v128_load(ptr + 16); // a4 b4 c4 d4 ... - v128_t u3 = wasm_v128_load(ptr + 24); // a6 b6 c6 d6 ... - - v128_t v0 = wasm_i8x16_shuffle(u0, u1, 0,1,8,9,16,17,24,25,2,3,10,11,18,19,26,27); // a0 a1 a2 a3 b0 b1 b2 b3 - v128_t v1 = wasm_i8x16_shuffle(u2, u3, 0,1,8,9,16,17,24,25,2,3,10,11,18,19,26,27); // a4 a5 a6 a7 b4 b5 b6 b7 - v128_t v2 = wasm_i8x16_shuffle(u0, u1, 4,5,12,13,20,21,28,29,6,7,14,15,22,23,30,31); // c0 c1 c2 c3 d0 d1 d2 d3 - v128_t v3 = wasm_i8x16_shuffle(u2, u3, 4,5,12,13,20,21,28,29,6,7,14,15,22,23,30,31); // c4 c5 c6 c7 d4 d5 d6 d7 - - a.val = wasm_i8x16_shuffle(v0, v1, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); - b.val = wasm_i8x16_shuffle(v0, v1, 8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31); - c.val = wasm_i8x16_shuffle(v2, v3, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); - d.val = wasm_i8x16_shuffle(v2, v3, 8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31); -} - -inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b) -{ - v128_t v0 = wasm_v128_load(ptr); // a0 b0 a1 b1 - v128_t v1 = wasm_v128_load(ptr + 4); // a2 b2 a3 b3 - - a.val = wasm_i8x16_shuffle(v0, v1, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27); // a0 a1 a2 a3 - b.val = wasm_i8x16_shuffle(v0, v1, 4,5,6,7,12,13,14,15,20,21,22,23,28,29,30,31); // b0 b1 b2 b3 -} - -inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c) -{ - v128_t t00 = wasm_v128_load(ptr); // a0 b0 c0 a1 - v128_t t01 = wasm_v128_load(ptr + 4); // b2 c2 a3 b3 - v128_t t02 = wasm_v128_load(ptr + 8); // c3 a4 b4 c4 - - v128_t t10 = wasm_i8x16_shuffle(t00, t01, 0,1,2,3,12,13,14,15,24,25,26,27,4,5,6,7); - v128_t t11 = wasm_i8x16_shuffle(t00, t01, 4,5,6,7,16,17,18,19,28,29,30,31,0,1,2,3); - v128_t t12 = wasm_i8x16_shuffle(t00, t01, 8,9,10,11,20,21,22,23,0,1,2,3,4,5,6,7); - - a.val = wasm_i8x16_shuffle(t10, t02, 0,1,2,3,4,5,6,7,8,9,10,11,20,21,22,23); - b.val = wasm_i8x16_shuffle(t11, t02, 0,1,2,3,4,5,6,7,8,9,10,11,24,25,26,27); - c.val = wasm_i8x16_shuffle(t12, t02, 0,1,2,3,4,5,6,7,16,17,18,19,28,29,30,31); -} - -inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c, v_uint32x4& d) -{ - v_uint32x4 s0(wasm_v128_load(ptr)); // a0 b0 c0 d0 - v_uint32x4 s1(wasm_v128_load(ptr + 4)); // a1 b1 c1 d1 - v_uint32x4 s2(wasm_v128_load(ptr + 8)); // a2 b2 c2 d2 - v_uint32x4 s3(wasm_v128_load(ptr + 12)); // a3 b3 c3 d3 - - v_transpose4x4(s0, s1, s2, s3, a, b, c, d); -} - -inline void v_load_deinterleave(const float* ptr, v_float32x4& a, v_float32x4& b) -{ - v128_t v0 = wasm_v128_load(ptr); // a0 b0 a1 b1 - v128_t v1 = wasm_v128_load((ptr + 4)); // a2 b2 a3 b3 - - a.val = wasm_i8x16_shuffle(v0, v1, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27); // a0 a1 a2 a3 - b.val = wasm_i8x16_shuffle(v0, v1, 4,5,6,7,12,13,14,15,20,21,22,23,28,29,30,31); // b0 b1 b2 b3 -} - -inline void v_load_deinterleave(const float* ptr, v_float32x4& a, v_float32x4& b, v_float32x4& c) -{ - v128_t t00 = wasm_v128_load(ptr); // a0 b0 c0 a1 - v128_t t01 = wasm_v128_load(ptr + 4); // b2 c2 a3 b3 - v128_t t02 = wasm_v128_load(ptr + 8); // c3 a4 b4 c4 - - v128_t t10 = wasm_i8x16_shuffle(t00, t01, 0,1,2,3,12,13,14,15,24,25,26,27,4,5,6,7); - v128_t t11 = wasm_i8x16_shuffle(t00, t01, 4,5,6,7,16,17,18,19,28,29,30,31,0,1,2,3); - v128_t t12 = wasm_i8x16_shuffle(t00, t01, 8,9,10,11,20,21,22,23,0,1,2,3,4,5,6,7); - - a.val = wasm_i8x16_shuffle(t10, t02, 0,1,2,3,4,5,6,7,8,9,10,11,20,21,22,23); - b.val = wasm_i8x16_shuffle(t11, t02, 0,1,2,3,4,5,6,7,8,9,10,11,24,25,26,27); - c.val = wasm_i8x16_shuffle(t12, t02, 0,1,2,3,4,5,6,7,16,17,18,19,28,29,30,31); -} - -inline void v_load_deinterleave(const float* ptr, v_float32x4& a, v_float32x4& b, v_float32x4& c, v_float32x4& d) -{ - v_float32x4 s0(wasm_v128_load(ptr)); // a0 b0 c0 d0 - v_float32x4 s1(wasm_v128_load(ptr + 4)); // a1 b1 c1 d1 - v_float32x4 s2(wasm_v128_load(ptr + 8)); // a2 b2 c2 d2 - v_float32x4 s3(wasm_v128_load(ptr + 12)); // a3 b3 c3 d3 - - v_transpose4x4(s0, s1, s2, s3, a, b, c, d); -} - -inline void v_load_deinterleave(const uint64 *ptr, v_uint64x2& a, v_uint64x2& b) -{ - v128_t t0 = wasm_v128_load(ptr); // a0 b0 - v128_t t1 = wasm_v128_load(ptr + 2); // a1 b1 - - a.val = wasm_unpacklo_i64x2(t0, t1); - b.val = wasm_unpackhi_i64x2(t0, t1); -} - -inline void v_load_deinterleave(const uint64 *ptr, v_uint64x2& a, v_uint64x2& b, v_uint64x2& c) -{ - v128_t t0 = wasm_v128_load(ptr); // a0, b0 - v128_t t1 = wasm_v128_load(ptr + 2); // c0, a1 - v128_t t2 = wasm_v128_load(ptr + 4); // b1, c1 - - a.val = wasm_i8x16_shuffle(t0, t1, 0,1,2,3,4,5,6,7,24,25,26,27,28,29,30,31); - b.val = wasm_i8x16_shuffle(t0, t2, 8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23); - c.val = wasm_i8x16_shuffle(t1, t2, 0,1,2,3,4,5,6,7,24,25,26,27,28,29,30,31); -} - -inline void v_load_deinterleave(const uint64 *ptr, v_uint64x2& a, - v_uint64x2& b, v_uint64x2& c, v_uint64x2& d) -{ - v128_t t0 = wasm_v128_load(ptr); // a0 b0 - v128_t t1 = wasm_v128_load(ptr + 2); // c0 d0 - v128_t t2 = wasm_v128_load(ptr + 4); // a1 b1 - v128_t t3 = wasm_v128_load(ptr + 6); // c1 d1 - - a.val = wasm_unpacklo_i64x2(t0, t2); - b.val = wasm_unpackhi_i64x2(t0, t2); - c.val = wasm_unpacklo_i64x2(t1, t3); - d.val = wasm_unpackhi_i64x2(t1, t3); -} - -// store interleave - -inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v128_t v0 = wasm_unpacklo_i8x16(a.val, b.val); - v128_t v1 = wasm_unpackhi_i8x16(a.val, b.val); - - wasm_v128_store(ptr, v0); - wasm_v128_store(ptr + 16, v1); -} - -inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, - const v_uint8x16& c, hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v128_t t00 = wasm_i8x16_shuffle(a.val, b.val, 0,16,0,1,17,0,2,18,0,3,19,0,4,20,0,5); - v128_t t01 = wasm_i8x16_shuffle(a.val, b.val, 21,0,6,22,0,7,23,0,8,24,0,9,25,0,10,26); - v128_t t02 = wasm_i8x16_shuffle(a.val, b.val, 0,11,27,0,12,28,0,13,29,0,14,30,0,15,31,0); - - v128_t t10 = wasm_i8x16_shuffle(t00, c.val, 0,1,16,3,4,17,6,7,18,9,10,19,12,13,20,15); - v128_t t11 = wasm_i8x16_shuffle(t01, c.val, 0,21,2,3,22,5,6,23,8,9,24,11,12,25,14,15); - v128_t t12 = wasm_i8x16_shuffle(t02, c.val, 26,1,2,27,4,5,28,7,8,29,10,11,30,13,14,31); - - wasm_v128_store(ptr, t10); - wasm_v128_store(ptr + 16, t11); - wasm_v128_store(ptr + 32, t12); -} - -inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, - const v_uint8x16& c, const v_uint8x16& d, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - // a0 a1 a2 a3 .... - // b0 b1 b2 b3 .... - // c0 c1 c2 c3 .... - // d0 d1 d2 d3 .... - v128_t u0 = wasm_unpacklo_i8x16(a.val, c.val); // a0 c0 a1 c1 ... - v128_t u1 = wasm_unpackhi_i8x16(a.val, c.val); // a8 c8 a9 c9 ... - v128_t u2 = wasm_unpacklo_i8x16(b.val, d.val); // b0 d0 b1 d1 ... - v128_t u3 = wasm_unpackhi_i8x16(b.val, d.val); // b8 d8 b9 d9 ... - - v128_t v0 = wasm_unpacklo_i8x16(u0, u2); // a0 b0 c0 d0 ... - v128_t v1 = wasm_unpackhi_i8x16(u0, u2); // a4 b4 c4 d4 ... - v128_t v2 = wasm_unpacklo_i8x16(u1, u3); // a8 b8 c8 d8 ... - v128_t v3 = wasm_unpackhi_i8x16(u1, u3); // a12 b12 c12 d12 ... - - wasm_v128_store(ptr, v0); - wasm_v128_store(ptr + 16, v1); - wasm_v128_store(ptr + 32, v2); - wasm_v128_store(ptr + 48, v3); -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v128_t v0 = wasm_unpacklo_i16x8(a.val, b.val); - v128_t v1 = wasm_unpackhi_i16x8(a.val, b.val); - - wasm_v128_store(ptr, v0); - wasm_v128_store(ptr + 8, v1); -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, - const v_uint16x8& b, const v_uint16x8& c, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v128_t t00 = wasm_i8x16_shuffle(a.val, b.val, 0,1,16,17,0,0,2,3,18,19,0,0,4,5,20,21); - v128_t t01 = wasm_i8x16_shuffle(a.val, b.val, 0,0,6,7,22,23,0,0,8,9,24,25,0,0,10,11); - v128_t t02 = wasm_i8x16_shuffle(a.val, b.val, 26,27,0,0,12,13,28,29,0,0,14,15,30,31,0,0); - - v128_t t10 = wasm_i8x16_shuffle(t00, c.val, 0,1,2,3,16,17,6,7,8,9,18,19,12,13,14,15); - v128_t t11 = wasm_i8x16_shuffle(t01, c.val, 20,21,2,3,4,5,22,23,8,9,10,11,24,25,14,15); - v128_t t12 = wasm_i8x16_shuffle(t02, c.val, 0,1,26,27,4,5,6,7,28,29,10,11,12,13,30,31); - - wasm_v128_store(ptr, t10); - wasm_v128_store(ptr + 8, t11); - wasm_v128_store(ptr + 16, t12); -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, - const v_uint16x8& c, const v_uint16x8& d, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - // a0 a1 a2 a3 .... - // b0 b1 b2 b3 .... - // c0 c1 c2 c3 .... - // d0 d1 d2 d3 .... - v128_t u0 = wasm_unpacklo_i16x8(a.val, c.val); // a0 c0 a1 c1 ... - v128_t u1 = wasm_unpackhi_i16x8(a.val, c.val); // a4 c4 a5 c5 ... - v128_t u2 = wasm_unpacklo_i16x8(b.val, d.val); // b0 d0 b1 d1 ... - v128_t u3 = wasm_unpackhi_i16x8(b.val, d.val); // b4 d4 b5 d5 ... - - v128_t v0 = wasm_unpacklo_i16x8(u0, u2); // a0 b0 c0 d0 ... - v128_t v1 = wasm_unpackhi_i16x8(u0, u2); // a2 b2 c2 d2 ... - v128_t v2 = wasm_unpacklo_i16x8(u1, u3); // a4 b4 c4 d4 ... - v128_t v3 = wasm_unpackhi_i16x8(u1, u3); // a6 b6 c6 d6 ... - - wasm_v128_store(ptr, v0); - wasm_v128_store(ptr + 8, v1); - wasm_v128_store(ptr + 16, v2); - wasm_v128_store(ptr + 24, v3); -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v128_t v0 = wasm_unpacklo_i32x4(a.val, b.val); - v128_t v1 = wasm_unpackhi_i32x4(a.val, b.val); - - wasm_v128_store(ptr, v0); - wasm_v128_store(ptr + 4, v1); -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, - const v_uint32x4& c, hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v128_t t00 = wasm_i8x16_shuffle(a.val, b.val, 0,1,2,3,16,17,18,19,0,0,0,0,4,5,6,7); - v128_t t01 = wasm_i8x16_shuffle(a.val, b.val, 20,21,22,23,0,0,0,0,8,9,10,11,24,25,26,27); - v128_t t02 = wasm_i8x16_shuffle(a.val, b.val, 0,0,0,0,12,13,14,15,28,29,30,31,0,0,0,0); - - v128_t t10 = wasm_i8x16_shuffle(t00, c.val, 0,1,2,3,4,5,6,7,16,17,18,19,12,13,14,15); - v128_t t11 = wasm_i8x16_shuffle(t01, c.val, 0,1,2,3,20,21,22,23,8,9,10,11,12,13,14,15); - v128_t t12 = wasm_i8x16_shuffle(t02, c.val, 24,25,26,27,4,5,6,7,8,9,10,11,28,29,30,31); - - wasm_v128_store(ptr, t10); - wasm_v128_store(ptr + 4, t11); - wasm_v128_store(ptr + 8, t12); -} - -inline void v_store_interleave(unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, - const v_uint32x4& c, const v_uint32x4& d, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v_uint32x4 v0, v1, v2, v3; - v_transpose4x4(a, b, c, d, v0, v1, v2, v3); - - wasm_v128_store(ptr, v0.val); - wasm_v128_store(ptr + 4, v1.val); - wasm_v128_store(ptr + 8, v2.val); - wasm_v128_store(ptr + 12, v3.val); -} - -// 2-channel, float only -inline void v_store_interleave(float* ptr, const v_float32x4& a, const v_float32x4& b, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v128_t v0 = wasm_unpacklo_i32x4(a.val, b.val); - v128_t v1 = wasm_unpackhi_i32x4(a.val, b.val); - - wasm_v128_store(ptr, v0); - wasm_v128_store(ptr + 4, v1); -} - -inline void v_store_interleave(float* ptr, const v_float32x4& a, const v_float32x4& b, - const v_float32x4& c, hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v128_t t00 = wasm_i8x16_shuffle(a.val, b.val, 0,1,2,3,16,17,18,19,0,0,0,0,4,5,6,7); - v128_t t01 = wasm_i8x16_shuffle(a.val, b.val, 20,21,22,23,0,0,0,0,8,9,10,11,24,25,26,27); - v128_t t02 = wasm_i8x16_shuffle(a.val, b.val, 0,0,0,0,12,13,14,15,28,29,30,31,0,0,0,0); - - v128_t t10 = wasm_i8x16_shuffle(t00, c.val, 0,1,2,3,4,5,6,7,16,17,18,19,12,13,14,15); - v128_t t11 = wasm_i8x16_shuffle(t01, c.val, 0,1,2,3,20,21,22,23,8,9,10,11,12,13,14,15); - v128_t t12 = wasm_i8x16_shuffle(t02, c.val, 24,25,26,27,4,5,6,7,8,9,10,11,28,29,30,31); - - wasm_v128_store(ptr, t10); - wasm_v128_store(ptr + 4, t11); - wasm_v128_store(ptr + 8, t12); -} - -inline void v_store_interleave(float* ptr, const v_float32x4& a, const v_float32x4& b, - const v_float32x4& c, const v_float32x4& d, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v_float32x4 v0, v1, v2, v3; - v_transpose4x4(a, b, c, d, v0, v1, v2, v3); - - wasm_v128_store(ptr, v0.val); - wasm_v128_store(ptr + 4, v1.val); - wasm_v128_store(ptr + 8, v2.val); - wasm_v128_store(ptr + 12, v3.val); -} - -inline void v_store_interleave(uint64 *ptr, const v_uint64x2& a, const v_uint64x2& b, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v128_t v0 = wasm_unpacklo_i64x2(a.val, b.val); - v128_t v1 = wasm_unpackhi_i64x2(a.val, b.val); - - wasm_v128_store(ptr, v0); - wasm_v128_store(ptr + 2, v1); -} - -inline void v_store_interleave(uint64 *ptr, const v_uint64x2& a, const v_uint64x2& b, - const v_uint64x2& c, hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v128_t v0 = wasm_i8x16_shuffle(a.val, b.val, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); - v128_t v1 = wasm_i8x16_shuffle(a.val, c.val, 16,17,18,19,20,21,22,23,8,9,10,11,12,13,14,15); - v128_t v2 = wasm_i8x16_shuffle(b.val, c.val, 8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31); - - wasm_v128_store(ptr, v0); - wasm_v128_store(ptr + 2, v1); - wasm_v128_store(ptr + 4, v2); -} - -inline void v_store_interleave(uint64 *ptr, const v_uint64x2& a, const v_uint64x2& b, - const v_uint64x2& c, const v_uint64x2& d, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v128_t v0 = wasm_unpacklo_i64x2(a.val, b.val); - v128_t v1 = wasm_unpacklo_i64x2(c.val, d.val); - v128_t v2 = wasm_unpackhi_i64x2(a.val, b.val); - v128_t v3 = wasm_unpackhi_i64x2(c.val, d.val); - - wasm_v128_store(ptr, v0); - wasm_v128_store(ptr + 2, v1); - wasm_v128_store(ptr + 4, v2); - wasm_v128_store(ptr + 6, v3); -} - -#define OPENCV_HAL_IMPL_WASM_LOADSTORE_INTERLEAVE(_Tpvec0, _Tp0, suffix0, _Tpvec1, _Tp1, suffix1) \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0 ) \ -{ \ - _Tpvec1 a1, b1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ -} \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0 ) \ -{ \ - _Tpvec1 a1, b1, c1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ - c0 = v_reinterpret_as_##suffix0(c1); \ -} \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0, _Tpvec0& d0 ) \ -{ \ - _Tpvec1 a1, b1, c1, d1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1, d1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ - c0 = v_reinterpret_as_##suffix0(c1); \ - d0 = v_reinterpret_as_##suffix0(d1); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - hal::StoreMode mode = hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, mode); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - const _Tpvec0& c0, hal::StoreMode mode = hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, c1, mode); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - const _Tpvec0& c0, const _Tpvec0& d0, \ - hal::StoreMode mode = hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ - _Tpvec1 d1 = v_reinterpret_as_##suffix1(d0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, c1, d1, mode); \ -} - -OPENCV_HAL_IMPL_WASM_LOADSTORE_INTERLEAVE(v_int8x16, schar, s8, v_uint8x16, uchar, u8) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INTERLEAVE(v_int16x8, short, s16, v_uint16x8, ushort, u16) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INTERLEAVE(v_int32x4, int, s32, v_uint32x4, unsigned, u32) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INTERLEAVE(v_int64x2, int64, s64, v_uint64x2, uint64, u64) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INTERLEAVE(v_float64x2, double, f64, v_uint64x2, uint64, u64) - -inline v_float32x4 v_cvt_f32(const v_int32x4& a) -{ - return v_float32x4(wasm_f32x4_convert_i32x4(a.val)); -} - -inline v_float32x4 v_cvt_f32(const v_float64x2& a) -{ - double a_[2]; - wasm_v128_store(a_, a.val); - float c_[4]; - c_[0] = (float)(a_[0]); - c_[1] = (float)(a_[1]); - c_[2] = 0; - c_[3] = 0; - return v_float32x4(wasm_v128_load(c_)); -} - -inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) -{ - double a_[2], b_[2]; - wasm_v128_store(a_, a.val); - wasm_v128_store(b_, b.val); - float c_[4]; - c_[0] = (float)(a_[0]); - c_[1] = (float)(a_[1]); - c_[2] = (float)(b_[0]); - c_[3] = (float)(b_[1]); - return v_float32x4(wasm_v128_load(c_)); -} - -inline v_float64x2 v_cvt_f64(const v_int32x4& a) -{ -#ifdef __wasm_unimplemented_simd128__ - v128_t p = v128_cvti32x4_i64x2(a.val); - return v_float64x2(wasm_f64x2_convert_i64x2(p)); -#else - int a_[4]; - wasm_v128_store(a_, a.val); - double c_[2]; - c_[0] = (double)(a_[0]); - c_[1] = (double)(a_[1]); - return v_float64x2(wasm_v128_load(c_)); -#endif -} - -inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) -{ -#ifdef __wasm_unimplemented_simd128__ - v128_t p = v128_cvti32x4_i64x2_high(a.val); - return v_float64x2(wasm_f64x2_convert_i64x2(p)); -#else - int a_[4]; - wasm_v128_store(a_, a.val); - double c_[2]; - c_[0] = (double)(a_[2]); - c_[1] = (double)(a_[3]); - return v_float64x2(wasm_v128_load(c_)); -#endif -} - -inline v_float64x2 v_cvt_f64(const v_float32x4& a) -{ - float a_[4]; - wasm_v128_store(a_, a.val); - double c_[2]; - c_[0] = (double)(a_[0]); - c_[1] = (double)(a_[1]); - return v_float64x2(wasm_v128_load(c_)); -} - -inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) -{ - float a_[4]; - wasm_v128_store(a_, a.val); - double c_[2]; - c_[0] = (double)(a_[2]); - c_[1] = (double)(a_[3]); - return v_float64x2(wasm_v128_load(c_)); -} - -inline v_float64x2 v_cvt_f64(const v_int64x2& a) -{ -#ifdef __wasm_unimplemented_simd128__ - return v_float64x2(wasm_f64x2_convert_i64x2(a.val)); -#else - int64 a_[2]; - wasm_v128_store(a_, a.val); - double c_[2]; - c_[0] = (double)(a_[0]); - c_[1] = (double)(a_[1]); - return v_float64x2(wasm_v128_load(c_)); -#endif -} - -////////////// Lookup table access //////////////////// - -inline v_int8x16 v_lut(const schar* tab, const int* idx) -{ - return v_int8x16(tab[idx[0]], tab[idx[1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], tab[idx[ 5]], tab[idx[ 6]], tab[idx[ 7]], - tab[idx[8]], tab[idx[9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]]); -} -inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx) -{ - return v_int8x16(tab[idx[0]], tab[idx[0]+1], tab[idx[1]], tab[idx[1]+1], tab[idx[2]], tab[idx[2]+1], tab[idx[3]], tab[idx[3]+1], - tab[idx[4]], tab[idx[4]+1], tab[idx[5]], tab[idx[5]+1], tab[idx[6]], tab[idx[6]+1], tab[idx[7]], tab[idx[7]+1]); -} -inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) -{ - return v_int8x16(tab[idx[0]], tab[idx[0]+1], tab[idx[0]+2], tab[idx[0]+3], tab[idx[1]], tab[idx[1]+1], tab[idx[1]+2], tab[idx[1]+3], - tab[idx[2]], tab[idx[2]+1], tab[idx[2]+2], tab[idx[2]+3], tab[idx[3]], tab[idx[3]+1], tab[idx[3]+2], tab[idx[3]+3]); -} -inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((const schar *)tab, idx)); } -inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((const schar *)tab, idx)); } -inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((const schar *)tab, idx)); } - -inline v_int16x8 v_lut(const short* tab, const int* idx) -{ - return v_int16x8(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], - tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]]); -} -inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) -{ - return v_int16x8(tab[idx[0]], tab[idx[0]+1], tab[idx[1]], tab[idx[1]+1], - tab[idx[2]], tab[idx[2]+1], tab[idx[3]], tab[idx[3]+1]); -} -inline v_int16x8 v_lut_quads(const short* tab, const int* idx) -{ - return v_int16x8(tab[idx[0]], tab[idx[0]+1], tab[idx[0]+2], tab[idx[0]+3], - tab[idx[1]], tab[idx[1]+1], tab[idx[1]+2], tab[idx[1]+3]); -} -inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((const short *)tab, idx)); } -inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((const short *)tab, idx)); } -inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((const short *)tab, idx)); } - -inline v_int32x4 v_lut(const int* tab, const int* idx) -{ - return v_int32x4(tab[idx[0]], tab[idx[1]], - tab[idx[2]], tab[idx[3]]); -} -inline v_int32x4 v_lut_pairs(const int* tab, const int* idx) -{ - return v_int32x4(tab[idx[0]], tab[idx[0]+1], - tab[idx[1]], tab[idx[1]+1]); -} -inline v_int32x4 v_lut_quads(const int* tab, const int* idx) -{ - return v_int32x4(wasm_v128_load(tab + idx[0])); -} -inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((const int *)tab, idx)); } -inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((const int *)tab, idx)); } -inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((const int *)tab, idx)); } - -inline v_int64x2 v_lut(const int64_t* tab, const int* idx) -{ - return v_int64x2(tab[idx[0]], tab[idx[1]]); -} -inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) -{ - return v_int64x2(wasm_v128_load(tab + idx[0])); -} -inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } -inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } - -inline v_float32x4 v_lut(const float* tab, const int* idx) -{ - return v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); -} -inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) { return v_reinterpret_as_f32(v_lut_pairs((const int *)tab, idx)); } -inline v_float32x4 v_lut_quads(const float* tab, const int* idx) { return v_reinterpret_as_f32(v_lut_quads((const int *)tab, idx)); } - -inline v_float64x2 v_lut(const double* tab, const int* idx) -{ - return v_float64x2(tab[idx[0]], tab[idx[1]]); -} -inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) -{ - return v_float64x2(wasm_v128_load(tab + idx[0])); -} - -inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) -{ - return v_int32x4(tab[wasm_i32x4_extract_lane(idxvec.val, 0)], - tab[wasm_i32x4_extract_lane(idxvec.val, 1)], - tab[wasm_i32x4_extract_lane(idxvec.val, 2)], - tab[wasm_i32x4_extract_lane(idxvec.val, 3)]); -} - -inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) -{ - return v_reinterpret_as_u32(v_lut((const int *)tab, idxvec)); -} - -inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) -{ - return v_float32x4(tab[wasm_i32x4_extract_lane(idxvec.val, 0)], - tab[wasm_i32x4_extract_lane(idxvec.val, 1)], - tab[wasm_i32x4_extract_lane(idxvec.val, 2)], - tab[wasm_i32x4_extract_lane(idxvec.val, 3)]); -} - -inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) -{ - return v_float64x2(tab[wasm_i32x4_extract_lane(idxvec.val, 0)], - tab[wasm_i32x4_extract_lane(idxvec.val, 1)]); -} - -// loads pairs from the table and deinterleaves them, e.g. returns: -// x = (tab[idxvec[0], tab[idxvec[1]], tab[idxvec[2]], tab[idxvec[3]]), -// y = (tab[idxvec[0]+1], tab[idxvec[1]+1], tab[idxvec[2]+1], tab[idxvec[3]+1]) -// note that the indices are float's indices, not the float-pair indices. -// in theory, this function can be used to implement bilinear interpolation, -// when idxvec are the offsets within the image. -inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) -{ - x = v_float32x4(tab[wasm_i32x4_extract_lane(idxvec.val, 0)], - tab[wasm_i32x4_extract_lane(idxvec.val, 1)], - tab[wasm_i32x4_extract_lane(idxvec.val, 2)], - tab[wasm_i32x4_extract_lane(idxvec.val, 3)]); - y = v_float32x4(tab[wasm_i32x4_extract_lane(idxvec.val, 0)+1], - tab[wasm_i32x4_extract_lane(idxvec.val, 1)+1], - tab[wasm_i32x4_extract_lane(idxvec.val, 2)+1], - tab[wasm_i32x4_extract_lane(idxvec.val, 3)+1]); -} - -inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) -{ - v128_t xy0 = wasm_v128_load(tab + wasm_i32x4_extract_lane(idxvec.val, 0)); - v128_t xy1 = wasm_v128_load(tab + wasm_i32x4_extract_lane(idxvec.val, 1)); - x.val = wasm_unpacklo_i64x2(xy0, xy1); - y.val = wasm_unpacklo_i64x2(xy0, xy1); -} - -inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) -{ - return v_int8x16(wasm_i8x16_shuffle(vec.val, vec.val, 0,2,1,3,4,6,5,7,8,10,9,11,12,14,13,15)); -} -inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } -inline v_int8x16 v_interleave_quads(const v_int8x16& vec) -{ - return v_int8x16(wasm_i8x16_shuffle(vec.val, vec.val, 0,4,1,5,2,6,3,7,8,12,9,13,10,14,11,15)); -} -inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) -{ - return v_int16x8(wasm_i8x16_shuffle(vec.val, vec.val, 0,1,4,5,2,3,6,7,8,9,12,13,10,11,14,15)); -} -inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } -inline v_int16x8 v_interleave_quads(const v_int16x8& vec) -{ - return v_int16x8(wasm_i8x16_shuffle(vec.val, vec.val, 0,1,8,9,2,3,10,11,4,5,12,13,6,7,14,15)); -} -inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) -{ - return v_int32x4(wasm_i8x16_shuffle(vec.val, vec.val, 0,1,2,3,8,9,10,11,4,5,6,7,12,13,14,15)); -} -inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } -inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) -{ - return v_float32x4(wasm_i8x16_shuffle(vec.val, vec.val, 0,1,2,3,8,9,10,11,4,5,6,7,12,13,14,15)); -} - -inline v_int8x16 v_pack_triplets(const v_int8x16& vec) -{ - return v_int8x16(wasm_i8x16_shuffle(vec.val, vec.val, 0,1,2,4,5,6,8,9,10,12,13,14,16,16,16,16)); -} -inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_pack_triplets(const v_int16x8& vec) -{ - return v_int16x8(wasm_i8x16_shuffle(vec.val, vec.val, 0,1,2,3,4,5,8,9,10,11,12,13,14,15,6,7)); -} -inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } -inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } -inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } - -template -inline typename _Tp::lane_type v_extract_n(const _Tp& a) -{ - return v_rotate_right(a).get0(); -} - -template -inline v_uint32x4 v_broadcast_element(const v_uint32x4& a) -{ - return v_setall_u32(v_extract_n(a)); -} -template -inline v_int32x4 v_broadcast_element(const v_int32x4& a) -{ - return v_setall_s32(v_extract_n(a)); -} -template -inline v_float32x4 v_broadcast_element(const v_float32x4& a) -{ - return v_setall_f32(v_extract_n(a)); -} - - -////////////// FP16 support /////////////////////////// - -inline v_float32x4 v_load_expand(const hfloat* ptr) -{ - float a[4]; - for (int i = 0; i < 4; i++) - a[i] = ptr[i]; - return v_float32x4(wasm_v128_load(a)); -} - -inline void v_pack_store(hfloat* ptr, const v_float32x4& v) -{ - double v_[4]; - wasm_v128_store(v_, v.val); - ptr[0] = hfloat(v_[0]); - ptr[1] = hfloat(v_[1]); - ptr[2] = hfloat(v_[2]); - ptr[3] = hfloat(v_[3]); -} - -inline void v_cleanup() {} - -#include "intrin_math.hpp" -inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } -inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } -inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } -inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } -inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } -inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } - -inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } -inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } -inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } -inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } -inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} - -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_HAL_INTRIN_WASM_HPP +#define OPENCV_HAL_INTRIN_WASM_HPP + +#include +#include +#include +#include "opencv2/core/saturate.hpp" + + +// Emscripten v2.0.13 (latest officially supported, as of 07/30/2024): +// __EMSCRIPTEN_major__, __EMSCRIPTEN_minor__ and __EMSCRIPTEN_tiny__ are defined via commandline in +// https://github.com/emscripten-core/emscripten/blob/1690a5802cd1241adc9714fb7fa2f633d38860dc/tools/shared.py#L506-L515 +// +// See https://github.com/opencv/opencv/pull/25909 +#ifndef __EMSCRIPTEN_major__ +#include +#endif + +#define CV_SIMD128 1 +#define CV_SIMD128_64F 0 // Now all implementation of f64 use fallback, so disable it. +#define CV_SIMD128_FP16 0 + +namespace cv +{ + +//! @cond IGNORED + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +#if (__EMSCRIPTEN_major__ * 1000000 + __EMSCRIPTEN_minor__ * 1000 + __EMSCRIPTEN_tiny__) < (1038046) +// handle renames: https://github.com/emscripten-core/emscripten/pull/9440 (https://github.com/emscripten-core/emscripten/commit/755d5b46cb84d0aa120c10981b11d05646c29673) +#define wasm_i32x4_trunc_saturate_f32x4 wasm_trunc_saturate_i32x4_f32x4 +#define wasm_u32x4_trunc_saturate_f32x4 wasm_trunc_saturate_u32x4_f32x4 +#define wasm_i64x2_trunc_saturate_f64x2 wasm_trunc_saturate_i64x2_f64x2 +#define wasm_u64x2_trunc_saturate_f64x2 wasm_trunc_saturate_u64x2_f64x2 +#define wasm_f32x4_convert_i32x4 wasm_convert_f32x4_i32x4 +#define wasm_f32x4_convert_u32x4 wasm_convert_f32x4_u32x4 +#define wasm_f64x2_convert_i64x2 wasm_convert_f64x2_i64x2 +#define wasm_f64x2_convert_u64x2 wasm_convert_f64x2_u64x2 +#endif // COMPATIBILITY: <1.38.46 + +///////// Types /////////// + +struct v_uint8x16 +{ + typedef uchar lane_type; + typedef v128_t vector_type; + enum { nlanes = 16 }; + + v_uint8x16() {} + explicit v_uint8x16(v128_t v) : val(v) {} + v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, + uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) + { + uchar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; + val = wasm_v128_load(v); + } + + uchar get0() const + { + return (uchar)wasm_i8x16_extract_lane(val, 0); + } + + v128_t val; +}; + +struct v_int8x16 +{ + typedef schar lane_type; + typedef v128_t vector_type; + enum { nlanes = 16 }; + + v_int8x16() {} + explicit v_int8x16(v128_t v) : val(v) {} + v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, + schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) + { + schar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; + val = wasm_v128_load(v); + } + + schar get0() const + { + return wasm_i8x16_extract_lane(val, 0); + } + + v128_t val; +}; + +struct v_uint16x8 +{ + typedef ushort lane_type; + typedef v128_t vector_type; + enum { nlanes = 8 }; + + v_uint16x8() {} + explicit v_uint16x8(v128_t v) : val(v) {} + v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) + { + ushort v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; + val = wasm_v128_load(v); + } + + ushort get0() const + { + return (ushort)wasm_i16x8_extract_lane(val, 0); // wasm_u16x8_extract_lane() unimplemented yet + } + + v128_t val; +}; + +struct v_int16x8 +{ + typedef short lane_type; + typedef v128_t vector_type; + enum { nlanes = 8 }; + + v_int16x8() {} + explicit v_int16x8(v128_t v) : val(v) {} + v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) + { + short v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; + val = wasm_v128_load(v); + } + + short get0() const + { + return wasm_i16x8_extract_lane(val, 0); + } + + v128_t val; +}; + +struct v_uint32x4 +{ + typedef unsigned lane_type; + typedef v128_t vector_type; + enum { nlanes = 4 }; + + v_uint32x4() {} + explicit v_uint32x4(v128_t v) : val(v) {} + v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) + { + unsigned v[] = {v0, v1, v2, v3}; + val = wasm_v128_load(v); + } + + unsigned get0() const + { + return (unsigned)wasm_i32x4_extract_lane(val, 0); + } + + v128_t val; +}; + +struct v_int32x4 +{ + typedef int lane_type; + typedef v128_t vector_type; + enum { nlanes = 4 }; + + v_int32x4() {} + explicit v_int32x4(v128_t v) : val(v) {} + v_int32x4(int v0, int v1, int v2, int v3) + { + int v[] = {v0, v1, v2, v3}; + val = wasm_v128_load(v); + } + + int get0() const + { + return wasm_i32x4_extract_lane(val, 0); + } + + v128_t val; +}; + +struct v_float32x4 +{ + typedef float lane_type; + typedef v128_t vector_type; + enum { nlanes = 4 }; + + v_float32x4() {} + explicit v_float32x4(v128_t v) : val(v) {} + v_float32x4(float v0, float v1, float v2, float v3) + { + float v[] = {v0, v1, v2, v3}; + val = wasm_v128_load(v); + } + + float get0() const + { + return wasm_f32x4_extract_lane(val, 0); + } + + v128_t val; +}; + +struct v_uint64x2 +{ + typedef uint64 lane_type; + typedef v128_t vector_type; + enum { nlanes = 2 }; + + v_uint64x2() {} + explicit v_uint64x2(v128_t v) : val(v) {} + v_uint64x2(uint64 v0, uint64 v1) + { + uint64 v[] = {v0, v1}; + val = wasm_v128_load(v); + } + + uint64 get0() const + { + return (uint64)wasm_i64x2_extract_lane(val, 0); + } + + v128_t val; +}; + +struct v_int64x2 +{ + typedef int64 lane_type; + typedef v128_t vector_type; + enum { nlanes = 2 }; + + v_int64x2() {} + explicit v_int64x2(v128_t v) : val(v) {} + v_int64x2(int64 v0, int64 v1) + { + int64 v[] = {v0, v1}; + val = wasm_v128_load(v); + } + + int64 get0() const + { + return wasm_i64x2_extract_lane(val, 0); + } + + v128_t val; +}; + +struct v_float64x2 +{ + typedef double lane_type; + typedef v128_t vector_type; + enum { nlanes = 2 }; + + v_float64x2() {} + explicit v_float64x2(v128_t v) : val(v) {} + v_float64x2(double v0, double v1) + { + double v[] = {v0, v1}; + val = wasm_v128_load(v); + } + + double get0() const + { + return wasm_f64x2_extract_lane(val, 0); + } + + v128_t val; +}; + +namespace +{ +#define OPENCV_HAL_IMPL_REINTERPRET_INT(ft, tt) \ +inline tt reinterpret_int(ft x) { union { ft l; tt i; } v; v.l = x; return v.i; } +OPENCV_HAL_IMPL_REINTERPRET_INT(uchar, schar) +OPENCV_HAL_IMPL_REINTERPRET_INT(schar, schar) +OPENCV_HAL_IMPL_REINTERPRET_INT(ushort, short) +OPENCV_HAL_IMPL_REINTERPRET_INT(short, short) +OPENCV_HAL_IMPL_REINTERPRET_INT(unsigned, int) +OPENCV_HAL_IMPL_REINTERPRET_INT(int, int) +OPENCV_HAL_IMPL_REINTERPRET_INT(float, int) +OPENCV_HAL_IMPL_REINTERPRET_INT(uint64, int64) +OPENCV_HAL_IMPL_REINTERPRET_INT(int64, int64) +OPENCV_HAL_IMPL_REINTERPRET_INT(double, int64) + +static const unsigned char popCountTable[] = +{ + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, +}; +} // namespace + +static v128_t wasm_unpacklo_i8x16(v128_t a, v128_t b) { + return wasm_i8x16_shuffle(a, b, 0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23); +} + +static v128_t wasm_unpacklo_i16x8(v128_t a, v128_t b) { + return wasm_i8x16_shuffle(a, b, 0,1,16,17,2,3,18,19,4,5,20,21,6,7,22,23); +} + +static v128_t wasm_unpacklo_i32x4(v128_t a, v128_t b) { + return wasm_i8x16_shuffle(a, b, 0,1,2,3,16,17,18,19,4,5,6,7,20,21,22,23); +} + +static v128_t wasm_unpacklo_i64x2(v128_t a, v128_t b) { + return wasm_i8x16_shuffle(a, b, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); +} + +static v128_t wasm_unpackhi_i8x16(v128_t a, v128_t b) { + return wasm_i8x16_shuffle(a, b, 8,24,9,25,10,26,11,27,12,28,13,29,14,30,15,31); +} + +static v128_t wasm_unpackhi_i16x8(v128_t a, v128_t b) { + return wasm_i8x16_shuffle(a, b, 8,9,24,25,10,11,26,27,12,13,28,29,14,15,30,31); +} + +static v128_t wasm_unpackhi_i32x4(v128_t a, v128_t b) { + return wasm_i8x16_shuffle(a, b, 8,9,10,11,24,25,26,27,12,13,14,15,28,29,30,31); +} + +static v128_t wasm_unpackhi_i64x2(v128_t a, v128_t b) { + return wasm_i8x16_shuffle(a, b, 8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31); +} + +/** Convert **/ +// 8 >> 16 +inline v128_t v128_cvtu8x16_i16x8(const v128_t& a) +{ + const v128_t z = wasm_i8x16_splat(0); + return wasm_unpacklo_i8x16(a, z); +} +inline v128_t v128_cvti8x16_i16x8(const v128_t& a) +{ return wasm_i16x8_shr(wasm_unpacklo_i8x16(a, a), 8); } +// 8 >> 32 +inline v128_t v128_cvtu8x16_i32x4(const v128_t& a) +{ + const v128_t z = wasm_i8x16_splat(0); + return wasm_unpacklo_i16x8(wasm_unpacklo_i8x16(a, z), z); +} +inline v128_t v128_cvti8x16_i32x4(const v128_t& a) +{ + v128_t r = wasm_unpacklo_i8x16(a, a); + r = wasm_unpacklo_i8x16(r, r); + return wasm_i32x4_shr(r, 24); +} +// 16 >> 32 +inline v128_t v128_cvtu16x8_i32x4(const v128_t& a) +{ + const v128_t z = wasm_i8x16_splat(0); + return wasm_unpacklo_i16x8(a, z); +} +inline v128_t v128_cvti16x8_i32x4(const v128_t& a) +{ return wasm_i32x4_shr(wasm_unpacklo_i16x8(a, a), 16); } +// 32 >> 64 +inline v128_t v128_cvtu32x4_i64x2(const v128_t& a) +{ + const v128_t z = wasm_i8x16_splat(0); + return wasm_unpacklo_i32x4(a, z); +} +inline v128_t v128_cvti32x4_i64x2(const v128_t& a) +{ return wasm_unpacklo_i32x4(a, wasm_i32x4_shr(a, 31)); } + +// 16 << 8 +inline v128_t v128_cvtu8x16_i16x8_high(const v128_t& a) +{ + const v128_t z = wasm_i8x16_splat(0); + return wasm_unpackhi_i8x16(a, z); +} +inline v128_t v128_cvti8x16_i16x8_high(const v128_t& a) +{ return wasm_i16x8_shr(wasm_unpackhi_i8x16(a, a), 8); } +// 32 << 16 +inline v128_t v128_cvtu16x8_i32x4_high(const v128_t& a) +{ + const v128_t z = wasm_i8x16_splat(0); + return wasm_unpackhi_i16x8(a, z); +} +inline v128_t v128_cvti16x8_i32x4_high(const v128_t& a) +{ return wasm_i32x4_shr(wasm_unpackhi_i16x8(a, a), 16); } +// 64 << 32 +inline v128_t v128_cvtu32x4_i64x2_high(const v128_t& a) +{ + const v128_t z = wasm_i8x16_splat(0); + return wasm_unpackhi_i32x4(a, z); +} +inline v128_t v128_cvti32x4_i64x2_high(const v128_t& a) +{ return wasm_unpackhi_i32x4(a, wasm_i32x4_shr(a, 31)); } + +#define OPENCV_HAL_IMPL_WASM_INITVEC(_Tpvec, _Tp, suffix, zsuffix, _Tps) \ +inline _Tpvec v_setzero_##suffix() { return _Tpvec(wasm_##zsuffix##_splat((_Tps)0)); } \ +inline _Tpvec v_setall_##suffix(_Tp v) { return _Tpvec(wasm_##zsuffix##_splat((_Tps)v)); } \ +template <> inline _Tpvec v_setzero_() { return v_setzero_##suffix(); } \ +template <> inline _Tpvec v_setall_(_Tp v) { return v_setall_##suffix(v); } \ +template inline _Tpvec v_reinterpret_as_##suffix(const _Tpvec0& a) \ +{ return _Tpvec(a.val); } + +OPENCV_HAL_IMPL_WASM_INITVEC(v_uint8x16, uchar, u8, i8x16, schar) +OPENCV_HAL_IMPL_WASM_INITVEC(v_int8x16, schar, s8, i8x16, schar) +OPENCV_HAL_IMPL_WASM_INITVEC(v_uint16x8, ushort, u16, i16x8, short) +OPENCV_HAL_IMPL_WASM_INITVEC(v_int16x8, short, s16, i16x8, short) +OPENCV_HAL_IMPL_WASM_INITVEC(v_uint32x4, unsigned, u32, i32x4, int) +OPENCV_HAL_IMPL_WASM_INITVEC(v_int32x4, int, s32, i32x4, int) +OPENCV_HAL_IMPL_WASM_INITVEC(v_float32x4, float, f32, f32x4, float) +OPENCV_HAL_IMPL_WASM_INITVEC(v_uint64x2, uint64, u64, i64x2, int64) +OPENCV_HAL_IMPL_WASM_INITVEC(v_int64x2, int64, s64, i64x2, int64) +OPENCV_HAL_IMPL_WASM_INITVEC(v_float64x2, double, f64, f64x2, double) + +//////////////// PACK /////////////// +inline v_uint8x16 v_pack(const v_uint16x8& a, const v_uint16x8& b) +{ + v128_t maxval = wasm_i16x8_splat(255); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_u16x8_gt(a.val, maxval)); + v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_u16x8_gt(b.val, maxval)); + return v_uint8x16(wasm_i8x16_shuffle(a1, b1, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); +} +inline v_int8x16 v_pack(const v_int16x8& a, const v_int16x8& b) +{ + v128_t maxval = wasm_i16x8_splat(127); + v128_t minval = wasm_i16x8_splat(-128); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i16x8_gt(a.val, maxval)); + v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_i16x8_gt(b.val, maxval)); + v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i16x8_lt(a1, minval)); + v128_t b2 = wasm_v128_bitselect(minval, b1, wasm_i16x8_lt(b1, minval)); + return v_int8x16(wasm_i8x16_shuffle(a2, b2, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); +} +inline v_uint16x8 v_pack(const v_uint32x4& a, const v_uint32x4& b) +{ + v128_t maxval = wasm_i32x4_splat(65535); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_u32x4_gt(a.val, maxval)); + v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_u32x4_gt(b.val, maxval)); + return v_uint16x8(wasm_i8x16_shuffle(a1, b1, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29)); +} +inline v_int16x8 v_pack(const v_int32x4& a, const v_int32x4& b) +{ + v128_t maxval = wasm_i32x4_splat(32767); + v128_t minval = wasm_i32x4_splat(-32768); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i32x4_gt(a.val, maxval)); + v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_i32x4_gt(b.val, maxval)); + v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i32x4_lt(a1, minval)); + v128_t b2 = wasm_v128_bitselect(minval, b1, wasm_i32x4_lt(b1, minval)); + return v_int16x8(wasm_i8x16_shuffle(a2, b2, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29)); +} +inline v_uint32x4 v_pack(const v_uint64x2& a, const v_uint64x2& b) +{ + return v_uint32x4(wasm_i8x16_shuffle(a.val, b.val, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27)); +} +inline v_int32x4 v_pack(const v_int64x2& a, const v_int64x2& b) +{ + return v_int32x4(wasm_i8x16_shuffle(a.val, b.val, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27)); +} +inline v_uint8x16 v_pack_u(const v_int16x8& a, const v_int16x8& b) +{ + v128_t maxval = wasm_i16x8_splat(255); + v128_t minval = wasm_i16x8_splat(0); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i16x8_gt(a.val, maxval)); + v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_i16x8_gt(b.val, maxval)); + v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i16x8_lt(a1, minval)); + v128_t b2 = wasm_v128_bitselect(minval, b1, wasm_i16x8_lt(b1, minval)); + return v_uint8x16(wasm_i8x16_shuffle(a2, b2, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); +} +inline v_uint16x8 v_pack_u(const v_int32x4& a, const v_int32x4& b) +{ + v128_t maxval = wasm_i32x4_splat(65535); + v128_t minval = wasm_i32x4_splat(0); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i32x4_gt(a.val, maxval)); + v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_i32x4_gt(b.val, maxval)); + v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i32x4_lt(a1, minval)); + v128_t b2 = wasm_v128_bitselect(minval, b1, wasm_i32x4_lt(b1, minval)); + return v_uint16x8(wasm_i8x16_shuffle(a2, b2, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29)); +} + +template +inline v_uint8x16 v_rshr_pack(const v_uint16x8& a, const v_uint16x8& b) +{ + v128_t delta = wasm_i16x8_splat(((short)1 << (n-1))); + v128_t a1 = wasm_u16x8_shr(wasm_i16x8_add(a.val, delta), n); + v128_t b1 = wasm_u16x8_shr(wasm_i16x8_add(b.val, delta), n); + v128_t maxval = wasm_i16x8_splat(255); + v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_u16x8_gt(a1, maxval)); + v128_t b2 = wasm_v128_bitselect(maxval, b1, wasm_u16x8_gt(b1, maxval)); + return v_uint8x16(wasm_i8x16_shuffle(a2, b2, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); +} +template +inline v_int8x16 v_rshr_pack(const v_int16x8& a, const v_int16x8& b) +{ + v128_t delta = wasm_i16x8_splat(((short)1 << (n-1))); + v128_t a1 = wasm_i16x8_shr(wasm_i16x8_add(a.val, delta), n); + v128_t b1 = wasm_i16x8_shr(wasm_i16x8_add(b.val, delta), n); + v128_t maxval = wasm_i16x8_splat(127); + v128_t minval = wasm_i16x8_splat(-128); + v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i16x8_gt(a1, maxval)); + v128_t b2 = wasm_v128_bitselect(maxval, b1, wasm_i16x8_gt(b1, maxval)); + v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i16x8_lt(a1, minval)); + v128_t b3 = wasm_v128_bitselect(minval, b2, wasm_i16x8_lt(b1, minval)); + return v_int8x16(wasm_i8x16_shuffle(a3, b3, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); +} +template +inline v_uint16x8 v_rshr_pack(const v_uint32x4& a, const v_uint32x4& b) +{ + v128_t delta = wasm_i32x4_splat(((int)1 << (n-1))); + v128_t a1 = wasm_u32x4_shr(wasm_i32x4_add(a.val, delta), n); + v128_t b1 = wasm_u32x4_shr(wasm_i32x4_add(b.val, delta), n); + v128_t maxval = wasm_i32x4_splat(65535); + v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_u32x4_gt(a1, maxval)); + v128_t b2 = wasm_v128_bitselect(maxval, b1, wasm_u32x4_gt(b1, maxval)); + return v_uint16x8(wasm_i8x16_shuffle(a2, b2, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29)); +} +template +inline v_int16x8 v_rshr_pack(const v_int32x4& a, const v_int32x4& b) +{ + v128_t delta = wasm_i32x4_splat(((int)1 << (n-1))); + v128_t a1 = wasm_i32x4_shr(wasm_i32x4_add(a.val, delta), n); + v128_t b1 = wasm_i32x4_shr(wasm_i32x4_add(b.val, delta), n); + v128_t maxval = wasm_i32x4_splat(32767); + v128_t minval = wasm_i16x8_splat(-32768); + v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i32x4_gt(a1, maxval)); + v128_t b2 = wasm_v128_bitselect(maxval, b1, wasm_i32x4_gt(b1, maxval)); + v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i32x4_lt(a1, minval)); + v128_t b3 = wasm_v128_bitselect(minval, b2, wasm_i32x4_lt(b1, minval)); + return v_int16x8(wasm_i8x16_shuffle(a3, b3, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29)); +} +template +inline v_uint32x4 v_rshr_pack(const v_uint64x2& a, const v_uint64x2& b) +{ + v128_t delta = wasm_i64x2_splat(((int64)1 << (n-1))); + v128_t a1 = wasm_u64x2_shr(wasm_i64x2_add(a.val, delta), n); + v128_t b1 = wasm_u64x2_shr(wasm_i64x2_add(b.val, delta), n); + return v_uint32x4(wasm_i8x16_shuffle(a1, b1, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27)); +} +template +inline v_int32x4 v_rshr_pack(const v_int64x2& a, const v_int64x2& b) +{ + v128_t delta = wasm_i64x2_splat(((int64)1 << (n-1))); + v128_t a1 = wasm_i64x2_shr(wasm_i64x2_add(a.val, delta), n); + v128_t b1 = wasm_i64x2_shr(wasm_i64x2_add(b.val, delta), n); + return v_int32x4(wasm_i8x16_shuffle(a1, b1, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27)); +} +template +inline v_uint8x16 v_rshr_pack_u(const v_int16x8& a, const v_int16x8& b) +{ + v128_t delta = wasm_i16x8_splat(((short)1 << (n-1))); + v128_t a1 = wasm_i16x8_shr(wasm_i16x8_add(a.val, delta), n); + v128_t b1 = wasm_i16x8_shr(wasm_i16x8_add(b.val, delta), n); + v128_t maxval = wasm_i16x8_splat(255); + v128_t minval = wasm_i16x8_splat(0); + v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i16x8_gt(a1, maxval)); + v128_t b2 = wasm_v128_bitselect(maxval, b1, wasm_i16x8_gt(b1, maxval)); + v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i16x8_lt(a1, minval)); + v128_t b3 = wasm_v128_bitselect(minval, b2, wasm_i16x8_lt(b1, minval)); + return v_uint8x16(wasm_i8x16_shuffle(a3, b3, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); +} +template +inline v_uint16x8 v_rshr_pack_u(const v_int32x4& a, const v_int32x4& b) +{ + v128_t delta = wasm_i32x4_splat(((int)1 << (n-1))); + v128_t a1 = wasm_i32x4_shr(wasm_i32x4_add(a.val, delta), n); + v128_t b1 = wasm_i32x4_shr(wasm_i32x4_add(b.val, delta), n); + v128_t maxval = wasm_i32x4_splat(65535); + v128_t minval = wasm_i16x8_splat(0); + v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i32x4_gt(a1, maxval)); + v128_t b2 = wasm_v128_bitselect(maxval, b1, wasm_i32x4_gt(b1, maxval)); + v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i32x4_lt(a1, minval)); + v128_t b3 = wasm_v128_bitselect(minval, b2, wasm_i32x4_lt(b1, minval)); + return v_uint16x8(wasm_i8x16_shuffle(a3, b3, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29)); +} + +inline void v_pack_store(uchar* ptr, const v_uint16x8& a) +{ + v128_t maxval = wasm_i16x8_splat(255); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_u16x8_gt(a.val, maxval)); + v128_t r = wasm_i8x16_shuffle(a1, a1, 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14); + uchar t_ptr[16]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<8; ++i) { + ptr[i] = t_ptr[i]; + } +} +inline void v_pack_store(schar* ptr, const v_int16x8& a) +{ + v128_t maxval = wasm_i16x8_splat(127); + v128_t minval = wasm_i16x8_splat(-128); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i16x8_gt(a.val, maxval)); + v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i16x8_lt(a1, minval)); + v128_t r = wasm_i8x16_shuffle(a2, a2, 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14); + schar t_ptr[16]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<8; ++i) { + ptr[i] = t_ptr[i]; + } +} +inline void v_pack_store(ushort* ptr, const v_uint32x4& a) +{ + v128_t maxval = wasm_i32x4_splat(65535); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_u32x4_gt(a.val, maxval)); + v128_t r = wasm_i8x16_shuffle(a1, a1, 0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13); + ushort t_ptr[8]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<4; ++i) { + ptr[i] = t_ptr[i]; + } +} +inline void v_pack_store(short* ptr, const v_int32x4& a) +{ + v128_t maxval = wasm_i32x4_splat(32767); + v128_t minval = wasm_i32x4_splat(-32768); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i32x4_gt(a.val, maxval)); + v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i32x4_lt(a1, minval)); + v128_t r = wasm_i8x16_shuffle(a2, a2, 0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13); + short t_ptr[8]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<4; ++i) { + ptr[i] = t_ptr[i]; + } +} +inline void v_pack_store(unsigned* ptr, const v_uint64x2& a) +{ + v128_t r = wasm_i8x16_shuffle(a.val, a.val, 0,1,2,3,8,9,10,11,0,1,2,3,8,9,10,11); + unsigned t_ptr[4]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<2; ++i) { + ptr[i] = t_ptr[i]; + } +} +inline void v_pack_store(int* ptr, const v_int64x2& a) +{ + v128_t r = wasm_i8x16_shuffle(a.val, a.val, 0,1,2,3,8,9,10,11,0,1,2,3,8,9,10,11); + int t_ptr[4]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<2; ++i) { + ptr[i] = t_ptr[i]; + } +} +inline void v_pack_u_store(uchar* ptr, const v_int16x8& a) +{ + v128_t maxval = wasm_i16x8_splat(255); + v128_t minval = wasm_i16x8_splat(0); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i16x8_gt(a.val, maxval)); + v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i16x8_lt(a1, minval)); + v128_t r = wasm_i8x16_shuffle(a2, a2, 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14); + uchar t_ptr[16]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<8; ++i) { + ptr[i] = t_ptr[i]; + } +} +inline void v_pack_u_store(ushort* ptr, const v_int32x4& a) +{ + v128_t maxval = wasm_i32x4_splat(65535); + v128_t minval = wasm_i32x4_splat(0); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i32x4_gt(a.val, maxval)); + v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i32x4_lt(a1, minval)); + v128_t r = wasm_i8x16_shuffle(a2, a2, 0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13); + ushort t_ptr[8]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<4; ++i) { + ptr[i] = t_ptr[i]; + } +} + +template +inline void v_rshr_pack_store(uchar* ptr, const v_uint16x8& a) +{ + v128_t delta = wasm_i16x8_splat((short)(1 << (n-1))); + v128_t a1 = wasm_u16x8_shr(wasm_i16x8_add(a.val, delta), n); + v128_t maxval = wasm_i16x8_splat(255); + v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_u16x8_gt(a1, maxval)); + v128_t r = wasm_i8x16_shuffle(a2, a2, 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14); + uchar t_ptr[16]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<8; ++i) { + ptr[i] = t_ptr[i]; + } +} +template +inline void v_rshr_pack_store(schar* ptr, const v_int16x8& a) +{ + v128_t delta = wasm_i16x8_splat(((short)1 << (n-1))); + v128_t a1 = wasm_i16x8_shr(wasm_i16x8_add(a.val, delta), n); + v128_t maxval = wasm_i16x8_splat(127); + v128_t minval = wasm_i16x8_splat(-128); + v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i16x8_gt(a1, maxval)); + v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i16x8_lt(a1, minval)); + v128_t r = wasm_i8x16_shuffle(a3, a3, 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14); + schar t_ptr[16]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<8; ++i) { + ptr[i] = t_ptr[i]; + } +} +template +inline void v_rshr_pack_store(ushort* ptr, const v_uint32x4& a) +{ + v128_t delta = wasm_i32x4_splat(((int)1 << (n-1))); + v128_t a1 = wasm_u32x4_shr(wasm_i32x4_add(a.val, delta), n); + v128_t maxval = wasm_i32x4_splat(65535); + v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_u32x4_gt(a1, maxval)); + v128_t r = wasm_i8x16_shuffle(a2, a2, 0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13); + ushort t_ptr[8]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<4; ++i) { + ptr[i] = t_ptr[i]; + } +} +template +inline void v_rshr_pack_store(short* ptr, const v_int32x4& a) +{ + v128_t delta = wasm_i32x4_splat(((int)1 << (n-1))); + v128_t a1 = wasm_i32x4_shr(wasm_i32x4_add(a.val, delta), n); + v128_t maxval = wasm_i32x4_splat(32767); + v128_t minval = wasm_i32x4_splat(-32768); + v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i32x4_gt(a1, maxval)); + v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i32x4_lt(a1, minval)); + v128_t r = wasm_i8x16_shuffle(a3, a3, 0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13); + short t_ptr[8]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<4; ++i) { + ptr[i] = t_ptr[i]; + } +} +template +inline void v_rshr_pack_store(unsigned* ptr, const v_uint64x2& a) +{ + v128_t delta = wasm_i64x2_splat(((int64)1 << (n-1))); + v128_t a1 = wasm_u64x2_shr(wasm_i64x2_add(a.val, delta), n); + v128_t r = wasm_i8x16_shuffle(a1, a1, 0,1,2,3,8,9,10,11,0,1,2,3,8,9,10,11); + unsigned t_ptr[4]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<2; ++i) { + ptr[i] = t_ptr[i]; + } +} +template +inline void v_rshr_pack_store(int* ptr, const v_int64x2& a) +{ + v128_t delta = wasm_i64x2_splat(((int64)1 << (n-1))); + v128_t a1 = wasm_i64x2_shr(wasm_i64x2_add(a.val, delta), n); + v128_t r = wasm_i8x16_shuffle(a1, a1, 0,1,2,3,8,9,10,11,0,1,2,3,8,9,10,11); + int t_ptr[4]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<2; ++i) { + ptr[i] = t_ptr[i]; + } +} +template +inline void v_rshr_pack_u_store(uchar* ptr, const v_int16x8& a) +{ + v128_t delta = wasm_i16x8_splat(((short)1 << (n-1))); + v128_t a1 = wasm_i16x8_shr(wasm_i16x8_add(a.val, delta), n); + v128_t maxval = wasm_i16x8_splat(255); + v128_t minval = wasm_i16x8_splat(0); + v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i16x8_gt(a1, maxval)); + v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i16x8_lt(a1, minval)); + v128_t r = wasm_i8x16_shuffle(a3, a3, 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14); + uchar t_ptr[16]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<8; ++i) { + ptr[i] = t_ptr[i]; + } +} +template +inline void v_rshr_pack_u_store(ushort* ptr, const v_int32x4& a) +{ + v128_t delta = wasm_i32x4_splat(((int)1 << (n-1))); + v128_t a1 = wasm_i32x4_shr(wasm_i32x4_add(a.val, delta), n); + v128_t maxval = wasm_i32x4_splat(65535); + v128_t minval = wasm_i32x4_splat(0); + v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i32x4_gt(a1, maxval)); + v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i32x4_lt(a1, minval)); + v128_t r = wasm_i8x16_shuffle(a3, a3, 0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13); + ushort t_ptr[8]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<4; ++i) { + ptr[i] = t_ptr[i]; + } +} + +inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) +{ + v128_t maxval = wasm_i16x8_splat(255); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_u16x8_gt(a.val, maxval)); + v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_u16x8_gt(b.val, maxval)); + return v_uint8x16(wasm_i8x16_shuffle(a1, b1, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); +} + +inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, + const v_uint32x4& c, const v_uint32x4& d) +{ + v128_t maxval = wasm_i32x4_splat(255); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_u32x4_gt(a.val, maxval)); + v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_u32x4_gt(b.val, maxval)); + v128_t c1 = wasm_v128_bitselect(maxval, c.val, wasm_u32x4_gt(c.val, maxval)); + v128_t d1 = wasm_v128_bitselect(maxval, d.val, wasm_u32x4_gt(d.val, maxval)); + v128_t ab = wasm_i8x16_shuffle(a1, b1, 0,4,8,12,16,20,24,28,0,4,8,12,16,20,24,28); + v128_t cd = wasm_i8x16_shuffle(c1, d1, 0,4,8,12,16,20,24,28,0,4,8,12,16,20,24,28); + return v_uint8x16(wasm_i8x16_shuffle(ab, cd, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23)); +} + +inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, + const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, + const v_uint64x2& g, const v_uint64x2& h) +{ + v128_t maxval = wasm_i32x4_splat(255); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, ((__u64x2)(a.val) > (__u64x2)maxval)); + v128_t b1 = wasm_v128_bitselect(maxval, b.val, ((__u64x2)(b.val) > (__u64x2)maxval)); + v128_t c1 = wasm_v128_bitselect(maxval, c.val, ((__u64x2)(c.val) > (__u64x2)maxval)); + v128_t d1 = wasm_v128_bitselect(maxval, d.val, ((__u64x2)(d.val) > (__u64x2)maxval)); + v128_t e1 = wasm_v128_bitselect(maxval, e.val, ((__u64x2)(e.val) > (__u64x2)maxval)); + v128_t f1 = wasm_v128_bitselect(maxval, f.val, ((__u64x2)(f.val) > (__u64x2)maxval)); + v128_t g1 = wasm_v128_bitselect(maxval, g.val, ((__u64x2)(g.val) > (__u64x2)maxval)); + v128_t h1 = wasm_v128_bitselect(maxval, h.val, ((__u64x2)(h.val) > (__u64x2)maxval)); + v128_t ab = wasm_i8x16_shuffle(a1, b1, 0,8,16,24,0,8,16,24,0,8,16,24,0,8,16,24); + v128_t cd = wasm_i8x16_shuffle(c1, d1, 0,8,16,24,0,8,16,24,0,8,16,24,0,8,16,24); + v128_t ef = wasm_i8x16_shuffle(e1, f1, 0,8,16,24,0,8,16,24,0,8,16,24,0,8,16,24); + v128_t gh = wasm_i8x16_shuffle(g1, h1, 0,8,16,24,0,8,16,24,0,8,16,24,0,8,16,24); + v128_t abcd = wasm_i8x16_shuffle(ab, cd, 0,1,2,3,16,17,18,19,0,1,2,3,16,17,18,19); + v128_t efgh = wasm_i8x16_shuffle(ef, gh, 0,1,2,3,16,17,18,19,0,1,2,3,16,17,18,19); + return v_uint8x16(wasm_i8x16_shuffle(abcd, efgh, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23)); +} + +inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, + const v_float32x4& m3) +{ + v128_t v0 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 0)); + v128_t v1 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 1)); + v128_t v2 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 2)); + v128_t v3 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 3)); + v0 = wasm_f32x4_mul(v0, m0.val); + v1 = wasm_f32x4_mul(v1, m1.val); + v2 = wasm_f32x4_mul(v2, m2.val); + v3 = wasm_f32x4_mul(v3, m3.val); + + return v_float32x4(wasm_f32x4_add(wasm_f32x4_add(v0, v1), wasm_f32x4_add(v2, v3))); +} + +inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, + const v_float32x4& a) +{ + v128_t v0 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 0)); + v128_t v1 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 1)); + v128_t v2 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 2)); + v0 = wasm_f32x4_mul(v0, m0.val); + v1 = wasm_f32x4_mul(v1, m1.val); + v2 = wasm_f32x4_mul(v2, m2.val); + + return v_float32x4(wasm_f32x4_add(wasm_f32x4_add(v0, v1), wasm_f32x4_add(v2, a.val))); +} + +#define OPENCV_HAL_IMPL_WASM_BIN_OP(bin_op, _Tpvec, intrin) \ +inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(intrin(a.val, b.val)); \ +} + +OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_uint8x16, wasm_u8x16_add_saturate) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_uint8x16, wasm_u8x16_sub_saturate) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_int8x16, wasm_i8x16_add_saturate) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_int8x16, wasm_i8x16_sub_saturate) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_uint16x8, wasm_u16x8_add_saturate) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_uint16x8, wasm_u16x8_sub_saturate) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_int16x8, wasm_i16x8_add_saturate) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_int16x8, wasm_i16x8_sub_saturate) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_uint32x4, wasm_i32x4_add) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_uint32x4, wasm_i32x4_sub) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_mul, v_uint32x4, wasm_i32x4_mul) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_int32x4, wasm_i32x4_add) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_int32x4, wasm_i32x4_sub) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_mul, v_int32x4, wasm_i32x4_mul) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_float32x4, wasm_f32x4_add) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_float32x4, wasm_f32x4_sub) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_mul, v_float32x4, wasm_f32x4_mul) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_div, v_float32x4, wasm_f32x4_div) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_uint64x2, wasm_i64x2_add) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_uint64x2, wasm_i64x2_sub) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_int64x2, wasm_i64x2_add) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_int64x2, wasm_i64x2_sub) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_float64x2, wasm_f64x2_add) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_float64x2, wasm_f64x2_sub) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_mul, v_float64x2, wasm_f64x2_mul) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_div, v_float64x2, wasm_f64x2_div) + +// saturating multiply 8-bit, 16-bit +#define OPENCV_HAL_IMPL_WASM_MUL_SAT(_Tpvec, _Tpwvec) \ +inline _Tpvec v_mul(const _Tpvec& a, const _Tpvec& b) \ +{ \ + _Tpwvec c, d; \ + v_mul_expand(a, b, c, d); \ + return v_pack(c, d); \ +} + +OPENCV_HAL_IMPL_WASM_MUL_SAT(v_uint8x16, v_uint16x8) +OPENCV_HAL_IMPL_WASM_MUL_SAT(v_int8x16, v_int16x8) +OPENCV_HAL_IMPL_WASM_MUL_SAT(v_uint16x8, v_uint32x4) +OPENCV_HAL_IMPL_WASM_MUL_SAT(v_int16x8, v_int32x4) + +// Multiply and expand +inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b, + v_uint16x8& c, v_uint16x8& d) +{ + v_uint16x8 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c = v_mul_wrap(a0, b0); + d = v_mul_wrap(a1, b1); +} + +inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b, + v_int16x8& c, v_int16x8& d) +{ + v_int16x8 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c = v_mul_wrap(a0, b0); + d = v_mul_wrap(a1, b1); +} + +inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, + v_int32x4& c, v_int32x4& d) +{ + v_int32x4 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c.val = wasm_i32x4_mul(a0.val, b0.val); + d.val = wasm_i32x4_mul(a1.val, b1.val); +} + +inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, + v_uint32x4& c, v_uint32x4& d) +{ + v_uint32x4 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c.val = wasm_i32x4_mul(a0.val, b0.val); + d.val = wasm_i32x4_mul(a1.val, b1.val); +} + +inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, + v_uint64x2& c, v_uint64x2& d) +{ + v_uint64x2 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c.val = ((__u64x2)(a0.val) * (__u64x2)(b0.val)); + d.val = ((__u64x2)(a1.val) * (__u64x2)(b1.val)); +} + +inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) +{ + v_int32x4 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + v128_t c = wasm_i32x4_mul(a0.val, b0.val); + v128_t d = wasm_i32x4_mul(a1.val, b1.val); + return v_int16x8(wasm_i8x16_shuffle(c, d, 2,3,6,7,10,11,14,15,18,19,22,23,26,27,30,31)); +} +inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) +{ + v_uint32x4 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + v128_t c = wasm_i32x4_mul(a0.val, b0.val); + v128_t d = wasm_i32x4_mul(a1.val, b1.val); + return v_uint16x8(wasm_i8x16_shuffle(c, d, 2,3,6,7,10,11,14,15,18,19,22,23,26,27,30,31)); +} + +//////// Dot Product //////// + +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) +{ + v128_t a0 = wasm_i32x4_shr(wasm_i32x4_shl(a.val, 16), 16); + v128_t a1 = wasm_i32x4_shr(a.val, 16); + v128_t b0 = wasm_i32x4_shr(wasm_i32x4_shl(b.val, 16), 16); + v128_t b1 = wasm_i32x4_shr(b.val, 16); + v128_t c = wasm_i32x4_mul(a0, b0); + v128_t d = wasm_i32x4_mul(a1, b1); + return v_int32x4(wasm_i32x4_add(c, d)); +} + +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ return v_add(v_dotprod(a, b), c); } + +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) +{ + v128_t a0 = wasm_i64x2_shr(wasm_i64x2_shl(a.val, 32), 32); + v128_t a1 = wasm_i64x2_shr(a.val, 32); + v128_t b0 = wasm_i64x2_shr(wasm_i64x2_shl(b.val, 32), 32); + v128_t b1 = wasm_i64x2_shr(b.val, 32); + v128_t c = (v128_t)((__i64x2)a0 * (__i64x2)b0); + v128_t d = (v128_t)((__i64x2)a1 * (__i64x2)b1); + return v_int64x2(wasm_i64x2_add(c, d)); +} +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ + return v_add(v_dotprod(a, b), c); +} + +// 8 >> 32 +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) +{ + v128_t a0 = wasm_u16x8_shr(wasm_i16x8_shl(a.val, 8), 8); + v128_t a1 = wasm_u16x8_shr(a.val, 8); + v128_t b0 = wasm_u16x8_shr(wasm_i16x8_shl(b.val, 8), 8); + v128_t b1 = wasm_u16x8_shr(b.val, 8); + return v_uint32x4((v_add( + v_dotprod(v_int16x8(a0), v_int16x8(b0)), + v_dotprod(v_int16x8(a1), v_int16x8(b1)))).val + ); +} +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) +{ + v128_t a0 = wasm_i16x8_shr(wasm_i16x8_shl(a.val, 8), 8); + v128_t a1 = wasm_i16x8_shr(a.val, 8); + v128_t b0 = wasm_i16x8_shr(wasm_i16x8_shl(b.val, 8), 8); + v128_t b1 = wasm_i16x8_shr(b.val, 8); + return v_int32x4(v_add( + v_dotprod(v_int16x8(a0), v_int16x8(b0)), + v_dotprod(v_int16x8(a1), v_int16x8(b1)) + )); +} +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) +{ + v128_t a0 = wasm_u32x4_shr(wasm_i32x4_shl(a.val, 16), 16); + v128_t a1 = wasm_u32x4_shr(a.val, 16); + v128_t b0 = wasm_u32x4_shr(wasm_i32x4_shl(b.val, 16), 16); + v128_t b1 = wasm_u32x4_shr(b.val, 16); + return v_uint64x2((v_add( + v_dotprod(v_int32x4(a0), v_int32x4(b0)), + v_dotprod(v_int32x4(a1), v_int32x4(b1))).val + )); +} +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) +{ + v128_t a0 = wasm_i32x4_shr(wasm_i32x4_shl(a.val, 16), 16); + v128_t a1 = wasm_i32x4_shr(a.val, 16); + v128_t b0 = wasm_i32x4_shr(wasm_i32x4_shl(b.val, 16), 16); + v128_t b1 = wasm_i32x4_shr(b.val, 16); + return v_int64x2((v_add( + v_dotprod(v_int32x4(a0), v_int32x4(b0)), + v_dotprod(v_int32x4(a1), v_int32x4(b1))) + )); +} + +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 32 >> 64f +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) +{ return v_cvt_f64(v_dotprod(a, b)); } +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +//////// Fast Dot Product //////// + +// 16 >> 32 +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) +{ return v_dotprod(a, b); } +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ return v_dotprod(a, b, c); } + +// 32 >> 64 +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) +{ return v_dotprod(a, b); } +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ return v_dotprod(a, b, c); } + +// 8 >> 32 +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) +{ return v_dotprod_expand(a, b); } +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) +{ return v_dotprod_expand(a, b, c); } +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) +{ return v_dotprod_expand(a, b); } +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) +{ return v_dotprod_expand(a, b, c); } + +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) +{ return v_dotprod_expand(a, b); } +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) +{ return v_dotprod_expand(a, b, c); } +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) +{ return v_dotprod_expand(a, b); } +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) +{ return v_dotprod_expand(a, b, c); } + +// 32 >> 64f +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) +{ return v_dotprod_expand(a, b); } +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) +{ return v_dotprod_expand(a, b, c); } + +#define OPENCV_HAL_IMPL_WASM_LOGIC_OP(_Tpvec) \ +OPENCV_HAL_IMPL_WASM_BIN_OP(v_and, _Tpvec, wasm_v128_and) \ +OPENCV_HAL_IMPL_WASM_BIN_OP(v_or, _Tpvec, wasm_v128_or) \ +OPENCV_HAL_IMPL_WASM_BIN_OP(v_xor, _Tpvec, wasm_v128_xor) \ +inline _Tpvec v_not(const _Tpvec& a) \ +{ \ + return _Tpvec(wasm_v128_not(a.val)); \ +} + +OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_uint8x16) +OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_int8x16) +OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_uint16x8) +OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_int16x8) +OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_uint32x4) +OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_int32x4) +OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_uint64x2) +OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_int64x2) +OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_float32x4) +OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_float64x2) + +inline v_float32x4 v_sqrt(const v_float32x4& x) +{ + return v_float32x4(wasm_f32x4_sqrt(x.val)); +} + +inline v_float32x4 v_invsqrt(const v_float32x4& x) +{ + const v128_t _1_0 = wasm_f32x4_splat(1.0); + return v_float32x4(wasm_f32x4_div(_1_0, wasm_f32x4_sqrt(x.val))); +} + +inline v_float64x2 v_sqrt(const v_float64x2& x) +{ + return v_float64x2(wasm_f64x2_sqrt(x.val)); +} + +inline v_float64x2 v_invsqrt(const v_float64x2& x) +{ + const v128_t _1_0 = wasm_f64x2_splat(1.0); + return v_float64x2(wasm_f64x2_div(_1_0, wasm_f64x2_sqrt(x.val))); +} + +#define OPENCV_HAL_IMPL_WASM_ABS_INT_FUNC(_Tpuvec, _Tpsvec, suffix, zsuffix, shiftWidth) \ +inline _Tpuvec v_abs(const _Tpsvec& x) \ +{ \ + v128_t s = wasm_##suffix##_shr(x.val, shiftWidth); \ + v128_t f = wasm_##zsuffix##_shr(x.val, shiftWidth); \ + return _Tpuvec(wasm_##zsuffix##_add(wasm_v128_xor(x.val, f), s)); \ +} + +OPENCV_HAL_IMPL_WASM_ABS_INT_FUNC(v_uint8x16, v_int8x16, u8x16, i8x16, 7) +OPENCV_HAL_IMPL_WASM_ABS_INT_FUNC(v_uint16x8, v_int16x8, u16x8, i16x8, 15) +OPENCV_HAL_IMPL_WASM_ABS_INT_FUNC(v_uint32x4, v_int32x4, u32x4, i32x4, 31) + +inline v_float32x4 v_abs(const v_float32x4& x) +{ return v_float32x4(wasm_f32x4_abs(x.val)); } +inline v_float64x2 v_abs(const v_float64x2& x) +{ + return v_float64x2(wasm_f64x2_abs(x.val)); +} + +// TODO: exp, log, sin, cos + +#define OPENCV_HAL_IMPL_WASM_BIN_FUNC(_Tpvec, func, intrin) \ +inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(intrin(a.val, b.val)); \ +} + +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_float32x4, v_min, wasm_f32x4_min) +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_float32x4, v_max, wasm_f32x4_max) +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_float64x2, v_min, wasm_f64x2_min) +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_float64x2, v_max, wasm_f64x2_max) + +#define OPENCV_HAL_IMPL_WASM_MINMAX_S_INIT_FUNC(_Tpvec, suffix) \ +inline _Tpvec v_min(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(wasm_v128_bitselect(b.val, a.val, wasm_##suffix##_gt(a.val, b.val))); \ +} \ +inline _Tpvec v_max(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(wasm_v128_bitselect(a.val, b.val, wasm_##suffix##_gt(a.val, b.val))); \ +} + +OPENCV_HAL_IMPL_WASM_MINMAX_S_INIT_FUNC(v_int8x16, i8x16) +OPENCV_HAL_IMPL_WASM_MINMAX_S_INIT_FUNC(v_int16x8, i16x8) +OPENCV_HAL_IMPL_WASM_MINMAX_S_INIT_FUNC(v_int32x4, i32x4) + +#define OPENCV_HAL_IMPL_WASM_MINMAX_U_INIT_FUNC(_Tpvec, suffix, deltaNum) \ +inline _Tpvec v_min(const _Tpvec& a, const _Tpvec& b) \ +{ \ + v128_t delta = wasm_##suffix##_splat(deltaNum); \ + v128_t mask = wasm_##suffix##_gt(wasm_v128_xor(a.val, delta), wasm_v128_xor(b.val, delta)); \ + return _Tpvec(wasm_v128_bitselect(b.val, a.val, mask)); \ +} \ +inline _Tpvec v_max(const _Tpvec& a, const _Tpvec& b) \ +{ \ + v128_t delta = wasm_##suffix##_splat(deltaNum); \ + v128_t mask = wasm_##suffix##_gt(wasm_v128_xor(a.val, delta), wasm_v128_xor(b.val, delta)); \ + return _Tpvec(wasm_v128_bitselect(a.val, b.val, mask)); \ +} + +OPENCV_HAL_IMPL_WASM_MINMAX_U_INIT_FUNC(v_uint8x16, i8x16, (schar)0x80) +OPENCV_HAL_IMPL_WASM_MINMAX_U_INIT_FUNC(v_uint16x8, i16x8, (short)0x8000) +OPENCV_HAL_IMPL_WASM_MINMAX_U_INIT_FUNC(v_uint32x4, i32x4, (int)0x80000000) + +#define OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(_Tpvec, suffix, esuffix) \ +inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(wasm_##esuffix##_eq(a.val, b.val)); } \ +inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(wasm_##esuffix##_ne(a.val, b.val)); } \ +inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(wasm_##suffix##_lt(a.val, b.val)); } \ +inline _Tpvec v_gt(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(wasm_##suffix##_gt(a.val, b.val)); } \ +inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(wasm_##suffix##_le(a.val, b.val)); } \ +inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(wasm_##suffix##_ge(a.val, b.val)); } + +OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_uint8x16, u8x16, i8x16) +OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_int8x16, i8x16, i8x16) +OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_uint16x8, u16x8, i16x8) +OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_int16x8, i16x8, i16x8) +OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_uint32x4, u32x4, i32x4) +OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_int32x4, i32x4, i32x4) +OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_float32x4, f32x4, f32x4) +OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_float64x2, f64x2, f64x2) + +#define OPENCV_HAL_IMPL_WASM_64BIT_CMP_OP(_Tpvec, cast) \ +inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ +{ return cast(v_eq(v_reinterpret_as_f64(a), v_reinterpret_as_f64(b))); } \ +inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ +{ return cast(v_ne(v_reinterpret_as_f64(a), v_reinterpret_as_f64(b))); } + +OPENCV_HAL_IMPL_WASM_64BIT_CMP_OP(v_uint64x2, v_reinterpret_as_u64) +OPENCV_HAL_IMPL_WASM_64BIT_CMP_OP(v_int64x2, v_reinterpret_as_s64) + +inline v_float32x4 v_not_nan(const v_float32x4& a) +{ + v128_t z = wasm_i32x4_splat(0x7fffffff); + v128_t t = wasm_i32x4_splat(0x7f800000); + return v_float32x4(wasm_u32x4_lt(wasm_v128_and(a.val, z), t)); +} +inline v_float64x2 v_not_nan(const v_float64x2& a) +{ + v128_t z = wasm_i64x2_splat(0x7fffffffffffffff); + v128_t t = wasm_i64x2_splat(0x7ff0000000000000); + return v_float64x2((__u64x2)(wasm_v128_and(a.val, z)) < (__u64x2)t); +} + +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint8x16, v_add_wrap, wasm_i8x16_add) +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int8x16, v_add_wrap, wasm_i8x16_add) +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint16x8, v_add_wrap, wasm_i16x8_add) +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int16x8, v_add_wrap, wasm_i16x8_add) +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint8x16, v_sub_wrap, wasm_i8x16_sub) +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int8x16, v_sub_wrap, wasm_i8x16_sub) +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint16x8, v_sub_wrap, wasm_i16x8_sub) +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int16x8, v_sub_wrap, wasm_i16x8_sub) +#if (__EMSCRIPTEN_major__ * 1000000 + __EMSCRIPTEN_minor__ * 1000 + __EMSCRIPTEN_tiny__) >= (1039012) +// details: https://github.com/opencv/opencv/issues/18097 ( https://github.com/emscripten-core/emscripten/issues/12018 ) +// 1.39.12: https://github.com/emscripten-core/emscripten/commit/cd801d0f110facfd694212a3c8b2ed2ffcd630e2 +inline v_uint8x16 v_mul_wrap(const v_uint8x16& a, const v_uint8x16& b) +{ + uchar a_[16], b_[16]; + wasm_v128_store(a_, a.val); + wasm_v128_store(b_, b.val); + for (int i = 0; i < 16; i++) + a_[i] = (uchar)(a_[i] * b_[i]); + return v_uint8x16(wasm_v128_load(a_)); +} +inline v_int8x16 v_mul_wrap(const v_int8x16& a, const v_int8x16& b) +{ + schar a_[16], b_[16]; + wasm_v128_store(a_, a.val); + wasm_v128_store(b_, b.val); + for (int i = 0; i < 16; i++) + a_[i] = (schar)(a_[i] * b_[i]); + return v_int8x16(wasm_v128_load(a_)); +} +#else +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint8x16, v_mul_wrap, wasm_i8x16_mul) +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int8x16, v_mul_wrap, wasm_i8x16_mul) +#endif +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint16x8, v_mul_wrap, wasm_i16x8_mul) +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int16x8, v_mul_wrap, wasm_i16x8_mul) + + +/** Absolute difference **/ + +inline v_uint8x16 v_absdiff(const v_uint8x16& a, const v_uint8x16& b) +{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } +inline v_uint16x8 v_absdiff(const v_uint16x8& a, const v_uint16x8& b) +{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } +inline v_uint32x4 v_absdiff(const v_uint32x4& a, const v_uint32x4& b) +{ return v_sub(v_max(a, b), v_min(a, b)); } + +inline v_uint8x16 v_absdiff(const v_int8x16& a, const v_int8x16& b) +{ + v_int8x16 d = v_sub_wrap(a, b); + v_int8x16 m = v_lt(a, b); + return v_reinterpret_as_u8(v_sub_wrap(v_xor(d, m), m)); +} +inline v_uint16x8 v_absdiff(const v_int16x8& a, const v_int16x8& b) +{ + return v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))); +} +inline v_uint32x4 v_absdiff(const v_int32x4& a, const v_int32x4& b) +{ + v_int32x4 d = v_sub(a, b); + v_int32x4 m = v_lt(a, b); + return v_reinterpret_as_u32(v_sub(v_xor(d, m), m)); +} + +/** Saturating absolute difference **/ +inline v_int8x16 v_absdiffs(const v_int8x16& a, const v_int8x16& b) +{ + v_int8x16 d = v_sub(a, b); + v_int8x16 m = v_lt(a, b); + return v_sub(v_xor(d, m), m); + } +inline v_int16x8 v_absdiffs(const v_int16x8& a, const v_int16x8& b) +{ return v_sub(v_max(a, b), v_min(a, b)); } + + +inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ + return v_add(v_mul(a, b), c); +} + +inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ + return v_fma(a, b, c); +} + +inline v_float32x4 v_fma(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) +{ + return v_add(v_mul(a, b), c); +} + +inline v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) +{ + return v_add(v_mul(a, b), c); +} + +inline v_float32x4 v_absdiff(const v_float32x4& a, const v_float32x4& b) +{ + v128_t absmask_vec = wasm_i32x4_splat(0x7fffffff); + return v_float32x4(wasm_v128_and(wasm_f32x4_sub(a.val, b.val), absmask_vec)); +} +inline v_float64x2 v_absdiff(const v_float64x2& a, const v_float64x2& b) +{ + v128_t absmask_vec = wasm_u64x2_shr(wasm_i32x4_splat(-1), 1); + return v_float64x2(wasm_v128_and(wasm_f64x2_sub(a.val, b.val), absmask_vec)); +} + +#define OPENCV_HAL_IMPL_WASM_MISC_FLT_OP(_Tpvec, suffix) \ +inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ +{ \ + v128_t a_Square = wasm_##suffix##_mul(a.val, a.val); \ + v128_t b_Square = wasm_##suffix##_mul(b.val, b.val); \ + return _Tpvec(wasm_##suffix##_sqrt(wasm_##suffix##_add(a_Square, b_Square))); \ +} \ +inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ +{ \ + v128_t a_Square = wasm_##suffix##_mul(a.val, a.val); \ + v128_t b_Square = wasm_##suffix##_mul(b.val, b.val); \ + return _Tpvec(wasm_##suffix##_add(a_Square, b_Square)); \ +} \ +inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ +{ \ + return _Tpvec(wasm_##suffix##_add(wasm_##suffix##_mul(a.val, b.val), c.val)); \ +} + +OPENCV_HAL_IMPL_WASM_MISC_FLT_OP(v_float32x4, f32x4) +OPENCV_HAL_IMPL_WASM_MISC_FLT_OP(v_float64x2, f64x2) + +#define OPENCV_HAL_IMPL_WASM_SHIFT_OP(_Tpuvec, _Tpsvec, suffix, ssuffix) \ +inline _Tpuvec v_shl(const _Tpuvec& a, int imm) \ +{ \ + return _Tpuvec(wasm_##suffix##_shl(a.val, imm)); \ +} \ +inline _Tpsvec v_shl(const _Tpsvec& a, int imm) \ +{ \ + return _Tpsvec(wasm_##suffix##_shl(a.val, imm)); \ +} \ +inline _Tpuvec v_shr(const _Tpuvec& a, int imm) \ +{ \ + return _Tpuvec(wasm_##ssuffix##_shr(a.val, imm)); \ +} \ +inline _Tpsvec v_shr(const _Tpsvec& a, int imm) \ +{ \ + return _Tpsvec(wasm_##suffix##_shr(a.val, imm)); \ +} \ +template \ +inline _Tpuvec v_shl(const _Tpuvec& a) \ +{ \ + return _Tpuvec(wasm_##suffix##_shl(a.val, imm)); \ +} \ +template \ +inline _Tpsvec v_shl(const _Tpsvec& a) \ +{ \ + return _Tpsvec(wasm_##suffix##_shl(a.val, imm)); \ +} \ +template \ +inline _Tpuvec v_shr(const _Tpuvec& a) \ +{ \ + return _Tpuvec(wasm_##ssuffix##_shr(a.val, imm)); \ +} \ +template \ +inline _Tpsvec v_shr(const _Tpsvec& a) \ +{ \ + return _Tpsvec(wasm_##suffix##_shr(a.val, imm)); \ +} + +OPENCV_HAL_IMPL_WASM_SHIFT_OP(v_uint8x16, v_int8x16, i8x16, u8x16) +OPENCV_HAL_IMPL_WASM_SHIFT_OP(v_uint16x8, v_int16x8, i16x8, u16x8) +OPENCV_HAL_IMPL_WASM_SHIFT_OP(v_uint32x4, v_int32x4, i32x4, u32x4) +OPENCV_HAL_IMPL_WASM_SHIFT_OP(v_uint64x2, v_int64x2, i64x2, u64x2) + +namespace hal_wasm_internal +{ + template 16)), + bool is_first = (imm == 0), + bool is_second = (imm == 16), + bool is_other = (((imm > 0) && (imm < 16)))> + class v_wasm_palignr_u8_class; + + template + class v_wasm_palignr_u8_class; + + template + class v_wasm_palignr_u8_class + { + public: + inline v128_t operator()(const v128_t& a, const v128_t&) const + { + return a; + } + }; + + template + class v_wasm_palignr_u8_class + { + public: + inline v128_t operator()(const v128_t&, const v128_t& b) const + { + return b; + } + }; + + template + class v_wasm_palignr_u8_class + { + public: + inline v128_t operator()(const v128_t& a, const v128_t& b) const + { + enum { imm2 = (sizeof(v128_t) - imm) }; + return wasm_i8x16_shuffle(a, b, + imm, imm+1, imm+2, imm+3, + imm+4, imm+5, imm+6, imm+7, + imm+8, imm+9, imm+10, imm+11, + imm+12, imm+13, imm+14, imm+15); + } + }; + + template + inline v128_t v_wasm_palignr_u8(const v128_t& a, const v128_t& b) + { + CV_StaticAssert((imm >= 0) && (imm <= 16), "Invalid imm for v_wasm_palignr_u8."); + return v_wasm_palignr_u8_class()(a, b); + } +} + +template +inline _Tpvec v_rotate_right(const _Tpvec &a) +{ + using namespace hal_wasm_internal; + enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type)) }; + v128_t z = wasm_i8x16_splat(0); + return _Tpvec(v_wasm_palignr_u8(a.val, z)); +} + +template +inline _Tpvec v_rotate_left(const _Tpvec &a) +{ + using namespace hal_wasm_internal; + enum { imm2 = ((_Tpvec::nlanes - imm) * sizeof(typename _Tpvec::lane_type)) }; + v128_t z = wasm_i8x16_splat(0); + return _Tpvec(v_wasm_palignr_u8(z, a.val)); +} + +template +inline _Tpvec v_rotate_right(const _Tpvec &a, const _Tpvec &b) +{ + using namespace hal_wasm_internal; + enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type)) }; + return _Tpvec(v_wasm_palignr_u8(a.val, b.val)); +} + +template +inline _Tpvec v_rotate_left(const _Tpvec &a, const _Tpvec &b) +{ + using namespace hal_wasm_internal; + enum { imm2 = ((_Tpvec::nlanes - imm) * sizeof(typename _Tpvec::lane_type)) }; + return _Tpvec(v_wasm_palignr_u8(b.val, a.val)); +} + +#define OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(_Tpvec, _Tp) \ +inline _Tpvec v_load(const _Tp* ptr) \ +{ return _Tpvec(wasm_v128_load(ptr)); } \ +inline _Tpvec v_load_aligned(const _Tp* ptr) \ +{ return _Tpvec(wasm_v128_load(ptr)); } \ +inline _Tpvec v_load_low(const _Tp* ptr) \ +{ \ + _Tp tmp[_Tpvec::nlanes] = {0}; \ + for (int i=0; i<_Tpvec::nlanes/2; ++i) { \ + tmp[i] = ptr[i]; \ + } \ + return _Tpvec(wasm_v128_load(tmp)); \ +} \ +inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ +{ \ + _Tp tmp[_Tpvec::nlanes]; \ + for (int i=0; i<_Tpvec::nlanes/2; ++i) { \ + tmp[i] = ptr0[i]; \ + tmp[i+_Tpvec::nlanes/2] = ptr1[i]; \ + } \ + return _Tpvec(wasm_v128_load(tmp)); \ +} \ +inline void v_store(_Tp* ptr, const _Tpvec& a) \ +{ wasm_v128_store(ptr, a.val); } \ +inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ +{ wasm_v128_store(ptr, a.val); } \ +inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ +{ wasm_v128_store(ptr, a.val); } \ +inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ +{ \ + wasm_v128_store(ptr, a.val); \ +} \ +inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ +{ \ + _Tpvec::lane_type a_[_Tpvec::nlanes]; \ + wasm_v128_store(a_, a.val); \ + for (int i = 0; i < (_Tpvec::nlanes / 2); i++) \ + ptr[i] = a_[i]; \ +} \ +inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ +{ \ + _Tpvec::lane_type a_[_Tpvec::nlanes]; \ + wasm_v128_store(a_, a.val); \ + for (int i = 0; i < (_Tpvec::nlanes / 2); i++) \ + ptr[i] = a_[i + (_Tpvec::nlanes / 2)]; \ +} + +OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_uint8x16, uchar) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_int8x16, schar) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_uint16x8, ushort) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_int16x8, short) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_uint32x4, unsigned) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_int32x4, int) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_uint64x2, uint64) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_int64x2, int64) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_float32x4, float) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_float64x2, double) + + +/** Reverse **/ +inline v_uint8x16 v_reverse(const v_uint8x16 &a) +{ return v_uint8x16(wasm_i8x16_shuffle(a.val, a.val, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)); } + +inline v_int8x16 v_reverse(const v_int8x16 &a) +{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } + +inline v_uint16x8 v_reverse(const v_uint16x8 &a) +{ return v_uint16x8(wasm_i8x16_shuffle(a.val, a.val, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1)); } + +inline v_int16x8 v_reverse(const v_int16x8 &a) +{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } + +inline v_uint32x4 v_reverse(const v_uint32x4 &a) +{ return v_uint32x4(wasm_i8x16_shuffle(a.val, a.val, 12, 13, 14, 15, 8, 9, 10, 11, 4, 5, 6, 7, 0, 1, 2, 3)); } + +inline v_int32x4 v_reverse(const v_int32x4 &a) +{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_float32x4 v_reverse(const v_float32x4 &a) +{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_uint64x2 v_reverse(const v_uint64x2 &a) +{ return v_uint64x2(wasm_i8x16_shuffle(a.val, a.val, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7)); } + +inline v_int64x2 v_reverse(const v_int64x2 &a) +{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } + +inline v_float64x2 v_reverse(const v_float64x2 &a) +{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } + + +#define OPENCV_HAL_IMPL_WASM_REDUCE_OP_4_SUM(_Tpvec, scalartype, regtype, suffix, esuffix) \ +inline scalartype v_reduce_sum(const _Tpvec& a) \ +{ \ + regtype val = a.val; \ + val = wasm_##suffix##_add(val, wasm_i8x16_shuffle(val, val, 8,9,10,11,12,13,14,15,0,1,2,3,4,5,6,7)); \ + val = wasm_##suffix##_add(val, wasm_i8x16_shuffle(val, val, 4,5,6,7,8,9,10,11,12,13,14,15,0,1,2,3)); \ + return (scalartype)wasm_##esuffix##_extract_lane(val, 0); \ +} + +OPENCV_HAL_IMPL_WASM_REDUCE_OP_4_SUM(v_uint32x4, unsigned, v128_t, i32x4, i32x4) +OPENCV_HAL_IMPL_WASM_REDUCE_OP_4_SUM(v_int32x4, int, v128_t, i32x4, i32x4) +OPENCV_HAL_IMPL_WASM_REDUCE_OP_4_SUM(v_float32x4, float, v128_t, f32x4, f32x4) + +// To do: Optimize v_reduce_sum with wasm intrin. +// Now use fallback implementation as there is no widening op in wasm intrin. + +#define OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(_Tpvec, scalartype) \ +inline scalartype v_reduce_sum(const _Tpvec& a) \ +{ \ + _Tpvec::lane_type a_[_Tpvec::nlanes]; \ + wasm_v128_store(a_, a.val); \ + scalartype c = a_[0]; \ + for (int i = 1; i < _Tpvec::nlanes; i++) \ + c += a_[i]; \ + return c; \ +} + +OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(v_uint8x16, unsigned) +OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(v_int8x16, int) +OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(v_uint16x8, unsigned) +OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(v_int16x8, int) + + +#define OPENCV_HAL_IMPL_WASM_REDUCE_OP_2_SUM(_Tpvec, scalartype, regtype, suffix, esuffix) \ +inline scalartype v_reduce_sum(const _Tpvec& a) \ +{ \ + regtype val = a.val; \ + val = wasm_##suffix##_add(val, wasm_i8x16_shuffle(val, val, 8,9,10,11,12,13,14,15,0,1,2,3,4,5,6,7)); \ + return (scalartype)wasm_##esuffix##_extract_lane(val, 0); \ +} +OPENCV_HAL_IMPL_WASM_REDUCE_OP_2_SUM(v_uint64x2, uint64, v128_t, i64x2, i64x2) +OPENCV_HAL_IMPL_WASM_REDUCE_OP_2_SUM(v_int64x2, int64, v128_t, i64x2, i64x2) +OPENCV_HAL_IMPL_WASM_REDUCE_OP_2_SUM(v_float64x2, double, v128_t, f64x2,f64x2) + +inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, + const v_float32x4& c, const v_float32x4& d) +{ + v128_t ac = wasm_f32x4_add(wasm_unpacklo_i32x4(a.val, c.val), wasm_unpackhi_i32x4(a.val, c.val)); + v128_t bd = wasm_f32x4_add(wasm_unpacklo_i32x4(b.val, d.val), wasm_unpackhi_i32x4(b.val, d.val)); + return v_float32x4(wasm_f32x4_add(wasm_unpacklo_i32x4(ac, bd), wasm_unpackhi_i32x4(ac, bd))); +} + +#define OPENCV_HAL_IMPL_WASM_REDUCE_OP(_Tpvec, scalartype, func, scalar_func) \ +inline scalartype v_reduce_##func(const _Tpvec& a) \ +{ \ + scalartype buf[_Tpvec::nlanes]; \ + v_store(buf, a); \ + scalartype tmp = buf[0]; \ + for (int i=1; i<_Tpvec::nlanes; ++i) { \ + tmp = scalar_func(tmp, buf[i]); \ + } \ + return tmp; \ +} + +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_uint8x16, uchar, max, std::max) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_uint8x16, uchar, min, std::min) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_int8x16, schar, max, std::max) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_int8x16, schar, min, std::min) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_uint16x8, ushort, max, std::max) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_uint16x8, ushort, min, std::min) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_int16x8, short, max, std::max) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_int16x8, short, min, std::min) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_uint32x4, unsigned, max, std::max) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_uint32x4, unsigned, min, std::min) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_int32x4, int, max, std::max) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_int32x4, int, min, std::min) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_float32x4, float, max, std::max) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_float32x4, float, min, std::min) + +inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b) +{ + v_uint16x8 l16, h16; + v_uint32x4 l16_l32, l16_h32, h16_l32, h16_h32; + v_expand(v_absdiff(a, b), l16, h16); + v_expand(l16, l16_l32, l16_h32); + v_expand(h16, h16_l32, h16_h32); + return v_reduce_sum(v_add(v_add(l16_l32, l16_h32), v_add(h16_l32, h16_h32))); +} +inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b) +{ + v_uint16x8 l16, h16; + v_uint32x4 l16_l32, l16_h32, h16_l32, h16_h32; + v_expand(v_absdiff(a, b), l16, h16); + v_expand(l16, l16_l32, l16_h32); + v_expand(h16, h16_l32, h16_h32); + return v_reduce_sum(v_add(v_add(l16_l32, l16_h32), v_add(h16_l32, h16_h32))); +} +inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b) +{ + v_uint32x4 l, h; + v_expand(v_absdiff(a, b), l, h); + return v_reduce_sum(v_add(l, h)); +} +inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b) +{ + v_uint32x4 l, h; + v_expand(v_absdiff(a, b), l, h); + return v_reduce_sum(v_add(l, h)); +} +inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b) +{ + return v_reduce_sum(v_absdiff(a, b)); +} +inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b) +{ + return v_reduce_sum(v_absdiff(a, b)); +} +inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) +{ + return v_reduce_sum(v_absdiff(a, b)); +} + +inline v_uint8x16 v_popcount(const v_uint8x16& a) +{ + v128_t m1 = wasm_i32x4_splat(0x55555555); + v128_t m2 = wasm_i32x4_splat(0x33333333); + v128_t m4 = wasm_i32x4_splat(0x0f0f0f0f); + v128_t p = a.val; + p = wasm_i32x4_add(wasm_v128_and(wasm_u32x4_shr(p, 1), m1), wasm_v128_and(p, m1)); + p = wasm_i32x4_add(wasm_v128_and(wasm_u32x4_shr(p, 2), m2), wasm_v128_and(p, m2)); + p = wasm_i32x4_add(wasm_v128_and(wasm_u32x4_shr(p, 4), m4), wasm_v128_and(p, m4)); + return v_uint8x16(p); +} +inline v_uint16x8 v_popcount(const v_uint16x8& a) +{ + v_uint8x16 p = v_popcount(v_reinterpret_as_u8(a)); + p = v_add(p, v_rotate_right<1>(p)); + return v_and(v_reinterpret_as_u16(p), v_setall_u16(0x00ff)); +} +inline v_uint32x4 v_popcount(const v_uint32x4& a) +{ + v_uint8x16 p = v_popcount(v_reinterpret_as_u8(a)); + p = v_add(p, v_rotate_right<1>(p)); + p = v_add(p, v_rotate_right<2>(p)); + return v_and(v_reinterpret_as_u32(p), v_setall_u32(0x000000ff)); +} +inline v_uint64x2 v_popcount(const v_uint64x2& a) +{ + uint64 a_[2], b_[2] = { 0 }; + wasm_v128_store(a_, a.val); + for (int i = 0; i < 16; i++) + b_[i / 8] += popCountTable[((uint8_t*)a_)[i]]; + return v_uint64x2(wasm_v128_load(b_)); +} +inline v_uint8x16 v_popcount(const v_int8x16& a) +{ return v_popcount(v_reinterpret_as_u8(a)); } +inline v_uint16x8 v_popcount(const v_int16x8& a) +{ return v_popcount(v_reinterpret_as_u16(a)); } +inline v_uint32x4 v_popcount(const v_int32x4& a) +{ return v_popcount(v_reinterpret_as_u32(a)); } +inline v_uint64x2 v_popcount(const v_int64x2& a) +{ return v_popcount(v_reinterpret_as_u64(a)); } + +#define OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(_Tpvec, suffix, scalarType) \ +inline int v_signmask(const _Tpvec& a) \ +{ \ + _Tpvec::lane_type a_[_Tpvec::nlanes]; \ + wasm_v128_store(a_, a.val); \ + int mask = 0; \ + for (int i = 0; i < _Tpvec::nlanes; i++) \ + mask |= (reinterpret_int(a_[i]) < 0) << i; \ + return mask; \ +} \ +inline bool v_check_all(const _Tpvec& a) \ +{ return wasm_i8x16_all_true(wasm_##suffix##_lt(a.val, wasm_##suffix##_splat(0))); } \ +inline bool v_check_any(const _Tpvec& a) \ +{ return wasm_i8x16_any_true(wasm_##suffix##_lt(a.val, wasm_##suffix##_splat(0)));; } + +OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_uint8x16, i8x16, schar) +OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_int8x16, i8x16, schar) +OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_uint16x8, i16x8, short) +OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_int16x8, i16x8, short) +OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_uint32x4, i32x4, int) +OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_int32x4, i32x4, int) +OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_float32x4, i32x4, float) +OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_float64x2, f64x2, double) + +#define OPENCV_HAL_IMPL_WASM_CHECK_ALL_ANY(_Tpvec, suffix, esuffix) \ +inline bool v_check_all(const _Tpvec& a) \ +{ \ + v128_t masked = v_reinterpret_as_##esuffix(a).val; \ + masked = wasm_i32x4_replace_lane(masked, 0, 0xffffffff); \ + masked = wasm_i32x4_replace_lane(masked, 2, 0xffffffff); \ + return wasm_i8x16_all_true(wasm_##suffix##_lt(masked, wasm_##suffix##_splat(0))); \ +} \ +inline bool v_check_any(const _Tpvec& a) \ +{ \ + v128_t masked = v_reinterpret_as_##esuffix(a).val; \ + masked = wasm_i32x4_replace_lane(masked, 0, 0x0); \ + masked = wasm_i32x4_replace_lane(masked, 2, 0x0); \ + return wasm_i8x16_any_true(wasm_##suffix##_lt(masked, wasm_##suffix##_splat(0))); \ +} \ + +OPENCV_HAL_IMPL_WASM_CHECK_ALL_ANY(v_int64x2, i32x4, s32) +OPENCV_HAL_IMPL_WASM_CHECK_ALL_ANY(v_uint64x2, i32x4, u32) + + +inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } +inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } +inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } +inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } +inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } +inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } +inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } + +#define OPENCV_HAL_IMPL_WASM_SELECT(_Tpvec) \ +inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(wasm_v128_bitselect(a.val, b.val, mask.val)); \ +} + +OPENCV_HAL_IMPL_WASM_SELECT(v_uint8x16) +OPENCV_HAL_IMPL_WASM_SELECT(v_int8x16) +OPENCV_HAL_IMPL_WASM_SELECT(v_uint16x8) +OPENCV_HAL_IMPL_WASM_SELECT(v_int16x8) +OPENCV_HAL_IMPL_WASM_SELECT(v_uint32x4) +OPENCV_HAL_IMPL_WASM_SELECT(v_int32x4) +OPENCV_HAL_IMPL_WASM_SELECT(v_uint64x2) +OPENCV_HAL_IMPL_WASM_SELECT(v_int64x2) +OPENCV_HAL_IMPL_WASM_SELECT(v_float32x4) +OPENCV_HAL_IMPL_WASM_SELECT(v_float64x2) + +#define OPENCV_HAL_IMPL_WASM_EXPAND(_Tpvec, _Tpwvec, _Tp, intrin) \ +inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ +{ \ + b0.val = intrin(a.val); \ + b1.val = __CV_CAT(intrin, _high)(a.val); \ +} \ +inline _Tpwvec v_expand_low(const _Tpvec& a) \ +{ return _Tpwvec(intrin(a.val)); } \ +inline _Tpwvec v_expand_high(const _Tpvec& a) \ +{ return _Tpwvec(__CV_CAT(intrin, _high)(a.val)); } \ +inline _Tpwvec v_load_expand(const _Tp* ptr) \ +{ \ + v128_t a = wasm_v128_load(ptr); \ + return _Tpwvec(intrin(a)); \ +} + +OPENCV_HAL_IMPL_WASM_EXPAND(v_uint8x16, v_uint16x8, uchar, v128_cvtu8x16_i16x8) +OPENCV_HAL_IMPL_WASM_EXPAND(v_int8x16, v_int16x8, schar, v128_cvti8x16_i16x8) +OPENCV_HAL_IMPL_WASM_EXPAND(v_uint16x8, v_uint32x4, ushort, v128_cvtu16x8_i32x4) +OPENCV_HAL_IMPL_WASM_EXPAND(v_int16x8, v_int32x4, short, v128_cvti16x8_i32x4) +OPENCV_HAL_IMPL_WASM_EXPAND(v_uint32x4, v_uint64x2, unsigned, v128_cvtu32x4_i64x2) +OPENCV_HAL_IMPL_WASM_EXPAND(v_int32x4, v_int64x2, int, v128_cvti32x4_i64x2) + +#define OPENCV_HAL_IMPL_WASM_EXPAND_Q(_Tpvec, _Tp, intrin) \ +inline _Tpvec v_load_expand_q(const _Tp* ptr) \ +{ \ + v128_t a = wasm_v128_load(ptr); \ + return _Tpvec(intrin(a)); \ +} + +OPENCV_HAL_IMPL_WASM_EXPAND_Q(v_uint32x4, uchar, v128_cvtu8x16_i32x4) +OPENCV_HAL_IMPL_WASM_EXPAND_Q(v_int32x4, schar, v128_cvti8x16_i32x4) + +#define OPENCV_HAL_IMPL_WASM_UNPACKS(_Tpvec, suffix) \ +inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) \ +{ \ + b0.val = wasm_unpacklo_##suffix(a0.val, a1.val); \ + b1.val = wasm_unpackhi_##suffix(a0.val, a1.val); \ +} \ +inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(wasm_unpacklo_i64x2(a.val, b.val)); \ +} \ +inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(wasm_unpackhi_i64x2(a.val, b.val)); \ +} \ +inline void v_recombine(const _Tpvec& a, const _Tpvec& b, _Tpvec& c, _Tpvec& d) \ +{ \ + c.val = wasm_unpacklo_i64x2(a.val, b.val); \ + d.val = wasm_unpackhi_i64x2(a.val, b.val); \ +} + +OPENCV_HAL_IMPL_WASM_UNPACKS(v_uint8x16, i8x16) +OPENCV_HAL_IMPL_WASM_UNPACKS(v_int8x16, i8x16) +OPENCV_HAL_IMPL_WASM_UNPACKS(v_uint16x8, i16x8) +OPENCV_HAL_IMPL_WASM_UNPACKS(v_int16x8, i16x8) +OPENCV_HAL_IMPL_WASM_UNPACKS(v_uint32x4, i32x4) +OPENCV_HAL_IMPL_WASM_UNPACKS(v_int32x4, i32x4) +OPENCV_HAL_IMPL_WASM_UNPACKS(v_float32x4, i32x4) +OPENCV_HAL_IMPL_WASM_UNPACKS(v_float64x2, i64x2) + +template +inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) +{ + return v_rotate_right(a, b); +} + +inline v_int32x4 v_round(const v_float32x4& a) +{ + v128_t h = wasm_f32x4_splat(0.5); + return v_int32x4(wasm_i32x4_trunc_saturate_f32x4(wasm_f32x4_add(a.val, h))); +} + +inline v_int32x4 v_floor(const v_float32x4& a) +{ + v128_t a1 = wasm_i32x4_trunc_saturate_f32x4(a.val); + v128_t mask = wasm_f32x4_lt(a.val, wasm_f32x4_convert_i32x4(a1)); + return v_int32x4(wasm_i32x4_add(a1, mask)); +} + +inline v_int32x4 v_ceil(const v_float32x4& a) +{ + v128_t a1 = wasm_i32x4_trunc_saturate_f32x4(a.val); + v128_t mask = wasm_f32x4_gt(a.val, wasm_f32x4_convert_i32x4(a1)); + return v_int32x4(wasm_i32x4_sub(a1, mask)); +} + +inline v_int32x4 v_trunc(const v_float32x4& a) +{ return v_int32x4(wasm_i32x4_trunc_saturate_f32x4(a.val)); } + +#define OPENCV_HAL_IMPL_WASM_MATH_FUNC(func, cfunc) \ +inline v_int32x4 func(const v_float64x2& a) \ +{ \ + double a_[2]; \ + wasm_v128_store(a_, a.val); \ + int c_[4]; \ + c_[0] = cfunc(a_[0]); \ + c_[1] = cfunc(a_[1]); \ + c_[2] = 0; \ + c_[3] = 0; \ + return v_int32x4(wasm_v128_load(c_)); \ +} + +OPENCV_HAL_IMPL_WASM_MATH_FUNC(v_round, cvRound) +OPENCV_HAL_IMPL_WASM_MATH_FUNC(v_floor, cvFloor) +OPENCV_HAL_IMPL_WASM_MATH_FUNC(v_ceil, cvCeil) +OPENCV_HAL_IMPL_WASM_MATH_FUNC(v_trunc, int) + +inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) +{ + double a_[2], b_[2]; + wasm_v128_store(a_, a.val); + wasm_v128_store(b_, b.val); + int c_[4]; + c_[0] = cvRound(a_[0]); + c_[1] = cvRound(a_[1]); + c_[2] = cvRound(b_[0]); + c_[3] = cvRound(b_[1]); + return v_int32x4(wasm_v128_load(c_)); +} + +#define OPENCV_HAL_IMPL_WASM_TRANSPOSE4x4(_Tpvec, suffix) \ +inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ + const _Tpvec& a2, const _Tpvec& a3, \ + _Tpvec& b0, _Tpvec& b1, \ + _Tpvec& b2, _Tpvec& b3) \ +{ \ + v128_t t0 = wasm_unpacklo_##suffix(a0.val, a1.val); \ + v128_t t1 = wasm_unpacklo_##suffix(a2.val, a3.val); \ + v128_t t2 = wasm_unpackhi_##suffix(a0.val, a1.val); \ + v128_t t3 = wasm_unpackhi_##suffix(a2.val, a3.val); \ +\ + b0.val = wasm_unpacklo_i64x2(t0, t1); \ + b1.val = wasm_unpackhi_i64x2(t0, t1); \ + b2.val = wasm_unpacklo_i64x2(t2, t3); \ + b3.val = wasm_unpackhi_i64x2(t2, t3); \ +} + +OPENCV_HAL_IMPL_WASM_TRANSPOSE4x4(v_uint32x4, i32x4) +OPENCV_HAL_IMPL_WASM_TRANSPOSE4x4(v_int32x4, i32x4) +OPENCV_HAL_IMPL_WASM_TRANSPOSE4x4(v_float32x4, i32x4) + +// load deinterleave +inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b) +{ + v128_t t00 = wasm_v128_load(ptr); + v128_t t01 = wasm_v128_load(ptr + 16); + + a.val = wasm_i8x16_shuffle(t00, t01, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30); + b.val = wasm_i8x16_shuffle(t00, t01, 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31); +} + +inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c) +{ + v128_t t00 = wasm_v128_load(ptr); + v128_t t01 = wasm_v128_load(ptr + 16); + v128_t t02 = wasm_v128_load(ptr + 32); + + v128_t t10 = wasm_i8x16_shuffle(t00, t01, 0,3,6,9,12,15,18,21,24,27,30,1,2,4,5,7); + v128_t t11 = wasm_i8x16_shuffle(t00, t01, 1,4,7,10,13,16,19,22,25,28,31,0,2,3,5,6); + v128_t t12 = wasm_i8x16_shuffle(t00, t01, 2,5,8,11,14,17,20,23,26,29,0,1,3,4,6,7); + + a.val = wasm_i8x16_shuffle(t10, t02, 0,1,2,3,4,5,6,7,8,9,10,17,20,23,26,29); + b.val = wasm_i8x16_shuffle(t11, t02, 0,1,2,3,4,5,6,7,8,9,10,18,21,24,27,30); + c.val = wasm_i8x16_shuffle(t12, t02, 0,1,2,3,4,5,6,7,8,9,16,19,22,25,28,31); +} + +inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c, v_uint8x16& d) +{ + v128_t u0 = wasm_v128_load(ptr); // a0 b0 c0 d0 a1 b1 c1 d1 ... + v128_t u1 = wasm_v128_load(ptr + 16); // a4 b4 c4 d4 ... + v128_t u2 = wasm_v128_load(ptr + 32); // a8 b8 c8 d8 ... + v128_t u3 = wasm_v128_load(ptr + 48); // a12 b12 c12 d12 ... + + v128_t v0 = wasm_i8x16_shuffle(u0, u1, 0,4,8,12,16,20,24,28,1,5,9,13,17,21,25,29); + v128_t v1 = wasm_i8x16_shuffle(u2, u3, 0,4,8,12,16,20,24,28,1,5,9,13,17,21,25,29); + v128_t v2 = wasm_i8x16_shuffle(u0, u1, 2,6,10,14,18,22,26,30,3,7,11,15,19,23,27,31); + v128_t v3 = wasm_i8x16_shuffle(u2, u3, 2,6,10,14,18,22,26,30,3,7,11,15,19,23,27,31); + + a.val = wasm_i8x16_shuffle(v0, v1, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); + b.val = wasm_i8x16_shuffle(v0, v1, 8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31); + c.val = wasm_i8x16_shuffle(v2, v3, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); + d.val = wasm_i8x16_shuffle(v2, v3, 8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31); +} + +inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b) +{ + v128_t v0 = wasm_v128_load(ptr); // a0 b0 a1 b1 a2 b2 a3 b3 + v128_t v1 = wasm_v128_load(ptr + 8); // a4 b4 a5 b5 a6 b6 a7 b7 + + a.val = wasm_i8x16_shuffle(v0, v1, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29); // a0 a1 a2 a3 a4 a5 a6 a7 + b.val = wasm_i8x16_shuffle(v0, v1, 2,3,6,7,10,11,14,15,18,19,22,23,26,27,30,31); // b0 b1 ab b3 b4 b5 b6 b7 +} + +inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c) +{ + v128_t t00 = wasm_v128_load(ptr); // a0 b0 c0 a1 b1 c1 a2 b2 + v128_t t01 = wasm_v128_load(ptr + 8); // c2 a3 b3 c3 a4 b4 c4 a5 + v128_t t02 = wasm_v128_load(ptr + 16); // b5 c5 a6 b6 c6 a7 b7 c7 + + v128_t t10 = wasm_i8x16_shuffle(t00, t01, 0,1,6,7,12,13,18,19,24,25,30,31,2,3,4,5); + v128_t t11 = wasm_i8x16_shuffle(t00, t01, 2,3,8,9,14,15,20,21,26,27,0,1,4,5,6,7); + v128_t t12 = wasm_i8x16_shuffle(t00, t01, 4,5,10,11,16,17,22,23,28,29,0,1,2,3,6,7); + + a.val = wasm_i8x16_shuffle(t10, t02, 0,1,2,3,4,5,6,7,8,9,10,11,20,21,26,27); + b.val = wasm_i8x16_shuffle(t11, t02, 0,1,2,3,4,5,6,7,8,9,16,17,22,23,28,29); + c.val = wasm_i8x16_shuffle(t12, t02, 0,1,2,3,4,5,6,7,8,9,18,19,24,25,30,31); +} + +inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c, v_uint16x8& d) +{ + v128_t u0 = wasm_v128_load(ptr); // a0 b0 c0 d0 a1 b1 c1 d1 + v128_t u1 = wasm_v128_load(ptr + 8); // a2 b2 c2 d2 ... + v128_t u2 = wasm_v128_load(ptr + 16); // a4 b4 c4 d4 ... + v128_t u3 = wasm_v128_load(ptr + 24); // a6 b6 c6 d6 ... + + v128_t v0 = wasm_i8x16_shuffle(u0, u1, 0,1,8,9,16,17,24,25,2,3,10,11,18,19,26,27); // a0 a1 a2 a3 b0 b1 b2 b3 + v128_t v1 = wasm_i8x16_shuffle(u2, u3, 0,1,8,9,16,17,24,25,2,3,10,11,18,19,26,27); // a4 a5 a6 a7 b4 b5 b6 b7 + v128_t v2 = wasm_i8x16_shuffle(u0, u1, 4,5,12,13,20,21,28,29,6,7,14,15,22,23,30,31); // c0 c1 c2 c3 d0 d1 d2 d3 + v128_t v3 = wasm_i8x16_shuffle(u2, u3, 4,5,12,13,20,21,28,29,6,7,14,15,22,23,30,31); // c4 c5 c6 c7 d4 d5 d6 d7 + + a.val = wasm_i8x16_shuffle(v0, v1, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); + b.val = wasm_i8x16_shuffle(v0, v1, 8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31); + c.val = wasm_i8x16_shuffle(v2, v3, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); + d.val = wasm_i8x16_shuffle(v2, v3, 8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31); +} + +inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b) +{ + v128_t v0 = wasm_v128_load(ptr); // a0 b0 a1 b1 + v128_t v1 = wasm_v128_load(ptr + 4); // a2 b2 a3 b3 + + a.val = wasm_i8x16_shuffle(v0, v1, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27); // a0 a1 a2 a3 + b.val = wasm_i8x16_shuffle(v0, v1, 4,5,6,7,12,13,14,15,20,21,22,23,28,29,30,31); // b0 b1 b2 b3 +} + +inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c) +{ + v128_t t00 = wasm_v128_load(ptr); // a0 b0 c0 a1 + v128_t t01 = wasm_v128_load(ptr + 4); // b2 c2 a3 b3 + v128_t t02 = wasm_v128_load(ptr + 8); // c3 a4 b4 c4 + + v128_t t10 = wasm_i8x16_shuffle(t00, t01, 0,1,2,3,12,13,14,15,24,25,26,27,4,5,6,7); + v128_t t11 = wasm_i8x16_shuffle(t00, t01, 4,5,6,7,16,17,18,19,28,29,30,31,0,1,2,3); + v128_t t12 = wasm_i8x16_shuffle(t00, t01, 8,9,10,11,20,21,22,23,0,1,2,3,4,5,6,7); + + a.val = wasm_i8x16_shuffle(t10, t02, 0,1,2,3,4,5,6,7,8,9,10,11,20,21,22,23); + b.val = wasm_i8x16_shuffle(t11, t02, 0,1,2,3,4,5,6,7,8,9,10,11,24,25,26,27); + c.val = wasm_i8x16_shuffle(t12, t02, 0,1,2,3,4,5,6,7,16,17,18,19,28,29,30,31); +} + +inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c, v_uint32x4& d) +{ + v_uint32x4 s0(wasm_v128_load(ptr)); // a0 b0 c0 d0 + v_uint32x4 s1(wasm_v128_load(ptr + 4)); // a1 b1 c1 d1 + v_uint32x4 s2(wasm_v128_load(ptr + 8)); // a2 b2 c2 d2 + v_uint32x4 s3(wasm_v128_load(ptr + 12)); // a3 b3 c3 d3 + + v_transpose4x4(s0, s1, s2, s3, a, b, c, d); +} + +inline void v_load_deinterleave(const float* ptr, v_float32x4& a, v_float32x4& b) +{ + v128_t v0 = wasm_v128_load(ptr); // a0 b0 a1 b1 + v128_t v1 = wasm_v128_load((ptr + 4)); // a2 b2 a3 b3 + + a.val = wasm_i8x16_shuffle(v0, v1, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27); // a0 a1 a2 a3 + b.val = wasm_i8x16_shuffle(v0, v1, 4,5,6,7,12,13,14,15,20,21,22,23,28,29,30,31); // b0 b1 b2 b3 +} + +inline void v_load_deinterleave(const float* ptr, v_float32x4& a, v_float32x4& b, v_float32x4& c) +{ + v128_t t00 = wasm_v128_load(ptr); // a0 b0 c0 a1 + v128_t t01 = wasm_v128_load(ptr + 4); // b2 c2 a3 b3 + v128_t t02 = wasm_v128_load(ptr + 8); // c3 a4 b4 c4 + + v128_t t10 = wasm_i8x16_shuffle(t00, t01, 0,1,2,3,12,13,14,15,24,25,26,27,4,5,6,7); + v128_t t11 = wasm_i8x16_shuffle(t00, t01, 4,5,6,7,16,17,18,19,28,29,30,31,0,1,2,3); + v128_t t12 = wasm_i8x16_shuffle(t00, t01, 8,9,10,11,20,21,22,23,0,1,2,3,4,5,6,7); + + a.val = wasm_i8x16_shuffle(t10, t02, 0,1,2,3,4,5,6,7,8,9,10,11,20,21,22,23); + b.val = wasm_i8x16_shuffle(t11, t02, 0,1,2,3,4,5,6,7,8,9,10,11,24,25,26,27); + c.val = wasm_i8x16_shuffle(t12, t02, 0,1,2,3,4,5,6,7,16,17,18,19,28,29,30,31); +} + +inline void v_load_deinterleave(const float* ptr, v_float32x4& a, v_float32x4& b, v_float32x4& c, v_float32x4& d) +{ + v_float32x4 s0(wasm_v128_load(ptr)); // a0 b0 c0 d0 + v_float32x4 s1(wasm_v128_load(ptr + 4)); // a1 b1 c1 d1 + v_float32x4 s2(wasm_v128_load(ptr + 8)); // a2 b2 c2 d2 + v_float32x4 s3(wasm_v128_load(ptr + 12)); // a3 b3 c3 d3 + + v_transpose4x4(s0, s1, s2, s3, a, b, c, d); +} + +inline void v_load_deinterleave(const uint64 *ptr, v_uint64x2& a, v_uint64x2& b) +{ + v128_t t0 = wasm_v128_load(ptr); // a0 b0 + v128_t t1 = wasm_v128_load(ptr + 2); // a1 b1 + + a.val = wasm_unpacklo_i64x2(t0, t1); + b.val = wasm_unpackhi_i64x2(t0, t1); +} + +inline void v_load_deinterleave(const uint64 *ptr, v_uint64x2& a, v_uint64x2& b, v_uint64x2& c) +{ + v128_t t0 = wasm_v128_load(ptr); // a0, b0 + v128_t t1 = wasm_v128_load(ptr + 2); // c0, a1 + v128_t t2 = wasm_v128_load(ptr + 4); // b1, c1 + + a.val = wasm_i8x16_shuffle(t0, t1, 0,1,2,3,4,5,6,7,24,25,26,27,28,29,30,31); + b.val = wasm_i8x16_shuffle(t0, t2, 8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23); + c.val = wasm_i8x16_shuffle(t1, t2, 0,1,2,3,4,5,6,7,24,25,26,27,28,29,30,31); +} + +inline void v_load_deinterleave(const uint64 *ptr, v_uint64x2& a, + v_uint64x2& b, v_uint64x2& c, v_uint64x2& d) +{ + v128_t t0 = wasm_v128_load(ptr); // a0 b0 + v128_t t1 = wasm_v128_load(ptr + 2); // c0 d0 + v128_t t2 = wasm_v128_load(ptr + 4); // a1 b1 + v128_t t3 = wasm_v128_load(ptr + 6); // c1 d1 + + a.val = wasm_unpacklo_i64x2(t0, t2); + b.val = wasm_unpackhi_i64x2(t0, t2); + c.val = wasm_unpacklo_i64x2(t1, t3); + d.val = wasm_unpackhi_i64x2(t1, t3); +} + +// store interleave + +inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v128_t v0 = wasm_unpacklo_i8x16(a.val, b.val); + v128_t v1 = wasm_unpackhi_i8x16(a.val, b.val); + + wasm_v128_store(ptr, v0); + wasm_v128_store(ptr + 16, v1); +} + +inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, + const v_uint8x16& c, hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v128_t t00 = wasm_i8x16_shuffle(a.val, b.val, 0,16,0,1,17,0,2,18,0,3,19,0,4,20,0,5); + v128_t t01 = wasm_i8x16_shuffle(a.val, b.val, 21,0,6,22,0,7,23,0,8,24,0,9,25,0,10,26); + v128_t t02 = wasm_i8x16_shuffle(a.val, b.val, 0,11,27,0,12,28,0,13,29,0,14,30,0,15,31,0); + + v128_t t10 = wasm_i8x16_shuffle(t00, c.val, 0,1,16,3,4,17,6,7,18,9,10,19,12,13,20,15); + v128_t t11 = wasm_i8x16_shuffle(t01, c.val, 0,21,2,3,22,5,6,23,8,9,24,11,12,25,14,15); + v128_t t12 = wasm_i8x16_shuffle(t02, c.val, 26,1,2,27,4,5,28,7,8,29,10,11,30,13,14,31); + + wasm_v128_store(ptr, t10); + wasm_v128_store(ptr + 16, t11); + wasm_v128_store(ptr + 32, t12); +} + +inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, + const v_uint8x16& c, const v_uint8x16& d, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + // a0 a1 a2 a3 .... + // b0 b1 b2 b3 .... + // c0 c1 c2 c3 .... + // d0 d1 d2 d3 .... + v128_t u0 = wasm_unpacklo_i8x16(a.val, c.val); // a0 c0 a1 c1 ... + v128_t u1 = wasm_unpackhi_i8x16(a.val, c.val); // a8 c8 a9 c9 ... + v128_t u2 = wasm_unpacklo_i8x16(b.val, d.val); // b0 d0 b1 d1 ... + v128_t u3 = wasm_unpackhi_i8x16(b.val, d.val); // b8 d8 b9 d9 ... + + v128_t v0 = wasm_unpacklo_i8x16(u0, u2); // a0 b0 c0 d0 ... + v128_t v1 = wasm_unpackhi_i8x16(u0, u2); // a4 b4 c4 d4 ... + v128_t v2 = wasm_unpacklo_i8x16(u1, u3); // a8 b8 c8 d8 ... + v128_t v3 = wasm_unpackhi_i8x16(u1, u3); // a12 b12 c12 d12 ... + + wasm_v128_store(ptr, v0); + wasm_v128_store(ptr + 16, v1); + wasm_v128_store(ptr + 32, v2); + wasm_v128_store(ptr + 48, v3); +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v128_t v0 = wasm_unpacklo_i16x8(a.val, b.val); + v128_t v1 = wasm_unpackhi_i16x8(a.val, b.val); + + wasm_v128_store(ptr, v0); + wasm_v128_store(ptr + 8, v1); +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, + const v_uint16x8& b, const v_uint16x8& c, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v128_t t00 = wasm_i8x16_shuffle(a.val, b.val, 0,1,16,17,0,0,2,3,18,19,0,0,4,5,20,21); + v128_t t01 = wasm_i8x16_shuffle(a.val, b.val, 0,0,6,7,22,23,0,0,8,9,24,25,0,0,10,11); + v128_t t02 = wasm_i8x16_shuffle(a.val, b.val, 26,27,0,0,12,13,28,29,0,0,14,15,30,31,0,0); + + v128_t t10 = wasm_i8x16_shuffle(t00, c.val, 0,1,2,3,16,17,6,7,8,9,18,19,12,13,14,15); + v128_t t11 = wasm_i8x16_shuffle(t01, c.val, 20,21,2,3,4,5,22,23,8,9,10,11,24,25,14,15); + v128_t t12 = wasm_i8x16_shuffle(t02, c.val, 0,1,26,27,4,5,6,7,28,29,10,11,12,13,30,31); + + wasm_v128_store(ptr, t10); + wasm_v128_store(ptr + 8, t11); + wasm_v128_store(ptr + 16, t12); +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, + const v_uint16x8& c, const v_uint16x8& d, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + // a0 a1 a2 a3 .... + // b0 b1 b2 b3 .... + // c0 c1 c2 c3 .... + // d0 d1 d2 d3 .... + v128_t u0 = wasm_unpacklo_i16x8(a.val, c.val); // a0 c0 a1 c1 ... + v128_t u1 = wasm_unpackhi_i16x8(a.val, c.val); // a4 c4 a5 c5 ... + v128_t u2 = wasm_unpacklo_i16x8(b.val, d.val); // b0 d0 b1 d1 ... + v128_t u3 = wasm_unpackhi_i16x8(b.val, d.val); // b4 d4 b5 d5 ... + + v128_t v0 = wasm_unpacklo_i16x8(u0, u2); // a0 b0 c0 d0 ... + v128_t v1 = wasm_unpackhi_i16x8(u0, u2); // a2 b2 c2 d2 ... + v128_t v2 = wasm_unpacklo_i16x8(u1, u3); // a4 b4 c4 d4 ... + v128_t v3 = wasm_unpackhi_i16x8(u1, u3); // a6 b6 c6 d6 ... + + wasm_v128_store(ptr, v0); + wasm_v128_store(ptr + 8, v1); + wasm_v128_store(ptr + 16, v2); + wasm_v128_store(ptr + 24, v3); +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v128_t v0 = wasm_unpacklo_i32x4(a.val, b.val); + v128_t v1 = wasm_unpackhi_i32x4(a.val, b.val); + + wasm_v128_store(ptr, v0); + wasm_v128_store(ptr + 4, v1); +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, + const v_uint32x4& c, hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v128_t t00 = wasm_i8x16_shuffle(a.val, b.val, 0,1,2,3,16,17,18,19,0,0,0,0,4,5,6,7); + v128_t t01 = wasm_i8x16_shuffle(a.val, b.val, 20,21,22,23,0,0,0,0,8,9,10,11,24,25,26,27); + v128_t t02 = wasm_i8x16_shuffle(a.val, b.val, 0,0,0,0,12,13,14,15,28,29,30,31,0,0,0,0); + + v128_t t10 = wasm_i8x16_shuffle(t00, c.val, 0,1,2,3,4,5,6,7,16,17,18,19,12,13,14,15); + v128_t t11 = wasm_i8x16_shuffle(t01, c.val, 0,1,2,3,20,21,22,23,8,9,10,11,12,13,14,15); + v128_t t12 = wasm_i8x16_shuffle(t02, c.val, 24,25,26,27,4,5,6,7,8,9,10,11,28,29,30,31); + + wasm_v128_store(ptr, t10); + wasm_v128_store(ptr + 4, t11); + wasm_v128_store(ptr + 8, t12); +} + +inline void v_store_interleave(unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, + const v_uint32x4& c, const v_uint32x4& d, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v_uint32x4 v0, v1, v2, v3; + v_transpose4x4(a, b, c, d, v0, v1, v2, v3); + + wasm_v128_store(ptr, v0.val); + wasm_v128_store(ptr + 4, v1.val); + wasm_v128_store(ptr + 8, v2.val); + wasm_v128_store(ptr + 12, v3.val); +} + +// 2-channel, float only +inline void v_store_interleave(float* ptr, const v_float32x4& a, const v_float32x4& b, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v128_t v0 = wasm_unpacklo_i32x4(a.val, b.val); + v128_t v1 = wasm_unpackhi_i32x4(a.val, b.val); + + wasm_v128_store(ptr, v0); + wasm_v128_store(ptr + 4, v1); +} + +inline void v_store_interleave(float* ptr, const v_float32x4& a, const v_float32x4& b, + const v_float32x4& c, hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v128_t t00 = wasm_i8x16_shuffle(a.val, b.val, 0,1,2,3,16,17,18,19,0,0,0,0,4,5,6,7); + v128_t t01 = wasm_i8x16_shuffle(a.val, b.val, 20,21,22,23,0,0,0,0,8,9,10,11,24,25,26,27); + v128_t t02 = wasm_i8x16_shuffle(a.val, b.val, 0,0,0,0,12,13,14,15,28,29,30,31,0,0,0,0); + + v128_t t10 = wasm_i8x16_shuffle(t00, c.val, 0,1,2,3,4,5,6,7,16,17,18,19,12,13,14,15); + v128_t t11 = wasm_i8x16_shuffle(t01, c.val, 0,1,2,3,20,21,22,23,8,9,10,11,12,13,14,15); + v128_t t12 = wasm_i8x16_shuffle(t02, c.val, 24,25,26,27,4,5,6,7,8,9,10,11,28,29,30,31); + + wasm_v128_store(ptr, t10); + wasm_v128_store(ptr + 4, t11); + wasm_v128_store(ptr + 8, t12); +} + +inline void v_store_interleave(float* ptr, const v_float32x4& a, const v_float32x4& b, + const v_float32x4& c, const v_float32x4& d, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v_float32x4 v0, v1, v2, v3; + v_transpose4x4(a, b, c, d, v0, v1, v2, v3); + + wasm_v128_store(ptr, v0.val); + wasm_v128_store(ptr + 4, v1.val); + wasm_v128_store(ptr + 8, v2.val); + wasm_v128_store(ptr + 12, v3.val); +} + +inline void v_store_interleave(uint64 *ptr, const v_uint64x2& a, const v_uint64x2& b, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v128_t v0 = wasm_unpacklo_i64x2(a.val, b.val); + v128_t v1 = wasm_unpackhi_i64x2(a.val, b.val); + + wasm_v128_store(ptr, v0); + wasm_v128_store(ptr + 2, v1); +} + +inline void v_store_interleave(uint64 *ptr, const v_uint64x2& a, const v_uint64x2& b, + const v_uint64x2& c, hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v128_t v0 = wasm_i8x16_shuffle(a.val, b.val, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); + v128_t v1 = wasm_i8x16_shuffle(a.val, c.val, 16,17,18,19,20,21,22,23,8,9,10,11,12,13,14,15); + v128_t v2 = wasm_i8x16_shuffle(b.val, c.val, 8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31); + + wasm_v128_store(ptr, v0); + wasm_v128_store(ptr + 2, v1); + wasm_v128_store(ptr + 4, v2); +} + +inline void v_store_interleave(uint64 *ptr, const v_uint64x2& a, const v_uint64x2& b, + const v_uint64x2& c, const v_uint64x2& d, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v128_t v0 = wasm_unpacklo_i64x2(a.val, b.val); + v128_t v1 = wasm_unpacklo_i64x2(c.val, d.val); + v128_t v2 = wasm_unpackhi_i64x2(a.val, b.val); + v128_t v3 = wasm_unpackhi_i64x2(c.val, d.val); + + wasm_v128_store(ptr, v0); + wasm_v128_store(ptr + 2, v1); + wasm_v128_store(ptr + 4, v2); + wasm_v128_store(ptr + 6, v3); +} + +#define OPENCV_HAL_IMPL_WASM_LOADSTORE_INTERLEAVE(_Tpvec0, _Tp0, suffix0, _Tpvec1, _Tp1, suffix1) \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0 ) \ +{ \ + _Tpvec1 a1, b1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ +} \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0 ) \ +{ \ + _Tpvec1 a1, b1, c1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ + c0 = v_reinterpret_as_##suffix0(c1); \ +} \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0, _Tpvec0& d0 ) \ +{ \ + _Tpvec1 a1, b1, c1, d1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1, d1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ + c0 = v_reinterpret_as_##suffix0(c1); \ + d0 = v_reinterpret_as_##suffix0(d1); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + hal::StoreMode mode = hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, mode); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + const _Tpvec0& c0, hal::StoreMode mode = hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, c1, mode); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + const _Tpvec0& c0, const _Tpvec0& d0, \ + hal::StoreMode mode = hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ + _Tpvec1 d1 = v_reinterpret_as_##suffix1(d0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, c1, d1, mode); \ +} + +OPENCV_HAL_IMPL_WASM_LOADSTORE_INTERLEAVE(v_int8x16, schar, s8, v_uint8x16, uchar, u8) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INTERLEAVE(v_int16x8, short, s16, v_uint16x8, ushort, u16) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INTERLEAVE(v_int32x4, int, s32, v_uint32x4, unsigned, u32) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INTERLEAVE(v_int64x2, int64, s64, v_uint64x2, uint64, u64) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INTERLEAVE(v_float64x2, double, f64, v_uint64x2, uint64, u64) + +inline v_float32x4 v_cvt_f32(const v_int32x4& a) +{ + return v_float32x4(wasm_f32x4_convert_i32x4(a.val)); +} + +inline v_float32x4 v_cvt_f32(const v_float64x2& a) +{ + double a_[2]; + wasm_v128_store(a_, a.val); + float c_[4]; + c_[0] = (float)(a_[0]); + c_[1] = (float)(a_[1]); + c_[2] = 0; + c_[3] = 0; + return v_float32x4(wasm_v128_load(c_)); +} + +inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) +{ + double a_[2], b_[2]; + wasm_v128_store(a_, a.val); + wasm_v128_store(b_, b.val); + float c_[4]; + c_[0] = (float)(a_[0]); + c_[1] = (float)(a_[1]); + c_[2] = (float)(b_[0]); + c_[3] = (float)(b_[1]); + return v_float32x4(wasm_v128_load(c_)); +} + +inline v_float64x2 v_cvt_f64(const v_int32x4& a) +{ +#ifdef __wasm_unimplemented_simd128__ + v128_t p = v128_cvti32x4_i64x2(a.val); + return v_float64x2(wasm_f64x2_convert_i64x2(p)); +#else + int a_[4]; + wasm_v128_store(a_, a.val); + double c_[2]; + c_[0] = (double)(a_[0]); + c_[1] = (double)(a_[1]); + return v_float64x2(wasm_v128_load(c_)); +#endif +} + +inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) +{ +#ifdef __wasm_unimplemented_simd128__ + v128_t p = v128_cvti32x4_i64x2_high(a.val); + return v_float64x2(wasm_f64x2_convert_i64x2(p)); +#else + int a_[4]; + wasm_v128_store(a_, a.val); + double c_[2]; + c_[0] = (double)(a_[2]); + c_[1] = (double)(a_[3]); + return v_float64x2(wasm_v128_load(c_)); +#endif +} + +inline v_float64x2 v_cvt_f64(const v_float32x4& a) +{ + float a_[4]; + wasm_v128_store(a_, a.val); + double c_[2]; + c_[0] = (double)(a_[0]); + c_[1] = (double)(a_[1]); + return v_float64x2(wasm_v128_load(c_)); +} + +inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) +{ + float a_[4]; + wasm_v128_store(a_, a.val); + double c_[2]; + c_[0] = (double)(a_[2]); + c_[1] = (double)(a_[3]); + return v_float64x2(wasm_v128_load(c_)); +} + +inline v_float64x2 v_cvt_f64(const v_int64x2& a) +{ +#ifdef __wasm_unimplemented_simd128__ + return v_float64x2(wasm_f64x2_convert_i64x2(a.val)); +#else + int64 a_[2]; + wasm_v128_store(a_, a.val); + double c_[2]; + c_[0] = (double)(a_[0]); + c_[1] = (double)(a_[1]); + return v_float64x2(wasm_v128_load(c_)); +#endif +} + +////////////// Lookup table access //////////////////// + +inline v_int8x16 v_lut(const schar* tab, const int* idx) +{ + return v_int8x16(tab[idx[0]], tab[idx[1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], tab[idx[ 5]], tab[idx[ 6]], tab[idx[ 7]], + tab[idx[8]], tab[idx[9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]]); +} +inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx) +{ + return v_int8x16(tab[idx[0]], tab[idx[0]+1], tab[idx[1]], tab[idx[1]+1], tab[idx[2]], tab[idx[2]+1], tab[idx[3]], tab[idx[3]+1], + tab[idx[4]], tab[idx[4]+1], tab[idx[5]], tab[idx[5]+1], tab[idx[6]], tab[idx[6]+1], tab[idx[7]], tab[idx[7]+1]); +} +inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) +{ + return v_int8x16(tab[idx[0]], tab[idx[0]+1], tab[idx[0]+2], tab[idx[0]+3], tab[idx[1]], tab[idx[1]+1], tab[idx[1]+2], tab[idx[1]+3], + tab[idx[2]], tab[idx[2]+1], tab[idx[2]+2], tab[idx[2]+3], tab[idx[3]], tab[idx[3]+1], tab[idx[3]+2], tab[idx[3]+3]); +} +inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((const schar *)tab, idx)); } +inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((const schar *)tab, idx)); } +inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((const schar *)tab, idx)); } + +inline v_int16x8 v_lut(const short* tab, const int* idx) +{ + return v_int16x8(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], + tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]]); +} +inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) +{ + return v_int16x8(tab[idx[0]], tab[idx[0]+1], tab[idx[1]], tab[idx[1]+1], + tab[idx[2]], tab[idx[2]+1], tab[idx[3]], tab[idx[3]+1]); +} +inline v_int16x8 v_lut_quads(const short* tab, const int* idx) +{ + return v_int16x8(tab[idx[0]], tab[idx[0]+1], tab[idx[0]+2], tab[idx[0]+3], + tab[idx[1]], tab[idx[1]+1], tab[idx[1]+2], tab[idx[1]+3]); +} +inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((const short *)tab, idx)); } +inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((const short *)tab, idx)); } +inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((const short *)tab, idx)); } + +inline v_int32x4 v_lut(const int* tab, const int* idx) +{ + return v_int32x4(tab[idx[0]], tab[idx[1]], + tab[idx[2]], tab[idx[3]]); +} +inline v_int32x4 v_lut_pairs(const int* tab, const int* idx) +{ + return v_int32x4(tab[idx[0]], tab[idx[0]+1], + tab[idx[1]], tab[idx[1]+1]); +} +inline v_int32x4 v_lut_quads(const int* tab, const int* idx) +{ + return v_int32x4(wasm_v128_load(tab + idx[0])); +} +inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((const int *)tab, idx)); } +inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((const int *)tab, idx)); } +inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((const int *)tab, idx)); } + +inline v_int64x2 v_lut(const int64_t* tab, const int* idx) +{ + return v_int64x2(tab[idx[0]], tab[idx[1]]); +} +inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) +{ + return v_int64x2(wasm_v128_load(tab + idx[0])); +} +inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } +inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } + +inline v_float32x4 v_lut(const float* tab, const int* idx) +{ + return v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); +} +inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) { return v_reinterpret_as_f32(v_lut_pairs((const int *)tab, idx)); } +inline v_float32x4 v_lut_quads(const float* tab, const int* idx) { return v_reinterpret_as_f32(v_lut_quads((const int *)tab, idx)); } + +inline v_float64x2 v_lut(const double* tab, const int* idx) +{ + return v_float64x2(tab[idx[0]], tab[idx[1]]); +} +inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) +{ + return v_float64x2(wasm_v128_load(tab + idx[0])); +} + +inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) +{ + return v_int32x4(tab[wasm_i32x4_extract_lane(idxvec.val, 0)], + tab[wasm_i32x4_extract_lane(idxvec.val, 1)], + tab[wasm_i32x4_extract_lane(idxvec.val, 2)], + tab[wasm_i32x4_extract_lane(idxvec.val, 3)]); +} + +inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) +{ + return v_reinterpret_as_u32(v_lut((const int *)tab, idxvec)); +} + +inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) +{ + return v_float32x4(tab[wasm_i32x4_extract_lane(idxvec.val, 0)], + tab[wasm_i32x4_extract_lane(idxvec.val, 1)], + tab[wasm_i32x4_extract_lane(idxvec.val, 2)], + tab[wasm_i32x4_extract_lane(idxvec.val, 3)]); +} + +inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) +{ + return v_float64x2(tab[wasm_i32x4_extract_lane(idxvec.val, 0)], + tab[wasm_i32x4_extract_lane(idxvec.val, 1)]); +} + +// loads pairs from the table and deinterleaves them, e.g. returns: +// x = (tab[idxvec[0], tab[idxvec[1]], tab[idxvec[2]], tab[idxvec[3]]), +// y = (tab[idxvec[0]+1], tab[idxvec[1]+1], tab[idxvec[2]+1], tab[idxvec[3]+1]) +// note that the indices are float's indices, not the float-pair indices. +// in theory, this function can be used to implement bilinear interpolation, +// when idxvec are the offsets within the image. +inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) +{ + x = v_float32x4(tab[wasm_i32x4_extract_lane(idxvec.val, 0)], + tab[wasm_i32x4_extract_lane(idxvec.val, 1)], + tab[wasm_i32x4_extract_lane(idxvec.val, 2)], + tab[wasm_i32x4_extract_lane(idxvec.val, 3)]); + y = v_float32x4(tab[wasm_i32x4_extract_lane(idxvec.val, 0)+1], + tab[wasm_i32x4_extract_lane(idxvec.val, 1)+1], + tab[wasm_i32x4_extract_lane(idxvec.val, 2)+1], + tab[wasm_i32x4_extract_lane(idxvec.val, 3)+1]); +} + +inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) +{ + v128_t xy0 = wasm_v128_load(tab + wasm_i32x4_extract_lane(idxvec.val, 0)); + v128_t xy1 = wasm_v128_load(tab + wasm_i32x4_extract_lane(idxvec.val, 1)); + x.val = wasm_unpacklo_i64x2(xy0, xy1); + y.val = wasm_unpacklo_i64x2(xy0, xy1); +} + +inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) +{ + return v_int8x16(wasm_i8x16_shuffle(vec.val, vec.val, 0,2,1,3,4,6,5,7,8,10,9,11,12,14,13,15)); +} +inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } +inline v_int8x16 v_interleave_quads(const v_int8x16& vec) +{ + return v_int8x16(wasm_i8x16_shuffle(vec.val, vec.val, 0,4,1,5,2,6,3,7,8,12,9,13,10,14,11,15)); +} +inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) +{ + return v_int16x8(wasm_i8x16_shuffle(vec.val, vec.val, 0,1,4,5,2,3,6,7,8,9,12,13,10,11,14,15)); +} +inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } +inline v_int16x8 v_interleave_quads(const v_int16x8& vec) +{ + return v_int16x8(wasm_i8x16_shuffle(vec.val, vec.val, 0,1,8,9,2,3,10,11,4,5,12,13,6,7,14,15)); +} +inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) +{ + return v_int32x4(wasm_i8x16_shuffle(vec.val, vec.val, 0,1,2,3,8,9,10,11,4,5,6,7,12,13,14,15)); +} +inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } +inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) +{ + return v_float32x4(wasm_i8x16_shuffle(vec.val, vec.val, 0,1,2,3,8,9,10,11,4,5,6,7,12,13,14,15)); +} + +inline v_int8x16 v_pack_triplets(const v_int8x16& vec) +{ + return v_int8x16(wasm_i8x16_shuffle(vec.val, vec.val, 0,1,2,4,5,6,8,9,10,12,13,14,16,16,16,16)); +} +inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_pack_triplets(const v_int16x8& vec) +{ + return v_int16x8(wasm_i8x16_shuffle(vec.val, vec.val, 0,1,2,3,4,5,8,9,10,11,12,13,14,15,6,7)); +} +inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } +inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } +inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } + +template +inline typename _Tp::lane_type v_extract_n(const _Tp& a) +{ + return v_rotate_right(a).get0(); +} + +template +inline v_uint32x4 v_broadcast_element(const v_uint32x4& a) +{ + return v_setall_u32(v_extract_n(a)); +} +template +inline v_int32x4 v_broadcast_element(const v_int32x4& a) +{ + return v_setall_s32(v_extract_n(a)); +} +template +inline v_float32x4 v_broadcast_element(const v_float32x4& a) +{ + return v_setall_f32(v_extract_n(a)); +} + + +////////////// FP16 support /////////////////////////// + +inline v_float32x4 v_load_expand(const hfloat* ptr) +{ + float a[4]; + for (int i = 0; i < 4; i++) + a[i] = ptr[i]; + return v_float32x4(wasm_v128_load(a)); +} + +inline void v_pack_store(hfloat* ptr, const v_float32x4& v) +{ + double v_[4]; + wasm_v128_store(v_, v.val); + ptr[0] = hfloat(v_[0]); + ptr[1] = hfloat(v_[1]); + ptr[2] = hfloat(v_[2]); + ptr[3] = hfloat(v_[3]); +} + +inline void v_cleanup() {} + +#include "intrin_math.hpp" +inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } +inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } +inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } +inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } +inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } +inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } + +inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } +inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } +inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } +inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } +inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/msa_macros.h b/3rdParty/opencv-4.11.0/opencv2/core/hal/msa_macros.h index fad8c5adda..b856e3e4cd 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/msa_macros.h +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/msa_macros.h @@ -1,1558 +1,1558 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_HAL_MSA_MACROS_H -#define OPENCV_CORE_HAL_MSA_MACROS_H - -#ifdef __mips_msa -#include "msa.h" -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* Define 64 bits vector types */ -typedef signed char v8i8 __attribute__ ((vector_size(8), aligned(8))); -typedef unsigned char v8u8 __attribute__ ((vector_size(8), aligned(8))); -typedef short v4i16 __attribute__ ((vector_size(8), aligned(8))); -typedef unsigned short v4u16 __attribute__ ((vector_size(8), aligned(8))); -typedef int v2i32 __attribute__ ((vector_size(8), aligned(8))); -typedef unsigned int v2u32 __attribute__ ((vector_size(8), aligned(8))); -typedef long long v1i64 __attribute__ ((vector_size(8), aligned(8))); -typedef unsigned long long v1u64 __attribute__ ((vector_size(8), aligned(8))); -typedef float v2f32 __attribute__ ((vector_size(8), aligned(8))); -typedef double v1f64 __attribute__ ((vector_size(8), aligned(8))); - - -/* Load values from the given memory a 64-bit vector. */ -#define msa_ld1_s8(__a) (*((v8i8*)(__a))) -#define msa_ld1_s16(__a) (*((v4i16*)(__a))) -#define msa_ld1_s32(__a) (*((v2i32*)(__a))) -#define msa_ld1_s64(__a) (*((v1i64*)(__a))) -#define msa_ld1_u8(__a) (*((v8u8*)(__a))) -#define msa_ld1_u16(__a) (*((v4u16*)(__a))) -#define msa_ld1_u32(__a) (*((v2u32*)(__a))) -#define msa_ld1_u64(__a) (*((v1u64*)(__a))) -#define msa_ld1_f32(__a) (*((v2f32*)(__a))) -#define msa_ld1_f64(__a) (*((v1f64*)(__a))) - -/* Load values from the given memory address to a 128-bit vector */ -#define msa_ld1q_s8(__a) ((v16i8)__builtin_msa_ld_b(__a, 0)) -#define msa_ld1q_s16(__a) ((v8i16)__builtin_msa_ld_h(__a, 0)) -#define msa_ld1q_s32(__a) ((v4i32)__builtin_msa_ld_w(__a, 0)) -#define msa_ld1q_s64(__a) ((v2i64)__builtin_msa_ld_d(__a, 0)) -#define msa_ld1q_u8(__a) ((v16u8)__builtin_msa_ld_b(__a, 0)) -#define msa_ld1q_u16(__a) ((v8u16)__builtin_msa_ld_h(__a, 0)) -#define msa_ld1q_u32(__a) ((v4u32)__builtin_msa_ld_w(__a, 0)) -#define msa_ld1q_u64(__a) ((v2u64)__builtin_msa_ld_d(__a, 0)) -#define msa_ld1q_f32(__a) ((v4f32)__builtin_msa_ld_w(__a, 0)) -#define msa_ld1q_f64(__a) ((v2f64)__builtin_msa_ld_d(__a, 0)) - -/* Store 64bits vector elements values to the given memory address. */ -#define msa_st1_s8(__a, __b) (*((v8i8*)(__a)) = __b) -#define msa_st1_s16(__a, __b) (*((v4i16*)(__a)) = __b) -#define msa_st1_s32(__a, __b) (*((v2i32*)(__a)) = __b) -#define msa_st1_s64(__a, __b) (*((v1i64*)(__a)) = __b) -#define msa_st1_u8(__a, __b) (*((v8u8*)(__a)) = __b) -#define msa_st1_u16(__a, __b) (*((v4u16*)(__a)) = __b) -#define msa_st1_u32(__a, __b) (*((v2u32*)(__a)) = __b) -#define msa_st1_u64(__a, __b) (*((v1u64*)(__a)) = __b) -#define msa_st1_f32(__a, __b) (*((v2f32*)(__a)) = __b) -#define msa_st1_f64(__a, __b) (*((v1f64*)(__a)) = __b) - -/* Store the values of elements in the 128 bits vector __a to the given memory address __a. */ -#define msa_st1q_s8(__a, __b) (__builtin_msa_st_b((v16i8)(__b), __a, 0)) -#define msa_st1q_s16(__a, __b) (__builtin_msa_st_h((v8i16)(__b), __a, 0)) -#define msa_st1q_s32(__a, __b) (__builtin_msa_st_w((v4i32)(__b), __a, 0)) -#define msa_st1q_s64(__a, __b) (__builtin_msa_st_d((v2i64)(__b), __a, 0)) -#define msa_st1q_u8(__a, __b) (__builtin_msa_st_b((v16i8)(__b), __a, 0)) -#define msa_st1q_u16(__a, __b) (__builtin_msa_st_h((v8i16)(__b), __a, 0)) -#define msa_st1q_u32(__a, __b) (__builtin_msa_st_w((v4i32)(__b), __a, 0)) -#define msa_st1q_u64(__a, __b) (__builtin_msa_st_d((v2i64)(__b), __a, 0)) -#define msa_st1q_f32(__a, __b) (__builtin_msa_st_w((v4i32)(__b), __a, 0)) -#define msa_st1q_f64(__a, __b) (__builtin_msa_st_d((v2i64)(__b), __a, 0)) - -/* Store the value of the element with the index __c in vector __a to the given memory address __a. */ -#define msa_st1_lane_s8(__a, __b, __c) (*((int8_t*)(__a)) = __b[__c]) -#define msa_st1_lane_s16(__a, __b, __c) (*((int16_t*)(__a)) = __b[__c]) -#define msa_st1_lane_s32(__a, __b, __c) (*((int32_t*)(__a)) = __b[__c]) -#define msa_st1_lane_s64(__a, __b, __c) (*((int64_t*)(__a)) = __b[__c]) -#define msa_st1_lane_u8(__a, __b, __c) (*((uint8_t*)(__a)) = __b[__c]) -#define msa_st1_lane_u16(__a, __b, __c) (*((uint16_t*)(__a)) = __b[__c]) -#define msa_st1_lane_u32(__a, __b, __c) (*((uint32_t*)(__a)) = __b[__c]) -#define msa_st1_lane_u64(__a, __b, __c) (*((uint64_t*)(__a)) = __b[__c]) -#define msa_st1_lane_f32(__a, __b, __c) (*((float*)(__a)) = __b[__c]) -#define msa_st1_lane_f64(__a, __b, __c) (*((double*)(__a)) = __b[__c]) -#define msa_st1q_lane_s8(__a, __b, __c) (*((int8_t*)(__a)) = (int8_t)__builtin_msa_copy_s_b(__b, __c)) -#define msa_st1q_lane_s16(__a, __b, __c) (*((int16_t*)(__a)) = (int16_t)__builtin_msa_copy_s_h(__b, __c)) -#define msa_st1q_lane_s32(__a, __b, __c) (*((int32_t*)(__a)) = __builtin_msa_copy_s_w(__b, __c)) -#define msa_st1q_lane_s64(__a, __b, __c) (*((int64_t*)(__a)) = __builtin_msa_copy_s_d(__b, __c)) -#define msa_st1q_lane_u8(__a, __b, __c) (*((uint8_t*)(__a)) = (uint8_t)__builtin_msa_copy_u_b((v16i8)(__b), __c)) -#define msa_st1q_lane_u16(__a, __b, __c) (*((uint16_t*)(__a)) = (uint16_t)__builtin_msa_copy_u_h((v8i16)(__b), __c)) -#define msa_st1q_lane_u32(__a, __b, __c) (*((uint32_t*)(__a)) = __builtin_msa_copy_u_w((v4i32)(__b), __c)) -#define msa_st1q_lane_u64(__a, __b, __c) (*((uint64_t*)(__a)) = __builtin_msa_copy_u_d((v2i64)(__b), __c)) -#define msa_st1q_lane_f32(__a, __b, __c) (*((float*)(__a)) = __b[__c]) -#define msa_st1q_lane_f64(__a, __b, __c) (*((double*)(__a)) = __b[__c]) - -/* Duplicate elements for 64-bit doubleword vectors */ -#define msa_dup_n_s8(__a) ((v8i8)__builtin_msa_copy_s_d((v2i64)__builtin_msa_fill_b((int32_t)(__a)), 0)) -#define msa_dup_n_s16(__a) ((v4i16)__builtin_msa_copy_s_d((v2i64)__builtin_msa_fill_h((int32_t)(__a)), 0)) -#define msa_dup_n_s32(__a) ((v2i32){__a, __a}) -#define msa_dup_n_s64(__a) ((v1i64){__a}) -#define msa_dup_n_u8(__a) ((v8u8)__builtin_msa_copy_u_d((v2i64)__builtin_msa_fill_b((int32_t)(__a)), 0)) -#define msa_dup_n_u16(__a) ((v4u16)__builtin_msa_copy_u_d((v2i64)__builtin_msa_fill_h((int32_t)(__a)), 0)) -#define msa_dup_n_u32(__a) ((v2u32){__a, __a}) -#define msa_dup_n_u64(__a) ((v1u64){__a}) -#define msa_dup_n_f32(__a) ((v2f32){__a, __a}) -#define msa_dup_n_f64(__a) ((v1f64){__a}) - -/* Duplicate elements for 128-bit quadword vectors */ -#define msa_dupq_n_s8(__a) (__builtin_msa_fill_b((int32_t)(__a))) -#define msa_dupq_n_s16(__a) (__builtin_msa_fill_h((int32_t)(__a))) -#define msa_dupq_n_s32(__a) (__builtin_msa_fill_w((int32_t)(__a))) -#define msa_dupq_n_s64(__a) (__builtin_msa_fill_d((int64_t)(__a))) -#define msa_dupq_n_u8(__a) ((v16u8)__builtin_msa_fill_b((int32_t)(__a))) -#define msa_dupq_n_u16(__a) ((v8u16)__builtin_msa_fill_h((int32_t)(__a))) -#define msa_dupq_n_u32(__a) ((v4u32)__builtin_msa_fill_w((int32_t)(__a))) -#define msa_dupq_n_u64(__a) ((v2u64)__builtin_msa_fill_d((int64_t)(__a))) -#define msa_dupq_n_f32(__a) ((v4f32){__a, __a, __a, __a}) -#define msa_dupq_n_f64(__a) ((v2f64){__a, __a}) -#define msa_dupq_lane_s8(__a, __b) (__builtin_msa_splat_b(__a, __b)) -#define msa_dupq_lane_s16(__a, __b) (__builtin_msa_splat_h(__a, __b)) -#define msa_dupq_lane_s32(__a, __b) (__builtin_msa_splat_w(__a, __b)) -#define msa_dupq_lane_s64(__a, __b) (__builtin_msa_splat_d(__a, __b)) -#define msa_dupq_lane_u8(__a, __b) ((v16u8)__builtin_msa_splat_b((v16i8)(__a), __b)) -#define msa_dupq_lane_u16(__a, __b) ((v8u16)__builtin_msa_splat_h((v8i16)(__a), __b)) -#define msa_dupq_lane_u32(__a, __b) ((v4u32)__builtin_msa_splat_w((v4i32)(__a), __b)) -#define msa_dupq_lane_u64(__a, __b) ((v2u64)__builtin_msa_splat_d((v2i64)(__a), __b)) - -/* Create a 64 bits vector */ -#define msa_create_s8(__a) ((v8i8)((uint64_t)(__a))) -#define msa_create_s16(__a) ((v4i16)((uint64_t)(__a))) -#define msa_create_s32(__a) ((v2i32)((uint64_t)(__a))) -#define msa_create_s64(__a) ((v1i64)((uint64_t)(__a))) -#define msa_create_u8(__a) ((v8u8)((uint64_t)(__a))) -#define msa_create_u16(__a) ((v4u16)((uint64_t)(__a))) -#define msa_create_u32(__a) ((v2u32)((uint64_t)(__a))) -#define msa_create_u64(__a) ((v1u64)((uint64_t)(__a))) -#define msa_create_f32(__a) ((v2f32)((uint64_t)(__a))) -#define msa_create_f64(__a) ((v1f64)((uint64_t)(__a))) - -/* Sign extends or zero extends each element in a 64 bits vector to twice its original length, and places the results in a 128 bits vector. */ -/*Transform v8i8 to v8i16*/ -#define msa_movl_s8(__a) \ -((v8i16){(__a)[0], (__a)[1], (__a)[2], (__a)[3], \ - (__a)[4], (__a)[5], (__a)[6], (__a)[7]}) - -/*Transform v8u8 to v8u16*/ -#define msa_movl_u8(__a) \ -((v8u16){(__a)[0], (__a)[1], (__a)[2], (__a)[3], \ - (__a)[4], (__a)[5], (__a)[6], (__a)[7]}) - -/*Transform v4i16 to v8i16*/ -#define msa_movl_s16(__a) ((v4i32){(__a)[0], (__a)[1], (__a)[2], (__a)[3]}) - -/*Transform v2i32 to v4i32*/ -#define msa_movl_s32(__a) ((v2i64){(__a)[0], (__a)[1]}) - -/*Transform v4u16 to v8u16*/ -#define msa_movl_u16(__a) ((v4u32){(__a)[0], (__a)[1], (__a)[2], (__a)[3]}) - -/*Transform v2u32 to v4u32*/ -#define msa_movl_u32(__a) ((v2u64){(__a)[0], (__a)[1]}) - -/* Copies the least significant half of each element of a 128 bits vector into the corresponding elements of a 64 bits vector. */ -#define msa_movn_s16(__a) \ -({ \ - v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)(__a)); \ - (v8i8)__builtin_msa_copy_s_d((v2i64)__d, 0); \ -}) - -#define msa_movn_s32(__a) \ -({ \ - v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)(__a)); \ - (v4i16)__builtin_msa_copy_s_d((v2i64)__d, 0); \ -}) - -#define msa_movn_s64(__a) \ -({ \ - v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)(__a)); \ - (v2i32)__builtin_msa_copy_s_d((v2i64)__d, 0); \ -}) - -#define msa_movn_u16(__a) \ -({ \ - v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)(__a)); \ - (v8u8)__builtin_msa_copy_u_d((v2i64)__d, 0); \ -}) - -#define msa_movn_u32(__a) \ -({ \ - v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)(__a)); \ - (v4u16)__builtin_msa_copy_u_d((v2i64)__d, 0); \ -}) - -#define msa_movn_u64(__a) \ -({ \ - v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)(__a)); \ - (v2u32)__builtin_msa_copy_u_d((v2i64)__d, 0); \ -}) - -/* qmovn */ -#define msa_qmovn_s16(__a) \ -({ \ - v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_sat_s_h((v8i16)(__a), 7)); \ - (v8i8)__builtin_msa_copy_s_d((v2i64)__d, 0); \ -}) - -#define msa_qmovn_s32(__a) \ -({ \ - v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_sat_s_w((v4i32)(__a), 15)); \ - (v4i16)__builtin_msa_copy_s_d((v2i64)__d, 0); \ -}) - -#define msa_qmovn_s64(__a) \ -({ \ - v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_sat_s_d((v2i64)(__a), 31)); \ - (v2i32)__builtin_msa_copy_s_d((v2i64)__d, 0); \ -}) - -#define msa_qmovn_u16(__a) \ -({ \ - v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_sat_u_h((v8u16)(__a), 7)); \ - (v8u8)__builtin_msa_copy_u_d((v2i64)__d, 0); \ -}) - -#define msa_qmovn_u32(__a) \ -({ \ - v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_sat_u_w((v4u32)(__a), 15)); \ - (v4u16)__builtin_msa_copy_u_d((v2i64)__d, 0); \ -}) - -#define msa_qmovn_u64(__a) \ -({ \ - v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_sat_u_d((v2u64)(__a), 31)); \ - (v2u32)__builtin_msa_copy_u_d((v2i64)__d, 0); \ -}) - -/* qmovun */ -#define msa_qmovun_s16(__a) \ -({ \ - v8i16 __d = __builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__a)); \ - v16i8 __e = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_sat_u_h((v8u16)__d, 7)); \ - (v8u8)__builtin_msa_copy_u_d((v2i64)__e, 0); \ -}) - -#define msa_qmovun_s32(__a) \ -({ \ - v4i32 __d = __builtin_msa_max_s_w(__builtin_msa_fill_w(0), (v4i32)(__a)); \ - v8i16 __e = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_sat_u_w((v4u32)__d, 15)); \ - (v4u16)__builtin_msa_copy_u_d((v2i64)__e, 0); \ -}) - -#define msa_qmovun_s64(__a) \ -({ \ - v2i64 __d = __builtin_msa_max_s_d(__builtin_msa_fill_d(0), (v2i64)(__a)); \ - v4i32 __e = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_sat_u_d((v2u64)__d, 31)); \ - (v2u32)__builtin_msa_copy_u_d((v2i64)__e, 0); \ -}) - -/* Right shift elements in a 128 bits vector by an immediate value, and places the results in a 64 bits vector. */ -#define msa_shrn_n_s16(__a, __b) \ -({ \ - v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_srai_h((v8i16)(__a), (int)(__b))); \ - (v8i8)__builtin_msa_copy_s_d((v2i64)__d, 0); \ -}) - -#define msa_shrn_n_s32(__a, __b) \ -({ \ - v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_srai_w((v4i32)(__a), (int)(__b))); \ - (v4i16)__builtin_msa_copy_s_d((v2i64)__d, 0); \ -}) - -#define msa_shrn_n_s64(__a, __b) \ -({ \ - v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_srai_d((v2i64)(__a), (int)(__b))); \ - (v2i32)__builtin_msa_copy_s_d((v2i64)__d, 0); \ -}) - -#define msa_shrn_n_u16(__a, __b) \ -({ \ - v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_srli_h((v8i16)(__a), (int)(__b))); \ - (v8u8)__builtin_msa_copy_u_d((v2i64)__d, 0); \ -}) - -#define msa_shrn_n_u32(__a, __b) \ -({ \ - v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_srli_w((v4i32)(__a), (int)(__b))); \ - (v4u16)__builtin_msa_copy_u_d((v2i64)__d, 0); \ -}) - -#define msa_shrn_n_u64(__a, __b) \ -({ \ - v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_srli_d((v2i64)(__a), (int)(__b))); \ - (v2u32)__builtin_msa_copy_u_d((v2i64)__d, 0); \ -}) - -/* Right shift elements in a 128 bits vector by an immediate value, and places the results in a 64 bits vector. */ -#define msa_rshrn_n_s16(__a, __b) \ -({ \ - v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_srari_h((v8i16)(__a), (int)__b)); \ - (v8i8)__builtin_msa_copy_s_d((v2i64)__d, 0); \ -}) - -#define msa_rshrn_n_s32(__a, __b) \ -({ \ - v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_srari_w((v4i32)(__a), (int)__b)); \ - (v4i16)__builtin_msa_copy_s_d((v2i64)__d, 0); \ -}) - -#define msa_rshrn_n_s64(__a, __b) \ -({ \ - v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_srari_d((v2i64)(__a), (int)__b)); \ - (v2i32)__builtin_msa_copy_s_d((v2i64)__d, 0); \ -}) - -#define msa_rshrn_n_u16(__a, __b) \ -({ \ - v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_srlri_h((v8i16)(__a), (int)__b)); \ - (v8u8)__builtin_msa_copy_u_d((v2i64)__d, 0); \ -}) - -#define msa_rshrn_n_u32(__a, __b) \ -({ \ - v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_srlri_w((v4i32)(__a), (int)__b)); \ - (v4u16)__builtin_msa_copy_u_d((v2i64)__d, 0); \ -}) - -#define msa_rshrn_n_u64(__a, __b) \ -({ \ - v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_srlri_d((v2i64)(__a), (int)__b)); \ - (v2u32)__builtin_msa_copy_u_d((v2i64)__d, 0); \ -}) - -/* Right shift elements in a 128 bits vector by an immediate value, saturate the results and them in a 64 bits vector. */ -#define msa_qrshrn_n_s16(__a, __b) \ -({ \ - v8i16 __d = __builtin_msa_sat_s_h(__builtin_msa_srari_h((v8i16)(__a), (int)(__b)), 7); \ - v16i8 __e = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__d); \ - (v8i8)__builtin_msa_copy_s_d((v2i64)__e, 0); \ -}) - -#define msa_qrshrn_n_s32(__a, __b) \ -({ \ - v4i32 __d = __builtin_msa_sat_s_w(__builtin_msa_srari_w((v4i32)(__a), (int)(__b)), 15); \ - v8i16 __e = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__d); \ - (v4i16)__builtin_msa_copy_s_d((v2i64)__e, 0); \ -}) - -#define msa_qrshrn_n_s64(__a, __b) \ -({ \ - v2i64 __d = __builtin_msa_sat_s_d(__builtin_msa_srari_d((v2i64)(__a), (int)(__b)), 31); \ - v4i32 __e = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__d); \ - (v2i32)__builtin_msa_copy_s_d((v2i64)__e, 0); \ -}) - -#define msa_qrshrn_n_u16(__a, __b) \ -({ \ - v8u16 __d = __builtin_msa_sat_u_h((v8u16)__builtin_msa_srlri_h((v8i16)(__a), (int)(__b)), 7); \ - v16i8 __e = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__d); \ - (v8u8)__builtin_msa_copy_u_d((v2i64)__e, 0); \ -}) - -#define msa_qrshrn_n_u32(__a, __b) \ -({ \ - v4u32 __d = __builtin_msa_sat_u_w((v4u32)__builtin_msa_srlri_w((v4i32)(__a), (int)(__b)), 15); \ - v8i16 __e = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__d); \ - (v4u16)__builtin_msa_copy_u_d((v2i64)__e, 0); \ -}) - -#define msa_qrshrn_n_u64(__a, __b) \ -({ \ - v2u64 __d = __builtin_msa_sat_u_d((v2u64)__builtin_msa_srlri_d((v2i64)(__a), (int)(__b)), 31); \ - v4i32 __e = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__d); \ - (v2u32)__builtin_msa_copy_u_d((v2i64)__e, 0); \ -}) - -/* Right shift elements in a 128 bits vector by an immediate value, saturate the results and them in a 64 bits vector. - Input is signed and output is unsigned. */ -#define msa_qrshrun_n_s16(__a, __b) \ -({ \ - v8i16 __d = __builtin_msa_srlri_h(__builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__a)), (int)(__b)); \ - v16i8 __e = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_sat_u_h((v8u16)__d, 7)); \ - (v8u8)__builtin_msa_copy_u_d((v2i64)__e, 0); \ -}) - -#define msa_qrshrun_n_s32(__a, __b) \ -({ \ - v4i32 __d = __builtin_msa_srlri_w(__builtin_msa_max_s_w(__builtin_msa_fill_w(0), (v4i32)(__a)), (int)(__b)); \ - v8i16 __e = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_sat_u_w((v4u32)__d, 15)); \ - (v4u16)__builtin_msa_copy_u_d((v2i64)__e, 0); \ -}) - -#define msa_qrshrun_n_s64(__a, __b) \ -({ \ - v2i64 __d = __builtin_msa_srlri_d(__builtin_msa_max_s_d(__builtin_msa_fill_d(0), (v2i64)(__a)), (int)(__b)); \ - v4i32 __e = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_sat_u_d((v2u64)__d, 31)); \ - (v2u32)__builtin_msa_copy_u_d((v2i64)__e, 0); \ -}) - -/* pack */ -#define msa_pack_s16(__a, __b) (__builtin_msa_pckev_b((v16i8)(__b), (v16i8)(__a))) -#define msa_pack_s32(__a, __b) (__builtin_msa_pckev_h((v8i16)(__b), (v8i16)(__a))) -#define msa_pack_s64(__a, __b) (__builtin_msa_pckev_w((v4i32)(__b), (v4i32)(__a))) -#define msa_pack_u16(__a, __b) ((v16u8)__builtin_msa_pckev_b((v16i8)(__b), (v16i8)(__a))) -#define msa_pack_u32(__a, __b) ((v8u16)__builtin_msa_pckev_h((v8i16)(__b), (v8i16)(__a))) -#define msa_pack_u64(__a, __b) ((v4u32)__builtin_msa_pckev_w((v4i32)(__b), (v4i32)(__a))) - -/* qpack */ -#define msa_qpack_s16(__a, __b) \ -(__builtin_msa_pckev_b((v16i8)__builtin_msa_sat_s_h((v8i16)(__b), 7), (v16i8)__builtin_msa_sat_s_h((v8i16)(__a), 7))) -#define msa_qpack_s32(__a, __b) \ -(__builtin_msa_pckev_h((v8i16)__builtin_msa_sat_s_w((v4i32)(__b), 15), (v8i16)__builtin_msa_sat_s_w((v4i32)(__a), 15))) -#define msa_qpack_s64(__a, __b) \ -(__builtin_msa_pckev_w((v4i32)__builtin_msa_sat_s_d((v2i64)(__b), 31), (v4i32)__builtin_msa_sat_s_d((v2i64)(__a), 31))) -#define msa_qpack_u16(__a, __b) \ -((v16u8)__builtin_msa_pckev_b((v16i8)__builtin_msa_sat_u_h((v8u16)(__b), 7), (v16i8)__builtin_msa_sat_u_h((v8u16)(__a), 7))) -#define msa_qpack_u32(__a, __b) \ -((v8u16)__builtin_msa_pckev_h((v8i16)__builtin_msa_sat_u_w((v4u32)(__b), 15), (v8i16)__builtin_msa_sat_u_w((v4u32)(__a), 15))) -#define msa_qpack_u64(__a, __b) \ -((v4u32)__builtin_msa_pckev_w((v4i32)__builtin_msa_sat_u_d((v2u64)(__b), 31), (v4i32)__builtin_msa_sat_u_d((v2u64)(__a), 31))) - -/* qpacku */ -#define msa_qpacku_s16(__a, __b) \ -((v16u8)__builtin_msa_pckev_b((v16i8)__builtin_msa_sat_u_h((v8u16)(__builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__b))), 7), \ - (v16i8)__builtin_msa_sat_u_h((v8u16)(__builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__a))), 7))) -#define msa_qpacku_s32(__a, __b) \ -((v8u16)__builtin_msa_pckev_h((v8i16)__builtin_msa_sat_u_w((v4u32)(__builtin_msa_max_s_w(__builtin_msa_fill_w(0), (v4i32)(__b))), 15), \ - (v8i16)__builtin_msa_sat_u_w((v4u32)(__builtin_msa_max_s_w(__builtin_msa_fill_w(0), (v4i32)(__a))), 15))) -#define msa_qpacku_s64(__a, __b) \ -((v4u32)__builtin_msa_pckev_w((v4i32)__builtin_msa_sat_u_d((v2u64)(__builtin_msa_max_s_d(__builtin_msa_fill_d(0), (v2i64)(__b))), 31), \ - (v4i32)__builtin_msa_sat_u_d((v2u64)(__builtin_msa_max_s_d(__builtin_msa_fill_d(0), (v2i64)(__a))), 31))) - -/* packr */ -#define msa_packr_s16(__a, __b, __c) \ -(__builtin_msa_pckev_b((v16i8)__builtin_msa_srai_h((v8i16)(__b), (int)(__c)), (v16i8)__builtin_msa_srai_h((v8i16)(__a), (int)(__c)))) -#define msa_packr_s32(__a, __b, __c) \ -(__builtin_msa_pckev_h((v8i16)__builtin_msa_srai_w((v4i32)(__b), (int)(__c)), (v8i16)__builtin_msa_srai_w((v4i32)(__a), (int)(__c)))) -#define msa_packr_s64(__a, __b, __c) \ -(__builtin_msa_pckev_w((v4i32)__builtin_msa_srai_d((v2i64)(__b), (int)(__c)), (v4i32)__builtin_msa_srai_d((v2i64)(__a), (int)(__c)))) -#define msa_packr_u16(__a, __b, __c) \ -((v16u8)__builtin_msa_pckev_b((v16i8)__builtin_msa_srli_h((v8i16)(__b), (int)(__c)), (v16i8)__builtin_msa_srli_h((v8i16)(__a), (int)(__c)))) -#define msa_packr_u32(__a, __b, __c) \ -((v8u16)__builtin_msa_pckev_h((v8i16)__builtin_msa_srli_w((v4i32)(__b), (int)(__c)), (v8i16)__builtin_msa_srli_w((v4i32)(__a), (int)(__c)))) -#define msa_packr_u64(__a, __b, __c) \ -((v4u32)__builtin_msa_pckev_w((v4i32)__builtin_msa_srli_d((v2i64)(__b), (int)(__c)), (v4i32)__builtin_msa_srli_d((v2i64)(__a), (int)(__c)))) - -/* rpackr */ -#define msa_rpackr_s16(__a, __b, __c) \ -(__builtin_msa_pckev_b((v16i8)__builtin_msa_srari_h((v8i16)(__b), (int)(__c)), (v16i8)__builtin_msa_srari_h((v8i16)(__a), (int)(__c)))) -#define msa_rpackr_s32(__a, __b, __c) \ -(__builtin_msa_pckev_h((v8i16)__builtin_msa_srari_w((v4i32)(__b), (int)(__c)), (v8i16)__builtin_msa_srari_w((v4i32)(__a), (int)(__c)))) -#define msa_rpackr_s64(__a, __b, __c) \ -(__builtin_msa_pckev_w((v4i32)__builtin_msa_srari_d((v2i64)(__b), (int)(__c)), (v4i32)__builtin_msa_srari_d((v2i64)(__a), (int)(__c)))) -#define msa_rpackr_u16(__a, __b, __c) \ -((v16u8)__builtin_msa_pckev_b((v16i8)__builtin_msa_srlri_h((v8i16)(__b), (int)(__c)), (v16i8)__builtin_msa_srlri_h((v8i16)(__a), (int)(__c)))) -#define msa_rpackr_u32(__a, __b, __c) \ -((v8u16)__builtin_msa_pckev_h((v8i16)__builtin_msa_srlri_w((v4i32)(__b), (int)(__c)), (v8i16)__builtin_msa_srlri_w((v4i32)(__a), (int)(__c)))) -#define msa_rpackr_u64(__a, __b, __c) \ -((v4u32)__builtin_msa_pckev_w((v4i32)__builtin_msa_srlri_d((v2i64)(__b), (int)(__c)), (v4i32)__builtin_msa_srlri_d((v2i64)(__a), (int)(__c)))) - -/* qrpackr */ -#define msa_qrpackr_s16(__a, __b, __c) \ -(__builtin_msa_pckev_b((v16i8)__builtin_msa_sat_s_h(__builtin_msa_srari_h((v8i16)(__b), (int)(__c)), 7), \ - (v16i8)__builtin_msa_sat_s_h(__builtin_msa_srari_h((v8i16)(__a), (int)(__c)), 7))) -#define msa_qrpackr_s32(__a, __b, __c) \ -(__builtin_msa_pckev_h((v8i16)__builtin_msa_sat_s_w(__builtin_msa_srari_w((v4i32)(__b), (int)(__c)), 15), \ - (v8i16)__builtin_msa_sat_s_w(__builtin_msa_srari_w((v4i32)(__a), (int)(__c)), 15))) -#define msa_qrpackr_s64(__a, __b, __c) \ -(__builtin_msa_pckev_w((v4i32)__builtin_msa_sat_s_d(__builtin_msa_srari_d((v2i64)(__b), (int)(__c)), 31), \ - (v4i32)__builtin_msa_sat_s_d(__builtin_msa_srari_d((v2i64)(__a), (int)(__c)), 31))) -#define msa_qrpackr_u16(__a, __b, __c) \ -((v16u8)__builtin_msa_pckev_b((v16i8)__builtin_msa_sat_u_h((v8u16)__builtin_msa_srlri_h((v8i16)(__b), (int)(__c)), 7), \ - (v16i8)__builtin_msa_sat_u_h((v8u16)__builtin_msa_srlri_h((v8i16)(__a), (int)(__c)), 7))) -#define msa_qrpackr_u32(__a, __b, __c) \ -((v8u16)__builtin_msa_pckev_h((v8i16)__builtin_msa_sat_u_w((v4u32)__builtin_msa_srlri_w((v4i32)(__b), (int)(__c)), 15), \ - (v8i16)__builtin_msa_sat_u_w((v4u32)__builtin_msa_srlri_w((v4i32)(__a), (int)(__c)), 15))) -#define msa_qrpackr_u64(__a, __b, __c) \ -((v4u32)__builtin_msa_pckev_w((v4i32)__builtin_msa_sat_u_d((v2u64)__builtin_msa_srlri_d((v2i64)(__b), (int)(__c)), 31), \ - (v4i32)__builtin_msa_sat_u_d((v2u64)__builtin_msa_srlri_d((v2i64)(__a), (int)(__c)), 31))) - -/* qrpackru */ -#define msa_qrpackru_s16(__a, __b, __c) \ -({ \ - v8i16 __d = __builtin_msa_srlri_h(__builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__a)), (int)(__c)); \ - v8i16 __e = __builtin_msa_srlri_h(__builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__b)), (int)(__c)); \ - (v16u8)__builtin_msa_pckev_b((v16i8)__builtin_msa_sat_u_h((v8u16)__e, 7), (v16i8)__builtin_msa_sat_u_h((v8u16)__d, 7)); \ -}) - -#define msa_qrpackru_s32(__a, __b, __c) \ -({ \ - v4i32 __d = __builtin_msa_srlri_w(__builtin_msa_max_s_w(__builtin_msa_fill_w(0), (v4i32)(__a)), (int)(__c)); \ - v4i32 __e = __builtin_msa_srlri_w(__builtin_msa_max_s_w(__builtin_msa_fill_w(0), (v4i32)(__b)), (int)(__c)); \ - (v8u16)__builtin_msa_pckev_h((v8i16)__builtin_msa_sat_u_w((v4u32)__e, 15), (v8i16)__builtin_msa_sat_u_w((v4u32)__d, 15)); \ -}) - -#define msa_qrpackru_s64(__a, __b, __c) \ -({ \ - v2i64 __d = __builtin_msa_srlri_d(__builtin_msa_max_s_d(__builtin_msa_fill_d(0), (v2i64)(__a)), (int)(__c)); \ - v2i64 __e = __builtin_msa_srlri_d(__builtin_msa_max_s_d(__builtin_msa_fill_d(0), (v2i64)(__b)), (int)(__c)); \ - (v4u32)__builtin_msa_pckev_w((v4i32)__builtin_msa_sat_u_d((v2u64)__e, 31), (v4i32)__builtin_msa_sat_u_d((v2u64)__d, 31)); \ -}) - -/* Minimum values between corresponding elements in the two vectors are written to the returned vector. */ -#define msa_minq_s8(__a, __b) (__builtin_msa_min_s_b(__a, __b)) -#define msa_minq_s16(__a, __b) (__builtin_msa_min_s_h(__a, __b)) -#define msa_minq_s32(__a, __b) (__builtin_msa_min_s_w(__a, __b)) -#define msa_minq_s64(__a, __b) (__builtin_msa_min_s_d(__a, __b)) -#define msa_minq_u8(__a, __b) ((v16u8)__builtin_msa_min_u_b(__a, __b)) -#define msa_minq_u16(__a, __b) ((v8u16)__builtin_msa_min_u_h(__a, __b)) -#define msa_minq_u32(__a, __b) ((v4u32)__builtin_msa_min_u_w(__a, __b)) -#define msa_minq_u64(__a, __b) ((v2u64)__builtin_msa_min_u_d(__a, __b)) -#define msa_minq_f32(__a, __b) (__builtin_msa_fmin_w(__a, __b)) -#define msa_minq_f64(__a, __b) (__builtin_msa_fmin_d(__a, __b)) - -/* Maximum values between corresponding elements in the two vectors are written to the returned vector. */ -#define msa_maxq_s8(__a, __b) (__builtin_msa_max_s_b(__a, __b)) -#define msa_maxq_s16(__a, __b) (__builtin_msa_max_s_h(__a, __b)) -#define msa_maxq_s32(__a, __b) (__builtin_msa_max_s_w(__a, __b)) -#define msa_maxq_s64(__a, __b) (__builtin_msa_max_s_d(__a, __b)) -#define msa_maxq_u8(__a, __b) ((v16u8)__builtin_msa_max_u_b(__a, __b)) -#define msa_maxq_u16(__a, __b) ((v8u16)__builtin_msa_max_u_h(__a, __b)) -#define msa_maxq_u32(__a, __b) ((v4u32)__builtin_msa_max_u_w(__a, __b)) -#define msa_maxq_u64(__a, __b) ((v2u64)__builtin_msa_max_u_d(__a, __b)) -#define msa_maxq_f32(__a, __b) (__builtin_msa_fmax_w(__a, __b)) -#define msa_maxq_f64(__a, __b) (__builtin_msa_fmax_d(__a, __b)) - -/* Vector type reinterpretion */ -#define MSA_TPV_REINTERPRET(_Tpv, Vec) ((_Tpv)(Vec)) - -/* Add the odd elements in vector __a with the even elements in vector __b to double width elements in the returned vector. */ -/* v8i16 msa_hadd_s16 ((v16i8)__a, (v16i8)__b) */ -#define msa_hadd_s16(__a, __b) (__builtin_msa_hadd_s_h((v16i8)(__a), (v16i8)(__b))) -/* v4i32 msa_hadd_s32 ((v8i16)__a, (v8i16)__b) */ -#define msa_hadd_s32(__a, __b) (__builtin_msa_hadd_s_w((v8i16)(__a), (v8i16)(__b))) -/* v2i64 msa_hadd_s64 ((v4i32)__a, (v4i32)__b) */ -#define msa_hadd_s64(__a, __b) (__builtin_msa_hadd_s_d((v4i32)(__a), (v4i32)(__b))) - -/* Copy even elements in __a to the left half and even elements in __b to the right half and return the result vector. */ -#define msa_pckev_s8(__a, __b) (__builtin_msa_pckev_b((v16i8)(__a), (v16i8)(__b))) -#define msa_pckev_s16(__a, __b) (__builtin_msa_pckev_h((v8i16)(__a), (v8i16)(__b))) -#define msa_pckev_s32(__a, __b) (__builtin_msa_pckev_w((v4i32)(__a), (v4i32)(__b))) -#define msa_pckev_s64(__a, __b) (__builtin_msa_pckev_d((v2i64)(__a), (v2i64)(__b))) - -/* Copy even elements in __a to the left half and even elements in __b to the right half and return the result vector. */ -#define msa_pckod_s8(__a, __b) (__builtin_msa_pckod_b((v16i8)(__a), (v16i8)(__b))) -#define msa_pckod_s16(__a, __b) (__builtin_msa_pckod_h((v8i16)(__a), (v8i16)(__b))) -#define msa_pckod_s32(__a, __b) (__builtin_msa_pckod_w((v4i32)(__a), (v4i32)(__b))) -#define msa_pckod_s64(__a, __b) (__builtin_msa_pckod_d((v2i64)(__a), (v2i64)(__b))) - -#ifdef _MIPSEB -#define LANE_IMM0_1(x) (0b1 - ((x) & 0b1)) -#define LANE_IMM0_3(x) (0b11 - ((x) & 0b11)) -#define LANE_IMM0_7(x) (0b111 - ((x) & 0b111)) -#define LANE_IMM0_15(x) (0b1111 - ((x) & 0b1111)) -#else -#define LANE_IMM0_1(x) ((x) & 0b1) -#define LANE_IMM0_3(x) ((x) & 0b11) -#define LANE_IMM0_7(x) ((x) & 0b111) -#define LANE_IMM0_15(x) ((x) & 0b1111) -#endif - -#define msa_get_lane_u8(__a, __b) ((uint8_t)(__a)[LANE_IMM0_7(__b)]) -#define msa_get_lane_s8(__a, __b) ((int8_t)(__a)[LANE_IMM0_7(__b)]) -#define msa_get_lane_u16(__a, __b) ((uint16_t)(__a)[LANE_IMM0_3(__b)]) -#define msa_get_lane_s16(__a, __b) ((int16_t)(__a)[LANE_IMM0_3(__b)]) -#define msa_get_lane_u32(__a, __b) ((uint32_t)(__a)[LANE_IMM0_1(__b)]) -#define msa_get_lane_s32(__a, __b) ((int32_t)(__a)[LANE_IMM0_1(__b)]) -#define msa_get_lane_f32(__a, __b) ((float)(__a)[LANE_IMM0_3(__b)]) -#define msa_get_lane_s64(__a, __b) ((int64_t)(__a)[LANE_IMM0_1(__b)]) -#define msa_get_lane_u64(__a, __b) ((uint64_t)(__a)[LANE_IMM0_1(__b)]) -#define msa_get_lane_f64(__a, __b) ((double)(__a)[LANE_IMM0_1(__b)]) -#define msa_getq_lane_u8(__a, imm0_15) ((uint8_t)__builtin_msa_copy_u_b((v16i8)(__a), imm0_15)) -#define msa_getq_lane_s8(__a, imm0_15) ((int8_t)__builtin_msa_copy_s_b(__a, imm0_15)) -#define msa_getq_lane_u16(__a, imm0_7) ((uint16_t)__builtin_msa_copy_u_h((v8i16)(__a), imm0_7)) -#define msa_getq_lane_s16(__a, imm0_7) ((int16_t)__builtin_msa_copy_s_h(__a, imm0_7)) -#define msa_getq_lane_u32(__a, imm0_3) __builtin_msa_copy_u_w((v4i32)(__a), imm0_3) -#define msa_getq_lane_s32 __builtin_msa_copy_s_w -#define msa_getq_lane_f32(__a, __b) ((float)(__a)[LANE_IMM0_3(__b)]) -#define msa_getq_lane_f64(__a, __b) ((double)(__a)[LANE_IMM0_1(__b)]) -#if (__mips == 64) -#define msa_getq_lane_u64(__a, imm0_1) __builtin_msa_copy_u_d((v2i64)(__a), imm0_1) -#define msa_getq_lane_s64 __builtin_msa_copy_s_d -#else -#define msa_getq_lane_u64(__a, imm0_1) ((uint64_t)(__a)[LANE_IMM0_1(imm0_1)]) -#define msa_getq_lane_s64(__a, imm0_1) ((int64_t)(__a)[LANE_IMM0_1(imm0_1)]) -#endif - -/* combine */ -#if (__mips == 64) -#define __COMBINE_64_64(__TYPE, a, b) ((__TYPE)((v2u64){((v1u64)(a))[0], ((v1u64)(b))[0]})) -#else -#define __COMBINE_64_64(__TYPE, a, b) ((__TYPE)((v4u32){((v2u32)(a))[0], ((v2u32)(a))[1], \ - ((v2u32)(b))[0], ((v2u32)(b))[1]})) -#endif - -/* v16i8 msa_combine_s8 (v8i8 __a, v8i8 __b) */ -#define msa_combine_s8(__a, __b) __COMBINE_64_64(v16i8, __a, __b) - -/* v8i16 msa_combine_s16(v4i16 __a, v4i16 __b) */ -#define msa_combine_s16(__a, __b) __COMBINE_64_64(v8i16, __a, __b) - -/* v4i32 msa_combine_s32(v2i32 __a, v2i32 __b) */ -#define msa_combine_s32(__a, __b) __COMBINE_64_64(v4i32, __a, __b) - -/* v2i64 msa_combine_s64(v1i64 __a, v1i64 __b) */ -#define msa_combine_s64(__a, __b) __COMBINE_64_64(v2i64, __a, __b) - -/* v4f32 msa_combine_f32(v2f32 __a, v2f32 __b) */ -#define msa_combine_f32(__a, __b) __COMBINE_64_64(v4f32, __a, __b) - -/* v16u8 msa_combine_u8(v8u8 __a, v8u8 __b) */ -#define msa_combine_u8(__a, __b) __COMBINE_64_64(v16u8, __a, __b) - -/* v8u16 msa_combine_u16(v4u16 __a, v4u16 __b) */ -#define msa_combine_u16(__a, __b) __COMBINE_64_64(v8u16, __a, __b) - -/* v4u32 msa_combine_u32(v2u32 __a, v2u32 __b) */ -#define msa_combine_u32(__a, __b) __COMBINE_64_64(v4u32, __a, __b) - -/* v2u64 msa_combine_u64(v1u64 __a, v1u64 __b) */ -#define msa_combine_u64(__a, __b) __COMBINE_64_64(v2u64, __a, __b) - -/* v2f64 msa_combine_f64(v1f64 __a, v1f64 __b) */ -#define msa_combine_f64(__a, __b) __COMBINE_64_64(v2f64, __a, __b) - -/* get_low, get_high */ -#if (__mips == 64) -#define __GET_LOW(__TYPE, a) ((__TYPE)((v1u64)(__builtin_msa_copy_u_d((v2i64)(a), 0)))) -#define __GET_HIGH(__TYPE, a) ((__TYPE)((v1u64)(__builtin_msa_copy_u_d((v2i64)(a), 1)))) -#else -#define __GET_LOW(__TYPE, a) ((__TYPE)(((v2u64)(a))[0])) -#define __GET_HIGH(__TYPE, a) ((__TYPE)(((v2u64)(a))[1])) -#endif - -/* v8i8 msa_get_low_s8(v16i8 __a) */ -#define msa_get_low_s8(__a) __GET_LOW(v8i8, __a) - -/* v4i16 msa_get_low_s16(v8i16 __a) */ -#define msa_get_low_s16(__a) __GET_LOW(v4i16, __a) - -/* v2i32 msa_get_low_s32(v4i32 __a) */ -#define msa_get_low_s32(__a) __GET_LOW(v2i32, __a) - -/* v1i64 msa_get_low_s64(v2i64 __a) */ -#define msa_get_low_s64(__a) __GET_LOW(v1i64, __a) - -/* v8u8 msa_get_low_u8(v16u8 __a) */ -#define msa_get_low_u8(__a) __GET_LOW(v8u8, __a) - -/* v4u16 msa_get_low_u16(v8u16 __a) */ -#define msa_get_low_u16(__a) __GET_LOW(v4u16, __a) - -/* v2u32 msa_get_low_u32(v4u32 __a) */ -#define msa_get_low_u32(__a) __GET_LOW(v2u32, __a) - -/* v1u64 msa_get_low_u64(v2u64 __a) */ -#define msa_get_low_u64(__a) __GET_LOW(v1u64, __a) - -/* v2f32 msa_get_low_f32(v4f32 __a) */ -#define msa_get_low_f32(__a) __GET_LOW(v2f32, __a) - -/* v1f64 msa_get_low_f64(v2f64 __a) */ -#define msa_get_low_f64(__a) __GET_LOW(v1f64, __a) - -/* v8i8 msa_get_high_s8(v16i8 __a) */ -#define msa_get_high_s8(__a) __GET_HIGH(v8i8, __a) - -/* v4i16 msa_get_high_s16(v8i16 __a) */ -#define msa_get_high_s16(__a) __GET_HIGH(v4i16, __a) - -/* v2i32 msa_get_high_s32(v4i32 __a) */ -#define msa_get_high_s32(__a) __GET_HIGH(v2i32, __a) - -/* v1i64 msa_get_high_s64(v2i64 __a) */ -#define msa_get_high_s64(__a) __GET_HIGH(v1i64, __a) - -/* v8u8 msa_get_high_u8(v16u8 __a) */ -#define msa_get_high_u8(__a) __GET_HIGH(v8u8, __a) - -/* v4u16 msa_get_high_u16(v8u16 __a) */ -#define msa_get_high_u16(__a) __GET_HIGH(v4u16, __a) - -/* v2u32 msa_get_high_u32(v4u32 __a) */ -#define msa_get_high_u32(__a) __GET_HIGH(v2u32, __a) - -/* v1u64 msa_get_high_u64(v2u64 __a) */ -#define msa_get_high_u64(__a) __GET_HIGH(v1u64, __a) - -/* v2f32 msa_get_high_f32(v4f32 __a) */ -#define msa_get_high_f32(__a) __GET_HIGH(v2f32, __a) - -/* v1f64 msa_get_high_f64(v2f64 __a) */ -#define msa_get_high_f64(__a) __GET_HIGH(v1f64, __a) - -/* ri = ai * b[lane] */ -/* v4f32 msa_mulq_lane_f32(v4f32 __a, v4f32 __b, const int __lane) */ -#define msa_mulq_lane_f32(__a, __b, __lane) ((__a) * msa_getq_lane_f32(__b, __lane)) - -/* ri = ai + bi * c[lane] */ -/* v4f32 msa_mlaq_lane_f32(v4f32 __a, v4f32 __b, v4f32 __c, const int __lane) */ -#define msa_mlaq_lane_f32(__a, __b, __c, __lane) ((__a) + ((__b) * msa_getq_lane_f32(__c, __lane))) - -/* uint16_t msa_sum_u16(v8u16 __a)*/ -#define msa_sum_u16(__a) \ -({ \ - v4u32 _b; \ - v2u64 _c; \ - _b = __builtin_msa_hadd_u_w(__a, __a); \ - _c = __builtin_msa_hadd_u_d(_b, _b); \ - (uint16_t)(_c[0] + _c[1]); \ -}) - -/* int16_t msa_sum_s16(v8i16 __a) */ -#define msa_sum_s16(__a) \ -({ \ - v4i32 _b; \ - v2i64 _c; \ - _b = __builtin_msa_hadd_s_w(__a, __a); \ - _c = __builtin_msa_hadd_s_d(_b, _b); \ - (int32_t)(_c[0] + _c[1]); \ -}) - - -/* uint32_t msa_sum_u32(v4u32 __a)*/ -#define msa_sum_u32(__a) \ -({ \ - v2u64 _b; \ - _b = __builtin_msa_hadd_u_d(__a, __a); \ - (uint32_t)(_b[0] + _b[1]); \ -}) - -/* int32_t msa_sum_s32(v4i32 __a)*/ -#define msa_sum_s32(__a) \ -({ \ - v2i64 _b; \ - _b = __builtin_msa_hadd_s_d(__a, __a); \ - (int64_t)(_b[0] + _b[1]); \ -}) - -/* uint8_t msa_sum_u8(v16u8 __a)*/ -#define msa_sum_u8(__a) \ -({ \ - v8u16 _b16; \ - v4u32 _c32; \ - _b16 = __builtin_msa_hadd_u_h(__a, __a); \ - _c32 = __builtin_msa_hadd_u_w(_b16, _b16); \ - (uint8_t)msa_sum_u32(_c32); \ -}) - -/* int8_t msa_sum_s8(v16s8 __a)*/ -#define msa_sum_s8(__a) \ -({ \ - v8i16 _b16; \ - v4i32 _c32; \ - _b16 = __builtin_msa_hadd_s_h(__a, __a); \ - _c32 = __builtin_msa_hadd_s_w(_b16, _b16); \ - (int16_t)msa_sum_s32(_c32); \ -}) - -/* float msa_sum_f32(v4f32 __a)*/ -#define msa_sum_f32(__a) ((__a)[0] + (__a)[1] + (__a)[2] + (__a)[3]) - -/* v8u16 msa_paddlq_u8(v16u8 __a) */ -#define msa_paddlq_u8(__a) (__builtin_msa_hadd_u_h(__a, __a)) - -/* v8i16 msa_paddlq_s8(v16i8 __a) */ -#define msa_paddlq_s8(__a) (__builtin_msa_hadd_s_h(__a, __a)) - -/* v4u32 msa_paddlq_u16 (v8u16 __a)*/ -#define msa_paddlq_u16(__a) (__builtin_msa_hadd_u_w(__a, __a)) - -/* v4i32 msa_paddlq_s16 (v8i16 __a)*/ -#define msa_paddlq_s16(__a) (__builtin_msa_hadd_s_w(__a, __a)) - -/* v2u64 msa_paddlq_u32(v4u32 __a) */ -#define msa_paddlq_u32(__a) (__builtin_msa_hadd_u_d(__a, __a)) - -/* v2i64 msa_paddlq_s32(v4i32 __a) */ -#define msa_paddlq_s32(__a) (__builtin_msa_hadd_s_d(__a, __a)) - -#define V8U8_2_V8U16(x) {(uint16_t)x[0], (uint16_t)x[1], (uint16_t)x[2], (uint16_t)x[3], \ - (uint16_t)x[4], (uint16_t)x[5], (uint16_t)x[6], (uint16_t)x[7]} -#define V8U8_2_V8I16(x) {(int16_t)x[0], (int16_t)x[1], (int16_t)x[2], (int16_t)x[3], \ - (int16_t)x[4], (int16_t)x[5], (int16_t)x[6], (int16_t)x[7]} -#define V8I8_2_V8I16(x) {(int16_t)x[0], (int16_t)x[1], (int16_t)x[2], (int16_t)x[3], \ - (int16_t)x[4], (int16_t)x[5], (int16_t)x[6], (int16_t)x[7]} -#define V4U16_2_V4U32(x) {(uint32_t)x[0], (uint32_t)x[1], (uint32_t)x[2], (uint32_t)x[3]} -#define V4U16_2_V4I32(x) {(int32_t)x[0], (int32_t)x[1], (int32_t)x[2], (int32_t)x[3]} -#define V4I16_2_V4I32(x) {(int32_t)x[0], (int32_t)x[1], (int32_t)x[2], (int32_t)x[3]} -#define V2U32_2_V2U64(x) {(uint64_t)x[0], (uint64_t)x[1]} -#define V2U32_2_V2I64(x) {(int64_t)x[0], (int64_t)x[1]} - -/* v8u16 msa_mull_u8(v8u8 __a, v8u8 __b) */ -#define msa_mull_u8(__a, __b) ((v8u16)__builtin_msa_mulv_h((v8i16)V8U8_2_V8I16(__a), (v8i16)V8U8_2_V8I16(__b))) - -/* v8i16 msa_mull_s8(v8i8 __a, v8i8 __b)*/ -#define msa_mull_s8(__a, __b) (__builtin_msa_mulv_h((v8i16)V8I8_2_V8I16(__a), (v8i16)V8I8_2_V8I16(__b))) - -/* v4u32 msa_mull_u16(v4u16 __a, v4u16 __b) */ -#define msa_mull_u16(__a, __b) ((v4u32)__builtin_msa_mulv_w((v4i32)V4U16_2_V4I32(__a), (v4i32)V4U16_2_V4I32(__b))) - -/* v4i32 msa_mull_s16(v4i16 __a, v4i16 __b) */ -#define msa_mull_s16(__a, __b) (__builtin_msa_mulv_w((v4i32)V4I16_2_V4I32(__a), (v4i32)V4I16_2_V4I32(__b))) - -/* v2u64 msa_mull_u32(v2u32 __a, v2u32 __b) */ -#define msa_mull_u32(__a, __b) ((v2u64)__builtin_msa_mulv_d((v2i64)V2U32_2_V2I64(__a), (v2i64)V2U32_2_V2I64(__b))) - -/* bitwise and: __builtin_msa_and_v */ -#define msa_andq_u8(__a, __b) ((v16u8)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) -#define msa_andq_s8(__a, __b) ((v16i8)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) -#define msa_andq_u16(__a, __b) ((v8u16)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) -#define msa_andq_s16(__a, __b) ((v8i16)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) -#define msa_andq_u32(__a, __b) ((v4u32)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) -#define msa_andq_s32(__a, __b) ((v4i32)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) -#define msa_andq_u64(__a, __b) ((v2u64)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) -#define msa_andq_s64(__a, __b) ((v2i64)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) - -/* bitwise or: __builtin_msa_or_v */ -#define msa_orrq_u8(__a, __b) ((v16u8)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) -#define msa_orrq_s8(__a, __b) ((v16i8)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) -#define msa_orrq_u16(__a, __b) ((v8u16)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) -#define msa_orrq_s16(__a, __b) ((v8i16)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) -#define msa_orrq_u32(__a, __b) ((v4u32)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) -#define msa_orrq_s32(__a, __b) ((v4i32)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) -#define msa_orrq_u64(__a, __b) ((v2u64)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) -#define msa_orrq_s64(__a, __b) ((v2i64)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) - -/* bitwise xor: __builtin_msa_xor_v */ -#define msa_eorq_u8(__a, __b) ((v16u8)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) -#define msa_eorq_s8(__a, __b) ((v16i8)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) -#define msa_eorq_u16(__a, __b) ((v8u16)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) -#define msa_eorq_s16(__a, __b) ((v8i16)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) -#define msa_eorq_u32(__a, __b) ((v4u32)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) -#define msa_eorq_s32(__a, __b) ((v4i32)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) -#define msa_eorq_u64(__a, __b) ((v2u64)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) -#define msa_eorq_s64(__a, __b) ((v2i64)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) - -/* bitwise not: v16u8 __builtin_msa_xori_b (v16u8, 0xff) */ -#define msa_mvnq_u8(__a) ((v16u8)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) -#define msa_mvnq_s8(__a) ((v16i8)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) -#define msa_mvnq_u16(__a) ((v8u16)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) -#define msa_mvnq_s16(__a) ((v8i16)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) -#define msa_mvnq_u32(__a) ((v4u32)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) -#define msa_mvnq_s32(__a) ((v4i32)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) -#define msa_mvnq_u64(__a) ((v2u64)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) -#define msa_mvnq_s64(__a) ((v2i64)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) - -/* compare equal: ceq -> ri = ai == bi ? 1...1:0...0 */ -#define msa_ceqq_u8(__a, __b) ((v16u8)__builtin_msa_ceq_b((v16i8)(__a), (v16i8)(__b))) -#define msa_ceqq_s8(__a, __b) ((v16u8)__builtin_msa_ceq_b((v16i8)(__a), (v16i8)(__b))) -#define msa_ceqq_u16(__a, __b) ((v8u16)__builtin_msa_ceq_h((v8i16)(__a), (v8i16)(__b))) -#define msa_ceqq_s16(__a, __b) ((v8u16)__builtin_msa_ceq_h((v8i16)(__a), (v8i16)(__b))) -#define msa_ceqq_u32(__a, __b) ((v4u32)__builtin_msa_ceq_w((v4i32)(__a), (v4i32)(__b))) -#define msa_ceqq_s32(__a, __b) ((v4u32)__builtin_msa_ceq_w((v4i32)(__a), (v4i32)(__b))) -#define msa_ceqq_f32(__a, __b) ((v4u32)__builtin_msa_fceq_w((v4f32)(__a), (v4f32)(__b))) -#define msa_ceqq_u64(__a, __b) ((v2u64)__builtin_msa_ceq_d((v2i64)(__a), (v2i64)(__b))) -#define msa_ceqq_s64(__a, __b) ((v2u64)__builtin_msa_ceq_d((v2i64)(__a), (v2i64)(__b))) -#define msa_ceqq_f64(__a, __b) ((v2u64)__builtin_msa_fceq_d((v2f64)(__a), (v2f64)(__b))) - -/* Compare less-than: clt -> ri = ai < bi ? 1...1:0...0 */ -#define msa_cltq_u8(__a, __b) ((v16u8)__builtin_msa_clt_u_b((v16u8)(__a), (v16u8)(__b))) -#define msa_cltq_s8(__a, __b) ((v16u8)__builtin_msa_clt_s_b((v16i8)(__a), (v16i8)(__b))) -#define msa_cltq_u16(__a, __b) ((v8u16)__builtin_msa_clt_u_h((v8u16)(__a), (v8u16)(__b))) -#define msa_cltq_s16(__a, __b) ((v8u16)__builtin_msa_clt_s_h((v8i16)(__a), (v8i16)(__b))) -#define msa_cltq_u32(__a, __b) ((v4u32)__builtin_msa_clt_u_w((v4u32)(__a), (v4u32)(__b))) -#define msa_cltq_s32(__a, __b) ((v4u32)__builtin_msa_clt_s_w((v4i32)(__a), (v4i32)(__b))) -#define msa_cltq_f32(__a, __b) ((v4u32)__builtin_msa_fclt_w((v4f32)(__a), (v4f32)(__b))) -#define msa_cltq_u64(__a, __b) ((v2u64)__builtin_msa_clt_u_d((v2u64)(__a), (v2u64)(__b))) -#define msa_cltq_s64(__a, __b) ((v2u64)__builtin_msa_clt_s_d((v2i64)(__a), (v2i64)(__b))) -#define msa_cltq_f64(__a, __b) ((v2u64)__builtin_msa_fclt_d((v2f64)(__a), (v2f64)(__b))) - -/* compare greater-than: cgt -> ri = ai > bi ? 1...1:0...0 */ -#define msa_cgtq_u8(__a, __b) ((v16u8)__builtin_msa_clt_u_b((v16u8)(__b), (v16u8)(__a))) -#define msa_cgtq_s8(__a, __b) ((v16u8)__builtin_msa_clt_s_b((v16i8)(__b), (v16i8)(__a))) -#define msa_cgtq_u16(__a, __b) ((v8u16)__builtin_msa_clt_u_h((v8u16)(__b), (v8u16)(__a))) -#define msa_cgtq_s16(__a, __b) ((v8u16)__builtin_msa_clt_s_h((v8i16)(__b), (v8i16)(__a))) -#define msa_cgtq_u32(__a, __b) ((v4u32)__builtin_msa_clt_u_w((v4u32)(__b), (v4u32)(__a))) -#define msa_cgtq_s32(__a, __b) ((v4u32)__builtin_msa_clt_s_w((v4i32)(__b), (v4i32)(__a))) -#define msa_cgtq_f32(__a, __b) ((v4u32)__builtin_msa_fclt_w((v4f32)(__b), (v4f32)(__a))) -#define msa_cgtq_u64(__a, __b) ((v2u64)__builtin_msa_clt_u_d((v2u64)(__b), (v2u64)(__a))) -#define msa_cgtq_s64(__a, __b) ((v2u64)__builtin_msa_clt_s_d((v2i64)(__b), (v2i64)(__a))) -#define msa_cgtq_f64(__a, __b) ((v2u64)__builtin_msa_fclt_d((v2f64)(__b), (v2f64)(__a))) - -/* compare less-equal: cle -> ri = ai <= bi ? 1...1:0...0 */ -#define msa_cleq_u8(__a, __b) ((v16u8)__builtin_msa_cle_u_b((v16u8)(__a), (v16u8)(__b))) -#define msa_cleq_s8(__a, __b) ((v16u8)__builtin_msa_cle_s_b((v16i8)(__a), (v16i8)(__b))) -#define msa_cleq_u16(__a, __b) ((v8u16)__builtin_msa_cle_u_h((v8u16)(__a), (v8u16)(__b))) -#define msa_cleq_s16(__a, __b) ((v8u16)__builtin_msa_cle_s_h((v8i16)(__a), (v8i16)(__b))) -#define msa_cleq_u32(__a, __b) ((v4u32)__builtin_msa_cle_u_w((v4u32)(__a), (v4u32)(__b))) -#define msa_cleq_s32(__a, __b) ((v4u32)__builtin_msa_cle_s_w((v4i32)(__a), (v4i32)(__b))) -#define msa_cleq_f32(__a, __b) ((v4u32)__builtin_msa_fcle_w((v4f32)(__a), (v4f32)(__b))) -#define msa_cleq_u64(__a, __b) ((v2u64)__builtin_msa_cle_u_d((v2u64)(__a), (v2u64)(__b))) -#define msa_cleq_s64(__a, __b) ((v2u64)__builtin_msa_cle_s_d((v2i64)(__a), (v2i64)(__b))) -#define msa_cleq_f64(__a, __b) ((v2u64)__builtin_msa_fcle_d((v2f64)(__a), (v2f64)(__b))) - -/* compare greater-equal: cge -> ri = ai >= bi ? 1...1:0...0 */ -#define msa_cgeq_u8(__a, __b) ((v16u8)__builtin_msa_cle_u_b((v16u8)(__b), (v16u8)(__a))) -#define msa_cgeq_s8(__a, __b) ((v16u8)__builtin_msa_cle_s_b((v16i8)(__b), (v16i8)(__a))) -#define msa_cgeq_u16(__a, __b) ((v8u16)__builtin_msa_cle_u_h((v8u16)(__b), (v8u16)(__a))) -#define msa_cgeq_s16(__a, __b) ((v8u16)__builtin_msa_cle_s_h((v8i16)(__b), (v8i16)(__a))) -#define msa_cgeq_u32(__a, __b) ((v4u32)__builtin_msa_cle_u_w((v4u32)(__b), (v4u32)(__a))) -#define msa_cgeq_s32(__a, __b) ((v4u32)__builtin_msa_cle_s_w((v4i32)(__b), (v4i32)(__a))) -#define msa_cgeq_f32(__a, __b) ((v4u32)__builtin_msa_fcle_w((v4f32)(__b), (v4f32)(__a))) -#define msa_cgeq_u64(__a, __b) ((v2u64)__builtin_msa_cle_u_d((v2u64)(__b), (v2u64)(__a))) -#define msa_cgeq_s64(__a, __b) ((v2u64)__builtin_msa_cle_s_d((v2i64)(__b), (v2i64)(__a))) -#define msa_cgeq_f64(__a, __b) ((v2u64)__builtin_msa_fcle_d((v2f64)(__b), (v2f64)(__a))) - -/* Shift Left Logical: shl -> ri = ai << bi; */ -#define msa_shlq_u8(__a, __b) ((v16u8)__builtin_msa_sll_b((v16i8)(__a), (v16i8)(__b))) -#define msa_shlq_s8(__a, __b) ((v16i8)__builtin_msa_sll_b((v16i8)(__a), (v16i8)(__b))) -#define msa_shlq_u16(__a, __b) ((v8u16)__builtin_msa_sll_h((v8i16)(__a), (v8i16)(__b))) -#define msa_shlq_s16(__a, __b) ((v8i16)__builtin_msa_sll_h((v8i16)(__a), (v8i16)(__b))) -#define msa_shlq_u32(__a, __b) ((v4u32)__builtin_msa_sll_w((v4i32)(__a), (v4i32)(__b))) -#define msa_shlq_s32(__a, __b) ((v4i32)__builtin_msa_sll_w((v4i32)(__a), (v4i32)(__b))) -#define msa_shlq_u64(__a, __b) ((v2u64)__builtin_msa_sll_d((v2i64)(__a), (v2i64)(__b))) -#define msa_shlq_s64(__a, __b) ((v2i64)__builtin_msa_sll_d((v2i64)(__a), (v2i64)(__b))) - -/* Immediate Shift Left Logical: shl -> ri = ai << imm; */ -#define msa_shlq_n_u8(__a, __imm) ((v16u8)__builtin_msa_slli_b((v16i8)(__a), __imm)) -#define msa_shlq_n_s8(__a, __imm) ((v16i8)__builtin_msa_slli_b((v16i8)(__a), __imm)) -#define msa_shlq_n_u16(__a, __imm) ((v8u16)__builtin_msa_slli_h((v8i16)(__a), __imm)) -#define msa_shlq_n_s16(__a, __imm) ((v8i16)__builtin_msa_slli_h((v8i16)(__a), __imm)) -#define msa_shlq_n_u32(__a, __imm) ((v4u32)__builtin_msa_slli_w((v4i32)(__a), __imm)) -#define msa_shlq_n_s32(__a, __imm) ((v4i32)__builtin_msa_slli_w((v4i32)(__a), __imm)) -#define msa_shlq_n_u64(__a, __imm) ((v2u64)__builtin_msa_slli_d((v2i64)(__a), __imm)) -#define msa_shlq_n_s64(__a, __imm) ((v2i64)__builtin_msa_slli_d((v2i64)(__a), __imm)) - -/* shift right: shrq -> ri = ai >> bi; */ -#define msa_shrq_u8(__a, __b) ((v16u8)__builtin_msa_srl_b((v16i8)(__a), (v16i8)(__b))) -#define msa_shrq_s8(__a, __b) ((v16i8)__builtin_msa_sra_b((v16i8)(__a), (v16i8)(__b))) -#define msa_shrq_u16(__a, __b) ((v8u16)__builtin_msa_srl_h((v8i16)(__a), (v8i16)(__b))) -#define msa_shrq_s16(__a, __b) ((v8i16)__builtin_msa_sra_h((v8i16)(__a), (v8i16)(__b))) -#define msa_shrq_u32(__a, __b) ((v4u32)__builtin_msa_srl_w((v4i32)(__a), (v4i32)(__b))) -#define msa_shrq_s32(__a, __b) ((v4i32)__builtin_msa_sra_w((v4i32)(__a), (v4i32)(__b))) -#define msa_shrq_u64(__a, __b) ((v2u64)__builtin_msa_srl_d((v2i64)(__a), (v2i64)(__b))) -#define msa_shrq_s64(__a, __b) ((v2i64)__builtin_msa_sra_d((v2i64)(__a), (v2i64)(__b))) - -/* Immediate Shift Right: shr -> ri = ai >> imm; */ -#define msa_shrq_n_u8(__a, __imm) ((v16u8)__builtin_msa_srli_b((v16i8)(__a), __imm)) -#define msa_shrq_n_s8(__a, __imm) ((v16i8)__builtin_msa_srai_b((v16i8)(__a), __imm)) -#define msa_shrq_n_u16(__a, __imm) ((v8u16)__builtin_msa_srli_h((v8i16)(__a), __imm)) -#define msa_shrq_n_s16(__a, __imm) ((v8i16)__builtin_msa_srai_h((v8i16)(__a), __imm)) -#define msa_shrq_n_u32(__a, __imm) ((v4u32)__builtin_msa_srli_w((v4i32)(__a), __imm)) -#define msa_shrq_n_s32(__a, __imm) ((v4i32)__builtin_msa_srai_w((v4i32)(__a), __imm)) -#define msa_shrq_n_u64(__a, __imm) ((v2u64)__builtin_msa_srli_d((v2i64)(__a), __imm)) -#define msa_shrq_n_s64(__a, __imm) ((v2i64)__builtin_msa_srai_d((v2i64)(__a), __imm)) - -/* Immediate Shift Right Rounded: shr -> ri = ai >> (rounded)imm; */ -#define msa_rshrq_n_u8(__a, __imm) ((v16u8)__builtin_msa_srlri_b((v16i8)(__a), __imm)) -#define msa_rshrq_n_s8(__a, __imm) ((v16i8)__builtin_msa_srari_b((v16i8)(__a), __imm)) -#define msa_rshrq_n_u16(__a, __imm) ((v8u16)__builtin_msa_srlri_h((v8i16)(__a), __imm)) -#define msa_rshrq_n_s16(__a, __imm) ((v8i16)__builtin_msa_srari_h((v8i16)(__a), __imm)) -#define msa_rshrq_n_u32(__a, __imm) ((v4u32)__builtin_msa_srlri_w((v4i32)(__a), __imm)) -#define msa_rshrq_n_s32(__a, __imm) ((v4i32)__builtin_msa_srari_w((v4i32)(__a), __imm)) -#define msa_rshrq_n_u64(__a, __imm) ((v2u64)__builtin_msa_srlri_d((v2i64)(__a), __imm)) -#define msa_rshrq_n_s64(__a, __imm) ((v2i64)__builtin_msa_srari_d((v2i64)(__a), __imm)) - -/* Vector saturating rounding shift left, qrshl -> ri = ai << bi; */ -#define msa_qrshrq_s32(a, b) ((v4i32)__msa_srar_w((v4i32)(a), (v4i32)(b))) - -/* Rename the msa builtin func to unify the name style for intrin_msa.hpp */ -#define msa_qaddq_u8 __builtin_msa_adds_u_b -#define msa_qaddq_s8 __builtin_msa_adds_s_b -#define msa_qaddq_u16 __builtin_msa_adds_u_h -#define msa_qaddq_s16 __builtin_msa_adds_s_h -#define msa_qaddq_u32 __builtin_msa_adds_u_w -#define msa_qaddq_s32 __builtin_msa_adds_s_w -#define msa_qaddq_u64 __builtin_msa_adds_u_d -#define msa_qaddq_s64 __builtin_msa_adds_s_d -#define msa_addq_u8(a, b) ((v16u8)__builtin_msa_addv_b((v16i8)(a), (v16i8)(b))) -#define msa_addq_s8 __builtin_msa_addv_b -#define msa_addq_u16(a, b) ((v8u16)__builtin_msa_addv_h((v8i16)(a), (v8i16)(b))) -#define msa_addq_s16 __builtin_msa_addv_h -#define msa_addq_u32(a, b) ((v4u32)__builtin_msa_addv_w((v4i32)(a), (v4i32)(b))) -#define msa_addq_s32 __builtin_msa_addv_w -#define msa_addq_f32 __builtin_msa_fadd_w -#define msa_addq_u64(a, b) ((v2u64)__builtin_msa_addv_d((v2i64)(a), (v2i64)(b))) -#define msa_addq_s64 __builtin_msa_addv_d -#define msa_addq_f64 __builtin_msa_fadd_d -#define msa_qsubq_u8 __builtin_msa_subs_u_b -#define msa_qsubq_s8 __builtin_msa_subs_s_b -#define msa_qsubq_u16 __builtin_msa_subs_u_h -#define msa_qsubq_s16 __builtin_msa_subs_s_h -#define msa_subq_u8(a, b) ((v16u8)__builtin_msa_subv_b((v16i8)(a), (v16i8)(b))) -#define msa_subq_s8 __builtin_msa_subv_b -#define msa_subq_u16(a, b) ((v8u16)__builtin_msa_subv_h((v8i16)(a), (v8i16)(b))) -#define msa_subq_s16 __builtin_msa_subv_h -#define msa_subq_u32(a, b) ((v4u32)__builtin_msa_subv_w((v4i32)(a), (v4i32)(b))) -#define msa_subq_s32 __builtin_msa_subv_w -#define msa_subq_f32 __builtin_msa_fsub_w -#define msa_subq_u64(a, b) ((v2u64)__builtin_msa_subv_d((v2i64)(a), (v2i64)(b))) -#define msa_subq_s64 __builtin_msa_subv_d -#define msa_subq_f64 __builtin_msa_fsub_d -#define msa_mulq_u8(a, b) ((v16u8)__builtin_msa_mulv_b((v16i8)(a), (v16i8)(b))) -#define msa_mulq_s8(a, b) ((v16i8)__builtin_msa_mulv_b((v16i8)(a), (v16i8)(b))) -#define msa_mulq_u16(a, b) ((v8u16)__builtin_msa_mulv_h((v8i16)(a), (v8i16)(b))) -#define msa_mulq_s16(a, b) ((v8i16)__builtin_msa_mulv_h((v8i16)(a), (v8i16)(b))) -#define msa_mulq_u32(a, b) ((v4u32)__builtin_msa_mulv_w((v4i32)(a), (v4i32)(b))) -#define msa_mulq_s32(a, b) ((v4i32)__builtin_msa_mulv_w((v4i32)(a), (v4i32)(b))) -#define msa_mulq_u64(a, b) ((v2u64)__builtin_msa_mulv_d((v2i64)(a), (v2i64)(b))) -#define msa_mulq_s64(a, b) ((v2i64)__builtin_msa_mulv_d((v2i64)(a), (v2i64)(b))) -#define msa_mulq_f32 __builtin_msa_fmul_w -#define msa_mulq_f64 __builtin_msa_fmul_d -#define msa_divq_f32 __builtin_msa_fdiv_w -#define msa_divq_f64 __builtin_msa_fdiv_d -#define msa_dotp_s_h __builtin_msa_dotp_s_h -#define msa_dotp_s_w __builtin_msa_dotp_s_w -#define msa_dotp_s_d __builtin_msa_dotp_s_d -#define msa_dotp_u_h __builtin_msa_dotp_u_h -#define msa_dotp_u_w __builtin_msa_dotp_u_w -#define msa_dotp_u_d __builtin_msa_dotp_u_d -#define msa_dpadd_s_h __builtin_msa_dpadd_s_h -#define msa_dpadd_s_w __builtin_msa_dpadd_s_w -#define msa_dpadd_s_d __builtin_msa_dpadd_s_d -#define msa_dpadd_u_h __builtin_msa_dpadd_u_h -#define msa_dpadd_u_w __builtin_msa_dpadd_u_w -#define msa_dpadd_u_d __builtin_msa_dpadd_u_d - -#define ILVRL_B2(RTYPE, in0, in1, low, hi) do { \ - low = (RTYPE)__builtin_msa_ilvr_b((v16i8)(in0), (v16i8)(in1)); \ - hi = (RTYPE)__builtin_msa_ilvl_b((v16i8)(in0), (v16i8)(in1)); \ - } while (0) -#define ILVRL_B2_UB(...) ILVRL_B2(v16u8, __VA_ARGS__) -#define ILVRL_B2_SB(...) ILVRL_B2(v16i8, __VA_ARGS__) -#define ILVRL_B2_UH(...) ILVRL_B2(v8u16, __VA_ARGS__) -#define ILVRL_B2_SH(...) ILVRL_B2(v8i16, __VA_ARGS__) -#define ILVRL_B2_SW(...) ILVRL_B2(v4i32, __VA_ARGS__) - -#define ILVRL_H2(RTYPE, in0, in1, low, hi) do { \ - low = (RTYPE)__builtin_msa_ilvr_h((v8i16)(in0), (v8i16)(in1)); \ - hi = (RTYPE)__builtin_msa_ilvl_h((v8i16)(in0), (v8i16)(in1)); \ - } while (0) -#define ILVRL_H2_UB(...) ILVRL_H2(v16u8, __VA_ARGS__) -#define ILVRL_H2_SB(...) ILVRL_H2(v16i8, __VA_ARGS__) -#define ILVRL_H2_UH(...) ILVRL_H2(v8u16, __VA_ARGS__) -#define ILVRL_H2_SH(...) ILVRL_H2(v8i16, __VA_ARGS__) -#define ILVRL_H2_SW(...) ILVRL_H2(v4i32, __VA_ARGS__) -#define ILVRL_H2_UW(...) ILVRL_H2(v4u32, __VA_ARGS__) - -#define ILVRL_W2(RTYPE, in0, in1, low, hi) do { \ - low = (RTYPE)__builtin_msa_ilvr_w((v4i32)(in0), (v4i32)(in1)); \ - hi = (RTYPE)__builtin_msa_ilvl_w((v4i32)(in0), (v4i32)(in1)); \ - } while (0) -#define ILVRL_W2_UB(...) ILVRL_W2(v16u8, __VA_ARGS__) -#define ILVRL_W2_SH(...) ILVRL_W2(v8i16, __VA_ARGS__) -#define ILVRL_W2_SW(...) ILVRL_W2(v4i32, __VA_ARGS__) -#define ILVRL_W2_UW(...) ILVRL_W2(v4u32, __VA_ARGS__) - -/* absq, qabsq (r = |a|;) */ -#define msa_absq_s8(a) __builtin_msa_add_a_b(a, __builtin_msa_fill_b(0)) -#define msa_absq_s16(a) __builtin_msa_add_a_h(a, __builtin_msa_fill_h(0)) -#define msa_absq_s32(a) __builtin_msa_add_a_w(a, __builtin_msa_fill_w(0)) -#define msa_absq_s64(a) __builtin_msa_add_a_d(a, __builtin_msa_fill_d(0)) -#define msa_absq_f32(a) ((v4f32)__builtin_msa_bclri_w((v4u32)(a), 31)) -#define msa_absq_f64(a) ((v2f64)__builtin_msa_bclri_d((v2u64)(a), 63)) -#define msa_qabsq_s8(a) __builtin_msa_adds_a_b(a, __builtin_msa_fill_b(0)) -#define msa_qabsq_s16(a) __builtin_msa_adds_a_h(a, __builtin_msa_fill_h(0)) -#define msa_qabsq_s32(a) __builtin_msa_adds_a_w(a, __builtin_msa_fill_w(0)) -#define msa_qabsq_s64(a) __builtin_msa_adds_a_d(a, __builtin_msa_fill_d(0)) - -/* abdq, qabdq (r = |a - b|;) */ -#define msa_abdq_u8 __builtin_msa_asub_u_b -#define msa_abdq_s8 __builtin_msa_asub_s_b -#define msa_abdq_u16 __builtin_msa_asub_u_h -#define msa_abdq_s16 __builtin_msa_asub_s_h -#define msa_abdq_u32 __builtin_msa_asub_u_w -#define msa_abdq_s32 __builtin_msa_asub_s_w -#define msa_abdq_u64 __builtin_msa_asub_u_d -#define msa_abdq_s64 __builtin_msa_asub_s_d -#define msa_abdq_f32(a, b) msa_absq_f32(__builtin_msa_fsub_w(a, b)) -#define msa_abdq_f64(a, b) msa_absq_f64(__builtin_msa_fsub_d(a, b)) -#define msa_qabdq_s8(a, b) msa_qabsq_s8(__builtin_msa_subs_s_b(a, b)) -#define msa_qabdq_s16(a, b) msa_qabsq_s16(__builtin_msa_subs_s_h(a, b)) -#define msa_qabdq_s32(a, b) msa_qabsq_s32(__builtin_msa_subs_s_w(a, b)) -#define msa_qabdq_s64(a, b) msa_qabsq_s64(__builtin_msa_subs_s_d(a, b)) - -/* sqrtq, rsqrtq */ -#define msa_sqrtq_f32 __builtin_msa_fsqrt_w -#define msa_sqrtq_f64 __builtin_msa_fsqrt_d -#define msa_rsqrtq_f32 __builtin_msa_frsqrt_w -#define msa_rsqrtq_f64 __builtin_msa_frsqrt_d - - -/* mlaq: r = a + b * c; */ -__extension__ extern __inline v4i32 -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) -msa_mlaq_s32(v4i32 __a, v4i32 __b, v4i32 __c) -{ - __asm__ volatile("maddv.w %w[__a], %w[__b], %w[__c]\n" - // Outputs - : [__a] "+f"(__a) - // Inputs - : [__b] "f"(__b), [__c] "f"(__c)); - return __a; -} - -__extension__ extern __inline v2i64 -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) -msa_mlaq_s64(v2i64 __a, v2i64 __b, v2i64 __c) -{ - __asm__ volatile("maddv.d %w[__a], %w[__b], %w[__c]\n" - // Outputs - : [__a] "+f"(__a) - // Inputs - : [__b] "f"(__b), [__c] "f"(__c)); - return __a; -} - -__extension__ extern __inline v4f32 -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) -msa_mlaq_f32(v4f32 __a, v4f32 __b, v4f32 __c) -{ - __asm__ volatile("fmadd.w %w[__a], %w[__b], %w[__c]\n" - // Outputs - : [__a] "+f"(__a) - // Inputs - : [__b] "f"(__b), [__c] "f"(__c)); - return __a; -} - -__extension__ extern __inline v2f64 -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) -msa_mlaq_f64(v2f64 __a, v2f64 __b, v2f64 __c) -{ - __asm__ volatile("fmadd.d %w[__a], %w[__b], %w[__c]\n" - // Outputs - : [__a] "+f"(__a) - // Inputs - : [__b] "f"(__b), [__c] "f"(__c)); - return __a; -} - -/* cntq */ -#define msa_cntq_s8 __builtin_msa_pcnt_b -#define msa_cntq_s16 __builtin_msa_pcnt_h -#define msa_cntq_s32 __builtin_msa_pcnt_w -#define msa_cntq_s64 __builtin_msa_pcnt_d - -/* bslq (a: mask; r = b(if a == 0); r = c(if a == 1);) */ -#define msa_bslq_u8 __builtin_msa_bsel_v - -/* ilvrq, ilvlq (For EL only, ilvrq: b0, a0, b1, a1; ilvlq: b2, a2, b3, a3;) */ -#define msa_ilvrq_s8 __builtin_msa_ilvr_b -#define msa_ilvrq_s16 __builtin_msa_ilvr_h -#define msa_ilvrq_s32 __builtin_msa_ilvr_w -#define msa_ilvrq_s64 __builtin_msa_ilvr_d -#define msa_ilvlq_s8 __builtin_msa_ilvl_b -#define msa_ilvlq_s16 __builtin_msa_ilvl_h -#define msa_ilvlq_s32 __builtin_msa_ilvl_w -#define msa_ilvlq_s64 __builtin_msa_ilvl_d - -/* ilvevq, ilvodq (ilvevq: b0, a0, b2, a2; ilvodq: b1, a1, b3, a3; ) */ -#define msa_ilvevq_s8 __builtin_msa_ilvev_b -#define msa_ilvevq_s16 __builtin_msa_ilvev_h -#define msa_ilvevq_s32 __builtin_msa_ilvev_w -#define msa_ilvevq_s64 __builtin_msa_ilvev_d -#define msa_ilvodq_s8 __builtin_msa_ilvod_b -#define msa_ilvodq_s16 __builtin_msa_ilvod_h -#define msa_ilvodq_s32 __builtin_msa_ilvod_w -#define msa_ilvodq_s64 __builtin_msa_ilvod_d - -/* extq (r = (a || b); a concatenation b and get elements from index c) */ -#ifdef _MIPSEB -#define msa_extq_s8(a, b, c) \ -(__builtin_msa_vshf_b(__builtin_msa_subv_b((v16i8)((v2i64){0x1716151413121110, 0x1F1E1D1C1B1A1918}), __builtin_msa_fill_b(c)), a, b)) -#define msa_extq_s16(a, b, c) \ -(__builtin_msa_vshf_h(__builtin_msa_subv_h((v8i16)((v2i64){0x000B000A00090008, 0x000F000E000D000C}), __builtin_msa_fill_h(c)), a, b)) -#define msa_extq_s32(a, b, c) \ -(__builtin_msa_vshf_w(__builtin_msa_subv_w((v4i32)((v2i64){0x0000000500000004, 0x0000000700000006}), __builtin_msa_fill_w(c)), a, b)) -#define msa_extq_s64(a, b, c) \ -(__builtin_msa_vshf_d(__builtin_msa_subv_d((v2i64){0x0000000000000002, 0x0000000000000003}, __builtin_msa_fill_d(c)), a, b)) -#else -#define msa_extq_s8(a, b, c) \ -(__builtin_msa_vshf_b(__builtin_msa_addv_b((v16i8)((v2i64){0x0706050403020100, 0x0F0E0D0C0B0A0908}), __builtin_msa_fill_b(c)), b, a)) -#define msa_extq_s16(a, b, c) \ -(__builtin_msa_vshf_h(__builtin_msa_addv_h((v8i16)((v2i64){0x0003000200010000, 0x0007000600050004}), __builtin_msa_fill_h(c)), b, a)) -#define msa_extq_s32(a, b, c) \ -(__builtin_msa_vshf_w(__builtin_msa_addv_w((v4i32)((v2i64){0x0000000100000000, 0x0000000300000002}), __builtin_msa_fill_w(c)), b, a)) -#define msa_extq_s64(a, b, c) \ -(__builtin_msa_vshf_d(__builtin_msa_addv_d((v2i64){0x0000000000000000, 0x0000000000000001}, __builtin_msa_fill_d(c)), b, a)) -#endif /* _MIPSEB */ - -/* cvttruncq, cvttintq, cvtrintq */ -#define msa_cvttruncq_u32_f32 __builtin_msa_ftrunc_u_w -#define msa_cvttruncq_s32_f32 __builtin_msa_ftrunc_s_w -#define msa_cvttruncq_u64_f64 __builtin_msa_ftrunc_u_d -#define msa_cvttruncq_s64_f64 __builtin_msa_ftrunc_s_d -#define msa_cvttintq_u32_f32 __builtin_msa_ftint_u_w -#define msa_cvttintq_s32_f32 __builtin_msa_ftint_s_w -#define msa_cvttintq_u64_f64 __builtin_msa_ftint_u_d -#define msa_cvttintq_s64_f64 __builtin_msa_ftint_s_d -#define msa_cvtrintq_f32 __builtin_msa_frint_w -#define msa_cvtrintq_f64 __builtin_msa_frint_d - -/* cvtfintq, cvtfq */ -#define msa_cvtfintq_f32_u32 __builtin_msa_ffint_u_w -#define msa_cvtfintq_f32_s32 __builtin_msa_ffint_s_w -#define msa_cvtfintq_f64_u64 __builtin_msa_ffint_u_d -#define msa_cvtfintq_f64_s64 __builtin_msa_ffint_s_d -#define msa_cvtfq_f32_f64 __builtin_msa_fexdo_w -#define msa_cvtflq_f64_f32 __builtin_msa_fexupr_d -#define msa_cvtfhq_f64_f32 __builtin_msa_fexupl_d - -#define msa_addl_u8(a, b) ((v8u16)__builtin_msa_addv_h((v8i16)V8U8_2_V8I16(a), (v8i16)V8U8_2_V8I16(b))) -#define msa_addl_s8(a, b) (__builtin_msa_addv_h((v8i16)V8I8_2_V8I16(a), (v8i16)V8I8_2_V8I16(b))) -#define msa_addl_u16(a, b) ((v4u32)__builtin_msa_addv_w((v4i32)V4U16_2_V4I32(a), (v4i32)V4U16_2_V4I32(b))) -#define msa_addl_s16(a, b) (__builtin_msa_addv_w((v4i32)V4I16_2_V4I32(a), (v4i32)V4I16_2_V4I32(b))) -#define msa_subl_s16(a, b) (__builtin_msa_subv_w((v4i32)V4I16_2_V4I32(a), (v4i32)V4I16_2_V4I32(b))) -#define msa_recpeq_f32 __builtin_msa_frcp_w -#define msa_recpsq_f32(a, b) (__builtin_msa_fsub_w(msa_dupq_n_f32(2.0f), __builtin_msa_fmul_w(a, b))) - -#define MSA_INTERLEAVED_IMPL_LOAD2_STORE2(_Tp, _Tpv, _Tpvs, suffix, df, nlanes) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_ld2q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b) \ -{ \ - _Tpv v0 = msa_ld1q_##suffix(ptr); \ - _Tpv v1 = msa_ld1q_##suffix(ptr + nlanes); \ - *a = (_Tpv)__builtin_msa_pckev_##df((_Tpvs)v1, (_Tpvs)v0); \ - *b = (_Tpv)__builtin_msa_pckod_##df((_Tpvs)v1, (_Tpvs)v0); \ -} \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_st2q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b) \ -{ \ - msa_st1q_##suffix(ptr, (_Tpv)__builtin_msa_ilvr_##df((_Tpvs)b, (_Tpvs)a)); \ - msa_st1q_##suffix(ptr + nlanes, (_Tpv)__builtin_msa_ilvl_##df((_Tpvs)b, (_Tpvs)a)); \ -} - -MSA_INTERLEAVED_IMPL_LOAD2_STORE2(uint8_t, v16u8, v16i8, u8, b, 16) -MSA_INTERLEAVED_IMPL_LOAD2_STORE2(int8_t, v16i8, v16i8, s8, b, 16) -MSA_INTERLEAVED_IMPL_LOAD2_STORE2(uint16_t, v8u16, v8i16, u16, h, 8) -MSA_INTERLEAVED_IMPL_LOAD2_STORE2(int16_t, v8i16, v8i16, s16, h, 8) -MSA_INTERLEAVED_IMPL_LOAD2_STORE2(uint32_t, v4u32, v4i32, u32, w, 4) -MSA_INTERLEAVED_IMPL_LOAD2_STORE2(int32_t, v4i32, v4i32, s32, w, 4) -MSA_INTERLEAVED_IMPL_LOAD2_STORE2(float, v4f32, v4i32, f32, w, 4) -MSA_INTERLEAVED_IMPL_LOAD2_STORE2(uint64_t, v2u64, v2i64, u64, d, 2) -MSA_INTERLEAVED_IMPL_LOAD2_STORE2(int64_t, v2i64, v2i64, s64, d, 2) -MSA_INTERLEAVED_IMPL_LOAD2_STORE2(double, v2f64, v2i64, f64, d, 2) - -#ifdef _MIPSEB -#define MSA_INTERLEAVED_IMPL_LOAD3_8(_Tp, _Tpv, _Tpvs, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_ld3q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c) \ -{ \ - _Tpv v0 = msa_ld1q_##suffix(ptr); \ - _Tpv v1 = msa_ld1q_##suffix(ptr + 16); \ - _Tpv v2 = msa_ld1q_##suffix(ptr + 32); \ - _Tpvs v3 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0704011F1F1F1F1F, 0x1F1C191613100D0A}), (_Tpvs)v0, (_Tpvs)v1); \ - *a = (_Tpv)__builtin_msa_vshf_b((_Tpvs)((v2i64){0x1716150E0B080502, 0x1F1E1D1C1B1A1918}), v3, (_Tpvs)v2); \ - v3 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0603001F1F1F1F1F, 0x1E1B1815120F0C09}), (_Tpvs)v0, (_Tpvs)v1); \ - *b = (_Tpv)__builtin_msa_vshf_b((_Tpvs)((v2i64){0x1716150D0A070401, 0x1F1E1D1C1B1A1918}), v3, (_Tpvs)v2); \ - v3 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x05021F1F1F1F1F1F, 0x1D1A1714110E0B08}), (_Tpvs)v0, (_Tpvs)v1); \ - *c = (_Tpv)__builtin_msa_vshf_b((_Tpvs)((v2i64){0x17160F0C09060300, 0x1F1E1D1C1B1A1918}), v3, (_Tpvs)v2); \ -} -#else -#define MSA_INTERLEAVED_IMPL_LOAD3_8(_Tp, _Tpv, _Tpvs, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_ld3q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c) \ -{ \ - _Tpv v0 = msa_ld1q_##suffix(ptr); \ - _Tpv v1 = msa_ld1q_##suffix(ptr + 16); \ - _Tpv v2 = msa_ld1q_##suffix(ptr + 32); \ - _Tpvs v3 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x15120F0C09060300, 0x00000000001E1B18}), (_Tpvs)v1, (_Tpvs)v0); \ - *a = (_Tpv)__builtin_msa_vshf_b((_Tpvs)((v2i64){0x0706050403020100, 0x1D1A1714110A0908}), (_Tpvs)v2, v3); \ - v3 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x1613100D0A070401, 0x00000000001F1C19}), (_Tpvs)v1, (_Tpvs)v0); \ - *b = (_Tpv)__builtin_msa_vshf_b((_Tpvs)((v2i64){0x0706050403020100, 0x1E1B1815120A0908}), (_Tpvs)v2, v3); \ - v3 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x1714110E0B080502, 0x0000000000001D1A}), (_Tpvs)v1, (_Tpvs)v0); \ - *c = (_Tpv)__builtin_msa_vshf_b((_Tpvs)((v2i64){0x0706050403020100, 0x1F1C191613100908}), (_Tpvs)v2, v3); \ -} -#endif - -MSA_INTERLEAVED_IMPL_LOAD3_8(uint8_t, v16u8, v16i8, u8) -MSA_INTERLEAVED_IMPL_LOAD3_8(int8_t, v16i8, v16i8, s8) - -#ifdef _MIPSEB -#define MSA_INTERLEAVED_IMPL_LOAD3_16(_Tp, _Tpv, _Tpvs, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_ld3q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c) \ -{ \ - _Tpv v0 = msa_ld1q_##suffix(ptr); \ - _Tpv v1 = msa_ld1q_##suffix(ptr + 8); \ - _Tpv v2 = msa_ld1q_##suffix(ptr + 16); \ - _Tpvs v3 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x00030000000F000F, 0x000F000C00090006}), (_Tpvs)v1, (_Tpvs)v0); \ - *a = (_Tpv)__builtin_msa_vshf_h((_Tpvs)((v2i64){0x000B000A00050002, 0x000F000E000D000C}), (_Tpvs)v2, v3); \ - v3 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0002000F000F000F, 0x000E000B00080005}), (_Tpvs)v1, (_Tpvs)v0); \ - *b = (_Tpv)__builtin_msa_vshf_h((_Tpvs)((v2i64){0x000B000700040001, 0x000F000E000D000C}), (_Tpvs)v2, v3); \ - v3 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0001000F000F000F, 0x000D000A00070004}), (_Tpvs)v1, (_Tpvs)v0); \ - *c = (_Tpv)__builtin_msa_vshf_h((_Tpvs)((v2i64){0x000B000600030000, 0x000F000E000D000C}), (_Tpvs)v2, v3); \ -} -#else -#define MSA_INTERLEAVED_IMPL_LOAD3_16(_Tp, _Tpv, _Tpvs, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_ld3q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c) \ -{ \ - _Tpv v0 = msa_ld1q_##suffix(ptr); \ - _Tpv v1 = msa_ld1q_##suffix(ptr + 8); \ - _Tpv v2 = msa_ld1q_##suffix(ptr + 16); \ - _Tpvs v3 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0009000600030000, 0x00000000000F000C}), (_Tpvs)v1, (_Tpvs)v0); \ - *a = (_Tpv)__builtin_msa_vshf_h((_Tpvs)((v2i64){0x0003000200010000, 0x000D000A00050004}), (_Tpvs)v2, v3); \ - v3 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000A000700040001, 0x000000000000000D}), (_Tpvs)v1, (_Tpvs)v0); \ - *b = (_Tpv)__builtin_msa_vshf_h((_Tpvs)((v2i64){0x0003000200010000, 0x000E000B00080004}), (_Tpvs)v2, v3); \ - v3 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000B000800050002, 0x000000000000000E}), (_Tpvs)v1, (_Tpvs)v0); \ - *c = (_Tpv)__builtin_msa_vshf_h((_Tpvs)((v2i64){0x0003000200010000, 0x000F000C00090004}), (_Tpvs)v2, v3); \ -} -#endif - -MSA_INTERLEAVED_IMPL_LOAD3_16(uint16_t, v8u16, v8i16, u16) -MSA_INTERLEAVED_IMPL_LOAD3_16(int16_t, v8i16, v8i16, s16) - -#define MSA_INTERLEAVED_IMPL_LOAD3_32(_Tp, _Tpv, _Tpvs, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_ld3q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c) \ -{ \ - _Tpv v00 = msa_ld1q_##suffix(ptr); \ - _Tpv v01 = msa_ld1q_##suffix(ptr + 4); \ - _Tpv v02 = msa_ld1q_##suffix(ptr + 8); \ - _Tpvs v10 = __builtin_msa_ilvr_w((_Tpvs)__builtin_msa_ilvl_d((v2i64)v01, (v2i64)v01), (_Tpvs)v00); \ - _Tpvs v11 = __builtin_msa_ilvr_w((_Tpvs)v02, (_Tpvs)__builtin_msa_ilvl_d((v2i64)v00, (v2i64)v00)); \ - _Tpvs v12 = __builtin_msa_ilvr_w((_Tpvs)__builtin_msa_ilvl_d((v2i64)v02, (v2i64)v02), (_Tpvs)v01); \ - *a = (_Tpv)__builtin_msa_ilvr_w((_Tpvs)__builtin_msa_ilvl_d((v2i64)v11, (v2i64)v11), v10); \ - *b = (_Tpv)__builtin_msa_ilvr_w(v12, (_Tpvs)__builtin_msa_ilvl_d((v2i64)v10, (v2i64)v10)); \ - *c = (_Tpv)__builtin_msa_ilvr_w((_Tpvs)__builtin_msa_ilvl_d((v2i64)v12, (v2i64)v12), v11); \ -} - -MSA_INTERLEAVED_IMPL_LOAD3_32(uint32_t, v4u32, v4i32, u32) -MSA_INTERLEAVED_IMPL_LOAD3_32(int32_t, v4i32, v4i32, s32) -MSA_INTERLEAVED_IMPL_LOAD3_32(float, v4f32, v4i32, f32) - -#define MSA_INTERLEAVED_IMPL_LOAD3_64(_Tp, _Tpv, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_ld3q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c) \ -{ \ - *((_Tp*)a) = *ptr; *((_Tp*)b) = *(ptr + 1); *((_Tp*)c) = *(ptr + 2); \ - *((_Tp*)a + 1) = *(ptr + 3); *((_Tp*)b + 1) = *(ptr + 4); *((_Tp*)c + 1) = *(ptr + 5); \ -} - -MSA_INTERLEAVED_IMPL_LOAD3_64(uint64_t, v2u64, u64) -MSA_INTERLEAVED_IMPL_LOAD3_64(int64_t, v2i64, s64) -MSA_INTERLEAVED_IMPL_LOAD3_64(double, v2f64, f64) - -#ifdef _MIPSEB -#define MSA_INTERLEAVED_IMPL_STORE3_8(_Tp, _Tpv, _Tpvs, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ -{ \ - _Tpvs v0 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0F0E0D0C0B1F1F1F, 0x1F1E1D1C1B1A1F1F}), (_Tpvs)b, (_Tpvs)a); \ - _Tpvs v1 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0D1C140C1B130B1A, 0x1F170F1E160E1D15}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr, (_Tpv)v1); \ - v0 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0A09080706051F1F, 0x19181716151F1F1F}), (_Tpvs)b, (_Tpvs)a); \ - v1 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x1D14071C13061B12, 0x170A1F16091E1508}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr + 16, (_Tpv)v1); \ - v0 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x04030201001F1F1F, 0x14131211101F1F1F}), (_Tpvs)b, (_Tpvs)a); \ - v1 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x15021C14011B1300, 0x051F17041E16031D}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr + 32, (_Tpv)v1); \ -} -#else -#define MSA_INTERLEAVED_IMPL_STORE3_8(_Tp, _Tpv, _Tpvs, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ -{ \ - _Tpvs v0 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0000050403020100, 0x0000001413121110}), (_Tpvs)b, (_Tpvs)a); \ - _Tpvs v1 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0A02110901100800, 0x05140C04130B0312}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr, (_Tpv)v1); \ - v0 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0000000A09080706, 0x00001A1918171615}), (_Tpvs)b, (_Tpvs)a); \ - v1 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x170A011609001508, 0x0D04190C03180B02}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr + 16, (_Tpv)v1); \ - v0 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0000000F0E0D0C0B, 0x0000001F1E1D1C1B}), (_Tpvs)b, (_Tpvs)a); \ - v1 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x021C09011B08001A, 0x1F0C041E0B031D0A}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr + 32, (_Tpv)v1); \ -} -#endif - -MSA_INTERLEAVED_IMPL_STORE3_8(uint8_t, v16u8, v16i8, u8) -MSA_INTERLEAVED_IMPL_STORE3_8(int8_t, v16i8, v16i8, s8) - -#ifdef _MIPSEB -#define MSA_INTERLEAVED_IMPL_STORE3_16(_Tp, _Tpv, _Tpvs, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ -{ \ - _Tpvs v0 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000700060005000F, 0x000F000E000D000F}), (_Tpvs)b, (_Tpvs)a); \ - _Tpvs v1 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000A0006000D0009, 0x000F000B0007000E}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr, (_Tpv)v1); \ - v0 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x00040003000F000F, 0x000C000B000A000F}), (_Tpvs)b, (_Tpvs)a); \ - v1 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000E000A0003000D, 0x0005000F000B0004}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr + 8, (_Tpv)v1); \ - v0 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000200010000000F, 0x00090008000F000F}), (_Tpvs)b, (_Tpvs)a); \ - v1 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0001000E00090000, 0x000B0002000F000A}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr + 16, (_Tpv)v1); \ -} -#else -#define MSA_INTERLEAVED_IMPL_STORE3_16(_Tp, _Tpv, _Tpvs, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ -{ \ - _Tpvs v0 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0000000200010000, 0x0000000A00090008}), (_Tpvs)b, (_Tpvs)a); \ - _Tpvs v1 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0001000800040000, 0x0006000200090005}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr, (_Tpv)v1); \ - v0 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0000000500040003, 0x00000000000C000B}), (_Tpvs)b, (_Tpvs)a); \ - v1 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000B00040000000A, 0x0002000C00050001}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr + 8, (_Tpv)v1); \ - v0 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0000000000070006, 0x0000000F000E000D}), (_Tpvs)b, (_Tpvs)a); \ - v1 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x00050000000D0004, 0x000F00060001000E}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr + 16, (_Tpv)v1); \ -} -#endif - -MSA_INTERLEAVED_IMPL_STORE3_16(uint16_t, v8u16, v8i16, u16) -MSA_INTERLEAVED_IMPL_STORE3_16(int16_t, v8i16, v8i16, s16) - -#ifdef _MIPSEB -#define MSA_INTERLEAVED_IMPL_STORE3_32(_Tp, _Tpv, _Tpvs, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ -{ \ - _Tpvs v0 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000300000007, 0x0000000700000006}), (_Tpvs)b, (_Tpvs)a); \ - _Tpvs v1 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000300000006, 0x0000000700000005}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr, (_Tpv)v1); \ - v0 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000200000001, 0x0000000500000007}), (_Tpvs)b, (_Tpvs)a); \ - v1 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000700000004, 0x0000000500000002}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr + 4, (_Tpv)v1); \ - v0 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000000000007, 0x0000000400000007}), (_Tpvs)b, (_Tpvs)a); \ - v1 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000500000000, 0x0000000100000007}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr + 8, (_Tpv)v1); \ -} -#else -#define MSA_INTERLEAVED_IMPL_STORE3_32(_Tp, _Tpv, _Tpvs, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ -{ \ - _Tpvs v0 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000100000000, 0x0000000000000004}), (_Tpvs)b, (_Tpvs)a); \ - _Tpvs v1 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000200000000, 0x0000000100000004}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr, (_Tpv)v1); \ - v0 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000000000002, 0x0000000600000005}), (_Tpvs)b, (_Tpvs)a); \ - v1 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000500000002, 0x0000000300000000}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr + 4, (_Tpv)v1); \ - v0 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000000000003, 0x0000000000000007}), (_Tpvs)b, (_Tpvs)a); \ - v1 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000000000006, 0x0000000700000002}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr + 8, (_Tpv)v1); \ -} -#endif - -MSA_INTERLEAVED_IMPL_STORE3_32(uint32_t, v4u32, v4i32, u32) -MSA_INTERLEAVED_IMPL_STORE3_32(int32_t, v4i32, v4i32, s32) -MSA_INTERLEAVED_IMPL_STORE3_32(float, v4f32, v4i32, f32) - -#define MSA_INTERLEAVED_IMPL_STORE3_64(_Tp, _Tpv, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ -{ \ - *ptr = a[0]; *(ptr + 1) = b[0]; *(ptr + 2) = c[0]; \ - *(ptr + 3) = a[1]; *(ptr + 4) = b[1]; *(ptr + 5) = c[1]; \ -} - -MSA_INTERLEAVED_IMPL_STORE3_64(uint64_t, v2u64, u64) -MSA_INTERLEAVED_IMPL_STORE3_64(int64_t, v2i64, s64) -MSA_INTERLEAVED_IMPL_STORE3_64(double, v2f64, f64) - -#define MSA_INTERLEAVED_IMPL_LOAD4_STORE4(_Tp, _Tpv, _Tpvs, suffix, df, nlanes) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_ld4q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c, _Tpv* d) \ -{ \ - _Tpv v0 = msa_ld1q_##suffix(ptr); \ - _Tpv v1 = msa_ld1q_##suffix(ptr + nlanes); \ - _Tpv v2 = msa_ld1q_##suffix(ptr + nlanes * 2); \ - _Tpv v3 = msa_ld1q_##suffix(ptr + nlanes * 3); \ - _Tpvs t0 = __builtin_msa_pckev_##df((_Tpvs)v1, (_Tpvs)v0); \ - _Tpvs t1 = __builtin_msa_pckev_##df((_Tpvs)v3, (_Tpvs)v2); \ - _Tpvs t2 = __builtin_msa_pckod_##df((_Tpvs)v1, (_Tpvs)v0); \ - _Tpvs t3 = __builtin_msa_pckod_##df((_Tpvs)v3, (_Tpvs)v2); \ - *a = (_Tpv)__builtin_msa_pckev_##df(t1, t0); \ - *b = (_Tpv)__builtin_msa_pckev_##df(t3, t2); \ - *c = (_Tpv)__builtin_msa_pckod_##df(t1, t0); \ - *d = (_Tpv)__builtin_msa_pckod_##df(t3, t2); \ -} \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_st4q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c, const _Tpv d) \ -{ \ - _Tpvs v0 = __builtin_msa_ilvr_##df((_Tpvs)c, (_Tpvs)a); \ - _Tpvs v1 = __builtin_msa_ilvr_##df((_Tpvs)d, (_Tpvs)b); \ - _Tpvs v2 = __builtin_msa_ilvl_##df((_Tpvs)c, (_Tpvs)a); \ - _Tpvs v3 = __builtin_msa_ilvl_##df((_Tpvs)d, (_Tpvs)b); \ - msa_st1q_##suffix(ptr, (_Tpv)__builtin_msa_ilvr_##df(v1, v0)); \ - msa_st1q_##suffix(ptr + nlanes, (_Tpv)__builtin_msa_ilvl_##df(v1, v0)); \ - msa_st1q_##suffix(ptr + 2 * nlanes, (_Tpv)__builtin_msa_ilvr_##df(v3, v2)); \ - msa_st1q_##suffix(ptr + 3 * nlanes, (_Tpv)__builtin_msa_ilvl_##df(v3, v2)); \ -} - -MSA_INTERLEAVED_IMPL_LOAD4_STORE4(uint8_t, v16u8, v16i8, u8, b, 16) -MSA_INTERLEAVED_IMPL_LOAD4_STORE4(int8_t, v16i8, v16i8, s8, b, 16) -MSA_INTERLEAVED_IMPL_LOAD4_STORE4(uint16_t, v8u16, v8i16, u16, h, 8) -MSA_INTERLEAVED_IMPL_LOAD4_STORE4(int16_t, v8i16, v8i16, s16, h, 8) -MSA_INTERLEAVED_IMPL_LOAD4_STORE4(uint32_t, v4u32, v4i32, u32, w, 4) -MSA_INTERLEAVED_IMPL_LOAD4_STORE4(int32_t, v4i32, v4i32, s32, w, 4) -MSA_INTERLEAVED_IMPL_LOAD4_STORE4(float, v4f32, v4i32, f32, w, 4) - -#define MSA_INTERLEAVED_IMPL_LOAD4_STORE4_64(_Tp, _Tpv, _Tpvs, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_ld4q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c, _Tpv* d) \ -{ \ - _Tpv v0 = msa_ld1q_##suffix(ptr); \ - _Tpv v1 = msa_ld1q_##suffix(ptr + 2); \ - _Tpv v2 = msa_ld1q_##suffix(ptr + 4); \ - _Tpv v3 = msa_ld1q_##suffix(ptr + 6); \ - *a = (_Tpv)__builtin_msa_ilvr_d((_Tpvs)v2, (_Tpvs)v0); \ - *b = (_Tpv)__builtin_msa_ilvl_d((_Tpvs)v2, (_Tpvs)v0); \ - *c = (_Tpv)__builtin_msa_ilvr_d((_Tpvs)v3, (_Tpvs)v1); \ - *d = (_Tpv)__builtin_msa_ilvl_d((_Tpvs)v3, (_Tpvs)v1); \ -} \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_st4q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c, const _Tpv d) \ -{ \ - msa_st1q_##suffix(ptr, (_Tpv)__builtin_msa_ilvr_d((_Tpvs)b, (_Tpvs)a)); \ - msa_st1q_##suffix(ptr + 2, (_Tpv)__builtin_msa_ilvr_d((_Tpvs)d, (_Tpvs)c)); \ - msa_st1q_##suffix(ptr + 4, (_Tpv)__builtin_msa_ilvl_d((_Tpvs)b, (_Tpvs)a)); \ - msa_st1q_##suffix(ptr + 6, (_Tpv)__builtin_msa_ilvl_d((_Tpvs)d, (_Tpvs)c)); \ -} - -MSA_INTERLEAVED_IMPL_LOAD4_STORE4_64(uint64_t, v2u64, v2i64, u64) -MSA_INTERLEAVED_IMPL_LOAD4_STORE4_64(int64_t, v2i64, v2i64, s64) -MSA_INTERLEAVED_IMPL_LOAD4_STORE4_64(double, v2f64, v2i64, f64) - -__extension__ extern __inline v8i16 -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) -msa_qdmulhq_n_s16(v8i16 a, int16_t b) -{ - v8i16 a_lo, a_hi; - ILVRL_H2_SH(a, msa_dupq_n_s16(0), a_lo, a_hi); - return msa_packr_s32(msa_shlq_n_s32(msa_mulq_s32(msa_paddlq_s16(a_lo), msa_dupq_n_s32(b)), 1), - msa_shlq_n_s32(msa_mulq_s32(msa_paddlq_s16(a_hi), msa_dupq_n_s32(b)), 1), 16); -} - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif /*__mips_msa*/ -#endif /* OPENCV_CORE_MSA_MACROS_H */ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_HAL_MSA_MACROS_H +#define OPENCV_CORE_HAL_MSA_MACROS_H + +#ifdef __mips_msa +#include "msa.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Define 64 bits vector types */ +typedef signed char v8i8 __attribute__ ((vector_size(8), aligned(8))); +typedef unsigned char v8u8 __attribute__ ((vector_size(8), aligned(8))); +typedef short v4i16 __attribute__ ((vector_size(8), aligned(8))); +typedef unsigned short v4u16 __attribute__ ((vector_size(8), aligned(8))); +typedef int v2i32 __attribute__ ((vector_size(8), aligned(8))); +typedef unsigned int v2u32 __attribute__ ((vector_size(8), aligned(8))); +typedef long long v1i64 __attribute__ ((vector_size(8), aligned(8))); +typedef unsigned long long v1u64 __attribute__ ((vector_size(8), aligned(8))); +typedef float v2f32 __attribute__ ((vector_size(8), aligned(8))); +typedef double v1f64 __attribute__ ((vector_size(8), aligned(8))); + + +/* Load values from the given memory a 64-bit vector. */ +#define msa_ld1_s8(__a) (*((v8i8*)(__a))) +#define msa_ld1_s16(__a) (*((v4i16*)(__a))) +#define msa_ld1_s32(__a) (*((v2i32*)(__a))) +#define msa_ld1_s64(__a) (*((v1i64*)(__a))) +#define msa_ld1_u8(__a) (*((v8u8*)(__a))) +#define msa_ld1_u16(__a) (*((v4u16*)(__a))) +#define msa_ld1_u32(__a) (*((v2u32*)(__a))) +#define msa_ld1_u64(__a) (*((v1u64*)(__a))) +#define msa_ld1_f32(__a) (*((v2f32*)(__a))) +#define msa_ld1_f64(__a) (*((v1f64*)(__a))) + +/* Load values from the given memory address to a 128-bit vector */ +#define msa_ld1q_s8(__a) ((v16i8)__builtin_msa_ld_b(__a, 0)) +#define msa_ld1q_s16(__a) ((v8i16)__builtin_msa_ld_h(__a, 0)) +#define msa_ld1q_s32(__a) ((v4i32)__builtin_msa_ld_w(__a, 0)) +#define msa_ld1q_s64(__a) ((v2i64)__builtin_msa_ld_d(__a, 0)) +#define msa_ld1q_u8(__a) ((v16u8)__builtin_msa_ld_b(__a, 0)) +#define msa_ld1q_u16(__a) ((v8u16)__builtin_msa_ld_h(__a, 0)) +#define msa_ld1q_u32(__a) ((v4u32)__builtin_msa_ld_w(__a, 0)) +#define msa_ld1q_u64(__a) ((v2u64)__builtin_msa_ld_d(__a, 0)) +#define msa_ld1q_f32(__a) ((v4f32)__builtin_msa_ld_w(__a, 0)) +#define msa_ld1q_f64(__a) ((v2f64)__builtin_msa_ld_d(__a, 0)) + +/* Store 64bits vector elements values to the given memory address. */ +#define msa_st1_s8(__a, __b) (*((v8i8*)(__a)) = __b) +#define msa_st1_s16(__a, __b) (*((v4i16*)(__a)) = __b) +#define msa_st1_s32(__a, __b) (*((v2i32*)(__a)) = __b) +#define msa_st1_s64(__a, __b) (*((v1i64*)(__a)) = __b) +#define msa_st1_u8(__a, __b) (*((v8u8*)(__a)) = __b) +#define msa_st1_u16(__a, __b) (*((v4u16*)(__a)) = __b) +#define msa_st1_u32(__a, __b) (*((v2u32*)(__a)) = __b) +#define msa_st1_u64(__a, __b) (*((v1u64*)(__a)) = __b) +#define msa_st1_f32(__a, __b) (*((v2f32*)(__a)) = __b) +#define msa_st1_f64(__a, __b) (*((v1f64*)(__a)) = __b) + +/* Store the values of elements in the 128 bits vector __a to the given memory address __a. */ +#define msa_st1q_s8(__a, __b) (__builtin_msa_st_b((v16i8)(__b), __a, 0)) +#define msa_st1q_s16(__a, __b) (__builtin_msa_st_h((v8i16)(__b), __a, 0)) +#define msa_st1q_s32(__a, __b) (__builtin_msa_st_w((v4i32)(__b), __a, 0)) +#define msa_st1q_s64(__a, __b) (__builtin_msa_st_d((v2i64)(__b), __a, 0)) +#define msa_st1q_u8(__a, __b) (__builtin_msa_st_b((v16i8)(__b), __a, 0)) +#define msa_st1q_u16(__a, __b) (__builtin_msa_st_h((v8i16)(__b), __a, 0)) +#define msa_st1q_u32(__a, __b) (__builtin_msa_st_w((v4i32)(__b), __a, 0)) +#define msa_st1q_u64(__a, __b) (__builtin_msa_st_d((v2i64)(__b), __a, 0)) +#define msa_st1q_f32(__a, __b) (__builtin_msa_st_w((v4i32)(__b), __a, 0)) +#define msa_st1q_f64(__a, __b) (__builtin_msa_st_d((v2i64)(__b), __a, 0)) + +/* Store the value of the element with the index __c in vector __a to the given memory address __a. */ +#define msa_st1_lane_s8(__a, __b, __c) (*((int8_t*)(__a)) = __b[__c]) +#define msa_st1_lane_s16(__a, __b, __c) (*((int16_t*)(__a)) = __b[__c]) +#define msa_st1_lane_s32(__a, __b, __c) (*((int32_t*)(__a)) = __b[__c]) +#define msa_st1_lane_s64(__a, __b, __c) (*((int64_t*)(__a)) = __b[__c]) +#define msa_st1_lane_u8(__a, __b, __c) (*((uint8_t*)(__a)) = __b[__c]) +#define msa_st1_lane_u16(__a, __b, __c) (*((uint16_t*)(__a)) = __b[__c]) +#define msa_st1_lane_u32(__a, __b, __c) (*((uint32_t*)(__a)) = __b[__c]) +#define msa_st1_lane_u64(__a, __b, __c) (*((uint64_t*)(__a)) = __b[__c]) +#define msa_st1_lane_f32(__a, __b, __c) (*((float*)(__a)) = __b[__c]) +#define msa_st1_lane_f64(__a, __b, __c) (*((double*)(__a)) = __b[__c]) +#define msa_st1q_lane_s8(__a, __b, __c) (*((int8_t*)(__a)) = (int8_t)__builtin_msa_copy_s_b(__b, __c)) +#define msa_st1q_lane_s16(__a, __b, __c) (*((int16_t*)(__a)) = (int16_t)__builtin_msa_copy_s_h(__b, __c)) +#define msa_st1q_lane_s32(__a, __b, __c) (*((int32_t*)(__a)) = __builtin_msa_copy_s_w(__b, __c)) +#define msa_st1q_lane_s64(__a, __b, __c) (*((int64_t*)(__a)) = __builtin_msa_copy_s_d(__b, __c)) +#define msa_st1q_lane_u8(__a, __b, __c) (*((uint8_t*)(__a)) = (uint8_t)__builtin_msa_copy_u_b((v16i8)(__b), __c)) +#define msa_st1q_lane_u16(__a, __b, __c) (*((uint16_t*)(__a)) = (uint16_t)__builtin_msa_copy_u_h((v8i16)(__b), __c)) +#define msa_st1q_lane_u32(__a, __b, __c) (*((uint32_t*)(__a)) = __builtin_msa_copy_u_w((v4i32)(__b), __c)) +#define msa_st1q_lane_u64(__a, __b, __c) (*((uint64_t*)(__a)) = __builtin_msa_copy_u_d((v2i64)(__b), __c)) +#define msa_st1q_lane_f32(__a, __b, __c) (*((float*)(__a)) = __b[__c]) +#define msa_st1q_lane_f64(__a, __b, __c) (*((double*)(__a)) = __b[__c]) + +/* Duplicate elements for 64-bit doubleword vectors */ +#define msa_dup_n_s8(__a) ((v8i8)__builtin_msa_copy_s_d((v2i64)__builtin_msa_fill_b((int32_t)(__a)), 0)) +#define msa_dup_n_s16(__a) ((v4i16)__builtin_msa_copy_s_d((v2i64)__builtin_msa_fill_h((int32_t)(__a)), 0)) +#define msa_dup_n_s32(__a) ((v2i32){__a, __a}) +#define msa_dup_n_s64(__a) ((v1i64){__a}) +#define msa_dup_n_u8(__a) ((v8u8)__builtin_msa_copy_u_d((v2i64)__builtin_msa_fill_b((int32_t)(__a)), 0)) +#define msa_dup_n_u16(__a) ((v4u16)__builtin_msa_copy_u_d((v2i64)__builtin_msa_fill_h((int32_t)(__a)), 0)) +#define msa_dup_n_u32(__a) ((v2u32){__a, __a}) +#define msa_dup_n_u64(__a) ((v1u64){__a}) +#define msa_dup_n_f32(__a) ((v2f32){__a, __a}) +#define msa_dup_n_f64(__a) ((v1f64){__a}) + +/* Duplicate elements for 128-bit quadword vectors */ +#define msa_dupq_n_s8(__a) (__builtin_msa_fill_b((int32_t)(__a))) +#define msa_dupq_n_s16(__a) (__builtin_msa_fill_h((int32_t)(__a))) +#define msa_dupq_n_s32(__a) (__builtin_msa_fill_w((int32_t)(__a))) +#define msa_dupq_n_s64(__a) (__builtin_msa_fill_d((int64_t)(__a))) +#define msa_dupq_n_u8(__a) ((v16u8)__builtin_msa_fill_b((int32_t)(__a))) +#define msa_dupq_n_u16(__a) ((v8u16)__builtin_msa_fill_h((int32_t)(__a))) +#define msa_dupq_n_u32(__a) ((v4u32)__builtin_msa_fill_w((int32_t)(__a))) +#define msa_dupq_n_u64(__a) ((v2u64)__builtin_msa_fill_d((int64_t)(__a))) +#define msa_dupq_n_f32(__a) ((v4f32){__a, __a, __a, __a}) +#define msa_dupq_n_f64(__a) ((v2f64){__a, __a}) +#define msa_dupq_lane_s8(__a, __b) (__builtin_msa_splat_b(__a, __b)) +#define msa_dupq_lane_s16(__a, __b) (__builtin_msa_splat_h(__a, __b)) +#define msa_dupq_lane_s32(__a, __b) (__builtin_msa_splat_w(__a, __b)) +#define msa_dupq_lane_s64(__a, __b) (__builtin_msa_splat_d(__a, __b)) +#define msa_dupq_lane_u8(__a, __b) ((v16u8)__builtin_msa_splat_b((v16i8)(__a), __b)) +#define msa_dupq_lane_u16(__a, __b) ((v8u16)__builtin_msa_splat_h((v8i16)(__a), __b)) +#define msa_dupq_lane_u32(__a, __b) ((v4u32)__builtin_msa_splat_w((v4i32)(__a), __b)) +#define msa_dupq_lane_u64(__a, __b) ((v2u64)__builtin_msa_splat_d((v2i64)(__a), __b)) + +/* Create a 64 bits vector */ +#define msa_create_s8(__a) ((v8i8)((uint64_t)(__a))) +#define msa_create_s16(__a) ((v4i16)((uint64_t)(__a))) +#define msa_create_s32(__a) ((v2i32)((uint64_t)(__a))) +#define msa_create_s64(__a) ((v1i64)((uint64_t)(__a))) +#define msa_create_u8(__a) ((v8u8)((uint64_t)(__a))) +#define msa_create_u16(__a) ((v4u16)((uint64_t)(__a))) +#define msa_create_u32(__a) ((v2u32)((uint64_t)(__a))) +#define msa_create_u64(__a) ((v1u64)((uint64_t)(__a))) +#define msa_create_f32(__a) ((v2f32)((uint64_t)(__a))) +#define msa_create_f64(__a) ((v1f64)((uint64_t)(__a))) + +/* Sign extends or zero extends each element in a 64 bits vector to twice its original length, and places the results in a 128 bits vector. */ +/*Transform v8i8 to v8i16*/ +#define msa_movl_s8(__a) \ +((v8i16){(__a)[0], (__a)[1], (__a)[2], (__a)[3], \ + (__a)[4], (__a)[5], (__a)[6], (__a)[7]}) + +/*Transform v8u8 to v8u16*/ +#define msa_movl_u8(__a) \ +((v8u16){(__a)[0], (__a)[1], (__a)[2], (__a)[3], \ + (__a)[4], (__a)[5], (__a)[6], (__a)[7]}) + +/*Transform v4i16 to v8i16*/ +#define msa_movl_s16(__a) ((v4i32){(__a)[0], (__a)[1], (__a)[2], (__a)[3]}) + +/*Transform v2i32 to v4i32*/ +#define msa_movl_s32(__a) ((v2i64){(__a)[0], (__a)[1]}) + +/*Transform v4u16 to v8u16*/ +#define msa_movl_u16(__a) ((v4u32){(__a)[0], (__a)[1], (__a)[2], (__a)[3]}) + +/*Transform v2u32 to v4u32*/ +#define msa_movl_u32(__a) ((v2u64){(__a)[0], (__a)[1]}) + +/* Copies the least significant half of each element of a 128 bits vector into the corresponding elements of a 64 bits vector. */ +#define msa_movn_s16(__a) \ +({ \ + v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)(__a)); \ + (v8i8)__builtin_msa_copy_s_d((v2i64)__d, 0); \ +}) + +#define msa_movn_s32(__a) \ +({ \ + v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)(__a)); \ + (v4i16)__builtin_msa_copy_s_d((v2i64)__d, 0); \ +}) + +#define msa_movn_s64(__a) \ +({ \ + v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)(__a)); \ + (v2i32)__builtin_msa_copy_s_d((v2i64)__d, 0); \ +}) + +#define msa_movn_u16(__a) \ +({ \ + v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)(__a)); \ + (v8u8)__builtin_msa_copy_u_d((v2i64)__d, 0); \ +}) + +#define msa_movn_u32(__a) \ +({ \ + v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)(__a)); \ + (v4u16)__builtin_msa_copy_u_d((v2i64)__d, 0); \ +}) + +#define msa_movn_u64(__a) \ +({ \ + v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)(__a)); \ + (v2u32)__builtin_msa_copy_u_d((v2i64)__d, 0); \ +}) + +/* qmovn */ +#define msa_qmovn_s16(__a) \ +({ \ + v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_sat_s_h((v8i16)(__a), 7)); \ + (v8i8)__builtin_msa_copy_s_d((v2i64)__d, 0); \ +}) + +#define msa_qmovn_s32(__a) \ +({ \ + v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_sat_s_w((v4i32)(__a), 15)); \ + (v4i16)__builtin_msa_copy_s_d((v2i64)__d, 0); \ +}) + +#define msa_qmovn_s64(__a) \ +({ \ + v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_sat_s_d((v2i64)(__a), 31)); \ + (v2i32)__builtin_msa_copy_s_d((v2i64)__d, 0); \ +}) + +#define msa_qmovn_u16(__a) \ +({ \ + v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_sat_u_h((v8u16)(__a), 7)); \ + (v8u8)__builtin_msa_copy_u_d((v2i64)__d, 0); \ +}) + +#define msa_qmovn_u32(__a) \ +({ \ + v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_sat_u_w((v4u32)(__a), 15)); \ + (v4u16)__builtin_msa_copy_u_d((v2i64)__d, 0); \ +}) + +#define msa_qmovn_u64(__a) \ +({ \ + v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_sat_u_d((v2u64)(__a), 31)); \ + (v2u32)__builtin_msa_copy_u_d((v2i64)__d, 0); \ +}) + +/* qmovun */ +#define msa_qmovun_s16(__a) \ +({ \ + v8i16 __d = __builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__a)); \ + v16i8 __e = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_sat_u_h((v8u16)__d, 7)); \ + (v8u8)__builtin_msa_copy_u_d((v2i64)__e, 0); \ +}) + +#define msa_qmovun_s32(__a) \ +({ \ + v4i32 __d = __builtin_msa_max_s_w(__builtin_msa_fill_w(0), (v4i32)(__a)); \ + v8i16 __e = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_sat_u_w((v4u32)__d, 15)); \ + (v4u16)__builtin_msa_copy_u_d((v2i64)__e, 0); \ +}) + +#define msa_qmovun_s64(__a) \ +({ \ + v2i64 __d = __builtin_msa_max_s_d(__builtin_msa_fill_d(0), (v2i64)(__a)); \ + v4i32 __e = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_sat_u_d((v2u64)__d, 31)); \ + (v2u32)__builtin_msa_copy_u_d((v2i64)__e, 0); \ +}) + +/* Right shift elements in a 128 bits vector by an immediate value, and places the results in a 64 bits vector. */ +#define msa_shrn_n_s16(__a, __b) \ +({ \ + v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_srai_h((v8i16)(__a), (int)(__b))); \ + (v8i8)__builtin_msa_copy_s_d((v2i64)__d, 0); \ +}) + +#define msa_shrn_n_s32(__a, __b) \ +({ \ + v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_srai_w((v4i32)(__a), (int)(__b))); \ + (v4i16)__builtin_msa_copy_s_d((v2i64)__d, 0); \ +}) + +#define msa_shrn_n_s64(__a, __b) \ +({ \ + v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_srai_d((v2i64)(__a), (int)(__b))); \ + (v2i32)__builtin_msa_copy_s_d((v2i64)__d, 0); \ +}) + +#define msa_shrn_n_u16(__a, __b) \ +({ \ + v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_srli_h((v8i16)(__a), (int)(__b))); \ + (v8u8)__builtin_msa_copy_u_d((v2i64)__d, 0); \ +}) + +#define msa_shrn_n_u32(__a, __b) \ +({ \ + v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_srli_w((v4i32)(__a), (int)(__b))); \ + (v4u16)__builtin_msa_copy_u_d((v2i64)__d, 0); \ +}) + +#define msa_shrn_n_u64(__a, __b) \ +({ \ + v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_srli_d((v2i64)(__a), (int)(__b))); \ + (v2u32)__builtin_msa_copy_u_d((v2i64)__d, 0); \ +}) + +/* Right shift elements in a 128 bits vector by an immediate value, and places the results in a 64 bits vector. */ +#define msa_rshrn_n_s16(__a, __b) \ +({ \ + v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_srari_h((v8i16)(__a), (int)__b)); \ + (v8i8)__builtin_msa_copy_s_d((v2i64)__d, 0); \ +}) + +#define msa_rshrn_n_s32(__a, __b) \ +({ \ + v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_srari_w((v4i32)(__a), (int)__b)); \ + (v4i16)__builtin_msa_copy_s_d((v2i64)__d, 0); \ +}) + +#define msa_rshrn_n_s64(__a, __b) \ +({ \ + v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_srari_d((v2i64)(__a), (int)__b)); \ + (v2i32)__builtin_msa_copy_s_d((v2i64)__d, 0); \ +}) + +#define msa_rshrn_n_u16(__a, __b) \ +({ \ + v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_srlri_h((v8i16)(__a), (int)__b)); \ + (v8u8)__builtin_msa_copy_u_d((v2i64)__d, 0); \ +}) + +#define msa_rshrn_n_u32(__a, __b) \ +({ \ + v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_srlri_w((v4i32)(__a), (int)__b)); \ + (v4u16)__builtin_msa_copy_u_d((v2i64)__d, 0); \ +}) + +#define msa_rshrn_n_u64(__a, __b) \ +({ \ + v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_srlri_d((v2i64)(__a), (int)__b)); \ + (v2u32)__builtin_msa_copy_u_d((v2i64)__d, 0); \ +}) + +/* Right shift elements in a 128 bits vector by an immediate value, saturate the results and them in a 64 bits vector. */ +#define msa_qrshrn_n_s16(__a, __b) \ +({ \ + v8i16 __d = __builtin_msa_sat_s_h(__builtin_msa_srari_h((v8i16)(__a), (int)(__b)), 7); \ + v16i8 __e = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__d); \ + (v8i8)__builtin_msa_copy_s_d((v2i64)__e, 0); \ +}) + +#define msa_qrshrn_n_s32(__a, __b) \ +({ \ + v4i32 __d = __builtin_msa_sat_s_w(__builtin_msa_srari_w((v4i32)(__a), (int)(__b)), 15); \ + v8i16 __e = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__d); \ + (v4i16)__builtin_msa_copy_s_d((v2i64)__e, 0); \ +}) + +#define msa_qrshrn_n_s64(__a, __b) \ +({ \ + v2i64 __d = __builtin_msa_sat_s_d(__builtin_msa_srari_d((v2i64)(__a), (int)(__b)), 31); \ + v4i32 __e = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__d); \ + (v2i32)__builtin_msa_copy_s_d((v2i64)__e, 0); \ +}) + +#define msa_qrshrn_n_u16(__a, __b) \ +({ \ + v8u16 __d = __builtin_msa_sat_u_h((v8u16)__builtin_msa_srlri_h((v8i16)(__a), (int)(__b)), 7); \ + v16i8 __e = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__d); \ + (v8u8)__builtin_msa_copy_u_d((v2i64)__e, 0); \ +}) + +#define msa_qrshrn_n_u32(__a, __b) \ +({ \ + v4u32 __d = __builtin_msa_sat_u_w((v4u32)__builtin_msa_srlri_w((v4i32)(__a), (int)(__b)), 15); \ + v8i16 __e = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__d); \ + (v4u16)__builtin_msa_copy_u_d((v2i64)__e, 0); \ +}) + +#define msa_qrshrn_n_u64(__a, __b) \ +({ \ + v2u64 __d = __builtin_msa_sat_u_d((v2u64)__builtin_msa_srlri_d((v2i64)(__a), (int)(__b)), 31); \ + v4i32 __e = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__d); \ + (v2u32)__builtin_msa_copy_u_d((v2i64)__e, 0); \ +}) + +/* Right shift elements in a 128 bits vector by an immediate value, saturate the results and them in a 64 bits vector. + Input is signed and output is unsigned. */ +#define msa_qrshrun_n_s16(__a, __b) \ +({ \ + v8i16 __d = __builtin_msa_srlri_h(__builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__a)), (int)(__b)); \ + v16i8 __e = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_sat_u_h((v8u16)__d, 7)); \ + (v8u8)__builtin_msa_copy_u_d((v2i64)__e, 0); \ +}) + +#define msa_qrshrun_n_s32(__a, __b) \ +({ \ + v4i32 __d = __builtin_msa_srlri_w(__builtin_msa_max_s_w(__builtin_msa_fill_w(0), (v4i32)(__a)), (int)(__b)); \ + v8i16 __e = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_sat_u_w((v4u32)__d, 15)); \ + (v4u16)__builtin_msa_copy_u_d((v2i64)__e, 0); \ +}) + +#define msa_qrshrun_n_s64(__a, __b) \ +({ \ + v2i64 __d = __builtin_msa_srlri_d(__builtin_msa_max_s_d(__builtin_msa_fill_d(0), (v2i64)(__a)), (int)(__b)); \ + v4i32 __e = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_sat_u_d((v2u64)__d, 31)); \ + (v2u32)__builtin_msa_copy_u_d((v2i64)__e, 0); \ +}) + +/* pack */ +#define msa_pack_s16(__a, __b) (__builtin_msa_pckev_b((v16i8)(__b), (v16i8)(__a))) +#define msa_pack_s32(__a, __b) (__builtin_msa_pckev_h((v8i16)(__b), (v8i16)(__a))) +#define msa_pack_s64(__a, __b) (__builtin_msa_pckev_w((v4i32)(__b), (v4i32)(__a))) +#define msa_pack_u16(__a, __b) ((v16u8)__builtin_msa_pckev_b((v16i8)(__b), (v16i8)(__a))) +#define msa_pack_u32(__a, __b) ((v8u16)__builtin_msa_pckev_h((v8i16)(__b), (v8i16)(__a))) +#define msa_pack_u64(__a, __b) ((v4u32)__builtin_msa_pckev_w((v4i32)(__b), (v4i32)(__a))) + +/* qpack */ +#define msa_qpack_s16(__a, __b) \ +(__builtin_msa_pckev_b((v16i8)__builtin_msa_sat_s_h((v8i16)(__b), 7), (v16i8)__builtin_msa_sat_s_h((v8i16)(__a), 7))) +#define msa_qpack_s32(__a, __b) \ +(__builtin_msa_pckev_h((v8i16)__builtin_msa_sat_s_w((v4i32)(__b), 15), (v8i16)__builtin_msa_sat_s_w((v4i32)(__a), 15))) +#define msa_qpack_s64(__a, __b) \ +(__builtin_msa_pckev_w((v4i32)__builtin_msa_sat_s_d((v2i64)(__b), 31), (v4i32)__builtin_msa_sat_s_d((v2i64)(__a), 31))) +#define msa_qpack_u16(__a, __b) \ +((v16u8)__builtin_msa_pckev_b((v16i8)__builtin_msa_sat_u_h((v8u16)(__b), 7), (v16i8)__builtin_msa_sat_u_h((v8u16)(__a), 7))) +#define msa_qpack_u32(__a, __b) \ +((v8u16)__builtin_msa_pckev_h((v8i16)__builtin_msa_sat_u_w((v4u32)(__b), 15), (v8i16)__builtin_msa_sat_u_w((v4u32)(__a), 15))) +#define msa_qpack_u64(__a, __b) \ +((v4u32)__builtin_msa_pckev_w((v4i32)__builtin_msa_sat_u_d((v2u64)(__b), 31), (v4i32)__builtin_msa_sat_u_d((v2u64)(__a), 31))) + +/* qpacku */ +#define msa_qpacku_s16(__a, __b) \ +((v16u8)__builtin_msa_pckev_b((v16i8)__builtin_msa_sat_u_h((v8u16)(__builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__b))), 7), \ + (v16i8)__builtin_msa_sat_u_h((v8u16)(__builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__a))), 7))) +#define msa_qpacku_s32(__a, __b) \ +((v8u16)__builtin_msa_pckev_h((v8i16)__builtin_msa_sat_u_w((v4u32)(__builtin_msa_max_s_w(__builtin_msa_fill_w(0), (v4i32)(__b))), 15), \ + (v8i16)__builtin_msa_sat_u_w((v4u32)(__builtin_msa_max_s_w(__builtin_msa_fill_w(0), (v4i32)(__a))), 15))) +#define msa_qpacku_s64(__a, __b) \ +((v4u32)__builtin_msa_pckev_w((v4i32)__builtin_msa_sat_u_d((v2u64)(__builtin_msa_max_s_d(__builtin_msa_fill_d(0), (v2i64)(__b))), 31), \ + (v4i32)__builtin_msa_sat_u_d((v2u64)(__builtin_msa_max_s_d(__builtin_msa_fill_d(0), (v2i64)(__a))), 31))) + +/* packr */ +#define msa_packr_s16(__a, __b, __c) \ +(__builtin_msa_pckev_b((v16i8)__builtin_msa_srai_h((v8i16)(__b), (int)(__c)), (v16i8)__builtin_msa_srai_h((v8i16)(__a), (int)(__c)))) +#define msa_packr_s32(__a, __b, __c) \ +(__builtin_msa_pckev_h((v8i16)__builtin_msa_srai_w((v4i32)(__b), (int)(__c)), (v8i16)__builtin_msa_srai_w((v4i32)(__a), (int)(__c)))) +#define msa_packr_s64(__a, __b, __c) \ +(__builtin_msa_pckev_w((v4i32)__builtin_msa_srai_d((v2i64)(__b), (int)(__c)), (v4i32)__builtin_msa_srai_d((v2i64)(__a), (int)(__c)))) +#define msa_packr_u16(__a, __b, __c) \ +((v16u8)__builtin_msa_pckev_b((v16i8)__builtin_msa_srli_h((v8i16)(__b), (int)(__c)), (v16i8)__builtin_msa_srli_h((v8i16)(__a), (int)(__c)))) +#define msa_packr_u32(__a, __b, __c) \ +((v8u16)__builtin_msa_pckev_h((v8i16)__builtin_msa_srli_w((v4i32)(__b), (int)(__c)), (v8i16)__builtin_msa_srli_w((v4i32)(__a), (int)(__c)))) +#define msa_packr_u64(__a, __b, __c) \ +((v4u32)__builtin_msa_pckev_w((v4i32)__builtin_msa_srli_d((v2i64)(__b), (int)(__c)), (v4i32)__builtin_msa_srli_d((v2i64)(__a), (int)(__c)))) + +/* rpackr */ +#define msa_rpackr_s16(__a, __b, __c) \ +(__builtin_msa_pckev_b((v16i8)__builtin_msa_srari_h((v8i16)(__b), (int)(__c)), (v16i8)__builtin_msa_srari_h((v8i16)(__a), (int)(__c)))) +#define msa_rpackr_s32(__a, __b, __c) \ +(__builtin_msa_pckev_h((v8i16)__builtin_msa_srari_w((v4i32)(__b), (int)(__c)), (v8i16)__builtin_msa_srari_w((v4i32)(__a), (int)(__c)))) +#define msa_rpackr_s64(__a, __b, __c) \ +(__builtin_msa_pckev_w((v4i32)__builtin_msa_srari_d((v2i64)(__b), (int)(__c)), (v4i32)__builtin_msa_srari_d((v2i64)(__a), (int)(__c)))) +#define msa_rpackr_u16(__a, __b, __c) \ +((v16u8)__builtin_msa_pckev_b((v16i8)__builtin_msa_srlri_h((v8i16)(__b), (int)(__c)), (v16i8)__builtin_msa_srlri_h((v8i16)(__a), (int)(__c)))) +#define msa_rpackr_u32(__a, __b, __c) \ +((v8u16)__builtin_msa_pckev_h((v8i16)__builtin_msa_srlri_w((v4i32)(__b), (int)(__c)), (v8i16)__builtin_msa_srlri_w((v4i32)(__a), (int)(__c)))) +#define msa_rpackr_u64(__a, __b, __c) \ +((v4u32)__builtin_msa_pckev_w((v4i32)__builtin_msa_srlri_d((v2i64)(__b), (int)(__c)), (v4i32)__builtin_msa_srlri_d((v2i64)(__a), (int)(__c)))) + +/* qrpackr */ +#define msa_qrpackr_s16(__a, __b, __c) \ +(__builtin_msa_pckev_b((v16i8)__builtin_msa_sat_s_h(__builtin_msa_srari_h((v8i16)(__b), (int)(__c)), 7), \ + (v16i8)__builtin_msa_sat_s_h(__builtin_msa_srari_h((v8i16)(__a), (int)(__c)), 7))) +#define msa_qrpackr_s32(__a, __b, __c) \ +(__builtin_msa_pckev_h((v8i16)__builtin_msa_sat_s_w(__builtin_msa_srari_w((v4i32)(__b), (int)(__c)), 15), \ + (v8i16)__builtin_msa_sat_s_w(__builtin_msa_srari_w((v4i32)(__a), (int)(__c)), 15))) +#define msa_qrpackr_s64(__a, __b, __c) \ +(__builtin_msa_pckev_w((v4i32)__builtin_msa_sat_s_d(__builtin_msa_srari_d((v2i64)(__b), (int)(__c)), 31), \ + (v4i32)__builtin_msa_sat_s_d(__builtin_msa_srari_d((v2i64)(__a), (int)(__c)), 31))) +#define msa_qrpackr_u16(__a, __b, __c) \ +((v16u8)__builtin_msa_pckev_b((v16i8)__builtin_msa_sat_u_h((v8u16)__builtin_msa_srlri_h((v8i16)(__b), (int)(__c)), 7), \ + (v16i8)__builtin_msa_sat_u_h((v8u16)__builtin_msa_srlri_h((v8i16)(__a), (int)(__c)), 7))) +#define msa_qrpackr_u32(__a, __b, __c) \ +((v8u16)__builtin_msa_pckev_h((v8i16)__builtin_msa_sat_u_w((v4u32)__builtin_msa_srlri_w((v4i32)(__b), (int)(__c)), 15), \ + (v8i16)__builtin_msa_sat_u_w((v4u32)__builtin_msa_srlri_w((v4i32)(__a), (int)(__c)), 15))) +#define msa_qrpackr_u64(__a, __b, __c) \ +((v4u32)__builtin_msa_pckev_w((v4i32)__builtin_msa_sat_u_d((v2u64)__builtin_msa_srlri_d((v2i64)(__b), (int)(__c)), 31), \ + (v4i32)__builtin_msa_sat_u_d((v2u64)__builtin_msa_srlri_d((v2i64)(__a), (int)(__c)), 31))) + +/* qrpackru */ +#define msa_qrpackru_s16(__a, __b, __c) \ +({ \ + v8i16 __d = __builtin_msa_srlri_h(__builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__a)), (int)(__c)); \ + v8i16 __e = __builtin_msa_srlri_h(__builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__b)), (int)(__c)); \ + (v16u8)__builtin_msa_pckev_b((v16i8)__builtin_msa_sat_u_h((v8u16)__e, 7), (v16i8)__builtin_msa_sat_u_h((v8u16)__d, 7)); \ +}) + +#define msa_qrpackru_s32(__a, __b, __c) \ +({ \ + v4i32 __d = __builtin_msa_srlri_w(__builtin_msa_max_s_w(__builtin_msa_fill_w(0), (v4i32)(__a)), (int)(__c)); \ + v4i32 __e = __builtin_msa_srlri_w(__builtin_msa_max_s_w(__builtin_msa_fill_w(0), (v4i32)(__b)), (int)(__c)); \ + (v8u16)__builtin_msa_pckev_h((v8i16)__builtin_msa_sat_u_w((v4u32)__e, 15), (v8i16)__builtin_msa_sat_u_w((v4u32)__d, 15)); \ +}) + +#define msa_qrpackru_s64(__a, __b, __c) \ +({ \ + v2i64 __d = __builtin_msa_srlri_d(__builtin_msa_max_s_d(__builtin_msa_fill_d(0), (v2i64)(__a)), (int)(__c)); \ + v2i64 __e = __builtin_msa_srlri_d(__builtin_msa_max_s_d(__builtin_msa_fill_d(0), (v2i64)(__b)), (int)(__c)); \ + (v4u32)__builtin_msa_pckev_w((v4i32)__builtin_msa_sat_u_d((v2u64)__e, 31), (v4i32)__builtin_msa_sat_u_d((v2u64)__d, 31)); \ +}) + +/* Minimum values between corresponding elements in the two vectors are written to the returned vector. */ +#define msa_minq_s8(__a, __b) (__builtin_msa_min_s_b(__a, __b)) +#define msa_minq_s16(__a, __b) (__builtin_msa_min_s_h(__a, __b)) +#define msa_minq_s32(__a, __b) (__builtin_msa_min_s_w(__a, __b)) +#define msa_minq_s64(__a, __b) (__builtin_msa_min_s_d(__a, __b)) +#define msa_minq_u8(__a, __b) ((v16u8)__builtin_msa_min_u_b(__a, __b)) +#define msa_minq_u16(__a, __b) ((v8u16)__builtin_msa_min_u_h(__a, __b)) +#define msa_minq_u32(__a, __b) ((v4u32)__builtin_msa_min_u_w(__a, __b)) +#define msa_minq_u64(__a, __b) ((v2u64)__builtin_msa_min_u_d(__a, __b)) +#define msa_minq_f32(__a, __b) (__builtin_msa_fmin_w(__a, __b)) +#define msa_minq_f64(__a, __b) (__builtin_msa_fmin_d(__a, __b)) + +/* Maximum values between corresponding elements in the two vectors are written to the returned vector. */ +#define msa_maxq_s8(__a, __b) (__builtin_msa_max_s_b(__a, __b)) +#define msa_maxq_s16(__a, __b) (__builtin_msa_max_s_h(__a, __b)) +#define msa_maxq_s32(__a, __b) (__builtin_msa_max_s_w(__a, __b)) +#define msa_maxq_s64(__a, __b) (__builtin_msa_max_s_d(__a, __b)) +#define msa_maxq_u8(__a, __b) ((v16u8)__builtin_msa_max_u_b(__a, __b)) +#define msa_maxq_u16(__a, __b) ((v8u16)__builtin_msa_max_u_h(__a, __b)) +#define msa_maxq_u32(__a, __b) ((v4u32)__builtin_msa_max_u_w(__a, __b)) +#define msa_maxq_u64(__a, __b) ((v2u64)__builtin_msa_max_u_d(__a, __b)) +#define msa_maxq_f32(__a, __b) (__builtin_msa_fmax_w(__a, __b)) +#define msa_maxq_f64(__a, __b) (__builtin_msa_fmax_d(__a, __b)) + +/* Vector type reinterpretion */ +#define MSA_TPV_REINTERPRET(_Tpv, Vec) ((_Tpv)(Vec)) + +/* Add the odd elements in vector __a with the even elements in vector __b to double width elements in the returned vector. */ +/* v8i16 msa_hadd_s16 ((v16i8)__a, (v16i8)__b) */ +#define msa_hadd_s16(__a, __b) (__builtin_msa_hadd_s_h((v16i8)(__a), (v16i8)(__b))) +/* v4i32 msa_hadd_s32 ((v8i16)__a, (v8i16)__b) */ +#define msa_hadd_s32(__a, __b) (__builtin_msa_hadd_s_w((v8i16)(__a), (v8i16)(__b))) +/* v2i64 msa_hadd_s64 ((v4i32)__a, (v4i32)__b) */ +#define msa_hadd_s64(__a, __b) (__builtin_msa_hadd_s_d((v4i32)(__a), (v4i32)(__b))) + +/* Copy even elements in __a to the left half and even elements in __b to the right half and return the result vector. */ +#define msa_pckev_s8(__a, __b) (__builtin_msa_pckev_b((v16i8)(__a), (v16i8)(__b))) +#define msa_pckev_s16(__a, __b) (__builtin_msa_pckev_h((v8i16)(__a), (v8i16)(__b))) +#define msa_pckev_s32(__a, __b) (__builtin_msa_pckev_w((v4i32)(__a), (v4i32)(__b))) +#define msa_pckev_s64(__a, __b) (__builtin_msa_pckev_d((v2i64)(__a), (v2i64)(__b))) + +/* Copy even elements in __a to the left half and even elements in __b to the right half and return the result vector. */ +#define msa_pckod_s8(__a, __b) (__builtin_msa_pckod_b((v16i8)(__a), (v16i8)(__b))) +#define msa_pckod_s16(__a, __b) (__builtin_msa_pckod_h((v8i16)(__a), (v8i16)(__b))) +#define msa_pckod_s32(__a, __b) (__builtin_msa_pckod_w((v4i32)(__a), (v4i32)(__b))) +#define msa_pckod_s64(__a, __b) (__builtin_msa_pckod_d((v2i64)(__a), (v2i64)(__b))) + +#ifdef _MIPSEB +#define LANE_IMM0_1(x) (0b1 - ((x) & 0b1)) +#define LANE_IMM0_3(x) (0b11 - ((x) & 0b11)) +#define LANE_IMM0_7(x) (0b111 - ((x) & 0b111)) +#define LANE_IMM0_15(x) (0b1111 - ((x) & 0b1111)) +#else +#define LANE_IMM0_1(x) ((x) & 0b1) +#define LANE_IMM0_3(x) ((x) & 0b11) +#define LANE_IMM0_7(x) ((x) & 0b111) +#define LANE_IMM0_15(x) ((x) & 0b1111) +#endif + +#define msa_get_lane_u8(__a, __b) ((uint8_t)(__a)[LANE_IMM0_7(__b)]) +#define msa_get_lane_s8(__a, __b) ((int8_t)(__a)[LANE_IMM0_7(__b)]) +#define msa_get_lane_u16(__a, __b) ((uint16_t)(__a)[LANE_IMM0_3(__b)]) +#define msa_get_lane_s16(__a, __b) ((int16_t)(__a)[LANE_IMM0_3(__b)]) +#define msa_get_lane_u32(__a, __b) ((uint32_t)(__a)[LANE_IMM0_1(__b)]) +#define msa_get_lane_s32(__a, __b) ((int32_t)(__a)[LANE_IMM0_1(__b)]) +#define msa_get_lane_f32(__a, __b) ((float)(__a)[LANE_IMM0_3(__b)]) +#define msa_get_lane_s64(__a, __b) ((int64_t)(__a)[LANE_IMM0_1(__b)]) +#define msa_get_lane_u64(__a, __b) ((uint64_t)(__a)[LANE_IMM0_1(__b)]) +#define msa_get_lane_f64(__a, __b) ((double)(__a)[LANE_IMM0_1(__b)]) +#define msa_getq_lane_u8(__a, imm0_15) ((uint8_t)__builtin_msa_copy_u_b((v16i8)(__a), imm0_15)) +#define msa_getq_lane_s8(__a, imm0_15) ((int8_t)__builtin_msa_copy_s_b(__a, imm0_15)) +#define msa_getq_lane_u16(__a, imm0_7) ((uint16_t)__builtin_msa_copy_u_h((v8i16)(__a), imm0_7)) +#define msa_getq_lane_s16(__a, imm0_7) ((int16_t)__builtin_msa_copy_s_h(__a, imm0_7)) +#define msa_getq_lane_u32(__a, imm0_3) __builtin_msa_copy_u_w((v4i32)(__a), imm0_3) +#define msa_getq_lane_s32 __builtin_msa_copy_s_w +#define msa_getq_lane_f32(__a, __b) ((float)(__a)[LANE_IMM0_3(__b)]) +#define msa_getq_lane_f64(__a, __b) ((double)(__a)[LANE_IMM0_1(__b)]) +#if (__mips == 64) +#define msa_getq_lane_u64(__a, imm0_1) __builtin_msa_copy_u_d((v2i64)(__a), imm0_1) +#define msa_getq_lane_s64 __builtin_msa_copy_s_d +#else +#define msa_getq_lane_u64(__a, imm0_1) ((uint64_t)(__a)[LANE_IMM0_1(imm0_1)]) +#define msa_getq_lane_s64(__a, imm0_1) ((int64_t)(__a)[LANE_IMM0_1(imm0_1)]) +#endif + +/* combine */ +#if (__mips == 64) +#define __COMBINE_64_64(__TYPE, a, b) ((__TYPE)((v2u64){((v1u64)(a))[0], ((v1u64)(b))[0]})) +#else +#define __COMBINE_64_64(__TYPE, a, b) ((__TYPE)((v4u32){((v2u32)(a))[0], ((v2u32)(a))[1], \ + ((v2u32)(b))[0], ((v2u32)(b))[1]})) +#endif + +/* v16i8 msa_combine_s8 (v8i8 __a, v8i8 __b) */ +#define msa_combine_s8(__a, __b) __COMBINE_64_64(v16i8, __a, __b) + +/* v8i16 msa_combine_s16(v4i16 __a, v4i16 __b) */ +#define msa_combine_s16(__a, __b) __COMBINE_64_64(v8i16, __a, __b) + +/* v4i32 msa_combine_s32(v2i32 __a, v2i32 __b) */ +#define msa_combine_s32(__a, __b) __COMBINE_64_64(v4i32, __a, __b) + +/* v2i64 msa_combine_s64(v1i64 __a, v1i64 __b) */ +#define msa_combine_s64(__a, __b) __COMBINE_64_64(v2i64, __a, __b) + +/* v4f32 msa_combine_f32(v2f32 __a, v2f32 __b) */ +#define msa_combine_f32(__a, __b) __COMBINE_64_64(v4f32, __a, __b) + +/* v16u8 msa_combine_u8(v8u8 __a, v8u8 __b) */ +#define msa_combine_u8(__a, __b) __COMBINE_64_64(v16u8, __a, __b) + +/* v8u16 msa_combine_u16(v4u16 __a, v4u16 __b) */ +#define msa_combine_u16(__a, __b) __COMBINE_64_64(v8u16, __a, __b) + +/* v4u32 msa_combine_u32(v2u32 __a, v2u32 __b) */ +#define msa_combine_u32(__a, __b) __COMBINE_64_64(v4u32, __a, __b) + +/* v2u64 msa_combine_u64(v1u64 __a, v1u64 __b) */ +#define msa_combine_u64(__a, __b) __COMBINE_64_64(v2u64, __a, __b) + +/* v2f64 msa_combine_f64(v1f64 __a, v1f64 __b) */ +#define msa_combine_f64(__a, __b) __COMBINE_64_64(v2f64, __a, __b) + +/* get_low, get_high */ +#if (__mips == 64) +#define __GET_LOW(__TYPE, a) ((__TYPE)((v1u64)(__builtin_msa_copy_u_d((v2i64)(a), 0)))) +#define __GET_HIGH(__TYPE, a) ((__TYPE)((v1u64)(__builtin_msa_copy_u_d((v2i64)(a), 1)))) +#else +#define __GET_LOW(__TYPE, a) ((__TYPE)(((v2u64)(a))[0])) +#define __GET_HIGH(__TYPE, a) ((__TYPE)(((v2u64)(a))[1])) +#endif + +/* v8i8 msa_get_low_s8(v16i8 __a) */ +#define msa_get_low_s8(__a) __GET_LOW(v8i8, __a) + +/* v4i16 msa_get_low_s16(v8i16 __a) */ +#define msa_get_low_s16(__a) __GET_LOW(v4i16, __a) + +/* v2i32 msa_get_low_s32(v4i32 __a) */ +#define msa_get_low_s32(__a) __GET_LOW(v2i32, __a) + +/* v1i64 msa_get_low_s64(v2i64 __a) */ +#define msa_get_low_s64(__a) __GET_LOW(v1i64, __a) + +/* v8u8 msa_get_low_u8(v16u8 __a) */ +#define msa_get_low_u8(__a) __GET_LOW(v8u8, __a) + +/* v4u16 msa_get_low_u16(v8u16 __a) */ +#define msa_get_low_u16(__a) __GET_LOW(v4u16, __a) + +/* v2u32 msa_get_low_u32(v4u32 __a) */ +#define msa_get_low_u32(__a) __GET_LOW(v2u32, __a) + +/* v1u64 msa_get_low_u64(v2u64 __a) */ +#define msa_get_low_u64(__a) __GET_LOW(v1u64, __a) + +/* v2f32 msa_get_low_f32(v4f32 __a) */ +#define msa_get_low_f32(__a) __GET_LOW(v2f32, __a) + +/* v1f64 msa_get_low_f64(v2f64 __a) */ +#define msa_get_low_f64(__a) __GET_LOW(v1f64, __a) + +/* v8i8 msa_get_high_s8(v16i8 __a) */ +#define msa_get_high_s8(__a) __GET_HIGH(v8i8, __a) + +/* v4i16 msa_get_high_s16(v8i16 __a) */ +#define msa_get_high_s16(__a) __GET_HIGH(v4i16, __a) + +/* v2i32 msa_get_high_s32(v4i32 __a) */ +#define msa_get_high_s32(__a) __GET_HIGH(v2i32, __a) + +/* v1i64 msa_get_high_s64(v2i64 __a) */ +#define msa_get_high_s64(__a) __GET_HIGH(v1i64, __a) + +/* v8u8 msa_get_high_u8(v16u8 __a) */ +#define msa_get_high_u8(__a) __GET_HIGH(v8u8, __a) + +/* v4u16 msa_get_high_u16(v8u16 __a) */ +#define msa_get_high_u16(__a) __GET_HIGH(v4u16, __a) + +/* v2u32 msa_get_high_u32(v4u32 __a) */ +#define msa_get_high_u32(__a) __GET_HIGH(v2u32, __a) + +/* v1u64 msa_get_high_u64(v2u64 __a) */ +#define msa_get_high_u64(__a) __GET_HIGH(v1u64, __a) + +/* v2f32 msa_get_high_f32(v4f32 __a) */ +#define msa_get_high_f32(__a) __GET_HIGH(v2f32, __a) + +/* v1f64 msa_get_high_f64(v2f64 __a) */ +#define msa_get_high_f64(__a) __GET_HIGH(v1f64, __a) + +/* ri = ai * b[lane] */ +/* v4f32 msa_mulq_lane_f32(v4f32 __a, v4f32 __b, const int __lane) */ +#define msa_mulq_lane_f32(__a, __b, __lane) ((__a) * msa_getq_lane_f32(__b, __lane)) + +/* ri = ai + bi * c[lane] */ +/* v4f32 msa_mlaq_lane_f32(v4f32 __a, v4f32 __b, v4f32 __c, const int __lane) */ +#define msa_mlaq_lane_f32(__a, __b, __c, __lane) ((__a) + ((__b) * msa_getq_lane_f32(__c, __lane))) + +/* uint16_t msa_sum_u16(v8u16 __a)*/ +#define msa_sum_u16(__a) \ +({ \ + v4u32 _b; \ + v2u64 _c; \ + _b = __builtin_msa_hadd_u_w(__a, __a); \ + _c = __builtin_msa_hadd_u_d(_b, _b); \ + (uint16_t)(_c[0] + _c[1]); \ +}) + +/* int16_t msa_sum_s16(v8i16 __a) */ +#define msa_sum_s16(__a) \ +({ \ + v4i32 _b; \ + v2i64 _c; \ + _b = __builtin_msa_hadd_s_w(__a, __a); \ + _c = __builtin_msa_hadd_s_d(_b, _b); \ + (int32_t)(_c[0] + _c[1]); \ +}) + + +/* uint32_t msa_sum_u32(v4u32 __a)*/ +#define msa_sum_u32(__a) \ +({ \ + v2u64 _b; \ + _b = __builtin_msa_hadd_u_d(__a, __a); \ + (uint32_t)(_b[0] + _b[1]); \ +}) + +/* int32_t msa_sum_s32(v4i32 __a)*/ +#define msa_sum_s32(__a) \ +({ \ + v2i64 _b; \ + _b = __builtin_msa_hadd_s_d(__a, __a); \ + (int64_t)(_b[0] + _b[1]); \ +}) + +/* uint8_t msa_sum_u8(v16u8 __a)*/ +#define msa_sum_u8(__a) \ +({ \ + v8u16 _b16; \ + v4u32 _c32; \ + _b16 = __builtin_msa_hadd_u_h(__a, __a); \ + _c32 = __builtin_msa_hadd_u_w(_b16, _b16); \ + (uint8_t)msa_sum_u32(_c32); \ +}) + +/* int8_t msa_sum_s8(v16s8 __a)*/ +#define msa_sum_s8(__a) \ +({ \ + v8i16 _b16; \ + v4i32 _c32; \ + _b16 = __builtin_msa_hadd_s_h(__a, __a); \ + _c32 = __builtin_msa_hadd_s_w(_b16, _b16); \ + (int16_t)msa_sum_s32(_c32); \ +}) + +/* float msa_sum_f32(v4f32 __a)*/ +#define msa_sum_f32(__a) ((__a)[0] + (__a)[1] + (__a)[2] + (__a)[3]) + +/* v8u16 msa_paddlq_u8(v16u8 __a) */ +#define msa_paddlq_u8(__a) (__builtin_msa_hadd_u_h(__a, __a)) + +/* v8i16 msa_paddlq_s8(v16i8 __a) */ +#define msa_paddlq_s8(__a) (__builtin_msa_hadd_s_h(__a, __a)) + +/* v4u32 msa_paddlq_u16 (v8u16 __a)*/ +#define msa_paddlq_u16(__a) (__builtin_msa_hadd_u_w(__a, __a)) + +/* v4i32 msa_paddlq_s16 (v8i16 __a)*/ +#define msa_paddlq_s16(__a) (__builtin_msa_hadd_s_w(__a, __a)) + +/* v2u64 msa_paddlq_u32(v4u32 __a) */ +#define msa_paddlq_u32(__a) (__builtin_msa_hadd_u_d(__a, __a)) + +/* v2i64 msa_paddlq_s32(v4i32 __a) */ +#define msa_paddlq_s32(__a) (__builtin_msa_hadd_s_d(__a, __a)) + +#define V8U8_2_V8U16(x) {(uint16_t)x[0], (uint16_t)x[1], (uint16_t)x[2], (uint16_t)x[3], \ + (uint16_t)x[4], (uint16_t)x[5], (uint16_t)x[6], (uint16_t)x[7]} +#define V8U8_2_V8I16(x) {(int16_t)x[0], (int16_t)x[1], (int16_t)x[2], (int16_t)x[3], \ + (int16_t)x[4], (int16_t)x[5], (int16_t)x[6], (int16_t)x[7]} +#define V8I8_2_V8I16(x) {(int16_t)x[0], (int16_t)x[1], (int16_t)x[2], (int16_t)x[3], \ + (int16_t)x[4], (int16_t)x[5], (int16_t)x[6], (int16_t)x[7]} +#define V4U16_2_V4U32(x) {(uint32_t)x[0], (uint32_t)x[1], (uint32_t)x[2], (uint32_t)x[3]} +#define V4U16_2_V4I32(x) {(int32_t)x[0], (int32_t)x[1], (int32_t)x[2], (int32_t)x[3]} +#define V4I16_2_V4I32(x) {(int32_t)x[0], (int32_t)x[1], (int32_t)x[2], (int32_t)x[3]} +#define V2U32_2_V2U64(x) {(uint64_t)x[0], (uint64_t)x[1]} +#define V2U32_2_V2I64(x) {(int64_t)x[0], (int64_t)x[1]} + +/* v8u16 msa_mull_u8(v8u8 __a, v8u8 __b) */ +#define msa_mull_u8(__a, __b) ((v8u16)__builtin_msa_mulv_h((v8i16)V8U8_2_V8I16(__a), (v8i16)V8U8_2_V8I16(__b))) + +/* v8i16 msa_mull_s8(v8i8 __a, v8i8 __b)*/ +#define msa_mull_s8(__a, __b) (__builtin_msa_mulv_h((v8i16)V8I8_2_V8I16(__a), (v8i16)V8I8_2_V8I16(__b))) + +/* v4u32 msa_mull_u16(v4u16 __a, v4u16 __b) */ +#define msa_mull_u16(__a, __b) ((v4u32)__builtin_msa_mulv_w((v4i32)V4U16_2_V4I32(__a), (v4i32)V4U16_2_V4I32(__b))) + +/* v4i32 msa_mull_s16(v4i16 __a, v4i16 __b) */ +#define msa_mull_s16(__a, __b) (__builtin_msa_mulv_w((v4i32)V4I16_2_V4I32(__a), (v4i32)V4I16_2_V4I32(__b))) + +/* v2u64 msa_mull_u32(v2u32 __a, v2u32 __b) */ +#define msa_mull_u32(__a, __b) ((v2u64)__builtin_msa_mulv_d((v2i64)V2U32_2_V2I64(__a), (v2i64)V2U32_2_V2I64(__b))) + +/* bitwise and: __builtin_msa_and_v */ +#define msa_andq_u8(__a, __b) ((v16u8)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) +#define msa_andq_s8(__a, __b) ((v16i8)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) +#define msa_andq_u16(__a, __b) ((v8u16)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) +#define msa_andq_s16(__a, __b) ((v8i16)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) +#define msa_andq_u32(__a, __b) ((v4u32)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) +#define msa_andq_s32(__a, __b) ((v4i32)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) +#define msa_andq_u64(__a, __b) ((v2u64)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) +#define msa_andq_s64(__a, __b) ((v2i64)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) + +/* bitwise or: __builtin_msa_or_v */ +#define msa_orrq_u8(__a, __b) ((v16u8)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) +#define msa_orrq_s8(__a, __b) ((v16i8)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) +#define msa_orrq_u16(__a, __b) ((v8u16)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) +#define msa_orrq_s16(__a, __b) ((v8i16)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) +#define msa_orrq_u32(__a, __b) ((v4u32)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) +#define msa_orrq_s32(__a, __b) ((v4i32)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) +#define msa_orrq_u64(__a, __b) ((v2u64)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) +#define msa_orrq_s64(__a, __b) ((v2i64)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) + +/* bitwise xor: __builtin_msa_xor_v */ +#define msa_eorq_u8(__a, __b) ((v16u8)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) +#define msa_eorq_s8(__a, __b) ((v16i8)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) +#define msa_eorq_u16(__a, __b) ((v8u16)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) +#define msa_eorq_s16(__a, __b) ((v8i16)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) +#define msa_eorq_u32(__a, __b) ((v4u32)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) +#define msa_eorq_s32(__a, __b) ((v4i32)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) +#define msa_eorq_u64(__a, __b) ((v2u64)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) +#define msa_eorq_s64(__a, __b) ((v2i64)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) + +/* bitwise not: v16u8 __builtin_msa_xori_b (v16u8, 0xff) */ +#define msa_mvnq_u8(__a) ((v16u8)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) +#define msa_mvnq_s8(__a) ((v16i8)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) +#define msa_mvnq_u16(__a) ((v8u16)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) +#define msa_mvnq_s16(__a) ((v8i16)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) +#define msa_mvnq_u32(__a) ((v4u32)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) +#define msa_mvnq_s32(__a) ((v4i32)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) +#define msa_mvnq_u64(__a) ((v2u64)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) +#define msa_mvnq_s64(__a) ((v2i64)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) + +/* compare equal: ceq -> ri = ai == bi ? 1...1:0...0 */ +#define msa_ceqq_u8(__a, __b) ((v16u8)__builtin_msa_ceq_b((v16i8)(__a), (v16i8)(__b))) +#define msa_ceqq_s8(__a, __b) ((v16u8)__builtin_msa_ceq_b((v16i8)(__a), (v16i8)(__b))) +#define msa_ceqq_u16(__a, __b) ((v8u16)__builtin_msa_ceq_h((v8i16)(__a), (v8i16)(__b))) +#define msa_ceqq_s16(__a, __b) ((v8u16)__builtin_msa_ceq_h((v8i16)(__a), (v8i16)(__b))) +#define msa_ceqq_u32(__a, __b) ((v4u32)__builtin_msa_ceq_w((v4i32)(__a), (v4i32)(__b))) +#define msa_ceqq_s32(__a, __b) ((v4u32)__builtin_msa_ceq_w((v4i32)(__a), (v4i32)(__b))) +#define msa_ceqq_f32(__a, __b) ((v4u32)__builtin_msa_fceq_w((v4f32)(__a), (v4f32)(__b))) +#define msa_ceqq_u64(__a, __b) ((v2u64)__builtin_msa_ceq_d((v2i64)(__a), (v2i64)(__b))) +#define msa_ceqq_s64(__a, __b) ((v2u64)__builtin_msa_ceq_d((v2i64)(__a), (v2i64)(__b))) +#define msa_ceqq_f64(__a, __b) ((v2u64)__builtin_msa_fceq_d((v2f64)(__a), (v2f64)(__b))) + +/* Compare less-than: clt -> ri = ai < bi ? 1...1:0...0 */ +#define msa_cltq_u8(__a, __b) ((v16u8)__builtin_msa_clt_u_b((v16u8)(__a), (v16u8)(__b))) +#define msa_cltq_s8(__a, __b) ((v16u8)__builtin_msa_clt_s_b((v16i8)(__a), (v16i8)(__b))) +#define msa_cltq_u16(__a, __b) ((v8u16)__builtin_msa_clt_u_h((v8u16)(__a), (v8u16)(__b))) +#define msa_cltq_s16(__a, __b) ((v8u16)__builtin_msa_clt_s_h((v8i16)(__a), (v8i16)(__b))) +#define msa_cltq_u32(__a, __b) ((v4u32)__builtin_msa_clt_u_w((v4u32)(__a), (v4u32)(__b))) +#define msa_cltq_s32(__a, __b) ((v4u32)__builtin_msa_clt_s_w((v4i32)(__a), (v4i32)(__b))) +#define msa_cltq_f32(__a, __b) ((v4u32)__builtin_msa_fclt_w((v4f32)(__a), (v4f32)(__b))) +#define msa_cltq_u64(__a, __b) ((v2u64)__builtin_msa_clt_u_d((v2u64)(__a), (v2u64)(__b))) +#define msa_cltq_s64(__a, __b) ((v2u64)__builtin_msa_clt_s_d((v2i64)(__a), (v2i64)(__b))) +#define msa_cltq_f64(__a, __b) ((v2u64)__builtin_msa_fclt_d((v2f64)(__a), (v2f64)(__b))) + +/* compare greater-than: cgt -> ri = ai > bi ? 1...1:0...0 */ +#define msa_cgtq_u8(__a, __b) ((v16u8)__builtin_msa_clt_u_b((v16u8)(__b), (v16u8)(__a))) +#define msa_cgtq_s8(__a, __b) ((v16u8)__builtin_msa_clt_s_b((v16i8)(__b), (v16i8)(__a))) +#define msa_cgtq_u16(__a, __b) ((v8u16)__builtin_msa_clt_u_h((v8u16)(__b), (v8u16)(__a))) +#define msa_cgtq_s16(__a, __b) ((v8u16)__builtin_msa_clt_s_h((v8i16)(__b), (v8i16)(__a))) +#define msa_cgtq_u32(__a, __b) ((v4u32)__builtin_msa_clt_u_w((v4u32)(__b), (v4u32)(__a))) +#define msa_cgtq_s32(__a, __b) ((v4u32)__builtin_msa_clt_s_w((v4i32)(__b), (v4i32)(__a))) +#define msa_cgtq_f32(__a, __b) ((v4u32)__builtin_msa_fclt_w((v4f32)(__b), (v4f32)(__a))) +#define msa_cgtq_u64(__a, __b) ((v2u64)__builtin_msa_clt_u_d((v2u64)(__b), (v2u64)(__a))) +#define msa_cgtq_s64(__a, __b) ((v2u64)__builtin_msa_clt_s_d((v2i64)(__b), (v2i64)(__a))) +#define msa_cgtq_f64(__a, __b) ((v2u64)__builtin_msa_fclt_d((v2f64)(__b), (v2f64)(__a))) + +/* compare less-equal: cle -> ri = ai <= bi ? 1...1:0...0 */ +#define msa_cleq_u8(__a, __b) ((v16u8)__builtin_msa_cle_u_b((v16u8)(__a), (v16u8)(__b))) +#define msa_cleq_s8(__a, __b) ((v16u8)__builtin_msa_cle_s_b((v16i8)(__a), (v16i8)(__b))) +#define msa_cleq_u16(__a, __b) ((v8u16)__builtin_msa_cle_u_h((v8u16)(__a), (v8u16)(__b))) +#define msa_cleq_s16(__a, __b) ((v8u16)__builtin_msa_cle_s_h((v8i16)(__a), (v8i16)(__b))) +#define msa_cleq_u32(__a, __b) ((v4u32)__builtin_msa_cle_u_w((v4u32)(__a), (v4u32)(__b))) +#define msa_cleq_s32(__a, __b) ((v4u32)__builtin_msa_cle_s_w((v4i32)(__a), (v4i32)(__b))) +#define msa_cleq_f32(__a, __b) ((v4u32)__builtin_msa_fcle_w((v4f32)(__a), (v4f32)(__b))) +#define msa_cleq_u64(__a, __b) ((v2u64)__builtin_msa_cle_u_d((v2u64)(__a), (v2u64)(__b))) +#define msa_cleq_s64(__a, __b) ((v2u64)__builtin_msa_cle_s_d((v2i64)(__a), (v2i64)(__b))) +#define msa_cleq_f64(__a, __b) ((v2u64)__builtin_msa_fcle_d((v2f64)(__a), (v2f64)(__b))) + +/* compare greater-equal: cge -> ri = ai >= bi ? 1...1:0...0 */ +#define msa_cgeq_u8(__a, __b) ((v16u8)__builtin_msa_cle_u_b((v16u8)(__b), (v16u8)(__a))) +#define msa_cgeq_s8(__a, __b) ((v16u8)__builtin_msa_cle_s_b((v16i8)(__b), (v16i8)(__a))) +#define msa_cgeq_u16(__a, __b) ((v8u16)__builtin_msa_cle_u_h((v8u16)(__b), (v8u16)(__a))) +#define msa_cgeq_s16(__a, __b) ((v8u16)__builtin_msa_cle_s_h((v8i16)(__b), (v8i16)(__a))) +#define msa_cgeq_u32(__a, __b) ((v4u32)__builtin_msa_cle_u_w((v4u32)(__b), (v4u32)(__a))) +#define msa_cgeq_s32(__a, __b) ((v4u32)__builtin_msa_cle_s_w((v4i32)(__b), (v4i32)(__a))) +#define msa_cgeq_f32(__a, __b) ((v4u32)__builtin_msa_fcle_w((v4f32)(__b), (v4f32)(__a))) +#define msa_cgeq_u64(__a, __b) ((v2u64)__builtin_msa_cle_u_d((v2u64)(__b), (v2u64)(__a))) +#define msa_cgeq_s64(__a, __b) ((v2u64)__builtin_msa_cle_s_d((v2i64)(__b), (v2i64)(__a))) +#define msa_cgeq_f64(__a, __b) ((v2u64)__builtin_msa_fcle_d((v2f64)(__b), (v2f64)(__a))) + +/* Shift Left Logical: shl -> ri = ai << bi; */ +#define msa_shlq_u8(__a, __b) ((v16u8)__builtin_msa_sll_b((v16i8)(__a), (v16i8)(__b))) +#define msa_shlq_s8(__a, __b) ((v16i8)__builtin_msa_sll_b((v16i8)(__a), (v16i8)(__b))) +#define msa_shlq_u16(__a, __b) ((v8u16)__builtin_msa_sll_h((v8i16)(__a), (v8i16)(__b))) +#define msa_shlq_s16(__a, __b) ((v8i16)__builtin_msa_sll_h((v8i16)(__a), (v8i16)(__b))) +#define msa_shlq_u32(__a, __b) ((v4u32)__builtin_msa_sll_w((v4i32)(__a), (v4i32)(__b))) +#define msa_shlq_s32(__a, __b) ((v4i32)__builtin_msa_sll_w((v4i32)(__a), (v4i32)(__b))) +#define msa_shlq_u64(__a, __b) ((v2u64)__builtin_msa_sll_d((v2i64)(__a), (v2i64)(__b))) +#define msa_shlq_s64(__a, __b) ((v2i64)__builtin_msa_sll_d((v2i64)(__a), (v2i64)(__b))) + +/* Immediate Shift Left Logical: shl -> ri = ai << imm; */ +#define msa_shlq_n_u8(__a, __imm) ((v16u8)__builtin_msa_slli_b((v16i8)(__a), __imm)) +#define msa_shlq_n_s8(__a, __imm) ((v16i8)__builtin_msa_slli_b((v16i8)(__a), __imm)) +#define msa_shlq_n_u16(__a, __imm) ((v8u16)__builtin_msa_slli_h((v8i16)(__a), __imm)) +#define msa_shlq_n_s16(__a, __imm) ((v8i16)__builtin_msa_slli_h((v8i16)(__a), __imm)) +#define msa_shlq_n_u32(__a, __imm) ((v4u32)__builtin_msa_slli_w((v4i32)(__a), __imm)) +#define msa_shlq_n_s32(__a, __imm) ((v4i32)__builtin_msa_slli_w((v4i32)(__a), __imm)) +#define msa_shlq_n_u64(__a, __imm) ((v2u64)__builtin_msa_slli_d((v2i64)(__a), __imm)) +#define msa_shlq_n_s64(__a, __imm) ((v2i64)__builtin_msa_slli_d((v2i64)(__a), __imm)) + +/* shift right: shrq -> ri = ai >> bi; */ +#define msa_shrq_u8(__a, __b) ((v16u8)__builtin_msa_srl_b((v16i8)(__a), (v16i8)(__b))) +#define msa_shrq_s8(__a, __b) ((v16i8)__builtin_msa_sra_b((v16i8)(__a), (v16i8)(__b))) +#define msa_shrq_u16(__a, __b) ((v8u16)__builtin_msa_srl_h((v8i16)(__a), (v8i16)(__b))) +#define msa_shrq_s16(__a, __b) ((v8i16)__builtin_msa_sra_h((v8i16)(__a), (v8i16)(__b))) +#define msa_shrq_u32(__a, __b) ((v4u32)__builtin_msa_srl_w((v4i32)(__a), (v4i32)(__b))) +#define msa_shrq_s32(__a, __b) ((v4i32)__builtin_msa_sra_w((v4i32)(__a), (v4i32)(__b))) +#define msa_shrq_u64(__a, __b) ((v2u64)__builtin_msa_srl_d((v2i64)(__a), (v2i64)(__b))) +#define msa_shrq_s64(__a, __b) ((v2i64)__builtin_msa_sra_d((v2i64)(__a), (v2i64)(__b))) + +/* Immediate Shift Right: shr -> ri = ai >> imm; */ +#define msa_shrq_n_u8(__a, __imm) ((v16u8)__builtin_msa_srli_b((v16i8)(__a), __imm)) +#define msa_shrq_n_s8(__a, __imm) ((v16i8)__builtin_msa_srai_b((v16i8)(__a), __imm)) +#define msa_shrq_n_u16(__a, __imm) ((v8u16)__builtin_msa_srli_h((v8i16)(__a), __imm)) +#define msa_shrq_n_s16(__a, __imm) ((v8i16)__builtin_msa_srai_h((v8i16)(__a), __imm)) +#define msa_shrq_n_u32(__a, __imm) ((v4u32)__builtin_msa_srli_w((v4i32)(__a), __imm)) +#define msa_shrq_n_s32(__a, __imm) ((v4i32)__builtin_msa_srai_w((v4i32)(__a), __imm)) +#define msa_shrq_n_u64(__a, __imm) ((v2u64)__builtin_msa_srli_d((v2i64)(__a), __imm)) +#define msa_shrq_n_s64(__a, __imm) ((v2i64)__builtin_msa_srai_d((v2i64)(__a), __imm)) + +/* Immediate Shift Right Rounded: shr -> ri = ai >> (rounded)imm; */ +#define msa_rshrq_n_u8(__a, __imm) ((v16u8)__builtin_msa_srlri_b((v16i8)(__a), __imm)) +#define msa_rshrq_n_s8(__a, __imm) ((v16i8)__builtin_msa_srari_b((v16i8)(__a), __imm)) +#define msa_rshrq_n_u16(__a, __imm) ((v8u16)__builtin_msa_srlri_h((v8i16)(__a), __imm)) +#define msa_rshrq_n_s16(__a, __imm) ((v8i16)__builtin_msa_srari_h((v8i16)(__a), __imm)) +#define msa_rshrq_n_u32(__a, __imm) ((v4u32)__builtin_msa_srlri_w((v4i32)(__a), __imm)) +#define msa_rshrq_n_s32(__a, __imm) ((v4i32)__builtin_msa_srari_w((v4i32)(__a), __imm)) +#define msa_rshrq_n_u64(__a, __imm) ((v2u64)__builtin_msa_srlri_d((v2i64)(__a), __imm)) +#define msa_rshrq_n_s64(__a, __imm) ((v2i64)__builtin_msa_srari_d((v2i64)(__a), __imm)) + +/* Vector saturating rounding shift left, qrshl -> ri = ai << bi; */ +#define msa_qrshrq_s32(a, b) ((v4i32)__msa_srar_w((v4i32)(a), (v4i32)(b))) + +/* Rename the msa builtin func to unify the name style for intrin_msa.hpp */ +#define msa_qaddq_u8 __builtin_msa_adds_u_b +#define msa_qaddq_s8 __builtin_msa_adds_s_b +#define msa_qaddq_u16 __builtin_msa_adds_u_h +#define msa_qaddq_s16 __builtin_msa_adds_s_h +#define msa_qaddq_u32 __builtin_msa_adds_u_w +#define msa_qaddq_s32 __builtin_msa_adds_s_w +#define msa_qaddq_u64 __builtin_msa_adds_u_d +#define msa_qaddq_s64 __builtin_msa_adds_s_d +#define msa_addq_u8(a, b) ((v16u8)__builtin_msa_addv_b((v16i8)(a), (v16i8)(b))) +#define msa_addq_s8 __builtin_msa_addv_b +#define msa_addq_u16(a, b) ((v8u16)__builtin_msa_addv_h((v8i16)(a), (v8i16)(b))) +#define msa_addq_s16 __builtin_msa_addv_h +#define msa_addq_u32(a, b) ((v4u32)__builtin_msa_addv_w((v4i32)(a), (v4i32)(b))) +#define msa_addq_s32 __builtin_msa_addv_w +#define msa_addq_f32 __builtin_msa_fadd_w +#define msa_addq_u64(a, b) ((v2u64)__builtin_msa_addv_d((v2i64)(a), (v2i64)(b))) +#define msa_addq_s64 __builtin_msa_addv_d +#define msa_addq_f64 __builtin_msa_fadd_d +#define msa_qsubq_u8 __builtin_msa_subs_u_b +#define msa_qsubq_s8 __builtin_msa_subs_s_b +#define msa_qsubq_u16 __builtin_msa_subs_u_h +#define msa_qsubq_s16 __builtin_msa_subs_s_h +#define msa_subq_u8(a, b) ((v16u8)__builtin_msa_subv_b((v16i8)(a), (v16i8)(b))) +#define msa_subq_s8 __builtin_msa_subv_b +#define msa_subq_u16(a, b) ((v8u16)__builtin_msa_subv_h((v8i16)(a), (v8i16)(b))) +#define msa_subq_s16 __builtin_msa_subv_h +#define msa_subq_u32(a, b) ((v4u32)__builtin_msa_subv_w((v4i32)(a), (v4i32)(b))) +#define msa_subq_s32 __builtin_msa_subv_w +#define msa_subq_f32 __builtin_msa_fsub_w +#define msa_subq_u64(a, b) ((v2u64)__builtin_msa_subv_d((v2i64)(a), (v2i64)(b))) +#define msa_subq_s64 __builtin_msa_subv_d +#define msa_subq_f64 __builtin_msa_fsub_d +#define msa_mulq_u8(a, b) ((v16u8)__builtin_msa_mulv_b((v16i8)(a), (v16i8)(b))) +#define msa_mulq_s8(a, b) ((v16i8)__builtin_msa_mulv_b((v16i8)(a), (v16i8)(b))) +#define msa_mulq_u16(a, b) ((v8u16)__builtin_msa_mulv_h((v8i16)(a), (v8i16)(b))) +#define msa_mulq_s16(a, b) ((v8i16)__builtin_msa_mulv_h((v8i16)(a), (v8i16)(b))) +#define msa_mulq_u32(a, b) ((v4u32)__builtin_msa_mulv_w((v4i32)(a), (v4i32)(b))) +#define msa_mulq_s32(a, b) ((v4i32)__builtin_msa_mulv_w((v4i32)(a), (v4i32)(b))) +#define msa_mulq_u64(a, b) ((v2u64)__builtin_msa_mulv_d((v2i64)(a), (v2i64)(b))) +#define msa_mulq_s64(a, b) ((v2i64)__builtin_msa_mulv_d((v2i64)(a), (v2i64)(b))) +#define msa_mulq_f32 __builtin_msa_fmul_w +#define msa_mulq_f64 __builtin_msa_fmul_d +#define msa_divq_f32 __builtin_msa_fdiv_w +#define msa_divq_f64 __builtin_msa_fdiv_d +#define msa_dotp_s_h __builtin_msa_dotp_s_h +#define msa_dotp_s_w __builtin_msa_dotp_s_w +#define msa_dotp_s_d __builtin_msa_dotp_s_d +#define msa_dotp_u_h __builtin_msa_dotp_u_h +#define msa_dotp_u_w __builtin_msa_dotp_u_w +#define msa_dotp_u_d __builtin_msa_dotp_u_d +#define msa_dpadd_s_h __builtin_msa_dpadd_s_h +#define msa_dpadd_s_w __builtin_msa_dpadd_s_w +#define msa_dpadd_s_d __builtin_msa_dpadd_s_d +#define msa_dpadd_u_h __builtin_msa_dpadd_u_h +#define msa_dpadd_u_w __builtin_msa_dpadd_u_w +#define msa_dpadd_u_d __builtin_msa_dpadd_u_d + +#define ILVRL_B2(RTYPE, in0, in1, low, hi) do { \ + low = (RTYPE)__builtin_msa_ilvr_b((v16i8)(in0), (v16i8)(in1)); \ + hi = (RTYPE)__builtin_msa_ilvl_b((v16i8)(in0), (v16i8)(in1)); \ + } while (0) +#define ILVRL_B2_UB(...) ILVRL_B2(v16u8, __VA_ARGS__) +#define ILVRL_B2_SB(...) ILVRL_B2(v16i8, __VA_ARGS__) +#define ILVRL_B2_UH(...) ILVRL_B2(v8u16, __VA_ARGS__) +#define ILVRL_B2_SH(...) ILVRL_B2(v8i16, __VA_ARGS__) +#define ILVRL_B2_SW(...) ILVRL_B2(v4i32, __VA_ARGS__) + +#define ILVRL_H2(RTYPE, in0, in1, low, hi) do { \ + low = (RTYPE)__builtin_msa_ilvr_h((v8i16)(in0), (v8i16)(in1)); \ + hi = (RTYPE)__builtin_msa_ilvl_h((v8i16)(in0), (v8i16)(in1)); \ + } while (0) +#define ILVRL_H2_UB(...) ILVRL_H2(v16u8, __VA_ARGS__) +#define ILVRL_H2_SB(...) ILVRL_H2(v16i8, __VA_ARGS__) +#define ILVRL_H2_UH(...) ILVRL_H2(v8u16, __VA_ARGS__) +#define ILVRL_H2_SH(...) ILVRL_H2(v8i16, __VA_ARGS__) +#define ILVRL_H2_SW(...) ILVRL_H2(v4i32, __VA_ARGS__) +#define ILVRL_H2_UW(...) ILVRL_H2(v4u32, __VA_ARGS__) + +#define ILVRL_W2(RTYPE, in0, in1, low, hi) do { \ + low = (RTYPE)__builtin_msa_ilvr_w((v4i32)(in0), (v4i32)(in1)); \ + hi = (RTYPE)__builtin_msa_ilvl_w((v4i32)(in0), (v4i32)(in1)); \ + } while (0) +#define ILVRL_W2_UB(...) ILVRL_W2(v16u8, __VA_ARGS__) +#define ILVRL_W2_SH(...) ILVRL_W2(v8i16, __VA_ARGS__) +#define ILVRL_W2_SW(...) ILVRL_W2(v4i32, __VA_ARGS__) +#define ILVRL_W2_UW(...) ILVRL_W2(v4u32, __VA_ARGS__) + +/* absq, qabsq (r = |a|;) */ +#define msa_absq_s8(a) __builtin_msa_add_a_b(a, __builtin_msa_fill_b(0)) +#define msa_absq_s16(a) __builtin_msa_add_a_h(a, __builtin_msa_fill_h(0)) +#define msa_absq_s32(a) __builtin_msa_add_a_w(a, __builtin_msa_fill_w(0)) +#define msa_absq_s64(a) __builtin_msa_add_a_d(a, __builtin_msa_fill_d(0)) +#define msa_absq_f32(a) ((v4f32)__builtin_msa_bclri_w((v4u32)(a), 31)) +#define msa_absq_f64(a) ((v2f64)__builtin_msa_bclri_d((v2u64)(a), 63)) +#define msa_qabsq_s8(a) __builtin_msa_adds_a_b(a, __builtin_msa_fill_b(0)) +#define msa_qabsq_s16(a) __builtin_msa_adds_a_h(a, __builtin_msa_fill_h(0)) +#define msa_qabsq_s32(a) __builtin_msa_adds_a_w(a, __builtin_msa_fill_w(0)) +#define msa_qabsq_s64(a) __builtin_msa_adds_a_d(a, __builtin_msa_fill_d(0)) + +/* abdq, qabdq (r = |a - b|;) */ +#define msa_abdq_u8 __builtin_msa_asub_u_b +#define msa_abdq_s8 __builtin_msa_asub_s_b +#define msa_abdq_u16 __builtin_msa_asub_u_h +#define msa_abdq_s16 __builtin_msa_asub_s_h +#define msa_abdq_u32 __builtin_msa_asub_u_w +#define msa_abdq_s32 __builtin_msa_asub_s_w +#define msa_abdq_u64 __builtin_msa_asub_u_d +#define msa_abdq_s64 __builtin_msa_asub_s_d +#define msa_abdq_f32(a, b) msa_absq_f32(__builtin_msa_fsub_w(a, b)) +#define msa_abdq_f64(a, b) msa_absq_f64(__builtin_msa_fsub_d(a, b)) +#define msa_qabdq_s8(a, b) msa_qabsq_s8(__builtin_msa_subs_s_b(a, b)) +#define msa_qabdq_s16(a, b) msa_qabsq_s16(__builtin_msa_subs_s_h(a, b)) +#define msa_qabdq_s32(a, b) msa_qabsq_s32(__builtin_msa_subs_s_w(a, b)) +#define msa_qabdq_s64(a, b) msa_qabsq_s64(__builtin_msa_subs_s_d(a, b)) + +/* sqrtq, rsqrtq */ +#define msa_sqrtq_f32 __builtin_msa_fsqrt_w +#define msa_sqrtq_f64 __builtin_msa_fsqrt_d +#define msa_rsqrtq_f32 __builtin_msa_frsqrt_w +#define msa_rsqrtq_f64 __builtin_msa_frsqrt_d + + +/* mlaq: r = a + b * c; */ +__extension__ extern __inline v4i32 +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) +msa_mlaq_s32(v4i32 __a, v4i32 __b, v4i32 __c) +{ + __asm__ volatile("maddv.w %w[__a], %w[__b], %w[__c]\n" + // Outputs + : [__a] "+f"(__a) + // Inputs + : [__b] "f"(__b), [__c] "f"(__c)); + return __a; +} + +__extension__ extern __inline v2i64 +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) +msa_mlaq_s64(v2i64 __a, v2i64 __b, v2i64 __c) +{ + __asm__ volatile("maddv.d %w[__a], %w[__b], %w[__c]\n" + // Outputs + : [__a] "+f"(__a) + // Inputs + : [__b] "f"(__b), [__c] "f"(__c)); + return __a; +} + +__extension__ extern __inline v4f32 +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) +msa_mlaq_f32(v4f32 __a, v4f32 __b, v4f32 __c) +{ + __asm__ volatile("fmadd.w %w[__a], %w[__b], %w[__c]\n" + // Outputs + : [__a] "+f"(__a) + // Inputs + : [__b] "f"(__b), [__c] "f"(__c)); + return __a; +} + +__extension__ extern __inline v2f64 +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) +msa_mlaq_f64(v2f64 __a, v2f64 __b, v2f64 __c) +{ + __asm__ volatile("fmadd.d %w[__a], %w[__b], %w[__c]\n" + // Outputs + : [__a] "+f"(__a) + // Inputs + : [__b] "f"(__b), [__c] "f"(__c)); + return __a; +} + +/* cntq */ +#define msa_cntq_s8 __builtin_msa_pcnt_b +#define msa_cntq_s16 __builtin_msa_pcnt_h +#define msa_cntq_s32 __builtin_msa_pcnt_w +#define msa_cntq_s64 __builtin_msa_pcnt_d + +/* bslq (a: mask; r = b(if a == 0); r = c(if a == 1);) */ +#define msa_bslq_u8 __builtin_msa_bsel_v + +/* ilvrq, ilvlq (For EL only, ilvrq: b0, a0, b1, a1; ilvlq: b2, a2, b3, a3;) */ +#define msa_ilvrq_s8 __builtin_msa_ilvr_b +#define msa_ilvrq_s16 __builtin_msa_ilvr_h +#define msa_ilvrq_s32 __builtin_msa_ilvr_w +#define msa_ilvrq_s64 __builtin_msa_ilvr_d +#define msa_ilvlq_s8 __builtin_msa_ilvl_b +#define msa_ilvlq_s16 __builtin_msa_ilvl_h +#define msa_ilvlq_s32 __builtin_msa_ilvl_w +#define msa_ilvlq_s64 __builtin_msa_ilvl_d + +/* ilvevq, ilvodq (ilvevq: b0, a0, b2, a2; ilvodq: b1, a1, b3, a3; ) */ +#define msa_ilvevq_s8 __builtin_msa_ilvev_b +#define msa_ilvevq_s16 __builtin_msa_ilvev_h +#define msa_ilvevq_s32 __builtin_msa_ilvev_w +#define msa_ilvevq_s64 __builtin_msa_ilvev_d +#define msa_ilvodq_s8 __builtin_msa_ilvod_b +#define msa_ilvodq_s16 __builtin_msa_ilvod_h +#define msa_ilvodq_s32 __builtin_msa_ilvod_w +#define msa_ilvodq_s64 __builtin_msa_ilvod_d + +/* extq (r = (a || b); a concatenation b and get elements from index c) */ +#ifdef _MIPSEB +#define msa_extq_s8(a, b, c) \ +(__builtin_msa_vshf_b(__builtin_msa_subv_b((v16i8)((v2i64){0x1716151413121110, 0x1F1E1D1C1B1A1918}), __builtin_msa_fill_b(c)), a, b)) +#define msa_extq_s16(a, b, c) \ +(__builtin_msa_vshf_h(__builtin_msa_subv_h((v8i16)((v2i64){0x000B000A00090008, 0x000F000E000D000C}), __builtin_msa_fill_h(c)), a, b)) +#define msa_extq_s32(a, b, c) \ +(__builtin_msa_vshf_w(__builtin_msa_subv_w((v4i32)((v2i64){0x0000000500000004, 0x0000000700000006}), __builtin_msa_fill_w(c)), a, b)) +#define msa_extq_s64(a, b, c) \ +(__builtin_msa_vshf_d(__builtin_msa_subv_d((v2i64){0x0000000000000002, 0x0000000000000003}, __builtin_msa_fill_d(c)), a, b)) +#else +#define msa_extq_s8(a, b, c) \ +(__builtin_msa_vshf_b(__builtin_msa_addv_b((v16i8)((v2i64){0x0706050403020100, 0x0F0E0D0C0B0A0908}), __builtin_msa_fill_b(c)), b, a)) +#define msa_extq_s16(a, b, c) \ +(__builtin_msa_vshf_h(__builtin_msa_addv_h((v8i16)((v2i64){0x0003000200010000, 0x0007000600050004}), __builtin_msa_fill_h(c)), b, a)) +#define msa_extq_s32(a, b, c) \ +(__builtin_msa_vshf_w(__builtin_msa_addv_w((v4i32)((v2i64){0x0000000100000000, 0x0000000300000002}), __builtin_msa_fill_w(c)), b, a)) +#define msa_extq_s64(a, b, c) \ +(__builtin_msa_vshf_d(__builtin_msa_addv_d((v2i64){0x0000000000000000, 0x0000000000000001}, __builtin_msa_fill_d(c)), b, a)) +#endif /* _MIPSEB */ + +/* cvttruncq, cvttintq, cvtrintq */ +#define msa_cvttruncq_u32_f32 __builtin_msa_ftrunc_u_w +#define msa_cvttruncq_s32_f32 __builtin_msa_ftrunc_s_w +#define msa_cvttruncq_u64_f64 __builtin_msa_ftrunc_u_d +#define msa_cvttruncq_s64_f64 __builtin_msa_ftrunc_s_d +#define msa_cvttintq_u32_f32 __builtin_msa_ftint_u_w +#define msa_cvttintq_s32_f32 __builtin_msa_ftint_s_w +#define msa_cvttintq_u64_f64 __builtin_msa_ftint_u_d +#define msa_cvttintq_s64_f64 __builtin_msa_ftint_s_d +#define msa_cvtrintq_f32 __builtin_msa_frint_w +#define msa_cvtrintq_f64 __builtin_msa_frint_d + +/* cvtfintq, cvtfq */ +#define msa_cvtfintq_f32_u32 __builtin_msa_ffint_u_w +#define msa_cvtfintq_f32_s32 __builtin_msa_ffint_s_w +#define msa_cvtfintq_f64_u64 __builtin_msa_ffint_u_d +#define msa_cvtfintq_f64_s64 __builtin_msa_ffint_s_d +#define msa_cvtfq_f32_f64 __builtin_msa_fexdo_w +#define msa_cvtflq_f64_f32 __builtin_msa_fexupr_d +#define msa_cvtfhq_f64_f32 __builtin_msa_fexupl_d + +#define msa_addl_u8(a, b) ((v8u16)__builtin_msa_addv_h((v8i16)V8U8_2_V8I16(a), (v8i16)V8U8_2_V8I16(b))) +#define msa_addl_s8(a, b) (__builtin_msa_addv_h((v8i16)V8I8_2_V8I16(a), (v8i16)V8I8_2_V8I16(b))) +#define msa_addl_u16(a, b) ((v4u32)__builtin_msa_addv_w((v4i32)V4U16_2_V4I32(a), (v4i32)V4U16_2_V4I32(b))) +#define msa_addl_s16(a, b) (__builtin_msa_addv_w((v4i32)V4I16_2_V4I32(a), (v4i32)V4I16_2_V4I32(b))) +#define msa_subl_s16(a, b) (__builtin_msa_subv_w((v4i32)V4I16_2_V4I32(a), (v4i32)V4I16_2_V4I32(b))) +#define msa_recpeq_f32 __builtin_msa_frcp_w +#define msa_recpsq_f32(a, b) (__builtin_msa_fsub_w(msa_dupq_n_f32(2.0f), __builtin_msa_fmul_w(a, b))) + +#define MSA_INTERLEAVED_IMPL_LOAD2_STORE2(_Tp, _Tpv, _Tpvs, suffix, df, nlanes) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_ld2q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b) \ +{ \ + _Tpv v0 = msa_ld1q_##suffix(ptr); \ + _Tpv v1 = msa_ld1q_##suffix(ptr + nlanes); \ + *a = (_Tpv)__builtin_msa_pckev_##df((_Tpvs)v1, (_Tpvs)v0); \ + *b = (_Tpv)__builtin_msa_pckod_##df((_Tpvs)v1, (_Tpvs)v0); \ +} \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_st2q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b) \ +{ \ + msa_st1q_##suffix(ptr, (_Tpv)__builtin_msa_ilvr_##df((_Tpvs)b, (_Tpvs)a)); \ + msa_st1q_##suffix(ptr + nlanes, (_Tpv)__builtin_msa_ilvl_##df((_Tpvs)b, (_Tpvs)a)); \ +} + +MSA_INTERLEAVED_IMPL_LOAD2_STORE2(uint8_t, v16u8, v16i8, u8, b, 16) +MSA_INTERLEAVED_IMPL_LOAD2_STORE2(int8_t, v16i8, v16i8, s8, b, 16) +MSA_INTERLEAVED_IMPL_LOAD2_STORE2(uint16_t, v8u16, v8i16, u16, h, 8) +MSA_INTERLEAVED_IMPL_LOAD2_STORE2(int16_t, v8i16, v8i16, s16, h, 8) +MSA_INTERLEAVED_IMPL_LOAD2_STORE2(uint32_t, v4u32, v4i32, u32, w, 4) +MSA_INTERLEAVED_IMPL_LOAD2_STORE2(int32_t, v4i32, v4i32, s32, w, 4) +MSA_INTERLEAVED_IMPL_LOAD2_STORE2(float, v4f32, v4i32, f32, w, 4) +MSA_INTERLEAVED_IMPL_LOAD2_STORE2(uint64_t, v2u64, v2i64, u64, d, 2) +MSA_INTERLEAVED_IMPL_LOAD2_STORE2(int64_t, v2i64, v2i64, s64, d, 2) +MSA_INTERLEAVED_IMPL_LOAD2_STORE2(double, v2f64, v2i64, f64, d, 2) + +#ifdef _MIPSEB +#define MSA_INTERLEAVED_IMPL_LOAD3_8(_Tp, _Tpv, _Tpvs, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_ld3q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c) \ +{ \ + _Tpv v0 = msa_ld1q_##suffix(ptr); \ + _Tpv v1 = msa_ld1q_##suffix(ptr + 16); \ + _Tpv v2 = msa_ld1q_##suffix(ptr + 32); \ + _Tpvs v3 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0704011F1F1F1F1F, 0x1F1C191613100D0A}), (_Tpvs)v0, (_Tpvs)v1); \ + *a = (_Tpv)__builtin_msa_vshf_b((_Tpvs)((v2i64){0x1716150E0B080502, 0x1F1E1D1C1B1A1918}), v3, (_Tpvs)v2); \ + v3 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0603001F1F1F1F1F, 0x1E1B1815120F0C09}), (_Tpvs)v0, (_Tpvs)v1); \ + *b = (_Tpv)__builtin_msa_vshf_b((_Tpvs)((v2i64){0x1716150D0A070401, 0x1F1E1D1C1B1A1918}), v3, (_Tpvs)v2); \ + v3 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x05021F1F1F1F1F1F, 0x1D1A1714110E0B08}), (_Tpvs)v0, (_Tpvs)v1); \ + *c = (_Tpv)__builtin_msa_vshf_b((_Tpvs)((v2i64){0x17160F0C09060300, 0x1F1E1D1C1B1A1918}), v3, (_Tpvs)v2); \ +} +#else +#define MSA_INTERLEAVED_IMPL_LOAD3_8(_Tp, _Tpv, _Tpvs, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_ld3q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c) \ +{ \ + _Tpv v0 = msa_ld1q_##suffix(ptr); \ + _Tpv v1 = msa_ld1q_##suffix(ptr + 16); \ + _Tpv v2 = msa_ld1q_##suffix(ptr + 32); \ + _Tpvs v3 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x15120F0C09060300, 0x00000000001E1B18}), (_Tpvs)v1, (_Tpvs)v0); \ + *a = (_Tpv)__builtin_msa_vshf_b((_Tpvs)((v2i64){0x0706050403020100, 0x1D1A1714110A0908}), (_Tpvs)v2, v3); \ + v3 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x1613100D0A070401, 0x00000000001F1C19}), (_Tpvs)v1, (_Tpvs)v0); \ + *b = (_Tpv)__builtin_msa_vshf_b((_Tpvs)((v2i64){0x0706050403020100, 0x1E1B1815120A0908}), (_Tpvs)v2, v3); \ + v3 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x1714110E0B080502, 0x0000000000001D1A}), (_Tpvs)v1, (_Tpvs)v0); \ + *c = (_Tpv)__builtin_msa_vshf_b((_Tpvs)((v2i64){0x0706050403020100, 0x1F1C191613100908}), (_Tpvs)v2, v3); \ +} +#endif + +MSA_INTERLEAVED_IMPL_LOAD3_8(uint8_t, v16u8, v16i8, u8) +MSA_INTERLEAVED_IMPL_LOAD3_8(int8_t, v16i8, v16i8, s8) + +#ifdef _MIPSEB +#define MSA_INTERLEAVED_IMPL_LOAD3_16(_Tp, _Tpv, _Tpvs, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_ld3q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c) \ +{ \ + _Tpv v0 = msa_ld1q_##suffix(ptr); \ + _Tpv v1 = msa_ld1q_##suffix(ptr + 8); \ + _Tpv v2 = msa_ld1q_##suffix(ptr + 16); \ + _Tpvs v3 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x00030000000F000F, 0x000F000C00090006}), (_Tpvs)v1, (_Tpvs)v0); \ + *a = (_Tpv)__builtin_msa_vshf_h((_Tpvs)((v2i64){0x000B000A00050002, 0x000F000E000D000C}), (_Tpvs)v2, v3); \ + v3 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0002000F000F000F, 0x000E000B00080005}), (_Tpvs)v1, (_Tpvs)v0); \ + *b = (_Tpv)__builtin_msa_vshf_h((_Tpvs)((v2i64){0x000B000700040001, 0x000F000E000D000C}), (_Tpvs)v2, v3); \ + v3 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0001000F000F000F, 0x000D000A00070004}), (_Tpvs)v1, (_Tpvs)v0); \ + *c = (_Tpv)__builtin_msa_vshf_h((_Tpvs)((v2i64){0x000B000600030000, 0x000F000E000D000C}), (_Tpvs)v2, v3); \ +} +#else +#define MSA_INTERLEAVED_IMPL_LOAD3_16(_Tp, _Tpv, _Tpvs, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_ld3q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c) \ +{ \ + _Tpv v0 = msa_ld1q_##suffix(ptr); \ + _Tpv v1 = msa_ld1q_##suffix(ptr + 8); \ + _Tpv v2 = msa_ld1q_##suffix(ptr + 16); \ + _Tpvs v3 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0009000600030000, 0x00000000000F000C}), (_Tpvs)v1, (_Tpvs)v0); \ + *a = (_Tpv)__builtin_msa_vshf_h((_Tpvs)((v2i64){0x0003000200010000, 0x000D000A00050004}), (_Tpvs)v2, v3); \ + v3 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000A000700040001, 0x000000000000000D}), (_Tpvs)v1, (_Tpvs)v0); \ + *b = (_Tpv)__builtin_msa_vshf_h((_Tpvs)((v2i64){0x0003000200010000, 0x000E000B00080004}), (_Tpvs)v2, v3); \ + v3 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000B000800050002, 0x000000000000000E}), (_Tpvs)v1, (_Tpvs)v0); \ + *c = (_Tpv)__builtin_msa_vshf_h((_Tpvs)((v2i64){0x0003000200010000, 0x000F000C00090004}), (_Tpvs)v2, v3); \ +} +#endif + +MSA_INTERLEAVED_IMPL_LOAD3_16(uint16_t, v8u16, v8i16, u16) +MSA_INTERLEAVED_IMPL_LOAD3_16(int16_t, v8i16, v8i16, s16) + +#define MSA_INTERLEAVED_IMPL_LOAD3_32(_Tp, _Tpv, _Tpvs, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_ld3q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c) \ +{ \ + _Tpv v00 = msa_ld1q_##suffix(ptr); \ + _Tpv v01 = msa_ld1q_##suffix(ptr + 4); \ + _Tpv v02 = msa_ld1q_##suffix(ptr + 8); \ + _Tpvs v10 = __builtin_msa_ilvr_w((_Tpvs)__builtin_msa_ilvl_d((v2i64)v01, (v2i64)v01), (_Tpvs)v00); \ + _Tpvs v11 = __builtin_msa_ilvr_w((_Tpvs)v02, (_Tpvs)__builtin_msa_ilvl_d((v2i64)v00, (v2i64)v00)); \ + _Tpvs v12 = __builtin_msa_ilvr_w((_Tpvs)__builtin_msa_ilvl_d((v2i64)v02, (v2i64)v02), (_Tpvs)v01); \ + *a = (_Tpv)__builtin_msa_ilvr_w((_Tpvs)__builtin_msa_ilvl_d((v2i64)v11, (v2i64)v11), v10); \ + *b = (_Tpv)__builtin_msa_ilvr_w(v12, (_Tpvs)__builtin_msa_ilvl_d((v2i64)v10, (v2i64)v10)); \ + *c = (_Tpv)__builtin_msa_ilvr_w((_Tpvs)__builtin_msa_ilvl_d((v2i64)v12, (v2i64)v12), v11); \ +} + +MSA_INTERLEAVED_IMPL_LOAD3_32(uint32_t, v4u32, v4i32, u32) +MSA_INTERLEAVED_IMPL_LOAD3_32(int32_t, v4i32, v4i32, s32) +MSA_INTERLEAVED_IMPL_LOAD3_32(float, v4f32, v4i32, f32) + +#define MSA_INTERLEAVED_IMPL_LOAD3_64(_Tp, _Tpv, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_ld3q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c) \ +{ \ + *((_Tp*)a) = *ptr; *((_Tp*)b) = *(ptr + 1); *((_Tp*)c) = *(ptr + 2); \ + *((_Tp*)a + 1) = *(ptr + 3); *((_Tp*)b + 1) = *(ptr + 4); *((_Tp*)c + 1) = *(ptr + 5); \ +} + +MSA_INTERLEAVED_IMPL_LOAD3_64(uint64_t, v2u64, u64) +MSA_INTERLEAVED_IMPL_LOAD3_64(int64_t, v2i64, s64) +MSA_INTERLEAVED_IMPL_LOAD3_64(double, v2f64, f64) + +#ifdef _MIPSEB +#define MSA_INTERLEAVED_IMPL_STORE3_8(_Tp, _Tpv, _Tpvs, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ +{ \ + _Tpvs v0 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0F0E0D0C0B1F1F1F, 0x1F1E1D1C1B1A1F1F}), (_Tpvs)b, (_Tpvs)a); \ + _Tpvs v1 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0D1C140C1B130B1A, 0x1F170F1E160E1D15}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr, (_Tpv)v1); \ + v0 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0A09080706051F1F, 0x19181716151F1F1F}), (_Tpvs)b, (_Tpvs)a); \ + v1 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x1D14071C13061B12, 0x170A1F16091E1508}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr + 16, (_Tpv)v1); \ + v0 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x04030201001F1F1F, 0x14131211101F1F1F}), (_Tpvs)b, (_Tpvs)a); \ + v1 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x15021C14011B1300, 0x051F17041E16031D}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr + 32, (_Tpv)v1); \ +} +#else +#define MSA_INTERLEAVED_IMPL_STORE3_8(_Tp, _Tpv, _Tpvs, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ +{ \ + _Tpvs v0 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0000050403020100, 0x0000001413121110}), (_Tpvs)b, (_Tpvs)a); \ + _Tpvs v1 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0A02110901100800, 0x05140C04130B0312}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr, (_Tpv)v1); \ + v0 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0000000A09080706, 0x00001A1918171615}), (_Tpvs)b, (_Tpvs)a); \ + v1 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x170A011609001508, 0x0D04190C03180B02}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr + 16, (_Tpv)v1); \ + v0 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0000000F0E0D0C0B, 0x0000001F1E1D1C1B}), (_Tpvs)b, (_Tpvs)a); \ + v1 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x021C09011B08001A, 0x1F0C041E0B031D0A}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr + 32, (_Tpv)v1); \ +} +#endif + +MSA_INTERLEAVED_IMPL_STORE3_8(uint8_t, v16u8, v16i8, u8) +MSA_INTERLEAVED_IMPL_STORE3_8(int8_t, v16i8, v16i8, s8) + +#ifdef _MIPSEB +#define MSA_INTERLEAVED_IMPL_STORE3_16(_Tp, _Tpv, _Tpvs, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ +{ \ + _Tpvs v0 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000700060005000F, 0x000F000E000D000F}), (_Tpvs)b, (_Tpvs)a); \ + _Tpvs v1 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000A0006000D0009, 0x000F000B0007000E}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr, (_Tpv)v1); \ + v0 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x00040003000F000F, 0x000C000B000A000F}), (_Tpvs)b, (_Tpvs)a); \ + v1 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000E000A0003000D, 0x0005000F000B0004}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr + 8, (_Tpv)v1); \ + v0 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000200010000000F, 0x00090008000F000F}), (_Tpvs)b, (_Tpvs)a); \ + v1 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0001000E00090000, 0x000B0002000F000A}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr + 16, (_Tpv)v1); \ +} +#else +#define MSA_INTERLEAVED_IMPL_STORE3_16(_Tp, _Tpv, _Tpvs, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ +{ \ + _Tpvs v0 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0000000200010000, 0x0000000A00090008}), (_Tpvs)b, (_Tpvs)a); \ + _Tpvs v1 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0001000800040000, 0x0006000200090005}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr, (_Tpv)v1); \ + v0 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0000000500040003, 0x00000000000C000B}), (_Tpvs)b, (_Tpvs)a); \ + v1 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000B00040000000A, 0x0002000C00050001}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr + 8, (_Tpv)v1); \ + v0 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0000000000070006, 0x0000000F000E000D}), (_Tpvs)b, (_Tpvs)a); \ + v1 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x00050000000D0004, 0x000F00060001000E}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr + 16, (_Tpv)v1); \ +} +#endif + +MSA_INTERLEAVED_IMPL_STORE3_16(uint16_t, v8u16, v8i16, u16) +MSA_INTERLEAVED_IMPL_STORE3_16(int16_t, v8i16, v8i16, s16) + +#ifdef _MIPSEB +#define MSA_INTERLEAVED_IMPL_STORE3_32(_Tp, _Tpv, _Tpvs, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ +{ \ + _Tpvs v0 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000300000007, 0x0000000700000006}), (_Tpvs)b, (_Tpvs)a); \ + _Tpvs v1 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000300000006, 0x0000000700000005}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr, (_Tpv)v1); \ + v0 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000200000001, 0x0000000500000007}), (_Tpvs)b, (_Tpvs)a); \ + v1 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000700000004, 0x0000000500000002}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr + 4, (_Tpv)v1); \ + v0 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000000000007, 0x0000000400000007}), (_Tpvs)b, (_Tpvs)a); \ + v1 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000500000000, 0x0000000100000007}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr + 8, (_Tpv)v1); \ +} +#else +#define MSA_INTERLEAVED_IMPL_STORE3_32(_Tp, _Tpv, _Tpvs, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ +{ \ + _Tpvs v0 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000100000000, 0x0000000000000004}), (_Tpvs)b, (_Tpvs)a); \ + _Tpvs v1 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000200000000, 0x0000000100000004}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr, (_Tpv)v1); \ + v0 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000000000002, 0x0000000600000005}), (_Tpvs)b, (_Tpvs)a); \ + v1 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000500000002, 0x0000000300000000}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr + 4, (_Tpv)v1); \ + v0 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000000000003, 0x0000000000000007}), (_Tpvs)b, (_Tpvs)a); \ + v1 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000000000006, 0x0000000700000002}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr + 8, (_Tpv)v1); \ +} +#endif + +MSA_INTERLEAVED_IMPL_STORE3_32(uint32_t, v4u32, v4i32, u32) +MSA_INTERLEAVED_IMPL_STORE3_32(int32_t, v4i32, v4i32, s32) +MSA_INTERLEAVED_IMPL_STORE3_32(float, v4f32, v4i32, f32) + +#define MSA_INTERLEAVED_IMPL_STORE3_64(_Tp, _Tpv, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ +{ \ + *ptr = a[0]; *(ptr + 1) = b[0]; *(ptr + 2) = c[0]; \ + *(ptr + 3) = a[1]; *(ptr + 4) = b[1]; *(ptr + 5) = c[1]; \ +} + +MSA_INTERLEAVED_IMPL_STORE3_64(uint64_t, v2u64, u64) +MSA_INTERLEAVED_IMPL_STORE3_64(int64_t, v2i64, s64) +MSA_INTERLEAVED_IMPL_STORE3_64(double, v2f64, f64) + +#define MSA_INTERLEAVED_IMPL_LOAD4_STORE4(_Tp, _Tpv, _Tpvs, suffix, df, nlanes) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_ld4q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c, _Tpv* d) \ +{ \ + _Tpv v0 = msa_ld1q_##suffix(ptr); \ + _Tpv v1 = msa_ld1q_##suffix(ptr + nlanes); \ + _Tpv v2 = msa_ld1q_##suffix(ptr + nlanes * 2); \ + _Tpv v3 = msa_ld1q_##suffix(ptr + nlanes * 3); \ + _Tpvs t0 = __builtin_msa_pckev_##df((_Tpvs)v1, (_Tpvs)v0); \ + _Tpvs t1 = __builtin_msa_pckev_##df((_Tpvs)v3, (_Tpvs)v2); \ + _Tpvs t2 = __builtin_msa_pckod_##df((_Tpvs)v1, (_Tpvs)v0); \ + _Tpvs t3 = __builtin_msa_pckod_##df((_Tpvs)v3, (_Tpvs)v2); \ + *a = (_Tpv)__builtin_msa_pckev_##df(t1, t0); \ + *b = (_Tpv)__builtin_msa_pckev_##df(t3, t2); \ + *c = (_Tpv)__builtin_msa_pckod_##df(t1, t0); \ + *d = (_Tpv)__builtin_msa_pckod_##df(t3, t2); \ +} \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_st4q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c, const _Tpv d) \ +{ \ + _Tpvs v0 = __builtin_msa_ilvr_##df((_Tpvs)c, (_Tpvs)a); \ + _Tpvs v1 = __builtin_msa_ilvr_##df((_Tpvs)d, (_Tpvs)b); \ + _Tpvs v2 = __builtin_msa_ilvl_##df((_Tpvs)c, (_Tpvs)a); \ + _Tpvs v3 = __builtin_msa_ilvl_##df((_Tpvs)d, (_Tpvs)b); \ + msa_st1q_##suffix(ptr, (_Tpv)__builtin_msa_ilvr_##df(v1, v0)); \ + msa_st1q_##suffix(ptr + nlanes, (_Tpv)__builtin_msa_ilvl_##df(v1, v0)); \ + msa_st1q_##suffix(ptr + 2 * nlanes, (_Tpv)__builtin_msa_ilvr_##df(v3, v2)); \ + msa_st1q_##suffix(ptr + 3 * nlanes, (_Tpv)__builtin_msa_ilvl_##df(v3, v2)); \ +} + +MSA_INTERLEAVED_IMPL_LOAD4_STORE4(uint8_t, v16u8, v16i8, u8, b, 16) +MSA_INTERLEAVED_IMPL_LOAD4_STORE4(int8_t, v16i8, v16i8, s8, b, 16) +MSA_INTERLEAVED_IMPL_LOAD4_STORE4(uint16_t, v8u16, v8i16, u16, h, 8) +MSA_INTERLEAVED_IMPL_LOAD4_STORE4(int16_t, v8i16, v8i16, s16, h, 8) +MSA_INTERLEAVED_IMPL_LOAD4_STORE4(uint32_t, v4u32, v4i32, u32, w, 4) +MSA_INTERLEAVED_IMPL_LOAD4_STORE4(int32_t, v4i32, v4i32, s32, w, 4) +MSA_INTERLEAVED_IMPL_LOAD4_STORE4(float, v4f32, v4i32, f32, w, 4) + +#define MSA_INTERLEAVED_IMPL_LOAD4_STORE4_64(_Tp, _Tpv, _Tpvs, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_ld4q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c, _Tpv* d) \ +{ \ + _Tpv v0 = msa_ld1q_##suffix(ptr); \ + _Tpv v1 = msa_ld1q_##suffix(ptr + 2); \ + _Tpv v2 = msa_ld1q_##suffix(ptr + 4); \ + _Tpv v3 = msa_ld1q_##suffix(ptr + 6); \ + *a = (_Tpv)__builtin_msa_ilvr_d((_Tpvs)v2, (_Tpvs)v0); \ + *b = (_Tpv)__builtin_msa_ilvl_d((_Tpvs)v2, (_Tpvs)v0); \ + *c = (_Tpv)__builtin_msa_ilvr_d((_Tpvs)v3, (_Tpvs)v1); \ + *d = (_Tpv)__builtin_msa_ilvl_d((_Tpvs)v3, (_Tpvs)v1); \ +} \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_st4q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c, const _Tpv d) \ +{ \ + msa_st1q_##suffix(ptr, (_Tpv)__builtin_msa_ilvr_d((_Tpvs)b, (_Tpvs)a)); \ + msa_st1q_##suffix(ptr + 2, (_Tpv)__builtin_msa_ilvr_d((_Tpvs)d, (_Tpvs)c)); \ + msa_st1q_##suffix(ptr + 4, (_Tpv)__builtin_msa_ilvl_d((_Tpvs)b, (_Tpvs)a)); \ + msa_st1q_##suffix(ptr + 6, (_Tpv)__builtin_msa_ilvl_d((_Tpvs)d, (_Tpvs)c)); \ +} + +MSA_INTERLEAVED_IMPL_LOAD4_STORE4_64(uint64_t, v2u64, v2i64, u64) +MSA_INTERLEAVED_IMPL_LOAD4_STORE4_64(int64_t, v2i64, v2i64, s64) +MSA_INTERLEAVED_IMPL_LOAD4_STORE4_64(double, v2f64, v2i64, f64) + +__extension__ extern __inline v8i16 +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) +msa_qdmulhq_n_s16(v8i16 a, int16_t b) +{ + v8i16 a_lo, a_hi; + ILVRL_H2_SH(a, msa_dupq_n_s16(0), a_lo, a_hi); + return msa_packr_s32(msa_shlq_n_s32(msa_mulq_s32(msa_paddlq_s16(a_lo), msa_dupq_n_s32(b)), 1), + msa_shlq_n_s32(msa_mulq_s32(msa_paddlq_s16(a_hi), msa_dupq_n_s32(b)), 1), 16); +} + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif /*__mips_msa*/ +#endif /* OPENCV_CORE_MSA_MACROS_H */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/simd_utils.impl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/simd_utils.impl.hpp index 0a1ab2c523..14e3dfd56f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/simd_utils.impl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/simd_utils.impl.hpp @@ -1,186 +1,186 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -// This header is not standalone. Don't include directly, use "intrin.hpp" instead. -#ifdef OPENCV_HAL_INTRIN_HPP // defined in intrin.hpp - - -#if CV_SIMD128 || CV_SIMD128_CPP - -template struct Type2Vec128_Traits; -#define CV_INTRIN_DEF_TYPE2VEC128_TRAITS(type_, vec_type_) \ - template<> struct Type2Vec128_Traits \ - { \ - typedef vec_type_ vec_type; \ - } - -CV_INTRIN_DEF_TYPE2VEC128_TRAITS(uchar, v_uint8x16); -CV_INTRIN_DEF_TYPE2VEC128_TRAITS(schar, v_int8x16); -CV_INTRIN_DEF_TYPE2VEC128_TRAITS(ushort, v_uint16x8); -CV_INTRIN_DEF_TYPE2VEC128_TRAITS(short, v_int16x8); -CV_INTRIN_DEF_TYPE2VEC128_TRAITS(unsigned, v_uint32x4); -CV_INTRIN_DEF_TYPE2VEC128_TRAITS(int, v_int32x4); -CV_INTRIN_DEF_TYPE2VEC128_TRAITS(float, v_float32x4); -CV_INTRIN_DEF_TYPE2VEC128_TRAITS(uint64, v_uint64x2); -CV_INTRIN_DEF_TYPE2VEC128_TRAITS(int64, v_int64x2); -#if CV_SIMD128_64F -CV_INTRIN_DEF_TYPE2VEC128_TRAITS(double, v_float64x2); -#endif - -template static inline -typename Type2Vec128_Traits<_T>::vec_type v_setall(const _T& a); - -template<> inline Type2Vec128_Traits< uchar>::vec_type v_setall< uchar>(const uchar& a) { return v_setall_u8(a); } -template<> inline Type2Vec128_Traits< schar>::vec_type v_setall< schar>(const schar& a) { return v_setall_s8(a); } -template<> inline Type2Vec128_Traits::vec_type v_setall(const ushort& a) { return v_setall_u16(a); } -template<> inline Type2Vec128_Traits< short>::vec_type v_setall< short>(const short& a) { return v_setall_s16(a); } -template<> inline Type2Vec128_Traits< uint>::vec_type v_setall< uint>(const uint& a) { return v_setall_u32(a); } -template<> inline Type2Vec128_Traits< int>::vec_type v_setall< int>(const int& a) { return v_setall_s32(a); } -template<> inline Type2Vec128_Traits::vec_type v_setall(const uint64& a) { return v_setall_u64(a); } -template<> inline Type2Vec128_Traits< int64>::vec_type v_setall< int64>(const int64& a) { return v_setall_s64(a); } -template<> inline Type2Vec128_Traits< float>::vec_type v_setall< float>(const float& a) { return v_setall_f32(a); } -#if CV_SIMD128_64F -template<> inline Type2Vec128_Traits::vec_type v_setall(const double& a) { return v_setall_f64(a); } -#endif - -#endif // SIMD128 - - -#if CV_SIMD256 - -template struct Type2Vec256_Traits; -#define CV_INTRIN_DEF_TYPE2VEC256_TRAITS(type_, vec_type_) \ - template<> struct Type2Vec256_Traits \ - { \ - typedef vec_type_ vec_type; \ - } - -CV_INTRIN_DEF_TYPE2VEC256_TRAITS(uchar, v_uint8x32); -CV_INTRIN_DEF_TYPE2VEC256_TRAITS(schar, v_int8x32); -CV_INTRIN_DEF_TYPE2VEC256_TRAITS(ushort, v_uint16x16); -CV_INTRIN_DEF_TYPE2VEC256_TRAITS(short, v_int16x16); -CV_INTRIN_DEF_TYPE2VEC256_TRAITS(unsigned, v_uint32x8); -CV_INTRIN_DEF_TYPE2VEC256_TRAITS(int, v_int32x8); -CV_INTRIN_DEF_TYPE2VEC256_TRAITS(float, v_float32x8); -CV_INTRIN_DEF_TYPE2VEC256_TRAITS(uint64, v_uint64x4); -CV_INTRIN_DEF_TYPE2VEC256_TRAITS(int64, v_int64x4); -#if CV_SIMD256_64F -CV_INTRIN_DEF_TYPE2VEC256_TRAITS(double, v_float64x4); -#endif - -template static inline -typename Type2Vec256_Traits<_T>::vec_type v256_setall(const _T& a); - -template<> inline Type2Vec256_Traits< uchar>::vec_type v256_setall< uchar>(const uchar& a) { return v256_setall_u8(a); } -template<> inline Type2Vec256_Traits< schar>::vec_type v256_setall< schar>(const schar& a) { return v256_setall_s8(a); } -template<> inline Type2Vec256_Traits::vec_type v256_setall(const ushort& a) { return v256_setall_u16(a); } -template<> inline Type2Vec256_Traits< short>::vec_type v256_setall< short>(const short& a) { return v256_setall_s16(a); } -template<> inline Type2Vec256_Traits< uint>::vec_type v256_setall< uint>(const uint& a) { return v256_setall_u32(a); } -template<> inline Type2Vec256_Traits< int>::vec_type v256_setall< int>(const int& a) { return v256_setall_s32(a); } -template<> inline Type2Vec256_Traits::vec_type v256_setall(const uint64& a) { return v256_setall_u64(a); } -template<> inline Type2Vec256_Traits< int64>::vec_type v256_setall< int64>(const int64& a) { return v256_setall_s64(a); } -template<> inline Type2Vec256_Traits< float>::vec_type v256_setall< float>(const float& a) { return v256_setall_f32(a); } -#if CV_SIMD256_64F -template<> inline Type2Vec256_Traits::vec_type v256_setall(const double& a) { return v256_setall_f64(a); } -#endif - -#endif // SIMD256 - - -#if CV_SIMD512 - -template struct Type2Vec512_Traits; -#define CV_INTRIN_DEF_TYPE2VEC512_TRAITS(type_, vec_type_) \ - template<> struct Type2Vec512_Traits \ - { \ - typedef vec_type_ vec_type; \ - } - -CV_INTRIN_DEF_TYPE2VEC512_TRAITS(uchar, v_uint8x64); -CV_INTRIN_DEF_TYPE2VEC512_TRAITS(schar, v_int8x64); -CV_INTRIN_DEF_TYPE2VEC512_TRAITS(ushort, v_uint16x32); -CV_INTRIN_DEF_TYPE2VEC512_TRAITS(short, v_int16x32); -CV_INTRIN_DEF_TYPE2VEC512_TRAITS(unsigned, v_uint32x16); -CV_INTRIN_DEF_TYPE2VEC512_TRAITS(int, v_int32x16); -CV_INTRIN_DEF_TYPE2VEC512_TRAITS(float, v_float32x16); -CV_INTRIN_DEF_TYPE2VEC512_TRAITS(uint64, v_uint64x8); -CV_INTRIN_DEF_TYPE2VEC512_TRAITS(int64, v_int64x8); -#if CV_SIMD512_64F -CV_INTRIN_DEF_TYPE2VEC512_TRAITS(double, v_float64x8); -#endif - -template static inline -typename Type2Vec512_Traits<_T>::vec_type v512_setall(const _T& a); - -template<> inline Type2Vec512_Traits< uchar>::vec_type v512_setall< uchar>(const uchar& a) { return v512_setall_u8(a); } -template<> inline Type2Vec512_Traits< schar>::vec_type v512_setall< schar>(const schar& a) { return v512_setall_s8(a); } -template<> inline Type2Vec512_Traits::vec_type v512_setall(const ushort& a) { return v512_setall_u16(a); } -template<> inline Type2Vec512_Traits< short>::vec_type v512_setall< short>(const short& a) { return v512_setall_s16(a); } -template<> inline Type2Vec512_Traits< uint>::vec_type v512_setall< uint>(const uint& a) { return v512_setall_u32(a); } -template<> inline Type2Vec512_Traits< int>::vec_type v512_setall< int>(const int& a) { return v512_setall_s32(a); } -template<> inline Type2Vec512_Traits::vec_type v512_setall(const uint64& a) { return v512_setall_u64(a); } -template<> inline Type2Vec512_Traits< int64>::vec_type v512_setall< int64>(const int64& a) { return v512_setall_s64(a); } -template<> inline Type2Vec512_Traits< float>::vec_type v512_setall< float>(const float& a) { return v512_setall_f32(a); } -#if CV_SIMD512_64F -template<> inline Type2Vec512_Traits::vec_type v512_setall(const double& a) { return v512_setall_f64(a); } -#endif - -#endif // SIMD512 - -#if CV_SIMD_SCALABLE -template struct Type2Vec_Traits; -#define CV_INTRIN_DEF_TYPE2VEC_TRAITS(type_, vec_type_) \ - template<> struct Type2Vec_Traits \ - { \ - typedef vec_type_ vec_type; \ - } - -CV_INTRIN_DEF_TYPE2VEC_TRAITS(uchar, v_uint8); -CV_INTRIN_DEF_TYPE2VEC_TRAITS(schar, v_int8); -CV_INTRIN_DEF_TYPE2VEC_TRAITS(ushort, v_uint16); -CV_INTRIN_DEF_TYPE2VEC_TRAITS(short, v_int16); -CV_INTRIN_DEF_TYPE2VEC_TRAITS(unsigned, v_uint32); -CV_INTRIN_DEF_TYPE2VEC_TRAITS(int, v_int32); -CV_INTRIN_DEF_TYPE2VEC_TRAITS(float, v_float32); -CV_INTRIN_DEF_TYPE2VEC_TRAITS(uint64, v_uint64); -CV_INTRIN_DEF_TYPE2VEC_TRAITS(int64, v_int64); -#if CV_SIMD_SCALABLE_64F -CV_INTRIN_DEF_TYPE2VEC_TRAITS(double, v_float64); -#endif -template static inline -typename Type2Vec_Traits<_T>::vec_type v_setall(const _T& a); - -template<> inline Type2Vec_Traits< uchar>::vec_type v_setall< uchar>(const uchar& a) { return v_setall_u8(a); } -template<> inline Type2Vec_Traits< schar>::vec_type v_setall< schar>(const schar& a) { return v_setall_s8(a); } -template<> inline Type2Vec_Traits::vec_type v_setall(const ushort& a) { return v_setall_u16(a); } -template<> inline Type2Vec_Traits< short>::vec_type v_setall< short>(const short& a) { return v_setall_s16(a); } -template<> inline Type2Vec_Traits< uint>::vec_type v_setall< uint>(const uint& a) { return v_setall_u32(a); } -template<> inline Type2Vec_Traits< int>::vec_type v_setall< int>(const int& a) { return v_setall_s32(a); } -template<> inline Type2Vec_Traits::vec_type v_setall(const uint64& a) { return v_setall_u64(a); } -template<> inline Type2Vec_Traits< int64>::vec_type v_setall< int64>(const int64& a) { return v_setall_s64(a); } -template<> inline Type2Vec_Traits< float>::vec_type v_setall< float>(const float& a) { return v_setall_f32(a); } -#if CV_SIMD_SCALABLE_64F -template<> inline Type2Vec_Traits::vec_type v_setall(const double& a) { return v_setall_f64(a); } -#endif -#endif - - -#if CV_SIMD_SCALABLE -template static inline -typename Type2Vec_Traits<_T>::vec_type vx_setall(const _T& a) { return v_setall(a); } -#elif CV_SIMD_WIDTH == 16 -template static inline -typename Type2Vec128_Traits<_T>::vec_type vx_setall(const _T& a) { return v_setall(a); } -#elif CV_SIMD_WIDTH == 32 -template static inline -typename Type2Vec256_Traits<_T>::vec_type vx_setall(const _T& a) { return v256_setall(a); } -#elif CV_SIMD_WIDTH == 64 -template static inline -typename Type2Vec512_Traits<_T>::vec_type vx_setall(const _T& a) { return v512_setall(a); } -#else -#error "Build configuration error, unsupported CV_SIMD_WIDTH" -#endif - - -#endif // OPENCV_HAL_INTRIN_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +// This header is not standalone. Don't include directly, use "intrin.hpp" instead. +#ifdef OPENCV_HAL_INTRIN_HPP // defined in intrin.hpp + + +#if CV_SIMD128 || CV_SIMD128_CPP + +template struct Type2Vec128_Traits; +#define CV_INTRIN_DEF_TYPE2VEC128_TRAITS(type_, vec_type_) \ + template<> struct Type2Vec128_Traits \ + { \ + typedef vec_type_ vec_type; \ + } + +CV_INTRIN_DEF_TYPE2VEC128_TRAITS(uchar, v_uint8x16); +CV_INTRIN_DEF_TYPE2VEC128_TRAITS(schar, v_int8x16); +CV_INTRIN_DEF_TYPE2VEC128_TRAITS(ushort, v_uint16x8); +CV_INTRIN_DEF_TYPE2VEC128_TRAITS(short, v_int16x8); +CV_INTRIN_DEF_TYPE2VEC128_TRAITS(unsigned, v_uint32x4); +CV_INTRIN_DEF_TYPE2VEC128_TRAITS(int, v_int32x4); +CV_INTRIN_DEF_TYPE2VEC128_TRAITS(float, v_float32x4); +CV_INTRIN_DEF_TYPE2VEC128_TRAITS(uint64, v_uint64x2); +CV_INTRIN_DEF_TYPE2VEC128_TRAITS(int64, v_int64x2); +#if CV_SIMD128_64F +CV_INTRIN_DEF_TYPE2VEC128_TRAITS(double, v_float64x2); +#endif + +template static inline +typename Type2Vec128_Traits<_T>::vec_type v_setall(const _T& a); + +template<> inline Type2Vec128_Traits< uchar>::vec_type v_setall< uchar>(const uchar& a) { return v_setall_u8(a); } +template<> inline Type2Vec128_Traits< schar>::vec_type v_setall< schar>(const schar& a) { return v_setall_s8(a); } +template<> inline Type2Vec128_Traits::vec_type v_setall(const ushort& a) { return v_setall_u16(a); } +template<> inline Type2Vec128_Traits< short>::vec_type v_setall< short>(const short& a) { return v_setall_s16(a); } +template<> inline Type2Vec128_Traits< uint>::vec_type v_setall< uint>(const uint& a) { return v_setall_u32(a); } +template<> inline Type2Vec128_Traits< int>::vec_type v_setall< int>(const int& a) { return v_setall_s32(a); } +template<> inline Type2Vec128_Traits::vec_type v_setall(const uint64& a) { return v_setall_u64(a); } +template<> inline Type2Vec128_Traits< int64>::vec_type v_setall< int64>(const int64& a) { return v_setall_s64(a); } +template<> inline Type2Vec128_Traits< float>::vec_type v_setall< float>(const float& a) { return v_setall_f32(a); } +#if CV_SIMD128_64F +template<> inline Type2Vec128_Traits::vec_type v_setall(const double& a) { return v_setall_f64(a); } +#endif + +#endif // SIMD128 + + +#if CV_SIMD256 + +template struct Type2Vec256_Traits; +#define CV_INTRIN_DEF_TYPE2VEC256_TRAITS(type_, vec_type_) \ + template<> struct Type2Vec256_Traits \ + { \ + typedef vec_type_ vec_type; \ + } + +CV_INTRIN_DEF_TYPE2VEC256_TRAITS(uchar, v_uint8x32); +CV_INTRIN_DEF_TYPE2VEC256_TRAITS(schar, v_int8x32); +CV_INTRIN_DEF_TYPE2VEC256_TRAITS(ushort, v_uint16x16); +CV_INTRIN_DEF_TYPE2VEC256_TRAITS(short, v_int16x16); +CV_INTRIN_DEF_TYPE2VEC256_TRAITS(unsigned, v_uint32x8); +CV_INTRIN_DEF_TYPE2VEC256_TRAITS(int, v_int32x8); +CV_INTRIN_DEF_TYPE2VEC256_TRAITS(float, v_float32x8); +CV_INTRIN_DEF_TYPE2VEC256_TRAITS(uint64, v_uint64x4); +CV_INTRIN_DEF_TYPE2VEC256_TRAITS(int64, v_int64x4); +#if CV_SIMD256_64F +CV_INTRIN_DEF_TYPE2VEC256_TRAITS(double, v_float64x4); +#endif + +template static inline +typename Type2Vec256_Traits<_T>::vec_type v256_setall(const _T& a); + +template<> inline Type2Vec256_Traits< uchar>::vec_type v256_setall< uchar>(const uchar& a) { return v256_setall_u8(a); } +template<> inline Type2Vec256_Traits< schar>::vec_type v256_setall< schar>(const schar& a) { return v256_setall_s8(a); } +template<> inline Type2Vec256_Traits::vec_type v256_setall(const ushort& a) { return v256_setall_u16(a); } +template<> inline Type2Vec256_Traits< short>::vec_type v256_setall< short>(const short& a) { return v256_setall_s16(a); } +template<> inline Type2Vec256_Traits< uint>::vec_type v256_setall< uint>(const uint& a) { return v256_setall_u32(a); } +template<> inline Type2Vec256_Traits< int>::vec_type v256_setall< int>(const int& a) { return v256_setall_s32(a); } +template<> inline Type2Vec256_Traits::vec_type v256_setall(const uint64& a) { return v256_setall_u64(a); } +template<> inline Type2Vec256_Traits< int64>::vec_type v256_setall< int64>(const int64& a) { return v256_setall_s64(a); } +template<> inline Type2Vec256_Traits< float>::vec_type v256_setall< float>(const float& a) { return v256_setall_f32(a); } +#if CV_SIMD256_64F +template<> inline Type2Vec256_Traits::vec_type v256_setall(const double& a) { return v256_setall_f64(a); } +#endif + +#endif // SIMD256 + + +#if CV_SIMD512 + +template struct Type2Vec512_Traits; +#define CV_INTRIN_DEF_TYPE2VEC512_TRAITS(type_, vec_type_) \ + template<> struct Type2Vec512_Traits \ + { \ + typedef vec_type_ vec_type; \ + } + +CV_INTRIN_DEF_TYPE2VEC512_TRAITS(uchar, v_uint8x64); +CV_INTRIN_DEF_TYPE2VEC512_TRAITS(schar, v_int8x64); +CV_INTRIN_DEF_TYPE2VEC512_TRAITS(ushort, v_uint16x32); +CV_INTRIN_DEF_TYPE2VEC512_TRAITS(short, v_int16x32); +CV_INTRIN_DEF_TYPE2VEC512_TRAITS(unsigned, v_uint32x16); +CV_INTRIN_DEF_TYPE2VEC512_TRAITS(int, v_int32x16); +CV_INTRIN_DEF_TYPE2VEC512_TRAITS(float, v_float32x16); +CV_INTRIN_DEF_TYPE2VEC512_TRAITS(uint64, v_uint64x8); +CV_INTRIN_DEF_TYPE2VEC512_TRAITS(int64, v_int64x8); +#if CV_SIMD512_64F +CV_INTRIN_DEF_TYPE2VEC512_TRAITS(double, v_float64x8); +#endif + +template static inline +typename Type2Vec512_Traits<_T>::vec_type v512_setall(const _T& a); + +template<> inline Type2Vec512_Traits< uchar>::vec_type v512_setall< uchar>(const uchar& a) { return v512_setall_u8(a); } +template<> inline Type2Vec512_Traits< schar>::vec_type v512_setall< schar>(const schar& a) { return v512_setall_s8(a); } +template<> inline Type2Vec512_Traits::vec_type v512_setall(const ushort& a) { return v512_setall_u16(a); } +template<> inline Type2Vec512_Traits< short>::vec_type v512_setall< short>(const short& a) { return v512_setall_s16(a); } +template<> inline Type2Vec512_Traits< uint>::vec_type v512_setall< uint>(const uint& a) { return v512_setall_u32(a); } +template<> inline Type2Vec512_Traits< int>::vec_type v512_setall< int>(const int& a) { return v512_setall_s32(a); } +template<> inline Type2Vec512_Traits::vec_type v512_setall(const uint64& a) { return v512_setall_u64(a); } +template<> inline Type2Vec512_Traits< int64>::vec_type v512_setall< int64>(const int64& a) { return v512_setall_s64(a); } +template<> inline Type2Vec512_Traits< float>::vec_type v512_setall< float>(const float& a) { return v512_setall_f32(a); } +#if CV_SIMD512_64F +template<> inline Type2Vec512_Traits::vec_type v512_setall(const double& a) { return v512_setall_f64(a); } +#endif + +#endif // SIMD512 + +#if CV_SIMD_SCALABLE +template struct Type2Vec_Traits; +#define CV_INTRIN_DEF_TYPE2VEC_TRAITS(type_, vec_type_) \ + template<> struct Type2Vec_Traits \ + { \ + typedef vec_type_ vec_type; \ + } + +CV_INTRIN_DEF_TYPE2VEC_TRAITS(uchar, v_uint8); +CV_INTRIN_DEF_TYPE2VEC_TRAITS(schar, v_int8); +CV_INTRIN_DEF_TYPE2VEC_TRAITS(ushort, v_uint16); +CV_INTRIN_DEF_TYPE2VEC_TRAITS(short, v_int16); +CV_INTRIN_DEF_TYPE2VEC_TRAITS(unsigned, v_uint32); +CV_INTRIN_DEF_TYPE2VEC_TRAITS(int, v_int32); +CV_INTRIN_DEF_TYPE2VEC_TRAITS(float, v_float32); +CV_INTRIN_DEF_TYPE2VEC_TRAITS(uint64, v_uint64); +CV_INTRIN_DEF_TYPE2VEC_TRAITS(int64, v_int64); +#if CV_SIMD_SCALABLE_64F +CV_INTRIN_DEF_TYPE2VEC_TRAITS(double, v_float64); +#endif +template static inline +typename Type2Vec_Traits<_T>::vec_type v_setall(const _T& a); + +template<> inline Type2Vec_Traits< uchar>::vec_type v_setall< uchar>(const uchar& a) { return v_setall_u8(a); } +template<> inline Type2Vec_Traits< schar>::vec_type v_setall< schar>(const schar& a) { return v_setall_s8(a); } +template<> inline Type2Vec_Traits::vec_type v_setall(const ushort& a) { return v_setall_u16(a); } +template<> inline Type2Vec_Traits< short>::vec_type v_setall< short>(const short& a) { return v_setall_s16(a); } +template<> inline Type2Vec_Traits< uint>::vec_type v_setall< uint>(const uint& a) { return v_setall_u32(a); } +template<> inline Type2Vec_Traits< int>::vec_type v_setall< int>(const int& a) { return v_setall_s32(a); } +template<> inline Type2Vec_Traits::vec_type v_setall(const uint64& a) { return v_setall_u64(a); } +template<> inline Type2Vec_Traits< int64>::vec_type v_setall< int64>(const int64& a) { return v_setall_s64(a); } +template<> inline Type2Vec_Traits< float>::vec_type v_setall< float>(const float& a) { return v_setall_f32(a); } +#if CV_SIMD_SCALABLE_64F +template<> inline Type2Vec_Traits::vec_type v_setall(const double& a) { return v_setall_f64(a); } +#endif +#endif + + +#if CV_SIMD_SCALABLE +template static inline +typename Type2Vec_Traits<_T>::vec_type vx_setall(const _T& a) { return v_setall(a); } +#elif CV_SIMD_WIDTH == 16 +template static inline +typename Type2Vec128_Traits<_T>::vec_type vx_setall(const _T& a) { return v_setall(a); } +#elif CV_SIMD_WIDTH == 32 +template static inline +typename Type2Vec256_Traits<_T>::vec_type vx_setall(const _T& a) { return v256_setall(a); } +#elif CV_SIMD_WIDTH == 64 +template static inline +typename Type2Vec512_Traits<_T>::vec_type vx_setall(const _T& a) { return v512_setall(a); } +#else +#error "Build configuration error, unsupported CV_SIMD_WIDTH" +#endif + + +#endif // OPENCV_HAL_INTRIN_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/mat.hpp b/3rdParty/opencv-4.11.0/opencv2/core/mat.hpp index 2282e12aee..be1b8faecb 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/mat.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/mat.hpp @@ -1,3814 +1,3814 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CORE_MAT_HPP -#define OPENCV_CORE_MAT_HPP - -#ifndef __cplusplus -# error mat.hpp header must be compiled as C++ -#endif - -#include "opencv2/core/matx.hpp" -#include "opencv2/core/types.hpp" - -#include "opencv2/core/bufferpool.hpp" - -#include -#include - -namespace cv -{ - -//! @addtogroup core_basic -//! @{ - -enum AccessFlag { ACCESS_READ=1<<24, ACCESS_WRITE=1<<25, - ACCESS_RW=3<<24, ACCESS_MASK=ACCESS_RW, ACCESS_FAST=1<<26 }; -CV_ENUM_FLAGS(AccessFlag) -__CV_ENUM_FLAGS_BITWISE_AND(AccessFlag, int, AccessFlag) - -CV__DEBUG_NS_BEGIN - -class CV_EXPORTS _OutputArray; - -//////////////////////// Input/Output Array Arguments ///////////////////////////////// - -/** @brief This is the proxy class for passing read-only input arrays into OpenCV functions. - -It is defined as: -@code - typedef const _InputArray& InputArray; -@endcode -where \ref cv::_InputArray is a class that can be constructed from \ref cv::Mat, \ref cv::Mat_, -\ref cv::Matx, std::vector, std::vector>, std::vector, -std::vector>, \ref cv::UMat, std::vector or `double`. It can also be constructed from -a matrix expression. - -Since this is mostly implementation-level class, and its interface may change in future versions, we -do not describe it in details. There are a few key things, though, that should be kept in mind: - -- When you see in the reference manual or in OpenCV source code a function that takes - InputArray, it means that you can actually pass `Mat`, `Matx`, `vector` etc. (see above the - complete list). -- Optional input arguments: If some of the input arrays may be empty, pass cv::noArray() (or - simply cv::Mat() as you probably did before). -- The class is designed solely for passing parameters. That is, normally you *should not* - declare class members, local and global variables of this type. -- If you want to design your own function or a class method that can operate of arrays of - multiple types, you can use InputArray (or OutputArray) for the respective parameters. Inside - a function you should use _InputArray::getMat() method to construct a matrix header for the - array (without copying data). _InputArray::kind() can be used to distinguish Mat from - `vector<>` etc., but normally it is not needed. - -Here is how you can use a function that takes InputArray : -@code - std::vector vec; - // points or a circle - for( int i = 0; i < 30; i++ ) - vec.push_back(Point2f((float)(100 + 30*cos(i*CV_PI*2/5)), - (float)(100 - 30*sin(i*CV_PI*2/5)))); - cv::transform(vec, vec, cv::Matx23f(0.707, -0.707, 10, 0.707, 0.707, 20)); -@endcode -That is, we form an STL vector containing points, and apply in-place affine transformation to the -vector using the 2x3 matrix created inline as `Matx` instance. - -Here is how such a function can be implemented (for simplicity, we implement a very specific case of -it, according to the assertion statement inside) : -@code - void myAffineTransform(InputArray _src, OutputArray _dst, InputArray _m) - { - // get Mat headers for input arrays. This is O(1) operation, - // unless _src and/or _m are matrix expressions. - Mat src = _src.getMat(), m = _m.getMat(); - CV_Assert( src.type() == CV_32FC2 && m.type() == CV_32F && m.size() == Size(3, 2) ); - - // [re]create the output array so that it has the proper size and type. - // In case of Mat it calls Mat::create, in case of STL vector it calls vector::resize. - _dst.create(src.size(), src.type()); - Mat dst = _dst.getMat(); - - for( int i = 0; i < src.rows; i++ ) - for( int j = 0; j < src.cols; j++ ) - { - Point2f pt = src.at(i, j); - dst.at(i, j) = Point2f(m.at(0, 0)*pt.x + - m.at(0, 1)*pt.y + - m.at(0, 2), - m.at(1, 0)*pt.x + - m.at(1, 1)*pt.y + - m.at(1, 2)); - } - } -@endcode -There is another related type, InputArrayOfArrays, which is currently defined as a synonym for -InputArray: -@code - typedef InputArray InputArrayOfArrays; -@endcode -It denotes function arguments that are either vectors of vectors or vectors of matrices. A separate -synonym is needed to generate Python/Java etc. wrappers properly. At the function implementation -level their use is similar, but _InputArray::getMat(idx) should be used to get header for the -idx-th component of the outer vector and _InputArray::size().area() should be used to find the -number of components (vectors/matrices) of the outer vector. - -In general, type support is limited to cv::Mat types. Other types are forbidden. -But in some cases we need to support passing of custom non-general Mat types, like arrays of cv::KeyPoint, cv::DMatch, etc. -This data is not intended to be interpreted as an image data, or processed somehow like regular cv::Mat. -To pass such custom type use rawIn() / rawOut() / rawInOut() wrappers. -Custom type is wrapped as Mat-compatible `CV_8UC` values (N = sizeof(T), N <= CV_CN_MAX). - */ -class CV_EXPORTS _InputArray -{ -public: - enum KindFlag { - KIND_SHIFT = 16, - FIXED_TYPE = 0x8000 << KIND_SHIFT, - FIXED_SIZE = 0x4000 << KIND_SHIFT, - KIND_MASK = 31 << KIND_SHIFT, - - NONE = 0 << KIND_SHIFT, - MAT = 1 << KIND_SHIFT, - MATX = 2 << KIND_SHIFT, - STD_VECTOR = 3 << KIND_SHIFT, - STD_VECTOR_VECTOR = 4 << KIND_SHIFT, - STD_VECTOR_MAT = 5 << KIND_SHIFT, -#if OPENCV_ABI_COMPATIBILITY < 500 - EXPR = 6 << KIND_SHIFT, //!< removed: https://github.com/opencv/opencv/pull/17046 -#endif - OPENGL_BUFFER = 7 << KIND_SHIFT, - CUDA_HOST_MEM = 8 << KIND_SHIFT, - CUDA_GPU_MAT = 9 << KIND_SHIFT, - UMAT =10 << KIND_SHIFT, - STD_VECTOR_UMAT =11 << KIND_SHIFT, - STD_BOOL_VECTOR =12 << KIND_SHIFT, - STD_VECTOR_CUDA_GPU_MAT = 13 << KIND_SHIFT, -#if OPENCV_ABI_COMPATIBILITY < 500 - STD_ARRAY =14 << KIND_SHIFT, //!< removed: https://github.com/opencv/opencv/issues/18897 -#endif - STD_ARRAY_MAT =15 << KIND_SHIFT - }; - - _InputArray(); - _InputArray(int _flags, void* _obj); - _InputArray(const Mat& m); - _InputArray(const MatExpr& expr); - _InputArray(const std::vector& vec); - template _InputArray(const Mat_<_Tp>& m); - template _InputArray(const std::vector<_Tp>& vec); - _InputArray(const std::vector& vec); - template _InputArray(const std::vector >& vec); - _InputArray(const std::vector >&) = delete; // not supported - template _InputArray(const std::vector >& vec); - template _InputArray(const _Tp* vec, int n); - template _InputArray(const Matx<_Tp, m, n>& matx); - _InputArray(const double& val); - _InputArray(const cuda::GpuMat& d_mat); - _InputArray(const std::vector& d_mat_array); - _InputArray(const ogl::Buffer& buf); - _InputArray(const cuda::HostMem& cuda_mem); - template _InputArray(const cudev::GpuMat_<_Tp>& m); - _InputArray(const UMat& um); - _InputArray(const std::vector& umv); - - template _InputArray(const std::array<_Tp, _Nm>& arr); - template _InputArray(const std::array& arr); - - template static _InputArray rawIn(const std::vector<_Tp>& vec); - template static _InputArray rawIn(const std::array<_Tp, _Nm>& arr); - - Mat getMat(int idx=-1) const; - Mat getMat_(int idx=-1) const; - UMat getUMat(int idx=-1) const; - void getMatVector(std::vector& mv) const; - void getUMatVector(std::vector& umv) const; - void getGpuMatVector(std::vector& gpumv) const; - cuda::GpuMat getGpuMat() const; - ogl::Buffer getOGlBuffer() const; - - int getFlags() const; - void* getObj() const; - Size getSz() const; - - _InputArray::KindFlag kind() const; - int dims(int i=-1) const; - int cols(int i=-1) const; - int rows(int i=-1) const; - Size size(int i=-1) const; - int sizend(int* sz, int i=-1) const; - bool sameSize(const _InputArray& arr) const; - size_t total(int i=-1) const; - int type(int i=-1) const; - int depth(int i=-1) const; - int channels(int i=-1) const; - bool isContinuous(int i=-1) const; - bool isSubmatrix(int i=-1) const; - bool empty() const; - void copyTo(const _OutputArray& arr) const; - void copyTo(const _OutputArray& arr, const _InputArray & mask) const; - size_t offset(int i=-1) const; - size_t step(int i=-1) const; - bool isMat() const; - bool isUMat() const; - bool isMatVector() const; - bool isUMatVector() const; - bool isMatx() const; - bool isVector() const; - bool isGpuMat() const; - bool isGpuMatVector() const; - ~_InputArray(); - -protected: - int flags; - void* obj; - Size sz; - - void init(int _flags, const void* _obj); - void init(int _flags, const void* _obj, Size _sz); -}; -CV_ENUM_FLAGS(_InputArray::KindFlag) -__CV_ENUM_FLAGS_BITWISE_AND(_InputArray::KindFlag, int, _InputArray::KindFlag) - -/** @brief This type is very similar to InputArray except that it is used for input/output and output function -parameters. - -Just like with InputArray, OpenCV users should not care about OutputArray, they just pass `Mat`, -`vector` etc. to the functions. The same limitation as for `InputArray`: *Do not explicitly -create OutputArray instances* applies here too. - -If you want to make your function polymorphic (i.e. accept different arrays as output parameters), -it is also not very difficult. Take the sample above as the reference. Note that -_OutputArray::create() needs to be called before _OutputArray::getMat(). This way you guarantee -that the output array is properly allocated. - -Optional output parameters. If you do not need certain output array to be computed and returned to -you, pass cv::noArray(), just like you would in the case of optional input array. At the -implementation level, use _OutputArray::needed() to check if certain output array needs to be -computed or not. - -There are several synonyms for OutputArray that are used to assist automatic Python/Java/... wrapper -generators: -@code - typedef OutputArray OutputArrayOfArrays; - typedef OutputArray InputOutputArray; - typedef OutputArray InputOutputArrayOfArrays; -@endcode - */ -class CV_EXPORTS _OutputArray : public _InputArray -{ -public: - enum DepthMask - { - DEPTH_MASK_8U = 1 << CV_8U, - DEPTH_MASK_8S = 1 << CV_8S, - DEPTH_MASK_16U = 1 << CV_16U, - DEPTH_MASK_16S = 1 << CV_16S, - DEPTH_MASK_32S = 1 << CV_32S, - DEPTH_MASK_32F = 1 << CV_32F, - DEPTH_MASK_64F = 1 << CV_64F, - DEPTH_MASK_16F = 1 << CV_16F, - DEPTH_MASK_ALL = (DEPTH_MASK_64F<<1)-1, - DEPTH_MASK_ALL_BUT_8S = DEPTH_MASK_ALL & ~DEPTH_MASK_8S, - DEPTH_MASK_ALL_16F = (DEPTH_MASK_16F<<1)-1, - DEPTH_MASK_FLT = DEPTH_MASK_32F + DEPTH_MASK_64F - }; - - _OutputArray(); - _OutputArray(int _flags, void* _obj); - _OutputArray(Mat& m); - _OutputArray(std::vector& vec); - _OutputArray(cuda::GpuMat& d_mat); - _OutputArray(std::vector& d_mat); - _OutputArray(ogl::Buffer& buf); - _OutputArray(cuda::HostMem& cuda_mem); - template _OutputArray(cudev::GpuMat_<_Tp>& m); - template _OutputArray(std::vector<_Tp>& vec); - _OutputArray(std::vector& vec) = delete; // not supported - template _OutputArray(std::vector >& vec); - _OutputArray(std::vector >&) = delete; // not supported - template _OutputArray(std::vector >& vec); - template _OutputArray(Mat_<_Tp>& m); - template _OutputArray(_Tp* vec, int n); - template _OutputArray(Matx<_Tp, m, n>& matx); - _OutputArray(UMat& m); - _OutputArray(std::vector& vec); - - _OutputArray(const Mat& m); - _OutputArray(const std::vector& vec); - _OutputArray(const cuda::GpuMat& d_mat); - _OutputArray(const std::vector& d_mat); - _OutputArray(const ogl::Buffer& buf); - _OutputArray(const cuda::HostMem& cuda_mem); - template _OutputArray(const cudev::GpuMat_<_Tp>& m); - template _OutputArray(const std::vector<_Tp>& vec); - template _OutputArray(const std::vector >& vec); - template _OutputArray(const std::vector >& vec); - template _OutputArray(const Mat_<_Tp>& m); - template _OutputArray(const _Tp* vec, int n); - template _OutputArray(const Matx<_Tp, m, n>& matx); - _OutputArray(const UMat& m); - _OutputArray(const std::vector& vec); - - template _OutputArray(std::array<_Tp, _Nm>& arr); - template _OutputArray(const std::array<_Tp, _Nm>& arr); - template _OutputArray(std::array& arr); - template _OutputArray(const std::array& arr); - - template static _OutputArray rawOut(std::vector<_Tp>& vec); - template static _OutputArray rawOut(std::array<_Tp, _Nm>& arr); - - bool fixedSize() const; - bool fixedType() const; - bool needed() const; - Mat& getMatRef(int i=-1) const; - UMat& getUMatRef(int i=-1) const; - cuda::GpuMat& getGpuMatRef() const; - std::vector& getGpuMatVecRef() const; - ogl::Buffer& getOGlBufferRef() const; - cuda::HostMem& getHostMemRef() const; - void create(Size sz, int type, int i=-1, bool allowTransposed=false, _OutputArray::DepthMask fixedDepthMask=static_cast<_OutputArray::DepthMask>(0)) const; - void create(int rows, int cols, int type, int i=-1, bool allowTransposed=false, _OutputArray::DepthMask fixedDepthMask=static_cast<_OutputArray::DepthMask>(0)) const; - void create(int dims, const int* size, int type, int i=-1, bool allowTransposed=false, _OutputArray::DepthMask fixedDepthMask=static_cast<_OutputArray::DepthMask>(0)) const; - void createSameSize(const _InputArray& arr, int mtype) const; - void release() const; - void clear() const; - void setTo(const _InputArray& value, const _InputArray & mask = _InputArray()) const; - - void assign(const UMat& u) const; - void assign(const Mat& m) const; - - void assign(const std::vector& v) const; - void assign(const std::vector& v) const; - - void move(UMat& u) const; - void move(Mat& m) const; -}; - - -class CV_EXPORTS _InputOutputArray : public _OutputArray -{ -public: - _InputOutputArray(); - _InputOutputArray(int _flags, void* _obj); - _InputOutputArray(Mat& m); - _InputOutputArray(std::vector& vec); - _InputOutputArray(cuda::GpuMat& d_mat); - _InputOutputArray(ogl::Buffer& buf); - _InputOutputArray(cuda::HostMem& cuda_mem); - template _InputOutputArray(cudev::GpuMat_<_Tp>& m); - template _InputOutputArray(std::vector<_Tp>& vec); - _InputOutputArray(std::vector& vec) = delete; // not supported - template _InputOutputArray(std::vector >& vec); - template _InputOutputArray(std::vector >& vec); - template _InputOutputArray(Mat_<_Tp>& m); - template _InputOutputArray(_Tp* vec, int n); - template _InputOutputArray(Matx<_Tp, m, n>& matx); - _InputOutputArray(UMat& m); - _InputOutputArray(std::vector& vec); - - _InputOutputArray(const Mat& m); - _InputOutputArray(const std::vector& vec); - _InputOutputArray(const cuda::GpuMat& d_mat); - _InputOutputArray(const std::vector& d_mat); - _InputOutputArray(const ogl::Buffer& buf); - _InputOutputArray(const cuda::HostMem& cuda_mem); - template _InputOutputArray(const cudev::GpuMat_<_Tp>& m); - template _InputOutputArray(const std::vector<_Tp>& vec); - template _InputOutputArray(const std::vector >& vec); - template _InputOutputArray(const std::vector >& vec); - template _InputOutputArray(const Mat_<_Tp>& m); - template _InputOutputArray(const _Tp* vec, int n); - template _InputOutputArray(const Matx<_Tp, m, n>& matx); - _InputOutputArray(const UMat& m); - _InputOutputArray(const std::vector& vec); - - template _InputOutputArray(std::array<_Tp, _Nm>& arr); - template _InputOutputArray(const std::array<_Tp, _Nm>& arr); - template _InputOutputArray(std::array& arr); - template _InputOutputArray(const std::array& arr); - - template static _InputOutputArray rawInOut(std::vector<_Tp>& vec); - template _InputOutputArray rawInOut(std::array<_Tp, _Nm>& arr); - -}; - -/** Helper to wrap custom types. @see InputArray */ -template static inline _InputArray rawIn(_Tp& v); -/** Helper to wrap custom types. @see InputArray */ -template static inline _OutputArray rawOut(_Tp& v); -/** Helper to wrap custom types. @see InputArray */ -template static inline _InputOutputArray rawInOut(_Tp& v); - -CV__DEBUG_NS_END - -typedef const _InputArray& InputArray; -typedef InputArray InputArrayOfArrays; -typedef const _OutputArray& OutputArray; -typedef OutputArray OutputArrayOfArrays; -typedef const _InputOutputArray& InputOutputArray; -typedef InputOutputArray InputOutputArrayOfArrays; - -/** @brief Returns an empty InputArray or OutputArray. - - This function is used to provide an "empty" or "null" array when certain functions - take optional input or output arrays that you don't want to provide. - - Many OpenCV functions accept optional arguments as `cv::InputArray` or `cv::OutputArray`. - When you don't want to pass any data for these optional parameters, you can use `cv::noArray()` - to indicate that you are omitting them. - - @return An empty `cv::InputArray` or `cv::OutputArray` that can be used as a placeholder. - - @note This is often used when a function has optional arrays, and you do not want to - provide a specific input or output array. - - @see cv::InputArray, cv::OutputArray - */ -CV_EXPORTS InputOutputArray noArray(); - -/////////////////////////////////// MatAllocator ////////////////////////////////////// - -/** @brief Usage flags for allocator - - @warning All flags except `USAGE_DEFAULT` are experimental. - - @warning For the OpenCL allocator, `USAGE_ALLOCATE_SHARED_MEMORY` depends on - OpenCV's optional, experimental integration with OpenCL SVM. To enable this - integration, build OpenCV using the `WITH_OPENCL_SVM=ON` CMake option and, at - runtime, call `cv::ocl::Context::getDefault().setUseSVM(true);` or similar - code. Note that SVM is incompatible with OpenCL 1.x. -*/ -enum UMatUsageFlags -{ - USAGE_DEFAULT = 0, - - // buffer allocation policy is platform and usage specific - USAGE_ALLOCATE_HOST_MEMORY = 1 << 0, - USAGE_ALLOCATE_DEVICE_MEMORY = 1 << 1, - USAGE_ALLOCATE_SHARED_MEMORY = 1 << 2, // It is not equal to: USAGE_ALLOCATE_HOST_MEMORY | USAGE_ALLOCATE_DEVICE_MEMORY - - __UMAT_USAGE_FLAGS_32BIT = 0x7fffffff // Binary compatibility hint -}; - -struct CV_EXPORTS UMatData; - -/** @brief Custom array allocator -*/ -class CV_EXPORTS MatAllocator -{ -public: - MatAllocator() {} - virtual ~MatAllocator() {} - - // let's comment it off for now to detect and fix all the uses of allocator - //virtual void allocate(int dims, const int* sizes, int type, int*& refcount, - // uchar*& datastart, uchar*& data, size_t* step) = 0; - //virtual void deallocate(int* refcount, uchar* datastart, uchar* data) = 0; - virtual UMatData* allocate(int dims, const int* sizes, int type, - void* data, size_t* step, AccessFlag flags, UMatUsageFlags usageFlags) const = 0; - virtual bool allocate(UMatData* data, AccessFlag accessflags, UMatUsageFlags usageFlags) const = 0; - virtual void deallocate(UMatData* data) const = 0; - virtual void map(UMatData* data, AccessFlag accessflags) const; - virtual void unmap(UMatData* data) const; - virtual void download(UMatData* data, void* dst, int dims, const size_t sz[], - const size_t srcofs[], const size_t srcstep[], - const size_t dststep[]) const; - virtual void upload(UMatData* data, const void* src, int dims, const size_t sz[], - const size_t dstofs[], const size_t dststep[], - const size_t srcstep[]) const; - virtual void copy(UMatData* srcdata, UMatData* dstdata, int dims, const size_t sz[], - const size_t srcofs[], const size_t srcstep[], - const size_t dstofs[], const size_t dststep[], bool sync) const; - - // default implementation returns DummyBufferPoolController - virtual BufferPoolController* getBufferPoolController(const char* id = NULL) const; -}; - - -//////////////////////////////// MatCommaInitializer ////////////////////////////////// - -/** @brief Comma-separated Matrix Initializer - - The class instances are usually not created explicitly. - Instead, they are created on "matrix << firstValue" operator. - - The sample below initializes 2x2 rotation matrix: - - \code - double angle = 30, a = cos(angle*CV_PI/180), b = sin(angle*CV_PI/180); - Mat R = (Mat_(2,2) << a, -b, b, a); - \endcode -*/ -template class MatCommaInitializer_ -{ -public: - //! the constructor, created by "matrix << firstValue" operator, where matrix is cv::Mat - MatCommaInitializer_(Mat_<_Tp>* _m); - //! the operator that takes the next value and put it to the matrix - template MatCommaInitializer_<_Tp>& operator , (T2 v); - //! another form of conversion operator - operator Mat_<_Tp>() const; -protected: - MatIterator_<_Tp> it; -}; - - -/////////////////////////////////////// Mat /////////////////////////////////////////// - -// note that umatdata might be allocated together -// with the matrix data, not as a separate object. -// therefore, it does not have constructor or destructor; -// it should be explicitly initialized using init(). -struct CV_EXPORTS UMatData -{ - enum MemoryFlag { COPY_ON_MAP=1, HOST_COPY_OBSOLETE=2, - DEVICE_COPY_OBSOLETE=4, TEMP_UMAT=8, TEMP_COPIED_UMAT=24, - USER_ALLOCATED=32, DEVICE_MEM_MAPPED=64, - ASYNC_CLEANUP=128 - }; - UMatData(const MatAllocator* allocator); - ~UMatData(); - - // provide atomic access to the structure - void lock(); - void unlock(); - - bool hostCopyObsolete() const; - bool deviceCopyObsolete() const; - bool deviceMemMapped() const; - bool copyOnMap() const; - bool tempUMat() const; - bool tempCopiedUMat() const; - void markHostCopyObsolete(bool flag); - void markDeviceCopyObsolete(bool flag); - void markDeviceMemMapped(bool flag); - - const MatAllocator* prevAllocator; - const MatAllocator* currAllocator; - int urefcount; - int refcount; - uchar* data; - uchar* origdata; - size_t size; - - UMatData::MemoryFlag flags; - void* handle; - void* userdata; - int allocatorFlags_; - int mapcount; - UMatData* originalUMatData; - std::shared_ptr allocatorContext; -}; -CV_ENUM_FLAGS(UMatData::MemoryFlag) - - -struct CV_EXPORTS MatSize -{ - explicit MatSize(int* _p) CV_NOEXCEPT; - int dims() const CV_NOEXCEPT; - Size operator()() const; - const int& operator[](int i) const; - int& operator[](int i); - operator const int*() const CV_NOEXCEPT; // TODO OpenCV 4.0: drop this - bool operator == (const MatSize& sz) const CV_NOEXCEPT; - bool operator != (const MatSize& sz) const CV_NOEXCEPT; - - int* p; -}; - -struct CV_EXPORTS MatStep -{ - MatStep() CV_NOEXCEPT; - explicit MatStep(size_t s) CV_NOEXCEPT; - const size_t& operator[](int i) const CV_NOEXCEPT; - size_t& operator[](int i) CV_NOEXCEPT; - operator size_t() const; - MatStep& operator = (size_t s); - - size_t* p; - size_t buf[2]; -protected: - MatStep& operator = (const MatStep&); -}; - -/** @example samples/cpp/cout_mat.cpp -An example demonstrating the serial out capabilities of cv::Mat -*/ - - /** @brief n-dimensional dense array class \anchor CVMat_Details - -The class Mat represents an n-dimensional dense numerical single-channel or multi-channel array. It -can be used to store real or complex-valued vectors and matrices, grayscale or color images, voxel -volumes, vector fields, point clouds, tensors, histograms (though, very high-dimensional histograms -may be better stored in a SparseMat ). The data layout of the array `M` is defined by the array -`M.step[]`, so that the address of element \f$(i_0,...,i_{M.dims-1})\f$, where \f$0\leq i_k= M.step[i+1]` (in fact, `M.step[i] >= M.step[i+1]*M.size[i+1]` ). This means -that 2-dimensional matrices are stored row-by-row, 3-dimensional matrices are stored plane-by-plane, -and so on. M.step[M.dims-1] is minimal and always equal to the element size M.elemSize() . - -So, the data layout in Mat is compatible with the majority of dense array types from the standard -toolkits and SDKs, such as Numpy (ndarray), Win32 (independent device bitmaps), and others, -that is, with any array that uses *steps* (or *strides*) to compute the position of a pixel. -Due to this compatibility, it is possible to make a Mat header for user-allocated data and process -it in-place using OpenCV functions. - -There are many different ways to create a Mat object. The most popular options are listed below: - -- Use the create(nrows, ncols, type) method or the similar Mat(nrows, ncols, type[, fillValue]) -constructor. A new array of the specified size and type is allocated. type has the same meaning as -in the cvCreateMat method. For example, CV_8UC1 means a 8-bit single-channel array, CV_32FC2 -means a 2-channel (complex) floating-point array, and so on. -@code - // make a 7x7 complex matrix filled with 1+3j. - Mat M(7,7,CV_32FC2,Scalar(1,3)); - // and now turn M to a 100x60 15-channel 8-bit matrix. - // The old content will be deallocated - M.create(100,60,CV_8UC(15)); -@endcode -As noted in the introduction to this chapter, create() allocates only a new array when the shape -or type of the current array are different from the specified ones. - -- Create a multi-dimensional array: -@code - // create a 100x100x100 8-bit array - int sz[] = {100, 100, 100}; - Mat bigCube(3, sz, CV_8U, Scalar::all(0)); -@endcode -It passes the number of dimensions =1 to the Mat constructor but the created array will be -2-dimensional with the number of columns set to 1. So, Mat::dims is always \>= 2 (can also be 0 -when the array is empty). - -- Use a copy constructor or assignment operator where there can be an array or expression on the -right side (see below). As noted in the introduction, the array assignment is an O(1) operation -because it only copies the header and increases the reference counter. The Mat::clone() method can -be used to get a full (deep) copy of the array when you need it. - -- Construct a header for a part of another array. It can be a single row, single column, several -rows, several columns, rectangular region in the array (called a *minor* in algebra) or a -diagonal. Such operations are also O(1) because the new header references the same data. You can -actually modify a part of the array using this feature, for example: -@code - // add the 5-th row, multiplied by 3 to the 3rd row - M.row(3) = M.row(3) + M.row(5)*3; - // now copy the 7-th column to the 1-st column - // M.col(1) = M.col(7); // this will not work - Mat M1 = M.col(1); - M.col(7).copyTo(M1); - // create a new 320x240 image - Mat img(Size(320,240),CV_8UC3); - // select a ROI - Mat roi(img, Rect(10,10,100,100)); - // fill the ROI with (0,255,0) (which is green in RGB space); - // the original 320x240 image will be modified - roi = Scalar(0,255,0); -@endcode -Due to the additional datastart and dataend members, it is possible to compute a relative -sub-array position in the main *container* array using locateROI(): -@code - Mat A = Mat::eye(10, 10, CV_32S); - // extracts A columns, 1 (inclusive) to 3 (exclusive). - Mat B = A(Range::all(), Range(1, 3)); - // extracts B rows, 5 (inclusive) to 9 (exclusive). - // that is, C \~ A(Range(5, 9), Range(1, 3)) - Mat C = B(Range(5, 9), Range::all()); - Size size; Point ofs; - C.locateROI(size, ofs); - // size will be (width=10,height=10) and the ofs will be (x=1, y=5) -@endcode -As in case of whole matrices, if you need a deep copy, use the `clone()` method of the extracted -sub-matrices. - -- Make a header for user-allocated data. It can be useful to do the following: - -# Process "foreign" data using OpenCV (for example, when you implement a DirectShow\* filter or - a processing module for gstreamer, and so on). For example: - @code - Mat process_video_frame(const unsigned char* pixels, - int width, int height, int step) - { - // wrap input buffer - Mat img(height, width, CV_8UC3, (unsigned char*)pixels, step); - - Mat result; - GaussianBlur(img, result, Size(7, 7), 1.5, 1.5); - - return result; - } - @endcode - -# Quickly initialize small matrices and/or get a super-fast element access. - @code - double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}}; - Mat M = Mat(3, 3, CV_64F, m).inv(); - @endcode - . - -- Use MATLAB-style array initializers, zeros(), ones(), eye(), for example: -@code - // create a double-precision identity matrix and add it to M. - M += Mat::eye(M.rows, M.cols, CV_64F); -@endcode - -- Use a comma-separated initializer: -@code - // create a 3x3 double-precision identity matrix - Mat M = (Mat_(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1); -@endcode -With this approach, you first call a constructor of the Mat class with the proper parameters, and -then you just put `<< operator` followed by comma-separated values that can be constants, -variables, expressions, and so on. Also, note the extra parentheses required to avoid compilation -errors. - -Once the array is created, it is automatically managed via a reference-counting mechanism. If the -array header is built on top of user-allocated data, you should handle the data by yourself. The -array data is deallocated when no one points to it. If you want to release the data pointed by a -array header before the array destructor is called, use Mat::release(). - -The next important thing to learn about the array class is element access. This manual already -described how to compute an address of each array element. Normally, you are not required to use the -formula directly in the code. If you know the array element type (which can be retrieved using the -method Mat::type() ), you can access the element \f$M_{ij}\f$ of a 2-dimensional array as: -@code - M.at(i,j) += 1.f; -@endcode -assuming that `M` is a double-precision floating-point array. There are several variants of the method -at for a different number of dimensions. - -If you need to process a whole row of a 2D array, the most efficient way is to get the pointer to -the row first, and then just use the plain C operator [] : -@code - // compute sum of positive matrix elements - // (assuming that M is a double-precision matrix) - double sum=0; - for(int i = 0; i < M.rows; i++) - { - const double* Mi = M.ptr(i); - for(int j = 0; j < M.cols; j++) - sum += std::max(Mi[j], 0.); - } -@endcode -Some operations, like the one above, do not actually depend on the array shape. They just process -elements of an array one by one (or elements from multiple arrays that have the same coordinates, -for example, array addition). Such operations are called *element-wise*. It makes sense to check -whether all the input/output arrays are continuous, namely, have no gaps at the end of each row. If -yes, process them as a long single row: -@code - // compute the sum of positive matrix elements, optimized variant - double sum=0; - int cols = M.cols, rows = M.rows; - if(M.isContinuous()) - { - cols *= rows; - rows = 1; - } - for(int i = 0; i < rows; i++) - { - const double* Mi = M.ptr(i); - for(int j = 0; j < cols; j++) - sum += std::max(Mi[j], 0.); - } -@endcode -In case of the continuous matrix, the outer loop body is executed just once. So, the overhead is -smaller, which is especially noticeable in case of small matrices. - -Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows: -@code - // compute sum of positive matrix elements, iterator-based variant - double sum=0; - MatConstIterator_ it = M.begin(), it_end = M.end(); - for(; it != it_end; ++it) - sum += std::max(*it, 0.); -@endcode -The matrix iterators are random-access iterators, so they can be passed to any STL algorithm, -including std::sort(). - -@note Matrix Expressions and arithmetic see MatExpr -*/ -class CV_EXPORTS Mat -{ -public: - /** - These are various constructors that form a matrix. As noted in the AutomaticAllocation, often - the default constructor is enough, and the proper matrix will be allocated by an OpenCV function. - The constructed matrix can further be assigned to another matrix or matrix expression or can be - allocated with Mat::create . In the former case, the old content is de-referenced. - */ - Mat() CV_NOEXCEPT; - - /** @overload - @param rows Number of rows in a 2D array. - @param cols Number of columns in a 2D array. - @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - */ - Mat(int rows, int cols, int type); - - /** @overload - @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the - number of columns go in the reverse order. - @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - */ - Mat(Size size, int type); - - /** @overload - @param rows Number of rows in a 2D array. - @param cols Number of columns in a 2D array. - @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - @param s An optional value to initialize each matrix element with. To set all the matrix elements to - the particular value after the construction, use the assignment operator - Mat::operator=(const Scalar& value) . - */ - Mat(int rows, int cols, int type, const Scalar& s); - - /** @overload - @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the - number of columns go in the reverse order. - @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - @param s An optional value to initialize each matrix element with. To set all the matrix elements to - the particular value after the construction, use the assignment operator - Mat::operator=(const Scalar& value) . - */ - Mat(Size size, int type, const Scalar& s); - - /** @overload - @param ndims Array dimensionality. - @param sizes Array of integers specifying an n-dimensional array shape. - @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - */ - Mat(int ndims, const int* sizes, int type); - - /** @overload - @param sizes Array of integers specifying an n-dimensional array shape. - @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - */ - Mat(const std::vector& sizes, int type); - - /** @overload - @param ndims Array dimensionality. - @param sizes Array of integers specifying an n-dimensional array shape. - @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - @param s An optional value to initialize each matrix element with. To set all the matrix elements to - the particular value after the construction, use the assignment operator - Mat::operator=(const Scalar& value) . - */ - Mat(int ndims, const int* sizes, int type, const Scalar& s); - - /** @overload - @param sizes Array of integers specifying an n-dimensional array shape. - @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - @param s An optional value to initialize each matrix element with. To set all the matrix elements to - the particular value after the construction, use the assignment operator - Mat::operator=(const Scalar& value) . - */ - Mat(const std::vector& sizes, int type, const Scalar& s); - - - /** @overload - @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied - by these constructors. Instead, the header pointing to m data or its sub-array is constructed and - associated with it. The reference counter, if any, is incremented. So, when you modify the matrix - formed using such a constructor, you also modify the corresponding elements of m . If you want to - have an independent copy of the sub-array, use Mat::clone() . - */ - Mat(const Mat& m); - - /** @overload - @param rows Number of rows in a 2D array. - @param cols Number of columns in a 2D array. - @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - @param data Pointer to the user data. Matrix constructors that take data and step parameters do not - allocate matrix data. Instead, they just initialize the matrix header that points to the specified - data, which means that no data is copied. This operation is very efficient and can be used to - process external data using OpenCV functions. The external data is not automatically deallocated, so - you should take care of it. - @param step Number of bytes each matrix row occupies. The value should include the padding bytes at - the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed - and the actual step is calculated as cols*elemSize(). See Mat::elemSize. - */ - Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP); - - /** @overload - @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the - number of columns go in the reverse order. - @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - @param data Pointer to the user data. Matrix constructors that take data and step parameters do not - allocate matrix data. Instead, they just initialize the matrix header that points to the specified - data, which means that no data is copied. This operation is very efficient and can be used to - process external data using OpenCV functions. The external data is not automatically deallocated, so - you should take care of it. - @param step Number of bytes each matrix row occupies. The value should include the padding bytes at - the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed - and the actual step is calculated as cols*elemSize(). See Mat::elemSize. - */ - Mat(Size size, int type, void* data, size_t step=AUTO_STEP); - - /** @overload - @param ndims Array dimensionality. - @param sizes Array of integers specifying an n-dimensional array shape. - @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - @param data Pointer to the user data. Matrix constructors that take data and step parameters do not - allocate matrix data. Instead, they just initialize the matrix header that points to the specified - data, which means that no data is copied. This operation is very efficient and can be used to - process external data using OpenCV functions. The external data is not automatically deallocated, so - you should take care of it. - @param steps Array of ndims-1 steps in case of a multi-dimensional array (the last step is always - set to the element size). If not specified, the matrix is assumed to be continuous. - */ - Mat(int ndims, const int* sizes, int type, void* data, const size_t* steps=0); - - /** @overload - @param sizes Array of integers specifying an n-dimensional array shape. - @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - @param data Pointer to the user data. Matrix constructors that take data and step parameters do not - allocate matrix data. Instead, they just initialize the matrix header that points to the specified - data, which means that no data is copied. This operation is very efficient and can be used to - process external data using OpenCV functions. The external data is not automatically deallocated, so - you should take care of it. - @param steps Array of ndims-1 steps in case of a multi-dimensional array (the last step is always - set to the element size). If not specified, the matrix is assumed to be continuous. - */ - Mat(const std::vector& sizes, int type, void* data, const size_t* steps=0); - - /** @overload - @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied - by these constructors. Instead, the header pointing to m data or its sub-array is constructed and - associated with it. The reference counter, if any, is incremented. So, when you modify the matrix - formed using such a constructor, you also modify the corresponding elements of m . If you want to - have an independent copy of the sub-array, use Mat::clone() . - @param rowRange Range of the m rows to take. As usual, the range start is inclusive and the range - end is exclusive. Use Range::all() to take all the rows. - @param colRange Range of the m columns to take. Use Range::all() to take all the columns. - */ - Mat(const Mat& m, const Range& rowRange, const Range& colRange=Range::all()); - - /** @overload - @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied - by these constructors. Instead, the header pointing to m data or its sub-array is constructed and - associated with it. The reference counter, if any, is incremented. So, when you modify the matrix - formed using such a constructor, you also modify the corresponding elements of m . If you want to - have an independent copy of the sub-array, use Mat::clone() . - @param roi Region of interest. - */ - Mat(const Mat& m, const Rect& roi); - - /** @overload - @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied - by these constructors. Instead, the header pointing to m data or its sub-array is constructed and - associated with it. The reference counter, if any, is incremented. So, when you modify the matrix - formed using such a constructor, you also modify the corresponding elements of m . If you want to - have an independent copy of the sub-array, use Mat::clone() . - @param ranges Array of selected ranges of m along each dimensionality. - */ - Mat(const Mat& m, const Range* ranges); - - /** @overload - @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied - by these constructors. Instead, the header pointing to m data or its sub-array is constructed and - associated with it. The reference counter, if any, is incremented. So, when you modify the matrix - formed using such a constructor, you also modify the corresponding elements of m . If you want to - have an independent copy of the sub-array, use Mat::clone() . - @param ranges Array of selected ranges of m along each dimensionality. - */ - Mat(const Mat& m, const std::vector& ranges); - - /** @overload - @param vec STL vector whose elements form the matrix. The matrix has a single column and the number - of rows equal to the number of vector elements. Type of the matrix matches the type of vector - elements. The constructor can handle arbitrary types, for which there is a properly declared - DataType . This means that the vector elements must be primitive numbers or uni-type numerical - tuples of numbers. Mixed-type structures are not supported. The corresponding constructor is - explicit. Since STL vectors are not automatically converted to Mat instances, you should write - Mat(vec) explicitly. Unless you copy the data into the matrix ( copyData=true ), no new elements - will be added to the vector because it can potentially yield vector data reallocation, and, thus, - the matrix data pointer will be invalid. - @param copyData Flag to specify whether the underlying data of the STL vector should be copied - to (true) or shared with (false) the newly constructed matrix. When the data is copied, the - allocated buffer is managed using Mat reference counting mechanism. While the data is shared, - the reference counter is NULL, and you should not deallocate the data until the matrix is - destructed. - */ - template explicit Mat(const std::vector<_Tp>& vec, bool copyData=false); - - /** @overload - */ - template::value>::type> - explicit Mat(const std::initializer_list<_Tp> list); - - /** @overload - */ - template explicit Mat(const std::initializer_list sizes, const std::initializer_list<_Tp> list); - - /** @overload - */ - template explicit Mat(const std::array<_Tp, _Nm>& arr, bool copyData=false); - - /** @overload - */ - template explicit Mat(const Vec<_Tp, n>& vec, bool copyData=true); - - /** @overload - */ - template explicit Mat(const Matx<_Tp, m, n>& mtx, bool copyData=true); - - /** @overload - */ - template explicit Mat(const Point_<_Tp>& pt, bool copyData=true); - - /** @overload - */ - template explicit Mat(const Point3_<_Tp>& pt, bool copyData=true); - - /** @overload - */ - template explicit Mat(const MatCommaInitializer_<_Tp>& commaInitializer); - - //! download data from GpuMat - explicit Mat(const cuda::GpuMat& m); - - //! destructor - calls release() - ~Mat(); - - /** @brief assignment operators - - These are available assignment operators. Since they all are very different, make sure to read the - operator parameters description. - @param m Assigned, right-hand-side matrix. Matrix assignment is an O(1) operation. This means that - no data is copied but the data is shared and the reference counter, if any, is incremented. Before - assigning new data, the old data is de-referenced via Mat::release . - */ - Mat& operator = (const Mat& m); - - /** @overload - @param expr Assigned matrix expression object. As opposite to the first form of the assignment - operation, the second form can reuse already allocated matrix if it has the right size and type to - fit the matrix expression result. It is automatically handled by the real function that the matrix - expressions is expanded to. For example, C=A+B is expanded to add(A, B, C), and add takes care of - automatic C reallocation. - */ - Mat& operator = (const MatExpr& expr); - - //! retrieve UMat from Mat - UMat getUMat(AccessFlag accessFlags, UMatUsageFlags usageFlags = USAGE_DEFAULT) const; - - /** @brief Creates a matrix header for the specified matrix row. - - The method makes a new header for the specified matrix row and returns it. This is an O(1) - operation, regardless of the matrix size. The underlying data of the new matrix is shared with the - original matrix. Here is the example of one of the classical basic matrix processing operations, - axpy, used by LU and many other algorithms: - @code - inline void matrix_axpy(Mat& A, int i, int j, double alpha) - { - A.row(i) += A.row(j)*alpha; - } - @endcode - @note In the current implementation, the following code does not work as expected: - @code - Mat A; - ... - A.row(i) = A.row(j); // will not work - @endcode - This happens because A.row(i) forms a temporary header that is further assigned to another header. - Remember that each of these operations is O(1), that is, no data is copied. Thus, the above - assignment is not true if you may have expected the j-th row to be copied to the i-th row. To - achieve that, you should either turn this simple assignment into an expression or use the - Mat::copyTo method: - @code - Mat A; - ... - // works, but looks a bit obscure. - A.row(i) = A.row(j) + 0; - // this is a bit longer, but the recommended method. - A.row(j).copyTo(A.row(i)); - @endcode - @param y A 0-based row index. - */ - Mat row(int y) const; - - /** @brief Creates a matrix header for the specified matrix column. - - The method makes a new header for the specified matrix column and returns it. This is an O(1) - operation, regardless of the matrix size. The underlying data of the new matrix is shared with the - original matrix. See also the Mat::row description. - @param x A 0-based column index. - */ - Mat col(int x) const; - - /** @brief Creates a matrix header for the specified row span. - - The method makes a new header for the specified row span of the matrix. Similarly to Mat::row and - Mat::col , this is an O(1) operation. - @param startrow An inclusive 0-based start index of the row span. - @param endrow An exclusive 0-based ending index of the row span. - */ - Mat rowRange(int startrow, int endrow) const; - - /** @overload - @param r Range structure containing both the start and the end indices. - */ - Mat rowRange(const Range& r) const; - - /** @brief Creates a matrix header for the specified column span. - - The method makes a new header for the specified column span of the matrix. Similarly to Mat::row and - Mat::col , this is an O(1) operation. - @param startcol An inclusive 0-based start index of the column span. - @param endcol An exclusive 0-based ending index of the column span. - */ - Mat colRange(int startcol, int endcol) const; - - /** @overload - @param r Range structure containing both the start and the end indices. - */ - Mat colRange(const Range& r) const; - - /** @brief Extracts a diagonal from a matrix - - The method makes a new header for the specified matrix diagonal. The new matrix is represented as a - single-column matrix. Similarly to Mat::row and Mat::col, this is an O(1) operation. - @param d index of the diagonal, with the following values: - - `d=0` is the main diagonal. - - `d<0` is a diagonal from the lower half. For example, d=-1 means the diagonal is set - immediately below the main one. - - `d>0` is a diagonal from the upper half. For example, d=1 means the diagonal is set - immediately above the main one. - For example: - @code - Mat m = (Mat_(3,3) << - 1,2,3, - 4,5,6, - 7,8,9); - Mat d0 = m.diag(0); - Mat d1 = m.diag(1); - Mat d_1 = m.diag(-1); - @endcode - The resulting matrices are - @code - d0 = - [1; - 5; - 9] - d1 = - [2; - 6] - d_1 = - [4; - 8] - @endcode - */ - Mat diag(int d=0) const; - - /** @brief creates a diagonal matrix - - The method creates a square diagonal matrix from specified main diagonal. - @param d One-dimensional matrix that represents the main diagonal. - */ - CV_NODISCARD_STD static Mat diag(const Mat& d); - - /** @brief Creates a full copy of the array and the underlying data. - - The method creates a full copy of the array. The original step[] is not taken into account. So, the - array copy is a continuous array occupying total()*elemSize() bytes. - */ - CV_NODISCARD_STD Mat clone() const; - - /** @brief Copies the matrix to another one. - - The method copies the matrix data to another matrix. Before copying the data, the method invokes : - @code - m.create(this->size(), this->type()); - @endcode - so that the destination matrix is reallocated if needed. While m.copyTo(m); works flawlessly, the - function does not handle the case of a partial overlap between the source and the destination - matrices. - - When the operation mask is specified, if the Mat::create call shown above reallocates the matrix, - the newly allocated matrix is initialized with all zeros before copying the data. - @param m Destination matrix. If it does not have a proper size or type before the operation, it is - reallocated. - */ - void copyTo( OutputArray m ) const; - - /** @overload - @param m Destination matrix. If it does not have a proper size or type before the operation, it is - reallocated. - @param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix - elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels. - */ - void copyTo( OutputArray m, InputArray mask ) const; - - /** @brief Converts an array to another data type with optional scaling. - - The method converts source pixel values to the target data type. saturate_cast\<\> is applied at - the end to avoid possible overflows: - - \f[m(x,y) = saturate \_ cast( \alpha (*this)(x,y) + \beta )\f] - @param m output matrix; if it does not have a proper size or type before the operation, it is - reallocated. - @param rtype desired output matrix type or, rather, the depth since the number of channels are the - same as the input has; if rtype is negative, the output matrix will have the same type as the input. - @param alpha optional scale factor. - @param beta optional delta added to the scaled values. - */ - void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const; - - /** @brief Provides a functional form of convertTo. - - This is an internally used method called by the @ref MatrixExpressions engine. - @param m Destination array. - @param type Desired destination array depth (or -1 if it should be the same as the source type). - */ - void assignTo( Mat& m, int type=-1 ) const; - - /** @brief Sets all or some of the array elements to the specified value. - @param s Assigned scalar converted to the actual array type. - */ - Mat& operator = (const Scalar& s); - - /** @brief Sets all or some of the array elements to the specified value. - - This is an advanced variant of the Mat::operator=(const Scalar& s) operator. - @param value Assigned scalar converted to the actual array type. - @param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix - elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels - */ - Mat& setTo(InputArray value, InputArray mask=noArray()); - - /** @brief Changes the shape and/or the number of channels of a 2D matrix without copying the data. - - The method makes a new matrix header for \*this elements. The new matrix may have a different size - and/or different number of channels. Any combination is possible if: - - No extra elements are included into the new matrix and no elements are excluded. Consequently, - the product rows\*cols\*channels() must stay the same after the transformation. - - No data is copied. That is, this is an O(1) operation. Consequently, if you change the number of - rows, or the operation changes the indices of elements row in some other way, the matrix must be - continuous. See Mat::isContinuous . - - For example, if there is a set of 3D points stored as an STL vector, and you want to represent the - points as a 3xN matrix, do the following: - @code - std::vector vec; - ... - Mat pointMat = Mat(vec). // convert vector to Mat, O(1) operation - reshape(1). // make Nx3 1-channel matrix out of Nx1 3-channel. - // Also, an O(1) operation - t(); // finally, transpose the Nx3 matrix. - // This involves copying all the elements - @endcode - 3-channel 2x2 matrix reshaped to 1-channel 4x3 matrix, each column has values from one of original channels: - @code - Mat m(Size(2, 2), CV_8UC3, Scalar(1, 2, 3)); - vector new_shape {4, 3}; - m = m.reshape(1, new_shape); - @endcode - or: - @code - Mat m(Size(2, 2), CV_8UC3, Scalar(1, 2, 3)); - const int new_shape[] = {4, 3}; - m = m.reshape(1, 2, new_shape); - @endcode - @param cn New number of channels. If the parameter is 0, the number of channels remains the same. - @param rows New number of rows. If the parameter is 0, the number of rows remains the same. - */ - Mat reshape(int cn, int rows=0) const; - - /** @overload - * @param cn New number of channels. If the parameter is 0, the number of channels remains the same. - * @param newndims New number of dimentions. - * @param newsz Array with new matrix size by all dimentions. If some sizes are zero, - * the original sizes in those dimensions are presumed. - */ - Mat reshape(int cn, int newndims, const int* newsz) const; - - /** @overload - * @param cn New number of channels. If the parameter is 0, the number of channels remains the same. - * @param newshape Vector with new matrix size by all dimentions. If some sizes are zero, - * the original sizes in those dimensions are presumed. - */ - Mat reshape(int cn, const std::vector& newshape) const; - - /** @brief Transposes a matrix. - - The method performs matrix transposition by means of matrix expressions. It does not perform the - actual transposition but returns a temporary matrix transposition object that can be further used as - a part of more complex matrix expressions or can be assigned to a matrix: - @code - Mat A1 = A + Mat::eye(A.size(), A.type())*lambda; - Mat C = A1.t()*A1; // compute (A + lambda*I)^t * (A + lamda*I) - @endcode - */ - MatExpr t() const; - - /** @brief Inverses a matrix. - - The method performs a matrix inversion by means of matrix expressions. This means that a temporary - matrix inversion object is returned by the method and can be used further as a part of more complex - matrix expressions or can be assigned to a matrix. - @param method Matrix inversion method. One of cv::DecompTypes - */ - MatExpr inv(int method=DECOMP_LU) const; - - /** @brief Performs an element-wise multiplication or division of the two matrices. - - The method returns a temporary object encoding per-element array multiplication, with optional - scale. Note that this is not a matrix multiplication that corresponds to a simpler "\*" operator. - - Example: - @code - Mat C = A.mul(5/B); // equivalent to divide(A, B, C, 5) - @endcode - @param m Another array of the same type and the same size as \*this, or a matrix expression. - @param scale Optional scale factor. - */ - MatExpr mul(InputArray m, double scale=1) const; - - /** @brief Computes a cross-product of two 3-element vectors. - - The method computes a cross-product of two 3-element vectors. The vectors must be 3-element - floating-point vectors of the same shape and size. The result is another 3-element vector of the - same shape and type as operands. - @param m Another cross-product operand. - */ - Mat cross(InputArray m) const; - - /** @brief Computes a dot-product of two vectors. - - The method computes a dot-product of two matrices. If the matrices are not single-column or - single-row vectors, the top-to-bottom left-to-right scan ordering is used to treat them as 1D - vectors. The vectors must have the same size and type. If the matrices have more than one channel, - the dot products from all the channels are summed together. - @param m another dot-product operand. - */ - double dot(InputArray m) const; - - /** @brief Returns a zero array of the specified size and type. - - The method returns a Matlab-style zero array initializer. It can be used to quickly form a constant - array as a function parameter, part of a matrix expression, or as a matrix initializer: - @code - Mat A; - A = Mat::zeros(3, 3, CV_32F); - @endcode - In the example above, a new matrix is allocated only if A is not a 3x3 floating-point matrix. - Otherwise, the existing matrix A is filled with zeros. - @param rows Number of rows. - @param cols Number of columns. - @param type Created matrix type. - */ - CV_NODISCARD_STD static MatExpr zeros(int rows, int cols, int type); - - /** @overload - @param size Alternative to the matrix size specification Size(cols, rows) . - @param type Created matrix type. - */ - CV_NODISCARD_STD static MatExpr zeros(Size size, int type); - - /** @overload - @param ndims Array dimensionality. - @param sz Array of integers specifying the array shape. - @param type Created matrix type. - */ - CV_NODISCARD_STD static MatExpr zeros(int ndims, const int* sz, int type); - - /** @brief Returns an array of all 1's of the specified size and type. - - The method returns a Matlab-style 1's array initializer, similarly to Mat::zeros. Note that using - this method you can initialize an array with an arbitrary value, using the following Matlab idiom: - @code - Mat A = Mat::ones(100, 100, CV_8U)*3; // make 100x100 matrix filled with 3. - @endcode - The above operation does not form a 100x100 matrix of 1's and then multiply it by 3. Instead, it - just remembers the scale factor (3 in this case) and use it when actually invoking the matrix - initializer. - @note In case of multi-channels type, only the first channel will be initialized with 1's, the - others will be set to 0's. - @param rows Number of rows. - @param cols Number of columns. - @param type Created matrix type. - */ - CV_NODISCARD_STD static MatExpr ones(int rows, int cols, int type); - - /** @overload - @param size Alternative to the matrix size specification Size(cols, rows) . - @param type Created matrix type. - */ - CV_NODISCARD_STD static MatExpr ones(Size size, int type); - - /** @overload - @param ndims Array dimensionality. - @param sz Array of integers specifying the array shape. - @param type Created matrix type. - */ - CV_NODISCARD_STD static MatExpr ones(int ndims, const int* sz, int type); - - /** @brief Returns an identity matrix of the specified size and type. - - The method returns a Matlab-style identity matrix initializer, similarly to Mat::zeros. Similarly to - Mat::ones, you can use a scale operation to create a scaled identity matrix efficiently: - @code - // make a 4x4 diagonal matrix with 0.1's on the diagonal. - Mat A = Mat::eye(4, 4, CV_32F)*0.1; - @endcode - @note In case of multi-channels type, identity matrix will be initialized only for the first channel, - the others will be set to 0's - @param rows Number of rows. - @param cols Number of columns. - @param type Created matrix type. - */ - CV_NODISCARD_STD static MatExpr eye(int rows, int cols, int type); - - /** @overload - @param size Alternative matrix size specification as Size(cols, rows) . - @param type Created matrix type. - */ - CV_NODISCARD_STD static MatExpr eye(Size size, int type); - - /** @brief Allocates new array data if needed. - - This is one of the key Mat methods. Most new-style OpenCV functions and methods that produce arrays - call this method for each output array. The method uses the following algorithm: - - -# If the current array shape and the type match the new ones, return immediately. Otherwise, - de-reference the previous data by calling Mat::release. - -# Initialize the new header. - -# Allocate the new data of total()\*elemSize() bytes. - -# Allocate the new, associated with the data, reference counter and set it to 1. - - Such a scheme makes the memory management robust and efficient at the same time and helps avoid - extra typing for you. This means that usually there is no need to explicitly allocate output arrays. - That is, instead of writing: - @code - Mat color; - ... - Mat gray(color.rows, color.cols, color.depth()); - cvtColor(color, gray, COLOR_BGR2GRAY); - @endcode - you can simply write: - @code - Mat color; - ... - Mat gray; - cvtColor(color, gray, COLOR_BGR2GRAY); - @endcode - because cvtColor, as well as the most of OpenCV functions, calls Mat::create() for the output array - internally. - @param rows New number of rows. - @param cols New number of columns. - @param type New matrix type. - */ - void create(int rows, int cols, int type); - - /** @overload - @param size Alternative new matrix size specification: Size(cols, rows) - @param type New matrix type. - */ - void create(Size size, int type); - - /** @overload - @param ndims New array dimensionality. - @param sizes Array of integers specifying a new array shape. - @param type New matrix type. - */ - void create(int ndims, const int* sizes, int type); - - /** @overload - @param sizes Array of integers specifying a new array shape. - @param type New matrix type. - */ - void create(const std::vector& sizes, int type); - - /** @brief Increments the reference counter. - - The method increments the reference counter associated with the matrix data. If the matrix header - points to an external data set (see Mat::Mat ), the reference counter is NULL, and the method has no - effect in this case. Normally, to avoid memory leaks, the method should not be called explicitly. It - is called implicitly by the matrix assignment operator. The reference counter increment is an atomic - operation on the platforms that support it. Thus, it is safe to operate on the same matrices - asynchronously in different threads. - */ - void addref(); - - /** @brief Decrements the reference counter and deallocates the matrix if needed. - - The method decrements the reference counter associated with the matrix data. When the reference - counter reaches 0, the matrix data is deallocated and the data and the reference counter pointers - are set to NULL's. If the matrix header points to an external data set (see Mat::Mat ), the - reference counter is NULL, and the method has no effect in this case. - - This method can be called manually to force the matrix data deallocation. But since this method is - automatically called in the destructor, or by any other method that changes the data pointer, it is - usually not needed. The reference counter decrement and check for 0 is an atomic operation on the - platforms that support it. Thus, it is safe to operate on the same matrices asynchronously in - different threads. - */ - void release(); - - //! internal use function, consider to use 'release' method instead; deallocates the matrix data - void deallocate(); - //! internal use function; properly re-allocates _size, _step arrays - void copySize(const Mat& m); - - /** @brief Reserves space for the certain number of rows. - - The method reserves space for sz rows. If the matrix already has enough space to store sz rows, - nothing happens. If the matrix is reallocated, the first Mat::rows rows are preserved. The method - emulates the corresponding method of the STL vector class. - @param sz Number of rows. - */ - void reserve(size_t sz); - - /** @brief Reserves space for the certain number of bytes. - - The method reserves space for sz bytes. If the matrix already has enough space to store sz bytes, - nothing happens. If matrix has to be reallocated its previous content could be lost. - @param sz Number of bytes. - */ - void reserveBuffer(size_t sz); - - /** @brief Changes the number of matrix rows. - - The methods change the number of matrix rows. If the matrix is reallocated, the first - min(Mat::rows, sz) rows are preserved. The methods emulate the corresponding methods of the STL - vector class. - @param sz New number of rows. - */ - void resize(size_t sz); - - /** @overload - @param sz New number of rows. - @param s Value assigned to the newly added elements. - */ - void resize(size_t sz, const Scalar& s); - - //! internal function - void push_back_(const void* elem); - - /** @brief Adds elements to the bottom of the matrix. - - The methods add one or more elements to the bottom of the matrix. They emulate the corresponding - method of the STL vector class. When elem is Mat , its type and the number of columns must be the - same as in the container matrix. - @param elem Added element(s). - */ - template void push_back(const _Tp& elem); - - /** @overload - @param elem Added element(s). - */ - template void push_back(const Mat_<_Tp>& elem); - - /** @overload - @param elem Added element(s). - */ - template void push_back(const std::vector<_Tp>& elem); - - /** @overload - @param m Added line(s). - */ - void push_back(const Mat& m); - - /** @brief Removes elements from the bottom of the matrix. - - The method removes one or more rows from the bottom of the matrix. - @param nelems Number of removed rows. If it is greater than the total number of rows, an exception - is thrown. - */ - void pop_back(size_t nelems=1); - - /** @brief Locates the matrix header within a parent matrix. - - After you extracted a submatrix from a matrix using Mat::row, Mat::col, Mat::rowRange, - Mat::colRange, and others, the resultant submatrix points just to the part of the original big - matrix. However, each submatrix contains information (represented by datastart and dataend - fields) that helps reconstruct the original matrix size and the position of the extracted - submatrix within the original matrix. The method locateROI does exactly that. - @param wholeSize Output parameter that contains the size of the whole matrix containing *this* - as a part. - @param ofs Output parameter that contains an offset of *this* inside the whole matrix. - */ - void locateROI( Size& wholeSize, Point& ofs ) const; - - /** @brief Adjusts a submatrix size and position within the parent matrix. - - The method is complimentary to Mat::locateROI . The typical use of these functions is to determine - the submatrix position within the parent matrix and then shift the position somehow. Typically, it - can be required for filtering operations when pixels outside of the ROI should be taken into - account. When all the method parameters are positive, the ROI needs to grow in all directions by the - specified amount, for example: - @code - A.adjustROI(2, 2, 2, 2); - @endcode - In this example, the matrix size is increased by 4 elements in each direction. The matrix is shifted - by 2 elements to the left and 2 elements up, which brings in all the necessary pixels for the - filtering with the 5x5 kernel. - - adjustROI forces the adjusted ROI to be inside of the parent matrix that is boundaries of the - adjusted ROI are constrained by boundaries of the parent matrix. For example, if the submatrix A is - located in the first row of a parent matrix and you called A.adjustROI(2, 2, 2, 2) then A will not - be increased in the upward direction. - - The function is used internally by the OpenCV filtering functions, like filter2D , morphological - operations, and so on. - @param dtop Shift of the top submatrix boundary upwards. - @param dbottom Shift of the bottom submatrix boundary downwards. - @param dleft Shift of the left submatrix boundary to the left. - @param dright Shift of the right submatrix boundary to the right. - @sa copyMakeBorder - */ - Mat& adjustROI( int dtop, int dbottom, int dleft, int dright ); - - /** @brief Extracts a rectangular submatrix. - - The operators make a new header for the specified sub-array of \*this . They are the most - generalized forms of Mat::row, Mat::col, Mat::rowRange, and Mat::colRange . For example, - `A(Range(0, 10), Range::all())` is equivalent to `A.rowRange(0, 10)`. Similarly to all of the above, - the operators are O(1) operations, that is, no matrix data is copied. - @param rowRange Start and end row of the extracted submatrix. The upper boundary is not included. To - select all the rows, use Range::all(). - @param colRange Start and end column of the extracted submatrix. The upper boundary is not included. - To select all the columns, use Range::all(). - */ - Mat operator()( Range rowRange, Range colRange ) const; - - /** @overload - @param roi Extracted submatrix specified as a rectangle. - */ - Mat operator()( const Rect& roi ) const; - - /** @overload - @param ranges Array of selected ranges along each array dimension. - */ - Mat operator()( const Range* ranges ) const; - - /** @overload - @param ranges Array of selected ranges along each array dimension. - */ - Mat operator()(const std::vector& ranges) const; - - template operator std::vector<_Tp>() const; - template operator Vec<_Tp, n>() const; - template operator Matx<_Tp, m, n>() const; - - template operator std::array<_Tp, _Nm>() const; - - /** @brief Reports whether the matrix is continuous or not. - - The method returns true if the matrix elements are stored continuously without gaps at the end of - each row. Otherwise, it returns false. Obviously, 1x1 or 1xN matrices are always continuous. - Matrices created with Mat::create are always continuous. But if you extract a part of the matrix - using Mat::col, Mat::diag, and so on, or constructed a matrix header for externally allocated data, - such matrices may no longer have this property. - - The continuity flag is stored as a bit in the Mat::flags field and is computed automatically when - you construct a matrix header. Thus, the continuity check is a very fast operation, though - theoretically it could be done as follows: - @code - // alternative implementation of Mat::isContinuous() - bool myCheckMatContinuity(const Mat& m) - { - //return (m.flags & Mat::CONTINUOUS_FLAG) != 0; - return m.rows == 1 || m.step == m.cols*m.elemSize(); - } - @endcode - The method is used in quite a few of OpenCV functions. The point is that element-wise operations - (such as arithmetic and logical operations, math functions, alpha blending, color space - transformations, and others) do not depend on the image geometry. Thus, if all the input and output - arrays are continuous, the functions can process them as very long single-row vectors. The example - below illustrates how an alpha-blending function can be implemented: - @code - template - void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst) - { - const float alpha_scale = (float)std::numeric_limits::max(), - inv_scale = 1.f/alpha_scale; - - CV_Assert( src1.type() == src2.type() && - src1.type() == CV_MAKETYPE(traits::Depth::value, 4) && - src1.size() == src2.size()); - Size size = src1.size(); - dst.create(size, src1.type()); - - // here is the idiom: check the arrays for continuity and, - // if this is the case, - // treat the arrays as 1D vectors - if( src1.isContinuous() && src2.isContinuous() && dst.isContinuous() ) - { - size.width *= size.height; - size.height = 1; - } - size.width *= 4; - - for( int i = 0; i < size.height; i++ ) - { - // when the arrays are continuous, - // the outer loop is executed only once - const T* ptr1 = src1.ptr(i); - const T* ptr2 = src2.ptr(i); - T* dptr = dst.ptr(i); - - for( int j = 0; j < size.width; j += 4 ) - { - float alpha = ptr1[j+3]*inv_scale, beta = ptr2[j+3]*inv_scale; - dptr[j] = saturate_cast(ptr1[j]*alpha + ptr2[j]*beta); - dptr[j+1] = saturate_cast(ptr1[j+1]*alpha + ptr2[j+1]*beta); - dptr[j+2] = saturate_cast(ptr1[j+2]*alpha + ptr2[j+2]*beta); - dptr[j+3] = saturate_cast((1 - (1-alpha)*(1-beta))*alpha_scale); - } - } - } - @endcode - This approach, while being very simple, can boost the performance of a simple element-operation by - 10-20 percents, especially if the image is rather small and the operation is quite simple. - - Another OpenCV idiom in this function, a call of Mat::create for the destination array, that - allocates the destination array unless it already has the proper size and type. And while the newly - allocated arrays are always continuous, you still need to check the destination array because - Mat::create does not always allocate a new matrix. - */ - bool isContinuous() const; - - //! returns true if the matrix is a submatrix of another matrix - bool isSubmatrix() const; - - /** @brief Returns the matrix element size in bytes. - - The method returns the matrix element size in bytes. For example, if the matrix type is CV_16SC3 , - the method returns 3\*sizeof(short) or 6. - */ - size_t elemSize() const; - - /** @brief Returns the size of each matrix element channel in bytes. - - The method returns the matrix element channel size in bytes, that is, it ignores the number of - channels. For example, if the matrix type is CV_16SC3 , the method returns sizeof(short) or 2. - */ - size_t elemSize1() const; - - /** @brief Returns the type of a matrix element. - - The method returns a matrix element type. This is an identifier compatible with the CvMat type - system, like CV_16SC3 or 16-bit signed 3-channel array, and so on. - */ - int type() const; - - /** @brief Returns the depth of a matrix element. - - The method returns the identifier of the matrix element depth (the type of each individual channel). - For example, for a 16-bit signed element array, the method returns CV_16S . A complete list of - matrix types contains the following values: - - CV_8U - 8-bit unsigned integers ( 0..255 ) - - CV_8S - 8-bit signed integers ( -128..127 ) - - CV_16U - 16-bit unsigned integers ( 0..65535 ) - - CV_16S - 16-bit signed integers ( -32768..32767 ) - - CV_32S - 32-bit signed integers ( -2147483648..2147483647 ) - - CV_32F - 32-bit floating-point numbers ( -FLT_MAX..FLT_MAX, INF, NAN ) - - CV_64F - 64-bit floating-point numbers ( -DBL_MAX..DBL_MAX, INF, NAN ) - */ - int depth() const; - - /** @brief Returns the number of matrix channels. - - The method returns the number of matrix channels. - */ - int channels() const; - - /** @brief Returns a normalized step. - - The method returns a matrix step divided by Mat::elemSize1() . It can be useful to quickly access an - arbitrary matrix element. - */ - size_t step1(int i=0) const; - - /** @brief Returns true if the array has no elements. - - The method returns true if Mat::total() is 0 or if Mat::data is NULL. Because of pop_back() and - resize() methods `M.total() == 0` does not imply that `M.data == NULL`. - */ - bool empty() const; - - /** @brief Returns the total number of array elements. - - The method returns the number of array elements (a number of pixels if the array represents an - image). - */ - size_t total() const; - - /** @brief Returns the total number of array elements. - - The method returns the number of elements within a certain sub-array slice with startDim <= dim < endDim - */ - size_t total(int startDim, int endDim=INT_MAX) const; - - /** - * @param elemChannels Number of channels or number of columns the matrix should have. - * For a 2-D matrix, when the matrix has only 1 column, then it should have - * elemChannels channels; When the matrix has only 1 channel, - * then it should have elemChannels columns. - * For a 3-D matrix, it should have only one channel. Furthermore, - * if the number of planes is not one, then the number of rows - * within every plane has to be 1; if the number of rows within - * every plane is not 1, then the number of planes has to be 1. - * @param depth The depth the matrix should have. Set it to -1 when any depth is fine. - * @param requireContinuous Set it to true to require the matrix to be continuous - * @return -1 if the requirement is not satisfied. - * Otherwise, it returns the number of elements in the matrix. Note - * that an element may have multiple channels. - * - * The following code demonstrates its usage for a 2-d matrix: - * @snippet snippets/core_mat_checkVector.cpp example-2d - * - * The following code demonstrates its usage for a 3-d matrix: - * @snippet snippets/core_mat_checkVector.cpp example-3d - */ - int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const; - - /** @brief Returns a pointer to the specified matrix row. - - The methods return `uchar*` or typed pointer to the specified matrix row. See the sample in - Mat::isContinuous to know how to use these methods. - @param i0 A 0-based row index. - */ - uchar* ptr(int i0=0); - /** @overload */ - const uchar* ptr(int i0=0) const; - - /** @overload - @param row Index along the dimension 0 - @param col Index along the dimension 1 - */ - uchar* ptr(int row, int col); - /** @overload - @param row Index along the dimension 0 - @param col Index along the dimension 1 - */ - const uchar* ptr(int row, int col) const; - - /** @overload */ - uchar* ptr(int i0, int i1, int i2); - /** @overload */ - const uchar* ptr(int i0, int i1, int i2) const; - - /** @overload */ - uchar* ptr(const int* idx); - /** @overload */ - const uchar* ptr(const int* idx) const; - /** @overload */ - template uchar* ptr(const Vec& idx); - /** @overload */ - template const uchar* ptr(const Vec& idx) const; - - /** @overload */ - template _Tp* ptr(int i0=0); - /** @overload */ - template const _Tp* ptr(int i0=0) const; - /** @overload - @param row Index along the dimension 0 - @param col Index along the dimension 1 - */ - template _Tp* ptr(int row, int col); - /** @overload - @param row Index along the dimension 0 - @param col Index along the dimension 1 - */ - template const _Tp* ptr(int row, int col) const; - /** @overload */ - template _Tp* ptr(int i0, int i1, int i2); - /** @overload */ - template const _Tp* ptr(int i0, int i1, int i2) const; - /** @overload */ - template _Tp* ptr(const int* idx); - /** @overload */ - template const _Tp* ptr(const int* idx) const; - /** @overload */ - template _Tp* ptr(const Vec& idx); - /** @overload */ - template const _Tp* ptr(const Vec& idx) const; - - /** @brief Returns a reference to the specified array element. - - The template methods return a reference to the specified array element. For the sake of higher - performance, the index range checks are only performed in the Debug configuration. - - Note that the variants with a single index (i) can be used to access elements of single-row or - single-column 2-dimensional arrays. That is, if, for example, A is a 1 x N floating-point matrix and - B is an M x 1 integer matrix, you can simply write `A.at(k+4)` and `B.at(2*i+1)` - instead of `A.at(0,k+4)` and `B.at(2*i+1,0)`, respectively. - - The example below initializes a Hilbert matrix: - @code - Mat H(100, 100, CV_64F); - for(int i = 0; i < H.rows; i++) - for(int j = 0; j < H.cols; j++) - H.at(i,j)=1./(i+j+1); - @endcode - - Keep in mind that the size identifier used in the at operator cannot be chosen at random. It depends - on the image from which you are trying to retrieve the data. The table below gives a better insight in this: - - If matrix is of type `CV_8U` then use `Mat.at(y,x)`. - - If matrix is of type `CV_8S` then use `Mat.at(y,x)`. - - If matrix is of type `CV_16U` then use `Mat.at(y,x)`. - - If matrix is of type `CV_16S` then use `Mat.at(y,x)`. - - If matrix is of type `CV_32S` then use `Mat.at(y,x)`. - - If matrix is of type `CV_32F` then use `Mat.at(y,x)`. - - If matrix is of type `CV_64F` then use `Mat.at(y,x)`. - - @param i0 Index along the dimension 0 - */ - template _Tp& at(int i0=0); - /** @overload - @param i0 Index along the dimension 0 - */ - template const _Tp& at(int i0=0) const; - /** @overload - @param row Index along the dimension 0 - @param col Index along the dimension 1 - */ - template _Tp& at(int row, int col); - /** @overload - @param row Index along the dimension 0 - @param col Index along the dimension 1 - */ - template const _Tp& at(int row, int col) const; - - /** @overload - @param i0 Index along the dimension 0 - @param i1 Index along the dimension 1 - @param i2 Index along the dimension 2 - */ - template _Tp& at(int i0, int i1, int i2); - /** @overload - @param i0 Index along the dimension 0 - @param i1 Index along the dimension 1 - @param i2 Index along the dimension 2 - */ - template const _Tp& at(int i0, int i1, int i2) const; - - /** @overload - @param idx Array of Mat::dims indices. - */ - template _Tp& at(const int* idx); - /** @overload - @param idx Array of Mat::dims indices. - */ - template const _Tp& at(const int* idx) const; - - /** @overload */ - template _Tp& at(const Vec& idx); - /** @overload */ - template const _Tp& at(const Vec& idx) const; - - /** @overload - special versions for 2D arrays (especially convenient for referencing image pixels) - @param pt Element position specified as Point(j,i) . - */ - template _Tp& at(Point pt); - /** @overload - special versions for 2D arrays (especially convenient for referencing image pixels) - @param pt Element position specified as Point(j,i) . - */ - template const _Tp& at(Point pt) const; - - /** @brief Returns the matrix iterator and sets it to the first matrix element. - - The methods return the matrix read-only or read-write iterators. The use of matrix iterators is very - similar to the use of bi-directional STL iterators. In the example below, the alpha blending - function is rewritten using the matrix iterators: - @code - template - void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst) - { - typedef Vec VT; - - const float alpha_scale = (float)std::numeric_limits::max(), - inv_scale = 1.f/alpha_scale; - - CV_Assert( src1.type() == src2.type() && - src1.type() == traits::Type::value && - src1.size() == src2.size()); - Size size = src1.size(); - dst.create(size, src1.type()); - - MatConstIterator_ it1 = src1.begin(), it1_end = src1.end(); - MatConstIterator_ it2 = src2.begin(); - MatIterator_ dst_it = dst.begin(); - - for( ; it1 != it1_end; ++it1, ++it2, ++dst_it ) - { - VT pix1 = *it1, pix2 = *it2; - float alpha = pix1[3]*inv_scale, beta = pix2[3]*inv_scale; - *dst_it = VT(saturate_cast(pix1[0]*alpha + pix2[0]*beta), - saturate_cast(pix1[1]*alpha + pix2[1]*beta), - saturate_cast(pix1[2]*alpha + pix2[2]*beta), - saturate_cast((1 - (1-alpha)*(1-beta))*alpha_scale)); - } - } - @endcode - */ - template MatIterator_<_Tp> begin(); - template MatConstIterator_<_Tp> begin() const; - - /** @brief Same as begin() but for inverse traversal - */ - template std::reverse_iterator> rbegin(); - template std::reverse_iterator> rbegin() const; - - /** @brief Returns the matrix iterator and sets it to the after-last matrix element. - - The methods return the matrix read-only or read-write iterators, set to the point following the last - matrix element. - */ - template MatIterator_<_Tp> end(); - template MatConstIterator_<_Tp> end() const; - - /** @brief Same as end() but for inverse traversal - */ - template std::reverse_iterator< MatIterator_<_Tp>> rend(); - template std::reverse_iterator< MatConstIterator_<_Tp>> rend() const; - - - /** @brief Runs the given functor over all matrix elements in parallel. - - The operation passed as argument has to be a function pointer, a function object or a lambda(C++11). - - Example 1. All of the operations below put 0xFF the first channel of all matrix elements: - @code - Mat image(1920, 1080, CV_8UC3); - typedef cv::Point3_ Pixel; - - // first. raw pointer access. - for (int r = 0; r < image.rows; ++r) { - Pixel* ptr = image.ptr(r, 0); - const Pixel* ptr_end = ptr + image.cols; - for (; ptr != ptr_end; ++ptr) { - ptr->x = 255; - } - } - - // Using MatIterator. (Simple but there are a Iterator's overhead) - for (Pixel &p : cv::Mat_(image)) { - p.x = 255; - } - - // Parallel execution with function object. - struct Operator { - void operator ()(Pixel &pixel, const int * position) { - pixel.x = 255; - } - }; - image.forEach(Operator()); - - // Parallel execution using C++11 lambda. - image.forEach([](Pixel &p, const int * position) -> void { - p.x = 255; - }); - @endcode - Example 2. Using the pixel's position: - @code - // Creating 3D matrix (255 x 255 x 255) typed uint8_t - // and initialize all elements by the value which equals elements position. - // i.e. pixels (x,y,z) = (1,2,3) is (b,g,r) = (1,2,3). - - int sizes[] = { 255, 255, 255 }; - typedef cv::Point3_ Pixel; - - Mat_ image = Mat::zeros(3, sizes, CV_8UC3); - - image.forEach([](Pixel& pixel, const int position[]) -> void { - pixel.x = position[0]; - pixel.y = position[1]; - pixel.z = position[2]; - }); - @endcode - */ - template void forEach(const Functor& operation); - /** @overload */ - template void forEach(const Functor& operation) const; - - Mat(Mat&& m) CV_NOEXCEPT; - Mat& operator = (Mat&& m); - - enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG }; - enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 }; - - /*! includes several bit-fields: - - the magic signature - - continuity flag - - depth - - number of channels - */ - int flags; - //! the matrix dimensionality, >= 2 - int dims; - //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions - int rows, cols; - //! pointer to the data - uchar* data; - - //! helper fields used in locateROI and adjustROI - const uchar* datastart; - const uchar* dataend; - const uchar* datalimit; - - //! custom allocator - MatAllocator* allocator; - //! and the standard allocator - static MatAllocator* getStdAllocator(); - static MatAllocator* getDefaultAllocator(); - static void setDefaultAllocator(MatAllocator* allocator); - - //! internal use method: updates the continuity flag - void updateContinuityFlag(); - - //! interaction with UMat - UMatData* u; - - MatSize size; - MatStep step; - -protected: - template void forEach_impl(const Functor& operation); -}; - - -///////////////////////////////// Mat_<_Tp> //////////////////////////////////// - -/** @brief Template matrix class derived from Mat - -@code{.cpp} - template class Mat_ : public Mat - { - public: - // ... some specific methods - // and - // no new extra fields - }; -@endcode -The class `Mat_<_Tp>` is a *thin* template wrapper on top of the Mat class. It does not have any -extra data fields. Nor this class nor Mat has any virtual methods. Thus, references or pointers to -these two classes can be freely but carefully converted one to another. For example: -@code{.cpp} - // create a 100x100 8-bit matrix - Mat M(100,100,CV_8U); - // this will be compiled fine. no any data conversion will be done. - Mat_& M1 = (Mat_&)M; - // the program is likely to crash at the statement below - M1(99,99) = 1.f; -@endcode -While Mat is sufficient in most cases, Mat_ can be more convenient if you use a lot of element -access operations and if you know matrix type at the compilation time. Note that -`Mat::at(int y,int x)` and `Mat_::operator()(int y,int x)` do absolutely the same -and run at the same speed, but the latter is certainly shorter: -@code{.cpp} - Mat_ M(20,20); - for(int i = 0; i < M.rows; i++) - for(int j = 0; j < M.cols; j++) - M(i,j) = 1./(i+j+1); - Mat E, V; - eigen(M,E,V); - cout << E.at(0,0)/E.at(M.rows-1,0); -@endcode -To use Mat_ for multi-channel images/matrices, pass Vec as a Mat_ parameter: -@code{.cpp} - // allocate a 320x240 color image and fill it with green (in RGB space) - Mat_ img(240, 320, Vec3b(0,255,0)); - // now draw a diagonal white line - for(int i = 0; i < 100; i++) - img(i,i)=Vec3b(255,255,255); - // and now scramble the 2nd (red) channel of each pixel - for(int i = 0; i < img.rows; i++) - for(int j = 0; j < img.cols; j++) - img(i,j)[2] ^= (uchar)(i ^ j); -@endcode -Mat_ is fully compatible with C++11 range-based for loop. For example such loop -can be used to safely apply look-up table: -@code{.cpp} -void applyTable(Mat_& I, const uchar* const table) -{ - for(auto& pixel : I) - { - pixel = table[pixel]; - } -} -@endcode - */ -template class Mat_ : public Mat -{ -public: - typedef _Tp value_type; - typedef typename DataType<_Tp>::channel_type channel_type; - typedef MatIterator_<_Tp> iterator; - typedef MatConstIterator_<_Tp> const_iterator; - - //! default constructor - Mat_() CV_NOEXCEPT; - //! equivalent to Mat(_rows, _cols, DataType<_Tp>::type) - Mat_(int _rows, int _cols); - //! constructor that sets each matrix element to specified value - Mat_(int _rows, int _cols, const _Tp& value); - //! equivalent to Mat(_size, DataType<_Tp>::type) - explicit Mat_(Size _size); - //! constructor that sets each matrix element to specified value - Mat_(Size _size, const _Tp& value); - //! n-dim array constructor - Mat_(int _ndims, const int* _sizes); - //! n-dim array constructor that sets each matrix element to specified value - Mat_(int _ndims, const int* _sizes, const _Tp& value); - //! copy/conversion constructor. If m is of different type, it's converted - Mat_(const Mat& m); - //! copy constructor - Mat_(const Mat_& m); - //! constructs a matrix on top of user-allocated data. step is in bytes(!!!), regardless of the type - Mat_(int _rows, int _cols, _Tp* _data, size_t _step=AUTO_STEP); - //! constructs n-dim matrix on top of user-allocated data. steps are in bytes(!!!), regardless of the type - Mat_(int _ndims, const int* _sizes, _Tp* _data, const size_t* _steps=0); - //! selects a submatrix - Mat_(const Mat_& m, const Range& rowRange, const Range& colRange=Range::all()); - //! selects a submatrix - Mat_(const Mat_& m, const Rect& roi); - //! selects a submatrix, n-dim version - Mat_(const Mat_& m, const Range* ranges); - //! selects a submatrix, n-dim version - Mat_(const Mat_& m, const std::vector& ranges); - //! from a matrix expression - explicit Mat_(const MatExpr& e); - //! makes a matrix out of Vec, std::vector, Point_ or Point3_. The matrix will have a single column - explicit Mat_(const std::vector<_Tp>& vec, bool copyData=false); - template explicit Mat_(const Vec::channel_type, n>& vec, bool copyData=true); - template explicit Mat_(const Matx::channel_type, m, n>& mtx, bool copyData=true); - explicit Mat_(const Point_::channel_type>& pt, bool copyData=true); - explicit Mat_(const Point3_::channel_type>& pt, bool copyData=true); - explicit Mat_(const MatCommaInitializer_<_Tp>& commaInitializer); - - Mat_(std::initializer_list<_Tp> values); - explicit Mat_(const std::initializer_list sizes, const std::initializer_list<_Tp> values); - - template explicit Mat_(const std::array<_Tp, _Nm>& arr, bool copyData=false); - - Mat_& operator = (const Mat& m); - Mat_& operator = (const Mat_& m); - //! set all the elements to s. - Mat_& operator = (const _Tp& s); - //! assign a matrix expression - Mat_& operator = (const MatExpr& e); - - //! iterators; they are smart enough to skip gaps in the end of rows - iterator begin(); - iterator end(); - const_iterator begin() const; - const_iterator end() const; - - //reverse iterators - std::reverse_iterator rbegin(); - std::reverse_iterator rend(); - std::reverse_iterator rbegin() const; - std::reverse_iterator rend() const; - - //! template methods for operation over all matrix elements. - // the operations take care of skipping gaps in the end of rows (if any) - template void forEach(const Functor& operation); - template void forEach(const Functor& operation) const; - - //! equivalent to Mat::create(_rows, _cols, DataType<_Tp>::type) - void create(int _rows, int _cols); - //! equivalent to Mat::create(_size, DataType<_Tp>::type) - void create(Size _size); - //! equivalent to Mat::create(_ndims, _sizes, DatType<_Tp>::type) - void create(int _ndims, const int* _sizes); - //! equivalent to Mat::release() - void release(); - //! cross-product - Mat_ cross(const Mat_& m) const; - //! data type conversion - template operator Mat_() const; - //! overridden forms of Mat::row() etc. - Mat_ row(int y) const; - Mat_ col(int x) const; - Mat_ diag(int d=0) const; - CV_NODISCARD_STD Mat_ clone() const; - - //! overridden forms of Mat::elemSize() etc. - size_t elemSize() const; - size_t elemSize1() const; - int type() const; - int depth() const; - int channels() const; - size_t step1(int i=0) const; - //! returns step()/sizeof(_Tp) - size_t stepT(int i=0) const; - - //! overridden forms of Mat::zeros() etc. Data type is omitted, of course - CV_NODISCARD_STD static MatExpr zeros(int rows, int cols); - CV_NODISCARD_STD static MatExpr zeros(Size size); - CV_NODISCARD_STD static MatExpr zeros(int _ndims, const int* _sizes); - CV_NODISCARD_STD static MatExpr ones(int rows, int cols); - CV_NODISCARD_STD static MatExpr ones(Size size); - CV_NODISCARD_STD static MatExpr ones(int _ndims, const int* _sizes); - CV_NODISCARD_STD static MatExpr eye(int rows, int cols); - CV_NODISCARD_STD static MatExpr eye(Size size); - - //! some more overridden methods - Mat_& adjustROI( int dtop, int dbottom, int dleft, int dright ); - Mat_ operator()( const Range& rowRange, const Range& colRange ) const; - Mat_ operator()( const Rect& roi ) const; - Mat_ operator()( const Range* ranges ) const; - Mat_ operator()(const std::vector& ranges) const; - - //! more convenient forms of row and element access operators - _Tp* operator [](int y); - const _Tp* operator [](int y) const; - - //! returns reference to the specified element - _Tp& operator ()(const int* idx); - //! returns read-only reference to the specified element - const _Tp& operator ()(const int* idx) const; - - //! returns reference to the specified element - template _Tp& operator ()(const Vec& idx); - //! returns read-only reference to the specified element - template const _Tp& operator ()(const Vec& idx) const; - - //! returns reference to the specified element (1D case) - _Tp& operator ()(int idx0); - //! returns read-only reference to the specified element (1D case) - const _Tp& operator ()(int idx0) const; - //! returns reference to the specified element (2D case) - _Tp& operator ()(int row, int col); - //! returns read-only reference to the specified element (2D case) - const _Tp& operator ()(int row, int col) const; - //! returns reference to the specified element (3D case) - _Tp& operator ()(int idx0, int idx1, int idx2); - //! returns read-only reference to the specified element (3D case) - const _Tp& operator ()(int idx0, int idx1, int idx2) const; - - _Tp& operator ()(Point pt); - const _Tp& operator ()(Point pt) const; - - //! conversion to vector. - operator std::vector<_Tp>() const; - - //! conversion to array. - template operator std::array<_Tp, _Nm>() const; - - //! conversion to Vec - template operator Vec::channel_type, n>() const; - //! conversion to Matx - template operator Matx::channel_type, m, n>() const; - - Mat_(Mat_&& m); - Mat_& operator = (Mat_&& m); - - Mat_(Mat&& m); - Mat_& operator = (Mat&& m); - - Mat_(MatExpr&& e); -}; - -typedef Mat_ Mat1b; -typedef Mat_ Mat2b; -typedef Mat_ Mat3b; -typedef Mat_ Mat4b; - -typedef Mat_ Mat1s; -typedef Mat_ Mat2s; -typedef Mat_ Mat3s; -typedef Mat_ Mat4s; - -typedef Mat_ Mat1w; -typedef Mat_ Mat2w; -typedef Mat_ Mat3w; -typedef Mat_ Mat4w; - -typedef Mat_ Mat1i; -typedef Mat_ Mat2i; -typedef Mat_ Mat3i; -typedef Mat_ Mat4i; - -typedef Mat_ Mat1f; -typedef Mat_ Mat2f; -typedef Mat_ Mat3f; -typedef Mat_ Mat4f; - -typedef Mat_ Mat1d; -typedef Mat_ Mat2d; -typedef Mat_ Mat3d; -typedef Mat_ Mat4d; - -/** @todo document */ -class CV_EXPORTS UMat -{ -public: - //! default constructor - UMat(UMatUsageFlags usageFlags = USAGE_DEFAULT) CV_NOEXCEPT; - //! constructs 2D matrix of the specified size and type - // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.) - UMat(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); - UMat(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); - //! constructs 2D matrix and fills it with the specified value _s. - UMat(int rows, int cols, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT); - UMat(Size size, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT); - - //! constructs n-dimensional matrix - UMat(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); - UMat(int ndims, const int* sizes, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT); - - //! copy constructor - UMat(const UMat& m); - - //! creates a matrix header for a part of the bigger matrix - UMat(const UMat& m, const Range& rowRange, const Range& colRange=Range::all()); - UMat(const UMat& m, const Rect& roi); - UMat(const UMat& m, const Range* ranges); - UMat(const UMat& m, const std::vector& ranges); - - // FIXIT copyData=false is not implemented, drop this in favor of cv::Mat (OpenCV 5.0) - //! builds matrix from std::vector with or without copying the data - template explicit UMat(const std::vector<_Tp>& vec, bool copyData=false); - - //! destructor - calls release() - ~UMat(); - //! assignment operators - UMat& operator = (const UMat& m); - - Mat getMat(AccessFlag flags) const; - - //! returns a new matrix header for the specified row - UMat row(int y) const; - //! returns a new matrix header for the specified column - UMat col(int x) const; - //! ... for the specified row span - UMat rowRange(int startrow, int endrow) const; - UMat rowRange(const Range& r) const; - //! ... for the specified column span - UMat colRange(int startcol, int endcol) const; - UMat colRange(const Range& r) const; - //! ... for the specified diagonal - //! (d=0 - the main diagonal, - //! >0 - a diagonal from the upper half, - //! <0 - a diagonal from the lower half) - UMat diag(int d=0) const; - //! constructs a square diagonal matrix which main diagonal is vector "d" - CV_NODISCARD_STD static UMat diag(const UMat& d, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); - CV_NODISCARD_STD static UMat diag(const UMat& d) { return diag(d, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload - - //! returns deep copy of the matrix, i.e. the data is copied - CV_NODISCARD_STD UMat clone() const; - //! copies the matrix content to "m". - // It calls m.create(this->size(), this->type()). - void copyTo( OutputArray m ) const; - //! copies those matrix elements to "m" that are marked with non-zero mask elements. - void copyTo( OutputArray m, InputArray mask ) const; - //! converts matrix to another datatype with optional scaling. See cvConvertScale. - void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const; - - void assignTo( UMat& m, int type=-1 ) const; - - //! sets every matrix element to s - UMat& operator = (const Scalar& s); - //! sets some of the matrix elements to s, according to the mask - UMat& setTo(InputArray value, InputArray mask=noArray()); - //! creates alternative matrix header for the same data, with different - // number of channels and/or different number of rows. see cvReshape. - UMat reshape(int cn, int rows=0) const; - UMat reshape(int cn, int newndims, const int* newsz) const; - - //! matrix transposition by means of matrix expressions - UMat t() const; - //! matrix inversion by means of matrix expressions - UMat inv(int method=DECOMP_LU) const; - //! per-element matrix multiplication by means of matrix expressions - UMat mul(InputArray m, double scale=1) const; - - //! computes dot-product - double dot(InputArray m) const; - - //! Matlab-style matrix initialization - CV_NODISCARD_STD static UMat zeros(int rows, int cols, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); - CV_NODISCARD_STD static UMat zeros(Size size, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); - CV_NODISCARD_STD static UMat zeros(int ndims, const int* sz, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); - CV_NODISCARD_STD static UMat zeros(int rows, int cols, int type) { return zeros(rows, cols, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload - CV_NODISCARD_STD static UMat zeros(Size size, int type) { return zeros(size, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload - CV_NODISCARD_STD static UMat zeros(int ndims, const int* sz, int type) { return zeros(ndims, sz, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload - CV_NODISCARD_STD static UMat ones(int rows, int cols, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); - CV_NODISCARD_STD static UMat ones(Size size, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); - CV_NODISCARD_STD static UMat ones(int ndims, const int* sz, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); - CV_NODISCARD_STD static UMat ones(int rows, int cols, int type) { return ones(rows, cols, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload - CV_NODISCARD_STD static UMat ones(Size size, int type) { return ones(size, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload - CV_NODISCARD_STD static UMat ones(int ndims, const int* sz, int type) { return ones(ndims, sz, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload - CV_NODISCARD_STD static UMat eye(int rows, int cols, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); - CV_NODISCARD_STD static UMat eye(Size size, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); - CV_NODISCARD_STD static UMat eye(int rows, int cols, int type) { return eye(rows, cols, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload - CV_NODISCARD_STD static UMat eye(Size size, int type) { return eye(size, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload - - //! allocates new matrix data unless the matrix already has specified size and type. - // previous data is unreferenced if needed. - void create(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); - void create(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); - void create(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); - void create(const std::vector& sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); - - //! increases the reference counter; use with care to avoid memleaks - void addref(); - //! decreases reference counter; - // deallocates the data when reference counter reaches 0. - void release(); - - //! deallocates the matrix data - void deallocate(); - //! internal use function; properly re-allocates _size, _step arrays - void copySize(const UMat& m); - - //! locates matrix header within a parent matrix. See below - void locateROI( Size& wholeSize, Point& ofs ) const; - //! moves/resizes the current matrix ROI inside the parent matrix. - UMat& adjustROI( int dtop, int dbottom, int dleft, int dright ); - //! extracts a rectangular sub-matrix - // (this is a generalized form of row, rowRange etc.) - UMat operator()( Range rowRange, Range colRange ) const; - UMat operator()( const Rect& roi ) const; - UMat operator()( const Range* ranges ) const; - UMat operator()(const std::vector& ranges) const; - - //! returns true iff the matrix data is continuous - // (i.e. when there are no gaps between successive rows). - // similar to CV_IS_MAT_CONT(cvmat->type) - bool isContinuous() const; - - //! returns true if the matrix is a submatrix of another matrix - bool isSubmatrix() const; - - //! returns element size in bytes, - // similar to CV_ELEM_SIZE(cvmat->type) - size_t elemSize() const; - //! returns the size of element channel in bytes. - size_t elemSize1() const; - //! returns element type, similar to CV_MAT_TYPE(cvmat->type) - int type() const; - //! returns element type, similar to CV_MAT_DEPTH(cvmat->type) - int depth() const; - //! returns element type, similar to CV_MAT_CN(cvmat->type) - int channels() const; - //! returns step/elemSize1() - size_t step1(int i=0) const; - //! returns true if matrix data is NULL - bool empty() const; - //! returns the total number of matrix elements - size_t total() const; - - //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise - int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const; - - UMat(UMat&& m); - UMat& operator = (UMat&& m); - - /*! Returns the OpenCL buffer handle on which UMat operates on. - The UMat instance should be kept alive during the use of the handle to prevent the buffer to be - returned to the OpenCV buffer pool. - */ - void* handle(AccessFlag accessFlags) const; - void ndoffset(size_t* ofs) const; - - enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG }; - enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 }; - - /*! includes several bit-fields: - - the magic signature - - continuity flag - - depth - - number of channels - */ - int flags; - - //! the matrix dimensionality, >= 2 - int dims; - - //! number of rows in the matrix; -1 when the matrix has more than 2 dimensions - int rows; - - //! number of columns in the matrix; -1 when the matrix has more than 2 dimensions - int cols; - - //! custom allocator - MatAllocator* allocator; - - //! usage flags for allocator; recommend do not set directly, instead set during construct/create/getUMat - UMatUsageFlags usageFlags; - - //! and the standard allocator - static MatAllocator* getStdAllocator(); - - //! internal use method: updates the continuity flag - void updateContinuityFlag(); - - //! black-box container of UMat data - UMatData* u; - - //! offset of the submatrix (or 0) - size_t offset; - - //! dimensional size of the matrix; accessible in various formats - MatSize size; - - //! number of bytes each matrix element/row/plane/dimension occupies - MatStep step; - -protected: -}; - - -/////////////////////////// multi-dimensional sparse matrix ////////////////////////// - -/** @brief The class SparseMat represents multi-dimensional sparse numerical arrays. - -Such a sparse array can store elements of any type that Mat can store. *Sparse* means that only -non-zero elements are stored (though, as a result of operations on a sparse matrix, some of its -stored elements can actually become 0. It is up to you to detect such elements and delete them -using SparseMat::erase ). The non-zero elements are stored in a hash table that grows when it is -filled so that the search time is O(1) in average (regardless of whether element is there or not). -Elements can be accessed using the following methods: -- Query operations (SparseMat::ptr and the higher-level SparseMat::ref, SparseMat::value and - SparseMat::find), for example: - @code - const int dims = 5; - int size[5] = {10, 10, 10, 10, 10}; - SparseMat sparse_mat(dims, size, CV_32F); - for(int i = 0; i < 1000; i++) - { - int idx[dims]; - for(int k = 0; k < dims; k++) - idx[k] = rand() % size[k]; - sparse_mat.ref(idx) += 1.f; - } - cout << "nnz = " << sparse_mat.nzcount() << endl; - @endcode -- Sparse matrix iterators. They are similar to MatIterator but different from NAryMatIterator. - That is, the iteration loop is familiar to STL users: - @code - // prints elements of a sparse floating-point matrix - // and the sum of elements. - SparseMatConstIterator_ - it = sparse_mat.begin(), - it_end = sparse_mat.end(); - double s = 0; - int dims = sparse_mat.dims(); - for(; it != it_end; ++it) - { - // print element indices and the element value - const SparseMat::Node* n = it.node(); - printf("("); - for(int i = 0; i < dims; i++) - printf("%d%s", n->idx[i], i < dims-1 ? ", " : ")"); - printf(": %g\n", it.value()); - s += *it; - } - printf("Element sum is %g\n", s); - @endcode - If you run this loop, you will notice that elements are not enumerated in a logical order - (lexicographical, and so on). They come in the same order as they are stored in the hash table - (semi-randomly). You may collect pointers to the nodes and sort them to get the proper ordering. - Note, however, that pointers to the nodes may become invalid when you add more elements to the - matrix. This may happen due to possible buffer reallocation. -- Combination of the above 2 methods when you need to process 2 or more sparse matrices - simultaneously. For example, this is how you can compute unnormalized cross-correlation of the 2 - floating-point sparse matrices: - @code - double cross_corr(const SparseMat& a, const SparseMat& b) - { - const SparseMat *_a = &a, *_b = &b; - // if b contains less elements than a, - // it is faster to iterate through b - if(_a->nzcount() > _b->nzcount()) - std::swap(_a, _b); - SparseMatConstIterator_ it = _a->begin(), - it_end = _a->end(); - double ccorr = 0; - for(; it != it_end; ++it) - { - // take the next element from the first matrix - float avalue = *it; - const Node* anode = it.node(); - // and try to find an element with the same index in the second matrix. - // since the hash value depends only on the element index, - // reuse the hash value stored in the node - float bvalue = _b->value(anode->idx,&anode->hashval); - ccorr += avalue*bvalue; - } - return ccorr; - } - @endcode - */ -class CV_EXPORTS SparseMat -{ -public: - typedef SparseMatIterator iterator; - typedef SparseMatConstIterator const_iterator; - - enum { MAGIC_VAL=0x42FD0000, MAX_DIM=32, HASH_SCALE=0x5bd1e995, HASH_BIT=0x80000000 }; - - //! the sparse matrix header - struct CV_EXPORTS Hdr - { - Hdr(int _dims, const int* _sizes, int _type); - void clear(); - int refcount; - int dims; - int valueOffset; - size_t nodeSize; - size_t nodeCount; - size_t freeList; - std::vector pool; - std::vector hashtab; - int size[MAX_DIM]; - }; - - //! sparse matrix node - element of a hash table - struct CV_EXPORTS Node - { - //! hash value - size_t hashval; - //! index of the next node in the same hash table entry - size_t next; - //! index of the matrix element - int idx[MAX_DIM]; - }; - - /** @brief Various SparseMat constructors. - */ - SparseMat(); - - /** @overload - @param dims Array dimensionality. - @param _sizes Sparce matrix size on all dementions. - @param _type Sparse matrix data type. - */ - SparseMat(int dims, const int* _sizes, int _type); - - /** @overload - @param m Source matrix for copy constructor. If m is dense matrix (ocvMat) then it will be converted - to sparse representation. - */ - SparseMat(const SparseMat& m); - - /** @overload - @param m Source matrix for copy constructor. If m is dense matrix (ocvMat) then it will be converted - to sparse representation. - */ - explicit SparseMat(const Mat& m); - - //! the destructor - ~SparseMat(); - - //! assignment operator. This is O(1) operation, i.e. no data is copied - SparseMat& operator = (const SparseMat& m); - //! equivalent to the corresponding constructor - SparseMat& operator = (const Mat& m); - - //! creates full copy of the matrix - CV_NODISCARD_STD SparseMat clone() const; - - //! copies all the data to the destination matrix. All the previous content of m is erased - void copyTo( SparseMat& m ) const; - //! converts sparse matrix to dense matrix. - void copyTo( Mat& m ) const; - //! multiplies all the matrix elements by the specified scale factor alpha and converts the results to the specified data type - void convertTo( SparseMat& m, int rtype, double alpha=1 ) const; - //! converts sparse matrix to dense n-dim matrix with optional type conversion and scaling. - /*! - @param [out] m - output matrix; if it does not have a proper size or type before the operation, - it is reallocated - @param [in] rtype - desired output matrix type or, rather, the depth since the number of channels - are the same as the input has; if rtype is negative, the output matrix will have the - same type as the input. - @param [in] alpha - optional scale factor - @param [in] beta - optional delta added to the scaled values - */ - void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const; - - // not used now - void assignTo( SparseMat& m, int type=-1 ) const; - - //! reallocates sparse matrix. - /*! - If the matrix already had the proper size and type, - it is simply cleared with clear(), otherwise, - the old matrix is released (using release()) and the new one is allocated. - */ - void create(int dims, const int* _sizes, int _type); - //! sets all the sparse matrix elements to 0, which means clearing the hash table. - void clear(); - //! manually increments the reference counter to the header. - void addref(); - // decrements the header reference counter. When the counter reaches 0, the header and all the underlying data are deallocated. - void release(); - - //! converts sparse matrix to the old-style representation; all the elements are copied. - //operator CvSparseMat*() const; - //! returns the size of each element in bytes (not including the overhead - the space occupied by SparseMat::Node elements) - size_t elemSize() const; - //! returns elemSize()/channels() - size_t elemSize1() const; - - //! returns type of sparse matrix elements - int type() const; - //! returns the depth of sparse matrix elements - int depth() const; - //! returns the number of channels - int channels() const; - - //! returns the array of sizes, or NULL if the matrix is not allocated - const int* size() const; - //! returns the size of i-th matrix dimension (or 0) - int size(int i) const; - //! returns the matrix dimensionality - int dims() const; - //! returns the number of non-zero elements (=the number of hash table nodes) - size_t nzcount() const; - - //! computes the element hash value (1D case) - size_t hash(int i0) const; - //! computes the element hash value (2D case) - size_t hash(int i0, int i1) const; - //! computes the element hash value (3D case) - size_t hash(int i0, int i1, int i2) const; - //! computes the element hash value (nD case) - size_t hash(const int* idx) const; - - //!@{ - /*! - specialized variants for 1D, 2D, 3D cases and the generic_type one for n-D case. - return pointer to the matrix element. - - if the element is there (it's non-zero), the pointer to it is returned - - if it's not there and createMissing=false, NULL pointer is returned - - if it's not there and createMissing=true, then the new element - is created and initialized with 0. Pointer to it is returned - - if the optional hashval pointer is not NULL, the element hash value is - not computed, but *hashval is taken instead. - */ - //! returns pointer to the specified element (1D case) - uchar* ptr(int i0, bool createMissing, size_t* hashval=0); - //! returns pointer to the specified element (2D case) - uchar* ptr(int i0, int i1, bool createMissing, size_t* hashval=0); - //! returns pointer to the specified element (3D case) - uchar* ptr(int i0, int i1, int i2, bool createMissing, size_t* hashval=0); - //! returns pointer to the specified element (nD case) - uchar* ptr(const int* idx, bool createMissing, size_t* hashval=0); - //!@} - - //!@{ - /*! - return read-write reference to the specified sparse matrix element. - - `ref<_Tp>(i0,...[,hashval])` is equivalent to `*(_Tp*)ptr(i0,...,true[,hashval])`. - The methods always return a valid reference. - If the element did not exist, it is created and initialized with 0. - */ - //! returns reference to the specified element (1D case) - template _Tp& ref(int i0, size_t* hashval=0); - //! returns reference to the specified element (2D case) - template _Tp& ref(int i0, int i1, size_t* hashval=0); - //! returns reference to the specified element (3D case) - template _Tp& ref(int i0, int i1, int i2, size_t* hashval=0); - //! returns reference to the specified element (nD case) - template _Tp& ref(const int* idx, size_t* hashval=0); - //!@} - - //!@{ - /*! - return value of the specified sparse matrix element. - - `value<_Tp>(i0,...[,hashval])` is equivalent to - @code - { const _Tp* p = find<_Tp>(i0,...[,hashval]); return p ? *p : _Tp(); } - @endcode - - That is, if the element did not exist, the methods return 0. - */ - //! returns value of the specified element (1D case) - template _Tp value(int i0, size_t* hashval=0) const; - //! returns value of the specified element (2D case) - template _Tp value(int i0, int i1, size_t* hashval=0) const; - //! returns value of the specified element (3D case) - template _Tp value(int i0, int i1, int i2, size_t* hashval=0) const; - //! returns value of the specified element (nD case) - template _Tp value(const int* idx, size_t* hashval=0) const; - //!@} - - //!@{ - /*! - Return pointer to the specified sparse matrix element if it exists - - `find<_Tp>(i0,...[,hashval])` is equivalent to `(_const Tp*)ptr(i0,...false[,hashval])`. - - If the specified element does not exist, the methods return NULL. - */ - //! returns pointer to the specified element (1D case) - template const _Tp* find(int i0, size_t* hashval=0) const; - //! returns pointer to the specified element (2D case) - template const _Tp* find(int i0, int i1, size_t* hashval=0) const; - //! returns pointer to the specified element (3D case) - template const _Tp* find(int i0, int i1, int i2, size_t* hashval=0) const; - //! returns pointer to the specified element (nD case) - template const _Tp* find(const int* idx, size_t* hashval=0) const; - //!@} - - //! erases the specified element (2D case) - void erase(int i0, int i1, size_t* hashval=0); - //! erases the specified element (3D case) - void erase(int i0, int i1, int i2, size_t* hashval=0); - //! erases the specified element (nD case) - void erase(const int* idx, size_t* hashval=0); - - //!@{ - /*! - return the sparse matrix iterator pointing to the first sparse matrix element - */ - //! returns the sparse matrix iterator at the matrix beginning - SparseMatIterator begin(); - //! returns the sparse matrix iterator at the matrix beginning - template SparseMatIterator_<_Tp> begin(); - //! returns the read-only sparse matrix iterator at the matrix beginning - SparseMatConstIterator begin() const; - //! returns the read-only sparse matrix iterator at the matrix beginning - template SparseMatConstIterator_<_Tp> begin() const; - //!@} - /*! - return the sparse matrix iterator pointing to the element following the last sparse matrix element - */ - //! returns the sparse matrix iterator at the matrix end - SparseMatIterator end(); - //! returns the read-only sparse matrix iterator at the matrix end - SparseMatConstIterator end() const; - //! returns the typed sparse matrix iterator at the matrix end - template SparseMatIterator_<_Tp> end(); - //! returns the typed read-only sparse matrix iterator at the matrix end - template SparseMatConstIterator_<_Tp> end() const; - - //! returns the value stored in the sparse martix node - template _Tp& value(Node* n); - //! returns the value stored in the sparse martix node - template const _Tp& value(const Node* n) const; - - ////////////// some internal-use methods /////////////// - Node* node(size_t nidx); - const Node* node(size_t nidx) const; - - uchar* newNode(const int* idx, size_t hashval); - void removeNode(size_t hidx, size_t nidx, size_t previdx); - void resizeHashTab(size_t newsize); - - int flags; - Hdr* hdr; -}; - - - -///////////////////////////////// SparseMat_<_Tp> //////////////////////////////////// - -/** @brief Template sparse n-dimensional array class derived from SparseMat - -SparseMat_ is a thin wrapper on top of SparseMat created in the same way as Mat_ . It simplifies -notation of some operations: -@code - int sz[] = {10, 20, 30}; - SparseMat_ M(3, sz); - ... - M.ref(1, 2, 3) = M(4, 5, 6) + M(7, 8, 9); -@endcode - */ -template class SparseMat_ : public SparseMat -{ -public: - typedef SparseMatIterator_<_Tp> iterator; - typedef SparseMatConstIterator_<_Tp> const_iterator; - - //! the default constructor - SparseMat_(); - //! the full constructor equivalent to SparseMat(dims, _sizes, DataType<_Tp>::type) - SparseMat_(int dims, const int* _sizes); - //! the copy constructor. If DataType<_Tp>.type != m.type(), the m elements are converted - SparseMat_(const SparseMat& m); - //! the copy constructor. This is O(1) operation - no data is copied - SparseMat_(const SparseMat_& m); - //! converts dense matrix to the sparse form - SparseMat_(const Mat& m); - //! converts the old-style sparse matrix to the C++ class. All the elements are copied - //SparseMat_(const CvSparseMat* m); - //! the assignment operator. If DataType<_Tp>.type != m.type(), the m elements are converted - SparseMat_& operator = (const SparseMat& m); - //! the assignment operator. This is O(1) operation - no data is copied - SparseMat_& operator = (const SparseMat_& m); - //! converts dense matrix to the sparse form - SparseMat_& operator = (const Mat& m); - - //! makes full copy of the matrix. All the elements are duplicated - CV_NODISCARD_STD SparseMat_ clone() const; - //! equivalent to cv::SparseMat::create(dims, _sizes, DataType<_Tp>::type) - void create(int dims, const int* _sizes); - //! converts sparse matrix to the old-style CvSparseMat. All the elements are copied - //operator CvSparseMat*() const; - - //! returns type of the matrix elements - int type() const; - //! returns depth of the matrix elements - int depth() const; - //! returns the number of channels in each matrix element - int channels() const; - - //! equivalent to SparseMat::ref<_Tp>(i0, hashval) - _Tp& ref(int i0, size_t* hashval=0); - //! equivalent to SparseMat::ref<_Tp>(i0, i1, hashval) - _Tp& ref(int i0, int i1, size_t* hashval=0); - //! equivalent to SparseMat::ref<_Tp>(i0, i1, i2, hashval) - _Tp& ref(int i0, int i1, int i2, size_t* hashval=0); - //! equivalent to SparseMat::ref<_Tp>(idx, hashval) - _Tp& ref(const int* idx, size_t* hashval=0); - - //! equivalent to SparseMat::value<_Tp>(i0, hashval) - _Tp operator()(int i0, size_t* hashval=0) const; - //! equivalent to SparseMat::value<_Tp>(i0, i1, hashval) - _Tp operator()(int i0, int i1, size_t* hashval=0) const; - //! equivalent to SparseMat::value<_Tp>(i0, i1, i2, hashval) - _Tp operator()(int i0, int i1, int i2, size_t* hashval=0) const; - //! equivalent to SparseMat::value<_Tp>(idx, hashval) - _Tp operator()(const int* idx, size_t* hashval=0) const; - - //! returns sparse matrix iterator pointing to the first sparse matrix element - SparseMatIterator_<_Tp> begin(); - //! returns read-only sparse matrix iterator pointing to the first sparse matrix element - SparseMatConstIterator_<_Tp> begin() const; - //! returns sparse matrix iterator pointing to the element following the last sparse matrix element - SparseMatIterator_<_Tp> end(); - //! returns read-only sparse matrix iterator pointing to the element following the last sparse matrix element - SparseMatConstIterator_<_Tp> end() const; -}; - - - -////////////////////////////////// MatConstIterator ////////////////////////////////// - -class CV_EXPORTS MatConstIterator -{ -public: - typedef uchar* value_type; - typedef ptrdiff_t difference_type; - typedef const uchar** pointer; - typedef uchar* reference; - - typedef std::random_access_iterator_tag iterator_category; - - //! default constructor - MatConstIterator(); - //! constructor that sets the iterator to the beginning of the matrix - MatConstIterator(const Mat* _m); - //! constructor that sets the iterator to the specified element of the matrix - MatConstIterator(const Mat* _m, int _row, int _col=0); - //! constructor that sets the iterator to the specified element of the matrix - MatConstIterator(const Mat* _m, Point _pt); - //! constructor that sets the iterator to the specified element of the matrix - MatConstIterator(const Mat* _m, const int* _idx); - //! copy constructor - MatConstIterator(const MatConstIterator& it); - - //! copy operator - MatConstIterator& operator = (const MatConstIterator& it); - //! returns the current matrix element - const uchar* operator *() const; - //! returns the i-th matrix element, relative to the current - const uchar* operator [](ptrdiff_t i) const; - - //! shifts the iterator forward by the specified number of elements - MatConstIterator& operator += (ptrdiff_t ofs); - //! shifts the iterator backward by the specified number of elements - MatConstIterator& operator -= (ptrdiff_t ofs); - //! decrements the iterator - MatConstIterator& operator --(); - //! decrements the iterator - MatConstIterator operator --(int); - //! increments the iterator - MatConstIterator& operator ++(); - //! increments the iterator - MatConstIterator operator ++(int); - //! returns the current iterator position - Point pos() const; - //! returns the current iterator position - void pos(int* _idx) const; - - ptrdiff_t lpos() const; - void seek(ptrdiff_t ofs, bool relative = false); - void seek(const int* _idx, bool relative = false); - - const Mat* m; - size_t elemSize; - const uchar* ptr; - const uchar* sliceStart; - const uchar* sliceEnd; -}; - - - -////////////////////////////////// MatConstIterator_ ///////////////////////////////// - -/** @brief Matrix read-only iterator - */ -template -class MatConstIterator_ : public MatConstIterator -{ -public: - typedef _Tp value_type; - typedef ptrdiff_t difference_type; - typedef const _Tp* pointer; - typedef const _Tp& reference; - - typedef std::random_access_iterator_tag iterator_category; - - //! default constructor - MatConstIterator_(); - //! constructor that sets the iterator to the beginning of the matrix - MatConstIterator_(const Mat_<_Tp>* _m); - //! constructor that sets the iterator to the specified element of the matrix - MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col=0); - //! constructor that sets the iterator to the specified element of the matrix - MatConstIterator_(const Mat_<_Tp>* _m, Point _pt); - //! constructor that sets the iterator to the specified element of the matrix - MatConstIterator_(const Mat_<_Tp>* _m, const int* _idx); - //! copy constructor - MatConstIterator_(const MatConstIterator_& it); - - //! copy operator - MatConstIterator_& operator = (const MatConstIterator_& it); - //! returns the current matrix element - const _Tp& operator *() const; - //! returns the i-th matrix element, relative to the current - const _Tp& operator [](ptrdiff_t i) const; - - //! shifts the iterator forward by the specified number of elements - MatConstIterator_& operator += (ptrdiff_t ofs); - //! shifts the iterator backward by the specified number of elements - MatConstIterator_& operator -= (ptrdiff_t ofs); - //! decrements the iterator - MatConstIterator_& operator --(); - //! decrements the iterator - MatConstIterator_ operator --(int); - //! increments the iterator - MatConstIterator_& operator ++(); - //! increments the iterator - MatConstIterator_ operator ++(int); - //! returns the current iterator position - Point pos() const; -}; - - - -//////////////////////////////////// MatIterator_ //////////////////////////////////// - -/** @brief Matrix read-write iterator -*/ -template -class MatIterator_ : public MatConstIterator_<_Tp> -{ -public: - typedef _Tp* pointer; - typedef _Tp& reference; - - typedef std::random_access_iterator_tag iterator_category; - - //! the default constructor - MatIterator_(); - //! constructor that sets the iterator to the beginning of the matrix - MatIterator_(Mat_<_Tp>* _m); - //! constructor that sets the iterator to the specified element of the matrix - MatIterator_(Mat_<_Tp>* _m, int _row, int _col=0); - //! constructor that sets the iterator to the specified element of the matrix - MatIterator_(Mat_<_Tp>* _m, Point _pt); - //! constructor that sets the iterator to the specified element of the matrix - MatIterator_(Mat_<_Tp>* _m, const int* _idx); - //! copy constructor - MatIterator_(const MatIterator_& it); - //! copy operator - MatIterator_& operator = (const MatIterator_<_Tp>& it ); - - //! returns the current matrix element - _Tp& operator *() const; - //! returns the i-th matrix element, relative to the current - _Tp& operator [](ptrdiff_t i) const; - - //! shifts the iterator forward by the specified number of elements - MatIterator_& operator += (ptrdiff_t ofs); - //! shifts the iterator backward by the specified number of elements - MatIterator_& operator -= (ptrdiff_t ofs); - //! decrements the iterator - MatIterator_& operator --(); - //! decrements the iterator - MatIterator_ operator --(int); - //! increments the iterator - MatIterator_& operator ++(); - //! increments the iterator - MatIterator_ operator ++(int); -}; - - - -/////////////////////////////// SparseMatConstIterator /////////////////////////////// - -/** @brief Read-Only Sparse Matrix Iterator. - - Here is how to use the iterator to compute the sum of floating-point sparse matrix elements: - - \code - SparseMatConstIterator it = m.begin(), it_end = m.end(); - double s = 0; - CV_Assert( m.type() == CV_32F ); - for( ; it != it_end; ++it ) - s += it.value(); - \endcode -*/ -class CV_EXPORTS SparseMatConstIterator -{ -public: - //! the default constructor - SparseMatConstIterator(); - //! the full constructor setting the iterator to the first sparse matrix element - SparseMatConstIterator(const SparseMat* _m); - //! the copy constructor - SparseMatConstIterator(const SparseMatConstIterator& it); - - //! the assignment operator - SparseMatConstIterator& operator = (const SparseMatConstIterator& it); - - //! template method returning the current matrix element - template const _Tp& value() const; - //! returns the current node of the sparse matrix. it.node->idx is the current element index - const SparseMat::Node* node() const; - - //! moves iterator to the previous element - SparseMatConstIterator& operator --(); - //! moves iterator to the previous element - SparseMatConstIterator operator --(int); - //! moves iterator to the next element - SparseMatConstIterator& operator ++(); - //! moves iterator to the next element - SparseMatConstIterator operator ++(int); - - //! moves iterator to the element after the last element - void seekEnd(); - - const SparseMat* m; - size_t hashidx; - uchar* ptr; -}; - - - -////////////////////////////////// SparseMatIterator ///////////////////////////////// - -/** @brief Read-write Sparse Matrix Iterator - - The class is similar to cv::SparseMatConstIterator, - but can be used for in-place modification of the matrix elements. -*/ -class CV_EXPORTS SparseMatIterator : public SparseMatConstIterator -{ -public: - //! the default constructor - SparseMatIterator(); - //! the full constructor setting the iterator to the first sparse matrix element - SparseMatIterator(SparseMat* _m); - //! the full constructor setting the iterator to the specified sparse matrix element - SparseMatIterator(SparseMat* _m, const int* idx); - //! the copy constructor - SparseMatIterator(const SparseMatIterator& it); - - //! the assignment operator - SparseMatIterator& operator = (const SparseMatIterator& it); - //! returns read-write reference to the current sparse matrix element - template _Tp& value() const; - //! returns pointer to the current sparse matrix node. it.node->idx is the index of the current element (do not modify it!) - SparseMat::Node* node() const; - - //! moves iterator to the next element - SparseMatIterator& operator ++(); - //! moves iterator to the next element - SparseMatIterator operator ++(int); -}; - - - -/////////////////////////////// SparseMatConstIterator_ ////////////////////////////// - -/** @brief Template Read-Only Sparse Matrix Iterator Class. - - This is the derived from SparseMatConstIterator class that - introduces more convenient operator *() for accessing the current element. -*/ -template class SparseMatConstIterator_ : public SparseMatConstIterator -{ -public: - - typedef std::forward_iterator_tag iterator_category; - - //! the default constructor - SparseMatConstIterator_(); - //! the full constructor setting the iterator to the first sparse matrix element - SparseMatConstIterator_(const SparseMat_<_Tp>* _m); - SparseMatConstIterator_(const SparseMat* _m); - //! the copy constructor - SparseMatConstIterator_(const SparseMatConstIterator_& it); - - //! the assignment operator - SparseMatConstIterator_& operator = (const SparseMatConstIterator_& it); - //! the element access operator - const _Tp& operator *() const; - - //! moves iterator to the next element - SparseMatConstIterator_& operator ++(); - //! moves iterator to the next element - SparseMatConstIterator_ operator ++(int); -}; - - - -///////////////////////////////// SparseMatIterator_ ///////////////////////////////// - -/** @brief Template Read-Write Sparse Matrix Iterator Class. - - This is the derived from cv::SparseMatConstIterator_ class that - introduces more convenient operator *() for accessing the current element. -*/ -template class SparseMatIterator_ : public SparseMatConstIterator_<_Tp> -{ -public: - - typedef std::forward_iterator_tag iterator_category; - - //! the default constructor - SparseMatIterator_(); - //! the full constructor setting the iterator to the first sparse matrix element - SparseMatIterator_(SparseMat_<_Tp>* _m); - SparseMatIterator_(SparseMat* _m); - //! the copy constructor - SparseMatIterator_(const SparseMatIterator_& it); - - //! the assignment operator - SparseMatIterator_& operator = (const SparseMatIterator_& it); - //! returns the reference to the current element - _Tp& operator *() const; - - //! moves the iterator to the next element - SparseMatIterator_& operator ++(); - //! moves the iterator to the next element - SparseMatIterator_ operator ++(int); -}; - - - -/////////////////////////////////// NAryMatIterator ////////////////////////////////// - -/** @brief n-ary multi-dimensional array iterator. - -Use the class to implement unary, binary, and, generally, n-ary element-wise operations on -multi-dimensional arrays. Some of the arguments of an n-ary function may be continuous arrays, some -may be not. It is possible to use conventional MatIterator 's for each array but incrementing all of -the iterators after each small operations may be a big overhead. In this case consider using -NAryMatIterator to iterate through several matrices simultaneously as long as they have the same -geometry (dimensionality and all the dimension sizes are the same). On each iteration `it.planes[0]`, -`it.planes[1]`,... will be the slices of the corresponding matrices. - -The example below illustrates how you can compute a normalized and threshold 3D color histogram: -@code - void computeNormalizedColorHist(const Mat& image, Mat& hist, int N, double minProb) - { - const int histSize[] = {N, N, N}; - - // make sure that the histogram has a proper size and type - hist.create(3, histSize, CV_32F); - - // and clear it - hist = Scalar(0); - - // the loop below assumes that the image - // is a 8-bit 3-channel. check it. - CV_Assert(image.type() == CV_8UC3); - MatConstIterator_ it = image.begin(), - it_end = image.end(); - for( ; it != it_end; ++it ) - { - const Vec3b& pix = *it; - hist.at(pix[0]*N/256, pix[1]*N/256, pix[2]*N/256) += 1.f; - } - - minProb *= image.rows*image.cols; - - // initialize iterator (the style is different from STL). - // after initialization the iterator will contain - // the number of slices or planes the iterator will go through. - // it simultaneously increments iterators for several matrices - // supplied as a null terminated list of pointers - const Mat* arrays[] = {&hist, 0}; - Mat planes[1]; - NAryMatIterator itNAry(arrays, planes, 1); - double s = 0; - // iterate through the matrix. on each iteration - // itNAry.planes[i] (of type Mat) will be set to the current plane - // of the i-th n-dim matrix passed to the iterator constructor. - for(int p = 0; p < itNAry.nplanes; p++, ++itNAry) - { - threshold(itNAry.planes[0], itNAry.planes[0], minProb, 0, THRESH_TOZERO); - s += sum(itNAry.planes[0])[0]; - } - - s = 1./s; - itNAry = NAryMatIterator(arrays, planes, 1); - for(int p = 0; p < itNAry.nplanes; p++, ++itNAry) - itNAry.planes[0] *= s; - } -@endcode - */ -class CV_EXPORTS NAryMatIterator -{ -public: - //! the default constructor - NAryMatIterator(); - //! the full constructor taking arbitrary number of n-dim matrices - NAryMatIterator(const Mat** arrays, uchar** ptrs, int narrays=-1); - //! the full constructor taking arbitrary number of n-dim matrices - NAryMatIterator(const Mat** arrays, Mat* planes, int narrays=-1); - //! the separate iterator initialization method - void init(const Mat** arrays, Mat* planes, uchar** ptrs, int narrays=-1); - - //! proceeds to the next plane of every iterated matrix - NAryMatIterator& operator ++(); - //! proceeds to the next plane of every iterated matrix (postfix increment operator) - NAryMatIterator operator ++(int); - - //! the iterated arrays - const Mat** arrays; - //! the current planes - Mat* planes; - //! data pointers - uchar** ptrs; - //! the number of arrays - int narrays; - //! the number of hyper-planes that the iterator steps through - size_t nplanes; - //! the size of each segment (in elements) - size_t size; -protected: - int iterdepth; - size_t idx; -}; - - - -///////////////////////////////// Matrix Expressions ///////////////////////////////// - -class CV_EXPORTS MatOp -{ -public: - MatOp(); - virtual ~MatOp(); - - virtual bool elementWise(const MatExpr& expr) const; - virtual void assign(const MatExpr& expr, Mat& m, int type=-1) const = 0; - virtual void roi(const MatExpr& expr, const Range& rowRange, - const Range& colRange, MatExpr& res) const; - virtual void diag(const MatExpr& expr, int d, MatExpr& res) const; - virtual void augAssignAdd(const MatExpr& expr, Mat& m) const; - virtual void augAssignSubtract(const MatExpr& expr, Mat& m) const; - virtual void augAssignMultiply(const MatExpr& expr, Mat& m) const; - virtual void augAssignDivide(const MatExpr& expr, Mat& m) const; - virtual void augAssignAnd(const MatExpr& expr, Mat& m) const; - virtual void augAssignOr(const MatExpr& expr, Mat& m) const; - virtual void augAssignXor(const MatExpr& expr, Mat& m) const; - - virtual void add(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const; - virtual void add(const MatExpr& expr1, const Scalar& s, MatExpr& res) const; - - virtual void subtract(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const; - virtual void subtract(const Scalar& s, const MatExpr& expr, MatExpr& res) const; - - virtual void multiply(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const; - virtual void multiply(const MatExpr& expr1, double s, MatExpr& res) const; - - virtual void divide(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const; - virtual void divide(double s, const MatExpr& expr, MatExpr& res) const; - - virtual void abs(const MatExpr& expr, MatExpr& res) const; - - virtual void transpose(const MatExpr& expr, MatExpr& res) const; - virtual void matmul(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const; - virtual void invert(const MatExpr& expr, int method, MatExpr& res) const; - - virtual Size size(const MatExpr& expr) const; - virtual int type(const MatExpr& expr) const; -}; - -/** @brief Matrix expression representation -@anchor MatrixExpressions -This is a list of implemented matrix operations that can be combined in arbitrary complex -expressions (here A, B stand for matrices ( Mat ), s for a scalar ( Scalar ), alpha for a -real-valued scalar ( double )): -- Addition, subtraction, negation: `A+B`, `A-B`, `A+s`, `A-s`, `s+A`, `s-A`, `-A` -- Scaling: `A*alpha` -- Per-element multiplication and division: `A.mul(B)`, `A/B`, `alpha/A` -- Matrix multiplication: `A*B` -- Transposition: `A.t()` (means AT) -- Matrix inversion and pseudo-inversion, solving linear systems and least-squares problems: - `A.inv([method]) (~ A-1)`, `A.inv([method])*B (~ X: AX=B)` -- Comparison: `A cmpop B`, `A cmpop alpha`, `alpha cmpop A`, where *cmpop* is one of - `>`, `>=`, `==`, `!=`, `<=`, `<`. The result of comparison is an 8-bit single channel mask whose - elements are set to 255 (if the particular element or pair of elements satisfy the condition) or - 0. -- Bitwise logical operations: `A logicop B`, `A logicop s`, `s logicop A`, `~A`, where *logicop* is one of - `&`, `|`, `^`. -- Element-wise minimum and maximum: `min(A, B)`, `min(A, alpha)`, `max(A, B)`, `max(A, alpha)` -- Element-wise absolute value: `abs(A)` -- Cross-product, dot-product: `A.cross(B)`, `A.dot(B)` -- Any function of matrix or matrices and scalars that returns a matrix or a scalar, such as norm, - mean, sum, countNonZero, trace, determinant, repeat, and others. -- Matrix initializers ( Mat::eye(), Mat::zeros(), Mat::ones() ), matrix comma-separated - initializers, matrix constructors and operators that extract sub-matrices (see Mat description). -- Mat_() constructors to cast the result to the proper type. -@note Comma-separated initializers and probably some other operations may require additional -explicit Mat() or Mat_() constructor calls to resolve a possible ambiguity. - -Here are examples of matrix expressions: -@code - // compute pseudo-inverse of A, equivalent to A.inv(DECOMP_SVD) - SVD svd(A); - Mat pinvA = svd.vt.t()*Mat::diag(1./svd.w)*svd.u.t(); - - // compute the new vector of parameters in the Levenberg-Marquardt algorithm - x -= (A.t()*A + lambda*Mat::eye(A.cols,A.cols,A.type())).inv(DECOMP_CHOLESKY)*(A.t()*err); - - // sharpen image using "unsharp mask" algorithm - Mat blurred; double sigma = 1, threshold = 5, amount = 1; - GaussianBlur(img, blurred, Size(), sigma, sigma); - Mat lowContrastMask = abs(img - blurred) < threshold; - Mat sharpened = img*(1+amount) + blurred*(-amount); - img.copyTo(sharpened, lowContrastMask); -@endcode -*/ -class CV_EXPORTS MatExpr -{ -public: - MatExpr(); - explicit MatExpr(const Mat& m); - - MatExpr(const MatOp* _op, int _flags, const Mat& _a = Mat(), const Mat& _b = Mat(), - const Mat& _c = Mat(), double _alpha = 1, double _beta = 1, const Scalar& _s = Scalar()); - - operator Mat() const; - template operator Mat_<_Tp>() const; - - Size size() const; - int type() const; - - MatExpr row(int y) const; - MatExpr col(int x) const; - MatExpr diag(int d = 0) const; - MatExpr operator()( const Range& rowRange, const Range& colRange ) const; - MatExpr operator()( const Rect& roi ) const; - - MatExpr t() const; - MatExpr inv(int method = DECOMP_LU) const; - MatExpr mul(const MatExpr& e, double scale=1) const; - MatExpr mul(const Mat& m, double scale=1) const; - - Mat cross(const Mat& m) const; - double dot(const Mat& m) const; - - void swap(MatExpr& b); - - const MatOp* op; - int flags; - - Mat a, b, c; - double alpha, beta; - Scalar s; -}; - -//! @} core_basic - -//! @relates cv::MatExpr -//! @{ -CV_EXPORTS MatExpr operator + (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator + (const Mat& a, const Scalar& s); -CV_EXPORTS MatExpr operator + (const Scalar& s, const Mat& a); -CV_EXPORTS MatExpr operator + (const MatExpr& e, const Mat& m); -CV_EXPORTS MatExpr operator + (const Mat& m, const MatExpr& e); -CV_EXPORTS MatExpr operator + (const MatExpr& e, const Scalar& s); -CV_EXPORTS MatExpr operator + (const Scalar& s, const MatExpr& e); -CV_EXPORTS MatExpr operator + (const MatExpr& e1, const MatExpr& e2); -template static inline -MatExpr operator + (const Mat& a, const Matx<_Tp, m, n>& b) { return a + Mat(b); } -template static inline -MatExpr operator + (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) + b; } - -CV_EXPORTS MatExpr operator - (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator - (const Mat& a, const Scalar& s); -CV_EXPORTS MatExpr operator - (const Scalar& s, const Mat& a); -CV_EXPORTS MatExpr operator - (const MatExpr& e, const Mat& m); -CV_EXPORTS MatExpr operator - (const Mat& m, const MatExpr& e); -CV_EXPORTS MatExpr operator - (const MatExpr& e, const Scalar& s); -CV_EXPORTS MatExpr operator - (const Scalar& s, const MatExpr& e); -CV_EXPORTS MatExpr operator - (const MatExpr& e1, const MatExpr& e2); -template static inline -MatExpr operator - (const Mat& a, const Matx<_Tp, m, n>& b) { return a - Mat(b); } -template static inline -MatExpr operator - (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) - b; } - -CV_EXPORTS MatExpr operator - (const Mat& m); -CV_EXPORTS MatExpr operator - (const MatExpr& e); - -CV_EXPORTS MatExpr operator * (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator * (const Mat& a, double s); -CV_EXPORTS MatExpr operator * (double s, const Mat& a); -CV_EXPORTS MatExpr operator * (const MatExpr& e, const Mat& m); -CV_EXPORTS MatExpr operator * (const Mat& m, const MatExpr& e); -CV_EXPORTS MatExpr operator * (const MatExpr& e, double s); -CV_EXPORTS MatExpr operator * (double s, const MatExpr& e); -CV_EXPORTS MatExpr operator * (const MatExpr& e1, const MatExpr& e2); -template static inline -MatExpr operator * (const Mat& a, const Matx<_Tp, m, n>& b) { return a * Mat(b); } -template static inline -MatExpr operator * (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) * b; } - -CV_EXPORTS MatExpr operator / (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator / (const Mat& a, double s); -CV_EXPORTS MatExpr operator / (double s, const Mat& a); -CV_EXPORTS MatExpr operator / (const MatExpr& e, const Mat& m); -CV_EXPORTS MatExpr operator / (const Mat& m, const MatExpr& e); -CV_EXPORTS MatExpr operator / (const MatExpr& e, double s); -CV_EXPORTS MatExpr operator / (double s, const MatExpr& e); -CV_EXPORTS MatExpr operator / (const MatExpr& e1, const MatExpr& e2); -template static inline -MatExpr operator / (const Mat& a, const Matx<_Tp, m, n>& b) { return a / Mat(b); } -template static inline -MatExpr operator / (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) / b; } - -CV_EXPORTS MatExpr operator < (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator < (const Mat& a, double s); -CV_EXPORTS MatExpr operator < (double s, const Mat& a); -template static inline -MatExpr operator < (const Mat& a, const Matx<_Tp, m, n>& b) { return a < Mat(b); } -template static inline -MatExpr operator < (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) < b; } - -CV_EXPORTS MatExpr operator <= (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator <= (const Mat& a, double s); -CV_EXPORTS MatExpr operator <= (double s, const Mat& a); -template static inline -MatExpr operator <= (const Mat& a, const Matx<_Tp, m, n>& b) { return a <= Mat(b); } -template static inline -MatExpr operator <= (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) <= b; } - -CV_EXPORTS MatExpr operator == (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator == (const Mat& a, double s); -CV_EXPORTS MatExpr operator == (double s, const Mat& a); -template static inline -MatExpr operator == (const Mat& a, const Matx<_Tp, m, n>& b) { return a == Mat(b); } -template static inline -MatExpr operator == (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) == b; } - -CV_EXPORTS MatExpr operator != (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator != (const Mat& a, double s); -CV_EXPORTS MatExpr operator != (double s, const Mat& a); -template static inline -MatExpr operator != (const Mat& a, const Matx<_Tp, m, n>& b) { return a != Mat(b); } -template static inline -MatExpr operator != (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) != b; } - -CV_EXPORTS MatExpr operator >= (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator >= (const Mat& a, double s); -CV_EXPORTS MatExpr operator >= (double s, const Mat& a); -template static inline -MatExpr operator >= (const Mat& a, const Matx<_Tp, m, n>& b) { return a >= Mat(b); } -template static inline -MatExpr operator >= (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) >= b; } - -CV_EXPORTS MatExpr operator > (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator > (const Mat& a, double s); -CV_EXPORTS MatExpr operator > (double s, const Mat& a); -template static inline -MatExpr operator > (const Mat& a, const Matx<_Tp, m, n>& b) { return a > Mat(b); } -template static inline -MatExpr operator > (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) > b; } - -CV_EXPORTS MatExpr operator & (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator & (const Mat& a, const Scalar& s); -CV_EXPORTS MatExpr operator & (const Scalar& s, const Mat& a); -template static inline -MatExpr operator & (const Mat& a, const Matx<_Tp, m, n>& b) { return a & Mat(b); } -template static inline -MatExpr operator & (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) & b; } - -CV_EXPORTS MatExpr operator | (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator | (const Mat& a, const Scalar& s); -CV_EXPORTS MatExpr operator | (const Scalar& s, const Mat& a); -template static inline -MatExpr operator | (const Mat& a, const Matx<_Tp, m, n>& b) { return a | Mat(b); } -template static inline -MatExpr operator | (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) | b; } - -CV_EXPORTS MatExpr operator ^ (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator ^ (const Mat& a, const Scalar& s); -CV_EXPORTS MatExpr operator ^ (const Scalar& s, const Mat& a); -template static inline -MatExpr operator ^ (const Mat& a, const Matx<_Tp, m, n>& b) { return a ^ Mat(b); } -template static inline -MatExpr operator ^ (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) ^ b; } - -CV_EXPORTS MatExpr operator ~(const Mat& m); - -CV_EXPORTS MatExpr min(const Mat& a, const Mat& b); -CV_EXPORTS MatExpr min(const Mat& a, double s); -CV_EXPORTS MatExpr min(double s, const Mat& a); -template static inline -MatExpr min (const Mat& a, const Matx<_Tp, m, n>& b) { return min(a, Mat(b)); } -template static inline -MatExpr min (const Matx<_Tp, m, n>& a, const Mat& b) { return min(Mat(a), b); } - -CV_EXPORTS MatExpr max(const Mat& a, const Mat& b); -CV_EXPORTS MatExpr max(const Mat& a, double s); -CV_EXPORTS MatExpr max(double s, const Mat& a); -template static inline -MatExpr max (const Mat& a, const Matx<_Tp, m, n>& b) { return max(a, Mat(b)); } -template static inline -MatExpr max (const Matx<_Tp, m, n>& a, const Mat& b) { return max(Mat(a), b); } - -/** @brief Calculates an absolute value of each matrix element. - -abs is a meta-function that is expanded to one of absdiff or convertScaleAbs forms: -- C = abs(A-B) is equivalent to `absdiff(A, B, C)` -- C = abs(A) is equivalent to `absdiff(A, Scalar::all(0), C)` -- C = `Mat_ >(abs(A*alpha + beta))` is equivalent to `convertScaleAbs(A, C, alpha, -beta)` - -The output matrix has the same size and the same type as the input one except for the last case, -where C is depth=CV_8U . -@param m matrix. -@sa @ref MatrixExpressions, absdiff, convertScaleAbs - */ -CV_EXPORTS MatExpr abs(const Mat& m); -/** @overload -@param e matrix expression. -*/ -CV_EXPORTS MatExpr abs(const MatExpr& e); -//! @} relates cv::MatExpr - -} // cv - -#include "opencv2/core/mat.inl.hpp" - -#endif // OPENCV_CORE_MAT_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CORE_MAT_HPP +#define OPENCV_CORE_MAT_HPP + +#ifndef __cplusplus +# error mat.hpp header must be compiled as C++ +#endif + +#include "opencv2/core/matx.hpp" +#include "opencv2/core/types.hpp" + +#include "opencv2/core/bufferpool.hpp" + +#include +#include + +namespace cv +{ + +//! @addtogroup core_basic +//! @{ + +enum AccessFlag { ACCESS_READ=1<<24, ACCESS_WRITE=1<<25, + ACCESS_RW=3<<24, ACCESS_MASK=ACCESS_RW, ACCESS_FAST=1<<26 }; +CV_ENUM_FLAGS(AccessFlag) +__CV_ENUM_FLAGS_BITWISE_AND(AccessFlag, int, AccessFlag) + +CV__DEBUG_NS_BEGIN + +class CV_EXPORTS _OutputArray; + +//////////////////////// Input/Output Array Arguments ///////////////////////////////// + +/** @brief This is the proxy class for passing read-only input arrays into OpenCV functions. + +It is defined as: +@code + typedef const _InputArray& InputArray; +@endcode +where \ref cv::_InputArray is a class that can be constructed from \ref cv::Mat, \ref cv::Mat_, +\ref cv::Matx, std::vector, std::vector>, std::vector, +std::vector>, \ref cv::UMat, std::vector or `double`. It can also be constructed from +a matrix expression. + +Since this is mostly implementation-level class, and its interface may change in future versions, we +do not describe it in details. There are a few key things, though, that should be kept in mind: + +- When you see in the reference manual or in OpenCV source code a function that takes + InputArray, it means that you can actually pass `Mat`, `Matx`, `vector` etc. (see above the + complete list). +- Optional input arguments: If some of the input arrays may be empty, pass cv::noArray() (or + simply cv::Mat() as you probably did before). +- The class is designed solely for passing parameters. That is, normally you *should not* + declare class members, local and global variables of this type. +- If you want to design your own function or a class method that can operate of arrays of + multiple types, you can use InputArray (or OutputArray) for the respective parameters. Inside + a function you should use _InputArray::getMat() method to construct a matrix header for the + array (without copying data). _InputArray::kind() can be used to distinguish Mat from + `vector<>` etc., but normally it is not needed. + +Here is how you can use a function that takes InputArray : +@code + std::vector vec; + // points or a circle + for( int i = 0; i < 30; i++ ) + vec.push_back(Point2f((float)(100 + 30*cos(i*CV_PI*2/5)), + (float)(100 - 30*sin(i*CV_PI*2/5)))); + cv::transform(vec, vec, cv::Matx23f(0.707, -0.707, 10, 0.707, 0.707, 20)); +@endcode +That is, we form an STL vector containing points, and apply in-place affine transformation to the +vector using the 2x3 matrix created inline as `Matx` instance. + +Here is how such a function can be implemented (for simplicity, we implement a very specific case of +it, according to the assertion statement inside) : +@code + void myAffineTransform(InputArray _src, OutputArray _dst, InputArray _m) + { + // get Mat headers for input arrays. This is O(1) operation, + // unless _src and/or _m are matrix expressions. + Mat src = _src.getMat(), m = _m.getMat(); + CV_Assert( src.type() == CV_32FC2 && m.type() == CV_32F && m.size() == Size(3, 2) ); + + // [re]create the output array so that it has the proper size and type. + // In case of Mat it calls Mat::create, in case of STL vector it calls vector::resize. + _dst.create(src.size(), src.type()); + Mat dst = _dst.getMat(); + + for( int i = 0; i < src.rows; i++ ) + for( int j = 0; j < src.cols; j++ ) + { + Point2f pt = src.at(i, j); + dst.at(i, j) = Point2f(m.at(0, 0)*pt.x + + m.at(0, 1)*pt.y + + m.at(0, 2), + m.at(1, 0)*pt.x + + m.at(1, 1)*pt.y + + m.at(1, 2)); + } + } +@endcode +There is another related type, InputArrayOfArrays, which is currently defined as a synonym for +InputArray: +@code + typedef InputArray InputArrayOfArrays; +@endcode +It denotes function arguments that are either vectors of vectors or vectors of matrices. A separate +synonym is needed to generate Python/Java etc. wrappers properly. At the function implementation +level their use is similar, but _InputArray::getMat(idx) should be used to get header for the +idx-th component of the outer vector and _InputArray::size().area() should be used to find the +number of components (vectors/matrices) of the outer vector. + +In general, type support is limited to cv::Mat types. Other types are forbidden. +But in some cases we need to support passing of custom non-general Mat types, like arrays of cv::KeyPoint, cv::DMatch, etc. +This data is not intended to be interpreted as an image data, or processed somehow like regular cv::Mat. +To pass such custom type use rawIn() / rawOut() / rawInOut() wrappers. +Custom type is wrapped as Mat-compatible `CV_8UC` values (N = sizeof(T), N <= CV_CN_MAX). + */ +class CV_EXPORTS _InputArray +{ +public: + enum KindFlag { + KIND_SHIFT = 16, + FIXED_TYPE = 0x8000 << KIND_SHIFT, + FIXED_SIZE = 0x4000 << KIND_SHIFT, + KIND_MASK = 31 << KIND_SHIFT, + + NONE = 0 << KIND_SHIFT, + MAT = 1 << KIND_SHIFT, + MATX = 2 << KIND_SHIFT, + STD_VECTOR = 3 << KIND_SHIFT, + STD_VECTOR_VECTOR = 4 << KIND_SHIFT, + STD_VECTOR_MAT = 5 << KIND_SHIFT, +#if OPENCV_ABI_COMPATIBILITY < 500 + EXPR = 6 << KIND_SHIFT, //!< removed: https://github.com/opencv/opencv/pull/17046 +#endif + OPENGL_BUFFER = 7 << KIND_SHIFT, + CUDA_HOST_MEM = 8 << KIND_SHIFT, + CUDA_GPU_MAT = 9 << KIND_SHIFT, + UMAT =10 << KIND_SHIFT, + STD_VECTOR_UMAT =11 << KIND_SHIFT, + STD_BOOL_VECTOR =12 << KIND_SHIFT, + STD_VECTOR_CUDA_GPU_MAT = 13 << KIND_SHIFT, +#if OPENCV_ABI_COMPATIBILITY < 500 + STD_ARRAY =14 << KIND_SHIFT, //!< removed: https://github.com/opencv/opencv/issues/18897 +#endif + STD_ARRAY_MAT =15 << KIND_SHIFT + }; + + _InputArray(); + _InputArray(int _flags, void* _obj); + _InputArray(const Mat& m); + _InputArray(const MatExpr& expr); + _InputArray(const std::vector& vec); + template _InputArray(const Mat_<_Tp>& m); + template _InputArray(const std::vector<_Tp>& vec); + _InputArray(const std::vector& vec); + template _InputArray(const std::vector >& vec); + _InputArray(const std::vector >&) = delete; // not supported + template _InputArray(const std::vector >& vec); + template _InputArray(const _Tp* vec, int n); + template _InputArray(const Matx<_Tp, m, n>& matx); + _InputArray(const double& val); + _InputArray(const cuda::GpuMat& d_mat); + _InputArray(const std::vector& d_mat_array); + _InputArray(const ogl::Buffer& buf); + _InputArray(const cuda::HostMem& cuda_mem); + template _InputArray(const cudev::GpuMat_<_Tp>& m); + _InputArray(const UMat& um); + _InputArray(const std::vector& umv); + + template _InputArray(const std::array<_Tp, _Nm>& arr); + template _InputArray(const std::array& arr); + + template static _InputArray rawIn(const std::vector<_Tp>& vec); + template static _InputArray rawIn(const std::array<_Tp, _Nm>& arr); + + Mat getMat(int idx=-1) const; + Mat getMat_(int idx=-1) const; + UMat getUMat(int idx=-1) const; + void getMatVector(std::vector& mv) const; + void getUMatVector(std::vector& umv) const; + void getGpuMatVector(std::vector& gpumv) const; + cuda::GpuMat getGpuMat() const; + ogl::Buffer getOGlBuffer() const; + + int getFlags() const; + void* getObj() const; + Size getSz() const; + + _InputArray::KindFlag kind() const; + int dims(int i=-1) const; + int cols(int i=-1) const; + int rows(int i=-1) const; + Size size(int i=-1) const; + int sizend(int* sz, int i=-1) const; + bool sameSize(const _InputArray& arr) const; + size_t total(int i=-1) const; + int type(int i=-1) const; + int depth(int i=-1) const; + int channels(int i=-1) const; + bool isContinuous(int i=-1) const; + bool isSubmatrix(int i=-1) const; + bool empty() const; + void copyTo(const _OutputArray& arr) const; + void copyTo(const _OutputArray& arr, const _InputArray & mask) const; + size_t offset(int i=-1) const; + size_t step(int i=-1) const; + bool isMat() const; + bool isUMat() const; + bool isMatVector() const; + bool isUMatVector() const; + bool isMatx() const; + bool isVector() const; + bool isGpuMat() const; + bool isGpuMatVector() const; + ~_InputArray(); + +protected: + int flags; + void* obj; + Size sz; + + void init(int _flags, const void* _obj); + void init(int _flags, const void* _obj, Size _sz); +}; +CV_ENUM_FLAGS(_InputArray::KindFlag) +__CV_ENUM_FLAGS_BITWISE_AND(_InputArray::KindFlag, int, _InputArray::KindFlag) + +/** @brief This type is very similar to InputArray except that it is used for input/output and output function +parameters. + +Just like with InputArray, OpenCV users should not care about OutputArray, they just pass `Mat`, +`vector` etc. to the functions. The same limitation as for `InputArray`: *Do not explicitly +create OutputArray instances* applies here too. + +If you want to make your function polymorphic (i.e. accept different arrays as output parameters), +it is also not very difficult. Take the sample above as the reference. Note that +_OutputArray::create() needs to be called before _OutputArray::getMat(). This way you guarantee +that the output array is properly allocated. + +Optional output parameters. If you do not need certain output array to be computed and returned to +you, pass cv::noArray(), just like you would in the case of optional input array. At the +implementation level, use _OutputArray::needed() to check if certain output array needs to be +computed or not. + +There are several synonyms for OutputArray that are used to assist automatic Python/Java/... wrapper +generators: +@code + typedef OutputArray OutputArrayOfArrays; + typedef OutputArray InputOutputArray; + typedef OutputArray InputOutputArrayOfArrays; +@endcode + */ +class CV_EXPORTS _OutputArray : public _InputArray +{ +public: + enum DepthMask + { + DEPTH_MASK_8U = 1 << CV_8U, + DEPTH_MASK_8S = 1 << CV_8S, + DEPTH_MASK_16U = 1 << CV_16U, + DEPTH_MASK_16S = 1 << CV_16S, + DEPTH_MASK_32S = 1 << CV_32S, + DEPTH_MASK_32F = 1 << CV_32F, + DEPTH_MASK_64F = 1 << CV_64F, + DEPTH_MASK_16F = 1 << CV_16F, + DEPTH_MASK_ALL = (DEPTH_MASK_64F<<1)-1, + DEPTH_MASK_ALL_BUT_8S = DEPTH_MASK_ALL & ~DEPTH_MASK_8S, + DEPTH_MASK_ALL_16F = (DEPTH_MASK_16F<<1)-1, + DEPTH_MASK_FLT = DEPTH_MASK_32F + DEPTH_MASK_64F + }; + + _OutputArray(); + _OutputArray(int _flags, void* _obj); + _OutputArray(Mat& m); + _OutputArray(std::vector& vec); + _OutputArray(cuda::GpuMat& d_mat); + _OutputArray(std::vector& d_mat); + _OutputArray(ogl::Buffer& buf); + _OutputArray(cuda::HostMem& cuda_mem); + template _OutputArray(cudev::GpuMat_<_Tp>& m); + template _OutputArray(std::vector<_Tp>& vec); + _OutputArray(std::vector& vec) = delete; // not supported + template _OutputArray(std::vector >& vec); + _OutputArray(std::vector >&) = delete; // not supported + template _OutputArray(std::vector >& vec); + template _OutputArray(Mat_<_Tp>& m); + template _OutputArray(_Tp* vec, int n); + template _OutputArray(Matx<_Tp, m, n>& matx); + _OutputArray(UMat& m); + _OutputArray(std::vector& vec); + + _OutputArray(const Mat& m); + _OutputArray(const std::vector& vec); + _OutputArray(const cuda::GpuMat& d_mat); + _OutputArray(const std::vector& d_mat); + _OutputArray(const ogl::Buffer& buf); + _OutputArray(const cuda::HostMem& cuda_mem); + template _OutputArray(const cudev::GpuMat_<_Tp>& m); + template _OutputArray(const std::vector<_Tp>& vec); + template _OutputArray(const std::vector >& vec); + template _OutputArray(const std::vector >& vec); + template _OutputArray(const Mat_<_Tp>& m); + template _OutputArray(const _Tp* vec, int n); + template _OutputArray(const Matx<_Tp, m, n>& matx); + _OutputArray(const UMat& m); + _OutputArray(const std::vector& vec); + + template _OutputArray(std::array<_Tp, _Nm>& arr); + template _OutputArray(const std::array<_Tp, _Nm>& arr); + template _OutputArray(std::array& arr); + template _OutputArray(const std::array& arr); + + template static _OutputArray rawOut(std::vector<_Tp>& vec); + template static _OutputArray rawOut(std::array<_Tp, _Nm>& arr); + + bool fixedSize() const; + bool fixedType() const; + bool needed() const; + Mat& getMatRef(int i=-1) const; + UMat& getUMatRef(int i=-1) const; + cuda::GpuMat& getGpuMatRef() const; + std::vector& getGpuMatVecRef() const; + ogl::Buffer& getOGlBufferRef() const; + cuda::HostMem& getHostMemRef() const; + void create(Size sz, int type, int i=-1, bool allowTransposed=false, _OutputArray::DepthMask fixedDepthMask=static_cast<_OutputArray::DepthMask>(0)) const; + void create(int rows, int cols, int type, int i=-1, bool allowTransposed=false, _OutputArray::DepthMask fixedDepthMask=static_cast<_OutputArray::DepthMask>(0)) const; + void create(int dims, const int* size, int type, int i=-1, bool allowTransposed=false, _OutputArray::DepthMask fixedDepthMask=static_cast<_OutputArray::DepthMask>(0)) const; + void createSameSize(const _InputArray& arr, int mtype) const; + void release() const; + void clear() const; + void setTo(const _InputArray& value, const _InputArray & mask = _InputArray()) const; + + void assign(const UMat& u) const; + void assign(const Mat& m) const; + + void assign(const std::vector& v) const; + void assign(const std::vector& v) const; + + void move(UMat& u) const; + void move(Mat& m) const; +}; + + +class CV_EXPORTS _InputOutputArray : public _OutputArray +{ +public: + _InputOutputArray(); + _InputOutputArray(int _flags, void* _obj); + _InputOutputArray(Mat& m); + _InputOutputArray(std::vector& vec); + _InputOutputArray(cuda::GpuMat& d_mat); + _InputOutputArray(ogl::Buffer& buf); + _InputOutputArray(cuda::HostMem& cuda_mem); + template _InputOutputArray(cudev::GpuMat_<_Tp>& m); + template _InputOutputArray(std::vector<_Tp>& vec); + _InputOutputArray(std::vector& vec) = delete; // not supported + template _InputOutputArray(std::vector >& vec); + template _InputOutputArray(std::vector >& vec); + template _InputOutputArray(Mat_<_Tp>& m); + template _InputOutputArray(_Tp* vec, int n); + template _InputOutputArray(Matx<_Tp, m, n>& matx); + _InputOutputArray(UMat& m); + _InputOutputArray(std::vector& vec); + + _InputOutputArray(const Mat& m); + _InputOutputArray(const std::vector& vec); + _InputOutputArray(const cuda::GpuMat& d_mat); + _InputOutputArray(const std::vector& d_mat); + _InputOutputArray(const ogl::Buffer& buf); + _InputOutputArray(const cuda::HostMem& cuda_mem); + template _InputOutputArray(const cudev::GpuMat_<_Tp>& m); + template _InputOutputArray(const std::vector<_Tp>& vec); + template _InputOutputArray(const std::vector >& vec); + template _InputOutputArray(const std::vector >& vec); + template _InputOutputArray(const Mat_<_Tp>& m); + template _InputOutputArray(const _Tp* vec, int n); + template _InputOutputArray(const Matx<_Tp, m, n>& matx); + _InputOutputArray(const UMat& m); + _InputOutputArray(const std::vector& vec); + + template _InputOutputArray(std::array<_Tp, _Nm>& arr); + template _InputOutputArray(const std::array<_Tp, _Nm>& arr); + template _InputOutputArray(std::array& arr); + template _InputOutputArray(const std::array& arr); + + template static _InputOutputArray rawInOut(std::vector<_Tp>& vec); + template _InputOutputArray rawInOut(std::array<_Tp, _Nm>& arr); + +}; + +/** Helper to wrap custom types. @see InputArray */ +template static inline _InputArray rawIn(_Tp& v); +/** Helper to wrap custom types. @see InputArray */ +template static inline _OutputArray rawOut(_Tp& v); +/** Helper to wrap custom types. @see InputArray */ +template static inline _InputOutputArray rawInOut(_Tp& v); + +CV__DEBUG_NS_END + +typedef const _InputArray& InputArray; +typedef InputArray InputArrayOfArrays; +typedef const _OutputArray& OutputArray; +typedef OutputArray OutputArrayOfArrays; +typedef const _InputOutputArray& InputOutputArray; +typedef InputOutputArray InputOutputArrayOfArrays; + +/** @brief Returns an empty InputArray or OutputArray. + + This function is used to provide an "empty" or "null" array when certain functions + take optional input or output arrays that you don't want to provide. + + Many OpenCV functions accept optional arguments as `cv::InputArray` or `cv::OutputArray`. + When you don't want to pass any data for these optional parameters, you can use `cv::noArray()` + to indicate that you are omitting them. + + @return An empty `cv::InputArray` or `cv::OutputArray` that can be used as a placeholder. + + @note This is often used when a function has optional arrays, and you do not want to + provide a specific input or output array. + + @see cv::InputArray, cv::OutputArray + */ +CV_EXPORTS InputOutputArray noArray(); + +/////////////////////////////////// MatAllocator ////////////////////////////////////// + +/** @brief Usage flags for allocator + + @warning All flags except `USAGE_DEFAULT` are experimental. + + @warning For the OpenCL allocator, `USAGE_ALLOCATE_SHARED_MEMORY` depends on + OpenCV's optional, experimental integration with OpenCL SVM. To enable this + integration, build OpenCV using the `WITH_OPENCL_SVM=ON` CMake option and, at + runtime, call `cv::ocl::Context::getDefault().setUseSVM(true);` or similar + code. Note that SVM is incompatible with OpenCL 1.x. +*/ +enum UMatUsageFlags +{ + USAGE_DEFAULT = 0, + + // buffer allocation policy is platform and usage specific + USAGE_ALLOCATE_HOST_MEMORY = 1 << 0, + USAGE_ALLOCATE_DEVICE_MEMORY = 1 << 1, + USAGE_ALLOCATE_SHARED_MEMORY = 1 << 2, // It is not equal to: USAGE_ALLOCATE_HOST_MEMORY | USAGE_ALLOCATE_DEVICE_MEMORY + + __UMAT_USAGE_FLAGS_32BIT = 0x7fffffff // Binary compatibility hint +}; + +struct CV_EXPORTS UMatData; + +/** @brief Custom array allocator +*/ +class CV_EXPORTS MatAllocator +{ +public: + MatAllocator() {} + virtual ~MatAllocator() {} + + // let's comment it off for now to detect and fix all the uses of allocator + //virtual void allocate(int dims, const int* sizes, int type, int*& refcount, + // uchar*& datastart, uchar*& data, size_t* step) = 0; + //virtual void deallocate(int* refcount, uchar* datastart, uchar* data) = 0; + virtual UMatData* allocate(int dims, const int* sizes, int type, + void* data, size_t* step, AccessFlag flags, UMatUsageFlags usageFlags) const = 0; + virtual bool allocate(UMatData* data, AccessFlag accessflags, UMatUsageFlags usageFlags) const = 0; + virtual void deallocate(UMatData* data) const = 0; + virtual void map(UMatData* data, AccessFlag accessflags) const; + virtual void unmap(UMatData* data) const; + virtual void download(UMatData* data, void* dst, int dims, const size_t sz[], + const size_t srcofs[], const size_t srcstep[], + const size_t dststep[]) const; + virtual void upload(UMatData* data, const void* src, int dims, const size_t sz[], + const size_t dstofs[], const size_t dststep[], + const size_t srcstep[]) const; + virtual void copy(UMatData* srcdata, UMatData* dstdata, int dims, const size_t sz[], + const size_t srcofs[], const size_t srcstep[], + const size_t dstofs[], const size_t dststep[], bool sync) const; + + // default implementation returns DummyBufferPoolController + virtual BufferPoolController* getBufferPoolController(const char* id = NULL) const; +}; + + +//////////////////////////////// MatCommaInitializer ////////////////////////////////// + +/** @brief Comma-separated Matrix Initializer + + The class instances are usually not created explicitly. + Instead, they are created on "matrix << firstValue" operator. + + The sample below initializes 2x2 rotation matrix: + + \code + double angle = 30, a = cos(angle*CV_PI/180), b = sin(angle*CV_PI/180); + Mat R = (Mat_(2,2) << a, -b, b, a); + \endcode +*/ +template class MatCommaInitializer_ +{ +public: + //! the constructor, created by "matrix << firstValue" operator, where matrix is cv::Mat + MatCommaInitializer_(Mat_<_Tp>* _m); + //! the operator that takes the next value and put it to the matrix + template MatCommaInitializer_<_Tp>& operator , (T2 v); + //! another form of conversion operator + operator Mat_<_Tp>() const; +protected: + MatIterator_<_Tp> it; +}; + + +/////////////////////////////////////// Mat /////////////////////////////////////////// + +// note that umatdata might be allocated together +// with the matrix data, not as a separate object. +// therefore, it does not have constructor or destructor; +// it should be explicitly initialized using init(). +struct CV_EXPORTS UMatData +{ + enum MemoryFlag { COPY_ON_MAP=1, HOST_COPY_OBSOLETE=2, + DEVICE_COPY_OBSOLETE=4, TEMP_UMAT=8, TEMP_COPIED_UMAT=24, + USER_ALLOCATED=32, DEVICE_MEM_MAPPED=64, + ASYNC_CLEANUP=128 + }; + UMatData(const MatAllocator* allocator); + ~UMatData(); + + // provide atomic access to the structure + void lock(); + void unlock(); + + bool hostCopyObsolete() const; + bool deviceCopyObsolete() const; + bool deviceMemMapped() const; + bool copyOnMap() const; + bool tempUMat() const; + bool tempCopiedUMat() const; + void markHostCopyObsolete(bool flag); + void markDeviceCopyObsolete(bool flag); + void markDeviceMemMapped(bool flag); + + const MatAllocator* prevAllocator; + const MatAllocator* currAllocator; + int urefcount; + int refcount; + uchar* data; + uchar* origdata; + size_t size; + + UMatData::MemoryFlag flags; + void* handle; + void* userdata; + int allocatorFlags_; + int mapcount; + UMatData* originalUMatData; + std::shared_ptr allocatorContext; +}; +CV_ENUM_FLAGS(UMatData::MemoryFlag) + + +struct CV_EXPORTS MatSize +{ + explicit MatSize(int* _p) CV_NOEXCEPT; + int dims() const CV_NOEXCEPT; + Size operator()() const; + const int& operator[](int i) const; + int& operator[](int i); + operator const int*() const CV_NOEXCEPT; // TODO OpenCV 4.0: drop this + bool operator == (const MatSize& sz) const CV_NOEXCEPT; + bool operator != (const MatSize& sz) const CV_NOEXCEPT; + + int* p; +}; + +struct CV_EXPORTS MatStep +{ + MatStep() CV_NOEXCEPT; + explicit MatStep(size_t s) CV_NOEXCEPT; + const size_t& operator[](int i) const CV_NOEXCEPT; + size_t& operator[](int i) CV_NOEXCEPT; + operator size_t() const; + MatStep& operator = (size_t s); + + size_t* p; + size_t buf[2]; +protected: + MatStep& operator = (const MatStep&); +}; + +/** @example samples/cpp/cout_mat.cpp +An example demonstrating the serial out capabilities of cv::Mat +*/ + + /** @brief n-dimensional dense array class \anchor CVMat_Details + +The class Mat represents an n-dimensional dense numerical single-channel or multi-channel array. It +can be used to store real or complex-valued vectors and matrices, grayscale or color images, voxel +volumes, vector fields, point clouds, tensors, histograms (though, very high-dimensional histograms +may be better stored in a SparseMat ). The data layout of the array `M` is defined by the array +`M.step[]`, so that the address of element \f$(i_0,...,i_{M.dims-1})\f$, where \f$0\leq i_k= M.step[i+1]` (in fact, `M.step[i] >= M.step[i+1]*M.size[i+1]` ). This means +that 2-dimensional matrices are stored row-by-row, 3-dimensional matrices are stored plane-by-plane, +and so on. M.step[M.dims-1] is minimal and always equal to the element size M.elemSize() . + +So, the data layout in Mat is compatible with the majority of dense array types from the standard +toolkits and SDKs, such as Numpy (ndarray), Win32 (independent device bitmaps), and others, +that is, with any array that uses *steps* (or *strides*) to compute the position of a pixel. +Due to this compatibility, it is possible to make a Mat header for user-allocated data and process +it in-place using OpenCV functions. + +There are many different ways to create a Mat object. The most popular options are listed below: + +- Use the create(nrows, ncols, type) method or the similar Mat(nrows, ncols, type[, fillValue]) +constructor. A new array of the specified size and type is allocated. type has the same meaning as +in the cvCreateMat method. For example, CV_8UC1 means a 8-bit single-channel array, CV_32FC2 +means a 2-channel (complex) floating-point array, and so on. +@code + // make a 7x7 complex matrix filled with 1+3j. + Mat M(7,7,CV_32FC2,Scalar(1,3)); + // and now turn M to a 100x60 15-channel 8-bit matrix. + // The old content will be deallocated + M.create(100,60,CV_8UC(15)); +@endcode +As noted in the introduction to this chapter, create() allocates only a new array when the shape +or type of the current array are different from the specified ones. + +- Create a multi-dimensional array: +@code + // create a 100x100x100 8-bit array + int sz[] = {100, 100, 100}; + Mat bigCube(3, sz, CV_8U, Scalar::all(0)); +@endcode +It passes the number of dimensions =1 to the Mat constructor but the created array will be +2-dimensional with the number of columns set to 1. So, Mat::dims is always \>= 2 (can also be 0 +when the array is empty). + +- Use a copy constructor or assignment operator where there can be an array or expression on the +right side (see below). As noted in the introduction, the array assignment is an O(1) operation +because it only copies the header and increases the reference counter. The Mat::clone() method can +be used to get a full (deep) copy of the array when you need it. + +- Construct a header for a part of another array. It can be a single row, single column, several +rows, several columns, rectangular region in the array (called a *minor* in algebra) or a +diagonal. Such operations are also O(1) because the new header references the same data. You can +actually modify a part of the array using this feature, for example: +@code + // add the 5-th row, multiplied by 3 to the 3rd row + M.row(3) = M.row(3) + M.row(5)*3; + // now copy the 7-th column to the 1-st column + // M.col(1) = M.col(7); // this will not work + Mat M1 = M.col(1); + M.col(7).copyTo(M1); + // create a new 320x240 image + Mat img(Size(320,240),CV_8UC3); + // select a ROI + Mat roi(img, Rect(10,10,100,100)); + // fill the ROI with (0,255,0) (which is green in RGB space); + // the original 320x240 image will be modified + roi = Scalar(0,255,0); +@endcode +Due to the additional datastart and dataend members, it is possible to compute a relative +sub-array position in the main *container* array using locateROI(): +@code + Mat A = Mat::eye(10, 10, CV_32S); + // extracts A columns, 1 (inclusive) to 3 (exclusive). + Mat B = A(Range::all(), Range(1, 3)); + // extracts B rows, 5 (inclusive) to 9 (exclusive). + // that is, C \~ A(Range(5, 9), Range(1, 3)) + Mat C = B(Range(5, 9), Range::all()); + Size size; Point ofs; + C.locateROI(size, ofs); + // size will be (width=10,height=10) and the ofs will be (x=1, y=5) +@endcode +As in case of whole matrices, if you need a deep copy, use the `clone()` method of the extracted +sub-matrices. + +- Make a header for user-allocated data. It can be useful to do the following: + -# Process "foreign" data using OpenCV (for example, when you implement a DirectShow\* filter or + a processing module for gstreamer, and so on). For example: + @code + Mat process_video_frame(const unsigned char* pixels, + int width, int height, int step) + { + // wrap input buffer + Mat img(height, width, CV_8UC3, (unsigned char*)pixels, step); + + Mat result; + GaussianBlur(img, result, Size(7, 7), 1.5, 1.5); + + return result; + } + @endcode + -# Quickly initialize small matrices and/or get a super-fast element access. + @code + double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}}; + Mat M = Mat(3, 3, CV_64F, m).inv(); + @endcode + . + +- Use MATLAB-style array initializers, zeros(), ones(), eye(), for example: +@code + // create a double-precision identity matrix and add it to M. + M += Mat::eye(M.rows, M.cols, CV_64F); +@endcode + +- Use a comma-separated initializer: +@code + // create a 3x3 double-precision identity matrix + Mat M = (Mat_(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1); +@endcode +With this approach, you first call a constructor of the Mat class with the proper parameters, and +then you just put `<< operator` followed by comma-separated values that can be constants, +variables, expressions, and so on. Also, note the extra parentheses required to avoid compilation +errors. + +Once the array is created, it is automatically managed via a reference-counting mechanism. If the +array header is built on top of user-allocated data, you should handle the data by yourself. The +array data is deallocated when no one points to it. If you want to release the data pointed by a +array header before the array destructor is called, use Mat::release(). + +The next important thing to learn about the array class is element access. This manual already +described how to compute an address of each array element. Normally, you are not required to use the +formula directly in the code. If you know the array element type (which can be retrieved using the +method Mat::type() ), you can access the element \f$M_{ij}\f$ of a 2-dimensional array as: +@code + M.at(i,j) += 1.f; +@endcode +assuming that `M` is a double-precision floating-point array. There are several variants of the method +at for a different number of dimensions. + +If you need to process a whole row of a 2D array, the most efficient way is to get the pointer to +the row first, and then just use the plain C operator [] : +@code + // compute sum of positive matrix elements + // (assuming that M is a double-precision matrix) + double sum=0; + for(int i = 0; i < M.rows; i++) + { + const double* Mi = M.ptr(i); + for(int j = 0; j < M.cols; j++) + sum += std::max(Mi[j], 0.); + } +@endcode +Some operations, like the one above, do not actually depend on the array shape. They just process +elements of an array one by one (or elements from multiple arrays that have the same coordinates, +for example, array addition). Such operations are called *element-wise*. It makes sense to check +whether all the input/output arrays are continuous, namely, have no gaps at the end of each row. If +yes, process them as a long single row: +@code + // compute the sum of positive matrix elements, optimized variant + double sum=0; + int cols = M.cols, rows = M.rows; + if(M.isContinuous()) + { + cols *= rows; + rows = 1; + } + for(int i = 0; i < rows; i++) + { + const double* Mi = M.ptr(i); + for(int j = 0; j < cols; j++) + sum += std::max(Mi[j], 0.); + } +@endcode +In case of the continuous matrix, the outer loop body is executed just once. So, the overhead is +smaller, which is especially noticeable in case of small matrices. + +Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows: +@code + // compute sum of positive matrix elements, iterator-based variant + double sum=0; + MatConstIterator_ it = M.begin(), it_end = M.end(); + for(; it != it_end; ++it) + sum += std::max(*it, 0.); +@endcode +The matrix iterators are random-access iterators, so they can be passed to any STL algorithm, +including std::sort(). + +@note Matrix Expressions and arithmetic see MatExpr +*/ +class CV_EXPORTS Mat +{ +public: + /** + These are various constructors that form a matrix. As noted in the AutomaticAllocation, often + the default constructor is enough, and the proper matrix will be allocated by an OpenCV function. + The constructed matrix can further be assigned to another matrix or matrix expression or can be + allocated with Mat::create . In the former case, the old content is de-referenced. + */ + Mat() CV_NOEXCEPT; + + /** @overload + @param rows Number of rows in a 2D array. + @param cols Number of columns in a 2D array. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + */ + Mat(int rows, int cols, int type); + + /** @overload + @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the + number of columns go in the reverse order. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + */ + Mat(Size size, int type); + + /** @overload + @param rows Number of rows in a 2D array. + @param cols Number of columns in a 2D array. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param s An optional value to initialize each matrix element with. To set all the matrix elements to + the particular value after the construction, use the assignment operator + Mat::operator=(const Scalar& value) . + */ + Mat(int rows, int cols, int type, const Scalar& s); + + /** @overload + @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the + number of columns go in the reverse order. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param s An optional value to initialize each matrix element with. To set all the matrix elements to + the particular value after the construction, use the assignment operator + Mat::operator=(const Scalar& value) . + */ + Mat(Size size, int type, const Scalar& s); + + /** @overload + @param ndims Array dimensionality. + @param sizes Array of integers specifying an n-dimensional array shape. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + */ + Mat(int ndims, const int* sizes, int type); + + /** @overload + @param sizes Array of integers specifying an n-dimensional array shape. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + */ + Mat(const std::vector& sizes, int type); + + /** @overload + @param ndims Array dimensionality. + @param sizes Array of integers specifying an n-dimensional array shape. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param s An optional value to initialize each matrix element with. To set all the matrix elements to + the particular value after the construction, use the assignment operator + Mat::operator=(const Scalar& value) . + */ + Mat(int ndims, const int* sizes, int type, const Scalar& s); + + /** @overload + @param sizes Array of integers specifying an n-dimensional array shape. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param s An optional value to initialize each matrix element with. To set all the matrix elements to + the particular value after the construction, use the assignment operator + Mat::operator=(const Scalar& value) . + */ + Mat(const std::vector& sizes, int type, const Scalar& s); + + + /** @overload + @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied + by these constructors. Instead, the header pointing to m data or its sub-array is constructed and + associated with it. The reference counter, if any, is incremented. So, when you modify the matrix + formed using such a constructor, you also modify the corresponding elements of m . If you want to + have an independent copy of the sub-array, use Mat::clone() . + */ + Mat(const Mat& m); + + /** @overload + @param rows Number of rows in a 2D array. + @param cols Number of columns in a 2D array. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param data Pointer to the user data. Matrix constructors that take data and step parameters do not + allocate matrix data. Instead, they just initialize the matrix header that points to the specified + data, which means that no data is copied. This operation is very efficient and can be used to + process external data using OpenCV functions. The external data is not automatically deallocated, so + you should take care of it. + @param step Number of bytes each matrix row occupies. The value should include the padding bytes at + the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed + and the actual step is calculated as cols*elemSize(). See Mat::elemSize. + */ + Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP); + + /** @overload + @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the + number of columns go in the reverse order. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param data Pointer to the user data. Matrix constructors that take data and step parameters do not + allocate matrix data. Instead, they just initialize the matrix header that points to the specified + data, which means that no data is copied. This operation is very efficient and can be used to + process external data using OpenCV functions. The external data is not automatically deallocated, so + you should take care of it. + @param step Number of bytes each matrix row occupies. The value should include the padding bytes at + the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed + and the actual step is calculated as cols*elemSize(). See Mat::elemSize. + */ + Mat(Size size, int type, void* data, size_t step=AUTO_STEP); + + /** @overload + @param ndims Array dimensionality. + @param sizes Array of integers specifying an n-dimensional array shape. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param data Pointer to the user data. Matrix constructors that take data and step parameters do not + allocate matrix data. Instead, they just initialize the matrix header that points to the specified + data, which means that no data is copied. This operation is very efficient and can be used to + process external data using OpenCV functions. The external data is not automatically deallocated, so + you should take care of it. + @param steps Array of ndims-1 steps in case of a multi-dimensional array (the last step is always + set to the element size). If not specified, the matrix is assumed to be continuous. + */ + Mat(int ndims, const int* sizes, int type, void* data, const size_t* steps=0); + + /** @overload + @param sizes Array of integers specifying an n-dimensional array shape. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param data Pointer to the user data. Matrix constructors that take data and step parameters do not + allocate matrix data. Instead, they just initialize the matrix header that points to the specified + data, which means that no data is copied. This operation is very efficient and can be used to + process external data using OpenCV functions. The external data is not automatically deallocated, so + you should take care of it. + @param steps Array of ndims-1 steps in case of a multi-dimensional array (the last step is always + set to the element size). If not specified, the matrix is assumed to be continuous. + */ + Mat(const std::vector& sizes, int type, void* data, const size_t* steps=0); + + /** @overload + @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied + by these constructors. Instead, the header pointing to m data or its sub-array is constructed and + associated with it. The reference counter, if any, is incremented. So, when you modify the matrix + formed using such a constructor, you also modify the corresponding elements of m . If you want to + have an independent copy of the sub-array, use Mat::clone() . + @param rowRange Range of the m rows to take. As usual, the range start is inclusive and the range + end is exclusive. Use Range::all() to take all the rows. + @param colRange Range of the m columns to take. Use Range::all() to take all the columns. + */ + Mat(const Mat& m, const Range& rowRange, const Range& colRange=Range::all()); + + /** @overload + @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied + by these constructors. Instead, the header pointing to m data or its sub-array is constructed and + associated with it. The reference counter, if any, is incremented. So, when you modify the matrix + formed using such a constructor, you also modify the corresponding elements of m . If you want to + have an independent copy of the sub-array, use Mat::clone() . + @param roi Region of interest. + */ + Mat(const Mat& m, const Rect& roi); + + /** @overload + @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied + by these constructors. Instead, the header pointing to m data or its sub-array is constructed and + associated with it. The reference counter, if any, is incremented. So, when you modify the matrix + formed using such a constructor, you also modify the corresponding elements of m . If you want to + have an independent copy of the sub-array, use Mat::clone() . + @param ranges Array of selected ranges of m along each dimensionality. + */ + Mat(const Mat& m, const Range* ranges); + + /** @overload + @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied + by these constructors. Instead, the header pointing to m data or its sub-array is constructed and + associated with it. The reference counter, if any, is incremented. So, when you modify the matrix + formed using such a constructor, you also modify the corresponding elements of m . If you want to + have an independent copy of the sub-array, use Mat::clone() . + @param ranges Array of selected ranges of m along each dimensionality. + */ + Mat(const Mat& m, const std::vector& ranges); + + /** @overload + @param vec STL vector whose elements form the matrix. The matrix has a single column and the number + of rows equal to the number of vector elements. Type of the matrix matches the type of vector + elements. The constructor can handle arbitrary types, for which there is a properly declared + DataType . This means that the vector elements must be primitive numbers or uni-type numerical + tuples of numbers. Mixed-type structures are not supported. The corresponding constructor is + explicit. Since STL vectors are not automatically converted to Mat instances, you should write + Mat(vec) explicitly. Unless you copy the data into the matrix ( copyData=true ), no new elements + will be added to the vector because it can potentially yield vector data reallocation, and, thus, + the matrix data pointer will be invalid. + @param copyData Flag to specify whether the underlying data of the STL vector should be copied + to (true) or shared with (false) the newly constructed matrix. When the data is copied, the + allocated buffer is managed using Mat reference counting mechanism. While the data is shared, + the reference counter is NULL, and you should not deallocate the data until the matrix is + destructed. + */ + template explicit Mat(const std::vector<_Tp>& vec, bool copyData=false); + + /** @overload + */ + template::value>::type> + explicit Mat(const std::initializer_list<_Tp> list); + + /** @overload + */ + template explicit Mat(const std::initializer_list sizes, const std::initializer_list<_Tp> list); + + /** @overload + */ + template explicit Mat(const std::array<_Tp, _Nm>& arr, bool copyData=false); + + /** @overload + */ + template explicit Mat(const Vec<_Tp, n>& vec, bool copyData=true); + + /** @overload + */ + template explicit Mat(const Matx<_Tp, m, n>& mtx, bool copyData=true); + + /** @overload + */ + template explicit Mat(const Point_<_Tp>& pt, bool copyData=true); + + /** @overload + */ + template explicit Mat(const Point3_<_Tp>& pt, bool copyData=true); + + /** @overload + */ + template explicit Mat(const MatCommaInitializer_<_Tp>& commaInitializer); + + //! download data from GpuMat + explicit Mat(const cuda::GpuMat& m); + + //! destructor - calls release() + ~Mat(); + + /** @brief assignment operators + + These are available assignment operators. Since they all are very different, make sure to read the + operator parameters description. + @param m Assigned, right-hand-side matrix. Matrix assignment is an O(1) operation. This means that + no data is copied but the data is shared and the reference counter, if any, is incremented. Before + assigning new data, the old data is de-referenced via Mat::release . + */ + Mat& operator = (const Mat& m); + + /** @overload + @param expr Assigned matrix expression object. As opposite to the first form of the assignment + operation, the second form can reuse already allocated matrix if it has the right size and type to + fit the matrix expression result. It is automatically handled by the real function that the matrix + expressions is expanded to. For example, C=A+B is expanded to add(A, B, C), and add takes care of + automatic C reallocation. + */ + Mat& operator = (const MatExpr& expr); + + //! retrieve UMat from Mat + UMat getUMat(AccessFlag accessFlags, UMatUsageFlags usageFlags = USAGE_DEFAULT) const; + + /** @brief Creates a matrix header for the specified matrix row. + + The method makes a new header for the specified matrix row and returns it. This is an O(1) + operation, regardless of the matrix size. The underlying data of the new matrix is shared with the + original matrix. Here is the example of one of the classical basic matrix processing operations, + axpy, used by LU and many other algorithms: + @code + inline void matrix_axpy(Mat& A, int i, int j, double alpha) + { + A.row(i) += A.row(j)*alpha; + } + @endcode + @note In the current implementation, the following code does not work as expected: + @code + Mat A; + ... + A.row(i) = A.row(j); // will not work + @endcode + This happens because A.row(i) forms a temporary header that is further assigned to another header. + Remember that each of these operations is O(1), that is, no data is copied. Thus, the above + assignment is not true if you may have expected the j-th row to be copied to the i-th row. To + achieve that, you should either turn this simple assignment into an expression or use the + Mat::copyTo method: + @code + Mat A; + ... + // works, but looks a bit obscure. + A.row(i) = A.row(j) + 0; + // this is a bit longer, but the recommended method. + A.row(j).copyTo(A.row(i)); + @endcode + @param y A 0-based row index. + */ + Mat row(int y) const; + + /** @brief Creates a matrix header for the specified matrix column. + + The method makes a new header for the specified matrix column and returns it. This is an O(1) + operation, regardless of the matrix size. The underlying data of the new matrix is shared with the + original matrix. See also the Mat::row description. + @param x A 0-based column index. + */ + Mat col(int x) const; + + /** @brief Creates a matrix header for the specified row span. + + The method makes a new header for the specified row span of the matrix. Similarly to Mat::row and + Mat::col , this is an O(1) operation. + @param startrow An inclusive 0-based start index of the row span. + @param endrow An exclusive 0-based ending index of the row span. + */ + Mat rowRange(int startrow, int endrow) const; + + /** @overload + @param r Range structure containing both the start and the end indices. + */ + Mat rowRange(const Range& r) const; + + /** @brief Creates a matrix header for the specified column span. + + The method makes a new header for the specified column span of the matrix. Similarly to Mat::row and + Mat::col , this is an O(1) operation. + @param startcol An inclusive 0-based start index of the column span. + @param endcol An exclusive 0-based ending index of the column span. + */ + Mat colRange(int startcol, int endcol) const; + + /** @overload + @param r Range structure containing both the start and the end indices. + */ + Mat colRange(const Range& r) const; + + /** @brief Extracts a diagonal from a matrix + + The method makes a new header for the specified matrix diagonal. The new matrix is represented as a + single-column matrix. Similarly to Mat::row and Mat::col, this is an O(1) operation. + @param d index of the diagonal, with the following values: + - `d=0` is the main diagonal. + - `d<0` is a diagonal from the lower half. For example, d=-1 means the diagonal is set + immediately below the main one. + - `d>0` is a diagonal from the upper half. For example, d=1 means the diagonal is set + immediately above the main one. + For example: + @code + Mat m = (Mat_(3,3) << + 1,2,3, + 4,5,6, + 7,8,9); + Mat d0 = m.diag(0); + Mat d1 = m.diag(1); + Mat d_1 = m.diag(-1); + @endcode + The resulting matrices are + @code + d0 = + [1; + 5; + 9] + d1 = + [2; + 6] + d_1 = + [4; + 8] + @endcode + */ + Mat diag(int d=0) const; + + /** @brief creates a diagonal matrix + + The method creates a square diagonal matrix from specified main diagonal. + @param d One-dimensional matrix that represents the main diagonal. + */ + CV_NODISCARD_STD static Mat diag(const Mat& d); + + /** @brief Creates a full copy of the array and the underlying data. + + The method creates a full copy of the array. The original step[] is not taken into account. So, the + array copy is a continuous array occupying total()*elemSize() bytes. + */ + CV_NODISCARD_STD Mat clone() const; + + /** @brief Copies the matrix to another one. + + The method copies the matrix data to another matrix. Before copying the data, the method invokes : + @code + m.create(this->size(), this->type()); + @endcode + so that the destination matrix is reallocated if needed. While m.copyTo(m); works flawlessly, the + function does not handle the case of a partial overlap between the source and the destination + matrices. + + When the operation mask is specified, if the Mat::create call shown above reallocates the matrix, + the newly allocated matrix is initialized with all zeros before copying the data. + @param m Destination matrix. If it does not have a proper size or type before the operation, it is + reallocated. + */ + void copyTo( OutputArray m ) const; + + /** @overload + @param m Destination matrix. If it does not have a proper size or type before the operation, it is + reallocated. + @param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix + elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels. + */ + void copyTo( OutputArray m, InputArray mask ) const; + + /** @brief Converts an array to another data type with optional scaling. + + The method converts source pixel values to the target data type. saturate_cast\<\> is applied at + the end to avoid possible overflows: + + \f[m(x,y) = saturate \_ cast( \alpha (*this)(x,y) + \beta )\f] + @param m output matrix; if it does not have a proper size or type before the operation, it is + reallocated. + @param rtype desired output matrix type or, rather, the depth since the number of channels are the + same as the input has; if rtype is negative, the output matrix will have the same type as the input. + @param alpha optional scale factor. + @param beta optional delta added to the scaled values. + */ + void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const; + + /** @brief Provides a functional form of convertTo. + + This is an internally used method called by the @ref MatrixExpressions engine. + @param m Destination array. + @param type Desired destination array depth (or -1 if it should be the same as the source type). + */ + void assignTo( Mat& m, int type=-1 ) const; + + /** @brief Sets all or some of the array elements to the specified value. + @param s Assigned scalar converted to the actual array type. + */ + Mat& operator = (const Scalar& s); + + /** @brief Sets all or some of the array elements to the specified value. + + This is an advanced variant of the Mat::operator=(const Scalar& s) operator. + @param value Assigned scalar converted to the actual array type. + @param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix + elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels + */ + Mat& setTo(InputArray value, InputArray mask=noArray()); + + /** @brief Changes the shape and/or the number of channels of a 2D matrix without copying the data. + + The method makes a new matrix header for \*this elements. The new matrix may have a different size + and/or different number of channels. Any combination is possible if: + - No extra elements are included into the new matrix and no elements are excluded. Consequently, + the product rows\*cols\*channels() must stay the same after the transformation. + - No data is copied. That is, this is an O(1) operation. Consequently, if you change the number of + rows, or the operation changes the indices of elements row in some other way, the matrix must be + continuous. See Mat::isContinuous . + + For example, if there is a set of 3D points stored as an STL vector, and you want to represent the + points as a 3xN matrix, do the following: + @code + std::vector vec; + ... + Mat pointMat = Mat(vec). // convert vector to Mat, O(1) operation + reshape(1). // make Nx3 1-channel matrix out of Nx1 3-channel. + // Also, an O(1) operation + t(); // finally, transpose the Nx3 matrix. + // This involves copying all the elements + @endcode + 3-channel 2x2 matrix reshaped to 1-channel 4x3 matrix, each column has values from one of original channels: + @code + Mat m(Size(2, 2), CV_8UC3, Scalar(1, 2, 3)); + vector new_shape {4, 3}; + m = m.reshape(1, new_shape); + @endcode + or: + @code + Mat m(Size(2, 2), CV_8UC3, Scalar(1, 2, 3)); + const int new_shape[] = {4, 3}; + m = m.reshape(1, 2, new_shape); + @endcode + @param cn New number of channels. If the parameter is 0, the number of channels remains the same. + @param rows New number of rows. If the parameter is 0, the number of rows remains the same. + */ + Mat reshape(int cn, int rows=0) const; + + /** @overload + * @param cn New number of channels. If the parameter is 0, the number of channels remains the same. + * @param newndims New number of dimentions. + * @param newsz Array with new matrix size by all dimentions. If some sizes are zero, + * the original sizes in those dimensions are presumed. + */ + Mat reshape(int cn, int newndims, const int* newsz) const; + + /** @overload + * @param cn New number of channels. If the parameter is 0, the number of channels remains the same. + * @param newshape Vector with new matrix size by all dimentions. If some sizes are zero, + * the original sizes in those dimensions are presumed. + */ + Mat reshape(int cn, const std::vector& newshape) const; + + /** @brief Transposes a matrix. + + The method performs matrix transposition by means of matrix expressions. It does not perform the + actual transposition but returns a temporary matrix transposition object that can be further used as + a part of more complex matrix expressions or can be assigned to a matrix: + @code + Mat A1 = A + Mat::eye(A.size(), A.type())*lambda; + Mat C = A1.t()*A1; // compute (A + lambda*I)^t * (A + lamda*I) + @endcode + */ + MatExpr t() const; + + /** @brief Inverses a matrix. + + The method performs a matrix inversion by means of matrix expressions. This means that a temporary + matrix inversion object is returned by the method and can be used further as a part of more complex + matrix expressions or can be assigned to a matrix. + @param method Matrix inversion method. One of cv::DecompTypes + */ + MatExpr inv(int method=DECOMP_LU) const; + + /** @brief Performs an element-wise multiplication or division of the two matrices. + + The method returns a temporary object encoding per-element array multiplication, with optional + scale. Note that this is not a matrix multiplication that corresponds to a simpler "\*" operator. + + Example: + @code + Mat C = A.mul(5/B); // equivalent to divide(A, B, C, 5) + @endcode + @param m Another array of the same type and the same size as \*this, or a matrix expression. + @param scale Optional scale factor. + */ + MatExpr mul(InputArray m, double scale=1) const; + + /** @brief Computes a cross-product of two 3-element vectors. + + The method computes a cross-product of two 3-element vectors. The vectors must be 3-element + floating-point vectors of the same shape and size. The result is another 3-element vector of the + same shape and type as operands. + @param m Another cross-product operand. + */ + Mat cross(InputArray m) const; + + /** @brief Computes a dot-product of two vectors. + + The method computes a dot-product of two matrices. If the matrices are not single-column or + single-row vectors, the top-to-bottom left-to-right scan ordering is used to treat them as 1D + vectors. The vectors must have the same size and type. If the matrices have more than one channel, + the dot products from all the channels are summed together. + @param m another dot-product operand. + */ + double dot(InputArray m) const; + + /** @brief Returns a zero array of the specified size and type. + + The method returns a Matlab-style zero array initializer. It can be used to quickly form a constant + array as a function parameter, part of a matrix expression, or as a matrix initializer: + @code + Mat A; + A = Mat::zeros(3, 3, CV_32F); + @endcode + In the example above, a new matrix is allocated only if A is not a 3x3 floating-point matrix. + Otherwise, the existing matrix A is filled with zeros. + @param rows Number of rows. + @param cols Number of columns. + @param type Created matrix type. + */ + CV_NODISCARD_STD static MatExpr zeros(int rows, int cols, int type); + + /** @overload + @param size Alternative to the matrix size specification Size(cols, rows) . + @param type Created matrix type. + */ + CV_NODISCARD_STD static MatExpr zeros(Size size, int type); + + /** @overload + @param ndims Array dimensionality. + @param sz Array of integers specifying the array shape. + @param type Created matrix type. + */ + CV_NODISCARD_STD static MatExpr zeros(int ndims, const int* sz, int type); + + /** @brief Returns an array of all 1's of the specified size and type. + + The method returns a Matlab-style 1's array initializer, similarly to Mat::zeros. Note that using + this method you can initialize an array with an arbitrary value, using the following Matlab idiom: + @code + Mat A = Mat::ones(100, 100, CV_8U)*3; // make 100x100 matrix filled with 3. + @endcode + The above operation does not form a 100x100 matrix of 1's and then multiply it by 3. Instead, it + just remembers the scale factor (3 in this case) and use it when actually invoking the matrix + initializer. + @note In case of multi-channels type, only the first channel will be initialized with 1's, the + others will be set to 0's. + @param rows Number of rows. + @param cols Number of columns. + @param type Created matrix type. + */ + CV_NODISCARD_STD static MatExpr ones(int rows, int cols, int type); + + /** @overload + @param size Alternative to the matrix size specification Size(cols, rows) . + @param type Created matrix type. + */ + CV_NODISCARD_STD static MatExpr ones(Size size, int type); + + /** @overload + @param ndims Array dimensionality. + @param sz Array of integers specifying the array shape. + @param type Created matrix type. + */ + CV_NODISCARD_STD static MatExpr ones(int ndims, const int* sz, int type); + + /** @brief Returns an identity matrix of the specified size and type. + + The method returns a Matlab-style identity matrix initializer, similarly to Mat::zeros. Similarly to + Mat::ones, you can use a scale operation to create a scaled identity matrix efficiently: + @code + // make a 4x4 diagonal matrix with 0.1's on the diagonal. + Mat A = Mat::eye(4, 4, CV_32F)*0.1; + @endcode + @note In case of multi-channels type, identity matrix will be initialized only for the first channel, + the others will be set to 0's + @param rows Number of rows. + @param cols Number of columns. + @param type Created matrix type. + */ + CV_NODISCARD_STD static MatExpr eye(int rows, int cols, int type); + + /** @overload + @param size Alternative matrix size specification as Size(cols, rows) . + @param type Created matrix type. + */ + CV_NODISCARD_STD static MatExpr eye(Size size, int type); + + /** @brief Allocates new array data if needed. + + This is one of the key Mat methods. Most new-style OpenCV functions and methods that produce arrays + call this method for each output array. The method uses the following algorithm: + + -# If the current array shape and the type match the new ones, return immediately. Otherwise, + de-reference the previous data by calling Mat::release. + -# Initialize the new header. + -# Allocate the new data of total()\*elemSize() bytes. + -# Allocate the new, associated with the data, reference counter and set it to 1. + + Such a scheme makes the memory management robust and efficient at the same time and helps avoid + extra typing for you. This means that usually there is no need to explicitly allocate output arrays. + That is, instead of writing: + @code + Mat color; + ... + Mat gray(color.rows, color.cols, color.depth()); + cvtColor(color, gray, COLOR_BGR2GRAY); + @endcode + you can simply write: + @code + Mat color; + ... + Mat gray; + cvtColor(color, gray, COLOR_BGR2GRAY); + @endcode + because cvtColor, as well as the most of OpenCV functions, calls Mat::create() for the output array + internally. + @param rows New number of rows. + @param cols New number of columns. + @param type New matrix type. + */ + void create(int rows, int cols, int type); + + /** @overload + @param size Alternative new matrix size specification: Size(cols, rows) + @param type New matrix type. + */ + void create(Size size, int type); + + /** @overload + @param ndims New array dimensionality. + @param sizes Array of integers specifying a new array shape. + @param type New matrix type. + */ + void create(int ndims, const int* sizes, int type); + + /** @overload + @param sizes Array of integers specifying a new array shape. + @param type New matrix type. + */ + void create(const std::vector& sizes, int type); + + /** @brief Increments the reference counter. + + The method increments the reference counter associated with the matrix data. If the matrix header + points to an external data set (see Mat::Mat ), the reference counter is NULL, and the method has no + effect in this case. Normally, to avoid memory leaks, the method should not be called explicitly. It + is called implicitly by the matrix assignment operator. The reference counter increment is an atomic + operation on the platforms that support it. Thus, it is safe to operate on the same matrices + asynchronously in different threads. + */ + void addref(); + + /** @brief Decrements the reference counter and deallocates the matrix if needed. + + The method decrements the reference counter associated with the matrix data. When the reference + counter reaches 0, the matrix data is deallocated and the data and the reference counter pointers + are set to NULL's. If the matrix header points to an external data set (see Mat::Mat ), the + reference counter is NULL, and the method has no effect in this case. + + This method can be called manually to force the matrix data deallocation. But since this method is + automatically called in the destructor, or by any other method that changes the data pointer, it is + usually not needed. The reference counter decrement and check for 0 is an atomic operation on the + platforms that support it. Thus, it is safe to operate on the same matrices asynchronously in + different threads. + */ + void release(); + + //! internal use function, consider to use 'release' method instead; deallocates the matrix data + void deallocate(); + //! internal use function; properly re-allocates _size, _step arrays + void copySize(const Mat& m); + + /** @brief Reserves space for the certain number of rows. + + The method reserves space for sz rows. If the matrix already has enough space to store sz rows, + nothing happens. If the matrix is reallocated, the first Mat::rows rows are preserved. The method + emulates the corresponding method of the STL vector class. + @param sz Number of rows. + */ + void reserve(size_t sz); + + /** @brief Reserves space for the certain number of bytes. + + The method reserves space for sz bytes. If the matrix already has enough space to store sz bytes, + nothing happens. If matrix has to be reallocated its previous content could be lost. + @param sz Number of bytes. + */ + void reserveBuffer(size_t sz); + + /** @brief Changes the number of matrix rows. + + The methods change the number of matrix rows. If the matrix is reallocated, the first + min(Mat::rows, sz) rows are preserved. The methods emulate the corresponding methods of the STL + vector class. + @param sz New number of rows. + */ + void resize(size_t sz); + + /** @overload + @param sz New number of rows. + @param s Value assigned to the newly added elements. + */ + void resize(size_t sz, const Scalar& s); + + //! internal function + void push_back_(const void* elem); + + /** @brief Adds elements to the bottom of the matrix. + + The methods add one or more elements to the bottom of the matrix. They emulate the corresponding + method of the STL vector class. When elem is Mat , its type and the number of columns must be the + same as in the container matrix. + @param elem Added element(s). + */ + template void push_back(const _Tp& elem); + + /** @overload + @param elem Added element(s). + */ + template void push_back(const Mat_<_Tp>& elem); + + /** @overload + @param elem Added element(s). + */ + template void push_back(const std::vector<_Tp>& elem); + + /** @overload + @param m Added line(s). + */ + void push_back(const Mat& m); + + /** @brief Removes elements from the bottom of the matrix. + + The method removes one or more rows from the bottom of the matrix. + @param nelems Number of removed rows. If it is greater than the total number of rows, an exception + is thrown. + */ + void pop_back(size_t nelems=1); + + /** @brief Locates the matrix header within a parent matrix. + + After you extracted a submatrix from a matrix using Mat::row, Mat::col, Mat::rowRange, + Mat::colRange, and others, the resultant submatrix points just to the part of the original big + matrix. However, each submatrix contains information (represented by datastart and dataend + fields) that helps reconstruct the original matrix size and the position of the extracted + submatrix within the original matrix. The method locateROI does exactly that. + @param wholeSize Output parameter that contains the size of the whole matrix containing *this* + as a part. + @param ofs Output parameter that contains an offset of *this* inside the whole matrix. + */ + void locateROI( Size& wholeSize, Point& ofs ) const; + + /** @brief Adjusts a submatrix size and position within the parent matrix. + + The method is complimentary to Mat::locateROI . The typical use of these functions is to determine + the submatrix position within the parent matrix and then shift the position somehow. Typically, it + can be required for filtering operations when pixels outside of the ROI should be taken into + account. When all the method parameters are positive, the ROI needs to grow in all directions by the + specified amount, for example: + @code + A.adjustROI(2, 2, 2, 2); + @endcode + In this example, the matrix size is increased by 4 elements in each direction. The matrix is shifted + by 2 elements to the left and 2 elements up, which brings in all the necessary pixels for the + filtering with the 5x5 kernel. + + adjustROI forces the adjusted ROI to be inside of the parent matrix that is boundaries of the + adjusted ROI are constrained by boundaries of the parent matrix. For example, if the submatrix A is + located in the first row of a parent matrix and you called A.adjustROI(2, 2, 2, 2) then A will not + be increased in the upward direction. + + The function is used internally by the OpenCV filtering functions, like filter2D , morphological + operations, and so on. + @param dtop Shift of the top submatrix boundary upwards. + @param dbottom Shift of the bottom submatrix boundary downwards. + @param dleft Shift of the left submatrix boundary to the left. + @param dright Shift of the right submatrix boundary to the right. + @sa copyMakeBorder + */ + Mat& adjustROI( int dtop, int dbottom, int dleft, int dright ); + + /** @brief Extracts a rectangular submatrix. + + The operators make a new header for the specified sub-array of \*this . They are the most + generalized forms of Mat::row, Mat::col, Mat::rowRange, and Mat::colRange . For example, + `A(Range(0, 10), Range::all())` is equivalent to `A.rowRange(0, 10)`. Similarly to all of the above, + the operators are O(1) operations, that is, no matrix data is copied. + @param rowRange Start and end row of the extracted submatrix. The upper boundary is not included. To + select all the rows, use Range::all(). + @param colRange Start and end column of the extracted submatrix. The upper boundary is not included. + To select all the columns, use Range::all(). + */ + Mat operator()( Range rowRange, Range colRange ) const; + + /** @overload + @param roi Extracted submatrix specified as a rectangle. + */ + Mat operator()( const Rect& roi ) const; + + /** @overload + @param ranges Array of selected ranges along each array dimension. + */ + Mat operator()( const Range* ranges ) const; + + /** @overload + @param ranges Array of selected ranges along each array dimension. + */ + Mat operator()(const std::vector& ranges) const; + + template operator std::vector<_Tp>() const; + template operator Vec<_Tp, n>() const; + template operator Matx<_Tp, m, n>() const; + + template operator std::array<_Tp, _Nm>() const; + + /** @brief Reports whether the matrix is continuous or not. + + The method returns true if the matrix elements are stored continuously without gaps at the end of + each row. Otherwise, it returns false. Obviously, 1x1 or 1xN matrices are always continuous. + Matrices created with Mat::create are always continuous. But if you extract a part of the matrix + using Mat::col, Mat::diag, and so on, or constructed a matrix header for externally allocated data, + such matrices may no longer have this property. + + The continuity flag is stored as a bit in the Mat::flags field and is computed automatically when + you construct a matrix header. Thus, the continuity check is a very fast operation, though + theoretically it could be done as follows: + @code + // alternative implementation of Mat::isContinuous() + bool myCheckMatContinuity(const Mat& m) + { + //return (m.flags & Mat::CONTINUOUS_FLAG) != 0; + return m.rows == 1 || m.step == m.cols*m.elemSize(); + } + @endcode + The method is used in quite a few of OpenCV functions. The point is that element-wise operations + (such as arithmetic and logical operations, math functions, alpha blending, color space + transformations, and others) do not depend on the image geometry. Thus, if all the input and output + arrays are continuous, the functions can process them as very long single-row vectors. The example + below illustrates how an alpha-blending function can be implemented: + @code + template + void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst) + { + const float alpha_scale = (float)std::numeric_limits::max(), + inv_scale = 1.f/alpha_scale; + + CV_Assert( src1.type() == src2.type() && + src1.type() == CV_MAKETYPE(traits::Depth::value, 4) && + src1.size() == src2.size()); + Size size = src1.size(); + dst.create(size, src1.type()); + + // here is the idiom: check the arrays for continuity and, + // if this is the case, + // treat the arrays as 1D vectors + if( src1.isContinuous() && src2.isContinuous() && dst.isContinuous() ) + { + size.width *= size.height; + size.height = 1; + } + size.width *= 4; + + for( int i = 0; i < size.height; i++ ) + { + // when the arrays are continuous, + // the outer loop is executed only once + const T* ptr1 = src1.ptr(i); + const T* ptr2 = src2.ptr(i); + T* dptr = dst.ptr(i); + + for( int j = 0; j < size.width; j += 4 ) + { + float alpha = ptr1[j+3]*inv_scale, beta = ptr2[j+3]*inv_scale; + dptr[j] = saturate_cast(ptr1[j]*alpha + ptr2[j]*beta); + dptr[j+1] = saturate_cast(ptr1[j+1]*alpha + ptr2[j+1]*beta); + dptr[j+2] = saturate_cast(ptr1[j+2]*alpha + ptr2[j+2]*beta); + dptr[j+3] = saturate_cast((1 - (1-alpha)*(1-beta))*alpha_scale); + } + } + } + @endcode + This approach, while being very simple, can boost the performance of a simple element-operation by + 10-20 percents, especially if the image is rather small and the operation is quite simple. + + Another OpenCV idiom in this function, a call of Mat::create for the destination array, that + allocates the destination array unless it already has the proper size and type. And while the newly + allocated arrays are always continuous, you still need to check the destination array because + Mat::create does not always allocate a new matrix. + */ + bool isContinuous() const; + + //! returns true if the matrix is a submatrix of another matrix + bool isSubmatrix() const; + + /** @brief Returns the matrix element size in bytes. + + The method returns the matrix element size in bytes. For example, if the matrix type is CV_16SC3 , + the method returns 3\*sizeof(short) or 6. + */ + size_t elemSize() const; + + /** @brief Returns the size of each matrix element channel in bytes. + + The method returns the matrix element channel size in bytes, that is, it ignores the number of + channels. For example, if the matrix type is CV_16SC3 , the method returns sizeof(short) or 2. + */ + size_t elemSize1() const; + + /** @brief Returns the type of a matrix element. + + The method returns a matrix element type. This is an identifier compatible with the CvMat type + system, like CV_16SC3 or 16-bit signed 3-channel array, and so on. + */ + int type() const; + + /** @brief Returns the depth of a matrix element. + + The method returns the identifier of the matrix element depth (the type of each individual channel). + For example, for a 16-bit signed element array, the method returns CV_16S . A complete list of + matrix types contains the following values: + - CV_8U - 8-bit unsigned integers ( 0..255 ) + - CV_8S - 8-bit signed integers ( -128..127 ) + - CV_16U - 16-bit unsigned integers ( 0..65535 ) + - CV_16S - 16-bit signed integers ( -32768..32767 ) + - CV_32S - 32-bit signed integers ( -2147483648..2147483647 ) + - CV_32F - 32-bit floating-point numbers ( -FLT_MAX..FLT_MAX, INF, NAN ) + - CV_64F - 64-bit floating-point numbers ( -DBL_MAX..DBL_MAX, INF, NAN ) + */ + int depth() const; + + /** @brief Returns the number of matrix channels. + + The method returns the number of matrix channels. + */ + int channels() const; + + /** @brief Returns a normalized step. + + The method returns a matrix step divided by Mat::elemSize1() . It can be useful to quickly access an + arbitrary matrix element. + */ + size_t step1(int i=0) const; + + /** @brief Returns true if the array has no elements. + + The method returns true if Mat::total() is 0 or if Mat::data is NULL. Because of pop_back() and + resize() methods `M.total() == 0` does not imply that `M.data == NULL`. + */ + bool empty() const; + + /** @brief Returns the total number of array elements. + + The method returns the number of array elements (a number of pixels if the array represents an + image). + */ + size_t total() const; + + /** @brief Returns the total number of array elements. + + The method returns the number of elements within a certain sub-array slice with startDim <= dim < endDim + */ + size_t total(int startDim, int endDim=INT_MAX) const; + + /** + * @param elemChannels Number of channels or number of columns the matrix should have. + * For a 2-D matrix, when the matrix has only 1 column, then it should have + * elemChannels channels; When the matrix has only 1 channel, + * then it should have elemChannels columns. + * For a 3-D matrix, it should have only one channel. Furthermore, + * if the number of planes is not one, then the number of rows + * within every plane has to be 1; if the number of rows within + * every plane is not 1, then the number of planes has to be 1. + * @param depth The depth the matrix should have. Set it to -1 when any depth is fine. + * @param requireContinuous Set it to true to require the matrix to be continuous + * @return -1 if the requirement is not satisfied. + * Otherwise, it returns the number of elements in the matrix. Note + * that an element may have multiple channels. + * + * The following code demonstrates its usage for a 2-d matrix: + * @snippet snippets/core_mat_checkVector.cpp example-2d + * + * The following code demonstrates its usage for a 3-d matrix: + * @snippet snippets/core_mat_checkVector.cpp example-3d + */ + int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const; + + /** @brief Returns a pointer to the specified matrix row. + + The methods return `uchar*` or typed pointer to the specified matrix row. See the sample in + Mat::isContinuous to know how to use these methods. + @param i0 A 0-based row index. + */ + uchar* ptr(int i0=0); + /** @overload */ + const uchar* ptr(int i0=0) const; + + /** @overload + @param row Index along the dimension 0 + @param col Index along the dimension 1 + */ + uchar* ptr(int row, int col); + /** @overload + @param row Index along the dimension 0 + @param col Index along the dimension 1 + */ + const uchar* ptr(int row, int col) const; + + /** @overload */ + uchar* ptr(int i0, int i1, int i2); + /** @overload */ + const uchar* ptr(int i0, int i1, int i2) const; + + /** @overload */ + uchar* ptr(const int* idx); + /** @overload */ + const uchar* ptr(const int* idx) const; + /** @overload */ + template uchar* ptr(const Vec& idx); + /** @overload */ + template const uchar* ptr(const Vec& idx) const; + + /** @overload */ + template _Tp* ptr(int i0=0); + /** @overload */ + template const _Tp* ptr(int i0=0) const; + /** @overload + @param row Index along the dimension 0 + @param col Index along the dimension 1 + */ + template _Tp* ptr(int row, int col); + /** @overload + @param row Index along the dimension 0 + @param col Index along the dimension 1 + */ + template const _Tp* ptr(int row, int col) const; + /** @overload */ + template _Tp* ptr(int i0, int i1, int i2); + /** @overload */ + template const _Tp* ptr(int i0, int i1, int i2) const; + /** @overload */ + template _Tp* ptr(const int* idx); + /** @overload */ + template const _Tp* ptr(const int* idx) const; + /** @overload */ + template _Tp* ptr(const Vec& idx); + /** @overload */ + template const _Tp* ptr(const Vec& idx) const; + + /** @brief Returns a reference to the specified array element. + + The template methods return a reference to the specified array element. For the sake of higher + performance, the index range checks are only performed in the Debug configuration. + + Note that the variants with a single index (i) can be used to access elements of single-row or + single-column 2-dimensional arrays. That is, if, for example, A is a 1 x N floating-point matrix and + B is an M x 1 integer matrix, you can simply write `A.at(k+4)` and `B.at(2*i+1)` + instead of `A.at(0,k+4)` and `B.at(2*i+1,0)`, respectively. + + The example below initializes a Hilbert matrix: + @code + Mat H(100, 100, CV_64F); + for(int i = 0; i < H.rows; i++) + for(int j = 0; j < H.cols; j++) + H.at(i,j)=1./(i+j+1); + @endcode + + Keep in mind that the size identifier used in the at operator cannot be chosen at random. It depends + on the image from which you are trying to retrieve the data. The table below gives a better insight in this: + - If matrix is of type `CV_8U` then use `Mat.at(y,x)`. + - If matrix is of type `CV_8S` then use `Mat.at(y,x)`. + - If matrix is of type `CV_16U` then use `Mat.at(y,x)`. + - If matrix is of type `CV_16S` then use `Mat.at(y,x)`. + - If matrix is of type `CV_32S` then use `Mat.at(y,x)`. + - If matrix is of type `CV_32F` then use `Mat.at(y,x)`. + - If matrix is of type `CV_64F` then use `Mat.at(y,x)`. + + @param i0 Index along the dimension 0 + */ + template _Tp& at(int i0=0); + /** @overload + @param i0 Index along the dimension 0 + */ + template const _Tp& at(int i0=0) const; + /** @overload + @param row Index along the dimension 0 + @param col Index along the dimension 1 + */ + template _Tp& at(int row, int col); + /** @overload + @param row Index along the dimension 0 + @param col Index along the dimension 1 + */ + template const _Tp& at(int row, int col) const; + + /** @overload + @param i0 Index along the dimension 0 + @param i1 Index along the dimension 1 + @param i2 Index along the dimension 2 + */ + template _Tp& at(int i0, int i1, int i2); + /** @overload + @param i0 Index along the dimension 0 + @param i1 Index along the dimension 1 + @param i2 Index along the dimension 2 + */ + template const _Tp& at(int i0, int i1, int i2) const; + + /** @overload + @param idx Array of Mat::dims indices. + */ + template _Tp& at(const int* idx); + /** @overload + @param idx Array of Mat::dims indices. + */ + template const _Tp& at(const int* idx) const; + + /** @overload */ + template _Tp& at(const Vec& idx); + /** @overload */ + template const _Tp& at(const Vec& idx) const; + + /** @overload + special versions for 2D arrays (especially convenient for referencing image pixels) + @param pt Element position specified as Point(j,i) . + */ + template _Tp& at(Point pt); + /** @overload + special versions for 2D arrays (especially convenient for referencing image pixels) + @param pt Element position specified as Point(j,i) . + */ + template const _Tp& at(Point pt) const; + + /** @brief Returns the matrix iterator and sets it to the first matrix element. + + The methods return the matrix read-only or read-write iterators. The use of matrix iterators is very + similar to the use of bi-directional STL iterators. In the example below, the alpha blending + function is rewritten using the matrix iterators: + @code + template + void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst) + { + typedef Vec VT; + + const float alpha_scale = (float)std::numeric_limits::max(), + inv_scale = 1.f/alpha_scale; + + CV_Assert( src1.type() == src2.type() && + src1.type() == traits::Type::value && + src1.size() == src2.size()); + Size size = src1.size(); + dst.create(size, src1.type()); + + MatConstIterator_ it1 = src1.begin(), it1_end = src1.end(); + MatConstIterator_ it2 = src2.begin(); + MatIterator_ dst_it = dst.begin(); + + for( ; it1 != it1_end; ++it1, ++it2, ++dst_it ) + { + VT pix1 = *it1, pix2 = *it2; + float alpha = pix1[3]*inv_scale, beta = pix2[3]*inv_scale; + *dst_it = VT(saturate_cast(pix1[0]*alpha + pix2[0]*beta), + saturate_cast(pix1[1]*alpha + pix2[1]*beta), + saturate_cast(pix1[2]*alpha + pix2[2]*beta), + saturate_cast((1 - (1-alpha)*(1-beta))*alpha_scale)); + } + } + @endcode + */ + template MatIterator_<_Tp> begin(); + template MatConstIterator_<_Tp> begin() const; + + /** @brief Same as begin() but for inverse traversal + */ + template std::reverse_iterator> rbegin(); + template std::reverse_iterator> rbegin() const; + + /** @brief Returns the matrix iterator and sets it to the after-last matrix element. + + The methods return the matrix read-only or read-write iterators, set to the point following the last + matrix element. + */ + template MatIterator_<_Tp> end(); + template MatConstIterator_<_Tp> end() const; + + /** @brief Same as end() but for inverse traversal + */ + template std::reverse_iterator< MatIterator_<_Tp>> rend(); + template std::reverse_iterator< MatConstIterator_<_Tp>> rend() const; + + + /** @brief Runs the given functor over all matrix elements in parallel. + + The operation passed as argument has to be a function pointer, a function object or a lambda(C++11). + + Example 1. All of the operations below put 0xFF the first channel of all matrix elements: + @code + Mat image(1920, 1080, CV_8UC3); + typedef cv::Point3_ Pixel; + + // first. raw pointer access. + for (int r = 0; r < image.rows; ++r) { + Pixel* ptr = image.ptr(r, 0); + const Pixel* ptr_end = ptr + image.cols; + for (; ptr != ptr_end; ++ptr) { + ptr->x = 255; + } + } + + // Using MatIterator. (Simple but there are a Iterator's overhead) + for (Pixel &p : cv::Mat_(image)) { + p.x = 255; + } + + // Parallel execution with function object. + struct Operator { + void operator ()(Pixel &pixel, const int * position) { + pixel.x = 255; + } + }; + image.forEach(Operator()); + + // Parallel execution using C++11 lambda. + image.forEach([](Pixel &p, const int * position) -> void { + p.x = 255; + }); + @endcode + Example 2. Using the pixel's position: + @code + // Creating 3D matrix (255 x 255 x 255) typed uint8_t + // and initialize all elements by the value which equals elements position. + // i.e. pixels (x,y,z) = (1,2,3) is (b,g,r) = (1,2,3). + + int sizes[] = { 255, 255, 255 }; + typedef cv::Point3_ Pixel; + + Mat_ image = Mat::zeros(3, sizes, CV_8UC3); + + image.forEach([](Pixel& pixel, const int position[]) -> void { + pixel.x = position[0]; + pixel.y = position[1]; + pixel.z = position[2]; + }); + @endcode + */ + template void forEach(const Functor& operation); + /** @overload */ + template void forEach(const Functor& operation) const; + + Mat(Mat&& m) CV_NOEXCEPT; + Mat& operator = (Mat&& m); + + enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG }; + enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 }; + + /*! includes several bit-fields: + - the magic signature + - continuity flag + - depth + - number of channels + */ + int flags; + //! the matrix dimensionality, >= 2 + int dims; + //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions + int rows, cols; + //! pointer to the data + uchar* data; + + //! helper fields used in locateROI and adjustROI + const uchar* datastart; + const uchar* dataend; + const uchar* datalimit; + + //! custom allocator + MatAllocator* allocator; + //! and the standard allocator + static MatAllocator* getStdAllocator(); + static MatAllocator* getDefaultAllocator(); + static void setDefaultAllocator(MatAllocator* allocator); + + //! internal use method: updates the continuity flag + void updateContinuityFlag(); + + //! interaction with UMat + UMatData* u; + + MatSize size; + MatStep step; + +protected: + template void forEach_impl(const Functor& operation); +}; + + +///////////////////////////////// Mat_<_Tp> //////////////////////////////////// + +/** @brief Template matrix class derived from Mat + +@code{.cpp} + template class Mat_ : public Mat + { + public: + // ... some specific methods + // and + // no new extra fields + }; +@endcode +The class `Mat_<_Tp>` is a *thin* template wrapper on top of the Mat class. It does not have any +extra data fields. Nor this class nor Mat has any virtual methods. Thus, references or pointers to +these two classes can be freely but carefully converted one to another. For example: +@code{.cpp} + // create a 100x100 8-bit matrix + Mat M(100,100,CV_8U); + // this will be compiled fine. no any data conversion will be done. + Mat_& M1 = (Mat_&)M; + // the program is likely to crash at the statement below + M1(99,99) = 1.f; +@endcode +While Mat is sufficient in most cases, Mat_ can be more convenient if you use a lot of element +access operations and if you know matrix type at the compilation time. Note that +`Mat::at(int y,int x)` and `Mat_::operator()(int y,int x)` do absolutely the same +and run at the same speed, but the latter is certainly shorter: +@code{.cpp} + Mat_ M(20,20); + for(int i = 0; i < M.rows; i++) + for(int j = 0; j < M.cols; j++) + M(i,j) = 1./(i+j+1); + Mat E, V; + eigen(M,E,V); + cout << E.at(0,0)/E.at(M.rows-1,0); +@endcode +To use Mat_ for multi-channel images/matrices, pass Vec as a Mat_ parameter: +@code{.cpp} + // allocate a 320x240 color image and fill it with green (in RGB space) + Mat_ img(240, 320, Vec3b(0,255,0)); + // now draw a diagonal white line + for(int i = 0; i < 100; i++) + img(i,i)=Vec3b(255,255,255); + // and now scramble the 2nd (red) channel of each pixel + for(int i = 0; i < img.rows; i++) + for(int j = 0; j < img.cols; j++) + img(i,j)[2] ^= (uchar)(i ^ j); +@endcode +Mat_ is fully compatible with C++11 range-based for loop. For example such loop +can be used to safely apply look-up table: +@code{.cpp} +void applyTable(Mat_& I, const uchar* const table) +{ + for(auto& pixel : I) + { + pixel = table[pixel]; + } +} +@endcode + */ +template class Mat_ : public Mat +{ +public: + typedef _Tp value_type; + typedef typename DataType<_Tp>::channel_type channel_type; + typedef MatIterator_<_Tp> iterator; + typedef MatConstIterator_<_Tp> const_iterator; + + //! default constructor + Mat_() CV_NOEXCEPT; + //! equivalent to Mat(_rows, _cols, DataType<_Tp>::type) + Mat_(int _rows, int _cols); + //! constructor that sets each matrix element to specified value + Mat_(int _rows, int _cols, const _Tp& value); + //! equivalent to Mat(_size, DataType<_Tp>::type) + explicit Mat_(Size _size); + //! constructor that sets each matrix element to specified value + Mat_(Size _size, const _Tp& value); + //! n-dim array constructor + Mat_(int _ndims, const int* _sizes); + //! n-dim array constructor that sets each matrix element to specified value + Mat_(int _ndims, const int* _sizes, const _Tp& value); + //! copy/conversion constructor. If m is of different type, it's converted + Mat_(const Mat& m); + //! copy constructor + Mat_(const Mat_& m); + //! constructs a matrix on top of user-allocated data. step is in bytes(!!!), regardless of the type + Mat_(int _rows, int _cols, _Tp* _data, size_t _step=AUTO_STEP); + //! constructs n-dim matrix on top of user-allocated data. steps are in bytes(!!!), regardless of the type + Mat_(int _ndims, const int* _sizes, _Tp* _data, const size_t* _steps=0); + //! selects a submatrix + Mat_(const Mat_& m, const Range& rowRange, const Range& colRange=Range::all()); + //! selects a submatrix + Mat_(const Mat_& m, const Rect& roi); + //! selects a submatrix, n-dim version + Mat_(const Mat_& m, const Range* ranges); + //! selects a submatrix, n-dim version + Mat_(const Mat_& m, const std::vector& ranges); + //! from a matrix expression + explicit Mat_(const MatExpr& e); + //! makes a matrix out of Vec, std::vector, Point_ or Point3_. The matrix will have a single column + explicit Mat_(const std::vector<_Tp>& vec, bool copyData=false); + template explicit Mat_(const Vec::channel_type, n>& vec, bool copyData=true); + template explicit Mat_(const Matx::channel_type, m, n>& mtx, bool copyData=true); + explicit Mat_(const Point_::channel_type>& pt, bool copyData=true); + explicit Mat_(const Point3_::channel_type>& pt, bool copyData=true); + explicit Mat_(const MatCommaInitializer_<_Tp>& commaInitializer); + + Mat_(std::initializer_list<_Tp> values); + explicit Mat_(const std::initializer_list sizes, const std::initializer_list<_Tp> values); + + template explicit Mat_(const std::array<_Tp, _Nm>& arr, bool copyData=false); + + Mat_& operator = (const Mat& m); + Mat_& operator = (const Mat_& m); + //! set all the elements to s. + Mat_& operator = (const _Tp& s); + //! assign a matrix expression + Mat_& operator = (const MatExpr& e); + + //! iterators; they are smart enough to skip gaps in the end of rows + iterator begin(); + iterator end(); + const_iterator begin() const; + const_iterator end() const; + + //reverse iterators + std::reverse_iterator rbegin(); + std::reverse_iterator rend(); + std::reverse_iterator rbegin() const; + std::reverse_iterator rend() const; + + //! template methods for operation over all matrix elements. + // the operations take care of skipping gaps in the end of rows (if any) + template void forEach(const Functor& operation); + template void forEach(const Functor& operation) const; + + //! equivalent to Mat::create(_rows, _cols, DataType<_Tp>::type) + void create(int _rows, int _cols); + //! equivalent to Mat::create(_size, DataType<_Tp>::type) + void create(Size _size); + //! equivalent to Mat::create(_ndims, _sizes, DatType<_Tp>::type) + void create(int _ndims, const int* _sizes); + //! equivalent to Mat::release() + void release(); + //! cross-product + Mat_ cross(const Mat_& m) const; + //! data type conversion + template operator Mat_() const; + //! overridden forms of Mat::row() etc. + Mat_ row(int y) const; + Mat_ col(int x) const; + Mat_ diag(int d=0) const; + CV_NODISCARD_STD Mat_ clone() const; + + //! overridden forms of Mat::elemSize() etc. + size_t elemSize() const; + size_t elemSize1() const; + int type() const; + int depth() const; + int channels() const; + size_t step1(int i=0) const; + //! returns step()/sizeof(_Tp) + size_t stepT(int i=0) const; + + //! overridden forms of Mat::zeros() etc. Data type is omitted, of course + CV_NODISCARD_STD static MatExpr zeros(int rows, int cols); + CV_NODISCARD_STD static MatExpr zeros(Size size); + CV_NODISCARD_STD static MatExpr zeros(int _ndims, const int* _sizes); + CV_NODISCARD_STD static MatExpr ones(int rows, int cols); + CV_NODISCARD_STD static MatExpr ones(Size size); + CV_NODISCARD_STD static MatExpr ones(int _ndims, const int* _sizes); + CV_NODISCARD_STD static MatExpr eye(int rows, int cols); + CV_NODISCARD_STD static MatExpr eye(Size size); + + //! some more overridden methods + Mat_& adjustROI( int dtop, int dbottom, int dleft, int dright ); + Mat_ operator()( const Range& rowRange, const Range& colRange ) const; + Mat_ operator()( const Rect& roi ) const; + Mat_ operator()( const Range* ranges ) const; + Mat_ operator()(const std::vector& ranges) const; + + //! more convenient forms of row and element access operators + _Tp* operator [](int y); + const _Tp* operator [](int y) const; + + //! returns reference to the specified element + _Tp& operator ()(const int* idx); + //! returns read-only reference to the specified element + const _Tp& operator ()(const int* idx) const; + + //! returns reference to the specified element + template _Tp& operator ()(const Vec& idx); + //! returns read-only reference to the specified element + template const _Tp& operator ()(const Vec& idx) const; + + //! returns reference to the specified element (1D case) + _Tp& operator ()(int idx0); + //! returns read-only reference to the specified element (1D case) + const _Tp& operator ()(int idx0) const; + //! returns reference to the specified element (2D case) + _Tp& operator ()(int row, int col); + //! returns read-only reference to the specified element (2D case) + const _Tp& operator ()(int row, int col) const; + //! returns reference to the specified element (3D case) + _Tp& operator ()(int idx0, int idx1, int idx2); + //! returns read-only reference to the specified element (3D case) + const _Tp& operator ()(int idx0, int idx1, int idx2) const; + + _Tp& operator ()(Point pt); + const _Tp& operator ()(Point pt) const; + + //! conversion to vector. + operator std::vector<_Tp>() const; + + //! conversion to array. + template operator std::array<_Tp, _Nm>() const; + + //! conversion to Vec + template operator Vec::channel_type, n>() const; + //! conversion to Matx + template operator Matx::channel_type, m, n>() const; + + Mat_(Mat_&& m); + Mat_& operator = (Mat_&& m); + + Mat_(Mat&& m); + Mat_& operator = (Mat&& m); + + Mat_(MatExpr&& e); +}; + +typedef Mat_ Mat1b; +typedef Mat_ Mat2b; +typedef Mat_ Mat3b; +typedef Mat_ Mat4b; + +typedef Mat_ Mat1s; +typedef Mat_ Mat2s; +typedef Mat_ Mat3s; +typedef Mat_ Mat4s; + +typedef Mat_ Mat1w; +typedef Mat_ Mat2w; +typedef Mat_ Mat3w; +typedef Mat_ Mat4w; + +typedef Mat_ Mat1i; +typedef Mat_ Mat2i; +typedef Mat_ Mat3i; +typedef Mat_ Mat4i; + +typedef Mat_ Mat1f; +typedef Mat_ Mat2f; +typedef Mat_ Mat3f; +typedef Mat_ Mat4f; + +typedef Mat_ Mat1d; +typedef Mat_ Mat2d; +typedef Mat_ Mat3d; +typedef Mat_ Mat4d; + +/** @todo document */ +class CV_EXPORTS UMat +{ +public: + //! default constructor + UMat(UMatUsageFlags usageFlags = USAGE_DEFAULT) CV_NOEXCEPT; + //! constructs 2D matrix of the specified size and type + // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.) + UMat(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); + UMat(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); + //! constructs 2D matrix and fills it with the specified value _s. + UMat(int rows, int cols, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT); + UMat(Size size, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT); + + //! constructs n-dimensional matrix + UMat(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); + UMat(int ndims, const int* sizes, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT); + + //! copy constructor + UMat(const UMat& m); + + //! creates a matrix header for a part of the bigger matrix + UMat(const UMat& m, const Range& rowRange, const Range& colRange=Range::all()); + UMat(const UMat& m, const Rect& roi); + UMat(const UMat& m, const Range* ranges); + UMat(const UMat& m, const std::vector& ranges); + + // FIXIT copyData=false is not implemented, drop this in favor of cv::Mat (OpenCV 5.0) + //! builds matrix from std::vector with or without copying the data + template explicit UMat(const std::vector<_Tp>& vec, bool copyData=false); + + //! destructor - calls release() + ~UMat(); + //! assignment operators + UMat& operator = (const UMat& m); + + Mat getMat(AccessFlag flags) const; + + //! returns a new matrix header for the specified row + UMat row(int y) const; + //! returns a new matrix header for the specified column + UMat col(int x) const; + //! ... for the specified row span + UMat rowRange(int startrow, int endrow) const; + UMat rowRange(const Range& r) const; + //! ... for the specified column span + UMat colRange(int startcol, int endcol) const; + UMat colRange(const Range& r) const; + //! ... for the specified diagonal + //! (d=0 - the main diagonal, + //! >0 - a diagonal from the upper half, + //! <0 - a diagonal from the lower half) + UMat diag(int d=0) const; + //! constructs a square diagonal matrix which main diagonal is vector "d" + CV_NODISCARD_STD static UMat diag(const UMat& d, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); + CV_NODISCARD_STD static UMat diag(const UMat& d) { return diag(d, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload + + //! returns deep copy of the matrix, i.e. the data is copied + CV_NODISCARD_STD UMat clone() const; + //! copies the matrix content to "m". + // It calls m.create(this->size(), this->type()). + void copyTo( OutputArray m ) const; + //! copies those matrix elements to "m" that are marked with non-zero mask elements. + void copyTo( OutputArray m, InputArray mask ) const; + //! converts matrix to another datatype with optional scaling. See cvConvertScale. + void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const; + + void assignTo( UMat& m, int type=-1 ) const; + + //! sets every matrix element to s + UMat& operator = (const Scalar& s); + //! sets some of the matrix elements to s, according to the mask + UMat& setTo(InputArray value, InputArray mask=noArray()); + //! creates alternative matrix header for the same data, with different + // number of channels and/or different number of rows. see cvReshape. + UMat reshape(int cn, int rows=0) const; + UMat reshape(int cn, int newndims, const int* newsz) const; + + //! matrix transposition by means of matrix expressions + UMat t() const; + //! matrix inversion by means of matrix expressions + UMat inv(int method=DECOMP_LU) const; + //! per-element matrix multiplication by means of matrix expressions + UMat mul(InputArray m, double scale=1) const; + + //! computes dot-product + double dot(InputArray m) const; + + //! Matlab-style matrix initialization + CV_NODISCARD_STD static UMat zeros(int rows, int cols, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); + CV_NODISCARD_STD static UMat zeros(Size size, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); + CV_NODISCARD_STD static UMat zeros(int ndims, const int* sz, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); + CV_NODISCARD_STD static UMat zeros(int rows, int cols, int type) { return zeros(rows, cols, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload + CV_NODISCARD_STD static UMat zeros(Size size, int type) { return zeros(size, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload + CV_NODISCARD_STD static UMat zeros(int ndims, const int* sz, int type) { return zeros(ndims, sz, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload + CV_NODISCARD_STD static UMat ones(int rows, int cols, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); + CV_NODISCARD_STD static UMat ones(Size size, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); + CV_NODISCARD_STD static UMat ones(int ndims, const int* sz, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); + CV_NODISCARD_STD static UMat ones(int rows, int cols, int type) { return ones(rows, cols, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload + CV_NODISCARD_STD static UMat ones(Size size, int type) { return ones(size, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload + CV_NODISCARD_STD static UMat ones(int ndims, const int* sz, int type) { return ones(ndims, sz, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload + CV_NODISCARD_STD static UMat eye(int rows, int cols, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); + CV_NODISCARD_STD static UMat eye(Size size, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); + CV_NODISCARD_STD static UMat eye(int rows, int cols, int type) { return eye(rows, cols, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload + CV_NODISCARD_STD static UMat eye(Size size, int type) { return eye(size, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload + + //! allocates new matrix data unless the matrix already has specified size and type. + // previous data is unreferenced if needed. + void create(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); + void create(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); + void create(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); + void create(const std::vector& sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); + + //! increases the reference counter; use with care to avoid memleaks + void addref(); + //! decreases reference counter; + // deallocates the data when reference counter reaches 0. + void release(); + + //! deallocates the matrix data + void deallocate(); + //! internal use function; properly re-allocates _size, _step arrays + void copySize(const UMat& m); + + //! locates matrix header within a parent matrix. See below + void locateROI( Size& wholeSize, Point& ofs ) const; + //! moves/resizes the current matrix ROI inside the parent matrix. + UMat& adjustROI( int dtop, int dbottom, int dleft, int dright ); + //! extracts a rectangular sub-matrix + // (this is a generalized form of row, rowRange etc.) + UMat operator()( Range rowRange, Range colRange ) const; + UMat operator()( const Rect& roi ) const; + UMat operator()( const Range* ranges ) const; + UMat operator()(const std::vector& ranges) const; + + //! returns true iff the matrix data is continuous + // (i.e. when there are no gaps between successive rows). + // similar to CV_IS_MAT_CONT(cvmat->type) + bool isContinuous() const; + + //! returns true if the matrix is a submatrix of another matrix + bool isSubmatrix() const; + + //! returns element size in bytes, + // similar to CV_ELEM_SIZE(cvmat->type) + size_t elemSize() const; + //! returns the size of element channel in bytes. + size_t elemSize1() const; + //! returns element type, similar to CV_MAT_TYPE(cvmat->type) + int type() const; + //! returns element type, similar to CV_MAT_DEPTH(cvmat->type) + int depth() const; + //! returns element type, similar to CV_MAT_CN(cvmat->type) + int channels() const; + //! returns step/elemSize1() + size_t step1(int i=0) const; + //! returns true if matrix data is NULL + bool empty() const; + //! returns the total number of matrix elements + size_t total() const; + + //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise + int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const; + + UMat(UMat&& m); + UMat& operator = (UMat&& m); + + /*! Returns the OpenCL buffer handle on which UMat operates on. + The UMat instance should be kept alive during the use of the handle to prevent the buffer to be + returned to the OpenCV buffer pool. + */ + void* handle(AccessFlag accessFlags) const; + void ndoffset(size_t* ofs) const; + + enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG }; + enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 }; + + /*! includes several bit-fields: + - the magic signature + - continuity flag + - depth + - number of channels + */ + int flags; + + //! the matrix dimensionality, >= 2 + int dims; + + //! number of rows in the matrix; -1 when the matrix has more than 2 dimensions + int rows; + + //! number of columns in the matrix; -1 when the matrix has more than 2 dimensions + int cols; + + //! custom allocator + MatAllocator* allocator; + + //! usage flags for allocator; recommend do not set directly, instead set during construct/create/getUMat + UMatUsageFlags usageFlags; + + //! and the standard allocator + static MatAllocator* getStdAllocator(); + + //! internal use method: updates the continuity flag + void updateContinuityFlag(); + + //! black-box container of UMat data + UMatData* u; + + //! offset of the submatrix (or 0) + size_t offset; + + //! dimensional size of the matrix; accessible in various formats + MatSize size; + + //! number of bytes each matrix element/row/plane/dimension occupies + MatStep step; + +protected: +}; + + +/////////////////////////// multi-dimensional sparse matrix ////////////////////////// + +/** @brief The class SparseMat represents multi-dimensional sparse numerical arrays. + +Such a sparse array can store elements of any type that Mat can store. *Sparse* means that only +non-zero elements are stored (though, as a result of operations on a sparse matrix, some of its +stored elements can actually become 0. It is up to you to detect such elements and delete them +using SparseMat::erase ). The non-zero elements are stored in a hash table that grows when it is +filled so that the search time is O(1) in average (regardless of whether element is there or not). +Elements can be accessed using the following methods: +- Query operations (SparseMat::ptr and the higher-level SparseMat::ref, SparseMat::value and + SparseMat::find), for example: + @code + const int dims = 5; + int size[5] = {10, 10, 10, 10, 10}; + SparseMat sparse_mat(dims, size, CV_32F); + for(int i = 0; i < 1000; i++) + { + int idx[dims]; + for(int k = 0; k < dims; k++) + idx[k] = rand() % size[k]; + sparse_mat.ref(idx) += 1.f; + } + cout << "nnz = " << sparse_mat.nzcount() << endl; + @endcode +- Sparse matrix iterators. They are similar to MatIterator but different from NAryMatIterator. + That is, the iteration loop is familiar to STL users: + @code + // prints elements of a sparse floating-point matrix + // and the sum of elements. + SparseMatConstIterator_ + it = sparse_mat.begin(), + it_end = sparse_mat.end(); + double s = 0; + int dims = sparse_mat.dims(); + for(; it != it_end; ++it) + { + // print element indices and the element value + const SparseMat::Node* n = it.node(); + printf("("); + for(int i = 0; i < dims; i++) + printf("%d%s", n->idx[i], i < dims-1 ? ", " : ")"); + printf(": %g\n", it.value()); + s += *it; + } + printf("Element sum is %g\n", s); + @endcode + If you run this loop, you will notice that elements are not enumerated in a logical order + (lexicographical, and so on). They come in the same order as they are stored in the hash table + (semi-randomly). You may collect pointers to the nodes and sort them to get the proper ordering. + Note, however, that pointers to the nodes may become invalid when you add more elements to the + matrix. This may happen due to possible buffer reallocation. +- Combination of the above 2 methods when you need to process 2 or more sparse matrices + simultaneously. For example, this is how you can compute unnormalized cross-correlation of the 2 + floating-point sparse matrices: + @code + double cross_corr(const SparseMat& a, const SparseMat& b) + { + const SparseMat *_a = &a, *_b = &b; + // if b contains less elements than a, + // it is faster to iterate through b + if(_a->nzcount() > _b->nzcount()) + std::swap(_a, _b); + SparseMatConstIterator_ it = _a->begin(), + it_end = _a->end(); + double ccorr = 0; + for(; it != it_end; ++it) + { + // take the next element from the first matrix + float avalue = *it; + const Node* anode = it.node(); + // and try to find an element with the same index in the second matrix. + // since the hash value depends only on the element index, + // reuse the hash value stored in the node + float bvalue = _b->value(anode->idx,&anode->hashval); + ccorr += avalue*bvalue; + } + return ccorr; + } + @endcode + */ +class CV_EXPORTS SparseMat +{ +public: + typedef SparseMatIterator iterator; + typedef SparseMatConstIterator const_iterator; + + enum { MAGIC_VAL=0x42FD0000, MAX_DIM=32, HASH_SCALE=0x5bd1e995, HASH_BIT=0x80000000 }; + + //! the sparse matrix header + struct CV_EXPORTS Hdr + { + Hdr(int _dims, const int* _sizes, int _type); + void clear(); + int refcount; + int dims; + int valueOffset; + size_t nodeSize; + size_t nodeCount; + size_t freeList; + std::vector pool; + std::vector hashtab; + int size[MAX_DIM]; + }; + + //! sparse matrix node - element of a hash table + struct CV_EXPORTS Node + { + //! hash value + size_t hashval; + //! index of the next node in the same hash table entry + size_t next; + //! index of the matrix element + int idx[MAX_DIM]; + }; + + /** @brief Various SparseMat constructors. + */ + SparseMat(); + + /** @overload + @param dims Array dimensionality. + @param _sizes Sparce matrix size on all dementions. + @param _type Sparse matrix data type. + */ + SparseMat(int dims, const int* _sizes, int _type); + + /** @overload + @param m Source matrix for copy constructor. If m is dense matrix (ocvMat) then it will be converted + to sparse representation. + */ + SparseMat(const SparseMat& m); + + /** @overload + @param m Source matrix for copy constructor. If m is dense matrix (ocvMat) then it will be converted + to sparse representation. + */ + explicit SparseMat(const Mat& m); + + //! the destructor + ~SparseMat(); + + //! assignment operator. This is O(1) operation, i.e. no data is copied + SparseMat& operator = (const SparseMat& m); + //! equivalent to the corresponding constructor + SparseMat& operator = (const Mat& m); + + //! creates full copy of the matrix + CV_NODISCARD_STD SparseMat clone() const; + + //! copies all the data to the destination matrix. All the previous content of m is erased + void copyTo( SparseMat& m ) const; + //! converts sparse matrix to dense matrix. + void copyTo( Mat& m ) const; + //! multiplies all the matrix elements by the specified scale factor alpha and converts the results to the specified data type + void convertTo( SparseMat& m, int rtype, double alpha=1 ) const; + //! converts sparse matrix to dense n-dim matrix with optional type conversion and scaling. + /*! + @param [out] m - output matrix; if it does not have a proper size or type before the operation, + it is reallocated + @param [in] rtype - desired output matrix type or, rather, the depth since the number of channels + are the same as the input has; if rtype is negative, the output matrix will have the + same type as the input. + @param [in] alpha - optional scale factor + @param [in] beta - optional delta added to the scaled values + */ + void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const; + + // not used now + void assignTo( SparseMat& m, int type=-1 ) const; + + //! reallocates sparse matrix. + /*! + If the matrix already had the proper size and type, + it is simply cleared with clear(), otherwise, + the old matrix is released (using release()) and the new one is allocated. + */ + void create(int dims, const int* _sizes, int _type); + //! sets all the sparse matrix elements to 0, which means clearing the hash table. + void clear(); + //! manually increments the reference counter to the header. + void addref(); + // decrements the header reference counter. When the counter reaches 0, the header and all the underlying data are deallocated. + void release(); + + //! converts sparse matrix to the old-style representation; all the elements are copied. + //operator CvSparseMat*() const; + //! returns the size of each element in bytes (not including the overhead - the space occupied by SparseMat::Node elements) + size_t elemSize() const; + //! returns elemSize()/channels() + size_t elemSize1() const; + + //! returns type of sparse matrix elements + int type() const; + //! returns the depth of sparse matrix elements + int depth() const; + //! returns the number of channels + int channels() const; + + //! returns the array of sizes, or NULL if the matrix is not allocated + const int* size() const; + //! returns the size of i-th matrix dimension (or 0) + int size(int i) const; + //! returns the matrix dimensionality + int dims() const; + //! returns the number of non-zero elements (=the number of hash table nodes) + size_t nzcount() const; + + //! computes the element hash value (1D case) + size_t hash(int i0) const; + //! computes the element hash value (2D case) + size_t hash(int i0, int i1) const; + //! computes the element hash value (3D case) + size_t hash(int i0, int i1, int i2) const; + //! computes the element hash value (nD case) + size_t hash(const int* idx) const; + + //!@{ + /*! + specialized variants for 1D, 2D, 3D cases and the generic_type one for n-D case. + return pointer to the matrix element. + - if the element is there (it's non-zero), the pointer to it is returned + - if it's not there and createMissing=false, NULL pointer is returned + - if it's not there and createMissing=true, then the new element + is created and initialized with 0. Pointer to it is returned + - if the optional hashval pointer is not NULL, the element hash value is + not computed, but *hashval is taken instead. + */ + //! returns pointer to the specified element (1D case) + uchar* ptr(int i0, bool createMissing, size_t* hashval=0); + //! returns pointer to the specified element (2D case) + uchar* ptr(int i0, int i1, bool createMissing, size_t* hashval=0); + //! returns pointer to the specified element (3D case) + uchar* ptr(int i0, int i1, int i2, bool createMissing, size_t* hashval=0); + //! returns pointer to the specified element (nD case) + uchar* ptr(const int* idx, bool createMissing, size_t* hashval=0); + //!@} + + //!@{ + /*! + return read-write reference to the specified sparse matrix element. + + `ref<_Tp>(i0,...[,hashval])` is equivalent to `*(_Tp*)ptr(i0,...,true[,hashval])`. + The methods always return a valid reference. + If the element did not exist, it is created and initialized with 0. + */ + //! returns reference to the specified element (1D case) + template _Tp& ref(int i0, size_t* hashval=0); + //! returns reference to the specified element (2D case) + template _Tp& ref(int i0, int i1, size_t* hashval=0); + //! returns reference to the specified element (3D case) + template _Tp& ref(int i0, int i1, int i2, size_t* hashval=0); + //! returns reference to the specified element (nD case) + template _Tp& ref(const int* idx, size_t* hashval=0); + //!@} + + //!@{ + /*! + return value of the specified sparse matrix element. + + `value<_Tp>(i0,...[,hashval])` is equivalent to + @code + { const _Tp* p = find<_Tp>(i0,...[,hashval]); return p ? *p : _Tp(); } + @endcode + + That is, if the element did not exist, the methods return 0. + */ + //! returns value of the specified element (1D case) + template _Tp value(int i0, size_t* hashval=0) const; + //! returns value of the specified element (2D case) + template _Tp value(int i0, int i1, size_t* hashval=0) const; + //! returns value of the specified element (3D case) + template _Tp value(int i0, int i1, int i2, size_t* hashval=0) const; + //! returns value of the specified element (nD case) + template _Tp value(const int* idx, size_t* hashval=0) const; + //!@} + + //!@{ + /*! + Return pointer to the specified sparse matrix element if it exists + + `find<_Tp>(i0,...[,hashval])` is equivalent to `(_const Tp*)ptr(i0,...false[,hashval])`. + + If the specified element does not exist, the methods return NULL. + */ + //! returns pointer to the specified element (1D case) + template const _Tp* find(int i0, size_t* hashval=0) const; + //! returns pointer to the specified element (2D case) + template const _Tp* find(int i0, int i1, size_t* hashval=0) const; + //! returns pointer to the specified element (3D case) + template const _Tp* find(int i0, int i1, int i2, size_t* hashval=0) const; + //! returns pointer to the specified element (nD case) + template const _Tp* find(const int* idx, size_t* hashval=0) const; + //!@} + + //! erases the specified element (2D case) + void erase(int i0, int i1, size_t* hashval=0); + //! erases the specified element (3D case) + void erase(int i0, int i1, int i2, size_t* hashval=0); + //! erases the specified element (nD case) + void erase(const int* idx, size_t* hashval=0); + + //!@{ + /*! + return the sparse matrix iterator pointing to the first sparse matrix element + */ + //! returns the sparse matrix iterator at the matrix beginning + SparseMatIterator begin(); + //! returns the sparse matrix iterator at the matrix beginning + template SparseMatIterator_<_Tp> begin(); + //! returns the read-only sparse matrix iterator at the matrix beginning + SparseMatConstIterator begin() const; + //! returns the read-only sparse matrix iterator at the matrix beginning + template SparseMatConstIterator_<_Tp> begin() const; + //!@} + /*! + return the sparse matrix iterator pointing to the element following the last sparse matrix element + */ + //! returns the sparse matrix iterator at the matrix end + SparseMatIterator end(); + //! returns the read-only sparse matrix iterator at the matrix end + SparseMatConstIterator end() const; + //! returns the typed sparse matrix iterator at the matrix end + template SparseMatIterator_<_Tp> end(); + //! returns the typed read-only sparse matrix iterator at the matrix end + template SparseMatConstIterator_<_Tp> end() const; + + //! returns the value stored in the sparse martix node + template _Tp& value(Node* n); + //! returns the value stored in the sparse martix node + template const _Tp& value(const Node* n) const; + + ////////////// some internal-use methods /////////////// + Node* node(size_t nidx); + const Node* node(size_t nidx) const; + + uchar* newNode(const int* idx, size_t hashval); + void removeNode(size_t hidx, size_t nidx, size_t previdx); + void resizeHashTab(size_t newsize); + + int flags; + Hdr* hdr; +}; + + + +///////////////////////////////// SparseMat_<_Tp> //////////////////////////////////// + +/** @brief Template sparse n-dimensional array class derived from SparseMat + +SparseMat_ is a thin wrapper on top of SparseMat created in the same way as Mat_ . It simplifies +notation of some operations: +@code + int sz[] = {10, 20, 30}; + SparseMat_ M(3, sz); + ... + M.ref(1, 2, 3) = M(4, 5, 6) + M(7, 8, 9); +@endcode + */ +template class SparseMat_ : public SparseMat +{ +public: + typedef SparseMatIterator_<_Tp> iterator; + typedef SparseMatConstIterator_<_Tp> const_iterator; + + //! the default constructor + SparseMat_(); + //! the full constructor equivalent to SparseMat(dims, _sizes, DataType<_Tp>::type) + SparseMat_(int dims, const int* _sizes); + //! the copy constructor. If DataType<_Tp>.type != m.type(), the m elements are converted + SparseMat_(const SparseMat& m); + //! the copy constructor. This is O(1) operation - no data is copied + SparseMat_(const SparseMat_& m); + //! converts dense matrix to the sparse form + SparseMat_(const Mat& m); + //! converts the old-style sparse matrix to the C++ class. All the elements are copied + //SparseMat_(const CvSparseMat* m); + //! the assignment operator. If DataType<_Tp>.type != m.type(), the m elements are converted + SparseMat_& operator = (const SparseMat& m); + //! the assignment operator. This is O(1) operation - no data is copied + SparseMat_& operator = (const SparseMat_& m); + //! converts dense matrix to the sparse form + SparseMat_& operator = (const Mat& m); + + //! makes full copy of the matrix. All the elements are duplicated + CV_NODISCARD_STD SparseMat_ clone() const; + //! equivalent to cv::SparseMat::create(dims, _sizes, DataType<_Tp>::type) + void create(int dims, const int* _sizes); + //! converts sparse matrix to the old-style CvSparseMat. All the elements are copied + //operator CvSparseMat*() const; + + //! returns type of the matrix elements + int type() const; + //! returns depth of the matrix elements + int depth() const; + //! returns the number of channels in each matrix element + int channels() const; + + //! equivalent to SparseMat::ref<_Tp>(i0, hashval) + _Tp& ref(int i0, size_t* hashval=0); + //! equivalent to SparseMat::ref<_Tp>(i0, i1, hashval) + _Tp& ref(int i0, int i1, size_t* hashval=0); + //! equivalent to SparseMat::ref<_Tp>(i0, i1, i2, hashval) + _Tp& ref(int i0, int i1, int i2, size_t* hashval=0); + //! equivalent to SparseMat::ref<_Tp>(idx, hashval) + _Tp& ref(const int* idx, size_t* hashval=0); + + //! equivalent to SparseMat::value<_Tp>(i0, hashval) + _Tp operator()(int i0, size_t* hashval=0) const; + //! equivalent to SparseMat::value<_Tp>(i0, i1, hashval) + _Tp operator()(int i0, int i1, size_t* hashval=0) const; + //! equivalent to SparseMat::value<_Tp>(i0, i1, i2, hashval) + _Tp operator()(int i0, int i1, int i2, size_t* hashval=0) const; + //! equivalent to SparseMat::value<_Tp>(idx, hashval) + _Tp operator()(const int* idx, size_t* hashval=0) const; + + //! returns sparse matrix iterator pointing to the first sparse matrix element + SparseMatIterator_<_Tp> begin(); + //! returns read-only sparse matrix iterator pointing to the first sparse matrix element + SparseMatConstIterator_<_Tp> begin() const; + //! returns sparse matrix iterator pointing to the element following the last sparse matrix element + SparseMatIterator_<_Tp> end(); + //! returns read-only sparse matrix iterator pointing to the element following the last sparse matrix element + SparseMatConstIterator_<_Tp> end() const; +}; + + + +////////////////////////////////// MatConstIterator ////////////////////////////////// + +class CV_EXPORTS MatConstIterator +{ +public: + typedef uchar* value_type; + typedef ptrdiff_t difference_type; + typedef const uchar** pointer; + typedef uchar* reference; + + typedef std::random_access_iterator_tag iterator_category; + + //! default constructor + MatConstIterator(); + //! constructor that sets the iterator to the beginning of the matrix + MatConstIterator(const Mat* _m); + //! constructor that sets the iterator to the specified element of the matrix + MatConstIterator(const Mat* _m, int _row, int _col=0); + //! constructor that sets the iterator to the specified element of the matrix + MatConstIterator(const Mat* _m, Point _pt); + //! constructor that sets the iterator to the specified element of the matrix + MatConstIterator(const Mat* _m, const int* _idx); + //! copy constructor + MatConstIterator(const MatConstIterator& it); + + //! copy operator + MatConstIterator& operator = (const MatConstIterator& it); + //! returns the current matrix element + const uchar* operator *() const; + //! returns the i-th matrix element, relative to the current + const uchar* operator [](ptrdiff_t i) const; + + //! shifts the iterator forward by the specified number of elements + MatConstIterator& operator += (ptrdiff_t ofs); + //! shifts the iterator backward by the specified number of elements + MatConstIterator& operator -= (ptrdiff_t ofs); + //! decrements the iterator + MatConstIterator& operator --(); + //! decrements the iterator + MatConstIterator operator --(int); + //! increments the iterator + MatConstIterator& operator ++(); + //! increments the iterator + MatConstIterator operator ++(int); + //! returns the current iterator position + Point pos() const; + //! returns the current iterator position + void pos(int* _idx) const; + + ptrdiff_t lpos() const; + void seek(ptrdiff_t ofs, bool relative = false); + void seek(const int* _idx, bool relative = false); + + const Mat* m; + size_t elemSize; + const uchar* ptr; + const uchar* sliceStart; + const uchar* sliceEnd; +}; + + + +////////////////////////////////// MatConstIterator_ ///////////////////////////////// + +/** @brief Matrix read-only iterator + */ +template +class MatConstIterator_ : public MatConstIterator +{ +public: + typedef _Tp value_type; + typedef ptrdiff_t difference_type; + typedef const _Tp* pointer; + typedef const _Tp& reference; + + typedef std::random_access_iterator_tag iterator_category; + + //! default constructor + MatConstIterator_(); + //! constructor that sets the iterator to the beginning of the matrix + MatConstIterator_(const Mat_<_Tp>* _m); + //! constructor that sets the iterator to the specified element of the matrix + MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col=0); + //! constructor that sets the iterator to the specified element of the matrix + MatConstIterator_(const Mat_<_Tp>* _m, Point _pt); + //! constructor that sets the iterator to the specified element of the matrix + MatConstIterator_(const Mat_<_Tp>* _m, const int* _idx); + //! copy constructor + MatConstIterator_(const MatConstIterator_& it); + + //! copy operator + MatConstIterator_& operator = (const MatConstIterator_& it); + //! returns the current matrix element + const _Tp& operator *() const; + //! returns the i-th matrix element, relative to the current + const _Tp& operator [](ptrdiff_t i) const; + + //! shifts the iterator forward by the specified number of elements + MatConstIterator_& operator += (ptrdiff_t ofs); + //! shifts the iterator backward by the specified number of elements + MatConstIterator_& operator -= (ptrdiff_t ofs); + //! decrements the iterator + MatConstIterator_& operator --(); + //! decrements the iterator + MatConstIterator_ operator --(int); + //! increments the iterator + MatConstIterator_& operator ++(); + //! increments the iterator + MatConstIterator_ operator ++(int); + //! returns the current iterator position + Point pos() const; +}; + + + +//////////////////////////////////// MatIterator_ //////////////////////////////////// + +/** @brief Matrix read-write iterator +*/ +template +class MatIterator_ : public MatConstIterator_<_Tp> +{ +public: + typedef _Tp* pointer; + typedef _Tp& reference; + + typedef std::random_access_iterator_tag iterator_category; + + //! the default constructor + MatIterator_(); + //! constructor that sets the iterator to the beginning of the matrix + MatIterator_(Mat_<_Tp>* _m); + //! constructor that sets the iterator to the specified element of the matrix + MatIterator_(Mat_<_Tp>* _m, int _row, int _col=0); + //! constructor that sets the iterator to the specified element of the matrix + MatIterator_(Mat_<_Tp>* _m, Point _pt); + //! constructor that sets the iterator to the specified element of the matrix + MatIterator_(Mat_<_Tp>* _m, const int* _idx); + //! copy constructor + MatIterator_(const MatIterator_& it); + //! copy operator + MatIterator_& operator = (const MatIterator_<_Tp>& it ); + + //! returns the current matrix element + _Tp& operator *() const; + //! returns the i-th matrix element, relative to the current + _Tp& operator [](ptrdiff_t i) const; + + //! shifts the iterator forward by the specified number of elements + MatIterator_& operator += (ptrdiff_t ofs); + //! shifts the iterator backward by the specified number of elements + MatIterator_& operator -= (ptrdiff_t ofs); + //! decrements the iterator + MatIterator_& operator --(); + //! decrements the iterator + MatIterator_ operator --(int); + //! increments the iterator + MatIterator_& operator ++(); + //! increments the iterator + MatIterator_ operator ++(int); +}; + + + +/////////////////////////////// SparseMatConstIterator /////////////////////////////// + +/** @brief Read-Only Sparse Matrix Iterator. + + Here is how to use the iterator to compute the sum of floating-point sparse matrix elements: + + \code + SparseMatConstIterator it = m.begin(), it_end = m.end(); + double s = 0; + CV_Assert( m.type() == CV_32F ); + for( ; it != it_end; ++it ) + s += it.value(); + \endcode +*/ +class CV_EXPORTS SparseMatConstIterator +{ +public: + //! the default constructor + SparseMatConstIterator(); + //! the full constructor setting the iterator to the first sparse matrix element + SparseMatConstIterator(const SparseMat* _m); + //! the copy constructor + SparseMatConstIterator(const SparseMatConstIterator& it); + + //! the assignment operator + SparseMatConstIterator& operator = (const SparseMatConstIterator& it); + + //! template method returning the current matrix element + template const _Tp& value() const; + //! returns the current node of the sparse matrix. it.node->idx is the current element index + const SparseMat::Node* node() const; + + //! moves iterator to the previous element + SparseMatConstIterator& operator --(); + //! moves iterator to the previous element + SparseMatConstIterator operator --(int); + //! moves iterator to the next element + SparseMatConstIterator& operator ++(); + //! moves iterator to the next element + SparseMatConstIterator operator ++(int); + + //! moves iterator to the element after the last element + void seekEnd(); + + const SparseMat* m; + size_t hashidx; + uchar* ptr; +}; + + + +////////////////////////////////// SparseMatIterator ///////////////////////////////// + +/** @brief Read-write Sparse Matrix Iterator + + The class is similar to cv::SparseMatConstIterator, + but can be used for in-place modification of the matrix elements. +*/ +class CV_EXPORTS SparseMatIterator : public SparseMatConstIterator +{ +public: + //! the default constructor + SparseMatIterator(); + //! the full constructor setting the iterator to the first sparse matrix element + SparseMatIterator(SparseMat* _m); + //! the full constructor setting the iterator to the specified sparse matrix element + SparseMatIterator(SparseMat* _m, const int* idx); + //! the copy constructor + SparseMatIterator(const SparseMatIterator& it); + + //! the assignment operator + SparseMatIterator& operator = (const SparseMatIterator& it); + //! returns read-write reference to the current sparse matrix element + template _Tp& value() const; + //! returns pointer to the current sparse matrix node. it.node->idx is the index of the current element (do not modify it!) + SparseMat::Node* node() const; + + //! moves iterator to the next element + SparseMatIterator& operator ++(); + //! moves iterator to the next element + SparseMatIterator operator ++(int); +}; + + + +/////////////////////////////// SparseMatConstIterator_ ////////////////////////////// + +/** @brief Template Read-Only Sparse Matrix Iterator Class. + + This is the derived from SparseMatConstIterator class that + introduces more convenient operator *() for accessing the current element. +*/ +template class SparseMatConstIterator_ : public SparseMatConstIterator +{ +public: + + typedef std::forward_iterator_tag iterator_category; + + //! the default constructor + SparseMatConstIterator_(); + //! the full constructor setting the iterator to the first sparse matrix element + SparseMatConstIterator_(const SparseMat_<_Tp>* _m); + SparseMatConstIterator_(const SparseMat* _m); + //! the copy constructor + SparseMatConstIterator_(const SparseMatConstIterator_& it); + + //! the assignment operator + SparseMatConstIterator_& operator = (const SparseMatConstIterator_& it); + //! the element access operator + const _Tp& operator *() const; + + //! moves iterator to the next element + SparseMatConstIterator_& operator ++(); + //! moves iterator to the next element + SparseMatConstIterator_ operator ++(int); +}; + + + +///////////////////////////////// SparseMatIterator_ ///////////////////////////////// + +/** @brief Template Read-Write Sparse Matrix Iterator Class. + + This is the derived from cv::SparseMatConstIterator_ class that + introduces more convenient operator *() for accessing the current element. +*/ +template class SparseMatIterator_ : public SparseMatConstIterator_<_Tp> +{ +public: + + typedef std::forward_iterator_tag iterator_category; + + //! the default constructor + SparseMatIterator_(); + //! the full constructor setting the iterator to the first sparse matrix element + SparseMatIterator_(SparseMat_<_Tp>* _m); + SparseMatIterator_(SparseMat* _m); + //! the copy constructor + SparseMatIterator_(const SparseMatIterator_& it); + + //! the assignment operator + SparseMatIterator_& operator = (const SparseMatIterator_& it); + //! returns the reference to the current element + _Tp& operator *() const; + + //! moves the iterator to the next element + SparseMatIterator_& operator ++(); + //! moves the iterator to the next element + SparseMatIterator_ operator ++(int); +}; + + + +/////////////////////////////////// NAryMatIterator ////////////////////////////////// + +/** @brief n-ary multi-dimensional array iterator. + +Use the class to implement unary, binary, and, generally, n-ary element-wise operations on +multi-dimensional arrays. Some of the arguments of an n-ary function may be continuous arrays, some +may be not. It is possible to use conventional MatIterator 's for each array but incrementing all of +the iterators after each small operations may be a big overhead. In this case consider using +NAryMatIterator to iterate through several matrices simultaneously as long as they have the same +geometry (dimensionality and all the dimension sizes are the same). On each iteration `it.planes[0]`, +`it.planes[1]`,... will be the slices of the corresponding matrices. + +The example below illustrates how you can compute a normalized and threshold 3D color histogram: +@code + void computeNormalizedColorHist(const Mat& image, Mat& hist, int N, double minProb) + { + const int histSize[] = {N, N, N}; + + // make sure that the histogram has a proper size and type + hist.create(3, histSize, CV_32F); + + // and clear it + hist = Scalar(0); + + // the loop below assumes that the image + // is a 8-bit 3-channel. check it. + CV_Assert(image.type() == CV_8UC3); + MatConstIterator_ it = image.begin(), + it_end = image.end(); + for( ; it != it_end; ++it ) + { + const Vec3b& pix = *it; + hist.at(pix[0]*N/256, pix[1]*N/256, pix[2]*N/256) += 1.f; + } + + minProb *= image.rows*image.cols; + + // initialize iterator (the style is different from STL). + // after initialization the iterator will contain + // the number of slices or planes the iterator will go through. + // it simultaneously increments iterators for several matrices + // supplied as a null terminated list of pointers + const Mat* arrays[] = {&hist, 0}; + Mat planes[1]; + NAryMatIterator itNAry(arrays, planes, 1); + double s = 0; + // iterate through the matrix. on each iteration + // itNAry.planes[i] (of type Mat) will be set to the current plane + // of the i-th n-dim matrix passed to the iterator constructor. + for(int p = 0; p < itNAry.nplanes; p++, ++itNAry) + { + threshold(itNAry.planes[0], itNAry.planes[0], minProb, 0, THRESH_TOZERO); + s += sum(itNAry.planes[0])[0]; + } + + s = 1./s; + itNAry = NAryMatIterator(arrays, planes, 1); + for(int p = 0; p < itNAry.nplanes; p++, ++itNAry) + itNAry.planes[0] *= s; + } +@endcode + */ +class CV_EXPORTS NAryMatIterator +{ +public: + //! the default constructor + NAryMatIterator(); + //! the full constructor taking arbitrary number of n-dim matrices + NAryMatIterator(const Mat** arrays, uchar** ptrs, int narrays=-1); + //! the full constructor taking arbitrary number of n-dim matrices + NAryMatIterator(const Mat** arrays, Mat* planes, int narrays=-1); + //! the separate iterator initialization method + void init(const Mat** arrays, Mat* planes, uchar** ptrs, int narrays=-1); + + //! proceeds to the next plane of every iterated matrix + NAryMatIterator& operator ++(); + //! proceeds to the next plane of every iterated matrix (postfix increment operator) + NAryMatIterator operator ++(int); + + //! the iterated arrays + const Mat** arrays; + //! the current planes + Mat* planes; + //! data pointers + uchar** ptrs; + //! the number of arrays + int narrays; + //! the number of hyper-planes that the iterator steps through + size_t nplanes; + //! the size of each segment (in elements) + size_t size; +protected: + int iterdepth; + size_t idx; +}; + + + +///////////////////////////////// Matrix Expressions ///////////////////////////////// + +class CV_EXPORTS MatOp +{ +public: + MatOp(); + virtual ~MatOp(); + + virtual bool elementWise(const MatExpr& expr) const; + virtual void assign(const MatExpr& expr, Mat& m, int type=-1) const = 0; + virtual void roi(const MatExpr& expr, const Range& rowRange, + const Range& colRange, MatExpr& res) const; + virtual void diag(const MatExpr& expr, int d, MatExpr& res) const; + virtual void augAssignAdd(const MatExpr& expr, Mat& m) const; + virtual void augAssignSubtract(const MatExpr& expr, Mat& m) const; + virtual void augAssignMultiply(const MatExpr& expr, Mat& m) const; + virtual void augAssignDivide(const MatExpr& expr, Mat& m) const; + virtual void augAssignAnd(const MatExpr& expr, Mat& m) const; + virtual void augAssignOr(const MatExpr& expr, Mat& m) const; + virtual void augAssignXor(const MatExpr& expr, Mat& m) const; + + virtual void add(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const; + virtual void add(const MatExpr& expr1, const Scalar& s, MatExpr& res) const; + + virtual void subtract(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const; + virtual void subtract(const Scalar& s, const MatExpr& expr, MatExpr& res) const; + + virtual void multiply(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const; + virtual void multiply(const MatExpr& expr1, double s, MatExpr& res) const; + + virtual void divide(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const; + virtual void divide(double s, const MatExpr& expr, MatExpr& res) const; + + virtual void abs(const MatExpr& expr, MatExpr& res) const; + + virtual void transpose(const MatExpr& expr, MatExpr& res) const; + virtual void matmul(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const; + virtual void invert(const MatExpr& expr, int method, MatExpr& res) const; + + virtual Size size(const MatExpr& expr) const; + virtual int type(const MatExpr& expr) const; +}; + +/** @brief Matrix expression representation +@anchor MatrixExpressions +This is a list of implemented matrix operations that can be combined in arbitrary complex +expressions (here A, B stand for matrices ( Mat ), s for a scalar ( Scalar ), alpha for a +real-valued scalar ( double )): +- Addition, subtraction, negation: `A+B`, `A-B`, `A+s`, `A-s`, `s+A`, `s-A`, `-A` +- Scaling: `A*alpha` +- Per-element multiplication and division: `A.mul(B)`, `A/B`, `alpha/A` +- Matrix multiplication: `A*B` +- Transposition: `A.t()` (means AT) +- Matrix inversion and pseudo-inversion, solving linear systems and least-squares problems: + `A.inv([method]) (~ A-1)`, `A.inv([method])*B (~ X: AX=B)` +- Comparison: `A cmpop B`, `A cmpop alpha`, `alpha cmpop A`, where *cmpop* is one of + `>`, `>=`, `==`, `!=`, `<=`, `<`. The result of comparison is an 8-bit single channel mask whose + elements are set to 255 (if the particular element or pair of elements satisfy the condition) or + 0. +- Bitwise logical operations: `A logicop B`, `A logicop s`, `s logicop A`, `~A`, where *logicop* is one of + `&`, `|`, `^`. +- Element-wise minimum and maximum: `min(A, B)`, `min(A, alpha)`, `max(A, B)`, `max(A, alpha)` +- Element-wise absolute value: `abs(A)` +- Cross-product, dot-product: `A.cross(B)`, `A.dot(B)` +- Any function of matrix or matrices and scalars that returns a matrix or a scalar, such as norm, + mean, sum, countNonZero, trace, determinant, repeat, and others. +- Matrix initializers ( Mat::eye(), Mat::zeros(), Mat::ones() ), matrix comma-separated + initializers, matrix constructors and operators that extract sub-matrices (see Mat description). +- Mat_() constructors to cast the result to the proper type. +@note Comma-separated initializers and probably some other operations may require additional +explicit Mat() or Mat_() constructor calls to resolve a possible ambiguity. + +Here are examples of matrix expressions: +@code + // compute pseudo-inverse of A, equivalent to A.inv(DECOMP_SVD) + SVD svd(A); + Mat pinvA = svd.vt.t()*Mat::diag(1./svd.w)*svd.u.t(); + + // compute the new vector of parameters in the Levenberg-Marquardt algorithm + x -= (A.t()*A + lambda*Mat::eye(A.cols,A.cols,A.type())).inv(DECOMP_CHOLESKY)*(A.t()*err); + + // sharpen image using "unsharp mask" algorithm + Mat blurred; double sigma = 1, threshold = 5, amount = 1; + GaussianBlur(img, blurred, Size(), sigma, sigma); + Mat lowContrastMask = abs(img - blurred) < threshold; + Mat sharpened = img*(1+amount) + blurred*(-amount); + img.copyTo(sharpened, lowContrastMask); +@endcode +*/ +class CV_EXPORTS MatExpr +{ +public: + MatExpr(); + explicit MatExpr(const Mat& m); + + MatExpr(const MatOp* _op, int _flags, const Mat& _a = Mat(), const Mat& _b = Mat(), + const Mat& _c = Mat(), double _alpha = 1, double _beta = 1, const Scalar& _s = Scalar()); + + operator Mat() const; + template operator Mat_<_Tp>() const; + + Size size() const; + int type() const; + + MatExpr row(int y) const; + MatExpr col(int x) const; + MatExpr diag(int d = 0) const; + MatExpr operator()( const Range& rowRange, const Range& colRange ) const; + MatExpr operator()( const Rect& roi ) const; + + MatExpr t() const; + MatExpr inv(int method = DECOMP_LU) const; + MatExpr mul(const MatExpr& e, double scale=1) const; + MatExpr mul(const Mat& m, double scale=1) const; + + Mat cross(const Mat& m) const; + double dot(const Mat& m) const; + + void swap(MatExpr& b); + + const MatOp* op; + int flags; + + Mat a, b, c; + double alpha, beta; + Scalar s; +}; + +//! @} core_basic + +//! @relates cv::MatExpr +//! @{ +CV_EXPORTS MatExpr operator + (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator + (const Mat& a, const Scalar& s); +CV_EXPORTS MatExpr operator + (const Scalar& s, const Mat& a); +CV_EXPORTS MatExpr operator + (const MatExpr& e, const Mat& m); +CV_EXPORTS MatExpr operator + (const Mat& m, const MatExpr& e); +CV_EXPORTS MatExpr operator + (const MatExpr& e, const Scalar& s); +CV_EXPORTS MatExpr operator + (const Scalar& s, const MatExpr& e); +CV_EXPORTS MatExpr operator + (const MatExpr& e1, const MatExpr& e2); +template static inline +MatExpr operator + (const Mat& a, const Matx<_Tp, m, n>& b) { return a + Mat(b); } +template static inline +MatExpr operator + (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) + b; } + +CV_EXPORTS MatExpr operator - (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator - (const Mat& a, const Scalar& s); +CV_EXPORTS MatExpr operator - (const Scalar& s, const Mat& a); +CV_EXPORTS MatExpr operator - (const MatExpr& e, const Mat& m); +CV_EXPORTS MatExpr operator - (const Mat& m, const MatExpr& e); +CV_EXPORTS MatExpr operator - (const MatExpr& e, const Scalar& s); +CV_EXPORTS MatExpr operator - (const Scalar& s, const MatExpr& e); +CV_EXPORTS MatExpr operator - (const MatExpr& e1, const MatExpr& e2); +template static inline +MatExpr operator - (const Mat& a, const Matx<_Tp, m, n>& b) { return a - Mat(b); } +template static inline +MatExpr operator - (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) - b; } + +CV_EXPORTS MatExpr operator - (const Mat& m); +CV_EXPORTS MatExpr operator - (const MatExpr& e); + +CV_EXPORTS MatExpr operator * (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator * (const Mat& a, double s); +CV_EXPORTS MatExpr operator * (double s, const Mat& a); +CV_EXPORTS MatExpr operator * (const MatExpr& e, const Mat& m); +CV_EXPORTS MatExpr operator * (const Mat& m, const MatExpr& e); +CV_EXPORTS MatExpr operator * (const MatExpr& e, double s); +CV_EXPORTS MatExpr operator * (double s, const MatExpr& e); +CV_EXPORTS MatExpr operator * (const MatExpr& e1, const MatExpr& e2); +template static inline +MatExpr operator * (const Mat& a, const Matx<_Tp, m, n>& b) { return a * Mat(b); } +template static inline +MatExpr operator * (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) * b; } + +CV_EXPORTS MatExpr operator / (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator / (const Mat& a, double s); +CV_EXPORTS MatExpr operator / (double s, const Mat& a); +CV_EXPORTS MatExpr operator / (const MatExpr& e, const Mat& m); +CV_EXPORTS MatExpr operator / (const Mat& m, const MatExpr& e); +CV_EXPORTS MatExpr operator / (const MatExpr& e, double s); +CV_EXPORTS MatExpr operator / (double s, const MatExpr& e); +CV_EXPORTS MatExpr operator / (const MatExpr& e1, const MatExpr& e2); +template static inline +MatExpr operator / (const Mat& a, const Matx<_Tp, m, n>& b) { return a / Mat(b); } +template static inline +MatExpr operator / (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) / b; } + +CV_EXPORTS MatExpr operator < (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator < (const Mat& a, double s); +CV_EXPORTS MatExpr operator < (double s, const Mat& a); +template static inline +MatExpr operator < (const Mat& a, const Matx<_Tp, m, n>& b) { return a < Mat(b); } +template static inline +MatExpr operator < (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) < b; } + +CV_EXPORTS MatExpr operator <= (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator <= (const Mat& a, double s); +CV_EXPORTS MatExpr operator <= (double s, const Mat& a); +template static inline +MatExpr operator <= (const Mat& a, const Matx<_Tp, m, n>& b) { return a <= Mat(b); } +template static inline +MatExpr operator <= (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) <= b; } + +CV_EXPORTS MatExpr operator == (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator == (const Mat& a, double s); +CV_EXPORTS MatExpr operator == (double s, const Mat& a); +template static inline +MatExpr operator == (const Mat& a, const Matx<_Tp, m, n>& b) { return a == Mat(b); } +template static inline +MatExpr operator == (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) == b; } + +CV_EXPORTS MatExpr operator != (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator != (const Mat& a, double s); +CV_EXPORTS MatExpr operator != (double s, const Mat& a); +template static inline +MatExpr operator != (const Mat& a, const Matx<_Tp, m, n>& b) { return a != Mat(b); } +template static inline +MatExpr operator != (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) != b; } + +CV_EXPORTS MatExpr operator >= (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator >= (const Mat& a, double s); +CV_EXPORTS MatExpr operator >= (double s, const Mat& a); +template static inline +MatExpr operator >= (const Mat& a, const Matx<_Tp, m, n>& b) { return a >= Mat(b); } +template static inline +MatExpr operator >= (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) >= b; } + +CV_EXPORTS MatExpr operator > (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator > (const Mat& a, double s); +CV_EXPORTS MatExpr operator > (double s, const Mat& a); +template static inline +MatExpr operator > (const Mat& a, const Matx<_Tp, m, n>& b) { return a > Mat(b); } +template static inline +MatExpr operator > (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) > b; } + +CV_EXPORTS MatExpr operator & (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator & (const Mat& a, const Scalar& s); +CV_EXPORTS MatExpr operator & (const Scalar& s, const Mat& a); +template static inline +MatExpr operator & (const Mat& a, const Matx<_Tp, m, n>& b) { return a & Mat(b); } +template static inline +MatExpr operator & (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) & b; } + +CV_EXPORTS MatExpr operator | (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator | (const Mat& a, const Scalar& s); +CV_EXPORTS MatExpr operator | (const Scalar& s, const Mat& a); +template static inline +MatExpr operator | (const Mat& a, const Matx<_Tp, m, n>& b) { return a | Mat(b); } +template static inline +MatExpr operator | (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) | b; } + +CV_EXPORTS MatExpr operator ^ (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator ^ (const Mat& a, const Scalar& s); +CV_EXPORTS MatExpr operator ^ (const Scalar& s, const Mat& a); +template static inline +MatExpr operator ^ (const Mat& a, const Matx<_Tp, m, n>& b) { return a ^ Mat(b); } +template static inline +MatExpr operator ^ (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) ^ b; } + +CV_EXPORTS MatExpr operator ~(const Mat& m); + +CV_EXPORTS MatExpr min(const Mat& a, const Mat& b); +CV_EXPORTS MatExpr min(const Mat& a, double s); +CV_EXPORTS MatExpr min(double s, const Mat& a); +template static inline +MatExpr min (const Mat& a, const Matx<_Tp, m, n>& b) { return min(a, Mat(b)); } +template static inline +MatExpr min (const Matx<_Tp, m, n>& a, const Mat& b) { return min(Mat(a), b); } + +CV_EXPORTS MatExpr max(const Mat& a, const Mat& b); +CV_EXPORTS MatExpr max(const Mat& a, double s); +CV_EXPORTS MatExpr max(double s, const Mat& a); +template static inline +MatExpr max (const Mat& a, const Matx<_Tp, m, n>& b) { return max(a, Mat(b)); } +template static inline +MatExpr max (const Matx<_Tp, m, n>& a, const Mat& b) { return max(Mat(a), b); } + +/** @brief Calculates an absolute value of each matrix element. + +abs is a meta-function that is expanded to one of absdiff or convertScaleAbs forms: +- C = abs(A-B) is equivalent to `absdiff(A, B, C)` +- C = abs(A) is equivalent to `absdiff(A, Scalar::all(0), C)` +- C = `Mat_ >(abs(A*alpha + beta))` is equivalent to `convertScaleAbs(A, C, alpha, +beta)` + +The output matrix has the same size and the same type as the input one except for the last case, +where C is depth=CV_8U . +@param m matrix. +@sa @ref MatrixExpressions, absdiff, convertScaleAbs + */ +CV_EXPORTS MatExpr abs(const Mat& m); +/** @overload +@param e matrix expression. +*/ +CV_EXPORTS MatExpr abs(const MatExpr& e); +//! @} relates cv::MatExpr + +} // cv + +#include "opencv2/core/mat.inl.hpp" + +#endif // OPENCV_CORE_MAT_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/mat.inl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/mat.inl.hpp index bd0ba637b5..0d9c557bce 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/mat.inl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/mat.inl.hpp @@ -1,3422 +1,3422 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CORE_MATRIX_OPERATIONS_HPP -#define OPENCV_CORE_MATRIX_OPERATIONS_HPP - -#ifndef __cplusplus -# error mat.inl.hpp header must be compiled as C++ -#endif - -#ifdef _MSC_VER -#pragma warning( push ) -#pragma warning( disable: 4127 5054 ) -#endif - -#if defined(CV_SKIP_DISABLE_CLANG_ENUM_WARNINGS) - // nothing -#elif defined(CV_FORCE_DISABLE_CLANG_ENUM_WARNINGS) - #define CV_DISABLE_CLANG_ENUM_WARNINGS -#elif defined(__clang__) && defined(__has_warning) - #if __has_warning("-Wdeprecated-enum-enum-conversion") && __has_warning("-Wdeprecated-anon-enum-enum-conversion") - #define CV_DISABLE_CLANG_ENUM_WARNINGS - #endif -#endif -#ifdef CV_DISABLE_CLANG_ENUM_WARNINGS -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion" -#pragma clang diagnostic ignored "-Wdeprecated-anon-enum-enum-conversion" -#endif - -namespace cv -{ -CV__DEBUG_NS_BEGIN - - -//! @cond IGNORED - -////////////////////////// Custom (raw) type wrapper ////////////////////////// - -template static inline -int rawType() -{ - CV_StaticAssert(sizeof(_Tp) <= CV_CN_MAX, "sizeof(_Tp) is too large"); - const int elemSize = sizeof(_Tp); - return (int)CV_MAKETYPE(CV_8U, elemSize); -} - -//////////////////////// Input/Output Arrays //////////////////////// - -inline void _InputArray::init(int _flags, const void* _obj) -{ flags = _flags; obj = (void*)_obj; } - -inline void _InputArray::init(int _flags, const void* _obj, Size _sz) -{ flags = _flags; obj = (void*)_obj; sz = _sz; } - -inline void* _InputArray::getObj() const { return obj; } -inline int _InputArray::getFlags() const { return flags; } -inline Size _InputArray::getSz() const { return sz; } - -inline _InputArray::_InputArray() { init(0 + NONE, 0); } -inline _InputArray::_InputArray(int _flags, void* _obj) { init(_flags, _obj); } -inline _InputArray::_InputArray(const Mat& m) { init(+MAT+ACCESS_READ, &m); } -inline _InputArray::_InputArray(const std::vector& vec) { init(+STD_VECTOR_MAT+ACCESS_READ, &vec); } -inline _InputArray::_InputArray(const UMat& m) { init(+UMAT+ACCESS_READ, &m); } -inline _InputArray::_InputArray(const std::vector& vec) { init(+STD_VECTOR_UMAT+ACCESS_READ, &vec); } - -template inline -_InputArray::_InputArray(const std::vector<_Tp>& vec) -{ init(FIXED_TYPE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_READ, &vec); } - -template inline -_InputArray::_InputArray(const std::array<_Tp, _Nm>& arr) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_READ, arr.data(), Size(1, _Nm)); } - -template inline -_InputArray::_InputArray(const std::array& arr) -{ init(+STD_ARRAY_MAT + ACCESS_READ, arr.data(), Size(1, _Nm)); } - -inline -_InputArray::_InputArray(const std::vector& vec) -{ init(FIXED_TYPE + STD_BOOL_VECTOR + traits::Type::value + ACCESS_READ, &vec); } - -template inline -_InputArray::_InputArray(const std::vector >& vec) -{ init(FIXED_TYPE + STD_VECTOR_VECTOR + traits::Type<_Tp>::value + ACCESS_READ, &vec); } - -template inline -_InputArray::_InputArray(const std::vector >& vec) -{ init(FIXED_TYPE + STD_VECTOR_MAT + traits::Type<_Tp>::value + ACCESS_READ, &vec); } - -template inline -_InputArray::_InputArray(const Matx<_Tp, m, n>& mtx) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_READ, &mtx, Size(n, m)); } - -template inline -_InputArray::_InputArray(const _Tp* vec, int n) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_READ, vec, Size(n, 1)); } - -template inline -_InputArray::_InputArray(const Mat_<_Tp>& m) -{ init(FIXED_TYPE + MAT + traits::Type<_Tp>::value + ACCESS_READ, &m); } - -inline _InputArray::_InputArray(const double& val) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + CV_64F + ACCESS_READ, &val, Size(1,1)); } - -inline _InputArray::_InputArray(const cuda::GpuMat& d_mat) -{ init(+CUDA_GPU_MAT + ACCESS_READ, &d_mat); } - -inline _InputArray::_InputArray(const std::vector& d_mat) -{ init(+STD_VECTOR_CUDA_GPU_MAT + ACCESS_READ, &d_mat);} - -inline _InputArray::_InputArray(const ogl::Buffer& buf) -{ init(+OPENGL_BUFFER + ACCESS_READ, &buf); } - -inline _InputArray::_InputArray(const cuda::HostMem& cuda_mem) -{ init(+CUDA_HOST_MEM + ACCESS_READ, &cuda_mem); } - -template inline -_InputArray _InputArray::rawIn(const std::vector<_Tp>& vec) -{ - _InputArray v; - v.flags = _InputArray::FIXED_TYPE + _InputArray::STD_VECTOR + rawType<_Tp>() + ACCESS_READ; - v.obj = (void*)&vec; - return v; -} - -template inline -_InputArray _InputArray::rawIn(const std::array<_Tp, _Nm>& arr) -{ - _InputArray v; - v.flags = FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_READ; - v.obj = (void*)arr.data(); - v.sz = Size(1, _Nm); - return v; -} - -inline _InputArray::~_InputArray() {} - -inline Mat _InputArray::getMat(int i) const -{ - if( kind() == MAT && i < 0 ) - return *(const Mat*)obj; - return getMat_(i); -} - -inline bool _InputArray::isMat() const { return kind() == _InputArray::MAT; } -inline bool _InputArray::isUMat() const { return kind() == _InputArray::UMAT; } -inline bool _InputArray::isMatVector() const { return kind() == _InputArray::STD_VECTOR_MAT; } -inline bool _InputArray::isUMatVector() const { return kind() == _InputArray::STD_VECTOR_UMAT; } -inline bool _InputArray::isMatx() const { return kind() == _InputArray::MATX; } -inline bool _InputArray::isVector() const { return kind() == _InputArray::STD_VECTOR || - kind() == _InputArray::STD_BOOL_VECTOR || - (kind() == _InputArray::MATX && (sz.width <= 1 || sz.height <= 1)); } -inline bool _InputArray::isGpuMat() const { return kind() == _InputArray::CUDA_GPU_MAT; } -inline bool _InputArray::isGpuMatVector() const { return kind() == _InputArray::STD_VECTOR_CUDA_GPU_MAT; } - -//////////////////////////////////////////////////////////////////////////////////////// - -inline _OutputArray::_OutputArray() { init(+NONE + ACCESS_WRITE, 0); } -inline _OutputArray::_OutputArray(int _flags, void* _obj) { init(_flags + ACCESS_WRITE, _obj); } -inline _OutputArray::_OutputArray(Mat& m) { init(+MAT+ACCESS_WRITE, &m); } -inline _OutputArray::_OutputArray(std::vector& vec) { init(+STD_VECTOR_MAT + ACCESS_WRITE, &vec); } -inline _OutputArray::_OutputArray(UMat& m) { init(+UMAT + ACCESS_WRITE, &m); } -inline _OutputArray::_OutputArray(std::vector& vec) { init(+STD_VECTOR_UMAT + ACCESS_WRITE, &vec); } - -template inline -_OutputArray::_OutputArray(std::vector<_Tp>& vec) -{ init(FIXED_TYPE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); } - -template inline -_OutputArray::_OutputArray(std::array<_Tp, _Nm>& arr) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE, arr.data(), Size(1, _Nm)); } - -template inline -_OutputArray::_OutputArray(std::array& arr) -{ init(+STD_ARRAY_MAT + ACCESS_WRITE, arr.data(), Size(1, _Nm)); } - -template inline -_OutputArray::_OutputArray(std::vector >& vec) -{ init(FIXED_TYPE + STD_VECTOR_VECTOR + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); } - -template inline -_OutputArray::_OutputArray(std::vector >& vec) -{ init(FIXED_TYPE + STD_VECTOR_MAT + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); } - -template inline -_OutputArray::_OutputArray(Mat_<_Tp>& m) -{ init(FIXED_TYPE + MAT + traits::Type<_Tp>::value + ACCESS_WRITE, &m); } - -template inline -_OutputArray::_OutputArray(Matx<_Tp, m, n>& mtx) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE, &mtx, Size(n, m)); } - -template inline -_OutputArray::_OutputArray(_Tp* vec, int n) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE, vec, Size(n, 1)); } - -template inline -_OutputArray::_OutputArray(const std::vector<_Tp>& vec) -{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); } - -template inline -_OutputArray::_OutputArray(const std::array<_Tp, _Nm>& arr) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE, arr.data(), Size(1, _Nm)); } - -template inline -_OutputArray::_OutputArray(const std::array& arr) -{ init(FIXED_SIZE + STD_ARRAY_MAT + ACCESS_WRITE, arr.data(), Size(1, _Nm)); } - -template inline -_OutputArray::_OutputArray(const std::vector >& vec) -{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_VECTOR + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); } - -template inline -_OutputArray::_OutputArray(const std::vector >& vec) -{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_MAT + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); } - -template inline -_OutputArray::_OutputArray(const Mat_<_Tp>& m) -{ init(FIXED_TYPE + FIXED_SIZE + MAT + traits::Type<_Tp>::value + ACCESS_WRITE, &m); } - -template inline -_OutputArray::_OutputArray(const Matx<_Tp, m, n>& mtx) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE, &mtx, Size(n, m)); } - -template inline -_OutputArray::_OutputArray(const _Tp* vec, int n) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE, vec, Size(n, 1)); } - -inline _OutputArray::_OutputArray(cuda::GpuMat& d_mat) -{ init(+CUDA_GPU_MAT + ACCESS_WRITE, &d_mat); } - -inline _OutputArray::_OutputArray(std::vector& d_mat) -{ init(+STD_VECTOR_CUDA_GPU_MAT + ACCESS_WRITE, &d_mat);} - -inline _OutputArray::_OutputArray(ogl::Buffer& buf) -{ init(+OPENGL_BUFFER + ACCESS_WRITE, &buf); } - -inline _OutputArray::_OutputArray(cuda::HostMem& cuda_mem) -{ init(+CUDA_HOST_MEM + ACCESS_WRITE, &cuda_mem); } - -inline _OutputArray::_OutputArray(const Mat& m) -{ init(FIXED_TYPE + FIXED_SIZE + MAT + ACCESS_WRITE, &m); } - -inline _OutputArray::_OutputArray(const std::vector& vec) -{ init(FIXED_SIZE + STD_VECTOR_MAT + ACCESS_WRITE, &vec); } - -inline _OutputArray::_OutputArray(const UMat& m) -{ init(FIXED_TYPE + FIXED_SIZE + UMAT + ACCESS_WRITE, &m); } - -inline _OutputArray::_OutputArray(const std::vector& vec) -{ init(FIXED_SIZE + STD_VECTOR_UMAT + ACCESS_WRITE, &vec); } - -inline _OutputArray::_OutputArray(const cuda::GpuMat& d_mat) -{ init(FIXED_TYPE + FIXED_SIZE + CUDA_GPU_MAT + ACCESS_WRITE, &d_mat); } - - -inline _OutputArray::_OutputArray(const ogl::Buffer& buf) -{ init(FIXED_TYPE + FIXED_SIZE + OPENGL_BUFFER + ACCESS_WRITE, &buf); } - -inline _OutputArray::_OutputArray(const cuda::HostMem& cuda_mem) -{ init(FIXED_TYPE + FIXED_SIZE + CUDA_HOST_MEM + ACCESS_WRITE, &cuda_mem); } - -template inline -_OutputArray _OutputArray::rawOut(std::vector<_Tp>& vec) -{ - _OutputArray v; - v.flags = _InputArray::FIXED_TYPE + _InputArray::STD_VECTOR + rawType<_Tp>() + ACCESS_WRITE; - v.obj = (void*)&vec; - return v; -} - -template inline -_OutputArray _OutputArray::rawOut(std::array<_Tp, _Nm>& arr) -{ - _OutputArray v; - v.flags = FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE; - v.obj = (void*)arr.data(); - v.sz = Size(1, _Nm); - return v; -} - -/////////////////////////////////////////////////////////////////////////////////////////// - -inline _InputOutputArray::_InputOutputArray() { init(0+ACCESS_RW, 0); } -inline _InputOutputArray::_InputOutputArray(int _flags, void* _obj) { init(_flags+ACCESS_RW, _obj); } -inline _InputOutputArray::_InputOutputArray(Mat& m) { init(+MAT+ACCESS_RW, &m); } -inline _InputOutputArray::_InputOutputArray(std::vector& vec) { init(+STD_VECTOR_MAT+ACCESS_RW, &vec); } -inline _InputOutputArray::_InputOutputArray(UMat& m) { init(+UMAT+ACCESS_RW, &m); } -inline _InputOutputArray::_InputOutputArray(std::vector& vec) { init(+STD_VECTOR_UMAT+ACCESS_RW, &vec); } - -template inline -_InputOutputArray::_InputOutputArray(std::vector<_Tp>& vec) -{ init(FIXED_TYPE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_RW, &vec); } - -template inline -_InputOutputArray::_InputOutputArray(std::array<_Tp, _Nm>& arr) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW, arr.data(), Size(1, _Nm)); } - -template inline -_InputOutputArray::_InputOutputArray(std::array& arr) -{ init(+STD_ARRAY_MAT + ACCESS_RW, arr.data(), Size(1, _Nm)); } - -template inline -_InputOutputArray::_InputOutputArray(std::vector >& vec) -{ init(FIXED_TYPE + STD_VECTOR_VECTOR + traits::Type<_Tp>::value + ACCESS_RW, &vec); } - -template inline -_InputOutputArray::_InputOutputArray(std::vector >& vec) -{ init(FIXED_TYPE + STD_VECTOR_MAT + traits::Type<_Tp>::value + ACCESS_RW, &vec); } - -template inline -_InputOutputArray::_InputOutputArray(Mat_<_Tp>& m) -{ init(FIXED_TYPE + MAT + traits::Type<_Tp>::value + ACCESS_RW, &m); } - -template inline -_InputOutputArray::_InputOutputArray(Matx<_Tp, m, n>& mtx) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW, &mtx, Size(n, m)); } - -template inline -_InputOutputArray::_InputOutputArray(_Tp* vec, int n) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW, vec, Size(n, 1)); } - -template inline -_InputOutputArray::_InputOutputArray(const std::vector<_Tp>& vec) -{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_RW, &vec); } - -template inline -_InputOutputArray::_InputOutputArray(const std::array<_Tp, _Nm>& arr) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW, arr.data(), Size(1, _Nm)); } - -template inline -_InputOutputArray::_InputOutputArray(const std::array& arr) -{ init(FIXED_SIZE + STD_ARRAY_MAT + ACCESS_RW, arr.data(), Size(1, _Nm)); } - -template inline -_InputOutputArray::_InputOutputArray(const std::vector >& vec) -{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_VECTOR + traits::Type<_Tp>::value + ACCESS_RW, &vec); } - -template inline -_InputOutputArray::_InputOutputArray(const std::vector >& vec) -{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_MAT + traits::Type<_Tp>::value + ACCESS_RW, &vec); } - -template inline -_InputOutputArray::_InputOutputArray(const Mat_<_Tp>& m) -{ init(FIXED_TYPE + FIXED_SIZE + MAT + traits::Type<_Tp>::value + ACCESS_RW, &m); } - -template inline -_InputOutputArray::_InputOutputArray(const Matx<_Tp, m, n>& mtx) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW, &mtx, Size(n, m)); } - -template inline -_InputOutputArray::_InputOutputArray(const _Tp* vec, int n) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW, vec, Size(n, 1)); } - -inline _InputOutputArray::_InputOutputArray(cuda::GpuMat& d_mat) -{ init(+CUDA_GPU_MAT + ACCESS_RW, &d_mat); } - -inline _InputOutputArray::_InputOutputArray(ogl::Buffer& buf) -{ init(+OPENGL_BUFFER + ACCESS_RW, &buf); } - -inline _InputOutputArray::_InputOutputArray(cuda::HostMem& cuda_mem) -{ init(+CUDA_HOST_MEM + ACCESS_RW, &cuda_mem); } - -inline _InputOutputArray::_InputOutputArray(const Mat& m) -{ init(FIXED_TYPE + FIXED_SIZE + MAT + ACCESS_RW, &m); } - -inline _InputOutputArray::_InputOutputArray(const std::vector& vec) -{ init(FIXED_SIZE + STD_VECTOR_MAT + ACCESS_RW, &vec); } - -inline _InputOutputArray::_InputOutputArray(const UMat& m) -{ init(FIXED_TYPE + FIXED_SIZE + UMAT + ACCESS_RW, &m); } - -inline _InputOutputArray::_InputOutputArray(const std::vector& vec) -{ init(FIXED_SIZE + STD_VECTOR_UMAT + ACCESS_RW, &vec); } - -inline _InputOutputArray::_InputOutputArray(const cuda::GpuMat& d_mat) -{ init(FIXED_TYPE + FIXED_SIZE + CUDA_GPU_MAT + ACCESS_RW, &d_mat); } - -inline _InputOutputArray::_InputOutputArray(const std::vector& d_mat) -{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_CUDA_GPU_MAT + ACCESS_RW, &d_mat);} - -template<> inline _InputOutputArray::_InputOutputArray(std::vector& d_mat) -{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_CUDA_GPU_MAT + ACCESS_RW, &d_mat);} - -inline _InputOutputArray::_InputOutputArray(const ogl::Buffer& buf) -{ init(FIXED_TYPE + FIXED_SIZE + OPENGL_BUFFER + ACCESS_RW, &buf); } - -inline _InputOutputArray::_InputOutputArray(const cuda::HostMem& cuda_mem) -{ init(FIXED_TYPE + FIXED_SIZE + CUDA_HOST_MEM + ACCESS_RW, &cuda_mem); } - -template inline -_InputOutputArray _InputOutputArray::rawInOut(std::vector<_Tp>& vec) -{ - _InputOutputArray v; - v.flags = _InputArray::FIXED_TYPE + _InputArray::STD_VECTOR + rawType<_Tp>() + ACCESS_RW; - v.obj = (void*)&vec; - return v; -} - -template inline -_InputOutputArray _InputOutputArray::rawInOut(std::array<_Tp, _Nm>& arr) -{ - _InputOutputArray v; - v.flags = FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW; - v.obj = (void*)arr.data(); - v.sz = Size(1, _Nm); - return v; -} - - -template static inline _InputArray rawIn(_Tp& v) { return _InputArray::rawIn(v); } -template static inline _OutputArray rawOut(_Tp& v) { return _OutputArray::rawOut(v); } -template static inline _InputOutputArray rawInOut(_Tp& v) { return _InputOutputArray::rawInOut(v); } - -CV__DEBUG_NS_END - -//////////////////////////////////////////// Mat ////////////////////////////////////////// - -template inline -Mat::Mat(const std::vector<_Tp>& vec, bool copyData) - : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows((int)vec.size()), - cols(1), data(0), datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0) -{ - if(vec.empty()) - return; - if( !copyData ) - { - step[0] = step[1] = sizeof(_Tp); - datastart = data = (uchar*)&vec[0]; - datalimit = dataend = datastart + rows * step[0]; - } - else - Mat((int)vec.size(), 1, traits::Type<_Tp>::value, (uchar*)&vec[0]).copyTo(*this); -} - -template inline -Mat::Mat(const std::initializer_list<_Tp> list) - : Mat() -{ - CV_Assert(list.size() != 0); - Mat((int)list.size(), 1, traits::Type<_Tp>::value, (uchar*)list.begin()).copyTo(*this); -} - -template inline -Mat::Mat(const std::initializer_list sizes, const std::initializer_list<_Tp> list) - : Mat() -{ - size_t size_total = 1; - for(auto s : sizes) - size_total *= s; - CV_Assert(list.size() != 0); - CV_Assert(size_total == list.size()); - Mat((int)sizes.size(), (int*)sizes.begin(), traits::Type<_Tp>::value, (uchar*)list.begin()).copyTo(*this); -} - -template inline -Mat::Mat(const std::array<_Tp, _Nm>& arr, bool copyData) - : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows((int)arr.size()), - cols(1), data(0), datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0) -{ - if(arr.empty()) - return; - if( !copyData ) - { - step[0] = step[1] = sizeof(_Tp); - datastart = data = (uchar*)arr.data(); - datalimit = dataend = datastart + rows * step[0]; - } - else - Mat((int)arr.size(), 1, traits::Type<_Tp>::value, (uchar*)arr.data()).copyTo(*this); -} - -template inline -Mat::Mat(const Vec<_Tp, n>& vec, bool copyData) - : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows(n), cols(1), data(0), - datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0) -{ - if( !copyData ) - { - step[0] = step[1] = sizeof(_Tp); - datastart = data = (uchar*)vec.val; - datalimit = dataend = datastart + rows * step[0]; - } - else - Mat(n, 1, traits::Type<_Tp>::value, (void*)vec.val).copyTo(*this); -} - - -template inline -Mat::Mat(const Matx<_Tp,m,n>& M, bool copyData) - : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows(m), cols(n), data(0), - datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0) -{ - if( !copyData ) - { - step[0] = cols * sizeof(_Tp); - step[1] = sizeof(_Tp); - datastart = data = (uchar*)M.val; - datalimit = dataend = datastart + rows * step[0]; - } - else - Mat(m, n, traits::Type<_Tp>::value, (uchar*)M.val).copyTo(*this); -} - -template inline -Mat::Mat(const Point_<_Tp>& pt, bool copyData) - : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows(2), cols(1), data(0), - datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0) -{ - if( !copyData ) - { - step[0] = step[1] = sizeof(_Tp); - datastart = data = (uchar*)&pt.x; - datalimit = dataend = datastart + rows * step[0]; - } - else - { - create(2, 1, traits::Type<_Tp>::value); - ((_Tp*)data)[0] = pt.x; - ((_Tp*)data)[1] = pt.y; - } -} - -template inline -Mat::Mat(const Point3_<_Tp>& pt, bool copyData) - : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows(3), cols(1), data(0), - datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0) -{ - if( !copyData ) - { - step[0] = step[1] = sizeof(_Tp); - datastart = data = (uchar*)&pt.x; - datalimit = dataend = datastart + rows * step[0]; - } - else - { - create(3, 1, traits::Type<_Tp>::value); - ((_Tp*)data)[0] = pt.x; - ((_Tp*)data)[1] = pt.y; - ((_Tp*)data)[2] = pt.z; - } -} - -template inline -Mat::Mat(const MatCommaInitializer_<_Tp>& commaInitializer) - : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(0), rows(0), cols(0), data(0), - datastart(0), dataend(0), allocator(0), u(0), size(&rows) -{ - *this = commaInitializer.operator Mat_<_Tp>(); -} - -inline -Mat Mat::row(int y) const -{ - return Mat(*this, Range(y, y + 1), Range::all()); -} - -inline -Mat Mat::col(int x) const -{ - return Mat(*this, Range::all(), Range(x, x + 1)); -} - -inline -Mat Mat::rowRange(int startrow, int endrow) const -{ - return Mat(*this, Range(startrow, endrow), Range::all()); -} - -inline -Mat Mat::rowRange(const Range& r) const -{ - return Mat(*this, r, Range::all()); -} - -inline -Mat Mat::colRange(int startcol, int endcol) const -{ - return Mat(*this, Range::all(), Range(startcol, endcol)); -} - -inline -Mat Mat::colRange(const Range& r) const -{ - return Mat(*this, Range::all(), r); -} - -inline -Mat Mat::operator()( Range _rowRange, Range _colRange ) const -{ - return Mat(*this, _rowRange, _colRange); -} - -inline -Mat Mat::operator()( const Rect& roi ) const -{ - return Mat(*this, roi); -} - -inline -Mat Mat::operator()(const Range* ranges) const -{ - return Mat(*this, ranges); -} - -inline -Mat Mat::operator()(const std::vector& ranges) const -{ - return Mat(*this, ranges); -} - -inline -bool Mat::isContinuous() const -{ - return (flags & CONTINUOUS_FLAG) != 0; -} - -inline -bool Mat::isSubmatrix() const -{ - return (flags & SUBMATRIX_FLAG) != 0; -} - -inline -size_t Mat::elemSize() const -{ - size_t res = dims > 0 ? step.p[dims - 1] : 0; - CV_DbgAssert(res != 0); - return res; -} - -inline -size_t Mat::elemSize1() const -{ - return CV_ELEM_SIZE1(flags); -} - -inline -int Mat::type() const -{ - return CV_MAT_TYPE(flags); -} - -inline -int Mat::depth() const -{ - return CV_MAT_DEPTH(flags); -} - -inline -int Mat::channels() const -{ - return CV_MAT_CN(flags); -} - -inline -uchar* Mat::ptr(int y) -{ - CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) ); - return data + step.p[0] * y; -} - -inline -const uchar* Mat::ptr(int y) const -{ - CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) ); - return data + step.p[0] * y; -} - -template inline -_Tp* Mat::ptr(int y) -{ - CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) ); - return (_Tp*)(data + step.p[0] * y); -} - -template inline -const _Tp* Mat::ptr(int y) const -{ - CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) ); - return (const _Tp*)(data + step.p[0] * y); -} - -inline -uchar* Mat::ptr(int i0, int i1) -{ - CV_DbgAssert(dims >= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); - return data + i0 * step.p[0] + i1 * step.p[1]; -} - -inline -const uchar* Mat::ptr(int i0, int i1) const -{ - CV_DbgAssert(dims >= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); - return data + i0 * step.p[0] + i1 * step.p[1]; -} - -template inline -_Tp* Mat::ptr(int i0, int i1) -{ - CV_DbgAssert(dims >= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); - return (_Tp*)(data + i0 * step.p[0] + i1 * step.p[1]); -} - -template inline -const _Tp* Mat::ptr(int i0, int i1) const -{ - CV_DbgAssert(dims >= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); - return (const _Tp*)(data + i0 * step.p[0] + i1 * step.p[1]); -} - -inline -uchar* Mat::ptr(int i0, int i1, int i2) -{ - CV_DbgAssert(dims >= 3); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); - CV_DbgAssert((unsigned)i2 < (unsigned)size.p[2]); - return data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2]; -} - -inline -const uchar* Mat::ptr(int i0, int i1, int i2) const -{ - CV_DbgAssert(dims >= 3); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); - CV_DbgAssert((unsigned)i2 < (unsigned)size.p[2]); - return data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2]; -} - -template inline -_Tp* Mat::ptr(int i0, int i1, int i2) -{ - CV_DbgAssert(dims >= 3); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); - CV_DbgAssert((unsigned)i2 < (unsigned)size.p[2]); - return (_Tp*)(data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2]); -} - -template inline -const _Tp* Mat::ptr(int i0, int i1, int i2) const -{ - CV_DbgAssert(dims >= 3); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); - CV_DbgAssert((unsigned)i2 < (unsigned)size.p[2]); - return (const _Tp*)(data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2]); -} - -inline -uchar* Mat::ptr(const int* idx) -{ - int i, d = dims; - uchar* p = data; - CV_DbgAssert( d >= 1 && p ); - for( i = 0; i < d; i++ ) - { - CV_DbgAssert( (unsigned)idx[i] < (unsigned)size.p[i] ); - p += idx[i] * step.p[i]; - } - return p; -} - -inline -const uchar* Mat::ptr(const int* idx) const -{ - int i, d = dims; - uchar* p = data; - CV_DbgAssert( d >= 1 && p ); - for( i = 0; i < d; i++ ) - { - CV_DbgAssert( (unsigned)idx[i] < (unsigned)size.p[i] ); - p += idx[i] * step.p[i]; - } - return p; -} - -template inline -_Tp* Mat::ptr(const int* idx) -{ - int i, d = dims; - uchar* p = data; - CV_DbgAssert( d >= 1 && p ); - for( i = 0; i < d; i++ ) - { - CV_DbgAssert( (unsigned)idx[i] < (unsigned)size.p[i] ); - p += idx[i] * step.p[i]; - } - return (_Tp*)p; -} - -template inline -const _Tp* Mat::ptr(const int* idx) const -{ - int i, d = dims; - uchar* p = data; - CV_DbgAssert( d >= 1 && p ); - for( i = 0; i < d; i++ ) - { - CV_DbgAssert( (unsigned)idx[i] < (unsigned)size.p[i] ); - p += idx[i] * step.p[i]; - } - return (const _Tp*)p; -} - -template inline -uchar* Mat::ptr(const Vec& idx) -{ - return Mat::ptr(idx.val); -} - -template inline -const uchar* Mat::ptr(const Vec& idx) const -{ - return Mat::ptr(idx.val); -} - -template inline -_Tp* Mat::ptr(const Vec& idx) -{ - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return Mat::ptr<_Tp>(idx.val); -} - -template inline -const _Tp* Mat::ptr(const Vec& idx) const -{ - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return Mat::ptr<_Tp>(idx.val); -} - - -template inline -_Tp& Mat::at(int i0, int i1) -{ - CV_DbgAssert(dims <= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)(i1 * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels())); - CV_DbgAssert(CV_ELEM_SIZE1(traits::Depth<_Tp>::value) == elemSize1()); - return ((_Tp*)(data + step.p[0] * i0))[i1]; -} - -template inline -const _Tp& Mat::at(int i0, int i1) const -{ - CV_DbgAssert(dims <= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)(i1 * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels())); - CV_DbgAssert(CV_ELEM_SIZE1(traits::Depth<_Tp>::value) == elemSize1()); - return ((const _Tp*)(data + step.p[0] * i0))[i1]; -} - -template inline -_Tp& Mat::at(Point pt) -{ - CV_DbgAssert(dims <= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)pt.y < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)(pt.x * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels())); - CV_DbgAssert(CV_ELEM_SIZE1(traits::Depth<_Tp>::value) == elemSize1()); - return ((_Tp*)(data + step.p[0] * pt.y))[pt.x]; -} - -template inline -const _Tp& Mat::at(Point pt) const -{ - CV_DbgAssert(dims <= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)pt.y < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)(pt.x * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels())); - CV_DbgAssert(CV_ELEM_SIZE1(traits::Depth<_Tp>::value) == elemSize1()); - return ((const _Tp*)(data + step.p[0] * pt.y))[pt.x]; -} - -template inline -_Tp& Mat::at(int i0) -{ - CV_DbgAssert(dims <= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)(size.p[0] * size.p[1])); - CV_DbgAssert(elemSize() == sizeof(_Tp)); - if( isContinuous() || size.p[0] == 1 ) - return ((_Tp*)data)[i0]; - if( size.p[1] == 1 ) - return *(_Tp*)(data + step.p[0] * i0); - int i = i0 / cols, j = i0 - i * cols; - return ((_Tp*)(data + step.p[0] * i))[j]; -} - -template inline -const _Tp& Mat::at(int i0) const -{ - CV_DbgAssert(dims <= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)(size.p[0] * size.p[1])); - CV_DbgAssert(elemSize() == sizeof(_Tp)); - if( isContinuous() || size.p[0] == 1 ) - return ((const _Tp*)data)[i0]; - if( size.p[1] == 1 ) - return *(const _Tp*)(data + step.p[0] * i0); - int i = i0 / cols, j = i0 - i * cols; - return ((const _Tp*)(data + step.p[0] * i))[j]; -} - -template inline -_Tp& Mat::at(int i0, int i1, int i2) -{ - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return *(_Tp*)ptr(i0, i1, i2); -} - -template inline -const _Tp& Mat::at(int i0, int i1, int i2) const -{ - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return *(const _Tp*)ptr(i0, i1, i2); -} - -template inline -_Tp& Mat::at(const int* idx) -{ - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return *(_Tp*)ptr(idx); -} - -template inline -const _Tp& Mat::at(const int* idx) const -{ - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return *(const _Tp*)ptr(idx); -} - -template inline -_Tp& Mat::at(const Vec& idx) -{ - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return *(_Tp*)ptr(idx.val); -} - -template inline -const _Tp& Mat::at(const Vec& idx) const -{ - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return *(const _Tp*)ptr(idx.val); -} - -template inline -MatConstIterator_<_Tp> Mat::begin() const -{ - if (empty()) - return MatConstIterator_<_Tp>(); - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return MatConstIterator_<_Tp>((const Mat_<_Tp>*)this); -} - -template inline -std::reverse_iterator> Mat::rbegin() const -{ - if (empty()) - return std::reverse_iterator>(); - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - MatConstIterator_<_Tp> it((const Mat_<_Tp>*)this); - it += total(); - return std::reverse_iterator> (it); -} - -template inline -MatConstIterator_<_Tp> Mat::end() const -{ - if (empty()) - return MatConstIterator_<_Tp>(); - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - MatConstIterator_<_Tp> it((const Mat_<_Tp>*)this); - it += total(); - return it; -} - -template inline -std::reverse_iterator> Mat::rend() const -{ - if (empty()) - return std::reverse_iterator>(); - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return std::reverse_iterator>((const Mat_<_Tp>*)this); -} - -template inline -MatIterator_<_Tp> Mat::begin() -{ - if (empty()) - return MatIterator_<_Tp>(); - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return MatIterator_<_Tp>((Mat_<_Tp>*)this); -} - -template inline -std::reverse_iterator> Mat::rbegin() -{ - if (empty()) - return std::reverse_iterator>(); - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - MatIterator_<_Tp> it((Mat_<_Tp>*)this); - it += total(); - return std::reverse_iterator>(it); -} - -template inline -MatIterator_<_Tp> Mat::end() -{ - if (empty()) - return MatIterator_<_Tp>(); - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - MatIterator_<_Tp> it((Mat_<_Tp>*)this); - it += total(); - return it; -} - -template inline -std::reverse_iterator> Mat::rend() -{ - if (empty()) - return std::reverse_iterator>(); - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return std::reverse_iterator>(MatIterator_<_Tp>((Mat_<_Tp>*)this)); -} - -template inline -void Mat::forEach(const Functor& operation) { - this->forEach_impl<_Tp>(operation); -} - -template inline -void Mat::forEach(const Functor& operation) const { - // call as not const - (const_cast(this))->forEach<_Tp>(operation); -} - -template inline -Mat::operator std::vector<_Tp>() const -{ - std::vector<_Tp> v; - copyTo(v); - return v; -} - -template inline -Mat::operator std::array<_Tp, _Nm>() const -{ - std::array<_Tp, _Nm> v; - copyTo(v); - return v; -} - -template inline -Mat::operator Vec<_Tp, n>() const -{ - CV_Assert( data && dims <= 2 && (rows == 1 || cols == 1) && - rows + cols - 1 == n && channels() == 1 ); - - if( isContinuous() && type() == traits::Type<_Tp>::value ) - return Vec<_Tp, n>((_Tp*)data); - Vec<_Tp, n> v; - Mat tmp(rows, cols, traits::Type<_Tp>::value, v.val); - convertTo(tmp, tmp.type()); - return v; -} - -template inline -Mat::operator Matx<_Tp, m, n>() const -{ - CV_Assert( data && dims <= 2 && rows == m && cols == n && channels() == 1 ); - - if( isContinuous() && type() == traits::Type<_Tp>::value ) - return Matx<_Tp, m, n>((_Tp*)data); - Matx<_Tp, m, n> mtx; - Mat tmp(rows, cols, traits::Type<_Tp>::value, mtx.val); - convertTo(tmp, tmp.type()); - return mtx; -} - -template inline -void Mat::push_back(const _Tp& elem) -{ - if( !data ) - { - *this = Mat(1, 1, traits::Type<_Tp>::value, (void*)&elem).clone(); - return; - } - CV_Assert(traits::Type<_Tp>::value == type() && cols == 1 - /* && dims == 2 (cols == 1 implies dims == 2) */); - const uchar* tmp = dataend + step[0]; - if( !isSubmatrix() && isContinuous() && tmp <= datalimit ) - { - *(_Tp*)(data + (size.p[0]++) * step.p[0]) = elem; - dataend = tmp; - } - else - push_back_(&elem); -} - -template inline -void Mat::push_back(const Mat_<_Tp>& m) -{ - push_back((const Mat&)m); -} - -template<> inline -void Mat::push_back(const MatExpr& expr) -{ - push_back(static_cast(expr)); -} - - -template inline -void Mat::push_back(const std::vector<_Tp>& v) -{ - push_back(Mat(v)); -} - - -///////////////////////////// MatSize //////////////////////////// - -inline -MatSize::MatSize(int* _p) CV_NOEXCEPT - : p(_p) {} - -inline -int MatSize::dims() const CV_NOEXCEPT -{ - return (p - 1)[0]; -} - -inline -Size MatSize::operator()() const -{ - CV_DbgAssert(dims() <= 2); - return Size(p[1], p[0]); -} - -inline -const int& MatSize::operator[](int i) const -{ - CV_DbgAssert(i < dims()); -#ifdef __OPENCV_BUILD - CV_DbgAssert(i >= 0); -#endif - return p[i]; -} - -inline -int& MatSize::operator[](int i) -{ - CV_DbgAssert(i < dims()); -#ifdef __OPENCV_BUILD - CV_DbgAssert(i >= 0); -#endif - return p[i]; -} - -inline -MatSize::operator const int*() const CV_NOEXCEPT -{ - return p; -} - -inline -bool MatSize::operator != (const MatSize& sz) const CV_NOEXCEPT -{ - return !(*this == sz); -} - - - -///////////////////////////// MatStep //////////////////////////// - -inline -MatStep::MatStep() CV_NOEXCEPT -{ - p = buf; p[0] = p[1] = 0; -} - -inline -MatStep::MatStep(size_t s) CV_NOEXCEPT -{ - p = buf; p[0] = s; p[1] = 0; -} - -inline -const size_t& MatStep::operator[](int i) const CV_NOEXCEPT -{ - return p[i]; -} - -inline -size_t& MatStep::operator[](int i) CV_NOEXCEPT -{ - return p[i]; -} - -inline MatStep::operator size_t() const -{ - CV_DbgAssert( p == buf ); - return buf[0]; -} - -inline MatStep& MatStep::operator = (size_t s) -{ - CV_DbgAssert( p == buf ); - buf[0] = s; - return *this; -} - - - -////////////////////////////// Mat_<_Tp> //////////////////////////// - -template inline -Mat_<_Tp>::Mat_() CV_NOEXCEPT - : Mat() -{ - flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value; -} - -template inline -Mat_<_Tp>::Mat_(int _rows, int _cols) - : Mat(_rows, _cols, traits::Type<_Tp>::value) -{ -} - -template inline -Mat_<_Tp>::Mat_(int _rows, int _cols, const _Tp& value) - : Mat(_rows, _cols, traits::Type<_Tp>::value) -{ - *this = value; -} - -template inline -Mat_<_Tp>::Mat_(Size _sz) - : Mat(_sz.height, _sz.width, traits::Type<_Tp>::value) -{} - -template inline -Mat_<_Tp>::Mat_(Size _sz, const _Tp& value) - : Mat(_sz.height, _sz.width, traits::Type<_Tp>::value) -{ - *this = value; -} - -template inline -Mat_<_Tp>::Mat_(int _dims, const int* _sz) - : Mat(_dims, _sz, traits::Type<_Tp>::value) -{} - -template inline -Mat_<_Tp>::Mat_(int _dims, const int* _sz, const _Tp& _s) - : Mat(_dims, _sz, traits::Type<_Tp>::value, Scalar(_s)) -{} - -template inline -Mat_<_Tp>::Mat_(int _dims, const int* _sz, _Tp* _data, const size_t* _steps) - : Mat(_dims, _sz, traits::Type<_Tp>::value, _data, _steps) -{} - -template inline -Mat_<_Tp>::Mat_(const Mat_<_Tp>& m, const Range* ranges) - : Mat(m, ranges) -{} - -template inline -Mat_<_Tp>::Mat_(const Mat_<_Tp>& m, const std::vector& ranges) - : Mat(m, ranges) -{} - -template inline -Mat_<_Tp>::Mat_(const Mat& m) - : Mat() -{ - flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value; - *this = m; -} - -template inline -Mat_<_Tp>::Mat_(const Mat_& m) - : Mat(m) -{} - -template inline -Mat_<_Tp>::Mat_(int _rows, int _cols, _Tp* _data, size_t steps) - : Mat(_rows, _cols, traits::Type<_Tp>::value, _data, steps) -{} - -template inline -Mat_<_Tp>::Mat_(const Mat_& m, const Range& _rowRange, const Range& _colRange) - : Mat(m, _rowRange, _colRange) -{} - -template inline -Mat_<_Tp>::Mat_(const Mat_& m, const Rect& roi) - : Mat(m, roi) -{} - -template template inline -Mat_<_Tp>::Mat_(const Vec::channel_type, n>& vec, bool copyData) - : Mat(n / DataType<_Tp>::channels, 1, traits::Type<_Tp>::value, (void*)&vec) -{ - CV_Assert(n%DataType<_Tp>::channels == 0); - if( copyData ) - *this = clone(); -} - -template template inline -Mat_<_Tp>::Mat_(const Matx::channel_type, m, n>& M, bool copyData) - : Mat(m, n / DataType<_Tp>::channels, traits::Type<_Tp>::value, (void*)&M) -{ - CV_Assert(n % DataType<_Tp>::channels == 0); - if( copyData ) - *this = clone(); -} - -template inline -Mat_<_Tp>::Mat_(const Point_::channel_type>& pt, bool copyData) - : Mat(2 / DataType<_Tp>::channels, 1, traits::Type<_Tp>::value, (void*)&pt) -{ - CV_Assert(2 % DataType<_Tp>::channels == 0); - if( copyData ) - *this = clone(); -} - -template inline -Mat_<_Tp>::Mat_(const Point3_::channel_type>& pt, bool copyData) - : Mat(3 / DataType<_Tp>::channels, 1, traits::Type<_Tp>::value, (void*)&pt) -{ - CV_Assert(3 % DataType<_Tp>::channels == 0); - if( copyData ) - *this = clone(); -} - -template inline -Mat_<_Tp>::Mat_(const MatCommaInitializer_<_Tp>& commaInitializer) - : Mat(commaInitializer) -{} - -template inline -Mat_<_Tp>::Mat_(const std::vector<_Tp>& vec, bool copyData) - : Mat(vec, copyData) -{} - -template inline -Mat_<_Tp>::Mat_(std::initializer_list<_Tp> list) - : Mat(list) -{} - -template inline -Mat_<_Tp>::Mat_(const std::initializer_list sizes, std::initializer_list<_Tp> list) - : Mat(sizes, list) -{} - -template template inline -Mat_<_Tp>::Mat_(const std::array<_Tp, _Nm>& arr, bool copyData) - : Mat(arr, copyData) -{} - -template inline -Mat_<_Tp>& Mat_<_Tp>::operator = (const Mat& m) -{ - if (m.empty()) - { - release(); - return *this; - } - if( traits::Type<_Tp>::value == m.type() ) - { - Mat::operator = (m); - return *this; - } - if( traits::Depth<_Tp>::value == m.depth() ) - { - return (*this = m.reshape(DataType<_Tp>::channels, m.dims, 0)); - } - CV_Assert(DataType<_Tp>::channels == m.channels() || m.empty()); - m.convertTo(*this, type()); - return *this; -} - -template inline -Mat_<_Tp>& Mat_<_Tp>::operator = (const Mat_& m) -{ - Mat::operator=(m); - return *this; -} - -template inline -Mat_<_Tp>& Mat_<_Tp>::operator = (const _Tp& s) -{ - typedef typename DataType<_Tp>::vec_type VT; - Mat::operator=(Scalar((const VT&)s)); - return *this; -} - -template inline -void Mat_<_Tp>::create(int _rows, int _cols) -{ - Mat::create(_rows, _cols, traits::Type<_Tp>::value); -} - -template inline -void Mat_<_Tp>::create(Size _sz) -{ - Mat::create(_sz, traits::Type<_Tp>::value); -} - -template inline -void Mat_<_Tp>::create(int _dims, const int* _sz) -{ - Mat::create(_dims, _sz, traits::Type<_Tp>::value); -} - -template inline -void Mat_<_Tp>::release() -{ - Mat::release(); - flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value; -} - -template inline -Mat_<_Tp> Mat_<_Tp>::cross(const Mat_& m) const -{ - return Mat_<_Tp>(Mat::cross(m)); -} - -template template inline -Mat_<_Tp>::operator Mat_() const -{ - return Mat_(static_cast(*this)); -} - -template inline -Mat_<_Tp> Mat_<_Tp>::row(int y) const -{ - return Mat_(*this, Range(y, y+1), Range::all()); -} - -template inline -Mat_<_Tp> Mat_<_Tp>::col(int x) const -{ - return Mat_(*this, Range::all(), Range(x, x+1)); -} - -template inline -Mat_<_Tp> Mat_<_Tp>::diag(int d) const -{ - return Mat_(Mat::diag(d)); -} - -template inline -Mat_<_Tp> Mat_<_Tp>::clone() const -{ - return Mat_(Mat::clone()); -} - -template inline -size_t Mat_<_Tp>::elemSize() const -{ - CV_DbgAssert( Mat::elemSize() == sizeof(_Tp) ); - return sizeof(_Tp); -} - -template inline -size_t Mat_<_Tp>::elemSize1() const -{ - CV_DbgAssert( Mat::elemSize1() == sizeof(_Tp) / DataType<_Tp>::channels ); - return sizeof(_Tp) / DataType<_Tp>::channels; -} - -template inline -int Mat_<_Tp>::type() const -{ - CV_DbgAssert( Mat::type() == traits::Type<_Tp>::value ); - return traits::Type<_Tp>::value; -} - -template inline -int Mat_<_Tp>::depth() const -{ - CV_DbgAssert( Mat::depth() == traits::Depth<_Tp>::value ); - return traits::Depth<_Tp>::value; -} - -template inline -int Mat_<_Tp>::channels() const -{ - CV_DbgAssert( Mat::channels() == DataType<_Tp>::channels ); - return DataType<_Tp>::channels; -} - -template inline -size_t Mat_<_Tp>::stepT(int i) const -{ - return step.p[i] / elemSize(); -} - -template inline -size_t Mat_<_Tp>::step1(int i) const -{ - return step.p[i] / elemSize1(); -} - -template inline -Mat_<_Tp>& Mat_<_Tp>::adjustROI( int dtop, int dbottom, int dleft, int dright ) -{ - return (Mat_<_Tp>&)(Mat::adjustROI(dtop, dbottom, dleft, dright)); -} - -template inline -Mat_<_Tp> Mat_<_Tp>::operator()( const Range& _rowRange, const Range& _colRange ) const -{ - return Mat_<_Tp>(*this, _rowRange, _colRange); -} - -template inline -Mat_<_Tp> Mat_<_Tp>::operator()( const Rect& roi ) const -{ - return Mat_<_Tp>(*this, roi); -} - -template inline -Mat_<_Tp> Mat_<_Tp>::operator()( const Range* ranges ) const -{ - return Mat_<_Tp>(*this, ranges); -} - -template inline -Mat_<_Tp> Mat_<_Tp>::operator()(const std::vector& ranges) const -{ - return Mat_<_Tp>(*this, ranges); -} - -template inline -_Tp* Mat_<_Tp>::operator [](int y) -{ - CV_DbgAssert( 0 <= y && y < size.p[0] ); - return (_Tp*)(data + y*step.p[0]); -} - -template inline -const _Tp* Mat_<_Tp>::operator [](int y) const -{ - CV_DbgAssert( 0 <= y && y < size.p[0] ); - return (const _Tp*)(data + y*step.p[0]); -} - -template inline -_Tp& Mat_<_Tp>::operator ()(int i0, int i1) -{ - CV_DbgAssert(dims <= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); - CV_DbgAssert(type() == traits::Type<_Tp>::value); - return ((_Tp*)(data + step.p[0] * i0))[i1]; -} - -template inline -const _Tp& Mat_<_Tp>::operator ()(int i0, int i1) const -{ - CV_DbgAssert(dims <= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); - CV_DbgAssert(type() == traits::Type<_Tp>::value); - return ((const _Tp*)(data + step.p[0] * i0))[i1]; -} - -template inline -_Tp& Mat_<_Tp>::operator ()(Point pt) -{ - CV_DbgAssert(dims <= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)pt.y < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)pt.x < (unsigned)size.p[1]); - CV_DbgAssert(type() == traits::Type<_Tp>::value); - return ((_Tp*)(data + step.p[0] * pt.y))[pt.x]; -} - -template inline -const _Tp& Mat_<_Tp>::operator ()(Point pt) const -{ - CV_DbgAssert(dims <= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)pt.y < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)pt.x < (unsigned)size.p[1]); - CV_DbgAssert(type() == traits::Type<_Tp>::value); - return ((const _Tp*)(data + step.p[0] * pt.y))[pt.x]; -} - -template inline -_Tp& Mat_<_Tp>::operator ()(const int* idx) -{ - return Mat::at<_Tp>(idx); -} - -template inline -const _Tp& Mat_<_Tp>::operator ()(const int* idx) const -{ - return Mat::at<_Tp>(idx); -} - -template template inline -_Tp& Mat_<_Tp>::operator ()(const Vec& idx) -{ - return Mat::at<_Tp>(idx); -} - -template template inline -const _Tp& Mat_<_Tp>::operator ()(const Vec& idx) const -{ - return Mat::at<_Tp>(idx); -} - -template inline -_Tp& Mat_<_Tp>::operator ()(int i0) -{ - return this->at<_Tp>(i0); -} - -template inline -const _Tp& Mat_<_Tp>::operator ()(int i0) const -{ - return this->at<_Tp>(i0); -} - -template inline -_Tp& Mat_<_Tp>::operator ()(int i0, int i1, int i2) -{ - return this->at<_Tp>(i0, i1, i2); -} - -template inline -const _Tp& Mat_<_Tp>::operator ()(int i0, int i1, int i2) const -{ - return this->at<_Tp>(i0, i1, i2); -} - -template inline -Mat_<_Tp>::operator std::vector<_Tp>() const -{ - std::vector<_Tp> v; - copyTo(v); - return v; -} - -template template inline -Mat_<_Tp>::operator std::array<_Tp, _Nm>() const -{ - std::array<_Tp, _Nm> a; - copyTo(a); - return a; -} - -template template inline -Mat_<_Tp>::operator Vec::channel_type, n>() const -{ - CV_Assert(n % DataType<_Tp>::channels == 0); - -#if defined _MSC_VER - const Mat* pMat = (const Mat*)this; // workaround for MSVS <= 2012 compiler bugs (but GCC 4.6 dislikes this workaround) - return pMat->operator Vec::channel_type, n>(); -#else - return this->Mat::operator Vec::channel_type, n>(); -#endif -} - -template template inline -Mat_<_Tp>::operator Matx::channel_type, m, n>() const -{ - CV_Assert(n % DataType<_Tp>::channels == 0); - -#if defined _MSC_VER - const Mat* pMat = (const Mat*)this; // workaround for MSVS <= 2012 compiler bugs (but GCC 4.6 dislikes this workaround) - Matx::channel_type, m, n> res = pMat->operator Matx::channel_type, m, n>(); - return res; -#else - Matx::channel_type, m, n> res = this->Mat::operator Matx::channel_type, m, n>(); - return res; -#endif -} - -template inline -MatConstIterator_<_Tp> Mat_<_Tp>::begin() const -{ - return Mat::begin<_Tp>(); -} - -template inline -std::reverse_iterator> Mat_<_Tp>::rbegin() const -{ - return Mat::rbegin<_Tp>(); -} - -template inline -MatConstIterator_<_Tp> Mat_<_Tp>::end() const -{ - return Mat::end<_Tp>(); -} - -template inline -std::reverse_iterator> Mat_<_Tp>::rend() const -{ - return Mat::rend<_Tp>(); -} - -template inline -MatIterator_<_Tp> Mat_<_Tp>::begin() -{ - return Mat::begin<_Tp>(); -} - -template inline -std::reverse_iterator> Mat_<_Tp>::rbegin() -{ - return Mat::rbegin<_Tp>(); -} - -template inline -MatIterator_<_Tp> Mat_<_Tp>::end() -{ - return Mat::end<_Tp>(); -} - -template inline -std::reverse_iterator> Mat_<_Tp>::rend() -{ - return Mat::rend<_Tp>(); -} - -template template inline -void Mat_<_Tp>::forEach(const Functor& operation) { - Mat::forEach<_Tp, Functor>(operation); -} - -template template inline -void Mat_<_Tp>::forEach(const Functor& operation) const { - Mat::forEach<_Tp, Functor>(operation); -} - -template inline -Mat_<_Tp>::Mat_(Mat_&& m) - : Mat(std::move(m)) -{ -} - -template inline -Mat_<_Tp>& Mat_<_Tp>::operator = (Mat_&& m) -{ - Mat::operator = (std::move(m)); - return *this; -} - -template inline -Mat_<_Tp>::Mat_(Mat&& m) - : Mat() -{ - flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value; - *this = std::move(m); -} - -template inline -Mat_<_Tp>& Mat_<_Tp>::operator = (Mat&& m) -{ - if (m.empty()) - { - release(); - return *this; - } - if( traits::Type<_Tp>::value == m.type() ) - { - Mat::operator = ((Mat&&)m); - return *this; - } - if( traits::Depth<_Tp>::value == m.depth() ) - { - Mat::operator = ((Mat&&)m.reshape(DataType<_Tp>::channels, m.dims, 0)); - return *this; - } - CV_DbgAssert(DataType<_Tp>::channels == m.channels()); - m.convertTo(*this, type()); - return *this; -} - -template inline -Mat_<_Tp>::Mat_(MatExpr&& e) - : Mat() -{ - flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value; - *this = Mat(e); -} - - -///////////////////////////// SparseMat ///////////////////////////// - -inline -SparseMat SparseMat::clone() const -{ - SparseMat temp; - this->copyTo(temp); - return temp; -} - -inline -size_t SparseMat::elemSize() const -{ - return CV_ELEM_SIZE(flags); -} - -inline -size_t SparseMat::elemSize1() const -{ - return CV_ELEM_SIZE1(flags); -} - -inline -int SparseMat::type() const -{ - return CV_MAT_TYPE(flags); -} - -inline -int SparseMat::depth() const -{ - return CV_MAT_DEPTH(flags); -} - -inline -int SparseMat::channels() const -{ - return CV_MAT_CN(flags); -} - -inline -const int* SparseMat::size() const -{ - return hdr ? hdr->size : 0; -} - -inline -int SparseMat::size(int i) const -{ - if( hdr ) - { - CV_DbgAssert((unsigned)i < (unsigned)hdr->dims); - return hdr->size[i]; - } - return 0; -} - -inline -int SparseMat::dims() const -{ - return hdr ? hdr->dims : 0; -} - -inline -size_t SparseMat::nzcount() const -{ - return hdr ? hdr->nodeCount : 0; -} - -template inline -_Tp& SparseMat::ref(int i0, size_t* hashval) -{ - return *(_Tp*)((SparseMat*)this)->ptr(i0, true, hashval); -} - -template inline -_Tp& SparseMat::ref(int i0, int i1, size_t* hashval) -{ - return *(_Tp*)((SparseMat*)this)->ptr(i0, i1, true, hashval); -} - -template inline -_Tp& SparseMat::ref(int i0, int i1, int i2, size_t* hashval) -{ - return *(_Tp*)((SparseMat*)this)->ptr(i0, i1, i2, true, hashval); -} - -template inline -_Tp& SparseMat::ref(const int* idx, size_t* hashval) -{ - return *(_Tp*)((SparseMat*)this)->ptr(idx, true, hashval); -} - -template inline -_Tp SparseMat::value(int i0, size_t* hashval) const -{ - const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(i0, false, hashval); - return p ? *p : _Tp(); -} - -template inline -_Tp SparseMat::value(int i0, int i1, size_t* hashval) const -{ - const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(i0, i1, false, hashval); - return p ? *p : _Tp(); -} - -template inline -_Tp SparseMat::value(int i0, int i1, int i2, size_t* hashval) const -{ - const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(i0, i1, i2, false, hashval); - return p ? *p : _Tp(); -} - -template inline -_Tp SparseMat::value(const int* idx, size_t* hashval) const -{ - const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(idx, false, hashval); - return p ? *p : _Tp(); -} - -template inline -const _Tp* SparseMat::find(int i0, size_t* hashval) const -{ - return (const _Tp*)((SparseMat*)this)->ptr(i0, false, hashval); -} - -template inline -const _Tp* SparseMat::find(int i0, int i1, size_t* hashval) const -{ - return (const _Tp*)((SparseMat*)this)->ptr(i0, i1, false, hashval); -} - -template inline -const _Tp* SparseMat::find(int i0, int i1, int i2, size_t* hashval) const -{ - return (const _Tp*)((SparseMat*)this)->ptr(i0, i1, i2, false, hashval); -} - -template inline -const _Tp* SparseMat::find(const int* idx, size_t* hashval) const -{ - return (const _Tp*)((SparseMat*)this)->ptr(idx, false, hashval); -} - -template inline -_Tp& SparseMat::value(Node* n) -{ - return *(_Tp*)((uchar*)n + hdr->valueOffset); -} - -template inline -const _Tp& SparseMat::value(const Node* n) const -{ - return *(const _Tp*)((const uchar*)n + hdr->valueOffset); -} - -inline -SparseMat::Node* SparseMat::node(size_t nidx) -{ - return (Node*)(void*)&hdr->pool[nidx]; -} - -inline -const SparseMat::Node* SparseMat::node(size_t nidx) const -{ - return (const Node*)(const void*)&hdr->pool[nidx]; -} - -inline -SparseMatIterator SparseMat::begin() -{ - return SparseMatIterator(this); -} - -inline -SparseMatConstIterator SparseMat::begin() const -{ - return SparseMatConstIterator(this); -} - -inline -SparseMatIterator SparseMat::end() -{ - SparseMatIterator it(this); - it.seekEnd(); - return it; -} - -inline -SparseMatConstIterator SparseMat::end() const -{ - SparseMatConstIterator it(this); - it.seekEnd(); - return it; -} - -template inline -SparseMatIterator_<_Tp> SparseMat::begin() -{ - return SparseMatIterator_<_Tp>(this); -} - -template inline -SparseMatConstIterator_<_Tp> SparseMat::begin() const -{ - return SparseMatConstIterator_<_Tp>(this); -} - -template inline -SparseMatIterator_<_Tp> SparseMat::end() -{ - SparseMatIterator_<_Tp> it(this); - it.seekEnd(); - return it; -} - -template inline -SparseMatConstIterator_<_Tp> SparseMat::end() const -{ - SparseMatConstIterator_<_Tp> it(this); - it.seekEnd(); - return it; -} - - - -///////////////////////////// SparseMat_ //////////////////////////// - -template inline -SparseMat_<_Tp>::SparseMat_() -{ - flags = +MAGIC_VAL + traits::Type<_Tp>::value; -} - -template inline -SparseMat_<_Tp>::SparseMat_(int _dims, const int* _sizes) - : SparseMat(_dims, _sizes, traits::Type<_Tp>::value) -{} - -template inline -SparseMat_<_Tp>::SparseMat_(const SparseMat& m) -{ - if( m.type() == traits::Type<_Tp>::value ) - *this = (const SparseMat_<_Tp>&)m; - else - m.convertTo(*this, traits::Type<_Tp>::value); -} - -template inline -SparseMat_<_Tp>::SparseMat_(const SparseMat_<_Tp>& m) -{ - this->flags = m.flags; - this->hdr = m.hdr; - if( this->hdr ) - CV_XADD(&this->hdr->refcount, 1); -} - -template inline -SparseMat_<_Tp>::SparseMat_(const Mat& m) -{ - SparseMat sm(m); - *this = sm; -} - -template inline -SparseMat_<_Tp>& SparseMat_<_Tp>::operator = (const SparseMat_<_Tp>& m) -{ - if( this != &m ) - { - if( m.hdr ) CV_XADD(&m.hdr->refcount, 1); - release(); - flags = m.flags; - hdr = m.hdr; - } - return *this; -} - -template inline -SparseMat_<_Tp>& SparseMat_<_Tp>::operator = (const SparseMat& m) -{ - if( m.type() == traits::Type<_Tp>::value ) - return (*this = (const SparseMat_<_Tp>&)m); - m.convertTo(*this, traits::Type<_Tp>::value); - return *this; -} - -template inline -SparseMat_<_Tp>& SparseMat_<_Tp>::operator = (const Mat& m) -{ - return (*this = SparseMat(m)); -} - -template inline -SparseMat_<_Tp> SparseMat_<_Tp>::clone() const -{ - SparseMat_<_Tp> m; - this->copyTo(m); - return m; -} - -template inline -void SparseMat_<_Tp>::create(int _dims, const int* _sizes) -{ - SparseMat::create(_dims, _sizes, traits::Type<_Tp>::value); -} - -template inline -int SparseMat_<_Tp>::type() const -{ - return traits::Type<_Tp>::value; -} - -template inline -int SparseMat_<_Tp>::depth() const -{ - return traits::Depth<_Tp>::value; -} - -template inline -int SparseMat_<_Tp>::channels() const -{ - return DataType<_Tp>::channels; -} - -template inline -_Tp& SparseMat_<_Tp>::ref(int i0, size_t* hashval) -{ - return SparseMat::ref<_Tp>(i0, hashval); -} - -template inline -_Tp SparseMat_<_Tp>::operator()(int i0, size_t* hashval) const -{ - return SparseMat::value<_Tp>(i0, hashval); -} - -template inline -_Tp& SparseMat_<_Tp>::ref(int i0, int i1, size_t* hashval) -{ - return SparseMat::ref<_Tp>(i0, i1, hashval); -} - -template inline -_Tp SparseMat_<_Tp>::operator()(int i0, int i1, size_t* hashval) const -{ - return SparseMat::value<_Tp>(i0, i1, hashval); -} - -template inline -_Tp& SparseMat_<_Tp>::ref(int i0, int i1, int i2, size_t* hashval) -{ - return SparseMat::ref<_Tp>(i0, i1, i2, hashval); -} - -template inline -_Tp SparseMat_<_Tp>::operator()(int i0, int i1, int i2, size_t* hashval) const -{ - return SparseMat::value<_Tp>(i0, i1, i2, hashval); -} - -template inline -_Tp& SparseMat_<_Tp>::ref(const int* idx, size_t* hashval) -{ - return SparseMat::ref<_Tp>(idx, hashval); -} - -template inline -_Tp SparseMat_<_Tp>::operator()(const int* idx, size_t* hashval) const -{ - return SparseMat::value<_Tp>(idx, hashval); -} - -template inline -SparseMatIterator_<_Tp> SparseMat_<_Tp>::begin() -{ - return SparseMatIterator_<_Tp>(this); -} - -template inline -SparseMatConstIterator_<_Tp> SparseMat_<_Tp>::begin() const -{ - return SparseMatConstIterator_<_Tp>(this); -} - -template inline -SparseMatIterator_<_Tp> SparseMat_<_Tp>::end() -{ - SparseMatIterator_<_Tp> it(this); - it.seekEnd(); - return it; -} - -template inline -SparseMatConstIterator_<_Tp> SparseMat_<_Tp>::end() const -{ - SparseMatConstIterator_<_Tp> it(this); - it.seekEnd(); - return it; -} - - - -////////////////////////// MatConstIterator ///////////////////////// - -inline -MatConstIterator::MatConstIterator() - : m(0), elemSize(0), ptr(0), sliceStart(0), sliceEnd(0) -{} - -inline -MatConstIterator::MatConstIterator(const Mat* _m) - : m(_m), elemSize(_m->elemSize()), ptr(0), sliceStart(0), sliceEnd(0) -{ - if( m && m->isContinuous() ) - { - CV_Assert(!m->empty()); - sliceStart = m->ptr(); - sliceEnd = sliceStart + m->total()*elemSize; - } - seek((const int*)0); -} - -inline -MatConstIterator::MatConstIterator(const Mat* _m, int _row, int _col) - : m(_m), elemSize(_m->elemSize()), ptr(0), sliceStart(0), sliceEnd(0) -{ - CV_Assert(m && m->dims <= 2); - if( m->isContinuous() ) - { - CV_Assert(!m->empty()); - sliceStart = m->ptr(); - sliceEnd = sliceStart + m->total()*elemSize; - } - int idx[] = {_row, _col}; - seek(idx); -} - -inline -MatConstIterator::MatConstIterator(const Mat* _m, Point _pt) - : m(_m), elemSize(_m->elemSize()), ptr(0), sliceStart(0), sliceEnd(0) -{ - CV_Assert(m && m->dims <= 2); - if( m->isContinuous() ) - { - CV_Assert(!m->empty()); - sliceStart = m->ptr(); - sliceEnd = sliceStart + m->total()*elemSize; - } - int idx[] = {_pt.y, _pt.x}; - seek(idx); -} - -inline -MatConstIterator::MatConstIterator(const MatConstIterator& it) - : m(it.m), elemSize(it.elemSize), ptr(it.ptr), sliceStart(it.sliceStart), sliceEnd(it.sliceEnd) -{} - -inline -MatConstIterator& MatConstIterator::operator = (const MatConstIterator& it ) -{ - m = it.m; elemSize = it.elemSize; ptr = it.ptr; - sliceStart = it.sliceStart; sliceEnd = it.sliceEnd; - return *this; -} - -inline -const uchar* MatConstIterator::operator *() const -{ - return ptr; -} - -inline MatConstIterator& MatConstIterator::operator += (ptrdiff_t ofs) -{ - if( !m || ofs == 0 ) - return *this; - ptrdiff_t ofsb = ofs*elemSize; - ptr += ofsb; - if( ptr < sliceStart || sliceEnd <= ptr ) - { - ptr -= ofsb; - seek(ofs, true); - } - return *this; -} - -inline -MatConstIterator& MatConstIterator::operator -= (ptrdiff_t ofs) -{ - return (*this += -ofs); -} - -inline -MatConstIterator& MatConstIterator::operator --() -{ - if( m && (ptr -= elemSize) < sliceStart ) - { - ptr += elemSize; - seek(-1, true); - } - return *this; -} - -inline -MatConstIterator MatConstIterator::operator --(int) -{ - MatConstIterator b = *this; - *this += -1; - return b; -} - -inline -MatConstIterator& MatConstIterator::operator ++() -{ - if( m && (ptr += elemSize) >= sliceEnd ) - { - ptr -= elemSize; - seek(1, true); - } - return *this; -} - -inline MatConstIterator MatConstIterator::operator ++(int) -{ - MatConstIterator b = *this; - *this += 1; - return b; -} - - -static inline -bool operator == (const MatConstIterator& a, const MatConstIterator& b) -{ - return a.m == b.m && a.ptr == b.ptr; -} - -static inline -bool operator != (const MatConstIterator& a, const MatConstIterator& b) -{ - return !(a == b); -} - -static inline -bool operator < (const MatConstIterator& a, const MatConstIterator& b) -{ - return a.ptr < b.ptr; -} - -static inline -bool operator > (const MatConstIterator& a, const MatConstIterator& b) -{ - return a.ptr > b.ptr; -} - -static inline -bool operator <= (const MatConstIterator& a, const MatConstIterator& b) -{ - return a.ptr <= b.ptr; -} - -static inline -bool operator >= (const MatConstIterator& a, const MatConstIterator& b) -{ - return a.ptr >= b.ptr; -} - -static inline -ptrdiff_t operator - (const MatConstIterator& b, const MatConstIterator& a) -{ - if( a.m != b.m ) - return ((size_t)(-1) >> 1); - if( a.sliceEnd == b.sliceEnd ) - return (b.ptr - a.ptr)/static_cast(b.elemSize); - - return b.lpos() - a.lpos(); -} - -static inline -MatConstIterator operator + (const MatConstIterator& a, ptrdiff_t ofs) -{ - MatConstIterator b = a; - return b += ofs; -} - -static inline -MatConstIterator operator + (ptrdiff_t ofs, const MatConstIterator& a) -{ - MatConstIterator b = a; - return b += ofs; -} - -static inline -MatConstIterator operator - (const MatConstIterator& a, ptrdiff_t ofs) -{ - MatConstIterator b = a; - return b += -ofs; -} - - -inline -const uchar* MatConstIterator::operator [](ptrdiff_t i) const -{ - return *(*this + i); -} - - - -///////////////////////// MatConstIterator_ ///////////////////////// - -template inline -MatConstIterator_<_Tp>::MatConstIterator_() -{} - -template inline -MatConstIterator_<_Tp>::MatConstIterator_(const Mat_<_Tp>* _m) - : MatConstIterator(_m) -{} - -template inline -MatConstIterator_<_Tp>::MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col) - : MatConstIterator(_m, _row, _col) -{} - -template inline -MatConstIterator_<_Tp>::MatConstIterator_(const Mat_<_Tp>* _m, Point _pt) - : MatConstIterator(_m, _pt) -{} - -template inline -MatConstIterator_<_Tp>::MatConstIterator_(const MatConstIterator_& it) - : MatConstIterator(it) -{} - -template inline -MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator = (const MatConstIterator_& it ) -{ - MatConstIterator::operator = (it); - return *this; -} - -template inline -const _Tp& MatConstIterator_<_Tp>::operator *() const -{ - return *(_Tp*)(this->ptr); -} - -template inline -MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator += (ptrdiff_t ofs) -{ - MatConstIterator::operator += (ofs); - return *this; -} - -template inline -MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator -= (ptrdiff_t ofs) -{ - return (*this += -ofs); -} - -template inline -MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator --() -{ - MatConstIterator::operator --(); - return *this; -} - -template inline -MatConstIterator_<_Tp> MatConstIterator_<_Tp>::operator --(int) -{ - MatConstIterator_ b = *this; - MatConstIterator::operator --(); - return b; -} - -template inline -MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator ++() -{ - MatConstIterator::operator ++(); - return *this; -} - -template inline -MatConstIterator_<_Tp> MatConstIterator_<_Tp>::operator ++(int) -{ - MatConstIterator_ b = *this; - MatConstIterator::operator ++(); - return b; -} - - -template inline -Point MatConstIterator_<_Tp>::pos() const -{ - if( !m ) - return Point(); - CV_DbgAssert( m->dims <= 2 ); - if( m->isContinuous() ) - { - ptrdiff_t ofs = (const _Tp*)ptr - (const _Tp*)m->data; - int y = (int)(ofs / m->cols); - int x = (int)(ofs - (ptrdiff_t)y * m->cols); - return Point(x, y); - } - else - { - ptrdiff_t ofs = (uchar*)ptr - m->data; - int y = (int)(ofs / m->step); - int x = (int)((ofs - y * m->step)/sizeof(_Tp)); - return Point(x, y); - } -} - - -template static inline -bool operator == (const MatConstIterator_<_Tp>& a, const MatConstIterator_<_Tp>& b) -{ - return a.m == b.m && a.ptr == b.ptr; -} - -template static inline -bool operator != (const MatConstIterator_<_Tp>& a, const MatConstIterator_<_Tp>& b) -{ - return a.m != b.m || a.ptr != b.ptr; -} - -template static inline -MatConstIterator_<_Tp> operator + (const MatConstIterator_<_Tp>& a, ptrdiff_t ofs) -{ - MatConstIterator t = (const MatConstIterator&)a + ofs; - return (MatConstIterator_<_Tp>&)t; -} - -template static inline -MatConstIterator_<_Tp> operator + (ptrdiff_t ofs, const MatConstIterator_<_Tp>& a) -{ - MatConstIterator t = (const MatConstIterator&)a + ofs; - return (MatConstIterator_<_Tp>&)t; -} - -template static inline -MatConstIterator_<_Tp> operator - (const MatConstIterator_<_Tp>& a, ptrdiff_t ofs) -{ - MatConstIterator t = (const MatConstIterator&)a - ofs; - return (MatConstIterator_<_Tp>&)t; -} - -template inline -const _Tp& MatConstIterator_<_Tp>::operator [](ptrdiff_t i) const -{ - return *(_Tp*)MatConstIterator::operator [](i); -} - - - -//////////////////////////// MatIterator_ /////////////////////////// - -template inline -MatIterator_<_Tp>::MatIterator_() - : MatConstIterator_<_Tp>() -{} - -template inline -MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m) - : MatConstIterator_<_Tp>(_m) -{} - -template inline -MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m, int _row, int _col) - : MatConstIterator_<_Tp>(_m, _row, _col) -{} - -template inline -MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m, Point _pt) - : MatConstIterator_<_Tp>(_m, _pt) -{} - -template inline -MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m, const int* _idx) - : MatConstIterator_<_Tp>(_m, _idx) -{} - -template inline -MatIterator_<_Tp>::MatIterator_(const MatIterator_& it) - : MatConstIterator_<_Tp>(it) -{} - -template inline -MatIterator_<_Tp>& MatIterator_<_Tp>::operator = (const MatIterator_<_Tp>& it ) -{ - MatConstIterator::operator = (it); - return *this; -} - -template inline -_Tp& MatIterator_<_Tp>::operator *() const -{ - return *(_Tp*)(this->ptr); -} - -template inline -MatIterator_<_Tp>& MatIterator_<_Tp>::operator += (ptrdiff_t ofs) -{ - MatConstIterator::operator += (ofs); - return *this; -} - -template inline -MatIterator_<_Tp>& MatIterator_<_Tp>::operator -= (ptrdiff_t ofs) -{ - MatConstIterator::operator += (-ofs); - return *this; -} - -template inline -MatIterator_<_Tp>& MatIterator_<_Tp>::operator --() -{ - MatConstIterator::operator --(); - return *this; -} - -template inline -MatIterator_<_Tp> MatIterator_<_Tp>::operator --(int) -{ - MatIterator_ b = *this; - MatConstIterator::operator --(); - return b; -} - -template inline -MatIterator_<_Tp>& MatIterator_<_Tp>::operator ++() -{ - MatConstIterator::operator ++(); - return *this; -} - -template inline -MatIterator_<_Tp> MatIterator_<_Tp>::operator ++(int) -{ - MatIterator_ b = *this; - MatConstIterator::operator ++(); - return b; -} - -template inline -_Tp& MatIterator_<_Tp>::operator [](ptrdiff_t i) const -{ - return *(*this + i); -} - - -template static inline -bool operator == (const MatIterator_<_Tp>& a, const MatIterator_<_Tp>& b) -{ - return a.m == b.m && a.ptr == b.ptr; -} - -template static inline -bool operator != (const MatIterator_<_Tp>& a, const MatIterator_<_Tp>& b) -{ - return a.m != b.m || a.ptr != b.ptr; -} - -template static inline -MatIterator_<_Tp> operator + (const MatIterator_<_Tp>& a, ptrdiff_t ofs) -{ - MatConstIterator t = (const MatConstIterator&)a + ofs; - return (MatIterator_<_Tp>&)t; -} - -template static inline -MatIterator_<_Tp> operator + (ptrdiff_t ofs, const MatIterator_<_Tp>& a) -{ - MatConstIterator t = (const MatConstIterator&)a + ofs; - return (MatIterator_<_Tp>&)t; -} - -template static inline -MatIterator_<_Tp> operator - (const MatIterator_<_Tp>& a, ptrdiff_t ofs) -{ - MatConstIterator t = (const MatConstIterator&)a - ofs; - return (MatIterator_<_Tp>&)t; -} - - - -/////////////////////// SparseMatConstIterator ////////////////////// - -inline -SparseMatConstIterator::SparseMatConstIterator() - : m(0), hashidx(0), ptr(0) -{} - -inline -SparseMatConstIterator::SparseMatConstIterator(const SparseMatConstIterator& it) - : m(it.m), hashidx(it.hashidx), ptr(it.ptr) -{} - -inline SparseMatConstIterator& SparseMatConstIterator::operator = (const SparseMatConstIterator& it) -{ - if( this != &it ) - { - m = it.m; - hashidx = it.hashidx; - ptr = it.ptr; - } - return *this; -} - -template inline -const _Tp& SparseMatConstIterator::value() const -{ - return *(const _Tp*)ptr; -} - -inline -const SparseMat::Node* SparseMatConstIterator::node() const -{ - return (ptr && m && m->hdr) ? (const SparseMat::Node*)(const void*)(ptr - m->hdr->valueOffset) : 0; -} - -inline -SparseMatConstIterator SparseMatConstIterator::operator ++(int) -{ - SparseMatConstIterator it = *this; - ++*this; - return it; -} - -inline -void SparseMatConstIterator::seekEnd() -{ - if( m && m->hdr ) - { - hashidx = m->hdr->hashtab.size(); - ptr = 0; - } -} - - -static inline -bool operator == (const SparseMatConstIterator& it1, const SparseMatConstIterator& it2) -{ - return it1.m == it2.m && it1.ptr == it2.ptr; -} - -static inline -bool operator != (const SparseMatConstIterator& it1, const SparseMatConstIterator& it2) -{ - return !(it1 == it2); -} - - - -///////////////////////// SparseMatIterator ///////////////////////// - -inline -SparseMatIterator::SparseMatIterator() -{} - -inline -SparseMatIterator::SparseMatIterator(SparseMat* _m) - : SparseMatConstIterator(_m) -{} - -inline -SparseMatIterator::SparseMatIterator(const SparseMatIterator& it) - : SparseMatConstIterator(it) -{} - -inline -SparseMatIterator& SparseMatIterator::operator = (const SparseMatIterator& it) -{ - (SparseMatConstIterator&)*this = it; - return *this; -} - -template inline -_Tp& SparseMatIterator::value() const -{ - return *(_Tp*)ptr; -} - -inline -SparseMat::Node* SparseMatIterator::node() const -{ - return (SparseMat::Node*)SparseMatConstIterator::node(); -} - -inline -SparseMatIterator& SparseMatIterator::operator ++() -{ - SparseMatConstIterator::operator ++(); - return *this; -} - -inline -SparseMatIterator SparseMatIterator::operator ++(int) -{ - SparseMatIterator it = *this; - ++*this; - return it; -} - - - -////////////////////// SparseMatConstIterator_ ////////////////////// - -template inline -SparseMatConstIterator_<_Tp>::SparseMatConstIterator_() -{} - -template inline -SparseMatConstIterator_<_Tp>::SparseMatConstIterator_(const SparseMat_<_Tp>* _m) - : SparseMatConstIterator(_m) -{} - -template inline -SparseMatConstIterator_<_Tp>::SparseMatConstIterator_(const SparseMat* _m) - : SparseMatConstIterator(_m) -{ - CV_Assert( _m->type() == traits::Type<_Tp>::value ); -} - -template inline -SparseMatConstIterator_<_Tp>::SparseMatConstIterator_(const SparseMatConstIterator_<_Tp>& it) - : SparseMatConstIterator(it) -{} - -template inline -SparseMatConstIterator_<_Tp>& SparseMatConstIterator_<_Tp>::operator = (const SparseMatConstIterator_<_Tp>& it) -{ - return reinterpret_cast&> - (*reinterpret_cast(this) = - reinterpret_cast(it)); -} - -template inline -const _Tp& SparseMatConstIterator_<_Tp>::operator *() const -{ - return *(const _Tp*)this->ptr; -} - -template inline -SparseMatConstIterator_<_Tp>& SparseMatConstIterator_<_Tp>::operator ++() -{ - SparseMatConstIterator::operator ++(); - return *this; -} - -template inline -SparseMatConstIterator_<_Tp> SparseMatConstIterator_<_Tp>::operator ++(int) -{ - SparseMatConstIterator_<_Tp> it = *this; - SparseMatConstIterator::operator ++(); - return it; -} - - - -///////////////////////// SparseMatIterator_ //////////////////////// - -template inline -SparseMatIterator_<_Tp>::SparseMatIterator_() -{} - -template inline -SparseMatIterator_<_Tp>::SparseMatIterator_(SparseMat_<_Tp>* _m) - : SparseMatConstIterator_<_Tp>(_m) -{} - -template inline -SparseMatIterator_<_Tp>::SparseMatIterator_(SparseMat* _m) - : SparseMatConstIterator_<_Tp>(_m) -{} - -template inline -SparseMatIterator_<_Tp>::SparseMatIterator_(const SparseMatIterator_<_Tp>& it) - : SparseMatConstIterator_<_Tp>(it) -{} - -template inline -SparseMatIterator_<_Tp>& SparseMatIterator_<_Tp>::operator = (const SparseMatIterator_<_Tp>& it) -{ - return reinterpret_cast&> - (*reinterpret_cast(this) = - reinterpret_cast(it)); -} - -template inline -_Tp& SparseMatIterator_<_Tp>::operator *() const -{ - return *(_Tp*)this->ptr; -} - -template inline -SparseMatIterator_<_Tp>& SparseMatIterator_<_Tp>::operator ++() -{ - SparseMatConstIterator::operator ++(); - return *this; -} - -template inline -SparseMatIterator_<_Tp> SparseMatIterator_<_Tp>::operator ++(int) -{ - SparseMatIterator_<_Tp> it = *this; - SparseMatConstIterator::operator ++(); - return it; -} - - - -//////////////////////// MatCommaInitializer_ /////////////////////// - -template inline -MatCommaInitializer_<_Tp>::MatCommaInitializer_(Mat_<_Tp>* _m) - : it(_m) -{} - -template template inline -MatCommaInitializer_<_Tp>& MatCommaInitializer_<_Tp>::operator , (T2 v) -{ - CV_DbgAssert( this->it < ((const Mat_<_Tp>*)this->it.m)->end() ); - *this->it = _Tp(v); - ++this->it; - return *this; -} - -template inline -MatCommaInitializer_<_Tp>::operator Mat_<_Tp>() const -{ - CV_DbgAssert( this->it == ((const Mat_<_Tp>*)this->it.m)->end() ); - return Mat_<_Tp>(*this->it.m); -} - - -template static inline -MatCommaInitializer_<_Tp> operator << (const Mat_<_Tp>& m, T2 val) -{ - MatCommaInitializer_<_Tp> commaInitializer((Mat_<_Tp>*)&m); - return (commaInitializer, val); -} - - - -///////////////////////// Matrix Expressions //////////////////////// - -inline -Mat& Mat::operator = (const MatExpr& e) -{ - e.op->assign(e, *this); - return *this; -} - -template inline -Mat_<_Tp>::Mat_(const MatExpr& e) -{ - e.op->assign(e, *this, traits::Type<_Tp>::value); -} - -template inline -Mat_<_Tp>& Mat_<_Tp>::operator = (const MatExpr& e) -{ - e.op->assign(e, *this, traits::Type<_Tp>::value); - return *this; -} - -template inline -MatExpr Mat_<_Tp>::zeros(int rows, int cols) -{ - return Mat::zeros(rows, cols, traits::Type<_Tp>::value); -} - -template inline -MatExpr Mat_<_Tp>::zeros(Size sz) -{ - return Mat::zeros(sz, traits::Type<_Tp>::value); -} - -template inline -MatExpr Mat_<_Tp>::ones(int rows, int cols) -{ - return Mat::ones(rows, cols, traits::Type<_Tp>::value); -} - -template inline -MatExpr Mat_<_Tp>::ones(Size sz) -{ - return Mat::ones(sz, traits::Type<_Tp>::value); -} - -template inline -MatExpr Mat_<_Tp>::eye(int rows, int cols) -{ - return Mat::eye(rows, cols, traits::Type<_Tp>::value); -} - -template inline -MatExpr Mat_<_Tp>::eye(Size sz) -{ - return Mat::eye(sz, traits::Type<_Tp>::value); -} - -inline -MatExpr::MatExpr() - : op(0), flags(0), a(Mat()), b(Mat()), c(Mat()), alpha(0), beta(0), s() -{} - -inline -MatExpr::MatExpr(const MatOp* _op, int _flags, const Mat& _a, const Mat& _b, - const Mat& _c, double _alpha, double _beta, const Scalar& _s) - : op(_op), flags(_flags), a(_a), b(_b), c(_c), alpha(_alpha), beta(_beta), s(_s) -{} - -inline -MatExpr::operator Mat() const -{ - Mat m; - op->assign(*this, m); - return m; -} - -template inline -MatExpr::operator Mat_<_Tp>() const -{ - Mat_<_Tp> m; - op->assign(*this, m, traits::Type<_Tp>::value); - return m; -} - - -template static inline -MatExpr min(const Mat_<_Tp>& a, const Mat_<_Tp>& b) -{ - return cv::min((const Mat&)a, (const Mat&)b); -} - -template static inline -MatExpr min(const Mat_<_Tp>& a, double s) -{ - return cv::min((const Mat&)a, s); -} - -template static inline -MatExpr min(double s, const Mat_<_Tp>& a) -{ - return cv::min((const Mat&)a, s); -} - -template static inline -MatExpr max(const Mat_<_Tp>& a, const Mat_<_Tp>& b) -{ - return cv::max((const Mat&)a, (const Mat&)b); -} - -template static inline -MatExpr max(const Mat_<_Tp>& a, double s) -{ - return cv::max((const Mat&)a, s); -} - -template static inline -MatExpr max(double s, const Mat_<_Tp>& a) -{ - return cv::max((const Mat&)a, s); -} - -template static inline -MatExpr abs(const Mat_<_Tp>& m) -{ - return cv::abs((const Mat&)m); -} - - -static inline -Mat& operator += (Mat& a, const MatExpr& b) -{ - b.op->augAssignAdd(b, a); - return a; -} - -static inline -const Mat& operator += (const Mat& a, const MatExpr& b) -{ - b.op->augAssignAdd(b, (Mat&)a); - return a; -} - -template static inline -Mat_<_Tp>& operator += (Mat_<_Tp>& a, const MatExpr& b) -{ - b.op->augAssignAdd(b, a); - return a; -} - -template static inline -const Mat_<_Tp>& operator += (const Mat_<_Tp>& a, const MatExpr& b) -{ - b.op->augAssignAdd(b, (Mat&)a); - return a; -} - -static inline -Mat& operator -= (Mat& a, const MatExpr& b) -{ - b.op->augAssignSubtract(b, a); - return a; -} - -static inline -const Mat& operator -= (const Mat& a, const MatExpr& b) -{ - b.op->augAssignSubtract(b, (Mat&)a); - return a; -} - -template static inline -Mat_<_Tp>& operator -= (Mat_<_Tp>& a, const MatExpr& b) -{ - b.op->augAssignSubtract(b, a); - return a; -} - -template static inline -const Mat_<_Tp>& operator -= (const Mat_<_Tp>& a, const MatExpr& b) -{ - b.op->augAssignSubtract(b, (Mat&)a); - return a; -} - -static inline -Mat& operator *= (Mat& a, const MatExpr& b) -{ - b.op->augAssignMultiply(b, a); - return a; -} - -static inline -const Mat& operator *= (const Mat& a, const MatExpr& b) -{ - b.op->augAssignMultiply(b, (Mat&)a); - return a; -} - -template static inline -Mat_<_Tp>& operator *= (Mat_<_Tp>& a, const MatExpr& b) -{ - b.op->augAssignMultiply(b, a); - return a; -} - -template static inline -const Mat_<_Tp>& operator *= (const Mat_<_Tp>& a, const MatExpr& b) -{ - b.op->augAssignMultiply(b, (Mat&)a); - return a; -} - -static inline -Mat& operator /= (Mat& a, const MatExpr& b) -{ - b.op->augAssignDivide(b, a); - return a; -} - -static inline -const Mat& operator /= (const Mat& a, const MatExpr& b) -{ - b.op->augAssignDivide(b, (Mat&)a); - return a; -} - -template static inline -Mat_<_Tp>& operator /= (Mat_<_Tp>& a, const MatExpr& b) -{ - b.op->augAssignDivide(b, a); - return a; -} - -template static inline -const Mat_<_Tp>& operator /= (const Mat_<_Tp>& a, const MatExpr& b) -{ - b.op->augAssignDivide(b, (Mat&)a); - return a; -} - - -//////////////////////////////// UMat //////////////////////////////// - -template inline -UMat::UMat(const std::vector<_Tp>& vec, bool copyData) -: flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows((int)vec.size()), -cols(1), allocator(0), usageFlags(USAGE_DEFAULT), u(0), offset(0), size(&rows) -{ - if(vec.empty()) - return; - if( !copyData ) - { - // !!!TODO!!! - CV_Error(Error::StsNotImplemented, ""); - } - else - Mat((int)vec.size(), 1, traits::Type<_Tp>::value, (uchar*)&vec[0]).copyTo(*this); -} - -inline -UMat UMat::row(int y) const -{ - return UMat(*this, Range(y, y + 1), Range::all()); -} - -inline -UMat UMat::col(int x) const -{ - return UMat(*this, Range::all(), Range(x, x + 1)); -} - -inline -UMat UMat::rowRange(int startrow, int endrow) const -{ - return UMat(*this, Range(startrow, endrow), Range::all()); -} - -inline -UMat UMat::rowRange(const Range& r) const -{ - return UMat(*this, r, Range::all()); -} - -inline -UMat UMat::colRange(int startcol, int endcol) const -{ - return UMat(*this, Range::all(), Range(startcol, endcol)); -} - -inline -UMat UMat::colRange(const Range& r) const -{ - return UMat(*this, Range::all(), r); -} - -inline -UMat UMat::operator()( Range _rowRange, Range _colRange ) const -{ - return UMat(*this, _rowRange, _colRange); -} - -inline -UMat UMat::operator()( const Rect& roi ) const -{ - return UMat(*this, roi); -} - -inline -UMat UMat::operator()(const Range* ranges) const -{ - return UMat(*this, ranges); -} - -inline -UMat UMat::operator()(const std::vector& ranges) const -{ - return UMat(*this, ranges); -} - -inline -bool UMat::isContinuous() const -{ - return (flags & CONTINUOUS_FLAG) != 0; -} - -inline -bool UMat::isSubmatrix() const -{ - return (flags & SUBMATRIX_FLAG) != 0; -} - -inline -size_t UMat::elemSize() const -{ - size_t res = dims > 0 ? step.p[dims - 1] : 0; - CV_DbgAssert(res != 0); - return res; -} - -inline -size_t UMat::elemSize1() const -{ - return CV_ELEM_SIZE1(flags); -} - -inline -int UMat::type() const -{ - return CV_MAT_TYPE(flags); -} - -inline -int UMat::depth() const -{ - return CV_MAT_DEPTH(flags); -} - -inline -int UMat::channels() const -{ - return CV_MAT_CN(flags); -} - -inline -size_t UMat::step1(int i) const -{ - return step.p[i] / elemSize1(); -} - - -inline bool UMatData::hostCopyObsolete() const { return (flags & HOST_COPY_OBSOLETE) != 0; } -inline bool UMatData::deviceCopyObsolete() const { return (flags & DEVICE_COPY_OBSOLETE) != 0; } -inline bool UMatData::deviceMemMapped() const { return (flags & DEVICE_MEM_MAPPED) != 0; } -inline bool UMatData::copyOnMap() const { return (flags & COPY_ON_MAP) != 0; } -inline bool UMatData::tempUMat() const { return (flags & TEMP_UMAT) != 0; } -inline bool UMatData::tempCopiedUMat() const { return (flags & TEMP_COPIED_UMAT) == TEMP_COPIED_UMAT; } - -inline void UMatData::markDeviceMemMapped(bool flag) -{ - if(flag) - flags |= DEVICE_MEM_MAPPED; - else - flags &= ~DEVICE_MEM_MAPPED; -} - -inline void UMatData::markHostCopyObsolete(bool flag) -{ - if(flag) - flags |= HOST_COPY_OBSOLETE; - else - flags &= ~HOST_COPY_OBSOLETE; -} -inline void UMatData::markDeviceCopyObsolete(bool flag) -{ - if(flag) - flags |= DEVICE_COPY_OBSOLETE; - else - flags &= ~DEVICE_COPY_OBSOLETE; -} - -//! @endcond - -static inline -void swap(MatExpr& a, MatExpr& b) { a.swap(b); } - -} //cv - -#ifdef _MSC_VER -#pragma warning( pop ) -#endif - -#ifdef CV_DISABLE_CLANG_ENUM_WARNINGS -#undef CV_DISABLE_CLANG_ENUM_WARNINGS -#pragma clang diagnostic pop -#endif - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CORE_MATRIX_OPERATIONS_HPP +#define OPENCV_CORE_MATRIX_OPERATIONS_HPP + +#ifndef __cplusplus +# error mat.inl.hpp header must be compiled as C++ +#endif + +#ifdef _MSC_VER +#pragma warning( push ) +#pragma warning( disable: 4127 5054 ) +#endif + +#if defined(CV_SKIP_DISABLE_CLANG_ENUM_WARNINGS) + // nothing +#elif defined(CV_FORCE_DISABLE_CLANG_ENUM_WARNINGS) + #define CV_DISABLE_CLANG_ENUM_WARNINGS +#elif defined(__clang__) && defined(__has_warning) + #if __has_warning("-Wdeprecated-enum-enum-conversion") && __has_warning("-Wdeprecated-anon-enum-enum-conversion") + #define CV_DISABLE_CLANG_ENUM_WARNINGS + #endif +#endif +#ifdef CV_DISABLE_CLANG_ENUM_WARNINGS +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion" +#pragma clang diagnostic ignored "-Wdeprecated-anon-enum-enum-conversion" +#endif + +namespace cv +{ +CV__DEBUG_NS_BEGIN + + +//! @cond IGNORED + +////////////////////////// Custom (raw) type wrapper ////////////////////////// + +template static inline +int rawType() +{ + CV_StaticAssert(sizeof(_Tp) <= CV_CN_MAX, "sizeof(_Tp) is too large"); + const int elemSize = sizeof(_Tp); + return (int)CV_MAKETYPE(CV_8U, elemSize); +} + +//////////////////////// Input/Output Arrays //////////////////////// + +inline void _InputArray::init(int _flags, const void* _obj) +{ flags = _flags; obj = (void*)_obj; } + +inline void _InputArray::init(int _flags, const void* _obj, Size _sz) +{ flags = _flags; obj = (void*)_obj; sz = _sz; } + +inline void* _InputArray::getObj() const { return obj; } +inline int _InputArray::getFlags() const { return flags; } +inline Size _InputArray::getSz() const { return sz; } + +inline _InputArray::_InputArray() { init(0 + NONE, 0); } +inline _InputArray::_InputArray(int _flags, void* _obj) { init(_flags, _obj); } +inline _InputArray::_InputArray(const Mat& m) { init(+MAT+ACCESS_READ, &m); } +inline _InputArray::_InputArray(const std::vector& vec) { init(+STD_VECTOR_MAT+ACCESS_READ, &vec); } +inline _InputArray::_InputArray(const UMat& m) { init(+UMAT+ACCESS_READ, &m); } +inline _InputArray::_InputArray(const std::vector& vec) { init(+STD_VECTOR_UMAT+ACCESS_READ, &vec); } + +template inline +_InputArray::_InputArray(const std::vector<_Tp>& vec) +{ init(FIXED_TYPE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_READ, &vec); } + +template inline +_InputArray::_InputArray(const std::array<_Tp, _Nm>& arr) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_READ, arr.data(), Size(1, _Nm)); } + +template inline +_InputArray::_InputArray(const std::array& arr) +{ init(+STD_ARRAY_MAT + ACCESS_READ, arr.data(), Size(1, _Nm)); } + +inline +_InputArray::_InputArray(const std::vector& vec) +{ init(FIXED_TYPE + STD_BOOL_VECTOR + traits::Type::value + ACCESS_READ, &vec); } + +template inline +_InputArray::_InputArray(const std::vector >& vec) +{ init(FIXED_TYPE + STD_VECTOR_VECTOR + traits::Type<_Tp>::value + ACCESS_READ, &vec); } + +template inline +_InputArray::_InputArray(const std::vector >& vec) +{ init(FIXED_TYPE + STD_VECTOR_MAT + traits::Type<_Tp>::value + ACCESS_READ, &vec); } + +template inline +_InputArray::_InputArray(const Matx<_Tp, m, n>& mtx) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_READ, &mtx, Size(n, m)); } + +template inline +_InputArray::_InputArray(const _Tp* vec, int n) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_READ, vec, Size(n, 1)); } + +template inline +_InputArray::_InputArray(const Mat_<_Tp>& m) +{ init(FIXED_TYPE + MAT + traits::Type<_Tp>::value + ACCESS_READ, &m); } + +inline _InputArray::_InputArray(const double& val) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + CV_64F + ACCESS_READ, &val, Size(1,1)); } + +inline _InputArray::_InputArray(const cuda::GpuMat& d_mat) +{ init(+CUDA_GPU_MAT + ACCESS_READ, &d_mat); } + +inline _InputArray::_InputArray(const std::vector& d_mat) +{ init(+STD_VECTOR_CUDA_GPU_MAT + ACCESS_READ, &d_mat);} + +inline _InputArray::_InputArray(const ogl::Buffer& buf) +{ init(+OPENGL_BUFFER + ACCESS_READ, &buf); } + +inline _InputArray::_InputArray(const cuda::HostMem& cuda_mem) +{ init(+CUDA_HOST_MEM + ACCESS_READ, &cuda_mem); } + +template inline +_InputArray _InputArray::rawIn(const std::vector<_Tp>& vec) +{ + _InputArray v; + v.flags = _InputArray::FIXED_TYPE + _InputArray::STD_VECTOR + rawType<_Tp>() + ACCESS_READ; + v.obj = (void*)&vec; + return v; +} + +template inline +_InputArray _InputArray::rawIn(const std::array<_Tp, _Nm>& arr) +{ + _InputArray v; + v.flags = FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_READ; + v.obj = (void*)arr.data(); + v.sz = Size(1, _Nm); + return v; +} + +inline _InputArray::~_InputArray() {} + +inline Mat _InputArray::getMat(int i) const +{ + if( kind() == MAT && i < 0 ) + return *(const Mat*)obj; + return getMat_(i); +} + +inline bool _InputArray::isMat() const { return kind() == _InputArray::MAT; } +inline bool _InputArray::isUMat() const { return kind() == _InputArray::UMAT; } +inline bool _InputArray::isMatVector() const { return kind() == _InputArray::STD_VECTOR_MAT; } +inline bool _InputArray::isUMatVector() const { return kind() == _InputArray::STD_VECTOR_UMAT; } +inline bool _InputArray::isMatx() const { return kind() == _InputArray::MATX; } +inline bool _InputArray::isVector() const { return kind() == _InputArray::STD_VECTOR || + kind() == _InputArray::STD_BOOL_VECTOR || + (kind() == _InputArray::MATX && (sz.width <= 1 || sz.height <= 1)); } +inline bool _InputArray::isGpuMat() const { return kind() == _InputArray::CUDA_GPU_MAT; } +inline bool _InputArray::isGpuMatVector() const { return kind() == _InputArray::STD_VECTOR_CUDA_GPU_MAT; } + +//////////////////////////////////////////////////////////////////////////////////////// + +inline _OutputArray::_OutputArray() { init(+NONE + ACCESS_WRITE, 0); } +inline _OutputArray::_OutputArray(int _flags, void* _obj) { init(_flags + ACCESS_WRITE, _obj); } +inline _OutputArray::_OutputArray(Mat& m) { init(+MAT+ACCESS_WRITE, &m); } +inline _OutputArray::_OutputArray(std::vector& vec) { init(+STD_VECTOR_MAT + ACCESS_WRITE, &vec); } +inline _OutputArray::_OutputArray(UMat& m) { init(+UMAT + ACCESS_WRITE, &m); } +inline _OutputArray::_OutputArray(std::vector& vec) { init(+STD_VECTOR_UMAT + ACCESS_WRITE, &vec); } + +template inline +_OutputArray::_OutputArray(std::vector<_Tp>& vec) +{ init(FIXED_TYPE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); } + +template inline +_OutputArray::_OutputArray(std::array<_Tp, _Nm>& arr) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE, arr.data(), Size(1, _Nm)); } + +template inline +_OutputArray::_OutputArray(std::array& arr) +{ init(+STD_ARRAY_MAT + ACCESS_WRITE, arr.data(), Size(1, _Nm)); } + +template inline +_OutputArray::_OutputArray(std::vector >& vec) +{ init(FIXED_TYPE + STD_VECTOR_VECTOR + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); } + +template inline +_OutputArray::_OutputArray(std::vector >& vec) +{ init(FIXED_TYPE + STD_VECTOR_MAT + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); } + +template inline +_OutputArray::_OutputArray(Mat_<_Tp>& m) +{ init(FIXED_TYPE + MAT + traits::Type<_Tp>::value + ACCESS_WRITE, &m); } + +template inline +_OutputArray::_OutputArray(Matx<_Tp, m, n>& mtx) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE, &mtx, Size(n, m)); } + +template inline +_OutputArray::_OutputArray(_Tp* vec, int n) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE, vec, Size(n, 1)); } + +template inline +_OutputArray::_OutputArray(const std::vector<_Tp>& vec) +{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); } + +template inline +_OutputArray::_OutputArray(const std::array<_Tp, _Nm>& arr) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE, arr.data(), Size(1, _Nm)); } + +template inline +_OutputArray::_OutputArray(const std::array& arr) +{ init(FIXED_SIZE + STD_ARRAY_MAT + ACCESS_WRITE, arr.data(), Size(1, _Nm)); } + +template inline +_OutputArray::_OutputArray(const std::vector >& vec) +{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_VECTOR + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); } + +template inline +_OutputArray::_OutputArray(const std::vector >& vec) +{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_MAT + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); } + +template inline +_OutputArray::_OutputArray(const Mat_<_Tp>& m) +{ init(FIXED_TYPE + FIXED_SIZE + MAT + traits::Type<_Tp>::value + ACCESS_WRITE, &m); } + +template inline +_OutputArray::_OutputArray(const Matx<_Tp, m, n>& mtx) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE, &mtx, Size(n, m)); } + +template inline +_OutputArray::_OutputArray(const _Tp* vec, int n) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE, vec, Size(n, 1)); } + +inline _OutputArray::_OutputArray(cuda::GpuMat& d_mat) +{ init(+CUDA_GPU_MAT + ACCESS_WRITE, &d_mat); } + +inline _OutputArray::_OutputArray(std::vector& d_mat) +{ init(+STD_VECTOR_CUDA_GPU_MAT + ACCESS_WRITE, &d_mat);} + +inline _OutputArray::_OutputArray(ogl::Buffer& buf) +{ init(+OPENGL_BUFFER + ACCESS_WRITE, &buf); } + +inline _OutputArray::_OutputArray(cuda::HostMem& cuda_mem) +{ init(+CUDA_HOST_MEM + ACCESS_WRITE, &cuda_mem); } + +inline _OutputArray::_OutputArray(const Mat& m) +{ init(FIXED_TYPE + FIXED_SIZE + MAT + ACCESS_WRITE, &m); } + +inline _OutputArray::_OutputArray(const std::vector& vec) +{ init(FIXED_SIZE + STD_VECTOR_MAT + ACCESS_WRITE, &vec); } + +inline _OutputArray::_OutputArray(const UMat& m) +{ init(FIXED_TYPE + FIXED_SIZE + UMAT + ACCESS_WRITE, &m); } + +inline _OutputArray::_OutputArray(const std::vector& vec) +{ init(FIXED_SIZE + STD_VECTOR_UMAT + ACCESS_WRITE, &vec); } + +inline _OutputArray::_OutputArray(const cuda::GpuMat& d_mat) +{ init(FIXED_TYPE + FIXED_SIZE + CUDA_GPU_MAT + ACCESS_WRITE, &d_mat); } + + +inline _OutputArray::_OutputArray(const ogl::Buffer& buf) +{ init(FIXED_TYPE + FIXED_SIZE + OPENGL_BUFFER + ACCESS_WRITE, &buf); } + +inline _OutputArray::_OutputArray(const cuda::HostMem& cuda_mem) +{ init(FIXED_TYPE + FIXED_SIZE + CUDA_HOST_MEM + ACCESS_WRITE, &cuda_mem); } + +template inline +_OutputArray _OutputArray::rawOut(std::vector<_Tp>& vec) +{ + _OutputArray v; + v.flags = _InputArray::FIXED_TYPE + _InputArray::STD_VECTOR + rawType<_Tp>() + ACCESS_WRITE; + v.obj = (void*)&vec; + return v; +} + +template inline +_OutputArray _OutputArray::rawOut(std::array<_Tp, _Nm>& arr) +{ + _OutputArray v; + v.flags = FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE; + v.obj = (void*)arr.data(); + v.sz = Size(1, _Nm); + return v; +} + +/////////////////////////////////////////////////////////////////////////////////////////// + +inline _InputOutputArray::_InputOutputArray() { init(0+ACCESS_RW, 0); } +inline _InputOutputArray::_InputOutputArray(int _flags, void* _obj) { init(_flags+ACCESS_RW, _obj); } +inline _InputOutputArray::_InputOutputArray(Mat& m) { init(+MAT+ACCESS_RW, &m); } +inline _InputOutputArray::_InputOutputArray(std::vector& vec) { init(+STD_VECTOR_MAT+ACCESS_RW, &vec); } +inline _InputOutputArray::_InputOutputArray(UMat& m) { init(+UMAT+ACCESS_RW, &m); } +inline _InputOutputArray::_InputOutputArray(std::vector& vec) { init(+STD_VECTOR_UMAT+ACCESS_RW, &vec); } + +template inline +_InputOutputArray::_InputOutputArray(std::vector<_Tp>& vec) +{ init(FIXED_TYPE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_RW, &vec); } + +template inline +_InputOutputArray::_InputOutputArray(std::array<_Tp, _Nm>& arr) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW, arr.data(), Size(1, _Nm)); } + +template inline +_InputOutputArray::_InputOutputArray(std::array& arr) +{ init(+STD_ARRAY_MAT + ACCESS_RW, arr.data(), Size(1, _Nm)); } + +template inline +_InputOutputArray::_InputOutputArray(std::vector >& vec) +{ init(FIXED_TYPE + STD_VECTOR_VECTOR + traits::Type<_Tp>::value + ACCESS_RW, &vec); } + +template inline +_InputOutputArray::_InputOutputArray(std::vector >& vec) +{ init(FIXED_TYPE + STD_VECTOR_MAT + traits::Type<_Tp>::value + ACCESS_RW, &vec); } + +template inline +_InputOutputArray::_InputOutputArray(Mat_<_Tp>& m) +{ init(FIXED_TYPE + MAT + traits::Type<_Tp>::value + ACCESS_RW, &m); } + +template inline +_InputOutputArray::_InputOutputArray(Matx<_Tp, m, n>& mtx) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW, &mtx, Size(n, m)); } + +template inline +_InputOutputArray::_InputOutputArray(_Tp* vec, int n) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW, vec, Size(n, 1)); } + +template inline +_InputOutputArray::_InputOutputArray(const std::vector<_Tp>& vec) +{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_RW, &vec); } + +template inline +_InputOutputArray::_InputOutputArray(const std::array<_Tp, _Nm>& arr) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW, arr.data(), Size(1, _Nm)); } + +template inline +_InputOutputArray::_InputOutputArray(const std::array& arr) +{ init(FIXED_SIZE + STD_ARRAY_MAT + ACCESS_RW, arr.data(), Size(1, _Nm)); } + +template inline +_InputOutputArray::_InputOutputArray(const std::vector >& vec) +{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_VECTOR + traits::Type<_Tp>::value + ACCESS_RW, &vec); } + +template inline +_InputOutputArray::_InputOutputArray(const std::vector >& vec) +{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_MAT + traits::Type<_Tp>::value + ACCESS_RW, &vec); } + +template inline +_InputOutputArray::_InputOutputArray(const Mat_<_Tp>& m) +{ init(FIXED_TYPE + FIXED_SIZE + MAT + traits::Type<_Tp>::value + ACCESS_RW, &m); } + +template inline +_InputOutputArray::_InputOutputArray(const Matx<_Tp, m, n>& mtx) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW, &mtx, Size(n, m)); } + +template inline +_InputOutputArray::_InputOutputArray(const _Tp* vec, int n) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW, vec, Size(n, 1)); } + +inline _InputOutputArray::_InputOutputArray(cuda::GpuMat& d_mat) +{ init(+CUDA_GPU_MAT + ACCESS_RW, &d_mat); } + +inline _InputOutputArray::_InputOutputArray(ogl::Buffer& buf) +{ init(+OPENGL_BUFFER + ACCESS_RW, &buf); } + +inline _InputOutputArray::_InputOutputArray(cuda::HostMem& cuda_mem) +{ init(+CUDA_HOST_MEM + ACCESS_RW, &cuda_mem); } + +inline _InputOutputArray::_InputOutputArray(const Mat& m) +{ init(FIXED_TYPE + FIXED_SIZE + MAT + ACCESS_RW, &m); } + +inline _InputOutputArray::_InputOutputArray(const std::vector& vec) +{ init(FIXED_SIZE + STD_VECTOR_MAT + ACCESS_RW, &vec); } + +inline _InputOutputArray::_InputOutputArray(const UMat& m) +{ init(FIXED_TYPE + FIXED_SIZE + UMAT + ACCESS_RW, &m); } + +inline _InputOutputArray::_InputOutputArray(const std::vector& vec) +{ init(FIXED_SIZE + STD_VECTOR_UMAT + ACCESS_RW, &vec); } + +inline _InputOutputArray::_InputOutputArray(const cuda::GpuMat& d_mat) +{ init(FIXED_TYPE + FIXED_SIZE + CUDA_GPU_MAT + ACCESS_RW, &d_mat); } + +inline _InputOutputArray::_InputOutputArray(const std::vector& d_mat) +{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_CUDA_GPU_MAT + ACCESS_RW, &d_mat);} + +template<> inline _InputOutputArray::_InputOutputArray(std::vector& d_mat) +{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_CUDA_GPU_MAT + ACCESS_RW, &d_mat);} + +inline _InputOutputArray::_InputOutputArray(const ogl::Buffer& buf) +{ init(FIXED_TYPE + FIXED_SIZE + OPENGL_BUFFER + ACCESS_RW, &buf); } + +inline _InputOutputArray::_InputOutputArray(const cuda::HostMem& cuda_mem) +{ init(FIXED_TYPE + FIXED_SIZE + CUDA_HOST_MEM + ACCESS_RW, &cuda_mem); } + +template inline +_InputOutputArray _InputOutputArray::rawInOut(std::vector<_Tp>& vec) +{ + _InputOutputArray v; + v.flags = _InputArray::FIXED_TYPE + _InputArray::STD_VECTOR + rawType<_Tp>() + ACCESS_RW; + v.obj = (void*)&vec; + return v; +} + +template inline +_InputOutputArray _InputOutputArray::rawInOut(std::array<_Tp, _Nm>& arr) +{ + _InputOutputArray v; + v.flags = FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW; + v.obj = (void*)arr.data(); + v.sz = Size(1, _Nm); + return v; +} + + +template static inline _InputArray rawIn(_Tp& v) { return _InputArray::rawIn(v); } +template static inline _OutputArray rawOut(_Tp& v) { return _OutputArray::rawOut(v); } +template static inline _InputOutputArray rawInOut(_Tp& v) { return _InputOutputArray::rawInOut(v); } + +CV__DEBUG_NS_END + +//////////////////////////////////////////// Mat ////////////////////////////////////////// + +template inline +Mat::Mat(const std::vector<_Tp>& vec, bool copyData) + : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows((int)vec.size()), + cols(1), data(0), datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0) +{ + if(vec.empty()) + return; + if( !copyData ) + { + step[0] = step[1] = sizeof(_Tp); + datastart = data = (uchar*)&vec[0]; + datalimit = dataend = datastart + rows * step[0]; + } + else + Mat((int)vec.size(), 1, traits::Type<_Tp>::value, (uchar*)&vec[0]).copyTo(*this); +} + +template inline +Mat::Mat(const std::initializer_list<_Tp> list) + : Mat() +{ + CV_Assert(list.size() != 0); + Mat((int)list.size(), 1, traits::Type<_Tp>::value, (uchar*)list.begin()).copyTo(*this); +} + +template inline +Mat::Mat(const std::initializer_list sizes, const std::initializer_list<_Tp> list) + : Mat() +{ + size_t size_total = 1; + for(auto s : sizes) + size_total *= s; + CV_Assert(list.size() != 0); + CV_Assert(size_total == list.size()); + Mat((int)sizes.size(), (int*)sizes.begin(), traits::Type<_Tp>::value, (uchar*)list.begin()).copyTo(*this); +} + +template inline +Mat::Mat(const std::array<_Tp, _Nm>& arr, bool copyData) + : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows((int)arr.size()), + cols(1), data(0), datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0) +{ + if(arr.empty()) + return; + if( !copyData ) + { + step[0] = step[1] = sizeof(_Tp); + datastart = data = (uchar*)arr.data(); + datalimit = dataend = datastart + rows * step[0]; + } + else + Mat((int)arr.size(), 1, traits::Type<_Tp>::value, (uchar*)arr.data()).copyTo(*this); +} + +template inline +Mat::Mat(const Vec<_Tp, n>& vec, bool copyData) + : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows(n), cols(1), data(0), + datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0) +{ + if( !copyData ) + { + step[0] = step[1] = sizeof(_Tp); + datastart = data = (uchar*)vec.val; + datalimit = dataend = datastart + rows * step[0]; + } + else + Mat(n, 1, traits::Type<_Tp>::value, (void*)vec.val).copyTo(*this); +} + + +template inline +Mat::Mat(const Matx<_Tp,m,n>& M, bool copyData) + : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows(m), cols(n), data(0), + datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0) +{ + if( !copyData ) + { + step[0] = cols * sizeof(_Tp); + step[1] = sizeof(_Tp); + datastart = data = (uchar*)M.val; + datalimit = dataend = datastart + rows * step[0]; + } + else + Mat(m, n, traits::Type<_Tp>::value, (uchar*)M.val).copyTo(*this); +} + +template inline +Mat::Mat(const Point_<_Tp>& pt, bool copyData) + : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows(2), cols(1), data(0), + datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0) +{ + if( !copyData ) + { + step[0] = step[1] = sizeof(_Tp); + datastart = data = (uchar*)&pt.x; + datalimit = dataend = datastart + rows * step[0]; + } + else + { + create(2, 1, traits::Type<_Tp>::value); + ((_Tp*)data)[0] = pt.x; + ((_Tp*)data)[1] = pt.y; + } +} + +template inline +Mat::Mat(const Point3_<_Tp>& pt, bool copyData) + : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows(3), cols(1), data(0), + datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0) +{ + if( !copyData ) + { + step[0] = step[1] = sizeof(_Tp); + datastart = data = (uchar*)&pt.x; + datalimit = dataend = datastart + rows * step[0]; + } + else + { + create(3, 1, traits::Type<_Tp>::value); + ((_Tp*)data)[0] = pt.x; + ((_Tp*)data)[1] = pt.y; + ((_Tp*)data)[2] = pt.z; + } +} + +template inline +Mat::Mat(const MatCommaInitializer_<_Tp>& commaInitializer) + : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(0), rows(0), cols(0), data(0), + datastart(0), dataend(0), allocator(0), u(0), size(&rows) +{ + *this = commaInitializer.operator Mat_<_Tp>(); +} + +inline +Mat Mat::row(int y) const +{ + return Mat(*this, Range(y, y + 1), Range::all()); +} + +inline +Mat Mat::col(int x) const +{ + return Mat(*this, Range::all(), Range(x, x + 1)); +} + +inline +Mat Mat::rowRange(int startrow, int endrow) const +{ + return Mat(*this, Range(startrow, endrow), Range::all()); +} + +inline +Mat Mat::rowRange(const Range& r) const +{ + return Mat(*this, r, Range::all()); +} + +inline +Mat Mat::colRange(int startcol, int endcol) const +{ + return Mat(*this, Range::all(), Range(startcol, endcol)); +} + +inline +Mat Mat::colRange(const Range& r) const +{ + return Mat(*this, Range::all(), r); +} + +inline +Mat Mat::operator()( Range _rowRange, Range _colRange ) const +{ + return Mat(*this, _rowRange, _colRange); +} + +inline +Mat Mat::operator()( const Rect& roi ) const +{ + return Mat(*this, roi); +} + +inline +Mat Mat::operator()(const Range* ranges) const +{ + return Mat(*this, ranges); +} + +inline +Mat Mat::operator()(const std::vector& ranges) const +{ + return Mat(*this, ranges); +} + +inline +bool Mat::isContinuous() const +{ + return (flags & CONTINUOUS_FLAG) != 0; +} + +inline +bool Mat::isSubmatrix() const +{ + return (flags & SUBMATRIX_FLAG) != 0; +} + +inline +size_t Mat::elemSize() const +{ + size_t res = dims > 0 ? step.p[dims - 1] : 0; + CV_DbgAssert(res != 0); + return res; +} + +inline +size_t Mat::elemSize1() const +{ + return CV_ELEM_SIZE1(flags); +} + +inline +int Mat::type() const +{ + return CV_MAT_TYPE(flags); +} + +inline +int Mat::depth() const +{ + return CV_MAT_DEPTH(flags); +} + +inline +int Mat::channels() const +{ + return CV_MAT_CN(flags); +} + +inline +uchar* Mat::ptr(int y) +{ + CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) ); + return data + step.p[0] * y; +} + +inline +const uchar* Mat::ptr(int y) const +{ + CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) ); + return data + step.p[0] * y; +} + +template inline +_Tp* Mat::ptr(int y) +{ + CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) ); + return (_Tp*)(data + step.p[0] * y); +} + +template inline +const _Tp* Mat::ptr(int y) const +{ + CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) ); + return (const _Tp*)(data + step.p[0] * y); +} + +inline +uchar* Mat::ptr(int i0, int i1) +{ + CV_DbgAssert(dims >= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); + return data + i0 * step.p[0] + i1 * step.p[1]; +} + +inline +const uchar* Mat::ptr(int i0, int i1) const +{ + CV_DbgAssert(dims >= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); + return data + i0 * step.p[0] + i1 * step.p[1]; +} + +template inline +_Tp* Mat::ptr(int i0, int i1) +{ + CV_DbgAssert(dims >= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); + return (_Tp*)(data + i0 * step.p[0] + i1 * step.p[1]); +} + +template inline +const _Tp* Mat::ptr(int i0, int i1) const +{ + CV_DbgAssert(dims >= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); + return (const _Tp*)(data + i0 * step.p[0] + i1 * step.p[1]); +} + +inline +uchar* Mat::ptr(int i0, int i1, int i2) +{ + CV_DbgAssert(dims >= 3); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); + CV_DbgAssert((unsigned)i2 < (unsigned)size.p[2]); + return data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2]; +} + +inline +const uchar* Mat::ptr(int i0, int i1, int i2) const +{ + CV_DbgAssert(dims >= 3); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); + CV_DbgAssert((unsigned)i2 < (unsigned)size.p[2]); + return data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2]; +} + +template inline +_Tp* Mat::ptr(int i0, int i1, int i2) +{ + CV_DbgAssert(dims >= 3); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); + CV_DbgAssert((unsigned)i2 < (unsigned)size.p[2]); + return (_Tp*)(data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2]); +} + +template inline +const _Tp* Mat::ptr(int i0, int i1, int i2) const +{ + CV_DbgAssert(dims >= 3); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); + CV_DbgAssert((unsigned)i2 < (unsigned)size.p[2]); + return (const _Tp*)(data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2]); +} + +inline +uchar* Mat::ptr(const int* idx) +{ + int i, d = dims; + uchar* p = data; + CV_DbgAssert( d >= 1 && p ); + for( i = 0; i < d; i++ ) + { + CV_DbgAssert( (unsigned)idx[i] < (unsigned)size.p[i] ); + p += idx[i] * step.p[i]; + } + return p; +} + +inline +const uchar* Mat::ptr(const int* idx) const +{ + int i, d = dims; + uchar* p = data; + CV_DbgAssert( d >= 1 && p ); + for( i = 0; i < d; i++ ) + { + CV_DbgAssert( (unsigned)idx[i] < (unsigned)size.p[i] ); + p += idx[i] * step.p[i]; + } + return p; +} + +template inline +_Tp* Mat::ptr(const int* idx) +{ + int i, d = dims; + uchar* p = data; + CV_DbgAssert( d >= 1 && p ); + for( i = 0; i < d; i++ ) + { + CV_DbgAssert( (unsigned)idx[i] < (unsigned)size.p[i] ); + p += idx[i] * step.p[i]; + } + return (_Tp*)p; +} + +template inline +const _Tp* Mat::ptr(const int* idx) const +{ + int i, d = dims; + uchar* p = data; + CV_DbgAssert( d >= 1 && p ); + for( i = 0; i < d; i++ ) + { + CV_DbgAssert( (unsigned)idx[i] < (unsigned)size.p[i] ); + p += idx[i] * step.p[i]; + } + return (const _Tp*)p; +} + +template inline +uchar* Mat::ptr(const Vec& idx) +{ + return Mat::ptr(idx.val); +} + +template inline +const uchar* Mat::ptr(const Vec& idx) const +{ + return Mat::ptr(idx.val); +} + +template inline +_Tp* Mat::ptr(const Vec& idx) +{ + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + return Mat::ptr<_Tp>(idx.val); +} + +template inline +const _Tp* Mat::ptr(const Vec& idx) const +{ + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + return Mat::ptr<_Tp>(idx.val); +} + + +template inline +_Tp& Mat::at(int i0, int i1) +{ + CV_DbgAssert(dims <= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)(i1 * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels())); + CV_DbgAssert(CV_ELEM_SIZE1(traits::Depth<_Tp>::value) == elemSize1()); + return ((_Tp*)(data + step.p[0] * i0))[i1]; +} + +template inline +const _Tp& Mat::at(int i0, int i1) const +{ + CV_DbgAssert(dims <= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)(i1 * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels())); + CV_DbgAssert(CV_ELEM_SIZE1(traits::Depth<_Tp>::value) == elemSize1()); + return ((const _Tp*)(data + step.p[0] * i0))[i1]; +} + +template inline +_Tp& Mat::at(Point pt) +{ + CV_DbgAssert(dims <= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)pt.y < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)(pt.x * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels())); + CV_DbgAssert(CV_ELEM_SIZE1(traits::Depth<_Tp>::value) == elemSize1()); + return ((_Tp*)(data + step.p[0] * pt.y))[pt.x]; +} + +template inline +const _Tp& Mat::at(Point pt) const +{ + CV_DbgAssert(dims <= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)pt.y < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)(pt.x * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels())); + CV_DbgAssert(CV_ELEM_SIZE1(traits::Depth<_Tp>::value) == elemSize1()); + return ((const _Tp*)(data + step.p[0] * pt.y))[pt.x]; +} + +template inline +_Tp& Mat::at(int i0) +{ + CV_DbgAssert(dims <= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)(size.p[0] * size.p[1])); + CV_DbgAssert(elemSize() == sizeof(_Tp)); + if( isContinuous() || size.p[0] == 1 ) + return ((_Tp*)data)[i0]; + if( size.p[1] == 1 ) + return *(_Tp*)(data + step.p[0] * i0); + int i = i0 / cols, j = i0 - i * cols; + return ((_Tp*)(data + step.p[0] * i))[j]; +} + +template inline +const _Tp& Mat::at(int i0) const +{ + CV_DbgAssert(dims <= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)(size.p[0] * size.p[1])); + CV_DbgAssert(elemSize() == sizeof(_Tp)); + if( isContinuous() || size.p[0] == 1 ) + return ((const _Tp*)data)[i0]; + if( size.p[1] == 1 ) + return *(const _Tp*)(data + step.p[0] * i0); + int i = i0 / cols, j = i0 - i * cols; + return ((const _Tp*)(data + step.p[0] * i))[j]; +} + +template inline +_Tp& Mat::at(int i0, int i1, int i2) +{ + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + return *(_Tp*)ptr(i0, i1, i2); +} + +template inline +const _Tp& Mat::at(int i0, int i1, int i2) const +{ + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + return *(const _Tp*)ptr(i0, i1, i2); +} + +template inline +_Tp& Mat::at(const int* idx) +{ + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + return *(_Tp*)ptr(idx); +} + +template inline +const _Tp& Mat::at(const int* idx) const +{ + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + return *(const _Tp*)ptr(idx); +} + +template inline +_Tp& Mat::at(const Vec& idx) +{ + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + return *(_Tp*)ptr(idx.val); +} + +template inline +const _Tp& Mat::at(const Vec& idx) const +{ + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + return *(const _Tp*)ptr(idx.val); +} + +template inline +MatConstIterator_<_Tp> Mat::begin() const +{ + if (empty()) + return MatConstIterator_<_Tp>(); + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + return MatConstIterator_<_Tp>((const Mat_<_Tp>*)this); +} + +template inline +std::reverse_iterator> Mat::rbegin() const +{ + if (empty()) + return std::reverse_iterator>(); + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + MatConstIterator_<_Tp> it((const Mat_<_Tp>*)this); + it += total(); + return std::reverse_iterator> (it); +} + +template inline +MatConstIterator_<_Tp> Mat::end() const +{ + if (empty()) + return MatConstIterator_<_Tp>(); + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + MatConstIterator_<_Tp> it((const Mat_<_Tp>*)this); + it += total(); + return it; +} + +template inline +std::reverse_iterator> Mat::rend() const +{ + if (empty()) + return std::reverse_iterator>(); + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + return std::reverse_iterator>((const Mat_<_Tp>*)this); +} + +template inline +MatIterator_<_Tp> Mat::begin() +{ + if (empty()) + return MatIterator_<_Tp>(); + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + return MatIterator_<_Tp>((Mat_<_Tp>*)this); +} + +template inline +std::reverse_iterator> Mat::rbegin() +{ + if (empty()) + return std::reverse_iterator>(); + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + MatIterator_<_Tp> it((Mat_<_Tp>*)this); + it += total(); + return std::reverse_iterator>(it); +} + +template inline +MatIterator_<_Tp> Mat::end() +{ + if (empty()) + return MatIterator_<_Tp>(); + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + MatIterator_<_Tp> it((Mat_<_Tp>*)this); + it += total(); + return it; +} + +template inline +std::reverse_iterator> Mat::rend() +{ + if (empty()) + return std::reverse_iterator>(); + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + return std::reverse_iterator>(MatIterator_<_Tp>((Mat_<_Tp>*)this)); +} + +template inline +void Mat::forEach(const Functor& operation) { + this->forEach_impl<_Tp>(operation); +} + +template inline +void Mat::forEach(const Functor& operation) const { + // call as not const + (const_cast(this))->forEach<_Tp>(operation); +} + +template inline +Mat::operator std::vector<_Tp>() const +{ + std::vector<_Tp> v; + copyTo(v); + return v; +} + +template inline +Mat::operator std::array<_Tp, _Nm>() const +{ + std::array<_Tp, _Nm> v; + copyTo(v); + return v; +} + +template inline +Mat::operator Vec<_Tp, n>() const +{ + CV_Assert( data && dims <= 2 && (rows == 1 || cols == 1) && + rows + cols - 1 == n && channels() == 1 ); + + if( isContinuous() && type() == traits::Type<_Tp>::value ) + return Vec<_Tp, n>((_Tp*)data); + Vec<_Tp, n> v; + Mat tmp(rows, cols, traits::Type<_Tp>::value, v.val); + convertTo(tmp, tmp.type()); + return v; +} + +template inline +Mat::operator Matx<_Tp, m, n>() const +{ + CV_Assert( data && dims <= 2 && rows == m && cols == n && channels() == 1 ); + + if( isContinuous() && type() == traits::Type<_Tp>::value ) + return Matx<_Tp, m, n>((_Tp*)data); + Matx<_Tp, m, n> mtx; + Mat tmp(rows, cols, traits::Type<_Tp>::value, mtx.val); + convertTo(tmp, tmp.type()); + return mtx; +} + +template inline +void Mat::push_back(const _Tp& elem) +{ + if( !data ) + { + *this = Mat(1, 1, traits::Type<_Tp>::value, (void*)&elem).clone(); + return; + } + CV_Assert(traits::Type<_Tp>::value == type() && cols == 1 + /* && dims == 2 (cols == 1 implies dims == 2) */); + const uchar* tmp = dataend + step[0]; + if( !isSubmatrix() && isContinuous() && tmp <= datalimit ) + { + *(_Tp*)(data + (size.p[0]++) * step.p[0]) = elem; + dataend = tmp; + } + else + push_back_(&elem); +} + +template inline +void Mat::push_back(const Mat_<_Tp>& m) +{ + push_back((const Mat&)m); +} + +template<> inline +void Mat::push_back(const MatExpr& expr) +{ + push_back(static_cast(expr)); +} + + +template inline +void Mat::push_back(const std::vector<_Tp>& v) +{ + push_back(Mat(v)); +} + + +///////////////////////////// MatSize //////////////////////////// + +inline +MatSize::MatSize(int* _p) CV_NOEXCEPT + : p(_p) {} + +inline +int MatSize::dims() const CV_NOEXCEPT +{ + return (p - 1)[0]; +} + +inline +Size MatSize::operator()() const +{ + CV_DbgAssert(dims() <= 2); + return Size(p[1], p[0]); +} + +inline +const int& MatSize::operator[](int i) const +{ + CV_DbgAssert(i < dims()); +#ifdef __OPENCV_BUILD + CV_DbgAssert(i >= 0); +#endif + return p[i]; +} + +inline +int& MatSize::operator[](int i) +{ + CV_DbgAssert(i < dims()); +#ifdef __OPENCV_BUILD + CV_DbgAssert(i >= 0); +#endif + return p[i]; +} + +inline +MatSize::operator const int*() const CV_NOEXCEPT +{ + return p; +} + +inline +bool MatSize::operator != (const MatSize& sz) const CV_NOEXCEPT +{ + return !(*this == sz); +} + + + +///////////////////////////// MatStep //////////////////////////// + +inline +MatStep::MatStep() CV_NOEXCEPT +{ + p = buf; p[0] = p[1] = 0; +} + +inline +MatStep::MatStep(size_t s) CV_NOEXCEPT +{ + p = buf; p[0] = s; p[1] = 0; +} + +inline +const size_t& MatStep::operator[](int i) const CV_NOEXCEPT +{ + return p[i]; +} + +inline +size_t& MatStep::operator[](int i) CV_NOEXCEPT +{ + return p[i]; +} + +inline MatStep::operator size_t() const +{ + CV_DbgAssert( p == buf ); + return buf[0]; +} + +inline MatStep& MatStep::operator = (size_t s) +{ + CV_DbgAssert( p == buf ); + buf[0] = s; + return *this; +} + + + +////////////////////////////// Mat_<_Tp> //////////////////////////// + +template inline +Mat_<_Tp>::Mat_() CV_NOEXCEPT + : Mat() +{ + flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value; +} + +template inline +Mat_<_Tp>::Mat_(int _rows, int _cols) + : Mat(_rows, _cols, traits::Type<_Tp>::value) +{ +} + +template inline +Mat_<_Tp>::Mat_(int _rows, int _cols, const _Tp& value) + : Mat(_rows, _cols, traits::Type<_Tp>::value) +{ + *this = value; +} + +template inline +Mat_<_Tp>::Mat_(Size _sz) + : Mat(_sz.height, _sz.width, traits::Type<_Tp>::value) +{} + +template inline +Mat_<_Tp>::Mat_(Size _sz, const _Tp& value) + : Mat(_sz.height, _sz.width, traits::Type<_Tp>::value) +{ + *this = value; +} + +template inline +Mat_<_Tp>::Mat_(int _dims, const int* _sz) + : Mat(_dims, _sz, traits::Type<_Tp>::value) +{} + +template inline +Mat_<_Tp>::Mat_(int _dims, const int* _sz, const _Tp& _s) + : Mat(_dims, _sz, traits::Type<_Tp>::value, Scalar(_s)) +{} + +template inline +Mat_<_Tp>::Mat_(int _dims, const int* _sz, _Tp* _data, const size_t* _steps) + : Mat(_dims, _sz, traits::Type<_Tp>::value, _data, _steps) +{} + +template inline +Mat_<_Tp>::Mat_(const Mat_<_Tp>& m, const Range* ranges) + : Mat(m, ranges) +{} + +template inline +Mat_<_Tp>::Mat_(const Mat_<_Tp>& m, const std::vector& ranges) + : Mat(m, ranges) +{} + +template inline +Mat_<_Tp>::Mat_(const Mat& m) + : Mat() +{ + flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value; + *this = m; +} + +template inline +Mat_<_Tp>::Mat_(const Mat_& m) + : Mat(m) +{} + +template inline +Mat_<_Tp>::Mat_(int _rows, int _cols, _Tp* _data, size_t steps) + : Mat(_rows, _cols, traits::Type<_Tp>::value, _data, steps) +{} + +template inline +Mat_<_Tp>::Mat_(const Mat_& m, const Range& _rowRange, const Range& _colRange) + : Mat(m, _rowRange, _colRange) +{} + +template inline +Mat_<_Tp>::Mat_(const Mat_& m, const Rect& roi) + : Mat(m, roi) +{} + +template template inline +Mat_<_Tp>::Mat_(const Vec::channel_type, n>& vec, bool copyData) + : Mat(n / DataType<_Tp>::channels, 1, traits::Type<_Tp>::value, (void*)&vec) +{ + CV_Assert(n%DataType<_Tp>::channels == 0); + if( copyData ) + *this = clone(); +} + +template template inline +Mat_<_Tp>::Mat_(const Matx::channel_type, m, n>& M, bool copyData) + : Mat(m, n / DataType<_Tp>::channels, traits::Type<_Tp>::value, (void*)&M) +{ + CV_Assert(n % DataType<_Tp>::channels == 0); + if( copyData ) + *this = clone(); +} + +template inline +Mat_<_Tp>::Mat_(const Point_::channel_type>& pt, bool copyData) + : Mat(2 / DataType<_Tp>::channels, 1, traits::Type<_Tp>::value, (void*)&pt) +{ + CV_Assert(2 % DataType<_Tp>::channels == 0); + if( copyData ) + *this = clone(); +} + +template inline +Mat_<_Tp>::Mat_(const Point3_::channel_type>& pt, bool copyData) + : Mat(3 / DataType<_Tp>::channels, 1, traits::Type<_Tp>::value, (void*)&pt) +{ + CV_Assert(3 % DataType<_Tp>::channels == 0); + if( copyData ) + *this = clone(); +} + +template inline +Mat_<_Tp>::Mat_(const MatCommaInitializer_<_Tp>& commaInitializer) + : Mat(commaInitializer) +{} + +template inline +Mat_<_Tp>::Mat_(const std::vector<_Tp>& vec, bool copyData) + : Mat(vec, copyData) +{} + +template inline +Mat_<_Tp>::Mat_(std::initializer_list<_Tp> list) + : Mat(list) +{} + +template inline +Mat_<_Tp>::Mat_(const std::initializer_list sizes, std::initializer_list<_Tp> list) + : Mat(sizes, list) +{} + +template template inline +Mat_<_Tp>::Mat_(const std::array<_Tp, _Nm>& arr, bool copyData) + : Mat(arr, copyData) +{} + +template inline +Mat_<_Tp>& Mat_<_Tp>::operator = (const Mat& m) +{ + if (m.empty()) + { + release(); + return *this; + } + if( traits::Type<_Tp>::value == m.type() ) + { + Mat::operator = (m); + return *this; + } + if( traits::Depth<_Tp>::value == m.depth() ) + { + return (*this = m.reshape(DataType<_Tp>::channels, m.dims, 0)); + } + CV_Assert(DataType<_Tp>::channels == m.channels() || m.empty()); + m.convertTo(*this, type()); + return *this; +} + +template inline +Mat_<_Tp>& Mat_<_Tp>::operator = (const Mat_& m) +{ + Mat::operator=(m); + return *this; +} + +template inline +Mat_<_Tp>& Mat_<_Tp>::operator = (const _Tp& s) +{ + typedef typename DataType<_Tp>::vec_type VT; + Mat::operator=(Scalar((const VT&)s)); + return *this; +} + +template inline +void Mat_<_Tp>::create(int _rows, int _cols) +{ + Mat::create(_rows, _cols, traits::Type<_Tp>::value); +} + +template inline +void Mat_<_Tp>::create(Size _sz) +{ + Mat::create(_sz, traits::Type<_Tp>::value); +} + +template inline +void Mat_<_Tp>::create(int _dims, const int* _sz) +{ + Mat::create(_dims, _sz, traits::Type<_Tp>::value); +} + +template inline +void Mat_<_Tp>::release() +{ + Mat::release(); + flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value; +} + +template inline +Mat_<_Tp> Mat_<_Tp>::cross(const Mat_& m) const +{ + return Mat_<_Tp>(Mat::cross(m)); +} + +template template inline +Mat_<_Tp>::operator Mat_() const +{ + return Mat_(static_cast(*this)); +} + +template inline +Mat_<_Tp> Mat_<_Tp>::row(int y) const +{ + return Mat_(*this, Range(y, y+1), Range::all()); +} + +template inline +Mat_<_Tp> Mat_<_Tp>::col(int x) const +{ + return Mat_(*this, Range::all(), Range(x, x+1)); +} + +template inline +Mat_<_Tp> Mat_<_Tp>::diag(int d) const +{ + return Mat_(Mat::diag(d)); +} + +template inline +Mat_<_Tp> Mat_<_Tp>::clone() const +{ + return Mat_(Mat::clone()); +} + +template inline +size_t Mat_<_Tp>::elemSize() const +{ + CV_DbgAssert( Mat::elemSize() == sizeof(_Tp) ); + return sizeof(_Tp); +} + +template inline +size_t Mat_<_Tp>::elemSize1() const +{ + CV_DbgAssert( Mat::elemSize1() == sizeof(_Tp) / DataType<_Tp>::channels ); + return sizeof(_Tp) / DataType<_Tp>::channels; +} + +template inline +int Mat_<_Tp>::type() const +{ + CV_DbgAssert( Mat::type() == traits::Type<_Tp>::value ); + return traits::Type<_Tp>::value; +} + +template inline +int Mat_<_Tp>::depth() const +{ + CV_DbgAssert( Mat::depth() == traits::Depth<_Tp>::value ); + return traits::Depth<_Tp>::value; +} + +template inline +int Mat_<_Tp>::channels() const +{ + CV_DbgAssert( Mat::channels() == DataType<_Tp>::channels ); + return DataType<_Tp>::channels; +} + +template inline +size_t Mat_<_Tp>::stepT(int i) const +{ + return step.p[i] / elemSize(); +} + +template inline +size_t Mat_<_Tp>::step1(int i) const +{ + return step.p[i] / elemSize1(); +} + +template inline +Mat_<_Tp>& Mat_<_Tp>::adjustROI( int dtop, int dbottom, int dleft, int dright ) +{ + return (Mat_<_Tp>&)(Mat::adjustROI(dtop, dbottom, dleft, dright)); +} + +template inline +Mat_<_Tp> Mat_<_Tp>::operator()( const Range& _rowRange, const Range& _colRange ) const +{ + return Mat_<_Tp>(*this, _rowRange, _colRange); +} + +template inline +Mat_<_Tp> Mat_<_Tp>::operator()( const Rect& roi ) const +{ + return Mat_<_Tp>(*this, roi); +} + +template inline +Mat_<_Tp> Mat_<_Tp>::operator()( const Range* ranges ) const +{ + return Mat_<_Tp>(*this, ranges); +} + +template inline +Mat_<_Tp> Mat_<_Tp>::operator()(const std::vector& ranges) const +{ + return Mat_<_Tp>(*this, ranges); +} + +template inline +_Tp* Mat_<_Tp>::operator [](int y) +{ + CV_DbgAssert( 0 <= y && y < size.p[0] ); + return (_Tp*)(data + y*step.p[0]); +} + +template inline +const _Tp* Mat_<_Tp>::operator [](int y) const +{ + CV_DbgAssert( 0 <= y && y < size.p[0] ); + return (const _Tp*)(data + y*step.p[0]); +} + +template inline +_Tp& Mat_<_Tp>::operator ()(int i0, int i1) +{ + CV_DbgAssert(dims <= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); + CV_DbgAssert(type() == traits::Type<_Tp>::value); + return ((_Tp*)(data + step.p[0] * i0))[i1]; +} + +template inline +const _Tp& Mat_<_Tp>::operator ()(int i0, int i1) const +{ + CV_DbgAssert(dims <= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); + CV_DbgAssert(type() == traits::Type<_Tp>::value); + return ((const _Tp*)(data + step.p[0] * i0))[i1]; +} + +template inline +_Tp& Mat_<_Tp>::operator ()(Point pt) +{ + CV_DbgAssert(dims <= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)pt.y < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)pt.x < (unsigned)size.p[1]); + CV_DbgAssert(type() == traits::Type<_Tp>::value); + return ((_Tp*)(data + step.p[0] * pt.y))[pt.x]; +} + +template inline +const _Tp& Mat_<_Tp>::operator ()(Point pt) const +{ + CV_DbgAssert(dims <= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)pt.y < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)pt.x < (unsigned)size.p[1]); + CV_DbgAssert(type() == traits::Type<_Tp>::value); + return ((const _Tp*)(data + step.p[0] * pt.y))[pt.x]; +} + +template inline +_Tp& Mat_<_Tp>::operator ()(const int* idx) +{ + return Mat::at<_Tp>(idx); +} + +template inline +const _Tp& Mat_<_Tp>::operator ()(const int* idx) const +{ + return Mat::at<_Tp>(idx); +} + +template template inline +_Tp& Mat_<_Tp>::operator ()(const Vec& idx) +{ + return Mat::at<_Tp>(idx); +} + +template template inline +const _Tp& Mat_<_Tp>::operator ()(const Vec& idx) const +{ + return Mat::at<_Tp>(idx); +} + +template inline +_Tp& Mat_<_Tp>::operator ()(int i0) +{ + return this->at<_Tp>(i0); +} + +template inline +const _Tp& Mat_<_Tp>::operator ()(int i0) const +{ + return this->at<_Tp>(i0); +} + +template inline +_Tp& Mat_<_Tp>::operator ()(int i0, int i1, int i2) +{ + return this->at<_Tp>(i0, i1, i2); +} + +template inline +const _Tp& Mat_<_Tp>::operator ()(int i0, int i1, int i2) const +{ + return this->at<_Tp>(i0, i1, i2); +} + +template inline +Mat_<_Tp>::operator std::vector<_Tp>() const +{ + std::vector<_Tp> v; + copyTo(v); + return v; +} + +template template inline +Mat_<_Tp>::operator std::array<_Tp, _Nm>() const +{ + std::array<_Tp, _Nm> a; + copyTo(a); + return a; +} + +template template inline +Mat_<_Tp>::operator Vec::channel_type, n>() const +{ + CV_Assert(n % DataType<_Tp>::channels == 0); + +#if defined _MSC_VER + const Mat* pMat = (const Mat*)this; // workaround for MSVS <= 2012 compiler bugs (but GCC 4.6 dislikes this workaround) + return pMat->operator Vec::channel_type, n>(); +#else + return this->Mat::operator Vec::channel_type, n>(); +#endif +} + +template template inline +Mat_<_Tp>::operator Matx::channel_type, m, n>() const +{ + CV_Assert(n % DataType<_Tp>::channels == 0); + +#if defined _MSC_VER + const Mat* pMat = (const Mat*)this; // workaround for MSVS <= 2012 compiler bugs (but GCC 4.6 dislikes this workaround) + Matx::channel_type, m, n> res = pMat->operator Matx::channel_type, m, n>(); + return res; +#else + Matx::channel_type, m, n> res = this->Mat::operator Matx::channel_type, m, n>(); + return res; +#endif +} + +template inline +MatConstIterator_<_Tp> Mat_<_Tp>::begin() const +{ + return Mat::begin<_Tp>(); +} + +template inline +std::reverse_iterator> Mat_<_Tp>::rbegin() const +{ + return Mat::rbegin<_Tp>(); +} + +template inline +MatConstIterator_<_Tp> Mat_<_Tp>::end() const +{ + return Mat::end<_Tp>(); +} + +template inline +std::reverse_iterator> Mat_<_Tp>::rend() const +{ + return Mat::rend<_Tp>(); +} + +template inline +MatIterator_<_Tp> Mat_<_Tp>::begin() +{ + return Mat::begin<_Tp>(); +} + +template inline +std::reverse_iterator> Mat_<_Tp>::rbegin() +{ + return Mat::rbegin<_Tp>(); +} + +template inline +MatIterator_<_Tp> Mat_<_Tp>::end() +{ + return Mat::end<_Tp>(); +} + +template inline +std::reverse_iterator> Mat_<_Tp>::rend() +{ + return Mat::rend<_Tp>(); +} + +template template inline +void Mat_<_Tp>::forEach(const Functor& operation) { + Mat::forEach<_Tp, Functor>(operation); +} + +template template inline +void Mat_<_Tp>::forEach(const Functor& operation) const { + Mat::forEach<_Tp, Functor>(operation); +} + +template inline +Mat_<_Tp>::Mat_(Mat_&& m) + : Mat(std::move(m)) +{ +} + +template inline +Mat_<_Tp>& Mat_<_Tp>::operator = (Mat_&& m) +{ + Mat::operator = (std::move(m)); + return *this; +} + +template inline +Mat_<_Tp>::Mat_(Mat&& m) + : Mat() +{ + flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value; + *this = std::move(m); +} + +template inline +Mat_<_Tp>& Mat_<_Tp>::operator = (Mat&& m) +{ + if (m.empty()) + { + release(); + return *this; + } + if( traits::Type<_Tp>::value == m.type() ) + { + Mat::operator = ((Mat&&)m); + return *this; + } + if( traits::Depth<_Tp>::value == m.depth() ) + { + Mat::operator = ((Mat&&)m.reshape(DataType<_Tp>::channels, m.dims, 0)); + return *this; + } + CV_DbgAssert(DataType<_Tp>::channels == m.channels()); + m.convertTo(*this, type()); + return *this; +} + +template inline +Mat_<_Tp>::Mat_(MatExpr&& e) + : Mat() +{ + flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value; + *this = Mat(e); +} + + +///////////////////////////// SparseMat ///////////////////////////// + +inline +SparseMat SparseMat::clone() const +{ + SparseMat temp; + this->copyTo(temp); + return temp; +} + +inline +size_t SparseMat::elemSize() const +{ + return CV_ELEM_SIZE(flags); +} + +inline +size_t SparseMat::elemSize1() const +{ + return CV_ELEM_SIZE1(flags); +} + +inline +int SparseMat::type() const +{ + return CV_MAT_TYPE(flags); +} + +inline +int SparseMat::depth() const +{ + return CV_MAT_DEPTH(flags); +} + +inline +int SparseMat::channels() const +{ + return CV_MAT_CN(flags); +} + +inline +const int* SparseMat::size() const +{ + return hdr ? hdr->size : 0; +} + +inline +int SparseMat::size(int i) const +{ + if( hdr ) + { + CV_DbgAssert((unsigned)i < (unsigned)hdr->dims); + return hdr->size[i]; + } + return 0; +} + +inline +int SparseMat::dims() const +{ + return hdr ? hdr->dims : 0; +} + +inline +size_t SparseMat::nzcount() const +{ + return hdr ? hdr->nodeCount : 0; +} + +template inline +_Tp& SparseMat::ref(int i0, size_t* hashval) +{ + return *(_Tp*)((SparseMat*)this)->ptr(i0, true, hashval); +} + +template inline +_Tp& SparseMat::ref(int i0, int i1, size_t* hashval) +{ + return *(_Tp*)((SparseMat*)this)->ptr(i0, i1, true, hashval); +} + +template inline +_Tp& SparseMat::ref(int i0, int i1, int i2, size_t* hashval) +{ + return *(_Tp*)((SparseMat*)this)->ptr(i0, i1, i2, true, hashval); +} + +template inline +_Tp& SparseMat::ref(const int* idx, size_t* hashval) +{ + return *(_Tp*)((SparseMat*)this)->ptr(idx, true, hashval); +} + +template inline +_Tp SparseMat::value(int i0, size_t* hashval) const +{ + const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(i0, false, hashval); + return p ? *p : _Tp(); +} + +template inline +_Tp SparseMat::value(int i0, int i1, size_t* hashval) const +{ + const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(i0, i1, false, hashval); + return p ? *p : _Tp(); +} + +template inline +_Tp SparseMat::value(int i0, int i1, int i2, size_t* hashval) const +{ + const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(i0, i1, i2, false, hashval); + return p ? *p : _Tp(); +} + +template inline +_Tp SparseMat::value(const int* idx, size_t* hashval) const +{ + const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(idx, false, hashval); + return p ? *p : _Tp(); +} + +template inline +const _Tp* SparseMat::find(int i0, size_t* hashval) const +{ + return (const _Tp*)((SparseMat*)this)->ptr(i0, false, hashval); +} + +template inline +const _Tp* SparseMat::find(int i0, int i1, size_t* hashval) const +{ + return (const _Tp*)((SparseMat*)this)->ptr(i0, i1, false, hashval); +} + +template inline +const _Tp* SparseMat::find(int i0, int i1, int i2, size_t* hashval) const +{ + return (const _Tp*)((SparseMat*)this)->ptr(i0, i1, i2, false, hashval); +} + +template inline +const _Tp* SparseMat::find(const int* idx, size_t* hashval) const +{ + return (const _Tp*)((SparseMat*)this)->ptr(idx, false, hashval); +} + +template inline +_Tp& SparseMat::value(Node* n) +{ + return *(_Tp*)((uchar*)n + hdr->valueOffset); +} + +template inline +const _Tp& SparseMat::value(const Node* n) const +{ + return *(const _Tp*)((const uchar*)n + hdr->valueOffset); +} + +inline +SparseMat::Node* SparseMat::node(size_t nidx) +{ + return (Node*)(void*)&hdr->pool[nidx]; +} + +inline +const SparseMat::Node* SparseMat::node(size_t nidx) const +{ + return (const Node*)(const void*)&hdr->pool[nidx]; +} + +inline +SparseMatIterator SparseMat::begin() +{ + return SparseMatIterator(this); +} + +inline +SparseMatConstIterator SparseMat::begin() const +{ + return SparseMatConstIterator(this); +} + +inline +SparseMatIterator SparseMat::end() +{ + SparseMatIterator it(this); + it.seekEnd(); + return it; +} + +inline +SparseMatConstIterator SparseMat::end() const +{ + SparseMatConstIterator it(this); + it.seekEnd(); + return it; +} + +template inline +SparseMatIterator_<_Tp> SparseMat::begin() +{ + return SparseMatIterator_<_Tp>(this); +} + +template inline +SparseMatConstIterator_<_Tp> SparseMat::begin() const +{ + return SparseMatConstIterator_<_Tp>(this); +} + +template inline +SparseMatIterator_<_Tp> SparseMat::end() +{ + SparseMatIterator_<_Tp> it(this); + it.seekEnd(); + return it; +} + +template inline +SparseMatConstIterator_<_Tp> SparseMat::end() const +{ + SparseMatConstIterator_<_Tp> it(this); + it.seekEnd(); + return it; +} + + + +///////////////////////////// SparseMat_ //////////////////////////// + +template inline +SparseMat_<_Tp>::SparseMat_() +{ + flags = +MAGIC_VAL + traits::Type<_Tp>::value; +} + +template inline +SparseMat_<_Tp>::SparseMat_(int _dims, const int* _sizes) + : SparseMat(_dims, _sizes, traits::Type<_Tp>::value) +{} + +template inline +SparseMat_<_Tp>::SparseMat_(const SparseMat& m) +{ + if( m.type() == traits::Type<_Tp>::value ) + *this = (const SparseMat_<_Tp>&)m; + else + m.convertTo(*this, traits::Type<_Tp>::value); +} + +template inline +SparseMat_<_Tp>::SparseMat_(const SparseMat_<_Tp>& m) +{ + this->flags = m.flags; + this->hdr = m.hdr; + if( this->hdr ) + CV_XADD(&this->hdr->refcount, 1); +} + +template inline +SparseMat_<_Tp>::SparseMat_(const Mat& m) +{ + SparseMat sm(m); + *this = sm; +} + +template inline +SparseMat_<_Tp>& SparseMat_<_Tp>::operator = (const SparseMat_<_Tp>& m) +{ + if( this != &m ) + { + if( m.hdr ) CV_XADD(&m.hdr->refcount, 1); + release(); + flags = m.flags; + hdr = m.hdr; + } + return *this; +} + +template inline +SparseMat_<_Tp>& SparseMat_<_Tp>::operator = (const SparseMat& m) +{ + if( m.type() == traits::Type<_Tp>::value ) + return (*this = (const SparseMat_<_Tp>&)m); + m.convertTo(*this, traits::Type<_Tp>::value); + return *this; +} + +template inline +SparseMat_<_Tp>& SparseMat_<_Tp>::operator = (const Mat& m) +{ + return (*this = SparseMat(m)); +} + +template inline +SparseMat_<_Tp> SparseMat_<_Tp>::clone() const +{ + SparseMat_<_Tp> m; + this->copyTo(m); + return m; +} + +template inline +void SparseMat_<_Tp>::create(int _dims, const int* _sizes) +{ + SparseMat::create(_dims, _sizes, traits::Type<_Tp>::value); +} + +template inline +int SparseMat_<_Tp>::type() const +{ + return traits::Type<_Tp>::value; +} + +template inline +int SparseMat_<_Tp>::depth() const +{ + return traits::Depth<_Tp>::value; +} + +template inline +int SparseMat_<_Tp>::channels() const +{ + return DataType<_Tp>::channels; +} + +template inline +_Tp& SparseMat_<_Tp>::ref(int i0, size_t* hashval) +{ + return SparseMat::ref<_Tp>(i0, hashval); +} + +template inline +_Tp SparseMat_<_Tp>::operator()(int i0, size_t* hashval) const +{ + return SparseMat::value<_Tp>(i0, hashval); +} + +template inline +_Tp& SparseMat_<_Tp>::ref(int i0, int i1, size_t* hashval) +{ + return SparseMat::ref<_Tp>(i0, i1, hashval); +} + +template inline +_Tp SparseMat_<_Tp>::operator()(int i0, int i1, size_t* hashval) const +{ + return SparseMat::value<_Tp>(i0, i1, hashval); +} + +template inline +_Tp& SparseMat_<_Tp>::ref(int i0, int i1, int i2, size_t* hashval) +{ + return SparseMat::ref<_Tp>(i0, i1, i2, hashval); +} + +template inline +_Tp SparseMat_<_Tp>::operator()(int i0, int i1, int i2, size_t* hashval) const +{ + return SparseMat::value<_Tp>(i0, i1, i2, hashval); +} + +template inline +_Tp& SparseMat_<_Tp>::ref(const int* idx, size_t* hashval) +{ + return SparseMat::ref<_Tp>(idx, hashval); +} + +template inline +_Tp SparseMat_<_Tp>::operator()(const int* idx, size_t* hashval) const +{ + return SparseMat::value<_Tp>(idx, hashval); +} + +template inline +SparseMatIterator_<_Tp> SparseMat_<_Tp>::begin() +{ + return SparseMatIterator_<_Tp>(this); +} + +template inline +SparseMatConstIterator_<_Tp> SparseMat_<_Tp>::begin() const +{ + return SparseMatConstIterator_<_Tp>(this); +} + +template inline +SparseMatIterator_<_Tp> SparseMat_<_Tp>::end() +{ + SparseMatIterator_<_Tp> it(this); + it.seekEnd(); + return it; +} + +template inline +SparseMatConstIterator_<_Tp> SparseMat_<_Tp>::end() const +{ + SparseMatConstIterator_<_Tp> it(this); + it.seekEnd(); + return it; +} + + + +////////////////////////// MatConstIterator ///////////////////////// + +inline +MatConstIterator::MatConstIterator() + : m(0), elemSize(0), ptr(0), sliceStart(0), sliceEnd(0) +{} + +inline +MatConstIterator::MatConstIterator(const Mat* _m) + : m(_m), elemSize(_m->elemSize()), ptr(0), sliceStart(0), sliceEnd(0) +{ + if( m && m->isContinuous() ) + { + CV_Assert(!m->empty()); + sliceStart = m->ptr(); + sliceEnd = sliceStart + m->total()*elemSize; + } + seek((const int*)0); +} + +inline +MatConstIterator::MatConstIterator(const Mat* _m, int _row, int _col) + : m(_m), elemSize(_m->elemSize()), ptr(0), sliceStart(0), sliceEnd(0) +{ + CV_Assert(m && m->dims <= 2); + if( m->isContinuous() ) + { + CV_Assert(!m->empty()); + sliceStart = m->ptr(); + sliceEnd = sliceStart + m->total()*elemSize; + } + int idx[] = {_row, _col}; + seek(idx); +} + +inline +MatConstIterator::MatConstIterator(const Mat* _m, Point _pt) + : m(_m), elemSize(_m->elemSize()), ptr(0), sliceStart(0), sliceEnd(0) +{ + CV_Assert(m && m->dims <= 2); + if( m->isContinuous() ) + { + CV_Assert(!m->empty()); + sliceStart = m->ptr(); + sliceEnd = sliceStart + m->total()*elemSize; + } + int idx[] = {_pt.y, _pt.x}; + seek(idx); +} + +inline +MatConstIterator::MatConstIterator(const MatConstIterator& it) + : m(it.m), elemSize(it.elemSize), ptr(it.ptr), sliceStart(it.sliceStart), sliceEnd(it.sliceEnd) +{} + +inline +MatConstIterator& MatConstIterator::operator = (const MatConstIterator& it ) +{ + m = it.m; elemSize = it.elemSize; ptr = it.ptr; + sliceStart = it.sliceStart; sliceEnd = it.sliceEnd; + return *this; +} + +inline +const uchar* MatConstIterator::operator *() const +{ + return ptr; +} + +inline MatConstIterator& MatConstIterator::operator += (ptrdiff_t ofs) +{ + if( !m || ofs == 0 ) + return *this; + ptrdiff_t ofsb = ofs*elemSize; + ptr += ofsb; + if( ptr < sliceStart || sliceEnd <= ptr ) + { + ptr -= ofsb; + seek(ofs, true); + } + return *this; +} + +inline +MatConstIterator& MatConstIterator::operator -= (ptrdiff_t ofs) +{ + return (*this += -ofs); +} + +inline +MatConstIterator& MatConstIterator::operator --() +{ + if( m && (ptr -= elemSize) < sliceStart ) + { + ptr += elemSize; + seek(-1, true); + } + return *this; +} + +inline +MatConstIterator MatConstIterator::operator --(int) +{ + MatConstIterator b = *this; + *this += -1; + return b; +} + +inline +MatConstIterator& MatConstIterator::operator ++() +{ + if( m && (ptr += elemSize) >= sliceEnd ) + { + ptr -= elemSize; + seek(1, true); + } + return *this; +} + +inline MatConstIterator MatConstIterator::operator ++(int) +{ + MatConstIterator b = *this; + *this += 1; + return b; +} + + +static inline +bool operator == (const MatConstIterator& a, const MatConstIterator& b) +{ + return a.m == b.m && a.ptr == b.ptr; +} + +static inline +bool operator != (const MatConstIterator& a, const MatConstIterator& b) +{ + return !(a == b); +} + +static inline +bool operator < (const MatConstIterator& a, const MatConstIterator& b) +{ + return a.ptr < b.ptr; +} + +static inline +bool operator > (const MatConstIterator& a, const MatConstIterator& b) +{ + return a.ptr > b.ptr; +} + +static inline +bool operator <= (const MatConstIterator& a, const MatConstIterator& b) +{ + return a.ptr <= b.ptr; +} + +static inline +bool operator >= (const MatConstIterator& a, const MatConstIterator& b) +{ + return a.ptr >= b.ptr; +} + +static inline +ptrdiff_t operator - (const MatConstIterator& b, const MatConstIterator& a) +{ + if( a.m != b.m ) + return ((size_t)(-1) >> 1); + if( a.sliceEnd == b.sliceEnd ) + return (b.ptr - a.ptr)/static_cast(b.elemSize); + + return b.lpos() - a.lpos(); +} + +static inline +MatConstIterator operator + (const MatConstIterator& a, ptrdiff_t ofs) +{ + MatConstIterator b = a; + return b += ofs; +} + +static inline +MatConstIterator operator + (ptrdiff_t ofs, const MatConstIterator& a) +{ + MatConstIterator b = a; + return b += ofs; +} + +static inline +MatConstIterator operator - (const MatConstIterator& a, ptrdiff_t ofs) +{ + MatConstIterator b = a; + return b += -ofs; +} + + +inline +const uchar* MatConstIterator::operator [](ptrdiff_t i) const +{ + return *(*this + i); +} + + + +///////////////////////// MatConstIterator_ ///////////////////////// + +template inline +MatConstIterator_<_Tp>::MatConstIterator_() +{} + +template inline +MatConstIterator_<_Tp>::MatConstIterator_(const Mat_<_Tp>* _m) + : MatConstIterator(_m) +{} + +template inline +MatConstIterator_<_Tp>::MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col) + : MatConstIterator(_m, _row, _col) +{} + +template inline +MatConstIterator_<_Tp>::MatConstIterator_(const Mat_<_Tp>* _m, Point _pt) + : MatConstIterator(_m, _pt) +{} + +template inline +MatConstIterator_<_Tp>::MatConstIterator_(const MatConstIterator_& it) + : MatConstIterator(it) +{} + +template inline +MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator = (const MatConstIterator_& it ) +{ + MatConstIterator::operator = (it); + return *this; +} + +template inline +const _Tp& MatConstIterator_<_Tp>::operator *() const +{ + return *(_Tp*)(this->ptr); +} + +template inline +MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator += (ptrdiff_t ofs) +{ + MatConstIterator::operator += (ofs); + return *this; +} + +template inline +MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator -= (ptrdiff_t ofs) +{ + return (*this += -ofs); +} + +template inline +MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator --() +{ + MatConstIterator::operator --(); + return *this; +} + +template inline +MatConstIterator_<_Tp> MatConstIterator_<_Tp>::operator --(int) +{ + MatConstIterator_ b = *this; + MatConstIterator::operator --(); + return b; +} + +template inline +MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator ++() +{ + MatConstIterator::operator ++(); + return *this; +} + +template inline +MatConstIterator_<_Tp> MatConstIterator_<_Tp>::operator ++(int) +{ + MatConstIterator_ b = *this; + MatConstIterator::operator ++(); + return b; +} + + +template inline +Point MatConstIterator_<_Tp>::pos() const +{ + if( !m ) + return Point(); + CV_DbgAssert( m->dims <= 2 ); + if( m->isContinuous() ) + { + ptrdiff_t ofs = (const _Tp*)ptr - (const _Tp*)m->data; + int y = (int)(ofs / m->cols); + int x = (int)(ofs - (ptrdiff_t)y * m->cols); + return Point(x, y); + } + else + { + ptrdiff_t ofs = (uchar*)ptr - m->data; + int y = (int)(ofs / m->step); + int x = (int)((ofs - y * m->step)/sizeof(_Tp)); + return Point(x, y); + } +} + + +template static inline +bool operator == (const MatConstIterator_<_Tp>& a, const MatConstIterator_<_Tp>& b) +{ + return a.m == b.m && a.ptr == b.ptr; +} + +template static inline +bool operator != (const MatConstIterator_<_Tp>& a, const MatConstIterator_<_Tp>& b) +{ + return a.m != b.m || a.ptr != b.ptr; +} + +template static inline +MatConstIterator_<_Tp> operator + (const MatConstIterator_<_Tp>& a, ptrdiff_t ofs) +{ + MatConstIterator t = (const MatConstIterator&)a + ofs; + return (MatConstIterator_<_Tp>&)t; +} + +template static inline +MatConstIterator_<_Tp> operator + (ptrdiff_t ofs, const MatConstIterator_<_Tp>& a) +{ + MatConstIterator t = (const MatConstIterator&)a + ofs; + return (MatConstIterator_<_Tp>&)t; +} + +template static inline +MatConstIterator_<_Tp> operator - (const MatConstIterator_<_Tp>& a, ptrdiff_t ofs) +{ + MatConstIterator t = (const MatConstIterator&)a - ofs; + return (MatConstIterator_<_Tp>&)t; +} + +template inline +const _Tp& MatConstIterator_<_Tp>::operator [](ptrdiff_t i) const +{ + return *(_Tp*)MatConstIterator::operator [](i); +} + + + +//////////////////////////// MatIterator_ /////////////////////////// + +template inline +MatIterator_<_Tp>::MatIterator_() + : MatConstIterator_<_Tp>() +{} + +template inline +MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m) + : MatConstIterator_<_Tp>(_m) +{} + +template inline +MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m, int _row, int _col) + : MatConstIterator_<_Tp>(_m, _row, _col) +{} + +template inline +MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m, Point _pt) + : MatConstIterator_<_Tp>(_m, _pt) +{} + +template inline +MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m, const int* _idx) + : MatConstIterator_<_Tp>(_m, _idx) +{} + +template inline +MatIterator_<_Tp>::MatIterator_(const MatIterator_& it) + : MatConstIterator_<_Tp>(it) +{} + +template inline +MatIterator_<_Tp>& MatIterator_<_Tp>::operator = (const MatIterator_<_Tp>& it ) +{ + MatConstIterator::operator = (it); + return *this; +} + +template inline +_Tp& MatIterator_<_Tp>::operator *() const +{ + return *(_Tp*)(this->ptr); +} + +template inline +MatIterator_<_Tp>& MatIterator_<_Tp>::operator += (ptrdiff_t ofs) +{ + MatConstIterator::operator += (ofs); + return *this; +} + +template inline +MatIterator_<_Tp>& MatIterator_<_Tp>::operator -= (ptrdiff_t ofs) +{ + MatConstIterator::operator += (-ofs); + return *this; +} + +template inline +MatIterator_<_Tp>& MatIterator_<_Tp>::operator --() +{ + MatConstIterator::operator --(); + return *this; +} + +template inline +MatIterator_<_Tp> MatIterator_<_Tp>::operator --(int) +{ + MatIterator_ b = *this; + MatConstIterator::operator --(); + return b; +} + +template inline +MatIterator_<_Tp>& MatIterator_<_Tp>::operator ++() +{ + MatConstIterator::operator ++(); + return *this; +} + +template inline +MatIterator_<_Tp> MatIterator_<_Tp>::operator ++(int) +{ + MatIterator_ b = *this; + MatConstIterator::operator ++(); + return b; +} + +template inline +_Tp& MatIterator_<_Tp>::operator [](ptrdiff_t i) const +{ + return *(*this + i); +} + + +template static inline +bool operator == (const MatIterator_<_Tp>& a, const MatIterator_<_Tp>& b) +{ + return a.m == b.m && a.ptr == b.ptr; +} + +template static inline +bool operator != (const MatIterator_<_Tp>& a, const MatIterator_<_Tp>& b) +{ + return a.m != b.m || a.ptr != b.ptr; +} + +template static inline +MatIterator_<_Tp> operator + (const MatIterator_<_Tp>& a, ptrdiff_t ofs) +{ + MatConstIterator t = (const MatConstIterator&)a + ofs; + return (MatIterator_<_Tp>&)t; +} + +template static inline +MatIterator_<_Tp> operator + (ptrdiff_t ofs, const MatIterator_<_Tp>& a) +{ + MatConstIterator t = (const MatConstIterator&)a + ofs; + return (MatIterator_<_Tp>&)t; +} + +template static inline +MatIterator_<_Tp> operator - (const MatIterator_<_Tp>& a, ptrdiff_t ofs) +{ + MatConstIterator t = (const MatConstIterator&)a - ofs; + return (MatIterator_<_Tp>&)t; +} + + + +/////////////////////// SparseMatConstIterator ////////////////////// + +inline +SparseMatConstIterator::SparseMatConstIterator() + : m(0), hashidx(0), ptr(0) +{} + +inline +SparseMatConstIterator::SparseMatConstIterator(const SparseMatConstIterator& it) + : m(it.m), hashidx(it.hashidx), ptr(it.ptr) +{} + +inline SparseMatConstIterator& SparseMatConstIterator::operator = (const SparseMatConstIterator& it) +{ + if( this != &it ) + { + m = it.m; + hashidx = it.hashidx; + ptr = it.ptr; + } + return *this; +} + +template inline +const _Tp& SparseMatConstIterator::value() const +{ + return *(const _Tp*)ptr; +} + +inline +const SparseMat::Node* SparseMatConstIterator::node() const +{ + return (ptr && m && m->hdr) ? (const SparseMat::Node*)(const void*)(ptr - m->hdr->valueOffset) : 0; +} + +inline +SparseMatConstIterator SparseMatConstIterator::operator ++(int) +{ + SparseMatConstIterator it = *this; + ++*this; + return it; +} + +inline +void SparseMatConstIterator::seekEnd() +{ + if( m && m->hdr ) + { + hashidx = m->hdr->hashtab.size(); + ptr = 0; + } +} + + +static inline +bool operator == (const SparseMatConstIterator& it1, const SparseMatConstIterator& it2) +{ + return it1.m == it2.m && it1.ptr == it2.ptr; +} + +static inline +bool operator != (const SparseMatConstIterator& it1, const SparseMatConstIterator& it2) +{ + return !(it1 == it2); +} + + + +///////////////////////// SparseMatIterator ///////////////////////// + +inline +SparseMatIterator::SparseMatIterator() +{} + +inline +SparseMatIterator::SparseMatIterator(SparseMat* _m) + : SparseMatConstIterator(_m) +{} + +inline +SparseMatIterator::SparseMatIterator(const SparseMatIterator& it) + : SparseMatConstIterator(it) +{} + +inline +SparseMatIterator& SparseMatIterator::operator = (const SparseMatIterator& it) +{ + (SparseMatConstIterator&)*this = it; + return *this; +} + +template inline +_Tp& SparseMatIterator::value() const +{ + return *(_Tp*)ptr; +} + +inline +SparseMat::Node* SparseMatIterator::node() const +{ + return (SparseMat::Node*)SparseMatConstIterator::node(); +} + +inline +SparseMatIterator& SparseMatIterator::operator ++() +{ + SparseMatConstIterator::operator ++(); + return *this; +} + +inline +SparseMatIterator SparseMatIterator::operator ++(int) +{ + SparseMatIterator it = *this; + ++*this; + return it; +} + + + +////////////////////// SparseMatConstIterator_ ////////////////////// + +template inline +SparseMatConstIterator_<_Tp>::SparseMatConstIterator_() +{} + +template inline +SparseMatConstIterator_<_Tp>::SparseMatConstIterator_(const SparseMat_<_Tp>* _m) + : SparseMatConstIterator(_m) +{} + +template inline +SparseMatConstIterator_<_Tp>::SparseMatConstIterator_(const SparseMat* _m) + : SparseMatConstIterator(_m) +{ + CV_Assert( _m->type() == traits::Type<_Tp>::value ); +} + +template inline +SparseMatConstIterator_<_Tp>::SparseMatConstIterator_(const SparseMatConstIterator_<_Tp>& it) + : SparseMatConstIterator(it) +{} + +template inline +SparseMatConstIterator_<_Tp>& SparseMatConstIterator_<_Tp>::operator = (const SparseMatConstIterator_<_Tp>& it) +{ + return reinterpret_cast&> + (*reinterpret_cast(this) = + reinterpret_cast(it)); +} + +template inline +const _Tp& SparseMatConstIterator_<_Tp>::operator *() const +{ + return *(const _Tp*)this->ptr; +} + +template inline +SparseMatConstIterator_<_Tp>& SparseMatConstIterator_<_Tp>::operator ++() +{ + SparseMatConstIterator::operator ++(); + return *this; +} + +template inline +SparseMatConstIterator_<_Tp> SparseMatConstIterator_<_Tp>::operator ++(int) +{ + SparseMatConstIterator_<_Tp> it = *this; + SparseMatConstIterator::operator ++(); + return it; +} + + + +///////////////////////// SparseMatIterator_ //////////////////////// + +template inline +SparseMatIterator_<_Tp>::SparseMatIterator_() +{} + +template inline +SparseMatIterator_<_Tp>::SparseMatIterator_(SparseMat_<_Tp>* _m) + : SparseMatConstIterator_<_Tp>(_m) +{} + +template inline +SparseMatIterator_<_Tp>::SparseMatIterator_(SparseMat* _m) + : SparseMatConstIterator_<_Tp>(_m) +{} + +template inline +SparseMatIterator_<_Tp>::SparseMatIterator_(const SparseMatIterator_<_Tp>& it) + : SparseMatConstIterator_<_Tp>(it) +{} + +template inline +SparseMatIterator_<_Tp>& SparseMatIterator_<_Tp>::operator = (const SparseMatIterator_<_Tp>& it) +{ + return reinterpret_cast&> + (*reinterpret_cast(this) = + reinterpret_cast(it)); +} + +template inline +_Tp& SparseMatIterator_<_Tp>::operator *() const +{ + return *(_Tp*)this->ptr; +} + +template inline +SparseMatIterator_<_Tp>& SparseMatIterator_<_Tp>::operator ++() +{ + SparseMatConstIterator::operator ++(); + return *this; +} + +template inline +SparseMatIterator_<_Tp> SparseMatIterator_<_Tp>::operator ++(int) +{ + SparseMatIterator_<_Tp> it = *this; + SparseMatConstIterator::operator ++(); + return it; +} + + + +//////////////////////// MatCommaInitializer_ /////////////////////// + +template inline +MatCommaInitializer_<_Tp>::MatCommaInitializer_(Mat_<_Tp>* _m) + : it(_m) +{} + +template template inline +MatCommaInitializer_<_Tp>& MatCommaInitializer_<_Tp>::operator , (T2 v) +{ + CV_DbgAssert( this->it < ((const Mat_<_Tp>*)this->it.m)->end() ); + *this->it = _Tp(v); + ++this->it; + return *this; +} + +template inline +MatCommaInitializer_<_Tp>::operator Mat_<_Tp>() const +{ + CV_DbgAssert( this->it == ((const Mat_<_Tp>*)this->it.m)->end() ); + return Mat_<_Tp>(*this->it.m); +} + + +template static inline +MatCommaInitializer_<_Tp> operator << (const Mat_<_Tp>& m, T2 val) +{ + MatCommaInitializer_<_Tp> commaInitializer((Mat_<_Tp>*)&m); + return (commaInitializer, val); +} + + + +///////////////////////// Matrix Expressions //////////////////////// + +inline +Mat& Mat::operator = (const MatExpr& e) +{ + e.op->assign(e, *this); + return *this; +} + +template inline +Mat_<_Tp>::Mat_(const MatExpr& e) +{ + e.op->assign(e, *this, traits::Type<_Tp>::value); +} + +template inline +Mat_<_Tp>& Mat_<_Tp>::operator = (const MatExpr& e) +{ + e.op->assign(e, *this, traits::Type<_Tp>::value); + return *this; +} + +template inline +MatExpr Mat_<_Tp>::zeros(int rows, int cols) +{ + return Mat::zeros(rows, cols, traits::Type<_Tp>::value); +} + +template inline +MatExpr Mat_<_Tp>::zeros(Size sz) +{ + return Mat::zeros(sz, traits::Type<_Tp>::value); +} + +template inline +MatExpr Mat_<_Tp>::ones(int rows, int cols) +{ + return Mat::ones(rows, cols, traits::Type<_Tp>::value); +} + +template inline +MatExpr Mat_<_Tp>::ones(Size sz) +{ + return Mat::ones(sz, traits::Type<_Tp>::value); +} + +template inline +MatExpr Mat_<_Tp>::eye(int rows, int cols) +{ + return Mat::eye(rows, cols, traits::Type<_Tp>::value); +} + +template inline +MatExpr Mat_<_Tp>::eye(Size sz) +{ + return Mat::eye(sz, traits::Type<_Tp>::value); +} + +inline +MatExpr::MatExpr() + : op(0), flags(0), a(Mat()), b(Mat()), c(Mat()), alpha(0), beta(0), s() +{} + +inline +MatExpr::MatExpr(const MatOp* _op, int _flags, const Mat& _a, const Mat& _b, + const Mat& _c, double _alpha, double _beta, const Scalar& _s) + : op(_op), flags(_flags), a(_a), b(_b), c(_c), alpha(_alpha), beta(_beta), s(_s) +{} + +inline +MatExpr::operator Mat() const +{ + Mat m; + op->assign(*this, m); + return m; +} + +template inline +MatExpr::operator Mat_<_Tp>() const +{ + Mat_<_Tp> m; + op->assign(*this, m, traits::Type<_Tp>::value); + return m; +} + + +template static inline +MatExpr min(const Mat_<_Tp>& a, const Mat_<_Tp>& b) +{ + return cv::min((const Mat&)a, (const Mat&)b); +} + +template static inline +MatExpr min(const Mat_<_Tp>& a, double s) +{ + return cv::min((const Mat&)a, s); +} + +template static inline +MatExpr min(double s, const Mat_<_Tp>& a) +{ + return cv::min((const Mat&)a, s); +} + +template static inline +MatExpr max(const Mat_<_Tp>& a, const Mat_<_Tp>& b) +{ + return cv::max((const Mat&)a, (const Mat&)b); +} + +template static inline +MatExpr max(const Mat_<_Tp>& a, double s) +{ + return cv::max((const Mat&)a, s); +} + +template static inline +MatExpr max(double s, const Mat_<_Tp>& a) +{ + return cv::max((const Mat&)a, s); +} + +template static inline +MatExpr abs(const Mat_<_Tp>& m) +{ + return cv::abs((const Mat&)m); +} + + +static inline +Mat& operator += (Mat& a, const MatExpr& b) +{ + b.op->augAssignAdd(b, a); + return a; +} + +static inline +const Mat& operator += (const Mat& a, const MatExpr& b) +{ + b.op->augAssignAdd(b, (Mat&)a); + return a; +} + +template static inline +Mat_<_Tp>& operator += (Mat_<_Tp>& a, const MatExpr& b) +{ + b.op->augAssignAdd(b, a); + return a; +} + +template static inline +const Mat_<_Tp>& operator += (const Mat_<_Tp>& a, const MatExpr& b) +{ + b.op->augAssignAdd(b, (Mat&)a); + return a; +} + +static inline +Mat& operator -= (Mat& a, const MatExpr& b) +{ + b.op->augAssignSubtract(b, a); + return a; +} + +static inline +const Mat& operator -= (const Mat& a, const MatExpr& b) +{ + b.op->augAssignSubtract(b, (Mat&)a); + return a; +} + +template static inline +Mat_<_Tp>& operator -= (Mat_<_Tp>& a, const MatExpr& b) +{ + b.op->augAssignSubtract(b, a); + return a; +} + +template static inline +const Mat_<_Tp>& operator -= (const Mat_<_Tp>& a, const MatExpr& b) +{ + b.op->augAssignSubtract(b, (Mat&)a); + return a; +} + +static inline +Mat& operator *= (Mat& a, const MatExpr& b) +{ + b.op->augAssignMultiply(b, a); + return a; +} + +static inline +const Mat& operator *= (const Mat& a, const MatExpr& b) +{ + b.op->augAssignMultiply(b, (Mat&)a); + return a; +} + +template static inline +Mat_<_Tp>& operator *= (Mat_<_Tp>& a, const MatExpr& b) +{ + b.op->augAssignMultiply(b, a); + return a; +} + +template static inline +const Mat_<_Tp>& operator *= (const Mat_<_Tp>& a, const MatExpr& b) +{ + b.op->augAssignMultiply(b, (Mat&)a); + return a; +} + +static inline +Mat& operator /= (Mat& a, const MatExpr& b) +{ + b.op->augAssignDivide(b, a); + return a; +} + +static inline +const Mat& operator /= (const Mat& a, const MatExpr& b) +{ + b.op->augAssignDivide(b, (Mat&)a); + return a; +} + +template static inline +Mat_<_Tp>& operator /= (Mat_<_Tp>& a, const MatExpr& b) +{ + b.op->augAssignDivide(b, a); + return a; +} + +template static inline +const Mat_<_Tp>& operator /= (const Mat_<_Tp>& a, const MatExpr& b) +{ + b.op->augAssignDivide(b, (Mat&)a); + return a; +} + + +//////////////////////////////// UMat //////////////////////////////// + +template inline +UMat::UMat(const std::vector<_Tp>& vec, bool copyData) +: flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows((int)vec.size()), +cols(1), allocator(0), usageFlags(USAGE_DEFAULT), u(0), offset(0), size(&rows) +{ + if(vec.empty()) + return; + if( !copyData ) + { + // !!!TODO!!! + CV_Error(Error::StsNotImplemented, ""); + } + else + Mat((int)vec.size(), 1, traits::Type<_Tp>::value, (uchar*)&vec[0]).copyTo(*this); +} + +inline +UMat UMat::row(int y) const +{ + return UMat(*this, Range(y, y + 1), Range::all()); +} + +inline +UMat UMat::col(int x) const +{ + return UMat(*this, Range::all(), Range(x, x + 1)); +} + +inline +UMat UMat::rowRange(int startrow, int endrow) const +{ + return UMat(*this, Range(startrow, endrow), Range::all()); +} + +inline +UMat UMat::rowRange(const Range& r) const +{ + return UMat(*this, r, Range::all()); +} + +inline +UMat UMat::colRange(int startcol, int endcol) const +{ + return UMat(*this, Range::all(), Range(startcol, endcol)); +} + +inline +UMat UMat::colRange(const Range& r) const +{ + return UMat(*this, Range::all(), r); +} + +inline +UMat UMat::operator()( Range _rowRange, Range _colRange ) const +{ + return UMat(*this, _rowRange, _colRange); +} + +inline +UMat UMat::operator()( const Rect& roi ) const +{ + return UMat(*this, roi); +} + +inline +UMat UMat::operator()(const Range* ranges) const +{ + return UMat(*this, ranges); +} + +inline +UMat UMat::operator()(const std::vector& ranges) const +{ + return UMat(*this, ranges); +} + +inline +bool UMat::isContinuous() const +{ + return (flags & CONTINUOUS_FLAG) != 0; +} + +inline +bool UMat::isSubmatrix() const +{ + return (flags & SUBMATRIX_FLAG) != 0; +} + +inline +size_t UMat::elemSize() const +{ + size_t res = dims > 0 ? step.p[dims - 1] : 0; + CV_DbgAssert(res != 0); + return res; +} + +inline +size_t UMat::elemSize1() const +{ + return CV_ELEM_SIZE1(flags); +} + +inline +int UMat::type() const +{ + return CV_MAT_TYPE(flags); +} + +inline +int UMat::depth() const +{ + return CV_MAT_DEPTH(flags); +} + +inline +int UMat::channels() const +{ + return CV_MAT_CN(flags); +} + +inline +size_t UMat::step1(int i) const +{ + return step.p[i] / elemSize1(); +} + + +inline bool UMatData::hostCopyObsolete() const { return (flags & HOST_COPY_OBSOLETE) != 0; } +inline bool UMatData::deviceCopyObsolete() const { return (flags & DEVICE_COPY_OBSOLETE) != 0; } +inline bool UMatData::deviceMemMapped() const { return (flags & DEVICE_MEM_MAPPED) != 0; } +inline bool UMatData::copyOnMap() const { return (flags & COPY_ON_MAP) != 0; } +inline bool UMatData::tempUMat() const { return (flags & TEMP_UMAT) != 0; } +inline bool UMatData::tempCopiedUMat() const { return (flags & TEMP_COPIED_UMAT) == TEMP_COPIED_UMAT; } + +inline void UMatData::markDeviceMemMapped(bool flag) +{ + if(flag) + flags |= DEVICE_MEM_MAPPED; + else + flags &= ~DEVICE_MEM_MAPPED; +} + +inline void UMatData::markHostCopyObsolete(bool flag) +{ + if(flag) + flags |= HOST_COPY_OBSOLETE; + else + flags &= ~HOST_COPY_OBSOLETE; +} +inline void UMatData::markDeviceCopyObsolete(bool flag) +{ + if(flag) + flags |= DEVICE_COPY_OBSOLETE; + else + flags &= ~DEVICE_COPY_OBSOLETE; +} + +//! @endcond + +static inline +void swap(MatExpr& a, MatExpr& b) { a.swap(b); } + +} //cv + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#ifdef CV_DISABLE_CLANG_ENUM_WARNINGS +#undef CV_DISABLE_CLANG_ENUM_WARNINGS +#pragma clang diagnostic pop +#endif + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/matx.hpp b/3rdParty/opencv-4.11.0/opencv2/core/matx.hpp index ad13797da3..6216035aa9 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/matx.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/matx.hpp @@ -1,544 +1,544 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CORE_MATX_HPP -#define OPENCV_CORE_MATX_HPP - -#ifndef __cplusplus -# error matx.hpp header must be compiled as C++ -#endif - -#include "opencv2/core/cvdef.h" -#include "opencv2/core/base.hpp" -#include "opencv2/core/traits.hpp" -#include "opencv2/core/saturate.hpp" - -#include - -namespace cv -{ - -//! @addtogroup core_basic -//! @{ - -//! @cond IGNORED -// FIXIT Remove this (especially CV_EXPORTS modifier) -struct CV_EXPORTS Matx_AddOp { Matx_AddOp() {} Matx_AddOp(const Matx_AddOp&) {} }; -struct CV_EXPORTS Matx_SubOp { Matx_SubOp() {} Matx_SubOp(const Matx_SubOp&) {} }; -struct CV_EXPORTS Matx_ScaleOp { Matx_ScaleOp() {} Matx_ScaleOp(const Matx_ScaleOp&) {} }; -struct CV_EXPORTS Matx_MulOp { Matx_MulOp() {} Matx_MulOp(const Matx_MulOp&) {} }; -struct CV_EXPORTS Matx_DivOp { Matx_DivOp() {} Matx_DivOp(const Matx_DivOp&) {} }; -struct CV_EXPORTS Matx_MatMulOp { Matx_MatMulOp() {} Matx_MatMulOp(const Matx_MatMulOp&) {} }; -struct CV_EXPORTS Matx_TOp { Matx_TOp() {} Matx_TOp(const Matx_TOp&) {} }; -//! @endcond - -////////////////////////////// Small Matrix /////////////////////////// - -/** @brief Template class for small matrices whose type and size are known at compilation time - -If you need a more flexible type, use Mat . The elements of the matrix M are accessible using the -M(i,j) notation. Most of the common matrix operations (see also @ref MatrixExpressions ) are -available. To do an operation on Matx that is not implemented, you can easily convert the matrix to -Mat and backwards: -@code{.cpp} - Matx33f m(1, 2, 3, - 4, 5, 6, - 7, 8, 9); - cout << sum(Mat(m*m.t())) << endl; -@endcode -Except of the plain constructor which takes a list of elements, Matx can be initialized from a C-array: -@code{.cpp} - float values[] = { 1, 2, 3}; - Matx31f m(values); -@endcode -In case if C++11 features are available, std::initializer_list can be also used to initialize Matx: -@code{.cpp} - Matx31f m = { 1, 2, 3}; -@endcode - */ -template class Matx -{ -public: - enum { - rows = m, - cols = n, - channels = rows*cols, -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - depth = traits::Type<_Tp>::value, - type = CV_MAKETYPE(depth, channels), -#endif - shortdim = (m < n ? m : n) - }; - - typedef _Tp value_type; - typedef Matx<_Tp, m, n> mat_type; - typedef Matx<_Tp, shortdim, 1> diag_type; - - //! default constructor - Matx(); - - explicit Matx(_Tp v0); //!< 1x1 matrix - Matx(_Tp v0, _Tp v1); //!< 1x2 or 2x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2); //!< 1x3 or 3x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3); //!< 1x4, 2x2 or 4x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4); //!< 1x5 or 5x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5); //!< 1x6, 2x3, 3x2 or 6x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6); //!< 1x7 or 7x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7); //!< 1x8, 2x4, 4x2 or 8x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8); //!< 1x9, 3x3 or 9x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9); //!< 1x10, 2x5 or 5x2 or 10x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, - _Tp v4, _Tp v5, _Tp v6, _Tp v7, - _Tp v8, _Tp v9, _Tp v10, _Tp v11); //!< 1x12, 2x6, 3x4, 4x3, 6x2 or 12x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, - _Tp v4, _Tp v5, _Tp v6, _Tp v7, - _Tp v8, _Tp v9, _Tp v10, _Tp v11, - _Tp v12, _Tp v13); //!< 1x14, 2x7, 7x2 or 14x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, - _Tp v4, _Tp v5, _Tp v6, _Tp v7, - _Tp v8, _Tp v9, _Tp v10, _Tp v11, - _Tp v12, _Tp v13, _Tp v14, _Tp v15); //!< 1x16, 4x4 or 16x1 matrix - explicit Matx(const _Tp* vals); //!< initialize from a plain array - - Matx(std::initializer_list<_Tp>); //!< initialize from an initializer list - - CV_NODISCARD_STD static Matx all(_Tp alpha); - CV_NODISCARD_STD static Matx zeros(); - CV_NODISCARD_STD static Matx ones(); - CV_NODISCARD_STD static Matx eye(); - CV_NODISCARD_STD static Matx diag(const diag_type& d); - /** @brief Generates uniformly distributed random numbers - @param a Range boundary. - @param b The other range boundary (boundaries don't have to be ordered, the lower boundary is inclusive, - the upper one is exclusive). - */ - CV_NODISCARD_STD static Matx randu(_Tp a, _Tp b); - /** @brief Generates normally distributed random numbers - @param a Mean value. - @param b Standard deviation. - */ - CV_NODISCARD_STD static Matx randn(_Tp a, _Tp b); - - //! dot product computed with the default precision - _Tp dot(const Matx<_Tp, m, n>& v) const; - - //! dot product computed in double-precision arithmetics - double ddot(const Matx<_Tp, m, n>& v) const; - - //! conversion to another data type - template operator Matx() const; - - //! change the matrix shape - template Matx<_Tp, m1, n1> reshape() const; - - //! extract part of the matrix - template Matx<_Tp, m1, n1> get_minor(int base_row, int base_col) const; - - //! extract the matrix row - Matx<_Tp, 1, n> row(int i) const; - - //! extract the matrix column - Matx<_Tp, m, 1> col(int i) const; - - //! extract the matrix diagonal - diag_type diag() const; - - //! transpose the matrix - Matx<_Tp, n, m> t() const; - - //! invert the matrix - Matx<_Tp, n, m> inv(int method=DECOMP_LU, bool *p_is_ok = NULL) const; - - //! solve linear system - template Matx<_Tp, n, l> solve(const Matx<_Tp, m, l>& rhs, int flags=DECOMP_LU) const; - Vec<_Tp, n> solve(const Vec<_Tp, m>& rhs, int method) const; - - //! multiply two matrices element-wise - Matx<_Tp, m, n> mul(const Matx<_Tp, m, n>& a) const; - - //! divide two matrices element-wise - Matx<_Tp, m, n> div(const Matx<_Tp, m, n>& a) const; - - //! element access - const _Tp& operator ()(int row, int col) const; - _Tp& operator ()(int row, int col); - - //! 1D element access - const _Tp& operator ()(int i) const; - _Tp& operator ()(int i); - - Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_AddOp); - Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_SubOp); - template Matx(const Matx<_Tp, m, n>& a, _T2 alpha, Matx_ScaleOp); - Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_MulOp); - Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_DivOp); - template Matx(const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b, Matx_MatMulOp); - Matx(const Matx<_Tp, n, m>& a, Matx_TOp); - - _Tp val[m*n]; ///< matrix elements -}; - -typedef Matx Matx12f; -typedef Matx Matx12d; -typedef Matx Matx13f; -typedef Matx Matx13d; -typedef Matx Matx14f; -typedef Matx Matx14d; -typedef Matx Matx16f; -typedef Matx Matx16d; - -typedef Matx Matx21f; -typedef Matx Matx21d; -typedef Matx Matx31f; -typedef Matx Matx31d; -typedef Matx Matx41f; -typedef Matx Matx41d; -typedef Matx Matx61f; -typedef Matx Matx61d; - -typedef Matx Matx22f; -typedef Matx Matx22d; -typedef Matx Matx23f; -typedef Matx Matx23d; -typedef Matx Matx32f; -typedef Matx Matx32d; - -typedef Matx Matx33f; -typedef Matx Matx33d; - -typedef Matx Matx34f; -typedef Matx Matx34d; -typedef Matx Matx43f; -typedef Matx Matx43d; - -typedef Matx Matx44f; -typedef Matx Matx44d; -typedef Matx Matx66f; -typedef Matx Matx66d; - -template static inline -double determinant(const Matx<_Tp, m, m>& a); - -template static inline -double trace(const Matx<_Tp, m, n>& a); - -template static inline -double norm(const Matx<_Tp, m, n>& M); - -template static inline -double norm(const Matx<_Tp, m, n>& M, int normType); - -template static inline -Matx<_Tp1, m, n>& operator += (Matx<_Tp1, m, n>& a, const Matx<_Tp2, m, n>& b); - -template static inline -Matx<_Tp1, m, n>& operator -= (Matx<_Tp1, m, n>& a, const Matx<_Tp2, m, n>& b); - -template static inline -Matx<_Tp, m, n> operator + (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b); - -template static inline -Matx<_Tp, m, n> operator - (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b); - -template static inline -Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, int alpha); - -template static inline -Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, float alpha); - -template static inline -Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, double alpha); - -template static inline -Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, int alpha); - -template static inline -Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, float alpha); - -template static inline -Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, double alpha); - -template static inline -Matx<_Tp, m, n> operator * (int alpha, const Matx<_Tp, m, n>& a); - -template static inline -Matx<_Tp, m, n> operator * (float alpha, const Matx<_Tp, m, n>& a); - -template static inline -Matx<_Tp, m, n> operator * (double alpha, const Matx<_Tp, m, n>& a); - -template static inline -Matx<_Tp, m, n>& operator /= (Matx<_Tp, m, n>& a, float alpha); - -template static inline -Matx<_Tp, m, n>& operator /= (Matx<_Tp, m, n>& a, double alpha); - -template static inline -Matx<_Tp, m, n> operator / (const Matx<_Tp, m, n>& a, float alpha); - -template static inline -Matx<_Tp, m, n> operator / (const Matx<_Tp, m, n>& a, double alpha); - -template static inline -Matx<_Tp, m, n> operator - (const Matx<_Tp, m, n>& a); - -template static inline -Matx<_Tp, m, n> operator * (const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b); - -template static inline -Vec<_Tp, m> operator * (const Matx<_Tp, m, n>& a, const Vec<_Tp, n>& b); - -template static inline -bool operator == (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b); - -template static inline -bool operator != (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b); - - -/////////////////////// Vec (used as element of multi-channel images ///////////////////// - -/** @brief Template class for short numerical vectors, a partial case of Matx - -This template class represents short numerical vectors (of 1, 2, 3, 4 ... elements) on which you -can perform basic arithmetical operations, access individual elements using [] operator etc. The -vectors are allocated on stack, as opposite to std::valarray, std::vector, cv::Mat etc., which -elements are dynamically allocated in the heap. - -The template takes 2 parameters: -@tparam _Tp element type -@tparam cn the number of elements - -In addition to the universal notation like Vec, you can use shorter aliases -for the most popular specialized variants of Vec, e.g. Vec3f ~ Vec. - -It is possible to convert Vec\ to/from Point_, Vec\ to/from Point3_ , and Vec\ -to CvScalar or Scalar_. Use operator[] to access the elements of Vec. - -All the expected vector operations are also implemented: -- v1 = v2 + v3 -- v1 = v2 - v3 -- v1 = v2 \* scale -- v1 = scale \* v2 -- v1 = -v2 -- v1 += v2 and other augmenting operations -- v1 == v2, v1 != v2 -- norm(v1) (euclidean norm) -The Vec class is commonly used to describe pixel types of multi-channel arrays. See Mat for details. -*/ -template class Vec : public Matx<_Tp, cn, 1> -{ -public: - typedef _Tp value_type; - enum { - channels = cn, -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - depth = Matx<_Tp, cn, 1>::depth, - type = CV_MAKETYPE(depth, channels), -#endif - _dummy_enum_finalizer = 0 - }; - - //! default constructor - Vec(); - - Vec(_Tp v0); //!< 1-element vector constructor - Vec(_Tp v0, _Tp v1); //!< 2-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2); //!< 3-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3); //!< 4-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4); //!< 5-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5); //!< 6-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6); //!< 7-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7); //!< 8-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8); //!< 9-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9); //!< 10-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11, _Tp v12, _Tp v13); //!< 14-element vector constructor - explicit Vec(const _Tp* values); - - Vec(std::initializer_list<_Tp>); - - Vec(const Vec<_Tp, cn>& v); - - static Vec all(_Tp alpha); - static Vec ones(); - static Vec randn(_Tp a, _Tp b); - static Vec randu(_Tp a, _Tp b); - static Vec zeros(); - static Vec diag(_Tp alpha) = delete; - static Vec eye() = delete; - - //! per-element multiplication - Vec mul(const Vec<_Tp, cn>& v) const; - - //! conjugation (makes sense for complex numbers and quaternions) - Vec conj() const; - - /*! - cross product of the two 3D vectors. - - For other dimensionalities the exception is raised - */ - Vec cross(const Vec& v) const; - //! conversion to another data type - template operator Vec() const; - - /*! element access */ - const _Tp& operator [](int i) const; - _Tp& operator[](int i); - const _Tp& operator ()(int i) const; - _Tp& operator ()(int i); - - Vec<_Tp, cn>& operator=(const Vec<_Tp, cn>& rhs) = default; - - Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_AddOp); - Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_SubOp); - template Vec(const Matx<_Tp, cn, 1>& a, _T2 alpha, Matx_ScaleOp); -}; - -/** @name Shorter aliases for the most popular specializations of Vec - @{ -*/ -typedef Vec Vec2b; -typedef Vec Vec3b; -typedef Vec Vec4b; - -typedef Vec Vec2s; -typedef Vec Vec3s; -typedef Vec Vec4s; - -typedef Vec Vec2w; -typedef Vec Vec3w; -typedef Vec Vec4w; - -typedef Vec Vec2i; -typedef Vec Vec3i; -typedef Vec Vec4i; -typedef Vec Vec6i; -typedef Vec Vec8i; - -typedef Vec Vec2f; -typedef Vec Vec3f; -typedef Vec Vec4f; -typedef Vec Vec6f; - -typedef Vec Vec2d; -typedef Vec Vec3d; -typedef Vec Vec4d; -typedef Vec Vec6d; -/** @} */ - -template inline -Vec<_Tp, cn> normalize(const Vec<_Tp, cn>& v); - -template static inline -Vec<_Tp1, cn>& operator += (Vec<_Tp1, cn>& a, const Vec<_Tp2, cn>& b); - -template static inline -Vec<_Tp1, cn>& operator -= (Vec<_Tp1, cn>& a, const Vec<_Tp2, cn>& b); - -template static inline -Vec<_Tp, cn> operator + (const Vec<_Tp, cn>& a, const Vec<_Tp, cn>& b); - -template static inline -Vec<_Tp, cn> operator - (const Vec<_Tp, cn>& a, const Vec<_Tp, cn>& b); - -template static inline -Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, int alpha); - -template static inline -Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, float alpha); - -template static inline -Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, double alpha); - -template static inline -Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, int alpha); - -template static inline -Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, float alpha); - -template static inline -Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, double alpha); - -template static inline -Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, int alpha); - -template static inline -Vec<_Tp, cn> operator * (int alpha, const Vec<_Tp, cn>& a); - -template static inline -Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, float alpha); - -template static inline -Vec<_Tp, cn> operator * (float alpha, const Vec<_Tp, cn>& a); - -template static inline -Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, double alpha); - -template static inline -Vec<_Tp, cn> operator * (double alpha, const Vec<_Tp, cn>& a); - -template static inline -Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, int alpha); - -template static inline -Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, float alpha); - -template static inline -Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, double alpha); - -template static inline -Vec<_Tp, cn> operator - (const Vec<_Tp, cn>& a); - -template inline -Vec<_Tp, 4> operator * (const Vec<_Tp, 4>& v1, const Vec<_Tp, 4>& v2); - -template inline -Vec<_Tp, 4>& operator *= (Vec<_Tp, 4>& v1, const Vec<_Tp, 4>& v2); - -//! @} core_basic - -} // cv - -#include "opencv2/core/matx.inl.hpp" - -#endif // OPENCV_CORE_MATX_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CORE_MATX_HPP +#define OPENCV_CORE_MATX_HPP + +#ifndef __cplusplus +# error matx.hpp header must be compiled as C++ +#endif + +#include "opencv2/core/cvdef.h" +#include "opencv2/core/base.hpp" +#include "opencv2/core/traits.hpp" +#include "opencv2/core/saturate.hpp" + +#include + +namespace cv +{ + +//! @addtogroup core_basic +//! @{ + +//! @cond IGNORED +// FIXIT Remove this (especially CV_EXPORTS modifier) +struct CV_EXPORTS Matx_AddOp { Matx_AddOp() {} Matx_AddOp(const Matx_AddOp&) {} }; +struct CV_EXPORTS Matx_SubOp { Matx_SubOp() {} Matx_SubOp(const Matx_SubOp&) {} }; +struct CV_EXPORTS Matx_ScaleOp { Matx_ScaleOp() {} Matx_ScaleOp(const Matx_ScaleOp&) {} }; +struct CV_EXPORTS Matx_MulOp { Matx_MulOp() {} Matx_MulOp(const Matx_MulOp&) {} }; +struct CV_EXPORTS Matx_DivOp { Matx_DivOp() {} Matx_DivOp(const Matx_DivOp&) {} }; +struct CV_EXPORTS Matx_MatMulOp { Matx_MatMulOp() {} Matx_MatMulOp(const Matx_MatMulOp&) {} }; +struct CV_EXPORTS Matx_TOp { Matx_TOp() {} Matx_TOp(const Matx_TOp&) {} }; +//! @endcond + +////////////////////////////// Small Matrix /////////////////////////// + +/** @brief Template class for small matrices whose type and size are known at compilation time + +If you need a more flexible type, use Mat . The elements of the matrix M are accessible using the +M(i,j) notation. Most of the common matrix operations (see also @ref MatrixExpressions ) are +available. To do an operation on Matx that is not implemented, you can easily convert the matrix to +Mat and backwards: +@code{.cpp} + Matx33f m(1, 2, 3, + 4, 5, 6, + 7, 8, 9); + cout << sum(Mat(m*m.t())) << endl; +@endcode +Except of the plain constructor which takes a list of elements, Matx can be initialized from a C-array: +@code{.cpp} + float values[] = { 1, 2, 3}; + Matx31f m(values); +@endcode +In case if C++11 features are available, std::initializer_list can be also used to initialize Matx: +@code{.cpp} + Matx31f m = { 1, 2, 3}; +@endcode + */ +template class Matx +{ +public: + enum { + rows = m, + cols = n, + channels = rows*cols, +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + depth = traits::Type<_Tp>::value, + type = CV_MAKETYPE(depth, channels), +#endif + shortdim = (m < n ? m : n) + }; + + typedef _Tp value_type; + typedef Matx<_Tp, m, n> mat_type; + typedef Matx<_Tp, shortdim, 1> diag_type; + + //! default constructor + Matx(); + + explicit Matx(_Tp v0); //!< 1x1 matrix + Matx(_Tp v0, _Tp v1); //!< 1x2 or 2x1 matrix + Matx(_Tp v0, _Tp v1, _Tp v2); //!< 1x3 or 3x1 matrix + Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3); //!< 1x4, 2x2 or 4x1 matrix + Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4); //!< 1x5 or 5x1 matrix + Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5); //!< 1x6, 2x3, 3x2 or 6x1 matrix + Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6); //!< 1x7 or 7x1 matrix + Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7); //!< 1x8, 2x4, 4x2 or 8x1 matrix + Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8); //!< 1x9, 3x3 or 9x1 matrix + Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9); //!< 1x10, 2x5 or 5x2 or 10x1 matrix + Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, + _Tp v4, _Tp v5, _Tp v6, _Tp v7, + _Tp v8, _Tp v9, _Tp v10, _Tp v11); //!< 1x12, 2x6, 3x4, 4x3, 6x2 or 12x1 matrix + Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, + _Tp v4, _Tp v5, _Tp v6, _Tp v7, + _Tp v8, _Tp v9, _Tp v10, _Tp v11, + _Tp v12, _Tp v13); //!< 1x14, 2x7, 7x2 or 14x1 matrix + Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, + _Tp v4, _Tp v5, _Tp v6, _Tp v7, + _Tp v8, _Tp v9, _Tp v10, _Tp v11, + _Tp v12, _Tp v13, _Tp v14, _Tp v15); //!< 1x16, 4x4 or 16x1 matrix + explicit Matx(const _Tp* vals); //!< initialize from a plain array + + Matx(std::initializer_list<_Tp>); //!< initialize from an initializer list + + CV_NODISCARD_STD static Matx all(_Tp alpha); + CV_NODISCARD_STD static Matx zeros(); + CV_NODISCARD_STD static Matx ones(); + CV_NODISCARD_STD static Matx eye(); + CV_NODISCARD_STD static Matx diag(const diag_type& d); + /** @brief Generates uniformly distributed random numbers + @param a Range boundary. + @param b The other range boundary (boundaries don't have to be ordered, the lower boundary is inclusive, + the upper one is exclusive). + */ + CV_NODISCARD_STD static Matx randu(_Tp a, _Tp b); + /** @brief Generates normally distributed random numbers + @param a Mean value. + @param b Standard deviation. + */ + CV_NODISCARD_STD static Matx randn(_Tp a, _Tp b); + + //! dot product computed with the default precision + _Tp dot(const Matx<_Tp, m, n>& v) const; + + //! dot product computed in double-precision arithmetics + double ddot(const Matx<_Tp, m, n>& v) const; + + //! conversion to another data type + template operator Matx() const; + + //! change the matrix shape + template Matx<_Tp, m1, n1> reshape() const; + + //! extract part of the matrix + template Matx<_Tp, m1, n1> get_minor(int base_row, int base_col) const; + + //! extract the matrix row + Matx<_Tp, 1, n> row(int i) const; + + //! extract the matrix column + Matx<_Tp, m, 1> col(int i) const; + + //! extract the matrix diagonal + diag_type diag() const; + + //! transpose the matrix + Matx<_Tp, n, m> t() const; + + //! invert the matrix + Matx<_Tp, n, m> inv(int method=DECOMP_LU, bool *p_is_ok = NULL) const; + + //! solve linear system + template Matx<_Tp, n, l> solve(const Matx<_Tp, m, l>& rhs, int flags=DECOMP_LU) const; + Vec<_Tp, n> solve(const Vec<_Tp, m>& rhs, int method) const; + + //! multiply two matrices element-wise + Matx<_Tp, m, n> mul(const Matx<_Tp, m, n>& a) const; + + //! divide two matrices element-wise + Matx<_Tp, m, n> div(const Matx<_Tp, m, n>& a) const; + + //! element access + const _Tp& operator ()(int row, int col) const; + _Tp& operator ()(int row, int col); + + //! 1D element access + const _Tp& operator ()(int i) const; + _Tp& operator ()(int i); + + Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_AddOp); + Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_SubOp); + template Matx(const Matx<_Tp, m, n>& a, _T2 alpha, Matx_ScaleOp); + Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_MulOp); + Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_DivOp); + template Matx(const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b, Matx_MatMulOp); + Matx(const Matx<_Tp, n, m>& a, Matx_TOp); + + _Tp val[m*n]; ///< matrix elements +}; + +typedef Matx Matx12f; +typedef Matx Matx12d; +typedef Matx Matx13f; +typedef Matx Matx13d; +typedef Matx Matx14f; +typedef Matx Matx14d; +typedef Matx Matx16f; +typedef Matx Matx16d; + +typedef Matx Matx21f; +typedef Matx Matx21d; +typedef Matx Matx31f; +typedef Matx Matx31d; +typedef Matx Matx41f; +typedef Matx Matx41d; +typedef Matx Matx61f; +typedef Matx Matx61d; + +typedef Matx Matx22f; +typedef Matx Matx22d; +typedef Matx Matx23f; +typedef Matx Matx23d; +typedef Matx Matx32f; +typedef Matx Matx32d; + +typedef Matx Matx33f; +typedef Matx Matx33d; + +typedef Matx Matx34f; +typedef Matx Matx34d; +typedef Matx Matx43f; +typedef Matx Matx43d; + +typedef Matx Matx44f; +typedef Matx Matx44d; +typedef Matx Matx66f; +typedef Matx Matx66d; + +template static inline +double determinant(const Matx<_Tp, m, m>& a); + +template static inline +double trace(const Matx<_Tp, m, n>& a); + +template static inline +double norm(const Matx<_Tp, m, n>& M); + +template static inline +double norm(const Matx<_Tp, m, n>& M, int normType); + +template static inline +Matx<_Tp1, m, n>& operator += (Matx<_Tp1, m, n>& a, const Matx<_Tp2, m, n>& b); + +template static inline +Matx<_Tp1, m, n>& operator -= (Matx<_Tp1, m, n>& a, const Matx<_Tp2, m, n>& b); + +template static inline +Matx<_Tp, m, n> operator + (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b); + +template static inline +Matx<_Tp, m, n> operator - (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b); + +template static inline +Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, int alpha); + +template static inline +Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, float alpha); + +template static inline +Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, double alpha); + +template static inline +Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, int alpha); + +template static inline +Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, float alpha); + +template static inline +Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, double alpha); + +template static inline +Matx<_Tp, m, n> operator * (int alpha, const Matx<_Tp, m, n>& a); + +template static inline +Matx<_Tp, m, n> operator * (float alpha, const Matx<_Tp, m, n>& a); + +template static inline +Matx<_Tp, m, n> operator * (double alpha, const Matx<_Tp, m, n>& a); + +template static inline +Matx<_Tp, m, n>& operator /= (Matx<_Tp, m, n>& a, float alpha); + +template static inline +Matx<_Tp, m, n>& operator /= (Matx<_Tp, m, n>& a, double alpha); + +template static inline +Matx<_Tp, m, n> operator / (const Matx<_Tp, m, n>& a, float alpha); + +template static inline +Matx<_Tp, m, n> operator / (const Matx<_Tp, m, n>& a, double alpha); + +template static inline +Matx<_Tp, m, n> operator - (const Matx<_Tp, m, n>& a); + +template static inline +Matx<_Tp, m, n> operator * (const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b); + +template static inline +Vec<_Tp, m> operator * (const Matx<_Tp, m, n>& a, const Vec<_Tp, n>& b); + +template static inline +bool operator == (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b); + +template static inline +bool operator != (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b); + + +/////////////////////// Vec (used as element of multi-channel images ///////////////////// + +/** @brief Template class for short numerical vectors, a partial case of Matx + +This template class represents short numerical vectors (of 1, 2, 3, 4 ... elements) on which you +can perform basic arithmetical operations, access individual elements using [] operator etc. The +vectors are allocated on stack, as opposite to std::valarray, std::vector, cv::Mat etc., which +elements are dynamically allocated in the heap. + +The template takes 2 parameters: +@tparam _Tp element type +@tparam cn the number of elements + +In addition to the universal notation like Vec, you can use shorter aliases +for the most popular specialized variants of Vec, e.g. Vec3f ~ Vec. + +It is possible to convert Vec\ to/from Point_, Vec\ to/from Point3_ , and Vec\ +to CvScalar or Scalar_. Use operator[] to access the elements of Vec. + +All the expected vector operations are also implemented: +- v1 = v2 + v3 +- v1 = v2 - v3 +- v1 = v2 \* scale +- v1 = scale \* v2 +- v1 = -v2 +- v1 += v2 and other augmenting operations +- v1 == v2, v1 != v2 +- norm(v1) (euclidean norm) +The Vec class is commonly used to describe pixel types of multi-channel arrays. See Mat for details. +*/ +template class Vec : public Matx<_Tp, cn, 1> +{ +public: + typedef _Tp value_type; + enum { + channels = cn, +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + depth = Matx<_Tp, cn, 1>::depth, + type = CV_MAKETYPE(depth, channels), +#endif + _dummy_enum_finalizer = 0 + }; + + //! default constructor + Vec(); + + Vec(_Tp v0); //!< 1-element vector constructor + Vec(_Tp v0, _Tp v1); //!< 2-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2); //!< 3-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3); //!< 4-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4); //!< 5-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5); //!< 6-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6); //!< 7-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7); //!< 8-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8); //!< 9-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9); //!< 10-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11, _Tp v12, _Tp v13); //!< 14-element vector constructor + explicit Vec(const _Tp* values); + + Vec(std::initializer_list<_Tp>); + + Vec(const Vec<_Tp, cn>& v); + + static Vec all(_Tp alpha); + static Vec ones(); + static Vec randn(_Tp a, _Tp b); + static Vec randu(_Tp a, _Tp b); + static Vec zeros(); + static Vec diag(_Tp alpha) = delete; + static Vec eye() = delete; + + //! per-element multiplication + Vec mul(const Vec<_Tp, cn>& v) const; + + //! conjugation (makes sense for complex numbers and quaternions) + Vec conj() const; + + /*! + cross product of the two 3D vectors. + + For other dimensionalities the exception is raised + */ + Vec cross(const Vec& v) const; + //! conversion to another data type + template operator Vec() const; + + /*! element access */ + const _Tp& operator [](int i) const; + _Tp& operator[](int i); + const _Tp& operator ()(int i) const; + _Tp& operator ()(int i); + + Vec<_Tp, cn>& operator=(const Vec<_Tp, cn>& rhs) = default; + + Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_AddOp); + Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_SubOp); + template Vec(const Matx<_Tp, cn, 1>& a, _T2 alpha, Matx_ScaleOp); +}; + +/** @name Shorter aliases for the most popular specializations of Vec + @{ +*/ +typedef Vec Vec2b; +typedef Vec Vec3b; +typedef Vec Vec4b; + +typedef Vec Vec2s; +typedef Vec Vec3s; +typedef Vec Vec4s; + +typedef Vec Vec2w; +typedef Vec Vec3w; +typedef Vec Vec4w; + +typedef Vec Vec2i; +typedef Vec Vec3i; +typedef Vec Vec4i; +typedef Vec Vec6i; +typedef Vec Vec8i; + +typedef Vec Vec2f; +typedef Vec Vec3f; +typedef Vec Vec4f; +typedef Vec Vec6f; + +typedef Vec Vec2d; +typedef Vec Vec3d; +typedef Vec Vec4d; +typedef Vec Vec6d; +/** @} */ + +template inline +Vec<_Tp, cn> normalize(const Vec<_Tp, cn>& v); + +template static inline +Vec<_Tp1, cn>& operator += (Vec<_Tp1, cn>& a, const Vec<_Tp2, cn>& b); + +template static inline +Vec<_Tp1, cn>& operator -= (Vec<_Tp1, cn>& a, const Vec<_Tp2, cn>& b); + +template static inline +Vec<_Tp, cn> operator + (const Vec<_Tp, cn>& a, const Vec<_Tp, cn>& b); + +template static inline +Vec<_Tp, cn> operator - (const Vec<_Tp, cn>& a, const Vec<_Tp, cn>& b); + +template static inline +Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, int alpha); + +template static inline +Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, float alpha); + +template static inline +Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, double alpha); + +template static inline +Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, int alpha); + +template static inline +Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, float alpha); + +template static inline +Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, double alpha); + +template static inline +Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, int alpha); + +template static inline +Vec<_Tp, cn> operator * (int alpha, const Vec<_Tp, cn>& a); + +template static inline +Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, float alpha); + +template static inline +Vec<_Tp, cn> operator * (float alpha, const Vec<_Tp, cn>& a); + +template static inline +Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, double alpha); + +template static inline +Vec<_Tp, cn> operator * (double alpha, const Vec<_Tp, cn>& a); + +template static inline +Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, int alpha); + +template static inline +Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, float alpha); + +template static inline +Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, double alpha); + +template static inline +Vec<_Tp, cn> operator - (const Vec<_Tp, cn>& a); + +template inline +Vec<_Tp, 4> operator * (const Vec<_Tp, 4>& v1, const Vec<_Tp, 4>& v2); + +template inline +Vec<_Tp, 4>& operator *= (Vec<_Tp, 4>& v1, const Vec<_Tp, 4>& v2); + +//! @} core_basic + +} // cv + +#include "opencv2/core/matx.inl.hpp" + +#endif // OPENCV_CORE_MATX_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/matx.inl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/matx.inl.hpp index faa3e749d6..8b5b28087d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/matx.inl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/matx.inl.hpp @@ -1,1115 +1,1115 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_MATX_INL_HPP -#define OPENCV_CORE_MATX_INL_HPP - -#ifndef __cplusplus -# error matx.inl.hpp header must be compiled as C++ -#endif - -#include "opencv2/core/matx.hpp" - -namespace cv -{ - -//============================================================================== -// Helpers - -namespace internal -{ - -template struct Matx_DetOp -{ - double operator ()(const Matx<_Tp, m, m>& a) const - { - Matx<_Tp, m, m> temp = a; - double p = LU(temp.val, m*sizeof(_Tp), m, 0, 0, 0); - if( p == 0 ) - return p; - for( int i = 0; i < m; i++ ) - p *= temp(i, i); - return p; - } -}; - -template struct Matx_DetOp<_Tp, 1> -{ - double operator ()(const Matx<_Tp, 1, 1>& a) const - { - return a(0,0); - } -}; - -template struct Matx_DetOp<_Tp, 2> -{ - double operator ()(const Matx<_Tp, 2, 2>& a) const - { - return a(0,0)*a(1,1) - a(0,1)*a(1,0); - } -}; - -template struct Matx_DetOp<_Tp, 3> -{ - double operator ()(const Matx<_Tp, 3, 3>& a) const - { - return a(0,0)*(a(1,1)*a(2,2) - a(2,1)*a(1,2)) - - a(0,1)*(a(1,0)*a(2,2) - a(2,0)*a(1,2)) + - a(0,2)*(a(1,0)*a(2,1) - a(2,0)*a(1,1)); - } -}; - -template Vec<_Tp, 2> inline conjugate(const Vec<_Tp, 2>& v) -{ - return Vec<_Tp, 2>(v[0], -v[1]); -} - -template Vec<_Tp, 4> inline conjugate(const Vec<_Tp, 4>& v) -{ - return Vec<_Tp, 4>(v[0], -v[1], -v[2], -v[3]); -} - -} // internal:: - - -//============================================================================== -// Matx - -template class DataType< Matx<_Tp, m, n> > -{ -public: - typedef Matx<_Tp, m, n> value_type; - typedef Matx::work_type, m, n> work_type; - typedef _Tp channel_type; - typedef value_type vec_type; - - enum { generic_type = 0, - channels = m * n, - fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - ,depth = DataType::depth - ,type = CV_MAKETYPE(depth, channels) -#endif - }; -}; - - -namespace traits { -template -struct Depth< Matx<_Tp, m, n> > { enum { value = Depth<_Tp>::value }; }; -template -struct Type< Matx<_Tp, m, n> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, n*m) }; }; -} // namespace - - -//! @brief Comma-separated Matrix Initializer -template class MatxCommaInitializer -{ -public: - MatxCommaInitializer(Matx<_Tp, m, n>* _mtx); - template MatxCommaInitializer<_Tp, m, n>& operator , (T2 val); - Matx<_Tp, m, n> operator *() const; - - Matx<_Tp, m, n>* dst; - int idx; -}; - -template static inline -MatxCommaInitializer<_Tp, m, n> operator << (const Matx<_Tp, m, n>& mtx, _T2 val) -{ - MatxCommaInitializer<_Tp, m, n> commaInitializer((Matx<_Tp, m, n>*)&mtx); - return (commaInitializer, val); -} - -template inline -MatxCommaInitializer<_Tp, m, n>::MatxCommaInitializer(Matx<_Tp, m, n>* _mtx) - : dst(_mtx), idx(0) -{} - -template template inline -MatxCommaInitializer<_Tp, m, n>& MatxCommaInitializer<_Tp, m, n>::operator , (_T2 value) -{ - CV_DbgAssert( idx < m*n ); - dst->val[idx++] = saturate_cast<_Tp>(value); - return *this; -} - -template inline -Matx<_Tp, m, n> MatxCommaInitializer<_Tp, m, n>::operator *() const -{ - CV_DbgAssert( idx == n*m ); - return *dst; -} - -////////////////////////////////// Matx Implementation /////////////////////////////////// - -template inline -Matx<_Tp, m, n>::Matx() -{ - for(int i = 0; i < channels; i++) val[i] = _Tp(0); -} - -template inline -Matx<_Tp, m, n>::Matx(_Tp v0) -{ - val[0] = v0; - for(int i = 1; i < channels; i++) val[i] = _Tp(0); -} - -template inline -Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1) -{ - CV_StaticAssert(channels >= 2, "Matx should have at least 2 elements."); - val[0] = v0; val[1] = v1; - for(int i = 2; i < channels; i++) val[i] = _Tp(0); -} - -template inline -Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2) -{ - CV_StaticAssert(channels >= 3, "Matx should have at least 3 elements."); - val[0] = v0; val[1] = v1; val[2] = v2; - for(int i = 3; i < channels; i++) val[i] = _Tp(0); -} - -template inline -Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3) -{ - CV_StaticAssert(channels >= 4, "Matx should have at least 4 elements."); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - for(int i = 4; i < channels; i++) val[i] = _Tp(0); -} - -template inline -Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4) -{ - CV_StaticAssert(channels >= 5, "Matx should have at least 5 elements."); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; val[4] = v4; - for(int i = 5; i < channels; i++) val[i] = _Tp(0); -} - -template inline -Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5) -{ - CV_StaticAssert(channels >= 6, "Matx should have at least 6 elements."); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - val[4] = v4; val[5] = v5; - for(int i = 6; i < channels; i++) val[i] = _Tp(0); -} - -template inline -Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6) -{ - CV_StaticAssert(channels >= 7, "Matx should have at least 7 elements."); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - val[4] = v4; val[5] = v5; val[6] = v6; - for(int i = 7; i < channels; i++) val[i] = _Tp(0); -} - -template inline -Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7) -{ - CV_StaticAssert(channels >= 8, "Matx should have at least 8 elements."); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; - for(int i = 8; i < channels; i++) val[i] = _Tp(0); -} - -template inline -Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8) -{ - CV_StaticAssert(channels >= 9, "Matx should have at least 9 elements."); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; - val[8] = v8; - for(int i = 9; i < channels; i++) val[i] = _Tp(0); -} - -template inline -Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9) -{ - CV_StaticAssert(channels >= 10, "Matx should have at least 10 elements."); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; - val[8] = v8; val[9] = v9; - for(int i = 10; i < channels; i++) val[i] = _Tp(0); -} - - -template inline -Matx<_Tp,m,n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11) -{ - CV_StaticAssert(channels >= 12, "Matx should have at least 12 elements."); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; - val[8] = v8; val[9] = v9; val[10] = v10; val[11] = v11; - for(int i = 12; i < channels; i++) val[i] = _Tp(0); -} - -template inline -Matx<_Tp,m,n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11, _Tp v12, _Tp v13) -{ - CV_StaticAssert(channels >= 14, "Matx should have at least 14 elements."); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; - val[8] = v8; val[9] = v9; val[10] = v10; val[11] = v11; - val[12] = v12; val[13] = v13; - for (int i = 14; i < channels; i++) val[i] = _Tp(0); -} - - -template inline -Matx<_Tp,m,n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11, _Tp v12, _Tp v13, _Tp v14, _Tp v15) -{ - CV_StaticAssert(channels >= 16, "Matx should have at least 16 elements."); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; - val[8] = v8; val[9] = v9; val[10] = v10; val[11] = v11; - val[12] = v12; val[13] = v13; val[14] = v14; val[15] = v15; - for(int i = 16; i < channels; i++) val[i] = _Tp(0); -} - -// WARNING: unreachable code using Ninja -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(push) -#pragma warning(disable: 4702) -#endif -template inline -Matx<_Tp, m, n>::Matx(const _Tp* values) -{ - for( int i = 0; i < channels; i++ ) val[i] = values[i]; -} -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(pop) -#endif - -template inline -Matx<_Tp, m, n>::Matx(std::initializer_list<_Tp> list) -{ - CV_DbgAssert(list.size() == channels); - int i = 0; - for(const auto& elem : list) - { - val[i++] = elem; - } -} - -template inline -Matx<_Tp, m, n> Matx<_Tp, m, n>::all(_Tp alpha) -{ - Matx<_Tp, m, n> M; - for( int i = 0; i < m*n; i++ ) M.val[i] = alpha; - return M; -} - -template inline -Matx<_Tp,m,n> Matx<_Tp,m,n>::zeros() -{ - return all(0); -} - -template inline -Matx<_Tp,m,n> Matx<_Tp,m,n>::ones() -{ - return all(1); -} - -template inline -Matx<_Tp,m,n> Matx<_Tp,m,n>::eye() -{ - Matx<_Tp,m,n> M; - for(int i = 0; i < shortdim; i++) - M(i,i) = 1; - return M; -} - -template inline -_Tp Matx<_Tp, m, n>::dot(const Matx<_Tp, m, n>& M) const -{ - _Tp s = 0; - for( int i = 0; i < channels; i++ ) s += val[i]*M.val[i]; - return s; -} - -template inline -double Matx<_Tp, m, n>::ddot(const Matx<_Tp, m, n>& M) const -{ - double s = 0; - for( int i = 0; i < channels; i++ ) s += (double)val[i]*M.val[i]; - return s; -} - -template inline -Matx<_Tp,m,n> Matx<_Tp,m,n>::diag(const typename Matx<_Tp,m,n>::diag_type& d) -{ - Matx<_Tp,m,n> M; - for(int i = 0; i < shortdim; i++) - M(i,i) = d(i, 0); - return M; -} - -template template -inline Matx<_Tp, m, n>::operator Matx() const -{ - Matx M; - for( int i = 0; i < m*n; i++ ) M.val[i] = saturate_cast(val[i]); - return M; -} - -template template inline -Matx<_Tp, m1, n1> Matx<_Tp, m, n>::reshape() const -{ - CV_StaticAssert(m1*n1 == m*n, "Input and destination matrices must have the same number of elements"); - return (const Matx<_Tp, m1, n1>&)*this; -} - -template -template inline -Matx<_Tp, m1, n1> Matx<_Tp, m, n>::get_minor(int base_row, int base_col) const -{ - CV_DbgAssert(0 <= base_row && base_row+m1 <= m && 0 <= base_col && base_col+n1 <= n); - Matx<_Tp, m1, n1> s; - for( int di = 0; di < m1; di++ ) - for( int dj = 0; dj < n1; dj++ ) - s(di, dj) = (*this)(base_row+di, base_col+dj); - return s; -} - -template inline -Matx<_Tp, 1, n> Matx<_Tp, m, n>::row(int i) const -{ - CV_DbgAssert((unsigned)i < (unsigned)m); - return Matx<_Tp, 1, n>(&val[i*n]); -} - -template inline -Matx<_Tp, m, 1> Matx<_Tp, m, n>::col(int j) const -{ - CV_DbgAssert((unsigned)j < (unsigned)n); - Matx<_Tp, m, 1> v; - for( int i = 0; i < m; i++ ) - v.val[i] = val[i*n + j]; - return v; -} - -template inline -typename Matx<_Tp, m, n>::diag_type Matx<_Tp, m, n>::diag() const -{ - diag_type d; - for( int i = 0; i < shortdim; i++ ) - d.val[i] = val[i*n + i]; - return d; -} - -template inline -const _Tp& Matx<_Tp, m, n>::operator()(int row_idx, int col_idx) const -{ - CV_DbgAssert( (unsigned)row_idx < (unsigned)m && (unsigned)col_idx < (unsigned)n ); - return this->val[row_idx*n + col_idx]; -} - -template inline -_Tp& Matx<_Tp, m, n>::operator ()(int row_idx, int col_idx) -{ - CV_DbgAssert( (unsigned)row_idx < (unsigned)m && (unsigned)col_idx < (unsigned)n ); - return val[row_idx*n + col_idx]; -} - -template inline -const _Tp& Matx<_Tp, m, n>::operator ()(int i) const -{ - CV_StaticAssert(m == 1 || n == 1, "Single index indexation requires matrix to be a column or a row"); - CV_DbgAssert( (unsigned)i < (unsigned)(m+n-1) ); - return val[i]; -} - -template inline -_Tp& Matx<_Tp, m, n>::operator ()(int i) -{ - CV_StaticAssert(m == 1 || n == 1, "Single index indexation requires matrix to be a column or a row"); - CV_DbgAssert( (unsigned)i < (unsigned)(m+n-1) ); - return val[i]; -} - -template inline -Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_AddOp) -{ - for( int i = 0; i < channels; i++ ) - val[i] = saturate_cast<_Tp>(a.val[i] + b.val[i]); -} - -template inline -Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_SubOp) -{ - for( int i = 0; i < channels; i++ ) - val[i] = saturate_cast<_Tp>(a.val[i] - b.val[i]); -} - -template template inline -Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, _T2 alpha, Matx_ScaleOp) -{ - for( int i = 0; i < channels; i++ ) - val[i] = saturate_cast<_Tp>(a.val[i] * alpha); -} - -template inline -Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_MulOp) -{ - for( int i = 0; i < channels; i++ ) - val[i] = saturate_cast<_Tp>(a.val[i] * b.val[i]); -} - -template inline -Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_DivOp) -{ - for( int i = 0; i < channels; i++ ) - val[i] = saturate_cast<_Tp>(a.val[i] / b.val[i]); -} - -template template inline -Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b, Matx_MatMulOp) -{ - for( int i = 0; i < m; i++ ) - for( int j = 0; j < n; j++ ) - { - _Tp s = 0; - for( int k = 0; k < l; k++ ) - s += a(i, k) * b(k, j); - val[i*n + j] = s; - } -} - -template inline -Matx<_Tp,m,n>::Matx(const Matx<_Tp, n, m>& a, Matx_TOp) -{ - for( int i = 0; i < m; i++ ) - for( int j = 0; j < n; j++ ) - val[i*n + j] = a(j, i); -} - -template inline -Matx<_Tp, m, n> Matx<_Tp, m, n>::mul(const Matx<_Tp, m, n>& a) const -{ - return Matx<_Tp, m, n>(*this, a, Matx_MulOp()); -} - -template inline -Matx<_Tp, m, n> Matx<_Tp, m, n>::div(const Matx<_Tp, m, n>& a) const -{ - return Matx<_Tp, m, n>(*this, a, Matx_DivOp()); -} - -template inline -Matx<_Tp, n, m> Matx<_Tp, m, n>::t() const -{ - return Matx<_Tp, n, m>(*this, Matx_TOp()); -} - -template inline -Vec<_Tp, n> Matx<_Tp, m, n>::solve(const Vec<_Tp, m>& rhs, int method) const -{ - Matx<_Tp, n, 1> x = solve((const Matx<_Tp, m, 1>&)(rhs), method); - return (Vec<_Tp, n>&)(x); -} - -template static inline -double determinant(const Matx<_Tp, m, m>& a) -{ - return cv::internal::Matx_DetOp<_Tp, m>()(a); -} - -template static inline -double trace(const Matx<_Tp, m, n>& a) -{ - _Tp s = 0; - for( int i = 0; i < std::min(m, n); i++ ) - s += a(i,i); - return s; -} - -template static inline -double norm(const Matx<_Tp, m, n>& M) -{ - return std::sqrt(normL2Sqr<_Tp, double>(M.val, m*n)); -} - -template static inline -double norm(const Matx<_Tp, m, n>& M, int normType) -{ - switch(normType) { - case NORM_INF: - return (double)normInf<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n); - case NORM_L1: - return (double)normL1<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n); - case NORM_L2SQR: - return (double)normL2Sqr<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n); - default: - case NORM_L2: - return std::sqrt((double)normL2Sqr<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n)); - } -} - -template static inline -Matx<_Tp1, m, n>& operator += (Matx<_Tp1, m, n>& a, const Matx<_Tp2, m, n>& b) -{ - for( int i = 0; i < m*n; i++ ) - a.val[i] = saturate_cast<_Tp1>(a.val[i] + b.val[i]); - return a; -} - -template static inline -Matx<_Tp1, m, n>& operator -= (Matx<_Tp1, m, n>& a, const Matx<_Tp2, m, n>& b) -{ - for( int i = 0; i < m*n; i++ ) - a.val[i] = saturate_cast<_Tp1>(a.val[i] - b.val[i]); - return a; -} - -template static inline -Matx<_Tp, m, n> operator + (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) -{ - return Matx<_Tp, m, n>(a, b, Matx_AddOp()); -} - -template static inline -Matx<_Tp, m, n> operator - (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) -{ - return Matx<_Tp, m, n>(a, b, Matx_SubOp()); -} - -template static inline -Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, int alpha) -{ - for( int i = 0; i < m*n; i++ ) - a.val[i] = saturate_cast<_Tp>(a.val[i] * alpha); - return a; -} - -template static inline -Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, float alpha) -{ - for( int i = 0; i < m*n; i++ ) - a.val[i] = saturate_cast<_Tp>(a.val[i] * alpha); - return a; -} - -template static inline -Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, double alpha) -{ - for( int i = 0; i < m*n; i++ ) - a.val[i] = saturate_cast<_Tp>(a.val[i] * alpha); - return a; -} - -template static inline -Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, int alpha) -{ - return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, float alpha) -{ - return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, double alpha) -{ - return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Matx<_Tp, m, n> operator * (int alpha, const Matx<_Tp, m, n>& a) -{ - return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Matx<_Tp, m, n> operator * (float alpha, const Matx<_Tp, m, n>& a) -{ - return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Matx<_Tp, m, n> operator * (double alpha, const Matx<_Tp, m, n>& a) -{ - return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Matx<_Tp, m, n>& operator /= (Matx<_Tp, m, n>& a, float alpha) -{ - for( int i = 0; i < m*n; i++ ) - a.val[i] = a.val[i] / alpha; - return a; -} - -template static inline -Matx<_Tp, m, n>& operator /= (Matx<_Tp, m, n>& a, double alpha) -{ - for( int i = 0; i < m*n; i++ ) - a.val[i] = a.val[i] / alpha; - return a; -} - -template static inline -Matx<_Tp, m, n> operator / (const Matx<_Tp, m, n>& a, float alpha) -{ - return Matx<_Tp, m, n>(a, 1.f/alpha, Matx_ScaleOp()); -} - -template static inline -Matx<_Tp, m, n> operator / (const Matx<_Tp, m, n>& a, double alpha) -{ - return Matx<_Tp, m, n>(a, 1./alpha, Matx_ScaleOp()); -} - -template static inline -Matx<_Tp, m, n> operator - (const Matx<_Tp, m, n>& a) -{ - return Matx<_Tp, m, n>(a, -1, Matx_ScaleOp()); -} - -template static inline -Matx<_Tp, m, n> operator * (const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b) -{ - return Matx<_Tp, m, n>(a, b, Matx_MatMulOp()); -} - -template static inline -Vec<_Tp, m> operator * (const Matx<_Tp, m, n>& a, const Vec<_Tp, n>& b) -{ - Matx<_Tp, m, 1> c(a, b, Matx_MatMulOp()); - return (const Vec<_Tp, m>&)(c); -} - -template static inline -bool operator == (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) -{ - for( int i = 0; i < m*n; i++ ) - if( a.val[i] != b.val[i] ) return false; - return true; -} - -template static inline -bool operator != (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) -{ - return !(a == b); -} - -//============================================================================== -// Vec - -template class DataType< Vec<_Tp, cn> > -{ -public: - typedef Vec<_Tp, cn> value_type; - typedef Vec::work_type, cn> work_type; - typedef _Tp channel_type; - typedef value_type vec_type; - - enum { generic_type = 0, - channels = cn, - fmt = DataType::fmt + ((channels - 1) << 8), -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - depth = DataType::depth, - type = CV_MAKETYPE(depth, channels), -#endif - _dummy_enum_finalizer = 0 - }; -}; - -namespace traits { -template -struct Depth< Vec<_Tp, cn> > { enum { value = Depth<_Tp>::value }; }; -template -struct Type< Vec<_Tp, cn> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, cn) }; }; -} // namespace - -/** @brief Comma-separated Vec Initializer -*/ -template class VecCommaInitializer : public MatxCommaInitializer<_Tp, m, 1> -{ -public: - VecCommaInitializer(Vec<_Tp, m>* _vec); - template VecCommaInitializer<_Tp, m>& operator , (T2 val); - Vec<_Tp, m> operator *() const; -}; - -template static inline -VecCommaInitializer<_Tp, cn> operator << (const Vec<_Tp, cn>& vec, _T2 val) -{ - VecCommaInitializer<_Tp, cn> commaInitializer((Vec<_Tp, cn>*)&vec); - return (commaInitializer, val); -} - -template inline -VecCommaInitializer<_Tp, cn>::VecCommaInitializer(Vec<_Tp, cn>* _vec) - : MatxCommaInitializer<_Tp, cn, 1>(_vec) -{} - -template template inline -VecCommaInitializer<_Tp, cn>& VecCommaInitializer<_Tp, cn>::operator , (_T2 value) -{ - CV_DbgAssert( this->idx < cn ); - this->dst->val[this->idx++] = saturate_cast<_Tp>(value); - return *this; -} - -template inline -Vec<_Tp, cn> VecCommaInitializer<_Tp, cn>::operator *() const -{ - CV_DbgAssert( this->idx == cn ); - return *this->dst; -} - - -template inline -Vec<_Tp, cn>::Vec() {} - -template inline -Vec<_Tp, cn>::Vec(_Tp v0) - : Matx<_Tp, cn, 1>(v0) {} - -template inline -Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1) - : Matx<_Tp, cn, 1>(v0, v1) {} - -template inline -Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2) - : Matx<_Tp, cn, 1>(v0, v1, v2) {} - -template inline -Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3) - : Matx<_Tp, cn, 1>(v0, v1, v2, v3) {} - -template inline -Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4) - : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4) {} - -template inline -Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5) - : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5) {} - -template inline -Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6) - : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6) {} - -template inline -Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7) - : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6, v7) {} - -template inline -Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8) - : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6, v7, v8) {} - -template inline -Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9) - : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {} - -template inline -Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11, _Tp v12, _Tp v13) - : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) {} - -template inline -Vec<_Tp, cn>::Vec(const _Tp* values) - : Matx<_Tp, cn, 1>(values) {} - -template inline -Vec<_Tp, cn>::Vec(std::initializer_list<_Tp> list) - : Matx<_Tp, cn, 1>(list) {} - -template inline -Vec<_Tp, cn>::Vec(const Vec<_Tp, cn>& m) - : Matx<_Tp, cn, 1>(m.val) {} - -template inline -Vec<_Tp, cn>::Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_AddOp op) - : Matx<_Tp, cn, 1>(a, b, op) {} - -template inline -Vec<_Tp, cn>::Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_SubOp op) - : Matx<_Tp, cn, 1>(a, b, op) {} - -template template inline -Vec<_Tp, cn>::Vec(const Matx<_Tp, cn, 1>& a, _T2 alpha, Matx_ScaleOp op) - : Matx<_Tp, cn, 1>(a, alpha, op) {} - -template inline -Vec<_Tp, cn> Vec<_Tp, cn>::all(_Tp alpha) -{ - Vec v; - for( int i = 0; i < cn; i++ ) v.val[i] = alpha; - return v; -} - -template inline -Vec<_Tp, cn> Vec<_Tp, cn>::ones() -{ - return Vec::all(1); -} - -template inline -Vec<_Tp, cn> Vec<_Tp, cn>::zeros() -{ - return Vec::all(0); -} - -template inline -Vec<_Tp, cn> Vec<_Tp, cn>::mul(const Vec<_Tp, cn>& v) const -{ - Vec<_Tp, cn> w; - for( int i = 0; i < cn; i++ ) w.val[i] = saturate_cast<_Tp>(this->val[i]*v.val[i]); - return w; -} - -template<> inline -Vec Vec::conj() const -{ - return cv::internal::conjugate(*this); -} - -template<> inline -Vec Vec::conj() const -{ - return cv::internal::conjugate(*this); -} - -template<> inline -Vec Vec::conj() const -{ - return cv::internal::conjugate(*this); -} - -template<> inline -Vec Vec::conj() const -{ - return cv::internal::conjugate(*this); -} - -template inline -Vec<_Tp, cn> Vec<_Tp, cn>::cross(const Vec<_Tp, cn>&) const -{ - CV_StaticAssert(cn == 3, "for arbitrary-size vector there is no cross-product defined"); - return Vec<_Tp, cn>(); -} - -template<> inline -Vec Vec::cross(const Vec& v) const -{ - return Vec(this->val[1]*v.val[2] - this->val[2]*v.val[1], - this->val[2]*v.val[0] - this->val[0]*v.val[2], - this->val[0]*v.val[1] - this->val[1]*v.val[0]); -} - -template<> inline -Vec Vec::cross(const Vec& v) const -{ - return Vec(this->val[1]*v.val[2] - this->val[2]*v.val[1], - this->val[2]*v.val[0] - this->val[0]*v.val[2], - this->val[0]*v.val[1] - this->val[1]*v.val[0]); -} - -template template inline -Vec<_Tp, cn>::operator Vec() const -{ - Vec v; - for( int i = 0; i < cn; i++ ) v.val[i] = saturate_cast(this->val[i]); - return v; -} - -template inline -const _Tp& Vec<_Tp, cn>::operator [](int i) const -{ - CV_DbgAssert( (unsigned)i < (unsigned)cn ); - return this->val[i]; -} - -template inline -_Tp& Vec<_Tp, cn>::operator [](int i) -{ - CV_DbgAssert( (unsigned)i < (unsigned)cn ); - return this->val[i]; -} - -template inline -const _Tp& Vec<_Tp, cn>::operator ()(int i) const -{ - CV_DbgAssert( (unsigned)i < (unsigned)cn ); - return this->val[i]; -} - -template inline -_Tp& Vec<_Tp, cn>::operator ()(int i) -{ - CV_DbgAssert( (unsigned)i < (unsigned)cn ); - return this->val[i]; -} - -template inline -Vec<_Tp, cn> normalize(const Vec<_Tp, cn>& v) -{ - double nv = norm(v); - return v * (nv ? 1./nv : 0.); -} - -template static inline -Vec<_Tp1, cn>& operator += (Vec<_Tp1, cn>& a, const Vec<_Tp2, cn>& b) -{ - for( int i = 0; i < cn; i++ ) - a.val[i] = saturate_cast<_Tp1>(a.val[i] + b.val[i]); - return a; -} - -template static inline -Vec<_Tp1, cn>& operator -= (Vec<_Tp1, cn>& a, const Vec<_Tp2, cn>& b) -{ - for( int i = 0; i < cn; i++ ) - a.val[i] = saturate_cast<_Tp1>(a.val[i] - b.val[i]); - return a; -} - -template static inline -Vec<_Tp, cn> operator + (const Vec<_Tp, cn>& a, const Vec<_Tp, cn>& b) -{ - return Vec<_Tp, cn>(a, b, Matx_AddOp()); -} - -template static inline -Vec<_Tp, cn> operator - (const Vec<_Tp, cn>& a, const Vec<_Tp, cn>& b) -{ - return Vec<_Tp, cn>(a, b, Matx_SubOp()); -} - -template static inline -Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, int alpha) -{ - for( int i = 0; i < cn; i++ ) - a[i] = saturate_cast<_Tp>(a[i]*alpha); - return a; -} - -template static inline -Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, float alpha) -{ - for( int i = 0; i < cn; i++ ) - a[i] = saturate_cast<_Tp>(a[i]*alpha); - return a; -} - -template static inline -Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, double alpha) -{ - for( int i = 0; i < cn; i++ ) - a[i] = saturate_cast<_Tp>(a[i]*alpha); - return a; -} - -template static inline -Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, int alpha) -{ - double ialpha = 1./alpha; - for( int i = 0; i < cn; i++ ) - a[i] = saturate_cast<_Tp>(a[i]*ialpha); - return a; -} - -template static inline -Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, float alpha) -{ - float ialpha = 1.f/alpha; - for( int i = 0; i < cn; i++ ) - a[i] = saturate_cast<_Tp>(a[i]*ialpha); - return a; -} - -template static inline -Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, double alpha) -{ - double ialpha = 1./alpha; - for( int i = 0; i < cn; i++ ) - a[i] = saturate_cast<_Tp>(a[i]*ialpha); - return a; -} - -template static inline -Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, int alpha) -{ - return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Vec<_Tp, cn> operator * (int alpha, const Vec<_Tp, cn>& a) -{ - return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, float alpha) -{ - return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Vec<_Tp, cn> operator * (float alpha, const Vec<_Tp, cn>& a) -{ - return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, double alpha) -{ - return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Vec<_Tp, cn> operator * (double alpha, const Vec<_Tp, cn>& a) -{ - return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, int alpha) -{ - return Vec<_Tp, cn>(a, 1./alpha, Matx_ScaleOp()); -} - -template static inline -Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, float alpha) -{ - return Vec<_Tp, cn>(a, 1.f/alpha, Matx_ScaleOp()); -} - -template static inline -Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, double alpha) -{ - return Vec<_Tp, cn>(a, 1./alpha, Matx_ScaleOp()); -} - -template static inline -Vec<_Tp, cn> operator - (const Vec<_Tp, cn>& a) -{ - Vec<_Tp,cn> t; - for( int i = 0; i < cn; i++ ) t.val[i] = saturate_cast<_Tp>(-a.val[i]); - return t; -} - -template inline Vec<_Tp, 4> operator * (const Vec<_Tp, 4>& v1, const Vec<_Tp, 4>& v2) -{ - return Vec<_Tp, 4>(saturate_cast<_Tp>(v1[0]*v2[0] - v1[1]*v2[1] - v1[2]*v2[2] - v1[3]*v2[3]), - saturate_cast<_Tp>(v1[0]*v2[1] + v1[1]*v2[0] + v1[2]*v2[3] - v1[3]*v2[2]), - saturate_cast<_Tp>(v1[0]*v2[2] - v1[1]*v2[3] + v1[2]*v2[0] + v1[3]*v2[1]), - saturate_cast<_Tp>(v1[0]*v2[3] + v1[1]*v2[2] - v1[2]*v2[1] + v1[3]*v2[0])); -} - -template inline Vec<_Tp, 4>& operator *= (Vec<_Tp, 4>& v1, const Vec<_Tp, 4>& v2) -{ - v1 = v1 * v2; - return v1; -} - -} // cv:: - -#endif // OPENCV_CORE_MATX_INL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_MATX_INL_HPP +#define OPENCV_CORE_MATX_INL_HPP + +#ifndef __cplusplus +# error matx.inl.hpp header must be compiled as C++ +#endif + +#include "opencv2/core/matx.hpp" + +namespace cv +{ + +//============================================================================== +// Helpers + +namespace internal +{ + +template struct Matx_DetOp +{ + double operator ()(const Matx<_Tp, m, m>& a) const + { + Matx<_Tp, m, m> temp = a; + double p = LU(temp.val, m*sizeof(_Tp), m, 0, 0, 0); + if( p == 0 ) + return p; + for( int i = 0; i < m; i++ ) + p *= temp(i, i); + return p; + } +}; + +template struct Matx_DetOp<_Tp, 1> +{ + double operator ()(const Matx<_Tp, 1, 1>& a) const + { + return a(0,0); + } +}; + +template struct Matx_DetOp<_Tp, 2> +{ + double operator ()(const Matx<_Tp, 2, 2>& a) const + { + return a(0,0)*a(1,1) - a(0,1)*a(1,0); + } +}; + +template struct Matx_DetOp<_Tp, 3> +{ + double operator ()(const Matx<_Tp, 3, 3>& a) const + { + return a(0,0)*(a(1,1)*a(2,2) - a(2,1)*a(1,2)) - + a(0,1)*(a(1,0)*a(2,2) - a(2,0)*a(1,2)) + + a(0,2)*(a(1,0)*a(2,1) - a(2,0)*a(1,1)); + } +}; + +template Vec<_Tp, 2> inline conjugate(const Vec<_Tp, 2>& v) +{ + return Vec<_Tp, 2>(v[0], -v[1]); +} + +template Vec<_Tp, 4> inline conjugate(const Vec<_Tp, 4>& v) +{ + return Vec<_Tp, 4>(v[0], -v[1], -v[2], -v[3]); +} + +} // internal:: + + +//============================================================================== +// Matx + +template class DataType< Matx<_Tp, m, n> > +{ +public: + typedef Matx<_Tp, m, n> value_type; + typedef Matx::work_type, m, n> work_type; + typedef _Tp channel_type; + typedef value_type vec_type; + + enum { generic_type = 0, + channels = m * n, + fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + ,depth = DataType::depth + ,type = CV_MAKETYPE(depth, channels) +#endif + }; +}; + + +namespace traits { +template +struct Depth< Matx<_Tp, m, n> > { enum { value = Depth<_Tp>::value }; }; +template +struct Type< Matx<_Tp, m, n> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, n*m) }; }; +} // namespace + + +//! @brief Comma-separated Matrix Initializer +template class MatxCommaInitializer +{ +public: + MatxCommaInitializer(Matx<_Tp, m, n>* _mtx); + template MatxCommaInitializer<_Tp, m, n>& operator , (T2 val); + Matx<_Tp, m, n> operator *() const; + + Matx<_Tp, m, n>* dst; + int idx; +}; + +template static inline +MatxCommaInitializer<_Tp, m, n> operator << (const Matx<_Tp, m, n>& mtx, _T2 val) +{ + MatxCommaInitializer<_Tp, m, n> commaInitializer((Matx<_Tp, m, n>*)&mtx); + return (commaInitializer, val); +} + +template inline +MatxCommaInitializer<_Tp, m, n>::MatxCommaInitializer(Matx<_Tp, m, n>* _mtx) + : dst(_mtx), idx(0) +{} + +template template inline +MatxCommaInitializer<_Tp, m, n>& MatxCommaInitializer<_Tp, m, n>::operator , (_T2 value) +{ + CV_DbgAssert( idx < m*n ); + dst->val[idx++] = saturate_cast<_Tp>(value); + return *this; +} + +template inline +Matx<_Tp, m, n> MatxCommaInitializer<_Tp, m, n>::operator *() const +{ + CV_DbgAssert( idx == n*m ); + return *dst; +} + +////////////////////////////////// Matx Implementation /////////////////////////////////// + +template inline +Matx<_Tp, m, n>::Matx() +{ + for(int i = 0; i < channels; i++) val[i] = _Tp(0); +} + +template inline +Matx<_Tp, m, n>::Matx(_Tp v0) +{ + val[0] = v0; + for(int i = 1; i < channels; i++) val[i] = _Tp(0); +} + +template inline +Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1) +{ + CV_StaticAssert(channels >= 2, "Matx should have at least 2 elements."); + val[0] = v0; val[1] = v1; + for(int i = 2; i < channels; i++) val[i] = _Tp(0); +} + +template inline +Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2) +{ + CV_StaticAssert(channels >= 3, "Matx should have at least 3 elements."); + val[0] = v0; val[1] = v1; val[2] = v2; + for(int i = 3; i < channels; i++) val[i] = _Tp(0); +} + +template inline +Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3) +{ + CV_StaticAssert(channels >= 4, "Matx should have at least 4 elements."); + val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; + for(int i = 4; i < channels; i++) val[i] = _Tp(0); +} + +template inline +Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4) +{ + CV_StaticAssert(channels >= 5, "Matx should have at least 5 elements."); + val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; val[4] = v4; + for(int i = 5; i < channels; i++) val[i] = _Tp(0); +} + +template inline +Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5) +{ + CV_StaticAssert(channels >= 6, "Matx should have at least 6 elements."); + val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; + val[4] = v4; val[5] = v5; + for(int i = 6; i < channels; i++) val[i] = _Tp(0); +} + +template inline +Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6) +{ + CV_StaticAssert(channels >= 7, "Matx should have at least 7 elements."); + val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; + val[4] = v4; val[5] = v5; val[6] = v6; + for(int i = 7; i < channels; i++) val[i] = _Tp(0); +} + +template inline +Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7) +{ + CV_StaticAssert(channels >= 8, "Matx should have at least 8 elements."); + val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; + val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; + for(int i = 8; i < channels; i++) val[i] = _Tp(0); +} + +template inline +Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8) +{ + CV_StaticAssert(channels >= 9, "Matx should have at least 9 elements."); + val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; + val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; + val[8] = v8; + for(int i = 9; i < channels; i++) val[i] = _Tp(0); +} + +template inline +Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9) +{ + CV_StaticAssert(channels >= 10, "Matx should have at least 10 elements."); + val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; + val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; + val[8] = v8; val[9] = v9; + for(int i = 10; i < channels; i++) val[i] = _Tp(0); +} + + +template inline +Matx<_Tp,m,n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11) +{ + CV_StaticAssert(channels >= 12, "Matx should have at least 12 elements."); + val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; + val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; + val[8] = v8; val[9] = v9; val[10] = v10; val[11] = v11; + for(int i = 12; i < channels; i++) val[i] = _Tp(0); +} + +template inline +Matx<_Tp,m,n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11, _Tp v12, _Tp v13) +{ + CV_StaticAssert(channels >= 14, "Matx should have at least 14 elements."); + val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; + val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; + val[8] = v8; val[9] = v9; val[10] = v10; val[11] = v11; + val[12] = v12; val[13] = v13; + for (int i = 14; i < channels; i++) val[i] = _Tp(0); +} + + +template inline +Matx<_Tp,m,n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11, _Tp v12, _Tp v13, _Tp v14, _Tp v15) +{ + CV_StaticAssert(channels >= 16, "Matx should have at least 16 elements."); + val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; + val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; + val[8] = v8; val[9] = v9; val[10] = v10; val[11] = v11; + val[12] = v12; val[13] = v13; val[14] = v14; val[15] = v15; + for(int i = 16; i < channels; i++) val[i] = _Tp(0); +} + +// WARNING: unreachable code using Ninja +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(push) +#pragma warning(disable: 4702) +#endif +template inline +Matx<_Tp, m, n>::Matx(const _Tp* values) +{ + for( int i = 0; i < channels; i++ ) val[i] = values[i]; +} +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(pop) +#endif + +template inline +Matx<_Tp, m, n>::Matx(std::initializer_list<_Tp> list) +{ + CV_DbgAssert(list.size() == channels); + int i = 0; + for(const auto& elem : list) + { + val[i++] = elem; + } +} + +template inline +Matx<_Tp, m, n> Matx<_Tp, m, n>::all(_Tp alpha) +{ + Matx<_Tp, m, n> M; + for( int i = 0; i < m*n; i++ ) M.val[i] = alpha; + return M; +} + +template inline +Matx<_Tp,m,n> Matx<_Tp,m,n>::zeros() +{ + return all(0); +} + +template inline +Matx<_Tp,m,n> Matx<_Tp,m,n>::ones() +{ + return all(1); +} + +template inline +Matx<_Tp,m,n> Matx<_Tp,m,n>::eye() +{ + Matx<_Tp,m,n> M; + for(int i = 0; i < shortdim; i++) + M(i,i) = 1; + return M; +} + +template inline +_Tp Matx<_Tp, m, n>::dot(const Matx<_Tp, m, n>& M) const +{ + _Tp s = 0; + for( int i = 0; i < channels; i++ ) s += val[i]*M.val[i]; + return s; +} + +template inline +double Matx<_Tp, m, n>::ddot(const Matx<_Tp, m, n>& M) const +{ + double s = 0; + for( int i = 0; i < channels; i++ ) s += (double)val[i]*M.val[i]; + return s; +} + +template inline +Matx<_Tp,m,n> Matx<_Tp,m,n>::diag(const typename Matx<_Tp,m,n>::diag_type& d) +{ + Matx<_Tp,m,n> M; + for(int i = 0; i < shortdim; i++) + M(i,i) = d(i, 0); + return M; +} + +template template +inline Matx<_Tp, m, n>::operator Matx() const +{ + Matx M; + for( int i = 0; i < m*n; i++ ) M.val[i] = saturate_cast(val[i]); + return M; +} + +template template inline +Matx<_Tp, m1, n1> Matx<_Tp, m, n>::reshape() const +{ + CV_StaticAssert(m1*n1 == m*n, "Input and destination matrices must have the same number of elements"); + return (const Matx<_Tp, m1, n1>&)*this; +} + +template +template inline +Matx<_Tp, m1, n1> Matx<_Tp, m, n>::get_minor(int base_row, int base_col) const +{ + CV_DbgAssert(0 <= base_row && base_row+m1 <= m && 0 <= base_col && base_col+n1 <= n); + Matx<_Tp, m1, n1> s; + for( int di = 0; di < m1; di++ ) + for( int dj = 0; dj < n1; dj++ ) + s(di, dj) = (*this)(base_row+di, base_col+dj); + return s; +} + +template inline +Matx<_Tp, 1, n> Matx<_Tp, m, n>::row(int i) const +{ + CV_DbgAssert((unsigned)i < (unsigned)m); + return Matx<_Tp, 1, n>(&val[i*n]); +} + +template inline +Matx<_Tp, m, 1> Matx<_Tp, m, n>::col(int j) const +{ + CV_DbgAssert((unsigned)j < (unsigned)n); + Matx<_Tp, m, 1> v; + for( int i = 0; i < m; i++ ) + v.val[i] = val[i*n + j]; + return v; +} + +template inline +typename Matx<_Tp, m, n>::diag_type Matx<_Tp, m, n>::diag() const +{ + diag_type d; + for( int i = 0; i < shortdim; i++ ) + d.val[i] = val[i*n + i]; + return d; +} + +template inline +const _Tp& Matx<_Tp, m, n>::operator()(int row_idx, int col_idx) const +{ + CV_DbgAssert( (unsigned)row_idx < (unsigned)m && (unsigned)col_idx < (unsigned)n ); + return this->val[row_idx*n + col_idx]; +} + +template inline +_Tp& Matx<_Tp, m, n>::operator ()(int row_idx, int col_idx) +{ + CV_DbgAssert( (unsigned)row_idx < (unsigned)m && (unsigned)col_idx < (unsigned)n ); + return val[row_idx*n + col_idx]; +} + +template inline +const _Tp& Matx<_Tp, m, n>::operator ()(int i) const +{ + CV_StaticAssert(m == 1 || n == 1, "Single index indexation requires matrix to be a column or a row"); + CV_DbgAssert( (unsigned)i < (unsigned)(m+n-1) ); + return val[i]; +} + +template inline +_Tp& Matx<_Tp, m, n>::operator ()(int i) +{ + CV_StaticAssert(m == 1 || n == 1, "Single index indexation requires matrix to be a column or a row"); + CV_DbgAssert( (unsigned)i < (unsigned)(m+n-1) ); + return val[i]; +} + +template inline +Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_AddOp) +{ + for( int i = 0; i < channels; i++ ) + val[i] = saturate_cast<_Tp>(a.val[i] + b.val[i]); +} + +template inline +Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_SubOp) +{ + for( int i = 0; i < channels; i++ ) + val[i] = saturate_cast<_Tp>(a.val[i] - b.val[i]); +} + +template template inline +Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, _T2 alpha, Matx_ScaleOp) +{ + for( int i = 0; i < channels; i++ ) + val[i] = saturate_cast<_Tp>(a.val[i] * alpha); +} + +template inline +Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_MulOp) +{ + for( int i = 0; i < channels; i++ ) + val[i] = saturate_cast<_Tp>(a.val[i] * b.val[i]); +} + +template inline +Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_DivOp) +{ + for( int i = 0; i < channels; i++ ) + val[i] = saturate_cast<_Tp>(a.val[i] / b.val[i]); +} + +template template inline +Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b, Matx_MatMulOp) +{ + for( int i = 0; i < m; i++ ) + for( int j = 0; j < n; j++ ) + { + _Tp s = 0; + for( int k = 0; k < l; k++ ) + s += a(i, k) * b(k, j); + val[i*n + j] = s; + } +} + +template inline +Matx<_Tp,m,n>::Matx(const Matx<_Tp, n, m>& a, Matx_TOp) +{ + for( int i = 0; i < m; i++ ) + for( int j = 0; j < n; j++ ) + val[i*n + j] = a(j, i); +} + +template inline +Matx<_Tp, m, n> Matx<_Tp, m, n>::mul(const Matx<_Tp, m, n>& a) const +{ + return Matx<_Tp, m, n>(*this, a, Matx_MulOp()); +} + +template inline +Matx<_Tp, m, n> Matx<_Tp, m, n>::div(const Matx<_Tp, m, n>& a) const +{ + return Matx<_Tp, m, n>(*this, a, Matx_DivOp()); +} + +template inline +Matx<_Tp, n, m> Matx<_Tp, m, n>::t() const +{ + return Matx<_Tp, n, m>(*this, Matx_TOp()); +} + +template inline +Vec<_Tp, n> Matx<_Tp, m, n>::solve(const Vec<_Tp, m>& rhs, int method) const +{ + Matx<_Tp, n, 1> x = solve((const Matx<_Tp, m, 1>&)(rhs), method); + return (Vec<_Tp, n>&)(x); +} + +template static inline +double determinant(const Matx<_Tp, m, m>& a) +{ + return cv::internal::Matx_DetOp<_Tp, m>()(a); +} + +template static inline +double trace(const Matx<_Tp, m, n>& a) +{ + _Tp s = 0; + for( int i = 0; i < std::min(m, n); i++ ) + s += a(i,i); + return s; +} + +template static inline +double norm(const Matx<_Tp, m, n>& M) +{ + return std::sqrt(normL2Sqr<_Tp, double>(M.val, m*n)); +} + +template static inline +double norm(const Matx<_Tp, m, n>& M, int normType) +{ + switch(normType) { + case NORM_INF: + return (double)normInf<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n); + case NORM_L1: + return (double)normL1<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n); + case NORM_L2SQR: + return (double)normL2Sqr<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n); + default: + case NORM_L2: + return std::sqrt((double)normL2Sqr<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n)); + } +} + +template static inline +Matx<_Tp1, m, n>& operator += (Matx<_Tp1, m, n>& a, const Matx<_Tp2, m, n>& b) +{ + for( int i = 0; i < m*n; i++ ) + a.val[i] = saturate_cast<_Tp1>(a.val[i] + b.val[i]); + return a; +} + +template static inline +Matx<_Tp1, m, n>& operator -= (Matx<_Tp1, m, n>& a, const Matx<_Tp2, m, n>& b) +{ + for( int i = 0; i < m*n; i++ ) + a.val[i] = saturate_cast<_Tp1>(a.val[i] - b.val[i]); + return a; +} + +template static inline +Matx<_Tp, m, n> operator + (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) +{ + return Matx<_Tp, m, n>(a, b, Matx_AddOp()); +} + +template static inline +Matx<_Tp, m, n> operator - (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) +{ + return Matx<_Tp, m, n>(a, b, Matx_SubOp()); +} + +template static inline +Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, int alpha) +{ + for( int i = 0; i < m*n; i++ ) + a.val[i] = saturate_cast<_Tp>(a.val[i] * alpha); + return a; +} + +template static inline +Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, float alpha) +{ + for( int i = 0; i < m*n; i++ ) + a.val[i] = saturate_cast<_Tp>(a.val[i] * alpha); + return a; +} + +template static inline +Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, double alpha) +{ + for( int i = 0; i < m*n; i++ ) + a.val[i] = saturate_cast<_Tp>(a.val[i] * alpha); + return a; +} + +template static inline +Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, int alpha) +{ + return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); +} + +template static inline +Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, float alpha) +{ + return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); +} + +template static inline +Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, double alpha) +{ + return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); +} + +template static inline +Matx<_Tp, m, n> operator * (int alpha, const Matx<_Tp, m, n>& a) +{ + return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); +} + +template static inline +Matx<_Tp, m, n> operator * (float alpha, const Matx<_Tp, m, n>& a) +{ + return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); +} + +template static inline +Matx<_Tp, m, n> operator * (double alpha, const Matx<_Tp, m, n>& a) +{ + return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); +} + +template static inline +Matx<_Tp, m, n>& operator /= (Matx<_Tp, m, n>& a, float alpha) +{ + for( int i = 0; i < m*n; i++ ) + a.val[i] = a.val[i] / alpha; + return a; +} + +template static inline +Matx<_Tp, m, n>& operator /= (Matx<_Tp, m, n>& a, double alpha) +{ + for( int i = 0; i < m*n; i++ ) + a.val[i] = a.val[i] / alpha; + return a; +} + +template static inline +Matx<_Tp, m, n> operator / (const Matx<_Tp, m, n>& a, float alpha) +{ + return Matx<_Tp, m, n>(a, 1.f/alpha, Matx_ScaleOp()); +} + +template static inline +Matx<_Tp, m, n> operator / (const Matx<_Tp, m, n>& a, double alpha) +{ + return Matx<_Tp, m, n>(a, 1./alpha, Matx_ScaleOp()); +} + +template static inline +Matx<_Tp, m, n> operator - (const Matx<_Tp, m, n>& a) +{ + return Matx<_Tp, m, n>(a, -1, Matx_ScaleOp()); +} + +template static inline +Matx<_Tp, m, n> operator * (const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b) +{ + return Matx<_Tp, m, n>(a, b, Matx_MatMulOp()); +} + +template static inline +Vec<_Tp, m> operator * (const Matx<_Tp, m, n>& a, const Vec<_Tp, n>& b) +{ + Matx<_Tp, m, 1> c(a, b, Matx_MatMulOp()); + return (const Vec<_Tp, m>&)(c); +} + +template static inline +bool operator == (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) +{ + for( int i = 0; i < m*n; i++ ) + if( a.val[i] != b.val[i] ) return false; + return true; +} + +template static inline +bool operator != (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) +{ + return !(a == b); +} + +//============================================================================== +// Vec + +template class DataType< Vec<_Tp, cn> > +{ +public: + typedef Vec<_Tp, cn> value_type; + typedef Vec::work_type, cn> work_type; + typedef _Tp channel_type; + typedef value_type vec_type; + + enum { generic_type = 0, + channels = cn, + fmt = DataType::fmt + ((channels - 1) << 8), +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + depth = DataType::depth, + type = CV_MAKETYPE(depth, channels), +#endif + _dummy_enum_finalizer = 0 + }; +}; + +namespace traits { +template +struct Depth< Vec<_Tp, cn> > { enum { value = Depth<_Tp>::value }; }; +template +struct Type< Vec<_Tp, cn> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, cn) }; }; +} // namespace + +/** @brief Comma-separated Vec Initializer +*/ +template class VecCommaInitializer : public MatxCommaInitializer<_Tp, m, 1> +{ +public: + VecCommaInitializer(Vec<_Tp, m>* _vec); + template VecCommaInitializer<_Tp, m>& operator , (T2 val); + Vec<_Tp, m> operator *() const; +}; + +template static inline +VecCommaInitializer<_Tp, cn> operator << (const Vec<_Tp, cn>& vec, _T2 val) +{ + VecCommaInitializer<_Tp, cn> commaInitializer((Vec<_Tp, cn>*)&vec); + return (commaInitializer, val); +} + +template inline +VecCommaInitializer<_Tp, cn>::VecCommaInitializer(Vec<_Tp, cn>* _vec) + : MatxCommaInitializer<_Tp, cn, 1>(_vec) +{} + +template template inline +VecCommaInitializer<_Tp, cn>& VecCommaInitializer<_Tp, cn>::operator , (_T2 value) +{ + CV_DbgAssert( this->idx < cn ); + this->dst->val[this->idx++] = saturate_cast<_Tp>(value); + return *this; +} + +template inline +Vec<_Tp, cn> VecCommaInitializer<_Tp, cn>::operator *() const +{ + CV_DbgAssert( this->idx == cn ); + return *this->dst; +} + + +template inline +Vec<_Tp, cn>::Vec() {} + +template inline +Vec<_Tp, cn>::Vec(_Tp v0) + : Matx<_Tp, cn, 1>(v0) {} + +template inline +Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1) + : Matx<_Tp, cn, 1>(v0, v1) {} + +template inline +Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2) + : Matx<_Tp, cn, 1>(v0, v1, v2) {} + +template inline +Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3) + : Matx<_Tp, cn, 1>(v0, v1, v2, v3) {} + +template inline +Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4) + : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4) {} + +template inline +Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5) + : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5) {} + +template inline +Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6) + : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6) {} + +template inline +Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7) + : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6, v7) {} + +template inline +Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8) + : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6, v7, v8) {} + +template inline +Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9) + : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {} + +template inline +Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11, _Tp v12, _Tp v13) + : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) {} + +template inline +Vec<_Tp, cn>::Vec(const _Tp* values) + : Matx<_Tp, cn, 1>(values) {} + +template inline +Vec<_Tp, cn>::Vec(std::initializer_list<_Tp> list) + : Matx<_Tp, cn, 1>(list) {} + +template inline +Vec<_Tp, cn>::Vec(const Vec<_Tp, cn>& m) + : Matx<_Tp, cn, 1>(m.val) {} + +template inline +Vec<_Tp, cn>::Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_AddOp op) + : Matx<_Tp, cn, 1>(a, b, op) {} + +template inline +Vec<_Tp, cn>::Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_SubOp op) + : Matx<_Tp, cn, 1>(a, b, op) {} + +template template inline +Vec<_Tp, cn>::Vec(const Matx<_Tp, cn, 1>& a, _T2 alpha, Matx_ScaleOp op) + : Matx<_Tp, cn, 1>(a, alpha, op) {} + +template inline +Vec<_Tp, cn> Vec<_Tp, cn>::all(_Tp alpha) +{ + Vec v; + for( int i = 0; i < cn; i++ ) v.val[i] = alpha; + return v; +} + +template inline +Vec<_Tp, cn> Vec<_Tp, cn>::ones() +{ + return Vec::all(1); +} + +template inline +Vec<_Tp, cn> Vec<_Tp, cn>::zeros() +{ + return Vec::all(0); +} + +template inline +Vec<_Tp, cn> Vec<_Tp, cn>::mul(const Vec<_Tp, cn>& v) const +{ + Vec<_Tp, cn> w; + for( int i = 0; i < cn; i++ ) w.val[i] = saturate_cast<_Tp>(this->val[i]*v.val[i]); + return w; +} + +template<> inline +Vec Vec::conj() const +{ + return cv::internal::conjugate(*this); +} + +template<> inline +Vec Vec::conj() const +{ + return cv::internal::conjugate(*this); +} + +template<> inline +Vec Vec::conj() const +{ + return cv::internal::conjugate(*this); +} + +template<> inline +Vec Vec::conj() const +{ + return cv::internal::conjugate(*this); +} + +template inline +Vec<_Tp, cn> Vec<_Tp, cn>::cross(const Vec<_Tp, cn>&) const +{ + CV_StaticAssert(cn == 3, "for arbitrary-size vector there is no cross-product defined"); + return Vec<_Tp, cn>(); +} + +template<> inline +Vec Vec::cross(const Vec& v) const +{ + return Vec(this->val[1]*v.val[2] - this->val[2]*v.val[1], + this->val[2]*v.val[0] - this->val[0]*v.val[2], + this->val[0]*v.val[1] - this->val[1]*v.val[0]); +} + +template<> inline +Vec Vec::cross(const Vec& v) const +{ + return Vec(this->val[1]*v.val[2] - this->val[2]*v.val[1], + this->val[2]*v.val[0] - this->val[0]*v.val[2], + this->val[0]*v.val[1] - this->val[1]*v.val[0]); +} + +template template inline +Vec<_Tp, cn>::operator Vec() const +{ + Vec v; + for( int i = 0; i < cn; i++ ) v.val[i] = saturate_cast(this->val[i]); + return v; +} + +template inline +const _Tp& Vec<_Tp, cn>::operator [](int i) const +{ + CV_DbgAssert( (unsigned)i < (unsigned)cn ); + return this->val[i]; +} + +template inline +_Tp& Vec<_Tp, cn>::operator [](int i) +{ + CV_DbgAssert( (unsigned)i < (unsigned)cn ); + return this->val[i]; +} + +template inline +const _Tp& Vec<_Tp, cn>::operator ()(int i) const +{ + CV_DbgAssert( (unsigned)i < (unsigned)cn ); + return this->val[i]; +} + +template inline +_Tp& Vec<_Tp, cn>::operator ()(int i) +{ + CV_DbgAssert( (unsigned)i < (unsigned)cn ); + return this->val[i]; +} + +template inline +Vec<_Tp, cn> normalize(const Vec<_Tp, cn>& v) +{ + double nv = norm(v); + return v * (nv ? 1./nv : 0.); +} + +template static inline +Vec<_Tp1, cn>& operator += (Vec<_Tp1, cn>& a, const Vec<_Tp2, cn>& b) +{ + for( int i = 0; i < cn; i++ ) + a.val[i] = saturate_cast<_Tp1>(a.val[i] + b.val[i]); + return a; +} + +template static inline +Vec<_Tp1, cn>& operator -= (Vec<_Tp1, cn>& a, const Vec<_Tp2, cn>& b) +{ + for( int i = 0; i < cn; i++ ) + a.val[i] = saturate_cast<_Tp1>(a.val[i] - b.val[i]); + return a; +} + +template static inline +Vec<_Tp, cn> operator + (const Vec<_Tp, cn>& a, const Vec<_Tp, cn>& b) +{ + return Vec<_Tp, cn>(a, b, Matx_AddOp()); +} + +template static inline +Vec<_Tp, cn> operator - (const Vec<_Tp, cn>& a, const Vec<_Tp, cn>& b) +{ + return Vec<_Tp, cn>(a, b, Matx_SubOp()); +} + +template static inline +Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, int alpha) +{ + for( int i = 0; i < cn; i++ ) + a[i] = saturate_cast<_Tp>(a[i]*alpha); + return a; +} + +template static inline +Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, float alpha) +{ + for( int i = 0; i < cn; i++ ) + a[i] = saturate_cast<_Tp>(a[i]*alpha); + return a; +} + +template static inline +Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, double alpha) +{ + for( int i = 0; i < cn; i++ ) + a[i] = saturate_cast<_Tp>(a[i]*alpha); + return a; +} + +template static inline +Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, int alpha) +{ + double ialpha = 1./alpha; + for( int i = 0; i < cn; i++ ) + a[i] = saturate_cast<_Tp>(a[i]*ialpha); + return a; +} + +template static inline +Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, float alpha) +{ + float ialpha = 1.f/alpha; + for( int i = 0; i < cn; i++ ) + a[i] = saturate_cast<_Tp>(a[i]*ialpha); + return a; +} + +template static inline +Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, double alpha) +{ + double ialpha = 1./alpha; + for( int i = 0; i < cn; i++ ) + a[i] = saturate_cast<_Tp>(a[i]*ialpha); + return a; +} + +template static inline +Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, int alpha) +{ + return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); +} + +template static inline +Vec<_Tp, cn> operator * (int alpha, const Vec<_Tp, cn>& a) +{ + return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); +} + +template static inline +Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, float alpha) +{ + return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); +} + +template static inline +Vec<_Tp, cn> operator * (float alpha, const Vec<_Tp, cn>& a) +{ + return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); +} + +template static inline +Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, double alpha) +{ + return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); +} + +template static inline +Vec<_Tp, cn> operator * (double alpha, const Vec<_Tp, cn>& a) +{ + return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); +} + +template static inline +Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, int alpha) +{ + return Vec<_Tp, cn>(a, 1./alpha, Matx_ScaleOp()); +} + +template static inline +Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, float alpha) +{ + return Vec<_Tp, cn>(a, 1.f/alpha, Matx_ScaleOp()); +} + +template static inline +Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, double alpha) +{ + return Vec<_Tp, cn>(a, 1./alpha, Matx_ScaleOp()); +} + +template static inline +Vec<_Tp, cn> operator - (const Vec<_Tp, cn>& a) +{ + Vec<_Tp,cn> t; + for( int i = 0; i < cn; i++ ) t.val[i] = saturate_cast<_Tp>(-a.val[i]); + return t; +} + +template inline Vec<_Tp, 4> operator * (const Vec<_Tp, 4>& v1, const Vec<_Tp, 4>& v2) +{ + return Vec<_Tp, 4>(saturate_cast<_Tp>(v1[0]*v2[0] - v1[1]*v2[1] - v1[2]*v2[2] - v1[3]*v2[3]), + saturate_cast<_Tp>(v1[0]*v2[1] + v1[1]*v2[0] + v1[2]*v2[3] - v1[3]*v2[2]), + saturate_cast<_Tp>(v1[0]*v2[2] - v1[1]*v2[3] + v1[2]*v2[0] + v1[3]*v2[1]), + saturate_cast<_Tp>(v1[0]*v2[3] + v1[1]*v2[2] - v1[2]*v2[1] + v1[3]*v2[0])); +} + +template inline Vec<_Tp, 4>& operator *= (Vec<_Tp, 4>& v1, const Vec<_Tp, 4>& v2) +{ + v1 = v1 * v2; + return v1; +} + +} // cv:: + +#endif // OPENCV_CORE_MATX_INL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/neon_utils.hpp b/3rdParty/opencv-4.11.0/opencv2/core/neon_utils.hpp index 573ba99ec3..7109006e19 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/neon_utils.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/neon_utils.hpp @@ -1,128 +1,128 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_HAL_NEON_UTILS_HPP -#define OPENCV_HAL_NEON_UTILS_HPP - -#include "opencv2/core/cvdef.h" - -//! @addtogroup core_utils_neon -//! @{ - -#if CV_NEON - -inline int32x2_t cv_vrnd_s32_f32(float32x2_t v) -{ - static int32x2_t v_sign = vdup_n_s32(1 << 31), - v_05 = vreinterpret_s32_f32(vdup_n_f32(0.5f)); - - int32x2_t v_addition = vorr_s32(v_05, vand_s32(v_sign, vreinterpret_s32_f32(v))); - return vcvt_s32_f32(vadd_f32(v, vreinterpret_f32_s32(v_addition))); -} - -inline int32x4_t cv_vrndq_s32_f32(float32x4_t v) -{ - static int32x4_t v_sign = vdupq_n_s32(1 << 31), - v_05 = vreinterpretq_s32_f32(vdupq_n_f32(0.5f)); - - int32x4_t v_addition = vorrq_s32(v_05, vandq_s32(v_sign, vreinterpretq_s32_f32(v))); - return vcvtq_s32_f32(vaddq_f32(v, vreinterpretq_f32_s32(v_addition))); -} - -inline uint32x2_t cv_vrnd_u32_f32(float32x2_t v) -{ - static float32x2_t v_05 = vdup_n_f32(0.5f); - return vcvt_u32_f32(vadd_f32(v, v_05)); -} - -inline uint32x4_t cv_vrndq_u32_f32(float32x4_t v) -{ - static float32x4_t v_05 = vdupq_n_f32(0.5f); - return vcvtq_u32_f32(vaddq_f32(v, v_05)); -} - -inline float32x4_t cv_vrecpq_f32(float32x4_t val) -{ - float32x4_t reciprocal = vrecpeq_f32(val); - reciprocal = vmulq_f32(vrecpsq_f32(val, reciprocal), reciprocal); - reciprocal = vmulq_f32(vrecpsq_f32(val, reciprocal), reciprocal); - return reciprocal; -} - -inline float32x2_t cv_vrecp_f32(float32x2_t val) -{ - float32x2_t reciprocal = vrecpe_f32(val); - reciprocal = vmul_f32(vrecps_f32(val, reciprocal), reciprocal); - reciprocal = vmul_f32(vrecps_f32(val, reciprocal), reciprocal); - return reciprocal; -} - -inline float32x4_t cv_vrsqrtq_f32(float32x4_t val) -{ - float32x4_t e = vrsqrteq_f32(val); - e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(e, e), val), e); - e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(e, e), val), e); - return e; -} - -inline float32x2_t cv_vrsqrt_f32(float32x2_t val) -{ - float32x2_t e = vrsqrte_f32(val); - e = vmul_f32(vrsqrts_f32(vmul_f32(e, e), val), e); - e = vmul_f32(vrsqrts_f32(vmul_f32(e, e), val), e); - return e; -} - -inline float32x4_t cv_vsqrtq_f32(float32x4_t val) -{ - return cv_vrecpq_f32(cv_vrsqrtq_f32(val)); -} - -inline float32x2_t cv_vsqrt_f32(float32x2_t val) -{ - return cv_vrecp_f32(cv_vrsqrt_f32(val)); -} - -#endif - -//! @} - -#endif // OPENCV_HAL_NEON_UTILS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_HAL_NEON_UTILS_HPP +#define OPENCV_HAL_NEON_UTILS_HPP + +#include "opencv2/core/cvdef.h" + +//! @addtogroup core_utils_neon +//! @{ + +#if CV_NEON + +inline int32x2_t cv_vrnd_s32_f32(float32x2_t v) +{ + static int32x2_t v_sign = vdup_n_s32(1 << 31), + v_05 = vreinterpret_s32_f32(vdup_n_f32(0.5f)); + + int32x2_t v_addition = vorr_s32(v_05, vand_s32(v_sign, vreinterpret_s32_f32(v))); + return vcvt_s32_f32(vadd_f32(v, vreinterpret_f32_s32(v_addition))); +} + +inline int32x4_t cv_vrndq_s32_f32(float32x4_t v) +{ + static int32x4_t v_sign = vdupq_n_s32(1 << 31), + v_05 = vreinterpretq_s32_f32(vdupq_n_f32(0.5f)); + + int32x4_t v_addition = vorrq_s32(v_05, vandq_s32(v_sign, vreinterpretq_s32_f32(v))); + return vcvtq_s32_f32(vaddq_f32(v, vreinterpretq_f32_s32(v_addition))); +} + +inline uint32x2_t cv_vrnd_u32_f32(float32x2_t v) +{ + static float32x2_t v_05 = vdup_n_f32(0.5f); + return vcvt_u32_f32(vadd_f32(v, v_05)); +} + +inline uint32x4_t cv_vrndq_u32_f32(float32x4_t v) +{ + static float32x4_t v_05 = vdupq_n_f32(0.5f); + return vcvtq_u32_f32(vaddq_f32(v, v_05)); +} + +inline float32x4_t cv_vrecpq_f32(float32x4_t val) +{ + float32x4_t reciprocal = vrecpeq_f32(val); + reciprocal = vmulq_f32(vrecpsq_f32(val, reciprocal), reciprocal); + reciprocal = vmulq_f32(vrecpsq_f32(val, reciprocal), reciprocal); + return reciprocal; +} + +inline float32x2_t cv_vrecp_f32(float32x2_t val) +{ + float32x2_t reciprocal = vrecpe_f32(val); + reciprocal = vmul_f32(vrecps_f32(val, reciprocal), reciprocal); + reciprocal = vmul_f32(vrecps_f32(val, reciprocal), reciprocal); + return reciprocal; +} + +inline float32x4_t cv_vrsqrtq_f32(float32x4_t val) +{ + float32x4_t e = vrsqrteq_f32(val); + e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(e, e), val), e); + e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(e, e), val), e); + return e; +} + +inline float32x2_t cv_vrsqrt_f32(float32x2_t val) +{ + float32x2_t e = vrsqrte_f32(val); + e = vmul_f32(vrsqrts_f32(vmul_f32(e, e), val), e); + e = vmul_f32(vrsqrts_f32(vmul_f32(e, e), val), e); + return e; +} + +inline float32x4_t cv_vsqrtq_f32(float32x4_t val) +{ + return cv_vrecpq_f32(cv_vrsqrtq_f32(val)); +} + +inline float32x2_t cv_vsqrt_f32(float32x2_t val) +{ + return cv_vrecp_f32(cv_vrsqrt_f32(val)); +} + +#endif + +//! @} + +#endif // OPENCV_HAL_NEON_UTILS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/ocl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/ocl.hpp index 891fd678b7..ab561691d8 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/ocl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/ocl.hpp @@ -1,923 +1,923 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 OpenCV Foundation 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. -// -//M*/ - -#ifndef OPENCV_OPENCL_HPP -#define OPENCV_OPENCL_HPP - -#include "opencv2/core.hpp" -#include -#include - -namespace cv { namespace ocl { - -//! @addtogroup core_opencl -//! @{ - -CV_EXPORTS_W bool haveOpenCL(); -CV_EXPORTS_W bool useOpenCL(); -CV_EXPORTS_W bool haveAmdBlas(); -CV_EXPORTS_W bool haveAmdFft(); -CV_EXPORTS_W void setUseOpenCL(bool flag); -CV_EXPORTS_W void finish(); - -CV_EXPORTS bool haveSVM(); - -class CV_EXPORTS Context; -class CV_EXPORTS_W_SIMPLE Device; -class CV_EXPORTS Kernel; -class CV_EXPORTS Program; -class CV_EXPORTS ProgramSource; -class CV_EXPORTS Queue; -class CV_EXPORTS PlatformInfo; -class CV_EXPORTS Image2D; - -class CV_EXPORTS_W_SIMPLE Device -{ -public: - CV_WRAP Device() CV_NOEXCEPT; - explicit Device(void* d); - Device(const Device& d); - Device& operator = (const Device& d); - Device(Device&& d) CV_NOEXCEPT; - Device& operator = (Device&& d) CV_NOEXCEPT; - CV_WRAP ~Device(); - - void set(void* d); - - enum - { - TYPE_DEFAULT = (1 << 0), - TYPE_CPU = (1 << 1), - TYPE_GPU = (1 << 2), - TYPE_ACCELERATOR = (1 << 3), - TYPE_DGPU = TYPE_GPU + (1 << 16), - TYPE_IGPU = TYPE_GPU + (1 << 17), - TYPE_ALL = 0xFFFFFFFF - }; - - CV_WRAP String name() const; - CV_WRAP String extensions() const; - CV_WRAP bool isExtensionSupported(const String& extensionName) const; - CV_WRAP String version() const; - CV_WRAP String vendorName() const; - CV_WRAP String OpenCL_C_Version() const; - CV_WRAP String OpenCLVersion() const; - CV_WRAP int deviceVersionMajor() const; - CV_WRAP int deviceVersionMinor() const; - CV_WRAP String driverVersion() const; - void* ptr() const; - - CV_WRAP int type() const; - - CV_WRAP int addressBits() const; - CV_WRAP bool available() const; - CV_WRAP bool compilerAvailable() const; - CV_WRAP bool linkerAvailable() const; - - enum - { - FP_DENORM=(1 << 0), - FP_INF_NAN=(1 << 1), - FP_ROUND_TO_NEAREST=(1 << 2), - FP_ROUND_TO_ZERO=(1 << 3), - FP_ROUND_TO_INF=(1 << 4), - FP_FMA=(1 << 5), - FP_SOFT_FLOAT=(1 << 6), - FP_CORRECTLY_ROUNDED_DIVIDE_SQRT=(1 << 7) - }; - CV_WRAP int doubleFPConfig() const; - CV_WRAP int singleFPConfig() const; - CV_WRAP int halfFPConfig() const; - - /// true if 'cl_khr_fp64' extension is available - CV_WRAP bool hasFP64() const; - /// true if 'cl_khr_fp16' extension is available - CV_WRAP bool hasFP16() const; - - CV_WRAP bool endianLittle() const; - CV_WRAP bool errorCorrectionSupport() const; - - enum - { - EXEC_KERNEL=(1 << 0), - EXEC_NATIVE_KERNEL=(1 << 1) - }; - CV_WRAP int executionCapabilities() const; - - CV_WRAP size_t globalMemCacheSize() const; - - enum - { - NO_CACHE=0, - READ_ONLY_CACHE=1, - READ_WRITE_CACHE=2 - }; - CV_WRAP int globalMemCacheType() const; - CV_WRAP int globalMemCacheLineSize() const; - CV_WRAP size_t globalMemSize() const; - - CV_WRAP size_t localMemSize() const; - enum - { - NO_LOCAL_MEM=0, - LOCAL_IS_LOCAL=1, - LOCAL_IS_GLOBAL=2 - }; - CV_WRAP int localMemType() const; - CV_WRAP bool hostUnifiedMemory() const; - - CV_WRAP bool imageSupport() const; - - CV_WRAP bool imageFromBufferSupport() const; - uint imagePitchAlignment() const; - uint imageBaseAddressAlignment() const; - - /// deprecated, use isExtensionSupported() method (probably with "cl_khr_subgroups" value) - CV_WRAP bool intelSubgroupsSupport() const; - - CV_WRAP size_t image2DMaxWidth() const; - CV_WRAP size_t image2DMaxHeight() const; - - CV_WRAP size_t image3DMaxWidth() const; - CV_WRAP size_t image3DMaxHeight() const; - CV_WRAP size_t image3DMaxDepth() const; - - CV_WRAP size_t imageMaxBufferSize() const; - CV_WRAP size_t imageMaxArraySize() const; - - enum - { - UNKNOWN_VENDOR=0, - VENDOR_AMD=1, - VENDOR_INTEL=2, - VENDOR_NVIDIA=3 - }; - CV_WRAP int vendorID() const; - // FIXIT - // dev.isAMD() doesn't work for OpenCL CPU devices from AMD OpenCL platform. - // This method should use platform name instead of vendor name. - // After fix restore code in arithm.cpp: ocl_compare() - CV_WRAP inline bool isAMD() const { return vendorID() == VENDOR_AMD; } - CV_WRAP inline bool isIntel() const { return vendorID() == VENDOR_INTEL; } - CV_WRAP inline bool isNVidia() const { return vendorID() == VENDOR_NVIDIA; } - - CV_WRAP int maxClockFrequency() const; - CV_WRAP int maxComputeUnits() const; - CV_WRAP int maxConstantArgs() const; - CV_WRAP size_t maxConstantBufferSize() const; - - CV_WRAP size_t maxMemAllocSize() const; - CV_WRAP size_t maxParameterSize() const; - - CV_WRAP int maxReadImageArgs() const; - CV_WRAP int maxWriteImageArgs() const; - CV_WRAP int maxSamplers() const; - - CV_WRAP size_t maxWorkGroupSize() const; - CV_WRAP int maxWorkItemDims() const; - void maxWorkItemSizes(size_t*) const; - - CV_WRAP int memBaseAddrAlign() const; - - CV_WRAP int nativeVectorWidthChar() const; - CV_WRAP int nativeVectorWidthShort() const; - CV_WRAP int nativeVectorWidthInt() const; - CV_WRAP int nativeVectorWidthLong() const; - CV_WRAP int nativeVectorWidthFloat() const; - CV_WRAP int nativeVectorWidthDouble() const; - CV_WRAP int nativeVectorWidthHalf() const; - - CV_WRAP int preferredVectorWidthChar() const; - CV_WRAP int preferredVectorWidthShort() const; - CV_WRAP int preferredVectorWidthInt() const; - CV_WRAP int preferredVectorWidthLong() const; - CV_WRAP int preferredVectorWidthFloat() const; - CV_WRAP int preferredVectorWidthDouble() const; - CV_WRAP int preferredVectorWidthHalf() const; - - CV_WRAP size_t printfBufferSize() const; - CV_WRAP size_t profilingTimerResolution() const; - - CV_WRAP static const Device& getDefault(); - - /** - * @param d OpenCL handle (cl_device_id). clRetainDevice() is called on success. - * - * @note Ownership of the passed device is passed to OpenCV on success. - * The caller should additionally call `clRetainDevice` on it if it intends - * to continue using the device. - */ - static Device fromHandle(void* d); - - struct Impl; - inline Impl* getImpl() const { return (Impl*)p; } - inline bool empty() const { return !p; } -protected: - Impl* p; -}; - - -class CV_EXPORTS Context -{ -public: - Context() CV_NOEXCEPT; - explicit Context(int dtype); //!< @deprecated - ~Context(); - Context(const Context& c); - Context& operator= (const Context& c); - Context(Context&& c) CV_NOEXCEPT; - Context& operator = (Context&& c) CV_NOEXCEPT; - - /** @deprecated */ - bool create(); - /** @deprecated */ - bool create(int dtype); - - size_t ndevices() const; - Device& device(size_t idx) const; - Program getProg(const ProgramSource& prog, - const String& buildopt, String& errmsg); - void unloadProg(Program& prog); - - - /** Get thread-local OpenCL context (initialize if necessary) */ -#if 0 // OpenCV 5.0 - static Context& getDefault(); -#else - static Context& getDefault(bool initialize = true); -#endif - - /** @returns cl_context value */ - void* ptr() const; - - /** - * @brief Get OpenCL context property specified on context creation - * @param propertyId Property id (CL_CONTEXT_* as defined in cl_context_properties type) - * @returns Property value if property was specified on clCreateContext, or NULL if context created without the property - */ - void* getOpenCLContextProperty(int propertyId) const; - - bool useSVM() const; - void setUseSVM(bool enabled); - - /** - * @param context OpenCL handle (cl_context). clRetainContext() is called on success - */ - static Context fromHandle(void* context); - static Context fromDevice(const ocl::Device& device); - static Context create(const std::string& configuration); - - void release(); - - class CV_EXPORTS UserContext { - public: - virtual ~UserContext(); - }; - template - inline void setUserContext(const std::shared_ptr& userContext) { - setUserContext(typeid(T), userContext); - } - template - inline std::shared_ptr getUserContext() { - return std::dynamic_pointer_cast(getUserContext(typeid(T))); - } - void setUserContext(std::type_index typeId, const std::shared_ptr& userContext); - std::shared_ptr getUserContext(std::type_index typeId); - - struct Impl; - inline Impl* getImpl() const { return (Impl*)p; } - inline bool empty() const { return !p; } -// TODO OpenCV 5.0 -//protected: - Impl* p; -}; - -/** @deprecated */ -class CV_EXPORTS Platform -{ -public: - Platform() CV_NOEXCEPT; - ~Platform(); - Platform(const Platform& p); - Platform& operator = (const Platform& p); - Platform(Platform&& p) CV_NOEXCEPT; - Platform& operator = (Platform&& p) CV_NOEXCEPT; - - void* ptr() const; - - /** @deprecated */ - static Platform& getDefault(); - - struct Impl; - inline Impl* getImpl() const { return (Impl*)p; } - inline bool empty() const { return !p; } -protected: - Impl* p; -}; - -/** @brief Attaches OpenCL context to OpenCV -@note - OpenCV will check if available OpenCL platform has platformName name, then assign context to - OpenCV and call `clRetainContext` function. The deviceID device will be used as target device and - new command queue will be created. -@param platformName name of OpenCL platform to attach, this string is used to check if platform is available to OpenCV at runtime -@param platformID ID of platform attached context was created for -@param context OpenCL context to be attached to OpenCV -@param deviceID ID of device, must be created from attached context -*/ -CV_EXPORTS void attachContext(const String& platformName, void* platformID, void* context, void* deviceID); - -/** @brief Convert OpenCL buffer to UMat -@note - OpenCL buffer (cl_mem_buffer) should contain 2D image data, compatible with OpenCV. Memory - content is not copied from `clBuffer` to UMat. Instead, buffer handle assigned to UMat and - `clRetainMemObject` is called. -@param cl_mem_buffer source clBuffer handle -@param step num of bytes in single row -@param rows number of rows -@param cols number of cols -@param type OpenCV type of image -@param dst destination UMat -*/ -CV_EXPORTS void convertFromBuffer(void* cl_mem_buffer, size_t step, int rows, int cols, int type, UMat& dst); - -/** @brief Convert OpenCL image2d_t to UMat -@note - OpenCL `image2d_t` (cl_mem_image), should be compatible with OpenCV UMat formats. Memory content - is copied from image to UMat with `clEnqueueCopyImageToBuffer` function. -@param cl_mem_image source image2d_t handle -@param dst destination UMat -*/ -CV_EXPORTS void convertFromImage(void* cl_mem_image, UMat& dst); - -// TODO Move to internal header -/// @deprecated -void initializeContextFromHandle(Context& ctx, void* platform, void* context, void* device); - -class CV_EXPORTS Queue -{ -public: - Queue() CV_NOEXCEPT; - explicit Queue(const Context& c, const Device& d=Device()); - ~Queue(); - Queue(const Queue& q); - Queue& operator = (const Queue& q); - Queue(Queue&& q) CV_NOEXCEPT; - Queue& operator = (Queue&& q) CV_NOEXCEPT; - - bool create(const Context& c=Context(), const Device& d=Device()); - void finish(); - void* ptr() const; - static Queue& getDefault(); - - /// @brief Returns OpenCL command queue with enable profiling mode support - const Queue& getProfilingQueue() const; - - struct Impl; friend struct Impl; - inline Impl* getImpl() const { return p; } - inline bool empty() const { return !p; } -protected: - Impl* p; -}; - - -class CV_EXPORTS KernelArg -{ -public: - enum { LOCAL=1, READ_ONLY=2, WRITE_ONLY=4, READ_WRITE=6, CONSTANT=8, PTR_ONLY = 16, NO_SIZE=256 }; - KernelArg(int _flags, UMat* _m, int wscale=1, int iwscale=1, const void* _obj=0, size_t _sz=0); - KernelArg() CV_NOEXCEPT; - - static KernelArg Local(size_t localMemSize) - { return KernelArg(LOCAL, 0, 1, 1, 0, localMemSize); } - static KernelArg PtrWriteOnly(const UMat& m) - { return KernelArg(PTR_ONLY+WRITE_ONLY, (UMat*)&m); } - static KernelArg PtrReadOnly(const UMat& m) - { return KernelArg(PTR_ONLY+READ_ONLY, (UMat*)&m); } - static KernelArg PtrReadWrite(const UMat& m) - { return KernelArg(PTR_ONLY+READ_WRITE, (UMat*)&m); } - static KernelArg ReadWrite(const UMat& m, int wscale=1, int iwscale=1) - { return KernelArg(READ_WRITE, (UMat*)&m, wscale, iwscale); } - static KernelArg ReadWriteNoSize(const UMat& m, int wscale=1, int iwscale=1) - { return KernelArg(READ_WRITE+NO_SIZE, (UMat*)&m, wscale, iwscale); } - static KernelArg ReadOnly(const UMat& m, int wscale=1, int iwscale=1) - { return KernelArg(READ_ONLY, (UMat*)&m, wscale, iwscale); } - static KernelArg WriteOnly(const UMat& m, int wscale=1, int iwscale=1) - { return KernelArg(WRITE_ONLY, (UMat*)&m, wscale, iwscale); } - static KernelArg ReadOnlyNoSize(const UMat& m, int wscale=1, int iwscale=1) - { return KernelArg(READ_ONLY+NO_SIZE, (UMat*)&m, wscale, iwscale); } - static KernelArg WriteOnlyNoSize(const UMat& m, int wscale=1, int iwscale=1) - { return KernelArg(WRITE_ONLY+NO_SIZE, (UMat*)&m, wscale, iwscale); } - static KernelArg Constant(const Mat& m); - template static KernelArg Constant(const _Tp* arr, size_t n) - { return KernelArg(CONSTANT, 0, 1, 1, (void*)arr, n); } - - int flags; - UMat* m; - const void* obj; - size_t sz; - int wscale, iwscale; -}; - - -class CV_EXPORTS Kernel -{ -public: - Kernel() CV_NOEXCEPT; - Kernel(const char* kname, const Program& prog); - Kernel(const char* kname, const ProgramSource& prog, - const String& buildopts = String(), String* errmsg=0); - ~Kernel(); - Kernel(const Kernel& k); - Kernel& operator = (const Kernel& k); - Kernel(Kernel&& k) CV_NOEXCEPT; - Kernel& operator = (Kernel&& k) CV_NOEXCEPT; - - bool empty() const; - bool create(const char* kname, const Program& prog); - bool create(const char* kname, const ProgramSource& prog, - const String& buildopts, String* errmsg=0); - - int set(int i, const void* value, size_t sz); - int set(int i, const Image2D& image2D); - int set(int i, const UMat& m); - int set(int i, const KernelArg& arg); - template int set(int i, const _Tp& value) - { return set(i, &value, sizeof(value)); } - - -protected: - template inline - int set_args_(int i, const _Tp0& a0) { return set(i, a0); } - template inline - int set_args_(int i, const _Tp0& a0, const _Tps&... rest_args) { i = set(i, a0); return set_args_(i, rest_args...); } -public: - /** @brief Setup OpenCL Kernel arguments. - Avoid direct using of set(i, ...) methods. - @code - bool ok = kernel - .args( - srcUMat, dstUMat, - (float)some_float_param - ).run(ndims, globalSize, localSize); - if (!ok) return false; - @endcode - */ - template inline - Kernel& args(const _Tps&... kernel_args) { set_args_(0, kernel_args...); return *this; } - - /** @brief Run the OpenCL kernel (globalsize value may be adjusted) - - @param dims the work problem dimensions. It is the length of globalsize and localsize. It can be either 1, 2 or 3. - @param globalsize work items for each dimension. It is not the final globalsize passed to - OpenCL. Each dimension will be adjusted to the nearest integer divisible by the corresponding - value in localsize. If localsize is NULL, it will still be adjusted depending on dims. The - adjusted values are greater than or equal to the original values. - @param localsize work-group size for each dimension. - @param sync specify whether to wait for OpenCL computation to finish before return. - @param q command queue - - @note Use run_() if your kernel code doesn't support adjusted globalsize. - */ - bool run(int dims, size_t globalsize[], - size_t localsize[], bool sync, const Queue& q=Queue()); - - /** @brief Run the OpenCL kernel - * - * @param dims the work problem dimensions. It is the length of globalsize and localsize. It can be either 1, 2 or 3. - * @param globalsize work items for each dimension. This value is passed to OpenCL without changes. - * @param localsize work-group size for each dimension. - * @param sync specify whether to wait for OpenCL computation to finish before return. - * @param q command queue - */ - bool run_(int dims, size_t globalsize[], size_t localsize[], bool sync, const Queue& q=Queue()); - - bool runTask(bool sync, const Queue& q=Queue()); - - /** @brief Similar to synchronized run_() call with returning of kernel execution time - * - * Separate OpenCL command queue may be used (with CL_QUEUE_PROFILING_ENABLE) - * @return Execution time in nanoseconds or negative number on error - */ - int64 runProfiling(int dims, size_t globalsize[], size_t localsize[], const Queue& q=Queue()); - - size_t workGroupSize() const; - size_t preferedWorkGroupSizeMultiple() const; - bool compileWorkGroupSize(size_t wsz[]) const; - size_t localMemSize() const; - - void* ptr() const; - struct Impl; - -protected: - Impl* p; -}; - -class CV_EXPORTS Program -{ -public: - Program() CV_NOEXCEPT; - Program(const ProgramSource& src, - const String& buildflags, String& errmsg); - Program(const Program& prog); - Program& operator = (const Program& prog); - Program(Program&& prog) CV_NOEXCEPT; - Program& operator = (Program&& prog) CV_NOEXCEPT; - ~Program(); - - bool create(const ProgramSource& src, - const String& buildflags, String& errmsg); - - void* ptr() const; - - /** - * @brief Query device-specific program binary. - * - * Returns RAW OpenCL executable binary without additional attachments. - * - * @sa ProgramSource::fromBinary - * - * @param[out] binary output buffer - */ - void getBinary(std::vector& binary) const; - - struct Impl; friend struct Impl; - inline Impl* getImpl() const { return (Impl*)p; } - inline bool empty() const { return !p; } -protected: - Impl* p; -public: -#ifndef OPENCV_REMOVE_DEPRECATED_API - // TODO Remove this - CV_DEPRECATED bool read(const String& buf, const String& buildflags); // removed, use ProgramSource instead - CV_DEPRECATED bool write(String& buf) const; // removed, use getBinary() method instead (RAW OpenCL binary) - CV_DEPRECATED const ProgramSource& source() const; // implementation removed - CV_DEPRECATED String getPrefix() const; // deprecated, implementation replaced - CV_DEPRECATED static String getPrefix(const String& buildflags); // deprecated, implementation replaced -#endif -}; - - -class CV_EXPORTS ProgramSource -{ -public: - typedef uint64 hash_t; // deprecated - - ProgramSource() CV_NOEXCEPT; - explicit ProgramSource(const String& module, const String& name, const String& codeStr, const String& codeHash); - explicit ProgramSource(const String& prog); // deprecated - explicit ProgramSource(const char* prog); // deprecated - ~ProgramSource(); - ProgramSource(const ProgramSource& prog); - ProgramSource& operator = (const ProgramSource& prog); - ProgramSource(ProgramSource&& prog) CV_NOEXCEPT; - ProgramSource& operator = (ProgramSource&& prog) CV_NOEXCEPT; - - const String& source() const; // deprecated - hash_t hash() const; // deprecated - - - /** @brief Describe OpenCL program binary. - * Do not call clCreateProgramWithBinary() and/or clBuildProgram(). - * - * Caller should guarantee binary buffer lifetime greater than ProgramSource object (and any of its copies). - * - * This kind of binary is not portable between platforms in general - it is specific to OpenCL vendor / device / driver version. - * - * @param module name of program owner module - * @param name unique name of program (module+name is used as key for OpenCL program caching) - * @param binary buffer address. See buffer lifetime requirement in description. - * @param size buffer size - * @param buildOptions additional program-related build options passed to clBuildProgram() - * @return created ProgramSource object - */ - static ProgramSource fromBinary(const String& module, const String& name, - const unsigned char* binary, const size_t size, - const cv::String& buildOptions = cv::String()); - - /** @brief Describe OpenCL program in SPIR format. - * Do not call clCreateProgramWithBinary() and/or clBuildProgram(). - * - * Supports SPIR 1.2 by default (pass '-spir-std=X.Y' in buildOptions to override this behavior) - * - * Caller should guarantee binary buffer lifetime greater than ProgramSource object (and any of its copies). - * - * Programs in this format are portable between OpenCL implementations with 'khr_spir' extension: - * https://www.khronos.org/registry/OpenCL/sdk/2.0/docs/man/xhtml/cl_khr_spir.html - * (but they are not portable between different platforms: 32-bit / 64-bit) - * - * Note: these programs can't support vendor specific extensions, like 'cl_intel_subgroups'. - * - * @param module name of program owner module - * @param name unique name of program (module+name is used as key for OpenCL program caching) - * @param binary buffer address. See buffer lifetime requirement in description. - * @param size buffer size - * @param buildOptions additional program-related build options passed to clBuildProgram() - * (these options are added automatically: '-x spir' and '-spir-std=1.2') - * @return created ProgramSource object. - */ - static ProgramSource fromSPIR(const String& module, const String& name, - const unsigned char* binary, const size_t size, - const cv::String& buildOptions = cv::String()); - - //OpenCL 2.1+ only - //static Program fromSPIRV(const String& module, const String& name, - // const unsigned char* binary, const size_t size, - // const cv::String& buildOptions = cv::String()); - - struct Impl; friend struct Impl; - inline Impl* getImpl() const { return (Impl*)p; } - inline bool empty() const { return !p; } -protected: - Impl* p; -}; - -class CV_EXPORTS PlatformInfo -{ -public: - PlatformInfo() CV_NOEXCEPT; - /** - * @param id pointer cl_platform_id (cl_platform_id*) - */ - explicit PlatformInfo(void* id); - ~PlatformInfo(); - - PlatformInfo(const PlatformInfo& i); - PlatformInfo& operator =(const PlatformInfo& i); - PlatformInfo(PlatformInfo&& i) CV_NOEXCEPT; - PlatformInfo& operator = (PlatformInfo&& i) CV_NOEXCEPT; - - String name() const; - String vendor() const; - - /// See CL_PLATFORM_VERSION - String version() const; - int versionMajor() const; - int versionMinor() const; - - int deviceNumber() const; - void getDevice(Device& device, int d) const; - - struct Impl; - bool empty() const { return !p; } -protected: - Impl* p; -}; - -CV_EXPORTS CV_DEPRECATED const char* convertTypeStr(int sdepth, int ddepth, int cn, char* buf); -CV_EXPORTS const char* convertTypeStr(int sdepth, int ddepth, int cn, char* buf, size_t buf_size); -CV_EXPORTS const char* typeToStr(int t); -CV_EXPORTS const char* memopTypeToStr(int t); -CV_EXPORTS const char* vecopTypeToStr(int t); -CV_EXPORTS const char* getOpenCLErrorString(int errorCode); -CV_EXPORTS String kernelToStr(InputArray _kernel, int ddepth = -1, const char * name = NULL); -CV_EXPORTS void getPlatfomsInfo(std::vector& platform_info); - - -enum OclVectorStrategy -{ - // all matrices have its own vector width - OCL_VECTOR_OWN = 0, - // all matrices have maximal vector width among all matrices - // (useful for cases when matrices have different data types) - OCL_VECTOR_MAX = 1, - - // default strategy - OCL_VECTOR_DEFAULT = OCL_VECTOR_OWN -}; - -CV_EXPORTS int predictOptimalVectorWidth(InputArray src1, InputArray src2 = noArray(), InputArray src3 = noArray(), - InputArray src4 = noArray(), InputArray src5 = noArray(), InputArray src6 = noArray(), - InputArray src7 = noArray(), InputArray src8 = noArray(), InputArray src9 = noArray(), - OclVectorStrategy strat = OCL_VECTOR_DEFAULT); - -CV_EXPORTS int checkOptimalVectorWidth(const int *vectorWidths, - InputArray src1, InputArray src2 = noArray(), InputArray src3 = noArray(), - InputArray src4 = noArray(), InputArray src5 = noArray(), InputArray src6 = noArray(), - InputArray src7 = noArray(), InputArray src8 = noArray(), InputArray src9 = noArray(), - OclVectorStrategy strat = OCL_VECTOR_DEFAULT); - -// with OCL_VECTOR_MAX strategy -CV_EXPORTS int predictOptimalVectorWidthMax(InputArray src1, InputArray src2 = noArray(), InputArray src3 = noArray(), - InputArray src4 = noArray(), InputArray src5 = noArray(), InputArray src6 = noArray(), - InputArray src7 = noArray(), InputArray src8 = noArray(), InputArray src9 = noArray()); - -CV_EXPORTS void buildOptionsAddMatrixDescription(String& buildOptions, const String& name, InputArray _m); - -class CV_EXPORTS Image2D -{ -public: - Image2D() CV_NOEXCEPT; - - /** - @param src UMat object from which to get image properties and data - @param norm flag to enable the use of normalized channel data types - @param alias flag indicating that the image should alias the src UMat. If true, changes to the - image or src will be reflected in both objects. - */ - explicit Image2D(const UMat &src, bool norm = false, bool alias = false); - Image2D(const Image2D & i); - ~Image2D(); - - Image2D & operator = (const Image2D & i); - Image2D(Image2D &&) CV_NOEXCEPT; - Image2D &operator=(Image2D &&) CV_NOEXCEPT; - - /** Indicates if creating an aliased image should succeed. - Depends on the underlying platform and the dimensions of the UMat. - */ - static bool canCreateAlias(const UMat &u); - - /** Indicates if the image format is supported. - */ - static bool isFormatSupported(int depth, int cn, bool norm); - - void* ptr() const; -protected: - struct Impl; - Impl* p; -}; - -class CV_EXPORTS Timer -{ -public: - Timer(const Queue& q); - ~Timer(); - void start(); - void stop(); - - uint64 durationNS() const; ///< duration in nanoseconds - -protected: - struct Impl; - Impl* const p; - -private: - Timer(const Timer&); // disabled - Timer& operator=(const Timer&); // disabled -}; - -CV_EXPORTS MatAllocator* getOpenCLAllocator(); - - -class CV_EXPORTS_W OpenCLExecutionContext -{ -public: - OpenCLExecutionContext() = default; - ~OpenCLExecutionContext() = default; - - OpenCLExecutionContext(const OpenCLExecutionContext&) = default; - OpenCLExecutionContext(OpenCLExecutionContext&&) = default; - - OpenCLExecutionContext& operator=(const OpenCLExecutionContext&) = default; - OpenCLExecutionContext& operator=(OpenCLExecutionContext&&) = default; - - /** Get associated ocl::Context */ - Context& getContext() const; - /** Get the single default associated ocl::Device */ - Device& getDevice() const; - /** Get the single ocl::Queue that is associated with the ocl::Context and - * the single default ocl::Device - */ - Queue& getQueue() const; - - bool useOpenCL() const; - void setUseOpenCL(bool flag); - - /** Get OpenCL execution context of current thread. - * - * Initialize OpenCL execution context if it is empty - * - create new - * - reuse context of the main thread (threadID = 0) - */ - static OpenCLExecutionContext& getCurrent(); - - /** Get OpenCL execution context of current thread (can be empty) */ - static OpenCLExecutionContext& getCurrentRef(); - - /** Bind this OpenCL execution context to current thread. - * - * Context can't be empty. - * - * @note clFinish is not called for queue of previous execution context - */ - void bind() const; - - /** Creates new execution context with same OpenCV context and device - * - * @param q OpenCL queue - */ - OpenCLExecutionContext cloneWithNewQueue(const ocl::Queue& q) const; - /** @overload */ - OpenCLExecutionContext cloneWithNewQueue() const; - - /** @brief Creates OpenCL execution context - * OpenCV will check if available OpenCL platform has platformName name, - * then assign context to OpenCV. - * The deviceID device will be used as target device and a new command queue will be created. - * - * @note On success, ownership of one reference of the context and device is taken. - * The caller should additionally call `clRetainContext` and/or `clRetainDevice` - * to increase the reference count if it wishes to continue using them. - * - * @param platformName name of OpenCL platform to attach, this string is used to check if platform is available to OpenCV at runtime - * @param platformID ID of platform attached context was created for (cl_platform_id) - * @param context OpenCL context to be attached to OpenCV (cl_context) - * @param deviceID OpenCL device (cl_device_id) - */ - static OpenCLExecutionContext create(const std::string& platformName, void* platformID, void* context, void* deviceID); - - /** @brief Creates OpenCL execution context - * - * @param context non-empty OpenCL context - * @param device non-empty OpenCL device (must be a part of context) - * @param queue non-empty OpenCL queue for provided context and device - */ - static OpenCLExecutionContext create(const Context& context, const Device& device, const ocl::Queue& queue); - /** @overload */ - static OpenCLExecutionContext create(const Context& context, const Device& device); - - struct Impl; - inline bool empty() const { return !p; } - void release(); -protected: - std::shared_ptr p; -}; - -class OpenCLExecutionContextScope -{ - OpenCLExecutionContext ctx_; -public: - inline OpenCLExecutionContextScope(const OpenCLExecutionContext& ctx) - { - CV_Assert(!ctx.empty()); - ctx_ = OpenCLExecutionContext::getCurrentRef(); - ctx.bind(); - } - - inline ~OpenCLExecutionContextScope() - { - if (!ctx_.empty()) - { - ctx_.bind(); - } - } -}; - -#ifdef __OPENCV_BUILD -namespace internal { - -CV_EXPORTS bool isOpenCLForced(); -#define OCL_FORCE_CHECK(condition) (cv::ocl::internal::isOpenCLForced() || (condition)) - -CV_EXPORTS bool isPerformanceCheckBypassed(); -#define OCL_PERFORMANCE_CHECK(condition) (cv::ocl::internal::isPerformanceCheckBypassed() || (condition)) - -CV_EXPORTS bool isCLBuffer(UMat& u); - -} // namespace internal -#endif - -//! @} - -}} - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 OpenCV Foundation 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. +// +//M*/ + +#ifndef OPENCV_OPENCL_HPP +#define OPENCV_OPENCL_HPP + +#include "opencv2/core.hpp" +#include +#include + +namespace cv { namespace ocl { + +//! @addtogroup core_opencl +//! @{ + +CV_EXPORTS_W bool haveOpenCL(); +CV_EXPORTS_W bool useOpenCL(); +CV_EXPORTS_W bool haveAmdBlas(); +CV_EXPORTS_W bool haveAmdFft(); +CV_EXPORTS_W void setUseOpenCL(bool flag); +CV_EXPORTS_W void finish(); + +CV_EXPORTS bool haveSVM(); + +class CV_EXPORTS Context; +class CV_EXPORTS_W_SIMPLE Device; +class CV_EXPORTS Kernel; +class CV_EXPORTS Program; +class CV_EXPORTS ProgramSource; +class CV_EXPORTS Queue; +class CV_EXPORTS PlatformInfo; +class CV_EXPORTS Image2D; + +class CV_EXPORTS_W_SIMPLE Device +{ +public: + CV_WRAP Device() CV_NOEXCEPT; + explicit Device(void* d); + Device(const Device& d); + Device& operator = (const Device& d); + Device(Device&& d) CV_NOEXCEPT; + Device& operator = (Device&& d) CV_NOEXCEPT; + CV_WRAP ~Device(); + + void set(void* d); + + enum + { + TYPE_DEFAULT = (1 << 0), + TYPE_CPU = (1 << 1), + TYPE_GPU = (1 << 2), + TYPE_ACCELERATOR = (1 << 3), + TYPE_DGPU = TYPE_GPU + (1 << 16), + TYPE_IGPU = TYPE_GPU + (1 << 17), + TYPE_ALL = 0xFFFFFFFF + }; + + CV_WRAP String name() const; + CV_WRAP String extensions() const; + CV_WRAP bool isExtensionSupported(const String& extensionName) const; + CV_WRAP String version() const; + CV_WRAP String vendorName() const; + CV_WRAP String OpenCL_C_Version() const; + CV_WRAP String OpenCLVersion() const; + CV_WRAP int deviceVersionMajor() const; + CV_WRAP int deviceVersionMinor() const; + CV_WRAP String driverVersion() const; + void* ptr() const; + + CV_WRAP int type() const; + + CV_WRAP int addressBits() const; + CV_WRAP bool available() const; + CV_WRAP bool compilerAvailable() const; + CV_WRAP bool linkerAvailable() const; + + enum + { + FP_DENORM=(1 << 0), + FP_INF_NAN=(1 << 1), + FP_ROUND_TO_NEAREST=(1 << 2), + FP_ROUND_TO_ZERO=(1 << 3), + FP_ROUND_TO_INF=(1 << 4), + FP_FMA=(1 << 5), + FP_SOFT_FLOAT=(1 << 6), + FP_CORRECTLY_ROUNDED_DIVIDE_SQRT=(1 << 7) + }; + CV_WRAP int doubleFPConfig() const; + CV_WRAP int singleFPConfig() const; + CV_WRAP int halfFPConfig() const; + + /// true if 'cl_khr_fp64' extension is available + CV_WRAP bool hasFP64() const; + /// true if 'cl_khr_fp16' extension is available + CV_WRAP bool hasFP16() const; + + CV_WRAP bool endianLittle() const; + CV_WRAP bool errorCorrectionSupport() const; + + enum + { + EXEC_KERNEL=(1 << 0), + EXEC_NATIVE_KERNEL=(1 << 1) + }; + CV_WRAP int executionCapabilities() const; + + CV_WRAP size_t globalMemCacheSize() const; + + enum + { + NO_CACHE=0, + READ_ONLY_CACHE=1, + READ_WRITE_CACHE=2 + }; + CV_WRAP int globalMemCacheType() const; + CV_WRAP int globalMemCacheLineSize() const; + CV_WRAP size_t globalMemSize() const; + + CV_WRAP size_t localMemSize() const; + enum + { + NO_LOCAL_MEM=0, + LOCAL_IS_LOCAL=1, + LOCAL_IS_GLOBAL=2 + }; + CV_WRAP int localMemType() const; + CV_WRAP bool hostUnifiedMemory() const; + + CV_WRAP bool imageSupport() const; + + CV_WRAP bool imageFromBufferSupport() const; + uint imagePitchAlignment() const; + uint imageBaseAddressAlignment() const; + + /// deprecated, use isExtensionSupported() method (probably with "cl_khr_subgroups" value) + CV_WRAP bool intelSubgroupsSupport() const; + + CV_WRAP size_t image2DMaxWidth() const; + CV_WRAP size_t image2DMaxHeight() const; + + CV_WRAP size_t image3DMaxWidth() const; + CV_WRAP size_t image3DMaxHeight() const; + CV_WRAP size_t image3DMaxDepth() const; + + CV_WRAP size_t imageMaxBufferSize() const; + CV_WRAP size_t imageMaxArraySize() const; + + enum + { + UNKNOWN_VENDOR=0, + VENDOR_AMD=1, + VENDOR_INTEL=2, + VENDOR_NVIDIA=3 + }; + CV_WRAP int vendorID() const; + // FIXIT + // dev.isAMD() doesn't work for OpenCL CPU devices from AMD OpenCL platform. + // This method should use platform name instead of vendor name. + // After fix restore code in arithm.cpp: ocl_compare() + CV_WRAP inline bool isAMD() const { return vendorID() == VENDOR_AMD; } + CV_WRAP inline bool isIntel() const { return vendorID() == VENDOR_INTEL; } + CV_WRAP inline bool isNVidia() const { return vendorID() == VENDOR_NVIDIA; } + + CV_WRAP int maxClockFrequency() const; + CV_WRAP int maxComputeUnits() const; + CV_WRAP int maxConstantArgs() const; + CV_WRAP size_t maxConstantBufferSize() const; + + CV_WRAP size_t maxMemAllocSize() const; + CV_WRAP size_t maxParameterSize() const; + + CV_WRAP int maxReadImageArgs() const; + CV_WRAP int maxWriteImageArgs() const; + CV_WRAP int maxSamplers() const; + + CV_WRAP size_t maxWorkGroupSize() const; + CV_WRAP int maxWorkItemDims() const; + void maxWorkItemSizes(size_t*) const; + + CV_WRAP int memBaseAddrAlign() const; + + CV_WRAP int nativeVectorWidthChar() const; + CV_WRAP int nativeVectorWidthShort() const; + CV_WRAP int nativeVectorWidthInt() const; + CV_WRAP int nativeVectorWidthLong() const; + CV_WRAP int nativeVectorWidthFloat() const; + CV_WRAP int nativeVectorWidthDouble() const; + CV_WRAP int nativeVectorWidthHalf() const; + + CV_WRAP int preferredVectorWidthChar() const; + CV_WRAP int preferredVectorWidthShort() const; + CV_WRAP int preferredVectorWidthInt() const; + CV_WRAP int preferredVectorWidthLong() const; + CV_WRAP int preferredVectorWidthFloat() const; + CV_WRAP int preferredVectorWidthDouble() const; + CV_WRAP int preferredVectorWidthHalf() const; + + CV_WRAP size_t printfBufferSize() const; + CV_WRAP size_t profilingTimerResolution() const; + + CV_WRAP static const Device& getDefault(); + + /** + * @param d OpenCL handle (cl_device_id). clRetainDevice() is called on success. + * + * @note Ownership of the passed device is passed to OpenCV on success. + * The caller should additionally call `clRetainDevice` on it if it intends + * to continue using the device. + */ + static Device fromHandle(void* d); + + struct Impl; + inline Impl* getImpl() const { return (Impl*)p; } + inline bool empty() const { return !p; } +protected: + Impl* p; +}; + + +class CV_EXPORTS Context +{ +public: + Context() CV_NOEXCEPT; + explicit Context(int dtype); //!< @deprecated + ~Context(); + Context(const Context& c); + Context& operator= (const Context& c); + Context(Context&& c) CV_NOEXCEPT; + Context& operator = (Context&& c) CV_NOEXCEPT; + + /** @deprecated */ + bool create(); + /** @deprecated */ + bool create(int dtype); + + size_t ndevices() const; + Device& device(size_t idx) const; + Program getProg(const ProgramSource& prog, + const String& buildopt, String& errmsg); + void unloadProg(Program& prog); + + + /** Get thread-local OpenCL context (initialize if necessary) */ +#if 0 // OpenCV 5.0 + static Context& getDefault(); +#else + static Context& getDefault(bool initialize = true); +#endif + + /** @returns cl_context value */ + void* ptr() const; + + /** + * @brief Get OpenCL context property specified on context creation + * @param propertyId Property id (CL_CONTEXT_* as defined in cl_context_properties type) + * @returns Property value if property was specified on clCreateContext, or NULL if context created without the property + */ + void* getOpenCLContextProperty(int propertyId) const; + + bool useSVM() const; + void setUseSVM(bool enabled); + + /** + * @param context OpenCL handle (cl_context). clRetainContext() is called on success + */ + static Context fromHandle(void* context); + static Context fromDevice(const ocl::Device& device); + static Context create(const std::string& configuration); + + void release(); + + class CV_EXPORTS UserContext { + public: + virtual ~UserContext(); + }; + template + inline void setUserContext(const std::shared_ptr& userContext) { + setUserContext(typeid(T), userContext); + } + template + inline std::shared_ptr getUserContext() { + return std::dynamic_pointer_cast(getUserContext(typeid(T))); + } + void setUserContext(std::type_index typeId, const std::shared_ptr& userContext); + std::shared_ptr getUserContext(std::type_index typeId); + + struct Impl; + inline Impl* getImpl() const { return (Impl*)p; } + inline bool empty() const { return !p; } +// TODO OpenCV 5.0 +//protected: + Impl* p; +}; + +/** @deprecated */ +class CV_EXPORTS Platform +{ +public: + Platform() CV_NOEXCEPT; + ~Platform(); + Platform(const Platform& p); + Platform& operator = (const Platform& p); + Platform(Platform&& p) CV_NOEXCEPT; + Platform& operator = (Platform&& p) CV_NOEXCEPT; + + void* ptr() const; + + /** @deprecated */ + static Platform& getDefault(); + + struct Impl; + inline Impl* getImpl() const { return (Impl*)p; } + inline bool empty() const { return !p; } +protected: + Impl* p; +}; + +/** @brief Attaches OpenCL context to OpenCV +@note + OpenCV will check if available OpenCL platform has platformName name, then assign context to + OpenCV and call `clRetainContext` function. The deviceID device will be used as target device and + new command queue will be created. +@param platformName name of OpenCL platform to attach, this string is used to check if platform is available to OpenCV at runtime +@param platformID ID of platform attached context was created for +@param context OpenCL context to be attached to OpenCV +@param deviceID ID of device, must be created from attached context +*/ +CV_EXPORTS void attachContext(const String& platformName, void* platformID, void* context, void* deviceID); + +/** @brief Convert OpenCL buffer to UMat +@note + OpenCL buffer (cl_mem_buffer) should contain 2D image data, compatible with OpenCV. Memory + content is not copied from `clBuffer` to UMat. Instead, buffer handle assigned to UMat and + `clRetainMemObject` is called. +@param cl_mem_buffer source clBuffer handle +@param step num of bytes in single row +@param rows number of rows +@param cols number of cols +@param type OpenCV type of image +@param dst destination UMat +*/ +CV_EXPORTS void convertFromBuffer(void* cl_mem_buffer, size_t step, int rows, int cols, int type, UMat& dst); + +/** @brief Convert OpenCL image2d_t to UMat +@note + OpenCL `image2d_t` (cl_mem_image), should be compatible with OpenCV UMat formats. Memory content + is copied from image to UMat with `clEnqueueCopyImageToBuffer` function. +@param cl_mem_image source image2d_t handle +@param dst destination UMat +*/ +CV_EXPORTS void convertFromImage(void* cl_mem_image, UMat& dst); + +// TODO Move to internal header +/// @deprecated +void initializeContextFromHandle(Context& ctx, void* platform, void* context, void* device); + +class CV_EXPORTS Queue +{ +public: + Queue() CV_NOEXCEPT; + explicit Queue(const Context& c, const Device& d=Device()); + ~Queue(); + Queue(const Queue& q); + Queue& operator = (const Queue& q); + Queue(Queue&& q) CV_NOEXCEPT; + Queue& operator = (Queue&& q) CV_NOEXCEPT; + + bool create(const Context& c=Context(), const Device& d=Device()); + void finish(); + void* ptr() const; + static Queue& getDefault(); + + /// @brief Returns OpenCL command queue with enable profiling mode support + const Queue& getProfilingQueue() const; + + struct Impl; friend struct Impl; + inline Impl* getImpl() const { return p; } + inline bool empty() const { return !p; } +protected: + Impl* p; +}; + + +class CV_EXPORTS KernelArg +{ +public: + enum { LOCAL=1, READ_ONLY=2, WRITE_ONLY=4, READ_WRITE=6, CONSTANT=8, PTR_ONLY = 16, NO_SIZE=256 }; + KernelArg(int _flags, UMat* _m, int wscale=1, int iwscale=1, const void* _obj=0, size_t _sz=0); + KernelArg() CV_NOEXCEPT; + + static KernelArg Local(size_t localMemSize) + { return KernelArg(LOCAL, 0, 1, 1, 0, localMemSize); } + static KernelArg PtrWriteOnly(const UMat& m) + { return KernelArg(PTR_ONLY+WRITE_ONLY, (UMat*)&m); } + static KernelArg PtrReadOnly(const UMat& m) + { return KernelArg(PTR_ONLY+READ_ONLY, (UMat*)&m); } + static KernelArg PtrReadWrite(const UMat& m) + { return KernelArg(PTR_ONLY+READ_WRITE, (UMat*)&m); } + static KernelArg ReadWrite(const UMat& m, int wscale=1, int iwscale=1) + { return KernelArg(READ_WRITE, (UMat*)&m, wscale, iwscale); } + static KernelArg ReadWriteNoSize(const UMat& m, int wscale=1, int iwscale=1) + { return KernelArg(READ_WRITE+NO_SIZE, (UMat*)&m, wscale, iwscale); } + static KernelArg ReadOnly(const UMat& m, int wscale=1, int iwscale=1) + { return KernelArg(READ_ONLY, (UMat*)&m, wscale, iwscale); } + static KernelArg WriteOnly(const UMat& m, int wscale=1, int iwscale=1) + { return KernelArg(WRITE_ONLY, (UMat*)&m, wscale, iwscale); } + static KernelArg ReadOnlyNoSize(const UMat& m, int wscale=1, int iwscale=1) + { return KernelArg(READ_ONLY+NO_SIZE, (UMat*)&m, wscale, iwscale); } + static KernelArg WriteOnlyNoSize(const UMat& m, int wscale=1, int iwscale=1) + { return KernelArg(WRITE_ONLY+NO_SIZE, (UMat*)&m, wscale, iwscale); } + static KernelArg Constant(const Mat& m); + template static KernelArg Constant(const _Tp* arr, size_t n) + { return KernelArg(CONSTANT, 0, 1, 1, (void*)arr, n); } + + int flags; + UMat* m; + const void* obj; + size_t sz; + int wscale, iwscale; +}; + + +class CV_EXPORTS Kernel +{ +public: + Kernel() CV_NOEXCEPT; + Kernel(const char* kname, const Program& prog); + Kernel(const char* kname, const ProgramSource& prog, + const String& buildopts = String(), String* errmsg=0); + ~Kernel(); + Kernel(const Kernel& k); + Kernel& operator = (const Kernel& k); + Kernel(Kernel&& k) CV_NOEXCEPT; + Kernel& operator = (Kernel&& k) CV_NOEXCEPT; + + bool empty() const; + bool create(const char* kname, const Program& prog); + bool create(const char* kname, const ProgramSource& prog, + const String& buildopts, String* errmsg=0); + + int set(int i, const void* value, size_t sz); + int set(int i, const Image2D& image2D); + int set(int i, const UMat& m); + int set(int i, const KernelArg& arg); + template int set(int i, const _Tp& value) + { return set(i, &value, sizeof(value)); } + + +protected: + template inline + int set_args_(int i, const _Tp0& a0) { return set(i, a0); } + template inline + int set_args_(int i, const _Tp0& a0, const _Tps&... rest_args) { i = set(i, a0); return set_args_(i, rest_args...); } +public: + /** @brief Setup OpenCL Kernel arguments. + Avoid direct using of set(i, ...) methods. + @code + bool ok = kernel + .args( + srcUMat, dstUMat, + (float)some_float_param + ).run(ndims, globalSize, localSize); + if (!ok) return false; + @endcode + */ + template inline + Kernel& args(const _Tps&... kernel_args) { set_args_(0, kernel_args...); return *this; } + + /** @brief Run the OpenCL kernel (globalsize value may be adjusted) + + @param dims the work problem dimensions. It is the length of globalsize and localsize. It can be either 1, 2 or 3. + @param globalsize work items for each dimension. It is not the final globalsize passed to + OpenCL. Each dimension will be adjusted to the nearest integer divisible by the corresponding + value in localsize. If localsize is NULL, it will still be adjusted depending on dims. The + adjusted values are greater than or equal to the original values. + @param localsize work-group size for each dimension. + @param sync specify whether to wait for OpenCL computation to finish before return. + @param q command queue + + @note Use run_() if your kernel code doesn't support adjusted globalsize. + */ + bool run(int dims, size_t globalsize[], + size_t localsize[], bool sync, const Queue& q=Queue()); + + /** @brief Run the OpenCL kernel + * + * @param dims the work problem dimensions. It is the length of globalsize and localsize. It can be either 1, 2 or 3. + * @param globalsize work items for each dimension. This value is passed to OpenCL without changes. + * @param localsize work-group size for each dimension. + * @param sync specify whether to wait for OpenCL computation to finish before return. + * @param q command queue + */ + bool run_(int dims, size_t globalsize[], size_t localsize[], bool sync, const Queue& q=Queue()); + + bool runTask(bool sync, const Queue& q=Queue()); + + /** @brief Similar to synchronized run_() call with returning of kernel execution time + * + * Separate OpenCL command queue may be used (with CL_QUEUE_PROFILING_ENABLE) + * @return Execution time in nanoseconds or negative number on error + */ + int64 runProfiling(int dims, size_t globalsize[], size_t localsize[], const Queue& q=Queue()); + + size_t workGroupSize() const; + size_t preferedWorkGroupSizeMultiple() const; + bool compileWorkGroupSize(size_t wsz[]) const; + size_t localMemSize() const; + + void* ptr() const; + struct Impl; + +protected: + Impl* p; +}; + +class CV_EXPORTS Program +{ +public: + Program() CV_NOEXCEPT; + Program(const ProgramSource& src, + const String& buildflags, String& errmsg); + Program(const Program& prog); + Program& operator = (const Program& prog); + Program(Program&& prog) CV_NOEXCEPT; + Program& operator = (Program&& prog) CV_NOEXCEPT; + ~Program(); + + bool create(const ProgramSource& src, + const String& buildflags, String& errmsg); + + void* ptr() const; + + /** + * @brief Query device-specific program binary. + * + * Returns RAW OpenCL executable binary without additional attachments. + * + * @sa ProgramSource::fromBinary + * + * @param[out] binary output buffer + */ + void getBinary(std::vector& binary) const; + + struct Impl; friend struct Impl; + inline Impl* getImpl() const { return (Impl*)p; } + inline bool empty() const { return !p; } +protected: + Impl* p; +public: +#ifndef OPENCV_REMOVE_DEPRECATED_API + // TODO Remove this + CV_DEPRECATED bool read(const String& buf, const String& buildflags); // removed, use ProgramSource instead + CV_DEPRECATED bool write(String& buf) const; // removed, use getBinary() method instead (RAW OpenCL binary) + CV_DEPRECATED const ProgramSource& source() const; // implementation removed + CV_DEPRECATED String getPrefix() const; // deprecated, implementation replaced + CV_DEPRECATED static String getPrefix(const String& buildflags); // deprecated, implementation replaced +#endif +}; + + +class CV_EXPORTS ProgramSource +{ +public: + typedef uint64 hash_t; // deprecated + + ProgramSource() CV_NOEXCEPT; + explicit ProgramSource(const String& module, const String& name, const String& codeStr, const String& codeHash); + explicit ProgramSource(const String& prog); // deprecated + explicit ProgramSource(const char* prog); // deprecated + ~ProgramSource(); + ProgramSource(const ProgramSource& prog); + ProgramSource& operator = (const ProgramSource& prog); + ProgramSource(ProgramSource&& prog) CV_NOEXCEPT; + ProgramSource& operator = (ProgramSource&& prog) CV_NOEXCEPT; + + const String& source() const; // deprecated + hash_t hash() const; // deprecated + + + /** @brief Describe OpenCL program binary. + * Do not call clCreateProgramWithBinary() and/or clBuildProgram(). + * + * Caller should guarantee binary buffer lifetime greater than ProgramSource object (and any of its copies). + * + * This kind of binary is not portable between platforms in general - it is specific to OpenCL vendor / device / driver version. + * + * @param module name of program owner module + * @param name unique name of program (module+name is used as key for OpenCL program caching) + * @param binary buffer address. See buffer lifetime requirement in description. + * @param size buffer size + * @param buildOptions additional program-related build options passed to clBuildProgram() + * @return created ProgramSource object + */ + static ProgramSource fromBinary(const String& module, const String& name, + const unsigned char* binary, const size_t size, + const cv::String& buildOptions = cv::String()); + + /** @brief Describe OpenCL program in SPIR format. + * Do not call clCreateProgramWithBinary() and/or clBuildProgram(). + * + * Supports SPIR 1.2 by default (pass '-spir-std=X.Y' in buildOptions to override this behavior) + * + * Caller should guarantee binary buffer lifetime greater than ProgramSource object (and any of its copies). + * + * Programs in this format are portable between OpenCL implementations with 'khr_spir' extension: + * https://www.khronos.org/registry/OpenCL/sdk/2.0/docs/man/xhtml/cl_khr_spir.html + * (but they are not portable between different platforms: 32-bit / 64-bit) + * + * Note: these programs can't support vendor specific extensions, like 'cl_intel_subgroups'. + * + * @param module name of program owner module + * @param name unique name of program (module+name is used as key for OpenCL program caching) + * @param binary buffer address. See buffer lifetime requirement in description. + * @param size buffer size + * @param buildOptions additional program-related build options passed to clBuildProgram() + * (these options are added automatically: '-x spir' and '-spir-std=1.2') + * @return created ProgramSource object. + */ + static ProgramSource fromSPIR(const String& module, const String& name, + const unsigned char* binary, const size_t size, + const cv::String& buildOptions = cv::String()); + + //OpenCL 2.1+ only + //static Program fromSPIRV(const String& module, const String& name, + // const unsigned char* binary, const size_t size, + // const cv::String& buildOptions = cv::String()); + + struct Impl; friend struct Impl; + inline Impl* getImpl() const { return (Impl*)p; } + inline bool empty() const { return !p; } +protected: + Impl* p; +}; + +class CV_EXPORTS PlatformInfo +{ +public: + PlatformInfo() CV_NOEXCEPT; + /** + * @param id pointer cl_platform_id (cl_platform_id*) + */ + explicit PlatformInfo(void* id); + ~PlatformInfo(); + + PlatformInfo(const PlatformInfo& i); + PlatformInfo& operator =(const PlatformInfo& i); + PlatformInfo(PlatformInfo&& i) CV_NOEXCEPT; + PlatformInfo& operator = (PlatformInfo&& i) CV_NOEXCEPT; + + String name() const; + String vendor() const; + + /// See CL_PLATFORM_VERSION + String version() const; + int versionMajor() const; + int versionMinor() const; + + int deviceNumber() const; + void getDevice(Device& device, int d) const; + + struct Impl; + bool empty() const { return !p; } +protected: + Impl* p; +}; + +CV_EXPORTS CV_DEPRECATED const char* convertTypeStr(int sdepth, int ddepth, int cn, char* buf); +CV_EXPORTS const char* convertTypeStr(int sdepth, int ddepth, int cn, char* buf, size_t buf_size); +CV_EXPORTS const char* typeToStr(int t); +CV_EXPORTS const char* memopTypeToStr(int t); +CV_EXPORTS const char* vecopTypeToStr(int t); +CV_EXPORTS const char* getOpenCLErrorString(int errorCode); +CV_EXPORTS String kernelToStr(InputArray _kernel, int ddepth = -1, const char * name = NULL); +CV_EXPORTS void getPlatfomsInfo(std::vector& platform_info); + + +enum OclVectorStrategy +{ + // all matrices have its own vector width + OCL_VECTOR_OWN = 0, + // all matrices have maximal vector width among all matrices + // (useful for cases when matrices have different data types) + OCL_VECTOR_MAX = 1, + + // default strategy + OCL_VECTOR_DEFAULT = OCL_VECTOR_OWN +}; + +CV_EXPORTS int predictOptimalVectorWidth(InputArray src1, InputArray src2 = noArray(), InputArray src3 = noArray(), + InputArray src4 = noArray(), InputArray src5 = noArray(), InputArray src6 = noArray(), + InputArray src7 = noArray(), InputArray src8 = noArray(), InputArray src9 = noArray(), + OclVectorStrategy strat = OCL_VECTOR_DEFAULT); + +CV_EXPORTS int checkOptimalVectorWidth(const int *vectorWidths, + InputArray src1, InputArray src2 = noArray(), InputArray src3 = noArray(), + InputArray src4 = noArray(), InputArray src5 = noArray(), InputArray src6 = noArray(), + InputArray src7 = noArray(), InputArray src8 = noArray(), InputArray src9 = noArray(), + OclVectorStrategy strat = OCL_VECTOR_DEFAULT); + +// with OCL_VECTOR_MAX strategy +CV_EXPORTS int predictOptimalVectorWidthMax(InputArray src1, InputArray src2 = noArray(), InputArray src3 = noArray(), + InputArray src4 = noArray(), InputArray src5 = noArray(), InputArray src6 = noArray(), + InputArray src7 = noArray(), InputArray src8 = noArray(), InputArray src9 = noArray()); + +CV_EXPORTS void buildOptionsAddMatrixDescription(String& buildOptions, const String& name, InputArray _m); + +class CV_EXPORTS Image2D +{ +public: + Image2D() CV_NOEXCEPT; + + /** + @param src UMat object from which to get image properties and data + @param norm flag to enable the use of normalized channel data types + @param alias flag indicating that the image should alias the src UMat. If true, changes to the + image or src will be reflected in both objects. + */ + explicit Image2D(const UMat &src, bool norm = false, bool alias = false); + Image2D(const Image2D & i); + ~Image2D(); + + Image2D & operator = (const Image2D & i); + Image2D(Image2D &&) CV_NOEXCEPT; + Image2D &operator=(Image2D &&) CV_NOEXCEPT; + + /** Indicates if creating an aliased image should succeed. + Depends on the underlying platform and the dimensions of the UMat. + */ + static bool canCreateAlias(const UMat &u); + + /** Indicates if the image format is supported. + */ + static bool isFormatSupported(int depth, int cn, bool norm); + + void* ptr() const; +protected: + struct Impl; + Impl* p; +}; + +class CV_EXPORTS Timer +{ +public: + Timer(const Queue& q); + ~Timer(); + void start(); + void stop(); + + uint64 durationNS() const; ///< duration in nanoseconds + +protected: + struct Impl; + Impl* const p; + +private: + Timer(const Timer&); // disabled + Timer& operator=(const Timer&); // disabled +}; + +CV_EXPORTS MatAllocator* getOpenCLAllocator(); + + +class CV_EXPORTS_W OpenCLExecutionContext +{ +public: + OpenCLExecutionContext() = default; + ~OpenCLExecutionContext() = default; + + OpenCLExecutionContext(const OpenCLExecutionContext&) = default; + OpenCLExecutionContext(OpenCLExecutionContext&&) = default; + + OpenCLExecutionContext& operator=(const OpenCLExecutionContext&) = default; + OpenCLExecutionContext& operator=(OpenCLExecutionContext&&) = default; + + /** Get associated ocl::Context */ + Context& getContext() const; + /** Get the single default associated ocl::Device */ + Device& getDevice() const; + /** Get the single ocl::Queue that is associated with the ocl::Context and + * the single default ocl::Device + */ + Queue& getQueue() const; + + bool useOpenCL() const; + void setUseOpenCL(bool flag); + + /** Get OpenCL execution context of current thread. + * + * Initialize OpenCL execution context if it is empty + * - create new + * - reuse context of the main thread (threadID = 0) + */ + static OpenCLExecutionContext& getCurrent(); + + /** Get OpenCL execution context of current thread (can be empty) */ + static OpenCLExecutionContext& getCurrentRef(); + + /** Bind this OpenCL execution context to current thread. + * + * Context can't be empty. + * + * @note clFinish is not called for queue of previous execution context + */ + void bind() const; + + /** Creates new execution context with same OpenCV context and device + * + * @param q OpenCL queue + */ + OpenCLExecutionContext cloneWithNewQueue(const ocl::Queue& q) const; + /** @overload */ + OpenCLExecutionContext cloneWithNewQueue() const; + + /** @brief Creates OpenCL execution context + * OpenCV will check if available OpenCL platform has platformName name, + * then assign context to OpenCV. + * The deviceID device will be used as target device and a new command queue will be created. + * + * @note On success, ownership of one reference of the context and device is taken. + * The caller should additionally call `clRetainContext` and/or `clRetainDevice` + * to increase the reference count if it wishes to continue using them. + * + * @param platformName name of OpenCL platform to attach, this string is used to check if platform is available to OpenCV at runtime + * @param platformID ID of platform attached context was created for (cl_platform_id) + * @param context OpenCL context to be attached to OpenCV (cl_context) + * @param deviceID OpenCL device (cl_device_id) + */ + static OpenCLExecutionContext create(const std::string& platformName, void* platformID, void* context, void* deviceID); + + /** @brief Creates OpenCL execution context + * + * @param context non-empty OpenCL context + * @param device non-empty OpenCL device (must be a part of context) + * @param queue non-empty OpenCL queue for provided context and device + */ + static OpenCLExecutionContext create(const Context& context, const Device& device, const ocl::Queue& queue); + /** @overload */ + static OpenCLExecutionContext create(const Context& context, const Device& device); + + struct Impl; + inline bool empty() const { return !p; } + void release(); +protected: + std::shared_ptr p; +}; + +class OpenCLExecutionContextScope +{ + OpenCLExecutionContext ctx_; +public: + inline OpenCLExecutionContextScope(const OpenCLExecutionContext& ctx) + { + CV_Assert(!ctx.empty()); + ctx_ = OpenCLExecutionContext::getCurrentRef(); + ctx.bind(); + } + + inline ~OpenCLExecutionContextScope() + { + if (!ctx_.empty()) + { + ctx_.bind(); + } + } +}; + +#ifdef __OPENCV_BUILD +namespace internal { + +CV_EXPORTS bool isOpenCLForced(); +#define OCL_FORCE_CHECK(condition) (cv::ocl::internal::isOpenCLForced() || (condition)) + +CV_EXPORTS bool isPerformanceCheckBypassed(); +#define OCL_PERFORMANCE_CHECK(condition) (cv::ocl::internal::isPerformanceCheckBypassed() || (condition)) + +CV_EXPORTS bool isCLBuffer(UMat& u); + +} // namespace internal +#endif + +//! @} + +}} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/ocl_genbase.hpp b/3rdParty/opencv-4.11.0/opencv2/core/ocl_genbase.hpp index 5334cf1f4f..5366250a55 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/ocl_genbase.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/ocl_genbase.hpp @@ -1,69 +1,69 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 OpenCV Foundation 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. -// -//M*/ - -#ifndef OPENCV_OPENCL_GENBASE_HPP -#define OPENCV_OPENCL_GENBASE_HPP - -//! @cond IGNORED - -namespace cv { -namespace ocl { - -class ProgramSource; - -namespace internal { - -struct CV_EXPORTS ProgramEntry -{ - const char* module; - const char* name; - const char* programCode; - const char* programHash; - ProgramSource* pProgramSource; - - operator ProgramSource& () const; -}; - -} } } // namespace - -//! @endcond - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 OpenCV Foundation 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. +// +//M*/ + +#ifndef OPENCV_OPENCL_GENBASE_HPP +#define OPENCV_OPENCL_GENBASE_HPP + +//! @cond IGNORED + +namespace cv { +namespace ocl { + +class ProgramSource; + +namespace internal { + +struct CV_EXPORTS ProgramEntry +{ + const char* module; + const char* name; + const char* programCode; + const char* programHash; + ProgramSource* pProgramSource; + + operator ProgramSource& () const; +}; + +} } } // namespace + +//! @endcond + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/ocl_defs.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/ocl_defs.hpp index 14df750fc7..1369d14b85 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/ocl_defs.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/ocl_defs.hpp @@ -1,82 +1,82 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -// Copyright (C) 2014, Advanced Micro Devices, Inc., all rights reserved. -// Third party copyrights are property of their respective owners. - -#ifndef OPENCV_CORE_OPENCL_DEFS_HPP -#define OPENCV_CORE_OPENCL_DEFS_HPP - -#include "opencv2/core/utility.hpp" -#include "cvconfig.h" - -namespace cv { namespace ocl { -#ifdef HAVE_OPENCL -/// Call is similar to useOpenCL() but doesn't try to load OpenCL runtime or create OpenCL context -CV_EXPORTS bool isOpenCLActivated(); -#else -static inline bool isOpenCLActivated() { return false; } -#endif -}} // namespace - - -//#define CV_OPENCL_RUN_ASSERT - -#ifdef HAVE_OPENCL - -#ifdef CV_OPENCL_RUN_VERBOSE -#define CV_OCL_RUN_(condition, func, ...) \ - { \ - if (cv::ocl::isOpenCLActivated() && (condition) && func) \ - { \ - printf("%s: OpenCL implementation is running\n", CV_Func); \ - fflush(stdout); \ - CV_IMPL_ADD(CV_IMPL_OCL); \ - return __VA_ARGS__; \ - } \ - else \ - { \ - printf("%s: Plain implementation is running\n", CV_Func); \ - fflush(stdout); \ - } \ - } -#elif defined CV_OPENCL_RUN_ASSERT -#define CV_OCL_RUN_(condition, func, ...) \ - { \ - if (cv::ocl::isOpenCLActivated() && (condition)) \ - { \ - if(func) \ - { \ - CV_IMPL_ADD(CV_IMPL_OCL); \ - } \ - else \ - { \ - CV_Error(cv::Error::StsAssert, #func); \ - } \ - return __VA_ARGS__; \ - } \ - } -#else -#define CV_OCL_RUN_(condition, func, ...) \ -try \ -{ \ - if (cv::ocl::isOpenCLActivated() && (condition) && func) \ - { \ - CV_IMPL_ADD(CV_IMPL_OCL); \ - return __VA_ARGS__; \ - } \ -} \ -catch (const cv::Exception& e) \ -{ \ - CV_UNUSED(e); /* TODO: Add some logging here */ \ -} -#endif - -#else -#define CV_OCL_RUN_(condition, func, ...) -#endif - -#define CV_OCL_RUN(condition, func) CV_OCL_RUN_(condition, func) - -#endif // OPENCV_CORE_OPENCL_DEFS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +// Copyright (C) 2014, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. + +#ifndef OPENCV_CORE_OPENCL_DEFS_HPP +#define OPENCV_CORE_OPENCL_DEFS_HPP + +#include "opencv2/core/utility.hpp" +#include "cvconfig.h" + +namespace cv { namespace ocl { +#ifdef HAVE_OPENCL +/// Call is similar to useOpenCL() but doesn't try to load OpenCL runtime or create OpenCL context +CV_EXPORTS bool isOpenCLActivated(); +#else +static inline bool isOpenCLActivated() { return false; } +#endif +}} // namespace + + +//#define CV_OPENCL_RUN_ASSERT + +#ifdef HAVE_OPENCL + +#ifdef CV_OPENCL_RUN_VERBOSE +#define CV_OCL_RUN_(condition, func, ...) \ + { \ + if (cv::ocl::isOpenCLActivated() && (condition) && func) \ + { \ + printf("%s: OpenCL implementation is running\n", CV_Func); \ + fflush(stdout); \ + CV_IMPL_ADD(CV_IMPL_OCL); \ + return __VA_ARGS__; \ + } \ + else \ + { \ + printf("%s: Plain implementation is running\n", CV_Func); \ + fflush(stdout); \ + } \ + } +#elif defined CV_OPENCL_RUN_ASSERT +#define CV_OCL_RUN_(condition, func, ...) \ + { \ + if (cv::ocl::isOpenCLActivated() && (condition)) \ + { \ + if(func) \ + { \ + CV_IMPL_ADD(CV_IMPL_OCL); \ + } \ + else \ + { \ + CV_Error(cv::Error::StsAssert, #func); \ + } \ + return __VA_ARGS__; \ + } \ + } +#else +#define CV_OCL_RUN_(condition, func, ...) \ +try \ +{ \ + if (cv::ocl::isOpenCLActivated() && (condition) && func) \ + { \ + CV_IMPL_ADD(CV_IMPL_OCL); \ + return __VA_ARGS__; \ + } \ +} \ +catch (const cv::Exception& e) \ +{ \ + CV_UNUSED(e); /* TODO: Add some logging here */ \ +} +#endif + +#else +#define CV_OCL_RUN_(condition, func, ...) +#endif + +#define CV_OCL_RUN(condition, func) CV_OCL_RUN_(condition, func) + +#endif // OPENCV_CORE_OPENCL_DEFS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/opencl_info.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/opencl_info.hpp index 845efba9fc..06c5f9b94d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/opencl_info.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/opencl_info.hpp @@ -1,213 +1,213 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#include -#include - -#include -#include - -#ifndef DUMP_CONFIG_PROPERTY -#define DUMP_CONFIG_PROPERTY(...) -#endif - -#ifndef DUMP_MESSAGE_STDOUT -#define DUMP_MESSAGE_STDOUT(...) do { std::cout << __VA_ARGS__ << std::endl; } while (false) -#endif - -namespace cv { - -namespace { -static std::string bytesToStringRepr(size_t value) -{ - size_t b = value % 1024; - value /= 1024; - - size_t kb = value % 1024; - value /= 1024; - - size_t mb = value % 1024; - value /= 1024; - - size_t gb = value; - - std::ostringstream stream; - - if (gb > 0) - stream << gb << " GB "; - if (mb > 0) - stream << mb << " MB "; - if (kb > 0) - stream << kb << " KB "; - if (b > 0) - stream << b << " B"; - - std::string s = stream.str(); - if (s[s.size() - 1] == ' ') - s = s.substr(0, s.size() - 1); - return s; -} - -static String getDeviceTypeString(const cv::ocl::Device& device) -{ - if (device.type() == cv::ocl::Device::TYPE_CPU) { - return "CPU"; - } - - if (device.type() == cv::ocl::Device::TYPE_GPU) { - if (device.hostUnifiedMemory()) { - return "iGPU"; - } else { - return "dGPU"; - } - } - - return "unknown"; -} -} // namespace - -static void dumpOpenCLInformation() -{ - using namespace cv::ocl; - - try - { - if (!haveOpenCL() || !useOpenCL()) - { - DUMP_MESSAGE_STDOUT("OpenCL is disabled"); - DUMP_CONFIG_PROPERTY("cv_ocl", "disabled"); - return; - } - - std::vector platforms; - cv::ocl::getPlatfomsInfo(platforms); - if (platforms.empty()) - { - DUMP_MESSAGE_STDOUT("OpenCL is not available"); - DUMP_CONFIG_PROPERTY("cv_ocl", "not available"); - return; - } - - DUMP_MESSAGE_STDOUT("OpenCL Platforms: "); - for (size_t i = 0; i < platforms.size(); i++) - { - const PlatformInfo* platform = &platforms[i]; - DUMP_MESSAGE_STDOUT(" " << platform->name()); - Device current_device; - for (int j = 0; j < platform->deviceNumber(); j++) - { - platform->getDevice(current_device, j); - String deviceTypeStr = getDeviceTypeString(current_device); - DUMP_MESSAGE_STDOUT( " " << deviceTypeStr << ": " << current_device.name() << " (" << current_device.version() << ")"); - DUMP_CONFIG_PROPERTY( cv::format("cv_ocl_platform_%d_device_%d", (int)i, j ), - cv::format("(Platform=%s)(Type=%s)(Name=%s)(Version=%s)", - platform->name().c_str(), deviceTypeStr.c_str(), current_device.name().c_str(), current_device.version().c_str()) ); - } - } - const Device& device = Device::getDefault(); - if (!device.available()) - CV_Error(Error::OpenCLInitError, "OpenCL device is not available"); - - DUMP_MESSAGE_STDOUT("Current OpenCL device: "); - - String deviceTypeStr = getDeviceTypeString(device); - DUMP_MESSAGE_STDOUT(" Type = " << deviceTypeStr); - DUMP_CONFIG_PROPERTY("cv_ocl_current_deviceType", deviceTypeStr); - - DUMP_MESSAGE_STDOUT(" Name = " << device.name()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_deviceName", device.name()); - - DUMP_MESSAGE_STDOUT(" Version = " << device.version()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_deviceVersion", device.version()); - - DUMP_MESSAGE_STDOUT(" Driver version = " << device.driverVersion()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_driverVersion", device.driverVersion()); - - DUMP_MESSAGE_STDOUT(" Address bits = " << device.addressBits()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_addressBits", device.addressBits()); - - DUMP_MESSAGE_STDOUT(" Compute units = " << device.maxComputeUnits()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_maxComputeUnits", device.maxComputeUnits()); - - DUMP_MESSAGE_STDOUT(" Max work group size = " << device.maxWorkGroupSize()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_maxWorkGroupSize", device.maxWorkGroupSize()); - - std::string localMemorySizeStr = bytesToStringRepr(device.localMemSize()); - DUMP_MESSAGE_STDOUT(" Local memory size = " << localMemorySizeStr); - DUMP_CONFIG_PROPERTY("cv_ocl_current_localMemSize", device.localMemSize()); - - std::string maxMemAllocSizeStr = bytesToStringRepr(device.maxMemAllocSize()); - DUMP_MESSAGE_STDOUT(" Max memory allocation size = " << maxMemAllocSizeStr); - DUMP_CONFIG_PROPERTY("cv_ocl_current_maxMemAllocSize", device.maxMemAllocSize()); - - const char* doubleSupportStr = device.hasFP64() ? "Yes" : "No"; - DUMP_MESSAGE_STDOUT(" Double support = " << doubleSupportStr); - DUMP_CONFIG_PROPERTY("cv_ocl_current_haveDoubleSupport", device.hasFP64()); - - const char* halfSupportStr = device.hasFP16() ? "Yes" : "No"; - DUMP_MESSAGE_STDOUT(" Half support = " << halfSupportStr); - DUMP_CONFIG_PROPERTY("cv_ocl_current_haveHalfSupport", device.hasFP16()); - - const char* isUnifiedMemoryStr = device.hostUnifiedMemory() ? "Yes" : "No"; - DUMP_MESSAGE_STDOUT(" Host unified memory = " << isUnifiedMemoryStr); - DUMP_CONFIG_PROPERTY("cv_ocl_current_hostUnifiedMemory", device.hostUnifiedMemory()); - - DUMP_MESSAGE_STDOUT(" Device extensions:"); - String extensionsStr = device.extensions(); - size_t pos = 0; - while (pos < extensionsStr.size()) - { - size_t pos2 = extensionsStr.find(' ', pos); - if (pos2 == String::npos) - pos2 = extensionsStr.size(); - if (pos2 > pos) - { - String extensionName = extensionsStr.substr(pos, pos2 - pos); - DUMP_MESSAGE_STDOUT(" " << extensionName); - } - pos = pos2 + 1; - } - DUMP_CONFIG_PROPERTY("cv_ocl_current_extensions", extensionsStr); - - const char* haveAmdBlasStr = haveAmdBlas() ? "Yes" : "No"; - DUMP_MESSAGE_STDOUT(" Has AMD Blas = " << haveAmdBlasStr); - DUMP_CONFIG_PROPERTY("cv_ocl_current_AmdBlas", haveAmdBlas()); - - const char* haveAmdFftStr = haveAmdFft() ? "Yes" : "No"; - DUMP_MESSAGE_STDOUT(" Has AMD Fft = " << haveAmdFftStr); - DUMP_CONFIG_PROPERTY("cv_ocl_current_AmdFft", haveAmdFft()); - - - DUMP_MESSAGE_STDOUT(" Preferred vector width char = " << device.preferredVectorWidthChar()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthChar", device.preferredVectorWidthChar()); - - DUMP_MESSAGE_STDOUT(" Preferred vector width short = " << device.preferredVectorWidthShort()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthShort", device.preferredVectorWidthShort()); - - DUMP_MESSAGE_STDOUT(" Preferred vector width int = " << device.preferredVectorWidthInt()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthInt", device.preferredVectorWidthInt()); - - DUMP_MESSAGE_STDOUT(" Preferred vector width long = " << device.preferredVectorWidthLong()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthLong", device.preferredVectorWidthLong()); - - DUMP_MESSAGE_STDOUT(" Preferred vector width float = " << device.preferredVectorWidthFloat()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthFloat", device.preferredVectorWidthFloat()); - - DUMP_MESSAGE_STDOUT(" Preferred vector width double = " << device.preferredVectorWidthDouble()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthDouble", device.preferredVectorWidthDouble()); - - DUMP_MESSAGE_STDOUT(" Preferred vector width half = " << device.preferredVectorWidthHalf()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthHalf", device.preferredVectorWidthHalf()); - } - catch (...) - { - DUMP_MESSAGE_STDOUT("Exception. Can't dump OpenCL info"); - DUMP_MESSAGE_STDOUT("OpenCL device not available"); - DUMP_CONFIG_PROPERTY("cv_ocl", "not available"); - } -} -#undef DUMP_MESSAGE_STDOUT -#undef DUMP_CONFIG_PROPERTY - -} // namespace +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#include +#include + +#include +#include + +#ifndef DUMP_CONFIG_PROPERTY +#define DUMP_CONFIG_PROPERTY(...) +#endif + +#ifndef DUMP_MESSAGE_STDOUT +#define DUMP_MESSAGE_STDOUT(...) do { std::cout << __VA_ARGS__ << std::endl; } while (false) +#endif + +namespace cv { + +namespace { +static std::string bytesToStringRepr(size_t value) +{ + size_t b = value % 1024; + value /= 1024; + + size_t kb = value % 1024; + value /= 1024; + + size_t mb = value % 1024; + value /= 1024; + + size_t gb = value; + + std::ostringstream stream; + + if (gb > 0) + stream << gb << " GB "; + if (mb > 0) + stream << mb << " MB "; + if (kb > 0) + stream << kb << " KB "; + if (b > 0) + stream << b << " B"; + + std::string s = stream.str(); + if (s[s.size() - 1] == ' ') + s = s.substr(0, s.size() - 1); + return s; +} + +static String getDeviceTypeString(const cv::ocl::Device& device) +{ + if (device.type() == cv::ocl::Device::TYPE_CPU) { + return "CPU"; + } + + if (device.type() == cv::ocl::Device::TYPE_GPU) { + if (device.hostUnifiedMemory()) { + return "iGPU"; + } else { + return "dGPU"; + } + } + + return "unknown"; +} +} // namespace + +static void dumpOpenCLInformation() +{ + using namespace cv::ocl; + + try + { + if (!haveOpenCL() || !useOpenCL()) + { + DUMP_MESSAGE_STDOUT("OpenCL is disabled"); + DUMP_CONFIG_PROPERTY("cv_ocl", "disabled"); + return; + } + + std::vector platforms; + cv::ocl::getPlatfomsInfo(platforms); + if (platforms.empty()) + { + DUMP_MESSAGE_STDOUT("OpenCL is not available"); + DUMP_CONFIG_PROPERTY("cv_ocl", "not available"); + return; + } + + DUMP_MESSAGE_STDOUT("OpenCL Platforms: "); + for (size_t i = 0; i < platforms.size(); i++) + { + const PlatformInfo* platform = &platforms[i]; + DUMP_MESSAGE_STDOUT(" " << platform->name()); + Device current_device; + for (int j = 0; j < platform->deviceNumber(); j++) + { + platform->getDevice(current_device, j); + String deviceTypeStr = getDeviceTypeString(current_device); + DUMP_MESSAGE_STDOUT( " " << deviceTypeStr << ": " << current_device.name() << " (" << current_device.version() << ")"); + DUMP_CONFIG_PROPERTY( cv::format("cv_ocl_platform_%d_device_%d", (int)i, j ), + cv::format("(Platform=%s)(Type=%s)(Name=%s)(Version=%s)", + platform->name().c_str(), deviceTypeStr.c_str(), current_device.name().c_str(), current_device.version().c_str()) ); + } + } + const Device& device = Device::getDefault(); + if (!device.available()) + CV_Error(Error::OpenCLInitError, "OpenCL device is not available"); + + DUMP_MESSAGE_STDOUT("Current OpenCL device: "); + + String deviceTypeStr = getDeviceTypeString(device); + DUMP_MESSAGE_STDOUT(" Type = " << deviceTypeStr); + DUMP_CONFIG_PROPERTY("cv_ocl_current_deviceType", deviceTypeStr); + + DUMP_MESSAGE_STDOUT(" Name = " << device.name()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_deviceName", device.name()); + + DUMP_MESSAGE_STDOUT(" Version = " << device.version()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_deviceVersion", device.version()); + + DUMP_MESSAGE_STDOUT(" Driver version = " << device.driverVersion()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_driverVersion", device.driverVersion()); + + DUMP_MESSAGE_STDOUT(" Address bits = " << device.addressBits()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_addressBits", device.addressBits()); + + DUMP_MESSAGE_STDOUT(" Compute units = " << device.maxComputeUnits()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_maxComputeUnits", device.maxComputeUnits()); + + DUMP_MESSAGE_STDOUT(" Max work group size = " << device.maxWorkGroupSize()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_maxWorkGroupSize", device.maxWorkGroupSize()); + + std::string localMemorySizeStr = bytesToStringRepr(device.localMemSize()); + DUMP_MESSAGE_STDOUT(" Local memory size = " << localMemorySizeStr); + DUMP_CONFIG_PROPERTY("cv_ocl_current_localMemSize", device.localMemSize()); + + std::string maxMemAllocSizeStr = bytesToStringRepr(device.maxMemAllocSize()); + DUMP_MESSAGE_STDOUT(" Max memory allocation size = " << maxMemAllocSizeStr); + DUMP_CONFIG_PROPERTY("cv_ocl_current_maxMemAllocSize", device.maxMemAllocSize()); + + const char* doubleSupportStr = device.hasFP64() ? "Yes" : "No"; + DUMP_MESSAGE_STDOUT(" Double support = " << doubleSupportStr); + DUMP_CONFIG_PROPERTY("cv_ocl_current_haveDoubleSupport", device.hasFP64()); + + const char* halfSupportStr = device.hasFP16() ? "Yes" : "No"; + DUMP_MESSAGE_STDOUT(" Half support = " << halfSupportStr); + DUMP_CONFIG_PROPERTY("cv_ocl_current_haveHalfSupport", device.hasFP16()); + + const char* isUnifiedMemoryStr = device.hostUnifiedMemory() ? "Yes" : "No"; + DUMP_MESSAGE_STDOUT(" Host unified memory = " << isUnifiedMemoryStr); + DUMP_CONFIG_PROPERTY("cv_ocl_current_hostUnifiedMemory", device.hostUnifiedMemory()); + + DUMP_MESSAGE_STDOUT(" Device extensions:"); + String extensionsStr = device.extensions(); + size_t pos = 0; + while (pos < extensionsStr.size()) + { + size_t pos2 = extensionsStr.find(' ', pos); + if (pos2 == String::npos) + pos2 = extensionsStr.size(); + if (pos2 > pos) + { + String extensionName = extensionsStr.substr(pos, pos2 - pos); + DUMP_MESSAGE_STDOUT(" " << extensionName); + } + pos = pos2 + 1; + } + DUMP_CONFIG_PROPERTY("cv_ocl_current_extensions", extensionsStr); + + const char* haveAmdBlasStr = haveAmdBlas() ? "Yes" : "No"; + DUMP_MESSAGE_STDOUT(" Has AMD Blas = " << haveAmdBlasStr); + DUMP_CONFIG_PROPERTY("cv_ocl_current_AmdBlas", haveAmdBlas()); + + const char* haveAmdFftStr = haveAmdFft() ? "Yes" : "No"; + DUMP_MESSAGE_STDOUT(" Has AMD Fft = " << haveAmdFftStr); + DUMP_CONFIG_PROPERTY("cv_ocl_current_AmdFft", haveAmdFft()); + + + DUMP_MESSAGE_STDOUT(" Preferred vector width char = " << device.preferredVectorWidthChar()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthChar", device.preferredVectorWidthChar()); + + DUMP_MESSAGE_STDOUT(" Preferred vector width short = " << device.preferredVectorWidthShort()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthShort", device.preferredVectorWidthShort()); + + DUMP_MESSAGE_STDOUT(" Preferred vector width int = " << device.preferredVectorWidthInt()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthInt", device.preferredVectorWidthInt()); + + DUMP_MESSAGE_STDOUT(" Preferred vector width long = " << device.preferredVectorWidthLong()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthLong", device.preferredVectorWidthLong()); + + DUMP_MESSAGE_STDOUT(" Preferred vector width float = " << device.preferredVectorWidthFloat()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthFloat", device.preferredVectorWidthFloat()); + + DUMP_MESSAGE_STDOUT(" Preferred vector width double = " << device.preferredVectorWidthDouble()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthDouble", device.preferredVectorWidthDouble()); + + DUMP_MESSAGE_STDOUT(" Preferred vector width half = " << device.preferredVectorWidthHalf()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthHalf", device.preferredVectorWidthHalf()); + } + catch (...) + { + DUMP_MESSAGE_STDOUT("Exception. Can't dump OpenCL info"); + DUMP_MESSAGE_STDOUT("OpenCL device not available"); + DUMP_CONFIG_PROPERTY("cv_ocl", "not available"); + } +} +#undef DUMP_MESSAGE_STDOUT +#undef DUMP_CONFIG_PROPERTY + +} // namespace diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/opencl_svm.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/opencl_svm.hpp index 7453082a67..f6b840e3ba 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/opencl_svm.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/opencl_svm.hpp @@ -1,81 +1,81 @@ -/* See LICENSE file in the root OpenCV directory */ - -#ifndef OPENCV_CORE_OPENCL_SVM_HPP -#define OPENCV_CORE_OPENCL_SVM_HPP - -// -// Internal usage only (binary compatibility is not guaranteed) -// -#ifndef __OPENCV_BUILD -#error Internal header file -#endif - -#if defined(HAVE_OPENCL) && defined(HAVE_OPENCL_SVM) -#include "runtime/opencl_core.hpp" -#include "runtime/opencl_svm_20.hpp" -#include "runtime/opencl_svm_hsa_extension.hpp" - -namespace cv { namespace ocl { namespace svm { - -struct SVMCapabilities -{ - enum Value - { - SVM_COARSE_GRAIN_BUFFER = (1 << 0), - SVM_FINE_GRAIN_BUFFER = (1 << 1), - SVM_FINE_GRAIN_SYSTEM = (1 << 2), - SVM_ATOMICS = (1 << 3), - }; - int value_; - - SVMCapabilities(int capabilities = 0) : value_(capabilities) { } - operator int() const { return value_; } - - inline bool isNoSVMSupport() const { return value_ == 0; } - inline bool isSupportCoarseGrainBuffer() const { return (value_ & SVM_COARSE_GRAIN_BUFFER) != 0; } - inline bool isSupportFineGrainBuffer() const { return (value_ & SVM_FINE_GRAIN_BUFFER) != 0; } - inline bool isSupportFineGrainSystem() const { return (value_ & SVM_FINE_GRAIN_SYSTEM) != 0; } - inline bool isSupportAtomics() const { return (value_ & SVM_ATOMICS) != 0; } -}; - -CV_EXPORTS const SVMCapabilities getSVMCapabilitites(const ocl::Context& context); - -struct SVMFunctions -{ - clSVMAllocAMD_fn fn_clSVMAlloc; - clSVMFreeAMD_fn fn_clSVMFree; - clSetKernelArgSVMPointerAMD_fn fn_clSetKernelArgSVMPointer; - //clSetKernelExecInfoAMD_fn fn_clSetKernelExecInfo; - //clEnqueueSVMFreeAMD_fn fn_clEnqueueSVMFree; - clEnqueueSVMMemcpyAMD_fn fn_clEnqueueSVMMemcpy; - clEnqueueSVMMemFillAMD_fn fn_clEnqueueSVMMemFill; - clEnqueueSVMMapAMD_fn fn_clEnqueueSVMMap; - clEnqueueSVMUnmapAMD_fn fn_clEnqueueSVMUnmap; - - inline SVMFunctions() - : fn_clSVMAlloc(NULL), fn_clSVMFree(NULL), - fn_clSetKernelArgSVMPointer(NULL), /*fn_clSetKernelExecInfo(NULL),*/ - /*fn_clEnqueueSVMFree(NULL),*/ fn_clEnqueueSVMMemcpy(NULL), fn_clEnqueueSVMMemFill(NULL), - fn_clEnqueueSVMMap(NULL), fn_clEnqueueSVMUnmap(NULL) - { - // nothing - } - - inline bool isValid() const - { - return fn_clSVMAlloc != NULL && fn_clSVMFree && fn_clSetKernelArgSVMPointer && - /*fn_clSetKernelExecInfo && fn_clEnqueueSVMFree &&*/ fn_clEnqueueSVMMemcpy && - fn_clEnqueueSVMMemFill && fn_clEnqueueSVMMap && fn_clEnqueueSVMUnmap; - } -}; - -// We should guarantee that SVMFunctions lifetime is not less than context's lifetime -CV_EXPORTS const SVMFunctions* getSVMFunctions(const ocl::Context& context); - -CV_EXPORTS bool useSVM(UMatUsageFlags usageFlags); - -}}} //namespace cv::ocl::svm -#endif - -#endif // OPENCV_CORE_OPENCL_SVM_HPP -/* End of file. */ +/* See LICENSE file in the root OpenCV directory */ + +#ifndef OPENCV_CORE_OPENCL_SVM_HPP +#define OPENCV_CORE_OPENCL_SVM_HPP + +// +// Internal usage only (binary compatibility is not guaranteed) +// +#ifndef __OPENCV_BUILD +#error Internal header file +#endif + +#if defined(HAVE_OPENCL) && defined(HAVE_OPENCL_SVM) +#include "runtime/opencl_core.hpp" +#include "runtime/opencl_svm_20.hpp" +#include "runtime/opencl_svm_hsa_extension.hpp" + +namespace cv { namespace ocl { namespace svm { + +struct SVMCapabilities +{ + enum Value + { + SVM_COARSE_GRAIN_BUFFER = (1 << 0), + SVM_FINE_GRAIN_BUFFER = (1 << 1), + SVM_FINE_GRAIN_SYSTEM = (1 << 2), + SVM_ATOMICS = (1 << 3), + }; + int value_; + + SVMCapabilities(int capabilities = 0) : value_(capabilities) { } + operator int() const { return value_; } + + inline bool isNoSVMSupport() const { return value_ == 0; } + inline bool isSupportCoarseGrainBuffer() const { return (value_ & SVM_COARSE_GRAIN_BUFFER) != 0; } + inline bool isSupportFineGrainBuffer() const { return (value_ & SVM_FINE_GRAIN_BUFFER) != 0; } + inline bool isSupportFineGrainSystem() const { return (value_ & SVM_FINE_GRAIN_SYSTEM) != 0; } + inline bool isSupportAtomics() const { return (value_ & SVM_ATOMICS) != 0; } +}; + +CV_EXPORTS const SVMCapabilities getSVMCapabilitites(const ocl::Context& context); + +struct SVMFunctions +{ + clSVMAllocAMD_fn fn_clSVMAlloc; + clSVMFreeAMD_fn fn_clSVMFree; + clSetKernelArgSVMPointerAMD_fn fn_clSetKernelArgSVMPointer; + //clSetKernelExecInfoAMD_fn fn_clSetKernelExecInfo; + //clEnqueueSVMFreeAMD_fn fn_clEnqueueSVMFree; + clEnqueueSVMMemcpyAMD_fn fn_clEnqueueSVMMemcpy; + clEnqueueSVMMemFillAMD_fn fn_clEnqueueSVMMemFill; + clEnqueueSVMMapAMD_fn fn_clEnqueueSVMMap; + clEnqueueSVMUnmapAMD_fn fn_clEnqueueSVMUnmap; + + inline SVMFunctions() + : fn_clSVMAlloc(NULL), fn_clSVMFree(NULL), + fn_clSetKernelArgSVMPointer(NULL), /*fn_clSetKernelExecInfo(NULL),*/ + /*fn_clEnqueueSVMFree(NULL),*/ fn_clEnqueueSVMMemcpy(NULL), fn_clEnqueueSVMMemFill(NULL), + fn_clEnqueueSVMMap(NULL), fn_clEnqueueSVMUnmap(NULL) + { + // nothing + } + + inline bool isValid() const + { + return fn_clSVMAlloc != NULL && fn_clSVMFree && fn_clSetKernelArgSVMPointer && + /*fn_clSetKernelExecInfo && fn_clEnqueueSVMFree &&*/ fn_clEnqueueSVMMemcpy && + fn_clEnqueueSVMMemFill && fn_clEnqueueSVMMap && fn_clEnqueueSVMUnmap; + } +}; + +// We should guarantee that SVMFunctions lifetime is not less than context's lifetime +CV_EXPORTS const SVMFunctions* getSVMFunctions(const ocl::Context& context); + +CV_EXPORTS bool useSVM(UMatUsageFlags usageFlags); + +}}} //namespace cv::ocl::svm +#endif + +#endif // OPENCV_CORE_OPENCL_SVM_HPP +/* End of file. */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_clblas.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_clblas.hpp index 2749927bea..37e019110d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_clblas.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_clblas.hpp @@ -1,602 +1,602 @@ -// -// AUTOGENERATED, DO NOT EDIT -// -#ifndef OPENCV_CORE_OCL_RUNTIME_CLAMDBLAS_HPP -#error "Invalid usage" -#endif - -// generated by parser_clblas.py -#define clblasCaxpy clblasCaxpy_ -#define clblasCcopy clblasCcopy_ -#define clblasCdotc clblasCdotc_ -#define clblasCdotu clblasCdotu_ -#define clblasCgbmv clblasCgbmv_ -#define clblasCgemm clblasCgemm_ -#define clblasCgemv clblasCgemv_ -#define clblasCgerc clblasCgerc_ -#define clblasCgeru clblasCgeru_ -#define clblasChbmv clblasChbmv_ -#define clblasChemm clblasChemm_ -#define clblasChemv clblasChemv_ -#define clblasCher clblasCher_ -#define clblasCher2 clblasCher2_ -#define clblasCher2k clblasCher2k_ -#define clblasCherk clblasCherk_ -#define clblasChpmv clblasChpmv_ -#define clblasChpr clblasChpr_ -#define clblasChpr2 clblasChpr2_ -#define clblasCrotg clblasCrotg_ -#define clblasCscal clblasCscal_ -#define clblasCsrot clblasCsrot_ -#define clblasCsscal clblasCsscal_ -#define clblasCswap clblasCswap_ -#define clblasCsymm clblasCsymm_ -#define clblasCsyr2k clblasCsyr2k_ -#define clblasCsyrk clblasCsyrk_ -#define clblasCtbmv clblasCtbmv_ -#define clblasCtbsv clblasCtbsv_ -#define clblasCtpmv clblasCtpmv_ -#define clblasCtpsv clblasCtpsv_ -#define clblasCtrmm clblasCtrmm_ -#define clblasCtrmv clblasCtrmv_ -#define clblasCtrsm clblasCtrsm_ -#define clblasCtrsv clblasCtrsv_ -#define clblasDasum clblasDasum_ -#define clblasDaxpy clblasDaxpy_ -#define clblasDcopy clblasDcopy_ -#define clblasDdot clblasDdot_ -#define clblasDgbmv clblasDgbmv_ -#define clblasDgemm clblasDgemm_ -#define clblasDgemv clblasDgemv_ -#define clblasDger clblasDger_ -#define clblasDnrm2 clblasDnrm2_ -#define clblasDrot clblasDrot_ -#define clblasDrotg clblasDrotg_ -#define clblasDrotm clblasDrotm_ -#define clblasDrotmg clblasDrotmg_ -#define clblasDsbmv clblasDsbmv_ -#define clblasDscal clblasDscal_ -#define clblasDspmv clblasDspmv_ -#define clblasDspr clblasDspr_ -#define clblasDspr2 clblasDspr2_ -#define clblasDswap clblasDswap_ -#define clblasDsymm clblasDsymm_ -#define clblasDsymv clblasDsymv_ -#define clblasDsyr clblasDsyr_ -#define clblasDsyr2 clblasDsyr2_ -#define clblasDsyr2k clblasDsyr2k_ -#define clblasDsyrk clblasDsyrk_ -#define clblasDtbmv clblasDtbmv_ -#define clblasDtbsv clblasDtbsv_ -#define clblasDtpmv clblasDtpmv_ -#define clblasDtpsv clblasDtpsv_ -#define clblasDtrmm clblasDtrmm_ -#define clblasDtrmv clblasDtrmv_ -#define clblasDtrsm clblasDtrsm_ -#define clblasDtrsv clblasDtrsv_ -#define clblasDzasum clblasDzasum_ -#define clblasDznrm2 clblasDznrm2_ -#define clblasGetVersion clblasGetVersion_ -#define clblasSasum clblasSasum_ -#define clblasSaxpy clblasSaxpy_ -#define clblasScasum clblasScasum_ -#define clblasScnrm2 clblasScnrm2_ -#define clblasScopy clblasScopy_ -#define clblasSdot clblasSdot_ -#define clblasSetup clblasSetup_ -#define clblasSgbmv clblasSgbmv_ -#define clblasSgemm clblasSgemm_ -#define clblasSgemv clblasSgemv_ -#define clblasSger clblasSger_ -#define clblasSnrm2 clblasSnrm2_ -#define clblasSrot clblasSrot_ -#define clblasSrotg clblasSrotg_ -#define clblasSrotm clblasSrotm_ -#define clblasSrotmg clblasSrotmg_ -#define clblasSsbmv clblasSsbmv_ -#define clblasSscal clblasSscal_ -#define clblasSspmv clblasSspmv_ -#define clblasSspr clblasSspr_ -#define clblasSspr2 clblasSspr2_ -#define clblasSswap clblasSswap_ -#define clblasSsymm clblasSsymm_ -#define clblasSsymv clblasSsymv_ -#define clblasSsyr clblasSsyr_ -#define clblasSsyr2 clblasSsyr2_ -#define clblasSsyr2k clblasSsyr2k_ -#define clblasSsyrk clblasSsyrk_ -#define clblasStbmv clblasStbmv_ -#define clblasStbsv clblasStbsv_ -#define clblasStpmv clblasStpmv_ -#define clblasStpsv clblasStpsv_ -#define clblasStrmm clblasStrmm_ -#define clblasStrmv clblasStrmv_ -#define clblasStrsm clblasStrsm_ -#define clblasStrsv clblasStrsv_ -#define clblasTeardown clblasTeardown_ -#define clblasZaxpy clblasZaxpy_ -#define clblasZcopy clblasZcopy_ -#define clblasZdotc clblasZdotc_ -#define clblasZdotu clblasZdotu_ -#define clblasZdrot clblasZdrot_ -#define clblasZdscal clblasZdscal_ -#define clblasZgbmv clblasZgbmv_ -#define clblasZgemm clblasZgemm_ -#define clblasZgemv clblasZgemv_ -#define clblasZgerc clblasZgerc_ -#define clblasZgeru clblasZgeru_ -#define clblasZhbmv clblasZhbmv_ -#define clblasZhemm clblasZhemm_ -#define clblasZhemv clblasZhemv_ -#define clblasZher clblasZher_ -#define clblasZher2 clblasZher2_ -#define clblasZher2k clblasZher2k_ -#define clblasZherk clblasZherk_ -#define clblasZhpmv clblasZhpmv_ -#define clblasZhpr clblasZhpr_ -#define clblasZhpr2 clblasZhpr2_ -#define clblasZrotg clblasZrotg_ -#define clblasZscal clblasZscal_ -#define clblasZswap clblasZswap_ -#define clblasZsymm clblasZsymm_ -#define clblasZsyr2k clblasZsyr2k_ -#define clblasZsyrk clblasZsyrk_ -#define clblasZtbmv clblasZtbmv_ -#define clblasZtbsv clblasZtbsv_ -#define clblasZtpmv clblasZtpmv_ -#define clblasZtpsv clblasZtpsv_ -#define clblasZtrmm clblasZtrmm_ -#define clblasZtrmv clblasZtrmv_ -#define clblasZtrsm clblasZtrsm_ -#define clblasZtrsv clblasZtrsv_ -#define clblasiCamax clblasiCamax_ -#define clblasiDamax clblasiDamax_ -#define clblasiSamax clblasiSamax_ -#define clblasiZamax clblasiZamax_ - -#include - -// generated by parser_clblas.py -#undef clblasCaxpy -//#define clblasCaxpy clblasCaxpy_pfn -#undef clblasCcopy -//#define clblasCcopy clblasCcopy_pfn -#undef clblasCdotc -//#define clblasCdotc clblasCdotc_pfn -#undef clblasCdotu -//#define clblasCdotu clblasCdotu_pfn -#undef clblasCgbmv -//#define clblasCgbmv clblasCgbmv_pfn -#undef clblasCgemm -#define clblasCgemm clblasCgemm_pfn -#undef clblasCgemv -//#define clblasCgemv clblasCgemv_pfn -#undef clblasCgerc -//#define clblasCgerc clblasCgerc_pfn -#undef clblasCgeru -//#define clblasCgeru clblasCgeru_pfn -#undef clblasChbmv -//#define clblasChbmv clblasChbmv_pfn -#undef clblasChemm -//#define clblasChemm clblasChemm_pfn -#undef clblasChemv -//#define clblasChemv clblasChemv_pfn -#undef clblasCher -//#define clblasCher clblasCher_pfn -#undef clblasCher2 -//#define clblasCher2 clblasCher2_pfn -#undef clblasCher2k -//#define clblasCher2k clblasCher2k_pfn -#undef clblasCherk -//#define clblasCherk clblasCherk_pfn -#undef clblasChpmv -//#define clblasChpmv clblasChpmv_pfn -#undef clblasChpr -//#define clblasChpr clblasChpr_pfn -#undef clblasChpr2 -//#define clblasChpr2 clblasChpr2_pfn -#undef clblasCrotg -//#define clblasCrotg clblasCrotg_pfn -#undef clblasCscal -//#define clblasCscal clblasCscal_pfn -#undef clblasCsrot -//#define clblasCsrot clblasCsrot_pfn -#undef clblasCsscal -//#define clblasCsscal clblasCsscal_pfn -#undef clblasCswap -//#define clblasCswap clblasCswap_pfn -#undef clblasCsymm -//#define clblasCsymm clblasCsymm_pfn -#undef clblasCsyr2k -//#define clblasCsyr2k clblasCsyr2k_pfn -#undef clblasCsyrk -//#define clblasCsyrk clblasCsyrk_pfn -#undef clblasCtbmv -//#define clblasCtbmv clblasCtbmv_pfn -#undef clblasCtbsv -//#define clblasCtbsv clblasCtbsv_pfn -#undef clblasCtpmv -//#define clblasCtpmv clblasCtpmv_pfn -#undef clblasCtpsv -//#define clblasCtpsv clblasCtpsv_pfn -#undef clblasCtrmm -//#define clblasCtrmm clblasCtrmm_pfn -#undef clblasCtrmv -//#define clblasCtrmv clblasCtrmv_pfn -#undef clblasCtrsm -//#define clblasCtrsm clblasCtrsm_pfn -#undef clblasCtrsv -//#define clblasCtrsv clblasCtrsv_pfn -#undef clblasDasum -//#define clblasDasum clblasDasum_pfn -#undef clblasDaxpy -//#define clblasDaxpy clblasDaxpy_pfn -#undef clblasDcopy -//#define clblasDcopy clblasDcopy_pfn -#undef clblasDdot -//#define clblasDdot clblasDdot_pfn -#undef clblasDgbmv -//#define clblasDgbmv clblasDgbmv_pfn -#undef clblasDgemm -#define clblasDgemm clblasDgemm_pfn -#undef clblasDgemv -//#define clblasDgemv clblasDgemv_pfn -#undef clblasDger -//#define clblasDger clblasDger_pfn -#undef clblasDnrm2 -//#define clblasDnrm2 clblasDnrm2_pfn -#undef clblasDrot -//#define clblasDrot clblasDrot_pfn -#undef clblasDrotg -//#define clblasDrotg clblasDrotg_pfn -#undef clblasDrotm -//#define clblasDrotm clblasDrotm_pfn -#undef clblasDrotmg -//#define clblasDrotmg clblasDrotmg_pfn -#undef clblasDsbmv -//#define clblasDsbmv clblasDsbmv_pfn -#undef clblasDscal -//#define clblasDscal clblasDscal_pfn -#undef clblasDspmv -//#define clblasDspmv clblasDspmv_pfn -#undef clblasDspr -//#define clblasDspr clblasDspr_pfn -#undef clblasDspr2 -//#define clblasDspr2 clblasDspr2_pfn -#undef clblasDswap -//#define clblasDswap clblasDswap_pfn -#undef clblasDsymm -//#define clblasDsymm clblasDsymm_pfn -#undef clblasDsymv -//#define clblasDsymv clblasDsymv_pfn -#undef clblasDsyr -//#define clblasDsyr clblasDsyr_pfn -#undef clblasDsyr2 -//#define clblasDsyr2 clblasDsyr2_pfn -#undef clblasDsyr2k -//#define clblasDsyr2k clblasDsyr2k_pfn -#undef clblasDsyrk -//#define clblasDsyrk clblasDsyrk_pfn -#undef clblasDtbmv -//#define clblasDtbmv clblasDtbmv_pfn -#undef clblasDtbsv -//#define clblasDtbsv clblasDtbsv_pfn -#undef clblasDtpmv -//#define clblasDtpmv clblasDtpmv_pfn -#undef clblasDtpsv -//#define clblasDtpsv clblasDtpsv_pfn -#undef clblasDtrmm -//#define clblasDtrmm clblasDtrmm_pfn -#undef clblasDtrmv -//#define clblasDtrmv clblasDtrmv_pfn -#undef clblasDtrsm -//#define clblasDtrsm clblasDtrsm_pfn -#undef clblasDtrsv -//#define clblasDtrsv clblasDtrsv_pfn -#undef clblasDzasum -//#define clblasDzasum clblasDzasum_pfn -#undef clblasDznrm2 -//#define clblasDznrm2 clblasDznrm2_pfn -#undef clblasGetVersion -//#define clblasGetVersion clblasGetVersion_pfn -#undef clblasSasum -//#define clblasSasum clblasSasum_pfn -#undef clblasSaxpy -//#define clblasSaxpy clblasSaxpy_pfn -#undef clblasScasum -//#define clblasScasum clblasScasum_pfn -#undef clblasScnrm2 -//#define clblasScnrm2 clblasScnrm2_pfn -#undef clblasScopy -//#define clblasScopy clblasScopy_pfn -#undef clblasSdot -//#define clblasSdot clblasSdot_pfn -#undef clblasSetup -#define clblasSetup clblasSetup_pfn -#undef clblasSgbmv -//#define clblasSgbmv clblasSgbmv_pfn -#undef clblasSgemm -#define clblasSgemm clblasSgemm_pfn -#undef clblasSgemv -//#define clblasSgemv clblasSgemv_pfn -#undef clblasSger -//#define clblasSger clblasSger_pfn -#undef clblasSnrm2 -//#define clblasSnrm2 clblasSnrm2_pfn -#undef clblasSrot -//#define clblasSrot clblasSrot_pfn -#undef clblasSrotg -//#define clblasSrotg clblasSrotg_pfn -#undef clblasSrotm -//#define clblasSrotm clblasSrotm_pfn -#undef clblasSrotmg -//#define clblasSrotmg clblasSrotmg_pfn -#undef clblasSsbmv -//#define clblasSsbmv clblasSsbmv_pfn -#undef clblasSscal -//#define clblasSscal clblasSscal_pfn -#undef clblasSspmv -//#define clblasSspmv clblasSspmv_pfn -#undef clblasSspr -//#define clblasSspr clblasSspr_pfn -#undef clblasSspr2 -//#define clblasSspr2 clblasSspr2_pfn -#undef clblasSswap -//#define clblasSswap clblasSswap_pfn -#undef clblasSsymm -//#define clblasSsymm clblasSsymm_pfn -#undef clblasSsymv -//#define clblasSsymv clblasSsymv_pfn -#undef clblasSsyr -//#define clblasSsyr clblasSsyr_pfn -#undef clblasSsyr2 -//#define clblasSsyr2 clblasSsyr2_pfn -#undef clblasSsyr2k -//#define clblasSsyr2k clblasSsyr2k_pfn -#undef clblasSsyrk -//#define clblasSsyrk clblasSsyrk_pfn -#undef clblasStbmv -//#define clblasStbmv clblasStbmv_pfn -#undef clblasStbsv -//#define clblasStbsv clblasStbsv_pfn -#undef clblasStpmv -//#define clblasStpmv clblasStpmv_pfn -#undef clblasStpsv -//#define clblasStpsv clblasStpsv_pfn -#undef clblasStrmm -//#define clblasStrmm clblasStrmm_pfn -#undef clblasStrmv -//#define clblasStrmv clblasStrmv_pfn -#undef clblasStrsm -//#define clblasStrsm clblasStrsm_pfn -#undef clblasStrsv -//#define clblasStrsv clblasStrsv_pfn -#undef clblasTeardown -#define clblasTeardown clblasTeardown_pfn -#undef clblasZaxpy -//#define clblasZaxpy clblasZaxpy_pfn -#undef clblasZcopy -//#define clblasZcopy clblasZcopy_pfn -#undef clblasZdotc -//#define clblasZdotc clblasZdotc_pfn -#undef clblasZdotu -//#define clblasZdotu clblasZdotu_pfn -#undef clblasZdrot -//#define clblasZdrot clblasZdrot_pfn -#undef clblasZdscal -//#define clblasZdscal clblasZdscal_pfn -#undef clblasZgbmv -//#define clblasZgbmv clblasZgbmv_pfn -#undef clblasZgemm -#define clblasZgemm clblasZgemm_pfn -#undef clblasZgemv -//#define clblasZgemv clblasZgemv_pfn -#undef clblasZgerc -//#define clblasZgerc clblasZgerc_pfn -#undef clblasZgeru -//#define clblasZgeru clblasZgeru_pfn -#undef clblasZhbmv -//#define clblasZhbmv clblasZhbmv_pfn -#undef clblasZhemm -//#define clblasZhemm clblasZhemm_pfn -#undef clblasZhemv -//#define clblasZhemv clblasZhemv_pfn -#undef clblasZher -//#define clblasZher clblasZher_pfn -#undef clblasZher2 -//#define clblasZher2 clblasZher2_pfn -#undef clblasZher2k -//#define clblasZher2k clblasZher2k_pfn -#undef clblasZherk -//#define clblasZherk clblasZherk_pfn -#undef clblasZhpmv -//#define clblasZhpmv clblasZhpmv_pfn -#undef clblasZhpr -//#define clblasZhpr clblasZhpr_pfn -#undef clblasZhpr2 -//#define clblasZhpr2 clblasZhpr2_pfn -#undef clblasZrotg -//#define clblasZrotg clblasZrotg_pfn -#undef clblasZscal -//#define clblasZscal clblasZscal_pfn -#undef clblasZswap -//#define clblasZswap clblasZswap_pfn -#undef clblasZsymm -//#define clblasZsymm clblasZsymm_pfn -#undef clblasZsyr2k -//#define clblasZsyr2k clblasZsyr2k_pfn -#undef clblasZsyrk -//#define clblasZsyrk clblasZsyrk_pfn -#undef clblasZtbmv -//#define clblasZtbmv clblasZtbmv_pfn -#undef clblasZtbsv -//#define clblasZtbsv clblasZtbsv_pfn -#undef clblasZtpmv -//#define clblasZtpmv clblasZtpmv_pfn -#undef clblasZtpsv -//#define clblasZtpsv clblasZtpsv_pfn -#undef clblasZtrmm -//#define clblasZtrmm clblasZtrmm_pfn -#undef clblasZtrmv -//#define clblasZtrmv clblasZtrmv_pfn -#undef clblasZtrsm -//#define clblasZtrsm clblasZtrsm_pfn -#undef clblasZtrsv -//#define clblasZtrsv clblasZtrsv_pfn -#undef clblasiCamax -//#define clblasiCamax clblasiCamax_pfn -#undef clblasiDamax -//#define clblasiDamax clblasiDamax_pfn -#undef clblasiSamax -//#define clblasiSamax clblasiSamax_pfn -#undef clblasiZamax -//#define clblasiZamax clblasiZamax_pfn - -// generated by parser_clblas.py -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCaxpy)(size_t N, cl_float2 alpha, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCcopy)(size_t N, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCdotc)(size_t N, cl_mem dotProduct, size_t offDP, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCdotu)(size_t N, cl_mem dotProduct, size_t offDP, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCgbmv)(clblasOrder order, clblasTranspose trans, size_t M, size_t N, size_t KL, size_t KU, cl_float2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_float2 beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -extern CL_RUNTIME_EXPORT clblasStatus (*clblasCgemm)(clblasOrder order, clblasTranspose transA, clblasTranspose transB, size_t M, size_t N, size_t K, FloatComplex alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, FloatComplex beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCgemv)(clblasOrder order, clblasTranspose transA, size_t M, size_t N, FloatComplex alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem x, size_t offx, int incx, FloatComplex beta, cl_mem y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCgerc)(clblasOrder order, size_t M, size_t N, cl_float2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCgeru)(clblasOrder order, size_t M, size_t N, cl_float2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasChbmv)(clblasOrder order, clblasUplo uplo, size_t N, size_t K, cl_float2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_float2 beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasChemm)(clblasOrder order, clblasSide side, clblasUplo uplo, size_t M, size_t N, cl_float2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_float2 beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasChemv)(clblasOrder order, clblasUplo uplo, size_t N, FloatComplex alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, FloatComplex beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCher)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCher2)(clblasOrder order, clblasUplo uplo, size_t N, cl_float2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCher2k)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, size_t N, size_t K, FloatComplex alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_float beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCherk)(clblasOrder order, clblasUplo uplo, clblasTranspose transA, size_t N, size_t K, float alpha, const cl_mem A, size_t offa, size_t lda, float beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasChpmv)(clblasOrder order, clblasUplo uplo, size_t N, cl_float2 alpha, const cl_mem AP, size_t offa, const cl_mem X, size_t offx, int incx, cl_float2 beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasChpr)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasChpr2)(clblasOrder order, clblasUplo uplo, size_t N, cl_float2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCrotg)(cl_mem CA, size_t offCA, cl_mem CB, size_t offCB, cl_mem C, size_t offC, cl_mem S, size_t offS, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCscal)(size_t N, cl_float2 alpha, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCsrot)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_float C, cl_float S, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCsscal)(size_t N, cl_float alpha, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCswap)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCsymm)(clblasOrder order, clblasSide side, clblasUplo uplo, size_t M, size_t N, cl_float2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_float2 beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCsyr2k)(clblasOrder order, clblasUplo uplo, clblasTranspose transAB, size_t N, size_t K, FloatComplex alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, FloatComplex beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCsyrk)(clblasOrder order, clblasUplo uplo, clblasTranspose transA, size_t N, size_t K, FloatComplex alpha, const cl_mem A, size_t offA, size_t lda, FloatComplex beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtbmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtbsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtpmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem AP, size_t offa, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtpsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtrmm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, FloatComplex alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtrmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtrsm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, FloatComplex alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtrsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDasum)(size_t N, cl_mem asum, size_t offAsum, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDaxpy)(size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDcopy)(size_t N, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDdot)(size_t N, cl_mem dotProduct, size_t offDP, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDgbmv)(clblasOrder order, clblasTranspose trans, size_t M, size_t N, size_t KL, size_t KU, cl_double alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_double beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -extern CL_RUNTIME_EXPORT clblasStatus (*clblasDgemm)(clblasOrder order, clblasTranspose transA, clblasTranspose transB, size_t M, size_t N, size_t K, cl_double alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, cl_double beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDgemv)(clblasOrder order, clblasTranspose transA, size_t M, size_t N, cl_double alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem x, size_t offx, int incx, cl_double beta, cl_mem y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDger)(clblasOrder order, size_t M, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDnrm2)(size_t N, cl_mem NRM2, size_t offNRM2, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDrot)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_double C, cl_double S, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDrotg)(cl_mem DA, size_t offDA, cl_mem DB, size_t offDB, cl_mem C, size_t offC, cl_mem S, size_t offS, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDrotm)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, const cl_mem DPARAM, size_t offDparam, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDrotmg)(cl_mem DD1, size_t offDD1, cl_mem DD2, size_t offDD2, cl_mem DX1, size_t offDX1, const cl_mem DY1, size_t offDY1, cl_mem DPARAM, size_t offDparam, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsbmv)(clblasOrder order, clblasUplo uplo, size_t N, size_t K, cl_double alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_double beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDscal)(size_t N, cl_double alpha, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDspmv)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem AP, size_t offa, const cl_mem X, size_t offx, int incx, cl_double beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDspr)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDspr2)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDswap)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsymm)(clblasOrder order, clblasSide side, clblasUplo uplo, size_t M, size_t N, cl_double alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_double beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsymv)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem x, size_t offx, int incx, cl_double beta, cl_mem y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsyr)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsyr2)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsyr2k)(clblasOrder order, clblasUplo uplo, clblasTranspose transAB, size_t N, size_t K, cl_double alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, cl_double beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsyrk)(clblasOrder order, clblasUplo uplo, clblasTranspose transA, size_t N, size_t K, cl_double alpha, const cl_mem A, size_t offA, size_t lda, cl_double beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtbmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtbsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtpmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem AP, size_t offa, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtpsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtrmm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, cl_double alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtrmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtrsm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, cl_double alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtrsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDzasum)(size_t N, cl_mem asum, size_t offAsum, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDznrm2)(size_t N, cl_mem NRM2, size_t offNRM2, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasGetVersion)(cl_uint* major, cl_uint* minor, cl_uint* patch); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSasum)(size_t N, cl_mem asum, size_t offAsum, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSaxpy)(size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasScasum)(size_t N, cl_mem asum, size_t offAsum, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasScnrm2)(size_t N, cl_mem NRM2, size_t offNRM2, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasScopy)(size_t N, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSdot)(size_t N, cl_mem dotProduct, size_t offDP, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -extern CL_RUNTIME_EXPORT clblasStatus (*clblasSetup)(); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSgbmv)(clblasOrder order, clblasTranspose trans, size_t M, size_t N, size_t KL, size_t KU, cl_float alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_float beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -extern CL_RUNTIME_EXPORT clblasStatus (*clblasSgemm)(clblasOrder order, clblasTranspose transA, clblasTranspose transB, size_t M, size_t N, size_t K, cl_float alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, cl_float beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSgemv)(clblasOrder order, clblasTranspose transA, size_t M, size_t N, cl_float alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem x, size_t offx, int incx, cl_float beta, cl_mem y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSger)(clblasOrder order, size_t M, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSnrm2)(size_t N, cl_mem NRM2, size_t offNRM2, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSrot)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_float C, cl_float S, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSrotg)(cl_mem SA, size_t offSA, cl_mem SB, size_t offSB, cl_mem C, size_t offC, cl_mem S, size_t offS, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSrotm)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, const cl_mem SPARAM, size_t offSparam, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSrotmg)(cl_mem SD1, size_t offSD1, cl_mem SD2, size_t offSD2, cl_mem SX1, size_t offSX1, const cl_mem SY1, size_t offSY1, cl_mem SPARAM, size_t offSparam, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsbmv)(clblasOrder order, clblasUplo uplo, size_t N, size_t K, cl_float alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_float beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSscal)(size_t N, cl_float alpha, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSspmv)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem AP, size_t offa, const cl_mem X, size_t offx, int incx, cl_float beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSspr)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSspr2)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSswap)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsymm)(clblasOrder order, clblasSide side, clblasUplo uplo, size_t M, size_t N, cl_float alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_float beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsymv)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem x, size_t offx, int incx, cl_float beta, cl_mem y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsyr)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsyr2)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsyr2k)(clblasOrder order, clblasUplo uplo, clblasTranspose transAB, size_t N, size_t K, cl_float alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, cl_float beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsyrk)(clblasOrder order, clblasUplo uplo, clblasTranspose transA, size_t N, size_t K, cl_float alpha, const cl_mem A, size_t offA, size_t lda, cl_float beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStbmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStbsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStpmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem AP, size_t offa, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStpsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStrmm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, cl_float alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStrmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStrsm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, cl_float alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStrsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -extern CL_RUNTIME_EXPORT void (*clblasTeardown)(); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZaxpy)(size_t N, cl_double2 alpha, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZcopy)(size_t N, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZdotc)(size_t N, cl_mem dotProduct, size_t offDP, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZdotu)(size_t N, cl_mem dotProduct, size_t offDP, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZdrot)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_double C, cl_double S, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZdscal)(size_t N, cl_double alpha, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZgbmv)(clblasOrder order, clblasTranspose trans, size_t M, size_t N, size_t KL, size_t KU, cl_double2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_double2 beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -extern CL_RUNTIME_EXPORT clblasStatus (*clblasZgemm)(clblasOrder order, clblasTranspose transA, clblasTranspose transB, size_t M, size_t N, size_t K, DoubleComplex alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, DoubleComplex beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZgemv)(clblasOrder order, clblasTranspose transA, size_t M, size_t N, DoubleComplex alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem x, size_t offx, int incx, DoubleComplex beta, cl_mem y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZgerc)(clblasOrder order, size_t M, size_t N, cl_double2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZgeru)(clblasOrder order, size_t M, size_t N, cl_double2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZhbmv)(clblasOrder order, clblasUplo uplo, size_t N, size_t K, cl_double2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_double2 beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZhemm)(clblasOrder order, clblasSide side, clblasUplo uplo, size_t M, size_t N, cl_double2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_double2 beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZhemv)(clblasOrder order, clblasUplo uplo, size_t N, DoubleComplex alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, DoubleComplex beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZher)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZher2)(clblasOrder order, clblasUplo uplo, size_t N, cl_double2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZher2k)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, size_t N, size_t K, DoubleComplex alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_double beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZherk)(clblasOrder order, clblasUplo uplo, clblasTranspose transA, size_t N, size_t K, double alpha, const cl_mem A, size_t offa, size_t lda, double beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZhpmv)(clblasOrder order, clblasUplo uplo, size_t N, cl_double2 alpha, const cl_mem AP, size_t offa, const cl_mem X, size_t offx, int incx, cl_double2 beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZhpr)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZhpr2)(clblasOrder order, clblasUplo uplo, size_t N, cl_double2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZrotg)(cl_mem CA, size_t offCA, cl_mem CB, size_t offCB, cl_mem C, size_t offC, cl_mem S, size_t offS, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZscal)(size_t N, cl_double2 alpha, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZswap)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZsymm)(clblasOrder order, clblasSide side, clblasUplo uplo, size_t M, size_t N, cl_double2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_double2 beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZsyr2k)(clblasOrder order, clblasUplo uplo, clblasTranspose transAB, size_t N, size_t K, DoubleComplex alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, DoubleComplex beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZsyrk)(clblasOrder order, clblasUplo uplo, clblasTranspose transA, size_t N, size_t K, DoubleComplex alpha, const cl_mem A, size_t offA, size_t lda, DoubleComplex beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtbmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtbsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtpmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem AP, size_t offa, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtpsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtrmm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, DoubleComplex alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtrmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtrsm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, DoubleComplex alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtrsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasiCamax)(size_t N, cl_mem iMax, size_t offiMax, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasiDamax)(size_t N, cl_mem iMax, size_t offiMax, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasiSamax)(size_t N, cl_mem iMax, size_t offiMax, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasiZamax)(size_t N, cl_mem iMax, size_t offiMax, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +// +// AUTOGENERATED, DO NOT EDIT +// +#ifndef OPENCV_CORE_OCL_RUNTIME_CLAMDBLAS_HPP +#error "Invalid usage" +#endif + +// generated by parser_clblas.py +#define clblasCaxpy clblasCaxpy_ +#define clblasCcopy clblasCcopy_ +#define clblasCdotc clblasCdotc_ +#define clblasCdotu clblasCdotu_ +#define clblasCgbmv clblasCgbmv_ +#define clblasCgemm clblasCgemm_ +#define clblasCgemv clblasCgemv_ +#define clblasCgerc clblasCgerc_ +#define clblasCgeru clblasCgeru_ +#define clblasChbmv clblasChbmv_ +#define clblasChemm clblasChemm_ +#define clblasChemv clblasChemv_ +#define clblasCher clblasCher_ +#define clblasCher2 clblasCher2_ +#define clblasCher2k clblasCher2k_ +#define clblasCherk clblasCherk_ +#define clblasChpmv clblasChpmv_ +#define clblasChpr clblasChpr_ +#define clblasChpr2 clblasChpr2_ +#define clblasCrotg clblasCrotg_ +#define clblasCscal clblasCscal_ +#define clblasCsrot clblasCsrot_ +#define clblasCsscal clblasCsscal_ +#define clblasCswap clblasCswap_ +#define clblasCsymm clblasCsymm_ +#define clblasCsyr2k clblasCsyr2k_ +#define clblasCsyrk clblasCsyrk_ +#define clblasCtbmv clblasCtbmv_ +#define clblasCtbsv clblasCtbsv_ +#define clblasCtpmv clblasCtpmv_ +#define clblasCtpsv clblasCtpsv_ +#define clblasCtrmm clblasCtrmm_ +#define clblasCtrmv clblasCtrmv_ +#define clblasCtrsm clblasCtrsm_ +#define clblasCtrsv clblasCtrsv_ +#define clblasDasum clblasDasum_ +#define clblasDaxpy clblasDaxpy_ +#define clblasDcopy clblasDcopy_ +#define clblasDdot clblasDdot_ +#define clblasDgbmv clblasDgbmv_ +#define clblasDgemm clblasDgemm_ +#define clblasDgemv clblasDgemv_ +#define clblasDger clblasDger_ +#define clblasDnrm2 clblasDnrm2_ +#define clblasDrot clblasDrot_ +#define clblasDrotg clblasDrotg_ +#define clblasDrotm clblasDrotm_ +#define clblasDrotmg clblasDrotmg_ +#define clblasDsbmv clblasDsbmv_ +#define clblasDscal clblasDscal_ +#define clblasDspmv clblasDspmv_ +#define clblasDspr clblasDspr_ +#define clblasDspr2 clblasDspr2_ +#define clblasDswap clblasDswap_ +#define clblasDsymm clblasDsymm_ +#define clblasDsymv clblasDsymv_ +#define clblasDsyr clblasDsyr_ +#define clblasDsyr2 clblasDsyr2_ +#define clblasDsyr2k clblasDsyr2k_ +#define clblasDsyrk clblasDsyrk_ +#define clblasDtbmv clblasDtbmv_ +#define clblasDtbsv clblasDtbsv_ +#define clblasDtpmv clblasDtpmv_ +#define clblasDtpsv clblasDtpsv_ +#define clblasDtrmm clblasDtrmm_ +#define clblasDtrmv clblasDtrmv_ +#define clblasDtrsm clblasDtrsm_ +#define clblasDtrsv clblasDtrsv_ +#define clblasDzasum clblasDzasum_ +#define clblasDznrm2 clblasDznrm2_ +#define clblasGetVersion clblasGetVersion_ +#define clblasSasum clblasSasum_ +#define clblasSaxpy clblasSaxpy_ +#define clblasScasum clblasScasum_ +#define clblasScnrm2 clblasScnrm2_ +#define clblasScopy clblasScopy_ +#define clblasSdot clblasSdot_ +#define clblasSetup clblasSetup_ +#define clblasSgbmv clblasSgbmv_ +#define clblasSgemm clblasSgemm_ +#define clblasSgemv clblasSgemv_ +#define clblasSger clblasSger_ +#define clblasSnrm2 clblasSnrm2_ +#define clblasSrot clblasSrot_ +#define clblasSrotg clblasSrotg_ +#define clblasSrotm clblasSrotm_ +#define clblasSrotmg clblasSrotmg_ +#define clblasSsbmv clblasSsbmv_ +#define clblasSscal clblasSscal_ +#define clblasSspmv clblasSspmv_ +#define clblasSspr clblasSspr_ +#define clblasSspr2 clblasSspr2_ +#define clblasSswap clblasSswap_ +#define clblasSsymm clblasSsymm_ +#define clblasSsymv clblasSsymv_ +#define clblasSsyr clblasSsyr_ +#define clblasSsyr2 clblasSsyr2_ +#define clblasSsyr2k clblasSsyr2k_ +#define clblasSsyrk clblasSsyrk_ +#define clblasStbmv clblasStbmv_ +#define clblasStbsv clblasStbsv_ +#define clblasStpmv clblasStpmv_ +#define clblasStpsv clblasStpsv_ +#define clblasStrmm clblasStrmm_ +#define clblasStrmv clblasStrmv_ +#define clblasStrsm clblasStrsm_ +#define clblasStrsv clblasStrsv_ +#define clblasTeardown clblasTeardown_ +#define clblasZaxpy clblasZaxpy_ +#define clblasZcopy clblasZcopy_ +#define clblasZdotc clblasZdotc_ +#define clblasZdotu clblasZdotu_ +#define clblasZdrot clblasZdrot_ +#define clblasZdscal clblasZdscal_ +#define clblasZgbmv clblasZgbmv_ +#define clblasZgemm clblasZgemm_ +#define clblasZgemv clblasZgemv_ +#define clblasZgerc clblasZgerc_ +#define clblasZgeru clblasZgeru_ +#define clblasZhbmv clblasZhbmv_ +#define clblasZhemm clblasZhemm_ +#define clblasZhemv clblasZhemv_ +#define clblasZher clblasZher_ +#define clblasZher2 clblasZher2_ +#define clblasZher2k clblasZher2k_ +#define clblasZherk clblasZherk_ +#define clblasZhpmv clblasZhpmv_ +#define clblasZhpr clblasZhpr_ +#define clblasZhpr2 clblasZhpr2_ +#define clblasZrotg clblasZrotg_ +#define clblasZscal clblasZscal_ +#define clblasZswap clblasZswap_ +#define clblasZsymm clblasZsymm_ +#define clblasZsyr2k clblasZsyr2k_ +#define clblasZsyrk clblasZsyrk_ +#define clblasZtbmv clblasZtbmv_ +#define clblasZtbsv clblasZtbsv_ +#define clblasZtpmv clblasZtpmv_ +#define clblasZtpsv clblasZtpsv_ +#define clblasZtrmm clblasZtrmm_ +#define clblasZtrmv clblasZtrmv_ +#define clblasZtrsm clblasZtrsm_ +#define clblasZtrsv clblasZtrsv_ +#define clblasiCamax clblasiCamax_ +#define clblasiDamax clblasiDamax_ +#define clblasiSamax clblasiSamax_ +#define clblasiZamax clblasiZamax_ + +#include + +// generated by parser_clblas.py +#undef clblasCaxpy +//#define clblasCaxpy clblasCaxpy_pfn +#undef clblasCcopy +//#define clblasCcopy clblasCcopy_pfn +#undef clblasCdotc +//#define clblasCdotc clblasCdotc_pfn +#undef clblasCdotu +//#define clblasCdotu clblasCdotu_pfn +#undef clblasCgbmv +//#define clblasCgbmv clblasCgbmv_pfn +#undef clblasCgemm +#define clblasCgemm clblasCgemm_pfn +#undef clblasCgemv +//#define clblasCgemv clblasCgemv_pfn +#undef clblasCgerc +//#define clblasCgerc clblasCgerc_pfn +#undef clblasCgeru +//#define clblasCgeru clblasCgeru_pfn +#undef clblasChbmv +//#define clblasChbmv clblasChbmv_pfn +#undef clblasChemm +//#define clblasChemm clblasChemm_pfn +#undef clblasChemv +//#define clblasChemv clblasChemv_pfn +#undef clblasCher +//#define clblasCher clblasCher_pfn +#undef clblasCher2 +//#define clblasCher2 clblasCher2_pfn +#undef clblasCher2k +//#define clblasCher2k clblasCher2k_pfn +#undef clblasCherk +//#define clblasCherk clblasCherk_pfn +#undef clblasChpmv +//#define clblasChpmv clblasChpmv_pfn +#undef clblasChpr +//#define clblasChpr clblasChpr_pfn +#undef clblasChpr2 +//#define clblasChpr2 clblasChpr2_pfn +#undef clblasCrotg +//#define clblasCrotg clblasCrotg_pfn +#undef clblasCscal +//#define clblasCscal clblasCscal_pfn +#undef clblasCsrot +//#define clblasCsrot clblasCsrot_pfn +#undef clblasCsscal +//#define clblasCsscal clblasCsscal_pfn +#undef clblasCswap +//#define clblasCswap clblasCswap_pfn +#undef clblasCsymm +//#define clblasCsymm clblasCsymm_pfn +#undef clblasCsyr2k +//#define clblasCsyr2k clblasCsyr2k_pfn +#undef clblasCsyrk +//#define clblasCsyrk clblasCsyrk_pfn +#undef clblasCtbmv +//#define clblasCtbmv clblasCtbmv_pfn +#undef clblasCtbsv +//#define clblasCtbsv clblasCtbsv_pfn +#undef clblasCtpmv +//#define clblasCtpmv clblasCtpmv_pfn +#undef clblasCtpsv +//#define clblasCtpsv clblasCtpsv_pfn +#undef clblasCtrmm +//#define clblasCtrmm clblasCtrmm_pfn +#undef clblasCtrmv +//#define clblasCtrmv clblasCtrmv_pfn +#undef clblasCtrsm +//#define clblasCtrsm clblasCtrsm_pfn +#undef clblasCtrsv +//#define clblasCtrsv clblasCtrsv_pfn +#undef clblasDasum +//#define clblasDasum clblasDasum_pfn +#undef clblasDaxpy +//#define clblasDaxpy clblasDaxpy_pfn +#undef clblasDcopy +//#define clblasDcopy clblasDcopy_pfn +#undef clblasDdot +//#define clblasDdot clblasDdot_pfn +#undef clblasDgbmv +//#define clblasDgbmv clblasDgbmv_pfn +#undef clblasDgemm +#define clblasDgemm clblasDgemm_pfn +#undef clblasDgemv +//#define clblasDgemv clblasDgemv_pfn +#undef clblasDger +//#define clblasDger clblasDger_pfn +#undef clblasDnrm2 +//#define clblasDnrm2 clblasDnrm2_pfn +#undef clblasDrot +//#define clblasDrot clblasDrot_pfn +#undef clblasDrotg +//#define clblasDrotg clblasDrotg_pfn +#undef clblasDrotm +//#define clblasDrotm clblasDrotm_pfn +#undef clblasDrotmg +//#define clblasDrotmg clblasDrotmg_pfn +#undef clblasDsbmv +//#define clblasDsbmv clblasDsbmv_pfn +#undef clblasDscal +//#define clblasDscal clblasDscal_pfn +#undef clblasDspmv +//#define clblasDspmv clblasDspmv_pfn +#undef clblasDspr +//#define clblasDspr clblasDspr_pfn +#undef clblasDspr2 +//#define clblasDspr2 clblasDspr2_pfn +#undef clblasDswap +//#define clblasDswap clblasDswap_pfn +#undef clblasDsymm +//#define clblasDsymm clblasDsymm_pfn +#undef clblasDsymv +//#define clblasDsymv clblasDsymv_pfn +#undef clblasDsyr +//#define clblasDsyr clblasDsyr_pfn +#undef clblasDsyr2 +//#define clblasDsyr2 clblasDsyr2_pfn +#undef clblasDsyr2k +//#define clblasDsyr2k clblasDsyr2k_pfn +#undef clblasDsyrk +//#define clblasDsyrk clblasDsyrk_pfn +#undef clblasDtbmv +//#define clblasDtbmv clblasDtbmv_pfn +#undef clblasDtbsv +//#define clblasDtbsv clblasDtbsv_pfn +#undef clblasDtpmv +//#define clblasDtpmv clblasDtpmv_pfn +#undef clblasDtpsv +//#define clblasDtpsv clblasDtpsv_pfn +#undef clblasDtrmm +//#define clblasDtrmm clblasDtrmm_pfn +#undef clblasDtrmv +//#define clblasDtrmv clblasDtrmv_pfn +#undef clblasDtrsm +//#define clblasDtrsm clblasDtrsm_pfn +#undef clblasDtrsv +//#define clblasDtrsv clblasDtrsv_pfn +#undef clblasDzasum +//#define clblasDzasum clblasDzasum_pfn +#undef clblasDznrm2 +//#define clblasDznrm2 clblasDznrm2_pfn +#undef clblasGetVersion +//#define clblasGetVersion clblasGetVersion_pfn +#undef clblasSasum +//#define clblasSasum clblasSasum_pfn +#undef clblasSaxpy +//#define clblasSaxpy clblasSaxpy_pfn +#undef clblasScasum +//#define clblasScasum clblasScasum_pfn +#undef clblasScnrm2 +//#define clblasScnrm2 clblasScnrm2_pfn +#undef clblasScopy +//#define clblasScopy clblasScopy_pfn +#undef clblasSdot +//#define clblasSdot clblasSdot_pfn +#undef clblasSetup +#define clblasSetup clblasSetup_pfn +#undef clblasSgbmv +//#define clblasSgbmv clblasSgbmv_pfn +#undef clblasSgemm +#define clblasSgemm clblasSgemm_pfn +#undef clblasSgemv +//#define clblasSgemv clblasSgemv_pfn +#undef clblasSger +//#define clblasSger clblasSger_pfn +#undef clblasSnrm2 +//#define clblasSnrm2 clblasSnrm2_pfn +#undef clblasSrot +//#define clblasSrot clblasSrot_pfn +#undef clblasSrotg +//#define clblasSrotg clblasSrotg_pfn +#undef clblasSrotm +//#define clblasSrotm clblasSrotm_pfn +#undef clblasSrotmg +//#define clblasSrotmg clblasSrotmg_pfn +#undef clblasSsbmv +//#define clblasSsbmv clblasSsbmv_pfn +#undef clblasSscal +//#define clblasSscal clblasSscal_pfn +#undef clblasSspmv +//#define clblasSspmv clblasSspmv_pfn +#undef clblasSspr +//#define clblasSspr clblasSspr_pfn +#undef clblasSspr2 +//#define clblasSspr2 clblasSspr2_pfn +#undef clblasSswap +//#define clblasSswap clblasSswap_pfn +#undef clblasSsymm +//#define clblasSsymm clblasSsymm_pfn +#undef clblasSsymv +//#define clblasSsymv clblasSsymv_pfn +#undef clblasSsyr +//#define clblasSsyr clblasSsyr_pfn +#undef clblasSsyr2 +//#define clblasSsyr2 clblasSsyr2_pfn +#undef clblasSsyr2k +//#define clblasSsyr2k clblasSsyr2k_pfn +#undef clblasSsyrk +//#define clblasSsyrk clblasSsyrk_pfn +#undef clblasStbmv +//#define clblasStbmv clblasStbmv_pfn +#undef clblasStbsv +//#define clblasStbsv clblasStbsv_pfn +#undef clblasStpmv +//#define clblasStpmv clblasStpmv_pfn +#undef clblasStpsv +//#define clblasStpsv clblasStpsv_pfn +#undef clblasStrmm +//#define clblasStrmm clblasStrmm_pfn +#undef clblasStrmv +//#define clblasStrmv clblasStrmv_pfn +#undef clblasStrsm +//#define clblasStrsm clblasStrsm_pfn +#undef clblasStrsv +//#define clblasStrsv clblasStrsv_pfn +#undef clblasTeardown +#define clblasTeardown clblasTeardown_pfn +#undef clblasZaxpy +//#define clblasZaxpy clblasZaxpy_pfn +#undef clblasZcopy +//#define clblasZcopy clblasZcopy_pfn +#undef clblasZdotc +//#define clblasZdotc clblasZdotc_pfn +#undef clblasZdotu +//#define clblasZdotu clblasZdotu_pfn +#undef clblasZdrot +//#define clblasZdrot clblasZdrot_pfn +#undef clblasZdscal +//#define clblasZdscal clblasZdscal_pfn +#undef clblasZgbmv +//#define clblasZgbmv clblasZgbmv_pfn +#undef clblasZgemm +#define clblasZgemm clblasZgemm_pfn +#undef clblasZgemv +//#define clblasZgemv clblasZgemv_pfn +#undef clblasZgerc +//#define clblasZgerc clblasZgerc_pfn +#undef clblasZgeru +//#define clblasZgeru clblasZgeru_pfn +#undef clblasZhbmv +//#define clblasZhbmv clblasZhbmv_pfn +#undef clblasZhemm +//#define clblasZhemm clblasZhemm_pfn +#undef clblasZhemv +//#define clblasZhemv clblasZhemv_pfn +#undef clblasZher +//#define clblasZher clblasZher_pfn +#undef clblasZher2 +//#define clblasZher2 clblasZher2_pfn +#undef clblasZher2k +//#define clblasZher2k clblasZher2k_pfn +#undef clblasZherk +//#define clblasZherk clblasZherk_pfn +#undef clblasZhpmv +//#define clblasZhpmv clblasZhpmv_pfn +#undef clblasZhpr +//#define clblasZhpr clblasZhpr_pfn +#undef clblasZhpr2 +//#define clblasZhpr2 clblasZhpr2_pfn +#undef clblasZrotg +//#define clblasZrotg clblasZrotg_pfn +#undef clblasZscal +//#define clblasZscal clblasZscal_pfn +#undef clblasZswap +//#define clblasZswap clblasZswap_pfn +#undef clblasZsymm +//#define clblasZsymm clblasZsymm_pfn +#undef clblasZsyr2k +//#define clblasZsyr2k clblasZsyr2k_pfn +#undef clblasZsyrk +//#define clblasZsyrk clblasZsyrk_pfn +#undef clblasZtbmv +//#define clblasZtbmv clblasZtbmv_pfn +#undef clblasZtbsv +//#define clblasZtbsv clblasZtbsv_pfn +#undef clblasZtpmv +//#define clblasZtpmv clblasZtpmv_pfn +#undef clblasZtpsv +//#define clblasZtpsv clblasZtpsv_pfn +#undef clblasZtrmm +//#define clblasZtrmm clblasZtrmm_pfn +#undef clblasZtrmv +//#define clblasZtrmv clblasZtrmv_pfn +#undef clblasZtrsm +//#define clblasZtrsm clblasZtrsm_pfn +#undef clblasZtrsv +//#define clblasZtrsv clblasZtrsv_pfn +#undef clblasiCamax +//#define clblasiCamax clblasiCamax_pfn +#undef clblasiDamax +//#define clblasiDamax clblasiDamax_pfn +#undef clblasiSamax +//#define clblasiSamax clblasiSamax_pfn +#undef clblasiZamax +//#define clblasiZamax clblasiZamax_pfn + +// generated by parser_clblas.py +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCaxpy)(size_t N, cl_float2 alpha, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCcopy)(size_t N, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCdotc)(size_t N, cl_mem dotProduct, size_t offDP, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCdotu)(size_t N, cl_mem dotProduct, size_t offDP, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCgbmv)(clblasOrder order, clblasTranspose trans, size_t M, size_t N, size_t KL, size_t KU, cl_float2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_float2 beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +extern CL_RUNTIME_EXPORT clblasStatus (*clblasCgemm)(clblasOrder order, clblasTranspose transA, clblasTranspose transB, size_t M, size_t N, size_t K, FloatComplex alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, FloatComplex beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCgemv)(clblasOrder order, clblasTranspose transA, size_t M, size_t N, FloatComplex alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem x, size_t offx, int incx, FloatComplex beta, cl_mem y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCgerc)(clblasOrder order, size_t M, size_t N, cl_float2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCgeru)(clblasOrder order, size_t M, size_t N, cl_float2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasChbmv)(clblasOrder order, clblasUplo uplo, size_t N, size_t K, cl_float2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_float2 beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasChemm)(clblasOrder order, clblasSide side, clblasUplo uplo, size_t M, size_t N, cl_float2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_float2 beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasChemv)(clblasOrder order, clblasUplo uplo, size_t N, FloatComplex alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, FloatComplex beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCher)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCher2)(clblasOrder order, clblasUplo uplo, size_t N, cl_float2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCher2k)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, size_t N, size_t K, FloatComplex alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_float beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCherk)(clblasOrder order, clblasUplo uplo, clblasTranspose transA, size_t N, size_t K, float alpha, const cl_mem A, size_t offa, size_t lda, float beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasChpmv)(clblasOrder order, clblasUplo uplo, size_t N, cl_float2 alpha, const cl_mem AP, size_t offa, const cl_mem X, size_t offx, int incx, cl_float2 beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasChpr)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasChpr2)(clblasOrder order, clblasUplo uplo, size_t N, cl_float2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCrotg)(cl_mem CA, size_t offCA, cl_mem CB, size_t offCB, cl_mem C, size_t offC, cl_mem S, size_t offS, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCscal)(size_t N, cl_float2 alpha, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCsrot)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_float C, cl_float S, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCsscal)(size_t N, cl_float alpha, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCswap)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCsymm)(clblasOrder order, clblasSide side, clblasUplo uplo, size_t M, size_t N, cl_float2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_float2 beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCsyr2k)(clblasOrder order, clblasUplo uplo, clblasTranspose transAB, size_t N, size_t K, FloatComplex alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, FloatComplex beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCsyrk)(clblasOrder order, clblasUplo uplo, clblasTranspose transA, size_t N, size_t K, FloatComplex alpha, const cl_mem A, size_t offA, size_t lda, FloatComplex beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtbmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtbsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtpmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem AP, size_t offa, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtpsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtrmm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, FloatComplex alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtrmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtrsm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, FloatComplex alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtrsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDasum)(size_t N, cl_mem asum, size_t offAsum, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDaxpy)(size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDcopy)(size_t N, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDdot)(size_t N, cl_mem dotProduct, size_t offDP, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDgbmv)(clblasOrder order, clblasTranspose trans, size_t M, size_t N, size_t KL, size_t KU, cl_double alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_double beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +extern CL_RUNTIME_EXPORT clblasStatus (*clblasDgemm)(clblasOrder order, clblasTranspose transA, clblasTranspose transB, size_t M, size_t N, size_t K, cl_double alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, cl_double beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDgemv)(clblasOrder order, clblasTranspose transA, size_t M, size_t N, cl_double alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem x, size_t offx, int incx, cl_double beta, cl_mem y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDger)(clblasOrder order, size_t M, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDnrm2)(size_t N, cl_mem NRM2, size_t offNRM2, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDrot)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_double C, cl_double S, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDrotg)(cl_mem DA, size_t offDA, cl_mem DB, size_t offDB, cl_mem C, size_t offC, cl_mem S, size_t offS, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDrotm)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, const cl_mem DPARAM, size_t offDparam, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDrotmg)(cl_mem DD1, size_t offDD1, cl_mem DD2, size_t offDD2, cl_mem DX1, size_t offDX1, const cl_mem DY1, size_t offDY1, cl_mem DPARAM, size_t offDparam, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsbmv)(clblasOrder order, clblasUplo uplo, size_t N, size_t K, cl_double alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_double beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDscal)(size_t N, cl_double alpha, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDspmv)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem AP, size_t offa, const cl_mem X, size_t offx, int incx, cl_double beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDspr)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDspr2)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDswap)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsymm)(clblasOrder order, clblasSide side, clblasUplo uplo, size_t M, size_t N, cl_double alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_double beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsymv)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem x, size_t offx, int incx, cl_double beta, cl_mem y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsyr)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsyr2)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsyr2k)(clblasOrder order, clblasUplo uplo, clblasTranspose transAB, size_t N, size_t K, cl_double alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, cl_double beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsyrk)(clblasOrder order, clblasUplo uplo, clblasTranspose transA, size_t N, size_t K, cl_double alpha, const cl_mem A, size_t offA, size_t lda, cl_double beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtbmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtbsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtpmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem AP, size_t offa, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtpsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtrmm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, cl_double alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtrmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtrsm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, cl_double alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtrsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDzasum)(size_t N, cl_mem asum, size_t offAsum, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDznrm2)(size_t N, cl_mem NRM2, size_t offNRM2, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasGetVersion)(cl_uint* major, cl_uint* minor, cl_uint* patch); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSasum)(size_t N, cl_mem asum, size_t offAsum, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSaxpy)(size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasScasum)(size_t N, cl_mem asum, size_t offAsum, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasScnrm2)(size_t N, cl_mem NRM2, size_t offNRM2, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasScopy)(size_t N, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSdot)(size_t N, cl_mem dotProduct, size_t offDP, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +extern CL_RUNTIME_EXPORT clblasStatus (*clblasSetup)(); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSgbmv)(clblasOrder order, clblasTranspose trans, size_t M, size_t N, size_t KL, size_t KU, cl_float alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_float beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +extern CL_RUNTIME_EXPORT clblasStatus (*clblasSgemm)(clblasOrder order, clblasTranspose transA, clblasTranspose transB, size_t M, size_t N, size_t K, cl_float alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, cl_float beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSgemv)(clblasOrder order, clblasTranspose transA, size_t M, size_t N, cl_float alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem x, size_t offx, int incx, cl_float beta, cl_mem y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSger)(clblasOrder order, size_t M, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSnrm2)(size_t N, cl_mem NRM2, size_t offNRM2, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSrot)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_float C, cl_float S, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSrotg)(cl_mem SA, size_t offSA, cl_mem SB, size_t offSB, cl_mem C, size_t offC, cl_mem S, size_t offS, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSrotm)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, const cl_mem SPARAM, size_t offSparam, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSrotmg)(cl_mem SD1, size_t offSD1, cl_mem SD2, size_t offSD2, cl_mem SX1, size_t offSX1, const cl_mem SY1, size_t offSY1, cl_mem SPARAM, size_t offSparam, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsbmv)(clblasOrder order, clblasUplo uplo, size_t N, size_t K, cl_float alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_float beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSscal)(size_t N, cl_float alpha, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSspmv)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem AP, size_t offa, const cl_mem X, size_t offx, int incx, cl_float beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSspr)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSspr2)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSswap)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsymm)(clblasOrder order, clblasSide side, clblasUplo uplo, size_t M, size_t N, cl_float alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_float beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsymv)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem x, size_t offx, int incx, cl_float beta, cl_mem y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsyr)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsyr2)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsyr2k)(clblasOrder order, clblasUplo uplo, clblasTranspose transAB, size_t N, size_t K, cl_float alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, cl_float beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsyrk)(clblasOrder order, clblasUplo uplo, clblasTranspose transA, size_t N, size_t K, cl_float alpha, const cl_mem A, size_t offA, size_t lda, cl_float beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStbmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStbsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStpmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem AP, size_t offa, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStpsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStrmm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, cl_float alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStrmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStrsm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, cl_float alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStrsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +extern CL_RUNTIME_EXPORT void (*clblasTeardown)(); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZaxpy)(size_t N, cl_double2 alpha, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZcopy)(size_t N, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZdotc)(size_t N, cl_mem dotProduct, size_t offDP, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZdotu)(size_t N, cl_mem dotProduct, size_t offDP, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZdrot)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_double C, cl_double S, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZdscal)(size_t N, cl_double alpha, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZgbmv)(clblasOrder order, clblasTranspose trans, size_t M, size_t N, size_t KL, size_t KU, cl_double2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_double2 beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +extern CL_RUNTIME_EXPORT clblasStatus (*clblasZgemm)(clblasOrder order, clblasTranspose transA, clblasTranspose transB, size_t M, size_t N, size_t K, DoubleComplex alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, DoubleComplex beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZgemv)(clblasOrder order, clblasTranspose transA, size_t M, size_t N, DoubleComplex alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem x, size_t offx, int incx, DoubleComplex beta, cl_mem y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZgerc)(clblasOrder order, size_t M, size_t N, cl_double2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZgeru)(clblasOrder order, size_t M, size_t N, cl_double2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZhbmv)(clblasOrder order, clblasUplo uplo, size_t N, size_t K, cl_double2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_double2 beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZhemm)(clblasOrder order, clblasSide side, clblasUplo uplo, size_t M, size_t N, cl_double2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_double2 beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZhemv)(clblasOrder order, clblasUplo uplo, size_t N, DoubleComplex alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, DoubleComplex beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZher)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZher2)(clblasOrder order, clblasUplo uplo, size_t N, cl_double2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZher2k)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, size_t N, size_t K, DoubleComplex alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_double beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZherk)(clblasOrder order, clblasUplo uplo, clblasTranspose transA, size_t N, size_t K, double alpha, const cl_mem A, size_t offa, size_t lda, double beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZhpmv)(clblasOrder order, clblasUplo uplo, size_t N, cl_double2 alpha, const cl_mem AP, size_t offa, const cl_mem X, size_t offx, int incx, cl_double2 beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZhpr)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZhpr2)(clblasOrder order, clblasUplo uplo, size_t N, cl_double2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZrotg)(cl_mem CA, size_t offCA, cl_mem CB, size_t offCB, cl_mem C, size_t offC, cl_mem S, size_t offS, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZscal)(size_t N, cl_double2 alpha, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZswap)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZsymm)(clblasOrder order, clblasSide side, clblasUplo uplo, size_t M, size_t N, cl_double2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_double2 beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZsyr2k)(clblasOrder order, clblasUplo uplo, clblasTranspose transAB, size_t N, size_t K, DoubleComplex alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, DoubleComplex beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZsyrk)(clblasOrder order, clblasUplo uplo, clblasTranspose transA, size_t N, size_t K, DoubleComplex alpha, const cl_mem A, size_t offA, size_t lda, DoubleComplex beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtbmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtbsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtpmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem AP, size_t offa, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtpsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtrmm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, DoubleComplex alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtrmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtrsm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, DoubleComplex alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtrsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasiCamax)(size_t N, cl_mem iMax, size_t offiMax, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasiDamax)(size_t N, cl_mem iMax, size_t offiMax, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasiSamax)(size_t N, cl_mem iMax, size_t offiMax, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasiZamax)(size_t N, cl_mem iMax, size_t offiMax, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_clfft.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_clfft.hpp index dff3b406a6..c2d14a28f6 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_clfft.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_clfft.hpp @@ -1,146 +1,146 @@ -// -// AUTOGENERATED, DO NOT EDIT -// -#ifndef OPENCV_CORE_OCL_RUNTIME_CLAMDFFT_HPP -#error "Invalid usage" -#endif - -// generated by parser_clfft.py -#define clfftBakePlan clfftBakePlan_ -#define clfftCopyPlan clfftCopyPlan_ -#define clfftCreateDefaultPlan clfftCreateDefaultPlan_ -#define clfftDestroyPlan clfftDestroyPlan_ -#define clfftEnqueueTransform clfftEnqueueTransform_ -#define clfftGetLayout clfftGetLayout_ -#define clfftGetPlanBatchSize clfftGetPlanBatchSize_ -#define clfftGetPlanContext clfftGetPlanContext_ -#define clfftGetPlanDim clfftGetPlanDim_ -#define clfftGetPlanDistance clfftGetPlanDistance_ -#define clfftGetPlanInStride clfftGetPlanInStride_ -#define clfftGetPlanLength clfftGetPlanLength_ -#define clfftGetPlanOutStride clfftGetPlanOutStride_ -#define clfftGetPlanPrecision clfftGetPlanPrecision_ -#define clfftGetPlanScale clfftGetPlanScale_ -#define clfftGetPlanTransposeResult clfftGetPlanTransposeResult_ -#define clfftGetResultLocation clfftGetResultLocation_ -#define clfftGetTmpBufSize clfftGetTmpBufSize_ -#define clfftGetVersion clfftGetVersion_ -#define clfftSetLayout clfftSetLayout_ -#define clfftSetPlanBatchSize clfftSetPlanBatchSize_ -#define clfftSetPlanCallback clfftSetPlanCallback_ -#define clfftSetPlanDim clfftSetPlanDim_ -#define clfftSetPlanDistance clfftSetPlanDistance_ -#define clfftSetPlanInStride clfftSetPlanInStride_ -#define clfftSetPlanLength clfftSetPlanLength_ -#define clfftSetPlanOutStride clfftSetPlanOutStride_ -#define clfftSetPlanPrecision clfftSetPlanPrecision_ -#define clfftSetPlanScale clfftSetPlanScale_ -#define clfftSetPlanTransposeResult clfftSetPlanTransposeResult_ -#define clfftSetResultLocation clfftSetResultLocation_ -#define clfftSetup clfftSetup_ -#define clfftTeardown clfftTeardown_ - -#include - -// generated by parser_clfft.py -#undef clfftBakePlan -#define clfftBakePlan clfftBakePlan_pfn -#undef clfftCopyPlan -//#define clfftCopyPlan clfftCopyPlan_pfn -#undef clfftCreateDefaultPlan -#define clfftCreateDefaultPlan clfftCreateDefaultPlan_pfn -#undef clfftDestroyPlan -#define clfftDestroyPlan clfftDestroyPlan_pfn -#undef clfftEnqueueTransform -#define clfftEnqueueTransform clfftEnqueueTransform_pfn -#undef clfftGetLayout -//#define clfftGetLayout clfftGetLayout_pfn -#undef clfftGetPlanBatchSize -//#define clfftGetPlanBatchSize clfftGetPlanBatchSize_pfn -#undef clfftGetPlanContext -//#define clfftGetPlanContext clfftGetPlanContext_pfn -#undef clfftGetPlanDim -//#define clfftGetPlanDim clfftGetPlanDim_pfn -#undef clfftGetPlanDistance -//#define clfftGetPlanDistance clfftGetPlanDistance_pfn -#undef clfftGetPlanInStride -//#define clfftGetPlanInStride clfftGetPlanInStride_pfn -#undef clfftGetPlanLength -//#define clfftGetPlanLength clfftGetPlanLength_pfn -#undef clfftGetPlanOutStride -//#define clfftGetPlanOutStride clfftGetPlanOutStride_pfn -#undef clfftGetPlanPrecision -//#define clfftGetPlanPrecision clfftGetPlanPrecision_pfn -#undef clfftGetPlanScale -//#define clfftGetPlanScale clfftGetPlanScale_pfn -#undef clfftGetPlanTransposeResult -//#define clfftGetPlanTransposeResult clfftGetPlanTransposeResult_pfn -#undef clfftGetResultLocation -//#define clfftGetResultLocation clfftGetResultLocation_pfn -#undef clfftGetTmpBufSize -#define clfftGetTmpBufSize clfftGetTmpBufSize_pfn -#undef clfftGetVersion -#define clfftGetVersion clfftGetVersion_pfn -#undef clfftSetLayout -#define clfftSetLayout clfftSetLayout_pfn -#undef clfftSetPlanBatchSize -#define clfftSetPlanBatchSize clfftSetPlanBatchSize_pfn -#undef clfftSetPlanCallback -//#define clfftSetPlanCallback clfftSetPlanCallback_pfn -#undef clfftSetPlanDim -//#define clfftSetPlanDim clfftSetPlanDim_pfn -#undef clfftSetPlanDistance -#define clfftSetPlanDistance clfftSetPlanDistance_pfn -#undef clfftSetPlanInStride -#define clfftSetPlanInStride clfftSetPlanInStride_pfn -#undef clfftSetPlanLength -//#define clfftSetPlanLength clfftSetPlanLength_pfn -#undef clfftSetPlanOutStride -#define clfftSetPlanOutStride clfftSetPlanOutStride_pfn -#undef clfftSetPlanPrecision -#define clfftSetPlanPrecision clfftSetPlanPrecision_pfn -#undef clfftSetPlanScale -#define clfftSetPlanScale clfftSetPlanScale_pfn -#undef clfftSetPlanTransposeResult -//#define clfftSetPlanTransposeResult clfftSetPlanTransposeResult_pfn -#undef clfftSetResultLocation -#define clfftSetResultLocation clfftSetResultLocation_pfn -#undef clfftSetup -#define clfftSetup clfftSetup_pfn -#undef clfftTeardown -#define clfftTeardown clfftTeardown_pfn - -// generated by parser_clfft.py -extern CL_RUNTIME_EXPORT clfftStatus (*clfftBakePlan)(clfftPlanHandle plHandle, cl_uint numQueues, cl_command_queue* commQueueFFT, void (CL_CALLBACK* pfn_notify) (clfftPlanHandle plHandle, void* user_data), void* user_data); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftCopyPlan)(clfftPlanHandle* out_plHandle, cl_context new_context, clfftPlanHandle in_plHandle); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftCreateDefaultPlan)(clfftPlanHandle* plHandle, cl_context context, const clfftDim dim, const size_t* clLengths); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftDestroyPlan)(clfftPlanHandle* plHandle); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftEnqueueTransform)(clfftPlanHandle plHandle, clfftDirection dir, cl_uint numQueuesAndEvents, cl_command_queue* commQueues, cl_uint numWaitEvents, const cl_event* waitEvents, cl_event* outEvents, cl_mem* inputBuffers, cl_mem* outputBuffers, cl_mem tmpBuffer); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetLayout)(const clfftPlanHandle plHandle, clfftLayout* iLayout, clfftLayout* oLayout); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanBatchSize)(const clfftPlanHandle plHandle, size_t* batchSize); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanContext)(const clfftPlanHandle plHandle, cl_context* context); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanDim)(const clfftPlanHandle plHandle, clfftDim* dim, cl_uint* size); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanDistance)(const clfftPlanHandle plHandle, size_t* iDist, size_t* oDist); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanInStride)(const clfftPlanHandle plHandle, const clfftDim dim, size_t* clStrides); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanLength)(const clfftPlanHandle plHandle, const clfftDim dim, size_t* clLengths); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanOutStride)(const clfftPlanHandle plHandle, const clfftDim dim, size_t* clStrides); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanPrecision)(const clfftPlanHandle plHandle, clfftPrecision* precision); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanScale)(const clfftPlanHandle plHandle, clfftDirection dir, cl_float* scale); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanTransposeResult)(const clfftPlanHandle plHandle, clfftResultTransposed* transposed); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetResultLocation)(const clfftPlanHandle plHandle, clfftResultLocation* placeness); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetTmpBufSize)(const clfftPlanHandle plHandle, size_t* buffersize); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetVersion)(cl_uint* major, cl_uint* minor, cl_uint* patch); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetLayout)(clfftPlanHandle plHandle, clfftLayout iLayout, clfftLayout oLayout); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanBatchSize)(clfftPlanHandle plHandle, size_t batchSize); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanCallback)(clfftPlanHandle plHandle, const char* funcName, const char* funcString, int localMemSize, clfftCallbackType callbackType, cl_mem* userdata, int numUserdataBuffers); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanDim)(clfftPlanHandle plHandle, const clfftDim dim); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanDistance)(clfftPlanHandle plHandle, size_t iDist, size_t oDist); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanInStride)(clfftPlanHandle plHandle, const clfftDim dim, size_t* clStrides); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanLength)(clfftPlanHandle plHandle, const clfftDim dim, const size_t* clLengths); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanOutStride)(clfftPlanHandle plHandle, const clfftDim dim, size_t* clStrides); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanPrecision)(clfftPlanHandle plHandle, clfftPrecision precision); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanScale)(clfftPlanHandle plHandle, clfftDirection dir, cl_float scale); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanTransposeResult)(clfftPlanHandle plHandle, clfftResultTransposed transposed); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetResultLocation)(clfftPlanHandle plHandle, clfftResultLocation placeness); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetup)(const clfftSetupData* setupData); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftTeardown)(); +// +// AUTOGENERATED, DO NOT EDIT +// +#ifndef OPENCV_CORE_OCL_RUNTIME_CLAMDFFT_HPP +#error "Invalid usage" +#endif + +// generated by parser_clfft.py +#define clfftBakePlan clfftBakePlan_ +#define clfftCopyPlan clfftCopyPlan_ +#define clfftCreateDefaultPlan clfftCreateDefaultPlan_ +#define clfftDestroyPlan clfftDestroyPlan_ +#define clfftEnqueueTransform clfftEnqueueTransform_ +#define clfftGetLayout clfftGetLayout_ +#define clfftGetPlanBatchSize clfftGetPlanBatchSize_ +#define clfftGetPlanContext clfftGetPlanContext_ +#define clfftGetPlanDim clfftGetPlanDim_ +#define clfftGetPlanDistance clfftGetPlanDistance_ +#define clfftGetPlanInStride clfftGetPlanInStride_ +#define clfftGetPlanLength clfftGetPlanLength_ +#define clfftGetPlanOutStride clfftGetPlanOutStride_ +#define clfftGetPlanPrecision clfftGetPlanPrecision_ +#define clfftGetPlanScale clfftGetPlanScale_ +#define clfftGetPlanTransposeResult clfftGetPlanTransposeResult_ +#define clfftGetResultLocation clfftGetResultLocation_ +#define clfftGetTmpBufSize clfftGetTmpBufSize_ +#define clfftGetVersion clfftGetVersion_ +#define clfftSetLayout clfftSetLayout_ +#define clfftSetPlanBatchSize clfftSetPlanBatchSize_ +#define clfftSetPlanCallback clfftSetPlanCallback_ +#define clfftSetPlanDim clfftSetPlanDim_ +#define clfftSetPlanDistance clfftSetPlanDistance_ +#define clfftSetPlanInStride clfftSetPlanInStride_ +#define clfftSetPlanLength clfftSetPlanLength_ +#define clfftSetPlanOutStride clfftSetPlanOutStride_ +#define clfftSetPlanPrecision clfftSetPlanPrecision_ +#define clfftSetPlanScale clfftSetPlanScale_ +#define clfftSetPlanTransposeResult clfftSetPlanTransposeResult_ +#define clfftSetResultLocation clfftSetResultLocation_ +#define clfftSetup clfftSetup_ +#define clfftTeardown clfftTeardown_ + +#include + +// generated by parser_clfft.py +#undef clfftBakePlan +#define clfftBakePlan clfftBakePlan_pfn +#undef clfftCopyPlan +//#define clfftCopyPlan clfftCopyPlan_pfn +#undef clfftCreateDefaultPlan +#define clfftCreateDefaultPlan clfftCreateDefaultPlan_pfn +#undef clfftDestroyPlan +#define clfftDestroyPlan clfftDestroyPlan_pfn +#undef clfftEnqueueTransform +#define clfftEnqueueTransform clfftEnqueueTransform_pfn +#undef clfftGetLayout +//#define clfftGetLayout clfftGetLayout_pfn +#undef clfftGetPlanBatchSize +//#define clfftGetPlanBatchSize clfftGetPlanBatchSize_pfn +#undef clfftGetPlanContext +//#define clfftGetPlanContext clfftGetPlanContext_pfn +#undef clfftGetPlanDim +//#define clfftGetPlanDim clfftGetPlanDim_pfn +#undef clfftGetPlanDistance +//#define clfftGetPlanDistance clfftGetPlanDistance_pfn +#undef clfftGetPlanInStride +//#define clfftGetPlanInStride clfftGetPlanInStride_pfn +#undef clfftGetPlanLength +//#define clfftGetPlanLength clfftGetPlanLength_pfn +#undef clfftGetPlanOutStride +//#define clfftGetPlanOutStride clfftGetPlanOutStride_pfn +#undef clfftGetPlanPrecision +//#define clfftGetPlanPrecision clfftGetPlanPrecision_pfn +#undef clfftGetPlanScale +//#define clfftGetPlanScale clfftGetPlanScale_pfn +#undef clfftGetPlanTransposeResult +//#define clfftGetPlanTransposeResult clfftGetPlanTransposeResult_pfn +#undef clfftGetResultLocation +//#define clfftGetResultLocation clfftGetResultLocation_pfn +#undef clfftGetTmpBufSize +#define clfftGetTmpBufSize clfftGetTmpBufSize_pfn +#undef clfftGetVersion +#define clfftGetVersion clfftGetVersion_pfn +#undef clfftSetLayout +#define clfftSetLayout clfftSetLayout_pfn +#undef clfftSetPlanBatchSize +#define clfftSetPlanBatchSize clfftSetPlanBatchSize_pfn +#undef clfftSetPlanCallback +//#define clfftSetPlanCallback clfftSetPlanCallback_pfn +#undef clfftSetPlanDim +//#define clfftSetPlanDim clfftSetPlanDim_pfn +#undef clfftSetPlanDistance +#define clfftSetPlanDistance clfftSetPlanDistance_pfn +#undef clfftSetPlanInStride +#define clfftSetPlanInStride clfftSetPlanInStride_pfn +#undef clfftSetPlanLength +//#define clfftSetPlanLength clfftSetPlanLength_pfn +#undef clfftSetPlanOutStride +#define clfftSetPlanOutStride clfftSetPlanOutStride_pfn +#undef clfftSetPlanPrecision +#define clfftSetPlanPrecision clfftSetPlanPrecision_pfn +#undef clfftSetPlanScale +#define clfftSetPlanScale clfftSetPlanScale_pfn +#undef clfftSetPlanTransposeResult +//#define clfftSetPlanTransposeResult clfftSetPlanTransposeResult_pfn +#undef clfftSetResultLocation +#define clfftSetResultLocation clfftSetResultLocation_pfn +#undef clfftSetup +#define clfftSetup clfftSetup_pfn +#undef clfftTeardown +#define clfftTeardown clfftTeardown_pfn + +// generated by parser_clfft.py +extern CL_RUNTIME_EXPORT clfftStatus (*clfftBakePlan)(clfftPlanHandle plHandle, cl_uint numQueues, cl_command_queue* commQueueFFT, void (CL_CALLBACK* pfn_notify) (clfftPlanHandle plHandle, void* user_data), void* user_data); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftCopyPlan)(clfftPlanHandle* out_plHandle, cl_context new_context, clfftPlanHandle in_plHandle); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftCreateDefaultPlan)(clfftPlanHandle* plHandle, cl_context context, const clfftDim dim, const size_t* clLengths); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftDestroyPlan)(clfftPlanHandle* plHandle); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftEnqueueTransform)(clfftPlanHandle plHandle, clfftDirection dir, cl_uint numQueuesAndEvents, cl_command_queue* commQueues, cl_uint numWaitEvents, const cl_event* waitEvents, cl_event* outEvents, cl_mem* inputBuffers, cl_mem* outputBuffers, cl_mem tmpBuffer); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetLayout)(const clfftPlanHandle plHandle, clfftLayout* iLayout, clfftLayout* oLayout); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanBatchSize)(const clfftPlanHandle plHandle, size_t* batchSize); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanContext)(const clfftPlanHandle plHandle, cl_context* context); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanDim)(const clfftPlanHandle plHandle, clfftDim* dim, cl_uint* size); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanDistance)(const clfftPlanHandle plHandle, size_t* iDist, size_t* oDist); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanInStride)(const clfftPlanHandle plHandle, const clfftDim dim, size_t* clStrides); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanLength)(const clfftPlanHandle plHandle, const clfftDim dim, size_t* clLengths); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanOutStride)(const clfftPlanHandle plHandle, const clfftDim dim, size_t* clStrides); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanPrecision)(const clfftPlanHandle plHandle, clfftPrecision* precision); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanScale)(const clfftPlanHandle plHandle, clfftDirection dir, cl_float* scale); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanTransposeResult)(const clfftPlanHandle plHandle, clfftResultTransposed* transposed); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetResultLocation)(const clfftPlanHandle plHandle, clfftResultLocation* placeness); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetTmpBufSize)(const clfftPlanHandle plHandle, size_t* buffersize); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetVersion)(cl_uint* major, cl_uint* minor, cl_uint* patch); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetLayout)(clfftPlanHandle plHandle, clfftLayout iLayout, clfftLayout oLayout); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanBatchSize)(clfftPlanHandle plHandle, size_t batchSize); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanCallback)(clfftPlanHandle plHandle, const char* funcName, const char* funcString, int localMemSize, clfftCallbackType callbackType, cl_mem* userdata, int numUserdataBuffers); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanDim)(clfftPlanHandle plHandle, const clfftDim dim); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanDistance)(clfftPlanHandle plHandle, size_t iDist, size_t oDist); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanInStride)(clfftPlanHandle plHandle, const clfftDim dim, size_t* clStrides); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanLength)(clfftPlanHandle plHandle, const clfftDim dim, const size_t* clLengths); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanOutStride)(clfftPlanHandle plHandle, const clfftDim dim, size_t* clStrides); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanPrecision)(clfftPlanHandle plHandle, clfftPrecision precision); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanScale)(clfftPlanHandle plHandle, clfftDirection dir, cl_float scale); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanTransposeResult)(clfftPlanHandle plHandle, clfftResultTransposed transposed); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetResultLocation)(clfftPlanHandle plHandle, clfftResultLocation placeness); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetup)(const clfftSetupData* setupData); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftTeardown)(); diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_core.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_core.hpp index 28618a1f3a..b170241e3c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_core.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_core.hpp @@ -1,371 +1,371 @@ -// -// AUTOGENERATED, DO NOT EDIT -// -#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_CORE_HPP -#error "Invalid usage" -#endif - -// generated by parser_cl.py -#define clBuildProgram clBuildProgram_ -#define clCompileProgram clCompileProgram_ -#define clCreateBuffer clCreateBuffer_ -#define clCreateCommandQueue clCreateCommandQueue_ -#define clCreateContext clCreateContext_ -#define clCreateContextFromType clCreateContextFromType_ -#define clCreateImage clCreateImage_ -#define clCreateImage2D clCreateImage2D_ -#define clCreateImage3D clCreateImage3D_ -#define clCreateKernel clCreateKernel_ -#define clCreateKernelsInProgram clCreateKernelsInProgram_ -#define clCreateProgramWithBinary clCreateProgramWithBinary_ -#define clCreateProgramWithBuiltInKernels clCreateProgramWithBuiltInKernels_ -#define clCreateProgramWithSource clCreateProgramWithSource_ -#define clCreateSampler clCreateSampler_ -#define clCreateSubBuffer clCreateSubBuffer_ -#define clCreateSubDevices clCreateSubDevices_ -#define clCreateUserEvent clCreateUserEvent_ -#define clEnqueueBarrier clEnqueueBarrier_ -#define clEnqueueBarrierWithWaitList clEnqueueBarrierWithWaitList_ -#define clEnqueueCopyBuffer clEnqueueCopyBuffer_ -#define clEnqueueCopyBufferRect clEnqueueCopyBufferRect_ -#define clEnqueueCopyBufferToImage clEnqueueCopyBufferToImage_ -#define clEnqueueCopyImage clEnqueueCopyImage_ -#define clEnqueueCopyImageToBuffer clEnqueueCopyImageToBuffer_ -#define clEnqueueFillBuffer clEnqueueFillBuffer_ -#define clEnqueueFillImage clEnqueueFillImage_ -#define clEnqueueMapBuffer clEnqueueMapBuffer_ -#define clEnqueueMapImage clEnqueueMapImage_ -#define clEnqueueMarker clEnqueueMarker_ -#define clEnqueueMarkerWithWaitList clEnqueueMarkerWithWaitList_ -#define clEnqueueMigrateMemObjects clEnqueueMigrateMemObjects_ -#define clEnqueueNDRangeKernel clEnqueueNDRangeKernel_ -#define clEnqueueNativeKernel clEnqueueNativeKernel_ -#define clEnqueueReadBuffer clEnqueueReadBuffer_ -#define clEnqueueReadBufferRect clEnqueueReadBufferRect_ -#define clEnqueueReadImage clEnqueueReadImage_ -#define clEnqueueTask clEnqueueTask_ -#define clEnqueueUnmapMemObject clEnqueueUnmapMemObject_ -#define clEnqueueWaitForEvents clEnqueueWaitForEvents_ -#define clEnqueueWriteBuffer clEnqueueWriteBuffer_ -#define clEnqueueWriteBufferRect clEnqueueWriteBufferRect_ -#define clEnqueueWriteImage clEnqueueWriteImage_ -#define clFinish clFinish_ -#define clFlush clFlush_ -#define clGetCommandQueueInfo clGetCommandQueueInfo_ -#define clGetContextInfo clGetContextInfo_ -#define clGetDeviceIDs clGetDeviceIDs_ -#define clGetDeviceInfo clGetDeviceInfo_ -#define clGetEventInfo clGetEventInfo_ -#define clGetEventProfilingInfo clGetEventProfilingInfo_ -#define clGetExtensionFunctionAddress clGetExtensionFunctionAddress_ -#define clGetExtensionFunctionAddressForPlatform clGetExtensionFunctionAddressForPlatform_ -#define clGetImageInfo clGetImageInfo_ -#define clGetKernelArgInfo clGetKernelArgInfo_ -#define clGetKernelInfo clGetKernelInfo_ -#define clGetKernelWorkGroupInfo clGetKernelWorkGroupInfo_ -#define clGetMemObjectInfo clGetMemObjectInfo_ -#define clGetPlatformIDs clGetPlatformIDs_ -#define clGetPlatformInfo clGetPlatformInfo_ -#define clGetProgramBuildInfo clGetProgramBuildInfo_ -#define clGetProgramInfo clGetProgramInfo_ -#define clGetSamplerInfo clGetSamplerInfo_ -#define clGetSupportedImageFormats clGetSupportedImageFormats_ -#define clLinkProgram clLinkProgram_ -#define clReleaseCommandQueue clReleaseCommandQueue_ -#define clReleaseContext clReleaseContext_ -#define clReleaseDevice clReleaseDevice_ -#define clReleaseEvent clReleaseEvent_ -#define clReleaseKernel clReleaseKernel_ -#define clReleaseMemObject clReleaseMemObject_ -#define clReleaseProgram clReleaseProgram_ -#define clReleaseSampler clReleaseSampler_ -#define clRetainCommandQueue clRetainCommandQueue_ -#define clRetainContext clRetainContext_ -#define clRetainDevice clRetainDevice_ -#define clRetainEvent clRetainEvent_ -#define clRetainKernel clRetainKernel_ -#define clRetainMemObject clRetainMemObject_ -#define clRetainProgram clRetainProgram_ -#define clRetainSampler clRetainSampler_ -#define clSetEventCallback clSetEventCallback_ -#define clSetKernelArg clSetKernelArg_ -#define clSetMemObjectDestructorCallback clSetMemObjectDestructorCallback_ -#define clSetUserEventStatus clSetUserEventStatus_ -#define clUnloadCompiler clUnloadCompiler_ -#define clUnloadPlatformCompiler clUnloadPlatformCompiler_ -#define clWaitForEvents clWaitForEvents_ - -#if defined __APPLE__ -#define CL_SILENCE_DEPRECATION -#include -#else -#include -#endif - -// generated by parser_cl.py -#undef clBuildProgram -#define clBuildProgram clBuildProgram_pfn -#undef clCompileProgram -#define clCompileProgram clCompileProgram_pfn -#undef clCreateBuffer -#define clCreateBuffer clCreateBuffer_pfn -#undef clCreateCommandQueue -#define clCreateCommandQueue clCreateCommandQueue_pfn -#undef clCreateContext -#define clCreateContext clCreateContext_pfn -#undef clCreateContextFromType -#define clCreateContextFromType clCreateContextFromType_pfn -#undef clCreateImage -#define clCreateImage clCreateImage_pfn -#undef clCreateImage2D -#define clCreateImage2D clCreateImage2D_pfn -#undef clCreateImage3D -#define clCreateImage3D clCreateImage3D_pfn -#undef clCreateKernel -#define clCreateKernel clCreateKernel_pfn -#undef clCreateKernelsInProgram -#define clCreateKernelsInProgram clCreateKernelsInProgram_pfn -#undef clCreateProgramWithBinary -#define clCreateProgramWithBinary clCreateProgramWithBinary_pfn -#undef clCreateProgramWithBuiltInKernels -#define clCreateProgramWithBuiltInKernels clCreateProgramWithBuiltInKernels_pfn -#undef clCreateProgramWithSource -#define clCreateProgramWithSource clCreateProgramWithSource_pfn -#undef clCreateSampler -#define clCreateSampler clCreateSampler_pfn -#undef clCreateSubBuffer -#define clCreateSubBuffer clCreateSubBuffer_pfn -#undef clCreateSubDevices -#define clCreateSubDevices clCreateSubDevices_pfn -#undef clCreateUserEvent -#define clCreateUserEvent clCreateUserEvent_pfn -#undef clEnqueueBarrier -#define clEnqueueBarrier clEnqueueBarrier_pfn -#undef clEnqueueBarrierWithWaitList -#define clEnqueueBarrierWithWaitList clEnqueueBarrierWithWaitList_pfn -#undef clEnqueueCopyBuffer -#define clEnqueueCopyBuffer clEnqueueCopyBuffer_pfn -#undef clEnqueueCopyBufferRect -#define clEnqueueCopyBufferRect clEnqueueCopyBufferRect_pfn -#undef clEnqueueCopyBufferToImage -#define clEnqueueCopyBufferToImage clEnqueueCopyBufferToImage_pfn -#undef clEnqueueCopyImage -#define clEnqueueCopyImage clEnqueueCopyImage_pfn -#undef clEnqueueCopyImageToBuffer -#define clEnqueueCopyImageToBuffer clEnqueueCopyImageToBuffer_pfn -#undef clEnqueueFillBuffer -#define clEnqueueFillBuffer clEnqueueFillBuffer_pfn -#undef clEnqueueFillImage -#define clEnqueueFillImage clEnqueueFillImage_pfn -#undef clEnqueueMapBuffer -#define clEnqueueMapBuffer clEnqueueMapBuffer_pfn -#undef clEnqueueMapImage -#define clEnqueueMapImage clEnqueueMapImage_pfn -#undef clEnqueueMarker -#define clEnqueueMarker clEnqueueMarker_pfn -#undef clEnqueueMarkerWithWaitList -#define clEnqueueMarkerWithWaitList clEnqueueMarkerWithWaitList_pfn -#undef clEnqueueMigrateMemObjects -#define clEnqueueMigrateMemObjects clEnqueueMigrateMemObjects_pfn -#undef clEnqueueNDRangeKernel -#define clEnqueueNDRangeKernel clEnqueueNDRangeKernel_pfn -#undef clEnqueueNativeKernel -#define clEnqueueNativeKernel clEnqueueNativeKernel_pfn -#undef clEnqueueReadBuffer -#define clEnqueueReadBuffer clEnqueueReadBuffer_pfn -#undef clEnqueueReadBufferRect -#define clEnqueueReadBufferRect clEnqueueReadBufferRect_pfn -#undef clEnqueueReadImage -#define clEnqueueReadImage clEnqueueReadImage_pfn -#undef clEnqueueTask -#define clEnqueueTask clEnqueueTask_pfn -#undef clEnqueueUnmapMemObject -#define clEnqueueUnmapMemObject clEnqueueUnmapMemObject_pfn -#undef clEnqueueWaitForEvents -#define clEnqueueWaitForEvents clEnqueueWaitForEvents_pfn -#undef clEnqueueWriteBuffer -#define clEnqueueWriteBuffer clEnqueueWriteBuffer_pfn -#undef clEnqueueWriteBufferRect -#define clEnqueueWriteBufferRect clEnqueueWriteBufferRect_pfn -#undef clEnqueueWriteImage -#define clEnqueueWriteImage clEnqueueWriteImage_pfn -#undef clFinish -#define clFinish clFinish_pfn -#undef clFlush -#define clFlush clFlush_pfn -#undef clGetCommandQueueInfo -#define clGetCommandQueueInfo clGetCommandQueueInfo_pfn -#undef clGetContextInfo -#define clGetContextInfo clGetContextInfo_pfn -#undef clGetDeviceIDs -#define clGetDeviceIDs clGetDeviceIDs_pfn -#undef clGetDeviceInfo -#define clGetDeviceInfo clGetDeviceInfo_pfn -#undef clGetEventInfo -#define clGetEventInfo clGetEventInfo_pfn -#undef clGetEventProfilingInfo -#define clGetEventProfilingInfo clGetEventProfilingInfo_pfn -#undef clGetExtensionFunctionAddress -#define clGetExtensionFunctionAddress clGetExtensionFunctionAddress_pfn -#undef clGetExtensionFunctionAddressForPlatform -#define clGetExtensionFunctionAddressForPlatform clGetExtensionFunctionAddressForPlatform_pfn -#undef clGetImageInfo -#define clGetImageInfo clGetImageInfo_pfn -#undef clGetKernelArgInfo -#define clGetKernelArgInfo clGetKernelArgInfo_pfn -#undef clGetKernelInfo -#define clGetKernelInfo clGetKernelInfo_pfn -#undef clGetKernelWorkGroupInfo -#define clGetKernelWorkGroupInfo clGetKernelWorkGroupInfo_pfn -#undef clGetMemObjectInfo -#define clGetMemObjectInfo clGetMemObjectInfo_pfn -#undef clGetPlatformIDs -#define clGetPlatformIDs clGetPlatformIDs_pfn -#undef clGetPlatformInfo -#define clGetPlatformInfo clGetPlatformInfo_pfn -#undef clGetProgramBuildInfo -#define clGetProgramBuildInfo clGetProgramBuildInfo_pfn -#undef clGetProgramInfo -#define clGetProgramInfo clGetProgramInfo_pfn -#undef clGetSamplerInfo -#define clGetSamplerInfo clGetSamplerInfo_pfn -#undef clGetSupportedImageFormats -#define clGetSupportedImageFormats clGetSupportedImageFormats_pfn -#undef clLinkProgram -#define clLinkProgram clLinkProgram_pfn -#undef clReleaseCommandQueue -#define clReleaseCommandQueue clReleaseCommandQueue_pfn -#undef clReleaseContext -#define clReleaseContext clReleaseContext_pfn -#undef clReleaseDevice -#define clReleaseDevice clReleaseDevice_pfn -#undef clReleaseEvent -#define clReleaseEvent clReleaseEvent_pfn -#undef clReleaseKernel -#define clReleaseKernel clReleaseKernel_pfn -#undef clReleaseMemObject -#define clReleaseMemObject clReleaseMemObject_pfn -#undef clReleaseProgram -#define clReleaseProgram clReleaseProgram_pfn -#undef clReleaseSampler -#define clReleaseSampler clReleaseSampler_pfn -#undef clRetainCommandQueue -#define clRetainCommandQueue clRetainCommandQueue_pfn -#undef clRetainContext -#define clRetainContext clRetainContext_pfn -#undef clRetainDevice -#define clRetainDevice clRetainDevice_pfn -#undef clRetainEvent -#define clRetainEvent clRetainEvent_pfn -#undef clRetainKernel -#define clRetainKernel clRetainKernel_pfn -#undef clRetainMemObject -#define clRetainMemObject clRetainMemObject_pfn -#undef clRetainProgram -#define clRetainProgram clRetainProgram_pfn -#undef clRetainSampler -#define clRetainSampler clRetainSampler_pfn -#undef clSetEventCallback -#define clSetEventCallback clSetEventCallback_pfn -#undef clSetKernelArg -#define clSetKernelArg clSetKernelArg_pfn -#undef clSetMemObjectDestructorCallback -#define clSetMemObjectDestructorCallback clSetMemObjectDestructorCallback_pfn -#undef clSetUserEventStatus -#define clSetUserEventStatus clSetUserEventStatus_pfn -#undef clUnloadCompiler -#define clUnloadCompiler clUnloadCompiler_pfn -#undef clUnloadPlatformCompiler -#define clUnloadPlatformCompiler clUnloadPlatformCompiler_pfn -#undef clWaitForEvents -#define clWaitForEvents clWaitForEvents_pfn - -// generated by parser_cl.py -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clBuildProgram)(cl_program, cl_uint, const cl_device_id*, const char*, void (CL_CALLBACK*) (cl_program, void*), void*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clCompileProgram)(cl_program, cl_uint, const cl_device_id*, const char*, cl_uint, const cl_program*, const char**, void (CL_CALLBACK*) (cl_program, void*), void*); -extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateBuffer)(cl_context, cl_mem_flags, size_t, void*, cl_int*); -extern CL_RUNTIME_EXPORT cl_command_queue (CL_API_CALL*clCreateCommandQueue)(cl_context, cl_device_id, cl_command_queue_properties, cl_int*); -extern CL_RUNTIME_EXPORT cl_context (CL_API_CALL*clCreateContext)(const cl_context_properties*, cl_uint, const cl_device_id*, void (CL_CALLBACK*) (const char*, const void*, size_t, void*), void*, cl_int*); -extern CL_RUNTIME_EXPORT cl_context (CL_API_CALL*clCreateContextFromType)(const cl_context_properties*, cl_device_type, void (CL_CALLBACK*) (const char*, const void*, size_t, void*), void*, cl_int*); -extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateImage)(cl_context, cl_mem_flags, const cl_image_format*, const cl_image_desc*, void*, cl_int*); -extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateImage2D)(cl_context, cl_mem_flags, const cl_image_format*, size_t, size_t, size_t, void*, cl_int*); -extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateImage3D)(cl_context, cl_mem_flags, const cl_image_format*, size_t, size_t, size_t, size_t, size_t, void*, cl_int*); -extern CL_RUNTIME_EXPORT cl_kernel (CL_API_CALL*clCreateKernel)(cl_program, const char*, cl_int*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clCreateKernelsInProgram)(cl_program, cl_uint, cl_kernel*, cl_uint*); -extern CL_RUNTIME_EXPORT cl_program (CL_API_CALL*clCreateProgramWithBinary)(cl_context, cl_uint, const cl_device_id*, const size_t*, const unsigned char**, cl_int*, cl_int*); -extern CL_RUNTIME_EXPORT cl_program (CL_API_CALL*clCreateProgramWithBuiltInKernels)(cl_context, cl_uint, const cl_device_id*, const char*, cl_int*); -extern CL_RUNTIME_EXPORT cl_program (CL_API_CALL*clCreateProgramWithSource)(cl_context, cl_uint, const char**, const size_t*, cl_int*); -extern CL_RUNTIME_EXPORT cl_sampler (CL_API_CALL*clCreateSampler)(cl_context, cl_bool, cl_addressing_mode, cl_filter_mode, cl_int*); -extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateSubBuffer)(cl_mem, cl_mem_flags, cl_buffer_create_type, const void*, cl_int*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clCreateSubDevices)(cl_device_id, const cl_device_partition_property*, cl_uint, cl_device_id*, cl_uint*); -extern CL_RUNTIME_EXPORT cl_event (CL_API_CALL*clCreateUserEvent)(cl_context, cl_int*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueBarrier)(cl_command_queue); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueBarrierWithWaitList)(cl_command_queue, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueCopyBuffer)(cl_command_queue, cl_mem, cl_mem, size_t, size_t, size_t, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueCopyBufferRect)(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, const size_t*, size_t, size_t, size_t, size_t, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueCopyBufferToImage)(cl_command_queue, cl_mem, cl_mem, size_t, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueCopyImage)(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueCopyImageToBuffer)(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, size_t, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueFillBuffer)(cl_command_queue, cl_mem, const void*, size_t, size_t, size_t, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueFillImage)(cl_command_queue, cl_mem, const void*, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT void* (CL_API_CALL*clEnqueueMapBuffer)(cl_command_queue, cl_mem, cl_bool, cl_map_flags, size_t, size_t, cl_uint, const cl_event*, cl_event*, cl_int*); -extern CL_RUNTIME_EXPORT void* (CL_API_CALL*clEnqueueMapImage)(cl_command_queue, cl_mem, cl_bool, cl_map_flags, const size_t*, const size_t*, size_t*, size_t*, cl_uint, const cl_event*, cl_event*, cl_int*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueMarker)(cl_command_queue, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueMarkerWithWaitList)(cl_command_queue, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueMigrateMemObjects)(cl_command_queue, cl_uint, const cl_mem*, cl_mem_migration_flags, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueNDRangeKernel)(cl_command_queue, cl_kernel, cl_uint, const size_t*, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueNativeKernel)(cl_command_queue, void (CL_CALLBACK*) (void*), void*, size_t, cl_uint, const cl_mem*, const void**, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueReadBuffer)(cl_command_queue, cl_mem, cl_bool, size_t, size_t, void*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueReadBufferRect)(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, const size_t*, size_t, size_t, size_t, size_t, void*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueReadImage)(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, size_t, size_t, void*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueTask)(cl_command_queue, cl_kernel, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueUnmapMemObject)(cl_command_queue, cl_mem, void*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueWaitForEvents)(cl_command_queue, cl_uint, const cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueWriteBuffer)(cl_command_queue, cl_mem, cl_bool, size_t, size_t, const void*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueWriteBufferRect)(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, const size_t*, size_t, size_t, size_t, size_t, const void*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueWriteImage)(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, size_t, size_t, const void*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clFinish)(cl_command_queue); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clFlush)(cl_command_queue); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetCommandQueueInfo)(cl_command_queue, cl_command_queue_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetContextInfo)(cl_context, cl_context_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetDeviceIDs)(cl_platform_id, cl_device_type, cl_uint, cl_device_id*, cl_uint*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetDeviceInfo)(cl_device_id, cl_device_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetEventInfo)(cl_event, cl_event_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetEventProfilingInfo)(cl_event, cl_profiling_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT void* (CL_API_CALL*clGetExtensionFunctionAddress)(const char*); -extern CL_RUNTIME_EXPORT void* (CL_API_CALL*clGetExtensionFunctionAddressForPlatform)(cl_platform_id, const char*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetImageInfo)(cl_mem, cl_image_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetKernelArgInfo)(cl_kernel, cl_uint, cl_kernel_arg_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetKernelInfo)(cl_kernel, cl_kernel_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetKernelWorkGroupInfo)(cl_kernel, cl_device_id, cl_kernel_work_group_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetMemObjectInfo)(cl_mem, cl_mem_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetPlatformIDs)(cl_uint, cl_platform_id*, cl_uint*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetPlatformInfo)(cl_platform_id, cl_platform_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetProgramBuildInfo)(cl_program, cl_device_id, cl_program_build_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetProgramInfo)(cl_program, cl_program_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetSamplerInfo)(cl_sampler, cl_sampler_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetSupportedImageFormats)(cl_context, cl_mem_flags, cl_mem_object_type, cl_uint, cl_image_format*, cl_uint*); -extern CL_RUNTIME_EXPORT cl_program (CL_API_CALL*clLinkProgram)(cl_context, cl_uint, const cl_device_id*, const char*, cl_uint, const cl_program*, void (CL_CALLBACK*) (cl_program, void*), void*, cl_int*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseCommandQueue)(cl_command_queue); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseContext)(cl_context); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseDevice)(cl_device_id); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseEvent)(cl_event); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseKernel)(cl_kernel); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseMemObject)(cl_mem); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseProgram)(cl_program); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseSampler)(cl_sampler); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainCommandQueue)(cl_command_queue); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainContext)(cl_context); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainDevice)(cl_device_id); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainEvent)(cl_event); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainKernel)(cl_kernel); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainMemObject)(cl_mem); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainProgram)(cl_program); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainSampler)(cl_sampler); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clSetEventCallback)(cl_event, cl_int, void (CL_CALLBACK*) (cl_event, cl_int, void*), void*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clSetKernelArg)(cl_kernel, cl_uint, size_t, const void*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clSetMemObjectDestructorCallback)(cl_mem, void (CL_CALLBACK*) (cl_mem, void*), void*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clSetUserEventStatus)(cl_event, cl_int); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clUnloadCompiler)(); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clUnloadPlatformCompiler)(cl_platform_id); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clWaitForEvents)(cl_uint, const cl_event*); +// +// AUTOGENERATED, DO NOT EDIT +// +#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_CORE_HPP +#error "Invalid usage" +#endif + +// generated by parser_cl.py +#define clBuildProgram clBuildProgram_ +#define clCompileProgram clCompileProgram_ +#define clCreateBuffer clCreateBuffer_ +#define clCreateCommandQueue clCreateCommandQueue_ +#define clCreateContext clCreateContext_ +#define clCreateContextFromType clCreateContextFromType_ +#define clCreateImage clCreateImage_ +#define clCreateImage2D clCreateImage2D_ +#define clCreateImage3D clCreateImage3D_ +#define clCreateKernel clCreateKernel_ +#define clCreateKernelsInProgram clCreateKernelsInProgram_ +#define clCreateProgramWithBinary clCreateProgramWithBinary_ +#define clCreateProgramWithBuiltInKernels clCreateProgramWithBuiltInKernels_ +#define clCreateProgramWithSource clCreateProgramWithSource_ +#define clCreateSampler clCreateSampler_ +#define clCreateSubBuffer clCreateSubBuffer_ +#define clCreateSubDevices clCreateSubDevices_ +#define clCreateUserEvent clCreateUserEvent_ +#define clEnqueueBarrier clEnqueueBarrier_ +#define clEnqueueBarrierWithWaitList clEnqueueBarrierWithWaitList_ +#define clEnqueueCopyBuffer clEnqueueCopyBuffer_ +#define clEnqueueCopyBufferRect clEnqueueCopyBufferRect_ +#define clEnqueueCopyBufferToImage clEnqueueCopyBufferToImage_ +#define clEnqueueCopyImage clEnqueueCopyImage_ +#define clEnqueueCopyImageToBuffer clEnqueueCopyImageToBuffer_ +#define clEnqueueFillBuffer clEnqueueFillBuffer_ +#define clEnqueueFillImage clEnqueueFillImage_ +#define clEnqueueMapBuffer clEnqueueMapBuffer_ +#define clEnqueueMapImage clEnqueueMapImage_ +#define clEnqueueMarker clEnqueueMarker_ +#define clEnqueueMarkerWithWaitList clEnqueueMarkerWithWaitList_ +#define clEnqueueMigrateMemObjects clEnqueueMigrateMemObjects_ +#define clEnqueueNDRangeKernel clEnqueueNDRangeKernel_ +#define clEnqueueNativeKernel clEnqueueNativeKernel_ +#define clEnqueueReadBuffer clEnqueueReadBuffer_ +#define clEnqueueReadBufferRect clEnqueueReadBufferRect_ +#define clEnqueueReadImage clEnqueueReadImage_ +#define clEnqueueTask clEnqueueTask_ +#define clEnqueueUnmapMemObject clEnqueueUnmapMemObject_ +#define clEnqueueWaitForEvents clEnqueueWaitForEvents_ +#define clEnqueueWriteBuffer clEnqueueWriteBuffer_ +#define clEnqueueWriteBufferRect clEnqueueWriteBufferRect_ +#define clEnqueueWriteImage clEnqueueWriteImage_ +#define clFinish clFinish_ +#define clFlush clFlush_ +#define clGetCommandQueueInfo clGetCommandQueueInfo_ +#define clGetContextInfo clGetContextInfo_ +#define clGetDeviceIDs clGetDeviceIDs_ +#define clGetDeviceInfo clGetDeviceInfo_ +#define clGetEventInfo clGetEventInfo_ +#define clGetEventProfilingInfo clGetEventProfilingInfo_ +#define clGetExtensionFunctionAddress clGetExtensionFunctionAddress_ +#define clGetExtensionFunctionAddressForPlatform clGetExtensionFunctionAddressForPlatform_ +#define clGetImageInfo clGetImageInfo_ +#define clGetKernelArgInfo clGetKernelArgInfo_ +#define clGetKernelInfo clGetKernelInfo_ +#define clGetKernelWorkGroupInfo clGetKernelWorkGroupInfo_ +#define clGetMemObjectInfo clGetMemObjectInfo_ +#define clGetPlatformIDs clGetPlatformIDs_ +#define clGetPlatformInfo clGetPlatformInfo_ +#define clGetProgramBuildInfo clGetProgramBuildInfo_ +#define clGetProgramInfo clGetProgramInfo_ +#define clGetSamplerInfo clGetSamplerInfo_ +#define clGetSupportedImageFormats clGetSupportedImageFormats_ +#define clLinkProgram clLinkProgram_ +#define clReleaseCommandQueue clReleaseCommandQueue_ +#define clReleaseContext clReleaseContext_ +#define clReleaseDevice clReleaseDevice_ +#define clReleaseEvent clReleaseEvent_ +#define clReleaseKernel clReleaseKernel_ +#define clReleaseMemObject clReleaseMemObject_ +#define clReleaseProgram clReleaseProgram_ +#define clReleaseSampler clReleaseSampler_ +#define clRetainCommandQueue clRetainCommandQueue_ +#define clRetainContext clRetainContext_ +#define clRetainDevice clRetainDevice_ +#define clRetainEvent clRetainEvent_ +#define clRetainKernel clRetainKernel_ +#define clRetainMemObject clRetainMemObject_ +#define clRetainProgram clRetainProgram_ +#define clRetainSampler clRetainSampler_ +#define clSetEventCallback clSetEventCallback_ +#define clSetKernelArg clSetKernelArg_ +#define clSetMemObjectDestructorCallback clSetMemObjectDestructorCallback_ +#define clSetUserEventStatus clSetUserEventStatus_ +#define clUnloadCompiler clUnloadCompiler_ +#define clUnloadPlatformCompiler clUnloadPlatformCompiler_ +#define clWaitForEvents clWaitForEvents_ + +#if defined __APPLE__ +#define CL_SILENCE_DEPRECATION +#include +#else +#include +#endif + +// generated by parser_cl.py +#undef clBuildProgram +#define clBuildProgram clBuildProgram_pfn +#undef clCompileProgram +#define clCompileProgram clCompileProgram_pfn +#undef clCreateBuffer +#define clCreateBuffer clCreateBuffer_pfn +#undef clCreateCommandQueue +#define clCreateCommandQueue clCreateCommandQueue_pfn +#undef clCreateContext +#define clCreateContext clCreateContext_pfn +#undef clCreateContextFromType +#define clCreateContextFromType clCreateContextFromType_pfn +#undef clCreateImage +#define clCreateImage clCreateImage_pfn +#undef clCreateImage2D +#define clCreateImage2D clCreateImage2D_pfn +#undef clCreateImage3D +#define clCreateImage3D clCreateImage3D_pfn +#undef clCreateKernel +#define clCreateKernel clCreateKernel_pfn +#undef clCreateKernelsInProgram +#define clCreateKernelsInProgram clCreateKernelsInProgram_pfn +#undef clCreateProgramWithBinary +#define clCreateProgramWithBinary clCreateProgramWithBinary_pfn +#undef clCreateProgramWithBuiltInKernels +#define clCreateProgramWithBuiltInKernels clCreateProgramWithBuiltInKernels_pfn +#undef clCreateProgramWithSource +#define clCreateProgramWithSource clCreateProgramWithSource_pfn +#undef clCreateSampler +#define clCreateSampler clCreateSampler_pfn +#undef clCreateSubBuffer +#define clCreateSubBuffer clCreateSubBuffer_pfn +#undef clCreateSubDevices +#define clCreateSubDevices clCreateSubDevices_pfn +#undef clCreateUserEvent +#define clCreateUserEvent clCreateUserEvent_pfn +#undef clEnqueueBarrier +#define clEnqueueBarrier clEnqueueBarrier_pfn +#undef clEnqueueBarrierWithWaitList +#define clEnqueueBarrierWithWaitList clEnqueueBarrierWithWaitList_pfn +#undef clEnqueueCopyBuffer +#define clEnqueueCopyBuffer clEnqueueCopyBuffer_pfn +#undef clEnqueueCopyBufferRect +#define clEnqueueCopyBufferRect clEnqueueCopyBufferRect_pfn +#undef clEnqueueCopyBufferToImage +#define clEnqueueCopyBufferToImage clEnqueueCopyBufferToImage_pfn +#undef clEnqueueCopyImage +#define clEnqueueCopyImage clEnqueueCopyImage_pfn +#undef clEnqueueCopyImageToBuffer +#define clEnqueueCopyImageToBuffer clEnqueueCopyImageToBuffer_pfn +#undef clEnqueueFillBuffer +#define clEnqueueFillBuffer clEnqueueFillBuffer_pfn +#undef clEnqueueFillImage +#define clEnqueueFillImage clEnqueueFillImage_pfn +#undef clEnqueueMapBuffer +#define clEnqueueMapBuffer clEnqueueMapBuffer_pfn +#undef clEnqueueMapImage +#define clEnqueueMapImage clEnqueueMapImage_pfn +#undef clEnqueueMarker +#define clEnqueueMarker clEnqueueMarker_pfn +#undef clEnqueueMarkerWithWaitList +#define clEnqueueMarkerWithWaitList clEnqueueMarkerWithWaitList_pfn +#undef clEnqueueMigrateMemObjects +#define clEnqueueMigrateMemObjects clEnqueueMigrateMemObjects_pfn +#undef clEnqueueNDRangeKernel +#define clEnqueueNDRangeKernel clEnqueueNDRangeKernel_pfn +#undef clEnqueueNativeKernel +#define clEnqueueNativeKernel clEnqueueNativeKernel_pfn +#undef clEnqueueReadBuffer +#define clEnqueueReadBuffer clEnqueueReadBuffer_pfn +#undef clEnqueueReadBufferRect +#define clEnqueueReadBufferRect clEnqueueReadBufferRect_pfn +#undef clEnqueueReadImage +#define clEnqueueReadImage clEnqueueReadImage_pfn +#undef clEnqueueTask +#define clEnqueueTask clEnqueueTask_pfn +#undef clEnqueueUnmapMemObject +#define clEnqueueUnmapMemObject clEnqueueUnmapMemObject_pfn +#undef clEnqueueWaitForEvents +#define clEnqueueWaitForEvents clEnqueueWaitForEvents_pfn +#undef clEnqueueWriteBuffer +#define clEnqueueWriteBuffer clEnqueueWriteBuffer_pfn +#undef clEnqueueWriteBufferRect +#define clEnqueueWriteBufferRect clEnqueueWriteBufferRect_pfn +#undef clEnqueueWriteImage +#define clEnqueueWriteImage clEnqueueWriteImage_pfn +#undef clFinish +#define clFinish clFinish_pfn +#undef clFlush +#define clFlush clFlush_pfn +#undef clGetCommandQueueInfo +#define clGetCommandQueueInfo clGetCommandQueueInfo_pfn +#undef clGetContextInfo +#define clGetContextInfo clGetContextInfo_pfn +#undef clGetDeviceIDs +#define clGetDeviceIDs clGetDeviceIDs_pfn +#undef clGetDeviceInfo +#define clGetDeviceInfo clGetDeviceInfo_pfn +#undef clGetEventInfo +#define clGetEventInfo clGetEventInfo_pfn +#undef clGetEventProfilingInfo +#define clGetEventProfilingInfo clGetEventProfilingInfo_pfn +#undef clGetExtensionFunctionAddress +#define clGetExtensionFunctionAddress clGetExtensionFunctionAddress_pfn +#undef clGetExtensionFunctionAddressForPlatform +#define clGetExtensionFunctionAddressForPlatform clGetExtensionFunctionAddressForPlatform_pfn +#undef clGetImageInfo +#define clGetImageInfo clGetImageInfo_pfn +#undef clGetKernelArgInfo +#define clGetKernelArgInfo clGetKernelArgInfo_pfn +#undef clGetKernelInfo +#define clGetKernelInfo clGetKernelInfo_pfn +#undef clGetKernelWorkGroupInfo +#define clGetKernelWorkGroupInfo clGetKernelWorkGroupInfo_pfn +#undef clGetMemObjectInfo +#define clGetMemObjectInfo clGetMemObjectInfo_pfn +#undef clGetPlatformIDs +#define clGetPlatformIDs clGetPlatformIDs_pfn +#undef clGetPlatformInfo +#define clGetPlatformInfo clGetPlatformInfo_pfn +#undef clGetProgramBuildInfo +#define clGetProgramBuildInfo clGetProgramBuildInfo_pfn +#undef clGetProgramInfo +#define clGetProgramInfo clGetProgramInfo_pfn +#undef clGetSamplerInfo +#define clGetSamplerInfo clGetSamplerInfo_pfn +#undef clGetSupportedImageFormats +#define clGetSupportedImageFormats clGetSupportedImageFormats_pfn +#undef clLinkProgram +#define clLinkProgram clLinkProgram_pfn +#undef clReleaseCommandQueue +#define clReleaseCommandQueue clReleaseCommandQueue_pfn +#undef clReleaseContext +#define clReleaseContext clReleaseContext_pfn +#undef clReleaseDevice +#define clReleaseDevice clReleaseDevice_pfn +#undef clReleaseEvent +#define clReleaseEvent clReleaseEvent_pfn +#undef clReleaseKernel +#define clReleaseKernel clReleaseKernel_pfn +#undef clReleaseMemObject +#define clReleaseMemObject clReleaseMemObject_pfn +#undef clReleaseProgram +#define clReleaseProgram clReleaseProgram_pfn +#undef clReleaseSampler +#define clReleaseSampler clReleaseSampler_pfn +#undef clRetainCommandQueue +#define clRetainCommandQueue clRetainCommandQueue_pfn +#undef clRetainContext +#define clRetainContext clRetainContext_pfn +#undef clRetainDevice +#define clRetainDevice clRetainDevice_pfn +#undef clRetainEvent +#define clRetainEvent clRetainEvent_pfn +#undef clRetainKernel +#define clRetainKernel clRetainKernel_pfn +#undef clRetainMemObject +#define clRetainMemObject clRetainMemObject_pfn +#undef clRetainProgram +#define clRetainProgram clRetainProgram_pfn +#undef clRetainSampler +#define clRetainSampler clRetainSampler_pfn +#undef clSetEventCallback +#define clSetEventCallback clSetEventCallback_pfn +#undef clSetKernelArg +#define clSetKernelArg clSetKernelArg_pfn +#undef clSetMemObjectDestructorCallback +#define clSetMemObjectDestructorCallback clSetMemObjectDestructorCallback_pfn +#undef clSetUserEventStatus +#define clSetUserEventStatus clSetUserEventStatus_pfn +#undef clUnloadCompiler +#define clUnloadCompiler clUnloadCompiler_pfn +#undef clUnloadPlatformCompiler +#define clUnloadPlatformCompiler clUnloadPlatformCompiler_pfn +#undef clWaitForEvents +#define clWaitForEvents clWaitForEvents_pfn + +// generated by parser_cl.py +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clBuildProgram)(cl_program, cl_uint, const cl_device_id*, const char*, void (CL_CALLBACK*) (cl_program, void*), void*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clCompileProgram)(cl_program, cl_uint, const cl_device_id*, const char*, cl_uint, const cl_program*, const char**, void (CL_CALLBACK*) (cl_program, void*), void*); +extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateBuffer)(cl_context, cl_mem_flags, size_t, void*, cl_int*); +extern CL_RUNTIME_EXPORT cl_command_queue (CL_API_CALL*clCreateCommandQueue)(cl_context, cl_device_id, cl_command_queue_properties, cl_int*); +extern CL_RUNTIME_EXPORT cl_context (CL_API_CALL*clCreateContext)(const cl_context_properties*, cl_uint, const cl_device_id*, void (CL_CALLBACK*) (const char*, const void*, size_t, void*), void*, cl_int*); +extern CL_RUNTIME_EXPORT cl_context (CL_API_CALL*clCreateContextFromType)(const cl_context_properties*, cl_device_type, void (CL_CALLBACK*) (const char*, const void*, size_t, void*), void*, cl_int*); +extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateImage)(cl_context, cl_mem_flags, const cl_image_format*, const cl_image_desc*, void*, cl_int*); +extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateImage2D)(cl_context, cl_mem_flags, const cl_image_format*, size_t, size_t, size_t, void*, cl_int*); +extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateImage3D)(cl_context, cl_mem_flags, const cl_image_format*, size_t, size_t, size_t, size_t, size_t, void*, cl_int*); +extern CL_RUNTIME_EXPORT cl_kernel (CL_API_CALL*clCreateKernel)(cl_program, const char*, cl_int*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clCreateKernelsInProgram)(cl_program, cl_uint, cl_kernel*, cl_uint*); +extern CL_RUNTIME_EXPORT cl_program (CL_API_CALL*clCreateProgramWithBinary)(cl_context, cl_uint, const cl_device_id*, const size_t*, const unsigned char**, cl_int*, cl_int*); +extern CL_RUNTIME_EXPORT cl_program (CL_API_CALL*clCreateProgramWithBuiltInKernels)(cl_context, cl_uint, const cl_device_id*, const char*, cl_int*); +extern CL_RUNTIME_EXPORT cl_program (CL_API_CALL*clCreateProgramWithSource)(cl_context, cl_uint, const char**, const size_t*, cl_int*); +extern CL_RUNTIME_EXPORT cl_sampler (CL_API_CALL*clCreateSampler)(cl_context, cl_bool, cl_addressing_mode, cl_filter_mode, cl_int*); +extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateSubBuffer)(cl_mem, cl_mem_flags, cl_buffer_create_type, const void*, cl_int*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clCreateSubDevices)(cl_device_id, const cl_device_partition_property*, cl_uint, cl_device_id*, cl_uint*); +extern CL_RUNTIME_EXPORT cl_event (CL_API_CALL*clCreateUserEvent)(cl_context, cl_int*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueBarrier)(cl_command_queue); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueBarrierWithWaitList)(cl_command_queue, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueCopyBuffer)(cl_command_queue, cl_mem, cl_mem, size_t, size_t, size_t, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueCopyBufferRect)(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, const size_t*, size_t, size_t, size_t, size_t, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueCopyBufferToImage)(cl_command_queue, cl_mem, cl_mem, size_t, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueCopyImage)(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueCopyImageToBuffer)(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, size_t, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueFillBuffer)(cl_command_queue, cl_mem, const void*, size_t, size_t, size_t, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueFillImage)(cl_command_queue, cl_mem, const void*, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT void* (CL_API_CALL*clEnqueueMapBuffer)(cl_command_queue, cl_mem, cl_bool, cl_map_flags, size_t, size_t, cl_uint, const cl_event*, cl_event*, cl_int*); +extern CL_RUNTIME_EXPORT void* (CL_API_CALL*clEnqueueMapImage)(cl_command_queue, cl_mem, cl_bool, cl_map_flags, const size_t*, const size_t*, size_t*, size_t*, cl_uint, const cl_event*, cl_event*, cl_int*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueMarker)(cl_command_queue, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueMarkerWithWaitList)(cl_command_queue, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueMigrateMemObjects)(cl_command_queue, cl_uint, const cl_mem*, cl_mem_migration_flags, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueNDRangeKernel)(cl_command_queue, cl_kernel, cl_uint, const size_t*, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueNativeKernel)(cl_command_queue, void (CL_CALLBACK*) (void*), void*, size_t, cl_uint, const cl_mem*, const void**, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueReadBuffer)(cl_command_queue, cl_mem, cl_bool, size_t, size_t, void*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueReadBufferRect)(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, const size_t*, size_t, size_t, size_t, size_t, void*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueReadImage)(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, size_t, size_t, void*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueTask)(cl_command_queue, cl_kernel, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueUnmapMemObject)(cl_command_queue, cl_mem, void*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueWaitForEvents)(cl_command_queue, cl_uint, const cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueWriteBuffer)(cl_command_queue, cl_mem, cl_bool, size_t, size_t, const void*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueWriteBufferRect)(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, const size_t*, size_t, size_t, size_t, size_t, const void*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueWriteImage)(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, size_t, size_t, const void*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clFinish)(cl_command_queue); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clFlush)(cl_command_queue); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetCommandQueueInfo)(cl_command_queue, cl_command_queue_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetContextInfo)(cl_context, cl_context_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetDeviceIDs)(cl_platform_id, cl_device_type, cl_uint, cl_device_id*, cl_uint*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetDeviceInfo)(cl_device_id, cl_device_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetEventInfo)(cl_event, cl_event_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetEventProfilingInfo)(cl_event, cl_profiling_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT void* (CL_API_CALL*clGetExtensionFunctionAddress)(const char*); +extern CL_RUNTIME_EXPORT void* (CL_API_CALL*clGetExtensionFunctionAddressForPlatform)(cl_platform_id, const char*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetImageInfo)(cl_mem, cl_image_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetKernelArgInfo)(cl_kernel, cl_uint, cl_kernel_arg_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetKernelInfo)(cl_kernel, cl_kernel_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetKernelWorkGroupInfo)(cl_kernel, cl_device_id, cl_kernel_work_group_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetMemObjectInfo)(cl_mem, cl_mem_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetPlatformIDs)(cl_uint, cl_platform_id*, cl_uint*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetPlatformInfo)(cl_platform_id, cl_platform_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetProgramBuildInfo)(cl_program, cl_device_id, cl_program_build_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetProgramInfo)(cl_program, cl_program_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetSamplerInfo)(cl_sampler, cl_sampler_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetSupportedImageFormats)(cl_context, cl_mem_flags, cl_mem_object_type, cl_uint, cl_image_format*, cl_uint*); +extern CL_RUNTIME_EXPORT cl_program (CL_API_CALL*clLinkProgram)(cl_context, cl_uint, const cl_device_id*, const char*, cl_uint, const cl_program*, void (CL_CALLBACK*) (cl_program, void*), void*, cl_int*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseCommandQueue)(cl_command_queue); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseContext)(cl_context); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseDevice)(cl_device_id); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseEvent)(cl_event); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseKernel)(cl_kernel); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseMemObject)(cl_mem); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseProgram)(cl_program); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseSampler)(cl_sampler); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainCommandQueue)(cl_command_queue); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainContext)(cl_context); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainDevice)(cl_device_id); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainEvent)(cl_event); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainKernel)(cl_kernel); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainMemObject)(cl_mem); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainProgram)(cl_program); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainSampler)(cl_sampler); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clSetEventCallback)(cl_event, cl_int, void (CL_CALLBACK*) (cl_event, cl_int, void*), void*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clSetKernelArg)(cl_kernel, cl_uint, size_t, const void*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clSetMemObjectDestructorCallback)(cl_mem, void (CL_CALLBACK*) (cl_mem, void*), void*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clSetUserEventStatus)(cl_event, cl_int); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clUnloadCompiler)(); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clUnloadPlatformCompiler)(cl_platform_id); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clWaitForEvents)(cl_uint, const cl_event*); diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_core_wrappers.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_core_wrappers.hpp index 216b22b8a8..418b5126c3 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_core_wrappers.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_core_wrappers.hpp @@ -1,272 +1,272 @@ -// -// AUTOGENERATED, DO NOT EDIT -// -#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_WRAPPERS_HPP -#error "Invalid usage" -#endif - -// generated by parser_cl.py -#undef clBuildProgram -#define clBuildProgram clBuildProgram_fn -inline cl_int clBuildProgram(cl_program p0, cl_uint p1, const cl_device_id* p2, const char* p3, void (CL_CALLBACK*p4) (cl_program, void*), void* p5) { return clBuildProgram_pfn(p0, p1, p2, p3, p4, p5); } -#undef clCompileProgram -#define clCompileProgram clCompileProgram_fn -inline cl_int clCompileProgram(cl_program p0, cl_uint p1, const cl_device_id* p2, const char* p3, cl_uint p4, const cl_program* p5, const char** p6, void (CL_CALLBACK*p7) (cl_program, void*), void* p8) { return clCompileProgram_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } -#undef clCreateBuffer -#define clCreateBuffer clCreateBuffer_fn -inline cl_mem clCreateBuffer(cl_context p0, cl_mem_flags p1, size_t p2, void* p3, cl_int* p4) { return clCreateBuffer_pfn(p0, p1, p2, p3, p4); } -#undef clCreateCommandQueue -#define clCreateCommandQueue clCreateCommandQueue_fn -inline cl_command_queue clCreateCommandQueue(cl_context p0, cl_device_id p1, cl_command_queue_properties p2, cl_int* p3) { return clCreateCommandQueue_pfn(p0, p1, p2, p3); } -#undef clCreateContext -#define clCreateContext clCreateContext_fn -inline cl_context clCreateContext(const cl_context_properties* p0, cl_uint p1, const cl_device_id* p2, void (CL_CALLBACK*p3) (const char*, const void*, size_t, void*), void* p4, cl_int* p5) { return clCreateContext_pfn(p0, p1, p2, p3, p4, p5); } -#undef clCreateContextFromType -#define clCreateContextFromType clCreateContextFromType_fn -inline cl_context clCreateContextFromType(const cl_context_properties* p0, cl_device_type p1, void (CL_CALLBACK*p2) (const char*, const void*, size_t, void*), void* p3, cl_int* p4) { return clCreateContextFromType_pfn(p0, p1, p2, p3, p4); } -#undef clCreateImage -#define clCreateImage clCreateImage_fn -inline cl_mem clCreateImage(cl_context p0, cl_mem_flags p1, const cl_image_format* p2, const cl_image_desc* p3, void* p4, cl_int* p5) { return clCreateImage_pfn(p0, p1, p2, p3, p4, p5); } -#undef clCreateImage2D -#define clCreateImage2D clCreateImage2D_fn -inline cl_mem clCreateImage2D(cl_context p0, cl_mem_flags p1, const cl_image_format* p2, size_t p3, size_t p4, size_t p5, void* p6, cl_int* p7) { return clCreateImage2D_pfn(p0, p1, p2, p3, p4, p5, p6, p7); } -#undef clCreateImage3D -#define clCreateImage3D clCreateImage3D_fn -inline cl_mem clCreateImage3D(cl_context p0, cl_mem_flags p1, const cl_image_format* p2, size_t p3, size_t p4, size_t p5, size_t p6, size_t p7, void* p8, cl_int* p9) { return clCreateImage3D_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); } -#undef clCreateKernel -#define clCreateKernel clCreateKernel_fn -inline cl_kernel clCreateKernel(cl_program p0, const char* p1, cl_int* p2) { return clCreateKernel_pfn(p0, p1, p2); } -#undef clCreateKernelsInProgram -#define clCreateKernelsInProgram clCreateKernelsInProgram_fn -inline cl_int clCreateKernelsInProgram(cl_program p0, cl_uint p1, cl_kernel* p2, cl_uint* p3) { return clCreateKernelsInProgram_pfn(p0, p1, p2, p3); } -#undef clCreateProgramWithBinary -#define clCreateProgramWithBinary clCreateProgramWithBinary_fn -inline cl_program clCreateProgramWithBinary(cl_context p0, cl_uint p1, const cl_device_id* p2, const size_t* p3, const unsigned char** p4, cl_int* p5, cl_int* p6) { return clCreateProgramWithBinary_pfn(p0, p1, p2, p3, p4, p5, p6); } -#undef clCreateProgramWithBuiltInKernels -#define clCreateProgramWithBuiltInKernels clCreateProgramWithBuiltInKernels_fn -inline cl_program clCreateProgramWithBuiltInKernels(cl_context p0, cl_uint p1, const cl_device_id* p2, const char* p3, cl_int* p4) { return clCreateProgramWithBuiltInKernels_pfn(p0, p1, p2, p3, p4); } -#undef clCreateProgramWithSource -#define clCreateProgramWithSource clCreateProgramWithSource_fn -inline cl_program clCreateProgramWithSource(cl_context p0, cl_uint p1, const char** p2, const size_t* p3, cl_int* p4) { return clCreateProgramWithSource_pfn(p0, p1, p2, p3, p4); } -#undef clCreateSampler -#define clCreateSampler clCreateSampler_fn -inline cl_sampler clCreateSampler(cl_context p0, cl_bool p1, cl_addressing_mode p2, cl_filter_mode p3, cl_int* p4) { return clCreateSampler_pfn(p0, p1, p2, p3, p4); } -#undef clCreateSubBuffer -#define clCreateSubBuffer clCreateSubBuffer_fn -inline cl_mem clCreateSubBuffer(cl_mem p0, cl_mem_flags p1, cl_buffer_create_type p2, const void* p3, cl_int* p4) { return clCreateSubBuffer_pfn(p0, p1, p2, p3, p4); } -#undef clCreateSubDevices -#define clCreateSubDevices clCreateSubDevices_fn -inline cl_int clCreateSubDevices(cl_device_id p0, const cl_device_partition_property* p1, cl_uint p2, cl_device_id* p3, cl_uint* p4) { return clCreateSubDevices_pfn(p0, p1, p2, p3, p4); } -#undef clCreateUserEvent -#define clCreateUserEvent clCreateUserEvent_fn -inline cl_event clCreateUserEvent(cl_context p0, cl_int* p1) { return clCreateUserEvent_pfn(p0, p1); } -#undef clEnqueueBarrier -#define clEnqueueBarrier clEnqueueBarrier_fn -inline cl_int clEnqueueBarrier(cl_command_queue p0) { return clEnqueueBarrier_pfn(p0); } -#undef clEnqueueBarrierWithWaitList -#define clEnqueueBarrierWithWaitList clEnqueueBarrierWithWaitList_fn -inline cl_int clEnqueueBarrierWithWaitList(cl_command_queue p0, cl_uint p1, const cl_event* p2, cl_event* p3) { return clEnqueueBarrierWithWaitList_pfn(p0, p1, p2, p3); } -#undef clEnqueueCopyBuffer -#define clEnqueueCopyBuffer clEnqueueCopyBuffer_fn -inline cl_int clEnqueueCopyBuffer(cl_command_queue p0, cl_mem p1, cl_mem p2, size_t p3, size_t p4, size_t p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueCopyBuffer_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } -#undef clEnqueueCopyBufferRect -#define clEnqueueCopyBufferRect clEnqueueCopyBufferRect_fn -inline cl_int clEnqueueCopyBufferRect(cl_command_queue p0, cl_mem p1, cl_mem p2, const size_t* p3, const size_t* p4, const size_t* p5, size_t p6, size_t p7, size_t p8, size_t p9, cl_uint p10, const cl_event* p11, cl_event* p12) { return clEnqueueCopyBufferRect_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12); } -#undef clEnqueueCopyBufferToImage -#define clEnqueueCopyBufferToImage clEnqueueCopyBufferToImage_fn -inline cl_int clEnqueueCopyBufferToImage(cl_command_queue p0, cl_mem p1, cl_mem p2, size_t p3, const size_t* p4, const size_t* p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueCopyBufferToImage_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } -#undef clEnqueueCopyImage -#define clEnqueueCopyImage clEnqueueCopyImage_fn -inline cl_int clEnqueueCopyImage(cl_command_queue p0, cl_mem p1, cl_mem p2, const size_t* p3, const size_t* p4, const size_t* p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueCopyImage_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } -#undef clEnqueueCopyImageToBuffer -#define clEnqueueCopyImageToBuffer clEnqueueCopyImageToBuffer_fn -inline cl_int clEnqueueCopyImageToBuffer(cl_command_queue p0, cl_mem p1, cl_mem p2, const size_t* p3, const size_t* p4, size_t p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueCopyImageToBuffer_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } -#undef clEnqueueFillBuffer -#define clEnqueueFillBuffer clEnqueueFillBuffer_fn -inline cl_int clEnqueueFillBuffer(cl_command_queue p0, cl_mem p1, const void* p2, size_t p3, size_t p4, size_t p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueFillBuffer_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } -#undef clEnqueueFillImage -#define clEnqueueFillImage clEnqueueFillImage_fn -inline cl_int clEnqueueFillImage(cl_command_queue p0, cl_mem p1, const void* p2, const size_t* p3, const size_t* p4, cl_uint p5, const cl_event* p6, cl_event* p7) { return clEnqueueFillImage_pfn(p0, p1, p2, p3, p4, p5, p6, p7); } -#undef clEnqueueMapBuffer -#define clEnqueueMapBuffer clEnqueueMapBuffer_fn -inline void* clEnqueueMapBuffer(cl_command_queue p0, cl_mem p1, cl_bool p2, cl_map_flags p3, size_t p4, size_t p5, cl_uint p6, const cl_event* p7, cl_event* p8, cl_int* p9) { return clEnqueueMapBuffer_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); } -#undef clEnqueueMapImage -#define clEnqueueMapImage clEnqueueMapImage_fn -inline void* clEnqueueMapImage(cl_command_queue p0, cl_mem p1, cl_bool p2, cl_map_flags p3, const size_t* p4, const size_t* p5, size_t* p6, size_t* p7, cl_uint p8, const cl_event* p9, cl_event* p10, cl_int* p11) { return clEnqueueMapImage_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11); } -#undef clEnqueueMarker -#define clEnqueueMarker clEnqueueMarker_fn -inline cl_int clEnqueueMarker(cl_command_queue p0, cl_event* p1) { return clEnqueueMarker_pfn(p0, p1); } -#undef clEnqueueMarkerWithWaitList -#define clEnqueueMarkerWithWaitList clEnqueueMarkerWithWaitList_fn -inline cl_int clEnqueueMarkerWithWaitList(cl_command_queue p0, cl_uint p1, const cl_event* p2, cl_event* p3) { return clEnqueueMarkerWithWaitList_pfn(p0, p1, p2, p3); } -#undef clEnqueueMigrateMemObjects -#define clEnqueueMigrateMemObjects clEnqueueMigrateMemObjects_fn -inline cl_int clEnqueueMigrateMemObjects(cl_command_queue p0, cl_uint p1, const cl_mem* p2, cl_mem_migration_flags p3, cl_uint p4, const cl_event* p5, cl_event* p6) { return clEnqueueMigrateMemObjects_pfn(p0, p1, p2, p3, p4, p5, p6); } -#undef clEnqueueNDRangeKernel -#define clEnqueueNDRangeKernel clEnqueueNDRangeKernel_fn -inline cl_int clEnqueueNDRangeKernel(cl_command_queue p0, cl_kernel p1, cl_uint p2, const size_t* p3, const size_t* p4, const size_t* p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueNDRangeKernel_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } -#undef clEnqueueNativeKernel -#define clEnqueueNativeKernel clEnqueueNativeKernel_fn -inline cl_int clEnqueueNativeKernel(cl_command_queue p0, void (CL_CALLBACK*p1) (void*), void* p2, size_t p3, cl_uint p4, const cl_mem* p5, const void** p6, cl_uint p7, const cl_event* p8, cl_event* p9) { return clEnqueueNativeKernel_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); } -#undef clEnqueueReadBuffer -#define clEnqueueReadBuffer clEnqueueReadBuffer_fn -inline cl_int clEnqueueReadBuffer(cl_command_queue p0, cl_mem p1, cl_bool p2, size_t p3, size_t p4, void* p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueReadBuffer_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } -#undef clEnqueueReadBufferRect -#define clEnqueueReadBufferRect clEnqueueReadBufferRect_fn -inline cl_int clEnqueueReadBufferRect(cl_command_queue p0, cl_mem p1, cl_bool p2, const size_t* p3, const size_t* p4, const size_t* p5, size_t p6, size_t p7, size_t p8, size_t p9, void* p10, cl_uint p11, const cl_event* p12, cl_event* p13) { return clEnqueueReadBufferRect_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13); } -#undef clEnqueueReadImage -#define clEnqueueReadImage clEnqueueReadImage_fn -inline cl_int clEnqueueReadImage(cl_command_queue p0, cl_mem p1, cl_bool p2, const size_t* p3, const size_t* p4, size_t p5, size_t p6, void* p7, cl_uint p8, const cl_event* p9, cl_event* p10) { return clEnqueueReadImage_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10); } -#undef clEnqueueTask -#define clEnqueueTask clEnqueueTask_fn -inline cl_int clEnqueueTask(cl_command_queue p0, cl_kernel p1, cl_uint p2, const cl_event* p3, cl_event* p4) { return clEnqueueTask_pfn(p0, p1, p2, p3, p4); } -#undef clEnqueueUnmapMemObject -#define clEnqueueUnmapMemObject clEnqueueUnmapMemObject_fn -inline cl_int clEnqueueUnmapMemObject(cl_command_queue p0, cl_mem p1, void* p2, cl_uint p3, const cl_event* p4, cl_event* p5) { return clEnqueueUnmapMemObject_pfn(p0, p1, p2, p3, p4, p5); } -#undef clEnqueueWaitForEvents -#define clEnqueueWaitForEvents clEnqueueWaitForEvents_fn -inline cl_int clEnqueueWaitForEvents(cl_command_queue p0, cl_uint p1, const cl_event* p2) { return clEnqueueWaitForEvents_pfn(p0, p1, p2); } -#undef clEnqueueWriteBuffer -#define clEnqueueWriteBuffer clEnqueueWriteBuffer_fn -inline cl_int clEnqueueWriteBuffer(cl_command_queue p0, cl_mem p1, cl_bool p2, size_t p3, size_t p4, const void* p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueWriteBuffer_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } -#undef clEnqueueWriteBufferRect -#define clEnqueueWriteBufferRect clEnqueueWriteBufferRect_fn -inline cl_int clEnqueueWriteBufferRect(cl_command_queue p0, cl_mem p1, cl_bool p2, const size_t* p3, const size_t* p4, const size_t* p5, size_t p6, size_t p7, size_t p8, size_t p9, const void* p10, cl_uint p11, const cl_event* p12, cl_event* p13) { return clEnqueueWriteBufferRect_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13); } -#undef clEnqueueWriteImage -#define clEnqueueWriteImage clEnqueueWriteImage_fn -inline cl_int clEnqueueWriteImage(cl_command_queue p0, cl_mem p1, cl_bool p2, const size_t* p3, const size_t* p4, size_t p5, size_t p6, const void* p7, cl_uint p8, const cl_event* p9, cl_event* p10) { return clEnqueueWriteImage_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10); } -#undef clFinish -#define clFinish clFinish_fn -inline cl_int clFinish(cl_command_queue p0) { return clFinish_pfn(p0); } -#undef clFlush -#define clFlush clFlush_fn -inline cl_int clFlush(cl_command_queue p0) { return clFlush_pfn(p0); } -#undef clGetCommandQueueInfo -#define clGetCommandQueueInfo clGetCommandQueueInfo_fn -inline cl_int clGetCommandQueueInfo(cl_command_queue p0, cl_command_queue_info p1, size_t p2, void* p3, size_t* p4) { return clGetCommandQueueInfo_pfn(p0, p1, p2, p3, p4); } -#undef clGetContextInfo -#define clGetContextInfo clGetContextInfo_fn -inline cl_int clGetContextInfo(cl_context p0, cl_context_info p1, size_t p2, void* p3, size_t* p4) { return clGetContextInfo_pfn(p0, p1, p2, p3, p4); } -#undef clGetDeviceIDs -#define clGetDeviceIDs clGetDeviceIDs_fn -inline cl_int clGetDeviceIDs(cl_platform_id p0, cl_device_type p1, cl_uint p2, cl_device_id* p3, cl_uint* p4) { return clGetDeviceIDs_pfn(p0, p1, p2, p3, p4); } -#undef clGetDeviceInfo -#define clGetDeviceInfo clGetDeviceInfo_fn -inline cl_int clGetDeviceInfo(cl_device_id p0, cl_device_info p1, size_t p2, void* p3, size_t* p4) { return clGetDeviceInfo_pfn(p0, p1, p2, p3, p4); } -#undef clGetEventInfo -#define clGetEventInfo clGetEventInfo_fn -inline cl_int clGetEventInfo(cl_event p0, cl_event_info p1, size_t p2, void* p3, size_t* p4) { return clGetEventInfo_pfn(p0, p1, p2, p3, p4); } -#undef clGetEventProfilingInfo -#define clGetEventProfilingInfo clGetEventProfilingInfo_fn -inline cl_int clGetEventProfilingInfo(cl_event p0, cl_profiling_info p1, size_t p2, void* p3, size_t* p4) { return clGetEventProfilingInfo_pfn(p0, p1, p2, p3, p4); } -#undef clGetExtensionFunctionAddress -#define clGetExtensionFunctionAddress clGetExtensionFunctionAddress_fn -inline void* clGetExtensionFunctionAddress(const char* p0) { return clGetExtensionFunctionAddress_pfn(p0); } -#undef clGetExtensionFunctionAddressForPlatform -#define clGetExtensionFunctionAddressForPlatform clGetExtensionFunctionAddressForPlatform_fn -inline void* clGetExtensionFunctionAddressForPlatform(cl_platform_id p0, const char* p1) { return clGetExtensionFunctionAddressForPlatform_pfn(p0, p1); } -#undef clGetImageInfo -#define clGetImageInfo clGetImageInfo_fn -inline cl_int clGetImageInfo(cl_mem p0, cl_image_info p1, size_t p2, void* p3, size_t* p4) { return clGetImageInfo_pfn(p0, p1, p2, p3, p4); } -#undef clGetKernelArgInfo -#define clGetKernelArgInfo clGetKernelArgInfo_fn -inline cl_int clGetKernelArgInfo(cl_kernel p0, cl_uint p1, cl_kernel_arg_info p2, size_t p3, void* p4, size_t* p5) { return clGetKernelArgInfo_pfn(p0, p1, p2, p3, p4, p5); } -#undef clGetKernelInfo -#define clGetKernelInfo clGetKernelInfo_fn -inline cl_int clGetKernelInfo(cl_kernel p0, cl_kernel_info p1, size_t p2, void* p3, size_t* p4) { return clGetKernelInfo_pfn(p0, p1, p2, p3, p4); } -#undef clGetKernelWorkGroupInfo -#define clGetKernelWorkGroupInfo clGetKernelWorkGroupInfo_fn -inline cl_int clGetKernelWorkGroupInfo(cl_kernel p0, cl_device_id p1, cl_kernel_work_group_info p2, size_t p3, void* p4, size_t* p5) { return clGetKernelWorkGroupInfo_pfn(p0, p1, p2, p3, p4, p5); } -#undef clGetMemObjectInfo -#define clGetMemObjectInfo clGetMemObjectInfo_fn -inline cl_int clGetMemObjectInfo(cl_mem p0, cl_mem_info p1, size_t p2, void* p3, size_t* p4) { return clGetMemObjectInfo_pfn(p0, p1, p2, p3, p4); } -#undef clGetPlatformIDs -#define clGetPlatformIDs clGetPlatformIDs_fn -inline cl_int clGetPlatformIDs(cl_uint p0, cl_platform_id* p1, cl_uint* p2) { return clGetPlatformIDs_pfn(p0, p1, p2); } -#undef clGetPlatformInfo -#define clGetPlatformInfo clGetPlatformInfo_fn -inline cl_int clGetPlatformInfo(cl_platform_id p0, cl_platform_info p1, size_t p2, void* p3, size_t* p4) { return clGetPlatformInfo_pfn(p0, p1, p2, p3, p4); } -#undef clGetProgramBuildInfo -#define clGetProgramBuildInfo clGetProgramBuildInfo_fn -inline cl_int clGetProgramBuildInfo(cl_program p0, cl_device_id p1, cl_program_build_info p2, size_t p3, void* p4, size_t* p5) { return clGetProgramBuildInfo_pfn(p0, p1, p2, p3, p4, p5); } -#undef clGetProgramInfo -#define clGetProgramInfo clGetProgramInfo_fn -inline cl_int clGetProgramInfo(cl_program p0, cl_program_info p1, size_t p2, void* p3, size_t* p4) { return clGetProgramInfo_pfn(p0, p1, p2, p3, p4); } -#undef clGetSamplerInfo -#define clGetSamplerInfo clGetSamplerInfo_fn -inline cl_int clGetSamplerInfo(cl_sampler p0, cl_sampler_info p1, size_t p2, void* p3, size_t* p4) { return clGetSamplerInfo_pfn(p0, p1, p2, p3, p4); } -#undef clGetSupportedImageFormats -#define clGetSupportedImageFormats clGetSupportedImageFormats_fn -inline cl_int clGetSupportedImageFormats(cl_context p0, cl_mem_flags p1, cl_mem_object_type p2, cl_uint p3, cl_image_format* p4, cl_uint* p5) { return clGetSupportedImageFormats_pfn(p0, p1, p2, p3, p4, p5); } -#undef clLinkProgram -#define clLinkProgram clLinkProgram_fn -inline cl_program clLinkProgram(cl_context p0, cl_uint p1, const cl_device_id* p2, const char* p3, cl_uint p4, const cl_program* p5, void (CL_CALLBACK*p6) (cl_program, void*), void* p7, cl_int* p8) { return clLinkProgram_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } -#undef clReleaseCommandQueue -#define clReleaseCommandQueue clReleaseCommandQueue_fn -inline cl_int clReleaseCommandQueue(cl_command_queue p0) { return clReleaseCommandQueue_pfn(p0); } -#undef clReleaseContext -#define clReleaseContext clReleaseContext_fn -inline cl_int clReleaseContext(cl_context p0) { return clReleaseContext_pfn(p0); } -#undef clReleaseDevice -#define clReleaseDevice clReleaseDevice_fn -inline cl_int clReleaseDevice(cl_device_id p0) { return clReleaseDevice_pfn(p0); } -#undef clReleaseEvent -#define clReleaseEvent clReleaseEvent_fn -inline cl_int clReleaseEvent(cl_event p0) { return clReleaseEvent_pfn(p0); } -#undef clReleaseKernel -#define clReleaseKernel clReleaseKernel_fn -inline cl_int clReleaseKernel(cl_kernel p0) { return clReleaseKernel_pfn(p0); } -#undef clReleaseMemObject -#define clReleaseMemObject clReleaseMemObject_fn -inline cl_int clReleaseMemObject(cl_mem p0) { return clReleaseMemObject_pfn(p0); } -#undef clReleaseProgram -#define clReleaseProgram clReleaseProgram_fn -inline cl_int clReleaseProgram(cl_program p0) { return clReleaseProgram_pfn(p0); } -#undef clReleaseSampler -#define clReleaseSampler clReleaseSampler_fn -inline cl_int clReleaseSampler(cl_sampler p0) { return clReleaseSampler_pfn(p0); } -#undef clRetainCommandQueue -#define clRetainCommandQueue clRetainCommandQueue_fn -inline cl_int clRetainCommandQueue(cl_command_queue p0) { return clRetainCommandQueue_pfn(p0); } -#undef clRetainContext -#define clRetainContext clRetainContext_fn -inline cl_int clRetainContext(cl_context p0) { return clRetainContext_pfn(p0); } -#undef clRetainDevice -#define clRetainDevice clRetainDevice_fn -inline cl_int clRetainDevice(cl_device_id p0) { return clRetainDevice_pfn(p0); } -#undef clRetainEvent -#define clRetainEvent clRetainEvent_fn -inline cl_int clRetainEvent(cl_event p0) { return clRetainEvent_pfn(p0); } -#undef clRetainKernel -#define clRetainKernel clRetainKernel_fn -inline cl_int clRetainKernel(cl_kernel p0) { return clRetainKernel_pfn(p0); } -#undef clRetainMemObject -#define clRetainMemObject clRetainMemObject_fn -inline cl_int clRetainMemObject(cl_mem p0) { return clRetainMemObject_pfn(p0); } -#undef clRetainProgram -#define clRetainProgram clRetainProgram_fn -inline cl_int clRetainProgram(cl_program p0) { return clRetainProgram_pfn(p0); } -#undef clRetainSampler -#define clRetainSampler clRetainSampler_fn -inline cl_int clRetainSampler(cl_sampler p0) { return clRetainSampler_pfn(p0); } -#undef clSetEventCallback -#define clSetEventCallback clSetEventCallback_fn -inline cl_int clSetEventCallback(cl_event p0, cl_int p1, void (CL_CALLBACK*p2) (cl_event, cl_int, void*), void* p3) { return clSetEventCallback_pfn(p0, p1, p2, p3); } -#undef clSetKernelArg -#define clSetKernelArg clSetKernelArg_fn -inline cl_int clSetKernelArg(cl_kernel p0, cl_uint p1, size_t p2, const void* p3) { return clSetKernelArg_pfn(p0, p1, p2, p3); } -#undef clSetMemObjectDestructorCallback -#define clSetMemObjectDestructorCallback clSetMemObjectDestructorCallback_fn -inline cl_int clSetMemObjectDestructorCallback(cl_mem p0, void (CL_CALLBACK*p1) (cl_mem, void*), void* p2) { return clSetMemObjectDestructorCallback_pfn(p0, p1, p2); } -#undef clSetUserEventStatus -#define clSetUserEventStatus clSetUserEventStatus_fn -inline cl_int clSetUserEventStatus(cl_event p0, cl_int p1) { return clSetUserEventStatus_pfn(p0, p1); } -#undef clUnloadCompiler -#define clUnloadCompiler clUnloadCompiler_fn -inline cl_int clUnloadCompiler() { return clUnloadCompiler_pfn(); } -#undef clUnloadPlatformCompiler -#define clUnloadPlatformCompiler clUnloadPlatformCompiler_fn -inline cl_int clUnloadPlatformCompiler(cl_platform_id p0) { return clUnloadPlatformCompiler_pfn(p0); } -#undef clWaitForEvents -#define clWaitForEvents clWaitForEvents_fn -inline cl_int clWaitForEvents(cl_uint p0, const cl_event* p1) { return clWaitForEvents_pfn(p0, p1); } +// +// AUTOGENERATED, DO NOT EDIT +// +#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_WRAPPERS_HPP +#error "Invalid usage" +#endif + +// generated by parser_cl.py +#undef clBuildProgram +#define clBuildProgram clBuildProgram_fn +inline cl_int clBuildProgram(cl_program p0, cl_uint p1, const cl_device_id* p2, const char* p3, void (CL_CALLBACK*p4) (cl_program, void*), void* p5) { return clBuildProgram_pfn(p0, p1, p2, p3, p4, p5); } +#undef clCompileProgram +#define clCompileProgram clCompileProgram_fn +inline cl_int clCompileProgram(cl_program p0, cl_uint p1, const cl_device_id* p2, const char* p3, cl_uint p4, const cl_program* p5, const char** p6, void (CL_CALLBACK*p7) (cl_program, void*), void* p8) { return clCompileProgram_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } +#undef clCreateBuffer +#define clCreateBuffer clCreateBuffer_fn +inline cl_mem clCreateBuffer(cl_context p0, cl_mem_flags p1, size_t p2, void* p3, cl_int* p4) { return clCreateBuffer_pfn(p0, p1, p2, p3, p4); } +#undef clCreateCommandQueue +#define clCreateCommandQueue clCreateCommandQueue_fn +inline cl_command_queue clCreateCommandQueue(cl_context p0, cl_device_id p1, cl_command_queue_properties p2, cl_int* p3) { return clCreateCommandQueue_pfn(p0, p1, p2, p3); } +#undef clCreateContext +#define clCreateContext clCreateContext_fn +inline cl_context clCreateContext(const cl_context_properties* p0, cl_uint p1, const cl_device_id* p2, void (CL_CALLBACK*p3) (const char*, const void*, size_t, void*), void* p4, cl_int* p5) { return clCreateContext_pfn(p0, p1, p2, p3, p4, p5); } +#undef clCreateContextFromType +#define clCreateContextFromType clCreateContextFromType_fn +inline cl_context clCreateContextFromType(const cl_context_properties* p0, cl_device_type p1, void (CL_CALLBACK*p2) (const char*, const void*, size_t, void*), void* p3, cl_int* p4) { return clCreateContextFromType_pfn(p0, p1, p2, p3, p4); } +#undef clCreateImage +#define clCreateImage clCreateImage_fn +inline cl_mem clCreateImage(cl_context p0, cl_mem_flags p1, const cl_image_format* p2, const cl_image_desc* p3, void* p4, cl_int* p5) { return clCreateImage_pfn(p0, p1, p2, p3, p4, p5); } +#undef clCreateImage2D +#define clCreateImage2D clCreateImage2D_fn +inline cl_mem clCreateImage2D(cl_context p0, cl_mem_flags p1, const cl_image_format* p2, size_t p3, size_t p4, size_t p5, void* p6, cl_int* p7) { return clCreateImage2D_pfn(p0, p1, p2, p3, p4, p5, p6, p7); } +#undef clCreateImage3D +#define clCreateImage3D clCreateImage3D_fn +inline cl_mem clCreateImage3D(cl_context p0, cl_mem_flags p1, const cl_image_format* p2, size_t p3, size_t p4, size_t p5, size_t p6, size_t p7, void* p8, cl_int* p9) { return clCreateImage3D_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); } +#undef clCreateKernel +#define clCreateKernel clCreateKernel_fn +inline cl_kernel clCreateKernel(cl_program p0, const char* p1, cl_int* p2) { return clCreateKernel_pfn(p0, p1, p2); } +#undef clCreateKernelsInProgram +#define clCreateKernelsInProgram clCreateKernelsInProgram_fn +inline cl_int clCreateKernelsInProgram(cl_program p0, cl_uint p1, cl_kernel* p2, cl_uint* p3) { return clCreateKernelsInProgram_pfn(p0, p1, p2, p3); } +#undef clCreateProgramWithBinary +#define clCreateProgramWithBinary clCreateProgramWithBinary_fn +inline cl_program clCreateProgramWithBinary(cl_context p0, cl_uint p1, const cl_device_id* p2, const size_t* p3, const unsigned char** p4, cl_int* p5, cl_int* p6) { return clCreateProgramWithBinary_pfn(p0, p1, p2, p3, p4, p5, p6); } +#undef clCreateProgramWithBuiltInKernels +#define clCreateProgramWithBuiltInKernels clCreateProgramWithBuiltInKernels_fn +inline cl_program clCreateProgramWithBuiltInKernels(cl_context p0, cl_uint p1, const cl_device_id* p2, const char* p3, cl_int* p4) { return clCreateProgramWithBuiltInKernels_pfn(p0, p1, p2, p3, p4); } +#undef clCreateProgramWithSource +#define clCreateProgramWithSource clCreateProgramWithSource_fn +inline cl_program clCreateProgramWithSource(cl_context p0, cl_uint p1, const char** p2, const size_t* p3, cl_int* p4) { return clCreateProgramWithSource_pfn(p0, p1, p2, p3, p4); } +#undef clCreateSampler +#define clCreateSampler clCreateSampler_fn +inline cl_sampler clCreateSampler(cl_context p0, cl_bool p1, cl_addressing_mode p2, cl_filter_mode p3, cl_int* p4) { return clCreateSampler_pfn(p0, p1, p2, p3, p4); } +#undef clCreateSubBuffer +#define clCreateSubBuffer clCreateSubBuffer_fn +inline cl_mem clCreateSubBuffer(cl_mem p0, cl_mem_flags p1, cl_buffer_create_type p2, const void* p3, cl_int* p4) { return clCreateSubBuffer_pfn(p0, p1, p2, p3, p4); } +#undef clCreateSubDevices +#define clCreateSubDevices clCreateSubDevices_fn +inline cl_int clCreateSubDevices(cl_device_id p0, const cl_device_partition_property* p1, cl_uint p2, cl_device_id* p3, cl_uint* p4) { return clCreateSubDevices_pfn(p0, p1, p2, p3, p4); } +#undef clCreateUserEvent +#define clCreateUserEvent clCreateUserEvent_fn +inline cl_event clCreateUserEvent(cl_context p0, cl_int* p1) { return clCreateUserEvent_pfn(p0, p1); } +#undef clEnqueueBarrier +#define clEnqueueBarrier clEnqueueBarrier_fn +inline cl_int clEnqueueBarrier(cl_command_queue p0) { return clEnqueueBarrier_pfn(p0); } +#undef clEnqueueBarrierWithWaitList +#define clEnqueueBarrierWithWaitList clEnqueueBarrierWithWaitList_fn +inline cl_int clEnqueueBarrierWithWaitList(cl_command_queue p0, cl_uint p1, const cl_event* p2, cl_event* p3) { return clEnqueueBarrierWithWaitList_pfn(p0, p1, p2, p3); } +#undef clEnqueueCopyBuffer +#define clEnqueueCopyBuffer clEnqueueCopyBuffer_fn +inline cl_int clEnqueueCopyBuffer(cl_command_queue p0, cl_mem p1, cl_mem p2, size_t p3, size_t p4, size_t p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueCopyBuffer_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } +#undef clEnqueueCopyBufferRect +#define clEnqueueCopyBufferRect clEnqueueCopyBufferRect_fn +inline cl_int clEnqueueCopyBufferRect(cl_command_queue p0, cl_mem p1, cl_mem p2, const size_t* p3, const size_t* p4, const size_t* p5, size_t p6, size_t p7, size_t p8, size_t p9, cl_uint p10, const cl_event* p11, cl_event* p12) { return clEnqueueCopyBufferRect_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12); } +#undef clEnqueueCopyBufferToImage +#define clEnqueueCopyBufferToImage clEnqueueCopyBufferToImage_fn +inline cl_int clEnqueueCopyBufferToImage(cl_command_queue p0, cl_mem p1, cl_mem p2, size_t p3, const size_t* p4, const size_t* p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueCopyBufferToImage_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } +#undef clEnqueueCopyImage +#define clEnqueueCopyImage clEnqueueCopyImage_fn +inline cl_int clEnqueueCopyImage(cl_command_queue p0, cl_mem p1, cl_mem p2, const size_t* p3, const size_t* p4, const size_t* p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueCopyImage_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } +#undef clEnqueueCopyImageToBuffer +#define clEnqueueCopyImageToBuffer clEnqueueCopyImageToBuffer_fn +inline cl_int clEnqueueCopyImageToBuffer(cl_command_queue p0, cl_mem p1, cl_mem p2, const size_t* p3, const size_t* p4, size_t p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueCopyImageToBuffer_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } +#undef clEnqueueFillBuffer +#define clEnqueueFillBuffer clEnqueueFillBuffer_fn +inline cl_int clEnqueueFillBuffer(cl_command_queue p0, cl_mem p1, const void* p2, size_t p3, size_t p4, size_t p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueFillBuffer_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } +#undef clEnqueueFillImage +#define clEnqueueFillImage clEnqueueFillImage_fn +inline cl_int clEnqueueFillImage(cl_command_queue p0, cl_mem p1, const void* p2, const size_t* p3, const size_t* p4, cl_uint p5, const cl_event* p6, cl_event* p7) { return clEnqueueFillImage_pfn(p0, p1, p2, p3, p4, p5, p6, p7); } +#undef clEnqueueMapBuffer +#define clEnqueueMapBuffer clEnqueueMapBuffer_fn +inline void* clEnqueueMapBuffer(cl_command_queue p0, cl_mem p1, cl_bool p2, cl_map_flags p3, size_t p4, size_t p5, cl_uint p6, const cl_event* p7, cl_event* p8, cl_int* p9) { return clEnqueueMapBuffer_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); } +#undef clEnqueueMapImage +#define clEnqueueMapImage clEnqueueMapImage_fn +inline void* clEnqueueMapImage(cl_command_queue p0, cl_mem p1, cl_bool p2, cl_map_flags p3, const size_t* p4, const size_t* p5, size_t* p6, size_t* p7, cl_uint p8, const cl_event* p9, cl_event* p10, cl_int* p11) { return clEnqueueMapImage_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11); } +#undef clEnqueueMarker +#define clEnqueueMarker clEnqueueMarker_fn +inline cl_int clEnqueueMarker(cl_command_queue p0, cl_event* p1) { return clEnqueueMarker_pfn(p0, p1); } +#undef clEnqueueMarkerWithWaitList +#define clEnqueueMarkerWithWaitList clEnqueueMarkerWithWaitList_fn +inline cl_int clEnqueueMarkerWithWaitList(cl_command_queue p0, cl_uint p1, const cl_event* p2, cl_event* p3) { return clEnqueueMarkerWithWaitList_pfn(p0, p1, p2, p3); } +#undef clEnqueueMigrateMemObjects +#define clEnqueueMigrateMemObjects clEnqueueMigrateMemObjects_fn +inline cl_int clEnqueueMigrateMemObjects(cl_command_queue p0, cl_uint p1, const cl_mem* p2, cl_mem_migration_flags p3, cl_uint p4, const cl_event* p5, cl_event* p6) { return clEnqueueMigrateMemObjects_pfn(p0, p1, p2, p3, p4, p5, p6); } +#undef clEnqueueNDRangeKernel +#define clEnqueueNDRangeKernel clEnqueueNDRangeKernel_fn +inline cl_int clEnqueueNDRangeKernel(cl_command_queue p0, cl_kernel p1, cl_uint p2, const size_t* p3, const size_t* p4, const size_t* p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueNDRangeKernel_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } +#undef clEnqueueNativeKernel +#define clEnqueueNativeKernel clEnqueueNativeKernel_fn +inline cl_int clEnqueueNativeKernel(cl_command_queue p0, void (CL_CALLBACK*p1) (void*), void* p2, size_t p3, cl_uint p4, const cl_mem* p5, const void** p6, cl_uint p7, const cl_event* p8, cl_event* p9) { return clEnqueueNativeKernel_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); } +#undef clEnqueueReadBuffer +#define clEnqueueReadBuffer clEnqueueReadBuffer_fn +inline cl_int clEnqueueReadBuffer(cl_command_queue p0, cl_mem p1, cl_bool p2, size_t p3, size_t p4, void* p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueReadBuffer_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } +#undef clEnqueueReadBufferRect +#define clEnqueueReadBufferRect clEnqueueReadBufferRect_fn +inline cl_int clEnqueueReadBufferRect(cl_command_queue p0, cl_mem p1, cl_bool p2, const size_t* p3, const size_t* p4, const size_t* p5, size_t p6, size_t p7, size_t p8, size_t p9, void* p10, cl_uint p11, const cl_event* p12, cl_event* p13) { return clEnqueueReadBufferRect_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13); } +#undef clEnqueueReadImage +#define clEnqueueReadImage clEnqueueReadImage_fn +inline cl_int clEnqueueReadImage(cl_command_queue p0, cl_mem p1, cl_bool p2, const size_t* p3, const size_t* p4, size_t p5, size_t p6, void* p7, cl_uint p8, const cl_event* p9, cl_event* p10) { return clEnqueueReadImage_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10); } +#undef clEnqueueTask +#define clEnqueueTask clEnqueueTask_fn +inline cl_int clEnqueueTask(cl_command_queue p0, cl_kernel p1, cl_uint p2, const cl_event* p3, cl_event* p4) { return clEnqueueTask_pfn(p0, p1, p2, p3, p4); } +#undef clEnqueueUnmapMemObject +#define clEnqueueUnmapMemObject clEnqueueUnmapMemObject_fn +inline cl_int clEnqueueUnmapMemObject(cl_command_queue p0, cl_mem p1, void* p2, cl_uint p3, const cl_event* p4, cl_event* p5) { return clEnqueueUnmapMemObject_pfn(p0, p1, p2, p3, p4, p5); } +#undef clEnqueueWaitForEvents +#define clEnqueueWaitForEvents clEnqueueWaitForEvents_fn +inline cl_int clEnqueueWaitForEvents(cl_command_queue p0, cl_uint p1, const cl_event* p2) { return clEnqueueWaitForEvents_pfn(p0, p1, p2); } +#undef clEnqueueWriteBuffer +#define clEnqueueWriteBuffer clEnqueueWriteBuffer_fn +inline cl_int clEnqueueWriteBuffer(cl_command_queue p0, cl_mem p1, cl_bool p2, size_t p3, size_t p4, const void* p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueWriteBuffer_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } +#undef clEnqueueWriteBufferRect +#define clEnqueueWriteBufferRect clEnqueueWriteBufferRect_fn +inline cl_int clEnqueueWriteBufferRect(cl_command_queue p0, cl_mem p1, cl_bool p2, const size_t* p3, const size_t* p4, const size_t* p5, size_t p6, size_t p7, size_t p8, size_t p9, const void* p10, cl_uint p11, const cl_event* p12, cl_event* p13) { return clEnqueueWriteBufferRect_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13); } +#undef clEnqueueWriteImage +#define clEnqueueWriteImage clEnqueueWriteImage_fn +inline cl_int clEnqueueWriteImage(cl_command_queue p0, cl_mem p1, cl_bool p2, const size_t* p3, const size_t* p4, size_t p5, size_t p6, const void* p7, cl_uint p8, const cl_event* p9, cl_event* p10) { return clEnqueueWriteImage_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10); } +#undef clFinish +#define clFinish clFinish_fn +inline cl_int clFinish(cl_command_queue p0) { return clFinish_pfn(p0); } +#undef clFlush +#define clFlush clFlush_fn +inline cl_int clFlush(cl_command_queue p0) { return clFlush_pfn(p0); } +#undef clGetCommandQueueInfo +#define clGetCommandQueueInfo clGetCommandQueueInfo_fn +inline cl_int clGetCommandQueueInfo(cl_command_queue p0, cl_command_queue_info p1, size_t p2, void* p3, size_t* p4) { return clGetCommandQueueInfo_pfn(p0, p1, p2, p3, p4); } +#undef clGetContextInfo +#define clGetContextInfo clGetContextInfo_fn +inline cl_int clGetContextInfo(cl_context p0, cl_context_info p1, size_t p2, void* p3, size_t* p4) { return clGetContextInfo_pfn(p0, p1, p2, p3, p4); } +#undef clGetDeviceIDs +#define clGetDeviceIDs clGetDeviceIDs_fn +inline cl_int clGetDeviceIDs(cl_platform_id p0, cl_device_type p1, cl_uint p2, cl_device_id* p3, cl_uint* p4) { return clGetDeviceIDs_pfn(p0, p1, p2, p3, p4); } +#undef clGetDeviceInfo +#define clGetDeviceInfo clGetDeviceInfo_fn +inline cl_int clGetDeviceInfo(cl_device_id p0, cl_device_info p1, size_t p2, void* p3, size_t* p4) { return clGetDeviceInfo_pfn(p0, p1, p2, p3, p4); } +#undef clGetEventInfo +#define clGetEventInfo clGetEventInfo_fn +inline cl_int clGetEventInfo(cl_event p0, cl_event_info p1, size_t p2, void* p3, size_t* p4) { return clGetEventInfo_pfn(p0, p1, p2, p3, p4); } +#undef clGetEventProfilingInfo +#define clGetEventProfilingInfo clGetEventProfilingInfo_fn +inline cl_int clGetEventProfilingInfo(cl_event p0, cl_profiling_info p1, size_t p2, void* p3, size_t* p4) { return clGetEventProfilingInfo_pfn(p0, p1, p2, p3, p4); } +#undef clGetExtensionFunctionAddress +#define clGetExtensionFunctionAddress clGetExtensionFunctionAddress_fn +inline void* clGetExtensionFunctionAddress(const char* p0) { return clGetExtensionFunctionAddress_pfn(p0); } +#undef clGetExtensionFunctionAddressForPlatform +#define clGetExtensionFunctionAddressForPlatform clGetExtensionFunctionAddressForPlatform_fn +inline void* clGetExtensionFunctionAddressForPlatform(cl_platform_id p0, const char* p1) { return clGetExtensionFunctionAddressForPlatform_pfn(p0, p1); } +#undef clGetImageInfo +#define clGetImageInfo clGetImageInfo_fn +inline cl_int clGetImageInfo(cl_mem p0, cl_image_info p1, size_t p2, void* p3, size_t* p4) { return clGetImageInfo_pfn(p0, p1, p2, p3, p4); } +#undef clGetKernelArgInfo +#define clGetKernelArgInfo clGetKernelArgInfo_fn +inline cl_int clGetKernelArgInfo(cl_kernel p0, cl_uint p1, cl_kernel_arg_info p2, size_t p3, void* p4, size_t* p5) { return clGetKernelArgInfo_pfn(p0, p1, p2, p3, p4, p5); } +#undef clGetKernelInfo +#define clGetKernelInfo clGetKernelInfo_fn +inline cl_int clGetKernelInfo(cl_kernel p0, cl_kernel_info p1, size_t p2, void* p3, size_t* p4) { return clGetKernelInfo_pfn(p0, p1, p2, p3, p4); } +#undef clGetKernelWorkGroupInfo +#define clGetKernelWorkGroupInfo clGetKernelWorkGroupInfo_fn +inline cl_int clGetKernelWorkGroupInfo(cl_kernel p0, cl_device_id p1, cl_kernel_work_group_info p2, size_t p3, void* p4, size_t* p5) { return clGetKernelWorkGroupInfo_pfn(p0, p1, p2, p3, p4, p5); } +#undef clGetMemObjectInfo +#define clGetMemObjectInfo clGetMemObjectInfo_fn +inline cl_int clGetMemObjectInfo(cl_mem p0, cl_mem_info p1, size_t p2, void* p3, size_t* p4) { return clGetMemObjectInfo_pfn(p0, p1, p2, p3, p4); } +#undef clGetPlatformIDs +#define clGetPlatformIDs clGetPlatformIDs_fn +inline cl_int clGetPlatformIDs(cl_uint p0, cl_platform_id* p1, cl_uint* p2) { return clGetPlatformIDs_pfn(p0, p1, p2); } +#undef clGetPlatformInfo +#define clGetPlatformInfo clGetPlatformInfo_fn +inline cl_int clGetPlatformInfo(cl_platform_id p0, cl_platform_info p1, size_t p2, void* p3, size_t* p4) { return clGetPlatformInfo_pfn(p0, p1, p2, p3, p4); } +#undef clGetProgramBuildInfo +#define clGetProgramBuildInfo clGetProgramBuildInfo_fn +inline cl_int clGetProgramBuildInfo(cl_program p0, cl_device_id p1, cl_program_build_info p2, size_t p3, void* p4, size_t* p5) { return clGetProgramBuildInfo_pfn(p0, p1, p2, p3, p4, p5); } +#undef clGetProgramInfo +#define clGetProgramInfo clGetProgramInfo_fn +inline cl_int clGetProgramInfo(cl_program p0, cl_program_info p1, size_t p2, void* p3, size_t* p4) { return clGetProgramInfo_pfn(p0, p1, p2, p3, p4); } +#undef clGetSamplerInfo +#define clGetSamplerInfo clGetSamplerInfo_fn +inline cl_int clGetSamplerInfo(cl_sampler p0, cl_sampler_info p1, size_t p2, void* p3, size_t* p4) { return clGetSamplerInfo_pfn(p0, p1, p2, p3, p4); } +#undef clGetSupportedImageFormats +#define clGetSupportedImageFormats clGetSupportedImageFormats_fn +inline cl_int clGetSupportedImageFormats(cl_context p0, cl_mem_flags p1, cl_mem_object_type p2, cl_uint p3, cl_image_format* p4, cl_uint* p5) { return clGetSupportedImageFormats_pfn(p0, p1, p2, p3, p4, p5); } +#undef clLinkProgram +#define clLinkProgram clLinkProgram_fn +inline cl_program clLinkProgram(cl_context p0, cl_uint p1, const cl_device_id* p2, const char* p3, cl_uint p4, const cl_program* p5, void (CL_CALLBACK*p6) (cl_program, void*), void* p7, cl_int* p8) { return clLinkProgram_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } +#undef clReleaseCommandQueue +#define clReleaseCommandQueue clReleaseCommandQueue_fn +inline cl_int clReleaseCommandQueue(cl_command_queue p0) { return clReleaseCommandQueue_pfn(p0); } +#undef clReleaseContext +#define clReleaseContext clReleaseContext_fn +inline cl_int clReleaseContext(cl_context p0) { return clReleaseContext_pfn(p0); } +#undef clReleaseDevice +#define clReleaseDevice clReleaseDevice_fn +inline cl_int clReleaseDevice(cl_device_id p0) { return clReleaseDevice_pfn(p0); } +#undef clReleaseEvent +#define clReleaseEvent clReleaseEvent_fn +inline cl_int clReleaseEvent(cl_event p0) { return clReleaseEvent_pfn(p0); } +#undef clReleaseKernel +#define clReleaseKernel clReleaseKernel_fn +inline cl_int clReleaseKernel(cl_kernel p0) { return clReleaseKernel_pfn(p0); } +#undef clReleaseMemObject +#define clReleaseMemObject clReleaseMemObject_fn +inline cl_int clReleaseMemObject(cl_mem p0) { return clReleaseMemObject_pfn(p0); } +#undef clReleaseProgram +#define clReleaseProgram clReleaseProgram_fn +inline cl_int clReleaseProgram(cl_program p0) { return clReleaseProgram_pfn(p0); } +#undef clReleaseSampler +#define clReleaseSampler clReleaseSampler_fn +inline cl_int clReleaseSampler(cl_sampler p0) { return clReleaseSampler_pfn(p0); } +#undef clRetainCommandQueue +#define clRetainCommandQueue clRetainCommandQueue_fn +inline cl_int clRetainCommandQueue(cl_command_queue p0) { return clRetainCommandQueue_pfn(p0); } +#undef clRetainContext +#define clRetainContext clRetainContext_fn +inline cl_int clRetainContext(cl_context p0) { return clRetainContext_pfn(p0); } +#undef clRetainDevice +#define clRetainDevice clRetainDevice_fn +inline cl_int clRetainDevice(cl_device_id p0) { return clRetainDevice_pfn(p0); } +#undef clRetainEvent +#define clRetainEvent clRetainEvent_fn +inline cl_int clRetainEvent(cl_event p0) { return clRetainEvent_pfn(p0); } +#undef clRetainKernel +#define clRetainKernel clRetainKernel_fn +inline cl_int clRetainKernel(cl_kernel p0) { return clRetainKernel_pfn(p0); } +#undef clRetainMemObject +#define clRetainMemObject clRetainMemObject_fn +inline cl_int clRetainMemObject(cl_mem p0) { return clRetainMemObject_pfn(p0); } +#undef clRetainProgram +#define clRetainProgram clRetainProgram_fn +inline cl_int clRetainProgram(cl_program p0) { return clRetainProgram_pfn(p0); } +#undef clRetainSampler +#define clRetainSampler clRetainSampler_fn +inline cl_int clRetainSampler(cl_sampler p0) { return clRetainSampler_pfn(p0); } +#undef clSetEventCallback +#define clSetEventCallback clSetEventCallback_fn +inline cl_int clSetEventCallback(cl_event p0, cl_int p1, void (CL_CALLBACK*p2) (cl_event, cl_int, void*), void* p3) { return clSetEventCallback_pfn(p0, p1, p2, p3); } +#undef clSetKernelArg +#define clSetKernelArg clSetKernelArg_fn +inline cl_int clSetKernelArg(cl_kernel p0, cl_uint p1, size_t p2, const void* p3) { return clSetKernelArg_pfn(p0, p1, p2, p3); } +#undef clSetMemObjectDestructorCallback +#define clSetMemObjectDestructorCallback clSetMemObjectDestructorCallback_fn +inline cl_int clSetMemObjectDestructorCallback(cl_mem p0, void (CL_CALLBACK*p1) (cl_mem, void*), void* p2) { return clSetMemObjectDestructorCallback_pfn(p0, p1, p2); } +#undef clSetUserEventStatus +#define clSetUserEventStatus clSetUserEventStatus_fn +inline cl_int clSetUserEventStatus(cl_event p0, cl_int p1) { return clSetUserEventStatus_pfn(p0, p1); } +#undef clUnloadCompiler +#define clUnloadCompiler clUnloadCompiler_fn +inline cl_int clUnloadCompiler() { return clUnloadCompiler_pfn(); } +#undef clUnloadPlatformCompiler +#define clUnloadPlatformCompiler clUnloadPlatformCompiler_fn +inline cl_int clUnloadPlatformCompiler(cl_platform_id p0) { return clUnloadPlatformCompiler_pfn(p0); } +#undef clWaitForEvents +#define clWaitForEvents clWaitForEvents_fn +inline cl_int clWaitForEvents(cl_uint p0, const cl_event* p1) { return clWaitForEvents_pfn(p0, p1); } diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_gl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_gl.hpp index 0b12aed6c6..8b0d4c8d6e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_gl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_gl.hpp @@ -1,62 +1,62 @@ -// -// AUTOGENERATED, DO NOT EDIT -// -#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_HPP -#error "Invalid usage" -#endif - -// generated by parser_cl.py -#define clCreateFromGLBuffer clCreateFromGLBuffer_ -#define clCreateFromGLRenderbuffer clCreateFromGLRenderbuffer_ -#define clCreateFromGLTexture clCreateFromGLTexture_ -#define clCreateFromGLTexture2D clCreateFromGLTexture2D_ -#define clCreateFromGLTexture3D clCreateFromGLTexture3D_ -#define clEnqueueAcquireGLObjects clEnqueueAcquireGLObjects_ -#define clEnqueueReleaseGLObjects clEnqueueReleaseGLObjects_ -#define clGetGLContextInfoKHR clGetGLContextInfoKHR_ -#define clGetGLObjectInfo clGetGLObjectInfo_ -#define clGetGLTextureInfo clGetGLTextureInfo_ - -#if defined __APPLE__ -#include -#else -#include -#endif - -// generated by parser_cl.py -#undef clCreateFromGLBuffer -#define clCreateFromGLBuffer clCreateFromGLBuffer_pfn -#undef clCreateFromGLRenderbuffer -#define clCreateFromGLRenderbuffer clCreateFromGLRenderbuffer_pfn -#undef clCreateFromGLTexture -#define clCreateFromGLTexture clCreateFromGLTexture_pfn -#undef clCreateFromGLTexture2D -#define clCreateFromGLTexture2D clCreateFromGLTexture2D_pfn -#undef clCreateFromGLTexture3D -#define clCreateFromGLTexture3D clCreateFromGLTexture3D_pfn -#undef clEnqueueAcquireGLObjects -#define clEnqueueAcquireGLObjects clEnqueueAcquireGLObjects_pfn -#undef clEnqueueReleaseGLObjects -#define clEnqueueReleaseGLObjects clEnqueueReleaseGLObjects_pfn -#undef clGetGLContextInfoKHR -#define clGetGLContextInfoKHR clGetGLContextInfoKHR_pfn -#undef clGetGLObjectInfo -#define clGetGLObjectInfo clGetGLObjectInfo_pfn -#undef clGetGLTextureInfo -#define clGetGLTextureInfo clGetGLTextureInfo_pfn - -#ifdef cl_khr_gl_sharing - -// generated by parser_cl.py -extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateFromGLBuffer)(cl_context, cl_mem_flags, cl_GLuint, int*); -extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateFromGLRenderbuffer)(cl_context, cl_mem_flags, cl_GLuint, cl_int*); -extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateFromGLTexture)(cl_context, cl_mem_flags, cl_GLenum, cl_GLint, cl_GLuint, cl_int*); -extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateFromGLTexture2D)(cl_context, cl_mem_flags, cl_GLenum, cl_GLint, cl_GLuint, cl_int*); -extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateFromGLTexture3D)(cl_context, cl_mem_flags, cl_GLenum, cl_GLint, cl_GLuint, cl_int*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueAcquireGLObjects)(cl_command_queue, cl_uint, const cl_mem*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueReleaseGLObjects)(cl_command_queue, cl_uint, const cl_mem*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetGLContextInfoKHR)(const cl_context_properties*, cl_gl_context_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetGLObjectInfo)(cl_mem, cl_gl_object_type*, cl_GLuint*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetGLTextureInfo)(cl_mem, cl_gl_texture_info, size_t, void*, size_t*); - -#endif // cl_khr_gl_sharing +// +// AUTOGENERATED, DO NOT EDIT +// +#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_HPP +#error "Invalid usage" +#endif + +// generated by parser_cl.py +#define clCreateFromGLBuffer clCreateFromGLBuffer_ +#define clCreateFromGLRenderbuffer clCreateFromGLRenderbuffer_ +#define clCreateFromGLTexture clCreateFromGLTexture_ +#define clCreateFromGLTexture2D clCreateFromGLTexture2D_ +#define clCreateFromGLTexture3D clCreateFromGLTexture3D_ +#define clEnqueueAcquireGLObjects clEnqueueAcquireGLObjects_ +#define clEnqueueReleaseGLObjects clEnqueueReleaseGLObjects_ +#define clGetGLContextInfoKHR clGetGLContextInfoKHR_ +#define clGetGLObjectInfo clGetGLObjectInfo_ +#define clGetGLTextureInfo clGetGLTextureInfo_ + +#if defined __APPLE__ +#include +#else +#include +#endif + +// generated by parser_cl.py +#undef clCreateFromGLBuffer +#define clCreateFromGLBuffer clCreateFromGLBuffer_pfn +#undef clCreateFromGLRenderbuffer +#define clCreateFromGLRenderbuffer clCreateFromGLRenderbuffer_pfn +#undef clCreateFromGLTexture +#define clCreateFromGLTexture clCreateFromGLTexture_pfn +#undef clCreateFromGLTexture2D +#define clCreateFromGLTexture2D clCreateFromGLTexture2D_pfn +#undef clCreateFromGLTexture3D +#define clCreateFromGLTexture3D clCreateFromGLTexture3D_pfn +#undef clEnqueueAcquireGLObjects +#define clEnqueueAcquireGLObjects clEnqueueAcquireGLObjects_pfn +#undef clEnqueueReleaseGLObjects +#define clEnqueueReleaseGLObjects clEnqueueReleaseGLObjects_pfn +#undef clGetGLContextInfoKHR +#define clGetGLContextInfoKHR clGetGLContextInfoKHR_pfn +#undef clGetGLObjectInfo +#define clGetGLObjectInfo clGetGLObjectInfo_pfn +#undef clGetGLTextureInfo +#define clGetGLTextureInfo clGetGLTextureInfo_pfn + +#ifdef cl_khr_gl_sharing + +// generated by parser_cl.py +extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateFromGLBuffer)(cl_context, cl_mem_flags, cl_GLuint, int*); +extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateFromGLRenderbuffer)(cl_context, cl_mem_flags, cl_GLuint, cl_int*); +extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateFromGLTexture)(cl_context, cl_mem_flags, cl_GLenum, cl_GLint, cl_GLuint, cl_int*); +extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateFromGLTexture2D)(cl_context, cl_mem_flags, cl_GLenum, cl_GLint, cl_GLuint, cl_int*); +extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateFromGLTexture3D)(cl_context, cl_mem_flags, cl_GLenum, cl_GLint, cl_GLuint, cl_int*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueAcquireGLObjects)(cl_command_queue, cl_uint, const cl_mem*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueReleaseGLObjects)(cl_command_queue, cl_uint, const cl_mem*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetGLContextInfoKHR)(const cl_context_properties*, cl_gl_context_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetGLObjectInfo)(cl_mem, cl_gl_object_type*, cl_GLuint*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetGLTextureInfo)(cl_mem, cl_gl_texture_info, size_t, void*, size_t*); + +#endif // cl_khr_gl_sharing diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_gl_wrappers.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_gl_wrappers.hpp index 12f342b2e4..308673789d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_gl_wrappers.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_gl_wrappers.hpp @@ -1,42 +1,42 @@ -// -// AUTOGENERATED, DO NOT EDIT -// -#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_WRAPPERS_HPP -#error "Invalid usage" -#endif - -#ifdef cl_khr_gl_sharing - -// generated by parser_cl.py -#undef clCreateFromGLBuffer -#define clCreateFromGLBuffer clCreateFromGLBuffer_fn -inline cl_mem clCreateFromGLBuffer(cl_context p0, cl_mem_flags p1, cl_GLuint p2, int* p3) { return clCreateFromGLBuffer_pfn(p0, p1, p2, p3); } -#undef clCreateFromGLRenderbuffer -#define clCreateFromGLRenderbuffer clCreateFromGLRenderbuffer_fn -inline cl_mem clCreateFromGLRenderbuffer(cl_context p0, cl_mem_flags p1, cl_GLuint p2, cl_int* p3) { return clCreateFromGLRenderbuffer_pfn(p0, p1, p2, p3); } -#undef clCreateFromGLTexture -#define clCreateFromGLTexture clCreateFromGLTexture_fn -inline cl_mem clCreateFromGLTexture(cl_context p0, cl_mem_flags p1, cl_GLenum p2, cl_GLint p3, cl_GLuint p4, cl_int* p5) { return clCreateFromGLTexture_pfn(p0, p1, p2, p3, p4, p5); } -#undef clCreateFromGLTexture2D -#define clCreateFromGLTexture2D clCreateFromGLTexture2D_fn -inline cl_mem clCreateFromGLTexture2D(cl_context p0, cl_mem_flags p1, cl_GLenum p2, cl_GLint p3, cl_GLuint p4, cl_int* p5) { return clCreateFromGLTexture2D_pfn(p0, p1, p2, p3, p4, p5); } -#undef clCreateFromGLTexture3D -#define clCreateFromGLTexture3D clCreateFromGLTexture3D_fn -inline cl_mem clCreateFromGLTexture3D(cl_context p0, cl_mem_flags p1, cl_GLenum p2, cl_GLint p3, cl_GLuint p4, cl_int* p5) { return clCreateFromGLTexture3D_pfn(p0, p1, p2, p3, p4, p5); } -#undef clEnqueueAcquireGLObjects -#define clEnqueueAcquireGLObjects clEnqueueAcquireGLObjects_fn -inline cl_int clEnqueueAcquireGLObjects(cl_command_queue p0, cl_uint p1, const cl_mem* p2, cl_uint p3, const cl_event* p4, cl_event* p5) { return clEnqueueAcquireGLObjects_pfn(p0, p1, p2, p3, p4, p5); } -#undef clEnqueueReleaseGLObjects -#define clEnqueueReleaseGLObjects clEnqueueReleaseGLObjects_fn -inline cl_int clEnqueueReleaseGLObjects(cl_command_queue p0, cl_uint p1, const cl_mem* p2, cl_uint p3, const cl_event* p4, cl_event* p5) { return clEnqueueReleaseGLObjects_pfn(p0, p1, p2, p3, p4, p5); } -#undef clGetGLContextInfoKHR -#define clGetGLContextInfoKHR clGetGLContextInfoKHR_fn -inline cl_int clGetGLContextInfoKHR(const cl_context_properties* p0, cl_gl_context_info p1, size_t p2, void* p3, size_t* p4) { return clGetGLContextInfoKHR_pfn(p0, p1, p2, p3, p4); } -#undef clGetGLObjectInfo -#define clGetGLObjectInfo clGetGLObjectInfo_fn -inline cl_int clGetGLObjectInfo(cl_mem p0, cl_gl_object_type* p1, cl_GLuint* p2) { return clGetGLObjectInfo_pfn(p0, p1, p2); } -#undef clGetGLTextureInfo -#define clGetGLTextureInfo clGetGLTextureInfo_fn -inline cl_int clGetGLTextureInfo(cl_mem p0, cl_gl_texture_info p1, size_t p2, void* p3, size_t* p4) { return clGetGLTextureInfo_pfn(p0, p1, p2, p3, p4); } - -#endif // cl_khr_gl_sharing +// +// AUTOGENERATED, DO NOT EDIT +// +#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_WRAPPERS_HPP +#error "Invalid usage" +#endif + +#ifdef cl_khr_gl_sharing + +// generated by parser_cl.py +#undef clCreateFromGLBuffer +#define clCreateFromGLBuffer clCreateFromGLBuffer_fn +inline cl_mem clCreateFromGLBuffer(cl_context p0, cl_mem_flags p1, cl_GLuint p2, int* p3) { return clCreateFromGLBuffer_pfn(p0, p1, p2, p3); } +#undef clCreateFromGLRenderbuffer +#define clCreateFromGLRenderbuffer clCreateFromGLRenderbuffer_fn +inline cl_mem clCreateFromGLRenderbuffer(cl_context p0, cl_mem_flags p1, cl_GLuint p2, cl_int* p3) { return clCreateFromGLRenderbuffer_pfn(p0, p1, p2, p3); } +#undef clCreateFromGLTexture +#define clCreateFromGLTexture clCreateFromGLTexture_fn +inline cl_mem clCreateFromGLTexture(cl_context p0, cl_mem_flags p1, cl_GLenum p2, cl_GLint p3, cl_GLuint p4, cl_int* p5) { return clCreateFromGLTexture_pfn(p0, p1, p2, p3, p4, p5); } +#undef clCreateFromGLTexture2D +#define clCreateFromGLTexture2D clCreateFromGLTexture2D_fn +inline cl_mem clCreateFromGLTexture2D(cl_context p0, cl_mem_flags p1, cl_GLenum p2, cl_GLint p3, cl_GLuint p4, cl_int* p5) { return clCreateFromGLTexture2D_pfn(p0, p1, p2, p3, p4, p5); } +#undef clCreateFromGLTexture3D +#define clCreateFromGLTexture3D clCreateFromGLTexture3D_fn +inline cl_mem clCreateFromGLTexture3D(cl_context p0, cl_mem_flags p1, cl_GLenum p2, cl_GLint p3, cl_GLuint p4, cl_int* p5) { return clCreateFromGLTexture3D_pfn(p0, p1, p2, p3, p4, p5); } +#undef clEnqueueAcquireGLObjects +#define clEnqueueAcquireGLObjects clEnqueueAcquireGLObjects_fn +inline cl_int clEnqueueAcquireGLObjects(cl_command_queue p0, cl_uint p1, const cl_mem* p2, cl_uint p3, const cl_event* p4, cl_event* p5) { return clEnqueueAcquireGLObjects_pfn(p0, p1, p2, p3, p4, p5); } +#undef clEnqueueReleaseGLObjects +#define clEnqueueReleaseGLObjects clEnqueueReleaseGLObjects_fn +inline cl_int clEnqueueReleaseGLObjects(cl_command_queue p0, cl_uint p1, const cl_mem* p2, cl_uint p3, const cl_event* p4, cl_event* p5) { return clEnqueueReleaseGLObjects_pfn(p0, p1, p2, p3, p4, p5); } +#undef clGetGLContextInfoKHR +#define clGetGLContextInfoKHR clGetGLContextInfoKHR_fn +inline cl_int clGetGLContextInfoKHR(const cl_context_properties* p0, cl_gl_context_info p1, size_t p2, void* p3, size_t* p4) { return clGetGLContextInfoKHR_pfn(p0, p1, p2, p3, p4); } +#undef clGetGLObjectInfo +#define clGetGLObjectInfo clGetGLObjectInfo_fn +inline cl_int clGetGLObjectInfo(cl_mem p0, cl_gl_object_type* p1, cl_GLuint* p2) { return clGetGLObjectInfo_pfn(p0, p1, p2); } +#undef clGetGLTextureInfo +#define clGetGLTextureInfo clGetGLTextureInfo_fn +inline cl_int clGetGLTextureInfo(cl_mem p0, cl_gl_texture_info p1, size_t p2, void* p3, size_t* p4) { return clGetGLTextureInfo_pfn(p0, p1, p2, p3, p4); } + +#endif // cl_khr_gl_sharing diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_clblas.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_clblas.hpp index ccddf8f76c..822f6cd2b3 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_clblas.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_clblas.hpp @@ -1,53 +1,53 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 OpenCV Foundation 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. -// -//M*/ - -#ifndef OPENCV_CORE_OCL_RUNTIME_CLAMDBLAS_HPP -#define OPENCV_CORE_OCL_RUNTIME_CLAMDBLAS_HPP - -#ifdef HAVE_CLAMDBLAS - -#include "opencl_core.hpp" - -#include "autogenerated/opencl_clblas.hpp" - -#endif // HAVE_CLAMDBLAS - -#endif // OPENCV_CORE_OCL_RUNTIME_CLAMDBLAS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 OpenCV Foundation 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. +// +//M*/ + +#ifndef OPENCV_CORE_OCL_RUNTIME_CLAMDBLAS_HPP +#define OPENCV_CORE_OCL_RUNTIME_CLAMDBLAS_HPP + +#ifdef HAVE_CLAMDBLAS + +#include "opencl_core.hpp" + +#include "autogenerated/opencl_clblas.hpp" + +#endif // HAVE_CLAMDBLAS + +#endif // OPENCV_CORE_OCL_RUNTIME_CLAMDBLAS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_clfft.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_clfft.hpp index 7f4af5e60b..7dd51f3889 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_clfft.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_clfft.hpp @@ -1,53 +1,53 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 OpenCV Foundation 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. -// -//M*/ - -#ifndef OPENCV_CORE_OCL_RUNTIME_CLAMDFFT_HPP -#define OPENCV_CORE_OCL_RUNTIME_CLAMDFFT_HPP - -#ifdef HAVE_CLAMDFFT - -#include "opencl_core.hpp" - -#include "autogenerated/opencl_clfft.hpp" - -#endif // HAVE_CLAMDFFT - -#endif // OPENCV_CORE_OCL_RUNTIME_CLAMDFFT_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 OpenCV Foundation 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. +// +//M*/ + +#ifndef OPENCV_CORE_OCL_RUNTIME_CLAMDFFT_HPP +#define OPENCV_CORE_OCL_RUNTIME_CLAMDFFT_HPP + +#ifdef HAVE_CLAMDFFT + +#include "opencl_core.hpp" + +#include "autogenerated/opencl_clfft.hpp" + +#endif // HAVE_CLAMDFFT + +#endif // OPENCV_CORE_OCL_RUNTIME_CLAMDFFT_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_core.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_core.hpp index 0404b3177a..5802dd81d1 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_core.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_core.hpp @@ -1,84 +1,84 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 OpenCV Foundation 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. -// -//M*/ - -#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_CORE_HPP -#define OPENCV_CORE_OCL_RUNTIME_OPENCL_CORE_HPP - -#ifdef HAVE_OPENCL - -#ifndef CL_RUNTIME_EXPORT -#if (defined(BUILD_SHARED_LIBS) || defined(OPENCV_CORE_SHARED)) && (defined _WIN32 || defined WINCE) && \ - !(defined(__OPENCV_BUILD) && defined(OPENCV_MODULE_IS_PART_OF_WORLD)) -#define CL_RUNTIME_EXPORT __declspec(dllimport) -#else -#define CL_RUNTIME_EXPORT -#endif -#endif - -#ifdef HAVE_OPENCL_SVM -#define clSVMAlloc clSVMAlloc_ -#define clSVMFree clSVMFree_ -#define clSetKernelArgSVMPointer clSetKernelArgSVMPointer_ -#define clSetKernelExecInfo clSetKernelExecInfo_ -#define clEnqueueSVMFree clEnqueueSVMFree_ -#define clEnqueueSVMMemcpy clEnqueueSVMMemcpy_ -#define clEnqueueSVMMemFill clEnqueueSVMMemFill_ -#define clEnqueueSVMMap clEnqueueSVMMap_ -#define clEnqueueSVMUnmap clEnqueueSVMUnmap_ -#endif - -#include "autogenerated/opencl_core.hpp" - -#ifndef CL_DEVICE_DOUBLE_FP_CONFIG -#define CL_DEVICE_DOUBLE_FP_CONFIG 0x1032 -#endif - -#ifndef CL_DEVICE_HALF_FP_CONFIG -#define CL_DEVICE_HALF_FP_CONFIG 0x1033 -#endif - -#ifndef CL_VERSION_1_2 -#define CV_REQUIRE_OPENCL_1_2_ERROR CV_Error(cv::Error::OpenCLApiCallError, "OpenCV compiled without OpenCL v1.2 support, so we can't use functionality from OpenCL v1.2") -#endif - -#endif // HAVE_OPENCL - -#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_CORE_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 OpenCV Foundation 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. +// +//M*/ + +#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_CORE_HPP +#define OPENCV_CORE_OCL_RUNTIME_OPENCL_CORE_HPP + +#ifdef HAVE_OPENCL + +#ifndef CL_RUNTIME_EXPORT +#if (defined(BUILD_SHARED_LIBS) || defined(OPENCV_CORE_SHARED)) && (defined _WIN32 || defined WINCE) && \ + !(defined(__OPENCV_BUILD) && defined(OPENCV_MODULE_IS_PART_OF_WORLD)) +#define CL_RUNTIME_EXPORT __declspec(dllimport) +#else +#define CL_RUNTIME_EXPORT +#endif +#endif + +#ifdef HAVE_OPENCL_SVM +#define clSVMAlloc clSVMAlloc_ +#define clSVMFree clSVMFree_ +#define clSetKernelArgSVMPointer clSetKernelArgSVMPointer_ +#define clSetKernelExecInfo clSetKernelExecInfo_ +#define clEnqueueSVMFree clEnqueueSVMFree_ +#define clEnqueueSVMMemcpy clEnqueueSVMMemcpy_ +#define clEnqueueSVMMemFill clEnqueueSVMMemFill_ +#define clEnqueueSVMMap clEnqueueSVMMap_ +#define clEnqueueSVMUnmap clEnqueueSVMUnmap_ +#endif + +#include "autogenerated/opencl_core.hpp" + +#ifndef CL_DEVICE_DOUBLE_FP_CONFIG +#define CL_DEVICE_DOUBLE_FP_CONFIG 0x1032 +#endif + +#ifndef CL_DEVICE_HALF_FP_CONFIG +#define CL_DEVICE_HALF_FP_CONFIG 0x1033 +#endif + +#ifndef CL_VERSION_1_2 +#define CV_REQUIRE_OPENCL_1_2_ERROR CV_Error(cv::Error::OpenCLApiCallError, "OpenCV compiled without OpenCL v1.2 support, so we can't use functionality from OpenCL v1.2") +#endif + +#endif // HAVE_OPENCL + +#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_CORE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_core_wrappers.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_core_wrappers.hpp index 38fcae9952..d1d5e15e09 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_core_wrappers.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_core_wrappers.hpp @@ -1,47 +1,47 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 OpenCV Foundation 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. -// -//M*/ - -#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_WRAPPERS_HPP -#define OPENCV_CORE_OCL_RUNTIME_OPENCL_WRAPPERS_HPP - -#include "autogenerated/opencl_core_wrappers.hpp" - -#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_WRAPPERS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 OpenCV Foundation 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. +// +//M*/ + +#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_WRAPPERS_HPP +#define OPENCV_CORE_OCL_RUNTIME_OPENCL_WRAPPERS_HPP + +#include "autogenerated/opencl_core_wrappers.hpp" + +#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_WRAPPERS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_gl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_gl.hpp index 659c7d8058..8de4590fb8 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_gl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_gl.hpp @@ -1,53 +1,53 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 OpenCV Foundation 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. -// -//M*/ - -#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_HPP -#define OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_HPP - -#if defined HAVE_OPENCL && defined HAVE_OPENGL - -#include "opencl_core.hpp" - -#include "autogenerated/opencl_gl.hpp" - -#endif // defined HAVE_OPENCL && defined HAVE_OPENGL - -#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 OpenCV Foundation 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. +// +//M*/ + +#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_HPP +#define OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_HPP + +#if defined HAVE_OPENCL && defined HAVE_OPENGL + +#include "opencl_core.hpp" + +#include "autogenerated/opencl_gl.hpp" + +#endif // defined HAVE_OPENCL && defined HAVE_OPENGL + +#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_gl_wrappers.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_gl_wrappers.hpp index 9700004cae..861df4e8f7 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_gl_wrappers.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_gl_wrappers.hpp @@ -1,47 +1,47 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 OpenCV Foundation 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. -// -//M*/ - -#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_WRAPPERS_HPP -#define OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_WRAPPERS_HPP - -#include "autogenerated/opencl_gl_wrappers.hpp" - -#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_WRAPPERS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 OpenCV Foundation 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. +// +//M*/ + +#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_WRAPPERS_HPP +#define OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_WRAPPERS_HPP + +#include "autogenerated/opencl_gl_wrappers.hpp" + +#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_WRAPPERS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_svm_20.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_svm_20.hpp index 9636b19b02..97e3741901 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_svm_20.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_svm_20.hpp @@ -1,48 +1,48 @@ -/* See LICENSE file in the root OpenCV directory */ - -#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_2_0_HPP -#define OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_2_0_HPP - -#if defined(HAVE_OPENCL_SVM) -#include "opencl_core.hpp" - -#include "opencl_svm_definitions.hpp" - -#undef clSVMAlloc -#define clSVMAlloc clSVMAlloc_pfn -#undef clSVMFree -#define clSVMFree clSVMFree_pfn -#undef clSetKernelArgSVMPointer -#define clSetKernelArgSVMPointer clSetKernelArgSVMPointer_pfn -#undef clSetKernelExecInfo -//#define clSetKernelExecInfo clSetKernelExecInfo_pfn -#undef clEnqueueSVMFree -//#define clEnqueueSVMFree clEnqueueSVMFree_pfn -#undef clEnqueueSVMMemcpy -#define clEnqueueSVMMemcpy clEnqueueSVMMemcpy_pfn -#undef clEnqueueSVMMemFill -#define clEnqueueSVMMemFill clEnqueueSVMMemFill_pfn -#undef clEnqueueSVMMap -#define clEnqueueSVMMap clEnqueueSVMMap_pfn -#undef clEnqueueSVMUnmap -#define clEnqueueSVMUnmap clEnqueueSVMUnmap_pfn - -extern CL_RUNTIME_EXPORT void* (CL_API_CALL *clSVMAlloc)(cl_context context, cl_svm_mem_flags flags, size_t size, unsigned int alignment); -extern CL_RUNTIME_EXPORT void (CL_API_CALL *clSVMFree)(cl_context context, void* svm_pointer); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL *clSetKernelArgSVMPointer)(cl_kernel kernel, cl_uint arg_index, const void* arg_value); -//extern CL_RUNTIME_EXPORT void* (CL_API_CALL *clSetKernelExecInfo)(cl_kernel kernel, cl_kernel_exec_info param_name, size_t param_value_size, const void* param_value); -//extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL *clEnqueueSVMFree)(cl_command_queue command_queue, cl_uint num_svm_pointers, void* svm_pointers[], -// void (CL_CALLBACK *pfn_free_func)(cl_command_queue queue, cl_uint num_svm_pointers, void* svm_pointers[], void* user_data), void* user_data, -// cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL *clEnqueueSVMMemcpy)(cl_command_queue command_queue, cl_bool blocking_copy, void* dst_ptr, const void* src_ptr, size_t size, - cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL *clEnqueueSVMMemFill)(cl_command_queue command_queue, void* svm_ptr, const void* pattern, size_t pattern_size, size_t size, - cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL *clEnqueueSVMMap)(cl_command_queue command_queue, cl_bool blocking_map, cl_map_flags map_flags, void* svm_ptr, size_t size, - cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL *clEnqueueSVMUnmap)(cl_command_queue command_queue, void* svm_ptr, - cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event); - -#endif // HAVE_OPENCL_SVM - -#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_2_0_HPP +/* See LICENSE file in the root OpenCV directory */ + +#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_2_0_HPP +#define OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_2_0_HPP + +#if defined(HAVE_OPENCL_SVM) +#include "opencl_core.hpp" + +#include "opencl_svm_definitions.hpp" + +#undef clSVMAlloc +#define clSVMAlloc clSVMAlloc_pfn +#undef clSVMFree +#define clSVMFree clSVMFree_pfn +#undef clSetKernelArgSVMPointer +#define clSetKernelArgSVMPointer clSetKernelArgSVMPointer_pfn +#undef clSetKernelExecInfo +//#define clSetKernelExecInfo clSetKernelExecInfo_pfn +#undef clEnqueueSVMFree +//#define clEnqueueSVMFree clEnqueueSVMFree_pfn +#undef clEnqueueSVMMemcpy +#define clEnqueueSVMMemcpy clEnqueueSVMMemcpy_pfn +#undef clEnqueueSVMMemFill +#define clEnqueueSVMMemFill clEnqueueSVMMemFill_pfn +#undef clEnqueueSVMMap +#define clEnqueueSVMMap clEnqueueSVMMap_pfn +#undef clEnqueueSVMUnmap +#define clEnqueueSVMUnmap clEnqueueSVMUnmap_pfn + +extern CL_RUNTIME_EXPORT void* (CL_API_CALL *clSVMAlloc)(cl_context context, cl_svm_mem_flags flags, size_t size, unsigned int alignment); +extern CL_RUNTIME_EXPORT void (CL_API_CALL *clSVMFree)(cl_context context, void* svm_pointer); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL *clSetKernelArgSVMPointer)(cl_kernel kernel, cl_uint arg_index, const void* arg_value); +//extern CL_RUNTIME_EXPORT void* (CL_API_CALL *clSetKernelExecInfo)(cl_kernel kernel, cl_kernel_exec_info param_name, size_t param_value_size, const void* param_value); +//extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL *clEnqueueSVMFree)(cl_command_queue command_queue, cl_uint num_svm_pointers, void* svm_pointers[], +// void (CL_CALLBACK *pfn_free_func)(cl_command_queue queue, cl_uint num_svm_pointers, void* svm_pointers[], void* user_data), void* user_data, +// cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL *clEnqueueSVMMemcpy)(cl_command_queue command_queue, cl_bool blocking_copy, void* dst_ptr, const void* src_ptr, size_t size, + cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL *clEnqueueSVMMemFill)(cl_command_queue command_queue, void* svm_ptr, const void* pattern, size_t pattern_size, size_t size, + cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL *clEnqueueSVMMap)(cl_command_queue command_queue, cl_bool blocking_map, cl_map_flags map_flags, void* svm_ptr, size_t size, + cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL *clEnqueueSVMUnmap)(cl_command_queue command_queue, void* svm_ptr, + cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event); + +#endif // HAVE_OPENCL_SVM + +#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_2_0_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_svm_definitions.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_svm_definitions.hpp index 97c927b44d..c6dcc776fb 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_svm_definitions.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_svm_definitions.hpp @@ -1,42 +1,42 @@ -/* See LICENSE file in the root OpenCV directory */ - -#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_DEFINITIONS_HPP -#define OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_DEFINITIONS_HPP - -#if defined(HAVE_OPENCL_SVM) -#if defined(CL_VERSION_2_0) - -// OpenCL 2.0 contains SVM definitions - -#else - -typedef cl_bitfield cl_device_svm_capabilities; -typedef cl_bitfield cl_svm_mem_flags; -typedef cl_uint cl_kernel_exec_info; - -// -// TODO Add real values after OpenCL 2.0 release -// - -#ifndef CL_DEVICE_SVM_CAPABILITIES -#define CL_DEVICE_SVM_CAPABILITIES 0x1053 - -#define CL_DEVICE_SVM_COARSE_GRAIN_BUFFER (1 << 0) -#define CL_DEVICE_SVM_FINE_GRAIN_BUFFER (1 << 1) -#define CL_DEVICE_SVM_FINE_GRAIN_SYSTEM (1 << 2) -#define CL_DEVICE_SVM_ATOMICS (1 << 3) -#endif - -#ifndef CL_MEM_SVM_FINE_GRAIN_BUFFER -#define CL_MEM_SVM_FINE_GRAIN_BUFFER (1 << 10) -#endif - -#ifndef CL_MEM_SVM_ATOMICS -#define CL_MEM_SVM_ATOMICS (1 << 11) -#endif - - -#endif // CL_VERSION_2_0 -#endif // HAVE_OPENCL_SVM - -#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_DEFINITIONS_HPP +/* See LICENSE file in the root OpenCV directory */ + +#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_DEFINITIONS_HPP +#define OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_DEFINITIONS_HPP + +#if defined(HAVE_OPENCL_SVM) +#if defined(CL_VERSION_2_0) + +// OpenCL 2.0 contains SVM definitions + +#else + +typedef cl_bitfield cl_device_svm_capabilities; +typedef cl_bitfield cl_svm_mem_flags; +typedef cl_uint cl_kernel_exec_info; + +// +// TODO Add real values after OpenCL 2.0 release +// + +#ifndef CL_DEVICE_SVM_CAPABILITIES +#define CL_DEVICE_SVM_CAPABILITIES 0x1053 + +#define CL_DEVICE_SVM_COARSE_GRAIN_BUFFER (1 << 0) +#define CL_DEVICE_SVM_FINE_GRAIN_BUFFER (1 << 1) +#define CL_DEVICE_SVM_FINE_GRAIN_SYSTEM (1 << 2) +#define CL_DEVICE_SVM_ATOMICS (1 << 3) +#endif + +#ifndef CL_MEM_SVM_FINE_GRAIN_BUFFER +#define CL_MEM_SVM_FINE_GRAIN_BUFFER (1 << 10) +#endif + +#ifndef CL_MEM_SVM_ATOMICS +#define CL_MEM_SVM_ATOMICS (1 << 11) +#endif + + +#endif // CL_VERSION_2_0 +#endif // HAVE_OPENCL_SVM + +#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_DEFINITIONS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_svm_hsa_extension.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_svm_hsa_extension.hpp index 497bc3de72..9aa46a8f2f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_svm_hsa_extension.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_svm_hsa_extension.hpp @@ -1,166 +1,166 @@ -/* See LICENSE file in the root OpenCV directory */ - -#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_HSA_EXTENSION_HPP -#define OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_HSA_EXTENSION_HPP - -#if defined(HAVE_OPENCL_SVM) -#include "opencl_core.hpp" - -#ifndef CL_DEVICE_SVM_CAPABILITIES_AMD -// -// Part of the file is an extract from the cl_ext.h file from AMD APP SDK package. -// Below is the original copyright. -// -/******************************************************************************* - * Copyright (c) 2008-2013 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - ******************************************************************************/ - -/******************************************* - * Shared Virtual Memory (SVM) extension - *******************************************/ -typedef cl_bitfield cl_device_svm_capabilities_amd; -typedef cl_bitfield cl_svm_mem_flags_amd; -typedef cl_uint cl_kernel_exec_info_amd; - -/* cl_device_info */ -#define CL_DEVICE_SVM_CAPABILITIES_AMD 0x1053 -#define CL_DEVICE_PREFERRED_PLATFORM_ATOMIC_ALIGNMENT_AMD 0x1054 - -/* cl_device_svm_capabilities_amd */ -#define CL_DEVICE_SVM_COARSE_GRAIN_BUFFER_AMD (1 << 0) -#define CL_DEVICE_SVM_FINE_GRAIN_BUFFER_AMD (1 << 1) -#define CL_DEVICE_SVM_FINE_GRAIN_SYSTEM_AMD (1 << 2) -#define CL_DEVICE_SVM_ATOMICS_AMD (1 << 3) - -/* cl_svm_mem_flags_amd */ -#define CL_MEM_SVM_FINE_GRAIN_BUFFER_AMD (1 << 10) -#define CL_MEM_SVM_ATOMICS_AMD (1 << 11) - -/* cl_mem_info */ -#define CL_MEM_USES_SVM_POINTER_AMD 0x1109 - -/* cl_kernel_exec_info_amd */ -#define CL_KERNEL_EXEC_INFO_SVM_PTRS_AMD 0x11B6 -#define CL_KERNEL_EXEC_INFO_SVM_FINE_GRAIN_SYSTEM_AMD 0x11B7 - -/* cl_command_type */ -#define CL_COMMAND_SVM_FREE_AMD 0x1209 -#define CL_COMMAND_SVM_MEMCPY_AMD 0x120A -#define CL_COMMAND_SVM_MEMFILL_AMD 0x120B -#define CL_COMMAND_SVM_MAP_AMD 0x120C -#define CL_COMMAND_SVM_UNMAP_AMD 0x120D - -typedef CL_API_ENTRY void* -(CL_API_CALL * clSVMAllocAMD_fn)( - cl_context /* context */, - cl_svm_mem_flags_amd /* flags */, - size_t /* size */, - unsigned int /* alignment */ -) CL_EXT_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY void -(CL_API_CALL * clSVMFreeAMD_fn)( - cl_context /* context */, - void* /* svm_pointer */ -) CL_EXT_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_int -(CL_API_CALL * clEnqueueSVMFreeAMD_fn)( - cl_command_queue /* command_queue */, - cl_uint /* num_svm_pointers */, - void** /* svm_pointers */, - void (CL_CALLBACK *)( /*pfn_free_func*/ - cl_command_queue /* queue */, - cl_uint /* num_svm_pointers */, - void** /* svm_pointers */, - void* /* user_data */), - void* /* user_data */, - cl_uint /* num_events_in_wait_list */, - const cl_event* /* event_wait_list */, - cl_event* /* event */ -) CL_EXT_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_int -(CL_API_CALL * clEnqueueSVMMemcpyAMD_fn)( - cl_command_queue /* command_queue */, - cl_bool /* blocking_copy */, - void* /* dst_ptr */, - const void* /* src_ptr */, - size_t /* size */, - cl_uint /* num_events_in_wait_list */, - const cl_event* /* event_wait_list */, - cl_event* /* event */ -) CL_EXT_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_int -(CL_API_CALL * clEnqueueSVMMemFillAMD_fn)( - cl_command_queue /* command_queue */, - void* /* svm_ptr */, - const void* /* pattern */, - size_t /* pattern_size */, - size_t /* size */, - cl_uint /* num_events_in_wait_list */, - const cl_event* /* event_wait_list */, - cl_event* /* event */ -) CL_EXT_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_int -(CL_API_CALL * clEnqueueSVMMapAMD_fn)( - cl_command_queue /* command_queue */, - cl_bool /* blocking_map */, - cl_map_flags /* map_flags */, - void* /* svm_ptr */, - size_t /* size */, - cl_uint /* num_events_in_wait_list */, - const cl_event* /* event_wait_list */, - cl_event* /* event */ -) CL_EXT_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_int -(CL_API_CALL * clEnqueueSVMUnmapAMD_fn)( - cl_command_queue /* command_queue */, - void* /* svm_ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event* /* event_wait_list */, - cl_event* /* event */ -) CL_EXT_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_int -(CL_API_CALL * clSetKernelArgSVMPointerAMD_fn)( - cl_kernel /* kernel */, - cl_uint /* arg_index */, - const void * /* arg_value */ -) CL_EXT_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_int -(CL_API_CALL * clSetKernelExecInfoAMD_fn)( - cl_kernel /* kernel */, - cl_kernel_exec_info_amd /* param_name */, - size_t /* param_value_size */, - const void * /* param_value */ -) CL_EXT_SUFFIX__VERSION_1_2; - -#endif - -#endif // HAVE_OPENCL_SVM - -#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_HSA_EXTENSION_HPP +/* See LICENSE file in the root OpenCV directory */ + +#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_HSA_EXTENSION_HPP +#define OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_HSA_EXTENSION_HPP + +#if defined(HAVE_OPENCL_SVM) +#include "opencl_core.hpp" + +#ifndef CL_DEVICE_SVM_CAPABILITIES_AMD +// +// Part of the file is an extract from the cl_ext.h file from AMD APP SDK package. +// Below is the original copyright. +// +/******************************************************************************* + * Copyright (c) 2008-2013 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and/or associated documentation files (the + * "Materials"), to deal in the Materials without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Materials, and to + * permit persons to whom the Materials are furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Materials. + * + * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + ******************************************************************************/ + +/******************************************* + * Shared Virtual Memory (SVM) extension + *******************************************/ +typedef cl_bitfield cl_device_svm_capabilities_amd; +typedef cl_bitfield cl_svm_mem_flags_amd; +typedef cl_uint cl_kernel_exec_info_amd; + +/* cl_device_info */ +#define CL_DEVICE_SVM_CAPABILITIES_AMD 0x1053 +#define CL_DEVICE_PREFERRED_PLATFORM_ATOMIC_ALIGNMENT_AMD 0x1054 + +/* cl_device_svm_capabilities_amd */ +#define CL_DEVICE_SVM_COARSE_GRAIN_BUFFER_AMD (1 << 0) +#define CL_DEVICE_SVM_FINE_GRAIN_BUFFER_AMD (1 << 1) +#define CL_DEVICE_SVM_FINE_GRAIN_SYSTEM_AMD (1 << 2) +#define CL_DEVICE_SVM_ATOMICS_AMD (1 << 3) + +/* cl_svm_mem_flags_amd */ +#define CL_MEM_SVM_FINE_GRAIN_BUFFER_AMD (1 << 10) +#define CL_MEM_SVM_ATOMICS_AMD (1 << 11) + +/* cl_mem_info */ +#define CL_MEM_USES_SVM_POINTER_AMD 0x1109 + +/* cl_kernel_exec_info_amd */ +#define CL_KERNEL_EXEC_INFO_SVM_PTRS_AMD 0x11B6 +#define CL_KERNEL_EXEC_INFO_SVM_FINE_GRAIN_SYSTEM_AMD 0x11B7 + +/* cl_command_type */ +#define CL_COMMAND_SVM_FREE_AMD 0x1209 +#define CL_COMMAND_SVM_MEMCPY_AMD 0x120A +#define CL_COMMAND_SVM_MEMFILL_AMD 0x120B +#define CL_COMMAND_SVM_MAP_AMD 0x120C +#define CL_COMMAND_SVM_UNMAP_AMD 0x120D + +typedef CL_API_ENTRY void* +(CL_API_CALL * clSVMAllocAMD_fn)( + cl_context /* context */, + cl_svm_mem_flags_amd /* flags */, + size_t /* size */, + unsigned int /* alignment */ +) CL_EXT_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY void +(CL_API_CALL * clSVMFreeAMD_fn)( + cl_context /* context */, + void* /* svm_pointer */ +) CL_EXT_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY cl_int +(CL_API_CALL * clEnqueueSVMFreeAMD_fn)( + cl_command_queue /* command_queue */, + cl_uint /* num_svm_pointers */, + void** /* svm_pointers */, + void (CL_CALLBACK *)( /*pfn_free_func*/ + cl_command_queue /* queue */, + cl_uint /* num_svm_pointers */, + void** /* svm_pointers */, + void* /* user_data */), + void* /* user_data */, + cl_uint /* num_events_in_wait_list */, + const cl_event* /* event_wait_list */, + cl_event* /* event */ +) CL_EXT_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY cl_int +(CL_API_CALL * clEnqueueSVMMemcpyAMD_fn)( + cl_command_queue /* command_queue */, + cl_bool /* blocking_copy */, + void* /* dst_ptr */, + const void* /* src_ptr */, + size_t /* size */, + cl_uint /* num_events_in_wait_list */, + const cl_event* /* event_wait_list */, + cl_event* /* event */ +) CL_EXT_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY cl_int +(CL_API_CALL * clEnqueueSVMMemFillAMD_fn)( + cl_command_queue /* command_queue */, + void* /* svm_ptr */, + const void* /* pattern */, + size_t /* pattern_size */, + size_t /* size */, + cl_uint /* num_events_in_wait_list */, + const cl_event* /* event_wait_list */, + cl_event* /* event */ +) CL_EXT_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY cl_int +(CL_API_CALL * clEnqueueSVMMapAMD_fn)( + cl_command_queue /* command_queue */, + cl_bool /* blocking_map */, + cl_map_flags /* map_flags */, + void* /* svm_ptr */, + size_t /* size */, + cl_uint /* num_events_in_wait_list */, + const cl_event* /* event_wait_list */, + cl_event* /* event */ +) CL_EXT_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY cl_int +(CL_API_CALL * clEnqueueSVMUnmapAMD_fn)( + cl_command_queue /* command_queue */, + void* /* svm_ptr */, + cl_uint /* num_events_in_wait_list */, + const cl_event* /* event_wait_list */, + cl_event* /* event */ +) CL_EXT_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY cl_int +(CL_API_CALL * clSetKernelArgSVMPointerAMD_fn)( + cl_kernel /* kernel */, + cl_uint /* arg_index */, + const void * /* arg_value */ +) CL_EXT_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY cl_int +(CL_API_CALL * clSetKernelExecInfoAMD_fn)( + cl_kernel /* kernel */, + cl_kernel_exec_info_amd /* param_name */, + size_t /* param_value_size */, + const void * /* param_value */ +) CL_EXT_SUFFIX__VERSION_1_2; + +#endif + +#endif // HAVE_OPENCL_SVM + +#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_HSA_EXTENSION_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opengl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opengl.hpp index 5d19f81f85..72387bd824 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opengl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opengl.hpp @@ -1,733 +1,733 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CORE_OPENGL_HPP -#define OPENCV_CORE_OPENGL_HPP - -#ifndef __cplusplus -# error opengl.hpp header must be compiled as C++ -#endif - -#include "opencv2/core.hpp" -#include "ocl.hpp" - -namespace cv { namespace ogl { - -/** @addtogroup core_opengl -This section describes OpenGL interoperability. - -To enable OpenGL support, configure OpenCV using CMake with WITH_OPENGL=ON . Currently OpenGL is -supported only with WIN32, GTK and Qt backends on Windows and Linux (MacOS and Android are not -supported). For GTK-2.0 backend gtkglext-1.0 library is required. - -To use OpenGL functionality you should first create OpenGL context (window or frame buffer). You can -do this with namedWindow function or with other OpenGL toolkit (GLUT, for example). -*/ -//! @{ - -/////////////////// OpenGL Objects /////////////////// - -/** @brief Smart pointer for OpenGL buffer object with reference counting. - -Buffer Objects are OpenGL objects that store an array of unformatted memory allocated by the OpenGL -context. These can be used to store vertex data, pixel data retrieved from images or the -framebuffer, and a variety of other things. - -ogl::Buffer has interface similar with Mat interface and represents 2D array memory. - -ogl::Buffer supports memory transfers between host and device and also can be mapped to CUDA memory. - */ -class CV_EXPORTS Buffer -{ -public: - /** @brief The target defines how you intend to use the buffer object. - */ - enum Target - { - ARRAY_BUFFER = 0x8892, //!< The buffer will be used as a source for vertex data - ELEMENT_ARRAY_BUFFER = 0x8893, //!< The buffer will be used for indices (in glDrawElements, for example) - PIXEL_PACK_BUFFER = 0x88EB, //!< The buffer will be used for reading from OpenGL textures - PIXEL_UNPACK_BUFFER = 0x88EC //!< The buffer will be used for writing to OpenGL textures - }; - - enum Access - { - READ_ONLY = 0x88B8, - WRITE_ONLY = 0x88B9, - READ_WRITE = 0x88BA - }; - - /** @brief The constructors. - - Creates empty ogl::Buffer object, creates ogl::Buffer object from existed buffer ( abufId - parameter), allocates memory for ogl::Buffer object or copies from host/device memory. - */ - Buffer(); - - /** @overload - @param arows Number of rows in a 2D array. - @param acols Number of columns in a 2D array. - @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. - @param abufId Buffer object name. - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - Buffer(int arows, int acols, int atype, unsigned int abufId, bool autoRelease = false); - - /** @overload - @param asize 2D array size. - @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. - @param abufId Buffer object name. - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - Buffer(Size asize, int atype, unsigned int abufId, bool autoRelease = false); - - /** @overload - @param arows Number of rows in a 2D array. - @param acols Number of columns in a 2D array. - @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. - @param target Buffer usage. See cv::ogl::Buffer::Target . - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - Buffer(int arows, int acols, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false); - - /** @overload - @param asize 2D array size. - @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. - @param target Buffer usage. See cv::ogl::Buffer::Target . - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - Buffer(Size asize, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false); - - /** @overload - @param arr Input array (host or device memory, it can be Mat , cuda::GpuMat or std::vector ). - @param target Buffer usage. See cv::ogl::Buffer::Target . - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - explicit Buffer(InputArray arr, Target target = ARRAY_BUFFER, bool autoRelease = false); - - /** @brief Allocates memory for ogl::Buffer object. - - @param arows Number of rows in a 2D array. - @param acols Number of columns in a 2D array. - @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. - @param target Buffer usage. See cv::ogl::Buffer::Target . - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - void create(int arows, int acols, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false); - - /** @overload - @param asize 2D array size. - @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. - @param target Buffer usage. See cv::ogl::Buffer::Target . - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - void create(Size asize, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false); - - /** @brief Decrements the reference counter and destroys the buffer object if needed. - - The function will call setAutoRelease(true) . - */ - void release(); - - /** @brief Sets auto release mode. - - The lifetime of the OpenGL object is tied to the lifetime of the context. If OpenGL context was - bound to a window it could be released at any time (user can close a window). If object's destructor - is called after destruction of the context it will cause an error. Thus ogl::Buffer doesn't destroy - OpenGL object in destructor by default (all OpenGL resources will be released with OpenGL context). - This function can force ogl::Buffer destructor to destroy OpenGL object. - @param flag Auto release mode (if true, release will be called in object's destructor). - */ - void setAutoRelease(bool flag); - - /** @brief Copies from host/device memory to OpenGL buffer. - @param arr Input array (host or device memory, it can be Mat , cuda::GpuMat or std::vector ). - @param target Buffer usage. See cv::ogl::Buffer::Target . - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - void copyFrom(InputArray arr, Target target = ARRAY_BUFFER, bool autoRelease = false); - - /** @overload */ - void copyFrom(InputArray arr, cuda::Stream& stream, Target target = ARRAY_BUFFER, bool autoRelease = false); - - /** @brief Copies from OpenGL buffer to host/device memory or another OpenGL buffer object. - - @param arr Destination array (host or device memory, can be Mat , cuda::GpuMat , std::vector or - ogl::Buffer ). - */ - void copyTo(OutputArray arr) const; - - /** @overload */ - void copyTo(OutputArray arr, cuda::Stream& stream) const; - - /** @brief Creates a full copy of the buffer object and the underlying data. - - @param target Buffer usage for destination buffer. - @param autoRelease Auto release mode for destination buffer. - */ - Buffer clone(Target target = ARRAY_BUFFER, bool autoRelease = false) const; - - /** @brief Binds OpenGL buffer to the specified buffer binding point. - - @param target Binding point. See cv::ogl::Buffer::Target . - */ - void bind(Target target) const; - - /** @brief Unbind any buffers from the specified binding point. - - @param target Binding point. See cv::ogl::Buffer::Target . - */ - static void unbind(Target target); - - /** @brief Maps OpenGL buffer to host memory. - - mapHost maps to the client's address space the entire data store of the buffer object. The data can - then be directly read and/or written relative to the returned pointer, depending on the specified - access policy. - - A mapped data store must be unmapped with ogl::Buffer::unmapHost before its buffer object is used. - - This operation can lead to memory transfers between host and device. - - Only one buffer object can be mapped at a time. - @param access Access policy, indicating whether it will be possible to read from, write to, or both - read from and write to the buffer object's mapped data store. The symbolic constant must be - ogl::Buffer::READ_ONLY , ogl::Buffer::WRITE_ONLY or ogl::Buffer::READ_WRITE . - */ - Mat mapHost(Access access); - - /** @brief Unmaps OpenGL buffer. - */ - void unmapHost(); - - //! map to device memory (blocking) - cuda::GpuMat mapDevice(); - void unmapDevice(); - - /** @brief Maps OpenGL buffer to CUDA device memory. - - This operation doesn't copy data. Several buffer objects can be mapped to CUDA memory at a time. - - A mapped data store must be unmapped with ogl::Buffer::unmapDevice before its buffer object is used. - */ - cuda::GpuMat mapDevice(cuda::Stream& stream); - - /** @brief Unmaps OpenGL buffer. - */ - void unmapDevice(cuda::Stream& stream); - - int rows() const; - int cols() const; - Size size() const; - bool empty() const; - - int type() const; - int depth() const; - int channels() const; - int elemSize() const; - int elemSize1() const; - - //! get OpenGL opject id - unsigned int bufId() const; - - class Impl; - -private: - Ptr impl_; - int rows_; - int cols_; - int type_; -}; - -/** @brief Smart pointer for OpenGL 2D texture memory with reference counting. - */ -class CV_EXPORTS Texture2D -{ -public: - /** @brief An Image Format describes the way that the images in Textures store their data. - */ - enum Format - { - NONE = 0, - DEPTH_COMPONENT = 0x1902, //!< Depth - RGB = 0x1907, //!< Red, Green, Blue - RGBA = 0x1908 //!< Red, Green, Blue, Alpha - }; - - /** @brief The constructors. - - Creates empty ogl::Texture2D object, allocates memory for ogl::Texture2D object or copies from - host/device memory. - */ - Texture2D(); - - /** @overload */ - Texture2D(int arows, int acols, Format aformat, unsigned int atexId, bool autoRelease = false); - - /** @overload */ - Texture2D(Size asize, Format aformat, unsigned int atexId, bool autoRelease = false); - - /** @overload - @param arows Number of rows. - @param acols Number of columns. - @param aformat Image format. See cv::ogl::Texture2D::Format . - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - Texture2D(int arows, int acols, Format aformat, bool autoRelease = false); - - /** @overload - @param asize 2D array size. - @param aformat Image format. See cv::ogl::Texture2D::Format . - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - Texture2D(Size asize, Format aformat, bool autoRelease = false); - - /** @overload - @param arr Input array (host or device memory, it can be Mat , cuda::GpuMat or ogl::Buffer ). - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - explicit Texture2D(InputArray arr, bool autoRelease = false); - - /** @brief Allocates memory for ogl::Texture2D object. - - @param arows Number of rows. - @param acols Number of columns. - @param aformat Image format. See cv::ogl::Texture2D::Format . - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - void create(int arows, int acols, Format aformat, bool autoRelease = false); - /** @overload - @param asize 2D array size. - @param aformat Image format. See cv::ogl::Texture2D::Format . - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - void create(Size asize, Format aformat, bool autoRelease = false); - - /** @brief Decrements the reference counter and destroys the texture object if needed. - - The function will call setAutoRelease(true) . - */ - void release(); - - /** @brief Sets auto release mode. - - @param flag Auto release mode (if true, release will be called in object's destructor). - - The lifetime of the OpenGL object is tied to the lifetime of the context. If OpenGL context was - bound to a window it could be released at any time (user can close a window). If object's destructor - is called after destruction of the context it will cause an error. Thus ogl::Texture2D doesn't - destroy OpenGL object in destructor by default (all OpenGL resources will be released with OpenGL - context). This function can force ogl::Texture2D destructor to destroy OpenGL object. - */ - void setAutoRelease(bool flag); - - /** @brief Copies from host/device memory to OpenGL texture. - - @param arr Input array (host or device memory, it can be Mat , cuda::GpuMat or ogl::Buffer ). - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - void copyFrom(InputArray arr, bool autoRelease = false); - - /** @brief Copies from OpenGL texture to host/device memory or another OpenGL texture object. - - @param arr Destination array (host or device memory, can be Mat , cuda::GpuMat , ogl::Buffer or - ogl::Texture2D ). - @param ddepth Destination depth. - @param autoRelease Auto release mode for destination buffer (if arr is OpenGL buffer or texture). - */ - void copyTo(OutputArray arr, int ddepth = CV_32F, bool autoRelease = false) const; - - /** @brief Binds texture to current active texture unit for GL_TEXTURE_2D target. - */ - void bind() const; - - int rows() const; - int cols() const; - Size size() const; - bool empty() const; - - Format format() const; - - //! get OpenGL opject id - unsigned int texId() const; - - class Impl; - -private: - Ptr impl_; - int rows_; - int cols_; - Format format_; -}; - -/** @brief Wrapper for OpenGL Client-Side Vertex arrays. - -ogl::Arrays stores vertex data in ogl::Buffer objects. - */ -class CV_EXPORTS Arrays -{ -public: - /** @brief Default constructor - */ - Arrays(); - - /** @brief Sets an array of vertex coordinates. - @param vertex array with vertex coordinates, can be both host and device memory. - */ - void setVertexArray(InputArray vertex); - - /** @brief Resets vertex coordinates. - */ - void resetVertexArray(); - - /** @brief Sets an array of vertex colors. - @param color array with vertex colors, can be both host and device memory. - */ - void setColorArray(InputArray color); - - /** @brief Resets vertex colors. - */ - void resetColorArray(); - - /** @brief Sets an array of vertex normals. - @param normal array with vertex normals, can be both host and device memory. - */ - void setNormalArray(InputArray normal); - - /** @brief Resets vertex normals. - */ - void resetNormalArray(); - - /** @brief Sets an array of vertex texture coordinates. - @param texCoord array with vertex texture coordinates, can be both host and device memory. - */ - void setTexCoordArray(InputArray texCoord); - - /** @brief Resets vertex texture coordinates. - */ - void resetTexCoordArray(); - - /** @brief Releases all inner buffers. - */ - void release(); - - /** @brief Sets auto release mode all inner buffers. - @param flag Auto release mode. - */ - void setAutoRelease(bool flag); - - /** @brief Binds all vertex arrays. - */ - void bind() const; - - /** @brief Returns the vertex count. - */ - int size() const; - bool empty() const; - -private: - int size_; - Buffer vertex_; - Buffer color_; - Buffer normal_; - Buffer texCoord_; -}; - -/////////////////// Render Functions /////////////////// - -//! render mode -enum RenderModes { - POINTS = 0x0000, - LINES = 0x0001, - LINE_LOOP = 0x0002, - LINE_STRIP = 0x0003, - TRIANGLES = 0x0004, - TRIANGLE_STRIP = 0x0005, - TRIANGLE_FAN = 0x0006, - QUADS = 0x0007, - QUAD_STRIP = 0x0008, - POLYGON = 0x0009 -}; - -/** @brief Render OpenGL texture or primitives. -@param tex Texture to draw. -@param wndRect Region of window, where to draw a texture (normalized coordinates). -@param texRect Region of texture to draw (normalized coordinates). - */ -CV_EXPORTS void render(const Texture2D& tex, - Rect_ wndRect = Rect_(0.0, 0.0, 1.0, 1.0), - Rect_ texRect = Rect_(0.0, 0.0, 1.0, 1.0)); - -/** @overload -@param arr Array of privitives vertices. -@param mode Render mode. One of cv::ogl::RenderModes -@param color Color for all vertices. Will be used if arr doesn't contain color array. -*/ -CV_EXPORTS void render(const Arrays& arr, int mode = POINTS, Scalar color = Scalar::all(255)); - -/** @overload -@param arr Array of privitives vertices. -@param indices Array of vertices indices (host or device memory). -@param mode Render mode. One of cv::ogl::RenderModes -@param color Color for all vertices. Will be used if arr doesn't contain color array. -*/ -CV_EXPORTS void render(const Arrays& arr, InputArray indices, int mode = POINTS, Scalar color = Scalar::all(255)); - -/////////////////// CL-GL Interoperability Functions /////////////////// - -namespace ocl { -using namespace cv::ocl; - -// TODO static functions in the Context class -/** @brief Creates OpenCL context from GL. -@return Returns reference to OpenCL Context - */ -CV_EXPORTS Context& initializeContextFromGL(); - -} // namespace cv::ogl::ocl - -/** @brief Converts InputArray to Texture2D object. -@param src - source InputArray. -@param texture - destination Texture2D object. - */ -CV_EXPORTS void convertToGLTexture2D(InputArray src, Texture2D& texture); - -/** @brief Converts Texture2D object to OutputArray. -@param texture - source Texture2D object. -@param dst - destination OutputArray. - */ -CV_EXPORTS void convertFromGLTexture2D(const Texture2D& texture, OutputArray dst); - -/** @brief Maps Buffer object to process on CL side (convert to UMat). - -Function creates CL buffer from GL one, and then constructs UMat that can be used -to process buffer data with OpenCV functions. Note that in current implementation -UMat constructed this way doesn't own corresponding GL buffer object, so it is -the user responsibility to close down CL/GL buffers relationships by explicitly -calling unmapGLBuffer() function. -@param buffer - source Buffer object. -@param accessFlags - data access flags (ACCESS_READ|ACCESS_WRITE). -@return Returns UMat object - */ -CV_EXPORTS UMat mapGLBuffer(const Buffer& buffer, AccessFlag accessFlags = ACCESS_READ | ACCESS_WRITE); - -/** @brief Unmaps Buffer object (releases UMat, previously mapped from Buffer). - -Function must be called explicitly by the user for each UMat previously constructed -by the call to mapGLBuffer() function. -@param u - source UMat, created by mapGLBuffer(). - */ -CV_EXPORTS void unmapGLBuffer(UMat& u); - -//! @} -}} // namespace cv::ogl - -namespace cv { namespace cuda { - -/** @brief Sets a CUDA device and initializes it for the current thread with OpenGL interoperability. - -This function should be explicitly called after OpenGL context creation and before any CUDA calls. -@param device System index of a CUDA device starting with 0. -@ingroup core_opengl - */ -CV_EXPORTS void setGlDevice(int device = 0); - -}} - -//! @cond IGNORED - -//////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////// - -inline -cv::ogl::Buffer::Buffer(int arows, int acols, int atype, Target target, bool autoRelease) : rows_(0), cols_(0), type_(0) -{ - create(arows, acols, atype, target, autoRelease); -} - -inline -cv::ogl::Buffer::Buffer(Size asize, int atype, Target target, bool autoRelease) : rows_(0), cols_(0), type_(0) -{ - create(asize, atype, target, autoRelease); -} - -inline -void cv::ogl::Buffer::create(Size asize, int atype, Target target, bool autoRelease) -{ - create(asize.height, asize.width, atype, target, autoRelease); -} - -inline -int cv::ogl::Buffer::rows() const -{ - return rows_; -} - -inline -int cv::ogl::Buffer::cols() const -{ - return cols_; -} - -inline -cv::Size cv::ogl::Buffer::size() const -{ - return Size(cols_, rows_); -} - -inline -bool cv::ogl::Buffer::empty() const -{ - return rows_ == 0 || cols_ == 0; -} - -inline -int cv::ogl::Buffer::type() const -{ - return type_; -} - -inline -int cv::ogl::Buffer::depth() const -{ - return CV_MAT_DEPTH(type_); -} - -inline -int cv::ogl::Buffer::channels() const -{ - return CV_MAT_CN(type_); -} - -inline -int cv::ogl::Buffer::elemSize() const -{ - return CV_ELEM_SIZE(type_); -} - -inline -int cv::ogl::Buffer::elemSize1() const -{ - return CV_ELEM_SIZE1(type_); -} - -/////// - -inline -cv::ogl::Texture2D::Texture2D(int arows, int acols, Format aformat, bool autoRelease) : rows_(0), cols_(0), format_(NONE) -{ - create(arows, acols, aformat, autoRelease); -} - -inline -cv::ogl::Texture2D::Texture2D(Size asize, Format aformat, bool autoRelease) : rows_(0), cols_(0), format_(NONE) -{ - create(asize, aformat, autoRelease); -} - -inline -void cv::ogl::Texture2D::create(Size asize, Format aformat, bool autoRelease) -{ - create(asize.height, asize.width, aformat, autoRelease); -} - -inline -int cv::ogl::Texture2D::rows() const -{ - return rows_; -} - -inline -int cv::ogl::Texture2D::cols() const -{ - return cols_; -} - -inline -cv::Size cv::ogl::Texture2D::size() const -{ - return Size(cols_, rows_); -} - -inline -bool cv::ogl::Texture2D::empty() const -{ - return rows_ == 0 || cols_ == 0; -} - -inline -cv::ogl::Texture2D::Format cv::ogl::Texture2D::format() const -{ - return format_; -} - -/////// - -// WARNING: unreachable code using Ninja -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(push) -#pragma warning(disable: 4702) -#endif -inline -cv::ogl::Arrays::Arrays() : size_(0) -{ -} -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(pop) -#endif - -inline -int cv::ogl::Arrays::size() const -{ - return size_; -} - -inline -bool cv::ogl::Arrays::empty() const -{ - return size_ == 0; -} - -//! @endcond - -#endif /* OPENCV_CORE_OPENGL_HPP */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CORE_OPENGL_HPP +#define OPENCV_CORE_OPENGL_HPP + +#ifndef __cplusplus +# error opengl.hpp header must be compiled as C++ +#endif + +#include "opencv2/core.hpp" +#include "ocl.hpp" + +namespace cv { namespace ogl { + +/** @addtogroup core_opengl +This section describes OpenGL interoperability. + +To enable OpenGL support, configure OpenCV using CMake with WITH_OPENGL=ON . Currently OpenGL is +supported only with WIN32, GTK and Qt backends on Windows and Linux (MacOS and Android are not +supported). For GTK-2.0 backend gtkglext-1.0 library is required. + +To use OpenGL functionality you should first create OpenGL context (window or frame buffer). You can +do this with namedWindow function or with other OpenGL toolkit (GLUT, for example). +*/ +//! @{ + +/////////////////// OpenGL Objects /////////////////// + +/** @brief Smart pointer for OpenGL buffer object with reference counting. + +Buffer Objects are OpenGL objects that store an array of unformatted memory allocated by the OpenGL +context. These can be used to store vertex data, pixel data retrieved from images or the +framebuffer, and a variety of other things. + +ogl::Buffer has interface similar with Mat interface and represents 2D array memory. + +ogl::Buffer supports memory transfers between host and device and also can be mapped to CUDA memory. + */ +class CV_EXPORTS Buffer +{ +public: + /** @brief The target defines how you intend to use the buffer object. + */ + enum Target + { + ARRAY_BUFFER = 0x8892, //!< The buffer will be used as a source for vertex data + ELEMENT_ARRAY_BUFFER = 0x8893, //!< The buffer will be used for indices (in glDrawElements, for example) + PIXEL_PACK_BUFFER = 0x88EB, //!< The buffer will be used for reading from OpenGL textures + PIXEL_UNPACK_BUFFER = 0x88EC //!< The buffer will be used for writing to OpenGL textures + }; + + enum Access + { + READ_ONLY = 0x88B8, + WRITE_ONLY = 0x88B9, + READ_WRITE = 0x88BA + }; + + /** @brief The constructors. + + Creates empty ogl::Buffer object, creates ogl::Buffer object from existed buffer ( abufId + parameter), allocates memory for ogl::Buffer object or copies from host/device memory. + */ + Buffer(); + + /** @overload + @param arows Number of rows in a 2D array. + @param acols Number of columns in a 2D array. + @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. + @param abufId Buffer object name. + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + Buffer(int arows, int acols, int atype, unsigned int abufId, bool autoRelease = false); + + /** @overload + @param asize 2D array size. + @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. + @param abufId Buffer object name. + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + Buffer(Size asize, int atype, unsigned int abufId, bool autoRelease = false); + + /** @overload + @param arows Number of rows in a 2D array. + @param acols Number of columns in a 2D array. + @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. + @param target Buffer usage. See cv::ogl::Buffer::Target . + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + Buffer(int arows, int acols, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false); + + /** @overload + @param asize 2D array size. + @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. + @param target Buffer usage. See cv::ogl::Buffer::Target . + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + Buffer(Size asize, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false); + + /** @overload + @param arr Input array (host or device memory, it can be Mat , cuda::GpuMat or std::vector ). + @param target Buffer usage. See cv::ogl::Buffer::Target . + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + explicit Buffer(InputArray arr, Target target = ARRAY_BUFFER, bool autoRelease = false); + + /** @brief Allocates memory for ogl::Buffer object. + + @param arows Number of rows in a 2D array. + @param acols Number of columns in a 2D array. + @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. + @param target Buffer usage. See cv::ogl::Buffer::Target . + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + void create(int arows, int acols, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false); + + /** @overload + @param asize 2D array size. + @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. + @param target Buffer usage. See cv::ogl::Buffer::Target . + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + void create(Size asize, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false); + + /** @brief Decrements the reference counter and destroys the buffer object if needed. + + The function will call setAutoRelease(true) . + */ + void release(); + + /** @brief Sets auto release mode. + + The lifetime of the OpenGL object is tied to the lifetime of the context. If OpenGL context was + bound to a window it could be released at any time (user can close a window). If object's destructor + is called after destruction of the context it will cause an error. Thus ogl::Buffer doesn't destroy + OpenGL object in destructor by default (all OpenGL resources will be released with OpenGL context). + This function can force ogl::Buffer destructor to destroy OpenGL object. + @param flag Auto release mode (if true, release will be called in object's destructor). + */ + void setAutoRelease(bool flag); + + /** @brief Copies from host/device memory to OpenGL buffer. + @param arr Input array (host or device memory, it can be Mat , cuda::GpuMat or std::vector ). + @param target Buffer usage. See cv::ogl::Buffer::Target . + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + void copyFrom(InputArray arr, Target target = ARRAY_BUFFER, bool autoRelease = false); + + /** @overload */ + void copyFrom(InputArray arr, cuda::Stream& stream, Target target = ARRAY_BUFFER, bool autoRelease = false); + + /** @brief Copies from OpenGL buffer to host/device memory or another OpenGL buffer object. + + @param arr Destination array (host or device memory, can be Mat , cuda::GpuMat , std::vector or + ogl::Buffer ). + */ + void copyTo(OutputArray arr) const; + + /** @overload */ + void copyTo(OutputArray arr, cuda::Stream& stream) const; + + /** @brief Creates a full copy of the buffer object and the underlying data. + + @param target Buffer usage for destination buffer. + @param autoRelease Auto release mode for destination buffer. + */ + Buffer clone(Target target = ARRAY_BUFFER, bool autoRelease = false) const; + + /** @brief Binds OpenGL buffer to the specified buffer binding point. + + @param target Binding point. See cv::ogl::Buffer::Target . + */ + void bind(Target target) const; + + /** @brief Unbind any buffers from the specified binding point. + + @param target Binding point. See cv::ogl::Buffer::Target . + */ + static void unbind(Target target); + + /** @brief Maps OpenGL buffer to host memory. + + mapHost maps to the client's address space the entire data store of the buffer object. The data can + then be directly read and/or written relative to the returned pointer, depending on the specified + access policy. + + A mapped data store must be unmapped with ogl::Buffer::unmapHost before its buffer object is used. + + This operation can lead to memory transfers between host and device. + + Only one buffer object can be mapped at a time. + @param access Access policy, indicating whether it will be possible to read from, write to, or both + read from and write to the buffer object's mapped data store. The symbolic constant must be + ogl::Buffer::READ_ONLY , ogl::Buffer::WRITE_ONLY or ogl::Buffer::READ_WRITE . + */ + Mat mapHost(Access access); + + /** @brief Unmaps OpenGL buffer. + */ + void unmapHost(); + + //! map to device memory (blocking) + cuda::GpuMat mapDevice(); + void unmapDevice(); + + /** @brief Maps OpenGL buffer to CUDA device memory. + + This operation doesn't copy data. Several buffer objects can be mapped to CUDA memory at a time. + + A mapped data store must be unmapped with ogl::Buffer::unmapDevice before its buffer object is used. + */ + cuda::GpuMat mapDevice(cuda::Stream& stream); + + /** @brief Unmaps OpenGL buffer. + */ + void unmapDevice(cuda::Stream& stream); + + int rows() const; + int cols() const; + Size size() const; + bool empty() const; + + int type() const; + int depth() const; + int channels() const; + int elemSize() const; + int elemSize1() const; + + //! get OpenGL opject id + unsigned int bufId() const; + + class Impl; + +private: + Ptr impl_; + int rows_; + int cols_; + int type_; +}; + +/** @brief Smart pointer for OpenGL 2D texture memory with reference counting. + */ +class CV_EXPORTS Texture2D +{ +public: + /** @brief An Image Format describes the way that the images in Textures store their data. + */ + enum Format + { + NONE = 0, + DEPTH_COMPONENT = 0x1902, //!< Depth + RGB = 0x1907, //!< Red, Green, Blue + RGBA = 0x1908 //!< Red, Green, Blue, Alpha + }; + + /** @brief The constructors. + + Creates empty ogl::Texture2D object, allocates memory for ogl::Texture2D object or copies from + host/device memory. + */ + Texture2D(); + + /** @overload */ + Texture2D(int arows, int acols, Format aformat, unsigned int atexId, bool autoRelease = false); + + /** @overload */ + Texture2D(Size asize, Format aformat, unsigned int atexId, bool autoRelease = false); + + /** @overload + @param arows Number of rows. + @param acols Number of columns. + @param aformat Image format. See cv::ogl::Texture2D::Format . + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + Texture2D(int arows, int acols, Format aformat, bool autoRelease = false); + + /** @overload + @param asize 2D array size. + @param aformat Image format. See cv::ogl::Texture2D::Format . + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + Texture2D(Size asize, Format aformat, bool autoRelease = false); + + /** @overload + @param arr Input array (host or device memory, it can be Mat , cuda::GpuMat or ogl::Buffer ). + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + explicit Texture2D(InputArray arr, bool autoRelease = false); + + /** @brief Allocates memory for ogl::Texture2D object. + + @param arows Number of rows. + @param acols Number of columns. + @param aformat Image format. See cv::ogl::Texture2D::Format . + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + void create(int arows, int acols, Format aformat, bool autoRelease = false); + /** @overload + @param asize 2D array size. + @param aformat Image format. See cv::ogl::Texture2D::Format . + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + void create(Size asize, Format aformat, bool autoRelease = false); + + /** @brief Decrements the reference counter and destroys the texture object if needed. + + The function will call setAutoRelease(true) . + */ + void release(); + + /** @brief Sets auto release mode. + + @param flag Auto release mode (if true, release will be called in object's destructor). + + The lifetime of the OpenGL object is tied to the lifetime of the context. If OpenGL context was + bound to a window it could be released at any time (user can close a window). If object's destructor + is called after destruction of the context it will cause an error. Thus ogl::Texture2D doesn't + destroy OpenGL object in destructor by default (all OpenGL resources will be released with OpenGL + context). This function can force ogl::Texture2D destructor to destroy OpenGL object. + */ + void setAutoRelease(bool flag); + + /** @brief Copies from host/device memory to OpenGL texture. + + @param arr Input array (host or device memory, it can be Mat , cuda::GpuMat or ogl::Buffer ). + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + void copyFrom(InputArray arr, bool autoRelease = false); + + /** @brief Copies from OpenGL texture to host/device memory or another OpenGL texture object. + + @param arr Destination array (host or device memory, can be Mat , cuda::GpuMat , ogl::Buffer or + ogl::Texture2D ). + @param ddepth Destination depth. + @param autoRelease Auto release mode for destination buffer (if arr is OpenGL buffer or texture). + */ + void copyTo(OutputArray arr, int ddepth = CV_32F, bool autoRelease = false) const; + + /** @brief Binds texture to current active texture unit for GL_TEXTURE_2D target. + */ + void bind() const; + + int rows() const; + int cols() const; + Size size() const; + bool empty() const; + + Format format() const; + + //! get OpenGL opject id + unsigned int texId() const; + + class Impl; + +private: + Ptr impl_; + int rows_; + int cols_; + Format format_; +}; + +/** @brief Wrapper for OpenGL Client-Side Vertex arrays. + +ogl::Arrays stores vertex data in ogl::Buffer objects. + */ +class CV_EXPORTS Arrays +{ +public: + /** @brief Default constructor + */ + Arrays(); + + /** @brief Sets an array of vertex coordinates. + @param vertex array with vertex coordinates, can be both host and device memory. + */ + void setVertexArray(InputArray vertex); + + /** @brief Resets vertex coordinates. + */ + void resetVertexArray(); + + /** @brief Sets an array of vertex colors. + @param color array with vertex colors, can be both host and device memory. + */ + void setColorArray(InputArray color); + + /** @brief Resets vertex colors. + */ + void resetColorArray(); + + /** @brief Sets an array of vertex normals. + @param normal array with vertex normals, can be both host and device memory. + */ + void setNormalArray(InputArray normal); + + /** @brief Resets vertex normals. + */ + void resetNormalArray(); + + /** @brief Sets an array of vertex texture coordinates. + @param texCoord array with vertex texture coordinates, can be both host and device memory. + */ + void setTexCoordArray(InputArray texCoord); + + /** @brief Resets vertex texture coordinates. + */ + void resetTexCoordArray(); + + /** @brief Releases all inner buffers. + */ + void release(); + + /** @brief Sets auto release mode all inner buffers. + @param flag Auto release mode. + */ + void setAutoRelease(bool flag); + + /** @brief Binds all vertex arrays. + */ + void bind() const; + + /** @brief Returns the vertex count. + */ + int size() const; + bool empty() const; + +private: + int size_; + Buffer vertex_; + Buffer color_; + Buffer normal_; + Buffer texCoord_; +}; + +/////////////////// Render Functions /////////////////// + +//! render mode +enum RenderModes { + POINTS = 0x0000, + LINES = 0x0001, + LINE_LOOP = 0x0002, + LINE_STRIP = 0x0003, + TRIANGLES = 0x0004, + TRIANGLE_STRIP = 0x0005, + TRIANGLE_FAN = 0x0006, + QUADS = 0x0007, + QUAD_STRIP = 0x0008, + POLYGON = 0x0009 +}; + +/** @brief Render OpenGL texture or primitives. +@param tex Texture to draw. +@param wndRect Region of window, where to draw a texture (normalized coordinates). +@param texRect Region of texture to draw (normalized coordinates). + */ +CV_EXPORTS void render(const Texture2D& tex, + Rect_ wndRect = Rect_(0.0, 0.0, 1.0, 1.0), + Rect_ texRect = Rect_(0.0, 0.0, 1.0, 1.0)); + +/** @overload +@param arr Array of privitives vertices. +@param mode Render mode. One of cv::ogl::RenderModes +@param color Color for all vertices. Will be used if arr doesn't contain color array. +*/ +CV_EXPORTS void render(const Arrays& arr, int mode = POINTS, Scalar color = Scalar::all(255)); + +/** @overload +@param arr Array of privitives vertices. +@param indices Array of vertices indices (host or device memory). +@param mode Render mode. One of cv::ogl::RenderModes +@param color Color for all vertices. Will be used if arr doesn't contain color array. +*/ +CV_EXPORTS void render(const Arrays& arr, InputArray indices, int mode = POINTS, Scalar color = Scalar::all(255)); + +/////////////////// CL-GL Interoperability Functions /////////////////// + +namespace ocl { +using namespace cv::ocl; + +// TODO static functions in the Context class +/** @brief Creates OpenCL context from GL. +@return Returns reference to OpenCL Context + */ +CV_EXPORTS Context& initializeContextFromGL(); + +} // namespace cv::ogl::ocl + +/** @brief Converts InputArray to Texture2D object. +@param src - source InputArray. +@param texture - destination Texture2D object. + */ +CV_EXPORTS void convertToGLTexture2D(InputArray src, Texture2D& texture); + +/** @brief Converts Texture2D object to OutputArray. +@param texture - source Texture2D object. +@param dst - destination OutputArray. + */ +CV_EXPORTS void convertFromGLTexture2D(const Texture2D& texture, OutputArray dst); + +/** @brief Maps Buffer object to process on CL side (convert to UMat). + +Function creates CL buffer from GL one, and then constructs UMat that can be used +to process buffer data with OpenCV functions. Note that in current implementation +UMat constructed this way doesn't own corresponding GL buffer object, so it is +the user responsibility to close down CL/GL buffers relationships by explicitly +calling unmapGLBuffer() function. +@param buffer - source Buffer object. +@param accessFlags - data access flags (ACCESS_READ|ACCESS_WRITE). +@return Returns UMat object + */ +CV_EXPORTS UMat mapGLBuffer(const Buffer& buffer, AccessFlag accessFlags = ACCESS_READ | ACCESS_WRITE); + +/** @brief Unmaps Buffer object (releases UMat, previously mapped from Buffer). + +Function must be called explicitly by the user for each UMat previously constructed +by the call to mapGLBuffer() function. +@param u - source UMat, created by mapGLBuffer(). + */ +CV_EXPORTS void unmapGLBuffer(UMat& u); + +//! @} +}} // namespace cv::ogl + +namespace cv { namespace cuda { + +/** @brief Sets a CUDA device and initializes it for the current thread with OpenGL interoperability. + +This function should be explicitly called after OpenGL context creation and before any CUDA calls. +@param device System index of a CUDA device starting with 0. +@ingroup core_opengl + */ +CV_EXPORTS void setGlDevice(int device = 0); + +}} + +//! @cond IGNORED + +//////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////// + +inline +cv::ogl::Buffer::Buffer(int arows, int acols, int atype, Target target, bool autoRelease) : rows_(0), cols_(0), type_(0) +{ + create(arows, acols, atype, target, autoRelease); +} + +inline +cv::ogl::Buffer::Buffer(Size asize, int atype, Target target, bool autoRelease) : rows_(0), cols_(0), type_(0) +{ + create(asize, atype, target, autoRelease); +} + +inline +void cv::ogl::Buffer::create(Size asize, int atype, Target target, bool autoRelease) +{ + create(asize.height, asize.width, atype, target, autoRelease); +} + +inline +int cv::ogl::Buffer::rows() const +{ + return rows_; +} + +inline +int cv::ogl::Buffer::cols() const +{ + return cols_; +} + +inline +cv::Size cv::ogl::Buffer::size() const +{ + return Size(cols_, rows_); +} + +inline +bool cv::ogl::Buffer::empty() const +{ + return rows_ == 0 || cols_ == 0; +} + +inline +int cv::ogl::Buffer::type() const +{ + return type_; +} + +inline +int cv::ogl::Buffer::depth() const +{ + return CV_MAT_DEPTH(type_); +} + +inline +int cv::ogl::Buffer::channels() const +{ + return CV_MAT_CN(type_); +} + +inline +int cv::ogl::Buffer::elemSize() const +{ + return CV_ELEM_SIZE(type_); +} + +inline +int cv::ogl::Buffer::elemSize1() const +{ + return CV_ELEM_SIZE1(type_); +} + +/////// + +inline +cv::ogl::Texture2D::Texture2D(int arows, int acols, Format aformat, bool autoRelease) : rows_(0), cols_(0), format_(NONE) +{ + create(arows, acols, aformat, autoRelease); +} + +inline +cv::ogl::Texture2D::Texture2D(Size asize, Format aformat, bool autoRelease) : rows_(0), cols_(0), format_(NONE) +{ + create(asize, aformat, autoRelease); +} + +inline +void cv::ogl::Texture2D::create(Size asize, Format aformat, bool autoRelease) +{ + create(asize.height, asize.width, aformat, autoRelease); +} + +inline +int cv::ogl::Texture2D::rows() const +{ + return rows_; +} + +inline +int cv::ogl::Texture2D::cols() const +{ + return cols_; +} + +inline +cv::Size cv::ogl::Texture2D::size() const +{ + return Size(cols_, rows_); +} + +inline +bool cv::ogl::Texture2D::empty() const +{ + return rows_ == 0 || cols_ == 0; +} + +inline +cv::ogl::Texture2D::Format cv::ogl::Texture2D::format() const +{ + return format_; +} + +/////// + +// WARNING: unreachable code using Ninja +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(push) +#pragma warning(disable: 4702) +#endif +inline +cv::ogl::Arrays::Arrays() : size_(0) +{ +} +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(pop) +#endif + +inline +int cv::ogl::Arrays::size() const +{ + return size_; +} + +inline +bool cv::ogl::Arrays::empty() const +{ + return size_ == 0; +} + +//! @endcond + +#endif /* OPENCV_CORE_OPENGL_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/operations.hpp b/3rdParty/opencv-4.11.0/opencv2/core/operations.hpp index 7eeb2ab4c2..f754b6f01b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/operations.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/operations.hpp @@ -1,612 +1,612 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CORE_OPERATIONS_HPP -#define OPENCV_CORE_OPERATIONS_HPP - -#ifndef __cplusplus -# error operations.hpp header must be compiled as C++ -#endif - -#include - -#if defined(__GNUC__) || defined(__clang__) // at least GCC 3.1+, clang 3.5+ -# if defined(__MINGW_PRINTF_FORMAT) // https://sourceforge.net/p/mingw-w64/wiki2/gnu%20printf/. -# define CV_FORMAT_PRINTF(string_idx, first_to_check) __attribute__ ((format (__MINGW_PRINTF_FORMAT, string_idx, first_to_check))) -# else -# define CV_FORMAT_PRINTF(string_idx, first_to_check) __attribute__ ((format (printf, string_idx, first_to_check))) -# endif -#else -# define CV_FORMAT_PRINTF(A, B) -#endif - -namespace cv -{ -//! @cond IGNORED - - -////////////////////////////// Matx methods depending on core API ///////////////////////////// - -namespace internal -{ - -template struct Matx_FastInvOp -{ - bool operator()(const Matx<_Tp, m, n>& a, Matx<_Tp, n, m>& b, int method) const - { - return invert(a, b, method) != 0; - } -}; - -template struct Matx_FastInvOp<_Tp, m, m> -{ - bool operator()(const Matx<_Tp, m, m>& a, Matx<_Tp, m, m>& b, int method) const - { - if (method == DECOMP_LU || method == DECOMP_CHOLESKY) - { - Matx<_Tp, m, m> temp = a; - - // assume that b is all 0's on input => make it a unity matrix - for (int i = 0; i < m; i++) - b(i, i) = (_Tp)1; - - if (method == DECOMP_CHOLESKY) - return Cholesky(temp.val, m*sizeof(_Tp), m, b.val, m*sizeof(_Tp), m); - - return LU(temp.val, m*sizeof(_Tp), m, b.val, m*sizeof(_Tp), m) != 0; - } - else - { - return invert(a, b, method) != 0; - } - } -}; - -template struct Matx_FastInvOp<_Tp, 2, 2> -{ - bool operator()(const Matx<_Tp, 2, 2>& a, Matx<_Tp, 2, 2>& b, int /*method*/) const - { - _Tp d = (_Tp)determinant(a); - if (d == 0) - return false; - d = 1/d; - b(1,1) = a(0,0)*d; - b(0,0) = a(1,1)*d; - b(0,1) = -a(0,1)*d; - b(1,0) = -a(1,0)*d; - return true; - } -}; - -template struct Matx_FastInvOp<_Tp, 3, 3> -{ - bool operator()(const Matx<_Tp, 3, 3>& a, Matx<_Tp, 3, 3>& b, int /*method*/) const - { - _Tp d = (_Tp)determinant(a); - if (d == 0) - return false; - d = 1/d; - b(0,0) = (a(1,1) * a(2,2) - a(1,2) * a(2,1)) * d; - b(0,1) = (a(0,2) * a(2,1) - a(0,1) * a(2,2)) * d; - b(0,2) = (a(0,1) * a(1,2) - a(0,2) * a(1,1)) * d; - - b(1,0) = (a(1,2) * a(2,0) - a(1,0) * a(2,2)) * d; - b(1,1) = (a(0,0) * a(2,2) - a(0,2) * a(2,0)) * d; - b(1,2) = (a(0,2) * a(1,0) - a(0,0) * a(1,2)) * d; - - b(2,0) = (a(1,0) * a(2,1) - a(1,1) * a(2,0)) * d; - b(2,1) = (a(0,1) * a(2,0) - a(0,0) * a(2,1)) * d; - b(2,2) = (a(0,0) * a(1,1) - a(0,1) * a(1,0)) * d; - return true; - } -}; - - -template struct Matx_FastSolveOp -{ - bool operator()(const Matx<_Tp, m, l>& a, const Matx<_Tp, m, n>& b, - Matx<_Tp, l, n>& x, int method) const - { - return cv::solve(a, b, x, method); - } -}; - -template struct Matx_FastSolveOp<_Tp, m, m, n> -{ - bool operator()(const Matx<_Tp, m, m>& a, const Matx<_Tp, m, n>& b, - Matx<_Tp, m, n>& x, int method) const - { - if (method == DECOMP_LU || method == DECOMP_CHOLESKY) - { - Matx<_Tp, m, m> temp = a; - x = b; - if( method == DECOMP_CHOLESKY ) - return Cholesky(temp.val, m*sizeof(_Tp), m, x.val, n*sizeof(_Tp), n); - - return LU(temp.val, m*sizeof(_Tp), m, x.val, n*sizeof(_Tp), n) != 0; - } - else - { - return cv::solve(a, b, x, method); - } - } -}; - -template struct Matx_FastSolveOp<_Tp, 2, 2, 1> -{ - bool operator()(const Matx<_Tp, 2, 2>& a, const Matx<_Tp, 2, 1>& b, - Matx<_Tp, 2, 1>& x, int) const - { - _Tp d = (_Tp)determinant(a); - if (d == 0) - return false; - d = 1/d; - x(0) = (b(0)*a(1,1) - b(1)*a(0,1))*d; - x(1) = (b(1)*a(0,0) - b(0)*a(1,0))*d; - return true; - } -}; - -template struct Matx_FastSolveOp<_Tp, 3, 3, 1> -{ - bool operator()(const Matx<_Tp, 3, 3>& a, const Matx<_Tp, 3, 1>& b, - Matx<_Tp, 3, 1>& x, int) const - { - _Tp d = (_Tp)determinant(a); - if (d == 0) - return false; - d = 1/d; - x(0) = d*(b(0)*(a(1,1)*a(2,2) - a(1,2)*a(2,1)) - - a(0,1)*(b(1)*a(2,2) - a(1,2)*b(2)) + - a(0,2)*(b(1)*a(2,1) - a(1,1)*b(2))); - - x(1) = d*(a(0,0)*(b(1)*a(2,2) - a(1,2)*b(2)) - - b(0)*(a(1,0)*a(2,2) - a(1,2)*a(2,0)) + - a(0,2)*(a(1,0)*b(2) - b(1)*a(2,0))); - - x(2) = d*(a(0,0)*(a(1,1)*b(2) - b(1)*a(2,1)) - - a(0,1)*(a(1,0)*b(2) - b(1)*a(2,0)) + - b(0)*(a(1,0)*a(2,1) - a(1,1)*a(2,0))); - return true; - } -}; - -} // internal - -template inline -Matx<_Tp,m,n> Matx<_Tp,m,n>::randu(_Tp a, _Tp b) -{ - Matx<_Tp,m,n> M; - cv::randu(M, Scalar(a), Scalar(b)); - return M; -} - -template inline -Matx<_Tp,m,n> Matx<_Tp,m,n>::randn(_Tp a, _Tp b) -{ - Matx<_Tp,m,n> M; - cv::randn(M, Scalar(a), Scalar(b)); - return M; -} - -template inline -Vec<_Tp, cn> Vec<_Tp, cn>::randu(_Tp a, _Tp b) -{ - Vec<_Tp,cn> V; - cv::randu(V, Scalar(a), Scalar(b)); - return V; -} - -template inline -Vec<_Tp, cn> Vec<_Tp, cn>::randn(_Tp a, _Tp b) -{ - Vec<_Tp,cn> V; - cv::randn(V, Scalar(a), Scalar(b)); - return V; -} - -template inline -Matx<_Tp, n, m> Matx<_Tp, m, n>::inv(int method, bool *p_is_ok /*= NULL*/) const -{ - Matx<_Tp, n, m> b; - bool ok = cv::internal::Matx_FastInvOp<_Tp, m, n>()(*this, b, method); - if (p_is_ok) *p_is_ok = ok; - return ok ? b : Matx<_Tp, n, m>::zeros(); -} - -template template inline -Matx<_Tp, n, l> Matx<_Tp, m, n>::solve(const Matx<_Tp, m, l>& rhs, int method) const -{ - Matx<_Tp, n, l> x; - bool ok = cv::internal::Matx_FastSolveOp<_Tp, m, n, l>()(*this, rhs, x, method); - return ok ? x : Matx<_Tp, n, l>::zeros(); -} - - - -////////////////////////// Augmenting algebraic & logical operations ////////////////////////// - -#define CV_MAT_AUG_OPERATOR1(op, cvop, A, B) \ - static inline A& operator op (A& a, const B& b) { cvop; return a; } - -#define CV_MAT_AUG_OPERATOR(op, cvop, A, B) \ - CV_MAT_AUG_OPERATOR1(op, cvop, A, B) \ - CV_MAT_AUG_OPERATOR1(op, cvop, const A, B) - -#define CV_MAT_AUG_OPERATOR_T(op, cvop, A, B) \ - template CV_MAT_AUG_OPERATOR1(op, cvop, A, B) \ - template CV_MAT_AUG_OPERATOR1(op, cvop, const A, B) - -#define CV_MAT_AUG_OPERATOR_TN(op, cvop, A) \ - template static inline A& operator op (A& a, const Matx<_Tp,m,n>& b) { cvop; return a; } \ - template static inline const A& operator op (const A& a, const Matx<_Tp,m,n>& b) { cvop; return a; } - -CV_MAT_AUG_OPERATOR (+=, cv::add(a, b, (const Mat&)a), Mat, Mat) -CV_MAT_AUG_OPERATOR (+=, cv::add(a, b, (const Mat&)a), Mat, Scalar) -CV_MAT_AUG_OPERATOR_T(+=, cv::add(a, b, (const Mat&)a), Mat_<_Tp>, Mat) -CV_MAT_AUG_OPERATOR_T(+=, cv::add(a, b, (const Mat&)a), Mat_<_Tp>, Scalar) -CV_MAT_AUG_OPERATOR_T(+=, cv::add(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>) -CV_MAT_AUG_OPERATOR_TN(+=, cv::add(a, Mat(b), (const Mat&)a), Mat) -CV_MAT_AUG_OPERATOR_TN(+=, cv::add(a, Mat(b), (const Mat&)a), Mat_<_Tp>) - -CV_MAT_AUG_OPERATOR (-=, cv::subtract(a, b, (const Mat&)a), Mat, Mat) -CV_MAT_AUG_OPERATOR (-=, cv::subtract(a, b, (const Mat&)a), Mat, Scalar) -CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a, b, (const Mat&)a), Mat_<_Tp>, Mat) -CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a, b, (const Mat&)a), Mat_<_Tp>, Scalar) -CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>) -CV_MAT_AUG_OPERATOR_TN(-=, cv::subtract(a, Mat(b), (const Mat&)a), Mat) -CV_MAT_AUG_OPERATOR_TN(-=, cv::subtract(a, Mat(b), (const Mat&)a), Mat_<_Tp>) - -CV_MAT_AUG_OPERATOR (*=, cv::gemm(a, b, 1, Mat(), 0, a, 0), Mat, Mat) -CV_MAT_AUG_OPERATOR_T(*=, cv::gemm(a, b, 1, Mat(), 0, a, 0), Mat_<_Tp>, Mat) -CV_MAT_AUG_OPERATOR_T(*=, cv::gemm(a, b, 1, Mat(), 0, a, 0), Mat_<_Tp>, Mat_<_Tp>) -CV_MAT_AUG_OPERATOR (*=, a.convertTo(a, -1, b), Mat, double) -CV_MAT_AUG_OPERATOR_T(*=, a.convertTo(a, -1, b), Mat_<_Tp>, double) -CV_MAT_AUG_OPERATOR_TN(*=, cv::gemm(a, Mat(b), 1, Mat(), 0, a, 0), Mat) -CV_MAT_AUG_OPERATOR_TN(*=, cv::gemm(a, Mat(b), 1, Mat(), 0, a, 0), Mat_<_Tp>) - -CV_MAT_AUG_OPERATOR (/=, cv::divide(a, b, (const Mat&)a), Mat, Mat) -CV_MAT_AUG_OPERATOR_T(/=, cv::divide(a, b, (const Mat&)a), Mat_<_Tp>, Mat) -CV_MAT_AUG_OPERATOR_T(/=, cv::divide(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>) -CV_MAT_AUG_OPERATOR (/=, a.convertTo((Mat&)a, -1, 1./b), Mat, double) -CV_MAT_AUG_OPERATOR_T(/=, a.convertTo((Mat&)a, -1, 1./b), Mat_<_Tp>, double) -CV_MAT_AUG_OPERATOR_TN(/=, cv::divide(a, Mat(b), (const Mat&)a), Mat) -CV_MAT_AUG_OPERATOR_TN(/=, cv::divide(a, Mat(b), (const Mat&)a), Mat_<_Tp>) - -CV_MAT_AUG_OPERATOR (&=, cv::bitwise_and(a, b, (const Mat&)a), Mat, Mat) -CV_MAT_AUG_OPERATOR (&=, cv::bitwise_and(a, b, (const Mat&)a), Mat, Scalar) -CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a, b, (const Mat&)a), Mat_<_Tp>, Mat) -CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a, b, (const Mat&)a), Mat_<_Tp>, Scalar) -CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>) -CV_MAT_AUG_OPERATOR_TN(&=, cv::bitwise_and(a, Mat(b), (const Mat&)a), Mat) -CV_MAT_AUG_OPERATOR_TN(&=, cv::bitwise_and(a, Mat(b), (const Mat&)a), Mat_<_Tp>) - -CV_MAT_AUG_OPERATOR (|=, cv::bitwise_or(a, b, (const Mat&)a), Mat, Mat) -CV_MAT_AUG_OPERATOR (|=, cv::bitwise_or(a, b, (const Mat&)a), Mat, Scalar) -CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a, b, (const Mat&)a), Mat_<_Tp>, Mat) -CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a, b, (const Mat&)a), Mat_<_Tp>, Scalar) -CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>) -CV_MAT_AUG_OPERATOR_TN(|=, cv::bitwise_or(a, Mat(b), (const Mat&)a), Mat) -CV_MAT_AUG_OPERATOR_TN(|=, cv::bitwise_or(a, Mat(b), (const Mat&)a), Mat_<_Tp>) - -CV_MAT_AUG_OPERATOR (^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat, Mat) -CV_MAT_AUG_OPERATOR (^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat, Scalar) -CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat_<_Tp>, Mat) -CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat_<_Tp>, Scalar) -CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>) -CV_MAT_AUG_OPERATOR_TN(^=, cv::bitwise_xor(a, Mat(b), (const Mat&)a), Mat) -CV_MAT_AUG_OPERATOR_TN(^=, cv::bitwise_xor(a, Mat(b), (const Mat&)a), Mat_<_Tp>) - -#undef CV_MAT_AUG_OPERATOR_TN -#undef CV_MAT_AUG_OPERATOR_T -#undef CV_MAT_AUG_OPERATOR -#undef CV_MAT_AUG_OPERATOR1 - - - -///////////////////////////////////////////// SVD ///////////////////////////////////////////// - -inline SVD::SVD() {} -inline SVD::SVD( InputArray m, int flags ) { operator ()(m, flags); } -inline void SVD::solveZ( InputArray m, OutputArray _dst ) -{ - Mat mtx = m.getMat(); - SVD svd(mtx, (mtx.rows >= mtx.cols ? 0 : SVD::FULL_UV)); - _dst.create(svd.vt.cols, 1, svd.vt.type()); - Mat dst = _dst.getMat(); - svd.vt.row(svd.vt.rows-1).reshape(1,svd.vt.cols).copyTo(dst); -} - -template inline void - SVD::compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt ) -{ - CV_StaticAssert( nm == MIN(m, n), "Invalid size of output vector."); - Mat _a(a, false), _u(u, false), _w(w, false), _vt(vt, false); - SVD::compute(_a, _w, _u, _vt); - CV_Assert(_w.data == (uchar*)&w.val[0] && _u.data == (uchar*)&u.val[0] && _vt.data == (uchar*)&vt.val[0]); -} - -template inline void -SVD::compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w ) -{ - CV_StaticAssert( nm == MIN(m, n), "Invalid size of output vector."); - Mat _a(a, false), _w(w, false); - SVD::compute(_a, _w); - CV_Assert(_w.data == (uchar*)&w.val[0]); -} - -template inline void -SVD::backSubst( const Matx<_Tp, nm, 1>& w, const Matx<_Tp, m, nm>& u, - const Matx<_Tp, n, nm>& vt, const Matx<_Tp, m, nb>& rhs, - Matx<_Tp, n, nb>& dst ) -{ - CV_StaticAssert( nm == MIN(m, n), "Invalid size of output vector."); - Mat _u(u, false), _w(w, false), _vt(vt, false), _rhs(rhs, false), _dst(dst, false); - SVD::backSubst(_w, _u, _vt, _rhs, _dst); - CV_Assert(_dst.data == (uchar*)&dst.val[0]); -} - - - -/////////////////////////////////// Multiply-with-Carry RNG /////////////////////////////////// - -inline RNG::RNG() { state = 0xffffffff; } -inline RNG::RNG(uint64 _state) { state = _state ? _state : 0xffffffff; } - -inline RNG::operator uchar() { return (uchar)next(); } -inline RNG::operator schar() { return (schar)next(); } -inline RNG::operator ushort() { return (ushort)next(); } -inline RNG::operator short() { return (short)next(); } -inline RNG::operator int() { return (int)next(); } -inline RNG::operator unsigned() { return next(); } -inline RNG::operator float() { return next()*2.3283064365386962890625e-10f; } -inline RNG::operator double() { unsigned t = next(); return (((uint64)t << 32) | next()) * 5.4210108624275221700372640043497e-20; } - -inline unsigned RNG::operator ()(unsigned N) { return (unsigned)uniform(0,N); } -inline unsigned RNG::operator ()() { return next(); } - -inline int RNG::uniform(int a, int b) { return a == b ? a : (int)(next() % (b - a) + a); } -inline float RNG::uniform(float a, float b) { return ((float)*this)*(b - a) + a; } -inline double RNG::uniform(double a, double b) { return ((double)*this)*(b - a) + a; } - -inline bool RNG::operator ==(const RNG& other) const { return state == other.state; } - -inline unsigned RNG::next() -{ - state = (uint64)(unsigned)state* /*CV_RNG_COEFF*/ 4164903690U + (unsigned)(state >> 32); - return (unsigned)state; -} - -//! returns the next uniformly-distributed random number of the specified type -template static inline _Tp randu() -{ - return (_Tp)theRNG(); -} - - -///////////////////////////////// Formatted output of cv::Mat ///////////////////////////////// - -static inline -Ptr format(InputArray mtx, Formatter::FormatType fmt) -{ - return Formatter::get(fmt)->format(mtx.getMat()); -} - -static inline -int print(Ptr fmtd, FILE* stream = stdout) -{ - int written = 0; - fmtd->reset(); - for(const char* str = fmtd->next(); str; str = fmtd->next()) - written += fputs(str, stream); - - return written; -} - -static inline -int print(const Mat& mtx, FILE* stream = stdout) -{ - return print(Formatter::get()->format(mtx), stream); -} - -static inline -int print(const UMat& mtx, FILE* stream = stdout) -{ - return print(Formatter::get()->format(mtx.getMat(ACCESS_READ)), stream); -} - -template static inline -int print(const std::vector >& vec, FILE* stream = stdout) -{ - return print(Formatter::get()->format(Mat(vec)), stream); -} - -template static inline -int print(const std::vector >& vec, FILE* stream = stdout) -{ - return print(Formatter::get()->format(Mat(vec)), stream); -} - -template static inline -int print(const Matx<_Tp, m, n>& matx, FILE* stream = stdout) -{ - return print(Formatter::get()->format(cv::Mat(matx)), stream); -} - -//! @endcond - -///////////////////////////////// Formatted string generation ///////////////////////////////// - -/** @brief Returns a text string formatted using the printf-like expression. - -The function acts like sprintf but forms and returns an STL string. It can be used to form an error -message in the Exception constructor. -@param fmt printf-compatible formatting specifiers. - -**Note**: -|Type|Specifier| -|-|-| -|`const char*`|`%s`| -|`char`|`%c`| -|`float` / `double`|`%f`,`%g`| -|`int`, `long`, `long long`|`%d`, `%ld`, ``%lld`| -|`unsigned`, `unsigned long`, `unsigned long long`|`%u`, `%lu`, `%llu`| -|`uint64` -> `uintmax_t`, `int64` -> `intmax_t`|`%ju`, `%jd`| -|`size_t`|`%zu`| -@ingroup core_utils - */ -CV_EXPORTS String format(const char* fmt, ...) CV_FORMAT_PRINTF(1, 2); - -/****************************************************************************************\ -* Auxiliary algorithms * -\****************************************************************************************/ - -/** @brief Splits an element set into equivalency classes. - -The generic function partition implements an \f$O(N^2)\f$ algorithm for splitting a set of \f$N\f$ elements -into one or more equivalency classes, as described in - . The function returns the number of -equivalency classes. -@param vec Set of elements stored as a vector. -@param labels Output vector of labels. It contains as many elements as vec. Each label labels[i] is -a 0-based cluster index of `vec[i]`. -@param predicate Equivalence predicate (pointer to a boolean function of two arguments or an -instance of the class that has the method bool operator()(const _Tp& a, const _Tp& b) ). The -predicate returns true when the elements are certainly in the same class, and returns false if they -may or may not be in the same class. -@ingroup core_cluster -*/ -template int -partition( const std::vector<_Tp>& vec, std::vector& labels, - _EqPredicate predicate=_EqPredicate()) -{ - int i, j, N = (int)vec.size(); - const _Tp* _vec = &vec[0]; - - const int PARENT=0; - const int RANK=1; - - std::vector _nodes(N*2); - int (*nodes)[2] = (int(*)[2])&_nodes[0]; - - // The first O(N) pass: create N single-vertex trees - for(i = 0; i < N; i++) - { - nodes[i][PARENT]=-1; - nodes[i][RANK] = 0; - } - - // The main O(N^2) pass: merge connected components - for( i = 0; i < N; i++ ) - { - int root = i; - - // find root - while( nodes[root][PARENT] >= 0 ) - root = nodes[root][PARENT]; - - for( j = 0; j < N; j++ ) - { - if( i == j || !predicate(_vec[i], _vec[j])) - continue; - int root2 = j; - - while( nodes[root2][PARENT] >= 0 ) - root2 = nodes[root2][PARENT]; - - if( root2 != root ) - { - // unite both trees - int rank = nodes[root][RANK], rank2 = nodes[root2][RANK]; - if( rank > rank2 ) - nodes[root2][PARENT] = root; - else - { - nodes[root][PARENT] = root2; - nodes[root2][RANK] += rank == rank2; - root = root2; - } - CV_Assert( nodes[root][PARENT] < 0 ); - - int k = j, parent; - - // compress the path from node2 to root - while( (parent = nodes[k][PARENT]) >= 0 ) - { - nodes[k][PARENT] = root; - k = parent; - } - - // compress the path from node to root - k = i; - while( (parent = nodes[k][PARENT]) >= 0 ) - { - nodes[k][PARENT] = root; - k = parent; - } - } - } - } - - // Final O(N) pass: enumerate classes - labels.resize(N); - int nclasses = 0; - - for( i = 0; i < N; i++ ) - { - int root = i; - while( nodes[root][PARENT] >= 0 ) - root = nodes[root][PARENT]; - // re-use the rank as the class label - if( nodes[root][RANK] >= 0 ) - nodes[root][RANK] = ~nclasses++; - labels[i] = ~nodes[root][RANK]; - } - - return nclasses; -} - -} // cv - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CORE_OPERATIONS_HPP +#define OPENCV_CORE_OPERATIONS_HPP + +#ifndef __cplusplus +# error operations.hpp header must be compiled as C++ +#endif + +#include + +#if defined(__GNUC__) || defined(__clang__) // at least GCC 3.1+, clang 3.5+ +# if defined(__MINGW_PRINTF_FORMAT) // https://sourceforge.net/p/mingw-w64/wiki2/gnu%20printf/. +# define CV_FORMAT_PRINTF(string_idx, first_to_check) __attribute__ ((format (__MINGW_PRINTF_FORMAT, string_idx, first_to_check))) +# else +# define CV_FORMAT_PRINTF(string_idx, first_to_check) __attribute__ ((format (printf, string_idx, first_to_check))) +# endif +#else +# define CV_FORMAT_PRINTF(A, B) +#endif + +namespace cv +{ +//! @cond IGNORED + + +////////////////////////////// Matx methods depending on core API ///////////////////////////// + +namespace internal +{ + +template struct Matx_FastInvOp +{ + bool operator()(const Matx<_Tp, m, n>& a, Matx<_Tp, n, m>& b, int method) const + { + return invert(a, b, method) != 0; + } +}; + +template struct Matx_FastInvOp<_Tp, m, m> +{ + bool operator()(const Matx<_Tp, m, m>& a, Matx<_Tp, m, m>& b, int method) const + { + if (method == DECOMP_LU || method == DECOMP_CHOLESKY) + { + Matx<_Tp, m, m> temp = a; + + // assume that b is all 0's on input => make it a unity matrix + for (int i = 0; i < m; i++) + b(i, i) = (_Tp)1; + + if (method == DECOMP_CHOLESKY) + return Cholesky(temp.val, m*sizeof(_Tp), m, b.val, m*sizeof(_Tp), m); + + return LU(temp.val, m*sizeof(_Tp), m, b.val, m*sizeof(_Tp), m) != 0; + } + else + { + return invert(a, b, method) != 0; + } + } +}; + +template struct Matx_FastInvOp<_Tp, 2, 2> +{ + bool operator()(const Matx<_Tp, 2, 2>& a, Matx<_Tp, 2, 2>& b, int /*method*/) const + { + _Tp d = (_Tp)determinant(a); + if (d == 0) + return false; + d = 1/d; + b(1,1) = a(0,0)*d; + b(0,0) = a(1,1)*d; + b(0,1) = -a(0,1)*d; + b(1,0) = -a(1,0)*d; + return true; + } +}; + +template struct Matx_FastInvOp<_Tp, 3, 3> +{ + bool operator()(const Matx<_Tp, 3, 3>& a, Matx<_Tp, 3, 3>& b, int /*method*/) const + { + _Tp d = (_Tp)determinant(a); + if (d == 0) + return false; + d = 1/d; + b(0,0) = (a(1,1) * a(2,2) - a(1,2) * a(2,1)) * d; + b(0,1) = (a(0,2) * a(2,1) - a(0,1) * a(2,2)) * d; + b(0,2) = (a(0,1) * a(1,2) - a(0,2) * a(1,1)) * d; + + b(1,0) = (a(1,2) * a(2,0) - a(1,0) * a(2,2)) * d; + b(1,1) = (a(0,0) * a(2,2) - a(0,2) * a(2,0)) * d; + b(1,2) = (a(0,2) * a(1,0) - a(0,0) * a(1,2)) * d; + + b(2,0) = (a(1,0) * a(2,1) - a(1,1) * a(2,0)) * d; + b(2,1) = (a(0,1) * a(2,0) - a(0,0) * a(2,1)) * d; + b(2,2) = (a(0,0) * a(1,1) - a(0,1) * a(1,0)) * d; + return true; + } +}; + + +template struct Matx_FastSolveOp +{ + bool operator()(const Matx<_Tp, m, l>& a, const Matx<_Tp, m, n>& b, + Matx<_Tp, l, n>& x, int method) const + { + return cv::solve(a, b, x, method); + } +}; + +template struct Matx_FastSolveOp<_Tp, m, m, n> +{ + bool operator()(const Matx<_Tp, m, m>& a, const Matx<_Tp, m, n>& b, + Matx<_Tp, m, n>& x, int method) const + { + if (method == DECOMP_LU || method == DECOMP_CHOLESKY) + { + Matx<_Tp, m, m> temp = a; + x = b; + if( method == DECOMP_CHOLESKY ) + return Cholesky(temp.val, m*sizeof(_Tp), m, x.val, n*sizeof(_Tp), n); + + return LU(temp.val, m*sizeof(_Tp), m, x.val, n*sizeof(_Tp), n) != 0; + } + else + { + return cv::solve(a, b, x, method); + } + } +}; + +template struct Matx_FastSolveOp<_Tp, 2, 2, 1> +{ + bool operator()(const Matx<_Tp, 2, 2>& a, const Matx<_Tp, 2, 1>& b, + Matx<_Tp, 2, 1>& x, int) const + { + _Tp d = (_Tp)determinant(a); + if (d == 0) + return false; + d = 1/d; + x(0) = (b(0)*a(1,1) - b(1)*a(0,1))*d; + x(1) = (b(1)*a(0,0) - b(0)*a(1,0))*d; + return true; + } +}; + +template struct Matx_FastSolveOp<_Tp, 3, 3, 1> +{ + bool operator()(const Matx<_Tp, 3, 3>& a, const Matx<_Tp, 3, 1>& b, + Matx<_Tp, 3, 1>& x, int) const + { + _Tp d = (_Tp)determinant(a); + if (d == 0) + return false; + d = 1/d; + x(0) = d*(b(0)*(a(1,1)*a(2,2) - a(1,2)*a(2,1)) - + a(0,1)*(b(1)*a(2,2) - a(1,2)*b(2)) + + a(0,2)*(b(1)*a(2,1) - a(1,1)*b(2))); + + x(1) = d*(a(0,0)*(b(1)*a(2,2) - a(1,2)*b(2)) - + b(0)*(a(1,0)*a(2,2) - a(1,2)*a(2,0)) + + a(0,2)*(a(1,0)*b(2) - b(1)*a(2,0))); + + x(2) = d*(a(0,0)*(a(1,1)*b(2) - b(1)*a(2,1)) - + a(0,1)*(a(1,0)*b(2) - b(1)*a(2,0)) + + b(0)*(a(1,0)*a(2,1) - a(1,1)*a(2,0))); + return true; + } +}; + +} // internal + +template inline +Matx<_Tp,m,n> Matx<_Tp,m,n>::randu(_Tp a, _Tp b) +{ + Matx<_Tp,m,n> M; + cv::randu(M, Scalar(a), Scalar(b)); + return M; +} + +template inline +Matx<_Tp,m,n> Matx<_Tp,m,n>::randn(_Tp a, _Tp b) +{ + Matx<_Tp,m,n> M; + cv::randn(M, Scalar(a), Scalar(b)); + return M; +} + +template inline +Vec<_Tp, cn> Vec<_Tp, cn>::randu(_Tp a, _Tp b) +{ + Vec<_Tp,cn> V; + cv::randu(V, Scalar(a), Scalar(b)); + return V; +} + +template inline +Vec<_Tp, cn> Vec<_Tp, cn>::randn(_Tp a, _Tp b) +{ + Vec<_Tp,cn> V; + cv::randn(V, Scalar(a), Scalar(b)); + return V; +} + +template inline +Matx<_Tp, n, m> Matx<_Tp, m, n>::inv(int method, bool *p_is_ok /*= NULL*/) const +{ + Matx<_Tp, n, m> b; + bool ok = cv::internal::Matx_FastInvOp<_Tp, m, n>()(*this, b, method); + if (p_is_ok) *p_is_ok = ok; + return ok ? b : Matx<_Tp, n, m>::zeros(); +} + +template template inline +Matx<_Tp, n, l> Matx<_Tp, m, n>::solve(const Matx<_Tp, m, l>& rhs, int method) const +{ + Matx<_Tp, n, l> x; + bool ok = cv::internal::Matx_FastSolveOp<_Tp, m, n, l>()(*this, rhs, x, method); + return ok ? x : Matx<_Tp, n, l>::zeros(); +} + + + +////////////////////////// Augmenting algebraic & logical operations ////////////////////////// + +#define CV_MAT_AUG_OPERATOR1(op, cvop, A, B) \ + static inline A& operator op (A& a, const B& b) { cvop; return a; } + +#define CV_MAT_AUG_OPERATOR(op, cvop, A, B) \ + CV_MAT_AUG_OPERATOR1(op, cvop, A, B) \ + CV_MAT_AUG_OPERATOR1(op, cvop, const A, B) + +#define CV_MAT_AUG_OPERATOR_T(op, cvop, A, B) \ + template CV_MAT_AUG_OPERATOR1(op, cvop, A, B) \ + template CV_MAT_AUG_OPERATOR1(op, cvop, const A, B) + +#define CV_MAT_AUG_OPERATOR_TN(op, cvop, A) \ + template static inline A& operator op (A& a, const Matx<_Tp,m,n>& b) { cvop; return a; } \ + template static inline const A& operator op (const A& a, const Matx<_Tp,m,n>& b) { cvop; return a; } + +CV_MAT_AUG_OPERATOR (+=, cv::add(a, b, (const Mat&)a), Mat, Mat) +CV_MAT_AUG_OPERATOR (+=, cv::add(a, b, (const Mat&)a), Mat, Scalar) +CV_MAT_AUG_OPERATOR_T(+=, cv::add(a, b, (const Mat&)a), Mat_<_Tp>, Mat) +CV_MAT_AUG_OPERATOR_T(+=, cv::add(a, b, (const Mat&)a), Mat_<_Tp>, Scalar) +CV_MAT_AUG_OPERATOR_T(+=, cv::add(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>) +CV_MAT_AUG_OPERATOR_TN(+=, cv::add(a, Mat(b), (const Mat&)a), Mat) +CV_MAT_AUG_OPERATOR_TN(+=, cv::add(a, Mat(b), (const Mat&)a), Mat_<_Tp>) + +CV_MAT_AUG_OPERATOR (-=, cv::subtract(a, b, (const Mat&)a), Mat, Mat) +CV_MAT_AUG_OPERATOR (-=, cv::subtract(a, b, (const Mat&)a), Mat, Scalar) +CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a, b, (const Mat&)a), Mat_<_Tp>, Mat) +CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a, b, (const Mat&)a), Mat_<_Tp>, Scalar) +CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>) +CV_MAT_AUG_OPERATOR_TN(-=, cv::subtract(a, Mat(b), (const Mat&)a), Mat) +CV_MAT_AUG_OPERATOR_TN(-=, cv::subtract(a, Mat(b), (const Mat&)a), Mat_<_Tp>) + +CV_MAT_AUG_OPERATOR (*=, cv::gemm(a, b, 1, Mat(), 0, a, 0), Mat, Mat) +CV_MAT_AUG_OPERATOR_T(*=, cv::gemm(a, b, 1, Mat(), 0, a, 0), Mat_<_Tp>, Mat) +CV_MAT_AUG_OPERATOR_T(*=, cv::gemm(a, b, 1, Mat(), 0, a, 0), Mat_<_Tp>, Mat_<_Tp>) +CV_MAT_AUG_OPERATOR (*=, a.convertTo(a, -1, b), Mat, double) +CV_MAT_AUG_OPERATOR_T(*=, a.convertTo(a, -1, b), Mat_<_Tp>, double) +CV_MAT_AUG_OPERATOR_TN(*=, cv::gemm(a, Mat(b), 1, Mat(), 0, a, 0), Mat) +CV_MAT_AUG_OPERATOR_TN(*=, cv::gemm(a, Mat(b), 1, Mat(), 0, a, 0), Mat_<_Tp>) + +CV_MAT_AUG_OPERATOR (/=, cv::divide(a, b, (const Mat&)a), Mat, Mat) +CV_MAT_AUG_OPERATOR_T(/=, cv::divide(a, b, (const Mat&)a), Mat_<_Tp>, Mat) +CV_MAT_AUG_OPERATOR_T(/=, cv::divide(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>) +CV_MAT_AUG_OPERATOR (/=, a.convertTo((Mat&)a, -1, 1./b), Mat, double) +CV_MAT_AUG_OPERATOR_T(/=, a.convertTo((Mat&)a, -1, 1./b), Mat_<_Tp>, double) +CV_MAT_AUG_OPERATOR_TN(/=, cv::divide(a, Mat(b), (const Mat&)a), Mat) +CV_MAT_AUG_OPERATOR_TN(/=, cv::divide(a, Mat(b), (const Mat&)a), Mat_<_Tp>) + +CV_MAT_AUG_OPERATOR (&=, cv::bitwise_and(a, b, (const Mat&)a), Mat, Mat) +CV_MAT_AUG_OPERATOR (&=, cv::bitwise_and(a, b, (const Mat&)a), Mat, Scalar) +CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a, b, (const Mat&)a), Mat_<_Tp>, Mat) +CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a, b, (const Mat&)a), Mat_<_Tp>, Scalar) +CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>) +CV_MAT_AUG_OPERATOR_TN(&=, cv::bitwise_and(a, Mat(b), (const Mat&)a), Mat) +CV_MAT_AUG_OPERATOR_TN(&=, cv::bitwise_and(a, Mat(b), (const Mat&)a), Mat_<_Tp>) + +CV_MAT_AUG_OPERATOR (|=, cv::bitwise_or(a, b, (const Mat&)a), Mat, Mat) +CV_MAT_AUG_OPERATOR (|=, cv::bitwise_or(a, b, (const Mat&)a), Mat, Scalar) +CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a, b, (const Mat&)a), Mat_<_Tp>, Mat) +CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a, b, (const Mat&)a), Mat_<_Tp>, Scalar) +CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>) +CV_MAT_AUG_OPERATOR_TN(|=, cv::bitwise_or(a, Mat(b), (const Mat&)a), Mat) +CV_MAT_AUG_OPERATOR_TN(|=, cv::bitwise_or(a, Mat(b), (const Mat&)a), Mat_<_Tp>) + +CV_MAT_AUG_OPERATOR (^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat, Mat) +CV_MAT_AUG_OPERATOR (^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat, Scalar) +CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat_<_Tp>, Mat) +CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat_<_Tp>, Scalar) +CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>) +CV_MAT_AUG_OPERATOR_TN(^=, cv::bitwise_xor(a, Mat(b), (const Mat&)a), Mat) +CV_MAT_AUG_OPERATOR_TN(^=, cv::bitwise_xor(a, Mat(b), (const Mat&)a), Mat_<_Tp>) + +#undef CV_MAT_AUG_OPERATOR_TN +#undef CV_MAT_AUG_OPERATOR_T +#undef CV_MAT_AUG_OPERATOR +#undef CV_MAT_AUG_OPERATOR1 + + + +///////////////////////////////////////////// SVD ///////////////////////////////////////////// + +inline SVD::SVD() {} +inline SVD::SVD( InputArray m, int flags ) { operator ()(m, flags); } +inline void SVD::solveZ( InputArray m, OutputArray _dst ) +{ + Mat mtx = m.getMat(); + SVD svd(mtx, (mtx.rows >= mtx.cols ? 0 : SVD::FULL_UV)); + _dst.create(svd.vt.cols, 1, svd.vt.type()); + Mat dst = _dst.getMat(); + svd.vt.row(svd.vt.rows-1).reshape(1,svd.vt.cols).copyTo(dst); +} + +template inline void + SVD::compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt ) +{ + CV_StaticAssert( nm == MIN(m, n), "Invalid size of output vector."); + Mat _a(a, false), _u(u, false), _w(w, false), _vt(vt, false); + SVD::compute(_a, _w, _u, _vt); + CV_Assert(_w.data == (uchar*)&w.val[0] && _u.data == (uchar*)&u.val[0] && _vt.data == (uchar*)&vt.val[0]); +} + +template inline void +SVD::compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w ) +{ + CV_StaticAssert( nm == MIN(m, n), "Invalid size of output vector."); + Mat _a(a, false), _w(w, false); + SVD::compute(_a, _w); + CV_Assert(_w.data == (uchar*)&w.val[0]); +} + +template inline void +SVD::backSubst( const Matx<_Tp, nm, 1>& w, const Matx<_Tp, m, nm>& u, + const Matx<_Tp, n, nm>& vt, const Matx<_Tp, m, nb>& rhs, + Matx<_Tp, n, nb>& dst ) +{ + CV_StaticAssert( nm == MIN(m, n), "Invalid size of output vector."); + Mat _u(u, false), _w(w, false), _vt(vt, false), _rhs(rhs, false), _dst(dst, false); + SVD::backSubst(_w, _u, _vt, _rhs, _dst); + CV_Assert(_dst.data == (uchar*)&dst.val[0]); +} + + + +/////////////////////////////////// Multiply-with-Carry RNG /////////////////////////////////// + +inline RNG::RNG() { state = 0xffffffff; } +inline RNG::RNG(uint64 _state) { state = _state ? _state : 0xffffffff; } + +inline RNG::operator uchar() { return (uchar)next(); } +inline RNG::operator schar() { return (schar)next(); } +inline RNG::operator ushort() { return (ushort)next(); } +inline RNG::operator short() { return (short)next(); } +inline RNG::operator int() { return (int)next(); } +inline RNG::operator unsigned() { return next(); } +inline RNG::operator float() { return next()*2.3283064365386962890625e-10f; } +inline RNG::operator double() { unsigned t = next(); return (((uint64)t << 32) | next()) * 5.4210108624275221700372640043497e-20; } + +inline unsigned RNG::operator ()(unsigned N) { return (unsigned)uniform(0,N); } +inline unsigned RNG::operator ()() { return next(); } + +inline int RNG::uniform(int a, int b) { return a == b ? a : (int)(next() % (b - a) + a); } +inline float RNG::uniform(float a, float b) { return ((float)*this)*(b - a) + a; } +inline double RNG::uniform(double a, double b) { return ((double)*this)*(b - a) + a; } + +inline bool RNG::operator ==(const RNG& other) const { return state == other.state; } + +inline unsigned RNG::next() +{ + state = (uint64)(unsigned)state* /*CV_RNG_COEFF*/ 4164903690U + (unsigned)(state >> 32); + return (unsigned)state; +} + +//! returns the next uniformly-distributed random number of the specified type +template static inline _Tp randu() +{ + return (_Tp)theRNG(); +} + + +///////////////////////////////// Formatted output of cv::Mat ///////////////////////////////// + +static inline +Ptr format(InputArray mtx, Formatter::FormatType fmt) +{ + return Formatter::get(fmt)->format(mtx.getMat()); +} + +static inline +int print(Ptr fmtd, FILE* stream = stdout) +{ + int written = 0; + fmtd->reset(); + for(const char* str = fmtd->next(); str; str = fmtd->next()) + written += fputs(str, stream); + + return written; +} + +static inline +int print(const Mat& mtx, FILE* stream = stdout) +{ + return print(Formatter::get()->format(mtx), stream); +} + +static inline +int print(const UMat& mtx, FILE* stream = stdout) +{ + return print(Formatter::get()->format(mtx.getMat(ACCESS_READ)), stream); +} + +template static inline +int print(const std::vector >& vec, FILE* stream = stdout) +{ + return print(Formatter::get()->format(Mat(vec)), stream); +} + +template static inline +int print(const std::vector >& vec, FILE* stream = stdout) +{ + return print(Formatter::get()->format(Mat(vec)), stream); +} + +template static inline +int print(const Matx<_Tp, m, n>& matx, FILE* stream = stdout) +{ + return print(Formatter::get()->format(cv::Mat(matx)), stream); +} + +//! @endcond + +///////////////////////////////// Formatted string generation ///////////////////////////////// + +/** @brief Returns a text string formatted using the printf-like expression. + +The function acts like sprintf but forms and returns an STL string. It can be used to form an error +message in the Exception constructor. +@param fmt printf-compatible formatting specifiers. + +**Note**: +|Type|Specifier| +|-|-| +|`const char*`|`%s`| +|`char`|`%c`| +|`float` / `double`|`%f`,`%g`| +|`int`, `long`, `long long`|`%d`, `%ld`, ``%lld`| +|`unsigned`, `unsigned long`, `unsigned long long`|`%u`, `%lu`, `%llu`| +|`uint64` -> `uintmax_t`, `int64` -> `intmax_t`|`%ju`, `%jd`| +|`size_t`|`%zu`| +@ingroup core_utils + */ +CV_EXPORTS String format(const char* fmt, ...) CV_FORMAT_PRINTF(1, 2); + +/****************************************************************************************\ +* Auxiliary algorithms * +\****************************************************************************************/ + +/** @brief Splits an element set into equivalency classes. + +The generic function partition implements an \f$O(N^2)\f$ algorithm for splitting a set of \f$N\f$ elements +into one or more equivalency classes, as described in + . The function returns the number of +equivalency classes. +@param vec Set of elements stored as a vector. +@param labels Output vector of labels. It contains as many elements as vec. Each label labels[i] is +a 0-based cluster index of `vec[i]`. +@param predicate Equivalence predicate (pointer to a boolean function of two arguments or an +instance of the class that has the method bool operator()(const _Tp& a, const _Tp& b) ). The +predicate returns true when the elements are certainly in the same class, and returns false if they +may or may not be in the same class. +@ingroup core_cluster +*/ +template int +partition( const std::vector<_Tp>& vec, std::vector& labels, + _EqPredicate predicate=_EqPredicate()) +{ + int i, j, N = (int)vec.size(); + const _Tp* _vec = &vec[0]; + + const int PARENT=0; + const int RANK=1; + + std::vector _nodes(N*2); + int (*nodes)[2] = (int(*)[2])&_nodes[0]; + + // The first O(N) pass: create N single-vertex trees + for(i = 0; i < N; i++) + { + nodes[i][PARENT]=-1; + nodes[i][RANK] = 0; + } + + // The main O(N^2) pass: merge connected components + for( i = 0; i < N; i++ ) + { + int root = i; + + // find root + while( nodes[root][PARENT] >= 0 ) + root = nodes[root][PARENT]; + + for( j = 0; j < N; j++ ) + { + if( i == j || !predicate(_vec[i], _vec[j])) + continue; + int root2 = j; + + while( nodes[root2][PARENT] >= 0 ) + root2 = nodes[root2][PARENT]; + + if( root2 != root ) + { + // unite both trees + int rank = nodes[root][RANK], rank2 = nodes[root2][RANK]; + if( rank > rank2 ) + nodes[root2][PARENT] = root; + else + { + nodes[root][PARENT] = root2; + nodes[root2][RANK] += rank == rank2; + root = root2; + } + CV_Assert( nodes[root][PARENT] < 0 ); + + int k = j, parent; + + // compress the path from node2 to root + while( (parent = nodes[k][PARENT]) >= 0 ) + { + nodes[k][PARENT] = root; + k = parent; + } + + // compress the path from node to root + k = i; + while( (parent = nodes[k][PARENT]) >= 0 ) + { + nodes[k][PARENT] = root; + k = parent; + } + } + } + } + + // Final O(N) pass: enumerate classes + labels.resize(N); + int nclasses = 0; + + for( i = 0; i < N; i++ ) + { + int root = i; + while( nodes[root][PARENT] >= 0 ) + root = nodes[root][PARENT]; + // re-use the rank as the class label + if( nodes[root][RANK] >= 0 ) + nodes[root][RANK] = ~nclasses++; + labels[i] = ~nodes[root][RANK]; + } + + return nclasses; +} + +} // cv + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/optim.hpp b/3rdParty/opencv-4.11.0/opencv2/core/optim.hpp index 59fe978c26..6dfb59e81e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/optim.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/optim.hpp @@ -1,307 +1,307 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 OpenCV Foundation 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. -// -//M*/ - -#ifndef OPENCV_OPTIM_HPP -#define OPENCV_OPTIM_HPP - -#include "opencv2/core.hpp" - -namespace cv -{ - -/** @addtogroup core_optim -The algorithms in this section minimize or maximize function value within specified constraints or -without any constraints. -@{ -*/ - -/** @brief Basic interface for all solvers - */ -class CV_EXPORTS MinProblemSolver : public Algorithm -{ -public: - /** @brief Represents function being optimized - */ - class CV_EXPORTS Function - { - public: - virtual ~Function() {} - virtual int getDims() const = 0; - virtual double getGradientEps() const; - virtual double calc(const double* x) const = 0; - virtual void getGradient(const double* x,double* grad); - }; - - /** @brief Getter for the optimized function. - - The optimized function is represented by Function interface, which requires derivatives to - implement the calc(double*) and getDim() methods to evaluate the function. - - @return Smart-pointer to an object that implements Function interface - it represents the - function that is being optimized. It can be empty, if no function was given so far. - */ - virtual Ptr getFunction() const = 0; - - /** @brief Setter for the optimized function. - - *It should be called at least once before the call to* minimize(), as default value is not usable. - - @param f The new function to optimize. - */ - virtual void setFunction(const Ptr& f) = 0; - - /** @brief Getter for the previously set terminal criteria for this algorithm. - - @return Deep copy of the terminal criteria used at the moment. - */ - virtual TermCriteria getTermCriteria() const = 0; - - /** @brief Set terminal criteria for solver. - - This method *is not necessary* to be called before the first call to minimize(), as the default - value is sensible. - - Algorithm stops when the number of function evaluations done exceeds termcrit.maxCount, when - the function values at the vertices of simplex are within termcrit.epsilon range or simplex - becomes so small that it can enclosed in a box with termcrit.epsilon sides, whatever comes - first. - @param termcrit Terminal criteria to be used, represented as cv::TermCriteria structure. - */ - virtual void setTermCriteria(const TermCriteria& termcrit) = 0; - - /** @brief actually runs the algorithm and performs the minimization. - - The sole input parameter determines the centroid of the starting simplex (roughly, it tells - where to start), all the others (terminal criteria, initial step, function to be minimized) are - supposed to be set via the setters before the call to this method or the default values (not - always sensible) will be used. - - @param x The initial point, that will become a centroid of an initial simplex. After the algorithm - will terminate, it will be set to the point where the algorithm stops, the point of possible - minimum. - @return The value of a function at the point found. - */ - virtual double minimize(InputOutputArray x) = 0; -}; - -/** @brief This class is used to perform the non-linear non-constrained minimization of a function, - -defined on an `n`-dimensional Euclidean space, using the **Nelder-Mead method**, also known as -**downhill simplex method**. The basic idea about the method can be obtained from -. - -It should be noted, that this method, although deterministic, is rather a heuristic and therefore -may converge to a local minima, not necessary a global one. It is iterative optimization technique, -which at each step uses an information about the values of a function evaluated only at `n+1` -points, arranged as a *simplex* in `n`-dimensional space (hence the second name of the method). At -each step new point is chosen to evaluate function at, obtained value is compared with previous -ones and based on this information simplex changes it's shape , slowly moving to the local minimum. -Thus this method is using *only* function values to make decision, on contrary to, say, Nonlinear -Conjugate Gradient method (which is also implemented in optim). - -Algorithm stops when the number of function evaluations done exceeds termcrit.maxCount, when the -function values at the vertices of simplex are within termcrit.epsilon range or simplex becomes so -small that it can enclosed in a box with termcrit.epsilon sides, whatever comes first, for some -defined by user positive integer termcrit.maxCount and positive non-integer termcrit.epsilon. - -@note DownhillSolver is a derivative of the abstract interface -cv::MinProblemSolver, which in turn is derived from the Algorithm interface and is used to -encapsulate the functionality, common to all non-linear optimization algorithms in the optim -module. - -@note term criteria should meet following condition: -@code - termcrit.type == (TermCriteria::MAX_ITER + TermCriteria::EPS) && termcrit.epsilon > 0 && termcrit.maxCount > 0 -@endcode - */ -class CV_EXPORTS DownhillSolver : public MinProblemSolver -{ -public: - /** @brief Returns the initial step that will be used in downhill simplex algorithm. - - @param step Initial step that will be used in algorithm. Note, that although corresponding setter - accepts column-vectors as well as row-vectors, this method will return a row-vector. - @see DownhillSolver::setInitStep - */ - virtual void getInitStep(OutputArray step) const=0; - - /** @brief Sets the initial step that will be used in downhill simplex algorithm. - - Step, together with initial point (given in DownhillSolver::minimize) are two `n`-dimensional - vectors that are used to determine the shape of initial simplex. Roughly said, initial point - determines the position of a simplex (it will become simplex's centroid), while step determines the - spread (size in each dimension) of a simplex. To be more precise, if \f$s,x_0\in\mathbb{R}^n\f$ are - the initial step and initial point respectively, the vertices of a simplex will be: - \f$v_0:=x_0-\frac{1}{2} s\f$ and \f$v_i:=x_0+s_i\f$ for \f$i=1,2,\dots,n\f$ where \f$s_i\f$ denotes - projections of the initial step of *n*-th coordinate (the result of projection is treated to be - vector given by \f$s_i:=e_i\cdot\left\f$, where \f$e_i\f$ form canonical basis) - - @param step Initial step that will be used in algorithm. Roughly said, it determines the spread - (size in each dimension) of an initial simplex. - */ - virtual void setInitStep(InputArray step)=0; - - /** @brief This function returns the reference to the ready-to-use DownhillSolver object. - - All the parameters are optional, so this procedure can be called even without parameters at - all. In this case, the default values will be used. As default value for terminal criteria are - the only sensible ones, MinProblemSolver::setFunction() and DownhillSolver::setInitStep() - should be called upon the obtained object, if the respective parameters were not given to - create(). Otherwise, the two ways (give parameters to createDownhillSolver() or miss them out - and call the MinProblemSolver::setFunction() and DownhillSolver::setInitStep()) are absolutely - equivalent (and will drop the same errors in the same way, should invalid input be detected). - @param f Pointer to the function that will be minimized, similarly to the one you submit via - MinProblemSolver::setFunction. - @param initStep Initial step, that will be used to construct the initial simplex, similarly to the one - you submit via MinProblemSolver::setInitStep. - @param termcrit Terminal criteria to the algorithm, similarly to the one you submit via - MinProblemSolver::setTermCriteria. - */ - static Ptr create(const Ptr& f=Ptr(), - InputArray initStep=Mat_(1,1,0.0), - TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5000,0.000001)); -}; - -/** @brief This class is used to perform the non-linear non-constrained minimization of a function -with known gradient, - -defined on an *n*-dimensional Euclidean space, using the **Nonlinear Conjugate Gradient method**. -The implementation was done based on the beautifully clear explanatory article [An Introduction to -the Conjugate Gradient Method Without the Agonizing -Pain](http://www.cs.cmu.edu/~quake-papers/painless-conjugate-gradient.pdf) by Jonathan Richard -Shewchuk. The method can be seen as an adaptation of a standard Conjugate Gradient method (see, for -example ) for numerically solving the -systems of linear equations. - -It should be noted, that this method, although deterministic, is rather a heuristic method and -therefore may converge to a local minima, not necessary a global one. What is even more disastrous, -most of its behaviour is ruled by gradient, therefore it essentially cannot distinguish between -local minima and maxima. Therefore, if it starts sufficiently near to the local maximum, it may -converge to it. Another obvious restriction is that it should be possible to compute the gradient of -a function at any point, thus it is preferable to have analytic expression for gradient and -computational burden should be born by the user. - -The latter responsibility is accomplished via the getGradient method of a -MinProblemSolver::Function interface (which represents function being optimized). This method takes -point a point in *n*-dimensional space (first argument represents the array of coordinates of that -point) and compute its gradient (it should be stored in the second argument as an array). - -@note class ConjGradSolver thus does not add any new methods to the basic MinProblemSolver interface. - -@note term criteria should meet following condition: -@code - termcrit.type == (TermCriteria::MAX_ITER + TermCriteria::EPS) && termcrit.epsilon > 0 && termcrit.maxCount > 0 - // or - termcrit.type == TermCriteria::MAX_ITER) && termcrit.maxCount > 0 -@endcode - */ -class CV_EXPORTS ConjGradSolver : public MinProblemSolver -{ -public: - /** @brief This function returns the reference to the ready-to-use ConjGradSolver object. - - All the parameters are optional, so this procedure can be called even without parameters at - all. In this case, the default values will be used. As default value for terminal criteria are - the only sensible ones, MinProblemSolver::setFunction() should be called upon the obtained - object, if the function was not given to create(). Otherwise, the two ways (submit it to - create() or miss it out and call the MinProblemSolver::setFunction()) are absolutely equivalent - (and will drop the same errors in the same way, should invalid input be detected). - @param f Pointer to the function that will be minimized, similarly to the one you submit via - MinProblemSolver::setFunction. - @param termcrit Terminal criteria to the algorithm, similarly to the one you submit via - MinProblemSolver::setTermCriteria. - */ - static Ptr create(const Ptr& f=Ptr(), - TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5000,0.000001)); -}; - -//! return codes for cv::solveLP() function -enum SolveLPResult -{ - SOLVELP_LOST = -3, //!< problem is feasible, but solver lost solution due to floating-point arithmetic errors - SOLVELP_UNBOUNDED = -2, //!< problem is unbounded (target function can achieve arbitrary high values) - SOLVELP_UNFEASIBLE = -1, //!< problem is unfeasible (there are no points that satisfy all the constraints imposed) - SOLVELP_SINGLE = 0, //!< there is only one maximum for target function - SOLVELP_MULTI = 1 //!< there are multiple maxima for target function - the arbitrary one is returned -}; - -/** @brief Solve given (non-integer) linear programming problem using the Simplex Algorithm (Simplex Method). - -What we mean here by "linear programming problem" (or LP problem, for short) can be formulated as: - -\f[\mbox{Maximize } c\cdot x\\ - \mbox{Subject to:}\\ - Ax\leq b\\ - x\geq 0\f] - -Where \f$c\f$ is fixed `1`-by-`n` row-vector, \f$A\f$ is fixed `m`-by-`n` matrix, \f$b\f$ is fixed `m`-by-`1` -column vector and \f$x\f$ is an arbitrary `n`-by-`1` column vector, which satisfies the constraints. - -Simplex algorithm is one of many algorithms that are designed to handle this sort of problems -efficiently. Although it is not optimal in theoretical sense (there exist algorithms that can solve -any problem written as above in polynomial time, while simplex method degenerates to exponential -time for some special cases), it is well-studied, easy to implement and is shown to work well for -real-life purposes. - -The particular implementation is taken almost verbatim from **Introduction to Algorithms, third -edition** by T. H. Cormen, C. E. Leiserson, R. L. Rivest and Clifford Stein. In particular, the -Bland's rule is used to prevent cycling. - -@param Func This row-vector corresponds to \f$c\f$ in the LP problem formulation (see above). It should -contain 32- or 64-bit floating point numbers. As a convenience, column-vector may be also submitted, -in the latter case it is understood to correspond to \f$c^T\f$. -@param Constr `m`-by-`n+1` matrix, whose rightmost column corresponds to \f$b\f$ in formulation above -and the remaining to \f$A\f$. It should contain 32- or 64-bit floating point numbers. -@param z The solution will be returned here as a column-vector - it corresponds to \f$c\f$ in the -formulation above. It will contain 64-bit floating point numbers. -@param constr_eps allowed numeric disparity for constraints -@return One of cv::SolveLPResult - */ -CV_EXPORTS_W int solveLP(InputArray Func, InputArray Constr, OutputArray z, double constr_eps); - -/** @overload */ -CV_EXPORTS_W int solveLP(InputArray Func, InputArray Constr, OutputArray z); - -//! @} - -}// cv - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 OpenCV Foundation 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. +// +//M*/ + +#ifndef OPENCV_OPTIM_HPP +#define OPENCV_OPTIM_HPP + +#include "opencv2/core.hpp" + +namespace cv +{ + +/** @addtogroup core_optim +The algorithms in this section minimize or maximize function value within specified constraints or +without any constraints. +@{ +*/ + +/** @brief Basic interface for all solvers + */ +class CV_EXPORTS MinProblemSolver : public Algorithm +{ +public: + /** @brief Represents function being optimized + */ + class CV_EXPORTS Function + { + public: + virtual ~Function() {} + virtual int getDims() const = 0; + virtual double getGradientEps() const; + virtual double calc(const double* x) const = 0; + virtual void getGradient(const double* x,double* grad); + }; + + /** @brief Getter for the optimized function. + + The optimized function is represented by Function interface, which requires derivatives to + implement the calc(double*) and getDim() methods to evaluate the function. + + @return Smart-pointer to an object that implements Function interface - it represents the + function that is being optimized. It can be empty, if no function was given so far. + */ + virtual Ptr getFunction() const = 0; + + /** @brief Setter for the optimized function. + + *It should be called at least once before the call to* minimize(), as default value is not usable. + + @param f The new function to optimize. + */ + virtual void setFunction(const Ptr& f) = 0; + + /** @brief Getter for the previously set terminal criteria for this algorithm. + + @return Deep copy of the terminal criteria used at the moment. + */ + virtual TermCriteria getTermCriteria() const = 0; + + /** @brief Set terminal criteria for solver. + + This method *is not necessary* to be called before the first call to minimize(), as the default + value is sensible. + + Algorithm stops when the number of function evaluations done exceeds termcrit.maxCount, when + the function values at the vertices of simplex are within termcrit.epsilon range or simplex + becomes so small that it can enclosed in a box with termcrit.epsilon sides, whatever comes + first. + @param termcrit Terminal criteria to be used, represented as cv::TermCriteria structure. + */ + virtual void setTermCriteria(const TermCriteria& termcrit) = 0; + + /** @brief actually runs the algorithm and performs the minimization. + + The sole input parameter determines the centroid of the starting simplex (roughly, it tells + where to start), all the others (terminal criteria, initial step, function to be minimized) are + supposed to be set via the setters before the call to this method or the default values (not + always sensible) will be used. + + @param x The initial point, that will become a centroid of an initial simplex. After the algorithm + will terminate, it will be set to the point where the algorithm stops, the point of possible + minimum. + @return The value of a function at the point found. + */ + virtual double minimize(InputOutputArray x) = 0; +}; + +/** @brief This class is used to perform the non-linear non-constrained minimization of a function, + +defined on an `n`-dimensional Euclidean space, using the **Nelder-Mead method**, also known as +**downhill simplex method**. The basic idea about the method can be obtained from +. + +It should be noted, that this method, although deterministic, is rather a heuristic and therefore +may converge to a local minima, not necessary a global one. It is iterative optimization technique, +which at each step uses an information about the values of a function evaluated only at `n+1` +points, arranged as a *simplex* in `n`-dimensional space (hence the second name of the method). At +each step new point is chosen to evaluate function at, obtained value is compared with previous +ones and based on this information simplex changes it's shape , slowly moving to the local minimum. +Thus this method is using *only* function values to make decision, on contrary to, say, Nonlinear +Conjugate Gradient method (which is also implemented in optim). + +Algorithm stops when the number of function evaluations done exceeds termcrit.maxCount, when the +function values at the vertices of simplex are within termcrit.epsilon range or simplex becomes so +small that it can enclosed in a box with termcrit.epsilon sides, whatever comes first, for some +defined by user positive integer termcrit.maxCount and positive non-integer termcrit.epsilon. + +@note DownhillSolver is a derivative of the abstract interface +cv::MinProblemSolver, which in turn is derived from the Algorithm interface and is used to +encapsulate the functionality, common to all non-linear optimization algorithms in the optim +module. + +@note term criteria should meet following condition: +@code + termcrit.type == (TermCriteria::MAX_ITER + TermCriteria::EPS) && termcrit.epsilon > 0 && termcrit.maxCount > 0 +@endcode + */ +class CV_EXPORTS DownhillSolver : public MinProblemSolver +{ +public: + /** @brief Returns the initial step that will be used in downhill simplex algorithm. + + @param step Initial step that will be used in algorithm. Note, that although corresponding setter + accepts column-vectors as well as row-vectors, this method will return a row-vector. + @see DownhillSolver::setInitStep + */ + virtual void getInitStep(OutputArray step) const=0; + + /** @brief Sets the initial step that will be used in downhill simplex algorithm. + + Step, together with initial point (given in DownhillSolver::minimize) are two `n`-dimensional + vectors that are used to determine the shape of initial simplex. Roughly said, initial point + determines the position of a simplex (it will become simplex's centroid), while step determines the + spread (size in each dimension) of a simplex. To be more precise, if \f$s,x_0\in\mathbb{R}^n\f$ are + the initial step and initial point respectively, the vertices of a simplex will be: + \f$v_0:=x_0-\frac{1}{2} s\f$ and \f$v_i:=x_0+s_i\f$ for \f$i=1,2,\dots,n\f$ where \f$s_i\f$ denotes + projections of the initial step of *n*-th coordinate (the result of projection is treated to be + vector given by \f$s_i:=e_i\cdot\left\f$, where \f$e_i\f$ form canonical basis) + + @param step Initial step that will be used in algorithm. Roughly said, it determines the spread + (size in each dimension) of an initial simplex. + */ + virtual void setInitStep(InputArray step)=0; + + /** @brief This function returns the reference to the ready-to-use DownhillSolver object. + + All the parameters are optional, so this procedure can be called even without parameters at + all. In this case, the default values will be used. As default value for terminal criteria are + the only sensible ones, MinProblemSolver::setFunction() and DownhillSolver::setInitStep() + should be called upon the obtained object, if the respective parameters were not given to + create(). Otherwise, the two ways (give parameters to createDownhillSolver() or miss them out + and call the MinProblemSolver::setFunction() and DownhillSolver::setInitStep()) are absolutely + equivalent (and will drop the same errors in the same way, should invalid input be detected). + @param f Pointer to the function that will be minimized, similarly to the one you submit via + MinProblemSolver::setFunction. + @param initStep Initial step, that will be used to construct the initial simplex, similarly to the one + you submit via MinProblemSolver::setInitStep. + @param termcrit Terminal criteria to the algorithm, similarly to the one you submit via + MinProblemSolver::setTermCriteria. + */ + static Ptr create(const Ptr& f=Ptr(), + InputArray initStep=Mat_(1,1,0.0), + TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5000,0.000001)); +}; + +/** @brief This class is used to perform the non-linear non-constrained minimization of a function +with known gradient, + +defined on an *n*-dimensional Euclidean space, using the **Nonlinear Conjugate Gradient method**. +The implementation was done based on the beautifully clear explanatory article [An Introduction to +the Conjugate Gradient Method Without the Agonizing +Pain](http://www.cs.cmu.edu/~quake-papers/painless-conjugate-gradient.pdf) by Jonathan Richard +Shewchuk. The method can be seen as an adaptation of a standard Conjugate Gradient method (see, for +example ) for numerically solving the +systems of linear equations. + +It should be noted, that this method, although deterministic, is rather a heuristic method and +therefore may converge to a local minima, not necessary a global one. What is even more disastrous, +most of its behaviour is ruled by gradient, therefore it essentially cannot distinguish between +local minima and maxima. Therefore, if it starts sufficiently near to the local maximum, it may +converge to it. Another obvious restriction is that it should be possible to compute the gradient of +a function at any point, thus it is preferable to have analytic expression for gradient and +computational burden should be born by the user. + +The latter responsibility is accomplished via the getGradient method of a +MinProblemSolver::Function interface (which represents function being optimized). This method takes +point a point in *n*-dimensional space (first argument represents the array of coordinates of that +point) and compute its gradient (it should be stored in the second argument as an array). + +@note class ConjGradSolver thus does not add any new methods to the basic MinProblemSolver interface. + +@note term criteria should meet following condition: +@code + termcrit.type == (TermCriteria::MAX_ITER + TermCriteria::EPS) && termcrit.epsilon > 0 && termcrit.maxCount > 0 + // or + termcrit.type == TermCriteria::MAX_ITER) && termcrit.maxCount > 0 +@endcode + */ +class CV_EXPORTS ConjGradSolver : public MinProblemSolver +{ +public: + /** @brief This function returns the reference to the ready-to-use ConjGradSolver object. + + All the parameters are optional, so this procedure can be called even without parameters at + all. In this case, the default values will be used. As default value for terminal criteria are + the only sensible ones, MinProblemSolver::setFunction() should be called upon the obtained + object, if the function was not given to create(). Otherwise, the two ways (submit it to + create() or miss it out and call the MinProblemSolver::setFunction()) are absolutely equivalent + (and will drop the same errors in the same way, should invalid input be detected). + @param f Pointer to the function that will be minimized, similarly to the one you submit via + MinProblemSolver::setFunction. + @param termcrit Terminal criteria to the algorithm, similarly to the one you submit via + MinProblemSolver::setTermCriteria. + */ + static Ptr create(const Ptr& f=Ptr(), + TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5000,0.000001)); +}; + +//! return codes for cv::solveLP() function +enum SolveLPResult +{ + SOLVELP_LOST = -3, //!< problem is feasible, but solver lost solution due to floating-point arithmetic errors + SOLVELP_UNBOUNDED = -2, //!< problem is unbounded (target function can achieve arbitrary high values) + SOLVELP_UNFEASIBLE = -1, //!< problem is unfeasible (there are no points that satisfy all the constraints imposed) + SOLVELP_SINGLE = 0, //!< there is only one maximum for target function + SOLVELP_MULTI = 1 //!< there are multiple maxima for target function - the arbitrary one is returned +}; + +/** @brief Solve given (non-integer) linear programming problem using the Simplex Algorithm (Simplex Method). + +What we mean here by "linear programming problem" (or LP problem, for short) can be formulated as: + +\f[\mbox{Maximize } c\cdot x\\ + \mbox{Subject to:}\\ + Ax\leq b\\ + x\geq 0\f] + +Where \f$c\f$ is fixed `1`-by-`n` row-vector, \f$A\f$ is fixed `m`-by-`n` matrix, \f$b\f$ is fixed `m`-by-`1` +column vector and \f$x\f$ is an arbitrary `n`-by-`1` column vector, which satisfies the constraints. + +Simplex algorithm is one of many algorithms that are designed to handle this sort of problems +efficiently. Although it is not optimal in theoretical sense (there exist algorithms that can solve +any problem written as above in polynomial time, while simplex method degenerates to exponential +time for some special cases), it is well-studied, easy to implement and is shown to work well for +real-life purposes. + +The particular implementation is taken almost verbatim from **Introduction to Algorithms, third +edition** by T. H. Cormen, C. E. Leiserson, R. L. Rivest and Clifford Stein. In particular, the +Bland's rule is used to prevent cycling. + +@param Func This row-vector corresponds to \f$c\f$ in the LP problem formulation (see above). It should +contain 32- or 64-bit floating point numbers. As a convenience, column-vector may be also submitted, +in the latter case it is understood to correspond to \f$c^T\f$. +@param Constr `m`-by-`n+1` matrix, whose rightmost column corresponds to \f$b\f$ in formulation above +and the remaining to \f$A\f$. It should contain 32- or 64-bit floating point numbers. +@param z The solution will be returned here as a column-vector - it corresponds to \f$c\f$ in the +formulation above. It will contain 64-bit floating point numbers. +@param constr_eps allowed numeric disparity for constraints +@return One of cv::SolveLPResult + */ +CV_EXPORTS_W int solveLP(InputArray Func, InputArray Constr, OutputArray z, double constr_eps); + +/** @overload */ +CV_EXPORTS_W int solveLP(InputArray Func, InputArray Constr, OutputArray z); + +//! @} + +}// cv + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/ovx.hpp b/3rdParty/opencv-4.11.0/opencv2/core/ovx.hpp index 8bb7d54911..ba7a59ed53 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/ovx.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/ovx.hpp @@ -1,28 +1,28 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -// Copyright (C) 2016, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. - -// OpenVX related definitions and declarations - -#pragma once -#ifndef OPENCV_OVX_HPP -#define OPENCV_OVX_HPP - -#include "cvdef.h" - -namespace cv -{ -/// Check if use of OpenVX is possible -CV_EXPORTS_W bool haveOpenVX(); - -/// Check if use of OpenVX is enabled -CV_EXPORTS_W bool useOpenVX(); - -/// Enable/disable use of OpenVX -CV_EXPORTS_W void setUseOpenVX(bool flag); -} // namespace cv - -#endif // OPENCV_OVX_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +// Copyright (C) 2016, Intel Corporation, all rights reserved. +// Third party copyrights are property of their respective owners. + +// OpenVX related definitions and declarations + +#pragma once +#ifndef OPENCV_OVX_HPP +#define OPENCV_OVX_HPP + +#include "cvdef.h" + +namespace cv +{ +/// Check if use of OpenVX is possible +CV_EXPORTS_W bool haveOpenVX(); + +/// Check if use of OpenVX is enabled +CV_EXPORTS_W bool useOpenVX(); + +/// Enable/disable use of OpenVX +CV_EXPORTS_W void setUseOpenVX(bool flag); +} // namespace cv + +#endif // OPENCV_OVX_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/parallel/backend/parallel_for.openmp.hpp b/3rdParty/opencv-4.11.0/opencv2/core/parallel/backend/parallel_for.openmp.hpp index b172cac34d..95667e8bd6 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/parallel/backend/parallel_for.openmp.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/parallel/backend/parallel_for.openmp.hpp @@ -1,72 +1,72 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_PARALLEL_FOR_OPENMP_HPP -#define OPENCV_CORE_PARALLEL_FOR_OPENMP_HPP - -#include "opencv2/core/parallel/parallel_backend.hpp" - -#if !defined(_OPENMP) && !defined(OPENCV_SKIP_OPENMP_PRESENSE_CHECK) -#error "This file must be compiled with enabled OpenMP" -#endif - -#include - -namespace cv { namespace parallel { namespace openmp { - -/** OpenMP parallel_for API implementation - * - * @sa setParallelForBackend - * @ingroup core_parallel_backend - */ -class ParallelForBackend : public ParallelForAPI -{ -protected: - int numThreads; - int numThreadsMax; -public: - ParallelForBackend() - { - numThreads = 0; - numThreadsMax = omp_get_max_threads(); - } - - virtual ~ParallelForBackend() {} - - virtual void parallel_for(int tasks, FN_parallel_for_body_cb_t body_callback, void* callback_data) CV_OVERRIDE - { -#pragma omp parallel for schedule(dynamic) num_threads(numThreads > 0 ? numThreads : numThreadsMax) - for (int i = 0; i < tasks; ++i) - body_callback(i, i + 1, callback_data); - } - - virtual int getThreadNum() const CV_OVERRIDE - { - return omp_get_thread_num(); - } - - virtual int getNumThreads() const CV_OVERRIDE - { - return numThreads > 0 - ? numThreads - : numThreadsMax; - } - - virtual int setNumThreads(int nThreads) CV_OVERRIDE - { - int oldNumThreads = numThreads; - numThreads = nThreads; - // nothing needed as numThreads is used in #pragma omp parallel for directly - return oldNumThreads; - } - - const char* getName() const CV_OVERRIDE - { - return "openmp"; - } -}; - -}}} // namespace - -#endif // OPENCV_CORE_PARALLEL_FOR_OPENMP_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_PARALLEL_FOR_OPENMP_HPP +#define OPENCV_CORE_PARALLEL_FOR_OPENMP_HPP + +#include "opencv2/core/parallel/parallel_backend.hpp" + +#if !defined(_OPENMP) && !defined(OPENCV_SKIP_OPENMP_PRESENSE_CHECK) +#error "This file must be compiled with enabled OpenMP" +#endif + +#include + +namespace cv { namespace parallel { namespace openmp { + +/** OpenMP parallel_for API implementation + * + * @sa setParallelForBackend + * @ingroup core_parallel_backend + */ +class ParallelForBackend : public ParallelForAPI +{ +protected: + int numThreads; + int numThreadsMax; +public: + ParallelForBackend() + { + numThreads = 0; + numThreadsMax = omp_get_max_threads(); + } + + virtual ~ParallelForBackend() {} + + virtual void parallel_for(int tasks, FN_parallel_for_body_cb_t body_callback, void* callback_data) CV_OVERRIDE + { +#pragma omp parallel for schedule(dynamic) num_threads(numThreads > 0 ? numThreads : numThreadsMax) + for (int i = 0; i < tasks; ++i) + body_callback(i, i + 1, callback_data); + } + + virtual int getThreadNum() const CV_OVERRIDE + { + return omp_get_thread_num(); + } + + virtual int getNumThreads() const CV_OVERRIDE + { + return numThreads > 0 + ? numThreads + : numThreadsMax; + } + + virtual int setNumThreads(int nThreads) CV_OVERRIDE + { + int oldNumThreads = numThreads; + numThreads = nThreads; + // nothing needed as numThreads is used in #pragma omp parallel for directly + return oldNumThreads; + } + + const char* getName() const CV_OVERRIDE + { + return "openmp"; + } +}; + +}}} // namespace + +#endif // OPENCV_CORE_PARALLEL_FOR_OPENMP_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/parallel/backend/parallel_for.tbb.hpp b/3rdParty/opencv-4.11.0/opencv2/core/parallel/backend/parallel_for.tbb.hpp index 04b0c4c6cb..8dce454649 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/parallel/backend/parallel_for.tbb.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/parallel/backend/parallel_for.tbb.hpp @@ -1,153 +1,153 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_PARALLEL_FOR_TBB_HPP -#define OPENCV_CORE_PARALLEL_FOR_TBB_HPP - -#include "opencv2/core/parallel/parallel_backend.hpp" -#include - -#ifndef TBB_SUPPRESS_DEPRECATED_MESSAGES // supress warning -#define TBB_SUPPRESS_DEPRECATED_MESSAGES 1 -#endif -#include "tbb/tbb.h" -#if !defined(TBB_INTERFACE_VERSION) -#error "Unknows/unsupported TBB version" -#endif - -#if TBB_INTERFACE_VERSION >= 8000 -#include "tbb/task_arena.h" -#endif - -namespace cv { namespace parallel { namespace tbb { - -using namespace ::tbb; - -#if TBB_INTERFACE_VERSION >= 8000 -static tbb::task_arena& getArena() -{ - static tbb::task_arena tbbArena(tbb::task_arena::automatic); - return tbbArena; -} -#else -static tbb::task_scheduler_init& getScheduler() -{ - static tbb::task_scheduler_init tbbScheduler(tbb::task_scheduler_init::deferred); - return tbbScheduler; -} -#endif - -/** TBB parallel_for API implementation - * - * @sa setParallelForBackend - * @ingroup core_parallel_backend - */ -class ParallelForBackend : public ParallelForAPI -{ -protected: - int numThreads; - int numThreadsMax; -public: - ParallelForBackend() - { - CV_LOG_INFO(NULL, "Initializing TBB parallel backend: TBB_INTERFACE_VERSION=" << TBB_INTERFACE_VERSION); - numThreads = 0; -#if TBB_INTERFACE_VERSION >= 8000 - (void)getArena(); -#else - (void)getScheduler(); -#endif - } - - virtual ~ParallelForBackend() {} - - class CallbackProxy - { - const FN_parallel_for_body_cb_t& callback; - void* const callback_data; - const int tasks; - public: - inline CallbackProxy(int tasks_, FN_parallel_for_body_cb_t& callback_, void* callback_data_) - : callback(callback_), callback_data(callback_data_), tasks(tasks_) - { - // nothing - } - - void operator()(const tbb::blocked_range& range) const - { - this->callback(range.begin(), range.end(), callback_data); - } - - void operator()() const - { - tbb::parallel_for(tbb::blocked_range(0, tasks), *this); - } - }; - - virtual void parallel_for(int tasks, FN_parallel_for_body_cb_t body_callback, void* callback_data) CV_OVERRIDE - { - CallbackProxy task(tasks, body_callback, callback_data); -#if TBB_INTERFACE_VERSION >= 8000 - getArena().execute(task); -#else - task(); -#endif - } - - virtual int getThreadNum() const CV_OVERRIDE - { -#if TBB_INTERFACE_VERSION >= 9100 - return tbb::this_task_arena::current_thread_index(); -#elif TBB_INTERFACE_VERSION >= 8000 - return tbb::task_arena::current_thread_index(); -#else - return 0; -#endif - } - - virtual int getNumThreads() const CV_OVERRIDE - { -#if TBB_INTERFACE_VERSION >= 9100 - return getArena().max_concurrency(); -#elif TBB_INTERFACE_VERSION >= 8000 - return numThreads > 0 - ? numThreads - : tbb::task_scheduler_init::default_num_threads(); -#else - return getScheduler().is_active() - ? numThreads - : tbb::task_scheduler_init::default_num_threads(); -#endif - } - - virtual int setNumThreads(int nThreads) CV_OVERRIDE - { - int oldNumThreads = numThreads; - numThreads = nThreads; - -#if TBB_INTERFACE_VERSION >= 8000 - auto& tbbArena = getArena(); - if (tbbArena.is_active()) - tbbArena.terminate(); - if (numThreads > 0) - tbbArena.initialize(numThreads); -#else - auto& tbbScheduler = getScheduler(); - if (tbbScheduler.is_active()) - tbbScheduler.terminate(); - if (numThreads > 0) - tbbScheduler.initialize(numThreads); -#endif - return oldNumThreads; - } - - const char* getName() const CV_OVERRIDE - { - return "tbb"; - } -}; - -}}} // namespace - -#endif // OPENCV_CORE_PARALLEL_FOR_TBB_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_PARALLEL_FOR_TBB_HPP +#define OPENCV_CORE_PARALLEL_FOR_TBB_HPP + +#include "opencv2/core/parallel/parallel_backend.hpp" +#include + +#ifndef TBB_SUPPRESS_DEPRECATED_MESSAGES // supress warning +#define TBB_SUPPRESS_DEPRECATED_MESSAGES 1 +#endif +#include "tbb/tbb.h" +#if !defined(TBB_INTERFACE_VERSION) +#error "Unknows/unsupported TBB version" +#endif + +#if TBB_INTERFACE_VERSION >= 8000 +#include "tbb/task_arena.h" +#endif + +namespace cv { namespace parallel { namespace tbb { + +using namespace ::tbb; + +#if TBB_INTERFACE_VERSION >= 8000 +static tbb::task_arena& getArena() +{ + static tbb::task_arena tbbArena(tbb::task_arena::automatic); + return tbbArena; +} +#else +static tbb::task_scheduler_init& getScheduler() +{ + static tbb::task_scheduler_init tbbScheduler(tbb::task_scheduler_init::deferred); + return tbbScheduler; +} +#endif + +/** TBB parallel_for API implementation + * + * @sa setParallelForBackend + * @ingroup core_parallel_backend + */ +class ParallelForBackend : public ParallelForAPI +{ +protected: + int numThreads; + int numThreadsMax; +public: + ParallelForBackend() + { + CV_LOG_INFO(NULL, "Initializing TBB parallel backend: TBB_INTERFACE_VERSION=" << TBB_INTERFACE_VERSION); + numThreads = 0; +#if TBB_INTERFACE_VERSION >= 8000 + (void)getArena(); +#else + (void)getScheduler(); +#endif + } + + virtual ~ParallelForBackend() {} + + class CallbackProxy + { + const FN_parallel_for_body_cb_t& callback; + void* const callback_data; + const int tasks; + public: + inline CallbackProxy(int tasks_, FN_parallel_for_body_cb_t& callback_, void* callback_data_) + : callback(callback_), callback_data(callback_data_), tasks(tasks_) + { + // nothing + } + + void operator()(const tbb::blocked_range& range) const + { + this->callback(range.begin(), range.end(), callback_data); + } + + void operator()() const + { + tbb::parallel_for(tbb::blocked_range(0, tasks), *this); + } + }; + + virtual void parallel_for(int tasks, FN_parallel_for_body_cb_t body_callback, void* callback_data) CV_OVERRIDE + { + CallbackProxy task(tasks, body_callback, callback_data); +#if TBB_INTERFACE_VERSION >= 8000 + getArena().execute(task); +#else + task(); +#endif + } + + virtual int getThreadNum() const CV_OVERRIDE + { +#if TBB_INTERFACE_VERSION >= 9100 + return tbb::this_task_arena::current_thread_index(); +#elif TBB_INTERFACE_VERSION >= 8000 + return tbb::task_arena::current_thread_index(); +#else + return 0; +#endif + } + + virtual int getNumThreads() const CV_OVERRIDE + { +#if TBB_INTERFACE_VERSION >= 9100 + return getArena().max_concurrency(); +#elif TBB_INTERFACE_VERSION >= 8000 + return numThreads > 0 + ? numThreads + : tbb::task_scheduler_init::default_num_threads(); +#else + return getScheduler().is_active() + ? numThreads + : tbb::task_scheduler_init::default_num_threads(); +#endif + } + + virtual int setNumThreads(int nThreads) CV_OVERRIDE + { + int oldNumThreads = numThreads; + numThreads = nThreads; + +#if TBB_INTERFACE_VERSION >= 8000 + auto& tbbArena = getArena(); + if (tbbArena.is_active()) + tbbArena.terminate(); + if (numThreads > 0) + tbbArena.initialize(numThreads); +#else + auto& tbbScheduler = getScheduler(); + if (tbbScheduler.is_active()) + tbbScheduler.terminate(); + if (numThreads > 0) + tbbScheduler.initialize(numThreads); +#endif + return oldNumThreads; + } + + const char* getName() const CV_OVERRIDE + { + return "tbb"; + } +}; + +}}} // namespace + +#endif // OPENCV_CORE_PARALLEL_FOR_TBB_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/parallel/parallel_backend.hpp b/3rdParty/opencv-4.11.0/opencv2/core/parallel/parallel_backend.hpp index c3e8333c1c..37501e1eed 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/parallel/parallel_backend.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/parallel/parallel_backend.hpp @@ -1,90 +1,90 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_PARALLEL_BACKEND_HPP -#define OPENCV_CORE_PARALLEL_BACKEND_HPP - -#include "opencv2/core/cvdef.h" -#include - -namespace cv { namespace parallel { -#ifndef CV_API_CALL -#define CV_API_CALL -#endif - -/** @addtogroup core_parallel_backend - * @{ - * API below is provided to resolve problem of CPU resource over-subscription by multiple thread pools from different multi-threading frameworks. - * This is common problem for cases when OpenCV compiled threading framework is different from the Users Applications framework. - * - * Applications can replace OpenCV `parallel_for()` backend with own implementation (to reuse Application's thread pool). - * - * - * ### Backend API usage examples - * - * #### Intel TBB - * - * - include header with simple implementation of TBB backend: - * @snippet parallel_backend/example-tbb.cpp tbb_include - * - execute backend replacement code: - * @snippet parallel_backend/example-tbb.cpp tbb_backend - * - configuration of compiler/linker options is responsibility of Application's scripts - * - * #### OpenMP - * - * - include header with simple implementation of OpenMP backend: - * @snippet parallel_backend/example-openmp.cpp openmp_include - * - execute backend replacement code: - * @snippet parallel_backend/example-openmp.cpp openmp_backend - * - Configuration of compiler/linker options is responsibility of Application's scripts - * - * - * ### Plugins support - * - * Runtime configuration options: - * - change backend priority: `OPENCV_PARALLEL_PRIORITY_=9999` - * - disable backend: `OPENCV_PARALLEL_PRIORITY_=0` - * - specify list of backends with high priority (>100000): `OPENCV_PARALLEL_PRIORITY_LIST=TBB,OPENMP`. Unknown backends are registered as new plugins. - * - */ - -/** Interface for parallel_for backends implementations - * - * @sa setParallelForBackend - */ -class CV_EXPORTS ParallelForAPI -{ -public: - virtual ~ParallelForAPI(); - - typedef void (CV_API_CALL *FN_parallel_for_body_cb_t)(int start, int end, void* data); - - virtual void parallel_for(int tasks, FN_parallel_for_body_cb_t body_callback, void* callback_data) = 0; - - virtual int getThreadNum() const = 0; - - virtual int getNumThreads() const = 0; - - virtual int setNumThreads(int nThreads) = 0; - - virtual const char* getName() const = 0; -}; - -/** @brief Replace OpenCV parallel_for backend - * - * Application can replace OpenCV `parallel_for()` backend with own implementation. - * - * @note This call is not thread-safe. Consider calling this function from the `main()` before any other OpenCV processing functions (and without any other created threads). - */ -CV_EXPORTS void setParallelForBackend(const std::shared_ptr& api, bool propagateNumThreads = true); - -/** @brief Change OpenCV parallel_for backend - * - * @note This call is not thread-safe. Consider calling this function from the `main()` before any other OpenCV processing functions (and without any other created threads). - */ -CV_EXPORTS_W bool setParallelForBackend(const std::string& backendName, bool propagateNumThreads = true); - -//! @} -}} // namespace -#endif // OPENCV_CORE_PARALLEL_BACKEND_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_PARALLEL_BACKEND_HPP +#define OPENCV_CORE_PARALLEL_BACKEND_HPP + +#include "opencv2/core/cvdef.h" +#include + +namespace cv { namespace parallel { +#ifndef CV_API_CALL +#define CV_API_CALL +#endif + +/** @addtogroup core_parallel_backend + * @{ + * API below is provided to resolve problem of CPU resource over-subscription by multiple thread pools from different multi-threading frameworks. + * This is common problem for cases when OpenCV compiled threading framework is different from the Users Applications framework. + * + * Applications can replace OpenCV `parallel_for()` backend with own implementation (to reuse Application's thread pool). + * + * + * ### Backend API usage examples + * + * #### Intel TBB + * + * - include header with simple implementation of TBB backend: + * @snippet parallel_backend/example-tbb.cpp tbb_include + * - execute backend replacement code: + * @snippet parallel_backend/example-tbb.cpp tbb_backend + * - configuration of compiler/linker options is responsibility of Application's scripts + * + * #### OpenMP + * + * - include header with simple implementation of OpenMP backend: + * @snippet parallel_backend/example-openmp.cpp openmp_include + * - execute backend replacement code: + * @snippet parallel_backend/example-openmp.cpp openmp_backend + * - Configuration of compiler/linker options is responsibility of Application's scripts + * + * + * ### Plugins support + * + * Runtime configuration options: + * - change backend priority: `OPENCV_PARALLEL_PRIORITY_=9999` + * - disable backend: `OPENCV_PARALLEL_PRIORITY_=0` + * - specify list of backends with high priority (>100000): `OPENCV_PARALLEL_PRIORITY_LIST=TBB,OPENMP`. Unknown backends are registered as new plugins. + * + */ + +/** Interface for parallel_for backends implementations + * + * @sa setParallelForBackend + */ +class CV_EXPORTS ParallelForAPI +{ +public: + virtual ~ParallelForAPI(); + + typedef void (CV_API_CALL *FN_parallel_for_body_cb_t)(int start, int end, void* data); + + virtual void parallel_for(int tasks, FN_parallel_for_body_cb_t body_callback, void* callback_data) = 0; + + virtual int getThreadNum() const = 0; + + virtual int getNumThreads() const = 0; + + virtual int setNumThreads(int nThreads) = 0; + + virtual const char* getName() const = 0; +}; + +/** @brief Replace OpenCV parallel_for backend + * + * Application can replace OpenCV `parallel_for()` backend with own implementation. + * + * @note This call is not thread-safe. Consider calling this function from the `main()` before any other OpenCV processing functions (and without any other created threads). + */ +CV_EXPORTS void setParallelForBackend(const std::shared_ptr& api, bool propagateNumThreads = true); + +/** @brief Change OpenCV parallel_for backend + * + * @note This call is not thread-safe. Consider calling this function from the `main()` before any other OpenCV processing functions (and without any other created threads). + */ +CV_EXPORTS_W bool setParallelForBackend(const std::string& backendName, bool propagateNumThreads = true); + +//! @} +}} // namespace +#endif // OPENCV_CORE_PARALLEL_BACKEND_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/persistence.hpp b/3rdParty/opencv-4.11.0/opencv2/core/persistence.hpp index c6ddf6f0ca..cac3755aae 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/persistence.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/persistence.hpp @@ -1,1274 +1,1274 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CORE_PERSISTENCE_HPP -#define OPENCV_CORE_PERSISTENCE_HPP - -#ifndef CV_DOXYGEN -/// Define to support persistence legacy formats -#define CV__LEGACY_PERSISTENCE -#endif - -#ifndef __cplusplus -# error persistence.hpp header must be compiled as C++ -#endif - -#include "opencv2/core/types.hpp" -#include "opencv2/core/mat.hpp" - -namespace cv { - -/** @addtogroup core_xml - -XML/YAML/JSON file storages. {#xml_storage} -======================= -Writing to a file storage. --------------------------- -You can store and then restore various OpenCV data structures to/from XML (), -YAML () or JSON () formats. Also, it is possible to store -and load arbitrarily complex data structures, which include OpenCV data structures, as well as -primitive data types (integer and floating-point numbers and text strings) as their elements. - -Use the following procedure to write something to XML, YAML or JSON: --# Create new FileStorage and open it for writing. It can be done with a single call to -FileStorage::FileStorage constructor that takes a filename, or you can use the default constructor -and then call FileStorage::open. Format of the file (XML, YAML or JSON) is determined from the filename -extension (".xml", ".yml"/".yaml" and ".json", respectively) --# Write all the data you want using the streaming operator `<<`, just like in the case of STL -streams. --# Close the file using FileStorage::release. FileStorage destructor also closes the file. - -Here is an example: -@code - #include "opencv2/core.hpp" - #include - - using namespace cv; - - int main(int, char** argv) - { - FileStorage fs("test.yml", FileStorage::WRITE); - - fs << "frameCount" << 5; - time_t rawtime; time(&rawtime); - fs << "calibrationDate" << asctime(localtime(&rawtime)); - Mat cameraMatrix = (Mat_(3,3) << 1000, 0, 320, 0, 1000, 240, 0, 0, 1); - Mat distCoeffs = (Mat_(5,1) << 0.1, 0.01, -0.001, 0, 0); - fs << "cameraMatrix" << cameraMatrix << "distCoeffs" << distCoeffs; - fs << "features" << "["; - for( int i = 0; i < 3; i++ ) - { - int x = rand() % 640; - int y = rand() % 480; - uchar lbp = rand() % 256; - - fs << "{:" << "x" << x << "y" << y << "lbp" << "[:"; - for( int j = 0; j < 8; j++ ) - fs << ((lbp >> j) & 1); - fs << "]" << "}"; - } - fs << "]"; - fs.release(); - return 0; - } -@endcode -The sample above stores to YML an integer, a text string (calibration date), 2 matrices, and a custom -structure "feature", which includes feature coordinates and LBP (local binary pattern) value. Here -is output of the sample: -@code{.yaml} -%YAML:1.0 -frameCount: 5 -calibrationDate: "Fri Jun 17 14:09:29 2011\n" -cameraMatrix: !!opencv-matrix - rows: 3 - cols: 3 - dt: d - data: [ 1000., 0., 320., 0., 1000., 240., 0., 0., 1. ] -distCoeffs: !!opencv-matrix - rows: 5 - cols: 1 - dt: d - data: [ 1.0000000000000001e-01, 1.0000000000000000e-02, - -1.0000000000000000e-03, 0., 0. ] -features: - - { x:167, y:49, lbp:[ 1, 0, 0, 1, 1, 0, 1, 1 ] } - - { x:298, y:130, lbp:[ 0, 0, 0, 1, 0, 0, 1, 1 ] } - - { x:344, y:158, lbp:[ 1, 1, 0, 0, 0, 0, 1, 0 ] } -@endcode - -As an exercise, you can replace ".yml" with ".xml" or ".json" in the sample above and see, how the -corresponding XML file will look like. - -Several things can be noted by looking at the sample code and the output: - -- The produced YAML (and XML/JSON) consists of heterogeneous collections that can be nested. There are - 2 types of collections: named collections (mappings) and unnamed collections (sequences). In mappings - each element has a name and is accessed by name. This is similar to structures and std::map in - C/C++ and dictionaries in Python. In sequences elements do not have names, they are accessed by - indices. This is similar to arrays and std::vector in C/C++ and lists, tuples in Python. - "Heterogeneous" means that elements of each single collection can have different types. - - Top-level collection in YAML/XML/JSON is a mapping. Each matrix is stored as a mapping, and the matrix - elements are stored as a sequence. Then, there is a sequence of features, where each feature is - represented a mapping, and lbp value in a nested sequence. - -- When you write to a mapping (a structure), you write element name followed by its value. When you - write to a sequence, you simply write the elements one by one. OpenCV data structures (such as - cv::Mat) are written in absolutely the same way as simple C data structures - using `<<` - operator. - -- To write a mapping, you first write the special string `{` to the storage, then write the - elements as pairs (`fs << << `) and then write the closing - `}`. - -- To write a sequence, you first write the special string `[`, then write the elements, then - write the closing `]`. - -- In YAML/JSON (but not XML), mappings and sequences can be written in a compact Python-like inline - form. In the sample above matrix elements, as well as each feature, including its lbp value, is - stored in such inline form. To store a mapping/sequence in a compact form, put `:` after the - opening character, e.g. use `{:` instead of `{` and `[:` instead of `[`. When the - data is written to XML, those extra `:` are ignored. - -Reading data from a file storage. ---------------------------------- -To read the previously written XML, YAML or JSON file, do the following: --# Open the file storage using FileStorage::FileStorage constructor or FileStorage::open method. - In the current implementation the whole file is parsed and the whole representation of file - storage is built in memory as a hierarchy of file nodes (see FileNode) - --# Read the data you are interested in. Use FileStorage::operator [], FileNode::operator [] - and/or FileNodeIterator. - --# Close the storage using FileStorage::release. - -Here is how to read the file created by the code sample above: -@code - FileStorage fs2("test.yml", FileStorage::READ); - - // first method: use (type) operator on FileNode. - int frameCount = (int)fs2["frameCount"]; - - String date; - // second method: use FileNode::operator >> - fs2["calibrationDate"] >> date; - - Mat cameraMatrix2, distCoeffs2; - fs2["cameraMatrix"] >> cameraMatrix2; - fs2["distCoeffs"] >> distCoeffs2; - - cout << "frameCount: " << frameCount << endl - << "calibration date: " << date << endl - << "camera matrix: " << cameraMatrix2 << endl - << "distortion coeffs: " << distCoeffs2 << endl; - - FileNode features = fs2["features"]; - FileNodeIterator it = features.begin(), it_end = features.end(); - int idx = 0; - std::vector lbpval; - - // iterate through a sequence using FileNodeIterator - for( ; it != it_end; ++it, idx++ ) - { - cout << "feature #" << idx << ": "; - cout << "x=" << (int)(*it)["x"] << ", y=" << (int)(*it)["y"] << ", lbp: ("; - // you can also easily read numerical arrays using FileNode >> std::vector operator. - (*it)["lbp"] >> lbpval; - for( int i = 0; i < (int)lbpval.size(); i++ ) - cout << " " << (int)lbpval[i]; - cout << ")" << endl; - } - fs2.release(); -@endcode - -Format specification {#format_spec} --------------------- -`([count]{u|c|w|s|i|f|d})`... where the characters correspond to fundamental C++ types: -- `u` 8-bit unsigned number -- `c` 8-bit signed number -- `w` 16-bit unsigned number -- `s` 16-bit signed number -- `i` 32-bit signed number -- `f` single precision floating-point number -- `d` double precision floating-point number -- `r` pointer, 32 lower bits of which are written as a signed integer. The type can be used to - store structures with links between the elements. - -`count` is the optional counter of values of a given type. For example, `2if` means that each array -element is a structure of 2 integers, followed by a single-precision floating-point number. The -equivalent notations of the above specification are `iif`, `2i1f` and so forth. Other examples: `u` -means that the array consists of bytes, and `2d` means the array consists of pairs of doubles. - -@see @ref samples/cpp/tutorial_code/core/file_input_output/file_input_output.cpp -*/ - -//! @{ - -/** @example samples/cpp/tutorial_code/core/file_input_output/file_input_output.cpp -A complete example using the FileStorage interface -Check @ref tutorial_file_input_output_with_xml_yml "the corresponding tutorial" for more details -*/ - -////////////////////////// XML & YAML I/O ////////////////////////// - -class CV_EXPORTS FileNode; -class CV_EXPORTS FileNodeIterator; - -/** @brief XML/YAML/JSON file storage class that encapsulates all the information necessary for writing or -reading data to/from a file. - */ -class CV_EXPORTS_W FileStorage -{ -public: - //! file storage mode - enum Mode - { - READ = 0, //!< value, open the file for reading - WRITE = 1, //!< value, open the file for writing - APPEND = 2, //!< value, open the file for appending - MEMORY = 4, /**< flag, read data from source or write data to the internal buffer (which is - returned by FileStorage::release) */ - FORMAT_MASK = (7<<3), //!< mask for format flags - FORMAT_AUTO = 0, //!< flag, auto format - FORMAT_XML = (1<<3), //!< flag, XML format - FORMAT_YAML = (2<<3), //!< flag, YAML format - FORMAT_JSON = (3<<3), //!< flag, JSON format - - BASE64 = 64, //!< flag, write rawdata in Base64 by default. (consider using WRITE_BASE64) - WRITE_BASE64 = BASE64 | WRITE, //!< flag, enable both WRITE and BASE64 - }; - enum State - { - UNDEFINED = 0, //!< Initial or uninitialized state. - VALUE_EXPECTED = 1, //!< Expecting a value in the current position. - NAME_EXPECTED = 2, //!< Expecting a key/name in the current position. - INSIDE_MAP = 4 //!< Indicates being inside a map (a set of key-value pairs). - }; - - /** @brief The constructors. - - The full constructor opens the file. Alternatively you can use the default constructor and then - call FileStorage::open. - */ - CV_WRAP FileStorage(); - - /** @overload - @copydoc open() - */ - CV_WRAP FileStorage(const String& filename, int flags, const String& encoding=String()); - - //! the destructor. calls release() - virtual ~FileStorage(); - - /** @brief Opens a file. - - See description of parameters in FileStorage::FileStorage. The method calls FileStorage::release - before opening the file. - @param filename Name of the file to open or the text string to read the data from. - Extension of the file (.xml, .yml/.yaml or .json) determines its format (XML, YAML or JSON - respectively). Also you can append .gz to work with compressed files, for example myHugeMatrix.xml.gz. If both - FileStorage::WRITE and FileStorage::MEMORY flags are specified, source is used just to specify - the output file format (e.g. mydata.xml, .yml etc.). A file name can also contain parameters. - You can use this format, "*?base64" (e.g. "file.json?base64" (case sensitive)), as an alternative to - FileStorage::BASE64 flag. - @param flags Mode of operation. One of FileStorage::Mode - @param encoding Encoding of the file. Note that UTF-16 XML encoding is not supported currently and - you should use 8-bit encoding instead of it. - */ - CV_WRAP virtual bool open(const String& filename, int flags, const String& encoding=String()); - - /** @brief Checks whether the file is opened. - - @returns true if the object is associated with the current file and false otherwise. It is a - good practice to call this method after you tried to open a file. - */ - CV_WRAP virtual bool isOpened() const; - - /** @brief Closes the file and releases all the memory buffers. - - Call this method after all I/O operations with the storage are finished. - */ - CV_WRAP virtual void release(); - - /** @brief Closes the file and releases all the memory buffers. - - Call this method after all I/O operations with the storage are finished. If the storage was - opened for writing data and FileStorage::WRITE was specified - */ - CV_WRAP virtual String releaseAndGetString(); - - /** @brief Returns the first element of the top-level mapping. - @returns The first element of the top-level mapping. - */ - CV_WRAP FileNode getFirstTopLevelNode() const; - - /** @brief Returns the top-level mapping - @param streamidx Zero-based index of the stream. In most cases there is only one stream in the file. - However, YAML supports multiple streams and so there can be several. - @returns The top-level mapping. - */ - CV_WRAP FileNode root(int streamidx=0) const; - - /** @brief Returns the specified element of the top-level mapping. - @param nodename Name of the file node. - @returns Node with the given name. - */ - FileNode operator[](const String& nodename) const; - - /** @overload */ - CV_WRAP_AS(getNode) FileNode operator[](const char* nodename) const; - - /** - * @brief Simplified writing API to use with bindings. - * @param name Name of the written object. When writing to sequences (a.k.a. "arrays"), pass an empty string. - * @param val Value of the written object. - */ - CV_WRAP void write(const String& name, int val); - /// @overload - CV_WRAP void write(const String& name, int64_t val); - /// @overload - CV_WRAP void write(const String& name, double val); - /// @overload - CV_WRAP void write(const String& name, const String& val); - /// @overload - CV_WRAP void write(const String& name, const Mat& val); - /// @overload - CV_WRAP void write(const String& name, const std::vector& val); - - /** @brief Writes multiple numbers. - - Writes one or more numbers of the specified format to the currently written structure. Usually it is - more convenient to use operator `<<` instead of this method. - @param fmt Specification of each array element, see @ref format_spec "format specification" - @param vec Pointer to the written array. - @param len Number of the uchar elements to write. - */ - void writeRaw( const String& fmt, const void* vec, size_t len ); - - /** @brief Writes a comment. - - The function writes a comment into file storage. The comments are skipped when the storage is read. - @param comment The written comment, single-line or multi-line - @param append If true, the function tries to put the comment at the end of current line. - Else if the comment is multi-line, or if it does not fit at the end of the current - line, the comment starts a new line. - */ - CV_WRAP void writeComment(const String& comment, bool append = false); - - /** @brief Starts to write a nested structure (sequence or a mapping). - @param name name of the structure. When writing to sequences (a.k.a. "arrays"), pass an empty string. - @param flags type of the structure (FileNode::MAP or FileNode::SEQ (both with optional FileNode::FLOW)). - @param typeName optional name of the type you store. The effect of setting this depends on the storage format. - I.e. if the format has a specification for storing type information, this parameter is used. - */ - CV_WRAP void startWriteStruct(const String& name, int flags, const String& typeName=String()); - - /** @brief Finishes writing nested structure (should pair startWriteStruct()) - */ - CV_WRAP void endWriteStruct(); - - /** @brief Returns the normalized object name for the specified name of a file. - @param filename Name of a file - @returns The normalized object name. - */ - static String getDefaultObjectName(const String& filename); - - /** @brief Returns the current format. - * @returns The current format, see FileStorage::Mode - */ - CV_WRAP int getFormat() const; - - int state; - std::string elname; - - class Impl; - Ptr p; -}; - -/** @brief File Storage Node class. - -The node is used to store each and every element of the file storage opened for reading. When -XML/YAML file is read, it is first parsed and stored in the memory as a hierarchical collection of -nodes. Each node can be a "leaf" that is contain a single number or a string, or be a collection of -other nodes. There can be named collections (mappings) where each element has a name and it is -accessed by a name, and ordered collections (sequences) where elements do not have names but rather -accessed by index. Type of the file node can be determined using FileNode::type method. - -Note that file nodes are only used for navigating file storages opened for reading. When a file -storage is opened for writing, no data is stored in memory after it is written. - */ -class CV_EXPORTS_W_SIMPLE FileNode -{ -public: - //! type of the file storage node - enum - { - NONE = 0, //!< empty node - INT = 1, //!< an integer - REAL = 2, //!< floating-point number - FLOAT = REAL, //!< synonym or REAL - STR = 3, //!< text string in UTF-8 encoding - STRING = STR, //!< synonym for STR - SEQ = 4, //!< sequence - MAP = 5, //!< mapping - TYPE_MASK = 7, - - FLOW = 8, //!< compact representation of a sequence or mapping. Used only by YAML writer - UNIFORM = 8, //!< if set, means that all the collection elements are numbers of the same type (real's or int's). - //!< UNIFORM is used only when reading FileStorage; FLOW is used only when writing. So they share the same bit - EMPTY = 16, //!< empty structure (sequence or mapping) - NAMED = 32 //!< the node has a name (i.e. it is element of a mapping). - }; - /** @brief The constructors. - - These constructors are used to create a default file node, construct it from obsolete structures or - from the another file node. - */ - CV_WRAP FileNode(); - - /** @overload - @param fs Pointer to the file storage structure. - @param blockIdx Index of the memory block where the file node is stored - @param ofs Offset in bytes from the beginning of the serialized storage - - @deprecated - */ - FileNode(const FileStorage* fs, size_t blockIdx, size_t ofs); - - /** @overload - @param node File node to be used as initialization for the created file node. - */ - FileNode(const FileNode& node); - - FileNode& operator=(const FileNode& node); - - /** @brief Returns element of a mapping node or a sequence node. - @param nodename Name of an element in the mapping node. - @returns Returns the element with the given identifier. - */ - FileNode operator[](const String& nodename) const; - - /** @overload - @param nodename Name of an element in the mapping node. - */ - CV_WRAP_AS(getNode) FileNode operator[](const char* nodename) const; - - /** @overload - @param i Index of an element in the sequence node. - */ - CV_WRAP_AS(at) FileNode operator[](int i) const; - - /** @brief Returns keys of a mapping node. - @returns Keys of a mapping node. - */ - CV_WRAP std::vector keys() const; - - /** @brief Returns type of the node. - @returns Type of the node. See FileNode::Type - */ - CV_WRAP int type() const; - - //! returns true if the node is empty - CV_WRAP bool empty() const; - //! returns true if the node is a "none" object - CV_WRAP bool isNone() const; - //! returns true if the node is a sequence - CV_WRAP bool isSeq() const; - //! returns true if the node is a mapping - CV_WRAP bool isMap() const; - //! returns true if the node is an integer - CV_WRAP bool isInt() const; - //! returns true if the node is a floating-point number - CV_WRAP bool isReal() const; - //! returns true if the node is a text string - CV_WRAP bool isString() const; - //! returns true if the node has a name - CV_WRAP bool isNamed() const; - //! returns the node name or an empty string if the node is nameless - CV_WRAP std::string name() const; - //! returns the number of elements in the node, if it is a sequence or mapping, or 1 otherwise. - CV_WRAP size_t size() const; - //! returns raw size of the FileNode in bytes - CV_WRAP size_t rawSize() const; - //! returns the node content as an integer. If the node stores floating-point number, it is rounded. - operator int() const; - //! returns the node content as a signed 64bit integer. If the node stores floating-point number, it is rounded. - operator int64_t() const; - //! returns the node content as float - operator float() const; - //! returns the node content as double - operator double() const; - //! returns the node content as text string - inline operator std::string() const { return this->string(); } - - static bool isMap(int flags); - static bool isSeq(int flags); - static bool isCollection(int flags); - static bool isEmptyCollection(int flags); - static bool isFlow(int flags); - - uchar* ptr(); - const uchar* ptr() const; - - //! returns iterator pointing to the first node element - FileNodeIterator begin() const; - //! returns iterator pointing to the element following the last node element - FileNodeIterator end() const; - - /** @brief Reads node elements to the buffer with the specified format. - - Usually it is more convenient to use operator `>>` instead of this method. - @param fmt Specification of each array element. See @ref format_spec "format specification" - @param vec Pointer to the destination array. - @param len Number of bytes to read (buffer size limit). If it is greater than number of - remaining elements then all of them will be read. - */ - void readRaw( const String& fmt, void* vec, size_t len ) const; - - /** Internal method used when reading FileStorage. - Sets the type (int, real or string) and value of the previously created node. - */ - void setValue( int type, const void* value, int len=-1 ); - - //! Simplified reading API to use with bindings. - CV_WRAP double real() const; - //! Simplified reading API to use with bindings. - CV_WRAP std::string string() const; - //! Simplified reading API to use with bindings. - CV_WRAP Mat mat() const; - - //protected: - FileNode(FileStorage::Impl* fs, size_t blockIdx, size_t ofs); - - FileStorage::Impl* fs; - size_t blockIdx; - size_t ofs; -}; - - -/** @brief used to iterate through sequences and mappings. - - A standard STL notation, with node.begin(), node.end() denoting the beginning and the end of a - sequence, stored in node. See the data reading sample in the beginning of the section. - */ -class CV_EXPORTS FileNodeIterator -{ -public: - /** @brief The constructors. - - These constructors are used to create a default iterator, set it to specific element in a file node - or construct it from another iterator. - */ - FileNodeIterator(); - - /** @overload - @param node File node - the collection to iterate over; - it can be a scalar (equivalent to 1-element collection) or "none" (equivalent to empty collection). - @param seekEnd - true if iterator needs to be set after the last element of the node; - that is: - * node.begin() => FileNodeIterator(node, false) - * node.end() => FileNodeIterator(node, true) - */ - FileNodeIterator(const FileNode& node, bool seekEnd); - - /** @overload - @param it Iterator to be used as initialization for the created iterator. - */ - FileNodeIterator(const FileNodeIterator& it); - - FileNodeIterator& operator=(const FileNodeIterator& it); - - //! returns the currently observed element - FileNode operator *() const; - - //! moves iterator to the next node - FileNodeIterator& operator ++ (); - //! moves iterator to the next node - FileNodeIterator operator ++ (int); - //! moves iterator forward by the specified offset (possibly negative) - FileNodeIterator& operator += (int ofs); - - /** @brief Reads node elements to the buffer with the specified format. - - Usually it is more convenient to use operator `>>` instead of this method. - @param fmt Specification of each array element. See @ref format_spec "format specification" - @param vec Pointer to the destination array. - @param len Number of bytes to read (buffer size limit). If it is greater than number of - remaining elements then all of them will be read. - */ - FileNodeIterator& readRaw( const String& fmt, void* vec, - size_t len=(size_t)INT_MAX ); - - //! returns the number of remaining (not read yet) elements - size_t remaining() const; - - bool equalTo(const FileNodeIterator& it) const; - -protected: - FileStorage::Impl* fs; - size_t blockIdx; - size_t ofs; - size_t blockSize; - size_t nodeNElems; - size_t idx; -}; - -//! @} core_xml - -/////////////////// XML & YAML I/O implementation ////////////////// - -CV_EXPORTS void write( FileStorage& fs, const String& name, int value ); -CV_EXPORTS void write( FileStorage& fs, const String& name, int64_t value ); -CV_EXPORTS void write( FileStorage& fs, const String& name, float value ); -CV_EXPORTS void write( FileStorage& fs, const String& name, double value ); -CV_EXPORTS void write( FileStorage& fs, const String& name, const String& value ); -CV_EXPORTS void write( FileStorage& fs, const String& name, const Mat& value ); -CV_EXPORTS void write( FileStorage& fs, const String& name, const SparseMat& value ); -#ifdef CV__LEGACY_PERSISTENCE -CV_EXPORTS void write( FileStorage& fs, const String& name, const std::vector& value); -CV_EXPORTS void write( FileStorage& fs, const String& name, const std::vector& value); -#endif - -CV_EXPORTS void writeScalar( FileStorage& fs, int value ); -CV_EXPORTS void writeScalar( FileStorage& fs, int64_t value ); -CV_EXPORTS void writeScalar( FileStorage& fs, float value ); -CV_EXPORTS void writeScalar( FileStorage& fs, double value ); -CV_EXPORTS void writeScalar( FileStorage& fs, const String& value ); - -CV_EXPORTS void read(const FileNode& node, int& value, int default_value); -CV_EXPORTS void read(const FileNode& node, int64_t& value, int64_t default_value); -CV_EXPORTS void read(const FileNode& node, float& value, float default_value); -CV_EXPORTS void read(const FileNode& node, double& value, double default_value); -CV_EXPORTS void read(const FileNode& node, std::string& value, const std::string& default_value); -CV_EXPORTS void read(const FileNode& node, Mat& mat, const Mat& default_mat = Mat() ); -CV_EXPORTS void read(const FileNode& node, SparseMat& mat, const SparseMat& default_mat = SparseMat() ); -#ifdef CV__LEGACY_PERSISTENCE -CV_EXPORTS void read(const FileNode& node, std::vector& keypoints); -CV_EXPORTS void read(const FileNode& node, std::vector& matches); -#endif -CV_EXPORTS void read(const FileNode& node, KeyPoint& value, const KeyPoint& default_value); -CV_EXPORTS void read(const FileNode& node, DMatch& value, const DMatch& default_value); - -template static inline void read(const FileNode& node, Point_<_Tp>& value, const Point_<_Tp>& default_value) -{ - std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; - value = temp.size() != 2 ? default_value : Point_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1])); -} - -template static inline void read(const FileNode& node, Point3_<_Tp>& value, const Point3_<_Tp>& default_value) -{ - std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; - value = temp.size() != 3 ? default_value : Point3_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]), - saturate_cast<_Tp>(temp[2])); -} - -template static inline void read(const FileNode& node, Size_<_Tp>& value, const Size_<_Tp>& default_value) -{ - std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; - value = temp.size() != 2 ? default_value : Size_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1])); -} - -template static inline void read(const FileNode& node, Complex<_Tp>& value, const Complex<_Tp>& default_value) -{ - std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; - value = temp.size() != 2 ? default_value : Complex<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1])); -} - -template static inline void read(const FileNode& node, Rect_<_Tp>& value, const Rect_<_Tp>& default_value) -{ - std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; - value = temp.size() != 4 ? default_value : Rect_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]), - saturate_cast<_Tp>(temp[2]), saturate_cast<_Tp>(temp[3])); -} - -template static inline void read(const FileNode& node, Vec<_Tp, cn>& value, const Vec<_Tp, cn>& default_value) -{ - std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; - value = temp.size() != cn ? default_value : Vec<_Tp, cn>(&temp[0]); -} - -template static inline void read(const FileNode& node, Matx<_Tp, m, n>& value, const Matx<_Tp, m, n>& default_matx = Matx<_Tp, m, n>()) -{ - Mat temp; - read(node, temp); // read as a Mat class - - if (temp.empty()) - value = default_matx; - else - value = Matx<_Tp, m, n>(temp); -} - -template static inline void read(const FileNode& node, Scalar_<_Tp>& value, const Scalar_<_Tp>& default_value) -{ - std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; - value = temp.size() != 4 ? default_value : Scalar_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]), - saturate_cast<_Tp>(temp[2]), saturate_cast<_Tp>(temp[3])); -} - -static inline void read(const FileNode& node, Range& value, const Range& default_value) -{ - Point2i temp(value.start, value.end); const Point2i default_temp = Point2i(default_value.start, default_value.end); - read(node, temp, default_temp); - value.start = temp.x; value.end = temp.y; -} - -/** @brief Writes string to a file storage. - */ -CV_EXPORTS FileStorage& operator << (FileStorage& fs, const String& str); - -//! @cond IGNORED - -namespace internal -{ - class CV_EXPORTS WriteStructContext - { - public: - WriteStructContext(FileStorage& _fs, const String& name, int flags, const String& typeName = String()); - ~WriteStructContext(); - private: - FileStorage* fs; - }; - - template class VecWriterProxy - { - public: - VecWriterProxy( FileStorage* _fs ) : fs(_fs) {} - void operator()(const std::vector<_Tp>& vec) const - { - size_t count = vec.size(); - for (size_t i = 0; i < count; i++) - write(*fs, vec[i]); - } - private: - FileStorage* fs; - }; - - template class VecWriterProxy<_Tp, 1> - { - public: - VecWriterProxy( FileStorage* _fs ) : fs(_fs) {} - void operator()(const std::vector<_Tp>& vec) const - { - int _fmt = traits::SafeFmt<_Tp>::fmt; - char fmt[] = { (char)((_fmt >> 8) + '1'), (char)_fmt, '\0' }; - fs->writeRaw(fmt, !vec.empty() ? (uchar*)&vec[0] : 0, vec.size() * sizeof(_Tp)); - } - private: - FileStorage* fs; - }; - - template class VecReaderProxy - { - public: - VecReaderProxy( FileNodeIterator* _it ) : it(_it) {} - void operator()(std::vector<_Tp>& vec, size_t count) const - { - count = std::min(count, it->remaining()); - vec.resize(count); - for (size_t i = 0; i < count; i++, ++(*it)) - read(**it, vec[i], _Tp()); - } - private: - FileNodeIterator* it; - }; - - template class VecReaderProxy<_Tp, 1> - { - public: - VecReaderProxy( FileNodeIterator* _it ) : it(_it) {} - void operator()(std::vector<_Tp>& vec, size_t count) const - { - size_t remaining = it->remaining(); - size_t cn = DataType<_Tp>::channels; - int _fmt = traits::SafeFmt<_Tp>::fmt; - CV_Assert((_fmt >> 8) < 9); - char fmt[] = { (char)((_fmt >> 8)+'1'), (char)_fmt, '\0' }; - CV_Assert((remaining % cn) == 0); - size_t remaining1 = remaining / cn; - count = count > remaining1 ? remaining1 : count; - vec.resize(count); - it->readRaw(fmt, !vec.empty() ? (uchar*)&vec[0] : 0, count*sizeof(_Tp)); - } - private: - FileNodeIterator* it; - }; - -} // internal - -//! @endcond - -template static inline -void write(FileStorage& fs, const _Tp& value) -{ - write(fs, String(), value); -} - -template<> inline -void write( FileStorage& fs, const int& value ) -{ - writeScalar(fs, value); -} - -template<> inline -void write( FileStorage& fs, const float& value ) -{ - writeScalar(fs, value); -} - -template<> inline -void write( FileStorage& fs, const double& value ) -{ - writeScalar(fs, value); -} - -template<> inline -void write( FileStorage& fs, const String& value ) -{ - writeScalar(fs, value); -} - -template static inline -void write(FileStorage& fs, const Point_<_Tp>& pt ) -{ - write(fs, pt.x); - write(fs, pt.y); -} - -template static inline -void write(FileStorage& fs, const Point3_<_Tp>& pt ) -{ - write(fs, pt.x); - write(fs, pt.y); - write(fs, pt.z); -} - -template static inline -void write(FileStorage& fs, const Size_<_Tp>& sz ) -{ - write(fs, sz.width); - write(fs, sz.height); -} - -template static inline -void write(FileStorage& fs, const Complex<_Tp>& c ) -{ - write(fs, c.re); - write(fs, c.im); -} - -template static inline -void write(FileStorage& fs, const Rect_<_Tp>& r ) -{ - write(fs, r.x); - write(fs, r.y); - write(fs, r.width); - write(fs, r.height); -} - -template static inline -void write(FileStorage& fs, const Vec<_Tp, cn>& v ) -{ - for(int i = 0; i < cn; i++) - write(fs, v.val[i]); -} - -template static inline -void write(FileStorage& fs, const Matx<_Tp, m, n>& x ) -{ - write(fs, Mat(x)); // write as a Mat class -} - -template static inline -void write(FileStorage& fs, const Scalar_<_Tp>& s ) -{ - write(fs, s.val[0]); - write(fs, s.val[1]); - write(fs, s.val[2]); - write(fs, s.val[3]); -} - -static inline -void write(FileStorage& fs, const Range& r ) -{ - write(fs, r.start); - write(fs, r.end); -} - -template static inline -void write( FileStorage& fs, const std::vector<_Tp>& vec ) -{ - cv::internal::VecWriterProxy<_Tp, traits::SafeFmt<_Tp>::fmt != 0> w(&fs); - w(vec); -} - -template static inline -void write(FileStorage& fs, const String& name, const Point_<_Tp>& pt ) -{ - cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); - write(fs, pt); -} - -template static inline -void write(FileStorage& fs, const String& name, const Point3_<_Tp>& pt ) -{ - cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); - write(fs, pt); -} - -template static inline -void write(FileStorage& fs, const String& name, const Size_<_Tp>& sz ) -{ - cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); - write(fs, sz); -} - -template static inline -void write(FileStorage& fs, const String& name, const Complex<_Tp>& c ) -{ - cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); - write(fs, c); -} - -template static inline -void write(FileStorage& fs, const String& name, const Rect_<_Tp>& r ) -{ - cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); - write(fs, r); -} - -template static inline -void write(FileStorage& fs, const String& name, const Vec<_Tp, cn>& v ) -{ - cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); - write(fs, v); -} - -template static inline -void write(FileStorage& fs, const String& name, const Matx<_Tp, m, n>& x ) -{ - write(fs, name, Mat(x)); // write as a Mat class -} - -template static inline -void write(FileStorage& fs, const String& name, const Scalar_<_Tp>& s ) -{ - cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); - write(fs, s); -} - -static inline -void write(FileStorage& fs, const String& name, const Range& r ) -{ - cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); - write(fs, r); -} - -static inline -void write(FileStorage& fs, const String& name, const KeyPoint& kpt) -{ - cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); - write(fs, kpt.pt.x); - write(fs, kpt.pt.y); - write(fs, kpt.size); - write(fs, kpt.angle); - write(fs, kpt.response); - write(fs, kpt.octave); - write(fs, kpt.class_id); -} - -static inline -void write(FileStorage& fs, const String& name, const DMatch& m) -{ - cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); - write(fs, m.queryIdx); - write(fs, m.trainIdx); - write(fs, m.imgIdx); - write(fs, m.distance); -} - -template::value >::type* = nullptr> -static inline void write( FileStorage& fs, const String& name, const _Tp& val ) -{ - write(fs, name, static_cast(val)); -} - -template static inline -void write( FileStorage& fs, const String& name, const std::vector<_Tp>& vec ) -{ - cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+(traits::SafeFmt<_Tp>::fmt != 0 ? FileNode::FLOW : 0)); - write(fs, vec); -} - -template static inline -void write( FileStorage& fs, const String& name, const std::vector< std::vector<_Tp> >& vec ) -{ - cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ); - for(size_t i = 0; i < vec.size(); i++) - { - cv::internal::WriteStructContext ws_(fs, name, FileNode::SEQ+(traits::SafeFmt<_Tp>::fmt != 0 ? FileNode::FLOW : 0)); - write(fs, vec[i]); - } -} - -#ifdef CV__LEGACY_PERSISTENCE -// This code is not needed anymore, but it is preserved here to keep source compatibility -// Implementation is similar to templates instantiations -static inline void write(FileStorage& fs, const KeyPoint& kpt) { write(fs, String(), kpt); } -static inline void write(FileStorage& fs, const DMatch& m) { write(fs, String(), m); } -static inline void write(FileStorage& fs, const std::vector& vec) -{ - cv::internal::VecWriterProxy w(&fs); - w(vec); -} -static inline void write(FileStorage& fs, const std::vector& vec) -{ - cv::internal::VecWriterProxy w(&fs); - w(vec); - -} -#endif - - -static inline -void read(const FileNode& node, bool& value, bool default_value) -{ - int temp; - read(node, temp, (int)default_value); - value = temp != 0; -} - -static inline -void read(const FileNode& node, uchar& value, uchar default_value) -{ - int temp; - read(node, temp, (int)default_value); - value = saturate_cast(temp); -} - -static inline -void read(const FileNode& node, schar& value, schar default_value) -{ - int temp; - read(node, temp, (int)default_value); - value = saturate_cast(temp); -} - -static inline -void read(const FileNode& node, ushort& value, ushort default_value) -{ - int temp; - read(node, temp, (int)default_value); - value = saturate_cast(temp); -} - -static inline -void read(const FileNode& node, short& value, short default_value) -{ - int temp; - read(node, temp, (int)default_value); - value = saturate_cast(temp); -} - -template static inline -void read( FileNodeIterator& it, std::vector<_Tp>& vec, size_t maxCount = (size_t)INT_MAX ) -{ - cv::internal::VecReaderProxy<_Tp, traits::SafeFmt<_Tp>::fmt != 0> r(&it); - r(vec, maxCount); -} - -template::value >::type* = nullptr> -static inline void read(const FileNode& node, _Tp& value, const _Tp& default_value = static_cast<_Tp>(0)) -{ - int temp; - read(node, temp, static_cast(default_value)); - value = static_cast<_Tp>(temp); -} - -template static inline -void read( const FileNode& node, std::vector<_Tp>& vec, const std::vector<_Tp>& default_value = std::vector<_Tp>() ) -{ - if(node.empty()) - vec = default_value; - else - { - FileNodeIterator it = node.begin(); - read( it, vec ); - } -} - -static inline -void read( const FileNode& node, std::vector& vec, const std::vector& default_value ) -{ - if(node.empty()) - vec = default_value; - else - read(node, vec); -} - -static inline -void read( const FileNode& node, std::vector& vec, const std::vector& default_value ) -{ - if(node.empty()) - vec = default_value; - else - read(node, vec); -} - -/** @brief Writes data to a file storage. - */ -template static inline -FileStorage& operator << (FileStorage& fs, const _Tp& value) -{ - if( !fs.isOpened() ) - return fs; - if( fs.state == FileStorage::NAME_EXPECTED + FileStorage::INSIDE_MAP ) - CV_Error( Error::StsError, "No element name has been given" ); - write( fs, fs.elname, value ); - if( fs.state & FileStorage::INSIDE_MAP ) - fs.state = FileStorage::NAME_EXPECTED + FileStorage::INSIDE_MAP; - return fs; -} - -/** @brief Writes data to a file storage. - */ -static inline -FileStorage& operator << (FileStorage& fs, const char* str) -{ - return (fs << String(str)); -} - -/** @brief Writes data to a file storage. - */ -static inline -FileStorage& operator << (FileStorage& fs, char* value) -{ - return (fs << String(value)); -} - -/** @brief Reads data from a file storage. - */ -template static inline -FileNodeIterator& operator >> (FileNodeIterator& it, _Tp& value) -{ - read( *it, value, _Tp()); - return ++it; -} - -/** @brief Reads data from a file storage. - */ -template static inline -FileNodeIterator& operator >> (FileNodeIterator& it, std::vector<_Tp>& vec) -{ - cv::internal::VecReaderProxy<_Tp, traits::SafeFmt<_Tp>::fmt != 0> r(&it); - r(vec, (size_t)INT_MAX); - return it; -} - -/** @brief Reads data from a file storage. - */ -template static inline -void operator >> (const FileNode& n, _Tp& value) -{ - read( n, value, _Tp()); -} - -/** @brief Reads data from a file storage. - */ -template static inline -void operator >> (const FileNode& n, std::vector<_Tp>& vec) -{ - FileNodeIterator it = n.begin(); - it >> vec; -} - -/** @brief Reads KeyPoint from a file storage. -*/ -//It needs special handling because it contains two types of fields, int & float. -static inline -void operator >> (const FileNode& n, KeyPoint& kpt) -{ - FileNodeIterator it = n.begin(); - it >> kpt.pt.x >> kpt.pt.y >> kpt.size >> kpt.angle >> kpt.response >> kpt.octave >> kpt.class_id; -} - -#ifdef CV__LEGACY_PERSISTENCE -static inline -void operator >> (const FileNode& n, std::vector& vec) -{ - read(n, vec); -} -static inline -void operator >> (const FileNode& n, std::vector& vec) -{ - read(n, vec); -} -#endif - -/** @brief Reads DMatch from a file storage. -*/ -//It needs special handling because it contains two types of fields, int & float. -static inline -void operator >> (const FileNode& n, DMatch& m) -{ - FileNodeIterator it = n.begin(); - it >> m.queryIdx >> m.trainIdx >> m.imgIdx >> m.distance; -} - -CV_EXPORTS bool operator == (const FileNodeIterator& it1, const FileNodeIterator& it2); -CV_EXPORTS bool operator != (const FileNodeIterator& it1, const FileNodeIterator& it2); - -static inline -ptrdiff_t operator - (const FileNodeIterator& it1, const FileNodeIterator& it2) -{ - return it2.remaining() - it1.remaining(); -} - -static inline -bool operator < (const FileNodeIterator& it1, const FileNodeIterator& it2) -{ - return it1.remaining() > it2.remaining(); -} - -} // cv - -#endif // OPENCV_CORE_PERSISTENCE_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CORE_PERSISTENCE_HPP +#define OPENCV_CORE_PERSISTENCE_HPP + +#ifndef CV_DOXYGEN +/// Define to support persistence legacy formats +#define CV__LEGACY_PERSISTENCE +#endif + +#ifndef __cplusplus +# error persistence.hpp header must be compiled as C++ +#endif + +#include "opencv2/core/types.hpp" +#include "opencv2/core/mat.hpp" + +namespace cv { + +/** @addtogroup core_xml + +XML/YAML/JSON file storages. {#xml_storage} +======================= +Writing to a file storage. +-------------------------- +You can store and then restore various OpenCV data structures to/from XML (), +YAML () or JSON () formats. Also, it is possible to store +and load arbitrarily complex data structures, which include OpenCV data structures, as well as +primitive data types (integer and floating-point numbers and text strings) as their elements. + +Use the following procedure to write something to XML, YAML or JSON: +-# Create new FileStorage and open it for writing. It can be done with a single call to +FileStorage::FileStorage constructor that takes a filename, or you can use the default constructor +and then call FileStorage::open. Format of the file (XML, YAML or JSON) is determined from the filename +extension (".xml", ".yml"/".yaml" and ".json", respectively) +-# Write all the data you want using the streaming operator `<<`, just like in the case of STL +streams. +-# Close the file using FileStorage::release. FileStorage destructor also closes the file. + +Here is an example: +@code + #include "opencv2/core.hpp" + #include + + using namespace cv; + + int main(int, char** argv) + { + FileStorage fs("test.yml", FileStorage::WRITE); + + fs << "frameCount" << 5; + time_t rawtime; time(&rawtime); + fs << "calibrationDate" << asctime(localtime(&rawtime)); + Mat cameraMatrix = (Mat_(3,3) << 1000, 0, 320, 0, 1000, 240, 0, 0, 1); + Mat distCoeffs = (Mat_(5,1) << 0.1, 0.01, -0.001, 0, 0); + fs << "cameraMatrix" << cameraMatrix << "distCoeffs" << distCoeffs; + fs << "features" << "["; + for( int i = 0; i < 3; i++ ) + { + int x = rand() % 640; + int y = rand() % 480; + uchar lbp = rand() % 256; + + fs << "{:" << "x" << x << "y" << y << "lbp" << "[:"; + for( int j = 0; j < 8; j++ ) + fs << ((lbp >> j) & 1); + fs << "]" << "}"; + } + fs << "]"; + fs.release(); + return 0; + } +@endcode +The sample above stores to YML an integer, a text string (calibration date), 2 matrices, and a custom +structure "feature", which includes feature coordinates and LBP (local binary pattern) value. Here +is output of the sample: +@code{.yaml} +%YAML:1.0 +frameCount: 5 +calibrationDate: "Fri Jun 17 14:09:29 2011\n" +cameraMatrix: !!opencv-matrix + rows: 3 + cols: 3 + dt: d + data: [ 1000., 0., 320., 0., 1000., 240., 0., 0., 1. ] +distCoeffs: !!opencv-matrix + rows: 5 + cols: 1 + dt: d + data: [ 1.0000000000000001e-01, 1.0000000000000000e-02, + -1.0000000000000000e-03, 0., 0. ] +features: + - { x:167, y:49, lbp:[ 1, 0, 0, 1, 1, 0, 1, 1 ] } + - { x:298, y:130, lbp:[ 0, 0, 0, 1, 0, 0, 1, 1 ] } + - { x:344, y:158, lbp:[ 1, 1, 0, 0, 0, 0, 1, 0 ] } +@endcode + +As an exercise, you can replace ".yml" with ".xml" or ".json" in the sample above and see, how the +corresponding XML file will look like. + +Several things can be noted by looking at the sample code and the output: + +- The produced YAML (and XML/JSON) consists of heterogeneous collections that can be nested. There are + 2 types of collections: named collections (mappings) and unnamed collections (sequences). In mappings + each element has a name and is accessed by name. This is similar to structures and std::map in + C/C++ and dictionaries in Python. In sequences elements do not have names, they are accessed by + indices. This is similar to arrays and std::vector in C/C++ and lists, tuples in Python. + "Heterogeneous" means that elements of each single collection can have different types. + + Top-level collection in YAML/XML/JSON is a mapping. Each matrix is stored as a mapping, and the matrix + elements are stored as a sequence. Then, there is a sequence of features, where each feature is + represented a mapping, and lbp value in a nested sequence. + +- When you write to a mapping (a structure), you write element name followed by its value. When you + write to a sequence, you simply write the elements one by one. OpenCV data structures (such as + cv::Mat) are written in absolutely the same way as simple C data structures - using `<<` + operator. + +- To write a mapping, you first write the special string `{` to the storage, then write the + elements as pairs (`fs << << `) and then write the closing + `}`. + +- To write a sequence, you first write the special string `[`, then write the elements, then + write the closing `]`. + +- In YAML/JSON (but not XML), mappings and sequences can be written in a compact Python-like inline + form. In the sample above matrix elements, as well as each feature, including its lbp value, is + stored in such inline form. To store a mapping/sequence in a compact form, put `:` after the + opening character, e.g. use `{:` instead of `{` and `[:` instead of `[`. When the + data is written to XML, those extra `:` are ignored. + +Reading data from a file storage. +--------------------------------- +To read the previously written XML, YAML or JSON file, do the following: +-# Open the file storage using FileStorage::FileStorage constructor or FileStorage::open method. + In the current implementation the whole file is parsed and the whole representation of file + storage is built in memory as a hierarchy of file nodes (see FileNode) + +-# Read the data you are interested in. Use FileStorage::operator [], FileNode::operator [] + and/or FileNodeIterator. + +-# Close the storage using FileStorage::release. + +Here is how to read the file created by the code sample above: +@code + FileStorage fs2("test.yml", FileStorage::READ); + + // first method: use (type) operator on FileNode. + int frameCount = (int)fs2["frameCount"]; + + String date; + // second method: use FileNode::operator >> + fs2["calibrationDate"] >> date; + + Mat cameraMatrix2, distCoeffs2; + fs2["cameraMatrix"] >> cameraMatrix2; + fs2["distCoeffs"] >> distCoeffs2; + + cout << "frameCount: " << frameCount << endl + << "calibration date: " << date << endl + << "camera matrix: " << cameraMatrix2 << endl + << "distortion coeffs: " << distCoeffs2 << endl; + + FileNode features = fs2["features"]; + FileNodeIterator it = features.begin(), it_end = features.end(); + int idx = 0; + std::vector lbpval; + + // iterate through a sequence using FileNodeIterator + for( ; it != it_end; ++it, idx++ ) + { + cout << "feature #" << idx << ": "; + cout << "x=" << (int)(*it)["x"] << ", y=" << (int)(*it)["y"] << ", lbp: ("; + // you can also easily read numerical arrays using FileNode >> std::vector operator. + (*it)["lbp"] >> lbpval; + for( int i = 0; i < (int)lbpval.size(); i++ ) + cout << " " << (int)lbpval[i]; + cout << ")" << endl; + } + fs2.release(); +@endcode + +Format specification {#format_spec} +-------------------- +`([count]{u|c|w|s|i|f|d})`... where the characters correspond to fundamental C++ types: +- `u` 8-bit unsigned number +- `c` 8-bit signed number +- `w` 16-bit unsigned number +- `s` 16-bit signed number +- `i` 32-bit signed number +- `f` single precision floating-point number +- `d` double precision floating-point number +- `r` pointer, 32 lower bits of which are written as a signed integer. The type can be used to + store structures with links between the elements. + +`count` is the optional counter of values of a given type. For example, `2if` means that each array +element is a structure of 2 integers, followed by a single-precision floating-point number. The +equivalent notations of the above specification are `iif`, `2i1f` and so forth. Other examples: `u` +means that the array consists of bytes, and `2d` means the array consists of pairs of doubles. + +@see @ref samples/cpp/tutorial_code/core/file_input_output/file_input_output.cpp +*/ + +//! @{ + +/** @example samples/cpp/tutorial_code/core/file_input_output/file_input_output.cpp +A complete example using the FileStorage interface +Check @ref tutorial_file_input_output_with_xml_yml "the corresponding tutorial" for more details +*/ + +////////////////////////// XML & YAML I/O ////////////////////////// + +class CV_EXPORTS FileNode; +class CV_EXPORTS FileNodeIterator; + +/** @brief XML/YAML/JSON file storage class that encapsulates all the information necessary for writing or +reading data to/from a file. + */ +class CV_EXPORTS_W FileStorage +{ +public: + //! file storage mode + enum Mode + { + READ = 0, //!< value, open the file for reading + WRITE = 1, //!< value, open the file for writing + APPEND = 2, //!< value, open the file for appending + MEMORY = 4, /**< flag, read data from source or write data to the internal buffer (which is + returned by FileStorage::release) */ + FORMAT_MASK = (7<<3), //!< mask for format flags + FORMAT_AUTO = 0, //!< flag, auto format + FORMAT_XML = (1<<3), //!< flag, XML format + FORMAT_YAML = (2<<3), //!< flag, YAML format + FORMAT_JSON = (3<<3), //!< flag, JSON format + + BASE64 = 64, //!< flag, write rawdata in Base64 by default. (consider using WRITE_BASE64) + WRITE_BASE64 = BASE64 | WRITE, //!< flag, enable both WRITE and BASE64 + }; + enum State + { + UNDEFINED = 0, //!< Initial or uninitialized state. + VALUE_EXPECTED = 1, //!< Expecting a value in the current position. + NAME_EXPECTED = 2, //!< Expecting a key/name in the current position. + INSIDE_MAP = 4 //!< Indicates being inside a map (a set of key-value pairs). + }; + + /** @brief The constructors. + + The full constructor opens the file. Alternatively you can use the default constructor and then + call FileStorage::open. + */ + CV_WRAP FileStorage(); + + /** @overload + @copydoc open() + */ + CV_WRAP FileStorage(const String& filename, int flags, const String& encoding=String()); + + //! the destructor. calls release() + virtual ~FileStorage(); + + /** @brief Opens a file. + + See description of parameters in FileStorage::FileStorage. The method calls FileStorage::release + before opening the file. + @param filename Name of the file to open or the text string to read the data from. + Extension of the file (.xml, .yml/.yaml or .json) determines its format (XML, YAML or JSON + respectively). Also you can append .gz to work with compressed files, for example myHugeMatrix.xml.gz. If both + FileStorage::WRITE and FileStorage::MEMORY flags are specified, source is used just to specify + the output file format (e.g. mydata.xml, .yml etc.). A file name can also contain parameters. + You can use this format, "*?base64" (e.g. "file.json?base64" (case sensitive)), as an alternative to + FileStorage::BASE64 flag. + @param flags Mode of operation. One of FileStorage::Mode + @param encoding Encoding of the file. Note that UTF-16 XML encoding is not supported currently and + you should use 8-bit encoding instead of it. + */ + CV_WRAP virtual bool open(const String& filename, int flags, const String& encoding=String()); + + /** @brief Checks whether the file is opened. + + @returns true if the object is associated with the current file and false otherwise. It is a + good practice to call this method after you tried to open a file. + */ + CV_WRAP virtual bool isOpened() const; + + /** @brief Closes the file and releases all the memory buffers. + + Call this method after all I/O operations with the storage are finished. + */ + CV_WRAP virtual void release(); + + /** @brief Closes the file and releases all the memory buffers. + + Call this method after all I/O operations with the storage are finished. If the storage was + opened for writing data and FileStorage::WRITE was specified + */ + CV_WRAP virtual String releaseAndGetString(); + + /** @brief Returns the first element of the top-level mapping. + @returns The first element of the top-level mapping. + */ + CV_WRAP FileNode getFirstTopLevelNode() const; + + /** @brief Returns the top-level mapping + @param streamidx Zero-based index of the stream. In most cases there is only one stream in the file. + However, YAML supports multiple streams and so there can be several. + @returns The top-level mapping. + */ + CV_WRAP FileNode root(int streamidx=0) const; + + /** @brief Returns the specified element of the top-level mapping. + @param nodename Name of the file node. + @returns Node with the given name. + */ + FileNode operator[](const String& nodename) const; + + /** @overload */ + CV_WRAP_AS(getNode) FileNode operator[](const char* nodename) const; + + /** + * @brief Simplified writing API to use with bindings. + * @param name Name of the written object. When writing to sequences (a.k.a. "arrays"), pass an empty string. + * @param val Value of the written object. + */ + CV_WRAP void write(const String& name, int val); + /// @overload + CV_WRAP void write(const String& name, int64_t val); + /// @overload + CV_WRAP void write(const String& name, double val); + /// @overload + CV_WRAP void write(const String& name, const String& val); + /// @overload + CV_WRAP void write(const String& name, const Mat& val); + /// @overload + CV_WRAP void write(const String& name, const std::vector& val); + + /** @brief Writes multiple numbers. + + Writes one or more numbers of the specified format to the currently written structure. Usually it is + more convenient to use operator `<<` instead of this method. + @param fmt Specification of each array element, see @ref format_spec "format specification" + @param vec Pointer to the written array. + @param len Number of the uchar elements to write. + */ + void writeRaw( const String& fmt, const void* vec, size_t len ); + + /** @brief Writes a comment. + + The function writes a comment into file storage. The comments are skipped when the storage is read. + @param comment The written comment, single-line or multi-line + @param append If true, the function tries to put the comment at the end of current line. + Else if the comment is multi-line, or if it does not fit at the end of the current + line, the comment starts a new line. + */ + CV_WRAP void writeComment(const String& comment, bool append = false); + + /** @brief Starts to write a nested structure (sequence or a mapping). + @param name name of the structure. When writing to sequences (a.k.a. "arrays"), pass an empty string. + @param flags type of the structure (FileNode::MAP or FileNode::SEQ (both with optional FileNode::FLOW)). + @param typeName optional name of the type you store. The effect of setting this depends on the storage format. + I.e. if the format has a specification for storing type information, this parameter is used. + */ + CV_WRAP void startWriteStruct(const String& name, int flags, const String& typeName=String()); + + /** @brief Finishes writing nested structure (should pair startWriteStruct()) + */ + CV_WRAP void endWriteStruct(); + + /** @brief Returns the normalized object name for the specified name of a file. + @param filename Name of a file + @returns The normalized object name. + */ + static String getDefaultObjectName(const String& filename); + + /** @brief Returns the current format. + * @returns The current format, see FileStorage::Mode + */ + CV_WRAP int getFormat() const; + + int state; + std::string elname; + + class Impl; + Ptr p; +}; + +/** @brief File Storage Node class. + +The node is used to store each and every element of the file storage opened for reading. When +XML/YAML file is read, it is first parsed and stored in the memory as a hierarchical collection of +nodes. Each node can be a "leaf" that is contain a single number or a string, or be a collection of +other nodes. There can be named collections (mappings) where each element has a name and it is +accessed by a name, and ordered collections (sequences) where elements do not have names but rather +accessed by index. Type of the file node can be determined using FileNode::type method. + +Note that file nodes are only used for navigating file storages opened for reading. When a file +storage is opened for writing, no data is stored in memory after it is written. + */ +class CV_EXPORTS_W_SIMPLE FileNode +{ +public: + //! type of the file storage node + enum + { + NONE = 0, //!< empty node + INT = 1, //!< an integer + REAL = 2, //!< floating-point number + FLOAT = REAL, //!< synonym or REAL + STR = 3, //!< text string in UTF-8 encoding + STRING = STR, //!< synonym for STR + SEQ = 4, //!< sequence + MAP = 5, //!< mapping + TYPE_MASK = 7, + + FLOW = 8, //!< compact representation of a sequence or mapping. Used only by YAML writer + UNIFORM = 8, //!< if set, means that all the collection elements are numbers of the same type (real's or int's). + //!< UNIFORM is used only when reading FileStorage; FLOW is used only when writing. So they share the same bit + EMPTY = 16, //!< empty structure (sequence or mapping) + NAMED = 32 //!< the node has a name (i.e. it is element of a mapping). + }; + /** @brief The constructors. + + These constructors are used to create a default file node, construct it from obsolete structures or + from the another file node. + */ + CV_WRAP FileNode(); + + /** @overload + @param fs Pointer to the file storage structure. + @param blockIdx Index of the memory block where the file node is stored + @param ofs Offset in bytes from the beginning of the serialized storage + + @deprecated + */ + FileNode(const FileStorage* fs, size_t blockIdx, size_t ofs); + + /** @overload + @param node File node to be used as initialization for the created file node. + */ + FileNode(const FileNode& node); + + FileNode& operator=(const FileNode& node); + + /** @brief Returns element of a mapping node or a sequence node. + @param nodename Name of an element in the mapping node. + @returns Returns the element with the given identifier. + */ + FileNode operator[](const String& nodename) const; + + /** @overload + @param nodename Name of an element in the mapping node. + */ + CV_WRAP_AS(getNode) FileNode operator[](const char* nodename) const; + + /** @overload + @param i Index of an element in the sequence node. + */ + CV_WRAP_AS(at) FileNode operator[](int i) const; + + /** @brief Returns keys of a mapping node. + @returns Keys of a mapping node. + */ + CV_WRAP std::vector keys() const; + + /** @brief Returns type of the node. + @returns Type of the node. See FileNode::Type + */ + CV_WRAP int type() const; + + //! returns true if the node is empty + CV_WRAP bool empty() const; + //! returns true if the node is a "none" object + CV_WRAP bool isNone() const; + //! returns true if the node is a sequence + CV_WRAP bool isSeq() const; + //! returns true if the node is a mapping + CV_WRAP bool isMap() const; + //! returns true if the node is an integer + CV_WRAP bool isInt() const; + //! returns true if the node is a floating-point number + CV_WRAP bool isReal() const; + //! returns true if the node is a text string + CV_WRAP bool isString() const; + //! returns true if the node has a name + CV_WRAP bool isNamed() const; + //! returns the node name or an empty string if the node is nameless + CV_WRAP std::string name() const; + //! returns the number of elements in the node, if it is a sequence or mapping, or 1 otherwise. + CV_WRAP size_t size() const; + //! returns raw size of the FileNode in bytes + CV_WRAP size_t rawSize() const; + //! returns the node content as an integer. If the node stores floating-point number, it is rounded. + operator int() const; + //! returns the node content as a signed 64bit integer. If the node stores floating-point number, it is rounded. + operator int64_t() const; + //! returns the node content as float + operator float() const; + //! returns the node content as double + operator double() const; + //! returns the node content as text string + inline operator std::string() const { return this->string(); } + + static bool isMap(int flags); + static bool isSeq(int flags); + static bool isCollection(int flags); + static bool isEmptyCollection(int flags); + static bool isFlow(int flags); + + uchar* ptr(); + const uchar* ptr() const; + + //! returns iterator pointing to the first node element + FileNodeIterator begin() const; + //! returns iterator pointing to the element following the last node element + FileNodeIterator end() const; + + /** @brief Reads node elements to the buffer with the specified format. + + Usually it is more convenient to use operator `>>` instead of this method. + @param fmt Specification of each array element. See @ref format_spec "format specification" + @param vec Pointer to the destination array. + @param len Number of bytes to read (buffer size limit). If it is greater than number of + remaining elements then all of them will be read. + */ + void readRaw( const String& fmt, void* vec, size_t len ) const; + + /** Internal method used when reading FileStorage. + Sets the type (int, real or string) and value of the previously created node. + */ + void setValue( int type, const void* value, int len=-1 ); + + //! Simplified reading API to use with bindings. + CV_WRAP double real() const; + //! Simplified reading API to use with bindings. + CV_WRAP std::string string() const; + //! Simplified reading API to use with bindings. + CV_WRAP Mat mat() const; + + //protected: + FileNode(FileStorage::Impl* fs, size_t blockIdx, size_t ofs); + + FileStorage::Impl* fs; + size_t blockIdx; + size_t ofs; +}; + + +/** @brief used to iterate through sequences and mappings. + + A standard STL notation, with node.begin(), node.end() denoting the beginning and the end of a + sequence, stored in node. See the data reading sample in the beginning of the section. + */ +class CV_EXPORTS FileNodeIterator +{ +public: + /** @brief The constructors. + + These constructors are used to create a default iterator, set it to specific element in a file node + or construct it from another iterator. + */ + FileNodeIterator(); + + /** @overload + @param node File node - the collection to iterate over; + it can be a scalar (equivalent to 1-element collection) or "none" (equivalent to empty collection). + @param seekEnd - true if iterator needs to be set after the last element of the node; + that is: + * node.begin() => FileNodeIterator(node, false) + * node.end() => FileNodeIterator(node, true) + */ + FileNodeIterator(const FileNode& node, bool seekEnd); + + /** @overload + @param it Iterator to be used as initialization for the created iterator. + */ + FileNodeIterator(const FileNodeIterator& it); + + FileNodeIterator& operator=(const FileNodeIterator& it); + + //! returns the currently observed element + FileNode operator *() const; + + //! moves iterator to the next node + FileNodeIterator& operator ++ (); + //! moves iterator to the next node + FileNodeIterator operator ++ (int); + //! moves iterator forward by the specified offset (possibly negative) + FileNodeIterator& operator += (int ofs); + + /** @brief Reads node elements to the buffer with the specified format. + + Usually it is more convenient to use operator `>>` instead of this method. + @param fmt Specification of each array element. See @ref format_spec "format specification" + @param vec Pointer to the destination array. + @param len Number of bytes to read (buffer size limit). If it is greater than number of + remaining elements then all of them will be read. + */ + FileNodeIterator& readRaw( const String& fmt, void* vec, + size_t len=(size_t)INT_MAX ); + + //! returns the number of remaining (not read yet) elements + size_t remaining() const; + + bool equalTo(const FileNodeIterator& it) const; + +protected: + FileStorage::Impl* fs; + size_t blockIdx; + size_t ofs; + size_t blockSize; + size_t nodeNElems; + size_t idx; +}; + +//! @} core_xml + +/////////////////// XML & YAML I/O implementation ////////////////// + +CV_EXPORTS void write( FileStorage& fs, const String& name, int value ); +CV_EXPORTS void write( FileStorage& fs, const String& name, int64_t value ); +CV_EXPORTS void write( FileStorage& fs, const String& name, float value ); +CV_EXPORTS void write( FileStorage& fs, const String& name, double value ); +CV_EXPORTS void write( FileStorage& fs, const String& name, const String& value ); +CV_EXPORTS void write( FileStorage& fs, const String& name, const Mat& value ); +CV_EXPORTS void write( FileStorage& fs, const String& name, const SparseMat& value ); +#ifdef CV__LEGACY_PERSISTENCE +CV_EXPORTS void write( FileStorage& fs, const String& name, const std::vector& value); +CV_EXPORTS void write( FileStorage& fs, const String& name, const std::vector& value); +#endif + +CV_EXPORTS void writeScalar( FileStorage& fs, int value ); +CV_EXPORTS void writeScalar( FileStorage& fs, int64_t value ); +CV_EXPORTS void writeScalar( FileStorage& fs, float value ); +CV_EXPORTS void writeScalar( FileStorage& fs, double value ); +CV_EXPORTS void writeScalar( FileStorage& fs, const String& value ); + +CV_EXPORTS void read(const FileNode& node, int& value, int default_value); +CV_EXPORTS void read(const FileNode& node, int64_t& value, int64_t default_value); +CV_EXPORTS void read(const FileNode& node, float& value, float default_value); +CV_EXPORTS void read(const FileNode& node, double& value, double default_value); +CV_EXPORTS void read(const FileNode& node, std::string& value, const std::string& default_value); +CV_EXPORTS void read(const FileNode& node, Mat& mat, const Mat& default_mat = Mat() ); +CV_EXPORTS void read(const FileNode& node, SparseMat& mat, const SparseMat& default_mat = SparseMat() ); +#ifdef CV__LEGACY_PERSISTENCE +CV_EXPORTS void read(const FileNode& node, std::vector& keypoints); +CV_EXPORTS void read(const FileNode& node, std::vector& matches); +#endif +CV_EXPORTS void read(const FileNode& node, KeyPoint& value, const KeyPoint& default_value); +CV_EXPORTS void read(const FileNode& node, DMatch& value, const DMatch& default_value); + +template static inline void read(const FileNode& node, Point_<_Tp>& value, const Point_<_Tp>& default_value) +{ + std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; + value = temp.size() != 2 ? default_value : Point_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1])); +} + +template static inline void read(const FileNode& node, Point3_<_Tp>& value, const Point3_<_Tp>& default_value) +{ + std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; + value = temp.size() != 3 ? default_value : Point3_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]), + saturate_cast<_Tp>(temp[2])); +} + +template static inline void read(const FileNode& node, Size_<_Tp>& value, const Size_<_Tp>& default_value) +{ + std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; + value = temp.size() != 2 ? default_value : Size_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1])); +} + +template static inline void read(const FileNode& node, Complex<_Tp>& value, const Complex<_Tp>& default_value) +{ + std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; + value = temp.size() != 2 ? default_value : Complex<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1])); +} + +template static inline void read(const FileNode& node, Rect_<_Tp>& value, const Rect_<_Tp>& default_value) +{ + std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; + value = temp.size() != 4 ? default_value : Rect_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]), + saturate_cast<_Tp>(temp[2]), saturate_cast<_Tp>(temp[3])); +} + +template static inline void read(const FileNode& node, Vec<_Tp, cn>& value, const Vec<_Tp, cn>& default_value) +{ + std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; + value = temp.size() != cn ? default_value : Vec<_Tp, cn>(&temp[0]); +} + +template static inline void read(const FileNode& node, Matx<_Tp, m, n>& value, const Matx<_Tp, m, n>& default_matx = Matx<_Tp, m, n>()) +{ + Mat temp; + read(node, temp); // read as a Mat class + + if (temp.empty()) + value = default_matx; + else + value = Matx<_Tp, m, n>(temp); +} + +template static inline void read(const FileNode& node, Scalar_<_Tp>& value, const Scalar_<_Tp>& default_value) +{ + std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; + value = temp.size() != 4 ? default_value : Scalar_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]), + saturate_cast<_Tp>(temp[2]), saturate_cast<_Tp>(temp[3])); +} + +static inline void read(const FileNode& node, Range& value, const Range& default_value) +{ + Point2i temp(value.start, value.end); const Point2i default_temp = Point2i(default_value.start, default_value.end); + read(node, temp, default_temp); + value.start = temp.x; value.end = temp.y; +} + +/** @brief Writes string to a file storage. + */ +CV_EXPORTS FileStorage& operator << (FileStorage& fs, const String& str); + +//! @cond IGNORED + +namespace internal +{ + class CV_EXPORTS WriteStructContext + { + public: + WriteStructContext(FileStorage& _fs, const String& name, int flags, const String& typeName = String()); + ~WriteStructContext(); + private: + FileStorage* fs; + }; + + template class VecWriterProxy + { + public: + VecWriterProxy( FileStorage* _fs ) : fs(_fs) {} + void operator()(const std::vector<_Tp>& vec) const + { + size_t count = vec.size(); + for (size_t i = 0; i < count; i++) + write(*fs, vec[i]); + } + private: + FileStorage* fs; + }; + + template class VecWriterProxy<_Tp, 1> + { + public: + VecWriterProxy( FileStorage* _fs ) : fs(_fs) {} + void operator()(const std::vector<_Tp>& vec) const + { + int _fmt = traits::SafeFmt<_Tp>::fmt; + char fmt[] = { (char)((_fmt >> 8) + '1'), (char)_fmt, '\0' }; + fs->writeRaw(fmt, !vec.empty() ? (uchar*)&vec[0] : 0, vec.size() * sizeof(_Tp)); + } + private: + FileStorage* fs; + }; + + template class VecReaderProxy + { + public: + VecReaderProxy( FileNodeIterator* _it ) : it(_it) {} + void operator()(std::vector<_Tp>& vec, size_t count) const + { + count = std::min(count, it->remaining()); + vec.resize(count); + for (size_t i = 0; i < count; i++, ++(*it)) + read(**it, vec[i], _Tp()); + } + private: + FileNodeIterator* it; + }; + + template class VecReaderProxy<_Tp, 1> + { + public: + VecReaderProxy( FileNodeIterator* _it ) : it(_it) {} + void operator()(std::vector<_Tp>& vec, size_t count) const + { + size_t remaining = it->remaining(); + size_t cn = DataType<_Tp>::channels; + int _fmt = traits::SafeFmt<_Tp>::fmt; + CV_Assert((_fmt >> 8) < 9); + char fmt[] = { (char)((_fmt >> 8)+'1'), (char)_fmt, '\0' }; + CV_Assert((remaining % cn) == 0); + size_t remaining1 = remaining / cn; + count = count > remaining1 ? remaining1 : count; + vec.resize(count); + it->readRaw(fmt, !vec.empty() ? (uchar*)&vec[0] : 0, count*sizeof(_Tp)); + } + private: + FileNodeIterator* it; + }; + +} // internal + +//! @endcond + +template static inline +void write(FileStorage& fs, const _Tp& value) +{ + write(fs, String(), value); +} + +template<> inline +void write( FileStorage& fs, const int& value ) +{ + writeScalar(fs, value); +} + +template<> inline +void write( FileStorage& fs, const float& value ) +{ + writeScalar(fs, value); +} + +template<> inline +void write( FileStorage& fs, const double& value ) +{ + writeScalar(fs, value); +} + +template<> inline +void write( FileStorage& fs, const String& value ) +{ + writeScalar(fs, value); +} + +template static inline +void write(FileStorage& fs, const Point_<_Tp>& pt ) +{ + write(fs, pt.x); + write(fs, pt.y); +} + +template static inline +void write(FileStorage& fs, const Point3_<_Tp>& pt ) +{ + write(fs, pt.x); + write(fs, pt.y); + write(fs, pt.z); +} + +template static inline +void write(FileStorage& fs, const Size_<_Tp>& sz ) +{ + write(fs, sz.width); + write(fs, sz.height); +} + +template static inline +void write(FileStorage& fs, const Complex<_Tp>& c ) +{ + write(fs, c.re); + write(fs, c.im); +} + +template static inline +void write(FileStorage& fs, const Rect_<_Tp>& r ) +{ + write(fs, r.x); + write(fs, r.y); + write(fs, r.width); + write(fs, r.height); +} + +template static inline +void write(FileStorage& fs, const Vec<_Tp, cn>& v ) +{ + for(int i = 0; i < cn; i++) + write(fs, v.val[i]); +} + +template static inline +void write(FileStorage& fs, const Matx<_Tp, m, n>& x ) +{ + write(fs, Mat(x)); // write as a Mat class +} + +template static inline +void write(FileStorage& fs, const Scalar_<_Tp>& s ) +{ + write(fs, s.val[0]); + write(fs, s.val[1]); + write(fs, s.val[2]); + write(fs, s.val[3]); +} + +static inline +void write(FileStorage& fs, const Range& r ) +{ + write(fs, r.start); + write(fs, r.end); +} + +template static inline +void write( FileStorage& fs, const std::vector<_Tp>& vec ) +{ + cv::internal::VecWriterProxy<_Tp, traits::SafeFmt<_Tp>::fmt != 0> w(&fs); + w(vec); +} + +template static inline +void write(FileStorage& fs, const String& name, const Point_<_Tp>& pt ) +{ + cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); + write(fs, pt); +} + +template static inline +void write(FileStorage& fs, const String& name, const Point3_<_Tp>& pt ) +{ + cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); + write(fs, pt); +} + +template static inline +void write(FileStorage& fs, const String& name, const Size_<_Tp>& sz ) +{ + cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); + write(fs, sz); +} + +template static inline +void write(FileStorage& fs, const String& name, const Complex<_Tp>& c ) +{ + cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); + write(fs, c); +} + +template static inline +void write(FileStorage& fs, const String& name, const Rect_<_Tp>& r ) +{ + cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); + write(fs, r); +} + +template static inline +void write(FileStorage& fs, const String& name, const Vec<_Tp, cn>& v ) +{ + cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); + write(fs, v); +} + +template static inline +void write(FileStorage& fs, const String& name, const Matx<_Tp, m, n>& x ) +{ + write(fs, name, Mat(x)); // write as a Mat class +} + +template static inline +void write(FileStorage& fs, const String& name, const Scalar_<_Tp>& s ) +{ + cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); + write(fs, s); +} + +static inline +void write(FileStorage& fs, const String& name, const Range& r ) +{ + cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); + write(fs, r); +} + +static inline +void write(FileStorage& fs, const String& name, const KeyPoint& kpt) +{ + cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); + write(fs, kpt.pt.x); + write(fs, kpt.pt.y); + write(fs, kpt.size); + write(fs, kpt.angle); + write(fs, kpt.response); + write(fs, kpt.octave); + write(fs, kpt.class_id); +} + +static inline +void write(FileStorage& fs, const String& name, const DMatch& m) +{ + cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); + write(fs, m.queryIdx); + write(fs, m.trainIdx); + write(fs, m.imgIdx); + write(fs, m.distance); +} + +template::value >::type* = nullptr> +static inline void write( FileStorage& fs, const String& name, const _Tp& val ) +{ + write(fs, name, static_cast(val)); +} + +template static inline +void write( FileStorage& fs, const String& name, const std::vector<_Tp>& vec ) +{ + cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+(traits::SafeFmt<_Tp>::fmt != 0 ? FileNode::FLOW : 0)); + write(fs, vec); +} + +template static inline +void write( FileStorage& fs, const String& name, const std::vector< std::vector<_Tp> >& vec ) +{ + cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ); + for(size_t i = 0; i < vec.size(); i++) + { + cv::internal::WriteStructContext ws_(fs, name, FileNode::SEQ+(traits::SafeFmt<_Tp>::fmt != 0 ? FileNode::FLOW : 0)); + write(fs, vec[i]); + } +} + +#ifdef CV__LEGACY_PERSISTENCE +// This code is not needed anymore, but it is preserved here to keep source compatibility +// Implementation is similar to templates instantiations +static inline void write(FileStorage& fs, const KeyPoint& kpt) { write(fs, String(), kpt); } +static inline void write(FileStorage& fs, const DMatch& m) { write(fs, String(), m); } +static inline void write(FileStorage& fs, const std::vector& vec) +{ + cv::internal::VecWriterProxy w(&fs); + w(vec); +} +static inline void write(FileStorage& fs, const std::vector& vec) +{ + cv::internal::VecWriterProxy w(&fs); + w(vec); + +} +#endif + + +static inline +void read(const FileNode& node, bool& value, bool default_value) +{ + int temp; + read(node, temp, (int)default_value); + value = temp != 0; +} + +static inline +void read(const FileNode& node, uchar& value, uchar default_value) +{ + int temp; + read(node, temp, (int)default_value); + value = saturate_cast(temp); +} + +static inline +void read(const FileNode& node, schar& value, schar default_value) +{ + int temp; + read(node, temp, (int)default_value); + value = saturate_cast(temp); +} + +static inline +void read(const FileNode& node, ushort& value, ushort default_value) +{ + int temp; + read(node, temp, (int)default_value); + value = saturate_cast(temp); +} + +static inline +void read(const FileNode& node, short& value, short default_value) +{ + int temp; + read(node, temp, (int)default_value); + value = saturate_cast(temp); +} + +template static inline +void read( FileNodeIterator& it, std::vector<_Tp>& vec, size_t maxCount = (size_t)INT_MAX ) +{ + cv::internal::VecReaderProxy<_Tp, traits::SafeFmt<_Tp>::fmt != 0> r(&it); + r(vec, maxCount); +} + +template::value >::type* = nullptr> +static inline void read(const FileNode& node, _Tp& value, const _Tp& default_value = static_cast<_Tp>(0)) +{ + int temp; + read(node, temp, static_cast(default_value)); + value = static_cast<_Tp>(temp); +} + +template static inline +void read( const FileNode& node, std::vector<_Tp>& vec, const std::vector<_Tp>& default_value = std::vector<_Tp>() ) +{ + if(node.empty()) + vec = default_value; + else + { + FileNodeIterator it = node.begin(); + read( it, vec ); + } +} + +static inline +void read( const FileNode& node, std::vector& vec, const std::vector& default_value ) +{ + if(node.empty()) + vec = default_value; + else + read(node, vec); +} + +static inline +void read( const FileNode& node, std::vector& vec, const std::vector& default_value ) +{ + if(node.empty()) + vec = default_value; + else + read(node, vec); +} + +/** @brief Writes data to a file storage. + */ +template static inline +FileStorage& operator << (FileStorage& fs, const _Tp& value) +{ + if( !fs.isOpened() ) + return fs; + if( fs.state == FileStorage::NAME_EXPECTED + FileStorage::INSIDE_MAP ) + CV_Error( Error::StsError, "No element name has been given" ); + write( fs, fs.elname, value ); + if( fs.state & FileStorage::INSIDE_MAP ) + fs.state = FileStorage::NAME_EXPECTED + FileStorage::INSIDE_MAP; + return fs; +} + +/** @brief Writes data to a file storage. + */ +static inline +FileStorage& operator << (FileStorage& fs, const char* str) +{ + return (fs << String(str)); +} + +/** @brief Writes data to a file storage. + */ +static inline +FileStorage& operator << (FileStorage& fs, char* value) +{ + return (fs << String(value)); +} + +/** @brief Reads data from a file storage. + */ +template static inline +FileNodeIterator& operator >> (FileNodeIterator& it, _Tp& value) +{ + read( *it, value, _Tp()); + return ++it; +} + +/** @brief Reads data from a file storage. + */ +template static inline +FileNodeIterator& operator >> (FileNodeIterator& it, std::vector<_Tp>& vec) +{ + cv::internal::VecReaderProxy<_Tp, traits::SafeFmt<_Tp>::fmt != 0> r(&it); + r(vec, (size_t)INT_MAX); + return it; +} + +/** @brief Reads data from a file storage. + */ +template static inline +void operator >> (const FileNode& n, _Tp& value) +{ + read( n, value, _Tp()); +} + +/** @brief Reads data from a file storage. + */ +template static inline +void operator >> (const FileNode& n, std::vector<_Tp>& vec) +{ + FileNodeIterator it = n.begin(); + it >> vec; +} + +/** @brief Reads KeyPoint from a file storage. +*/ +//It needs special handling because it contains two types of fields, int & float. +static inline +void operator >> (const FileNode& n, KeyPoint& kpt) +{ + FileNodeIterator it = n.begin(); + it >> kpt.pt.x >> kpt.pt.y >> kpt.size >> kpt.angle >> kpt.response >> kpt.octave >> kpt.class_id; +} + +#ifdef CV__LEGACY_PERSISTENCE +static inline +void operator >> (const FileNode& n, std::vector& vec) +{ + read(n, vec); +} +static inline +void operator >> (const FileNode& n, std::vector& vec) +{ + read(n, vec); +} +#endif + +/** @brief Reads DMatch from a file storage. +*/ +//It needs special handling because it contains two types of fields, int & float. +static inline +void operator >> (const FileNode& n, DMatch& m) +{ + FileNodeIterator it = n.begin(); + it >> m.queryIdx >> m.trainIdx >> m.imgIdx >> m.distance; +} + +CV_EXPORTS bool operator == (const FileNodeIterator& it1, const FileNodeIterator& it2); +CV_EXPORTS bool operator != (const FileNodeIterator& it1, const FileNodeIterator& it2); + +static inline +ptrdiff_t operator - (const FileNodeIterator& it1, const FileNodeIterator& it2) +{ + return it2.remaining() - it1.remaining(); +} + +static inline +bool operator < (const FileNodeIterator& it1, const FileNodeIterator& it2) +{ + return it1.remaining() > it2.remaining(); +} + +} // cv + +#endif // OPENCV_CORE_PERSISTENCE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/quaternion.hpp b/3rdParty/opencv-4.11.0/opencv2/core/quaternion.hpp index e39065020c..ab96ce2bae 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/quaternion.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/quaternion.hpp @@ -1,1696 +1,1696 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2020, Huawei Technologies Co., Ltd. All rights reserved. -// Third party copyrights are property of their respective owners. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Author: Liangqian Kong -// Longbu Wang -#ifndef OPENCV_CORE_QUATERNION_HPP -#define OPENCV_CORE_QUATERNION_HPP - -#include -#include -#include -namespace cv -{ -//! @addtogroup core_quaternion -//! @{ - -//! Unit quaternion flag -enum QuatAssumeType -{ - /** - * This flag is specified by default. - * If this flag is specified, the input quaternions are assumed to be not unit quaternions. - * It can guarantee the correctness of the calculations, - * although the calculation speed will be slower than the flag QUAT_ASSUME_UNIT. - */ - QUAT_ASSUME_NOT_UNIT, - /** - * If this flag is specified, the input quaternions are assumed to be unit quaternions which - * will save some computations. However, if this flag is specified without unit quaternion, - * the program correctness of the result will not be guaranteed. - */ - QUAT_ASSUME_UNIT -}; - -class QuatEnum -{ -public: - /** @brief Enum of Euler angles type. - * - * Without considering the possibility of using two different convertions for the definition of the rotation axes , - * there exists twelve possible sequences of rotation axes, divided into two groups: - * - Proper Euler angles (Z-X-Z, X-Y-X, Y-Z-Y, Z-Y-Z, X-Z-X, Y-X-Y) - * - Tait–Bryan angles (X-Y-Z, Y-Z-X, Z-X-Y, X-Z-Y, Z-Y-X, Y-X-Z). - * - * The three elemental rotations may be [extrinsic](https://en.wikipedia.org/wiki/Euler_angles#Definition_by_extrinsic_rotations) - * (rotations about the axes *xyz* of the original coordinate system, which is assumed to remain motionless), - * or [intrinsic](https://en.wikipedia.org/wiki/Euler_angles#Definition_by_intrinsic_rotations)(rotations about the axes of the rotating coordinate system *XYZ*, solidary with the moving body, which changes its orientation after each elemental rotation). - * - * - * Extrinsic and intrinsic rotations are relevant. - * - * The definition of the Euler angles is as following, - * - \f$\theta_1 \f$ represents the first rotation angle, - * - \f$\theta_2 \f$ represents the second rotation angle, - * - \f$\theta_3 \f$ represents the third rotation angle. - * - * For intrinsic rotations in the order of X-Y-Z, the rotation matrix R can be calculated by:\f[R =X(\theta_1) Y(\theta_2) Z(\theta_3) \f] - * For extrinsic rotations in the order of X-Y-Z, the rotation matrix R can be calculated by:\f[R =Z({\theta_3}) Y({\theta_2}) X({\theta_1})\f] - * where - * \f[X({\theta_1})={\begin{bmatrix}1&0&0\\0&\cos {\theta_1} &-\sin {\theta_1} \\0&\sin {\theta_1} &\cos {\theta_1} \\\end{bmatrix}}, - * Y({\theta_2})={\begin{bmatrix}\cos \theta_{2}&0&\sin \theta_{2}\\0&1 &0 \\\ -sin \theta_2& 0&\cos \theta_{2} \\\end{bmatrix}}, - * Z({\theta_3})={\begin{bmatrix}\cos\theta_{3} &-\sin \theta_3&0\\\sin \theta_3 &\cos \theta_3 &0\\0&0&1\\\end{bmatrix}}. - * \f] - * - * The function is designed according to this set of conventions: - * - [Right handed](https://en.wikipedia.org/wiki/Right_hand_rule) reference frames are adopted, and the [right hand rule](https://en.wikipedia.org/wiki/Right_hand_rule) is used to determine the sign of angles. - * - Each matrix is meant to represent an [active rotation](https://en.wikipedia.org/wiki/Active_and_passive_transformation) (the composing and composed matrices - * are supposed to act on the coordinates of vectors defined in the initial fixed reference frame and give as a result the coordinates of a rotated vector defined in the same reference frame). - * - For \f$\theta_1\f$ and \f$\theta_3\f$, the valid range is (−π, π]. - * - * For \f$\theta_2\f$, the valid range is [−π/2, π/2] or [0, π]. - * - * For Tait–Bryan angles, the valid range of \f$\theta_2\f$ is [−π/2, π/2]. When transforming a quaternion to Euler angles, the solution of Euler angles is unique in condition of \f$ \theta_2 \in (−π/2, π/2)\f$ . - * If \f$\theta_2 = −π/2 \f$ or \f$ \theta_2 = π/2\f$, there are infinite solutions. The common name for this situation is gimbal lock. - * For Proper Euler angles,the valid range of \f$\theta_2\f$ is in [0, π]. The solutions of Euler angles are unique in condition of \f$ \theta_2 \in (0, π)\f$ . If \f$\theta_2 =0 \f$ or \f$\theta_2 =π \f$, - * there are infinite solutions and gimbal lock will occur. - */ - enum EulerAnglesType - { - INT_XYZ, ///< Intrinsic rotations with the Euler angles type X-Y-Z - INT_XZY, ///< Intrinsic rotations with the Euler angles type X-Z-Y - INT_YXZ, ///< Intrinsic rotations with the Euler angles type Y-X-Z - INT_YZX, ///< Intrinsic rotations with the Euler angles type Y-Z-X - INT_ZXY, ///< Intrinsic rotations with the Euler angles type Z-X-Y - INT_ZYX, ///< Intrinsic rotations with the Euler angles type Z-Y-X - INT_XYX, ///< Intrinsic rotations with the Euler angles type X-Y-X - INT_XZX, ///< Intrinsic rotations with the Euler angles type X-Z-X - INT_YXY, ///< Intrinsic rotations with the Euler angles type Y-X-Y - INT_YZY, ///< Intrinsic rotations with the Euler angles type Y-Z-Y - INT_ZXZ, ///< Intrinsic rotations with the Euler angles type Z-X-Z - INT_ZYZ, ///< Intrinsic rotations with the Euler angles type Z-Y-Z - - EXT_XYZ, ///< Extrinsic rotations with the Euler angles type X-Y-Z - EXT_XZY, ///< Extrinsic rotations with the Euler angles type X-Z-Y - EXT_YXZ, ///< Extrinsic rotations with the Euler angles type Y-X-Z - EXT_YZX, ///< Extrinsic rotations with the Euler angles type Y-Z-X - EXT_ZXY, ///< Extrinsic rotations with the Euler angles type Z-X-Y - EXT_ZYX, ///< Extrinsic rotations with the Euler angles type Z-Y-X - EXT_XYX, ///< Extrinsic rotations with the Euler angles type X-Y-X - EXT_XZX, ///< Extrinsic rotations with the Euler angles type X-Z-X - EXT_YXY, ///< Extrinsic rotations with the Euler angles type Y-X-Y - EXT_YZY, ///< Extrinsic rotations with the Euler angles type Y-Z-Y - EXT_ZXZ, ///< Extrinsic rotations with the Euler angles type Z-X-Z - EXT_ZYZ, ///< Extrinsic rotations with the Euler angles type Z-Y-Z - #ifndef CV_DOXYGEN - EULER_ANGLES_MAX_VALUE - #endif - }; - -}; - -template class Quat; -template std::ostream& operator<<(std::ostream&, const Quat<_Tp>&); - -/** - * Quaternion is a number system that extends the complex numbers. It can be expressed as a - * rotation in three-dimensional space. - * A quaternion is generally represented in the form: - * \f[q = w + x\boldsymbol{i} + y\boldsymbol{j} + z\boldsymbol{k}\f] - * \f[q = [w, x, y, z]\f] - * \f[q = [w, \boldsymbol{v}] \f] - * \f[q = ||q||[\cos\psi, u_x\sin\psi,u_y\sin\psi, u_z\sin\psi].\f] - * \f[q = ||q||[\cos\psi, \boldsymbol{u}\sin\psi]\f] - * where \f$\psi = \frac{\theta}{2}\f$, \f$\theta\f$ represents rotation angle, - * \f$\boldsymbol{u} = [u_x, u_y, u_z]\f$ represents normalized rotation axis, - * and \f$||q||\f$ represents the norm of \f$q\f$. - * - * A unit quaternion is usually represents rotation, which has the form: - * \f[q = [\cos\psi, u_x\sin\psi,u_y\sin\psi, u_z\sin\psi].\f] - * - * To create a quaternion representing the rotation around the axis \f$\boldsymbol{u}\f$ - * with angle \f$\theta\f$, you can use - * ``` - * using namespace cv; - * double angle = CV_PI; - * Vec3d axis = {0, 0, 1}; - * Quatd q = Quatd::createFromAngleAxis(angle, axis); - * ``` - * - * You can simply use four same type number to create a quaternion - * ``` - * Quatd q(1, 2, 3, 4); - * ``` - * Or use a Vec4d or Vec4f vector. - * ``` - * Vec4d vec{1, 2, 3, 4}; - * Quatd q(vec); - * ``` - * - * ``` - * Vec4f vec{1, 2, 3, 4}; - * Quatf q(vec); - * ``` - * - * If you already have a 3x3 rotation matrix R, then you can use - * ``` - * Quatd q = Quatd::createFromRotMat(R); - * ``` - * - * If you already have a rotation vector rvec which has the form of `angle * axis`, then you can use - * ``` - * Quatd q = Quatd::createFromRvec(rvec); - * ``` - * - * To extract the rotation matrix from quaternion, see toRotMat3x3() - * - * To extract the Vec4d or Vec4f, see toVec() - * - * To extract the rotation vector, see toRotVec() - * - * If there are two quaternions \f$q_0, q_1\f$ are needed to interpolate, you can use nlerp(), slerp() or spline() - * ``` - * Quatd::nlerp(q0, q1, t) - * - * Quatd::slerp(q0, q1, t) - * - * Quatd::spline(q0, q0, q1, q1, t) - * ``` - * spline can smoothly connect rotations of multiple quaternions - * - * Three ways to get an element in Quaternion - * ``` - * Quatf q(1,2,3,4); - * std::cout << q.w << std::endl; // w=1, x=2, y=3, z=4 - * std::cout << q[0] << std::endl; // q[0]=1, q[1]=2, q[2]=3, q[3]=4 - * std::cout << q.at(0) << std::endl; - * ``` - */ -template -class Quat -{ - static_assert(std::is_floating_point<_Tp>::value, "Quaternion only make sense with type of float or double"); - using value_type = _Tp; -public: - static constexpr _Tp CV_QUAT_EPS = (_Tp)1.e-6; - static constexpr _Tp CV_QUAT_CONVERT_THRESHOLD = (_Tp)1.e-6; - - Quat(); - - /** - * @brief From Vec4d or Vec4f. - */ - explicit Quat(const Vec<_Tp, 4> &coeff); - - /** - * @brief from four numbers. - */ - Quat(_Tp w, _Tp x, _Tp y, _Tp z); - - /** - * @brief from an angle, axis. Axis will be normalized in this function. And - * it generates - * \f[q = [\cos\psi, u_x\sin\psi,u_y\sin\psi, u_z\sin\psi].\f] - * where \f$\psi = \frac{\theta}{2}\f$, \f$\theta\f$ is the rotation angle. - */ - static Quat<_Tp> createFromAngleAxis(const _Tp angle, const Vec<_Tp, 3> &axis); - - /** - * @brief from a 3x3 rotation matrix. - */ - static Quat<_Tp> createFromRotMat(InputArray R); - - /** - * @brief from a rotation vector - * \f$r\f$ has the form \f$\theta \cdot \boldsymbol{u}\f$, where \f$\theta\f$ - * represents rotation angle and \f$\boldsymbol{u}\f$ represents normalized rotation axis. - * - * Angle and axis could be easily derived as: - * \f[ - * \begin{equation} - * \begin{split} - * \psi &= ||r||\\ - * \boldsymbol{u} &= \frac{r}{\theta} - * \end{split} - * \end{equation} - * \f] - * Then a quaternion can be calculated by - * \f[q = [\cos\psi, \boldsymbol{u}\sin\psi]\f] - * where \f$\psi = \theta / 2 \f$ - */ - static Quat<_Tp> createFromRvec(InputArray rvec); - - /** - * @brief - * from Euler angles - * - * A quaternion can be generated from Euler angles by combining the quaternion representations of the Euler rotations. - * - * For example, if we use intrinsic rotations in the order of X-Y-Z,\f$\theta_1 \f$ is rotation around the X-axis, \f$\theta_2 \f$ is rotation around the Y-axis, - * \f$\theta_3 \f$ is rotation around the Z-axis. The final quaternion q can be calculated by - * - * \f[ {q} = q_{X, \theta_1} q_{Y, \theta_2} q_{Z, \theta_3}\f] - * where \f$ q_{X, \theta_1} \f$ is created from @ref createFromXRot, \f$ q_{Y, \theta_2} \f$ is created from @ref createFromYRot, - * \f$ q_{Z, \theta_3} \f$ is created from @ref createFromZRot. - * @param angles the Euler angles in a vector of length 3 - * @param eulerAnglesType the convertion Euler angles type - */ - static Quat<_Tp> createFromEulerAngles(const Vec<_Tp, 3> &angles, QuatEnum::EulerAnglesType eulerAnglesType); - - /** - * @brief get a quaternion from a rotation about the Y-axis by \f$\theta\f$ . - * \f[q = \cos(\theta/2)+0 i+ sin(\theta/2) j +0k \f] - */ - static Quat<_Tp> createFromYRot(const _Tp theta); - - /** - * @brief get a quaternion from a rotation about the X-axis by \f$\theta\f$ . - * \f[q = \cos(\theta/2)+sin(\theta/2) i +0 j +0 k \f] - */ - static Quat<_Tp> createFromXRot(const _Tp theta); - - /** - * @brief get a quaternion from a rotation about the Z-axis by \f$\theta\f$. - * \f[q = \cos(\theta/2)+0 i +0 j +sin(\theta/2) k \f] - */ - static Quat<_Tp> createFromZRot(const _Tp theta); - - /** - * @brief a way to get element. - * @param index over a range [0, 3]. - * - * A quaternion q - * - * q.at(0) is equivalent to q.w, - * - * q.at(1) is equivalent to q.x, - * - * q.at(2) is equivalent to q.y, - * - * q.at(3) is equivalent to q.z. - */ - _Tp at(size_t index) const; - - /** - * @brief return the conjugate of this quaternion. - * \f[q.conjugate() = (w, -x, -y, -z).\f] - */ - Quat<_Tp> conjugate() const; - - /** - * - * @brief return the value of exponential value. - * \f[\exp(q) = e^w (\cos||\boldsymbol{v}||+ \frac{v}{||\boldsymbol{v}||})\sin||\boldsymbol{v}||\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * @param q a quaternion. - * - * For example: - * ``` - * Quatd q{1,2,3,4}; - * cout << exp(q) << endl; - * ``` - */ - template - friend Quat exp(const Quat &q); - - /** - * @brief return the value of exponential value. - * \f[\exp(q) = e^w (\cos||\boldsymbol{v}||+ \frac{v}{||\boldsymbol{v}||}\sin||\boldsymbol{v}||)\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * - * For example - * ``` - * Quatd q{1,2,3,4}; - * cout << q.exp() << endl; - * ``` - */ - Quat<_Tp> exp() const; - - /** - * @brief return the value of logarithm function. - * \f[\ln(q) = \ln||q|| + \frac{\boldsymbol{v}}{||\boldsymbol{v}||}\arccos\frac{w}{||q||}.\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * @param q a quaternion. - * @param assumeUnit if QUAT_ASSUME_UNIT, q assume to be a unit quaternion and this function will save some computations. - * - * For example - * ``` - * Quatd q1{1,2,3,4}; - * cout << log(q1) << endl; - * ``` - */ - template - friend Quat log(const Quat &q, QuatAssumeType assumeUnit); - - /** - * @brief return the value of logarithm function. - * \f[\ln(q) = \ln||q|| + \frac{\boldsymbol{v}}{||\boldsymbol{v}||}\arccos\frac{w}{||q||}\f]. - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and this function will save some computations. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.log(); - * - * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; - * Quatd q1(1,2,3,4); - * q1.normalize().log(assumeUnit); - * ``` - */ - Quat<_Tp> log(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief return the value of power function with index \f$x\f$. - * \f[q^x = ||q||(cos(x\theta) + \boldsymbol{u}sin(x\theta))).\f] - * @param q a quaternion. - * @param x index of exponentiation. - * @param assumeUnit if QUAT_ASSUME_UNIT, quaternion q assume to be a unit quaternion and this function will save some computations. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * power(q, 2.0); - * - * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; - * double angle = CV_PI; - * Vec3d axis{0, 0, 1}; - * Quatd q1 = Quatd::createFromAngleAxis(angle, axis); //generate a unit quat by axis and angle - * power(q1, 2.0, assumeUnit);//This assumeUnit means q1 is a unit quaternion. - * ``` - * @note the type of the index should be the same as the quaternion. - */ - template - friend Quat power(const Quat &q, const T x, QuatAssumeType assumeUnit); - - /** - * @brief return the value of power function with index \f$x\f$. - * \f[q^x = ||q||(\cos(x\theta) + \boldsymbol{u}\sin(x\theta))).\f] - * @param x index of exponentiation. - * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and this function will save some computations. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.power(2.0); - * - * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; - * double angle = CV_PI; - * Vec3d axis{0, 0, 1}; - * Quatd q1 = Quatd::createFromAngleAxis(angle, axis); //generate a unit quat by axis and angle - * q1.power(2.0, assumeUnit); //This assumeUnt means q1 is a unit quaternion - * ``` - */ - Quat<_Tp> power(const _Tp x, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief return \f$\sqrt{q}\f$. - * @param q a quaternion. - * @param assumeUnit if QUAT_ASSUME_UNIT, quaternion q assume to be a unit quaternion and this function will save some computations. - * - * For example - * ``` - * Quatf q(1,2,3,4); - * sqrt(q); - * - * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; - * q = {1,0,0,0}; - * sqrt(q, assumeUnit); //This assumeUnit means q is a unit quaternion. - * ``` - */ - template - friend Quat sqrt(const Quat &q, QuatAssumeType assumeUnit); - - /** - * @brief return \f$\sqrt{q}\f$. - * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and this function will save some computations. - * - * For example - * ``` - * Quatf q(1,2,3,4); - * q.sqrt(); - * - * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; - * q = {1,0,0,0}; - * q.sqrt(assumeUnit); //This assumeUnit means q is a unit quaternion - * ``` - */ - Quat<_Tp> sqrt(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief return the value of power function with quaternion \f$q\f$. - * \f[p^q = e^{q\ln(p)}.\f] - * @param p base quaternion of power function. - * @param q index quaternion of power function. - * @param assumeUnit if QUAT_ASSUME_UNIT, quaternion \f$p\f$ assume to be a unit quaternion and this function will save some computations. - * - * For example - * ``` - * Quatd p(1,2,3,4); - * Quatd q(5,6,7,8); - * power(p, q); - * - * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; - * p = p.normalize(); - * power(p, q, assumeUnit); //This assumeUnit means p is a unit quaternion - * ``` - */ - template - friend Quat power(const Quat &p, const Quat &q, QuatAssumeType assumeUnit); - - /** - * @brief return the value of power function with quaternion \f$q\f$. - * \f[p^q = e^{q\ln(p)}.\f] - * @param q index quaternion of power function. - * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and this function will save some computations. - * - * For example - * ``` - * Quatd p(1,2,3,4); - * Quatd q(5,6,7,8); - * p.power(q); - * - * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; - * p = p.normalize(); - * p.power(q, assumeUnit); //This assumeUnit means p is a unit quaternion - * ``` - */ - Quat<_Tp> power(const Quat<_Tp> &q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief return the crossProduct between \f$p = (a, b, c, d) = (a, \boldsymbol{u})\f$ and \f$q = (w, x, y, z) = (w, \boldsymbol{v})\f$. - * \f[p \times q = \frac{pq- qp}{2}\f] - * \f[p \times q = \boldsymbol{u} \times \boldsymbol{v}\f] - * \f[p \times q = (cz-dy)i + (dx-bz)j + (by-xc)k \f] - * - * For example - * ``` - * Quatd q{1,2,3,4}; - * Quatd p{5,6,7,8}; - * crossProduct(p, q); - * ``` - */ - template - friend Quat crossProduct(const Quat &p, const Quat &q); - - /** - * @brief return the crossProduct between \f$p = (a, b, c, d) = (a, \boldsymbol{u})\f$ and \f$q = (w, x, y, z) = (w, \boldsymbol{v})\f$. - * \f[p \times q = \frac{pq- qp}{2}.\f] - * \f[p \times q = \boldsymbol{u} \times \boldsymbol{v}.\f] - * \f[p \times q = (cz-dy)i + (dx-bz)j + (by-xc)k. \f] - * - * For example - * ``` - * Quatd q{1,2,3,4}; - * Quatd p{5,6,7,8}; - * p.crossProduct(q) - * ``` - */ - Quat<_Tp> crossProduct(const Quat<_Tp> &q) const; - - /** - * @brief return the norm of quaternion. - * \f[||q|| = \sqrt{w^2 + x^2 + y^2 + z^2}.\f] - */ - _Tp norm() const; - - /** - * @brief return a normalized \f$p\f$. - * \f[p = \frac{q}{||q||}\f] - * where \f$p\f$ satisfies \f$(p.x)^2 + (p.y)^2 + (p.z)^2 + (p.w)^2 = 1.\f$ - */ - Quat<_Tp> normalize() const; - - /** - * @brief return \f$q^{-1}\f$ which is an inverse of \f$q\f$ - * which satisfies \f$q * q^{-1} = 1\f$. - * @param q a quaternion. - * @param assumeUnit if QUAT_ASSUME_UNIT, quaternion q assume to be a unit quaternion and this function will save some computations. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * inv(q); - * - * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; - * q = q.normalize(); - * inv(q, assumeUnit);//This assumeUnit means p is a unit quaternion - * ``` - */ - template - friend Quat inv(const Quat &q, QuatAssumeType assumeUnit); - - /** - * @brief return \f$q^{-1}\f$ which is an inverse of \f$q\f$ - * satisfying \f$q * q^{-1} = 1\f$. - * @param assumeUnit if QUAT_ASSUME_UNIT, quaternion q assume to be a unit quaternion and this function will save some computations. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.inv(); - * - * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; - * q = q.normalize(); - * q.inv(assumeUnit); //assumeUnit means p is a unit quaternion - * ``` - */ - Quat<_Tp> inv(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief return sinh value of quaternion q, sinh could be calculated as: - * \f[\sinh(p) = \sin(w)\cos(||\boldsymbol{v}||) + \cosh(w)\frac{v}{||\boldsymbol{v}||}\sin||\boldsymbol{v}||\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * @param q a quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * sinh(q); - * ``` - */ - template - friend Quat sinh(const Quat &q); - - /** - * @brief return sinh value of this quaternion, sinh could be calculated as: - * \f$\sinh(p) = \sin(w)\cos(||\boldsymbol{v}||) + \cosh(w)\frac{v}{||\boldsymbol{v}||}\sin||\boldsymbol{v}||\f$ - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.sinh(); - * ``` - */ - Quat<_Tp> sinh() const; - - /** - * @brief return cosh value of quaternion q, cosh could be calculated as: - * \f[\cosh(p) = \cosh(w) * \cos(||\boldsymbol{v}||) + \sinh(w)\frac{\boldsymbol{v}}{||\boldsymbol{v}||}\sin(||\boldsymbol{v}||)\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * @param q a quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * cosh(q); - * ``` - */ - template - friend Quat cosh(const Quat &q); - - /** - * @brief return cosh value of this quaternion, cosh could be calculated as: - * \f[\cosh(p) = \cosh(w) * \cos(||\boldsymbol{v}||) + \sinh(w)\frac{\boldsymbol{v}}{||\boldsymbol{v}||}sin(||\boldsymbol{v}||)\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.cosh(); - * ``` - */ - Quat<_Tp> cosh() const; - - /** - * @brief return tanh value of quaternion q, tanh could be calculated as: - * \f[ \tanh(q) = \frac{\sinh(q)}{\cosh(q)}.\f] - * @param q a quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * tanh(q); - * ``` - * @sa sinh, cosh - */ - template - friend Quat tanh(const Quat &q); - - /** - * @brief return tanh value of this quaternion, tanh could be calculated as: - * \f[ \tanh(q) = \frac{\sinh(q)}{\cosh(q)}.\f] - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.tanh(); - * ``` - * @sa sinh, cosh - */ - Quat<_Tp> tanh() const; - - /** - * @brief return tanh value of quaternion q, sin could be calculated as: - * \f[\sin(p) = \sin(w) * \cosh(||\boldsymbol{v}||) + \cos(w)\frac{\boldsymbol{v}}{||\boldsymbol{v}||}\sinh(||\boldsymbol{v}||)\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * @param q a quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * sin(q); - * ``` - */ - template - friend Quat sin(const Quat &q); - - /** - * @brief return sin value of this quaternion, sin could be calculated as: - * \f[\sin(p) = \sin(w) * \cosh(||\boldsymbol{v}||) + \cos(w)\frac{\boldsymbol{v}}{||\boldsymbol{v}||}\sinh(||\boldsymbol{v}||)\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.sin(); - * ``` - */ - Quat<_Tp> sin() const; - - /** - * @brief return sin value of quaternion q, cos could be calculated as: - * \f[\cos(p) = \cos(w) * \cosh(||\boldsymbol{v}||) - \sin(w)\frac{\boldsymbol{v}}{||\boldsymbol{v}||}\sinh(||\boldsymbol{v}||)\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * @param q a quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * cos(q); - * ``` - */ - template - friend Quat cos(const Quat &q); - - /** - * @brief return cos value of this quaternion, cos could be calculated as: - * \f[\cos(p) = \cos(w) * \cosh(||\boldsymbol{v}||) - \sin(w)\frac{\boldsymbol{v}}{||\boldsymbol{v}||}\sinh(||\boldsymbol{v}||)\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.cos(); - * ``` - */ - Quat<_Tp> cos() const; - - /** - * @brief return tan value of quaternion q, tan could be calculated as: - * \f[\tan(q) = \frac{\sin(q)}{\cos(q)}.\f] - * @param q a quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * tan(q); - * ``` - */ - template - friend Quat tan(const Quat &q); - - /** - * @brief return tan value of this quaternion, tan could be calculated as: - * \f[\tan(q) = \frac{\sin(q)}{\cos(q)}.\f] - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.tan(); - * ``` - */ - Quat<_Tp> tan() const; - - /** - * @brief return arcsin value of quaternion q, arcsin could be calculated as: - * \f[\arcsin(q) = -\frac{\boldsymbol{v}}{||\boldsymbol{v}||}arcsinh(q\frac{\boldsymbol{v}}{||\boldsymbol{v}||})\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * @param q a quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * asin(q); - * ``` - */ - template - friend Quat asin(const Quat &q); - - /** - * @brief return arcsin value of this quaternion, arcsin could be calculated as: - * \f[\arcsin(q) = -\frac{\boldsymbol{v}}{||\boldsymbol{v}||}arcsinh(q\frac{\boldsymbol{v}}{||\boldsymbol{v}||})\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.asin(); - * ``` - */ - Quat<_Tp> asin() const; - - /** - * @brief return arccos value of quaternion q, arccos could be calculated as: - * \f[\arccos(q) = -\frac{\boldsymbol{v}}{||\boldsymbol{v}||}arccosh(q)\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * @param q a quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * acos(q); - * ``` - */ - template - friend Quat acos(const Quat &q); - - /** - * @brief return arccos value of this quaternion, arccos could be calculated as: - * \f[\arccos(q) = -\frac{\boldsymbol{v}}{||\boldsymbol{v}||}arccosh(q)\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.acos(); - * ``` - */ - Quat<_Tp> acos() const; - - /** - * @brief return arctan value of quaternion q, arctan could be calculated as: - * \f[\arctan(q) = -\frac{\boldsymbol{v}}{||\boldsymbol{v}||}arctanh(q\frac{\boldsymbol{v}}{||\boldsymbol{v}||})\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * @param q a quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * atan(q); - * ``` - */ - template - friend Quat atan(const Quat &q); - - /** - * @brief return arctan value of this quaternion, arctan could be calculated as: - * \f[\arctan(q) = -\frac{\boldsymbol{v}}{||\boldsymbol{v}||}arctanh(q\frac{\boldsymbol{v}}{||\boldsymbol{v}||})\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.atan(); - * ``` - */ - Quat<_Tp> atan() const; - - /** - * @brief return arcsinh value of quaternion q, arcsinh could be calculated as: - * \f[arcsinh(q) = \ln(q + \sqrt{q^2 + 1})\f]. - * @param q a quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * asinh(q); - * ``` - */ - template - friend Quat asinh(const Quat &q); - - /** - * @brief return arcsinh value of this quaternion, arcsinh could be calculated as: - * \f[arcsinh(q) = \ln(q + \sqrt{q^2 + 1})\f]. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.asinh(); - * ``` - */ - Quat<_Tp> asinh() const; - - /** - * @brief return arccosh value of quaternion q, arccosh could be calculated as: - * \f[arccosh(q) = \ln(q + \sqrt{q^2 - 1})\f]. - * @param q a quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * acosh(q); - * ``` - */ - template - friend Quat acosh(const Quat &q); - - /** - * @brief return arccosh value of this quaternion, arccosh could be calculated as: - * \f[arcosh(q) = \ln(q + \sqrt{q^2 - 1})\f]. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.acosh(); - * ``` - */ - Quat<_Tp> acosh() const; - - /** - * @brief return arctanh value of quaternion q, arctanh could be calculated as: - * \f[arctanh(q) = \frac{\ln(q + 1) - \ln(1 - q)}{2}\f]. - * @param q a quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * atanh(q); - * ``` - */ - template - friend Quat atanh(const Quat &q); - - /** - * @brief return arctanh value of this quaternion, arctanh could be calculated as: - * \f[arcsinh(q) = \frac{\ln(q + 1) - \ln(1 - q)}{2}\f]. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.atanh(); - * ``` - */ - Quat<_Tp> atanh() const; - - /** - * @brief return true if this quaternion is a unit quaternion. - * @param eps tolerance scope of normalization. The eps could be defined as - * - * \f[eps = |1 - dotValue|\f] where \f[dotValue = (this.w^2 + this.x^2 + this,y^2 + this.z^2).\f] - * And this function will consider it is normalized when the dotValue over a range \f$[1-eps, 1+eps]\f$. - */ - bool isNormal(_Tp eps=CV_QUAT_EPS) const; - - /** - * @brief to throw an error if this quaternion is not a unit quaternion. - * @param eps tolerance scope of normalization. - * @sa isNormal - */ - void assertNormal(_Tp eps=CV_QUAT_EPS) const; - - /** - * @brief transform a quaternion to a 3x3 rotation matrix. - * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and - * this function will save some computations. Otherwise, this function will normalize this - * quaternion at first then do the transformation. - * - * @note Matrix A which is to be rotated should have the form - * \f[\begin{bmatrix} - * x_0& x_1& x_2&...&x_n\\ - * y_0& y_1& y_2&...&y_n\\ - * z_0& z_1& z_2&...&z_n - * \end{bmatrix}\f] - * where the same subscript represents a point. The shape of A assume to be [3, n] - * The points matrix A can be rotated by toRotMat3x3() * A. - * The result has 3 rows and n columns too. - - * For example - * ``` - * double angle = CV_PI; - * Vec3d axis{0,0,1}; - * Quatd q_unit = Quatd::createFromAngleAxis(angle, axis); //quaternion could also be get by interpolation by two or more quaternions. - * - * //assume there is two points (1,0,0) and (1,0,1) to be rotated - * Mat pointsA = (Mat_(2, 3) << 1,0,0,1,0,1); - * //change the shape - * pointsA = pointsA.t(); - * // rotate 180 degrees around the z axis - * Mat new_point = q_unit.toRotMat3x3() * pointsA; - * // print two points - * cout << new_point << endl; - * ``` - */ - Matx<_Tp, 3, 3> toRotMat3x3(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief transform a quaternion to a 4x4 rotation matrix. - * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and - * this function will save some computations. Otherwise, this function will normalize this - * quaternion at first then do the transformation. - * - * The operations is similar as toRotMat3x3 - * except that the points matrix should have the form - * \f[\begin{bmatrix} - * x_0& x_1& x_2&...&x_n\\ - * y_0& y_1& y_2&...&y_n\\ - * z_0& z_1& z_2&...&z_n\\ - * 0&0&0&...&0 - * \end{bmatrix}\f] - * - * @sa toRotMat3x3 - */ - - Matx<_Tp, 4, 4> toRotMat4x4(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief transform the this quaternion to a Vec. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.toVec(); - * ``` - */ - Vec<_Tp, 4> toVec() const; - - /** - * @brief transform this quaternion to a Rotation vector. - * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and - * this function will save some computations. - * Rotation vector rVec is defined as: - * \f[ rVec = [\theta v_x, \theta v_y, \theta v_z]\f] - * where \f$\theta\f$ represents rotation angle, and \f$\boldsymbol{v}\f$ represents the normalized rotation axis. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.toRotVec(); - * - * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; - * q.normalize().toRotVec(assumeUnit); //answer is same as q.toRotVec(). - * ``` - */ - Vec<_Tp, 3> toRotVec(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief get the angle of quaternion, it returns the rotation angle. - * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and - * this function will save some computations. - * \f[\psi = 2 *arccos(\frac{w}{||q||})\f] - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.getAngle(); - * - * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; - * q.normalize().getAngle(assumeUnit);//same as q.getAngle(). - * ``` - * @note It always return the value between \f$[0, 2\pi]\f$. - */ - _Tp getAngle(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief get the axis of quaternion, it returns a vector of length 3. - * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and - * this function will save some computations. - * - * the unit axis \f$\boldsymbol{u}\f$ is defined by - * \f[\begin{equation} - * \begin{split} - * \boldsymbol{v} - * &= \boldsymbol{u} ||\boldsymbol{v}||\\ - * &= \boldsymbol{u}||q||sin(\frac{\theta}{2}) - * \end{split} - * \end{equation}\f] - * where \f$v=[x, y ,z]\f$ and \f$\theta\f$ represents rotation angle. - * - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.getAxis(); - * - * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; - * q.normalize().getAxis(assumeUnit);//same as q.getAxis() - * ``` - */ - Vec<_Tp, 3> getAxis(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief return the dot between quaternion \f$q\f$ and this quaternion. - * - * dot(p, q) is a good metric of how close the quaternions are. - * Indeed, consider the unit quaternion difference \f$p^{-1} * q\f$, its real part is dot(p, q). - * At the same time its real part is equal to \f$\cos(\beta/2)\f$ where \f$\beta\f$ is - * an angle of rotation between p and q, i.e., - * Therefore, the closer dot(p, q) to 1, - * the smaller rotation between them. - * \f[p \cdot q = p.w \cdot q.w + p.x \cdot q.x + p.y \cdot q.y + p.z \cdot q.z\f] - * @param q the other quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * Quatd p(5,6,7,8); - * p.dot(q); - * ``` - */ - _Tp dot(Quat<_Tp> q) const; - - /** - * @brief To calculate the interpolation from \f$q_0\f$ to \f$q_1\f$ by Linear Interpolation(Nlerp) - * For two quaternions, this interpolation curve can be displayed as: - * \f[Lerp(q_0, q_1, t) = (1 - t)q_0 + tq_1.\f] - * Obviously, the lerp will interpolate along a straight line if we think of \f$q_0\f$ and \f$q_1\f$ as a vector - * in a two-dimensional space. When \f$t = 0\f$, it returns \f$q_0\f$ and when \f$t= 1\f$, it returns \f$q_1\f$. - * \f$t\f$ should to be ranged in \f$[0, 1]\f$ normally. - * @param q0 a quaternion used in linear interpolation. - * @param q1 a quaternion used in linear interpolation. - * @param t percent of vector \f$\overrightarrow{q_0q_1}\f$ over a range [0, 1]. - * @note it returns a non-unit quaternion. - */ - static Quat<_Tp> lerp(const Quat<_Tp> &q0, const Quat &q1, const _Tp t); - - /** - * @brief To calculate the interpolation from \f$q_0\f$ to \f$q_1\f$ by Normalized Linear Interpolation(Nlerp). - * it returns a normalized quaternion of Linear Interpolation(Lerp). - * \f[ Nlerp(q_0, q_1, t) = \frac{(1 - t)q_0 + tq_1}{||(1 - t)q_0 + tq_1||}.\f] - * The interpolation will always choose the shortest path but the constant speed is not guaranteed. - * @param q0 a quaternion used in normalized linear interpolation. - * @param q1 a quaternion used in normalized linear interpolation. - * @param t percent of vector \f$\overrightarrow{q_0q_1}\f$ over a range [0, 1]. - * @param assumeUnit if QUAT_ASSUME_UNIT, all input quaternions assume to be unit quaternion. Otherwise, all inputs - quaternion will be normalized inside the function. - * @sa lerp - */ - static Quat<_Tp> nlerp(const Quat<_Tp> &q0, const Quat &q1, const _Tp t, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); - - /** - @brief To calculate the interpolation between \f$q_0\f$ and \f$q_1\f$ by Spherical Linear - Interpolation(Slerp), which can be defined as: - \f[ Slerp(q_0, q_1, t) = \frac{\sin((1-t)\theta)}{\sin(\theta)}q_0 + \frac{\sin(t\theta)}{\sin(\theta)}q_1\f] - where \f$\theta\f$ can be calculated as: - \f[\theta=cos^{-1}(q_0\cdot q_1)\f] - resulting from the both of their norm is unit. - @param q0 a quaternion used in Slerp. - @param q1 a quaternion used in Slerp. - @param t percent of angle between \f$q_0\f$ and \f$q_1\f$ over a range [0, 1]. - @param assumeUnit if QUAT_ASSUME_UNIT, all input quaternions assume to be unit quaternions. Otherwise, all input - quaternions will be normalized inside the function. - @param directChange if QUAT_ASSUME_UNIT, the interpolation will choose the nearest path. - @note If the interpolation angle is small, the error between Nlerp and Slerp is not so large. To improve efficiency and - avoid zero division error, we use Nlerp instead of Slerp. - */ - static Quat<_Tp> slerp(const Quat<_Tp> &q0, const Quat &q1, const _Tp t, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT, bool directChange=true); - - /** - * @brief To calculate the interpolation between \f$q_0\f$,\f$q_1\f$,\f$q_2\f$,\f$q_3\f$ by Spherical and quadrangle(Squad). This could be defined as: - * \f[Squad(q_i, s_i, s_{i+1}, q_{i+1}, t) = Slerp(Slerp(q_i, q_{i+1}, t), Slerp(s_i, s_{i+1}, t), 2t(1-t))\f] - * where - * \f[s_i = q_i\exp(-\frac{\log(q^*_iq_{i+1}) + \log(q^*_iq_{i-1})}{4})\f] - * - * The Squad expression is analogous to the \f$B\acute{e}zier\f$ curve, but involves spherical linear - * interpolation instead of simple linear interpolation. Each \f$s_i\f$ needs to be calculated by three - * quaternions. - * - * @param q0 the first quaternion. - * @param s0 the second quaternion. - * @param s1 the third quaternion. - * @param q1 thr fourth quaternion. - * @param t interpolation parameter of quadratic and linear interpolation over a range \f$[0, 1]\f$. - * @param assumeUnit if QUAT_ASSUME_UNIT, all input quaternions assume to be unit quaternion. Otherwise, all input - * quaternions will be normalized inside the function. - * @param directChange if QUAT_ASSUME_UNIT, squad will find the nearest path to interpolate. - * @sa interPoint, spline - */ - static Quat<_Tp> squad(const Quat<_Tp> &q0, const Quat<_Tp> &s0, - const Quat<_Tp> &s1, const Quat<_Tp> &q1, - const _Tp t, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT, - bool directChange=true); - - /** - * @brief This is the part calculation of squad. - * To calculate the intermedia quaternion \f$s_i\f$ between each three quaternion - * \f[s_i = q_i\exp(-\frac{\log(q^*_iq_{i+1}) + \log(q^*_iq_{i-1})}{4}).\f] - * @param q0 the first quaternion. - * @param q1 the second quaternion. - * @param q2 the third quaternion. - * @param assumeUnit if QUAT_ASSUME_UNIT, all input quaternions assume to be unit quaternion. Otherwise, all input - * quaternions will be normalized inside the function. - * @sa squad - */ - static Quat<_Tp> interPoint(const Quat<_Tp> &q0, const Quat<_Tp> &q1, - const Quat<_Tp> &q2, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); - - /** - * @brief to calculate a quaternion which is the result of a \f$C^1\f$ continuous - * spline curve constructed by squad at the ratio t. Here, the interpolation values are - * between \f$q_1\f$ and \f$q_2\f$. \f$q_0\f$ and \f$q_2\f$ are used to ensure the \f$C^1\f$ - * continuity. if t = 0, it returns \f$q_1\f$, if t = 1, it returns \f$q_2\f$. - * @param q0 the first input quaternion to ensure \f$C^1\f$ continuity. - * @param q1 the second input quaternion. - * @param q2 the third input quaternion. - * @param q3 the fourth input quaternion the same use of \f$q1\f$. - * @param t ratio over a range [0, 1]. - * @param assumeUnit if QUAT_ASSUME_UNIT, \f$q_0, q_1, q_2, q_3\f$ assume to be unit quaternion. Otherwise, all input - * quaternions will be normalized inside the function. - * - * For example: - * - * If there are three double quaternions \f$v_0, v_1, v_2\f$ waiting to be interpolated. - * - * Interpolation between \f$v_0\f$ and \f$v_1\f$ with a ratio \f$t_0\f$ could be calculated as - * ``` - * Quatd::spline(v0, v0, v1, v2, t0); - * ``` - * Interpolation between \f$v_1\f$ and \f$v_2\f$ with a ratio \f$t_0\f$ could be calculated as - * ``` - * Quatd::spline(v0, v1, v2, v2, t0); - * ``` - * @sa squad, slerp - */ - static Quat<_Tp> spline(const Quat<_Tp> &q0, const Quat<_Tp> &q1, - const Quat<_Tp> &q2, const Quat<_Tp> &q3, - const _Tp t, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); - - /** - * @brief Return opposite quaternion \f$-p\f$ - * which satisfies \f$p + (-p) = 0.\f$ - * - * For example - * ``` - * Quatd q{1, 2, 3, 4}; - * std::cout << -q << std::endl; // [-1, -2, -3, -4] - * ``` - */ - Quat<_Tp> operator-() const; - - /** - * @brief return true if two quaternions p and q are nearly equal, i.e. when the absolute - * value of each \f$p_i\f$ and \f$q_i\f$ is less than CV_QUAT_EPS. - */ - bool operator==(const Quat<_Tp>&) const; - - /** - * @brief Addition operator of two quaternions p and q. - * It returns a new quaternion that each value is the sum of \f$p_i\f$ and \f$q_i\f$. - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * Quatd q{5, 6, 7, 8}; - * std::cout << p + q << std::endl; //[6, 8, 10, 12] - * ``` - */ - Quat<_Tp> operator+(const Quat<_Tp>&) const; - - /** - * @brief Addition assignment operator of two quaternions p and q. - * It adds right operand to the left operand and assign the result to left operand. - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * Quatd q{5, 6, 7, 8}; - * p += q; // equivalent to p = p + q - * std::cout << p << std::endl; //[6, 8, 10, 12] - * - * ``` - */ - Quat<_Tp>& operator+=(const Quat<_Tp>&); - - /** - * @brief Subtraction operator of two quaternions p and q. - * It returns a new quaternion that each value is the sum of \f$p_i\f$ and \f$-q_i\f$. - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * Quatd q{5, 6, 7, 8}; - * std::cout << p - q << std::endl; //[-4, -4, -4, -4] - * ``` - */ - Quat<_Tp> operator-(const Quat<_Tp>&) const; - - /** - * @brief Subtraction assignment operator of two quaternions p and q. - * It subtracts right operand from the left operand and assign the result to left operand. - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * Quatd q{5, 6, 7, 8}; - * p -= q; // equivalent to p = p - q - * std::cout << p << std::endl; //[-4, -4, -4, -4] - * - * ``` - */ - Quat<_Tp>& operator-=(const Quat<_Tp>&); - - /** - * @brief Multiplication assignment operator of two quaternions q and p. - * It multiplies right operand with the left operand and assign the result to left operand. - * - * Rule of quaternion multiplication: - * \f[ - * \begin{equation} - * \begin{split} - * p * q &= [p_0, \boldsymbol{u}]*[q_0, \boldsymbol{v}]\\ - * &=[p_0q_0 - \boldsymbol{u}\cdot \boldsymbol{v}, p_0\boldsymbol{v} + q_0\boldsymbol{u}+ \boldsymbol{u}\times \boldsymbol{v}]. - * \end{split} - * \end{equation} - * \f] - * where \f$\cdot\f$ means dot product and \f$\times \f$ means cross product. - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * Quatd q{5, 6, 7, 8}; - * p *= q; // equivalent to p = p * q - * std::cout << p << std::endl; //[-60, 12, 30, 24] - * ``` - */ - Quat<_Tp>& operator*=(const Quat<_Tp>&); - - /** - * @brief Multiplication assignment operator of a quaternions and a scalar. - * It multiplies right operand with the left operand and assign the result to left operand. - * - * Rule of quaternion multiplication with a scalar: - * \f[ - * \begin{equation} - * \begin{split} - * p * s &= [w, x, y, z] * s\\ - * &=[w * s, x * s, y * s, z * s]. - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * double s = 2.0; - * p *= s; // equivalent to p = p * s - * std::cout << p << std::endl; //[2.0, 4.0, 6.0, 8.0] - * ``` - * @note the type of scalar should be equal to the quaternion. - */ - Quat<_Tp>& operator*=(const _Tp s); - - /** - * @brief Multiplication operator of two quaternions q and p. - * Multiplies values on either side of the operator. - * - * Rule of quaternion multiplication: - * \f[ - * \begin{equation} - * \begin{split} - * p * q &= [p_0, \boldsymbol{u}]*[q_0, \boldsymbol{v}]\\ - * &=[p_0q_0 - \boldsymbol{u}\cdot \boldsymbol{v}, p_0\boldsymbol{v} + q_0\boldsymbol{u}+ \boldsymbol{u}\times \boldsymbol{v}]. - * \end{split} - * \end{equation} - * \f] - * where \f$\cdot\f$ means dot product and \f$\times \f$ means cross product. - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * Quatd q{5, 6, 7, 8}; - * std::cout << p * q << std::endl; //[-60, 12, 30, 24] - * ``` - */ - Quat<_Tp> operator*(const Quat<_Tp>&) const; - - /** - * @brief Division operator of a quaternions and a scalar. - * It divides left operand with the right operand and assign the result to left operand. - * - * Rule of quaternion division with a scalar: - * \f[ - * \begin{equation} - * \begin{split} - * p / s &= [w, x, y, z] / s\\ - * &=[w/s, x/s, y/s, z/s]. - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * double s = 2.0; - * p /= s; // equivalent to p = p / s - * std::cout << p << std::endl; //[0.5, 1, 1.5, 2] - * ``` - * @note the type of scalar should be equal to this quaternion. - */ - Quat<_Tp> operator/(const _Tp s) const; - - /** - * @brief Division operator of two quaternions p and q. - * Divides left hand operand by right hand operand. - * - * Rule of quaternion division with a scalar: - * \f[ - * \begin{equation} - * \begin{split} - * p / q &= p * q.inv()\\ - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * Quatd q{5, 6, 7, 8}; - * std::cout << p / q << std::endl; // equivalent to p * q.inv() - * ``` - */ - Quat<_Tp> operator/(const Quat<_Tp>&) const; - - /** - * @brief Division assignment operator of a quaternions and a scalar. - * It divides left operand with the right operand and assign the result to left operand. - * - * Rule of quaternion division with a scalar: - * \f[ - * \begin{equation} - * \begin{split} - * p / s &= [w, x, y, z] / s\\ - * &=[w / s, x / s, y / s, z / s]. - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * double s = 2.0;; - * p /= s; // equivalent to p = p / s - * std::cout << p << std::endl; //[0.5, 1.0, 1.5, 2.0] - * ``` - * @note the type of scalar should be equal to the quaternion. - */ - Quat<_Tp>& operator/=(const _Tp s); - - /** - * @brief Division assignment operator of two quaternions p and q; - * It divides left operand with the right operand and assign the result to left operand. - * - * Rule of quaternion division with a quaternion: - * \f[ - * \begin{equation} - * \begin{split} - * p / q&= p * q.inv()\\ - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * Quatd q{5, 6, 7, 8}; - * p /= q; // equivalent to p = p * q.inv() - * std::cout << p << std::endl; - * ``` - */ - Quat<_Tp>& operator/=(const Quat<_Tp>&); - - _Tp& operator[](std::size_t n); - - const _Tp& operator[](std::size_t n) const; - - /** - * @brief Subtraction operator of a scalar and a quaternions. - * Subtracts right hand operand from left hand operand. - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * double scalar = 2.0; - * std::cout << scalar - p << std::endl; //[1.0, -2, -3, -4] - * ``` - * @note the type of scalar should be equal to the quaternion. - */ - template - friend Quat cv::operator-(const T s, const Quat&); - - /** - * @brief Subtraction operator of a quaternions and a scalar. - * Subtracts right hand operand from left hand operand. - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * double scalar = 2.0; - * std::cout << p - scalar << std::endl; //[-1.0, 2, 3, 4] - * ``` - * @note the type of scalar should be equal to the quaternion. - */ - template - friend Quat cv::operator-(const Quat&, const T s); - - /** - * @brief Addition operator of a quaternions and a scalar. - * Adds right hand operand from left hand operand. - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * double scalar = 2.0; - * std::cout << scalar + p << std::endl; //[3.0, 2, 3, 4] - * ``` - * @note the type of scalar should be equal to the quaternion. - */ - template - friend Quat cv::operator+(const T s, const Quat&); - - /** - * @brief Addition operator of a quaternions and a scalar. - * Adds right hand operand from left hand operand. - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * double scalar = 2.0; - * std::cout << p + scalar << std::endl; //[3.0, 2, 3, 4] - * ``` - * @note the type of scalar should be equal to the quaternion. - */ - template - friend Quat cv::operator+(const Quat&, const T s); - - /** - * @brief Multiplication operator of a scalar and a quaternions. - * It multiplies right operand with the left operand and assign the result to left operand. - * - * Rule of quaternion multiplication with a scalar: - * \f[ - * \begin{equation} - * \begin{split} - * p * s &= [w, x, y, z] * s\\ - * &=[w * s, x * s, y * s, z * s]. - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * double s = 2.0; - * std::cout << s * p << std::endl; //[2.0, 4.0, 6.0, 8.0] - * ``` - * @note the type of scalar should be equal to the quaternion. - */ - template - friend Quat cv::operator*(const T s, const Quat&); - - /** - * @brief Multiplication operator of a quaternion and a scalar. - * It multiplies right operand with the left operand and assign the result to left operand. - * - * Rule of quaternion multiplication with a scalar: - * \f[ - * \begin{equation} - * \begin{split} - * p * s &= [w, x, y, z] * s\\ - * &=[w * s, x * s, y * s, z * s]. - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * double s = 2.0; - * std::cout << p * s << std::endl; //[2.0, 4.0, 6.0, 8.0] - * ``` - * @note the type of scalar should be equal to the quaternion. - */ - template - friend Quat cv::operator*(const Quat&, const T s); - - template - friend std::ostream& cv::operator<<(std::ostream&, const Quat&); - - /** - * @brief Transform a quaternion q to Euler angles. - * - * - * When transforming a quaternion \f$q = w + x\boldsymbol{i} + y\boldsymbol{j} + z\boldsymbol{k}\f$ to Euler angles, rotation matrix M can be calculated by: - * \f[ \begin{aligned} {M} &={\begin{bmatrix}1-2(y^{2}+z^{2})&2(xy-zx)&2(xz+yw)\\2(xy+zw)&1-2(x^{2}+z^{2})&2(yz-xw)\\2(xz-yw)&2(yz+xw)&1-2(x^{2}+y^{2})\end{bmatrix}}\end{aligned}.\f] - * On the other hand, the rotation matrix can be obtained from Euler angles. - * Using intrinsic rotations with Euler angles type XYZ as an example, - * \f$\theta_1 \f$, \f$\theta_2 \f$, \f$\theta_3 \f$ are three angles for Euler angles, the rotation matrix R can be calculated by:\f[R =X(\theta_1)Y(\theta_2)Z(\theta_3) - * ={\begin{bmatrix}\cos\theta_{2}\cos\theta_{3}&-\cos\theta_{2}\sin\theta_{3}&\sin\theta_{2}\\\cos\theta_{1}\sin\theta_{3}+\cos\theta_{3}\sin\theta_{1}\sin\theta_{2}&\cos\theta_{1}\cos\theta_{3}-\sin\theta_{1}\sin\theta_{2}\sin\theta_{3}&-\cos\theta_{2}\sin\theta_{1}\\\sin\theta_{1}\sin\theta_{3}-\cos\theta_{1}\cos\theta_{3}\sin\theta_{2}&\cos\theta_{3}\sin\theta_{1}+\cos\theta_{1}\sin\theta_{2}\sin\theta_{3}&\cos\theta_{1}\cos_{2}\end{bmatrix}}\f] - * Rotation matrix M and R are equal. As long as \f$ s_{2} \neq 1 \f$, by comparing each element of two matrices ,the solution is\f$\begin{cases} \theta_1 = \arctan2(-m_{23},m_{33})\\\theta_2 = arcsin(m_{13}) \\\theta_3 = \arctan2(-m_{12},m_{11}) \end{cases}\f$. - * - * When \f$ s_{2}=1\f$ or \f$ s_{2}=-1\f$, the gimbal lock occurs. The function will prompt "WARNING: Gimbal Lock will occur. Euler angles is non-unique. For intrinsic rotations, we set the third angle to 0, and for external rotation, we set the first angle to 0.". - * - * When \f$ s_{2}=1\f$ , - * The rotation matrix R is \f$R = {\begin{bmatrix}0&0&1\\\sin(\theta_1+\theta_3)&\cos(\theta_1+\theta_3)&0\\-\cos(\theta_1+\theta_3)&\sin(\theta_1+\theta_3)&0\end{bmatrix}}\f$. - * - * The number of solutions is infinite with the condition \f$\begin{cases} \theta_1+\theta_3 = \arctan2(m_{21},m_{22})\\ \theta_2=\pi/2 \end{cases}\ \f$. - * - * We set \f$ \theta_3 = 0\f$, the solution is \f$\begin{cases} \theta_1=\arctan2(m_{21},m_{22})\\ \theta_2=\pi/2\\ \theta_3=0 \end{cases}\f$. - * - * When \f$ s_{2}=-1\f$, - * The rotation matrix R is \f$X_{1}Y_{2}Z_{3}={\begin{bmatrix}0&0&-1\\-\sin(\theta_1-\theta_3)&\cos(\theta_1-\theta_3)&0\\\cos(\theta_1-\theta_3)&\sin(\theta_1-\theta_3)&0\end{bmatrix}}\f$. - * - * The number of solutions is infinite with the condition \f$\begin{cases} \theta_1+\theta_3 = \arctan2(m_{32},m_{22})\\ \theta_2=\pi/2 \end{cases}\ \f$. - * - * We set \f$ \theta_3 = 0\f$, the solution is \f$ \begin{cases}\theta_1=\arctan2(m_{32},m_{22}) \\ \theta_2=-\pi/2\\ \theta_3=0\end{cases}\f$. - * - * Since \f$ sin \theta\in [-1,1] \f$ and \f$ cos \theta \in [-1,1] \f$, the unnormalized quaternion will cause computational troubles. For this reason, this function will normalize the quaternion at first and @ref QuatAssumeType is not needed. - * - * When the gimbal lock occurs, we set \f$\theta_3 = 0\f$ for intrinsic rotations or \f$\theta_1 = 0\f$ for extrinsic rotations. - * - * As a result, for every Euler angles type, we can get solution as shown in the following table. - * EulerAnglesType | Ordinary | \f$\theta_2 = π/2\f$ | \f$\theta_2 = -π/2\f$ - * ------------- | -------------| -------------| ------------- - * INT_XYZ|\f$ \theta_1 = \arctan2(-m_{23},m_{33})\\\theta_2 = \arcsin(m_{13}) \\\theta_3= \arctan2(-m_{12},m_{11}) \f$|\f$ \theta_1=\arctan2(m_{21},m_{22})\\ \theta_2=\pi/2\\ \theta_3=0 \f$|\f$ \theta_1=\arctan2(m_{32},m_{22})\\ \theta_2=-\pi/2\\ \theta_3=0 \f$ - * INT_XZY|\f$ \theta_1 = \arctan2(m_{32},m_{22})\\\theta_2 = -\arcsin(m_{12}) \\\theta_3= \arctan2(m_{13},m_{11}) \f$|\f$ \theta_1=\arctan2(m_{31},m_{33})\\ \theta_2=\pi/2\\ \theta_3=0 \f$|\f$ \theta_1=\arctan2(-m_{23},m_{33})\\ \theta_2=-\pi/2\\ \theta_3=0 \f$ - * INT_YXZ|\f$ \theta_1 = \arctan2(m_{13},m_{33})\\\theta_2 = -\arcsin(m_{23}) \\\theta_3= \arctan2(m_{21},m_{22}) \f$|\f$ \theta_1=\arctan2(m_{12},m_{11})\\ \theta_2=\pi/2\\ \theta_3=0 \f$|\f$ \theta_1=\arctan2(-m_{12},m_{11})\\ \theta_2=-\pi/2\\ \theta_3=0 \f$ - * INT_YZX|\f$ \theta_1 = \arctan2(-m_{31},m_{11})\\\theta_2 = \arcsin(m_{21}) \\\theta_3= \arctan2(-m_{23},m_{22}) \f$|\f$ \theta_1=\arctan2(m_{13},m_{33})\\ \theta_2=\pi/2\\ \theta_3=0 \f$|\f$ \theta_1=\arctan2(m_{13},m_{12})\\ \theta_2=-\pi/2\\ \theta_3=0 \f$ - * INT_ZXY|\f$ \theta_1 = \arctan2(-m_{12},m_{22})\\\theta_2 = \arcsin(m_{32}) \\\theta_3= \arctan2(-m_{31},m_{33}) \f$|\f$ \theta_1=\arctan2(m_{21},m_{11})\\ \theta_2=\pi/2\\ \theta_3=0 \f$|\f$ \theta_1=\arctan2(m_{21},m_{11})\\ \theta_2=-\pi/2\\ \theta_3=0 \f$ - * INT_ZYX|\f$ \theta_1 = \arctan2(m_{21},m_{11})\\\theta_2 = \arcsin(-m_{31}) \\\theta_3= \arctan2(m_{32},m_{33}) \f$|\f$ \theta_1=\arctan2(m_{23},m_{22})\\ \theta_2=\pi/2\\ \theta_3=0 \f$|\f$ \theta_1=\arctan2(-m_{12},m_{22})\\ \theta_2=-\pi/2\\ \theta_3=0 \f$ - * EXT_XYZ|\f$ \theta_1 = \arctan2(m_{32},m_{33})\\\theta_2 = \arcsin(-m_{31}) \\\ \theta_3 = \arctan2(m_{21},m_{11})\f$|\f$ \theta_1= 0\\ \theta_2=\pi/2\\ \theta_3=\arctan2(m_{23},m_{22}) \f$|\f$ \theta_1=0\\ \theta_2=-\pi/2\\ \theta_3=\arctan2(-m_{12},m_{22}) \f$ - * EXT_XZY|\f$ \theta_1 = \arctan2(-m_{23},m_{22})\\\theta_2 = \arcsin(m_{21}) \\\theta_3= \arctan2(-m_{31},m_{11})\f$|\f$ \theta_1= 0\\ \theta_2=\pi/2\\ \theta_3=\arctan2(m_{13},m_{33}) \f$|\f$ \theta_1=0\\ \theta_2=-\pi/2\\ \theta_3=\arctan2(m_{13},m_{12}) \f$ - * EXT_YXZ|\f$ \theta_1 = \arctan2(-m_{31},m_{33}) \\\theta_2 = \arcsin(m_{32}) \\\theta_3= \arctan2(-m_{12},m_{22})\f$|\f$ \theta_1= 0\\ \theta_2=\pi/2\\ \theta_3=\arctan2(m_{21},m_{11}) \f$|\f$ \theta_1=0\\ \theta_2=-\pi/2\\ \theta_3=\arctan2(m_{21},m_{11}) \f$ - * EXT_YZX|\f$ \theta_1 = \arctan2(m_{13},m_{11})\\\theta_2 = -\arcsin(m_{12}) \\\theta_3= \arctan2(m_{32},m_{22})\f$|\f$ \theta_1= 0\\ \theta_2=\pi/2\\ \theta_3=\arctan2(m_{31},m_{33}) \f$|\f$ \theta_1=0\\ \theta_2=-\pi/2\\ \theta_3=\arctan2(-m_{23},m_{33}) \f$ - * EXT_ZXY|\f$ \theta_1 = \arctan2(m_{21},m_{22})\\\theta_2 = -\arcsin(m_{23}) \\\theta_3= \arctan2(m_{13},m_{33})\f$|\f$ \theta_1= 0\\ \theta_2=\pi/2\\ \theta_3=\arctan2(m_{12},m_{11}) \f$|\f$ \theta_1= 0\\ \theta_2=-\pi/2\\ \theta_3=\arctan2(-m_{12},m_{11}) \f$ - * EXT_ZYX|\f$ \theta_1 = \arctan2(-m_{12},m_{11})\\\theta_2 = \arcsin(m_{13}) \\\theta_3= \arctan2(-m_{23},m_{33})\f$|\f$ \theta_1=0\\ \theta_2=\pi/2\\ \theta_3=\arctan2(m_{21},m_{22}) \f$|\f$ \theta_1=0\\ \theta_2=-\pi/2\\ \theta_3=\arctan2(m_{32},m_{22}) \f$ - * - * EulerAnglesType | Ordinary | \f$\theta_2 = 0\f$ | \f$\theta_2 = π\f$ - * ------------- | -------------| -------------| ------------- - * INT_XYX| \f$ \theta_1 = \arctan2(m_{21},-m_{31})\\\theta_2 =\arccos(m_{11}) \\\theta_3 = \arctan2(m_{12},m_{13}) \f$| \f$ \theta_1=\arctan2(m_{32},m_{33})\\ \theta_2=0\\ \theta_3=0 \f$| \f$ \theta_1=\arctan2(m_{23},m_{22})\\ \theta_2=\pi\\ \theta_3=0 \f$ - * INT_XZX| \f$ \theta_1 = \arctan2(m_{31},m_{21})\\\theta_2 = \arccos(m_{11}) \\\theta_3 = \arctan2(m_{13},-m_{12}) \f$| \f$ \theta_1=\arctan2(m_{32},m_{33})\\ \theta_2=0\\ \theta_3=0 \f$| \f$ \theta_1=\arctan2(-m_{32},m_{33})\\ \theta_2=\pi\\ \theta_3=0 \f$ - * INT_YXY| \f$ \theta_1 = \arctan2(m_{12},m_{32})\\\theta_2 = \arccos(m_{22}) \\\theta_3 = \arctan2(m_{21},-m_{23}) \f$| \f$ \theta_1=\arctan2(m_{13},m_{11})\\ \theta_2=0\\ \theta_3=0 \f$| \f$ \theta_1=\arctan2(-m_{31},m_{11})\\ \theta_2=\pi\\ \theta_3=0 \f$ - * INT_YZY| \f$ \theta_1 = \arctan2(m_{32},-m_{12})\\\theta_2 = \arccos(m_{22}) \\\theta_3 =\arctan2(m_{23},m_{21}) \f$| \f$ \theta_1=\arctan2(m_{13},m_{11})\\ \theta_2=0\\ \theta_3=0 \f$| \f$ \theta_1=\arctan2(m_{13},-m_{11})\\ \theta_2=\pi\\ \theta_3=0 \f$ - * INT_ZXZ| \f$ \theta_1 = \arctan2(-m_{13},m_{23})\\\theta_2 = \arccos(m_{33}) \\\theta_3 =\arctan2(m_{31},m_{32}) \f$| \f$ \theta_1=\arctan2(m_{21},m_{22})\\ \theta_2=0\\ \theta_3=0 \f$| \f$ \theta_1=\arctan2(m_{21},m_{11})\\ \theta_2=\pi\\ \theta_3=0 \f$ - * INT_ZYZ| \f$ \theta_1 = \arctan2(m_{23},m_{13})\\\theta_2 = \arccos(m_{33}) \\\theta_3 = \arctan2(m_{32},-m_{31}) \f$| \f$ \theta_1=\arctan2(m_{21},m_{11})\\ \theta_2=0\\ \theta_3=0 \f$| \f$ \theta_1=\arctan2(m_{21},m_{11})\\ \theta_2=\pi\\ \theta_3=0 \f$ - * EXT_XYX| \f$ \theta_1 = \arctan2(m_{12},m_{13}) \\\theta_2 = \arccos(m_{11}) \\\theta_3 = \arctan2(m_{21},-m_{31})\f$| \f$ \theta_1=0\\ \theta_2=0\\ \theta_3=\arctan2(m_{32},m_{33}) \f$| \f$ \theta_1= 0\\ \theta_2=\pi\\ \theta_3= \arctan2(m_{23},m_{22}) \f$ - * EXT_XZX| \f$ \theta_1 = \arctan2(m_{13},-m_{12})\\\theta_2 = \arccos(m_{11}) \\\theta_3 = \arctan2(m_{31},m_{21})\f$| \f$ \theta_1= 0\\ \theta_2=0\\ \theta_3=\arctan2(m_{32},m_{33}) \f$| \f$ \theta_1= 0\\ \theta_2=\pi\\ \theta_3=\arctan2(-m_{32},m_{33}) \f$ - * EXT_YXY| \f$ \theta_1 = \arctan2(m_{21},-m_{23})\\\theta_2 = \arccos(m_{22}) \\\theta_3 = \arctan2(m_{12},m_{32}) \f$| \f$ \theta_1= 0\\ \theta_2=0\\ \theta_3=\arctan2(m_{13},m_{11}) \f$| \f$ \theta_1= 0\\ \theta_2=\pi\\ \theta_3=\arctan2(-m_{31},m_{11}) \f$ - * EXT_YZY| \f$ \theta_1 = \arctan2(m_{23},m_{21}) \\\theta_2 = \arccos(m_{22}) \\\theta_3 = \arctan2(m_{32},-m_{12}) \f$| \f$ \theta_1= 0\\ \theta_2=0\\ \theta_3=\arctan2(m_{13},m_{11}) \f$| \f$ \theta_1=0\\ \theta_2=\pi\\ \theta_3=\arctan2(m_{13},-m_{11}) \f$ - * EXT_ZXZ| \f$ \theta_1 = \arctan2(m_{31},m_{32}) \\\theta_2 = \arccos(m_{33}) \\\theta_3 = \arctan2(-m_{13},m_{23})\f$| \f$ \theta_1=0\\ \theta_2=0\\ \theta_3=\arctan2(m_{21},m_{22}) \f$| \f$ \theta_1= 0\\ \theta_2=\pi\\ \theta_3=\arctan2(m_{21},m_{11}) \f$ - * EXT_ZYZ| \f$ \theta_1 = \arctan2(m_{32},-m_{31})\\\theta_2 = \arccos(m_{33}) \\\theta_3 = \arctan2(m_{23},m_{13}) \f$| \f$ \theta_1=0\\ \theta_2=0\\ \theta_3=\arctan2(m_{21},m_{11}) \f$| \f$ \theta_1= 0\\ \theta_2=\pi\\ \theta_3=\arctan2(m_{21},m_{11}) \f$ - * - * @param eulerAnglesType the convertion Euler angles type - */ - - Vec<_Tp, 3> toEulerAngles(QuatEnum::EulerAnglesType eulerAnglesType); - - _Tp w, x, y, z; - -}; - -template -Quat inv(const Quat &q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); - -template -Quat sinh(const Quat &q); - -template -Quat cosh(const Quat &q); - -template -Quat tanh(const Quat &q); - -template -Quat sin(const Quat &q); - -template -Quat cos(const Quat &q); - -template -Quat tan(const Quat &q); - -template -Quat asinh(const Quat &q); - -template -Quat acosh(const Quat &q); - -template -Quat atanh(const Quat &q); - -template -Quat asin(const Quat &q); - -template -Quat acos(const Quat &q); - -template -Quat atan(const Quat &q); - -template -Quat power(const Quat &q, const Quat &p, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); - -template -Quat exp(const Quat &q); - -template -Quat log(const Quat &q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); - -template -Quat power(const Quat& q, const T x, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); - -template -Quat crossProduct(const Quat &p, const Quat &q); - -template -Quat sqrt(const Quat &q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); - -template -Quat operator*(const T, const Quat&); - -template -Quat operator*(const Quat&, const T); - -template -std::ostream& operator<<(std::ostream&, const Quat&); - -using Quatd = Quat; -using Quatf = Quat; - -//! @} core -} - -#include "opencv2/core/quaternion.inl.hpp" - -#endif /* OPENCV_CORE_QUATERNION_HPP */ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2020, Huawei Technologies Co., Ltd. All rights reserved. +// Third party copyrights are property of their respective owners. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Author: Liangqian Kong +// Longbu Wang +#ifndef OPENCV_CORE_QUATERNION_HPP +#define OPENCV_CORE_QUATERNION_HPP + +#include +#include +#include +namespace cv +{ +//! @addtogroup core_quaternion +//! @{ + +//! Unit quaternion flag +enum QuatAssumeType +{ + /** + * This flag is specified by default. + * If this flag is specified, the input quaternions are assumed to be not unit quaternions. + * It can guarantee the correctness of the calculations, + * although the calculation speed will be slower than the flag QUAT_ASSUME_UNIT. + */ + QUAT_ASSUME_NOT_UNIT, + /** + * If this flag is specified, the input quaternions are assumed to be unit quaternions which + * will save some computations. However, if this flag is specified without unit quaternion, + * the program correctness of the result will not be guaranteed. + */ + QUAT_ASSUME_UNIT +}; + +class QuatEnum +{ +public: + /** @brief Enum of Euler angles type. + * + * Without considering the possibility of using two different convertions for the definition of the rotation axes , + * there exists twelve possible sequences of rotation axes, divided into two groups: + * - Proper Euler angles (Z-X-Z, X-Y-X, Y-Z-Y, Z-Y-Z, X-Z-X, Y-X-Y) + * - Tait–Bryan angles (X-Y-Z, Y-Z-X, Z-X-Y, X-Z-Y, Z-Y-X, Y-X-Z). + * + * The three elemental rotations may be [extrinsic](https://en.wikipedia.org/wiki/Euler_angles#Definition_by_extrinsic_rotations) + * (rotations about the axes *xyz* of the original coordinate system, which is assumed to remain motionless), + * or [intrinsic](https://en.wikipedia.org/wiki/Euler_angles#Definition_by_intrinsic_rotations)(rotations about the axes of the rotating coordinate system *XYZ*, solidary with the moving body, which changes its orientation after each elemental rotation). + * + * + * Extrinsic and intrinsic rotations are relevant. + * + * The definition of the Euler angles is as following, + * - \f$\theta_1 \f$ represents the first rotation angle, + * - \f$\theta_2 \f$ represents the second rotation angle, + * - \f$\theta_3 \f$ represents the third rotation angle. + * + * For intrinsic rotations in the order of X-Y-Z, the rotation matrix R can be calculated by:\f[R =X(\theta_1) Y(\theta_2) Z(\theta_3) \f] + * For extrinsic rotations in the order of X-Y-Z, the rotation matrix R can be calculated by:\f[R =Z({\theta_3}) Y({\theta_2}) X({\theta_1})\f] + * where + * \f[X({\theta_1})={\begin{bmatrix}1&0&0\\0&\cos {\theta_1} &-\sin {\theta_1} \\0&\sin {\theta_1} &\cos {\theta_1} \\\end{bmatrix}}, + * Y({\theta_2})={\begin{bmatrix}\cos \theta_{2}&0&\sin \theta_{2}\\0&1 &0 \\\ -sin \theta_2& 0&\cos \theta_{2} \\\end{bmatrix}}, + * Z({\theta_3})={\begin{bmatrix}\cos\theta_{3} &-\sin \theta_3&0\\\sin \theta_3 &\cos \theta_3 &0\\0&0&1\\\end{bmatrix}}. + * \f] + * + * The function is designed according to this set of conventions: + * - [Right handed](https://en.wikipedia.org/wiki/Right_hand_rule) reference frames are adopted, and the [right hand rule](https://en.wikipedia.org/wiki/Right_hand_rule) is used to determine the sign of angles. + * - Each matrix is meant to represent an [active rotation](https://en.wikipedia.org/wiki/Active_and_passive_transformation) (the composing and composed matrices + * are supposed to act on the coordinates of vectors defined in the initial fixed reference frame and give as a result the coordinates of a rotated vector defined in the same reference frame). + * - For \f$\theta_1\f$ and \f$\theta_3\f$, the valid range is (−π, π]. + * + * For \f$\theta_2\f$, the valid range is [−π/2, π/2] or [0, π]. + * + * For Tait–Bryan angles, the valid range of \f$\theta_2\f$ is [−π/2, π/2]. When transforming a quaternion to Euler angles, the solution of Euler angles is unique in condition of \f$ \theta_2 \in (−π/2, π/2)\f$ . + * If \f$\theta_2 = −π/2 \f$ or \f$ \theta_2 = π/2\f$, there are infinite solutions. The common name for this situation is gimbal lock. + * For Proper Euler angles,the valid range of \f$\theta_2\f$ is in [0, π]. The solutions of Euler angles are unique in condition of \f$ \theta_2 \in (0, π)\f$ . If \f$\theta_2 =0 \f$ or \f$\theta_2 =π \f$, + * there are infinite solutions and gimbal lock will occur. + */ + enum EulerAnglesType + { + INT_XYZ, ///< Intrinsic rotations with the Euler angles type X-Y-Z + INT_XZY, ///< Intrinsic rotations with the Euler angles type X-Z-Y + INT_YXZ, ///< Intrinsic rotations with the Euler angles type Y-X-Z + INT_YZX, ///< Intrinsic rotations with the Euler angles type Y-Z-X + INT_ZXY, ///< Intrinsic rotations with the Euler angles type Z-X-Y + INT_ZYX, ///< Intrinsic rotations with the Euler angles type Z-Y-X + INT_XYX, ///< Intrinsic rotations with the Euler angles type X-Y-X + INT_XZX, ///< Intrinsic rotations with the Euler angles type X-Z-X + INT_YXY, ///< Intrinsic rotations with the Euler angles type Y-X-Y + INT_YZY, ///< Intrinsic rotations with the Euler angles type Y-Z-Y + INT_ZXZ, ///< Intrinsic rotations with the Euler angles type Z-X-Z + INT_ZYZ, ///< Intrinsic rotations with the Euler angles type Z-Y-Z + + EXT_XYZ, ///< Extrinsic rotations with the Euler angles type X-Y-Z + EXT_XZY, ///< Extrinsic rotations with the Euler angles type X-Z-Y + EXT_YXZ, ///< Extrinsic rotations with the Euler angles type Y-X-Z + EXT_YZX, ///< Extrinsic rotations with the Euler angles type Y-Z-X + EXT_ZXY, ///< Extrinsic rotations with the Euler angles type Z-X-Y + EXT_ZYX, ///< Extrinsic rotations with the Euler angles type Z-Y-X + EXT_XYX, ///< Extrinsic rotations with the Euler angles type X-Y-X + EXT_XZX, ///< Extrinsic rotations with the Euler angles type X-Z-X + EXT_YXY, ///< Extrinsic rotations with the Euler angles type Y-X-Y + EXT_YZY, ///< Extrinsic rotations with the Euler angles type Y-Z-Y + EXT_ZXZ, ///< Extrinsic rotations with the Euler angles type Z-X-Z + EXT_ZYZ, ///< Extrinsic rotations with the Euler angles type Z-Y-Z + #ifndef CV_DOXYGEN + EULER_ANGLES_MAX_VALUE + #endif + }; + +}; + +template class Quat; +template std::ostream& operator<<(std::ostream&, const Quat<_Tp>&); + +/** + * Quaternion is a number system that extends the complex numbers. It can be expressed as a + * rotation in three-dimensional space. + * A quaternion is generally represented in the form: + * \f[q = w + x\boldsymbol{i} + y\boldsymbol{j} + z\boldsymbol{k}\f] + * \f[q = [w, x, y, z]\f] + * \f[q = [w, \boldsymbol{v}] \f] + * \f[q = ||q||[\cos\psi, u_x\sin\psi,u_y\sin\psi, u_z\sin\psi].\f] + * \f[q = ||q||[\cos\psi, \boldsymbol{u}\sin\psi]\f] + * where \f$\psi = \frac{\theta}{2}\f$, \f$\theta\f$ represents rotation angle, + * \f$\boldsymbol{u} = [u_x, u_y, u_z]\f$ represents normalized rotation axis, + * and \f$||q||\f$ represents the norm of \f$q\f$. + * + * A unit quaternion is usually represents rotation, which has the form: + * \f[q = [\cos\psi, u_x\sin\psi,u_y\sin\psi, u_z\sin\psi].\f] + * + * To create a quaternion representing the rotation around the axis \f$\boldsymbol{u}\f$ + * with angle \f$\theta\f$, you can use + * ``` + * using namespace cv; + * double angle = CV_PI; + * Vec3d axis = {0, 0, 1}; + * Quatd q = Quatd::createFromAngleAxis(angle, axis); + * ``` + * + * You can simply use four same type number to create a quaternion + * ``` + * Quatd q(1, 2, 3, 4); + * ``` + * Or use a Vec4d or Vec4f vector. + * ``` + * Vec4d vec{1, 2, 3, 4}; + * Quatd q(vec); + * ``` + * + * ``` + * Vec4f vec{1, 2, 3, 4}; + * Quatf q(vec); + * ``` + * + * If you already have a 3x3 rotation matrix R, then you can use + * ``` + * Quatd q = Quatd::createFromRotMat(R); + * ``` + * + * If you already have a rotation vector rvec which has the form of `angle * axis`, then you can use + * ``` + * Quatd q = Quatd::createFromRvec(rvec); + * ``` + * + * To extract the rotation matrix from quaternion, see toRotMat3x3() + * + * To extract the Vec4d or Vec4f, see toVec() + * + * To extract the rotation vector, see toRotVec() + * + * If there are two quaternions \f$q_0, q_1\f$ are needed to interpolate, you can use nlerp(), slerp() or spline() + * ``` + * Quatd::nlerp(q0, q1, t) + * + * Quatd::slerp(q0, q1, t) + * + * Quatd::spline(q0, q0, q1, q1, t) + * ``` + * spline can smoothly connect rotations of multiple quaternions + * + * Three ways to get an element in Quaternion + * ``` + * Quatf q(1,2,3,4); + * std::cout << q.w << std::endl; // w=1, x=2, y=3, z=4 + * std::cout << q[0] << std::endl; // q[0]=1, q[1]=2, q[2]=3, q[3]=4 + * std::cout << q.at(0) << std::endl; + * ``` + */ +template +class Quat +{ + static_assert(std::is_floating_point<_Tp>::value, "Quaternion only make sense with type of float or double"); + using value_type = _Tp; +public: + static constexpr _Tp CV_QUAT_EPS = (_Tp)1.e-6; + static constexpr _Tp CV_QUAT_CONVERT_THRESHOLD = (_Tp)1.e-6; + + Quat(); + + /** + * @brief From Vec4d or Vec4f. + */ + explicit Quat(const Vec<_Tp, 4> &coeff); + + /** + * @brief from four numbers. + */ + Quat(_Tp w, _Tp x, _Tp y, _Tp z); + + /** + * @brief from an angle, axis. Axis will be normalized in this function. And + * it generates + * \f[q = [\cos\psi, u_x\sin\psi,u_y\sin\psi, u_z\sin\psi].\f] + * where \f$\psi = \frac{\theta}{2}\f$, \f$\theta\f$ is the rotation angle. + */ + static Quat<_Tp> createFromAngleAxis(const _Tp angle, const Vec<_Tp, 3> &axis); + + /** + * @brief from a 3x3 rotation matrix. + */ + static Quat<_Tp> createFromRotMat(InputArray R); + + /** + * @brief from a rotation vector + * \f$r\f$ has the form \f$\theta \cdot \boldsymbol{u}\f$, where \f$\theta\f$ + * represents rotation angle and \f$\boldsymbol{u}\f$ represents normalized rotation axis. + * + * Angle and axis could be easily derived as: + * \f[ + * \begin{equation} + * \begin{split} + * \psi &= ||r||\\ + * \boldsymbol{u} &= \frac{r}{\theta} + * \end{split} + * \end{equation} + * \f] + * Then a quaternion can be calculated by + * \f[q = [\cos\psi, \boldsymbol{u}\sin\psi]\f] + * where \f$\psi = \theta / 2 \f$ + */ + static Quat<_Tp> createFromRvec(InputArray rvec); + + /** + * @brief + * from Euler angles + * + * A quaternion can be generated from Euler angles by combining the quaternion representations of the Euler rotations. + * + * For example, if we use intrinsic rotations in the order of X-Y-Z,\f$\theta_1 \f$ is rotation around the X-axis, \f$\theta_2 \f$ is rotation around the Y-axis, + * \f$\theta_3 \f$ is rotation around the Z-axis. The final quaternion q can be calculated by + * + * \f[ {q} = q_{X, \theta_1} q_{Y, \theta_2} q_{Z, \theta_3}\f] + * where \f$ q_{X, \theta_1} \f$ is created from @ref createFromXRot, \f$ q_{Y, \theta_2} \f$ is created from @ref createFromYRot, + * \f$ q_{Z, \theta_3} \f$ is created from @ref createFromZRot. + * @param angles the Euler angles in a vector of length 3 + * @param eulerAnglesType the convertion Euler angles type + */ + static Quat<_Tp> createFromEulerAngles(const Vec<_Tp, 3> &angles, QuatEnum::EulerAnglesType eulerAnglesType); + + /** + * @brief get a quaternion from a rotation about the Y-axis by \f$\theta\f$ . + * \f[q = \cos(\theta/2)+0 i+ sin(\theta/2) j +0k \f] + */ + static Quat<_Tp> createFromYRot(const _Tp theta); + + /** + * @brief get a quaternion from a rotation about the X-axis by \f$\theta\f$ . + * \f[q = \cos(\theta/2)+sin(\theta/2) i +0 j +0 k \f] + */ + static Quat<_Tp> createFromXRot(const _Tp theta); + + /** + * @brief get a quaternion from a rotation about the Z-axis by \f$\theta\f$. + * \f[q = \cos(\theta/2)+0 i +0 j +sin(\theta/2) k \f] + */ + static Quat<_Tp> createFromZRot(const _Tp theta); + + /** + * @brief a way to get element. + * @param index over a range [0, 3]. + * + * A quaternion q + * + * q.at(0) is equivalent to q.w, + * + * q.at(1) is equivalent to q.x, + * + * q.at(2) is equivalent to q.y, + * + * q.at(3) is equivalent to q.z. + */ + _Tp at(size_t index) const; + + /** + * @brief return the conjugate of this quaternion. + * \f[q.conjugate() = (w, -x, -y, -z).\f] + */ + Quat<_Tp> conjugate() const; + + /** + * + * @brief return the value of exponential value. + * \f[\exp(q) = e^w (\cos||\boldsymbol{v}||+ \frac{v}{||\boldsymbol{v}||})\sin||\boldsymbol{v}||\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * @param q a quaternion. + * + * For example: + * ``` + * Quatd q{1,2,3,4}; + * cout << exp(q) << endl; + * ``` + */ + template + friend Quat exp(const Quat &q); + + /** + * @brief return the value of exponential value. + * \f[\exp(q) = e^w (\cos||\boldsymbol{v}||+ \frac{v}{||\boldsymbol{v}||}\sin||\boldsymbol{v}||)\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * + * For example + * ``` + * Quatd q{1,2,3,4}; + * cout << q.exp() << endl; + * ``` + */ + Quat<_Tp> exp() const; + + /** + * @brief return the value of logarithm function. + * \f[\ln(q) = \ln||q|| + \frac{\boldsymbol{v}}{||\boldsymbol{v}||}\arccos\frac{w}{||q||}.\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * @param q a quaternion. + * @param assumeUnit if QUAT_ASSUME_UNIT, q assume to be a unit quaternion and this function will save some computations. + * + * For example + * ``` + * Quatd q1{1,2,3,4}; + * cout << log(q1) << endl; + * ``` + */ + template + friend Quat log(const Quat &q, QuatAssumeType assumeUnit); + + /** + * @brief return the value of logarithm function. + * \f[\ln(q) = \ln||q|| + \frac{\boldsymbol{v}}{||\boldsymbol{v}||}\arccos\frac{w}{||q||}\f]. + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and this function will save some computations. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.log(); + * + * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; + * Quatd q1(1,2,3,4); + * q1.normalize().log(assumeUnit); + * ``` + */ + Quat<_Tp> log(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief return the value of power function with index \f$x\f$. + * \f[q^x = ||q||(cos(x\theta) + \boldsymbol{u}sin(x\theta))).\f] + * @param q a quaternion. + * @param x index of exponentiation. + * @param assumeUnit if QUAT_ASSUME_UNIT, quaternion q assume to be a unit quaternion and this function will save some computations. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * power(q, 2.0); + * + * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; + * double angle = CV_PI; + * Vec3d axis{0, 0, 1}; + * Quatd q1 = Quatd::createFromAngleAxis(angle, axis); //generate a unit quat by axis and angle + * power(q1, 2.0, assumeUnit);//This assumeUnit means q1 is a unit quaternion. + * ``` + * @note the type of the index should be the same as the quaternion. + */ + template + friend Quat power(const Quat &q, const T x, QuatAssumeType assumeUnit); + + /** + * @brief return the value of power function with index \f$x\f$. + * \f[q^x = ||q||(\cos(x\theta) + \boldsymbol{u}\sin(x\theta))).\f] + * @param x index of exponentiation. + * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and this function will save some computations. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.power(2.0); + * + * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; + * double angle = CV_PI; + * Vec3d axis{0, 0, 1}; + * Quatd q1 = Quatd::createFromAngleAxis(angle, axis); //generate a unit quat by axis and angle + * q1.power(2.0, assumeUnit); //This assumeUnt means q1 is a unit quaternion + * ``` + */ + Quat<_Tp> power(const _Tp x, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief return \f$\sqrt{q}\f$. + * @param q a quaternion. + * @param assumeUnit if QUAT_ASSUME_UNIT, quaternion q assume to be a unit quaternion and this function will save some computations. + * + * For example + * ``` + * Quatf q(1,2,3,4); + * sqrt(q); + * + * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; + * q = {1,0,0,0}; + * sqrt(q, assumeUnit); //This assumeUnit means q is a unit quaternion. + * ``` + */ + template + friend Quat sqrt(const Quat &q, QuatAssumeType assumeUnit); + + /** + * @brief return \f$\sqrt{q}\f$. + * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and this function will save some computations. + * + * For example + * ``` + * Quatf q(1,2,3,4); + * q.sqrt(); + * + * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; + * q = {1,0,0,0}; + * q.sqrt(assumeUnit); //This assumeUnit means q is a unit quaternion + * ``` + */ + Quat<_Tp> sqrt(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief return the value of power function with quaternion \f$q\f$. + * \f[p^q = e^{q\ln(p)}.\f] + * @param p base quaternion of power function. + * @param q index quaternion of power function. + * @param assumeUnit if QUAT_ASSUME_UNIT, quaternion \f$p\f$ assume to be a unit quaternion and this function will save some computations. + * + * For example + * ``` + * Quatd p(1,2,3,4); + * Quatd q(5,6,7,8); + * power(p, q); + * + * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; + * p = p.normalize(); + * power(p, q, assumeUnit); //This assumeUnit means p is a unit quaternion + * ``` + */ + template + friend Quat power(const Quat &p, const Quat &q, QuatAssumeType assumeUnit); + + /** + * @brief return the value of power function with quaternion \f$q\f$. + * \f[p^q = e^{q\ln(p)}.\f] + * @param q index quaternion of power function. + * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and this function will save some computations. + * + * For example + * ``` + * Quatd p(1,2,3,4); + * Quatd q(5,6,7,8); + * p.power(q); + * + * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; + * p = p.normalize(); + * p.power(q, assumeUnit); //This assumeUnit means p is a unit quaternion + * ``` + */ + Quat<_Tp> power(const Quat<_Tp> &q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief return the crossProduct between \f$p = (a, b, c, d) = (a, \boldsymbol{u})\f$ and \f$q = (w, x, y, z) = (w, \boldsymbol{v})\f$. + * \f[p \times q = \frac{pq- qp}{2}\f] + * \f[p \times q = \boldsymbol{u} \times \boldsymbol{v}\f] + * \f[p \times q = (cz-dy)i + (dx-bz)j + (by-xc)k \f] + * + * For example + * ``` + * Quatd q{1,2,3,4}; + * Quatd p{5,6,7,8}; + * crossProduct(p, q); + * ``` + */ + template + friend Quat crossProduct(const Quat &p, const Quat &q); + + /** + * @brief return the crossProduct between \f$p = (a, b, c, d) = (a, \boldsymbol{u})\f$ and \f$q = (w, x, y, z) = (w, \boldsymbol{v})\f$. + * \f[p \times q = \frac{pq- qp}{2}.\f] + * \f[p \times q = \boldsymbol{u} \times \boldsymbol{v}.\f] + * \f[p \times q = (cz-dy)i + (dx-bz)j + (by-xc)k. \f] + * + * For example + * ``` + * Quatd q{1,2,3,4}; + * Quatd p{5,6,7,8}; + * p.crossProduct(q) + * ``` + */ + Quat<_Tp> crossProduct(const Quat<_Tp> &q) const; + + /** + * @brief return the norm of quaternion. + * \f[||q|| = \sqrt{w^2 + x^2 + y^2 + z^2}.\f] + */ + _Tp norm() const; + + /** + * @brief return a normalized \f$p\f$. + * \f[p = \frac{q}{||q||}\f] + * where \f$p\f$ satisfies \f$(p.x)^2 + (p.y)^2 + (p.z)^2 + (p.w)^2 = 1.\f$ + */ + Quat<_Tp> normalize() const; + + /** + * @brief return \f$q^{-1}\f$ which is an inverse of \f$q\f$ + * which satisfies \f$q * q^{-1} = 1\f$. + * @param q a quaternion. + * @param assumeUnit if QUAT_ASSUME_UNIT, quaternion q assume to be a unit quaternion and this function will save some computations. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * inv(q); + * + * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; + * q = q.normalize(); + * inv(q, assumeUnit);//This assumeUnit means p is a unit quaternion + * ``` + */ + template + friend Quat inv(const Quat &q, QuatAssumeType assumeUnit); + + /** + * @brief return \f$q^{-1}\f$ which is an inverse of \f$q\f$ + * satisfying \f$q * q^{-1} = 1\f$. + * @param assumeUnit if QUAT_ASSUME_UNIT, quaternion q assume to be a unit quaternion and this function will save some computations. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.inv(); + * + * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; + * q = q.normalize(); + * q.inv(assumeUnit); //assumeUnit means p is a unit quaternion + * ``` + */ + Quat<_Tp> inv(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief return sinh value of quaternion q, sinh could be calculated as: + * \f[\sinh(p) = \sin(w)\cos(||\boldsymbol{v}||) + \cosh(w)\frac{v}{||\boldsymbol{v}||}\sin||\boldsymbol{v}||\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * @param q a quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * sinh(q); + * ``` + */ + template + friend Quat sinh(const Quat &q); + + /** + * @brief return sinh value of this quaternion, sinh could be calculated as: + * \f$\sinh(p) = \sin(w)\cos(||\boldsymbol{v}||) + \cosh(w)\frac{v}{||\boldsymbol{v}||}\sin||\boldsymbol{v}||\f$ + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.sinh(); + * ``` + */ + Quat<_Tp> sinh() const; + + /** + * @brief return cosh value of quaternion q, cosh could be calculated as: + * \f[\cosh(p) = \cosh(w) * \cos(||\boldsymbol{v}||) + \sinh(w)\frac{\boldsymbol{v}}{||\boldsymbol{v}||}\sin(||\boldsymbol{v}||)\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * @param q a quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * cosh(q); + * ``` + */ + template + friend Quat cosh(const Quat &q); + + /** + * @brief return cosh value of this quaternion, cosh could be calculated as: + * \f[\cosh(p) = \cosh(w) * \cos(||\boldsymbol{v}||) + \sinh(w)\frac{\boldsymbol{v}}{||\boldsymbol{v}||}sin(||\boldsymbol{v}||)\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.cosh(); + * ``` + */ + Quat<_Tp> cosh() const; + + /** + * @brief return tanh value of quaternion q, tanh could be calculated as: + * \f[ \tanh(q) = \frac{\sinh(q)}{\cosh(q)}.\f] + * @param q a quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * tanh(q); + * ``` + * @sa sinh, cosh + */ + template + friend Quat tanh(const Quat &q); + + /** + * @brief return tanh value of this quaternion, tanh could be calculated as: + * \f[ \tanh(q) = \frac{\sinh(q)}{\cosh(q)}.\f] + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.tanh(); + * ``` + * @sa sinh, cosh + */ + Quat<_Tp> tanh() const; + + /** + * @brief return tanh value of quaternion q, sin could be calculated as: + * \f[\sin(p) = \sin(w) * \cosh(||\boldsymbol{v}||) + \cos(w)\frac{\boldsymbol{v}}{||\boldsymbol{v}||}\sinh(||\boldsymbol{v}||)\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * @param q a quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * sin(q); + * ``` + */ + template + friend Quat sin(const Quat &q); + + /** + * @brief return sin value of this quaternion, sin could be calculated as: + * \f[\sin(p) = \sin(w) * \cosh(||\boldsymbol{v}||) + \cos(w)\frac{\boldsymbol{v}}{||\boldsymbol{v}||}\sinh(||\boldsymbol{v}||)\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.sin(); + * ``` + */ + Quat<_Tp> sin() const; + + /** + * @brief return sin value of quaternion q, cos could be calculated as: + * \f[\cos(p) = \cos(w) * \cosh(||\boldsymbol{v}||) - \sin(w)\frac{\boldsymbol{v}}{||\boldsymbol{v}||}\sinh(||\boldsymbol{v}||)\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * @param q a quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * cos(q); + * ``` + */ + template + friend Quat cos(const Quat &q); + + /** + * @brief return cos value of this quaternion, cos could be calculated as: + * \f[\cos(p) = \cos(w) * \cosh(||\boldsymbol{v}||) - \sin(w)\frac{\boldsymbol{v}}{||\boldsymbol{v}||}\sinh(||\boldsymbol{v}||)\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.cos(); + * ``` + */ + Quat<_Tp> cos() const; + + /** + * @brief return tan value of quaternion q, tan could be calculated as: + * \f[\tan(q) = \frac{\sin(q)}{\cos(q)}.\f] + * @param q a quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * tan(q); + * ``` + */ + template + friend Quat tan(const Quat &q); + + /** + * @brief return tan value of this quaternion, tan could be calculated as: + * \f[\tan(q) = \frac{\sin(q)}{\cos(q)}.\f] + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.tan(); + * ``` + */ + Quat<_Tp> tan() const; + + /** + * @brief return arcsin value of quaternion q, arcsin could be calculated as: + * \f[\arcsin(q) = -\frac{\boldsymbol{v}}{||\boldsymbol{v}||}arcsinh(q\frac{\boldsymbol{v}}{||\boldsymbol{v}||})\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * @param q a quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * asin(q); + * ``` + */ + template + friend Quat asin(const Quat &q); + + /** + * @brief return arcsin value of this quaternion, arcsin could be calculated as: + * \f[\arcsin(q) = -\frac{\boldsymbol{v}}{||\boldsymbol{v}||}arcsinh(q\frac{\boldsymbol{v}}{||\boldsymbol{v}||})\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.asin(); + * ``` + */ + Quat<_Tp> asin() const; + + /** + * @brief return arccos value of quaternion q, arccos could be calculated as: + * \f[\arccos(q) = -\frac{\boldsymbol{v}}{||\boldsymbol{v}||}arccosh(q)\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * @param q a quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * acos(q); + * ``` + */ + template + friend Quat acos(const Quat &q); + + /** + * @brief return arccos value of this quaternion, arccos could be calculated as: + * \f[\arccos(q) = -\frac{\boldsymbol{v}}{||\boldsymbol{v}||}arccosh(q)\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.acos(); + * ``` + */ + Quat<_Tp> acos() const; + + /** + * @brief return arctan value of quaternion q, arctan could be calculated as: + * \f[\arctan(q) = -\frac{\boldsymbol{v}}{||\boldsymbol{v}||}arctanh(q\frac{\boldsymbol{v}}{||\boldsymbol{v}||})\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * @param q a quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * atan(q); + * ``` + */ + template + friend Quat atan(const Quat &q); + + /** + * @brief return arctan value of this quaternion, arctan could be calculated as: + * \f[\arctan(q) = -\frac{\boldsymbol{v}}{||\boldsymbol{v}||}arctanh(q\frac{\boldsymbol{v}}{||\boldsymbol{v}||})\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.atan(); + * ``` + */ + Quat<_Tp> atan() const; + + /** + * @brief return arcsinh value of quaternion q, arcsinh could be calculated as: + * \f[arcsinh(q) = \ln(q + \sqrt{q^2 + 1})\f]. + * @param q a quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * asinh(q); + * ``` + */ + template + friend Quat asinh(const Quat &q); + + /** + * @brief return arcsinh value of this quaternion, arcsinh could be calculated as: + * \f[arcsinh(q) = \ln(q + \sqrt{q^2 + 1})\f]. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.asinh(); + * ``` + */ + Quat<_Tp> asinh() const; + + /** + * @brief return arccosh value of quaternion q, arccosh could be calculated as: + * \f[arccosh(q) = \ln(q + \sqrt{q^2 - 1})\f]. + * @param q a quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * acosh(q); + * ``` + */ + template + friend Quat acosh(const Quat &q); + + /** + * @brief return arccosh value of this quaternion, arccosh could be calculated as: + * \f[arcosh(q) = \ln(q + \sqrt{q^2 - 1})\f]. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.acosh(); + * ``` + */ + Quat<_Tp> acosh() const; + + /** + * @brief return arctanh value of quaternion q, arctanh could be calculated as: + * \f[arctanh(q) = \frac{\ln(q + 1) - \ln(1 - q)}{2}\f]. + * @param q a quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * atanh(q); + * ``` + */ + template + friend Quat atanh(const Quat &q); + + /** + * @brief return arctanh value of this quaternion, arctanh could be calculated as: + * \f[arcsinh(q) = \frac{\ln(q + 1) - \ln(1 - q)}{2}\f]. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.atanh(); + * ``` + */ + Quat<_Tp> atanh() const; + + /** + * @brief return true if this quaternion is a unit quaternion. + * @param eps tolerance scope of normalization. The eps could be defined as + * + * \f[eps = |1 - dotValue|\f] where \f[dotValue = (this.w^2 + this.x^2 + this,y^2 + this.z^2).\f] + * And this function will consider it is normalized when the dotValue over a range \f$[1-eps, 1+eps]\f$. + */ + bool isNormal(_Tp eps=CV_QUAT_EPS) const; + + /** + * @brief to throw an error if this quaternion is not a unit quaternion. + * @param eps tolerance scope of normalization. + * @sa isNormal + */ + void assertNormal(_Tp eps=CV_QUAT_EPS) const; + + /** + * @brief transform a quaternion to a 3x3 rotation matrix. + * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and + * this function will save some computations. Otherwise, this function will normalize this + * quaternion at first then do the transformation. + * + * @note Matrix A which is to be rotated should have the form + * \f[\begin{bmatrix} + * x_0& x_1& x_2&...&x_n\\ + * y_0& y_1& y_2&...&y_n\\ + * z_0& z_1& z_2&...&z_n + * \end{bmatrix}\f] + * where the same subscript represents a point. The shape of A assume to be [3, n] + * The points matrix A can be rotated by toRotMat3x3() * A. + * The result has 3 rows and n columns too. + + * For example + * ``` + * double angle = CV_PI; + * Vec3d axis{0,0,1}; + * Quatd q_unit = Quatd::createFromAngleAxis(angle, axis); //quaternion could also be get by interpolation by two or more quaternions. + * + * //assume there is two points (1,0,0) and (1,0,1) to be rotated + * Mat pointsA = (Mat_(2, 3) << 1,0,0,1,0,1); + * //change the shape + * pointsA = pointsA.t(); + * // rotate 180 degrees around the z axis + * Mat new_point = q_unit.toRotMat3x3() * pointsA; + * // print two points + * cout << new_point << endl; + * ``` + */ + Matx<_Tp, 3, 3> toRotMat3x3(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief transform a quaternion to a 4x4 rotation matrix. + * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and + * this function will save some computations. Otherwise, this function will normalize this + * quaternion at first then do the transformation. + * + * The operations is similar as toRotMat3x3 + * except that the points matrix should have the form + * \f[\begin{bmatrix} + * x_0& x_1& x_2&...&x_n\\ + * y_0& y_1& y_2&...&y_n\\ + * z_0& z_1& z_2&...&z_n\\ + * 0&0&0&...&0 + * \end{bmatrix}\f] + * + * @sa toRotMat3x3 + */ + + Matx<_Tp, 4, 4> toRotMat4x4(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief transform the this quaternion to a Vec. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.toVec(); + * ``` + */ + Vec<_Tp, 4> toVec() const; + + /** + * @brief transform this quaternion to a Rotation vector. + * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and + * this function will save some computations. + * Rotation vector rVec is defined as: + * \f[ rVec = [\theta v_x, \theta v_y, \theta v_z]\f] + * where \f$\theta\f$ represents rotation angle, and \f$\boldsymbol{v}\f$ represents the normalized rotation axis. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.toRotVec(); + * + * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; + * q.normalize().toRotVec(assumeUnit); //answer is same as q.toRotVec(). + * ``` + */ + Vec<_Tp, 3> toRotVec(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief get the angle of quaternion, it returns the rotation angle. + * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and + * this function will save some computations. + * \f[\psi = 2 *arccos(\frac{w}{||q||})\f] + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.getAngle(); + * + * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; + * q.normalize().getAngle(assumeUnit);//same as q.getAngle(). + * ``` + * @note It always return the value between \f$[0, 2\pi]\f$. + */ + _Tp getAngle(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief get the axis of quaternion, it returns a vector of length 3. + * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and + * this function will save some computations. + * + * the unit axis \f$\boldsymbol{u}\f$ is defined by + * \f[\begin{equation} + * \begin{split} + * \boldsymbol{v} + * &= \boldsymbol{u} ||\boldsymbol{v}||\\ + * &= \boldsymbol{u}||q||sin(\frac{\theta}{2}) + * \end{split} + * \end{equation}\f] + * where \f$v=[x, y ,z]\f$ and \f$\theta\f$ represents rotation angle. + * + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.getAxis(); + * + * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; + * q.normalize().getAxis(assumeUnit);//same as q.getAxis() + * ``` + */ + Vec<_Tp, 3> getAxis(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief return the dot between quaternion \f$q\f$ and this quaternion. + * + * dot(p, q) is a good metric of how close the quaternions are. + * Indeed, consider the unit quaternion difference \f$p^{-1} * q\f$, its real part is dot(p, q). + * At the same time its real part is equal to \f$\cos(\beta/2)\f$ where \f$\beta\f$ is + * an angle of rotation between p and q, i.e., + * Therefore, the closer dot(p, q) to 1, + * the smaller rotation between them. + * \f[p \cdot q = p.w \cdot q.w + p.x \cdot q.x + p.y \cdot q.y + p.z \cdot q.z\f] + * @param q the other quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * Quatd p(5,6,7,8); + * p.dot(q); + * ``` + */ + _Tp dot(Quat<_Tp> q) const; + + /** + * @brief To calculate the interpolation from \f$q_0\f$ to \f$q_1\f$ by Linear Interpolation(Nlerp) + * For two quaternions, this interpolation curve can be displayed as: + * \f[Lerp(q_0, q_1, t) = (1 - t)q_0 + tq_1.\f] + * Obviously, the lerp will interpolate along a straight line if we think of \f$q_0\f$ and \f$q_1\f$ as a vector + * in a two-dimensional space. When \f$t = 0\f$, it returns \f$q_0\f$ and when \f$t= 1\f$, it returns \f$q_1\f$. + * \f$t\f$ should to be ranged in \f$[0, 1]\f$ normally. + * @param q0 a quaternion used in linear interpolation. + * @param q1 a quaternion used in linear interpolation. + * @param t percent of vector \f$\overrightarrow{q_0q_1}\f$ over a range [0, 1]. + * @note it returns a non-unit quaternion. + */ + static Quat<_Tp> lerp(const Quat<_Tp> &q0, const Quat &q1, const _Tp t); + + /** + * @brief To calculate the interpolation from \f$q_0\f$ to \f$q_1\f$ by Normalized Linear Interpolation(Nlerp). + * it returns a normalized quaternion of Linear Interpolation(Lerp). + * \f[ Nlerp(q_0, q_1, t) = \frac{(1 - t)q_0 + tq_1}{||(1 - t)q_0 + tq_1||}.\f] + * The interpolation will always choose the shortest path but the constant speed is not guaranteed. + * @param q0 a quaternion used in normalized linear interpolation. + * @param q1 a quaternion used in normalized linear interpolation. + * @param t percent of vector \f$\overrightarrow{q_0q_1}\f$ over a range [0, 1]. + * @param assumeUnit if QUAT_ASSUME_UNIT, all input quaternions assume to be unit quaternion. Otherwise, all inputs + quaternion will be normalized inside the function. + * @sa lerp + */ + static Quat<_Tp> nlerp(const Quat<_Tp> &q0, const Quat &q1, const _Tp t, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); + + /** + @brief To calculate the interpolation between \f$q_0\f$ and \f$q_1\f$ by Spherical Linear + Interpolation(Slerp), which can be defined as: + \f[ Slerp(q_0, q_1, t) = \frac{\sin((1-t)\theta)}{\sin(\theta)}q_0 + \frac{\sin(t\theta)}{\sin(\theta)}q_1\f] + where \f$\theta\f$ can be calculated as: + \f[\theta=cos^{-1}(q_0\cdot q_1)\f] + resulting from the both of their norm is unit. + @param q0 a quaternion used in Slerp. + @param q1 a quaternion used in Slerp. + @param t percent of angle between \f$q_0\f$ and \f$q_1\f$ over a range [0, 1]. + @param assumeUnit if QUAT_ASSUME_UNIT, all input quaternions assume to be unit quaternions. Otherwise, all input + quaternions will be normalized inside the function. + @param directChange if QUAT_ASSUME_UNIT, the interpolation will choose the nearest path. + @note If the interpolation angle is small, the error between Nlerp and Slerp is not so large. To improve efficiency and + avoid zero division error, we use Nlerp instead of Slerp. + */ + static Quat<_Tp> slerp(const Quat<_Tp> &q0, const Quat &q1, const _Tp t, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT, bool directChange=true); + + /** + * @brief To calculate the interpolation between \f$q_0\f$,\f$q_1\f$,\f$q_2\f$,\f$q_3\f$ by Spherical and quadrangle(Squad). This could be defined as: + * \f[Squad(q_i, s_i, s_{i+1}, q_{i+1}, t) = Slerp(Slerp(q_i, q_{i+1}, t), Slerp(s_i, s_{i+1}, t), 2t(1-t))\f] + * where + * \f[s_i = q_i\exp(-\frac{\log(q^*_iq_{i+1}) + \log(q^*_iq_{i-1})}{4})\f] + * + * The Squad expression is analogous to the \f$B\acute{e}zier\f$ curve, but involves spherical linear + * interpolation instead of simple linear interpolation. Each \f$s_i\f$ needs to be calculated by three + * quaternions. + * + * @param q0 the first quaternion. + * @param s0 the second quaternion. + * @param s1 the third quaternion. + * @param q1 thr fourth quaternion. + * @param t interpolation parameter of quadratic and linear interpolation over a range \f$[0, 1]\f$. + * @param assumeUnit if QUAT_ASSUME_UNIT, all input quaternions assume to be unit quaternion. Otherwise, all input + * quaternions will be normalized inside the function. + * @param directChange if QUAT_ASSUME_UNIT, squad will find the nearest path to interpolate. + * @sa interPoint, spline + */ + static Quat<_Tp> squad(const Quat<_Tp> &q0, const Quat<_Tp> &s0, + const Quat<_Tp> &s1, const Quat<_Tp> &q1, + const _Tp t, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT, + bool directChange=true); + + /** + * @brief This is the part calculation of squad. + * To calculate the intermedia quaternion \f$s_i\f$ between each three quaternion + * \f[s_i = q_i\exp(-\frac{\log(q^*_iq_{i+1}) + \log(q^*_iq_{i-1})}{4}).\f] + * @param q0 the first quaternion. + * @param q1 the second quaternion. + * @param q2 the third quaternion. + * @param assumeUnit if QUAT_ASSUME_UNIT, all input quaternions assume to be unit quaternion. Otherwise, all input + * quaternions will be normalized inside the function. + * @sa squad + */ + static Quat<_Tp> interPoint(const Quat<_Tp> &q0, const Quat<_Tp> &q1, + const Quat<_Tp> &q2, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); + + /** + * @brief to calculate a quaternion which is the result of a \f$C^1\f$ continuous + * spline curve constructed by squad at the ratio t. Here, the interpolation values are + * between \f$q_1\f$ and \f$q_2\f$. \f$q_0\f$ and \f$q_2\f$ are used to ensure the \f$C^1\f$ + * continuity. if t = 0, it returns \f$q_1\f$, if t = 1, it returns \f$q_2\f$. + * @param q0 the first input quaternion to ensure \f$C^1\f$ continuity. + * @param q1 the second input quaternion. + * @param q2 the third input quaternion. + * @param q3 the fourth input quaternion the same use of \f$q1\f$. + * @param t ratio over a range [0, 1]. + * @param assumeUnit if QUAT_ASSUME_UNIT, \f$q_0, q_1, q_2, q_3\f$ assume to be unit quaternion. Otherwise, all input + * quaternions will be normalized inside the function. + * + * For example: + * + * If there are three double quaternions \f$v_0, v_1, v_2\f$ waiting to be interpolated. + * + * Interpolation between \f$v_0\f$ and \f$v_1\f$ with a ratio \f$t_0\f$ could be calculated as + * ``` + * Quatd::spline(v0, v0, v1, v2, t0); + * ``` + * Interpolation between \f$v_1\f$ and \f$v_2\f$ with a ratio \f$t_0\f$ could be calculated as + * ``` + * Quatd::spline(v0, v1, v2, v2, t0); + * ``` + * @sa squad, slerp + */ + static Quat<_Tp> spline(const Quat<_Tp> &q0, const Quat<_Tp> &q1, + const Quat<_Tp> &q2, const Quat<_Tp> &q3, + const _Tp t, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); + + /** + * @brief Return opposite quaternion \f$-p\f$ + * which satisfies \f$p + (-p) = 0.\f$ + * + * For example + * ``` + * Quatd q{1, 2, 3, 4}; + * std::cout << -q << std::endl; // [-1, -2, -3, -4] + * ``` + */ + Quat<_Tp> operator-() const; + + /** + * @brief return true if two quaternions p and q are nearly equal, i.e. when the absolute + * value of each \f$p_i\f$ and \f$q_i\f$ is less than CV_QUAT_EPS. + */ + bool operator==(const Quat<_Tp>&) const; + + /** + * @brief Addition operator of two quaternions p and q. + * It returns a new quaternion that each value is the sum of \f$p_i\f$ and \f$q_i\f$. + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * Quatd q{5, 6, 7, 8}; + * std::cout << p + q << std::endl; //[6, 8, 10, 12] + * ``` + */ + Quat<_Tp> operator+(const Quat<_Tp>&) const; + + /** + * @brief Addition assignment operator of two quaternions p and q. + * It adds right operand to the left operand and assign the result to left operand. + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * Quatd q{5, 6, 7, 8}; + * p += q; // equivalent to p = p + q + * std::cout << p << std::endl; //[6, 8, 10, 12] + * + * ``` + */ + Quat<_Tp>& operator+=(const Quat<_Tp>&); + + /** + * @brief Subtraction operator of two quaternions p and q. + * It returns a new quaternion that each value is the sum of \f$p_i\f$ and \f$-q_i\f$. + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * Quatd q{5, 6, 7, 8}; + * std::cout << p - q << std::endl; //[-4, -4, -4, -4] + * ``` + */ + Quat<_Tp> operator-(const Quat<_Tp>&) const; + + /** + * @brief Subtraction assignment operator of two quaternions p and q. + * It subtracts right operand from the left operand and assign the result to left operand. + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * Quatd q{5, 6, 7, 8}; + * p -= q; // equivalent to p = p - q + * std::cout << p << std::endl; //[-4, -4, -4, -4] + * + * ``` + */ + Quat<_Tp>& operator-=(const Quat<_Tp>&); + + /** + * @brief Multiplication assignment operator of two quaternions q and p. + * It multiplies right operand with the left operand and assign the result to left operand. + * + * Rule of quaternion multiplication: + * \f[ + * \begin{equation} + * \begin{split} + * p * q &= [p_0, \boldsymbol{u}]*[q_0, \boldsymbol{v}]\\ + * &=[p_0q_0 - \boldsymbol{u}\cdot \boldsymbol{v}, p_0\boldsymbol{v} + q_0\boldsymbol{u}+ \boldsymbol{u}\times \boldsymbol{v}]. + * \end{split} + * \end{equation} + * \f] + * where \f$\cdot\f$ means dot product and \f$\times \f$ means cross product. + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * Quatd q{5, 6, 7, 8}; + * p *= q; // equivalent to p = p * q + * std::cout << p << std::endl; //[-60, 12, 30, 24] + * ``` + */ + Quat<_Tp>& operator*=(const Quat<_Tp>&); + + /** + * @brief Multiplication assignment operator of a quaternions and a scalar. + * It multiplies right operand with the left operand and assign the result to left operand. + * + * Rule of quaternion multiplication with a scalar: + * \f[ + * \begin{equation} + * \begin{split} + * p * s &= [w, x, y, z] * s\\ + * &=[w * s, x * s, y * s, z * s]. + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * double s = 2.0; + * p *= s; // equivalent to p = p * s + * std::cout << p << std::endl; //[2.0, 4.0, 6.0, 8.0] + * ``` + * @note the type of scalar should be equal to the quaternion. + */ + Quat<_Tp>& operator*=(const _Tp s); + + /** + * @brief Multiplication operator of two quaternions q and p. + * Multiplies values on either side of the operator. + * + * Rule of quaternion multiplication: + * \f[ + * \begin{equation} + * \begin{split} + * p * q &= [p_0, \boldsymbol{u}]*[q_0, \boldsymbol{v}]\\ + * &=[p_0q_0 - \boldsymbol{u}\cdot \boldsymbol{v}, p_0\boldsymbol{v} + q_0\boldsymbol{u}+ \boldsymbol{u}\times \boldsymbol{v}]. + * \end{split} + * \end{equation} + * \f] + * where \f$\cdot\f$ means dot product and \f$\times \f$ means cross product. + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * Quatd q{5, 6, 7, 8}; + * std::cout << p * q << std::endl; //[-60, 12, 30, 24] + * ``` + */ + Quat<_Tp> operator*(const Quat<_Tp>&) const; + + /** + * @brief Division operator of a quaternions and a scalar. + * It divides left operand with the right operand and assign the result to left operand. + * + * Rule of quaternion division with a scalar: + * \f[ + * \begin{equation} + * \begin{split} + * p / s &= [w, x, y, z] / s\\ + * &=[w/s, x/s, y/s, z/s]. + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * double s = 2.0; + * p /= s; // equivalent to p = p / s + * std::cout << p << std::endl; //[0.5, 1, 1.5, 2] + * ``` + * @note the type of scalar should be equal to this quaternion. + */ + Quat<_Tp> operator/(const _Tp s) const; + + /** + * @brief Division operator of two quaternions p and q. + * Divides left hand operand by right hand operand. + * + * Rule of quaternion division with a scalar: + * \f[ + * \begin{equation} + * \begin{split} + * p / q &= p * q.inv()\\ + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * Quatd q{5, 6, 7, 8}; + * std::cout << p / q << std::endl; // equivalent to p * q.inv() + * ``` + */ + Quat<_Tp> operator/(const Quat<_Tp>&) const; + + /** + * @brief Division assignment operator of a quaternions and a scalar. + * It divides left operand with the right operand and assign the result to left operand. + * + * Rule of quaternion division with a scalar: + * \f[ + * \begin{equation} + * \begin{split} + * p / s &= [w, x, y, z] / s\\ + * &=[w / s, x / s, y / s, z / s]. + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * double s = 2.0;; + * p /= s; // equivalent to p = p / s + * std::cout << p << std::endl; //[0.5, 1.0, 1.5, 2.0] + * ``` + * @note the type of scalar should be equal to the quaternion. + */ + Quat<_Tp>& operator/=(const _Tp s); + + /** + * @brief Division assignment operator of two quaternions p and q; + * It divides left operand with the right operand and assign the result to left operand. + * + * Rule of quaternion division with a quaternion: + * \f[ + * \begin{equation} + * \begin{split} + * p / q&= p * q.inv()\\ + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * Quatd q{5, 6, 7, 8}; + * p /= q; // equivalent to p = p * q.inv() + * std::cout << p << std::endl; + * ``` + */ + Quat<_Tp>& operator/=(const Quat<_Tp>&); + + _Tp& operator[](std::size_t n); + + const _Tp& operator[](std::size_t n) const; + + /** + * @brief Subtraction operator of a scalar and a quaternions. + * Subtracts right hand operand from left hand operand. + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * double scalar = 2.0; + * std::cout << scalar - p << std::endl; //[1.0, -2, -3, -4] + * ``` + * @note the type of scalar should be equal to the quaternion. + */ + template + friend Quat cv::operator-(const T s, const Quat&); + + /** + * @brief Subtraction operator of a quaternions and a scalar. + * Subtracts right hand operand from left hand operand. + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * double scalar = 2.0; + * std::cout << p - scalar << std::endl; //[-1.0, 2, 3, 4] + * ``` + * @note the type of scalar should be equal to the quaternion. + */ + template + friend Quat cv::operator-(const Quat&, const T s); + + /** + * @brief Addition operator of a quaternions and a scalar. + * Adds right hand operand from left hand operand. + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * double scalar = 2.0; + * std::cout << scalar + p << std::endl; //[3.0, 2, 3, 4] + * ``` + * @note the type of scalar should be equal to the quaternion. + */ + template + friend Quat cv::operator+(const T s, const Quat&); + + /** + * @brief Addition operator of a quaternions and a scalar. + * Adds right hand operand from left hand operand. + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * double scalar = 2.0; + * std::cout << p + scalar << std::endl; //[3.0, 2, 3, 4] + * ``` + * @note the type of scalar should be equal to the quaternion. + */ + template + friend Quat cv::operator+(const Quat&, const T s); + + /** + * @brief Multiplication operator of a scalar and a quaternions. + * It multiplies right operand with the left operand and assign the result to left operand. + * + * Rule of quaternion multiplication with a scalar: + * \f[ + * \begin{equation} + * \begin{split} + * p * s &= [w, x, y, z] * s\\ + * &=[w * s, x * s, y * s, z * s]. + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * double s = 2.0; + * std::cout << s * p << std::endl; //[2.0, 4.0, 6.0, 8.0] + * ``` + * @note the type of scalar should be equal to the quaternion. + */ + template + friend Quat cv::operator*(const T s, const Quat&); + + /** + * @brief Multiplication operator of a quaternion and a scalar. + * It multiplies right operand with the left operand and assign the result to left operand. + * + * Rule of quaternion multiplication with a scalar: + * \f[ + * \begin{equation} + * \begin{split} + * p * s &= [w, x, y, z] * s\\ + * &=[w * s, x * s, y * s, z * s]. + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * double s = 2.0; + * std::cout << p * s << std::endl; //[2.0, 4.0, 6.0, 8.0] + * ``` + * @note the type of scalar should be equal to the quaternion. + */ + template + friend Quat cv::operator*(const Quat&, const T s); + + template + friend std::ostream& cv::operator<<(std::ostream&, const Quat&); + + /** + * @brief Transform a quaternion q to Euler angles. + * + * + * When transforming a quaternion \f$q = w + x\boldsymbol{i} + y\boldsymbol{j} + z\boldsymbol{k}\f$ to Euler angles, rotation matrix M can be calculated by: + * \f[ \begin{aligned} {M} &={\begin{bmatrix}1-2(y^{2}+z^{2})&2(xy-zx)&2(xz+yw)\\2(xy+zw)&1-2(x^{2}+z^{2})&2(yz-xw)\\2(xz-yw)&2(yz+xw)&1-2(x^{2}+y^{2})\end{bmatrix}}\end{aligned}.\f] + * On the other hand, the rotation matrix can be obtained from Euler angles. + * Using intrinsic rotations with Euler angles type XYZ as an example, + * \f$\theta_1 \f$, \f$\theta_2 \f$, \f$\theta_3 \f$ are three angles for Euler angles, the rotation matrix R can be calculated by:\f[R =X(\theta_1)Y(\theta_2)Z(\theta_3) + * ={\begin{bmatrix}\cos\theta_{2}\cos\theta_{3}&-\cos\theta_{2}\sin\theta_{3}&\sin\theta_{2}\\\cos\theta_{1}\sin\theta_{3}+\cos\theta_{3}\sin\theta_{1}\sin\theta_{2}&\cos\theta_{1}\cos\theta_{3}-\sin\theta_{1}\sin\theta_{2}\sin\theta_{3}&-\cos\theta_{2}\sin\theta_{1}\\\sin\theta_{1}\sin\theta_{3}-\cos\theta_{1}\cos\theta_{3}\sin\theta_{2}&\cos\theta_{3}\sin\theta_{1}+\cos\theta_{1}\sin\theta_{2}\sin\theta_{3}&\cos\theta_{1}\cos_{2}\end{bmatrix}}\f] + * Rotation matrix M and R are equal. As long as \f$ s_{2} \neq 1 \f$, by comparing each element of two matrices ,the solution is\f$\begin{cases} \theta_1 = \arctan2(-m_{23},m_{33})\\\theta_2 = arcsin(m_{13}) \\\theta_3 = \arctan2(-m_{12},m_{11}) \end{cases}\f$. + * + * When \f$ s_{2}=1\f$ or \f$ s_{2}=-1\f$, the gimbal lock occurs. The function will prompt "WARNING: Gimbal Lock will occur. Euler angles is non-unique. For intrinsic rotations, we set the third angle to 0, and for external rotation, we set the first angle to 0.". + * + * When \f$ s_{2}=1\f$ , + * The rotation matrix R is \f$R = {\begin{bmatrix}0&0&1\\\sin(\theta_1+\theta_3)&\cos(\theta_1+\theta_3)&0\\-\cos(\theta_1+\theta_3)&\sin(\theta_1+\theta_3)&0\end{bmatrix}}\f$. + * + * The number of solutions is infinite with the condition \f$\begin{cases} \theta_1+\theta_3 = \arctan2(m_{21},m_{22})\\ \theta_2=\pi/2 \end{cases}\ \f$. + * + * We set \f$ \theta_3 = 0\f$, the solution is \f$\begin{cases} \theta_1=\arctan2(m_{21},m_{22})\\ \theta_2=\pi/2\\ \theta_3=0 \end{cases}\f$. + * + * When \f$ s_{2}=-1\f$, + * The rotation matrix R is \f$X_{1}Y_{2}Z_{3}={\begin{bmatrix}0&0&-1\\-\sin(\theta_1-\theta_3)&\cos(\theta_1-\theta_3)&0\\\cos(\theta_1-\theta_3)&\sin(\theta_1-\theta_3)&0\end{bmatrix}}\f$. + * + * The number of solutions is infinite with the condition \f$\begin{cases} \theta_1+\theta_3 = \arctan2(m_{32},m_{22})\\ \theta_2=\pi/2 \end{cases}\ \f$. + * + * We set \f$ \theta_3 = 0\f$, the solution is \f$ \begin{cases}\theta_1=\arctan2(m_{32},m_{22}) \\ \theta_2=-\pi/2\\ \theta_3=0\end{cases}\f$. + * + * Since \f$ sin \theta\in [-1,1] \f$ and \f$ cos \theta \in [-1,1] \f$, the unnormalized quaternion will cause computational troubles. For this reason, this function will normalize the quaternion at first and @ref QuatAssumeType is not needed. + * + * When the gimbal lock occurs, we set \f$\theta_3 = 0\f$ for intrinsic rotations or \f$\theta_1 = 0\f$ for extrinsic rotations. + * + * As a result, for every Euler angles type, we can get solution as shown in the following table. + * EulerAnglesType | Ordinary | \f$\theta_2 = π/2\f$ | \f$\theta_2 = -π/2\f$ + * ------------- | -------------| -------------| ------------- + * INT_XYZ|\f$ \theta_1 = \arctan2(-m_{23},m_{33})\\\theta_2 = \arcsin(m_{13}) \\\theta_3= \arctan2(-m_{12},m_{11}) \f$|\f$ \theta_1=\arctan2(m_{21},m_{22})\\ \theta_2=\pi/2\\ \theta_3=0 \f$|\f$ \theta_1=\arctan2(m_{32},m_{22})\\ \theta_2=-\pi/2\\ \theta_3=0 \f$ + * INT_XZY|\f$ \theta_1 = \arctan2(m_{32},m_{22})\\\theta_2 = -\arcsin(m_{12}) \\\theta_3= \arctan2(m_{13},m_{11}) \f$|\f$ \theta_1=\arctan2(m_{31},m_{33})\\ \theta_2=\pi/2\\ \theta_3=0 \f$|\f$ \theta_1=\arctan2(-m_{23},m_{33})\\ \theta_2=-\pi/2\\ \theta_3=0 \f$ + * INT_YXZ|\f$ \theta_1 = \arctan2(m_{13},m_{33})\\\theta_2 = -\arcsin(m_{23}) \\\theta_3= \arctan2(m_{21},m_{22}) \f$|\f$ \theta_1=\arctan2(m_{12},m_{11})\\ \theta_2=\pi/2\\ \theta_3=0 \f$|\f$ \theta_1=\arctan2(-m_{12},m_{11})\\ \theta_2=-\pi/2\\ \theta_3=0 \f$ + * INT_YZX|\f$ \theta_1 = \arctan2(-m_{31},m_{11})\\\theta_2 = \arcsin(m_{21}) \\\theta_3= \arctan2(-m_{23},m_{22}) \f$|\f$ \theta_1=\arctan2(m_{13},m_{33})\\ \theta_2=\pi/2\\ \theta_3=0 \f$|\f$ \theta_1=\arctan2(m_{13},m_{12})\\ \theta_2=-\pi/2\\ \theta_3=0 \f$ + * INT_ZXY|\f$ \theta_1 = \arctan2(-m_{12},m_{22})\\\theta_2 = \arcsin(m_{32}) \\\theta_3= \arctan2(-m_{31},m_{33}) \f$|\f$ \theta_1=\arctan2(m_{21},m_{11})\\ \theta_2=\pi/2\\ \theta_3=0 \f$|\f$ \theta_1=\arctan2(m_{21},m_{11})\\ \theta_2=-\pi/2\\ \theta_3=0 \f$ + * INT_ZYX|\f$ \theta_1 = \arctan2(m_{21},m_{11})\\\theta_2 = \arcsin(-m_{31}) \\\theta_3= \arctan2(m_{32},m_{33}) \f$|\f$ \theta_1=\arctan2(m_{23},m_{22})\\ \theta_2=\pi/2\\ \theta_3=0 \f$|\f$ \theta_1=\arctan2(-m_{12},m_{22})\\ \theta_2=-\pi/2\\ \theta_3=0 \f$ + * EXT_XYZ|\f$ \theta_1 = \arctan2(m_{32},m_{33})\\\theta_2 = \arcsin(-m_{31}) \\\ \theta_3 = \arctan2(m_{21},m_{11})\f$|\f$ \theta_1= 0\\ \theta_2=\pi/2\\ \theta_3=\arctan2(m_{23},m_{22}) \f$|\f$ \theta_1=0\\ \theta_2=-\pi/2\\ \theta_3=\arctan2(-m_{12},m_{22}) \f$ + * EXT_XZY|\f$ \theta_1 = \arctan2(-m_{23},m_{22})\\\theta_2 = \arcsin(m_{21}) \\\theta_3= \arctan2(-m_{31},m_{11})\f$|\f$ \theta_1= 0\\ \theta_2=\pi/2\\ \theta_3=\arctan2(m_{13},m_{33}) \f$|\f$ \theta_1=0\\ \theta_2=-\pi/2\\ \theta_3=\arctan2(m_{13},m_{12}) \f$ + * EXT_YXZ|\f$ \theta_1 = \arctan2(-m_{31},m_{33}) \\\theta_2 = \arcsin(m_{32}) \\\theta_3= \arctan2(-m_{12},m_{22})\f$|\f$ \theta_1= 0\\ \theta_2=\pi/2\\ \theta_3=\arctan2(m_{21},m_{11}) \f$|\f$ \theta_1=0\\ \theta_2=-\pi/2\\ \theta_3=\arctan2(m_{21},m_{11}) \f$ + * EXT_YZX|\f$ \theta_1 = \arctan2(m_{13},m_{11})\\\theta_2 = -\arcsin(m_{12}) \\\theta_3= \arctan2(m_{32},m_{22})\f$|\f$ \theta_1= 0\\ \theta_2=\pi/2\\ \theta_3=\arctan2(m_{31},m_{33}) \f$|\f$ \theta_1=0\\ \theta_2=-\pi/2\\ \theta_3=\arctan2(-m_{23},m_{33}) \f$ + * EXT_ZXY|\f$ \theta_1 = \arctan2(m_{21},m_{22})\\\theta_2 = -\arcsin(m_{23}) \\\theta_3= \arctan2(m_{13},m_{33})\f$|\f$ \theta_1= 0\\ \theta_2=\pi/2\\ \theta_3=\arctan2(m_{12},m_{11}) \f$|\f$ \theta_1= 0\\ \theta_2=-\pi/2\\ \theta_3=\arctan2(-m_{12},m_{11}) \f$ + * EXT_ZYX|\f$ \theta_1 = \arctan2(-m_{12},m_{11})\\\theta_2 = \arcsin(m_{13}) \\\theta_3= \arctan2(-m_{23},m_{33})\f$|\f$ \theta_1=0\\ \theta_2=\pi/2\\ \theta_3=\arctan2(m_{21},m_{22}) \f$|\f$ \theta_1=0\\ \theta_2=-\pi/2\\ \theta_3=\arctan2(m_{32},m_{22}) \f$ + * + * EulerAnglesType | Ordinary | \f$\theta_2 = 0\f$ | \f$\theta_2 = π\f$ + * ------------- | -------------| -------------| ------------- + * INT_XYX| \f$ \theta_1 = \arctan2(m_{21},-m_{31})\\\theta_2 =\arccos(m_{11}) \\\theta_3 = \arctan2(m_{12},m_{13}) \f$| \f$ \theta_1=\arctan2(m_{32},m_{33})\\ \theta_2=0\\ \theta_3=0 \f$| \f$ \theta_1=\arctan2(m_{23},m_{22})\\ \theta_2=\pi\\ \theta_3=0 \f$ + * INT_XZX| \f$ \theta_1 = \arctan2(m_{31},m_{21})\\\theta_2 = \arccos(m_{11}) \\\theta_3 = \arctan2(m_{13},-m_{12}) \f$| \f$ \theta_1=\arctan2(m_{32},m_{33})\\ \theta_2=0\\ \theta_3=0 \f$| \f$ \theta_1=\arctan2(-m_{32},m_{33})\\ \theta_2=\pi\\ \theta_3=0 \f$ + * INT_YXY| \f$ \theta_1 = \arctan2(m_{12},m_{32})\\\theta_2 = \arccos(m_{22}) \\\theta_3 = \arctan2(m_{21},-m_{23}) \f$| \f$ \theta_1=\arctan2(m_{13},m_{11})\\ \theta_2=0\\ \theta_3=0 \f$| \f$ \theta_1=\arctan2(-m_{31},m_{11})\\ \theta_2=\pi\\ \theta_3=0 \f$ + * INT_YZY| \f$ \theta_1 = \arctan2(m_{32},-m_{12})\\\theta_2 = \arccos(m_{22}) \\\theta_3 =\arctan2(m_{23},m_{21}) \f$| \f$ \theta_1=\arctan2(m_{13},m_{11})\\ \theta_2=0\\ \theta_3=0 \f$| \f$ \theta_1=\arctan2(m_{13},-m_{11})\\ \theta_2=\pi\\ \theta_3=0 \f$ + * INT_ZXZ| \f$ \theta_1 = \arctan2(-m_{13},m_{23})\\\theta_2 = \arccos(m_{33}) \\\theta_3 =\arctan2(m_{31},m_{32}) \f$| \f$ \theta_1=\arctan2(m_{21},m_{22})\\ \theta_2=0\\ \theta_3=0 \f$| \f$ \theta_1=\arctan2(m_{21},m_{11})\\ \theta_2=\pi\\ \theta_3=0 \f$ + * INT_ZYZ| \f$ \theta_1 = \arctan2(m_{23},m_{13})\\\theta_2 = \arccos(m_{33}) \\\theta_3 = \arctan2(m_{32},-m_{31}) \f$| \f$ \theta_1=\arctan2(m_{21},m_{11})\\ \theta_2=0\\ \theta_3=0 \f$| \f$ \theta_1=\arctan2(m_{21},m_{11})\\ \theta_2=\pi\\ \theta_3=0 \f$ + * EXT_XYX| \f$ \theta_1 = \arctan2(m_{12},m_{13}) \\\theta_2 = \arccos(m_{11}) \\\theta_3 = \arctan2(m_{21},-m_{31})\f$| \f$ \theta_1=0\\ \theta_2=0\\ \theta_3=\arctan2(m_{32},m_{33}) \f$| \f$ \theta_1= 0\\ \theta_2=\pi\\ \theta_3= \arctan2(m_{23},m_{22}) \f$ + * EXT_XZX| \f$ \theta_1 = \arctan2(m_{13},-m_{12})\\\theta_2 = \arccos(m_{11}) \\\theta_3 = \arctan2(m_{31},m_{21})\f$| \f$ \theta_1= 0\\ \theta_2=0\\ \theta_3=\arctan2(m_{32},m_{33}) \f$| \f$ \theta_1= 0\\ \theta_2=\pi\\ \theta_3=\arctan2(-m_{32},m_{33}) \f$ + * EXT_YXY| \f$ \theta_1 = \arctan2(m_{21},-m_{23})\\\theta_2 = \arccos(m_{22}) \\\theta_3 = \arctan2(m_{12},m_{32}) \f$| \f$ \theta_1= 0\\ \theta_2=0\\ \theta_3=\arctan2(m_{13},m_{11}) \f$| \f$ \theta_1= 0\\ \theta_2=\pi\\ \theta_3=\arctan2(-m_{31},m_{11}) \f$ + * EXT_YZY| \f$ \theta_1 = \arctan2(m_{23},m_{21}) \\\theta_2 = \arccos(m_{22}) \\\theta_3 = \arctan2(m_{32},-m_{12}) \f$| \f$ \theta_1= 0\\ \theta_2=0\\ \theta_3=\arctan2(m_{13},m_{11}) \f$| \f$ \theta_1=0\\ \theta_2=\pi\\ \theta_3=\arctan2(m_{13},-m_{11}) \f$ + * EXT_ZXZ| \f$ \theta_1 = \arctan2(m_{31},m_{32}) \\\theta_2 = \arccos(m_{33}) \\\theta_3 = \arctan2(-m_{13},m_{23})\f$| \f$ \theta_1=0\\ \theta_2=0\\ \theta_3=\arctan2(m_{21},m_{22}) \f$| \f$ \theta_1= 0\\ \theta_2=\pi\\ \theta_3=\arctan2(m_{21},m_{11}) \f$ + * EXT_ZYZ| \f$ \theta_1 = \arctan2(m_{32},-m_{31})\\\theta_2 = \arccos(m_{33}) \\\theta_3 = \arctan2(m_{23},m_{13}) \f$| \f$ \theta_1=0\\ \theta_2=0\\ \theta_3=\arctan2(m_{21},m_{11}) \f$| \f$ \theta_1= 0\\ \theta_2=\pi\\ \theta_3=\arctan2(m_{21},m_{11}) \f$ + * + * @param eulerAnglesType the convertion Euler angles type + */ + + Vec<_Tp, 3> toEulerAngles(QuatEnum::EulerAnglesType eulerAnglesType); + + _Tp w, x, y, z; + +}; + +template +Quat inv(const Quat &q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); + +template +Quat sinh(const Quat &q); + +template +Quat cosh(const Quat &q); + +template +Quat tanh(const Quat &q); + +template +Quat sin(const Quat &q); + +template +Quat cos(const Quat &q); + +template +Quat tan(const Quat &q); + +template +Quat asinh(const Quat &q); + +template +Quat acosh(const Quat &q); + +template +Quat atanh(const Quat &q); + +template +Quat asin(const Quat &q); + +template +Quat acos(const Quat &q); + +template +Quat atan(const Quat &q); + +template +Quat power(const Quat &q, const Quat &p, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); + +template +Quat exp(const Quat &q); + +template +Quat log(const Quat &q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); + +template +Quat power(const Quat& q, const T x, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); + +template +Quat crossProduct(const Quat &p, const Quat &q); + +template +Quat sqrt(const Quat &q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); + +template +Quat operator*(const T, const Quat&); + +template +Quat operator*(const Quat&, const T); + +template +std::ostream& operator<<(std::ostream&, const Quat&); + +using Quatd = Quat; +using Quatf = Quat; + +//! @} core +} + +#include "opencv2/core/quaternion.inl.hpp" + +#endif /* OPENCV_CORE_QUATERNION_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/quaternion.inl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/quaternion.inl.hpp index 4204806a82..9d5a6d86f1 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/quaternion.inl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/quaternion.inl.hpp @@ -1,1063 +1,1063 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2020, Huawei Technologies Co., Ltd. All rights reserved. -// Third party copyrights are property of their respective owners. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Author: Liangqian Kong -// Longbu Wang - -#ifndef OPENCV_CORE_QUATERNION_INL_HPP -#define OPENCV_CORE_QUATERNION_INL_HPP - -#ifndef OPENCV_CORE_QUATERNION_HPP -#error This is not a standalone header. Include quaternion.hpp instead. -#endif - -//@cond IGNORE -/////////////////////////////////////////////////////////////////////////////////////// -//Implementation -namespace cv { - -template -Quat::Quat() : w(0), x(0), y(0), z(0) {} - -template -Quat::Quat(const Vec &coeff):w(coeff[0]), x(coeff[1]), y(coeff[2]), z(coeff[3]){} - -template -Quat::Quat(const T qw, const T qx, const T qy, const T qz):w(qw), x(qx), y(qy), z(qz){} - -template -Quat Quat::createFromAngleAxis(const T angle, const Vec &axis) -{ - T w, x, y, z; - T vNorm = std::sqrt(axis.dot(axis)); - if (vNorm < CV_QUAT_EPS) - { - CV_Error(Error::StsBadArg, "this quaternion does not represent a rotation"); - } - const T angle_half = angle * T(0.5); - w = std::cos(angle_half); - const T sin_v = std::sin(angle_half); - const T sin_norm = sin_v / vNorm; - x = sin_norm * axis[0]; - y = sin_norm * axis[1]; - z = sin_norm * axis[2]; - return Quat(w, x, y, z); -} - -template -Quat Quat::createFromRotMat(InputArray _R) -{ - CV_CheckTypeEQ(_R.type(), cv::traits::Type::value, ""); - if (_R.rows() != 3 || _R.cols() != 3) - { - CV_Error(Error::StsBadArg, "Cannot convert matrix to quaternion: rotation matrix should be a 3x3 matrix"); - } - Matx R; - _R.copyTo(R); - - T S, w, x, y, z; - T trace = R(0, 0) + R(1, 1) + R(2, 2); - if (trace > 0) - { - S = std::sqrt(trace + 1) * T(2); - x = (R(1, 2) - R(2, 1)) / S; - y = (R(2, 0) - R(0, 2)) / S; - z = (R(0, 1) - R(1, 0)) / S; - w = -T(0.25) * S; - } - else if (R(0, 0) > R(1, 1) && R(0, 0) > R(2, 2)) - { - - S = std::sqrt(T(1.0) + R(0, 0) - R(1, 1) - R(2, 2)) * T(2); - x = -T(0.25) * S; - y = -(R(1, 0) + R(0, 1)) / S; - z = -(R(0, 2) + R(2, 0)) / S; - w = (R(1, 2) - R(2, 1)) / S; - } - else if (R(1, 1) > R(2, 2)) - { - S = std::sqrt(T(1.0) - R(0, 0) + R(1, 1) - R(2, 2)) * T(2); - x = (R(0, 1) + R(1, 0)) / S; - y = T(0.25) * S; - z = (R(1, 2) + R(2, 1)) / S; - w = (R(0, 2) - R(2, 0)) / S; - } - else - { - S = std::sqrt(T(1.0) - R(0, 0) - R(1, 1) + R(2, 2)) * T(2); - x = (R(0, 2) + R(2, 0)) / S; - y = (R(1, 2) + R(2, 1)) / S; - z = T(0.25) * S; - w = -(R(0, 1) - R(1, 0)) / S; - } - return Quat (w, x, y, z); -} - -template -Quat Quat::createFromRvec(InputArray _rvec) -{ - if (!((_rvec.cols() == 1 && _rvec.rows() == 3) || (_rvec.cols() == 3 && _rvec.rows() == 1))) { - CV_Error(Error::StsBadArg, "Cannot convert rotation vector to quaternion: The length of rotation vector should be 3"); - } - Vec rvec; - _rvec.copyTo(rvec); - T psi = std::sqrt(rvec.dot(rvec)); - if (abs(psi) < CV_QUAT_EPS) { - return Quat (1, 0, 0, 0); - } - Vec axis = rvec / psi; - return createFromAngleAxis(psi, axis); -} - -template -inline Quat Quat::operator-() const -{ - return Quat(-w, -x, -y, -z); -} - - -template -inline bool Quat::operator==(const Quat &q) const -{ - return (abs(w - q.w) < CV_QUAT_EPS && abs(x - q.x) < CV_QUAT_EPS && abs(y - q.y) < CV_QUAT_EPS && abs(z - q.z) < CV_QUAT_EPS); -} - -template -inline Quat Quat::operator+(const Quat &q1) const -{ - return Quat(w + q1.w, x + q1.x, y + q1.y, z + q1.z); -} - -template -inline Quat operator+(const T a, const Quat& q) -{ - return Quat(q.w + a, q.x, q.y, q.z); -} - -template -inline Quat operator+(const Quat& q, const T a) -{ - return Quat(q.w + a, q.x, q.y, q.z); -} - -template -inline Quat operator-(const T a, const Quat& q) -{ - return Quat(a - q.w, -q.x, -q.y, -q.z); -} - -template -inline Quat operator-(const Quat& q, const T a) -{ - return Quat(q.w - a, q.x, q.y, q.z); -} - -template -inline Quat Quat::operator-(const Quat &q1) const -{ - return Quat(w - q1.w, x - q1.x, y - q1.y, z - q1.z); -} - -template -inline Quat& Quat::operator+=(const Quat &q1) -{ - w += q1.w; - x += q1.x; - y += q1.y; - z += q1.z; - return *this; -} - -template -inline Quat& Quat::operator-=(const Quat &q1) -{ - w -= q1.w; - x -= q1.x; - y -= q1.y; - z -= q1.z; - return *this; -} - -template -inline Quat Quat::operator*(const Quat &q1) const -{ - Vec q{w, x, y, z}; - Vec q2{q1.w, q1.x, q1.y, q1.z}; - return Quat(q * q2); -} - - -template -Quat operator*(const Quat &q1, const T a) -{ - return Quat(a * q1.w, a * q1.x, a * q1.y, a * q1.z); -} - -template -Quat operator*(const T a, const Quat &q1) -{ - return Quat(a * q1.w, a * q1.x, a * q1.y, a * q1.z); -} - -template -inline Quat& Quat::operator*=(const Quat &q1) -{ - T qw, qx, qy, qz; - qw = w * q1.w - x * q1.x - y * q1.y - z * q1.z; - qx = x * q1.w + w * q1.x + y * q1.z - z * q1.y; - qy = y * q1.w + w * q1.y + z * q1.x - x * q1.z; - qz = z * q1.w + w * q1.z + x * q1.y - y * q1.x; - w = qw; - x = qx; - y = qy; - z = qz; - return *this; -} - -template -inline Quat& Quat::operator/=(const Quat &q1) -{ - Quat q(*this * q1.inv()); - w = q.w; - x = q.x; - y = q.y; - z = q.z; - return *this; -} -template -Quat& Quat::operator*=(const T q1) -{ - w *= q1; - x *= q1; - y *= q1; - z *= q1; - return *this; -} - -template -inline Quat& Quat::operator/=(const T a) -{ - const T a_inv = 1.0 / a; - w *= a_inv; - x *= a_inv; - y *= a_inv; - z *= a_inv; - return *this; -} - -template -inline Quat Quat::operator/(const T a) const -{ - const T a_inv = T(1.0) / a; - return Quat(w * a_inv, x * a_inv, y * a_inv, z * a_inv); -} - -template -inline Quat Quat::operator/(const Quat &q) const -{ - return *this * q.inv(); -} - -template -inline const T& Quat::operator[](std::size_t n) const -{ - switch (n) { - case 0: - return w; - case 1: - return x; - case 2: - return y; - case 3: - return z; - default: - CV_Error(Error::StsOutOfRange, "subscript exceeds the index range"); - } -} - -template -inline T& Quat::operator[](std::size_t n) -{ - switch (n) { - case 0: - return w; - case 1: - return x; - case 2: - return y; - case 3: - return z; - default: - CV_Error(Error::StsOutOfRange, "subscript exceeds the index range"); - } -} - -template -std::ostream & operator<<(std::ostream &os, const Quat &q) -{ - os << "Quat " << Vec{q.w, q.x, q.y, q.z}; - return os; -} - -template -inline T Quat::at(size_t index) const -{ - return (*this)[index]; -} - -template -inline Quat Quat::conjugate() const -{ - return Quat(w, -x, -y, -z); -} - -template -inline T Quat::norm() const -{ - return std::sqrt(dot(*this)); -} - -template -Quat exp(const Quat &q) -{ - return q.exp(); -} - -template -Quat Quat::exp() const -{ - Vec v{x, y, z}; - T normV = std::sqrt(v.dot(v)); - T k = normV < CV_QUAT_EPS ? 1 : std::sin(normV) / normV; - return std::exp(w) * Quat(std::cos(normV), v[0] * k, v[1] * k, v[2] * k); -} - -template -Quat log(const Quat &q, QuatAssumeType assumeUnit) -{ - return q.log(assumeUnit); -} - -template -Quat Quat::log(QuatAssumeType assumeUnit) const -{ - Vec v{x, y, z}; - T vNorm = std::sqrt(v.dot(v)); - if (assumeUnit) - { - T k = vNorm < CV_QUAT_EPS ? 1 : std::acos(w) / vNorm; - return Quat(0, v[0] * k, v[1] * k, v[2] * k); - } - T qNorm = norm(); - if (qNorm < CV_QUAT_EPS) - { - CV_Error(Error::StsBadArg, "Cannot apply this quaternion to log function: undefined"); - } - T k = vNorm < CV_QUAT_EPS ? 1 : std::acos(w / qNorm) / vNorm; - return Quat(std::log(qNorm), v[0] * k, v[1] * k, v[2] *k); -} - -template -inline Quat power(const Quat &q1, const T alpha, QuatAssumeType assumeUnit) -{ - return q1.power(alpha, assumeUnit); -} - -template -inline Quat Quat::power(const T alpha, QuatAssumeType assumeUnit) const -{ - if (x * x + y * y + z * z > CV_QUAT_EPS) - { - T angle = getAngle(assumeUnit); - Vec axis = getAxis(assumeUnit); - if (assumeUnit) - { - return createFromAngleAxis(alpha * angle, axis); - } - return std::pow(norm(), alpha) * createFromAngleAxis(alpha * angle, axis); - } - else - { - return std::pow(norm(), alpha) * Quat(w, x, y, z); - } -} - - -template -inline Quat sqrt(const Quat &q, QuatAssumeType assumeUnit) -{ - return q.sqrt(assumeUnit); -} - -template -inline Quat Quat::sqrt(QuatAssumeType assumeUnit) const -{ - return power(0.5, assumeUnit); -} - - -template -inline Quat power(const Quat &p, const Quat &q, QuatAssumeType assumeUnit) -{ - return p.power(q, assumeUnit); -} - - -template -inline Quat Quat::power(const Quat &q, QuatAssumeType assumeUnit) const -{ - return cv::exp(q * log(assumeUnit)); -} - -template -inline T Quat::dot(Quat q1) const -{ - return w * q1.w + x * q1.x + y * q1.y + z * q1.z; -} - - -template -inline Quat crossProduct(const Quat &p, const Quat &q) -{ - return p.crossProduct(q); -} - - -template -inline Quat Quat::crossProduct(const Quat &q) const -{ - return Quat (0, y * q.z - z * q.y, z * q.x - x * q.z, x * q.y - q.x * y); -} - -template -inline Quat Quat::normalize() const -{ - T normVal = norm(); - if (normVal < CV_QUAT_EPS) - { - CV_Error(Error::StsBadArg, "Cannot normalize this quaternion: the norm is too small."); - } - return Quat(w / normVal, x / normVal, y / normVal, z / normVal) ; -} - -template -inline Quat inv(const Quat &q, QuatAssumeType assumeUnit) -{ - return q.inv(assumeUnit); -} - - -template -inline Quat Quat::inv(QuatAssumeType assumeUnit) const -{ - if (assumeUnit) - { - return conjugate(); - } - T norm2 = dot(*this); - if (norm2 < CV_QUAT_EPS) - { - CV_Error(Error::StsBadArg, "This quaternion do not have inverse quaternion"); - } - return conjugate() / norm2; -} - -template -inline Quat sinh(const Quat &q) -{ - return q.sinh(); -} - - -template -inline Quat Quat::sinh() const -{ - Vec v{x, y ,z}; - T vNorm = std::sqrt(v.dot(v)); - T k = vNorm < CV_QUAT_EPS ? 1 : std::cosh(w) * std::sin(vNorm) / vNorm; - return Quat(std::sinh(w) * std::cos(vNorm), v[0] * k, v[1] * k, v[2] * k); -} - - -template -inline Quat cosh(const Quat &q) -{ - return q.cosh(); -} - - -template -inline Quat Quat::cosh() const -{ - Vec v{x, y ,z}; - T vNorm = std::sqrt(v.dot(v)); - T k = vNorm < CV_QUAT_EPS ? 1 : std::sinh(w) * std::sin(vNorm) / vNorm; - return Quat(std::cosh(w) * std::cos(vNorm), v[0] * k, v[1] * k, v[2] * k); -} - -template -inline Quat tanh(const Quat &q) -{ - return q.tanh(); -} - -template -inline Quat Quat::tanh() const -{ - return sinh() * cosh().inv(); -} - - -template -inline Quat sin(const Quat &q) -{ - return q.sin(); -} - - -template -inline Quat Quat::sin() const -{ - Vec v{x, y ,z}; - T vNorm = std::sqrt(v.dot(v)); - T k = vNorm < CV_QUAT_EPS ? 1 : std::cos(w) * std::sinh(vNorm) / vNorm; - return Quat(std::sin(w) * std::cosh(vNorm), v[0] * k, v[1] * k, v[2] * k); -} - -template -inline Quat cos(const Quat &q) -{ - return q.cos(); -} - -template -inline Quat Quat::cos() const -{ - Vec v{x, y ,z}; - T vNorm = std::sqrt(v.dot(v)); - T k = vNorm < CV_QUAT_EPS ? 1 : std::sin(w) * std::sinh(vNorm) / vNorm; - return Quat(std::cos(w) * std::cosh(vNorm), -v[0] * k, -v[1] * k, -v[2] * k); -} - -template -inline Quat tan(const Quat &q) -{ - return q.tan(); -} - -template -inline Quat Quat::tan() const -{ - return sin() * cos().inv(); -} - -template -inline Quat asinh(const Quat &q) -{ - return q.asinh(); -} - -template -inline Quat Quat::asinh() const -{ - return cv::log(*this + cv::power(*this * *this + Quat(1, 0, 0, 0), 0.5)); -} - -template -inline Quat acosh(const Quat &q) -{ - return q.acosh(); -} - -template -inline Quat Quat::acosh() const -{ - return cv::log(*this + cv::power(*this * *this - Quat(1,0,0,0), 0.5)); -} - -template -inline Quat atanh(const Quat &q) -{ - return q.atanh(); -} - -template -inline Quat Quat::atanh() const -{ - Quat ident(1, 0, 0, 0); - Quat c1 = (ident + *this).log(); - Quat c2 = (ident - *this).log(); - return 0.5 * (c1 - c2); -} - -template -inline Quat asin(const Quat &q) -{ - return q.asin(); -} - -template -inline Quat Quat::asin() const -{ - Quat v(0, x, y, z); - T vNorm = v.norm(); - T k = vNorm < CV_QUAT_EPS ? 1 : vNorm; - return -v / k * (*this * v / k).asinh(); -} - -template -inline Quat acos(const Quat &q) -{ - return q.acos(); -} - -template -inline Quat Quat::acos() const -{ - Quat v(0, x, y, z); - T vNorm = v.norm(); - T k = vNorm < CV_QUAT_EPS ? 1 : vNorm; - return -v / k * acosh(); -} - -template -inline Quat atan(const Quat &q) -{ - return q.atan(); -} - -template -inline Quat Quat::atan() const -{ - Quat v(0, x, y, z); - T vNorm = v.norm(); - T k = vNorm < CV_QUAT_EPS ? 1 : vNorm; - return -v / k * (*this * v / k).atanh(); -} - -template -inline T Quat::getAngle(QuatAssumeType assumeUnit) const -{ - if (assumeUnit) - { - return 2 * std::acos(w); - } - if (norm() < CV_QUAT_EPS) - { - CV_Error(Error::StsBadArg, "This quaternion does not represent a rotation"); - } - return 2 * std::acos(w / norm()); -} - -template -inline Vec Quat::getAxis(QuatAssumeType assumeUnit) const -{ - T angle = getAngle(assumeUnit); - const T sin_v = std::sin(angle * 0.5); - if (assumeUnit) - { - return Vec{x, y, z} / sin_v; - } - return Vec {x, y, z} / (norm() * sin_v); -} - -template -Matx Quat::toRotMat4x4(QuatAssumeType assumeUnit) const -{ - T a = w, b = x, c = y, d = z; - if (!assumeUnit) - { - Quat qTemp = normalize(); - a = qTemp.w; - b = qTemp.x; - c = qTemp.y; - d = qTemp.z; - } - Matx R{ - 1 - 2 * (c * c + d * d), 2 * (b * c - a * d) , 2 * (b * d + a * c) , 0, - 2 * (b * c + a * d) , 1 - 2 * (b * b + d * d), 2 * (c * d - a * b) , 0, - 2 * (b * d - a * c) , 2 * (c * d + a * b) , 1 - 2 * (b * b + c * c), 0, - 0 , 0 , 0 , 1, - }; - return R; -} - -template -Matx Quat::toRotMat3x3(QuatAssumeType assumeUnit) const -{ - T a = w, b = x, c = y, d = z; - if (!assumeUnit) - { - Quat qTemp = normalize(); - a = qTemp.w; - b = qTemp.x; - c = qTemp.y; - d = qTemp.z; - } - Matx R{ - 1 - 2 * (c * c + d * d), 2 * (b * c - a * d) , 2 * (b * d + a * c), - 2 * (b * c + a * d) , 1 - 2 * (b * b + d * d), 2 * (c * d - a * b), - 2 * (b * d - a * c) , 2 * (c * d + a * b) , 1 - 2 * (b * b + c * c) - }; - return R; -} - -template -Vec Quat::toRotVec(QuatAssumeType assumeUnit) const -{ - T angle = getAngle(assumeUnit); - Vec axis = getAxis(assumeUnit); - return angle * axis; -} - -template -Vec Quat::toVec() const -{ - return Vec{w, x, y, z}; -} - -template -Quat Quat::lerp(const Quat &q0, const Quat &q1, const T t) -{ - return (1 - t) * q0 + t * q1; -} - -template -Quat Quat::slerp(const Quat &q0, const Quat &q1, const T t, QuatAssumeType assumeUnit, bool directChange) -{ - Quat v0(q0); - Quat v1(q1); - if (!assumeUnit) - { - v0 = v0.normalize(); - v1 = v1.normalize(); - } - T cosTheta = v0.dot(v1); - constexpr T DOT_THRESHOLD = 0.995; - if (std::abs(cosTheta) > DOT_THRESHOLD) - { - return nlerp(v0, v1, t, QUAT_ASSUME_UNIT); - } - - if (directChange && cosTheta < 0) - { - v0 = -v0; - cosTheta = -cosTheta; - } - T sinTheta = std::sqrt(1 - cosTheta * cosTheta); - T angle = atan2(sinTheta, cosTheta); - return (std::sin((1 - t) * angle) / (sinTheta) * v0 + std::sin(t * angle) / (sinTheta) * v1).normalize(); -} - - -template -inline Quat Quat::nlerp(const Quat &q0, const Quat &q1, const T t, QuatAssumeType assumeUnit) -{ - Quat v0(q0), v1(q1); - if (v1.dot(v0) < 0) - { - v0 = -v0; - } - if (assumeUnit) - { - return ((1 - t) * v0 + t * v1).normalize(); - } - v0 = v0.normalize(); - v1 = v1.normalize(); - return ((1 - t) * v0 + t * v1).normalize(); -} - - -template -inline bool Quat::isNormal(T eps) const -{ - - double normVar = norm(); - if ((normVar > 1 - eps) && (normVar < 1 + eps)) - return true; - return false; -} - -template -inline void Quat::assertNormal(T eps) const -{ - if (!isNormal(eps)) - CV_Error(Error::StsBadArg, "Quaternion should be normalized"); -} - - -template -inline Quat Quat::squad(const Quat &q0, const Quat &q1, - const Quat &q2, const Quat &q3, - const T t, QuatAssumeType assumeUnit, - bool directChange) -{ - Quat v0(q0), v1(q1), v2(q2), v3(q3); - if (!assumeUnit) - { - v0 = v0.normalize(); - v1 = v1.normalize(); - v2 = v2.normalize(); - v3 = v3.normalize(); - } - - Quat c0 = slerp(v0, v3, t, assumeUnit, directChange); - Quat c1 = slerp(v1, v2, t, assumeUnit, directChange); - return slerp(c0, c1, 2 * t * (1 - t), assumeUnit, directChange); -} - -template -Quat Quat::interPoint(const Quat &q0, const Quat &q1, - const Quat &q2, QuatAssumeType assumeUnit) -{ - Quat v0(q0), v1(q1), v2(q2); - if (!assumeUnit) - { - v0 = v0.normalize(); - v1 = v1.normalize(); - v2 = v2.normalize(); - } - return v1 * cv::exp(-(cv::log(v1.conjugate() * v0, assumeUnit) + (cv::log(v1.conjugate() * v2, assumeUnit))) / 4); -} - -template -Quat Quat::spline(const Quat &q0, const Quat &q1, const Quat &q2, const Quat &q3, const T t, QuatAssumeType assumeUnit) -{ - Quat v0(q0), v1(q1), v2(q2), v3(q3); - if (!assumeUnit) - { - v0 = v0.normalize(); - v1 = v1.normalize(); - v2 = v2.normalize(); - v3 = v3.normalize(); - } - T cosTheta; - std::vector> vec{v0, v1, v2, v3}; - for (size_t i = 0; i < 3; ++i) - { - cosTheta = vec[i].dot(vec[i + 1]); - if (cosTheta < 0) - { - vec[i + 1] = -vec[i + 1]; - } - } - Quat s1 = interPoint(vec[0], vec[1], vec[2], QUAT_ASSUME_UNIT); - Quat s2 = interPoint(vec[1], vec[2], vec[3], QUAT_ASSUME_UNIT); - return squad(vec[1], s1, s2, vec[2], t, assumeUnit, QUAT_ASSUME_NOT_UNIT); -} - -namespace detail { - -template static -Quat createFromAxisRot(int axis, const T theta) -{ - if (axis == 0) - return Quat::createFromXRot(theta); - if (axis == 1) - return Quat::createFromYRot(theta); - if (axis == 2) - return Quat::createFromZRot(theta); - CV_Assert(0); -} - -inline bool isIntAngleType(QuatEnum::EulerAnglesType eulerAnglesType) -{ - return eulerAnglesType < QuatEnum::EXT_XYZ; -} - -inline bool isTaitBryan(QuatEnum::EulerAnglesType eulerAnglesType) -{ - return eulerAnglesType/6 == 1 || eulerAnglesType/6 == 3; -} -} // namespace detail - -template -Quat Quat::createFromYRot(const T theta) -{ - return Quat{std::cos(theta * 0.5f), 0, std::sin(theta * 0.5f), 0}; -} - -template -Quat Quat::createFromXRot(const T theta){ - return Quat{std::cos(theta * 0.5f), std::sin(theta * 0.5f), 0, 0}; -} - -template -Quat Quat::createFromZRot(const T theta){ - return Quat{std::cos(theta * 0.5f), 0, 0, std::sin(theta * 0.5f)}; -} - - -template -Quat Quat::createFromEulerAngles(const Vec &angles, QuatEnum::EulerAnglesType eulerAnglesType) { - CV_Assert(eulerAnglesType < QuatEnum::EulerAnglesType::EULER_ANGLES_MAX_VALUE); - static const int rotationAxis[24][3] = { - {0, 1, 2}, ///< Intrinsic rotations with the Euler angles type X-Y-Z - {0, 2, 1}, ///< Intrinsic rotations with the Euler angles type X-Z-Y - {1, 0, 2}, ///< Intrinsic rotations with the Euler angles type Y-X-Z - {1, 2, 0}, ///< Intrinsic rotations with the Euler angles type Y-Z-X - {2, 0, 1}, ///< Intrinsic rotations with the Euler angles type Z-X-Y - {2, 1, 0}, ///< Intrinsic rotations with the Euler angles type Z-Y-X - {0, 1, 0}, ///< Intrinsic rotations with the Euler angles type X-Y-X - {0, 2, 0}, ///< Intrinsic rotations with the Euler angles type X-Z-X - {1, 0, 1}, ///< Intrinsic rotations with the Euler angles type Y-X-Y - {1, 2, 1}, ///< Intrinsic rotations with the Euler angles type Y-Z-Y - {2, 0, 2}, ///< Intrinsic rotations with the Euler angles type Z-X-Z - {2, 1, 2}, ///< Intrinsic rotations with the Euler angles type Z-Y-Z - {0, 1, 2}, ///< Extrinsic rotations with the Euler angles type X-Y-Z - {0, 2, 1}, ///< Extrinsic rotations with the Euler angles type X-Z-Y - {1, 0, 2}, ///< Extrinsic rotations with the Euler angles type Y-X-Z - {1, 2, 0}, ///< Extrinsic rotations with the Euler angles type Y-Z-X - {2, 0, 1}, ///< Extrinsic rotations with the Euler angles type Z-X-Y - {2, 1, 0}, ///< Extrinsic rotations with the Euler angles type Z-Y-X - {0, 1, 0}, ///< Extrinsic rotations with the Euler angles type X-Y-X - {0, 2, 0}, ///< Extrinsic rotations with the Euler angles type X-Z-X - {1, 0, 1}, ///< Extrinsic rotations with the Euler angles type Y-X-Y - {1, 2, 1}, ///< Extrinsic rotations with the Euler angles type Y-Z-Y - {2, 0, 2}, ///< Extrinsic rotations with the Euler angles type Z-X-Z - {2, 1, 2} ///< Extrinsic rotations with the Euler angles type Z-Y-Z - }; - Quat q1 = detail::createFromAxisRot(rotationAxis[eulerAnglesType][0], angles(0)); - Quat q2 = detail::createFromAxisRot(rotationAxis[eulerAnglesType][1], angles(1)); - Quat q3 = detail::createFromAxisRot(rotationAxis[eulerAnglesType][2], angles(2)); - if (detail::isIntAngleType(eulerAnglesType)) - { - return q1 * q2 * q3; - } - else // (!detail::isIntAngleType(eulerAnglesType)) - { - return q3 * q2 * q1; - } -} - -template -Vec Quat::toEulerAngles(QuatEnum::EulerAnglesType eulerAnglesType){ - CV_Assert(eulerAnglesType < QuatEnum::EulerAnglesType::EULER_ANGLES_MAX_VALUE); - Matx33d R = toRotMat3x3(); - enum { - C_ZERO, - C_PI, - C_PI_2, - N_CONSTANTS, - R_0_0 = N_CONSTANTS, R_0_1, R_0_2, - R_1_0, R_1_1, R_1_2, - R_2_0, R_2_1, R_2_2 - }; - static const T constants_[N_CONSTANTS] = { - 0, // C_ZERO - (T)CV_PI, // C_PI - (T)(CV_PI * 0.5) // C_PI_2, -C_PI_2 - }; - static const int rotationR_[24][12] = { - {+R_0_2, +R_1_0, +R_1_1, C_PI_2, +R_2_1, +R_1_1, -C_PI_2, -R_1_2, +R_2_2, +R_0_2, -R_0_1, +R_0_0}, // INT_XYZ - {+R_0_1, -R_1_2, +R_2_2, -C_PI_2, +R_2_0, +R_2_2, C_PI_2, +R_2_1, +R_1_1, -R_0_1, +R_0_2, +R_0_0}, // INT_XZY - {+R_1_2, -R_0_1, +R_0_0, -C_PI_2, +R_0_1, +R_0_0, C_PI_2, +R_0_2, +R_2_2, -R_1_2, +R_1_0, +R_1_1}, // INT_YXZ - {+R_1_0, +R_0_2, +R_2_2, C_PI_2, +R_0_2, +R_0_1, -C_PI_2, -R_2_0, +R_0_0, +R_1_0, -R_1_2, +R_1_1}, // INT_YZX - {+R_2_1, +R_1_0, +R_0_0, C_PI_2, +R_1_0, +R_0_0, -C_PI_2, -R_0_1, +R_1_1, +R_2_1, -R_2_0, +R_2_2}, // INT_ZXY - {+R_2_0, -R_0_1, +R_1_1, -C_PI_2, +R_1_2, +R_1_1, C_PI_2, +R_1_0, +R_0_0, -R_2_0, +R_2_1, +R_2_2}, // INT_ZYX - {+R_0_0, +R_2_1, +R_2_2, C_ZERO, +R_1_2, +R_1_1, C_PI, +R_1_0, -R_2_0, +R_0_0, +R_0_1, +R_0_2}, // INT_XYX - {+R_0_0, +R_2_1, +R_2_2, C_ZERO, -R_2_1, +R_2_2, C_PI, +R_2_0, +R_1_0, +R_0_0, +R_0_2, -R_0_1}, // INT_XZX - {+R_1_1, +R_0_2, +R_0_0, C_ZERO, -R_2_0, +R_0_0, C_PI, +R_0_1, +R_2_1, +R_1_1, +R_1_0, -R_1_2}, // INT_YXY - {+R_1_1, +R_0_2, +R_0_0, C_ZERO, +R_0_2, -R_0_0, C_PI, +R_2_1, -R_0_1, +R_1_1, +R_1_2, +R_1_0}, // INT_YZY - {+R_2_2, +R_1_0, +R_1_1, C_ZERO, +R_1_0, +R_0_0, C_PI, +R_0_2, -R_1_2, +R_2_2, +R_2_0, +R_2_1}, // INT_ZXZ - {+R_2_2, +R_1_0, +R_0_0, C_ZERO, +R_1_0, +R_0_0, C_PI, +R_1_2, +R_0_2, +R_2_2, +R_2_1, -R_2_0}, // INT_ZYZ - - {+R_2_0, -C_PI_2, -R_0_1, +R_1_1, C_PI_2, +R_1_2, +R_1_1, +R_2_1, +R_2_2, -R_2_0, +R_1_0, +R_0_0}, // EXT_XYZ - {+R_1_0, C_PI_2, +R_0_2, +R_2_2, -C_PI_2, +R_0_2, +R_0_1, -R_1_2, +R_1_1, +R_1_0, -R_2_0, +R_0_0}, // EXT_XZY - {+R_2_1, C_PI_2, +R_1_0, +R_0_0, -C_PI_2, +R_1_0, +R_0_0, -R_2_0, +R_2_2, +R_2_1, -R_0_1, +R_1_1}, // EXT_YXZ - {+R_0_2, -C_PI_2, -R_1_2, +R_2_2, C_PI_2, +R_2_0, +R_2_2, +R_0_2, +R_0_0, -R_0_1, +R_2_1, +R_1_1}, // EXT_YZX - {+R_1_2, -C_PI_2, -R_0_1, +R_0_0, C_PI_2, +R_0_1, +R_0_0, +R_1_0, +R_1_1, -R_1_2, +R_0_2, +R_2_2}, // EXT_ZXY - {+R_0_2, C_PI_2, +R_1_0, +R_1_1, -C_PI_2, +R_2_1, +R_1_1, -R_0_1, +R_0_0, +R_0_2, -R_1_2, +R_2_2}, // EXT_ZYX - {+R_0_0, C_ZERO, +R_2_1, +R_2_2, C_PI, +R_1_2, +R_1_1, +R_0_1, +R_0_2, +R_0_0, +R_1_0, -R_2_0}, // EXT_XYX - {+R_0_0, C_ZERO, +R_2_1, +R_2_2, C_PI, +R_2_1, +R_2_2, +R_0_2, -R_0_1, +R_0_0, +R_2_0, +R_1_0}, // EXT_XZX - {+R_1_1, C_ZERO, +R_0_2, +R_0_0, C_PI, -R_2_0, +R_0_0, +R_1_0, -R_1_2, +R_1_1, +R_0_1, +R_2_1}, // EXT_YXY - {+R_1_1, C_ZERO, +R_0_2, +R_0_0, C_PI, +R_0_2, -R_0_0, +R_1_2, +R_1_0, +R_1_1, +R_2_1, -R_0_1}, // EXT_YZY - {+R_2_2, C_ZERO, +R_1_0, +R_1_1, C_PI, +R_1_0, +R_0_0, +R_2_0, +R_2_1, +R_2_2, +R_0_2, -R_1_2}, // EXT_ZXZ - {+R_2_2, C_ZERO, +R_1_0, +R_0_0, C_PI, +R_1_0, +R_0_0, +R_2_1, -R_2_0, +R_2_2, +R_1_2, +R_0_2}, // EXT_ZYZ - }; - T rotationR[12]; - for (int i = 0; i < 12; i++) - { - int id = rotationR_[eulerAnglesType][i]; - unsigned idx = std::abs(id); - T value = 0.0f; - if (idx < N_CONSTANTS) - { - value = constants_[idx]; - } - else - { - unsigned r_idx = idx - N_CONSTANTS; - CV_DbgAssert(r_idx < 9); - value = R.val[r_idx]; - } - bool isNegative = id < 0; - if (isNegative) - value = -value; - rotationR[i] = value; - } - Vec angles; - if (detail::isIntAngleType(eulerAnglesType)) - { - if (abs(rotationR[0] - 1) < CV_QUAT_CONVERT_THRESHOLD) - { - CV_LOG_WARNING(NULL,"Gimbal Lock occurs. Euler angles are non-unique, we set the third angle to 0"); - angles = {std::atan2(rotationR[1], rotationR[2]), rotationR[3], 0}; - return angles; - } - else if(abs(rotationR[0] + 1) < CV_QUAT_CONVERT_THRESHOLD) - { - CV_LOG_WARNING(NULL,"Gimbal Lock occurs. Euler angles are non-unique, we set the third angle to 0"); - angles = {std::atan2(rotationR[4], rotationR[5]), rotationR[6], 0}; - return angles; - } - } - else // (!detail::isIntAngleType(eulerAnglesType)) - { - if (abs(rotationR[0] - 1) < CV_QUAT_CONVERT_THRESHOLD) - { - CV_LOG_WARNING(NULL,"Gimbal Lock occurs. Euler angles are non-unique, we set the first angle to 0"); - angles = {0, rotationR[1], std::atan2(rotationR[2], rotationR[3])}; - return angles; - } - else if (abs(rotationR[0] + 1) < CV_QUAT_CONVERT_THRESHOLD) - { - CV_LOG_WARNING(NULL,"Gimbal Lock occurs. Euler angles are non-unique, we set the first angle to 0"); - angles = {0, rotationR[4], std::atan2(rotationR[5], rotationR[6])}; - return angles; - } - } - - angles(0) = std::atan2(rotationR[7], rotationR[8]); - if (detail::isTaitBryan(eulerAnglesType)) - angles(1) = std::acos(rotationR[9]); - else - angles(1) = std::asin(rotationR[9]); - angles(2) = std::atan2(rotationR[10], rotationR[11]); - return angles; -} - -} // namepsace -//! @endcond - -#endif /*OPENCV_CORE_QUATERNION_INL_HPP*/ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2020, Huawei Technologies Co., Ltd. All rights reserved. +// Third party copyrights are property of their respective owners. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Author: Liangqian Kong +// Longbu Wang + +#ifndef OPENCV_CORE_QUATERNION_INL_HPP +#define OPENCV_CORE_QUATERNION_INL_HPP + +#ifndef OPENCV_CORE_QUATERNION_HPP +#error This is not a standalone header. Include quaternion.hpp instead. +#endif + +//@cond IGNORE +/////////////////////////////////////////////////////////////////////////////////////// +//Implementation +namespace cv { + +template +Quat::Quat() : w(0), x(0), y(0), z(0) {} + +template +Quat::Quat(const Vec &coeff):w(coeff[0]), x(coeff[1]), y(coeff[2]), z(coeff[3]){} + +template +Quat::Quat(const T qw, const T qx, const T qy, const T qz):w(qw), x(qx), y(qy), z(qz){} + +template +Quat Quat::createFromAngleAxis(const T angle, const Vec &axis) +{ + T w, x, y, z; + T vNorm = std::sqrt(axis.dot(axis)); + if (vNorm < CV_QUAT_EPS) + { + CV_Error(Error::StsBadArg, "this quaternion does not represent a rotation"); + } + const T angle_half = angle * T(0.5); + w = std::cos(angle_half); + const T sin_v = std::sin(angle_half); + const T sin_norm = sin_v / vNorm; + x = sin_norm * axis[0]; + y = sin_norm * axis[1]; + z = sin_norm * axis[2]; + return Quat(w, x, y, z); +} + +template +Quat Quat::createFromRotMat(InputArray _R) +{ + CV_CheckTypeEQ(_R.type(), cv::traits::Type::value, ""); + if (_R.rows() != 3 || _R.cols() != 3) + { + CV_Error(Error::StsBadArg, "Cannot convert matrix to quaternion: rotation matrix should be a 3x3 matrix"); + } + Matx R; + _R.copyTo(R); + + T S, w, x, y, z; + T trace = R(0, 0) + R(1, 1) + R(2, 2); + if (trace > 0) + { + S = std::sqrt(trace + 1) * T(2); + x = (R(1, 2) - R(2, 1)) / S; + y = (R(2, 0) - R(0, 2)) / S; + z = (R(0, 1) - R(1, 0)) / S; + w = -T(0.25) * S; + } + else if (R(0, 0) > R(1, 1) && R(0, 0) > R(2, 2)) + { + + S = std::sqrt(T(1.0) + R(0, 0) - R(1, 1) - R(2, 2)) * T(2); + x = -T(0.25) * S; + y = -(R(1, 0) + R(0, 1)) / S; + z = -(R(0, 2) + R(2, 0)) / S; + w = (R(1, 2) - R(2, 1)) / S; + } + else if (R(1, 1) > R(2, 2)) + { + S = std::sqrt(T(1.0) - R(0, 0) + R(1, 1) - R(2, 2)) * T(2); + x = (R(0, 1) + R(1, 0)) / S; + y = T(0.25) * S; + z = (R(1, 2) + R(2, 1)) / S; + w = (R(0, 2) - R(2, 0)) / S; + } + else + { + S = std::sqrt(T(1.0) - R(0, 0) - R(1, 1) + R(2, 2)) * T(2); + x = (R(0, 2) + R(2, 0)) / S; + y = (R(1, 2) + R(2, 1)) / S; + z = T(0.25) * S; + w = -(R(0, 1) - R(1, 0)) / S; + } + return Quat (w, x, y, z); +} + +template +Quat Quat::createFromRvec(InputArray _rvec) +{ + if (!((_rvec.cols() == 1 && _rvec.rows() == 3) || (_rvec.cols() == 3 && _rvec.rows() == 1))) { + CV_Error(Error::StsBadArg, "Cannot convert rotation vector to quaternion: The length of rotation vector should be 3"); + } + Vec rvec; + _rvec.copyTo(rvec); + T psi = std::sqrt(rvec.dot(rvec)); + if (abs(psi) < CV_QUAT_EPS) { + return Quat (1, 0, 0, 0); + } + Vec axis = rvec / psi; + return createFromAngleAxis(psi, axis); +} + +template +inline Quat Quat::operator-() const +{ + return Quat(-w, -x, -y, -z); +} + + +template +inline bool Quat::operator==(const Quat &q) const +{ + return (abs(w - q.w) < CV_QUAT_EPS && abs(x - q.x) < CV_QUAT_EPS && abs(y - q.y) < CV_QUAT_EPS && abs(z - q.z) < CV_QUAT_EPS); +} + +template +inline Quat Quat::operator+(const Quat &q1) const +{ + return Quat(w + q1.w, x + q1.x, y + q1.y, z + q1.z); +} + +template +inline Quat operator+(const T a, const Quat& q) +{ + return Quat(q.w + a, q.x, q.y, q.z); +} + +template +inline Quat operator+(const Quat& q, const T a) +{ + return Quat(q.w + a, q.x, q.y, q.z); +} + +template +inline Quat operator-(const T a, const Quat& q) +{ + return Quat(a - q.w, -q.x, -q.y, -q.z); +} + +template +inline Quat operator-(const Quat& q, const T a) +{ + return Quat(q.w - a, q.x, q.y, q.z); +} + +template +inline Quat Quat::operator-(const Quat &q1) const +{ + return Quat(w - q1.w, x - q1.x, y - q1.y, z - q1.z); +} + +template +inline Quat& Quat::operator+=(const Quat &q1) +{ + w += q1.w; + x += q1.x; + y += q1.y; + z += q1.z; + return *this; +} + +template +inline Quat& Quat::operator-=(const Quat &q1) +{ + w -= q1.w; + x -= q1.x; + y -= q1.y; + z -= q1.z; + return *this; +} + +template +inline Quat Quat::operator*(const Quat &q1) const +{ + Vec q{w, x, y, z}; + Vec q2{q1.w, q1.x, q1.y, q1.z}; + return Quat(q * q2); +} + + +template +Quat operator*(const Quat &q1, const T a) +{ + return Quat(a * q1.w, a * q1.x, a * q1.y, a * q1.z); +} + +template +Quat operator*(const T a, const Quat &q1) +{ + return Quat(a * q1.w, a * q1.x, a * q1.y, a * q1.z); +} + +template +inline Quat& Quat::operator*=(const Quat &q1) +{ + T qw, qx, qy, qz; + qw = w * q1.w - x * q1.x - y * q1.y - z * q1.z; + qx = x * q1.w + w * q1.x + y * q1.z - z * q1.y; + qy = y * q1.w + w * q1.y + z * q1.x - x * q1.z; + qz = z * q1.w + w * q1.z + x * q1.y - y * q1.x; + w = qw; + x = qx; + y = qy; + z = qz; + return *this; +} + +template +inline Quat& Quat::operator/=(const Quat &q1) +{ + Quat q(*this * q1.inv()); + w = q.w; + x = q.x; + y = q.y; + z = q.z; + return *this; +} +template +Quat& Quat::operator*=(const T q1) +{ + w *= q1; + x *= q1; + y *= q1; + z *= q1; + return *this; +} + +template +inline Quat& Quat::operator/=(const T a) +{ + const T a_inv = 1.0 / a; + w *= a_inv; + x *= a_inv; + y *= a_inv; + z *= a_inv; + return *this; +} + +template +inline Quat Quat::operator/(const T a) const +{ + const T a_inv = T(1.0) / a; + return Quat(w * a_inv, x * a_inv, y * a_inv, z * a_inv); +} + +template +inline Quat Quat::operator/(const Quat &q) const +{ + return *this * q.inv(); +} + +template +inline const T& Quat::operator[](std::size_t n) const +{ + switch (n) { + case 0: + return w; + case 1: + return x; + case 2: + return y; + case 3: + return z; + default: + CV_Error(Error::StsOutOfRange, "subscript exceeds the index range"); + } +} + +template +inline T& Quat::operator[](std::size_t n) +{ + switch (n) { + case 0: + return w; + case 1: + return x; + case 2: + return y; + case 3: + return z; + default: + CV_Error(Error::StsOutOfRange, "subscript exceeds the index range"); + } +} + +template +std::ostream & operator<<(std::ostream &os, const Quat &q) +{ + os << "Quat " << Vec{q.w, q.x, q.y, q.z}; + return os; +} + +template +inline T Quat::at(size_t index) const +{ + return (*this)[index]; +} + +template +inline Quat Quat::conjugate() const +{ + return Quat(w, -x, -y, -z); +} + +template +inline T Quat::norm() const +{ + return std::sqrt(dot(*this)); +} + +template +Quat exp(const Quat &q) +{ + return q.exp(); +} + +template +Quat Quat::exp() const +{ + Vec v{x, y, z}; + T normV = std::sqrt(v.dot(v)); + T k = normV < CV_QUAT_EPS ? 1 : std::sin(normV) / normV; + return std::exp(w) * Quat(std::cos(normV), v[0] * k, v[1] * k, v[2] * k); +} + +template +Quat log(const Quat &q, QuatAssumeType assumeUnit) +{ + return q.log(assumeUnit); +} + +template +Quat Quat::log(QuatAssumeType assumeUnit) const +{ + Vec v{x, y, z}; + T vNorm = std::sqrt(v.dot(v)); + if (assumeUnit) + { + T k = vNorm < CV_QUAT_EPS ? 1 : std::acos(w) / vNorm; + return Quat(0, v[0] * k, v[1] * k, v[2] * k); + } + T qNorm = norm(); + if (qNorm < CV_QUAT_EPS) + { + CV_Error(Error::StsBadArg, "Cannot apply this quaternion to log function: undefined"); + } + T k = vNorm < CV_QUAT_EPS ? 1 : std::acos(w / qNorm) / vNorm; + return Quat(std::log(qNorm), v[0] * k, v[1] * k, v[2] *k); +} + +template +inline Quat power(const Quat &q1, const T alpha, QuatAssumeType assumeUnit) +{ + return q1.power(alpha, assumeUnit); +} + +template +inline Quat Quat::power(const T alpha, QuatAssumeType assumeUnit) const +{ + if (x * x + y * y + z * z > CV_QUAT_EPS) + { + T angle = getAngle(assumeUnit); + Vec axis = getAxis(assumeUnit); + if (assumeUnit) + { + return createFromAngleAxis(alpha * angle, axis); + } + return std::pow(norm(), alpha) * createFromAngleAxis(alpha * angle, axis); + } + else + { + return std::pow(norm(), alpha) * Quat(w, x, y, z); + } +} + + +template +inline Quat sqrt(const Quat &q, QuatAssumeType assumeUnit) +{ + return q.sqrt(assumeUnit); +} + +template +inline Quat Quat::sqrt(QuatAssumeType assumeUnit) const +{ + return power(0.5, assumeUnit); +} + + +template +inline Quat power(const Quat &p, const Quat &q, QuatAssumeType assumeUnit) +{ + return p.power(q, assumeUnit); +} + + +template +inline Quat Quat::power(const Quat &q, QuatAssumeType assumeUnit) const +{ + return cv::exp(q * log(assumeUnit)); +} + +template +inline T Quat::dot(Quat q1) const +{ + return w * q1.w + x * q1.x + y * q1.y + z * q1.z; +} + + +template +inline Quat crossProduct(const Quat &p, const Quat &q) +{ + return p.crossProduct(q); +} + + +template +inline Quat Quat::crossProduct(const Quat &q) const +{ + return Quat (0, y * q.z - z * q.y, z * q.x - x * q.z, x * q.y - q.x * y); +} + +template +inline Quat Quat::normalize() const +{ + T normVal = norm(); + if (normVal < CV_QUAT_EPS) + { + CV_Error(Error::StsBadArg, "Cannot normalize this quaternion: the norm is too small."); + } + return Quat(w / normVal, x / normVal, y / normVal, z / normVal) ; +} + +template +inline Quat inv(const Quat &q, QuatAssumeType assumeUnit) +{ + return q.inv(assumeUnit); +} + + +template +inline Quat Quat::inv(QuatAssumeType assumeUnit) const +{ + if (assumeUnit) + { + return conjugate(); + } + T norm2 = dot(*this); + if (norm2 < CV_QUAT_EPS) + { + CV_Error(Error::StsBadArg, "This quaternion do not have inverse quaternion"); + } + return conjugate() / norm2; +} + +template +inline Quat sinh(const Quat &q) +{ + return q.sinh(); +} + + +template +inline Quat Quat::sinh() const +{ + Vec v{x, y ,z}; + T vNorm = std::sqrt(v.dot(v)); + T k = vNorm < CV_QUAT_EPS ? 1 : std::cosh(w) * std::sin(vNorm) / vNorm; + return Quat(std::sinh(w) * std::cos(vNorm), v[0] * k, v[1] * k, v[2] * k); +} + + +template +inline Quat cosh(const Quat &q) +{ + return q.cosh(); +} + + +template +inline Quat Quat::cosh() const +{ + Vec v{x, y ,z}; + T vNorm = std::sqrt(v.dot(v)); + T k = vNorm < CV_QUAT_EPS ? 1 : std::sinh(w) * std::sin(vNorm) / vNorm; + return Quat(std::cosh(w) * std::cos(vNorm), v[0] * k, v[1] * k, v[2] * k); +} + +template +inline Quat tanh(const Quat &q) +{ + return q.tanh(); +} + +template +inline Quat Quat::tanh() const +{ + return sinh() * cosh().inv(); +} + + +template +inline Quat sin(const Quat &q) +{ + return q.sin(); +} + + +template +inline Quat Quat::sin() const +{ + Vec v{x, y ,z}; + T vNorm = std::sqrt(v.dot(v)); + T k = vNorm < CV_QUAT_EPS ? 1 : std::cos(w) * std::sinh(vNorm) / vNorm; + return Quat(std::sin(w) * std::cosh(vNorm), v[0] * k, v[1] * k, v[2] * k); +} + +template +inline Quat cos(const Quat &q) +{ + return q.cos(); +} + +template +inline Quat Quat::cos() const +{ + Vec v{x, y ,z}; + T vNorm = std::sqrt(v.dot(v)); + T k = vNorm < CV_QUAT_EPS ? 1 : std::sin(w) * std::sinh(vNorm) / vNorm; + return Quat(std::cos(w) * std::cosh(vNorm), -v[0] * k, -v[1] * k, -v[2] * k); +} + +template +inline Quat tan(const Quat &q) +{ + return q.tan(); +} + +template +inline Quat Quat::tan() const +{ + return sin() * cos().inv(); +} + +template +inline Quat asinh(const Quat &q) +{ + return q.asinh(); +} + +template +inline Quat Quat::asinh() const +{ + return cv::log(*this + cv::power(*this * *this + Quat(1, 0, 0, 0), 0.5)); +} + +template +inline Quat acosh(const Quat &q) +{ + return q.acosh(); +} + +template +inline Quat Quat::acosh() const +{ + return cv::log(*this + cv::power(*this * *this - Quat(1,0,0,0), 0.5)); +} + +template +inline Quat atanh(const Quat &q) +{ + return q.atanh(); +} + +template +inline Quat Quat::atanh() const +{ + Quat ident(1, 0, 0, 0); + Quat c1 = (ident + *this).log(); + Quat c2 = (ident - *this).log(); + return 0.5 * (c1 - c2); +} + +template +inline Quat asin(const Quat &q) +{ + return q.asin(); +} + +template +inline Quat Quat::asin() const +{ + Quat v(0, x, y, z); + T vNorm = v.norm(); + T k = vNorm < CV_QUAT_EPS ? 1 : vNorm; + return -v / k * (*this * v / k).asinh(); +} + +template +inline Quat acos(const Quat &q) +{ + return q.acos(); +} + +template +inline Quat Quat::acos() const +{ + Quat v(0, x, y, z); + T vNorm = v.norm(); + T k = vNorm < CV_QUAT_EPS ? 1 : vNorm; + return -v / k * acosh(); +} + +template +inline Quat atan(const Quat &q) +{ + return q.atan(); +} + +template +inline Quat Quat::atan() const +{ + Quat v(0, x, y, z); + T vNorm = v.norm(); + T k = vNorm < CV_QUAT_EPS ? 1 : vNorm; + return -v / k * (*this * v / k).atanh(); +} + +template +inline T Quat::getAngle(QuatAssumeType assumeUnit) const +{ + if (assumeUnit) + { + return 2 * std::acos(w); + } + if (norm() < CV_QUAT_EPS) + { + CV_Error(Error::StsBadArg, "This quaternion does not represent a rotation"); + } + return 2 * std::acos(w / norm()); +} + +template +inline Vec Quat::getAxis(QuatAssumeType assumeUnit) const +{ + T angle = getAngle(assumeUnit); + const T sin_v = std::sin(angle * 0.5); + if (assumeUnit) + { + return Vec{x, y, z} / sin_v; + } + return Vec {x, y, z} / (norm() * sin_v); +} + +template +Matx Quat::toRotMat4x4(QuatAssumeType assumeUnit) const +{ + T a = w, b = x, c = y, d = z; + if (!assumeUnit) + { + Quat qTemp = normalize(); + a = qTemp.w; + b = qTemp.x; + c = qTemp.y; + d = qTemp.z; + } + Matx R{ + 1 - 2 * (c * c + d * d), 2 * (b * c - a * d) , 2 * (b * d + a * c) , 0, + 2 * (b * c + a * d) , 1 - 2 * (b * b + d * d), 2 * (c * d - a * b) , 0, + 2 * (b * d - a * c) , 2 * (c * d + a * b) , 1 - 2 * (b * b + c * c), 0, + 0 , 0 , 0 , 1, + }; + return R; +} + +template +Matx Quat::toRotMat3x3(QuatAssumeType assumeUnit) const +{ + T a = w, b = x, c = y, d = z; + if (!assumeUnit) + { + Quat qTemp = normalize(); + a = qTemp.w; + b = qTemp.x; + c = qTemp.y; + d = qTemp.z; + } + Matx R{ + 1 - 2 * (c * c + d * d), 2 * (b * c - a * d) , 2 * (b * d + a * c), + 2 * (b * c + a * d) , 1 - 2 * (b * b + d * d), 2 * (c * d - a * b), + 2 * (b * d - a * c) , 2 * (c * d + a * b) , 1 - 2 * (b * b + c * c) + }; + return R; +} + +template +Vec Quat::toRotVec(QuatAssumeType assumeUnit) const +{ + T angle = getAngle(assumeUnit); + Vec axis = getAxis(assumeUnit); + return angle * axis; +} + +template +Vec Quat::toVec() const +{ + return Vec{w, x, y, z}; +} + +template +Quat Quat::lerp(const Quat &q0, const Quat &q1, const T t) +{ + return (1 - t) * q0 + t * q1; +} + +template +Quat Quat::slerp(const Quat &q0, const Quat &q1, const T t, QuatAssumeType assumeUnit, bool directChange) +{ + Quat v0(q0); + Quat v1(q1); + if (!assumeUnit) + { + v0 = v0.normalize(); + v1 = v1.normalize(); + } + T cosTheta = v0.dot(v1); + constexpr T DOT_THRESHOLD = 0.995; + if (std::abs(cosTheta) > DOT_THRESHOLD) + { + return nlerp(v0, v1, t, QUAT_ASSUME_UNIT); + } + + if (directChange && cosTheta < 0) + { + v0 = -v0; + cosTheta = -cosTheta; + } + T sinTheta = std::sqrt(1 - cosTheta * cosTheta); + T angle = atan2(sinTheta, cosTheta); + return (std::sin((1 - t) * angle) / (sinTheta) * v0 + std::sin(t * angle) / (sinTheta) * v1).normalize(); +} + + +template +inline Quat Quat::nlerp(const Quat &q0, const Quat &q1, const T t, QuatAssumeType assumeUnit) +{ + Quat v0(q0), v1(q1); + if (v1.dot(v0) < 0) + { + v0 = -v0; + } + if (assumeUnit) + { + return ((1 - t) * v0 + t * v1).normalize(); + } + v0 = v0.normalize(); + v1 = v1.normalize(); + return ((1 - t) * v0 + t * v1).normalize(); +} + + +template +inline bool Quat::isNormal(T eps) const +{ + + double normVar = norm(); + if ((normVar > 1 - eps) && (normVar < 1 + eps)) + return true; + return false; +} + +template +inline void Quat::assertNormal(T eps) const +{ + if (!isNormal(eps)) + CV_Error(Error::StsBadArg, "Quaternion should be normalized"); +} + + +template +inline Quat Quat::squad(const Quat &q0, const Quat &q1, + const Quat &q2, const Quat &q3, + const T t, QuatAssumeType assumeUnit, + bool directChange) +{ + Quat v0(q0), v1(q1), v2(q2), v3(q3); + if (!assumeUnit) + { + v0 = v0.normalize(); + v1 = v1.normalize(); + v2 = v2.normalize(); + v3 = v3.normalize(); + } + + Quat c0 = slerp(v0, v3, t, assumeUnit, directChange); + Quat c1 = slerp(v1, v2, t, assumeUnit, directChange); + return slerp(c0, c1, 2 * t * (1 - t), assumeUnit, directChange); +} + +template +Quat Quat::interPoint(const Quat &q0, const Quat &q1, + const Quat &q2, QuatAssumeType assumeUnit) +{ + Quat v0(q0), v1(q1), v2(q2); + if (!assumeUnit) + { + v0 = v0.normalize(); + v1 = v1.normalize(); + v2 = v2.normalize(); + } + return v1 * cv::exp(-(cv::log(v1.conjugate() * v0, assumeUnit) + (cv::log(v1.conjugate() * v2, assumeUnit))) / 4); +} + +template +Quat Quat::spline(const Quat &q0, const Quat &q1, const Quat &q2, const Quat &q3, const T t, QuatAssumeType assumeUnit) +{ + Quat v0(q0), v1(q1), v2(q2), v3(q3); + if (!assumeUnit) + { + v0 = v0.normalize(); + v1 = v1.normalize(); + v2 = v2.normalize(); + v3 = v3.normalize(); + } + T cosTheta; + std::vector> vec{v0, v1, v2, v3}; + for (size_t i = 0; i < 3; ++i) + { + cosTheta = vec[i].dot(vec[i + 1]); + if (cosTheta < 0) + { + vec[i + 1] = -vec[i + 1]; + } + } + Quat s1 = interPoint(vec[0], vec[1], vec[2], QUAT_ASSUME_UNIT); + Quat s2 = interPoint(vec[1], vec[2], vec[3], QUAT_ASSUME_UNIT); + return squad(vec[1], s1, s2, vec[2], t, assumeUnit, QUAT_ASSUME_NOT_UNIT); +} + +namespace detail { + +template static +Quat createFromAxisRot(int axis, const T theta) +{ + if (axis == 0) + return Quat::createFromXRot(theta); + if (axis == 1) + return Quat::createFromYRot(theta); + if (axis == 2) + return Quat::createFromZRot(theta); + CV_Assert(0); +} + +inline bool isIntAngleType(QuatEnum::EulerAnglesType eulerAnglesType) +{ + return eulerAnglesType < QuatEnum::EXT_XYZ; +} + +inline bool isTaitBryan(QuatEnum::EulerAnglesType eulerAnglesType) +{ + return eulerAnglesType/6 == 1 || eulerAnglesType/6 == 3; +} +} // namespace detail + +template +Quat Quat::createFromYRot(const T theta) +{ + return Quat{std::cos(theta * 0.5f), 0, std::sin(theta * 0.5f), 0}; +} + +template +Quat Quat::createFromXRot(const T theta){ + return Quat{std::cos(theta * 0.5f), std::sin(theta * 0.5f), 0, 0}; +} + +template +Quat Quat::createFromZRot(const T theta){ + return Quat{std::cos(theta * 0.5f), 0, 0, std::sin(theta * 0.5f)}; +} + + +template +Quat Quat::createFromEulerAngles(const Vec &angles, QuatEnum::EulerAnglesType eulerAnglesType) { + CV_Assert(eulerAnglesType < QuatEnum::EulerAnglesType::EULER_ANGLES_MAX_VALUE); + static const int rotationAxis[24][3] = { + {0, 1, 2}, ///< Intrinsic rotations with the Euler angles type X-Y-Z + {0, 2, 1}, ///< Intrinsic rotations with the Euler angles type X-Z-Y + {1, 0, 2}, ///< Intrinsic rotations with the Euler angles type Y-X-Z + {1, 2, 0}, ///< Intrinsic rotations with the Euler angles type Y-Z-X + {2, 0, 1}, ///< Intrinsic rotations with the Euler angles type Z-X-Y + {2, 1, 0}, ///< Intrinsic rotations with the Euler angles type Z-Y-X + {0, 1, 0}, ///< Intrinsic rotations with the Euler angles type X-Y-X + {0, 2, 0}, ///< Intrinsic rotations with the Euler angles type X-Z-X + {1, 0, 1}, ///< Intrinsic rotations with the Euler angles type Y-X-Y + {1, 2, 1}, ///< Intrinsic rotations with the Euler angles type Y-Z-Y + {2, 0, 2}, ///< Intrinsic rotations with the Euler angles type Z-X-Z + {2, 1, 2}, ///< Intrinsic rotations with the Euler angles type Z-Y-Z + {0, 1, 2}, ///< Extrinsic rotations with the Euler angles type X-Y-Z + {0, 2, 1}, ///< Extrinsic rotations with the Euler angles type X-Z-Y + {1, 0, 2}, ///< Extrinsic rotations with the Euler angles type Y-X-Z + {1, 2, 0}, ///< Extrinsic rotations with the Euler angles type Y-Z-X + {2, 0, 1}, ///< Extrinsic rotations with the Euler angles type Z-X-Y + {2, 1, 0}, ///< Extrinsic rotations with the Euler angles type Z-Y-X + {0, 1, 0}, ///< Extrinsic rotations with the Euler angles type X-Y-X + {0, 2, 0}, ///< Extrinsic rotations with the Euler angles type X-Z-X + {1, 0, 1}, ///< Extrinsic rotations with the Euler angles type Y-X-Y + {1, 2, 1}, ///< Extrinsic rotations with the Euler angles type Y-Z-Y + {2, 0, 2}, ///< Extrinsic rotations with the Euler angles type Z-X-Z + {2, 1, 2} ///< Extrinsic rotations with the Euler angles type Z-Y-Z + }; + Quat q1 = detail::createFromAxisRot(rotationAxis[eulerAnglesType][0], angles(0)); + Quat q2 = detail::createFromAxisRot(rotationAxis[eulerAnglesType][1], angles(1)); + Quat q3 = detail::createFromAxisRot(rotationAxis[eulerAnglesType][2], angles(2)); + if (detail::isIntAngleType(eulerAnglesType)) + { + return q1 * q2 * q3; + } + else // (!detail::isIntAngleType(eulerAnglesType)) + { + return q3 * q2 * q1; + } +} + +template +Vec Quat::toEulerAngles(QuatEnum::EulerAnglesType eulerAnglesType){ + CV_Assert(eulerAnglesType < QuatEnum::EulerAnglesType::EULER_ANGLES_MAX_VALUE); + Matx33d R = toRotMat3x3(); + enum { + C_ZERO, + C_PI, + C_PI_2, + N_CONSTANTS, + R_0_0 = N_CONSTANTS, R_0_1, R_0_2, + R_1_0, R_1_1, R_1_2, + R_2_0, R_2_1, R_2_2 + }; + static const T constants_[N_CONSTANTS] = { + 0, // C_ZERO + (T)CV_PI, // C_PI + (T)(CV_PI * 0.5) // C_PI_2, -C_PI_2 + }; + static const int rotationR_[24][12] = { + {+R_0_2, +R_1_0, +R_1_1, C_PI_2, +R_2_1, +R_1_1, -C_PI_2, -R_1_2, +R_2_2, +R_0_2, -R_0_1, +R_0_0}, // INT_XYZ + {+R_0_1, -R_1_2, +R_2_2, -C_PI_2, +R_2_0, +R_2_2, C_PI_2, +R_2_1, +R_1_1, -R_0_1, +R_0_2, +R_0_0}, // INT_XZY + {+R_1_2, -R_0_1, +R_0_0, -C_PI_2, +R_0_1, +R_0_0, C_PI_2, +R_0_2, +R_2_2, -R_1_2, +R_1_0, +R_1_1}, // INT_YXZ + {+R_1_0, +R_0_2, +R_2_2, C_PI_2, +R_0_2, +R_0_1, -C_PI_2, -R_2_0, +R_0_0, +R_1_0, -R_1_2, +R_1_1}, // INT_YZX + {+R_2_1, +R_1_0, +R_0_0, C_PI_2, +R_1_0, +R_0_0, -C_PI_2, -R_0_1, +R_1_1, +R_2_1, -R_2_0, +R_2_2}, // INT_ZXY + {+R_2_0, -R_0_1, +R_1_1, -C_PI_2, +R_1_2, +R_1_1, C_PI_2, +R_1_0, +R_0_0, -R_2_0, +R_2_1, +R_2_2}, // INT_ZYX + {+R_0_0, +R_2_1, +R_2_2, C_ZERO, +R_1_2, +R_1_1, C_PI, +R_1_0, -R_2_0, +R_0_0, +R_0_1, +R_0_2}, // INT_XYX + {+R_0_0, +R_2_1, +R_2_2, C_ZERO, -R_2_1, +R_2_2, C_PI, +R_2_0, +R_1_0, +R_0_0, +R_0_2, -R_0_1}, // INT_XZX + {+R_1_1, +R_0_2, +R_0_0, C_ZERO, -R_2_0, +R_0_0, C_PI, +R_0_1, +R_2_1, +R_1_1, +R_1_0, -R_1_2}, // INT_YXY + {+R_1_1, +R_0_2, +R_0_0, C_ZERO, +R_0_2, -R_0_0, C_PI, +R_2_1, -R_0_1, +R_1_1, +R_1_2, +R_1_0}, // INT_YZY + {+R_2_2, +R_1_0, +R_1_1, C_ZERO, +R_1_0, +R_0_0, C_PI, +R_0_2, -R_1_2, +R_2_2, +R_2_0, +R_2_1}, // INT_ZXZ + {+R_2_2, +R_1_0, +R_0_0, C_ZERO, +R_1_0, +R_0_0, C_PI, +R_1_2, +R_0_2, +R_2_2, +R_2_1, -R_2_0}, // INT_ZYZ + + {+R_2_0, -C_PI_2, -R_0_1, +R_1_1, C_PI_2, +R_1_2, +R_1_1, +R_2_1, +R_2_2, -R_2_0, +R_1_0, +R_0_0}, // EXT_XYZ + {+R_1_0, C_PI_2, +R_0_2, +R_2_2, -C_PI_2, +R_0_2, +R_0_1, -R_1_2, +R_1_1, +R_1_0, -R_2_0, +R_0_0}, // EXT_XZY + {+R_2_1, C_PI_2, +R_1_0, +R_0_0, -C_PI_2, +R_1_0, +R_0_0, -R_2_0, +R_2_2, +R_2_1, -R_0_1, +R_1_1}, // EXT_YXZ + {+R_0_2, -C_PI_2, -R_1_2, +R_2_2, C_PI_2, +R_2_0, +R_2_2, +R_0_2, +R_0_0, -R_0_1, +R_2_1, +R_1_1}, // EXT_YZX + {+R_1_2, -C_PI_2, -R_0_1, +R_0_0, C_PI_2, +R_0_1, +R_0_0, +R_1_0, +R_1_1, -R_1_2, +R_0_2, +R_2_2}, // EXT_ZXY + {+R_0_2, C_PI_2, +R_1_0, +R_1_1, -C_PI_2, +R_2_1, +R_1_1, -R_0_1, +R_0_0, +R_0_2, -R_1_2, +R_2_2}, // EXT_ZYX + {+R_0_0, C_ZERO, +R_2_1, +R_2_2, C_PI, +R_1_2, +R_1_1, +R_0_1, +R_0_2, +R_0_0, +R_1_0, -R_2_0}, // EXT_XYX + {+R_0_0, C_ZERO, +R_2_1, +R_2_2, C_PI, +R_2_1, +R_2_2, +R_0_2, -R_0_1, +R_0_0, +R_2_0, +R_1_0}, // EXT_XZX + {+R_1_1, C_ZERO, +R_0_2, +R_0_0, C_PI, -R_2_0, +R_0_0, +R_1_0, -R_1_2, +R_1_1, +R_0_1, +R_2_1}, // EXT_YXY + {+R_1_1, C_ZERO, +R_0_2, +R_0_0, C_PI, +R_0_2, -R_0_0, +R_1_2, +R_1_0, +R_1_1, +R_2_1, -R_0_1}, // EXT_YZY + {+R_2_2, C_ZERO, +R_1_0, +R_1_1, C_PI, +R_1_0, +R_0_0, +R_2_0, +R_2_1, +R_2_2, +R_0_2, -R_1_2}, // EXT_ZXZ + {+R_2_2, C_ZERO, +R_1_0, +R_0_0, C_PI, +R_1_0, +R_0_0, +R_2_1, -R_2_0, +R_2_2, +R_1_2, +R_0_2}, // EXT_ZYZ + }; + T rotationR[12]; + for (int i = 0; i < 12; i++) + { + int id = rotationR_[eulerAnglesType][i]; + unsigned idx = std::abs(id); + T value = 0.0f; + if (idx < N_CONSTANTS) + { + value = constants_[idx]; + } + else + { + unsigned r_idx = idx - N_CONSTANTS; + CV_DbgAssert(r_idx < 9); + value = R.val[r_idx]; + } + bool isNegative = id < 0; + if (isNegative) + value = -value; + rotationR[i] = value; + } + Vec angles; + if (detail::isIntAngleType(eulerAnglesType)) + { + if (abs(rotationR[0] - 1) < CV_QUAT_CONVERT_THRESHOLD) + { + CV_LOG_WARNING(NULL,"Gimbal Lock occurs. Euler angles are non-unique, we set the third angle to 0"); + angles = {std::atan2(rotationR[1], rotationR[2]), rotationR[3], 0}; + return angles; + } + else if(abs(rotationR[0] + 1) < CV_QUAT_CONVERT_THRESHOLD) + { + CV_LOG_WARNING(NULL,"Gimbal Lock occurs. Euler angles are non-unique, we set the third angle to 0"); + angles = {std::atan2(rotationR[4], rotationR[5]), rotationR[6], 0}; + return angles; + } + } + else // (!detail::isIntAngleType(eulerAnglesType)) + { + if (abs(rotationR[0] - 1) < CV_QUAT_CONVERT_THRESHOLD) + { + CV_LOG_WARNING(NULL,"Gimbal Lock occurs. Euler angles are non-unique, we set the first angle to 0"); + angles = {0, rotationR[1], std::atan2(rotationR[2], rotationR[3])}; + return angles; + } + else if (abs(rotationR[0] + 1) < CV_QUAT_CONVERT_THRESHOLD) + { + CV_LOG_WARNING(NULL,"Gimbal Lock occurs. Euler angles are non-unique, we set the first angle to 0"); + angles = {0, rotationR[4], std::atan2(rotationR[5], rotationR[6])}; + return angles; + } + } + + angles(0) = std::atan2(rotationR[7], rotationR[8]); + if (detail::isTaitBryan(eulerAnglesType)) + angles(1) = std::acos(rotationR[9]); + else + angles(1) = std::asin(rotationR[9]); + angles(2) = std::atan2(rotationR[10], rotationR[11]); + return angles; +} + +} // namepsace +//! @endcond + +#endif /*OPENCV_CORE_QUATERNION_INL_HPP*/ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/saturate.hpp b/3rdParty/opencv-4.11.0/opencv2/core/saturate.hpp index 18ffd1c7af..04951d42f2 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/saturate.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/saturate.hpp @@ -1,180 +1,180 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2014, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CORE_SATURATE_HPP -#define OPENCV_CORE_SATURATE_HPP - -#include "opencv2/core/cvdef.h" -#include -#include "opencv2/core/fast_math.hpp" - -namespace cv -{ - -//! @addtogroup core_utils -//! @{ - -/////////////// saturate_cast (used in image & signal processing) /////////////////// - -/** @brief Template function for accurate conversion from one primitive type to another. - - The function saturate_cast resembles the standard C++ cast operations, such as static_cast\() - and others. It perform an efficient and accurate conversion from one primitive type to another - (see the introduction chapter). saturate in the name means that when the input value v is out of the - range of the target type, the result is not formed just by taking low bits of the input, but instead - the value is clipped. For example: - @code - uchar a = saturate_cast(-100); // a = 0 (UCHAR_MIN) - short b = saturate_cast(33333.33333); // b = 32767 (SHRT_MAX) - @endcode - Such clipping is done when the target type is unsigned char , signed char , unsigned short or - signed short . For 32-bit integers, no clipping is done. - - When the parameter is a floating-point value and the target type is an integer (8-, 16- or 32-bit), - the floating-point value is first rounded to the nearest integer and then clipped if needed (when - the target type is 8- or 16-bit). - - @param v Function parameter. - @sa add, subtract, multiply, divide, Mat::convertTo - */ -template static inline _Tp saturate_cast(uchar v) { return _Tp(v); } -/** @overload */ -template static inline _Tp saturate_cast(schar v) { return _Tp(v); } -/** @overload */ -template static inline _Tp saturate_cast(ushort v) { return _Tp(v); } -/** @overload */ -template static inline _Tp saturate_cast(short v) { return _Tp(v); } -/** @overload */ -template static inline _Tp saturate_cast(unsigned v) { return _Tp(v); } -/** @overload */ -template static inline _Tp saturate_cast(int v) { return _Tp(v); } -/** @overload */ -template static inline _Tp saturate_cast(float v) { return _Tp(v); } -/** @overload */ -template static inline _Tp saturate_cast(double v) { return _Tp(v); } -/** @overload */ -template static inline _Tp saturate_cast(int64 v) { return _Tp(v); } -/** @overload */ -template static inline _Tp saturate_cast(uint64 v) { return _Tp(v); } - -template<> inline uchar saturate_cast(schar v) { return (uchar)std::max((int)v, 0); } -template<> inline uchar saturate_cast(ushort v) { return (uchar)std::min((unsigned)v, (unsigned)UCHAR_MAX); } -template<> inline uchar saturate_cast(int v) { return (uchar)((unsigned)v <= UCHAR_MAX ? v : v > 0 ? UCHAR_MAX : 0); } -template<> inline uchar saturate_cast(short v) { return saturate_cast((int)v); } -template<> inline uchar saturate_cast(unsigned v) { return (uchar)std::min(v, (unsigned)UCHAR_MAX); } -template<> inline uchar saturate_cast(float v) { int iv = cvRound(v); return saturate_cast(iv); } -template<> inline uchar saturate_cast(double v) { int iv = cvRound(v); return saturate_cast(iv); } -template<> inline uchar saturate_cast(int64 v) { return (uchar)((uint64)v <= (uint64)UCHAR_MAX ? v : v > 0 ? UCHAR_MAX : 0); } -template<> inline uchar saturate_cast(uint64 v) { return (uchar)std::min(v, (uint64)UCHAR_MAX); } - -template<> inline schar saturate_cast(uchar v) { return (schar)std::min((int)v, SCHAR_MAX); } -template<> inline schar saturate_cast(ushort v) { return (schar)std::min((unsigned)v, (unsigned)SCHAR_MAX); } -template<> inline schar saturate_cast(int v) { return (schar)((unsigned)(v-SCHAR_MIN) <= (unsigned)UCHAR_MAX ? v : v > 0 ? SCHAR_MAX : SCHAR_MIN); } -template<> inline schar saturate_cast(short v) { return saturate_cast((int)v); } -template<> inline schar saturate_cast(unsigned v) { return (schar)std::min(v, (unsigned)SCHAR_MAX); } -template<> inline schar saturate_cast(float v) { int iv = cvRound(v); return saturate_cast(iv); } -template<> inline schar saturate_cast(double v) { int iv = cvRound(v); return saturate_cast(iv); } -template<> inline schar saturate_cast(int64 v) { return (schar)((uint64)((int64)v-SCHAR_MIN) <= (uint64)UCHAR_MAX ? v : v > 0 ? SCHAR_MAX : SCHAR_MIN); } -template<> inline schar saturate_cast(uint64 v) { return (schar)std::min(v, (uint64)SCHAR_MAX); } - -template<> inline ushort saturate_cast(schar v) { return (ushort)std::max((int)v, 0); } -template<> inline ushort saturate_cast(short v) { return (ushort)std::max((int)v, 0); } -template<> inline ushort saturate_cast(int v) { return (ushort)((unsigned)v <= (unsigned)USHRT_MAX ? v : v > 0 ? USHRT_MAX : 0); } -template<> inline ushort saturate_cast(unsigned v) { return (ushort)std::min(v, (unsigned)USHRT_MAX); } -template<> inline ushort saturate_cast(float v) { int iv = cvRound(v); return saturate_cast(iv); } -template<> inline ushort saturate_cast(double v) { int iv = cvRound(v); return saturate_cast(iv); } -template<> inline ushort saturate_cast(int64 v) { return (ushort)((uint64)v <= (uint64)USHRT_MAX ? v : v > 0 ? USHRT_MAX : 0); } -template<> inline ushort saturate_cast(uint64 v) { return (ushort)std::min(v, (uint64)USHRT_MAX); } - -template<> inline short saturate_cast(ushort v) { return (short)std::min((int)v, SHRT_MAX); } -template<> inline short saturate_cast(int v) { return (short)((unsigned)(v - SHRT_MIN) <= (unsigned)USHRT_MAX ? v : v > 0 ? SHRT_MAX : SHRT_MIN); } -template<> inline short saturate_cast(unsigned v) { return (short)std::min(v, (unsigned)SHRT_MAX); } -template<> inline short saturate_cast(float v) { int iv = cvRound(v); return saturate_cast(iv); } -template<> inline short saturate_cast(double v) { int iv = cvRound(v); return saturate_cast(iv); } -template<> inline short saturate_cast(int64 v) { return (short)((uint64)((int64)v - SHRT_MIN) <= (uint64)USHRT_MAX ? v : v > 0 ? SHRT_MAX : SHRT_MIN); } -template<> inline short saturate_cast(uint64 v) { return (short)std::min(v, (uint64)SHRT_MAX); } - -template<> inline int saturate_cast(unsigned v) { return (int)std::min(v, (unsigned)INT_MAX); } -template<> inline int saturate_cast(int64 v) { return (int)((uint64)(v - INT_MIN) <= (uint64)UINT_MAX ? v : v > 0 ? INT_MAX : INT_MIN); } -template<> inline int saturate_cast(uint64 v) { return (int)std::min(v, (uint64)INT_MAX); } -template<> inline int saturate_cast(float v) { return cvRound(v); } -template<> inline int saturate_cast(double v) { return cvRound(v); } - -template<> inline unsigned saturate_cast(schar v) { return (unsigned)std::max(v, (schar)0); } -template<> inline unsigned saturate_cast(short v) { return (unsigned)std::max(v, (short)0); } -template<> inline unsigned saturate_cast(int v) { return (unsigned)std::max(v, (int)0); } -template<> inline unsigned saturate_cast(int64 v) { return (unsigned)((uint64)v <= (uint64)UINT_MAX ? v : v > 0 ? UINT_MAX : 0); } -template<> inline unsigned saturate_cast(uint64 v) { return (unsigned)std::min(v, (uint64)UINT_MAX); } -// we intentionally do not clip negative numbers, to make -1 become 0xffffffff etc. -template<> inline unsigned saturate_cast(float v) { return static_cast(cvRound(v)); } -template<> inline unsigned saturate_cast(double v) { return static_cast(cvRound(v)); } - -template<> inline uint64 saturate_cast(schar v) { return (uint64)std::max(v, (schar)0); } -template<> inline uint64 saturate_cast(short v) { return (uint64)std::max(v, (short)0); } -template<> inline uint64 saturate_cast(int v) { return (uint64)std::max(v, (int)0); } -template<> inline uint64 saturate_cast(int64 v) { return (uint64)std::max(v, (int64)0); } - -template<> inline int64 saturate_cast(uint64 v) { return (int64)std::min(v, (uint64)LLONG_MAX); } - -/** @overload */ -template static inline _Tp saturate_cast(hfloat v) { return saturate_cast<_Tp>((float)v); } - -// in theory, we could use a LUT for 8u/8s->16f conversion, -// but with hardware support for FP32->FP16 conversion the current approach is preferable -template<> inline hfloat saturate_cast(uchar v) { return hfloat((float)v); } -template<> inline hfloat saturate_cast(schar v) { return hfloat((float)v); } -template<> inline hfloat saturate_cast(ushort v) { return hfloat((float)v); } -template<> inline hfloat saturate_cast(short v) { return hfloat((float)v); } -template<> inline hfloat saturate_cast(unsigned v){ return hfloat((float)v); } -template<> inline hfloat saturate_cast(int v) { return hfloat((float)v); } -template<> inline hfloat saturate_cast(uint64 v) { return hfloat((float)v); } -template<> inline hfloat saturate_cast(int64 v) { return hfloat((float)v); } -template<> inline hfloat saturate_cast(float v) { return hfloat(v); } -template<> inline hfloat saturate_cast(double v) { return hfloat((float)v); } - -//! @} - -} // cv - -#endif // OPENCV_CORE_SATURATE_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2014, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CORE_SATURATE_HPP +#define OPENCV_CORE_SATURATE_HPP + +#include "opencv2/core/cvdef.h" +#include +#include "opencv2/core/fast_math.hpp" + +namespace cv +{ + +//! @addtogroup core_utils +//! @{ + +/////////////// saturate_cast (used in image & signal processing) /////////////////// + +/** @brief Template function for accurate conversion from one primitive type to another. + + The function saturate_cast resembles the standard C++ cast operations, such as static_cast\() + and others. It perform an efficient and accurate conversion from one primitive type to another + (see the introduction chapter). saturate in the name means that when the input value v is out of the + range of the target type, the result is not formed just by taking low bits of the input, but instead + the value is clipped. For example: + @code + uchar a = saturate_cast(-100); // a = 0 (UCHAR_MIN) + short b = saturate_cast(33333.33333); // b = 32767 (SHRT_MAX) + @endcode + Such clipping is done when the target type is unsigned char , signed char , unsigned short or + signed short . For 32-bit integers, no clipping is done. + + When the parameter is a floating-point value and the target type is an integer (8-, 16- or 32-bit), + the floating-point value is first rounded to the nearest integer and then clipped if needed (when + the target type is 8- or 16-bit). + + @param v Function parameter. + @sa add, subtract, multiply, divide, Mat::convertTo + */ +template static inline _Tp saturate_cast(uchar v) { return _Tp(v); } +/** @overload */ +template static inline _Tp saturate_cast(schar v) { return _Tp(v); } +/** @overload */ +template static inline _Tp saturate_cast(ushort v) { return _Tp(v); } +/** @overload */ +template static inline _Tp saturate_cast(short v) { return _Tp(v); } +/** @overload */ +template static inline _Tp saturate_cast(unsigned v) { return _Tp(v); } +/** @overload */ +template static inline _Tp saturate_cast(int v) { return _Tp(v); } +/** @overload */ +template static inline _Tp saturate_cast(float v) { return _Tp(v); } +/** @overload */ +template static inline _Tp saturate_cast(double v) { return _Tp(v); } +/** @overload */ +template static inline _Tp saturate_cast(int64 v) { return _Tp(v); } +/** @overload */ +template static inline _Tp saturate_cast(uint64 v) { return _Tp(v); } + +template<> inline uchar saturate_cast(schar v) { return (uchar)std::max((int)v, 0); } +template<> inline uchar saturate_cast(ushort v) { return (uchar)std::min((unsigned)v, (unsigned)UCHAR_MAX); } +template<> inline uchar saturate_cast(int v) { return (uchar)((unsigned)v <= UCHAR_MAX ? v : v > 0 ? UCHAR_MAX : 0); } +template<> inline uchar saturate_cast(short v) { return saturate_cast((int)v); } +template<> inline uchar saturate_cast(unsigned v) { return (uchar)std::min(v, (unsigned)UCHAR_MAX); } +template<> inline uchar saturate_cast(float v) { int iv = cvRound(v); return saturate_cast(iv); } +template<> inline uchar saturate_cast(double v) { int iv = cvRound(v); return saturate_cast(iv); } +template<> inline uchar saturate_cast(int64 v) { return (uchar)((uint64)v <= (uint64)UCHAR_MAX ? v : v > 0 ? UCHAR_MAX : 0); } +template<> inline uchar saturate_cast(uint64 v) { return (uchar)std::min(v, (uint64)UCHAR_MAX); } + +template<> inline schar saturate_cast(uchar v) { return (schar)std::min((int)v, SCHAR_MAX); } +template<> inline schar saturate_cast(ushort v) { return (schar)std::min((unsigned)v, (unsigned)SCHAR_MAX); } +template<> inline schar saturate_cast(int v) { return (schar)((unsigned)(v-SCHAR_MIN) <= (unsigned)UCHAR_MAX ? v : v > 0 ? SCHAR_MAX : SCHAR_MIN); } +template<> inline schar saturate_cast(short v) { return saturate_cast((int)v); } +template<> inline schar saturate_cast(unsigned v) { return (schar)std::min(v, (unsigned)SCHAR_MAX); } +template<> inline schar saturate_cast(float v) { int iv = cvRound(v); return saturate_cast(iv); } +template<> inline schar saturate_cast(double v) { int iv = cvRound(v); return saturate_cast(iv); } +template<> inline schar saturate_cast(int64 v) { return (schar)((uint64)((int64)v-SCHAR_MIN) <= (uint64)UCHAR_MAX ? v : v > 0 ? SCHAR_MAX : SCHAR_MIN); } +template<> inline schar saturate_cast(uint64 v) { return (schar)std::min(v, (uint64)SCHAR_MAX); } + +template<> inline ushort saturate_cast(schar v) { return (ushort)std::max((int)v, 0); } +template<> inline ushort saturate_cast(short v) { return (ushort)std::max((int)v, 0); } +template<> inline ushort saturate_cast(int v) { return (ushort)((unsigned)v <= (unsigned)USHRT_MAX ? v : v > 0 ? USHRT_MAX : 0); } +template<> inline ushort saturate_cast(unsigned v) { return (ushort)std::min(v, (unsigned)USHRT_MAX); } +template<> inline ushort saturate_cast(float v) { int iv = cvRound(v); return saturate_cast(iv); } +template<> inline ushort saturate_cast(double v) { int iv = cvRound(v); return saturate_cast(iv); } +template<> inline ushort saturate_cast(int64 v) { return (ushort)((uint64)v <= (uint64)USHRT_MAX ? v : v > 0 ? USHRT_MAX : 0); } +template<> inline ushort saturate_cast(uint64 v) { return (ushort)std::min(v, (uint64)USHRT_MAX); } + +template<> inline short saturate_cast(ushort v) { return (short)std::min((int)v, SHRT_MAX); } +template<> inline short saturate_cast(int v) { return (short)((unsigned)(v - SHRT_MIN) <= (unsigned)USHRT_MAX ? v : v > 0 ? SHRT_MAX : SHRT_MIN); } +template<> inline short saturate_cast(unsigned v) { return (short)std::min(v, (unsigned)SHRT_MAX); } +template<> inline short saturate_cast(float v) { int iv = cvRound(v); return saturate_cast(iv); } +template<> inline short saturate_cast(double v) { int iv = cvRound(v); return saturate_cast(iv); } +template<> inline short saturate_cast(int64 v) { return (short)((uint64)((int64)v - SHRT_MIN) <= (uint64)USHRT_MAX ? v : v > 0 ? SHRT_MAX : SHRT_MIN); } +template<> inline short saturate_cast(uint64 v) { return (short)std::min(v, (uint64)SHRT_MAX); } + +template<> inline int saturate_cast(unsigned v) { return (int)std::min(v, (unsigned)INT_MAX); } +template<> inline int saturate_cast(int64 v) { return (int)((uint64)(v - INT_MIN) <= (uint64)UINT_MAX ? v : v > 0 ? INT_MAX : INT_MIN); } +template<> inline int saturate_cast(uint64 v) { return (int)std::min(v, (uint64)INT_MAX); } +template<> inline int saturate_cast(float v) { return cvRound(v); } +template<> inline int saturate_cast(double v) { return cvRound(v); } + +template<> inline unsigned saturate_cast(schar v) { return (unsigned)std::max(v, (schar)0); } +template<> inline unsigned saturate_cast(short v) { return (unsigned)std::max(v, (short)0); } +template<> inline unsigned saturate_cast(int v) { return (unsigned)std::max(v, (int)0); } +template<> inline unsigned saturate_cast(int64 v) { return (unsigned)((uint64)v <= (uint64)UINT_MAX ? v : v > 0 ? UINT_MAX : 0); } +template<> inline unsigned saturate_cast(uint64 v) { return (unsigned)std::min(v, (uint64)UINT_MAX); } +// we intentionally do not clip negative numbers, to make -1 become 0xffffffff etc. +template<> inline unsigned saturate_cast(float v) { return static_cast(cvRound(v)); } +template<> inline unsigned saturate_cast(double v) { return static_cast(cvRound(v)); } + +template<> inline uint64 saturate_cast(schar v) { return (uint64)std::max(v, (schar)0); } +template<> inline uint64 saturate_cast(short v) { return (uint64)std::max(v, (short)0); } +template<> inline uint64 saturate_cast(int v) { return (uint64)std::max(v, (int)0); } +template<> inline uint64 saturate_cast(int64 v) { return (uint64)std::max(v, (int64)0); } + +template<> inline int64 saturate_cast(uint64 v) { return (int64)std::min(v, (uint64)LLONG_MAX); } + +/** @overload */ +template static inline _Tp saturate_cast(hfloat v) { return saturate_cast<_Tp>((float)v); } + +// in theory, we could use a LUT for 8u/8s->16f conversion, +// but with hardware support for FP32->FP16 conversion the current approach is preferable +template<> inline hfloat saturate_cast(uchar v) { return hfloat((float)v); } +template<> inline hfloat saturate_cast(schar v) { return hfloat((float)v); } +template<> inline hfloat saturate_cast(ushort v) { return hfloat((float)v); } +template<> inline hfloat saturate_cast(short v) { return hfloat((float)v); } +template<> inline hfloat saturate_cast(unsigned v){ return hfloat((float)v); } +template<> inline hfloat saturate_cast(int v) { return hfloat((float)v); } +template<> inline hfloat saturate_cast(uint64 v) { return hfloat((float)v); } +template<> inline hfloat saturate_cast(int64 v) { return hfloat((float)v); } +template<> inline hfloat saturate_cast(float v) { return hfloat(v); } +template<> inline hfloat saturate_cast(double v) { return hfloat((float)v); } + +//! @} + +} // cv + +#endif // OPENCV_CORE_SATURATE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/simd_intrinsics.hpp b/3rdParty/opencv-4.11.0/opencv2/core/simd_intrinsics.hpp index 2658d92c89..93453d5eea 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/simd_intrinsics.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/simd_intrinsics.hpp @@ -1,87 +1,87 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_SIMD_INTRINSICS_HPP -#define OPENCV_CORE_SIMD_INTRINSICS_HPP - -/** -Helper header to support SIMD intrinsics (universal intrinsics) in user code. -Intrinsics documentation: https://docs.opencv.org/4.x/df/d91/group__core__hal__intrin.html - - -Checks of target CPU instruction set based on compiler definitions don't work well enough. -More reliable solutions require utilization of configuration systems (like CMake). - -So, probably you need to specify your own configuration. - -You can do that via CMake in this way: - add_definitions(/DOPENCV_SIMD_CONFIG_HEADER=opencv_simd_config_custom.hpp) -or - add_definitions(/DOPENCV_SIMD_CONFIG_INCLUDE_DIR=1) - -Additionally you may need to add include directory to your files: - include_directories("${CMAKE_CURRENT_LIST_DIR}/opencv_config_${MYTARGET}") - -These files can be pre-generated for target configurations of your application -or generated by CMake on the fly (use CMAKE_BINARY_DIR for that). - -Notes: -- H/W capability checks are still responsibility of your application -- runtime dispatching is not covered by this helper header -*/ - -#ifdef __OPENCV_BUILD -#error "Use core/hal/intrin.hpp during OpenCV build" -#endif - -#ifdef OPENCV_HAL_INTRIN_HPP -#error "core/simd_intrinsics.hpp must be included before core/hal/intrin.hpp" -#endif - -#include "opencv2/core/cvdef.h" - -#ifdef OPENCV_SIMD_CONFIG_HEADER -#include CVAUX_STR(OPENCV_SIMD_CONFIG_HEADER) -#elif defined(OPENCV_SIMD_CONFIG_INCLUDE_DIR) -#include "opencv_simd_config.hpp" // corresponding directory should be added via -I compiler parameter -#else // custom config headers - -#if (!defined(CV_AVX_512F) || !CV_AVX_512F) && (defined(__AVX512__) || defined(__AVX512F__)) -# include -# undef CV_AVX_512F -# define CV_AVX_512F 1 -# ifndef OPENCV_SIMD_DONT_ASSUME_SKX // Skylake-X with AVX-512F/CD/BW/DQ/VL -# undef CV_AVX512_SKX -# define CV_AVX512_SKX 1 -# undef CV_AVX_512CD -# define CV_AVX_512CD 1 -# undef CV_AVX_512BW -# define CV_AVX_512BW 1 -# undef CV_AVX_512DQ -# define CV_AVX_512DQ 1 -# undef CV_AVX_512VL -# define CV_AVX_512VL 1 -# endif -#endif // AVX512 - -// GCC/Clang: -mavx2 -// MSVC: /arch:AVX2 -#if defined __AVX2__ -# include -# undef CV_AVX2 -# define CV_AVX2 1 -# if defined __F16C__ -# undef CV_FP16 -# define CV_FP16 1 -# endif -#endif - -#endif - -// SSE / NEON / VSX is handled by cv_cpu_dispatch.h compatibility block -#include "cv_cpu_dispatch.h" - -#include "hal/intrin.hpp" - -#endif // OPENCV_CORE_SIMD_INTRINSICS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_SIMD_INTRINSICS_HPP +#define OPENCV_CORE_SIMD_INTRINSICS_HPP + +/** +Helper header to support SIMD intrinsics (universal intrinsics) in user code. +Intrinsics documentation: https://docs.opencv.org/4.x/df/d91/group__core__hal__intrin.html + + +Checks of target CPU instruction set based on compiler definitions don't work well enough. +More reliable solutions require utilization of configuration systems (like CMake). + +So, probably you need to specify your own configuration. + +You can do that via CMake in this way: + add_definitions(/DOPENCV_SIMD_CONFIG_HEADER=opencv_simd_config_custom.hpp) +or + add_definitions(/DOPENCV_SIMD_CONFIG_INCLUDE_DIR=1) + +Additionally you may need to add include directory to your files: + include_directories("${CMAKE_CURRENT_LIST_DIR}/opencv_config_${MYTARGET}") + +These files can be pre-generated for target configurations of your application +or generated by CMake on the fly (use CMAKE_BINARY_DIR for that). + +Notes: +- H/W capability checks are still responsibility of your application +- runtime dispatching is not covered by this helper header +*/ + +#ifdef __OPENCV_BUILD +#error "Use core/hal/intrin.hpp during OpenCV build" +#endif + +#ifdef OPENCV_HAL_INTRIN_HPP +#error "core/simd_intrinsics.hpp must be included before core/hal/intrin.hpp" +#endif + +#include "opencv2/core/cvdef.h" + +#ifdef OPENCV_SIMD_CONFIG_HEADER +#include CVAUX_STR(OPENCV_SIMD_CONFIG_HEADER) +#elif defined(OPENCV_SIMD_CONFIG_INCLUDE_DIR) +#include "opencv_simd_config.hpp" // corresponding directory should be added via -I compiler parameter +#else // custom config headers + +#if (!defined(CV_AVX_512F) || !CV_AVX_512F) && (defined(__AVX512__) || defined(__AVX512F__)) +# include +# undef CV_AVX_512F +# define CV_AVX_512F 1 +# ifndef OPENCV_SIMD_DONT_ASSUME_SKX // Skylake-X with AVX-512F/CD/BW/DQ/VL +# undef CV_AVX512_SKX +# define CV_AVX512_SKX 1 +# undef CV_AVX_512CD +# define CV_AVX_512CD 1 +# undef CV_AVX_512BW +# define CV_AVX_512BW 1 +# undef CV_AVX_512DQ +# define CV_AVX_512DQ 1 +# undef CV_AVX_512VL +# define CV_AVX_512VL 1 +# endif +#endif // AVX512 + +// GCC/Clang: -mavx2 +// MSVC: /arch:AVX2 +#if defined __AVX2__ +# include +# undef CV_AVX2 +# define CV_AVX2 1 +# if defined __F16C__ +# undef CV_FP16 +# define CV_FP16 1 +# endif +#endif + +#endif + +// SSE / NEON / VSX is handled by cv_cpu_dispatch.h compatibility block +#include "cv_cpu_dispatch.h" + +#include "hal/intrin.hpp" + +#endif // OPENCV_CORE_SIMD_INTRINSICS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/softfloat.hpp b/3rdParty/opencv-4.11.0/opencv2/core/softfloat.hpp index 485e15c473..17814896ab 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/softfloat.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/softfloat.hpp @@ -1,514 +1,514 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -// This file is based on files from package issued with the following license: - -/*============================================================================ - -This C header file is part of the SoftFloat IEEE Floating-Point Arithmetic -Package, Release 3c, by John R. Hauser. - -Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the -University of California. All rights reserved. - -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. - - 3. Neither the name of the University nor the names of its contributors may - be used to endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. - -=============================================================================*/ - -#pragma once -#ifndef softfloat_h -#define softfloat_h 1 - -#include "cvdef.h" - -namespace cv -{ - -/** @addtogroup core_utils_softfloat - - [SoftFloat](http://www.jhauser.us/arithmetic/SoftFloat.html) is a software implementation - of floating-point calculations according to IEEE 754 standard. - All calculations are done in integers, that's why they are machine-independent and bit-exact. - This library can be useful in accuracy-critical parts like look-up tables generation, tests, etc. - OpenCV contains a subset of SoftFloat partially rewritten to C++. - - ### Types - - There are two basic types: @ref softfloat and @ref softdouble. - These types are binary compatible with float and double types respectively - and support conversions to/from them. - Other types from original SoftFloat library like fp16 or fp128 were thrown away - as well as quiet/signaling NaN support, on-the-fly rounding mode switch - and exception flags (though exceptions can be implemented in the future). - - ### Operations - - Both types support the following: - - Construction from signed and unsigned 32-bit and 64 integers, - float/double or raw binary representation - - Conversions between each other, to float or double and to int - using @ref cvRound, @ref cvTrunc, @ref cvFloor, @ref cvCeil or a bunch of - saturate_cast functions - - Add, subtract, multiply, divide, remainder, square root, FMA with absolute precision - - Comparison operations - - Explicit sign, exponent and significand manipulation through get/set methods, - number state indicators (isInf, isNan, isSubnormal) - - Type-specific constants like eps, minimum/maximum value, best pi approximation, etc. - - min(), max(), abs(), exp(), log() and pow() functions - -*/ -//! @{ - -struct softfloat; -struct softdouble; - -struct CV_EXPORTS softfloat -{ -public: - /** @brief Default constructor */ - softfloat() { v = 0; } - /** @brief Copy constructor */ - softfloat( const softfloat& c) { v = c.v; } - /** @brief Assign constructor */ - softfloat& operator=( const softfloat& c ) - { - if(&c != this) v = c.v; - return *this; - } - /** @brief Construct from raw - - Builds new value from raw binary representation - */ - static const softfloat fromRaw( const uint32_t a ) { softfloat x; x.v = a; return x; } - - /** @brief Construct from integer */ - explicit softfloat( const uint32_t ); - explicit softfloat( const uint64_t ); - explicit softfloat( const int32_t ); - explicit softfloat( const int64_t ); - -#ifdef CV_INT32_T_IS_LONG_INT - // for platforms with int32_t = long int - explicit softfloat( const int a ) { *this = softfloat(static_cast(a)); } -#endif - - /** @brief Construct from float */ - explicit softfloat( const float a ) { Cv32suf s; s.f = a; v = s.u; } - - /** @brief Type casts */ - operator softdouble() const; - operator float() const { Cv32suf s; s.u = v; return s.f; } - - /** @brief Basic arithmetics */ - softfloat operator + (const softfloat&) const; - softfloat operator - (const softfloat&) const; - softfloat operator * (const softfloat&) const; - softfloat operator / (const softfloat&) const; - softfloat operator - () const { softfloat x; x.v = v ^ (1U << 31); return x; } - - /** @brief Remainder operator - - A quote from original SoftFloat manual: - - > The IEEE Standard remainder operation computes the value - > a - n * b, where n is the integer closest to a / b. - > If a / b is exactly halfway between two integers, n is the even integer - > closest to a / b. The IEEE Standard’s remainder operation is always exact and so requires no rounding. - > Depending on the relative magnitudes of the operands, the remainder functions - > can take considerably longer to execute than the other SoftFloat functions. - > This is an inherent characteristic of the remainder operation itself and is not a flaw - > in the SoftFloat implementation. - */ - softfloat operator % (const softfloat&) const; - - softfloat& operator += (const softfloat& a) { *this = *this + a; return *this; } - softfloat& operator -= (const softfloat& a) { *this = *this - a; return *this; } - softfloat& operator *= (const softfloat& a) { *this = *this * a; return *this; } - softfloat& operator /= (const softfloat& a) { *this = *this / a; return *this; } - softfloat& operator %= (const softfloat& a) { *this = *this % a; return *this; } - - /** @brief Comparison operations - - - Any operation with NaN produces false - + The only exception is when x is NaN: x != y for any y. - - Positive and negative zeros are equal - */ - bool operator == ( const softfloat& ) const; - bool operator != ( const softfloat& ) const; - bool operator > ( const softfloat& ) const; - bool operator >= ( const softfloat& ) const; - bool operator < ( const softfloat& ) const; - bool operator <= ( const softfloat& ) const; - - /** @brief NaN state indicator */ - inline bool isNaN() const { return (v & 0x7fffffff) > 0x7f800000; } - /** @brief Inf state indicator */ - inline bool isInf() const { return (v & 0x7fffffff) == 0x7f800000; } - /** @brief Subnormal number indicator */ - inline bool isSubnormal() const { return ((v >> 23) & 0xFF) == 0; } - - /** @brief Get sign bit */ - inline bool getSign() const { return (v >> 31) != 0; } - /** @brief Construct a copy with new sign bit */ - inline softfloat setSign(bool sign) const { softfloat x; x.v = (v & ((1U << 31) - 1)) | ((uint32_t)sign << 31); return x; } - /** @brief Get 0-based exponent */ - inline int getExp() const { return ((v >> 23) & 0xFF) - 127; } - /** @brief Construct a copy with new 0-based exponent */ - inline softfloat setExp(int e) const { softfloat x; x.v = (v & 0x807fffff) | (((e + 127) & 0xFF) << 23 ); return x; } - - /** @brief Get a fraction part - - Returns a number 1 <= x < 2 with the same significand - */ - inline softfloat getFrac() const - { - uint_fast32_t vv = (v & 0x007fffff) | (127 << 23); - return softfloat::fromRaw(vv); - } - /** @brief Construct a copy with provided significand - - Constructs a copy of a number with significand taken from parameter - */ - inline softfloat setFrac(const softfloat& s) const - { - softfloat x; - x.v = (v & 0xff800000) | (s.v & 0x007fffff); - return x; - } - - /** @brief Zero constant */ - static softfloat zero() { return softfloat::fromRaw( 0 ); } - /** @brief Positive infinity constant */ - static softfloat inf() { return softfloat::fromRaw( 0xFF << 23 ); } - /** @brief Default NaN constant */ - static softfloat nan() { return softfloat::fromRaw( 0x7fffffff ); } - /** @brief One constant */ - static softfloat one() { return softfloat::fromRaw( 127 << 23 ); } - /** @brief Smallest normalized value */ - static softfloat min() { return softfloat::fromRaw( 0x01 << 23 ); } - /** @brief Difference between 1 and next representable value */ - static softfloat eps() { return softfloat::fromRaw( (127 - 23) << 23 ); } - /** @brief Biggest finite value */ - static softfloat max() { return softfloat::fromRaw( (0xFF << 23) - 1 ); } - /** @brief Correct pi approximation */ - static softfloat pi() { return softfloat::fromRaw( 0x40490fdb ); } - - uint32_t v; -}; - -/*---------------------------------------------------------------------------- -*----------------------------------------------------------------------------*/ - -struct CV_EXPORTS softdouble -{ -public: - /** @brief Default constructor */ - softdouble() : v(0) { } - /** @brief Copy constructor */ - softdouble( const softdouble& c) { v = c.v; } - /** @brief Assign constructor */ - softdouble& operator=( const softdouble& c ) - { - if(&c != this) v = c.v; - return *this; - } - /** @brief Construct from raw - - Builds new value from raw binary representation - */ - static softdouble fromRaw( const uint64_t a ) { softdouble x; x.v = a; return x; } - - /** @brief Construct from integer */ - explicit softdouble( const uint32_t ); - explicit softdouble( const uint64_t ); - explicit softdouble( const int32_t ); - explicit softdouble( const int64_t ); - -#ifdef CV_INT32_T_IS_LONG_INT - // for platforms with int32_t = long int - explicit softdouble( const int a ) { *this = softdouble(static_cast(a)); } -#endif - - /** @brief Construct from double */ - explicit softdouble( const double a ) { Cv64suf s; s.f = a; v = s.u; } - - /** @brief Type casts */ - operator softfloat() const; - operator double() const { Cv64suf s; s.u = v; return s.f; } - - /** @brief Basic arithmetics */ - softdouble operator + (const softdouble&) const; - softdouble operator - (const softdouble&) const; - softdouble operator * (const softdouble&) const; - softdouble operator / (const softdouble&) const; - softdouble operator - () const { softdouble x; x.v = v ^ (1ULL << 63); return x; } - - /** @brief Remainder operator - - A quote from original SoftFloat manual: - - > The IEEE Standard remainder operation computes the value - > a - n * b, where n is the integer closest to a / b. - > If a / b is exactly halfway between two integers, n is the even integer - > closest to a / b. The IEEE Standard’s remainder operation is always exact and so requires no rounding. - > Depending on the relative magnitudes of the operands, the remainder functions - > can take considerably longer to execute than the other SoftFloat functions. - > This is an inherent characteristic of the remainder operation itself and is not a flaw - > in the SoftFloat implementation. - */ - softdouble operator % (const softdouble&) const; - - softdouble& operator += (const softdouble& a) { *this = *this + a; return *this; } - softdouble& operator -= (const softdouble& a) { *this = *this - a; return *this; } - softdouble& operator *= (const softdouble& a) { *this = *this * a; return *this; } - softdouble& operator /= (const softdouble& a) { *this = *this / a; return *this; } - softdouble& operator %= (const softdouble& a) { *this = *this % a; return *this; } - - /** @brief Comparison operations - - - Any operation with NaN produces false - + The only exception is when x is NaN: x != y for any y. - - Positive and negative zeros are equal - */ - bool operator == ( const softdouble& ) const; - bool operator != ( const softdouble& ) const; - bool operator > ( const softdouble& ) const; - bool operator >= ( const softdouble& ) const; - bool operator < ( const softdouble& ) const; - bool operator <= ( const softdouble& ) const; - - /** @brief NaN state indicator */ - inline bool isNaN() const { return (v & 0x7fffffffffffffff) > 0x7ff0000000000000; } - /** @brief Inf state indicator */ - inline bool isInf() const { return (v & 0x7fffffffffffffff) == 0x7ff0000000000000; } - /** @brief Subnormal number indicator */ - inline bool isSubnormal() const { return ((v >> 52) & 0x7FF) == 0; } - - /** @brief Get sign bit */ - inline bool getSign() const { return (v >> 63) != 0; } - /** @brief Construct a copy with new sign bit */ - softdouble setSign(bool sign) const { softdouble x; x.v = (v & ((1ULL << 63) - 1)) | ((uint_fast64_t)(sign) << 63); return x; } - /** @brief Get 0-based exponent */ - inline int getExp() const { return ((v >> 52) & 0x7FF) - 1023; } - /** @brief Construct a copy with new 0-based exponent */ - inline softdouble setExp(int e) const - { - softdouble x; - x.v = (v & 0x800FFFFFFFFFFFFF) | ((uint_fast64_t)((e + 1023) & 0x7FF) << 52); - return x; - } - - /** @brief Get a fraction part - - Returns a number 1 <= x < 2 with the same significand - */ - inline softdouble getFrac() const - { - uint_fast64_t vv = (v & 0x000FFFFFFFFFFFFF) | ((uint_fast64_t)(1023) << 52); - return softdouble::fromRaw(vv); - } - /** @brief Construct a copy with provided significand - - Constructs a copy of a number with significand taken from parameter - */ - inline softdouble setFrac(const softdouble& s) const - { - softdouble x; - x.v = (v & 0xFFF0000000000000) | (s.v & 0x000FFFFFFFFFFFFF); - return x; - } - - /** @brief Zero constant */ - static softdouble zero() { return softdouble::fromRaw( 0 ); } - /** @brief Positive infinity constant */ - static softdouble inf() { return softdouble::fromRaw( (uint_fast64_t)(0x7FF) << 52 ); } - /** @brief Default NaN constant */ - static softdouble nan() { return softdouble::fromRaw( CV_BIG_INT(0x7FFFFFFFFFFFFFFF) ); } - /** @brief One constant */ - static softdouble one() { return softdouble::fromRaw( (uint_fast64_t)( 1023) << 52 ); } - /** @brief Smallest normalized value */ - static softdouble min() { return softdouble::fromRaw( (uint_fast64_t)( 0x01) << 52 ); } - /** @brief Difference between 1 and next representable value */ - static softdouble eps() { return softdouble::fromRaw( (uint_fast64_t)( 1023 - 52 ) << 52 ); } - /** @brief Biggest finite value */ - static softdouble max() { return softdouble::fromRaw( ((uint_fast64_t)(0x7FF) << 52) - 1 ); } - /** @brief Correct pi approximation */ - static softdouble pi() { return softdouble::fromRaw( CV_BIG_INT(0x400921FB54442D18) ); } - - uint64_t v; -}; - -/*---------------------------------------------------------------------------- -*----------------------------------------------------------------------------*/ - -/** @brief Fused Multiplication and Addition - -Computes (a*b)+c with single rounding -*/ -CV_EXPORTS softfloat mulAdd( const softfloat& a, const softfloat& b, const softfloat & c); -CV_EXPORTS softdouble mulAdd( const softdouble& a, const softdouble& b, const softdouble& c); - -/** @brief Square root */ -CV_EXPORTS softfloat sqrt( const softfloat& a ); -CV_EXPORTS softdouble sqrt( const softdouble& a ); -} - -/*---------------------------------------------------------------------------- -| Ported from OpenCV and added for usability -*----------------------------------------------------------------------------*/ - -/** @brief Truncates number to integer with minimum magnitude */ -CV_EXPORTS int cvTrunc(const cv::softfloat& a); -CV_EXPORTS int cvTrunc(const cv::softdouble& a); - -/** @brief Rounds a number to nearest even integer */ -CV_EXPORTS int cvRound(const cv::softfloat& a); -CV_EXPORTS int cvRound(const cv::softdouble& a); - -/** @brief Rounds a number to nearest even long long integer */ -CV_EXPORTS int64_t cvRound64(const cv::softdouble& a); - -/** @brief Rounds a number down to integer */ -CV_EXPORTS int cvFloor(const cv::softfloat& a); -CV_EXPORTS int cvFloor(const cv::softdouble& a); - -/** @brief Rounds number up to integer */ -CV_EXPORTS int cvCeil(const cv::softfloat& a); -CV_EXPORTS int cvCeil(const cv::softdouble& a); - -namespace cv -{ -/** @brief Saturate casts */ -template static inline _Tp saturate_cast(softfloat a) { return _Tp(a); } -template static inline _Tp saturate_cast(softdouble a) { return _Tp(a); } - -template<> inline uchar saturate_cast(softfloat a) { return (uchar)std::max(std::min(cvRound(a), (int)UCHAR_MAX), 0); } -template<> inline uchar saturate_cast(softdouble a) { return (uchar)std::max(std::min(cvRound(a), (int)UCHAR_MAX), 0); } - -template<> inline schar saturate_cast(softfloat a) { return (schar)std::min(std::max(cvRound(a), (int)SCHAR_MIN), (int)SCHAR_MAX); } -template<> inline schar saturate_cast(softdouble a) { return (schar)std::min(std::max(cvRound(a), (int)SCHAR_MIN), (int)SCHAR_MAX); } - -template<> inline ushort saturate_cast(softfloat a) { return (ushort)std::max(std::min(cvRound(a), (int)USHRT_MAX), 0); } -template<> inline ushort saturate_cast(softdouble a) { return (ushort)std::max(std::min(cvRound(a), (int)USHRT_MAX), 0); } - -template<> inline short saturate_cast(softfloat a) { return (short)std::min(std::max(cvRound(a), (int)SHRT_MIN), (int)SHRT_MAX); } -template<> inline short saturate_cast(softdouble a) { return (short)std::min(std::max(cvRound(a), (int)SHRT_MIN), (int)SHRT_MAX); } - -template<> inline int saturate_cast(softfloat a) { return cvRound(a); } -template<> inline int saturate_cast(softdouble a) { return cvRound(a); } - -template<> inline int64_t saturate_cast(softfloat a) { return cvRound(a); } -template<> inline int64_t saturate_cast(softdouble a) { return cvRound64(a); } - -/** @brief Saturate cast to unsigned integer and unsigned long long integer -We intentionally do not clip negative numbers, to make -1 become 0xffffffff etc. -*/ -template<> inline unsigned saturate_cast(softfloat a) { return cvRound(a); } -template<> inline unsigned saturate_cast(softdouble a) { return cvRound(a); } - -template<> inline uint64_t saturate_cast(softfloat a) { return cvRound(a); } -template<> inline uint64_t saturate_cast(softdouble a) { return cvRound64(a); } - -/** @brief Min and Max functions */ -inline softfloat min(const softfloat& a, const softfloat& b) { return (a > b) ? b : a; } -inline softdouble min(const softdouble& a, const softdouble& b) { return (a > b) ? b : a; } - -inline softfloat max(const softfloat& a, const softfloat& b) { return (a > b) ? a : b; } -inline softdouble max(const softdouble& a, const softdouble& b) { return (a > b) ? a : b; } - -/** @brief Absolute value */ -inline softfloat abs( softfloat a) { softfloat x; x.v = a.v & ((1U << 31) - 1); return x; } -inline softdouble abs( softdouble a) { softdouble x; x.v = a.v & ((1ULL << 63) - 1); return x; } - -/** @brief Exponent - -Special cases: -- exp(NaN) is NaN -- exp(-Inf) == 0 -- exp(+Inf) == +Inf -*/ -CV_EXPORTS softfloat exp( const softfloat& a); -CV_EXPORTS softdouble exp( const softdouble& a); - -/** @brief Natural logarithm - -Special cases: -- log(NaN), log(x < 0) are NaN -- log(0) == -Inf -*/ -CV_EXPORTS softfloat log( const softfloat& a ); -CV_EXPORTS softdouble log( const softdouble& a ); - -/** @brief Raising to the power - -Special cases: -- x**NaN is NaN for any x -- ( |x| == 1 )**Inf is NaN -- ( |x| > 1 )**+Inf or ( |x| < 1 )**-Inf is +Inf -- ( |x| > 1 )**-Inf or ( |x| < 1 )**+Inf is 0 -- x ** 0 == 1 for any x -- x ** 1 == 1 for any x -- NaN ** y is NaN for any other y -- Inf**(y < 0) == 0 -- Inf ** y is +Inf for any other y -- (x < 0)**y is NaN for any other y if x can't be correctly rounded to integer -- 0 ** 0 == 1 -- 0 ** (y < 0) is +Inf -- 0 ** (y > 0) is 0 -*/ -CV_EXPORTS softfloat pow( const softfloat& a, const softfloat& b); -CV_EXPORTS softdouble pow( const softdouble& a, const softdouble& b); - -/** @brief Cube root - -Special cases: -- cbrt(NaN) is NaN -- cbrt(+/-Inf) is +/-Inf -*/ -CV_EXPORTS softfloat cbrt( const softfloat& a ); - -/** @brief Sine - -Special cases: -- sin(Inf) or sin(NaN) is NaN -- sin(x) == x when sin(x) is close to zero -*/ -CV_EXPORTS softdouble sin( const softdouble& a ); - -/** @brief Cosine - * -Special cases: -- cos(Inf) or cos(NaN) is NaN -- cos(x) == +/- 1 when cos(x) is close to +/- 1 -*/ -CV_EXPORTS softdouble cos( const softdouble& a ); - -//! @} core_utils_softfloat - -} // cv:: - -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +// This file is based on files from package issued with the following license: + +/*============================================================================ + +This C header file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3c, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +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. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. + +=============================================================================*/ + +#pragma once +#ifndef softfloat_h +#define softfloat_h 1 + +#include "cvdef.h" + +namespace cv +{ + +/** @addtogroup core_utils_softfloat + + [SoftFloat](http://www.jhauser.us/arithmetic/SoftFloat.html) is a software implementation + of floating-point calculations according to IEEE 754 standard. + All calculations are done in integers, that's why they are machine-independent and bit-exact. + This library can be useful in accuracy-critical parts like look-up tables generation, tests, etc. + OpenCV contains a subset of SoftFloat partially rewritten to C++. + + ### Types + + There are two basic types: @ref softfloat and @ref softdouble. + These types are binary compatible with float and double types respectively + and support conversions to/from them. + Other types from original SoftFloat library like fp16 or fp128 were thrown away + as well as quiet/signaling NaN support, on-the-fly rounding mode switch + and exception flags (though exceptions can be implemented in the future). + + ### Operations + + Both types support the following: + - Construction from signed and unsigned 32-bit and 64 integers, + float/double or raw binary representation + - Conversions between each other, to float or double and to int + using @ref cvRound, @ref cvTrunc, @ref cvFloor, @ref cvCeil or a bunch of + saturate_cast functions + - Add, subtract, multiply, divide, remainder, square root, FMA with absolute precision + - Comparison operations + - Explicit sign, exponent and significand manipulation through get/set methods, + number state indicators (isInf, isNan, isSubnormal) + - Type-specific constants like eps, minimum/maximum value, best pi approximation, etc. + - min(), max(), abs(), exp(), log() and pow() functions + +*/ +//! @{ + +struct softfloat; +struct softdouble; + +struct CV_EXPORTS softfloat +{ +public: + /** @brief Default constructor */ + softfloat() { v = 0; } + /** @brief Copy constructor */ + softfloat( const softfloat& c) { v = c.v; } + /** @brief Assign constructor */ + softfloat& operator=( const softfloat& c ) + { + if(&c != this) v = c.v; + return *this; + } + /** @brief Construct from raw + + Builds new value from raw binary representation + */ + static const softfloat fromRaw( const uint32_t a ) { softfloat x; x.v = a; return x; } + + /** @brief Construct from integer */ + explicit softfloat( const uint32_t ); + explicit softfloat( const uint64_t ); + explicit softfloat( const int32_t ); + explicit softfloat( const int64_t ); + +#ifdef CV_INT32_T_IS_LONG_INT + // for platforms with int32_t = long int + explicit softfloat( const int a ) { *this = softfloat(static_cast(a)); } +#endif + + /** @brief Construct from float */ + explicit softfloat( const float a ) { Cv32suf s; s.f = a; v = s.u; } + + /** @brief Type casts */ + operator softdouble() const; + operator float() const { Cv32suf s; s.u = v; return s.f; } + + /** @brief Basic arithmetics */ + softfloat operator + (const softfloat&) const; + softfloat operator - (const softfloat&) const; + softfloat operator * (const softfloat&) const; + softfloat operator / (const softfloat&) const; + softfloat operator - () const { softfloat x; x.v = v ^ (1U << 31); return x; } + + /** @brief Remainder operator + + A quote from original SoftFloat manual: + + > The IEEE Standard remainder operation computes the value + > a - n * b, where n is the integer closest to a / b. + > If a / b is exactly halfway between two integers, n is the even integer + > closest to a / b. The IEEE Standard’s remainder operation is always exact and so requires no rounding. + > Depending on the relative magnitudes of the operands, the remainder functions + > can take considerably longer to execute than the other SoftFloat functions. + > This is an inherent characteristic of the remainder operation itself and is not a flaw + > in the SoftFloat implementation. + */ + softfloat operator % (const softfloat&) const; + + softfloat& operator += (const softfloat& a) { *this = *this + a; return *this; } + softfloat& operator -= (const softfloat& a) { *this = *this - a; return *this; } + softfloat& operator *= (const softfloat& a) { *this = *this * a; return *this; } + softfloat& operator /= (const softfloat& a) { *this = *this / a; return *this; } + softfloat& operator %= (const softfloat& a) { *this = *this % a; return *this; } + + /** @brief Comparison operations + + - Any operation with NaN produces false + + The only exception is when x is NaN: x != y for any y. + - Positive and negative zeros are equal + */ + bool operator == ( const softfloat& ) const; + bool operator != ( const softfloat& ) const; + bool operator > ( const softfloat& ) const; + bool operator >= ( const softfloat& ) const; + bool operator < ( const softfloat& ) const; + bool operator <= ( const softfloat& ) const; + + /** @brief NaN state indicator */ + inline bool isNaN() const { return (v & 0x7fffffff) > 0x7f800000; } + /** @brief Inf state indicator */ + inline bool isInf() const { return (v & 0x7fffffff) == 0x7f800000; } + /** @brief Subnormal number indicator */ + inline bool isSubnormal() const { return ((v >> 23) & 0xFF) == 0; } + + /** @brief Get sign bit */ + inline bool getSign() const { return (v >> 31) != 0; } + /** @brief Construct a copy with new sign bit */ + inline softfloat setSign(bool sign) const { softfloat x; x.v = (v & ((1U << 31) - 1)) | ((uint32_t)sign << 31); return x; } + /** @brief Get 0-based exponent */ + inline int getExp() const { return ((v >> 23) & 0xFF) - 127; } + /** @brief Construct a copy with new 0-based exponent */ + inline softfloat setExp(int e) const { softfloat x; x.v = (v & 0x807fffff) | (((e + 127) & 0xFF) << 23 ); return x; } + + /** @brief Get a fraction part + + Returns a number 1 <= x < 2 with the same significand + */ + inline softfloat getFrac() const + { + uint_fast32_t vv = (v & 0x007fffff) | (127 << 23); + return softfloat::fromRaw(vv); + } + /** @brief Construct a copy with provided significand + + Constructs a copy of a number with significand taken from parameter + */ + inline softfloat setFrac(const softfloat& s) const + { + softfloat x; + x.v = (v & 0xff800000) | (s.v & 0x007fffff); + return x; + } + + /** @brief Zero constant */ + static softfloat zero() { return softfloat::fromRaw( 0 ); } + /** @brief Positive infinity constant */ + static softfloat inf() { return softfloat::fromRaw( 0xFF << 23 ); } + /** @brief Default NaN constant */ + static softfloat nan() { return softfloat::fromRaw( 0x7fffffff ); } + /** @brief One constant */ + static softfloat one() { return softfloat::fromRaw( 127 << 23 ); } + /** @brief Smallest normalized value */ + static softfloat min() { return softfloat::fromRaw( 0x01 << 23 ); } + /** @brief Difference between 1 and next representable value */ + static softfloat eps() { return softfloat::fromRaw( (127 - 23) << 23 ); } + /** @brief Biggest finite value */ + static softfloat max() { return softfloat::fromRaw( (0xFF << 23) - 1 ); } + /** @brief Correct pi approximation */ + static softfloat pi() { return softfloat::fromRaw( 0x40490fdb ); } + + uint32_t v; +}; + +/*---------------------------------------------------------------------------- +*----------------------------------------------------------------------------*/ + +struct CV_EXPORTS softdouble +{ +public: + /** @brief Default constructor */ + softdouble() : v(0) { } + /** @brief Copy constructor */ + softdouble( const softdouble& c) { v = c.v; } + /** @brief Assign constructor */ + softdouble& operator=( const softdouble& c ) + { + if(&c != this) v = c.v; + return *this; + } + /** @brief Construct from raw + + Builds new value from raw binary representation + */ + static softdouble fromRaw( const uint64_t a ) { softdouble x; x.v = a; return x; } + + /** @brief Construct from integer */ + explicit softdouble( const uint32_t ); + explicit softdouble( const uint64_t ); + explicit softdouble( const int32_t ); + explicit softdouble( const int64_t ); + +#ifdef CV_INT32_T_IS_LONG_INT + // for platforms with int32_t = long int + explicit softdouble( const int a ) { *this = softdouble(static_cast(a)); } +#endif + + /** @brief Construct from double */ + explicit softdouble( const double a ) { Cv64suf s; s.f = a; v = s.u; } + + /** @brief Type casts */ + operator softfloat() const; + operator double() const { Cv64suf s; s.u = v; return s.f; } + + /** @brief Basic arithmetics */ + softdouble operator + (const softdouble&) const; + softdouble operator - (const softdouble&) const; + softdouble operator * (const softdouble&) const; + softdouble operator / (const softdouble&) const; + softdouble operator - () const { softdouble x; x.v = v ^ (1ULL << 63); return x; } + + /** @brief Remainder operator + + A quote from original SoftFloat manual: + + > The IEEE Standard remainder operation computes the value + > a - n * b, where n is the integer closest to a / b. + > If a / b is exactly halfway between two integers, n is the even integer + > closest to a / b. The IEEE Standard’s remainder operation is always exact and so requires no rounding. + > Depending on the relative magnitudes of the operands, the remainder functions + > can take considerably longer to execute than the other SoftFloat functions. + > This is an inherent characteristic of the remainder operation itself and is not a flaw + > in the SoftFloat implementation. + */ + softdouble operator % (const softdouble&) const; + + softdouble& operator += (const softdouble& a) { *this = *this + a; return *this; } + softdouble& operator -= (const softdouble& a) { *this = *this - a; return *this; } + softdouble& operator *= (const softdouble& a) { *this = *this * a; return *this; } + softdouble& operator /= (const softdouble& a) { *this = *this / a; return *this; } + softdouble& operator %= (const softdouble& a) { *this = *this % a; return *this; } + + /** @brief Comparison operations + + - Any operation with NaN produces false + + The only exception is when x is NaN: x != y for any y. + - Positive and negative zeros are equal + */ + bool operator == ( const softdouble& ) const; + bool operator != ( const softdouble& ) const; + bool operator > ( const softdouble& ) const; + bool operator >= ( const softdouble& ) const; + bool operator < ( const softdouble& ) const; + bool operator <= ( const softdouble& ) const; + + /** @brief NaN state indicator */ + inline bool isNaN() const { return (v & 0x7fffffffffffffff) > 0x7ff0000000000000; } + /** @brief Inf state indicator */ + inline bool isInf() const { return (v & 0x7fffffffffffffff) == 0x7ff0000000000000; } + /** @brief Subnormal number indicator */ + inline bool isSubnormal() const { return ((v >> 52) & 0x7FF) == 0; } + + /** @brief Get sign bit */ + inline bool getSign() const { return (v >> 63) != 0; } + /** @brief Construct a copy with new sign bit */ + softdouble setSign(bool sign) const { softdouble x; x.v = (v & ((1ULL << 63) - 1)) | ((uint_fast64_t)(sign) << 63); return x; } + /** @brief Get 0-based exponent */ + inline int getExp() const { return ((v >> 52) & 0x7FF) - 1023; } + /** @brief Construct a copy with new 0-based exponent */ + inline softdouble setExp(int e) const + { + softdouble x; + x.v = (v & 0x800FFFFFFFFFFFFF) | ((uint_fast64_t)((e + 1023) & 0x7FF) << 52); + return x; + } + + /** @brief Get a fraction part + + Returns a number 1 <= x < 2 with the same significand + */ + inline softdouble getFrac() const + { + uint_fast64_t vv = (v & 0x000FFFFFFFFFFFFF) | ((uint_fast64_t)(1023) << 52); + return softdouble::fromRaw(vv); + } + /** @brief Construct a copy with provided significand + + Constructs a copy of a number with significand taken from parameter + */ + inline softdouble setFrac(const softdouble& s) const + { + softdouble x; + x.v = (v & 0xFFF0000000000000) | (s.v & 0x000FFFFFFFFFFFFF); + return x; + } + + /** @brief Zero constant */ + static softdouble zero() { return softdouble::fromRaw( 0 ); } + /** @brief Positive infinity constant */ + static softdouble inf() { return softdouble::fromRaw( (uint_fast64_t)(0x7FF) << 52 ); } + /** @brief Default NaN constant */ + static softdouble nan() { return softdouble::fromRaw( CV_BIG_INT(0x7FFFFFFFFFFFFFFF) ); } + /** @brief One constant */ + static softdouble one() { return softdouble::fromRaw( (uint_fast64_t)( 1023) << 52 ); } + /** @brief Smallest normalized value */ + static softdouble min() { return softdouble::fromRaw( (uint_fast64_t)( 0x01) << 52 ); } + /** @brief Difference between 1 and next representable value */ + static softdouble eps() { return softdouble::fromRaw( (uint_fast64_t)( 1023 - 52 ) << 52 ); } + /** @brief Biggest finite value */ + static softdouble max() { return softdouble::fromRaw( ((uint_fast64_t)(0x7FF) << 52) - 1 ); } + /** @brief Correct pi approximation */ + static softdouble pi() { return softdouble::fromRaw( CV_BIG_INT(0x400921FB54442D18) ); } + + uint64_t v; +}; + +/*---------------------------------------------------------------------------- +*----------------------------------------------------------------------------*/ + +/** @brief Fused Multiplication and Addition + +Computes (a*b)+c with single rounding +*/ +CV_EXPORTS softfloat mulAdd( const softfloat& a, const softfloat& b, const softfloat & c); +CV_EXPORTS softdouble mulAdd( const softdouble& a, const softdouble& b, const softdouble& c); + +/** @brief Square root */ +CV_EXPORTS softfloat sqrt( const softfloat& a ); +CV_EXPORTS softdouble sqrt( const softdouble& a ); +} + +/*---------------------------------------------------------------------------- +| Ported from OpenCV and added for usability +*----------------------------------------------------------------------------*/ + +/** @brief Truncates number to integer with minimum magnitude */ +CV_EXPORTS int cvTrunc(const cv::softfloat& a); +CV_EXPORTS int cvTrunc(const cv::softdouble& a); + +/** @brief Rounds a number to nearest even integer */ +CV_EXPORTS int cvRound(const cv::softfloat& a); +CV_EXPORTS int cvRound(const cv::softdouble& a); + +/** @brief Rounds a number to nearest even long long integer */ +CV_EXPORTS int64_t cvRound64(const cv::softdouble& a); + +/** @brief Rounds a number down to integer */ +CV_EXPORTS int cvFloor(const cv::softfloat& a); +CV_EXPORTS int cvFloor(const cv::softdouble& a); + +/** @brief Rounds number up to integer */ +CV_EXPORTS int cvCeil(const cv::softfloat& a); +CV_EXPORTS int cvCeil(const cv::softdouble& a); + +namespace cv +{ +/** @brief Saturate casts */ +template static inline _Tp saturate_cast(softfloat a) { return _Tp(a); } +template static inline _Tp saturate_cast(softdouble a) { return _Tp(a); } + +template<> inline uchar saturate_cast(softfloat a) { return (uchar)std::max(std::min(cvRound(a), (int)UCHAR_MAX), 0); } +template<> inline uchar saturate_cast(softdouble a) { return (uchar)std::max(std::min(cvRound(a), (int)UCHAR_MAX), 0); } + +template<> inline schar saturate_cast(softfloat a) { return (schar)std::min(std::max(cvRound(a), (int)SCHAR_MIN), (int)SCHAR_MAX); } +template<> inline schar saturate_cast(softdouble a) { return (schar)std::min(std::max(cvRound(a), (int)SCHAR_MIN), (int)SCHAR_MAX); } + +template<> inline ushort saturate_cast(softfloat a) { return (ushort)std::max(std::min(cvRound(a), (int)USHRT_MAX), 0); } +template<> inline ushort saturate_cast(softdouble a) { return (ushort)std::max(std::min(cvRound(a), (int)USHRT_MAX), 0); } + +template<> inline short saturate_cast(softfloat a) { return (short)std::min(std::max(cvRound(a), (int)SHRT_MIN), (int)SHRT_MAX); } +template<> inline short saturate_cast(softdouble a) { return (short)std::min(std::max(cvRound(a), (int)SHRT_MIN), (int)SHRT_MAX); } + +template<> inline int saturate_cast(softfloat a) { return cvRound(a); } +template<> inline int saturate_cast(softdouble a) { return cvRound(a); } + +template<> inline int64_t saturate_cast(softfloat a) { return cvRound(a); } +template<> inline int64_t saturate_cast(softdouble a) { return cvRound64(a); } + +/** @brief Saturate cast to unsigned integer and unsigned long long integer +We intentionally do not clip negative numbers, to make -1 become 0xffffffff etc. +*/ +template<> inline unsigned saturate_cast(softfloat a) { return cvRound(a); } +template<> inline unsigned saturate_cast(softdouble a) { return cvRound(a); } + +template<> inline uint64_t saturate_cast(softfloat a) { return cvRound(a); } +template<> inline uint64_t saturate_cast(softdouble a) { return cvRound64(a); } + +/** @brief Min and Max functions */ +inline softfloat min(const softfloat& a, const softfloat& b) { return (a > b) ? b : a; } +inline softdouble min(const softdouble& a, const softdouble& b) { return (a > b) ? b : a; } + +inline softfloat max(const softfloat& a, const softfloat& b) { return (a > b) ? a : b; } +inline softdouble max(const softdouble& a, const softdouble& b) { return (a > b) ? a : b; } + +/** @brief Absolute value */ +inline softfloat abs( softfloat a) { softfloat x; x.v = a.v & ((1U << 31) - 1); return x; } +inline softdouble abs( softdouble a) { softdouble x; x.v = a.v & ((1ULL << 63) - 1); return x; } + +/** @brief Exponent + +Special cases: +- exp(NaN) is NaN +- exp(-Inf) == 0 +- exp(+Inf) == +Inf +*/ +CV_EXPORTS softfloat exp( const softfloat& a); +CV_EXPORTS softdouble exp( const softdouble& a); + +/** @brief Natural logarithm + +Special cases: +- log(NaN), log(x < 0) are NaN +- log(0) == -Inf +*/ +CV_EXPORTS softfloat log( const softfloat& a ); +CV_EXPORTS softdouble log( const softdouble& a ); + +/** @brief Raising to the power + +Special cases: +- x**NaN is NaN for any x +- ( |x| == 1 )**Inf is NaN +- ( |x| > 1 )**+Inf or ( |x| < 1 )**-Inf is +Inf +- ( |x| > 1 )**-Inf or ( |x| < 1 )**+Inf is 0 +- x ** 0 == 1 for any x +- x ** 1 == 1 for any x +- NaN ** y is NaN for any other y +- Inf**(y < 0) == 0 +- Inf ** y is +Inf for any other y +- (x < 0)**y is NaN for any other y if x can't be correctly rounded to integer +- 0 ** 0 == 1 +- 0 ** (y < 0) is +Inf +- 0 ** (y > 0) is 0 +*/ +CV_EXPORTS softfloat pow( const softfloat& a, const softfloat& b); +CV_EXPORTS softdouble pow( const softdouble& a, const softdouble& b); + +/** @brief Cube root + +Special cases: +- cbrt(NaN) is NaN +- cbrt(+/-Inf) is +/-Inf +*/ +CV_EXPORTS softfloat cbrt( const softfloat& a ); + +/** @brief Sine + +Special cases: +- sin(Inf) or sin(NaN) is NaN +- sin(x) == x when sin(x) is close to zero +*/ +CV_EXPORTS softdouble sin( const softdouble& a ); + +/** @brief Cosine + * +Special cases: +- cos(Inf) or cos(NaN) is NaN +- cos(x) == +/- 1 when cos(x) is close to +/- 1 +*/ +CV_EXPORTS softdouble cos( const softdouble& a ); + +//! @} core_utils_softfloat + +} // cv:: + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/sse_utils.hpp b/3rdParty/opencv-4.11.0/opencv2/core/sse_utils.hpp index 0906583ea4..c0892e939f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/sse_utils.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/sse_utils.hpp @@ -1,652 +1,652 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CORE_SSE_UTILS_HPP -#define OPENCV_CORE_SSE_UTILS_HPP - -#ifndef __cplusplus -# error sse_utils.hpp header must be compiled as C++ -#endif - -#include "opencv2/core/cvdef.h" - -//! @addtogroup core_utils_sse -//! @{ - -#if CV_SSE2 - -inline void _mm_deinterleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1) -{ - __m128i layer1_chunk0 = _mm_unpacklo_epi8(v_r0, v_g0); - __m128i layer1_chunk1 = _mm_unpackhi_epi8(v_r0, v_g0); - __m128i layer1_chunk2 = _mm_unpacklo_epi8(v_r1, v_g1); - __m128i layer1_chunk3 = _mm_unpackhi_epi8(v_r1, v_g1); - - __m128i layer2_chunk0 = _mm_unpacklo_epi8(layer1_chunk0, layer1_chunk2); - __m128i layer2_chunk1 = _mm_unpackhi_epi8(layer1_chunk0, layer1_chunk2); - __m128i layer2_chunk2 = _mm_unpacklo_epi8(layer1_chunk1, layer1_chunk3); - __m128i layer2_chunk3 = _mm_unpackhi_epi8(layer1_chunk1, layer1_chunk3); - - __m128i layer3_chunk0 = _mm_unpacklo_epi8(layer2_chunk0, layer2_chunk2); - __m128i layer3_chunk1 = _mm_unpackhi_epi8(layer2_chunk0, layer2_chunk2); - __m128i layer3_chunk2 = _mm_unpacklo_epi8(layer2_chunk1, layer2_chunk3); - __m128i layer3_chunk3 = _mm_unpackhi_epi8(layer2_chunk1, layer2_chunk3); - - __m128i layer4_chunk0 = _mm_unpacklo_epi8(layer3_chunk0, layer3_chunk2); - __m128i layer4_chunk1 = _mm_unpackhi_epi8(layer3_chunk0, layer3_chunk2); - __m128i layer4_chunk2 = _mm_unpacklo_epi8(layer3_chunk1, layer3_chunk3); - __m128i layer4_chunk3 = _mm_unpackhi_epi8(layer3_chunk1, layer3_chunk3); - - v_r0 = _mm_unpacklo_epi8(layer4_chunk0, layer4_chunk2); - v_r1 = _mm_unpackhi_epi8(layer4_chunk0, layer4_chunk2); - v_g0 = _mm_unpacklo_epi8(layer4_chunk1, layer4_chunk3); - v_g1 = _mm_unpackhi_epi8(layer4_chunk1, layer4_chunk3); -} - -inline void _mm_deinterleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, - __m128i & v_g1, __m128i & v_b0, __m128i & v_b1) -{ - __m128i layer1_chunk0 = _mm_unpacklo_epi8(v_r0, v_g1); - __m128i layer1_chunk1 = _mm_unpackhi_epi8(v_r0, v_g1); - __m128i layer1_chunk2 = _mm_unpacklo_epi8(v_r1, v_b0); - __m128i layer1_chunk3 = _mm_unpackhi_epi8(v_r1, v_b0); - __m128i layer1_chunk4 = _mm_unpacklo_epi8(v_g0, v_b1); - __m128i layer1_chunk5 = _mm_unpackhi_epi8(v_g0, v_b1); - - __m128i layer2_chunk0 = _mm_unpacklo_epi8(layer1_chunk0, layer1_chunk3); - __m128i layer2_chunk1 = _mm_unpackhi_epi8(layer1_chunk0, layer1_chunk3); - __m128i layer2_chunk2 = _mm_unpacklo_epi8(layer1_chunk1, layer1_chunk4); - __m128i layer2_chunk3 = _mm_unpackhi_epi8(layer1_chunk1, layer1_chunk4); - __m128i layer2_chunk4 = _mm_unpacklo_epi8(layer1_chunk2, layer1_chunk5); - __m128i layer2_chunk5 = _mm_unpackhi_epi8(layer1_chunk2, layer1_chunk5); - - __m128i layer3_chunk0 = _mm_unpacklo_epi8(layer2_chunk0, layer2_chunk3); - __m128i layer3_chunk1 = _mm_unpackhi_epi8(layer2_chunk0, layer2_chunk3); - __m128i layer3_chunk2 = _mm_unpacklo_epi8(layer2_chunk1, layer2_chunk4); - __m128i layer3_chunk3 = _mm_unpackhi_epi8(layer2_chunk1, layer2_chunk4); - __m128i layer3_chunk4 = _mm_unpacklo_epi8(layer2_chunk2, layer2_chunk5); - __m128i layer3_chunk5 = _mm_unpackhi_epi8(layer2_chunk2, layer2_chunk5); - - __m128i layer4_chunk0 = _mm_unpacklo_epi8(layer3_chunk0, layer3_chunk3); - __m128i layer4_chunk1 = _mm_unpackhi_epi8(layer3_chunk0, layer3_chunk3); - __m128i layer4_chunk2 = _mm_unpacklo_epi8(layer3_chunk1, layer3_chunk4); - __m128i layer4_chunk3 = _mm_unpackhi_epi8(layer3_chunk1, layer3_chunk4); - __m128i layer4_chunk4 = _mm_unpacklo_epi8(layer3_chunk2, layer3_chunk5); - __m128i layer4_chunk5 = _mm_unpackhi_epi8(layer3_chunk2, layer3_chunk5); - - v_r0 = _mm_unpacklo_epi8(layer4_chunk0, layer4_chunk3); - v_r1 = _mm_unpackhi_epi8(layer4_chunk0, layer4_chunk3); - v_g0 = _mm_unpacklo_epi8(layer4_chunk1, layer4_chunk4); - v_g1 = _mm_unpackhi_epi8(layer4_chunk1, layer4_chunk4); - v_b0 = _mm_unpacklo_epi8(layer4_chunk2, layer4_chunk5); - v_b1 = _mm_unpackhi_epi8(layer4_chunk2, layer4_chunk5); -} - -inline void _mm_deinterleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1, - __m128i & v_b0, __m128i & v_b1, __m128i & v_a0, __m128i & v_a1) -{ - __m128i layer1_chunk0 = _mm_unpacklo_epi8(v_r0, v_b0); - __m128i layer1_chunk1 = _mm_unpackhi_epi8(v_r0, v_b0); - __m128i layer1_chunk2 = _mm_unpacklo_epi8(v_r1, v_b1); - __m128i layer1_chunk3 = _mm_unpackhi_epi8(v_r1, v_b1); - __m128i layer1_chunk4 = _mm_unpacklo_epi8(v_g0, v_a0); - __m128i layer1_chunk5 = _mm_unpackhi_epi8(v_g0, v_a0); - __m128i layer1_chunk6 = _mm_unpacklo_epi8(v_g1, v_a1); - __m128i layer1_chunk7 = _mm_unpackhi_epi8(v_g1, v_a1); - - __m128i layer2_chunk0 = _mm_unpacklo_epi8(layer1_chunk0, layer1_chunk4); - __m128i layer2_chunk1 = _mm_unpackhi_epi8(layer1_chunk0, layer1_chunk4); - __m128i layer2_chunk2 = _mm_unpacklo_epi8(layer1_chunk1, layer1_chunk5); - __m128i layer2_chunk3 = _mm_unpackhi_epi8(layer1_chunk1, layer1_chunk5); - __m128i layer2_chunk4 = _mm_unpacklo_epi8(layer1_chunk2, layer1_chunk6); - __m128i layer2_chunk5 = _mm_unpackhi_epi8(layer1_chunk2, layer1_chunk6); - __m128i layer2_chunk6 = _mm_unpacklo_epi8(layer1_chunk3, layer1_chunk7); - __m128i layer2_chunk7 = _mm_unpackhi_epi8(layer1_chunk3, layer1_chunk7); - - __m128i layer3_chunk0 = _mm_unpacklo_epi8(layer2_chunk0, layer2_chunk4); - __m128i layer3_chunk1 = _mm_unpackhi_epi8(layer2_chunk0, layer2_chunk4); - __m128i layer3_chunk2 = _mm_unpacklo_epi8(layer2_chunk1, layer2_chunk5); - __m128i layer3_chunk3 = _mm_unpackhi_epi8(layer2_chunk1, layer2_chunk5); - __m128i layer3_chunk4 = _mm_unpacklo_epi8(layer2_chunk2, layer2_chunk6); - __m128i layer3_chunk5 = _mm_unpackhi_epi8(layer2_chunk2, layer2_chunk6); - __m128i layer3_chunk6 = _mm_unpacklo_epi8(layer2_chunk3, layer2_chunk7); - __m128i layer3_chunk7 = _mm_unpackhi_epi8(layer2_chunk3, layer2_chunk7); - - __m128i layer4_chunk0 = _mm_unpacklo_epi8(layer3_chunk0, layer3_chunk4); - __m128i layer4_chunk1 = _mm_unpackhi_epi8(layer3_chunk0, layer3_chunk4); - __m128i layer4_chunk2 = _mm_unpacklo_epi8(layer3_chunk1, layer3_chunk5); - __m128i layer4_chunk3 = _mm_unpackhi_epi8(layer3_chunk1, layer3_chunk5); - __m128i layer4_chunk4 = _mm_unpacklo_epi8(layer3_chunk2, layer3_chunk6); - __m128i layer4_chunk5 = _mm_unpackhi_epi8(layer3_chunk2, layer3_chunk6); - __m128i layer4_chunk6 = _mm_unpacklo_epi8(layer3_chunk3, layer3_chunk7); - __m128i layer4_chunk7 = _mm_unpackhi_epi8(layer3_chunk3, layer3_chunk7); - - v_r0 = _mm_unpacklo_epi8(layer4_chunk0, layer4_chunk4); - v_r1 = _mm_unpackhi_epi8(layer4_chunk0, layer4_chunk4); - v_g0 = _mm_unpacklo_epi8(layer4_chunk1, layer4_chunk5); - v_g1 = _mm_unpackhi_epi8(layer4_chunk1, layer4_chunk5); - v_b0 = _mm_unpacklo_epi8(layer4_chunk2, layer4_chunk6); - v_b1 = _mm_unpackhi_epi8(layer4_chunk2, layer4_chunk6); - v_a0 = _mm_unpacklo_epi8(layer4_chunk3, layer4_chunk7); - v_a1 = _mm_unpackhi_epi8(layer4_chunk3, layer4_chunk7); -} - -inline void _mm_interleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1) -{ - __m128i v_mask = _mm_set1_epi16(0x00ff); - - __m128i layer4_chunk0 = _mm_packus_epi16(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); - __m128i layer4_chunk2 = _mm_packus_epi16(_mm_srli_epi16(v_r0, 8), _mm_srli_epi16(v_r1, 8)); - __m128i layer4_chunk1 = _mm_packus_epi16(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); - __m128i layer4_chunk3 = _mm_packus_epi16(_mm_srli_epi16(v_g0, 8), _mm_srli_epi16(v_g1, 8)); - - __m128i layer3_chunk0 = _mm_packus_epi16(_mm_and_si128(layer4_chunk0, v_mask), _mm_and_si128(layer4_chunk1, v_mask)); - __m128i layer3_chunk2 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk0, 8), _mm_srli_epi16(layer4_chunk1, 8)); - __m128i layer3_chunk1 = _mm_packus_epi16(_mm_and_si128(layer4_chunk2, v_mask), _mm_and_si128(layer4_chunk3, v_mask)); - __m128i layer3_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk2, 8), _mm_srli_epi16(layer4_chunk3, 8)); - - __m128i layer2_chunk0 = _mm_packus_epi16(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); - __m128i layer2_chunk2 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk0, 8), _mm_srli_epi16(layer3_chunk1, 8)); - __m128i layer2_chunk1 = _mm_packus_epi16(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); - __m128i layer2_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk2, 8), _mm_srli_epi16(layer3_chunk3, 8)); - - __m128i layer1_chunk0 = _mm_packus_epi16(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); - __m128i layer1_chunk2 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk0, 8), _mm_srli_epi16(layer2_chunk1, 8)); - __m128i layer1_chunk1 = _mm_packus_epi16(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); - __m128i layer1_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk2, 8), _mm_srli_epi16(layer2_chunk3, 8)); - - v_r0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); - v_g0 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk0, 8), _mm_srli_epi16(layer1_chunk1, 8)); - v_r1 = _mm_packus_epi16(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); - v_g1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk2, 8), _mm_srli_epi16(layer1_chunk3, 8)); -} - -inline void _mm_interleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, - __m128i & v_g1, __m128i & v_b0, __m128i & v_b1) -{ - __m128i v_mask = _mm_set1_epi16(0x00ff); - - __m128i layer4_chunk0 = _mm_packus_epi16(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); - __m128i layer4_chunk3 = _mm_packus_epi16(_mm_srli_epi16(v_r0, 8), _mm_srli_epi16(v_r1, 8)); - __m128i layer4_chunk1 = _mm_packus_epi16(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); - __m128i layer4_chunk4 = _mm_packus_epi16(_mm_srli_epi16(v_g0, 8), _mm_srli_epi16(v_g1, 8)); - __m128i layer4_chunk2 = _mm_packus_epi16(_mm_and_si128(v_b0, v_mask), _mm_and_si128(v_b1, v_mask)); - __m128i layer4_chunk5 = _mm_packus_epi16(_mm_srli_epi16(v_b0, 8), _mm_srli_epi16(v_b1, 8)); - - __m128i layer3_chunk0 = _mm_packus_epi16(_mm_and_si128(layer4_chunk0, v_mask), _mm_and_si128(layer4_chunk1, v_mask)); - __m128i layer3_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk0, 8), _mm_srli_epi16(layer4_chunk1, 8)); - __m128i layer3_chunk1 = _mm_packus_epi16(_mm_and_si128(layer4_chunk2, v_mask), _mm_and_si128(layer4_chunk3, v_mask)); - __m128i layer3_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk2, 8), _mm_srli_epi16(layer4_chunk3, 8)); - __m128i layer3_chunk2 = _mm_packus_epi16(_mm_and_si128(layer4_chunk4, v_mask), _mm_and_si128(layer4_chunk5, v_mask)); - __m128i layer3_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk4, 8), _mm_srli_epi16(layer4_chunk5, 8)); - - __m128i layer2_chunk0 = _mm_packus_epi16(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); - __m128i layer2_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk0, 8), _mm_srli_epi16(layer3_chunk1, 8)); - __m128i layer2_chunk1 = _mm_packus_epi16(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); - __m128i layer2_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk2, 8), _mm_srli_epi16(layer3_chunk3, 8)); - __m128i layer2_chunk2 = _mm_packus_epi16(_mm_and_si128(layer3_chunk4, v_mask), _mm_and_si128(layer3_chunk5, v_mask)); - __m128i layer2_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk4, 8), _mm_srli_epi16(layer3_chunk5, 8)); - - __m128i layer1_chunk0 = _mm_packus_epi16(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); - __m128i layer1_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk0, 8), _mm_srli_epi16(layer2_chunk1, 8)); - __m128i layer1_chunk1 = _mm_packus_epi16(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); - __m128i layer1_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk2, 8), _mm_srli_epi16(layer2_chunk3, 8)); - __m128i layer1_chunk2 = _mm_packus_epi16(_mm_and_si128(layer2_chunk4, v_mask), _mm_and_si128(layer2_chunk5, v_mask)); - __m128i layer1_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk4, 8), _mm_srli_epi16(layer2_chunk5, 8)); - - v_r0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); - v_g1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk0, 8), _mm_srli_epi16(layer1_chunk1, 8)); - v_r1 = _mm_packus_epi16(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); - v_b0 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk2, 8), _mm_srli_epi16(layer1_chunk3, 8)); - v_g0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk4, v_mask), _mm_and_si128(layer1_chunk5, v_mask)); - v_b1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk4, 8), _mm_srli_epi16(layer1_chunk5, 8)); -} - -inline void _mm_interleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1, - __m128i & v_b0, __m128i & v_b1, __m128i & v_a0, __m128i & v_a1) -{ - __m128i v_mask = _mm_set1_epi16(0x00ff); - - __m128i layer4_chunk0 = _mm_packus_epi16(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); - __m128i layer4_chunk4 = _mm_packus_epi16(_mm_srli_epi16(v_r0, 8), _mm_srli_epi16(v_r1, 8)); - __m128i layer4_chunk1 = _mm_packus_epi16(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); - __m128i layer4_chunk5 = _mm_packus_epi16(_mm_srli_epi16(v_g0, 8), _mm_srli_epi16(v_g1, 8)); - __m128i layer4_chunk2 = _mm_packus_epi16(_mm_and_si128(v_b0, v_mask), _mm_and_si128(v_b1, v_mask)); - __m128i layer4_chunk6 = _mm_packus_epi16(_mm_srli_epi16(v_b0, 8), _mm_srli_epi16(v_b1, 8)); - __m128i layer4_chunk3 = _mm_packus_epi16(_mm_and_si128(v_a0, v_mask), _mm_and_si128(v_a1, v_mask)); - __m128i layer4_chunk7 = _mm_packus_epi16(_mm_srli_epi16(v_a0, 8), _mm_srli_epi16(v_a1, 8)); - - __m128i layer3_chunk0 = _mm_packus_epi16(_mm_and_si128(layer4_chunk0, v_mask), _mm_and_si128(layer4_chunk1, v_mask)); - __m128i layer3_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk0, 8), _mm_srli_epi16(layer4_chunk1, 8)); - __m128i layer3_chunk1 = _mm_packus_epi16(_mm_and_si128(layer4_chunk2, v_mask), _mm_and_si128(layer4_chunk3, v_mask)); - __m128i layer3_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk2, 8), _mm_srli_epi16(layer4_chunk3, 8)); - __m128i layer3_chunk2 = _mm_packus_epi16(_mm_and_si128(layer4_chunk4, v_mask), _mm_and_si128(layer4_chunk5, v_mask)); - __m128i layer3_chunk6 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk4, 8), _mm_srli_epi16(layer4_chunk5, 8)); - __m128i layer3_chunk3 = _mm_packus_epi16(_mm_and_si128(layer4_chunk6, v_mask), _mm_and_si128(layer4_chunk7, v_mask)); - __m128i layer3_chunk7 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk6, 8), _mm_srli_epi16(layer4_chunk7, 8)); - - __m128i layer2_chunk0 = _mm_packus_epi16(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); - __m128i layer2_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk0, 8), _mm_srli_epi16(layer3_chunk1, 8)); - __m128i layer2_chunk1 = _mm_packus_epi16(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); - __m128i layer2_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk2, 8), _mm_srli_epi16(layer3_chunk3, 8)); - __m128i layer2_chunk2 = _mm_packus_epi16(_mm_and_si128(layer3_chunk4, v_mask), _mm_and_si128(layer3_chunk5, v_mask)); - __m128i layer2_chunk6 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk4, 8), _mm_srli_epi16(layer3_chunk5, 8)); - __m128i layer2_chunk3 = _mm_packus_epi16(_mm_and_si128(layer3_chunk6, v_mask), _mm_and_si128(layer3_chunk7, v_mask)); - __m128i layer2_chunk7 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk6, 8), _mm_srli_epi16(layer3_chunk7, 8)); - - __m128i layer1_chunk0 = _mm_packus_epi16(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); - __m128i layer1_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk0, 8), _mm_srli_epi16(layer2_chunk1, 8)); - __m128i layer1_chunk1 = _mm_packus_epi16(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); - __m128i layer1_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk2, 8), _mm_srli_epi16(layer2_chunk3, 8)); - __m128i layer1_chunk2 = _mm_packus_epi16(_mm_and_si128(layer2_chunk4, v_mask), _mm_and_si128(layer2_chunk5, v_mask)); - __m128i layer1_chunk6 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk4, 8), _mm_srli_epi16(layer2_chunk5, 8)); - __m128i layer1_chunk3 = _mm_packus_epi16(_mm_and_si128(layer2_chunk6, v_mask), _mm_and_si128(layer2_chunk7, v_mask)); - __m128i layer1_chunk7 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk6, 8), _mm_srli_epi16(layer2_chunk7, 8)); - - v_r0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); - v_b0 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk0, 8), _mm_srli_epi16(layer1_chunk1, 8)); - v_r1 = _mm_packus_epi16(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); - v_b1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk2, 8), _mm_srli_epi16(layer1_chunk3, 8)); - v_g0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk4, v_mask), _mm_and_si128(layer1_chunk5, v_mask)); - v_a0 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk4, 8), _mm_srli_epi16(layer1_chunk5, 8)); - v_g1 = _mm_packus_epi16(_mm_and_si128(layer1_chunk6, v_mask), _mm_and_si128(layer1_chunk7, v_mask)); - v_a1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk6, 8), _mm_srli_epi16(layer1_chunk7, 8)); -} - -inline void _mm_deinterleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1) -{ - __m128i layer1_chunk0 = _mm_unpacklo_epi16(v_r0, v_g0); - __m128i layer1_chunk1 = _mm_unpackhi_epi16(v_r0, v_g0); - __m128i layer1_chunk2 = _mm_unpacklo_epi16(v_r1, v_g1); - __m128i layer1_chunk3 = _mm_unpackhi_epi16(v_r1, v_g1); - - __m128i layer2_chunk0 = _mm_unpacklo_epi16(layer1_chunk0, layer1_chunk2); - __m128i layer2_chunk1 = _mm_unpackhi_epi16(layer1_chunk0, layer1_chunk2); - __m128i layer2_chunk2 = _mm_unpacklo_epi16(layer1_chunk1, layer1_chunk3); - __m128i layer2_chunk3 = _mm_unpackhi_epi16(layer1_chunk1, layer1_chunk3); - - __m128i layer3_chunk0 = _mm_unpacklo_epi16(layer2_chunk0, layer2_chunk2); - __m128i layer3_chunk1 = _mm_unpackhi_epi16(layer2_chunk0, layer2_chunk2); - __m128i layer3_chunk2 = _mm_unpacklo_epi16(layer2_chunk1, layer2_chunk3); - __m128i layer3_chunk3 = _mm_unpackhi_epi16(layer2_chunk1, layer2_chunk3); - - v_r0 = _mm_unpacklo_epi16(layer3_chunk0, layer3_chunk2); - v_r1 = _mm_unpackhi_epi16(layer3_chunk0, layer3_chunk2); - v_g0 = _mm_unpacklo_epi16(layer3_chunk1, layer3_chunk3); - v_g1 = _mm_unpackhi_epi16(layer3_chunk1, layer3_chunk3); -} - -inline void _mm_deinterleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, - __m128i & v_g1, __m128i & v_b0, __m128i & v_b1) -{ - __m128i layer1_chunk0 = _mm_unpacklo_epi16(v_r0, v_g1); - __m128i layer1_chunk1 = _mm_unpackhi_epi16(v_r0, v_g1); - __m128i layer1_chunk2 = _mm_unpacklo_epi16(v_r1, v_b0); - __m128i layer1_chunk3 = _mm_unpackhi_epi16(v_r1, v_b0); - __m128i layer1_chunk4 = _mm_unpacklo_epi16(v_g0, v_b1); - __m128i layer1_chunk5 = _mm_unpackhi_epi16(v_g0, v_b1); - - __m128i layer2_chunk0 = _mm_unpacklo_epi16(layer1_chunk0, layer1_chunk3); - __m128i layer2_chunk1 = _mm_unpackhi_epi16(layer1_chunk0, layer1_chunk3); - __m128i layer2_chunk2 = _mm_unpacklo_epi16(layer1_chunk1, layer1_chunk4); - __m128i layer2_chunk3 = _mm_unpackhi_epi16(layer1_chunk1, layer1_chunk4); - __m128i layer2_chunk4 = _mm_unpacklo_epi16(layer1_chunk2, layer1_chunk5); - __m128i layer2_chunk5 = _mm_unpackhi_epi16(layer1_chunk2, layer1_chunk5); - - __m128i layer3_chunk0 = _mm_unpacklo_epi16(layer2_chunk0, layer2_chunk3); - __m128i layer3_chunk1 = _mm_unpackhi_epi16(layer2_chunk0, layer2_chunk3); - __m128i layer3_chunk2 = _mm_unpacklo_epi16(layer2_chunk1, layer2_chunk4); - __m128i layer3_chunk3 = _mm_unpackhi_epi16(layer2_chunk1, layer2_chunk4); - __m128i layer3_chunk4 = _mm_unpacklo_epi16(layer2_chunk2, layer2_chunk5); - __m128i layer3_chunk5 = _mm_unpackhi_epi16(layer2_chunk2, layer2_chunk5); - - v_r0 = _mm_unpacklo_epi16(layer3_chunk0, layer3_chunk3); - v_r1 = _mm_unpackhi_epi16(layer3_chunk0, layer3_chunk3); - v_g0 = _mm_unpacklo_epi16(layer3_chunk1, layer3_chunk4); - v_g1 = _mm_unpackhi_epi16(layer3_chunk1, layer3_chunk4); - v_b0 = _mm_unpacklo_epi16(layer3_chunk2, layer3_chunk5); - v_b1 = _mm_unpackhi_epi16(layer3_chunk2, layer3_chunk5); -} - -inline void _mm_deinterleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1, - __m128i & v_b0, __m128i & v_b1, __m128i & v_a0, __m128i & v_a1) -{ - __m128i layer1_chunk0 = _mm_unpacklo_epi16(v_r0, v_b0); - __m128i layer1_chunk1 = _mm_unpackhi_epi16(v_r0, v_b0); - __m128i layer1_chunk2 = _mm_unpacklo_epi16(v_r1, v_b1); - __m128i layer1_chunk3 = _mm_unpackhi_epi16(v_r1, v_b1); - __m128i layer1_chunk4 = _mm_unpacklo_epi16(v_g0, v_a0); - __m128i layer1_chunk5 = _mm_unpackhi_epi16(v_g0, v_a0); - __m128i layer1_chunk6 = _mm_unpacklo_epi16(v_g1, v_a1); - __m128i layer1_chunk7 = _mm_unpackhi_epi16(v_g1, v_a1); - - __m128i layer2_chunk0 = _mm_unpacklo_epi16(layer1_chunk0, layer1_chunk4); - __m128i layer2_chunk1 = _mm_unpackhi_epi16(layer1_chunk0, layer1_chunk4); - __m128i layer2_chunk2 = _mm_unpacklo_epi16(layer1_chunk1, layer1_chunk5); - __m128i layer2_chunk3 = _mm_unpackhi_epi16(layer1_chunk1, layer1_chunk5); - __m128i layer2_chunk4 = _mm_unpacklo_epi16(layer1_chunk2, layer1_chunk6); - __m128i layer2_chunk5 = _mm_unpackhi_epi16(layer1_chunk2, layer1_chunk6); - __m128i layer2_chunk6 = _mm_unpacklo_epi16(layer1_chunk3, layer1_chunk7); - __m128i layer2_chunk7 = _mm_unpackhi_epi16(layer1_chunk3, layer1_chunk7); - - __m128i layer3_chunk0 = _mm_unpacklo_epi16(layer2_chunk0, layer2_chunk4); - __m128i layer3_chunk1 = _mm_unpackhi_epi16(layer2_chunk0, layer2_chunk4); - __m128i layer3_chunk2 = _mm_unpacklo_epi16(layer2_chunk1, layer2_chunk5); - __m128i layer3_chunk3 = _mm_unpackhi_epi16(layer2_chunk1, layer2_chunk5); - __m128i layer3_chunk4 = _mm_unpacklo_epi16(layer2_chunk2, layer2_chunk6); - __m128i layer3_chunk5 = _mm_unpackhi_epi16(layer2_chunk2, layer2_chunk6); - __m128i layer3_chunk6 = _mm_unpacklo_epi16(layer2_chunk3, layer2_chunk7); - __m128i layer3_chunk7 = _mm_unpackhi_epi16(layer2_chunk3, layer2_chunk7); - - v_r0 = _mm_unpacklo_epi16(layer3_chunk0, layer3_chunk4); - v_r1 = _mm_unpackhi_epi16(layer3_chunk0, layer3_chunk4); - v_g0 = _mm_unpacklo_epi16(layer3_chunk1, layer3_chunk5); - v_g1 = _mm_unpackhi_epi16(layer3_chunk1, layer3_chunk5); - v_b0 = _mm_unpacklo_epi16(layer3_chunk2, layer3_chunk6); - v_b1 = _mm_unpackhi_epi16(layer3_chunk2, layer3_chunk6); - v_a0 = _mm_unpacklo_epi16(layer3_chunk3, layer3_chunk7); - v_a1 = _mm_unpackhi_epi16(layer3_chunk3, layer3_chunk7); -} - -#if CV_SSE4_1 - -inline void _mm_interleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1) -{ - __m128i v_mask = _mm_set1_epi32(0x0000ffff); - - __m128i layer3_chunk0 = _mm_packus_epi32(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); - __m128i layer3_chunk2 = _mm_packus_epi32(_mm_srli_epi32(v_r0, 16), _mm_srli_epi32(v_r1, 16)); - __m128i layer3_chunk1 = _mm_packus_epi32(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); - __m128i layer3_chunk3 = _mm_packus_epi32(_mm_srli_epi32(v_g0, 16), _mm_srli_epi32(v_g1, 16)); - - __m128i layer2_chunk0 = _mm_packus_epi32(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); - __m128i layer2_chunk2 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk0, 16), _mm_srli_epi32(layer3_chunk1, 16)); - __m128i layer2_chunk1 = _mm_packus_epi32(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); - __m128i layer2_chunk3 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk2, 16), _mm_srli_epi32(layer3_chunk3, 16)); - - __m128i layer1_chunk0 = _mm_packus_epi32(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); - __m128i layer1_chunk2 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk0, 16), _mm_srli_epi32(layer2_chunk1, 16)); - __m128i layer1_chunk1 = _mm_packus_epi32(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); - __m128i layer1_chunk3 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk2, 16), _mm_srli_epi32(layer2_chunk3, 16)); - - v_r0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); - v_g0 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk0, 16), _mm_srli_epi32(layer1_chunk1, 16)); - v_r1 = _mm_packus_epi32(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); - v_g1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk2, 16), _mm_srli_epi32(layer1_chunk3, 16)); -} - -inline void _mm_interleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, - __m128i & v_g1, __m128i & v_b0, __m128i & v_b1) -{ - __m128i v_mask = _mm_set1_epi32(0x0000ffff); - - __m128i layer3_chunk0 = _mm_packus_epi32(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); - __m128i layer3_chunk3 = _mm_packus_epi32(_mm_srli_epi32(v_r0, 16), _mm_srli_epi32(v_r1, 16)); - __m128i layer3_chunk1 = _mm_packus_epi32(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); - __m128i layer3_chunk4 = _mm_packus_epi32(_mm_srli_epi32(v_g0, 16), _mm_srli_epi32(v_g1, 16)); - __m128i layer3_chunk2 = _mm_packus_epi32(_mm_and_si128(v_b0, v_mask), _mm_and_si128(v_b1, v_mask)); - __m128i layer3_chunk5 = _mm_packus_epi32(_mm_srli_epi32(v_b0, 16), _mm_srli_epi32(v_b1, 16)); - - __m128i layer2_chunk0 = _mm_packus_epi32(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); - __m128i layer2_chunk3 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk0, 16), _mm_srli_epi32(layer3_chunk1, 16)); - __m128i layer2_chunk1 = _mm_packus_epi32(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); - __m128i layer2_chunk4 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk2, 16), _mm_srli_epi32(layer3_chunk3, 16)); - __m128i layer2_chunk2 = _mm_packus_epi32(_mm_and_si128(layer3_chunk4, v_mask), _mm_and_si128(layer3_chunk5, v_mask)); - __m128i layer2_chunk5 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk4, 16), _mm_srli_epi32(layer3_chunk5, 16)); - - __m128i layer1_chunk0 = _mm_packus_epi32(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); - __m128i layer1_chunk3 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk0, 16), _mm_srli_epi32(layer2_chunk1, 16)); - __m128i layer1_chunk1 = _mm_packus_epi32(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); - __m128i layer1_chunk4 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk2, 16), _mm_srli_epi32(layer2_chunk3, 16)); - __m128i layer1_chunk2 = _mm_packus_epi32(_mm_and_si128(layer2_chunk4, v_mask), _mm_and_si128(layer2_chunk5, v_mask)); - __m128i layer1_chunk5 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk4, 16), _mm_srli_epi32(layer2_chunk5, 16)); - - v_r0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); - v_g1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk0, 16), _mm_srli_epi32(layer1_chunk1, 16)); - v_r1 = _mm_packus_epi32(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); - v_b0 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk2, 16), _mm_srli_epi32(layer1_chunk3, 16)); - v_g0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk4, v_mask), _mm_and_si128(layer1_chunk5, v_mask)); - v_b1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk4, 16), _mm_srli_epi32(layer1_chunk5, 16)); -} - -inline void _mm_interleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1, - __m128i & v_b0, __m128i & v_b1, __m128i & v_a0, __m128i & v_a1) -{ - __m128i v_mask = _mm_set1_epi32(0x0000ffff); - - __m128i layer3_chunk0 = _mm_packus_epi32(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); - __m128i layer3_chunk4 = _mm_packus_epi32(_mm_srli_epi32(v_r0, 16), _mm_srli_epi32(v_r1, 16)); - __m128i layer3_chunk1 = _mm_packus_epi32(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); - __m128i layer3_chunk5 = _mm_packus_epi32(_mm_srli_epi32(v_g0, 16), _mm_srli_epi32(v_g1, 16)); - __m128i layer3_chunk2 = _mm_packus_epi32(_mm_and_si128(v_b0, v_mask), _mm_and_si128(v_b1, v_mask)); - __m128i layer3_chunk6 = _mm_packus_epi32(_mm_srli_epi32(v_b0, 16), _mm_srli_epi32(v_b1, 16)); - __m128i layer3_chunk3 = _mm_packus_epi32(_mm_and_si128(v_a0, v_mask), _mm_and_si128(v_a1, v_mask)); - __m128i layer3_chunk7 = _mm_packus_epi32(_mm_srli_epi32(v_a0, 16), _mm_srli_epi32(v_a1, 16)); - - __m128i layer2_chunk0 = _mm_packus_epi32(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); - __m128i layer2_chunk4 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk0, 16), _mm_srli_epi32(layer3_chunk1, 16)); - __m128i layer2_chunk1 = _mm_packus_epi32(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); - __m128i layer2_chunk5 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk2, 16), _mm_srli_epi32(layer3_chunk3, 16)); - __m128i layer2_chunk2 = _mm_packus_epi32(_mm_and_si128(layer3_chunk4, v_mask), _mm_and_si128(layer3_chunk5, v_mask)); - __m128i layer2_chunk6 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk4, 16), _mm_srli_epi32(layer3_chunk5, 16)); - __m128i layer2_chunk3 = _mm_packus_epi32(_mm_and_si128(layer3_chunk6, v_mask), _mm_and_si128(layer3_chunk7, v_mask)); - __m128i layer2_chunk7 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk6, 16), _mm_srli_epi32(layer3_chunk7, 16)); - - __m128i layer1_chunk0 = _mm_packus_epi32(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); - __m128i layer1_chunk4 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk0, 16), _mm_srli_epi32(layer2_chunk1, 16)); - __m128i layer1_chunk1 = _mm_packus_epi32(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); - __m128i layer1_chunk5 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk2, 16), _mm_srli_epi32(layer2_chunk3, 16)); - __m128i layer1_chunk2 = _mm_packus_epi32(_mm_and_si128(layer2_chunk4, v_mask), _mm_and_si128(layer2_chunk5, v_mask)); - __m128i layer1_chunk6 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk4, 16), _mm_srli_epi32(layer2_chunk5, 16)); - __m128i layer1_chunk3 = _mm_packus_epi32(_mm_and_si128(layer2_chunk6, v_mask), _mm_and_si128(layer2_chunk7, v_mask)); - __m128i layer1_chunk7 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk6, 16), _mm_srli_epi32(layer2_chunk7, 16)); - - v_r0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); - v_b0 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk0, 16), _mm_srli_epi32(layer1_chunk1, 16)); - v_r1 = _mm_packus_epi32(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); - v_b1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk2, 16), _mm_srli_epi32(layer1_chunk3, 16)); - v_g0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk4, v_mask), _mm_and_si128(layer1_chunk5, v_mask)); - v_a0 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk4, 16), _mm_srli_epi32(layer1_chunk5, 16)); - v_g1 = _mm_packus_epi32(_mm_and_si128(layer1_chunk6, v_mask), _mm_and_si128(layer1_chunk7, v_mask)); - v_a1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk6, 16), _mm_srli_epi32(layer1_chunk7, 16)); -} - -#endif // CV_SSE4_1 - -inline void _mm_deinterleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, __m128 & v_g1) -{ - __m128 layer1_chunk0 = _mm_unpacklo_ps(v_r0, v_g0); - __m128 layer1_chunk1 = _mm_unpackhi_ps(v_r0, v_g0); - __m128 layer1_chunk2 = _mm_unpacklo_ps(v_r1, v_g1); - __m128 layer1_chunk3 = _mm_unpackhi_ps(v_r1, v_g1); - - __m128 layer2_chunk0 = _mm_unpacklo_ps(layer1_chunk0, layer1_chunk2); - __m128 layer2_chunk1 = _mm_unpackhi_ps(layer1_chunk0, layer1_chunk2); - __m128 layer2_chunk2 = _mm_unpacklo_ps(layer1_chunk1, layer1_chunk3); - __m128 layer2_chunk3 = _mm_unpackhi_ps(layer1_chunk1, layer1_chunk3); - - v_r0 = _mm_unpacklo_ps(layer2_chunk0, layer2_chunk2); - v_r1 = _mm_unpackhi_ps(layer2_chunk0, layer2_chunk2); - v_g0 = _mm_unpacklo_ps(layer2_chunk1, layer2_chunk3); - v_g1 = _mm_unpackhi_ps(layer2_chunk1, layer2_chunk3); -} - -inline void _mm_deinterleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, - __m128 & v_g1, __m128 & v_b0, __m128 & v_b1) -{ - __m128 layer1_chunk0 = _mm_unpacklo_ps(v_r0, v_g1); - __m128 layer1_chunk1 = _mm_unpackhi_ps(v_r0, v_g1); - __m128 layer1_chunk2 = _mm_unpacklo_ps(v_r1, v_b0); - __m128 layer1_chunk3 = _mm_unpackhi_ps(v_r1, v_b0); - __m128 layer1_chunk4 = _mm_unpacklo_ps(v_g0, v_b1); - __m128 layer1_chunk5 = _mm_unpackhi_ps(v_g0, v_b1); - - __m128 layer2_chunk0 = _mm_unpacklo_ps(layer1_chunk0, layer1_chunk3); - __m128 layer2_chunk1 = _mm_unpackhi_ps(layer1_chunk0, layer1_chunk3); - __m128 layer2_chunk2 = _mm_unpacklo_ps(layer1_chunk1, layer1_chunk4); - __m128 layer2_chunk3 = _mm_unpackhi_ps(layer1_chunk1, layer1_chunk4); - __m128 layer2_chunk4 = _mm_unpacklo_ps(layer1_chunk2, layer1_chunk5); - __m128 layer2_chunk5 = _mm_unpackhi_ps(layer1_chunk2, layer1_chunk5); - - v_r0 = _mm_unpacklo_ps(layer2_chunk0, layer2_chunk3); - v_r1 = _mm_unpackhi_ps(layer2_chunk0, layer2_chunk3); - v_g0 = _mm_unpacklo_ps(layer2_chunk1, layer2_chunk4); - v_g1 = _mm_unpackhi_ps(layer2_chunk1, layer2_chunk4); - v_b0 = _mm_unpacklo_ps(layer2_chunk2, layer2_chunk5); - v_b1 = _mm_unpackhi_ps(layer2_chunk2, layer2_chunk5); -} - -inline void _mm_deinterleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, __m128 & v_g1, - __m128 & v_b0, __m128 & v_b1, __m128 & v_a0, __m128 & v_a1) -{ - __m128 layer1_chunk0 = _mm_unpacklo_ps(v_r0, v_b0); - __m128 layer1_chunk1 = _mm_unpackhi_ps(v_r0, v_b0); - __m128 layer1_chunk2 = _mm_unpacklo_ps(v_r1, v_b1); - __m128 layer1_chunk3 = _mm_unpackhi_ps(v_r1, v_b1); - __m128 layer1_chunk4 = _mm_unpacklo_ps(v_g0, v_a0); - __m128 layer1_chunk5 = _mm_unpackhi_ps(v_g0, v_a0); - __m128 layer1_chunk6 = _mm_unpacklo_ps(v_g1, v_a1); - __m128 layer1_chunk7 = _mm_unpackhi_ps(v_g1, v_a1); - - __m128 layer2_chunk0 = _mm_unpacklo_ps(layer1_chunk0, layer1_chunk4); - __m128 layer2_chunk1 = _mm_unpackhi_ps(layer1_chunk0, layer1_chunk4); - __m128 layer2_chunk2 = _mm_unpacklo_ps(layer1_chunk1, layer1_chunk5); - __m128 layer2_chunk3 = _mm_unpackhi_ps(layer1_chunk1, layer1_chunk5); - __m128 layer2_chunk4 = _mm_unpacklo_ps(layer1_chunk2, layer1_chunk6); - __m128 layer2_chunk5 = _mm_unpackhi_ps(layer1_chunk2, layer1_chunk6); - __m128 layer2_chunk6 = _mm_unpacklo_ps(layer1_chunk3, layer1_chunk7); - __m128 layer2_chunk7 = _mm_unpackhi_ps(layer1_chunk3, layer1_chunk7); - - v_r0 = _mm_unpacklo_ps(layer2_chunk0, layer2_chunk4); - v_r1 = _mm_unpackhi_ps(layer2_chunk0, layer2_chunk4); - v_g0 = _mm_unpacklo_ps(layer2_chunk1, layer2_chunk5); - v_g1 = _mm_unpackhi_ps(layer2_chunk1, layer2_chunk5); - v_b0 = _mm_unpacklo_ps(layer2_chunk2, layer2_chunk6); - v_b1 = _mm_unpackhi_ps(layer2_chunk2, layer2_chunk6); - v_a0 = _mm_unpacklo_ps(layer2_chunk3, layer2_chunk7); - v_a1 = _mm_unpackhi_ps(layer2_chunk3, layer2_chunk7); -} - -inline void _mm_interleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, __m128 & v_g1) -{ - enum { mask_lo = _MM_SHUFFLE(2, 0, 2, 0), mask_hi = _MM_SHUFFLE(3, 1, 3, 1) }; - - __m128 layer2_chunk0 = _mm_shuffle_ps(v_r0, v_r1, mask_lo); - __m128 layer2_chunk2 = _mm_shuffle_ps(v_r0, v_r1, mask_hi); - __m128 layer2_chunk1 = _mm_shuffle_ps(v_g0, v_g1, mask_lo); - __m128 layer2_chunk3 = _mm_shuffle_ps(v_g0, v_g1, mask_hi); - - __m128 layer1_chunk0 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_lo); - __m128 layer1_chunk2 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_hi); - __m128 layer1_chunk1 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_lo); - __m128 layer1_chunk3 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_hi); - - v_r0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_lo); - v_g0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_hi); - v_r1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_lo); - v_g1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_hi); -} - -inline void _mm_interleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, - __m128 & v_g1, __m128 & v_b0, __m128 & v_b1) -{ - enum { mask_lo = _MM_SHUFFLE(2, 0, 2, 0), mask_hi = _MM_SHUFFLE(3, 1, 3, 1) }; - - __m128 layer2_chunk0 = _mm_shuffle_ps(v_r0, v_r1, mask_lo); - __m128 layer2_chunk3 = _mm_shuffle_ps(v_r0, v_r1, mask_hi); - __m128 layer2_chunk1 = _mm_shuffle_ps(v_g0, v_g1, mask_lo); - __m128 layer2_chunk4 = _mm_shuffle_ps(v_g0, v_g1, mask_hi); - __m128 layer2_chunk2 = _mm_shuffle_ps(v_b0, v_b1, mask_lo); - __m128 layer2_chunk5 = _mm_shuffle_ps(v_b0, v_b1, mask_hi); - - __m128 layer1_chunk0 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_lo); - __m128 layer1_chunk3 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_hi); - __m128 layer1_chunk1 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_lo); - __m128 layer1_chunk4 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_hi); - __m128 layer1_chunk2 = _mm_shuffle_ps(layer2_chunk4, layer2_chunk5, mask_lo); - __m128 layer1_chunk5 = _mm_shuffle_ps(layer2_chunk4, layer2_chunk5, mask_hi); - - v_r0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_lo); - v_g1 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_hi); - v_r1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_lo); - v_b0 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_hi); - v_g0 = _mm_shuffle_ps(layer1_chunk4, layer1_chunk5, mask_lo); - v_b1 = _mm_shuffle_ps(layer1_chunk4, layer1_chunk5, mask_hi); -} - -inline void _mm_interleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, __m128 & v_g1, - __m128 & v_b0, __m128 & v_b1, __m128 & v_a0, __m128 & v_a1) -{ - enum { mask_lo = _MM_SHUFFLE(2, 0, 2, 0), mask_hi = _MM_SHUFFLE(3, 1, 3, 1) }; - - __m128 layer2_chunk0 = _mm_shuffle_ps(v_r0, v_r1, mask_lo); - __m128 layer2_chunk4 = _mm_shuffle_ps(v_r0, v_r1, mask_hi); - __m128 layer2_chunk1 = _mm_shuffle_ps(v_g0, v_g1, mask_lo); - __m128 layer2_chunk5 = _mm_shuffle_ps(v_g0, v_g1, mask_hi); - __m128 layer2_chunk2 = _mm_shuffle_ps(v_b0, v_b1, mask_lo); - __m128 layer2_chunk6 = _mm_shuffle_ps(v_b0, v_b1, mask_hi); - __m128 layer2_chunk3 = _mm_shuffle_ps(v_a0, v_a1, mask_lo); - __m128 layer2_chunk7 = _mm_shuffle_ps(v_a0, v_a1, mask_hi); - - __m128 layer1_chunk0 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_lo); - __m128 layer1_chunk4 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_hi); - __m128 layer1_chunk1 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_lo); - __m128 layer1_chunk5 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_hi); - __m128 layer1_chunk2 = _mm_shuffle_ps(layer2_chunk4, layer2_chunk5, mask_lo); - __m128 layer1_chunk6 = _mm_shuffle_ps(layer2_chunk4, layer2_chunk5, mask_hi); - __m128 layer1_chunk3 = _mm_shuffle_ps(layer2_chunk6, layer2_chunk7, mask_lo); - __m128 layer1_chunk7 = _mm_shuffle_ps(layer2_chunk6, layer2_chunk7, mask_hi); - - v_r0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_lo); - v_b0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_hi); - v_r1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_lo); - v_b1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_hi); - v_g0 = _mm_shuffle_ps(layer1_chunk4, layer1_chunk5, mask_lo); - v_a0 = _mm_shuffle_ps(layer1_chunk4, layer1_chunk5, mask_hi); - v_g1 = _mm_shuffle_ps(layer1_chunk6, layer1_chunk7, mask_lo); - v_a1 = _mm_shuffle_ps(layer1_chunk6, layer1_chunk7, mask_hi); -} - -#endif // CV_SSE2 - -//! @} - -#endif //OPENCV_CORE_SSE_UTILS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CORE_SSE_UTILS_HPP +#define OPENCV_CORE_SSE_UTILS_HPP + +#ifndef __cplusplus +# error sse_utils.hpp header must be compiled as C++ +#endif + +#include "opencv2/core/cvdef.h" + +//! @addtogroup core_utils_sse +//! @{ + +#if CV_SSE2 + +inline void _mm_deinterleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1) +{ + __m128i layer1_chunk0 = _mm_unpacklo_epi8(v_r0, v_g0); + __m128i layer1_chunk1 = _mm_unpackhi_epi8(v_r0, v_g0); + __m128i layer1_chunk2 = _mm_unpacklo_epi8(v_r1, v_g1); + __m128i layer1_chunk3 = _mm_unpackhi_epi8(v_r1, v_g1); + + __m128i layer2_chunk0 = _mm_unpacklo_epi8(layer1_chunk0, layer1_chunk2); + __m128i layer2_chunk1 = _mm_unpackhi_epi8(layer1_chunk0, layer1_chunk2); + __m128i layer2_chunk2 = _mm_unpacklo_epi8(layer1_chunk1, layer1_chunk3); + __m128i layer2_chunk3 = _mm_unpackhi_epi8(layer1_chunk1, layer1_chunk3); + + __m128i layer3_chunk0 = _mm_unpacklo_epi8(layer2_chunk0, layer2_chunk2); + __m128i layer3_chunk1 = _mm_unpackhi_epi8(layer2_chunk0, layer2_chunk2); + __m128i layer3_chunk2 = _mm_unpacklo_epi8(layer2_chunk1, layer2_chunk3); + __m128i layer3_chunk3 = _mm_unpackhi_epi8(layer2_chunk1, layer2_chunk3); + + __m128i layer4_chunk0 = _mm_unpacklo_epi8(layer3_chunk0, layer3_chunk2); + __m128i layer4_chunk1 = _mm_unpackhi_epi8(layer3_chunk0, layer3_chunk2); + __m128i layer4_chunk2 = _mm_unpacklo_epi8(layer3_chunk1, layer3_chunk3); + __m128i layer4_chunk3 = _mm_unpackhi_epi8(layer3_chunk1, layer3_chunk3); + + v_r0 = _mm_unpacklo_epi8(layer4_chunk0, layer4_chunk2); + v_r1 = _mm_unpackhi_epi8(layer4_chunk0, layer4_chunk2); + v_g0 = _mm_unpacklo_epi8(layer4_chunk1, layer4_chunk3); + v_g1 = _mm_unpackhi_epi8(layer4_chunk1, layer4_chunk3); +} + +inline void _mm_deinterleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, + __m128i & v_g1, __m128i & v_b0, __m128i & v_b1) +{ + __m128i layer1_chunk0 = _mm_unpacklo_epi8(v_r0, v_g1); + __m128i layer1_chunk1 = _mm_unpackhi_epi8(v_r0, v_g1); + __m128i layer1_chunk2 = _mm_unpacklo_epi8(v_r1, v_b0); + __m128i layer1_chunk3 = _mm_unpackhi_epi8(v_r1, v_b0); + __m128i layer1_chunk4 = _mm_unpacklo_epi8(v_g0, v_b1); + __m128i layer1_chunk5 = _mm_unpackhi_epi8(v_g0, v_b1); + + __m128i layer2_chunk0 = _mm_unpacklo_epi8(layer1_chunk0, layer1_chunk3); + __m128i layer2_chunk1 = _mm_unpackhi_epi8(layer1_chunk0, layer1_chunk3); + __m128i layer2_chunk2 = _mm_unpacklo_epi8(layer1_chunk1, layer1_chunk4); + __m128i layer2_chunk3 = _mm_unpackhi_epi8(layer1_chunk1, layer1_chunk4); + __m128i layer2_chunk4 = _mm_unpacklo_epi8(layer1_chunk2, layer1_chunk5); + __m128i layer2_chunk5 = _mm_unpackhi_epi8(layer1_chunk2, layer1_chunk5); + + __m128i layer3_chunk0 = _mm_unpacklo_epi8(layer2_chunk0, layer2_chunk3); + __m128i layer3_chunk1 = _mm_unpackhi_epi8(layer2_chunk0, layer2_chunk3); + __m128i layer3_chunk2 = _mm_unpacklo_epi8(layer2_chunk1, layer2_chunk4); + __m128i layer3_chunk3 = _mm_unpackhi_epi8(layer2_chunk1, layer2_chunk4); + __m128i layer3_chunk4 = _mm_unpacklo_epi8(layer2_chunk2, layer2_chunk5); + __m128i layer3_chunk5 = _mm_unpackhi_epi8(layer2_chunk2, layer2_chunk5); + + __m128i layer4_chunk0 = _mm_unpacklo_epi8(layer3_chunk0, layer3_chunk3); + __m128i layer4_chunk1 = _mm_unpackhi_epi8(layer3_chunk0, layer3_chunk3); + __m128i layer4_chunk2 = _mm_unpacklo_epi8(layer3_chunk1, layer3_chunk4); + __m128i layer4_chunk3 = _mm_unpackhi_epi8(layer3_chunk1, layer3_chunk4); + __m128i layer4_chunk4 = _mm_unpacklo_epi8(layer3_chunk2, layer3_chunk5); + __m128i layer4_chunk5 = _mm_unpackhi_epi8(layer3_chunk2, layer3_chunk5); + + v_r0 = _mm_unpacklo_epi8(layer4_chunk0, layer4_chunk3); + v_r1 = _mm_unpackhi_epi8(layer4_chunk0, layer4_chunk3); + v_g0 = _mm_unpacklo_epi8(layer4_chunk1, layer4_chunk4); + v_g1 = _mm_unpackhi_epi8(layer4_chunk1, layer4_chunk4); + v_b0 = _mm_unpacklo_epi8(layer4_chunk2, layer4_chunk5); + v_b1 = _mm_unpackhi_epi8(layer4_chunk2, layer4_chunk5); +} + +inline void _mm_deinterleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1, + __m128i & v_b0, __m128i & v_b1, __m128i & v_a0, __m128i & v_a1) +{ + __m128i layer1_chunk0 = _mm_unpacklo_epi8(v_r0, v_b0); + __m128i layer1_chunk1 = _mm_unpackhi_epi8(v_r0, v_b0); + __m128i layer1_chunk2 = _mm_unpacklo_epi8(v_r1, v_b1); + __m128i layer1_chunk3 = _mm_unpackhi_epi8(v_r1, v_b1); + __m128i layer1_chunk4 = _mm_unpacklo_epi8(v_g0, v_a0); + __m128i layer1_chunk5 = _mm_unpackhi_epi8(v_g0, v_a0); + __m128i layer1_chunk6 = _mm_unpacklo_epi8(v_g1, v_a1); + __m128i layer1_chunk7 = _mm_unpackhi_epi8(v_g1, v_a1); + + __m128i layer2_chunk0 = _mm_unpacklo_epi8(layer1_chunk0, layer1_chunk4); + __m128i layer2_chunk1 = _mm_unpackhi_epi8(layer1_chunk0, layer1_chunk4); + __m128i layer2_chunk2 = _mm_unpacklo_epi8(layer1_chunk1, layer1_chunk5); + __m128i layer2_chunk3 = _mm_unpackhi_epi8(layer1_chunk1, layer1_chunk5); + __m128i layer2_chunk4 = _mm_unpacklo_epi8(layer1_chunk2, layer1_chunk6); + __m128i layer2_chunk5 = _mm_unpackhi_epi8(layer1_chunk2, layer1_chunk6); + __m128i layer2_chunk6 = _mm_unpacklo_epi8(layer1_chunk3, layer1_chunk7); + __m128i layer2_chunk7 = _mm_unpackhi_epi8(layer1_chunk3, layer1_chunk7); + + __m128i layer3_chunk0 = _mm_unpacklo_epi8(layer2_chunk0, layer2_chunk4); + __m128i layer3_chunk1 = _mm_unpackhi_epi8(layer2_chunk0, layer2_chunk4); + __m128i layer3_chunk2 = _mm_unpacklo_epi8(layer2_chunk1, layer2_chunk5); + __m128i layer3_chunk3 = _mm_unpackhi_epi8(layer2_chunk1, layer2_chunk5); + __m128i layer3_chunk4 = _mm_unpacklo_epi8(layer2_chunk2, layer2_chunk6); + __m128i layer3_chunk5 = _mm_unpackhi_epi8(layer2_chunk2, layer2_chunk6); + __m128i layer3_chunk6 = _mm_unpacklo_epi8(layer2_chunk3, layer2_chunk7); + __m128i layer3_chunk7 = _mm_unpackhi_epi8(layer2_chunk3, layer2_chunk7); + + __m128i layer4_chunk0 = _mm_unpacklo_epi8(layer3_chunk0, layer3_chunk4); + __m128i layer4_chunk1 = _mm_unpackhi_epi8(layer3_chunk0, layer3_chunk4); + __m128i layer4_chunk2 = _mm_unpacklo_epi8(layer3_chunk1, layer3_chunk5); + __m128i layer4_chunk3 = _mm_unpackhi_epi8(layer3_chunk1, layer3_chunk5); + __m128i layer4_chunk4 = _mm_unpacklo_epi8(layer3_chunk2, layer3_chunk6); + __m128i layer4_chunk5 = _mm_unpackhi_epi8(layer3_chunk2, layer3_chunk6); + __m128i layer4_chunk6 = _mm_unpacklo_epi8(layer3_chunk3, layer3_chunk7); + __m128i layer4_chunk7 = _mm_unpackhi_epi8(layer3_chunk3, layer3_chunk7); + + v_r0 = _mm_unpacklo_epi8(layer4_chunk0, layer4_chunk4); + v_r1 = _mm_unpackhi_epi8(layer4_chunk0, layer4_chunk4); + v_g0 = _mm_unpacklo_epi8(layer4_chunk1, layer4_chunk5); + v_g1 = _mm_unpackhi_epi8(layer4_chunk1, layer4_chunk5); + v_b0 = _mm_unpacklo_epi8(layer4_chunk2, layer4_chunk6); + v_b1 = _mm_unpackhi_epi8(layer4_chunk2, layer4_chunk6); + v_a0 = _mm_unpacklo_epi8(layer4_chunk3, layer4_chunk7); + v_a1 = _mm_unpackhi_epi8(layer4_chunk3, layer4_chunk7); +} + +inline void _mm_interleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1) +{ + __m128i v_mask = _mm_set1_epi16(0x00ff); + + __m128i layer4_chunk0 = _mm_packus_epi16(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); + __m128i layer4_chunk2 = _mm_packus_epi16(_mm_srli_epi16(v_r0, 8), _mm_srli_epi16(v_r1, 8)); + __m128i layer4_chunk1 = _mm_packus_epi16(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); + __m128i layer4_chunk3 = _mm_packus_epi16(_mm_srli_epi16(v_g0, 8), _mm_srli_epi16(v_g1, 8)); + + __m128i layer3_chunk0 = _mm_packus_epi16(_mm_and_si128(layer4_chunk0, v_mask), _mm_and_si128(layer4_chunk1, v_mask)); + __m128i layer3_chunk2 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk0, 8), _mm_srli_epi16(layer4_chunk1, 8)); + __m128i layer3_chunk1 = _mm_packus_epi16(_mm_and_si128(layer4_chunk2, v_mask), _mm_and_si128(layer4_chunk3, v_mask)); + __m128i layer3_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk2, 8), _mm_srli_epi16(layer4_chunk3, 8)); + + __m128i layer2_chunk0 = _mm_packus_epi16(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); + __m128i layer2_chunk2 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk0, 8), _mm_srli_epi16(layer3_chunk1, 8)); + __m128i layer2_chunk1 = _mm_packus_epi16(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); + __m128i layer2_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk2, 8), _mm_srli_epi16(layer3_chunk3, 8)); + + __m128i layer1_chunk0 = _mm_packus_epi16(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); + __m128i layer1_chunk2 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk0, 8), _mm_srli_epi16(layer2_chunk1, 8)); + __m128i layer1_chunk1 = _mm_packus_epi16(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); + __m128i layer1_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk2, 8), _mm_srli_epi16(layer2_chunk3, 8)); + + v_r0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); + v_g0 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk0, 8), _mm_srli_epi16(layer1_chunk1, 8)); + v_r1 = _mm_packus_epi16(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); + v_g1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk2, 8), _mm_srli_epi16(layer1_chunk3, 8)); +} + +inline void _mm_interleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, + __m128i & v_g1, __m128i & v_b0, __m128i & v_b1) +{ + __m128i v_mask = _mm_set1_epi16(0x00ff); + + __m128i layer4_chunk0 = _mm_packus_epi16(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); + __m128i layer4_chunk3 = _mm_packus_epi16(_mm_srli_epi16(v_r0, 8), _mm_srli_epi16(v_r1, 8)); + __m128i layer4_chunk1 = _mm_packus_epi16(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); + __m128i layer4_chunk4 = _mm_packus_epi16(_mm_srli_epi16(v_g0, 8), _mm_srli_epi16(v_g1, 8)); + __m128i layer4_chunk2 = _mm_packus_epi16(_mm_and_si128(v_b0, v_mask), _mm_and_si128(v_b1, v_mask)); + __m128i layer4_chunk5 = _mm_packus_epi16(_mm_srli_epi16(v_b0, 8), _mm_srli_epi16(v_b1, 8)); + + __m128i layer3_chunk0 = _mm_packus_epi16(_mm_and_si128(layer4_chunk0, v_mask), _mm_and_si128(layer4_chunk1, v_mask)); + __m128i layer3_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk0, 8), _mm_srli_epi16(layer4_chunk1, 8)); + __m128i layer3_chunk1 = _mm_packus_epi16(_mm_and_si128(layer4_chunk2, v_mask), _mm_and_si128(layer4_chunk3, v_mask)); + __m128i layer3_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk2, 8), _mm_srli_epi16(layer4_chunk3, 8)); + __m128i layer3_chunk2 = _mm_packus_epi16(_mm_and_si128(layer4_chunk4, v_mask), _mm_and_si128(layer4_chunk5, v_mask)); + __m128i layer3_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk4, 8), _mm_srli_epi16(layer4_chunk5, 8)); + + __m128i layer2_chunk0 = _mm_packus_epi16(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); + __m128i layer2_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk0, 8), _mm_srli_epi16(layer3_chunk1, 8)); + __m128i layer2_chunk1 = _mm_packus_epi16(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); + __m128i layer2_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk2, 8), _mm_srli_epi16(layer3_chunk3, 8)); + __m128i layer2_chunk2 = _mm_packus_epi16(_mm_and_si128(layer3_chunk4, v_mask), _mm_and_si128(layer3_chunk5, v_mask)); + __m128i layer2_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk4, 8), _mm_srli_epi16(layer3_chunk5, 8)); + + __m128i layer1_chunk0 = _mm_packus_epi16(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); + __m128i layer1_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk0, 8), _mm_srli_epi16(layer2_chunk1, 8)); + __m128i layer1_chunk1 = _mm_packus_epi16(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); + __m128i layer1_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk2, 8), _mm_srli_epi16(layer2_chunk3, 8)); + __m128i layer1_chunk2 = _mm_packus_epi16(_mm_and_si128(layer2_chunk4, v_mask), _mm_and_si128(layer2_chunk5, v_mask)); + __m128i layer1_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk4, 8), _mm_srli_epi16(layer2_chunk5, 8)); + + v_r0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); + v_g1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk0, 8), _mm_srli_epi16(layer1_chunk1, 8)); + v_r1 = _mm_packus_epi16(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); + v_b0 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk2, 8), _mm_srli_epi16(layer1_chunk3, 8)); + v_g0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk4, v_mask), _mm_and_si128(layer1_chunk5, v_mask)); + v_b1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk4, 8), _mm_srli_epi16(layer1_chunk5, 8)); +} + +inline void _mm_interleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1, + __m128i & v_b0, __m128i & v_b1, __m128i & v_a0, __m128i & v_a1) +{ + __m128i v_mask = _mm_set1_epi16(0x00ff); + + __m128i layer4_chunk0 = _mm_packus_epi16(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); + __m128i layer4_chunk4 = _mm_packus_epi16(_mm_srli_epi16(v_r0, 8), _mm_srli_epi16(v_r1, 8)); + __m128i layer4_chunk1 = _mm_packus_epi16(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); + __m128i layer4_chunk5 = _mm_packus_epi16(_mm_srli_epi16(v_g0, 8), _mm_srli_epi16(v_g1, 8)); + __m128i layer4_chunk2 = _mm_packus_epi16(_mm_and_si128(v_b0, v_mask), _mm_and_si128(v_b1, v_mask)); + __m128i layer4_chunk6 = _mm_packus_epi16(_mm_srli_epi16(v_b0, 8), _mm_srli_epi16(v_b1, 8)); + __m128i layer4_chunk3 = _mm_packus_epi16(_mm_and_si128(v_a0, v_mask), _mm_and_si128(v_a1, v_mask)); + __m128i layer4_chunk7 = _mm_packus_epi16(_mm_srli_epi16(v_a0, 8), _mm_srli_epi16(v_a1, 8)); + + __m128i layer3_chunk0 = _mm_packus_epi16(_mm_and_si128(layer4_chunk0, v_mask), _mm_and_si128(layer4_chunk1, v_mask)); + __m128i layer3_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk0, 8), _mm_srli_epi16(layer4_chunk1, 8)); + __m128i layer3_chunk1 = _mm_packus_epi16(_mm_and_si128(layer4_chunk2, v_mask), _mm_and_si128(layer4_chunk3, v_mask)); + __m128i layer3_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk2, 8), _mm_srli_epi16(layer4_chunk3, 8)); + __m128i layer3_chunk2 = _mm_packus_epi16(_mm_and_si128(layer4_chunk4, v_mask), _mm_and_si128(layer4_chunk5, v_mask)); + __m128i layer3_chunk6 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk4, 8), _mm_srli_epi16(layer4_chunk5, 8)); + __m128i layer3_chunk3 = _mm_packus_epi16(_mm_and_si128(layer4_chunk6, v_mask), _mm_and_si128(layer4_chunk7, v_mask)); + __m128i layer3_chunk7 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk6, 8), _mm_srli_epi16(layer4_chunk7, 8)); + + __m128i layer2_chunk0 = _mm_packus_epi16(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); + __m128i layer2_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk0, 8), _mm_srli_epi16(layer3_chunk1, 8)); + __m128i layer2_chunk1 = _mm_packus_epi16(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); + __m128i layer2_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk2, 8), _mm_srli_epi16(layer3_chunk3, 8)); + __m128i layer2_chunk2 = _mm_packus_epi16(_mm_and_si128(layer3_chunk4, v_mask), _mm_and_si128(layer3_chunk5, v_mask)); + __m128i layer2_chunk6 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk4, 8), _mm_srli_epi16(layer3_chunk5, 8)); + __m128i layer2_chunk3 = _mm_packus_epi16(_mm_and_si128(layer3_chunk6, v_mask), _mm_and_si128(layer3_chunk7, v_mask)); + __m128i layer2_chunk7 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk6, 8), _mm_srli_epi16(layer3_chunk7, 8)); + + __m128i layer1_chunk0 = _mm_packus_epi16(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); + __m128i layer1_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk0, 8), _mm_srli_epi16(layer2_chunk1, 8)); + __m128i layer1_chunk1 = _mm_packus_epi16(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); + __m128i layer1_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk2, 8), _mm_srli_epi16(layer2_chunk3, 8)); + __m128i layer1_chunk2 = _mm_packus_epi16(_mm_and_si128(layer2_chunk4, v_mask), _mm_and_si128(layer2_chunk5, v_mask)); + __m128i layer1_chunk6 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk4, 8), _mm_srli_epi16(layer2_chunk5, 8)); + __m128i layer1_chunk3 = _mm_packus_epi16(_mm_and_si128(layer2_chunk6, v_mask), _mm_and_si128(layer2_chunk7, v_mask)); + __m128i layer1_chunk7 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk6, 8), _mm_srli_epi16(layer2_chunk7, 8)); + + v_r0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); + v_b0 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk0, 8), _mm_srli_epi16(layer1_chunk1, 8)); + v_r1 = _mm_packus_epi16(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); + v_b1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk2, 8), _mm_srli_epi16(layer1_chunk3, 8)); + v_g0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk4, v_mask), _mm_and_si128(layer1_chunk5, v_mask)); + v_a0 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk4, 8), _mm_srli_epi16(layer1_chunk5, 8)); + v_g1 = _mm_packus_epi16(_mm_and_si128(layer1_chunk6, v_mask), _mm_and_si128(layer1_chunk7, v_mask)); + v_a1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk6, 8), _mm_srli_epi16(layer1_chunk7, 8)); +} + +inline void _mm_deinterleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1) +{ + __m128i layer1_chunk0 = _mm_unpacklo_epi16(v_r0, v_g0); + __m128i layer1_chunk1 = _mm_unpackhi_epi16(v_r0, v_g0); + __m128i layer1_chunk2 = _mm_unpacklo_epi16(v_r1, v_g1); + __m128i layer1_chunk3 = _mm_unpackhi_epi16(v_r1, v_g1); + + __m128i layer2_chunk0 = _mm_unpacklo_epi16(layer1_chunk0, layer1_chunk2); + __m128i layer2_chunk1 = _mm_unpackhi_epi16(layer1_chunk0, layer1_chunk2); + __m128i layer2_chunk2 = _mm_unpacklo_epi16(layer1_chunk1, layer1_chunk3); + __m128i layer2_chunk3 = _mm_unpackhi_epi16(layer1_chunk1, layer1_chunk3); + + __m128i layer3_chunk0 = _mm_unpacklo_epi16(layer2_chunk0, layer2_chunk2); + __m128i layer3_chunk1 = _mm_unpackhi_epi16(layer2_chunk0, layer2_chunk2); + __m128i layer3_chunk2 = _mm_unpacklo_epi16(layer2_chunk1, layer2_chunk3); + __m128i layer3_chunk3 = _mm_unpackhi_epi16(layer2_chunk1, layer2_chunk3); + + v_r0 = _mm_unpacklo_epi16(layer3_chunk0, layer3_chunk2); + v_r1 = _mm_unpackhi_epi16(layer3_chunk0, layer3_chunk2); + v_g0 = _mm_unpacklo_epi16(layer3_chunk1, layer3_chunk3); + v_g1 = _mm_unpackhi_epi16(layer3_chunk1, layer3_chunk3); +} + +inline void _mm_deinterleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, + __m128i & v_g1, __m128i & v_b0, __m128i & v_b1) +{ + __m128i layer1_chunk0 = _mm_unpacklo_epi16(v_r0, v_g1); + __m128i layer1_chunk1 = _mm_unpackhi_epi16(v_r0, v_g1); + __m128i layer1_chunk2 = _mm_unpacklo_epi16(v_r1, v_b0); + __m128i layer1_chunk3 = _mm_unpackhi_epi16(v_r1, v_b0); + __m128i layer1_chunk4 = _mm_unpacklo_epi16(v_g0, v_b1); + __m128i layer1_chunk5 = _mm_unpackhi_epi16(v_g0, v_b1); + + __m128i layer2_chunk0 = _mm_unpacklo_epi16(layer1_chunk0, layer1_chunk3); + __m128i layer2_chunk1 = _mm_unpackhi_epi16(layer1_chunk0, layer1_chunk3); + __m128i layer2_chunk2 = _mm_unpacklo_epi16(layer1_chunk1, layer1_chunk4); + __m128i layer2_chunk3 = _mm_unpackhi_epi16(layer1_chunk1, layer1_chunk4); + __m128i layer2_chunk4 = _mm_unpacklo_epi16(layer1_chunk2, layer1_chunk5); + __m128i layer2_chunk5 = _mm_unpackhi_epi16(layer1_chunk2, layer1_chunk5); + + __m128i layer3_chunk0 = _mm_unpacklo_epi16(layer2_chunk0, layer2_chunk3); + __m128i layer3_chunk1 = _mm_unpackhi_epi16(layer2_chunk0, layer2_chunk3); + __m128i layer3_chunk2 = _mm_unpacklo_epi16(layer2_chunk1, layer2_chunk4); + __m128i layer3_chunk3 = _mm_unpackhi_epi16(layer2_chunk1, layer2_chunk4); + __m128i layer3_chunk4 = _mm_unpacklo_epi16(layer2_chunk2, layer2_chunk5); + __m128i layer3_chunk5 = _mm_unpackhi_epi16(layer2_chunk2, layer2_chunk5); + + v_r0 = _mm_unpacklo_epi16(layer3_chunk0, layer3_chunk3); + v_r1 = _mm_unpackhi_epi16(layer3_chunk0, layer3_chunk3); + v_g0 = _mm_unpacklo_epi16(layer3_chunk1, layer3_chunk4); + v_g1 = _mm_unpackhi_epi16(layer3_chunk1, layer3_chunk4); + v_b0 = _mm_unpacklo_epi16(layer3_chunk2, layer3_chunk5); + v_b1 = _mm_unpackhi_epi16(layer3_chunk2, layer3_chunk5); +} + +inline void _mm_deinterleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1, + __m128i & v_b0, __m128i & v_b1, __m128i & v_a0, __m128i & v_a1) +{ + __m128i layer1_chunk0 = _mm_unpacklo_epi16(v_r0, v_b0); + __m128i layer1_chunk1 = _mm_unpackhi_epi16(v_r0, v_b0); + __m128i layer1_chunk2 = _mm_unpacklo_epi16(v_r1, v_b1); + __m128i layer1_chunk3 = _mm_unpackhi_epi16(v_r1, v_b1); + __m128i layer1_chunk4 = _mm_unpacklo_epi16(v_g0, v_a0); + __m128i layer1_chunk5 = _mm_unpackhi_epi16(v_g0, v_a0); + __m128i layer1_chunk6 = _mm_unpacklo_epi16(v_g1, v_a1); + __m128i layer1_chunk7 = _mm_unpackhi_epi16(v_g1, v_a1); + + __m128i layer2_chunk0 = _mm_unpacklo_epi16(layer1_chunk0, layer1_chunk4); + __m128i layer2_chunk1 = _mm_unpackhi_epi16(layer1_chunk0, layer1_chunk4); + __m128i layer2_chunk2 = _mm_unpacklo_epi16(layer1_chunk1, layer1_chunk5); + __m128i layer2_chunk3 = _mm_unpackhi_epi16(layer1_chunk1, layer1_chunk5); + __m128i layer2_chunk4 = _mm_unpacklo_epi16(layer1_chunk2, layer1_chunk6); + __m128i layer2_chunk5 = _mm_unpackhi_epi16(layer1_chunk2, layer1_chunk6); + __m128i layer2_chunk6 = _mm_unpacklo_epi16(layer1_chunk3, layer1_chunk7); + __m128i layer2_chunk7 = _mm_unpackhi_epi16(layer1_chunk3, layer1_chunk7); + + __m128i layer3_chunk0 = _mm_unpacklo_epi16(layer2_chunk0, layer2_chunk4); + __m128i layer3_chunk1 = _mm_unpackhi_epi16(layer2_chunk0, layer2_chunk4); + __m128i layer3_chunk2 = _mm_unpacklo_epi16(layer2_chunk1, layer2_chunk5); + __m128i layer3_chunk3 = _mm_unpackhi_epi16(layer2_chunk1, layer2_chunk5); + __m128i layer3_chunk4 = _mm_unpacklo_epi16(layer2_chunk2, layer2_chunk6); + __m128i layer3_chunk5 = _mm_unpackhi_epi16(layer2_chunk2, layer2_chunk6); + __m128i layer3_chunk6 = _mm_unpacklo_epi16(layer2_chunk3, layer2_chunk7); + __m128i layer3_chunk7 = _mm_unpackhi_epi16(layer2_chunk3, layer2_chunk7); + + v_r0 = _mm_unpacklo_epi16(layer3_chunk0, layer3_chunk4); + v_r1 = _mm_unpackhi_epi16(layer3_chunk0, layer3_chunk4); + v_g0 = _mm_unpacklo_epi16(layer3_chunk1, layer3_chunk5); + v_g1 = _mm_unpackhi_epi16(layer3_chunk1, layer3_chunk5); + v_b0 = _mm_unpacklo_epi16(layer3_chunk2, layer3_chunk6); + v_b1 = _mm_unpackhi_epi16(layer3_chunk2, layer3_chunk6); + v_a0 = _mm_unpacklo_epi16(layer3_chunk3, layer3_chunk7); + v_a1 = _mm_unpackhi_epi16(layer3_chunk3, layer3_chunk7); +} + +#if CV_SSE4_1 + +inline void _mm_interleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1) +{ + __m128i v_mask = _mm_set1_epi32(0x0000ffff); + + __m128i layer3_chunk0 = _mm_packus_epi32(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); + __m128i layer3_chunk2 = _mm_packus_epi32(_mm_srli_epi32(v_r0, 16), _mm_srli_epi32(v_r1, 16)); + __m128i layer3_chunk1 = _mm_packus_epi32(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); + __m128i layer3_chunk3 = _mm_packus_epi32(_mm_srli_epi32(v_g0, 16), _mm_srli_epi32(v_g1, 16)); + + __m128i layer2_chunk0 = _mm_packus_epi32(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); + __m128i layer2_chunk2 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk0, 16), _mm_srli_epi32(layer3_chunk1, 16)); + __m128i layer2_chunk1 = _mm_packus_epi32(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); + __m128i layer2_chunk3 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk2, 16), _mm_srli_epi32(layer3_chunk3, 16)); + + __m128i layer1_chunk0 = _mm_packus_epi32(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); + __m128i layer1_chunk2 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk0, 16), _mm_srli_epi32(layer2_chunk1, 16)); + __m128i layer1_chunk1 = _mm_packus_epi32(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); + __m128i layer1_chunk3 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk2, 16), _mm_srli_epi32(layer2_chunk3, 16)); + + v_r0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); + v_g0 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk0, 16), _mm_srli_epi32(layer1_chunk1, 16)); + v_r1 = _mm_packus_epi32(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); + v_g1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk2, 16), _mm_srli_epi32(layer1_chunk3, 16)); +} + +inline void _mm_interleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, + __m128i & v_g1, __m128i & v_b0, __m128i & v_b1) +{ + __m128i v_mask = _mm_set1_epi32(0x0000ffff); + + __m128i layer3_chunk0 = _mm_packus_epi32(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); + __m128i layer3_chunk3 = _mm_packus_epi32(_mm_srli_epi32(v_r0, 16), _mm_srli_epi32(v_r1, 16)); + __m128i layer3_chunk1 = _mm_packus_epi32(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); + __m128i layer3_chunk4 = _mm_packus_epi32(_mm_srli_epi32(v_g0, 16), _mm_srli_epi32(v_g1, 16)); + __m128i layer3_chunk2 = _mm_packus_epi32(_mm_and_si128(v_b0, v_mask), _mm_and_si128(v_b1, v_mask)); + __m128i layer3_chunk5 = _mm_packus_epi32(_mm_srli_epi32(v_b0, 16), _mm_srli_epi32(v_b1, 16)); + + __m128i layer2_chunk0 = _mm_packus_epi32(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); + __m128i layer2_chunk3 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk0, 16), _mm_srli_epi32(layer3_chunk1, 16)); + __m128i layer2_chunk1 = _mm_packus_epi32(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); + __m128i layer2_chunk4 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk2, 16), _mm_srli_epi32(layer3_chunk3, 16)); + __m128i layer2_chunk2 = _mm_packus_epi32(_mm_and_si128(layer3_chunk4, v_mask), _mm_and_si128(layer3_chunk5, v_mask)); + __m128i layer2_chunk5 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk4, 16), _mm_srli_epi32(layer3_chunk5, 16)); + + __m128i layer1_chunk0 = _mm_packus_epi32(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); + __m128i layer1_chunk3 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk0, 16), _mm_srli_epi32(layer2_chunk1, 16)); + __m128i layer1_chunk1 = _mm_packus_epi32(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); + __m128i layer1_chunk4 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk2, 16), _mm_srli_epi32(layer2_chunk3, 16)); + __m128i layer1_chunk2 = _mm_packus_epi32(_mm_and_si128(layer2_chunk4, v_mask), _mm_and_si128(layer2_chunk5, v_mask)); + __m128i layer1_chunk5 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk4, 16), _mm_srli_epi32(layer2_chunk5, 16)); + + v_r0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); + v_g1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk0, 16), _mm_srli_epi32(layer1_chunk1, 16)); + v_r1 = _mm_packus_epi32(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); + v_b0 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk2, 16), _mm_srli_epi32(layer1_chunk3, 16)); + v_g0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk4, v_mask), _mm_and_si128(layer1_chunk5, v_mask)); + v_b1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk4, 16), _mm_srli_epi32(layer1_chunk5, 16)); +} + +inline void _mm_interleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1, + __m128i & v_b0, __m128i & v_b1, __m128i & v_a0, __m128i & v_a1) +{ + __m128i v_mask = _mm_set1_epi32(0x0000ffff); + + __m128i layer3_chunk0 = _mm_packus_epi32(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); + __m128i layer3_chunk4 = _mm_packus_epi32(_mm_srli_epi32(v_r0, 16), _mm_srli_epi32(v_r1, 16)); + __m128i layer3_chunk1 = _mm_packus_epi32(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); + __m128i layer3_chunk5 = _mm_packus_epi32(_mm_srli_epi32(v_g0, 16), _mm_srli_epi32(v_g1, 16)); + __m128i layer3_chunk2 = _mm_packus_epi32(_mm_and_si128(v_b0, v_mask), _mm_and_si128(v_b1, v_mask)); + __m128i layer3_chunk6 = _mm_packus_epi32(_mm_srli_epi32(v_b0, 16), _mm_srli_epi32(v_b1, 16)); + __m128i layer3_chunk3 = _mm_packus_epi32(_mm_and_si128(v_a0, v_mask), _mm_and_si128(v_a1, v_mask)); + __m128i layer3_chunk7 = _mm_packus_epi32(_mm_srli_epi32(v_a0, 16), _mm_srli_epi32(v_a1, 16)); + + __m128i layer2_chunk0 = _mm_packus_epi32(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); + __m128i layer2_chunk4 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk0, 16), _mm_srli_epi32(layer3_chunk1, 16)); + __m128i layer2_chunk1 = _mm_packus_epi32(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); + __m128i layer2_chunk5 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk2, 16), _mm_srli_epi32(layer3_chunk3, 16)); + __m128i layer2_chunk2 = _mm_packus_epi32(_mm_and_si128(layer3_chunk4, v_mask), _mm_and_si128(layer3_chunk5, v_mask)); + __m128i layer2_chunk6 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk4, 16), _mm_srli_epi32(layer3_chunk5, 16)); + __m128i layer2_chunk3 = _mm_packus_epi32(_mm_and_si128(layer3_chunk6, v_mask), _mm_and_si128(layer3_chunk7, v_mask)); + __m128i layer2_chunk7 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk6, 16), _mm_srli_epi32(layer3_chunk7, 16)); + + __m128i layer1_chunk0 = _mm_packus_epi32(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); + __m128i layer1_chunk4 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk0, 16), _mm_srli_epi32(layer2_chunk1, 16)); + __m128i layer1_chunk1 = _mm_packus_epi32(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); + __m128i layer1_chunk5 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk2, 16), _mm_srli_epi32(layer2_chunk3, 16)); + __m128i layer1_chunk2 = _mm_packus_epi32(_mm_and_si128(layer2_chunk4, v_mask), _mm_and_si128(layer2_chunk5, v_mask)); + __m128i layer1_chunk6 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk4, 16), _mm_srli_epi32(layer2_chunk5, 16)); + __m128i layer1_chunk3 = _mm_packus_epi32(_mm_and_si128(layer2_chunk6, v_mask), _mm_and_si128(layer2_chunk7, v_mask)); + __m128i layer1_chunk7 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk6, 16), _mm_srli_epi32(layer2_chunk7, 16)); + + v_r0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); + v_b0 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk0, 16), _mm_srli_epi32(layer1_chunk1, 16)); + v_r1 = _mm_packus_epi32(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); + v_b1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk2, 16), _mm_srli_epi32(layer1_chunk3, 16)); + v_g0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk4, v_mask), _mm_and_si128(layer1_chunk5, v_mask)); + v_a0 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk4, 16), _mm_srli_epi32(layer1_chunk5, 16)); + v_g1 = _mm_packus_epi32(_mm_and_si128(layer1_chunk6, v_mask), _mm_and_si128(layer1_chunk7, v_mask)); + v_a1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk6, 16), _mm_srli_epi32(layer1_chunk7, 16)); +} + +#endif // CV_SSE4_1 + +inline void _mm_deinterleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, __m128 & v_g1) +{ + __m128 layer1_chunk0 = _mm_unpacklo_ps(v_r0, v_g0); + __m128 layer1_chunk1 = _mm_unpackhi_ps(v_r0, v_g0); + __m128 layer1_chunk2 = _mm_unpacklo_ps(v_r1, v_g1); + __m128 layer1_chunk3 = _mm_unpackhi_ps(v_r1, v_g1); + + __m128 layer2_chunk0 = _mm_unpacklo_ps(layer1_chunk0, layer1_chunk2); + __m128 layer2_chunk1 = _mm_unpackhi_ps(layer1_chunk0, layer1_chunk2); + __m128 layer2_chunk2 = _mm_unpacklo_ps(layer1_chunk1, layer1_chunk3); + __m128 layer2_chunk3 = _mm_unpackhi_ps(layer1_chunk1, layer1_chunk3); + + v_r0 = _mm_unpacklo_ps(layer2_chunk0, layer2_chunk2); + v_r1 = _mm_unpackhi_ps(layer2_chunk0, layer2_chunk2); + v_g0 = _mm_unpacklo_ps(layer2_chunk1, layer2_chunk3); + v_g1 = _mm_unpackhi_ps(layer2_chunk1, layer2_chunk3); +} + +inline void _mm_deinterleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, + __m128 & v_g1, __m128 & v_b0, __m128 & v_b1) +{ + __m128 layer1_chunk0 = _mm_unpacklo_ps(v_r0, v_g1); + __m128 layer1_chunk1 = _mm_unpackhi_ps(v_r0, v_g1); + __m128 layer1_chunk2 = _mm_unpacklo_ps(v_r1, v_b0); + __m128 layer1_chunk3 = _mm_unpackhi_ps(v_r1, v_b0); + __m128 layer1_chunk4 = _mm_unpacklo_ps(v_g0, v_b1); + __m128 layer1_chunk5 = _mm_unpackhi_ps(v_g0, v_b1); + + __m128 layer2_chunk0 = _mm_unpacklo_ps(layer1_chunk0, layer1_chunk3); + __m128 layer2_chunk1 = _mm_unpackhi_ps(layer1_chunk0, layer1_chunk3); + __m128 layer2_chunk2 = _mm_unpacklo_ps(layer1_chunk1, layer1_chunk4); + __m128 layer2_chunk3 = _mm_unpackhi_ps(layer1_chunk1, layer1_chunk4); + __m128 layer2_chunk4 = _mm_unpacklo_ps(layer1_chunk2, layer1_chunk5); + __m128 layer2_chunk5 = _mm_unpackhi_ps(layer1_chunk2, layer1_chunk5); + + v_r0 = _mm_unpacklo_ps(layer2_chunk0, layer2_chunk3); + v_r1 = _mm_unpackhi_ps(layer2_chunk0, layer2_chunk3); + v_g0 = _mm_unpacklo_ps(layer2_chunk1, layer2_chunk4); + v_g1 = _mm_unpackhi_ps(layer2_chunk1, layer2_chunk4); + v_b0 = _mm_unpacklo_ps(layer2_chunk2, layer2_chunk5); + v_b1 = _mm_unpackhi_ps(layer2_chunk2, layer2_chunk5); +} + +inline void _mm_deinterleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, __m128 & v_g1, + __m128 & v_b0, __m128 & v_b1, __m128 & v_a0, __m128 & v_a1) +{ + __m128 layer1_chunk0 = _mm_unpacklo_ps(v_r0, v_b0); + __m128 layer1_chunk1 = _mm_unpackhi_ps(v_r0, v_b0); + __m128 layer1_chunk2 = _mm_unpacklo_ps(v_r1, v_b1); + __m128 layer1_chunk3 = _mm_unpackhi_ps(v_r1, v_b1); + __m128 layer1_chunk4 = _mm_unpacklo_ps(v_g0, v_a0); + __m128 layer1_chunk5 = _mm_unpackhi_ps(v_g0, v_a0); + __m128 layer1_chunk6 = _mm_unpacklo_ps(v_g1, v_a1); + __m128 layer1_chunk7 = _mm_unpackhi_ps(v_g1, v_a1); + + __m128 layer2_chunk0 = _mm_unpacklo_ps(layer1_chunk0, layer1_chunk4); + __m128 layer2_chunk1 = _mm_unpackhi_ps(layer1_chunk0, layer1_chunk4); + __m128 layer2_chunk2 = _mm_unpacklo_ps(layer1_chunk1, layer1_chunk5); + __m128 layer2_chunk3 = _mm_unpackhi_ps(layer1_chunk1, layer1_chunk5); + __m128 layer2_chunk4 = _mm_unpacklo_ps(layer1_chunk2, layer1_chunk6); + __m128 layer2_chunk5 = _mm_unpackhi_ps(layer1_chunk2, layer1_chunk6); + __m128 layer2_chunk6 = _mm_unpacklo_ps(layer1_chunk3, layer1_chunk7); + __m128 layer2_chunk7 = _mm_unpackhi_ps(layer1_chunk3, layer1_chunk7); + + v_r0 = _mm_unpacklo_ps(layer2_chunk0, layer2_chunk4); + v_r1 = _mm_unpackhi_ps(layer2_chunk0, layer2_chunk4); + v_g0 = _mm_unpacklo_ps(layer2_chunk1, layer2_chunk5); + v_g1 = _mm_unpackhi_ps(layer2_chunk1, layer2_chunk5); + v_b0 = _mm_unpacklo_ps(layer2_chunk2, layer2_chunk6); + v_b1 = _mm_unpackhi_ps(layer2_chunk2, layer2_chunk6); + v_a0 = _mm_unpacklo_ps(layer2_chunk3, layer2_chunk7); + v_a1 = _mm_unpackhi_ps(layer2_chunk3, layer2_chunk7); +} + +inline void _mm_interleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, __m128 & v_g1) +{ + enum { mask_lo = _MM_SHUFFLE(2, 0, 2, 0), mask_hi = _MM_SHUFFLE(3, 1, 3, 1) }; + + __m128 layer2_chunk0 = _mm_shuffle_ps(v_r0, v_r1, mask_lo); + __m128 layer2_chunk2 = _mm_shuffle_ps(v_r0, v_r1, mask_hi); + __m128 layer2_chunk1 = _mm_shuffle_ps(v_g0, v_g1, mask_lo); + __m128 layer2_chunk3 = _mm_shuffle_ps(v_g0, v_g1, mask_hi); + + __m128 layer1_chunk0 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_lo); + __m128 layer1_chunk2 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_hi); + __m128 layer1_chunk1 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_lo); + __m128 layer1_chunk3 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_hi); + + v_r0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_lo); + v_g0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_hi); + v_r1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_lo); + v_g1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_hi); +} + +inline void _mm_interleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, + __m128 & v_g1, __m128 & v_b0, __m128 & v_b1) +{ + enum { mask_lo = _MM_SHUFFLE(2, 0, 2, 0), mask_hi = _MM_SHUFFLE(3, 1, 3, 1) }; + + __m128 layer2_chunk0 = _mm_shuffle_ps(v_r0, v_r1, mask_lo); + __m128 layer2_chunk3 = _mm_shuffle_ps(v_r0, v_r1, mask_hi); + __m128 layer2_chunk1 = _mm_shuffle_ps(v_g0, v_g1, mask_lo); + __m128 layer2_chunk4 = _mm_shuffle_ps(v_g0, v_g1, mask_hi); + __m128 layer2_chunk2 = _mm_shuffle_ps(v_b0, v_b1, mask_lo); + __m128 layer2_chunk5 = _mm_shuffle_ps(v_b0, v_b1, mask_hi); + + __m128 layer1_chunk0 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_lo); + __m128 layer1_chunk3 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_hi); + __m128 layer1_chunk1 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_lo); + __m128 layer1_chunk4 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_hi); + __m128 layer1_chunk2 = _mm_shuffle_ps(layer2_chunk4, layer2_chunk5, mask_lo); + __m128 layer1_chunk5 = _mm_shuffle_ps(layer2_chunk4, layer2_chunk5, mask_hi); + + v_r0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_lo); + v_g1 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_hi); + v_r1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_lo); + v_b0 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_hi); + v_g0 = _mm_shuffle_ps(layer1_chunk4, layer1_chunk5, mask_lo); + v_b1 = _mm_shuffle_ps(layer1_chunk4, layer1_chunk5, mask_hi); +} + +inline void _mm_interleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, __m128 & v_g1, + __m128 & v_b0, __m128 & v_b1, __m128 & v_a0, __m128 & v_a1) +{ + enum { mask_lo = _MM_SHUFFLE(2, 0, 2, 0), mask_hi = _MM_SHUFFLE(3, 1, 3, 1) }; + + __m128 layer2_chunk0 = _mm_shuffle_ps(v_r0, v_r1, mask_lo); + __m128 layer2_chunk4 = _mm_shuffle_ps(v_r0, v_r1, mask_hi); + __m128 layer2_chunk1 = _mm_shuffle_ps(v_g0, v_g1, mask_lo); + __m128 layer2_chunk5 = _mm_shuffle_ps(v_g0, v_g1, mask_hi); + __m128 layer2_chunk2 = _mm_shuffle_ps(v_b0, v_b1, mask_lo); + __m128 layer2_chunk6 = _mm_shuffle_ps(v_b0, v_b1, mask_hi); + __m128 layer2_chunk3 = _mm_shuffle_ps(v_a0, v_a1, mask_lo); + __m128 layer2_chunk7 = _mm_shuffle_ps(v_a0, v_a1, mask_hi); + + __m128 layer1_chunk0 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_lo); + __m128 layer1_chunk4 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_hi); + __m128 layer1_chunk1 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_lo); + __m128 layer1_chunk5 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_hi); + __m128 layer1_chunk2 = _mm_shuffle_ps(layer2_chunk4, layer2_chunk5, mask_lo); + __m128 layer1_chunk6 = _mm_shuffle_ps(layer2_chunk4, layer2_chunk5, mask_hi); + __m128 layer1_chunk3 = _mm_shuffle_ps(layer2_chunk6, layer2_chunk7, mask_lo); + __m128 layer1_chunk7 = _mm_shuffle_ps(layer2_chunk6, layer2_chunk7, mask_hi); + + v_r0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_lo); + v_b0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_hi); + v_r1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_lo); + v_b1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_hi); + v_g0 = _mm_shuffle_ps(layer1_chunk4, layer1_chunk5, mask_lo); + v_a0 = _mm_shuffle_ps(layer1_chunk4, layer1_chunk5, mask_hi); + v_g1 = _mm_shuffle_ps(layer1_chunk6, layer1_chunk7, mask_lo); + v_a1 = _mm_shuffle_ps(layer1_chunk6, layer1_chunk7, mask_hi); +} + +#endif // CV_SSE2 + +//! @} + +#endif //OPENCV_CORE_SSE_UTILS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/traits.hpp b/3rdParty/opencv-4.11.0/opencv2/core/traits.hpp index 522519389b..d17dc4e508 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/traits.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/traits.hpp @@ -1,417 +1,417 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CORE_TRAITS_HPP -#define OPENCV_CORE_TRAITS_HPP - -#include "opencv2/core/cvdef.h" - -namespace cv -{ - -//#define OPENCV_TRAITS_ENABLE_DEPRECATED - -//! @addtogroup core_basic -//! @{ - -/** @brief Template "trait" class for OpenCV primitive data types. - -@note Deprecated. This is replaced by "single purpose" traits: traits::Type and traits::Depth - -A primitive OpenCV data type is one of unsigned char, bool, signed char, unsigned short, signed -short, int, float, double, or a tuple of values of one of these types, where all the values in the -tuple have the same type. Any primitive type from the list can be defined by an identifier in the -form CV_\{U|S|F}C(\), for example: uchar \~ CV_8UC1, 3-element -floating-point tuple \~ CV_32FC3, and so on. A universal OpenCV structure that is able to store a -single instance of such a primitive data type is Vec. Multiple instances of such a type can be -stored in a std::vector, Mat, Mat_, SparseMat, SparseMat_, or any other container that is able to -store Vec instances. - -The DataType class is basically used to provide a description of such primitive data types without -adding any fields or methods to the corresponding classes (and it is actually impossible to add -anything to primitive C/C++ data types). This technique is known in C++ as class traits. It is not -DataType itself that is used but its specialized versions, such as: -@code - template<> class DataType - { - typedef uchar value_type; - typedef int work_type; - typedef uchar channel_type; - enum { channel_type = CV_8U, channels = 1, fmt='u', type = CV_8U }; - }; - ... - template DataType > - { - typedef std::complex<_Tp> value_type; - typedef std::complex<_Tp> work_type; - typedef _Tp channel_type; - // DataDepth is another helper trait class - enum { depth = DataDepth<_Tp>::value, channels=2, - fmt=(channels-1)*256+DataDepth<_Tp>::fmt, - type=CV_MAKETYPE(depth, channels) }; - }; - ... -@endcode -The main purpose of this class is to convert compilation-time type information to an -OpenCV-compatible data type identifier, for example: -@code - // allocates a 30x40 floating-point matrix - Mat A(30, 40, DataType::type); - - Mat B = Mat_ >(3, 3); - // the statement below will print 6, 2 , that is depth == CV_64F, channels == 2 - cout << B.depth() << ", " << B.channels() << endl; -@endcode -So, such traits are used to tell OpenCV which data type you are working with, even if such a type is -not native to OpenCV. For example, the matrix B initialization above is compiled because OpenCV -defines the proper specialized template class DataType\ \> . This mechanism is also -useful (and used in OpenCV this way) for generic algorithms implementations. - -@note Default values were dropped to stop confusing developers about using of unsupported types (see #7599) -*/ -template class DataType -{ -public: -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - typedef _Tp value_type; - typedef value_type work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 1, - depth = -1, - channels = 1, - fmt = 0, - type = CV_MAKETYPE(depth, channels) - }; -#endif -}; - -template<> class DataType -{ -public: - typedef bool value_type; - typedef int work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, - depth = CV_8U, - channels = 1, - fmt = (int)'u', - type = CV_MAKETYPE(depth, channels) - }; -}; - -template<> class DataType -{ -public: - typedef uchar value_type; - typedef int work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, - depth = CV_8U, - channels = 1, - fmt = (int)'u', - type = CV_MAKETYPE(depth, channels) - }; -}; - -template<> class DataType -{ -public: - typedef schar value_type; - typedef int work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, - depth = CV_8S, - channels = 1, - fmt = (int)'c', - type = CV_MAKETYPE(depth, channels) - }; -}; - -template<> class DataType -{ -public: - typedef schar value_type; - typedef int work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, - depth = CV_8S, - channels = 1, - fmt = (int)'c', - type = CV_MAKETYPE(depth, channels) - }; -}; - -template<> class DataType -{ -public: - typedef ushort value_type; - typedef int work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, - depth = CV_16U, - channels = 1, - fmt = (int)'w', - type = CV_MAKETYPE(depth, channels) - }; -}; - -template<> class DataType -{ -public: - typedef short value_type; - typedef int work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, - depth = CV_16S, - channels = 1, - fmt = (int)'s', - type = CV_MAKETYPE(depth, channels) - }; -}; - -template<> class DataType -{ -public: - typedef int value_type; - typedef value_type work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, - depth = CV_32S, - channels = 1, - fmt = (int)'i', - type = CV_MAKETYPE(depth, channels) - }; -}; - -template<> class DataType -{ -public: - typedef float value_type; - typedef value_type work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, - depth = CV_32F, - channels = 1, - fmt = (int)'f', - type = CV_MAKETYPE(depth, channels) - }; -}; - -template<> class DataType -{ -public: - typedef double value_type; - typedef value_type work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, - depth = CV_64F, - channels = 1, - fmt = (int)'d', - type = CV_MAKETYPE(depth, channels) - }; -}; - -template<> class DataType -{ -public: - typedef hfloat value_type; - typedef float work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, - depth = CV_16F, - channels = 1, - fmt = (int)'h', - type = CV_MAKETYPE(depth, channels) - }; -}; - -/** @brief A helper class for cv::DataType - -The class is specialized for each fundamental numerical data type supported by OpenCV. It provides -DataDepth::value constant. -*/ -template class DataDepth -{ -public: - enum - { - value = DataType<_Tp>::depth, - fmt = DataType<_Tp>::fmt - }; -}; - - -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - -template class TypeDepth -{ -#ifdef OPENCV_TRAITS_ENABLE_LEGACY_DEFAULTS - enum { depth = CV_USRTYPE1 }; - typedef void value_type; -#endif -}; - -template<> class TypeDepth -{ - enum { depth = CV_8U }; - typedef uchar value_type; -}; - -template<> class TypeDepth -{ - enum { depth = CV_8S }; - typedef schar value_type; -}; - -template<> class TypeDepth -{ - enum { depth = CV_16U }; - typedef ushort value_type; -}; - -template<> class TypeDepth -{ - enum { depth = CV_16S }; - typedef short value_type; -}; - -template<> class TypeDepth -{ - enum { depth = CV_32S }; - typedef int value_type; -}; - -template<> class TypeDepth -{ - enum { depth = CV_32F }; - typedef float value_type; -}; - -template<> class TypeDepth -{ - enum { depth = CV_64F }; - typedef double value_type; -}; - -template<> class TypeDepth -{ - enum { depth = CV_16F }; - typedef hfloat value_type; -}; - -#endif - -//! @} - -namespace traits { - -namespace internal { -#define CV_CREATE_MEMBER_CHECK(X) \ -template class CheckMember_##X { \ - struct Fallback { int X; }; \ - struct Derived : T, Fallback { }; \ - template struct Check; \ - typedef char CV_NO[1]; \ - typedef char CV_YES[2]; \ - template static CV_NO & func(Check *); \ - template static CV_YES & func(...); \ -public: \ - typedef CheckMember_##X type; \ - enum { value = sizeof(func(0)) == sizeof(CV_YES) }; \ -}; - -CV_CREATE_MEMBER_CHECK(fmt) -CV_CREATE_MEMBER_CHECK(type) - -} // namespace internal - - -template -struct Depth -{ enum { value = DataType::depth }; }; - -template -struct Type -{ enum { value = DataType::type }; }; - -/** Similar to traits::Type but has value = -1 in case of unknown type (instead of compiler error) */ -template >::value > -struct SafeType {}; - -template -struct SafeType -{ enum { value = -1 }; }; - -template -struct SafeType -{ enum { value = Type::value }; }; - - -template >::value > -struct SafeFmt {}; - -template -struct SafeFmt -{ enum { fmt = 0 }; }; - -template -struct SafeFmt -{ enum { fmt = DataType::fmt }; }; - - -} // namespace - -} // cv - -#endif // OPENCV_CORE_TRAITS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CORE_TRAITS_HPP +#define OPENCV_CORE_TRAITS_HPP + +#include "opencv2/core/cvdef.h" + +namespace cv +{ + +//#define OPENCV_TRAITS_ENABLE_DEPRECATED + +//! @addtogroup core_basic +//! @{ + +/** @brief Template "trait" class for OpenCV primitive data types. + +@note Deprecated. This is replaced by "single purpose" traits: traits::Type and traits::Depth + +A primitive OpenCV data type is one of unsigned char, bool, signed char, unsigned short, signed +short, int, float, double, or a tuple of values of one of these types, where all the values in the +tuple have the same type. Any primitive type from the list can be defined by an identifier in the +form CV_\{U|S|F}C(\), for example: uchar \~ CV_8UC1, 3-element +floating-point tuple \~ CV_32FC3, and so on. A universal OpenCV structure that is able to store a +single instance of such a primitive data type is Vec. Multiple instances of such a type can be +stored in a std::vector, Mat, Mat_, SparseMat, SparseMat_, or any other container that is able to +store Vec instances. + +The DataType class is basically used to provide a description of such primitive data types without +adding any fields or methods to the corresponding classes (and it is actually impossible to add +anything to primitive C/C++ data types). This technique is known in C++ as class traits. It is not +DataType itself that is used but its specialized versions, such as: +@code + template<> class DataType + { + typedef uchar value_type; + typedef int work_type; + typedef uchar channel_type; + enum { channel_type = CV_8U, channels = 1, fmt='u', type = CV_8U }; + }; + ... + template DataType > + { + typedef std::complex<_Tp> value_type; + typedef std::complex<_Tp> work_type; + typedef _Tp channel_type; + // DataDepth is another helper trait class + enum { depth = DataDepth<_Tp>::value, channels=2, + fmt=(channels-1)*256+DataDepth<_Tp>::fmt, + type=CV_MAKETYPE(depth, channels) }; + }; + ... +@endcode +The main purpose of this class is to convert compilation-time type information to an +OpenCV-compatible data type identifier, for example: +@code + // allocates a 30x40 floating-point matrix + Mat A(30, 40, DataType::type); + + Mat B = Mat_ >(3, 3); + // the statement below will print 6, 2 , that is depth == CV_64F, channels == 2 + cout << B.depth() << ", " << B.channels() << endl; +@endcode +So, such traits are used to tell OpenCV which data type you are working with, even if such a type is +not native to OpenCV. For example, the matrix B initialization above is compiled because OpenCV +defines the proper specialized template class DataType\ \> . This mechanism is also +useful (and used in OpenCV this way) for generic algorithms implementations. + +@note Default values were dropped to stop confusing developers about using of unsupported types (see #7599) +*/ +template class DataType +{ +public: +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + typedef _Tp value_type; + typedef value_type work_type; + typedef value_type channel_type; + typedef value_type vec_type; + enum { generic_type = 1, + depth = -1, + channels = 1, + fmt = 0, + type = CV_MAKETYPE(depth, channels) + }; +#endif +}; + +template<> class DataType +{ +public: + typedef bool value_type; + typedef int work_type; + typedef value_type channel_type; + typedef value_type vec_type; + enum { generic_type = 0, + depth = CV_8U, + channels = 1, + fmt = (int)'u', + type = CV_MAKETYPE(depth, channels) + }; +}; + +template<> class DataType +{ +public: + typedef uchar value_type; + typedef int work_type; + typedef value_type channel_type; + typedef value_type vec_type; + enum { generic_type = 0, + depth = CV_8U, + channels = 1, + fmt = (int)'u', + type = CV_MAKETYPE(depth, channels) + }; +}; + +template<> class DataType +{ +public: + typedef schar value_type; + typedef int work_type; + typedef value_type channel_type; + typedef value_type vec_type; + enum { generic_type = 0, + depth = CV_8S, + channels = 1, + fmt = (int)'c', + type = CV_MAKETYPE(depth, channels) + }; +}; + +template<> class DataType +{ +public: + typedef schar value_type; + typedef int work_type; + typedef value_type channel_type; + typedef value_type vec_type; + enum { generic_type = 0, + depth = CV_8S, + channels = 1, + fmt = (int)'c', + type = CV_MAKETYPE(depth, channels) + }; +}; + +template<> class DataType +{ +public: + typedef ushort value_type; + typedef int work_type; + typedef value_type channel_type; + typedef value_type vec_type; + enum { generic_type = 0, + depth = CV_16U, + channels = 1, + fmt = (int)'w', + type = CV_MAKETYPE(depth, channels) + }; +}; + +template<> class DataType +{ +public: + typedef short value_type; + typedef int work_type; + typedef value_type channel_type; + typedef value_type vec_type; + enum { generic_type = 0, + depth = CV_16S, + channels = 1, + fmt = (int)'s', + type = CV_MAKETYPE(depth, channels) + }; +}; + +template<> class DataType +{ +public: + typedef int value_type; + typedef value_type work_type; + typedef value_type channel_type; + typedef value_type vec_type; + enum { generic_type = 0, + depth = CV_32S, + channels = 1, + fmt = (int)'i', + type = CV_MAKETYPE(depth, channels) + }; +}; + +template<> class DataType +{ +public: + typedef float value_type; + typedef value_type work_type; + typedef value_type channel_type; + typedef value_type vec_type; + enum { generic_type = 0, + depth = CV_32F, + channels = 1, + fmt = (int)'f', + type = CV_MAKETYPE(depth, channels) + }; +}; + +template<> class DataType +{ +public: + typedef double value_type; + typedef value_type work_type; + typedef value_type channel_type; + typedef value_type vec_type; + enum { generic_type = 0, + depth = CV_64F, + channels = 1, + fmt = (int)'d', + type = CV_MAKETYPE(depth, channels) + }; +}; + +template<> class DataType +{ +public: + typedef hfloat value_type; + typedef float work_type; + typedef value_type channel_type; + typedef value_type vec_type; + enum { generic_type = 0, + depth = CV_16F, + channels = 1, + fmt = (int)'h', + type = CV_MAKETYPE(depth, channels) + }; +}; + +/** @brief A helper class for cv::DataType + +The class is specialized for each fundamental numerical data type supported by OpenCV. It provides +DataDepth::value constant. +*/ +template class DataDepth +{ +public: + enum + { + value = DataType<_Tp>::depth, + fmt = DataType<_Tp>::fmt + }; +}; + + +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + +template class TypeDepth +{ +#ifdef OPENCV_TRAITS_ENABLE_LEGACY_DEFAULTS + enum { depth = CV_USRTYPE1 }; + typedef void value_type; +#endif +}; + +template<> class TypeDepth +{ + enum { depth = CV_8U }; + typedef uchar value_type; +}; + +template<> class TypeDepth +{ + enum { depth = CV_8S }; + typedef schar value_type; +}; + +template<> class TypeDepth +{ + enum { depth = CV_16U }; + typedef ushort value_type; +}; + +template<> class TypeDepth +{ + enum { depth = CV_16S }; + typedef short value_type; +}; + +template<> class TypeDepth +{ + enum { depth = CV_32S }; + typedef int value_type; +}; + +template<> class TypeDepth +{ + enum { depth = CV_32F }; + typedef float value_type; +}; + +template<> class TypeDepth +{ + enum { depth = CV_64F }; + typedef double value_type; +}; + +template<> class TypeDepth +{ + enum { depth = CV_16F }; + typedef hfloat value_type; +}; + +#endif + +//! @} + +namespace traits { + +namespace internal { +#define CV_CREATE_MEMBER_CHECK(X) \ +template class CheckMember_##X { \ + struct Fallback { int X; }; \ + struct Derived : T, Fallback { }; \ + template struct Check; \ + typedef char CV_NO[1]; \ + typedef char CV_YES[2]; \ + template static CV_NO & func(Check *); \ + template static CV_YES & func(...); \ +public: \ + typedef CheckMember_##X type; \ + enum { value = sizeof(func(0)) == sizeof(CV_YES) }; \ +}; + +CV_CREATE_MEMBER_CHECK(fmt) +CV_CREATE_MEMBER_CHECK(type) + +} // namespace internal + + +template +struct Depth +{ enum { value = DataType::depth }; }; + +template +struct Type +{ enum { value = DataType::type }; }; + +/** Similar to traits::Type but has value = -1 in case of unknown type (instead of compiler error) */ +template >::value > +struct SafeType {}; + +template +struct SafeType +{ enum { value = -1 }; }; + +template +struct SafeType +{ enum { value = Type::value }; }; + + +template >::value > +struct SafeFmt {}; + +template +struct SafeFmt +{ enum { fmt = 0 }; }; + +template +struct SafeFmt +{ enum { fmt = DataType::fmt }; }; + + +} // namespace + +} // cv + +#endif // OPENCV_CORE_TRAITS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/types.hpp b/3rdParty/opencv-4.11.0/opencv2/core/types.hpp index df4fd21885..f69e499f36 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/types.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/types.hpp @@ -1,2487 +1,2489 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CORE_TYPES_HPP -#define OPENCV_CORE_TYPES_HPP - -#ifndef __cplusplus -# error types.hpp header must be compiled as C++ -#endif - -#include -#include -#include -#include - -#include "opencv2/core/cvdef.h" -#include "opencv2/core/cvstd.hpp" -#include "opencv2/core/matx.hpp" - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable: 4459) // declaration of '...' hides global declaration -#endif - -namespace cv -{ - -//! @addtogroup core_basic -//! @{ - -//////////////////////////////// Complex ////////////////////////////// - -/** @brief A complex number class. - - The template class is similar and compatible with std::complex, however it provides slightly - more convenient access to the real and imaginary parts using through the simple field access, as opposite - to std::complex::real() and std::complex::imag(). -*/ -template class Complex -{ -public: - - //! default constructor - Complex(); - Complex( _Tp _re, _Tp _im = 0 ); - - //! conversion to another data type - template operator Complex() const; - //! conjugation - Complex conj() const; - - _Tp re, im; ///< the real and the imaginary parts -}; - -typedef Complex Complexf; -typedef Complex Complexd; - -template class DataType< Complex<_Tp> > -{ -public: - typedef Complex<_Tp> value_type; - typedef value_type work_type; - typedef _Tp channel_type; - - enum { generic_type = 0, - channels = 2, - fmt = DataType::fmt + ((channels - 1) << 8) -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - ,depth = DataType::depth - ,type = CV_MAKETYPE(depth, channels) -#endif - }; - - typedef Vec vec_type; -}; - -namespace traits { -template -struct Depth< Complex<_Tp> > { enum { value = Depth<_Tp>::value }; }; -template -struct Type< Complex<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 2) }; }; -} // namespace - - -//////////////////////////////// Point_ //////////////////////////////// - -/** @brief Template class for 2D points specified by its coordinates `x` and `y`. - -An instance of the class is interchangeable with C structures, CvPoint and CvPoint2D32f . There is -also a cast operator to convert point coordinates to the specified type. The conversion from -floating-point coordinates to integer coordinates is done by rounding. Commonly, the conversion -uses this operation for each of the coordinates. Besides the class members listed in the -declaration above, the following operations on points are implemented: -@code - pt1 = pt2 + pt3; - pt1 = pt2 - pt3; - pt1 = pt2 * a; - pt1 = a * pt2; - pt1 = pt2 / a; - pt1 += pt2; - pt1 -= pt2; - pt1 *= a; - pt1 /= a; - double value = norm(pt); // L2 norm - pt1 == pt2; - pt1 != pt2; -@endcode -For your convenience, the following type aliases are defined: -@code - typedef Point_ Point2i; - typedef Point2i Point; - typedef Point_ Point2f; - typedef Point_ Point2d; -@endcode -Example: -@code - Point2f a(0.3f, 0.f), b(0.f, 0.4f); - Point pt = (a + b)*10.f; - cout << pt.x << ", " << pt.y << endl; -@endcode -*/ -template class Point_ -{ -public: - typedef _Tp value_type; - - //! default constructor - Point_(); - Point_(_Tp _x, _Tp _y); -#if (defined(__GNUC__) && __GNUC__ < 5) && !defined(__clang__) // GCC 4.x bug. Details: https://github.com/opencv/opencv/pull/20837 - Point_(const Point_& pt); - Point_(Point_&& pt) CV_NOEXCEPT = default; -#elif OPENCV_ABI_COMPATIBILITY < 500 - Point_(const Point_& pt) = default; - Point_(Point_&& pt) CV_NOEXCEPT = default; -#endif - Point_(const Size_<_Tp>& sz); - Point_(const Vec<_Tp, 2>& v); - -#if (defined(__GNUC__) && __GNUC__ < 5) && !defined(__clang__) // GCC 4.x bug. Details: https://github.com/opencv/opencv/pull/20837 - Point_& operator = (const Point_& pt); - Point_& operator = (Point_&& pt) CV_NOEXCEPT = default; -#elif OPENCV_ABI_COMPATIBILITY < 500 - Point_& operator = (const Point_& pt) = default; - Point_& operator = (Point_&& pt) CV_NOEXCEPT = default; -#endif - //! conversion to another data type - template operator Point_<_Tp2>() const; - - //! conversion to the old-style C structures - operator Vec<_Tp, 2>() const; - - //! dot product - _Tp dot(const Point_& pt) const; - //! dot product computed in double-precision arithmetics - double ddot(const Point_& pt) const; - //! cross-product - double cross(const Point_& pt) const; - //! checks whether the point is inside the specified rectangle - bool inside(const Rect_<_Tp>& r) const; - _Tp x; //!< x coordinate of the point - _Tp y; //!< y coordinate of the point -}; - -typedef Point_ Point2i; -typedef Point_ Point2l; -typedef Point_ Point2f; -typedef Point_ Point2d; -typedef Point2i Point; - -template class DataType< Point_<_Tp> > -{ -public: - typedef Point_<_Tp> value_type; - typedef Point_::work_type> work_type; - typedef _Tp channel_type; - - enum { generic_type = 0, - channels = 2, - fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - ,depth = DataType::depth - ,type = CV_MAKETYPE(depth, channels) -#endif - }; - - typedef Vec vec_type; -}; - -namespace traits { -template -struct Depth< Point_<_Tp> > { enum { value = Depth<_Tp>::value }; }; -template -struct Type< Point_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 2) }; }; -} // namespace - - -//////////////////////////////// Point3_ //////////////////////////////// - -/** @brief Template class for 3D points specified by its coordinates `x`, `y` and `z`. - -An instance of the class is interchangeable with the C structure CvPoint2D32f . Similarly to -Point_ , the coordinates of 3D points can be converted to another type. The vector arithmetic and -comparison operations are also supported. - -The following Point3_\<\> aliases are available: -@code - typedef Point3_ Point3i; - typedef Point3_ Point3f; - typedef Point3_ Point3d; -@endcode -@see cv::Point3i, cv::Point3f and cv::Point3d -*/ -template class Point3_ -{ -public: - typedef _Tp value_type; - - //! default constructor - Point3_(); - Point3_(_Tp _x, _Tp _y, _Tp _z); -#if OPENCV_ABI_COMPATIBILITY < 500 - Point3_(const Point3_& pt) = default; - Point3_(Point3_&& pt) CV_NOEXCEPT = default; -#endif - explicit Point3_(const Point_<_Tp>& pt); - Point3_(const Vec<_Tp, 3>& v); - -#if OPENCV_ABI_COMPATIBILITY < 500 - Point3_& operator = (const Point3_& pt) = default; - Point3_& operator = (Point3_&& pt) CV_NOEXCEPT = default; -#endif - //! conversion to another data type - template operator Point3_<_Tp2>() const; - //! conversion to cv::Vec<> - operator Vec<_Tp, 3>() const; - - //! dot product - _Tp dot(const Point3_& pt) const; - //! dot product computed in double-precision arithmetics - double ddot(const Point3_& pt) const; - //! cross product of the 2 3D points - Point3_ cross(const Point3_& pt) const; - _Tp x; //!< x coordinate of the 3D point - _Tp y; //!< y coordinate of the 3D point - _Tp z; //!< z coordinate of the 3D point -}; - -typedef Point3_ Point3i; -typedef Point3_ Point3f; -typedef Point3_ Point3d; - -template class DataType< Point3_<_Tp> > -{ -public: - typedef Point3_<_Tp> value_type; - typedef Point3_::work_type> work_type; - typedef _Tp channel_type; - - enum { generic_type = 0, - channels = 3, - fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - ,depth = DataType::depth - ,type = CV_MAKETYPE(depth, channels) -#endif - }; - - typedef Vec vec_type; -}; - -namespace traits { -template -struct Depth< Point3_<_Tp> > { enum { value = Depth<_Tp>::value }; }; -template -struct Type< Point3_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 3) }; }; -} // namespace - -//////////////////////////////// Size_ //////////////////////////////// - -/** @brief Template class for specifying the size of an image or rectangle. - -The class includes two members called width and height. The structure can be converted to and from -the old OpenCV structures CvSize and CvSize2D32f . The same set of arithmetic and comparison -operations as for Point_ is available. - -OpenCV defines the following Size_\<\> aliases: -@code - typedef Size_ Size2i; - typedef Size2i Size; - typedef Size_ Size2f; -@endcode -*/ -template class Size_ -{ -public: - typedef _Tp value_type; - - //! default constructor - Size_(); - Size_(_Tp _width, _Tp _height); -#if OPENCV_ABI_COMPATIBILITY < 500 - Size_(const Size_& sz) = default; - Size_(Size_&& sz) CV_NOEXCEPT = default; -#endif - Size_(const Point_<_Tp>& pt); - -#if OPENCV_ABI_COMPATIBILITY < 500 - Size_& operator = (const Size_& sz) = default; - Size_& operator = (Size_&& sz) CV_NOEXCEPT = default; -#endif - //! the area (width*height) - _Tp area() const; - //! aspect ratio (width/height) - double aspectRatio() const; - //! true if empty - bool empty() const; - - //! conversion of another data type. - template operator Size_<_Tp2>() const; - - _Tp width; //!< the width - _Tp height; //!< the height -}; - -typedef Size_ Size2i; -typedef Size_ Size2l; -typedef Size_ Size2f; -typedef Size_ Size2d; -typedef Size2i Size; - -template class DataType< Size_<_Tp> > -{ -public: - typedef Size_<_Tp> value_type; - typedef Size_::work_type> work_type; - typedef _Tp channel_type; - - enum { generic_type = 0, - channels = 2, - fmt = DataType::fmt + ((channels - 1) << 8) -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - ,depth = DataType::depth - ,type = CV_MAKETYPE(depth, channels) -#endif - }; - - typedef Vec vec_type; -}; - -namespace traits { -template -struct Depth< Size_<_Tp> > { enum { value = Depth<_Tp>::value }; }; -template -struct Type< Size_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 2) }; }; -} // namespace - -//////////////////////////////// Rect_ //////////////////////////////// - -/** @brief Template class for 2D rectangles - -described by the following parameters: -- Coordinates of the top-left corner. This is a default interpretation of Rect_::x and Rect_::y - in OpenCV. Though, in your algorithms you may count x and y from the bottom-left corner. -- Rectangle width and height. - -OpenCV typically assumes that the top and left boundary of the rectangle are inclusive, while the -right and bottom boundaries are not. For example, the method Rect_::contains returns true if - -\f[x \leq pt.x < x+width, - y \leq pt.y < y+height\f] - -Virtually every loop over an image ROI in OpenCV (where ROI is specified by Rect_\ ) is -implemented as: -@code - for(int y = roi.y; y < roi.y + roi.height; y++) - for(int x = roi.x; x < roi.x + roi.width; x++) - { - // ... - } -@endcode -In addition to the class members, the following operations on rectangles are implemented: -- \f$\texttt{rect} = \texttt{rect} \pm \texttt{point}\f$ (shifting a rectangle by a certain offset) -- \f$\texttt{rect} = \texttt{rect} \pm \texttt{size}\f$ (expanding or shrinking a rectangle by a - certain amount) -- rect += point, rect -= point, rect += size, rect -= size (augmenting operations) -- rect = rect1 & rect2 (rectangle intersection) -- rect = rect1 | rect2 (minimum area rectangle containing rect1 and rect2 ) -- rect &= rect1, rect |= rect1 (and the corresponding augmenting operations) -- rect == rect1, rect != rect1 (rectangle comparison) - -This is an example how the partial ordering on rectangles can be established (rect1 \f$\subseteq\f$ -rect2): -@code - template inline bool - operator <= (const Rect_<_Tp>& r1, const Rect_<_Tp>& r2) - { - return (r1 & r2) == r1; - } -@endcode -For your convenience, the Rect_\<\> alias is available: cv::Rect -*/ -template class Rect_ -{ -public: - typedef _Tp value_type; - - //! default constructor - Rect_(); - Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height); -#if OPENCV_ABI_COMPATIBILITY < 500 - Rect_(const Rect_& r) = default; - Rect_(Rect_&& r) CV_NOEXCEPT = default; -#endif - Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz); - Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2); - -#if OPENCV_ABI_COMPATIBILITY < 500 - Rect_& operator = (const Rect_& r) = default; - Rect_& operator = (Rect_&& r) CV_NOEXCEPT = default; -#endif - //! the top-left corner - Point_<_Tp> tl() const; - //! the bottom-right corner - Point_<_Tp> br() const; - - //! size (width, height) of the rectangle - Size_<_Tp> size() const; - //! area (width*height) of the rectangle - _Tp area() const; - //! true if empty - bool empty() const; - - //! conversion to another data type - template operator Rect_<_Tp2>() const; - - //! checks whether the rectangle contains the point - /*! @warning After OpenCV 4.11.0, when calling Rect.contains() with cv::Point2f / cv::Point2d point, point should not convert/round to int. - * ``` - * Rect_ r(0,0,500,500); Point_ pt(250.0f, 499.9f); - * r.contains(pt) returns false.(OpenCV 4.10.0 or before) - * r.contains(pt) returns true. (OpenCV 4.11.0 or later) - * ``` - */ - template inline bool contains(const Point_<_Tp2>& pt) const; - - _Tp x; //!< x coordinate of the top-left corner - _Tp y; //!< y coordinate of the top-left corner - _Tp width; //!< width of the rectangle - _Tp height; //!< height of the rectangle -}; - -typedef Rect_ Rect2i; -typedef Rect_ Rect2f; -typedef Rect_ Rect2d; -typedef Rect2i Rect; - -template class DataType< Rect_<_Tp> > -{ -public: - typedef Rect_<_Tp> value_type; - typedef Rect_::work_type> work_type; - typedef _Tp channel_type; - - enum { generic_type = 0, - channels = 4, - fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - ,depth = DataType::depth - ,type = CV_MAKETYPE(depth, channels) -#endif - }; - - typedef Vec vec_type; -}; - -namespace traits { -template -struct Depth< Rect_<_Tp> > { enum { value = Depth<_Tp>::value }; }; -template -struct Type< Rect_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 4) }; }; -} // namespace - -///////////////////////////// RotatedRect ///////////////////////////// - -/** @brief The class represents rotated (i.e. not up-right) rectangles on a plane. - -Each rectangle is specified by the center point (mass center), length of each side (represented by -#Size2f structure) and the rotation angle in degrees. - -The sample below demonstrates how to use RotatedRect: -@snippet snippets/core_various.cpp RotatedRect_demo -![image](pics/rotatedrect.png) - -@sa CamShift, fitEllipse, minAreaRect, CvBox2D -*/ -class CV_EXPORTS_W_SIMPLE RotatedRect -{ -public: - //! default constructor - CV_WRAP RotatedRect(); - /** full constructor - @param center The rectangle mass center. - @param size Width and height of the rectangle. - @param angle The rotation angle in a clockwise direction. When the angle is 0, 90, 180, 270 etc., - the rectangle becomes an up-right rectangle. - */ - CV_WRAP RotatedRect(const Point2f& center, const Size2f& size, float angle); - /** - Any 3 end points of the RotatedRect. They must be given in order (either clockwise or - anticlockwise). - */ - CV_WRAP RotatedRect(const Point2f& point1, const Point2f& point2, const Point2f& point3); - - /** returns 4 vertices of the rotated rectangle - @param pts The points array for storing rectangle vertices. The order is _bottomLeft_, _topLeft_, topRight, bottomRight. - @note _Bottom_, _Top_, _Left_ and _Right_ sides refer to the original rectangle (angle is 0), - so after 180 degree rotation _bottomLeft_ point will be located at the top right corner of the - rectangle. - */ - void points(Point2f pts[]) const; - - CV_WRAP void points(CV_OUT std::vector& pts) const; - - //! returns the minimal up-right integer rectangle containing the rotated rectangle - CV_WRAP Rect boundingRect() const; - //! returns the minimal (exact) floating point rectangle containing the rotated rectangle, not intended for use with images - CV_WRAP Rect2f boundingRect2f() const; - //! returns the rectangle mass center - CV_PROP_RW Point2f center; - //! returns width and height of the rectangle - CV_PROP_RW Size2f size; - //! returns the rotation angle. When the angle is 0, 90, 180, 270 etc., the rectangle becomes an up-right rectangle. - CV_PROP_RW float angle; -}; - -template<> class DataType< RotatedRect > -{ -public: - typedef RotatedRect value_type; - typedef value_type work_type; - typedef float channel_type; - - enum { generic_type = 0, - channels = (int)sizeof(value_type)/sizeof(channel_type), // 5 - fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - ,depth = DataType::depth - ,type = CV_MAKETYPE(depth, channels) -#endif - }; - - typedef Vec vec_type; -}; - -namespace traits { -template<> -struct Depth< RotatedRect > { enum { value = Depth::value }; }; -template<> -struct Type< RotatedRect > { enum { value = CV_MAKETYPE(Depth::value, (int)sizeof(RotatedRect)/sizeof(float)) }; }; -} // namespace - - -//////////////////////////////// Range ///////////////////////////////// - -/** @brief Template class specifying a continuous subsequence (slice) of a sequence. - -The class is used to specify a row or a column span in a matrix ( Mat ) and for many other purposes. -Range(a,b) is basically the same as a:b in Matlab or a..b in Python. As in Python, start is an -inclusive left boundary of the range and end is an exclusive right boundary of the range. Such a -half-opened interval is usually denoted as \f$[start,end)\f$ . - -The static method Range::all() returns a special variable that means "the whole sequence" or "the -whole range", just like " : " in Matlab or " ... " in Python. All the methods and functions in -OpenCV that take Range support this special Range::all() value. But, of course, in case of your own -custom processing, you will probably have to check and handle it explicitly: -@code - void my_function(..., const Range& r, ....) - { - if(r == Range::all()) { - // process all the data - } - else { - // process [r.start, r.end) - } - } -@endcode -*/ -class CV_EXPORTS Range -{ -public: - Range(); - Range(int _start, int _end); - int size() const; - bool empty() const; - static Range all(); - - int start, end; -}; - -template<> class DataType -{ -public: - typedef Range value_type; - typedef value_type work_type; - typedef int channel_type; - - enum { generic_type = 0, - channels = 2, - fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - ,depth = DataType::depth - ,type = CV_MAKETYPE(depth, channels) -#endif - }; - - typedef Vec vec_type; -}; - -namespace traits { -template<> -struct Depth< Range > { enum { value = Depth::value }; }; -template<> -struct Type< Range > { enum { value = CV_MAKETYPE(Depth::value, 2) }; }; -} // namespace - - -//////////////////////////////// Scalar_ /////////////////////////////// - -/** @brief Template class for a 4-element vector derived from Vec. - -Being derived from Vec\<_Tp, 4\> , Scalar\_ and Scalar can be used just as typical 4-element -vectors. In addition, they can be converted to/from CvScalar . The type Scalar is widely used in -OpenCV to pass pixel values. -*/ -template class Scalar_ : public Vec<_Tp, 4> -{ -public: - //! default constructor - Scalar_(); - Scalar_(_Tp v0, _Tp v1, _Tp v2=0, _Tp v3=0); - Scalar_(_Tp v0); - - Scalar_(const Scalar_& s); - Scalar_(Scalar_&& s) CV_NOEXCEPT; - - Scalar_& operator=(const Scalar_& s); - Scalar_& operator=(Scalar_&& s) CV_NOEXCEPT; - - template - Scalar_(const Vec<_Tp2, cn>& v); - - //! returns a scalar with all elements set to v0 - static Scalar_<_Tp> all(_Tp v0); - - //! conversion to another data type - template operator Scalar_() const; - - //! per-element product - Scalar_<_Tp> mul(const Scalar_<_Tp>& a, double scale=1 ) const; - - //! returns (v0, -v1, -v2, -v3) - Scalar_<_Tp> conj() const; - - //! returns true iff v1 == v2 == v3 == 0 - bool isReal() const; -}; - -typedef Scalar_ Scalar; - -template class DataType< Scalar_<_Tp> > -{ -public: - typedef Scalar_<_Tp> value_type; - typedef Scalar_::work_type> work_type; - typedef _Tp channel_type; - - enum { generic_type = 0, - channels = 4, - fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - ,depth = DataType::depth - ,type = CV_MAKETYPE(depth, channels) -#endif - }; - - typedef Vec vec_type; -}; - -namespace traits { -template -struct Depth< Scalar_<_Tp> > { enum { value = Depth<_Tp>::value }; }; -template -struct Type< Scalar_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 4) }; }; -} // namespace - - -/////////////////////////////// KeyPoint //////////////////////////////// - -/** @brief Data structure for salient point detectors. - -The class instance stores a keypoint, i.e. a point feature found by one of many available keypoint -detectors, such as Harris corner detector, #FAST, %StarDetector, %SURF, %SIFT etc. - -The keypoint is characterized by the 2D position, scale (proportional to the diameter of the -neighborhood that needs to be taken into account), orientation and some other parameters. The -keypoint neighborhood is then analyzed by another algorithm that builds a descriptor (usually -represented as a feature vector). The keypoints representing the same object in different images -can then be matched using %KDTree or another method. -*/ -class CV_EXPORTS_W_SIMPLE KeyPoint -{ -public: - //! the default constructor - CV_WRAP KeyPoint(); - /** - @param pt x & y coordinates of the keypoint - @param size keypoint diameter - @param angle keypoint orientation - @param response keypoint detector response on the keypoint (that is, strength of the keypoint) - @param octave pyramid octave in which the keypoint has been detected - @param class_id object id - */ - KeyPoint(Point2f pt, float size, float angle=-1, float response=0, int octave=0, int class_id=-1); - /** - @param x x-coordinate of the keypoint - @param y y-coordinate of the keypoint - @param size keypoint diameter - @param angle keypoint orientation - @param response keypoint detector response on the keypoint (that is, strength of the keypoint) - @param octave pyramid octave in which the keypoint has been detected - @param class_id object id - */ - CV_WRAP KeyPoint(float x, float y, float size, float angle=-1, float response=0, int octave=0, int class_id=-1); - - size_t hash() const; - - /** - This method converts vector of keypoints to vector of points or the reverse, where each keypoint is - assigned the same size and the same orientation. - - @param keypoints Keypoints obtained from any feature detection algorithm like SIFT/SURF/ORB - @param points2f Array of (x,y) coordinates of each keypoint - @param keypointIndexes Array of indexes of keypoints to be converted to points. (Acts like a mask to - convert only specified keypoints) - */ - CV_WRAP static void convert(const std::vector& keypoints, - CV_OUT std::vector& points2f, - const std::vector& keypointIndexes=std::vector()); - /** @overload - @param points2f Array of (x,y) coordinates of each keypoint - @param keypoints Keypoints obtained from any feature detection algorithm like SIFT/SURF/ORB - @param size keypoint diameter - @param response keypoint detector response on the keypoint (that is, strength of the keypoint) - @param octave pyramid octave in which the keypoint has been detected - @param class_id object id - */ - CV_WRAP static void convert(const std::vector& points2f, - CV_OUT std::vector& keypoints, - float size=1, float response=1, int octave=0, int class_id=-1); - - /** - This method computes overlap for pair of keypoints. Overlap is the ratio between area of keypoint - regions' intersection and area of keypoint regions' union (considering keypoint region as circle). - If they don't overlap, we get zero. If they coincide at same location with same size, we get 1. - @param kp1 First keypoint - @param kp2 Second keypoint - */ - CV_WRAP static float overlap(const KeyPoint& kp1, const KeyPoint& kp2); - - CV_PROP_RW Point2f pt; //!< coordinates of the keypoints - CV_PROP_RW float size; //!< diameter of the meaningful keypoint neighborhood - CV_PROP_RW float angle; //!< computed orientation of the keypoint (-1 if not applicable); - //!< it's in [0,360) degrees and measured relative to - //!< image coordinate system, ie in clockwise. - CV_PROP_RW float response; //!< the response by which the most strong keypoints have been selected. Can be used for the further sorting or subsampling - CV_PROP_RW int octave; //!< octave (pyramid layer) from which the keypoint has been extracted - CV_PROP_RW int class_id; //!< object class (if the keypoints need to be clustered by an object they belong to) -}; - -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED -template<> class DataType -{ -public: - typedef KeyPoint value_type; - typedef float work_type; - typedef float channel_type; - - enum { generic_type = 0, - depth = DataType::depth, - channels = (int)(sizeof(value_type)/sizeof(channel_type)), // 7 - fmt = DataType::fmt + ((channels - 1) << 8), - type = CV_MAKETYPE(depth, channels) - }; - - typedef Vec vec_type; -}; -#endif - - -//////////////////////////////// DMatch ///////////////////////////////// - -/** @brief Class for matching keypoint descriptors - -query descriptor index, train descriptor index, train image index, and distance between -descriptors. -*/ -class CV_EXPORTS_W_SIMPLE DMatch -{ -public: - CV_WRAP DMatch(); - CV_WRAP DMatch(int _queryIdx, int _trainIdx, float _distance); - CV_WRAP DMatch(int _queryIdx, int _trainIdx, int _imgIdx, float _distance); - - CV_PROP_RW int queryIdx; //!< query descriptor index - CV_PROP_RW int trainIdx; //!< train descriptor index - CV_PROP_RW int imgIdx; //!< train image index - - CV_PROP_RW float distance; - - // less is better - bool operator<(const DMatch &m) const; -}; - -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED -template<> class DataType -{ -public: - typedef DMatch value_type; - typedef int work_type; - typedef int channel_type; - - enum { generic_type = 0, - depth = DataType::depth, - channels = (int)(sizeof(value_type)/sizeof(channel_type)), // 4 - fmt = DataType::fmt + ((channels - 1) << 8), - type = CV_MAKETYPE(depth, channels) - }; - - typedef Vec vec_type; -}; -#endif - - -///////////////////////////// TermCriteria ////////////////////////////// - -/** @brief The class defining termination criteria for iterative algorithms. - -You can initialize it by default constructor and then override any parameters, or the structure may -be fully initialized using the advanced variant of the constructor. -*/ -class CV_EXPORTS TermCriteria -{ -public: - /** - Criteria type, can be one of: COUNT, EPS or COUNT + EPS - */ - enum Type - { - COUNT=1, //!< the maximum number of iterations or elements to compute - MAX_ITER=COUNT, //!< ditto - EPS=2 //!< the desired accuracy or change in parameters at which the iterative algorithm stops - }; - - //! default constructor - TermCriteria(); - /** - @param type The type of termination criteria, one of TermCriteria::Type - @param maxCount The maximum number of iterations or elements to compute. - @param epsilon The desired accuracy or change in parameters at which the iterative algorithm stops. - */ - TermCriteria(int type, int maxCount, double epsilon); - - inline bool isValid() const - { - const bool isCount = (type & COUNT) && maxCount > 0; - const bool isEps = (type & EPS) && !cvIsNaN(epsilon); - return isCount || isEps; - } - - int type; //!< the type of termination criteria: COUNT, EPS or COUNT + EPS - int maxCount; //!< the maximum number of iterations/elements - double epsilon; //!< the desired accuracy -}; - - -//! @} core_basic - -///////////////////////// raster image moments ////////////////////////// - -//! @addtogroup imgproc_shape -//! @{ - -/** @brief struct returned by cv::moments - -The spatial moments \f$\texttt{Moments::m}_{ji}\f$ are computed as: - -\f[\texttt{m} _{ji}= \sum _{x,y} \left ( \texttt{array} (x,y) \cdot x^j \cdot y^i \right )\f] - -The central moments \f$\texttt{Moments::mu}_{ji}\f$ are computed as: - -\f[\texttt{mu} _{ji}= \sum _{x,y} \left ( \texttt{array} (x,y) \cdot (x - \bar{x} )^j \cdot (y - \bar{y} )^i \right )\f] - -where \f$(\bar{x}, \bar{y})\f$ is the mass center: - -\f[\bar{x} = \frac{\texttt{m}_{10}}{\texttt{m}_{00}} , \; \bar{y} = \frac{\texttt{m}_{01}}{\texttt{m}_{00}}\f] - -The normalized central moments \f$\texttt{Moments::nu}_{ij}\f$ are computed as: - -\f[\texttt{nu} _{ji}= \frac{\texttt{mu}_{ji}}{\texttt{m}_{00}^{(i+j)/2+1}} .\f] - -@note -\f$\texttt{mu}_{00}=\texttt{m}_{00}\f$, \f$\texttt{nu}_{00}=1\f$ -\f$\texttt{nu}_{10}=\texttt{mu}_{10}=\texttt{mu}_{01}=\texttt{mu}_{10}=0\f$ , hence the values are not -stored. - -The moments of a contour are defined in the same way but computed using the Green's formula (see -). So, due to a limited raster resolution, the moments -computed for a contour are slightly different from the moments computed for the same rasterized -contour. - -@note -Since the contour moments are computed using Green formula, you may get seemingly odd results for -contours with self-intersections, e.g. a zero area (m00) for butterfly-shaped contours. - */ -class CV_EXPORTS_W_MAP Moments -{ -public: - //! the default constructor - Moments(); - //! the full constructor - Moments(double m00, double m10, double m01, double m20, double m11, - double m02, double m30, double m21, double m12, double m03 ); - ////! the conversion from CvMoments - //Moments( const CvMoments& moments ); - ////! the conversion to CvMoments - //operator CvMoments() const; - - //! @name spatial moments - //! @{ - CV_PROP_RW double m00, m10, m01, m20, m11, m02, m30, m21, m12, m03; - //! @} - - //! @name central moments - //! @{ - CV_PROP_RW double mu20, mu11, mu02, mu30, mu21, mu12, mu03; - //! @} - - //! @name central normalized moments - //! @{ - CV_PROP_RW double nu20, nu11, nu02, nu30, nu21, nu12, nu03; - //! @} -}; - -template<> class DataType -{ -public: - typedef Moments value_type; - typedef double work_type; - typedef double channel_type; - - enum { generic_type = 0, - channels = (int)(sizeof(value_type)/sizeof(channel_type)), // 24 - fmt = DataType::fmt + ((channels - 1) << 8) -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - ,depth = DataType::depth - ,type = CV_MAKETYPE(depth, channels) -#endif - }; - - typedef Vec vec_type; -}; - -namespace traits { -template<> -struct Depth< Moments > { enum { value = Depth::value }; }; -template<> -struct Type< Moments > { enum { value = CV_MAKETYPE(Depth::value, (int)(sizeof(Moments)/sizeof(double))) }; }; -} // namespace - -//! @} imgproc_shape - -//! @cond IGNORED - -///////////////////////////////////////////////////////////////////////// -///////////////////////////// Implementation //////////////////////////// -///////////////////////////////////////////////////////////////////////// - -//////////////////////////////// Complex //////////////////////////////// - -template inline -Complex<_Tp>::Complex() - : re(0), im(0) {} - -template inline -Complex<_Tp>::Complex( _Tp _re, _Tp _im ) - : re(_re), im(_im) {} - -template template inline -Complex<_Tp>::operator Complex() const -{ - return Complex(saturate_cast(re), saturate_cast(im)); -} - -template inline -Complex<_Tp> Complex<_Tp>::conj() const -{ - return Complex<_Tp>(re, -im); -} - - -template static inline -bool operator == (const Complex<_Tp>& a, const Complex<_Tp>& b) -{ - return a.re == b.re && a.im == b.im; -} - -template static inline -bool operator != (const Complex<_Tp>& a, const Complex<_Tp>& b) -{ - return a.re != b.re || a.im != b.im; -} - -template static inline -Complex<_Tp> operator + (const Complex<_Tp>& a, const Complex<_Tp>& b) -{ - return Complex<_Tp>( a.re + b.re, a.im + b.im ); -} - -template static inline -Complex<_Tp>& operator += (Complex<_Tp>& a, const Complex<_Tp>& b) -{ - a.re += b.re; a.im += b.im; - return a; -} - -template static inline -Complex<_Tp> operator - (const Complex<_Tp>& a, const Complex<_Tp>& b) -{ - return Complex<_Tp>( a.re - b.re, a.im - b.im ); -} - -template static inline -Complex<_Tp>& operator -= (Complex<_Tp>& a, const Complex<_Tp>& b) -{ - a.re -= b.re; a.im -= b.im; - return a; -} - -template static inline -Complex<_Tp> operator - (const Complex<_Tp>& a) -{ - return Complex<_Tp>(-a.re, -a.im); -} - -template static inline -Complex<_Tp> operator * (const Complex<_Tp>& a, const Complex<_Tp>& b) -{ - return Complex<_Tp>( a.re*b.re - a.im*b.im, a.re*b.im + a.im*b.re ); -} - -template static inline -Complex<_Tp> operator * (const Complex<_Tp>& a, _Tp b) -{ - return Complex<_Tp>( a.re*b, a.im*b ); -} - -template static inline -Complex<_Tp> operator * (_Tp b, const Complex<_Tp>& a) -{ - return Complex<_Tp>( a.re*b, a.im*b ); -} - -template static inline -Complex<_Tp> operator + (const Complex<_Tp>& a, _Tp b) -{ - return Complex<_Tp>( a.re + b, a.im ); -} - -template static inline -Complex<_Tp> operator - (const Complex<_Tp>& a, _Tp b) -{ return Complex<_Tp>( a.re - b, a.im ); } - -template static inline -Complex<_Tp> operator + (_Tp b, const Complex<_Tp>& a) -{ - return Complex<_Tp>( a.re + b, a.im ); -} - -template static inline -Complex<_Tp> operator - (_Tp b, const Complex<_Tp>& a) -{ - return Complex<_Tp>( b - a.re, -a.im ); -} - -template static inline -Complex<_Tp>& operator += (Complex<_Tp>& a, _Tp b) -{ - a.re += b; return a; -} - -template static inline -Complex<_Tp>& operator -= (Complex<_Tp>& a, _Tp b) -{ - a.re -= b; return a; -} - -template static inline -Complex<_Tp>& operator *= (Complex<_Tp>& a, _Tp b) -{ - a.re *= b; a.im *= b; return a; -} - -template static inline -double abs(const Complex<_Tp>& a) -{ - return std::sqrt( (double)a.re*a.re + (double)a.im*a.im); -} - -template static inline -Complex<_Tp> operator / (const Complex<_Tp>& a, const Complex<_Tp>& b) -{ - double t = 1./((double)b.re*b.re + (double)b.im*b.im); - return Complex<_Tp>( (_Tp)((a.re*b.re + a.im*b.im)*t), - (_Tp)((-a.re*b.im + a.im*b.re)*t) ); -} - -template static inline -Complex<_Tp>& operator /= (Complex<_Tp>& a, const Complex<_Tp>& b) -{ - a = a / b; - return a; -} - -template static inline -Complex<_Tp> operator / (const Complex<_Tp>& a, _Tp b) -{ - _Tp t = (_Tp)1/b; - return Complex<_Tp>( a.re*t, a.im*t ); -} - -template static inline -Complex<_Tp> operator / (_Tp b, const Complex<_Tp>& a) -{ - return Complex<_Tp>(b)/a; -} - -template static inline -Complex<_Tp> operator /= (const Complex<_Tp>& a, _Tp b) -{ - _Tp t = (_Tp)1/b; - a.re *= t; a.im *= t; return a; -} - - - -//////////////////////////////// 2D Point /////////////////////////////// - -template inline -Point_<_Tp>::Point_() - : x(0), y(0) {} - -template inline -Point_<_Tp>::Point_(_Tp _x, _Tp _y) - : x(_x), y(_y) {} - -#if (defined(__GNUC__) && __GNUC__ < 5) && !defined(__clang__) // GCC 4.x bug. Details: https://github.com/opencv/opencv/pull/20837 -template inline -Point_<_Tp>::Point_(const Point_& pt) - : x(pt.x), y(pt.y) {} -#endif - -template inline -Point_<_Tp>::Point_(const Size_<_Tp>& sz) - : x(sz.width), y(sz.height) {} - -template inline -Point_<_Tp>::Point_(const Vec<_Tp,2>& v) - : x(v[0]), y(v[1]) {} - -#if (defined(__GNUC__) && __GNUC__ < 5) && !defined(__clang__) // GCC 4.x bug. Details: https://github.com/opencv/opencv/pull/20837 -template inline -Point_<_Tp>& Point_<_Tp>::operator = (const Point_& pt) -{ - x = pt.x; y = pt.y; - return *this; -} -#endif - -template template inline -Point_<_Tp>::operator Point_<_Tp2>() const -{ - return Point_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y)); -} - -template inline -Point_<_Tp>::operator Vec<_Tp, 2>() const -{ - return Vec<_Tp, 2>(x, y); -} - -template inline -_Tp Point_<_Tp>::dot(const Point_& pt) const -{ - return saturate_cast<_Tp>(x*pt.x + y*pt.y); -} - -template inline -double Point_<_Tp>::ddot(const Point_& pt) const -{ - return (double)x*(double)(pt.x) + (double)y*(double)(pt.y); -} - -template inline -double Point_<_Tp>::cross(const Point_& pt) const -{ - return (double)x*pt.y - (double)y*pt.x; -} - -template inline bool -Point_<_Tp>::inside( const Rect_<_Tp>& r ) const -{ - return r.contains(*this); -} - - -template static inline -Point_<_Tp>& operator += (Point_<_Tp>& a, const Point_<_Tp>& b) -{ - a.x += b.x; - a.y += b.y; - return a; -} - -template static inline -Point_<_Tp>& operator -= (Point_<_Tp>& a, const Point_<_Tp>& b) -{ - a.x -= b.x; - a.y -= b.y; - return a; -} - -template static inline -Point_<_Tp>& operator *= (Point_<_Tp>& a, int b) -{ - a.x = saturate_cast<_Tp>(a.x * b); - a.y = saturate_cast<_Tp>(a.y * b); - return a; -} - -template static inline -Point_<_Tp>& operator *= (Point_<_Tp>& a, float b) -{ - a.x = saturate_cast<_Tp>(a.x * b); - a.y = saturate_cast<_Tp>(a.y * b); - return a; -} - -template static inline -Point_<_Tp>& operator *= (Point_<_Tp>& a, double b) -{ - a.x = saturate_cast<_Tp>(a.x * b); - a.y = saturate_cast<_Tp>(a.y * b); - return a; -} - -template static inline -Point_<_Tp>& operator /= (Point_<_Tp>& a, int b) -{ - a.x = saturate_cast<_Tp>(a.x / b); - a.y = saturate_cast<_Tp>(a.y / b); - return a; -} - -template static inline -Point_<_Tp>& operator /= (Point_<_Tp>& a, float b) -{ - a.x = saturate_cast<_Tp>(a.x / b); - a.y = saturate_cast<_Tp>(a.y / b); - return a; -} - -template static inline -Point_<_Tp>& operator /= (Point_<_Tp>& a, double b) -{ - a.x = saturate_cast<_Tp>(a.x / b); - a.y = saturate_cast<_Tp>(a.y / b); - return a; -} - -template static inline -double norm(const Point_<_Tp>& pt) -{ - return std::sqrt((double)pt.x*pt.x + (double)pt.y*pt.y); -} - -template static inline -bool operator == (const Point_<_Tp>& a, const Point_<_Tp>& b) -{ - return a.x == b.x && a.y == b.y; -} - -template static inline -bool operator != (const Point_<_Tp>& a, const Point_<_Tp>& b) -{ - return a.x != b.x || a.y != b.y; -} - -template static inline -Point_<_Tp> operator + (const Point_<_Tp>& a, const Point_<_Tp>& b) -{ - return Point_<_Tp>( saturate_cast<_Tp>(a.x + b.x), saturate_cast<_Tp>(a.y + b.y) ); -} - -template static inline -Point_<_Tp> operator - (const Point_<_Tp>& a, const Point_<_Tp>& b) -{ - return Point_<_Tp>( saturate_cast<_Tp>(a.x - b.x), saturate_cast<_Tp>(a.y - b.y) ); -} - -template static inline -Point_<_Tp> operator - (const Point_<_Tp>& a) -{ - return Point_<_Tp>( saturate_cast<_Tp>(-a.x), saturate_cast<_Tp>(-a.y) ); -} - -template static inline -Point_<_Tp> operator * (const Point_<_Tp>& a, int b) -{ - return Point_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b) ); -} - -template static inline -Point_<_Tp> operator * (int a, const Point_<_Tp>& b) -{ - return Point_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a) ); -} - -template static inline -Point_<_Tp> operator * (const Point_<_Tp>& a, float b) -{ - return Point_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b) ); -} - -template static inline -Point_<_Tp> operator * (float a, const Point_<_Tp>& b) -{ - return Point_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a) ); -} - -template static inline -Point_<_Tp> operator * (const Point_<_Tp>& a, double b) -{ - return Point_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b) ); -} - -template static inline -Point_<_Tp> operator * (double a, const Point_<_Tp>& b) -{ - return Point_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a) ); -} - -template static inline -Point_<_Tp> operator * (const Matx<_Tp, 2, 2>& a, const Point_<_Tp>& b) -{ - Matx<_Tp, 2, 1> tmp = a * Vec<_Tp,2>(b.x, b.y); - return Point_<_Tp>(tmp.val[0], tmp.val[1]); -} - -template static inline -Point3_<_Tp> operator * (const Matx<_Tp, 3, 3>& a, const Point_<_Tp>& b) -{ - Matx<_Tp, 3, 1> tmp = a * Vec<_Tp,3>(b.x, b.y, 1); - return Point3_<_Tp>(tmp.val[0], tmp.val[1], tmp.val[2]); -} - -template static inline -Point_<_Tp> operator / (const Point_<_Tp>& a, int b) -{ - Point_<_Tp> tmp(a); - tmp /= b; - return tmp; -} - -template static inline -Point_<_Tp> operator / (const Point_<_Tp>& a, float b) -{ - Point_<_Tp> tmp(a); - tmp /= b; - return tmp; -} - -template static inline -Point_<_Tp> operator / (const Point_<_Tp>& a, double b) -{ - Point_<_Tp> tmp(a); - tmp /= b; - return tmp; -} - - -template static inline _AccTp normL2Sqr(const Point_& pt); -template static inline _AccTp normL2Sqr(const Point_& pt); -template static inline _AccTp normL2Sqr(const Point_& pt); -template static inline _AccTp normL2Sqr(const Point_& pt); - -template<> inline int normL2Sqr(const Point_& pt) { return pt.dot(pt); } -template<> inline int64 normL2Sqr(const Point_& pt) { return pt.dot(pt); } -template<> inline float normL2Sqr(const Point_& pt) { return pt.dot(pt); } -template<> inline double normL2Sqr(const Point_& pt) { return pt.dot(pt); } - -template<> inline double normL2Sqr(const Point_& pt) { return pt.ddot(pt); } -template<> inline double normL2Sqr(const Point_& pt) { return pt.ddot(pt); } - - - -//////////////////////////////// 3D Point /////////////////////////////// - -template inline -Point3_<_Tp>::Point3_() - : x(0), y(0), z(0) {} - -template inline -Point3_<_Tp>::Point3_(_Tp _x, _Tp _y, _Tp _z) - : x(_x), y(_y), z(_z) {} - -template inline -Point3_<_Tp>::Point3_(const Point_<_Tp>& pt) - : x(pt.x), y(pt.y), z(_Tp()) {} - -template inline -Point3_<_Tp>::Point3_(const Vec<_Tp, 3>& v) - : x(v[0]), y(v[1]), z(v[2]) {} - -template template inline -Point3_<_Tp>::operator Point3_<_Tp2>() const -{ - return Point3_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y), saturate_cast<_Tp2>(z)); -} - -template inline -Point3_<_Tp>::operator Vec<_Tp, 3>() const -{ - return Vec<_Tp, 3>(x, y, z); -} - -template inline -_Tp Point3_<_Tp>::dot(const Point3_& pt) const -{ - return saturate_cast<_Tp>(x*pt.x + y*pt.y + z*pt.z); -} - -template inline -double Point3_<_Tp>::ddot(const Point3_& pt) const -{ - return (double)x*pt.x + (double)y*pt.y + (double)z*pt.z; -} - -template inline -Point3_<_Tp> Point3_<_Tp>::cross(const Point3_<_Tp>& pt) const -{ - return Point3_<_Tp>(y*pt.z - z*pt.y, z*pt.x - x*pt.z, x*pt.y - y*pt.x); -} - - -template static inline -Point3_<_Tp>& operator += (Point3_<_Tp>& a, const Point3_<_Tp>& b) -{ - a.x += b.x; - a.y += b.y; - a.z += b.z; - return a; -} - -template static inline -Point3_<_Tp>& operator -= (Point3_<_Tp>& a, const Point3_<_Tp>& b) -{ - a.x -= b.x; - a.y -= b.y; - a.z -= b.z; - return a; -} - -template static inline -Point3_<_Tp>& operator *= (Point3_<_Tp>& a, int b) -{ - a.x = saturate_cast<_Tp>(a.x * b); - a.y = saturate_cast<_Tp>(a.y * b); - a.z = saturate_cast<_Tp>(a.z * b); - return a; -} - -template static inline -Point3_<_Tp>& operator *= (Point3_<_Tp>& a, float b) -{ - a.x = saturate_cast<_Tp>(a.x * b); - a.y = saturate_cast<_Tp>(a.y * b); - a.z = saturate_cast<_Tp>(a.z * b); - return a; -} - -template static inline -Point3_<_Tp>& operator *= (Point3_<_Tp>& a, double b) -{ - a.x = saturate_cast<_Tp>(a.x * b); - a.y = saturate_cast<_Tp>(a.y * b); - a.z = saturate_cast<_Tp>(a.z * b); - return a; -} - -template static inline -Point3_<_Tp>& operator /= (Point3_<_Tp>& a, int b) -{ - a.x = saturate_cast<_Tp>(a.x / b); - a.y = saturate_cast<_Tp>(a.y / b); - a.z = saturate_cast<_Tp>(a.z / b); - return a; -} - -template static inline -Point3_<_Tp>& operator /= (Point3_<_Tp>& a, float b) -{ - a.x = saturate_cast<_Tp>(a.x / b); - a.y = saturate_cast<_Tp>(a.y / b); - a.z = saturate_cast<_Tp>(a.z / b); - return a; -} - -template static inline -Point3_<_Tp>& operator /= (Point3_<_Tp>& a, double b) -{ - a.x = saturate_cast<_Tp>(a.x / b); - a.y = saturate_cast<_Tp>(a.y / b); - a.z = saturate_cast<_Tp>(a.z / b); - return a; -} - -template static inline -double norm(const Point3_<_Tp>& pt) -{ - return std::sqrt((double)pt.x*pt.x + (double)pt.y*pt.y + (double)pt.z*pt.z); -} - -template static inline -bool operator == (const Point3_<_Tp>& a, const Point3_<_Tp>& b) -{ - return a.x == b.x && a.y == b.y && a.z == b.z; -} - -template static inline -bool operator != (const Point3_<_Tp>& a, const Point3_<_Tp>& b) -{ - return a.x != b.x || a.y != b.y || a.z != b.z; -} - -template static inline -Point3_<_Tp> operator + (const Point3_<_Tp>& a, const Point3_<_Tp>& b) -{ - return Point3_<_Tp>( saturate_cast<_Tp>(a.x + b.x), saturate_cast<_Tp>(a.y + b.y), saturate_cast<_Tp>(a.z + b.z)); -} - -template static inline -Point3_<_Tp> operator - (const Point3_<_Tp>& a, const Point3_<_Tp>& b) -{ - return Point3_<_Tp>( saturate_cast<_Tp>(a.x - b.x), saturate_cast<_Tp>(a.y - b.y), saturate_cast<_Tp>(a.z - b.z)); -} - -template static inline -Point3_<_Tp> operator - (const Point3_<_Tp>& a) -{ - return Point3_<_Tp>( saturate_cast<_Tp>(-a.x), saturate_cast<_Tp>(-a.y), saturate_cast<_Tp>(-a.z) ); -} - -template static inline -Point3_<_Tp> operator * (const Point3_<_Tp>& a, int b) -{ - return Point3_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b), saturate_cast<_Tp>(a.z*b) ); -} - -template static inline -Point3_<_Tp> operator * (int a, const Point3_<_Tp>& b) -{ - return Point3_<_Tp>( saturate_cast<_Tp>(b.x * a), saturate_cast<_Tp>(b.y * a), saturate_cast<_Tp>(b.z * a) ); -} - -template static inline -Point3_<_Tp> operator * (const Point3_<_Tp>& a, float b) -{ - return Point3_<_Tp>( saturate_cast<_Tp>(a.x * b), saturate_cast<_Tp>(a.y * b), saturate_cast<_Tp>(a.z * b) ); -} - -template static inline -Point3_<_Tp> operator * (float a, const Point3_<_Tp>& b) -{ - return Point3_<_Tp>( saturate_cast<_Tp>(b.x * a), saturate_cast<_Tp>(b.y * a), saturate_cast<_Tp>(b.z * a) ); -} - -template static inline -Point3_<_Tp> operator * (const Point3_<_Tp>& a, double b) -{ - return Point3_<_Tp>( saturate_cast<_Tp>(a.x * b), saturate_cast<_Tp>(a.y * b), saturate_cast<_Tp>(a.z * b) ); -} - -template static inline -Point3_<_Tp> operator * (double a, const Point3_<_Tp>& b) -{ - return Point3_<_Tp>( saturate_cast<_Tp>(b.x * a), saturate_cast<_Tp>(b.y * a), saturate_cast<_Tp>(b.z * a) ); -} - -template static inline -Point3_<_Tp> operator * (const Matx<_Tp, 3, 3>& a, const Point3_<_Tp>& b) -{ - Matx<_Tp, 3, 1> tmp = a * Vec<_Tp,3>(b.x, b.y, b.z); - return Point3_<_Tp>(tmp.val[0], tmp.val[1], tmp.val[2]); -} - -template static inline -Matx<_Tp, 4, 1> operator * (const Matx<_Tp, 4, 4>& a, const Point3_<_Tp>& b) -{ - return a * Matx<_Tp, 4, 1>(b.x, b.y, b.z, 1); -} - -template static inline -Point3_<_Tp> operator / (const Point3_<_Tp>& a, int b) -{ - Point3_<_Tp> tmp(a); - tmp /= b; - return tmp; -} - -template static inline -Point3_<_Tp> operator / (const Point3_<_Tp>& a, float b) -{ - Point3_<_Tp> tmp(a); - tmp /= b; - return tmp; -} - -template static inline -Point3_<_Tp> operator / (const Point3_<_Tp>& a, double b) -{ - Point3_<_Tp> tmp(a); - tmp /= b; - return tmp; -} - - - -////////////////////////////////// Size ///////////////////////////////// - -template inline -Size_<_Tp>::Size_() - : width(0), height(0) {} - -template inline -Size_<_Tp>::Size_(_Tp _width, _Tp _height) - : width(_width), height(_height) {} - -template inline -Size_<_Tp>::Size_(const Point_<_Tp>& pt) - : width(pt.x), height(pt.y) {} - -template template inline -Size_<_Tp>::operator Size_<_Tp2>() const -{ - return Size_<_Tp2>(saturate_cast<_Tp2>(width), saturate_cast<_Tp2>(height)); -} - -template inline -_Tp Size_<_Tp>::area() const -{ - const _Tp result = width * height; - CV_DbgAssert(!std::numeric_limits<_Tp>::is_integer - || width == 0 || result / width == height); // make sure the result fits in the return value - return result; -} - -template inline -double Size_<_Tp>::aspectRatio() const -{ - return width / static_cast(height); -} - -template inline -bool Size_<_Tp>::empty() const -{ - return width <= 0 || height <= 0; -} - - -template static inline -Size_<_Tp>& operator *= (Size_<_Tp>& a, _Tp b) -{ - a.width *= b; - a.height *= b; - return a; -} - -template static inline -Size_<_Tp> operator * (const Size_<_Tp>& a, _Tp b) -{ - Size_<_Tp> tmp(a); - tmp *= b; - return tmp; -} - -template static inline -Size_<_Tp>& operator /= (Size_<_Tp>& a, _Tp b) -{ - a.width /= b; - a.height /= b; - return a; -} - -template static inline -Size_<_Tp> operator / (const Size_<_Tp>& a, _Tp b) -{ - Size_<_Tp> tmp(a); - tmp /= b; - return tmp; -} - -template static inline -Size_<_Tp>& operator += (Size_<_Tp>& a, const Size_<_Tp>& b) -{ - a.width += b.width; - a.height += b.height; - return a; -} - -template static inline -Size_<_Tp> operator + (const Size_<_Tp>& a, const Size_<_Tp>& b) -{ - Size_<_Tp> tmp(a); - tmp += b; - return tmp; -} - -template static inline -Size_<_Tp>& operator -= (Size_<_Tp>& a, const Size_<_Tp>& b) -{ - a.width -= b.width; - a.height -= b.height; - return a; -} - -template static inline -Size_<_Tp> operator - (const Size_<_Tp>& a, const Size_<_Tp>& b) -{ - Size_<_Tp> tmp(a); - tmp -= b; - return tmp; -} - -template static inline -bool operator == (const Size_<_Tp>& a, const Size_<_Tp>& b) -{ - return a.width == b.width && a.height == b.height; -} - -template static inline -bool operator != (const Size_<_Tp>& a, const Size_<_Tp>& b) -{ - return !(a == b); -} - - - -////////////////////////////////// Rect ///////////////////////////////// - -template inline -Rect_<_Tp>::Rect_() - : x(0), y(0), width(0), height(0) {} - -template inline -Rect_<_Tp>::Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height) - : x(_x), y(_y), width(_width), height(_height) {} - -template inline -Rect_<_Tp>::Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz) - : x(org.x), y(org.y), width(sz.width), height(sz.height) {} - -template inline -Rect_<_Tp>::Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2) -{ - x = std::min(pt1.x, pt2.x); - y = std::min(pt1.y, pt2.y); - width = std::max(pt1.x, pt2.x) - x; - height = std::max(pt1.y, pt2.y) - y; -} - -template inline -Point_<_Tp> Rect_<_Tp>::tl() const -{ - return Point_<_Tp>(x,y); -} - -template inline -Point_<_Tp> Rect_<_Tp>::br() const -{ - return Point_<_Tp>(x + width, y + height); -} - -template inline -Size_<_Tp> Rect_<_Tp>::size() const -{ - return Size_<_Tp>(width, height); -} - -template inline -_Tp Rect_<_Tp>::area() const -{ - const _Tp result = width * height; - CV_DbgAssert(!std::numeric_limits<_Tp>::is_integer - || width == 0 || result / width == height); // make sure the result fits in the return value - return result; -} - -template inline -bool Rect_<_Tp>::empty() const -{ - return width <= 0 || height <= 0; -} - -template template inline -Rect_<_Tp>::operator Rect_<_Tp2>() const -{ - return Rect_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y), saturate_cast<_Tp2>(width), saturate_cast<_Tp2>(height)); -} - -template template inline -bool Rect_<_Tp>::contains(const Point_<_Tp2>& pt) const -{ - return x <= pt.x && pt.x < x + width && y <= pt.y && pt.y < y + height; -} -// See https://github.com/opencv/opencv/issues/26016 -template<> template<> inline -bool Rect_::contains(const Point_& pt) const -{ - // std::numeric_limits::digits is 31. - // std::numeric_limits::digits is 53. - // So conversion int->double does not lead to accuracy errors. - const Rect_ _rect(static_cast(x), static_cast(y), static_cast(width), static_cast(height)); - return _rect.contains(pt); -} -template<> template<> inline -bool Rect_::contains(const Point_& _pt) const -{ - // std::numeric_limits::digits is 24. - // std::numeric_limits::digits is 53. - // So conversion float->double does not lead to accuracy errors. - return contains(Point_(static_cast(_pt.x), static_cast(_pt.y))); -} - -template static inline -Rect_<_Tp>& operator += ( Rect_<_Tp>& a, const Point_<_Tp>& b ) -{ - a.x += b.x; - a.y += b.y; - return a; -} - -template static inline -Rect_<_Tp>& operator -= ( Rect_<_Tp>& a, const Point_<_Tp>& b ) -{ - a.x -= b.x; - a.y -= b.y; - return a; -} - -template static inline -Rect_<_Tp>& operator += ( Rect_<_Tp>& a, const Size_<_Tp>& b ) -{ - a.width += b.width; - a.height += b.height; - return a; -} - -template static inline -Rect_<_Tp>& operator -= ( Rect_<_Tp>& a, const Size_<_Tp>& b ) -{ - const _Tp width = a.width - b.width; - const _Tp height = a.height - b.height; - CV_DbgAssert(width >= 0 && height >= 0); - a.width = width; - a.height = height; - return a; -} - -template static inline -Rect_<_Tp>& operator &= ( Rect_<_Tp>& a, const Rect_<_Tp>& b ) -{ - if (a.empty() || b.empty()) { - a = Rect(); - return a; - } - const Rect_<_Tp>& Rx_min = (a.x < b.x) ? a : b; - const Rect_<_Tp>& Rx_max = (a.x < b.x) ? b : a; - const Rect_<_Tp>& Ry_min = (a.y < b.y) ? a : b; - const Rect_<_Tp>& Ry_max = (a.y < b.y) ? b : a; - // Looking at the formula below, we will compute Rx_min.width - (Rx_max.x - Rx_min.x) - // but we want to avoid overflows. Rx_min.width >= 0 and (Rx_max.x - Rx_min.x) >= 0 - // by definition so the difference does not overflow. The only thing that can overflow - // is (Rx_max.x - Rx_min.x). And it can only overflow if Rx_min.x < 0. - // Let us first deal with the following case. - if ((Rx_min.x < 0 && Rx_min.x + Rx_min.width < Rx_max.x) || - (Ry_min.y < 0 && Ry_min.y + Ry_min.height < Ry_max.y)) { - a = Rect(); - return a; - } - // We now know that either Rx_min.x >= 0, or - // Rx_min.x < 0 && Rx_min.x + Rx_min.width >= Rx_max.x and therefore - // Rx_min.width >= (Rx_max.x - Rx_min.x) which means (Rx_max.x - Rx_min.x) - // is inferior to a valid int and therefore does not overflow. - a.width = std::min(Rx_min.width - (Rx_max.x - Rx_min.x), Rx_max.width); - a.height = std::min(Ry_min.height - (Ry_max.y - Ry_min.y), Ry_max.height); - a.x = Rx_max.x; - a.y = Ry_max.y; - if (a.empty()) - a = Rect(); - return a; -} - -template static inline -Rect_<_Tp>& operator |= ( Rect_<_Tp>& a, const Rect_<_Tp>& b ) -{ - if (a.empty()) { - a = b; - } - else if (!b.empty()) { - _Tp x1 = std::min(a.x, b.x); - _Tp y1 = std::min(a.y, b.y); - a.width = std::max(a.x + a.width, b.x + b.width) - x1; - a.height = std::max(a.y + a.height, b.y + b.height) - y1; - a.x = x1; - a.y = y1; - } - return a; -} - -template static inline -bool operator == (const Rect_<_Tp>& a, const Rect_<_Tp>& b) -{ - return a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height; -} - -template static inline -bool operator != (const Rect_<_Tp>& a, const Rect_<_Tp>& b) -{ - return a.x != b.x || a.y != b.y || a.width != b.width || a.height != b.height; -} - -template static inline -Rect_<_Tp> operator + (const Rect_<_Tp>& a, const Point_<_Tp>& b) -{ - return Rect_<_Tp>( a.x + b.x, a.y + b.y, a.width, a.height ); -} - -template static inline -Rect_<_Tp> operator - (const Rect_<_Tp>& a, const Point_<_Tp>& b) -{ - return Rect_<_Tp>( a.x - b.x, a.y - b.y, a.width, a.height ); -} - -template static inline -Rect_<_Tp> operator + (const Rect_<_Tp>& a, const Size_<_Tp>& b) -{ - return Rect_<_Tp>( a.x, a.y, a.width + b.width, a.height + b.height ); -} - -template static inline -Rect_<_Tp> operator - (const Rect_<_Tp>& a, const Size_<_Tp>& b) -{ - const _Tp width = a.width - b.width; - const _Tp height = a.height - b.height; - CV_DbgAssert(width >= 0 && height >= 0); - return Rect_<_Tp>( a.x, a.y, width, height ); -} - -template static inline -Rect_<_Tp> operator & (const Rect_<_Tp>& a, const Rect_<_Tp>& b) -{ - Rect_<_Tp> c = a; - return c &= b; -} - -template static inline -Rect_<_Tp> operator | (const Rect_<_Tp>& a, const Rect_<_Tp>& b) -{ - Rect_<_Tp> c = a; - return c |= b; -} - -/** - * @brief measure dissimilarity between two sample sets - * - * computes the complement of the Jaccard Index as described in . - * For rectangles this reduces to computing the intersection over the union. - */ -template static inline -double jaccardDistance(const Rect_<_Tp>& a, const Rect_<_Tp>& b) { - _Tp Aa = a.area(); - _Tp Ab = b.area(); - - if ((Aa + Ab) <= std::numeric_limits<_Tp>::epsilon()) { - // jaccard_index = 1 -> distance = 0 - return 0.0; - } - - double Aab = (a & b).area(); - // distance = 1 - jaccard_index - return 1.0 - Aab / (Aa + Ab - Aab); -} - -/** @brief Finds out if there is any intersection between two rectangles - * - * mainly useful for language bindings - * @param a First rectangle - * @param b Second rectangle - * @return the area of the intersection - */ -CV_EXPORTS_W inline double rectangleIntersectionArea(const Rect2d& a, const Rect2d& b) { return (a & b).area(); } - -////////////////////////////// RotatedRect ////////////////////////////// - -inline -RotatedRect::RotatedRect() - : center(), size(), angle(0) {} - -inline -RotatedRect::RotatedRect(const Point2f& _center, const Size2f& _size, float _angle) - : center(_center), size(_size), angle(_angle) {} - -///////////////////////////////// Range ///////////////////////////////// - -inline -Range::Range() - : start(0), end(0) {} - -inline -Range::Range(int _start, int _end) - : start(_start), end(_end) {} - -inline -int Range::size() const -{ - return end - start; -} - -inline -bool Range::empty() const -{ - return start == end; -} - -inline -Range Range::all() -{ - return Range(INT_MIN, INT_MAX); -} - - -static inline -bool operator == (const Range& r1, const Range& r2) -{ - return r1.start == r2.start && r1.end == r2.end; -} - -static inline -bool operator != (const Range& r1, const Range& r2) -{ - return !(r1 == r2); -} - -static inline -bool operator !(const Range& r) -{ - return r.start == r.end; -} - -static inline -Range operator & (const Range& r1, const Range& r2) -{ - Range r(std::max(r1.start, r2.start), std::min(r1.end, r2.end)); - r.end = std::max(r.end, r.start); - return r; -} - -static inline -Range& operator &= (Range& r1, const Range& r2) -{ - r1 = r1 & r2; - return r1; -} - -static inline -Range operator + (const Range& r1, int delta) -{ - return Range(r1.start + delta, r1.end + delta); -} - -static inline -Range operator + (int delta, const Range& r1) -{ - return Range(r1.start + delta, r1.end + delta); -} - -static inline -Range operator - (const Range& r1, int delta) -{ - return r1 + (-delta); -} - - - -///////////////////////////////// Scalar //////////////////////////////// - -template inline -Scalar_<_Tp>::Scalar_() -{ - this->val[0] = this->val[1] = this->val[2] = this->val[3] = 0; -} - -template inline -Scalar_<_Tp>::Scalar_(_Tp v0, _Tp v1, _Tp v2, _Tp v3) -{ - this->val[0] = v0; - this->val[1] = v1; - this->val[2] = v2; - this->val[3] = v3; -} - -template inline -Scalar_<_Tp>::Scalar_(const Scalar_<_Tp>& s) : Vec<_Tp, 4>(s) { -} - -template inline -Scalar_<_Tp>::Scalar_(Scalar_<_Tp>&& s) CV_NOEXCEPT { - this->val[0] = std::move(s.val[0]); - this->val[1] = std::move(s.val[1]); - this->val[2] = std::move(s.val[2]); - this->val[3] = std::move(s.val[3]); -} - -template inline -Scalar_<_Tp>& Scalar_<_Tp>::operator=(const Scalar_<_Tp>& s) { - this->val[0] = s.val[0]; - this->val[1] = s.val[1]; - this->val[2] = s.val[2]; - this->val[3] = s.val[3]; - return *this; -} - -template inline -Scalar_<_Tp>& Scalar_<_Tp>::operator=(Scalar_<_Tp>&& s) CV_NOEXCEPT { - this->val[0] = std::move(s.val[0]); - this->val[1] = std::move(s.val[1]); - this->val[2] = std::move(s.val[2]); - this->val[3] = std::move(s.val[3]); - return *this; -} - -template template inline -Scalar_<_Tp>::Scalar_(const Vec<_Tp2, cn>& v) -{ - int i; - for( i = 0; i < (cn < 4 ? cn : 4); i++ ) - this->val[i] = cv::saturate_cast<_Tp>(v.val[i]); - for( ; i < 4; i++ ) - this->val[i] = 0; -} - -template inline -Scalar_<_Tp>::Scalar_(_Tp v0) -{ - this->val[0] = v0; - this->val[1] = this->val[2] = this->val[3] = 0; -} - -template inline -Scalar_<_Tp> Scalar_<_Tp>::all(_Tp v0) -{ - return Scalar_<_Tp>(v0, v0, v0, v0); -} - - -template inline -Scalar_<_Tp> Scalar_<_Tp>::mul(const Scalar_<_Tp>& a, double scale ) const -{ - return Scalar_<_Tp>(saturate_cast<_Tp>(this->val[0] * a.val[0] * scale), - saturate_cast<_Tp>(this->val[1] * a.val[1] * scale), - saturate_cast<_Tp>(this->val[2] * a.val[2] * scale), - saturate_cast<_Tp>(this->val[3] * a.val[3] * scale)); -} - -template inline -Scalar_<_Tp> Scalar_<_Tp>::conj() const -{ - return Scalar_<_Tp>(saturate_cast<_Tp>( this->val[0]), - saturate_cast<_Tp>(-this->val[1]), - saturate_cast<_Tp>(-this->val[2]), - saturate_cast<_Tp>(-this->val[3])); -} - -template inline -bool Scalar_<_Tp>::isReal() const -{ - return this->val[1] == 0 && this->val[2] == 0 && this->val[3] == 0; -} - - -template template inline -Scalar_<_Tp>::operator Scalar_() const -{ - return Scalar_(saturate_cast(this->val[0]), - saturate_cast(this->val[1]), - saturate_cast(this->val[2]), - saturate_cast(this->val[3])); -} - - -template static inline -Scalar_<_Tp>& operator += (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) -{ - a.val[0] += b.val[0]; - a.val[1] += b.val[1]; - a.val[2] += b.val[2]; - a.val[3] += b.val[3]; - return a; -} - -template static inline -Scalar_<_Tp>& operator -= (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) -{ - a.val[0] -= b.val[0]; - a.val[1] -= b.val[1]; - a.val[2] -= b.val[2]; - a.val[3] -= b.val[3]; - return a; -} - -template static inline -Scalar_<_Tp>& operator *= ( Scalar_<_Tp>& a, _Tp v ) -{ - a.val[0] *= v; - a.val[1] *= v; - a.val[2] *= v; - a.val[3] *= v; - return a; -} - -template static inline -bool operator == ( const Scalar_<_Tp>& a, const Scalar_<_Tp>& b ) -{ - return a.val[0] == b.val[0] && a.val[1] == b.val[1] && - a.val[2] == b.val[2] && a.val[3] == b.val[3]; -} - -template static inline -bool operator != ( const Scalar_<_Tp>& a, const Scalar_<_Tp>& b ) -{ - return a.val[0] != b.val[0] || a.val[1] != b.val[1] || - a.val[2] != b.val[2] || a.val[3] != b.val[3]; -} - -template static inline -Scalar_<_Tp> operator + (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) -{ - return Scalar_<_Tp>(a.val[0] + b.val[0], - a.val[1] + b.val[1], - a.val[2] + b.val[2], - a.val[3] + b.val[3]); -} - -template static inline -Scalar_<_Tp> operator - (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) -{ - return Scalar_<_Tp>(saturate_cast<_Tp>(a.val[0] - b.val[0]), - saturate_cast<_Tp>(a.val[1] - b.val[1]), - saturate_cast<_Tp>(a.val[2] - b.val[2]), - saturate_cast<_Tp>(a.val[3] - b.val[3])); -} - -template static inline -Scalar_<_Tp> operator * (const Scalar_<_Tp>& a, _Tp alpha) -{ - return Scalar_<_Tp>(a.val[0] * alpha, - a.val[1] * alpha, - a.val[2] * alpha, - a.val[3] * alpha); -} - -template static inline -Scalar_<_Tp> operator * (_Tp alpha, const Scalar_<_Tp>& a) -{ - return a*alpha; -} - -template static inline -Scalar_<_Tp> operator - (const Scalar_<_Tp>& a) -{ - return Scalar_<_Tp>(saturate_cast<_Tp>(-a.val[0]), - saturate_cast<_Tp>(-a.val[1]), - saturate_cast<_Tp>(-a.val[2]), - saturate_cast<_Tp>(-a.val[3])); -} - - -template static inline -Scalar_<_Tp> operator * (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) -{ - return Scalar_<_Tp>(saturate_cast<_Tp>(a[0]*b[0] - a[1]*b[1] - a[2]*b[2] - a[3]*b[3]), - saturate_cast<_Tp>(a[0]*b[1] + a[1]*b[0] + a[2]*b[3] - a[3]*b[2]), - saturate_cast<_Tp>(a[0]*b[2] - a[1]*b[3] + a[2]*b[0] + a[3]*b[1]), - saturate_cast<_Tp>(a[0]*b[3] + a[1]*b[2] - a[2]*b[1] + a[3]*b[0])); -} - -template static inline -Scalar_<_Tp>& operator *= (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) -{ - a = a * b; - return a; -} - -template static inline -Scalar_<_Tp> operator / (const Scalar_<_Tp>& a, _Tp alpha) -{ - return Scalar_<_Tp>(a.val[0] / alpha, - a.val[1] / alpha, - a.val[2] / alpha, - a.val[3] / alpha); -} - -template static inline -Scalar_ operator / (const Scalar_& a, float alpha) -{ - float s = 1 / alpha; - return Scalar_(a.val[0] * s, a.val[1] * s, a.val[2] * s, a.val[3] * s); -} - -template static inline -Scalar_ operator / (const Scalar_& a, double alpha) -{ - double s = 1 / alpha; - return Scalar_(a.val[0] * s, a.val[1] * s, a.val[2] * s, a.val[3] * s); -} - -template static inline -Scalar_<_Tp>& operator /= (Scalar_<_Tp>& a, _Tp alpha) -{ - a = a / alpha; - return a; -} - -template static inline -Scalar_<_Tp> operator / (_Tp a, const Scalar_<_Tp>& b) -{ - _Tp s = a / (b[0]*b[0] + b[1]*b[1] + b[2]*b[2] + b[3]*b[3]); - return b.conj() * s; -} - -template static inline -Scalar_<_Tp> operator / (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) -{ - return a * ((_Tp)1 / b); -} - -template static inline -Scalar_<_Tp>& operator /= (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) -{ - a = a / b; - return a; -} - -template static inline -Scalar operator * (const Matx<_Tp, 4, 4>& a, const Scalar& b) -{ - Matx c((Matx)a, b, Matx_MatMulOp()); - return reinterpret_cast(c); -} - -template<> inline -Scalar operator * (const Matx& a, const Scalar& b) -{ - Matx c(a, b, Matx_MatMulOp()); - return reinterpret_cast(c); -} - - - -//////////////////////////////// KeyPoint /////////////////////////////// - -inline -KeyPoint::KeyPoint() - : pt(0,0), size(0), angle(-1), response(0), octave(0), class_id(-1) {} - -inline -KeyPoint::KeyPoint(Point2f _pt, float _size, float _angle, float _response, int _octave, int _class_id) - : pt(_pt), size(_size), angle(_angle), response(_response), octave(_octave), class_id(_class_id) {} - -inline -KeyPoint::KeyPoint(float x, float y, float _size, float _angle, float _response, int _octave, int _class_id) - : pt(x, y), size(_size), angle(_angle), response(_response), octave(_octave), class_id(_class_id) {} - - - -///////////////////////////////// DMatch //////////////////////////////// - -inline -DMatch::DMatch() - : queryIdx(-1), trainIdx(-1), imgIdx(-1), distance(FLT_MAX) {} - -inline -DMatch::DMatch(int _queryIdx, int _trainIdx, float _distance) - : queryIdx(_queryIdx), trainIdx(_trainIdx), imgIdx(-1), distance(_distance) {} - -inline -DMatch::DMatch(int _queryIdx, int _trainIdx, int _imgIdx, float _distance) - : queryIdx(_queryIdx), trainIdx(_trainIdx), imgIdx(_imgIdx), distance(_distance) {} - -inline -bool DMatch::operator < (const DMatch &m) const -{ - return distance < m.distance; -} - - - -////////////////////////////// TermCriteria ///////////////////////////// - -inline -TermCriteria::TermCriteria() - : type(0), maxCount(0), epsilon(0) {} - -inline -TermCriteria::TermCriteria(int _type, int _maxCount, double _epsilon) - : type(_type), maxCount(_maxCount), epsilon(_epsilon) {} - -//! @endcond - -} // cv - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -#endif //OPENCV_CORE_TYPES_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CORE_TYPES_HPP +#define OPENCV_CORE_TYPES_HPP + +#ifndef __cplusplus +# error types.hpp header must be compiled as C++ +#endif + +#include +#include +#include +#include + +#include "opencv2/core/cvdef.h" +#include "opencv2/core/cvstd.hpp" +#include "opencv2/core/matx.hpp" + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable: 4459) // declaration of '...' hides global declaration +#endif + +namespace cv +{ + +//! @addtogroup core_basic +//! @{ + +//////////////////////////////// Complex ////////////////////////////// + +/** @brief A complex number class. + + The template class is similar and compatible with std::complex, however it provides slightly + more convenient access to the real and imaginary parts using through the simple field access, as opposite + to std::complex::real() and std::complex::imag(). +*/ +template class Complex +{ +public: + + //! default constructor + Complex(); + Complex( _Tp _re, _Tp _im = 0 ); + + //! conversion to another data type + template operator Complex() const; + //! conjugation + Complex conj() const; + + _Tp re, im; ///< the real and the imaginary parts +}; + +typedef Complex Complexf; +typedef Complex Complexd; + +template class DataType< Complex<_Tp> > +{ +public: + typedef Complex<_Tp> value_type; + typedef value_type work_type; + typedef _Tp channel_type; + + enum { generic_type = 0, + channels = 2, + fmt = DataType::fmt + ((channels - 1) << 8) +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + ,depth = DataType::depth + ,type = CV_MAKETYPE(depth, channels) +#endif + }; + + typedef Vec vec_type; +}; + +namespace traits { +template +struct Depth< Complex<_Tp> > { enum { value = Depth<_Tp>::value }; }; +template +struct Type< Complex<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 2) }; }; +} // namespace + + +//////////////////////////////// Point_ //////////////////////////////// + +/** @brief Template class for 2D points specified by its coordinates `x` and `y`. + +An instance of the class is interchangeable with C structures, CvPoint and CvPoint2D32f . There is +also a cast operator to convert point coordinates to the specified type. The conversion from +floating-point coordinates to integer coordinates is done by rounding. Commonly, the conversion +uses this operation for each of the coordinates. Besides the class members listed in the +declaration above, the following operations on points are implemented: +@code + pt1 = pt2 + pt3; + pt1 = pt2 - pt3; + pt1 = pt2 * a; + pt1 = a * pt2; + pt1 = pt2 / a; + pt1 += pt2; + pt1 -= pt2; + pt1 *= a; + pt1 /= a; + double value = norm(pt); // L2 norm + pt1 == pt2; + pt1 != pt2; +@endcode +For your convenience, the following type aliases are defined: +@code + typedef Point_ Point2i; + typedef Point2i Point; + typedef Point_ Point2f; + typedef Point_ Point2d; +@endcode +Example: +@code + Point2f a(0.3f, 0.f), b(0.f, 0.4f); + Point pt = (a + b)*10.f; + cout << pt.x << ", " << pt.y << endl; +@endcode +*/ +template class Point_ +{ +public: + typedef _Tp value_type; + + //! default constructor + Point_(); + Point_(_Tp _x, _Tp _y); +#if (defined(__GNUC__) && __GNUC__ < 5) && !defined(__clang__) // GCC 4.x bug. Details: https://github.com/opencv/opencv/pull/20837 + Point_(const Point_& pt); + Point_(Point_&& pt) CV_NOEXCEPT = default; +#elif OPENCV_ABI_COMPATIBILITY < 500 + Point_(const Point_& pt) = default; + Point_(Point_&& pt) CV_NOEXCEPT = default; +#endif + Point_(const Size_<_Tp>& sz); + Point_(const Vec<_Tp, 2>& v); + +#if (defined(__GNUC__) && __GNUC__ < 5) && !defined(__clang__) // GCC 4.x bug. Details: https://github.com/opencv/opencv/pull/20837 + Point_& operator = (const Point_& pt); + Point_& operator = (Point_&& pt) CV_NOEXCEPT = default; +#elif OPENCV_ABI_COMPATIBILITY < 500 + Point_& operator = (const Point_& pt) = default; + Point_& operator = (Point_&& pt) CV_NOEXCEPT = default; +#endif + //! conversion to another data type + template operator Point_<_Tp2>() const; + + //! conversion to the old-style C structures + operator Vec<_Tp, 2>() const; + + //! dot product + _Tp dot(const Point_& pt) const; + //! dot product computed in double-precision arithmetics + double ddot(const Point_& pt) const; + //! cross-product + double cross(const Point_& pt) const; + //! checks whether the point is inside the specified rectangle + bool inside(const Rect_<_Tp>& r) const; + _Tp x; //!< x coordinate of the point + _Tp y; //!< y coordinate of the point +}; + +typedef Point_ Point2i; +typedef Point_ Point2l; +typedef Point_ Point2f; +typedef Point_ Point2d; +typedef Point2i Point; + +template class DataType< Point_<_Tp> > +{ +public: + typedef Point_<_Tp> value_type; + typedef Point_::work_type> work_type; + typedef _Tp channel_type; + + enum { generic_type = 0, + channels = 2, + fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + ,depth = DataType::depth + ,type = CV_MAKETYPE(depth, channels) +#endif + }; + + typedef Vec vec_type; +}; + +namespace traits { +template +struct Depth< Point_<_Tp> > { enum { value = Depth<_Tp>::value }; }; +template +struct Type< Point_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 2) }; }; +} // namespace + + +//////////////////////////////// Point3_ //////////////////////////////// + +/** @brief Template class for 3D points specified by its coordinates `x`, `y` and `z`. + +An instance of the class is interchangeable with the C structure CvPoint2D32f . Similarly to +Point_ , the coordinates of 3D points can be converted to another type. The vector arithmetic and +comparison operations are also supported. + +The following Point3_\<\> aliases are available: +@code + typedef Point3_ Point3i; + typedef Point3_ Point3f; + typedef Point3_ Point3d; +@endcode +@see cv::Point3i, cv::Point3f and cv::Point3d +*/ +template class Point3_ +{ +public: + typedef _Tp value_type; + + //! default constructor + Point3_(); + Point3_(_Tp _x, _Tp _y, _Tp _z); +#if OPENCV_ABI_COMPATIBILITY < 500 + Point3_(const Point3_& pt) = default; + Point3_(Point3_&& pt) CV_NOEXCEPT = default; +#endif + explicit Point3_(const Point_<_Tp>& pt); + Point3_(const Vec<_Tp, 3>& v); + +#if OPENCV_ABI_COMPATIBILITY < 500 + Point3_& operator = (const Point3_& pt) = default; + Point3_& operator = (Point3_&& pt) CV_NOEXCEPT = default; +#endif + //! conversion to another data type + template operator Point3_<_Tp2>() const; + //! conversion to cv::Vec<> + operator Vec<_Tp, 3>() const; + + //! dot product + _Tp dot(const Point3_& pt) const; + //! dot product computed in double-precision arithmetics + double ddot(const Point3_& pt) const; + //! cross product of the 2 3D points + Point3_ cross(const Point3_& pt) const; + _Tp x; //!< x coordinate of the 3D point + _Tp y; //!< y coordinate of the 3D point + _Tp z; //!< z coordinate of the 3D point +}; + +typedef Point3_ Point3i; +typedef Point3_ Point3f; +typedef Point3_ Point3d; + +template class DataType< Point3_<_Tp> > +{ +public: + typedef Point3_<_Tp> value_type; + typedef Point3_::work_type> work_type; + typedef _Tp channel_type; + + enum { generic_type = 0, + channels = 3, + fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + ,depth = DataType::depth + ,type = CV_MAKETYPE(depth, channels) +#endif + }; + + typedef Vec vec_type; +}; + +namespace traits { +template +struct Depth< Point3_<_Tp> > { enum { value = Depth<_Tp>::value }; }; +template +struct Type< Point3_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 3) }; }; +} // namespace + +//////////////////////////////// Size_ //////////////////////////////// + +/** @brief Template class for specifying the size of an image or rectangle. + +The class includes two members called width and height. The structure can be converted to and from +the old OpenCV structures CvSize and CvSize2D32f . The same set of arithmetic and comparison +operations as for Point_ is available. + +OpenCV defines the following Size_\<\> aliases: +@code + typedef Size_ Size2i; + typedef Size2i Size; + typedef Size_ Size2f; +@endcode +*/ +template class Size_ +{ +public: + typedef _Tp value_type; + + //! default constructor + Size_(); + Size_(_Tp _width, _Tp _height); +#if OPENCV_ABI_COMPATIBILITY < 500 + Size_(const Size_& sz) = default; + Size_(Size_&& sz) CV_NOEXCEPT = default; +#endif + Size_(const Point_<_Tp>& pt); + +#if OPENCV_ABI_COMPATIBILITY < 500 + Size_& operator = (const Size_& sz) = default; + Size_& operator = (Size_&& sz) CV_NOEXCEPT = default; +#endif + //! the area (width*height) + _Tp area() const; + //! aspect ratio (width/height) + double aspectRatio() const; + //! true if empty + bool empty() const; + + //! conversion of another data type. + template operator Size_<_Tp2>() const; + + _Tp width; //!< the width + _Tp height; //!< the height +}; + +typedef Size_ Size2i; +typedef Size_ Size2l; +typedef Size_ Size2f; +typedef Size_ Size2d; +typedef Size2i Size; + +template class DataType< Size_<_Tp> > +{ +public: + typedef Size_<_Tp> value_type; + typedef Size_::work_type> work_type; + typedef _Tp channel_type; + + enum { generic_type = 0, + channels = 2, + fmt = DataType::fmt + ((channels - 1) << 8) +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + ,depth = DataType::depth + ,type = CV_MAKETYPE(depth, channels) +#endif + }; + + typedef Vec vec_type; +}; + +namespace traits { +template +struct Depth< Size_<_Tp> > { enum { value = Depth<_Tp>::value }; }; +template +struct Type< Size_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 2) }; }; +} // namespace + +//////////////////////////////// Rect_ //////////////////////////////// + +/** @brief Template class for 2D rectangles + +described by the following parameters: +- Coordinates of the top-left corner. This is a default interpretation of Rect_::x and Rect_::y + in OpenCV. Though, in your algorithms you may count x and y from the bottom-left corner. +- Rectangle width and height. + +OpenCV typically assumes that the top and left boundary of the rectangle are inclusive, while the +right and bottom boundaries are not. For example, the method Rect_::contains returns true if + +\f[x \leq pt.x < x+width, + y \leq pt.y < y+height\f] + +Virtually every loop over an image ROI in OpenCV (where ROI is specified by Rect_\ ) is +implemented as: +@code + for(int y = roi.y; y < roi.y + roi.height; y++) + for(int x = roi.x; x < roi.x + roi.width; x++) + { + // ... + } +@endcode +In addition to the class members, the following operations on rectangles are implemented: +- \f$\texttt{rect} = \texttt{rect} \pm \texttt{point}\f$ (shifting a rectangle by a certain offset) +- \f$\texttt{rect} = \texttt{rect} \pm \texttt{size}\f$ (expanding or shrinking a rectangle by a + certain amount) +- rect += point, rect -= point, rect += size, rect -= size (augmenting operations) +- rect = rect1 & rect2 (rectangle intersection) +- rect = rect1 | rect2 (minimum area rectangle containing rect1 and rect2 ) +- rect &= rect1, rect |= rect1 (and the corresponding augmenting operations) +- rect == rect1, rect != rect1 (rectangle comparison) + +This is an example how the partial ordering on rectangles can be established (rect1 \f$\subseteq\f$ +rect2): +@code + template inline bool + operator <= (const Rect_<_Tp>& r1, const Rect_<_Tp>& r2) + { + return (r1 & r2) == r1; + } +@endcode +For your convenience, the Rect_\<\> alias is available: cv::Rect +*/ +template class Rect_ +{ +public: + typedef _Tp value_type; + + //! default constructor + Rect_(); + Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height); +#if OPENCV_ABI_COMPATIBILITY < 500 + Rect_(const Rect_& r) = default; + Rect_(Rect_&& r) CV_NOEXCEPT = default; +#endif + Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz); + Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2); + +#if OPENCV_ABI_COMPATIBILITY < 500 + Rect_& operator = (const Rect_& r) = default; + Rect_& operator = (Rect_&& r) CV_NOEXCEPT = default; +#endif + //! the top-left corner + Point_<_Tp> tl() const; + //! the bottom-right corner + Point_<_Tp> br() const; + + //! size (width, height) of the rectangle + Size_<_Tp> size() const; + //! area (width*height) of the rectangle + _Tp area() const; + //! true if empty + bool empty() const; + + //! conversion to another data type + template operator Rect_<_Tp2>() const; + + //! checks whether the rectangle contains the point + /*! @warning After OpenCV 4.11.0, when calling Rect.contains() with cv::Point2f / cv::Point2d point, point should not convert/round to int. + * ``` + * Rect_ r(0,0,500,500); Point_ pt(250.0f, 499.9f); + * r.contains(pt) returns false.(OpenCV 4.10.0 or before) + * r.contains(pt) returns true. (OpenCV 4.11.0 or later) + * ``` + */ + template inline bool contains(const Point_<_Tp2>& pt) const; + + _Tp x; //!< x coordinate of the top-left corner + _Tp y; //!< y coordinate of the top-left corner + _Tp width; //!< width of the rectangle + _Tp height; //!< height of the rectangle +}; + +typedef Rect_ Rect2i; +typedef Rect_ Rect2f; +typedef Rect_ Rect2d; +typedef Rect2i Rect; + +template class DataType< Rect_<_Tp> > +{ +public: + typedef Rect_<_Tp> value_type; + typedef Rect_::work_type> work_type; + typedef _Tp channel_type; + + enum { generic_type = 0, + channels = 4, + fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + ,depth = DataType::depth + ,type = CV_MAKETYPE(depth, channels) +#endif + }; + + typedef Vec vec_type; +}; + +namespace traits { +template +struct Depth< Rect_<_Tp> > { enum { value = Depth<_Tp>::value }; }; +template +struct Type< Rect_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 4) }; }; +} // namespace + +///////////////////////////// RotatedRect ///////////////////////////// + +/** @brief The class represents rotated (i.e. not up-right) rectangles on a plane. + +Each rectangle is specified by the center point (mass center), length of each side (represented by +#Size2f structure) and the rotation angle in degrees. + +The sample below demonstrates how to use RotatedRect: +@snippet snippets/core_various.cpp RotatedRect_demo +![image](pics/rotatedrect.png) + +@sa CamShift, fitEllipse, minAreaRect, CvBox2D +*/ +class CV_EXPORTS_W_SIMPLE RotatedRect +{ +public: + //! default constructor + CV_WRAP RotatedRect(); + /** full constructor + @param center The rectangle mass center. + @param size Width and height of the rectangle. + @param angle The rotation angle in a clockwise direction. When the angle is 0, 90, 180, 270 etc., + the rectangle becomes an up-right rectangle. + */ + CV_WRAP RotatedRect(const Point2f& center, const Size2f& size, float angle); + /** + Any 3 end points of the RotatedRect. They must be given in order (either clockwise or + anticlockwise). + */ + CV_WRAP RotatedRect(const Point2f& point1, const Point2f& point2, const Point2f& point3); + + /** returns 4 vertices of the rotated rectangle + @param pts The points array for storing rectangle vertices. The order is _bottomLeft_, _topLeft_, topRight, bottomRight. + @note _Bottom_, _Top_, _Left_ and _Right_ sides refer to the original rectangle (angle is 0), + so after 180 degree rotation _bottomLeft_ point will be located at the top right corner of the + rectangle. + */ + void points(Point2f pts[]) const; + + CV_WRAP void points(CV_OUT std::vector& pts) const; + + //! returns the minimal up-right integer rectangle containing the rotated rectangle + CV_WRAP Rect boundingRect() const; + //! returns the minimal (exact) floating point rectangle containing the rotated rectangle, not intended for use with images + CV_WRAP Rect2f boundingRect2f() const; + //! returns the rectangle mass center + CV_PROP_RW Point2f center; + //! returns width and height of the rectangle + CV_PROP_RW Size2f size; + //! returns the rotation angle. When the angle is 0, 90, 180, 270 etc., the rectangle becomes an up-right rectangle. + CV_PROP_RW float angle; +}; + +template<> class DataType< RotatedRect > +{ +public: + typedef RotatedRect value_type; + typedef value_type work_type; + typedef float channel_type; + + enum { generic_type = 0, + channels = (int)sizeof(value_type)/sizeof(channel_type), // 5 + fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + ,depth = DataType::depth + ,type = CV_MAKETYPE(depth, channels) +#endif + }; + + typedef Vec vec_type; +}; + +namespace traits { +template<> +struct Depth< RotatedRect > { enum { value = Depth::value }; }; +template<> +struct Type< RotatedRect > { enum { value = CV_MAKETYPE(Depth::value, (int)sizeof(RotatedRect)/sizeof(float)) }; }; +} // namespace + + +//////////////////////////////// Range ///////////////////////////////// + +/** @brief Template class specifying a continuous subsequence (slice) of a sequence. + +The class is used to specify a row or a column span in a matrix ( Mat ) and for many other purposes. +Range(a,b) is basically the same as a:b in Matlab or a..b in Python. As in Python, start is an +inclusive left boundary of the range and end is an exclusive right boundary of the range. Such a +half-opened interval is usually denoted as \f$[start,end)\f$ . + +The static method Range::all() returns a special variable that means "the whole sequence" or "the +whole range", just like " : " in Matlab or " ... " in Python. All the methods and functions in +OpenCV that take Range support this special Range::all() value. But, of course, in case of your own +custom processing, you will probably have to check and handle it explicitly: +@code + void my_function(..., const Range& r, ....) + { + if(r == Range::all()) { + // process all the data + } + else { + // process [r.start, r.end) + } + } +@endcode +*/ +class CV_EXPORTS Range +{ +public: + Range(); + Range(int _start, int _end); + int size() const; + bool empty() const; + static Range all(); + + int start, end; +}; + +template<> class DataType +{ +public: + typedef Range value_type; + typedef value_type work_type; + typedef int channel_type; + + enum { generic_type = 0, + channels = 2, + fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + ,depth = DataType::depth + ,type = CV_MAKETYPE(depth, channels) +#endif + }; + + typedef Vec vec_type; +}; + +namespace traits { +template<> +struct Depth< Range > { enum { value = Depth::value }; }; +template<> +struct Type< Range > { enum { value = CV_MAKETYPE(Depth::value, 2) }; }; +} // namespace + + +//////////////////////////////// Scalar_ /////////////////////////////// + +/** @brief Template class for a 4-element vector derived from Vec. + +Being derived from Vec\<_Tp, 4\> , Scalar\_ and Scalar can be used just as typical 4-element +vectors. In addition, they can be converted to/from CvScalar . The type Scalar is widely used in +OpenCV to pass pixel values. +*/ +template class Scalar_ : public Vec<_Tp, 4> +{ +public: + //! default constructor + Scalar_(); + Scalar_(_Tp v0, _Tp v1, _Tp v2=0, _Tp v3=0); + Scalar_(_Tp v0); + + Scalar_(const Scalar_& s); + Scalar_(Scalar_&& s) CV_NOEXCEPT; + + Scalar_& operator=(const Scalar_& s); + Scalar_& operator=(Scalar_&& s) CV_NOEXCEPT; + + template + Scalar_(const Vec<_Tp2, cn>& v); + + //! returns a scalar with all elements set to v0 + static Scalar_<_Tp> all(_Tp v0); + + //! conversion to another data type + template operator Scalar_() const; + + //! per-element product + Scalar_<_Tp> mul(const Scalar_<_Tp>& a, double scale=1 ) const; + + //! returns (v0, -v1, -v2, -v3) + Scalar_<_Tp> conj() const; + + //! returns true iff v1 == v2 == v3 == 0 + bool isReal() const; +}; + +typedef Scalar_ Scalar; + +template class DataType< Scalar_<_Tp> > +{ +public: + typedef Scalar_<_Tp> value_type; + typedef Scalar_::work_type> work_type; + typedef _Tp channel_type; + + enum { generic_type = 0, + channels = 4, + fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + ,depth = DataType::depth + ,type = CV_MAKETYPE(depth, channels) +#endif + }; + + typedef Vec vec_type; +}; + +namespace traits { +template +struct Depth< Scalar_<_Tp> > { enum { value = Depth<_Tp>::value }; }; +template +struct Type< Scalar_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 4) }; }; +} // namespace + + +/////////////////////////////// KeyPoint //////////////////////////////// + +/** @brief Data structure for salient point detectors. + +The class instance stores a keypoint, i.e. a point feature found by one of many available keypoint +detectors, such as Harris corner detector, #FAST, %StarDetector, %SURF, %SIFT etc. + +The keypoint is characterized by the 2D position, scale (proportional to the diameter of the +neighborhood that needs to be taken into account), orientation and some other parameters. The +keypoint neighborhood is then analyzed by another algorithm that builds a descriptor (usually +represented as a feature vector). The keypoints representing the same object in different images +can then be matched using %KDTree or another method. +*/ +class CV_EXPORTS_W_SIMPLE KeyPoint +{ +public: + //! the default constructor + CV_WRAP KeyPoint(); + /** + @param pt x & y coordinates of the keypoint + @param size keypoint diameter + @param angle keypoint orientation + @param response keypoint detector response on the keypoint (that is, strength of the keypoint) + @param octave pyramid octave in which the keypoint has been detected + @param class_id object id + */ + KeyPoint(Point2f pt, float size, float angle=-1, float response=0, int octave=0, int class_id=-1); + /** + @param x x-coordinate of the keypoint + @param y y-coordinate of the keypoint + @param size keypoint diameter + @param angle keypoint orientation + @param response keypoint detector response on the keypoint (that is, strength of the keypoint) + @param octave pyramid octave in which the keypoint has been detected + @param class_id object id + */ + CV_WRAP KeyPoint(float x, float y, float size, float angle=-1, float response=0, int octave=0, int class_id=-1); + + size_t hash() const; + + /** + This method converts vector of keypoints to vector of points or the reverse, where each keypoint is + assigned the same size and the same orientation. + + @param keypoints Keypoints obtained from any feature detection algorithm like SIFT/SURF/ORB + @param points2f Array of (x,y) coordinates of each keypoint + @param keypointIndexes Array of indexes of keypoints to be converted to points. (Acts like a mask to + convert only specified keypoints) + */ + CV_WRAP static void convert(const std::vector& keypoints, + CV_OUT std::vector& points2f, + const std::vector& keypointIndexes=std::vector()); + /** @overload + @param points2f Array of (x,y) coordinates of each keypoint + @param keypoints Keypoints obtained from any feature detection algorithm like SIFT/SURF/ORB + @param size keypoint diameter + @param response keypoint detector response on the keypoint (that is, strength of the keypoint) + @param octave pyramid octave in which the keypoint has been detected + @param class_id object id + */ + CV_WRAP static void convert(const std::vector& points2f, + CV_OUT std::vector& keypoints, + float size=1, float response=1, int octave=0, int class_id=-1); + + /** + This method computes overlap for pair of keypoints. Overlap is the ratio between area of keypoint + regions' intersection and area of keypoint regions' union (considering keypoint region as circle). + If they don't overlap, we get zero. If they coincide at same location with same size, we get 1. + @param kp1 First keypoint + @param kp2 Second keypoint + */ + CV_WRAP static float overlap(const KeyPoint& kp1, const KeyPoint& kp2); + + CV_PROP_RW Point2f pt; //!< coordinates of the keypoints + CV_PROP_RW float size; //!< diameter of the meaningful keypoint neighborhood + CV_PROP_RW float angle; //!< computed orientation of the keypoint (-1 if not applicable); + //!< it's in [0,360) degrees and measured relative to + //!< image coordinate system, ie in clockwise. + CV_PROP_RW float response; //!< the response by which the most strong keypoints have been selected. Can be used for the further sorting or subsampling + CV_PROP_RW int octave; //!< octave (pyramid layer) from which the keypoint has been extracted + CV_PROP_RW int class_id; //!< object class (if the keypoints need to be clustered by an object they belong to) +}; + +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED +template<> class DataType +{ +public: + typedef KeyPoint value_type; + typedef float work_type; + typedef float channel_type; + + enum { generic_type = 0, + depth = DataType::depth, + channels = (int)(sizeof(value_type)/sizeof(channel_type)), // 7 + fmt = DataType::fmt + ((channels - 1) << 8), + type = CV_MAKETYPE(depth, channels) + }; + + typedef Vec vec_type; +}; +#endif + + +//////////////////////////////// DMatch ///////////////////////////////// + +/** @brief Class for matching keypoint descriptors + +query descriptor index, train descriptor index, train image index, and distance between +descriptors. +*/ +class CV_EXPORTS_W_SIMPLE DMatch +{ +public: + CV_WRAP DMatch(); + CV_WRAP DMatch(int _queryIdx, int _trainIdx, float _distance); + CV_WRAP DMatch(int _queryIdx, int _trainIdx, int _imgIdx, float _distance); + + CV_PROP_RW int queryIdx; //!< query descriptor index + CV_PROP_RW int trainIdx; //!< train descriptor index + CV_PROP_RW int imgIdx; //!< train image index + + CV_PROP_RW float distance; + + // less is better + bool operator<(const DMatch &m) const; +}; + +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED +template<> class DataType +{ +public: + typedef DMatch value_type; + typedef int work_type; + typedef int channel_type; + + enum { generic_type = 0, + depth = DataType::depth, + channels = (int)(sizeof(value_type)/sizeof(channel_type)), // 4 + fmt = DataType::fmt + ((channels - 1) << 8), + type = CV_MAKETYPE(depth, channels) + }; + + typedef Vec vec_type; +}; +#endif + + +///////////////////////////// TermCriteria ////////////////////////////// + +/** @brief The class defining termination criteria for iterative algorithms. + +You can initialize it by default constructor and then override any parameters, or the structure may +be fully initialized using the advanced variant of the constructor. +*/ +class CV_EXPORTS TermCriteria +{ +public: + /** + Criteria type, can be one of: COUNT, EPS or COUNT + EPS + */ + enum Type + { + COUNT=1, //!< the maximum number of iterations or elements to compute + MAX_ITER=COUNT, //!< ditto + EPS=2 //!< the desired accuracy or change in parameters at which the iterative algorithm stops + }; + + //! default constructor + TermCriteria(); + /** + @param type The type of termination criteria, one of TermCriteria::Type + @param maxCount The maximum number of iterations or elements to compute. + @param epsilon The desired accuracy or change in parameters at which the iterative algorithm stops. + */ + TermCriteria(int type, int maxCount, double epsilon); + + inline bool isValid() const + { + const bool isCount = (type & COUNT) && maxCount > 0; + const bool isEps = (type & EPS) && !cvIsNaN(epsilon); + return isCount || isEps; + } + + int type; //!< the type of termination criteria: COUNT, EPS or COUNT + EPS + int maxCount; //!< the maximum number of iterations/elements + double epsilon; //!< the desired accuracy +}; + + +//! @} core_basic + +///////////////////////// raster image moments ////////////////////////// + +//! @addtogroup imgproc_shape +//! @{ + +/** @brief struct returned by cv::moments + +The spatial moments \f$\texttt{Moments::m}_{ji}\f$ are computed as: + +\f[\texttt{m} _{ji}= \sum _{x,y} \left ( \texttt{array} (x,y) \cdot x^j \cdot y^i \right )\f] + +The central moments \f$\texttt{Moments::mu}_{ji}\f$ are computed as: + +\f[\texttt{mu} _{ji}= \sum _{x,y} \left ( \texttt{array} (x,y) \cdot (x - \bar{x} )^j \cdot (y - \bar{y} )^i \right )\f] + +where \f$(\bar{x}, \bar{y})\f$ is the mass center: + +\f[\bar{x} = \frac{\texttt{m}_{10}}{\texttt{m}_{00}} , \; \bar{y} = \frac{\texttt{m}_{01}}{\texttt{m}_{00}}\f] + +The normalized central moments \f$\texttt{Moments::nu}_{ij}\f$ are computed as: + +\f[\texttt{nu} _{ji}= \frac{\texttt{mu}_{ji}}{\texttt{m}_{00}^{(i+j)/2+1}} .\f] + +@note +\f$\texttt{mu}_{00}=\texttt{m}_{00}\f$, \f$\texttt{nu}_{00}=1\f$ +\f$\texttt{nu}_{10}=\texttt{mu}_{10}=\texttt{mu}_{01}=\texttt{mu}_{10}=0\f$ , hence the values are not +stored. + +The moments of a contour are defined in the same way but computed using the Green's formula (see +). So, due to a limited raster resolution, the moments +computed for a contour are slightly different from the moments computed for the same rasterized +contour. + +@note +Since the contour moments are computed using Green formula, you may get seemingly odd results for +contours with self-intersections, e.g. a zero area (m00) for butterfly-shaped contours. + */ +class CV_EXPORTS_W_MAP Moments +{ +public: + //! the default constructor + Moments(); + //! the full constructor + Moments(double m00, double m10, double m01, double m20, double m11, + double m02, double m30, double m21, double m12, double m03 ); + ////! the conversion from CvMoments + //Moments( const CvMoments& moments ); + ////! the conversion to CvMoments + //operator CvMoments() const; + + //! @name spatial moments + //! @{ + CV_PROP_RW double m00, m10, m01, m20, m11, m02, m30, m21, m12, m03; + //! @} + + //! @name central moments + //! @{ + CV_PROP_RW double mu20, mu11, mu02, mu30, mu21, mu12, mu03; + //! @} + + //! @name central normalized moments + //! @{ + CV_PROP_RW double nu20, nu11, nu02, nu30, nu21, nu12, nu03; + //! @} +}; + +template<> class DataType +{ +public: + typedef Moments value_type; + typedef double work_type; + typedef double channel_type; + + enum { generic_type = 0, + channels = (int)(sizeof(value_type)/sizeof(channel_type)), // 24 + fmt = DataType::fmt + ((channels - 1) << 8) +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + ,depth = DataType::depth + ,type = CV_MAKETYPE(depth, channels) +#endif + }; + + typedef Vec vec_type; +}; + +namespace traits { +template<> +struct Depth< Moments > { enum { value = Depth::value }; }; +template<> +struct Type< Moments > { enum { value = CV_MAKETYPE(Depth::value, (int)(sizeof(Moments)/sizeof(double))) }; }; +} // namespace + +//! @} imgproc_shape + +//! @cond IGNORED + +///////////////////////////////////////////////////////////////////////// +///////////////////////////// Implementation //////////////////////////// +///////////////////////////////////////////////////////////////////////// + +//////////////////////////////// Complex //////////////////////////////// + +template inline +Complex<_Tp>::Complex() + : re(0), im(0) {} + +template inline +Complex<_Tp>::Complex( _Tp _re, _Tp _im ) + : re(_re), im(_im) {} + +template template inline +Complex<_Tp>::operator Complex() const +{ + return Complex(saturate_cast(re), saturate_cast(im)); +} + +template inline +Complex<_Tp> Complex<_Tp>::conj() const +{ + return Complex<_Tp>(re, -im); +} + + +template static inline +bool operator == (const Complex<_Tp>& a, const Complex<_Tp>& b) +{ + return a.re == b.re && a.im == b.im; +} + +template static inline +bool operator != (const Complex<_Tp>& a, const Complex<_Tp>& b) +{ + return a.re != b.re || a.im != b.im; +} + +template static inline +Complex<_Tp> operator + (const Complex<_Tp>& a, const Complex<_Tp>& b) +{ + return Complex<_Tp>( a.re + b.re, a.im + b.im ); +} + +template static inline +Complex<_Tp>& operator += (Complex<_Tp>& a, const Complex<_Tp>& b) +{ + a.re += b.re; a.im += b.im; + return a; +} + +template static inline +Complex<_Tp> operator - (const Complex<_Tp>& a, const Complex<_Tp>& b) +{ + return Complex<_Tp>( a.re - b.re, a.im - b.im ); +} + +template static inline +Complex<_Tp>& operator -= (Complex<_Tp>& a, const Complex<_Tp>& b) +{ + a.re -= b.re; a.im -= b.im; + return a; +} + +template static inline +Complex<_Tp> operator - (const Complex<_Tp>& a) +{ + return Complex<_Tp>(-a.re, -a.im); +} + +template static inline +Complex<_Tp> operator * (const Complex<_Tp>& a, const Complex<_Tp>& b) +{ + return Complex<_Tp>( a.re*b.re - a.im*b.im, a.re*b.im + a.im*b.re ); +} + +template static inline +Complex<_Tp> operator * (const Complex<_Tp>& a, _Tp b) +{ + return Complex<_Tp>( a.re*b, a.im*b ); +} + +template static inline +Complex<_Tp> operator * (_Tp b, const Complex<_Tp>& a) +{ + return Complex<_Tp>( a.re*b, a.im*b ); +} + +template static inline +Complex<_Tp> operator + (const Complex<_Tp>& a, _Tp b) +{ + return Complex<_Tp>( a.re + b, a.im ); +} + +template static inline +Complex<_Tp> operator - (const Complex<_Tp>& a, _Tp b) +{ return Complex<_Tp>( a.re - b, a.im ); } + +template static inline +Complex<_Tp> operator + (_Tp b, const Complex<_Tp>& a) +{ + return Complex<_Tp>( a.re + b, a.im ); +} + +template static inline +Complex<_Tp> operator - (_Tp b, const Complex<_Tp>& a) +{ + return Complex<_Tp>( b - a.re, -a.im ); +} + +template static inline +Complex<_Tp>& operator += (Complex<_Tp>& a, _Tp b) +{ + a.re += b; return a; +} + +template static inline +Complex<_Tp>& operator -= (Complex<_Tp>& a, _Tp b) +{ + a.re -= b; return a; +} + +template static inline +Complex<_Tp>& operator *= (Complex<_Tp>& a, _Tp b) +{ + a.re *= b; a.im *= b; return a; +} + +template static inline +double abs(const Complex<_Tp>& a) +{ + return std::sqrt( (double)a.re*a.re + (double)a.im*a.im); +} + +template static inline +Complex<_Tp> operator / (const Complex<_Tp>& a, const Complex<_Tp>& b) +{ + double t = 1./((double)b.re*b.re + (double)b.im*b.im); + return Complex<_Tp>( (_Tp)((a.re*b.re + a.im*b.im)*t), + (_Tp)((-a.re*b.im + a.im*b.re)*t) ); +} + +template static inline +Complex<_Tp>& operator /= (Complex<_Tp>& a, const Complex<_Tp>& b) +{ + a = a / b; + return a; +} + +template static inline +Complex<_Tp> operator / (const Complex<_Tp>& a, _Tp b) +{ + _Tp t = (_Tp)1/b; + return Complex<_Tp>( a.re*t, a.im*t ); +} + +template static inline +Complex<_Tp> operator / (_Tp b, const Complex<_Tp>& a) +{ + return Complex<_Tp>(b)/a; +} + +template static inline +Complex<_Tp> operator /= (const Complex<_Tp>& a, _Tp b) +{ + _Tp t = (_Tp)1/b; + a.re *= t; a.im *= t; return a; +} + + + +//////////////////////////////// 2D Point /////////////////////////////// + +template inline +Point_<_Tp>::Point_() + : x(0), y(0) {} + +template inline +Point_<_Tp>::Point_(_Tp _x, _Tp _y) + : x(_x), y(_y) {} + +#if (defined(__GNUC__) && __GNUC__ < 5) && !defined(__clang__) // GCC 4.x bug. Details: https://github.com/opencv/opencv/pull/20837 +template inline +Point_<_Tp>::Point_(const Point_& pt) + : x(pt.x), y(pt.y) {} +#endif + +template inline +Point_<_Tp>::Point_(const Size_<_Tp>& sz) + : x(sz.width), y(sz.height) {} + +template inline +Point_<_Tp>::Point_(const Vec<_Tp,2>& v) + : x(v[0]), y(v[1]) {} + +#if (defined(__GNUC__) && __GNUC__ < 5) && !defined(__clang__) // GCC 4.x bug. Details: https://github.com/opencv/opencv/pull/20837 +template inline +Point_<_Tp>& Point_<_Tp>::operator = (const Point_& pt) +{ + x = pt.x; y = pt.y; + return *this; +} +#endif + +template template inline +Point_<_Tp>::operator Point_<_Tp2>() const +{ + return Point_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y)); +} + +template inline +Point_<_Tp>::operator Vec<_Tp, 2>() const +{ + return Vec<_Tp, 2>(x, y); +} + +template inline +_Tp Point_<_Tp>::dot(const Point_& pt) const +{ + return saturate_cast<_Tp>(x*pt.x + y*pt.y); +} + +template inline +double Point_<_Tp>::ddot(const Point_& pt) const +{ + return (double)x*(double)(pt.x) + (double)y*(double)(pt.y); +} + +template inline +double Point_<_Tp>::cross(const Point_& pt) const +{ + return (double)x*pt.y - (double)y*pt.x; +} + +template inline bool +Point_<_Tp>::inside( const Rect_<_Tp>& r ) const +{ + return r.contains(*this); +} + + +template static inline +Point_<_Tp>& operator += (Point_<_Tp>& a, const Point_<_Tp>& b) +{ + a.x += b.x; + a.y += b.y; + return a; +} + +template static inline +Point_<_Tp>& operator -= (Point_<_Tp>& a, const Point_<_Tp>& b) +{ + a.x -= b.x; + a.y -= b.y; + return a; +} + +template static inline +Point_<_Tp>& operator *= (Point_<_Tp>& a, int b) +{ + a.x = saturate_cast<_Tp>(a.x * b); + a.y = saturate_cast<_Tp>(a.y * b); + return a; +} + +template static inline +Point_<_Tp>& operator *= (Point_<_Tp>& a, float b) +{ + a.x = saturate_cast<_Tp>(a.x * b); + a.y = saturate_cast<_Tp>(a.y * b); + return a; +} + +template static inline +Point_<_Tp>& operator *= (Point_<_Tp>& a, double b) +{ + a.x = saturate_cast<_Tp>(a.x * b); + a.y = saturate_cast<_Tp>(a.y * b); + return a; +} + +template static inline +Point_<_Tp>& operator /= (Point_<_Tp>& a, int b) +{ + a.x = saturate_cast<_Tp>(a.x / b); + a.y = saturate_cast<_Tp>(a.y / b); + return a; +} + +template static inline +Point_<_Tp>& operator /= (Point_<_Tp>& a, float b) +{ + a.x = saturate_cast<_Tp>(a.x / b); + a.y = saturate_cast<_Tp>(a.y / b); + return a; +} + +template static inline +Point_<_Tp>& operator /= (Point_<_Tp>& a, double b) +{ + a.x = saturate_cast<_Tp>(a.x / b); + a.y = saturate_cast<_Tp>(a.y / b); + return a; +} + +template static inline +double norm(const Point_<_Tp>& pt) +{ + return std::sqrt((double)pt.x*pt.x + (double)pt.y*pt.y); +} + +template static inline +bool operator == (const Point_<_Tp>& a, const Point_<_Tp>& b) +{ + return a.x == b.x && a.y == b.y; +} + +template static inline +bool operator != (const Point_<_Tp>& a, const Point_<_Tp>& b) +{ + return a.x != b.x || a.y != b.y; +} + +template static inline +Point_<_Tp> operator + (const Point_<_Tp>& a, const Point_<_Tp>& b) +{ + return Point_<_Tp>( saturate_cast<_Tp>(a.x + b.x), saturate_cast<_Tp>(a.y + b.y) ); +} + +template static inline +Point_<_Tp> operator - (const Point_<_Tp>& a, const Point_<_Tp>& b) +{ + return Point_<_Tp>( saturate_cast<_Tp>(a.x - b.x), saturate_cast<_Tp>(a.y - b.y) ); +} + +template static inline +Point_<_Tp> operator - (const Point_<_Tp>& a) +{ + return Point_<_Tp>( saturate_cast<_Tp>(-a.x), saturate_cast<_Tp>(-a.y) ); +} + +template static inline +Point_<_Tp> operator * (const Point_<_Tp>& a, int b) +{ + return Point_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b) ); +} + +template static inline +Point_<_Tp> operator * (int a, const Point_<_Tp>& b) +{ + return Point_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a) ); +} + +template static inline +Point_<_Tp> operator * (const Point_<_Tp>& a, float b) +{ + return Point_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b) ); +} + +template static inline +Point_<_Tp> operator * (float a, const Point_<_Tp>& b) +{ + return Point_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a) ); +} + +template static inline +Point_<_Tp> operator * (const Point_<_Tp>& a, double b) +{ + return Point_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b) ); +} + +template static inline +Point_<_Tp> operator * (double a, const Point_<_Tp>& b) +{ + return Point_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a) ); +} + +template static inline +Point_<_Tp> operator * (const Matx<_Tp, 2, 2>& a, const Point_<_Tp>& b) +{ + Matx<_Tp, 2, 1> tmp = a * Vec<_Tp,2>(b.x, b.y); + return Point_<_Tp>(tmp.val[0], tmp.val[1]); +} + +template static inline +Point3_<_Tp> operator * (const Matx<_Tp, 3, 3>& a, const Point_<_Tp>& b) +{ + Matx<_Tp, 3, 1> tmp = a * Vec<_Tp,3>(b.x, b.y, 1); + return Point3_<_Tp>(tmp.val[0], tmp.val[1], tmp.val[2]); +} + +template static inline +Point_<_Tp> operator / (const Point_<_Tp>& a, int b) +{ + Point_<_Tp> tmp(a); + tmp /= b; + return tmp; +} + +template static inline +Point_<_Tp> operator / (const Point_<_Tp>& a, float b) +{ + Point_<_Tp> tmp(a); + tmp /= b; + return tmp; +} + +template static inline +Point_<_Tp> operator / (const Point_<_Tp>& a, double b) +{ + Point_<_Tp> tmp(a); + tmp /= b; + return tmp; +} + + +template static inline _AccTp normL2Sqr(const Point_& pt); +template static inline _AccTp normL2Sqr(const Point_& pt); +template static inline _AccTp normL2Sqr(const Point_& pt); +template static inline _AccTp normL2Sqr(const Point_& pt); + +template<> inline int normL2Sqr(const Point_& pt) { return pt.dot(pt); } +template<> inline int64 normL2Sqr(const Point_& pt) { return pt.dot(pt); } +template<> inline float normL2Sqr(const Point_& pt) { return pt.dot(pt); } +template<> inline double normL2Sqr(const Point_& pt) { return pt.dot(pt); } + +template<> inline double normL2Sqr(const Point_& pt) { return pt.ddot(pt); } +template<> inline double normL2Sqr(const Point_& pt) { return pt.ddot(pt); } + + + +//////////////////////////////// 3D Point /////////////////////////////// + +template inline +Point3_<_Tp>::Point3_() + : x(0), y(0), z(0) {} + +template inline +Point3_<_Tp>::Point3_(_Tp _x, _Tp _y, _Tp _z) + : x(_x), y(_y), z(_z) {} + +template inline +Point3_<_Tp>::Point3_(const Point_<_Tp>& pt) + : x(pt.x), y(pt.y), z(_Tp()) {} + +template inline +Point3_<_Tp>::Point3_(const Vec<_Tp, 3>& v) + : x(v[0]), y(v[1]), z(v[2]) {} + +template template inline +Point3_<_Tp>::operator Point3_<_Tp2>() const +{ + return Point3_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y), saturate_cast<_Tp2>(z)); +} + +template inline +Point3_<_Tp>::operator Vec<_Tp, 3>() const +{ + return Vec<_Tp, 3>(x, y, z); +} + +template inline +_Tp Point3_<_Tp>::dot(const Point3_& pt) const +{ + return saturate_cast<_Tp>(x*pt.x + y*pt.y + z*pt.z); +} + +template inline +double Point3_<_Tp>::ddot(const Point3_& pt) const +{ + return (double)x*pt.x + (double)y*pt.y + (double)z*pt.z; +} + +template inline +Point3_<_Tp> Point3_<_Tp>::cross(const Point3_<_Tp>& pt) const +{ + return Point3_<_Tp>(y*pt.z - z*pt.y, z*pt.x - x*pt.z, x*pt.y - y*pt.x); +} + + +template static inline +Point3_<_Tp>& operator += (Point3_<_Tp>& a, const Point3_<_Tp>& b) +{ + a.x += b.x; + a.y += b.y; + a.z += b.z; + return a; +} + +template static inline +Point3_<_Tp>& operator -= (Point3_<_Tp>& a, const Point3_<_Tp>& b) +{ + a.x -= b.x; + a.y -= b.y; + a.z -= b.z; + return a; +} + +template static inline +Point3_<_Tp>& operator *= (Point3_<_Tp>& a, int b) +{ + a.x = saturate_cast<_Tp>(a.x * b); + a.y = saturate_cast<_Tp>(a.y * b); + a.z = saturate_cast<_Tp>(a.z * b); + return a; +} + +template static inline +Point3_<_Tp>& operator *= (Point3_<_Tp>& a, float b) +{ + a.x = saturate_cast<_Tp>(a.x * b); + a.y = saturate_cast<_Tp>(a.y * b); + a.z = saturate_cast<_Tp>(a.z * b); + return a; +} + +template static inline +Point3_<_Tp>& operator *= (Point3_<_Tp>& a, double b) +{ + a.x = saturate_cast<_Tp>(a.x * b); + a.y = saturate_cast<_Tp>(a.y * b); + a.z = saturate_cast<_Tp>(a.z * b); + return a; +} + +template static inline +Point3_<_Tp>& operator /= (Point3_<_Tp>& a, int b) +{ + a.x = saturate_cast<_Tp>(a.x / b); + a.y = saturate_cast<_Tp>(a.y / b); + a.z = saturate_cast<_Tp>(a.z / b); + return a; +} + +template static inline +Point3_<_Tp>& operator /= (Point3_<_Tp>& a, float b) +{ + a.x = saturate_cast<_Tp>(a.x / b); + a.y = saturate_cast<_Tp>(a.y / b); + a.z = saturate_cast<_Tp>(a.z / b); + return a; +} + +template static inline +Point3_<_Tp>& operator /= (Point3_<_Tp>& a, double b) +{ + a.x = saturate_cast<_Tp>(a.x / b); + a.y = saturate_cast<_Tp>(a.y / b); + a.z = saturate_cast<_Tp>(a.z / b); + return a; +} + +template static inline +double norm(const Point3_<_Tp>& pt) +{ + return std::sqrt((double)pt.x*pt.x + (double)pt.y*pt.y + (double)pt.z*pt.z); +} + +template static inline +bool operator == (const Point3_<_Tp>& a, const Point3_<_Tp>& b) +{ + return a.x == b.x && a.y == b.y && a.z == b.z; +} + +template static inline +bool operator != (const Point3_<_Tp>& a, const Point3_<_Tp>& b) +{ + return a.x != b.x || a.y != b.y || a.z != b.z; +} + +template static inline +Point3_<_Tp> operator + (const Point3_<_Tp>& a, const Point3_<_Tp>& b) +{ + return Point3_<_Tp>( saturate_cast<_Tp>(a.x + b.x), saturate_cast<_Tp>(a.y + b.y), saturate_cast<_Tp>(a.z + b.z)); +} + +template static inline +Point3_<_Tp> operator - (const Point3_<_Tp>& a, const Point3_<_Tp>& b) +{ + return Point3_<_Tp>( saturate_cast<_Tp>(a.x - b.x), saturate_cast<_Tp>(a.y - b.y), saturate_cast<_Tp>(a.z - b.z)); +} + +template static inline +Point3_<_Tp> operator - (const Point3_<_Tp>& a) +{ + return Point3_<_Tp>( saturate_cast<_Tp>(-a.x), saturate_cast<_Tp>(-a.y), saturate_cast<_Tp>(-a.z) ); +} + +template static inline +Point3_<_Tp> operator * (const Point3_<_Tp>& a, int b) +{ + return Point3_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b), saturate_cast<_Tp>(a.z*b) ); +} + +template static inline +Point3_<_Tp> operator * (int a, const Point3_<_Tp>& b) +{ + return Point3_<_Tp>( saturate_cast<_Tp>(b.x * a), saturate_cast<_Tp>(b.y * a), saturate_cast<_Tp>(b.z * a) ); +} + +template static inline +Point3_<_Tp> operator * (const Point3_<_Tp>& a, float b) +{ + return Point3_<_Tp>( saturate_cast<_Tp>(a.x * b), saturate_cast<_Tp>(a.y * b), saturate_cast<_Tp>(a.z * b) ); +} + +template static inline +Point3_<_Tp> operator * (float a, const Point3_<_Tp>& b) +{ + return Point3_<_Tp>( saturate_cast<_Tp>(b.x * a), saturate_cast<_Tp>(b.y * a), saturate_cast<_Tp>(b.z * a) ); +} + +template static inline +Point3_<_Tp> operator * (const Point3_<_Tp>& a, double b) +{ + return Point3_<_Tp>( saturate_cast<_Tp>(a.x * b), saturate_cast<_Tp>(a.y * b), saturate_cast<_Tp>(a.z * b) ); +} + +template static inline +Point3_<_Tp> operator * (double a, const Point3_<_Tp>& b) +{ + return Point3_<_Tp>( saturate_cast<_Tp>(b.x * a), saturate_cast<_Tp>(b.y * a), saturate_cast<_Tp>(b.z * a) ); +} + +template static inline +Point3_<_Tp> operator * (const Matx<_Tp, 3, 3>& a, const Point3_<_Tp>& b) +{ + Matx<_Tp, 3, 1> tmp = a * Vec<_Tp,3>(b.x, b.y, b.z); + return Point3_<_Tp>(tmp.val[0], tmp.val[1], tmp.val[2]); +} + +template static inline +Matx<_Tp, 4, 1> operator * (const Matx<_Tp, 4, 4>& a, const Point3_<_Tp>& b) +{ + return a * Matx<_Tp, 4, 1>(b.x, b.y, b.z, 1); +} + +template static inline +Point3_<_Tp> operator / (const Point3_<_Tp>& a, int b) +{ + Point3_<_Tp> tmp(a); + tmp /= b; + return tmp; +} + +template static inline +Point3_<_Tp> operator / (const Point3_<_Tp>& a, float b) +{ + Point3_<_Tp> tmp(a); + tmp /= b; + return tmp; +} + +template static inline +Point3_<_Tp> operator / (const Point3_<_Tp>& a, double b) +{ + Point3_<_Tp> tmp(a); + tmp /= b; + return tmp; +} + + + +////////////////////////////////// Size ///////////////////////////////// + +template inline +Size_<_Tp>::Size_() + : width(0), height(0) {} + +template inline +Size_<_Tp>::Size_(_Tp _width, _Tp _height) + : width(_width), height(_height) {} + +template inline +Size_<_Tp>::Size_(const Point_<_Tp>& pt) + : width(pt.x), height(pt.y) {} + +template template inline +Size_<_Tp>::operator Size_<_Tp2>() const +{ + return Size_<_Tp2>(saturate_cast<_Tp2>(width), saturate_cast<_Tp2>(height)); +} + +template inline +_Tp Size_<_Tp>::area() const +{ + const _Tp result = width * height; + CV_DbgAssert(!std::numeric_limits<_Tp>::is_integer + || width == 0 || result / width == height); // make sure the result fits in the return value + return result; +} + +template inline +double Size_<_Tp>::aspectRatio() const +{ + return width / static_cast(height); +} + +template inline +bool Size_<_Tp>::empty() const +{ + return width <= 0 || height <= 0; +} + + +template static inline +Size_<_Tp>& operator *= (Size_<_Tp>& a, _Tp b) +{ + a.width *= b; + a.height *= b; + return a; +} + +template static inline +Size_<_Tp> operator * (const Size_<_Tp>& a, _Tp b) +{ + Size_<_Tp> tmp(a); + tmp *= b; + return tmp; +} + +template static inline +Size_<_Tp>& operator /= (Size_<_Tp>& a, _Tp b) +{ + a.width /= b; + a.height /= b; + return a; +} + +template static inline +Size_<_Tp> operator / (const Size_<_Tp>& a, _Tp b) +{ + Size_<_Tp> tmp(a); + tmp /= b; + return tmp; +} + +template static inline +Size_<_Tp>& operator += (Size_<_Tp>& a, const Size_<_Tp>& b) +{ + a.width += b.width; + a.height += b.height; + return a; +} + +template static inline +Size_<_Tp> operator + (const Size_<_Tp>& a, const Size_<_Tp>& b) +{ + Size_<_Tp> tmp(a); + tmp += b; + return tmp; +} + +template static inline +Size_<_Tp>& operator -= (Size_<_Tp>& a, const Size_<_Tp>& b) +{ + a.width -= b.width; + a.height -= b.height; + return a; +} + +template static inline +Size_<_Tp> operator - (const Size_<_Tp>& a, const Size_<_Tp>& b) +{ + Size_<_Tp> tmp(a); + tmp -= b; + return tmp; +} + +template static inline +bool operator == (const Size_<_Tp>& a, const Size_<_Tp>& b) +{ + return a.width == b.width && a.height == b.height; +} + +template static inline +bool operator != (const Size_<_Tp>& a, const Size_<_Tp>& b) +{ + return !(a == b); +} + + + +////////////////////////////////// Rect ///////////////////////////////// + +template inline +Rect_<_Tp>::Rect_() + : x(0), y(0), width(0), height(0) {} + +template inline +Rect_<_Tp>::Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height) + : x(_x), y(_y), width(_width), height(_height) {} + +template inline +Rect_<_Tp>::Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz) + : x(org.x), y(org.y), width(sz.width), height(sz.height) {} + +template inline +Rect_<_Tp>::Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2) +{ + x = std::min(pt1.x, pt2.x); + y = std::min(pt1.y, pt2.y); + width = std::max(pt1.x, pt2.x) - x; + height = std::max(pt1.y, pt2.y) - y; +} + +template inline +Point_<_Tp> Rect_<_Tp>::tl() const +{ + return Point_<_Tp>(x,y); +} + +template inline +Point_<_Tp> Rect_<_Tp>::br() const +{ + return Point_<_Tp>(x + width, y + height); +} + +template inline +Size_<_Tp> Rect_<_Tp>::size() const +{ + return Size_<_Tp>(width, height); +} + +template inline +_Tp Rect_<_Tp>::area() const +{ + const _Tp result = width * height; + if constexpr (std::numeric_limits<_Tp>::is_integer) + { + CV_DbgAssert(width == 0 || result / width == height); // make sure the result fits in the return value + } + return result; +} + +template inline +bool Rect_<_Tp>::empty() const +{ + return width <= 0 || height <= 0; +} + +template template inline +Rect_<_Tp>::operator Rect_<_Tp2>() const +{ + return Rect_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y), saturate_cast<_Tp2>(width), saturate_cast<_Tp2>(height)); +} + +template template inline +bool Rect_<_Tp>::contains(const Point_<_Tp2>& pt) const +{ + return x <= pt.x && pt.x < x + width && y <= pt.y && pt.y < y + height; +} +// See https://github.com/opencv/opencv/issues/26016 +template<> template<> inline +bool Rect_::contains(const Point_& pt) const +{ + // std::numeric_limits::digits is 31. + // std::numeric_limits::digits is 53. + // So conversion int->double does not lead to accuracy errors. + const Rect_ _rect(static_cast(x), static_cast(y), static_cast(width), static_cast(height)); + return _rect.contains(pt); +} +template<> template<> inline +bool Rect_::contains(const Point_& _pt) const +{ + // std::numeric_limits::digits is 24. + // std::numeric_limits::digits is 53. + // So conversion float->double does not lead to accuracy errors. + return contains(Point_(static_cast(_pt.x), static_cast(_pt.y))); +} + +template static inline +Rect_<_Tp>& operator += ( Rect_<_Tp>& a, const Point_<_Tp>& b ) +{ + a.x += b.x; + a.y += b.y; + return a; +} + +template static inline +Rect_<_Tp>& operator -= ( Rect_<_Tp>& a, const Point_<_Tp>& b ) +{ + a.x -= b.x; + a.y -= b.y; + return a; +} + +template static inline +Rect_<_Tp>& operator += ( Rect_<_Tp>& a, const Size_<_Tp>& b ) +{ + a.width += b.width; + a.height += b.height; + return a; +} + +template static inline +Rect_<_Tp>& operator -= ( Rect_<_Tp>& a, const Size_<_Tp>& b ) +{ + const _Tp width = a.width - b.width; + const _Tp height = a.height - b.height; + CV_DbgAssert(width >= 0 && height >= 0); + a.width = width; + a.height = height; + return a; +} + +template static inline +Rect_<_Tp>& operator &= ( Rect_<_Tp>& a, const Rect_<_Tp>& b ) +{ + if (a.empty() || b.empty()) { + a = Rect(); + return a; + } + const Rect_<_Tp>& Rx_min = (a.x < b.x) ? a : b; + const Rect_<_Tp>& Rx_max = (a.x < b.x) ? b : a; + const Rect_<_Tp>& Ry_min = (a.y < b.y) ? a : b; + const Rect_<_Tp>& Ry_max = (a.y < b.y) ? b : a; + // Looking at the formula below, we will compute Rx_min.width - (Rx_max.x - Rx_min.x) + // but we want to avoid overflows. Rx_min.width >= 0 and (Rx_max.x - Rx_min.x) >= 0 + // by definition so the difference does not overflow. The only thing that can overflow + // is (Rx_max.x - Rx_min.x). And it can only overflow if Rx_min.x < 0. + // Let us first deal with the following case. + if ((Rx_min.x < 0 && Rx_min.x + Rx_min.width < Rx_max.x) || + (Ry_min.y < 0 && Ry_min.y + Ry_min.height < Ry_max.y)) { + a = Rect(); + return a; + } + // We now know that either Rx_min.x >= 0, or + // Rx_min.x < 0 && Rx_min.x + Rx_min.width >= Rx_max.x and therefore + // Rx_min.width >= (Rx_max.x - Rx_min.x) which means (Rx_max.x - Rx_min.x) + // is inferior to a valid int and therefore does not overflow. + a.width = std::min(Rx_min.width - (Rx_max.x - Rx_min.x), Rx_max.width); + a.height = std::min(Ry_min.height - (Ry_max.y - Ry_min.y), Ry_max.height); + a.x = Rx_max.x; + a.y = Ry_max.y; + if (a.empty()) + a = Rect(); + return a; +} + +template static inline +Rect_<_Tp>& operator |= ( Rect_<_Tp>& a, const Rect_<_Tp>& b ) +{ + if (a.empty()) { + a = b; + } + else if (!b.empty()) { + _Tp x1 = std::min(a.x, b.x); + _Tp y1 = std::min(a.y, b.y); + a.width = std::max(a.x + a.width, b.x + b.width) - x1; + a.height = std::max(a.y + a.height, b.y + b.height) - y1; + a.x = x1; + a.y = y1; + } + return a; +} + +template static inline +bool operator == (const Rect_<_Tp>& a, const Rect_<_Tp>& b) +{ + return a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height; +} + +template static inline +bool operator != (const Rect_<_Tp>& a, const Rect_<_Tp>& b) +{ + return a.x != b.x || a.y != b.y || a.width != b.width || a.height != b.height; +} + +template static inline +Rect_<_Tp> operator + (const Rect_<_Tp>& a, const Point_<_Tp>& b) +{ + return Rect_<_Tp>( a.x + b.x, a.y + b.y, a.width, a.height ); +} + +template static inline +Rect_<_Tp> operator - (const Rect_<_Tp>& a, const Point_<_Tp>& b) +{ + return Rect_<_Tp>( a.x - b.x, a.y - b.y, a.width, a.height ); +} + +template static inline +Rect_<_Tp> operator + (const Rect_<_Tp>& a, const Size_<_Tp>& b) +{ + return Rect_<_Tp>( a.x, a.y, a.width + b.width, a.height + b.height ); +} + +template static inline +Rect_<_Tp> operator - (const Rect_<_Tp>& a, const Size_<_Tp>& b) +{ + const _Tp width = a.width - b.width; + const _Tp height = a.height - b.height; + CV_DbgAssert(width >= 0 && height >= 0); + return Rect_<_Tp>( a.x, a.y, width, height ); +} + +template static inline +Rect_<_Tp> operator & (const Rect_<_Tp>& a, const Rect_<_Tp>& b) +{ + Rect_<_Tp> c = a; + return c &= b; +} + +template static inline +Rect_<_Tp> operator | (const Rect_<_Tp>& a, const Rect_<_Tp>& b) +{ + Rect_<_Tp> c = a; + return c |= b; +} + +/** + * @brief measure dissimilarity between two sample sets + * + * computes the complement of the Jaccard Index as described in . + * For rectangles this reduces to computing the intersection over the union. + */ +template static inline +double jaccardDistance(const Rect_<_Tp>& a, const Rect_<_Tp>& b) { + _Tp Aa = a.area(); + _Tp Ab = b.area(); + + if ((Aa + Ab) <= std::numeric_limits<_Tp>::epsilon()) { + // jaccard_index = 1 -> distance = 0 + return 0.0; + } + + double Aab = (a & b).area(); + // distance = 1 - jaccard_index + return 1.0 - Aab / (Aa + Ab - Aab); +} + +/** @brief Finds out if there is any intersection between two rectangles + * + * mainly useful for language bindings + * @param a First rectangle + * @param b Second rectangle + * @return the area of the intersection + */ +CV_EXPORTS_W inline double rectangleIntersectionArea(const Rect2d& a, const Rect2d& b) { return (a & b).area(); } + +////////////////////////////// RotatedRect ////////////////////////////// + +inline +RotatedRect::RotatedRect() + : center(), size(), angle(0) {} + +inline +RotatedRect::RotatedRect(const Point2f& _center, const Size2f& _size, float _angle) + : center(_center), size(_size), angle(_angle) {} + +///////////////////////////////// Range ///////////////////////////////// + +inline +Range::Range() + : start(0), end(0) {} + +inline +Range::Range(int _start, int _end) + : start(_start), end(_end) {} + +inline +int Range::size() const +{ + return end - start; +} + +inline +bool Range::empty() const +{ + return start == end; +} + +inline +Range Range::all() +{ + return Range(INT_MIN, INT_MAX); +} + + +static inline +bool operator == (const Range& r1, const Range& r2) +{ + return r1.start == r2.start && r1.end == r2.end; +} + +static inline +bool operator != (const Range& r1, const Range& r2) +{ + return !(r1 == r2); +} + +static inline +bool operator !(const Range& r) +{ + return r.start == r.end; +} + +static inline +Range operator & (const Range& r1, const Range& r2) +{ + Range r(std::max(r1.start, r2.start), std::min(r1.end, r2.end)); + r.end = std::max(r.end, r.start); + return r; +} + +static inline +Range& operator &= (Range& r1, const Range& r2) +{ + r1 = r1 & r2; + return r1; +} + +static inline +Range operator + (const Range& r1, int delta) +{ + return Range(r1.start + delta, r1.end + delta); +} + +static inline +Range operator + (int delta, const Range& r1) +{ + return Range(r1.start + delta, r1.end + delta); +} + +static inline +Range operator - (const Range& r1, int delta) +{ + return r1 + (-delta); +} + + + +///////////////////////////////// Scalar //////////////////////////////// + +template inline +Scalar_<_Tp>::Scalar_() +{ + this->val[0] = this->val[1] = this->val[2] = this->val[3] = 0; +} + +template inline +Scalar_<_Tp>::Scalar_(_Tp v0, _Tp v1, _Tp v2, _Tp v3) +{ + this->val[0] = v0; + this->val[1] = v1; + this->val[2] = v2; + this->val[3] = v3; +} + +template inline +Scalar_<_Tp>::Scalar_(const Scalar_<_Tp>& s) : Vec<_Tp, 4>(s) { +} + +template inline +Scalar_<_Tp>::Scalar_(Scalar_<_Tp>&& s) CV_NOEXCEPT { + this->val[0] = std::move(s.val[0]); + this->val[1] = std::move(s.val[1]); + this->val[2] = std::move(s.val[2]); + this->val[3] = std::move(s.val[3]); +} + +template inline +Scalar_<_Tp>& Scalar_<_Tp>::operator=(const Scalar_<_Tp>& s) { + this->val[0] = s.val[0]; + this->val[1] = s.val[1]; + this->val[2] = s.val[2]; + this->val[3] = s.val[3]; + return *this; +} + +template inline +Scalar_<_Tp>& Scalar_<_Tp>::operator=(Scalar_<_Tp>&& s) CV_NOEXCEPT { + this->val[0] = std::move(s.val[0]); + this->val[1] = std::move(s.val[1]); + this->val[2] = std::move(s.val[2]); + this->val[3] = std::move(s.val[3]); + return *this; +} + +template template inline +Scalar_<_Tp>::Scalar_(const Vec<_Tp2, cn>& v) +{ + int i; + for( i = 0; i < (cn < 4 ? cn : 4); i++ ) + this->val[i] = cv::saturate_cast<_Tp>(v.val[i]); + for( ; i < 4; i++ ) + this->val[i] = 0; +} + +template inline +Scalar_<_Tp>::Scalar_(_Tp v0) +{ + this->val[0] = v0; + this->val[1] = this->val[2] = this->val[3] = 0; +} + +template inline +Scalar_<_Tp> Scalar_<_Tp>::all(_Tp v0) +{ + return Scalar_<_Tp>(v0, v0, v0, v0); +} + + +template inline +Scalar_<_Tp> Scalar_<_Tp>::mul(const Scalar_<_Tp>& a, double scale ) const +{ + return Scalar_<_Tp>(saturate_cast<_Tp>(this->val[0] * a.val[0] * scale), + saturate_cast<_Tp>(this->val[1] * a.val[1] * scale), + saturate_cast<_Tp>(this->val[2] * a.val[2] * scale), + saturate_cast<_Tp>(this->val[3] * a.val[3] * scale)); +} + +template inline +Scalar_<_Tp> Scalar_<_Tp>::conj() const +{ + return Scalar_<_Tp>(saturate_cast<_Tp>( this->val[0]), + saturate_cast<_Tp>(-this->val[1]), + saturate_cast<_Tp>(-this->val[2]), + saturate_cast<_Tp>(-this->val[3])); +} + +template inline +bool Scalar_<_Tp>::isReal() const +{ + return this->val[1] == 0 && this->val[2] == 0 && this->val[3] == 0; +} + + +template template inline +Scalar_<_Tp>::operator Scalar_() const +{ + return Scalar_(saturate_cast(this->val[0]), + saturate_cast(this->val[1]), + saturate_cast(this->val[2]), + saturate_cast(this->val[3])); +} + + +template static inline +Scalar_<_Tp>& operator += (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) +{ + a.val[0] += b.val[0]; + a.val[1] += b.val[1]; + a.val[2] += b.val[2]; + a.val[3] += b.val[3]; + return a; +} + +template static inline +Scalar_<_Tp>& operator -= (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) +{ + a.val[0] -= b.val[0]; + a.val[1] -= b.val[1]; + a.val[2] -= b.val[2]; + a.val[3] -= b.val[3]; + return a; +} + +template static inline +Scalar_<_Tp>& operator *= ( Scalar_<_Tp>& a, _Tp v ) +{ + a.val[0] *= v; + a.val[1] *= v; + a.val[2] *= v; + a.val[3] *= v; + return a; +} + +template static inline +bool operator == ( const Scalar_<_Tp>& a, const Scalar_<_Tp>& b ) +{ + return a.val[0] == b.val[0] && a.val[1] == b.val[1] && + a.val[2] == b.val[2] && a.val[3] == b.val[3]; +} + +template static inline +bool operator != ( const Scalar_<_Tp>& a, const Scalar_<_Tp>& b ) +{ + return a.val[0] != b.val[0] || a.val[1] != b.val[1] || + a.val[2] != b.val[2] || a.val[3] != b.val[3]; +} + +template static inline +Scalar_<_Tp> operator + (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) +{ + return Scalar_<_Tp>(a.val[0] + b.val[0], + a.val[1] + b.val[1], + a.val[2] + b.val[2], + a.val[3] + b.val[3]); +} + +template static inline +Scalar_<_Tp> operator - (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) +{ + return Scalar_<_Tp>(saturate_cast<_Tp>(a.val[0] - b.val[0]), + saturate_cast<_Tp>(a.val[1] - b.val[1]), + saturate_cast<_Tp>(a.val[2] - b.val[2]), + saturate_cast<_Tp>(a.val[3] - b.val[3])); +} + +template static inline +Scalar_<_Tp> operator * (const Scalar_<_Tp>& a, _Tp alpha) +{ + return Scalar_<_Tp>(a.val[0] * alpha, + a.val[1] * alpha, + a.val[2] * alpha, + a.val[3] * alpha); +} + +template static inline +Scalar_<_Tp> operator * (_Tp alpha, const Scalar_<_Tp>& a) +{ + return a*alpha; +} + +template static inline +Scalar_<_Tp> operator - (const Scalar_<_Tp>& a) +{ + return Scalar_<_Tp>(saturate_cast<_Tp>(-a.val[0]), + saturate_cast<_Tp>(-a.val[1]), + saturate_cast<_Tp>(-a.val[2]), + saturate_cast<_Tp>(-a.val[3])); +} + + +template static inline +Scalar_<_Tp> operator * (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) +{ + return Scalar_<_Tp>(saturate_cast<_Tp>(a[0]*b[0] - a[1]*b[1] - a[2]*b[2] - a[3]*b[3]), + saturate_cast<_Tp>(a[0]*b[1] + a[1]*b[0] + a[2]*b[3] - a[3]*b[2]), + saturate_cast<_Tp>(a[0]*b[2] - a[1]*b[3] + a[2]*b[0] + a[3]*b[1]), + saturate_cast<_Tp>(a[0]*b[3] + a[1]*b[2] - a[2]*b[1] + a[3]*b[0])); +} + +template static inline +Scalar_<_Tp>& operator *= (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) +{ + a = a * b; + return a; +} + +template static inline +Scalar_<_Tp> operator / (const Scalar_<_Tp>& a, _Tp alpha) +{ + return Scalar_<_Tp>(a.val[0] / alpha, + a.val[1] / alpha, + a.val[2] / alpha, + a.val[3] / alpha); +} + +template static inline +Scalar_ operator / (const Scalar_& a, float alpha) +{ + float s = 1 / alpha; + return Scalar_(a.val[0] * s, a.val[1] * s, a.val[2] * s, a.val[3] * s); +} + +template static inline +Scalar_ operator / (const Scalar_& a, double alpha) +{ + double s = 1 / alpha; + return Scalar_(a.val[0] * s, a.val[1] * s, a.val[2] * s, a.val[3] * s); +} + +template static inline +Scalar_<_Tp>& operator /= (Scalar_<_Tp>& a, _Tp alpha) +{ + a = a / alpha; + return a; +} + +template static inline +Scalar_<_Tp> operator / (_Tp a, const Scalar_<_Tp>& b) +{ + _Tp s = a / (b[0]*b[0] + b[1]*b[1] + b[2]*b[2] + b[3]*b[3]); + return b.conj() * s; +} + +template static inline +Scalar_<_Tp> operator / (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) +{ + return a * ((_Tp)1 / b); +} + +template static inline +Scalar_<_Tp>& operator /= (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) +{ + a = a / b; + return a; +} + +template static inline +Scalar operator * (const Matx<_Tp, 4, 4>& a, const Scalar& b) +{ + Matx c((Matx)a, b, Matx_MatMulOp()); + return reinterpret_cast(c); +} + +template<> inline +Scalar operator * (const Matx& a, const Scalar& b) +{ + Matx c(a, b, Matx_MatMulOp()); + return reinterpret_cast(c); +} + + + +//////////////////////////////// KeyPoint /////////////////////////////// + +inline +KeyPoint::KeyPoint() + : pt(0,0), size(0), angle(-1), response(0), octave(0), class_id(-1) {} + +inline +KeyPoint::KeyPoint(Point2f _pt, float _size, float _angle, float _response, int _octave, int _class_id) + : pt(_pt), size(_size), angle(_angle), response(_response), octave(_octave), class_id(_class_id) {} + +inline +KeyPoint::KeyPoint(float x, float y, float _size, float _angle, float _response, int _octave, int _class_id) + : pt(x, y), size(_size), angle(_angle), response(_response), octave(_octave), class_id(_class_id) {} + + + +///////////////////////////////// DMatch //////////////////////////////// + +inline +DMatch::DMatch() + : queryIdx(-1), trainIdx(-1), imgIdx(-1), distance(FLT_MAX) {} + +inline +DMatch::DMatch(int _queryIdx, int _trainIdx, float _distance) + : queryIdx(_queryIdx), trainIdx(_trainIdx), imgIdx(-1), distance(_distance) {} + +inline +DMatch::DMatch(int _queryIdx, int _trainIdx, int _imgIdx, float _distance) + : queryIdx(_queryIdx), trainIdx(_trainIdx), imgIdx(_imgIdx), distance(_distance) {} + +inline +bool DMatch::operator < (const DMatch &m) const +{ + return distance < m.distance; +} + + + +////////////////////////////// TermCriteria ///////////////////////////// + +inline +TermCriteria::TermCriteria() + : type(0), maxCount(0), epsilon(0) {} + +inline +TermCriteria::TermCriteria(int _type, int _maxCount, double _epsilon) + : type(_type), maxCount(_maxCount), epsilon(_epsilon) {} + +//! @endcond + +} // cv + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#endif //OPENCV_CORE_TYPES_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/types_c.h b/3rdParty/opencv-4.11.0/opencv2/core/types_c.h index 02d4a4f680..473062a53f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/types_c.h +++ b/3rdParty/opencv-4.11.0/opencv2/core/types_c.h @@ -1,2110 +1,2110 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CORE_TYPES_H -#define OPENCV_CORE_TYPES_H - -#ifdef CV__ENABLE_C_API_CTORS // invalid C API ctors (must be removed) -#if defined(_WIN32) && !defined(CV__SKIP_MESSAGE_MALFORMED_C_API_CTORS) -#error "C API ctors don't work on Win32: https://github.com/opencv/opencv/issues/15990" -#endif -#endif - -//#define CV__VALIDATE_UNUNITIALIZED_VARS 1 // C++11 & GCC only - -#ifdef __cplusplus - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS -#pragma GCC diagnostic ignored "-Wmissing-field-initializers" -#define CV_STRUCT_INITIALIZER {0,} -#else -#if defined(__GNUC__) && __GNUC__ == 4 // GCC 4.x warns on "= {}" initialization, fixed in GCC 5.0 -#pragma GCC diagnostic ignored "-Wmissing-field-initializers" -#endif -#define CV_STRUCT_INITIALIZER {} -#endif - -#else -#define CV_STRUCT_INITIALIZER {0} -#endif - - -#ifdef HAVE_IPL -# ifndef __IPL_H__ -# if defined _WIN32 -# include -# else -# include -# endif -# endif -#elif defined __IPL_H__ -# define HAVE_IPL -#endif - -#include "opencv2/core/cvdef.h" - -#ifndef SKIP_INCLUDES -#include -#include -#include -#include -#endif // SKIP_INCLUDES - - - -#ifndef CV_DEFAULT -# ifdef __cplusplus -# define CV_DEFAULT(val) = val -# else -# define CV_DEFAULT(val) -# endif -#endif - -#ifndef CV_EXTERN_C_FUNCPTR -# ifdef __cplusplus -# define CV_EXTERN_C_FUNCPTR(x) extern "C" { typedef x; } -# else -# define CV_EXTERN_C_FUNCPTR(x) typedef x -# endif -#endif - -#ifndef CVAPI -# define CVAPI(rettype) CV_EXTERN_C CV_EXPORTS rettype CV_CDECL -#endif - -#ifndef CV_IMPL -# define CV_IMPL CV_EXTERN_C -#endif - -#ifdef __cplusplus -# include "opencv2/core.hpp" -#endif - -/** @addtogroup core_c - @{ -*/ - -/** @brief This is the "metatype" used *only* as a function parameter. - -It denotes that the function accepts arrays of multiple types, such as IplImage*, CvMat* or even -CvSeq* sometimes. The particular array type is determined at runtime by analyzing the first 4 -bytes of the header. In C++ interface the role of CvArr is played by InputArray and OutputArray. - */ -typedef void CvArr; - -typedef int CVStatus; - -/** @see cv::Error::Code */ -enum { - CV_StsOk= 0, /**< everything is ok */ - CV_StsBackTrace= -1, /**< pseudo error for back trace */ - CV_StsError= -2, /**< unknown /unspecified error */ - CV_StsInternal= -3, /**< internal error (bad state) */ - CV_StsNoMem= -4, /**< insufficient memory */ - CV_StsBadArg= -5, /**< function arg/param is bad */ - CV_StsBadFunc= -6, /**< unsupported function */ - CV_StsNoConv= -7, /**< iter. didn't converge */ - CV_StsAutoTrace= -8, /**< tracing */ - CV_HeaderIsNull= -9, /**< image header is NULL */ - CV_BadImageSize= -10, /**< image size is invalid */ - CV_BadOffset= -11, /**< offset is invalid */ - CV_BadDataPtr= -12, /**/ - CV_BadStep= -13, /**< image step is wrong, this may happen for a non-continuous matrix */ - CV_BadModelOrChSeq= -14, /**/ - CV_BadNumChannels= -15, /**< bad number of channels, for example, some functions accept only single channel matrices */ - CV_BadNumChannel1U= -16, /**/ - CV_BadDepth= -17, /**< input image depth is not supported by the function */ - CV_BadAlphaChannel= -18, /**/ - CV_BadOrder= -19, /**< number of dimensions is out of range */ - CV_BadOrigin= -20, /**< incorrect input origin */ - CV_BadAlign= -21, /**< incorrect input align */ - CV_BadCallBack= -22, /**/ - CV_BadTileSize= -23, /**/ - CV_BadCOI= -24, /**< input COI is not supported */ - CV_BadROISize= -25, /**< incorrect input roi */ - CV_MaskIsTiled= -26, /**/ - CV_StsNullPtr= -27, /**< null pointer */ - CV_StsVecLengthErr= -28, /**< incorrect vector length */ - CV_StsFilterStructContentErr= -29, /**< incorrect filter structure content */ - CV_StsKernelStructContentErr= -30, /**< incorrect transform kernel content */ - CV_StsFilterOffsetErr= -31, /**< incorrect filter offset value */ - CV_StsBadSize= -201, /**< the input/output structure size is incorrect */ - CV_StsDivByZero= -202, /**< division by zero */ - CV_StsInplaceNotSupported= -203, /**< in-place operation is not supported */ - CV_StsObjectNotFound= -204, /**< request can't be completed */ - CV_StsUnmatchedFormats= -205, /**< formats of input/output arrays differ */ - CV_StsBadFlag= -206, /**< flag is wrong or not supported */ - CV_StsBadPoint= -207, /**< bad CvPoint */ - CV_StsBadMask= -208, /**< bad format of mask (neither 8uC1 nor 8sC1)*/ - CV_StsUnmatchedSizes= -209, /**< sizes of input/output structures do not match */ - CV_StsUnsupportedFormat= -210, /**< the data format/type is not supported by the function*/ - CV_StsOutOfRange= -211, /**< some of parameters are out of range */ - CV_StsParseError= -212, /**< invalid syntax/structure of the parsed file */ - CV_StsNotImplemented= -213, /**< the requested function/feature is not implemented */ - CV_StsBadMemBlock= -214, /**< an allocated block has been corrupted */ - CV_StsAssert= -215, /**< assertion failed */ - CV_GpuNotSupported= -216, /**< no CUDA support */ - CV_GpuApiCallError= -217, /**< GPU API call error */ - CV_OpenGlNotSupported= -218, /**< no OpenGL support */ - CV_OpenGlApiCallError= -219, /**< OpenGL API call error */ - CV_OpenCLApiCallError= -220, /**< OpenCL API call error */ - CV_OpenCLDoubleNotSupported= -221, - CV_OpenCLInitError= -222, /**< OpenCL initialization error */ - CV_OpenCLNoAMDBlasFft= -223 -}; - -/****************************************************************************************\ -* Common macros and inline functions * -\****************************************************************************************/ - -/** absolute value without jumps */ -#ifndef __cplusplus -# define CV_IABS(a) (((a) ^ ((a) < 0 ? -1 : 0)) - ((a) < 0 ? -1 : 0)) -#else -# define CV_IABS(a) abs(a) -#endif - - -#define cvInvSqrt(value) ((float)(1./sqrt(value))) -#define cvSqrt(value) ((float)sqrt(value)) - - -/*************** Random number generation *******************/ - -typedef uint64 CvRNG; - -#define CV_RNG_COEFF 4164903690U - -/** @brief Initializes a random number generator state. - -The function initializes a random number generator and returns the state. The pointer to the state -can be then passed to the cvRandInt, cvRandReal and cvRandArr functions. In the current -implementation a multiply-with-carry generator is used. -@param seed 64-bit value used to initiate a random sequence -@sa the C++ class RNG replaced CvRNG. - */ -CV_INLINE CvRNG cvRNG( int64 seed CV_DEFAULT(-1)) -{ - CvRNG rng = seed ? (uint64)seed : (uint64)(int64)-1; - return rng; -} - -/** @brief Returns a 32-bit unsigned integer and updates RNG. - -The function returns a uniformly-distributed random 32-bit unsigned integer and updates the RNG -state. It is similar to the rand() function from the C runtime library, except that OpenCV functions -always generates a 32-bit random number, regardless of the platform. -@param rng CvRNG state initialized by cvRNG. - */ -CV_INLINE unsigned cvRandInt( CvRNG* rng ) -{ - uint64 temp = *rng; - temp = (uint64)(unsigned)temp*CV_RNG_COEFF + (temp >> 32); - *rng = temp; - return (unsigned)temp; -} - -/** @brief Returns a floating-point random number and updates RNG. - -The function returns a uniformly-distributed random floating-point number between 0 and 1 (1 is not -included). -@param rng RNG state initialized by cvRNG - */ -CV_INLINE double cvRandReal( CvRNG* rng ) -{ - return cvRandInt(rng)*2.3283064365386962890625e-10 /* 2^-32 */; -} - -/****************************************************************************************\ -* Image type (IplImage) * -\****************************************************************************************/ - -#ifndef HAVE_IPL - -/* - * The following definitions (until #endif) - * is an extract from IPL headers. - * Copyright (c) 1995 Intel Corporation. - */ -#define IPL_DEPTH_SIGN 0x80000000 - -#define IPL_DEPTH_1U 1 -#define IPL_DEPTH_8U 8 -#define IPL_DEPTH_16U 16 -#define IPL_DEPTH_32F 32 - -#define IPL_DEPTH_8S (IPL_DEPTH_SIGN| 8) -#define IPL_DEPTH_16S (IPL_DEPTH_SIGN|16) -#define IPL_DEPTH_32S (IPL_DEPTH_SIGN|32) - -#define IPL_DATA_ORDER_PIXEL 0 -#define IPL_DATA_ORDER_PLANE 1 - -#define IPL_ORIGIN_TL 0 -#define IPL_ORIGIN_BL 1 - -#define IPL_ALIGN_4BYTES 4 -#define IPL_ALIGN_8BYTES 8 -#define IPL_ALIGN_16BYTES 16 -#define IPL_ALIGN_32BYTES 32 - -#define IPL_ALIGN_DWORD IPL_ALIGN_4BYTES -#define IPL_ALIGN_QWORD IPL_ALIGN_8BYTES - -#define IPL_BORDER_CONSTANT 0 -#define IPL_BORDER_REPLICATE 1 -#define IPL_BORDER_REFLECT 2 -#define IPL_BORDER_WRAP 3 - -#ifdef __cplusplus -typedef struct _IplImage IplImage; -CV_EXPORTS _IplImage cvIplImage(const cv::Mat& m); -#endif - -/** The IplImage is taken from the Intel Image Processing Library, in which the format is native. OpenCV -only supports a subset of possible IplImage formats, as outlined in the parameter list above. - -In addition to the above restrictions, OpenCV handles ROIs differently. OpenCV functions require -that the image size or ROI size of all source and destination images match exactly. On the other -hand, the Intel Image Processing Library processes the area of intersection between the source and -destination images (or ROIs), allowing them to vary independently. -*/ -typedef struct -_IplImage -{ - int nSize; /**< sizeof(IplImage) */ - int ID; /**< version (=0)*/ - int nChannels; /**< Most of OpenCV functions support 1,2,3 or 4 channels */ - int alphaChannel; /**< Ignored by OpenCV */ - int depth; /**< Pixel depth in bits: IPL_DEPTH_8U, IPL_DEPTH_8S, IPL_DEPTH_16S, - IPL_DEPTH_32S, IPL_DEPTH_32F and IPL_DEPTH_64F are supported. */ - char colorModel[4]; /**< Ignored by OpenCV */ - char channelSeq[4]; /**< ditto */ - int dataOrder; /**< 0 - interleaved color channels, 1 - separate color channels. - cvCreateImage can only create interleaved images */ - int origin; /**< 0 - top-left origin, - 1 - bottom-left origin (Windows bitmaps style). */ - int align; /**< Alignment of image rows (4 or 8). - OpenCV ignores it and uses widthStep instead. */ - int width; /**< Image width in pixels. */ - int height; /**< Image height in pixels. */ - struct _IplROI *roi; /**< Image ROI. If NULL, the whole image is selected. */ - struct _IplImage *maskROI; /**< Must be NULL. */ - void *imageId; /**< " " */ - struct _IplTileInfo *tileInfo; /**< " " */ - int imageSize; /**< Image data size in bytes - (==image->height*image->widthStep - in case of interleaved data)*/ - char *imageData; /**< Pointer to aligned image data. */ - int widthStep; /**< Size of aligned image row in bytes. */ - int BorderMode[4]; /**< Ignored by OpenCV. */ - int BorderConst[4]; /**< Ditto. */ - char *imageDataOrigin; /**< Pointer to very origin of image data - (not necessarily aligned) - - needed for correct deallocation */ - -#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - _IplImage() - { - memset(this, 0, sizeof(*this)); // valid for POD structure - nSize = sizeof(IplImage); - } - _IplImage(const cv::Mat& m) { *this = cvIplImage(m); } -#endif -} -IplImage; - -CV_INLINE IplImage cvIplImage() -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - IplImage self = CV_STRUCT_INITIALIZER; self.nSize = sizeof(IplImage); return self; -#else - return _IplImage(); -#endif -} - -typedef struct _IplTileInfo IplTileInfo; - -typedef struct _IplROI -{ - int coi; /**< 0 - no COI (all channels are selected), 1 - 0th channel is selected ...*/ - int xOffset; - int yOffset; - int width; - int height; -} -IplROI; - -typedef struct _IplConvKernel -{ - int nCols; - int nRows; - int anchorX; - int anchorY; - int *values; - int nShiftR; -} -IplConvKernel; - -typedef struct _IplConvKernelFP -{ - int nCols; - int nRows; - int anchorX; - int anchorY; - float *values; -} -IplConvKernelFP; - -#define IPL_IMAGE_HEADER 1 -#define IPL_IMAGE_DATA 2 -#define IPL_IMAGE_ROI 4 - -#endif/*HAVE_IPL*/ - -/** extra border mode */ -#define IPL_BORDER_REFLECT_101 4 -#define IPL_BORDER_TRANSPARENT 5 - -#define IPL_IMAGE_MAGIC_VAL ((int)sizeof(IplImage)) -#define CV_TYPE_NAME_IMAGE "opencv-image" - -#define CV_IS_IMAGE_HDR(img) \ - ((img) != NULL && ((const IplImage*)(img))->nSize == sizeof(IplImage)) - -#define CV_IS_IMAGE(img) \ - (CV_IS_IMAGE_HDR(img) && ((IplImage*)img)->imageData != NULL) - -/** for storing double-precision - floating point data in IplImage's */ -#define IPL_DEPTH_64F 64 - -/** get reference to pixel at (col,row), - for multi-channel images (col) should be multiplied by number of channels */ -#define CV_IMAGE_ELEM( image, elemtype, row, col ) \ - (((elemtype*)((image)->imageData + (image)->widthStep*(row)))[(col)]) - -/****************************************************************************************\ -* Matrix type (CvMat) * -\****************************************************************************************/ - -#define CV_AUTO_STEP 0x7fffffff -#define CV_WHOLE_ARR cvSlice( 0, 0x3fffffff ) - -#define CV_MAGIC_MASK 0xFFFF0000 -#define CV_MAT_MAGIC_VAL 0x42420000 -#define CV_TYPE_NAME_MAT "opencv-matrix" - -#ifdef __cplusplus -typedef struct CvMat CvMat; -CV_INLINE CvMat cvMat(const cv::Mat& m); -#endif - -/** Matrix elements are stored row by row. Element (i, j) (i - 0-based row index, j - 0-based column -index) of a matrix can be retrieved or modified using CV_MAT_ELEM macro: - - uchar pixval = CV_MAT_ELEM(grayimg, uchar, i, j) - CV_MAT_ELEM(cameraMatrix, float, 0, 2) = image.width*0.5f; - -To access multiple-channel matrices, you can use -CV_MAT_ELEM(matrix, type, i, j\*nchannels + channel_idx). - -@deprecated CvMat is now obsolete; consider using Mat instead. - */ -typedef struct CvMat -{ - int type; - int step; - - /* for internal use only */ - int* refcount; - int hdr_refcount; - - union - { - uchar* ptr; - short* s; - int* i; - float* fl; - double* db; - } data; - -#ifdef __cplusplus - union - { - int rows; - int height; - }; - - union - { - int cols; - int width; - }; -#else - int rows; - int cols; -#endif - -#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvMat() {} - CvMat(const cv::Mat& m) { *this = cvMat(m); } -#endif -} -CvMat; - - -#define CV_IS_MAT_HDR(mat) \ - ((mat) != NULL && \ - (((const CvMat*)(mat))->type & CV_MAGIC_MASK) == CV_MAT_MAGIC_VAL && \ - ((const CvMat*)(mat))->cols > 0 && ((const CvMat*)(mat))->rows > 0) - -#define CV_IS_MAT_HDR_Z(mat) \ - ((mat) != NULL && \ - (((const CvMat*)(mat))->type & CV_MAGIC_MASK) == CV_MAT_MAGIC_VAL && \ - ((const CvMat*)(mat))->cols >= 0 && ((const CvMat*)(mat))->rows >= 0) - -#define CV_IS_MAT(mat) \ - (CV_IS_MAT_HDR(mat) && ((const CvMat*)(mat))->data.ptr != NULL) - -#define CV_IS_MASK_ARR(mat) \ - (((mat)->type & (CV_MAT_TYPE_MASK & ~CV_8SC1)) == 0) - -#define CV_ARE_TYPES_EQ(mat1, mat2) \ - ((((mat1)->type ^ (mat2)->type) & CV_MAT_TYPE_MASK) == 0) - -#define CV_ARE_CNS_EQ(mat1, mat2) \ - ((((mat1)->type ^ (mat2)->type) & CV_MAT_CN_MASK) == 0) - -#define CV_ARE_DEPTHS_EQ(mat1, mat2) \ - ((((mat1)->type ^ (mat2)->type) & CV_MAT_DEPTH_MASK) == 0) - -#define CV_ARE_SIZES_EQ(mat1, mat2) \ - ((mat1)->rows == (mat2)->rows && (mat1)->cols == (mat2)->cols) - -#define CV_IS_MAT_CONST(mat) \ - (((mat)->rows|(mat)->cols) == 1) - -#define IPL2CV_DEPTH(depth) \ - ((((CV_8U)+(CV_16U<<4)+(CV_32F<<8)+(CV_64F<<16)+(CV_8S<<20)+ \ - (CV_16S<<24)+(CV_32S<<28)) >> ((((depth) & 0xF0) >> 2) + \ - (((depth) & IPL_DEPTH_SIGN) ? 20 : 0))) & 15) - -/** Inline constructor. No data is allocated internally!!! - * (Use together with cvCreateData, or use cvCreateMat instead to - * get a matrix with allocated data): - */ -CV_INLINE CvMat cvMat( int rows, int cols, int type, void* data CV_DEFAULT(NULL)) -{ - CvMat m; - - assert( (unsigned)CV_MAT_DEPTH(type) <= CV_64F ); - type = CV_MAT_TYPE(type); - m.type = CV_MAT_MAGIC_VAL | CV_MAT_CONT_FLAG | type; - m.cols = cols; - m.rows = rows; - m.step = m.cols*CV_ELEM_SIZE(type); - m.data.ptr = (uchar*)data; - m.refcount = NULL; - m.hdr_refcount = 0; - - return m; -} - -#ifdef __cplusplus - -CV_INLINE CvMat cvMat(const cv::Mat& m) -{ - CvMat self; - CV_DbgAssert(m.dims <= 2); - self = cvMat(m.rows, m.dims == 1 ? 1 : m.cols, m.type(), m.data); - self.step = (int)m.step[0]; - self.type = (self.type & ~cv::Mat::CONTINUOUS_FLAG) | (m.flags & cv::Mat::CONTINUOUS_FLAG); - return self; -} -CV_INLINE CvMat cvMat() -{ -#if !defined(CV__ENABLE_C_API_CTORS) - CvMat self = CV_STRUCT_INITIALIZER; return self; -#else - return CvMat(); -#endif -} -CV_INLINE CvMat cvMat(const CvMat& m) -{ -#if !defined(CV__ENABLE_C_API_CTORS) - CvMat self = CV_STRUCT_INITIALIZER; memcpy(&self, &m, sizeof(self)); return self; -#else - return CvMat(m); -#endif -} - -#endif // __cplusplus - - -#define CV_MAT_ELEM_PTR_FAST( mat, row, col, pix_size ) \ - (assert( (unsigned)(row) < (unsigned)(mat).rows && \ - (unsigned)(col) < (unsigned)(mat).cols ), \ - (mat).data.ptr + (size_t)(mat).step*(row) + (pix_size)*(col)) - -#define CV_MAT_ELEM_PTR( mat, row, col ) \ - CV_MAT_ELEM_PTR_FAST( mat, row, col, CV_ELEM_SIZE((mat).type) ) - -#define CV_MAT_ELEM( mat, elemtype, row, col ) \ - (*(elemtype*)CV_MAT_ELEM_PTR_FAST( mat, row, col, sizeof(elemtype))) - -/** @brief Returns the particular element of single-channel floating-point matrix. - -The function is a fast replacement for cvGetReal2D in the case of single-channel floating-point -matrices. It is faster because it is inline, it does fewer checks for array type and array element -type, and it checks for the row and column ranges only in debug mode. -@param mat Input matrix -@param row The zero-based index of row -@param col The zero-based index of column - */ -CV_INLINE double cvmGet( const CvMat* mat, int row, int col ) -{ - int type; - - type = CV_MAT_TYPE(mat->type); - assert( (unsigned)row < (unsigned)mat->rows && - (unsigned)col < (unsigned)mat->cols ); - - if( type == CV_32FC1 ) - return ((float*)(void*)(mat->data.ptr + (size_t)mat->step*row))[col]; - else - { - assert( type == CV_64FC1 ); - return ((double*)(void*)(mat->data.ptr + (size_t)mat->step*row))[col]; - } -} - -/** @brief Sets a specific element of a single-channel floating-point matrix. - -The function is a fast replacement for cvSetReal2D in the case of single-channel floating-point -matrices. It is faster because it is inline, it does fewer checks for array type and array element -type, and it checks for the row and column ranges only in debug mode. -@param mat The matrix -@param row The zero-based index of row -@param col The zero-based index of column -@param value The new value of the matrix element - */ -CV_INLINE void cvmSet( CvMat* mat, int row, int col, double value ) -{ - int type; - type = CV_MAT_TYPE(mat->type); - assert( (unsigned)row < (unsigned)mat->rows && - (unsigned)col < (unsigned)mat->cols ); - - if( type == CV_32FC1 ) - ((float*)(void*)(mat->data.ptr + (size_t)mat->step*row))[col] = (float)value; - else - { - assert( type == CV_64FC1 ); - ((double*)(void*)(mat->data.ptr + (size_t)mat->step*row))[col] = value; - } -} - - -CV_INLINE int cvIplDepth( int type ) -{ - int depth = CV_MAT_DEPTH(type); - return CV_ELEM_SIZE1(depth)*8 | (depth == CV_8S || depth == CV_16S || - depth == CV_32S ? IPL_DEPTH_SIGN : 0); -} - - -/****************************************************************************************\ -* Multi-dimensional dense array (CvMatND) * -\****************************************************************************************/ - -#define CV_MATND_MAGIC_VAL 0x42430000 -#define CV_TYPE_NAME_MATND "opencv-nd-matrix" - -#ifdef __cplusplus -typedef struct CvMatND CvMatND; -CV_EXPORTS CvMatND cvMatND(const cv::Mat& m); -#endif - -/** - @deprecated consider using cv::Mat instead - */ -typedef struct -CvMatND -{ - int type; - int dims; - - int* refcount; - int hdr_refcount; - - union - { - uchar* ptr; - float* fl; - double* db; - int* i; - short* s; - } data; - - struct - { - int size; - int step; - } - dim[CV_MAX_DIM]; - -#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvMatND() {} - CvMatND(const cv::Mat& m) { *this = cvMatND(m); } -#endif -} -CvMatND; - - -CV_INLINE CvMatND cvMatND() -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvMatND self = CV_STRUCT_INITIALIZER; return self; -#else - return CvMatND(); -#endif -} - -#define CV_IS_MATND_HDR(mat) \ - ((mat) != NULL && (((const CvMatND*)(mat))->type & CV_MAGIC_MASK) == CV_MATND_MAGIC_VAL) - -#define CV_IS_MATND(mat) \ - (CV_IS_MATND_HDR(mat) && ((const CvMatND*)(mat))->data.ptr != NULL) - - -/****************************************************************************************\ -* Multi-dimensional sparse array (CvSparseMat) * -\****************************************************************************************/ - -#define CV_SPARSE_MAT_MAGIC_VAL 0x42440000 -#define CV_TYPE_NAME_SPARSE_MAT "opencv-sparse-matrix" - -struct CvSet; - -typedef struct CvSparseMat -{ - int type; - int dims; - int* refcount; - int hdr_refcount; - - struct CvSet* heap; - void** hashtable; - int hashsize; - int valoffset; - int idxoffset; - int size[CV_MAX_DIM]; - -#ifdef __cplusplus - CV_EXPORTS void copyToSparseMat(cv::SparseMat& m) const; -#endif -} -CvSparseMat; - -#ifdef __cplusplus -CV_EXPORTS CvSparseMat* cvCreateSparseMat(const cv::SparseMat& m); -#endif - -#define CV_IS_SPARSE_MAT_HDR(mat) \ - ((mat) != NULL && \ - (((const CvSparseMat*)(mat))->type & CV_MAGIC_MASK) == CV_SPARSE_MAT_MAGIC_VAL) - -#define CV_IS_SPARSE_MAT(mat) \ - CV_IS_SPARSE_MAT_HDR(mat) - -/**************** iteration through a sparse array *****************/ - -typedef struct CvSparseNode -{ - unsigned hashval; - struct CvSparseNode* next; -} -CvSparseNode; - -typedef struct CvSparseMatIterator -{ - CvSparseMat* mat; - CvSparseNode* node; - int curidx; -} -CvSparseMatIterator; - -#define CV_NODE_VAL(mat,node) ((void*)((uchar*)(node) + (mat)->valoffset)) -#define CV_NODE_IDX(mat,node) ((int*)((uchar*)(node) + (mat)->idxoffset)) - -/****************************************************************************************\ -* Histogram * -\****************************************************************************************/ - -typedef int CvHistType; - -#define CV_HIST_MAGIC_VAL 0x42450000 -#define CV_HIST_UNIFORM_FLAG (1 << 10) - -/** indicates whether bin ranges are set already or not */ -#define CV_HIST_RANGES_FLAG (1 << 11) - -#define CV_HIST_ARRAY 0 -#define CV_HIST_SPARSE 1 -#define CV_HIST_TREE CV_HIST_SPARSE - -/** should be used as a parameter only, - it turns to CV_HIST_UNIFORM_FLAG of hist->type */ -#define CV_HIST_UNIFORM 1 - -typedef struct CvHistogram -{ - int type; - CvArr* bins; - float thresh[CV_MAX_DIM][2]; /**< For uniform histograms. */ - float** thresh2; /**< For non-uniform histograms. */ - CvMatND mat; /**< Embedded matrix header for array histograms. */ -} -CvHistogram; - -#define CV_IS_HIST( hist ) \ - ((hist) != NULL && \ - (((CvHistogram*)(hist))->type & CV_MAGIC_MASK) == CV_HIST_MAGIC_VAL && \ - (hist)->bins != NULL) - -#define CV_IS_UNIFORM_HIST( hist ) \ - (((hist)->type & CV_HIST_UNIFORM_FLAG) != 0) - -#define CV_IS_SPARSE_HIST( hist ) \ - CV_IS_SPARSE_MAT((hist)->bins) - -#define CV_HIST_HAS_RANGES( hist ) \ - (((hist)->type & CV_HIST_RANGES_FLAG) != 0) - -/****************************************************************************************\ -* Other supplementary data type definitions * -\****************************************************************************************/ - -/*************************************** CvRect *****************************************/ -/** @sa Rect_ */ -typedef struct CvRect -{ - int x; - int y; - int width; - int height; - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvRect() __attribute__(( warning("Non-initialized variable") )) {}; - template CvRect(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 4); - x = y = width = height = 0; - if (list.size() == 4) - { - x = list.begin()[0]; y = list.begin()[1]; width = list.begin()[2]; height = list.begin()[3]; - } - }; -#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvRect(int _x = 0, int _y = 0, int w = 0, int h = 0): x(_x), y(_y), width(w), height(h) {} - template - CvRect(const cv::Rect_<_Tp>& r): x(cv::saturate_cast(r.x)), y(cv::saturate_cast(r.y)), width(cv::saturate_cast(r.width)), height(cv::saturate_cast(r.height)) {} -#endif -#ifdef __cplusplus - template - operator cv::Rect_<_Tp>() const { return cv::Rect_<_Tp>((_Tp)x, (_Tp)y, (_Tp)width, (_Tp)height); } -#endif -} -CvRect; - -/** constructs CvRect structure. */ -CV_INLINE CvRect cvRect( int x, int y, int width, int height ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvRect r = {x, y, width, height}; -#else - CvRect r(x, y , width, height); -#endif - return r; -} -#ifdef __cplusplus -CV_INLINE CvRect cvRect(const cv::Rect& rc) { return cvRect(rc.x, rc.y, rc.width, rc.height); } -#endif - -CV_INLINE IplROI cvRectToROI( CvRect rect, int coi ) -{ - IplROI roi; - roi.xOffset = rect.x; - roi.yOffset = rect.y; - roi.width = rect.width; - roi.height = rect.height; - roi.coi = coi; - - return roi; -} - - -CV_INLINE CvRect cvROIToRect( IplROI roi ) -{ - return cvRect( roi.xOffset, roi.yOffset, roi.width, roi.height ); -} - -/*********************************** CvTermCriteria *************************************/ - -#define CV_TERMCRIT_ITER 1 -#define CV_TERMCRIT_NUMBER CV_TERMCRIT_ITER -#define CV_TERMCRIT_EPS 2 - -/** @sa TermCriteria - */ -typedef struct CvTermCriteria -{ - int type; /**< may be combination of - CV_TERMCRIT_ITER - CV_TERMCRIT_EPS */ - int max_iter; - double epsilon; -#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvTermCriteria(int _type = 0, int _iter = 0, double _eps = 0) : type(_type), max_iter(_iter), epsilon(_eps) {} - CvTermCriteria(const cv::TermCriteria& t) : type(t.type), max_iter(t.maxCount), epsilon(t.epsilon) {} -#endif -#ifdef __cplusplus - operator cv::TermCriteria() const { return cv::TermCriteria(type, max_iter, epsilon); } -#endif -} -CvTermCriteria; - -CV_INLINE CvTermCriteria cvTermCriteria( int type, int max_iter, double epsilon ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvTermCriteria t = { type, max_iter, (float)epsilon}; -#else - CvTermCriteria t(type, max_iter, epsilon); -#endif - return t; -} -#ifdef __cplusplus -CV_INLINE CvTermCriteria cvTermCriteria(const cv::TermCriteria& t) { return cvTermCriteria(t.type, t.maxCount, t.epsilon); } -#endif - - -/******************************* CvPoint and variants ***********************************/ - -typedef struct CvPoint -{ - int x; - int y; - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvPoint() __attribute__(( warning("Non-initialized variable") )) {} - template CvPoint(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 2); - x = y = 0; - if (list.size() == 2) - { - x = list.begin()[0]; y = list.begin()[1]; - } - }; -#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvPoint(int _x = 0, int _y = 0): x(_x), y(_y) {} - template - CvPoint(const cv::Point_<_Tp>& pt): x((int)pt.x), y((int)pt.y) {} -#endif -#ifdef __cplusplus - template - operator cv::Point_<_Tp>() const { return cv::Point_<_Tp>(cv::saturate_cast<_Tp>(x), cv::saturate_cast<_Tp>(y)); } -#endif -} -CvPoint; - -/** constructs CvPoint structure. */ -CV_INLINE CvPoint cvPoint( int x, int y ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvPoint p = {x, y}; -#else - CvPoint p(x, y); -#endif - return p; -} -#ifdef __cplusplus -CV_INLINE CvPoint cvPoint(const cv::Point& pt) { return cvPoint(pt.x, pt.y); } -#endif - -typedef struct CvPoint2D32f -{ - float x; - float y; - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvPoint2D32f() __attribute__(( warning("Non-initialized variable") )) {} - template CvPoint2D32f(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 2); - x = y = 0; - if (list.size() == 2) - { - x = list.begin()[0]; y = list.begin()[1]; - } - }; -#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvPoint2D32f(float _x = 0, float _y = 0): x(_x), y(_y) {} - template - CvPoint2D32f(const cv::Point_<_Tp>& pt): x((float)pt.x), y((float)pt.y) {} -#endif -#ifdef __cplusplus - template - operator cv::Point_<_Tp>() const { return cv::Point_<_Tp>(cv::saturate_cast<_Tp>(x), cv::saturate_cast<_Tp>(y)); } -#endif -} -CvPoint2D32f; - -/** constructs CvPoint2D32f structure. */ -CV_INLINE CvPoint2D32f cvPoint2D32f( double x, double y ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvPoint2D32f p = { (float)x, (float)y }; -#else - CvPoint2D32f p((float)x, (float)y); -#endif - return p; -} - -#ifdef __cplusplus -template -CvPoint2D32f cvPoint2D32f(const cv::Point_<_Tp>& pt) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvPoint2D32f p = { (float)pt.x, (float)pt.y }; -#else - CvPoint2D32f p((float)pt.x, (float)pt.y); -#endif - return p; -} -#endif - -/** converts CvPoint to CvPoint2D32f. */ -CV_INLINE CvPoint2D32f cvPointTo32f( CvPoint point ) -{ - return cvPoint2D32f( (float)point.x, (float)point.y ); -} - -/** converts CvPoint2D32f to CvPoint. */ -CV_INLINE CvPoint cvPointFrom32f( CvPoint2D32f point ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvPoint ipt = { cvRound(point.x), cvRound(point.y) }; -#else - CvPoint ipt(cvRound(point.x), cvRound(point.y)); -#endif - return ipt; -} - - -typedef struct CvPoint3D32f -{ - float x; - float y; - float z; - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvPoint3D32f() __attribute__(( warning("Non-initialized variable") )) {} - template CvPoint3D32f(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 3); - x = y = z = 0; - if (list.size() == 3) - { - x = list.begin()[0]; y = list.begin()[1]; z = list.begin()[2]; - } - }; -#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvPoint3D32f(float _x = 0, float _y = 0, float _z = 0): x(_x), y(_y), z(_z) {} - template - CvPoint3D32f(const cv::Point3_<_Tp>& pt): x((float)pt.x), y((float)pt.y), z((float)pt.z) {} -#endif -#ifdef __cplusplus - template - operator cv::Point3_<_Tp>() const { return cv::Point3_<_Tp>(cv::saturate_cast<_Tp>(x), cv::saturate_cast<_Tp>(y), cv::saturate_cast<_Tp>(z)); } -#endif -} -CvPoint3D32f; - -/** constructs CvPoint3D32f structure. */ -CV_INLINE CvPoint3D32f cvPoint3D32f( double x, double y, double z ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvPoint3D32f p = { (float)x, (float)y, (float)z }; -#else - CvPoint3D32f p((float)x, (float)y, (float)z); -#endif - return p; -} - -#ifdef __cplusplus -template -CvPoint3D32f cvPoint3D32f(const cv::Point3_<_Tp>& pt) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvPoint3D32f p = { (float)pt.x, (float)pt.y, (float)pt.z }; -#else - CvPoint3D32f p((float)pt.x, (float)pt.y, (float)pt.z); -#endif - return p; -} -#endif - - -typedef struct CvPoint2D64f -{ - double x; - double y; -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvPoint2D64f() __attribute__(( warning("Non-initialized variable") )) {} - template CvPoint2D64f(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 2); - x = y = 0; - if (list.size() == 2) - { - x = list.begin()[0]; y = list.begin()[1]; - } - }; -#endif -} -CvPoint2D64f; - -/** constructs CvPoint2D64f structure.*/ -CV_INLINE CvPoint2D64f cvPoint2D64f( double x, double y ) -{ - CvPoint2D64f p = { x, y }; - return p; -} - - -typedef struct CvPoint3D64f -{ - double x; - double y; - double z; -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvPoint3D64f() __attribute__(( warning("Non-initialized variable") )) {} - template CvPoint3D64f(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 3); - x = y = z = 0; - if (list.size() == 3) - { - x = list.begin()[0]; y = list.begin()[1]; z = list.begin()[2]; - } - }; -#endif -} -CvPoint3D64f; - -/** constructs CvPoint3D64f structure. */ -CV_INLINE CvPoint3D64f cvPoint3D64f( double x, double y, double z ) -{ - CvPoint3D64f p = { x, y, z }; - return p; -} - - -/******************************** CvSize's & CvBox **************************************/ - -typedef struct CvSize -{ - int width; - int height; - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvSize() __attribute__(( warning("Non-initialized variable") )) {} - template CvSize(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 2); - width = 0; height = 0; - if (list.size() == 2) - { - width = list.begin()[0]; height = list.begin()[1]; - } - }; -#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvSize(int w = 0, int h = 0): width(w), height(h) {} - template - CvSize(const cv::Size_<_Tp>& sz): width(cv::saturate_cast(sz.width)), height(cv::saturate_cast(sz.height)) {} -#endif -#ifdef __cplusplus - template - operator cv::Size_<_Tp>() const { return cv::Size_<_Tp>(cv::saturate_cast<_Tp>(width), cv::saturate_cast<_Tp>(height)); } -#endif -} -CvSize; - -/** constructs CvSize structure. */ -CV_INLINE CvSize cvSize( int width, int height ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvSize s = { width, height }; -#else - CvSize s(width, height); -#endif - return s; -} - -#ifdef __cplusplus -CV_INLINE CvSize cvSize(const cv::Size& sz) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvSize s = { sz.width, sz.height }; -#else - CvSize s(sz.width, sz.height); -#endif - return s; -} -#endif - -typedef struct CvSize2D32f -{ - float width; - float height; - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvSize2D32f() __attribute__(( warning("Non-initialized variable") )) {} - template CvSize2D32f(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 2); - width = 0; height = 0; - if (list.size() == 2) - { - width = list.begin()[0]; height = list.begin()[1]; - } - }; -#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvSize2D32f(float w = 0, float h = 0): width(w), height(h) {} - template - CvSize2D32f(const cv::Size_<_Tp>& sz): width(cv::saturate_cast(sz.width)), height(cv::saturate_cast(sz.height)) {} -#endif -#ifdef __cplusplus - template - operator cv::Size_<_Tp>() const { return cv::Size_<_Tp>(cv::saturate_cast<_Tp>(width), cv::saturate_cast<_Tp>(height)); } -#endif -} -CvSize2D32f; - -/** constructs CvSize2D32f structure. */ -CV_INLINE CvSize2D32f cvSize2D32f( double width, double height ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvSize2D32f s = { (float)width, (float)height }; -#else - CvSize2D32f s((float)width, (float)height); -#endif - return s; -} -#ifdef __cplusplus -template -CvSize2D32f cvSize2D32f(const cv::Size_<_Tp>& sz) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvSize2D32f s = { (float)sz.width, (float)sz.height }; -#else - CvSize2D32f s((float)sz.width, (float)sz.height); -#endif - return s; -} -#endif - -/** @sa RotatedRect - */ -typedef struct CvBox2D -{ - CvPoint2D32f center; /**< Center of the box. */ - CvSize2D32f size; /**< Box width and length. */ - float angle; /**< Angle between the horizontal axis */ - /**< and the first side (i.e. length) in degrees */ - -#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvBox2D(CvPoint2D32f c = CvPoint2D32f(), CvSize2D32f s = CvSize2D32f(), float a = 0) : center(c), size(s), angle(a) {} - CvBox2D(const cv::RotatedRect& rr) : center(rr.center), size(rr.size), angle(rr.angle) {} -#endif -#ifdef __cplusplus - operator cv::RotatedRect() const { return cv::RotatedRect(center, size, angle); } -#endif -} -CvBox2D; - - -#ifdef __cplusplus -CV_INLINE CvBox2D cvBox2D(CvPoint2D32f c = CvPoint2D32f(), CvSize2D32f s = CvSize2D32f(), float a = 0) -{ - CvBox2D self; - self.center = c; - self.size = s; - self.angle = a; - return self; -} -CV_INLINE CvBox2D cvBox2D(const cv::RotatedRect& rr) -{ - CvBox2D self; - self.center = cvPoint2D32f(rr.center); - self.size = cvSize2D32f(rr.size); - self.angle = rr.angle; - return self; -} -#endif - - -/** Line iterator state: */ -typedef struct CvLineIterator -{ - /** Pointer to the current point: */ - uchar* ptr; - - /* Bresenham algorithm state: */ - int err; - int plus_delta; - int minus_delta; - int plus_step; - int minus_step; -} -CvLineIterator; - - - -/************************************* CvSlice ******************************************/ -#define CV_WHOLE_SEQ_END_INDEX 0x3fffffff -#define CV_WHOLE_SEQ cvSlice(0, CV_WHOLE_SEQ_END_INDEX) - -typedef struct CvSlice -{ - int start_index, end_index; - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvSlice() __attribute__(( warning("Non-initialized variable") )) {} - template CvSlice(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 2); - start_index = end_index = 0; - if (list.size() == 2) - { - start_index = list.begin()[0]; end_index = list.begin()[1]; - } - }; -#endif -#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) && !defined(__CUDACC__) - CvSlice(int start = 0, int end = 0) : start_index(start), end_index(end) {} - CvSlice(const cv::Range& r) { *this = (r.start != INT_MIN && r.end != INT_MAX) ? CvSlice(r.start, r.end) : CvSlice(0, CV_WHOLE_SEQ_END_INDEX); } - operator cv::Range() const { return (start_index == 0 && end_index == CV_WHOLE_SEQ_END_INDEX ) ? cv::Range::all() : cv::Range(start_index, end_index); } -#endif -} -CvSlice; - -CV_INLINE CvSlice cvSlice( int start, int end ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) && !defined(__CUDACC__)) - CvSlice slice = { start, end }; -#else - CvSlice slice(start, end); -#endif - return slice; -} - -#if defined(__cplusplus) -CV_INLINE CvSlice cvSlice(const cv::Range& r) -{ - CvSlice slice = (r.start != INT_MIN && r.end != INT_MAX) ? cvSlice(r.start, r.end) : cvSlice(0, CV_WHOLE_SEQ_END_INDEX); - return slice; -} -#endif - - -/************************************* CvScalar *****************************************/ -/** @sa Scalar_ - */ -typedef struct CvScalar -{ - double val[4]; - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvScalar() __attribute__(( warning("Non-initialized variable") )) {} - CvScalar(const std::initializer_list list) - { - CV_Assert(list.size() == 0 || list.size() == 4); - val[0] = val[1] = val[2] = val[3] = 0; - if (list.size() == 4) - { - val[0] = list.begin()[0]; val[1] = list.begin()[1]; val[2] = list.begin()[2]; val[3] = list.begin()[3]; - } - }; -#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvScalar() {} - CvScalar(double d0, double d1 = 0, double d2 = 0, double d3 = 0) { val[0] = d0; val[1] = d1; val[2] = d2; val[3] = d3; } - template - CvScalar(const cv::Scalar_<_Tp>& s) { val[0] = s.val[0]; val[1] = s.val[1]; val[2] = s.val[2]; val[3] = s.val[3]; } - template - CvScalar(const cv::Vec<_Tp, cn>& v) - { - int i; - for( i = 0; i < (cn < 4 ? cn : 4); i++ ) val[i] = v.val[i]; - for( ; i < 4; i++ ) val[i] = 0; - } -#endif -#ifdef __cplusplus - template - operator cv::Scalar_<_Tp>() const { return cv::Scalar_<_Tp>(cv::saturate_cast<_Tp>(val[0]), cv::saturate_cast<_Tp>(val[1]), cv::saturate_cast<_Tp>(val[2]), cv::saturate_cast<_Tp>(val[3])); } -#endif -} -CvScalar; - -CV_INLINE CvScalar cvScalar( double val0, double val1 CV_DEFAULT(0), - double val2 CV_DEFAULT(0), double val3 CV_DEFAULT(0)) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvScalar scalar = CV_STRUCT_INITIALIZER; -#else - CvScalar scalar; -#endif - scalar.val[0] = val0; scalar.val[1] = val1; - scalar.val[2] = val2; scalar.val[3] = val3; - return scalar; -} - -#ifdef __cplusplus -CV_INLINE CvScalar cvScalar() -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvScalar scalar = CV_STRUCT_INITIALIZER; -#else - CvScalar scalar; -#endif - scalar.val[0] = scalar.val[1] = scalar.val[2] = scalar.val[3] = 0; - return scalar; -} -CV_INLINE CvScalar cvScalar(const cv::Scalar& s) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvScalar scalar = CV_STRUCT_INITIALIZER; -#else - CvScalar scalar; -#endif - scalar.val[0] = s.val[0]; - scalar.val[1] = s.val[1]; - scalar.val[2] = s.val[2]; - scalar.val[3] = s.val[3]; - return scalar; -} -#endif - -CV_INLINE CvScalar cvRealScalar( double val0 ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvScalar scalar = CV_STRUCT_INITIALIZER; -#else - CvScalar scalar; -#endif - scalar.val[0] = val0; - scalar.val[1] = scalar.val[2] = scalar.val[3] = 0; - return scalar; -} - -CV_INLINE CvScalar cvScalarAll( double val0123 ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvScalar scalar = CV_STRUCT_INITIALIZER; -#else - CvScalar scalar; -#endif - scalar.val[0] = val0123; - scalar.val[1] = val0123; - scalar.val[2] = val0123; - scalar.val[3] = val0123; - return scalar; -} - -/****************************************************************************************\ -* Dynamic Data structures * -\****************************************************************************************/ - -/******************************** Memory storage ****************************************/ - -typedef struct CvMemBlock -{ - struct CvMemBlock* prev; - struct CvMemBlock* next; -} -CvMemBlock; - -#define CV_STORAGE_MAGIC_VAL 0x42890000 - -typedef struct CvMemStorage -{ - int signature; - CvMemBlock* bottom; /**< First allocated block. */ - CvMemBlock* top; /**< Current memory block - top of the stack. */ - struct CvMemStorage* parent; /**< We get new blocks from parent as needed. */ - int block_size; /**< Block size. */ - int free_space; /**< Remaining free space in current block. */ -} -CvMemStorage; - -#define CV_IS_STORAGE(storage) \ - ((storage) != NULL && \ - (((CvMemStorage*)(storage))->signature & CV_MAGIC_MASK) == CV_STORAGE_MAGIC_VAL) - - -typedef struct CvMemStoragePos -{ - CvMemBlock* top; - int free_space; -} -CvMemStoragePos; - - -/*********************************** Sequence *******************************************/ - -typedef struct CvSeqBlock -{ - struct CvSeqBlock* prev; /**< Previous sequence block. */ - struct CvSeqBlock* next; /**< Next sequence block. */ - int start_index; /**< Index of the first element in the block + */ - /**< sequence->first->start_index. */ - int count; /**< Number of elements in the block. */ - schar* data; /**< Pointer to the first element of the block. */ -} -CvSeqBlock; - - -#define CV_TREE_NODE_FIELDS(node_type) \ - int flags; /**< Miscellaneous flags. */ \ - int header_size; /**< Size of sequence header. */ \ - struct node_type* h_prev; /**< Previous sequence. */ \ - struct node_type* h_next; /**< Next sequence. */ \ - struct node_type* v_prev; /**< 2nd previous sequence. */ \ - struct node_type* v_next /**< 2nd next sequence. */ - -/** - Read/Write sequence. - Elements can be dynamically inserted to or deleted from the sequence. -*/ -#define CV_SEQUENCE_FIELDS() \ - CV_TREE_NODE_FIELDS(CvSeq); \ - int total; /**< Total number of elements. */ \ - int elem_size; /**< Size of sequence element in bytes. */ \ - schar* block_max; /**< Maximal bound of the last block. */ \ - schar* ptr; /**< Current write pointer. */ \ - int delta_elems; /**< Grow seq this many at a time. */ \ - CvMemStorage* storage; /**< Where the seq is stored. */ \ - CvSeqBlock* free_blocks; /**< Free blocks list. */ \ - CvSeqBlock* first; /**< Pointer to the first sequence block. */ - -typedef struct CvSeq -{ - CV_SEQUENCE_FIELDS() -} -CvSeq; - -#define CV_TYPE_NAME_SEQ "opencv-sequence" -#define CV_TYPE_NAME_SEQ_TREE "opencv-sequence-tree" - -/*************************************** Set ********************************************/ -/** @brief Set - Order is not preserved. There can be gaps between sequence elements. - After the element has been inserted it stays in the same place all the time. - The MSB(most-significant or sign bit) of the first field (flags) is 0 iff the element exists. -*/ -#define CV_SET_ELEM_FIELDS(elem_type) \ - int flags; \ - struct elem_type* next_free; - -typedef struct CvSetElem -{ - CV_SET_ELEM_FIELDS(CvSetElem) -} -CvSetElem; - -#define CV_SET_FIELDS() \ - CV_SEQUENCE_FIELDS() \ - CvSetElem* free_elems; \ - int active_count; - -typedef struct CvSet -{ - CV_SET_FIELDS() -} -CvSet; - - -#define CV_SET_ELEM_IDX_MASK ((1 << 26) - 1) -#define CV_SET_ELEM_FREE_FLAG (1 << (sizeof(int)*8-1)) - -/** Checks whether the element pointed by ptr belongs to a set or not */ -#define CV_IS_SET_ELEM( ptr ) (((CvSetElem*)(ptr))->flags >= 0) - -/************************************* Graph ********************************************/ - -/** @name Graph - -We represent a graph as a set of vertices. Vertices contain their adjacency lists (more exactly, -pointers to first incoming or outcoming edge (or 0 if isolated vertex)). Edges are stored in -another set. There is a singly-linked list of incoming/outcoming edges for each vertex. - -Each edge consists of: - -- Two pointers to the starting and ending vertices (vtx[0] and vtx[1] respectively). - - A graph may be oriented or not. In the latter case, edges between vertex i to vertex j are not -distinguished during search operations. - -- Two pointers to next edges for the starting and ending vertices, where next[0] points to the -next edge in the vtx[0] adjacency list and next[1] points to the next edge in the vtx[1] -adjacency list. - -@see CvGraphEdge, CvGraphVtx, CvGraphVtx2D, CvGraph -@{ -*/ -#define CV_GRAPH_EDGE_FIELDS() \ - int flags; \ - float weight; \ - struct CvGraphEdge* next[2]; \ - struct CvGraphVtx* vtx[2]; - - -#define CV_GRAPH_VERTEX_FIELDS() \ - int flags; \ - struct CvGraphEdge* first; - - -typedef struct CvGraphEdge -{ - CV_GRAPH_EDGE_FIELDS() -} -CvGraphEdge; - -typedef struct CvGraphVtx -{ - CV_GRAPH_VERTEX_FIELDS() -} -CvGraphVtx; - -typedef struct CvGraphVtx2D -{ - CV_GRAPH_VERTEX_FIELDS() - CvPoint2D32f* ptr; -} -CvGraphVtx2D; - -/** - Graph is "derived" from the set (this is set a of vertices) - and includes another set (edges) -*/ -#define CV_GRAPH_FIELDS() \ - CV_SET_FIELDS() \ - CvSet* edges; - -typedef struct CvGraph -{ - CV_GRAPH_FIELDS() -} -CvGraph; - -#define CV_TYPE_NAME_GRAPH "opencv-graph" - -/** @} */ - -/*********************************** Chain/Contour *************************************/ - -typedef struct CvChain -{ - CV_SEQUENCE_FIELDS() - CvPoint origin; -} -CvChain; - -#define CV_CONTOUR_FIELDS() \ - CV_SEQUENCE_FIELDS() \ - CvRect rect; \ - int color; \ - int reserved[3]; - -typedef struct CvContour -{ - CV_CONTOUR_FIELDS() -} -CvContour; - -typedef CvContour CvPoint2DSeq; - -/****************************************************************************************\ -* Sequence types * -\****************************************************************************************/ - -#define CV_SEQ_MAGIC_VAL 0x42990000 - -#define CV_IS_SEQ(seq) \ - ((seq) != NULL && (((CvSeq*)(seq))->flags & CV_MAGIC_MASK) == CV_SEQ_MAGIC_VAL) - -#define CV_SET_MAGIC_VAL 0x42980000 -#define CV_IS_SET(set) \ - ((set) != NULL && (((CvSeq*)(set))->flags & CV_MAGIC_MASK) == CV_SET_MAGIC_VAL) - -#define CV_SEQ_ELTYPE_BITS 12 -#define CV_SEQ_ELTYPE_MASK ((1 << CV_SEQ_ELTYPE_BITS) - 1) - -#define CV_SEQ_ELTYPE_POINT CV_32SC2 /**< (x,y) */ -#define CV_SEQ_ELTYPE_CODE CV_8UC1 /**< freeman code: 0..7 */ -#define CV_SEQ_ELTYPE_GENERIC 0 -#define CV_SEQ_ELTYPE_PTR CV_MAKE_TYPE(CV_8U, 8 /*sizeof(void*)*/) -#define CV_SEQ_ELTYPE_PPOINT CV_SEQ_ELTYPE_PTR /**< &(x,y) */ -#define CV_SEQ_ELTYPE_INDEX CV_32SC1 /**< #(x,y) */ -#define CV_SEQ_ELTYPE_GRAPH_EDGE 0 /**< &next_o, &next_d, &vtx_o, &vtx_d */ -#define CV_SEQ_ELTYPE_GRAPH_VERTEX 0 /**< first_edge, &(x,y) */ -#define CV_SEQ_ELTYPE_TRIAN_ATR 0 /**< vertex of the binary tree */ -#define CV_SEQ_ELTYPE_CONNECTED_COMP 0 /**< connected component */ -#define CV_SEQ_ELTYPE_POINT3D CV_32FC3 /**< (x,y,z) */ - -#define CV_SEQ_KIND_BITS 2 -#define CV_SEQ_KIND_MASK (((1 << CV_SEQ_KIND_BITS) - 1)<flags & CV_SEQ_ELTYPE_MASK) -#define CV_SEQ_KIND( seq ) ((seq)->flags & CV_SEQ_KIND_MASK ) - -/** flag checking */ -#define CV_IS_SEQ_INDEX( seq ) ((CV_SEQ_ELTYPE(seq) == CV_SEQ_ELTYPE_INDEX) && \ - (CV_SEQ_KIND(seq) == CV_SEQ_KIND_GENERIC)) - -#define CV_IS_SEQ_CURVE( seq ) (CV_SEQ_KIND(seq) == CV_SEQ_KIND_CURVE) -#define CV_IS_SEQ_CLOSED( seq ) (((seq)->flags & CV_SEQ_FLAG_CLOSED) != 0) -#define CV_IS_SEQ_CONVEX( seq ) 0 -#define CV_IS_SEQ_HOLE( seq ) (((seq)->flags & CV_SEQ_FLAG_HOLE) != 0) -#define CV_IS_SEQ_SIMPLE( seq ) 1 - -/** type checking macros */ -#define CV_IS_SEQ_POINT_SET( seq ) \ - ((CV_SEQ_ELTYPE(seq) == CV_32SC2 || CV_SEQ_ELTYPE(seq) == CV_32FC2)) - -#define CV_IS_SEQ_POINT_SUBSET( seq ) \ - (CV_IS_SEQ_INDEX( seq ) || CV_SEQ_ELTYPE(seq) == CV_SEQ_ELTYPE_PPOINT) - -#define CV_IS_SEQ_POLYLINE( seq ) \ - (CV_SEQ_KIND(seq) == CV_SEQ_KIND_CURVE && CV_IS_SEQ_POINT_SET(seq)) - -#define CV_IS_SEQ_POLYGON( seq ) \ - (CV_IS_SEQ_POLYLINE(seq) && CV_IS_SEQ_CLOSED(seq)) - -#define CV_IS_SEQ_CHAIN( seq ) \ - (CV_SEQ_KIND(seq) == CV_SEQ_KIND_CURVE && (seq)->elem_size == 1) - -#define CV_IS_SEQ_CONTOUR( seq ) \ - (CV_IS_SEQ_CLOSED(seq) && (CV_IS_SEQ_POLYLINE(seq) || CV_IS_SEQ_CHAIN(seq))) - -#define CV_IS_SEQ_CHAIN_CONTOUR( seq ) \ - (CV_IS_SEQ_CHAIN( seq ) && CV_IS_SEQ_CLOSED( seq )) - -#define CV_IS_SEQ_POLYGON_TREE( seq ) \ - (CV_SEQ_ELTYPE (seq) == CV_SEQ_ELTYPE_TRIAN_ATR && \ - CV_SEQ_KIND( seq ) == CV_SEQ_KIND_BIN_TREE ) - -#define CV_IS_GRAPH( seq ) \ - (CV_IS_SET(seq) && CV_SEQ_KIND((CvSet*)(seq)) == CV_SEQ_KIND_GRAPH) - -#define CV_IS_GRAPH_ORIENTED( seq ) \ - (((seq)->flags & CV_GRAPH_FLAG_ORIENTED) != 0) - -#define CV_IS_SUBDIV2D( seq ) \ - (CV_IS_SET(seq) && CV_SEQ_KIND((CvSet*)(seq)) == CV_SEQ_KIND_SUBDIV2D) - -/****************************************************************************************/ -/* Sequence writer & reader */ -/****************************************************************************************/ - -#define CV_SEQ_WRITER_FIELDS() \ - int header_size; \ - CvSeq* seq; /**< the sequence written */ \ - CvSeqBlock* block; /**< current block */ \ - schar* ptr; /**< pointer to free space */ \ - schar* block_min; /**< pointer to the beginning of block*/\ - schar* block_max; /**< pointer to the end of block */ - -typedef struct CvSeqWriter -{ - CV_SEQ_WRITER_FIELDS() -} -CvSeqWriter; - - -#define CV_SEQ_READER_FIELDS() \ - int header_size; \ - CvSeq* seq; /**< sequence, beign read */ \ - CvSeqBlock* block; /**< current block */ \ - schar* ptr; /**< pointer to element be read next */ \ - schar* block_min; /**< pointer to the beginning of block */\ - schar* block_max; /**< pointer to the end of block */ \ - int delta_index;/**< = seq->first->start_index */ \ - schar* prev_elem; /**< pointer to previous element */ - -typedef struct CvSeqReader -{ - CV_SEQ_READER_FIELDS() -} -CvSeqReader; - -/****************************************************************************************/ -/* Operations on sequences */ -/****************************************************************************************/ - -#define CV_SEQ_ELEM( seq, elem_type, index ) \ -/** assert gives some guarantee that parameter is valid */ \ -( assert(sizeof((seq)->first[0]) == sizeof(CvSeqBlock) && \ - (seq)->elem_size == sizeof(elem_type)), \ - (elem_type*)((seq)->first && (unsigned)index < \ - (unsigned)((seq)->first->count) ? \ - (seq)->first->data + (index) * sizeof(elem_type) : \ - cvGetSeqElem( (CvSeq*)(seq), (index) ))) -#define CV_GET_SEQ_ELEM( elem_type, seq, index ) CV_SEQ_ELEM( (seq), elem_type, (index) ) - -/** Add element to sequence: */ -#define CV_WRITE_SEQ_ELEM_VAR( elem_ptr, writer ) \ -{ \ - if( (writer).ptr >= (writer).block_max ) \ - { \ - cvCreateSeqBlock( &writer); \ - } \ - memcpy((writer).ptr, elem_ptr, (writer).seq->elem_size);\ - (writer).ptr += (writer).seq->elem_size; \ -} - -#define CV_WRITE_SEQ_ELEM( elem, writer ) \ -{ \ - assert( (writer).seq->elem_size == sizeof(elem)); \ - if( (writer).ptr >= (writer).block_max ) \ - { \ - cvCreateSeqBlock( &writer); \ - } \ - assert( (writer).ptr <= (writer).block_max - sizeof(elem));\ - memcpy((writer).ptr, &(elem), sizeof(elem)); \ - (writer).ptr += sizeof(elem); \ -} - - -/** Move reader position forward: */ -#define CV_NEXT_SEQ_ELEM( elem_size, reader ) \ -{ \ - if( ((reader).ptr += (elem_size)) >= (reader).block_max ) \ - { \ - cvChangeSeqBlock( &(reader), 1 ); \ - } \ -} - - -/** Move reader position backward: */ -#define CV_PREV_SEQ_ELEM( elem_size, reader ) \ -{ \ - if( ((reader).ptr -= (elem_size)) < (reader).block_min ) \ - { \ - cvChangeSeqBlock( &(reader), -1 ); \ - } \ -} - -/** Read element and move read position forward: */ -#define CV_READ_SEQ_ELEM( elem, reader ) \ -{ \ - assert( (reader).seq->elem_size == sizeof(elem)); \ - memcpy( &(elem), (reader).ptr, sizeof((elem))); \ - CV_NEXT_SEQ_ELEM( sizeof(elem), reader ) \ -} - -/** Read element and move read position backward: */ -#define CV_REV_READ_SEQ_ELEM( elem, reader ) \ -{ \ - assert( (reader).seq->elem_size == sizeof(elem)); \ - memcpy(&(elem), (reader).ptr, sizeof((elem))); \ - CV_PREV_SEQ_ELEM( sizeof(elem), reader ) \ -} - - -#define CV_READ_CHAIN_POINT( _pt, reader ) \ -{ \ - (_pt) = (reader).pt; \ - if( (reader).ptr ) \ - { \ - CV_READ_SEQ_ELEM( (reader).code, (reader)); \ - assert( ((reader).code & ~7) == 0 ); \ - (reader).pt.x += (reader).deltas[(int)(reader).code][0]; \ - (reader).pt.y += (reader).deltas[(int)(reader).code][1]; \ - } \ -} - -#define CV_CURRENT_POINT( reader ) (*((CvPoint*)((reader).ptr))) -#define CV_PREV_POINT( reader ) (*((CvPoint*)((reader).prev_elem))) - -#define CV_READ_EDGE( pt1, pt2, reader ) \ -{ \ - assert( sizeof(pt1) == sizeof(CvPoint) && \ - sizeof(pt2) == sizeof(CvPoint) && \ - reader.seq->elem_size == sizeof(CvPoint)); \ - (pt1) = CV_PREV_POINT( reader ); \ - (pt2) = CV_CURRENT_POINT( reader ); \ - (reader).prev_elem = (reader).ptr; \ - CV_NEXT_SEQ_ELEM( sizeof(CvPoint), (reader)); \ -} - -/************ Graph macros ************/ - -/** Return next graph edge for given vertex: */ -#define CV_NEXT_GRAPH_EDGE( edge, vertex ) \ - (assert((edge)->vtx[0] == (vertex) || (edge)->vtx[1] == (vertex)), \ - (edge)->next[(edge)->vtx[1] == (vertex)]) - - - -/****************************************************************************************\ -* Data structures for persistence (a.k.a serialization) functionality * -\****************************************************************************************/ - -#if 0 - -/** "black box" file storage */ -typedef struct CvFileStorage CvFileStorage; - -/** Storage flags: */ -#define CV_STORAGE_READ 0 -#define CV_STORAGE_WRITE 1 -#define CV_STORAGE_WRITE_TEXT CV_STORAGE_WRITE -#define CV_STORAGE_WRITE_BINARY CV_STORAGE_WRITE -#define CV_STORAGE_APPEND 2 -#define CV_STORAGE_MEMORY 4 -#define CV_STORAGE_FORMAT_MASK (7<<3) -#define CV_STORAGE_FORMAT_AUTO 0 -#define CV_STORAGE_FORMAT_XML 8 -#define CV_STORAGE_FORMAT_YAML 16 -#define CV_STORAGE_FORMAT_JSON 24 -#define CV_STORAGE_BASE64 64 -#define CV_STORAGE_WRITE_BASE64 (CV_STORAGE_BASE64 | CV_STORAGE_WRITE) - -/** @brief List of attributes. : - -In the current implementation, attributes are used to pass extra parameters when writing user -objects (see cvWrite). XML attributes inside tags are not supported, aside from the object type -specification (type_id attribute). -@see cvAttrList, cvAttrValue - */ -typedef struct CvAttrList -{ - const char** attr; /**< NULL-terminated array of (attribute_name,attribute_value) pairs. */ - struct CvAttrList* next; /**< Pointer to next chunk of the attributes list. */ -} -CvAttrList; - -/** initializes CvAttrList structure */ -CV_INLINE CvAttrList cvAttrList( const char** attr CV_DEFAULT(NULL), - CvAttrList* next CV_DEFAULT(NULL) ) -{ - CvAttrList l; - l.attr = attr; - l.next = next; - - return l; -} - -struct CvTypeInfo; - -#define CV_NODE_NONE 0 -#define CV_NODE_INT 1 -#define CV_NODE_INTEGER CV_NODE_INT -#define CV_NODE_REAL 2 -#define CV_NODE_FLOAT CV_NODE_REAL -#define CV_NODE_STR 3 -#define CV_NODE_STRING CV_NODE_STR -#define CV_NODE_REF 4 /**< not used */ -#define CV_NODE_SEQ 5 -#define CV_NODE_MAP 6 -#define CV_NODE_TYPE_MASK 7 - -#define CV_NODE_TYPE(flags) ((flags) & CV_NODE_TYPE_MASK) - -/** file node flags */ -#define CV_NODE_FLOW 8 /**= CV_NODE_SEQ) -#define CV_NODE_IS_FLOW(flags) (((flags) & CV_NODE_FLOW) != 0) -#define CV_NODE_IS_EMPTY(flags) (((flags) & CV_NODE_EMPTY) != 0) -#define CV_NODE_IS_USER(flags) (((flags) & CV_NODE_USER) != 0) -#define CV_NODE_HAS_NAME(flags) (((flags) & CV_NODE_NAMED) != 0) - -#define CV_NODE_SEQ_SIMPLE 256 -#define CV_NODE_SEQ_IS_SIMPLE(seq) (((seq)->flags & CV_NODE_SEQ_SIMPLE) != 0) - -typedef struct CvString -{ - int len; - char* ptr; -} -CvString; - -/** All the keys (names) of elements in the read file storage - are stored in the hash to speed up the lookup operations: */ -typedef struct CvStringHashNode -{ - unsigned hashval; - CvString str; - struct CvStringHashNode* next; -} -CvStringHashNode; - -typedef struct CvGenericHash CvFileNodeHash; - -/** Basic element of the file storage - scalar or collection: */ -typedef struct CvFileNode -{ - int tag; - struct CvTypeInfo* info; /**< type information - (only for user-defined object, for others it is 0) */ - union - { - double f; /**< scalar floating-point number */ - int i; /**< scalar integer number */ - CvString str; /**< text string */ - CvSeq* seq; /**< sequence (ordered collection of file nodes) */ - CvFileNodeHash* map; /**< map (collection of named file nodes) */ - } data; -} -CvFileNode; - -#ifdef __cplusplus -extern "C" { -#endif -typedef int (CV_CDECL *CvIsInstanceFunc)( const void* struct_ptr ); -typedef void (CV_CDECL *CvReleaseFunc)( void** struct_dblptr ); -typedef void* (CV_CDECL *CvReadFunc)( CvFileStorage* storage, CvFileNode* node ); -typedef void (CV_CDECL *CvWriteFunc)( CvFileStorage* storage, const char* name, - const void* struct_ptr, CvAttrList attributes ); -typedef void* (CV_CDECL *CvCloneFunc)( const void* struct_ptr ); -#ifdef __cplusplus -} -#endif - -/** @brief Type information - -The structure contains information about one of the standard or user-defined types. Instances of the -type may or may not contain a pointer to the corresponding CvTypeInfo structure. In any case, there -is a way to find the type info structure for a given object using the cvTypeOf function. -Alternatively, type info can be found by type name using cvFindType, which is used when an object -is read from file storage. The user can register a new type with cvRegisterType that adds the type -information structure into the beginning of the type list. Thus, it is possible to create -specialized types from generic standard types and override the basic methods. - */ -typedef struct CvTypeInfo -{ - int flags; /**< not used */ - int header_size; /**< sizeof(CvTypeInfo) */ - struct CvTypeInfo* prev; /**< previous registered type in the list */ - struct CvTypeInfo* next; /**< next registered type in the list */ - const char* type_name; /**< type name, written to file storage */ - CvIsInstanceFunc is_instance; /**< checks if the passed object belongs to the type */ - CvReleaseFunc release; /**< releases object (memory etc.) */ - CvReadFunc read; /**< reads object from file storage */ - CvWriteFunc write; /**< writes object to file storage */ - CvCloneFunc clone; /**< creates a copy of the object */ -} -CvTypeInfo; -#endif - -/** @} */ - -#endif /*OPENCV_CORE_TYPES_H*/ - -/* End of file. */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CORE_TYPES_H +#define OPENCV_CORE_TYPES_H + +#ifdef CV__ENABLE_C_API_CTORS // invalid C API ctors (must be removed) +#if defined(_WIN32) && !defined(CV__SKIP_MESSAGE_MALFORMED_C_API_CTORS) +#error "C API ctors don't work on Win32: https://github.com/opencv/opencv/issues/15990" +#endif +#endif + +//#define CV__VALIDATE_UNUNITIALIZED_VARS 1 // C++11 & GCC only + +#ifdef __cplusplus + +#ifdef CV__VALIDATE_UNUNITIALIZED_VARS +#pragma GCC diagnostic ignored "-Wmissing-field-initializers" +#define CV_STRUCT_INITIALIZER {0,} +#else +#if defined(__GNUC__) && __GNUC__ == 4 // GCC 4.x warns on "= {}" initialization, fixed in GCC 5.0 +#pragma GCC diagnostic ignored "-Wmissing-field-initializers" +#endif +#define CV_STRUCT_INITIALIZER {} +#endif + +#else +#define CV_STRUCT_INITIALIZER {0} +#endif + + +#ifdef HAVE_IPL +# ifndef __IPL_H__ +# if defined _WIN32 +# include +# else +# include +# endif +# endif +#elif defined __IPL_H__ +# define HAVE_IPL +#endif + +#include "opencv2/core/cvdef.h" + +#ifndef SKIP_INCLUDES +#include +#include +#include +#include +#endif // SKIP_INCLUDES + + + +#ifndef CV_DEFAULT +# ifdef __cplusplus +# define CV_DEFAULT(val) = val +# else +# define CV_DEFAULT(val) +# endif +#endif + +#ifndef CV_EXTERN_C_FUNCPTR +# ifdef __cplusplus +# define CV_EXTERN_C_FUNCPTR(x) extern "C" { typedef x; } +# else +# define CV_EXTERN_C_FUNCPTR(x) typedef x +# endif +#endif + +#ifndef CVAPI +# define CVAPI(rettype) CV_EXTERN_C CV_EXPORTS rettype CV_CDECL +#endif + +#ifndef CV_IMPL +# define CV_IMPL CV_EXTERN_C +#endif + +#ifdef __cplusplus +# include "opencv2/core.hpp" +#endif + +/** @addtogroup core_c + @{ +*/ + +/** @brief This is the "metatype" used *only* as a function parameter. + +It denotes that the function accepts arrays of multiple types, such as IplImage*, CvMat* or even +CvSeq* sometimes. The particular array type is determined at runtime by analyzing the first 4 +bytes of the header. In C++ interface the role of CvArr is played by InputArray and OutputArray. + */ +typedef void CvArr; + +typedef int CVStatus; + +/** @see cv::Error::Code */ +enum { + CV_StsOk= 0, /**< everything is ok */ + CV_StsBackTrace= -1, /**< pseudo error for back trace */ + CV_StsError= -2, /**< unknown /unspecified error */ + CV_StsInternal= -3, /**< internal error (bad state) */ + CV_StsNoMem= -4, /**< insufficient memory */ + CV_StsBadArg= -5, /**< function arg/param is bad */ + CV_StsBadFunc= -6, /**< unsupported function */ + CV_StsNoConv= -7, /**< iter. didn't converge */ + CV_StsAutoTrace= -8, /**< tracing */ + CV_HeaderIsNull= -9, /**< image header is NULL */ + CV_BadImageSize= -10, /**< image size is invalid */ + CV_BadOffset= -11, /**< offset is invalid */ + CV_BadDataPtr= -12, /**/ + CV_BadStep= -13, /**< image step is wrong, this may happen for a non-continuous matrix */ + CV_BadModelOrChSeq= -14, /**/ + CV_BadNumChannels= -15, /**< bad number of channels, for example, some functions accept only single channel matrices */ + CV_BadNumChannel1U= -16, /**/ + CV_BadDepth= -17, /**< input image depth is not supported by the function */ + CV_BadAlphaChannel= -18, /**/ + CV_BadOrder= -19, /**< number of dimensions is out of range */ + CV_BadOrigin= -20, /**< incorrect input origin */ + CV_BadAlign= -21, /**< incorrect input align */ + CV_BadCallBack= -22, /**/ + CV_BadTileSize= -23, /**/ + CV_BadCOI= -24, /**< input COI is not supported */ + CV_BadROISize= -25, /**< incorrect input roi */ + CV_MaskIsTiled= -26, /**/ + CV_StsNullPtr= -27, /**< null pointer */ + CV_StsVecLengthErr= -28, /**< incorrect vector length */ + CV_StsFilterStructContentErr= -29, /**< incorrect filter structure content */ + CV_StsKernelStructContentErr= -30, /**< incorrect transform kernel content */ + CV_StsFilterOffsetErr= -31, /**< incorrect filter offset value */ + CV_StsBadSize= -201, /**< the input/output structure size is incorrect */ + CV_StsDivByZero= -202, /**< division by zero */ + CV_StsInplaceNotSupported= -203, /**< in-place operation is not supported */ + CV_StsObjectNotFound= -204, /**< request can't be completed */ + CV_StsUnmatchedFormats= -205, /**< formats of input/output arrays differ */ + CV_StsBadFlag= -206, /**< flag is wrong or not supported */ + CV_StsBadPoint= -207, /**< bad CvPoint */ + CV_StsBadMask= -208, /**< bad format of mask (neither 8uC1 nor 8sC1)*/ + CV_StsUnmatchedSizes= -209, /**< sizes of input/output structures do not match */ + CV_StsUnsupportedFormat= -210, /**< the data format/type is not supported by the function*/ + CV_StsOutOfRange= -211, /**< some of parameters are out of range */ + CV_StsParseError= -212, /**< invalid syntax/structure of the parsed file */ + CV_StsNotImplemented= -213, /**< the requested function/feature is not implemented */ + CV_StsBadMemBlock= -214, /**< an allocated block has been corrupted */ + CV_StsAssert= -215, /**< assertion failed */ + CV_GpuNotSupported= -216, /**< no CUDA support */ + CV_GpuApiCallError= -217, /**< GPU API call error */ + CV_OpenGlNotSupported= -218, /**< no OpenGL support */ + CV_OpenGlApiCallError= -219, /**< OpenGL API call error */ + CV_OpenCLApiCallError= -220, /**< OpenCL API call error */ + CV_OpenCLDoubleNotSupported= -221, + CV_OpenCLInitError= -222, /**< OpenCL initialization error */ + CV_OpenCLNoAMDBlasFft= -223 +}; + +/****************************************************************************************\ +* Common macros and inline functions * +\****************************************************************************************/ + +/** absolute value without jumps */ +#ifndef __cplusplus +# define CV_IABS(a) (((a) ^ ((a) < 0 ? -1 : 0)) - ((a) < 0 ? -1 : 0)) +#else +# define CV_IABS(a) abs(a) +#endif + + +#define cvInvSqrt(value) ((float)(1./sqrt(value))) +#define cvSqrt(value) ((float)sqrt(value)) + + +/*************** Random number generation *******************/ + +typedef uint64 CvRNG; + +#define CV_RNG_COEFF 4164903690U + +/** @brief Initializes a random number generator state. + +The function initializes a random number generator and returns the state. The pointer to the state +can be then passed to the cvRandInt, cvRandReal and cvRandArr functions. In the current +implementation a multiply-with-carry generator is used. +@param seed 64-bit value used to initiate a random sequence +@sa the C++ class RNG replaced CvRNG. + */ +CV_INLINE CvRNG cvRNG( int64 seed CV_DEFAULT(-1)) +{ + CvRNG rng = seed ? (uint64)seed : (uint64)(int64)-1; + return rng; +} + +/** @brief Returns a 32-bit unsigned integer and updates RNG. + +The function returns a uniformly-distributed random 32-bit unsigned integer and updates the RNG +state. It is similar to the rand() function from the C runtime library, except that OpenCV functions +always generates a 32-bit random number, regardless of the platform. +@param rng CvRNG state initialized by cvRNG. + */ +CV_INLINE unsigned cvRandInt( CvRNG* rng ) +{ + uint64 temp = *rng; + temp = (uint64)(unsigned)temp*CV_RNG_COEFF + (temp >> 32); + *rng = temp; + return (unsigned)temp; +} + +/** @brief Returns a floating-point random number and updates RNG. + +The function returns a uniformly-distributed random floating-point number between 0 and 1 (1 is not +included). +@param rng RNG state initialized by cvRNG + */ +CV_INLINE double cvRandReal( CvRNG* rng ) +{ + return cvRandInt(rng)*2.3283064365386962890625e-10 /* 2^-32 */; +} + +/****************************************************************************************\ +* Image type (IplImage) * +\****************************************************************************************/ + +#ifndef HAVE_IPL + +/* + * The following definitions (until #endif) + * is an extract from IPL headers. + * Copyright (c) 1995 Intel Corporation. + */ +#define IPL_DEPTH_SIGN 0x80000000 + +#define IPL_DEPTH_1U 1 +#define IPL_DEPTH_8U 8 +#define IPL_DEPTH_16U 16 +#define IPL_DEPTH_32F 32 + +#define IPL_DEPTH_8S (IPL_DEPTH_SIGN| 8) +#define IPL_DEPTH_16S (IPL_DEPTH_SIGN|16) +#define IPL_DEPTH_32S (IPL_DEPTH_SIGN|32) + +#define IPL_DATA_ORDER_PIXEL 0 +#define IPL_DATA_ORDER_PLANE 1 + +#define IPL_ORIGIN_TL 0 +#define IPL_ORIGIN_BL 1 + +#define IPL_ALIGN_4BYTES 4 +#define IPL_ALIGN_8BYTES 8 +#define IPL_ALIGN_16BYTES 16 +#define IPL_ALIGN_32BYTES 32 + +#define IPL_ALIGN_DWORD IPL_ALIGN_4BYTES +#define IPL_ALIGN_QWORD IPL_ALIGN_8BYTES + +#define IPL_BORDER_CONSTANT 0 +#define IPL_BORDER_REPLICATE 1 +#define IPL_BORDER_REFLECT 2 +#define IPL_BORDER_WRAP 3 + +#ifdef __cplusplus +typedef struct _IplImage IplImage; +CV_EXPORTS _IplImage cvIplImage(const cv::Mat& m); +#endif + +/** The IplImage is taken from the Intel Image Processing Library, in which the format is native. OpenCV +only supports a subset of possible IplImage formats, as outlined in the parameter list above. + +In addition to the above restrictions, OpenCV handles ROIs differently. OpenCV functions require +that the image size or ROI size of all source and destination images match exactly. On the other +hand, the Intel Image Processing Library processes the area of intersection between the source and +destination images (or ROIs), allowing them to vary independently. +*/ +typedef struct +_IplImage +{ + int nSize; /**< sizeof(IplImage) */ + int ID; /**< version (=0)*/ + int nChannels; /**< Most of OpenCV functions support 1,2,3 or 4 channels */ + int alphaChannel; /**< Ignored by OpenCV */ + int depth; /**< Pixel depth in bits: IPL_DEPTH_8U, IPL_DEPTH_8S, IPL_DEPTH_16S, + IPL_DEPTH_32S, IPL_DEPTH_32F and IPL_DEPTH_64F are supported. */ + char colorModel[4]; /**< Ignored by OpenCV */ + char channelSeq[4]; /**< ditto */ + int dataOrder; /**< 0 - interleaved color channels, 1 - separate color channels. + cvCreateImage can only create interleaved images */ + int origin; /**< 0 - top-left origin, + 1 - bottom-left origin (Windows bitmaps style). */ + int align; /**< Alignment of image rows (4 or 8). + OpenCV ignores it and uses widthStep instead. */ + int width; /**< Image width in pixels. */ + int height; /**< Image height in pixels. */ + struct _IplROI *roi; /**< Image ROI. If NULL, the whole image is selected. */ + struct _IplImage *maskROI; /**< Must be NULL. */ + void *imageId; /**< " " */ + struct _IplTileInfo *tileInfo; /**< " " */ + int imageSize; /**< Image data size in bytes + (==image->height*image->widthStep + in case of interleaved data)*/ + char *imageData; /**< Pointer to aligned image data. */ + int widthStep; /**< Size of aligned image row in bytes. */ + int BorderMode[4]; /**< Ignored by OpenCV. */ + int BorderConst[4]; /**< Ditto. */ + char *imageDataOrigin; /**< Pointer to very origin of image data + (not necessarily aligned) - + needed for correct deallocation */ + +#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + _IplImage() + { + memset(this, 0, sizeof(*this)); // valid for POD structure + nSize = sizeof(IplImage); + } + _IplImage(const cv::Mat& m) { *this = cvIplImage(m); } +#endif +} +IplImage; + +CV_INLINE IplImage cvIplImage() +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + IplImage self = CV_STRUCT_INITIALIZER; self.nSize = sizeof(IplImage); return self; +#else + return _IplImage(); +#endif +} + +typedef struct _IplTileInfo IplTileInfo; + +typedef struct _IplROI +{ + int coi; /**< 0 - no COI (all channels are selected), 1 - 0th channel is selected ...*/ + int xOffset; + int yOffset; + int width; + int height; +} +IplROI; + +typedef struct _IplConvKernel +{ + int nCols; + int nRows; + int anchorX; + int anchorY; + int *values; + int nShiftR; +} +IplConvKernel; + +typedef struct _IplConvKernelFP +{ + int nCols; + int nRows; + int anchorX; + int anchorY; + float *values; +} +IplConvKernelFP; + +#define IPL_IMAGE_HEADER 1 +#define IPL_IMAGE_DATA 2 +#define IPL_IMAGE_ROI 4 + +#endif/*HAVE_IPL*/ + +/** extra border mode */ +#define IPL_BORDER_REFLECT_101 4 +#define IPL_BORDER_TRANSPARENT 5 + +#define IPL_IMAGE_MAGIC_VAL ((int)sizeof(IplImage)) +#define CV_TYPE_NAME_IMAGE "opencv-image" + +#define CV_IS_IMAGE_HDR(img) \ + ((img) != NULL && ((const IplImage*)(img))->nSize == sizeof(IplImage)) + +#define CV_IS_IMAGE(img) \ + (CV_IS_IMAGE_HDR(img) && ((IplImage*)img)->imageData != NULL) + +/** for storing double-precision + floating point data in IplImage's */ +#define IPL_DEPTH_64F 64 + +/** get reference to pixel at (col,row), + for multi-channel images (col) should be multiplied by number of channels */ +#define CV_IMAGE_ELEM( image, elemtype, row, col ) \ + (((elemtype*)((image)->imageData + (image)->widthStep*(row)))[(col)]) + +/****************************************************************************************\ +* Matrix type (CvMat) * +\****************************************************************************************/ + +#define CV_AUTO_STEP 0x7fffffff +#define CV_WHOLE_ARR cvSlice( 0, 0x3fffffff ) + +#define CV_MAGIC_MASK 0xFFFF0000 +#define CV_MAT_MAGIC_VAL 0x42420000 +#define CV_TYPE_NAME_MAT "opencv-matrix" + +#ifdef __cplusplus +typedef struct CvMat CvMat; +CV_INLINE CvMat cvMat(const cv::Mat& m); +#endif + +/** Matrix elements are stored row by row. Element (i, j) (i - 0-based row index, j - 0-based column +index) of a matrix can be retrieved or modified using CV_MAT_ELEM macro: + + uchar pixval = CV_MAT_ELEM(grayimg, uchar, i, j) + CV_MAT_ELEM(cameraMatrix, float, 0, 2) = image.width*0.5f; + +To access multiple-channel matrices, you can use +CV_MAT_ELEM(matrix, type, i, j\*nchannels + channel_idx). + +@deprecated CvMat is now obsolete; consider using Mat instead. + */ +typedef struct CvMat +{ + int type; + int step; + + /* for internal use only */ + int* refcount; + int hdr_refcount; + + union + { + uchar* ptr; + short* s; + int* i; + float* fl; + double* db; + } data; + +#ifdef __cplusplus + union + { + int rows; + int height; + }; + + union + { + int cols; + int width; + }; +#else + int rows; + int cols; +#endif + +#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + CvMat() {} + CvMat(const cv::Mat& m) { *this = cvMat(m); } +#endif +} +CvMat; + + +#define CV_IS_MAT_HDR(mat) \ + ((mat) != NULL && \ + (((const CvMat*)(mat))->type & CV_MAGIC_MASK) == CV_MAT_MAGIC_VAL && \ + ((const CvMat*)(mat))->cols > 0 && ((const CvMat*)(mat))->rows > 0) + +#define CV_IS_MAT_HDR_Z(mat) \ + ((mat) != NULL && \ + (((const CvMat*)(mat))->type & CV_MAGIC_MASK) == CV_MAT_MAGIC_VAL && \ + ((const CvMat*)(mat))->cols >= 0 && ((const CvMat*)(mat))->rows >= 0) + +#define CV_IS_MAT(mat) \ + (CV_IS_MAT_HDR(mat) && ((const CvMat*)(mat))->data.ptr != NULL) + +#define CV_IS_MASK_ARR(mat) \ + (((mat)->type & (CV_MAT_TYPE_MASK & ~CV_8SC1)) == 0) + +#define CV_ARE_TYPES_EQ(mat1, mat2) \ + ((((mat1)->type ^ (mat2)->type) & CV_MAT_TYPE_MASK) == 0) + +#define CV_ARE_CNS_EQ(mat1, mat2) \ + ((((mat1)->type ^ (mat2)->type) & CV_MAT_CN_MASK) == 0) + +#define CV_ARE_DEPTHS_EQ(mat1, mat2) \ + ((((mat1)->type ^ (mat2)->type) & CV_MAT_DEPTH_MASK) == 0) + +#define CV_ARE_SIZES_EQ(mat1, mat2) \ + ((mat1)->rows == (mat2)->rows && (mat1)->cols == (mat2)->cols) + +#define CV_IS_MAT_CONST(mat) \ + (((mat)->rows|(mat)->cols) == 1) + +#define IPL2CV_DEPTH(depth) \ + ((((CV_8U)+(CV_16U<<4)+(CV_32F<<8)+(CV_64F<<16)+(CV_8S<<20)+ \ + (CV_16S<<24)+(CV_32S<<28)) >> ((((depth) & 0xF0) >> 2) + \ + (((depth) & IPL_DEPTH_SIGN) ? 20 : 0))) & 15) + +/** Inline constructor. No data is allocated internally!!! + * (Use together with cvCreateData, or use cvCreateMat instead to + * get a matrix with allocated data): + */ +CV_INLINE CvMat cvMat( int rows, int cols, int type, void* data CV_DEFAULT(NULL)) +{ + CvMat m; + + assert( (unsigned)CV_MAT_DEPTH(type) <= CV_64F ); + type = CV_MAT_TYPE(type); + m.type = CV_MAT_MAGIC_VAL | CV_MAT_CONT_FLAG | type; + m.cols = cols; + m.rows = rows; + m.step = m.cols*CV_ELEM_SIZE(type); + m.data.ptr = (uchar*)data; + m.refcount = NULL; + m.hdr_refcount = 0; + + return m; +} + +#ifdef __cplusplus + +CV_INLINE CvMat cvMat(const cv::Mat& m) +{ + CvMat self; + CV_DbgAssert(m.dims <= 2); + self = cvMat(m.rows, m.dims == 1 ? 1 : m.cols, m.type(), m.data); + self.step = (int)m.step[0]; + self.type = (self.type & ~cv::Mat::CONTINUOUS_FLAG) | (m.flags & cv::Mat::CONTINUOUS_FLAG); + return self; +} +CV_INLINE CvMat cvMat() +{ +#if !defined(CV__ENABLE_C_API_CTORS) + CvMat self = CV_STRUCT_INITIALIZER; return self; +#else + return CvMat(); +#endif +} +CV_INLINE CvMat cvMat(const CvMat& m) +{ +#if !defined(CV__ENABLE_C_API_CTORS) + CvMat self = CV_STRUCT_INITIALIZER; memcpy(&self, &m, sizeof(self)); return self; +#else + return CvMat(m); +#endif +} + +#endif // __cplusplus + + +#define CV_MAT_ELEM_PTR_FAST( mat, row, col, pix_size ) \ + (assert( (unsigned)(row) < (unsigned)(mat).rows && \ + (unsigned)(col) < (unsigned)(mat).cols ), \ + (mat).data.ptr + (size_t)(mat).step*(row) + (pix_size)*(col)) + +#define CV_MAT_ELEM_PTR( mat, row, col ) \ + CV_MAT_ELEM_PTR_FAST( mat, row, col, CV_ELEM_SIZE((mat).type) ) + +#define CV_MAT_ELEM( mat, elemtype, row, col ) \ + (*(elemtype*)CV_MAT_ELEM_PTR_FAST( mat, row, col, sizeof(elemtype))) + +/** @brief Returns the particular element of single-channel floating-point matrix. + +The function is a fast replacement for cvGetReal2D in the case of single-channel floating-point +matrices. It is faster because it is inline, it does fewer checks for array type and array element +type, and it checks for the row and column ranges only in debug mode. +@param mat Input matrix +@param row The zero-based index of row +@param col The zero-based index of column + */ +CV_INLINE double cvmGet( const CvMat* mat, int row, int col ) +{ + int type; + + type = CV_MAT_TYPE(mat->type); + assert( (unsigned)row < (unsigned)mat->rows && + (unsigned)col < (unsigned)mat->cols ); + + if( type == CV_32FC1 ) + return ((float*)(void*)(mat->data.ptr + (size_t)mat->step*row))[col]; + else + { + assert( type == CV_64FC1 ); + return ((double*)(void*)(mat->data.ptr + (size_t)mat->step*row))[col]; + } +} + +/** @brief Sets a specific element of a single-channel floating-point matrix. + +The function is a fast replacement for cvSetReal2D in the case of single-channel floating-point +matrices. It is faster because it is inline, it does fewer checks for array type and array element +type, and it checks for the row and column ranges only in debug mode. +@param mat The matrix +@param row The zero-based index of row +@param col The zero-based index of column +@param value The new value of the matrix element + */ +CV_INLINE void cvmSet( CvMat* mat, int row, int col, double value ) +{ + int type; + type = CV_MAT_TYPE(mat->type); + assert( (unsigned)row < (unsigned)mat->rows && + (unsigned)col < (unsigned)mat->cols ); + + if( type == CV_32FC1 ) + ((float*)(void*)(mat->data.ptr + (size_t)mat->step*row))[col] = (float)value; + else + { + assert( type == CV_64FC1 ); + ((double*)(void*)(mat->data.ptr + (size_t)mat->step*row))[col] = value; + } +} + + +CV_INLINE int cvIplDepth( int type ) +{ + int depth = CV_MAT_DEPTH(type); + return CV_ELEM_SIZE1(depth)*8 | (depth == CV_8S || depth == CV_16S || + depth == CV_32S ? IPL_DEPTH_SIGN : 0); +} + + +/****************************************************************************************\ +* Multi-dimensional dense array (CvMatND) * +\****************************************************************************************/ + +#define CV_MATND_MAGIC_VAL 0x42430000 +#define CV_TYPE_NAME_MATND "opencv-nd-matrix" + +#ifdef __cplusplus +typedef struct CvMatND CvMatND; +CV_EXPORTS CvMatND cvMatND(const cv::Mat& m); +#endif + +/** + @deprecated consider using cv::Mat instead + */ +typedef struct +CvMatND +{ + int type; + int dims; + + int* refcount; + int hdr_refcount; + + union + { + uchar* ptr; + float* fl; + double* db; + int* i; + short* s; + } data; + + struct + { + int size; + int step; + } + dim[CV_MAX_DIM]; + +#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + CvMatND() {} + CvMatND(const cv::Mat& m) { *this = cvMatND(m); } +#endif +} +CvMatND; + + +CV_INLINE CvMatND cvMatND() +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvMatND self = CV_STRUCT_INITIALIZER; return self; +#else + return CvMatND(); +#endif +} + +#define CV_IS_MATND_HDR(mat) \ + ((mat) != NULL && (((const CvMatND*)(mat))->type & CV_MAGIC_MASK) == CV_MATND_MAGIC_VAL) + +#define CV_IS_MATND(mat) \ + (CV_IS_MATND_HDR(mat) && ((const CvMatND*)(mat))->data.ptr != NULL) + + +/****************************************************************************************\ +* Multi-dimensional sparse array (CvSparseMat) * +\****************************************************************************************/ + +#define CV_SPARSE_MAT_MAGIC_VAL 0x42440000 +#define CV_TYPE_NAME_SPARSE_MAT "opencv-sparse-matrix" + +struct CvSet; + +typedef struct CvSparseMat +{ + int type; + int dims; + int* refcount; + int hdr_refcount; + + struct CvSet* heap; + void** hashtable; + int hashsize; + int valoffset; + int idxoffset; + int size[CV_MAX_DIM]; + +#ifdef __cplusplus + CV_EXPORTS void copyToSparseMat(cv::SparseMat& m) const; +#endif +} +CvSparseMat; + +#ifdef __cplusplus +CV_EXPORTS CvSparseMat* cvCreateSparseMat(const cv::SparseMat& m); +#endif + +#define CV_IS_SPARSE_MAT_HDR(mat) \ + ((mat) != NULL && \ + (((const CvSparseMat*)(mat))->type & CV_MAGIC_MASK) == CV_SPARSE_MAT_MAGIC_VAL) + +#define CV_IS_SPARSE_MAT(mat) \ + CV_IS_SPARSE_MAT_HDR(mat) + +/**************** iteration through a sparse array *****************/ + +typedef struct CvSparseNode +{ + unsigned hashval; + struct CvSparseNode* next; +} +CvSparseNode; + +typedef struct CvSparseMatIterator +{ + CvSparseMat* mat; + CvSparseNode* node; + int curidx; +} +CvSparseMatIterator; + +#define CV_NODE_VAL(mat,node) ((void*)((uchar*)(node) + (mat)->valoffset)) +#define CV_NODE_IDX(mat,node) ((int*)((uchar*)(node) + (mat)->idxoffset)) + +/****************************************************************************************\ +* Histogram * +\****************************************************************************************/ + +typedef int CvHistType; + +#define CV_HIST_MAGIC_VAL 0x42450000 +#define CV_HIST_UNIFORM_FLAG (1 << 10) + +/** indicates whether bin ranges are set already or not */ +#define CV_HIST_RANGES_FLAG (1 << 11) + +#define CV_HIST_ARRAY 0 +#define CV_HIST_SPARSE 1 +#define CV_HIST_TREE CV_HIST_SPARSE + +/** should be used as a parameter only, + it turns to CV_HIST_UNIFORM_FLAG of hist->type */ +#define CV_HIST_UNIFORM 1 + +typedef struct CvHistogram +{ + int type; + CvArr* bins; + float thresh[CV_MAX_DIM][2]; /**< For uniform histograms. */ + float** thresh2; /**< For non-uniform histograms. */ + CvMatND mat; /**< Embedded matrix header for array histograms. */ +} +CvHistogram; + +#define CV_IS_HIST( hist ) \ + ((hist) != NULL && \ + (((CvHistogram*)(hist))->type & CV_MAGIC_MASK) == CV_HIST_MAGIC_VAL && \ + (hist)->bins != NULL) + +#define CV_IS_UNIFORM_HIST( hist ) \ + (((hist)->type & CV_HIST_UNIFORM_FLAG) != 0) + +#define CV_IS_SPARSE_HIST( hist ) \ + CV_IS_SPARSE_MAT((hist)->bins) + +#define CV_HIST_HAS_RANGES( hist ) \ + (((hist)->type & CV_HIST_RANGES_FLAG) != 0) + +/****************************************************************************************\ +* Other supplementary data type definitions * +\****************************************************************************************/ + +/*************************************** CvRect *****************************************/ +/** @sa Rect_ */ +typedef struct CvRect +{ + int x; + int y; + int width; + int height; + +#ifdef CV__VALIDATE_UNUNITIALIZED_VARS + CvRect() __attribute__(( warning("Non-initialized variable") )) {}; + template CvRect(const std::initializer_list<_Tp> list) + { + CV_Assert(list.size() == 0 || list.size() == 4); + x = y = width = height = 0; + if (list.size() == 4) + { + x = list.begin()[0]; y = list.begin()[1]; width = list.begin()[2]; height = list.begin()[3]; + } + }; +#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + CvRect(int _x = 0, int _y = 0, int w = 0, int h = 0): x(_x), y(_y), width(w), height(h) {} + template + CvRect(const cv::Rect_<_Tp>& r): x(cv::saturate_cast(r.x)), y(cv::saturate_cast(r.y)), width(cv::saturate_cast(r.width)), height(cv::saturate_cast(r.height)) {} +#endif +#ifdef __cplusplus + template + operator cv::Rect_<_Tp>() const { return cv::Rect_<_Tp>((_Tp)x, (_Tp)y, (_Tp)width, (_Tp)height); } +#endif +} +CvRect; + +/** constructs CvRect structure. */ +CV_INLINE CvRect cvRect( int x, int y, int width, int height ) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvRect r = {x, y, width, height}; +#else + CvRect r(x, y , width, height); +#endif + return r; +} +#ifdef __cplusplus +CV_INLINE CvRect cvRect(const cv::Rect& rc) { return cvRect(rc.x, rc.y, rc.width, rc.height); } +#endif + +CV_INLINE IplROI cvRectToROI( CvRect rect, int coi ) +{ + IplROI roi; + roi.xOffset = rect.x; + roi.yOffset = rect.y; + roi.width = rect.width; + roi.height = rect.height; + roi.coi = coi; + + return roi; +} + + +CV_INLINE CvRect cvROIToRect( IplROI roi ) +{ + return cvRect( roi.xOffset, roi.yOffset, roi.width, roi.height ); +} + +/*********************************** CvTermCriteria *************************************/ + +#define CV_TERMCRIT_ITER 1 +#define CV_TERMCRIT_NUMBER CV_TERMCRIT_ITER +#define CV_TERMCRIT_EPS 2 + +/** @sa TermCriteria + */ +typedef struct CvTermCriteria +{ + int type; /**< may be combination of + CV_TERMCRIT_ITER + CV_TERMCRIT_EPS */ + int max_iter; + double epsilon; +#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + CvTermCriteria(int _type = 0, int _iter = 0, double _eps = 0) : type(_type), max_iter(_iter), epsilon(_eps) {} + CvTermCriteria(const cv::TermCriteria& t) : type(t.type), max_iter(t.maxCount), epsilon(t.epsilon) {} +#endif +#ifdef __cplusplus + operator cv::TermCriteria() const { return cv::TermCriteria(type, max_iter, epsilon); } +#endif +} +CvTermCriteria; + +CV_INLINE CvTermCriteria cvTermCriteria( int type, int max_iter, double epsilon ) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvTermCriteria t = { type, max_iter, (float)epsilon}; +#else + CvTermCriteria t(type, max_iter, epsilon); +#endif + return t; +} +#ifdef __cplusplus +CV_INLINE CvTermCriteria cvTermCriteria(const cv::TermCriteria& t) { return cvTermCriteria(t.type, t.maxCount, t.epsilon); } +#endif + + +/******************************* CvPoint and variants ***********************************/ + +typedef struct CvPoint +{ + int x; + int y; + +#ifdef CV__VALIDATE_UNUNITIALIZED_VARS + CvPoint() __attribute__(( warning("Non-initialized variable") )) {} + template CvPoint(const std::initializer_list<_Tp> list) + { + CV_Assert(list.size() == 0 || list.size() == 2); + x = y = 0; + if (list.size() == 2) + { + x = list.begin()[0]; y = list.begin()[1]; + } + }; +#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + CvPoint(int _x = 0, int _y = 0): x(_x), y(_y) {} + template + CvPoint(const cv::Point_<_Tp>& pt): x((int)pt.x), y((int)pt.y) {} +#endif +#ifdef __cplusplus + template + operator cv::Point_<_Tp>() const { return cv::Point_<_Tp>(cv::saturate_cast<_Tp>(x), cv::saturate_cast<_Tp>(y)); } +#endif +} +CvPoint; + +/** constructs CvPoint structure. */ +CV_INLINE CvPoint cvPoint( int x, int y ) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvPoint p = {x, y}; +#else + CvPoint p(x, y); +#endif + return p; +} +#ifdef __cplusplus +CV_INLINE CvPoint cvPoint(const cv::Point& pt) { return cvPoint(pt.x, pt.y); } +#endif + +typedef struct CvPoint2D32f +{ + float x; + float y; + +#ifdef CV__VALIDATE_UNUNITIALIZED_VARS + CvPoint2D32f() __attribute__(( warning("Non-initialized variable") )) {} + template CvPoint2D32f(const std::initializer_list<_Tp> list) + { + CV_Assert(list.size() == 0 || list.size() == 2); + x = y = 0; + if (list.size() == 2) + { + x = list.begin()[0]; y = list.begin()[1]; + } + }; +#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + CvPoint2D32f(float _x = 0, float _y = 0): x(_x), y(_y) {} + template + CvPoint2D32f(const cv::Point_<_Tp>& pt): x((float)pt.x), y((float)pt.y) {} +#endif +#ifdef __cplusplus + template + operator cv::Point_<_Tp>() const { return cv::Point_<_Tp>(cv::saturate_cast<_Tp>(x), cv::saturate_cast<_Tp>(y)); } +#endif +} +CvPoint2D32f; + +/** constructs CvPoint2D32f structure. */ +CV_INLINE CvPoint2D32f cvPoint2D32f( double x, double y ) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvPoint2D32f p = { (float)x, (float)y }; +#else + CvPoint2D32f p((float)x, (float)y); +#endif + return p; +} + +#ifdef __cplusplus +template +CvPoint2D32f cvPoint2D32f(const cv::Point_<_Tp>& pt) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvPoint2D32f p = { (float)pt.x, (float)pt.y }; +#else + CvPoint2D32f p((float)pt.x, (float)pt.y); +#endif + return p; +} +#endif + +/** converts CvPoint to CvPoint2D32f. */ +CV_INLINE CvPoint2D32f cvPointTo32f( CvPoint point ) +{ + return cvPoint2D32f( (float)point.x, (float)point.y ); +} + +/** converts CvPoint2D32f to CvPoint. */ +CV_INLINE CvPoint cvPointFrom32f( CvPoint2D32f point ) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvPoint ipt = { cvRound(point.x), cvRound(point.y) }; +#else + CvPoint ipt(cvRound(point.x), cvRound(point.y)); +#endif + return ipt; +} + + +typedef struct CvPoint3D32f +{ + float x; + float y; + float z; + +#ifdef CV__VALIDATE_UNUNITIALIZED_VARS + CvPoint3D32f() __attribute__(( warning("Non-initialized variable") )) {} + template CvPoint3D32f(const std::initializer_list<_Tp> list) + { + CV_Assert(list.size() == 0 || list.size() == 3); + x = y = z = 0; + if (list.size() == 3) + { + x = list.begin()[0]; y = list.begin()[1]; z = list.begin()[2]; + } + }; +#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + CvPoint3D32f(float _x = 0, float _y = 0, float _z = 0): x(_x), y(_y), z(_z) {} + template + CvPoint3D32f(const cv::Point3_<_Tp>& pt): x((float)pt.x), y((float)pt.y), z((float)pt.z) {} +#endif +#ifdef __cplusplus + template + operator cv::Point3_<_Tp>() const { return cv::Point3_<_Tp>(cv::saturate_cast<_Tp>(x), cv::saturate_cast<_Tp>(y), cv::saturate_cast<_Tp>(z)); } +#endif +} +CvPoint3D32f; + +/** constructs CvPoint3D32f structure. */ +CV_INLINE CvPoint3D32f cvPoint3D32f( double x, double y, double z ) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvPoint3D32f p = { (float)x, (float)y, (float)z }; +#else + CvPoint3D32f p((float)x, (float)y, (float)z); +#endif + return p; +} + +#ifdef __cplusplus +template +CvPoint3D32f cvPoint3D32f(const cv::Point3_<_Tp>& pt) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvPoint3D32f p = { (float)pt.x, (float)pt.y, (float)pt.z }; +#else + CvPoint3D32f p((float)pt.x, (float)pt.y, (float)pt.z); +#endif + return p; +} +#endif + + +typedef struct CvPoint2D64f +{ + double x; + double y; +#ifdef CV__VALIDATE_UNUNITIALIZED_VARS + CvPoint2D64f() __attribute__(( warning("Non-initialized variable") )) {} + template CvPoint2D64f(const std::initializer_list<_Tp> list) + { + CV_Assert(list.size() == 0 || list.size() == 2); + x = y = 0; + if (list.size() == 2) + { + x = list.begin()[0]; y = list.begin()[1]; + } + }; +#endif +} +CvPoint2D64f; + +/** constructs CvPoint2D64f structure.*/ +CV_INLINE CvPoint2D64f cvPoint2D64f( double x, double y ) +{ + CvPoint2D64f p = { x, y }; + return p; +} + + +typedef struct CvPoint3D64f +{ + double x; + double y; + double z; +#ifdef CV__VALIDATE_UNUNITIALIZED_VARS + CvPoint3D64f() __attribute__(( warning("Non-initialized variable") )) {} + template CvPoint3D64f(const std::initializer_list<_Tp> list) + { + CV_Assert(list.size() == 0 || list.size() == 3); + x = y = z = 0; + if (list.size() == 3) + { + x = list.begin()[0]; y = list.begin()[1]; z = list.begin()[2]; + } + }; +#endif +} +CvPoint3D64f; + +/** constructs CvPoint3D64f structure. */ +CV_INLINE CvPoint3D64f cvPoint3D64f( double x, double y, double z ) +{ + CvPoint3D64f p = { x, y, z }; + return p; +} + + +/******************************** CvSize's & CvBox **************************************/ + +typedef struct CvSize +{ + int width; + int height; + +#ifdef CV__VALIDATE_UNUNITIALIZED_VARS + CvSize() __attribute__(( warning("Non-initialized variable") )) {} + template CvSize(const std::initializer_list<_Tp> list) + { + CV_Assert(list.size() == 0 || list.size() == 2); + width = 0; height = 0; + if (list.size() == 2) + { + width = list.begin()[0]; height = list.begin()[1]; + } + }; +#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + CvSize(int w = 0, int h = 0): width(w), height(h) {} + template + CvSize(const cv::Size_<_Tp>& sz): width(cv::saturate_cast(sz.width)), height(cv::saturate_cast(sz.height)) {} +#endif +#ifdef __cplusplus + template + operator cv::Size_<_Tp>() const { return cv::Size_<_Tp>(cv::saturate_cast<_Tp>(width), cv::saturate_cast<_Tp>(height)); } +#endif +} +CvSize; + +/** constructs CvSize structure. */ +CV_INLINE CvSize cvSize( int width, int height ) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvSize s = { width, height }; +#else + CvSize s(width, height); +#endif + return s; +} + +#ifdef __cplusplus +CV_INLINE CvSize cvSize(const cv::Size& sz) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvSize s = { sz.width, sz.height }; +#else + CvSize s(sz.width, sz.height); +#endif + return s; +} +#endif + +typedef struct CvSize2D32f +{ + float width; + float height; + +#ifdef CV__VALIDATE_UNUNITIALIZED_VARS + CvSize2D32f() __attribute__(( warning("Non-initialized variable") )) {} + template CvSize2D32f(const std::initializer_list<_Tp> list) + { + CV_Assert(list.size() == 0 || list.size() == 2); + width = 0; height = 0; + if (list.size() == 2) + { + width = list.begin()[0]; height = list.begin()[1]; + } + }; +#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + CvSize2D32f(float w = 0, float h = 0): width(w), height(h) {} + template + CvSize2D32f(const cv::Size_<_Tp>& sz): width(cv::saturate_cast(sz.width)), height(cv::saturate_cast(sz.height)) {} +#endif +#ifdef __cplusplus + template + operator cv::Size_<_Tp>() const { return cv::Size_<_Tp>(cv::saturate_cast<_Tp>(width), cv::saturate_cast<_Tp>(height)); } +#endif +} +CvSize2D32f; + +/** constructs CvSize2D32f structure. */ +CV_INLINE CvSize2D32f cvSize2D32f( double width, double height ) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvSize2D32f s = { (float)width, (float)height }; +#else + CvSize2D32f s((float)width, (float)height); +#endif + return s; +} +#ifdef __cplusplus +template +CvSize2D32f cvSize2D32f(const cv::Size_<_Tp>& sz) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvSize2D32f s = { (float)sz.width, (float)sz.height }; +#else + CvSize2D32f s((float)sz.width, (float)sz.height); +#endif + return s; +} +#endif + +/** @sa RotatedRect + */ +typedef struct CvBox2D +{ + CvPoint2D32f center; /**< Center of the box. */ + CvSize2D32f size; /**< Box width and length. */ + float angle; /**< Angle between the horizontal axis */ + /**< and the first side (i.e. length) in degrees */ + +#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + CvBox2D(CvPoint2D32f c = CvPoint2D32f(), CvSize2D32f s = CvSize2D32f(), float a = 0) : center(c), size(s), angle(a) {} + CvBox2D(const cv::RotatedRect& rr) : center(rr.center), size(rr.size), angle(rr.angle) {} +#endif +#ifdef __cplusplus + operator cv::RotatedRect() const { return cv::RotatedRect(center, size, angle); } +#endif +} +CvBox2D; + + +#ifdef __cplusplus +CV_INLINE CvBox2D cvBox2D(CvPoint2D32f c = CvPoint2D32f(), CvSize2D32f s = CvSize2D32f(), float a = 0) +{ + CvBox2D self; + self.center = c; + self.size = s; + self.angle = a; + return self; +} +CV_INLINE CvBox2D cvBox2D(const cv::RotatedRect& rr) +{ + CvBox2D self; + self.center = cvPoint2D32f(rr.center); + self.size = cvSize2D32f(rr.size); + self.angle = rr.angle; + return self; +} +#endif + + +/** Line iterator state: */ +typedef struct CvLineIterator +{ + /** Pointer to the current point: */ + uchar* ptr; + + /* Bresenham algorithm state: */ + int err; + int plus_delta; + int minus_delta; + int plus_step; + int minus_step; +} +CvLineIterator; + + + +/************************************* CvSlice ******************************************/ +#define CV_WHOLE_SEQ_END_INDEX 0x3fffffff +#define CV_WHOLE_SEQ cvSlice(0, CV_WHOLE_SEQ_END_INDEX) + +typedef struct CvSlice +{ + int start_index, end_index; + +#ifdef CV__VALIDATE_UNUNITIALIZED_VARS + CvSlice() __attribute__(( warning("Non-initialized variable") )) {} + template CvSlice(const std::initializer_list<_Tp> list) + { + CV_Assert(list.size() == 0 || list.size() == 2); + start_index = end_index = 0; + if (list.size() == 2) + { + start_index = list.begin()[0]; end_index = list.begin()[1]; + } + }; +#endif +#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) && !defined(__CUDACC__) + CvSlice(int start = 0, int end = 0) : start_index(start), end_index(end) {} + CvSlice(const cv::Range& r) { *this = (r.start != INT_MIN && r.end != INT_MAX) ? CvSlice(r.start, r.end) : CvSlice(0, CV_WHOLE_SEQ_END_INDEX); } + operator cv::Range() const { return (start_index == 0 && end_index == CV_WHOLE_SEQ_END_INDEX ) ? cv::Range::all() : cv::Range(start_index, end_index); } +#endif +} +CvSlice; + +CV_INLINE CvSlice cvSlice( int start, int end ) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) && !defined(__CUDACC__)) + CvSlice slice = { start, end }; +#else + CvSlice slice(start, end); +#endif + return slice; +} + +#if defined(__cplusplus) +CV_INLINE CvSlice cvSlice(const cv::Range& r) +{ + CvSlice slice = (r.start != INT_MIN && r.end != INT_MAX) ? cvSlice(r.start, r.end) : cvSlice(0, CV_WHOLE_SEQ_END_INDEX); + return slice; +} +#endif + + +/************************************* CvScalar *****************************************/ +/** @sa Scalar_ + */ +typedef struct CvScalar +{ + double val[4]; + +#ifdef CV__VALIDATE_UNUNITIALIZED_VARS + CvScalar() __attribute__(( warning("Non-initialized variable") )) {} + CvScalar(const std::initializer_list list) + { + CV_Assert(list.size() == 0 || list.size() == 4); + val[0] = val[1] = val[2] = val[3] = 0; + if (list.size() == 4) + { + val[0] = list.begin()[0]; val[1] = list.begin()[1]; val[2] = list.begin()[2]; val[3] = list.begin()[3]; + } + }; +#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + CvScalar() {} + CvScalar(double d0, double d1 = 0, double d2 = 0, double d3 = 0) { val[0] = d0; val[1] = d1; val[2] = d2; val[3] = d3; } + template + CvScalar(const cv::Scalar_<_Tp>& s) { val[0] = s.val[0]; val[1] = s.val[1]; val[2] = s.val[2]; val[3] = s.val[3]; } + template + CvScalar(const cv::Vec<_Tp, cn>& v) + { + int i; + for( i = 0; i < (cn < 4 ? cn : 4); i++ ) val[i] = v.val[i]; + for( ; i < 4; i++ ) val[i] = 0; + } +#endif +#ifdef __cplusplus + template + operator cv::Scalar_<_Tp>() const { return cv::Scalar_<_Tp>(cv::saturate_cast<_Tp>(val[0]), cv::saturate_cast<_Tp>(val[1]), cv::saturate_cast<_Tp>(val[2]), cv::saturate_cast<_Tp>(val[3])); } +#endif +} +CvScalar; + +CV_INLINE CvScalar cvScalar( double val0, double val1 CV_DEFAULT(0), + double val2 CV_DEFAULT(0), double val3 CV_DEFAULT(0)) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvScalar scalar = CV_STRUCT_INITIALIZER; +#else + CvScalar scalar; +#endif + scalar.val[0] = val0; scalar.val[1] = val1; + scalar.val[2] = val2; scalar.val[3] = val3; + return scalar; +} + +#ifdef __cplusplus +CV_INLINE CvScalar cvScalar() +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvScalar scalar = CV_STRUCT_INITIALIZER; +#else + CvScalar scalar; +#endif + scalar.val[0] = scalar.val[1] = scalar.val[2] = scalar.val[3] = 0; + return scalar; +} +CV_INLINE CvScalar cvScalar(const cv::Scalar& s) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvScalar scalar = CV_STRUCT_INITIALIZER; +#else + CvScalar scalar; +#endif + scalar.val[0] = s.val[0]; + scalar.val[1] = s.val[1]; + scalar.val[2] = s.val[2]; + scalar.val[3] = s.val[3]; + return scalar; +} +#endif + +CV_INLINE CvScalar cvRealScalar( double val0 ) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvScalar scalar = CV_STRUCT_INITIALIZER; +#else + CvScalar scalar; +#endif + scalar.val[0] = val0; + scalar.val[1] = scalar.val[2] = scalar.val[3] = 0; + return scalar; +} + +CV_INLINE CvScalar cvScalarAll( double val0123 ) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvScalar scalar = CV_STRUCT_INITIALIZER; +#else + CvScalar scalar; +#endif + scalar.val[0] = val0123; + scalar.val[1] = val0123; + scalar.val[2] = val0123; + scalar.val[3] = val0123; + return scalar; +} + +/****************************************************************************************\ +* Dynamic Data structures * +\****************************************************************************************/ + +/******************************** Memory storage ****************************************/ + +typedef struct CvMemBlock +{ + struct CvMemBlock* prev; + struct CvMemBlock* next; +} +CvMemBlock; + +#define CV_STORAGE_MAGIC_VAL 0x42890000 + +typedef struct CvMemStorage +{ + int signature; + CvMemBlock* bottom; /**< First allocated block. */ + CvMemBlock* top; /**< Current memory block - top of the stack. */ + struct CvMemStorage* parent; /**< We get new blocks from parent as needed. */ + int block_size; /**< Block size. */ + int free_space; /**< Remaining free space in current block. */ +} +CvMemStorage; + +#define CV_IS_STORAGE(storage) \ + ((storage) != NULL && \ + (((CvMemStorage*)(storage))->signature & CV_MAGIC_MASK) == CV_STORAGE_MAGIC_VAL) + + +typedef struct CvMemStoragePos +{ + CvMemBlock* top; + int free_space; +} +CvMemStoragePos; + + +/*********************************** Sequence *******************************************/ + +typedef struct CvSeqBlock +{ + struct CvSeqBlock* prev; /**< Previous sequence block. */ + struct CvSeqBlock* next; /**< Next sequence block. */ + int start_index; /**< Index of the first element in the block + */ + /**< sequence->first->start_index. */ + int count; /**< Number of elements in the block. */ + schar* data; /**< Pointer to the first element of the block. */ +} +CvSeqBlock; + + +#define CV_TREE_NODE_FIELDS(node_type) \ + int flags; /**< Miscellaneous flags. */ \ + int header_size; /**< Size of sequence header. */ \ + struct node_type* h_prev; /**< Previous sequence. */ \ + struct node_type* h_next; /**< Next sequence. */ \ + struct node_type* v_prev; /**< 2nd previous sequence. */ \ + struct node_type* v_next /**< 2nd next sequence. */ + +/** + Read/Write sequence. + Elements can be dynamically inserted to or deleted from the sequence. +*/ +#define CV_SEQUENCE_FIELDS() \ + CV_TREE_NODE_FIELDS(CvSeq); \ + int total; /**< Total number of elements. */ \ + int elem_size; /**< Size of sequence element in bytes. */ \ + schar* block_max; /**< Maximal bound of the last block. */ \ + schar* ptr; /**< Current write pointer. */ \ + int delta_elems; /**< Grow seq this many at a time. */ \ + CvMemStorage* storage; /**< Where the seq is stored. */ \ + CvSeqBlock* free_blocks; /**< Free blocks list. */ \ + CvSeqBlock* first; /**< Pointer to the first sequence block. */ + +typedef struct CvSeq +{ + CV_SEQUENCE_FIELDS() +} +CvSeq; + +#define CV_TYPE_NAME_SEQ "opencv-sequence" +#define CV_TYPE_NAME_SEQ_TREE "opencv-sequence-tree" + +/*************************************** Set ********************************************/ +/** @brief Set + Order is not preserved. There can be gaps between sequence elements. + After the element has been inserted it stays in the same place all the time. + The MSB(most-significant or sign bit) of the first field (flags) is 0 iff the element exists. +*/ +#define CV_SET_ELEM_FIELDS(elem_type) \ + int flags; \ + struct elem_type* next_free; + +typedef struct CvSetElem +{ + CV_SET_ELEM_FIELDS(CvSetElem) +} +CvSetElem; + +#define CV_SET_FIELDS() \ + CV_SEQUENCE_FIELDS() \ + CvSetElem* free_elems; \ + int active_count; + +typedef struct CvSet +{ + CV_SET_FIELDS() +} +CvSet; + + +#define CV_SET_ELEM_IDX_MASK ((1 << 26) - 1) +#define CV_SET_ELEM_FREE_FLAG (1 << (sizeof(int)*8-1)) + +/** Checks whether the element pointed by ptr belongs to a set or not */ +#define CV_IS_SET_ELEM( ptr ) (((CvSetElem*)(ptr))->flags >= 0) + +/************************************* Graph ********************************************/ + +/** @name Graph + +We represent a graph as a set of vertices. Vertices contain their adjacency lists (more exactly, +pointers to first incoming or outcoming edge (or 0 if isolated vertex)). Edges are stored in +another set. There is a singly-linked list of incoming/outcoming edges for each vertex. + +Each edge consists of: + +- Two pointers to the starting and ending vertices (vtx[0] and vtx[1] respectively). + + A graph may be oriented or not. In the latter case, edges between vertex i to vertex j are not +distinguished during search operations. + +- Two pointers to next edges for the starting and ending vertices, where next[0] points to the +next edge in the vtx[0] adjacency list and next[1] points to the next edge in the vtx[1] +adjacency list. + +@see CvGraphEdge, CvGraphVtx, CvGraphVtx2D, CvGraph +@{ +*/ +#define CV_GRAPH_EDGE_FIELDS() \ + int flags; \ + float weight; \ + struct CvGraphEdge* next[2]; \ + struct CvGraphVtx* vtx[2]; + + +#define CV_GRAPH_VERTEX_FIELDS() \ + int flags; \ + struct CvGraphEdge* first; + + +typedef struct CvGraphEdge +{ + CV_GRAPH_EDGE_FIELDS() +} +CvGraphEdge; + +typedef struct CvGraphVtx +{ + CV_GRAPH_VERTEX_FIELDS() +} +CvGraphVtx; + +typedef struct CvGraphVtx2D +{ + CV_GRAPH_VERTEX_FIELDS() + CvPoint2D32f* ptr; +} +CvGraphVtx2D; + +/** + Graph is "derived" from the set (this is set a of vertices) + and includes another set (edges) +*/ +#define CV_GRAPH_FIELDS() \ + CV_SET_FIELDS() \ + CvSet* edges; + +typedef struct CvGraph +{ + CV_GRAPH_FIELDS() +} +CvGraph; + +#define CV_TYPE_NAME_GRAPH "opencv-graph" + +/** @} */ + +/*********************************** Chain/Contour *************************************/ + +typedef struct CvChain +{ + CV_SEQUENCE_FIELDS() + CvPoint origin; +} +CvChain; + +#define CV_CONTOUR_FIELDS() \ + CV_SEQUENCE_FIELDS() \ + CvRect rect; \ + int color; \ + int reserved[3]; + +typedef struct CvContour +{ + CV_CONTOUR_FIELDS() +} +CvContour; + +typedef CvContour CvPoint2DSeq; + +/****************************************************************************************\ +* Sequence types * +\****************************************************************************************/ + +#define CV_SEQ_MAGIC_VAL 0x42990000 + +#define CV_IS_SEQ(seq) \ + ((seq) != NULL && (((CvSeq*)(seq))->flags & CV_MAGIC_MASK) == CV_SEQ_MAGIC_VAL) + +#define CV_SET_MAGIC_VAL 0x42980000 +#define CV_IS_SET(set) \ + ((set) != NULL && (((CvSeq*)(set))->flags & CV_MAGIC_MASK) == CV_SET_MAGIC_VAL) + +#define CV_SEQ_ELTYPE_BITS 12 +#define CV_SEQ_ELTYPE_MASK ((1 << CV_SEQ_ELTYPE_BITS) - 1) + +#define CV_SEQ_ELTYPE_POINT CV_32SC2 /**< (x,y) */ +#define CV_SEQ_ELTYPE_CODE CV_8UC1 /**< freeman code: 0..7 */ +#define CV_SEQ_ELTYPE_GENERIC 0 +#define CV_SEQ_ELTYPE_PTR CV_MAKE_TYPE(CV_8U, 8 /*sizeof(void*)*/) +#define CV_SEQ_ELTYPE_PPOINT CV_SEQ_ELTYPE_PTR /**< &(x,y) */ +#define CV_SEQ_ELTYPE_INDEX CV_32SC1 /**< #(x,y) */ +#define CV_SEQ_ELTYPE_GRAPH_EDGE 0 /**< &next_o, &next_d, &vtx_o, &vtx_d */ +#define CV_SEQ_ELTYPE_GRAPH_VERTEX 0 /**< first_edge, &(x,y) */ +#define CV_SEQ_ELTYPE_TRIAN_ATR 0 /**< vertex of the binary tree */ +#define CV_SEQ_ELTYPE_CONNECTED_COMP 0 /**< connected component */ +#define CV_SEQ_ELTYPE_POINT3D CV_32FC3 /**< (x,y,z) */ + +#define CV_SEQ_KIND_BITS 2 +#define CV_SEQ_KIND_MASK (((1 << CV_SEQ_KIND_BITS) - 1)<flags & CV_SEQ_ELTYPE_MASK) +#define CV_SEQ_KIND( seq ) ((seq)->flags & CV_SEQ_KIND_MASK ) + +/** flag checking */ +#define CV_IS_SEQ_INDEX( seq ) ((CV_SEQ_ELTYPE(seq) == CV_SEQ_ELTYPE_INDEX) && \ + (CV_SEQ_KIND(seq) == CV_SEQ_KIND_GENERIC)) + +#define CV_IS_SEQ_CURVE( seq ) (CV_SEQ_KIND(seq) == CV_SEQ_KIND_CURVE) +#define CV_IS_SEQ_CLOSED( seq ) (((seq)->flags & CV_SEQ_FLAG_CLOSED) != 0) +#define CV_IS_SEQ_CONVEX( seq ) 0 +#define CV_IS_SEQ_HOLE( seq ) (((seq)->flags & CV_SEQ_FLAG_HOLE) != 0) +#define CV_IS_SEQ_SIMPLE( seq ) 1 + +/** type checking macros */ +#define CV_IS_SEQ_POINT_SET( seq ) \ + ((CV_SEQ_ELTYPE(seq) == CV_32SC2 || CV_SEQ_ELTYPE(seq) == CV_32FC2)) + +#define CV_IS_SEQ_POINT_SUBSET( seq ) \ + (CV_IS_SEQ_INDEX( seq ) || CV_SEQ_ELTYPE(seq) == CV_SEQ_ELTYPE_PPOINT) + +#define CV_IS_SEQ_POLYLINE( seq ) \ + (CV_SEQ_KIND(seq) == CV_SEQ_KIND_CURVE && CV_IS_SEQ_POINT_SET(seq)) + +#define CV_IS_SEQ_POLYGON( seq ) \ + (CV_IS_SEQ_POLYLINE(seq) && CV_IS_SEQ_CLOSED(seq)) + +#define CV_IS_SEQ_CHAIN( seq ) \ + (CV_SEQ_KIND(seq) == CV_SEQ_KIND_CURVE && (seq)->elem_size == 1) + +#define CV_IS_SEQ_CONTOUR( seq ) \ + (CV_IS_SEQ_CLOSED(seq) && (CV_IS_SEQ_POLYLINE(seq) || CV_IS_SEQ_CHAIN(seq))) + +#define CV_IS_SEQ_CHAIN_CONTOUR( seq ) \ + (CV_IS_SEQ_CHAIN( seq ) && CV_IS_SEQ_CLOSED( seq )) + +#define CV_IS_SEQ_POLYGON_TREE( seq ) \ + (CV_SEQ_ELTYPE (seq) == CV_SEQ_ELTYPE_TRIAN_ATR && \ + CV_SEQ_KIND( seq ) == CV_SEQ_KIND_BIN_TREE ) + +#define CV_IS_GRAPH( seq ) \ + (CV_IS_SET(seq) && CV_SEQ_KIND((CvSet*)(seq)) == CV_SEQ_KIND_GRAPH) + +#define CV_IS_GRAPH_ORIENTED( seq ) \ + (((seq)->flags & CV_GRAPH_FLAG_ORIENTED) != 0) + +#define CV_IS_SUBDIV2D( seq ) \ + (CV_IS_SET(seq) && CV_SEQ_KIND((CvSet*)(seq)) == CV_SEQ_KIND_SUBDIV2D) + +/****************************************************************************************/ +/* Sequence writer & reader */ +/****************************************************************************************/ + +#define CV_SEQ_WRITER_FIELDS() \ + int header_size; \ + CvSeq* seq; /**< the sequence written */ \ + CvSeqBlock* block; /**< current block */ \ + schar* ptr; /**< pointer to free space */ \ + schar* block_min; /**< pointer to the beginning of block*/\ + schar* block_max; /**< pointer to the end of block */ + +typedef struct CvSeqWriter +{ + CV_SEQ_WRITER_FIELDS() +} +CvSeqWriter; + + +#define CV_SEQ_READER_FIELDS() \ + int header_size; \ + CvSeq* seq; /**< sequence, beign read */ \ + CvSeqBlock* block; /**< current block */ \ + schar* ptr; /**< pointer to element be read next */ \ + schar* block_min; /**< pointer to the beginning of block */\ + schar* block_max; /**< pointer to the end of block */ \ + int delta_index;/**< = seq->first->start_index */ \ + schar* prev_elem; /**< pointer to previous element */ + +typedef struct CvSeqReader +{ + CV_SEQ_READER_FIELDS() +} +CvSeqReader; + +/****************************************************************************************/ +/* Operations on sequences */ +/****************************************************************************************/ + +#define CV_SEQ_ELEM( seq, elem_type, index ) \ +/** assert gives some guarantee that parameter is valid */ \ +( assert(sizeof((seq)->first[0]) == sizeof(CvSeqBlock) && \ + (seq)->elem_size == sizeof(elem_type)), \ + (elem_type*)((seq)->first && (unsigned)index < \ + (unsigned)((seq)->first->count) ? \ + (seq)->first->data + (index) * sizeof(elem_type) : \ + cvGetSeqElem( (CvSeq*)(seq), (index) ))) +#define CV_GET_SEQ_ELEM( elem_type, seq, index ) CV_SEQ_ELEM( (seq), elem_type, (index) ) + +/** Add element to sequence: */ +#define CV_WRITE_SEQ_ELEM_VAR( elem_ptr, writer ) \ +{ \ + if( (writer).ptr >= (writer).block_max ) \ + { \ + cvCreateSeqBlock( &writer); \ + } \ + memcpy((writer).ptr, elem_ptr, (writer).seq->elem_size);\ + (writer).ptr += (writer).seq->elem_size; \ +} + +#define CV_WRITE_SEQ_ELEM( elem, writer ) \ +{ \ + assert( (writer).seq->elem_size == sizeof(elem)); \ + if( (writer).ptr >= (writer).block_max ) \ + { \ + cvCreateSeqBlock( &writer); \ + } \ + assert( (writer).ptr <= (writer).block_max - sizeof(elem));\ + memcpy((writer).ptr, &(elem), sizeof(elem)); \ + (writer).ptr += sizeof(elem); \ +} + + +/** Move reader position forward: */ +#define CV_NEXT_SEQ_ELEM( elem_size, reader ) \ +{ \ + if( ((reader).ptr += (elem_size)) >= (reader).block_max ) \ + { \ + cvChangeSeqBlock( &(reader), 1 ); \ + } \ +} + + +/** Move reader position backward: */ +#define CV_PREV_SEQ_ELEM( elem_size, reader ) \ +{ \ + if( ((reader).ptr -= (elem_size)) < (reader).block_min ) \ + { \ + cvChangeSeqBlock( &(reader), -1 ); \ + } \ +} + +/** Read element and move read position forward: */ +#define CV_READ_SEQ_ELEM( elem, reader ) \ +{ \ + assert( (reader).seq->elem_size == sizeof(elem)); \ + memcpy( &(elem), (reader).ptr, sizeof((elem))); \ + CV_NEXT_SEQ_ELEM( sizeof(elem), reader ) \ +} + +/** Read element and move read position backward: */ +#define CV_REV_READ_SEQ_ELEM( elem, reader ) \ +{ \ + assert( (reader).seq->elem_size == sizeof(elem)); \ + memcpy(&(elem), (reader).ptr, sizeof((elem))); \ + CV_PREV_SEQ_ELEM( sizeof(elem), reader ) \ +} + + +#define CV_READ_CHAIN_POINT( _pt, reader ) \ +{ \ + (_pt) = (reader).pt; \ + if( (reader).ptr ) \ + { \ + CV_READ_SEQ_ELEM( (reader).code, (reader)); \ + assert( ((reader).code & ~7) == 0 ); \ + (reader).pt.x += (reader).deltas[(int)(reader).code][0]; \ + (reader).pt.y += (reader).deltas[(int)(reader).code][1]; \ + } \ +} + +#define CV_CURRENT_POINT( reader ) (*((CvPoint*)((reader).ptr))) +#define CV_PREV_POINT( reader ) (*((CvPoint*)((reader).prev_elem))) + +#define CV_READ_EDGE( pt1, pt2, reader ) \ +{ \ + assert( sizeof(pt1) == sizeof(CvPoint) && \ + sizeof(pt2) == sizeof(CvPoint) && \ + reader.seq->elem_size == sizeof(CvPoint)); \ + (pt1) = CV_PREV_POINT( reader ); \ + (pt2) = CV_CURRENT_POINT( reader ); \ + (reader).prev_elem = (reader).ptr; \ + CV_NEXT_SEQ_ELEM( sizeof(CvPoint), (reader)); \ +} + +/************ Graph macros ************/ + +/** Return next graph edge for given vertex: */ +#define CV_NEXT_GRAPH_EDGE( edge, vertex ) \ + (assert((edge)->vtx[0] == (vertex) || (edge)->vtx[1] == (vertex)), \ + (edge)->next[(edge)->vtx[1] == (vertex)]) + + + +/****************************************************************************************\ +* Data structures for persistence (a.k.a serialization) functionality * +\****************************************************************************************/ + +#if 0 + +/** "black box" file storage */ +typedef struct CvFileStorage CvFileStorage; + +/** Storage flags: */ +#define CV_STORAGE_READ 0 +#define CV_STORAGE_WRITE 1 +#define CV_STORAGE_WRITE_TEXT CV_STORAGE_WRITE +#define CV_STORAGE_WRITE_BINARY CV_STORAGE_WRITE +#define CV_STORAGE_APPEND 2 +#define CV_STORAGE_MEMORY 4 +#define CV_STORAGE_FORMAT_MASK (7<<3) +#define CV_STORAGE_FORMAT_AUTO 0 +#define CV_STORAGE_FORMAT_XML 8 +#define CV_STORAGE_FORMAT_YAML 16 +#define CV_STORAGE_FORMAT_JSON 24 +#define CV_STORAGE_BASE64 64 +#define CV_STORAGE_WRITE_BASE64 (CV_STORAGE_BASE64 | CV_STORAGE_WRITE) + +/** @brief List of attributes. : + +In the current implementation, attributes are used to pass extra parameters when writing user +objects (see cvWrite). XML attributes inside tags are not supported, aside from the object type +specification (type_id attribute). +@see cvAttrList, cvAttrValue + */ +typedef struct CvAttrList +{ + const char** attr; /**< NULL-terminated array of (attribute_name,attribute_value) pairs. */ + struct CvAttrList* next; /**< Pointer to next chunk of the attributes list. */ +} +CvAttrList; + +/** initializes CvAttrList structure */ +CV_INLINE CvAttrList cvAttrList( const char** attr CV_DEFAULT(NULL), + CvAttrList* next CV_DEFAULT(NULL) ) +{ + CvAttrList l; + l.attr = attr; + l.next = next; + + return l; +} + +struct CvTypeInfo; + +#define CV_NODE_NONE 0 +#define CV_NODE_INT 1 +#define CV_NODE_INTEGER CV_NODE_INT +#define CV_NODE_REAL 2 +#define CV_NODE_FLOAT CV_NODE_REAL +#define CV_NODE_STR 3 +#define CV_NODE_STRING CV_NODE_STR +#define CV_NODE_REF 4 /**< not used */ +#define CV_NODE_SEQ 5 +#define CV_NODE_MAP 6 +#define CV_NODE_TYPE_MASK 7 + +#define CV_NODE_TYPE(flags) ((flags) & CV_NODE_TYPE_MASK) + +/** file node flags */ +#define CV_NODE_FLOW 8 /**= CV_NODE_SEQ) +#define CV_NODE_IS_FLOW(flags) (((flags) & CV_NODE_FLOW) != 0) +#define CV_NODE_IS_EMPTY(flags) (((flags) & CV_NODE_EMPTY) != 0) +#define CV_NODE_IS_USER(flags) (((flags) & CV_NODE_USER) != 0) +#define CV_NODE_HAS_NAME(flags) (((flags) & CV_NODE_NAMED) != 0) + +#define CV_NODE_SEQ_SIMPLE 256 +#define CV_NODE_SEQ_IS_SIMPLE(seq) (((seq)->flags & CV_NODE_SEQ_SIMPLE) != 0) + +typedef struct CvString +{ + int len; + char* ptr; +} +CvString; + +/** All the keys (names) of elements in the read file storage + are stored in the hash to speed up the lookup operations: */ +typedef struct CvStringHashNode +{ + unsigned hashval; + CvString str; + struct CvStringHashNode* next; +} +CvStringHashNode; + +typedef struct CvGenericHash CvFileNodeHash; + +/** Basic element of the file storage - scalar or collection: */ +typedef struct CvFileNode +{ + int tag; + struct CvTypeInfo* info; /**< type information + (only for user-defined object, for others it is 0) */ + union + { + double f; /**< scalar floating-point number */ + int i; /**< scalar integer number */ + CvString str; /**< text string */ + CvSeq* seq; /**< sequence (ordered collection of file nodes) */ + CvFileNodeHash* map; /**< map (collection of named file nodes) */ + } data; +} +CvFileNode; + +#ifdef __cplusplus +extern "C" { +#endif +typedef int (CV_CDECL *CvIsInstanceFunc)( const void* struct_ptr ); +typedef void (CV_CDECL *CvReleaseFunc)( void** struct_dblptr ); +typedef void* (CV_CDECL *CvReadFunc)( CvFileStorage* storage, CvFileNode* node ); +typedef void (CV_CDECL *CvWriteFunc)( CvFileStorage* storage, const char* name, + const void* struct_ptr, CvAttrList attributes ); +typedef void* (CV_CDECL *CvCloneFunc)( const void* struct_ptr ); +#ifdef __cplusplus +} +#endif + +/** @brief Type information + +The structure contains information about one of the standard or user-defined types. Instances of the +type may or may not contain a pointer to the corresponding CvTypeInfo structure. In any case, there +is a way to find the type info structure for a given object using the cvTypeOf function. +Alternatively, type info can be found by type name using cvFindType, which is used when an object +is read from file storage. The user can register a new type with cvRegisterType that adds the type +information structure into the beginning of the type list. Thus, it is possible to create +specialized types from generic standard types and override the basic methods. + */ +typedef struct CvTypeInfo +{ + int flags; /**< not used */ + int header_size; /**< sizeof(CvTypeInfo) */ + struct CvTypeInfo* prev; /**< previous registered type in the list */ + struct CvTypeInfo* next; /**< next registered type in the list */ + const char* type_name; /**< type name, written to file storage */ + CvIsInstanceFunc is_instance; /**< checks if the passed object belongs to the type */ + CvReleaseFunc release; /**< releases object (memory etc.) */ + CvReadFunc read; /**< reads object from file storage */ + CvWriteFunc write; /**< writes object to file storage */ + CvCloneFunc clone; /**< creates a copy of the object */ +} +CvTypeInfo; +#endif + +/** @} */ + +#endif /*OPENCV_CORE_TYPES_H*/ + +/* End of file. */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/utility.hpp b/3rdParty/opencv-4.11.0/opencv2/core/utility.hpp index cfe98401db..985d20dcb4 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/utility.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/utility.hpp @@ -1,1301 +1,1301 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_CORE_UTILITY_H -#define OPENCV_CORE_UTILITY_H - -#ifndef __cplusplus -# error utility.hpp header must be compiled as C++ -#endif - -#if defined(check) -# warning Detected Apple 'check' macro definition, it can cause build conflicts. Please, include this header before any Apple headers. -#endif - -#include "opencv2/core.hpp" -#include - -#include - -#if !defined(_M_CEE) -#include // std::mutex, std::lock_guard -#endif - -namespace cv -{ - -//! @addtogroup core_utils -//! @{ - -/** @brief Automatically Allocated Buffer Class - - The class is used for temporary buffers in functions and methods. - If a temporary buffer is usually small (a few K's of memory), - but its size depends on the parameters, it makes sense to create a small - fixed-size array on stack and use it if it's large enough. If the required buffer size - is larger than the fixed size, another buffer of sufficient size is allocated dynamically - and released after the processing. Therefore, in typical cases, when the buffer size is small, - there is no overhead associated with malloc()/free(). - At the same time, there is no limit on the size of processed data. - - This is what AutoBuffer does. The template takes 2 parameters - type of the buffer elements and - the number of stack-allocated elements. Here is how the class is used: - - \code - void my_func(const cv::Mat& m) - { - cv::AutoBuffer buf(1000); // create automatic buffer containing 1000 floats - - buf.allocate(m.rows); // if m.rows <= 1000, the pre-allocated buffer is used, - // otherwise the buffer of "m.rows" floats will be allocated - // dynamically and deallocated in cv::AutoBuffer destructor - ... - } - \endcode -*/ -#ifdef OPENCV_ENABLE_MEMORY_SANITIZER -template class AutoBuffer -#else -template class AutoBuffer -#endif -{ -public: - typedef _Tp value_type; - - //! the default constructor - AutoBuffer(); - //! constructor taking the real buffer size - explicit AutoBuffer(size_t _size); - - //! the copy constructor - AutoBuffer(const AutoBuffer<_Tp, fixed_size>& buf); - //! the assignment operator - AutoBuffer<_Tp, fixed_size>& operator = (const AutoBuffer<_Tp, fixed_size>& buf); - - //! destructor. calls deallocate() - ~AutoBuffer(); - - //! allocates the new buffer of size _size. if the _size is small enough, stack-allocated buffer is used - void allocate(size_t _size); - //! deallocates the buffer if it was dynamically allocated - void deallocate(); - //! resizes the buffer and preserves the content - void resize(size_t _size); - //! returns the current buffer size - size_t size() const; - //! returns pointer to the real buffer, stack-allocated or heap-allocated - inline _Tp* data() { return ptr; } - //! returns read-only pointer to the real buffer, stack-allocated or heap-allocated - inline const _Tp* data() const { return ptr; } - -#if !defined(OPENCV_DISABLE_DEPRECATED_COMPATIBILITY) // use to .data() calls instead - //! returns pointer to the real buffer, stack-allocated or heap-allocated - operator _Tp* () { return ptr; } - //! returns read-only pointer to the real buffer, stack-allocated or heap-allocated - operator const _Tp* () const { return ptr; } -#else - //! returns a reference to the element at specified location. No bounds checking is performed in Release builds. - inline _Tp& operator[] (size_t i) { CV_DbgCheckLT(i, sz, "out of range"); return ptr[i]; } - //! returns a reference to the element at specified location. No bounds checking is performed in Release builds. - inline const _Tp& operator[] (size_t i) const { CV_DbgCheckLT(i, sz, "out of range"); return ptr[i]; } -#endif - -protected: - //! pointer to the real buffer, can point to buf if the buffer is small enough - _Tp* ptr; - //! size of the real buffer - size_t sz; - //! pre-allocated buffer. At least 1 element to confirm C++ standard requirements - _Tp buf[(fixed_size > 0) ? fixed_size : 1]; -}; - -/** @brief Sets/resets the break-on-error mode. - -When the break-on-error mode is set, the default error handler issues a hardware exception, which -can make debugging more convenient. - -\return the previous state - */ -CV_EXPORTS bool setBreakOnError(bool flag); - -extern "C" typedef int (*ErrorCallback)( int status, const char* func_name, - const char* err_msg, const char* file_name, - int line, void* userdata ); - - -/** @brief Sets the new error handler and the optional user data. - - The function sets the new error handler, called from cv::error(). - - \param errCallback the new error handler. If NULL, the default error handler is used. - \param userdata the optional user data pointer, passed to the callback. - \param prevUserdata the optional output parameter where the previous user data pointer is stored - - \return the previous error handler -*/ -CV_EXPORTS ErrorCallback redirectError( ErrorCallback errCallback, void* userdata=0, void** prevUserdata=0); - -/** @brief Generates a unique temporary file name. - -This function generates a full, unique file path for a temporary file, -which can be used to create temporary files for various purposes. - -@param suffix (optional) The desired file extension or suffix for the temporary file (e.g., ".png", ".txt"). -If no suffix is provided (suffix = 0), the file will not have a specific extension. - -@return cv::String A full unique path for the temporary file. - -@note -- The function does not create the file, it only generates the name. -- The file name is unique for the system session. -- Works cross-platform (Windows, Linux, macOS). - */ -CV_EXPORTS String tempfile( const char* suffix = 0); - -/** @brief Searches for files matching the specified pattern in a directory. - -This function searches for files that match a given pattern (e.g., `*.jpg`) -in the specified directory. The search can be limited to the directory itself -or be recursive, including subdirectories. - -@param pattern The file search pattern, which can include wildcards like `*` -(for matching multiple characters) or `?` (for matching a single character). - -@param result Output vector where the file paths matching the search -pattern will be stored. -@param recursive (optional) Boolean flag indicating whether to search -subdirectories recursively. If true, the search will include all subdirectories. -The default value is `false`. - */ -CV_EXPORTS void glob(String pattern, std::vector& result, bool recursive = false); - -/** @brief OpenCV will try to set the number of threads for subsequent parallel regions. - -If threads == 1, OpenCV will disable threading optimizations and run all it's functions -sequentially. Passing threads \< 0 will reset threads number to system default. -The function is not thread-safe. It must not be called in parallel region or concurrent threads. - -OpenCV will try to run its functions with specified threads number, but some behaviour differs from -framework: -- `TBB` - User-defined parallel constructions will run with the same threads number, if - another is not specified. If later on user creates his own scheduler, OpenCV will use it. -- `OpenMP` - No special defined behaviour. -- `Concurrency` - If threads == 1, OpenCV will disable threading optimizations and run its - functions sequentially. -- `GCD` - Supports only values \<= 0. -- `C=` - No special defined behaviour. -@param nthreads Number of threads used by OpenCV. -@sa getNumThreads, getThreadNum - */ -CV_EXPORTS_W void setNumThreads(int nthreads); - -/** @brief Returns the number of threads used by OpenCV for parallel regions. - -Always returns 1 if OpenCV is built without threading support. - -The exact meaning of return value depends on the threading framework used by OpenCV library: -- `TBB` - The number of threads, that OpenCV will try to use for parallel regions. If there is - any tbb::thread_scheduler_init in user code conflicting with OpenCV, then function returns - default number of threads used by TBB library. -- `OpenMP` - An upper bound on the number of threads that could be used to form a new team. -- `Concurrency` - The number of threads, that OpenCV will try to use for parallel regions. -- `GCD` - Unsupported; returns the GCD thread pool limit (512) for compatibility. -- `C=` - The number of threads, that OpenCV will try to use for parallel regions, if before - called setNumThreads with threads \> 0, otherwise returns the number of logical CPUs, - available for the process. -@sa setNumThreads, getThreadNum - */ -CV_EXPORTS_W int getNumThreads(); - -/** @brief Returns the index of the currently executed thread within the current parallel region. Always -returns 0 if called outside of parallel region. - -@deprecated Current implementation doesn't corresponding to this documentation. - -The exact meaning of the return value depends on the threading framework used by OpenCV library: -- `TBB` - Unsupported with current 4.1 TBB release. Maybe will be supported in future. -- `OpenMP` - The thread number, within the current team, of the calling thread. -- `Concurrency` - An ID for the virtual processor that the current context is executing on (0 - for master thread and unique number for others, but not necessary 1,2,3,...). -- `GCD` - System calling thread's ID. Never returns 0 inside parallel region. -- `C=` - The index of the current parallel task. -@sa setNumThreads, getNumThreads - */ -CV_EXPORTS_W int getThreadNum(); - -/** @brief Returns full configuration time cmake output. - -Returned value is raw cmake output including version control system revision, compiler version, -compiler flags, enabled modules and third party libraries, etc. Output format depends on target -architecture. - */ -CV_EXPORTS_W const String& getBuildInformation(); - -/** @brief Returns library version string - -For example "3.4.1-dev". - -@sa getMajorVersion, getMinorVersion, getRevisionVersion -*/ -CV_EXPORTS_W String getVersionString(); - -/** @brief Returns major library version */ -CV_EXPORTS_W int getVersionMajor(); - -/** @brief Returns minor library version */ -CV_EXPORTS_W int getVersionMinor(); - -/** @brief Returns revision field of the library version */ -CV_EXPORTS_W int getVersionRevision(); - -/** @brief Returns the number of ticks. - -The function returns the number of ticks after the certain event (for example, when the machine was -turned on). It can be used to initialize RNG or to measure a function execution time by reading the -tick count before and after the function call. -@sa getTickFrequency, TickMeter - */ -CV_EXPORTS_W int64 getTickCount(); - -/** @brief Returns the number of ticks per second. - -The function returns the number of ticks per second. That is, the following code computes the -execution time in seconds: -@code - double t = (double)getTickCount(); - // do something ... - t = ((double)getTickCount() - t)/getTickFrequency(); -@endcode -@sa getTickCount, TickMeter - */ -CV_EXPORTS_W double getTickFrequency(); - -/** @brief a Class to measure passing time. - -The class computes passing time by counting the number of ticks per second. That is, the following code computes the -execution time in seconds: -@snippet snippets/core_various.cpp TickMeter_total - -It is also possible to compute the average time over multiple runs: -@snippet snippets/core_various.cpp TickMeter_average - -@sa getTickCount, getTickFrequency -*/ -class CV_EXPORTS_W TickMeter -{ -public: - //! the default constructor - CV_WRAP TickMeter() - { - reset(); - } - - //! starts counting ticks. - CV_WRAP void start() - { - startTime = cv::getTickCount(); - } - - //! stops counting ticks. - CV_WRAP void stop() - { - const int64 time = cv::getTickCount(); - if (startTime == 0) - return; - ++counter; - lastTime = time - startTime; - sumTime += lastTime; - startTime = 0; - } - - //! returns counted ticks. - CV_WRAP int64 getTimeTicks() const - { - return sumTime; - } - - //! returns passed time in microseconds. - CV_WRAP double getTimeMicro() const - { - return getTimeMilli()*1e3; - } - - //! returns passed time in milliseconds. - CV_WRAP double getTimeMilli() const - { - return getTimeSec()*1e3; - } - - //! returns passed time in seconds. - CV_WRAP double getTimeSec() const - { - return (double)getTimeTicks() / getTickFrequency(); - } - - //! returns counted ticks of the last iteration. - CV_WRAP int64 getLastTimeTicks() const - { - return lastTime; - } - - //! returns passed time of the last iteration in microseconds. - CV_WRAP double getLastTimeMicro() const - { - return getLastTimeMilli()*1e3; - } - - //! returns passed time of the last iteration in milliseconds. - CV_WRAP double getLastTimeMilli() const - { - return getLastTimeSec()*1e3; - } - - //! returns passed time of the last iteration in seconds. - CV_WRAP double getLastTimeSec() const - { - return (double)getLastTimeTicks() / getTickFrequency(); - } - - //! returns internal counter value. - CV_WRAP int64 getCounter() const - { - return counter; - } - - //! returns average FPS (frames per second) value. - CV_WRAP double getFPS() const - { - const double sec = getTimeSec(); - if (sec < DBL_EPSILON) - return 0.; - return counter / sec; - } - - //! returns average time in seconds - CV_WRAP double getAvgTimeSec() const - { - if (counter <= 0) - return 0.; - return getTimeSec() / counter; - } - - //! returns average time in milliseconds - CV_WRAP double getAvgTimeMilli() const - { - return getAvgTimeSec() * 1e3; - } - - //! resets internal values. - CV_WRAP void reset() - { - counter = 0; - sumTime = 0; - startTime = 0; - lastTime = 0; - } - -private: - int64 counter; - int64 sumTime; - int64 startTime; - int64 lastTime; -}; - -/** @brief output operator -@code -TickMeter tm; -tm.start(); -// do something ... -tm.stop(); -std::cout << tm; -@endcode -*/ - -static inline -std::ostream& operator << (std::ostream& out, const TickMeter& tm) -{ - return out << tm.getTimeSec() << "sec"; -} - -/** @brief Returns the number of CPU ticks. - -The function returns the current number of CPU ticks on some architectures (such as x86, x64, -PowerPC). On other platforms the function is equivalent to getTickCount. It can also be used for -very accurate time measurements, as well as for RNG initialization. Note that in case of multi-CPU -systems a thread, from which getCPUTickCount is called, can be suspended and resumed at another CPU -with its own counter. So, theoretically (and practically) the subsequent calls to the function do -not necessary return the monotonously increasing values. Also, since a modern CPU varies the CPU -frequency depending on the load, the number of CPU clocks spent in some code cannot be directly -converted to time units. Therefore, getTickCount is generally a preferable solution for measuring -execution time. - */ -CV_EXPORTS_W int64 getCPUTickCount(); - -/** @brief Returns true if the specified feature is supported by the host hardware. - -The function returns true if the host hardware supports the specified feature. When user calls -setUseOptimized(false), the subsequent calls to checkHardwareSupport() will return false until -setUseOptimized(true) is called. This way user can dynamically switch on and off the optimized code -in OpenCV. -@param feature The feature of interest, one of cv::CpuFeatures - */ -CV_EXPORTS_W bool checkHardwareSupport(int feature); - -/** @brief Returns feature name by ID - -Returns empty string if feature is not defined -*/ -CV_EXPORTS_W String getHardwareFeatureName(int feature); - -/** @brief Returns list of CPU features enabled during compilation. - -Returned value is a string containing space separated list of CPU features with following markers: - -- no markers - baseline features -- prefix `*` - features enabled in dispatcher -- suffix `?` - features enabled but not available in HW - -Example: `SSE SSE2 SSE3 *SSE4.1 *SSE4.2 *FP16 *AVX *AVX2 *AVX512-SKX?` -*/ -CV_EXPORTS_W std::string getCPUFeaturesLine(); - -/** @brief Returns the number of logical CPUs available for the process. - */ -CV_EXPORTS_W int getNumberOfCPUs(); - - -/** @brief Aligns a pointer to the specified number of bytes. - -The function returns the aligned pointer of the same type as the input pointer: -\f[\texttt{(_Tp*)(((size_t)ptr + n-1) & -n)}\f] -@param ptr Aligned pointer. -@param n Alignment size that must be a power of two. - */ -template static inline _Tp* alignPtr(_Tp* ptr, int n=(int)sizeof(_Tp)) -{ - CV_DbgAssert((n & (n - 1)) == 0); // n is a power of 2 - return (_Tp*)(((size_t)ptr + n-1) & -n); -} - -/** @brief Aligns a buffer size to the specified number of bytes. - -The function returns the minimum number that is greater than or equal to sz and is divisible by n : -\f[\texttt{(sz + n-1) & -n}\f] -@param sz Buffer size to align. -@param n Alignment size that must be a power of two. - */ -static inline size_t alignSize(size_t sz, int n) -{ - CV_DbgAssert((n & (n - 1)) == 0); // n is a power of 2 - return (sz + n-1) & -n; -} - -/** @brief Integer division with result round up. - -Use this function instead of `ceil((float)a / b)` expressions. - -@sa alignSize -*/ -static inline int divUp(int a, unsigned int b) -{ - CV_DbgAssert(a >= 0); - return (a + b - 1) / b; -} -/** @overload */ -static inline size_t divUp(size_t a, unsigned int b) -{ - return (a + b - 1) / b; -} - -/** @brief Round first value up to the nearest multiple of second value. - -Use this function instead of `ceil((float)a / b) * b` expressions. - -@sa divUp -*/ -static inline int roundUp(int a, unsigned int b) -{ - CV_DbgAssert(a >= 0); - return a + b - 1 - (a + b -1) % b; -} -/** @overload */ -static inline size_t roundUp(size_t a, unsigned int b) -{ - return a + b - 1 - (a + b - 1) % b; -} - -/** @brief Alignment check of passed values - -Usage: `isAligned(...)` - -@note Alignment(N) must be a power of 2 (2**k, 2^k) -*/ -template static inline -bool isAligned(const T& data) -{ - CV_StaticAssert((N & (N - 1)) == 0, ""); // power of 2 - return (((size_t)data) & (N - 1)) == 0; -} -/** @overload */ -template static inline -bool isAligned(const void* p1) -{ - return isAligned((size_t)p1); -} -/** @overload */ -template static inline -bool isAligned(const void* p1, const void* p2) -{ - return isAligned(((size_t)p1)|((size_t)p2)); -} -/** @overload */ -template static inline -bool isAligned(const void* p1, const void* p2, const void* p3) -{ - return isAligned(((size_t)p1)|((size_t)p2)|((size_t)p3)); -} -/** @overload */ -template static inline -bool isAligned(const void* p1, const void* p2, const void* p3, const void* p4) -{ - return isAligned(((size_t)p1)|((size_t)p2)|((size_t)p3)|((size_t)p4)); -} - -/*! @brief Flags that allow to midify some functions behavior. Used as set of flags. -*/ -enum AlgorithmHint { - ALGO_HINT_DEFAULT = 0, //!< Default algorithm behaviour defined during OpenCV build - ALGO_HINT_ACCURATE = 1, //!< Use generic portable implementation - ALGO_HINT_APPROX = 2, //!< Allow alternative approximations to get faster implementation. Behaviour and result depends on a platform -}; - -/*! @brief Returns AlgorithmHint defined during OpenCV compilation. Defines #ALGO_HINT_DEFAULT behavior. - */ -CV_EXPORTS_W AlgorithmHint getDefaultAlgorithmHint(); - -/** @brief Enables or disables the optimized code. - -The function can be used to dynamically turn on and off optimized dispatched code (code that uses SSE4.2, AVX/AVX2, -and other instructions on the platforms that support it). It sets a global flag that is further -checked by OpenCV functions. Since the flag is not checked in the inner OpenCV loops, it is only -safe to call the function on the very top level in your application where you can be sure that no -other OpenCV function is currently executed. - -By default, the optimized code is enabled unless you disable it in CMake. The current status can be -retrieved using useOptimized. -@param onoff The boolean flag specifying whether the optimized code should be used (onoff=true) -or not (onoff=false). - */ -CV_EXPORTS_W void setUseOptimized(bool onoff); - -/** @brief Returns the status of optimized code usage. - -The function returns true if the optimized code is enabled. Otherwise, it returns false. - */ -CV_EXPORTS_W bool useOptimized(); - -static inline size_t getElemSize(int type) { return (size_t)CV_ELEM_SIZE(type); } - -/////////////////////////////// Parallel Primitives ////////////////////////////////// - -/** @brief Base class for parallel data processors - -@ingroup core_parallel -*/ -class CV_EXPORTS ParallelLoopBody -{ -public: - virtual ~ParallelLoopBody(); - virtual void operator() (const Range& range) const = 0; -}; - -/** @brief Parallel data processor - -@ingroup core_parallel -*/ -CV_EXPORTS void parallel_for_(const Range& range, const ParallelLoopBody& body, double nstripes=-1.); - -//! @ingroup core_parallel -class ParallelLoopBodyLambdaWrapper : public ParallelLoopBody -{ -private: - std::function m_functor; -public: - inline - ParallelLoopBodyLambdaWrapper(std::function functor) - : m_functor(functor) - { - // nothing - } - - virtual void operator() (const cv::Range& range) const CV_OVERRIDE - { - m_functor(range); - } -}; - -//! @ingroup core_parallel -static inline -void parallel_for_(const Range& range, std::function functor, double nstripes=-1.) -{ - parallel_for_(range, ParallelLoopBodyLambdaWrapper(functor), nstripes); -} - - -/////////////////////////////// forEach method of cv::Mat //////////////////////////// -template inline -void Mat::forEach_impl(const Functor& operation) { - if (false) { - operation(*reinterpret_cast<_Tp*>(0), reinterpret_cast(0)); - // If your compiler fails in this line. - // Please check that your functor signature is - // (_Tp&, const int*) <- multi-dimensional - // or (_Tp&, void*) <- in case you don't need current idx. - } - - CV_Assert(!empty()); - CV_Assert(this->total() / this->size[this->dims - 1] <= INT_MAX); - const int LINES = static_cast(this->total() / this->size[this->dims - 1]); - - class PixelOperationWrapper :public ParallelLoopBody - { - public: - PixelOperationWrapper(Mat_<_Tp>* const frame, const Functor& _operation) - : mat(frame), op(_operation) {} - virtual ~PixelOperationWrapper(){} - // ! Overloaded virtual operator - // convert range call to row call. - virtual void operator()(const Range &range) const CV_OVERRIDE - { - const int DIMS = mat->dims; - const int COLS = mat->size[DIMS - 1]; - if (DIMS <= 2) { - for (int row = range.start; row < range.end; ++row) { - this->rowCall2(row, COLS); - } - } else { - std::vector idx(DIMS); /// idx is modified in this->rowCall - idx[DIMS - 2] = range.start - 1; - - for (int line_num = range.start; line_num < range.end; ++line_num) { - idx[DIMS - 2]++; - for (int i = DIMS - 2; i >= 0; --i) { - if (idx[i] >= mat->size[i]) { - idx[i - 1] += idx[i] / mat->size[i]; - idx[i] %= mat->size[i]; - continue; // carry-over; - } - else { - break; - } - } - this->rowCall(&idx[0], COLS, DIMS); - } - } - } - private: - Mat_<_Tp>* const mat; - const Functor op; - // ! Call operator for each elements in this row. - inline void rowCall(int* const idx, const int COLS, const int DIMS) const { - int &col = idx[DIMS - 1]; - col = 0; - _Tp* pixel = &(mat->template at<_Tp>(idx)); - - while (col < COLS) { - op(*pixel, const_cast(idx)); - pixel++; col++; - } - col = 0; - } - // ! Call operator for each elements in this row. 2d mat special version. - inline void rowCall2(const int row, const int COLS) const { - union Index{ - int body[2]; - operator const int*() const { - return reinterpret_cast(this); - } - int& operator[](const int i) { - return body[i]; - } - } idx = {{row, 0}}; - // Special union is needed to avoid - // "error: array subscript is above array bounds [-Werror=array-bounds]" - // when call the functor `op` such that access idx[3]. - - _Tp* pixel = &(mat->template at<_Tp>(idx)); - const _Tp* const pixel_end = pixel + COLS; - while(pixel < pixel_end) { - op(*pixel++, static_cast(idx)); - idx[1]++; - } - } - PixelOperationWrapper& operator=(const PixelOperationWrapper &) { - CV_Assert(false); - // We can not remove this implementation because Visual Studio warning C4822. - return *this; - } - }; - - parallel_for_(cv::Range(0, LINES), PixelOperationWrapper(reinterpret_cast*>(this), operation)); -} - -/////////////////////////// Synchronization Primitives /////////////////////////////// - -#if !defined(_M_CEE) -#ifndef OPENCV_DISABLE_THREAD_SUPPORT -typedef std::recursive_mutex Mutex; -typedef std::lock_guard AutoLock; -#else // OPENCV_DISABLE_THREAD_SUPPORT -// Custom (failing) implementation of `std::recursive_mutex`. -struct Mutex { - void lock(){ - CV_Error(cv::Error::StsNotImplemented, - "cv::Mutex is disabled by OPENCV_DISABLE_THREAD_SUPPORT=ON"); - } - void unlock(){ - CV_Error(cv::Error::StsNotImplemented, - "cv::Mutex is disabled by OPENCV_DISABLE_THREAD_SUPPORT=ON"); - } -}; -// Stub for cv::AutoLock when threads are disabled. -struct AutoLock { - AutoLock(Mutex &) { } -}; -#endif // OPENCV_DISABLE_THREAD_SUPPORT -#endif // !defined(_M_CEE) - - -/** @brief Designed for command line parsing - -The sample below demonstrates how to use CommandLineParser: -@code - CommandLineParser parser(argc, argv, keys); - parser.about("Application name v1.0.0"); - - if (parser.has("help")) - { - parser.printMessage(); - return 0; - } - - int N = parser.get("N"); - double fps = parser.get("fps"); - String path = parser.get("path"); - - use_time_stamp = parser.has("timestamp"); - - String img1 = parser.get(0); - String img2 = parser.get(1); - - int repeat = parser.get(2); - - if (!parser.check()) - { - parser.printErrors(); - return 0; - } -@endcode - -### Keys syntax - -The keys parameter is a string containing several blocks, each one is enclosed in curly braces and -describes one argument. Each argument contains three parts separated by the `|` symbol: - --# argument names is a list of option synonyms separated by standard space characters ' ' (to mark argument as positional, prefix it with the `@` symbol) --# default value will be used if the argument was not provided (can be empty) --# help message (can be empty) - -For example: - -@code{.cpp} - const String keys = - "{help h usage ? | | print this message }" - "{@image1 | | image1 for compare }" - "{@image2 || image2 for compare }" - "{@repeat |1 | number }" - "{path |. | path to file }" - "{fps | -1.0 | fps for output video }" - "{N count |100 | count of objects }" - "{ts timestamp | | use time stamp }" - ; -} -@endcode - -Note that there are no default values for `help` and `timestamp` so we can check their presence using the `has()` method. -Arguments with default values are considered to be always present. Use the `get()` method in these cases to check their -actual value instead. -Note that whitespace characters other than standard spaces are considered part of the string. -Additionally, leading and trailing standard spaces around the help messages are ignored. - -String keys like `get("@image1")` return the empty string `""` by default - even with an empty default value. -Use the special `` default value to enforce that the returned string must not be empty. (like in `get("@image2")`) - -### Usage - -For the described keys: - -@code{.sh} - # Good call (3 positional parameters: image1, image2 and repeat; N is 200, ts is true) - $ ./app -N=200 1.png 2.jpg 19 -ts - - # Bad call - $ ./app -fps=aaa - ERRORS: - Parameter 'fps': can not convert: [aaa] to [double] -@endcode - */ -class CV_EXPORTS CommandLineParser -{ -public: - - /** @brief Constructor - - Initializes command line parser object - - @param argc number of command line arguments (from main()) - @param argv array of command line arguments (from main()) - @param keys string describing acceptable command line parameters (see class description for syntax) - */ - CommandLineParser(int argc, const char* const argv[], const String& keys); - - /** @brief Copy constructor */ - CommandLineParser(const CommandLineParser& parser); - - /** @brief Assignment operator */ - CommandLineParser& operator = (const CommandLineParser& parser); - - /** @brief Destructor */ - ~CommandLineParser(); - - /** @brief Returns application path - - This method returns the path to the executable from the command line (`argv[0]`). - - For example, if the application has been started with such a command: - @code{.sh} - $ ./bin/my-executable - @endcode - this method will return `./bin`. - */ - String getPathToApplication() const; - - /** @brief Access arguments by name - - Returns argument converted to selected type. If the argument is not known or can not be - converted to selected type, the error flag is set (can be checked with @ref check). - - For example, define: - @code{.cpp} - String keys = "{N count||}"; - @endcode - - Call: - @code{.sh} - $ ./my-app -N=20 - # or - $ ./my-app --count=20 - @endcode - - Access: - @code{.cpp} - int N = parser.get("N"); - @endcode - - @param name name of the argument - @param space_delete remove spaces from the left and right of the string - @tparam T the argument will be converted to this type if possible - - @note You can access positional arguments by their `@`-prefixed name: - @code{.cpp} - parser.get("@image"); - @endcode - */ - template - T get(const String& name, bool space_delete = true) const - { - T val = T(); - getByName(name, space_delete, ParamType::type, (void*)&val); - return val; - } - - /** @brief Access positional arguments by index - - Returns argument converted to selected type. Indexes are counted from zero. - - For example, define: - @code{.cpp} - String keys = "{@arg1||}{@arg2||}" - @endcode - - Call: - @code{.sh} - ./my-app abc qwe - @endcode - - Access arguments: - @code{.cpp} - String val_1 = parser.get(0); // returns "abc", arg1 - String val_2 = parser.get(1); // returns "qwe", arg2 - @endcode - - @param index index of the argument - @param space_delete remove spaces from the left and right of the string - @tparam T the argument will be converted to this type if possible - */ - template - T get(int index, bool space_delete = true) const - { - T val = T(); - getByIndex(index, space_delete, ParamType::type, (void*)&val); - return val; - } - - /** @brief Check if field was provided in the command line - - @param name argument name to check - */ - bool has(const String& name) const; - - /** @brief Check for parsing errors - - Returns false if error occurred while accessing the parameters (bad conversion, missing arguments, - etc.). Call @ref printErrors to print error messages list. - */ - bool check() const; - - /** @brief Set the about message - - The about message will be shown when @ref printMessage is called, right before arguments table. - */ - void about(const String& message); - - /** @brief Print help message - - This method will print standard help message containing the about message and arguments description. - - @sa about - */ - void printMessage() const; - - /** @brief Print list of errors occurred - - @sa check - */ - void printErrors() const; - -protected: - void getByName(const String& name, bool space_delete, Param type, void* dst) const; - void getByIndex(int index, bool space_delete, Param type, void* dst) const; - - struct Impl; - Impl* impl; -}; - -//! @} core_utils - -//! @cond IGNORED - -/////////////////////////////// AutoBuffer implementation //////////////////////////////////////// - -template inline -AutoBuffer<_Tp, fixed_size>::AutoBuffer() -{ - ptr = buf; - sz = fixed_size; -} - -template inline -AutoBuffer<_Tp, fixed_size>::AutoBuffer(size_t _size) -{ - ptr = buf; - sz = fixed_size; - allocate(_size); -} - -template inline -AutoBuffer<_Tp, fixed_size>::AutoBuffer(const AutoBuffer<_Tp, fixed_size>& abuf ) -{ - ptr = buf; - sz = fixed_size; - allocate(abuf.size()); - for( size_t i = 0; i < sz; i++ ) - ptr[i] = abuf.ptr[i]; -} - -template inline AutoBuffer<_Tp, fixed_size>& -AutoBuffer<_Tp, fixed_size>::operator = (const AutoBuffer<_Tp, fixed_size>& abuf) -{ - if( this != &abuf ) - { - deallocate(); - allocate(abuf.size()); - for( size_t i = 0; i < sz; i++ ) - ptr[i] = abuf.ptr[i]; - } - return *this; -} - -template inline -AutoBuffer<_Tp, fixed_size>::~AutoBuffer() -{ deallocate(); } - -template inline void -AutoBuffer<_Tp, fixed_size>::allocate(size_t _size) -{ - if(_size <= sz) - { - sz = _size; - return; - } - deallocate(); - sz = _size; - if(_size > fixed_size) - { - ptr = new _Tp[_size]; - } -} - -template inline void -AutoBuffer<_Tp, fixed_size>::deallocate() -{ - if( ptr != buf ) - { - delete[] ptr; - ptr = buf; - sz = fixed_size; - } -} - -template inline void -AutoBuffer<_Tp, fixed_size>::resize(size_t _size) -{ - if(_size <= sz) - { - sz = _size; - return; - } - size_t i, prevsize = sz, minsize = MIN(prevsize, _size); - _Tp* prevptr = ptr; - - ptr = _size > fixed_size ? new _Tp[_size] : buf; - sz = _size; - - if( ptr != prevptr ) - for( i = 0; i < minsize; i++ ) - ptr[i] = prevptr[i]; - for( i = prevsize; i < _size; i++ ) - ptr[i] = _Tp(); - - if( prevptr != buf ) - delete[] prevptr; -} - -template inline size_t -AutoBuffer<_Tp, fixed_size>::size() const -{ return sz; } - -//! @endcond - - -// Basic Node class for tree building -template -class CV_EXPORTS Node -{ -public: - Node() - { - m_pParent = 0; - } - Node(OBJECT& payload) : m_payload(payload) - { - m_pParent = 0; - } - ~Node() - { - removeChilds(); - if (m_pParent) - { - int idx = m_pParent->findChild(this); - if (idx >= 0) - m_pParent->m_childs.erase(m_pParent->m_childs.begin() + idx); - } - } - - Node* findChild(OBJECT& payload) const - { - for(size_t i = 0; i < this->m_childs.size(); i++) - { - if(this->m_childs[i]->m_payload == payload) - return this->m_childs[i]; - } - return NULL; - } - - int findChild(Node *pNode) const - { - for (size_t i = 0; i < this->m_childs.size(); i++) - { - if(this->m_childs[i] == pNode) - return (int)i; - } - return -1; - } - - void addChild(Node *pNode) - { - if(!pNode) - return; - - CV_Assert(pNode->m_pParent == 0); - pNode->m_pParent = this; - this->m_childs.push_back(pNode); - } - - void removeChilds() - { - for(size_t i = 0; i < m_childs.size(); i++) - { - m_childs[i]->m_pParent = 0; // avoid excessive parent vector trimming - delete m_childs[i]; - } - m_childs.clear(); - } - - int getDepth() - { - int count = 0; - Node *pParent = m_pParent; - while(pParent) count++, pParent = pParent->m_pParent; - return count; - } - -public: - OBJECT m_payload; - Node* m_pParent; - std::vector*> m_childs; -}; - - -namespace samples { - -//! @addtogroup core_utils_samples -// This section describes utility functions for OpenCV samples. -// -// @note Implementation of these utilities is not thread-safe. -// -//! @{ - -/** @brief Try to find requested data file - -Search directories: - -1. Directories passed via `addSamplesDataSearchPath()` -2. OPENCV_SAMPLES_DATA_PATH_HINT environment variable -3. OPENCV_SAMPLES_DATA_PATH environment variable - If parameter value is not empty and nothing is found then stop searching. -4. Detects build/install path based on: - a. current working directory (CWD) - b. and/or binary module location (opencv_core/opencv_world, doesn't work with static linkage) -5. Scan `/{,data,samples/data}` directories if build directory is detected or the current directory is in source tree. -6. Scan `/share/OpenCV` directory if install directory is detected. - -@see cv::utils::findDataFile - -@param relative_path Relative path to data file -@param required Specify "file not found" handling. - If true, function prints information message and raises cv::Exception. - If false, function returns empty result -@param silentMode Disables messages -@return Returns path (absolute or relative to the current directory) or empty string if file is not found -*/ -CV_EXPORTS_W cv::String findFile(const cv::String& relative_path, bool required = true, bool silentMode = false); - -CV_EXPORTS_W cv::String findFileOrKeep(const cv::String& relative_path, bool silentMode = false); - -inline cv::String findFileOrKeep(const cv::String& relative_path, bool silentMode) -{ - cv::String res = findFile(relative_path, false, silentMode); - if (res.empty()) - return relative_path; - return res; -} - -/** @brief Override search data path by adding new search location - -Use this only to override default behavior -Passed paths are used in LIFO order. - -@param path Path to used samples data -*/ -CV_EXPORTS_W void addSamplesDataSearchPath(const cv::String& path); - -/** @brief Append samples search data sub directory - -General usage is to add OpenCV modules name (`/modules//samples/data` -> `/samples/data` + `modules//samples/data`). -Passed subdirectories are used in LIFO order. - -@param subdir samples data sub directory -*/ -CV_EXPORTS_W void addSamplesDataSearchSubDirectory(const cv::String& subdir); - -//! @} -} // namespace samples - -namespace utils { - -CV_EXPORTS int getThreadID(); - -} // namespace - -} //namespace cv - -#ifdef CV_COLLECT_IMPL_DATA -#include "opencv2/core/utils/instrumentation.hpp" -#else -/// Collect implementation data on OpenCV function call. Requires ENABLE_IMPL_COLLECTION build option. -#define CV_IMPL_ADD(impl) -#endif - -#endif //OPENCV_CORE_UTILITY_H +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_CORE_UTILITY_H +#define OPENCV_CORE_UTILITY_H + +#ifndef __cplusplus +# error utility.hpp header must be compiled as C++ +#endif + +#if defined(check) +# warning Detected Apple 'check' macro definition, it can cause build conflicts. Please, include this header before any Apple headers. +#endif + +#include "opencv2/core.hpp" +#include + +#include + +#if !defined(_M_CEE) +#include // std::mutex, std::lock_guard +#endif + +namespace cv +{ + +//! @addtogroup core_utils +//! @{ + +/** @brief Automatically Allocated Buffer Class + + The class is used for temporary buffers in functions and methods. + If a temporary buffer is usually small (a few K's of memory), + but its size depends on the parameters, it makes sense to create a small + fixed-size array on stack and use it if it's large enough. If the required buffer size + is larger than the fixed size, another buffer of sufficient size is allocated dynamically + and released after the processing. Therefore, in typical cases, when the buffer size is small, + there is no overhead associated with malloc()/free(). + At the same time, there is no limit on the size of processed data. + + This is what AutoBuffer does. The template takes 2 parameters - type of the buffer elements and + the number of stack-allocated elements. Here is how the class is used: + + \code + void my_func(const cv::Mat& m) + { + cv::AutoBuffer buf(1000); // create automatic buffer containing 1000 floats + + buf.allocate(m.rows); // if m.rows <= 1000, the pre-allocated buffer is used, + // otherwise the buffer of "m.rows" floats will be allocated + // dynamically and deallocated in cv::AutoBuffer destructor + ... + } + \endcode +*/ +#ifdef OPENCV_ENABLE_MEMORY_SANITIZER +template class AutoBuffer +#else +template class AutoBuffer +#endif +{ +public: + typedef _Tp value_type; + + //! the default constructor + AutoBuffer(); + //! constructor taking the real buffer size + explicit AutoBuffer(size_t _size); + + //! the copy constructor + AutoBuffer(const AutoBuffer<_Tp, fixed_size>& buf); + //! the assignment operator + AutoBuffer<_Tp, fixed_size>& operator = (const AutoBuffer<_Tp, fixed_size>& buf); + + //! destructor. calls deallocate() + ~AutoBuffer(); + + //! allocates the new buffer of size _size. if the _size is small enough, stack-allocated buffer is used + void allocate(size_t _size); + //! deallocates the buffer if it was dynamically allocated + void deallocate(); + //! resizes the buffer and preserves the content + void resize(size_t _size); + //! returns the current buffer size + size_t size() const; + //! returns pointer to the real buffer, stack-allocated or heap-allocated + inline _Tp* data() { return ptr; } + //! returns read-only pointer to the real buffer, stack-allocated or heap-allocated + inline const _Tp* data() const { return ptr; } + +#if !defined(OPENCV_DISABLE_DEPRECATED_COMPATIBILITY) // use to .data() calls instead + //! returns pointer to the real buffer, stack-allocated or heap-allocated + operator _Tp* () { return ptr; } + //! returns read-only pointer to the real buffer, stack-allocated or heap-allocated + operator const _Tp* () const { return ptr; } +#else + //! returns a reference to the element at specified location. No bounds checking is performed in Release builds. + inline _Tp& operator[] (size_t i) { CV_DbgCheckLT(i, sz, "out of range"); return ptr[i]; } + //! returns a reference to the element at specified location. No bounds checking is performed in Release builds. + inline const _Tp& operator[] (size_t i) const { CV_DbgCheckLT(i, sz, "out of range"); return ptr[i]; } +#endif + +protected: + //! pointer to the real buffer, can point to buf if the buffer is small enough + _Tp* ptr; + //! size of the real buffer + size_t sz; + //! pre-allocated buffer. At least 1 element to confirm C++ standard requirements + _Tp buf[(fixed_size > 0) ? fixed_size : 1]; +}; + +/** @brief Sets/resets the break-on-error mode. + +When the break-on-error mode is set, the default error handler issues a hardware exception, which +can make debugging more convenient. + +\return the previous state + */ +CV_EXPORTS bool setBreakOnError(bool flag); + +extern "C" typedef int (*ErrorCallback)( int status, const char* func_name, + const char* err_msg, const char* file_name, + int line, void* userdata ); + + +/** @brief Sets the new error handler and the optional user data. + + The function sets the new error handler, called from cv::error(). + + \param errCallback the new error handler. If NULL, the default error handler is used. + \param userdata the optional user data pointer, passed to the callback. + \param prevUserdata the optional output parameter where the previous user data pointer is stored + + \return the previous error handler +*/ +CV_EXPORTS ErrorCallback redirectError( ErrorCallback errCallback, void* userdata=0, void** prevUserdata=0); + +/** @brief Generates a unique temporary file name. + +This function generates a full, unique file path for a temporary file, +which can be used to create temporary files for various purposes. + +@param suffix (optional) The desired file extension or suffix for the temporary file (e.g., ".png", ".txt"). +If no suffix is provided (suffix = 0), the file will not have a specific extension. + +@return cv::String A full unique path for the temporary file. + +@note +- The function does not create the file, it only generates the name. +- The file name is unique for the system session. +- Works cross-platform (Windows, Linux, macOS). + */ +CV_EXPORTS String tempfile( const char* suffix = 0); + +/** @brief Searches for files matching the specified pattern in a directory. + +This function searches for files that match a given pattern (e.g., `*.jpg`) +in the specified directory. The search can be limited to the directory itself +or be recursive, including subdirectories. + +@param pattern The file search pattern, which can include wildcards like `*` +(for matching multiple characters) or `?` (for matching a single character). + +@param result Output vector where the file paths matching the search +pattern will be stored. +@param recursive (optional) Boolean flag indicating whether to search +subdirectories recursively. If true, the search will include all subdirectories. +The default value is `false`. + */ +CV_EXPORTS void glob(String pattern, std::vector& result, bool recursive = false); + +/** @brief OpenCV will try to set the number of threads for subsequent parallel regions. + +If threads == 1, OpenCV will disable threading optimizations and run all it's functions +sequentially. Passing threads \< 0 will reset threads number to system default. +The function is not thread-safe. It must not be called in parallel region or concurrent threads. + +OpenCV will try to run its functions with specified threads number, but some behaviour differs from +framework: +- `TBB` - User-defined parallel constructions will run with the same threads number, if + another is not specified. If later on user creates his own scheduler, OpenCV will use it. +- `OpenMP` - No special defined behaviour. +- `Concurrency` - If threads == 1, OpenCV will disable threading optimizations and run its + functions sequentially. +- `GCD` - Supports only values \<= 0. +- `C=` - No special defined behaviour. +@param nthreads Number of threads used by OpenCV. +@sa getNumThreads, getThreadNum + */ +CV_EXPORTS_W void setNumThreads(int nthreads); + +/** @brief Returns the number of threads used by OpenCV for parallel regions. + +Always returns 1 if OpenCV is built without threading support. + +The exact meaning of return value depends on the threading framework used by OpenCV library: +- `TBB` - The number of threads, that OpenCV will try to use for parallel regions. If there is + any tbb::thread_scheduler_init in user code conflicting with OpenCV, then function returns + default number of threads used by TBB library. +- `OpenMP` - An upper bound on the number of threads that could be used to form a new team. +- `Concurrency` - The number of threads, that OpenCV will try to use for parallel regions. +- `GCD` - Unsupported; returns the GCD thread pool limit (512) for compatibility. +- `C=` - The number of threads, that OpenCV will try to use for parallel regions, if before + called setNumThreads with threads \> 0, otherwise returns the number of logical CPUs, + available for the process. +@sa setNumThreads, getThreadNum + */ +CV_EXPORTS_W int getNumThreads(); + +/** @brief Returns the index of the currently executed thread within the current parallel region. Always +returns 0 if called outside of parallel region. + +@deprecated Current implementation doesn't corresponding to this documentation. + +The exact meaning of the return value depends on the threading framework used by OpenCV library: +- `TBB` - Unsupported with current 4.1 TBB release. Maybe will be supported in future. +- `OpenMP` - The thread number, within the current team, of the calling thread. +- `Concurrency` - An ID for the virtual processor that the current context is executing on (0 + for master thread and unique number for others, but not necessary 1,2,3,...). +- `GCD` - System calling thread's ID. Never returns 0 inside parallel region. +- `C=` - The index of the current parallel task. +@sa setNumThreads, getNumThreads + */ +CV_EXPORTS_W int getThreadNum(); + +/** @brief Returns full configuration time cmake output. + +Returned value is raw cmake output including version control system revision, compiler version, +compiler flags, enabled modules and third party libraries, etc. Output format depends on target +architecture. + */ +CV_EXPORTS_W const String& getBuildInformation(); + +/** @brief Returns library version string + +For example "3.4.1-dev". + +@sa getMajorVersion, getMinorVersion, getRevisionVersion +*/ +CV_EXPORTS_W String getVersionString(); + +/** @brief Returns major library version */ +CV_EXPORTS_W int getVersionMajor(); + +/** @brief Returns minor library version */ +CV_EXPORTS_W int getVersionMinor(); + +/** @brief Returns revision field of the library version */ +CV_EXPORTS_W int getVersionRevision(); + +/** @brief Returns the number of ticks. + +The function returns the number of ticks after the certain event (for example, when the machine was +turned on). It can be used to initialize RNG or to measure a function execution time by reading the +tick count before and after the function call. +@sa getTickFrequency, TickMeter + */ +CV_EXPORTS_W int64 getTickCount(); + +/** @brief Returns the number of ticks per second. + +The function returns the number of ticks per second. That is, the following code computes the +execution time in seconds: +@code + double t = (double)getTickCount(); + // do something ... + t = ((double)getTickCount() - t)/getTickFrequency(); +@endcode +@sa getTickCount, TickMeter + */ +CV_EXPORTS_W double getTickFrequency(); + +/** @brief a Class to measure passing time. + +The class computes passing time by counting the number of ticks per second. That is, the following code computes the +execution time in seconds: +@snippet snippets/core_various.cpp TickMeter_total + +It is also possible to compute the average time over multiple runs: +@snippet snippets/core_various.cpp TickMeter_average + +@sa getTickCount, getTickFrequency +*/ +class CV_EXPORTS_W TickMeter +{ +public: + //! the default constructor + CV_WRAP TickMeter() + { + reset(); + } + + //! starts counting ticks. + CV_WRAP void start() + { + startTime = cv::getTickCount(); + } + + //! stops counting ticks. + CV_WRAP void stop() + { + const int64 time = cv::getTickCount(); + if (startTime == 0) + return; + ++counter; + lastTime = time - startTime; + sumTime += lastTime; + startTime = 0; + } + + //! returns counted ticks. + CV_WRAP int64 getTimeTicks() const + { + return sumTime; + } + + //! returns passed time in microseconds. + CV_WRAP double getTimeMicro() const + { + return getTimeMilli()*1e3; + } + + //! returns passed time in milliseconds. + CV_WRAP double getTimeMilli() const + { + return getTimeSec()*1e3; + } + + //! returns passed time in seconds. + CV_WRAP double getTimeSec() const + { + return (double)getTimeTicks() / getTickFrequency(); + } + + //! returns counted ticks of the last iteration. + CV_WRAP int64 getLastTimeTicks() const + { + return lastTime; + } + + //! returns passed time of the last iteration in microseconds. + CV_WRAP double getLastTimeMicro() const + { + return getLastTimeMilli()*1e3; + } + + //! returns passed time of the last iteration in milliseconds. + CV_WRAP double getLastTimeMilli() const + { + return getLastTimeSec()*1e3; + } + + //! returns passed time of the last iteration in seconds. + CV_WRAP double getLastTimeSec() const + { + return (double)getLastTimeTicks() / getTickFrequency(); + } + + //! returns internal counter value. + CV_WRAP int64 getCounter() const + { + return counter; + } + + //! returns average FPS (frames per second) value. + CV_WRAP double getFPS() const + { + const double sec = getTimeSec(); + if (sec < DBL_EPSILON) + return 0.; + return counter / sec; + } + + //! returns average time in seconds + CV_WRAP double getAvgTimeSec() const + { + if (counter <= 0) + return 0.; + return getTimeSec() / counter; + } + + //! returns average time in milliseconds + CV_WRAP double getAvgTimeMilli() const + { + return getAvgTimeSec() * 1e3; + } + + //! resets internal values. + CV_WRAP void reset() + { + counter = 0; + sumTime = 0; + startTime = 0; + lastTime = 0; + } + +private: + int64 counter; + int64 sumTime; + int64 startTime; + int64 lastTime; +}; + +/** @brief output operator +@code +TickMeter tm; +tm.start(); +// do something ... +tm.stop(); +std::cout << tm; +@endcode +*/ + +static inline +std::ostream& operator << (std::ostream& out, const TickMeter& tm) +{ + return out << tm.getTimeSec() << "sec"; +} + +/** @brief Returns the number of CPU ticks. + +The function returns the current number of CPU ticks on some architectures (such as x86, x64, +PowerPC). On other platforms the function is equivalent to getTickCount. It can also be used for +very accurate time measurements, as well as for RNG initialization. Note that in case of multi-CPU +systems a thread, from which getCPUTickCount is called, can be suspended and resumed at another CPU +with its own counter. So, theoretically (and practically) the subsequent calls to the function do +not necessary return the monotonously increasing values. Also, since a modern CPU varies the CPU +frequency depending on the load, the number of CPU clocks spent in some code cannot be directly +converted to time units. Therefore, getTickCount is generally a preferable solution for measuring +execution time. + */ +CV_EXPORTS_W int64 getCPUTickCount(); + +/** @brief Returns true if the specified feature is supported by the host hardware. + +The function returns true if the host hardware supports the specified feature. When user calls +setUseOptimized(false), the subsequent calls to checkHardwareSupport() will return false until +setUseOptimized(true) is called. This way user can dynamically switch on and off the optimized code +in OpenCV. +@param feature The feature of interest, one of cv::CpuFeatures + */ +CV_EXPORTS_W bool checkHardwareSupport(int feature); + +/** @brief Returns feature name by ID + +Returns empty string if feature is not defined +*/ +CV_EXPORTS_W String getHardwareFeatureName(int feature); + +/** @brief Returns list of CPU features enabled during compilation. + +Returned value is a string containing space separated list of CPU features with following markers: + +- no markers - baseline features +- prefix `*` - features enabled in dispatcher +- suffix `?` - features enabled but not available in HW + +Example: `SSE SSE2 SSE3 *SSE4.1 *SSE4.2 *FP16 *AVX *AVX2 *AVX512-SKX?` +*/ +CV_EXPORTS_W std::string getCPUFeaturesLine(); + +/** @brief Returns the number of logical CPUs available for the process. + */ +CV_EXPORTS_W int getNumberOfCPUs(); + + +/** @brief Aligns a pointer to the specified number of bytes. + +The function returns the aligned pointer of the same type as the input pointer: +\f[\texttt{(_Tp*)(((size_t)ptr + n-1) & -n)}\f] +@param ptr Aligned pointer. +@param n Alignment size that must be a power of two. + */ +template static inline _Tp* alignPtr(_Tp* ptr, int n=(int)sizeof(_Tp)) +{ + CV_DbgAssert((n & (n - 1)) == 0); // n is a power of 2 + return (_Tp*)(((size_t)ptr + n-1) & -n); +} + +/** @brief Aligns a buffer size to the specified number of bytes. + +The function returns the minimum number that is greater than or equal to sz and is divisible by n : +\f[\texttt{(sz + n-1) & -n}\f] +@param sz Buffer size to align. +@param n Alignment size that must be a power of two. + */ +static inline size_t alignSize(size_t sz, int n) +{ + CV_DbgAssert((n & (n - 1)) == 0); // n is a power of 2 + return (sz + n-1) & -n; +} + +/** @brief Integer division with result round up. + +Use this function instead of `ceil((float)a / b)` expressions. + +@sa alignSize +*/ +static inline int divUp(int a, unsigned int b) +{ + CV_DbgAssert(a >= 0); + return (a + b - 1) / b; +} +/** @overload */ +static inline size_t divUp(size_t a, unsigned int b) +{ + return (a + b - 1) / b; +} + +/** @brief Round first value up to the nearest multiple of second value. + +Use this function instead of `ceil((float)a / b) * b` expressions. + +@sa divUp +*/ +static inline int roundUp(int a, unsigned int b) +{ + CV_DbgAssert(a >= 0); + return a + b - 1 - (a + b -1) % b; +} +/** @overload */ +static inline size_t roundUp(size_t a, unsigned int b) +{ + return a + b - 1 - (a + b - 1) % b; +} + +/** @brief Alignment check of passed values + +Usage: `isAligned(...)` + +@note Alignment(N) must be a power of 2 (2**k, 2^k) +*/ +template static inline +bool isAligned(const T& data) +{ + CV_StaticAssert((N & (N - 1)) == 0, ""); // power of 2 + return (((size_t)data) & (N - 1)) == 0; +} +/** @overload */ +template static inline +bool isAligned(const void* p1) +{ + return isAligned((size_t)p1); +} +/** @overload */ +template static inline +bool isAligned(const void* p1, const void* p2) +{ + return isAligned(((size_t)p1)|((size_t)p2)); +} +/** @overload */ +template static inline +bool isAligned(const void* p1, const void* p2, const void* p3) +{ + return isAligned(((size_t)p1)|((size_t)p2)|((size_t)p3)); +} +/** @overload */ +template static inline +bool isAligned(const void* p1, const void* p2, const void* p3, const void* p4) +{ + return isAligned(((size_t)p1)|((size_t)p2)|((size_t)p3)|((size_t)p4)); +} + +/*! @brief Flags that allow to midify some functions behavior. Used as set of flags. +*/ +enum AlgorithmHint { + ALGO_HINT_DEFAULT = 0, //!< Default algorithm behaviour defined during OpenCV build + ALGO_HINT_ACCURATE = 1, //!< Use generic portable implementation + ALGO_HINT_APPROX = 2, //!< Allow alternative approximations to get faster implementation. Behaviour and result depends on a platform +}; + +/*! @brief Returns AlgorithmHint defined during OpenCV compilation. Defines #ALGO_HINT_DEFAULT behavior. + */ +CV_EXPORTS_W AlgorithmHint getDefaultAlgorithmHint(); + +/** @brief Enables or disables the optimized code. + +The function can be used to dynamically turn on and off optimized dispatched code (code that uses SSE4.2, AVX/AVX2, +and other instructions on the platforms that support it). It sets a global flag that is further +checked by OpenCV functions. Since the flag is not checked in the inner OpenCV loops, it is only +safe to call the function on the very top level in your application where you can be sure that no +other OpenCV function is currently executed. + +By default, the optimized code is enabled unless you disable it in CMake. The current status can be +retrieved using useOptimized. +@param onoff The boolean flag specifying whether the optimized code should be used (onoff=true) +or not (onoff=false). + */ +CV_EXPORTS_W void setUseOptimized(bool onoff); + +/** @brief Returns the status of optimized code usage. + +The function returns true if the optimized code is enabled. Otherwise, it returns false. + */ +CV_EXPORTS_W bool useOptimized(); + +static inline size_t getElemSize(int type) { return (size_t)CV_ELEM_SIZE(type); } + +/////////////////////////////// Parallel Primitives ////////////////////////////////// + +/** @brief Base class for parallel data processors + +@ingroup core_parallel +*/ +class CV_EXPORTS ParallelLoopBody +{ +public: + virtual ~ParallelLoopBody(); + virtual void operator() (const Range& range) const = 0; +}; + +/** @brief Parallel data processor + +@ingroup core_parallel +*/ +CV_EXPORTS void parallel_for_(const Range& range, const ParallelLoopBody& body, double nstripes=-1.); + +//! @ingroup core_parallel +class ParallelLoopBodyLambdaWrapper : public ParallelLoopBody +{ +private: + std::function m_functor; +public: + inline + ParallelLoopBodyLambdaWrapper(std::function functor) + : m_functor(functor) + { + // nothing + } + + virtual void operator() (const cv::Range& range) const CV_OVERRIDE + { + m_functor(range); + } +}; + +//! @ingroup core_parallel +static inline +void parallel_for_(const Range& range, std::function functor, double nstripes=-1.) +{ + parallel_for_(range, ParallelLoopBodyLambdaWrapper(functor), nstripes); +} + + +/////////////////////////////// forEach method of cv::Mat //////////////////////////// +template inline +void Mat::forEach_impl(const Functor& operation) { + if (false) { + operation(*reinterpret_cast<_Tp*>(0), reinterpret_cast(0)); + // If your compiler fails in this line. + // Please check that your functor signature is + // (_Tp&, const int*) <- multi-dimensional + // or (_Tp&, void*) <- in case you don't need current idx. + } + + CV_Assert(!empty()); + CV_Assert(this->total() / this->size[this->dims - 1] <= INT_MAX); + const int LINES = static_cast(this->total() / this->size[this->dims - 1]); + + class PixelOperationWrapper :public ParallelLoopBody + { + public: + PixelOperationWrapper(Mat_<_Tp>* const frame, const Functor& _operation) + : mat(frame), op(_operation) {} + virtual ~PixelOperationWrapper(){} + // ! Overloaded virtual operator + // convert range call to row call. + virtual void operator()(const Range &range) const CV_OVERRIDE + { + const int DIMS = mat->dims; + const int COLS = mat->size[DIMS - 1]; + if (DIMS <= 2) { + for (int row = range.start; row < range.end; ++row) { + this->rowCall2(row, COLS); + } + } else { + std::vector idx(DIMS); /// idx is modified in this->rowCall + idx[DIMS - 2] = range.start - 1; + + for (int line_num = range.start; line_num < range.end; ++line_num) { + idx[DIMS - 2]++; + for (int i = DIMS - 2; i >= 0; --i) { + if (idx[i] >= mat->size[i]) { + idx[i - 1] += idx[i] / mat->size[i]; + idx[i] %= mat->size[i]; + continue; // carry-over; + } + else { + break; + } + } + this->rowCall(&idx[0], COLS, DIMS); + } + } + } + private: + Mat_<_Tp>* const mat; + const Functor op; + // ! Call operator for each elements in this row. + inline void rowCall(int* const idx, const int COLS, const int DIMS) const { + int &col = idx[DIMS - 1]; + col = 0; + _Tp* pixel = &(mat->template at<_Tp>(idx)); + + while (col < COLS) { + op(*pixel, const_cast(idx)); + pixel++; col++; + } + col = 0; + } + // ! Call operator for each elements in this row. 2d mat special version. + inline void rowCall2(const int row, const int COLS) const { + union Index{ + int body[2]; + operator const int*() const { + return reinterpret_cast(this); + } + int& operator[](const int i) { + return body[i]; + } + } idx = {{row, 0}}; + // Special union is needed to avoid + // "error: array subscript is above array bounds [-Werror=array-bounds]" + // when call the functor `op` such that access idx[3]. + + _Tp* pixel = &(mat->template at<_Tp>(idx)); + const _Tp* const pixel_end = pixel + COLS; + while(pixel < pixel_end) { + op(*pixel++, static_cast(idx)); + idx[1]++; + } + } + PixelOperationWrapper& operator=(const PixelOperationWrapper &) { + CV_Assert(false); + // We can not remove this implementation because Visual Studio warning C4822. + return *this; + } + }; + + parallel_for_(cv::Range(0, LINES), PixelOperationWrapper(reinterpret_cast*>(this), operation)); +} + +/////////////////////////// Synchronization Primitives /////////////////////////////// + +#if !defined(_M_CEE) +#ifndef OPENCV_DISABLE_THREAD_SUPPORT +typedef std::recursive_mutex Mutex; +typedef std::lock_guard AutoLock; +#else // OPENCV_DISABLE_THREAD_SUPPORT +// Custom (failing) implementation of `std::recursive_mutex`. +struct Mutex { + void lock(){ + CV_Error(cv::Error::StsNotImplemented, + "cv::Mutex is disabled by OPENCV_DISABLE_THREAD_SUPPORT=ON"); + } + void unlock(){ + CV_Error(cv::Error::StsNotImplemented, + "cv::Mutex is disabled by OPENCV_DISABLE_THREAD_SUPPORT=ON"); + } +}; +// Stub for cv::AutoLock when threads are disabled. +struct AutoLock { + AutoLock(Mutex &) { } +}; +#endif // OPENCV_DISABLE_THREAD_SUPPORT +#endif // !defined(_M_CEE) + + +/** @brief Designed for command line parsing + +The sample below demonstrates how to use CommandLineParser: +@code + CommandLineParser parser(argc, argv, keys); + parser.about("Application name v1.0.0"); + + if (parser.has("help")) + { + parser.printMessage(); + return 0; + } + + int N = parser.get("N"); + double fps = parser.get("fps"); + String path = parser.get("path"); + + use_time_stamp = parser.has("timestamp"); + + String img1 = parser.get(0); + String img2 = parser.get(1); + + int repeat = parser.get(2); + + if (!parser.check()) + { + parser.printErrors(); + return 0; + } +@endcode + +### Keys syntax + +The keys parameter is a string containing several blocks, each one is enclosed in curly braces and +describes one argument. Each argument contains three parts separated by the `|` symbol: + +-# argument names is a list of option synonyms separated by standard space characters ' ' (to mark argument as positional, prefix it with the `@` symbol) +-# default value will be used if the argument was not provided (can be empty) +-# help message (can be empty) + +For example: + +@code{.cpp} + const String keys = + "{help h usage ? | | print this message }" + "{@image1 | | image1 for compare }" + "{@image2 || image2 for compare }" + "{@repeat |1 | number }" + "{path |. | path to file }" + "{fps | -1.0 | fps for output video }" + "{N count |100 | count of objects }" + "{ts timestamp | | use time stamp }" + ; +} +@endcode + +Note that there are no default values for `help` and `timestamp` so we can check their presence using the `has()` method. +Arguments with default values are considered to be always present. Use the `get()` method in these cases to check their +actual value instead. +Note that whitespace characters other than standard spaces are considered part of the string. +Additionally, leading and trailing standard spaces around the help messages are ignored. + +String keys like `get("@image1")` return the empty string `""` by default - even with an empty default value. +Use the special `` default value to enforce that the returned string must not be empty. (like in `get("@image2")`) + +### Usage + +For the described keys: + +@code{.sh} + # Good call (3 positional parameters: image1, image2 and repeat; N is 200, ts is true) + $ ./app -N=200 1.png 2.jpg 19 -ts + + # Bad call + $ ./app -fps=aaa + ERRORS: + Parameter 'fps': can not convert: [aaa] to [double] +@endcode + */ +class CV_EXPORTS CommandLineParser +{ +public: + + /** @brief Constructor + + Initializes command line parser object + + @param argc number of command line arguments (from main()) + @param argv array of command line arguments (from main()) + @param keys string describing acceptable command line parameters (see class description for syntax) + */ + CommandLineParser(int argc, const char* const argv[], const String& keys); + + /** @brief Copy constructor */ + CommandLineParser(const CommandLineParser& parser); + + /** @brief Assignment operator */ + CommandLineParser& operator = (const CommandLineParser& parser); + + /** @brief Destructor */ + ~CommandLineParser(); + + /** @brief Returns application path + + This method returns the path to the executable from the command line (`argv[0]`). + + For example, if the application has been started with such a command: + @code{.sh} + $ ./bin/my-executable + @endcode + this method will return `./bin`. + */ + String getPathToApplication() const; + + /** @brief Access arguments by name + + Returns argument converted to selected type. If the argument is not known or can not be + converted to selected type, the error flag is set (can be checked with @ref check). + + For example, define: + @code{.cpp} + String keys = "{N count||}"; + @endcode + + Call: + @code{.sh} + $ ./my-app -N=20 + # or + $ ./my-app --count=20 + @endcode + + Access: + @code{.cpp} + int N = parser.get("N"); + @endcode + + @param name name of the argument + @param space_delete remove spaces from the left and right of the string + @tparam T the argument will be converted to this type if possible + + @note You can access positional arguments by their `@`-prefixed name: + @code{.cpp} + parser.get("@image"); + @endcode + */ + template + T get(const String& name, bool space_delete = true) const + { + T val = T(); + getByName(name, space_delete, ParamType::type, (void*)&val); + return val; + } + + /** @brief Access positional arguments by index + + Returns argument converted to selected type. Indexes are counted from zero. + + For example, define: + @code{.cpp} + String keys = "{@arg1||}{@arg2||}" + @endcode + + Call: + @code{.sh} + ./my-app abc qwe + @endcode + + Access arguments: + @code{.cpp} + String val_1 = parser.get(0); // returns "abc", arg1 + String val_2 = parser.get(1); // returns "qwe", arg2 + @endcode + + @param index index of the argument + @param space_delete remove spaces from the left and right of the string + @tparam T the argument will be converted to this type if possible + */ + template + T get(int index, bool space_delete = true) const + { + T val = T(); + getByIndex(index, space_delete, ParamType::type, (void*)&val); + return val; + } + + /** @brief Check if field was provided in the command line + + @param name argument name to check + */ + bool has(const String& name) const; + + /** @brief Check for parsing errors + + Returns false if error occurred while accessing the parameters (bad conversion, missing arguments, + etc.). Call @ref printErrors to print error messages list. + */ + bool check() const; + + /** @brief Set the about message + + The about message will be shown when @ref printMessage is called, right before arguments table. + */ + void about(const String& message); + + /** @brief Print help message + + This method will print standard help message containing the about message and arguments description. + + @sa about + */ + void printMessage() const; + + /** @brief Print list of errors occurred + + @sa check + */ + void printErrors() const; + +protected: + void getByName(const String& name, bool space_delete, Param type, void* dst) const; + void getByIndex(int index, bool space_delete, Param type, void* dst) const; + + struct Impl; + Impl* impl; +}; + +//! @} core_utils + +//! @cond IGNORED + +/////////////////////////////// AutoBuffer implementation //////////////////////////////////////// + +template inline +AutoBuffer<_Tp, fixed_size>::AutoBuffer() +{ + ptr = buf; + sz = fixed_size; +} + +template inline +AutoBuffer<_Tp, fixed_size>::AutoBuffer(size_t _size) +{ + ptr = buf; + sz = fixed_size; + allocate(_size); +} + +template inline +AutoBuffer<_Tp, fixed_size>::AutoBuffer(const AutoBuffer<_Tp, fixed_size>& abuf ) +{ + ptr = buf; + sz = fixed_size; + allocate(abuf.size()); + for( size_t i = 0; i < sz; i++ ) + ptr[i] = abuf.ptr[i]; +} + +template inline AutoBuffer<_Tp, fixed_size>& +AutoBuffer<_Tp, fixed_size>::operator = (const AutoBuffer<_Tp, fixed_size>& abuf) +{ + if( this != &abuf ) + { + deallocate(); + allocate(abuf.size()); + for( size_t i = 0; i < sz; i++ ) + ptr[i] = abuf.ptr[i]; + } + return *this; +} + +template inline +AutoBuffer<_Tp, fixed_size>::~AutoBuffer() +{ deallocate(); } + +template inline void +AutoBuffer<_Tp, fixed_size>::allocate(size_t _size) +{ + if(_size <= sz) + { + sz = _size; + return; + } + deallocate(); + sz = _size; + if(_size > fixed_size) + { + ptr = new _Tp[_size]; + } +} + +template inline void +AutoBuffer<_Tp, fixed_size>::deallocate() +{ + if( ptr != buf ) + { + delete[] ptr; + ptr = buf; + sz = fixed_size; + } +} + +template inline void +AutoBuffer<_Tp, fixed_size>::resize(size_t _size) +{ + if(_size <= sz) + { + sz = _size; + return; + } + size_t i, prevsize = sz, minsize = MIN(prevsize, _size); + _Tp* prevptr = ptr; + + ptr = _size > fixed_size ? new _Tp[_size] : buf; + sz = _size; + + if( ptr != prevptr ) + for( i = 0; i < minsize; i++ ) + ptr[i] = prevptr[i]; + for( i = prevsize; i < _size; i++ ) + ptr[i] = _Tp(); + + if( prevptr != buf ) + delete[] prevptr; +} + +template inline size_t +AutoBuffer<_Tp, fixed_size>::size() const +{ return sz; } + +//! @endcond + + +// Basic Node class for tree building +template +class CV_EXPORTS Node +{ +public: + Node() + { + m_pParent = 0; + } + Node(OBJECT& payload) : m_payload(payload) + { + m_pParent = 0; + } + ~Node() + { + removeChilds(); + if (m_pParent) + { + int idx = m_pParent->findChild(this); + if (idx >= 0) + m_pParent->m_childs.erase(m_pParent->m_childs.begin() + idx); + } + } + + Node* findChild(OBJECT& payload) const + { + for(size_t i = 0; i < this->m_childs.size(); i++) + { + if(this->m_childs[i]->m_payload == payload) + return this->m_childs[i]; + } + return NULL; + } + + int findChild(Node *pNode) const + { + for (size_t i = 0; i < this->m_childs.size(); i++) + { + if(this->m_childs[i] == pNode) + return (int)i; + } + return -1; + } + + void addChild(Node *pNode) + { + if(!pNode) + return; + + CV_Assert(pNode->m_pParent == 0); + pNode->m_pParent = this; + this->m_childs.push_back(pNode); + } + + void removeChilds() + { + for(size_t i = 0; i < m_childs.size(); i++) + { + m_childs[i]->m_pParent = 0; // avoid excessive parent vector trimming + delete m_childs[i]; + } + m_childs.clear(); + } + + int getDepth() + { + int count = 0; + Node *pParent = m_pParent; + while(pParent) count++, pParent = pParent->m_pParent; + return count; + } + +public: + OBJECT m_payload; + Node* m_pParent; + std::vector*> m_childs; +}; + + +namespace samples { + +//! @addtogroup core_utils_samples +// This section describes utility functions for OpenCV samples. +// +// @note Implementation of these utilities is not thread-safe. +// +//! @{ + +/** @brief Try to find requested data file + +Search directories: + +1. Directories passed via `addSamplesDataSearchPath()` +2. OPENCV_SAMPLES_DATA_PATH_HINT environment variable +3. OPENCV_SAMPLES_DATA_PATH environment variable + If parameter value is not empty and nothing is found then stop searching. +4. Detects build/install path based on: + a. current working directory (CWD) + b. and/or binary module location (opencv_core/opencv_world, doesn't work with static linkage) +5. Scan `/{,data,samples/data}` directories if build directory is detected or the current directory is in source tree. +6. Scan `/share/OpenCV` directory if install directory is detected. + +@see cv::utils::findDataFile + +@param relative_path Relative path to data file +@param required Specify "file not found" handling. + If true, function prints information message and raises cv::Exception. + If false, function returns empty result +@param silentMode Disables messages +@return Returns path (absolute or relative to the current directory) or empty string if file is not found +*/ +CV_EXPORTS_W cv::String findFile(const cv::String& relative_path, bool required = true, bool silentMode = false); + +CV_EXPORTS_W cv::String findFileOrKeep(const cv::String& relative_path, bool silentMode = false); + +inline cv::String findFileOrKeep(const cv::String& relative_path, bool silentMode) +{ + cv::String res = findFile(relative_path, false, silentMode); + if (res.empty()) + return relative_path; + return res; +} + +/** @brief Override search data path by adding new search location + +Use this only to override default behavior +Passed paths are used in LIFO order. + +@param path Path to used samples data +*/ +CV_EXPORTS_W void addSamplesDataSearchPath(const cv::String& path); + +/** @brief Append samples search data sub directory + +General usage is to add OpenCV modules name (`/modules//samples/data` -> `/samples/data` + `modules//samples/data`). +Passed subdirectories are used in LIFO order. + +@param subdir samples data sub directory +*/ +CV_EXPORTS_W void addSamplesDataSearchSubDirectory(const cv::String& subdir); + +//! @} +} // namespace samples + +namespace utils { + +CV_EXPORTS int getThreadID(); + +} // namespace + +} //namespace cv + +#ifdef CV_COLLECT_IMPL_DATA +#include "opencv2/core/utils/instrumentation.hpp" +#else +/// Collect implementation data on OpenCV function call. Requires ENABLE_IMPL_COLLECTION build option. +#define CV_IMPL_ADD(impl) +#endif + +#endif //OPENCV_CORE_UTILITY_H diff --git a/3rdParty/opencv-4.11.0/opencv2/core/utils/allocator_stats.hpp b/3rdParty/opencv-4.11.0/opencv2/core/utils/allocator_stats.hpp index 79e933820a..f0adb6fe0a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/utils/allocator_stats.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/utils/allocator_stats.hpp @@ -1,29 +1,29 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_ALLOCATOR_STATS_HPP -#define OPENCV_CORE_ALLOCATOR_STATS_HPP - -#include "../cvdef.h" - -namespace cv { namespace utils { - -class AllocatorStatisticsInterface -{ -protected: - AllocatorStatisticsInterface() {} - virtual ~AllocatorStatisticsInterface() {} -public: - virtual uint64_t getCurrentUsage() const = 0; - virtual uint64_t getTotalUsage() const = 0; - virtual uint64_t getNumberOfAllocations() const = 0; - virtual uint64_t getPeakUsage() const = 0; - - /** set peak usage = current usage */ - virtual void resetPeakUsage() = 0; -}; - -}} // namespace - -#endif // OPENCV_CORE_ALLOCATOR_STATS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_ALLOCATOR_STATS_HPP +#define OPENCV_CORE_ALLOCATOR_STATS_HPP + +#include "../cvdef.h" + +namespace cv { namespace utils { + +class AllocatorStatisticsInterface +{ +protected: + AllocatorStatisticsInterface() {} + virtual ~AllocatorStatisticsInterface() {} +public: + virtual uint64_t getCurrentUsage() const = 0; + virtual uint64_t getTotalUsage() const = 0; + virtual uint64_t getNumberOfAllocations() const = 0; + virtual uint64_t getPeakUsage() const = 0; + + /** set peak usage = current usage */ + virtual void resetPeakUsage() = 0; +}; + +}} // namespace + +#endif // OPENCV_CORE_ALLOCATOR_STATS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/utils/allocator_stats.impl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/utils/allocator_stats.impl.hpp index bbc6cf8979..99ceabc547 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/utils/allocator_stats.impl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/utils/allocator_stats.impl.hpp @@ -1,106 +1,106 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_ALLOCATOR_STATS_IMPL_HPP -#define OPENCV_CORE_ALLOCATOR_STATS_IMPL_HPP - -#include "./allocator_stats.hpp" - -//#define OPENCV_DISABLE_ALLOCATOR_STATS - -#include - -#ifndef OPENCV_ALLOCATOR_STATS_COUNTER_TYPE -#if defined(__GNUC__) && (\ - (defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ == 4) || \ - (defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4) && !defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8)) \ - ) -#define OPENCV_ALLOCATOR_STATS_COUNTER_TYPE int -#endif -#endif - -#ifndef OPENCV_ALLOCATOR_STATS_COUNTER_TYPE -#define OPENCV_ALLOCATOR_STATS_COUNTER_TYPE long long -#endif - -namespace cv { namespace utils { - -#ifdef CV__ALLOCATOR_STATS_LOG -namespace { -#endif - -class AllocatorStatistics : public AllocatorStatisticsInterface -{ -#ifdef OPENCV_DISABLE_ALLOCATOR_STATS - -public: - AllocatorStatistics() {} - ~AllocatorStatistics() CV_OVERRIDE {} - - uint64_t getCurrentUsage() const CV_OVERRIDE { return 0; } - uint64_t getTotalUsage() const CV_OVERRIDE { return 0; } - uint64_t getNumberOfAllocations() const CV_OVERRIDE { return 0; } - uint64_t getPeakUsage() const CV_OVERRIDE { return 0; } - - /** set peak usage = current usage */ - void resetPeakUsage() CV_OVERRIDE {}; - - void onAllocate(size_t /*sz*/) {} - void onFree(size_t /*sz*/) {} - -#else - -protected: - typedef OPENCV_ALLOCATOR_STATS_COUNTER_TYPE counter_t; - std::atomic curr, total, total_allocs, peak; -public: - AllocatorStatistics() {} - ~AllocatorStatistics() CV_OVERRIDE {} - - uint64_t getCurrentUsage() const CV_OVERRIDE { return (uint64_t)curr.load(); } - uint64_t getTotalUsage() const CV_OVERRIDE { return (uint64_t)total.load(); } - uint64_t getNumberOfAllocations() const CV_OVERRIDE { return (uint64_t)total_allocs.load(); } - uint64_t getPeakUsage() const CV_OVERRIDE { return (uint64_t)peak.load(); } - - /** set peak usage = current usage */ - void resetPeakUsage() CV_OVERRIDE { peak.store(curr.load()); } - - // Controller interface - void onAllocate(size_t sz) - { -#ifdef CV__ALLOCATOR_STATS_LOG - CV__ALLOCATOR_STATS_LOG(cv::format("allocate: %lld (curr=%lld)", (long long int)sz, (long long int)curr.load())); -#endif - - counter_t new_curr = curr.fetch_add((counter_t)sz) + (counter_t)sz; - - // peak = std::max((uint64_t)peak, new_curr); - auto prev_peak = peak.load(); - while (prev_peak < new_curr) - { - if (peak.compare_exchange_weak(prev_peak, new_curr)) - break; - } - // end of peak = max(...) - - total += (counter_t)sz; - total_allocs++; - } - void onFree(size_t sz) - { -#ifdef CV__ALLOCATOR_STATS_LOG - CV__ALLOCATOR_STATS_LOG(cv::format("free: %lld (curr=%lld)", (long long int)sz, (long long int)curr.load())); -#endif - curr -= (counter_t)sz; - } -#endif // OPENCV_DISABLE_ALLOCATOR_STATS -}; - -#ifdef CV__ALLOCATOR_STATS_LOG -} // namespace -#endif - -}} // namespace - -#endif // OPENCV_CORE_ALLOCATOR_STATS_IMPL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_ALLOCATOR_STATS_IMPL_HPP +#define OPENCV_CORE_ALLOCATOR_STATS_IMPL_HPP + +#include "./allocator_stats.hpp" + +//#define OPENCV_DISABLE_ALLOCATOR_STATS + +#include + +#ifndef OPENCV_ALLOCATOR_STATS_COUNTER_TYPE +#if defined(__GNUC__) && (\ + (defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ == 4) || \ + (defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4) && !defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8)) \ + ) +#define OPENCV_ALLOCATOR_STATS_COUNTER_TYPE int +#endif +#endif + +#ifndef OPENCV_ALLOCATOR_STATS_COUNTER_TYPE +#define OPENCV_ALLOCATOR_STATS_COUNTER_TYPE long long +#endif + +namespace cv { namespace utils { + +#ifdef CV__ALLOCATOR_STATS_LOG +namespace { +#endif + +class AllocatorStatistics : public AllocatorStatisticsInterface +{ +#ifdef OPENCV_DISABLE_ALLOCATOR_STATS + +public: + AllocatorStatistics() {} + ~AllocatorStatistics() CV_OVERRIDE {} + + uint64_t getCurrentUsage() const CV_OVERRIDE { return 0; } + uint64_t getTotalUsage() const CV_OVERRIDE { return 0; } + uint64_t getNumberOfAllocations() const CV_OVERRIDE { return 0; } + uint64_t getPeakUsage() const CV_OVERRIDE { return 0; } + + /** set peak usage = current usage */ + void resetPeakUsage() CV_OVERRIDE {}; + + void onAllocate(size_t /*sz*/) {} + void onFree(size_t /*sz*/) {} + +#else + +protected: + typedef OPENCV_ALLOCATOR_STATS_COUNTER_TYPE counter_t; + std::atomic curr, total, total_allocs, peak; +public: + AllocatorStatistics() {} + ~AllocatorStatistics() CV_OVERRIDE {} + + uint64_t getCurrentUsage() const CV_OVERRIDE { return (uint64_t)curr.load(); } + uint64_t getTotalUsage() const CV_OVERRIDE { return (uint64_t)total.load(); } + uint64_t getNumberOfAllocations() const CV_OVERRIDE { return (uint64_t)total_allocs.load(); } + uint64_t getPeakUsage() const CV_OVERRIDE { return (uint64_t)peak.load(); } + + /** set peak usage = current usage */ + void resetPeakUsage() CV_OVERRIDE { peak.store(curr.load()); } + + // Controller interface + void onAllocate(size_t sz) + { +#ifdef CV__ALLOCATOR_STATS_LOG + CV__ALLOCATOR_STATS_LOG(cv::format("allocate: %lld (curr=%lld)", (long long int)sz, (long long int)curr.load())); +#endif + + counter_t new_curr = curr.fetch_add((counter_t)sz) + (counter_t)sz; + + // peak = std::max((uint64_t)peak, new_curr); + auto prev_peak = peak.load(); + while (prev_peak < new_curr) + { + if (peak.compare_exchange_weak(prev_peak, new_curr)) + break; + } + // end of peak = max(...) + + total += (counter_t)sz; + total_allocs++; + } + void onFree(size_t sz) + { +#ifdef CV__ALLOCATOR_STATS_LOG + CV__ALLOCATOR_STATS_LOG(cv::format("free: %lld (curr=%lld)", (long long int)sz, (long long int)curr.load())); +#endif + curr -= (counter_t)sz; + } +#endif // OPENCV_DISABLE_ALLOCATOR_STATS +}; + +#ifdef CV__ALLOCATOR_STATS_LOG +} // namespace +#endif + +}} // namespace + +#endif // OPENCV_CORE_ALLOCATOR_STATS_IMPL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/utils/filesystem.hpp b/3rdParty/opencv-4.11.0/opencv2/core/utils/filesystem.hpp index 8619ae4d1a..93bc33aefd 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/utils/filesystem.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/utils/filesystem.hpp @@ -1,82 +1,82 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_UTILS_FILESYSTEM_HPP -#define OPENCV_UTILS_FILESYSTEM_HPP - -namespace cv { namespace utils { namespace fs { - - -CV_EXPORTS bool exists(const cv::String& path); -CV_EXPORTS bool isDirectory(const cv::String& path); - -CV_EXPORTS void remove_all(const cv::String& path); - - -CV_EXPORTS cv::String getcwd(); - -/** @brief Converts path p to a canonical absolute path - * Symlinks are processed if there is support for them on running platform. - * - * @param path input path. Target file/directory should exist. - */ -CV_EXPORTS cv::String canonical(const cv::String& path); - -/** Join path components */ -CV_EXPORTS cv::String join(const cv::String& base, const cv::String& path); - -/** Get parent directory */ -CV_EXPORTS cv::String getParent(const cv::String &path); -CV_EXPORTS std::wstring getParent(const std::wstring& path); - -/** - * Generate a list of all files that match the globbing pattern. - * - * Result entries are prefixed by base directory path. - * - * @param directory base directory - * @param pattern filter pattern (based on '*'/'?' symbols). Use empty string to disable filtering and return all results - * @param[out] result result of globing. - * @param recursive scan nested directories too - * @param includeDirectories include directories into results list - */ -CV_EXPORTS void glob(const cv::String& directory, const cv::String& pattern, - CV_OUT std::vector& result, - bool recursive = false, bool includeDirectories = false); - -/** - * Generate a list of all files that match the globbing pattern. - * - * @param directory base directory - * @param pattern filter pattern (based on '*'/'?' symbols). Use empty string to disable filtering and return all results - * @param[out] result globbing result with relative paths from base directory - * @param recursive scan nested directories too - * @param includeDirectories include directories into results list - */ -CV_EXPORTS void glob_relative(const cv::String& directory, const cv::String& pattern, - CV_OUT std::vector& result, - bool recursive = false, bool includeDirectories = false); - - -CV_EXPORTS bool createDirectory(const cv::String& path); -CV_EXPORTS bool createDirectories(const cv::String& path); - -#if defined(__OPENCV_BUILD) || defined(BUILD_PLUGIN) -// TODO -//CV_EXPORTS cv::String getTempDirectory(); - -/** - * @brief Returns directory to store OpenCV cache files - * Create sub-directory in common OpenCV cache directory if it doesn't exist. - * @param sub_directory_name name of sub-directory. NULL or "" value asks to return root cache directory. - * @param configuration_name optional name of configuration parameter name which overrides default behavior. - * @return Path to cache directory. Returns empty string if cache directories support is not available. Returns "disabled" if cache disabled by user. - */ -CV_EXPORTS cv::String getCacheDirectory(const char* sub_directory_name, const char* configuration_name = NULL); - -#endif - -}}} // namespace - -#endif // OPENCV_UTILS_FILESYSTEM_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_UTILS_FILESYSTEM_HPP +#define OPENCV_UTILS_FILESYSTEM_HPP + +namespace cv { namespace utils { namespace fs { + + +CV_EXPORTS bool exists(const cv::String& path); +CV_EXPORTS bool isDirectory(const cv::String& path); + +CV_EXPORTS void remove_all(const cv::String& path); + + +CV_EXPORTS cv::String getcwd(); + +/** @brief Converts path p to a canonical absolute path + * Symlinks are processed if there is support for them on running platform. + * + * @param path input path. Target file/directory should exist. + */ +CV_EXPORTS cv::String canonical(const cv::String& path); + +/** Join path components */ +CV_EXPORTS cv::String join(const cv::String& base, const cv::String& path); + +/** Get parent directory */ +CV_EXPORTS cv::String getParent(const cv::String &path); +CV_EXPORTS std::wstring getParent(const std::wstring& path); + +/** + * Generate a list of all files that match the globbing pattern. + * + * Result entries are prefixed by base directory path. + * + * @param directory base directory + * @param pattern filter pattern (based on '*'/'?' symbols). Use empty string to disable filtering and return all results + * @param[out] result result of globing. + * @param recursive scan nested directories too + * @param includeDirectories include directories into results list + */ +CV_EXPORTS void glob(const cv::String& directory, const cv::String& pattern, + CV_OUT std::vector& result, + bool recursive = false, bool includeDirectories = false); + +/** + * Generate a list of all files that match the globbing pattern. + * + * @param directory base directory + * @param pattern filter pattern (based on '*'/'?' symbols). Use empty string to disable filtering and return all results + * @param[out] result globbing result with relative paths from base directory + * @param recursive scan nested directories too + * @param includeDirectories include directories into results list + */ +CV_EXPORTS void glob_relative(const cv::String& directory, const cv::String& pattern, + CV_OUT std::vector& result, + bool recursive = false, bool includeDirectories = false); + + +CV_EXPORTS bool createDirectory(const cv::String& path); +CV_EXPORTS bool createDirectories(const cv::String& path); + +#if defined(__OPENCV_BUILD) || defined(BUILD_PLUGIN) +// TODO +//CV_EXPORTS cv::String getTempDirectory(); + +/** + * @brief Returns directory to store OpenCV cache files + * Create sub-directory in common OpenCV cache directory if it doesn't exist. + * @param sub_directory_name name of sub-directory. NULL or "" value asks to return root cache directory. + * @param configuration_name optional name of configuration parameter name which overrides default behavior. + * @return Path to cache directory. Returns empty string if cache directories support is not available. Returns "disabled" if cache disabled by user. + */ +CV_EXPORTS cv::String getCacheDirectory(const char* sub_directory_name, const char* configuration_name = NULL); + +#endif + +}}} // namespace + +#endif // OPENCV_UTILS_FILESYSTEM_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/utils/fp_control_utils.hpp b/3rdParty/opencv-4.11.0/opencv2/core/utils/fp_control_utils.hpp index 930bc5d367..2ab87f6c87 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/utils/fp_control_utils.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/utils/fp_control_utils.hpp @@ -1,69 +1,69 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_FP_CONTROL_UTILS_HPP -#define OPENCV_CORE_FP_CONTROL_UTILS_HPP - -namespace cv { - -namespace details { - -struct FPDenormalsModeState -{ - uint32_t reserved[16]; // 64-bytes -}; // FPDenormalsModeState - -CV_EXPORTS void setFPDenormalsIgnoreHint(bool ignore, CV_OUT FPDenormalsModeState& state); -CV_EXPORTS int saveFPDenormalsState(CV_OUT FPDenormalsModeState& state); -CV_EXPORTS bool restoreFPDenormalsState(const FPDenormalsModeState& state); - -class FPDenormalsIgnoreHintScope -{ -public: - inline explicit FPDenormalsIgnoreHintScope(bool ignore = true) - { - details::setFPDenormalsIgnoreHint(ignore, saved_state); - } - - inline explicit FPDenormalsIgnoreHintScope(const FPDenormalsModeState& state) - { - details::saveFPDenormalsState(saved_state); - details::restoreFPDenormalsState(state); - } - - inline ~FPDenormalsIgnoreHintScope() - { - details::restoreFPDenormalsState(saved_state); - } - -protected: - FPDenormalsModeState saved_state; -}; // FPDenormalsIgnoreHintScope - -class FPDenormalsIgnoreHintScopeNOOP -{ -public: - inline FPDenormalsIgnoreHintScopeNOOP(bool ignore = true) { CV_UNUSED(ignore); } - inline FPDenormalsIgnoreHintScopeNOOP(const FPDenormalsModeState& state) { CV_UNUSED(state); } - inline ~FPDenormalsIgnoreHintScopeNOOP() { } -}; // FPDenormalsIgnoreHintScopeNOOP - -} // namespace details - - -// Should depend on target compilation architecture only -// Note: previously added archs should NOT be removed to preserve ABI compatibility -#if defined(OPENCV_SUPPORTS_FP_DENORMALS_HINT) - // preserve configuration overloading through ports -#elif defined(__i386__) || defined(__x86_64__) || defined(_M_X64) || defined(_X86_) -typedef details::FPDenormalsIgnoreHintScope FPDenormalsIgnoreHintScope; -#define OPENCV_SUPPORTS_FP_DENORMALS_HINT 1 -#else -#define OPENCV_SUPPORTS_FP_DENORMALS_HINT 0 -typedef details::FPDenormalsIgnoreHintScopeNOOP FPDenormalsIgnoreHintScope; -#endif - -} // namespace cv - -#endif // OPENCV_CORE_FP_CONTROL_UTILS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_FP_CONTROL_UTILS_HPP +#define OPENCV_CORE_FP_CONTROL_UTILS_HPP + +namespace cv { + +namespace details { + +struct FPDenormalsModeState +{ + uint32_t reserved[16]; // 64-bytes +}; // FPDenormalsModeState + +CV_EXPORTS void setFPDenormalsIgnoreHint(bool ignore, CV_OUT FPDenormalsModeState& state); +CV_EXPORTS int saveFPDenormalsState(CV_OUT FPDenormalsModeState& state); +CV_EXPORTS bool restoreFPDenormalsState(const FPDenormalsModeState& state); + +class FPDenormalsIgnoreHintScope +{ +public: + inline explicit FPDenormalsIgnoreHintScope(bool ignore = true) + { + details::setFPDenormalsIgnoreHint(ignore, saved_state); + } + + inline explicit FPDenormalsIgnoreHintScope(const FPDenormalsModeState& state) + { + details::saveFPDenormalsState(saved_state); + details::restoreFPDenormalsState(state); + } + + inline ~FPDenormalsIgnoreHintScope() + { + details::restoreFPDenormalsState(saved_state); + } + +protected: + FPDenormalsModeState saved_state; +}; // FPDenormalsIgnoreHintScope + +class FPDenormalsIgnoreHintScopeNOOP +{ +public: + inline FPDenormalsIgnoreHintScopeNOOP(bool ignore = true) { CV_UNUSED(ignore); } + inline FPDenormalsIgnoreHintScopeNOOP(const FPDenormalsModeState& state) { CV_UNUSED(state); } + inline ~FPDenormalsIgnoreHintScopeNOOP() { } +}; // FPDenormalsIgnoreHintScopeNOOP + +} // namespace details + + +// Should depend on target compilation architecture only +// Note: previously added archs should NOT be removed to preserve ABI compatibility +#if defined(OPENCV_SUPPORTS_FP_DENORMALS_HINT) + // preserve configuration overloading through ports +#elif defined(__i386__) || defined(__x86_64__) || defined(_M_X64) || defined(_X86_) +typedef details::FPDenormalsIgnoreHintScope FPDenormalsIgnoreHintScope; +#define OPENCV_SUPPORTS_FP_DENORMALS_HINT 1 +#else +#define OPENCV_SUPPORTS_FP_DENORMALS_HINT 0 +typedef details::FPDenormalsIgnoreHintScopeNOOP FPDenormalsIgnoreHintScope; +#endif + +} // namespace cv + +#endif // OPENCV_CORE_FP_CONTROL_UTILS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/utils/instrumentation.hpp b/3rdParty/opencv-4.11.0/opencv2/core/utils/instrumentation.hpp index 3639867080..ef8ed40b11 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/utils/instrumentation.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/utils/instrumentation.hpp @@ -1,125 +1,125 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_UTILS_INSTR_HPP -#define OPENCV_UTILS_INSTR_HPP - -#include -#include - -namespace cv { - -//! @addtogroup core_utils -//! @{ - -#ifdef CV_COLLECT_IMPL_DATA -CV_EXPORTS void setImpl(int flags); // set implementation flags and reset storage arrays -CV_EXPORTS void addImpl(int flag, const char* func = 0); // add implementation and function name to storage arrays -// Get stored implementation flags and functions names arrays -// Each implementation entry correspond to function name entry, so you can find which implementation was executed in which function -CV_EXPORTS int getImpl(std::vector &impl, std::vector &funName); - -CV_EXPORTS bool useCollection(); // return implementation collection state -CV_EXPORTS void setUseCollection(bool flag); // set implementation collection state - -#define CV_IMPL_PLAIN 0x01 // native CPU OpenCV implementation -#define CV_IMPL_OCL 0x02 // OpenCL implementation -#define CV_IMPL_IPP 0x04 // IPP implementation -#define CV_IMPL_MT 0x10 // multithreaded implementation - -#undef CV_IMPL_ADD -#define CV_IMPL_ADD(impl) \ - if(cv::useCollection()) \ - { \ - cv::addImpl(impl, CV_Func); \ - } -#endif - -// Instrumentation external interface -namespace instr -{ - -#if !defined OPENCV_ABI_CHECK - -enum TYPE -{ - TYPE_GENERAL = 0, // OpenCV API function, e.g. exported function - TYPE_MARKER, // Information marker - TYPE_WRAPPER, // Wrapper function for implementation - TYPE_FUN, // Simple function call -}; - -enum IMPL -{ - IMPL_PLAIN = 0, - IMPL_IPP, - IMPL_OPENCL, -}; - -struct NodeDataTls -{ - NodeDataTls() - { - m_ticksTotal = 0; - } - uint64 m_ticksTotal; -}; - -class CV_EXPORTS NodeData -{ -public: - NodeData(const char* funName = 0, const char* fileName = NULL, int lineNum = 0, void* retAddress = NULL, bool alwaysExpand = false, cv::instr::TYPE instrType = TYPE_GENERAL, cv::instr::IMPL implType = IMPL_PLAIN); - NodeData(NodeData &ref); - ~NodeData(); - NodeData& operator=(const NodeData&); - - cv::String m_funName; - cv::instr::TYPE m_instrType; - cv::instr::IMPL m_implType; - const char* m_fileName; - int m_lineNum; - void* m_retAddress; - bool m_alwaysExpand; - bool m_funError; - - volatile int m_counter; - volatile uint64 m_ticksTotal; - TLSDataAccumulator m_tls; - int m_threads; - - // No synchronization - double getTotalMs() const { return ((double)m_ticksTotal / cv::getTickFrequency()) * 1000; } - double getMeanMs() const { return (((double)m_ticksTotal/m_counter) / cv::getTickFrequency()) * 1000; } -}; -bool operator==(const NodeData& lhs, const NodeData& rhs); - -typedef Node InstrNode; - -CV_EXPORTS InstrNode* getTrace(); - -#endif // !defined OPENCV_ABI_CHECK - - -CV_EXPORTS bool useInstrumentation(); -CV_EXPORTS void setUseInstrumentation(bool flag); -CV_EXPORTS void resetTrace(); - -enum FLAGS -{ - FLAGS_NONE = 0, - FLAGS_MAPPING = 0x01, - FLAGS_EXPAND_SAME_NAMES = 0x02, -}; - -CV_EXPORTS void setFlags(FLAGS modeFlags); -static inline void setFlags(int modeFlags) { setFlags((FLAGS)modeFlags); } -CV_EXPORTS FLAGS getFlags(); - -} // namespace instr - -//! @} - -} // namespace - -#endif // OPENCV_UTILS_TLS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_UTILS_INSTR_HPP +#define OPENCV_UTILS_INSTR_HPP + +#include +#include + +namespace cv { + +//! @addtogroup core_utils +//! @{ + +#ifdef CV_COLLECT_IMPL_DATA +CV_EXPORTS void setImpl(int flags); // set implementation flags and reset storage arrays +CV_EXPORTS void addImpl(int flag, const char* func = 0); // add implementation and function name to storage arrays +// Get stored implementation flags and functions names arrays +// Each implementation entry correspond to function name entry, so you can find which implementation was executed in which function +CV_EXPORTS int getImpl(std::vector &impl, std::vector &funName); + +CV_EXPORTS bool useCollection(); // return implementation collection state +CV_EXPORTS void setUseCollection(bool flag); // set implementation collection state + +#define CV_IMPL_PLAIN 0x01 // native CPU OpenCV implementation +#define CV_IMPL_OCL 0x02 // OpenCL implementation +#define CV_IMPL_IPP 0x04 // IPP implementation +#define CV_IMPL_MT 0x10 // multithreaded implementation + +#undef CV_IMPL_ADD +#define CV_IMPL_ADD(impl) \ + if(cv::useCollection()) \ + { \ + cv::addImpl(impl, CV_Func); \ + } +#endif + +// Instrumentation external interface +namespace instr +{ + +#if !defined OPENCV_ABI_CHECK + +enum TYPE +{ + TYPE_GENERAL = 0, // OpenCV API function, e.g. exported function + TYPE_MARKER, // Information marker + TYPE_WRAPPER, // Wrapper function for implementation + TYPE_FUN, // Simple function call +}; + +enum IMPL +{ + IMPL_PLAIN = 0, + IMPL_IPP, + IMPL_OPENCL, +}; + +struct NodeDataTls +{ + NodeDataTls() + { + m_ticksTotal = 0; + } + uint64 m_ticksTotal; +}; + +class CV_EXPORTS NodeData +{ +public: + NodeData(const char* funName = 0, const char* fileName = NULL, int lineNum = 0, void* retAddress = NULL, bool alwaysExpand = false, cv::instr::TYPE instrType = TYPE_GENERAL, cv::instr::IMPL implType = IMPL_PLAIN); + NodeData(NodeData &ref); + ~NodeData(); + NodeData& operator=(const NodeData&); + + cv::String m_funName; + cv::instr::TYPE m_instrType; + cv::instr::IMPL m_implType; + const char* m_fileName; + int m_lineNum; + void* m_retAddress; + bool m_alwaysExpand; + bool m_funError; + + volatile int m_counter; + volatile uint64 m_ticksTotal; + TLSDataAccumulator m_tls; + int m_threads; + + // No synchronization + double getTotalMs() const { return ((double)m_ticksTotal / cv::getTickFrequency()) * 1000; } + double getMeanMs() const { return (((double)m_ticksTotal/m_counter) / cv::getTickFrequency()) * 1000; } +}; +bool operator==(const NodeData& lhs, const NodeData& rhs); + +typedef Node InstrNode; + +CV_EXPORTS InstrNode* getTrace(); + +#endif // !defined OPENCV_ABI_CHECK + + +CV_EXPORTS bool useInstrumentation(); +CV_EXPORTS void setUseInstrumentation(bool flag); +CV_EXPORTS void resetTrace(); + +enum FLAGS +{ + FLAGS_NONE = 0, + FLAGS_MAPPING = 0x01, + FLAGS_EXPAND_SAME_NAMES = 0x02, +}; + +CV_EXPORTS void setFlags(FLAGS modeFlags); +static inline void setFlags(int modeFlags) { setFlags((FLAGS)modeFlags); } +CV_EXPORTS FLAGS getFlags(); + +} // namespace instr + +//! @} + +} // namespace + +#endif // OPENCV_UTILS_TLS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/utils/logger.defines.hpp b/3rdParty/opencv-4.11.0/opencv2/core/utils/logger.defines.hpp index 7d73f02b66..86ecdc0bd5 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/utils/logger.defines.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/utils/logger.defines.hpp @@ -1,42 +1,42 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_LOGGER_DEFINES_HPP -#define OPENCV_LOGGER_DEFINES_HPP - -//! @addtogroup core_logging -//! @{ - -// Supported logging levels and their semantic -#define CV_LOG_LEVEL_SILENT 0 //!< for using in setLogLevel() call -#define CV_LOG_LEVEL_FATAL 1 //!< Fatal (critical) error (unrecoverable internal error) -#define CV_LOG_LEVEL_ERROR 2 //!< Error message -#define CV_LOG_LEVEL_WARN 3 //!< Warning message -#define CV_LOG_LEVEL_INFO 4 //!< Info message -#define CV_LOG_LEVEL_DEBUG 5 //!< Debug message. Disabled in the "Release" build. -#define CV_LOG_LEVEL_VERBOSE 6 //!< Verbose (trace) messages. Requires verbosity level. Disabled in the "Release" build. - -namespace cv { -namespace utils { -namespace logging { - -//! Supported logging levels and their semantic -enum LogLevel { - LOG_LEVEL_SILENT = 0, //!< for using in setLogVevel() call - LOG_LEVEL_FATAL = 1, //!< Fatal (critical) error (unrecoverable internal error) - LOG_LEVEL_ERROR = 2, //!< Error message - LOG_LEVEL_WARNING = 3, //!< Warning message - LOG_LEVEL_INFO = 4, //!< Info message - LOG_LEVEL_DEBUG = 5, //!< Debug message. Disabled in the "Release" build. - LOG_LEVEL_VERBOSE = 6, //!< Verbose (trace) messages. Requires verbosity level. Disabled in the "Release" build. -#ifndef CV_DOXYGEN - ENUM_LOG_LEVEL_FORCE_INT = INT_MAX -#endif -}; - -}}} // namespace - -//! @} - -#endif // OPENCV_LOGGER_DEFINES_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_LOGGER_DEFINES_HPP +#define OPENCV_LOGGER_DEFINES_HPP + +//! @addtogroup core_logging +//! @{ + +// Supported logging levels and their semantic +#define CV_LOG_LEVEL_SILENT 0 //!< for using in setLogLevel() call +#define CV_LOG_LEVEL_FATAL 1 //!< Fatal (critical) error (unrecoverable internal error) +#define CV_LOG_LEVEL_ERROR 2 //!< Error message +#define CV_LOG_LEVEL_WARN 3 //!< Warning message +#define CV_LOG_LEVEL_INFO 4 //!< Info message +#define CV_LOG_LEVEL_DEBUG 5 //!< Debug message. Disabled in the "Release" build. +#define CV_LOG_LEVEL_VERBOSE 6 //!< Verbose (trace) messages. Requires verbosity level. Disabled in the "Release" build. + +namespace cv { +namespace utils { +namespace logging { + +//! Supported logging levels and their semantic +enum LogLevel { + LOG_LEVEL_SILENT = 0, //!< for using in setLogVevel() call + LOG_LEVEL_FATAL = 1, //!< Fatal (critical) error (unrecoverable internal error) + LOG_LEVEL_ERROR = 2, //!< Error message + LOG_LEVEL_WARNING = 3, //!< Warning message + LOG_LEVEL_INFO = 4, //!< Info message + LOG_LEVEL_DEBUG = 5, //!< Debug message. Disabled in the "Release" build. + LOG_LEVEL_VERBOSE = 6, //!< Verbose (trace) messages. Requires verbosity level. Disabled in the "Release" build. +#ifndef CV_DOXYGEN + ENUM_LOG_LEVEL_FORCE_INT = INT_MAX +#endif +}; + +}}} // namespace + +//! @} + +#endif // OPENCV_LOGGER_DEFINES_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/utils/logger.hpp b/3rdParty/opencv-4.11.0/opencv2/core/utils/logger.hpp index accb860ada..5fc5fb74ae 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/utils/logger.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/utils/logger.hpp @@ -1,218 +1,218 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_LOGGER_HPP -#define OPENCV_LOGGER_HPP - -#include -#include -#include // INT_MAX - -#include "logger.defines.hpp" -#include "logtag.hpp" - -namespace cv { -namespace utils { -namespace logging { - -//! @addtogroup core_logging -//! @{ - -/** Set global logging level -@return previous logging level -*/ -CV_EXPORTS LogLevel setLogLevel(LogLevel logLevel); -/** Get global logging level */ -CV_EXPORTS LogLevel getLogLevel(); - -CV_EXPORTS void registerLogTag(cv::utils::logging::LogTag* plogtag); - -CV_EXPORTS void setLogTagLevel(const char* tag, cv::utils::logging::LogLevel level); - -CV_EXPORTS cv::utils::logging::LogLevel getLogTagLevel(const char* tag); - -namespace internal { - -/** Get global log tag */ -CV_EXPORTS cv::utils::logging::LogTag* getGlobalLogTag(); - -/** Write log message */ -CV_EXPORTS void writeLogMessage(LogLevel logLevel, const char* message); - -/** Write log message */ -CV_EXPORTS void writeLogMessageEx(LogLevel logLevel, const char* tag, const char* file, int line, const char* func, const char* message); - -} // namespace - -struct LogTagAuto - : public LogTag -{ - inline LogTagAuto(const char* _name, LogLevel _level) - : LogTag(_name, _level) - { - registerLogTag(this); - } -}; - -/** - * \def CV_LOG_STRIP_LEVEL - * - * Define CV_LOG_STRIP_LEVEL=CV_LOG_LEVEL_[DEBUG|INFO|WARN|ERROR|FATAL|SILENT] to compile out anything at that and before that logging level - */ -#ifndef CV_LOG_STRIP_LEVEL -# if defined NDEBUG -# define CV_LOG_STRIP_LEVEL CV_LOG_LEVEL_DEBUG -# else -# define CV_LOG_STRIP_LEVEL CV_LOG_LEVEL_VERBOSE -# endif -#endif - -#define CV_LOGTAG_PTR_CAST(expr) static_cast(expr) - -// CV_LOGTAG_EXPAND_NAME is intended to be re-defined (undef and then define again) -// to allows logging users to use a shorter name argument when calling -// CV_LOG_WITH_TAG or its related macros such as CV_LOG_INFO. -// -// This macro is intended to modify the tag argument as a string (token), via -// preprocessor token pasting or metaprogramming techniques. A typical usage -// is to apply a prefix, such as -// ...... #define CV_LOGTAG_EXPAND_NAME(tag) cv_logtag_##tag -// -// It is permitted to re-define to a hard-coded expression, ignoring the tag. -// This would work identically like the CV_LOGTAG_FALLBACK macro. -// -// Important: When the logging macro is called with tag being NULL, a user-defined -// CV_LOGTAG_EXPAND_NAME may expand it into cv_logtag_0, cv_logtag_NULL, or -// cv_logtag_nullptr. Use with care. Also be mindful of C++ symbol redefinitions. -// -// If there is significant amount of logging code with tag being NULL, it is -// recommended to use (re-define) CV_LOGTAG_FALLBACK to inject locally a default -// tag at the beginning of a compilation unit, to minimize lines of code changes. -// -#define CV_LOGTAG_EXPAND_NAME(tag) tag - -// CV_LOGTAG_FALLBACK is intended to be re-defined (undef and then define again) -// by any other compilation units to provide a log tag when the logging statement -// does not specify one. The macro needs to expand into a C++ expression that can -// be static_cast into (cv::utils::logging::LogTag*). Null (nullptr) is permitted. -#define CV_LOGTAG_FALLBACK nullptr - -// CV_LOGTAG_GLOBAL is the tag used when a log tag is not specified in the logging -// statement nor the compilation unit. The macro needs to expand into a C++ -// expression that can be static_cast into (cv::utils::logging::LogTag*). Must be -// non-null. Do not re-define. -#define CV_LOGTAG_GLOBAL cv::utils::logging::internal::getGlobalLogTag() - -#define CV_LOG_WITH_TAG(tag, msgLevel, extra_check0, extra_check1, ...) \ - for(;;) { \ - extra_check0; \ - const auto cv_temp_msglevel = (cv::utils::logging::LogLevel)(msgLevel); \ - if (cv_temp_msglevel >= (CV_LOG_STRIP_LEVEL)) break; \ - auto cv_temp_logtagptr = CV_LOGTAG_PTR_CAST(CV_LOGTAG_EXPAND_NAME(tag)); \ - if (!cv_temp_logtagptr) cv_temp_logtagptr = CV_LOGTAG_PTR_CAST(CV_LOGTAG_FALLBACK); \ - if (!cv_temp_logtagptr) cv_temp_logtagptr = CV_LOGTAG_PTR_CAST(CV_LOGTAG_GLOBAL); \ - if (cv_temp_logtagptr && (cv_temp_msglevel > cv_temp_logtagptr->level)) break; \ - extra_check1; \ - std::stringstream cv_temp_logstream; \ - cv_temp_logstream << __VA_ARGS__; \ - cv::utils::logging::internal::writeLogMessageEx( \ - cv_temp_msglevel, \ - (cv_temp_logtagptr ? cv_temp_logtagptr->name : nullptr), \ - __FILE__, \ - __LINE__, \ - CV_Func, \ - cv_temp_logstream.str().c_str()); \ - break; \ - } - -#define CV_LOG_FATAL(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_FATAL, , , __VA_ARGS__) -#define CV_LOG_ERROR(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_ERROR, , , __VA_ARGS__) -#define CV_LOG_WARNING(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_WARNING, , , __VA_ARGS__) -#define CV_LOG_INFO(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_INFO, , , __VA_ARGS__) -#define CV_LOG_DEBUG(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_DEBUG, , , __VA_ARGS__) -#define CV_LOG_VERBOSE(tag, v, ...) CV_LOG_WITH_TAG(tag, (cv::utils::logging::LOG_LEVEL_VERBOSE + (int)(v)), , , __VA_ARGS__) - -#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_INFO -#undef CV_LOG_INFO -#define CV_LOG_INFO(tag, ...) -#endif - -#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_DEBUG -#undef CV_LOG_DEBUG -#define CV_LOG_DEBUG(tag, ...) -#endif - -#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_VERBOSE -#undef CV_LOG_VERBOSE -#define CV_LOG_VERBOSE(tag, v, ...) -#endif - -//! @cond IGNORED -#define CV__LOG_ONCE_CHECK_PRE \ - static bool _cv_log_once_ ## __LINE__ = false; \ - if (_cv_log_once_ ## __LINE__) break; - -#define CV__LOG_ONCE_CHECK_POST \ - _cv_log_once_ ## __LINE__ = true; - -#define CV__LOG_IF_CHECK(logging_cond) \ - if (!(logging_cond)) break; - -//! @endcond - - -// CV_LOG_ONCE_XXX macros - -#define CV_LOG_ONCE_ERROR(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_ERROR, CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, __VA_ARGS__) -#define CV_LOG_ONCE_WARNING(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_WARNING, CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, __VA_ARGS__) -#define CV_LOG_ONCE_INFO(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_INFO, CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, __VA_ARGS__) -#define CV_LOG_ONCE_DEBUG(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_DEBUG, CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, __VA_ARGS__) -#define CV_LOG_ONCE_VERBOSE(tag, v, ...) CV_LOG_WITH_TAG(tag, (cv::utils::logging::LOG_LEVEL_VERBOSE + (int)(v)), CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, __VA_ARGS__) - -#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_INFO -#undef CV_LOG_ONCE_INFO -#define CV_LOG_ONCE_INFO(tag, ...) -#endif - -#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_DEBUG -#undef CV_LOG_ONCE_DEBUG -#define CV_LOG_ONCE_DEBUG(tag, ...) -#endif - -#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_VERBOSE -#undef CV_LOG_ONCE_VERBOSE -#define CV_LOG_ONCE_VERBOSE(tag, v, ...) -#endif - - -// CV_LOG_IF_XXX macros - -#define CV_LOG_IF_FATAL(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_FATAL, , CV__LOG_IF_CHECK(logging_cond), __VA_ARGS__) -#define CV_LOG_IF_ERROR(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_ERROR, , CV__LOG_IF_CHECK(logging_cond), __VA_ARGS__) -#define CV_LOG_IF_WARNING(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_WARNING, , CV__LOG_IF_CHECK(logging_cond), __VA_ARGS__) -#define CV_LOG_IF_INFO(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_INFO, , CV__LOG_IF_CHECK(logging_cond), __VA_ARGS__) -#define CV_LOG_IF_DEBUG(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_DEBUG, , CV__LOG_IF_CHECK(logging_cond), __VA_ARGS__) -#define CV_LOG_IF_VERBOSE(tag, v, logging_cond, ...) CV_LOG_WITH_TAG(tag, (cv::utils::logging::LOG_LEVEL_VERBOSE + (int)(v)), , CV__LOG_IF_CHECK(logging_cond), __VA_ARGS__) - -#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_INFO -#undef CV_LOG_IF_INFO -#define CV_LOG_IF_INFO(tag, logging_cond, ...) -#endif - -#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_DEBUG -#undef CV_LOG_IF_DEBUG -#define CV_LOG_IF_DEBUG(tag, logging_cond, ...) -#endif - -#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_VERBOSE -#undef CV_LOG_IF_VERBOSE -#define CV_LOG_IF_VERBOSE(tag, v, logging_cond, ...) -#endif - - -//! @} - -}}} // namespace - -#endif // OPENCV_LOGGER_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_LOGGER_HPP +#define OPENCV_LOGGER_HPP + +#include +#include +#include // INT_MAX + +#include "logger.defines.hpp" +#include "logtag.hpp" + +namespace cv { +namespace utils { +namespace logging { + +//! @addtogroup core_logging +//! @{ + +/** Set global logging level +@return previous logging level +*/ +CV_EXPORTS LogLevel setLogLevel(LogLevel logLevel); +/** Get global logging level */ +CV_EXPORTS LogLevel getLogLevel(); + +CV_EXPORTS void registerLogTag(cv::utils::logging::LogTag* plogtag); + +CV_EXPORTS void setLogTagLevel(const char* tag, cv::utils::logging::LogLevel level); + +CV_EXPORTS cv::utils::logging::LogLevel getLogTagLevel(const char* tag); + +namespace internal { + +/** Get global log tag */ +CV_EXPORTS cv::utils::logging::LogTag* getGlobalLogTag(); + +/** Write log message */ +CV_EXPORTS void writeLogMessage(LogLevel logLevel, const char* message); + +/** Write log message */ +CV_EXPORTS void writeLogMessageEx(LogLevel logLevel, const char* tag, const char* file, int line, const char* func, const char* message); + +} // namespace + +struct LogTagAuto + : public LogTag +{ + inline LogTagAuto(const char* _name, LogLevel _level) + : LogTag(_name, _level) + { + registerLogTag(this); + } +}; + +/** + * \def CV_LOG_STRIP_LEVEL + * + * Define CV_LOG_STRIP_LEVEL=CV_LOG_LEVEL_[DEBUG|INFO|WARN|ERROR|FATAL|SILENT] to compile out anything at that and before that logging level + */ +#ifndef CV_LOG_STRIP_LEVEL +# if defined NDEBUG +# define CV_LOG_STRIP_LEVEL CV_LOG_LEVEL_DEBUG +# else +# define CV_LOG_STRIP_LEVEL CV_LOG_LEVEL_VERBOSE +# endif +#endif + +#define CV_LOGTAG_PTR_CAST(expr) static_cast(expr) + +// CV_LOGTAG_EXPAND_NAME is intended to be re-defined (undef and then define again) +// to allows logging users to use a shorter name argument when calling +// CV_LOG_WITH_TAG or its related macros such as CV_LOG_INFO. +// +// This macro is intended to modify the tag argument as a string (token), via +// preprocessor token pasting or metaprogramming techniques. A typical usage +// is to apply a prefix, such as +// ...... #define CV_LOGTAG_EXPAND_NAME(tag) cv_logtag_##tag +// +// It is permitted to re-define to a hard-coded expression, ignoring the tag. +// This would work identically like the CV_LOGTAG_FALLBACK macro. +// +// Important: When the logging macro is called with tag being NULL, a user-defined +// CV_LOGTAG_EXPAND_NAME may expand it into cv_logtag_0, cv_logtag_NULL, or +// cv_logtag_nullptr. Use with care. Also be mindful of C++ symbol redefinitions. +// +// If there is significant amount of logging code with tag being NULL, it is +// recommended to use (re-define) CV_LOGTAG_FALLBACK to inject locally a default +// tag at the beginning of a compilation unit, to minimize lines of code changes. +// +#define CV_LOGTAG_EXPAND_NAME(tag) tag + +// CV_LOGTAG_FALLBACK is intended to be re-defined (undef and then define again) +// by any other compilation units to provide a log tag when the logging statement +// does not specify one. The macro needs to expand into a C++ expression that can +// be static_cast into (cv::utils::logging::LogTag*). Null (nullptr) is permitted. +#define CV_LOGTAG_FALLBACK nullptr + +// CV_LOGTAG_GLOBAL is the tag used when a log tag is not specified in the logging +// statement nor the compilation unit. The macro needs to expand into a C++ +// expression that can be static_cast into (cv::utils::logging::LogTag*). Must be +// non-null. Do not re-define. +#define CV_LOGTAG_GLOBAL cv::utils::logging::internal::getGlobalLogTag() + +#define CV_LOG_WITH_TAG(tag, msgLevel, extra_check0, extra_check1, ...) \ + for(;;) { \ + extra_check0; \ + const auto cv_temp_msglevel = (cv::utils::logging::LogLevel)(msgLevel); \ + if (cv_temp_msglevel >= (CV_LOG_STRIP_LEVEL)) break; \ + auto cv_temp_logtagptr = CV_LOGTAG_PTR_CAST(CV_LOGTAG_EXPAND_NAME(tag)); \ + if (!cv_temp_logtagptr) cv_temp_logtagptr = CV_LOGTAG_PTR_CAST(CV_LOGTAG_FALLBACK); \ + if (!cv_temp_logtagptr) cv_temp_logtagptr = CV_LOGTAG_PTR_CAST(CV_LOGTAG_GLOBAL); \ + if (cv_temp_logtagptr && (cv_temp_msglevel > cv_temp_logtagptr->level)) break; \ + extra_check1; \ + std::stringstream cv_temp_logstream; \ + cv_temp_logstream << __VA_ARGS__; \ + cv::utils::logging::internal::writeLogMessageEx( \ + cv_temp_msglevel, \ + (cv_temp_logtagptr ? cv_temp_logtagptr->name : nullptr), \ + __FILE__, \ + __LINE__, \ + CV_Func, \ + cv_temp_logstream.str().c_str()); \ + break; \ + } + +#define CV_LOG_FATAL(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_FATAL, , , __VA_ARGS__) +#define CV_LOG_ERROR(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_ERROR, , , __VA_ARGS__) +#define CV_LOG_WARNING(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_WARNING, , , __VA_ARGS__) +#define CV_LOG_INFO(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_INFO, , , __VA_ARGS__) +#define CV_LOG_DEBUG(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_DEBUG, , , __VA_ARGS__) +#define CV_LOG_VERBOSE(tag, v, ...) CV_LOG_WITH_TAG(tag, (cv::utils::logging::LOG_LEVEL_VERBOSE + (int)(v)), , , __VA_ARGS__) + +#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_INFO +#undef CV_LOG_INFO +#define CV_LOG_INFO(tag, ...) +#endif + +#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_DEBUG +#undef CV_LOG_DEBUG +#define CV_LOG_DEBUG(tag, ...) +#endif + +#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_VERBOSE +#undef CV_LOG_VERBOSE +#define CV_LOG_VERBOSE(tag, v, ...) +#endif + +//! @cond IGNORED +#define CV__LOG_ONCE_CHECK_PRE \ + static bool _cv_log_once_ ## __LINE__ = false; \ + if (_cv_log_once_ ## __LINE__) break; + +#define CV__LOG_ONCE_CHECK_POST \ + _cv_log_once_ ## __LINE__ = true; + +#define CV__LOG_IF_CHECK(logging_cond) \ + if (!(logging_cond)) break; + +//! @endcond + + +// CV_LOG_ONCE_XXX macros + +#define CV_LOG_ONCE_ERROR(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_ERROR, CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, __VA_ARGS__) +#define CV_LOG_ONCE_WARNING(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_WARNING, CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, __VA_ARGS__) +#define CV_LOG_ONCE_INFO(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_INFO, CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, __VA_ARGS__) +#define CV_LOG_ONCE_DEBUG(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_DEBUG, CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, __VA_ARGS__) +#define CV_LOG_ONCE_VERBOSE(tag, v, ...) CV_LOG_WITH_TAG(tag, (cv::utils::logging::LOG_LEVEL_VERBOSE + (int)(v)), CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, __VA_ARGS__) + +#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_INFO +#undef CV_LOG_ONCE_INFO +#define CV_LOG_ONCE_INFO(tag, ...) +#endif + +#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_DEBUG +#undef CV_LOG_ONCE_DEBUG +#define CV_LOG_ONCE_DEBUG(tag, ...) +#endif + +#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_VERBOSE +#undef CV_LOG_ONCE_VERBOSE +#define CV_LOG_ONCE_VERBOSE(tag, v, ...) +#endif + + +// CV_LOG_IF_XXX macros + +#define CV_LOG_IF_FATAL(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_FATAL, , CV__LOG_IF_CHECK(logging_cond), __VA_ARGS__) +#define CV_LOG_IF_ERROR(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_ERROR, , CV__LOG_IF_CHECK(logging_cond), __VA_ARGS__) +#define CV_LOG_IF_WARNING(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_WARNING, , CV__LOG_IF_CHECK(logging_cond), __VA_ARGS__) +#define CV_LOG_IF_INFO(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_INFO, , CV__LOG_IF_CHECK(logging_cond), __VA_ARGS__) +#define CV_LOG_IF_DEBUG(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_DEBUG, , CV__LOG_IF_CHECK(logging_cond), __VA_ARGS__) +#define CV_LOG_IF_VERBOSE(tag, v, logging_cond, ...) CV_LOG_WITH_TAG(tag, (cv::utils::logging::LOG_LEVEL_VERBOSE + (int)(v)), , CV__LOG_IF_CHECK(logging_cond), __VA_ARGS__) + +#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_INFO +#undef CV_LOG_IF_INFO +#define CV_LOG_IF_INFO(tag, logging_cond, ...) +#endif + +#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_DEBUG +#undef CV_LOG_IF_DEBUG +#define CV_LOG_IF_DEBUG(tag, logging_cond, ...) +#endif + +#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_VERBOSE +#undef CV_LOG_IF_VERBOSE +#define CV_LOG_IF_VERBOSE(tag, v, logging_cond, ...) +#endif + + +//! @} + +}}} // namespace + +#endif // OPENCV_LOGGER_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/utils/logtag.hpp b/3rdParty/opencv-4.11.0/opencv2/core/utils/logtag.hpp index 4089720767..d51f84decb 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/utils/logtag.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/utils/logtag.hpp @@ -1,28 +1,28 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_LOGTAG_HPP -#define OPENCV_CORE_LOGTAG_HPP - -#include "opencv2/core/cvstd.hpp" -#include "logger.defines.hpp" - -namespace cv { -namespace utils { -namespace logging { - -struct LogTag -{ - const char* name; - LogLevel level; - - inline LogTag(const char* _name, LogLevel _level) - : name(_name) - , level(_level) - {} -}; - -}}} - -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_LOGTAG_HPP +#define OPENCV_CORE_LOGTAG_HPP + +#include "opencv2/core/cvstd.hpp" +#include "logger.defines.hpp" + +namespace cv { +namespace utils { +namespace logging { + +struct LogTag +{ + const char* name; + LogLevel level; + + inline LogTag(const char* _name, LogLevel _level) + : name(_name) + , level(_level) + {} +}; + +}}} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/utils/tls.hpp b/3rdParty/opencv-4.11.0/opencv2/core/utils/tls.hpp index 124caebc85..042ca6c787 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/utils/tls.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/utils/tls.hpp @@ -1,235 +1,235 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_UTILS_TLS_HPP -#define OPENCV_UTILS_TLS_HPP - -#ifndef OPENCV_CORE_UTILITY_H -#error "tls.hpp must be included after opencv2/core/utility.hpp or opencv2/core.hpp" -#endif - -namespace cv { - -//! @addtogroup core_utils -//! @{ - -namespace details { class TlsStorage; } - -/** TLS container base implementation - * - * Don't use directly. - * - * @sa TLSData, TLSDataAccumulator templates - */ -class CV_EXPORTS TLSDataContainer -{ -protected: - TLSDataContainer(); - virtual ~TLSDataContainer(); - - /// @deprecated use detachData() instead - void gatherData(std::vector &data) const; - /// get TLS data and detach all data from threads (similar to cleanup() call) - void detachData(std::vector& data); - - void* getData() const; - void release(); - -protected: - virtual void* createDataInstance() const = 0; - virtual void deleteDataInstance(void* pData) const = 0; - -private: - int key_; - - friend class cv::details::TlsStorage; // core/src/system.cpp - -public: - void cleanup(); //!< Release created TLS data container objects. It is similar to release() call, but it keeps TLS container valid. - -private: - // Disable copy/assign (noncopyable pattern) - TLSDataContainer(TLSDataContainer &) = delete; - TLSDataContainer& operator =(const TLSDataContainer &) = delete; -}; - - -/** @brief Simple TLS data class - * - * @sa TLSDataAccumulator - */ -template -class TLSData : protected TLSDataContainer -{ -public: - inline TLSData() {} - inline ~TLSData() { release(); } - - inline T* get() const { return (T*)getData(); } //!< Get data associated with key - inline T& getRef() const { T* ptr = (T*)getData(); CV_DbgAssert(ptr); return *ptr; } //!< Get data associated with key - - /// Release associated thread data - inline void cleanup() - { - TLSDataContainer::cleanup(); - } - -protected: - /// Wrapper to allocate data by template - virtual void* createDataInstance() const CV_OVERRIDE { return new T; } - /// Wrapper to release data by template - virtual void deleteDataInstance(void* pData) const CV_OVERRIDE { delete (T*)pData; } -}; - - -/// TLS data accumulator with gathering methods -template -class TLSDataAccumulator : public TLSData -{ - mutable cv::Mutex mutex; - mutable std::vector dataFromTerminatedThreads; - std::vector detachedData; - bool cleanupMode; -public: - TLSDataAccumulator() : cleanupMode(false) {} - ~TLSDataAccumulator() - { - release(); - } - - /** @brief Get data from all threads - * @deprecated replaced by detachData() - * - * Lifetime of vector data is valid until next detachData()/cleanup()/release() calls - * - * @param[out] data result buffer (should be empty) - */ - void gather(std::vector &data) const - { - CV_Assert(cleanupMode == false); // state is not valid - CV_Assert(data.empty()); - { - std::vector &dataVoid = reinterpret_cast&>(data); - TLSDataContainer::gatherData(dataVoid); - } - { - AutoLock lock(mutex); - data.reserve(data.size() + dataFromTerminatedThreads.size()); - for (typename std::vector::const_iterator i = dataFromTerminatedThreads.begin(); i != dataFromTerminatedThreads.end(); ++i) - { - data.push_back((T*)*i); - } - } - } - - /** @brief Get and detach data from all threads - * - * Call cleanupDetachedData() when returned vector is not needed anymore. - * - * @return Vector with associated data. Content is preserved (including lifetime of attached data pointers) until next detachData()/cleanupDetachedData()/cleanup()/release() calls - */ - std::vector& detachData() - { - CV_Assert(cleanupMode == false); // state is not valid - std::vector dataVoid; - { - TLSDataContainer::detachData(dataVoid); - } - { - AutoLock lock(mutex); - detachedData.reserve(dataVoid.size() + dataFromTerminatedThreads.size()); - for (typename std::vector::const_iterator i = dataFromTerminatedThreads.begin(); i != dataFromTerminatedThreads.end(); ++i) - { - detachedData.push_back((T*)*i); - } - dataFromTerminatedThreads.clear(); - for (typename std::vector::const_iterator i = dataVoid.begin(); i != dataVoid.end(); ++i) - { - detachedData.push_back((T*)(void*)*i); - } - } - dataVoid.clear(); - return detachedData; - } - - /// Release associated thread data returned by detachData() call - void cleanupDetachedData() - { - AutoLock lock(mutex); - cleanupMode = true; - _cleanupDetachedData(); - cleanupMode = false; - } - - /// Release associated thread data - void cleanup() - { - cleanupMode = true; - TLSDataContainer::cleanup(); - - AutoLock lock(mutex); - _cleanupDetachedData(); - _cleanupTerminatedData(); - cleanupMode = false; - } - - /// Release associated thread data and free TLS key - void release() - { - cleanupMode = true; - TLSDataContainer::release(); - { - AutoLock lock(mutex); - _cleanupDetachedData(); - _cleanupTerminatedData(); - } - } - -protected: - // synchronized - void _cleanupDetachedData() - { - for (typename std::vector::iterator i = detachedData.begin(); i != detachedData.end(); ++i) - { - deleteDataInstance((T*)*i); - } - detachedData.clear(); - } - - // synchronized - void _cleanupTerminatedData() - { - for (typename std::vector::iterator i = dataFromTerminatedThreads.begin(); i != dataFromTerminatedThreads.end(); ++i) - { - deleteDataInstance((T*)*i); - } - dataFromTerminatedThreads.clear(); - } - -protected: - virtual void* createDataInstance() const CV_OVERRIDE - { - // Note: we can collect all allocated data here, but this would require raced mutex locks - return new T; - } - virtual void deleteDataInstance(void* pData) const CV_OVERRIDE - { - if (cleanupMode) - { - delete (T*)pData; - } - else - { - AutoLock lock(mutex); - dataFromTerminatedThreads.push_back((T*)pData); - } - } -}; - - -//! @} - -} // namespace - -#endif // OPENCV_UTILS_TLS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_UTILS_TLS_HPP +#define OPENCV_UTILS_TLS_HPP + +#ifndef OPENCV_CORE_UTILITY_H +#error "tls.hpp must be included after opencv2/core/utility.hpp or opencv2/core.hpp" +#endif + +namespace cv { + +//! @addtogroup core_utils +//! @{ + +namespace details { class TlsStorage; } + +/** TLS container base implementation + * + * Don't use directly. + * + * @sa TLSData, TLSDataAccumulator templates + */ +class CV_EXPORTS TLSDataContainer +{ +protected: + TLSDataContainer(); + virtual ~TLSDataContainer(); + + /// @deprecated use detachData() instead + void gatherData(std::vector &data) const; + /// get TLS data and detach all data from threads (similar to cleanup() call) + void detachData(std::vector& data); + + void* getData() const; + void release(); + +protected: + virtual void* createDataInstance() const = 0; + virtual void deleteDataInstance(void* pData) const = 0; + +private: + int key_; + + friend class cv::details::TlsStorage; // core/src/system.cpp + +public: + void cleanup(); //!< Release created TLS data container objects. It is similar to release() call, but it keeps TLS container valid. + +private: + // Disable copy/assign (noncopyable pattern) + TLSDataContainer(TLSDataContainer &) = delete; + TLSDataContainer& operator =(const TLSDataContainer &) = delete; +}; + + +/** @brief Simple TLS data class + * + * @sa TLSDataAccumulator + */ +template +class TLSData : protected TLSDataContainer +{ +public: + inline TLSData() {} + inline ~TLSData() { release(); } + + inline T* get() const { return (T*)getData(); } //!< Get data associated with key + inline T& getRef() const { T* ptr = (T*)getData(); CV_DbgAssert(ptr); return *ptr; } //!< Get data associated with key + + /// Release associated thread data + inline void cleanup() + { + TLSDataContainer::cleanup(); + } + +protected: + /// Wrapper to allocate data by template + virtual void* createDataInstance() const CV_OVERRIDE { return new T; } + /// Wrapper to release data by template + virtual void deleteDataInstance(void* pData) const CV_OVERRIDE { delete (T*)pData; } +}; + + +/// TLS data accumulator with gathering methods +template +class TLSDataAccumulator : public TLSData +{ + mutable cv::Mutex mutex; + mutable std::vector dataFromTerminatedThreads; + std::vector detachedData; + bool cleanupMode; +public: + TLSDataAccumulator() : cleanupMode(false) {} + ~TLSDataAccumulator() + { + release(); + } + + /** @brief Get data from all threads + * @deprecated replaced by detachData() + * + * Lifetime of vector data is valid until next detachData()/cleanup()/release() calls + * + * @param[out] data result buffer (should be empty) + */ + void gather(std::vector &data) const + { + CV_Assert(cleanupMode == false); // state is not valid + CV_Assert(data.empty()); + { + std::vector &dataVoid = reinterpret_cast&>(data); + TLSDataContainer::gatherData(dataVoid); + } + { + AutoLock lock(mutex); + data.reserve(data.size() + dataFromTerminatedThreads.size()); + for (typename std::vector::const_iterator i = dataFromTerminatedThreads.begin(); i != dataFromTerminatedThreads.end(); ++i) + { + data.push_back((T*)*i); + } + } + } + + /** @brief Get and detach data from all threads + * + * Call cleanupDetachedData() when returned vector is not needed anymore. + * + * @return Vector with associated data. Content is preserved (including lifetime of attached data pointers) until next detachData()/cleanupDetachedData()/cleanup()/release() calls + */ + std::vector& detachData() + { + CV_Assert(cleanupMode == false); // state is not valid + std::vector dataVoid; + { + TLSDataContainer::detachData(dataVoid); + } + { + AutoLock lock(mutex); + detachedData.reserve(dataVoid.size() + dataFromTerminatedThreads.size()); + for (typename std::vector::const_iterator i = dataFromTerminatedThreads.begin(); i != dataFromTerminatedThreads.end(); ++i) + { + detachedData.push_back((T*)*i); + } + dataFromTerminatedThreads.clear(); + for (typename std::vector::const_iterator i = dataVoid.begin(); i != dataVoid.end(); ++i) + { + detachedData.push_back((T*)(void*)*i); + } + } + dataVoid.clear(); + return detachedData; + } + + /// Release associated thread data returned by detachData() call + void cleanupDetachedData() + { + AutoLock lock(mutex); + cleanupMode = true; + _cleanupDetachedData(); + cleanupMode = false; + } + + /// Release associated thread data + void cleanup() + { + cleanupMode = true; + TLSDataContainer::cleanup(); + + AutoLock lock(mutex); + _cleanupDetachedData(); + _cleanupTerminatedData(); + cleanupMode = false; + } + + /// Release associated thread data and free TLS key + void release() + { + cleanupMode = true; + TLSDataContainer::release(); + { + AutoLock lock(mutex); + _cleanupDetachedData(); + _cleanupTerminatedData(); + } + } + +protected: + // synchronized + void _cleanupDetachedData() + { + for (typename std::vector::iterator i = detachedData.begin(); i != detachedData.end(); ++i) + { + deleteDataInstance((T*)*i); + } + detachedData.clear(); + } + + // synchronized + void _cleanupTerminatedData() + { + for (typename std::vector::iterator i = dataFromTerminatedThreads.begin(); i != dataFromTerminatedThreads.end(); ++i) + { + deleteDataInstance((T*)*i); + } + dataFromTerminatedThreads.clear(); + } + +protected: + virtual void* createDataInstance() const CV_OVERRIDE + { + // Note: we can collect all allocated data here, but this would require raced mutex locks + return new T; + } + virtual void deleteDataInstance(void* pData) const CV_OVERRIDE + { + if (cleanupMode) + { + delete (T*)pData; + } + else + { + AutoLock lock(mutex); + dataFromTerminatedThreads.push_back((T*)pData); + } + } +}; + + +//! @} + +} // namespace + +#endif // OPENCV_UTILS_TLS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/utils/trace.hpp b/3rdParty/opencv-4.11.0/opencv2/core/utils/trace.hpp index ea43bbeea1..74d1256c9f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/utils/trace.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/utils/trace.hpp @@ -1,252 +1,252 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_TRACE_HPP -#define OPENCV_TRACE_HPP - -#include - -namespace cv { -namespace utils { -namespace trace { - -//! @addtogroup core_logging -//! @{ - -//! Macro to trace function -#define CV_TRACE_FUNCTION() - -#define CV_TRACE_FUNCTION_SKIP_NESTED() - -//! Trace code scope. -//! @note Dynamic names are not supported in this macro (on stack or heap). Use string literals here only, like "initialize". -#define CV_TRACE_REGION(name_as_static_string_literal) -//! mark completed of the current opened region and create new one -//! @note Dynamic names are not supported in this macro (on stack or heap). Use string literals here only, like "step1". -#define CV_TRACE_REGION_NEXT(name_as_static_string_literal) - -//! Macro to trace argument value -#define CV_TRACE_ARG(arg_id) - -//! Macro to trace argument value (expanded version) -#define CV_TRACE_ARG_VALUE(arg_id, arg_name, value) - -//! @cond IGNORED -#define CV_TRACE_NS cv::utils::trace - -#if !defined(OPENCV_DISABLE_TRACE) && defined(__EMSCRIPTEN__) -#define OPENCV_DISABLE_TRACE 1 -#endif - -namespace details { - -#ifndef __OPENCV_TRACE -# if defined __OPENCV_BUILD && !defined __OPENCV_TESTS && !defined __OPENCV_APPS -# define __OPENCV_TRACE 1 -# else -# define __OPENCV_TRACE 0 -# endif -#endif - -#ifndef CV_TRACE_FILENAME -# define CV_TRACE_FILENAME __FILE__ -#endif - -#ifndef CV__TRACE_FUNCTION -# if defined _MSC_VER -# define CV__TRACE_FUNCTION __FUNCSIG__ -# elif defined __GNUC__ -# define CV__TRACE_FUNCTION __PRETTY_FUNCTION__ -# else -# define CV__TRACE_FUNCTION "" -# endif -#endif - -//! Thread-local instance (usually allocated on stack) -class CV_EXPORTS Region -{ -public: - struct LocationExtraData; - struct LocationStaticStorage - { - LocationExtraData** ppExtra; ///< implementation specific data - const char* name; ///< region name (function name or other custom name) - const char* filename; ///< source code filename - int line; ///< source code line - int flags; ///< flags (implementation code path: Plain, IPP, OpenCL) - }; - - Region(const LocationStaticStorage& location); - inline ~Region() - { - if (implFlags != 0) - destroy(); - CV_DbgAssert(implFlags == 0); - CV_DbgAssert(pImpl == NULL); - } - - class Impl; - Impl* pImpl; // NULL if current region is not active - int implFlags; // see RegionFlag, 0 if region is ignored - - bool isActive() const { return pImpl != NULL; } - - void destroy(); -private: - Region(const Region&); // disabled - Region& operator= (const Region&); // disabled -}; - -//! Specify region flags -enum RegionLocationFlag { - REGION_FLAG_FUNCTION = (1 << 0), ///< region is function (=1) / nested named region (=0) - REGION_FLAG_APP_CODE = (1 << 1), ///< region is Application code (=1) / OpenCV library code (=0) - REGION_FLAG_SKIP_NESTED = (1 << 2), ///< avoid processing of nested regions - - REGION_FLAG_IMPL_IPP = (1 << 16), ///< region is part of IPP code path - REGION_FLAG_IMPL_OPENCL = (2 << 16), ///< region is part of OpenCL code path - REGION_FLAG_IMPL_OPENVX = (3 << 16), ///< region is part of OpenVX code path - - REGION_FLAG_IMPL_MASK = (15 << 16), - - REGION_FLAG_REGION_FORCE = (1 << 30), - REGION_FLAG_REGION_NEXT = (1 << 31), ///< close previous region (see #CV_TRACE_REGION_NEXT macro) - - ENUM_REGION_FLAG_FORCE_INT = INT_MAX -}; - -struct CV_EXPORTS TraceArg { -public: - struct ExtraData; - ExtraData** ppExtra; - const char* name; - int flags; -}; -/** @brief Add meta information to current region (function) - * See CV_TRACE_ARG macro - * @param arg argument information structure (global static cache) - * @param value argument value (can by dynamic string literal in case of string, static allocation is not required) - */ -CV_EXPORTS void traceArg(const TraceArg& arg, const char* value); -//! @overload -CV_EXPORTS void traceArg(const TraceArg& arg, int value); -//! @overload -CV_EXPORTS void traceArg(const TraceArg& arg, int64 value); -//! @overload -CV_EXPORTS void traceArg(const TraceArg& arg, double value); - -#define CV__TRACE_LOCATION_VARNAME(loc_id) CVAUX_CONCAT(CVAUX_CONCAT(__cv_trace_location_, loc_id), __LINE__) -#define CV__TRACE_LOCATION_EXTRA_VARNAME(loc_id) CVAUX_CONCAT(CVAUX_CONCAT(__cv_trace_location_extra_, loc_id) , __LINE__) - -#define CV__TRACE_DEFINE_LOCATION_(loc_id, name, flags) \ - static CV_TRACE_NS::details::Region::LocationExtraData* CV__TRACE_LOCATION_EXTRA_VARNAME(loc_id) = 0; \ - static const CV_TRACE_NS::details::Region::LocationStaticStorage \ - CV__TRACE_LOCATION_VARNAME(loc_id) = { &(CV__TRACE_LOCATION_EXTRA_VARNAME(loc_id)), name, CV_TRACE_FILENAME, __LINE__, flags}; - -#define CV__TRACE_DEFINE_LOCATION_FN(name, flags) CV__TRACE_DEFINE_LOCATION_(fn, name, ((flags) | CV_TRACE_NS::details::REGION_FLAG_FUNCTION)) - - -#define CV__TRACE_OPENCV_FUNCTION() \ - CV__TRACE_DEFINE_LOCATION_FN(CV__TRACE_FUNCTION, 0); \ - const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); - -#define CV__TRACE_OPENCV_FUNCTION_NAME(name) \ - CV__TRACE_DEFINE_LOCATION_FN(name, 0); \ - const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); - -#define CV__TRACE_APP_FUNCTION() \ - CV__TRACE_DEFINE_LOCATION_FN(CV__TRACE_FUNCTION, CV_TRACE_NS::details::REGION_FLAG_APP_CODE); \ - const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); - -#define CV__TRACE_APP_FUNCTION_NAME(name) \ - CV__TRACE_DEFINE_LOCATION_FN(name, CV_TRACE_NS::details::REGION_FLAG_APP_CODE); \ - const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); - - -#define CV__TRACE_OPENCV_FUNCTION_SKIP_NESTED() \ - CV__TRACE_DEFINE_LOCATION_FN(CV__TRACE_FUNCTION, CV_TRACE_NS::details::REGION_FLAG_SKIP_NESTED); \ - const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); - -#define CV__TRACE_OPENCV_FUNCTION_NAME_SKIP_NESTED(name) \ - CV__TRACE_DEFINE_LOCATION_FN(name, CV_TRACE_NS::details::REGION_FLAG_SKIP_NESTED); \ - const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); - -#define CV__TRACE_APP_FUNCTION_SKIP_NESTED() \ - CV__TRACE_DEFINE_LOCATION_FN(CV__TRACE_FUNCTION, CV_TRACE_NS::details::REGION_FLAG_SKIP_NESTED | CV_TRACE_NS::details::REGION_FLAG_APP_CODE); \ - const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); - - -#define CV__TRACE_REGION_(name_as_static_string_literal, flags) \ - CV__TRACE_DEFINE_LOCATION_(region, name_as_static_string_literal, flags); \ - CV_TRACE_NS::details::Region CVAUX_CONCAT(__region_, __LINE__)(CV__TRACE_LOCATION_VARNAME(region)); - -#define CV__TRACE_REGION(name_as_static_string_literal) CV__TRACE_REGION_(name_as_static_string_literal, 0) -#define CV__TRACE_REGION_NEXT(name_as_static_string_literal) CV__TRACE_REGION_(name_as_static_string_literal, CV_TRACE_NS::details::REGION_FLAG_REGION_NEXT) - -#define CV__TRACE_ARG_VARNAME(arg_id) CVAUX_CONCAT(__cv_trace_arg_ ## arg_id, __LINE__) -#define CV__TRACE_ARG_EXTRA_VARNAME(arg_id) CVAUX_CONCAT(__cv_trace_arg_extra_ ## arg_id, __LINE__) - -#define CV__TRACE_DEFINE_ARG_(arg_id, name, flags) \ - static CV_TRACE_NS::details::TraceArg::ExtraData* CV__TRACE_ARG_EXTRA_VARNAME(arg_id) = 0; \ - static const CV_TRACE_NS::details::TraceArg \ - CV__TRACE_ARG_VARNAME(arg_id) = { &(CV__TRACE_ARG_EXTRA_VARNAME(arg_id)), name, flags }; - -#define CV__TRACE_ARG_VALUE(arg_id, arg_name, value) \ - CV__TRACE_DEFINE_ARG_(arg_id, arg_name, 0); \ - CV_TRACE_NS::details::traceArg((CV__TRACE_ARG_VARNAME(arg_id)), value); - -#define CV__TRACE_ARG(arg_id) CV_TRACE_ARG_VALUE(arg_id, #arg_id, (arg_id)) - -} // namespace - -#ifndef OPENCV_DISABLE_TRACE -#undef CV_TRACE_FUNCTION -#undef CV_TRACE_FUNCTION_SKIP_NESTED -#if __OPENCV_TRACE -#define CV_TRACE_FUNCTION CV__TRACE_OPENCV_FUNCTION -#define CV_TRACE_FUNCTION_SKIP_NESTED CV__TRACE_OPENCV_FUNCTION_SKIP_NESTED -#else -#define CV_TRACE_FUNCTION CV__TRACE_APP_FUNCTION -#define CV_TRACE_FUNCTION_SKIP_NESTED CV__TRACE_APP_FUNCTION_SKIP_NESTED -#endif - -#undef CV_TRACE_REGION -#define CV_TRACE_REGION CV__TRACE_REGION - -#undef CV_TRACE_REGION_NEXT -#define CV_TRACE_REGION_NEXT CV__TRACE_REGION_NEXT - -#undef CV_TRACE_ARG_VALUE -#define CV_TRACE_ARG_VALUE(arg_id, arg_name, value) \ - if (__region_fn.isActive()) \ - { \ - CV__TRACE_ARG_VALUE(arg_id, arg_name, value); \ - } - -#undef CV_TRACE_ARG -#define CV_TRACE_ARG CV__TRACE_ARG - -#endif // OPENCV_DISABLE_TRACE - -#ifdef OPENCV_TRACE_VERBOSE -#define CV_TRACE_FUNCTION_VERBOSE CV_TRACE_FUNCTION -#define CV_TRACE_REGION_VERBOSE CV_TRACE_REGION -#define CV_TRACE_REGION_NEXT_VERBOSE CV_TRACE_REGION_NEXT -#define CV_TRACE_ARG_VALUE_VERBOSE CV_TRACE_ARG_VALUE -#define CV_TRACE_ARG_VERBOSE CV_TRACE_ARG -#else -#define CV_TRACE_FUNCTION_VERBOSE(...) -#define CV_TRACE_REGION_VERBOSE(...) -#define CV_TRACE_REGION_NEXT_VERBOSE(...) -#define CV_TRACE_ARG_VALUE_VERBOSE(...) -#define CV_TRACE_ARG_VERBOSE(...) -#endif - -//! @endcond - -//! @} - -}}} // namespace - -#endif // OPENCV_TRACE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_TRACE_HPP +#define OPENCV_TRACE_HPP + +#include + +namespace cv { +namespace utils { +namespace trace { + +//! @addtogroup core_logging +//! @{ + +//! Macro to trace function +#define CV_TRACE_FUNCTION() + +#define CV_TRACE_FUNCTION_SKIP_NESTED() + +//! Trace code scope. +//! @note Dynamic names are not supported in this macro (on stack or heap). Use string literals here only, like "initialize". +#define CV_TRACE_REGION(name_as_static_string_literal) +//! mark completed of the current opened region and create new one +//! @note Dynamic names are not supported in this macro (on stack or heap). Use string literals here only, like "step1". +#define CV_TRACE_REGION_NEXT(name_as_static_string_literal) + +//! Macro to trace argument value +#define CV_TRACE_ARG(arg_id) + +//! Macro to trace argument value (expanded version) +#define CV_TRACE_ARG_VALUE(arg_id, arg_name, value) + +//! @cond IGNORED +#define CV_TRACE_NS cv::utils::trace + +#if !defined(OPENCV_DISABLE_TRACE) && defined(__EMSCRIPTEN__) +#define OPENCV_DISABLE_TRACE 1 +#endif + +namespace details { + +#ifndef __OPENCV_TRACE +# if defined __OPENCV_BUILD && !defined __OPENCV_TESTS && !defined __OPENCV_APPS +# define __OPENCV_TRACE 1 +# else +# define __OPENCV_TRACE 0 +# endif +#endif + +#ifndef CV_TRACE_FILENAME +# define CV_TRACE_FILENAME __FILE__ +#endif + +#ifndef CV__TRACE_FUNCTION +# if defined _MSC_VER +# define CV__TRACE_FUNCTION __FUNCSIG__ +# elif defined __GNUC__ +# define CV__TRACE_FUNCTION __PRETTY_FUNCTION__ +# else +# define CV__TRACE_FUNCTION "" +# endif +#endif + +//! Thread-local instance (usually allocated on stack) +class CV_EXPORTS Region +{ +public: + struct LocationExtraData; + struct LocationStaticStorage + { + LocationExtraData** ppExtra; ///< implementation specific data + const char* name; ///< region name (function name or other custom name) + const char* filename; ///< source code filename + int line; ///< source code line + int flags; ///< flags (implementation code path: Plain, IPP, OpenCL) + }; + + Region(const LocationStaticStorage& location); + inline ~Region() + { + if (implFlags != 0) + destroy(); + CV_DbgAssert(implFlags == 0); + CV_DbgAssert(pImpl == NULL); + } + + class Impl; + Impl* pImpl; // NULL if current region is not active + int implFlags; // see RegionFlag, 0 if region is ignored + + bool isActive() const { return pImpl != NULL; } + + void destroy(); +private: + Region(const Region&); // disabled + Region& operator= (const Region&); // disabled +}; + +//! Specify region flags +enum RegionLocationFlag { + REGION_FLAG_FUNCTION = (1 << 0), ///< region is function (=1) / nested named region (=0) + REGION_FLAG_APP_CODE = (1 << 1), ///< region is Application code (=1) / OpenCV library code (=0) + REGION_FLAG_SKIP_NESTED = (1 << 2), ///< avoid processing of nested regions + + REGION_FLAG_IMPL_IPP = (1 << 16), ///< region is part of IPP code path + REGION_FLAG_IMPL_OPENCL = (2 << 16), ///< region is part of OpenCL code path + REGION_FLAG_IMPL_OPENVX = (3 << 16), ///< region is part of OpenVX code path + + REGION_FLAG_IMPL_MASK = (15 << 16), + + REGION_FLAG_REGION_FORCE = (1 << 30), + REGION_FLAG_REGION_NEXT = (1 << 31), ///< close previous region (see #CV_TRACE_REGION_NEXT macro) + + ENUM_REGION_FLAG_FORCE_INT = INT_MAX +}; + +struct CV_EXPORTS TraceArg { +public: + struct ExtraData; + ExtraData** ppExtra; + const char* name; + int flags; +}; +/** @brief Add meta information to current region (function) + * See CV_TRACE_ARG macro + * @param arg argument information structure (global static cache) + * @param value argument value (can by dynamic string literal in case of string, static allocation is not required) + */ +CV_EXPORTS void traceArg(const TraceArg& arg, const char* value); +//! @overload +CV_EXPORTS void traceArg(const TraceArg& arg, int value); +//! @overload +CV_EXPORTS void traceArg(const TraceArg& arg, int64 value); +//! @overload +CV_EXPORTS void traceArg(const TraceArg& arg, double value); + +#define CV__TRACE_LOCATION_VARNAME(loc_id) CVAUX_CONCAT(CVAUX_CONCAT(__cv_trace_location_, loc_id), __LINE__) +#define CV__TRACE_LOCATION_EXTRA_VARNAME(loc_id) CVAUX_CONCAT(CVAUX_CONCAT(__cv_trace_location_extra_, loc_id) , __LINE__) + +#define CV__TRACE_DEFINE_LOCATION_(loc_id, name, flags) \ + static CV_TRACE_NS::details::Region::LocationExtraData* CV__TRACE_LOCATION_EXTRA_VARNAME(loc_id) = 0; \ + static const CV_TRACE_NS::details::Region::LocationStaticStorage \ + CV__TRACE_LOCATION_VARNAME(loc_id) = { &(CV__TRACE_LOCATION_EXTRA_VARNAME(loc_id)), name, CV_TRACE_FILENAME, __LINE__, flags}; + +#define CV__TRACE_DEFINE_LOCATION_FN(name, flags) CV__TRACE_DEFINE_LOCATION_(fn, name, ((flags) | CV_TRACE_NS::details::REGION_FLAG_FUNCTION)) + + +#define CV__TRACE_OPENCV_FUNCTION() \ + CV__TRACE_DEFINE_LOCATION_FN(CV__TRACE_FUNCTION, 0); \ + const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); + +#define CV__TRACE_OPENCV_FUNCTION_NAME(name) \ + CV__TRACE_DEFINE_LOCATION_FN(name, 0); \ + const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); + +#define CV__TRACE_APP_FUNCTION() \ + CV__TRACE_DEFINE_LOCATION_FN(CV__TRACE_FUNCTION, CV_TRACE_NS::details::REGION_FLAG_APP_CODE); \ + const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); + +#define CV__TRACE_APP_FUNCTION_NAME(name) \ + CV__TRACE_DEFINE_LOCATION_FN(name, CV_TRACE_NS::details::REGION_FLAG_APP_CODE); \ + const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); + + +#define CV__TRACE_OPENCV_FUNCTION_SKIP_NESTED() \ + CV__TRACE_DEFINE_LOCATION_FN(CV__TRACE_FUNCTION, CV_TRACE_NS::details::REGION_FLAG_SKIP_NESTED); \ + const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); + +#define CV__TRACE_OPENCV_FUNCTION_NAME_SKIP_NESTED(name) \ + CV__TRACE_DEFINE_LOCATION_FN(name, CV_TRACE_NS::details::REGION_FLAG_SKIP_NESTED); \ + const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); + +#define CV__TRACE_APP_FUNCTION_SKIP_NESTED() \ + CV__TRACE_DEFINE_LOCATION_FN(CV__TRACE_FUNCTION, CV_TRACE_NS::details::REGION_FLAG_SKIP_NESTED | CV_TRACE_NS::details::REGION_FLAG_APP_CODE); \ + const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); + + +#define CV__TRACE_REGION_(name_as_static_string_literal, flags) \ + CV__TRACE_DEFINE_LOCATION_(region, name_as_static_string_literal, flags); \ + CV_TRACE_NS::details::Region CVAUX_CONCAT(__region_, __LINE__)(CV__TRACE_LOCATION_VARNAME(region)); + +#define CV__TRACE_REGION(name_as_static_string_literal) CV__TRACE_REGION_(name_as_static_string_literal, 0) +#define CV__TRACE_REGION_NEXT(name_as_static_string_literal) CV__TRACE_REGION_(name_as_static_string_literal, CV_TRACE_NS::details::REGION_FLAG_REGION_NEXT) + +#define CV__TRACE_ARG_VARNAME(arg_id) CVAUX_CONCAT(__cv_trace_arg_ ## arg_id, __LINE__) +#define CV__TRACE_ARG_EXTRA_VARNAME(arg_id) CVAUX_CONCAT(__cv_trace_arg_extra_ ## arg_id, __LINE__) + +#define CV__TRACE_DEFINE_ARG_(arg_id, name, flags) \ + static CV_TRACE_NS::details::TraceArg::ExtraData* CV__TRACE_ARG_EXTRA_VARNAME(arg_id) = 0; \ + static const CV_TRACE_NS::details::TraceArg \ + CV__TRACE_ARG_VARNAME(arg_id) = { &(CV__TRACE_ARG_EXTRA_VARNAME(arg_id)), name, flags }; + +#define CV__TRACE_ARG_VALUE(arg_id, arg_name, value) \ + CV__TRACE_DEFINE_ARG_(arg_id, arg_name, 0); \ + CV_TRACE_NS::details::traceArg((CV__TRACE_ARG_VARNAME(arg_id)), value); + +#define CV__TRACE_ARG(arg_id) CV_TRACE_ARG_VALUE(arg_id, #arg_id, (arg_id)) + +} // namespace + +#ifndef OPENCV_DISABLE_TRACE +#undef CV_TRACE_FUNCTION +#undef CV_TRACE_FUNCTION_SKIP_NESTED +#if __OPENCV_TRACE +#define CV_TRACE_FUNCTION CV__TRACE_OPENCV_FUNCTION +#define CV_TRACE_FUNCTION_SKIP_NESTED CV__TRACE_OPENCV_FUNCTION_SKIP_NESTED +#else +#define CV_TRACE_FUNCTION CV__TRACE_APP_FUNCTION +#define CV_TRACE_FUNCTION_SKIP_NESTED CV__TRACE_APP_FUNCTION_SKIP_NESTED +#endif + +#undef CV_TRACE_REGION +#define CV_TRACE_REGION CV__TRACE_REGION + +#undef CV_TRACE_REGION_NEXT +#define CV_TRACE_REGION_NEXT CV__TRACE_REGION_NEXT + +#undef CV_TRACE_ARG_VALUE +#define CV_TRACE_ARG_VALUE(arg_id, arg_name, value) \ + if (__region_fn.isActive()) \ + { \ + CV__TRACE_ARG_VALUE(arg_id, arg_name, value); \ + } + +#undef CV_TRACE_ARG +#define CV_TRACE_ARG CV__TRACE_ARG + +#endif // OPENCV_DISABLE_TRACE + +#ifdef OPENCV_TRACE_VERBOSE +#define CV_TRACE_FUNCTION_VERBOSE CV_TRACE_FUNCTION +#define CV_TRACE_REGION_VERBOSE CV_TRACE_REGION +#define CV_TRACE_REGION_NEXT_VERBOSE CV_TRACE_REGION_NEXT +#define CV_TRACE_ARG_VALUE_VERBOSE CV_TRACE_ARG_VALUE +#define CV_TRACE_ARG_VERBOSE CV_TRACE_ARG +#else +#define CV_TRACE_FUNCTION_VERBOSE(...) +#define CV_TRACE_REGION_VERBOSE(...) +#define CV_TRACE_REGION_NEXT_VERBOSE(...) +#define CV_TRACE_ARG_VALUE_VERBOSE(...) +#define CV_TRACE_ARG_VERBOSE(...) +#endif + +//! @endcond + +//! @} + +}}} // namespace + +#endif // OPENCV_TRACE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/va_intel.hpp b/3rdParty/opencv-4.11.0/opencv2/core/va_intel.hpp index b37ce75135..e224a7ae06 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/va_intel.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/va_intel.hpp @@ -1,75 +1,75 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -// Copyright (C) 2015, Itseez, Inc., all rights reserved. -// Third party copyrights are property of their respective owners. - -#ifndef OPENCV_CORE_VA_INTEL_HPP -#define OPENCV_CORE_VA_INTEL_HPP - -#ifndef __cplusplus -# error va_intel.hpp header must be compiled as C++ -#endif - -#include "opencv2/core.hpp" -#include "ocl.hpp" - -#if defined(HAVE_VA) -# include "va/va.h" -#else // HAVE_VA -# if !defined(_VA_H_) - typedef void* VADisplay; - typedef unsigned int VASurfaceID; -# endif // !_VA_H_ -#endif // HAVE_VA - -namespace cv { namespace va_intel { - -/** @addtogroup core_va_intel -This section describes Intel VA-API/OpenCL (CL-VA) interoperability. - -To enable basic VA interoperability build OpenCV with libva library integration enabled: `-DWITH_VA=ON` (corresponding dev package should be installed). - -To enable advanced CL-VA interoperability support on Intel HW, enable option: `-DWITH_VA_INTEL=ON` (OpenCL integration should be enabled which is the default setting). Special runtime environment should be set up in order to use this feature: correct combination of [libva](https://github.com/intel/libva), [OpenCL runtime](https://github.com/intel/compute-runtime) and [media driver](https://github.com/intel/media-driver) should be installed. - -Check usage example for details: samples/va_intel/va_intel_interop.cpp -*/ -//! @{ - -/////////////////// CL-VA Interoperability Functions /////////////////// - -namespace ocl { -using namespace cv::ocl; - -// TODO static functions in the Context class -/** @brief Creates OpenCL context from VA. -@param display - VADisplay for which CL interop should be established. -@param tryInterop - try to set up for interoperability, if true; set up for use slow copy if false. -@return Returns reference to OpenCL Context - */ -CV_EXPORTS Context& initializeContextFromVA(VADisplay display, bool tryInterop = true); - -} // namespace cv::va_intel::ocl - -/** @brief Converts InputArray to VASurfaceID object. -@param display - VADisplay object. -@param src - source InputArray. -@param surface - destination VASurfaceID object. -@param size - size of image represented by VASurfaceID object. - */ -CV_EXPORTS void convertToVASurface(VADisplay display, InputArray src, VASurfaceID surface, Size size); - -/** @brief Converts VASurfaceID object to OutputArray. -@param display - VADisplay object. -@param surface - source VASurfaceID object. -@param size - size of image represented by VASurfaceID object. -@param dst - destination OutputArray. - */ -CV_EXPORTS void convertFromVASurface(VADisplay display, VASurfaceID surface, Size size, OutputArray dst); - -//! @} - -}} // namespace cv::va_intel - -#endif /* OPENCV_CORE_VA_INTEL_HPP */ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +// Copyright (C) 2015, Itseez, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. + +#ifndef OPENCV_CORE_VA_INTEL_HPP +#define OPENCV_CORE_VA_INTEL_HPP + +#ifndef __cplusplus +# error va_intel.hpp header must be compiled as C++ +#endif + +#include "opencv2/core.hpp" +#include "ocl.hpp" + +#if defined(HAVE_VA) +# include "va/va.h" +#else // HAVE_VA +# if !defined(_VA_H_) + typedef void* VADisplay; + typedef unsigned int VASurfaceID; +# endif // !_VA_H_ +#endif // HAVE_VA + +namespace cv { namespace va_intel { + +/** @addtogroup core_va_intel +This section describes Intel VA-API/OpenCL (CL-VA) interoperability. + +To enable basic VA interoperability build OpenCV with libva library integration enabled: `-DWITH_VA=ON` (corresponding dev package should be installed). + +To enable advanced CL-VA interoperability support on Intel HW, enable option: `-DWITH_VA_INTEL=ON` (OpenCL integration should be enabled which is the default setting). Special runtime environment should be set up in order to use this feature: correct combination of [libva](https://github.com/intel/libva), [OpenCL runtime](https://github.com/intel/compute-runtime) and [media driver](https://github.com/intel/media-driver) should be installed. + +Check usage example for details: samples/va_intel/va_intel_interop.cpp +*/ +//! @{ + +/////////////////// CL-VA Interoperability Functions /////////////////// + +namespace ocl { +using namespace cv::ocl; + +// TODO static functions in the Context class +/** @brief Creates OpenCL context from VA. +@param display - VADisplay for which CL interop should be established. +@param tryInterop - try to set up for interoperability, if true; set up for use slow copy if false. +@return Returns reference to OpenCL Context + */ +CV_EXPORTS Context& initializeContextFromVA(VADisplay display, bool tryInterop = true); + +} // namespace cv::va_intel::ocl + +/** @brief Converts InputArray to VASurfaceID object. +@param display - VADisplay object. +@param src - source InputArray. +@param surface - destination VASurfaceID object. +@param size - size of image represented by VASurfaceID object. + */ +CV_EXPORTS void convertToVASurface(VADisplay display, InputArray src, VASurfaceID surface, Size size); + +/** @brief Converts VASurfaceID object to OutputArray. +@param display - VADisplay object. +@param surface - source VASurfaceID object. +@param size - size of image represented by VASurfaceID object. +@param dst - destination OutputArray. + */ +CV_EXPORTS void convertFromVASurface(VADisplay display, VASurfaceID surface, Size size, OutputArray dst); + +//! @} + +}} // namespace cv::va_intel + +#endif /* OPENCV_CORE_VA_INTEL_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/version.hpp b/3rdParty/opencv-4.11.0/opencv2/core/version.hpp index 7c5eaa1437..8a9621f68b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/version.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/version.hpp @@ -1,26 +1,26 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_VERSION_HPP -#define OPENCV_VERSION_HPP - -#define CV_VERSION_MAJOR 4 -#define CV_VERSION_MINOR 11 -#define CV_VERSION_REVISION 0 -#define CV_VERSION_STATUS "" - -#define CVAUX_STR_EXP(__A) #__A -#define CVAUX_STR(__A) CVAUX_STR_EXP(__A) - -#define CVAUX_STRW_EXP(__A) L ## #__A -#define CVAUX_STRW(__A) CVAUX_STRW_EXP(__A) - -#define CV_VERSION CVAUX_STR(CV_VERSION_MAJOR) "." CVAUX_STR(CV_VERSION_MINOR) "." CVAUX_STR(CV_VERSION_REVISION) CV_VERSION_STATUS - -/* old style version constants*/ -#define CV_MAJOR_VERSION CV_VERSION_MAJOR -#define CV_MINOR_VERSION CV_VERSION_MINOR -#define CV_SUBMINOR_VERSION CV_VERSION_REVISION - -#endif // OPENCV_VERSION_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_VERSION_HPP +#define OPENCV_VERSION_HPP + +#define CV_VERSION_MAJOR 4 +#define CV_VERSION_MINOR 11 +#define CV_VERSION_REVISION 0 +#define CV_VERSION_STATUS "" + +#define CVAUX_STR_EXP(__A) #__A +#define CVAUX_STR(__A) CVAUX_STR_EXP(__A) + +#define CVAUX_STRW_EXP(__A) L ## #__A +#define CVAUX_STRW(__A) CVAUX_STRW_EXP(__A) + +#define CV_VERSION CVAUX_STR(CV_VERSION_MAJOR) "." CVAUX_STR(CV_VERSION_MINOR) "." CVAUX_STR(CV_VERSION_REVISION) CV_VERSION_STATUS + +/* old style version constants*/ +#define CV_MAJOR_VERSION CV_VERSION_MAJOR +#define CV_MINOR_VERSION CV_VERSION_MINOR +#define CV_SUBMINOR_VERSION CV_VERSION_REVISION + +#endif // OPENCV_VERSION_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/vsx_utils.hpp b/3rdParty/opencv-4.11.0/opencv2/core/vsx_utils.hpp index 79a1074d59..c285c7edf2 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/vsx_utils.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/vsx_utils.hpp @@ -1,1047 +1,1047 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -#ifndef OPENCV_HAL_VSX_UTILS_HPP -#define OPENCV_HAL_VSX_UTILS_HPP - -#include "opencv2/core/cvdef.h" - -#ifndef SKIP_INCLUDES -# include -#endif - -//! @addtogroup core_utils_vsx -//! @{ -#if CV_VSX - -#define __VSX_S16__(c, v) (c){v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v} -#define __VSX_S8__(c, v) (c){v, v, v, v, v, v, v, v} -#define __VSX_S4__(c, v) (c){v, v, v, v} -#define __VSX_S2__(c, v) (c){v, v} - -typedef __vector unsigned char vec_uchar16; -#define vec_uchar16_set(...) (vec_uchar16){__VA_ARGS__} -#define vec_uchar16_sp(c) (__VSX_S16__(vec_uchar16, (unsigned char)c)) -#define vec_uchar16_c(v) ((vec_uchar16)(v)) -#define vec_uchar16_z vec_uchar16_sp(0) - -typedef __vector signed char vec_char16; -#define vec_char16_set(...) (vec_char16){__VA_ARGS__} -#define vec_char16_sp(c) (__VSX_S16__(vec_char16, (signed char)c)) -#define vec_char16_c(v) ((vec_char16)(v)) -#define vec_char16_z vec_char16_sp(0) - -typedef __vector unsigned short vec_ushort8; -#define vec_ushort8_set(...) (vec_ushort8){__VA_ARGS__} -#define vec_ushort8_sp(c) (__VSX_S8__(vec_ushort8, (unsigned short)c)) -#define vec_ushort8_c(v) ((vec_ushort8)(v)) -#define vec_ushort8_z vec_ushort8_sp(0) - -typedef __vector signed short vec_short8; -#define vec_short8_set(...) (vec_short8){__VA_ARGS__} -#define vec_short8_sp(c) (__VSX_S8__(vec_short8, (signed short)c)) -#define vec_short8_c(v) ((vec_short8)(v)) -#define vec_short8_z vec_short8_sp(0) - -typedef __vector unsigned int vec_uint4; -#define vec_uint4_set(...) (vec_uint4){__VA_ARGS__} -#define vec_uint4_sp(c) (__VSX_S4__(vec_uint4, (unsigned int)c)) -#define vec_uint4_c(v) ((vec_uint4)(v)) -#define vec_uint4_z vec_uint4_sp(0) - -typedef __vector signed int vec_int4; -#define vec_int4_set(...) (vec_int4){__VA_ARGS__} -#define vec_int4_sp(c) (__VSX_S4__(vec_int4, (signed int)c)) -#define vec_int4_c(v) ((vec_int4)(v)) -#define vec_int4_z vec_int4_sp(0) - -typedef __vector float vec_float4; -#define vec_float4_set(...) (vec_float4){__VA_ARGS__} -#define vec_float4_sp(c) (__VSX_S4__(vec_float4, c)) -#define vec_float4_c(v) ((vec_float4)(v)) -#define vec_float4_z vec_float4_sp(0) - -typedef __vector unsigned long long vec_udword2; -#define vec_udword2_set(...) (vec_udword2){__VA_ARGS__} -#define vec_udword2_sp(c) (__VSX_S2__(vec_udword2, (unsigned long long)c)) -#define vec_udword2_c(v) ((vec_udword2)(v)) -#define vec_udword2_z vec_udword2_sp(0) - -typedef __vector signed long long vec_dword2; -#define vec_dword2_set(...) (vec_dword2){__VA_ARGS__} -#define vec_dword2_sp(c) (__VSX_S2__(vec_dword2, (signed long long)c)) -#define vec_dword2_c(v) ((vec_dword2)(v)) -#define vec_dword2_z vec_dword2_sp(0) - -typedef __vector double vec_double2; -#define vec_double2_set(...) (vec_double2){__VA_ARGS__} -#define vec_double2_c(v) ((vec_double2)(v)) -#define vec_double2_sp(c) (__VSX_S2__(vec_double2, c)) -#define vec_double2_z vec_double2_sp(0) - -#define vec_bchar16 __vector __bool char -#define vec_bchar16_set(...) (vec_bchar16){__VA_ARGS__} -#define vec_bchar16_c(v) ((vec_bchar16)(v)) - -#define vec_bshort8 __vector __bool short -#define vec_bshort8_set(...) (vec_bshort8){__VA_ARGS__} -#define vec_bshort8_c(v) ((vec_bshort8)(v)) - -#define vec_bint4 __vector __bool int -#define vec_bint4_set(...) (vec_bint4){__VA_ARGS__} -#define vec_bint4_c(v) ((vec_bint4)(v)) - -#define vec_bdword2 __vector __bool long long -#define vec_bdword2_set(...) (vec_bdword2){__VA_ARGS__} -#define vec_bdword2_c(v) ((vec_bdword2)(v)) - -#define VSX_FINLINE(tp) extern inline tp __attribute__((always_inline)) - -#define VSX_REDIRECT_1RG(rt, rg, fnm, fn2) \ -VSX_FINLINE(rt) fnm(const rg& a) { return fn2(a); } - -#define VSX_REDIRECT_2RG(rt, rg, fnm, fn2) \ -VSX_FINLINE(rt) fnm(const rg& a, const rg& b) { return fn2(a, b); } - -/* - * GCC VSX compatibility -**/ -#if defined(__GNUG__) && !defined(__clang__) - -// inline asm helper -#define VSX_IMPL_1RG(rt, rg, opc, fnm) \ -VSX_FINLINE(rt) fnm(const rg& a) \ -{ rt rs; __asm__ __volatile__(#opc" %x0,%x1" : "=wa" (rs) : "wa" (a)); return rs; } - -#define VSX_IMPL_1VRG(rt, rg, opc, fnm) \ -VSX_FINLINE(rt) fnm(const rg& a) \ -{ rt rs; __asm__ __volatile__(#opc" %0,%1" : "=v" (rs) : "v" (a)); return rs; } - -#define VSX_IMPL_2VRG_F(rt, rg, fopc, fnm) \ -VSX_FINLINE(rt) fnm(const rg& a, const rg& b) \ -{ rt rs; __asm__ __volatile__(fopc : "=v" (rs) : "v" (a), "v" (b)); return rs; } - -#define VSX_IMPL_2VRG(rt, rg, opc, fnm) VSX_IMPL_2VRG_F(rt, rg, #opc" %0,%1,%2", fnm) - -#if __GNUG__ < 8 - - // Support for int4 -> dword2 expanding multiply was added in GCC 8. - #ifdef vec_mule - #undef vec_mule - #endif - #ifdef vec_mulo - #undef vec_mulo - #endif - - VSX_REDIRECT_2RG(vec_ushort8, vec_uchar16, vec_mule, __builtin_vec_mule) - VSX_REDIRECT_2RG(vec_short8, vec_char16, vec_mule, __builtin_vec_mule) - VSX_REDIRECT_2RG(vec_int4, vec_short8, vec_mule, __builtin_vec_mule) - VSX_REDIRECT_2RG(vec_uint4, vec_ushort8, vec_mule, __builtin_vec_mule) - VSX_REDIRECT_2RG(vec_ushort8, vec_uchar16, vec_mulo, __builtin_vec_mulo) - VSX_REDIRECT_2RG(vec_short8, vec_char16, vec_mulo, __builtin_vec_mulo) - VSX_REDIRECT_2RG(vec_int4, vec_short8, vec_mulo, __builtin_vec_mulo) - VSX_REDIRECT_2RG(vec_uint4, vec_ushort8, vec_mulo, __builtin_vec_mulo) - - // dword2 support arrived in ISA 2.07 and GCC 8+ - VSX_IMPL_2VRG(vec_dword2, vec_int4, vmulosw, vec_mule) - VSX_IMPL_2VRG(vec_udword2, vec_uint4, vmulouw, vec_mule) - VSX_IMPL_2VRG(vec_dword2, vec_int4, vmulesw, vec_mulo) - VSX_IMPL_2VRG(vec_udword2, vec_uint4, vmuleuw, vec_mulo) - -#endif - -#if __GNUG__ < 7 -// up to GCC 6 vec_mul only supports precisions and llong -# ifdef vec_mul -# undef vec_mul -# endif -/* - * there's no a direct instruction for supporting 8-bit, 16-bit multiplication in ISA 2.07, - * XLC Implement it by using instruction "multiply even", "multiply odd" and "permute" -**/ -# define VSX_IMPL_MULH(Tvec, cperm) \ - VSX_FINLINE(Tvec) vec_mul(const Tvec& a, const Tvec& b) \ - { \ - static const vec_uchar16 ev_od = {cperm}; \ - return vec_perm((Tvec)vec_mule(a, b), (Tvec)vec_mulo(a, b), ev_od); \ - } - #define VSX_IMPL_MULH_P16 0, 16, 2, 18, 4, 20, 6, 22, 8, 24, 10, 26, 12, 28, 14, 30 - VSX_IMPL_MULH(vec_char16, VSX_IMPL_MULH_P16) - VSX_IMPL_MULH(vec_uchar16, VSX_IMPL_MULH_P16) - #define VSX_IMPL_MULH_P8 0, 1, 16, 17, 4, 5, 20, 21, 8, 9, 24, 25, 12, 13, 28, 29 - VSX_IMPL_MULH(vec_short8, VSX_IMPL_MULH_P8) - VSX_IMPL_MULH(vec_ushort8, VSX_IMPL_MULH_P8) - // vmuluwm can be used for unsigned or signed integers, that's what they said - VSX_IMPL_2VRG(vec_int4, vec_int4, vmuluwm, vec_mul) - VSX_IMPL_2VRG(vec_uint4, vec_uint4, vmuluwm, vec_mul) - // redirect to GCC builtin vec_mul, since it already supports precisions and llong - VSX_REDIRECT_2RG(vec_float4, vec_float4, vec_mul, __builtin_vec_mul) - VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mul, __builtin_vec_mul) - VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mul, __builtin_vec_mul) - VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mul, __builtin_vec_mul) -#endif // __GNUG__ < 7 - -#if __GNUG__ < 6 -/* - * Instruction "compare greater than or equal" in ISA 2.07 only supports single - * and double precision. - * In XLC and new versions of GCC implement integers by using instruction "greater than" and NOR. -**/ -# ifdef vec_cmpge -# undef vec_cmpge -# endif -# ifdef vec_cmple -# undef vec_cmple -# endif -# define vec_cmple(a, b) vec_cmpge(b, a) -# define VSX_IMPL_CMPGE(rt, rg, opc, fnm) \ - VSX_IMPL_2VRG_F(rt, rg, #opc" %0,%2,%1\n\t xxlnor %x0,%x0,%x0", fnm) - - VSX_IMPL_CMPGE(vec_bchar16, vec_char16, vcmpgtsb, vec_cmpge) - VSX_IMPL_CMPGE(vec_bchar16, vec_uchar16, vcmpgtub, vec_cmpge) - VSX_IMPL_CMPGE(vec_bshort8, vec_short8, vcmpgtsh, vec_cmpge) - VSX_IMPL_CMPGE(vec_bshort8, vec_ushort8, vcmpgtuh, vec_cmpge) - VSX_IMPL_CMPGE(vec_bint4, vec_int4, vcmpgtsw, vec_cmpge) - VSX_IMPL_CMPGE(vec_bint4, vec_uint4, vcmpgtuw, vec_cmpge) - VSX_IMPL_CMPGE(vec_bdword2, vec_dword2, vcmpgtsd, vec_cmpge) - VSX_IMPL_CMPGE(vec_bdword2, vec_udword2, vcmpgtud, vec_cmpge) - -// redirect to GCC builtin cmpge, since it already supports precisions - VSX_REDIRECT_2RG(vec_bint4, vec_float4, vec_cmpge, __builtin_vec_cmpge) - VSX_REDIRECT_2RG(vec_bdword2, vec_double2, vec_cmpge, __builtin_vec_cmpge) - -// up to gcc5 vec_nor doesn't support bool long long -# undef vec_nor - template - VSX_REDIRECT_2RG(T, T, vec_nor, __builtin_vec_nor) - - VSX_FINLINE(vec_bdword2) vec_nor(const vec_bdword2& a, const vec_bdword2& b) - { return vec_bdword2_c(__builtin_vec_nor(vec_dword2_c(a), vec_dword2_c(b))); } - -// vec_packs doesn't support double words in gcc4 and old versions of gcc5 -# undef vec_packs - VSX_REDIRECT_2RG(vec_char16, vec_short8, vec_packs, __builtin_vec_packs) - VSX_REDIRECT_2RG(vec_uchar16, vec_ushort8, vec_packs, __builtin_vec_packs) - VSX_REDIRECT_2RG(vec_short8, vec_int4, vec_packs, __builtin_vec_packs) - VSX_REDIRECT_2RG(vec_ushort8, vec_uint4, vec_packs, __builtin_vec_packs) - - VSX_IMPL_2VRG_F(vec_int4, vec_dword2, "vpksdss %0,%2,%1", vec_packs) - VSX_IMPL_2VRG_F(vec_uint4, vec_udword2, "vpkudus %0,%2,%1", vec_packs) -#endif // __GNUG__ < 6 - -#if __GNUG__ < 5 -// vec_xxpermdi in gcc4 missing little-endian supports just like clang -# define vec_permi(a, b, c) vec_xxpermdi(b, a, (3 ^ (((c) & 1) << 1 | (c) >> 1))) -// same as vec_xxpermdi -# undef vec_vbpermq - VSX_IMPL_2VRG(vec_udword2, vec_uchar16, vbpermq, vec_vbpermq) - VSX_IMPL_2VRG(vec_dword2, vec_char16, vbpermq, vec_vbpermq) -#else -# define vec_permi vec_xxpermdi -#endif // __GNUG__ < 5 - -// shift left double by word immediate -#ifndef vec_sldw -# define vec_sldw __builtin_vsx_xxsldwi -#endif - -// vector population count -VSX_IMPL_1VRG(vec_uchar16, vec_uchar16, vpopcntb, vec_popcntu) -VSX_IMPL_1VRG(vec_uchar16, vec_char16, vpopcntb, vec_popcntu) -VSX_IMPL_1VRG(vec_ushort8, vec_ushort8, vpopcnth, vec_popcntu) -VSX_IMPL_1VRG(vec_ushort8, vec_short8, vpopcnth, vec_popcntu) -VSX_IMPL_1VRG(vec_uint4, vec_uint4, vpopcntw, vec_popcntu) -VSX_IMPL_1VRG(vec_uint4, vec_int4, vpopcntw, vec_popcntu) -VSX_IMPL_1VRG(vec_udword2, vec_udword2, vpopcntd, vec_popcntu) -VSX_IMPL_1VRG(vec_udword2, vec_dword2, vpopcntd, vec_popcntu) - -// converts between single and double-precision -VSX_REDIRECT_1RG(vec_float4, vec_double2, vec_cvfo, __builtin_vsx_xvcvdpsp) -VSX_REDIRECT_1RG(vec_double2, vec_float4, vec_cvfo, __builtin_vsx_xvcvspdp) - -// converts word and doubleword to double-precision -#undef vec_ctd -VSX_IMPL_1RG(vec_double2, vec_int4, xvcvsxwdp, vec_ctdo) -VSX_IMPL_1RG(vec_double2, vec_uint4, xvcvuxwdp, vec_ctdo) -VSX_IMPL_1RG(vec_double2, vec_dword2, xvcvsxddp, vec_ctd) -VSX_IMPL_1RG(vec_double2, vec_udword2, xvcvuxddp, vec_ctd) - -// converts word and doubleword to single-precision -#undef vec_ctf -VSX_IMPL_1RG(vec_float4, vec_int4, xvcvsxwsp, vec_ctf) -VSX_IMPL_1RG(vec_float4, vec_uint4, xvcvuxwsp, vec_ctf) -VSX_IMPL_1RG(vec_float4, vec_dword2, xvcvsxdsp, vec_ctfo) -VSX_IMPL_1RG(vec_float4, vec_udword2, xvcvuxdsp, vec_ctfo) - -// converts single and double precision to signed word -#undef vec_cts -VSX_IMPL_1RG(vec_int4, vec_double2, xvcvdpsxws, vec_ctso) -VSX_IMPL_1RG(vec_int4, vec_float4, xvcvspsxws, vec_cts) - -// converts single and double precision to unsigned word -#undef vec_ctu -VSX_IMPL_1RG(vec_uint4, vec_double2, xvcvdpuxws, vec_ctuo) -VSX_IMPL_1RG(vec_uint4, vec_float4, xvcvspuxws, vec_ctu) - -// converts single and double precision to signed doubleword -#undef vec_ctsl -VSX_IMPL_1RG(vec_dword2, vec_double2, xvcvdpsxds, vec_ctsl) -VSX_IMPL_1RG(vec_dword2, vec_float4, xvcvspsxds, vec_ctslo) - -// converts single and double precision to unsigned doubleword -#undef vec_ctul -VSX_IMPL_1RG(vec_udword2, vec_double2, xvcvdpuxds, vec_ctul) -VSX_IMPL_1RG(vec_udword2, vec_float4, xvcvspuxds, vec_ctulo) - -// just in case if GCC doesn't define it -#ifndef vec_xl -# define vec_xl vec_vsx_ld -# define vec_xst vec_vsx_st -#endif - -#endif // GCC VSX compatibility - -/* - * CLANG VSX compatibility -**/ -#if defined(__clang__) && !defined(__IBMCPP__) - -/* - * CLANG doesn't support %x in the inline asm template which fixes register number - * when using any of the register constraints wa, wd, wf - * - * For more explanation checkout PowerPC and IBM RS6000 in https://gcc.gnu.org/onlinedocs/gcc/Machine-Constraints.html - * Also there's already an open bug https://bugs.llvm.org/show_bug.cgi?id=31837 - * - * So we're not able to use inline asm and only use built-in functions that CLANG supports - * and use __builtin_convertvector if clang missing any of vector conversions built-in functions - * - * todo: clang asm template bug is fixed, need to reconsider the current workarounds. -*/ - -// convert vector helper -#define VSX_IMPL_CONVERT(rt, rg, fnm) \ -VSX_FINLINE(rt) fnm(const rg& a) { return __builtin_convertvector(a, rt); } - -#ifndef vec_permi -#if __clang_major__ < 5 -// implement vec_permi in a dirty way -# define VSX_IMPL_CLANG_4_PERMI(Tvec) \ - VSX_FINLINE(Tvec) vec_permi(const Tvec& a, const Tvec& b, unsigned const char c) \ - { \ - switch (c) \ - { \ - case 0: \ - return vec_mergeh(a, b); \ - case 1: \ - return vec_mergel(vec_mergeh(a, a), b); \ - case 2: \ - return vec_mergeh(vec_mergel(a, a), b); \ - default: \ - return vec_mergel(a, b); \ - } \ - } - VSX_IMPL_CLANG_4_PERMI(vec_udword2) - VSX_IMPL_CLANG_4_PERMI(vec_dword2) - VSX_IMPL_CLANG_4_PERMI(vec_double2) - -// vec_xxsldwi is missing in clang 4 -# define vec_xxsldwi(a, b, c) vec_sld(a, b, (c) * 4) -#else -// vec_xxpermdi is missing little-endian supports in clang 4 just like gcc4 -# define vec_permi(a, b, c) vec_xxpermdi(b, a, (3 ^ (((c) & 1) << 1 | (c) >> 1))) -#endif // __clang_major__ < 5 -#endif - -// shift left double by word immediate -#ifndef vec_sldw -# define vec_sldw vec_xxsldwi -#endif - -#if __clang_major__ < 13 -// Implement vec_rsqrt since clang only supports vec_rsqrte -#ifndef vec_rsqrt - VSX_FINLINE(vec_float4) vec_rsqrt(const vec_float4& a) - { return vec_div(vec_float4_sp(1), vec_sqrt(a)); } - - VSX_FINLINE(vec_double2) vec_rsqrt(const vec_double2& a) - { return vec_div(vec_double2_sp(1), vec_sqrt(a)); } -#endif - -// vec_promote missing support for doubleword -VSX_FINLINE(vec_dword2) vec_promote(long long a, int b) -{ - vec_dword2 ret = vec_dword2_z; - ret[b & 1] = a; - return ret; -} - -VSX_FINLINE(vec_udword2) vec_promote(unsigned long long a, int b) -{ - vec_udword2 ret = vec_udword2_z; - ret[b & 1] = a; - return ret; -} -#endif - -// vec_popcnt should return unsigned but clang has different thought just like gcc in vec_vpopcnt -#define VSX_IMPL_POPCNTU(Tvec, Tvec2, ucast) \ -VSX_FINLINE(Tvec) vec_popcntu(const Tvec2& a) \ -{ return ucast(vec_popcnt(a)); } -VSX_IMPL_POPCNTU(vec_uchar16, vec_char16, vec_uchar16_c); -VSX_IMPL_POPCNTU(vec_ushort8, vec_short8, vec_ushort8_c); -VSX_IMPL_POPCNTU(vec_uint4, vec_int4, vec_uint4_c); -VSX_IMPL_POPCNTU(vec_udword2, vec_dword2, vec_udword2_c); -// redirect unsigned types -VSX_REDIRECT_1RG(vec_uchar16, vec_uchar16, vec_popcntu, vec_popcnt) -VSX_REDIRECT_1RG(vec_ushort8, vec_ushort8, vec_popcntu, vec_popcnt) -VSX_REDIRECT_1RG(vec_uint4, vec_uint4, vec_popcntu, vec_popcnt) -VSX_REDIRECT_1RG(vec_udword2, vec_udword2, vec_popcntu, vec_popcnt) - -// converts between single and double precision -VSX_REDIRECT_1RG(vec_float4, vec_double2, vec_cvfo, __builtin_vsx_xvcvdpsp) -VSX_REDIRECT_1RG(vec_double2, vec_float4, vec_cvfo, __builtin_vsx_xvcvspdp) - -// converts word and doubleword to double-precision -#ifdef vec_ctd -# undef vec_ctd -#endif -VSX_REDIRECT_1RG(vec_double2, vec_int4, vec_ctdo, __builtin_vsx_xvcvsxwdp) -VSX_REDIRECT_1RG(vec_double2, vec_uint4, vec_ctdo, __builtin_vsx_xvcvuxwdp) - -VSX_IMPL_CONVERT(vec_double2, vec_dword2, vec_ctd) -VSX_IMPL_CONVERT(vec_double2, vec_udword2, vec_ctd) - -// converts word and doubleword to single-precision -#if __clang_major__ > 4 -# undef vec_ctf -#endif -VSX_IMPL_CONVERT(vec_float4, vec_int4, vec_ctf) -VSX_IMPL_CONVERT(vec_float4, vec_uint4, vec_ctf) -VSX_REDIRECT_1RG(vec_float4, vec_dword2, vec_ctfo, __builtin_vsx_xvcvsxdsp) -VSX_REDIRECT_1RG(vec_float4, vec_udword2, vec_ctfo, __builtin_vsx_xvcvuxdsp) - -// converts single and double precision to signed word -#if __clang_major__ > 4 -# undef vec_cts -#endif -VSX_REDIRECT_1RG(vec_int4, vec_double2, vec_ctso, __builtin_vsx_xvcvdpsxws) -VSX_IMPL_CONVERT(vec_int4, vec_float4, vec_cts) - -// converts single and double precision to unsigned word -#if __clang_major__ > 4 -# undef vec_ctu -#endif -VSX_REDIRECT_1RG(vec_uint4, vec_double2, vec_ctuo, __builtin_vsx_xvcvdpuxws) -VSX_IMPL_CONVERT(vec_uint4, vec_float4, vec_ctu) - -// converts single and double precision to signed doubleword -#ifdef vec_ctsl -# undef vec_ctsl -#endif -VSX_IMPL_CONVERT(vec_dword2, vec_double2, vec_ctsl) -// __builtin_convertvector unable to convert, xvcvspsxds is missing on it -VSX_FINLINE(vec_dword2) vec_ctslo(const vec_float4& a) -{ return vec_ctsl(vec_cvfo(a)); } - -// converts single and double precision to unsigned doubleword -#ifdef vec_ctul -# undef vec_ctul -#endif -VSX_IMPL_CONVERT(vec_udword2, vec_double2, vec_ctul) -// __builtin_convertvector unable to convert, xvcvspuxds is missing on it -VSX_FINLINE(vec_udword2) vec_ctulo(const vec_float4& a) -{ return vec_ctul(vec_cvfo(a)); } - -#endif // CLANG VSX compatibility - -/* - * Common GCC, CLANG compatibility -**/ -#if defined(__GNUG__) && !defined(__IBMCPP__) - -#ifdef vec_cvf -# undef vec_cvf -#endif - -#define VSX_IMPL_CONV_EVEN_4_2(rt, rg, fnm, fn2) \ -VSX_FINLINE(rt) fnm(const rg& a) \ -{ return fn2(vec_sldw(a, a, 1)); } - -VSX_IMPL_CONV_EVEN_4_2(vec_double2, vec_float4, vec_cvf, vec_cvfo) -VSX_IMPL_CONV_EVEN_4_2(vec_double2, vec_int4, vec_ctd, vec_ctdo) -VSX_IMPL_CONV_EVEN_4_2(vec_double2, vec_uint4, vec_ctd, vec_ctdo) - -VSX_IMPL_CONV_EVEN_4_2(vec_dword2, vec_float4, vec_ctsl, vec_ctslo) -VSX_IMPL_CONV_EVEN_4_2(vec_udword2, vec_float4, vec_ctul, vec_ctulo) - -#define VSX_IMPL_CONV_EVEN_2_4(rt, rg, fnm, fn2) \ -VSX_FINLINE(rt) fnm(const rg& a) \ -{ \ - rt v4 = fn2(a); \ - return vec_sldw(v4, v4, 3); \ -} - -VSX_IMPL_CONV_EVEN_2_4(vec_float4, vec_double2, vec_cvf, vec_cvfo) -VSX_IMPL_CONV_EVEN_2_4(vec_float4, vec_dword2, vec_ctf, vec_ctfo) -VSX_IMPL_CONV_EVEN_2_4(vec_float4, vec_udword2, vec_ctf, vec_ctfo) - -VSX_IMPL_CONV_EVEN_2_4(vec_int4, vec_double2, vec_cts, vec_ctso) -VSX_IMPL_CONV_EVEN_2_4(vec_uint4, vec_double2, vec_ctu, vec_ctuo) - -// Only for Eigen! -/* - * changing behavior of conversion intrinsics for gcc has effect on Eigen - * so we redefine old behavior again only on gcc, clang -*/ -#if !defined(__clang__) || __clang_major__ > 4 - // ignoring second arg since Eigen only truncates toward zero -# define VSX_IMPL_CONV_2VARIANT(rt, rg, fnm, fn2) \ - VSX_FINLINE(rt) fnm(const rg& a, int only_truncate) \ - { \ - assert(only_truncate == 0); \ - CV_UNUSED(only_truncate); \ - return fn2(a); \ - } - VSX_IMPL_CONV_2VARIANT(vec_int4, vec_float4, vec_cts, vec_cts) - VSX_IMPL_CONV_2VARIANT(vec_uint4, vec_float4, vec_ctu, vec_ctu) - VSX_IMPL_CONV_2VARIANT(vec_float4, vec_int4, vec_ctf, vec_ctf) - VSX_IMPL_CONV_2VARIANT(vec_float4, vec_uint4, vec_ctf, vec_ctf) - // define vec_cts for converting double precision to signed doubleword - // which isn't compatible with xlc but its okay since Eigen only uses it for gcc - VSX_IMPL_CONV_2VARIANT(vec_dword2, vec_double2, vec_cts, vec_ctsl) -#endif // Eigen - -#endif // Common GCC, CLANG compatibility - -/* - * XLC VSX compatibility -**/ -#if defined(__IBMCPP__) - -// vector population count -#define vec_popcntu vec_popcnt - -// overload and redirect with setting second arg to zero -// since we only support conversions without the second arg -#define VSX_IMPL_OVERLOAD_Z2(rt, rg, fnm) \ -VSX_FINLINE(rt) fnm(const rg& a) { return fnm(a, 0); } - -VSX_IMPL_OVERLOAD_Z2(vec_double2, vec_int4, vec_ctd) -VSX_IMPL_OVERLOAD_Z2(vec_double2, vec_uint4, vec_ctd) -VSX_IMPL_OVERLOAD_Z2(vec_double2, vec_dword2, vec_ctd) -VSX_IMPL_OVERLOAD_Z2(vec_double2, vec_udword2, vec_ctd) - -VSX_IMPL_OVERLOAD_Z2(vec_float4, vec_int4, vec_ctf) -VSX_IMPL_OVERLOAD_Z2(vec_float4, vec_uint4, vec_ctf) -VSX_IMPL_OVERLOAD_Z2(vec_float4, vec_dword2, vec_ctf) -VSX_IMPL_OVERLOAD_Z2(vec_float4, vec_udword2, vec_ctf) - -VSX_IMPL_OVERLOAD_Z2(vec_int4, vec_double2, vec_cts) -VSX_IMPL_OVERLOAD_Z2(vec_int4, vec_float4, vec_cts) - -VSX_IMPL_OVERLOAD_Z2(vec_uint4, vec_double2, vec_ctu) -VSX_IMPL_OVERLOAD_Z2(vec_uint4, vec_float4, vec_ctu) - -VSX_IMPL_OVERLOAD_Z2(vec_dword2, vec_double2, vec_ctsl) -VSX_IMPL_OVERLOAD_Z2(vec_dword2, vec_float4, vec_ctsl) - -VSX_IMPL_OVERLOAD_Z2(vec_udword2, vec_double2, vec_ctul) -VSX_IMPL_OVERLOAD_Z2(vec_udword2, vec_float4, vec_ctul) - -// fixme: implement conversions of odd-numbered elements in a dirty way -// since xlc doesn't support VSX registers operand in inline asm. -#define VSX_IMPL_CONV_ODD_4_2(rt, rg, fnm, fn2) \ -VSX_FINLINE(rt) fnm(const rg& a) { return fn2(vec_sldw(a, a, 3)); } - -VSX_IMPL_CONV_ODD_4_2(vec_double2, vec_float4, vec_cvfo, vec_cvf) -VSX_IMPL_CONV_ODD_4_2(vec_double2, vec_int4, vec_ctdo, vec_ctd) -VSX_IMPL_CONV_ODD_4_2(vec_double2, vec_uint4, vec_ctdo, vec_ctd) - -VSX_IMPL_CONV_ODD_4_2(vec_dword2, vec_float4, vec_ctslo, vec_ctsl) -VSX_IMPL_CONV_ODD_4_2(vec_udword2, vec_float4, vec_ctulo, vec_ctul) - -#define VSX_IMPL_CONV_ODD_2_4(rt, rg, fnm, fn2) \ -VSX_FINLINE(rt) fnm(const rg& a) \ -{ \ - rt v4 = fn2(a); \ - return vec_sldw(v4, v4, 1); \ -} - -VSX_IMPL_CONV_ODD_2_4(vec_float4, vec_double2, vec_cvfo, vec_cvf) -VSX_IMPL_CONV_ODD_2_4(vec_float4, vec_dword2, vec_ctfo, vec_ctf) -VSX_IMPL_CONV_ODD_2_4(vec_float4, vec_udword2, vec_ctfo, vec_ctf) - -VSX_IMPL_CONV_ODD_2_4(vec_int4, vec_double2, vec_ctso, vec_cts) -VSX_IMPL_CONV_ODD_2_4(vec_uint4, vec_double2, vec_ctuo, vec_ctu) - -#endif // XLC VSX compatibility - -// ignore GCC warning that caused by -Wunused-but-set-variable in rare cases -#if defined(__GNUG__) && !defined(__clang__) -# define VSX_UNUSED(Tvec) Tvec __attribute__((__unused__)) -#else // CLANG, XLC -# define VSX_UNUSED(Tvec) Tvec -#endif - -// gcc can find his way in casting log int and XLC, CLANG ambiguous -#if defined(__clang__) || defined(__IBMCPP__) - VSX_FINLINE(vec_udword2) vec_splats(uint64 v) - { return vec_splats((unsigned long long) v); } - - VSX_FINLINE(vec_dword2) vec_splats(int64 v) - { return vec_splats((long long) v); } - - VSX_FINLINE(vec_udword2) vec_promote(uint64 a, int b) - { return vec_promote((unsigned long long) a, b); } - - VSX_FINLINE(vec_dword2) vec_promote(int64 a, int b) - { return vec_promote((long long) a, b); } -#endif - -/* - * implement vsx_ld(offset, pointer), vsx_st(vector, offset, pointer) - * load and set using offset depend on the pointer type - * - * implement vsx_ldf(offset, pointer), vsx_stf(vector, offset, pointer) - * load and set using offset depend on fixed bytes size - * - * Note: In clang vec_xl and vec_xst fails to load unaligned addresses - * so we are using vec_vsx_ld, vec_vsx_st instead -*/ - -#if defined(__clang__) && !defined(__IBMCPP__) -# define vsx_ldf vec_vsx_ld -# define vsx_stf vec_vsx_st -#else // GCC , XLC -# define vsx_ldf vec_xl -# define vsx_stf vec_xst -#endif - -#define VSX_OFFSET(o, p) ((o) * sizeof(*(p))) -#define vsx_ld(o, p) vsx_ldf(VSX_OFFSET(o, p), p) -#define vsx_st(v, o, p) vsx_stf(v, VSX_OFFSET(o, p), p) - -/* - * implement vsx_ld2(offset, pointer), vsx_st2(vector, offset, pointer) to load and store double words - * In GCC vec_xl and vec_xst it maps to vec_vsx_ld, vec_vsx_st which doesn't support long long - * and in CLANG we are using vec_vsx_ld, vec_vsx_st because vec_xl, vec_xst fails to load unaligned addresses - * - * In XLC vec_xl and vec_xst fail to cast int64(long int) to long long -*/ -#if (defined(__GNUG__) || defined(__clang__)) && !defined(__IBMCPP__) - VSX_FINLINE(vec_udword2) vsx_ld2(long o, const uint64* p) - { return vec_udword2_c(vsx_ldf(VSX_OFFSET(o, p), (unsigned int*)p)); } - - VSX_FINLINE(vec_dword2) vsx_ld2(long o, const int64* p) - { return vec_dword2_c(vsx_ldf(VSX_OFFSET(o, p), (int*)p)); } - - VSX_FINLINE(void) vsx_st2(const vec_udword2& vec, long o, uint64* p) - { vsx_stf(vec_uint4_c(vec), VSX_OFFSET(o, p), (unsigned int*)p); } - - VSX_FINLINE(void) vsx_st2(const vec_dword2& vec, long o, int64* p) - { vsx_stf(vec_int4_c(vec), VSX_OFFSET(o, p), (int*)p); } -#else // XLC - VSX_FINLINE(vec_udword2) vsx_ld2(long o, const uint64* p) - { return vsx_ldf(VSX_OFFSET(o, p), (unsigned long long*)p); } - - VSX_FINLINE(vec_dword2) vsx_ld2(long o, const int64* p) - { return vsx_ldf(VSX_OFFSET(o, p), (long long*)p); } - - VSX_FINLINE(void) vsx_st2(const vec_udword2& vec, long o, uint64* p) - { vsx_stf(vec, VSX_OFFSET(o, p), (unsigned long long*)p); } - - VSX_FINLINE(void) vsx_st2(const vec_dword2& vec, long o, int64* p) - { vsx_stf(vec, VSX_OFFSET(o, p), (long long*)p); } -#endif - -// Store lower 8 byte -#define vec_st_l8(v, p) *((uint64*)(p)) = vec_extract(vec_udword2_c(v), 0) - -// Store higher 8 byte -#define vec_st_h8(v, p) *((uint64*)(p)) = vec_extract(vec_udword2_c(v), 1) - -// Load 64-bits of integer data to lower part -#define VSX_IMPL_LOAD_L8(Tvec, Tp) \ -VSX_FINLINE(Tvec) vec_ld_l8(const Tp *p) \ -{ return ((Tvec)vec_promote(*((uint64*)p), 0)); } - -VSX_IMPL_LOAD_L8(vec_uchar16, uchar) -VSX_IMPL_LOAD_L8(vec_char16, schar) -VSX_IMPL_LOAD_L8(vec_ushort8, ushort) -VSX_IMPL_LOAD_L8(vec_short8, short) -VSX_IMPL_LOAD_L8(vec_uint4, uint) -VSX_IMPL_LOAD_L8(vec_int4, int) -VSX_IMPL_LOAD_L8(vec_float4, float) -VSX_IMPL_LOAD_L8(vec_udword2, uint64) -VSX_IMPL_LOAD_L8(vec_dword2, int64) -VSX_IMPL_LOAD_L8(vec_double2, double) - -// logical not -#define vec_not(a) vec_nor(a, a) - -// power9 yaya -// not equal -#ifndef vec_cmpne -# define vec_cmpne(a, b) vec_not(vec_cmpeq(a, b)) -#endif - -// absolute difference -#ifndef _ARCH_PWR9 -# undef vec_absd -# define vec_absd(a, b) vec_sub(vec_max(a, b), vec_min(a, b)) -#endif - -/* - * Implement vec_unpacklu and vec_unpackhu - * since vec_unpackl, vec_unpackh only support signed integers -**/ -#define VSX_IMPL_UNPACKU(rt, rg, zero) \ -VSX_FINLINE(rt) vec_unpacklu(const rg& a) \ -{ return (rt)(vec_mergel(a, zero)); } \ -VSX_FINLINE(rt) vec_unpackhu(const rg& a) \ -{ return (rt)(vec_mergeh(a, zero)); } - -VSX_IMPL_UNPACKU(vec_ushort8, vec_uchar16, vec_uchar16_z) -VSX_IMPL_UNPACKU(vec_uint4, vec_ushort8, vec_ushort8_z) -VSX_IMPL_UNPACKU(vec_udword2, vec_uint4, vec_uint4_z) - -/* - * Implement vec_mergesqe and vec_mergesqo - * Merges the sequence values of even and odd elements of two vectors -*/ -#define VSX_IMPL_PERM(rt, fnm, ...) \ -VSX_FINLINE(rt) fnm(const rt& a, const rt& b) \ -{ static const vec_uchar16 perm = {__VA_ARGS__}; return vec_perm(a, b, perm); } - -// 16 -#define perm16_mergesqe 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30 -#define perm16_mergesqo 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 -VSX_IMPL_PERM(vec_uchar16, vec_mergesqe, perm16_mergesqe) -VSX_IMPL_PERM(vec_uchar16, vec_mergesqo, perm16_mergesqo) -VSX_IMPL_PERM(vec_char16, vec_mergesqe, perm16_mergesqe) -VSX_IMPL_PERM(vec_char16, vec_mergesqo, perm16_mergesqo) -// 8 -#define perm8_mergesqe 0, 1, 4, 5, 8, 9, 12, 13, 16, 17, 20, 21, 24, 25, 28, 29 -#define perm8_mergesqo 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 -VSX_IMPL_PERM(vec_ushort8, vec_mergesqe, perm8_mergesqe) -VSX_IMPL_PERM(vec_ushort8, vec_mergesqo, perm8_mergesqo) -VSX_IMPL_PERM(vec_short8, vec_mergesqe, perm8_mergesqe) -VSX_IMPL_PERM(vec_short8, vec_mergesqo, perm8_mergesqo) -// 4 -#define perm4_mergesqe 0, 1, 2, 3, 8, 9, 10, 11, 16, 17, 18, 19, 24, 25, 26, 27 -#define perm4_mergesqo 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 -VSX_IMPL_PERM(vec_uint4, vec_mergesqe, perm4_mergesqe) -VSX_IMPL_PERM(vec_uint4, vec_mergesqo, perm4_mergesqo) -VSX_IMPL_PERM(vec_int4, vec_mergesqe, perm4_mergesqe) -VSX_IMPL_PERM(vec_int4, vec_mergesqo, perm4_mergesqo) -VSX_IMPL_PERM(vec_float4, vec_mergesqe, perm4_mergesqe) -VSX_IMPL_PERM(vec_float4, vec_mergesqo, perm4_mergesqo) -// 2 -VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mergesqe, vec_mergeh) -VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mergesqo, vec_mergel) -VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mergesqe, vec_mergeh) -VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mergesqo, vec_mergel) -VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mergesqe, vec_mergeh) -VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mergesqo, vec_mergel) - -/* - * Implement vec_mergesqh and vec_mergesql - * Merges the sequence most and least significant halves of two vectors -*/ -#define VSX_IMPL_MERGESQHL(Tvec) \ -VSX_FINLINE(Tvec) vec_mergesqh(const Tvec& a, const Tvec& b) \ -{ return (Tvec)vec_mergeh(vec_udword2_c(a), vec_udword2_c(b)); } \ -VSX_FINLINE(Tvec) vec_mergesql(const Tvec& a, const Tvec& b) \ -{ return (Tvec)vec_mergel(vec_udword2_c(a), vec_udword2_c(b)); } -VSX_IMPL_MERGESQHL(vec_uchar16) -VSX_IMPL_MERGESQHL(vec_char16) -VSX_IMPL_MERGESQHL(vec_ushort8) -VSX_IMPL_MERGESQHL(vec_short8) -VSX_IMPL_MERGESQHL(vec_uint4) -VSX_IMPL_MERGESQHL(vec_int4) -VSX_IMPL_MERGESQHL(vec_float4) -VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mergesqh, vec_mergeh) -VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mergesql, vec_mergel) -VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mergesqh, vec_mergeh) -VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mergesql, vec_mergel) -VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mergesqh, vec_mergeh) -VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mergesql, vec_mergel) - - -// 2 and 4 channels interleave for all types except 2 lanes -#define VSX_IMPL_ST_INTERLEAVE(Tp, Tvec) \ -VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, Tp* ptr) \ -{ \ - vsx_stf(vec_mergeh(a, b), 0, ptr); \ - vsx_stf(vec_mergel(a, b), 16, ptr); \ -} \ -VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ - const Tvec& c, const Tvec& d, Tp* ptr) \ -{ \ - Tvec ac = vec_mergeh(a, c); \ - Tvec bd = vec_mergeh(b, d); \ - vsx_stf(vec_mergeh(ac, bd), 0, ptr); \ - vsx_stf(vec_mergel(ac, bd), 16, ptr); \ - ac = vec_mergel(a, c); \ - bd = vec_mergel(b, d); \ - vsx_stf(vec_mergeh(ac, bd), 32, ptr); \ - vsx_stf(vec_mergel(ac, bd), 48, ptr); \ -} -VSX_IMPL_ST_INTERLEAVE(uchar, vec_uchar16) -VSX_IMPL_ST_INTERLEAVE(schar, vec_char16) -VSX_IMPL_ST_INTERLEAVE(ushort, vec_ushort8) -VSX_IMPL_ST_INTERLEAVE(short, vec_short8) -VSX_IMPL_ST_INTERLEAVE(uint, vec_uint4) -VSX_IMPL_ST_INTERLEAVE(int, vec_int4) -VSX_IMPL_ST_INTERLEAVE(float, vec_float4) - -// 2 and 4 channels deinterleave for 16 lanes -#define VSX_IMPL_ST_DINTERLEAVE_8(Tp, Tvec) \ -VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b) \ -{ \ - Tvec v0 = vsx_ld(0, ptr); \ - Tvec v1 = vsx_ld(16, ptr); \ - a = vec_mergesqe(v0, v1); \ - b = vec_mergesqo(v0, v1); \ -} \ -VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, \ - Tvec& c, Tvec& d) \ -{ \ - Tvec v0 = vsx_ld(0, ptr); \ - Tvec v1 = vsx_ld(16, ptr); \ - Tvec v2 = vsx_ld(32, ptr); \ - Tvec v3 = vsx_ld(48, ptr); \ - Tvec m0 = vec_mergesqe(v0, v1); \ - Tvec m1 = vec_mergesqe(v2, v3); \ - a = vec_mergesqe(m0, m1); \ - c = vec_mergesqo(m0, m1); \ - m0 = vec_mergesqo(v0, v1); \ - m1 = vec_mergesqo(v2, v3); \ - b = vec_mergesqe(m0, m1); \ - d = vec_mergesqo(m0, m1); \ -} -VSX_IMPL_ST_DINTERLEAVE_8(uchar, vec_uchar16) -VSX_IMPL_ST_DINTERLEAVE_8(schar, vec_char16) - -// 2 and 4 channels deinterleave for 8 lanes -#define VSX_IMPL_ST_DINTERLEAVE_16(Tp, Tvec) \ -VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b) \ -{ \ - Tvec v0 = vsx_ld(0, ptr); \ - Tvec v1 = vsx_ld(8, ptr); \ - a = vec_mergesqe(v0, v1); \ - b = vec_mergesqo(v0, v1); \ -} \ -VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, \ - Tvec& c, Tvec& d) \ -{ \ - Tvec v0 = vsx_ld(0, ptr); \ - Tvec v1 = vsx_ld(8, ptr); \ - Tvec m0 = vec_mergeh(v0, v1); \ - Tvec m1 = vec_mergel(v0, v1); \ - Tvec ab0 = vec_mergeh(m0, m1); \ - Tvec cd0 = vec_mergel(m0, m1); \ - v0 = vsx_ld(16, ptr); \ - v1 = vsx_ld(24, ptr); \ - m0 = vec_mergeh(v0, v1); \ - m1 = vec_mergel(v0, v1); \ - Tvec ab1 = vec_mergeh(m0, m1); \ - Tvec cd1 = vec_mergel(m0, m1); \ - a = vec_mergesqh(ab0, ab1); \ - b = vec_mergesql(ab0, ab1); \ - c = vec_mergesqh(cd0, cd1); \ - d = vec_mergesql(cd0, cd1); \ -} -VSX_IMPL_ST_DINTERLEAVE_16(ushort, vec_ushort8) -VSX_IMPL_ST_DINTERLEAVE_16(short, vec_short8) - -// 2 and 4 channels deinterleave for 4 lanes -#define VSX_IMPL_ST_DINTERLEAVE_32(Tp, Tvec) \ -VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b) \ -{ \ - a = vsx_ld(0, ptr); \ - b = vsx_ld(4, ptr); \ - Tvec m0 = vec_mergeh(a, b); \ - Tvec m1 = vec_mergel(a, b); \ - a = vec_mergeh(m0, m1); \ - b = vec_mergel(m0, m1); \ -} \ -VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, \ - Tvec& c, Tvec& d) \ -{ \ - Tvec v0 = vsx_ld(0, ptr); \ - Tvec v1 = vsx_ld(4, ptr); \ - Tvec v2 = vsx_ld(8, ptr); \ - Tvec v3 = vsx_ld(12, ptr); \ - Tvec m0 = vec_mergeh(v0, v2); \ - Tvec m1 = vec_mergeh(v1, v3); \ - a = vec_mergeh(m0, m1); \ - b = vec_mergel(m0, m1); \ - m0 = vec_mergel(v0, v2); \ - m1 = vec_mergel(v1, v3); \ - c = vec_mergeh(m0, m1); \ - d = vec_mergel(m0, m1); \ -} -VSX_IMPL_ST_DINTERLEAVE_32(uint, vec_uint4) -VSX_IMPL_ST_DINTERLEAVE_32(int, vec_int4) -VSX_IMPL_ST_DINTERLEAVE_32(float, vec_float4) - -// 2 and 4 channels interleave and deinterleave for 2 lanes -#define VSX_IMPL_ST_D_INTERLEAVE_64(Tp, Tvec, ld_func, st_func) \ -VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, Tp* ptr) \ -{ \ - st_func(vec_mergeh(a, b), 0, ptr); \ - st_func(vec_mergel(a, b), 2, ptr); \ -} \ -VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ - const Tvec& c, const Tvec& d, Tp* ptr) \ -{ \ - st_func(vec_mergeh(a, b), 0, ptr); \ - st_func(vec_mergeh(c, d), 2, ptr); \ - st_func(vec_mergel(a, b), 4, ptr); \ - st_func(vec_mergel(c, d), 6, ptr); \ -} \ -VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b) \ -{ \ - Tvec m0 = ld_func(0, ptr); \ - Tvec m1 = ld_func(2, ptr); \ - a = vec_mergeh(m0, m1); \ - b = vec_mergel(m0, m1); \ -} \ -VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, \ - Tvec& c, Tvec& d) \ -{ \ - Tvec v0 = ld_func(0, ptr); \ - Tvec v1 = ld_func(2, ptr); \ - Tvec v2 = ld_func(4, ptr); \ - Tvec v3 = ld_func(6, ptr); \ - a = vec_mergeh(v0, v2); \ - b = vec_mergel(v0, v2); \ - c = vec_mergeh(v1, v3); \ - d = vec_mergel(v1, v3); \ -} -VSX_IMPL_ST_D_INTERLEAVE_64(int64, vec_dword2, vsx_ld2, vsx_st2) -VSX_IMPL_ST_D_INTERLEAVE_64(uint64, vec_udword2, vsx_ld2, vsx_st2) -VSX_IMPL_ST_D_INTERLEAVE_64(double, vec_double2, vsx_ld, vsx_st) - -/* 3 channels */ -#define VSX_IMPL_ST_INTERLEAVE_3CH_16(Tp, Tvec) \ -VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ - const Tvec& c, Tp* ptr) \ -{ \ - static const vec_uchar16 a12 = {0, 16, 0, 1, 17, 0, 2, 18, 0, 3, 19, 0, 4, 20, 0, 5}; \ - static const vec_uchar16 a123 = {0, 1, 16, 3, 4, 17, 6, 7, 18, 9, 10, 19, 12, 13, 20, 15}; \ - vsx_st(vec_perm(vec_perm(a, b, a12), c, a123), 0, ptr); \ - static const vec_uchar16 b12 = {21, 0, 6, 22, 0, 7, 23, 0, 8, 24, 0, 9, 25, 0, 10, 26}; \ - static const vec_uchar16 b123 = {0, 21, 2, 3, 22, 5, 6, 23, 8, 9, 24, 11, 12, 25, 14, 15}; \ - vsx_st(vec_perm(vec_perm(a, b, b12), c, b123), 16, ptr); \ - static const vec_uchar16 c12 = {0, 11, 27, 0, 12, 28, 0, 13, 29, 0, 14, 30, 0, 15, 31, 0}; \ - static const vec_uchar16 c123 = {26, 1, 2, 27, 4, 5, 28, 7, 8, 29, 10, 11, 30, 13, 14, 31}; \ - vsx_st(vec_perm(vec_perm(a, b, c12), c, c123), 32, ptr); \ -} \ -VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, Tvec& c) \ -{ \ - Tvec v1 = vsx_ld(0, ptr); \ - Tvec v2 = vsx_ld(16, ptr); \ - Tvec v3 = vsx_ld(32, ptr); \ - static const vec_uchar16 a12_perm = {0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 0, 0, 0, 0, 0}; \ - static const vec_uchar16 a123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 17, 20, 23, 26, 29}; \ - a = vec_perm(vec_perm(v1, v2, a12_perm), v3, a123_perm); \ - static const vec_uchar16 b12_perm = {1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 0, 0, 0, 0, 0}; \ - static const vec_uchar16 b123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 18, 21, 24, 27, 30}; \ - b = vec_perm(vec_perm(v1, v2, b12_perm), v3, b123_perm); \ - static const vec_uchar16 c12_perm = {2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 0, 0, 0, 0, 0, 0}; \ - static const vec_uchar16 c123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 19, 22, 25, 28, 31}; \ - c = vec_perm(vec_perm(v1, v2, c12_perm), v3, c123_perm); \ -} -VSX_IMPL_ST_INTERLEAVE_3CH_16(uchar, vec_uchar16) -VSX_IMPL_ST_INTERLEAVE_3CH_16(schar, vec_char16) - -#define VSX_IMPL_ST_INTERLEAVE_3CH_8(Tp, Tvec) \ -VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ - const Tvec& c, Tp* ptr) \ -{ \ - static const vec_uchar16 a12 = {0, 1, 16, 17, 0, 0, 2, 3, 18, 19, 0, 0, 4, 5, 20, 21}; \ - static const vec_uchar16 a123 = {0, 1, 2, 3, 16, 17, 6, 7, 8, 9, 18, 19, 12, 13, 14, 15}; \ - vsx_st(vec_perm(vec_perm(a, b, a12), c, a123), 0, ptr); \ - static const vec_uchar16 b12 = {0, 0, 6, 7, 22, 23, 0, 0, 8, 9, 24, 25, 0, 0, 10, 11}; \ - static const vec_uchar16 b123 = {20, 21, 2, 3, 4, 5, 22, 23, 8, 9, 10, 11, 24, 25, 14, 15}; \ - vsx_st(vec_perm(vec_perm(a, b, b12), c, b123), 8, ptr); \ - static const vec_uchar16 c12 = {26, 27, 0, 0, 12, 13, 28, 29, 0, 0, 14, 15, 30, 31, 0, 0}; \ - static const vec_uchar16 c123 = {0, 1, 26, 27, 4, 5, 6, 7, 28, 29, 10, 11, 12, 13, 30, 31}; \ - vsx_st(vec_perm(vec_perm(a, b, c12), c, c123), 16, ptr); \ -} \ -VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, Tvec& c) \ -{ \ - Tvec v1 = vsx_ld(0, ptr); \ - Tvec v2 = vsx_ld(8, ptr); \ - Tvec v3 = vsx_ld(16, ptr); \ - static const vec_uchar16 a12_perm = {0, 1, 6, 7, 12, 13, 18, 19, 24, 25, 30, 31, 0, 0, 0, 0}; \ - static const vec_uchar16 a123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 20, 21, 26, 27}; \ - a = vec_perm(vec_perm(v1, v2, a12_perm), v3, a123_perm); \ - static const vec_uchar16 b12_perm = {2, 3, 8, 9, 14, 15, 20, 21, 26, 27, 0, 0, 0, 0, 0, 0}; \ - static const vec_uchar16 b123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 22, 23, 28, 29}; \ - b = vec_perm(vec_perm(v1, v2, b12_perm), v3, b123_perm); \ - static const vec_uchar16 c12_perm = {4, 5, 10, 11, 16, 17, 22, 23, 28, 29, 0, 0, 0, 0, 0, 0}; \ - static const vec_uchar16 c123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 18, 19, 24, 25, 30, 31}; \ - c = vec_perm(vec_perm(v1, v2, c12_perm), v3, c123_perm); \ -} -VSX_IMPL_ST_INTERLEAVE_3CH_8(ushort, vec_ushort8) -VSX_IMPL_ST_INTERLEAVE_3CH_8(short, vec_short8) - -#define VSX_IMPL_ST_INTERLEAVE_3CH_4(Tp, Tvec) \ -VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ - const Tvec& c, Tp* ptr) \ -{ \ - Tvec hbc = vec_mergeh(b, c); \ - static const vec_uchar16 ahbc = {0, 1, 2, 3, 16, 17, 18, 19, 20, 21, 22, 23, 4, 5, 6, 7}; \ - vsx_st(vec_perm(a, hbc, ahbc), 0, ptr); \ - Tvec lab = vec_mergel(a, b); \ - vsx_st(vec_sld(lab, hbc, 8), 4, ptr); \ - static const vec_uchar16 clab = {8, 9, 10, 11, 24, 25, 26, 27, 28, 29, 30, 31, 12, 13, 14, 15};\ - vsx_st(vec_perm(c, lab, clab), 8, ptr); \ -} \ -VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, Tvec& c) \ -{ \ - Tvec v1 = vsx_ld(0, ptr); \ - Tvec v2 = vsx_ld(4, ptr); \ - Tvec v3 = vsx_ld(8, ptr); \ - static const vec_uchar16 flp = {0, 1, 2, 3, 12, 13, 14, 15, 16, 17, 18, 19, 28, 29, 30, 31}; \ - a = vec_perm(v1, vec_sld(v3, v2, 8), flp); \ - static const vec_uchar16 flp2 = {28, 29, 30, 31, 0, 1, 2, 3, 12, 13, 14, 15, 16, 17, 18, 19}; \ - b = vec_perm(v2, vec_sld(v1, v3, 8), flp2); \ - c = vec_perm(vec_sld(v2, v1, 8), v3, flp); \ -} -VSX_IMPL_ST_INTERLEAVE_3CH_4(uint, vec_uint4) -VSX_IMPL_ST_INTERLEAVE_3CH_4(int, vec_int4) -VSX_IMPL_ST_INTERLEAVE_3CH_4(float, vec_float4) - -#define VSX_IMPL_ST_INTERLEAVE_3CH_2(Tp, Tvec, ld_func, st_func) \ -VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ - const Tvec& c, Tp* ptr) \ -{ \ - st_func(vec_mergeh(a, b), 0, ptr); \ - st_func(vec_permi(c, a, 1), 2, ptr); \ - st_func(vec_mergel(b, c), 4, ptr); \ -} \ -VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, \ - Tvec& b, Tvec& c) \ -{ \ - Tvec v1 = ld_func(0, ptr); \ - Tvec v2 = ld_func(2, ptr); \ - Tvec v3 = ld_func(4, ptr); \ - a = vec_permi(v1, v2, 1); \ - b = vec_permi(v1, v3, 2); \ - c = vec_permi(v2, v3, 1); \ -} -VSX_IMPL_ST_INTERLEAVE_3CH_2(int64, vec_dword2, vsx_ld2, vsx_st2) -VSX_IMPL_ST_INTERLEAVE_3CH_2(uint64, vec_udword2, vsx_ld2, vsx_st2) -VSX_IMPL_ST_INTERLEAVE_3CH_2(double, vec_double2, vsx_ld, vsx_st) - -#endif // CV_VSX - -//! @} - -#endif // OPENCV_HAL_VSX_UTILS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +#ifndef OPENCV_HAL_VSX_UTILS_HPP +#define OPENCV_HAL_VSX_UTILS_HPP + +#include "opencv2/core/cvdef.h" + +#ifndef SKIP_INCLUDES +# include +#endif + +//! @addtogroup core_utils_vsx +//! @{ +#if CV_VSX + +#define __VSX_S16__(c, v) (c){v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v} +#define __VSX_S8__(c, v) (c){v, v, v, v, v, v, v, v} +#define __VSX_S4__(c, v) (c){v, v, v, v} +#define __VSX_S2__(c, v) (c){v, v} + +typedef __vector unsigned char vec_uchar16; +#define vec_uchar16_set(...) (vec_uchar16){__VA_ARGS__} +#define vec_uchar16_sp(c) (__VSX_S16__(vec_uchar16, (unsigned char)c)) +#define vec_uchar16_c(v) ((vec_uchar16)(v)) +#define vec_uchar16_z vec_uchar16_sp(0) + +typedef __vector signed char vec_char16; +#define vec_char16_set(...) (vec_char16){__VA_ARGS__} +#define vec_char16_sp(c) (__VSX_S16__(vec_char16, (signed char)c)) +#define vec_char16_c(v) ((vec_char16)(v)) +#define vec_char16_z vec_char16_sp(0) + +typedef __vector unsigned short vec_ushort8; +#define vec_ushort8_set(...) (vec_ushort8){__VA_ARGS__} +#define vec_ushort8_sp(c) (__VSX_S8__(vec_ushort8, (unsigned short)c)) +#define vec_ushort8_c(v) ((vec_ushort8)(v)) +#define vec_ushort8_z vec_ushort8_sp(0) + +typedef __vector signed short vec_short8; +#define vec_short8_set(...) (vec_short8){__VA_ARGS__} +#define vec_short8_sp(c) (__VSX_S8__(vec_short8, (signed short)c)) +#define vec_short8_c(v) ((vec_short8)(v)) +#define vec_short8_z vec_short8_sp(0) + +typedef __vector unsigned int vec_uint4; +#define vec_uint4_set(...) (vec_uint4){__VA_ARGS__} +#define vec_uint4_sp(c) (__VSX_S4__(vec_uint4, (unsigned int)c)) +#define vec_uint4_c(v) ((vec_uint4)(v)) +#define vec_uint4_z vec_uint4_sp(0) + +typedef __vector signed int vec_int4; +#define vec_int4_set(...) (vec_int4){__VA_ARGS__} +#define vec_int4_sp(c) (__VSX_S4__(vec_int4, (signed int)c)) +#define vec_int4_c(v) ((vec_int4)(v)) +#define vec_int4_z vec_int4_sp(0) + +typedef __vector float vec_float4; +#define vec_float4_set(...) (vec_float4){__VA_ARGS__} +#define vec_float4_sp(c) (__VSX_S4__(vec_float4, c)) +#define vec_float4_c(v) ((vec_float4)(v)) +#define vec_float4_z vec_float4_sp(0) + +typedef __vector unsigned long long vec_udword2; +#define vec_udword2_set(...) (vec_udword2){__VA_ARGS__} +#define vec_udword2_sp(c) (__VSX_S2__(vec_udword2, (unsigned long long)c)) +#define vec_udword2_c(v) ((vec_udword2)(v)) +#define vec_udword2_z vec_udword2_sp(0) + +typedef __vector signed long long vec_dword2; +#define vec_dword2_set(...) (vec_dword2){__VA_ARGS__} +#define vec_dword2_sp(c) (__VSX_S2__(vec_dword2, (signed long long)c)) +#define vec_dword2_c(v) ((vec_dword2)(v)) +#define vec_dword2_z vec_dword2_sp(0) + +typedef __vector double vec_double2; +#define vec_double2_set(...) (vec_double2){__VA_ARGS__} +#define vec_double2_c(v) ((vec_double2)(v)) +#define vec_double2_sp(c) (__VSX_S2__(vec_double2, c)) +#define vec_double2_z vec_double2_sp(0) + +#define vec_bchar16 __vector __bool char +#define vec_bchar16_set(...) (vec_bchar16){__VA_ARGS__} +#define vec_bchar16_c(v) ((vec_bchar16)(v)) + +#define vec_bshort8 __vector __bool short +#define vec_bshort8_set(...) (vec_bshort8){__VA_ARGS__} +#define vec_bshort8_c(v) ((vec_bshort8)(v)) + +#define vec_bint4 __vector __bool int +#define vec_bint4_set(...) (vec_bint4){__VA_ARGS__} +#define vec_bint4_c(v) ((vec_bint4)(v)) + +#define vec_bdword2 __vector __bool long long +#define vec_bdword2_set(...) (vec_bdword2){__VA_ARGS__} +#define vec_bdword2_c(v) ((vec_bdword2)(v)) + +#define VSX_FINLINE(tp) extern inline tp __attribute__((always_inline)) + +#define VSX_REDIRECT_1RG(rt, rg, fnm, fn2) \ +VSX_FINLINE(rt) fnm(const rg& a) { return fn2(a); } + +#define VSX_REDIRECT_2RG(rt, rg, fnm, fn2) \ +VSX_FINLINE(rt) fnm(const rg& a, const rg& b) { return fn2(a, b); } + +/* + * GCC VSX compatibility +**/ +#if defined(__GNUG__) && !defined(__clang__) + +// inline asm helper +#define VSX_IMPL_1RG(rt, rg, opc, fnm) \ +VSX_FINLINE(rt) fnm(const rg& a) \ +{ rt rs; __asm__ __volatile__(#opc" %x0,%x1" : "=wa" (rs) : "wa" (a)); return rs; } + +#define VSX_IMPL_1VRG(rt, rg, opc, fnm) \ +VSX_FINLINE(rt) fnm(const rg& a) \ +{ rt rs; __asm__ __volatile__(#opc" %0,%1" : "=v" (rs) : "v" (a)); return rs; } + +#define VSX_IMPL_2VRG_F(rt, rg, fopc, fnm) \ +VSX_FINLINE(rt) fnm(const rg& a, const rg& b) \ +{ rt rs; __asm__ __volatile__(fopc : "=v" (rs) : "v" (a), "v" (b)); return rs; } + +#define VSX_IMPL_2VRG(rt, rg, opc, fnm) VSX_IMPL_2VRG_F(rt, rg, #opc" %0,%1,%2", fnm) + +#if __GNUG__ < 8 + + // Support for int4 -> dword2 expanding multiply was added in GCC 8. + #ifdef vec_mule + #undef vec_mule + #endif + #ifdef vec_mulo + #undef vec_mulo + #endif + + VSX_REDIRECT_2RG(vec_ushort8, vec_uchar16, vec_mule, __builtin_vec_mule) + VSX_REDIRECT_2RG(vec_short8, vec_char16, vec_mule, __builtin_vec_mule) + VSX_REDIRECT_2RG(vec_int4, vec_short8, vec_mule, __builtin_vec_mule) + VSX_REDIRECT_2RG(vec_uint4, vec_ushort8, vec_mule, __builtin_vec_mule) + VSX_REDIRECT_2RG(vec_ushort8, vec_uchar16, vec_mulo, __builtin_vec_mulo) + VSX_REDIRECT_2RG(vec_short8, vec_char16, vec_mulo, __builtin_vec_mulo) + VSX_REDIRECT_2RG(vec_int4, vec_short8, vec_mulo, __builtin_vec_mulo) + VSX_REDIRECT_2RG(vec_uint4, vec_ushort8, vec_mulo, __builtin_vec_mulo) + + // dword2 support arrived in ISA 2.07 and GCC 8+ + VSX_IMPL_2VRG(vec_dword2, vec_int4, vmulosw, vec_mule) + VSX_IMPL_2VRG(vec_udword2, vec_uint4, vmulouw, vec_mule) + VSX_IMPL_2VRG(vec_dword2, vec_int4, vmulesw, vec_mulo) + VSX_IMPL_2VRG(vec_udword2, vec_uint4, vmuleuw, vec_mulo) + +#endif + +#if __GNUG__ < 7 +// up to GCC 6 vec_mul only supports precisions and llong +# ifdef vec_mul +# undef vec_mul +# endif +/* + * there's no a direct instruction for supporting 8-bit, 16-bit multiplication in ISA 2.07, + * XLC Implement it by using instruction "multiply even", "multiply odd" and "permute" +**/ +# define VSX_IMPL_MULH(Tvec, cperm) \ + VSX_FINLINE(Tvec) vec_mul(const Tvec& a, const Tvec& b) \ + { \ + static const vec_uchar16 ev_od = {cperm}; \ + return vec_perm((Tvec)vec_mule(a, b), (Tvec)vec_mulo(a, b), ev_od); \ + } + #define VSX_IMPL_MULH_P16 0, 16, 2, 18, 4, 20, 6, 22, 8, 24, 10, 26, 12, 28, 14, 30 + VSX_IMPL_MULH(vec_char16, VSX_IMPL_MULH_P16) + VSX_IMPL_MULH(vec_uchar16, VSX_IMPL_MULH_P16) + #define VSX_IMPL_MULH_P8 0, 1, 16, 17, 4, 5, 20, 21, 8, 9, 24, 25, 12, 13, 28, 29 + VSX_IMPL_MULH(vec_short8, VSX_IMPL_MULH_P8) + VSX_IMPL_MULH(vec_ushort8, VSX_IMPL_MULH_P8) + // vmuluwm can be used for unsigned or signed integers, that's what they said + VSX_IMPL_2VRG(vec_int4, vec_int4, vmuluwm, vec_mul) + VSX_IMPL_2VRG(vec_uint4, vec_uint4, vmuluwm, vec_mul) + // redirect to GCC builtin vec_mul, since it already supports precisions and llong + VSX_REDIRECT_2RG(vec_float4, vec_float4, vec_mul, __builtin_vec_mul) + VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mul, __builtin_vec_mul) + VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mul, __builtin_vec_mul) + VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mul, __builtin_vec_mul) +#endif // __GNUG__ < 7 + +#if __GNUG__ < 6 +/* + * Instruction "compare greater than or equal" in ISA 2.07 only supports single + * and double precision. + * In XLC and new versions of GCC implement integers by using instruction "greater than" and NOR. +**/ +# ifdef vec_cmpge +# undef vec_cmpge +# endif +# ifdef vec_cmple +# undef vec_cmple +# endif +# define vec_cmple(a, b) vec_cmpge(b, a) +# define VSX_IMPL_CMPGE(rt, rg, opc, fnm) \ + VSX_IMPL_2VRG_F(rt, rg, #opc" %0,%2,%1\n\t xxlnor %x0,%x0,%x0", fnm) + + VSX_IMPL_CMPGE(vec_bchar16, vec_char16, vcmpgtsb, vec_cmpge) + VSX_IMPL_CMPGE(vec_bchar16, vec_uchar16, vcmpgtub, vec_cmpge) + VSX_IMPL_CMPGE(vec_bshort8, vec_short8, vcmpgtsh, vec_cmpge) + VSX_IMPL_CMPGE(vec_bshort8, vec_ushort8, vcmpgtuh, vec_cmpge) + VSX_IMPL_CMPGE(vec_bint4, vec_int4, vcmpgtsw, vec_cmpge) + VSX_IMPL_CMPGE(vec_bint4, vec_uint4, vcmpgtuw, vec_cmpge) + VSX_IMPL_CMPGE(vec_bdword2, vec_dword2, vcmpgtsd, vec_cmpge) + VSX_IMPL_CMPGE(vec_bdword2, vec_udword2, vcmpgtud, vec_cmpge) + +// redirect to GCC builtin cmpge, since it already supports precisions + VSX_REDIRECT_2RG(vec_bint4, vec_float4, vec_cmpge, __builtin_vec_cmpge) + VSX_REDIRECT_2RG(vec_bdword2, vec_double2, vec_cmpge, __builtin_vec_cmpge) + +// up to gcc5 vec_nor doesn't support bool long long +# undef vec_nor + template + VSX_REDIRECT_2RG(T, T, vec_nor, __builtin_vec_nor) + + VSX_FINLINE(vec_bdword2) vec_nor(const vec_bdword2& a, const vec_bdword2& b) + { return vec_bdword2_c(__builtin_vec_nor(vec_dword2_c(a), vec_dword2_c(b))); } + +// vec_packs doesn't support double words in gcc4 and old versions of gcc5 +# undef vec_packs + VSX_REDIRECT_2RG(vec_char16, vec_short8, vec_packs, __builtin_vec_packs) + VSX_REDIRECT_2RG(vec_uchar16, vec_ushort8, vec_packs, __builtin_vec_packs) + VSX_REDIRECT_2RG(vec_short8, vec_int4, vec_packs, __builtin_vec_packs) + VSX_REDIRECT_2RG(vec_ushort8, vec_uint4, vec_packs, __builtin_vec_packs) + + VSX_IMPL_2VRG_F(vec_int4, vec_dword2, "vpksdss %0,%2,%1", vec_packs) + VSX_IMPL_2VRG_F(vec_uint4, vec_udword2, "vpkudus %0,%2,%1", vec_packs) +#endif // __GNUG__ < 6 + +#if __GNUG__ < 5 +// vec_xxpermdi in gcc4 missing little-endian supports just like clang +# define vec_permi(a, b, c) vec_xxpermdi(b, a, (3 ^ (((c) & 1) << 1 | (c) >> 1))) +// same as vec_xxpermdi +# undef vec_vbpermq + VSX_IMPL_2VRG(vec_udword2, vec_uchar16, vbpermq, vec_vbpermq) + VSX_IMPL_2VRG(vec_dword2, vec_char16, vbpermq, vec_vbpermq) +#else +# define vec_permi vec_xxpermdi +#endif // __GNUG__ < 5 + +// shift left double by word immediate +#ifndef vec_sldw +# define vec_sldw __builtin_vsx_xxsldwi +#endif + +// vector population count +VSX_IMPL_1VRG(vec_uchar16, vec_uchar16, vpopcntb, vec_popcntu) +VSX_IMPL_1VRG(vec_uchar16, vec_char16, vpopcntb, vec_popcntu) +VSX_IMPL_1VRG(vec_ushort8, vec_ushort8, vpopcnth, vec_popcntu) +VSX_IMPL_1VRG(vec_ushort8, vec_short8, vpopcnth, vec_popcntu) +VSX_IMPL_1VRG(vec_uint4, vec_uint4, vpopcntw, vec_popcntu) +VSX_IMPL_1VRG(vec_uint4, vec_int4, vpopcntw, vec_popcntu) +VSX_IMPL_1VRG(vec_udword2, vec_udword2, vpopcntd, vec_popcntu) +VSX_IMPL_1VRG(vec_udword2, vec_dword2, vpopcntd, vec_popcntu) + +// converts between single and double-precision +VSX_REDIRECT_1RG(vec_float4, vec_double2, vec_cvfo, __builtin_vsx_xvcvdpsp) +VSX_REDIRECT_1RG(vec_double2, vec_float4, vec_cvfo, __builtin_vsx_xvcvspdp) + +// converts word and doubleword to double-precision +#undef vec_ctd +VSX_IMPL_1RG(vec_double2, vec_int4, xvcvsxwdp, vec_ctdo) +VSX_IMPL_1RG(vec_double2, vec_uint4, xvcvuxwdp, vec_ctdo) +VSX_IMPL_1RG(vec_double2, vec_dword2, xvcvsxddp, vec_ctd) +VSX_IMPL_1RG(vec_double2, vec_udword2, xvcvuxddp, vec_ctd) + +// converts word and doubleword to single-precision +#undef vec_ctf +VSX_IMPL_1RG(vec_float4, vec_int4, xvcvsxwsp, vec_ctf) +VSX_IMPL_1RG(vec_float4, vec_uint4, xvcvuxwsp, vec_ctf) +VSX_IMPL_1RG(vec_float4, vec_dword2, xvcvsxdsp, vec_ctfo) +VSX_IMPL_1RG(vec_float4, vec_udword2, xvcvuxdsp, vec_ctfo) + +// converts single and double precision to signed word +#undef vec_cts +VSX_IMPL_1RG(vec_int4, vec_double2, xvcvdpsxws, vec_ctso) +VSX_IMPL_1RG(vec_int4, vec_float4, xvcvspsxws, vec_cts) + +// converts single and double precision to unsigned word +#undef vec_ctu +VSX_IMPL_1RG(vec_uint4, vec_double2, xvcvdpuxws, vec_ctuo) +VSX_IMPL_1RG(vec_uint4, vec_float4, xvcvspuxws, vec_ctu) + +// converts single and double precision to signed doubleword +#undef vec_ctsl +VSX_IMPL_1RG(vec_dword2, vec_double2, xvcvdpsxds, vec_ctsl) +VSX_IMPL_1RG(vec_dword2, vec_float4, xvcvspsxds, vec_ctslo) + +// converts single and double precision to unsigned doubleword +#undef vec_ctul +VSX_IMPL_1RG(vec_udword2, vec_double2, xvcvdpuxds, vec_ctul) +VSX_IMPL_1RG(vec_udword2, vec_float4, xvcvspuxds, vec_ctulo) + +// just in case if GCC doesn't define it +#ifndef vec_xl +# define vec_xl vec_vsx_ld +# define vec_xst vec_vsx_st +#endif + +#endif // GCC VSX compatibility + +/* + * CLANG VSX compatibility +**/ +#if defined(__clang__) && !defined(__IBMCPP__) + +/* + * CLANG doesn't support %x in the inline asm template which fixes register number + * when using any of the register constraints wa, wd, wf + * + * For more explanation checkout PowerPC and IBM RS6000 in https://gcc.gnu.org/onlinedocs/gcc/Machine-Constraints.html + * Also there's already an open bug https://bugs.llvm.org/show_bug.cgi?id=31837 + * + * So we're not able to use inline asm and only use built-in functions that CLANG supports + * and use __builtin_convertvector if clang missing any of vector conversions built-in functions + * + * todo: clang asm template bug is fixed, need to reconsider the current workarounds. +*/ + +// convert vector helper +#define VSX_IMPL_CONVERT(rt, rg, fnm) \ +VSX_FINLINE(rt) fnm(const rg& a) { return __builtin_convertvector(a, rt); } + +#ifndef vec_permi +#if __clang_major__ < 5 +// implement vec_permi in a dirty way +# define VSX_IMPL_CLANG_4_PERMI(Tvec) \ + VSX_FINLINE(Tvec) vec_permi(const Tvec& a, const Tvec& b, unsigned const char c) \ + { \ + switch (c) \ + { \ + case 0: \ + return vec_mergeh(a, b); \ + case 1: \ + return vec_mergel(vec_mergeh(a, a), b); \ + case 2: \ + return vec_mergeh(vec_mergel(a, a), b); \ + default: \ + return vec_mergel(a, b); \ + } \ + } + VSX_IMPL_CLANG_4_PERMI(vec_udword2) + VSX_IMPL_CLANG_4_PERMI(vec_dword2) + VSX_IMPL_CLANG_4_PERMI(vec_double2) + +// vec_xxsldwi is missing in clang 4 +# define vec_xxsldwi(a, b, c) vec_sld(a, b, (c) * 4) +#else +// vec_xxpermdi is missing little-endian supports in clang 4 just like gcc4 +# define vec_permi(a, b, c) vec_xxpermdi(b, a, (3 ^ (((c) & 1) << 1 | (c) >> 1))) +#endif // __clang_major__ < 5 +#endif + +// shift left double by word immediate +#ifndef vec_sldw +# define vec_sldw vec_xxsldwi +#endif + +#if __clang_major__ < 13 +// Implement vec_rsqrt since clang only supports vec_rsqrte +#ifndef vec_rsqrt + VSX_FINLINE(vec_float4) vec_rsqrt(const vec_float4& a) + { return vec_div(vec_float4_sp(1), vec_sqrt(a)); } + + VSX_FINLINE(vec_double2) vec_rsqrt(const vec_double2& a) + { return vec_div(vec_double2_sp(1), vec_sqrt(a)); } +#endif + +// vec_promote missing support for doubleword +VSX_FINLINE(vec_dword2) vec_promote(long long a, int b) +{ + vec_dword2 ret = vec_dword2_z; + ret[b & 1] = a; + return ret; +} + +VSX_FINLINE(vec_udword2) vec_promote(unsigned long long a, int b) +{ + vec_udword2 ret = vec_udword2_z; + ret[b & 1] = a; + return ret; +} +#endif + +// vec_popcnt should return unsigned but clang has different thought just like gcc in vec_vpopcnt +#define VSX_IMPL_POPCNTU(Tvec, Tvec2, ucast) \ +VSX_FINLINE(Tvec) vec_popcntu(const Tvec2& a) \ +{ return ucast(vec_popcnt(a)); } +VSX_IMPL_POPCNTU(vec_uchar16, vec_char16, vec_uchar16_c); +VSX_IMPL_POPCNTU(vec_ushort8, vec_short8, vec_ushort8_c); +VSX_IMPL_POPCNTU(vec_uint4, vec_int4, vec_uint4_c); +VSX_IMPL_POPCNTU(vec_udword2, vec_dword2, vec_udword2_c); +// redirect unsigned types +VSX_REDIRECT_1RG(vec_uchar16, vec_uchar16, vec_popcntu, vec_popcnt) +VSX_REDIRECT_1RG(vec_ushort8, vec_ushort8, vec_popcntu, vec_popcnt) +VSX_REDIRECT_1RG(vec_uint4, vec_uint4, vec_popcntu, vec_popcnt) +VSX_REDIRECT_1RG(vec_udword2, vec_udword2, vec_popcntu, vec_popcnt) + +// converts between single and double precision +VSX_REDIRECT_1RG(vec_float4, vec_double2, vec_cvfo, __builtin_vsx_xvcvdpsp) +VSX_REDIRECT_1RG(vec_double2, vec_float4, vec_cvfo, __builtin_vsx_xvcvspdp) + +// converts word and doubleword to double-precision +#ifdef vec_ctd +# undef vec_ctd +#endif +VSX_REDIRECT_1RG(vec_double2, vec_int4, vec_ctdo, __builtin_vsx_xvcvsxwdp) +VSX_REDIRECT_1RG(vec_double2, vec_uint4, vec_ctdo, __builtin_vsx_xvcvuxwdp) + +VSX_IMPL_CONVERT(vec_double2, vec_dword2, vec_ctd) +VSX_IMPL_CONVERT(vec_double2, vec_udword2, vec_ctd) + +// converts word and doubleword to single-precision +#if __clang_major__ > 4 +# undef vec_ctf +#endif +VSX_IMPL_CONVERT(vec_float4, vec_int4, vec_ctf) +VSX_IMPL_CONVERT(vec_float4, vec_uint4, vec_ctf) +VSX_REDIRECT_1RG(vec_float4, vec_dword2, vec_ctfo, __builtin_vsx_xvcvsxdsp) +VSX_REDIRECT_1RG(vec_float4, vec_udword2, vec_ctfo, __builtin_vsx_xvcvuxdsp) + +// converts single and double precision to signed word +#if __clang_major__ > 4 +# undef vec_cts +#endif +VSX_REDIRECT_1RG(vec_int4, vec_double2, vec_ctso, __builtin_vsx_xvcvdpsxws) +VSX_IMPL_CONVERT(vec_int4, vec_float4, vec_cts) + +// converts single and double precision to unsigned word +#if __clang_major__ > 4 +# undef vec_ctu +#endif +VSX_REDIRECT_1RG(vec_uint4, vec_double2, vec_ctuo, __builtin_vsx_xvcvdpuxws) +VSX_IMPL_CONVERT(vec_uint4, vec_float4, vec_ctu) + +// converts single and double precision to signed doubleword +#ifdef vec_ctsl +# undef vec_ctsl +#endif +VSX_IMPL_CONVERT(vec_dword2, vec_double2, vec_ctsl) +// __builtin_convertvector unable to convert, xvcvspsxds is missing on it +VSX_FINLINE(vec_dword2) vec_ctslo(const vec_float4& a) +{ return vec_ctsl(vec_cvfo(a)); } + +// converts single and double precision to unsigned doubleword +#ifdef vec_ctul +# undef vec_ctul +#endif +VSX_IMPL_CONVERT(vec_udword2, vec_double2, vec_ctul) +// __builtin_convertvector unable to convert, xvcvspuxds is missing on it +VSX_FINLINE(vec_udword2) vec_ctulo(const vec_float4& a) +{ return vec_ctul(vec_cvfo(a)); } + +#endif // CLANG VSX compatibility + +/* + * Common GCC, CLANG compatibility +**/ +#if defined(__GNUG__) && !defined(__IBMCPP__) + +#ifdef vec_cvf +# undef vec_cvf +#endif + +#define VSX_IMPL_CONV_EVEN_4_2(rt, rg, fnm, fn2) \ +VSX_FINLINE(rt) fnm(const rg& a) \ +{ return fn2(vec_sldw(a, a, 1)); } + +VSX_IMPL_CONV_EVEN_4_2(vec_double2, vec_float4, vec_cvf, vec_cvfo) +VSX_IMPL_CONV_EVEN_4_2(vec_double2, vec_int4, vec_ctd, vec_ctdo) +VSX_IMPL_CONV_EVEN_4_2(vec_double2, vec_uint4, vec_ctd, vec_ctdo) + +VSX_IMPL_CONV_EVEN_4_2(vec_dword2, vec_float4, vec_ctsl, vec_ctslo) +VSX_IMPL_CONV_EVEN_4_2(vec_udword2, vec_float4, vec_ctul, vec_ctulo) + +#define VSX_IMPL_CONV_EVEN_2_4(rt, rg, fnm, fn2) \ +VSX_FINLINE(rt) fnm(const rg& a) \ +{ \ + rt v4 = fn2(a); \ + return vec_sldw(v4, v4, 3); \ +} + +VSX_IMPL_CONV_EVEN_2_4(vec_float4, vec_double2, vec_cvf, vec_cvfo) +VSX_IMPL_CONV_EVEN_2_4(vec_float4, vec_dword2, vec_ctf, vec_ctfo) +VSX_IMPL_CONV_EVEN_2_4(vec_float4, vec_udword2, vec_ctf, vec_ctfo) + +VSX_IMPL_CONV_EVEN_2_4(vec_int4, vec_double2, vec_cts, vec_ctso) +VSX_IMPL_CONV_EVEN_2_4(vec_uint4, vec_double2, vec_ctu, vec_ctuo) + +// Only for Eigen! +/* + * changing behavior of conversion intrinsics for gcc has effect on Eigen + * so we redefine old behavior again only on gcc, clang +*/ +#if !defined(__clang__) || __clang_major__ > 4 + // ignoring second arg since Eigen only truncates toward zero +# define VSX_IMPL_CONV_2VARIANT(rt, rg, fnm, fn2) \ + VSX_FINLINE(rt) fnm(const rg& a, int only_truncate) \ + { \ + assert(only_truncate == 0); \ + CV_UNUSED(only_truncate); \ + return fn2(a); \ + } + VSX_IMPL_CONV_2VARIANT(vec_int4, vec_float4, vec_cts, vec_cts) + VSX_IMPL_CONV_2VARIANT(vec_uint4, vec_float4, vec_ctu, vec_ctu) + VSX_IMPL_CONV_2VARIANT(vec_float4, vec_int4, vec_ctf, vec_ctf) + VSX_IMPL_CONV_2VARIANT(vec_float4, vec_uint4, vec_ctf, vec_ctf) + // define vec_cts for converting double precision to signed doubleword + // which isn't compatible with xlc but its okay since Eigen only uses it for gcc + VSX_IMPL_CONV_2VARIANT(vec_dword2, vec_double2, vec_cts, vec_ctsl) +#endif // Eigen + +#endif // Common GCC, CLANG compatibility + +/* + * XLC VSX compatibility +**/ +#if defined(__IBMCPP__) + +// vector population count +#define vec_popcntu vec_popcnt + +// overload and redirect with setting second arg to zero +// since we only support conversions without the second arg +#define VSX_IMPL_OVERLOAD_Z2(rt, rg, fnm) \ +VSX_FINLINE(rt) fnm(const rg& a) { return fnm(a, 0); } + +VSX_IMPL_OVERLOAD_Z2(vec_double2, vec_int4, vec_ctd) +VSX_IMPL_OVERLOAD_Z2(vec_double2, vec_uint4, vec_ctd) +VSX_IMPL_OVERLOAD_Z2(vec_double2, vec_dword2, vec_ctd) +VSX_IMPL_OVERLOAD_Z2(vec_double2, vec_udword2, vec_ctd) + +VSX_IMPL_OVERLOAD_Z2(vec_float4, vec_int4, vec_ctf) +VSX_IMPL_OVERLOAD_Z2(vec_float4, vec_uint4, vec_ctf) +VSX_IMPL_OVERLOAD_Z2(vec_float4, vec_dword2, vec_ctf) +VSX_IMPL_OVERLOAD_Z2(vec_float4, vec_udword2, vec_ctf) + +VSX_IMPL_OVERLOAD_Z2(vec_int4, vec_double2, vec_cts) +VSX_IMPL_OVERLOAD_Z2(vec_int4, vec_float4, vec_cts) + +VSX_IMPL_OVERLOAD_Z2(vec_uint4, vec_double2, vec_ctu) +VSX_IMPL_OVERLOAD_Z2(vec_uint4, vec_float4, vec_ctu) + +VSX_IMPL_OVERLOAD_Z2(vec_dword2, vec_double2, vec_ctsl) +VSX_IMPL_OVERLOAD_Z2(vec_dword2, vec_float4, vec_ctsl) + +VSX_IMPL_OVERLOAD_Z2(vec_udword2, vec_double2, vec_ctul) +VSX_IMPL_OVERLOAD_Z2(vec_udword2, vec_float4, vec_ctul) + +// fixme: implement conversions of odd-numbered elements in a dirty way +// since xlc doesn't support VSX registers operand in inline asm. +#define VSX_IMPL_CONV_ODD_4_2(rt, rg, fnm, fn2) \ +VSX_FINLINE(rt) fnm(const rg& a) { return fn2(vec_sldw(a, a, 3)); } + +VSX_IMPL_CONV_ODD_4_2(vec_double2, vec_float4, vec_cvfo, vec_cvf) +VSX_IMPL_CONV_ODD_4_2(vec_double2, vec_int4, vec_ctdo, vec_ctd) +VSX_IMPL_CONV_ODD_4_2(vec_double2, vec_uint4, vec_ctdo, vec_ctd) + +VSX_IMPL_CONV_ODD_4_2(vec_dword2, vec_float4, vec_ctslo, vec_ctsl) +VSX_IMPL_CONV_ODD_4_2(vec_udword2, vec_float4, vec_ctulo, vec_ctul) + +#define VSX_IMPL_CONV_ODD_2_4(rt, rg, fnm, fn2) \ +VSX_FINLINE(rt) fnm(const rg& a) \ +{ \ + rt v4 = fn2(a); \ + return vec_sldw(v4, v4, 1); \ +} + +VSX_IMPL_CONV_ODD_2_4(vec_float4, vec_double2, vec_cvfo, vec_cvf) +VSX_IMPL_CONV_ODD_2_4(vec_float4, vec_dword2, vec_ctfo, vec_ctf) +VSX_IMPL_CONV_ODD_2_4(vec_float4, vec_udword2, vec_ctfo, vec_ctf) + +VSX_IMPL_CONV_ODD_2_4(vec_int4, vec_double2, vec_ctso, vec_cts) +VSX_IMPL_CONV_ODD_2_4(vec_uint4, vec_double2, vec_ctuo, vec_ctu) + +#endif // XLC VSX compatibility + +// ignore GCC warning that caused by -Wunused-but-set-variable in rare cases +#if defined(__GNUG__) && !defined(__clang__) +# define VSX_UNUSED(Tvec) Tvec __attribute__((__unused__)) +#else // CLANG, XLC +# define VSX_UNUSED(Tvec) Tvec +#endif + +// gcc can find his way in casting log int and XLC, CLANG ambiguous +#if defined(__clang__) || defined(__IBMCPP__) + VSX_FINLINE(vec_udword2) vec_splats(uint64 v) + { return vec_splats((unsigned long long) v); } + + VSX_FINLINE(vec_dword2) vec_splats(int64 v) + { return vec_splats((long long) v); } + + VSX_FINLINE(vec_udword2) vec_promote(uint64 a, int b) + { return vec_promote((unsigned long long) a, b); } + + VSX_FINLINE(vec_dword2) vec_promote(int64 a, int b) + { return vec_promote((long long) a, b); } +#endif + +/* + * implement vsx_ld(offset, pointer), vsx_st(vector, offset, pointer) + * load and set using offset depend on the pointer type + * + * implement vsx_ldf(offset, pointer), vsx_stf(vector, offset, pointer) + * load and set using offset depend on fixed bytes size + * + * Note: In clang vec_xl and vec_xst fails to load unaligned addresses + * so we are using vec_vsx_ld, vec_vsx_st instead +*/ + +#if defined(__clang__) && !defined(__IBMCPP__) +# define vsx_ldf vec_vsx_ld +# define vsx_stf vec_vsx_st +#else // GCC , XLC +# define vsx_ldf vec_xl +# define vsx_stf vec_xst +#endif + +#define VSX_OFFSET(o, p) ((o) * sizeof(*(p))) +#define vsx_ld(o, p) vsx_ldf(VSX_OFFSET(o, p), p) +#define vsx_st(v, o, p) vsx_stf(v, VSX_OFFSET(o, p), p) + +/* + * implement vsx_ld2(offset, pointer), vsx_st2(vector, offset, pointer) to load and store double words + * In GCC vec_xl and vec_xst it maps to vec_vsx_ld, vec_vsx_st which doesn't support long long + * and in CLANG we are using vec_vsx_ld, vec_vsx_st because vec_xl, vec_xst fails to load unaligned addresses + * + * In XLC vec_xl and vec_xst fail to cast int64(long int) to long long +*/ +#if (defined(__GNUG__) || defined(__clang__)) && !defined(__IBMCPP__) + VSX_FINLINE(vec_udword2) vsx_ld2(long o, const uint64* p) + { return vec_udword2_c(vsx_ldf(VSX_OFFSET(o, p), (unsigned int*)p)); } + + VSX_FINLINE(vec_dword2) vsx_ld2(long o, const int64* p) + { return vec_dword2_c(vsx_ldf(VSX_OFFSET(o, p), (int*)p)); } + + VSX_FINLINE(void) vsx_st2(const vec_udword2& vec, long o, uint64* p) + { vsx_stf(vec_uint4_c(vec), VSX_OFFSET(o, p), (unsigned int*)p); } + + VSX_FINLINE(void) vsx_st2(const vec_dword2& vec, long o, int64* p) + { vsx_stf(vec_int4_c(vec), VSX_OFFSET(o, p), (int*)p); } +#else // XLC + VSX_FINLINE(vec_udword2) vsx_ld2(long o, const uint64* p) + { return vsx_ldf(VSX_OFFSET(o, p), (unsigned long long*)p); } + + VSX_FINLINE(vec_dword2) vsx_ld2(long o, const int64* p) + { return vsx_ldf(VSX_OFFSET(o, p), (long long*)p); } + + VSX_FINLINE(void) vsx_st2(const vec_udword2& vec, long o, uint64* p) + { vsx_stf(vec, VSX_OFFSET(o, p), (unsigned long long*)p); } + + VSX_FINLINE(void) vsx_st2(const vec_dword2& vec, long o, int64* p) + { vsx_stf(vec, VSX_OFFSET(o, p), (long long*)p); } +#endif + +// Store lower 8 byte +#define vec_st_l8(v, p) *((uint64*)(p)) = vec_extract(vec_udword2_c(v), 0) + +// Store higher 8 byte +#define vec_st_h8(v, p) *((uint64*)(p)) = vec_extract(vec_udword2_c(v), 1) + +// Load 64-bits of integer data to lower part +#define VSX_IMPL_LOAD_L8(Tvec, Tp) \ +VSX_FINLINE(Tvec) vec_ld_l8(const Tp *p) \ +{ return ((Tvec)vec_promote(*((uint64*)p), 0)); } + +VSX_IMPL_LOAD_L8(vec_uchar16, uchar) +VSX_IMPL_LOAD_L8(vec_char16, schar) +VSX_IMPL_LOAD_L8(vec_ushort8, ushort) +VSX_IMPL_LOAD_L8(vec_short8, short) +VSX_IMPL_LOAD_L8(vec_uint4, uint) +VSX_IMPL_LOAD_L8(vec_int4, int) +VSX_IMPL_LOAD_L8(vec_float4, float) +VSX_IMPL_LOAD_L8(vec_udword2, uint64) +VSX_IMPL_LOAD_L8(vec_dword2, int64) +VSX_IMPL_LOAD_L8(vec_double2, double) + +// logical not +#define vec_not(a) vec_nor(a, a) + +// power9 yaya +// not equal +#ifndef vec_cmpne +# define vec_cmpne(a, b) vec_not(vec_cmpeq(a, b)) +#endif + +// absolute difference +#ifndef _ARCH_PWR9 +# undef vec_absd +# define vec_absd(a, b) vec_sub(vec_max(a, b), vec_min(a, b)) +#endif + +/* + * Implement vec_unpacklu and vec_unpackhu + * since vec_unpackl, vec_unpackh only support signed integers +**/ +#define VSX_IMPL_UNPACKU(rt, rg, zero) \ +VSX_FINLINE(rt) vec_unpacklu(const rg& a) \ +{ return (rt)(vec_mergel(a, zero)); } \ +VSX_FINLINE(rt) vec_unpackhu(const rg& a) \ +{ return (rt)(vec_mergeh(a, zero)); } + +VSX_IMPL_UNPACKU(vec_ushort8, vec_uchar16, vec_uchar16_z) +VSX_IMPL_UNPACKU(vec_uint4, vec_ushort8, vec_ushort8_z) +VSX_IMPL_UNPACKU(vec_udword2, vec_uint4, vec_uint4_z) + +/* + * Implement vec_mergesqe and vec_mergesqo + * Merges the sequence values of even and odd elements of two vectors +*/ +#define VSX_IMPL_PERM(rt, fnm, ...) \ +VSX_FINLINE(rt) fnm(const rt& a, const rt& b) \ +{ static const vec_uchar16 perm = {__VA_ARGS__}; return vec_perm(a, b, perm); } + +// 16 +#define perm16_mergesqe 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30 +#define perm16_mergesqo 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 +VSX_IMPL_PERM(vec_uchar16, vec_mergesqe, perm16_mergesqe) +VSX_IMPL_PERM(vec_uchar16, vec_mergesqo, perm16_mergesqo) +VSX_IMPL_PERM(vec_char16, vec_mergesqe, perm16_mergesqe) +VSX_IMPL_PERM(vec_char16, vec_mergesqo, perm16_mergesqo) +// 8 +#define perm8_mergesqe 0, 1, 4, 5, 8, 9, 12, 13, 16, 17, 20, 21, 24, 25, 28, 29 +#define perm8_mergesqo 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 +VSX_IMPL_PERM(vec_ushort8, vec_mergesqe, perm8_mergesqe) +VSX_IMPL_PERM(vec_ushort8, vec_mergesqo, perm8_mergesqo) +VSX_IMPL_PERM(vec_short8, vec_mergesqe, perm8_mergesqe) +VSX_IMPL_PERM(vec_short8, vec_mergesqo, perm8_mergesqo) +// 4 +#define perm4_mergesqe 0, 1, 2, 3, 8, 9, 10, 11, 16, 17, 18, 19, 24, 25, 26, 27 +#define perm4_mergesqo 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 +VSX_IMPL_PERM(vec_uint4, vec_mergesqe, perm4_mergesqe) +VSX_IMPL_PERM(vec_uint4, vec_mergesqo, perm4_mergesqo) +VSX_IMPL_PERM(vec_int4, vec_mergesqe, perm4_mergesqe) +VSX_IMPL_PERM(vec_int4, vec_mergesqo, perm4_mergesqo) +VSX_IMPL_PERM(vec_float4, vec_mergesqe, perm4_mergesqe) +VSX_IMPL_PERM(vec_float4, vec_mergesqo, perm4_mergesqo) +// 2 +VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mergesqe, vec_mergeh) +VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mergesqo, vec_mergel) +VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mergesqe, vec_mergeh) +VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mergesqo, vec_mergel) +VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mergesqe, vec_mergeh) +VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mergesqo, vec_mergel) + +/* + * Implement vec_mergesqh and vec_mergesql + * Merges the sequence most and least significant halves of two vectors +*/ +#define VSX_IMPL_MERGESQHL(Tvec) \ +VSX_FINLINE(Tvec) vec_mergesqh(const Tvec& a, const Tvec& b) \ +{ return (Tvec)vec_mergeh(vec_udword2_c(a), vec_udword2_c(b)); } \ +VSX_FINLINE(Tvec) vec_mergesql(const Tvec& a, const Tvec& b) \ +{ return (Tvec)vec_mergel(vec_udword2_c(a), vec_udword2_c(b)); } +VSX_IMPL_MERGESQHL(vec_uchar16) +VSX_IMPL_MERGESQHL(vec_char16) +VSX_IMPL_MERGESQHL(vec_ushort8) +VSX_IMPL_MERGESQHL(vec_short8) +VSX_IMPL_MERGESQHL(vec_uint4) +VSX_IMPL_MERGESQHL(vec_int4) +VSX_IMPL_MERGESQHL(vec_float4) +VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mergesqh, vec_mergeh) +VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mergesql, vec_mergel) +VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mergesqh, vec_mergeh) +VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mergesql, vec_mergel) +VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mergesqh, vec_mergeh) +VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mergesql, vec_mergel) + + +// 2 and 4 channels interleave for all types except 2 lanes +#define VSX_IMPL_ST_INTERLEAVE(Tp, Tvec) \ +VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, Tp* ptr) \ +{ \ + vsx_stf(vec_mergeh(a, b), 0, ptr); \ + vsx_stf(vec_mergel(a, b), 16, ptr); \ +} \ +VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ + const Tvec& c, const Tvec& d, Tp* ptr) \ +{ \ + Tvec ac = vec_mergeh(a, c); \ + Tvec bd = vec_mergeh(b, d); \ + vsx_stf(vec_mergeh(ac, bd), 0, ptr); \ + vsx_stf(vec_mergel(ac, bd), 16, ptr); \ + ac = vec_mergel(a, c); \ + bd = vec_mergel(b, d); \ + vsx_stf(vec_mergeh(ac, bd), 32, ptr); \ + vsx_stf(vec_mergel(ac, bd), 48, ptr); \ +} +VSX_IMPL_ST_INTERLEAVE(uchar, vec_uchar16) +VSX_IMPL_ST_INTERLEAVE(schar, vec_char16) +VSX_IMPL_ST_INTERLEAVE(ushort, vec_ushort8) +VSX_IMPL_ST_INTERLEAVE(short, vec_short8) +VSX_IMPL_ST_INTERLEAVE(uint, vec_uint4) +VSX_IMPL_ST_INTERLEAVE(int, vec_int4) +VSX_IMPL_ST_INTERLEAVE(float, vec_float4) + +// 2 and 4 channels deinterleave for 16 lanes +#define VSX_IMPL_ST_DINTERLEAVE_8(Tp, Tvec) \ +VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b) \ +{ \ + Tvec v0 = vsx_ld(0, ptr); \ + Tvec v1 = vsx_ld(16, ptr); \ + a = vec_mergesqe(v0, v1); \ + b = vec_mergesqo(v0, v1); \ +} \ +VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, \ + Tvec& c, Tvec& d) \ +{ \ + Tvec v0 = vsx_ld(0, ptr); \ + Tvec v1 = vsx_ld(16, ptr); \ + Tvec v2 = vsx_ld(32, ptr); \ + Tvec v3 = vsx_ld(48, ptr); \ + Tvec m0 = vec_mergesqe(v0, v1); \ + Tvec m1 = vec_mergesqe(v2, v3); \ + a = vec_mergesqe(m0, m1); \ + c = vec_mergesqo(m0, m1); \ + m0 = vec_mergesqo(v0, v1); \ + m1 = vec_mergesqo(v2, v3); \ + b = vec_mergesqe(m0, m1); \ + d = vec_mergesqo(m0, m1); \ +} +VSX_IMPL_ST_DINTERLEAVE_8(uchar, vec_uchar16) +VSX_IMPL_ST_DINTERLEAVE_8(schar, vec_char16) + +// 2 and 4 channels deinterleave for 8 lanes +#define VSX_IMPL_ST_DINTERLEAVE_16(Tp, Tvec) \ +VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b) \ +{ \ + Tvec v0 = vsx_ld(0, ptr); \ + Tvec v1 = vsx_ld(8, ptr); \ + a = vec_mergesqe(v0, v1); \ + b = vec_mergesqo(v0, v1); \ +} \ +VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, \ + Tvec& c, Tvec& d) \ +{ \ + Tvec v0 = vsx_ld(0, ptr); \ + Tvec v1 = vsx_ld(8, ptr); \ + Tvec m0 = vec_mergeh(v0, v1); \ + Tvec m1 = vec_mergel(v0, v1); \ + Tvec ab0 = vec_mergeh(m0, m1); \ + Tvec cd0 = vec_mergel(m0, m1); \ + v0 = vsx_ld(16, ptr); \ + v1 = vsx_ld(24, ptr); \ + m0 = vec_mergeh(v0, v1); \ + m1 = vec_mergel(v0, v1); \ + Tvec ab1 = vec_mergeh(m0, m1); \ + Tvec cd1 = vec_mergel(m0, m1); \ + a = vec_mergesqh(ab0, ab1); \ + b = vec_mergesql(ab0, ab1); \ + c = vec_mergesqh(cd0, cd1); \ + d = vec_mergesql(cd0, cd1); \ +} +VSX_IMPL_ST_DINTERLEAVE_16(ushort, vec_ushort8) +VSX_IMPL_ST_DINTERLEAVE_16(short, vec_short8) + +// 2 and 4 channels deinterleave for 4 lanes +#define VSX_IMPL_ST_DINTERLEAVE_32(Tp, Tvec) \ +VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b) \ +{ \ + a = vsx_ld(0, ptr); \ + b = vsx_ld(4, ptr); \ + Tvec m0 = vec_mergeh(a, b); \ + Tvec m1 = vec_mergel(a, b); \ + a = vec_mergeh(m0, m1); \ + b = vec_mergel(m0, m1); \ +} \ +VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, \ + Tvec& c, Tvec& d) \ +{ \ + Tvec v0 = vsx_ld(0, ptr); \ + Tvec v1 = vsx_ld(4, ptr); \ + Tvec v2 = vsx_ld(8, ptr); \ + Tvec v3 = vsx_ld(12, ptr); \ + Tvec m0 = vec_mergeh(v0, v2); \ + Tvec m1 = vec_mergeh(v1, v3); \ + a = vec_mergeh(m0, m1); \ + b = vec_mergel(m0, m1); \ + m0 = vec_mergel(v0, v2); \ + m1 = vec_mergel(v1, v3); \ + c = vec_mergeh(m0, m1); \ + d = vec_mergel(m0, m1); \ +} +VSX_IMPL_ST_DINTERLEAVE_32(uint, vec_uint4) +VSX_IMPL_ST_DINTERLEAVE_32(int, vec_int4) +VSX_IMPL_ST_DINTERLEAVE_32(float, vec_float4) + +// 2 and 4 channels interleave and deinterleave for 2 lanes +#define VSX_IMPL_ST_D_INTERLEAVE_64(Tp, Tvec, ld_func, st_func) \ +VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, Tp* ptr) \ +{ \ + st_func(vec_mergeh(a, b), 0, ptr); \ + st_func(vec_mergel(a, b), 2, ptr); \ +} \ +VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ + const Tvec& c, const Tvec& d, Tp* ptr) \ +{ \ + st_func(vec_mergeh(a, b), 0, ptr); \ + st_func(vec_mergeh(c, d), 2, ptr); \ + st_func(vec_mergel(a, b), 4, ptr); \ + st_func(vec_mergel(c, d), 6, ptr); \ +} \ +VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b) \ +{ \ + Tvec m0 = ld_func(0, ptr); \ + Tvec m1 = ld_func(2, ptr); \ + a = vec_mergeh(m0, m1); \ + b = vec_mergel(m0, m1); \ +} \ +VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, \ + Tvec& c, Tvec& d) \ +{ \ + Tvec v0 = ld_func(0, ptr); \ + Tvec v1 = ld_func(2, ptr); \ + Tvec v2 = ld_func(4, ptr); \ + Tvec v3 = ld_func(6, ptr); \ + a = vec_mergeh(v0, v2); \ + b = vec_mergel(v0, v2); \ + c = vec_mergeh(v1, v3); \ + d = vec_mergel(v1, v3); \ +} +VSX_IMPL_ST_D_INTERLEAVE_64(int64, vec_dword2, vsx_ld2, vsx_st2) +VSX_IMPL_ST_D_INTERLEAVE_64(uint64, vec_udword2, vsx_ld2, vsx_st2) +VSX_IMPL_ST_D_INTERLEAVE_64(double, vec_double2, vsx_ld, vsx_st) + +/* 3 channels */ +#define VSX_IMPL_ST_INTERLEAVE_3CH_16(Tp, Tvec) \ +VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ + const Tvec& c, Tp* ptr) \ +{ \ + static const vec_uchar16 a12 = {0, 16, 0, 1, 17, 0, 2, 18, 0, 3, 19, 0, 4, 20, 0, 5}; \ + static const vec_uchar16 a123 = {0, 1, 16, 3, 4, 17, 6, 7, 18, 9, 10, 19, 12, 13, 20, 15}; \ + vsx_st(vec_perm(vec_perm(a, b, a12), c, a123), 0, ptr); \ + static const vec_uchar16 b12 = {21, 0, 6, 22, 0, 7, 23, 0, 8, 24, 0, 9, 25, 0, 10, 26}; \ + static const vec_uchar16 b123 = {0, 21, 2, 3, 22, 5, 6, 23, 8, 9, 24, 11, 12, 25, 14, 15}; \ + vsx_st(vec_perm(vec_perm(a, b, b12), c, b123), 16, ptr); \ + static const vec_uchar16 c12 = {0, 11, 27, 0, 12, 28, 0, 13, 29, 0, 14, 30, 0, 15, 31, 0}; \ + static const vec_uchar16 c123 = {26, 1, 2, 27, 4, 5, 28, 7, 8, 29, 10, 11, 30, 13, 14, 31}; \ + vsx_st(vec_perm(vec_perm(a, b, c12), c, c123), 32, ptr); \ +} \ +VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, Tvec& c) \ +{ \ + Tvec v1 = vsx_ld(0, ptr); \ + Tvec v2 = vsx_ld(16, ptr); \ + Tvec v3 = vsx_ld(32, ptr); \ + static const vec_uchar16 a12_perm = {0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 0, 0, 0, 0, 0}; \ + static const vec_uchar16 a123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 17, 20, 23, 26, 29}; \ + a = vec_perm(vec_perm(v1, v2, a12_perm), v3, a123_perm); \ + static const vec_uchar16 b12_perm = {1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 0, 0, 0, 0, 0}; \ + static const vec_uchar16 b123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 18, 21, 24, 27, 30}; \ + b = vec_perm(vec_perm(v1, v2, b12_perm), v3, b123_perm); \ + static const vec_uchar16 c12_perm = {2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 0, 0, 0, 0, 0, 0}; \ + static const vec_uchar16 c123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 19, 22, 25, 28, 31}; \ + c = vec_perm(vec_perm(v1, v2, c12_perm), v3, c123_perm); \ +} +VSX_IMPL_ST_INTERLEAVE_3CH_16(uchar, vec_uchar16) +VSX_IMPL_ST_INTERLEAVE_3CH_16(schar, vec_char16) + +#define VSX_IMPL_ST_INTERLEAVE_3CH_8(Tp, Tvec) \ +VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ + const Tvec& c, Tp* ptr) \ +{ \ + static const vec_uchar16 a12 = {0, 1, 16, 17, 0, 0, 2, 3, 18, 19, 0, 0, 4, 5, 20, 21}; \ + static const vec_uchar16 a123 = {0, 1, 2, 3, 16, 17, 6, 7, 8, 9, 18, 19, 12, 13, 14, 15}; \ + vsx_st(vec_perm(vec_perm(a, b, a12), c, a123), 0, ptr); \ + static const vec_uchar16 b12 = {0, 0, 6, 7, 22, 23, 0, 0, 8, 9, 24, 25, 0, 0, 10, 11}; \ + static const vec_uchar16 b123 = {20, 21, 2, 3, 4, 5, 22, 23, 8, 9, 10, 11, 24, 25, 14, 15}; \ + vsx_st(vec_perm(vec_perm(a, b, b12), c, b123), 8, ptr); \ + static const vec_uchar16 c12 = {26, 27, 0, 0, 12, 13, 28, 29, 0, 0, 14, 15, 30, 31, 0, 0}; \ + static const vec_uchar16 c123 = {0, 1, 26, 27, 4, 5, 6, 7, 28, 29, 10, 11, 12, 13, 30, 31}; \ + vsx_st(vec_perm(vec_perm(a, b, c12), c, c123), 16, ptr); \ +} \ +VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, Tvec& c) \ +{ \ + Tvec v1 = vsx_ld(0, ptr); \ + Tvec v2 = vsx_ld(8, ptr); \ + Tvec v3 = vsx_ld(16, ptr); \ + static const vec_uchar16 a12_perm = {0, 1, 6, 7, 12, 13, 18, 19, 24, 25, 30, 31, 0, 0, 0, 0}; \ + static const vec_uchar16 a123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 20, 21, 26, 27}; \ + a = vec_perm(vec_perm(v1, v2, a12_perm), v3, a123_perm); \ + static const vec_uchar16 b12_perm = {2, 3, 8, 9, 14, 15, 20, 21, 26, 27, 0, 0, 0, 0, 0, 0}; \ + static const vec_uchar16 b123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 22, 23, 28, 29}; \ + b = vec_perm(vec_perm(v1, v2, b12_perm), v3, b123_perm); \ + static const vec_uchar16 c12_perm = {4, 5, 10, 11, 16, 17, 22, 23, 28, 29, 0, 0, 0, 0, 0, 0}; \ + static const vec_uchar16 c123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 18, 19, 24, 25, 30, 31}; \ + c = vec_perm(vec_perm(v1, v2, c12_perm), v3, c123_perm); \ +} +VSX_IMPL_ST_INTERLEAVE_3CH_8(ushort, vec_ushort8) +VSX_IMPL_ST_INTERLEAVE_3CH_8(short, vec_short8) + +#define VSX_IMPL_ST_INTERLEAVE_3CH_4(Tp, Tvec) \ +VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ + const Tvec& c, Tp* ptr) \ +{ \ + Tvec hbc = vec_mergeh(b, c); \ + static const vec_uchar16 ahbc = {0, 1, 2, 3, 16, 17, 18, 19, 20, 21, 22, 23, 4, 5, 6, 7}; \ + vsx_st(vec_perm(a, hbc, ahbc), 0, ptr); \ + Tvec lab = vec_mergel(a, b); \ + vsx_st(vec_sld(lab, hbc, 8), 4, ptr); \ + static const vec_uchar16 clab = {8, 9, 10, 11, 24, 25, 26, 27, 28, 29, 30, 31, 12, 13, 14, 15};\ + vsx_st(vec_perm(c, lab, clab), 8, ptr); \ +} \ +VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, Tvec& c) \ +{ \ + Tvec v1 = vsx_ld(0, ptr); \ + Tvec v2 = vsx_ld(4, ptr); \ + Tvec v3 = vsx_ld(8, ptr); \ + static const vec_uchar16 flp = {0, 1, 2, 3, 12, 13, 14, 15, 16, 17, 18, 19, 28, 29, 30, 31}; \ + a = vec_perm(v1, vec_sld(v3, v2, 8), flp); \ + static const vec_uchar16 flp2 = {28, 29, 30, 31, 0, 1, 2, 3, 12, 13, 14, 15, 16, 17, 18, 19}; \ + b = vec_perm(v2, vec_sld(v1, v3, 8), flp2); \ + c = vec_perm(vec_sld(v2, v1, 8), v3, flp); \ +} +VSX_IMPL_ST_INTERLEAVE_3CH_4(uint, vec_uint4) +VSX_IMPL_ST_INTERLEAVE_3CH_4(int, vec_int4) +VSX_IMPL_ST_INTERLEAVE_3CH_4(float, vec_float4) + +#define VSX_IMPL_ST_INTERLEAVE_3CH_2(Tp, Tvec, ld_func, st_func) \ +VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ + const Tvec& c, Tp* ptr) \ +{ \ + st_func(vec_mergeh(a, b), 0, ptr); \ + st_func(vec_permi(c, a, 1), 2, ptr); \ + st_func(vec_mergel(b, c), 4, ptr); \ +} \ +VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, \ + Tvec& b, Tvec& c) \ +{ \ + Tvec v1 = ld_func(0, ptr); \ + Tvec v2 = ld_func(2, ptr); \ + Tvec v3 = ld_func(4, ptr); \ + a = vec_permi(v1, v2, 1); \ + b = vec_permi(v1, v3, 2); \ + c = vec_permi(v2, v3, 1); \ +} +VSX_IMPL_ST_INTERLEAVE_3CH_2(int64, vec_dword2, vsx_ld2, vsx_st2) +VSX_IMPL_ST_INTERLEAVE_3CH_2(uint64, vec_udword2, vsx_ld2, vsx_st2) +VSX_IMPL_ST_INTERLEAVE_3CH_2(double, vec_double2, vsx_ld, vsx_st) + +#endif // CV_VSX + +//! @} + +#endif // OPENCV_HAL_VSX_UTILS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/cvconfig.h b/3rdParty/opencv-4.11.0/opencv2/cvconfig.h index 47c5735d79..e1b1ee82bb 100644 --- a/3rdParty/opencv-4.11.0/opencv2/cvconfig.h +++ b/3rdParty/opencv-4.11.0/opencv2/cvconfig.h @@ -1,155 +1,155 @@ -#ifndef OPENCV_CVCONFIG_H_INCLUDED -#define OPENCV_CVCONFIG_H_INCLUDED - -/* OpenCV compiled as static or dynamic libs */ -#define BUILD_SHARED_LIBS - -/* OpenCV intrinsics optimized code */ -#define CV_ENABLE_INTRINSICS - -/* OpenCV additional optimized code */ -/* #undef CV_DISABLE_OPTIMIZATION */ - -/* Compile for 'real' NVIDIA GPU architectures */ -#define CUDA_ARCH_BIN "" - -/* NVIDIA GPU features are used */ -#define CUDA_ARCH_FEATURES "" - -/* Compile for 'virtual' NVIDIA PTX architectures */ -#define CUDA_ARCH_PTX "" - -/* AMD's Basic Linear Algebra Subprograms Library*/ -/* #undef HAVE_CLAMDBLAS */ - -/* AMD's OpenCL Fast Fourier Transform Library*/ -/* #undef HAVE_CLAMDFFT */ - -/* Clp support */ -/* #undef HAVE_CLP */ - -/* NVIDIA CUDA Runtime API*/ -/* #undef HAVE_CUDA */ - -/* NVIDIA CUDA Basic Linear Algebra Subprograms (BLAS) API*/ -/* #undef HAVE_CUBLAS */ - -/* NVIDIA CUDA Deep Neural Network (cuDNN) API*/ -/* #undef HAVE_CUDNN */ - -/* NVIDIA CUDA Fast Fourier Transform (FFT) API*/ -/* #undef HAVE_CUFFT */ - -/* DirectX */ -#define HAVE_DIRECTX -#define HAVE_DIRECTX_NV12 -#define HAVE_D3D11 -#define HAVE_D3D10 -#define HAVE_D3D9 - -/* Eigen Matrix & Linear Algebra Library */ -/* #undef HAVE_EIGEN */ - -/* Geospatial Data Abstraction Library */ -/* #undef HAVE_GDAL */ - -/* Halide support */ -/* #undef HAVE_HALIDE */ - -/* Vulkan support */ -/* #undef HAVE_VULKAN */ - -/* Define to 1 if you have the header file. */ -#define HAVE_INTTYPES_H 1 - -/* Intel Integrated Performance Primitives */ -#define HAVE_IPP -#define HAVE_IPP_ICV -#define HAVE_IPP_IW -#define HAVE_IPP_IW_LL - -/* JPEG-2000 codec */ -#define HAVE_OPENJPEG -/* #undef HAVE_JASPER */ - -/* AVIF codec */ -/* #undef HAVE_AVIF */ - -/* IJG JPEG codec */ -#define HAVE_JPEG - -/* JPEG XL codec */ -/* #undef HAVE_JPEGXL */ - -/* GDCM DICOM codec */ -/* #undef HAVE_GDCM */ - -/* NVIDIA Video Decoding API*/ -/* #undef HAVE_NVCUVID */ -/* #undef HAVE_NVCUVID_HEADER */ -/* #undef HAVE_DYNLINK_NVCUVID_HEADER */ - -/* NVIDIA Video Encoding API*/ -/* #undef HAVE_NVCUVENC */ - -/* OpenCL Support */ -#define HAVE_OPENCL -/* #undef HAVE_OPENCL_STATIC */ -/* #undef HAVE_OPENCL_SVM */ - -/* NVIDIA OpenCL D3D Extensions support */ -#define HAVE_OPENCL_D3D11_NV - -/* OpenEXR codec */ -#define HAVE_OPENEXR - -/* OpenGL support*/ -/* #undef HAVE_OPENGL */ - -/* PNG codec */ -#define HAVE_PNG - -/* PNG codec */ -/* #undef HAVE_SPNG */ - -/* Posix threads (pthreads) */ -/* #undef HAVE_PTHREAD */ - -/* parallel_for with pthreads */ -/* #undef HAVE_PTHREADS_PF */ - -/* Intel Threading Building Blocks */ -/* #undef HAVE_TBB */ - -/* Ste||ar Group High Performance ParallelX */ -/* #undef HAVE_HPX */ - -/* TIFF codec */ -#define HAVE_TIFF - -/* Define if your processor stores words with the most significant byte - first (like Motorola and SPARC, unlike Intel and VAX). */ -/* #undef WORDS_BIGENDIAN */ - -/* VA library (libva) */ -/* #undef HAVE_VA */ - -/* Intel VA-API/OpenCL */ -/* #undef HAVE_VA_INTEL */ - -/* Lapack */ -/* #undef HAVE_LAPACK */ - -/* Library was compiled with functions instrumentation */ -/* #undef ENABLE_INSTRUMENTATION */ - -/* OpenVX */ -/* #undef HAVE_OPENVX */ - -/* OpenCV trace utilities */ -#define OPENCV_TRACE - -/* Library QR-code decoding */ -/* #undef HAVE_QUIRC */ - -#endif // OPENCV_CVCONFIG_H_INCLUDED +#ifndef OPENCV_CVCONFIG_H_INCLUDED +#define OPENCV_CVCONFIG_H_INCLUDED + +/* OpenCV compiled as static or dynamic libs */ +#define BUILD_SHARED_LIBS + +/* OpenCV intrinsics optimized code */ +#define CV_ENABLE_INTRINSICS + +/* OpenCV additional optimized code */ +/* #undef CV_DISABLE_OPTIMIZATION */ + +/* Compile for 'real' NVIDIA GPU architectures */ +#define CUDA_ARCH_BIN "" + +/* NVIDIA GPU features are used */ +#define CUDA_ARCH_FEATURES "" + +/* Compile for 'virtual' NVIDIA PTX architectures */ +#define CUDA_ARCH_PTX "" + +/* AMD's Basic Linear Algebra Subprograms Library*/ +/* #undef HAVE_CLAMDBLAS */ + +/* AMD's OpenCL Fast Fourier Transform Library*/ +/* #undef HAVE_CLAMDFFT */ + +/* Clp support */ +/* #undef HAVE_CLP */ + +/* NVIDIA CUDA Runtime API*/ +/* #undef HAVE_CUDA */ + +/* NVIDIA CUDA Basic Linear Algebra Subprograms (BLAS) API*/ +/* #undef HAVE_CUBLAS */ + +/* NVIDIA CUDA Deep Neural Network (cuDNN) API*/ +/* #undef HAVE_CUDNN */ + +/* NVIDIA CUDA Fast Fourier Transform (FFT) API*/ +/* #undef HAVE_CUFFT */ + +/* DirectX */ +#define HAVE_DIRECTX +#define HAVE_DIRECTX_NV12 +#define HAVE_D3D11 +#define HAVE_D3D10 +#define HAVE_D3D9 + +/* Eigen Matrix & Linear Algebra Library */ +/* #undef HAVE_EIGEN */ + +/* Geospatial Data Abstraction Library */ +/* #undef HAVE_GDAL */ + +/* Halide support */ +/* #undef HAVE_HALIDE */ + +/* Vulkan support */ +/* #undef HAVE_VULKAN */ + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Intel Integrated Performance Primitives */ +#define HAVE_IPP +#define HAVE_IPP_ICV +#define HAVE_IPP_IW +#define HAVE_IPP_IW_LL + +/* JPEG-2000 codec */ +#define HAVE_OPENJPEG +/* #undef HAVE_JASPER */ + +/* AVIF codec */ +/* #undef HAVE_AVIF */ + +/* IJG JPEG codec */ +#define HAVE_JPEG + +/* JPEG XL codec */ +/* #undef HAVE_JPEGXL */ + +/* GDCM DICOM codec */ +/* #undef HAVE_GDCM */ + +/* NVIDIA Video Decoding API*/ +/* #undef HAVE_NVCUVID */ +/* #undef HAVE_NVCUVID_HEADER */ +/* #undef HAVE_DYNLINK_NVCUVID_HEADER */ + +/* NVIDIA Video Encoding API*/ +/* #undef HAVE_NVCUVENC */ + +/* OpenCL Support */ +#define HAVE_OPENCL +/* #undef HAVE_OPENCL_STATIC */ +/* #undef HAVE_OPENCL_SVM */ + +/* NVIDIA OpenCL D3D Extensions support */ +#define HAVE_OPENCL_D3D11_NV + +/* OpenEXR codec */ +#define HAVE_OPENEXR + +/* OpenGL support*/ +/* #undef HAVE_OPENGL */ + +/* PNG codec */ +#define HAVE_PNG + +/* PNG codec */ +/* #undef HAVE_SPNG */ + +/* Posix threads (pthreads) */ +/* #undef HAVE_PTHREAD */ + +/* parallel_for with pthreads */ +/* #undef HAVE_PTHREADS_PF */ + +/* Intel Threading Building Blocks */ +/* #undef HAVE_TBB */ + +/* Ste||ar Group High Performance ParallelX */ +/* #undef HAVE_HPX */ + +/* TIFF codec */ +#define HAVE_TIFF + +/* Define if your processor stores words with the most significant byte + first (like Motorola and SPARC, unlike Intel and VAX). */ +/* #undef WORDS_BIGENDIAN */ + +/* VA library (libva) */ +/* #undef HAVE_VA */ + +/* Intel VA-API/OpenCL */ +/* #undef HAVE_VA_INTEL */ + +/* Lapack */ +/* #undef HAVE_LAPACK */ + +/* Library was compiled with functions instrumentation */ +/* #undef ENABLE_INSTRUMENTATION */ + +/* OpenVX */ +/* #undef HAVE_OPENVX */ + +/* OpenCV trace utilities */ +#define OPENCV_TRACE + +/* Library QR-code decoding */ +/* #undef HAVE_QUIRC */ + +#endif // OPENCV_CVCONFIG_H_INCLUDED diff --git a/3rdParty/opencv-4.11.0/opencv2/dnn.hpp b/3rdParty/opencv-4.11.0/opencv2/dnn.hpp index 97f2fe3ffd..f08efe815c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/dnn.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/dnn.hpp @@ -1,78 +1,78 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_DNN_HPP -#define OPENCV_DNN_HPP - -// This is an umbrella header to include into you project. -// We are free to change headers layout in dnn subfolder, so please include -// this header for future compatibility - - -/** @defgroup dnn Deep Neural Network module - @{ - This module contains: - - API for new layers creation, layers are building bricks of neural networks; - - set of built-in most-useful Layers; - - API to construct and modify comprehensive neural networks from layers; - - functionality for loading serialized networks models from different frameworks. - - Functionality of this module is designed only for forward pass computations (i.e. network testing). - A network training is in principle not supported. - @} -*/ -/** @example samples/dnn/classification.cpp -Check @ref tutorial_dnn_googlenet "the corresponding tutorial" for more details -*/ -/** @example samples/dnn/colorization.cpp -*/ -/** @example samples/dnn/object_detection.cpp -Check @ref tutorial_dnn_yolo "the corresponding tutorial" for more details -*/ -/** @example samples/dnn/openpose.cpp -*/ -/** @example samples/dnn/segmentation.cpp -*/ -/** @example samples/dnn/text_detection.cpp -*/ -#include - -#endif /* OPENCV_DNN_HPP */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_DNN_HPP +#define OPENCV_DNN_HPP + +// This is an umbrella header to include into you project. +// We are free to change headers layout in dnn subfolder, so please include +// this header for future compatibility + + +/** @defgroup dnn Deep Neural Network module + @{ + This module contains: + - API for new layers creation, layers are building bricks of neural networks; + - set of built-in most-useful Layers; + - API to construct and modify comprehensive neural networks from layers; + - functionality for loading serialized networks models from different frameworks. + + Functionality of this module is designed only for forward pass computations (i.e. network testing). + A network training is in principle not supported. + @} +*/ +/** @example samples/dnn/classification.cpp +Check @ref tutorial_dnn_googlenet "the corresponding tutorial" for more details +*/ +/** @example samples/dnn/colorization.cpp +*/ +/** @example samples/dnn/object_detection.cpp +Check @ref tutorial_dnn_yolo "the corresponding tutorial" for more details +*/ +/** @example samples/dnn/openpose.cpp +*/ +/** @example samples/dnn/segmentation.cpp +*/ +/** @example samples/dnn/text_detection.cpp +*/ +#include + +#endif /* OPENCV_DNN_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/dnn/all_layers.hpp b/3rdParty/opencv-4.11.0/opencv2/dnn/all_layers.hpp index d9d1833780..0475bac230 100644 --- a/3rdParty/opencv-4.11.0/opencv2/dnn/all_layers.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/dnn/all_layers.hpp @@ -1,1212 +1,1212 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_DNN_DNN_ALL_LAYERS_HPP -#define OPENCV_DNN_DNN_ALL_LAYERS_HPP -#include - -namespace cv { -namespace dnn { -CV__DNN_INLINE_NS_BEGIN -//! @addtogroup dnn -//! @{ - -/** @defgroup dnnLayerList Partial List of Implemented Layers - @{ - This subsection of dnn module contains information about built-in layers and their descriptions. - - Classes listed here, in fact, provides C++ API for creating instances of built-in layers. - In addition to this way of layers instantiation, there is a more common factory API (see @ref dnnLayerFactory), it allows to create layers dynamically (by name) and register new ones. - You can use both API, but factory API is less convenient for native C++ programming and basically designed for use inside importers (see @ref readNetFromCaffe(), @ref readNetFromTorch(), @ref readNetFromTensorflow()). - - Built-in layers partially reproduce functionality of corresponding Caffe and Torch7 layers. - In particular, the following layers and Caffe importer were tested to reproduce Caffe functionality: - - Convolution - - Deconvolution - - Pooling - - InnerProduct - - TanH, ReLU, Sigmoid, BNLL, Power, AbsVal - - Softmax - - Reshape, Flatten, Slice, Split - - LRN - - MVN - - Dropout (since it does nothing on forward pass -)) -*/ - - class CV_EXPORTS BlankLayer : public Layer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - /** - * Constant layer produces the same data blob at an every forward pass. - */ - class CV_EXPORTS ConstLayer : public Layer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - //! LSTM recurrent layer - class CV_EXPORTS LSTMLayer : public Layer - { - public: - /** Creates instance of LSTM layer */ - static Ptr create(const LayerParams& params); - - /** @deprecated Use LayerParams::blobs instead. - @brief Set trained weights for LSTM layer. - - LSTM behavior on each step is defined by current input, previous output, previous cell state and learned weights. - - Let @f$x_t@f$ be current input, @f$h_t@f$ be current output, @f$c_t@f$ be current state. - Than current output and current cell state is computed as follows: - @f{eqnarray*}{ - h_t &= o_t \odot tanh(c_t), \\ - c_t &= f_t \odot c_{t-1} + i_t \odot g_t, \\ - @f} - where @f$\odot@f$ is per-element multiply operation and @f$i_t, f_t, o_t, g_t@f$ is internal gates that are computed using learned weights. - - Gates are computed as follows: - @f{eqnarray*}{ - i_t &= sigmoid&(W_{xi} x_t + W_{hi} h_{t-1} + b_i), \\ - f_t &= sigmoid&(W_{xf} x_t + W_{hf} h_{t-1} + b_f), \\ - o_t &= sigmoid&(W_{xo} x_t + W_{ho} h_{t-1} + b_o), \\ - g_t &= tanh &(W_{xg} x_t + W_{hg} h_{t-1} + b_g), \\ - @f} - where @f$W_{x?}@f$, @f$W_{h?}@f$ and @f$b_{?}@f$ are learned weights represented as matrices: - @f$W_{x?} \in R^{N_h \times N_x}@f$, @f$W_{h?} \in R^{N_h \times N_h}@f$, @f$b_? \in R^{N_h}@f$. - - For simplicity and performance purposes we use @f$ W_x = [W_{xi}; W_{xf}; W_{xo}, W_{xg}] @f$ - (i.e. @f$W_x@f$ is vertical concatenation of @f$ W_{x?} @f$), @f$ W_x \in R^{4N_h \times N_x} @f$. - The same for @f$ W_h = [W_{hi}; W_{hf}; W_{ho}, W_{hg}], W_h \in R^{4N_h \times N_h} @f$ - and for @f$ b = [b_i; b_f, b_o, b_g]@f$, @f$b \in R^{4N_h} @f$. - - @param Wh is matrix defining how previous output is transformed to internal gates (i.e. according to above mentioned notation is @f$ W_h @f$) - @param Wx is matrix defining how current input is transformed to internal gates (i.e. according to above mentioned notation is @f$ W_x @f$) - @param b is bias vector (i.e. according to above mentioned notation is @f$ b @f$) - */ - CV_DEPRECATED virtual void setWeights(const Mat &Wh, const Mat &Wx, const Mat &b) = 0; - - /** @brief Specifies shape of output blob which will be [[`T`], `N`] + @p outTailShape. - * @details If this parameter is empty or unset then @p outTailShape = [`Wh`.size(0)] will be used, - * where `Wh` is parameter from setWeights(). - */ - virtual void setOutShape(const MatShape &outTailShape = MatShape()) = 0; - - /** @deprecated Use flag `produce_cell_output` in LayerParams. - * @brief Specifies either interpret first dimension of input blob as timestamp dimension either as sample. - * - * If flag is set to true then shape of input blob will be interpreted as [`T`, `N`, `[data dims]`] where `T` specifies number of timestamps, `N` is number of independent streams. - * In this case each forward() call will iterate through `T` timestamps and update layer's state `T` times. - * - * If flag is set to false then shape of input blob will be interpreted as [`N`, `[data dims]`]. - * In this case each forward() call will make one iteration and produce one timestamp with shape [`N`, `[out dims]`]. - */ - CV_DEPRECATED virtual void setUseTimstampsDim(bool use = true) = 0; - - /** @deprecated Use flag `use_timestamp_dim` in LayerParams. - * @brief If this flag is set to true then layer will produce @f$ c_t @f$ as second output. - * @details Shape of the second output is the same as first output. - */ - CV_DEPRECATED virtual void setProduceCellOutput(bool produce = false) = 0; - - /* In common case it use single input with @f$x_t@f$ values to compute output(s) @f$h_t@f$ (and @f$c_t@f$). - * @param input should contain packed values @f$x_t@f$ - * @param output contains computed outputs: @f$h_t@f$ (and @f$c_t@f$ if setProduceCellOutput() flag was set to true). - * - * If setUseTimstampsDim() is set to true then @p input[0] should has at least two dimensions with the following shape: [`T`, `N`, `[data dims]`], - * where `T` specifies number of timestamps, `N` is number of independent streams (i.e. @f$ x_{t_0 + t}^{stream} @f$ is stored inside @p input[0][t, stream, ...]). - * - * If setUseTimstampsDim() is set to false then @p input[0] should contain single timestamp, its shape should has form [`N`, `[data dims]`] with at least one dimension. - * (i.e. @f$ x_{t}^{stream} @f$ is stored inside @p input[0][stream, ...]). - */ - - int inputNameToIndex(String inputName) CV_OVERRIDE; - int outputNameToIndex(const String& outputName) CV_OVERRIDE; - }; - - /** @brief GRU recurrent one-layer - * - * Accepts input sequence and computes the final hidden state for each element in the batch. - * - * - input[0] containing the features of the input sequence. - * input[0] should have shape [`T`, `N`, `data_dims`] where `T` is sequence length, `N` is batch size, `data_dims` is input size - * - output would have shape [`T`, `N`, `D` * `hidden_size`] where `D = 2` if layer is bidirectional otherwise `D = 1` - * - * Depends on the following attributes: - * - hidden_size - Number of neurons in the hidden layer - * - direction - RNN could be bidirectional or forward - * - * The final hidden state @f$ h_t @f$ computes by the following formulas: - * - @f{eqnarray*}{ - r_t = \sigma(W_{ir} x_t + b_{ir} + W_{hr} h_{(t-1)} + b_{hr}) \\ - z_t = \sigma(W_{iz} x_t + b_{iz} + W_{hz} h_{(t-1)} + b_{hz}) \\ - n_t = \tanh(W_{in} x_t + b_{in} + r_t \odot (W_{hn} h_{(t-1)}+ b_{hn})) \\ - h_t = (1 - z_t) \odot n_t + z_t \odot h_{(t-1)} \\ - @f} - * Where @f$x_t@f$ is current input, @f$h_{(t-1)}@f$ is previous or initial hidden state. - * - * @f$W_{x?}@f$, @f$W_{h?}@f$ and @f$b_{?}@f$ are learned weights represented as matrices: - * @f$W_{x?} \in R^{N_h \times N_x}@f$, @f$W_{h?} \in R^{N_h \times N_h}@f$, @f$b_? \in R^{N_h}@f$. - * - * @f$\odot@f$ is per-element multiply operation. - */ - class CV_EXPORTS GRULayer : public Layer - { - public: - /** Creates instance of GRU layer */ - static Ptr create(const LayerParams& params); - }; - - /** @brief Classical recurrent layer - - Accepts two inputs @f$x_t@f$ and @f$h_{t-1}@f$ and compute two outputs @f$o_t@f$ and @f$h_t@f$. - - - input: should contain packed input @f$x_t@f$. - - output: should contain output @f$o_t@f$ (and @f$h_t@f$ if setProduceHiddenOutput() is set to true). - - input[0] should have shape [`T`, `N`, `data_dims`] where `T` and `N` is number of timestamps and number of independent samples of @f$x_t@f$ respectively. - - output[0] will have shape [`T`, `N`, @f$N_o@f$], where @f$N_o@f$ is number of rows in @f$ W_{xo} @f$ matrix. - - If setProduceHiddenOutput() is set to true then @p output[1] will contain a Mat with shape [`T`, `N`, @f$N_h@f$], where @f$N_h@f$ is number of rows in @f$ W_{hh} @f$ matrix. - */ - class CV_EXPORTS RNNLayer : public Layer - { - public: - /** Creates instance of RNNLayer */ - static Ptr create(const LayerParams& params); - - /** Setups learned weights. - - Recurrent-layer behavior on each step is defined by current input @f$ x_t @f$, previous state @f$ h_t @f$ and learned weights as follows: - @f{eqnarray*}{ - h_t &= tanh&(W_{hh} h_{t-1} + W_{xh} x_t + b_h), \\ - o_t &= tanh&(W_{ho} h_t + b_o), - @f} - - @param Wxh is @f$ W_{xh} @f$ matrix - @param bh is @f$ b_{h} @f$ vector - @param Whh is @f$ W_{hh} @f$ matrix - @param Who is @f$ W_{xo} @f$ matrix - @param bo is @f$ b_{o} @f$ vector - */ - virtual void setWeights(const Mat &Wxh, const Mat &bh, const Mat &Whh, const Mat &Who, const Mat &bo) = 0; - - /** @brief If this flag is set to true then layer will produce @f$ h_t @f$ as second output. - * @details Shape of the second output is the same as first output. - */ - virtual void setProduceHiddenOutput(bool produce = false) = 0; - - }; - - /** @brief This function performs array summation based - * on the Einstein summation convention. The function - * allows for concise expressions of various mathematical - * operations using subscripts. - * - * By default, the labels are placed in alphabetical - * order at the end of the output. - * For example: - * if `c = einsum("i,j", a, b)`, then `c[i,j] == a[i]*b[j]`. - * However, if `c = einsum("j,i", a, b)`, then `c[i,j] = a[j]*b[i]`. - * Alternatively, you can control the output order or prevent - * an axis from being summed/force an axis to be summed - * by providing indices for the output. - * For example: - * `diag(a)` -> `einsum("ii->i", a)` - * `sum(a, axis=0)` -> `einsum("i...->", a)` - * Subscripts at the beginning and end may be specified - * by putting an ellipsis "..." in the middle. - * For instance, the function `einsum("i...i", a)` takes - * the diagonal of the first and last dimensions of - * the operand, and `einsum("ij...,jk...->ik...")` performs - * the matrix product using the first two indices - * of each operand instead of the last two. - * When there is only one operand, no axes being summed, - * and no output parameter, this function returns - * a view into the operand instead of creating a copy. - */ - class CV_EXPORTS EinsumLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS BaseConvolutionLayer : public Layer - { - public: - CV_DEPRECATED_EXTERNAL Size kernel, stride, pad, dilation, adjustPad; - std::vector adjust_pads; - std::vector kernel_size, strides, dilations; - std::vector pads_begin, pads_end; - String padMode; - int numOutput; - }; - - class CV_EXPORTS ConvolutionLayer : public BaseConvolutionLayer - { - public: - static Ptr create(const LayerParams& params); - bool fusedActivation = false; - bool fusedAdd = false; - bool useWinograd = true; // Flag whether to use Winograd to speed up 3x3 convolution. - }; - - class CV_EXPORTS ConvolutionLayerInt8 : public BaseConvolutionLayer - { - public: - int input_zp, output_zp; - float input_sc, output_sc; - - // quantization type flag. The perChannel default is true, that means it contains the parameters - // of per-Channel quantization. Otherwise, that means this layer contains per-Tensor quantized parameters. - bool per_channel; - bool useWinograd = false; // Flag whether to use Winograd to speed up 3x3 convolution. - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS DeconvolutionLayer : public BaseConvolutionLayer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS LRNLayer : public Layer - { - public: - int type; - - int size; - float alpha, beta, bias; - bool normBySize; - - static Ptr create(const LayerParams& params); - }; - - - /** @brief ArgMax/ArgMin layer - * @note returns indices as floats, which means the supported range is [-2^24; 2^24] - */ - class CV_EXPORTS ArgLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - /** @brief Gather layer - */ - class CV_EXPORTS GatherLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - /** @brief GatherElements layer - * GatherElements takes two inputs data and indices of the same rank r >= 1 and an optional attribute axis and works such that: - * output[i][j][k] = data[index[i][j][k]][j][k] if axis = 0 and r = 3 - * output[i][j][k] = data[i][index[i][j][k]][k] if axis = 1 and r = 3 - * output[i][j][k] = data[i][j][index[i][j][k]] if axis = 2 and r = 3 - * - * Gather, on the other hand, takes a data tensor of rank r >= 1, and indices tensor of rank q, and works such that: - * it gathers the enteries along axis dimension of the input data indexed by indices and concatenates them in an output tensor of rank q + (r - 1) - * e.g. If axis = 0, let k = indices[i_{0}, ..., i_{q-1}] then output[i_{0}, ..., i_{q-1}, j_{0}, ..., j_{r-2}] = input[k , j_{0}, ..., j_{r-2}]: - **/ - class CV_EXPORTS GatherElementsLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS PoolingLayer : public Layer - { - public: - int type; - std::vector kernel_size, strides; - std::vector pads_begin, pads_end; - bool globalPooling; //!< Flag is true if at least one of the axes is global pooled. - std::vector isGlobalPooling; - bool computeMaxIdx; - String padMode; - bool ceilMode; - // If true for average pooling with padding, divide an every output region - // by a whole kernel area. Otherwise exclude zero padded values and divide - // by number of real values. - bool avePoolPaddedArea; - // ROIPooling parameters. - Size pooledSize; - float spatialScale; - // PSROIPooling parameters. - int psRoiOutChannels; - - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS PoolingLayerInt8 : public PoolingLayer - { - public: - int input_zp, output_zp; - float input_sc, output_sc; - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS ReduceLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS SoftmaxLayer : public Layer - { - public: - bool logSoftMax; - - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS SoftmaxLayerInt8 : public SoftmaxLayer - { - public: - float output_sc; - int output_zp; - static Ptr create(const LayerParams& params); - }; - - /** - * `InnerProduct`, `MatMul` and `Gemm` operations are all implemented by Fully Connected Layer. - * Parameter `is_matmul` is used to distinguish `MatMul` and `Gemm` from `InnerProduct`. - */ - class CV_EXPORTS InnerProductLayer : public Layer - { - public: - int axis; - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS InnerProductLayerInt8 : public InnerProductLayer - { - public: - int input_zp, output_zp; - float input_sc, output_sc; - - // quantization type flag. The perChannel default is true, that means it contains the parameters - // of per-Channel quantization. Otherwise, that means this layer contains per-Tensor quantized parameters. - bool per_channel; - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS MVNLayer : public Layer - { - public: - float eps; - bool normVariance, acrossChannels; - - static Ptr create(const LayerParams& params); - }; - - /* Reshaping */ - - class CV_EXPORTS ReshapeLayer : public Layer - { - public: - MatShape newShapeDesc; - Range newShapeRange; - - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS FlattenLayer : public Layer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS QuantizeLayer : public Layer - { - public: - std::vector scales; - std::vector zeropoints; - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS DequantizeLayer : public Layer - { - public: - std::vector scales; - std::vector zeropoints; - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS RequantizeLayer : public Layer - { - public: - float scale, shift; - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS ConcatLayer : public Layer - { - public: - int axis; - /** - * @brief Add zero padding in case of concatenation of blobs with different - * spatial sizes. - * - * Details: https://github.com/torch/nn/blob/master/doc/containers.md#depthconcat - */ - bool padding; - int paddingValue; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS SplitLayer : public Layer - { - public: - int outputsCount; //!< Number of copies that will be produced (is ignored when negative). - - static Ptr create(const LayerParams ¶ms); - }; - - /** - * Slice layer has several modes: - * 1. Caffe mode - * @param[in] axis Axis of split operation - * @param[in] slice_point Array of split points - * - * Number of output blobs equals to number of split points plus one. The - * first blob is a slice on input from 0 to @p slice_point[0] - 1 by @p axis, - * the second output blob is a slice of input from @p slice_point[0] to - * @p slice_point[1] - 1 by @p axis and the last output blob is a slice of - * input from @p slice_point[-1] up to the end of @p axis size. - * - * 2. TensorFlow mode - * @param begin Vector of start indices - * @param size Vector of sizes - * - * More convenient numpy-like slice. One and only output blob - * is a slice `input[begin[0]:begin[0]+size[0], begin[1]:begin[1]+size[1], ...]` - * - * 3. Torch mode - * @param axis Axis of split operation - * - * Split input blob on the equal parts by @p axis. - */ - class CV_EXPORTS SliceLayer : public Layer - { - public: - /** - * @brief Vector of slice ranges. - * - * The first dimension equals number of output blobs. - * Inner vector has slice ranges for the first number of input dimensions. - */ - std::vector > sliceRanges; - std::vector > sliceSteps; - int axis; - int num_split; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS PermuteLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - /** - * Permute channels of 4-dimensional input blob. - * @param group Number of groups to split input channels and pick in turns - * into output blob. - * - * \f[ groupSize = \frac{number\ of\ channels}{group} \f] - * \f[ output(n, c, h, w) = input(n, groupSize \times (c \% group) + \lfloor \frac{c}{group} \rfloor, h, w) \f] - * Read more at https://arxiv.org/pdf/1707.01083.pdf - */ - class CV_EXPORTS ShuffleChannelLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - - int group; - }; - - /** - * @brief Adds extra values for specific axes. - * @param paddings Vector of paddings in format - * @code - * [ pad_before, pad_after, // [0]th dimension - * pad_before, pad_after, // [1]st dimension - * ... - * pad_before, pad_after ] // [n]th dimension - * @endcode - * that represents number of padded values at every dimension - * starting from the first one. The rest of dimensions won't - * be padded. - * @param value Value to be padded. Defaults to zero. - * @param type Padding type: 'constant', 'reflect' - * @param input_dims Torch's parameter. If @p input_dims is not equal to the - * actual input dimensionality then the `[0]th` dimension - * is considered as a batch dimension and @p paddings are shifted - * to a one dimension. Defaults to `-1` that means padding - * corresponding to @p paddings. - */ - class CV_EXPORTS PaddingLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - /* Activations */ - class CV_EXPORTS ActivationLayer : public Layer - { - public: - virtual void forwardSlice(const float* src, float* dst, int len, - size_t outPlaneSize, int cn0, int cn1) const {} - virtual void forwardSlice(const int* src, const int* lut, int* dst, int len, - size_t outPlaneSize, int cn0, int cn1) const {} - virtual void forwardSlice(const int8_t* src, const int8_t* lut, int8_t* dst, int len, - size_t outPlaneSize, int cn0, int cn1) const {} - }; - - class CV_EXPORTS ReLULayer : public ActivationLayer - { - public: - float negativeSlope; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS ReLU6Layer : public ActivationLayer - { - public: - float minValue, maxValue; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS ChannelsPReLULayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS ELULayer : public ActivationLayer - { - public: - float alpha; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS TanHLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS SwishLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS MishLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS SigmoidLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS BNLLLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS AbsLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS PowerLayer : public ActivationLayer - { - public: - float power, scale, shift; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS ExpLayer : public ActivationLayer - { - public: - float base, scale, shift; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS CeilLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS FloorLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS LogLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS RoundLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS SqrtLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS NotLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS AcosLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS AcoshLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS AsinLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS AsinhLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS AtanLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS AtanhLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS CosLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS CoshLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS ErfLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS HardSwishLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS SinLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS SinhLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS SoftplusLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS SoftsignLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS TanLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS CeluLayer : public ActivationLayer - { - public: - float alpha; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS HardSigmoidLayer : public ActivationLayer - { - public: - float alpha; - float beta; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS SeluLayer : public ActivationLayer - { - public: - float alpha; - float gamma; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS GeluLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS GeluApproximationLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS ThresholdedReluLayer : public ActivationLayer - { - public: - float alpha; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS ActivationLayerInt8 : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS SignLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS ShrinkLayer : public ActivationLayer - { - public: - float bias; - float lambd; - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS ReciprocalLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - /* Layers used in semantic segmentation */ - - class CV_EXPORTS CropLayer : public Layer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - /** @brief Element wise operation on inputs - - Extra optional parameters: - - "operation" as string. Values are "sum" (default), "prod", "max", "div", "min" - - "coeff" as float array. Specify weights of inputs for SUM operation - - "output_channels_mode" as string. Values are "same" (default, all input must have the same layout), "input_0", "input_0_truncate", "max_input_channels" - */ - class CV_EXPORTS EltwiseLayer : public Layer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS EltwiseLayerInt8 : public Layer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS NaryEltwiseLayer : public Layer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS BatchNormLayer : public ActivationLayer - { - public: - bool hasWeights, hasBias; - float epsilon; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS BatchNormLayerInt8 : public BatchNormLayer - { - public: - float input_sc, output_sc; - int input_zp, output_zp; - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS MaxUnpoolLayer : public Layer - { - public: - Size poolKernel; - Size poolPad; - Size poolStride; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS ScaleLayer : public Layer - { - public: - bool hasBias; - int axis; - String mode; - - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS ScaleLayerInt8 : public ScaleLayer - { - public: - float output_sc; - int output_zp; - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS ShiftLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS ShiftLayerInt8 : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS CompareLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS DataAugmentationLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS CorrelationLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS AccumLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS FlowWarpLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS PriorBoxLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS ReorgLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS RegionLayer : public Layer - { - public: - float nmsThreshold; - - static Ptr create(const LayerParams& params); - }; - - /** - * @brief Detection output layer. - * - * The layer size is: @f$ (1 \times 1 \times N \times 7) @f$ - * where N is [keep_top_k] parameter multiplied by batch size. Each row is: - * [image_id, label, confidence, xmin, ymin, xmax, ymax] - * where image_id is the index of image input in the batch. - */ - class CV_EXPORTS DetectionOutputLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - /** - * @brief \f$ L_p \f$ - normalization layer. - * @param p Normalization factor. The most common `p = 1` for \f$ L_1 \f$ - - * normalization or `p = 2` for \f$ L_2 \f$ - normalization or a custom one. - * @param eps Parameter \f$ \epsilon \f$ to prevent a division by zero. - * @param across_spatial If true, normalize an input across all non-batch dimensions. - * Otherwise normalize an every channel separately. - * - * Across spatial: - * @f[ - * norm = \sqrt[p]{\epsilon + \sum_{x, y, c} |src(x, y, c)|^p } \\ - * dst(x, y, c) = \frac{ src(x, y, c) }{norm} - * @f] - * - * Channel wise normalization: - * @f[ - * norm(c) = \sqrt[p]{\epsilon + \sum_{x, y} |src(x, y, c)|^p } \\ - * dst(x, y, c) = \frac{ src(x, y, c) }{norm(c)} - * @f] - * - * Where `x, y` - spatial coordinates, `c` - channel. - * - * An every sample in the batch is normalized separately. Optionally, - * output is scaled by the trained parameters. - */ - class CV_EXPORTS NormalizeBBoxLayer : public Layer - { - public: - float pnorm, epsilon; - CV_DEPRECATED_EXTERNAL bool acrossSpatial; - - static Ptr create(const LayerParams& params); - }; - - /** - * @brief Resize input 4-dimensional blob by nearest neighbor or bilinear strategy. - * - * Layer is used to support TensorFlow's resize_nearest_neighbor and resize_bilinear ops. - */ - class CV_EXPORTS ResizeLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - /** - * @brief Bilinear resize layer from https://github.com/cdmh/deeplab-public-ver2 - * - * It differs from @ref ResizeLayer in output shape and resize scales computations. - */ - class CV_EXPORTS InterpLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS ProposalLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS CropAndResizeLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS CumSumLayer : public Layer - { - public: - int exclusive; - int reverse; - - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS ScatterLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS ScatterNDLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS TileLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS LayerNormLayer : public Layer - { - public: - CV_DEPRECATED_EXTERNAL bool hasBias; // Deprecated, preserve for compatibility - int axis; - float epsilon; - - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS GemmLayer : public Layer { - public: - bool trans_a; - bool trans_b; - float alpha; - float beta; - - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS MatMulLayer : public Layer { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS ExpandLayer : public Layer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS InstanceNormLayer : public Layer { - public: - float epsilon; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS AttentionLayer : public Layer { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS GroupNormLayer : public Layer { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS DepthToSpaceLayer : public Layer { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS SpaceToDepthLayer : public Layer { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS TopKLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - -//! @} -//! @} -CV__DNN_INLINE_NS_END -} -} -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_DNN_DNN_ALL_LAYERS_HPP +#define OPENCV_DNN_DNN_ALL_LAYERS_HPP +#include + +namespace cv { +namespace dnn { +CV__DNN_INLINE_NS_BEGIN +//! @addtogroup dnn +//! @{ + +/** @defgroup dnnLayerList Partial List of Implemented Layers + @{ + This subsection of dnn module contains information about built-in layers and their descriptions. + + Classes listed here, in fact, provides C++ API for creating instances of built-in layers. + In addition to this way of layers instantiation, there is a more common factory API (see @ref dnnLayerFactory), it allows to create layers dynamically (by name) and register new ones. + You can use both API, but factory API is less convenient for native C++ programming and basically designed for use inside importers (see @ref readNetFromCaffe(), @ref readNetFromTorch(), @ref readNetFromTensorflow()). + + Built-in layers partially reproduce functionality of corresponding Caffe and Torch7 layers. + In particular, the following layers and Caffe importer were tested to reproduce Caffe functionality: + - Convolution + - Deconvolution + - Pooling + - InnerProduct + - TanH, ReLU, Sigmoid, BNLL, Power, AbsVal + - Softmax + - Reshape, Flatten, Slice, Split + - LRN + - MVN + - Dropout (since it does nothing on forward pass -)) +*/ + + class CV_EXPORTS BlankLayer : public Layer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + /** + * Constant layer produces the same data blob at an every forward pass. + */ + class CV_EXPORTS ConstLayer : public Layer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + //! LSTM recurrent layer + class CV_EXPORTS LSTMLayer : public Layer + { + public: + /** Creates instance of LSTM layer */ + static Ptr create(const LayerParams& params); + + /** @deprecated Use LayerParams::blobs instead. + @brief Set trained weights for LSTM layer. + + LSTM behavior on each step is defined by current input, previous output, previous cell state and learned weights. + + Let @f$x_t@f$ be current input, @f$h_t@f$ be current output, @f$c_t@f$ be current state. + Than current output and current cell state is computed as follows: + @f{eqnarray*}{ + h_t &= o_t \odot tanh(c_t), \\ + c_t &= f_t \odot c_{t-1} + i_t \odot g_t, \\ + @f} + where @f$\odot@f$ is per-element multiply operation and @f$i_t, f_t, o_t, g_t@f$ is internal gates that are computed using learned weights. + + Gates are computed as follows: + @f{eqnarray*}{ + i_t &= sigmoid&(W_{xi} x_t + W_{hi} h_{t-1} + b_i), \\ + f_t &= sigmoid&(W_{xf} x_t + W_{hf} h_{t-1} + b_f), \\ + o_t &= sigmoid&(W_{xo} x_t + W_{ho} h_{t-1} + b_o), \\ + g_t &= tanh &(W_{xg} x_t + W_{hg} h_{t-1} + b_g), \\ + @f} + where @f$W_{x?}@f$, @f$W_{h?}@f$ and @f$b_{?}@f$ are learned weights represented as matrices: + @f$W_{x?} \in R^{N_h \times N_x}@f$, @f$W_{h?} \in R^{N_h \times N_h}@f$, @f$b_? \in R^{N_h}@f$. + + For simplicity and performance purposes we use @f$ W_x = [W_{xi}; W_{xf}; W_{xo}, W_{xg}] @f$ + (i.e. @f$W_x@f$ is vertical concatenation of @f$ W_{x?} @f$), @f$ W_x \in R^{4N_h \times N_x} @f$. + The same for @f$ W_h = [W_{hi}; W_{hf}; W_{ho}, W_{hg}], W_h \in R^{4N_h \times N_h} @f$ + and for @f$ b = [b_i; b_f, b_o, b_g]@f$, @f$b \in R^{4N_h} @f$. + + @param Wh is matrix defining how previous output is transformed to internal gates (i.e. according to above mentioned notation is @f$ W_h @f$) + @param Wx is matrix defining how current input is transformed to internal gates (i.e. according to above mentioned notation is @f$ W_x @f$) + @param b is bias vector (i.e. according to above mentioned notation is @f$ b @f$) + */ + CV_DEPRECATED virtual void setWeights(const Mat &Wh, const Mat &Wx, const Mat &b) = 0; + + /** @brief Specifies shape of output blob which will be [[`T`], `N`] + @p outTailShape. + * @details If this parameter is empty or unset then @p outTailShape = [`Wh`.size(0)] will be used, + * where `Wh` is parameter from setWeights(). + */ + virtual void setOutShape(const MatShape &outTailShape = MatShape()) = 0; + + /** @deprecated Use flag `produce_cell_output` in LayerParams. + * @brief Specifies either interpret first dimension of input blob as timestamp dimension either as sample. + * + * If flag is set to true then shape of input blob will be interpreted as [`T`, `N`, `[data dims]`] where `T` specifies number of timestamps, `N` is number of independent streams. + * In this case each forward() call will iterate through `T` timestamps and update layer's state `T` times. + * + * If flag is set to false then shape of input blob will be interpreted as [`N`, `[data dims]`]. + * In this case each forward() call will make one iteration and produce one timestamp with shape [`N`, `[out dims]`]. + */ + CV_DEPRECATED virtual void setUseTimstampsDim(bool use = true) = 0; + + /** @deprecated Use flag `use_timestamp_dim` in LayerParams. + * @brief If this flag is set to true then layer will produce @f$ c_t @f$ as second output. + * @details Shape of the second output is the same as first output. + */ + CV_DEPRECATED virtual void setProduceCellOutput(bool produce = false) = 0; + + /* In common case it use single input with @f$x_t@f$ values to compute output(s) @f$h_t@f$ (and @f$c_t@f$). + * @param input should contain packed values @f$x_t@f$ + * @param output contains computed outputs: @f$h_t@f$ (and @f$c_t@f$ if setProduceCellOutput() flag was set to true). + * + * If setUseTimstampsDim() is set to true then @p input[0] should has at least two dimensions with the following shape: [`T`, `N`, `[data dims]`], + * where `T` specifies number of timestamps, `N` is number of independent streams (i.e. @f$ x_{t_0 + t}^{stream} @f$ is stored inside @p input[0][t, stream, ...]). + * + * If setUseTimstampsDim() is set to false then @p input[0] should contain single timestamp, its shape should has form [`N`, `[data dims]`] with at least one dimension. + * (i.e. @f$ x_{t}^{stream} @f$ is stored inside @p input[0][stream, ...]). + */ + + int inputNameToIndex(String inputName) CV_OVERRIDE; + int outputNameToIndex(const String& outputName) CV_OVERRIDE; + }; + + /** @brief GRU recurrent one-layer + * + * Accepts input sequence and computes the final hidden state for each element in the batch. + * + * - input[0] containing the features of the input sequence. + * input[0] should have shape [`T`, `N`, `data_dims`] where `T` is sequence length, `N` is batch size, `data_dims` is input size + * - output would have shape [`T`, `N`, `D` * `hidden_size`] where `D = 2` if layer is bidirectional otherwise `D = 1` + * + * Depends on the following attributes: + * - hidden_size - Number of neurons in the hidden layer + * - direction - RNN could be bidirectional or forward + * + * The final hidden state @f$ h_t @f$ computes by the following formulas: + * + @f{eqnarray*}{ + r_t = \sigma(W_{ir} x_t + b_{ir} + W_{hr} h_{(t-1)} + b_{hr}) \\ + z_t = \sigma(W_{iz} x_t + b_{iz} + W_{hz} h_{(t-1)} + b_{hz}) \\ + n_t = \tanh(W_{in} x_t + b_{in} + r_t \odot (W_{hn} h_{(t-1)}+ b_{hn})) \\ + h_t = (1 - z_t) \odot n_t + z_t \odot h_{(t-1)} \\ + @f} + * Where @f$x_t@f$ is current input, @f$h_{(t-1)}@f$ is previous or initial hidden state. + * + * @f$W_{x?}@f$, @f$W_{h?}@f$ and @f$b_{?}@f$ are learned weights represented as matrices: + * @f$W_{x?} \in R^{N_h \times N_x}@f$, @f$W_{h?} \in R^{N_h \times N_h}@f$, @f$b_? \in R^{N_h}@f$. + * + * @f$\odot@f$ is per-element multiply operation. + */ + class CV_EXPORTS GRULayer : public Layer + { + public: + /** Creates instance of GRU layer */ + static Ptr create(const LayerParams& params); + }; + + /** @brief Classical recurrent layer + + Accepts two inputs @f$x_t@f$ and @f$h_{t-1}@f$ and compute two outputs @f$o_t@f$ and @f$h_t@f$. + + - input: should contain packed input @f$x_t@f$. + - output: should contain output @f$o_t@f$ (and @f$h_t@f$ if setProduceHiddenOutput() is set to true). + + input[0] should have shape [`T`, `N`, `data_dims`] where `T` and `N` is number of timestamps and number of independent samples of @f$x_t@f$ respectively. + + output[0] will have shape [`T`, `N`, @f$N_o@f$], where @f$N_o@f$ is number of rows in @f$ W_{xo} @f$ matrix. + + If setProduceHiddenOutput() is set to true then @p output[1] will contain a Mat with shape [`T`, `N`, @f$N_h@f$], where @f$N_h@f$ is number of rows in @f$ W_{hh} @f$ matrix. + */ + class CV_EXPORTS RNNLayer : public Layer + { + public: + /** Creates instance of RNNLayer */ + static Ptr create(const LayerParams& params); + + /** Setups learned weights. + + Recurrent-layer behavior on each step is defined by current input @f$ x_t @f$, previous state @f$ h_t @f$ and learned weights as follows: + @f{eqnarray*}{ + h_t &= tanh&(W_{hh} h_{t-1} + W_{xh} x_t + b_h), \\ + o_t &= tanh&(W_{ho} h_t + b_o), + @f} + + @param Wxh is @f$ W_{xh} @f$ matrix + @param bh is @f$ b_{h} @f$ vector + @param Whh is @f$ W_{hh} @f$ matrix + @param Who is @f$ W_{xo} @f$ matrix + @param bo is @f$ b_{o} @f$ vector + */ + virtual void setWeights(const Mat &Wxh, const Mat &bh, const Mat &Whh, const Mat &Who, const Mat &bo) = 0; + + /** @brief If this flag is set to true then layer will produce @f$ h_t @f$ as second output. + * @details Shape of the second output is the same as first output. + */ + virtual void setProduceHiddenOutput(bool produce = false) = 0; + + }; + + /** @brief This function performs array summation based + * on the Einstein summation convention. The function + * allows for concise expressions of various mathematical + * operations using subscripts. + * + * By default, the labels are placed in alphabetical + * order at the end of the output. + * For example: + * if `c = einsum("i,j", a, b)`, then `c[i,j] == a[i]*b[j]`. + * However, if `c = einsum("j,i", a, b)`, then `c[i,j] = a[j]*b[i]`. + * Alternatively, you can control the output order or prevent + * an axis from being summed/force an axis to be summed + * by providing indices for the output. + * For example: + * `diag(a)` -> `einsum("ii->i", a)` + * `sum(a, axis=0)` -> `einsum("i...->", a)` + * Subscripts at the beginning and end may be specified + * by putting an ellipsis "..." in the middle. + * For instance, the function `einsum("i...i", a)` takes + * the diagonal of the first and last dimensions of + * the operand, and `einsum("ij...,jk...->ik...")` performs + * the matrix product using the first two indices + * of each operand instead of the last two. + * When there is only one operand, no axes being summed, + * and no output parameter, this function returns + * a view into the operand instead of creating a copy. + */ + class CV_EXPORTS EinsumLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS BaseConvolutionLayer : public Layer + { + public: + CV_DEPRECATED_EXTERNAL Size kernel, stride, pad, dilation, adjustPad; + std::vector adjust_pads; + std::vector kernel_size, strides, dilations; + std::vector pads_begin, pads_end; + String padMode; + int numOutput; + }; + + class CV_EXPORTS ConvolutionLayer : public BaseConvolutionLayer + { + public: + static Ptr create(const LayerParams& params); + bool fusedActivation = false; + bool fusedAdd = false; + bool useWinograd = true; // Flag whether to use Winograd to speed up 3x3 convolution. + }; + + class CV_EXPORTS ConvolutionLayerInt8 : public BaseConvolutionLayer + { + public: + int input_zp, output_zp; + float input_sc, output_sc; + + // quantization type flag. The perChannel default is true, that means it contains the parameters + // of per-Channel quantization. Otherwise, that means this layer contains per-Tensor quantized parameters. + bool per_channel; + bool useWinograd = false; // Flag whether to use Winograd to speed up 3x3 convolution. + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS DeconvolutionLayer : public BaseConvolutionLayer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS LRNLayer : public Layer + { + public: + int type; + + int size; + float alpha, beta, bias; + bool normBySize; + + static Ptr create(const LayerParams& params); + }; + + + /** @brief ArgMax/ArgMin layer + * @note returns indices as floats, which means the supported range is [-2^24; 2^24] + */ + class CV_EXPORTS ArgLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + /** @brief Gather layer + */ + class CV_EXPORTS GatherLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + /** @brief GatherElements layer + * GatherElements takes two inputs data and indices of the same rank r >= 1 and an optional attribute axis and works such that: + * output[i][j][k] = data[index[i][j][k]][j][k] if axis = 0 and r = 3 + * output[i][j][k] = data[i][index[i][j][k]][k] if axis = 1 and r = 3 + * output[i][j][k] = data[i][j][index[i][j][k]] if axis = 2 and r = 3 + * + * Gather, on the other hand, takes a data tensor of rank r >= 1, and indices tensor of rank q, and works such that: + * it gathers the enteries along axis dimension of the input data indexed by indices and concatenates them in an output tensor of rank q + (r - 1) + * e.g. If axis = 0, let k = indices[i_{0}, ..., i_{q-1}] then output[i_{0}, ..., i_{q-1}, j_{0}, ..., j_{r-2}] = input[k , j_{0}, ..., j_{r-2}]: + **/ + class CV_EXPORTS GatherElementsLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS PoolingLayer : public Layer + { + public: + int type; + std::vector kernel_size, strides; + std::vector pads_begin, pads_end; + bool globalPooling; //!< Flag is true if at least one of the axes is global pooled. + std::vector isGlobalPooling; + bool computeMaxIdx; + String padMode; + bool ceilMode; + // If true for average pooling with padding, divide an every output region + // by a whole kernel area. Otherwise exclude zero padded values and divide + // by number of real values. + bool avePoolPaddedArea; + // ROIPooling parameters. + Size pooledSize; + float spatialScale; + // PSROIPooling parameters. + int psRoiOutChannels; + + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS PoolingLayerInt8 : public PoolingLayer + { + public: + int input_zp, output_zp; + float input_sc, output_sc; + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS ReduceLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS SoftmaxLayer : public Layer + { + public: + bool logSoftMax; + + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS SoftmaxLayerInt8 : public SoftmaxLayer + { + public: + float output_sc; + int output_zp; + static Ptr create(const LayerParams& params); + }; + + /** + * `InnerProduct`, `MatMul` and `Gemm` operations are all implemented by Fully Connected Layer. + * Parameter `is_matmul` is used to distinguish `MatMul` and `Gemm` from `InnerProduct`. + */ + class CV_EXPORTS InnerProductLayer : public Layer + { + public: + int axis; + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS InnerProductLayerInt8 : public InnerProductLayer + { + public: + int input_zp, output_zp; + float input_sc, output_sc; + + // quantization type flag. The perChannel default is true, that means it contains the parameters + // of per-Channel quantization. Otherwise, that means this layer contains per-Tensor quantized parameters. + bool per_channel; + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS MVNLayer : public Layer + { + public: + float eps; + bool normVariance, acrossChannels; + + static Ptr create(const LayerParams& params); + }; + + /* Reshaping */ + + class CV_EXPORTS ReshapeLayer : public Layer + { + public: + MatShape newShapeDesc; + Range newShapeRange; + + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS FlattenLayer : public Layer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS QuantizeLayer : public Layer + { + public: + std::vector scales; + std::vector zeropoints; + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS DequantizeLayer : public Layer + { + public: + std::vector scales; + std::vector zeropoints; + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS RequantizeLayer : public Layer + { + public: + float scale, shift; + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS ConcatLayer : public Layer + { + public: + int axis; + /** + * @brief Add zero padding in case of concatenation of blobs with different + * spatial sizes. + * + * Details: https://github.com/torch/nn/blob/master/doc/containers.md#depthconcat + */ + bool padding; + int paddingValue; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS SplitLayer : public Layer + { + public: + int outputsCount; //!< Number of copies that will be produced (is ignored when negative). + + static Ptr create(const LayerParams ¶ms); + }; + + /** + * Slice layer has several modes: + * 1. Caffe mode + * @param[in] axis Axis of split operation + * @param[in] slice_point Array of split points + * + * Number of output blobs equals to number of split points plus one. The + * first blob is a slice on input from 0 to @p slice_point[0] - 1 by @p axis, + * the second output blob is a slice of input from @p slice_point[0] to + * @p slice_point[1] - 1 by @p axis and the last output blob is a slice of + * input from @p slice_point[-1] up to the end of @p axis size. + * + * 2. TensorFlow mode + * @param begin Vector of start indices + * @param size Vector of sizes + * + * More convenient numpy-like slice. One and only output blob + * is a slice `input[begin[0]:begin[0]+size[0], begin[1]:begin[1]+size[1], ...]` + * + * 3. Torch mode + * @param axis Axis of split operation + * + * Split input blob on the equal parts by @p axis. + */ + class CV_EXPORTS SliceLayer : public Layer + { + public: + /** + * @brief Vector of slice ranges. + * + * The first dimension equals number of output blobs. + * Inner vector has slice ranges for the first number of input dimensions. + */ + std::vector > sliceRanges; + std::vector > sliceSteps; + int axis; + int num_split; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS PermuteLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + /** + * Permute channels of 4-dimensional input blob. + * @param group Number of groups to split input channels and pick in turns + * into output blob. + * + * \f[ groupSize = \frac{number\ of\ channels}{group} \f] + * \f[ output(n, c, h, w) = input(n, groupSize \times (c \% group) + \lfloor \frac{c}{group} \rfloor, h, w) \f] + * Read more at https://arxiv.org/pdf/1707.01083.pdf + */ + class CV_EXPORTS ShuffleChannelLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + + int group; + }; + + /** + * @brief Adds extra values for specific axes. + * @param paddings Vector of paddings in format + * @code + * [ pad_before, pad_after, // [0]th dimension + * pad_before, pad_after, // [1]st dimension + * ... + * pad_before, pad_after ] // [n]th dimension + * @endcode + * that represents number of padded values at every dimension + * starting from the first one. The rest of dimensions won't + * be padded. + * @param value Value to be padded. Defaults to zero. + * @param type Padding type: 'constant', 'reflect' + * @param input_dims Torch's parameter. If @p input_dims is not equal to the + * actual input dimensionality then the `[0]th` dimension + * is considered as a batch dimension and @p paddings are shifted + * to a one dimension. Defaults to `-1` that means padding + * corresponding to @p paddings. + */ + class CV_EXPORTS PaddingLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + /* Activations */ + class CV_EXPORTS ActivationLayer : public Layer + { + public: + virtual void forwardSlice(const float* src, float* dst, int len, + size_t outPlaneSize, int cn0, int cn1) const {} + virtual void forwardSlice(const int* src, const int* lut, int* dst, int len, + size_t outPlaneSize, int cn0, int cn1) const {} + virtual void forwardSlice(const int8_t* src, const int8_t* lut, int8_t* dst, int len, + size_t outPlaneSize, int cn0, int cn1) const {} + }; + + class CV_EXPORTS ReLULayer : public ActivationLayer + { + public: + float negativeSlope; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS ReLU6Layer : public ActivationLayer + { + public: + float minValue, maxValue; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS ChannelsPReLULayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS ELULayer : public ActivationLayer + { + public: + float alpha; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS TanHLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS SwishLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS MishLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS SigmoidLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS BNLLLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS AbsLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS PowerLayer : public ActivationLayer + { + public: + float power, scale, shift; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS ExpLayer : public ActivationLayer + { + public: + float base, scale, shift; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS CeilLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS FloorLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS LogLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS RoundLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS SqrtLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS NotLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS AcosLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS AcoshLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS AsinLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS AsinhLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS AtanLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS AtanhLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS CosLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS CoshLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS ErfLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS HardSwishLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS SinLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS SinhLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS SoftplusLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS SoftsignLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS TanLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS CeluLayer : public ActivationLayer + { + public: + float alpha; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS HardSigmoidLayer : public ActivationLayer + { + public: + float alpha; + float beta; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS SeluLayer : public ActivationLayer + { + public: + float alpha; + float gamma; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS GeluLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS GeluApproximationLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS ThresholdedReluLayer : public ActivationLayer + { + public: + float alpha; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS ActivationLayerInt8 : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS SignLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS ShrinkLayer : public ActivationLayer + { + public: + float bias; + float lambd; + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS ReciprocalLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + /* Layers used in semantic segmentation */ + + class CV_EXPORTS CropLayer : public Layer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + /** @brief Element wise operation on inputs + + Extra optional parameters: + - "operation" as string. Values are "sum" (default), "prod", "max", "div", "min" + - "coeff" as float array. Specify weights of inputs for SUM operation + - "output_channels_mode" as string. Values are "same" (default, all input must have the same layout), "input_0", "input_0_truncate", "max_input_channels" + */ + class CV_EXPORTS EltwiseLayer : public Layer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS EltwiseLayerInt8 : public Layer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS NaryEltwiseLayer : public Layer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS BatchNormLayer : public ActivationLayer + { + public: + bool hasWeights, hasBias; + float epsilon; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS BatchNormLayerInt8 : public BatchNormLayer + { + public: + float input_sc, output_sc; + int input_zp, output_zp; + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS MaxUnpoolLayer : public Layer + { + public: + Size poolKernel; + Size poolPad; + Size poolStride; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS ScaleLayer : public Layer + { + public: + bool hasBias; + int axis; + String mode; + + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS ScaleLayerInt8 : public ScaleLayer + { + public: + float output_sc; + int output_zp; + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS ShiftLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS ShiftLayerInt8 : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS CompareLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS DataAugmentationLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS CorrelationLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS AccumLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS FlowWarpLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS PriorBoxLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS ReorgLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS RegionLayer : public Layer + { + public: + float nmsThreshold; + + static Ptr create(const LayerParams& params); + }; + + /** + * @brief Detection output layer. + * + * The layer size is: @f$ (1 \times 1 \times N \times 7) @f$ + * where N is [keep_top_k] parameter multiplied by batch size. Each row is: + * [image_id, label, confidence, xmin, ymin, xmax, ymax] + * where image_id is the index of image input in the batch. + */ + class CV_EXPORTS DetectionOutputLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + /** + * @brief \f$ L_p \f$ - normalization layer. + * @param p Normalization factor. The most common `p = 1` for \f$ L_1 \f$ - + * normalization or `p = 2` for \f$ L_2 \f$ - normalization or a custom one. + * @param eps Parameter \f$ \epsilon \f$ to prevent a division by zero. + * @param across_spatial If true, normalize an input across all non-batch dimensions. + * Otherwise normalize an every channel separately. + * + * Across spatial: + * @f[ + * norm = \sqrt[p]{\epsilon + \sum_{x, y, c} |src(x, y, c)|^p } \\ + * dst(x, y, c) = \frac{ src(x, y, c) }{norm} + * @f] + * + * Channel wise normalization: + * @f[ + * norm(c) = \sqrt[p]{\epsilon + \sum_{x, y} |src(x, y, c)|^p } \\ + * dst(x, y, c) = \frac{ src(x, y, c) }{norm(c)} + * @f] + * + * Where `x, y` - spatial coordinates, `c` - channel. + * + * An every sample in the batch is normalized separately. Optionally, + * output is scaled by the trained parameters. + */ + class CV_EXPORTS NormalizeBBoxLayer : public Layer + { + public: + float pnorm, epsilon; + CV_DEPRECATED_EXTERNAL bool acrossSpatial; + + static Ptr create(const LayerParams& params); + }; + + /** + * @brief Resize input 4-dimensional blob by nearest neighbor or bilinear strategy. + * + * Layer is used to support TensorFlow's resize_nearest_neighbor and resize_bilinear ops. + */ + class CV_EXPORTS ResizeLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + /** + * @brief Bilinear resize layer from https://github.com/cdmh/deeplab-public-ver2 + * + * It differs from @ref ResizeLayer in output shape and resize scales computations. + */ + class CV_EXPORTS InterpLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS ProposalLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS CropAndResizeLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS CumSumLayer : public Layer + { + public: + int exclusive; + int reverse; + + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS ScatterLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS ScatterNDLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS TileLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS LayerNormLayer : public Layer + { + public: + CV_DEPRECATED_EXTERNAL bool hasBias; // Deprecated, preserve for compatibility + int axis; + float epsilon; + + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS GemmLayer : public Layer { + public: + bool trans_a; + bool trans_b; + float alpha; + float beta; + + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS MatMulLayer : public Layer { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS ExpandLayer : public Layer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS InstanceNormLayer : public Layer { + public: + float epsilon; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS AttentionLayer : public Layer { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS GroupNormLayer : public Layer { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS DepthToSpaceLayer : public Layer { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS SpaceToDepthLayer : public Layer { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS TopKLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + +//! @} +//! @} +CV__DNN_INLINE_NS_END +} +} +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/dnn/dict.hpp b/3rdParty/opencv-4.11.0/opencv2/dnn/dict.hpp index 059ce9b28e..938b4e7df6 100644 --- a/3rdParty/opencv-4.11.0/opencv2/dnn/dict.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/dnn/dict.hpp @@ -1,160 +1,160 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#include -#include -#include - -#include - -#ifndef OPENCV_DNN_DNN_DICT_HPP -#define OPENCV_DNN_DNN_DICT_HPP - -namespace cv { -namespace dnn { -CV__DNN_INLINE_NS_BEGIN -//! @addtogroup dnn -//! @{ - -/** @brief This struct stores the scalar value (or array) of one of the following type: double, cv::String or int64. - * @todo Maybe int64 is useless because double type exactly stores at least 2^52 integers. - */ -struct CV_EXPORTS_W DictValue -{ - DictValue(const DictValue &r); - explicit DictValue(bool i) : type(Param::INT), pi(new AutoBuffer) { (*pi)[0] = i ? 1 : 0; } //!< Constructs integer scalar - explicit DictValue(int64 i = 0) : type(Param::INT), pi(new AutoBuffer) { (*pi)[0] = i; } //!< Constructs integer scalar - CV_WRAP explicit DictValue(int i) : type(Param::INT), pi(new AutoBuffer) { (*pi)[0] = i; } //!< Constructs integer scalar - explicit DictValue(unsigned p) : type(Param::INT), pi(new AutoBuffer) { (*pi)[0] = p; } //!< Constructs integer scalar - CV_WRAP explicit DictValue(double p) : type(Param::REAL), pd(new AutoBuffer) { (*pd)[0] = p; } //!< Constructs floating point scalar - CV_WRAP explicit DictValue(const String &s) : type(Param::STRING), ps(new AutoBuffer) { (*ps)[0] = s; } //!< Constructs string scalar - explicit DictValue(const char *s) : type(Param::STRING), ps(new AutoBuffer) { (*ps)[0] = s; } //!< @overload - - template - static DictValue arrayInt(TypeIter begin, int size); //!< Constructs integer array - template - static DictValue arrayReal(TypeIter begin, int size); //!< Constructs floating point array - template - static DictValue arrayString(TypeIter begin, int size); //!< Constructs array of strings - - template - T get(int idx = -1) const; //!< Tries to convert array element with specified index to requested type and returns its. - - int size() const; - - CV_WRAP bool isInt() const; - CV_WRAP bool isString() const; - CV_WRAP bool isReal() const; - - CV_WRAP int getIntValue(int idx = -1) const; - CV_WRAP double getRealValue(int idx = -1) const; - CV_WRAP String getStringValue(int idx = -1) const; - - DictValue &operator=(const DictValue &r); - - friend std::ostream &operator<<(std::ostream &stream, const DictValue &dictv); - - ~DictValue(); - -private: - - Param type; - - union - { - AutoBuffer *pi; - AutoBuffer *pd; - AutoBuffer *ps; - void *pv; - }; - - DictValue(Param _type, void *_p) : type(_type), pv(_p) {} - void release(); -}; - -/** @brief This class implements name-value dictionary, values are instances of DictValue. */ -class CV_EXPORTS Dict -{ - typedef std::map _Dict; - _Dict dict; - -public: - - //! Checks a presence of the @p key in the dictionary. - bool has(const String &key) const; - - //! If the @p key in the dictionary then returns pointer to its value, else returns NULL. - DictValue *ptr(const String &key); - - /** @overload */ - const DictValue *ptr(const String &key) const; - - //! If the @p key in the dictionary then returns its value, else an error will be generated. - const DictValue &get(const String &key) const; - - /** @overload */ - template - T get(const String &key) const; - - //! If the @p key in the dictionary then returns its value, else returns @p defaultValue. - template - T get(const String &key, const T &defaultValue) const; - - //! Sets new @p value for the @p key, or adds new key-value pair into the dictionary. - template - const T &set(const String &key, const T &value); - - //! Erase @p key from the dictionary. - void erase(const String &key); - - friend std::ostream &operator<<(std::ostream &stream, const Dict &dict); - - std::map::const_iterator begin() const; - - std::map::const_iterator end() const; -}; - -//! @} -CV__DNN_INLINE_NS_END -} -} - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#include +#include +#include + +#include + +#ifndef OPENCV_DNN_DNN_DICT_HPP +#define OPENCV_DNN_DNN_DICT_HPP + +namespace cv { +namespace dnn { +CV__DNN_INLINE_NS_BEGIN +//! @addtogroup dnn +//! @{ + +/** @brief This struct stores the scalar value (or array) of one of the following type: double, cv::String or int64. + * @todo Maybe int64 is useless because double type exactly stores at least 2^52 integers. + */ +struct CV_EXPORTS_W DictValue +{ + DictValue(const DictValue &r); + explicit DictValue(bool i) : type(Param::INT), pi(new AutoBuffer) { (*pi)[0] = i ? 1 : 0; } //!< Constructs integer scalar + explicit DictValue(int64 i = 0) : type(Param::INT), pi(new AutoBuffer) { (*pi)[0] = i; } //!< Constructs integer scalar + CV_WRAP explicit DictValue(int i) : type(Param::INT), pi(new AutoBuffer) { (*pi)[0] = i; } //!< Constructs integer scalar + explicit DictValue(unsigned p) : type(Param::INT), pi(new AutoBuffer) { (*pi)[0] = p; } //!< Constructs integer scalar + CV_WRAP explicit DictValue(double p) : type(Param::REAL), pd(new AutoBuffer) { (*pd)[0] = p; } //!< Constructs floating point scalar + CV_WRAP explicit DictValue(const String &s) : type(Param::STRING), ps(new AutoBuffer) { (*ps)[0] = s; } //!< Constructs string scalar + explicit DictValue(const char *s) : type(Param::STRING), ps(new AutoBuffer) { (*ps)[0] = s; } //!< @overload + + template + static DictValue arrayInt(TypeIter begin, int size); //!< Constructs integer array + template + static DictValue arrayReal(TypeIter begin, int size); //!< Constructs floating point array + template + static DictValue arrayString(TypeIter begin, int size); //!< Constructs array of strings + + template + T get(int idx = -1) const; //!< Tries to convert array element with specified index to requested type and returns its. + + int size() const; + + CV_WRAP bool isInt() const; + CV_WRAP bool isString() const; + CV_WRAP bool isReal() const; + + CV_WRAP int getIntValue(int idx = -1) const; + CV_WRAP double getRealValue(int idx = -1) const; + CV_WRAP String getStringValue(int idx = -1) const; + + DictValue &operator=(const DictValue &r); + + friend std::ostream &operator<<(std::ostream &stream, const DictValue &dictv); + + ~DictValue(); + +private: + + Param type; + + union + { + AutoBuffer *pi; + AutoBuffer *pd; + AutoBuffer *ps; + void *pv; + }; + + DictValue(Param _type, void *_p) : type(_type), pv(_p) {} + void release(); +}; + +/** @brief This class implements name-value dictionary, values are instances of DictValue. */ +class CV_EXPORTS Dict +{ + typedef std::map _Dict; + _Dict dict; + +public: + + //! Checks a presence of the @p key in the dictionary. + bool has(const String &key) const; + + //! If the @p key in the dictionary then returns pointer to its value, else returns NULL. + DictValue *ptr(const String &key); + + /** @overload */ + const DictValue *ptr(const String &key) const; + + //! If the @p key in the dictionary then returns its value, else an error will be generated. + const DictValue &get(const String &key) const; + + /** @overload */ + template + T get(const String &key) const; + + //! If the @p key in the dictionary then returns its value, else returns @p defaultValue. + template + T get(const String &key, const T &defaultValue) const; + + //! Sets new @p value for the @p key, or adds new key-value pair into the dictionary. + template + const T &set(const String &key, const T &value); + + //! Erase @p key from the dictionary. + void erase(const String &key); + + friend std::ostream &operator<<(std::ostream &stream, const Dict &dict); + + std::map::const_iterator begin() const; + + std::map::const_iterator end() const; +}; + +//! @} +CV__DNN_INLINE_NS_END +} +} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/dnn/dnn.hpp b/3rdParty/opencv-4.11.0/opencv2/dnn/dnn.hpp index 0077ae4853..105e973193 100644 --- a/3rdParty/opencv-4.11.0/opencv2/dnn/dnn.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/dnn/dnn.hpp @@ -1,1946 +1,1946 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_DNN_DNN_HPP -#define OPENCV_DNN_DNN_HPP - -#include -#include -#include "opencv2/core/async.hpp" - -#include "../dnn/version.hpp" - -#include - -namespace cv { -namespace dnn { - -namespace accessor { -class DnnNetAccessor; // forward declaration -} - -CV__DNN_INLINE_NS_BEGIN -//! @addtogroup dnn -//! @{ - - typedef std::vector MatShape; - - /** - * @brief Enum of computation backends supported by layers. - * @see Net::setPreferableBackend - */ - enum Backend - { - //! DNN_BACKEND_DEFAULT equals to OPENCV_DNN_BACKEND_DEFAULT, which can be defined using CMake or a configuration parameter - DNN_BACKEND_DEFAULT = 0, - DNN_BACKEND_HALIDE, - DNN_BACKEND_INFERENCE_ENGINE, //!< Intel OpenVINO computational backend - //!< @note Tutorial how to build OpenCV with OpenVINO: @ref tutorial_dnn_openvino - DNN_BACKEND_OPENCV, - DNN_BACKEND_VKCOM, - DNN_BACKEND_CUDA, - DNN_BACKEND_WEBNN, - DNN_BACKEND_TIMVX, - DNN_BACKEND_CANN, -#if defined(__OPENCV_BUILD) || defined(BUILD_PLUGIN) -#if !defined(OPENCV_BINDING_PARSER) - DNN_BACKEND_INFERENCE_ENGINE_NGRAPH = 1000000, // internal - use DNN_BACKEND_INFERENCE_ENGINE + setInferenceEngineBackendType() - DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019, // internal - use DNN_BACKEND_INFERENCE_ENGINE + setInferenceEngineBackendType() -#endif -#endif - }; - - /** - * @brief Enum of target devices for computations. - * @see Net::setPreferableTarget - */ - enum Target - { - DNN_TARGET_CPU = 0, - DNN_TARGET_OPENCL, - DNN_TARGET_OPENCL_FP16, - DNN_TARGET_MYRIAD, - DNN_TARGET_VULKAN, - DNN_TARGET_FPGA, //!< FPGA device with CPU fallbacks using Inference Engine's Heterogeneous plugin. - DNN_TARGET_CUDA, - DNN_TARGET_CUDA_FP16, - DNN_TARGET_HDDL, - DNN_TARGET_NPU, - DNN_TARGET_CPU_FP16, // Only the ARM platform is supported. Low precision computing, accelerate model inference. - }; - - /** - * @brief Enum of data layout for model inference. - * @see Image2BlobParams - */ - enum DataLayout - { - DNN_LAYOUT_UNKNOWN = 0, - DNN_LAYOUT_ND = 1, //!< OpenCV data layout for 2D data. - DNN_LAYOUT_NCHW = 2, //!< OpenCV data layout for 4D data. - DNN_LAYOUT_NCDHW = 3, //!< OpenCV data layout for 5D data. - DNN_LAYOUT_NHWC = 4, //!< Tensorflow-like data layout for 4D data. - DNN_LAYOUT_NDHWC = 5, //!< Tensorflow-like data layout for 5D data. - DNN_LAYOUT_PLANAR = 6, //!< Tensorflow-like data layout, it should only be used at tf or tflite model parsing. - }; - - CV_EXPORTS std::vector< std::pair > getAvailableBackends(); - CV_EXPORTS_W std::vector getAvailableTargets(dnn::Backend be); - - /** - * @brief Enables detailed logging of the DNN model loading with CV DNN API. - * @param[in] isDiagnosticsMode Indicates whether diagnostic mode should be set. - * - * Diagnostic mode provides detailed logging of the model loading stage to explore - * potential problems (ex.: not implemented layer type). - * - * @note In diagnostic mode series of assertions will be skipped, it can lead to the - * expected application crash. - */ - CV_EXPORTS void enableModelDiagnostics(bool isDiagnosticsMode); - - /** @brief This class provides all data needed to initialize layer. - * - * It includes dictionary with scalar params (which can be read by using Dict interface), - * blob params #blobs and optional meta information: #name and #type of layer instance. - */ - class CV_EXPORTS LayerParams : public Dict - { - public: - //TODO: Add ability to name blob params - std::vector blobs; //!< List of learned parameters stored as blobs. - - String name; //!< Name of the layer instance (optional, can be used internal purposes). - String type; //!< Type name which was used for creating layer by layer factory (optional). - }; - - /** - * @brief Derivatives of this class encapsulates functions of certain backends. - */ - class BackendNode - { - public: - explicit BackendNode(int backendId); - - virtual ~BackendNode(); //!< Virtual destructor to make polymorphism. - - int backendId; //!< Backend identifier. - }; - - /** - * @brief Derivatives of this class wraps cv::Mat for different backends and targets. - */ - class BackendWrapper - { - public: - BackendWrapper(int backendId, int targetId); - - /** - * @brief Wrap cv::Mat for specific backend and target. - * @param[in] targetId Target identifier. - * @param[in] m cv::Mat for wrapping. - * - * Make CPU->GPU data transfer if it's require for the target. - */ - BackendWrapper(int targetId, const cv::Mat& m); - - /** - * @brief Make wrapper for reused cv::Mat. - * @param[in] base Wrapper of cv::Mat that will be reused. - * @param[in] shape Specific shape. - * - * Initialize wrapper from another one. It'll wrap the same host CPU - * memory and mustn't allocate memory on device(i.e. GPU). It might - * has different shape. Use in case of CPU memory reusing for reuse - * associated memory on device too. - */ - BackendWrapper(const Ptr& base, const MatShape& shape); - - virtual ~BackendWrapper(); //!< Virtual destructor to make polymorphism. - - /** - * @brief Transfer data to CPU host memory. - */ - virtual void copyToHost() = 0; - - /** - * @brief Indicate that an actual data is on CPU. - */ - virtual void setHostDirty() = 0; - - int backendId; //!< Backend identifier. - int targetId; //!< Target identifier. - }; - - class CV_EXPORTS ActivationLayer; - - /** @brief This interface class allows to build new Layers - are building blocks of networks. - * - * Each class, derived from Layer, must implement forward() method to compute outputs. - * Also before using the new layer into networks you must register your layer by using one of @ref dnnLayerFactory "LayerFactory" macros. - */ - class CV_EXPORTS_W Layer : public Algorithm - { - public: - - //! List of learned parameters must be stored here to allow read them by using Net::getParam(). - CV_PROP_RW std::vector blobs; - - /** @brief Computes and sets internal parameters according to inputs, outputs and blobs. - * @deprecated Use Layer::finalize(InputArrayOfArrays, OutputArrayOfArrays) instead - * @param[in] input vector of already allocated input blobs - * @param[out] output vector of already allocated output blobs - * - * This method is called after network has allocated all memory for input and output blobs - * and before inferencing. - */ - CV_DEPRECATED_EXTERNAL - virtual void finalize(const std::vector &input, std::vector &output); - - /** @brief Computes and sets internal parameters according to inputs, outputs and blobs. - * @param[in] inputs vector of already allocated input blobs - * @param[out] outputs vector of already allocated output blobs - * - * This method is called after network has allocated all memory for input and output blobs - * and before inferencing. - */ - CV_WRAP virtual void finalize(InputArrayOfArrays inputs, OutputArrayOfArrays outputs); - - /** @brief Given the @p input blobs, computes the output @p blobs. - * @deprecated Use Layer::forward(InputArrayOfArrays, OutputArrayOfArrays, OutputArrayOfArrays) instead - * @param[in] input the input blobs. - * @param[out] output allocated output blobs, which will store results of the computation. - * @param[out] internals allocated internal blobs - */ - CV_DEPRECATED_EXTERNAL - virtual void forward(std::vector &input, std::vector &output, std::vector &internals); - - /** @brief Given the @p input blobs, computes the output @p blobs. - * @param[in] inputs the input blobs. - * @param[out] outputs allocated output blobs, which will store results of the computation. - * @param[out] internals allocated internal blobs - */ - virtual void forward(InputArrayOfArrays inputs, OutputArrayOfArrays outputs, OutputArrayOfArrays internals); - - /** @brief Tries to quantize the given layer and compute the quantization parameters required for fixed point implementation. - * @param[in] scales input and output scales. - * @param[in] zeropoints input and output zeropoints. - * @param[out] params Quantized parameters required for fixed point implementation of that layer. - * @returns True if layer can be quantized. - */ - virtual bool tryQuantize(const std::vector > &scales, - const std::vector > &zeropoints, LayerParams& params); - - /** @brief Given the @p input blobs, computes the output @p blobs. - * @param[in] inputs the input blobs. - * @param[out] outputs allocated output blobs, which will store results of the computation. - * @param[out] internals allocated internal blobs - */ - void forward_fallback(InputArrayOfArrays inputs, OutputArrayOfArrays outputs, OutputArrayOfArrays internals); - - /** @brief - * @overload - * @deprecated Use Layer::finalize(InputArrayOfArrays, OutputArrayOfArrays) instead - */ - CV_DEPRECATED_EXTERNAL - void finalize(const std::vector &inputs, CV_OUT std::vector &outputs); - - /** @brief - * @overload - * @deprecated Use Layer::finalize(InputArrayOfArrays, OutputArrayOfArrays) instead - */ - CV_DEPRECATED std::vector finalize(const std::vector &inputs); - - /** @brief Allocates layer and computes output. - * @deprecated This method will be removed in the future release. - */ - CV_DEPRECATED CV_WRAP void run(const std::vector &inputs, CV_OUT std::vector &outputs, - CV_IN_OUT std::vector &internals); - - /** @brief Returns index of input blob into the input array. - * @param inputName label of input blob - * - * Each layer input and output can be labeled to easily identify them using "%[.output_name]" notation. - * This method maps label of input blob to its index into input vector. - */ - virtual int inputNameToIndex(String inputName); // FIXIT const - /** @brief Returns index of output blob in output array. - * @see inputNameToIndex() - */ - CV_WRAP virtual int outputNameToIndex(const String& outputName); // FIXIT const - - /** - * @brief Ask layer if it support specific backend for doing computations. - * @param[in] backendId computation backend identifier. - * @see Backend - */ - virtual bool supportBackend(int backendId); // FIXIT const - - /** - * @brief Returns Halide backend node. - * @param[in] inputs Input Halide buffers. - * @see BackendNode, BackendWrapper - * - * Input buffers should be exactly the same that will be used in forward invocations. - * Despite we can use Halide::ImageParam based on input shape only, - * it helps prevent some memory management issues (if something wrong, - * Halide tests will be failed). - */ - virtual Ptr initHalide(const std::vector > &inputs); - - virtual Ptr initNgraph(const std::vector > &inputs, const std::vector >& nodes); - - virtual Ptr initVkCom(const std::vector > &inputs, std::vector > &outputs); - - virtual Ptr initWebnn(const std::vector > &inputs, const std::vector >& nodes); - - /** - * @brief Returns a CUDA backend node - * - * @param context void pointer to CSLContext object - * @param inputs layer inputs - * @param outputs layer outputs - */ - virtual Ptr initCUDA( - void *context, - const std::vector>& inputs, - const std::vector>& outputs - ); - - /** - * @brief Returns a TimVX backend node - * - * @param timVxInfo void pointer to CSLContext object - * @param inputsWrapper layer inputs - * @param outputsWrapper layer outputs - * @param isLast if the node is the last one of the TimVX Graph. - */ - virtual Ptr initTimVX(void* timVxInfo, - const std::vector > &inputsWrapper, - const std::vector > &outputsWrapper, - bool isLast); - - /** - * @brief Returns a CANN backend node - * - * @param inputs input tensors of CANN operator - * @param outputs output tensors of CANN operator - * @param nodes nodes of input tensors - */ - virtual Ptr initCann(const std::vector > &inputs, - const std::vector > &outputs, - const std::vector >& nodes); - - /** - * @brief Automatic Halide scheduling based on layer hyper-parameters. - * @param[in] node Backend node with Halide functions. - * @param[in] inputs Blobs that will be used in forward invocations. - * @param[in] outputs Blobs that will be used in forward invocations. - * @param[in] targetId Target identifier - * @see BackendNode, Target - * - * Layer don't use own Halide::Func members because we can have applied - * layers fusing. In this way the fused function should be scheduled. - */ - virtual void applyHalideScheduler(Ptr& node, - const std::vector &inputs, - const std::vector &outputs, - int targetId) const; - - /** - * @brief Implement layers fusing. - * @param[in] node Backend node of bottom layer. - * @see BackendNode - * - * Actual for graph-based backends. If layer attached successfully, - * returns non-empty cv::Ptr to node of the same backend. - * Fuse only over the last function. - */ - virtual Ptr tryAttach(const Ptr& node); - - /** - * @brief Tries to attach to the layer the subsequent activation layer, i.e. do the layer fusion in a partial case. - * @param[in] layer The subsequent activation layer. - * - * Returns true if the activation layer has been attached successfully. - */ - virtual bool setActivation(const Ptr& layer); - - /** - * @brief Try to fuse current layer with a next one - * @param[in] top Next layer to be fused. - * @returns True if fusion was performed. - */ - virtual bool tryFuse(Ptr& top); - - /** - * @brief Returns parameters of layers with channel-wise multiplication and addition. - * @param[out] scale Channel-wise multipliers. Total number of values should - * be equal to number of channels. - * @param[out] shift Channel-wise offsets. Total number of values should - * be equal to number of channels. - * - * Some layers can fuse their transformations with further layers. - * In example, convolution + batch normalization. This way base layer - * use weights from layer after it. Fused layer is skipped. - * By default, @p scale and @p shift are empty that means layer has no - * element-wise multiplications or additions. - */ - virtual void getScaleShift(Mat& scale, Mat& shift) const; - - /** - * @brief Returns scale and zeropoint of layers - * @param[out] scale Output scale - * @param[out] zeropoint Output zeropoint - * - * By default, @p scale is 1 and @p zeropoint is 0. - */ - virtual void getScaleZeropoint(float& scale, int& zeropoint) const; - - - /** - * @brief "Detaches" all the layers, attached to particular layer. - */ - virtual void unsetAttached(); - - virtual bool getMemoryShapes(const std::vector &inputs, - const int requiredOutputs, - std::vector &outputs, - std::vector &internals) const; - - virtual int64 getFLOPS(const std::vector &inputs, - const std::vector &outputs) const {CV_UNUSED(inputs); CV_UNUSED(outputs); return 0;} - - virtual bool updateMemoryShapes(const std::vector &inputs); - - CV_PROP String name; //!< Name of the layer instance, can be used for logging or other internal purposes. - CV_PROP String type; //!< Type name which was used for creating layer by layer factory. - CV_PROP int preferableTarget; //!< prefer target for layer forwarding - - Layer(); - explicit Layer(const LayerParams ¶ms); //!< Initializes only #name, #type and #blobs fields. - void setParamsFrom(const LayerParams ¶ms); //!< Initializes only #name, #type and #blobs fields. - virtual ~Layer(); - }; - - /** @brief This class allows to create and manipulate comprehensive artificial neural networks. - * - * Neural network is presented as directed acyclic graph (DAG), where vertices are Layer instances, - * and edges specify relationships between layers inputs and outputs. - * - * Each network layer has unique integer id and unique string name inside its network. - * LayerId can store either layer name or layer id. - * - * This class supports reference counting of its instances, i. e. copies point to the same instance. - */ - class CV_EXPORTS_W_SIMPLE Net - { - public: - - CV_WRAP Net(); //!< Default constructor. - CV_WRAP ~Net(); //!< Destructor frees the net only if there aren't references to the net anymore. - - /** @brief Create a network from Intel's Model Optimizer intermediate representation (IR). - * @param[in] xml XML configuration file with network's topology. - * @param[in] bin Binary file with trained weights. - * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine - * backend. - */ - CV_WRAP static Net readFromModelOptimizer(CV_WRAP_FILE_PATH const String& xml, CV_WRAP_FILE_PATH const String& bin); - - /** @brief Create a network from Intel's Model Optimizer in-memory buffers with intermediate representation (IR). - * @param[in] bufferModelConfig buffer with model's configuration. - * @param[in] bufferWeights buffer with model's trained weights. - * @returns Net object. - */ - CV_WRAP static - Net readFromModelOptimizer(const std::vector& bufferModelConfig, const std::vector& bufferWeights); - - /** @brief Create a network from Intel's Model Optimizer in-memory buffers with intermediate representation (IR). - * @param[in] bufferModelConfigPtr buffer pointer of model's configuration. - * @param[in] bufferModelConfigSize buffer size of model's configuration. - * @param[in] bufferWeightsPtr buffer pointer of model's trained weights. - * @param[in] bufferWeightsSize buffer size of model's trained weights. - * @returns Net object. - */ - static - Net readFromModelOptimizer(const uchar* bufferModelConfigPtr, size_t bufferModelConfigSize, - const uchar* bufferWeightsPtr, size_t bufferWeightsSize); - - /** Returns true if there are no layers in the network. */ - CV_WRAP bool empty() const; - - /** @brief Dump net to String - * @returns String with structure, hyperparameters, backend, target and fusion - * Call method after setInput(). To see correct backend, target and fusion run after forward(). - */ - CV_WRAP String dump(); - /** @brief Dump net structure, hyperparameters, backend, target and fusion to dot file - * @param path path to output file with .dot extension - * @see dump() - */ - CV_WRAP void dumpToFile(CV_WRAP_FILE_PATH const String& path); - /** @brief Dump net structure, hyperparameters, backend, target and fusion to pbtxt file - * @param path path to output file with .pbtxt extension - * - * Use Netron (https://netron.app) to open the target file to visualize the model. - * Call method after setInput(). To see correct backend, target and fusion run after forward(). - */ - CV_WRAP void dumpToPbtxt(CV_WRAP_FILE_PATH const String& path); - - /** @brief Adds new layer to the net. - * @param name unique name of the adding layer. - * @param type typename of the adding layer (type must be registered in LayerRegister). - * @param dtype datatype of output blobs. - * @param params parameters which will be used to initialize the creating layer. - * @returns unique identifier of created layer, or -1 if a failure will happen. - */ - CV_WRAP int addLayer(const String &name, const String &type, const int &dtype, LayerParams ¶ms); - - /** @overload Datatype of output blobs set to default CV_32F */ - int addLayer(const String &name, const String &type, LayerParams ¶ms); - - /** @brief Adds new layer and connects its first input to the first output of previously added layer. - * @see addLayer() - */ - CV_WRAP int addLayerToPrev(const String &name, const String &type, const int &dtype, LayerParams ¶ms); - - /** @overload */ - int addLayerToPrev(const String &name, const String &type, LayerParams ¶ms); - - /** @brief Converts string name of the layer to the integer identifier. - * @returns id of the layer, or -1 if the layer wasn't found. - */ - CV_WRAP int getLayerId(const String &layer) const; - - CV_WRAP std::vector getLayerNames() const; - - /** @brief Container for strings and integers. - * - * @deprecated Use getLayerId() with int result. - */ - typedef DictValue LayerId; - - /** @brief Returns pointer to layer with specified id or name which the network use. */ - CV_WRAP Ptr getLayer(int layerId) const; - /** @overload - * @deprecated Use int getLayerId(const String &layer) - */ - CV_WRAP inline Ptr getLayer(const String& layerName) const { return getLayer(getLayerId(layerName)); } - /** @overload - * @deprecated to be removed - */ - CV_WRAP Ptr getLayer(const LayerId& layerId) const; - - /** @brief Returns pointers to input layers of specific layer. */ - std::vector > getLayerInputs(int layerId) const; // FIXIT: CV_WRAP - - /** @brief Connects output of the first layer to input of the second layer. - * @param outPin descriptor of the first layer output. - * @param inpPin descriptor of the second layer input. - * - * Descriptors have the following template <layer_name>[.input_number]: - * - the first part of the template layer_name is string name of the added layer. - * If this part is empty then the network input pseudo layer will be used; - * - the second optional part of the template input_number - * is either number of the layer input, either label one. - * If this part is omitted then the first layer input will be used. - * - * @see setNetInputs(), Layer::inputNameToIndex(), Layer::outputNameToIndex() - */ - CV_WRAP void connect(String outPin, String inpPin); - - /** @brief Connects #@p outNum output of the first layer to #@p inNum input of the second layer. - * @param outLayerId identifier of the first layer - * @param outNum number of the first layer output - * @param inpLayerId identifier of the second layer - * @param inpNum number of the second layer input - */ - void connect(int outLayerId, int outNum, int inpLayerId, int inpNum); - - /** @brief Registers network output with name - * - * Function may create additional 'Identity' layer. - * - * @param outputName identifier of the output - * @param layerId identifier of the second layer - * @param outputPort number of the second layer input - * - * @returns index of bound layer (the same as layerId or newly created) - */ - int registerOutput(const std::string& outputName, int layerId, int outputPort); - - /** @brief Sets outputs names of the network input pseudo layer. - * - * Each net always has special own the network input pseudo layer with id=0. - * This layer stores the user blobs only and don't make any computations. - * In fact, this layer provides the only way to pass user data into the network. - * As any other layer, this layer can label its outputs and this function provides an easy way to do this. - */ - CV_WRAP void setInputsNames(const std::vector &inputBlobNames); - - /** @brief Specify shape of network input. - */ - CV_WRAP void setInputShape(const String &inputName, const MatShape& shape); - - /** @brief Runs forward pass to compute output of layer with name @p outputName. - * @param outputName name for layer which output is needed to get - * @return blob for first output of specified layer. - * @details By default runs forward pass for the whole network. - */ - CV_WRAP Mat forward(const String& outputName = String()); - - /** @brief Runs forward pass to compute output of layer with name @p outputName. - * @param outputName name for layer which output is needed to get - * @details By default runs forward pass for the whole network. - * - * This is an asynchronous version of forward(const String&). - * dnn::DNN_BACKEND_INFERENCE_ENGINE backend is required. - */ - CV_WRAP AsyncArray forwardAsync(const String& outputName = String()); - - /** @brief Runs forward pass to compute output of layer with name @p outputName. - * @param outputBlobs contains all output blobs for specified layer. - * @param outputName name for layer which output is needed to get - * @details If @p outputName is empty, runs forward pass for the whole network. - */ - CV_WRAP void forward(CV_ND OutputArrayOfArrays outputBlobs, const String& outputName = String()); - - /** @brief Runs forward pass to compute outputs of layers listed in @p outBlobNames. - * @param outputBlobs contains blobs for first outputs of specified layers. - * @param outBlobNames names for layers which outputs are needed to get - */ - CV_WRAP void forward(CV_ND OutputArrayOfArrays outputBlobs, - const std::vector& outBlobNames); - - /** @brief Runs forward pass to compute outputs of layers listed in @p outBlobNames. - * @param outputBlobs contains all output blobs for each layer specified in @p outBlobNames. - * @param outBlobNames names for layers which outputs are needed to get - */ - CV_WRAP_AS(forwardAndRetrieve) void forward(CV_OUT std::vector >& outputBlobs, - const std::vector& outBlobNames); - - /** @brief Returns a quantized Net from a floating-point Net. - * @param calibData Calibration data to compute the quantization parameters. - * @param inputsDtype Datatype of quantized net's inputs. Can be CV_32F or CV_8S. - * @param outputsDtype Datatype of quantized net's outputs. Can be CV_32F or CV_8S. - * @param perChannel Quantization granularity of quantized Net. The default is true, that means quantize model - * in per-channel way (channel-wise). Set it false to quantize model in per-tensor way (or tensor-wise). - */ - CV_WRAP Net quantize(InputArrayOfArrays calibData, int inputsDtype, int outputsDtype, bool perChannel=true); - - /** @brief Returns input scale and zeropoint for a quantized Net. - * @param scales output parameter for returning input scales. - * @param zeropoints output parameter for returning input zeropoints. - */ - CV_WRAP void getInputDetails(CV_OUT std::vector& scales, CV_OUT std::vector& zeropoints) const; - - /** @brief Returns output scale and zeropoint for a quantized Net. - * @param scales output parameter for returning output scales. - * @param zeropoints output parameter for returning output zeropoints. - */ - CV_WRAP void getOutputDetails(CV_OUT std::vector& scales, CV_OUT std::vector& zeropoints) const; - - /** - * @brief Compile Halide layers. - * @param[in] scheduler Path to YAML file with scheduling directives. - * @see setPreferableBackend - * - * Schedule layers that support Halide backend. Then compile them for - * specific target. For layers that not represented in scheduling file - * or if no manual scheduling used at all, automatic scheduling will be applied. - */ - CV_WRAP void setHalideScheduler(const String& scheduler); - - /** - * @brief Ask network to use specific computation backend where it supported. - * @param[in] backendId backend identifier. - * @see Backend - */ - CV_WRAP void setPreferableBackend(int backendId); - - /** - * @brief Ask network to make computations on specific target device. - * @param[in] targetId target identifier. - * @see Target - * - * List of supported combinations backend / target: - * | | DNN_BACKEND_OPENCV | DNN_BACKEND_INFERENCE_ENGINE | DNN_BACKEND_HALIDE | DNN_BACKEND_CUDA | - * |------------------------|--------------------|------------------------------|--------------------|-------------------| - * | DNN_TARGET_CPU | + | + | + | | - * | DNN_TARGET_OPENCL | + | + | + | | - * | DNN_TARGET_OPENCL_FP16 | + | + | | | - * | DNN_TARGET_MYRIAD | | + | | | - * | DNN_TARGET_FPGA | | + | | | - * | DNN_TARGET_CUDA | | | | + | - * | DNN_TARGET_CUDA_FP16 | | | | + | - * | DNN_TARGET_HDDL | | + | | | - */ - CV_WRAP void setPreferableTarget(int targetId); - - /** @brief Sets the new input value for the network - * @param blob A new blob. Should have CV_32F or CV_8U depth. - * @param name A name of input layer. - * @param scalefactor An optional normalization scale. - * @param mean An optional mean subtraction values. - * @see connect(String, String) to know format of the descriptor. - * - * If scale or mean values are specified, a final input blob is computed - * as: - * \f[input(n,c,h,w) = scalefactor \times (blob(n,c,h,w) - mean_c)\f] - */ - CV_WRAP void setInput(CV_ND InputArray blob, const String& name = "", - double scalefactor = 1.0, const Scalar& mean = Scalar()); - - /** @brief Sets the new value for the learned param of the layer. - * @param layer name or id of the layer. - * @param numParam index of the layer parameter in the Layer::blobs array. - * @param blob the new value. - * @see Layer::blobs - * @note If shape of the new blob differs from the previous shape, - * then the following forward pass may fail. - */ - CV_WRAP void setParam(int layer, int numParam, CV_ND const Mat &blob); - CV_WRAP inline void setParam(const String& layerName, int numParam, CV_ND const Mat &blob) { return setParam(getLayerId(layerName), numParam, blob); } - - /** @brief Returns parameter blob of the layer. - * @param layer name or id of the layer. - * @param numParam index of the layer parameter in the Layer::blobs array. - * @see Layer::blobs - */ - CV_WRAP Mat getParam(int layer, int numParam = 0) const; - CV_WRAP inline Mat getParam(const String& layerName, int numParam = 0) const { return getParam(getLayerId(layerName), numParam); } - - /** @brief Returns indexes of layers with unconnected outputs. - * - * FIXIT: Rework API to registerOutput() approach, deprecate this call - */ - CV_WRAP std::vector getUnconnectedOutLayers() const; - - /** @brief Returns names of layers with unconnected outputs. - * - * FIXIT: Rework API to registerOutput() approach, deprecate this call - */ - CV_WRAP std::vector getUnconnectedOutLayersNames() const; - - /** @brief Returns input and output shapes for all layers in loaded model; - * preliminary inferencing isn't necessary. - * @param netInputShapes shapes for all input blobs in net input layer. - * @param layersIds output parameter for layer IDs. - * @param inLayersShapes output parameter for input layers shapes; - * order is the same as in layersIds - * @param outLayersShapes output parameter for output layers shapes; - * order is the same as in layersIds - */ - CV_WRAP void getLayersShapes(const std::vector& netInputShapes, - CV_OUT std::vector& layersIds, - CV_OUT std::vector >& inLayersShapes, - CV_OUT std::vector >& outLayersShapes) const; - - /** @overload */ - CV_WRAP void getLayersShapes(const MatShape& netInputShape, - CV_OUT std::vector& layersIds, - CV_OUT std::vector >& inLayersShapes, - CV_OUT std::vector >& outLayersShapes) const; - - /** @brief Returns input and output shapes for layer with specified - * id in loaded model; preliminary inferencing isn't necessary. - * @param netInputShape shape input blob in net input layer. - * @param layerId id for layer. - * @param inLayerShapes output parameter for input layers shapes; - * order is the same as in layersIds - * @param outLayerShapes output parameter for output layers shapes; - * order is the same as in layersIds - */ - void getLayerShapes(const MatShape& netInputShape, - const int layerId, - CV_OUT std::vector& inLayerShapes, - CV_OUT std::vector& outLayerShapes) const; // FIXIT: CV_WRAP - - /** @overload */ - void getLayerShapes(const std::vector& netInputShapes, - const int layerId, - CV_OUT std::vector& inLayerShapes, - CV_OUT std::vector& outLayerShapes) const; // FIXIT: CV_WRAP - - /** @brief Computes FLOP for whole loaded model with specified input shapes. - * @param netInputShapes vector of shapes for all net inputs. - * @returns computed FLOP. - */ - CV_WRAP int64 getFLOPS(const std::vector& netInputShapes) const; - /** @overload */ - CV_WRAP int64 getFLOPS(const MatShape& netInputShape) const; - /** @overload */ - CV_WRAP int64 getFLOPS(const int layerId, - const std::vector& netInputShapes) const; - /** @overload */ - CV_WRAP int64 getFLOPS(const int layerId, - const MatShape& netInputShape) const; - - /** @brief Returns list of types for layer used in model. - * @param layersTypes output parameter for returning types. - */ - CV_WRAP void getLayerTypes(CV_OUT std::vector& layersTypes) const; - - /** @brief Returns count of layers of specified type. - * @param layerType type. - * @returns count of layers - */ - CV_WRAP int getLayersCount(const String& layerType) const; - - /** @brief Computes bytes number which are required to store - * all weights and intermediate blobs for model. - * @param netInputShapes vector of shapes for all net inputs. - * @param weights output parameter to store resulting bytes for weights. - * @param blobs output parameter to store resulting bytes for intermediate blobs. - */ - void getMemoryConsumption(const std::vector& netInputShapes, - CV_OUT size_t& weights, CV_OUT size_t& blobs) const; // FIXIT: CV_WRAP - /** @overload */ - CV_WRAP void getMemoryConsumption(const MatShape& netInputShape, - CV_OUT size_t& weights, CV_OUT size_t& blobs) const; - /** @overload */ - CV_WRAP void getMemoryConsumption(const int layerId, - const std::vector& netInputShapes, - CV_OUT size_t& weights, CV_OUT size_t& blobs) const; - /** @overload */ - CV_WRAP void getMemoryConsumption(const int layerId, - const MatShape& netInputShape, - CV_OUT size_t& weights, CV_OUT size_t& blobs) const; - - /** @brief Computes bytes number which are required to store - * all weights and intermediate blobs for each layer. - * @param netInputShapes vector of shapes for all net inputs. - * @param layerIds output vector to save layer IDs. - * @param weights output parameter to store resulting bytes for weights. - * @param blobs output parameter to store resulting bytes for intermediate blobs. - */ - void getMemoryConsumption(const std::vector& netInputShapes, - CV_OUT std::vector& layerIds, - CV_OUT std::vector& weights, - CV_OUT std::vector& blobs) const; // FIXIT: CV_WRAP - /** @overload */ - void getMemoryConsumption(const MatShape& netInputShape, - CV_OUT std::vector& layerIds, - CV_OUT std::vector& weights, - CV_OUT std::vector& blobs) const; // FIXIT: CV_WRAP - - /** @brief Enables or disables layer fusion in the network. - * @param fusion true to enable the fusion, false to disable. The fusion is enabled by default. - */ - CV_WRAP void enableFusion(bool fusion); - - /** @brief Enables or disables the Winograd compute branch. The Winograd compute branch can speed up - * 3x3 Convolution at a small loss of accuracy. - * @param useWinograd true to enable the Winograd compute branch. The default is true. - */ - CV_WRAP void enableWinograd(bool useWinograd); - - /** @brief Returns overall time for inference and timings (in ticks) for layers. - * - * Indexes in returned vector correspond to layers ids. Some layers can be fused with others, - * in this case zero ticks count will be return for that skipped layers. Supported by DNN_BACKEND_OPENCV on DNN_TARGET_CPU only. - * - * @param[out] timings vector for tick timings for all layers. - * @return overall ticks for model inference. - */ - CV_WRAP int64 getPerfProfile(CV_OUT std::vector& timings); - - - struct Impl; - inline Impl* getImpl() const { return impl.get(); } - inline Impl& getImplRef() const { CV_DbgAssert(impl); return *impl.get(); } - friend class accessor::DnnNetAccessor; - protected: - Ptr impl; - }; - - /** @brief Reads a network model stored in Darknet model files. - * @param cfgFile path to the .cfg file with text description of the network architecture. - * @param darknetModel path to the .weights file with learned network. - * @returns Network object that ready to do forward, throw an exception in failure cases. - */ - CV_EXPORTS_W Net readNetFromDarknet(CV_WRAP_FILE_PATH const String &cfgFile, CV_WRAP_FILE_PATH const String &darknetModel = String()); - - /** @brief Reads a network model stored in Darknet model files. - * @param bufferCfg A buffer contains a content of .cfg file with text description of the network architecture. - * @param bufferModel A buffer contains a content of .weights file with learned network. - * @returns Net object. - */ - CV_EXPORTS_W Net readNetFromDarknet(const std::vector& bufferCfg, - const std::vector& bufferModel = std::vector()); - - /** @brief Reads a network model stored in Darknet model files. - * @param bufferCfg A buffer contains a content of .cfg file with text description of the network architecture. - * @param lenCfg Number of bytes to read from bufferCfg - * @param bufferModel A buffer contains a content of .weights file with learned network. - * @param lenModel Number of bytes to read from bufferModel - * @returns Net object. - */ - CV_EXPORTS Net readNetFromDarknet(const char *bufferCfg, size_t lenCfg, - const char *bufferModel = NULL, size_t lenModel = 0); - - /** @brief Reads a network model stored in Caffe framework's format. - * @param prototxt path to the .prototxt file with text description of the network architecture. - * @param caffeModel path to the .caffemodel file with learned network. - * @returns Net object. - */ - CV_EXPORTS_W Net readNetFromCaffe(CV_WRAP_FILE_PATH const String &prototxt, CV_WRAP_FILE_PATH const String &caffeModel = String()); - - /** @brief Reads a network model stored in Caffe model in memory. - * @param bufferProto buffer containing the content of the .prototxt file - * @param bufferModel buffer containing the content of the .caffemodel file - * @returns Net object. - */ - CV_EXPORTS_W Net readNetFromCaffe(const std::vector& bufferProto, - const std::vector& bufferModel = std::vector()); - - /** @brief Reads a network model stored in Caffe model in memory. - * @details This is an overloaded member function, provided for convenience. - * It differs from the above function only in what argument(s) it accepts. - * @param bufferProto buffer containing the content of the .prototxt file - * @param lenProto length of bufferProto - * @param bufferModel buffer containing the content of the .caffemodel file - * @param lenModel length of bufferModel - * @returns Net object. - */ - CV_EXPORTS Net readNetFromCaffe(const char *bufferProto, size_t lenProto, - const char *bufferModel = NULL, size_t lenModel = 0); - - /** @brief Reads a network model stored in TensorFlow framework's format. - * @param model path to the .pb file with binary protobuf description of the network architecture - * @param config path to the .pbtxt file that contains text graph definition in protobuf format. - * Resulting Net object is built by text graph using weights from a binary one that - * let us make it more flexible. - * @returns Net object. - */ - CV_EXPORTS_W Net readNetFromTensorflow(CV_WRAP_FILE_PATH const String &model, CV_WRAP_FILE_PATH const String &config = String()); - - /** @brief Reads a network model stored in TensorFlow framework's format. - * @param bufferModel buffer containing the content of the pb file - * @param bufferConfig buffer containing the content of the pbtxt file - * @returns Net object. - */ - CV_EXPORTS_W Net readNetFromTensorflow(const std::vector& bufferModel, - const std::vector& bufferConfig = std::vector()); - - /** @brief Reads a network model stored in TensorFlow framework's format. - * @details This is an overloaded member function, provided for convenience. - * It differs from the above function only in what argument(s) it accepts. - * @param bufferModel buffer containing the content of the pb file - * @param lenModel length of bufferModel - * @param bufferConfig buffer containing the content of the pbtxt file - * @param lenConfig length of bufferConfig - */ - CV_EXPORTS Net readNetFromTensorflow(const char *bufferModel, size_t lenModel, - const char *bufferConfig = NULL, size_t lenConfig = 0); - - /** @brief Reads a network model stored in TFLite framework's format. - * @param model path to the .tflite file with binary flatbuffers description of the network architecture - * @returns Net object. - */ - CV_EXPORTS_W Net readNetFromTFLite(CV_WRAP_FILE_PATH const String &model); - - /** @brief Reads a network model stored in TFLite framework's format. - * @param bufferModel buffer containing the content of the tflite file - * @returns Net object. - */ - CV_EXPORTS_W Net readNetFromTFLite(const std::vector& bufferModel); - - /** @brief Reads a network model stored in TFLite framework's format. - * @details This is an overloaded member function, provided for convenience. - * It differs from the above function only in what argument(s) it accepts. - * @param bufferModel buffer containing the content of the tflite file - * @param lenModel length of bufferModel - */ - CV_EXPORTS Net readNetFromTFLite(const char *bufferModel, size_t lenModel); - - /** - * @brief Reads a network model stored in Torch7 framework's format. - * @param model path to the file, dumped from Torch by using torch.save() function. - * @param isBinary specifies whether the network was serialized in ascii mode or binary. - * @param evaluate specifies testing phase of network. If true, it's similar to evaluate() method in Torch. - * @returns Net object. - * - * @note Ascii mode of Torch serializer is more preferable, because binary mode extensively use `long` type of C language, - * which has various bit-length on different systems. - * - * The loading file must contain serialized nn.Module object - * with importing network. Try to eliminate a custom objects from serialazing data to avoid importing errors. - * - * List of supported layers (i.e. object instances derived from Torch nn.Module class): - * - nn.Sequential - * - nn.Parallel - * - nn.Concat - * - nn.Linear - * - nn.SpatialConvolution - * - nn.SpatialMaxPooling, nn.SpatialAveragePooling - * - nn.ReLU, nn.TanH, nn.Sigmoid - * - nn.Reshape - * - nn.SoftMax, nn.LogSoftMax - * - * Also some equivalents of these classes from cunn, cudnn, and fbcunn may be successfully imported. - */ - CV_EXPORTS_W Net readNetFromTorch(CV_WRAP_FILE_PATH const String &model, bool isBinary = true, bool evaluate = true); - - /** - * @brief Read deep learning network represented in one of the supported formats. - * @param[in] model Binary file contains trained weights. The following file - * extensions are expected for models from different frameworks: - * * `*.caffemodel` (Caffe, http://caffe.berkeleyvision.org/) - * * `*.pb` (TensorFlow, https://www.tensorflow.org/) - * * `*.t7` | `*.net` (Torch, http://torch.ch/) - * * `*.weights` (Darknet, https://pjreddie.com/darknet/) - * * `*.bin` | `*.onnx` (OpenVINO, https://software.intel.com/openvino-toolkit) - * * `*.onnx` (ONNX, https://onnx.ai/) - * @param[in] config Text file contains network configuration. It could be a - * file with the following extensions: - * * `*.prototxt` (Caffe, http://caffe.berkeleyvision.org/) - * * `*.pbtxt` (TensorFlow, https://www.tensorflow.org/) - * * `*.cfg` (Darknet, https://pjreddie.com/darknet/) - * * `*.xml` (OpenVINO, https://software.intel.com/openvino-toolkit) - * @param[in] framework Explicit framework name tag to determine a format. - * @returns Net object. - * - * This function automatically detects an origin framework of trained model - * and calls an appropriate function such @ref readNetFromCaffe, @ref readNetFromTensorflow, - * @ref readNetFromTorch or @ref readNetFromDarknet. An order of @p model and @p config - * arguments does not matter. - */ - CV_EXPORTS_W Net readNet(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config = "", const String& framework = ""); - - /** - * @brief Read deep learning network represented in one of the supported formats. - * @details This is an overloaded member function, provided for convenience. - * It differs from the above function only in what argument(s) it accepts. - * @param[in] framework Name of origin framework. - * @param[in] bufferModel A buffer with a content of binary file with weights - * @param[in] bufferConfig A buffer with a content of text file contains network configuration. - * @returns Net object. - */ - CV_EXPORTS_W Net readNet(const String& framework, const std::vector& bufferModel, - const std::vector& bufferConfig = std::vector()); - - /** @brief Loads blob which was serialized as torch.Tensor object of Torch7 framework. - * @warning This function has the same limitations as readNetFromTorch(). - */ - CV_EXPORTS_W Mat readTorchBlob(const String &filename, bool isBinary = true); - - /** @brief Load a network from Intel's Model Optimizer intermediate representation. - * @param[in] xml XML configuration file with network's topology. - * @param[in] bin Binary file with trained weights. - * @returns Net object. - * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine - * backend. - */ - CV_EXPORTS_W - Net readNetFromModelOptimizer(CV_WRAP_FILE_PATH const String &xml, CV_WRAP_FILE_PATH const String &bin = ""); - - /** @brief Load a network from Intel's Model Optimizer intermediate representation. - * @param[in] bufferModelConfig Buffer contains XML configuration with network's topology. - * @param[in] bufferWeights Buffer contains binary data with trained weights. - * @returns Net object. - * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine - * backend. - */ - CV_EXPORTS_W - Net readNetFromModelOptimizer(const std::vector& bufferModelConfig, const std::vector& bufferWeights); - - /** @brief Load a network from Intel's Model Optimizer intermediate representation. - * @param[in] bufferModelConfigPtr Pointer to buffer which contains XML configuration with network's topology. - * @param[in] bufferModelConfigSize Binary size of XML configuration data. - * @param[in] bufferWeightsPtr Pointer to buffer which contains binary data with trained weights. - * @param[in] bufferWeightsSize Binary size of trained weights data. - * @returns Net object. - * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine - * backend. - */ - CV_EXPORTS - Net readNetFromModelOptimizer(const uchar* bufferModelConfigPtr, size_t bufferModelConfigSize, - const uchar* bufferWeightsPtr, size_t bufferWeightsSize); - - /** @brief Reads a network model ONNX. - * @param onnxFile path to the .onnx file with text description of the network architecture. - * @returns Network object that ready to do forward, throw an exception in failure cases. - */ - CV_EXPORTS_W Net readNetFromONNX(CV_WRAP_FILE_PATH const String &onnxFile); - - /** @brief Reads a network model from ONNX - * in-memory buffer. - * @param buffer memory address of the first byte of the buffer. - * @param sizeBuffer size of the buffer. - * @returns Network object that ready to do forward, throw an exception - * in failure cases. - */ - CV_EXPORTS Net readNetFromONNX(const char* buffer, size_t sizeBuffer); - - /** @brief Reads a network model from ONNX - * in-memory buffer. - * @param buffer in-memory buffer that stores the ONNX model bytes. - * @returns Network object that ready to do forward, throw an exception - * in failure cases. - */ - CV_EXPORTS_W Net readNetFromONNX(const std::vector& buffer); - - /** @brief Creates blob from .pb file. - * @param path to the .pb file with input tensor. - * @returns Mat. - */ - CV_EXPORTS_W Mat readTensorFromONNX(CV_WRAP_FILE_PATH const String& path); - - /** @brief Creates 4-dimensional blob from image. Optionally resizes and crops @p image from center, - * subtract @p mean values, scales values by @p scalefactor, swap Blue and Red channels. - * @param image input image (with 1-, 3- or 4-channels). - * @param scalefactor multiplier for @p images values. - * @param size spatial size for output image - * @param mean scalar with mean values which are subtracted from channels. Values are intended - * to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true. - * @param swapRB flag which indicates that swap first and last channels - * in 3-channel image is necessary. - * @param crop flag which indicates whether image will be cropped after resize or not - * @param ddepth Depth of output blob. Choose CV_32F or CV_8U. - * @details if @p crop is true, input image is resized so one side after resize is equal to corresponding - * dimension in @p size and another one is equal or larger. Then, crop from the center is performed. - * If @p crop is false, direct resize without cropping and preserving aspect ratio is performed. - * @returns 4-dimensional Mat with NCHW dimensions order. - * - * @note - * The order and usage of `scalefactor` and `mean` are (input - mean) * scalefactor. - */ - CV_EXPORTS_W Mat blobFromImage(InputArray image, double scalefactor=1.0, const Size& size = Size(), - const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false, - int ddepth=CV_32F); - - /** @brief Creates 4-dimensional blob from image. - * @details This is an overloaded member function, provided for convenience. - * It differs from the above function only in what argument(s) it accepts. - */ - CV_EXPORTS void blobFromImage(InputArray image, OutputArray blob, double scalefactor=1.0, - const Size& size = Size(), const Scalar& mean = Scalar(), - bool swapRB=false, bool crop=false, int ddepth=CV_32F); - - - /** @brief Creates 4-dimensional blob from series of images. Optionally resizes and - * crops @p images from center, subtract @p mean values, scales values by @p scalefactor, - * swap Blue and Red channels. - * @param images input images (all with 1-, 3- or 4-channels). - * @param size spatial size for output image - * @param mean scalar with mean values which are subtracted from channels. Values are intended - * to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true. - * @param scalefactor multiplier for @p images values. - * @param swapRB flag which indicates that swap first and last channels - * in 3-channel image is necessary. - * @param crop flag which indicates whether image will be cropped after resize or not - * @param ddepth Depth of output blob. Choose CV_32F or CV_8U. - * @details if @p crop is true, input image is resized so one side after resize is equal to corresponding - * dimension in @p size and another one is equal or larger. Then, crop from the center is performed. - * If @p crop is false, direct resize without cropping and preserving aspect ratio is performed. - * @returns 4-dimensional Mat with NCHW dimensions order. - * - * @note - * The order and usage of `scalefactor` and `mean` are (input - mean) * scalefactor. - */ - CV_EXPORTS_W Mat blobFromImages(InputArrayOfArrays images, double scalefactor=1.0, - Size size = Size(), const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false, - int ddepth=CV_32F); - - /** @brief Creates 4-dimensional blob from series of images. - * @details This is an overloaded member function, provided for convenience. - * It differs from the above function only in what argument(s) it accepts. - */ - CV_EXPORTS void blobFromImages(InputArrayOfArrays images, OutputArray blob, - double scalefactor=1.0, Size size = Size(), - const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false, - int ddepth=CV_32F); - - /** - * @brief Enum of image processing mode. - * To facilitate the specialization pre-processing requirements of the dnn model. - * For example, the `letter box` often used in the Yolo series of models. - * @see Image2BlobParams - */ - enum ImagePaddingMode - { - DNN_PMODE_NULL = 0, // !< Default. Resize to required input size without extra processing. - DNN_PMODE_CROP_CENTER = 1, // !< Image will be cropped after resize. - DNN_PMODE_LETTERBOX = 2, // !< Resize image to the desired size while preserving the aspect ratio of original image. - }; - - /** @brief Processing params of image to blob. - * - * It includes all possible image processing operations and corresponding parameters. - * - * @see blobFromImageWithParams - * - * @note - * The order and usage of `scalefactor` and `mean` are (input - mean) * scalefactor. - * The order and usage of `scalefactor`, `size`, `mean`, `swapRB`, and `ddepth` are consistent - * with the function of @ref blobFromImage. - */ - struct CV_EXPORTS_W_SIMPLE Image2BlobParams - { - CV_WRAP Image2BlobParams(); - CV_WRAP Image2BlobParams(const Scalar& scalefactor, const Size& size = Size(), const Scalar& mean = Scalar(), - bool swapRB = false, int ddepth = CV_32F, DataLayout datalayout = DNN_LAYOUT_NCHW, - ImagePaddingMode mode = DNN_PMODE_NULL, Scalar borderValue = 0.0); - - CV_PROP_RW Scalar scalefactor; //!< scalefactor multiplier for input image values. - CV_PROP_RW Size size; //!< Spatial size for output image. - CV_PROP_RW Scalar mean; //!< Scalar with mean values which are subtracted from channels. - CV_PROP_RW bool swapRB; //!< Flag which indicates that swap first and last channels - CV_PROP_RW int ddepth; //!< Depth of output blob. Choose CV_32F or CV_8U. - CV_PROP_RW DataLayout datalayout; //!< Order of output dimensions. Choose DNN_LAYOUT_NCHW or DNN_LAYOUT_NHWC. - CV_PROP_RW ImagePaddingMode paddingmode; //!< Image padding mode. @see ImagePaddingMode. - CV_PROP_RW Scalar borderValue; //!< Value used in padding mode for padding. - - /** @brief Get rectangle coordinates in original image system from rectangle in blob coordinates. - * @param rBlob rect in blob coordinates. - * @param size original input image size. - * @returns rectangle in original image coordinates. - */ - CV_WRAP Rect blobRectToImageRect(const Rect &rBlob, const Size &size); - - /** @brief Get rectangle coordinates in original image system from rectangle in blob coordinates. - * @param rBlob rect in blob coordinates. - * @param rImg result rect in image coordinates. - * @param size original input image size. - */ - CV_WRAP void blobRectsToImageRects(const std::vector &rBlob, CV_OUT std::vector& rImg, const Size& size); - }; - - /** @brief Creates 4-dimensional blob from image with given params. - * - * @details This function is an extension of @ref blobFromImage to meet more image preprocess needs. - * Given input image and preprocessing parameters, and function outputs the blob. - * - * @param image input image (all with 1-, 3- or 4-channels). - * @param param struct of Image2BlobParams, contains all parameters needed by processing of image to blob. - * @return 4-dimensional Mat. - */ - CV_EXPORTS_W Mat blobFromImageWithParams(InputArray image, const Image2BlobParams& param = Image2BlobParams()); - - /** @overload */ - CV_EXPORTS_W void blobFromImageWithParams(InputArray image, OutputArray blob, const Image2BlobParams& param = Image2BlobParams()); - - /** @brief Creates 4-dimensional blob from series of images with given params. - * - * @details This function is an extension of @ref blobFromImages to meet more image preprocess needs. - * Given input image and preprocessing parameters, and function outputs the blob. - * - * @param images input image (all with 1-, 3- or 4-channels). - * @param param struct of Image2BlobParams, contains all parameters needed by processing of image to blob. - * @returns 4-dimensional Mat. - */ - CV_EXPORTS_W Mat blobFromImagesWithParams(InputArrayOfArrays images, const Image2BlobParams& param = Image2BlobParams()); - - /** @overload */ - CV_EXPORTS_W void blobFromImagesWithParams(InputArrayOfArrays images, OutputArray blob, const Image2BlobParams& param = Image2BlobParams()); - - /** @brief Parse a 4D blob and output the images it contains as 2D arrays through a simpler data structure - * (std::vector). - * @param[in] blob_ 4 dimensional array (images, channels, height, width) in floating point precision (CV_32F) from - * which you would like to extract the images. - * @param[out] images_ array of 2D Mat containing the images extracted from the blob in floating point precision - * (CV_32F). They are non normalized neither mean added. The number of returned images equals the first dimension - * of the blob (batch size). Every image has a number of channels equals to the second dimension of the blob (depth). - */ - CV_EXPORTS_W void imagesFromBlob(const cv::Mat& blob_, OutputArrayOfArrays images_); - - /** @brief Convert all weights of Caffe network to half precision floating point. - * @param src Path to origin model from Caffe framework contains single - * precision floating point weights (usually has `.caffemodel` extension). - * @param dst Path to destination model with updated weights. - * @param layersTypes Set of layers types which parameters will be converted. - * By default, converts only Convolutional and Fully-Connected layers' - * weights. - * - * @note Shrinked model has no origin float32 weights so it can't be used - * in origin Caffe framework anymore. However the structure of data - * is taken from NVidia's Caffe fork: https://github.com/NVIDIA/caffe. - * So the resulting model may be used there. - */ - CV_EXPORTS_W void shrinkCaffeModel(CV_WRAP_FILE_PATH const String& src, CV_WRAP_FILE_PATH const String& dst, - const std::vector& layersTypes = std::vector()); - - /** @brief Create a text representation for a binary network stored in protocol buffer format. - * @param[in] model A path to binary network. - * @param[in] output A path to output text file to be created. - * - * @note To reduce output file size, trained weights are not included. - */ - CV_EXPORTS_W void writeTextGraph(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& output); - - /** @brief Performs non maximum suppression given boxes and corresponding scores. - - * @param bboxes a set of bounding boxes to apply NMS. - * @param scores a set of corresponding confidences. - * @param score_threshold a threshold used to filter boxes by score. - * @param nms_threshold a threshold used in non maximum suppression. - * @param indices the kept indices of bboxes after NMS. - * @param eta a coefficient in adaptive threshold formula: \f$nms\_threshold_{i+1}=eta\cdot nms\_threshold_i\f$. - * @param top_k if `>0`, keep at most @p top_k picked indices. - */ - CV_EXPORTS void NMSBoxes(const std::vector& bboxes, const std::vector& scores, - const float score_threshold, const float nms_threshold, - CV_OUT std::vector& indices, - const float eta = 1.f, const int top_k = 0); - - CV_EXPORTS_W void NMSBoxes(const std::vector& bboxes, const std::vector& scores, - const float score_threshold, const float nms_threshold, - CV_OUT std::vector& indices, - const float eta = 1.f, const int top_k = 0); - - CV_EXPORTS_AS(NMSBoxesRotated) void NMSBoxes(const std::vector& bboxes, const std::vector& scores, - const float score_threshold, const float nms_threshold, - CV_OUT std::vector& indices, - const float eta = 1.f, const int top_k = 0); - - /** @brief Performs batched non maximum suppression on given boxes and corresponding scores across different classes. - - * @param bboxes a set of bounding boxes to apply NMS. - * @param scores a set of corresponding confidences. - * @param class_ids a set of corresponding class ids. Ids are integer and usually start from 0. - * @param score_threshold a threshold used to filter boxes by score. - * @param nms_threshold a threshold used in non maximum suppression. - * @param indices the kept indices of bboxes after NMS. - * @param eta a coefficient in adaptive threshold formula: \f$nms\_threshold_{i+1}=eta\cdot nms\_threshold_i\f$. - * @param top_k if `>0`, keep at most @p top_k picked indices. - */ - CV_EXPORTS void NMSBoxesBatched(const std::vector& bboxes, const std::vector& scores, const std::vector& class_ids, - const float score_threshold, const float nms_threshold, - CV_OUT std::vector& indices, - const float eta = 1.f, const int top_k = 0); - - CV_EXPORTS_W void NMSBoxesBatched(const std::vector& bboxes, const std::vector& scores, const std::vector& class_ids, - const float score_threshold, const float nms_threshold, - CV_OUT std::vector& indices, - const float eta = 1.f, const int top_k = 0); - - /** - * @brief Enum of Soft NMS methods. - * @see softNMSBoxes - */ - enum class SoftNMSMethod - { - SOFTNMS_LINEAR = 1, - SOFTNMS_GAUSSIAN = 2 - }; - - /** @brief Performs soft non maximum suppression given boxes and corresponding scores. - * Reference: https://arxiv.org/abs/1704.04503 - * @param bboxes a set of bounding boxes to apply Soft NMS. - * @param scores a set of corresponding confidences. - * @param updated_scores a set of corresponding updated confidences. - * @param score_threshold a threshold used to filter boxes by score. - * @param nms_threshold a threshold used in non maximum suppression. - * @param indices the kept indices of bboxes after NMS. - * @param top_k keep at most @p top_k picked indices. - * @param sigma parameter of Gaussian weighting. - * @param method Gaussian or linear. - * @see SoftNMSMethod - */ - CV_EXPORTS_W void softNMSBoxes(const std::vector& bboxes, - const std::vector& scores, - CV_OUT std::vector& updated_scores, - const float score_threshold, - const float nms_threshold, - CV_OUT std::vector& indices, - size_t top_k = 0, - const float sigma = 0.5, - SoftNMSMethod method = SoftNMSMethod::SOFTNMS_GAUSSIAN); - - - /** @brief This class is presented high-level API for neural networks. - * - * Model allows to set params for preprocessing input image. - * Model creates net from file with trained weights and config, - * sets preprocessing input and runs forward pass. - */ - class CV_EXPORTS_W_SIMPLE Model - { - public: - CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) - Model(); - - Model(const Model&) = default; - Model(Model&&) = default; - Model& operator=(const Model&) = default; - Model& operator=(Model&&) = default; - - /** - * @brief Create model from deep learning network represented in one of the supported formats. - * An order of @p model and @p config arguments does not matter. - * @param[in] model Binary file contains trained weights. - * @param[in] config Text file contains network configuration. - */ - CV_WRAP Model(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config = ""); - - /** - * @brief Create model from deep learning network. - * @param[in] network Net object. - */ - CV_WRAP Model(const Net& network); - - /** @brief Set input size for frame. - * @param[in] size New input size. - * @note If shape of the new blob less than 0, then frame size not change. - */ - CV_WRAP Model& setInputSize(const Size& size); - - /** @overload - * @param[in] width New input width. - * @param[in] height New input height. - */ - CV_WRAP inline - Model& setInputSize(int width, int height) { return setInputSize(Size(width, height)); } - - /** @brief Set mean value for frame. - * @param[in] mean Scalar with mean values which are subtracted from channels. - */ - CV_WRAP Model& setInputMean(const Scalar& mean); - - /** @brief Set scalefactor value for frame. - * @param[in] scale Multiplier for frame values. - */ - CV_WRAP Model& setInputScale(const Scalar& scale); - - /** @brief Set flag crop for frame. - * @param[in] crop Flag which indicates whether image will be cropped after resize or not. - */ - CV_WRAP Model& setInputCrop(bool crop); - - /** @brief Set flag swapRB for frame. - * @param[in] swapRB Flag which indicates that swap first and last channels. - */ - CV_WRAP Model& setInputSwapRB(bool swapRB); - - /** @brief Set output names for frame. - * @param[in] outNames Names for output layers. - */ - CV_WRAP Model& setOutputNames(const std::vector& outNames); - - /** @brief Set preprocessing parameters for frame. - * @param[in] size New input size. - * @param[in] mean Scalar with mean values which are subtracted from channels. - * @param[in] scale Multiplier for frame values. - * @param[in] swapRB Flag which indicates that swap first and last channels. - * @param[in] crop Flag which indicates whether image will be cropped after resize or not. - * blob(n, c, y, x) = scale * resize( frame(y, x, c) ) - mean(c) ) - */ - CV_WRAP void setInputParams(double scale = 1.0, const Size& size = Size(), - const Scalar& mean = Scalar(), bool swapRB = false, bool crop = false); - - /** @brief Given the @p input frame, create input blob, run net and return the output @p blobs. - * @param[in] frame The input image. - * @param[out] outs Allocated output blobs, which will store results of the computation. - */ - CV_WRAP void predict(InputArray frame, OutputArrayOfArrays outs) const; - - - // ============================== Net proxy methods ============================== - // Never expose methods with network implementation details, like: - // - addLayer, addLayerToPrev, connect, setInputsNames, setInputShape, setParam, getParam - // - getLayer*, getUnconnectedOutLayers, getUnconnectedOutLayersNames, getLayersShapes - // - forward* methods, setInput - - /// @sa Net::setPreferableBackend - CV_WRAP Model& setPreferableBackend(dnn::Backend backendId); - /// @sa Net::setPreferableTarget - CV_WRAP Model& setPreferableTarget(dnn::Target targetId); - - /// @sa Net::enableWinograd - CV_WRAP Model& enableWinograd(bool useWinograd); - - CV_DEPRECATED_EXTERNAL - operator Net&() const { return getNetwork_(); } - - //protected: - internal/tests usage only - Net& getNetwork_() const; - inline Net& getNetwork_() { return const_cast(this)->getNetwork_(); } - - struct Impl; - inline Impl* getImpl() const { return impl.get(); } - inline Impl& getImplRef() const { CV_DbgAssert(impl); return *impl.get(); } - protected: - Ptr impl; - }; - - /** @brief This class represents high-level API for classification models. - * - * ClassificationModel allows to set params for preprocessing input image. - * ClassificationModel creates net from file with trained weights and config, - * sets preprocessing input, runs forward pass and return top-1 prediction. - */ - class CV_EXPORTS_W_SIMPLE ClassificationModel : public Model - { - public: - CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) - ClassificationModel(); - - /** - * @brief Create classification model from network represented in one of the supported formats. - * An order of @p model and @p config arguments does not matter. - * @param[in] model Binary file contains trained weights. - * @param[in] config Text file contains network configuration. - */ - CV_WRAP ClassificationModel(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config = ""); - - /** - * @brief Create model from deep learning network. - * @param[in] network Net object. - */ - CV_WRAP ClassificationModel(const Net& network); - - /** - * @brief Set enable/disable softmax post processing option. - * - * If this option is true, softmax is applied after forward inference within the classify() function - * to convert the confidences range to [0.0-1.0]. - * This function allows you to toggle this behavior. - * Please turn true when not contain softmax layer in model. - * @param[in] enable Set enable softmax post processing within the classify() function. - */ - CV_WRAP ClassificationModel& setEnableSoftmaxPostProcessing(bool enable); - - /** - * @brief Get enable/disable softmax post processing option. - * - * This option defaults to false, softmax post processing is not applied within the classify() function. - */ - CV_WRAP bool getEnableSoftmaxPostProcessing() const; - - /** @brief Given the @p input frame, create input blob, run net and return top-1 prediction. - * @param[in] frame The input image. - */ - std::pair classify(InputArray frame); - - /** @overload */ - CV_WRAP void classify(InputArray frame, CV_OUT int& classId, CV_OUT float& conf); - }; - - /** @brief This class represents high-level API for keypoints models - * - * KeypointsModel allows to set params for preprocessing input image. - * KeypointsModel creates net from file with trained weights and config, - * sets preprocessing input, runs forward pass and returns the x and y coordinates of each detected keypoint - */ - class CV_EXPORTS_W_SIMPLE KeypointsModel: public Model - { - public: - /** - * @brief Create keypoints model from network represented in one of the supported formats. - * An order of @p model and @p config arguments does not matter. - * @param[in] model Binary file contains trained weights. - * @param[in] config Text file contains network configuration. - */ - CV_WRAP KeypointsModel(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config = ""); - - /** - * @brief Create model from deep learning network. - * @param[in] network Net object. - */ - CV_WRAP KeypointsModel(const Net& network); - - /** @brief Given the @p input frame, create input blob, run net - * @param[in] frame The input image. - * @param thresh minimum confidence threshold to select a keypoint - * @returns a vector holding the x and y coordinates of each detected keypoint - * - */ - CV_WRAP std::vector estimate(InputArray frame, float thresh=0.5); - }; - - /** @brief This class represents high-level API for segmentation models - * - * SegmentationModel allows to set params for preprocessing input image. - * SegmentationModel creates net from file with trained weights and config, - * sets preprocessing input, runs forward pass and returns the class prediction for each pixel. - */ - class CV_EXPORTS_W_SIMPLE SegmentationModel: public Model - { - public: - /** - * @brief Create segmentation model from network represented in one of the supported formats. - * An order of @p model and @p config arguments does not matter. - * @param[in] model Binary file contains trained weights. - * @param[in] config Text file contains network configuration. - */ - CV_WRAP SegmentationModel(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config = ""); - - /** - * @brief Create model from deep learning network. - * @param[in] network Net object. - */ - CV_WRAP SegmentationModel(const Net& network); - - /** @brief Given the @p input frame, create input blob, run net - * @param[in] frame The input image. - * @param[out] mask Allocated class prediction for each pixel - */ - CV_WRAP void segment(InputArray frame, OutputArray mask); - }; - - /** @brief This class represents high-level API for object detection networks. - * - * DetectionModel allows to set params for preprocessing input image. - * DetectionModel creates net from file with trained weights and config, - * sets preprocessing input, runs forward pass and return result detections. - * For DetectionModel SSD, Faster R-CNN, YOLO topologies are supported. - */ - class CV_EXPORTS_W_SIMPLE DetectionModel : public Model - { - public: - /** - * @brief Create detection model from network represented in one of the supported formats. - * An order of @p model and @p config arguments does not matter. - * @param[in] model Binary file contains trained weights. - * @param[in] config Text file contains network configuration. - */ - CV_WRAP DetectionModel(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config = ""); - - /** - * @brief Create model from deep learning network. - * @param[in] network Net object. - */ - CV_WRAP DetectionModel(const Net& network); - - CV_DEPRECATED_EXTERNAL // avoid using in C++ code (need to fix bindings first) - DetectionModel(); - - /** - * @brief nmsAcrossClasses defaults to false, - * such that when non max suppression is used during the detect() function, it will do so per-class. - * This function allows you to toggle this behaviour. - * @param[in] value The new value for nmsAcrossClasses - */ - CV_WRAP DetectionModel& setNmsAcrossClasses(bool value); - - /** - * @brief Getter for nmsAcrossClasses. This variable defaults to false, - * such that when non max suppression is used during the detect() function, it will do so only per-class - */ - CV_WRAP bool getNmsAcrossClasses(); - - /** @brief Given the @p input frame, create input blob, run net and return result detections. - * @param[in] frame The input image. - * @param[out] classIds Class indexes in result detection. - * @param[out] confidences A set of corresponding confidences. - * @param[out] boxes A set of bounding boxes. - * @param[in] confThreshold A threshold used to filter boxes by confidences. - * @param[in] nmsThreshold A threshold used in non maximum suppression. - */ - CV_WRAP void detect(InputArray frame, CV_OUT std::vector& classIds, - CV_OUT std::vector& confidences, CV_OUT std::vector& boxes, - float confThreshold = 0.5f, float nmsThreshold = 0.0f); - }; - - -/** @brief This class represents high-level API for text recognition networks. - * - * TextRecognitionModel allows to set params for preprocessing input image. - * TextRecognitionModel creates net from file with trained weights and config, - * sets preprocessing input, runs forward pass and return recognition result. - * For TextRecognitionModel, CRNN-CTC is supported. - */ -class CV_EXPORTS_W_SIMPLE TextRecognitionModel : public Model -{ -public: - CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) - TextRecognitionModel(); - - /** - * @brief Create Text Recognition model from deep learning network - * Call setDecodeType() and setVocabulary() after constructor to initialize the decoding method - * @param[in] network Net object - */ - CV_WRAP TextRecognitionModel(const Net& network); - - /** - * @brief Create text recognition model from network represented in one of the supported formats - * Call setDecodeType() and setVocabulary() after constructor to initialize the decoding method - * @param[in] model Binary file contains trained weights - * @param[in] config Text file contains network configuration - */ - CV_WRAP inline - TextRecognitionModel(CV_WRAP_FILE_PATH const std::string& model, CV_WRAP_FILE_PATH const std::string& config = "") - : TextRecognitionModel(readNet(model, config)) { /* nothing */ } - - /** - * @brief Set the decoding method of translating the network output into string - * @param[in] decodeType The decoding method of translating the network output into string, currently supported type: - * - `"CTC-greedy"` greedy decoding for the output of CTC-based methods - * - `"CTC-prefix-beam-search"` Prefix beam search decoding for the output of CTC-based methods - */ - CV_WRAP - TextRecognitionModel& setDecodeType(const std::string& decodeType); - - /** - * @brief Get the decoding method - * @return the decoding method - */ - CV_WRAP - const std::string& getDecodeType() const; - - /** - * @brief Set the decoding method options for `"CTC-prefix-beam-search"` decode usage - * @param[in] beamSize Beam size for search - * @param[in] vocPruneSize Parameter to optimize big vocabulary search, - * only take top @p vocPruneSize tokens in each search step, @p vocPruneSize <= 0 stands for disable this prune. - */ - CV_WRAP - TextRecognitionModel& setDecodeOptsCTCPrefixBeamSearch(int beamSize, int vocPruneSize = 0); - - /** - * @brief Set the vocabulary for recognition. - * @param[in] vocabulary the associated vocabulary of the network. - */ - CV_WRAP - TextRecognitionModel& setVocabulary(const std::vector& vocabulary); - - /** - * @brief Get the vocabulary for recognition. - * @return vocabulary the associated vocabulary - */ - CV_WRAP - const std::vector& getVocabulary() const; - - /** - * @brief Given the @p input frame, create input blob, run net and return recognition result - * @param[in] frame The input image - * @return The text recognition result - */ - CV_WRAP - std::string recognize(InputArray frame) const; - - /** - * @brief Given the @p input frame, create input blob, run net and return recognition result - * @param[in] frame The input image - * @param[in] roiRects List of text detection regions of interest (cv::Rect, CV_32SC4). ROIs is be cropped as the network inputs - * @param[out] results A set of text recognition results. - */ - CV_WRAP - void recognize(InputArray frame, InputArrayOfArrays roiRects, CV_OUT std::vector& results) const; -}; - - -/** @brief Base class for text detection networks - */ -class CV_EXPORTS_W_SIMPLE TextDetectionModel : public Model -{ -protected: - CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) - TextDetectionModel(); - -public: - - /** @brief Performs detection - * - * Given the input @p frame, prepare network input, run network inference, post-process network output and return result detections. - * - * Each result is quadrangle's 4 points in this order: - * - bottom-left - * - top-left - * - top-right - * - bottom-right - * - * Use cv::getPerspectiveTransform function to retrieve image region without perspective transformations. - * - * @note If DL model doesn't support that kind of output then result may be derived from detectTextRectangles() output. - * - * @param[in] frame The input image - * @param[out] detections array with detections' quadrangles (4 points per result) - * @param[out] confidences array with detection confidences - */ - CV_WRAP - void detect( - InputArray frame, - CV_OUT std::vector< std::vector >& detections, - CV_OUT std::vector& confidences - ) const; - - /** @overload */ - CV_WRAP - void detect( - InputArray frame, - CV_OUT std::vector< std::vector >& detections - ) const; - - /** @brief Performs detection - * - * Given the input @p frame, prepare network input, run network inference, post-process network output and return result detections. - * - * Each result is rotated rectangle. - * - * @note Result may be inaccurate in case of strong perspective transformations. - * - * @param[in] frame the input image - * @param[out] detections array with detections' RotationRect results - * @param[out] confidences array with detection confidences - */ - CV_WRAP - void detectTextRectangles( - InputArray frame, - CV_OUT std::vector& detections, - CV_OUT std::vector& confidences - ) const; - - /** @overload */ - CV_WRAP - void detectTextRectangles( - InputArray frame, - CV_OUT std::vector& detections - ) const; -}; - -/** @brief This class represents high-level API for text detection DL networks compatible with EAST model. - * - * Configurable parameters: - * - (float) confThreshold - used to filter boxes by confidences, default: 0.5f - * - (float) nmsThreshold - used in non maximum suppression, default: 0.0f - */ -class CV_EXPORTS_W_SIMPLE TextDetectionModel_EAST : public TextDetectionModel -{ -public: - CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) - TextDetectionModel_EAST(); - - /** - * @brief Create text detection algorithm from deep learning network - * @param[in] network Net object - */ - CV_WRAP TextDetectionModel_EAST(const Net& network); - - /** - * @brief Create text detection model from network represented in one of the supported formats. - * An order of @p model and @p config arguments does not matter. - * @param[in] model Binary file contains trained weights. - * @param[in] config Text file contains network configuration. - */ - CV_WRAP inline - TextDetectionModel_EAST(CV_WRAP_FILE_PATH const std::string& model, CV_WRAP_FILE_PATH const std::string& config = "") - : TextDetectionModel_EAST(readNet(model, config)) { /* nothing */ } - - /** - * @brief Set the detection confidence threshold - * @param[in] confThreshold A threshold used to filter boxes by confidences - */ - CV_WRAP - TextDetectionModel_EAST& setConfidenceThreshold(float confThreshold); - - /** - * @brief Get the detection confidence threshold - */ - CV_WRAP - float getConfidenceThreshold() const; - - /** - * @brief Set the detection NMS filter threshold - * @param[in] nmsThreshold A threshold used in non maximum suppression - */ - CV_WRAP - TextDetectionModel_EAST& setNMSThreshold(float nmsThreshold); - - /** - * @brief Get the detection confidence threshold - */ - CV_WRAP - float getNMSThreshold() const; -}; - -/** @brief This class represents high-level API for text detection DL networks compatible with DB model. - * - * Related publications: @cite liao2020real - * Paper: https://arxiv.org/abs/1911.08947 - * For more information about the hyper-parameters setting, please refer to https://github.com/MhLiao/DB - * - * Configurable parameters: - * - (float) binaryThreshold - The threshold of the binary map. It is usually set to 0.3. - * - (float) polygonThreshold - The threshold of text polygons. It is usually set to 0.5, 0.6, and 0.7. Default is 0.5f - * - (double) unclipRatio - The unclip ratio of the detected text region, which determines the output size. It is usually set to 2.0. - * - (int) maxCandidates - The max number of the output results. - */ -class CV_EXPORTS_W_SIMPLE TextDetectionModel_DB : public TextDetectionModel -{ -public: - CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) - TextDetectionModel_DB(); - - /** - * @brief Create text detection algorithm from deep learning network. - * @param[in] network Net object. - */ - CV_WRAP TextDetectionModel_DB(const Net& network); - - /** - * @brief Create text detection model from network represented in one of the supported formats. - * An order of @p model and @p config arguments does not matter. - * @param[in] model Binary file contains trained weights. - * @param[in] config Text file contains network configuration. - */ - CV_WRAP inline - TextDetectionModel_DB(CV_WRAP_FILE_PATH const std::string& model, CV_WRAP_FILE_PATH const std::string& config = "") - : TextDetectionModel_DB(readNet(model, config)) { /* nothing */ } - - CV_WRAP TextDetectionModel_DB& setBinaryThreshold(float binaryThreshold); - CV_WRAP float getBinaryThreshold() const; - - CV_WRAP TextDetectionModel_DB& setPolygonThreshold(float polygonThreshold); - CV_WRAP float getPolygonThreshold() const; - - CV_WRAP TextDetectionModel_DB& setUnclipRatio(double unclipRatio); - CV_WRAP double getUnclipRatio() const; - - CV_WRAP TextDetectionModel_DB& setMaxCandidates(int maxCandidates); - CV_WRAP int getMaxCandidates() const; -}; - -//! @} -CV__DNN_INLINE_NS_END -} -} - -#include -#include - -/// @deprecated Include this header directly from application. Automatic inclusion will be removed -#include - -#endif /* OPENCV_DNN_DNN_HPP */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_DNN_DNN_HPP +#define OPENCV_DNN_DNN_HPP + +#include +#include +#include "opencv2/core/async.hpp" + +#include "../dnn/version.hpp" + +#include + +namespace cv { +namespace dnn { + +namespace accessor { +class DnnNetAccessor; // forward declaration +} + +CV__DNN_INLINE_NS_BEGIN +//! @addtogroup dnn +//! @{ + + typedef std::vector MatShape; + + /** + * @brief Enum of computation backends supported by layers. + * @see Net::setPreferableBackend + */ + enum Backend + { + //! DNN_BACKEND_DEFAULT equals to OPENCV_DNN_BACKEND_DEFAULT, which can be defined using CMake or a configuration parameter + DNN_BACKEND_DEFAULT = 0, + DNN_BACKEND_HALIDE, + DNN_BACKEND_INFERENCE_ENGINE, //!< Intel OpenVINO computational backend + //!< @note Tutorial how to build OpenCV with OpenVINO: @ref tutorial_dnn_openvino + DNN_BACKEND_OPENCV, + DNN_BACKEND_VKCOM, + DNN_BACKEND_CUDA, + DNN_BACKEND_WEBNN, + DNN_BACKEND_TIMVX, + DNN_BACKEND_CANN, +#if defined(__OPENCV_BUILD) || defined(BUILD_PLUGIN) +#if !defined(OPENCV_BINDING_PARSER) + DNN_BACKEND_INFERENCE_ENGINE_NGRAPH = 1000000, // internal - use DNN_BACKEND_INFERENCE_ENGINE + setInferenceEngineBackendType() + DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019, // internal - use DNN_BACKEND_INFERENCE_ENGINE + setInferenceEngineBackendType() +#endif +#endif + }; + + /** + * @brief Enum of target devices for computations. + * @see Net::setPreferableTarget + */ + enum Target + { + DNN_TARGET_CPU = 0, + DNN_TARGET_OPENCL, + DNN_TARGET_OPENCL_FP16, + DNN_TARGET_MYRIAD, + DNN_TARGET_VULKAN, + DNN_TARGET_FPGA, //!< FPGA device with CPU fallbacks using Inference Engine's Heterogeneous plugin. + DNN_TARGET_CUDA, + DNN_TARGET_CUDA_FP16, + DNN_TARGET_HDDL, + DNN_TARGET_NPU, + DNN_TARGET_CPU_FP16, // Only the ARM platform is supported. Low precision computing, accelerate model inference. + }; + + /** + * @brief Enum of data layout for model inference. + * @see Image2BlobParams + */ + enum DataLayout + { + DNN_LAYOUT_UNKNOWN = 0, + DNN_LAYOUT_ND = 1, //!< OpenCV data layout for 2D data. + DNN_LAYOUT_NCHW = 2, //!< OpenCV data layout for 4D data. + DNN_LAYOUT_NCDHW = 3, //!< OpenCV data layout for 5D data. + DNN_LAYOUT_NHWC = 4, //!< Tensorflow-like data layout for 4D data. + DNN_LAYOUT_NDHWC = 5, //!< Tensorflow-like data layout for 5D data. + DNN_LAYOUT_PLANAR = 6, //!< Tensorflow-like data layout, it should only be used at tf or tflite model parsing. + }; + + CV_EXPORTS std::vector< std::pair > getAvailableBackends(); + CV_EXPORTS_W std::vector getAvailableTargets(dnn::Backend be); + + /** + * @brief Enables detailed logging of the DNN model loading with CV DNN API. + * @param[in] isDiagnosticsMode Indicates whether diagnostic mode should be set. + * + * Diagnostic mode provides detailed logging of the model loading stage to explore + * potential problems (ex.: not implemented layer type). + * + * @note In diagnostic mode series of assertions will be skipped, it can lead to the + * expected application crash. + */ + CV_EXPORTS void enableModelDiagnostics(bool isDiagnosticsMode); + + /** @brief This class provides all data needed to initialize layer. + * + * It includes dictionary with scalar params (which can be read by using Dict interface), + * blob params #blobs and optional meta information: #name and #type of layer instance. + */ + class CV_EXPORTS LayerParams : public Dict + { + public: + //TODO: Add ability to name blob params + std::vector blobs; //!< List of learned parameters stored as blobs. + + String name; //!< Name of the layer instance (optional, can be used internal purposes). + String type; //!< Type name which was used for creating layer by layer factory (optional). + }; + + /** + * @brief Derivatives of this class encapsulates functions of certain backends. + */ + class BackendNode + { + public: + explicit BackendNode(int backendId); + + virtual ~BackendNode(); //!< Virtual destructor to make polymorphism. + + int backendId; //!< Backend identifier. + }; + + /** + * @brief Derivatives of this class wraps cv::Mat for different backends and targets. + */ + class BackendWrapper + { + public: + BackendWrapper(int backendId, int targetId); + + /** + * @brief Wrap cv::Mat for specific backend and target. + * @param[in] targetId Target identifier. + * @param[in] m cv::Mat for wrapping. + * + * Make CPU->GPU data transfer if it's require for the target. + */ + BackendWrapper(int targetId, const cv::Mat& m); + + /** + * @brief Make wrapper for reused cv::Mat. + * @param[in] base Wrapper of cv::Mat that will be reused. + * @param[in] shape Specific shape. + * + * Initialize wrapper from another one. It'll wrap the same host CPU + * memory and mustn't allocate memory on device(i.e. GPU). It might + * has different shape. Use in case of CPU memory reusing for reuse + * associated memory on device too. + */ + BackendWrapper(const Ptr& base, const MatShape& shape); + + virtual ~BackendWrapper(); //!< Virtual destructor to make polymorphism. + + /** + * @brief Transfer data to CPU host memory. + */ + virtual void copyToHost() = 0; + + /** + * @brief Indicate that an actual data is on CPU. + */ + virtual void setHostDirty() = 0; + + int backendId; //!< Backend identifier. + int targetId; //!< Target identifier. + }; + + class CV_EXPORTS ActivationLayer; + + /** @brief This interface class allows to build new Layers - are building blocks of networks. + * + * Each class, derived from Layer, must implement forward() method to compute outputs. + * Also before using the new layer into networks you must register your layer by using one of @ref dnnLayerFactory "LayerFactory" macros. + */ + class CV_EXPORTS_W Layer : public Algorithm + { + public: + + //! List of learned parameters must be stored here to allow read them by using Net::getParam(). + CV_PROP_RW std::vector blobs; + + /** @brief Computes and sets internal parameters according to inputs, outputs and blobs. + * @deprecated Use Layer::finalize(InputArrayOfArrays, OutputArrayOfArrays) instead + * @param[in] input vector of already allocated input blobs + * @param[out] output vector of already allocated output blobs + * + * This method is called after network has allocated all memory for input and output blobs + * and before inferencing. + */ + CV_DEPRECATED_EXTERNAL + virtual void finalize(const std::vector &input, std::vector &output); + + /** @brief Computes and sets internal parameters according to inputs, outputs and blobs. + * @param[in] inputs vector of already allocated input blobs + * @param[out] outputs vector of already allocated output blobs + * + * This method is called after network has allocated all memory for input and output blobs + * and before inferencing. + */ + CV_WRAP virtual void finalize(InputArrayOfArrays inputs, OutputArrayOfArrays outputs); + + /** @brief Given the @p input blobs, computes the output @p blobs. + * @deprecated Use Layer::forward(InputArrayOfArrays, OutputArrayOfArrays, OutputArrayOfArrays) instead + * @param[in] input the input blobs. + * @param[out] output allocated output blobs, which will store results of the computation. + * @param[out] internals allocated internal blobs + */ + CV_DEPRECATED_EXTERNAL + virtual void forward(std::vector &input, std::vector &output, std::vector &internals); + + /** @brief Given the @p input blobs, computes the output @p blobs. + * @param[in] inputs the input blobs. + * @param[out] outputs allocated output blobs, which will store results of the computation. + * @param[out] internals allocated internal blobs + */ + virtual void forward(InputArrayOfArrays inputs, OutputArrayOfArrays outputs, OutputArrayOfArrays internals); + + /** @brief Tries to quantize the given layer and compute the quantization parameters required for fixed point implementation. + * @param[in] scales input and output scales. + * @param[in] zeropoints input and output zeropoints. + * @param[out] params Quantized parameters required for fixed point implementation of that layer. + * @returns True if layer can be quantized. + */ + virtual bool tryQuantize(const std::vector > &scales, + const std::vector > &zeropoints, LayerParams& params); + + /** @brief Given the @p input blobs, computes the output @p blobs. + * @param[in] inputs the input blobs. + * @param[out] outputs allocated output blobs, which will store results of the computation. + * @param[out] internals allocated internal blobs + */ + void forward_fallback(InputArrayOfArrays inputs, OutputArrayOfArrays outputs, OutputArrayOfArrays internals); + + /** @brief + * @overload + * @deprecated Use Layer::finalize(InputArrayOfArrays, OutputArrayOfArrays) instead + */ + CV_DEPRECATED_EXTERNAL + void finalize(const std::vector &inputs, CV_OUT std::vector &outputs); + + /** @brief + * @overload + * @deprecated Use Layer::finalize(InputArrayOfArrays, OutputArrayOfArrays) instead + */ + CV_DEPRECATED std::vector finalize(const std::vector &inputs); + + /** @brief Allocates layer and computes output. + * @deprecated This method will be removed in the future release. + */ + CV_DEPRECATED CV_WRAP void run(const std::vector &inputs, CV_OUT std::vector &outputs, + CV_IN_OUT std::vector &internals); + + /** @brief Returns index of input blob into the input array. + * @param inputName label of input blob + * + * Each layer input and output can be labeled to easily identify them using "%[.output_name]" notation. + * This method maps label of input blob to its index into input vector. + */ + virtual int inputNameToIndex(String inputName); // FIXIT const + /** @brief Returns index of output blob in output array. + * @see inputNameToIndex() + */ + CV_WRAP virtual int outputNameToIndex(const String& outputName); // FIXIT const + + /** + * @brief Ask layer if it support specific backend for doing computations. + * @param[in] backendId computation backend identifier. + * @see Backend + */ + virtual bool supportBackend(int backendId); // FIXIT const + + /** + * @brief Returns Halide backend node. + * @param[in] inputs Input Halide buffers. + * @see BackendNode, BackendWrapper + * + * Input buffers should be exactly the same that will be used in forward invocations. + * Despite we can use Halide::ImageParam based on input shape only, + * it helps prevent some memory management issues (if something wrong, + * Halide tests will be failed). + */ + virtual Ptr initHalide(const std::vector > &inputs); + + virtual Ptr initNgraph(const std::vector > &inputs, const std::vector >& nodes); + + virtual Ptr initVkCom(const std::vector > &inputs, std::vector > &outputs); + + virtual Ptr initWebnn(const std::vector > &inputs, const std::vector >& nodes); + + /** + * @brief Returns a CUDA backend node + * + * @param context void pointer to CSLContext object + * @param inputs layer inputs + * @param outputs layer outputs + */ + virtual Ptr initCUDA( + void *context, + const std::vector>& inputs, + const std::vector>& outputs + ); + + /** + * @brief Returns a TimVX backend node + * + * @param timVxInfo void pointer to CSLContext object + * @param inputsWrapper layer inputs + * @param outputsWrapper layer outputs + * @param isLast if the node is the last one of the TimVX Graph. + */ + virtual Ptr initTimVX(void* timVxInfo, + const std::vector > &inputsWrapper, + const std::vector > &outputsWrapper, + bool isLast); + + /** + * @brief Returns a CANN backend node + * + * @param inputs input tensors of CANN operator + * @param outputs output tensors of CANN operator + * @param nodes nodes of input tensors + */ + virtual Ptr initCann(const std::vector > &inputs, + const std::vector > &outputs, + const std::vector >& nodes); + + /** + * @brief Automatic Halide scheduling based on layer hyper-parameters. + * @param[in] node Backend node with Halide functions. + * @param[in] inputs Blobs that will be used in forward invocations. + * @param[in] outputs Blobs that will be used in forward invocations. + * @param[in] targetId Target identifier + * @see BackendNode, Target + * + * Layer don't use own Halide::Func members because we can have applied + * layers fusing. In this way the fused function should be scheduled. + */ + virtual void applyHalideScheduler(Ptr& node, + const std::vector &inputs, + const std::vector &outputs, + int targetId) const; + + /** + * @brief Implement layers fusing. + * @param[in] node Backend node of bottom layer. + * @see BackendNode + * + * Actual for graph-based backends. If layer attached successfully, + * returns non-empty cv::Ptr to node of the same backend. + * Fuse only over the last function. + */ + virtual Ptr tryAttach(const Ptr& node); + + /** + * @brief Tries to attach to the layer the subsequent activation layer, i.e. do the layer fusion in a partial case. + * @param[in] layer The subsequent activation layer. + * + * Returns true if the activation layer has been attached successfully. + */ + virtual bool setActivation(const Ptr& layer); + + /** + * @brief Try to fuse current layer with a next one + * @param[in] top Next layer to be fused. + * @returns True if fusion was performed. + */ + virtual bool tryFuse(Ptr& top); + + /** + * @brief Returns parameters of layers with channel-wise multiplication and addition. + * @param[out] scale Channel-wise multipliers. Total number of values should + * be equal to number of channels. + * @param[out] shift Channel-wise offsets. Total number of values should + * be equal to number of channels. + * + * Some layers can fuse their transformations with further layers. + * In example, convolution + batch normalization. This way base layer + * use weights from layer after it. Fused layer is skipped. + * By default, @p scale and @p shift are empty that means layer has no + * element-wise multiplications or additions. + */ + virtual void getScaleShift(Mat& scale, Mat& shift) const; + + /** + * @brief Returns scale and zeropoint of layers + * @param[out] scale Output scale + * @param[out] zeropoint Output zeropoint + * + * By default, @p scale is 1 and @p zeropoint is 0. + */ + virtual void getScaleZeropoint(float& scale, int& zeropoint) const; + + + /** + * @brief "Detaches" all the layers, attached to particular layer. + */ + virtual void unsetAttached(); + + virtual bool getMemoryShapes(const std::vector &inputs, + const int requiredOutputs, + std::vector &outputs, + std::vector &internals) const; + + virtual int64 getFLOPS(const std::vector &inputs, + const std::vector &outputs) const {CV_UNUSED(inputs); CV_UNUSED(outputs); return 0;} + + virtual bool updateMemoryShapes(const std::vector &inputs); + + CV_PROP String name; //!< Name of the layer instance, can be used for logging or other internal purposes. + CV_PROP String type; //!< Type name which was used for creating layer by layer factory. + CV_PROP int preferableTarget; //!< prefer target for layer forwarding + + Layer(); + explicit Layer(const LayerParams ¶ms); //!< Initializes only #name, #type and #blobs fields. + void setParamsFrom(const LayerParams ¶ms); //!< Initializes only #name, #type and #blobs fields. + virtual ~Layer(); + }; + + /** @brief This class allows to create and manipulate comprehensive artificial neural networks. + * + * Neural network is presented as directed acyclic graph (DAG), where vertices are Layer instances, + * and edges specify relationships between layers inputs and outputs. + * + * Each network layer has unique integer id and unique string name inside its network. + * LayerId can store either layer name or layer id. + * + * This class supports reference counting of its instances, i. e. copies point to the same instance. + */ + class CV_EXPORTS_W_SIMPLE Net + { + public: + + CV_WRAP Net(); //!< Default constructor. + CV_WRAP ~Net(); //!< Destructor frees the net only if there aren't references to the net anymore. + + /** @brief Create a network from Intel's Model Optimizer intermediate representation (IR). + * @param[in] xml XML configuration file with network's topology. + * @param[in] bin Binary file with trained weights. + * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine + * backend. + */ + CV_WRAP static Net readFromModelOptimizer(CV_WRAP_FILE_PATH const String& xml, CV_WRAP_FILE_PATH const String& bin); + + /** @brief Create a network from Intel's Model Optimizer in-memory buffers with intermediate representation (IR). + * @param[in] bufferModelConfig buffer with model's configuration. + * @param[in] bufferWeights buffer with model's trained weights. + * @returns Net object. + */ + CV_WRAP static + Net readFromModelOptimizer(const std::vector& bufferModelConfig, const std::vector& bufferWeights); + + /** @brief Create a network from Intel's Model Optimizer in-memory buffers with intermediate representation (IR). + * @param[in] bufferModelConfigPtr buffer pointer of model's configuration. + * @param[in] bufferModelConfigSize buffer size of model's configuration. + * @param[in] bufferWeightsPtr buffer pointer of model's trained weights. + * @param[in] bufferWeightsSize buffer size of model's trained weights. + * @returns Net object. + */ + static + Net readFromModelOptimizer(const uchar* bufferModelConfigPtr, size_t bufferModelConfigSize, + const uchar* bufferWeightsPtr, size_t bufferWeightsSize); + + /** Returns true if there are no layers in the network. */ + CV_WRAP bool empty() const; + + /** @brief Dump net to String + * @returns String with structure, hyperparameters, backend, target and fusion + * Call method after setInput(). To see correct backend, target and fusion run after forward(). + */ + CV_WRAP String dump(); + /** @brief Dump net structure, hyperparameters, backend, target and fusion to dot file + * @param path path to output file with .dot extension + * @see dump() + */ + CV_WRAP void dumpToFile(CV_WRAP_FILE_PATH const String& path); + /** @brief Dump net structure, hyperparameters, backend, target and fusion to pbtxt file + * @param path path to output file with .pbtxt extension + * + * Use Netron (https://netron.app) to open the target file to visualize the model. + * Call method after setInput(). To see correct backend, target and fusion run after forward(). + */ + CV_WRAP void dumpToPbtxt(CV_WRAP_FILE_PATH const String& path); + + /** @brief Adds new layer to the net. + * @param name unique name of the adding layer. + * @param type typename of the adding layer (type must be registered in LayerRegister). + * @param dtype datatype of output blobs. + * @param params parameters which will be used to initialize the creating layer. + * @returns unique identifier of created layer, or -1 if a failure will happen. + */ + CV_WRAP int addLayer(const String &name, const String &type, const int &dtype, LayerParams ¶ms); + + /** @overload Datatype of output blobs set to default CV_32F */ + int addLayer(const String &name, const String &type, LayerParams ¶ms); + + /** @brief Adds new layer and connects its first input to the first output of previously added layer. + * @see addLayer() + */ + CV_WRAP int addLayerToPrev(const String &name, const String &type, const int &dtype, LayerParams ¶ms); + + /** @overload */ + int addLayerToPrev(const String &name, const String &type, LayerParams ¶ms); + + /** @brief Converts string name of the layer to the integer identifier. + * @returns id of the layer, or -1 if the layer wasn't found. + */ + CV_WRAP int getLayerId(const String &layer) const; + + CV_WRAP std::vector getLayerNames() const; + + /** @brief Container for strings and integers. + * + * @deprecated Use getLayerId() with int result. + */ + typedef DictValue LayerId; + + /** @brief Returns pointer to layer with specified id or name which the network use. */ + CV_WRAP Ptr getLayer(int layerId) const; + /** @overload + * @deprecated Use int getLayerId(const String &layer) + */ + CV_WRAP inline Ptr getLayer(const String& layerName) const { return getLayer(getLayerId(layerName)); } + /** @overload + * @deprecated to be removed + */ + CV_WRAP Ptr getLayer(const LayerId& layerId) const; + + /** @brief Returns pointers to input layers of specific layer. */ + std::vector > getLayerInputs(int layerId) const; // FIXIT: CV_WRAP + + /** @brief Connects output of the first layer to input of the second layer. + * @param outPin descriptor of the first layer output. + * @param inpPin descriptor of the second layer input. + * + * Descriptors have the following template <layer_name>[.input_number]: + * - the first part of the template layer_name is string name of the added layer. + * If this part is empty then the network input pseudo layer will be used; + * - the second optional part of the template input_number + * is either number of the layer input, either label one. + * If this part is omitted then the first layer input will be used. + * + * @see setNetInputs(), Layer::inputNameToIndex(), Layer::outputNameToIndex() + */ + CV_WRAP void connect(String outPin, String inpPin); + + /** @brief Connects #@p outNum output of the first layer to #@p inNum input of the second layer. + * @param outLayerId identifier of the first layer + * @param outNum number of the first layer output + * @param inpLayerId identifier of the second layer + * @param inpNum number of the second layer input + */ + void connect(int outLayerId, int outNum, int inpLayerId, int inpNum); + + /** @brief Registers network output with name + * + * Function may create additional 'Identity' layer. + * + * @param outputName identifier of the output + * @param layerId identifier of the second layer + * @param outputPort number of the second layer input + * + * @returns index of bound layer (the same as layerId or newly created) + */ + int registerOutput(const std::string& outputName, int layerId, int outputPort); + + /** @brief Sets outputs names of the network input pseudo layer. + * + * Each net always has special own the network input pseudo layer with id=0. + * This layer stores the user blobs only and don't make any computations. + * In fact, this layer provides the only way to pass user data into the network. + * As any other layer, this layer can label its outputs and this function provides an easy way to do this. + */ + CV_WRAP void setInputsNames(const std::vector &inputBlobNames); + + /** @brief Specify shape of network input. + */ + CV_WRAP void setInputShape(const String &inputName, const MatShape& shape); + + /** @brief Runs forward pass to compute output of layer with name @p outputName. + * @param outputName name for layer which output is needed to get + * @return blob for first output of specified layer. + * @details By default runs forward pass for the whole network. + */ + CV_WRAP Mat forward(const String& outputName = String()); + + /** @brief Runs forward pass to compute output of layer with name @p outputName. + * @param outputName name for layer which output is needed to get + * @details By default runs forward pass for the whole network. + * + * This is an asynchronous version of forward(const String&). + * dnn::DNN_BACKEND_INFERENCE_ENGINE backend is required. + */ + CV_WRAP AsyncArray forwardAsync(const String& outputName = String()); + + /** @brief Runs forward pass to compute output of layer with name @p outputName. + * @param outputBlobs contains all output blobs for specified layer. + * @param outputName name for layer which output is needed to get + * @details If @p outputName is empty, runs forward pass for the whole network. + */ + CV_WRAP void forward(CV_ND OutputArrayOfArrays outputBlobs, const String& outputName = String()); + + /** @brief Runs forward pass to compute outputs of layers listed in @p outBlobNames. + * @param outputBlobs contains blobs for first outputs of specified layers. + * @param outBlobNames names for layers which outputs are needed to get + */ + CV_WRAP void forward(CV_ND OutputArrayOfArrays outputBlobs, + const std::vector& outBlobNames); + + /** @brief Runs forward pass to compute outputs of layers listed in @p outBlobNames. + * @param outputBlobs contains all output blobs for each layer specified in @p outBlobNames. + * @param outBlobNames names for layers which outputs are needed to get + */ + CV_WRAP_AS(forwardAndRetrieve) void forward(CV_OUT std::vector >& outputBlobs, + const std::vector& outBlobNames); + + /** @brief Returns a quantized Net from a floating-point Net. + * @param calibData Calibration data to compute the quantization parameters. + * @param inputsDtype Datatype of quantized net's inputs. Can be CV_32F or CV_8S. + * @param outputsDtype Datatype of quantized net's outputs. Can be CV_32F or CV_8S. + * @param perChannel Quantization granularity of quantized Net. The default is true, that means quantize model + * in per-channel way (channel-wise). Set it false to quantize model in per-tensor way (or tensor-wise). + */ + CV_WRAP Net quantize(InputArrayOfArrays calibData, int inputsDtype, int outputsDtype, bool perChannel=true); + + /** @brief Returns input scale and zeropoint for a quantized Net. + * @param scales output parameter for returning input scales. + * @param zeropoints output parameter for returning input zeropoints. + */ + CV_WRAP void getInputDetails(CV_OUT std::vector& scales, CV_OUT std::vector& zeropoints) const; + + /** @brief Returns output scale and zeropoint for a quantized Net. + * @param scales output parameter for returning output scales. + * @param zeropoints output parameter for returning output zeropoints. + */ + CV_WRAP void getOutputDetails(CV_OUT std::vector& scales, CV_OUT std::vector& zeropoints) const; + + /** + * @brief Compile Halide layers. + * @param[in] scheduler Path to YAML file with scheduling directives. + * @see setPreferableBackend + * + * Schedule layers that support Halide backend. Then compile them for + * specific target. For layers that not represented in scheduling file + * or if no manual scheduling used at all, automatic scheduling will be applied. + */ + CV_WRAP void setHalideScheduler(const String& scheduler); + + /** + * @brief Ask network to use specific computation backend where it supported. + * @param[in] backendId backend identifier. + * @see Backend + */ + CV_WRAP void setPreferableBackend(int backendId); + + /** + * @brief Ask network to make computations on specific target device. + * @param[in] targetId target identifier. + * @see Target + * + * List of supported combinations backend / target: + * | | DNN_BACKEND_OPENCV | DNN_BACKEND_INFERENCE_ENGINE | DNN_BACKEND_HALIDE | DNN_BACKEND_CUDA | + * |------------------------|--------------------|------------------------------|--------------------|-------------------| + * | DNN_TARGET_CPU | + | + | + | | + * | DNN_TARGET_OPENCL | + | + | + | | + * | DNN_TARGET_OPENCL_FP16 | + | + | | | + * | DNN_TARGET_MYRIAD | | + | | | + * | DNN_TARGET_FPGA | | + | | | + * | DNN_TARGET_CUDA | | | | + | + * | DNN_TARGET_CUDA_FP16 | | | | + | + * | DNN_TARGET_HDDL | | + | | | + */ + CV_WRAP void setPreferableTarget(int targetId); + + /** @brief Sets the new input value for the network + * @param blob A new blob. Should have CV_32F or CV_8U depth. + * @param name A name of input layer. + * @param scalefactor An optional normalization scale. + * @param mean An optional mean subtraction values. + * @see connect(String, String) to know format of the descriptor. + * + * If scale or mean values are specified, a final input blob is computed + * as: + * \f[input(n,c,h,w) = scalefactor \times (blob(n,c,h,w) - mean_c)\f] + */ + CV_WRAP void setInput(CV_ND InputArray blob, const String& name = "", + double scalefactor = 1.0, const Scalar& mean = Scalar()); + + /** @brief Sets the new value for the learned param of the layer. + * @param layer name or id of the layer. + * @param numParam index of the layer parameter in the Layer::blobs array. + * @param blob the new value. + * @see Layer::blobs + * @note If shape of the new blob differs from the previous shape, + * then the following forward pass may fail. + */ + CV_WRAP void setParam(int layer, int numParam, CV_ND const Mat &blob); + CV_WRAP inline void setParam(const String& layerName, int numParam, CV_ND const Mat &blob) { return setParam(getLayerId(layerName), numParam, blob); } + + /** @brief Returns parameter blob of the layer. + * @param layer name or id of the layer. + * @param numParam index of the layer parameter in the Layer::blobs array. + * @see Layer::blobs + */ + CV_WRAP Mat getParam(int layer, int numParam = 0) const; + CV_WRAP inline Mat getParam(const String& layerName, int numParam = 0) const { return getParam(getLayerId(layerName), numParam); } + + /** @brief Returns indexes of layers with unconnected outputs. + * + * FIXIT: Rework API to registerOutput() approach, deprecate this call + */ + CV_WRAP std::vector getUnconnectedOutLayers() const; + + /** @brief Returns names of layers with unconnected outputs. + * + * FIXIT: Rework API to registerOutput() approach, deprecate this call + */ + CV_WRAP std::vector getUnconnectedOutLayersNames() const; + + /** @brief Returns input and output shapes for all layers in loaded model; + * preliminary inferencing isn't necessary. + * @param netInputShapes shapes for all input blobs in net input layer. + * @param layersIds output parameter for layer IDs. + * @param inLayersShapes output parameter for input layers shapes; + * order is the same as in layersIds + * @param outLayersShapes output parameter for output layers shapes; + * order is the same as in layersIds + */ + CV_WRAP void getLayersShapes(const std::vector& netInputShapes, + CV_OUT std::vector& layersIds, + CV_OUT std::vector >& inLayersShapes, + CV_OUT std::vector >& outLayersShapes) const; + + /** @overload */ + CV_WRAP void getLayersShapes(const MatShape& netInputShape, + CV_OUT std::vector& layersIds, + CV_OUT std::vector >& inLayersShapes, + CV_OUT std::vector >& outLayersShapes) const; + + /** @brief Returns input and output shapes for layer with specified + * id in loaded model; preliminary inferencing isn't necessary. + * @param netInputShape shape input blob in net input layer. + * @param layerId id for layer. + * @param inLayerShapes output parameter for input layers shapes; + * order is the same as in layersIds + * @param outLayerShapes output parameter for output layers shapes; + * order is the same as in layersIds + */ + void getLayerShapes(const MatShape& netInputShape, + const int layerId, + CV_OUT std::vector& inLayerShapes, + CV_OUT std::vector& outLayerShapes) const; // FIXIT: CV_WRAP + + /** @overload */ + void getLayerShapes(const std::vector& netInputShapes, + const int layerId, + CV_OUT std::vector& inLayerShapes, + CV_OUT std::vector& outLayerShapes) const; // FIXIT: CV_WRAP + + /** @brief Computes FLOP for whole loaded model with specified input shapes. + * @param netInputShapes vector of shapes for all net inputs. + * @returns computed FLOP. + */ + CV_WRAP int64 getFLOPS(const std::vector& netInputShapes) const; + /** @overload */ + CV_WRAP int64 getFLOPS(const MatShape& netInputShape) const; + /** @overload */ + CV_WRAP int64 getFLOPS(const int layerId, + const std::vector& netInputShapes) const; + /** @overload */ + CV_WRAP int64 getFLOPS(const int layerId, + const MatShape& netInputShape) const; + + /** @brief Returns list of types for layer used in model. + * @param layersTypes output parameter for returning types. + */ + CV_WRAP void getLayerTypes(CV_OUT std::vector& layersTypes) const; + + /** @brief Returns count of layers of specified type. + * @param layerType type. + * @returns count of layers + */ + CV_WRAP int getLayersCount(const String& layerType) const; + + /** @brief Computes bytes number which are required to store + * all weights and intermediate blobs for model. + * @param netInputShapes vector of shapes for all net inputs. + * @param weights output parameter to store resulting bytes for weights. + * @param blobs output parameter to store resulting bytes for intermediate blobs. + */ + void getMemoryConsumption(const std::vector& netInputShapes, + CV_OUT size_t& weights, CV_OUT size_t& blobs) const; // FIXIT: CV_WRAP + /** @overload */ + CV_WRAP void getMemoryConsumption(const MatShape& netInputShape, + CV_OUT size_t& weights, CV_OUT size_t& blobs) const; + /** @overload */ + CV_WRAP void getMemoryConsumption(const int layerId, + const std::vector& netInputShapes, + CV_OUT size_t& weights, CV_OUT size_t& blobs) const; + /** @overload */ + CV_WRAP void getMemoryConsumption(const int layerId, + const MatShape& netInputShape, + CV_OUT size_t& weights, CV_OUT size_t& blobs) const; + + /** @brief Computes bytes number which are required to store + * all weights and intermediate blobs for each layer. + * @param netInputShapes vector of shapes for all net inputs. + * @param layerIds output vector to save layer IDs. + * @param weights output parameter to store resulting bytes for weights. + * @param blobs output parameter to store resulting bytes for intermediate blobs. + */ + void getMemoryConsumption(const std::vector& netInputShapes, + CV_OUT std::vector& layerIds, + CV_OUT std::vector& weights, + CV_OUT std::vector& blobs) const; // FIXIT: CV_WRAP + /** @overload */ + void getMemoryConsumption(const MatShape& netInputShape, + CV_OUT std::vector& layerIds, + CV_OUT std::vector& weights, + CV_OUT std::vector& blobs) const; // FIXIT: CV_WRAP + + /** @brief Enables or disables layer fusion in the network. + * @param fusion true to enable the fusion, false to disable. The fusion is enabled by default. + */ + CV_WRAP void enableFusion(bool fusion); + + /** @brief Enables or disables the Winograd compute branch. The Winograd compute branch can speed up + * 3x3 Convolution at a small loss of accuracy. + * @param useWinograd true to enable the Winograd compute branch. The default is true. + */ + CV_WRAP void enableWinograd(bool useWinograd); + + /** @brief Returns overall time for inference and timings (in ticks) for layers. + * + * Indexes in returned vector correspond to layers ids. Some layers can be fused with others, + * in this case zero ticks count will be return for that skipped layers. Supported by DNN_BACKEND_OPENCV on DNN_TARGET_CPU only. + * + * @param[out] timings vector for tick timings for all layers. + * @return overall ticks for model inference. + */ + CV_WRAP int64 getPerfProfile(CV_OUT std::vector& timings); + + + struct Impl; + inline Impl* getImpl() const { return impl.get(); } + inline Impl& getImplRef() const { CV_DbgAssert(impl); return *impl.get(); } + friend class accessor::DnnNetAccessor; + protected: + Ptr impl; + }; + + /** @brief Reads a network model stored in Darknet model files. + * @param cfgFile path to the .cfg file with text description of the network architecture. + * @param darknetModel path to the .weights file with learned network. + * @returns Network object that ready to do forward, throw an exception in failure cases. + */ + CV_EXPORTS_W Net readNetFromDarknet(CV_WRAP_FILE_PATH const String &cfgFile, CV_WRAP_FILE_PATH const String &darknetModel = String()); + + /** @brief Reads a network model stored in Darknet model files. + * @param bufferCfg A buffer contains a content of .cfg file with text description of the network architecture. + * @param bufferModel A buffer contains a content of .weights file with learned network. + * @returns Net object. + */ + CV_EXPORTS_W Net readNetFromDarknet(const std::vector& bufferCfg, + const std::vector& bufferModel = std::vector()); + + /** @brief Reads a network model stored in Darknet model files. + * @param bufferCfg A buffer contains a content of .cfg file with text description of the network architecture. + * @param lenCfg Number of bytes to read from bufferCfg + * @param bufferModel A buffer contains a content of .weights file with learned network. + * @param lenModel Number of bytes to read from bufferModel + * @returns Net object. + */ + CV_EXPORTS Net readNetFromDarknet(const char *bufferCfg, size_t lenCfg, + const char *bufferModel = NULL, size_t lenModel = 0); + + /** @brief Reads a network model stored in Caffe framework's format. + * @param prototxt path to the .prototxt file with text description of the network architecture. + * @param caffeModel path to the .caffemodel file with learned network. + * @returns Net object. + */ + CV_EXPORTS_W Net readNetFromCaffe(CV_WRAP_FILE_PATH const String &prototxt, CV_WRAP_FILE_PATH const String &caffeModel = String()); + + /** @brief Reads a network model stored in Caffe model in memory. + * @param bufferProto buffer containing the content of the .prototxt file + * @param bufferModel buffer containing the content of the .caffemodel file + * @returns Net object. + */ + CV_EXPORTS_W Net readNetFromCaffe(const std::vector& bufferProto, + const std::vector& bufferModel = std::vector()); + + /** @brief Reads a network model stored in Caffe model in memory. + * @details This is an overloaded member function, provided for convenience. + * It differs from the above function only in what argument(s) it accepts. + * @param bufferProto buffer containing the content of the .prototxt file + * @param lenProto length of bufferProto + * @param bufferModel buffer containing the content of the .caffemodel file + * @param lenModel length of bufferModel + * @returns Net object. + */ + CV_EXPORTS Net readNetFromCaffe(const char *bufferProto, size_t lenProto, + const char *bufferModel = NULL, size_t lenModel = 0); + + /** @brief Reads a network model stored in TensorFlow framework's format. + * @param model path to the .pb file with binary protobuf description of the network architecture + * @param config path to the .pbtxt file that contains text graph definition in protobuf format. + * Resulting Net object is built by text graph using weights from a binary one that + * let us make it more flexible. + * @returns Net object. + */ + CV_EXPORTS_W Net readNetFromTensorflow(CV_WRAP_FILE_PATH const String &model, CV_WRAP_FILE_PATH const String &config = String()); + + /** @brief Reads a network model stored in TensorFlow framework's format. + * @param bufferModel buffer containing the content of the pb file + * @param bufferConfig buffer containing the content of the pbtxt file + * @returns Net object. + */ + CV_EXPORTS_W Net readNetFromTensorflow(const std::vector& bufferModel, + const std::vector& bufferConfig = std::vector()); + + /** @brief Reads a network model stored in TensorFlow framework's format. + * @details This is an overloaded member function, provided for convenience. + * It differs from the above function only in what argument(s) it accepts. + * @param bufferModel buffer containing the content of the pb file + * @param lenModel length of bufferModel + * @param bufferConfig buffer containing the content of the pbtxt file + * @param lenConfig length of bufferConfig + */ + CV_EXPORTS Net readNetFromTensorflow(const char *bufferModel, size_t lenModel, + const char *bufferConfig = NULL, size_t lenConfig = 0); + + /** @brief Reads a network model stored in TFLite framework's format. + * @param model path to the .tflite file with binary flatbuffers description of the network architecture + * @returns Net object. + */ + CV_EXPORTS_W Net readNetFromTFLite(CV_WRAP_FILE_PATH const String &model); + + /** @brief Reads a network model stored in TFLite framework's format. + * @param bufferModel buffer containing the content of the tflite file + * @returns Net object. + */ + CV_EXPORTS_W Net readNetFromTFLite(const std::vector& bufferModel); + + /** @brief Reads a network model stored in TFLite framework's format. + * @details This is an overloaded member function, provided for convenience. + * It differs from the above function only in what argument(s) it accepts. + * @param bufferModel buffer containing the content of the tflite file + * @param lenModel length of bufferModel + */ + CV_EXPORTS Net readNetFromTFLite(const char *bufferModel, size_t lenModel); + + /** + * @brief Reads a network model stored in Torch7 framework's format. + * @param model path to the file, dumped from Torch by using torch.save() function. + * @param isBinary specifies whether the network was serialized in ascii mode or binary. + * @param evaluate specifies testing phase of network. If true, it's similar to evaluate() method in Torch. + * @returns Net object. + * + * @note Ascii mode of Torch serializer is more preferable, because binary mode extensively use `long` type of C language, + * which has various bit-length on different systems. + * + * The loading file must contain serialized nn.Module object + * with importing network. Try to eliminate a custom objects from serialazing data to avoid importing errors. + * + * List of supported layers (i.e. object instances derived from Torch nn.Module class): + * - nn.Sequential + * - nn.Parallel + * - nn.Concat + * - nn.Linear + * - nn.SpatialConvolution + * - nn.SpatialMaxPooling, nn.SpatialAveragePooling + * - nn.ReLU, nn.TanH, nn.Sigmoid + * - nn.Reshape + * - nn.SoftMax, nn.LogSoftMax + * + * Also some equivalents of these classes from cunn, cudnn, and fbcunn may be successfully imported. + */ + CV_EXPORTS_W Net readNetFromTorch(CV_WRAP_FILE_PATH const String &model, bool isBinary = true, bool evaluate = true); + + /** + * @brief Read deep learning network represented in one of the supported formats. + * @param[in] model Binary file contains trained weights. The following file + * extensions are expected for models from different frameworks: + * * `*.caffemodel` (Caffe, http://caffe.berkeleyvision.org/) + * * `*.pb` (TensorFlow, https://www.tensorflow.org/) + * * `*.t7` | `*.net` (Torch, http://torch.ch/) + * * `*.weights` (Darknet, https://pjreddie.com/darknet/) + * * `*.bin` | `*.onnx` (OpenVINO, https://software.intel.com/openvino-toolkit) + * * `*.onnx` (ONNX, https://onnx.ai/) + * @param[in] config Text file contains network configuration. It could be a + * file with the following extensions: + * * `*.prototxt` (Caffe, http://caffe.berkeleyvision.org/) + * * `*.pbtxt` (TensorFlow, https://www.tensorflow.org/) + * * `*.cfg` (Darknet, https://pjreddie.com/darknet/) + * * `*.xml` (OpenVINO, https://software.intel.com/openvino-toolkit) + * @param[in] framework Explicit framework name tag to determine a format. + * @returns Net object. + * + * This function automatically detects an origin framework of trained model + * and calls an appropriate function such @ref readNetFromCaffe, @ref readNetFromTensorflow, + * @ref readNetFromTorch or @ref readNetFromDarknet. An order of @p model and @p config + * arguments does not matter. + */ + CV_EXPORTS_W Net readNet(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config = "", const String& framework = ""); + + /** + * @brief Read deep learning network represented in one of the supported formats. + * @details This is an overloaded member function, provided for convenience. + * It differs from the above function only in what argument(s) it accepts. + * @param[in] framework Name of origin framework. + * @param[in] bufferModel A buffer with a content of binary file with weights + * @param[in] bufferConfig A buffer with a content of text file contains network configuration. + * @returns Net object. + */ + CV_EXPORTS_W Net readNet(const String& framework, const std::vector& bufferModel, + const std::vector& bufferConfig = std::vector()); + + /** @brief Loads blob which was serialized as torch.Tensor object of Torch7 framework. + * @warning This function has the same limitations as readNetFromTorch(). + */ + CV_EXPORTS_W Mat readTorchBlob(const String &filename, bool isBinary = true); + + /** @brief Load a network from Intel's Model Optimizer intermediate representation. + * @param[in] xml XML configuration file with network's topology. + * @param[in] bin Binary file with trained weights. + * @returns Net object. + * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine + * backend. + */ + CV_EXPORTS_W + Net readNetFromModelOptimizer(CV_WRAP_FILE_PATH const String &xml, CV_WRAP_FILE_PATH const String &bin = ""); + + /** @brief Load a network from Intel's Model Optimizer intermediate representation. + * @param[in] bufferModelConfig Buffer contains XML configuration with network's topology. + * @param[in] bufferWeights Buffer contains binary data with trained weights. + * @returns Net object. + * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine + * backend. + */ + CV_EXPORTS_W + Net readNetFromModelOptimizer(const std::vector& bufferModelConfig, const std::vector& bufferWeights); + + /** @brief Load a network from Intel's Model Optimizer intermediate representation. + * @param[in] bufferModelConfigPtr Pointer to buffer which contains XML configuration with network's topology. + * @param[in] bufferModelConfigSize Binary size of XML configuration data. + * @param[in] bufferWeightsPtr Pointer to buffer which contains binary data with trained weights. + * @param[in] bufferWeightsSize Binary size of trained weights data. + * @returns Net object. + * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine + * backend. + */ + CV_EXPORTS + Net readNetFromModelOptimizer(const uchar* bufferModelConfigPtr, size_t bufferModelConfigSize, + const uchar* bufferWeightsPtr, size_t bufferWeightsSize); + + /** @brief Reads a network model ONNX. + * @param onnxFile path to the .onnx file with text description of the network architecture. + * @returns Network object that ready to do forward, throw an exception in failure cases. + */ + CV_EXPORTS_W Net readNetFromONNX(CV_WRAP_FILE_PATH const String &onnxFile); + + /** @brief Reads a network model from ONNX + * in-memory buffer. + * @param buffer memory address of the first byte of the buffer. + * @param sizeBuffer size of the buffer. + * @returns Network object that ready to do forward, throw an exception + * in failure cases. + */ + CV_EXPORTS Net readNetFromONNX(const char* buffer, size_t sizeBuffer); + + /** @brief Reads a network model from ONNX + * in-memory buffer. + * @param buffer in-memory buffer that stores the ONNX model bytes. + * @returns Network object that ready to do forward, throw an exception + * in failure cases. + */ + CV_EXPORTS_W Net readNetFromONNX(const std::vector& buffer); + + /** @brief Creates blob from .pb file. + * @param path to the .pb file with input tensor. + * @returns Mat. + */ + CV_EXPORTS_W Mat readTensorFromONNX(CV_WRAP_FILE_PATH const String& path); + + /** @brief Creates 4-dimensional blob from image. Optionally resizes and crops @p image from center, + * subtract @p mean values, scales values by @p scalefactor, swap Blue and Red channels. + * @param image input image (with 1-, 3- or 4-channels). + * @param scalefactor multiplier for @p images values. + * @param size spatial size for output image + * @param mean scalar with mean values which are subtracted from channels. Values are intended + * to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true. + * @param swapRB flag which indicates that swap first and last channels + * in 3-channel image is necessary. + * @param crop flag which indicates whether image will be cropped after resize or not + * @param ddepth Depth of output blob. Choose CV_32F or CV_8U. + * @details if @p crop is true, input image is resized so one side after resize is equal to corresponding + * dimension in @p size and another one is equal or larger. Then, crop from the center is performed. + * If @p crop is false, direct resize without cropping and preserving aspect ratio is performed. + * @returns 4-dimensional Mat with NCHW dimensions order. + * + * @note + * The order and usage of `scalefactor` and `mean` are (input - mean) * scalefactor. + */ + CV_EXPORTS_W Mat blobFromImage(InputArray image, double scalefactor=1.0, const Size& size = Size(), + const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false, + int ddepth=CV_32F); + + /** @brief Creates 4-dimensional blob from image. + * @details This is an overloaded member function, provided for convenience. + * It differs from the above function only in what argument(s) it accepts. + */ + CV_EXPORTS void blobFromImage(InputArray image, OutputArray blob, double scalefactor=1.0, + const Size& size = Size(), const Scalar& mean = Scalar(), + bool swapRB=false, bool crop=false, int ddepth=CV_32F); + + + /** @brief Creates 4-dimensional blob from series of images. Optionally resizes and + * crops @p images from center, subtract @p mean values, scales values by @p scalefactor, + * swap Blue and Red channels. + * @param images input images (all with 1-, 3- or 4-channels). + * @param size spatial size for output image + * @param mean scalar with mean values which are subtracted from channels. Values are intended + * to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true. + * @param scalefactor multiplier for @p images values. + * @param swapRB flag which indicates that swap first and last channels + * in 3-channel image is necessary. + * @param crop flag which indicates whether image will be cropped after resize or not + * @param ddepth Depth of output blob. Choose CV_32F or CV_8U. + * @details if @p crop is true, input image is resized so one side after resize is equal to corresponding + * dimension in @p size and another one is equal or larger. Then, crop from the center is performed. + * If @p crop is false, direct resize without cropping and preserving aspect ratio is performed. + * @returns 4-dimensional Mat with NCHW dimensions order. + * + * @note + * The order and usage of `scalefactor` and `mean` are (input - mean) * scalefactor. + */ + CV_EXPORTS_W Mat blobFromImages(InputArrayOfArrays images, double scalefactor=1.0, + Size size = Size(), const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false, + int ddepth=CV_32F); + + /** @brief Creates 4-dimensional blob from series of images. + * @details This is an overloaded member function, provided for convenience. + * It differs from the above function only in what argument(s) it accepts. + */ + CV_EXPORTS void blobFromImages(InputArrayOfArrays images, OutputArray blob, + double scalefactor=1.0, Size size = Size(), + const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false, + int ddepth=CV_32F); + + /** + * @brief Enum of image processing mode. + * To facilitate the specialization pre-processing requirements of the dnn model. + * For example, the `letter box` often used in the Yolo series of models. + * @see Image2BlobParams + */ + enum ImagePaddingMode + { + DNN_PMODE_NULL = 0, // !< Default. Resize to required input size without extra processing. + DNN_PMODE_CROP_CENTER = 1, // !< Image will be cropped after resize. + DNN_PMODE_LETTERBOX = 2, // !< Resize image to the desired size while preserving the aspect ratio of original image. + }; + + /** @brief Processing params of image to blob. + * + * It includes all possible image processing operations and corresponding parameters. + * + * @see blobFromImageWithParams + * + * @note + * The order and usage of `scalefactor` and `mean` are (input - mean) * scalefactor. + * The order and usage of `scalefactor`, `size`, `mean`, `swapRB`, and `ddepth` are consistent + * with the function of @ref blobFromImage. + */ + struct CV_EXPORTS_W_SIMPLE Image2BlobParams + { + CV_WRAP Image2BlobParams(); + CV_WRAP Image2BlobParams(const Scalar& scalefactor, const Size& size = Size(), const Scalar& mean = Scalar(), + bool swapRB = false, int ddepth = CV_32F, DataLayout datalayout = DNN_LAYOUT_NCHW, + ImagePaddingMode mode = DNN_PMODE_NULL, Scalar borderValue = 0.0); + + CV_PROP_RW Scalar scalefactor; //!< scalefactor multiplier for input image values. + CV_PROP_RW Size size; //!< Spatial size for output image. + CV_PROP_RW Scalar mean; //!< Scalar with mean values which are subtracted from channels. + CV_PROP_RW bool swapRB; //!< Flag which indicates that swap first and last channels + CV_PROP_RW int ddepth; //!< Depth of output blob. Choose CV_32F or CV_8U. + CV_PROP_RW DataLayout datalayout; //!< Order of output dimensions. Choose DNN_LAYOUT_NCHW or DNN_LAYOUT_NHWC. + CV_PROP_RW ImagePaddingMode paddingmode; //!< Image padding mode. @see ImagePaddingMode. + CV_PROP_RW Scalar borderValue; //!< Value used in padding mode for padding. + + /** @brief Get rectangle coordinates in original image system from rectangle in blob coordinates. + * @param rBlob rect in blob coordinates. + * @param size original input image size. + * @returns rectangle in original image coordinates. + */ + CV_WRAP Rect blobRectToImageRect(const Rect &rBlob, const Size &size); + + /** @brief Get rectangle coordinates in original image system from rectangle in blob coordinates. + * @param rBlob rect in blob coordinates. + * @param rImg result rect in image coordinates. + * @param size original input image size. + */ + CV_WRAP void blobRectsToImageRects(const std::vector &rBlob, CV_OUT std::vector& rImg, const Size& size); + }; + + /** @brief Creates 4-dimensional blob from image with given params. + * + * @details This function is an extension of @ref blobFromImage to meet more image preprocess needs. + * Given input image and preprocessing parameters, and function outputs the blob. + * + * @param image input image (all with 1-, 3- or 4-channels). + * @param param struct of Image2BlobParams, contains all parameters needed by processing of image to blob. + * @return 4-dimensional Mat. + */ + CV_EXPORTS_W Mat blobFromImageWithParams(InputArray image, const Image2BlobParams& param = Image2BlobParams()); + + /** @overload */ + CV_EXPORTS_W void blobFromImageWithParams(InputArray image, OutputArray blob, const Image2BlobParams& param = Image2BlobParams()); + + /** @brief Creates 4-dimensional blob from series of images with given params. + * + * @details This function is an extension of @ref blobFromImages to meet more image preprocess needs. + * Given input image and preprocessing parameters, and function outputs the blob. + * + * @param images input image (all with 1-, 3- or 4-channels). + * @param param struct of Image2BlobParams, contains all parameters needed by processing of image to blob. + * @returns 4-dimensional Mat. + */ + CV_EXPORTS_W Mat blobFromImagesWithParams(InputArrayOfArrays images, const Image2BlobParams& param = Image2BlobParams()); + + /** @overload */ + CV_EXPORTS_W void blobFromImagesWithParams(InputArrayOfArrays images, OutputArray blob, const Image2BlobParams& param = Image2BlobParams()); + + /** @brief Parse a 4D blob and output the images it contains as 2D arrays through a simpler data structure + * (std::vector). + * @param[in] blob_ 4 dimensional array (images, channels, height, width) in floating point precision (CV_32F) from + * which you would like to extract the images. + * @param[out] images_ array of 2D Mat containing the images extracted from the blob in floating point precision + * (CV_32F). They are non normalized neither mean added. The number of returned images equals the first dimension + * of the blob (batch size). Every image has a number of channels equals to the second dimension of the blob (depth). + */ + CV_EXPORTS_W void imagesFromBlob(const cv::Mat& blob_, OutputArrayOfArrays images_); + + /** @brief Convert all weights of Caffe network to half precision floating point. + * @param src Path to origin model from Caffe framework contains single + * precision floating point weights (usually has `.caffemodel` extension). + * @param dst Path to destination model with updated weights. + * @param layersTypes Set of layers types which parameters will be converted. + * By default, converts only Convolutional and Fully-Connected layers' + * weights. + * + * @note Shrinked model has no origin float32 weights so it can't be used + * in origin Caffe framework anymore. However the structure of data + * is taken from NVidia's Caffe fork: https://github.com/NVIDIA/caffe. + * So the resulting model may be used there. + */ + CV_EXPORTS_W void shrinkCaffeModel(CV_WRAP_FILE_PATH const String& src, CV_WRAP_FILE_PATH const String& dst, + const std::vector& layersTypes = std::vector()); + + /** @brief Create a text representation for a binary network stored in protocol buffer format. + * @param[in] model A path to binary network. + * @param[in] output A path to output text file to be created. + * + * @note To reduce output file size, trained weights are not included. + */ + CV_EXPORTS_W void writeTextGraph(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& output); + + /** @brief Performs non maximum suppression given boxes and corresponding scores. + + * @param bboxes a set of bounding boxes to apply NMS. + * @param scores a set of corresponding confidences. + * @param score_threshold a threshold used to filter boxes by score. + * @param nms_threshold a threshold used in non maximum suppression. + * @param indices the kept indices of bboxes after NMS. + * @param eta a coefficient in adaptive threshold formula: \f$nms\_threshold_{i+1}=eta\cdot nms\_threshold_i\f$. + * @param top_k if `>0`, keep at most @p top_k picked indices. + */ + CV_EXPORTS void NMSBoxes(const std::vector& bboxes, const std::vector& scores, + const float score_threshold, const float nms_threshold, + CV_OUT std::vector& indices, + const float eta = 1.f, const int top_k = 0); + + CV_EXPORTS_W void NMSBoxes(const std::vector& bboxes, const std::vector& scores, + const float score_threshold, const float nms_threshold, + CV_OUT std::vector& indices, + const float eta = 1.f, const int top_k = 0); + + CV_EXPORTS_AS(NMSBoxesRotated) void NMSBoxes(const std::vector& bboxes, const std::vector& scores, + const float score_threshold, const float nms_threshold, + CV_OUT std::vector& indices, + const float eta = 1.f, const int top_k = 0); + + /** @brief Performs batched non maximum suppression on given boxes and corresponding scores across different classes. + + * @param bboxes a set of bounding boxes to apply NMS. + * @param scores a set of corresponding confidences. + * @param class_ids a set of corresponding class ids. Ids are integer and usually start from 0. + * @param score_threshold a threshold used to filter boxes by score. + * @param nms_threshold a threshold used in non maximum suppression. + * @param indices the kept indices of bboxes after NMS. + * @param eta a coefficient in adaptive threshold formula: \f$nms\_threshold_{i+1}=eta\cdot nms\_threshold_i\f$. + * @param top_k if `>0`, keep at most @p top_k picked indices. + */ + CV_EXPORTS void NMSBoxesBatched(const std::vector& bboxes, const std::vector& scores, const std::vector& class_ids, + const float score_threshold, const float nms_threshold, + CV_OUT std::vector& indices, + const float eta = 1.f, const int top_k = 0); + + CV_EXPORTS_W void NMSBoxesBatched(const std::vector& bboxes, const std::vector& scores, const std::vector& class_ids, + const float score_threshold, const float nms_threshold, + CV_OUT std::vector& indices, + const float eta = 1.f, const int top_k = 0); + + /** + * @brief Enum of Soft NMS methods. + * @see softNMSBoxes + */ + enum class SoftNMSMethod + { + SOFTNMS_LINEAR = 1, + SOFTNMS_GAUSSIAN = 2 + }; + + /** @brief Performs soft non maximum suppression given boxes and corresponding scores. + * Reference: https://arxiv.org/abs/1704.04503 + * @param bboxes a set of bounding boxes to apply Soft NMS. + * @param scores a set of corresponding confidences. + * @param updated_scores a set of corresponding updated confidences. + * @param score_threshold a threshold used to filter boxes by score. + * @param nms_threshold a threshold used in non maximum suppression. + * @param indices the kept indices of bboxes after NMS. + * @param top_k keep at most @p top_k picked indices. + * @param sigma parameter of Gaussian weighting. + * @param method Gaussian or linear. + * @see SoftNMSMethod + */ + CV_EXPORTS_W void softNMSBoxes(const std::vector& bboxes, + const std::vector& scores, + CV_OUT std::vector& updated_scores, + const float score_threshold, + const float nms_threshold, + CV_OUT std::vector& indices, + size_t top_k = 0, + const float sigma = 0.5, + SoftNMSMethod method = SoftNMSMethod::SOFTNMS_GAUSSIAN); + + + /** @brief This class is presented high-level API for neural networks. + * + * Model allows to set params for preprocessing input image. + * Model creates net from file with trained weights and config, + * sets preprocessing input and runs forward pass. + */ + class CV_EXPORTS_W_SIMPLE Model + { + public: + CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) + Model(); + + Model(const Model&) = default; + Model(Model&&) = default; + Model& operator=(const Model&) = default; + Model& operator=(Model&&) = default; + + /** + * @brief Create model from deep learning network represented in one of the supported formats. + * An order of @p model and @p config arguments does not matter. + * @param[in] model Binary file contains trained weights. + * @param[in] config Text file contains network configuration. + */ + CV_WRAP Model(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config = ""); + + /** + * @brief Create model from deep learning network. + * @param[in] network Net object. + */ + CV_WRAP Model(const Net& network); + + /** @brief Set input size for frame. + * @param[in] size New input size. + * @note If shape of the new blob less than 0, then frame size not change. + */ + CV_WRAP Model& setInputSize(const Size& size); + + /** @overload + * @param[in] width New input width. + * @param[in] height New input height. + */ + CV_WRAP inline + Model& setInputSize(int width, int height) { return setInputSize(Size(width, height)); } + + /** @brief Set mean value for frame. + * @param[in] mean Scalar with mean values which are subtracted from channels. + */ + CV_WRAP Model& setInputMean(const Scalar& mean); + + /** @brief Set scalefactor value for frame. + * @param[in] scale Multiplier for frame values. + */ + CV_WRAP Model& setInputScale(const Scalar& scale); + + /** @brief Set flag crop for frame. + * @param[in] crop Flag which indicates whether image will be cropped after resize or not. + */ + CV_WRAP Model& setInputCrop(bool crop); + + /** @brief Set flag swapRB for frame. + * @param[in] swapRB Flag which indicates that swap first and last channels. + */ + CV_WRAP Model& setInputSwapRB(bool swapRB); + + /** @brief Set output names for frame. + * @param[in] outNames Names for output layers. + */ + CV_WRAP Model& setOutputNames(const std::vector& outNames); + + /** @brief Set preprocessing parameters for frame. + * @param[in] size New input size. + * @param[in] mean Scalar with mean values which are subtracted from channels. + * @param[in] scale Multiplier for frame values. + * @param[in] swapRB Flag which indicates that swap first and last channels. + * @param[in] crop Flag which indicates whether image will be cropped after resize or not. + * blob(n, c, y, x) = scale * resize( frame(y, x, c) ) - mean(c) ) + */ + CV_WRAP void setInputParams(double scale = 1.0, const Size& size = Size(), + const Scalar& mean = Scalar(), bool swapRB = false, bool crop = false); + + /** @brief Given the @p input frame, create input blob, run net and return the output @p blobs. + * @param[in] frame The input image. + * @param[out] outs Allocated output blobs, which will store results of the computation. + */ + CV_WRAP void predict(InputArray frame, OutputArrayOfArrays outs) const; + + + // ============================== Net proxy methods ============================== + // Never expose methods with network implementation details, like: + // - addLayer, addLayerToPrev, connect, setInputsNames, setInputShape, setParam, getParam + // - getLayer*, getUnconnectedOutLayers, getUnconnectedOutLayersNames, getLayersShapes + // - forward* methods, setInput + + /// @sa Net::setPreferableBackend + CV_WRAP Model& setPreferableBackend(dnn::Backend backendId); + /// @sa Net::setPreferableTarget + CV_WRAP Model& setPreferableTarget(dnn::Target targetId); + + /// @sa Net::enableWinograd + CV_WRAP Model& enableWinograd(bool useWinograd); + + CV_DEPRECATED_EXTERNAL + operator Net&() const { return getNetwork_(); } + + //protected: - internal/tests usage only + Net& getNetwork_() const; + inline Net& getNetwork_() { return const_cast(this)->getNetwork_(); } + + struct Impl; + inline Impl* getImpl() const { return impl.get(); } + inline Impl& getImplRef() const { CV_DbgAssert(impl); return *impl.get(); } + protected: + Ptr impl; + }; + + /** @brief This class represents high-level API for classification models. + * + * ClassificationModel allows to set params for preprocessing input image. + * ClassificationModel creates net from file with trained weights and config, + * sets preprocessing input, runs forward pass and return top-1 prediction. + */ + class CV_EXPORTS_W_SIMPLE ClassificationModel : public Model + { + public: + CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) + ClassificationModel(); + + /** + * @brief Create classification model from network represented in one of the supported formats. + * An order of @p model and @p config arguments does not matter. + * @param[in] model Binary file contains trained weights. + * @param[in] config Text file contains network configuration. + */ + CV_WRAP ClassificationModel(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config = ""); + + /** + * @brief Create model from deep learning network. + * @param[in] network Net object. + */ + CV_WRAP ClassificationModel(const Net& network); + + /** + * @brief Set enable/disable softmax post processing option. + * + * If this option is true, softmax is applied after forward inference within the classify() function + * to convert the confidences range to [0.0-1.0]. + * This function allows you to toggle this behavior. + * Please turn true when not contain softmax layer in model. + * @param[in] enable Set enable softmax post processing within the classify() function. + */ + CV_WRAP ClassificationModel& setEnableSoftmaxPostProcessing(bool enable); + + /** + * @brief Get enable/disable softmax post processing option. + * + * This option defaults to false, softmax post processing is not applied within the classify() function. + */ + CV_WRAP bool getEnableSoftmaxPostProcessing() const; + + /** @brief Given the @p input frame, create input blob, run net and return top-1 prediction. + * @param[in] frame The input image. + */ + std::pair classify(InputArray frame); + + /** @overload */ + CV_WRAP void classify(InputArray frame, CV_OUT int& classId, CV_OUT float& conf); + }; + + /** @brief This class represents high-level API for keypoints models + * + * KeypointsModel allows to set params for preprocessing input image. + * KeypointsModel creates net from file with trained weights and config, + * sets preprocessing input, runs forward pass and returns the x and y coordinates of each detected keypoint + */ + class CV_EXPORTS_W_SIMPLE KeypointsModel: public Model + { + public: + /** + * @brief Create keypoints model from network represented in one of the supported formats. + * An order of @p model and @p config arguments does not matter. + * @param[in] model Binary file contains trained weights. + * @param[in] config Text file contains network configuration. + */ + CV_WRAP KeypointsModel(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config = ""); + + /** + * @brief Create model from deep learning network. + * @param[in] network Net object. + */ + CV_WRAP KeypointsModel(const Net& network); + + /** @brief Given the @p input frame, create input blob, run net + * @param[in] frame The input image. + * @param thresh minimum confidence threshold to select a keypoint + * @returns a vector holding the x and y coordinates of each detected keypoint + * + */ + CV_WRAP std::vector estimate(InputArray frame, float thresh=0.5); + }; + + /** @brief This class represents high-level API for segmentation models + * + * SegmentationModel allows to set params for preprocessing input image. + * SegmentationModel creates net from file with trained weights and config, + * sets preprocessing input, runs forward pass and returns the class prediction for each pixel. + */ + class CV_EXPORTS_W_SIMPLE SegmentationModel: public Model + { + public: + /** + * @brief Create segmentation model from network represented in one of the supported formats. + * An order of @p model and @p config arguments does not matter. + * @param[in] model Binary file contains trained weights. + * @param[in] config Text file contains network configuration. + */ + CV_WRAP SegmentationModel(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config = ""); + + /** + * @brief Create model from deep learning network. + * @param[in] network Net object. + */ + CV_WRAP SegmentationModel(const Net& network); + + /** @brief Given the @p input frame, create input blob, run net + * @param[in] frame The input image. + * @param[out] mask Allocated class prediction for each pixel + */ + CV_WRAP void segment(InputArray frame, OutputArray mask); + }; + + /** @brief This class represents high-level API for object detection networks. + * + * DetectionModel allows to set params for preprocessing input image. + * DetectionModel creates net from file with trained weights and config, + * sets preprocessing input, runs forward pass and return result detections. + * For DetectionModel SSD, Faster R-CNN, YOLO topologies are supported. + */ + class CV_EXPORTS_W_SIMPLE DetectionModel : public Model + { + public: + /** + * @brief Create detection model from network represented in one of the supported formats. + * An order of @p model and @p config arguments does not matter. + * @param[in] model Binary file contains trained weights. + * @param[in] config Text file contains network configuration. + */ + CV_WRAP DetectionModel(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config = ""); + + /** + * @brief Create model from deep learning network. + * @param[in] network Net object. + */ + CV_WRAP DetectionModel(const Net& network); + + CV_DEPRECATED_EXTERNAL // avoid using in C++ code (need to fix bindings first) + DetectionModel(); + + /** + * @brief nmsAcrossClasses defaults to false, + * such that when non max suppression is used during the detect() function, it will do so per-class. + * This function allows you to toggle this behaviour. + * @param[in] value The new value for nmsAcrossClasses + */ + CV_WRAP DetectionModel& setNmsAcrossClasses(bool value); + + /** + * @brief Getter for nmsAcrossClasses. This variable defaults to false, + * such that when non max suppression is used during the detect() function, it will do so only per-class + */ + CV_WRAP bool getNmsAcrossClasses(); + + /** @brief Given the @p input frame, create input blob, run net and return result detections. + * @param[in] frame The input image. + * @param[out] classIds Class indexes in result detection. + * @param[out] confidences A set of corresponding confidences. + * @param[out] boxes A set of bounding boxes. + * @param[in] confThreshold A threshold used to filter boxes by confidences. + * @param[in] nmsThreshold A threshold used in non maximum suppression. + */ + CV_WRAP void detect(InputArray frame, CV_OUT std::vector& classIds, + CV_OUT std::vector& confidences, CV_OUT std::vector& boxes, + float confThreshold = 0.5f, float nmsThreshold = 0.0f); + }; + + +/** @brief This class represents high-level API for text recognition networks. + * + * TextRecognitionModel allows to set params for preprocessing input image. + * TextRecognitionModel creates net from file with trained weights and config, + * sets preprocessing input, runs forward pass and return recognition result. + * For TextRecognitionModel, CRNN-CTC is supported. + */ +class CV_EXPORTS_W_SIMPLE TextRecognitionModel : public Model +{ +public: + CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) + TextRecognitionModel(); + + /** + * @brief Create Text Recognition model from deep learning network + * Call setDecodeType() and setVocabulary() after constructor to initialize the decoding method + * @param[in] network Net object + */ + CV_WRAP TextRecognitionModel(const Net& network); + + /** + * @brief Create text recognition model from network represented in one of the supported formats + * Call setDecodeType() and setVocabulary() after constructor to initialize the decoding method + * @param[in] model Binary file contains trained weights + * @param[in] config Text file contains network configuration + */ + CV_WRAP inline + TextRecognitionModel(CV_WRAP_FILE_PATH const std::string& model, CV_WRAP_FILE_PATH const std::string& config = "") + : TextRecognitionModel(readNet(model, config)) { /* nothing */ } + + /** + * @brief Set the decoding method of translating the network output into string + * @param[in] decodeType The decoding method of translating the network output into string, currently supported type: + * - `"CTC-greedy"` greedy decoding for the output of CTC-based methods + * - `"CTC-prefix-beam-search"` Prefix beam search decoding for the output of CTC-based methods + */ + CV_WRAP + TextRecognitionModel& setDecodeType(const std::string& decodeType); + + /** + * @brief Get the decoding method + * @return the decoding method + */ + CV_WRAP + const std::string& getDecodeType() const; + + /** + * @brief Set the decoding method options for `"CTC-prefix-beam-search"` decode usage + * @param[in] beamSize Beam size for search + * @param[in] vocPruneSize Parameter to optimize big vocabulary search, + * only take top @p vocPruneSize tokens in each search step, @p vocPruneSize <= 0 stands for disable this prune. + */ + CV_WRAP + TextRecognitionModel& setDecodeOptsCTCPrefixBeamSearch(int beamSize, int vocPruneSize = 0); + + /** + * @brief Set the vocabulary for recognition. + * @param[in] vocabulary the associated vocabulary of the network. + */ + CV_WRAP + TextRecognitionModel& setVocabulary(const std::vector& vocabulary); + + /** + * @brief Get the vocabulary for recognition. + * @return vocabulary the associated vocabulary + */ + CV_WRAP + const std::vector& getVocabulary() const; + + /** + * @brief Given the @p input frame, create input blob, run net and return recognition result + * @param[in] frame The input image + * @return The text recognition result + */ + CV_WRAP + std::string recognize(InputArray frame) const; + + /** + * @brief Given the @p input frame, create input blob, run net and return recognition result + * @param[in] frame The input image + * @param[in] roiRects List of text detection regions of interest (cv::Rect, CV_32SC4). ROIs is be cropped as the network inputs + * @param[out] results A set of text recognition results. + */ + CV_WRAP + void recognize(InputArray frame, InputArrayOfArrays roiRects, CV_OUT std::vector& results) const; +}; + + +/** @brief Base class for text detection networks + */ +class CV_EXPORTS_W_SIMPLE TextDetectionModel : public Model +{ +protected: + CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) + TextDetectionModel(); + +public: + + /** @brief Performs detection + * + * Given the input @p frame, prepare network input, run network inference, post-process network output and return result detections. + * + * Each result is quadrangle's 4 points in this order: + * - bottom-left + * - top-left + * - top-right + * - bottom-right + * + * Use cv::getPerspectiveTransform function to retrieve image region without perspective transformations. + * + * @note If DL model doesn't support that kind of output then result may be derived from detectTextRectangles() output. + * + * @param[in] frame The input image + * @param[out] detections array with detections' quadrangles (4 points per result) + * @param[out] confidences array with detection confidences + */ + CV_WRAP + void detect( + InputArray frame, + CV_OUT std::vector< std::vector >& detections, + CV_OUT std::vector& confidences + ) const; + + /** @overload */ + CV_WRAP + void detect( + InputArray frame, + CV_OUT std::vector< std::vector >& detections + ) const; + + /** @brief Performs detection + * + * Given the input @p frame, prepare network input, run network inference, post-process network output and return result detections. + * + * Each result is rotated rectangle. + * + * @note Result may be inaccurate in case of strong perspective transformations. + * + * @param[in] frame the input image + * @param[out] detections array with detections' RotationRect results + * @param[out] confidences array with detection confidences + */ + CV_WRAP + void detectTextRectangles( + InputArray frame, + CV_OUT std::vector& detections, + CV_OUT std::vector& confidences + ) const; + + /** @overload */ + CV_WRAP + void detectTextRectangles( + InputArray frame, + CV_OUT std::vector& detections + ) const; +}; + +/** @brief This class represents high-level API for text detection DL networks compatible with EAST model. + * + * Configurable parameters: + * - (float) confThreshold - used to filter boxes by confidences, default: 0.5f + * - (float) nmsThreshold - used in non maximum suppression, default: 0.0f + */ +class CV_EXPORTS_W_SIMPLE TextDetectionModel_EAST : public TextDetectionModel +{ +public: + CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) + TextDetectionModel_EAST(); + + /** + * @brief Create text detection algorithm from deep learning network + * @param[in] network Net object + */ + CV_WRAP TextDetectionModel_EAST(const Net& network); + + /** + * @brief Create text detection model from network represented in one of the supported formats. + * An order of @p model and @p config arguments does not matter. + * @param[in] model Binary file contains trained weights. + * @param[in] config Text file contains network configuration. + */ + CV_WRAP inline + TextDetectionModel_EAST(CV_WRAP_FILE_PATH const std::string& model, CV_WRAP_FILE_PATH const std::string& config = "") + : TextDetectionModel_EAST(readNet(model, config)) { /* nothing */ } + + /** + * @brief Set the detection confidence threshold + * @param[in] confThreshold A threshold used to filter boxes by confidences + */ + CV_WRAP + TextDetectionModel_EAST& setConfidenceThreshold(float confThreshold); + + /** + * @brief Get the detection confidence threshold + */ + CV_WRAP + float getConfidenceThreshold() const; + + /** + * @brief Set the detection NMS filter threshold + * @param[in] nmsThreshold A threshold used in non maximum suppression + */ + CV_WRAP + TextDetectionModel_EAST& setNMSThreshold(float nmsThreshold); + + /** + * @brief Get the detection confidence threshold + */ + CV_WRAP + float getNMSThreshold() const; +}; + +/** @brief This class represents high-level API for text detection DL networks compatible with DB model. + * + * Related publications: @cite liao2020real + * Paper: https://arxiv.org/abs/1911.08947 + * For more information about the hyper-parameters setting, please refer to https://github.com/MhLiao/DB + * + * Configurable parameters: + * - (float) binaryThreshold - The threshold of the binary map. It is usually set to 0.3. + * - (float) polygonThreshold - The threshold of text polygons. It is usually set to 0.5, 0.6, and 0.7. Default is 0.5f + * - (double) unclipRatio - The unclip ratio of the detected text region, which determines the output size. It is usually set to 2.0. + * - (int) maxCandidates - The max number of the output results. + */ +class CV_EXPORTS_W_SIMPLE TextDetectionModel_DB : public TextDetectionModel +{ +public: + CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) + TextDetectionModel_DB(); + + /** + * @brief Create text detection algorithm from deep learning network. + * @param[in] network Net object. + */ + CV_WRAP TextDetectionModel_DB(const Net& network); + + /** + * @brief Create text detection model from network represented in one of the supported formats. + * An order of @p model and @p config arguments does not matter. + * @param[in] model Binary file contains trained weights. + * @param[in] config Text file contains network configuration. + */ + CV_WRAP inline + TextDetectionModel_DB(CV_WRAP_FILE_PATH const std::string& model, CV_WRAP_FILE_PATH const std::string& config = "") + : TextDetectionModel_DB(readNet(model, config)) { /* nothing */ } + + CV_WRAP TextDetectionModel_DB& setBinaryThreshold(float binaryThreshold); + CV_WRAP float getBinaryThreshold() const; + + CV_WRAP TextDetectionModel_DB& setPolygonThreshold(float polygonThreshold); + CV_WRAP float getPolygonThreshold() const; + + CV_WRAP TextDetectionModel_DB& setUnclipRatio(double unclipRatio); + CV_WRAP double getUnclipRatio() const; + + CV_WRAP TextDetectionModel_DB& setMaxCandidates(int maxCandidates); + CV_WRAP int getMaxCandidates() const; +}; + +//! @} +CV__DNN_INLINE_NS_END +} +} + +#include +#include + +/// @deprecated Include this header directly from application. Automatic inclusion will be removed +#include + +#endif /* OPENCV_DNN_DNN_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/dnn/dnn.inl.hpp b/3rdParty/opencv-4.11.0/opencv2/dnn/dnn.inl.hpp index 8312a418f3..27ff5bd7fd 100644 --- a/3rdParty/opencv-4.11.0/opencv2/dnn/dnn.inl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/dnn/dnn.inl.hpp @@ -1,412 +1,412 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_DNN_DNN_INL_HPP -#define OPENCV_DNN_DNN_INL_HPP - -#include - -namespace cv { -namespace dnn { -CV__DNN_INLINE_NS_BEGIN - -template -DictValue DictValue::arrayInt(TypeIter begin, int size) -{ - DictValue res(Param::INT, new AutoBuffer(size)); - for (int j = 0; j < size; begin++, j++) - (*res.pi)[j] = *begin; - return res; -} - -template -DictValue DictValue::arrayReal(TypeIter begin, int size) -{ - DictValue res(Param::REAL, new AutoBuffer(size)); - for (int j = 0; j < size; begin++, j++) - (*res.pd)[j] = *begin; - return res; -} - -template -DictValue DictValue::arrayString(TypeIter begin, int size) -{ - DictValue res(Param::STRING, new AutoBuffer(size)); - for (int j = 0; j < size; begin++, j++) - (*res.ps)[j] = *begin; - return res; -} - -template<> -inline DictValue DictValue::get(int idx) const -{ - CV_Assert(idx == -1); - return *this; -} - -template<> -inline int64 DictValue::get(int idx) const -{ - CV_Assert((idx == -1 && size() == 1) || (idx >= 0 && idx < size())); - idx = (idx == -1) ? 0 : idx; - - if (type == Param::INT) - { - return (*pi)[idx]; - } - else if (type == Param::REAL) - { - double doubleValue = (*pd)[idx]; - - double fracpart, intpart; - fracpart = std::modf(doubleValue, &intpart); - CV_Assert(fracpart == 0.0); - - return (int64)doubleValue; - } - else if (type == Param::STRING) - { - return std::atoi((*ps)[idx].c_str()); - } - else - { - CV_Assert(isInt() || isReal() || isString()); - return 0; - } -} - -template<> -inline int DictValue::get(int idx) const -{ - return (int)get(idx); -} - -inline int DictValue::getIntValue(int idx) const -{ - return (int)get(idx); -} - -template<> -inline unsigned DictValue::get(int idx) const -{ - return (unsigned)get(idx); -} - -template<> -inline bool DictValue::get(int idx) const -{ - return (get(idx) != 0); -} - -template<> -inline double DictValue::get(int idx) const -{ - CV_Assert((idx == -1 && size() == 1) || (idx >= 0 && idx < size())); - idx = (idx == -1) ? 0 : idx; - - if (type == Param::REAL) - { - return (*pd)[idx]; - } - else if (type == Param::INT) - { - return (double)(*pi)[idx]; - } - else if (type == Param::STRING) - { - return std::atof((*ps)[idx].c_str()); - } - else - { - CV_Assert(isReal() || isInt() || isString()); - return 0; - } -} - -inline double DictValue::getRealValue(int idx) const -{ - return get(idx); -} - -template<> -inline float DictValue::get(int idx) const -{ - return (float)get(idx); -} - -template<> -inline String DictValue::get(int idx) const -{ - CV_Assert(isString()); - CV_Assert((idx == -1 && ps->size() == 1) || (idx >= 0 && idx < (int)ps->size())); - return (*ps)[(idx == -1) ? 0 : idx]; -} - - -inline String DictValue::getStringValue(int idx) const -{ - return get(idx); -} - -inline void DictValue::release() -{ - switch (type) - { - case Param::INT: - delete pi; - break; - case Param::STRING: - delete ps; - break; - case Param::REAL: - delete pd; - break; - case Param::BOOLEAN: - case Param::MAT: - case Param::MAT_VECTOR: - case Param::ALGORITHM: - case Param::FLOAT: - case Param::UNSIGNED_INT: - case Param::UINT64: - case Param::UCHAR: - case Param::SCALAR: - break; // unhandled - } -} - -inline DictValue::~DictValue() -{ - release(); -} - -inline DictValue & DictValue::operator=(const DictValue &r) -{ - if (&r == this) - return *this; - - if (r.type == Param::INT) - { - AutoBuffer *tmp = new AutoBuffer(*r.pi); - release(); - pi = tmp; - } - else if (r.type == Param::STRING) - { - AutoBuffer *tmp = new AutoBuffer(*r.ps); - release(); - ps = tmp; - } - else if (r.type == Param::REAL) - { - AutoBuffer *tmp = new AutoBuffer(*r.pd); - release(); - pd = tmp; - } - - type = r.type; - - return *this; -} - -inline DictValue::DictValue(const DictValue &r) - : pv(NULL) -{ - type = r.type; - - if (r.type == Param::INT) - pi = new AutoBuffer(*r.pi); - else if (r.type == Param::STRING) - ps = new AutoBuffer(*r.ps); - else if (r.type == Param::REAL) - pd = new AutoBuffer(*r.pd); -} - -inline bool DictValue::isString() const -{ - return (type == Param::STRING); -} - -inline bool DictValue::isInt() const -{ - return (type == Param::INT); -} - -inline bool DictValue::isReal() const -{ - return (type == Param::REAL || type == Param::INT); -} - -inline int DictValue::size() const -{ - switch (type) - { - case Param::INT: - return (int)pi->size(); - case Param::STRING: - return (int)ps->size(); - case Param::REAL: - return (int)pd->size(); - case Param::BOOLEAN: - case Param::MAT: - case Param::MAT_VECTOR: - case Param::ALGORITHM: - case Param::FLOAT: - case Param::UNSIGNED_INT: - case Param::UINT64: - case Param::UCHAR: - case Param::SCALAR: - break; // unhandled - } - CV_Error_(Error::StsInternal, ("Unhandled type (%d)", static_cast(type))); -} - -inline std::ostream &operator<<(std::ostream &stream, const DictValue &dictv) -{ - int i; - - if (dictv.isInt()) - { - for (i = 0; i < dictv.size() - 1; i++) - stream << dictv.get(i) << ", "; - stream << dictv.get(i); - } - else if (dictv.isReal()) - { - for (i = 0; i < dictv.size() - 1; i++) - stream << dictv.get(i) << ", "; - stream << dictv.get(i); - } - else if (dictv.isString()) - { - for (i = 0; i < dictv.size() - 1; i++) - stream << "\"" << dictv.get(i) << "\", "; - stream << dictv.get(i); - } - - return stream; -} - -///////////////////////////////////////////////////////////////// - -inline bool Dict::has(const String &key) const -{ - return dict.count(key) != 0; -} - -inline DictValue *Dict::ptr(const String &key) -{ - _Dict::iterator i = dict.find(key); - return (i == dict.end()) ? NULL : &i->second; -} - -inline const DictValue *Dict::ptr(const String &key) const -{ - _Dict::const_iterator i = dict.find(key); - return (i == dict.end()) ? NULL : &i->second; -} - -inline const DictValue &Dict::get(const String &key) const -{ - _Dict::const_iterator i = dict.find(key); - if (i == dict.end()) - CV_Error(Error::StsObjectNotFound, "Required argument \"" + key + "\" not found into dictionary"); - return i->second; -} - -template -inline T Dict::get(const String &key) const -{ - return this->get(key).get(); -} - -template -inline T Dict::get(const String &key, const T &defaultValue) const -{ - _Dict::const_iterator i = dict.find(key); - - if (i != dict.end()) - return i->second.get(); - else - return defaultValue; -} - -template -inline const T &Dict::set(const String &key, const T &value) -{ - _Dict::iterator i = dict.find(key); - - if (i != dict.end()) - i->second = DictValue(value); - else - dict.insert(std::make_pair(key, DictValue(value))); - - return value; -} - -inline void Dict::erase(const String &key) -{ - dict.erase(key); -} - -inline std::ostream &operator<<(std::ostream &stream, const Dict &dict) -{ - Dict::_Dict::const_iterator it; - for (it = dict.dict.begin(); it != dict.dict.end(); it++) - stream << it->first << " : " << it->second << "\n"; - - return stream; -} - -inline std::map::const_iterator Dict::begin() const -{ - return dict.begin(); -} - -inline std::map::const_iterator Dict::end() const -{ - return dict.end(); -} - -CV__DNN_INLINE_NS_END -} -} - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_DNN_DNN_INL_HPP +#define OPENCV_DNN_DNN_INL_HPP + +#include + +namespace cv { +namespace dnn { +CV__DNN_INLINE_NS_BEGIN + +template +DictValue DictValue::arrayInt(TypeIter begin, int size) +{ + DictValue res(Param::INT, new AutoBuffer(size)); + for (int j = 0; j < size; begin++, j++) + (*res.pi)[j] = *begin; + return res; +} + +template +DictValue DictValue::arrayReal(TypeIter begin, int size) +{ + DictValue res(Param::REAL, new AutoBuffer(size)); + for (int j = 0; j < size; begin++, j++) + (*res.pd)[j] = *begin; + return res; +} + +template +DictValue DictValue::arrayString(TypeIter begin, int size) +{ + DictValue res(Param::STRING, new AutoBuffer(size)); + for (int j = 0; j < size; begin++, j++) + (*res.ps)[j] = *begin; + return res; +} + +template<> +inline DictValue DictValue::get(int idx) const +{ + CV_Assert(idx == -1); + return *this; +} + +template<> +inline int64 DictValue::get(int idx) const +{ + CV_Assert((idx == -1 && size() == 1) || (idx >= 0 && idx < size())); + idx = (idx == -1) ? 0 : idx; + + if (type == Param::INT) + { + return (*pi)[idx]; + } + else if (type == Param::REAL) + { + double doubleValue = (*pd)[idx]; + + double fracpart, intpart; + fracpart = std::modf(doubleValue, &intpart); + CV_Assert(fracpart == 0.0); + + return (int64)doubleValue; + } + else if (type == Param::STRING) + { + return std::atoi((*ps)[idx].c_str()); + } + else + { + CV_Assert(isInt() || isReal() || isString()); + return 0; + } +} + +template<> +inline int DictValue::get(int idx) const +{ + return (int)get(idx); +} + +inline int DictValue::getIntValue(int idx) const +{ + return (int)get(idx); +} + +template<> +inline unsigned DictValue::get(int idx) const +{ + return (unsigned)get(idx); +} + +template<> +inline bool DictValue::get(int idx) const +{ + return (get(idx) != 0); +} + +template<> +inline double DictValue::get(int idx) const +{ + CV_Assert((idx == -1 && size() == 1) || (idx >= 0 && idx < size())); + idx = (idx == -1) ? 0 : idx; + + if (type == Param::REAL) + { + return (*pd)[idx]; + } + else if (type == Param::INT) + { + return (double)(*pi)[idx]; + } + else if (type == Param::STRING) + { + return std::atof((*ps)[idx].c_str()); + } + else + { + CV_Assert(isReal() || isInt() || isString()); + return 0; + } +} + +inline double DictValue::getRealValue(int idx) const +{ + return get(idx); +} + +template<> +inline float DictValue::get(int idx) const +{ + return (float)get(idx); +} + +template<> +inline String DictValue::get(int idx) const +{ + CV_Assert(isString()); + CV_Assert((idx == -1 && ps->size() == 1) || (idx >= 0 && idx < (int)ps->size())); + return (*ps)[(idx == -1) ? 0 : idx]; +} + + +inline String DictValue::getStringValue(int idx) const +{ + return get(idx); +} + +inline void DictValue::release() +{ + switch (type) + { + case Param::INT: + delete pi; + break; + case Param::STRING: + delete ps; + break; + case Param::REAL: + delete pd; + break; + case Param::BOOLEAN: + case Param::MAT: + case Param::MAT_VECTOR: + case Param::ALGORITHM: + case Param::FLOAT: + case Param::UNSIGNED_INT: + case Param::UINT64: + case Param::UCHAR: + case Param::SCALAR: + break; // unhandled + } +} + +inline DictValue::~DictValue() +{ + release(); +} + +inline DictValue & DictValue::operator=(const DictValue &r) +{ + if (&r == this) + return *this; + + if (r.type == Param::INT) + { + AutoBuffer *tmp = new AutoBuffer(*r.pi); + release(); + pi = tmp; + } + else if (r.type == Param::STRING) + { + AutoBuffer *tmp = new AutoBuffer(*r.ps); + release(); + ps = tmp; + } + else if (r.type == Param::REAL) + { + AutoBuffer *tmp = new AutoBuffer(*r.pd); + release(); + pd = tmp; + } + + type = r.type; + + return *this; +} + +inline DictValue::DictValue(const DictValue &r) + : pv(NULL) +{ + type = r.type; + + if (r.type == Param::INT) + pi = new AutoBuffer(*r.pi); + else if (r.type == Param::STRING) + ps = new AutoBuffer(*r.ps); + else if (r.type == Param::REAL) + pd = new AutoBuffer(*r.pd); +} + +inline bool DictValue::isString() const +{ + return (type == Param::STRING); +} + +inline bool DictValue::isInt() const +{ + return (type == Param::INT); +} + +inline bool DictValue::isReal() const +{ + return (type == Param::REAL || type == Param::INT); +} + +inline int DictValue::size() const +{ + switch (type) + { + case Param::INT: + return (int)pi->size(); + case Param::STRING: + return (int)ps->size(); + case Param::REAL: + return (int)pd->size(); + case Param::BOOLEAN: + case Param::MAT: + case Param::MAT_VECTOR: + case Param::ALGORITHM: + case Param::FLOAT: + case Param::UNSIGNED_INT: + case Param::UINT64: + case Param::UCHAR: + case Param::SCALAR: + break; // unhandled + } + CV_Error_(Error::StsInternal, ("Unhandled type (%d)", static_cast(type))); +} + +inline std::ostream &operator<<(std::ostream &stream, const DictValue &dictv) +{ + int i; + + if (dictv.isInt()) + { + for (i = 0; i < dictv.size() - 1; i++) + stream << dictv.get(i) << ", "; + stream << dictv.get(i); + } + else if (dictv.isReal()) + { + for (i = 0; i < dictv.size() - 1; i++) + stream << dictv.get(i) << ", "; + stream << dictv.get(i); + } + else if (dictv.isString()) + { + for (i = 0; i < dictv.size() - 1; i++) + stream << "\"" << dictv.get(i) << "\", "; + stream << dictv.get(i); + } + + return stream; +} + +///////////////////////////////////////////////////////////////// + +inline bool Dict::has(const String &key) const +{ + return dict.count(key) != 0; +} + +inline DictValue *Dict::ptr(const String &key) +{ + _Dict::iterator i = dict.find(key); + return (i == dict.end()) ? NULL : &i->second; +} + +inline const DictValue *Dict::ptr(const String &key) const +{ + _Dict::const_iterator i = dict.find(key); + return (i == dict.end()) ? NULL : &i->second; +} + +inline const DictValue &Dict::get(const String &key) const +{ + _Dict::const_iterator i = dict.find(key); + if (i == dict.end()) + CV_Error(Error::StsObjectNotFound, "Required argument \"" + key + "\" not found into dictionary"); + return i->second; +} + +template +inline T Dict::get(const String &key) const +{ + return this->get(key).get(); +} + +template +inline T Dict::get(const String &key, const T &defaultValue) const +{ + _Dict::const_iterator i = dict.find(key); + + if (i != dict.end()) + return i->second.get(); + else + return defaultValue; +} + +template +inline const T &Dict::set(const String &key, const T &value) +{ + _Dict::iterator i = dict.find(key); + + if (i != dict.end()) + i->second = DictValue(value); + else + dict.insert(std::make_pair(key, DictValue(value))); + + return value; +} + +inline void Dict::erase(const String &key) +{ + dict.erase(key); +} + +inline std::ostream &operator<<(std::ostream &stream, const Dict &dict) +{ + Dict::_Dict::const_iterator it; + for (it = dict.dict.begin(); it != dict.dict.end(); it++) + stream << it->first << " : " << it->second << "\n"; + + return stream; +} + +inline std::map::const_iterator Dict::begin() const +{ + return dict.begin(); +} + +inline std::map::const_iterator Dict::end() const +{ + return dict.end(); +} + +CV__DNN_INLINE_NS_END +} +} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/dnn/layer.details.hpp b/3rdParty/opencv-4.11.0/opencv2/dnn/layer.details.hpp index 1133da562e..deabe8839e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/dnn/layer.details.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/dnn/layer.details.hpp @@ -1,78 +1,78 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -#ifndef OPENCV_DNN_LAYER_DETAILS_HPP -#define OPENCV_DNN_LAYER_DETAILS_HPP - -#include - -namespace cv { -namespace dnn { -CV__DNN_INLINE_NS_BEGIN - -/** @brief Registers layer constructor in runtime. -* @param type string, containing type name of the layer. -* @param constructorFunc pointer to the function of type LayerRegister::Constructor, which creates the layer. -* @details This macros must be placed inside the function code. -*/ -#define CV_DNN_REGISTER_LAYER_FUNC(type, constructorFunc) \ - cv::dnn::LayerFactory::registerLayer(#type, constructorFunc); - -/** @brief Registers layer class in runtime. - * @param type string, containing type name of the layer. - * @param class C++ class, derived from Layer. - * @details This macros must be placed inside the function code. - */ -#define CV_DNN_REGISTER_LAYER_CLASS(type, class) \ - cv::dnn::LayerFactory::registerLayer(#type, cv::dnn::details::_layerDynamicRegisterer); - -/** @brief Registers layer constructor on module load time. -* @param type string, containing type name of the layer. -* @param constructorFunc pointer to the function of type LayerRegister::Constructor, which creates the layer. -* @details This macros must be placed outside the function code. -*/ -#define CV_DNN_REGISTER_LAYER_FUNC_STATIC(type, constructorFunc) \ -static cv::dnn::details::_LayerStaticRegisterer __LayerStaticRegisterer_##type(#type, constructorFunc); - -/** @brief Registers layer class on module load time. - * @param type string, containing type name of the layer. - * @param class C++ class, derived from Layer. - * @details This macros must be placed outside the function code. - */ -#define CV_DNN_REGISTER_LAYER_CLASS_STATIC(type, class) \ -Ptr __LayerStaticRegisterer_func_##type(LayerParams ¶ms) \ - { return Ptr(new class(params)); } \ -static cv::dnn::details::_LayerStaticRegisterer __LayerStaticRegisterer_##type(#type, __LayerStaticRegisterer_func_##type); - -namespace details { - -template -Ptr _layerDynamicRegisterer(LayerParams ¶ms) -{ - return Ptr(LayerClass::create(params)); -} - -//allows automatically register created layer on module load time -class _LayerStaticRegisterer -{ - String type; -public: - - _LayerStaticRegisterer(const String &layerType, LayerFactory::Constructor layerConstructor) - { - this->type = layerType; - LayerFactory::registerLayer(layerType, layerConstructor); - } - - ~_LayerStaticRegisterer() - { - LayerFactory::unregisterLayer(type); - } -}; - -} // namespace -CV__DNN_INLINE_NS_END -}} // namespace - -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +#ifndef OPENCV_DNN_LAYER_DETAILS_HPP +#define OPENCV_DNN_LAYER_DETAILS_HPP + +#include + +namespace cv { +namespace dnn { +CV__DNN_INLINE_NS_BEGIN + +/** @brief Registers layer constructor in runtime. +* @param type string, containing type name of the layer. +* @param constructorFunc pointer to the function of type LayerRegister::Constructor, which creates the layer. +* @details This macros must be placed inside the function code. +*/ +#define CV_DNN_REGISTER_LAYER_FUNC(type, constructorFunc) \ + cv::dnn::LayerFactory::registerLayer(#type, constructorFunc); + +/** @brief Registers layer class in runtime. + * @param type string, containing type name of the layer. + * @param class C++ class, derived from Layer. + * @details This macros must be placed inside the function code. + */ +#define CV_DNN_REGISTER_LAYER_CLASS(type, class) \ + cv::dnn::LayerFactory::registerLayer(#type, cv::dnn::details::_layerDynamicRegisterer); + +/** @brief Registers layer constructor on module load time. +* @param type string, containing type name of the layer. +* @param constructorFunc pointer to the function of type LayerRegister::Constructor, which creates the layer. +* @details This macros must be placed outside the function code. +*/ +#define CV_DNN_REGISTER_LAYER_FUNC_STATIC(type, constructorFunc) \ +static cv::dnn::details::_LayerStaticRegisterer __LayerStaticRegisterer_##type(#type, constructorFunc); + +/** @brief Registers layer class on module load time. + * @param type string, containing type name of the layer. + * @param class C++ class, derived from Layer. + * @details This macros must be placed outside the function code. + */ +#define CV_DNN_REGISTER_LAYER_CLASS_STATIC(type, class) \ +Ptr __LayerStaticRegisterer_func_##type(LayerParams ¶ms) \ + { return Ptr(new class(params)); } \ +static cv::dnn::details::_LayerStaticRegisterer __LayerStaticRegisterer_##type(#type, __LayerStaticRegisterer_func_##type); + +namespace details { + +template +Ptr _layerDynamicRegisterer(LayerParams ¶ms) +{ + return Ptr(LayerClass::create(params)); +} + +//allows automatically register created layer on module load time +class _LayerStaticRegisterer +{ + String type; +public: + + _LayerStaticRegisterer(const String &layerType, LayerFactory::Constructor layerConstructor) + { + this->type = layerType; + LayerFactory::registerLayer(layerType, layerConstructor); + } + + ~_LayerStaticRegisterer() + { + LayerFactory::unregisterLayer(type); + } +}; + +} // namespace +CV__DNN_INLINE_NS_END +}} // namespace + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/dnn/layer.hpp b/3rdParty/opencv-4.11.0/opencv2/dnn/layer.hpp index a4d167564d..44607ff9fa 100644 --- a/3rdParty/opencv-4.11.0/opencv2/dnn/layer.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/dnn/layer.hpp @@ -1,88 +1,88 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_DNN_LAYER_HPP -#define OPENCV_DNN_LAYER_HPP -#include - -namespace cv { -namespace dnn { -CV__DNN_INLINE_NS_BEGIN -//! @addtogroup dnn -//! @{ -//! -//! @defgroup dnnLayerFactory Utilities for New Layers Registration -//! @{ - -/** @brief %Layer factory allows to create instances of registered layers. */ -class CV_EXPORTS LayerFactory -{ -public: - - //! Each Layer class must provide this function to the factory - typedef Ptr(*Constructor)(LayerParams ¶ms); - - //! Registers the layer class with typename @p type and specified @p constructor. Thread-safe. - static void registerLayer(const String &type, Constructor constructor); - - //! Unregisters registered layer with specified type name. Thread-safe. - static void unregisterLayer(const String &type); - - //! Check if layer is registered. - static bool isLayerRegistered(const std::string& type); - - /** @brief Creates instance of registered layer. - * @param type type name of creating layer. - * @param params parameters which will be used for layer initialization. - * @note Thread-safe. - */ - static Ptr createLayerInstance(const String &type, LayerParams& params); - -private: - LayerFactory(); -}; - -//! @} -//! @} -CV__DNN_INLINE_NS_END -} -} -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_DNN_LAYER_HPP +#define OPENCV_DNN_LAYER_HPP +#include + +namespace cv { +namespace dnn { +CV__DNN_INLINE_NS_BEGIN +//! @addtogroup dnn +//! @{ +//! +//! @defgroup dnnLayerFactory Utilities for New Layers Registration +//! @{ + +/** @brief %Layer factory allows to create instances of registered layers. */ +class CV_EXPORTS LayerFactory +{ +public: + + //! Each Layer class must provide this function to the factory + typedef Ptr(*Constructor)(LayerParams ¶ms); + + //! Registers the layer class with typename @p type and specified @p constructor. Thread-safe. + static void registerLayer(const String &type, Constructor constructor); + + //! Unregisters registered layer with specified type name. Thread-safe. + static void unregisterLayer(const String &type); + + //! Check if layer is registered. + static bool isLayerRegistered(const std::string& type); + + /** @brief Creates instance of registered layer. + * @param type type name of creating layer. + * @param params parameters which will be used for layer initialization. + * @note Thread-safe. + */ + static Ptr createLayerInstance(const String &type, LayerParams& params); + +private: + LayerFactory(); +}; + +//! @} +//! @} +CV__DNN_INLINE_NS_END +} +} +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/dnn/shape_utils.hpp b/3rdParty/opencv-4.11.0/opencv2/dnn/shape_utils.hpp index 0ad8797ddd..5391017440 100644 --- a/3rdParty/opencv-4.11.0/opencv2/dnn/shape_utils.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/dnn/shape_utils.hpp @@ -1,290 +1,290 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_DNN_DNN_SHAPE_UTILS_HPP -#define OPENCV_DNN_DNN_SHAPE_UTILS_HPP - -#include -#include // CV_MAX_DIM -#include -#include -#include - -namespace cv { -namespace dnn { -CV__DNN_INLINE_NS_BEGIN - -//Slicing - -struct _Range : public cv::Range -{ - _Range(const Range &r) : cv::Range(r) {} - _Range(int start_, int size_ = 1) : cv::Range(start_, start_ + size_) {} -}; - -static inline Mat slice(const Mat &m, const _Range &r0) -{ - Range ranges[CV_MAX_DIM]; - for (int i = 1; i < m.dims; i++) - ranges[i] = Range::all(); - ranges[0] = r0; - return m(&ranges[0]); -} - -static inline Mat slice(const Mat &m, const _Range &r0, const _Range &r1) -{ - CV_Assert(m.dims >= 2); - Range ranges[CV_MAX_DIM]; - for (int i = 2; i < m.dims; i++) - ranges[i] = Range::all(); - ranges[0] = r0; - ranges[1] = r1; - return m(&ranges[0]); -} - -static inline Mat slice(const Mat &m, const _Range &r0, const _Range &r1, const _Range &r2) -{ - CV_Assert(m.dims >= 3); - Range ranges[CV_MAX_DIM]; - for (int i = 3; i < m.dims; i++) - ranges[i] = Range::all(); - ranges[0] = r0; - ranges[1] = r1; - ranges[2] = r2; - return m(&ranges[0]); -} - -static inline Mat slice(const Mat &m, const _Range &r0, const _Range &r1, const _Range &r2, const _Range &r3) -{ - CV_Assert(m.dims >= 4); - Range ranges[CV_MAX_DIM]; - for (int i = 4; i < m.dims; i++) - ranges[i] = Range::all(); - ranges[0] = r0; - ranges[1] = r1; - ranges[2] = r2; - ranges[3] = r3; - return m(&ranges[0]); -} - -static inline Mat getPlane(const Mat &m, int n, int cn) -{ - CV_Assert(m.dims > 2); - int sz[CV_MAX_DIM]; - for(int i = 2; i < m.dims; i++) - { - sz[i-2] = m.size.p[i]; - } - return Mat(m.dims - 2, sz, m.type(), (void*)m.ptr(n, cn)); -} - -static inline MatShape shape(const int* dims, const int n) -{ - MatShape shape; - shape.assign(dims, dims + n); - return shape; -} - -static inline MatShape shape(const Mat& mat) -{ - return shape(mat.size.p, mat.dims); -} - -static inline MatShape shape(const MatSize& sz) -{ - return shape(sz.p, sz.dims()); -} - -static inline MatShape shape(const UMat& mat) -{ - return shape(mat.size.p, mat.dims); -} - -#if 0 // issues with MatExpr wrapped into InputArray -static inline -MatShape shape(InputArray input) -{ - int sz[CV_MAX_DIM]; - int ndims = input.sizend(sz); - return shape(sz, ndims); -} -#endif - -namespace {inline bool is_neg(int i) { return i < 0; }} - -static inline MatShape shape(int a0, int a1=-1, int a2=-1, int a3=-1) -{ - int dims[] = {a0, a1, a2, a3}; - MatShape s = shape(dims, 4); - s.erase(std::remove_if(s.begin(), s.end(), is_neg), s.end()); - return s; -} - -static inline int total(const MatShape& shape, int start = -1, int end = -1) -{ - if (shape.empty()) - return 0; - - int dims = (int)shape.size(); - - if (start == -1) start = 0; - if (end == -1) end = dims; - - CV_CheckLE(0, start, ""); - CV_CheckLE(start, end, ""); - CV_CheckLE(end, dims, ""); - - int elems = 1; - for (int i = start; i < end; i++) - { - elems *= shape[i]; - } - return elems; -} - -// TODO: rename to countDimsElements() -static inline int total(const Mat& mat, int start = -1, int end = -1) -{ - if (mat.empty()) - return 0; - - int dims = mat.dims; - - if (start == -1) start = 0; - if (end == -1) end = dims; - - CV_CheckLE(0, start, ""); - CV_CheckLE(start, end, ""); - CV_CheckLE(end, dims, ""); - - int elems = 1; - for (int i = start; i < end; i++) - { - elems *= mat.size[i]; - } - return elems; -} - -static inline MatShape concat(const MatShape& a, const MatShape& b) -{ - MatShape c = a; - c.insert(c.end(), b.begin(), b.end()); - - return c; -} - -template -static inline std::string toString(const std::vector<_Tp>& shape, const String& name = "") -{ - std::ostringstream ss; - if (!name.empty()) - ss << name << ' '; - ss << '['; - for(size_t i = 0, n = shape.size(); i < n; ++i) - ss << ' ' << shape[i]; - ss << " ]"; - return ss.str(); -} - -template -static inline void print(const std::vector<_Tp>& shape, const String& name = "") -{ - std::cout << toString(shape, name) << std::endl; -} -template -static inline std::ostream& operator<<(std::ostream &out, const std::vector<_Tp>& shape) -{ - out << toString(shape); - return out; -} - -/// @brief Converts axis from `[-dims; dims)` (similar to Python's slice notation) to `[0; dims)` range. -static inline -int normalize_axis(int axis, int dims) -{ - CV_Check(axis, axis >= -dims && axis < dims, ""); - axis = (axis < 0) ? (dims + axis) : axis; - CV_DbgCheck(axis, axis >= 0 && axis < dims, ""); - return axis; -} - -static inline -int normalize_axis(int axis, const MatShape& shape) -{ - return normalize_axis(axis, (int)shape.size()); -} - -static inline -Range normalize_axis_range(const Range& r, int axisSize) -{ - if (r == Range::all()) - return Range(0, axisSize); - CV_CheckGE(r.start, 0, ""); - Range clamped(r.start, - r.end > 0 ? std::min(r.end, axisSize) : axisSize + r.end + 1); - CV_DbgCheckGE(clamped.start, 0, ""); - CV_CheckLT(clamped.start, clamped.end, ""); - CV_CheckLE(clamped.end, axisSize, ""); - return clamped; -} - -static inline -bool isAllOnes(const MatShape &inputShape, int startPos, int endPos) -{ - CV_Assert(!inputShape.empty()); - - CV_CheckGE((int) inputShape.size(), startPos, ""); - CV_CheckGE(startPos, 0, ""); - CV_CheckLE(startPos, endPos, ""); - CV_CheckLE((size_t)endPos, inputShape.size(), ""); - - for (size_t i = startPos; i < endPos; i++) - { - if (inputShape[i] != 1) - return false; - } - return true; -} - -CV__DNN_INLINE_NS_END -} -} -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_DNN_DNN_SHAPE_UTILS_HPP +#define OPENCV_DNN_DNN_SHAPE_UTILS_HPP + +#include +#include // CV_MAX_DIM +#include +#include +#include + +namespace cv { +namespace dnn { +CV__DNN_INLINE_NS_BEGIN + +//Slicing + +struct _Range : public cv::Range +{ + _Range(const Range &r) : cv::Range(r) {} + _Range(int start_, int size_ = 1) : cv::Range(start_, start_ + size_) {} +}; + +static inline Mat slice(const Mat &m, const _Range &r0) +{ + Range ranges[CV_MAX_DIM]; + for (int i = 1; i < m.dims; i++) + ranges[i] = Range::all(); + ranges[0] = r0; + return m(&ranges[0]); +} + +static inline Mat slice(const Mat &m, const _Range &r0, const _Range &r1) +{ + CV_Assert(m.dims >= 2); + Range ranges[CV_MAX_DIM]; + for (int i = 2; i < m.dims; i++) + ranges[i] = Range::all(); + ranges[0] = r0; + ranges[1] = r1; + return m(&ranges[0]); +} + +static inline Mat slice(const Mat &m, const _Range &r0, const _Range &r1, const _Range &r2) +{ + CV_Assert(m.dims >= 3); + Range ranges[CV_MAX_DIM]; + for (int i = 3; i < m.dims; i++) + ranges[i] = Range::all(); + ranges[0] = r0; + ranges[1] = r1; + ranges[2] = r2; + return m(&ranges[0]); +} + +static inline Mat slice(const Mat &m, const _Range &r0, const _Range &r1, const _Range &r2, const _Range &r3) +{ + CV_Assert(m.dims >= 4); + Range ranges[CV_MAX_DIM]; + for (int i = 4; i < m.dims; i++) + ranges[i] = Range::all(); + ranges[0] = r0; + ranges[1] = r1; + ranges[2] = r2; + ranges[3] = r3; + return m(&ranges[0]); +} + +static inline Mat getPlane(const Mat &m, int n, int cn) +{ + CV_Assert(m.dims > 2); + int sz[CV_MAX_DIM]; + for(int i = 2; i < m.dims; i++) + { + sz[i-2] = m.size.p[i]; + } + return Mat(m.dims - 2, sz, m.type(), (void*)m.ptr(n, cn)); +} + +static inline MatShape shape(const int* dims, const int n) +{ + MatShape shape; + shape.assign(dims, dims + n); + return shape; +} + +static inline MatShape shape(const Mat& mat) +{ + return shape(mat.size.p, mat.dims); +} + +static inline MatShape shape(const MatSize& sz) +{ + return shape(sz.p, sz.dims()); +} + +static inline MatShape shape(const UMat& mat) +{ + return shape(mat.size.p, mat.dims); +} + +#if 0 // issues with MatExpr wrapped into InputArray +static inline +MatShape shape(InputArray input) +{ + int sz[CV_MAX_DIM]; + int ndims = input.sizend(sz); + return shape(sz, ndims); +} +#endif + +namespace {inline bool is_neg(int i) { return i < 0; }} + +static inline MatShape shape(int a0, int a1=-1, int a2=-1, int a3=-1) +{ + int dims[] = {a0, a1, a2, a3}; + MatShape s = shape(dims, 4); + s.erase(std::remove_if(s.begin(), s.end(), is_neg), s.end()); + return s; +} + +static inline int total(const MatShape& shape, int start = -1, int end = -1) +{ + if (shape.empty()) + return 0; + + int dims = (int)shape.size(); + + if (start == -1) start = 0; + if (end == -1) end = dims; + + CV_CheckLE(0, start, ""); + CV_CheckLE(start, end, ""); + CV_CheckLE(end, dims, ""); + + int elems = 1; + for (int i = start; i < end; i++) + { + elems *= shape[i]; + } + return elems; +} + +// TODO: rename to countDimsElements() +static inline int total(const Mat& mat, int start = -1, int end = -1) +{ + if (mat.empty()) + return 0; + + int dims = mat.dims; + + if (start == -1) start = 0; + if (end == -1) end = dims; + + CV_CheckLE(0, start, ""); + CV_CheckLE(start, end, ""); + CV_CheckLE(end, dims, ""); + + int elems = 1; + for (int i = start; i < end; i++) + { + elems *= mat.size[i]; + } + return elems; +} + +static inline MatShape concat(const MatShape& a, const MatShape& b) +{ + MatShape c = a; + c.insert(c.end(), b.begin(), b.end()); + + return c; +} + +template +static inline std::string toString(const std::vector<_Tp>& shape, const String& name = "") +{ + std::ostringstream ss; + if (!name.empty()) + ss << name << ' '; + ss << '['; + for(size_t i = 0, n = shape.size(); i < n; ++i) + ss << ' ' << shape[i]; + ss << " ]"; + return ss.str(); +} + +template +static inline void print(const std::vector<_Tp>& shape, const String& name = "") +{ + std::cout << toString(shape, name) << std::endl; +} +template +static inline std::ostream& operator<<(std::ostream &out, const std::vector<_Tp>& shape) +{ + out << toString(shape); + return out; +} + +/// @brief Converts axis from `[-dims; dims)` (similar to Python's slice notation) to `[0; dims)` range. +static inline +int normalize_axis(int axis, int dims) +{ + CV_Check(axis, axis >= -dims && axis < dims, ""); + axis = (axis < 0) ? (dims + axis) : axis; + CV_DbgCheck(axis, axis >= 0 && axis < dims, ""); + return axis; +} + +static inline +int normalize_axis(int axis, const MatShape& shape) +{ + return normalize_axis(axis, (int)shape.size()); +} + +static inline +Range normalize_axis_range(const Range& r, int axisSize) +{ + if (r == Range::all()) + return Range(0, axisSize); + CV_CheckGE(r.start, 0, ""); + Range clamped(r.start, + r.end > 0 ? std::min(r.end, axisSize) : axisSize + r.end + 1); + CV_DbgCheckGE(clamped.start, 0, ""); + CV_CheckLT(clamped.start, clamped.end, ""); + CV_CheckLE(clamped.end, axisSize, ""); + return clamped; +} + +static inline +bool isAllOnes(const MatShape &inputShape, int startPos, int endPos) +{ + CV_Assert(!inputShape.empty()); + + CV_CheckGE((int) inputShape.size(), startPos, ""); + CV_CheckGE(startPos, 0, ""); + CV_CheckLE(startPos, endPos, ""); + CV_CheckLE((size_t)endPos, inputShape.size(), ""); + + for (size_t i = startPos; i < endPos; i++) + { + if (inputShape[i] != 1) + return false; + } + return true; +} + +CV__DNN_INLINE_NS_END +} +} +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/dnn/utils/debug_utils.hpp b/3rdParty/opencv-4.11.0/opencv2/dnn/utils/debug_utils.hpp index 71dd3ab8d6..fdce655e37 100644 --- a/3rdParty/opencv-4.11.0/opencv2/dnn/utils/debug_utils.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/dnn/utils/debug_utils.hpp @@ -1,24 +1,24 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_DNN_UTILS_DEBUG_UTILS_HPP -#define OPENCV_DNN_UTILS_DEBUG_UTILS_HPP - -#include "../dnn.hpp" - -namespace cv { namespace dnn { -CV__DNN_INLINE_NS_BEGIN - -/** - * @brief Skip model import after diagnostic run in readNet() functions. - * @param[in] skip Indicates whether to skip the import. - * - * This is an internal OpenCV function not intended for users. - */ -CV_EXPORTS void skipModelImport(bool skip); - -CV__DNN_INLINE_NS_END -}} // namespace - -#endif // OPENCV_DNN_UTILS_DEBUG_UTILS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_DNN_UTILS_DEBUG_UTILS_HPP +#define OPENCV_DNN_UTILS_DEBUG_UTILS_HPP + +#include "../dnn.hpp" + +namespace cv { namespace dnn { +CV__DNN_INLINE_NS_BEGIN + +/** + * @brief Skip model import after diagnostic run in readNet() functions. + * @param[in] skip Indicates whether to skip the import. + * + * This is an internal OpenCV function not intended for users. + */ +CV_EXPORTS void skipModelImport(bool skip); + +CV__DNN_INLINE_NS_END +}} // namespace + +#endif // OPENCV_DNN_UTILS_DEBUG_UTILS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/dnn/utils/inference_engine.hpp b/3rdParty/opencv-4.11.0/opencv2/dnn/utils/inference_engine.hpp index b81806ed5a..fba659671a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/dnn/utils/inference_engine.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/dnn/utils/inference_engine.hpp @@ -1,82 +1,82 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2019, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. - -#ifndef OPENCV_DNN_UTILS_INF_ENGINE_HPP -#define OPENCV_DNN_UTILS_INF_ENGINE_HPP - -#include "../dnn.hpp" - -namespace cv { namespace dnn { -CV__DNN_INLINE_NS_BEGIN - - -/* Values for 'OPENCV_DNN_BACKEND_INFERENCE_ENGINE_TYPE' parameter */ -/// @deprecated -#define CV_DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_API "NN_BUILDER" -/// @deprecated -#define CV_DNN_BACKEND_INFERENCE_ENGINE_NGRAPH "NGRAPH" - -/** @brief Returns Inference Engine internal backend API. - * - * See values of `CV_DNN_BACKEND_INFERENCE_ENGINE_*` macros. - * - * `OPENCV_DNN_BACKEND_INFERENCE_ENGINE_TYPE` runtime parameter (environment variable) is ignored since 4.6.0. - * - * @deprecated - */ -CV_EXPORTS_W cv::String getInferenceEngineBackendType(); - -/** @brief Specify Inference Engine internal backend API. - * - * See values of `CV_DNN_BACKEND_INFERENCE_ENGINE_*` macros. - * - * @returns previous value of internal backend API - * - * @deprecated - */ -CV_EXPORTS_W cv::String setInferenceEngineBackendType(const cv::String& newBackendType); - - -/** @brief Release a Myriad device (binded by OpenCV). - * - * Single Myriad device cannot be shared across multiple processes which uses - * Inference Engine's Myriad plugin. - */ -CV_EXPORTS_W void resetMyriadDevice(); - - -/* Values for 'OPENCV_DNN_IE_VPU_TYPE' parameter */ -#define CV_DNN_INFERENCE_ENGINE_VPU_TYPE_UNSPECIFIED "" -/// Intel(R) Movidius(TM) Neural Compute Stick, NCS (USB 03e7:2150), Myriad2 (https://software.intel.com/en-us/movidius-ncs) -#define CV_DNN_INFERENCE_ENGINE_VPU_TYPE_MYRIAD_2 "Myriad2" -/// Intel(R) Neural Compute Stick 2, NCS2 (USB 03e7:2485), MyriadX (https://software.intel.com/ru-ru/neural-compute-stick) -#define CV_DNN_INFERENCE_ENGINE_VPU_TYPE_MYRIAD_X "MyriadX" -#define CV_DNN_INFERENCE_ENGINE_CPU_TYPE_ARM_COMPUTE "ARM_COMPUTE" -#define CV_DNN_INFERENCE_ENGINE_CPU_TYPE_X86 "X86" - - -/** @brief Returns Inference Engine VPU type. - * - * See values of `CV_DNN_INFERENCE_ENGINE_VPU_TYPE_*` macros. - */ -CV_EXPORTS_W cv::String getInferenceEngineVPUType(); - -/** @brief Returns Inference Engine CPU type. - * - * Specify OpenVINO plugin: CPU or ARM. - */ -CV_EXPORTS_W cv::String getInferenceEngineCPUType(); - -/** @brief Release a HDDL plugin. - */ -CV_EXPORTS_W void releaseHDDLPlugin(); - - -CV__DNN_INLINE_NS_END -}} // namespace - -#endif // OPENCV_DNN_UTILS_INF_ENGINE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2019, Intel Corporation, all rights reserved. +// Third party copyrights are property of their respective owners. + +#ifndef OPENCV_DNN_UTILS_INF_ENGINE_HPP +#define OPENCV_DNN_UTILS_INF_ENGINE_HPP + +#include "../dnn.hpp" + +namespace cv { namespace dnn { +CV__DNN_INLINE_NS_BEGIN + + +/* Values for 'OPENCV_DNN_BACKEND_INFERENCE_ENGINE_TYPE' parameter */ +/// @deprecated +#define CV_DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_API "NN_BUILDER" +/// @deprecated +#define CV_DNN_BACKEND_INFERENCE_ENGINE_NGRAPH "NGRAPH" + +/** @brief Returns Inference Engine internal backend API. + * + * See values of `CV_DNN_BACKEND_INFERENCE_ENGINE_*` macros. + * + * `OPENCV_DNN_BACKEND_INFERENCE_ENGINE_TYPE` runtime parameter (environment variable) is ignored since 4.6.0. + * + * @deprecated + */ +CV_EXPORTS_W cv::String getInferenceEngineBackendType(); + +/** @brief Specify Inference Engine internal backend API. + * + * See values of `CV_DNN_BACKEND_INFERENCE_ENGINE_*` macros. + * + * @returns previous value of internal backend API + * + * @deprecated + */ +CV_EXPORTS_W cv::String setInferenceEngineBackendType(const cv::String& newBackendType); + + +/** @brief Release a Myriad device (binded by OpenCV). + * + * Single Myriad device cannot be shared across multiple processes which uses + * Inference Engine's Myriad plugin. + */ +CV_EXPORTS_W void resetMyriadDevice(); + + +/* Values for 'OPENCV_DNN_IE_VPU_TYPE' parameter */ +#define CV_DNN_INFERENCE_ENGINE_VPU_TYPE_UNSPECIFIED "" +/// Intel(R) Movidius(TM) Neural Compute Stick, NCS (USB 03e7:2150), Myriad2 (https://software.intel.com/en-us/movidius-ncs) +#define CV_DNN_INFERENCE_ENGINE_VPU_TYPE_MYRIAD_2 "Myriad2" +/// Intel(R) Neural Compute Stick 2, NCS2 (USB 03e7:2485), MyriadX (https://software.intel.com/ru-ru/neural-compute-stick) +#define CV_DNN_INFERENCE_ENGINE_VPU_TYPE_MYRIAD_X "MyriadX" +#define CV_DNN_INFERENCE_ENGINE_CPU_TYPE_ARM_COMPUTE "ARM_COMPUTE" +#define CV_DNN_INFERENCE_ENGINE_CPU_TYPE_X86 "X86" + + +/** @brief Returns Inference Engine VPU type. + * + * See values of `CV_DNN_INFERENCE_ENGINE_VPU_TYPE_*` macros. + */ +CV_EXPORTS_W cv::String getInferenceEngineVPUType(); + +/** @brief Returns Inference Engine CPU type. + * + * Specify OpenVINO plugin: CPU or ARM. + */ +CV_EXPORTS_W cv::String getInferenceEngineCPUType(); + +/** @brief Release a HDDL plugin. + */ +CV_EXPORTS_W void releaseHDDLPlugin(); + + +CV__DNN_INLINE_NS_END +}} // namespace + +#endif // OPENCV_DNN_UTILS_INF_ENGINE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/dnn/version.hpp b/3rdParty/opencv-4.11.0/opencv2/dnn/version.hpp index 5cf0870b44..a651e05826 100644 --- a/3rdParty/opencv-4.11.0/opencv2/dnn/version.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/dnn/version.hpp @@ -1,21 +1,21 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_DNN_VERSION_HPP -#define OPENCV_DNN_VERSION_HPP - -/// Use with major OpenCV version only. -#define OPENCV_DNN_API_VERSION 20241223 - -#if !defined CV_DOXYGEN && !defined CV_STATIC_ANALYSIS && !defined CV_DNN_DONT_ADD_INLINE_NS -#define CV__DNN_INLINE_NS __CV_CAT(dnn4_v, OPENCV_DNN_API_VERSION) -#define CV__DNN_INLINE_NS_BEGIN namespace CV__DNN_INLINE_NS { -#define CV__DNN_INLINE_NS_END } -namespace cv { namespace dnn { namespace CV__DNN_INLINE_NS { } using namespace CV__DNN_INLINE_NS; }} -#else -#define CV__DNN_INLINE_NS_BEGIN -#define CV__DNN_INLINE_NS_END -#endif - -#endif // OPENCV_DNN_VERSION_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_DNN_VERSION_HPP +#define OPENCV_DNN_VERSION_HPP + +/// Use with major OpenCV version only. +#define OPENCV_DNN_API_VERSION 20241223 + +#if !defined CV_DOXYGEN && !defined CV_STATIC_ANALYSIS && !defined CV_DNN_DONT_ADD_INLINE_NS +#define CV__DNN_INLINE_NS __CV_CAT(dnn4_v, OPENCV_DNN_API_VERSION) +#define CV__DNN_INLINE_NS_BEGIN namespace CV__DNN_INLINE_NS { +#define CV__DNN_INLINE_NS_END } +namespace cv { namespace dnn { namespace CV__DNN_INLINE_NS { } using namespace CV__DNN_INLINE_NS; }} +#else +#define CV__DNN_INLINE_NS_BEGIN +#define CV__DNN_INLINE_NS_END +#endif + +#endif // OPENCV_DNN_VERSION_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/features2d.hpp b/3rdParty/opencv-4.11.0/opencv2/features2d.hpp index b4c4dde712..43dcd02ee3 100644 --- a/3rdParty/opencv-4.11.0/opencv2/features2d.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/features2d.hpp @@ -1,1602 +1,1602 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_FEATURES_2D_HPP -#define OPENCV_FEATURES_2D_HPP - -#include "opencv2/opencv_modules.hpp" -#include "opencv2/core.hpp" - -#ifdef HAVE_OPENCV_FLANN -#include "opencv2/flann/miniflann.hpp" -#endif - -/** - @defgroup features2d 2D Features Framework - @{ - @defgroup features2d_main Feature Detection and Description - @defgroup features2d_match Descriptor Matchers - - Matchers of keypoint descriptors in OpenCV have wrappers with a common interface that enables - you to easily switch between different algorithms solving the same problem. This section is - devoted to matching descriptors that are represented as vectors in a multidimensional space. - All objects that implement vector descriptor matchers inherit the DescriptorMatcher interface. - - @defgroup features2d_draw Drawing Function of Keypoints and Matches - @defgroup features2d_category Object Categorization - - This section describes approaches based on local 2D features and used to categorize objects. - - @defgroup feature2d_hal Hardware Acceleration Layer - @{ - @defgroup features2d_hal_interface Interface - @} - @} - */ - -namespace cv -{ - -//! @addtogroup features2d_main -//! @{ - -// //! writes vector of keypoints to the file storage -// CV_EXPORTS void write(FileStorage& fs, const String& name, const std::vector& keypoints); -// //! reads vector of keypoints from the specified file storage node -// CV_EXPORTS void read(const FileNode& node, CV_OUT std::vector& keypoints); - -/** @brief A class filters a vector of keypoints. - - Because now it is difficult to provide a convenient interface for all usage scenarios of the - keypoints filter class, it has only several needed by now static methods. - */ -class CV_EXPORTS KeyPointsFilter -{ -public: - KeyPointsFilter(){} - - /* - * Remove keypoints within borderPixels of an image edge. - */ - static void runByImageBorder( std::vector& keypoints, Size imageSize, int borderSize ); - /* - * Remove keypoints of sizes out of range. - */ - static void runByKeypointSize( std::vector& keypoints, float minSize, - float maxSize=FLT_MAX ); - /* - * Remove keypoints from some image by mask for pixels of this image. - */ - static void runByPixelsMask( std::vector& keypoints, const Mat& mask ); - /* - * Remove objects from some image and a vector of points by mask for pixels of this image - */ - static void runByPixelsMask2VectorPoint(std::vector &keypoints, std::vector > &removeFrom, const Mat &mask); - /* - * Remove duplicated keypoints. - */ - static void removeDuplicated( std::vector& keypoints ); - /* - * Remove duplicated keypoints and sort the remaining keypoints - */ - static void removeDuplicatedSorted( std::vector& keypoints ); - - /* - * Retain the specified number of the best keypoints (according to the response) - */ - static void retainBest( std::vector& keypoints, int npoints ); -}; - - -/************************************ Base Classes ************************************/ - -/** @brief Abstract base class for 2D image feature detectors and descriptor extractors -*/ -#ifdef __EMSCRIPTEN__ -class CV_EXPORTS_W Feature2D : public Algorithm -#else -class CV_EXPORTS_W Feature2D : public virtual Algorithm -#endif -{ -public: - virtual ~Feature2D(); - - /** @brief Detects keypoints in an image (first variant) or image set (second variant). - - @param image Image. - @param keypoints The detected keypoints. In the second variant of the method keypoints[i] is a set - of keypoints detected in images[i] . - @param mask Mask specifying where to look for keypoints (optional). It must be a 8-bit integer - matrix with non-zero values in the region of interest. - */ - CV_WRAP virtual void detect( InputArray image, - CV_OUT std::vector& keypoints, - InputArray mask=noArray() ); - - /** @overload - @param images Image set. - @param keypoints The detected keypoints. In the second variant of the method keypoints[i] is a set - of keypoints detected in images[i] . - @param masks Masks for each input image specifying where to look for keypoints (optional). - masks[i] is a mask for images[i]. - */ - CV_WRAP virtual void detect( InputArrayOfArrays images, - CV_OUT std::vector >& keypoints, - InputArrayOfArrays masks=noArray() ); - - /** @brief Computes the descriptors for a set of keypoints detected in an image (first variant) or image set - (second variant). - - @param image Image. - @param keypoints Input collection of keypoints. Keypoints for which a descriptor cannot be - computed are removed. Sometimes new keypoints can be added, for example: SIFT duplicates keypoint - with several dominant orientations (for each orientation). - @param descriptors Computed descriptors. In the second variant of the method descriptors[i] are - descriptors computed for a keypoints[i]. Row j is the keypoints (or keypoints[i]) is the - descriptor for keypoint j-th keypoint. - */ - CV_WRAP virtual void compute( InputArray image, - CV_OUT CV_IN_OUT std::vector& keypoints, - OutputArray descriptors ); - - /** @overload - - @param images Image set. - @param keypoints Input collection of keypoints. Keypoints for which a descriptor cannot be - computed are removed. Sometimes new keypoints can be added, for example: SIFT duplicates keypoint - with several dominant orientations (for each orientation). - @param descriptors Computed descriptors. In the second variant of the method descriptors[i] are - descriptors computed for a keypoints[i]. Row j is the keypoints (or keypoints[i]) is the - descriptor for keypoint j-th keypoint. - */ - CV_WRAP virtual void compute( InputArrayOfArrays images, - CV_OUT CV_IN_OUT std::vector >& keypoints, - OutputArrayOfArrays descriptors ); - - /** Detects keypoints and computes the descriptors */ - CV_WRAP virtual void detectAndCompute( InputArray image, InputArray mask, - CV_OUT std::vector& keypoints, - OutputArray descriptors, - bool useProvidedKeypoints=false ); - - CV_WRAP virtual int descriptorSize() const; - CV_WRAP virtual int descriptorType() const; - CV_WRAP virtual int defaultNorm() const; - - CV_WRAP void write( const String& fileName ) const; - - CV_WRAP void read( const String& fileName ); - - virtual void write( FileStorage&) const CV_OVERRIDE; - - // see corresponding cv::Algorithm method - CV_WRAP virtual void read( const FileNode&) CV_OVERRIDE; - - //! Return true if detector object is empty - CV_WRAP virtual bool empty() const CV_OVERRIDE; - CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; - - // see corresponding cv::Algorithm method - CV_WRAP inline void write(FileStorage& fs, const String& name) const { Algorithm::write(fs, name); } -#if CV_VERSION_MAJOR < 5 - inline void write(const Ptr& fs, const String& name) const { CV_Assert(fs); Algorithm::write(*fs, name); } -#endif -}; - -/** Feature detectors in OpenCV have wrappers with a common interface that enables you to easily switch -between different algorithms solving the same problem. All objects that implement keypoint detectors -inherit the FeatureDetector interface. */ -typedef Feature2D FeatureDetector; - -/** Extractors of keypoint descriptors in OpenCV have wrappers with a common interface that enables you -to easily switch between different algorithms solving the same problem. This section is devoted to -computing descriptors represented as vectors in a multidimensional space. All objects that implement -the vector descriptor extractors inherit the DescriptorExtractor interface. - */ -typedef Feature2D DescriptorExtractor; - - -/** @brief Class for implementing the wrapper which makes detectors and extractors to be affine invariant, -described as ASIFT in @cite YM11 . -*/ -class CV_EXPORTS_W AffineFeature : public Feature2D -{ -public: - /** - @param backend The detector/extractor you want to use as backend. - @param maxTilt The highest power index of tilt factor. 5 is used in the paper as tilt sampling range n. - @param minTilt The lowest power index of tilt factor. 0 is used in the paper. - @param tiltStep Tilt sampling step \f$\delta_t\f$ in Algorithm 1 in the paper. - @param rotateStepBase Rotation sampling step factor b in Algorithm 1 in the paper. - */ - CV_WRAP static Ptr create(const Ptr& backend, - int maxTilt = 5, int minTilt = 0, float tiltStep = 1.4142135623730951f, float rotateStepBase = 72); - - CV_WRAP virtual void setViewParams(const std::vector& tilts, const std::vector& rolls) = 0; - CV_WRAP virtual void getViewParams(std::vector& tilts, std::vector& rolls) const = 0; - CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; -}; - -typedef AffineFeature AffineFeatureDetector; -typedef AffineFeature AffineDescriptorExtractor; - - -/** @brief Class for extracting keypoints and computing descriptors using the Scale Invariant Feature Transform -(SIFT) algorithm by D. Lowe @cite Lowe04 . -*/ -class CV_EXPORTS_W SIFT : public Feature2D -{ -public: - /** - @param nfeatures The number of best features to retain. The features are ranked by their scores - (measured in SIFT algorithm as the local contrast) - - @param nOctaveLayers The number of layers in each octave. 3 is the value used in D. Lowe paper. The - number of octaves is computed automatically from the image resolution. - - @param contrastThreshold The contrast threshold used to filter out weak features in semi-uniform - (low-contrast) regions. The larger the threshold, the less features are produced by the detector. - - @note The contrast threshold will be divided by nOctaveLayers when the filtering is applied. When - nOctaveLayers is set to default and if you want to use the value used in D. Lowe paper, 0.03, set - this argument to 0.09. - - @param edgeThreshold The threshold used to filter out edge-like features. Note that the its meaning - is different from the contrastThreshold, i.e. the larger the edgeThreshold, the less features are - filtered out (more features are retained). - - @param sigma The sigma of the Gaussian applied to the input image at the octave \#0. If your image - is captured with a weak camera with soft lenses, you might want to reduce the number. - - @param enable_precise_upscale Whether to enable precise upscaling in the scale pyramid, which maps - index \f$\texttt{x}\f$ to \f$\texttt{2x}\f$. This prevents localization bias. The option - is disabled by default. - */ - CV_WRAP static Ptr create(int nfeatures = 0, int nOctaveLayers = 3, - double contrastThreshold = 0.04, double edgeThreshold = 10, - double sigma = 1.6, bool enable_precise_upscale = false); - - /** @brief Create SIFT with specified descriptorType. - @param nfeatures The number of best features to retain. The features are ranked by their scores - (measured in SIFT algorithm as the local contrast) - - @param nOctaveLayers The number of layers in each octave. 3 is the value used in D. Lowe paper. The - number of octaves is computed automatically from the image resolution. - - @param contrastThreshold The contrast threshold used to filter out weak features in semi-uniform - (low-contrast) regions. The larger the threshold, the less features are produced by the detector. - - @note The contrast threshold will be divided by nOctaveLayers when the filtering is applied. When - nOctaveLayers is set to default and if you want to use the value used in D. Lowe paper, 0.03, set - this argument to 0.09. - - @param edgeThreshold The threshold used to filter out edge-like features. Note that the its meaning - is different from the contrastThreshold, i.e. the larger the edgeThreshold, the less features are - filtered out (more features are retained). - - @param sigma The sigma of the Gaussian applied to the input image at the octave \#0. If your image - is captured with a weak camera with soft lenses, you might want to reduce the number. - - @param descriptorType The type of descriptors. Only CV_32F and CV_8U are supported. - - @param enable_precise_upscale Whether to enable precise upscaling in the scale pyramid, which maps - index \f$\texttt{x}\f$ to \f$\texttt{2x}\f$. This prevents localization bias. The option - is disabled by default. - */ - CV_WRAP static Ptr create(int nfeatures, int nOctaveLayers, - double contrastThreshold, double edgeThreshold, - double sigma, int descriptorType, bool enable_precise_upscale = false); - - CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; - - CV_WRAP virtual void setNFeatures(int maxFeatures) = 0; - CV_WRAP virtual int getNFeatures() const = 0; - - CV_WRAP virtual void setNOctaveLayers(int nOctaveLayers) = 0; - CV_WRAP virtual int getNOctaveLayers() const = 0; - - CV_WRAP virtual void setContrastThreshold(double contrastThreshold) = 0; - CV_WRAP virtual double getContrastThreshold() const = 0; - - CV_WRAP virtual void setEdgeThreshold(double edgeThreshold) = 0; - CV_WRAP virtual double getEdgeThreshold() const = 0; - - CV_WRAP virtual void setSigma(double sigma) = 0; - CV_WRAP virtual double getSigma() const = 0; -}; - -typedef SIFT SiftFeatureDetector; -typedef SIFT SiftDescriptorExtractor; - - -/** @brief Class implementing the BRISK keypoint detector and descriptor extractor, described in @cite LCS11 . - */ -class CV_EXPORTS_W BRISK : public Feature2D -{ -public: - /** @brief The BRISK constructor - - @param thresh AGAST detection threshold score. - @param octaves detection octaves. Use 0 to do single scale. - @param patternScale apply this scale to the pattern used for sampling the neighbourhood of a - keypoint. - */ - CV_WRAP static Ptr create(int thresh=30, int octaves=3, float patternScale=1.0f); - - /** @brief The BRISK constructor for a custom pattern - - @param radiusList defines the radii (in pixels) where the samples around a keypoint are taken (for - keypoint scale 1). - @param numberList defines the number of sampling points on the sampling circle. Must be the same - size as radiusList.. - @param dMax threshold for the short pairings used for descriptor formation (in pixels for keypoint - scale 1). - @param dMin threshold for the long pairings used for orientation determination (in pixels for - keypoint scale 1). - @param indexChange index remapping of the bits. */ - CV_WRAP static Ptr create(const std::vector &radiusList, const std::vector &numberList, - float dMax=5.85f, float dMin=8.2f, const std::vector& indexChange=std::vector()); - - /** @brief The BRISK constructor for a custom pattern, detection threshold and octaves - - @param thresh AGAST detection threshold score. - @param octaves detection octaves. Use 0 to do single scale. - @param radiusList defines the radii (in pixels) where the samples around a keypoint are taken (for - keypoint scale 1). - @param numberList defines the number of sampling points on the sampling circle. Must be the same - size as radiusList.. - @param dMax threshold for the short pairings used for descriptor formation (in pixels for keypoint - scale 1). - @param dMin threshold for the long pairings used for orientation determination (in pixels for - keypoint scale 1). - @param indexChange index remapping of the bits. */ - CV_WRAP static Ptr create(int thresh, int octaves, const std::vector &radiusList, - const std::vector &numberList, float dMax=5.85f, float dMin=8.2f, - const std::vector& indexChange=std::vector()); - CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; - - /** @brief Set detection threshold. - @param threshold AGAST detection threshold score. - */ - CV_WRAP virtual void setThreshold(int threshold) = 0; - CV_WRAP virtual int getThreshold() const = 0; - - /** @brief Set detection octaves. - @param octaves detection octaves. Use 0 to do single scale. - */ - CV_WRAP virtual void setOctaves(int octaves) = 0; - CV_WRAP virtual int getOctaves() const = 0; - /** @brief Set detection patternScale. - @param patternScale apply this scale to the pattern used for sampling the neighbourhood of a - keypoint. - */ - CV_WRAP virtual void setPatternScale(float patternScale) = 0; - CV_WRAP virtual float getPatternScale() const = 0; -}; - -/** @brief Class implementing the ORB (*oriented BRIEF*) keypoint detector and descriptor extractor - -described in @cite RRKB11 . The algorithm uses FAST in pyramids to detect stable keypoints, selects -the strongest features using FAST or Harris response, finds their orientation using first-order -moments and computes the descriptors using BRIEF (where the coordinates of random point pairs (or -k-tuples) are rotated according to the measured orientation). - */ -class CV_EXPORTS_W ORB : public Feature2D -{ -public: - enum ScoreType { HARRIS_SCORE=0, FAST_SCORE=1 }; - static const int kBytes = 32; - - /** @brief The ORB constructor - - @param nfeatures The maximum number of features to retain. - @param scaleFactor Pyramid decimation ratio, greater than 1. scaleFactor==2 means the classical - pyramid, where each next level has 4x less pixels than the previous, but such a big scale factor - will degrade feature matching scores dramatically. On the other hand, too close to 1 scale factor - will mean that to cover certain scale range you will need more pyramid levels and so the speed - will suffer. - @param nlevels The number of pyramid levels. The smallest level will have linear size equal to - input_image_linear_size/pow(scaleFactor, nlevels - firstLevel). - @param edgeThreshold This is size of the border where the features are not detected. It should - roughly match the patchSize parameter. - @param firstLevel The level of pyramid to put source image to. Previous layers are filled - with upscaled source image. - @param WTA_K The number of points that produce each element of the oriented BRIEF descriptor. The - default value 2 means the BRIEF where we take a random point pair and compare their brightnesses, - so we get 0/1 response. Other possible values are 3 and 4. For example, 3 means that we take 3 - random points (of course, those point coordinates are random, but they are generated from the - pre-defined seed, so each element of BRIEF descriptor is computed deterministically from the pixel - rectangle), find point of maximum brightness and output index of the winner (0, 1 or 2). Such - output will occupy 2 bits, and therefore it will need a special variant of Hamming distance, - denoted as NORM_HAMMING2 (2 bits per bin). When WTA_K=4, we take 4 random points to compute each - bin (that will also occupy 2 bits with possible values 0, 1, 2 or 3). - @param scoreType The default HARRIS_SCORE means that Harris algorithm is used to rank features - (the score is written to KeyPoint::score and is used to retain best nfeatures features); - FAST_SCORE is alternative value of the parameter that produces slightly less stable keypoints, - but it is a little faster to compute. - @param patchSize size of the patch used by the oriented BRIEF descriptor. Of course, on smaller - pyramid layers the perceived image area covered by a feature will be larger. - @param fastThreshold the fast threshold - */ - CV_WRAP static Ptr create(int nfeatures=500, float scaleFactor=1.2f, int nlevels=8, int edgeThreshold=31, - int firstLevel=0, int WTA_K=2, ORB::ScoreType scoreType=ORB::HARRIS_SCORE, int patchSize=31, int fastThreshold=20); - - CV_WRAP virtual void setMaxFeatures(int maxFeatures) = 0; - CV_WRAP virtual int getMaxFeatures() const = 0; - - CV_WRAP virtual void setScaleFactor(double scaleFactor) = 0; - CV_WRAP virtual double getScaleFactor() const = 0; - - CV_WRAP virtual void setNLevels(int nlevels) = 0; - CV_WRAP virtual int getNLevels() const = 0; - - CV_WRAP virtual void setEdgeThreshold(int edgeThreshold) = 0; - CV_WRAP virtual int getEdgeThreshold() const = 0; - - CV_WRAP virtual void setFirstLevel(int firstLevel) = 0; - CV_WRAP virtual int getFirstLevel() const = 0; - - CV_WRAP virtual void setWTA_K(int wta_k) = 0; - CV_WRAP virtual int getWTA_K() const = 0; - - CV_WRAP virtual void setScoreType(ORB::ScoreType scoreType) = 0; - CV_WRAP virtual ORB::ScoreType getScoreType() const = 0; - - CV_WRAP virtual void setPatchSize(int patchSize) = 0; - CV_WRAP virtual int getPatchSize() const = 0; - - CV_WRAP virtual void setFastThreshold(int fastThreshold) = 0; - CV_WRAP virtual int getFastThreshold() const = 0; - CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; -}; - -/** @brief Maximally stable extremal region extractor - -The class encapsulates all the parameters of the %MSER extraction algorithm (see [wiki -article](http://en.wikipedia.org/wiki/Maximally_stable_extremal_regions)). - -- there are two different implementation of %MSER: one for grey image, one for color image - -- the grey image algorithm is taken from: @cite nister2008linear ; the paper claims to be faster -than union-find method; it actually get 1.5~2m/s on my centrino L7200 1.2GHz laptop. - -- the color image algorithm is taken from: @cite forssen2007maximally ; it should be much slower -than grey image method ( 3~4 times ) - -- (Python) A complete example showing the use of the %MSER detector can be found at samples/python/mser.py -*/ -class CV_EXPORTS_W MSER : public Feature2D -{ -public: - /** @brief Full constructor for %MSER detector - - @param delta it compares \f$(size_{i}-size_{i-delta})/size_{i-delta}\f$ - @param min_area prune the area which smaller than minArea - @param max_area prune the area which bigger than maxArea - @param max_variation prune the area have similar size to its children - @param min_diversity for color image, trace back to cut off mser with diversity less than min_diversity - @param max_evolution for color image, the evolution steps - @param area_threshold for color image, the area threshold to cause re-initialize - @param min_margin for color image, ignore too small margin - @param edge_blur_size for color image, the aperture size for edge blur - */ - CV_WRAP static Ptr create( int delta=5, int min_area=60, int max_area=14400, - double max_variation=0.25, double min_diversity=.2, - int max_evolution=200, double area_threshold=1.01, - double min_margin=0.003, int edge_blur_size=5 ); - - /** @brief Detect %MSER regions - - @param image input image (8UC1, 8UC3 or 8UC4, must be greater or equal than 3x3) - @param msers resulting list of point sets - @param bboxes resulting bounding boxes - */ - CV_WRAP virtual void detectRegions( InputArray image, - CV_OUT std::vector >& msers, - CV_OUT std::vector& bboxes ) = 0; - - CV_WRAP virtual void setDelta(int delta) = 0; - CV_WRAP virtual int getDelta() const = 0; - - CV_WRAP virtual void setMinArea(int minArea) = 0; - CV_WRAP virtual int getMinArea() const = 0; - - CV_WRAP virtual void setMaxArea(int maxArea) = 0; - CV_WRAP virtual int getMaxArea() const = 0; - - CV_WRAP virtual void setMaxVariation(double maxVariation) = 0; - CV_WRAP virtual double getMaxVariation() const = 0; - - CV_WRAP virtual void setMinDiversity(double minDiversity) = 0; - CV_WRAP virtual double getMinDiversity() const = 0; - - CV_WRAP virtual void setMaxEvolution(int maxEvolution) = 0; - CV_WRAP virtual int getMaxEvolution() const = 0; - - CV_WRAP virtual void setAreaThreshold(double areaThreshold) = 0; - CV_WRAP virtual double getAreaThreshold() const = 0; - - CV_WRAP virtual void setMinMargin(double min_margin) = 0; - CV_WRAP virtual double getMinMargin() const = 0; - - CV_WRAP virtual void setEdgeBlurSize(int edge_blur_size) = 0; - CV_WRAP virtual int getEdgeBlurSize() const = 0; - - CV_WRAP virtual void setPass2Only(bool f) = 0; - CV_WRAP virtual bool getPass2Only() const = 0; - - CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; -}; - - -/** @brief Wrapping class for feature detection using the FAST method. : - */ -class CV_EXPORTS_W FastFeatureDetector : public Feature2D -{ -public: - enum DetectorType - { - TYPE_5_8 = 0, TYPE_7_12 = 1, TYPE_9_16 = 2 - }; - enum - { - THRESHOLD = 10000, NONMAX_SUPPRESSION=10001, FAST_N=10002 - }; - - - CV_WRAP static Ptr create( int threshold=10, - bool nonmaxSuppression=true, - FastFeatureDetector::DetectorType type=FastFeatureDetector::TYPE_9_16 ); - - CV_WRAP virtual void setThreshold(int threshold) = 0; - CV_WRAP virtual int getThreshold() const = 0; - - CV_WRAP virtual void setNonmaxSuppression(bool f) = 0; - CV_WRAP virtual bool getNonmaxSuppression() const = 0; - - CV_WRAP virtual void setType(FastFeatureDetector::DetectorType type) = 0; - CV_WRAP virtual FastFeatureDetector::DetectorType getType() const = 0; - CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; -}; - -/** @overload */ -CV_EXPORTS void FAST( InputArray image, CV_OUT std::vector& keypoints, - int threshold, bool nonmaxSuppression=true ); - -/** @brief Detects corners using the FAST algorithm - -@param image grayscale image where keypoints (corners) are detected. -@param keypoints keypoints detected on the image. -@param threshold threshold on difference between intensity of the central pixel and pixels of a -circle around this pixel. -@param nonmaxSuppression if true, non-maximum suppression is applied to detected corners -(keypoints). -@param type one of the three neighborhoods as defined in the paper: -FastFeatureDetector::TYPE_9_16, FastFeatureDetector::TYPE_7_12, -FastFeatureDetector::TYPE_5_8 - -Detects corners using the FAST algorithm by @cite Rosten06 . - -@note In Python API, types are given as cv.FAST_FEATURE_DETECTOR_TYPE_5_8, -cv.FAST_FEATURE_DETECTOR_TYPE_7_12 and cv.FAST_FEATURE_DETECTOR_TYPE_9_16. For corner -detection, use cv.FAST.detect() method. - */ -CV_EXPORTS void FAST( InputArray image, CV_OUT std::vector& keypoints, - int threshold, bool nonmaxSuppression, FastFeatureDetector::DetectorType type ); - - -/** @brief Wrapping class for feature detection using the AGAST method. : - */ -class CV_EXPORTS_W AgastFeatureDetector : public Feature2D -{ -public: - enum DetectorType - { - AGAST_5_8 = 0, AGAST_7_12d = 1, AGAST_7_12s = 2, OAST_9_16 = 3, - }; - - enum - { - THRESHOLD = 10000, NONMAX_SUPPRESSION = 10001, - }; - - CV_WRAP static Ptr create( int threshold=10, - bool nonmaxSuppression=true, - AgastFeatureDetector::DetectorType type = AgastFeatureDetector::OAST_9_16); - - CV_WRAP virtual void setThreshold(int threshold) = 0; - CV_WRAP virtual int getThreshold() const = 0; - - CV_WRAP virtual void setNonmaxSuppression(bool f) = 0; - CV_WRAP virtual bool getNonmaxSuppression() const = 0; - - CV_WRAP virtual void setType(AgastFeatureDetector::DetectorType type) = 0; - CV_WRAP virtual AgastFeatureDetector::DetectorType getType() const = 0; - CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; -}; - -/** @overload */ -CV_EXPORTS void AGAST( InputArray image, CV_OUT std::vector& keypoints, - int threshold, bool nonmaxSuppression=true ); - -/** @brief Detects corners using the AGAST algorithm - -@param image grayscale image where keypoints (corners) are detected. -@param keypoints keypoints detected on the image. -@param threshold threshold on difference between intensity of the central pixel and pixels of a -circle around this pixel. -@param nonmaxSuppression if true, non-maximum suppression is applied to detected corners -(keypoints). -@param type one of the four neighborhoods as defined in the paper: -AgastFeatureDetector::AGAST_5_8, AgastFeatureDetector::AGAST_7_12d, -AgastFeatureDetector::AGAST_7_12s, AgastFeatureDetector::OAST_9_16 - -For non-Intel platforms, there is a tree optimised variant of AGAST with same numerical results. -The 32-bit binary tree tables were generated automatically from original code using perl script. -The perl script and examples of tree generation are placed in features2d/doc folder. -Detects corners using the AGAST algorithm by @cite mair2010_agast . - - */ -CV_EXPORTS void AGAST( InputArray image, CV_OUT std::vector& keypoints, - int threshold, bool nonmaxSuppression, AgastFeatureDetector::DetectorType type ); - -/** @brief Wrapping class for feature detection using the goodFeaturesToTrack function. : - */ -class CV_EXPORTS_W GFTTDetector : public Feature2D -{ -public: - CV_WRAP static Ptr create( int maxCorners=1000, double qualityLevel=0.01, double minDistance=1, - int blockSize=3, bool useHarrisDetector=false, double k=0.04 ); - CV_WRAP static Ptr create( int maxCorners, double qualityLevel, double minDistance, - int blockSize, int gradiantSize, bool useHarrisDetector=false, double k=0.04 ); - CV_WRAP virtual void setMaxFeatures(int maxFeatures) = 0; - CV_WRAP virtual int getMaxFeatures() const = 0; - - CV_WRAP virtual void setQualityLevel(double qlevel) = 0; - CV_WRAP virtual double getQualityLevel() const = 0; - - CV_WRAP virtual void setMinDistance(double minDistance) = 0; - CV_WRAP virtual double getMinDistance() const = 0; - - CV_WRAP virtual void setBlockSize(int blockSize) = 0; - CV_WRAP virtual int getBlockSize() const = 0; - - CV_WRAP virtual void setGradientSize(int gradientSize_) = 0; - CV_WRAP virtual int getGradientSize() = 0; - - CV_WRAP virtual void setHarrisDetector(bool val) = 0; - CV_WRAP virtual bool getHarrisDetector() const = 0; - - CV_WRAP virtual void setK(double k) = 0; - CV_WRAP virtual double getK() const = 0; - CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; -}; - -/** @brief Class for extracting blobs from an image. : - -The class implements a simple algorithm for extracting blobs from an image: - -1. Convert the source image to binary images by applying thresholding with several thresholds from - minThreshold (inclusive) to maxThreshold (exclusive) with distance thresholdStep between - neighboring thresholds. -2. Extract connected components from every binary image by findContours and calculate their - centers. -3. Group centers from several binary images by their coordinates. Close centers form one group that - corresponds to one blob, which is controlled by the minDistBetweenBlobs parameter. -4. From the groups, estimate final centers of blobs and their radiuses and return as locations and - sizes of keypoints. - -This class performs several filtrations of returned blobs. You should set filterBy\* to true/false -to turn on/off corresponding filtration. Available filtrations: - -- **By color**. This filter compares the intensity of a binary image at the center of a blob to -blobColor. If they differ, the blob is filtered out. Use blobColor = 0 to extract dark blobs -and blobColor = 255 to extract light blobs. -- **By area**. Extracted blobs have an area between minArea (inclusive) and maxArea (exclusive). -- **By circularity**. Extracted blobs have circularity -(\f$\frac{4*\pi*Area}{perimeter * perimeter}\f$) between minCircularity (inclusive) and -maxCircularity (exclusive). -- **By ratio of the minimum inertia to maximum inertia**. Extracted blobs have this ratio -between minInertiaRatio (inclusive) and maxInertiaRatio (exclusive). -- **By convexity**. Extracted blobs have convexity (area / area of blob convex hull) between -minConvexity (inclusive) and maxConvexity (exclusive). - -Default values of parameters are tuned to extract dark circular blobs. - */ -class CV_EXPORTS_W SimpleBlobDetector : public Feature2D -{ -public: - struct CV_EXPORTS_W_SIMPLE Params - { - CV_WRAP Params(); - CV_PROP_RW float thresholdStep; - CV_PROP_RW float minThreshold; - CV_PROP_RW float maxThreshold; - CV_PROP_RW size_t minRepeatability; - CV_PROP_RW float minDistBetweenBlobs; - - CV_PROP_RW bool filterByColor; - CV_PROP_RW uchar blobColor; - - CV_PROP_RW bool filterByArea; - CV_PROP_RW float minArea, maxArea; - - CV_PROP_RW bool filterByCircularity; - CV_PROP_RW float minCircularity, maxCircularity; - - CV_PROP_RW bool filterByInertia; - CV_PROP_RW float minInertiaRatio, maxInertiaRatio; - - CV_PROP_RW bool filterByConvexity; - CV_PROP_RW float minConvexity, maxConvexity; - - CV_PROP_RW bool collectContours; - - void read( const FileNode& fn ); - void write( FileStorage& fs ) const; - }; - - CV_WRAP static Ptr - create(const SimpleBlobDetector::Params ¶meters = SimpleBlobDetector::Params()); - - CV_WRAP virtual void setParams(const SimpleBlobDetector::Params& params ) = 0; - CV_WRAP virtual SimpleBlobDetector::Params getParams() const = 0; - - CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; - CV_WRAP virtual const std::vector >& getBlobContours() const; -}; - - -/** @brief Class implementing the KAZE keypoint detector and descriptor extractor, described in @cite ABD12 . - -@note AKAZE descriptor can only be used with KAZE or AKAZE keypoints .. [ABD12] KAZE Features. Pablo -F. Alcantarilla, Adrien Bartoli and Andrew J. Davison. In European Conference on Computer Vision -(ECCV), Fiorenze, Italy, October 2012. -*/ -class CV_EXPORTS_W KAZE : public Feature2D -{ -public: - enum DiffusivityType - { - DIFF_PM_G1 = 0, - DIFF_PM_G2 = 1, - DIFF_WEICKERT = 2, - DIFF_CHARBONNIER = 3 - }; - - /** @brief The KAZE constructor - - @param extended Set to enable extraction of extended (128-byte) descriptor. - @param upright Set to enable use of upright descriptors (non rotation-invariant). - @param threshold Detector response threshold to accept point - @param nOctaves Maximum octave evolution of the image - @param nOctaveLayers Default number of sublevels per scale level - @param diffusivity Diffusivity type. DIFF_PM_G1, DIFF_PM_G2, DIFF_WEICKERT or - DIFF_CHARBONNIER - */ - CV_WRAP static Ptr create(bool extended=false, bool upright=false, - float threshold = 0.001f, - int nOctaves = 4, int nOctaveLayers = 4, - KAZE::DiffusivityType diffusivity = KAZE::DIFF_PM_G2); - - CV_WRAP virtual void setExtended(bool extended) = 0; - CV_WRAP virtual bool getExtended() const = 0; - - CV_WRAP virtual void setUpright(bool upright) = 0; - CV_WRAP virtual bool getUpright() const = 0; - - CV_WRAP virtual void setThreshold(double threshold) = 0; - CV_WRAP virtual double getThreshold() const = 0; - - CV_WRAP virtual void setNOctaves(int octaves) = 0; - CV_WRAP virtual int getNOctaves() const = 0; - - CV_WRAP virtual void setNOctaveLayers(int octaveLayers) = 0; - CV_WRAP virtual int getNOctaveLayers() const = 0; - - CV_WRAP virtual void setDiffusivity(KAZE::DiffusivityType diff) = 0; - CV_WRAP virtual KAZE::DiffusivityType getDiffusivity() const = 0; - CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; -}; - -/** @brief Class implementing the AKAZE keypoint detector and descriptor extractor, described in @cite ANB13. - -@details AKAZE descriptors can only be used with KAZE or AKAZE keypoints. This class is thread-safe. - -@note When you need descriptors use Feature2D::detectAndCompute, which -provides better performance. When using Feature2D::detect followed by -Feature2D::compute scale space pyramid is computed twice. - -@note AKAZE implements T-API. When image is passed as UMat some parts of the algorithm -will use OpenCL. - -@note [ANB13] Fast Explicit Diffusion for Accelerated Features in Nonlinear -Scale Spaces. Pablo F. Alcantarilla, Jesús Nuevo and Adrien Bartoli. In -British Machine Vision Conference (BMVC), Bristol, UK, September 2013. - -*/ -class CV_EXPORTS_W AKAZE : public Feature2D -{ -public: - // AKAZE descriptor type - enum DescriptorType - { - DESCRIPTOR_KAZE_UPRIGHT = 2, ///< Upright descriptors, not invariant to rotation - DESCRIPTOR_KAZE = 3, - DESCRIPTOR_MLDB_UPRIGHT = 4, ///< Upright descriptors, not invariant to rotation - DESCRIPTOR_MLDB = 5 - }; - - /** @brief The AKAZE constructor - - @param descriptor_type Type of the extracted descriptor: DESCRIPTOR_KAZE, - DESCRIPTOR_KAZE_UPRIGHT, DESCRIPTOR_MLDB or DESCRIPTOR_MLDB_UPRIGHT. - @param descriptor_size Size of the descriptor in bits. 0 -\> Full size - @param descriptor_channels Number of channels in the descriptor (1, 2, 3) - @param threshold Detector response threshold to accept point - @param nOctaves Maximum octave evolution of the image - @param nOctaveLayers Default number of sublevels per scale level - @param diffusivity Diffusivity type. DIFF_PM_G1, DIFF_PM_G2, DIFF_WEICKERT or - DIFF_CHARBONNIER - @param max_points Maximum amount of returned points. In case if image contains - more features, then the features with highest response are returned. - Negative value means no limitation. - */ - CV_WRAP static Ptr create(AKAZE::DescriptorType descriptor_type = AKAZE::DESCRIPTOR_MLDB, - int descriptor_size = 0, int descriptor_channels = 3, - float threshold = 0.001f, int nOctaves = 4, - int nOctaveLayers = 4, KAZE::DiffusivityType diffusivity = KAZE::DIFF_PM_G2, - int max_points = -1); - - CV_WRAP virtual void setDescriptorType(AKAZE::DescriptorType dtype) = 0; - CV_WRAP virtual AKAZE::DescriptorType getDescriptorType() const = 0; - - CV_WRAP virtual void setDescriptorSize(int dsize) = 0; - CV_WRAP virtual int getDescriptorSize() const = 0; - - CV_WRAP virtual void setDescriptorChannels(int dch) = 0; - CV_WRAP virtual int getDescriptorChannels() const = 0; - - CV_WRAP virtual void setThreshold(double threshold) = 0; - CV_WRAP virtual double getThreshold() const = 0; - - CV_WRAP virtual void setNOctaves(int octaves) = 0; - CV_WRAP virtual int getNOctaves() const = 0; - - CV_WRAP virtual void setNOctaveLayers(int octaveLayers) = 0; - CV_WRAP virtual int getNOctaveLayers() const = 0; - - CV_WRAP virtual void setDiffusivity(KAZE::DiffusivityType diff) = 0; - CV_WRAP virtual KAZE::DiffusivityType getDiffusivity() const = 0; - CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; - - CV_WRAP virtual void setMaxPoints(int max_points) = 0; - CV_WRAP virtual int getMaxPoints() const = 0; -}; - - -/****************************************************************************************\ -* Distance * -\****************************************************************************************/ - -template -struct CV_EXPORTS Accumulator -{ - typedef T Type; -}; - -template<> struct Accumulator { typedef float Type; }; -template<> struct Accumulator { typedef float Type; }; -template<> struct Accumulator { typedef float Type; }; -template<> struct Accumulator { typedef float Type; }; - -/* - * Squared Euclidean distance functor - */ -template -struct CV_EXPORTS SL2 -{ - static const NormTypes normType = NORM_L2SQR; - typedef T ValueType; - typedef typename Accumulator::Type ResultType; - - ResultType operator()( const T* a, const T* b, int size ) const - { - return normL2Sqr(a, b, size); - } -}; - -/* - * Euclidean distance functor - */ -template -struct L2 -{ - static const NormTypes normType = NORM_L2; - typedef T ValueType; - typedef typename Accumulator::Type ResultType; - - ResultType operator()( const T* a, const T* b, int size ) const - { - return (ResultType)std::sqrt((double)normL2Sqr(a, b, size)); - } -}; - -/* - * Manhattan distance (city block distance) functor - */ -template -struct L1 -{ - static const NormTypes normType = NORM_L1; - typedef T ValueType; - typedef typename Accumulator::Type ResultType; - - ResultType operator()( const T* a, const T* b, int size ) const - { - return normL1(a, b, size); - } -}; - -//! @} features2d_main - -/****************************************************************************************\ -* DescriptorMatcher * -\****************************************************************************************/ - -//! @addtogroup features2d_match -//! @{ - -/** @brief Abstract base class for matching keypoint descriptors. - -It has two groups of match methods: for matching descriptors of an image with another image or with -an image set. - */ -class CV_EXPORTS_W DescriptorMatcher : public Algorithm -{ -public: - enum MatcherType - { - FLANNBASED = 1, - BRUTEFORCE = 2, - BRUTEFORCE_L1 = 3, - BRUTEFORCE_HAMMING = 4, - BRUTEFORCE_HAMMINGLUT = 5, - BRUTEFORCE_SL2 = 6 - }; - - virtual ~DescriptorMatcher(); - - /** @brief Adds descriptors to train a CPU(trainDescCollectionis) or GPU(utrainDescCollectionis) descriptor - collection. - - If the collection is not empty, the new descriptors are added to existing train descriptors. - - @param descriptors Descriptors to add. Each descriptors[i] is a set of descriptors from the same - train image. - */ - CV_WRAP virtual void add( InputArrayOfArrays descriptors ); - - /** @brief Returns a constant link to the train descriptor collection trainDescCollection . - */ - CV_WRAP const std::vector& getTrainDescriptors() const; - - /** @brief Clears the train descriptor collections. - */ - CV_WRAP virtual void clear() CV_OVERRIDE; - - /** @brief Returns true if there are no train descriptors in the both collections. - */ - CV_WRAP virtual bool empty() const CV_OVERRIDE; - - /** @brief Returns true if the descriptor matcher supports masking permissible matches. - */ - CV_WRAP virtual bool isMaskSupported() const = 0; - - /** @brief Trains a descriptor matcher - - Trains a descriptor matcher (for example, the flann index). In all methods to match, the method - train() is run every time before matching. Some descriptor matchers (for example, BruteForceMatcher) - have an empty implementation of this method. Other matchers really train their inner structures (for - example, FlannBasedMatcher trains flann::Index ). - */ - CV_WRAP virtual void train(); - - /** @brief Finds the best match for each descriptor from a query set. - - @param queryDescriptors Query set of descriptors. - @param trainDescriptors Train set of descriptors. This set is not added to the train descriptors - collection stored in the class object. - @param matches Matches. If a query descriptor is masked out in mask , no match is added for this - descriptor. So, matches size may be smaller than the query descriptors count. - @param mask Mask specifying permissible matches between an input query and train matrices of - descriptors. - - In the first variant of this method, the train descriptors are passed as an input argument. In the - second variant of the method, train descriptors collection that was set by DescriptorMatcher::add is - used. Optional mask (or masks) can be passed to specify which query and training descriptors can be - matched. Namely, queryDescriptors[i] can be matched with trainDescriptors[j] only if - mask.at\(i,j) is non-zero. - */ - CV_WRAP void match( InputArray queryDescriptors, InputArray trainDescriptors, - CV_OUT std::vector& matches, InputArray mask=noArray() ) const; - - /** @brief Finds the k best matches for each descriptor from a query set. - - @param queryDescriptors Query set of descriptors. - @param trainDescriptors Train set of descriptors. This set is not added to the train descriptors - collection stored in the class object. - @param mask Mask specifying permissible matches between an input query and train matrices of - descriptors. - @param matches Matches. Each matches[i] is k or less matches for the same query descriptor. - @param k Count of best matches found per each query descriptor or less if a query descriptor has - less than k possible matches in total. - @param compactResult Parameter used when the mask (or masks) is not empty. If compactResult is - false, the matches vector has the same size as queryDescriptors rows. If compactResult is true, - the matches vector does not contain matches for fully masked-out query descriptors. - - These extended variants of DescriptorMatcher::match methods find several best matches for each query - descriptor. The matches are returned in the distance increasing order. See DescriptorMatcher::match - for the details about query and train descriptors. - */ - CV_WRAP void knnMatch( InputArray queryDescriptors, InputArray trainDescriptors, - CV_OUT std::vector >& matches, int k, - InputArray mask=noArray(), bool compactResult=false ) const; - - /** @brief For each query descriptor, finds the training descriptors not farther than the specified distance. - - @param queryDescriptors Query set of descriptors. - @param trainDescriptors Train set of descriptors. This set is not added to the train descriptors - collection stored in the class object. - @param matches Found matches. - @param compactResult Parameter used when the mask (or masks) is not empty. If compactResult is - false, the matches vector has the same size as queryDescriptors rows. If compactResult is true, - the matches vector does not contain matches for fully masked-out query descriptors. - @param maxDistance Threshold for the distance between matched descriptors. Distance means here - metric distance (e.g. Hamming distance), not the distance between coordinates (which is measured - in Pixels)! - @param mask Mask specifying permissible matches between an input query and train matrices of - descriptors. - - For each query descriptor, the methods find such training descriptors that the distance between the - query descriptor and the training descriptor is equal or smaller than maxDistance. Found matches are - returned in the distance increasing order. - */ - CV_WRAP void radiusMatch( InputArray queryDescriptors, InputArray trainDescriptors, - CV_OUT std::vector >& matches, float maxDistance, - InputArray mask=noArray(), bool compactResult=false ) const; - - /** @overload - @param queryDescriptors Query set of descriptors. - @param matches Matches. If a query descriptor is masked out in mask , no match is added for this - descriptor. So, matches size may be smaller than the query descriptors count. - @param masks Set of masks. Each masks[i] specifies permissible matches between the input query - descriptors and stored train descriptors from the i-th image trainDescCollection[i]. - */ - CV_WRAP void match( InputArray queryDescriptors, CV_OUT std::vector& matches, - InputArrayOfArrays masks=noArray() ); - /** @overload - @param queryDescriptors Query set of descriptors. - @param matches Matches. Each matches[i] is k or less matches for the same query descriptor. - @param k Count of best matches found per each query descriptor or less if a query descriptor has - less than k possible matches in total. - @param masks Set of masks. Each masks[i] specifies permissible matches between the input query - descriptors and stored train descriptors from the i-th image trainDescCollection[i]. - @param compactResult Parameter used when the mask (or masks) is not empty. If compactResult is - false, the matches vector has the same size as queryDescriptors rows. If compactResult is true, - the matches vector does not contain matches for fully masked-out query descriptors. - */ - CV_WRAP void knnMatch( InputArray queryDescriptors, CV_OUT std::vector >& matches, int k, - InputArrayOfArrays masks=noArray(), bool compactResult=false ); - /** @overload - @param queryDescriptors Query set of descriptors. - @param matches Found matches. - @param maxDistance Threshold for the distance between matched descriptors. Distance means here - metric distance (e.g. Hamming distance), not the distance between coordinates (which is measured - in Pixels)! - @param masks Set of masks. Each masks[i] specifies permissible matches between the input query - descriptors and stored train descriptors from the i-th image trainDescCollection[i]. - @param compactResult Parameter used when the mask (or masks) is not empty. If compactResult is - false, the matches vector has the same size as queryDescriptors rows. If compactResult is true, - the matches vector does not contain matches for fully masked-out query descriptors. - */ - CV_WRAP void radiusMatch( InputArray queryDescriptors, CV_OUT std::vector >& matches, float maxDistance, - InputArrayOfArrays masks=noArray(), bool compactResult=false ); - - - CV_WRAP void write( const String& fileName ) const - { - FileStorage fs(fileName, FileStorage::WRITE); - write(fs); - } - - CV_WRAP void read( const String& fileName ) - { - FileStorage fs(fileName, FileStorage::READ); - read(fs.root()); - } - // Reads matcher object from a file node - // see corresponding cv::Algorithm method - CV_WRAP virtual void read( const FileNode& ) CV_OVERRIDE; - // Writes matcher object to a file storage - virtual void write( FileStorage& ) const CV_OVERRIDE; - - /** @brief Clones the matcher. - - @param emptyTrainData If emptyTrainData is false, the method creates a deep copy of the object, - that is, copies both parameters and train data. If emptyTrainData is true, the method creates an - object copy with the current parameters but with empty train data. - */ - CV_WRAP CV_NODISCARD_STD virtual Ptr clone( bool emptyTrainData=false ) const = 0; - - /** @brief Creates a descriptor matcher of a given type with the default parameters (using default - constructor). - - @param descriptorMatcherType Descriptor matcher type. Now the following matcher types are - supported: - - `BruteForce` (it uses L2 ) - - `BruteForce-L1` - - `BruteForce-Hamming` - - `BruteForce-Hamming(2)` - - `FlannBased` - */ - CV_WRAP static Ptr create( const String& descriptorMatcherType ); - - CV_WRAP static Ptr create( const DescriptorMatcher::MatcherType& matcherType ); - - - // see corresponding cv::Algorithm method - CV_WRAP inline void write(FileStorage& fs, const String& name) const { Algorithm::write(fs, name); } -#if CV_VERSION_MAJOR < 5 - inline void write(const Ptr& fs, const String& name) const { CV_Assert(fs); Algorithm::write(*fs, name); } -#endif - -protected: - /** - * Class to work with descriptors from several images as with one merged matrix. - * It is used e.g. in FlannBasedMatcher. - */ - class CV_EXPORTS DescriptorCollection - { - public: - DescriptorCollection(); - DescriptorCollection( const DescriptorCollection& collection ); - virtual ~DescriptorCollection(); - - // Vector of matrices "descriptors" will be merged to one matrix "mergedDescriptors" here. - void set( const std::vector& descriptors ); - virtual void clear(); - - const Mat& getDescriptors() const; - Mat getDescriptor( int imgIdx, int localDescIdx ) const; - Mat getDescriptor( int globalDescIdx ) const; - void getLocalIdx( int globalDescIdx, int& imgIdx, int& localDescIdx ) const; - - int size() const; - - protected: - Mat mergedDescriptors; - std::vector startIdxs; - }; - - //! In fact the matching is implemented only by the following two methods. These methods suppose - //! that the class object has been trained already. Public match methods call these methods - //! after calling train(). - virtual void knnMatchImpl( InputArray queryDescriptors, std::vector >& matches, int k, - InputArrayOfArrays masks=noArray(), bool compactResult=false ) = 0; - virtual void radiusMatchImpl( InputArray queryDescriptors, std::vector >& matches, float maxDistance, - InputArrayOfArrays masks=noArray(), bool compactResult=false ) = 0; - - static bool isPossibleMatch( InputArray mask, int queryIdx, int trainIdx ); - static bool isMaskedOut( InputArrayOfArrays masks, int queryIdx ); - - CV_NODISCARD_STD static Mat clone_op( Mat m ) { return m.clone(); } - void checkMasks( InputArrayOfArrays masks, int queryDescriptorsCount ) const; - - //! Collection of descriptors from train images. - std::vector trainDescCollection; - std::vector utrainDescCollection; -}; - -/** @brief Brute-force descriptor matcher. - -For each descriptor in the first set, this matcher finds the closest descriptor in the second set -by trying each one. This descriptor matcher supports masking permissible matches of descriptor -sets. - */ -class CV_EXPORTS_W BFMatcher : public DescriptorMatcher -{ -public: - /** @brief Brute-force matcher constructor (obsolete). Please use BFMatcher.create() - * - * - */ - CV_WRAP BFMatcher( int normType=NORM_L2, bool crossCheck=false ); - - virtual ~BFMatcher() {} - - virtual bool isMaskSupported() const CV_OVERRIDE { return true; } - - /** @brief Brute-force matcher create method. - @param normType One of NORM_L1, NORM_L2, NORM_HAMMING, NORM_HAMMING2. L1 and L2 norms are - preferable choices for SIFT and SURF descriptors, NORM_HAMMING should be used with ORB, BRISK and - BRIEF, NORM_HAMMING2 should be used with ORB when WTA_K==3 or 4 (see ORB::ORB constructor - description). - @param crossCheck If it is false, this is will be default BFMatcher behaviour when it finds the k - nearest neighbors for each query descriptor. If crossCheck==true, then the knnMatch() method with - k=1 will only return pairs (i,j) such that for i-th query descriptor the j-th descriptor in the - matcher's collection is the nearest and vice versa, i.e. the BFMatcher will only return consistent - pairs. Such technique usually produces best results with minimal number of outliers when there are - enough matches. This is alternative to the ratio test, used by D. Lowe in SIFT paper. - */ - CV_WRAP static Ptr create( int normType=NORM_L2, bool crossCheck=false ) ; - - CV_NODISCARD_STD virtual Ptr clone( bool emptyTrainData=false ) const CV_OVERRIDE; -protected: - virtual void knnMatchImpl( InputArray queryDescriptors, std::vector >& matches, int k, - InputArrayOfArrays masks=noArray(), bool compactResult=false ) CV_OVERRIDE; - virtual void radiusMatchImpl( InputArray queryDescriptors, std::vector >& matches, float maxDistance, - InputArrayOfArrays masks=noArray(), bool compactResult=false ) CV_OVERRIDE; - - int normType; - bool crossCheck; -}; - -#if defined(HAVE_OPENCV_FLANN) || defined(CV_DOXYGEN) - -/** @brief Flann-based descriptor matcher. - -This matcher trains cv::flann::Index on a train descriptor collection and calls its nearest search -methods to find the best matches. So, this matcher may be faster when matching a large train -collection than the brute force matcher. FlannBasedMatcher does not support masking permissible -matches of descriptor sets because flann::Index does not support this. : - */ -class CV_EXPORTS_W FlannBasedMatcher : public DescriptorMatcher -{ -public: - CV_WRAP FlannBasedMatcher( const Ptr& indexParams=makePtr(), - const Ptr& searchParams=makePtr() ); - - virtual void add( InputArrayOfArrays descriptors ) CV_OVERRIDE; - virtual void clear() CV_OVERRIDE; - - // Reads matcher object from a file node - virtual void read( const FileNode& ) CV_OVERRIDE; - // Writes matcher object to a file storage - virtual void write( FileStorage& ) const CV_OVERRIDE; - - virtual void train() CV_OVERRIDE; - virtual bool isMaskSupported() const CV_OVERRIDE; - - CV_WRAP static Ptr create(); - - CV_NODISCARD_STD virtual Ptr clone( bool emptyTrainData=false ) const CV_OVERRIDE; -protected: - static void convertToDMatches( const DescriptorCollection& descriptors, - const Mat& indices, const Mat& distances, - std::vector >& matches ); - - virtual void knnMatchImpl( InputArray queryDescriptors, std::vector >& matches, int k, - InputArrayOfArrays masks=noArray(), bool compactResult=false ) CV_OVERRIDE; - virtual void radiusMatchImpl( InputArray queryDescriptors, std::vector >& matches, float maxDistance, - InputArrayOfArrays masks=noArray(), bool compactResult=false ) CV_OVERRIDE; - - Ptr indexParams; - Ptr searchParams; - Ptr flannIndex; - - DescriptorCollection mergedDescriptors; - int addedDescCount; -}; - -#endif - -//! @} features2d_match - -/****************************************************************************************\ -* Drawing functions * -\****************************************************************************************/ - -//! @addtogroup features2d_draw -//! @{ - -enum struct DrawMatchesFlags -{ - DEFAULT = 0, //!< Output image matrix will be created (Mat::create), - //!< i.e. existing memory of output image may be reused. - //!< Two source image, matches and single keypoints will be drawn. - //!< For each keypoint only the center point will be drawn (without - //!< the circle around keypoint with keypoint size and orientation). - DRAW_OVER_OUTIMG = 1, //!< Output image matrix will not be created (Mat::create). - //!< Matches will be drawn on existing content of output image. - NOT_DRAW_SINGLE_POINTS = 2, //!< Single keypoints will not be drawn. - DRAW_RICH_KEYPOINTS = 4 //!< For each keypoint the circle around keypoint with keypoint size and - //!< orientation will be drawn. -}; -CV_ENUM_FLAGS(DrawMatchesFlags) - -/** @brief Draws keypoints. - -@param image Source image. -@param keypoints Keypoints from the source image. -@param outImage Output image. Its content depends on the flags value defining what is drawn in the -output image. See possible flags bit values below. -@param color Color of keypoints. -@param flags Flags setting drawing features. Possible flags bit values are defined by -DrawMatchesFlags. See details above in drawMatches . - -@note -For Python API, flags are modified as cv.DRAW_MATCHES_FLAGS_DEFAULT, -cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS, cv.DRAW_MATCHES_FLAGS_DRAW_OVER_OUTIMG, -cv.DRAW_MATCHES_FLAGS_NOT_DRAW_SINGLE_POINTS - */ -CV_EXPORTS_W void drawKeypoints( InputArray image, const std::vector& keypoints, InputOutputArray outImage, - const Scalar& color=Scalar::all(-1), DrawMatchesFlags flags=DrawMatchesFlags::DEFAULT ); - -/** @brief Draws the found matches of keypoints from two images. - -@param img1 First source image. -@param keypoints1 Keypoints from the first source image. -@param img2 Second source image. -@param keypoints2 Keypoints from the second source image. -@param matches1to2 Matches from the first image to the second one, which means that keypoints1[i] -has a corresponding point in keypoints2[matches[i]] . -@param outImg Output image. Its content depends on the flags value defining what is drawn in the -output image. See possible flags bit values below. -@param matchColor Color of matches (lines and connected keypoints). If matchColor==Scalar::all(-1) -, the color is generated randomly. -@param singlePointColor Color of single keypoints (circles), which means that keypoints do not -have the matches. If singlePointColor==Scalar::all(-1) , the color is generated randomly. -@param matchesMask Mask determining which matches are drawn. If the mask is empty, all matches are -drawn. -@param flags Flags setting drawing features. Possible flags bit values are defined by -DrawMatchesFlags. - -This function draws matches of keypoints from two images in the output image. Match is a line -connecting two keypoints (circles). See cv::DrawMatchesFlags. - */ -CV_EXPORTS_W void drawMatches( InputArray img1, const std::vector& keypoints1, - InputArray img2, const std::vector& keypoints2, - const std::vector& matches1to2, InputOutputArray outImg, - const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1), - const std::vector& matchesMask=std::vector(), DrawMatchesFlags flags=DrawMatchesFlags::DEFAULT ); - -/** @overload */ -CV_EXPORTS_W void drawMatches( InputArray img1, const std::vector& keypoints1, - InputArray img2, const std::vector& keypoints2, - const std::vector& matches1to2, InputOutputArray outImg, - const int matchesThickness, const Scalar& matchColor=Scalar::all(-1), - const Scalar& singlePointColor=Scalar::all(-1), const std::vector& matchesMask=std::vector(), - DrawMatchesFlags flags=DrawMatchesFlags::DEFAULT ); - -CV_EXPORTS_AS(drawMatchesKnn) void drawMatches( InputArray img1, const std::vector& keypoints1, - InputArray img2, const std::vector& keypoints2, - const std::vector >& matches1to2, InputOutputArray outImg, - const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1), - const std::vector >& matchesMask=std::vector >(), DrawMatchesFlags flags=DrawMatchesFlags::DEFAULT ); - -//! @} features2d_draw - -/****************************************************************************************\ -* Functions to evaluate the feature detectors and [generic] descriptor extractors * -\****************************************************************************************/ - -//! @addtogroup features2d_main -//! @{ - -CV_EXPORTS void evaluateFeatureDetector( const Mat& img1, const Mat& img2, const Mat& H1to2, - std::vector* keypoints1, std::vector* keypoints2, - float& repeatability, int& correspCount, - const Ptr& fdetector=Ptr() ); - -CV_EXPORTS void computeRecallPrecisionCurve( const std::vector >& matches1to2, - const std::vector >& correctMatches1to2Mask, - std::vector& recallPrecisionCurve ); - -CV_EXPORTS float getRecall( const std::vector& recallPrecisionCurve, float l_precision ); -CV_EXPORTS int getNearestPoint( const std::vector& recallPrecisionCurve, float l_precision ); - -//! @} - -/****************************************************************************************\ -* Bag of visual words * -\****************************************************************************************/ - -//! @addtogroup features2d_category -//! @{ - -/** @brief Abstract base class for training the *bag of visual words* vocabulary from a set of descriptors. - -For details, see, for example, *Visual Categorization with Bags of Keypoints* by Gabriella Csurka, -Christopher R. Dance, Lixin Fan, Jutta Willamowski, Cedric Bray, 2004. : - */ -class CV_EXPORTS_W BOWTrainer -{ -public: - BOWTrainer(); - virtual ~BOWTrainer(); - - /** @brief Adds descriptors to a training set. - - @param descriptors Descriptors to add to a training set. Each row of the descriptors matrix is a - descriptor. - - The training set is clustered using clustermethod to construct the vocabulary. - */ - CV_WRAP void add( const Mat& descriptors ); - - /** @brief Returns a training set of descriptors. - */ - CV_WRAP const std::vector& getDescriptors() const; - - /** @brief Returns the count of all descriptors stored in the training set. - */ - CV_WRAP int descriptorsCount() const; - - CV_WRAP virtual void clear(); - - /** @overload */ - CV_WRAP virtual Mat cluster() const = 0; - - /** @brief Clusters train descriptors. - - @param descriptors Descriptors to cluster. Each row of the descriptors matrix is a descriptor. - Descriptors are not added to the inner train descriptor set. - - The vocabulary consists of cluster centers. So, this method returns the vocabulary. In the first - variant of the method, train descriptors stored in the object are clustered. In the second variant, - input descriptors are clustered. - */ - CV_WRAP virtual Mat cluster( const Mat& descriptors ) const = 0; - -protected: - std::vector descriptors; - int size; -}; - -/** @brief kmeans -based class to train visual vocabulary using the *bag of visual words* approach. : - */ -class CV_EXPORTS_W BOWKMeansTrainer : public BOWTrainer -{ -public: - /** @brief The constructor. - - @see cv::kmeans - */ - CV_WRAP BOWKMeansTrainer( int clusterCount, const TermCriteria& termcrit=TermCriteria(), - int attempts=3, int flags=KMEANS_PP_CENTERS ); - virtual ~BOWKMeansTrainer(); - - // Returns trained vocabulary (i.e. cluster centers). - CV_WRAP virtual Mat cluster() const CV_OVERRIDE; - CV_WRAP virtual Mat cluster( const Mat& descriptors ) const CV_OVERRIDE; - -protected: - - int clusterCount; - TermCriteria termcrit; - int attempts; - int flags; -}; - -/** @brief Class to compute an image descriptor using the *bag of visual words*. - -Such a computation consists of the following steps: - -1. Compute descriptors for a given image and its keypoints set. -2. Find the nearest visual words from the vocabulary for each keypoint descriptor. -3. Compute the bag-of-words image descriptor as is a normalized histogram of vocabulary words -encountered in the image. The i-th bin of the histogram is a frequency of i-th word of the -vocabulary in the given image. - */ -class CV_EXPORTS_W BOWImgDescriptorExtractor -{ -public: - /** @brief The constructor. - - @param dextractor Descriptor extractor that is used to compute descriptors for an input image and - its keypoints. - @param dmatcher Descriptor matcher that is used to find the nearest word of the trained vocabulary - for each keypoint descriptor of the image. - */ - CV_WRAP BOWImgDescriptorExtractor( const Ptr& dextractor, - const Ptr& dmatcher ); - /** @overload */ - BOWImgDescriptorExtractor( const Ptr& dmatcher ); - virtual ~BOWImgDescriptorExtractor(); - - /** @brief Sets a visual vocabulary. - - @param vocabulary Vocabulary (can be trained using the inheritor of BOWTrainer ). Each row of the - vocabulary is a visual word (cluster center). - */ - CV_WRAP void setVocabulary( const Mat& vocabulary ); - - /** @brief Returns the set vocabulary. - */ - CV_WRAP const Mat& getVocabulary() const; - - /** @brief Computes an image descriptor using the set visual vocabulary. - - @param image Image, for which the descriptor is computed. - @param keypoints Keypoints detected in the input image. - @param imgDescriptor Computed output image descriptor. - @param pointIdxsOfClusters Indices of keypoints that belong to the cluster. This means that - pointIdxsOfClusters[i] are keypoint indices that belong to the i -th cluster (word of vocabulary) - returned if it is non-zero. - @param descriptors Descriptors of the image keypoints that are returned if they are non-zero. - */ - void compute( InputArray image, std::vector& keypoints, OutputArray imgDescriptor, - std::vector >* pointIdxsOfClusters=0, Mat* descriptors=0 ); - /** @overload - @param keypointDescriptors Computed descriptors to match with vocabulary. - @param imgDescriptor Computed output image descriptor. - @param pointIdxsOfClusters Indices of keypoints that belong to the cluster. This means that - pointIdxsOfClusters[i] are keypoint indices that belong to the i -th cluster (word of vocabulary) - returned if it is non-zero. - */ - void compute( InputArray keypointDescriptors, OutputArray imgDescriptor, - std::vector >* pointIdxsOfClusters=0 ); - // compute() is not constant because DescriptorMatcher::match is not constant - - CV_WRAP_AS(compute) void compute2( const Mat& image, std::vector& keypoints, CV_OUT Mat& imgDescriptor ) - { compute(image,keypoints,imgDescriptor); } - - /** @brief Returns an image descriptor size if the vocabulary is set. Otherwise, it returns 0. - */ - CV_WRAP int descriptorSize() const; - - /** @brief Returns an image descriptor type. - */ - CV_WRAP int descriptorType() const; - -protected: - Mat vocabulary; - Ptr dextractor; - Ptr dmatcher; -}; - -//! @} features2d_category - -} /* namespace cv */ - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_FEATURES_2D_HPP +#define OPENCV_FEATURES_2D_HPP + +#include "opencv2/opencv_modules.hpp" +#include "opencv2/core.hpp" + +#ifdef HAVE_OPENCV_FLANN +#include "opencv2/flann/miniflann.hpp" +#endif + +/** + @defgroup features2d 2D Features Framework + @{ + @defgroup features2d_main Feature Detection and Description + @defgroup features2d_match Descriptor Matchers + + Matchers of keypoint descriptors in OpenCV have wrappers with a common interface that enables + you to easily switch between different algorithms solving the same problem. This section is + devoted to matching descriptors that are represented as vectors in a multidimensional space. + All objects that implement vector descriptor matchers inherit the DescriptorMatcher interface. + + @defgroup features2d_draw Drawing Function of Keypoints and Matches + @defgroup features2d_category Object Categorization + + This section describes approaches based on local 2D features and used to categorize objects. + + @defgroup feature2d_hal Hardware Acceleration Layer + @{ + @defgroup features2d_hal_interface Interface + @} + @} + */ + +namespace cv +{ + +//! @addtogroup features2d_main +//! @{ + +// //! writes vector of keypoints to the file storage +// CV_EXPORTS void write(FileStorage& fs, const String& name, const std::vector& keypoints); +// //! reads vector of keypoints from the specified file storage node +// CV_EXPORTS void read(const FileNode& node, CV_OUT std::vector& keypoints); + +/** @brief A class filters a vector of keypoints. + + Because now it is difficult to provide a convenient interface for all usage scenarios of the + keypoints filter class, it has only several needed by now static methods. + */ +class CV_EXPORTS KeyPointsFilter +{ +public: + KeyPointsFilter(){} + + /* + * Remove keypoints within borderPixels of an image edge. + */ + static void runByImageBorder( std::vector& keypoints, Size imageSize, int borderSize ); + /* + * Remove keypoints of sizes out of range. + */ + static void runByKeypointSize( std::vector& keypoints, float minSize, + float maxSize=FLT_MAX ); + /* + * Remove keypoints from some image by mask for pixels of this image. + */ + static void runByPixelsMask( std::vector& keypoints, const Mat& mask ); + /* + * Remove objects from some image and a vector of points by mask for pixels of this image + */ + static void runByPixelsMask2VectorPoint(std::vector &keypoints, std::vector > &removeFrom, const Mat &mask); + /* + * Remove duplicated keypoints. + */ + static void removeDuplicated( std::vector& keypoints ); + /* + * Remove duplicated keypoints and sort the remaining keypoints + */ + static void removeDuplicatedSorted( std::vector& keypoints ); + + /* + * Retain the specified number of the best keypoints (according to the response) + */ + static void retainBest( std::vector& keypoints, int npoints ); +}; + + +/************************************ Base Classes ************************************/ + +/** @brief Abstract base class for 2D image feature detectors and descriptor extractors +*/ +#ifdef __EMSCRIPTEN__ +class CV_EXPORTS_W Feature2D : public Algorithm +#else +class CV_EXPORTS_W Feature2D : public virtual Algorithm +#endif +{ +public: + virtual ~Feature2D(); + + /** @brief Detects keypoints in an image (first variant) or image set (second variant). + + @param image Image. + @param keypoints The detected keypoints. In the second variant of the method keypoints[i] is a set + of keypoints detected in images[i] . + @param mask Mask specifying where to look for keypoints (optional). It must be a 8-bit integer + matrix with non-zero values in the region of interest. + */ + CV_WRAP virtual void detect( InputArray image, + CV_OUT std::vector& keypoints, + InputArray mask=noArray() ); + + /** @overload + @param images Image set. + @param keypoints The detected keypoints. In the second variant of the method keypoints[i] is a set + of keypoints detected in images[i] . + @param masks Masks for each input image specifying where to look for keypoints (optional). + masks[i] is a mask for images[i]. + */ + CV_WRAP virtual void detect( InputArrayOfArrays images, + CV_OUT std::vector >& keypoints, + InputArrayOfArrays masks=noArray() ); + + /** @brief Computes the descriptors for a set of keypoints detected in an image (first variant) or image set + (second variant). + + @param image Image. + @param keypoints Input collection of keypoints. Keypoints for which a descriptor cannot be + computed are removed. Sometimes new keypoints can be added, for example: SIFT duplicates keypoint + with several dominant orientations (for each orientation). + @param descriptors Computed descriptors. In the second variant of the method descriptors[i] are + descriptors computed for a keypoints[i]. Row j is the keypoints (or keypoints[i]) is the + descriptor for keypoint j-th keypoint. + */ + CV_WRAP virtual void compute( InputArray image, + CV_OUT CV_IN_OUT std::vector& keypoints, + OutputArray descriptors ); + + /** @overload + + @param images Image set. + @param keypoints Input collection of keypoints. Keypoints for which a descriptor cannot be + computed are removed. Sometimes new keypoints can be added, for example: SIFT duplicates keypoint + with several dominant orientations (for each orientation). + @param descriptors Computed descriptors. In the second variant of the method descriptors[i] are + descriptors computed for a keypoints[i]. Row j is the keypoints (or keypoints[i]) is the + descriptor for keypoint j-th keypoint. + */ + CV_WRAP virtual void compute( InputArrayOfArrays images, + CV_OUT CV_IN_OUT std::vector >& keypoints, + OutputArrayOfArrays descriptors ); + + /** Detects keypoints and computes the descriptors */ + CV_WRAP virtual void detectAndCompute( InputArray image, InputArray mask, + CV_OUT std::vector& keypoints, + OutputArray descriptors, + bool useProvidedKeypoints=false ); + + CV_WRAP virtual int descriptorSize() const; + CV_WRAP virtual int descriptorType() const; + CV_WRAP virtual int defaultNorm() const; + + CV_WRAP void write( const String& fileName ) const; + + CV_WRAP void read( const String& fileName ); + + virtual void write( FileStorage&) const CV_OVERRIDE; + + // see corresponding cv::Algorithm method + CV_WRAP virtual void read( const FileNode&) CV_OVERRIDE; + + //! Return true if detector object is empty + CV_WRAP virtual bool empty() const CV_OVERRIDE; + CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; + + // see corresponding cv::Algorithm method + CV_WRAP inline void write(FileStorage& fs, const String& name) const { Algorithm::write(fs, name); } +#if CV_VERSION_MAJOR < 5 + inline void write(const Ptr& fs, const String& name) const { CV_Assert(fs); Algorithm::write(*fs, name); } +#endif +}; + +/** Feature detectors in OpenCV have wrappers with a common interface that enables you to easily switch +between different algorithms solving the same problem. All objects that implement keypoint detectors +inherit the FeatureDetector interface. */ +typedef Feature2D FeatureDetector; + +/** Extractors of keypoint descriptors in OpenCV have wrappers with a common interface that enables you +to easily switch between different algorithms solving the same problem. This section is devoted to +computing descriptors represented as vectors in a multidimensional space. All objects that implement +the vector descriptor extractors inherit the DescriptorExtractor interface. + */ +typedef Feature2D DescriptorExtractor; + + +/** @brief Class for implementing the wrapper which makes detectors and extractors to be affine invariant, +described as ASIFT in @cite YM11 . +*/ +class CV_EXPORTS_W AffineFeature : public Feature2D +{ +public: + /** + @param backend The detector/extractor you want to use as backend. + @param maxTilt The highest power index of tilt factor. 5 is used in the paper as tilt sampling range n. + @param minTilt The lowest power index of tilt factor. 0 is used in the paper. + @param tiltStep Tilt sampling step \f$\delta_t\f$ in Algorithm 1 in the paper. + @param rotateStepBase Rotation sampling step factor b in Algorithm 1 in the paper. + */ + CV_WRAP static Ptr create(const Ptr& backend, + int maxTilt = 5, int minTilt = 0, float tiltStep = 1.4142135623730951f, float rotateStepBase = 72); + + CV_WRAP virtual void setViewParams(const std::vector& tilts, const std::vector& rolls) = 0; + CV_WRAP virtual void getViewParams(std::vector& tilts, std::vector& rolls) const = 0; + CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; +}; + +typedef AffineFeature AffineFeatureDetector; +typedef AffineFeature AffineDescriptorExtractor; + + +/** @brief Class for extracting keypoints and computing descriptors using the Scale Invariant Feature Transform +(SIFT) algorithm by D. Lowe @cite Lowe04 . +*/ +class CV_EXPORTS_W SIFT : public Feature2D +{ +public: + /** + @param nfeatures The number of best features to retain. The features are ranked by their scores + (measured in SIFT algorithm as the local contrast) + + @param nOctaveLayers The number of layers in each octave. 3 is the value used in D. Lowe paper. The + number of octaves is computed automatically from the image resolution. + + @param contrastThreshold The contrast threshold used to filter out weak features in semi-uniform + (low-contrast) regions. The larger the threshold, the less features are produced by the detector. + + @note The contrast threshold will be divided by nOctaveLayers when the filtering is applied. When + nOctaveLayers is set to default and if you want to use the value used in D. Lowe paper, 0.03, set + this argument to 0.09. + + @param edgeThreshold The threshold used to filter out edge-like features. Note that the its meaning + is different from the contrastThreshold, i.e. the larger the edgeThreshold, the less features are + filtered out (more features are retained). + + @param sigma The sigma of the Gaussian applied to the input image at the octave \#0. If your image + is captured with a weak camera with soft lenses, you might want to reduce the number. + + @param enable_precise_upscale Whether to enable precise upscaling in the scale pyramid, which maps + index \f$\texttt{x}\f$ to \f$\texttt{2x}\f$. This prevents localization bias. The option + is disabled by default. + */ + CV_WRAP static Ptr create(int nfeatures = 0, int nOctaveLayers = 3, + double contrastThreshold = 0.04, double edgeThreshold = 10, + double sigma = 1.6, bool enable_precise_upscale = false); + + /** @brief Create SIFT with specified descriptorType. + @param nfeatures The number of best features to retain. The features are ranked by their scores + (measured in SIFT algorithm as the local contrast) + + @param nOctaveLayers The number of layers in each octave. 3 is the value used in D. Lowe paper. The + number of octaves is computed automatically from the image resolution. + + @param contrastThreshold The contrast threshold used to filter out weak features in semi-uniform + (low-contrast) regions. The larger the threshold, the less features are produced by the detector. + + @note The contrast threshold will be divided by nOctaveLayers when the filtering is applied. When + nOctaveLayers is set to default and if you want to use the value used in D. Lowe paper, 0.03, set + this argument to 0.09. + + @param edgeThreshold The threshold used to filter out edge-like features. Note that the its meaning + is different from the contrastThreshold, i.e. the larger the edgeThreshold, the less features are + filtered out (more features are retained). + + @param sigma The sigma of the Gaussian applied to the input image at the octave \#0. If your image + is captured with a weak camera with soft lenses, you might want to reduce the number. + + @param descriptorType The type of descriptors. Only CV_32F and CV_8U are supported. + + @param enable_precise_upscale Whether to enable precise upscaling in the scale pyramid, which maps + index \f$\texttt{x}\f$ to \f$\texttt{2x}\f$. This prevents localization bias. The option + is disabled by default. + */ + CV_WRAP static Ptr create(int nfeatures, int nOctaveLayers, + double contrastThreshold, double edgeThreshold, + double sigma, int descriptorType, bool enable_precise_upscale = false); + + CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; + + CV_WRAP virtual void setNFeatures(int maxFeatures) = 0; + CV_WRAP virtual int getNFeatures() const = 0; + + CV_WRAP virtual void setNOctaveLayers(int nOctaveLayers) = 0; + CV_WRAP virtual int getNOctaveLayers() const = 0; + + CV_WRAP virtual void setContrastThreshold(double contrastThreshold) = 0; + CV_WRAP virtual double getContrastThreshold() const = 0; + + CV_WRAP virtual void setEdgeThreshold(double edgeThreshold) = 0; + CV_WRAP virtual double getEdgeThreshold() const = 0; + + CV_WRAP virtual void setSigma(double sigma) = 0; + CV_WRAP virtual double getSigma() const = 0; +}; + +typedef SIFT SiftFeatureDetector; +typedef SIFT SiftDescriptorExtractor; + + +/** @brief Class implementing the BRISK keypoint detector and descriptor extractor, described in @cite LCS11 . + */ +class CV_EXPORTS_W BRISK : public Feature2D +{ +public: + /** @brief The BRISK constructor + + @param thresh AGAST detection threshold score. + @param octaves detection octaves. Use 0 to do single scale. + @param patternScale apply this scale to the pattern used for sampling the neighbourhood of a + keypoint. + */ + CV_WRAP static Ptr create(int thresh=30, int octaves=3, float patternScale=1.0f); + + /** @brief The BRISK constructor for a custom pattern + + @param radiusList defines the radii (in pixels) where the samples around a keypoint are taken (for + keypoint scale 1). + @param numberList defines the number of sampling points on the sampling circle. Must be the same + size as radiusList.. + @param dMax threshold for the short pairings used for descriptor formation (in pixels for keypoint + scale 1). + @param dMin threshold for the long pairings used for orientation determination (in pixels for + keypoint scale 1). + @param indexChange index remapping of the bits. */ + CV_WRAP static Ptr create(const std::vector &radiusList, const std::vector &numberList, + float dMax=5.85f, float dMin=8.2f, const std::vector& indexChange=std::vector()); + + /** @brief The BRISK constructor for a custom pattern, detection threshold and octaves + + @param thresh AGAST detection threshold score. + @param octaves detection octaves. Use 0 to do single scale. + @param radiusList defines the radii (in pixels) where the samples around a keypoint are taken (for + keypoint scale 1). + @param numberList defines the number of sampling points on the sampling circle. Must be the same + size as radiusList.. + @param dMax threshold for the short pairings used for descriptor formation (in pixels for keypoint + scale 1). + @param dMin threshold for the long pairings used for orientation determination (in pixels for + keypoint scale 1). + @param indexChange index remapping of the bits. */ + CV_WRAP static Ptr create(int thresh, int octaves, const std::vector &radiusList, + const std::vector &numberList, float dMax=5.85f, float dMin=8.2f, + const std::vector& indexChange=std::vector()); + CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; + + /** @brief Set detection threshold. + @param threshold AGAST detection threshold score. + */ + CV_WRAP virtual void setThreshold(int threshold) = 0; + CV_WRAP virtual int getThreshold() const = 0; + + /** @brief Set detection octaves. + @param octaves detection octaves. Use 0 to do single scale. + */ + CV_WRAP virtual void setOctaves(int octaves) = 0; + CV_WRAP virtual int getOctaves() const = 0; + /** @brief Set detection patternScale. + @param patternScale apply this scale to the pattern used for sampling the neighbourhood of a + keypoint. + */ + CV_WRAP virtual void setPatternScale(float patternScale) = 0; + CV_WRAP virtual float getPatternScale() const = 0; +}; + +/** @brief Class implementing the ORB (*oriented BRIEF*) keypoint detector and descriptor extractor + +described in @cite RRKB11 . The algorithm uses FAST in pyramids to detect stable keypoints, selects +the strongest features using FAST or Harris response, finds their orientation using first-order +moments and computes the descriptors using BRIEF (where the coordinates of random point pairs (or +k-tuples) are rotated according to the measured orientation). + */ +class CV_EXPORTS_W ORB : public Feature2D +{ +public: + enum ScoreType { HARRIS_SCORE=0, FAST_SCORE=1 }; + static const int kBytes = 32; + + /** @brief The ORB constructor + + @param nfeatures The maximum number of features to retain. + @param scaleFactor Pyramid decimation ratio, greater than 1. scaleFactor==2 means the classical + pyramid, where each next level has 4x less pixels than the previous, but such a big scale factor + will degrade feature matching scores dramatically. On the other hand, too close to 1 scale factor + will mean that to cover certain scale range you will need more pyramid levels and so the speed + will suffer. + @param nlevels The number of pyramid levels. The smallest level will have linear size equal to + input_image_linear_size/pow(scaleFactor, nlevels - firstLevel). + @param edgeThreshold This is size of the border where the features are not detected. It should + roughly match the patchSize parameter. + @param firstLevel The level of pyramid to put source image to. Previous layers are filled + with upscaled source image. + @param WTA_K The number of points that produce each element of the oriented BRIEF descriptor. The + default value 2 means the BRIEF where we take a random point pair and compare their brightnesses, + so we get 0/1 response. Other possible values are 3 and 4. For example, 3 means that we take 3 + random points (of course, those point coordinates are random, but they are generated from the + pre-defined seed, so each element of BRIEF descriptor is computed deterministically from the pixel + rectangle), find point of maximum brightness and output index of the winner (0, 1 or 2). Such + output will occupy 2 bits, and therefore it will need a special variant of Hamming distance, + denoted as NORM_HAMMING2 (2 bits per bin). When WTA_K=4, we take 4 random points to compute each + bin (that will also occupy 2 bits with possible values 0, 1, 2 or 3). + @param scoreType The default HARRIS_SCORE means that Harris algorithm is used to rank features + (the score is written to KeyPoint::score and is used to retain best nfeatures features); + FAST_SCORE is alternative value of the parameter that produces slightly less stable keypoints, + but it is a little faster to compute. + @param patchSize size of the patch used by the oriented BRIEF descriptor. Of course, on smaller + pyramid layers the perceived image area covered by a feature will be larger. + @param fastThreshold the fast threshold + */ + CV_WRAP static Ptr create(int nfeatures=500, float scaleFactor=1.2f, int nlevels=8, int edgeThreshold=31, + int firstLevel=0, int WTA_K=2, ORB::ScoreType scoreType=ORB::HARRIS_SCORE, int patchSize=31, int fastThreshold=20); + + CV_WRAP virtual void setMaxFeatures(int maxFeatures) = 0; + CV_WRAP virtual int getMaxFeatures() const = 0; + + CV_WRAP virtual void setScaleFactor(double scaleFactor) = 0; + CV_WRAP virtual double getScaleFactor() const = 0; + + CV_WRAP virtual void setNLevels(int nlevels) = 0; + CV_WRAP virtual int getNLevels() const = 0; + + CV_WRAP virtual void setEdgeThreshold(int edgeThreshold) = 0; + CV_WRAP virtual int getEdgeThreshold() const = 0; + + CV_WRAP virtual void setFirstLevel(int firstLevel) = 0; + CV_WRAP virtual int getFirstLevel() const = 0; + + CV_WRAP virtual void setWTA_K(int wta_k) = 0; + CV_WRAP virtual int getWTA_K() const = 0; + + CV_WRAP virtual void setScoreType(ORB::ScoreType scoreType) = 0; + CV_WRAP virtual ORB::ScoreType getScoreType() const = 0; + + CV_WRAP virtual void setPatchSize(int patchSize) = 0; + CV_WRAP virtual int getPatchSize() const = 0; + + CV_WRAP virtual void setFastThreshold(int fastThreshold) = 0; + CV_WRAP virtual int getFastThreshold() const = 0; + CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; +}; + +/** @brief Maximally stable extremal region extractor + +The class encapsulates all the parameters of the %MSER extraction algorithm (see [wiki +article](http://en.wikipedia.org/wiki/Maximally_stable_extremal_regions)). + +- there are two different implementation of %MSER: one for grey image, one for color image + +- the grey image algorithm is taken from: @cite nister2008linear ; the paper claims to be faster +than union-find method; it actually get 1.5~2m/s on my centrino L7200 1.2GHz laptop. + +- the color image algorithm is taken from: @cite forssen2007maximally ; it should be much slower +than grey image method ( 3~4 times ) + +- (Python) A complete example showing the use of the %MSER detector can be found at samples/python/mser.py +*/ +class CV_EXPORTS_W MSER : public Feature2D +{ +public: + /** @brief Full constructor for %MSER detector + + @param delta it compares \f$(size_{i}-size_{i-delta})/size_{i-delta}\f$ + @param min_area prune the area which smaller than minArea + @param max_area prune the area which bigger than maxArea + @param max_variation prune the area have similar size to its children + @param min_diversity for color image, trace back to cut off mser with diversity less than min_diversity + @param max_evolution for color image, the evolution steps + @param area_threshold for color image, the area threshold to cause re-initialize + @param min_margin for color image, ignore too small margin + @param edge_blur_size for color image, the aperture size for edge blur + */ + CV_WRAP static Ptr create( int delta=5, int min_area=60, int max_area=14400, + double max_variation=0.25, double min_diversity=.2, + int max_evolution=200, double area_threshold=1.01, + double min_margin=0.003, int edge_blur_size=5 ); + + /** @brief Detect %MSER regions + + @param image input image (8UC1, 8UC3 or 8UC4, must be greater or equal than 3x3) + @param msers resulting list of point sets + @param bboxes resulting bounding boxes + */ + CV_WRAP virtual void detectRegions( InputArray image, + CV_OUT std::vector >& msers, + CV_OUT std::vector& bboxes ) = 0; + + CV_WRAP virtual void setDelta(int delta) = 0; + CV_WRAP virtual int getDelta() const = 0; + + CV_WRAP virtual void setMinArea(int minArea) = 0; + CV_WRAP virtual int getMinArea() const = 0; + + CV_WRAP virtual void setMaxArea(int maxArea) = 0; + CV_WRAP virtual int getMaxArea() const = 0; + + CV_WRAP virtual void setMaxVariation(double maxVariation) = 0; + CV_WRAP virtual double getMaxVariation() const = 0; + + CV_WRAP virtual void setMinDiversity(double minDiversity) = 0; + CV_WRAP virtual double getMinDiversity() const = 0; + + CV_WRAP virtual void setMaxEvolution(int maxEvolution) = 0; + CV_WRAP virtual int getMaxEvolution() const = 0; + + CV_WRAP virtual void setAreaThreshold(double areaThreshold) = 0; + CV_WRAP virtual double getAreaThreshold() const = 0; + + CV_WRAP virtual void setMinMargin(double min_margin) = 0; + CV_WRAP virtual double getMinMargin() const = 0; + + CV_WRAP virtual void setEdgeBlurSize(int edge_blur_size) = 0; + CV_WRAP virtual int getEdgeBlurSize() const = 0; + + CV_WRAP virtual void setPass2Only(bool f) = 0; + CV_WRAP virtual bool getPass2Only() const = 0; + + CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; +}; + + +/** @brief Wrapping class for feature detection using the FAST method. : + */ +class CV_EXPORTS_W FastFeatureDetector : public Feature2D +{ +public: + enum DetectorType + { + TYPE_5_8 = 0, TYPE_7_12 = 1, TYPE_9_16 = 2 + }; + enum + { + THRESHOLD = 10000, NONMAX_SUPPRESSION=10001, FAST_N=10002 + }; + + + CV_WRAP static Ptr create( int threshold=10, + bool nonmaxSuppression=true, + FastFeatureDetector::DetectorType type=FastFeatureDetector::TYPE_9_16 ); + + CV_WRAP virtual void setThreshold(int threshold) = 0; + CV_WRAP virtual int getThreshold() const = 0; + + CV_WRAP virtual void setNonmaxSuppression(bool f) = 0; + CV_WRAP virtual bool getNonmaxSuppression() const = 0; + + CV_WRAP virtual void setType(FastFeatureDetector::DetectorType type) = 0; + CV_WRAP virtual FastFeatureDetector::DetectorType getType() const = 0; + CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; +}; + +/** @overload */ +CV_EXPORTS void FAST( InputArray image, CV_OUT std::vector& keypoints, + int threshold, bool nonmaxSuppression=true ); + +/** @brief Detects corners using the FAST algorithm + +@param image grayscale image where keypoints (corners) are detected. +@param keypoints keypoints detected on the image. +@param threshold threshold on difference between intensity of the central pixel and pixels of a +circle around this pixel. +@param nonmaxSuppression if true, non-maximum suppression is applied to detected corners +(keypoints). +@param type one of the three neighborhoods as defined in the paper: +FastFeatureDetector::TYPE_9_16, FastFeatureDetector::TYPE_7_12, +FastFeatureDetector::TYPE_5_8 + +Detects corners using the FAST algorithm by @cite Rosten06 . + +@note In Python API, types are given as cv.FAST_FEATURE_DETECTOR_TYPE_5_8, +cv.FAST_FEATURE_DETECTOR_TYPE_7_12 and cv.FAST_FEATURE_DETECTOR_TYPE_9_16. For corner +detection, use cv.FAST.detect() method. + */ +CV_EXPORTS void FAST( InputArray image, CV_OUT std::vector& keypoints, + int threshold, bool nonmaxSuppression, FastFeatureDetector::DetectorType type ); + + +/** @brief Wrapping class for feature detection using the AGAST method. : + */ +class CV_EXPORTS_W AgastFeatureDetector : public Feature2D +{ +public: + enum DetectorType + { + AGAST_5_8 = 0, AGAST_7_12d = 1, AGAST_7_12s = 2, OAST_9_16 = 3, + }; + + enum + { + THRESHOLD = 10000, NONMAX_SUPPRESSION = 10001, + }; + + CV_WRAP static Ptr create( int threshold=10, + bool nonmaxSuppression=true, + AgastFeatureDetector::DetectorType type = AgastFeatureDetector::OAST_9_16); + + CV_WRAP virtual void setThreshold(int threshold) = 0; + CV_WRAP virtual int getThreshold() const = 0; + + CV_WRAP virtual void setNonmaxSuppression(bool f) = 0; + CV_WRAP virtual bool getNonmaxSuppression() const = 0; + + CV_WRAP virtual void setType(AgastFeatureDetector::DetectorType type) = 0; + CV_WRAP virtual AgastFeatureDetector::DetectorType getType() const = 0; + CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; +}; + +/** @overload */ +CV_EXPORTS void AGAST( InputArray image, CV_OUT std::vector& keypoints, + int threshold, bool nonmaxSuppression=true ); + +/** @brief Detects corners using the AGAST algorithm + +@param image grayscale image where keypoints (corners) are detected. +@param keypoints keypoints detected on the image. +@param threshold threshold on difference between intensity of the central pixel and pixels of a +circle around this pixel. +@param nonmaxSuppression if true, non-maximum suppression is applied to detected corners +(keypoints). +@param type one of the four neighborhoods as defined in the paper: +AgastFeatureDetector::AGAST_5_8, AgastFeatureDetector::AGAST_7_12d, +AgastFeatureDetector::AGAST_7_12s, AgastFeatureDetector::OAST_9_16 + +For non-Intel platforms, there is a tree optimised variant of AGAST with same numerical results. +The 32-bit binary tree tables were generated automatically from original code using perl script. +The perl script and examples of tree generation are placed in features2d/doc folder. +Detects corners using the AGAST algorithm by @cite mair2010_agast . + + */ +CV_EXPORTS void AGAST( InputArray image, CV_OUT std::vector& keypoints, + int threshold, bool nonmaxSuppression, AgastFeatureDetector::DetectorType type ); + +/** @brief Wrapping class for feature detection using the goodFeaturesToTrack function. : + */ +class CV_EXPORTS_W GFTTDetector : public Feature2D +{ +public: + CV_WRAP static Ptr create( int maxCorners=1000, double qualityLevel=0.01, double minDistance=1, + int blockSize=3, bool useHarrisDetector=false, double k=0.04 ); + CV_WRAP static Ptr create( int maxCorners, double qualityLevel, double minDistance, + int blockSize, int gradiantSize, bool useHarrisDetector=false, double k=0.04 ); + CV_WRAP virtual void setMaxFeatures(int maxFeatures) = 0; + CV_WRAP virtual int getMaxFeatures() const = 0; + + CV_WRAP virtual void setQualityLevel(double qlevel) = 0; + CV_WRAP virtual double getQualityLevel() const = 0; + + CV_WRAP virtual void setMinDistance(double minDistance) = 0; + CV_WRAP virtual double getMinDistance() const = 0; + + CV_WRAP virtual void setBlockSize(int blockSize) = 0; + CV_WRAP virtual int getBlockSize() const = 0; + + CV_WRAP virtual void setGradientSize(int gradientSize_) = 0; + CV_WRAP virtual int getGradientSize() = 0; + + CV_WRAP virtual void setHarrisDetector(bool val) = 0; + CV_WRAP virtual bool getHarrisDetector() const = 0; + + CV_WRAP virtual void setK(double k) = 0; + CV_WRAP virtual double getK() const = 0; + CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; +}; + +/** @brief Class for extracting blobs from an image. : + +The class implements a simple algorithm for extracting blobs from an image: + +1. Convert the source image to binary images by applying thresholding with several thresholds from + minThreshold (inclusive) to maxThreshold (exclusive) with distance thresholdStep between + neighboring thresholds. +2. Extract connected components from every binary image by findContours and calculate their + centers. +3. Group centers from several binary images by their coordinates. Close centers form one group that + corresponds to one blob, which is controlled by the minDistBetweenBlobs parameter. +4. From the groups, estimate final centers of blobs and their radiuses and return as locations and + sizes of keypoints. + +This class performs several filtrations of returned blobs. You should set filterBy\* to true/false +to turn on/off corresponding filtration. Available filtrations: + +- **By color**. This filter compares the intensity of a binary image at the center of a blob to +blobColor. If they differ, the blob is filtered out. Use blobColor = 0 to extract dark blobs +and blobColor = 255 to extract light blobs. +- **By area**. Extracted blobs have an area between minArea (inclusive) and maxArea (exclusive). +- **By circularity**. Extracted blobs have circularity +(\f$\frac{4*\pi*Area}{perimeter * perimeter}\f$) between minCircularity (inclusive) and +maxCircularity (exclusive). +- **By ratio of the minimum inertia to maximum inertia**. Extracted blobs have this ratio +between minInertiaRatio (inclusive) and maxInertiaRatio (exclusive). +- **By convexity**. Extracted blobs have convexity (area / area of blob convex hull) between +minConvexity (inclusive) and maxConvexity (exclusive). + +Default values of parameters are tuned to extract dark circular blobs. + */ +class CV_EXPORTS_W SimpleBlobDetector : public Feature2D +{ +public: + struct CV_EXPORTS_W_SIMPLE Params + { + CV_WRAP Params(); + CV_PROP_RW float thresholdStep; + CV_PROP_RW float minThreshold; + CV_PROP_RW float maxThreshold; + CV_PROP_RW size_t minRepeatability; + CV_PROP_RW float minDistBetweenBlobs; + + CV_PROP_RW bool filterByColor; + CV_PROP_RW uchar blobColor; + + CV_PROP_RW bool filterByArea; + CV_PROP_RW float minArea, maxArea; + + CV_PROP_RW bool filterByCircularity; + CV_PROP_RW float minCircularity, maxCircularity; + + CV_PROP_RW bool filterByInertia; + CV_PROP_RW float minInertiaRatio, maxInertiaRatio; + + CV_PROP_RW bool filterByConvexity; + CV_PROP_RW float minConvexity, maxConvexity; + + CV_PROP_RW bool collectContours; + + void read( const FileNode& fn ); + void write( FileStorage& fs ) const; + }; + + CV_WRAP static Ptr + create(const SimpleBlobDetector::Params ¶meters = SimpleBlobDetector::Params()); + + CV_WRAP virtual void setParams(const SimpleBlobDetector::Params& params ) = 0; + CV_WRAP virtual SimpleBlobDetector::Params getParams() const = 0; + + CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; + CV_WRAP virtual const std::vector >& getBlobContours() const; +}; + + +/** @brief Class implementing the KAZE keypoint detector and descriptor extractor, described in @cite ABD12 . + +@note AKAZE descriptor can only be used with KAZE or AKAZE keypoints .. [ABD12] KAZE Features. Pablo +F. Alcantarilla, Adrien Bartoli and Andrew J. Davison. In European Conference on Computer Vision +(ECCV), Fiorenze, Italy, October 2012. +*/ +class CV_EXPORTS_W KAZE : public Feature2D +{ +public: + enum DiffusivityType + { + DIFF_PM_G1 = 0, + DIFF_PM_G2 = 1, + DIFF_WEICKERT = 2, + DIFF_CHARBONNIER = 3 + }; + + /** @brief The KAZE constructor + + @param extended Set to enable extraction of extended (128-byte) descriptor. + @param upright Set to enable use of upright descriptors (non rotation-invariant). + @param threshold Detector response threshold to accept point + @param nOctaves Maximum octave evolution of the image + @param nOctaveLayers Default number of sublevels per scale level + @param diffusivity Diffusivity type. DIFF_PM_G1, DIFF_PM_G2, DIFF_WEICKERT or + DIFF_CHARBONNIER + */ + CV_WRAP static Ptr create(bool extended=false, bool upright=false, + float threshold = 0.001f, + int nOctaves = 4, int nOctaveLayers = 4, + KAZE::DiffusivityType diffusivity = KAZE::DIFF_PM_G2); + + CV_WRAP virtual void setExtended(bool extended) = 0; + CV_WRAP virtual bool getExtended() const = 0; + + CV_WRAP virtual void setUpright(bool upright) = 0; + CV_WRAP virtual bool getUpright() const = 0; + + CV_WRAP virtual void setThreshold(double threshold) = 0; + CV_WRAP virtual double getThreshold() const = 0; + + CV_WRAP virtual void setNOctaves(int octaves) = 0; + CV_WRAP virtual int getNOctaves() const = 0; + + CV_WRAP virtual void setNOctaveLayers(int octaveLayers) = 0; + CV_WRAP virtual int getNOctaveLayers() const = 0; + + CV_WRAP virtual void setDiffusivity(KAZE::DiffusivityType diff) = 0; + CV_WRAP virtual KAZE::DiffusivityType getDiffusivity() const = 0; + CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; +}; + +/** @brief Class implementing the AKAZE keypoint detector and descriptor extractor, described in @cite ANB13. + +@details AKAZE descriptors can only be used with KAZE or AKAZE keypoints. This class is thread-safe. + +@note When you need descriptors use Feature2D::detectAndCompute, which +provides better performance. When using Feature2D::detect followed by +Feature2D::compute scale space pyramid is computed twice. + +@note AKAZE implements T-API. When image is passed as UMat some parts of the algorithm +will use OpenCL. + +@note [ANB13] Fast Explicit Diffusion for Accelerated Features in Nonlinear +Scale Spaces. Pablo F. Alcantarilla, Jesús Nuevo and Adrien Bartoli. In +British Machine Vision Conference (BMVC), Bristol, UK, September 2013. + +*/ +class CV_EXPORTS_W AKAZE : public Feature2D +{ +public: + // AKAZE descriptor type + enum DescriptorType + { + DESCRIPTOR_KAZE_UPRIGHT = 2, ///< Upright descriptors, not invariant to rotation + DESCRIPTOR_KAZE = 3, + DESCRIPTOR_MLDB_UPRIGHT = 4, ///< Upright descriptors, not invariant to rotation + DESCRIPTOR_MLDB = 5 + }; + + /** @brief The AKAZE constructor + + @param descriptor_type Type of the extracted descriptor: DESCRIPTOR_KAZE, + DESCRIPTOR_KAZE_UPRIGHT, DESCRIPTOR_MLDB or DESCRIPTOR_MLDB_UPRIGHT. + @param descriptor_size Size of the descriptor in bits. 0 -\> Full size + @param descriptor_channels Number of channels in the descriptor (1, 2, 3) + @param threshold Detector response threshold to accept point + @param nOctaves Maximum octave evolution of the image + @param nOctaveLayers Default number of sublevels per scale level + @param diffusivity Diffusivity type. DIFF_PM_G1, DIFF_PM_G2, DIFF_WEICKERT or + DIFF_CHARBONNIER + @param max_points Maximum amount of returned points. In case if image contains + more features, then the features with highest response are returned. + Negative value means no limitation. + */ + CV_WRAP static Ptr create(AKAZE::DescriptorType descriptor_type = AKAZE::DESCRIPTOR_MLDB, + int descriptor_size = 0, int descriptor_channels = 3, + float threshold = 0.001f, int nOctaves = 4, + int nOctaveLayers = 4, KAZE::DiffusivityType diffusivity = KAZE::DIFF_PM_G2, + int max_points = -1); + + CV_WRAP virtual void setDescriptorType(AKAZE::DescriptorType dtype) = 0; + CV_WRAP virtual AKAZE::DescriptorType getDescriptorType() const = 0; + + CV_WRAP virtual void setDescriptorSize(int dsize) = 0; + CV_WRAP virtual int getDescriptorSize() const = 0; + + CV_WRAP virtual void setDescriptorChannels(int dch) = 0; + CV_WRAP virtual int getDescriptorChannels() const = 0; + + CV_WRAP virtual void setThreshold(double threshold) = 0; + CV_WRAP virtual double getThreshold() const = 0; + + CV_WRAP virtual void setNOctaves(int octaves) = 0; + CV_WRAP virtual int getNOctaves() const = 0; + + CV_WRAP virtual void setNOctaveLayers(int octaveLayers) = 0; + CV_WRAP virtual int getNOctaveLayers() const = 0; + + CV_WRAP virtual void setDiffusivity(KAZE::DiffusivityType diff) = 0; + CV_WRAP virtual KAZE::DiffusivityType getDiffusivity() const = 0; + CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; + + CV_WRAP virtual void setMaxPoints(int max_points) = 0; + CV_WRAP virtual int getMaxPoints() const = 0; +}; + + +/****************************************************************************************\ +* Distance * +\****************************************************************************************/ + +template +struct CV_EXPORTS Accumulator +{ + typedef T Type; +}; + +template<> struct Accumulator { typedef float Type; }; +template<> struct Accumulator { typedef float Type; }; +template<> struct Accumulator { typedef float Type; }; +template<> struct Accumulator { typedef float Type; }; + +/* + * Squared Euclidean distance functor + */ +template +struct CV_EXPORTS SL2 +{ + static const NormTypes normType = NORM_L2SQR; + typedef T ValueType; + typedef typename Accumulator::Type ResultType; + + ResultType operator()( const T* a, const T* b, int size ) const + { + return normL2Sqr(a, b, size); + } +}; + +/* + * Euclidean distance functor + */ +template +struct L2 +{ + static const NormTypes normType = NORM_L2; + typedef T ValueType; + typedef typename Accumulator::Type ResultType; + + ResultType operator()( const T* a, const T* b, int size ) const + { + return (ResultType)std::sqrt((double)normL2Sqr(a, b, size)); + } +}; + +/* + * Manhattan distance (city block distance) functor + */ +template +struct L1 +{ + static const NormTypes normType = NORM_L1; + typedef T ValueType; + typedef typename Accumulator::Type ResultType; + + ResultType operator()( const T* a, const T* b, int size ) const + { + return normL1(a, b, size); + } +}; + +//! @} features2d_main + +/****************************************************************************************\ +* DescriptorMatcher * +\****************************************************************************************/ + +//! @addtogroup features2d_match +//! @{ + +/** @brief Abstract base class for matching keypoint descriptors. + +It has two groups of match methods: for matching descriptors of an image with another image or with +an image set. + */ +class CV_EXPORTS_W DescriptorMatcher : public Algorithm +{ +public: + enum MatcherType + { + FLANNBASED = 1, + BRUTEFORCE = 2, + BRUTEFORCE_L1 = 3, + BRUTEFORCE_HAMMING = 4, + BRUTEFORCE_HAMMINGLUT = 5, + BRUTEFORCE_SL2 = 6 + }; + + virtual ~DescriptorMatcher(); + + /** @brief Adds descriptors to train a CPU(trainDescCollectionis) or GPU(utrainDescCollectionis) descriptor + collection. + + If the collection is not empty, the new descriptors are added to existing train descriptors. + + @param descriptors Descriptors to add. Each descriptors[i] is a set of descriptors from the same + train image. + */ + CV_WRAP virtual void add( InputArrayOfArrays descriptors ); + + /** @brief Returns a constant link to the train descriptor collection trainDescCollection . + */ + CV_WRAP const std::vector& getTrainDescriptors() const; + + /** @brief Clears the train descriptor collections. + */ + CV_WRAP virtual void clear() CV_OVERRIDE; + + /** @brief Returns true if there are no train descriptors in the both collections. + */ + CV_WRAP virtual bool empty() const CV_OVERRIDE; + + /** @brief Returns true if the descriptor matcher supports masking permissible matches. + */ + CV_WRAP virtual bool isMaskSupported() const = 0; + + /** @brief Trains a descriptor matcher + + Trains a descriptor matcher (for example, the flann index). In all methods to match, the method + train() is run every time before matching. Some descriptor matchers (for example, BruteForceMatcher) + have an empty implementation of this method. Other matchers really train their inner structures (for + example, FlannBasedMatcher trains flann::Index ). + */ + CV_WRAP virtual void train(); + + /** @brief Finds the best match for each descriptor from a query set. + + @param queryDescriptors Query set of descriptors. + @param trainDescriptors Train set of descriptors. This set is not added to the train descriptors + collection stored in the class object. + @param matches Matches. If a query descriptor is masked out in mask , no match is added for this + descriptor. So, matches size may be smaller than the query descriptors count. + @param mask Mask specifying permissible matches between an input query and train matrices of + descriptors. + + In the first variant of this method, the train descriptors are passed as an input argument. In the + second variant of the method, train descriptors collection that was set by DescriptorMatcher::add is + used. Optional mask (or masks) can be passed to specify which query and training descriptors can be + matched. Namely, queryDescriptors[i] can be matched with trainDescriptors[j] only if + mask.at\(i,j) is non-zero. + */ + CV_WRAP void match( InputArray queryDescriptors, InputArray trainDescriptors, + CV_OUT std::vector& matches, InputArray mask=noArray() ) const; + + /** @brief Finds the k best matches for each descriptor from a query set. + + @param queryDescriptors Query set of descriptors. + @param trainDescriptors Train set of descriptors. This set is not added to the train descriptors + collection stored in the class object. + @param mask Mask specifying permissible matches between an input query and train matrices of + descriptors. + @param matches Matches. Each matches[i] is k or less matches for the same query descriptor. + @param k Count of best matches found per each query descriptor or less if a query descriptor has + less than k possible matches in total. + @param compactResult Parameter used when the mask (or masks) is not empty. If compactResult is + false, the matches vector has the same size as queryDescriptors rows. If compactResult is true, + the matches vector does not contain matches for fully masked-out query descriptors. + + These extended variants of DescriptorMatcher::match methods find several best matches for each query + descriptor. The matches are returned in the distance increasing order. See DescriptorMatcher::match + for the details about query and train descriptors. + */ + CV_WRAP void knnMatch( InputArray queryDescriptors, InputArray trainDescriptors, + CV_OUT std::vector >& matches, int k, + InputArray mask=noArray(), bool compactResult=false ) const; + + /** @brief For each query descriptor, finds the training descriptors not farther than the specified distance. + + @param queryDescriptors Query set of descriptors. + @param trainDescriptors Train set of descriptors. This set is not added to the train descriptors + collection stored in the class object. + @param matches Found matches. + @param compactResult Parameter used when the mask (or masks) is not empty. If compactResult is + false, the matches vector has the same size as queryDescriptors rows. If compactResult is true, + the matches vector does not contain matches for fully masked-out query descriptors. + @param maxDistance Threshold for the distance between matched descriptors. Distance means here + metric distance (e.g. Hamming distance), not the distance between coordinates (which is measured + in Pixels)! + @param mask Mask specifying permissible matches between an input query and train matrices of + descriptors. + + For each query descriptor, the methods find such training descriptors that the distance between the + query descriptor and the training descriptor is equal or smaller than maxDistance. Found matches are + returned in the distance increasing order. + */ + CV_WRAP void radiusMatch( InputArray queryDescriptors, InputArray trainDescriptors, + CV_OUT std::vector >& matches, float maxDistance, + InputArray mask=noArray(), bool compactResult=false ) const; + + /** @overload + @param queryDescriptors Query set of descriptors. + @param matches Matches. If a query descriptor is masked out in mask , no match is added for this + descriptor. So, matches size may be smaller than the query descriptors count. + @param masks Set of masks. Each masks[i] specifies permissible matches between the input query + descriptors and stored train descriptors from the i-th image trainDescCollection[i]. + */ + CV_WRAP void match( InputArray queryDescriptors, CV_OUT std::vector& matches, + InputArrayOfArrays masks=noArray() ); + /** @overload + @param queryDescriptors Query set of descriptors. + @param matches Matches. Each matches[i] is k or less matches for the same query descriptor. + @param k Count of best matches found per each query descriptor or less if a query descriptor has + less than k possible matches in total. + @param masks Set of masks. Each masks[i] specifies permissible matches between the input query + descriptors and stored train descriptors from the i-th image trainDescCollection[i]. + @param compactResult Parameter used when the mask (or masks) is not empty. If compactResult is + false, the matches vector has the same size as queryDescriptors rows. If compactResult is true, + the matches vector does not contain matches for fully masked-out query descriptors. + */ + CV_WRAP void knnMatch( InputArray queryDescriptors, CV_OUT std::vector >& matches, int k, + InputArrayOfArrays masks=noArray(), bool compactResult=false ); + /** @overload + @param queryDescriptors Query set of descriptors. + @param matches Found matches. + @param maxDistance Threshold for the distance between matched descriptors. Distance means here + metric distance (e.g. Hamming distance), not the distance between coordinates (which is measured + in Pixels)! + @param masks Set of masks. Each masks[i] specifies permissible matches between the input query + descriptors and stored train descriptors from the i-th image trainDescCollection[i]. + @param compactResult Parameter used when the mask (or masks) is not empty. If compactResult is + false, the matches vector has the same size as queryDescriptors rows. If compactResult is true, + the matches vector does not contain matches for fully masked-out query descriptors. + */ + CV_WRAP void radiusMatch( InputArray queryDescriptors, CV_OUT std::vector >& matches, float maxDistance, + InputArrayOfArrays masks=noArray(), bool compactResult=false ); + + + CV_WRAP void write( const String& fileName ) const + { + FileStorage fs(fileName, FileStorage::WRITE); + write(fs); + } + + CV_WRAP void read( const String& fileName ) + { + FileStorage fs(fileName, FileStorage::READ); + read(fs.root()); + } + // Reads matcher object from a file node + // see corresponding cv::Algorithm method + CV_WRAP virtual void read( const FileNode& ) CV_OVERRIDE; + // Writes matcher object to a file storage + virtual void write( FileStorage& ) const CV_OVERRIDE; + + /** @brief Clones the matcher. + + @param emptyTrainData If emptyTrainData is false, the method creates a deep copy of the object, + that is, copies both parameters and train data. If emptyTrainData is true, the method creates an + object copy with the current parameters but with empty train data. + */ + CV_WRAP CV_NODISCARD_STD virtual Ptr clone( bool emptyTrainData=false ) const = 0; + + /** @brief Creates a descriptor matcher of a given type with the default parameters (using default + constructor). + + @param descriptorMatcherType Descriptor matcher type. Now the following matcher types are + supported: + - `BruteForce` (it uses L2 ) + - `BruteForce-L1` + - `BruteForce-Hamming` + - `BruteForce-Hamming(2)` + - `FlannBased` + */ + CV_WRAP static Ptr create( const String& descriptorMatcherType ); + + CV_WRAP static Ptr create( const DescriptorMatcher::MatcherType& matcherType ); + + + // see corresponding cv::Algorithm method + CV_WRAP inline void write(FileStorage& fs, const String& name) const { Algorithm::write(fs, name); } +#if CV_VERSION_MAJOR < 5 + inline void write(const Ptr& fs, const String& name) const { CV_Assert(fs); Algorithm::write(*fs, name); } +#endif + +protected: + /** + * Class to work with descriptors from several images as with one merged matrix. + * It is used e.g. in FlannBasedMatcher. + */ + class CV_EXPORTS DescriptorCollection + { + public: + DescriptorCollection(); + DescriptorCollection( const DescriptorCollection& collection ); + virtual ~DescriptorCollection(); + + // Vector of matrices "descriptors" will be merged to one matrix "mergedDescriptors" here. + void set( const std::vector& descriptors ); + virtual void clear(); + + const Mat& getDescriptors() const; + Mat getDescriptor( int imgIdx, int localDescIdx ) const; + Mat getDescriptor( int globalDescIdx ) const; + void getLocalIdx( int globalDescIdx, int& imgIdx, int& localDescIdx ) const; + + int size() const; + + protected: + Mat mergedDescriptors; + std::vector startIdxs; + }; + + //! In fact the matching is implemented only by the following two methods. These methods suppose + //! that the class object has been trained already. Public match methods call these methods + //! after calling train(). + virtual void knnMatchImpl( InputArray queryDescriptors, std::vector >& matches, int k, + InputArrayOfArrays masks=noArray(), bool compactResult=false ) = 0; + virtual void radiusMatchImpl( InputArray queryDescriptors, std::vector >& matches, float maxDistance, + InputArrayOfArrays masks=noArray(), bool compactResult=false ) = 0; + + static bool isPossibleMatch( InputArray mask, int queryIdx, int trainIdx ); + static bool isMaskedOut( InputArrayOfArrays masks, int queryIdx ); + + CV_NODISCARD_STD static Mat clone_op( Mat m ) { return m.clone(); } + void checkMasks( InputArrayOfArrays masks, int queryDescriptorsCount ) const; + + //! Collection of descriptors from train images. + std::vector trainDescCollection; + std::vector utrainDescCollection; +}; + +/** @brief Brute-force descriptor matcher. + +For each descriptor in the first set, this matcher finds the closest descriptor in the second set +by trying each one. This descriptor matcher supports masking permissible matches of descriptor +sets. + */ +class CV_EXPORTS_W BFMatcher : public DescriptorMatcher +{ +public: + /** @brief Brute-force matcher constructor (obsolete). Please use BFMatcher.create() + * + * + */ + CV_WRAP BFMatcher( int normType=NORM_L2, bool crossCheck=false ); + + virtual ~BFMatcher() {} + + virtual bool isMaskSupported() const CV_OVERRIDE { return true; } + + /** @brief Brute-force matcher create method. + @param normType One of NORM_L1, NORM_L2, NORM_HAMMING, NORM_HAMMING2. L1 and L2 norms are + preferable choices for SIFT and SURF descriptors, NORM_HAMMING should be used with ORB, BRISK and + BRIEF, NORM_HAMMING2 should be used with ORB when WTA_K==3 or 4 (see ORB::ORB constructor + description). + @param crossCheck If it is false, this is will be default BFMatcher behaviour when it finds the k + nearest neighbors for each query descriptor. If crossCheck==true, then the knnMatch() method with + k=1 will only return pairs (i,j) such that for i-th query descriptor the j-th descriptor in the + matcher's collection is the nearest and vice versa, i.e. the BFMatcher will only return consistent + pairs. Such technique usually produces best results with minimal number of outliers when there are + enough matches. This is alternative to the ratio test, used by D. Lowe in SIFT paper. + */ + CV_WRAP static Ptr create( int normType=NORM_L2, bool crossCheck=false ) ; + + CV_NODISCARD_STD virtual Ptr clone( bool emptyTrainData=false ) const CV_OVERRIDE; +protected: + virtual void knnMatchImpl( InputArray queryDescriptors, std::vector >& matches, int k, + InputArrayOfArrays masks=noArray(), bool compactResult=false ) CV_OVERRIDE; + virtual void radiusMatchImpl( InputArray queryDescriptors, std::vector >& matches, float maxDistance, + InputArrayOfArrays masks=noArray(), bool compactResult=false ) CV_OVERRIDE; + + int normType; + bool crossCheck; +}; + +#if defined(HAVE_OPENCV_FLANN) || defined(CV_DOXYGEN) + +/** @brief Flann-based descriptor matcher. + +This matcher trains cv::flann::Index on a train descriptor collection and calls its nearest search +methods to find the best matches. So, this matcher may be faster when matching a large train +collection than the brute force matcher. FlannBasedMatcher does not support masking permissible +matches of descriptor sets because flann::Index does not support this. : + */ +class CV_EXPORTS_W FlannBasedMatcher : public DescriptorMatcher +{ +public: + CV_WRAP FlannBasedMatcher( const Ptr& indexParams=makePtr(), + const Ptr& searchParams=makePtr() ); + + virtual void add( InputArrayOfArrays descriptors ) CV_OVERRIDE; + virtual void clear() CV_OVERRIDE; + + // Reads matcher object from a file node + virtual void read( const FileNode& ) CV_OVERRIDE; + // Writes matcher object to a file storage + virtual void write( FileStorage& ) const CV_OVERRIDE; + + virtual void train() CV_OVERRIDE; + virtual bool isMaskSupported() const CV_OVERRIDE; + + CV_WRAP static Ptr create(); + + CV_NODISCARD_STD virtual Ptr clone( bool emptyTrainData=false ) const CV_OVERRIDE; +protected: + static void convertToDMatches( const DescriptorCollection& descriptors, + const Mat& indices, const Mat& distances, + std::vector >& matches ); + + virtual void knnMatchImpl( InputArray queryDescriptors, std::vector >& matches, int k, + InputArrayOfArrays masks=noArray(), bool compactResult=false ) CV_OVERRIDE; + virtual void radiusMatchImpl( InputArray queryDescriptors, std::vector >& matches, float maxDistance, + InputArrayOfArrays masks=noArray(), bool compactResult=false ) CV_OVERRIDE; + + Ptr indexParams; + Ptr searchParams; + Ptr flannIndex; + + DescriptorCollection mergedDescriptors; + int addedDescCount; +}; + +#endif + +//! @} features2d_match + +/****************************************************************************************\ +* Drawing functions * +\****************************************************************************************/ + +//! @addtogroup features2d_draw +//! @{ + +enum struct DrawMatchesFlags +{ + DEFAULT = 0, //!< Output image matrix will be created (Mat::create), + //!< i.e. existing memory of output image may be reused. + //!< Two source image, matches and single keypoints will be drawn. + //!< For each keypoint only the center point will be drawn (without + //!< the circle around keypoint with keypoint size and orientation). + DRAW_OVER_OUTIMG = 1, //!< Output image matrix will not be created (Mat::create). + //!< Matches will be drawn on existing content of output image. + NOT_DRAW_SINGLE_POINTS = 2, //!< Single keypoints will not be drawn. + DRAW_RICH_KEYPOINTS = 4 //!< For each keypoint the circle around keypoint with keypoint size and + //!< orientation will be drawn. +}; +CV_ENUM_FLAGS(DrawMatchesFlags) + +/** @brief Draws keypoints. + +@param image Source image. +@param keypoints Keypoints from the source image. +@param outImage Output image. Its content depends on the flags value defining what is drawn in the +output image. See possible flags bit values below. +@param color Color of keypoints. +@param flags Flags setting drawing features. Possible flags bit values are defined by +DrawMatchesFlags. See details above in drawMatches . + +@note +For Python API, flags are modified as cv.DRAW_MATCHES_FLAGS_DEFAULT, +cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS, cv.DRAW_MATCHES_FLAGS_DRAW_OVER_OUTIMG, +cv.DRAW_MATCHES_FLAGS_NOT_DRAW_SINGLE_POINTS + */ +CV_EXPORTS_W void drawKeypoints( InputArray image, const std::vector& keypoints, InputOutputArray outImage, + const Scalar& color=Scalar::all(-1), DrawMatchesFlags flags=DrawMatchesFlags::DEFAULT ); + +/** @brief Draws the found matches of keypoints from two images. + +@param img1 First source image. +@param keypoints1 Keypoints from the first source image. +@param img2 Second source image. +@param keypoints2 Keypoints from the second source image. +@param matches1to2 Matches from the first image to the second one, which means that keypoints1[i] +has a corresponding point in keypoints2[matches[i]] . +@param outImg Output image. Its content depends on the flags value defining what is drawn in the +output image. See possible flags bit values below. +@param matchColor Color of matches (lines and connected keypoints). If matchColor==Scalar::all(-1) +, the color is generated randomly. +@param singlePointColor Color of single keypoints (circles), which means that keypoints do not +have the matches. If singlePointColor==Scalar::all(-1) , the color is generated randomly. +@param matchesMask Mask determining which matches are drawn. If the mask is empty, all matches are +drawn. +@param flags Flags setting drawing features. Possible flags bit values are defined by +DrawMatchesFlags. + +This function draws matches of keypoints from two images in the output image. Match is a line +connecting two keypoints (circles). See cv::DrawMatchesFlags. + */ +CV_EXPORTS_W void drawMatches( InputArray img1, const std::vector& keypoints1, + InputArray img2, const std::vector& keypoints2, + const std::vector& matches1to2, InputOutputArray outImg, + const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1), + const std::vector& matchesMask=std::vector(), DrawMatchesFlags flags=DrawMatchesFlags::DEFAULT ); + +/** @overload */ +CV_EXPORTS_W void drawMatches( InputArray img1, const std::vector& keypoints1, + InputArray img2, const std::vector& keypoints2, + const std::vector& matches1to2, InputOutputArray outImg, + const int matchesThickness, const Scalar& matchColor=Scalar::all(-1), + const Scalar& singlePointColor=Scalar::all(-1), const std::vector& matchesMask=std::vector(), + DrawMatchesFlags flags=DrawMatchesFlags::DEFAULT ); + +CV_EXPORTS_AS(drawMatchesKnn) void drawMatches( InputArray img1, const std::vector& keypoints1, + InputArray img2, const std::vector& keypoints2, + const std::vector >& matches1to2, InputOutputArray outImg, + const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1), + const std::vector >& matchesMask=std::vector >(), DrawMatchesFlags flags=DrawMatchesFlags::DEFAULT ); + +//! @} features2d_draw + +/****************************************************************************************\ +* Functions to evaluate the feature detectors and [generic] descriptor extractors * +\****************************************************************************************/ + +//! @addtogroup features2d_main +//! @{ + +CV_EXPORTS void evaluateFeatureDetector( const Mat& img1, const Mat& img2, const Mat& H1to2, + std::vector* keypoints1, std::vector* keypoints2, + float& repeatability, int& correspCount, + const Ptr& fdetector=Ptr() ); + +CV_EXPORTS void computeRecallPrecisionCurve( const std::vector >& matches1to2, + const std::vector >& correctMatches1to2Mask, + std::vector& recallPrecisionCurve ); + +CV_EXPORTS float getRecall( const std::vector& recallPrecisionCurve, float l_precision ); +CV_EXPORTS int getNearestPoint( const std::vector& recallPrecisionCurve, float l_precision ); + +//! @} + +/****************************************************************************************\ +* Bag of visual words * +\****************************************************************************************/ + +//! @addtogroup features2d_category +//! @{ + +/** @brief Abstract base class for training the *bag of visual words* vocabulary from a set of descriptors. + +For details, see, for example, *Visual Categorization with Bags of Keypoints* by Gabriella Csurka, +Christopher R. Dance, Lixin Fan, Jutta Willamowski, Cedric Bray, 2004. : + */ +class CV_EXPORTS_W BOWTrainer +{ +public: + BOWTrainer(); + virtual ~BOWTrainer(); + + /** @brief Adds descriptors to a training set. + + @param descriptors Descriptors to add to a training set. Each row of the descriptors matrix is a + descriptor. + + The training set is clustered using clustermethod to construct the vocabulary. + */ + CV_WRAP void add( const Mat& descriptors ); + + /** @brief Returns a training set of descriptors. + */ + CV_WRAP const std::vector& getDescriptors() const; + + /** @brief Returns the count of all descriptors stored in the training set. + */ + CV_WRAP int descriptorsCount() const; + + CV_WRAP virtual void clear(); + + /** @overload */ + CV_WRAP virtual Mat cluster() const = 0; + + /** @brief Clusters train descriptors. + + @param descriptors Descriptors to cluster. Each row of the descriptors matrix is a descriptor. + Descriptors are not added to the inner train descriptor set. + + The vocabulary consists of cluster centers. So, this method returns the vocabulary. In the first + variant of the method, train descriptors stored in the object are clustered. In the second variant, + input descriptors are clustered. + */ + CV_WRAP virtual Mat cluster( const Mat& descriptors ) const = 0; + +protected: + std::vector descriptors; + int size; +}; + +/** @brief kmeans -based class to train visual vocabulary using the *bag of visual words* approach. : + */ +class CV_EXPORTS_W BOWKMeansTrainer : public BOWTrainer +{ +public: + /** @brief The constructor. + + @see cv::kmeans + */ + CV_WRAP BOWKMeansTrainer( int clusterCount, const TermCriteria& termcrit=TermCriteria(), + int attempts=3, int flags=KMEANS_PP_CENTERS ); + virtual ~BOWKMeansTrainer(); + + // Returns trained vocabulary (i.e. cluster centers). + CV_WRAP virtual Mat cluster() const CV_OVERRIDE; + CV_WRAP virtual Mat cluster( const Mat& descriptors ) const CV_OVERRIDE; + +protected: + + int clusterCount; + TermCriteria termcrit; + int attempts; + int flags; +}; + +/** @brief Class to compute an image descriptor using the *bag of visual words*. + +Such a computation consists of the following steps: + +1. Compute descriptors for a given image and its keypoints set. +2. Find the nearest visual words from the vocabulary for each keypoint descriptor. +3. Compute the bag-of-words image descriptor as is a normalized histogram of vocabulary words +encountered in the image. The i-th bin of the histogram is a frequency of i-th word of the +vocabulary in the given image. + */ +class CV_EXPORTS_W BOWImgDescriptorExtractor +{ +public: + /** @brief The constructor. + + @param dextractor Descriptor extractor that is used to compute descriptors for an input image and + its keypoints. + @param dmatcher Descriptor matcher that is used to find the nearest word of the trained vocabulary + for each keypoint descriptor of the image. + */ + CV_WRAP BOWImgDescriptorExtractor( const Ptr& dextractor, + const Ptr& dmatcher ); + /** @overload */ + BOWImgDescriptorExtractor( const Ptr& dmatcher ); + virtual ~BOWImgDescriptorExtractor(); + + /** @brief Sets a visual vocabulary. + + @param vocabulary Vocabulary (can be trained using the inheritor of BOWTrainer ). Each row of the + vocabulary is a visual word (cluster center). + */ + CV_WRAP void setVocabulary( const Mat& vocabulary ); + + /** @brief Returns the set vocabulary. + */ + CV_WRAP const Mat& getVocabulary() const; + + /** @brief Computes an image descriptor using the set visual vocabulary. + + @param image Image, for which the descriptor is computed. + @param keypoints Keypoints detected in the input image. + @param imgDescriptor Computed output image descriptor. + @param pointIdxsOfClusters Indices of keypoints that belong to the cluster. This means that + pointIdxsOfClusters[i] are keypoint indices that belong to the i -th cluster (word of vocabulary) + returned if it is non-zero. + @param descriptors Descriptors of the image keypoints that are returned if they are non-zero. + */ + void compute( InputArray image, std::vector& keypoints, OutputArray imgDescriptor, + std::vector >* pointIdxsOfClusters=0, Mat* descriptors=0 ); + /** @overload + @param keypointDescriptors Computed descriptors to match with vocabulary. + @param imgDescriptor Computed output image descriptor. + @param pointIdxsOfClusters Indices of keypoints that belong to the cluster. This means that + pointIdxsOfClusters[i] are keypoint indices that belong to the i -th cluster (word of vocabulary) + returned if it is non-zero. + */ + void compute( InputArray keypointDescriptors, OutputArray imgDescriptor, + std::vector >* pointIdxsOfClusters=0 ); + // compute() is not constant because DescriptorMatcher::match is not constant + + CV_WRAP_AS(compute) void compute2( const Mat& image, std::vector& keypoints, CV_OUT Mat& imgDescriptor ) + { compute(image,keypoints,imgDescriptor); } + + /** @brief Returns an image descriptor size if the vocabulary is set. Otherwise, it returns 0. + */ + CV_WRAP int descriptorSize() const; + + /** @brief Returns an image descriptor type. + */ + CV_WRAP int descriptorType() const; + +protected: + Mat vocabulary; + Ptr dextractor; + Ptr dmatcher; +}; + +//! @} features2d_category + +} /* namespace cv */ + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/features2d/features2d.hpp b/3rdParty/opencv-4.11.0/opencv2/features2d/features2d.hpp index e81df0ad08..69c97639ee 100644 --- a/3rdParty/opencv-4.11.0/opencv2/features2d/features2d.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/features2d/features2d.hpp @@ -1,48 +1,48 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifdef __OPENCV_BUILD -#error this is a compatibility header which should not be used inside the OpenCV library -#endif - -#include "opencv2/features2d.hpp" +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/features2d.hpp" diff --git a/3rdParty/opencv-4.11.0/opencv2/features2d/hal/interface.h b/3rdParty/opencv-4.11.0/opencv2/features2d/hal/interface.h index bc3b084264..4ce2b999fd 100644 --- a/3rdParty/opencv-4.11.0/opencv2/features2d/hal/interface.h +++ b/3rdParty/opencv-4.11.0/opencv2/features2d/hal/interface.h @@ -1,33 +1,33 @@ -#ifndef OPENCV_FEATURE2D_HAL_INTERFACE_H -#define OPENCV_FEATURE2D_HAL_INTERFACE_H - -#include "opencv2/core/cvdef.h" -//! @addtogroup features2d_hal_interface -//! @{ - -//! @name Fast feature detector types -//! @sa cv::FastFeatureDetector -//! @{ -#define CV_HAL_TYPE_5_8 0 -#define CV_HAL_TYPE_7_12 1 -#define CV_HAL_TYPE_9_16 2 -//! @} - -//! @name Key point -//! @sa cv::KeyPoint -//! @{ -struct CV_EXPORTS cvhalKeyPoint -{ - float x; - float y; - float size; - float angle; - float response; - int octave; - int class_id; -}; -//! @} - -//! @} - -#endif +#ifndef OPENCV_FEATURE2D_HAL_INTERFACE_H +#define OPENCV_FEATURE2D_HAL_INTERFACE_H + +#include "opencv2/core/cvdef.h" +//! @addtogroup features2d_hal_interface +//! @{ + +//! @name Fast feature detector types +//! @sa cv::FastFeatureDetector +//! @{ +#define CV_HAL_TYPE_5_8 0 +#define CV_HAL_TYPE_7_12 1 +#define CV_HAL_TYPE_9_16 2 +//! @} + +//! @name Key point +//! @sa cv::KeyPoint +//! @{ +struct CV_EXPORTS cvhalKeyPoint +{ + float x; + float y; + float size; + float angle; + float response; + int octave; + int class_id; +}; +//! @} + +//! @} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/flann.hpp b/3rdParty/opencv-4.11.0/opencv2/flann.hpp index 90ee59e0b8..7f142ca7be 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/flann.hpp @@ -1,629 +1,629 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_FLANN_HPP -#define OPENCV_FLANN_HPP - -#include "opencv2/core.hpp" -#include "opencv2/flann/miniflann.hpp" -#include "opencv2/flann/flann_base.hpp" - -/** -@defgroup flann Clustering and Search in Multi-Dimensional Spaces - -This section documents OpenCV's interface to the FLANN library. FLANN (Fast Library for Approximate -Nearest Neighbors) is a library that contains a collection of algorithms optimized for fast nearest -neighbor search in large datasets and for high dimensional features. More information about FLANN -can be found in @cite Muja2009 . -*/ - -namespace cvflann -{ - CV_EXPORTS flann_distance_t flann_distance_type(); - CV_DEPRECATED CV_EXPORTS void set_distance_type(flann_distance_t distance_type, int order); -} - - -namespace cv -{ -namespace flann -{ - - -//! @addtogroup flann -//! @{ - -template struct CvType {}; -template <> struct CvType { static int type() { return CV_8U; } }; -template <> struct CvType { static int type() { return CV_8S; } }; -template <> struct CvType { static int type() { return CV_16U; } }; -template <> struct CvType { static int type() { return CV_16S; } }; -template <> struct CvType { static int type() { return CV_32S; } }; -template <> struct CvType { static int type() { return CV_32F; } }; -template <> struct CvType { static int type() { return CV_64F; } }; - - -// bring the flann parameters into this namespace -using ::cvflann::get_param; -using ::cvflann::print_params; - -// bring the flann distances into this namespace -using ::cvflann::L2_Simple; -using ::cvflann::L2; -using ::cvflann::L1; -using ::cvflann::MinkowskiDistance; -using ::cvflann::MaxDistance; -using ::cvflann::HammingLUT; -using ::cvflann::Hamming; -using ::cvflann::Hamming2; -using ::cvflann::DNAmmingLUT; -using ::cvflann::DNAmming2; -using ::cvflann::HistIntersectionDistance; -using ::cvflann::HellingerDistance; -using ::cvflann::ChiSquareDistance; -using ::cvflann::KL_Divergence; - - -/** @brief The FLANN nearest neighbor index class. This class is templated with the type of elements for which -the index is built. - -`Distance` functor specifies the metric to be used to calculate the distance between two points. -There are several `Distance` functors that are readily available: - -cv::cvflann::L2_Simple - Squared Euclidean distance functor. -This is the simpler, unrolled version. This is preferable for very low dimensionality data (eg 3D points) - -cv::flann::L2 - Squared Euclidean distance functor, optimized version. - -cv::flann::L1 - Manhattan distance functor, optimized version. - -cv::flann::MinkowskiDistance - The Minkowski distance functor. -This is highly optimised with loop unrolling. -The computation of squared root at the end is omitted for efficiency. - -cv::flann::MaxDistance - The max distance functor. It computes the -maximum distance between two vectors. This distance is not a valid kdtree distance, it's not -dimensionwise additive. - -cv::flann::HammingLUT - %Hamming distance functor. It counts the bit -differences between two strings using a lookup table implementation. - -cv::flann::Hamming - %Hamming distance functor. Population count is -performed using library calls, if available. Lookup table implementation is used as a fallback. - -cv::flann::Hamming2 - %Hamming distance functor. Population count is -implemented in 12 arithmetic operations (one of which is multiplication). - -cv::flann::DNAmmingLUT - %Adaptation of the Hamming distance functor to DNA comparison. -As the four bases A, C, G, T of the DNA (or A, G, C, U for RNA) can be coded on 2 bits, -it counts the bits pairs differences between two sequences using a lookup table implementation. - -cv::flann::DNAmming2 - %Adaptation of the Hamming distance functor to DNA comparison. -Bases differences count are vectorised thanks to arithmetic operations using standard -registers (AVX2 and AVX-512 should come in a near future). - -cv::flann::HistIntersectionDistance - The histogram -intersection distance functor. - -cv::flann::HellingerDistance - The Hellinger distance functor. - -cv::flann::ChiSquareDistance - The chi-square distance functor. - -cv::flann::KL_Divergence - The Kullback-Leibler divergence functor. - -Although the provided implementations cover a vast range of cases, it is also possible to use -a custom implementation. The distance functor is a class whose `operator()` computes the distance -between two features. If the distance is also a kd-tree compatible distance, it should also provide an -`accum_dist()` method that computes the distance between individual feature dimensions. - -In addition to `operator()` and `accum_dist()`, a distance functor should also define the -`ElementType` and the `ResultType` as the types of the elements it operates on and the type of the -result it computes. If a distance functor can be used as a kd-tree distance (meaning that the full -distance between a pair of features can be accumulated from the partial distances between the -individual dimensions) a typedef `is_kdtree_distance` should be present inside the distance functor. -If the distance is not a kd-tree distance, but it's a distance in a vector space (the individual -dimensions of the elements it operates on can be accessed independently) a typedef -`is_vector_space_distance` should be defined inside the functor. If neither typedef is defined, the -distance is assumed to be a metric distance and will only be used with indexes operating on -generic metric distances. - */ -template -class GenericIndex -{ -public: - typedef typename Distance::ElementType ElementType; - typedef typename Distance::ResultType DistanceType; - - /** @brief Constructs a nearest neighbor search index for a given dataset. - - @param features Matrix of containing the features(points) to index. The size of the matrix is - num_features x feature_dimensionality and the data type of the elements in the matrix must - coincide with the type of the index. - @param params Structure containing the index parameters. The type of index that will be - constructed depends on the type of this parameter. See the description. - @param distance - - The method constructs a fast search structure from a set of features using the specified algorithm - with specified parameters, as defined by params. params is a reference to one of the following class - IndexParams descendants: - - - **LinearIndexParams** When passing an object of this type, the index will perform a linear, - brute-force search. : - @code - struct LinearIndexParams : public IndexParams - { - }; - @endcode - - **KDTreeIndexParams** When passing an object of this type the index constructed will consist of - a set of randomized kd-trees which will be searched in parallel. : - @code - struct KDTreeIndexParams : public IndexParams - { - KDTreeIndexParams( int trees = 4 ); - }; - @endcode - - **HierarchicalClusteringIndexParams** When passing an object of this type the index constructed - will be a hierarchical tree of clusters, dividing each set of points into n clusters whose centers - are picked among the points without further refinement of their position. - This algorithm fits both floating, integer and binary vectors. : - @code - struct HierarchicalClusteringIndexParams : public IndexParams - { - HierarchicalClusteringIndexParams( - int branching = 32, - flann_centers_init_t centers_init = CENTERS_RANDOM, - int trees = 4, - int leaf_size = 100); - - }; - @endcode - - **KMeansIndexParams** When passing an object of this type the index constructed will be a - hierarchical k-means tree (one tree by default), dividing each set of points into n clusters - whose barycenters are refined iteratively. - Note that this algorithm has been extended to the support of binary vectors as an alternative - to LSH when knn search speed is the criterium. It will also outperform LSH when processing - directly (i.e. without the use of MCA/PCA) datasets whose points share mostly the same values - for most of the dimensions. It is recommended to set more than one tree with binary data. : - @code - struct KMeansIndexParams : public IndexParams - { - KMeansIndexParams( - int branching = 32, - int iterations = 11, - flann_centers_init_t centers_init = CENTERS_RANDOM, - float cb_index = 0.2, - int trees = 1); - }; - @endcode - - **CompositeIndexParams** When using a parameters object of this type the index created - combines the randomized kd-trees and the hierarchical k-means tree. : - @code - struct CompositeIndexParams : public IndexParams - { - CompositeIndexParams( - int trees = 4, - int branching = 32, - int iterations = 11, - flann_centers_init_t centers_init = CENTERS_RANDOM, - float cb_index = 0.2 ); - }; - @endcode - - **LshIndexParams** When using a parameters object of this type the index created uses - multi-probe LSH (by Multi-Probe LSH: Efficient Indexing for High-Dimensional Similarity Search - by Qin Lv, William Josephson, Zhe Wang, Moses Charikar, Kai Li., Proceedings of the 33rd - International Conference on Very Large Data Bases (VLDB). Vienna, Austria. September 2007). - This algorithm is designed for binary vectors. : - @code - struct LshIndexParams : public IndexParams - { - LshIndexParams( - int table_number, - int key_size, - int multi_probe_level ); - }; - @endcode - - **AutotunedIndexParams** When passing an object of this type the index created is - automatically tuned to offer the best performance, by choosing the optimal index type - (randomized kd-trees, hierarchical kmeans, linear) and parameters for the dataset provided. : - @code - struct AutotunedIndexParams : public IndexParams - { - AutotunedIndexParams( - float target_precision = 0.9, - float build_weight = 0.01, - float memory_weight = 0, - float sample_fraction = 0.1 ); - }; - @endcode - - **SavedIndexParams** This object type is used for loading a previously saved index from the - disk. : - @code - struct SavedIndexParams : public IndexParams - { - SavedIndexParams( String filename ); - }; - @endcode - */ - GenericIndex(const Mat& features, const ::cvflann::IndexParams& params, Distance distance = Distance()); - - ~GenericIndex(); - - /** @brief Performs a K-nearest neighbor search for a given query point using the index. - - @param query The query point - @param indices Vector that will contain the indices of the K-nearest neighbors found. It must have - at least knn size. - @param dists Vector that will contain the distances to the K-nearest neighbors found. It must have - at least knn size. - @param knn Number of nearest neighbors to search for. - @param params SearchParams - */ - void knnSearch(const std::vector& query, std::vector& indices, - std::vector& dists, int knn, const ::cvflann::SearchParams& params); - void knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& params); - - /** @brief Performs a radius nearest neighbor search for a given query point using the index. - - @param query The query point. - @param indices Vector that will contain the indices of the nearest neighbors found. - @param dists Vector that will contain the distances to the nearest neighbors found. It has the same - number of elements as indices. - @param radius The search radius. - @param params SearchParams - - This function returns the number of nearest neighbors found. - */ - int radiusSearch(const std::vector& query, std::vector& indices, - std::vector& dists, DistanceType radius, const ::cvflann::SearchParams& params); - int radiusSearch(const Mat& query, Mat& indices, Mat& dists, - DistanceType radius, const ::cvflann::SearchParams& params); - - void save(String filename) { nnIndex->save(filename); } - - int veclen() const { return nnIndex->veclen(); } - - int size() const { return (int)nnIndex->size(); } - - ::cvflann::IndexParams getParameters() { return nnIndex->getParameters(); } - - CV_DEPRECATED const ::cvflann::IndexParams* getIndexParameters() { return nnIndex->getIndexParameters(); } - -private: - ::cvflann::Index* nnIndex; - Mat _dataset; -}; - -//! @cond IGNORED - -#define FLANN_DISTANCE_CHECK \ - if ( ::cvflann::flann_distance_type() != cvflann::FLANN_DIST_L2) { \ - printf("[WARNING] You are using cv::flann::Index (or cv::flann::GenericIndex) and have also changed "\ - "the distance using cvflann::set_distance_type. This is no longer working as expected "\ - "(cv::flann::Index always uses L2). You should create the index templated on the distance, "\ - "for example for L1 distance use: GenericIndex< L1 > \n"); \ - } - - -template -GenericIndex::GenericIndex(const Mat& dataset, const ::cvflann::IndexParams& params, Distance distance) -: _dataset(dataset) -{ - CV_Assert(dataset.type() == CvType::type()); - CV_Assert(dataset.isContinuous()); - ::cvflann::Matrix m_dataset((ElementType*)_dataset.ptr(0), _dataset.rows, _dataset.cols); - - nnIndex = new ::cvflann::Index(m_dataset, params, distance); - - FLANN_DISTANCE_CHECK - - nnIndex->buildIndex(); -} - -template -GenericIndex::~GenericIndex() -{ - delete nnIndex; -} - -template -void GenericIndex::knnSearch(const std::vector& query, std::vector& indices, std::vector& dists, int knn, const ::cvflann::SearchParams& searchParams) -{ - ::cvflann::Matrix m_query((ElementType*)&query[0], 1, query.size()); - ::cvflann::Matrix m_indices(&indices[0], 1, indices.size()); - ::cvflann::Matrix m_dists(&dists[0], 1, dists.size()); - - FLANN_DISTANCE_CHECK - - nnIndex->knnSearch(m_query,m_indices,m_dists,knn,searchParams); -} - - -template -void GenericIndex::knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& searchParams) -{ - CV_Assert(queries.type() == CvType::type()); - CV_Assert(queries.isContinuous()); - ::cvflann::Matrix m_queries((ElementType*)queries.ptr(0), queries.rows, queries.cols); - - CV_Assert(indices.type() == CV_32S); - CV_Assert(indices.isContinuous()); - ::cvflann::Matrix m_indices((int*)indices.ptr(0), indices.rows, indices.cols); - - CV_Assert(dists.type() == CvType::type()); - CV_Assert(dists.isContinuous()); - ::cvflann::Matrix m_dists((DistanceType*)dists.ptr(0), dists.rows, dists.cols); - - FLANN_DISTANCE_CHECK - - nnIndex->knnSearch(m_queries,m_indices,m_dists,knn, searchParams); -} - -template -int GenericIndex::radiusSearch(const std::vector& query, std::vector& indices, std::vector& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams) -{ - ::cvflann::Matrix m_query((ElementType*)&query[0], 1, query.size()); - ::cvflann::Matrix m_indices(&indices[0], 1, indices.size()); - ::cvflann::Matrix m_dists(&dists[0], 1, dists.size()); - - FLANN_DISTANCE_CHECK - - return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); -} - -template -int GenericIndex::radiusSearch(const Mat& query, Mat& indices, Mat& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams) -{ - CV_Assert(query.type() == CvType::type()); - CV_Assert(query.isContinuous()); - ::cvflann::Matrix m_query((ElementType*)query.ptr(0), query.rows, query.cols); - - CV_Assert(indices.type() == CV_32S); - CV_Assert(indices.isContinuous()); - ::cvflann::Matrix m_indices((int*)indices.ptr(0), indices.rows, indices.cols); - - CV_Assert(dists.type() == CvType::type()); - CV_Assert(dists.isContinuous()); - ::cvflann::Matrix m_dists((DistanceType*)dists.ptr(0), dists.rows, dists.cols); - - FLANN_DISTANCE_CHECK - - return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); -} - -/** - * @deprecated Use GenericIndex class instead - */ -template -class Index_ -{ -public: - typedef typename L2::ElementType ElementType; - typedef typename L2::ResultType DistanceType; - - CV_DEPRECATED Index_(const Mat& dataset, const ::cvflann::IndexParams& params) - { - printf("[WARNING] The cv::flann::Index_ class is deperecated, use cv::flann::GenericIndex instead\n"); - - CV_Assert(dataset.type() == CvType::type()); - CV_Assert(dataset.isContinuous()); - ::cvflann::Matrix m_dataset((ElementType*)dataset.ptr(0), dataset.rows, dataset.cols); - - if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L2 ) { - nnIndex_L1 = NULL; - nnIndex_L2 = new ::cvflann::Index< L2 >(m_dataset, params); - } - else if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L1 ) { - nnIndex_L1 = new ::cvflann::Index< L1 >(m_dataset, params); - nnIndex_L2 = NULL; - } - else { - printf("[ERROR] cv::flann::Index_ only provides backwards compatibility for the L1 and L2 distances. " - "For other distance types you must use cv::flann::GenericIndex\n"); - CV_Assert(0); - } - if (nnIndex_L1) nnIndex_L1->buildIndex(); - if (nnIndex_L2) nnIndex_L2->buildIndex(); - } - CV_DEPRECATED ~Index_() - { - if (nnIndex_L1) delete nnIndex_L1; - if (nnIndex_L2) delete nnIndex_L2; - } - - CV_DEPRECATED void knnSearch(const std::vector& query, std::vector& indices, std::vector& dists, int knn, const ::cvflann::SearchParams& searchParams) - { - ::cvflann::Matrix m_query((ElementType*)&query[0], 1, query.size()); - ::cvflann::Matrix m_indices(&indices[0], 1, indices.size()); - ::cvflann::Matrix m_dists(&dists[0], 1, dists.size()); - - if (nnIndex_L1) nnIndex_L1->knnSearch(m_query,m_indices,m_dists,knn,searchParams); - if (nnIndex_L2) nnIndex_L2->knnSearch(m_query,m_indices,m_dists,knn,searchParams); - } - CV_DEPRECATED void knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& searchParams) - { - CV_Assert(queries.type() == CvType::type()); - CV_Assert(queries.isContinuous()); - ::cvflann::Matrix m_queries((ElementType*)queries.ptr(0), queries.rows, queries.cols); - - CV_Assert(indices.type() == CV_32S); - CV_Assert(indices.isContinuous()); - ::cvflann::Matrix m_indices((int*)indices.ptr(0), indices.rows, indices.cols); - - CV_Assert(dists.type() == CvType::type()); - CV_Assert(dists.isContinuous()); - ::cvflann::Matrix m_dists((DistanceType*)dists.ptr(0), dists.rows, dists.cols); - - if (nnIndex_L1) nnIndex_L1->knnSearch(m_queries,m_indices,m_dists,knn, searchParams); - if (nnIndex_L2) nnIndex_L2->knnSearch(m_queries,m_indices,m_dists,knn, searchParams); - } - - CV_DEPRECATED int radiusSearch(const std::vector& query, std::vector& indices, std::vector& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams) - { - ::cvflann::Matrix m_query((ElementType*)&query[0], 1, query.size()); - ::cvflann::Matrix m_indices(&indices[0], 1, indices.size()); - ::cvflann::Matrix m_dists(&dists[0], 1, dists.size()); - - if (nnIndex_L1) return nnIndex_L1->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); - if (nnIndex_L2) return nnIndex_L2->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); - } - - CV_DEPRECATED int radiusSearch(const Mat& query, Mat& indices, Mat& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams) - { - CV_Assert(query.type() == CvType::type()); - CV_Assert(query.isContinuous()); - ::cvflann::Matrix m_query((ElementType*)query.ptr(0), query.rows, query.cols); - - CV_Assert(indices.type() == CV_32S); - CV_Assert(indices.isContinuous()); - ::cvflann::Matrix m_indices((int*)indices.ptr(0), indices.rows, indices.cols); - - CV_Assert(dists.type() == CvType::type()); - CV_Assert(dists.isContinuous()); - ::cvflann::Matrix m_dists((DistanceType*)dists.ptr(0), dists.rows, dists.cols); - - if (nnIndex_L1) return nnIndex_L1->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); - if (nnIndex_L2) return nnIndex_L2->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); - } - - CV_DEPRECATED void save(String filename) - { - if (nnIndex_L1) nnIndex_L1->save(filename); - if (nnIndex_L2) nnIndex_L2->save(filename); - } - - CV_DEPRECATED int veclen() const - { - if (nnIndex_L1) return nnIndex_L1->veclen(); - if (nnIndex_L2) return nnIndex_L2->veclen(); - } - - CV_DEPRECATED int size() const - { - if (nnIndex_L1) return nnIndex_L1->size(); - if (nnIndex_L2) return nnIndex_L2->size(); - } - - CV_DEPRECATED ::cvflann::IndexParams getParameters() - { - if (nnIndex_L1) return nnIndex_L1->getParameters(); - if (nnIndex_L2) return nnIndex_L2->getParameters(); - - } - - CV_DEPRECATED const ::cvflann::IndexParams* getIndexParameters() - { - if (nnIndex_L1) return nnIndex_L1->getIndexParameters(); - if (nnIndex_L2) return nnIndex_L2->getIndexParameters(); - } - -private: - // providing backwards compatibility for L2 and L1 distances (most common) - ::cvflann::Index< L2 >* nnIndex_L2; - ::cvflann::Index< L1 >* nnIndex_L1; -}; - -//! @endcond - -/** @brief Clusters features using hierarchical k-means algorithm. - -@param features The points to be clustered. The matrix must have elements of type -Distance::ElementType. -@param centers The centers of the clusters obtained. The matrix must have type -Distance::CentersType. The number of rows in this matrix represents the number of clusters desired, -however, because of the way the cut in the hierarchical tree is chosen, the number of clusters -computed will be the highest number of the form (branching-1)\*k+1 that's lower than the number of -clusters desired, where branching is the tree's branching factor (see description of the -KMeansIndexParams). -@param params Parameters used in the construction of the hierarchical k-means tree. -@param d Distance to be used for clustering. - -The method clusters the given feature vectors by constructing a hierarchical k-means tree and -choosing a cut in the tree that minimizes the cluster's variance. It returns the number of clusters -found. - */ -template -int hierarchicalClustering(const Mat& features, Mat& centers, const ::cvflann::KMeansIndexParams& params, - Distance d = Distance()) -{ - typedef typename Distance::ElementType ElementType; - typedef typename Distance::CentersType CentersType; - - CV_Assert(features.type() == CvType::type()); - CV_Assert(features.isContinuous()); - ::cvflann::Matrix m_features((ElementType*)features.ptr(0), features.rows, features.cols); - - CV_Assert(centers.type() == CvType::type()); - CV_Assert(centers.isContinuous()); - ::cvflann::Matrix m_centers((CentersType*)centers.ptr(0), centers.rows, centers.cols); - - return ::cvflann::hierarchicalClustering(m_features, m_centers, params, d); -} - -//! @cond IGNORED - -template -CV_DEPRECATED int hierarchicalClustering(const Mat& features, Mat& centers, const ::cvflann::KMeansIndexParams& params) -{ - printf("[WARNING] cv::flann::hierarchicalClustering is deprecated, use " - "cv::flann::hierarchicalClustering instead\n"); - - if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L2 ) { - return hierarchicalClustering< L2 >(features, centers, params); - } - else if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L1 ) { - return hierarchicalClustering< L1 >(features, centers, params); - } - else { - printf("[ERROR] cv::flann::hierarchicalClustering only provides backwards " - "compatibility for the L1 and L2 distances. " - "For other distance types you must use cv::flann::hierarchicalClustering\n"); - CV_Assert(0); - } -} - -//! @endcond - -//! @} flann - -} } // namespace cv::flann - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_FLANN_HPP +#define OPENCV_FLANN_HPP + +#include "opencv2/core.hpp" +#include "opencv2/flann/miniflann.hpp" +#include "opencv2/flann/flann_base.hpp" + +/** +@defgroup flann Clustering and Search in Multi-Dimensional Spaces + +This section documents OpenCV's interface to the FLANN library. FLANN (Fast Library for Approximate +Nearest Neighbors) is a library that contains a collection of algorithms optimized for fast nearest +neighbor search in large datasets and for high dimensional features. More information about FLANN +can be found in @cite Muja2009 . +*/ + +namespace cvflann +{ + CV_EXPORTS flann_distance_t flann_distance_type(); + CV_DEPRECATED CV_EXPORTS void set_distance_type(flann_distance_t distance_type, int order); +} + + +namespace cv +{ +namespace flann +{ + + +//! @addtogroup flann +//! @{ + +template struct CvType {}; +template <> struct CvType { static int type() { return CV_8U; } }; +template <> struct CvType { static int type() { return CV_8S; } }; +template <> struct CvType { static int type() { return CV_16U; } }; +template <> struct CvType { static int type() { return CV_16S; } }; +template <> struct CvType { static int type() { return CV_32S; } }; +template <> struct CvType { static int type() { return CV_32F; } }; +template <> struct CvType { static int type() { return CV_64F; } }; + + +// bring the flann parameters into this namespace +using ::cvflann::get_param; +using ::cvflann::print_params; + +// bring the flann distances into this namespace +using ::cvflann::L2_Simple; +using ::cvflann::L2; +using ::cvflann::L1; +using ::cvflann::MinkowskiDistance; +using ::cvflann::MaxDistance; +using ::cvflann::HammingLUT; +using ::cvflann::Hamming; +using ::cvflann::Hamming2; +using ::cvflann::DNAmmingLUT; +using ::cvflann::DNAmming2; +using ::cvflann::HistIntersectionDistance; +using ::cvflann::HellingerDistance; +using ::cvflann::ChiSquareDistance; +using ::cvflann::KL_Divergence; + + +/** @brief The FLANN nearest neighbor index class. This class is templated with the type of elements for which +the index is built. + +`Distance` functor specifies the metric to be used to calculate the distance between two points. +There are several `Distance` functors that are readily available: + +cv::cvflann::L2_Simple - Squared Euclidean distance functor. +This is the simpler, unrolled version. This is preferable for very low dimensionality data (eg 3D points) + +cv::flann::L2 - Squared Euclidean distance functor, optimized version. + +cv::flann::L1 - Manhattan distance functor, optimized version. + +cv::flann::MinkowskiDistance - The Minkowski distance functor. +This is highly optimised with loop unrolling. +The computation of squared root at the end is omitted for efficiency. + +cv::flann::MaxDistance - The max distance functor. It computes the +maximum distance between two vectors. This distance is not a valid kdtree distance, it's not +dimensionwise additive. + +cv::flann::HammingLUT - %Hamming distance functor. It counts the bit +differences between two strings using a lookup table implementation. + +cv::flann::Hamming - %Hamming distance functor. Population count is +performed using library calls, if available. Lookup table implementation is used as a fallback. + +cv::flann::Hamming2 - %Hamming distance functor. Population count is +implemented in 12 arithmetic operations (one of which is multiplication). + +cv::flann::DNAmmingLUT - %Adaptation of the Hamming distance functor to DNA comparison. +As the four bases A, C, G, T of the DNA (or A, G, C, U for RNA) can be coded on 2 bits, +it counts the bits pairs differences between two sequences using a lookup table implementation. + +cv::flann::DNAmming2 - %Adaptation of the Hamming distance functor to DNA comparison. +Bases differences count are vectorised thanks to arithmetic operations using standard +registers (AVX2 and AVX-512 should come in a near future). + +cv::flann::HistIntersectionDistance - The histogram +intersection distance functor. + +cv::flann::HellingerDistance - The Hellinger distance functor. + +cv::flann::ChiSquareDistance - The chi-square distance functor. + +cv::flann::KL_Divergence - The Kullback-Leibler divergence functor. + +Although the provided implementations cover a vast range of cases, it is also possible to use +a custom implementation. The distance functor is a class whose `operator()` computes the distance +between two features. If the distance is also a kd-tree compatible distance, it should also provide an +`accum_dist()` method that computes the distance between individual feature dimensions. + +In addition to `operator()` and `accum_dist()`, a distance functor should also define the +`ElementType` and the `ResultType` as the types of the elements it operates on and the type of the +result it computes. If a distance functor can be used as a kd-tree distance (meaning that the full +distance between a pair of features can be accumulated from the partial distances between the +individual dimensions) a typedef `is_kdtree_distance` should be present inside the distance functor. +If the distance is not a kd-tree distance, but it's a distance in a vector space (the individual +dimensions of the elements it operates on can be accessed independently) a typedef +`is_vector_space_distance` should be defined inside the functor. If neither typedef is defined, the +distance is assumed to be a metric distance and will only be used with indexes operating on +generic metric distances. + */ +template +class GenericIndex +{ +public: + typedef typename Distance::ElementType ElementType; + typedef typename Distance::ResultType DistanceType; + + /** @brief Constructs a nearest neighbor search index for a given dataset. + + @param features Matrix of containing the features(points) to index. The size of the matrix is + num_features x feature_dimensionality and the data type of the elements in the matrix must + coincide with the type of the index. + @param params Structure containing the index parameters. The type of index that will be + constructed depends on the type of this parameter. See the description. + @param distance + + The method constructs a fast search structure from a set of features using the specified algorithm + with specified parameters, as defined by params. params is a reference to one of the following class + IndexParams descendants: + + - **LinearIndexParams** When passing an object of this type, the index will perform a linear, + brute-force search. : + @code + struct LinearIndexParams : public IndexParams + { + }; + @endcode + - **KDTreeIndexParams** When passing an object of this type the index constructed will consist of + a set of randomized kd-trees which will be searched in parallel. : + @code + struct KDTreeIndexParams : public IndexParams + { + KDTreeIndexParams( int trees = 4 ); + }; + @endcode + - **HierarchicalClusteringIndexParams** When passing an object of this type the index constructed + will be a hierarchical tree of clusters, dividing each set of points into n clusters whose centers + are picked among the points without further refinement of their position. + This algorithm fits both floating, integer and binary vectors. : + @code + struct HierarchicalClusteringIndexParams : public IndexParams + { + HierarchicalClusteringIndexParams( + int branching = 32, + flann_centers_init_t centers_init = CENTERS_RANDOM, + int trees = 4, + int leaf_size = 100); + + }; + @endcode + - **KMeansIndexParams** When passing an object of this type the index constructed will be a + hierarchical k-means tree (one tree by default), dividing each set of points into n clusters + whose barycenters are refined iteratively. + Note that this algorithm has been extended to the support of binary vectors as an alternative + to LSH when knn search speed is the criterium. It will also outperform LSH when processing + directly (i.e. without the use of MCA/PCA) datasets whose points share mostly the same values + for most of the dimensions. It is recommended to set more than one tree with binary data. : + @code + struct KMeansIndexParams : public IndexParams + { + KMeansIndexParams( + int branching = 32, + int iterations = 11, + flann_centers_init_t centers_init = CENTERS_RANDOM, + float cb_index = 0.2, + int trees = 1); + }; + @endcode + - **CompositeIndexParams** When using a parameters object of this type the index created + combines the randomized kd-trees and the hierarchical k-means tree. : + @code + struct CompositeIndexParams : public IndexParams + { + CompositeIndexParams( + int trees = 4, + int branching = 32, + int iterations = 11, + flann_centers_init_t centers_init = CENTERS_RANDOM, + float cb_index = 0.2 ); + }; + @endcode + - **LshIndexParams** When using a parameters object of this type the index created uses + multi-probe LSH (by Multi-Probe LSH: Efficient Indexing for High-Dimensional Similarity Search + by Qin Lv, William Josephson, Zhe Wang, Moses Charikar, Kai Li., Proceedings of the 33rd + International Conference on Very Large Data Bases (VLDB). Vienna, Austria. September 2007). + This algorithm is designed for binary vectors. : + @code + struct LshIndexParams : public IndexParams + { + LshIndexParams( + int table_number, + int key_size, + int multi_probe_level ); + }; + @endcode + - **AutotunedIndexParams** When passing an object of this type the index created is + automatically tuned to offer the best performance, by choosing the optimal index type + (randomized kd-trees, hierarchical kmeans, linear) and parameters for the dataset provided. : + @code + struct AutotunedIndexParams : public IndexParams + { + AutotunedIndexParams( + float target_precision = 0.9, + float build_weight = 0.01, + float memory_weight = 0, + float sample_fraction = 0.1 ); + }; + @endcode + - **SavedIndexParams** This object type is used for loading a previously saved index from the + disk. : + @code + struct SavedIndexParams : public IndexParams + { + SavedIndexParams( String filename ); + }; + @endcode + */ + GenericIndex(const Mat& features, const ::cvflann::IndexParams& params, Distance distance = Distance()); + + ~GenericIndex(); + + /** @brief Performs a K-nearest neighbor search for a given query point using the index. + + @param query The query point + @param indices Vector that will contain the indices of the K-nearest neighbors found. It must have + at least knn size. + @param dists Vector that will contain the distances to the K-nearest neighbors found. It must have + at least knn size. + @param knn Number of nearest neighbors to search for. + @param params SearchParams + */ + void knnSearch(const std::vector& query, std::vector& indices, + std::vector& dists, int knn, const ::cvflann::SearchParams& params); + void knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& params); + + /** @brief Performs a radius nearest neighbor search for a given query point using the index. + + @param query The query point. + @param indices Vector that will contain the indices of the nearest neighbors found. + @param dists Vector that will contain the distances to the nearest neighbors found. It has the same + number of elements as indices. + @param radius The search radius. + @param params SearchParams + + This function returns the number of nearest neighbors found. + */ + int radiusSearch(const std::vector& query, std::vector& indices, + std::vector& dists, DistanceType radius, const ::cvflann::SearchParams& params); + int radiusSearch(const Mat& query, Mat& indices, Mat& dists, + DistanceType radius, const ::cvflann::SearchParams& params); + + void save(String filename) { nnIndex->save(filename); } + + int veclen() const { return nnIndex->veclen(); } + + int size() const { return (int)nnIndex->size(); } + + ::cvflann::IndexParams getParameters() { return nnIndex->getParameters(); } + + CV_DEPRECATED const ::cvflann::IndexParams* getIndexParameters() { return nnIndex->getIndexParameters(); } + +private: + ::cvflann::Index* nnIndex; + Mat _dataset; +}; + +//! @cond IGNORED + +#define FLANN_DISTANCE_CHECK \ + if ( ::cvflann::flann_distance_type() != cvflann::FLANN_DIST_L2) { \ + printf("[WARNING] You are using cv::flann::Index (or cv::flann::GenericIndex) and have also changed "\ + "the distance using cvflann::set_distance_type. This is no longer working as expected "\ + "(cv::flann::Index always uses L2). You should create the index templated on the distance, "\ + "for example for L1 distance use: GenericIndex< L1 > \n"); \ + } + + +template +GenericIndex::GenericIndex(const Mat& dataset, const ::cvflann::IndexParams& params, Distance distance) +: _dataset(dataset) +{ + CV_Assert(dataset.type() == CvType::type()); + CV_Assert(dataset.isContinuous()); + ::cvflann::Matrix m_dataset((ElementType*)_dataset.ptr(0), _dataset.rows, _dataset.cols); + + nnIndex = new ::cvflann::Index(m_dataset, params, distance); + + FLANN_DISTANCE_CHECK + + nnIndex->buildIndex(); +} + +template +GenericIndex::~GenericIndex() +{ + delete nnIndex; +} + +template +void GenericIndex::knnSearch(const std::vector& query, std::vector& indices, std::vector& dists, int knn, const ::cvflann::SearchParams& searchParams) +{ + ::cvflann::Matrix m_query((ElementType*)&query[0], 1, query.size()); + ::cvflann::Matrix m_indices(&indices[0], 1, indices.size()); + ::cvflann::Matrix m_dists(&dists[0], 1, dists.size()); + + FLANN_DISTANCE_CHECK + + nnIndex->knnSearch(m_query,m_indices,m_dists,knn,searchParams); +} + + +template +void GenericIndex::knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& searchParams) +{ + CV_Assert(queries.type() == CvType::type()); + CV_Assert(queries.isContinuous()); + ::cvflann::Matrix m_queries((ElementType*)queries.ptr(0), queries.rows, queries.cols); + + CV_Assert(indices.type() == CV_32S); + CV_Assert(indices.isContinuous()); + ::cvflann::Matrix m_indices((int*)indices.ptr(0), indices.rows, indices.cols); + + CV_Assert(dists.type() == CvType::type()); + CV_Assert(dists.isContinuous()); + ::cvflann::Matrix m_dists((DistanceType*)dists.ptr(0), dists.rows, dists.cols); + + FLANN_DISTANCE_CHECK + + nnIndex->knnSearch(m_queries,m_indices,m_dists,knn, searchParams); +} + +template +int GenericIndex::radiusSearch(const std::vector& query, std::vector& indices, std::vector& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams) +{ + ::cvflann::Matrix m_query((ElementType*)&query[0], 1, query.size()); + ::cvflann::Matrix m_indices(&indices[0], 1, indices.size()); + ::cvflann::Matrix m_dists(&dists[0], 1, dists.size()); + + FLANN_DISTANCE_CHECK + + return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); +} + +template +int GenericIndex::radiusSearch(const Mat& query, Mat& indices, Mat& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams) +{ + CV_Assert(query.type() == CvType::type()); + CV_Assert(query.isContinuous()); + ::cvflann::Matrix m_query((ElementType*)query.ptr(0), query.rows, query.cols); + + CV_Assert(indices.type() == CV_32S); + CV_Assert(indices.isContinuous()); + ::cvflann::Matrix m_indices((int*)indices.ptr(0), indices.rows, indices.cols); + + CV_Assert(dists.type() == CvType::type()); + CV_Assert(dists.isContinuous()); + ::cvflann::Matrix m_dists((DistanceType*)dists.ptr(0), dists.rows, dists.cols); + + FLANN_DISTANCE_CHECK + + return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); +} + +/** + * @deprecated Use GenericIndex class instead + */ +template +class Index_ +{ +public: + typedef typename L2::ElementType ElementType; + typedef typename L2::ResultType DistanceType; + + CV_DEPRECATED Index_(const Mat& dataset, const ::cvflann::IndexParams& params) + { + printf("[WARNING] The cv::flann::Index_ class is deperecated, use cv::flann::GenericIndex instead\n"); + + CV_Assert(dataset.type() == CvType::type()); + CV_Assert(dataset.isContinuous()); + ::cvflann::Matrix m_dataset((ElementType*)dataset.ptr(0), dataset.rows, dataset.cols); + + if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L2 ) { + nnIndex_L1 = NULL; + nnIndex_L2 = new ::cvflann::Index< L2 >(m_dataset, params); + } + else if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L1 ) { + nnIndex_L1 = new ::cvflann::Index< L1 >(m_dataset, params); + nnIndex_L2 = NULL; + } + else { + printf("[ERROR] cv::flann::Index_ only provides backwards compatibility for the L1 and L2 distances. " + "For other distance types you must use cv::flann::GenericIndex\n"); + CV_Assert(0); + } + if (nnIndex_L1) nnIndex_L1->buildIndex(); + if (nnIndex_L2) nnIndex_L2->buildIndex(); + } + CV_DEPRECATED ~Index_() + { + if (nnIndex_L1) delete nnIndex_L1; + if (nnIndex_L2) delete nnIndex_L2; + } + + CV_DEPRECATED void knnSearch(const std::vector& query, std::vector& indices, std::vector& dists, int knn, const ::cvflann::SearchParams& searchParams) + { + ::cvflann::Matrix m_query((ElementType*)&query[0], 1, query.size()); + ::cvflann::Matrix m_indices(&indices[0], 1, indices.size()); + ::cvflann::Matrix m_dists(&dists[0], 1, dists.size()); + + if (nnIndex_L1) nnIndex_L1->knnSearch(m_query,m_indices,m_dists,knn,searchParams); + if (nnIndex_L2) nnIndex_L2->knnSearch(m_query,m_indices,m_dists,knn,searchParams); + } + CV_DEPRECATED void knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& searchParams) + { + CV_Assert(queries.type() == CvType::type()); + CV_Assert(queries.isContinuous()); + ::cvflann::Matrix m_queries((ElementType*)queries.ptr(0), queries.rows, queries.cols); + + CV_Assert(indices.type() == CV_32S); + CV_Assert(indices.isContinuous()); + ::cvflann::Matrix m_indices((int*)indices.ptr(0), indices.rows, indices.cols); + + CV_Assert(dists.type() == CvType::type()); + CV_Assert(dists.isContinuous()); + ::cvflann::Matrix m_dists((DistanceType*)dists.ptr(0), dists.rows, dists.cols); + + if (nnIndex_L1) nnIndex_L1->knnSearch(m_queries,m_indices,m_dists,knn, searchParams); + if (nnIndex_L2) nnIndex_L2->knnSearch(m_queries,m_indices,m_dists,knn, searchParams); + } + + CV_DEPRECATED int radiusSearch(const std::vector& query, std::vector& indices, std::vector& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams) + { + ::cvflann::Matrix m_query((ElementType*)&query[0], 1, query.size()); + ::cvflann::Matrix m_indices(&indices[0], 1, indices.size()); + ::cvflann::Matrix m_dists(&dists[0], 1, dists.size()); + + if (nnIndex_L1) return nnIndex_L1->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); + if (nnIndex_L2) return nnIndex_L2->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); + } + + CV_DEPRECATED int radiusSearch(const Mat& query, Mat& indices, Mat& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams) + { + CV_Assert(query.type() == CvType::type()); + CV_Assert(query.isContinuous()); + ::cvflann::Matrix m_query((ElementType*)query.ptr(0), query.rows, query.cols); + + CV_Assert(indices.type() == CV_32S); + CV_Assert(indices.isContinuous()); + ::cvflann::Matrix m_indices((int*)indices.ptr(0), indices.rows, indices.cols); + + CV_Assert(dists.type() == CvType::type()); + CV_Assert(dists.isContinuous()); + ::cvflann::Matrix m_dists((DistanceType*)dists.ptr(0), dists.rows, dists.cols); + + if (nnIndex_L1) return nnIndex_L1->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); + if (nnIndex_L2) return nnIndex_L2->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); + } + + CV_DEPRECATED void save(String filename) + { + if (nnIndex_L1) nnIndex_L1->save(filename); + if (nnIndex_L2) nnIndex_L2->save(filename); + } + + CV_DEPRECATED int veclen() const + { + if (nnIndex_L1) return nnIndex_L1->veclen(); + if (nnIndex_L2) return nnIndex_L2->veclen(); + } + + CV_DEPRECATED int size() const + { + if (nnIndex_L1) return nnIndex_L1->size(); + if (nnIndex_L2) return nnIndex_L2->size(); + } + + CV_DEPRECATED ::cvflann::IndexParams getParameters() + { + if (nnIndex_L1) return nnIndex_L1->getParameters(); + if (nnIndex_L2) return nnIndex_L2->getParameters(); + + } + + CV_DEPRECATED const ::cvflann::IndexParams* getIndexParameters() + { + if (nnIndex_L1) return nnIndex_L1->getIndexParameters(); + if (nnIndex_L2) return nnIndex_L2->getIndexParameters(); + } + +private: + // providing backwards compatibility for L2 and L1 distances (most common) + ::cvflann::Index< L2 >* nnIndex_L2; + ::cvflann::Index< L1 >* nnIndex_L1; +}; + +//! @endcond + +/** @brief Clusters features using hierarchical k-means algorithm. + +@param features The points to be clustered. The matrix must have elements of type +Distance::ElementType. +@param centers The centers of the clusters obtained. The matrix must have type +Distance::CentersType. The number of rows in this matrix represents the number of clusters desired, +however, because of the way the cut in the hierarchical tree is chosen, the number of clusters +computed will be the highest number of the form (branching-1)\*k+1 that's lower than the number of +clusters desired, where branching is the tree's branching factor (see description of the +KMeansIndexParams). +@param params Parameters used in the construction of the hierarchical k-means tree. +@param d Distance to be used for clustering. + +The method clusters the given feature vectors by constructing a hierarchical k-means tree and +choosing a cut in the tree that minimizes the cluster's variance. It returns the number of clusters +found. + */ +template +int hierarchicalClustering(const Mat& features, Mat& centers, const ::cvflann::KMeansIndexParams& params, + Distance d = Distance()) +{ + typedef typename Distance::ElementType ElementType; + typedef typename Distance::CentersType CentersType; + + CV_Assert(features.type() == CvType::type()); + CV_Assert(features.isContinuous()); + ::cvflann::Matrix m_features((ElementType*)features.ptr(0), features.rows, features.cols); + + CV_Assert(centers.type() == CvType::type()); + CV_Assert(centers.isContinuous()); + ::cvflann::Matrix m_centers((CentersType*)centers.ptr(0), centers.rows, centers.cols); + + return ::cvflann::hierarchicalClustering(m_features, m_centers, params, d); +} + +//! @cond IGNORED + +template +CV_DEPRECATED int hierarchicalClustering(const Mat& features, Mat& centers, const ::cvflann::KMeansIndexParams& params) +{ + printf("[WARNING] cv::flann::hierarchicalClustering is deprecated, use " + "cv::flann::hierarchicalClustering instead\n"); + + if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L2 ) { + return hierarchicalClustering< L2 >(features, centers, params); + } + else if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L1 ) { + return hierarchicalClustering< L1 >(features, centers, params); + } + else { + printf("[ERROR] cv::flann::hierarchicalClustering only provides backwards " + "compatibility for the L1 and L2 distances. " + "For other distance types you must use cv::flann::hierarchicalClustering\n"); + CV_Assert(0); + } +} + +//! @endcond + +//! @} flann + +} } // namespace cv::flann + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/all_indices.h b/3rdParty/opencv-4.11.0/opencv2/flann/all_indices.h index 03877ab6ad..a59f8c5fbf 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/all_indices.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/all_indices.h @@ -1,162 +1,162 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * 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 ``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 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 OPENCV_FLANN_ALL_INDICES_H_ -#define OPENCV_FLANN_ALL_INDICES_H_ - -//! @cond IGNORED - -#include "general.h" - -#include "nn_index.h" -#include "kdtree_index.h" -#include "kdtree_single_index.h" -#include "kmeans_index.h" -#include "composite_index.h" -#include "linear_index.h" -#include "hierarchical_clustering_index.h" -#include "lsh_index.h" -#include "autotuned_index.h" - - -namespace cvflann -{ - -template -struct index_creator -{ - static NNIndex* create(const Matrix& dataset, const IndexParams& params, const Distance& distance) - { - flann_algorithm_t index_type = get_param(params, "algorithm"); - - NNIndex* nnIndex; - switch (index_type) { - case FLANN_INDEX_LINEAR: - nnIndex = new LinearIndex(dataset, params, distance); - break; - case FLANN_INDEX_KDTREE_SINGLE: - nnIndex = new KDTreeSingleIndex(dataset, params, distance); - break; - case FLANN_INDEX_KDTREE: - nnIndex = new KDTreeIndex(dataset, params, distance); - break; - case FLANN_INDEX_KMEANS: - nnIndex = new KMeansIndex(dataset, params, distance); - break; - case FLANN_INDEX_COMPOSITE: - nnIndex = new CompositeIndex(dataset, params, distance); - break; - case FLANN_INDEX_AUTOTUNED: - nnIndex = new AutotunedIndex(dataset, params, distance); - break; - case FLANN_INDEX_HIERARCHICAL: - nnIndex = new HierarchicalClusteringIndex(dataset, params, distance); - break; - case FLANN_INDEX_LSH: - nnIndex = new LshIndex(dataset, params, distance); - break; - default: - FLANN_THROW(cv::Error::StsBadArg, "Unknown index type"); - } - - return nnIndex; - } -}; - -template -struct index_creator -{ - static NNIndex* create(const Matrix& dataset, const IndexParams& params, const Distance& distance) - { - flann_algorithm_t index_type = get_param(params, "algorithm"); - - NNIndex* nnIndex; - switch (index_type) { - case FLANN_INDEX_LINEAR: - nnIndex = new LinearIndex(dataset, params, distance); - break; - case FLANN_INDEX_KMEANS: - nnIndex = new KMeansIndex(dataset, params, distance); - break; - case FLANN_INDEX_HIERARCHICAL: - nnIndex = new HierarchicalClusteringIndex(dataset, params, distance); - break; - case FLANN_INDEX_LSH: - nnIndex = new LshIndex(dataset, params, distance); - break; - default: - FLANN_THROW(cv::Error::StsBadArg, "Unknown index type"); - } - - return nnIndex; - } -}; - -template -struct index_creator -{ - static NNIndex* create(const Matrix& dataset, const IndexParams& params, const Distance& distance) - { - flann_algorithm_t index_type = get_param(params, "algorithm"); - - NNIndex* nnIndex; - switch (index_type) { - case FLANN_INDEX_LINEAR: - nnIndex = new LinearIndex(dataset, params, distance); - break; - case FLANN_INDEX_KMEANS: - nnIndex = new KMeansIndex(dataset, params, distance); - break; - case FLANN_INDEX_HIERARCHICAL: - nnIndex = new HierarchicalClusteringIndex(dataset, params, distance); - break; - case FLANN_INDEX_LSH: - nnIndex = new LshIndex(dataset, params, distance); - break; - default: - FLANN_THROW(cv::Error::StsBadArg, "Unknown index type"); - } - - return nnIndex; - } -}; - -template -NNIndex* create_index_by_type(const Matrix& dataset, const IndexParams& params, const Distance& distance) -{ - return index_creator::create(dataset, params,distance); -} - -} - -//! @endcond - -#endif /* OPENCV_FLANN_ALL_INDICES_H_ */ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * 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 ``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 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 OPENCV_FLANN_ALL_INDICES_H_ +#define OPENCV_FLANN_ALL_INDICES_H_ + +//! @cond IGNORED + +#include "general.h" + +#include "nn_index.h" +#include "kdtree_index.h" +#include "kdtree_single_index.h" +#include "kmeans_index.h" +#include "composite_index.h" +#include "linear_index.h" +#include "hierarchical_clustering_index.h" +#include "lsh_index.h" +#include "autotuned_index.h" + + +namespace cvflann +{ + +template +struct index_creator +{ + static NNIndex* create(const Matrix& dataset, const IndexParams& params, const Distance& distance) + { + flann_algorithm_t index_type = get_param(params, "algorithm"); + + NNIndex* nnIndex; + switch (index_type) { + case FLANN_INDEX_LINEAR: + nnIndex = new LinearIndex(dataset, params, distance); + break; + case FLANN_INDEX_KDTREE_SINGLE: + nnIndex = new KDTreeSingleIndex(dataset, params, distance); + break; + case FLANN_INDEX_KDTREE: + nnIndex = new KDTreeIndex(dataset, params, distance); + break; + case FLANN_INDEX_KMEANS: + nnIndex = new KMeansIndex(dataset, params, distance); + break; + case FLANN_INDEX_COMPOSITE: + nnIndex = new CompositeIndex(dataset, params, distance); + break; + case FLANN_INDEX_AUTOTUNED: + nnIndex = new AutotunedIndex(dataset, params, distance); + break; + case FLANN_INDEX_HIERARCHICAL: + nnIndex = new HierarchicalClusteringIndex(dataset, params, distance); + break; + case FLANN_INDEX_LSH: + nnIndex = new LshIndex(dataset, params, distance); + break; + default: + FLANN_THROW(cv::Error::StsBadArg, "Unknown index type"); + } + + return nnIndex; + } +}; + +template +struct index_creator +{ + static NNIndex* create(const Matrix& dataset, const IndexParams& params, const Distance& distance) + { + flann_algorithm_t index_type = get_param(params, "algorithm"); + + NNIndex* nnIndex; + switch (index_type) { + case FLANN_INDEX_LINEAR: + nnIndex = new LinearIndex(dataset, params, distance); + break; + case FLANN_INDEX_KMEANS: + nnIndex = new KMeansIndex(dataset, params, distance); + break; + case FLANN_INDEX_HIERARCHICAL: + nnIndex = new HierarchicalClusteringIndex(dataset, params, distance); + break; + case FLANN_INDEX_LSH: + nnIndex = new LshIndex(dataset, params, distance); + break; + default: + FLANN_THROW(cv::Error::StsBadArg, "Unknown index type"); + } + + return nnIndex; + } +}; + +template +struct index_creator +{ + static NNIndex* create(const Matrix& dataset, const IndexParams& params, const Distance& distance) + { + flann_algorithm_t index_type = get_param(params, "algorithm"); + + NNIndex* nnIndex; + switch (index_type) { + case FLANN_INDEX_LINEAR: + nnIndex = new LinearIndex(dataset, params, distance); + break; + case FLANN_INDEX_KMEANS: + nnIndex = new KMeansIndex(dataset, params, distance); + break; + case FLANN_INDEX_HIERARCHICAL: + nnIndex = new HierarchicalClusteringIndex(dataset, params, distance); + break; + case FLANN_INDEX_LSH: + nnIndex = new LshIndex(dataset, params, distance); + break; + default: + FLANN_THROW(cv::Error::StsBadArg, "Unknown index type"); + } + + return nnIndex; + } +}; + +template +NNIndex* create_index_by_type(const Matrix& dataset, const IndexParams& params, const Distance& distance) +{ + return index_creator::create(dataset, params,distance); +} + +} + +//! @endcond + +#endif /* OPENCV_FLANN_ALL_INDICES_H_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/allocator.h b/3rdParty/opencv-4.11.0/opencv2/flann/allocator.h index d5870a0181..110858ef70 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/allocator.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/allocator.h @@ -1,196 +1,196 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * 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 ``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 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 OPENCV_FLANN_ALLOCATOR_H_ -#define OPENCV_FLANN_ALLOCATOR_H_ - -//! @cond IGNORED - -#include -#include - - -namespace cvflann -{ - -/** - * Allocates (using C's malloc) a generic type T. - * - * Params: - * count = number of instances to allocate. - * Returns: pointer (of type T*) to memory buffer - */ -template -T* allocate(size_t count = 1) -{ - T* mem = (T*) ::malloc(sizeof(T)*count); - return mem; -} - - -/** - * Pooled storage allocator - * - * The following routines allow for the efficient allocation of storage in - * small chunks from a specified pool. Rather than allowing each structure - * to be freed individually, an entire pool of storage is freed at once. - * This method has two advantages over just using malloc() and free(). First, - * it is far more efficient for allocating small objects, as there is - * no overhead for remembering all the information needed to free each - * object or consolidating fragmented memory. Second, the decision about - * how long to keep an object is made at the time of allocation, and there - * is no need to track down all the objects to free them. - * - */ - -const size_t WORDSIZE=16; -const size_t BLOCKSIZE=8192; - -class PooledAllocator -{ - /* We maintain memory alignment to word boundaries by requiring that all - allocations be in multiples of the machine wordsize. */ - /* Size of machine word in bytes. Must be power of 2. */ - /* Minimum number of bytes requested at a time from the system. Must be multiple of WORDSIZE. */ - - - int remaining; /* Number of bytes left in current block of storage. */ - void* base; /* Pointer to base of current block of storage. */ - void* loc; /* Current location in block to next allocate memory. */ - int blocksize; - - -public: - int usedMemory; - int wastedMemory; - - /** - Default constructor. Initializes a new pool. - */ - PooledAllocator(int blockSize = BLOCKSIZE) - { - blocksize = blockSize; - remaining = 0; - base = NULL; - loc = NULL; - - usedMemory = 0; - wastedMemory = 0; - } - - /** - * Destructor. Frees all the memory allocated in this pool. - */ - ~PooledAllocator() - { - void* prev; - - while (base != NULL) { - prev = *((void**) base); /* Get pointer to prev block. */ - ::free(base); - base = prev; - } - } - - /** - * Returns a pointer to a piece of new memory of the given size in bytes - * allocated from the pool. - */ - void* allocateMemory(int size) - { - int blockSize; - - /* Round size up to a multiple of wordsize. The following expression - only works for WORDSIZE that is a power of 2, by masking last bits of - incremented size to zero. - */ - size = (size + (WORDSIZE - 1)) & ~(WORDSIZE - 1); - - /* Check whether a new block must be allocated. Note that the first word - of a block is reserved for a pointer to the previous block. - */ - if (size > remaining) { - - wastedMemory += remaining; - - /* Allocate new storage. */ - blockSize = (size + sizeof(void*) + (WORDSIZE-1) > BLOCKSIZE) ? - size + sizeof(void*) + (WORDSIZE-1) : BLOCKSIZE; - - // use the standard C malloc to allocate memory - void* m = ::malloc(blockSize); - if (!m) { - fprintf(stderr,"Failed to allocate memory.\n"); - return NULL; - } - - /* Fill first word of new block with pointer to previous block. */ - ((void**) m)[0] = base; - base = m; - - int shift = 0; - //int shift = (WORDSIZE - ( (((size_t)m) + sizeof(void*)) & (WORDSIZE-1))) & (WORDSIZE-1); - - remaining = blockSize - sizeof(void*) - shift; - loc = ((char*)m + sizeof(void*) + shift); - } - void* rloc = loc; - loc = (char*)loc + size; - remaining -= size; - - usedMemory += size; - - return rloc; - } - - /** - * Allocates (using this pool) a generic type T. - * - * Params: - * count = number of instances to allocate. - * Returns: pointer (of type T*) to memory buffer - */ - template - T* allocate(size_t count = 1) - { - T* mem = (T*) this->allocateMemory((int)(sizeof(T)*count)); - return mem; - } - -private: - PooledAllocator(const PooledAllocator &); // copy disabled - PooledAllocator& operator=(const PooledAllocator &); // assign disabled -}; - -} - -//! @endcond - -#endif //OPENCV_FLANN_ALLOCATOR_H_ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * 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 ``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 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 OPENCV_FLANN_ALLOCATOR_H_ +#define OPENCV_FLANN_ALLOCATOR_H_ + +//! @cond IGNORED + +#include +#include + + +namespace cvflann +{ + +/** + * Allocates (using C's malloc) a generic type T. + * + * Params: + * count = number of instances to allocate. + * Returns: pointer (of type T*) to memory buffer + */ +template +T* allocate(size_t count = 1) +{ + T* mem = (T*) ::malloc(sizeof(T)*count); + return mem; +} + + +/** + * Pooled storage allocator + * + * The following routines allow for the efficient allocation of storage in + * small chunks from a specified pool. Rather than allowing each structure + * to be freed individually, an entire pool of storage is freed at once. + * This method has two advantages over just using malloc() and free(). First, + * it is far more efficient for allocating small objects, as there is + * no overhead for remembering all the information needed to free each + * object or consolidating fragmented memory. Second, the decision about + * how long to keep an object is made at the time of allocation, and there + * is no need to track down all the objects to free them. + * + */ + +const size_t WORDSIZE=16; +const size_t BLOCKSIZE=8192; + +class PooledAllocator +{ + /* We maintain memory alignment to word boundaries by requiring that all + allocations be in multiples of the machine wordsize. */ + /* Size of machine word in bytes. Must be power of 2. */ + /* Minimum number of bytes requested at a time from the system. Must be multiple of WORDSIZE. */ + + + int remaining; /* Number of bytes left in current block of storage. */ + void* base; /* Pointer to base of current block of storage. */ + void* loc; /* Current location in block to next allocate memory. */ + int blocksize; + + +public: + int usedMemory; + int wastedMemory; + + /** + Default constructor. Initializes a new pool. + */ + PooledAllocator(int blockSize = BLOCKSIZE) + { + blocksize = blockSize; + remaining = 0; + base = NULL; + loc = NULL; + + usedMemory = 0; + wastedMemory = 0; + } + + /** + * Destructor. Frees all the memory allocated in this pool. + */ + ~PooledAllocator() + { + void* prev; + + while (base != NULL) { + prev = *((void**) base); /* Get pointer to prev block. */ + ::free(base); + base = prev; + } + } + + /** + * Returns a pointer to a piece of new memory of the given size in bytes + * allocated from the pool. + */ + void* allocateMemory(int size) + { + int blockSize; + + /* Round size up to a multiple of wordsize. The following expression + only works for WORDSIZE that is a power of 2, by masking last bits of + incremented size to zero. + */ + size = (size + (WORDSIZE - 1)) & ~(WORDSIZE - 1); + + /* Check whether a new block must be allocated. Note that the first word + of a block is reserved for a pointer to the previous block. + */ + if (size > remaining) { + + wastedMemory += remaining; + + /* Allocate new storage. */ + blockSize = (size + sizeof(void*) + (WORDSIZE-1) > BLOCKSIZE) ? + size + sizeof(void*) + (WORDSIZE-1) : BLOCKSIZE; + + // use the standard C malloc to allocate memory + void* m = ::malloc(blockSize); + if (!m) { + fprintf(stderr,"Failed to allocate memory.\n"); + return NULL; + } + + /* Fill first word of new block with pointer to previous block. */ + ((void**) m)[0] = base; + base = m; + + int shift = 0; + //int shift = (WORDSIZE - ( (((size_t)m) + sizeof(void*)) & (WORDSIZE-1))) & (WORDSIZE-1); + + remaining = blockSize - sizeof(void*) - shift; + loc = ((char*)m + sizeof(void*) + shift); + } + void* rloc = loc; + loc = (char*)loc + size; + remaining -= size; + + usedMemory += size; + + return rloc; + } + + /** + * Allocates (using this pool) a generic type T. + * + * Params: + * count = number of instances to allocate. + * Returns: pointer (of type T*) to memory buffer + */ + template + T* allocate(size_t count = 1) + { + T* mem = (T*) this->allocateMemory((int)(sizeof(T)*count)); + return mem; + } + +private: + PooledAllocator(const PooledAllocator &); // copy disabled + PooledAllocator& operator=(const PooledAllocator &); // assign disabled +}; + +} + +//! @endcond + +#endif //OPENCV_FLANN_ALLOCATOR_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/any.h b/3rdParty/opencv-4.11.0/opencv2/flann/any.h index 2228bd1cfc..bc7df1039c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/any.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/any.h @@ -1,355 +1,355 @@ -#ifndef OPENCV_FLANN_ANY_H_ -#define OPENCV_FLANN_ANY_H_ -/* - * (C) Copyright Christopher Diggins 2005-2011 - * (C) Copyright Pablo Aguilar 2005 - * (C) Copyright Kevlin Henney 2001 - * - * Distributed under the Boost Software License, Version 1.0. (See - * accompanying file LICENSE_1_0.txt or copy at - * http://www.boost.org/LICENSE_1_0.txt - * - * Adapted for FLANN by Marius Muja - */ - -//! @cond IGNORED - -#include "defines.h" -#include -#include -#include - -#include "opencv2/core/cvdef.h" -#include "opencv2/core/utility.hpp" - -namespace cvflann -{ - -namespace anyimpl -{ - -struct bad_any_cast : public std::exception -{ - bad_any_cast() = default; - - bad_any_cast(const char* src, const char* dst) - : message_(cv::format("cvflann::bad_any_cast(from %s to %s)", src, dst)) {} - - - const char* what() const noexcept override - { - return message_.c_str(); - } - -private: - std::string message_{"cvflann::bad_any_cast"}; -}; - -#ifndef CV_THROW_IF_TYPE_MISMATCH -#define CV_THROW_IF_TYPE_MISMATCH(src_type_info, dst_type_info) \ - if ((src_type_info) != (dst_type_info)) \ - throw cvflann::anyimpl::bad_any_cast((src_type_info).name(), \ - (dst_type_info).name()) -#endif - -struct empty_any -{ -}; - -inline std::ostream& operator <<(std::ostream& out, const empty_any&) -{ - out << "[empty_any]"; - return out; -} - -struct base_any_policy -{ - virtual void static_delete(void** x) = 0; - virtual void copy_from_value(void const* src, void** dest) = 0; - virtual void clone(void* const* src, void** dest) = 0; - virtual void move(void* const* src, void** dest) = 0; - virtual void* get_value(void** src) = 0; - virtual const void* get_value(void* const * src) = 0; - virtual ::size_t get_size() = 0; - virtual const std::type_info& type() = 0; - virtual void print(std::ostream& out, void* const* src) = 0; - virtual ~base_any_policy() {} -}; - -template -struct typed_base_any_policy : base_any_policy -{ - virtual ::size_t get_size() CV_OVERRIDE { return sizeof(T); } - virtual const std::type_info& type() CV_OVERRIDE { return typeid(T); } - -}; - -template -struct small_any_policy CV_FINAL : typed_base_any_policy -{ - virtual void static_delete(void**) CV_OVERRIDE { } - virtual void copy_from_value(void const* src, void** dest) CV_OVERRIDE - { - new (dest) T(* reinterpret_cast(src)); - } - virtual void clone(void* const* src, void** dest) CV_OVERRIDE { *dest = *src; } - virtual void move(void* const* src, void** dest) CV_OVERRIDE { *dest = *src; } - virtual void* get_value(void** src) CV_OVERRIDE { return reinterpret_cast(src); } - virtual const void* get_value(void* const * src) CV_OVERRIDE { return reinterpret_cast(src); } - virtual void print(std::ostream& out, void* const* src) CV_OVERRIDE { out << *reinterpret_cast(src); } -}; - -template -struct big_any_policy CV_FINAL : typed_base_any_policy -{ - virtual void static_delete(void** x) CV_OVERRIDE - { - if (* x) delete (* reinterpret_cast(x)); - *x = NULL; - } - virtual void copy_from_value(void const* src, void** dest) CV_OVERRIDE - { - *dest = new T(*reinterpret_cast(src)); - } - virtual void clone(void* const* src, void** dest) CV_OVERRIDE - { - *dest = new T(**reinterpret_cast(src)); - } - virtual void move(void* const* src, void** dest) CV_OVERRIDE - { - (*reinterpret_cast(dest))->~T(); - **reinterpret_cast(dest) = **reinterpret_cast(src); - } - virtual void* get_value(void** src) CV_OVERRIDE { return *src; } - virtual const void* get_value(void* const * src) CV_OVERRIDE { return *src; } - virtual void print(std::ostream& out, void* const* src) CV_OVERRIDE { out << *reinterpret_cast(*src); } -}; - -template<> inline void big_any_policy::print(std::ostream& out, void* const* src) -{ - out << int(*reinterpret_cast(*src)); -} - -template<> inline void big_any_policy::print(std::ostream& out, void* const* src) -{ - out << int(*reinterpret_cast(*src)); -} - -template<> inline void big_any_policy::print(std::ostream& out, void* const* src) -{ - out << (*reinterpret_cast(*src)).c_str(); -} - -template -struct choose_policy -{ - typedef big_any_policy type; -}; - -template -struct choose_policy -{ - typedef small_any_policy type; -}; - -struct any; - -/// Choosing the policy for an any type is illegal, but should never happen. -/// This is designed to throw a compiler error. -template<> -struct choose_policy -{ - typedef void type; -}; - -/// Specializations for small types. -#define SMALL_POLICY(TYPE) \ - template<> \ - struct choose_policy { typedef small_any_policy type; \ - } - -SMALL_POLICY(signed char); -SMALL_POLICY(unsigned char); -SMALL_POLICY(signed short); -SMALL_POLICY(unsigned short); -SMALL_POLICY(signed int); -SMALL_POLICY(unsigned int); -SMALL_POLICY(signed long); -SMALL_POLICY(unsigned long); -SMALL_POLICY(float); -SMALL_POLICY(bool); - -#undef SMALL_POLICY - -template -class SinglePolicy -{ - SinglePolicy(); - SinglePolicy(const SinglePolicy& other); - SinglePolicy& operator=(const SinglePolicy& other); - -public: - static base_any_policy* get_policy(); -}; - -/// This function will return a different policy for each type. -template -inline base_any_policy* SinglePolicy::get_policy() -{ - static typename choose_policy::type policy; - return &policy; -} - -} // namespace anyimpl - -struct any -{ -private: - // fields - anyimpl::base_any_policy* policy; - void* object; - -public: - /// Initializing constructor. - template - any(const T& x) - : policy(anyimpl::SinglePolicy::get_policy()), object(NULL) - { - assign(x); - } - - /// Empty constructor. - any() - : policy(anyimpl::SinglePolicy::get_policy()), object(NULL) - { } - - /// Special initializing constructor for string literals. - any(const char* x) - : policy(anyimpl::SinglePolicy::get_policy()), object(NULL) - { - assign(x); - } - - /// Copy constructor. - any(const any& x) - : policy(anyimpl::SinglePolicy::get_policy()), object(NULL) - { - assign(x); - } - - /// Destructor. - ~any() - { - policy->static_delete(&object); - } - - /// Assignment function from another any. - any& assign(const any& x) - { - reset(); - policy = x.policy; - policy->clone(&x.object, &object); - return *this; - } - - /// Assignment function. - template - any& assign(const T& x) - { - reset(); - policy = anyimpl::SinglePolicy::get_policy(); - policy->copy_from_value(&x, &object); - return *this; - } - - /// Assignment operator. - template - any& operator=(const T& x) - { - return assign(x); - } - - /// Assignment operator. Template-based version above doesn't work as expected. We need regular assignment operator here. - any& operator=(const any& x) - { - return assign(x); - } - - /// Assignment operator, specialed for literal strings. - /// They have types like const char [6] which don't work as expected. - any& operator=(const char* x) - { - return assign(x); - } - - /// Utility functions - any& swap(any& x) - { - std::swap(policy, x.policy); - std::swap(object, x.object); - return *this; - } - - /// Cast operator. You can only cast to the original type. - template - T& cast() - { - CV_THROW_IF_TYPE_MISMATCH(policy->type(), typeid(T)); - T* r = reinterpret_cast(policy->get_value(&object)); - return *r; - } - - /// Cast operator. You can only cast to the original type. - template - const T& cast() const - { - CV_THROW_IF_TYPE_MISMATCH(policy->type(), typeid(T)); - const T* r = reinterpret_cast(policy->get_value(&object)); - return *r; - } - - /// Returns true if the any contains no value. - bool empty() const - { - return policy->type() == typeid(anyimpl::empty_any); - } - - /// Frees any allocated memory, and sets the value to NULL. - void reset() - { - policy->static_delete(&object); - policy = anyimpl::SinglePolicy::get_policy(); - } - - /// Returns true if the two types are the same. - bool compatible(const any& x) const - { - return policy->type() == x.policy->type(); - } - - /// Returns if the type is compatible with the policy - template - bool has_type() - { - return policy->type() == typeid(T); - } - - const std::type_info& type() const - { - return policy->type(); - } - - friend std::ostream& operator <<(std::ostream& out, const any& any_val); -}; - -inline std::ostream& operator <<(std::ostream& out, const any& any_val) -{ - any_val.policy->print(out,&any_val.object); - return out; -} - -} - -//! @endcond - -#endif // OPENCV_FLANN_ANY_H_ +#ifndef OPENCV_FLANN_ANY_H_ +#define OPENCV_FLANN_ANY_H_ +/* + * (C) Copyright Christopher Diggins 2005-2011 + * (C) Copyright Pablo Aguilar 2005 + * (C) Copyright Kevlin Henney 2001 + * + * Distributed under the Boost Software License, Version 1.0. (See + * accompanying file LICENSE_1_0.txt or copy at + * http://www.boost.org/LICENSE_1_0.txt + * + * Adapted for FLANN by Marius Muja + */ + +//! @cond IGNORED + +#include "defines.h" +#include +#include +#include + +#include "opencv2/core/cvdef.h" +#include "opencv2/core/utility.hpp" + +namespace cvflann +{ + +namespace anyimpl +{ + +struct bad_any_cast : public std::exception +{ + bad_any_cast() = default; + + bad_any_cast(const char* src, const char* dst) + : message_(cv::format("cvflann::bad_any_cast(from %s to %s)", src, dst)) {} + + + const char* what() const noexcept override + { + return message_.c_str(); + } + +private: + std::string message_{"cvflann::bad_any_cast"}; +}; + +#ifndef CV_THROW_IF_TYPE_MISMATCH +#define CV_THROW_IF_TYPE_MISMATCH(src_type_info, dst_type_info) \ + if ((src_type_info) != (dst_type_info)) \ + throw cvflann::anyimpl::bad_any_cast((src_type_info).name(), \ + (dst_type_info).name()) +#endif + +struct empty_any +{ +}; + +inline std::ostream& operator <<(std::ostream& out, const empty_any&) +{ + out << "[empty_any]"; + return out; +} + +struct base_any_policy +{ + virtual void static_delete(void** x) = 0; + virtual void copy_from_value(void const* src, void** dest) = 0; + virtual void clone(void* const* src, void** dest) = 0; + virtual void move(void* const* src, void** dest) = 0; + virtual void* get_value(void** src) = 0; + virtual const void* get_value(void* const * src) = 0; + virtual ::size_t get_size() = 0; + virtual const std::type_info& type() = 0; + virtual void print(std::ostream& out, void* const* src) = 0; + virtual ~base_any_policy() {} +}; + +template +struct typed_base_any_policy : base_any_policy +{ + virtual ::size_t get_size() CV_OVERRIDE { return sizeof(T); } + virtual const std::type_info& type() CV_OVERRIDE { return typeid(T); } + +}; + +template +struct small_any_policy CV_FINAL : typed_base_any_policy +{ + virtual void static_delete(void**) CV_OVERRIDE { } + virtual void copy_from_value(void const* src, void** dest) CV_OVERRIDE + { + new (dest) T(* reinterpret_cast(src)); + } + virtual void clone(void* const* src, void** dest) CV_OVERRIDE { *dest = *src; } + virtual void move(void* const* src, void** dest) CV_OVERRIDE { *dest = *src; } + virtual void* get_value(void** src) CV_OVERRIDE { return reinterpret_cast(src); } + virtual const void* get_value(void* const * src) CV_OVERRIDE { return reinterpret_cast(src); } + virtual void print(std::ostream& out, void* const* src) CV_OVERRIDE { out << *reinterpret_cast(src); } +}; + +template +struct big_any_policy CV_FINAL : typed_base_any_policy +{ + virtual void static_delete(void** x) CV_OVERRIDE + { + if (* x) delete (* reinterpret_cast(x)); + *x = NULL; + } + virtual void copy_from_value(void const* src, void** dest) CV_OVERRIDE + { + *dest = new T(*reinterpret_cast(src)); + } + virtual void clone(void* const* src, void** dest) CV_OVERRIDE + { + *dest = new T(**reinterpret_cast(src)); + } + virtual void move(void* const* src, void** dest) CV_OVERRIDE + { + (*reinterpret_cast(dest))->~T(); + **reinterpret_cast(dest) = **reinterpret_cast(src); + } + virtual void* get_value(void** src) CV_OVERRIDE { return *src; } + virtual const void* get_value(void* const * src) CV_OVERRIDE { return *src; } + virtual void print(std::ostream& out, void* const* src) CV_OVERRIDE { out << *reinterpret_cast(*src); } +}; + +template<> inline void big_any_policy::print(std::ostream& out, void* const* src) +{ + out << int(*reinterpret_cast(*src)); +} + +template<> inline void big_any_policy::print(std::ostream& out, void* const* src) +{ + out << int(*reinterpret_cast(*src)); +} + +template<> inline void big_any_policy::print(std::ostream& out, void* const* src) +{ + out << (*reinterpret_cast(*src)).c_str(); +} + +template +struct choose_policy +{ + typedef big_any_policy type; +}; + +template +struct choose_policy +{ + typedef small_any_policy type; +}; + +struct any; + +/// Choosing the policy for an any type is illegal, but should never happen. +/// This is designed to throw a compiler error. +template<> +struct choose_policy +{ + typedef void type; +}; + +/// Specializations for small types. +#define SMALL_POLICY(TYPE) \ + template<> \ + struct choose_policy { typedef small_any_policy type; \ + } + +SMALL_POLICY(signed char); +SMALL_POLICY(unsigned char); +SMALL_POLICY(signed short); +SMALL_POLICY(unsigned short); +SMALL_POLICY(signed int); +SMALL_POLICY(unsigned int); +SMALL_POLICY(signed long); +SMALL_POLICY(unsigned long); +SMALL_POLICY(float); +SMALL_POLICY(bool); + +#undef SMALL_POLICY + +template +class SinglePolicy +{ + SinglePolicy(); + SinglePolicy(const SinglePolicy& other); + SinglePolicy& operator=(const SinglePolicy& other); + +public: + static base_any_policy* get_policy(); +}; + +/// This function will return a different policy for each type. +template +inline base_any_policy* SinglePolicy::get_policy() +{ + static typename choose_policy::type policy; + return &policy; +} + +} // namespace anyimpl + +struct any +{ +private: + // fields + anyimpl::base_any_policy* policy; + void* object; + +public: + /// Initializing constructor. + template + any(const T& x) + : policy(anyimpl::SinglePolicy::get_policy()), object(NULL) + { + assign(x); + } + + /// Empty constructor. + any() + : policy(anyimpl::SinglePolicy::get_policy()), object(NULL) + { } + + /// Special initializing constructor for string literals. + any(const char* x) + : policy(anyimpl::SinglePolicy::get_policy()), object(NULL) + { + assign(x); + } + + /// Copy constructor. + any(const any& x) + : policy(anyimpl::SinglePolicy::get_policy()), object(NULL) + { + assign(x); + } + + /// Destructor. + ~any() + { + policy->static_delete(&object); + } + + /// Assignment function from another any. + any& assign(const any& x) + { + reset(); + policy = x.policy; + policy->clone(&x.object, &object); + return *this; + } + + /// Assignment function. + template + any& assign(const T& x) + { + reset(); + policy = anyimpl::SinglePolicy::get_policy(); + policy->copy_from_value(&x, &object); + return *this; + } + + /// Assignment operator. + template + any& operator=(const T& x) + { + return assign(x); + } + + /// Assignment operator. Template-based version above doesn't work as expected. We need regular assignment operator here. + any& operator=(const any& x) + { + return assign(x); + } + + /// Assignment operator, specialed for literal strings. + /// They have types like const char [6] which don't work as expected. + any& operator=(const char* x) + { + return assign(x); + } + + /// Utility functions + any& swap(any& x) + { + std::swap(policy, x.policy); + std::swap(object, x.object); + return *this; + } + + /// Cast operator. You can only cast to the original type. + template + T& cast() + { + CV_THROW_IF_TYPE_MISMATCH(policy->type(), typeid(T)); + T* r = reinterpret_cast(policy->get_value(&object)); + return *r; + } + + /// Cast operator. You can only cast to the original type. + template + const T& cast() const + { + CV_THROW_IF_TYPE_MISMATCH(policy->type(), typeid(T)); + const T* r = reinterpret_cast(policy->get_value(&object)); + return *r; + } + + /// Returns true if the any contains no value. + bool empty() const + { + return policy->type() == typeid(anyimpl::empty_any); + } + + /// Frees any allocated memory, and sets the value to NULL. + void reset() + { + policy->static_delete(&object); + policy = anyimpl::SinglePolicy::get_policy(); + } + + /// Returns true if the two types are the same. + bool compatible(const any& x) const + { + return policy->type() == x.policy->type(); + } + + /// Returns if the type is compatible with the policy + template + bool has_type() + { + return policy->type() == typeid(T); + } + + const std::type_info& type() const + { + return policy->type(); + } + + friend std::ostream& operator <<(std::ostream& out, const any& any_val); +}; + +inline std::ostream& operator <<(std::ostream& out, const any& any_val) +{ + any_val.policy->print(out,&any_val.object); + return out; +} + +} + +//! @endcond + +#endif // OPENCV_FLANN_ANY_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/autotuned_index.h b/3rdParty/opencv-4.11.0/opencv2/flann/autotuned_index.h index d90f739aff..32a0ab0852 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/autotuned_index.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/autotuned_index.h @@ -1,594 +1,594 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * 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 ``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 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 OPENCV_FLANN_AUTOTUNED_INDEX_H_ -#define OPENCV_FLANN_AUTOTUNED_INDEX_H_ - -//! @cond IGNORED - -#include - -#include "nn_index.h" -#include "ground_truth.h" -#include "index_testing.h" -#include "sampling.h" -#include "kdtree_index.h" -#include "kdtree_single_index.h" -#include "kmeans_index.h" -#include "composite_index.h" -#include "linear_index.h" -#include "logger.h" - -namespace cvflann -{ - -template -NNIndex* create_index_by_type(const Matrix& dataset, const IndexParams& params, const Distance& distance); - - -struct AutotunedIndexParams : public IndexParams -{ - AutotunedIndexParams(float target_precision = 0.8, float build_weight = 0.01, float memory_weight = 0, float sample_fraction = 0.1) - { - (*this)["algorithm"] = FLANN_INDEX_AUTOTUNED; - // precision desired (used for autotuning, -1 otherwise) - (*this)["target_precision"] = target_precision; - // build tree time weighting factor - (*this)["build_weight"] = build_weight; - // index memory weighting factor - (*this)["memory_weight"] = memory_weight; - // what fraction of the dataset to use for autotuning - (*this)["sample_fraction"] = sample_fraction; - } -}; - - -template -class AutotunedIndex : public NNIndex -{ -public: - typedef typename Distance::ElementType ElementType; - typedef typename Distance::ResultType DistanceType; - - AutotunedIndex(const Matrix& inputData, const IndexParams& params = AutotunedIndexParams(), Distance d = Distance()) : - dataset_(inputData), distance_(d) - { - target_precision_ = get_param(params, "target_precision",0.8f); - build_weight_ = get_param(params,"build_weight", 0.01f); - memory_weight_ = get_param(params, "memory_weight", 0.0f); - sample_fraction_ = get_param(params,"sample_fraction", 0.1f); - bestIndex_ = NULL; - speedup_ = 0; - } - - AutotunedIndex(const AutotunedIndex&); - AutotunedIndex& operator=(const AutotunedIndex&); - - virtual ~AutotunedIndex() - { - if (bestIndex_ != NULL) { - delete bestIndex_; - bestIndex_ = NULL; - } - } - - /** - * Method responsible with building the index. - */ - virtual void buildIndex() CV_OVERRIDE - { - std::ostringstream stream; - bestParams_ = estimateBuildParams(); - print_params(bestParams_, stream); - Logger::info("----------------------------------------------------\n"); - Logger::info("Autotuned parameters:\n"); - Logger::info("%s", stream.str().c_str()); - Logger::info("----------------------------------------------------\n"); - - bestIndex_ = create_index_by_type(dataset_, bestParams_, distance_); - bestIndex_->buildIndex(); - speedup_ = estimateSearchParams(bestSearchParams_); - stream.str(std::string()); - print_params(bestSearchParams_, stream); - Logger::info("----------------------------------------------------\n"); - Logger::info("Search parameters:\n"); - Logger::info("%s", stream.str().c_str()); - Logger::info("----------------------------------------------------\n"); - } - - /** - * Saves the index to a stream - */ - virtual void saveIndex(FILE* stream) CV_OVERRIDE - { - save_value(stream, (int)bestIndex_->getType()); - bestIndex_->saveIndex(stream); - save_value(stream, get_param(bestSearchParams_, "checks")); - } - - /** - * Loads the index from a stream - */ - virtual void loadIndex(FILE* stream) CV_OVERRIDE - { - int index_type; - - load_value(stream, index_type); - IndexParams params; - params["algorithm"] = (flann_algorithm_t)index_type; - bestIndex_ = create_index_by_type(dataset_, params, distance_); - bestIndex_->loadIndex(stream); - int checks; - load_value(stream, checks); - bestSearchParams_["checks"] = checks; - } - - /** - * Method that searches for nearest-neighbors - */ - virtual void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE - { - int checks = get_param(searchParams,"checks",FLANN_CHECKS_AUTOTUNED); - if (checks == FLANN_CHECKS_AUTOTUNED) { - bestIndex_->findNeighbors(result, vec, bestSearchParams_); - } - else { - bestIndex_->findNeighbors(result, vec, searchParams); - } - } - - - IndexParams getParameters() const CV_OVERRIDE - { - return bestIndex_->getParameters(); - } - - SearchParams getSearchParameters() const - { - return bestSearchParams_; - } - - float getSpeedup() const - { - return speedup_; - } - - - /** - * Number of features in this index. - */ - virtual size_t size() const CV_OVERRIDE - { - return bestIndex_->size(); - } - - /** - * The length of each vector in this index. - */ - virtual size_t veclen() const CV_OVERRIDE - { - return bestIndex_->veclen(); - } - - /** - * The amount of memory (in bytes) this index uses. - */ - virtual int usedMemory() const CV_OVERRIDE - { - return bestIndex_->usedMemory(); - } - - /** - * Algorithm name - */ - virtual flann_algorithm_t getType() const CV_OVERRIDE - { - return FLANN_INDEX_AUTOTUNED; - } - -private: - - struct CostData - { - float searchTimeCost; - float buildTimeCost; - float memoryCost; - float totalCost; - IndexParams params; - }; - - void evaluate_kmeans(CostData& cost) - { - StartStopTimer t; - int checks; - const int nn = 1; - - Logger::info("KMeansTree using params: max_iterations=%d, branching=%d\n", - get_param(cost.params,"iterations"), - get_param(cost.params,"branching")); - KMeansIndex kmeans(sampledDataset_, cost.params, distance_); - // measure index build time - t.start(); - kmeans.buildIndex(); - t.stop(); - float buildTime = (float)t.value; - - // measure search time - float searchTime = test_index_precision(kmeans, sampledDataset_, testDataset_, gt_matches_, target_precision_, checks, distance_, nn); - - float datasetMemory = float(sampledDataset_.rows * sampledDataset_.cols * sizeof(float)); - cost.memoryCost = (kmeans.usedMemory() + datasetMemory) / datasetMemory; - cost.searchTimeCost = searchTime; - cost.buildTimeCost = buildTime; - Logger::info("KMeansTree buildTime=%g, searchTime=%g, build_weight=%g\n", buildTime, searchTime, build_weight_); - } - - - void evaluate_kdtree(CostData& cost) - { - StartStopTimer t; - int checks; - const int nn = 1; - - Logger::info("KDTree using params: trees=%d\n", get_param(cost.params,"trees")); - KDTreeIndex kdtree(sampledDataset_, cost.params, distance_); - - t.start(); - kdtree.buildIndex(); - t.stop(); - float buildTime = (float)t.value; - - //measure search time - float searchTime = test_index_precision(kdtree, sampledDataset_, testDataset_, gt_matches_, target_precision_, checks, distance_, nn); - - float datasetMemory = float(sampledDataset_.rows * sampledDataset_.cols * sizeof(float)); - cost.memoryCost = (kdtree.usedMemory() + datasetMemory) / datasetMemory; - cost.searchTimeCost = searchTime; - cost.buildTimeCost = buildTime; - Logger::info("KDTree buildTime=%g, searchTime=%g\n", buildTime, searchTime); - } - - - // struct KMeansSimpleDownhillFunctor { - // - // Autotune& autotuner; - // KMeansSimpleDownhillFunctor(Autotune& autotuner_) : autotuner(autotuner_) {} - // - // float operator()(int* params) { - // - // float maxFloat = numeric_limits::max(); - // - // if (params[0]<2) return maxFloat; - // if (params[1]<0) return maxFloat; - // - // CostData c; - // c.params["algorithm"] = KMEANS; - // c.params["centers-init"] = CENTERS_RANDOM; - // c.params["branching"] = params[0]; - // c.params["max-iterations"] = params[1]; - // - // autotuner.evaluate_kmeans(c); - // - // return c.timeCost; - // - // } - // }; - // - // struct KDTreeSimpleDownhillFunctor { - // - // Autotune& autotuner; - // KDTreeSimpleDownhillFunctor(Autotune& autotuner_) : autotuner(autotuner_) {} - // - // float operator()(int* params) { - // float maxFloat = numeric_limits::max(); - // - // if (params[0]<1) return maxFloat; - // - // CostData c; - // c.params["algorithm"] = KDTREE; - // c.params["trees"] = params[0]; - // - // autotuner.evaluate_kdtree(c); - // - // return c.timeCost; - // - // } - // }; - - - - void optimizeKMeans(std::vector& costs) - { - Logger::info("KMEANS, Step 1: Exploring parameter space\n"); - - // explore kmeans parameters space using combinations of the parameters below - int maxIterations[] = { 1, 5, 10, 15 }; - int branchingFactors[] = { 16, 32, 64, 128, 256 }; - - int kmeansParamSpaceSize = FLANN_ARRAY_LEN(maxIterations) * FLANN_ARRAY_LEN(branchingFactors); - costs.reserve(costs.size() + kmeansParamSpaceSize); - - // evaluate kmeans for all parameter combinations - for (size_t i = 0; i < FLANN_ARRAY_LEN(maxIterations); ++i) { - for (size_t j = 0; j < FLANN_ARRAY_LEN(branchingFactors); ++j) { - CostData cost; - cost.params["algorithm"] = FLANN_INDEX_KMEANS; - cost.params["centers_init"] = FLANN_CENTERS_RANDOM; - cost.params["iterations"] = maxIterations[i]; - cost.params["branching"] = branchingFactors[j]; - - evaluate_kmeans(cost); - costs.push_back(cost); - } - } - - // Logger::info("KMEANS, Step 2: simplex-downhill optimization\n"); - // - // const int n = 2; - // // choose initial simplex points as the best parameters so far - // int kmeansNMPoints[n*(n+1)]; - // float kmeansVals[n+1]; - // for (int i=0;i& costs) - { - Logger::info("KD-TREE, Step 1: Exploring parameter space\n"); - - // explore kd-tree parameters space using the parameters below - int testTrees[] = { 1, 4, 8, 16, 32 }; - - // evaluate kdtree for all parameter combinations - for (size_t i = 0; i < FLANN_ARRAY_LEN(testTrees); ++i) { - CostData cost; - cost.params["algorithm"] = FLANN_INDEX_KDTREE; - cost.params["trees"] = testTrees[i]; - - evaluate_kdtree(cost); - costs.push_back(cost); - } - - // Logger::info("KD-TREE, Step 2: simplex-downhill optimization\n"); - // - // const int n = 1; - // // choose initial simplex points as the best parameters so far - // int kdtreeNMPoints[n*(n+1)]; - // float kdtreeVals[n+1]; - // for (int i=0;i costs; - - int sampleSize = int(sample_fraction_ * dataset_.rows); - int testSampleSize = std::min(sampleSize / 10, 1000); - - Logger::info("Entering autotuning, dataset size: %d, sampleSize: %d, testSampleSize: %d, target precision: %g\n", dataset_.rows, sampleSize, testSampleSize, target_precision_); - - // For a very small dataset, it makes no sense to build any fancy index, just - // use linear search - if (testSampleSize < 10) { - Logger::info("Choosing linear, dataset too small\n"); - return LinearIndexParams(); - } - - // We use a fraction of the original dataset to speedup the autotune algorithm - sampledDataset_ = random_sample(dataset_, sampleSize); - // We use a cross-validation approach, first we sample a testset from the dataset - testDataset_ = random_sample(sampledDataset_, testSampleSize, true); - - // We compute the ground truth using linear search - Logger::info("Computing ground truth... \n"); - gt_matches_ = Matrix(new int[testDataset_.rows], testDataset_.rows, 1); - StartStopTimer t; - t.start(); - compute_ground_truth(sampledDataset_, testDataset_, gt_matches_, 0, distance_); - t.stop(); - - CostData linear_cost; - linear_cost.searchTimeCost = (float)t.value; - linear_cost.buildTimeCost = 0; - linear_cost.memoryCost = 0; - linear_cost.params["algorithm"] = FLANN_INDEX_LINEAR; - - costs.push_back(linear_cost); - - // Start parameter autotune process - Logger::info("Autotuning parameters...\n"); - - optimizeKMeans(costs); - optimizeKDTree(costs); - - float bestTimeCost = costs[0].searchTimeCost; - for (size_t i = 0; i < costs.size(); ++i) { - float timeCost = costs[i].buildTimeCost * build_weight_ + costs[i].searchTimeCost; - if (timeCost < bestTimeCost) { - bestTimeCost = timeCost; - } - } - - float bestCost = costs[0].searchTimeCost / bestTimeCost; - IndexParams bestParams = costs[0].params; - if (bestTimeCost > 0) { - for (size_t i = 0; i < costs.size(); ++i) { - float crtCost = (costs[i].buildTimeCost * build_weight_ + costs[i].searchTimeCost) / bestTimeCost + - memory_weight_ * costs[i].memoryCost; - if (crtCost < bestCost) { - bestCost = crtCost; - bestParams = costs[i].params; - } - } - } - - delete[] gt_matches_.data; - delete[] testDataset_.data; - delete[] sampledDataset_.data; - - return bestParams; - } - - - - /** - * Estimates the search time parameters needed to get the desired precision. - * Precondition: the index is built - * Postcondition: the searchParams will have the optimum params set, also the speedup obtained over linear search. - */ - float estimateSearchParams(SearchParams& searchParams) - { - const int nn = 1; - const size_t SAMPLE_COUNT = 1000; - - CV_Assert(bestIndex_ != NULL && "Requires a valid index"); // must have a valid index - - float speedup = 0; - - int samples = (int)std::min(dataset_.rows / 10, SAMPLE_COUNT); - if (samples > 0) { - Matrix testDataset = random_sample(dataset_, samples); - - Logger::info("Computing ground truth\n"); - - // we need to compute the ground truth first - Matrix gt_matches(new int[testDataset.rows], testDataset.rows, 1); - StartStopTimer t; - t.start(); - compute_ground_truth(dataset_, testDataset, gt_matches, 1, distance_); - t.stop(); - float linear = (float)t.value; - - int checks; - Logger::info("Estimating number of checks\n"); - - float searchTime; - float cb_index; - if (bestIndex_->getType() == FLANN_INDEX_KMEANS) { - Logger::info("KMeans algorithm, estimating cluster border factor\n"); - KMeansIndex* kmeans = (KMeansIndex*)bestIndex_; - float bestSearchTime = -1; - float best_cb_index = -1; - int best_checks = -1; - for (cb_index = 0; cb_index < 1.1f; cb_index += 0.2f) { - kmeans->set_cb_index(cb_index); - searchTime = test_index_precision(*kmeans, dataset_, testDataset, gt_matches, target_precision_, checks, distance_, nn, 1); - if ((searchTime < bestSearchTime) || (bestSearchTime == -1)) { - bestSearchTime = searchTime; - best_cb_index = cb_index; - best_checks = checks; - } - } - searchTime = bestSearchTime; - cb_index = best_cb_index; - checks = best_checks; - - kmeans->set_cb_index(best_cb_index); - Logger::info("Optimum cb_index: %g\n", cb_index); - bestParams_["cb_index"] = cb_index; - } - else { - searchTime = test_index_precision(*bestIndex_, dataset_, testDataset, gt_matches, target_precision_, checks, distance_, nn, 1); - } - - Logger::info("Required number of checks: %d \n", checks); - searchParams["checks"] = checks; - - speedup = linear / searchTime; - - delete[] gt_matches.data; - delete[] testDataset.data; - } - - return speedup; - } - -private: - NNIndex* bestIndex_; - - IndexParams bestParams_; - SearchParams bestSearchParams_; - - Matrix sampledDataset_; - Matrix testDataset_; - Matrix gt_matches_; - - float speedup_; - - /** - * The dataset used by this index - */ - const Matrix dataset_; - - /** - * Index parameters - */ - float target_precision_; - float build_weight_; - float memory_weight_; - float sample_fraction_; - - Distance distance_; - - -}; -} - -//! @endcond - -#endif /* OPENCV_FLANN_AUTOTUNED_INDEX_H_ */ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * 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 ``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 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 OPENCV_FLANN_AUTOTUNED_INDEX_H_ +#define OPENCV_FLANN_AUTOTUNED_INDEX_H_ + +//! @cond IGNORED + +#include + +#include "nn_index.h" +#include "ground_truth.h" +#include "index_testing.h" +#include "sampling.h" +#include "kdtree_index.h" +#include "kdtree_single_index.h" +#include "kmeans_index.h" +#include "composite_index.h" +#include "linear_index.h" +#include "logger.h" + +namespace cvflann +{ + +template +NNIndex* create_index_by_type(const Matrix& dataset, const IndexParams& params, const Distance& distance); + + +struct AutotunedIndexParams : public IndexParams +{ + AutotunedIndexParams(float target_precision = 0.8, float build_weight = 0.01, float memory_weight = 0, float sample_fraction = 0.1) + { + (*this)["algorithm"] = FLANN_INDEX_AUTOTUNED; + // precision desired (used for autotuning, -1 otherwise) + (*this)["target_precision"] = target_precision; + // build tree time weighting factor + (*this)["build_weight"] = build_weight; + // index memory weighting factor + (*this)["memory_weight"] = memory_weight; + // what fraction of the dataset to use for autotuning + (*this)["sample_fraction"] = sample_fraction; + } +}; + + +template +class AutotunedIndex : public NNIndex +{ +public: + typedef typename Distance::ElementType ElementType; + typedef typename Distance::ResultType DistanceType; + + AutotunedIndex(const Matrix& inputData, const IndexParams& params = AutotunedIndexParams(), Distance d = Distance()) : + dataset_(inputData), distance_(d) + { + target_precision_ = get_param(params, "target_precision",0.8f); + build_weight_ = get_param(params,"build_weight", 0.01f); + memory_weight_ = get_param(params, "memory_weight", 0.0f); + sample_fraction_ = get_param(params,"sample_fraction", 0.1f); + bestIndex_ = NULL; + speedup_ = 0; + } + + AutotunedIndex(const AutotunedIndex&); + AutotunedIndex& operator=(const AutotunedIndex&); + + virtual ~AutotunedIndex() + { + if (bestIndex_ != NULL) { + delete bestIndex_; + bestIndex_ = NULL; + } + } + + /** + * Method responsible with building the index. + */ + virtual void buildIndex() CV_OVERRIDE + { + std::ostringstream stream; + bestParams_ = estimateBuildParams(); + print_params(bestParams_, stream); + Logger::info("----------------------------------------------------\n"); + Logger::info("Autotuned parameters:\n"); + Logger::info("%s", stream.str().c_str()); + Logger::info("----------------------------------------------------\n"); + + bestIndex_ = create_index_by_type(dataset_, bestParams_, distance_); + bestIndex_->buildIndex(); + speedup_ = estimateSearchParams(bestSearchParams_); + stream.str(std::string()); + print_params(bestSearchParams_, stream); + Logger::info("----------------------------------------------------\n"); + Logger::info("Search parameters:\n"); + Logger::info("%s", stream.str().c_str()); + Logger::info("----------------------------------------------------\n"); + } + + /** + * Saves the index to a stream + */ + virtual void saveIndex(FILE* stream) CV_OVERRIDE + { + save_value(stream, (int)bestIndex_->getType()); + bestIndex_->saveIndex(stream); + save_value(stream, get_param(bestSearchParams_, "checks")); + } + + /** + * Loads the index from a stream + */ + virtual void loadIndex(FILE* stream) CV_OVERRIDE + { + int index_type; + + load_value(stream, index_type); + IndexParams params; + params["algorithm"] = (flann_algorithm_t)index_type; + bestIndex_ = create_index_by_type(dataset_, params, distance_); + bestIndex_->loadIndex(stream); + int checks; + load_value(stream, checks); + bestSearchParams_["checks"] = checks; + } + + /** + * Method that searches for nearest-neighbors + */ + virtual void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE + { + int checks = get_param(searchParams,"checks",FLANN_CHECKS_AUTOTUNED); + if (checks == FLANN_CHECKS_AUTOTUNED) { + bestIndex_->findNeighbors(result, vec, bestSearchParams_); + } + else { + bestIndex_->findNeighbors(result, vec, searchParams); + } + } + + + IndexParams getParameters() const CV_OVERRIDE + { + return bestIndex_->getParameters(); + } + + SearchParams getSearchParameters() const + { + return bestSearchParams_; + } + + float getSpeedup() const + { + return speedup_; + } + + + /** + * Number of features in this index. + */ + virtual size_t size() const CV_OVERRIDE + { + return bestIndex_->size(); + } + + /** + * The length of each vector in this index. + */ + virtual size_t veclen() const CV_OVERRIDE + { + return bestIndex_->veclen(); + } + + /** + * The amount of memory (in bytes) this index uses. + */ + virtual int usedMemory() const CV_OVERRIDE + { + return bestIndex_->usedMemory(); + } + + /** + * Algorithm name + */ + virtual flann_algorithm_t getType() const CV_OVERRIDE + { + return FLANN_INDEX_AUTOTUNED; + } + +private: + + struct CostData + { + float searchTimeCost; + float buildTimeCost; + float memoryCost; + float totalCost; + IndexParams params; + }; + + void evaluate_kmeans(CostData& cost) + { + StartStopTimer t; + int checks; + const int nn = 1; + + Logger::info("KMeansTree using params: max_iterations=%d, branching=%d\n", + get_param(cost.params,"iterations"), + get_param(cost.params,"branching")); + KMeansIndex kmeans(sampledDataset_, cost.params, distance_); + // measure index build time + t.start(); + kmeans.buildIndex(); + t.stop(); + float buildTime = (float)t.value; + + // measure search time + float searchTime = test_index_precision(kmeans, sampledDataset_, testDataset_, gt_matches_, target_precision_, checks, distance_, nn); + + float datasetMemory = float(sampledDataset_.rows * sampledDataset_.cols * sizeof(float)); + cost.memoryCost = (kmeans.usedMemory() + datasetMemory) / datasetMemory; + cost.searchTimeCost = searchTime; + cost.buildTimeCost = buildTime; + Logger::info("KMeansTree buildTime=%g, searchTime=%g, build_weight=%g\n", buildTime, searchTime, build_weight_); + } + + + void evaluate_kdtree(CostData& cost) + { + StartStopTimer t; + int checks; + const int nn = 1; + + Logger::info("KDTree using params: trees=%d\n", get_param(cost.params,"trees")); + KDTreeIndex kdtree(sampledDataset_, cost.params, distance_); + + t.start(); + kdtree.buildIndex(); + t.stop(); + float buildTime = (float)t.value; + + //measure search time + float searchTime = test_index_precision(kdtree, sampledDataset_, testDataset_, gt_matches_, target_precision_, checks, distance_, nn); + + float datasetMemory = float(sampledDataset_.rows * sampledDataset_.cols * sizeof(float)); + cost.memoryCost = (kdtree.usedMemory() + datasetMemory) / datasetMemory; + cost.searchTimeCost = searchTime; + cost.buildTimeCost = buildTime; + Logger::info("KDTree buildTime=%g, searchTime=%g\n", buildTime, searchTime); + } + + + // struct KMeansSimpleDownhillFunctor { + // + // Autotune& autotuner; + // KMeansSimpleDownhillFunctor(Autotune& autotuner_) : autotuner(autotuner_) {} + // + // float operator()(int* params) { + // + // float maxFloat = numeric_limits::max(); + // + // if (params[0]<2) return maxFloat; + // if (params[1]<0) return maxFloat; + // + // CostData c; + // c.params["algorithm"] = KMEANS; + // c.params["centers-init"] = CENTERS_RANDOM; + // c.params["branching"] = params[0]; + // c.params["max-iterations"] = params[1]; + // + // autotuner.evaluate_kmeans(c); + // + // return c.timeCost; + // + // } + // }; + // + // struct KDTreeSimpleDownhillFunctor { + // + // Autotune& autotuner; + // KDTreeSimpleDownhillFunctor(Autotune& autotuner_) : autotuner(autotuner_) {} + // + // float operator()(int* params) { + // float maxFloat = numeric_limits::max(); + // + // if (params[0]<1) return maxFloat; + // + // CostData c; + // c.params["algorithm"] = KDTREE; + // c.params["trees"] = params[0]; + // + // autotuner.evaluate_kdtree(c); + // + // return c.timeCost; + // + // } + // }; + + + + void optimizeKMeans(std::vector& costs) + { + Logger::info("KMEANS, Step 1: Exploring parameter space\n"); + + // explore kmeans parameters space using combinations of the parameters below + int maxIterations[] = { 1, 5, 10, 15 }; + int branchingFactors[] = { 16, 32, 64, 128, 256 }; + + int kmeansParamSpaceSize = FLANN_ARRAY_LEN(maxIterations) * FLANN_ARRAY_LEN(branchingFactors); + costs.reserve(costs.size() + kmeansParamSpaceSize); + + // evaluate kmeans for all parameter combinations + for (size_t i = 0; i < FLANN_ARRAY_LEN(maxIterations); ++i) { + for (size_t j = 0; j < FLANN_ARRAY_LEN(branchingFactors); ++j) { + CostData cost; + cost.params["algorithm"] = FLANN_INDEX_KMEANS; + cost.params["centers_init"] = FLANN_CENTERS_RANDOM; + cost.params["iterations"] = maxIterations[i]; + cost.params["branching"] = branchingFactors[j]; + + evaluate_kmeans(cost); + costs.push_back(cost); + } + } + + // Logger::info("KMEANS, Step 2: simplex-downhill optimization\n"); + // + // const int n = 2; + // // choose initial simplex points as the best parameters so far + // int kmeansNMPoints[n*(n+1)]; + // float kmeansVals[n+1]; + // for (int i=0;i& costs) + { + Logger::info("KD-TREE, Step 1: Exploring parameter space\n"); + + // explore kd-tree parameters space using the parameters below + int testTrees[] = { 1, 4, 8, 16, 32 }; + + // evaluate kdtree for all parameter combinations + for (size_t i = 0; i < FLANN_ARRAY_LEN(testTrees); ++i) { + CostData cost; + cost.params["algorithm"] = FLANN_INDEX_KDTREE; + cost.params["trees"] = testTrees[i]; + + evaluate_kdtree(cost); + costs.push_back(cost); + } + + // Logger::info("KD-TREE, Step 2: simplex-downhill optimization\n"); + // + // const int n = 1; + // // choose initial simplex points as the best parameters so far + // int kdtreeNMPoints[n*(n+1)]; + // float kdtreeVals[n+1]; + // for (int i=0;i costs; + + int sampleSize = int(sample_fraction_ * dataset_.rows); + int testSampleSize = std::min(sampleSize / 10, 1000); + + Logger::info("Entering autotuning, dataset size: %d, sampleSize: %d, testSampleSize: %d, target precision: %g\n", dataset_.rows, sampleSize, testSampleSize, target_precision_); + + // For a very small dataset, it makes no sense to build any fancy index, just + // use linear search + if (testSampleSize < 10) { + Logger::info("Choosing linear, dataset too small\n"); + return LinearIndexParams(); + } + + // We use a fraction of the original dataset to speedup the autotune algorithm + sampledDataset_ = random_sample(dataset_, sampleSize); + // We use a cross-validation approach, first we sample a testset from the dataset + testDataset_ = random_sample(sampledDataset_, testSampleSize, true); + + // We compute the ground truth using linear search + Logger::info("Computing ground truth... \n"); + gt_matches_ = Matrix(new int[testDataset_.rows], testDataset_.rows, 1); + StartStopTimer t; + t.start(); + compute_ground_truth(sampledDataset_, testDataset_, gt_matches_, 0, distance_); + t.stop(); + + CostData linear_cost; + linear_cost.searchTimeCost = (float)t.value; + linear_cost.buildTimeCost = 0; + linear_cost.memoryCost = 0; + linear_cost.params["algorithm"] = FLANN_INDEX_LINEAR; + + costs.push_back(linear_cost); + + // Start parameter autotune process + Logger::info("Autotuning parameters...\n"); + + optimizeKMeans(costs); + optimizeKDTree(costs); + + float bestTimeCost = costs[0].searchTimeCost; + for (size_t i = 0; i < costs.size(); ++i) { + float timeCost = costs[i].buildTimeCost * build_weight_ + costs[i].searchTimeCost; + if (timeCost < bestTimeCost) { + bestTimeCost = timeCost; + } + } + + float bestCost = costs[0].searchTimeCost / bestTimeCost; + IndexParams bestParams = costs[0].params; + if (bestTimeCost > 0) { + for (size_t i = 0; i < costs.size(); ++i) { + float crtCost = (costs[i].buildTimeCost * build_weight_ + costs[i].searchTimeCost) / bestTimeCost + + memory_weight_ * costs[i].memoryCost; + if (crtCost < bestCost) { + bestCost = crtCost; + bestParams = costs[i].params; + } + } + } + + delete[] gt_matches_.data; + delete[] testDataset_.data; + delete[] sampledDataset_.data; + + return bestParams; + } + + + + /** + * Estimates the search time parameters needed to get the desired precision. + * Precondition: the index is built + * Postcondition: the searchParams will have the optimum params set, also the speedup obtained over linear search. + */ + float estimateSearchParams(SearchParams& searchParams) + { + const int nn = 1; + const size_t SAMPLE_COUNT = 1000; + + CV_Assert(bestIndex_ != NULL && "Requires a valid index"); // must have a valid index + + float speedup = 0; + + int samples = (int)std::min(dataset_.rows / 10, SAMPLE_COUNT); + if (samples > 0) { + Matrix testDataset = random_sample(dataset_, samples); + + Logger::info("Computing ground truth\n"); + + // we need to compute the ground truth first + Matrix gt_matches(new int[testDataset.rows], testDataset.rows, 1); + StartStopTimer t; + t.start(); + compute_ground_truth(dataset_, testDataset, gt_matches, 1, distance_); + t.stop(); + float linear = (float)t.value; + + int checks; + Logger::info("Estimating number of checks\n"); + + float searchTime; + float cb_index; + if (bestIndex_->getType() == FLANN_INDEX_KMEANS) { + Logger::info("KMeans algorithm, estimating cluster border factor\n"); + KMeansIndex* kmeans = (KMeansIndex*)bestIndex_; + float bestSearchTime = -1; + float best_cb_index = -1; + int best_checks = -1; + for (cb_index = 0; cb_index < 1.1f; cb_index += 0.2f) { + kmeans->set_cb_index(cb_index); + searchTime = test_index_precision(*kmeans, dataset_, testDataset, gt_matches, target_precision_, checks, distance_, nn, 1); + if ((searchTime < bestSearchTime) || (bestSearchTime == -1)) { + bestSearchTime = searchTime; + best_cb_index = cb_index; + best_checks = checks; + } + } + searchTime = bestSearchTime; + cb_index = best_cb_index; + checks = best_checks; + + kmeans->set_cb_index(best_cb_index); + Logger::info("Optimum cb_index: %g\n", cb_index); + bestParams_["cb_index"] = cb_index; + } + else { + searchTime = test_index_precision(*bestIndex_, dataset_, testDataset, gt_matches, target_precision_, checks, distance_, nn, 1); + } + + Logger::info("Required number of checks: %d \n", checks); + searchParams["checks"] = checks; + + speedup = linear / searchTime; + + delete[] gt_matches.data; + delete[] testDataset.data; + } + + return speedup; + } + +private: + NNIndex* bestIndex_; + + IndexParams bestParams_; + SearchParams bestSearchParams_; + + Matrix sampledDataset_; + Matrix testDataset_; + Matrix gt_matches_; + + float speedup_; + + /** + * The dataset used by this index + */ + const Matrix dataset_; + + /** + * Index parameters + */ + float target_precision_; + float build_weight_; + float memory_weight_; + float sample_fraction_; + + Distance distance_; + + +}; +} + +//! @endcond + +#endif /* OPENCV_FLANN_AUTOTUNED_INDEX_H_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/composite_index.h b/3rdParty/opencv-4.11.0/opencv2/flann/composite_index.h index 37a6223f88..1edaf557a3 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/composite_index.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/composite_index.h @@ -1,196 +1,196 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * 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 ``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 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 OPENCV_FLANN_COMPOSITE_INDEX_H_ -#define OPENCV_FLANN_COMPOSITE_INDEX_H_ - -//! @cond IGNORED - -#include "nn_index.h" -#include "kdtree_index.h" -#include "kmeans_index.h" - -namespace cvflann -{ - -/** - * Index parameters for the CompositeIndex. - */ -struct CompositeIndexParams : public IndexParams -{ - CompositeIndexParams(int trees = 4, int branching = 32, int iterations = 11, - flann_centers_init_t centers_init = FLANN_CENTERS_RANDOM, float cb_index = 0.2 ) - { - (*this)["algorithm"] = FLANN_INDEX_KMEANS; - // number of randomized trees to use (for kdtree) - (*this)["trees"] = trees; - // branching factor - (*this)["branching"] = branching; - // max iterations to perform in one kmeans clustering (kmeans tree) - (*this)["iterations"] = iterations; - // algorithm used for picking the initial cluster centers for kmeans tree - (*this)["centers_init"] = centers_init; - // cluster boundary index. Used when searching the kmeans tree - (*this)["cb_index"] = cb_index; - } -}; - - -/** - * This index builds a kd-tree index and a k-means index and performs nearest - * neighbour search both indexes. This gives a slight boost in search performance - * as some of the neighbours that are missed by one index are found by the other. - */ -template -class CompositeIndex : public NNIndex -{ -public: - typedef typename Distance::ElementType ElementType; - typedef typename Distance::ResultType DistanceType; - - /** - * Index constructor - * @param inputData dataset containing the points to index - * @param params Index parameters - * @param d Distance functor - */ - CompositeIndex(const Matrix& inputData, const IndexParams& params = CompositeIndexParams(), - Distance d = Distance()) : index_params_(params) - { - kdtree_index_ = new KDTreeIndex(inputData, params, d); - kmeans_index_ = new KMeansIndex(inputData, params, d); - - } - - CompositeIndex(const CompositeIndex&); - CompositeIndex& operator=(const CompositeIndex&); - - virtual ~CompositeIndex() - { - delete kdtree_index_; - delete kmeans_index_; - } - - /** - * @return The index type - */ - flann_algorithm_t getType() const CV_OVERRIDE - { - return FLANN_INDEX_COMPOSITE; - } - - /** - * @return Size of the index - */ - size_t size() const CV_OVERRIDE - { - return kdtree_index_->size(); - } - - /** - * \returns The dimensionality of the features in this index. - */ - size_t veclen() const CV_OVERRIDE - { - return kdtree_index_->veclen(); - } - - /** - * \returns The amount of memory (in bytes) used by the index. - */ - int usedMemory() const CV_OVERRIDE - { - return kmeans_index_->usedMemory() + kdtree_index_->usedMemory(); - } - - /** - * \brief Builds the index - */ - void buildIndex() CV_OVERRIDE - { - Logger::info("Building kmeans tree...\n"); - kmeans_index_->buildIndex(); - Logger::info("Building kdtree tree...\n"); - kdtree_index_->buildIndex(); - } - - /** - * \brief Saves the index to a stream - * \param stream The stream to save the index to - */ - void saveIndex(FILE* stream) CV_OVERRIDE - { - kmeans_index_->saveIndex(stream); - kdtree_index_->saveIndex(stream); - } - - /** - * \brief Loads the index from a stream - * \param stream The stream from which the index is loaded - */ - void loadIndex(FILE* stream) CV_OVERRIDE - { - kmeans_index_->loadIndex(stream); - kdtree_index_->loadIndex(stream); - } - - /** - * \returns The index parameters - */ - IndexParams getParameters() const CV_OVERRIDE - { - return index_params_; - } - - /** - * \brief Method that searches for nearest-neighbours - */ - void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE - { - kmeans_index_->findNeighbors(result, vec, searchParams); - kdtree_index_->findNeighbors(result, vec, searchParams); - } - -private: - /** The k-means index */ - KMeansIndex* kmeans_index_; - - /** The kd-tree index */ - KDTreeIndex* kdtree_index_; - - /** The index parameters */ - const IndexParams index_params_; -}; - -} - -//! @endcond - -#endif //OPENCV_FLANN_COMPOSITE_INDEX_H_ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * 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 ``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 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 OPENCV_FLANN_COMPOSITE_INDEX_H_ +#define OPENCV_FLANN_COMPOSITE_INDEX_H_ + +//! @cond IGNORED + +#include "nn_index.h" +#include "kdtree_index.h" +#include "kmeans_index.h" + +namespace cvflann +{ + +/** + * Index parameters for the CompositeIndex. + */ +struct CompositeIndexParams : public IndexParams +{ + CompositeIndexParams(int trees = 4, int branching = 32, int iterations = 11, + flann_centers_init_t centers_init = FLANN_CENTERS_RANDOM, float cb_index = 0.2 ) + { + (*this)["algorithm"] = FLANN_INDEX_KMEANS; + // number of randomized trees to use (for kdtree) + (*this)["trees"] = trees; + // branching factor + (*this)["branching"] = branching; + // max iterations to perform in one kmeans clustering (kmeans tree) + (*this)["iterations"] = iterations; + // algorithm used for picking the initial cluster centers for kmeans tree + (*this)["centers_init"] = centers_init; + // cluster boundary index. Used when searching the kmeans tree + (*this)["cb_index"] = cb_index; + } +}; + + +/** + * This index builds a kd-tree index and a k-means index and performs nearest + * neighbour search both indexes. This gives a slight boost in search performance + * as some of the neighbours that are missed by one index are found by the other. + */ +template +class CompositeIndex : public NNIndex +{ +public: + typedef typename Distance::ElementType ElementType; + typedef typename Distance::ResultType DistanceType; + + /** + * Index constructor + * @param inputData dataset containing the points to index + * @param params Index parameters + * @param d Distance functor + */ + CompositeIndex(const Matrix& inputData, const IndexParams& params = CompositeIndexParams(), + Distance d = Distance()) : index_params_(params) + { + kdtree_index_ = new KDTreeIndex(inputData, params, d); + kmeans_index_ = new KMeansIndex(inputData, params, d); + + } + + CompositeIndex(const CompositeIndex&); + CompositeIndex& operator=(const CompositeIndex&); + + virtual ~CompositeIndex() + { + delete kdtree_index_; + delete kmeans_index_; + } + + /** + * @return The index type + */ + flann_algorithm_t getType() const CV_OVERRIDE + { + return FLANN_INDEX_COMPOSITE; + } + + /** + * @return Size of the index + */ + size_t size() const CV_OVERRIDE + { + return kdtree_index_->size(); + } + + /** + * \returns The dimensionality of the features in this index. + */ + size_t veclen() const CV_OVERRIDE + { + return kdtree_index_->veclen(); + } + + /** + * \returns The amount of memory (in bytes) used by the index. + */ + int usedMemory() const CV_OVERRIDE + { + return kmeans_index_->usedMemory() + kdtree_index_->usedMemory(); + } + + /** + * \brief Builds the index + */ + void buildIndex() CV_OVERRIDE + { + Logger::info("Building kmeans tree...\n"); + kmeans_index_->buildIndex(); + Logger::info("Building kdtree tree...\n"); + kdtree_index_->buildIndex(); + } + + /** + * \brief Saves the index to a stream + * \param stream The stream to save the index to + */ + void saveIndex(FILE* stream) CV_OVERRIDE + { + kmeans_index_->saveIndex(stream); + kdtree_index_->saveIndex(stream); + } + + /** + * \brief Loads the index from a stream + * \param stream The stream from which the index is loaded + */ + void loadIndex(FILE* stream) CV_OVERRIDE + { + kmeans_index_->loadIndex(stream); + kdtree_index_->loadIndex(stream); + } + + /** + * \returns The index parameters + */ + IndexParams getParameters() const CV_OVERRIDE + { + return index_params_; + } + + /** + * \brief Method that searches for nearest-neighbours + */ + void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE + { + kmeans_index_->findNeighbors(result, vec, searchParams); + kdtree_index_->findNeighbors(result, vec, searchParams); + } + +private: + /** The k-means index */ + KMeansIndex* kmeans_index_; + + /** The kd-tree index */ + KDTreeIndex* kdtree_index_; + + /** The index parameters */ + const IndexParams index_params_; +}; + +} + +//! @endcond + +#endif //OPENCV_FLANN_COMPOSITE_INDEX_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/config.h b/3rdParty/opencv-4.11.0/opencv2/flann/config.h index c9342c00c3..fd08448a29 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/config.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/config.h @@ -1,42 +1,42 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2011 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2011 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * 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 ``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 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 OPENCV_FLANN_CONFIG_H_ -#define OPENCV_FLANN_CONFIG_H_ - -//! @cond IGNORED - -#ifdef FLANN_VERSION_ -#undef FLANN_VERSION_ -#endif -#define FLANN_VERSION_ "1.6.10" - -//! @endcond - -#endif /* OPENCV_FLANN_CONFIG_H_ */ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2011 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2011 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * 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 ``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 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 OPENCV_FLANN_CONFIG_H_ +#define OPENCV_FLANN_CONFIG_H_ + +//! @cond IGNORED + +#ifdef FLANN_VERSION_ +#undef FLANN_VERSION_ +#endif +#define FLANN_VERSION_ "1.6.10" + +//! @endcond + +#endif /* OPENCV_FLANN_CONFIG_H_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/defines.h b/3rdParty/opencv-4.11.0/opencv2/flann/defines.h index 8ab83293ff..9669aa56d9 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/defines.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/defines.h @@ -1,169 +1,169 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2011 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2011 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * 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 ``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 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 OPENCV_FLANN_DEFINES_H_ -#define OPENCV_FLANN_DEFINES_H_ - -//! @cond IGNORED - -#include "config.h" - -#ifdef FLANN_EXPORT -#undef FLANN_EXPORT -#endif -#ifdef _WIN32 -/* win32 dll export/import directives */ - #ifdef FLANN_EXPORTS - #define FLANN_EXPORT __declspec(dllexport) - #elif defined(FLANN_STATIC) - #define FLANN_EXPORT - #else - #define FLANN_EXPORT __declspec(dllimport) - #endif -#else -/* unix needs nothing */ - #define FLANN_EXPORT -#endif - - -#undef FLANN_PLATFORM_32_BIT -#undef FLANN_PLATFORM_64_BIT -#if defined __amd64__ || defined __x86_64__ || defined _WIN64 || defined _M_X64 -#define FLANN_PLATFORM_64_BIT -#else -#define FLANN_PLATFORM_32_BIT -#endif - - -#undef FLANN_ARRAY_LEN -#define FLANN_ARRAY_LEN(a) (sizeof(a)/sizeof(a[0])) - -namespace cvflann { - -/* Nearest neighbour index algorithms */ -enum flann_algorithm_t -{ - FLANN_INDEX_LINEAR = 0, - FLANN_INDEX_KDTREE = 1, - FLANN_INDEX_KMEANS = 2, - FLANN_INDEX_COMPOSITE = 3, - FLANN_INDEX_KDTREE_SINGLE = 4, - FLANN_INDEX_HIERARCHICAL = 5, - FLANN_INDEX_LSH = 6, - FLANN_INDEX_SAVED = 254, - FLANN_INDEX_AUTOTUNED = 255, - - // deprecated constants, should use the FLANN_INDEX_* ones instead - LINEAR = 0, - KDTREE = 1, - KMEANS = 2, - COMPOSITE = 3, - KDTREE_SINGLE = 4, - SAVED = 254, - AUTOTUNED = 255 -}; - - - -enum flann_centers_init_t -{ - FLANN_CENTERS_RANDOM = 0, - FLANN_CENTERS_GONZALES = 1, - FLANN_CENTERS_KMEANSPP = 2, - FLANN_CENTERS_GROUPWISE = 3, - - // deprecated constants, should use the FLANN_CENTERS_* ones instead - CENTERS_RANDOM = 0, - CENTERS_GONZALES = 1, - CENTERS_KMEANSPP = 2 -}; - -enum flann_log_level_t -{ - FLANN_LOG_NONE = 0, - FLANN_LOG_FATAL = 1, - FLANN_LOG_ERROR = 2, - FLANN_LOG_WARN = 3, - FLANN_LOG_INFO = 4 -}; - -enum flann_distance_t -{ - FLANN_DIST_EUCLIDEAN = 1, - FLANN_DIST_L2 = 1, - FLANN_DIST_MANHATTAN = 2, - FLANN_DIST_L1 = 2, - FLANN_DIST_MINKOWSKI = 3, - FLANN_DIST_MAX = 4, - FLANN_DIST_HIST_INTERSECT = 5, - FLANN_DIST_HELLINGER = 6, - FLANN_DIST_CHI_SQUARE = 7, - FLANN_DIST_CS = 7, - FLANN_DIST_KULLBACK_LEIBLER = 8, - FLANN_DIST_KL = 8, - FLANN_DIST_HAMMING = 9, - FLANN_DIST_DNAMMING = 10, - - // deprecated constants, should use the FLANN_DIST_* ones instead - EUCLIDEAN = 1, - MANHATTAN = 2, - MINKOWSKI = 3, - MAX_DIST = 4, - HIST_INTERSECT = 5, - HELLINGER = 6, - CS = 7, - KL = 8, - KULLBACK_LEIBLER = 8 -}; - -enum flann_datatype_t -{ - FLANN_INT8 = 0, - FLANN_INT16 = 1, - FLANN_INT32 = 2, - FLANN_INT64 = 3, - FLANN_UINT8 = 4, - FLANN_UINT16 = 5, - FLANN_UINT32 = 6, - FLANN_UINT64 = 7, - FLANN_FLOAT32 = 8, - FLANN_FLOAT64 = 9 -}; - -enum -{ - FLANN_CHECKS_UNLIMITED = -1, - FLANN_CHECKS_AUTOTUNED = -2 -}; - -} - -//! @endcond - -#endif /* OPENCV_FLANN_DEFINES_H_ */ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2011 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2011 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * 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 ``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 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 OPENCV_FLANN_DEFINES_H_ +#define OPENCV_FLANN_DEFINES_H_ + +//! @cond IGNORED + +#include "config.h" + +#ifdef FLANN_EXPORT +#undef FLANN_EXPORT +#endif +#ifdef _WIN32 +/* win32 dll export/import directives */ + #ifdef FLANN_EXPORTS + #define FLANN_EXPORT __declspec(dllexport) + #elif defined(FLANN_STATIC) + #define FLANN_EXPORT + #else + #define FLANN_EXPORT __declspec(dllimport) + #endif +#else +/* unix needs nothing */ + #define FLANN_EXPORT +#endif + + +#undef FLANN_PLATFORM_32_BIT +#undef FLANN_PLATFORM_64_BIT +#if defined __amd64__ || defined __x86_64__ || defined _WIN64 || defined _M_X64 +#define FLANN_PLATFORM_64_BIT +#else +#define FLANN_PLATFORM_32_BIT +#endif + + +#undef FLANN_ARRAY_LEN +#define FLANN_ARRAY_LEN(a) (sizeof(a)/sizeof(a[0])) + +namespace cvflann { + +/* Nearest neighbour index algorithms */ +enum flann_algorithm_t +{ + FLANN_INDEX_LINEAR = 0, + FLANN_INDEX_KDTREE = 1, + FLANN_INDEX_KMEANS = 2, + FLANN_INDEX_COMPOSITE = 3, + FLANN_INDEX_KDTREE_SINGLE = 4, + FLANN_INDEX_HIERARCHICAL = 5, + FLANN_INDEX_LSH = 6, + FLANN_INDEX_SAVED = 254, + FLANN_INDEX_AUTOTUNED = 255, + + // deprecated constants, should use the FLANN_INDEX_* ones instead + LINEAR = 0, + KDTREE = 1, + KMEANS = 2, + COMPOSITE = 3, + KDTREE_SINGLE = 4, + SAVED = 254, + AUTOTUNED = 255 +}; + + + +enum flann_centers_init_t +{ + FLANN_CENTERS_RANDOM = 0, + FLANN_CENTERS_GONZALES = 1, + FLANN_CENTERS_KMEANSPP = 2, + FLANN_CENTERS_GROUPWISE = 3, + + // deprecated constants, should use the FLANN_CENTERS_* ones instead + CENTERS_RANDOM = 0, + CENTERS_GONZALES = 1, + CENTERS_KMEANSPP = 2 +}; + +enum flann_log_level_t +{ + FLANN_LOG_NONE = 0, + FLANN_LOG_FATAL = 1, + FLANN_LOG_ERROR = 2, + FLANN_LOG_WARN = 3, + FLANN_LOG_INFO = 4 +}; + +enum flann_distance_t +{ + FLANN_DIST_EUCLIDEAN = 1, + FLANN_DIST_L2 = 1, + FLANN_DIST_MANHATTAN = 2, + FLANN_DIST_L1 = 2, + FLANN_DIST_MINKOWSKI = 3, + FLANN_DIST_MAX = 4, + FLANN_DIST_HIST_INTERSECT = 5, + FLANN_DIST_HELLINGER = 6, + FLANN_DIST_CHI_SQUARE = 7, + FLANN_DIST_CS = 7, + FLANN_DIST_KULLBACK_LEIBLER = 8, + FLANN_DIST_KL = 8, + FLANN_DIST_HAMMING = 9, + FLANN_DIST_DNAMMING = 10, + + // deprecated constants, should use the FLANN_DIST_* ones instead + EUCLIDEAN = 1, + MANHATTAN = 2, + MINKOWSKI = 3, + MAX_DIST = 4, + HIST_INTERSECT = 5, + HELLINGER = 6, + CS = 7, + KL = 8, + KULLBACK_LEIBLER = 8 +}; + +enum flann_datatype_t +{ + FLANN_INT8 = 0, + FLANN_INT16 = 1, + FLANN_INT32 = 2, + FLANN_INT64 = 3, + FLANN_UINT8 = 4, + FLANN_UINT16 = 5, + FLANN_UINT32 = 6, + FLANN_UINT64 = 7, + FLANN_FLOAT32 = 8, + FLANN_FLOAT64 = 9 +}; + +enum +{ + FLANN_CHECKS_UNLIMITED = -1, + FLANN_CHECKS_AUTOTUNED = -2 +}; + +} + +//! @endcond + +#endif /* OPENCV_FLANN_DEFINES_H_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/dist.h b/3rdParty/opencv-4.11.0/opencv2/flann/dist.h index 3029ebb5ef..d78c3ff65c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/dist.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/dist.h @@ -1,1292 +1,1292 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * 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 ``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 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 OPENCV_FLANN_DIST_H_ -#define OPENCV_FLANN_DIST_H_ - -//! @cond IGNORED - -#include -#include -#include -#ifdef _MSC_VER -typedef unsigned __int32 uint32_t; -typedef unsigned __int64 uint64_t; -#else -#include -#endif - -#include "defines.h" - -#if defined _WIN32 && (defined(_M_ARM) || defined(_M_ARM64)) -# include -#endif - -#if defined(__ARM_NEON) && !defined(__CUDACC__) -# include "arm_neon.h" -#endif - -namespace cvflann -{ - -template -inline T abs(T x) { return (x<0) ? -x : x; } - -template<> -inline int abs(int x) { return ::abs(x); } - -template<> -inline float abs(float x) { return fabsf(x); } - -template<> -inline double abs(double x) { return fabs(x); } - - -template -inline TargetType round(float x) { return static_cast(x); } - -template<> -inline unsigned int round(float x) { return static_cast(x + 0.5f); } - -template<> -inline unsigned short round(float x) { return static_cast(x + 0.5f); } - -template<> -inline unsigned char round(float x) { return static_cast(x + 0.5f); } - -template<> -inline long long round(float x) { return static_cast(x + 0.5f); } - -template<> -inline long round(float x) { return static_cast(x + 0.5f); } - -template<> -inline int round(float x) { return static_cast(x + 0.5f) - (x<0); } - -template<> -inline short round(float x) { return static_cast(x + 0.5f) - (x<0); } - -template<> -inline char round(float x) { return static_cast(x + 0.5f) - (x<0); } - - -template -inline TargetType round(double x) { return static_cast(x); } - -template<> -inline unsigned int round(double x) { return static_cast(x + 0.5); } - -template<> -inline unsigned short round(double x) { return static_cast(x + 0.5); } - -template<> -inline unsigned char round(double x) { return static_cast(x + 0.5); } - -template<> -inline long long round(double x) { return static_cast(x + 0.5); } - -template<> -inline long round(double x) { return static_cast(x + 0.5); } - -template<> -inline int round(double x) { return static_cast(x + 0.5) - (x<0); } - -template<> -inline short round(double x) { return static_cast(x + 0.5) - (x<0); } - -template<> -inline char round(double x) { return static_cast(x + 0.5) - (x<0); } - - -template -struct Accumulator { typedef T Type; }; -template<> -struct Accumulator { typedef float Type; }; -template<> -struct Accumulator { typedef float Type; }; -template<> -struct Accumulator { typedef float Type; }; -template<> -struct Accumulator { typedef float Type; }; -template<> -struct Accumulator { typedef float Type; }; -template<> -struct Accumulator { typedef float Type; }; - -#undef True -#undef False - -class True -{ -public: - static const bool val = true; -}; - -class False -{ -public: - static const bool val = false; -}; - - -/* - * This is a "zero iterator". It basically behaves like a zero filled - * array to all algorithms that use arrays as iterators (STL style). - * It's useful when there's a need to compute the distance between feature - * and origin it and allows for better compiler optimisation than using a - * zero-filled array. - */ -template -struct ZeroIterator -{ - - T operator*() - { - return 0; - } - - T operator[](int) - { - return 0; - } - - const ZeroIterator& operator ++() - { - return *this; - } - - ZeroIterator operator ++(int) - { - return *this; - } - - ZeroIterator& operator+=(int) - { - return *this; - } - -}; - - - -/** - * Squared Euclidean distance functor. - * - * This is the simpler, unrolled version. This is preferable for - * very low dimensionality data (eg 3D points) - */ -template -struct L2_Simple -{ - typedef True is_kdtree_distance; - typedef True is_vector_space_distance; - - typedef T ElementType; - typedef typename Accumulator::Type ResultType; - typedef ResultType CentersType; - - template - ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const - { - ResultType result = ResultType(); - ResultType diff; - for(size_t i = 0; i < size; ++i ) { - diff = (ResultType)(*a++ - *b++); - result += diff*diff; - } - return result; - } - - template - inline ResultType accum_dist(const U& a, const V& b, int) const - { - return (a-b)*(a-b); - } -}; - - - -/** - * Squared Euclidean distance functor, optimized version - */ -template -struct L2 -{ - typedef True is_kdtree_distance; - typedef True is_vector_space_distance; - - typedef T ElementType; - typedef typename Accumulator::Type ResultType; - typedef ResultType CentersType; - - /** - * Compute the squared Euclidean distance between two vectors. - * - * This is highly optimised, with loop unrolling, as it is one - * of the most expensive inner loops. - * - * The computation of squared root at the end is omitted for - * efficiency. - */ - template - ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const - { - ResultType result = ResultType(); - ResultType diff0, diff1, diff2, diff3; - Iterator1 last = a + size; - Iterator1 lastgroup = last - 3; - - /* Process 4 items with each loop for efficiency. */ - while (a < lastgroup) { - diff0 = (ResultType)(a[0] - b[0]); - diff1 = (ResultType)(a[1] - b[1]); - diff2 = (ResultType)(a[2] - b[2]); - diff3 = (ResultType)(a[3] - b[3]); - result += diff0 * diff0 + diff1 * diff1 + diff2 * diff2 + diff3 * diff3; - a += 4; - b += 4; - - if ((worst_dist>0)&&(result>worst_dist)) { - return result; - } - } - /* Process last 0-3 pixels. Not needed for standard vector lengths. */ - while (a < last) { - diff0 = (ResultType)(*a++ - *b++); - result += diff0 * diff0; - } - return result; - } - - /** - * Partial euclidean distance, using just one dimension. This is used by the - * kd-tree when computing partial distances while traversing the tree. - * - * Squared root is omitted for efficiency. - */ - template - inline ResultType accum_dist(const U& a, const V& b, int) const - { - return (a-b)*(a-b); - } -}; - - -/* - * Manhattan distance functor, optimized version - */ -template -struct L1 -{ - typedef True is_kdtree_distance; - typedef True is_vector_space_distance; - - typedef T ElementType; - typedef typename Accumulator::Type ResultType; - typedef ResultType CentersType; - - /** - * Compute the Manhattan (L_1) distance between two vectors. - * - * This is highly optimised, with loop unrolling, as it is one - * of the most expensive inner loops. - */ - template - ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const - { - ResultType result = ResultType(); - ResultType diff0, diff1, diff2, diff3; - Iterator1 last = a + size; - Iterator1 lastgroup = last - 3; - - /* Process 4 items with each loop for efficiency. */ - while (a < lastgroup) { - diff0 = (ResultType)abs(a[0] - b[0]); - diff1 = (ResultType)abs(a[1] - b[1]); - diff2 = (ResultType)abs(a[2] - b[2]); - diff3 = (ResultType)abs(a[3] - b[3]); - result += diff0 + diff1 + diff2 + diff3; - a += 4; - b += 4; - - if ((worst_dist>0)&&(result>worst_dist)) { - return result; - } - } - /* Process last 0-3 pixels. Not needed for standard vector lengths. */ - while (a < last) { - diff0 = (ResultType)abs(*a++ - *b++); - result += diff0; - } - return result; - } - - /** - * Partial distance, used by the kd-tree. - */ - template - inline ResultType accum_dist(const U& a, const V& b, int) const - { - return abs(a-b); - } -}; - - - -template -struct MinkowskiDistance -{ - typedef True is_kdtree_distance; - typedef True is_vector_space_distance; - - typedef T ElementType; - typedef typename Accumulator::Type ResultType; - typedef ResultType CentersType; - - int order; - - MinkowskiDistance(int order_) : order(order_) {} - - /** - * Compute the Minkowski (L_p) distance between two vectors. - * - * This is highly optimised, with loop unrolling, as it is one - * of the most expensive inner loops. - * - * The computation of squared root at the end is omitted for - * efficiency. - */ - template - ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const - { - ResultType result = ResultType(); - ResultType diff0, diff1, diff2, diff3; - Iterator1 last = a + size; - Iterator1 lastgroup = last - 3; - - /* Process 4 items with each loop for efficiency. */ - while (a < lastgroup) { - diff0 = (ResultType)abs(a[0] - b[0]); - diff1 = (ResultType)abs(a[1] - b[1]); - diff2 = (ResultType)abs(a[2] - b[2]); - diff3 = (ResultType)abs(a[3] - b[3]); - result += pow(diff0,order) + pow(diff1,order) + pow(diff2,order) + pow(diff3,order); - a += 4; - b += 4; - - if ((worst_dist>0)&&(result>worst_dist)) { - return result; - } - } - /* Process last 0-3 pixels. Not needed for standard vector lengths. */ - while (a < last) { - diff0 = (ResultType)abs(*a++ - *b++); - result += pow(diff0,order); - } - return result; - } - - /** - * Partial distance, used by the kd-tree. - */ - template - inline ResultType accum_dist(const U& a, const V& b, int) const - { - return pow(static_cast(abs(a-b)),order); - } -}; - - - -template -struct MaxDistance -{ - typedef False is_kdtree_distance; - typedef True is_vector_space_distance; - - typedef T ElementType; - typedef typename Accumulator::Type ResultType; - typedef ResultType CentersType; - - /** - * Compute the max distance (L_infinity) between two vectors. - * - * This distance is not a valid kdtree distance, it's not dimensionwise additive. - */ - template - ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const - { - ResultType result = ResultType(); - ResultType diff0, diff1, diff2, diff3; - Iterator1 last = a + size; - Iterator1 lastgroup = last - 3; - - /* Process 4 items with each loop for efficiency. */ - while (a < lastgroup) { - diff0 = abs(a[0] - b[0]); - diff1 = abs(a[1] - b[1]); - diff2 = abs(a[2] - b[2]); - diff3 = abs(a[3] - b[3]); - if (diff0>result) {result = diff0; } - if (diff1>result) {result = diff1; } - if (diff2>result) {result = diff2; } - if (diff3>result) {result = diff3; } - a += 4; - b += 4; - - if ((worst_dist>0)&&(result>worst_dist)) { - return result; - } - } - /* Process last 0-3 pixels. Not needed for standard vector lengths. */ - while (a < last) { - diff0 = abs(*a++ - *b++); - result = (diff0>result) ? diff0 : result; - } - return result; - } - - /* This distance functor is not dimension-wise additive, which - * makes it an invalid kd-tree distance, not implementing the accum_dist method */ - -}; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -/** - * Hamming distance functor - counts the bit differences between two strings - useful for the Brief descriptor - * bit count of A exclusive XOR'ed with B - */ -struct HammingLUT -{ - typedef False is_kdtree_distance; - typedef False is_vector_space_distance; - - typedef unsigned char ElementType; - typedef int ResultType; - typedef ElementType CentersType; - - /** this will count the bits in a ^ b - */ - template - ResultType operator()(const unsigned char* a, const Iterator2 b, size_t size) const - { - static const uchar popCountTable[] = - { - 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 - }; - ResultType result = 0; - const unsigned char* b2 = reinterpret_cast (b); - for (size_t i = 0; i < size; i++) { - result += popCountTable[a[i] ^ b2[i]]; - } - return result; - } - - - ResultType operator()(const unsigned char* a, const ZeroIterator b, size_t size) const - { - (void)b; - static const uchar popCountTable[] = - { - 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 - }; - ResultType result = 0; - for (size_t i = 0; i < size; i++) { - result += popCountTable[a[i]]; - } - return result; - } -}; - -/** - * Hamming distance functor (pop count between two binary vectors, i.e. xor them and count the number of bits set) - * That code was taken from brief.cpp in OpenCV - */ -template -struct Hamming -{ - typedef False is_kdtree_distance; - typedef False is_vector_space_distance; - - - typedef T ElementType; - typedef int ResultType; - typedef ElementType CentersType; - - template - ResultType operator()(const Iterator1 a, const Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const - { - ResultType result = 0; -#if defined(__ARM_NEON) && !defined(__CUDACC__) - { - const unsigned char* a2 = reinterpret_cast (a); - const unsigned char* b2 = reinterpret_cast (b); - uint32x4_t bits = vmovq_n_u32(0); - for (size_t i = 0; i < size; i += 16) { - uint8x16_t A_vec = vld1q_u8 (a2 + i); - uint8x16_t B_vec = vld1q_u8 (b2 + i); - uint8x16_t AxorB = veorq_u8 (A_vec, B_vec); - uint8x16_t bitsSet = vcntq_u8 (AxorB); - uint16x8_t bitSet8 = vpaddlq_u8 (bitsSet); - uint32x4_t bitSet4 = vpaddlq_u16 (bitSet8); - bits = vaddq_u32(bits, bitSet4); - } - uint64x2_t bitSet2 = vpaddlq_u32 (bits); - result = vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),0); - result += vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),2); - } -#elif defined(__GNUC__) - { - //for portability just use unsigned long -- and use the __builtin_popcountll (see docs for __builtin_popcountll) - typedef unsigned long long pop_t; - const size_t modulo = size % sizeof(pop_t); - const pop_t* a2 = reinterpret_cast (a); - const pop_t* b2 = reinterpret_cast (b); - const pop_t* a2_end = a2 + (size / sizeof(pop_t)); - - for (; a2 != a2_end; ++a2, ++b2) result += __builtin_popcountll((*a2) ^ (*b2)); - - if (modulo) { - //in the case where size is not dividable by sizeof(size_t) - //need to mask off the bits at the end - pop_t a_final = 0, b_final = 0; - memcpy(&a_final, a2, modulo); - memcpy(&b_final, b2, modulo); - result += __builtin_popcountll(a_final ^ b_final); - } - } -#else // NO NEON and NOT GNUC - HammingLUT lut; - result = lut(reinterpret_cast (a), - reinterpret_cast (b), size); -#endif - return result; - } - - - template - ResultType operator()(const Iterator1 a, ZeroIterator b, size_t size, ResultType /*worst_dist*/ = -1) const - { - (void)b; - ResultType result = 0; -#if defined(__ARM_NEON) && !defined(__CUDACC__) - { - const unsigned char* a2 = reinterpret_cast (a); - uint32x4_t bits = vmovq_n_u32(0); - for (size_t i = 0; i < size; i += 16) { - uint8x16_t A_vec = vld1q_u8 (a2 + i); - uint8x16_t bitsSet = vcntq_u8 (A_vec); - uint16x8_t bitSet8 = vpaddlq_u8 (bitsSet); - uint32x4_t bitSet4 = vpaddlq_u16 (bitSet8); - bits = vaddq_u32(bits, bitSet4); - } - uint64x2_t bitSet2 = vpaddlq_u32 (bits); - result = vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),0); - result += vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),2); - } -#elif defined(__GNUC__) - { - //for portability just use unsigned long -- and use the __builtin_popcountll (see docs for __builtin_popcountll) - typedef unsigned long long pop_t; - const size_t modulo = size % sizeof(pop_t); - const pop_t* a2 = reinterpret_cast (a); - const pop_t* a2_end = a2 + (size / sizeof(pop_t)); - - for (; a2 != a2_end; ++a2) result += __builtin_popcountll(*a2); - - if (modulo) { - //in the case where size is not dividable by sizeof(size_t) - //need to mask off the bits at the end - pop_t a_final = 0; - memcpy(&a_final, a2, modulo); - result += __builtin_popcountll(a_final); - } - } -#else // NO NEON and NOT GNUC - HammingLUT lut; - result = lut(reinterpret_cast (a), b, size); -#endif - return result; - } -}; - -template -struct Hamming2 -{ - typedef False is_kdtree_distance; - typedef False is_vector_space_distance; - - typedef T ElementType; - typedef int ResultType; - typedef ElementType CentersType; - - /** This is popcount_3() from: - * http://en.wikipedia.org/wiki/Hamming_weight */ - unsigned int popcnt32(uint32_t n) const - { - n -= ((n >> 1) & 0x55555555); - n = (n & 0x33333333) + ((n >> 2) & 0x33333333); - return (((n + (n >> 4))& 0xF0F0F0F)* 0x1010101) >> 24; - } - -#ifdef FLANN_PLATFORM_64_BIT - unsigned int popcnt64(uint64_t n) const - { - n -= ((n >> 1) & 0x5555555555555555); - n = (n & 0x3333333333333333) + ((n >> 2) & 0x3333333333333333); - return (((n + (n >> 4))& 0x0f0f0f0f0f0f0f0f)* 0x0101010101010101) >> 56; - } -#endif - - template - ResultType operator()(const Iterator1 a, const Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const - { - CV_DbgAssert(!(size % long_word_size_) && "vectors size must be multiple of long words size (i.e. 8)"); - -#ifdef FLANN_PLATFORM_64_BIT - const uint64_t* pa = reinterpret_cast(a); - const uint64_t* pb = reinterpret_cast(b); - ResultType result = 0; - size /= long_word_size_; - for(size_t i = 0; i < size; ++i ) { - result += popcnt64(*pa ^ *pb); - ++pa; - ++pb; - } -#else - const uint32_t* pa = reinterpret_cast(a); - const uint32_t* pb = reinterpret_cast(b); - ResultType result = 0; - size /= long_word_size_; - for(size_t i = 0; i < size; ++i ) { - result += popcnt32(*pa ^ *pb); - ++pa; - ++pb; - } -#endif - return result; - } - - - template - ResultType operator()(const Iterator1 a, ZeroIterator b, size_t size, ResultType /*worst_dist*/ = -1) const - { - CV_DbgAssert(!(size % long_word_size_) && "vectors size must be multiple of long words size (i.e. 8)"); - - (void)b; -#ifdef FLANN_PLATFORM_64_BIT - const uint64_t* pa = reinterpret_cast(a); - ResultType result = 0; - size /= long_word_size_; - for(size_t i = 0; i < size; ++i ) { - result += popcnt64(*pa); - ++pa; - } -#else - const uint32_t* pa = reinterpret_cast(a); - ResultType result = 0; - size /= long_word_size_; - for(size_t i = 0; i < size; ++i ) { - result += popcnt32(*pa); - ++pa; - } -#endif - return result; - } - -private: -#ifdef FLANN_PLATFORM_64_BIT - static const size_t long_word_size_ = sizeof(uint64_t)/sizeof(unsigned char); -#else - static const size_t long_word_size_ = sizeof(uint32_t)/sizeof(unsigned char); -#endif -}; - - - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -struct DNAmmingLUT -{ - typedef False is_kdtree_distance; - typedef False is_vector_space_distance; - - typedef unsigned char ElementType; - typedef int ResultType; - typedef ElementType CentersType; - - /** this will count the bits in a ^ b - */ - template - ResultType operator()(const unsigned char* a, const Iterator2 b, size_t size) const - { - static const uchar popCountTable[] = - { - 0, 1, 1, 1, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, - 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, - 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, - 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, - 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, - 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, - 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, - 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4 - }; - ResultType result = 0; - const unsigned char* b2 = reinterpret_cast (b); - for (size_t i = 0; i < size; i++) { - result += popCountTable[a[i] ^ b2[i]]; - } - return result; - } - - - ResultType operator()(const unsigned char* a, const ZeroIterator b, size_t size) const - { - (void)b; - static const uchar popCountTable[] = - { - 0, 1, 1, 1, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, - 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, - 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, - 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, - 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, - 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, - 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, - 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4 - }; - ResultType result = 0; - for (size_t i = 0; i < size; i++) { - result += popCountTable[a[i]]; - } - return result; - } -}; - - -template -struct DNAmming2 -{ - typedef False is_kdtree_distance; - typedef False is_vector_space_distance; - - typedef T ElementType; - typedef int ResultType; - typedef ElementType CentersType; - - /** This is popcount_3() from: - * http://en.wikipedia.org/wiki/Hamming_weight */ - unsigned int popcnt32(uint32_t n) const - { - n = ((n >> 1) | n) & 0x55555555; - n = (n & 0x33333333) + ((n >> 2) & 0x33333333); - return (((n + (n >> 4))& 0x0F0F0F0F)* 0x01010101) >> 24; - } - -#ifdef FLANN_PLATFORM_64_BIT - unsigned int popcnt64(uint64_t n) const - { - n = ((n >> 1) | n) & 0x5555555555555555; - n = (n & 0x3333333333333333) + ((n >> 2) & 0x3333333333333333); - return (((n + (n >> 4))& 0x0f0f0f0f0f0f0f0f)* 0x0101010101010101) >> 56; - } -#endif - - template - ResultType operator()(const Iterator1 a, const Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const - { - CV_DbgAssert(!(size % long_word_size_) && "vectors size must be multiple of long words size (i.e. 8)"); - -#ifdef FLANN_PLATFORM_64_BIT - const uint64_t* pa = reinterpret_cast(a); - const uint64_t* pb = reinterpret_cast(b); - ResultType result = 0; - size /= long_word_size_; - for(size_t i = 0; i < size; ++i ) { - result += popcnt64(*pa ^ *pb); - ++pa; - ++pb; - } -#else - const uint32_t* pa = reinterpret_cast(a); - const uint32_t* pb = reinterpret_cast(b); - ResultType result = 0; - size /= long_word_size_; - for(size_t i = 0; i < size; ++i ) { - result += popcnt32(*pa ^ *pb); - ++pa; - ++pb; - } -#endif - return result; - } - - - template - ResultType operator()(const Iterator1 a, ZeroIterator b, size_t size, ResultType /*worst_dist*/ = -1) const - { - CV_DbgAssert(!(size % long_word_size_) && "vectors size must be multiple of long words size (i.e. 8)"); - - (void)b; -#ifdef FLANN_PLATFORM_64_BIT - const uint64_t* pa = reinterpret_cast(a); - ResultType result = 0; - size /= long_word_size_; - for(size_t i = 0; i < size; ++i ) { - result += popcnt64(*pa); - ++pa; - } -#else - const uint32_t* pa = reinterpret_cast(a); - ResultType result = 0; - size /= long_word_size_; - for(size_t i = 0; i < size; ++i ) { - result += popcnt32(*pa); - ++pa; - } -#endif - return result; - } - -private: -#ifdef FLANN_PLATFORM_64_BIT - static const size_t long_word_size_= sizeof(uint64_t)/sizeof(unsigned char); -#else - static const size_t long_word_size_= sizeof(uint32_t)/sizeof(unsigned char); -#endif -}; - - - -template -struct HistIntersectionDistance -{ - typedef True is_kdtree_distance; - typedef True is_vector_space_distance; - - typedef T ElementType; - typedef typename Accumulator::Type ResultType; - typedef ResultType CentersType; - - /** - * Compute the histogram intersection distance - */ - template - ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const - { - ResultType result = ResultType(); - ResultType min0, min1, min2, min3; - Iterator1 last = a + size; - Iterator1 lastgroup = last - 3; - - /* Process 4 items with each loop for efficiency. */ - while (a < lastgroup) { - min0 = (ResultType)(a[0] < b[0] ? a[0] : b[0]); - min1 = (ResultType)(a[1] < b[1] ? a[1] : b[1]); - min2 = (ResultType)(a[2] < b[2] ? a[2] : b[2]); - min3 = (ResultType)(a[3] < b[3] ? a[3] : b[3]); - result += min0 + min1 + min2 + min3; - a += 4; - b += 4; - if ((worst_dist>0)&&(result>worst_dist)) { - return result; - } - } - /* Process last 0-3 pixels. Not needed for standard vector lengths. */ - while (a < last) { - min0 = (ResultType)(*a < *b ? *a : *b); - result += min0; - ++a; - ++b; - } - return result; - } - - /** - * Partial distance, used by the kd-tree. - */ - template - inline ResultType accum_dist(const U& a, const V& b, int) const - { - return a -struct HellingerDistance -{ - typedef True is_kdtree_distance; - typedef True is_vector_space_distance; - - typedef T ElementType; - typedef typename Accumulator::Type ResultType; - typedef ResultType CentersType; - - /** - * Compute the Hellinger distance - */ - template - ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const - { - ResultType result = ResultType(); - ResultType diff0, diff1, diff2, diff3; - Iterator1 last = a + size; - Iterator1 lastgroup = last - 3; - - /* Process 4 items with each loop for efficiency. */ - while (a < lastgroup) { - diff0 = sqrt(static_cast(a[0])) - sqrt(static_cast(b[0])); - diff1 = sqrt(static_cast(a[1])) - sqrt(static_cast(b[1])); - diff2 = sqrt(static_cast(a[2])) - sqrt(static_cast(b[2])); - diff3 = sqrt(static_cast(a[3])) - sqrt(static_cast(b[3])); - result += diff0 * diff0 + diff1 * diff1 + diff2 * diff2 + diff3 * diff3; - a += 4; - b += 4; - } - while (a < last) { - diff0 = sqrt(static_cast(*a++)) - sqrt(static_cast(*b++)); - result += diff0 * diff0; - } - return result; - } - - /** - * Partial distance, used by the kd-tree. - */ - template - inline ResultType accum_dist(const U& a, const V& b, int) const - { - ResultType diff = sqrt(static_cast(a)) - sqrt(static_cast(b)); - return diff * diff; - } -}; - - -template -struct ChiSquareDistance -{ - typedef True is_kdtree_distance; - typedef True is_vector_space_distance; - - typedef T ElementType; - typedef typename Accumulator::Type ResultType; - typedef ResultType CentersType; - - /** - * Compute the chi-square distance - */ - template - ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const - { - ResultType result = ResultType(); - ResultType sum, diff; - Iterator1 last = a + size; - - while (a < last) { - sum = (ResultType)(*a + *b); - if (sum>0) { - diff = (ResultType)(*a - *b); - result += diff*diff/sum; - } - ++a; - ++b; - - if ((worst_dist>0)&&(result>worst_dist)) { - return result; - } - } - return result; - } - - /** - * Partial distance, used by the kd-tree. - */ - template - inline ResultType accum_dist(const U& a, const V& b, int) const - { - ResultType result = ResultType(); - ResultType sum, diff; - - sum = (ResultType)(a+b); - if (sum>0) { - diff = (ResultType)(a-b); - result = diff*diff/sum; - } - return result; - } -}; - - -template -struct KL_Divergence -{ - typedef True is_kdtree_distance; - typedef True is_vector_space_distance; - - typedef T ElementType; - typedef typename Accumulator::Type ResultType; - typedef ResultType CentersType; - - /** - * Compute the Kullback-Leibler divergence - */ - template - ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const - { - ResultType result = ResultType(); - Iterator1 last = a + size; - - while (a < last) { - if ( *a != 0 && *b != 0 ) { - ResultType ratio = (ResultType)(*a / *b); - if (ratio>0) { - result += *a * log(ratio); - } - } - ++a; - ++b; - - if ((worst_dist>0)&&(result>worst_dist)) { - return result; - } - } - return result; - } - - /** - * Partial distance, used by the kd-tree. - */ - template - inline ResultType accum_dist(const U& a, const V& b, int) const - { - ResultType result = ResultType(); - if( a != 0 && b != 0 ) { - ResultType ratio = (ResultType)(a / b); - if (ratio>0) { - result = a * log(ratio); - } - } - return result; - } -}; - - -/* - * Depending on processed distances, some of them are already squared (e.g. L2) - * and some are not (e.g.Hamming). In KMeans++ for instance we want to be sure - * we are working on ^2 distances, thus following templates to ensure that. - */ -template -struct squareDistance -{ - typedef typename Distance::ResultType ResultType; - ResultType operator()( ResultType dist ) { return dist*dist; } -}; - - -template -struct squareDistance, ElementType> -{ - typedef typename L2_Simple::ResultType ResultType; - ResultType operator()( ResultType dist ) { return dist; } -}; - -template -struct squareDistance, ElementType> -{ - typedef typename L2::ResultType ResultType; - ResultType operator()( ResultType dist ) { return dist; } -}; - - -template -struct squareDistance, ElementType> -{ - typedef typename MinkowskiDistance::ResultType ResultType; - ResultType operator()( ResultType dist ) { return dist; } -}; - -template -struct squareDistance, ElementType> -{ - typedef typename HellingerDistance::ResultType ResultType; - ResultType operator()( ResultType dist ) { return dist; } -}; - -template -struct squareDistance, ElementType> -{ - typedef typename ChiSquareDistance::ResultType ResultType; - ResultType operator()( ResultType dist ) { return dist; } -}; - - -template -typename Distance::ResultType ensureSquareDistance( typename Distance::ResultType dist ) -{ - typedef typename Distance::ElementType ElementType; - - squareDistance dummy; - return dummy( dist ); -} - - -/* - * ...a template to tell the user if the distance he is working with is actually squared - */ - -template -struct isSquareDist -{ - bool operator()() { return false; } -}; - - -template -struct isSquareDist, ElementType> -{ - bool operator()() { return true; } -}; - -template -struct isSquareDist, ElementType> -{ - bool operator()() { return true; } -}; - - -template -struct isSquareDist, ElementType> -{ - bool operator()() { return true; } -}; - -template -struct isSquareDist, ElementType> -{ - bool operator()() { return true; } -}; - -template -struct isSquareDist, ElementType> -{ - bool operator()() { return true; } -}; - - -template -bool isSquareDistance() -{ - typedef typename Distance::ElementType ElementType; - - isSquareDist dummy; - return dummy(); -} - -/* - * ...and a template to ensure the user that he will process the normal distance, - * and not squared distance, without losing processing time calling sqrt(ensureSquareDistance) - * that will result in doing actually sqrt(dist*dist) for L1 distance for instance. - */ -template -struct simpleDistance -{ - typedef typename Distance::ResultType ResultType; - ResultType operator()( ResultType dist ) { return dist; } -}; - - -template -struct simpleDistance, ElementType> -{ - typedef typename L2_Simple::ResultType ResultType; - ResultType operator()( ResultType dist ) { return sqrt(dist); } -}; - -template -struct simpleDistance, ElementType> -{ - typedef typename L2::ResultType ResultType; - ResultType operator()( ResultType dist ) { return sqrt(dist); } -}; - - -template -struct simpleDistance, ElementType> -{ - typedef typename MinkowskiDistance::ResultType ResultType; - ResultType operator()( ResultType dist ) { return sqrt(dist); } -}; - -template -struct simpleDistance, ElementType> -{ - typedef typename HellingerDistance::ResultType ResultType; - ResultType operator()( ResultType dist ) { return sqrt(dist); } -}; - -template -struct simpleDistance, ElementType> -{ - typedef typename ChiSquareDistance::ResultType ResultType; - ResultType operator()( ResultType dist ) { return sqrt(dist); } -}; - - -template -typename Distance::ResultType ensureSimpleDistance( typename Distance::ResultType dist ) -{ - typedef typename Distance::ElementType ElementType; - - simpleDistance dummy; - return dummy( dist ); -} - -} - -//! @endcond - -#endif //OPENCV_FLANN_DIST_H_ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * 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 ``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 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 OPENCV_FLANN_DIST_H_ +#define OPENCV_FLANN_DIST_H_ + +//! @cond IGNORED + +#include +#include +#include +#ifdef _MSC_VER +typedef unsigned __int32 uint32_t; +typedef unsigned __int64 uint64_t; +#else +#include +#endif + +#include "defines.h" + +#if defined _WIN32 && (defined(_M_ARM) || defined(_M_ARM64)) +# include +#endif + +#if defined(__ARM_NEON) && !defined(__CUDACC__) +# include "arm_neon.h" +#endif + +namespace cvflann +{ + +template +inline T abs(T x) { return (x<0) ? -x : x; } + +template<> +inline int abs(int x) { return ::abs(x); } + +template<> +inline float abs(float x) { return fabsf(x); } + +template<> +inline double abs(double x) { return fabs(x); } + + +template +inline TargetType round(float x) { return static_cast(x); } + +template<> +inline unsigned int round(float x) { return static_cast(x + 0.5f); } + +template<> +inline unsigned short round(float x) { return static_cast(x + 0.5f); } + +template<> +inline unsigned char round(float x) { return static_cast(x + 0.5f); } + +template<> +inline long long round(float x) { return static_cast(x + 0.5f); } + +template<> +inline long round(float x) { return static_cast(x + 0.5f); } + +template<> +inline int round(float x) { return static_cast(x + 0.5f) - (x<0); } + +template<> +inline short round(float x) { return static_cast(x + 0.5f) - (x<0); } + +template<> +inline char round(float x) { return static_cast(x + 0.5f) - (x<0); } + + +template +inline TargetType round(double x) { return static_cast(x); } + +template<> +inline unsigned int round(double x) { return static_cast(x + 0.5); } + +template<> +inline unsigned short round(double x) { return static_cast(x + 0.5); } + +template<> +inline unsigned char round(double x) { return static_cast(x + 0.5); } + +template<> +inline long long round(double x) { return static_cast(x + 0.5); } + +template<> +inline long round(double x) { return static_cast(x + 0.5); } + +template<> +inline int round(double x) { return static_cast(x + 0.5) - (x<0); } + +template<> +inline short round(double x) { return static_cast(x + 0.5) - (x<0); } + +template<> +inline char round(double x) { return static_cast(x + 0.5) - (x<0); } + + +template +struct Accumulator { typedef T Type; }; +template<> +struct Accumulator { typedef float Type; }; +template<> +struct Accumulator { typedef float Type; }; +template<> +struct Accumulator { typedef float Type; }; +template<> +struct Accumulator { typedef float Type; }; +template<> +struct Accumulator { typedef float Type; }; +template<> +struct Accumulator { typedef float Type; }; + +#undef True +#undef False + +class True +{ +public: + static const bool val = true; +}; + +class False +{ +public: + static const bool val = false; +}; + + +/* + * This is a "zero iterator". It basically behaves like a zero filled + * array to all algorithms that use arrays as iterators (STL style). + * It's useful when there's a need to compute the distance between feature + * and origin it and allows for better compiler optimisation than using a + * zero-filled array. + */ +template +struct ZeroIterator +{ + + T operator*() + { + return 0; + } + + T operator[](int) + { + return 0; + } + + const ZeroIterator& operator ++() + { + return *this; + } + + ZeroIterator operator ++(int) + { + return *this; + } + + ZeroIterator& operator+=(int) + { + return *this; + } + +}; + + + +/** + * Squared Euclidean distance functor. + * + * This is the simpler, unrolled version. This is preferable for + * very low dimensionality data (eg 3D points) + */ +template +struct L2_Simple +{ + typedef True is_kdtree_distance; + typedef True is_vector_space_distance; + + typedef T ElementType; + typedef typename Accumulator::Type ResultType; + typedef ResultType CentersType; + + template + ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const + { + ResultType result = ResultType(); + ResultType diff; + for(size_t i = 0; i < size; ++i ) { + diff = (ResultType)(*a++ - *b++); + result += diff*diff; + } + return result; + } + + template + inline ResultType accum_dist(const U& a, const V& b, int) const + { + return (a-b)*(a-b); + } +}; + + + +/** + * Squared Euclidean distance functor, optimized version + */ +template +struct L2 +{ + typedef True is_kdtree_distance; + typedef True is_vector_space_distance; + + typedef T ElementType; + typedef typename Accumulator::Type ResultType; + typedef ResultType CentersType; + + /** + * Compute the squared Euclidean distance between two vectors. + * + * This is highly optimised, with loop unrolling, as it is one + * of the most expensive inner loops. + * + * The computation of squared root at the end is omitted for + * efficiency. + */ + template + ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const + { + ResultType result = ResultType(); + ResultType diff0, diff1, diff2, diff3; + Iterator1 last = a + size; + Iterator1 lastgroup = last - 3; + + /* Process 4 items with each loop for efficiency. */ + while (a < lastgroup) { + diff0 = (ResultType)(a[0] - b[0]); + diff1 = (ResultType)(a[1] - b[1]); + diff2 = (ResultType)(a[2] - b[2]); + diff3 = (ResultType)(a[3] - b[3]); + result += diff0 * diff0 + diff1 * diff1 + diff2 * diff2 + diff3 * diff3; + a += 4; + b += 4; + + if ((worst_dist>0)&&(result>worst_dist)) { + return result; + } + } + /* Process last 0-3 pixels. Not needed for standard vector lengths. */ + while (a < last) { + diff0 = (ResultType)(*a++ - *b++); + result += diff0 * diff0; + } + return result; + } + + /** + * Partial euclidean distance, using just one dimension. This is used by the + * kd-tree when computing partial distances while traversing the tree. + * + * Squared root is omitted for efficiency. + */ + template + inline ResultType accum_dist(const U& a, const V& b, int) const + { + return (a-b)*(a-b); + } +}; + + +/* + * Manhattan distance functor, optimized version + */ +template +struct L1 +{ + typedef True is_kdtree_distance; + typedef True is_vector_space_distance; + + typedef T ElementType; + typedef typename Accumulator::Type ResultType; + typedef ResultType CentersType; + + /** + * Compute the Manhattan (L_1) distance between two vectors. + * + * This is highly optimised, with loop unrolling, as it is one + * of the most expensive inner loops. + */ + template + ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const + { + ResultType result = ResultType(); + ResultType diff0, diff1, diff2, diff3; + Iterator1 last = a + size; + Iterator1 lastgroup = last - 3; + + /* Process 4 items with each loop for efficiency. */ + while (a < lastgroup) { + diff0 = (ResultType)abs(a[0] - b[0]); + diff1 = (ResultType)abs(a[1] - b[1]); + diff2 = (ResultType)abs(a[2] - b[2]); + diff3 = (ResultType)abs(a[3] - b[3]); + result += diff0 + diff1 + diff2 + diff3; + a += 4; + b += 4; + + if ((worst_dist>0)&&(result>worst_dist)) { + return result; + } + } + /* Process last 0-3 pixels. Not needed for standard vector lengths. */ + while (a < last) { + diff0 = (ResultType)abs(*a++ - *b++); + result += diff0; + } + return result; + } + + /** + * Partial distance, used by the kd-tree. + */ + template + inline ResultType accum_dist(const U& a, const V& b, int) const + { + return abs(a-b); + } +}; + + + +template +struct MinkowskiDistance +{ + typedef True is_kdtree_distance; + typedef True is_vector_space_distance; + + typedef T ElementType; + typedef typename Accumulator::Type ResultType; + typedef ResultType CentersType; + + int order; + + MinkowskiDistance(int order_) : order(order_) {} + + /** + * Compute the Minkowski (L_p) distance between two vectors. + * + * This is highly optimised, with loop unrolling, as it is one + * of the most expensive inner loops. + * + * The computation of squared root at the end is omitted for + * efficiency. + */ + template + ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const + { + ResultType result = ResultType(); + ResultType diff0, diff1, diff2, diff3; + Iterator1 last = a + size; + Iterator1 lastgroup = last - 3; + + /* Process 4 items with each loop for efficiency. */ + while (a < lastgroup) { + diff0 = (ResultType)abs(a[0] - b[0]); + diff1 = (ResultType)abs(a[1] - b[1]); + diff2 = (ResultType)abs(a[2] - b[2]); + diff3 = (ResultType)abs(a[3] - b[3]); + result += pow(diff0,order) + pow(diff1,order) + pow(diff2,order) + pow(diff3,order); + a += 4; + b += 4; + + if ((worst_dist>0)&&(result>worst_dist)) { + return result; + } + } + /* Process last 0-3 pixels. Not needed for standard vector lengths. */ + while (a < last) { + diff0 = (ResultType)abs(*a++ - *b++); + result += pow(diff0,order); + } + return result; + } + + /** + * Partial distance, used by the kd-tree. + */ + template + inline ResultType accum_dist(const U& a, const V& b, int) const + { + return pow(static_cast(abs(a-b)),order); + } +}; + + + +template +struct MaxDistance +{ + typedef False is_kdtree_distance; + typedef True is_vector_space_distance; + + typedef T ElementType; + typedef typename Accumulator::Type ResultType; + typedef ResultType CentersType; + + /** + * Compute the max distance (L_infinity) between two vectors. + * + * This distance is not a valid kdtree distance, it's not dimensionwise additive. + */ + template + ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const + { + ResultType result = ResultType(); + ResultType diff0, diff1, diff2, diff3; + Iterator1 last = a + size; + Iterator1 lastgroup = last - 3; + + /* Process 4 items with each loop for efficiency. */ + while (a < lastgroup) { + diff0 = abs(a[0] - b[0]); + diff1 = abs(a[1] - b[1]); + diff2 = abs(a[2] - b[2]); + diff3 = abs(a[3] - b[3]); + if (diff0>result) {result = diff0; } + if (diff1>result) {result = diff1; } + if (diff2>result) {result = diff2; } + if (diff3>result) {result = diff3; } + a += 4; + b += 4; + + if ((worst_dist>0)&&(result>worst_dist)) { + return result; + } + } + /* Process last 0-3 pixels. Not needed for standard vector lengths. */ + while (a < last) { + diff0 = abs(*a++ - *b++); + result = (diff0>result) ? diff0 : result; + } + return result; + } + + /* This distance functor is not dimension-wise additive, which + * makes it an invalid kd-tree distance, not implementing the accum_dist method */ + +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * Hamming distance functor - counts the bit differences between two strings - useful for the Brief descriptor + * bit count of A exclusive XOR'ed with B + */ +struct HammingLUT +{ + typedef False is_kdtree_distance; + typedef False is_vector_space_distance; + + typedef unsigned char ElementType; + typedef int ResultType; + typedef ElementType CentersType; + + /** this will count the bits in a ^ b + */ + template + ResultType operator()(const unsigned char* a, const Iterator2 b, size_t size) const + { + static const uchar popCountTable[] = + { + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 + }; + ResultType result = 0; + const unsigned char* b2 = reinterpret_cast (b); + for (size_t i = 0; i < size; i++) { + result += popCountTable[a[i] ^ b2[i]]; + } + return result; + } + + + ResultType operator()(const unsigned char* a, const ZeroIterator b, size_t size) const + { + (void)b; + static const uchar popCountTable[] = + { + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 + }; + ResultType result = 0; + for (size_t i = 0; i < size; i++) { + result += popCountTable[a[i]]; + } + return result; + } +}; + +/** + * Hamming distance functor (pop count between two binary vectors, i.e. xor them and count the number of bits set) + * That code was taken from brief.cpp in OpenCV + */ +template +struct Hamming +{ + typedef False is_kdtree_distance; + typedef False is_vector_space_distance; + + + typedef T ElementType; + typedef int ResultType; + typedef ElementType CentersType; + + template + ResultType operator()(const Iterator1 a, const Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const + { + ResultType result = 0; +#if defined(__ARM_NEON) && !defined(__CUDACC__) + { + const unsigned char* a2 = reinterpret_cast (a); + const unsigned char* b2 = reinterpret_cast (b); + uint32x4_t bits = vmovq_n_u32(0); + for (size_t i = 0; i < size; i += 16) { + uint8x16_t A_vec = vld1q_u8 (a2 + i); + uint8x16_t B_vec = vld1q_u8 (b2 + i); + uint8x16_t AxorB = veorq_u8 (A_vec, B_vec); + uint8x16_t bitsSet = vcntq_u8 (AxorB); + uint16x8_t bitSet8 = vpaddlq_u8 (bitsSet); + uint32x4_t bitSet4 = vpaddlq_u16 (bitSet8); + bits = vaddq_u32(bits, bitSet4); + } + uint64x2_t bitSet2 = vpaddlq_u32 (bits); + result = vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),0); + result += vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),2); + } +#elif defined(__GNUC__) + { + //for portability just use unsigned long -- and use the __builtin_popcountll (see docs for __builtin_popcountll) + typedef unsigned long long pop_t; + const size_t modulo = size % sizeof(pop_t); + const pop_t* a2 = reinterpret_cast (a); + const pop_t* b2 = reinterpret_cast (b); + const pop_t* a2_end = a2 + (size / sizeof(pop_t)); + + for (; a2 != a2_end; ++a2, ++b2) result += __builtin_popcountll((*a2) ^ (*b2)); + + if (modulo) { + //in the case where size is not dividable by sizeof(size_t) + //need to mask off the bits at the end + pop_t a_final = 0, b_final = 0; + memcpy(&a_final, a2, modulo); + memcpy(&b_final, b2, modulo); + result += __builtin_popcountll(a_final ^ b_final); + } + } +#else // NO NEON and NOT GNUC + HammingLUT lut; + result = lut(reinterpret_cast (a), + reinterpret_cast (b), size); +#endif + return result; + } + + + template + ResultType operator()(const Iterator1 a, ZeroIterator b, size_t size, ResultType /*worst_dist*/ = -1) const + { + (void)b; + ResultType result = 0; +#if defined(__ARM_NEON) && !defined(__CUDACC__) + { + const unsigned char* a2 = reinterpret_cast (a); + uint32x4_t bits = vmovq_n_u32(0); + for (size_t i = 0; i < size; i += 16) { + uint8x16_t A_vec = vld1q_u8 (a2 + i); + uint8x16_t bitsSet = vcntq_u8 (A_vec); + uint16x8_t bitSet8 = vpaddlq_u8 (bitsSet); + uint32x4_t bitSet4 = vpaddlq_u16 (bitSet8); + bits = vaddq_u32(bits, bitSet4); + } + uint64x2_t bitSet2 = vpaddlq_u32 (bits); + result = vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),0); + result += vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),2); + } +#elif defined(__GNUC__) + { + //for portability just use unsigned long -- and use the __builtin_popcountll (see docs for __builtin_popcountll) + typedef unsigned long long pop_t; + const size_t modulo = size % sizeof(pop_t); + const pop_t* a2 = reinterpret_cast (a); + const pop_t* a2_end = a2 + (size / sizeof(pop_t)); + + for (; a2 != a2_end; ++a2) result += __builtin_popcountll(*a2); + + if (modulo) { + //in the case where size is not dividable by sizeof(size_t) + //need to mask off the bits at the end + pop_t a_final = 0; + memcpy(&a_final, a2, modulo); + result += __builtin_popcountll(a_final); + } + } +#else // NO NEON and NOT GNUC + HammingLUT lut; + result = lut(reinterpret_cast (a), b, size); +#endif + return result; + } +}; + +template +struct Hamming2 +{ + typedef False is_kdtree_distance; + typedef False is_vector_space_distance; + + typedef T ElementType; + typedef int ResultType; + typedef ElementType CentersType; + + /** This is popcount_3() from: + * http://en.wikipedia.org/wiki/Hamming_weight */ + unsigned int popcnt32(uint32_t n) const + { + n -= ((n >> 1) & 0x55555555); + n = (n & 0x33333333) + ((n >> 2) & 0x33333333); + return (((n + (n >> 4))& 0xF0F0F0F)* 0x1010101) >> 24; + } + +#ifdef FLANN_PLATFORM_64_BIT + unsigned int popcnt64(uint64_t n) const + { + n -= ((n >> 1) & 0x5555555555555555); + n = (n & 0x3333333333333333) + ((n >> 2) & 0x3333333333333333); + return (((n + (n >> 4))& 0x0f0f0f0f0f0f0f0f)* 0x0101010101010101) >> 56; + } +#endif + + template + ResultType operator()(const Iterator1 a, const Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const + { + CV_DbgAssert(!(size % long_word_size_) && "vectors size must be multiple of long words size (i.e. 8)"); + +#ifdef FLANN_PLATFORM_64_BIT + const uint64_t* pa = reinterpret_cast(a); + const uint64_t* pb = reinterpret_cast(b); + ResultType result = 0; + size /= long_word_size_; + for(size_t i = 0; i < size; ++i ) { + result += popcnt64(*pa ^ *pb); + ++pa; + ++pb; + } +#else + const uint32_t* pa = reinterpret_cast(a); + const uint32_t* pb = reinterpret_cast(b); + ResultType result = 0; + size /= long_word_size_; + for(size_t i = 0; i < size; ++i ) { + result += popcnt32(*pa ^ *pb); + ++pa; + ++pb; + } +#endif + return result; + } + + + template + ResultType operator()(const Iterator1 a, ZeroIterator b, size_t size, ResultType /*worst_dist*/ = -1) const + { + CV_DbgAssert(!(size % long_word_size_) && "vectors size must be multiple of long words size (i.e. 8)"); + + (void)b; +#ifdef FLANN_PLATFORM_64_BIT + const uint64_t* pa = reinterpret_cast(a); + ResultType result = 0; + size /= long_word_size_; + for(size_t i = 0; i < size; ++i ) { + result += popcnt64(*pa); + ++pa; + } +#else + const uint32_t* pa = reinterpret_cast(a); + ResultType result = 0; + size /= long_word_size_; + for(size_t i = 0; i < size; ++i ) { + result += popcnt32(*pa); + ++pa; + } +#endif + return result; + } + +private: +#ifdef FLANN_PLATFORM_64_BIT + static const size_t long_word_size_ = sizeof(uint64_t)/sizeof(unsigned char); +#else + static const size_t long_word_size_ = sizeof(uint32_t)/sizeof(unsigned char); +#endif +}; + + + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +struct DNAmmingLUT +{ + typedef False is_kdtree_distance; + typedef False is_vector_space_distance; + + typedef unsigned char ElementType; + typedef int ResultType; + typedef ElementType CentersType; + + /** this will count the bits in a ^ b + */ + template + ResultType operator()(const unsigned char* a, const Iterator2 b, size_t size) const + { + static const uchar popCountTable[] = + { + 0, 1, 1, 1, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, + 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, + 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, + 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, + 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, + 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, + 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, + 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4 + }; + ResultType result = 0; + const unsigned char* b2 = reinterpret_cast (b); + for (size_t i = 0; i < size; i++) { + result += popCountTable[a[i] ^ b2[i]]; + } + return result; + } + + + ResultType operator()(const unsigned char* a, const ZeroIterator b, size_t size) const + { + (void)b; + static const uchar popCountTable[] = + { + 0, 1, 1, 1, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, + 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, + 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, + 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, + 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, + 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, + 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, + 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4 + }; + ResultType result = 0; + for (size_t i = 0; i < size; i++) { + result += popCountTable[a[i]]; + } + return result; + } +}; + + +template +struct DNAmming2 +{ + typedef False is_kdtree_distance; + typedef False is_vector_space_distance; + + typedef T ElementType; + typedef int ResultType; + typedef ElementType CentersType; + + /** This is popcount_3() from: + * http://en.wikipedia.org/wiki/Hamming_weight */ + unsigned int popcnt32(uint32_t n) const + { + n = ((n >> 1) | n) & 0x55555555; + n = (n & 0x33333333) + ((n >> 2) & 0x33333333); + return (((n + (n >> 4))& 0x0F0F0F0F)* 0x01010101) >> 24; + } + +#ifdef FLANN_PLATFORM_64_BIT + unsigned int popcnt64(uint64_t n) const + { + n = ((n >> 1) | n) & 0x5555555555555555; + n = (n & 0x3333333333333333) + ((n >> 2) & 0x3333333333333333); + return (((n + (n >> 4))& 0x0f0f0f0f0f0f0f0f)* 0x0101010101010101) >> 56; + } +#endif + + template + ResultType operator()(const Iterator1 a, const Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const + { + CV_DbgAssert(!(size % long_word_size_) && "vectors size must be multiple of long words size (i.e. 8)"); + +#ifdef FLANN_PLATFORM_64_BIT + const uint64_t* pa = reinterpret_cast(a); + const uint64_t* pb = reinterpret_cast(b); + ResultType result = 0; + size /= long_word_size_; + for(size_t i = 0; i < size; ++i ) { + result += popcnt64(*pa ^ *pb); + ++pa; + ++pb; + } +#else + const uint32_t* pa = reinterpret_cast(a); + const uint32_t* pb = reinterpret_cast(b); + ResultType result = 0; + size /= long_word_size_; + for(size_t i = 0; i < size; ++i ) { + result += popcnt32(*pa ^ *pb); + ++pa; + ++pb; + } +#endif + return result; + } + + + template + ResultType operator()(const Iterator1 a, ZeroIterator b, size_t size, ResultType /*worst_dist*/ = -1) const + { + CV_DbgAssert(!(size % long_word_size_) && "vectors size must be multiple of long words size (i.e. 8)"); + + (void)b; +#ifdef FLANN_PLATFORM_64_BIT + const uint64_t* pa = reinterpret_cast(a); + ResultType result = 0; + size /= long_word_size_; + for(size_t i = 0; i < size; ++i ) { + result += popcnt64(*pa); + ++pa; + } +#else + const uint32_t* pa = reinterpret_cast(a); + ResultType result = 0; + size /= long_word_size_; + for(size_t i = 0; i < size; ++i ) { + result += popcnt32(*pa); + ++pa; + } +#endif + return result; + } + +private: +#ifdef FLANN_PLATFORM_64_BIT + static const size_t long_word_size_= sizeof(uint64_t)/sizeof(unsigned char); +#else + static const size_t long_word_size_= sizeof(uint32_t)/sizeof(unsigned char); +#endif +}; + + + +template +struct HistIntersectionDistance +{ + typedef True is_kdtree_distance; + typedef True is_vector_space_distance; + + typedef T ElementType; + typedef typename Accumulator::Type ResultType; + typedef ResultType CentersType; + + /** + * Compute the histogram intersection distance + */ + template + ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const + { + ResultType result = ResultType(); + ResultType min0, min1, min2, min3; + Iterator1 last = a + size; + Iterator1 lastgroup = last - 3; + + /* Process 4 items with each loop for efficiency. */ + while (a < lastgroup) { + min0 = (ResultType)(a[0] < b[0] ? a[0] : b[0]); + min1 = (ResultType)(a[1] < b[1] ? a[1] : b[1]); + min2 = (ResultType)(a[2] < b[2] ? a[2] : b[2]); + min3 = (ResultType)(a[3] < b[3] ? a[3] : b[3]); + result += min0 + min1 + min2 + min3; + a += 4; + b += 4; + if ((worst_dist>0)&&(result>worst_dist)) { + return result; + } + } + /* Process last 0-3 pixels. Not needed for standard vector lengths. */ + while (a < last) { + min0 = (ResultType)(*a < *b ? *a : *b); + result += min0; + ++a; + ++b; + } + return result; + } + + /** + * Partial distance, used by the kd-tree. + */ + template + inline ResultType accum_dist(const U& a, const V& b, int) const + { + return a +struct HellingerDistance +{ + typedef True is_kdtree_distance; + typedef True is_vector_space_distance; + + typedef T ElementType; + typedef typename Accumulator::Type ResultType; + typedef ResultType CentersType; + + /** + * Compute the Hellinger distance + */ + template + ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const + { + ResultType result = ResultType(); + ResultType diff0, diff1, diff2, diff3; + Iterator1 last = a + size; + Iterator1 lastgroup = last - 3; + + /* Process 4 items with each loop for efficiency. */ + while (a < lastgroup) { + diff0 = sqrt(static_cast(a[0])) - sqrt(static_cast(b[0])); + diff1 = sqrt(static_cast(a[1])) - sqrt(static_cast(b[1])); + diff2 = sqrt(static_cast(a[2])) - sqrt(static_cast(b[2])); + diff3 = sqrt(static_cast(a[3])) - sqrt(static_cast(b[3])); + result += diff0 * diff0 + diff1 * diff1 + diff2 * diff2 + diff3 * diff3; + a += 4; + b += 4; + } + while (a < last) { + diff0 = sqrt(static_cast(*a++)) - sqrt(static_cast(*b++)); + result += diff0 * diff0; + } + return result; + } + + /** + * Partial distance, used by the kd-tree. + */ + template + inline ResultType accum_dist(const U& a, const V& b, int) const + { + ResultType diff = sqrt(static_cast(a)) - sqrt(static_cast(b)); + return diff * diff; + } +}; + + +template +struct ChiSquareDistance +{ + typedef True is_kdtree_distance; + typedef True is_vector_space_distance; + + typedef T ElementType; + typedef typename Accumulator::Type ResultType; + typedef ResultType CentersType; + + /** + * Compute the chi-square distance + */ + template + ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const + { + ResultType result = ResultType(); + ResultType sum, diff; + Iterator1 last = a + size; + + while (a < last) { + sum = (ResultType)(*a + *b); + if (sum>0) { + diff = (ResultType)(*a - *b); + result += diff*diff/sum; + } + ++a; + ++b; + + if ((worst_dist>0)&&(result>worst_dist)) { + return result; + } + } + return result; + } + + /** + * Partial distance, used by the kd-tree. + */ + template + inline ResultType accum_dist(const U& a, const V& b, int) const + { + ResultType result = ResultType(); + ResultType sum, diff; + + sum = (ResultType)(a+b); + if (sum>0) { + diff = (ResultType)(a-b); + result = diff*diff/sum; + } + return result; + } +}; + + +template +struct KL_Divergence +{ + typedef True is_kdtree_distance; + typedef True is_vector_space_distance; + + typedef T ElementType; + typedef typename Accumulator::Type ResultType; + typedef ResultType CentersType; + + /** + * Compute the Kullback-Leibler divergence + */ + template + ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const + { + ResultType result = ResultType(); + Iterator1 last = a + size; + + while (a < last) { + if ( *a != 0 && *b != 0 ) { + ResultType ratio = (ResultType)(*a / *b); + if (ratio>0) { + result += *a * log(ratio); + } + } + ++a; + ++b; + + if ((worst_dist>0)&&(result>worst_dist)) { + return result; + } + } + return result; + } + + /** + * Partial distance, used by the kd-tree. + */ + template + inline ResultType accum_dist(const U& a, const V& b, int) const + { + ResultType result = ResultType(); + if( a != 0 && b != 0 ) { + ResultType ratio = (ResultType)(a / b); + if (ratio>0) { + result = a * log(ratio); + } + } + return result; + } +}; + + +/* + * Depending on processed distances, some of them are already squared (e.g. L2) + * and some are not (e.g.Hamming). In KMeans++ for instance we want to be sure + * we are working on ^2 distances, thus following templates to ensure that. + */ +template +struct squareDistance +{ + typedef typename Distance::ResultType ResultType; + ResultType operator()( ResultType dist ) { return dist*dist; } +}; + + +template +struct squareDistance, ElementType> +{ + typedef typename L2_Simple::ResultType ResultType; + ResultType operator()( ResultType dist ) { return dist; } +}; + +template +struct squareDistance, ElementType> +{ + typedef typename L2::ResultType ResultType; + ResultType operator()( ResultType dist ) { return dist; } +}; + + +template +struct squareDistance, ElementType> +{ + typedef typename MinkowskiDistance::ResultType ResultType; + ResultType operator()( ResultType dist ) { return dist; } +}; + +template +struct squareDistance, ElementType> +{ + typedef typename HellingerDistance::ResultType ResultType; + ResultType operator()( ResultType dist ) { return dist; } +}; + +template +struct squareDistance, ElementType> +{ + typedef typename ChiSquareDistance::ResultType ResultType; + ResultType operator()( ResultType dist ) { return dist; } +}; + + +template +typename Distance::ResultType ensureSquareDistance( typename Distance::ResultType dist ) +{ + typedef typename Distance::ElementType ElementType; + + squareDistance dummy; + return dummy( dist ); +} + + +/* + * ...a template to tell the user if the distance he is working with is actually squared + */ + +template +struct isSquareDist +{ + bool operator()() { return false; } +}; + + +template +struct isSquareDist, ElementType> +{ + bool operator()() { return true; } +}; + +template +struct isSquareDist, ElementType> +{ + bool operator()() { return true; } +}; + + +template +struct isSquareDist, ElementType> +{ + bool operator()() { return true; } +}; + +template +struct isSquareDist, ElementType> +{ + bool operator()() { return true; } +}; + +template +struct isSquareDist, ElementType> +{ + bool operator()() { return true; } +}; + + +template +bool isSquareDistance() +{ + typedef typename Distance::ElementType ElementType; + + isSquareDist dummy; + return dummy(); +} + +/* + * ...and a template to ensure the user that he will process the normal distance, + * and not squared distance, without losing processing time calling sqrt(ensureSquareDistance) + * that will result in doing actually sqrt(dist*dist) for L1 distance for instance. + */ +template +struct simpleDistance +{ + typedef typename Distance::ResultType ResultType; + ResultType operator()( ResultType dist ) { return dist; } +}; + + +template +struct simpleDistance, ElementType> +{ + typedef typename L2_Simple::ResultType ResultType; + ResultType operator()( ResultType dist ) { return sqrt(dist); } +}; + +template +struct simpleDistance, ElementType> +{ + typedef typename L2::ResultType ResultType; + ResultType operator()( ResultType dist ) { return sqrt(dist); } +}; + + +template +struct simpleDistance, ElementType> +{ + typedef typename MinkowskiDistance::ResultType ResultType; + ResultType operator()( ResultType dist ) { return sqrt(dist); } +}; + +template +struct simpleDistance, ElementType> +{ + typedef typename HellingerDistance::ResultType ResultType; + ResultType operator()( ResultType dist ) { return sqrt(dist); } +}; + +template +struct simpleDistance, ElementType> +{ + typedef typename ChiSquareDistance::ResultType ResultType; + ResultType operator()( ResultType dist ) { return sqrt(dist); } +}; + + +template +typename Distance::ResultType ensureSimpleDistance( typename Distance::ResultType dist ) +{ + typedef typename Distance::ElementType ElementType; + + simpleDistance dummy; + return dummy( dist ); +} + +} + +//! @endcond + +#endif //OPENCV_FLANN_DIST_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/dummy.h b/3rdParty/opencv-4.11.0/opencv2/flann/dummy.h index c176f2e4ef..7cfb12fbe3 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/dummy.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/dummy.h @@ -1,16 +1,16 @@ - -#ifndef OPENCV_FLANN_DUMMY_H_ -#define OPENCV_FLANN_DUMMY_H_ - -//! @cond IGNORED - -namespace cvflann -{ - -CV_DEPRECATED inline void dummyfunc() {} - -} - -//! @endcond - -#endif /* OPENCV_FLANN_DUMMY_H_ */ + +#ifndef OPENCV_FLANN_DUMMY_H_ +#define OPENCV_FLANN_DUMMY_H_ + +//! @cond IGNORED + +namespace cvflann +{ + +CV_DEPRECATED inline void dummyfunc() {} + +} + +//! @endcond + +#endif /* OPENCV_FLANN_DUMMY_H_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/dynamic_bitset.h b/3rdParty/opencv-4.11.0/opencv2/flann/dynamic_bitset.h index 676cb0b71e..a3f0be6fa8 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/dynamic_bitset.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/dynamic_bitset.h @@ -1,160 +1,160 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * 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 ``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 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. - *************************************************************************/ - -/*********************************************************************** - * Author: Vincent Rabaud - *************************************************************************/ - -#ifndef OPENCV_FLANN_DYNAMIC_BITSET_H_ -#define OPENCV_FLANN_DYNAMIC_BITSET_H_ - -//! @cond IGNORED - -#ifndef FLANN_USE_BOOST -# define FLANN_USE_BOOST 0 -#endif -//#define FLANN_USE_BOOST 1 -#if FLANN_USE_BOOST -#include -typedef boost::dynamic_bitset<> DynamicBitset; -#else - -#include - -#include "dist.h" - -namespace cvflann { - -/** Class re-implementing the boost version of it - * This helps not depending on boost, it also does not do the bound checks - * and has a way to reset a block for speed - */ -class DynamicBitset -{ -public: - /** default constructor - */ - DynamicBitset() : size_(0) - { - } - - /** only constructor we use in our code - * @param sz the size of the bitset (in bits) - */ - DynamicBitset(size_t sz) - { - resize(sz); - reset(); - } - - /** Sets all the bits to 0 - */ - void clear() - { - std::fill(bitset_.begin(), bitset_.end(), 0); - } - - /** @brief checks if the bitset is empty - * @return true if the bitset is empty - */ - bool empty() const - { - return bitset_.empty(); - } - - /** set all the bits to 0 - */ - void reset() - { - std::fill(bitset_.begin(), bitset_.end(), 0); - } - - /** @brief set one bit to 0 - */ - void reset(size_t index) - { - bitset_[index / cell_bit_size_] &= ~(size_t(1) << (index % cell_bit_size_)); - } - - /** @brief sets a specific bit to 0, and more bits too - * This function is useful when resetting a given set of bits so that the - * whole bitset ends up being 0: if that's the case, we don't care about setting - * other bits to 0 - */ - void reset_block(size_t index) - { - bitset_[index / cell_bit_size_] = 0; - } - - /** resize the bitset so that it contains at least sz bits - */ - void resize(size_t sz) - { - size_ = sz; - bitset_.resize(sz / cell_bit_size_ + 1); - } - - /** set a bit to true - * @param index the index of the bit to set to 1 - */ - void set(size_t index) - { - bitset_[index / cell_bit_size_] |= size_t(1) << (index % cell_bit_size_); - } - - /** gives the number of contained bits - */ - size_t size() const - { - return size_; - } - - /** check if a bit is set - * @param index the index of the bit to check - * @return true if the bit is set - */ - bool test(size_t index) const - { - return (bitset_[index / cell_bit_size_] & (size_t(1) << (index % cell_bit_size_))) != 0; - } - -private: - std::vector bitset_; - size_t size_; - static const unsigned int cell_bit_size_ = CHAR_BIT * sizeof(size_t); -}; - -} // namespace cvflann - -#endif - -//! @endcond - -#endif // OPENCV_FLANN_DYNAMIC_BITSET_H_ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * 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 ``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 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. + *************************************************************************/ + +/*********************************************************************** + * Author: Vincent Rabaud + *************************************************************************/ + +#ifndef OPENCV_FLANN_DYNAMIC_BITSET_H_ +#define OPENCV_FLANN_DYNAMIC_BITSET_H_ + +//! @cond IGNORED + +#ifndef FLANN_USE_BOOST +# define FLANN_USE_BOOST 0 +#endif +//#define FLANN_USE_BOOST 1 +#if FLANN_USE_BOOST +#include +typedef boost::dynamic_bitset<> DynamicBitset; +#else + +#include + +#include "dist.h" + +namespace cvflann { + +/** Class re-implementing the boost version of it + * This helps not depending on boost, it also does not do the bound checks + * and has a way to reset a block for speed + */ +class DynamicBitset +{ +public: + /** default constructor + */ + DynamicBitset() : size_(0) + { + } + + /** only constructor we use in our code + * @param sz the size of the bitset (in bits) + */ + DynamicBitset(size_t sz) + { + resize(sz); + reset(); + } + + /** Sets all the bits to 0 + */ + void clear() + { + std::fill(bitset_.begin(), bitset_.end(), 0); + } + + /** @brief checks if the bitset is empty + * @return true if the bitset is empty + */ + bool empty() const + { + return bitset_.empty(); + } + + /** set all the bits to 0 + */ + void reset() + { + std::fill(bitset_.begin(), bitset_.end(), 0); + } + + /** @brief set one bit to 0 + */ + void reset(size_t index) + { + bitset_[index / cell_bit_size_] &= ~(size_t(1) << (index % cell_bit_size_)); + } + + /** @brief sets a specific bit to 0, and more bits too + * This function is useful when resetting a given set of bits so that the + * whole bitset ends up being 0: if that's the case, we don't care about setting + * other bits to 0 + */ + void reset_block(size_t index) + { + bitset_[index / cell_bit_size_] = 0; + } + + /** resize the bitset so that it contains at least sz bits + */ + void resize(size_t sz) + { + size_ = sz; + bitset_.resize(sz / cell_bit_size_ + 1); + } + + /** set a bit to true + * @param index the index of the bit to set to 1 + */ + void set(size_t index) + { + bitset_[index / cell_bit_size_] |= size_t(1) << (index % cell_bit_size_); + } + + /** gives the number of contained bits + */ + size_t size() const + { + return size_; + } + + /** check if a bit is set + * @param index the index of the bit to check + * @return true if the bit is set + */ + bool test(size_t index) const + { + return (bitset_[index / cell_bit_size_] & (size_t(1) << (index % cell_bit_size_))) != 0; + } + +private: + std::vector bitset_; + size_t size_; + static const unsigned int cell_bit_size_ = CHAR_BIT * sizeof(size_t); +}; + +} // namespace cvflann + +#endif + +//! @endcond + +#endif // OPENCV_FLANN_DYNAMIC_BITSET_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/flann.hpp b/3rdParty/opencv-4.11.0/opencv2/flann/flann.hpp index 227683f979..58ba51ee1e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/flann.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/flann/flann.hpp @@ -1,48 +1,48 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifdef __OPENCV_BUILD -#error this is a compatibility header which should not be used inside the OpenCV library -#endif - -#include "opencv2/flann.hpp" +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/flann.hpp" diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/flann_base.hpp b/3rdParty/opencv-4.11.0/opencv2/flann/flann_base.hpp index af0b380bbf..a516dfa26e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/flann_base.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/flann/flann_base.hpp @@ -1,312 +1,312 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * 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 ``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 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 OPENCV_FLANN_BASE_HPP_ -#define OPENCV_FLANN_BASE_HPP_ - -//! @cond IGNORED - -#include -#include - -#include "general.h" -#include "matrix.h" -#include "params.h" -#include "saving.h" - -#include "all_indices.h" - -namespace cvflann -{ -class FILEScopeGuard { - -public: - explicit FILEScopeGuard(FILE* file) { - file_ = file; - }; - - ~FILEScopeGuard() { - fclose(file_); - }; - -private: - FILE* file_; -}; - - -/** - * Sets the log level used for all flann functions - * @param level Verbosity level - */ -inline void log_verbosity(int level) -{ - if (level >= 0) { - Logger::setLevel(level); - } -} - -/** - * (Deprecated) Index parameters for creating a saved index. - */ -struct SavedIndexParams : public IndexParams -{ - SavedIndexParams(cv::String filename) - { - (* this)["algorithm"] = FLANN_INDEX_SAVED; - (*this)["filename"] = filename; - } -}; - -template -NNIndex* load_saved_index(const Matrix& dataset, const cv::String& filename, Distance distance) -{ - typedef typename Distance::ElementType ElementType; - - FILE* fin = fopen(filename.c_str(), "rb"); - if (fin == NULL) { - return NULL; - } - FILEScopeGuard fscgd(fin); - - IndexHeader header = load_header(fin); - if (header.data_type != Datatype::type()) { - FLANN_THROW(cv::Error::StsError, "Datatype of saved index is different than of the one to be created."); - } - if ((size_t(header.rows) != dataset.rows)||(size_t(header.cols) != dataset.cols)) { - FLANN_THROW(cv::Error::StsError, "The index saved belongs to a different dataset"); - } - - IndexParams params; - params["algorithm"] = header.index_type; - NNIndex* nnIndex = create_index_by_type(dataset, params, distance); - nnIndex->loadIndex(fin); - - return nnIndex; -} - - -template -class Index : public NNIndex -{ -public: - typedef typename Distance::ElementType ElementType; - typedef typename Distance::ResultType DistanceType; - - Index(const Matrix& features, const IndexParams& params, Distance distance = Distance() ) - :index_params_(params) - { - flann_algorithm_t index_type = get_param(params,"algorithm"); - loaded_ = false; - - if (index_type == FLANN_INDEX_SAVED) { - nnIndex_ = load_saved_index(features, get_param(params,"filename"), distance); - loaded_ = true; - } - else { - nnIndex_ = create_index_by_type(features, params, distance); - } - } - - ~Index() - { - delete nnIndex_; - } - - /** - * Builds the index. - */ - void buildIndex() CV_OVERRIDE - { - if (!loaded_) { - nnIndex_->buildIndex(); - } - } - - void save(cv::String filename) - { - FILE* fout = fopen(filename.c_str(), "wb"); - if (fout == NULL) { - FLANN_THROW(cv::Error::StsError, "Cannot open file"); - } - save_header(fout, *nnIndex_); - saveIndex(fout); - fclose(fout); - } - - /** - * \brief Saves the index to a stream - * \param stream The stream to save the index to - */ - virtual void saveIndex(FILE* stream) CV_OVERRIDE - { - nnIndex_->saveIndex(stream); - } - - /** - * \brief Loads the index from a stream - * \param stream The stream from which the index is loaded - */ - virtual void loadIndex(FILE* stream) CV_OVERRIDE - { - nnIndex_->loadIndex(stream); - } - - /** - * \returns number of features in this index. - */ - size_t veclen() const CV_OVERRIDE - { - return nnIndex_->veclen(); - } - - /** - * \returns The dimensionality of the features in this index. - */ - size_t size() const CV_OVERRIDE - { - return nnIndex_->size(); - } - - /** - * \returns The index type (kdtree, kmeans,...) - */ - flann_algorithm_t getType() const CV_OVERRIDE - { - return nnIndex_->getType(); - } - - /** - * \returns The amount of memory (in bytes) used by the index. - */ - virtual int usedMemory() const CV_OVERRIDE - { - return nnIndex_->usedMemory(); - } - - - /** - * \returns The index parameters - */ - IndexParams getParameters() const CV_OVERRIDE - { - return nnIndex_->getParameters(); - } - - /** - * \brief Perform k-nearest neighbor search - * \param[in] queries The query points for which to find the nearest neighbors - * \param[out] indices The indices of the nearest neighbors found - * \param[out] dists Distances to the nearest neighbors found - * \param[in] knn Number of nearest neighbors to return - * \param[in] params Search parameters - */ - void knnSearch(const Matrix& queries, Matrix& indices, Matrix& dists, int knn, const SearchParams& params) CV_OVERRIDE - { - nnIndex_->knnSearch(queries, indices, dists, knn, params); - } - - /** - * \brief Perform radius search - * \param[in] query The query point - * \param[out] indices The indinces of the neighbors found within the given radius - * \param[out] dists The distances to the nearest neighbors found - * \param[in] radius The radius used for search - * \param[in] params Search parameters - * \returns Number of neighbors found - */ - int radiusSearch(const Matrix& query, Matrix& indices, Matrix& dists, float radius, const SearchParams& params) CV_OVERRIDE - { - return nnIndex_->radiusSearch(query, indices, dists, radius, params); - } - - /** - * \brief Method that searches for nearest-neighbours - */ - void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE - { - nnIndex_->findNeighbors(result, vec, searchParams); - } - - /** - * \brief Returns actual index - */ - CV_DEPRECATED NNIndex* getIndex() - { - return nnIndex_; - } - - /** - * \brief Returns index parameters. - * \deprecated use getParameters() instead. - */ - CV_DEPRECATED const IndexParams* getIndexParameters() - { - return &index_params_; - } - -private: - /** Pointer to actual index class */ - NNIndex* nnIndex_; - /** Indices if the index was loaded from a file */ - bool loaded_; - /** Parameters passed to the index */ - IndexParams index_params_; - - Index(const Index &); // copy disabled - Index& operator=(const Index &); // assign disabled -}; - -/** - * Performs a hierarchical clustering of the points passed as argument and then takes a cut in the - * the clustering tree to return a flat clustering. - * @param[in] points Points to be clustered - * @param centers The computed cluster centres. Matrix should be preallocated and centers.rows is the - * number of clusters requested. - * @param params Clustering parameters (The same as for cvflann::KMeansIndex) - * @param d Distance to be used for clustering (eg: cvflann::L2) - * @return number of clusters computed (can be different than clusters.rows and is the highest number - * of the form (branching-1)*K+1 smaller than clusters.rows). - */ -template -int hierarchicalClustering(const Matrix& points, Matrix& centers, - const KMeansIndexParams& params, Distance d = Distance()) -{ - KMeansIndex kmeans(points, params, d); - kmeans.buildIndex(); - - int clusterNum = kmeans.getClusterCenters(centers); - return clusterNum; -} - -} - -//! @endcond - -#endif /* OPENCV_FLANN_BASE_HPP_ */ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * 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 ``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 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 OPENCV_FLANN_BASE_HPP_ +#define OPENCV_FLANN_BASE_HPP_ + +//! @cond IGNORED + +#include +#include + +#include "general.h" +#include "matrix.h" +#include "params.h" +#include "saving.h" + +#include "all_indices.h" + +namespace cvflann +{ +class FILEScopeGuard { + +public: + explicit FILEScopeGuard(FILE* file) { + file_ = file; + }; + + ~FILEScopeGuard() { + fclose(file_); + }; + +private: + FILE* file_; +}; + + +/** + * Sets the log level used for all flann functions + * @param level Verbosity level + */ +inline void log_verbosity(int level) +{ + if (level >= 0) { + Logger::setLevel(level); + } +} + +/** + * (Deprecated) Index parameters for creating a saved index. + */ +struct SavedIndexParams : public IndexParams +{ + SavedIndexParams(cv::String filename) + { + (* this)["algorithm"] = FLANN_INDEX_SAVED; + (*this)["filename"] = filename; + } +}; + +template +NNIndex* load_saved_index(const Matrix& dataset, const cv::String& filename, Distance distance) +{ + typedef typename Distance::ElementType ElementType; + + FILE* fin = fopen(filename.c_str(), "rb"); + if (fin == NULL) { + return NULL; + } + FILEScopeGuard fscgd(fin); + + IndexHeader header = load_header(fin); + if (header.data_type != Datatype::type()) { + FLANN_THROW(cv::Error::StsError, "Datatype of saved index is different than of the one to be created."); + } + if ((size_t(header.rows) != dataset.rows)||(size_t(header.cols) != dataset.cols)) { + FLANN_THROW(cv::Error::StsError, "The index saved belongs to a different dataset"); + } + + IndexParams params; + params["algorithm"] = header.index_type; + NNIndex* nnIndex = create_index_by_type(dataset, params, distance); + nnIndex->loadIndex(fin); + + return nnIndex; +} + + +template +class Index : public NNIndex +{ +public: + typedef typename Distance::ElementType ElementType; + typedef typename Distance::ResultType DistanceType; + + Index(const Matrix& features, const IndexParams& params, Distance distance = Distance() ) + :index_params_(params) + { + flann_algorithm_t index_type = get_param(params,"algorithm"); + loaded_ = false; + + if (index_type == FLANN_INDEX_SAVED) { + nnIndex_ = load_saved_index(features, get_param(params,"filename"), distance); + loaded_ = true; + } + else { + nnIndex_ = create_index_by_type(features, params, distance); + } + } + + ~Index() + { + delete nnIndex_; + } + + /** + * Builds the index. + */ + void buildIndex() CV_OVERRIDE + { + if (!loaded_) { + nnIndex_->buildIndex(); + } + } + + void save(cv::String filename) + { + FILE* fout = fopen(filename.c_str(), "wb"); + if (fout == NULL) { + FLANN_THROW(cv::Error::StsError, "Cannot open file"); + } + save_header(fout, *nnIndex_); + saveIndex(fout); + fclose(fout); + } + + /** + * \brief Saves the index to a stream + * \param stream The stream to save the index to + */ + virtual void saveIndex(FILE* stream) CV_OVERRIDE + { + nnIndex_->saveIndex(stream); + } + + /** + * \brief Loads the index from a stream + * \param stream The stream from which the index is loaded + */ + virtual void loadIndex(FILE* stream) CV_OVERRIDE + { + nnIndex_->loadIndex(stream); + } + + /** + * \returns number of features in this index. + */ + size_t veclen() const CV_OVERRIDE + { + return nnIndex_->veclen(); + } + + /** + * \returns The dimensionality of the features in this index. + */ + size_t size() const CV_OVERRIDE + { + return nnIndex_->size(); + } + + /** + * \returns The index type (kdtree, kmeans,...) + */ + flann_algorithm_t getType() const CV_OVERRIDE + { + return nnIndex_->getType(); + } + + /** + * \returns The amount of memory (in bytes) used by the index. + */ + virtual int usedMemory() const CV_OVERRIDE + { + return nnIndex_->usedMemory(); + } + + + /** + * \returns The index parameters + */ + IndexParams getParameters() const CV_OVERRIDE + { + return nnIndex_->getParameters(); + } + + /** + * \brief Perform k-nearest neighbor search + * \param[in] queries The query points for which to find the nearest neighbors + * \param[out] indices The indices of the nearest neighbors found + * \param[out] dists Distances to the nearest neighbors found + * \param[in] knn Number of nearest neighbors to return + * \param[in] params Search parameters + */ + void knnSearch(const Matrix& queries, Matrix& indices, Matrix& dists, int knn, const SearchParams& params) CV_OVERRIDE + { + nnIndex_->knnSearch(queries, indices, dists, knn, params); + } + + /** + * \brief Perform radius search + * \param[in] query The query point + * \param[out] indices The indinces of the neighbors found within the given radius + * \param[out] dists The distances to the nearest neighbors found + * \param[in] radius The radius used for search + * \param[in] params Search parameters + * \returns Number of neighbors found + */ + int radiusSearch(const Matrix& query, Matrix& indices, Matrix& dists, float radius, const SearchParams& params) CV_OVERRIDE + { + return nnIndex_->radiusSearch(query, indices, dists, radius, params); + } + + /** + * \brief Method that searches for nearest-neighbours + */ + void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE + { + nnIndex_->findNeighbors(result, vec, searchParams); + } + + /** + * \brief Returns actual index + */ + CV_DEPRECATED NNIndex* getIndex() + { + return nnIndex_; + } + + /** + * \brief Returns index parameters. + * \deprecated use getParameters() instead. + */ + CV_DEPRECATED const IndexParams* getIndexParameters() + { + return &index_params_; + } + +private: + /** Pointer to actual index class */ + NNIndex* nnIndex_; + /** Indices if the index was loaded from a file */ + bool loaded_; + /** Parameters passed to the index */ + IndexParams index_params_; + + Index(const Index &); // copy disabled + Index& operator=(const Index &); // assign disabled +}; + +/** + * Performs a hierarchical clustering of the points passed as argument and then takes a cut in the + * the clustering tree to return a flat clustering. + * @param[in] points Points to be clustered + * @param centers The computed cluster centres. Matrix should be preallocated and centers.rows is the + * number of clusters requested. + * @param params Clustering parameters (The same as for cvflann::KMeansIndex) + * @param d Distance to be used for clustering (eg: cvflann::L2) + * @return number of clusters computed (can be different than clusters.rows and is the highest number + * of the form (branching-1)*K+1 smaller than clusters.rows). + */ +template +int hierarchicalClustering(const Matrix& points, Matrix& centers, + const KMeansIndexParams& params, Distance d = Distance()) +{ + KMeansIndex kmeans(points, params, d); + kmeans.buildIndex(); + + int clusterNum = kmeans.getClusterCenters(centers); + return clusterNum; +} + +} + +//! @endcond + +#endif /* OPENCV_FLANN_BASE_HPP_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/general.h b/3rdParty/opencv-4.11.0/opencv2/flann/general.h index e65cba2f8a..eeb07e41f9 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/general.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/general.h @@ -1,65 +1,65 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * 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 ``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 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 OPENCV_FLANN_GENERAL_H_ -#define OPENCV_FLANN_GENERAL_H_ - -#include "opencv2/core/version.hpp" - -#if CV_VERSION_MAJOR <= 4 - -//! @cond IGNORED - -#include "opencv2/core.hpp" - -namespace cvflann -{ - -class FLANNException : public cv::Exception -{ -public: - FLANNException(const char* message) : cv::Exception(0, message, "", __FILE__, __LINE__) { } - - FLANNException(const cv::String& message) : cv::Exception(0, message, "", __FILE__, __LINE__) { } -}; - -} - -#define FLANN_THROW(TYPE, STR) throw FLANNException(STR) - -#else - -#define FLANN_THROW(TYPE, STR) CV_Error(TYPE, STR) - -#endif - -//! @endcond - -#endif /* OPENCV_FLANN_GENERAL_H_ */ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * 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 ``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 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 OPENCV_FLANN_GENERAL_H_ +#define OPENCV_FLANN_GENERAL_H_ + +#include "opencv2/core/version.hpp" + +#if CV_VERSION_MAJOR <= 4 + +//! @cond IGNORED + +#include "opencv2/core.hpp" + +namespace cvflann +{ + +class FLANNException : public cv::Exception +{ +public: + FLANNException(const char* message) : cv::Exception(0, message, "", __FILE__, __LINE__) { } + + FLANNException(const cv::String& message) : cv::Exception(0, message, "", __FILE__, __LINE__) { } +}; + +} + +#define FLANN_THROW(TYPE, STR) throw FLANNException(STR) + +#else + +#define FLANN_THROW(TYPE, STR) CV_Error(TYPE, STR) + +#endif + +//! @endcond + +#endif /* OPENCV_FLANN_GENERAL_H_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/ground_truth.h b/3rdParty/opencv-4.11.0/opencv2/flann/ground_truth.h index 17f2a8e848..b859e6a030 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/ground_truth.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/ground_truth.h @@ -1,98 +1,98 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * 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 ``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 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 OPENCV_FLANN_GROUND_TRUTH_H_ -#define OPENCV_FLANN_GROUND_TRUTH_H_ - -//! @cond IGNORED - -#include "dist.h" -#include "matrix.h" - - -namespace cvflann -{ - -template -void find_nearest(const Matrix& dataset, typename Distance::ElementType* query, int* matches, int nn, - int skip = 0, Distance distance = Distance()) -{ - typedef typename Distance::ResultType DistanceType; - int n = nn + skip; - - std::vector match(n); - std::vector dists(n); - - dists[0] = distance(dataset[0], query, dataset.cols); - match[0] = 0; - int dcnt = 1; - - for (size_t i=1; i=1 && dists[j] -void compute_ground_truth(const Matrix& dataset, const Matrix& testset, Matrix& matches, - int skip=0, Distance d = Distance()) -{ - for (size_t i=0; i(dataset, testset[i], matches[i], (int)matches.cols, skip, d); - } -} - - -} - -//! @endcond - -#endif //OPENCV_FLANN_GROUND_TRUTH_H_ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * 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 ``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 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 OPENCV_FLANN_GROUND_TRUTH_H_ +#define OPENCV_FLANN_GROUND_TRUTH_H_ + +//! @cond IGNORED + +#include "dist.h" +#include "matrix.h" + + +namespace cvflann +{ + +template +void find_nearest(const Matrix& dataset, typename Distance::ElementType* query, int* matches, int nn, + int skip = 0, Distance distance = Distance()) +{ + typedef typename Distance::ResultType DistanceType; + int n = nn + skip; + + std::vector match(n); + std::vector dists(n); + + dists[0] = distance(dataset[0], query, dataset.cols); + match[0] = 0; + int dcnt = 1; + + for (size_t i=1; i=1 && dists[j] +void compute_ground_truth(const Matrix& dataset, const Matrix& testset, Matrix& matches, + int skip=0, Distance d = Distance()) +{ + for (size_t i=0; i(dataset, testset[i], matches[i], (int)matches.cols, skip, d); + } +} + + +} + +//! @endcond + +#endif //OPENCV_FLANN_GROUND_TRUTH_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/heap.h b/3rdParty/opencv-4.11.0/opencv2/flann/heap.h index 8cace20449..488073d760 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/heap.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/heap.h @@ -1,244 +1,244 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * 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 ``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 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 OPENCV_FLANN_HEAP_H_ -#define OPENCV_FLANN_HEAP_H_ - -//! @cond IGNORED - -#include -#include - -#include - -namespace cvflann -{ - -// TODO: Define x > y operator and use std::greater instead -template -struct greater -{ - bool operator()(const T& x, const T& y) const - { - return y < x; - } -}; - -/** - * Priority Queue Implementation - * - * The priority queue is implemented with a heap. A heap is a complete - * (full) binary tree in which each parent is less than both of its - * children, but the order of the children is unspecified. - */ -template -class Heap -{ - /** - * Storage array for the heap. - * Type T must be comparable. - */ - std::vector heap; -public: - /** - * \brief Constructs a heap with a pre-allocated capacity - * - * \param capacity heap maximum capacity - */ - Heap(const int capacity) - { - reserve(capacity); - } - - /** - * \brief Move-constructs a heap from an external vector - * - * \param vec external vector - */ - Heap(std::vector&& vec) - : heap(std::move(vec)) - { - std::make_heap(heap.begin(), heap.end(), greater()); - } - - /** - * - * \returns heap size - */ - int size() const - { - return (int)heap.size(); - } - - /** - * - * \returns heap capacity - */ - int capacity() const - { - return (int)heap.capacity(); - } - - /** - * \brief Tests if the heap is empty - * - * \returns true is heap empty, false otherwise - */ - bool empty() - { - return heap.empty(); - } - - /** - * \brief Clears the heap. - */ - void clear() - { - heap.clear(); - } - - /** - * \brief Sets the heap maximum capacity. - * - * \param capacity heap maximum capacity - */ - void reserve(const int capacity) - { - heap.reserve(capacity); - } - - /** - * \brief Inserts a new element in the heap. - * - * We select the next empty leaf node, and then keep moving any larger - * parents down until the right location is found to store this element. - * - * \param value the new element to be inserted in the heap - */ - void insert(T value) - { - /* If heap is full, then return without adding this element. */ - if (size() == capacity()) { - return; - } - - heap.push_back(value); - std::push_heap(heap.begin(), heap.end(), greater()); - } - - /** - * \brief Returns the node of minimum value from the heap (top of the heap). - * - * \param[out] value parameter used to return the min element - * \returns false if heap empty - */ - bool popMin(T& value) - { - if (empty()) { - return false; - } - - value = heap[0]; - std::pop_heap(heap.begin(), heap.end(), greater()); - heap.pop_back(); - - return true; /* Return old last node. */ - } - - /** - * \brief Returns a shared heap for the given memory pool ID. - * - * It constructs the heap if it does not already exists. - * - * \param poolId a user-chosen hashable ID for identifying the heap. - * For thread-safe operations, using current thread ID is a good choice. - * \param capacity heap maximum capacity - * \param iterThreshold remove heaps that were not reused for more than specified iterations count - * if iterThreshold value is less 2, it will be internally adjusted to twice the number of CPU threads - * \returns pointer to the heap - */ - template - static cv::Ptr> getPooledInstance( - const HashableT& poolId, const int capacity, int iterThreshold = 0) - { - static cv::Mutex mutex; - const cv::AutoLock lock(mutex); - - struct HeapMapValueType { - cv::Ptr> heapPtr; - int iterCounter; - }; - typedef std::unordered_map HeapMapType; - - static HeapMapType heapsPool; - typename HeapMapType::iterator heapIt = heapsPool.find(poolId); - - if (heapIt == heapsPool.end()) - { - // Construct the heap as it does not already exists - HeapMapValueType heapAndTimePair = {cv::makePtr>(capacity), 0}; - const std::pair& emplaceResult = heapsPool.emplace(poolId, std::move(heapAndTimePair)); - CV_CheckEQ(static_cast(emplaceResult.second), 1, "Failed to insert the heap into its memory pool"); - heapIt = emplaceResult.first; - } - else - { - CV_CheckEQ(heapIt->second.heapPtr.use_count(), 1, "Cannot modify a heap that is currently accessed by another caller"); - heapIt->second.heapPtr->clear(); - heapIt->second.heapPtr->reserve(capacity); - heapIt->second.iterCounter = 0; - } - - if (iterThreshold <= 1) { - iterThreshold = 2 * cv::getNumThreads(); - } - - // Remove heaps that were not reused for more than given iterThreshold - typename HeapMapType::iterator cleanupIt = heapsPool.begin(); - while (cleanupIt != heapsPool.end()) - { - if (cleanupIt->second.iterCounter++ > iterThreshold) - { - CV_Assert(cleanupIt != heapIt); - cleanupIt = heapsPool.erase(cleanupIt); - continue; - } - ++cleanupIt; - } - - return heapIt->second.heapPtr; - } -}; - -} - -//! @endcond - -#endif //OPENCV_FLANN_HEAP_H_ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * 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 ``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 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 OPENCV_FLANN_HEAP_H_ +#define OPENCV_FLANN_HEAP_H_ + +//! @cond IGNORED + +#include +#include + +#include + +namespace cvflann +{ + +// TODO: Define x > y operator and use std::greater instead +template +struct greater +{ + bool operator()(const T& x, const T& y) const + { + return y < x; + } +}; + +/** + * Priority Queue Implementation + * + * The priority queue is implemented with a heap. A heap is a complete + * (full) binary tree in which each parent is less than both of its + * children, but the order of the children is unspecified. + */ +template +class Heap +{ + /** + * Storage array for the heap. + * Type T must be comparable. + */ + std::vector heap; +public: + /** + * \brief Constructs a heap with a pre-allocated capacity + * + * \param capacity heap maximum capacity + */ + Heap(const int capacity) + { + reserve(capacity); + } + + /** + * \brief Move-constructs a heap from an external vector + * + * \param vec external vector + */ + Heap(std::vector&& vec) + : heap(std::move(vec)) + { + std::make_heap(heap.begin(), heap.end(), greater()); + } + + /** + * + * \returns heap size + */ + int size() const + { + return (int)heap.size(); + } + + /** + * + * \returns heap capacity + */ + int capacity() const + { + return (int)heap.capacity(); + } + + /** + * \brief Tests if the heap is empty + * + * \returns true is heap empty, false otherwise + */ + bool empty() + { + return heap.empty(); + } + + /** + * \brief Clears the heap. + */ + void clear() + { + heap.clear(); + } + + /** + * \brief Sets the heap maximum capacity. + * + * \param capacity heap maximum capacity + */ + void reserve(const int capacity) + { + heap.reserve(capacity); + } + + /** + * \brief Inserts a new element in the heap. + * + * We select the next empty leaf node, and then keep moving any larger + * parents down until the right location is found to store this element. + * + * \param value the new element to be inserted in the heap + */ + void insert(T value) + { + /* If heap is full, then return without adding this element. */ + if (size() == capacity()) { + return; + } + + heap.push_back(value); + std::push_heap(heap.begin(), heap.end(), greater()); + } + + /** + * \brief Returns the node of minimum value from the heap (top of the heap). + * + * \param[out] value parameter used to return the min element + * \returns false if heap empty + */ + bool popMin(T& value) + { + if (empty()) { + return false; + } + + value = heap[0]; + std::pop_heap(heap.begin(), heap.end(), greater()); + heap.pop_back(); + + return true; /* Return old last node. */ + } + + /** + * \brief Returns a shared heap for the given memory pool ID. + * + * It constructs the heap if it does not already exists. + * + * \param poolId a user-chosen hashable ID for identifying the heap. + * For thread-safe operations, using current thread ID is a good choice. + * \param capacity heap maximum capacity + * \param iterThreshold remove heaps that were not reused for more than specified iterations count + * if iterThreshold value is less 2, it will be internally adjusted to twice the number of CPU threads + * \returns pointer to the heap + */ + template + static cv::Ptr> getPooledInstance( + const HashableT& poolId, const int capacity, int iterThreshold = 0) + { + static cv::Mutex mutex; + const cv::AutoLock lock(mutex); + + struct HeapMapValueType { + cv::Ptr> heapPtr; + int iterCounter; + }; + typedef std::unordered_map HeapMapType; + + static HeapMapType heapsPool; + typename HeapMapType::iterator heapIt = heapsPool.find(poolId); + + if (heapIt == heapsPool.end()) + { + // Construct the heap as it does not already exists + HeapMapValueType heapAndTimePair = {cv::makePtr>(capacity), 0}; + const std::pair& emplaceResult = heapsPool.emplace(poolId, std::move(heapAndTimePair)); + CV_CheckEQ(static_cast(emplaceResult.second), 1, "Failed to insert the heap into its memory pool"); + heapIt = emplaceResult.first; + } + else + { + CV_CheckEQ(heapIt->second.heapPtr.use_count(), 1, "Cannot modify a heap that is currently accessed by another caller"); + heapIt->second.heapPtr->clear(); + heapIt->second.heapPtr->reserve(capacity); + heapIt->second.iterCounter = 0; + } + + if (iterThreshold <= 1) { + iterThreshold = 2 * cv::getNumThreads(); + } + + // Remove heaps that were not reused for more than given iterThreshold + typename HeapMapType::iterator cleanupIt = heapsPool.begin(); + while (cleanupIt != heapsPool.end()) + { + if (cleanupIt->second.iterCounter++ > iterThreshold) + { + CV_Assert(cleanupIt != heapIt); + cleanupIt = heapsPool.erase(cleanupIt); + continue; + } + ++cleanupIt; + } + + return heapIt->second.heapPtr; + } +}; + +} + +//! @endcond + +#endif //OPENCV_FLANN_HEAP_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/hierarchical_clustering_index.h b/3rdParty/opencv-4.11.0/opencv2/flann/hierarchical_clustering_index.h index 60662e7714..31eef2b406 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/hierarchical_clustering_index.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/hierarchical_clustering_index.h @@ -1,846 +1,846 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2011 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2011 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * 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 ``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 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 OPENCV_FLANN_HIERARCHICAL_CLUSTERING_INDEX_H_ -#define OPENCV_FLANN_HIERARCHICAL_CLUSTERING_INDEX_H_ - -//! @cond IGNORED - -#include -#include -#include -#include - -#include "general.h" -#include "nn_index.h" -#include "dist.h" -#include "matrix.h" -#include "result_set.h" -#include "heap.h" -#include "allocator.h" -#include "random.h" -#include "saving.h" - - -namespace cvflann -{ - -struct HierarchicalClusteringIndexParams : public IndexParams -{ - HierarchicalClusteringIndexParams(int branching = 32, - flann_centers_init_t centers_init = FLANN_CENTERS_RANDOM, - int trees = 4, int leaf_size = 100) - { - (*this)["algorithm"] = FLANN_INDEX_HIERARCHICAL; - // The branching factor used in the hierarchical clustering - (*this)["branching"] = branching; - // Algorithm used for picking the initial cluster centers - (*this)["centers_init"] = centers_init; - // number of parallel trees to build - (*this)["trees"] = trees; - // maximum leaf size - (*this)["leaf_size"] = leaf_size; - } -}; - - -/** - * Hierarchical index - * - * Contains a tree constructed through a hierarchical clustering - * and other information for indexing a set of points for nearest-neighbour matching. - */ -template -class HierarchicalClusteringIndex : public NNIndex -{ -public: - typedef typename Distance::ElementType ElementType; - typedef typename Distance::ResultType DistanceType; - -private: - - - typedef void (HierarchicalClusteringIndex::* centersAlgFunction)(int, int*, int, int*, int&); - - /** - * The function used for choosing the cluster centers. - */ - centersAlgFunction chooseCenters; - - - - /** - * Chooses the initial centers in the k-means clustering in a random manner. - * - * Params: - * k = number of centers - * vecs = the dataset of points - * indices = indices in the dataset - * indices_length = length of indices vector - * - */ - void chooseCentersRandom(int k, int* dsindices, int indices_length, int* centers, int& centers_length) - { - UniqueRandom r(indices_length); - - int index; - for (index=0; index=0 && rnd < n); - - centers[0] = dsindices[rnd]; - - int index; - for (index=1; indexbest_val) { - best_val = dist; - best_index = j; - } - } - if (best_index!=-1) { - centers[index] = dsindices[best_index]; - } - else { - break; - } - } - centers_length = index; - } - - - /** - * Chooses the initial centers in the k-means using the algorithm - * proposed in the KMeans++ paper: - * Arthur, David; Vassilvitskii, Sergei - k-means++: The Advantages of Careful Seeding - * - * Implementation of this function was converted from the one provided in Arthur's code. - * - * Params: - * k = number of centers - * vecs = the dataset of points - * indices = indices in the dataset - * Returns: - */ - void chooseCentersKMeanspp(int k, int* dsindices, int indices_length, int* centers, int& centers_length) - { - int n = indices_length; - - double currentPot = 0; - DistanceType* closestDistSq = new DistanceType[n]; - - // Choose one random center and set the closestDistSq values - int index = rand_int(n); - CV_DbgAssert(index >=0 && index < n); - centers[0] = dsindices[index]; - - // Computing distance^2 will have the advantage of even higher probability further to pick new centers - // far from previous centers (and this complies to "k-means++: the advantages of careful seeding" article) - for (int i = 0; i < n; i++) { - closestDistSq[i] = distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols); - closestDistSq[i] = ensureSquareDistance( closestDistSq[i] ); - currentPot += closestDistSq[i]; - } - - - const int numLocalTries = 1; - - // Choose each center - int centerCount; - for (centerCount = 1; centerCount < k; centerCount++) { - - // Repeat several trials - double bestNewPot = -1; - int bestNewIndex = 0; - for (int localTrial = 0; localTrial < numLocalTries; localTrial++) { - - // Choose our center - have to be slightly careful to return a valid answer even accounting - // for possible rounding errors - double randVal = rand_double(currentPot); - for (index = 0; index < n-1; index++) { - if (randVal <= closestDistSq[index]) break; - else randVal -= closestDistSq[index]; - } - - // Compute the new potential - double newPot = 0; - for (int i = 0; i < n; i++) { - DistanceType dist = distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols); - newPot += std::min( ensureSquareDistance(dist), closestDistSq[i] ); - } - - // Store the best result - if ((bestNewPot < 0)||(newPot < bestNewPot)) { - bestNewPot = newPot; - bestNewIndex = index; - } - } - - // Add the appropriate center - centers[centerCount] = dsindices[bestNewIndex]; - currentPot = bestNewPot; - for (int i = 0; i < n; i++) { - DistanceType dist = distance(dataset[dsindices[i]], dataset[dsindices[bestNewIndex]], dataset.cols); - closestDistSq[i] = std::min( ensureSquareDistance(dist), closestDistSq[i] ); - } - } - - centers_length = centerCount; - - delete[] closestDistSq; - } - - - /** - * Chooses the initial centers in a way inspired by Gonzales (by Pierre-Emmanuel Viel): - * select the first point of the list as a candidate, then parse the points list. If another - * point is further than current candidate from the other centers, test if it is a good center - * of a local aggregation. If it is, replace current candidate by this point. And so on... - * - * Used with KMeansIndex that computes centers coordinates by averaging positions of clusters points, - * this doesn't make a real difference with previous methods. But used with HierarchicalClusteringIndex - * class that pick centers among existing points instead of computing the barycenters, there is a real - * improvement. - * - * Params: - * k = number of centers - * vecs = the dataset of points - * indices = indices in the dataset - * Returns: - */ - void GroupWiseCenterChooser(int k, int* dsindices, int indices_length, int* centers, int& centers_length) - { - const float kSpeedUpFactor = 1.3f; - - int n = indices_length; - - DistanceType* closestDistSq = new DistanceType[n]; - - // Choose one random center and set the closestDistSq values - int index = rand_int(n); - CV_DbgAssert(index >=0 && index < n); - centers[0] = dsindices[index]; - - for (int i = 0; i < n; i++) { - closestDistSq[i] = distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols); - } - - - // Choose each center - int centerCount; - for (centerCount = 1; centerCount < k; centerCount++) { - - // Repeat several trials - double bestNewPot = -1; - int bestNewIndex = 0; - DistanceType furthest = 0; - for (index = 0; index < n; index++) { - - // We will test only the potential of the points further than current candidate - if( closestDistSq[index] > kSpeedUpFactor * (float)furthest ) { - - // Compute the new potential - double newPot = 0; - for (int i = 0; i < n; i++) { - newPot += std::min( distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols) - , closestDistSq[i] ); - } - - // Store the best result - if ((bestNewPot < 0)||(newPot <= bestNewPot)) { - bestNewPot = newPot; - bestNewIndex = index; - furthest = closestDistSq[index]; - } - } - } - - // Add the appropriate center - centers[centerCount] = dsindices[bestNewIndex]; - for (int i = 0; i < n; i++) { - closestDistSq[i] = std::min( distance(dataset[dsindices[i]], dataset[dsindices[bestNewIndex]], dataset.cols) - , closestDistSq[i] ); - } - } - - centers_length = centerCount; - - delete[] closestDistSq; - } - - -public: - - - /** - * Index constructor - * - * Params: - * inputData = dataset with the input features - * params = parameters passed to the hierarchical k-means algorithm - */ - HierarchicalClusteringIndex(const Matrix& inputData, const IndexParams& index_params = HierarchicalClusteringIndexParams(), - Distance d = Distance()) - : dataset(inputData), params(index_params), root(NULL), indices(NULL), distance(d) - { - memoryCounter = 0; - - size_ = dataset.rows; - veclen_ = dataset.cols; - - branching_ = get_param(params,"branching",32); - centers_init_ = get_param(params,"centers_init", FLANN_CENTERS_RANDOM); - trees_ = get_param(params,"trees",4); - leaf_size_ = get_param(params,"leaf_size",100); - - if (centers_init_==FLANN_CENTERS_RANDOM) { - chooseCenters = &HierarchicalClusteringIndex::chooseCentersRandom; - } - else if (centers_init_==FLANN_CENTERS_GONZALES) { - chooseCenters = &HierarchicalClusteringIndex::chooseCentersGonzales; - } - else if (centers_init_==FLANN_CENTERS_KMEANSPP) { - chooseCenters = &HierarchicalClusteringIndex::chooseCentersKMeanspp; - } - else if (centers_init_==FLANN_CENTERS_GROUPWISE) { - chooseCenters = &HierarchicalClusteringIndex::GroupWiseCenterChooser; - } - else { - FLANN_THROW(cv::Error::StsError, "Unknown algorithm for choosing initial centers."); - } - - root = new NodePtr[trees_]; - indices = new int*[trees_]; - - for (int i=0; i(); - computeClustering(root[i], indices[i], (int)size_, branching_,0); - } - } - - - flann_algorithm_t getType() const CV_OVERRIDE - { - return FLANN_INDEX_HIERARCHICAL; - } - - - void saveIndex(FILE* stream) CV_OVERRIDE - { - save_value(stream, branching_); - save_value(stream, trees_); - save_value(stream, centers_init_); - save_value(stream, leaf_size_); - save_value(stream, memoryCounter); - for (int i=0; i& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE - { - - const int maxChecks = get_param(searchParams,"checks",32); - const bool explore_all_trees = get_param(searchParams,"explore_all_trees",false); - - // Priority queue storing intermediate branches in the best-bin-first search - const cv::Ptr>& heap = Heap::getPooledInstance(cv::utils::getThreadID(), (int)size_); - - std::vector checked(size_,false); - int checks = 0; - for (int i=0; i= maxChecks) && result.full()) - break; - } - - BranchSt branch; - while (heap->popMin(branch) && (checks BranchSt; - - - - void save_tree(FILE* stream, NodePtr node, int num) - { - save_value(stream, *node); - if (node->childs==NULL) { - int indices_offset = (int)(node->indices - indices[num]); - save_value(stream, indices_offset); - } - else { - for(int i=0; ichilds[i], num); - } - } - } - - - void load_tree(FILE* stream, NodePtr& node, int num) - { - node = pool.allocate(); - load_value(stream, *node); - if (node->childs==NULL) { - int indices_offset; - load_value(stream, indices_offset); - node->indices = indices[num] + indices_offset; - } - else { - node->childs = pool.allocate(branching_); - for(int i=0; ichilds[i], num); - } - } - } - - - /** - * Release the inner elements of indices[] - */ - void free_indices() - { - if (indices!=NULL) { - for(int i=0; inew_dist) { - labels[i] = j; - dist = new_dist; - } - } - cost += dist; - } - } - - /** - * The method responsible with actually doing the recursive hierarchical - * clustering - * - * Params: - * node = the node to cluster - * indices = indices of the points belonging to the current node - * branching = the branching factor to use in the clustering - * - * TODO: for 1-sized clusters don't store a cluster center (it's the same as the single cluster point) - */ - void computeClustering(NodePtr node, int* dsindices, int indices_length, int branching, int level) - { - node->size = indices_length; - node->level = level; - - if (indices_length < leaf_size_) { // leaf node - node->indices = dsindices; - std::sort(node->indices,node->indices+indices_length); - node->childs = NULL; - return; - } - - std::vector centers(branching); - std::vector labels(indices_length); - - int centers_length; - (this->*chooseCenters)(branching, dsindices, indices_length, ¢ers[0], centers_length); - - if (centers_lengthindices = dsindices; - std::sort(node->indices,node->indices+indices_length); - node->childs = NULL; - return; - } - - - // assign points to clusters - DistanceType cost; - computeLabels(dsindices, indices_length, ¢ers[0], centers_length, &labels[0], cost); - - node->childs = pool.allocate(branching); - int start = 0; - int end = start; - for (int i=0; ichilds[i] = pool.allocate(); - node->childs[i]->pivot = centers[i]; - node->childs[i]->indices = NULL; - computeClustering(node->childs[i],dsindices+start, end-start, branching, level+1); - start=end; - } - } - - - - /** - * Performs one descent in the hierarchical k-means tree. The branches not - * visited are stored in a priority queue. - * - * Params: - * node = node to explore - * result = container for the k-nearest neighbors found - * vec = query points - * checks = how many points in the dataset have been checked so far - * maxChecks = maximum dataset points to checks - */ - - - void findNN(NodePtr node, ResultSet& result, const ElementType* vec, int& checks, int maxChecks, - const cv::Ptr>& heap, std::vector& checked, bool explore_all_trees = false) - { - if (node->childs==NULL) { - if (!explore_all_trees && (checks>=maxChecks) && result.full()) { - return; - } - for (int i=0; isize; ++i) { - int index = node->indices[i]; - if (!checked[index]) { - DistanceType dist = distance(dataset[index], vec, veclen_); - result.addPoint(dist, index); - checked[index] = true; - ++checks; - } - } - } - else { - DistanceType* domain_distances = new DistanceType[branching_]; - int best_index = 0; - domain_distances[best_index] = distance(vec, dataset[node->childs[best_index]->pivot], veclen_); - for (int i=1; ichilds[i]->pivot], veclen_); - if (domain_distances[i]insert(BranchSt(node->childs[i],domain_distances[i])); - } - } - delete[] domain_distances; - findNN(node->childs[best_index],result,vec, checks, maxChecks, heap, checked, explore_all_trees); - } - } - -private: - - - /** - * The dataset used by this index - */ - const Matrix dataset; - - /** - * Parameters used by this index - */ - IndexParams params; - - - /** - * Number of features in the dataset. - */ - size_t size_; - - /** - * Length of each feature. - */ - size_t veclen_; - - /** - * The root node in the tree. - */ - NodePtr* root; - - /** - * Array of indices to vectors in the dataset. - */ - int** indices; - - - /** - * The distance - */ - Distance distance; - - /** - * Pooled memory allocator. - * - * Using a pooled memory allocator is more efficient - * than allocating memory directly when there is a large - * number small of memory allocations. - */ - PooledAllocator pool; - - /** - * Memory occupied by the index. - */ - int memoryCounter; - - /** index parameters */ - int branching_; - int trees_; - flann_centers_init_t centers_init_; - int leaf_size_; - - -}; - -} - -//! @endcond - -#endif /* OPENCV_FLANN_HIERARCHICAL_CLUSTERING_INDEX_H_ */ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2011 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2011 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * 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 ``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 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 OPENCV_FLANN_HIERARCHICAL_CLUSTERING_INDEX_H_ +#define OPENCV_FLANN_HIERARCHICAL_CLUSTERING_INDEX_H_ + +//! @cond IGNORED + +#include +#include +#include +#include + +#include "general.h" +#include "nn_index.h" +#include "dist.h" +#include "matrix.h" +#include "result_set.h" +#include "heap.h" +#include "allocator.h" +#include "random.h" +#include "saving.h" + + +namespace cvflann +{ + +struct HierarchicalClusteringIndexParams : public IndexParams +{ + HierarchicalClusteringIndexParams(int branching = 32, + flann_centers_init_t centers_init = FLANN_CENTERS_RANDOM, + int trees = 4, int leaf_size = 100) + { + (*this)["algorithm"] = FLANN_INDEX_HIERARCHICAL; + // The branching factor used in the hierarchical clustering + (*this)["branching"] = branching; + // Algorithm used for picking the initial cluster centers + (*this)["centers_init"] = centers_init; + // number of parallel trees to build + (*this)["trees"] = trees; + // maximum leaf size + (*this)["leaf_size"] = leaf_size; + } +}; + + +/** + * Hierarchical index + * + * Contains a tree constructed through a hierarchical clustering + * and other information for indexing a set of points for nearest-neighbour matching. + */ +template +class HierarchicalClusteringIndex : public NNIndex +{ +public: + typedef typename Distance::ElementType ElementType; + typedef typename Distance::ResultType DistanceType; + +private: + + + typedef void (HierarchicalClusteringIndex::* centersAlgFunction)(int, int*, int, int*, int&); + + /** + * The function used for choosing the cluster centers. + */ + centersAlgFunction chooseCenters; + + + + /** + * Chooses the initial centers in the k-means clustering in a random manner. + * + * Params: + * k = number of centers + * vecs = the dataset of points + * indices = indices in the dataset + * indices_length = length of indices vector + * + */ + void chooseCentersRandom(int k, int* dsindices, int indices_length, int* centers, int& centers_length) + { + UniqueRandom r(indices_length); + + int index; + for (index=0; index=0 && rnd < n); + + centers[0] = dsindices[rnd]; + + int index; + for (index=1; indexbest_val) { + best_val = dist; + best_index = j; + } + } + if (best_index!=-1) { + centers[index] = dsindices[best_index]; + } + else { + break; + } + } + centers_length = index; + } + + + /** + * Chooses the initial centers in the k-means using the algorithm + * proposed in the KMeans++ paper: + * Arthur, David; Vassilvitskii, Sergei - k-means++: The Advantages of Careful Seeding + * + * Implementation of this function was converted from the one provided in Arthur's code. + * + * Params: + * k = number of centers + * vecs = the dataset of points + * indices = indices in the dataset + * Returns: + */ + void chooseCentersKMeanspp(int k, int* dsindices, int indices_length, int* centers, int& centers_length) + { + int n = indices_length; + + double currentPot = 0; + DistanceType* closestDistSq = new DistanceType[n]; + + // Choose one random center and set the closestDistSq values + int index = rand_int(n); + CV_DbgAssert(index >=0 && index < n); + centers[0] = dsindices[index]; + + // Computing distance^2 will have the advantage of even higher probability further to pick new centers + // far from previous centers (and this complies to "k-means++: the advantages of careful seeding" article) + for (int i = 0; i < n; i++) { + closestDistSq[i] = distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols); + closestDistSq[i] = ensureSquareDistance( closestDistSq[i] ); + currentPot += closestDistSq[i]; + } + + + const int numLocalTries = 1; + + // Choose each center + int centerCount; + for (centerCount = 1; centerCount < k; centerCount++) { + + // Repeat several trials + double bestNewPot = -1; + int bestNewIndex = 0; + for (int localTrial = 0; localTrial < numLocalTries; localTrial++) { + + // Choose our center - have to be slightly careful to return a valid answer even accounting + // for possible rounding errors + double randVal = rand_double(currentPot); + for (index = 0; index < n-1; index++) { + if (randVal <= closestDistSq[index]) break; + else randVal -= closestDistSq[index]; + } + + // Compute the new potential + double newPot = 0; + for (int i = 0; i < n; i++) { + DistanceType dist = distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols); + newPot += std::min( ensureSquareDistance(dist), closestDistSq[i] ); + } + + // Store the best result + if ((bestNewPot < 0)||(newPot < bestNewPot)) { + bestNewPot = newPot; + bestNewIndex = index; + } + } + + // Add the appropriate center + centers[centerCount] = dsindices[bestNewIndex]; + currentPot = bestNewPot; + for (int i = 0; i < n; i++) { + DistanceType dist = distance(dataset[dsindices[i]], dataset[dsindices[bestNewIndex]], dataset.cols); + closestDistSq[i] = std::min( ensureSquareDistance(dist), closestDistSq[i] ); + } + } + + centers_length = centerCount; + + delete[] closestDistSq; + } + + + /** + * Chooses the initial centers in a way inspired by Gonzales (by Pierre-Emmanuel Viel): + * select the first point of the list as a candidate, then parse the points list. If another + * point is further than current candidate from the other centers, test if it is a good center + * of a local aggregation. If it is, replace current candidate by this point. And so on... + * + * Used with KMeansIndex that computes centers coordinates by averaging positions of clusters points, + * this doesn't make a real difference with previous methods. But used with HierarchicalClusteringIndex + * class that pick centers among existing points instead of computing the barycenters, there is a real + * improvement. + * + * Params: + * k = number of centers + * vecs = the dataset of points + * indices = indices in the dataset + * Returns: + */ + void GroupWiseCenterChooser(int k, int* dsindices, int indices_length, int* centers, int& centers_length) + { + const float kSpeedUpFactor = 1.3f; + + int n = indices_length; + + DistanceType* closestDistSq = new DistanceType[n]; + + // Choose one random center and set the closestDistSq values + int index = rand_int(n); + CV_DbgAssert(index >=0 && index < n); + centers[0] = dsindices[index]; + + for (int i = 0; i < n; i++) { + closestDistSq[i] = distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols); + } + + + // Choose each center + int centerCount; + for (centerCount = 1; centerCount < k; centerCount++) { + + // Repeat several trials + double bestNewPot = -1; + int bestNewIndex = 0; + DistanceType furthest = 0; + for (index = 0; index < n; index++) { + + // We will test only the potential of the points further than current candidate + if( closestDistSq[index] > kSpeedUpFactor * (float)furthest ) { + + // Compute the new potential + double newPot = 0; + for (int i = 0; i < n; i++) { + newPot += std::min( distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols) + , closestDistSq[i] ); + } + + // Store the best result + if ((bestNewPot < 0)||(newPot <= bestNewPot)) { + bestNewPot = newPot; + bestNewIndex = index; + furthest = closestDistSq[index]; + } + } + } + + // Add the appropriate center + centers[centerCount] = dsindices[bestNewIndex]; + for (int i = 0; i < n; i++) { + closestDistSq[i] = std::min( distance(dataset[dsindices[i]], dataset[dsindices[bestNewIndex]], dataset.cols) + , closestDistSq[i] ); + } + } + + centers_length = centerCount; + + delete[] closestDistSq; + } + + +public: + + + /** + * Index constructor + * + * Params: + * inputData = dataset with the input features + * params = parameters passed to the hierarchical k-means algorithm + */ + HierarchicalClusteringIndex(const Matrix& inputData, const IndexParams& index_params = HierarchicalClusteringIndexParams(), + Distance d = Distance()) + : dataset(inputData), params(index_params), root(NULL), indices(NULL), distance(d) + { + memoryCounter = 0; + + size_ = dataset.rows; + veclen_ = dataset.cols; + + branching_ = get_param(params,"branching",32); + centers_init_ = get_param(params,"centers_init", FLANN_CENTERS_RANDOM); + trees_ = get_param(params,"trees",4); + leaf_size_ = get_param(params,"leaf_size",100); + + if (centers_init_==FLANN_CENTERS_RANDOM) { + chooseCenters = &HierarchicalClusteringIndex::chooseCentersRandom; + } + else if (centers_init_==FLANN_CENTERS_GONZALES) { + chooseCenters = &HierarchicalClusteringIndex::chooseCentersGonzales; + } + else if (centers_init_==FLANN_CENTERS_KMEANSPP) { + chooseCenters = &HierarchicalClusteringIndex::chooseCentersKMeanspp; + } + else if (centers_init_==FLANN_CENTERS_GROUPWISE) { + chooseCenters = &HierarchicalClusteringIndex::GroupWiseCenterChooser; + } + else { + FLANN_THROW(cv::Error::StsError, "Unknown algorithm for choosing initial centers."); + } + + root = new NodePtr[trees_]; + indices = new int*[trees_]; + + for (int i=0; i(); + computeClustering(root[i], indices[i], (int)size_, branching_,0); + } + } + + + flann_algorithm_t getType() const CV_OVERRIDE + { + return FLANN_INDEX_HIERARCHICAL; + } + + + void saveIndex(FILE* stream) CV_OVERRIDE + { + save_value(stream, branching_); + save_value(stream, trees_); + save_value(stream, centers_init_); + save_value(stream, leaf_size_); + save_value(stream, memoryCounter); + for (int i=0; i& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE + { + + const int maxChecks = get_param(searchParams,"checks",32); + const bool explore_all_trees = get_param(searchParams,"explore_all_trees",false); + + // Priority queue storing intermediate branches in the best-bin-first search + const cv::Ptr>& heap = Heap::getPooledInstance(cv::utils::getThreadID(), (int)size_); + + std::vector checked(size_,false); + int checks = 0; + for (int i=0; i= maxChecks) && result.full()) + break; + } + + BranchSt branch; + while (heap->popMin(branch) && (checks BranchSt; + + + + void save_tree(FILE* stream, NodePtr node, int num) + { + save_value(stream, *node); + if (node->childs==NULL) { + int indices_offset = (int)(node->indices - indices[num]); + save_value(stream, indices_offset); + } + else { + for(int i=0; ichilds[i], num); + } + } + } + + + void load_tree(FILE* stream, NodePtr& node, int num) + { + node = pool.allocate(); + load_value(stream, *node); + if (node->childs==NULL) { + int indices_offset; + load_value(stream, indices_offset); + node->indices = indices[num] + indices_offset; + } + else { + node->childs = pool.allocate(branching_); + for(int i=0; ichilds[i], num); + } + } + } + + + /** + * Release the inner elements of indices[] + */ + void free_indices() + { + if (indices!=NULL) { + for(int i=0; inew_dist) { + labels[i] = j; + dist = new_dist; + } + } + cost += dist; + } + } + + /** + * The method responsible with actually doing the recursive hierarchical + * clustering + * + * Params: + * node = the node to cluster + * indices = indices of the points belonging to the current node + * branching = the branching factor to use in the clustering + * + * TODO: for 1-sized clusters don't store a cluster center (it's the same as the single cluster point) + */ + void computeClustering(NodePtr node, int* dsindices, int indices_length, int branching, int level) + { + node->size = indices_length; + node->level = level; + + if (indices_length < leaf_size_) { // leaf node + node->indices = dsindices; + std::sort(node->indices,node->indices+indices_length); + node->childs = NULL; + return; + } + + std::vector centers(branching); + std::vector labels(indices_length); + + int centers_length; + (this->*chooseCenters)(branching, dsindices, indices_length, ¢ers[0], centers_length); + + if (centers_lengthindices = dsindices; + std::sort(node->indices,node->indices+indices_length); + node->childs = NULL; + return; + } + + + // assign points to clusters + DistanceType cost; + computeLabels(dsindices, indices_length, ¢ers[0], centers_length, &labels[0], cost); + + node->childs = pool.allocate(branching); + int start = 0; + int end = start; + for (int i=0; ichilds[i] = pool.allocate(); + node->childs[i]->pivot = centers[i]; + node->childs[i]->indices = NULL; + computeClustering(node->childs[i],dsindices+start, end-start, branching, level+1); + start=end; + } + } + + + + /** + * Performs one descent in the hierarchical k-means tree. The branches not + * visited are stored in a priority queue. + * + * Params: + * node = node to explore + * result = container for the k-nearest neighbors found + * vec = query points + * checks = how many points in the dataset have been checked so far + * maxChecks = maximum dataset points to checks + */ + + + void findNN(NodePtr node, ResultSet& result, const ElementType* vec, int& checks, int maxChecks, + const cv::Ptr>& heap, std::vector& checked, bool explore_all_trees = false) + { + if (node->childs==NULL) { + if (!explore_all_trees && (checks>=maxChecks) && result.full()) { + return; + } + for (int i=0; isize; ++i) { + int index = node->indices[i]; + if (!checked[index]) { + DistanceType dist = distance(dataset[index], vec, veclen_); + result.addPoint(dist, index); + checked[index] = true; + ++checks; + } + } + } + else { + DistanceType* domain_distances = new DistanceType[branching_]; + int best_index = 0; + domain_distances[best_index] = distance(vec, dataset[node->childs[best_index]->pivot], veclen_); + for (int i=1; ichilds[i]->pivot], veclen_); + if (domain_distances[i]insert(BranchSt(node->childs[i],domain_distances[i])); + } + } + delete[] domain_distances; + findNN(node->childs[best_index],result,vec, checks, maxChecks, heap, checked, explore_all_trees); + } + } + +private: + + + /** + * The dataset used by this index + */ + const Matrix dataset; + + /** + * Parameters used by this index + */ + IndexParams params; + + + /** + * Number of features in the dataset. + */ + size_t size_; + + /** + * Length of each feature. + */ + size_t veclen_; + + /** + * The root node in the tree. + */ + NodePtr* root; + + /** + * Array of indices to vectors in the dataset. + */ + int** indices; + + + /** + * The distance + */ + Distance distance; + + /** + * Pooled memory allocator. + * + * Using a pooled memory allocator is more efficient + * than allocating memory directly when there is a large + * number small of memory allocations. + */ + PooledAllocator pool; + + /** + * Memory occupied by the index. + */ + int memoryCounter; + + /** index parameters */ + int branching_; + int trees_; + flann_centers_init_t centers_init_; + int leaf_size_; + + +}; + +} + +//! @endcond + +#endif /* OPENCV_FLANN_HIERARCHICAL_CLUSTERING_INDEX_H_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/index_testing.h b/3rdParty/opencv-4.11.0/opencv2/flann/index_testing.h index 4c00143326..972c453984 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/index_testing.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/index_testing.h @@ -1,319 +1,319 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * 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 ``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 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 OPENCV_FLANN_INDEX_TESTING_H_ -#define OPENCV_FLANN_INDEX_TESTING_H_ - -//! @cond IGNORED - -#include -#include - -#include "matrix.h" -#include "nn_index.h" -#include "result_set.h" -#include "logger.h" -#include "timer.h" - - -namespace cvflann -{ - -inline int countCorrectMatches(int* neighbors, int* groundTruth, int n) -{ - int count = 0; - for (int i=0; i -typename Distance::ResultType computeDistanceRaport(const Matrix& inputData, typename Distance::ElementType* target, - int* neighbors, int* groundTruth, int veclen, int n, const Distance& distance) -{ - typedef typename Distance::ResultType DistanceType; - - DistanceType ret = 0; - for (int i=0; i -float search_with_ground_truth(NNIndex& index, const Matrix& inputData, - const Matrix& testData, const Matrix& matches, int nn, int checks, - float& time, typename Distance::ResultType& dist, const Distance& distance, int skipMatches) -{ - typedef typename Distance::ResultType DistanceType; - - if (matches.cols resultSet(nn+skipMatches); - SearchParams searchParams(checks); - - std::vector indices(nn+skipMatches); - std::vector dists(nn+skipMatches); - int* neighbors = &indices[skipMatches]; - - int correct = 0; - DistanceType distR = 0; - StartStopTimer t; - int repeats = 0; - while (t.value<0.2) { - repeats++; - t.start(); - correct = 0; - distR = 0; - for (size_t i = 0; i < testData.rows; i++) { - resultSet.init(&indices[0], &dists[0]); - index.findNeighbors(resultSet, testData[i], searchParams); - - correct += countCorrectMatches(neighbors,matches[i], nn); - distR += computeDistanceRaport(inputData, testData[i], neighbors, matches[i], (int)testData.cols, nn, distance); - } - t.stop(); - } - time = float(t.value/repeats); - - float precicion = (float)correct/(nn*testData.rows); - - dist = distR/(testData.rows*nn); - - Logger::info("%8d %10.4g %10.5g %10.5g %10.5g\n", - checks, precicion, time, 1000.0 * time / testData.rows, dist); - - return precicion; -} - - -template -float test_index_checks(NNIndex& index, const Matrix& inputData, - const Matrix& testData, const Matrix& matches, - int checks, float& precision, const Distance& distance, int nn = 1, int skipMatches = 0) -{ - typedef typename Distance::ResultType DistanceType; - - Logger::info(" Nodes Precision(%) Time(s) Time/vec(ms) Mean dist\n"); - Logger::info("---------------------------------------------------------\n"); - - float time = 0; - DistanceType dist = 0; - precision = search_with_ground_truth(index, inputData, testData, matches, nn, checks, time, dist, distance, skipMatches); - - return time; -} - -template -float test_index_precision(NNIndex& index, const Matrix& inputData, - const Matrix& testData, const Matrix& matches, - float precision, int& checks, const Distance& distance, int nn = 1, int skipMatches = 0) -{ - typedef typename Distance::ResultType DistanceType; - const float SEARCH_EPS = 0.001f; - - Logger::info(" Nodes Precision(%) Time(s) Time/vec(ms) Mean dist\n"); - Logger::info("---------------------------------------------------------\n"); - - int c2 = 1; - float p2; - int c1 = 1; - //float p1; - float time; - DistanceType dist; - - p2 = search_with_ground_truth(index, inputData, testData, matches, nn, c2, time, dist, distance, skipMatches); - - if (p2>precision) { - Logger::info("Got as close as I can\n"); - checks = c2; - return time; - } - - while (p2SEARCH_EPS) { - Logger::info("Start linear estimation\n"); - // after we got to values in the vecinity of the desired precision - // use linear approximation get a better estimation - - cx = (c1+c2)/2; - realPrecision = search_with_ground_truth(index, inputData, testData, matches, nn, cx, time, dist, distance, skipMatches); - while (fabs(realPrecision-precision)>SEARCH_EPS) { - - if (realPrecision -void test_index_precisions(NNIndex& index, const Matrix& inputData, - const Matrix& testData, const Matrix& matches, - float* precisions, int precisions_length, const Distance& distance, int nn = 1, int skipMatches = 0, float maxTime = 0) -{ - typedef typename Distance::ResultType DistanceType; - - const float SEARCH_EPS = 0.001; - - // make sure precisions array is sorted - std::sort(precisions, precisions+precisions_length); - - int pindex = 0; - float precision = precisions[pindex]; - - Logger::info(" Nodes Precision(%) Time(s) Time/vec(ms) Mean dist\n"); - Logger::info("---------------------------------------------------------\n"); - - int c2 = 1; - float p2; - - int c1 = 1; - - float time; - DistanceType dist; - - p2 = search_with_ground_truth(index, inputData, testData, matches, nn, c2, time, dist, distance, skipMatches); - - // if precision for 1 run down the tree is already - // better then some of the requested precisions, then - // skip those - while (precisions[pindex] 0)&&(time > maxTime)&&(p2SEARCH_EPS) { - Logger::info("Start linear estimation\n"); - // after we got to values in the vecinity of the desired precision - // use linear approximation get a better estimation - - cx = (c1+c2)/2; - realPrecision = search_with_ground_truth(index, inputData, testData, matches, nn, cx, time, dist, distance, skipMatches); - while (fabs(realPrecision-precision)>SEARCH_EPS) { - - if (realPrecision +#include + +#include "matrix.h" +#include "nn_index.h" +#include "result_set.h" +#include "logger.h" +#include "timer.h" + + +namespace cvflann +{ + +inline int countCorrectMatches(int* neighbors, int* groundTruth, int n) +{ + int count = 0; + for (int i=0; i +typename Distance::ResultType computeDistanceRaport(const Matrix& inputData, typename Distance::ElementType* target, + int* neighbors, int* groundTruth, int veclen, int n, const Distance& distance) +{ + typedef typename Distance::ResultType DistanceType; + + DistanceType ret = 0; + for (int i=0; i +float search_with_ground_truth(NNIndex& index, const Matrix& inputData, + const Matrix& testData, const Matrix& matches, int nn, int checks, + float& time, typename Distance::ResultType& dist, const Distance& distance, int skipMatches) +{ + typedef typename Distance::ResultType DistanceType; + + if (matches.cols resultSet(nn+skipMatches); + SearchParams searchParams(checks); + + std::vector indices(nn+skipMatches); + std::vector dists(nn+skipMatches); + int* neighbors = &indices[skipMatches]; + + int correct = 0; + DistanceType distR = 0; + StartStopTimer t; + int repeats = 0; + while (t.value<0.2) { + repeats++; + t.start(); + correct = 0; + distR = 0; + for (size_t i = 0; i < testData.rows; i++) { + resultSet.init(&indices[0], &dists[0]); + index.findNeighbors(resultSet, testData[i], searchParams); + + correct += countCorrectMatches(neighbors,matches[i], nn); + distR += computeDistanceRaport(inputData, testData[i], neighbors, matches[i], (int)testData.cols, nn, distance); + } + t.stop(); + } + time = float(t.value/repeats); + + float precicion = (float)correct/(nn*testData.rows); + + dist = distR/(testData.rows*nn); + + Logger::info("%8d %10.4g %10.5g %10.5g %10.5g\n", + checks, precicion, time, 1000.0 * time / testData.rows, dist); + + return precicion; +} + + +template +float test_index_checks(NNIndex& index, const Matrix& inputData, + const Matrix& testData, const Matrix& matches, + int checks, float& precision, const Distance& distance, int nn = 1, int skipMatches = 0) +{ + typedef typename Distance::ResultType DistanceType; + + Logger::info(" Nodes Precision(%) Time(s) Time/vec(ms) Mean dist\n"); + Logger::info("---------------------------------------------------------\n"); + + float time = 0; + DistanceType dist = 0; + precision = search_with_ground_truth(index, inputData, testData, matches, nn, checks, time, dist, distance, skipMatches); + + return time; +} + +template +float test_index_precision(NNIndex& index, const Matrix& inputData, + const Matrix& testData, const Matrix& matches, + float precision, int& checks, const Distance& distance, int nn = 1, int skipMatches = 0) +{ + typedef typename Distance::ResultType DistanceType; + const float SEARCH_EPS = 0.001f; + + Logger::info(" Nodes Precision(%) Time(s) Time/vec(ms) Mean dist\n"); + Logger::info("---------------------------------------------------------\n"); + + int c2 = 1; + float p2; + int c1 = 1; + //float p1; + float time; + DistanceType dist; + + p2 = search_with_ground_truth(index, inputData, testData, matches, nn, c2, time, dist, distance, skipMatches); + + if (p2>precision) { + Logger::info("Got as close as I can\n"); + checks = c2; + return time; + } + + while (p2SEARCH_EPS) { + Logger::info("Start linear estimation\n"); + // after we got to values in the vecinity of the desired precision + // use linear approximation get a better estimation + + cx = (c1+c2)/2; + realPrecision = search_with_ground_truth(index, inputData, testData, matches, nn, cx, time, dist, distance, skipMatches); + while (fabs(realPrecision-precision)>SEARCH_EPS) { + + if (realPrecision +void test_index_precisions(NNIndex& index, const Matrix& inputData, + const Matrix& testData, const Matrix& matches, + float* precisions, int precisions_length, const Distance& distance, int nn = 1, int skipMatches = 0, float maxTime = 0) +{ + typedef typename Distance::ResultType DistanceType; + + const float SEARCH_EPS = 0.001; + + // make sure precisions array is sorted + std::sort(precisions, precisions+precisions_length); + + int pindex = 0; + float precision = precisions[pindex]; + + Logger::info(" Nodes Precision(%) Time(s) Time/vec(ms) Mean dist\n"); + Logger::info("---------------------------------------------------------\n"); + + int c2 = 1; + float p2; + + int c1 = 1; + + float time; + DistanceType dist; + + p2 = search_with_ground_truth(index, inputData, testData, matches, nn, c2, time, dist, distance, skipMatches); + + // if precision for 1 run down the tree is already + // better then some of the requested precisions, then + // skip those + while (precisions[pindex] 0)&&(time > maxTime)&&(p2SEARCH_EPS) { + Logger::info("Start linear estimation\n"); + // after we got to values in the vecinity of the desired precision + // use linear approximation get a better estimation + + cx = (c1+c2)/2; + realPrecision = search_with_ground_truth(index, inputData, testData, matches, nn, cx, time, dist, distance, skipMatches); + while (fabs(realPrecision-precision)>SEARCH_EPS) { + + if (realPrecision -#include -#include - -#include "nn_index.h" -#include "dynamic_bitset.h" -#include "matrix.h" -#include "result_set.h" -#include "heap.h" -#include "allocator.h" -#include "random.h" -#include "saving.h" - - -namespace cvflann -{ - -struct KDTreeIndexParams : public IndexParams -{ - KDTreeIndexParams(int trees = 4) - { - (*this)["algorithm"] = FLANN_INDEX_KDTREE; - (*this)["trees"] = trees; - } -}; - - -/** - * Randomized kd-tree index - * - * Contains the k-d trees and other information for indexing a set of points - * for nearest-neighbor matching. - */ -template -class KDTreeIndex : public NNIndex -{ -public: - typedef typename Distance::ElementType ElementType; - typedef typename Distance::ResultType DistanceType; - - - /** - * KDTree constructor - * - * Params: - * inputData = dataset with the input features - * params = parameters passed to the kdtree algorithm - */ - KDTreeIndex(const Matrix& inputData, const IndexParams& params = KDTreeIndexParams(), - Distance d = Distance() ) : - dataset_(inputData), index_params_(params), distance_(d) - { - size_ = dataset_.rows; - veclen_ = dataset_.cols; - - trees_ = get_param(index_params_,"trees",4); - tree_roots_ = new NodePtr[trees_]; - - // Create a permutable array of indices to the input vectors. - vind_.resize(size_); - for (size_t i = 0; i < size_; ++i) { - vind_[i] = int(i); - } - - mean_ = new DistanceType[veclen_]; - var_ = new DistanceType[veclen_]; - } - - - KDTreeIndex(const KDTreeIndex&); - KDTreeIndex& operator=(const KDTreeIndex&); - - /** - * Standard destructor - */ - ~KDTreeIndex() - { - if (tree_roots_!=NULL) { - delete[] tree_roots_; - } - delete[] mean_; - delete[] var_; - } - - /** - * Builds the index - */ - void buildIndex() CV_OVERRIDE - { - /* Construct the randomized trees. */ - for (int i = 0; i < trees_; i++) { - /* Randomize the order of vectors to allow for unbiased sampling. */ -#ifndef OPENCV_FLANN_USE_STD_RAND - cv::randShuffle(vind_); -#else - std::random_shuffle(vind_.begin(), vind_.end()); -#endif - - tree_roots_[i] = divideTree(&vind_[0], int(size_) ); - } - } - - - flann_algorithm_t getType() const CV_OVERRIDE - { - return FLANN_INDEX_KDTREE; - } - - - void saveIndex(FILE* stream) CV_OVERRIDE - { - save_value(stream, trees_); - for (int i=0; i& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE - { - const int maxChecks = get_param(searchParams,"checks", 32); - const float epsError = 1+get_param(searchParams,"eps",0.0f); - const bool explore_all_trees = get_param(searchParams,"explore_all_trees",false); - - if (maxChecks==FLANN_CHECKS_UNLIMITED) { - getExactNeighbors(result, vec, epsError); - } - else { - getNeighbors(result, vec, maxChecks, epsError, explore_all_trees); - } - } - - IndexParams getParameters() const CV_OVERRIDE - { - return index_params_; - } - -private: - - - /*--------------------- Internal Data Structures --------------------------*/ - struct Node - { - /** - * Dimension used for subdivision. - */ - int divfeat; - /** - * The values used for subdivision. - */ - DistanceType divval; - /** - * The child nodes. - */ - Node* child1, * child2; - }; - typedef Node* NodePtr; - typedef BranchStruct BranchSt; - typedef BranchSt* Branch; - - - - void save_tree(FILE* stream, NodePtr tree) - { - save_value(stream, *tree); - if (tree->child1!=NULL) { - save_tree(stream, tree->child1); - } - if (tree->child2!=NULL) { - save_tree(stream, tree->child2); - } - } - - - void load_tree(FILE* stream, NodePtr& tree) - { - tree = pool_.allocate(); - load_value(stream, *tree); - if (tree->child1!=NULL) { - load_tree(stream, tree->child1); - } - if (tree->child2!=NULL) { - load_tree(stream, tree->child2); - } - } - - - /** - * Create a tree node that subdivides the list of vecs from vind[first] - * to vind[last]. The routine is called recursively on each sublist. - * Place a pointer to this new tree node in the location pTree. - * - * Params: pTree = the new node to create - * first = index of the first vector - * last = index of the last vector - */ - NodePtr divideTree(int* ind, int count) - { - NodePtr node = pool_.allocate(); // allocate memory - - /* If too few exemplars remain, then make this a leaf node. */ - if ( count == 1) { - node->child1 = node->child2 = NULL; /* Mark as leaf node. */ - node->divfeat = *ind; /* Store index of this vec. */ - } - else { - int idx; - int cutfeat; - DistanceType cutval; - meanSplit(ind, count, idx, cutfeat, cutval); - - node->divfeat = cutfeat; - node->divval = cutval; - node->child1 = divideTree(ind, idx); - node->child2 = divideTree(ind+idx, count-idx); - } - - return node; - } - - - /** - * Choose which feature to use in order to subdivide this set of vectors. - * Make a random choice among those with the highest variance, and use - * its variance as the threshold value. - */ - void meanSplit(int* ind, int count, int& index, int& cutfeat, DistanceType& cutval) - { - memset(mean_,0,veclen_*sizeof(DistanceType)); - memset(var_,0,veclen_*sizeof(DistanceType)); - - /* Compute mean values. Only the first SAMPLE_MEAN values need to be - sampled to get a good estimate. - */ - int cnt = std::min((int)SAMPLE_MEAN+1, count); - for (int j = 0; j < cnt; ++j) { - ElementType* v = dataset_[ind[j]]; - for (size_t k=0; kcount/2) index = lim1; - else if (lim2 v[topind[num-1]])) { - /* Put this element at end of topind. */ - if (num < RAND_DIM) { - topind[num++] = i; /* Add to list. */ - } - else { - topind[num-1] = i; /* Replace last element. */ - } - /* Bubble end value down to right location by repeated swapping. */ - int j = num - 1; - while (j > 0 && v[topind[j]] > v[topind[j-1]]) { - std::swap(topind[j], topind[j-1]); - --j; - } - } - } - /* Select a random integer in range [0,num-1], and return that index. */ - int rnd = rand_int(num); - return (int)topind[rnd]; - } - - - /** - * Subdivide the list of points by a plane perpendicular on axe corresponding - * to the 'cutfeat' dimension at 'cutval' position. - * - * On return: - * dataset[ind[0..lim1-1]][cutfeat]cutval - */ - void planeSplit(int* ind, int count, int cutfeat, DistanceType cutval, int& lim1, int& lim2) - { - /* Move vector indices for left subtree to front of list. */ - int left = 0; - int right = count-1; - for (;; ) { - while (left<=right && dataset_[ind[left]][cutfeat]=cutval) --right; - if (left>right) break; - std::swap(ind[left], ind[right]); ++left; --right; - } - lim1 = left; - right = count-1; - for (;; ) { - while (left<=right && dataset_[ind[left]][cutfeat]<=cutval) ++left; - while (left<=right && dataset_[ind[right]][cutfeat]>cutval) --right; - if (left>right) break; - std::swap(ind[left], ind[right]); ++left; --right; - } - lim2 = left; - } - - /** - * Performs an exact nearest neighbor search. The exact search performs a full - * traversal of the tree. - */ - void getExactNeighbors(ResultSet& result, const ElementType* vec, float epsError) - { - // checkID -= 1; /* Set a different unique ID for each search. */ - - if (trees_ > 1) { - fprintf(stderr,"It doesn't make any sense to use more than one tree for exact search"); - } - if (trees_>0) { - searchLevelExact(result, vec, tree_roots_[0], 0.0, epsError); - } - CV_Assert(result.full()); - } - - /** - * Performs the approximate nearest-neighbor search. The search is approximate - * because the tree traversal is abandoned after a given number of descends in - * the tree. - */ - void getNeighbors(ResultSet& result, const ElementType* vec, - int maxCheck, float epsError, bool explore_all_trees = false) - { - int i; - BranchSt branch; - int checkCount = 0; - DynamicBitset checked(size_); - - // Priority queue storing intermediate branches in the best-bin-first search - const cv::Ptr>& heap = Heap::getPooledInstance(cv::utils::getThreadID(), (int)size_); - - /* Search once through each tree down to root. */ - for (i = 0; i < trees_; ++i) { - searchLevel(result, vec, tree_roots_[i], 0, checkCount, maxCheck, - epsError, heap, checked, explore_all_trees); - if (!explore_all_trees && (checkCount >= maxCheck) && result.full()) - break; - } - - /* Keep searching other branches from heap until finished. */ - while ( heap->popMin(branch) && (checkCount < maxCheck || !result.full() )) { - searchLevel(result, vec, branch.node, branch.mindist, checkCount, maxCheck, - epsError, heap, checked, false); - } - - CV_Assert(result.full()); - } - - - /** - * Search starting from a given node of the tree. Based on any mismatches at - * higher levels, all exemplars below this level must have a distance of - * at least "mindistsq". - */ - void searchLevel(ResultSet& result_set, const ElementType* vec, NodePtr node, DistanceType mindist, int& checkCount, int maxCheck, - float epsError, const cv::Ptr>& heap, DynamicBitset& checked, bool explore_all_trees = false) - { - if (result_set.worstDist()child1 == NULL)&&(node->child2 == NULL)) { - /* Do not check same node more than once when searching multiple trees. - Once a vector is checked, we set its location in vind to the - current checkID. - */ - int index = node->divfeat; - if ( checked.test(index) || - (!explore_all_trees && (checkCount>=maxCheck) && result_set.full()) ) { - return; - } - checked.set(index); - checkCount++; - - DistanceType dist = distance_(dataset_[index], vec, veclen_); - result_set.addPoint(dist,index); - - return; - } - - /* Which child branch should be taken first? */ - ElementType val = vec[node->divfeat]; - DistanceType diff = val - node->divval; - NodePtr bestChild = (diff < 0) ? node->child1 : node->child2; - NodePtr otherChild = (diff < 0) ? node->child2 : node->child1; - - /* Create a branch record for the branch not taken. Add distance - of this feature boundary (we don't attempt to correct for any - use of this feature in a parent node, which is unlikely to - happen and would have only a small effect). Don't bother - adding more branches to heap after halfway point, as cost of - adding exceeds their value. - */ - - DistanceType new_distsq = mindist + distance_.accum_dist(val, node->divval, node->divfeat); - // if (2 * checkCount < maxCheck || !result.full()) { - if ((new_distsq*epsError < result_set.worstDist())|| !result_set.full()) { - heap->insert( BranchSt(otherChild, new_distsq) ); - } - - /* Call recursively to search next level down. */ - searchLevel(result_set, vec, bestChild, mindist, checkCount, maxCheck, epsError, heap, checked); - } - - /** - * Performs an exact search in the tree starting from a node. - */ - void searchLevelExact(ResultSet& result_set, const ElementType* vec, const NodePtr node, DistanceType mindist, const float epsError) - { - /* If this is a leaf node, then do check and return. */ - if ((node->child1 == NULL)&&(node->child2 == NULL)) { - int index = node->divfeat; - DistanceType dist = distance_(dataset_[index], vec, veclen_); - result_set.addPoint(dist,index); - return; - } - - /* Which child branch should be taken first? */ - ElementType val = vec[node->divfeat]; - DistanceType diff = val - node->divval; - NodePtr bestChild = (diff < 0) ? node->child1 : node->child2; - NodePtr otherChild = (diff < 0) ? node->child2 : node->child1; - - /* Create a branch record for the branch not taken. Add distance - of this feature boundary (we don't attempt to correct for any - use of this feature in a parent node, which is unlikely to - happen and would have only a small effect). Don't bother - adding more branches to heap after halfway point, as cost of - adding exceeds their value. - */ - - DistanceType new_distsq = mindist + distance_.accum_dist(val, node->divval, node->divfeat); - - /* Call recursively to search next level down. */ - searchLevelExact(result_set, vec, bestChild, mindist, epsError); - - if (new_distsq*epsError<=result_set.worstDist()) { - searchLevelExact(result_set, vec, otherChild, new_distsq, epsError); - } - } - - -private: - - enum - { - /** - * To improve efficiency, only SAMPLE_MEAN random values are used to - * compute the mean and variance at each level when building a tree. - * A value of 100 seems to perform as well as using all values. - */ - SAMPLE_MEAN = 100, - /** - * Top random dimensions to consider - * - * When creating random trees, the dimension on which to subdivide is - * selected at random from among the top RAND_DIM dimensions with the - * highest variance. A value of 5 works well. - */ - RAND_DIM=5 - }; - - - /** - * Number of randomized trees that are used - */ - int trees_; - - /** - * Array of indices to vectors in the dataset. - */ - std::vector vind_; - - /** - * The dataset used by this index - */ - const Matrix dataset_; - - IndexParams index_params_; - - size_t size_; - size_t veclen_; - - - DistanceType* mean_; - DistanceType* var_; - - - /** - * Array of k-d trees used to find neighbours. - */ - NodePtr* tree_roots_; - - /** - * Pooled memory allocator. - * - * Using a pooled memory allocator is more efficient - * than allocating memory directly when there is a large - * number small of memory allocations. - */ - PooledAllocator pool_; - - Distance distance_; - - -}; // class KDTreeForest - -} - -//! @endcond - -#endif //OPENCV_FLANN_KDTREE_INDEX_H_ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * 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 ``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 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 OPENCV_FLANN_KDTREE_INDEX_H_ +#define OPENCV_FLANN_KDTREE_INDEX_H_ + +//! @cond IGNORED + +#include +#include +#include + +#include "nn_index.h" +#include "dynamic_bitset.h" +#include "matrix.h" +#include "result_set.h" +#include "heap.h" +#include "allocator.h" +#include "random.h" +#include "saving.h" + + +namespace cvflann +{ + +struct KDTreeIndexParams : public IndexParams +{ + KDTreeIndexParams(int trees = 4) + { + (*this)["algorithm"] = FLANN_INDEX_KDTREE; + (*this)["trees"] = trees; + } +}; + + +/** + * Randomized kd-tree index + * + * Contains the k-d trees and other information for indexing a set of points + * for nearest-neighbor matching. + */ +template +class KDTreeIndex : public NNIndex +{ +public: + typedef typename Distance::ElementType ElementType; + typedef typename Distance::ResultType DistanceType; + + + /** + * KDTree constructor + * + * Params: + * inputData = dataset with the input features + * params = parameters passed to the kdtree algorithm + */ + KDTreeIndex(const Matrix& inputData, const IndexParams& params = KDTreeIndexParams(), + Distance d = Distance() ) : + dataset_(inputData), index_params_(params), distance_(d) + { + size_ = dataset_.rows; + veclen_ = dataset_.cols; + + trees_ = get_param(index_params_,"trees",4); + tree_roots_ = new NodePtr[trees_]; + + // Create a permutable array of indices to the input vectors. + vind_.resize(size_); + for (size_t i = 0; i < size_; ++i) { + vind_[i] = int(i); + } + + mean_ = new DistanceType[veclen_]; + var_ = new DistanceType[veclen_]; + } + + + KDTreeIndex(const KDTreeIndex&); + KDTreeIndex& operator=(const KDTreeIndex&); + + /** + * Standard destructor + */ + ~KDTreeIndex() + { + if (tree_roots_!=NULL) { + delete[] tree_roots_; + } + delete[] mean_; + delete[] var_; + } + + /** + * Builds the index + */ + void buildIndex() CV_OVERRIDE + { + /* Construct the randomized trees. */ + for (int i = 0; i < trees_; i++) { + /* Randomize the order of vectors to allow for unbiased sampling. */ +#ifndef OPENCV_FLANN_USE_STD_RAND + cv::randShuffle(vind_); +#else + std::random_shuffle(vind_.begin(), vind_.end()); +#endif + + tree_roots_[i] = divideTree(&vind_[0], int(size_) ); + } + } + + + flann_algorithm_t getType() const CV_OVERRIDE + { + return FLANN_INDEX_KDTREE; + } + + + void saveIndex(FILE* stream) CV_OVERRIDE + { + save_value(stream, trees_); + for (int i=0; i& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE + { + const int maxChecks = get_param(searchParams,"checks", 32); + const float epsError = 1+get_param(searchParams,"eps",0.0f); + const bool explore_all_trees = get_param(searchParams,"explore_all_trees",false); + + if (maxChecks==FLANN_CHECKS_UNLIMITED) { + getExactNeighbors(result, vec, epsError); + } + else { + getNeighbors(result, vec, maxChecks, epsError, explore_all_trees); + } + } + + IndexParams getParameters() const CV_OVERRIDE + { + return index_params_; + } + +private: + + + /*--------------------- Internal Data Structures --------------------------*/ + struct Node + { + /** + * Dimension used for subdivision. + */ + int divfeat; + /** + * The values used for subdivision. + */ + DistanceType divval; + /** + * The child nodes. + */ + Node* child1, * child2; + }; + typedef Node* NodePtr; + typedef BranchStruct BranchSt; + typedef BranchSt* Branch; + + + + void save_tree(FILE* stream, NodePtr tree) + { + save_value(stream, *tree); + if (tree->child1!=NULL) { + save_tree(stream, tree->child1); + } + if (tree->child2!=NULL) { + save_tree(stream, tree->child2); + } + } + + + void load_tree(FILE* stream, NodePtr& tree) + { + tree = pool_.allocate(); + load_value(stream, *tree); + if (tree->child1!=NULL) { + load_tree(stream, tree->child1); + } + if (tree->child2!=NULL) { + load_tree(stream, tree->child2); + } + } + + + /** + * Create a tree node that subdivides the list of vecs from vind[first] + * to vind[last]. The routine is called recursively on each sublist. + * Place a pointer to this new tree node in the location pTree. + * + * Params: pTree = the new node to create + * first = index of the first vector + * last = index of the last vector + */ + NodePtr divideTree(int* ind, int count) + { + NodePtr node = pool_.allocate(); // allocate memory + + /* If too few exemplars remain, then make this a leaf node. */ + if ( count == 1) { + node->child1 = node->child2 = NULL; /* Mark as leaf node. */ + node->divfeat = *ind; /* Store index of this vec. */ + } + else { + int idx; + int cutfeat; + DistanceType cutval; + meanSplit(ind, count, idx, cutfeat, cutval); + + node->divfeat = cutfeat; + node->divval = cutval; + node->child1 = divideTree(ind, idx); + node->child2 = divideTree(ind+idx, count-idx); + } + + return node; + } + + + /** + * Choose which feature to use in order to subdivide this set of vectors. + * Make a random choice among those with the highest variance, and use + * its variance as the threshold value. + */ + void meanSplit(int* ind, int count, int& index, int& cutfeat, DistanceType& cutval) + { + memset(mean_,0,veclen_*sizeof(DistanceType)); + memset(var_,0,veclen_*sizeof(DistanceType)); + + /* Compute mean values. Only the first SAMPLE_MEAN values need to be + sampled to get a good estimate. + */ + int cnt = std::min((int)SAMPLE_MEAN+1, count); + for (int j = 0; j < cnt; ++j) { + ElementType* v = dataset_[ind[j]]; + for (size_t k=0; kcount/2) index = lim1; + else if (lim2 v[topind[num-1]])) { + /* Put this element at end of topind. */ + if (num < RAND_DIM) { + topind[num++] = i; /* Add to list. */ + } + else { + topind[num-1] = i; /* Replace last element. */ + } + /* Bubble end value down to right location by repeated swapping. */ + int j = num - 1; + while (j > 0 && v[topind[j]] > v[topind[j-1]]) { + std::swap(topind[j], topind[j-1]); + --j; + } + } + } + /* Select a random integer in range [0,num-1], and return that index. */ + int rnd = rand_int(num); + return (int)topind[rnd]; + } + + + /** + * Subdivide the list of points by a plane perpendicular on axe corresponding + * to the 'cutfeat' dimension at 'cutval' position. + * + * On return: + * dataset[ind[0..lim1-1]][cutfeat]cutval + */ + void planeSplit(int* ind, int count, int cutfeat, DistanceType cutval, int& lim1, int& lim2) + { + /* Move vector indices for left subtree to front of list. */ + int left = 0; + int right = count-1; + for (;; ) { + while (left<=right && dataset_[ind[left]][cutfeat]=cutval) --right; + if (left>right) break; + std::swap(ind[left], ind[right]); ++left; --right; + } + lim1 = left; + right = count-1; + for (;; ) { + while (left<=right && dataset_[ind[left]][cutfeat]<=cutval) ++left; + while (left<=right && dataset_[ind[right]][cutfeat]>cutval) --right; + if (left>right) break; + std::swap(ind[left], ind[right]); ++left; --right; + } + lim2 = left; + } + + /** + * Performs an exact nearest neighbor search. The exact search performs a full + * traversal of the tree. + */ + void getExactNeighbors(ResultSet& result, const ElementType* vec, float epsError) + { + // checkID -= 1; /* Set a different unique ID for each search. */ + + if (trees_ > 1) { + fprintf(stderr,"It doesn't make any sense to use more than one tree for exact search"); + } + if (trees_>0) { + searchLevelExact(result, vec, tree_roots_[0], 0.0, epsError); + } + CV_Assert(result.full()); + } + + /** + * Performs the approximate nearest-neighbor search. The search is approximate + * because the tree traversal is abandoned after a given number of descends in + * the tree. + */ + void getNeighbors(ResultSet& result, const ElementType* vec, + int maxCheck, float epsError, bool explore_all_trees = false) + { + int i; + BranchSt branch; + int checkCount = 0; + DynamicBitset checked(size_); + + // Priority queue storing intermediate branches in the best-bin-first search + const cv::Ptr>& heap = Heap::getPooledInstance(cv::utils::getThreadID(), (int)size_); + + /* Search once through each tree down to root. */ + for (i = 0; i < trees_; ++i) { + searchLevel(result, vec, tree_roots_[i], 0, checkCount, maxCheck, + epsError, heap, checked, explore_all_trees); + if (!explore_all_trees && (checkCount >= maxCheck) && result.full()) + break; + } + + /* Keep searching other branches from heap until finished. */ + while ( heap->popMin(branch) && (checkCount < maxCheck || !result.full() )) { + searchLevel(result, vec, branch.node, branch.mindist, checkCount, maxCheck, + epsError, heap, checked, false); + } + + CV_Assert(result.full()); + } + + + /** + * Search starting from a given node of the tree. Based on any mismatches at + * higher levels, all exemplars below this level must have a distance of + * at least "mindistsq". + */ + void searchLevel(ResultSet& result_set, const ElementType* vec, NodePtr node, DistanceType mindist, int& checkCount, int maxCheck, + float epsError, const cv::Ptr>& heap, DynamicBitset& checked, bool explore_all_trees = false) + { + if (result_set.worstDist()child1 == NULL)&&(node->child2 == NULL)) { + /* Do not check same node more than once when searching multiple trees. + Once a vector is checked, we set its location in vind to the + current checkID. + */ + int index = node->divfeat; + if ( checked.test(index) || + (!explore_all_trees && (checkCount>=maxCheck) && result_set.full()) ) { + return; + } + checked.set(index); + checkCount++; + + DistanceType dist = distance_(dataset_[index], vec, veclen_); + result_set.addPoint(dist,index); + + return; + } + + /* Which child branch should be taken first? */ + ElementType val = vec[node->divfeat]; + DistanceType diff = val - node->divval; + NodePtr bestChild = (diff < 0) ? node->child1 : node->child2; + NodePtr otherChild = (diff < 0) ? node->child2 : node->child1; + + /* Create a branch record for the branch not taken. Add distance + of this feature boundary (we don't attempt to correct for any + use of this feature in a parent node, which is unlikely to + happen and would have only a small effect). Don't bother + adding more branches to heap after halfway point, as cost of + adding exceeds their value. + */ + + DistanceType new_distsq = mindist + distance_.accum_dist(val, node->divval, node->divfeat); + // if (2 * checkCount < maxCheck || !result.full()) { + if ((new_distsq*epsError < result_set.worstDist())|| !result_set.full()) { + heap->insert( BranchSt(otherChild, new_distsq) ); + } + + /* Call recursively to search next level down. */ + searchLevel(result_set, vec, bestChild, mindist, checkCount, maxCheck, epsError, heap, checked); + } + + /** + * Performs an exact search in the tree starting from a node. + */ + void searchLevelExact(ResultSet& result_set, const ElementType* vec, const NodePtr node, DistanceType mindist, const float epsError) + { + /* If this is a leaf node, then do check and return. */ + if ((node->child1 == NULL)&&(node->child2 == NULL)) { + int index = node->divfeat; + DistanceType dist = distance_(dataset_[index], vec, veclen_); + result_set.addPoint(dist,index); + return; + } + + /* Which child branch should be taken first? */ + ElementType val = vec[node->divfeat]; + DistanceType diff = val - node->divval; + NodePtr bestChild = (diff < 0) ? node->child1 : node->child2; + NodePtr otherChild = (diff < 0) ? node->child2 : node->child1; + + /* Create a branch record for the branch not taken. Add distance + of this feature boundary (we don't attempt to correct for any + use of this feature in a parent node, which is unlikely to + happen and would have only a small effect). Don't bother + adding more branches to heap after halfway point, as cost of + adding exceeds their value. + */ + + DistanceType new_distsq = mindist + distance_.accum_dist(val, node->divval, node->divfeat); + + /* Call recursively to search next level down. */ + searchLevelExact(result_set, vec, bestChild, mindist, epsError); + + if (new_distsq*epsError<=result_set.worstDist()) { + searchLevelExact(result_set, vec, otherChild, new_distsq, epsError); + } + } + + +private: + + enum + { + /** + * To improve efficiency, only SAMPLE_MEAN random values are used to + * compute the mean and variance at each level when building a tree. + * A value of 100 seems to perform as well as using all values. + */ + SAMPLE_MEAN = 100, + /** + * Top random dimensions to consider + * + * When creating random trees, the dimension on which to subdivide is + * selected at random from among the top RAND_DIM dimensions with the + * highest variance. A value of 5 works well. + */ + RAND_DIM=5 + }; + + + /** + * Number of randomized trees that are used + */ + int trees_; + + /** + * Array of indices to vectors in the dataset. + */ + std::vector vind_; + + /** + * The dataset used by this index + */ + const Matrix dataset_; + + IndexParams index_params_; + + size_t size_; + size_t veclen_; + + + DistanceType* mean_; + DistanceType* var_; + + + /** + * Array of k-d trees used to find neighbours. + */ + NodePtr* tree_roots_; + + /** + * Pooled memory allocator. + * + * Using a pooled memory allocator is more efficient + * than allocating memory directly when there is a large + * number small of memory allocations. + */ + PooledAllocator pool_; + + Distance distance_; + + +}; // class KDTreeForest + +} + +//! @endcond + +#endif //OPENCV_FLANN_KDTREE_INDEX_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/kdtree_single_index.h b/3rdParty/opencv-4.11.0/opencv2/flann/kdtree_single_index.h index ed95c3db7d..5a5f8140f1 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/kdtree_single_index.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/kdtree_single_index.h @@ -1,645 +1,645 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * 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 ``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 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 OPENCV_FLANN_KDTREE_SINGLE_INDEX_H_ -#define OPENCV_FLANN_KDTREE_SINGLE_INDEX_H_ - -//! @cond IGNORED - -#include -#include -#include - -#include "nn_index.h" -#include "matrix.h" -#include "result_set.h" -#include "heap.h" -#include "allocator.h" -#include "random.h" -#include "saving.h" - -namespace cvflann -{ - -struct KDTreeSingleIndexParams : public IndexParams -{ - KDTreeSingleIndexParams(int leaf_max_size = 10, bool reorder = true, int dim = -1) - { - (*this)["algorithm"] = FLANN_INDEX_KDTREE_SINGLE; - (*this)["leaf_max_size"] = leaf_max_size; - (*this)["reorder"] = reorder; - (*this)["dim"] = dim; - } -}; - - -/** - * Randomized kd-tree index - * - * Contains the k-d trees and other information for indexing a set of points - * for nearest-neighbor matching. - */ -template -class KDTreeSingleIndex : public NNIndex -{ -public: - typedef typename Distance::ElementType ElementType; - typedef typename Distance::ResultType DistanceType; - - - /** - * KDTree constructor - * - * Params: - * inputData = dataset with the input features - * params = parameters passed to the kdtree algorithm - */ - KDTreeSingleIndex(const Matrix& inputData, const IndexParams& params = KDTreeSingleIndexParams(), - Distance d = Distance() ) : - dataset_(inputData), index_params_(params), distance_(d) - { - size_ = dataset_.rows; - dim_ = dataset_.cols; - root_node_ = 0; - int dim_param = get_param(params,"dim",-1); - if (dim_param>0) dim_ = dim_param; - leaf_max_size_ = get_param(params,"leaf_max_size",10); - reorder_ = get_param(params,"reorder",true); - - // Create a permutable array of indices to the input vectors. - vind_.resize(size_); - for (size_t i = 0; i < size_; i++) { - vind_[i] = (int)i; - } - } - - KDTreeSingleIndex(const KDTreeSingleIndex&); - KDTreeSingleIndex& operator=(const KDTreeSingleIndex&); - - /** - * Standard destructor - */ - ~KDTreeSingleIndex() - { - if (reorder_) delete[] data_.data; - } - - /** - * Builds the index - */ - void buildIndex() CV_OVERRIDE - { - computeBoundingBox(root_bbox_); - root_node_ = divideTree(0, (int)size_, root_bbox_ ); // construct the tree - - if (reorder_) { - delete[] data_.data; - data_ = cvflann::Matrix(new ElementType[size_*dim_], size_, dim_); - for (size_t i=0; i& queries, Matrix& indices, Matrix& dists, int knn, const SearchParams& params) CV_OVERRIDE - { - CV_Assert(queries.cols == veclen()); - CV_Assert(indices.rows >= queries.rows); - CV_Assert(dists.rows >= queries.rows); - CV_Assert(int(indices.cols) >= knn); - CV_Assert(int(dists.cols) >= knn); - - KNNSimpleResultSet resultSet(knn); - for (size_t i = 0; i < queries.rows; i++) { - resultSet.init(indices[i], dists[i]); - findNeighbors(resultSet, queries[i], params); - } - } - - IndexParams getParameters() const CV_OVERRIDE - { - return index_params_; - } - - /** - * Find set of nearest neighbors to vec. Their indices are stored inside - * the result object. - * - * Params: - * result = the result object in which the indices of the nearest-neighbors are stored - * vec = the vector for which to search the nearest neighbors - * maxCheck = the maximum number of restarts (in a best-bin-first manner) - */ - void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE - { - float epsError = 1+get_param(searchParams,"eps",0.0f); - - std::vector dists(dim_,0); - DistanceType distsq = computeInitialDistances(vec, dists); - searchLevel(result, vec, root_node_, distsq, dists, epsError); - } - -private: - - - /*--------------------- Internal Data Structures --------------------------*/ - struct Node - { - /** - * Indices of points in leaf node - */ - int left, right; - /** - * Dimension used for subdivision. - */ - int divfeat; - /** - * The values used for subdivision. - */ - DistanceType divlow, divhigh; - /** - * The child nodes. - */ - Node* child1, * child2; - }; - typedef Node* NodePtr; - - - struct Interval - { - DistanceType low, high; - }; - - typedef std::vector BoundingBox; - - typedef BranchStruct BranchSt; - typedef BranchSt* Branch; - - - - - void save_tree(FILE* stream, NodePtr tree) - { - save_value(stream, *tree); - if (tree->child1!=NULL) { - save_tree(stream, tree->child1); - } - if (tree->child2!=NULL) { - save_tree(stream, tree->child2); - } - } - - - void load_tree(FILE* stream, NodePtr& tree) - { - tree = pool_.allocate(); - load_value(stream, *tree); - if (tree->child1!=NULL) { - load_tree(stream, tree->child1); - } - if (tree->child2!=NULL) { - load_tree(stream, tree->child2); - } - } - - - void computeBoundingBox(BoundingBox& bbox) - { - bbox.resize(dim_); - for (size_t i=0; ibbox[i].high) bbox[i].high = (DistanceType)dataset_[k][i]; - } - } - } - - - /** - * Create a tree node that subdivides the list of vecs from vind[first] - * to vind[last]. The routine is called recursively on each sublist. - * Place a pointer to this new tree node in the location pTree. - * - * Params: pTree = the new node to create - * first = index of the first vector - * last = index of the last vector - */ - NodePtr divideTree(int left, int right, BoundingBox& bbox) - { - NodePtr node = pool_.allocate(); // allocate memory - - /* If too few exemplars remain, then make this a leaf node. */ - if ( (right-left) <= leaf_max_size_) { - node->child1 = node->child2 = NULL; /* Mark as leaf node. */ - node->left = left; - node->right = right; - - // compute bounding-box of leaf points - for (size_t i=0; idataset_[vind_[k]][i]) bbox[i].low=(DistanceType)dataset_[vind_[k]][i]; - if (bbox[i].highdivfeat = cutfeat; - - BoundingBox left_bbox(bbox); - left_bbox[cutfeat].high = cutval; - node->child1 = divideTree(left, left+idx, left_bbox); - - BoundingBox right_bbox(bbox); - right_bbox[cutfeat].low = cutval; - node->child2 = divideTree(left+idx, right, right_bbox); - - node->divlow = left_bbox[cutfeat].high; - node->divhigh = right_bbox[cutfeat].low; - - for (size_t i=0; imax_elem) max_elem = val; - } - } - - void middleSplit(int* ind, int count, int& index, int& cutfeat, DistanceType& cutval, const BoundingBox& bbox) - { - // find the largest span from the approximate bounding box - ElementType max_span = bbox[0].high-bbox[0].low; - cutfeat = 0; - cutval = (bbox[0].high+bbox[0].low)/2; - for (size_t i=1; imax_span) { - max_span = span; - cutfeat = i; - cutval = (bbox[i].high+bbox[i].low)/2; - } - } - - // compute exact span on the found dimension - ElementType min_elem, max_elem; - computeMinMax(ind, count, cutfeat, min_elem, max_elem); - cutval = (min_elem+max_elem)/2; - max_span = max_elem - min_elem; - - // check if a dimension of a largest span exists - size_t k = cutfeat; - for (size_t i=0; imax_span) { - computeMinMax(ind, count, i, min_elem, max_elem); - span = max_elem - min_elem; - if (span>max_span) { - max_span = span; - cutfeat = i; - cutval = (min_elem+max_elem)/2; - } - } - } - int lim1, lim2; - planeSplit(ind, count, cutfeat, cutval, lim1, lim2); - - if (lim1>count/2) index = lim1; - else if (lim2max_span) { - max_span = span; - } - } - DistanceType max_spread = -1; - cutfeat = 0; - for (size_t i=0; i(DistanceType)((1-EPS)*max_span)) { - ElementType min_elem, max_elem; - computeMinMax(ind, count, (int)i, min_elem, max_elem); - DistanceType spread = (DistanceType)(max_elem-min_elem); - if (spread>max_spread) { - cutfeat = (int)i; - max_spread = spread; - } - } - } - // split in the middle - DistanceType split_val = (bbox[cutfeat].low+bbox[cutfeat].high)/2; - ElementType min_elem, max_elem; - computeMinMax(ind, count, cutfeat, min_elem, max_elem); - - if (split_valmax_elem) cutval = (DistanceType)max_elem; - else cutval = split_val; - - int lim1, lim2; - planeSplit(ind, count, cutfeat, cutval, lim1, lim2); - - if (lim1>count/2) index = lim1; - else if (lim2cutval - */ - void planeSplit(int* ind, int count, int cutfeat, DistanceType cutval, int& lim1, int& lim2) - { - /* Move vector indices for left subtree to front of list. */ - int left = 0; - int right = count-1; - for (;; ) { - while (left<=right && dataset_[ind[left]][cutfeat]=cutval) --right; - if (left>right) break; - std::swap(ind[left], ind[right]); ++left; --right; - } - /* If either list is empty, it means that all remaining features - * are identical. Split in the middle to maintain a balanced tree. - */ - lim1 = left; - right = count-1; - for (;; ) { - while (left<=right && dataset_[ind[left]][cutfeat]<=cutval) ++left; - while (left<=right && dataset_[ind[right]][cutfeat]>cutval) --right; - if (left>right) break; - std::swap(ind[left], ind[right]); ++left; --right; - } - lim2 = left; - } - - DistanceType computeInitialDistances(const ElementType* vec, std::vector& dists) - { - DistanceType distsq = 0.0; - - for (size_t i = 0; i < dim_; ++i) { - if (vec[i] < root_bbox_[i].low) { - dists[i] = distance_.accum_dist(vec[i], root_bbox_[i].low, (int)i); - distsq += dists[i]; - } - if (vec[i] > root_bbox_[i].high) { - dists[i] = distance_.accum_dist(vec[i], root_bbox_[i].high, (int)i); - distsq += dists[i]; - } - } - - return distsq; - } - - /** - * Performs an exact search in the tree starting from a node. - */ - void searchLevel(ResultSet& result_set, const ElementType* vec, const NodePtr node, DistanceType mindistsq, - std::vector& dists, const float epsError) - { - /* If this is a leaf node, then do check and return. */ - if ((node->child1 == NULL)&&(node->child2 == NULL)) { - DistanceType worst_dist = result_set.worstDist(); - if (reorder_) { - for (int i=node->left; iright; ++i) { - DistanceType dist = distance_(vec, data_[i], dim_, worst_dist); - if (distleft; iright; ++i) { - DistanceType dist = distance_(vec, data_[vind_[i]], dim_, worst_dist); - if (distdivfeat; - ElementType val = vec[idx]; - DistanceType diff1 = val - node->divlow; - DistanceType diff2 = val - node->divhigh; - - NodePtr bestChild; - NodePtr otherChild; - DistanceType cut_dist; - if ((diff1+diff2)<0) { - bestChild = node->child1; - otherChild = node->child2; - cut_dist = distance_.accum_dist(val, node->divhigh, idx); - } - else { - bestChild = node->child2; - otherChild = node->child1; - cut_dist = distance_.accum_dist( val, node->divlow, idx); - } - - /* Call recursively to search next level down. */ - searchLevel(result_set, vec, bestChild, mindistsq, dists, epsError); - - DistanceType dst = dists[idx]; - mindistsq = mindistsq + cut_dist - dst; - dists[idx] = cut_dist; - if (mindistsq*epsError<=result_set.worstDist()) { - searchLevel(result_set, vec, otherChild, mindistsq, dists, epsError); - } - dists[idx] = dst; - } - -private: - - /** - * The dataset used by this index - */ - const Matrix dataset_; - - IndexParams index_params_; - - int leaf_max_size_; - bool reorder_; - - - /** - * Array of indices to vectors in the dataset. - */ - std::vector vind_; - - Matrix data_; - - size_t size_; - size_t dim_; - - /** - * Array of k-d trees used to find neighbours. - */ - NodePtr root_node_; - - BoundingBox root_bbox_; - - /** - * Pooled memory allocator. - * - * Using a pooled memory allocator is more efficient - * than allocating memory directly when there is a large - * number small of memory allocations. - */ - PooledAllocator pool_; - - Distance distance_; -}; // class KDTree - -} - -//! @endcond - -#endif //OPENCV_FLANN_KDTREE_SINGLE_INDEX_H_ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * 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 ``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 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 OPENCV_FLANN_KDTREE_SINGLE_INDEX_H_ +#define OPENCV_FLANN_KDTREE_SINGLE_INDEX_H_ + +//! @cond IGNORED + +#include +#include +#include + +#include "nn_index.h" +#include "matrix.h" +#include "result_set.h" +#include "heap.h" +#include "allocator.h" +#include "random.h" +#include "saving.h" + +namespace cvflann +{ + +struct KDTreeSingleIndexParams : public IndexParams +{ + KDTreeSingleIndexParams(int leaf_max_size = 10, bool reorder = true, int dim = -1) + { + (*this)["algorithm"] = FLANN_INDEX_KDTREE_SINGLE; + (*this)["leaf_max_size"] = leaf_max_size; + (*this)["reorder"] = reorder; + (*this)["dim"] = dim; + } +}; + + +/** + * Randomized kd-tree index + * + * Contains the k-d trees and other information for indexing a set of points + * for nearest-neighbor matching. + */ +template +class KDTreeSingleIndex : public NNIndex +{ +public: + typedef typename Distance::ElementType ElementType; + typedef typename Distance::ResultType DistanceType; + + + /** + * KDTree constructor + * + * Params: + * inputData = dataset with the input features + * params = parameters passed to the kdtree algorithm + */ + KDTreeSingleIndex(const Matrix& inputData, const IndexParams& params = KDTreeSingleIndexParams(), + Distance d = Distance() ) : + dataset_(inputData), index_params_(params), distance_(d) + { + size_ = dataset_.rows; + dim_ = dataset_.cols; + root_node_ = 0; + int dim_param = get_param(params,"dim",-1); + if (dim_param>0) dim_ = dim_param; + leaf_max_size_ = get_param(params,"leaf_max_size",10); + reorder_ = get_param(params,"reorder",true); + + // Create a permutable array of indices to the input vectors. + vind_.resize(size_); + for (size_t i = 0; i < size_; i++) { + vind_[i] = (int)i; + } + } + + KDTreeSingleIndex(const KDTreeSingleIndex&); + KDTreeSingleIndex& operator=(const KDTreeSingleIndex&); + + /** + * Standard destructor + */ + ~KDTreeSingleIndex() + { + if (reorder_) delete[] data_.data; + } + + /** + * Builds the index + */ + void buildIndex() CV_OVERRIDE + { + computeBoundingBox(root_bbox_); + root_node_ = divideTree(0, (int)size_, root_bbox_ ); // construct the tree + + if (reorder_) { + delete[] data_.data; + data_ = cvflann::Matrix(new ElementType[size_*dim_], size_, dim_); + for (size_t i=0; i& queries, Matrix& indices, Matrix& dists, int knn, const SearchParams& params) CV_OVERRIDE + { + CV_Assert(queries.cols == veclen()); + CV_Assert(indices.rows >= queries.rows); + CV_Assert(dists.rows >= queries.rows); + CV_Assert(int(indices.cols) >= knn); + CV_Assert(int(dists.cols) >= knn); + + KNNSimpleResultSet resultSet(knn); + for (size_t i = 0; i < queries.rows; i++) { + resultSet.init(indices[i], dists[i]); + findNeighbors(resultSet, queries[i], params); + } + } + + IndexParams getParameters() const CV_OVERRIDE + { + return index_params_; + } + + /** + * Find set of nearest neighbors to vec. Their indices are stored inside + * the result object. + * + * Params: + * result = the result object in which the indices of the nearest-neighbors are stored + * vec = the vector for which to search the nearest neighbors + * maxCheck = the maximum number of restarts (in a best-bin-first manner) + */ + void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE + { + float epsError = 1+get_param(searchParams,"eps",0.0f); + + std::vector dists(dim_,0); + DistanceType distsq = computeInitialDistances(vec, dists); + searchLevel(result, vec, root_node_, distsq, dists, epsError); + } + +private: + + + /*--------------------- Internal Data Structures --------------------------*/ + struct Node + { + /** + * Indices of points in leaf node + */ + int left, right; + /** + * Dimension used for subdivision. + */ + int divfeat; + /** + * The values used for subdivision. + */ + DistanceType divlow, divhigh; + /** + * The child nodes. + */ + Node* child1, * child2; + }; + typedef Node* NodePtr; + + + struct Interval + { + DistanceType low, high; + }; + + typedef std::vector BoundingBox; + + typedef BranchStruct BranchSt; + typedef BranchSt* Branch; + + + + + void save_tree(FILE* stream, NodePtr tree) + { + save_value(stream, *tree); + if (tree->child1!=NULL) { + save_tree(stream, tree->child1); + } + if (tree->child2!=NULL) { + save_tree(stream, tree->child2); + } + } + + + void load_tree(FILE* stream, NodePtr& tree) + { + tree = pool_.allocate(); + load_value(stream, *tree); + if (tree->child1!=NULL) { + load_tree(stream, tree->child1); + } + if (tree->child2!=NULL) { + load_tree(stream, tree->child2); + } + } + + + void computeBoundingBox(BoundingBox& bbox) + { + bbox.resize(dim_); + for (size_t i=0; ibbox[i].high) bbox[i].high = (DistanceType)dataset_[k][i]; + } + } + } + + + /** + * Create a tree node that subdivides the list of vecs from vind[first] + * to vind[last]. The routine is called recursively on each sublist. + * Place a pointer to this new tree node in the location pTree. + * + * Params: pTree = the new node to create + * first = index of the first vector + * last = index of the last vector + */ + NodePtr divideTree(int left, int right, BoundingBox& bbox) + { + NodePtr node = pool_.allocate(); // allocate memory + + /* If too few exemplars remain, then make this a leaf node. */ + if ( (right-left) <= leaf_max_size_) { + node->child1 = node->child2 = NULL; /* Mark as leaf node. */ + node->left = left; + node->right = right; + + // compute bounding-box of leaf points + for (size_t i=0; idataset_[vind_[k]][i]) bbox[i].low=(DistanceType)dataset_[vind_[k]][i]; + if (bbox[i].highdivfeat = cutfeat; + + BoundingBox left_bbox(bbox); + left_bbox[cutfeat].high = cutval; + node->child1 = divideTree(left, left+idx, left_bbox); + + BoundingBox right_bbox(bbox); + right_bbox[cutfeat].low = cutval; + node->child2 = divideTree(left+idx, right, right_bbox); + + node->divlow = left_bbox[cutfeat].high; + node->divhigh = right_bbox[cutfeat].low; + + for (size_t i=0; imax_elem) max_elem = val; + } + } + + void middleSplit(int* ind, int count, int& index, int& cutfeat, DistanceType& cutval, const BoundingBox& bbox) + { + // find the largest span from the approximate bounding box + ElementType max_span = bbox[0].high-bbox[0].low; + cutfeat = 0; + cutval = (bbox[0].high+bbox[0].low)/2; + for (size_t i=1; imax_span) { + max_span = span; + cutfeat = i; + cutval = (bbox[i].high+bbox[i].low)/2; + } + } + + // compute exact span on the found dimension + ElementType min_elem, max_elem; + computeMinMax(ind, count, cutfeat, min_elem, max_elem); + cutval = (min_elem+max_elem)/2; + max_span = max_elem - min_elem; + + // check if a dimension of a largest span exists + size_t k = cutfeat; + for (size_t i=0; imax_span) { + computeMinMax(ind, count, i, min_elem, max_elem); + span = max_elem - min_elem; + if (span>max_span) { + max_span = span; + cutfeat = i; + cutval = (min_elem+max_elem)/2; + } + } + } + int lim1, lim2; + planeSplit(ind, count, cutfeat, cutval, lim1, lim2); + + if (lim1>count/2) index = lim1; + else if (lim2max_span) { + max_span = span; + } + } + DistanceType max_spread = -1; + cutfeat = 0; + for (size_t i=0; i(DistanceType)((1-EPS)*max_span)) { + ElementType min_elem, max_elem; + computeMinMax(ind, count, (int)i, min_elem, max_elem); + DistanceType spread = (DistanceType)(max_elem-min_elem); + if (spread>max_spread) { + cutfeat = (int)i; + max_spread = spread; + } + } + } + // split in the middle + DistanceType split_val = (bbox[cutfeat].low+bbox[cutfeat].high)/2; + ElementType min_elem, max_elem; + computeMinMax(ind, count, cutfeat, min_elem, max_elem); + + if (split_valmax_elem) cutval = (DistanceType)max_elem; + else cutval = split_val; + + int lim1, lim2; + planeSplit(ind, count, cutfeat, cutval, lim1, lim2); + + if (lim1>count/2) index = lim1; + else if (lim2cutval + */ + void planeSplit(int* ind, int count, int cutfeat, DistanceType cutval, int& lim1, int& lim2) + { + /* Move vector indices for left subtree to front of list. */ + int left = 0; + int right = count-1; + for (;; ) { + while (left<=right && dataset_[ind[left]][cutfeat]=cutval) --right; + if (left>right) break; + std::swap(ind[left], ind[right]); ++left; --right; + } + /* If either list is empty, it means that all remaining features + * are identical. Split in the middle to maintain a balanced tree. + */ + lim1 = left; + right = count-1; + for (;; ) { + while (left<=right && dataset_[ind[left]][cutfeat]<=cutval) ++left; + while (left<=right && dataset_[ind[right]][cutfeat]>cutval) --right; + if (left>right) break; + std::swap(ind[left], ind[right]); ++left; --right; + } + lim2 = left; + } + + DistanceType computeInitialDistances(const ElementType* vec, std::vector& dists) + { + DistanceType distsq = 0.0; + + for (size_t i = 0; i < dim_; ++i) { + if (vec[i] < root_bbox_[i].low) { + dists[i] = distance_.accum_dist(vec[i], root_bbox_[i].low, (int)i); + distsq += dists[i]; + } + if (vec[i] > root_bbox_[i].high) { + dists[i] = distance_.accum_dist(vec[i], root_bbox_[i].high, (int)i); + distsq += dists[i]; + } + } + + return distsq; + } + + /** + * Performs an exact search in the tree starting from a node. + */ + void searchLevel(ResultSet& result_set, const ElementType* vec, const NodePtr node, DistanceType mindistsq, + std::vector& dists, const float epsError) + { + /* If this is a leaf node, then do check and return. */ + if ((node->child1 == NULL)&&(node->child2 == NULL)) { + DistanceType worst_dist = result_set.worstDist(); + if (reorder_) { + for (int i=node->left; iright; ++i) { + DistanceType dist = distance_(vec, data_[i], dim_, worst_dist); + if (distleft; iright; ++i) { + DistanceType dist = distance_(vec, data_[vind_[i]], dim_, worst_dist); + if (distdivfeat; + ElementType val = vec[idx]; + DistanceType diff1 = val - node->divlow; + DistanceType diff2 = val - node->divhigh; + + NodePtr bestChild; + NodePtr otherChild; + DistanceType cut_dist; + if ((diff1+diff2)<0) { + bestChild = node->child1; + otherChild = node->child2; + cut_dist = distance_.accum_dist(val, node->divhigh, idx); + } + else { + bestChild = node->child2; + otherChild = node->child1; + cut_dist = distance_.accum_dist( val, node->divlow, idx); + } + + /* Call recursively to search next level down. */ + searchLevel(result_set, vec, bestChild, mindistsq, dists, epsError); + + DistanceType dst = dists[idx]; + mindistsq = mindistsq + cut_dist - dst; + dists[idx] = cut_dist; + if (mindistsq*epsError<=result_set.worstDist()) { + searchLevel(result_set, vec, otherChild, mindistsq, dists, epsError); + } + dists[idx] = dst; + } + +private: + + /** + * The dataset used by this index + */ + const Matrix dataset_; + + IndexParams index_params_; + + int leaf_max_size_; + bool reorder_; + + + /** + * Array of indices to vectors in the dataset. + */ + std::vector vind_; + + Matrix data_; + + size_t size_; + size_t dim_; + + /** + * Array of k-d trees used to find neighbours. + */ + NodePtr root_node_; + + BoundingBox root_bbox_; + + /** + * Pooled memory allocator. + * + * Using a pooled memory allocator is more efficient + * than allocating memory directly when there is a large + * number small of memory allocations. + */ + PooledAllocator pool_; + + Distance distance_; +}; // class KDTree + +} + +//! @endcond + +#endif //OPENCV_FLANN_KDTREE_SINGLE_INDEX_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/kmeans_index.h b/3rdParty/opencv-4.11.0/opencv2/flann/kmeans_index.h index fd7fe2bd39..77aa7c2564 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/kmeans_index.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/kmeans_index.h @@ -1,1819 +1,1819 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * 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 ``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 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 OPENCV_FLANN_KMEANS_INDEX_H_ -#define OPENCV_FLANN_KMEANS_INDEX_H_ - -//! @cond IGNORED - -#include -#include -#include -#include - -#include "general.h" -#include "nn_index.h" -#include "dist.h" -#include "matrix.h" -#include "result_set.h" -#include "heap.h" -#include "allocator.h" -#include "random.h" -#include "saving.h" -#include "logger.h" - -#define BITS_PER_CHAR 8 -#define BITS_PER_BASE 2 // for DNA/RNA sequences -#define BASE_PER_CHAR (BITS_PER_CHAR/BITS_PER_BASE) -#define HISTOS_PER_BASE (1< -class KMeansIndex : public NNIndex -{ -public: - typedef typename Distance::ElementType ElementType; - typedef typename Distance::ResultType DistanceType; - typedef typename Distance::CentersType CentersType; - - typedef typename Distance::is_kdtree_distance is_kdtree_distance; - typedef typename Distance::is_vector_space_distance is_vector_space_distance; - - - - typedef void (KMeansIndex::* centersAlgFunction)(int, int*, int, int*, int&); - - /** - * The function used for choosing the cluster centers. - */ - centersAlgFunction chooseCenters; - - - - /** - * Chooses the initial centers in the k-means clustering in a random manner. - * - * Params: - * k = number of centers - * vecs = the dataset of points - * indices = indices in the dataset - * indices_length = length of indices vector - * - */ - void chooseCentersRandom(int k, int* indices, int indices_length, int* centers, int& centers_length) - { - UniqueRandom r(indices_length); - - int index; - for (index=0; index=0 && rnd < n); - - centers[0] = indices[rnd]; - - int index; - for (index=1; indexbest_val) { - best_val = dist; - best_index = j; - } - } - if (best_index!=-1) { - centers[index] = indices[best_index]; - } - else { - break; - } - } - centers_length = index; - } - - - /** - * Chooses the initial centers in the k-means using the algorithm - * proposed in the KMeans++ paper: - * Arthur, David; Vassilvitskii, Sergei - k-means++: The Advantages of Careful Seeding - * - * Implementation of this function was converted from the one provided in Arthur's code. - * - * Params: - * k = number of centers - * vecs = the dataset of points - * indices = indices in the dataset - * Returns: - */ - void chooseCentersKMeanspp(int k, int* indices, int indices_length, int* centers, int& centers_length) - { - int n = indices_length; - - double currentPot = 0; - DistanceType* closestDistSq = new DistanceType[n]; - - // Choose one random center and set the closestDistSq values - int index = rand_int(n); - CV_DbgAssert(index >=0 && index < n); - centers[0] = indices[index]; - - for (int i = 0; i < n; i++) { - closestDistSq[i] = distance_(dataset_[indices[i]], dataset_[indices[index]], dataset_.cols); - closestDistSq[i] = ensureSquareDistance( closestDistSq[i] ); - currentPot += closestDistSq[i]; - } - - - const int numLocalTries = 1; - - // Choose each center - int centerCount; - for (centerCount = 1; centerCount < k; centerCount++) { - - // Repeat several trials - double bestNewPot = -1; - int bestNewIndex = -1; - for (int localTrial = 0; localTrial < numLocalTries; localTrial++) { - - // Choose our center - have to be slightly careful to return a valid answer even accounting - // for possible rounding errors - double randVal = rand_double(currentPot); - for (index = 0; index < n-1; index++) { - if (randVal <= closestDistSq[index]) break; - else randVal -= closestDistSq[index]; - } - - // Compute the new potential - double newPot = 0; - for (int i = 0; i < n; i++) { - DistanceType dist = distance_(dataset_[indices[i]], dataset_[indices[index]], dataset_.cols); - newPot += std::min( ensureSquareDistance(dist), closestDistSq[i] ); - } - - // Store the best result - if ((bestNewPot < 0)||(newPot < bestNewPot)) { - bestNewPot = newPot; - bestNewIndex = index; - } - } - - // Add the appropriate center - centers[centerCount] = indices[bestNewIndex]; - currentPot = bestNewPot; - for (int i = 0; i < n; i++) { - DistanceType dist = distance_(dataset_[indices[i]], dataset_[indices[bestNewIndex]], dataset_.cols); - closestDistSq[i] = std::min( ensureSquareDistance(dist), closestDistSq[i] ); - } - } - - centers_length = centerCount; - - delete[] closestDistSq; - } - - - -public: - - flann_algorithm_t getType() const CV_OVERRIDE - { - return FLANN_INDEX_KMEANS; - } - - template - class KMeansDistanceComputer : public cv::ParallelLoopBody - { - public: - KMeansDistanceComputer(Distance _distance, const Matrix& _dataset, - const int _branching, const int* _indices, const CentersContainerType& _dcenters, - const size_t _veclen, std::vector &_new_centroids, - std::vector &_sq_dists) - : distance(_distance) - , dataset(_dataset) - , branching(_branching) - , indices(_indices) - , dcenters(_dcenters) - , veclen(_veclen) - , new_centroids(_new_centroids) - , sq_dists(_sq_dists) - { - } - - void operator()(const cv::Range& range) const CV_OVERRIDE - { - const int begin = range.start; - const int end = range.end; - - for( int i = begin; inew_sq_dist) { - new_centroid = j; - sq_dist = new_sq_dist; - } - } - sq_dists[i] = sq_dist; - new_centroids[i] = new_centroid; - } - } - - private: - Distance distance; - const Matrix& dataset; - const int branching; - const int* indices; - const CentersContainerType& dcenters; - const size_t veclen; - std::vector &new_centroids; - std::vector &sq_dists; - KMeansDistanceComputer& operator=( const KMeansDistanceComputer & ) { return *this; } - }; - - /** - * Index constructor - * - * Params: - * inputData = dataset with the input features - * params = parameters passed to the hierarchical k-means algorithm - */ - KMeansIndex(const Matrix& inputData, const IndexParams& params = KMeansIndexParams(), - Distance d = Distance()) - : dataset_(inputData), index_params_(params), root_(NULL), indices_(NULL), distance_(d) - { - memoryCounter_ = 0; - - size_ = dataset_.rows; - veclen_ = dataset_.cols; - - branching_ = get_param(params,"branching",32); - trees_ = get_param(params,"trees",1); - iterations_ = get_param(params,"iterations",11); - if (iterations_<0) { - iterations_ = (std::numeric_limits::max)(); - } - centers_init_ = get_param(params,"centers_init",FLANN_CENTERS_RANDOM); - - if (centers_init_==FLANN_CENTERS_RANDOM) { - chooseCenters = &KMeansIndex::chooseCentersRandom; - } - else if (centers_init_==FLANN_CENTERS_GONZALES) { - chooseCenters = &KMeansIndex::chooseCentersGonzales; - } - else if (centers_init_==FLANN_CENTERS_KMEANSPP) { - chooseCenters = &KMeansIndex::chooseCentersKMeanspp; - } - else { - FLANN_THROW(cv::Error::StsBadArg, "Unknown algorithm for choosing initial centers."); - } - cb_index_ = 0.4f; - - root_ = new KMeansNodePtr[trees_]; - indices_ = new int*[trees_]; - - for (int i=0; i(); - std::memset(root_[i], 0, sizeof(KMeansNode)); - - Distance* dummy = NULL; - computeNodeStatistics(root_[i], indices_[i], (unsigned int)size_, dummy); - - computeClustering(root_[i], indices_[i], (int)size_, branching_,0); - } - } - - - void saveIndex(FILE* stream) CV_OVERRIDE - { - save_value(stream, branching_); - save_value(stream, iterations_); - save_value(stream, memoryCounter_); - save_value(stream, cb_index_); - save_value(stream, trees_); - for (int i=0; i& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE - { - - const int maxChecks = get_param(searchParams,"checks",32); - - if (maxChecks==FLANN_CHECKS_UNLIMITED) { - findExactNN(root_[0], result, vec); - } - else { - // Priority queue storing intermediate branches in the best-bin-first search - const cv::Ptr>& heap = Heap::getPooledInstance(cv::utils::getThreadID(), (int)size_); - - int checks = 0; - for (int i=0; i= maxChecks) && result.full()) - break; - } - - BranchSt branch; - while (heap->popMin(branch) && (checks& centers) - { - int numClusters = centers.rows; - if (numClusters<1) { - FLANN_THROW(cv::Error::StsBadArg, "Number of clusters must be at least 1"); - } - - DistanceType variance; - KMeansNodePtr* clusters = new KMeansNodePtr[numClusters]; - - int clusterCount = getMinVarianceClusters(root_[0], clusters, numClusters, variance); - - Logger::info("Clusters requested: %d, returning %d\n",numClusters, clusterCount); - - for (int i=0; ipivot; - for (size_t j=0; j BranchSt; - - - - - void save_tree(FILE* stream, KMeansNodePtr node, int num) - { - save_value(stream, *node); - save_value(stream, *(node->pivot), (int)veclen_); - if (node->childs==NULL) { - int indices_offset = (int)(node->indices - indices_[num]); - save_value(stream, indices_offset); - } - else { - for(int i=0; ichilds[i], num); - } - } - } - - - void load_tree(FILE* stream, KMeansNodePtr& node, int num) - { - node = pool_.allocate(); - load_value(stream, *node); - node->pivot = new CentersType[veclen_]; - load_value(stream, *(node->pivot), (int)veclen_); - if (node->childs==NULL) { - int indices_offset; - load_value(stream, indices_offset); - node->indices = indices_[num] + indices_offset; - } - else { - node->childs = pool_.allocate(branching_); - for(int i=0; ichilds[i], num); - } - } - } - - - /** - * Helper function - */ - void free_centers(KMeansNodePtr node) - { - delete[] node->pivot; - if (node->childs!=NULL) { - for (int k=0; kchilds[k]); - } - } - } - - void free_centers() - { - if (root_ != NULL) { - for(int i=0; i(), veclen_); - } - float length = static_cast(indices_length); - for (size_t j=0; j( mean[j] / static_cast(indices_length) ); - } - variance /= static_cast( length ); - variance -= distance_(mean, ZeroIterator(), veclen_); - - DistanceType radius = 0; - for (unsigned int i=0; iradius) { - radius = tmp; - } - } - - node->variance = variance; - node->radius = radius; - node->pivot = mean; - } - - - void computeBitfieldNodeStatistics(KMeansNodePtr node, int* indices, - unsigned int indices_length) - { - const unsigned int accumulator_veclen = static_cast( - veclen_*sizeof(CentersType)*BITS_PER_CHAR); - - unsigned long long variance = 0ull; - CentersType* mean = new CentersType[veclen_]; - memoryCounter_ += int(veclen_*sizeof(CentersType)); - unsigned int* mean_accumulator = new unsigned int[accumulator_veclen]; - - memset(mean_accumulator, 0, sizeof(unsigned int)*accumulator_veclen); - - for (unsigned int i=0; i( ensureSquareDistance( - distance_(dataset_[indices[i]], ZeroIterator(), veclen_))); - unsigned char* vec = (unsigned char*)dataset_[indices[i]]; - for (size_t k=0, l=0; k>1) & 0x01; - mean_accumulator[k+2] += (vec[l]>>2) & 0x01; - mean_accumulator[k+3] += (vec[l]>>3) & 0x01; - mean_accumulator[k+4] += (vec[l]>>4) & 0x01; - mean_accumulator[k+5] += (vec[l]>>5) & 0x01; - mean_accumulator[k+6] += (vec[l]>>6) & 0x01; - mean_accumulator[k+7] += (vec[l]>>7) & 0x01; - } - } - double cnt = static_cast(indices_length); - unsigned char* char_mean = (unsigned char*)mean; - for (size_t k=0, l=0; k( - (((int)(0.5 + (double)(mean_accumulator[k]) / cnt))) - | (((int)(0.5 + (double)(mean_accumulator[k+1]) / cnt))<<1) - | (((int)(0.5 + (double)(mean_accumulator[k+2]) / cnt))<<2) - | (((int)(0.5 + (double)(mean_accumulator[k+3]) / cnt))<<3) - | (((int)(0.5 + (double)(mean_accumulator[k+4]) / cnt))<<4) - | (((int)(0.5 + (double)(mean_accumulator[k+5]) / cnt))<<5) - | (((int)(0.5 + (double)(mean_accumulator[k+6]) / cnt))<<6) - | (((int)(0.5 + (double)(mean_accumulator[k+7]) / cnt))<<7)); - } - variance = static_cast( - 0.5 + static_cast(variance) / static_cast(indices_length)); - variance -= static_cast( - ensureSquareDistance( - distance_(mean, ZeroIterator(), veclen_))); - - DistanceType radius = 0; - for (unsigned int i=0; iradius) { - radius = tmp; - } - } - - node->variance = static_cast(variance); - node->radius = radius; - node->pivot = mean; - - delete[] mean_accumulator; - } - - - void computeDnaNodeStatistics(KMeansNodePtr node, int* indices, - unsigned int indices_length) - { - const unsigned int histos_veclen = static_cast( - veclen_*sizeof(CentersType)*(HISTOS_PER_BASE*BASE_PER_CHAR)); - - unsigned long long variance = 0ull; - unsigned int* histograms = new unsigned int[histos_veclen]; - memset(histograms, 0, sizeof(unsigned int)*histos_veclen); - - for (unsigned int i=0; i( ensureSquareDistance( - distance_(dataset_[indices[i]], ZeroIterator(), veclen_))); - - unsigned char* vec = (unsigned char*)dataset_[indices[i]]; - for (size_t k=0, l=0; k>2) & 0x03)]++; - histograms[k + 8 + ((vec[l]>>4) & 0x03)]++; - histograms[k +12 + ((vec[l]>>6) & 0x03)]++; - } - } - - CentersType* mean = new CentersType[veclen_]; - memoryCounter_ += int(veclen_*sizeof(CentersType)); - unsigned char* char_mean = (unsigned char*)mean; - unsigned int* h = histograms; - for (size_t k=0, l=0; k h[k+1] ? h[k+2] > h[k+3] ? h[k] > h[k+2] ? 0x00 : 0x10 - : h[k] > h[k+3] ? 0x00 : 0x11 - : h[k+2] > h[k+3] ? h[k+1] > h[k+2] ? 0x01 : 0x10 - : h[k+1] > h[k+3] ? 0x01 : 0x11) - | (h[k+4]>h[k+5] ? h[k+6] > h[k+7] ? h[k+4] > h[k+6] ? 0x00 : 0x1000 - : h[k+4] > h[k+7] ? 0x00 : 0x1100 - : h[k+6] > h[k+7] ? h[k+5] > h[k+6] ? 0x0100 : 0x1000 - : h[k+5] > h[k+7] ? 0x0100 : 0x1100) - | (h[k+8]>h[k+9] ? h[k+10]>h[k+11] ? h[k+8] >h[k+10] ? 0x00 : 0x100000 - : h[k+8] >h[k+11] ? 0x00 : 0x110000 - : h[k+10]>h[k+11] ? h[k+9] >h[k+10] ? 0x010000 : 0x100000 - : h[k+9] >h[k+11] ? 0x010000 : 0x110000) - | (h[k+12]>h[k+13] ? h[k+14]>h[k+15] ? h[k+12] >h[k+14] ? 0x00 : 0x10000000 - : h[k+12] >h[k+15] ? 0x00 : 0x11000000 - : h[k+14]>h[k+15] ? h[k+13] >h[k+14] ? 0x01000000 : 0x10000000 - : h[k+13] >h[k+15] ? 0x01000000 : 0x11000000); - } - variance = static_cast( - 0.5 + static_cast(variance) / static_cast(indices_length)); - variance -= static_cast( - ensureSquareDistance( - distance_(mean, ZeroIterator(), veclen_))); - - DistanceType radius = 0; - for (unsigned int i=0; iradius) { - radius = tmp; - } - } - - node->variance = static_cast(variance); - node->radius = radius; - node->pivot = mean; - - delete[] histograms; - } - - - template - void computeNodeStatistics(KMeansNodePtr node, int* indices, - unsigned int indices_length, - const DistType* identifier) - { - (void)identifier; - computeNodeStatistics(node, indices, indices_length); - } - - void computeNodeStatistics(KMeansNodePtr node, int* indices, - unsigned int indices_length, - const cvflann::HammingLUT* identifier) - { - (void)identifier; - computeBitfieldNodeStatistics(node, indices, indices_length); - } - - void computeNodeStatistics(KMeansNodePtr node, int* indices, - unsigned int indices_length, - const cvflann::Hamming* identifier) - { - (void)identifier; - computeBitfieldNodeStatistics(node, indices, indices_length); - } - - void computeNodeStatistics(KMeansNodePtr node, int* indices, - unsigned int indices_length, - const cvflann::Hamming2* identifier) - { - (void)identifier; - computeBitfieldNodeStatistics(node, indices, indices_length); - } - - void computeNodeStatistics(KMeansNodePtr node, int* indices, - unsigned int indices_length, - const cvflann::DNAmmingLUT* identifier) - { - (void)identifier; - computeDnaNodeStatistics(node, indices, indices_length); - } - - void computeNodeStatistics(KMeansNodePtr node, int* indices, - unsigned int indices_length, - const cvflann::DNAmming2* identifier) - { - (void)identifier; - computeDnaNodeStatistics(node, indices, indices_length); - } - - - void refineClustering(int* indices, int indices_length, int branching, CentersType** centers, - std::vector& radiuses, int* belongs_to, int* count) - { - cv::AutoBuffer dcenters_buf(branching*veclen_); - Matrix dcenters(dcenters_buf.data(), branching, veclen_); - - bool converged = false; - int iteration = 0; - while (!converged && iteration new_centroids(indices_length); - std::vector sq_dists(indices_length); - - // reassign points to clusters - KMeansDistanceComputer > invoker( - distance_, dataset_, branching, indices, dcenters, veclen_, new_centroids, sq_dists); - parallel_for_(cv::Range(0, (int)indices_length), invoker); - - for (int i=0; i < (int)indices_length; ++i) { - DistanceType sq_dist(sq_dists[i]); - int new_centroid(new_centroids[i]); - if (sq_dist > radiuses[new_centroid]) { - radiuses[new_centroid] = sq_dist; - } - if (new_centroid != belongs_to[i]) { - count[belongs_to[i]]--; - count[new_centroid]++; - belongs_to[i] = new_centroid; - converged = false; - } - } - - for (int i=0; i& radiuses, int* belongs_to, int* count) - { - for (int i=0; i( - veclen_*sizeof(ElementType)*BITS_PER_CHAR); - cv::AutoBuffer dcenters_buf(branching*accumulator_veclen); - Matrix dcenters(dcenters_buf.data(), branching, accumulator_veclen); - - bool converged = false; - int iteration = 0; - while (!converged && iteration>1) & 0x01; - dcenter[k+2] += (vec[l]>>2) & 0x01; - dcenter[k+3] += (vec[l]>>3) & 0x01; - dcenter[k+4] += (vec[l]>>4) & 0x01; - dcenter[k+5] += (vec[l]>>5) & 0x01; - dcenter[k+6] += (vec[l]>>6) & 0x01; - dcenter[k+7] += (vec[l]>>7) & 0x01; - } - } - for (int i=0; i(count[i]); - unsigned int* dcenter = dcenters[i]; - unsigned char* charCenter = (unsigned char*)centers[i]; - for (size_t k=0, l=0; k( - (((int)(0.5 + (double)(dcenter[k]) / cnt))) - | (((int)(0.5 + (double)(dcenter[k+1]) / cnt))<<1) - | (((int)(0.5 + (double)(dcenter[k+2]) / cnt))<<2) - | (((int)(0.5 + (double)(dcenter[k+3]) / cnt))<<3) - | (((int)(0.5 + (double)(dcenter[k+4]) / cnt))<<4) - | (((int)(0.5 + (double)(dcenter[k+5]) / cnt))<<5) - | (((int)(0.5 + (double)(dcenter[k+6]) / cnt))<<6) - | (((int)(0.5 + (double)(dcenter[k+7]) / cnt))<<7)); - } - } - - std::vector new_centroids(indices_length); - std::vector dists(indices_length); - - // reassign points to clusters - KMeansDistanceComputer invoker( - distance_, dataset_, branching, indices, centers, veclen_, new_centroids, dists); - parallel_for_(cv::Range(0, (int)indices_length), invoker); - - for (int i=0; i < indices_length; ++i) { - DistanceType dist(dists[i]); - int new_centroid(new_centroids[i]); - if (dist > radiuses[new_centroid]) { - radiuses[new_centroid] = dist; - } - if (new_centroid != belongs_to[i]) { - count[belongs_to[i]]--; - count[new_centroid]++; - belongs_to[i] = new_centroid; - converged = false; - } - } - - for (int i=0; i& radiuses, int* belongs_to, int* count) - { - for (int i=0; i( - veclen_*sizeof(CentersType)*(HISTOS_PER_BASE*BASE_PER_CHAR)); - cv::AutoBuffer histos_buf(branching*histos_veclen); - Matrix histos(histos_buf.data(), branching, histos_veclen); - - bool converged = false; - int iteration = 0; - while (!converged && iteration>2) & 0x03)]++; - h[k + 8 + ((vec[l]>>4) & 0x03)]++; - h[k +12 + ((vec[l]>>6) & 0x03)]++; - } - } - for (int i=0; i h[k+1] ? h[k+2] > h[k+3] ? h[k] > h[k+2] ? 0x00 : 0x10 - : h[k] > h[k+3] ? 0x00 : 0x11 - : h[k+2] > h[k+3] ? h[k+1] > h[k+2] ? 0x01 : 0x10 - : h[k+1] > h[k+3] ? 0x01 : 0x11) - | (h[k+4]>h[k+5] ? h[k+6] > h[k+7] ? h[k+4] > h[k+6] ? 0x00 : 0x1000 - : h[k+4] > h[k+7] ? 0x00 : 0x1100 - : h[k+6] > h[k+7] ? h[k+5] > h[k+6] ? 0x0100 : 0x1000 - : h[k+5] > h[k+7] ? 0x0100 : 0x1100) - | (h[k+8]>h[k+9] ? h[k+10]>h[k+11] ? h[k+8] >h[k+10] ? 0x00 : 0x100000 - : h[k+8] >h[k+11] ? 0x00 : 0x110000 - : h[k+10]>h[k+11] ? h[k+9] >h[k+10] ? 0x010000 : 0x100000 - : h[k+9] >h[k+11] ? 0x010000 : 0x110000) - | (h[k+12]>h[k+13] ? h[k+14]>h[k+15] ? h[k+12] >h[k+14] ? 0x00 : 0x10000000 - : h[k+12] >h[k+15] ? 0x00 : 0x11000000 - : h[k+14]>h[k+15] ? h[k+13] >h[k+14] ? 0x01000000 : 0x10000000 - : h[k+13] >h[k+15] ? 0x01000000 : 0x11000000); - } - } - - std::vector new_centroids(indices_length); - std::vector dists(indices_length); - - // reassign points to clusters - KMeansDistanceComputer invoker( - distance_, dataset_, branching, indices, centers, veclen_, new_centroids, dists); - parallel_for_(cv::Range(0, (int)indices_length), invoker); - - for (int i=0; i < indices_length; ++i) { - DistanceType dist(dists[i]); - int new_centroid(new_centroids[i]); - if (dist > radiuses[new_centroid]) { - radiuses[new_centroid] = dist; - } - if (new_centroid != belongs_to[i]) { - count[belongs_to[i]]--; - count[new_centroid]++; - belongs_to[i] = new_centroid; - converged = false; - } - } - - for (int i=0; i& radiuses, int* belongs_to, int* count) - { - // compute kmeans clustering for each of the resulting clusters - node->childs = pool_.allocate(branching); - int start = 0; - int end = start; - for (int c=0; c(), veclen_); - variance += d; - mean_radius += static_cast( sqrt(d) ); - std::swap(indices[i],indices[end]); - std::swap(belongs_to[i],belongs_to[end]); - end++; - } - } - variance /= s; - mean_radius /= s; - variance -= distance_(centers[c], ZeroIterator(), veclen_); - - node->childs[c] = pool_.allocate(); - std::memset(node->childs[c], 0, sizeof(KMeansNode)); - node->childs[c]->radius = radiuses[c]; - node->childs[c]->pivot = centers[c]; - node->childs[c]->variance = variance; - node->childs[c]->mean_radius = mean_radius; - computeClustering(node->childs[c],indices+start, end-start, branching, level+1); - start=end; - } - } - - - void computeAnyBitfieldSubClustering(KMeansNodePtr node, int* indices, int indices_length, - int branching, int level, CentersType** centers, - std::vector& radiuses, int* belongs_to, int* count) - { - // compute kmeans clustering for each of the resulting clusters - node->childs = pool_.allocate(branching); - int start = 0; - int end = start; - for (int c=0; c(), veclen_); - variance += static_cast( ensureSquareDistance(d) ); - mean_radius += ensureSimpleDistance(d); - std::swap(indices[i],indices[end]); - std::swap(belongs_to[i],belongs_to[end]); - end++; - } - } - mean_radius = static_cast( - 0.5f + static_cast(mean_radius) / static_cast(s)); - variance = static_cast( - 0.5 + static_cast(variance) / static_cast(s)); - variance -= static_cast( - ensureSquareDistance( - distance_(centers[c], ZeroIterator(), veclen_))); - - node->childs[c] = pool_.allocate(); - std::memset(node->childs[c], 0, sizeof(KMeansNode)); - node->childs[c]->radius = radiuses[c]; - node->childs[c]->pivot = centers[c]; - node->childs[c]->variance = static_cast(variance); - node->childs[c]->mean_radius = mean_radius; - computeClustering(node->childs[c],indices+start, end-start, branching, level+1); - start=end; - } - } - - - template - void refineAndSplitClustering( - KMeansNodePtr node, int* indices, int indices_length, int branching, - int level, CentersType** centers, std::vector& radiuses, - int* belongs_to, int* count, const DistType* identifier) - { - (void)identifier; - refineClustering(indices, indices_length, branching, centers, radiuses, belongs_to, count); - - computeSubClustering(node, indices, indices_length, branching, - level, centers, radiuses, belongs_to, count); - } - - - /** - * The methods responsible with doing the recursive hierarchical clustering on - * binary vectors. - * As some might have heard that KMeans on binary data doesn't make sense, - * it's worth a little explanation why it actually fairly works. As - * with the Hierarchical Clustering algortihm, we seed several centers for the - * current node by picking some of its points. Then in a first pass each point - * of the node is then related to its closest center. Now let's have a look at - * the 5 central dimensions of the 9 following points: - * - * xxxxxx11100xxxxx (1) - * xxxxxx11010xxxxx (2) - * xxxxxx11001xxxxx (3) - * xxxxxx10110xxxxx (4) - * xxxxxx10101xxxxx (5) - * xxxxxx10011xxxxx (6) - * xxxxxx01110xxxxx (7) - * xxxxxx01101xxxxx (8) - * xxxxxx01011xxxxx (9) - * sum _____ - * of 1: 66555 - * - * Even if the barycenter notion doesn't apply, we can set a center - * xxxxxx11111xxxxx that will better fit the five dimensions we are focusing - * on for these points. - * - * Note that convergence isn't ensured anymore. In practice, using Gonzales - * as seeding algorithm should be fine for getting convergence ("iterations" - * value can be set to -1). But with KMeans++ seeding you should definitely - * set a maximum number of iterations (but make it higher than the "iterations" - * default value of 11). - * - * Params: - * node = the node to cluster - * indices = indices of the points belonging to the current node - * indices_length = number of points in the current node - * branching = the branching factor to use in the clustering - * level = 0 for the root node, it increases with the subdivision levels - * centers = clusters centers to compute - * radiuses = radiuses of clusters - * belongs_to = LookUp Table returning, for a given indice id, the center id it belongs to - * count = array storing the number of indices for a given center id - * identifier = dummy pointer on an instance of Distance (use to branch correctly among templates) - */ - void refineAndSplitClustering( - KMeansNodePtr node, int* indices, int indices_length, int branching, - int level, CentersType** centers, std::vector& radiuses, - int* belongs_to, int* count, const cvflann::HammingLUT* identifier) - { - (void)identifier; - refineBitfieldClustering( - indices, indices_length, branching, centers, radiuses, belongs_to, count); - - computeAnyBitfieldSubClustering(node, indices, indices_length, branching, - level, centers, radiuses, belongs_to, count); - } - - - void refineAndSplitClustering( - KMeansNodePtr node, int* indices, int indices_length, int branching, - int level, CentersType** centers, std::vector& radiuses, - int* belongs_to, int* count, const cvflann::Hamming* identifier) - { - (void)identifier; - refineBitfieldClustering( - indices, indices_length, branching, centers, radiuses, belongs_to, count); - - computeAnyBitfieldSubClustering(node, indices, indices_length, branching, - level, centers, radiuses, belongs_to, count); - } - - - void refineAndSplitClustering( - KMeansNodePtr node, int* indices, int indices_length, int branching, - int level, CentersType** centers, std::vector& radiuses, - int* belongs_to, int* count, const cvflann::Hamming2* identifier) - { - (void)identifier; - refineBitfieldClustering( - indices, indices_length, branching, centers, radiuses, belongs_to, count); - - computeAnyBitfieldSubClustering(node, indices, indices_length, branching, - level, centers, radiuses, belongs_to, count); - } - - - void refineAndSplitClustering( - KMeansNodePtr node, int* indices, int indices_length, int branching, - int level, CentersType** centers, std::vector& radiuses, - int* belongs_to, int* count, const cvflann::DNAmmingLUT* identifier) - { - (void)identifier; - refineDnaClustering( - indices, indices_length, branching, centers, radiuses, belongs_to, count); - - computeAnyBitfieldSubClustering(node, indices, indices_length, branching, - level, centers, radiuses, belongs_to, count); - } - - - void refineAndSplitClustering( - KMeansNodePtr node, int* indices, int indices_length, int branching, - int level, CentersType** centers, std::vector& radiuses, - int* belongs_to, int* count, const cvflann::DNAmming2* identifier) - { - (void)identifier; - refineDnaClustering( - indices, indices_length, branching, centers, radiuses, belongs_to, count); - - computeAnyBitfieldSubClustering(node, indices, indices_length, branching, - level, centers, radiuses, belongs_to, count); - } - - - /** - * The method responsible with actually doing the recursive hierarchical - * clustering - * - * Params: - * node = the node to cluster - * indices = indices of the points belonging to the current node - * branching = the branching factor to use in the clustering - * - * TODO: for 1-sized clusters don't store a cluster center (it's the same as the single cluster point) - */ - void computeClustering(KMeansNodePtr node, int* indices, int indices_length, int branching, int level) - { - node->size = indices_length; - node->level = level; - - if (indices_length < branching) { - node->indices = indices; - std::sort(node->indices,node->indices+indices_length); - node->childs = NULL; - return; - } - - cv::AutoBuffer centers_idx_buf(branching); - int* centers_idx = centers_idx_buf.data(); - int centers_length; - (this->*chooseCenters)(branching, indices, indices_length, centers_idx, centers_length); - - if (centers_lengthindices = indices; - std::sort(node->indices,node->indices+indices_length); - node->childs = NULL; - return; - } - - - std::vector radiuses(branching); - cv::AutoBuffer count_buf(branching); - int* count = count_buf.data(); - for (int i=0; i belongs_to_buf(indices_length); - int* belongs_to = belongs_to_buf.data(); - for (int i=0; inew_sq_dist) { - belongs_to[i] = j; - sq_dist = new_sq_dist; - } - } - if (sq_dist>radiuses[belongs_to[i]]) { - radiuses[belongs_to[i]] = sq_dist; - } - count[belongs_to[i]]++; - } - - CentersType** centers = new CentersType*[branching]; - - Distance* dummy = NULL; - refineAndSplitClustering(node, indices, indices_length, branching, level, - centers, radiuses, belongs_to, count, dummy); - - delete[] centers; - } - - - /** - * Performs one descent in the hierarchical k-means tree. The branches not - * visited are stored in a priority queue. - * - * Params: - * node = node to explore - * result = container for the k-nearest neighbors found - * vec = query points - * checks = how many points in the dataset have been checked so far - * maxChecks = maximum dataset points to checks - */ - - - void findNN(KMeansNodePtr node, ResultSet& result, const ElementType* vec, int& checks, int maxChecks, - const cv::Ptr>& heap) - { - // Ignore those clusters that are too far away - { - DistanceType bsq = distance_(vec, node->pivot, veclen_); - DistanceType rsq = node->radius; - DistanceType wsq = result.worstDist(); - - if (isSquareDistance()) - { - DistanceType val = bsq-rsq-wsq; - if ((val>0) && (val*val > 4*rsq*wsq)) - return; - } - else - { - if (bsq-rsq > wsq) - return; - } - } - - if (node->childs==NULL) { - if ((checks>=maxChecks) && result.full()) { - return; - } - checks += node->size; - for (int i=0; isize; ++i) { - int index = node->indices[i]; - DistanceType dist = distance_(dataset_[index], vec, veclen_); - result.addPoint(dist, index); - } - } - else { - DistanceType* domain_distances = new DistanceType[branching_]; - int closest_center = exploreNodeBranches(node, vec, domain_distances, heap); - delete[] domain_distances; - findNN(node->childs[closest_center],result,vec, checks, maxChecks, heap); - } - } - - /** - * Helper function that computes the nearest childs of a node to a given query point. - * Params: - * node = the node - * q = the query point - * distances = array with the distances to each child node. - * Returns: - */ - int exploreNodeBranches(KMeansNodePtr node, const ElementType* q, DistanceType* domain_distances, const cv::Ptr>& heap) - { - - int best_index = 0; - domain_distances[best_index] = distance_(q, node->childs[best_index]->pivot, veclen_); - for (int i=1; ichilds[i]->pivot, veclen_); - if (domain_distances[i]childs[best_index]->pivot; - for (int i=0; i( - cb_index_*node->childs[i]->variance ); - - // float dist_to_border = getDistanceToBorder(node.childs[i].pivot,best_center,q); - // if (domain_distances[i]insert(BranchSt(node->childs[i],domain_distances[i])); - } - } - - return best_index; - } - - - /** - * Function the performs exact nearest neighbor search by traversing the entire tree. - */ - void findExactNN(KMeansNodePtr node, ResultSet& result, const ElementType* vec) - { - // Ignore those clusters that are too far away - { - DistanceType bsq = distance_(vec, node->pivot, veclen_); - DistanceType rsq = node->radius; - DistanceType wsq = result.worstDist(); - - if (isSquareDistance()) - { - DistanceType val = bsq-rsq-wsq; - if ((val>0) && (val*val > 4*rsq*wsq)) - return; - } - else - { - if (bsq-rsq > wsq) - return; - } - } - - - if (node->childs==NULL) { - for (int i=0; isize; ++i) { - int index = node->indices[i]; - DistanceType dist = distance_(dataset_[index], vec, veclen_); - result.addPoint(dist, index); - } - } - else { - int* sort_indices = new int[branching_]; - - getCenterOrdering(node, vec, sort_indices); - - for (int i=0; ichilds[sort_indices[i]],result,vec); - } - - delete[] sort_indices; - } - } - - - /** - * Helper function. - * - * I computes the order in which to traverse the child nodes of a particular node. - */ - void getCenterOrdering(KMeansNodePtr node, const ElementType* q, int* sort_indices) - { - DistanceType* domain_distances = new DistanceType[branching_]; - for (int i=0; ichilds[i]->pivot, veclen_); - - int j=0; - while (domain_distances[j]j; --k) { - domain_distances[k] = domain_distances[k-1]; - sort_indices[k] = sort_indices[k-1]; - } - domain_distances[j] = dist; - sort_indices[j] = i; - } - delete[] domain_distances; - } - - /** - * Method that computes the squared distance from the query point q - * from inside region with center c to the border between this - * region and the region with center p - */ - DistanceType getDistanceToBorder(DistanceType* p, DistanceType* c, DistanceType* q) - { - DistanceType sum = 0; - DistanceType sum2 = 0; - - for (int i=0; ivariance*root->size; - - while (clusterCount::max)(); - int splitIndex = -1; - - for (int i=0; ichilds != NULL) { - - DistanceType variance = meanVariance - clusters[i]->variance*clusters[i]->size; - - for (int j=0; jchilds[j]->variance*clusters[i]->childs[j]->size; - } - if (variance clusters_length) break; - - meanVariance = minVariance; - - // split node - KMeansNodePtr toSplit = clusters[splitIndex]; - clusters[splitIndex] = toSplit->childs[0]; - for (int i=1; ichilds[i]; - } - } - - varianceValue = meanVariance/root->size; - return clusterCount; - } - -private: - /** The branching factor used in the hierarchical k-means clustering */ - int branching_; - - /** Number of kmeans trees (default is one) */ - int trees_; - - /** Maximum number of iterations to use when performing k-means clustering */ - int iterations_; - - /** Algorithm for choosing the cluster centers */ - flann_centers_init_t centers_init_; - - /** - * Cluster border index. This is used in the tree search phase when determining - * the closest cluster to explore next. A zero value takes into account only - * the cluster centres, a value greater then zero also take into account the size - * of the cluster. - */ - float cb_index_; - - /** - * The dataset used by this index - */ - const Matrix dataset_; - - /** Index parameters */ - IndexParams index_params_; - - /** - * Number of features in the dataset. - */ - size_t size_; - - /** - * Length of each feature. - */ - size_t veclen_; - - /** - * The root node in the tree. - */ - KMeansNodePtr* root_; - - /** - * Array of indices to vectors in the dataset. - */ - int** indices_; - - /** - * The distance - */ - Distance distance_; - - /** - * Pooled memory allocator. - */ - PooledAllocator pool_; - - /** - * Memory occupied by the index. - */ - int memoryCounter_; -}; - -} - -//! @endcond - -#endif //OPENCV_FLANN_KMEANS_INDEX_H_ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * 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 ``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 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 OPENCV_FLANN_KMEANS_INDEX_H_ +#define OPENCV_FLANN_KMEANS_INDEX_H_ + +//! @cond IGNORED + +#include +#include +#include +#include + +#include "general.h" +#include "nn_index.h" +#include "dist.h" +#include "matrix.h" +#include "result_set.h" +#include "heap.h" +#include "allocator.h" +#include "random.h" +#include "saving.h" +#include "logger.h" + +#define BITS_PER_CHAR 8 +#define BITS_PER_BASE 2 // for DNA/RNA sequences +#define BASE_PER_CHAR (BITS_PER_CHAR/BITS_PER_BASE) +#define HISTOS_PER_BASE (1< +class KMeansIndex : public NNIndex +{ +public: + typedef typename Distance::ElementType ElementType; + typedef typename Distance::ResultType DistanceType; + typedef typename Distance::CentersType CentersType; + + typedef typename Distance::is_kdtree_distance is_kdtree_distance; + typedef typename Distance::is_vector_space_distance is_vector_space_distance; + + + + typedef void (KMeansIndex::* centersAlgFunction)(int, int*, int, int*, int&); + + /** + * The function used for choosing the cluster centers. + */ + centersAlgFunction chooseCenters; + + + + /** + * Chooses the initial centers in the k-means clustering in a random manner. + * + * Params: + * k = number of centers + * vecs = the dataset of points + * indices = indices in the dataset + * indices_length = length of indices vector + * + */ + void chooseCentersRandom(int k, int* indices, int indices_length, int* centers, int& centers_length) + { + UniqueRandom r(indices_length); + + int index; + for (index=0; index=0 && rnd < n); + + centers[0] = indices[rnd]; + + int index; + for (index=1; indexbest_val) { + best_val = dist; + best_index = j; + } + } + if (best_index!=-1) { + centers[index] = indices[best_index]; + } + else { + break; + } + } + centers_length = index; + } + + + /** + * Chooses the initial centers in the k-means using the algorithm + * proposed in the KMeans++ paper: + * Arthur, David; Vassilvitskii, Sergei - k-means++: The Advantages of Careful Seeding + * + * Implementation of this function was converted from the one provided in Arthur's code. + * + * Params: + * k = number of centers + * vecs = the dataset of points + * indices = indices in the dataset + * Returns: + */ + void chooseCentersKMeanspp(int k, int* indices, int indices_length, int* centers, int& centers_length) + { + int n = indices_length; + + double currentPot = 0; + DistanceType* closestDistSq = new DistanceType[n]; + + // Choose one random center and set the closestDistSq values + int index = rand_int(n); + CV_DbgAssert(index >=0 && index < n); + centers[0] = indices[index]; + + for (int i = 0; i < n; i++) { + closestDistSq[i] = distance_(dataset_[indices[i]], dataset_[indices[index]], dataset_.cols); + closestDistSq[i] = ensureSquareDistance( closestDistSq[i] ); + currentPot += closestDistSq[i]; + } + + + const int numLocalTries = 1; + + // Choose each center + int centerCount; + for (centerCount = 1; centerCount < k; centerCount++) { + + // Repeat several trials + double bestNewPot = -1; + int bestNewIndex = -1; + for (int localTrial = 0; localTrial < numLocalTries; localTrial++) { + + // Choose our center - have to be slightly careful to return a valid answer even accounting + // for possible rounding errors + double randVal = rand_double(currentPot); + for (index = 0; index < n-1; index++) { + if (randVal <= closestDistSq[index]) break; + else randVal -= closestDistSq[index]; + } + + // Compute the new potential + double newPot = 0; + for (int i = 0; i < n; i++) { + DistanceType dist = distance_(dataset_[indices[i]], dataset_[indices[index]], dataset_.cols); + newPot += std::min( ensureSquareDistance(dist), closestDistSq[i] ); + } + + // Store the best result + if ((bestNewPot < 0)||(newPot < bestNewPot)) { + bestNewPot = newPot; + bestNewIndex = index; + } + } + + // Add the appropriate center + centers[centerCount] = indices[bestNewIndex]; + currentPot = bestNewPot; + for (int i = 0; i < n; i++) { + DistanceType dist = distance_(dataset_[indices[i]], dataset_[indices[bestNewIndex]], dataset_.cols); + closestDistSq[i] = std::min( ensureSquareDistance(dist), closestDistSq[i] ); + } + } + + centers_length = centerCount; + + delete[] closestDistSq; + } + + + +public: + + flann_algorithm_t getType() const CV_OVERRIDE + { + return FLANN_INDEX_KMEANS; + } + + template + class KMeansDistanceComputer : public cv::ParallelLoopBody + { + public: + KMeansDistanceComputer(Distance _distance, const Matrix& _dataset, + const int _branching, const int* _indices, const CentersContainerType& _dcenters, + const size_t _veclen, std::vector &_new_centroids, + std::vector &_sq_dists) + : distance(_distance) + , dataset(_dataset) + , branching(_branching) + , indices(_indices) + , dcenters(_dcenters) + , veclen(_veclen) + , new_centroids(_new_centroids) + , sq_dists(_sq_dists) + { + } + + void operator()(const cv::Range& range) const CV_OVERRIDE + { + const int begin = range.start; + const int end = range.end; + + for( int i = begin; inew_sq_dist) { + new_centroid = j; + sq_dist = new_sq_dist; + } + } + sq_dists[i] = sq_dist; + new_centroids[i] = new_centroid; + } + } + + private: + Distance distance; + const Matrix& dataset; + const int branching; + const int* indices; + const CentersContainerType& dcenters; + const size_t veclen; + std::vector &new_centroids; + std::vector &sq_dists; + KMeansDistanceComputer& operator=( const KMeansDistanceComputer & ) { return *this; } + }; + + /** + * Index constructor + * + * Params: + * inputData = dataset with the input features + * params = parameters passed to the hierarchical k-means algorithm + */ + KMeansIndex(const Matrix& inputData, const IndexParams& params = KMeansIndexParams(), + Distance d = Distance()) + : dataset_(inputData), index_params_(params), root_(NULL), indices_(NULL), distance_(d) + { + memoryCounter_ = 0; + + size_ = dataset_.rows; + veclen_ = dataset_.cols; + + branching_ = get_param(params,"branching",32); + trees_ = get_param(params,"trees",1); + iterations_ = get_param(params,"iterations",11); + if (iterations_<0) { + iterations_ = (std::numeric_limits::max)(); + } + centers_init_ = get_param(params,"centers_init",FLANN_CENTERS_RANDOM); + + if (centers_init_==FLANN_CENTERS_RANDOM) { + chooseCenters = &KMeansIndex::chooseCentersRandom; + } + else if (centers_init_==FLANN_CENTERS_GONZALES) { + chooseCenters = &KMeansIndex::chooseCentersGonzales; + } + else if (centers_init_==FLANN_CENTERS_KMEANSPP) { + chooseCenters = &KMeansIndex::chooseCentersKMeanspp; + } + else { + FLANN_THROW(cv::Error::StsBadArg, "Unknown algorithm for choosing initial centers."); + } + cb_index_ = 0.4f; + + root_ = new KMeansNodePtr[trees_]; + indices_ = new int*[trees_]; + + for (int i=0; i(); + std::memset(root_[i], 0, sizeof(KMeansNode)); + + Distance* dummy = NULL; + computeNodeStatistics(root_[i], indices_[i], (unsigned int)size_, dummy); + + computeClustering(root_[i], indices_[i], (int)size_, branching_,0); + } + } + + + void saveIndex(FILE* stream) CV_OVERRIDE + { + save_value(stream, branching_); + save_value(stream, iterations_); + save_value(stream, memoryCounter_); + save_value(stream, cb_index_); + save_value(stream, trees_); + for (int i=0; i& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE + { + + const int maxChecks = get_param(searchParams,"checks",32); + + if (maxChecks==FLANN_CHECKS_UNLIMITED) { + findExactNN(root_[0], result, vec); + } + else { + // Priority queue storing intermediate branches in the best-bin-first search + const cv::Ptr>& heap = Heap::getPooledInstance(cv::utils::getThreadID(), (int)size_); + + int checks = 0; + for (int i=0; i= maxChecks) && result.full()) + break; + } + + BranchSt branch; + while (heap->popMin(branch) && (checks& centers) + { + int numClusters = centers.rows; + if (numClusters<1) { + FLANN_THROW(cv::Error::StsBadArg, "Number of clusters must be at least 1"); + } + + DistanceType variance; + KMeansNodePtr* clusters = new KMeansNodePtr[numClusters]; + + int clusterCount = getMinVarianceClusters(root_[0], clusters, numClusters, variance); + + Logger::info("Clusters requested: %d, returning %d\n",numClusters, clusterCount); + + for (int i=0; ipivot; + for (size_t j=0; j BranchSt; + + + + + void save_tree(FILE* stream, KMeansNodePtr node, int num) + { + save_value(stream, *node); + save_value(stream, *(node->pivot), (int)veclen_); + if (node->childs==NULL) { + int indices_offset = (int)(node->indices - indices_[num]); + save_value(stream, indices_offset); + } + else { + for(int i=0; ichilds[i], num); + } + } + } + + + void load_tree(FILE* stream, KMeansNodePtr& node, int num) + { + node = pool_.allocate(); + load_value(stream, *node); + node->pivot = new CentersType[veclen_]; + load_value(stream, *(node->pivot), (int)veclen_); + if (node->childs==NULL) { + int indices_offset; + load_value(stream, indices_offset); + node->indices = indices_[num] + indices_offset; + } + else { + node->childs = pool_.allocate(branching_); + for(int i=0; ichilds[i], num); + } + } + } + + + /** + * Helper function + */ + void free_centers(KMeansNodePtr node) + { + delete[] node->pivot; + if (node->childs!=NULL) { + for (int k=0; kchilds[k]); + } + } + } + + void free_centers() + { + if (root_ != NULL) { + for(int i=0; i(), veclen_); + } + float length = static_cast(indices_length); + for (size_t j=0; j( mean[j] / static_cast(indices_length) ); + } + variance /= static_cast( length ); + variance -= distance_(mean, ZeroIterator(), veclen_); + + DistanceType radius = 0; + for (unsigned int i=0; iradius) { + radius = tmp; + } + } + + node->variance = variance; + node->radius = radius; + node->pivot = mean; + } + + + void computeBitfieldNodeStatistics(KMeansNodePtr node, int* indices, + unsigned int indices_length) + { + const unsigned int accumulator_veclen = static_cast( + veclen_*sizeof(CentersType)*BITS_PER_CHAR); + + unsigned long long variance = 0ull; + CentersType* mean = new CentersType[veclen_]; + memoryCounter_ += int(veclen_*sizeof(CentersType)); + unsigned int* mean_accumulator = new unsigned int[accumulator_veclen]; + + memset(mean_accumulator, 0, sizeof(unsigned int)*accumulator_veclen); + + for (unsigned int i=0; i( ensureSquareDistance( + distance_(dataset_[indices[i]], ZeroIterator(), veclen_))); + unsigned char* vec = (unsigned char*)dataset_[indices[i]]; + for (size_t k=0, l=0; k>1) & 0x01; + mean_accumulator[k+2] += (vec[l]>>2) & 0x01; + mean_accumulator[k+3] += (vec[l]>>3) & 0x01; + mean_accumulator[k+4] += (vec[l]>>4) & 0x01; + mean_accumulator[k+5] += (vec[l]>>5) & 0x01; + mean_accumulator[k+6] += (vec[l]>>6) & 0x01; + mean_accumulator[k+7] += (vec[l]>>7) & 0x01; + } + } + double cnt = static_cast(indices_length); + unsigned char* char_mean = (unsigned char*)mean; + for (size_t k=0, l=0; k( + (((int)(0.5 + (double)(mean_accumulator[k]) / cnt))) + | (((int)(0.5 + (double)(mean_accumulator[k+1]) / cnt))<<1) + | (((int)(0.5 + (double)(mean_accumulator[k+2]) / cnt))<<2) + | (((int)(0.5 + (double)(mean_accumulator[k+3]) / cnt))<<3) + | (((int)(0.5 + (double)(mean_accumulator[k+4]) / cnt))<<4) + | (((int)(0.5 + (double)(mean_accumulator[k+5]) / cnt))<<5) + | (((int)(0.5 + (double)(mean_accumulator[k+6]) / cnt))<<6) + | (((int)(0.5 + (double)(mean_accumulator[k+7]) / cnt))<<7)); + } + variance = static_cast( + 0.5 + static_cast(variance) / static_cast(indices_length)); + variance -= static_cast( + ensureSquareDistance( + distance_(mean, ZeroIterator(), veclen_))); + + DistanceType radius = 0; + for (unsigned int i=0; iradius) { + radius = tmp; + } + } + + node->variance = static_cast(variance); + node->radius = radius; + node->pivot = mean; + + delete[] mean_accumulator; + } + + + void computeDnaNodeStatistics(KMeansNodePtr node, int* indices, + unsigned int indices_length) + { + const unsigned int histos_veclen = static_cast( + veclen_*sizeof(CentersType)*(HISTOS_PER_BASE*BASE_PER_CHAR)); + + unsigned long long variance = 0ull; + unsigned int* histograms = new unsigned int[histos_veclen]; + memset(histograms, 0, sizeof(unsigned int)*histos_veclen); + + for (unsigned int i=0; i( ensureSquareDistance( + distance_(dataset_[indices[i]], ZeroIterator(), veclen_))); + + unsigned char* vec = (unsigned char*)dataset_[indices[i]]; + for (size_t k=0, l=0; k>2) & 0x03)]++; + histograms[k + 8 + ((vec[l]>>4) & 0x03)]++; + histograms[k +12 + ((vec[l]>>6) & 0x03)]++; + } + } + + CentersType* mean = new CentersType[veclen_]; + memoryCounter_ += int(veclen_*sizeof(CentersType)); + unsigned char* char_mean = (unsigned char*)mean; + unsigned int* h = histograms; + for (size_t k=0, l=0; k h[k+1] ? h[k+2] > h[k+3] ? h[k] > h[k+2] ? 0x00 : 0x10 + : h[k] > h[k+3] ? 0x00 : 0x11 + : h[k+2] > h[k+3] ? h[k+1] > h[k+2] ? 0x01 : 0x10 + : h[k+1] > h[k+3] ? 0x01 : 0x11) + | (h[k+4]>h[k+5] ? h[k+6] > h[k+7] ? h[k+4] > h[k+6] ? 0x00 : 0x1000 + : h[k+4] > h[k+7] ? 0x00 : 0x1100 + : h[k+6] > h[k+7] ? h[k+5] > h[k+6] ? 0x0100 : 0x1000 + : h[k+5] > h[k+7] ? 0x0100 : 0x1100) + | (h[k+8]>h[k+9] ? h[k+10]>h[k+11] ? h[k+8] >h[k+10] ? 0x00 : 0x100000 + : h[k+8] >h[k+11] ? 0x00 : 0x110000 + : h[k+10]>h[k+11] ? h[k+9] >h[k+10] ? 0x010000 : 0x100000 + : h[k+9] >h[k+11] ? 0x010000 : 0x110000) + | (h[k+12]>h[k+13] ? h[k+14]>h[k+15] ? h[k+12] >h[k+14] ? 0x00 : 0x10000000 + : h[k+12] >h[k+15] ? 0x00 : 0x11000000 + : h[k+14]>h[k+15] ? h[k+13] >h[k+14] ? 0x01000000 : 0x10000000 + : h[k+13] >h[k+15] ? 0x01000000 : 0x11000000); + } + variance = static_cast( + 0.5 + static_cast(variance) / static_cast(indices_length)); + variance -= static_cast( + ensureSquareDistance( + distance_(mean, ZeroIterator(), veclen_))); + + DistanceType radius = 0; + for (unsigned int i=0; iradius) { + radius = tmp; + } + } + + node->variance = static_cast(variance); + node->radius = radius; + node->pivot = mean; + + delete[] histograms; + } + + + template + void computeNodeStatistics(KMeansNodePtr node, int* indices, + unsigned int indices_length, + const DistType* identifier) + { + (void)identifier; + computeNodeStatistics(node, indices, indices_length); + } + + void computeNodeStatistics(KMeansNodePtr node, int* indices, + unsigned int indices_length, + const cvflann::HammingLUT* identifier) + { + (void)identifier; + computeBitfieldNodeStatistics(node, indices, indices_length); + } + + void computeNodeStatistics(KMeansNodePtr node, int* indices, + unsigned int indices_length, + const cvflann::Hamming* identifier) + { + (void)identifier; + computeBitfieldNodeStatistics(node, indices, indices_length); + } + + void computeNodeStatistics(KMeansNodePtr node, int* indices, + unsigned int indices_length, + const cvflann::Hamming2* identifier) + { + (void)identifier; + computeBitfieldNodeStatistics(node, indices, indices_length); + } + + void computeNodeStatistics(KMeansNodePtr node, int* indices, + unsigned int indices_length, + const cvflann::DNAmmingLUT* identifier) + { + (void)identifier; + computeDnaNodeStatistics(node, indices, indices_length); + } + + void computeNodeStatistics(KMeansNodePtr node, int* indices, + unsigned int indices_length, + const cvflann::DNAmming2* identifier) + { + (void)identifier; + computeDnaNodeStatistics(node, indices, indices_length); + } + + + void refineClustering(int* indices, int indices_length, int branching, CentersType** centers, + std::vector& radiuses, int* belongs_to, int* count) + { + cv::AutoBuffer dcenters_buf(branching*veclen_); + Matrix dcenters(dcenters_buf.data(), branching, veclen_); + + bool converged = false; + int iteration = 0; + while (!converged && iteration new_centroids(indices_length); + std::vector sq_dists(indices_length); + + // reassign points to clusters + KMeansDistanceComputer > invoker( + distance_, dataset_, branching, indices, dcenters, veclen_, new_centroids, sq_dists); + parallel_for_(cv::Range(0, (int)indices_length), invoker); + + for (int i=0; i < (int)indices_length; ++i) { + DistanceType sq_dist(sq_dists[i]); + int new_centroid(new_centroids[i]); + if (sq_dist > radiuses[new_centroid]) { + radiuses[new_centroid] = sq_dist; + } + if (new_centroid != belongs_to[i]) { + count[belongs_to[i]]--; + count[new_centroid]++; + belongs_to[i] = new_centroid; + converged = false; + } + } + + for (int i=0; i& radiuses, int* belongs_to, int* count) + { + for (int i=0; i( + veclen_*sizeof(ElementType)*BITS_PER_CHAR); + cv::AutoBuffer dcenters_buf(branching*accumulator_veclen); + Matrix dcenters(dcenters_buf.data(), branching, accumulator_veclen); + + bool converged = false; + int iteration = 0; + while (!converged && iteration>1) & 0x01; + dcenter[k+2] += (vec[l]>>2) & 0x01; + dcenter[k+3] += (vec[l]>>3) & 0x01; + dcenter[k+4] += (vec[l]>>4) & 0x01; + dcenter[k+5] += (vec[l]>>5) & 0x01; + dcenter[k+6] += (vec[l]>>6) & 0x01; + dcenter[k+7] += (vec[l]>>7) & 0x01; + } + } + for (int i=0; i(count[i]); + unsigned int* dcenter = dcenters[i]; + unsigned char* charCenter = (unsigned char*)centers[i]; + for (size_t k=0, l=0; k( + (((int)(0.5 + (double)(dcenter[k]) / cnt))) + | (((int)(0.5 + (double)(dcenter[k+1]) / cnt))<<1) + | (((int)(0.5 + (double)(dcenter[k+2]) / cnt))<<2) + | (((int)(0.5 + (double)(dcenter[k+3]) / cnt))<<3) + | (((int)(0.5 + (double)(dcenter[k+4]) / cnt))<<4) + | (((int)(0.5 + (double)(dcenter[k+5]) / cnt))<<5) + | (((int)(0.5 + (double)(dcenter[k+6]) / cnt))<<6) + | (((int)(0.5 + (double)(dcenter[k+7]) / cnt))<<7)); + } + } + + std::vector new_centroids(indices_length); + std::vector dists(indices_length); + + // reassign points to clusters + KMeansDistanceComputer invoker( + distance_, dataset_, branching, indices, centers, veclen_, new_centroids, dists); + parallel_for_(cv::Range(0, (int)indices_length), invoker); + + for (int i=0; i < indices_length; ++i) { + DistanceType dist(dists[i]); + int new_centroid(new_centroids[i]); + if (dist > radiuses[new_centroid]) { + radiuses[new_centroid] = dist; + } + if (new_centroid != belongs_to[i]) { + count[belongs_to[i]]--; + count[new_centroid]++; + belongs_to[i] = new_centroid; + converged = false; + } + } + + for (int i=0; i& radiuses, int* belongs_to, int* count) + { + for (int i=0; i( + veclen_*sizeof(CentersType)*(HISTOS_PER_BASE*BASE_PER_CHAR)); + cv::AutoBuffer histos_buf(branching*histos_veclen); + Matrix histos(histos_buf.data(), branching, histos_veclen); + + bool converged = false; + int iteration = 0; + while (!converged && iteration>2) & 0x03)]++; + h[k + 8 + ((vec[l]>>4) & 0x03)]++; + h[k +12 + ((vec[l]>>6) & 0x03)]++; + } + } + for (int i=0; i h[k+1] ? h[k+2] > h[k+3] ? h[k] > h[k+2] ? 0x00 : 0x10 + : h[k] > h[k+3] ? 0x00 : 0x11 + : h[k+2] > h[k+3] ? h[k+1] > h[k+2] ? 0x01 : 0x10 + : h[k+1] > h[k+3] ? 0x01 : 0x11) + | (h[k+4]>h[k+5] ? h[k+6] > h[k+7] ? h[k+4] > h[k+6] ? 0x00 : 0x1000 + : h[k+4] > h[k+7] ? 0x00 : 0x1100 + : h[k+6] > h[k+7] ? h[k+5] > h[k+6] ? 0x0100 : 0x1000 + : h[k+5] > h[k+7] ? 0x0100 : 0x1100) + | (h[k+8]>h[k+9] ? h[k+10]>h[k+11] ? h[k+8] >h[k+10] ? 0x00 : 0x100000 + : h[k+8] >h[k+11] ? 0x00 : 0x110000 + : h[k+10]>h[k+11] ? h[k+9] >h[k+10] ? 0x010000 : 0x100000 + : h[k+9] >h[k+11] ? 0x010000 : 0x110000) + | (h[k+12]>h[k+13] ? h[k+14]>h[k+15] ? h[k+12] >h[k+14] ? 0x00 : 0x10000000 + : h[k+12] >h[k+15] ? 0x00 : 0x11000000 + : h[k+14]>h[k+15] ? h[k+13] >h[k+14] ? 0x01000000 : 0x10000000 + : h[k+13] >h[k+15] ? 0x01000000 : 0x11000000); + } + } + + std::vector new_centroids(indices_length); + std::vector dists(indices_length); + + // reassign points to clusters + KMeansDistanceComputer invoker( + distance_, dataset_, branching, indices, centers, veclen_, new_centroids, dists); + parallel_for_(cv::Range(0, (int)indices_length), invoker); + + for (int i=0; i < indices_length; ++i) { + DistanceType dist(dists[i]); + int new_centroid(new_centroids[i]); + if (dist > radiuses[new_centroid]) { + radiuses[new_centroid] = dist; + } + if (new_centroid != belongs_to[i]) { + count[belongs_to[i]]--; + count[new_centroid]++; + belongs_to[i] = new_centroid; + converged = false; + } + } + + for (int i=0; i& radiuses, int* belongs_to, int* count) + { + // compute kmeans clustering for each of the resulting clusters + node->childs = pool_.allocate(branching); + int start = 0; + int end = start; + for (int c=0; c(), veclen_); + variance += d; + mean_radius += static_cast( sqrt(d) ); + std::swap(indices[i],indices[end]); + std::swap(belongs_to[i],belongs_to[end]); + end++; + } + } + variance /= s; + mean_radius /= s; + variance -= distance_(centers[c], ZeroIterator(), veclen_); + + node->childs[c] = pool_.allocate(); + std::memset(node->childs[c], 0, sizeof(KMeansNode)); + node->childs[c]->radius = radiuses[c]; + node->childs[c]->pivot = centers[c]; + node->childs[c]->variance = variance; + node->childs[c]->mean_radius = mean_radius; + computeClustering(node->childs[c],indices+start, end-start, branching, level+1); + start=end; + } + } + + + void computeAnyBitfieldSubClustering(KMeansNodePtr node, int* indices, int indices_length, + int branching, int level, CentersType** centers, + std::vector& radiuses, int* belongs_to, int* count) + { + // compute kmeans clustering for each of the resulting clusters + node->childs = pool_.allocate(branching); + int start = 0; + int end = start; + for (int c=0; c(), veclen_); + variance += static_cast( ensureSquareDistance(d) ); + mean_radius += ensureSimpleDistance(d); + std::swap(indices[i],indices[end]); + std::swap(belongs_to[i],belongs_to[end]); + end++; + } + } + mean_radius = static_cast( + 0.5f + static_cast(mean_radius) / static_cast(s)); + variance = static_cast( + 0.5 + static_cast(variance) / static_cast(s)); + variance -= static_cast( + ensureSquareDistance( + distance_(centers[c], ZeroIterator(), veclen_))); + + node->childs[c] = pool_.allocate(); + std::memset(node->childs[c], 0, sizeof(KMeansNode)); + node->childs[c]->radius = radiuses[c]; + node->childs[c]->pivot = centers[c]; + node->childs[c]->variance = static_cast(variance); + node->childs[c]->mean_radius = mean_radius; + computeClustering(node->childs[c],indices+start, end-start, branching, level+1); + start=end; + } + } + + + template + void refineAndSplitClustering( + KMeansNodePtr node, int* indices, int indices_length, int branching, + int level, CentersType** centers, std::vector& radiuses, + int* belongs_to, int* count, const DistType* identifier) + { + (void)identifier; + refineClustering(indices, indices_length, branching, centers, radiuses, belongs_to, count); + + computeSubClustering(node, indices, indices_length, branching, + level, centers, radiuses, belongs_to, count); + } + + + /** + * The methods responsible with doing the recursive hierarchical clustering on + * binary vectors. + * As some might have heard that KMeans on binary data doesn't make sense, + * it's worth a little explanation why it actually fairly works. As + * with the Hierarchical Clustering algortihm, we seed several centers for the + * current node by picking some of its points. Then in a first pass each point + * of the node is then related to its closest center. Now let's have a look at + * the 5 central dimensions of the 9 following points: + * + * xxxxxx11100xxxxx (1) + * xxxxxx11010xxxxx (2) + * xxxxxx11001xxxxx (3) + * xxxxxx10110xxxxx (4) + * xxxxxx10101xxxxx (5) + * xxxxxx10011xxxxx (6) + * xxxxxx01110xxxxx (7) + * xxxxxx01101xxxxx (8) + * xxxxxx01011xxxxx (9) + * sum _____ + * of 1: 66555 + * + * Even if the barycenter notion doesn't apply, we can set a center + * xxxxxx11111xxxxx that will better fit the five dimensions we are focusing + * on for these points. + * + * Note that convergence isn't ensured anymore. In practice, using Gonzales + * as seeding algorithm should be fine for getting convergence ("iterations" + * value can be set to -1). But with KMeans++ seeding you should definitely + * set a maximum number of iterations (but make it higher than the "iterations" + * default value of 11). + * + * Params: + * node = the node to cluster + * indices = indices of the points belonging to the current node + * indices_length = number of points in the current node + * branching = the branching factor to use in the clustering + * level = 0 for the root node, it increases with the subdivision levels + * centers = clusters centers to compute + * radiuses = radiuses of clusters + * belongs_to = LookUp Table returning, for a given indice id, the center id it belongs to + * count = array storing the number of indices for a given center id + * identifier = dummy pointer on an instance of Distance (use to branch correctly among templates) + */ + void refineAndSplitClustering( + KMeansNodePtr node, int* indices, int indices_length, int branching, + int level, CentersType** centers, std::vector& radiuses, + int* belongs_to, int* count, const cvflann::HammingLUT* identifier) + { + (void)identifier; + refineBitfieldClustering( + indices, indices_length, branching, centers, radiuses, belongs_to, count); + + computeAnyBitfieldSubClustering(node, indices, indices_length, branching, + level, centers, radiuses, belongs_to, count); + } + + + void refineAndSplitClustering( + KMeansNodePtr node, int* indices, int indices_length, int branching, + int level, CentersType** centers, std::vector& radiuses, + int* belongs_to, int* count, const cvflann::Hamming* identifier) + { + (void)identifier; + refineBitfieldClustering( + indices, indices_length, branching, centers, radiuses, belongs_to, count); + + computeAnyBitfieldSubClustering(node, indices, indices_length, branching, + level, centers, radiuses, belongs_to, count); + } + + + void refineAndSplitClustering( + KMeansNodePtr node, int* indices, int indices_length, int branching, + int level, CentersType** centers, std::vector& radiuses, + int* belongs_to, int* count, const cvflann::Hamming2* identifier) + { + (void)identifier; + refineBitfieldClustering( + indices, indices_length, branching, centers, radiuses, belongs_to, count); + + computeAnyBitfieldSubClustering(node, indices, indices_length, branching, + level, centers, radiuses, belongs_to, count); + } + + + void refineAndSplitClustering( + KMeansNodePtr node, int* indices, int indices_length, int branching, + int level, CentersType** centers, std::vector& radiuses, + int* belongs_to, int* count, const cvflann::DNAmmingLUT* identifier) + { + (void)identifier; + refineDnaClustering( + indices, indices_length, branching, centers, radiuses, belongs_to, count); + + computeAnyBitfieldSubClustering(node, indices, indices_length, branching, + level, centers, radiuses, belongs_to, count); + } + + + void refineAndSplitClustering( + KMeansNodePtr node, int* indices, int indices_length, int branching, + int level, CentersType** centers, std::vector& radiuses, + int* belongs_to, int* count, const cvflann::DNAmming2* identifier) + { + (void)identifier; + refineDnaClustering( + indices, indices_length, branching, centers, radiuses, belongs_to, count); + + computeAnyBitfieldSubClustering(node, indices, indices_length, branching, + level, centers, radiuses, belongs_to, count); + } + + + /** + * The method responsible with actually doing the recursive hierarchical + * clustering + * + * Params: + * node = the node to cluster + * indices = indices of the points belonging to the current node + * branching = the branching factor to use in the clustering + * + * TODO: for 1-sized clusters don't store a cluster center (it's the same as the single cluster point) + */ + void computeClustering(KMeansNodePtr node, int* indices, int indices_length, int branching, int level) + { + node->size = indices_length; + node->level = level; + + if (indices_length < branching) { + node->indices = indices; + std::sort(node->indices,node->indices+indices_length); + node->childs = NULL; + return; + } + + cv::AutoBuffer centers_idx_buf(branching); + int* centers_idx = centers_idx_buf.data(); + int centers_length; + (this->*chooseCenters)(branching, indices, indices_length, centers_idx, centers_length); + + if (centers_lengthindices = indices; + std::sort(node->indices,node->indices+indices_length); + node->childs = NULL; + return; + } + + + std::vector radiuses(branching); + cv::AutoBuffer count_buf(branching); + int* count = count_buf.data(); + for (int i=0; i belongs_to_buf(indices_length); + int* belongs_to = belongs_to_buf.data(); + for (int i=0; inew_sq_dist) { + belongs_to[i] = j; + sq_dist = new_sq_dist; + } + } + if (sq_dist>radiuses[belongs_to[i]]) { + radiuses[belongs_to[i]] = sq_dist; + } + count[belongs_to[i]]++; + } + + CentersType** centers = new CentersType*[branching]; + + Distance* dummy = NULL; + refineAndSplitClustering(node, indices, indices_length, branching, level, + centers, radiuses, belongs_to, count, dummy); + + delete[] centers; + } + + + /** + * Performs one descent in the hierarchical k-means tree. The branches not + * visited are stored in a priority queue. + * + * Params: + * node = node to explore + * result = container for the k-nearest neighbors found + * vec = query points + * checks = how many points in the dataset have been checked so far + * maxChecks = maximum dataset points to checks + */ + + + void findNN(KMeansNodePtr node, ResultSet& result, const ElementType* vec, int& checks, int maxChecks, + const cv::Ptr>& heap) + { + // Ignore those clusters that are too far away + { + DistanceType bsq = distance_(vec, node->pivot, veclen_); + DistanceType rsq = node->radius; + DistanceType wsq = result.worstDist(); + + if (isSquareDistance()) + { + DistanceType val = bsq-rsq-wsq; + if ((val>0) && (val*val > 4*rsq*wsq)) + return; + } + else + { + if (bsq-rsq > wsq) + return; + } + } + + if (node->childs==NULL) { + if ((checks>=maxChecks) && result.full()) { + return; + } + checks += node->size; + for (int i=0; isize; ++i) { + int index = node->indices[i]; + DistanceType dist = distance_(dataset_[index], vec, veclen_); + result.addPoint(dist, index); + } + } + else { + DistanceType* domain_distances = new DistanceType[branching_]; + int closest_center = exploreNodeBranches(node, vec, domain_distances, heap); + delete[] domain_distances; + findNN(node->childs[closest_center],result,vec, checks, maxChecks, heap); + } + } + + /** + * Helper function that computes the nearest childs of a node to a given query point. + * Params: + * node = the node + * q = the query point + * distances = array with the distances to each child node. + * Returns: + */ + int exploreNodeBranches(KMeansNodePtr node, const ElementType* q, DistanceType* domain_distances, const cv::Ptr>& heap) + { + + int best_index = 0; + domain_distances[best_index] = distance_(q, node->childs[best_index]->pivot, veclen_); + for (int i=1; ichilds[i]->pivot, veclen_); + if (domain_distances[i]childs[best_index]->pivot; + for (int i=0; i( + cb_index_*node->childs[i]->variance ); + + // float dist_to_border = getDistanceToBorder(node.childs[i].pivot,best_center,q); + // if (domain_distances[i]insert(BranchSt(node->childs[i],domain_distances[i])); + } + } + + return best_index; + } + + + /** + * Function the performs exact nearest neighbor search by traversing the entire tree. + */ + void findExactNN(KMeansNodePtr node, ResultSet& result, const ElementType* vec) + { + // Ignore those clusters that are too far away + { + DistanceType bsq = distance_(vec, node->pivot, veclen_); + DistanceType rsq = node->radius; + DistanceType wsq = result.worstDist(); + + if (isSquareDistance()) + { + DistanceType val = bsq-rsq-wsq; + if ((val>0) && (val*val > 4*rsq*wsq)) + return; + } + else + { + if (bsq-rsq > wsq) + return; + } + } + + + if (node->childs==NULL) { + for (int i=0; isize; ++i) { + int index = node->indices[i]; + DistanceType dist = distance_(dataset_[index], vec, veclen_); + result.addPoint(dist, index); + } + } + else { + int* sort_indices = new int[branching_]; + + getCenterOrdering(node, vec, sort_indices); + + for (int i=0; ichilds[sort_indices[i]],result,vec); + } + + delete[] sort_indices; + } + } + + + /** + * Helper function. + * + * I computes the order in which to traverse the child nodes of a particular node. + */ + void getCenterOrdering(KMeansNodePtr node, const ElementType* q, int* sort_indices) + { + DistanceType* domain_distances = new DistanceType[branching_]; + for (int i=0; ichilds[i]->pivot, veclen_); + + int j=0; + while (domain_distances[j]j; --k) { + domain_distances[k] = domain_distances[k-1]; + sort_indices[k] = sort_indices[k-1]; + } + domain_distances[j] = dist; + sort_indices[j] = i; + } + delete[] domain_distances; + } + + /** + * Method that computes the squared distance from the query point q + * from inside region with center c to the border between this + * region and the region with center p + */ + DistanceType getDistanceToBorder(DistanceType* p, DistanceType* c, DistanceType* q) + { + DistanceType sum = 0; + DistanceType sum2 = 0; + + for (int i=0; ivariance*root->size; + + while (clusterCount::max)(); + int splitIndex = -1; + + for (int i=0; ichilds != NULL) { + + DistanceType variance = meanVariance - clusters[i]->variance*clusters[i]->size; + + for (int j=0; jchilds[j]->variance*clusters[i]->childs[j]->size; + } + if (variance clusters_length) break; + + meanVariance = minVariance; + + // split node + KMeansNodePtr toSplit = clusters[splitIndex]; + clusters[splitIndex] = toSplit->childs[0]; + for (int i=1; ichilds[i]; + } + } + + varianceValue = meanVariance/root->size; + return clusterCount; + } + +private: + /** The branching factor used in the hierarchical k-means clustering */ + int branching_; + + /** Number of kmeans trees (default is one) */ + int trees_; + + /** Maximum number of iterations to use when performing k-means clustering */ + int iterations_; + + /** Algorithm for choosing the cluster centers */ + flann_centers_init_t centers_init_; + + /** + * Cluster border index. This is used in the tree search phase when determining + * the closest cluster to explore next. A zero value takes into account only + * the cluster centres, a value greater then zero also take into account the size + * of the cluster. + */ + float cb_index_; + + /** + * The dataset used by this index + */ + const Matrix dataset_; + + /** Index parameters */ + IndexParams index_params_; + + /** + * Number of features in the dataset. + */ + size_t size_; + + /** + * Length of each feature. + */ + size_t veclen_; + + /** + * The root node in the tree. + */ + KMeansNodePtr* root_; + + /** + * Array of indices to vectors in the dataset. + */ + int** indices_; + + /** + * The distance + */ + Distance distance_; + + /** + * Pooled memory allocator. + */ + PooledAllocator pool_; + + /** + * Memory occupied by the index. + */ + int memoryCounter_; +}; + +} + +//! @endcond + +#endif //OPENCV_FLANN_KMEANS_INDEX_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/linear_index.h b/3rdParty/opencv-4.11.0/opencv2/flann/linear_index.h index 6428c0d7ef..6dc91caa1a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/linear_index.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/linear_index.h @@ -1,135 +1,135 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * 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 ``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 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 OPENCV_FLANN_LINEAR_INDEX_H_ -#define OPENCV_FLANN_LINEAR_INDEX_H_ - -//! @cond IGNORED - -#include "nn_index.h" - -namespace cvflann -{ - -struct LinearIndexParams : public IndexParams -{ - LinearIndexParams() - { - (* this)["algorithm"] = FLANN_INDEX_LINEAR; - } -}; - -template -class LinearIndex : public NNIndex -{ -public: - - typedef typename Distance::ElementType ElementType; - typedef typename Distance::ResultType DistanceType; - - - LinearIndex(const Matrix& inputData, const IndexParams& params = LinearIndexParams(), - Distance d = Distance()) : - dataset_(inputData), index_params_(params), distance_(d) - { - } - - LinearIndex(const LinearIndex&); - LinearIndex& operator=(const LinearIndex&); - - flann_algorithm_t getType() const CV_OVERRIDE - { - return FLANN_INDEX_LINEAR; - } - - - size_t size() const CV_OVERRIDE - { - return dataset_.rows; - } - - size_t veclen() const CV_OVERRIDE - { - return dataset_.cols; - } - - - int usedMemory() const CV_OVERRIDE - { - return 0; - } - - void buildIndex() CV_OVERRIDE - { - /* nothing to do here for linear search */ - } - - void saveIndex(FILE*) CV_OVERRIDE - { - /* nothing to do here for linear search */ - } - - - void loadIndex(FILE*) CV_OVERRIDE - { - /* nothing to do here for linear search */ - - index_params_["algorithm"] = getType(); - } - - void findNeighbors(ResultSet& resultSet, const ElementType* vec, const SearchParams& /*searchParams*/) CV_OVERRIDE - { - ElementType* data = dataset_.data; - for (size_t i = 0; i < dataset_.rows; ++i, data += dataset_.cols) { - DistanceType dist = distance_(data, vec, dataset_.cols); - resultSet.addPoint(dist, (int)i); - } - } - - IndexParams getParameters() const CV_OVERRIDE - { - return index_params_; - } - -private: - /** The dataset */ - const Matrix dataset_; - /** Index parameters */ - IndexParams index_params_; - /** Index distance */ - Distance distance_; - -}; - -} - -//! @endcond - -#endif // OPENCV_FLANN_LINEAR_INDEX_H_ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * 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 ``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 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 OPENCV_FLANN_LINEAR_INDEX_H_ +#define OPENCV_FLANN_LINEAR_INDEX_H_ + +//! @cond IGNORED + +#include "nn_index.h" + +namespace cvflann +{ + +struct LinearIndexParams : public IndexParams +{ + LinearIndexParams() + { + (* this)["algorithm"] = FLANN_INDEX_LINEAR; + } +}; + +template +class LinearIndex : public NNIndex +{ +public: + + typedef typename Distance::ElementType ElementType; + typedef typename Distance::ResultType DistanceType; + + + LinearIndex(const Matrix& inputData, const IndexParams& params = LinearIndexParams(), + Distance d = Distance()) : + dataset_(inputData), index_params_(params), distance_(d) + { + } + + LinearIndex(const LinearIndex&); + LinearIndex& operator=(const LinearIndex&); + + flann_algorithm_t getType() const CV_OVERRIDE + { + return FLANN_INDEX_LINEAR; + } + + + size_t size() const CV_OVERRIDE + { + return dataset_.rows; + } + + size_t veclen() const CV_OVERRIDE + { + return dataset_.cols; + } + + + int usedMemory() const CV_OVERRIDE + { + return 0; + } + + void buildIndex() CV_OVERRIDE + { + /* nothing to do here for linear search */ + } + + void saveIndex(FILE*) CV_OVERRIDE + { + /* nothing to do here for linear search */ + } + + + void loadIndex(FILE*) CV_OVERRIDE + { + /* nothing to do here for linear search */ + + index_params_["algorithm"] = getType(); + } + + void findNeighbors(ResultSet& resultSet, const ElementType* vec, const SearchParams& /*searchParams*/) CV_OVERRIDE + { + ElementType* data = dataset_.data; + for (size_t i = 0; i < dataset_.rows; ++i, data += dataset_.cols) { + DistanceType dist = distance_(data, vec, dataset_.cols); + resultSet.addPoint(dist, (int)i); + } + } + + IndexParams getParameters() const CV_OVERRIDE + { + return index_params_; + } + +private: + /** The dataset */ + const Matrix dataset_; + /** Index parameters */ + IndexParams index_params_; + /** Index distance */ + Distance distance_; + +}; + +} + +//! @endcond + +#endif // OPENCV_FLANN_LINEAR_INDEX_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/logger.h b/3rdParty/opencv-4.11.0/opencv2/flann/logger.h index 31f9bbd77f..7708dfa2b8 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/logger.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/logger.h @@ -1,138 +1,138 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * 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 ``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 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 OPENCV_FLANN_LOGGER_H -#define OPENCV_FLANN_LOGGER_H - -//! @cond IGNORED - -#include -#include - -#include "defines.h" - - -namespace cvflann -{ - -class Logger -{ - Logger() : stream(stdout), logLevel(FLANN_LOG_WARN) {} - - ~Logger() - { - if ((stream!=NULL)&&(stream!=stdout)) { - fclose(stream); - } - } - - static Logger& instance() - { - static Logger logger; - return logger; - } - - void _setDestination(const char* name) - { - if (name==NULL) { - stream = stdout; - } - else { -#ifdef _MSC_VER - if (fopen_s(&stream, name, "w") != 0) - stream = NULL; -#else - stream = fopen(name,"w"); -#endif - if (stream == NULL) { - stream = stdout; - } - } - } - - int _log(int level, const char* fmt, va_list arglist) - { - if (level > logLevel ) return -1; - int ret = vfprintf(stream, fmt, arglist); - return ret; - } - -public: - /** - * Sets the logging level. All messages with lower priority will be ignored. - * @param level Logging level - */ - static void setLevel(int level) { instance().logLevel = level; } - - /** - * Sets the logging destination - * @param name Filename or NULL for console - */ - static void setDestination(const char* name) { instance()._setDestination(name); } - - /** - * Print log message - * @param level Log level - * @param fmt Message format - */ - static int log(int level, const char* fmt, ...) - { - va_list arglist; - va_start(arglist, fmt); - int ret = instance()._log(level,fmt,arglist); - va_end(arglist); - return ret; - } - -#define LOG_METHOD(NAME,LEVEL) \ - static int NAME(const char* fmt, ...) \ - { \ - va_list ap; \ - va_start(ap, fmt); \ - int ret = instance()._log(LEVEL, fmt, ap); \ - va_end(ap); \ - return ret; \ - } - - LOG_METHOD(fatal, FLANN_LOG_FATAL) - LOG_METHOD(error, FLANN_LOG_ERROR) - LOG_METHOD(warn, FLANN_LOG_WARN) - LOG_METHOD(info, FLANN_LOG_INFO) - -private: - FILE* stream; - int logLevel; -}; - -} - -//! @endcond - -#endif //OPENCV_FLANN_LOGGER_H +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * 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 ``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 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 OPENCV_FLANN_LOGGER_H +#define OPENCV_FLANN_LOGGER_H + +//! @cond IGNORED + +#include +#include + +#include "defines.h" + + +namespace cvflann +{ + +class Logger +{ + Logger() : stream(stdout), logLevel(FLANN_LOG_WARN) {} + + ~Logger() + { + if ((stream!=NULL)&&(stream!=stdout)) { + fclose(stream); + } + } + + static Logger& instance() + { + static Logger logger; + return logger; + } + + void _setDestination(const char* name) + { + if (name==NULL) { + stream = stdout; + } + else { +#ifdef _MSC_VER + if (fopen_s(&stream, name, "w") != 0) + stream = NULL; +#else + stream = fopen(name,"w"); +#endif + if (stream == NULL) { + stream = stdout; + } + } + } + + int _log(int level, const char* fmt, va_list arglist) + { + if (level > logLevel ) return -1; + int ret = vfprintf(stream, fmt, arglist); + return ret; + } + +public: + /** + * Sets the logging level. All messages with lower priority will be ignored. + * @param level Logging level + */ + static void setLevel(int level) { instance().logLevel = level; } + + /** + * Sets the logging destination + * @param name Filename or NULL for console + */ + static void setDestination(const char* name) { instance()._setDestination(name); } + + /** + * Print log message + * @param level Log level + * @param fmt Message format + */ + static int log(int level, const char* fmt, ...) + { + va_list arglist; + va_start(arglist, fmt); + int ret = instance()._log(level,fmt,arglist); + va_end(arglist); + return ret; + } + +#define LOG_METHOD(NAME,LEVEL) \ + static int NAME(const char* fmt, ...) \ + { \ + va_list ap; \ + va_start(ap, fmt); \ + int ret = instance()._log(LEVEL, fmt, ap); \ + va_end(ap); \ + return ret; \ + } + + LOG_METHOD(fatal, FLANN_LOG_FATAL) + LOG_METHOD(error, FLANN_LOG_ERROR) + LOG_METHOD(warn, FLANN_LOG_WARN) + LOG_METHOD(info, FLANN_LOG_INFO) + +private: + FILE* stream; + int logLevel; +}; + +} + +//! @endcond + +#endif //OPENCV_FLANN_LOGGER_H diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/lsh_index.h b/3rdParty/opencv-4.11.0/opencv2/flann/lsh_index.h index b5e87f6041..955549174d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/lsh_index.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/lsh_index.h @@ -1,403 +1,403 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * 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 ``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 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. - *************************************************************************/ - -/*********************************************************************** - * Author: Vincent Rabaud - *************************************************************************/ - -#ifndef OPENCV_FLANN_LSH_INDEX_H_ -#define OPENCV_FLANN_LSH_INDEX_H_ - -//! @cond IGNORED - -#include -#include -#include -#include - -#include "nn_index.h" -#include "matrix.h" -#include "result_set.h" -#include "heap.h" -#include "lsh_table.h" -#include "allocator.h" -#include "random.h" -#include "saving.h" - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable: 4702) //disable unreachable code -#endif - -namespace cvflann -{ - -struct LshIndexParams : public IndexParams -{ - LshIndexParams(int table_number = 12, int key_size = 20, int multi_probe_level = 2) - { - (*this)["algorithm"] = FLANN_INDEX_LSH; - // The number of hash tables to use - (*this)["table_number"] = table_number; - // The length of the key in the hash tables - (*this)["key_size"] = key_size; - // Number of levels to use in multi-probe (0 for standard LSH) - (*this)["multi_probe_level"] = multi_probe_level; - } -}; - -/** - * Locality-sensitive hashing index - * - * Contains the tables and other information for indexing a set of points - * for nearest-neighbor matching. - */ -template -class LshIndex : public NNIndex -{ -public: - typedef typename Distance::ElementType ElementType; - typedef typename Distance::ResultType DistanceType; - - /** Constructor - * @param input_data dataset with the input features - * @param params parameters passed to the LSH algorithm - * @param d the distance used - */ - LshIndex(const Matrix& input_data, const IndexParams& params = LshIndexParams(), - Distance d = Distance()) : - dataset_(input_data), index_params_(params), distance_(d) - { - // cv::flann::IndexParams sets integer params as 'int', so it is used with get_param - // in place of 'unsigned int' - table_number_ = get_param(index_params_,"table_number",12); - key_size_ = get_param(index_params_,"key_size",20); - multi_probe_level_ = get_param(index_params_,"multi_probe_level",2); - - feature_size_ = (unsigned)dataset_.cols; - fill_xor_mask(0, key_size_, multi_probe_level_, xor_masks_); - } - - - LshIndex(const LshIndex&); - LshIndex& operator=(const LshIndex&); - - /** - * Builds the index - */ - void buildIndex() CV_OVERRIDE - { - tables_.resize(table_number_); - for (int i = 0; i < table_number_; ++i) { - lsh::LshTable& table = tables_[i]; - table = lsh::LshTable(feature_size_, key_size_); - - // Add the features to the table - table.add(dataset_); - } - } - - flann_algorithm_t getType() const CV_OVERRIDE - { - return FLANN_INDEX_LSH; - } - - - void saveIndex(FILE* stream) CV_OVERRIDE - { - save_value(stream,table_number_); - save_value(stream,key_size_); - save_value(stream,multi_probe_level_); - save_value(stream, dataset_); - } - - void loadIndex(FILE* stream) CV_OVERRIDE - { - load_value(stream, table_number_); - load_value(stream, key_size_); - load_value(stream, multi_probe_level_); - load_value(stream, dataset_); - // Building the index is so fast we can afford not storing it - buildIndex(); - - index_params_["algorithm"] = getType(); - index_params_["table_number"] = table_number_; - index_params_["key_size"] = key_size_; - index_params_["multi_probe_level"] = multi_probe_level_; - } - - /** - * Returns size of index. - */ - size_t size() const CV_OVERRIDE - { - return dataset_.rows; - } - - /** - * Returns the length of an index feature. - */ - size_t veclen() const CV_OVERRIDE - { - return feature_size_; - } - - /** - * Computes the index memory usage - * Returns: memory used by the index - */ - int usedMemory() const CV_OVERRIDE - { - return (int)(dataset_.rows * sizeof(int)); - } - - - IndexParams getParameters() const CV_OVERRIDE - { - return index_params_; - } - - /** - * \brief Perform k-nearest neighbor search - * \param[in] queries The query points for which to find the nearest neighbors - * \param[out] indices The indices of the nearest neighbors found - * \param[out] dists Distances to the nearest neighbors found - * \param[in] knn Number of nearest neighbors to return - * \param[in] params Search parameters - */ - virtual void knnSearch(const Matrix& queries, Matrix& indices, Matrix& dists, int knn, const SearchParams& params) CV_OVERRIDE - { - CV_Assert(queries.cols == veclen()); - CV_Assert(indices.rows >= queries.rows); - CV_Assert(dists.rows >= queries.rows); - CV_Assert(int(indices.cols) >= knn); - CV_Assert(int(dists.cols) >= knn); - - - KNNUniqueResultSet resultSet(knn); - for (size_t i = 0; i < queries.rows; i++) { - resultSet.clear(); - std::fill_n(indices[i], knn, -1); - std::fill_n(dists[i], knn, std::numeric_limits::max()); - findNeighbors(resultSet, queries[i], params); - if (get_param(params,"sorted",true)) resultSet.sortAndCopy(indices[i], dists[i], knn); - else resultSet.copy(indices[i], dists[i], knn); - } - } - - - /** - * Find set of nearest neighbors to vec. Their indices are stored inside - * the result object. - * - * Params: - * result = the result object in which the indices of the nearest-neighbors are stored - * vec = the vector for which to search the nearest neighbors - * maxCheck = the maximum number of restarts (in a best-bin-first manner) - */ - void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& /*searchParams*/) CV_OVERRIDE - { - getNeighbors(vec, result); - } - -private: - /** Defines the comparator on score and index - */ - typedef std::pair ScoreIndexPair; - struct SortScoreIndexPairOnSecond - { - bool operator()(const ScoreIndexPair& left, const ScoreIndexPair& right) const - { - return left.second < right.second; - } - }; - - /** Fills the different xor masks to use when getting the neighbors in multi-probe LSH - * @param key the key we build neighbors from - * @param lowest_index the lowest index of the bit set - * @param level the multi-probe level we are at - * @param xor_masks all the xor mask - */ - void fill_xor_mask(lsh::BucketKey key, int lowest_index, unsigned int level, - std::vector& xor_masks) - { - xor_masks.push_back(key); - if (level == 0) return; - for (int index = lowest_index - 1; index >= 0; --index) { - // Create a new key - lsh::BucketKey new_key = key | (1 << index); - fill_xor_mask(new_key, index, level - 1, xor_masks); - } - } - - /** Performs the approximate nearest-neighbor search. - * @param vec the feature to analyze - * @param do_radius flag indicating if we check the radius too - * @param radius the radius if it is a radius search - * @param do_k flag indicating if we limit the number of nn - * @param k_nn the number of nearest neighbors - * @param checked_average used for debugging - */ - void getNeighbors(const ElementType* vec, bool /*do_radius*/, float radius, bool do_k, unsigned int k_nn, - float& /*checked_average*/) - { - static std::vector score_index_heap; - - if (do_k) { - unsigned int worst_score = std::numeric_limits::max(); - typename std::vector >::const_iterator table = tables_.begin(); - typename std::vector >::const_iterator table_end = tables_.end(); - for (; table != table_end; ++table) { - size_t key = table->getKey(vec); - std::vector::const_iterator xor_mask = xor_masks_.begin(); - std::vector::const_iterator xor_mask_end = xor_masks_.end(); - for (; xor_mask != xor_mask_end; ++xor_mask) { - size_t sub_key = key ^ (*xor_mask); - const lsh::Bucket* bucket = table->getBucketFromKey(sub_key); - if (bucket == 0) continue; - - // Go over each descriptor index - std::vector::const_iterator training_index = bucket->begin(); - std::vector::const_iterator last_training_index = bucket->end(); - DistanceType hamming_distance; - - // Process the rest of the candidates - for (; training_index < last_training_index; ++training_index) { - hamming_distance = distance_(vec, dataset_[*training_index], dataset_.cols); - - if (hamming_distance < worst_score) { - // Insert the new element - score_index_heap.push_back(ScoreIndexPair(hamming_distance, training_index)); - std::push_heap(score_index_heap.begin(), score_index_heap.end()); - - if (score_index_heap.size() > (unsigned int)k_nn) { - // Remove the highest distance value as we have too many elements - std::pop_heap(score_index_heap.begin(), score_index_heap.end()); - score_index_heap.pop_back(); - // Keep track of the worst score - worst_score = score_index_heap.front().first; - } - } - } - } - } - } - else { - typename std::vector >::const_iterator table = tables_.begin(); - typename std::vector >::const_iterator table_end = tables_.end(); - for (; table != table_end; ++table) { - size_t key = table->getKey(vec); - std::vector::const_iterator xor_mask = xor_masks_.begin(); - std::vector::const_iterator xor_mask_end = xor_masks_.end(); - for (; xor_mask != xor_mask_end; ++xor_mask) { - size_t sub_key = key ^ (*xor_mask); - const lsh::Bucket* bucket = table->getBucketFromKey(sub_key); - if (bucket == 0) continue; - - // Go over each descriptor index - std::vector::const_iterator training_index = bucket->begin(); - std::vector::const_iterator last_training_index = bucket->end(); - DistanceType hamming_distance; - - // Process the rest of the candidates - for (; training_index < last_training_index; ++training_index) { - // Compute the Hamming distance - hamming_distance = distance_(vec, dataset_[*training_index], dataset_.cols); - if (hamming_distance < radius) score_index_heap.push_back(ScoreIndexPair(hamming_distance, training_index)); - } - } - } - } - } - - /** Performs the approximate nearest-neighbor search. - * This is a slower version than the above as it uses the ResultSet - * @param vec the feature to analyze - */ - void getNeighbors(const ElementType* vec, ResultSet& result) - { - typename std::vector >::const_iterator table = tables_.begin(); - typename std::vector >::const_iterator table_end = tables_.end(); - for (; table != table_end; ++table) { - size_t key = table->getKey(vec); - std::vector::const_iterator xor_mask = xor_masks_.begin(); - std::vector::const_iterator xor_mask_end = xor_masks_.end(); - for (; xor_mask != xor_mask_end; ++xor_mask) { - size_t sub_key = key ^ (*xor_mask); - const lsh::Bucket* bucket = table->getBucketFromKey((lsh::BucketKey)sub_key); - if (bucket == 0) continue; - - // Go over each descriptor index - std::vector::const_iterator training_index = bucket->begin(); - std::vector::const_iterator last_training_index = bucket->end(); - DistanceType hamming_distance; - - // Process the rest of the candidates - for (; training_index < last_training_index; ++training_index) { - // Compute the Hamming distance - hamming_distance = distance_(vec, dataset_[*training_index], (int)dataset_.cols); - result.addPoint(hamming_distance, *training_index); - } - } - } - } - - /** The different hash tables */ - std::vector > tables_; - - /** The data the LSH tables where built from */ - Matrix dataset_; - - /** The size of the features (as ElementType[]) */ - unsigned int feature_size_; - - IndexParams index_params_; - - /** table number */ - int table_number_; - /** key size */ - int key_size_; - /** How far should we look for neighbors in multi-probe LSH */ - int multi_probe_level_; - - /** The XOR masks to apply to a key to get the neighboring buckets */ - std::vector xor_masks_; - - Distance distance_; -}; -} - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -//! @endcond - -#endif //OPENCV_FLANN_LSH_INDEX_H_ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * 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 ``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 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. + *************************************************************************/ + +/*********************************************************************** + * Author: Vincent Rabaud + *************************************************************************/ + +#ifndef OPENCV_FLANN_LSH_INDEX_H_ +#define OPENCV_FLANN_LSH_INDEX_H_ + +//! @cond IGNORED + +#include +#include +#include +#include + +#include "nn_index.h" +#include "matrix.h" +#include "result_set.h" +#include "heap.h" +#include "lsh_table.h" +#include "allocator.h" +#include "random.h" +#include "saving.h" + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable: 4702) //disable unreachable code +#endif + +namespace cvflann +{ + +struct LshIndexParams : public IndexParams +{ + LshIndexParams(int table_number = 12, int key_size = 20, int multi_probe_level = 2) + { + (*this)["algorithm"] = FLANN_INDEX_LSH; + // The number of hash tables to use + (*this)["table_number"] = table_number; + // The length of the key in the hash tables + (*this)["key_size"] = key_size; + // Number of levels to use in multi-probe (0 for standard LSH) + (*this)["multi_probe_level"] = multi_probe_level; + } +}; + +/** + * Locality-sensitive hashing index + * + * Contains the tables and other information for indexing a set of points + * for nearest-neighbor matching. + */ +template +class LshIndex : public NNIndex +{ +public: + typedef typename Distance::ElementType ElementType; + typedef typename Distance::ResultType DistanceType; + + /** Constructor + * @param input_data dataset with the input features + * @param params parameters passed to the LSH algorithm + * @param d the distance used + */ + LshIndex(const Matrix& input_data, const IndexParams& params = LshIndexParams(), + Distance d = Distance()) : + dataset_(input_data), index_params_(params), distance_(d) + { + // cv::flann::IndexParams sets integer params as 'int', so it is used with get_param + // in place of 'unsigned int' + table_number_ = get_param(index_params_,"table_number",12); + key_size_ = get_param(index_params_,"key_size",20); + multi_probe_level_ = get_param(index_params_,"multi_probe_level",2); + + feature_size_ = (unsigned)dataset_.cols; + fill_xor_mask(0, key_size_, multi_probe_level_, xor_masks_); + } + + + LshIndex(const LshIndex&); + LshIndex& operator=(const LshIndex&); + + /** + * Builds the index + */ + void buildIndex() CV_OVERRIDE + { + tables_.resize(table_number_); + for (int i = 0; i < table_number_; ++i) { + lsh::LshTable& table = tables_[i]; + table = lsh::LshTable(feature_size_, key_size_); + + // Add the features to the table + table.add(dataset_); + } + } + + flann_algorithm_t getType() const CV_OVERRIDE + { + return FLANN_INDEX_LSH; + } + + + void saveIndex(FILE* stream) CV_OVERRIDE + { + save_value(stream,table_number_); + save_value(stream,key_size_); + save_value(stream,multi_probe_level_); + save_value(stream, dataset_); + } + + void loadIndex(FILE* stream) CV_OVERRIDE + { + load_value(stream, table_number_); + load_value(stream, key_size_); + load_value(stream, multi_probe_level_); + load_value(stream, dataset_); + // Building the index is so fast we can afford not storing it + buildIndex(); + + index_params_["algorithm"] = getType(); + index_params_["table_number"] = table_number_; + index_params_["key_size"] = key_size_; + index_params_["multi_probe_level"] = multi_probe_level_; + } + + /** + * Returns size of index. + */ + size_t size() const CV_OVERRIDE + { + return dataset_.rows; + } + + /** + * Returns the length of an index feature. + */ + size_t veclen() const CV_OVERRIDE + { + return feature_size_; + } + + /** + * Computes the index memory usage + * Returns: memory used by the index + */ + int usedMemory() const CV_OVERRIDE + { + return (int)(dataset_.rows * sizeof(int)); + } + + + IndexParams getParameters() const CV_OVERRIDE + { + return index_params_; + } + + /** + * \brief Perform k-nearest neighbor search + * \param[in] queries The query points for which to find the nearest neighbors + * \param[out] indices The indices of the nearest neighbors found + * \param[out] dists Distances to the nearest neighbors found + * \param[in] knn Number of nearest neighbors to return + * \param[in] params Search parameters + */ + virtual void knnSearch(const Matrix& queries, Matrix& indices, Matrix& dists, int knn, const SearchParams& params) CV_OVERRIDE + { + CV_Assert(queries.cols == veclen()); + CV_Assert(indices.rows >= queries.rows); + CV_Assert(dists.rows >= queries.rows); + CV_Assert(int(indices.cols) >= knn); + CV_Assert(int(dists.cols) >= knn); + + + KNNUniqueResultSet resultSet(knn); + for (size_t i = 0; i < queries.rows; i++) { + resultSet.clear(); + std::fill_n(indices[i], knn, -1); + std::fill_n(dists[i], knn, std::numeric_limits::max()); + findNeighbors(resultSet, queries[i], params); + if (get_param(params,"sorted",true)) resultSet.sortAndCopy(indices[i], dists[i], knn); + else resultSet.copy(indices[i], dists[i], knn); + } + } + + + /** + * Find set of nearest neighbors to vec. Their indices are stored inside + * the result object. + * + * Params: + * result = the result object in which the indices of the nearest-neighbors are stored + * vec = the vector for which to search the nearest neighbors + * maxCheck = the maximum number of restarts (in a best-bin-first manner) + */ + void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& /*searchParams*/) CV_OVERRIDE + { + getNeighbors(vec, result); + } + +private: + /** Defines the comparator on score and index + */ + typedef std::pair ScoreIndexPair; + struct SortScoreIndexPairOnSecond + { + bool operator()(const ScoreIndexPair& left, const ScoreIndexPair& right) const + { + return left.second < right.second; + } + }; + + /** Fills the different xor masks to use when getting the neighbors in multi-probe LSH + * @param key the key we build neighbors from + * @param lowest_index the lowest index of the bit set + * @param level the multi-probe level we are at + * @param xor_masks all the xor mask + */ + void fill_xor_mask(lsh::BucketKey key, int lowest_index, unsigned int level, + std::vector& xor_masks) + { + xor_masks.push_back(key); + if (level == 0) return; + for (int index = lowest_index - 1; index >= 0; --index) { + // Create a new key + lsh::BucketKey new_key = key | (1 << index); + fill_xor_mask(new_key, index, level - 1, xor_masks); + } + } + + /** Performs the approximate nearest-neighbor search. + * @param vec the feature to analyze + * @param do_radius flag indicating if we check the radius too + * @param radius the radius if it is a radius search + * @param do_k flag indicating if we limit the number of nn + * @param k_nn the number of nearest neighbors + * @param checked_average used for debugging + */ + void getNeighbors(const ElementType* vec, bool /*do_radius*/, float radius, bool do_k, unsigned int k_nn, + float& /*checked_average*/) + { + static std::vector score_index_heap; + + if (do_k) { + unsigned int worst_score = std::numeric_limits::max(); + typename std::vector >::const_iterator table = tables_.begin(); + typename std::vector >::const_iterator table_end = tables_.end(); + for (; table != table_end; ++table) { + size_t key = table->getKey(vec); + std::vector::const_iterator xor_mask = xor_masks_.begin(); + std::vector::const_iterator xor_mask_end = xor_masks_.end(); + for (; xor_mask != xor_mask_end; ++xor_mask) { + size_t sub_key = key ^ (*xor_mask); + const lsh::Bucket* bucket = table->getBucketFromKey(sub_key); + if (bucket == 0) continue; + + // Go over each descriptor index + std::vector::const_iterator training_index = bucket->begin(); + std::vector::const_iterator last_training_index = bucket->end(); + DistanceType hamming_distance; + + // Process the rest of the candidates + for (; training_index < last_training_index; ++training_index) { + hamming_distance = distance_(vec, dataset_[*training_index], dataset_.cols); + + if (hamming_distance < worst_score) { + // Insert the new element + score_index_heap.push_back(ScoreIndexPair(hamming_distance, training_index)); + std::push_heap(score_index_heap.begin(), score_index_heap.end()); + + if (score_index_heap.size() > (unsigned int)k_nn) { + // Remove the highest distance value as we have too many elements + std::pop_heap(score_index_heap.begin(), score_index_heap.end()); + score_index_heap.pop_back(); + // Keep track of the worst score + worst_score = score_index_heap.front().first; + } + } + } + } + } + } + else { + typename std::vector >::const_iterator table = tables_.begin(); + typename std::vector >::const_iterator table_end = tables_.end(); + for (; table != table_end; ++table) { + size_t key = table->getKey(vec); + std::vector::const_iterator xor_mask = xor_masks_.begin(); + std::vector::const_iterator xor_mask_end = xor_masks_.end(); + for (; xor_mask != xor_mask_end; ++xor_mask) { + size_t sub_key = key ^ (*xor_mask); + const lsh::Bucket* bucket = table->getBucketFromKey(sub_key); + if (bucket == 0) continue; + + // Go over each descriptor index + std::vector::const_iterator training_index = bucket->begin(); + std::vector::const_iterator last_training_index = bucket->end(); + DistanceType hamming_distance; + + // Process the rest of the candidates + for (; training_index < last_training_index; ++training_index) { + // Compute the Hamming distance + hamming_distance = distance_(vec, dataset_[*training_index], dataset_.cols); + if (hamming_distance < radius) score_index_heap.push_back(ScoreIndexPair(hamming_distance, training_index)); + } + } + } + } + } + + /** Performs the approximate nearest-neighbor search. + * This is a slower version than the above as it uses the ResultSet + * @param vec the feature to analyze + */ + void getNeighbors(const ElementType* vec, ResultSet& result) + { + typename std::vector >::const_iterator table = tables_.begin(); + typename std::vector >::const_iterator table_end = tables_.end(); + for (; table != table_end; ++table) { + size_t key = table->getKey(vec); + std::vector::const_iterator xor_mask = xor_masks_.begin(); + std::vector::const_iterator xor_mask_end = xor_masks_.end(); + for (; xor_mask != xor_mask_end; ++xor_mask) { + size_t sub_key = key ^ (*xor_mask); + const lsh::Bucket* bucket = table->getBucketFromKey((lsh::BucketKey)sub_key); + if (bucket == 0) continue; + + // Go over each descriptor index + std::vector::const_iterator training_index = bucket->begin(); + std::vector::const_iterator last_training_index = bucket->end(); + DistanceType hamming_distance; + + // Process the rest of the candidates + for (; training_index < last_training_index; ++training_index) { + // Compute the Hamming distance + hamming_distance = distance_(vec, dataset_[*training_index], (int)dataset_.cols); + result.addPoint(hamming_distance, *training_index); + } + } + } + } + + /** The different hash tables */ + std::vector > tables_; + + /** The data the LSH tables where built from */ + Matrix dataset_; + + /** The size of the features (as ElementType[]) */ + unsigned int feature_size_; + + IndexParams index_params_; + + /** table number */ + int table_number_; + /** key size */ + int key_size_; + /** How far should we look for neighbors in multi-probe LSH */ + int multi_probe_level_; + + /** The XOR masks to apply to a key to get the neighboring buckets */ + std::vector xor_masks_; + + Distance distance_; +}; +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +//! @endcond + +#endif //OPENCV_FLANN_LSH_INDEX_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/lsh_table.h b/3rdParty/opencv-4.11.0/opencv2/flann/lsh_table.h index 3f51457cbb..9c72d11d52 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/lsh_table.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/lsh_table.h @@ -1,522 +1,522 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * 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 ``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 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. - *************************************************************************/ - -/*********************************************************************** - * Author: Vincent Rabaud - *************************************************************************/ - -#ifndef OPENCV_FLANN_LSH_TABLE_H_ -#define OPENCV_FLANN_LSH_TABLE_H_ - -//! @cond IGNORED - -#include -#include -#include -#include -// TODO as soon as we use C++0x, use the code in USE_UNORDERED_MAP -#ifdef __GXX_EXPERIMENTAL_CXX0X__ -# define USE_UNORDERED_MAP 1 -#else -# define USE_UNORDERED_MAP 0 -#endif -#if USE_UNORDERED_MAP -#include -#else -#include -#endif -#include -#include - -#include "dynamic_bitset.h" -#include "matrix.h" - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable: 4702) //disable unreachable code -#endif - - -namespace cvflann -{ - -namespace lsh -{ - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -/** What is stored in an LSH bucket - */ -typedef uint32_t FeatureIndex; -/** The id from which we can get a bucket back in an LSH table - */ -typedef unsigned int BucketKey; - -/** A bucket in an LSH table - */ -typedef std::vector Bucket; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -/** POD for stats about an LSH table - */ -struct LshStats -{ - std::vector bucket_sizes_; - size_t n_buckets_; - size_t bucket_size_mean_; - size_t bucket_size_median_; - size_t bucket_size_min_; - size_t bucket_size_max_; - size_t bucket_size_std_dev; - /** Each contained vector contains three value: beginning/end for interval, number of elements in the bin - */ - std::vector > size_histogram_; -}; - -/** Overload the << operator for LshStats - * @param out the streams - * @param stats the stats to display - * @return the streams - */ -inline std::ostream& operator <<(std::ostream& out, const LshStats& stats) -{ - int w = 20; - out << "Lsh Table Stats:\n" << std::setw(w) << std::setiosflags(std::ios::right) << "N buckets : " - << stats.n_buckets_ << "\n" << std::setw(w) << std::setiosflags(std::ios::right) << "mean size : " - << std::setiosflags(std::ios::left) << stats.bucket_size_mean_ << "\n" << std::setw(w) - << std::setiosflags(std::ios::right) << "median size : " << stats.bucket_size_median_ << "\n" << std::setw(w) - << std::setiosflags(std::ios::right) << "min size : " << std::setiosflags(std::ios::left) - << stats.bucket_size_min_ << "\n" << std::setw(w) << std::setiosflags(std::ios::right) << "max size : " - << std::setiosflags(std::ios::left) << stats.bucket_size_max_; - - // Display the histogram - out << std::endl << std::setw(w) << std::setiosflags(std::ios::right) << "histogram : " - << std::setiosflags(std::ios::left); - for (std::vector >::const_iterator iterator = stats.size_histogram_.begin(), end = - stats.size_histogram_.end(); iterator != end; ++iterator) out << (*iterator)[0] << "-" << (*iterator)[1] << ": " << (*iterator)[2] << ", "; - - return out; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -/** Lsh hash table. As its key is a sub-feature, and as usually - * the size of it is pretty small, we keep it as a continuous memory array. - * The value is an index in the corpus of features (we keep it as an unsigned - * int for pure memory reasons, it could be a size_t) - */ -template -class LshTable -{ -public: - /** A container of all the feature indices. Optimized for space - */ -#if USE_UNORDERED_MAP - typedef std::unordered_map BucketsSpace; -#else - typedef std::map BucketsSpace; -#endif - - /** A container of all the feature indices. Optimized for speed - */ - typedef std::vector BucketsSpeed; - - /** Default constructor - */ - LshTable() - { - key_size_ = 0; - feature_size_ = 0; - speed_level_ = kArray; - } - - /** Default constructor - * Create the mask and allocate the memory - * @param feature_size is the size of the feature (considered as a ElementType[]) - * @param key_size is the number of bits that are turned on in the feature - */ - LshTable(unsigned int feature_size, unsigned int key_size) - { - feature_size_ = feature_size; - CV_UNUSED(key_size); - CV_Error(cv::Error::StsUnsupportedFormat, "LSH is not implemented for that type" ); - } - - /** Add a feature to the table - * @param value the value to store for that feature - * @param feature the feature itself - */ - void add(unsigned int value, const ElementType* feature) - { - // Add the value to the corresponding bucket - BucketKey key = (lsh::BucketKey)getKey(feature); - - switch (speed_level_) { - case kArray: - // That means we get the buckets from an array - buckets_speed_[key].push_back(value); - break; - case kBitsetHash: - // That means we can check the bitset for the presence of a key - key_bitset_.set(key); - buckets_space_[key].push_back(value); - break; - case kHash: - { - // That means we have to check for the hash table for the presence of a key - buckets_space_[key].push_back(value); - break; - } - } - } - - /** Add a set of features to the table - * @param dataset the values to store - */ - void add(Matrix dataset) - { -#if USE_UNORDERED_MAP - buckets_space_.rehash((buckets_space_.size() + dataset.rows) * 1.2); -#endif - // Add the features to the table - for (unsigned int i = 0; i < dataset.rows; ++i) add(i, dataset[i]); - // Now that the table is full, optimize it for speed/space - optimize(); - } - - /** Get a bucket given the key - */ - inline const Bucket* getBucketFromKey(BucketKey key) const - { - // Generate other buckets - switch (speed_level_) { - case kArray: - // That means we get the buckets from an array - return &buckets_speed_[key]; - break; - case kBitsetHash: - // That means we can check the bitset for the presence of a key - if (key_bitset_.test(key)) return &buckets_space_.find(key)->second; - else return 0; - break; - case kHash: - { - // That means we have to check for the hash table for the presence of a key - BucketsSpace::const_iterator bucket_it, bucket_end = buckets_space_.end(); - bucket_it = buckets_space_.find(key); - // Stop here if that bucket does not exist - if (bucket_it == bucket_end) return 0; - else return &bucket_it->second; - break; - } - } - return 0; - } - - /** Compute the sub-signature of a feature - */ - size_t getKey(const ElementType* /*feature*/) const - { - CV_Error(cv::Error::StsUnsupportedFormat, "LSH is not implemented for that type" ); - return 0; - } - - /** Get statistics about the table - */ - LshStats getStats() const; - -private: - /** defines the speed fo the implementation - * kArray uses a vector for storing data - * kBitsetHash uses a hash map but checks for the validity of a key with a bitset - * kHash uses a hash map only - */ - enum SpeedLevel - { - kArray, kBitsetHash, kHash - }; - - /** Initialize some variables - */ - void initialize(size_t key_size) - { - const size_t key_size_lower_bound = 1; - //a value (size_t(1) << key_size) must fit the size_t type so key_size has to be strictly less than size of size_t - const size_t key_size_upper_bound = (std::min)(sizeof(BucketKey) * CHAR_BIT + 1, sizeof(size_t) * CHAR_BIT); - if (key_size < key_size_lower_bound || key_size >= key_size_upper_bound) - { - CV_Error(cv::Error::StsBadArg, cv::format("Invalid key_size (=%d). Valid values for your system are %d <= key_size < %d.", (int)key_size, (int)key_size_lower_bound, (int)key_size_upper_bound)); - } - - speed_level_ = kHash; - key_size_ = (unsigned)key_size; - } - - /** Optimize the table for speed/space - */ - void optimize() - { - // If we are already using the fast storage, no need to do anything - if (speed_level_ == kArray) return; - - // Use an array if it will be more than half full - if (buckets_space_.size() > ((size_t(1) << key_size_) / 2)) { - speed_level_ = kArray; - // Fill the array version of it - buckets_speed_.resize(size_t(1) << key_size_); - for (BucketsSpace::const_iterator key_bucket = buckets_space_.begin(); key_bucket != buckets_space_.end(); ++key_bucket) buckets_speed_[key_bucket->first] = key_bucket->second; - - // Empty the hash table - buckets_space_.clear(); - return; - } - - // If the bitset is going to use less than 10% of the RAM of the hash map (at least 1 size_t for the key and two - // for the vector) or less than 512MB (key_size_ <= 30) - if (((std::max(buckets_space_.size(), buckets_speed_.size()) * CHAR_BIT * 3 * sizeof(BucketKey)) / 10 - >= (size_t(1) << key_size_)) || (key_size_ <= 32)) { - speed_level_ = kBitsetHash; - key_bitset_.resize(size_t(1) << key_size_); - key_bitset_.reset(); - // Try with the BucketsSpace - for (BucketsSpace::const_iterator key_bucket = buckets_space_.begin(); key_bucket != buckets_space_.end(); ++key_bucket) key_bitset_.set(key_bucket->first); - } - else { - speed_level_ = kHash; - key_bitset_.clear(); - } - } - - /** The vector of all the buckets if they are held for speed - */ - BucketsSpeed buckets_speed_; - - /** The hash table of all the buckets in case we cannot use the speed version - */ - BucketsSpace buckets_space_; - - /** What is used to store the data */ - SpeedLevel speed_level_; - - /** If the subkey is small enough, it will keep track of which subkeys are set through that bitset - * That is just a speedup so that we don't look in the hash table (which can be mush slower that checking a bitset) - */ - DynamicBitset key_bitset_; - - /** The size of the sub-signature in bits - */ - unsigned int key_size_; - - unsigned int feature_size_; - - // Members only used for the unsigned char specialization - /** The mask to apply to a feature to get the hash key - * Only used in the unsigned char case - */ - std::vector mask_; -}; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// Specialization for unsigned char - -template<> -inline LshTable::LshTable(unsigned int feature_size, unsigned int subsignature_size) -{ - feature_size_ = feature_size; - initialize(subsignature_size); - // Allocate the mask - mask_ = std::vector((feature_size * sizeof(char) + sizeof(size_t) - 1) / sizeof(size_t), 0); - - // A bit brutal but fast to code - std::vector indices(feature_size * CHAR_BIT); - for (size_t i = 0; i < feature_size * CHAR_BIT; ++i) indices[i] = (int)i; -#ifndef OPENCV_FLANN_USE_STD_RAND - cv::randShuffle(indices); -#else - std::random_shuffle(indices.begin(), indices.end()); -#endif - - // Generate a random set of order of subsignature_size_ bits - for (unsigned int i = 0; i < key_size_; ++i) { - size_t index = indices[i]; - - // Set that bit in the mask - size_t divisor = CHAR_BIT * sizeof(size_t); - size_t idx = index / divisor; //pick the right size_t index - mask_[idx] |= size_t(1) << (index % divisor); //use modulo to find the bit offset - } - - // Set to 1 if you want to display the mask for debug -#if 0 - { - size_t bcount = 0; - BOOST_FOREACH(size_t mask_block, mask_){ - out << std::setw(sizeof(size_t) * CHAR_BIT / 4) << std::setfill('0') << std::hex << mask_block - << std::endl; - bcount += __builtin_popcountll(mask_block); - } - out << "bit count : " << std::dec << bcount << std::endl; - out << "mask size : " << mask_.size() << std::endl; - return out; - } -#endif -} - -/** Return the Subsignature of a feature - * @param feature the feature to analyze - */ -template<> -inline size_t LshTable::getKey(const unsigned char* feature) const -{ - // no need to check if T is dividable by sizeof(size_t) like in the Hamming - // distance computation as we have a mask - // FIXIT: This is bad assumption, because we reading tail bytes after of the allocated features buffer - const size_t* feature_block_ptr = reinterpret_cast ((const void*)feature); - - // Figure out the subsignature of the feature - // Given the feature ABCDEF, and the mask 001011, the output will be - // 000CEF - size_t subsignature = 0; - size_t bit_index = 1; - - for (unsigned i = 0; i < feature_size_; i += sizeof(size_t)) { - // get the mask and signature blocks - size_t feature_block; - if (i <= feature_size_ - sizeof(size_t)) - { - feature_block = *feature_block_ptr; - } - else - { - size_t tmp = 0; - memcpy(&tmp, feature_block_ptr, feature_size_ - i); // preserve bytes order - feature_block = tmp; - } - size_t mask_block = mask_[i / sizeof(size_t)]; - while (mask_block) { - // Get the lowest set bit in the mask block - size_t lowest_bit = mask_block & ~(mask_block - 1); - // Add it to the current subsignature if necessary - subsignature += (feature_block & lowest_bit) ? bit_index : 0; - // Reset the bit in the mask block - mask_block ^= lowest_bit; - // increment the bit index for the subsignature - bit_index <<= 1; - } - // Check the next feature block - ++feature_block_ptr; - } - return subsignature; -} - -template<> -inline LshStats LshTable::getStats() const -{ - LshStats stats; - stats.bucket_size_mean_ = 0; - if ((buckets_speed_.empty()) && (buckets_space_.empty())) { - stats.n_buckets_ = 0; - stats.bucket_size_median_ = 0; - stats.bucket_size_min_ = 0; - stats.bucket_size_max_ = 0; - return stats; - } - - if (!buckets_speed_.empty()) { - for (BucketsSpeed::const_iterator pbucket = buckets_speed_.begin(); pbucket != buckets_speed_.end(); ++pbucket) { - stats.bucket_sizes_.push_back((lsh::FeatureIndex)pbucket->size()); - stats.bucket_size_mean_ += pbucket->size(); - } - stats.bucket_size_mean_ /= buckets_speed_.size(); - stats.n_buckets_ = buckets_speed_.size(); - } - else { - for (BucketsSpace::const_iterator x = buckets_space_.begin(); x != buckets_space_.end(); ++x) { - stats.bucket_sizes_.push_back((lsh::FeatureIndex)x->second.size()); - stats.bucket_size_mean_ += x->second.size(); - } - stats.bucket_size_mean_ /= buckets_space_.size(); - stats.n_buckets_ = buckets_space_.size(); - } - - std::sort(stats.bucket_sizes_.begin(), stats.bucket_sizes_.end()); - - // BOOST_FOREACH(int size, stats.bucket_sizes_) - // std::cout << size << " "; - // std::cout << std::endl; - stats.bucket_size_median_ = stats.bucket_sizes_[stats.bucket_sizes_.size() / 2]; - stats.bucket_size_min_ = stats.bucket_sizes_.front(); - stats.bucket_size_max_ = stats.bucket_sizes_.back(); - - // TODO compute mean and std - /*float mean, stddev; - stats.bucket_size_mean_ = mean; - stats.bucket_size_std_dev = stddev;*/ - - // Include a histogram of the buckets - unsigned int bin_start = 0; - unsigned int bin_end = 20; - bool is_new_bin = true; - for (std::vector::iterator iterator = stats.bucket_sizes_.begin(), end = stats.bucket_sizes_.end(); iterator - != end; ) - if (*iterator < bin_end) { - if (is_new_bin) { - stats.size_histogram_.push_back(std::vector(3, 0)); - stats.size_histogram_.back()[0] = bin_start; - stats.size_histogram_.back()[1] = bin_end - 1; - is_new_bin = false; - } - ++stats.size_histogram_.back()[2]; - ++iterator; - } - else { - bin_start += 20; - bin_end += 20; - is_new_bin = true; - } - - return stats; -} - -// End the two namespaces -} -} - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -//! @endcond - -#endif /* OPENCV_FLANN_LSH_TABLE_H_ */ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * 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 ``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 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. + *************************************************************************/ + +/*********************************************************************** + * Author: Vincent Rabaud + *************************************************************************/ + +#ifndef OPENCV_FLANN_LSH_TABLE_H_ +#define OPENCV_FLANN_LSH_TABLE_H_ + +//! @cond IGNORED + +#include +#include +#include +#include +// TODO as soon as we use C++0x, use the code in USE_UNORDERED_MAP +#ifdef __GXX_EXPERIMENTAL_CXX0X__ +# define USE_UNORDERED_MAP 1 +#else +# define USE_UNORDERED_MAP 0 +#endif +#if USE_UNORDERED_MAP +#include +#else +#include +#endif +#include +#include + +#include "dynamic_bitset.h" +#include "matrix.h" + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable: 4702) //disable unreachable code +#endif + + +namespace cvflann +{ + +namespace lsh +{ + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +/** What is stored in an LSH bucket + */ +typedef uint32_t FeatureIndex; +/** The id from which we can get a bucket back in an LSH table + */ +typedef unsigned int BucketKey; + +/** A bucket in an LSH table + */ +typedef std::vector Bucket; + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +/** POD for stats about an LSH table + */ +struct LshStats +{ + std::vector bucket_sizes_; + size_t n_buckets_; + size_t bucket_size_mean_; + size_t bucket_size_median_; + size_t bucket_size_min_; + size_t bucket_size_max_; + size_t bucket_size_std_dev; + /** Each contained vector contains three value: beginning/end for interval, number of elements in the bin + */ + std::vector > size_histogram_; +}; + +/** Overload the << operator for LshStats + * @param out the streams + * @param stats the stats to display + * @return the streams + */ +inline std::ostream& operator <<(std::ostream& out, const LshStats& stats) +{ + int w = 20; + out << "Lsh Table Stats:\n" << std::setw(w) << std::setiosflags(std::ios::right) << "N buckets : " + << stats.n_buckets_ << "\n" << std::setw(w) << std::setiosflags(std::ios::right) << "mean size : " + << std::setiosflags(std::ios::left) << stats.bucket_size_mean_ << "\n" << std::setw(w) + << std::setiosflags(std::ios::right) << "median size : " << stats.bucket_size_median_ << "\n" << std::setw(w) + << std::setiosflags(std::ios::right) << "min size : " << std::setiosflags(std::ios::left) + << stats.bucket_size_min_ << "\n" << std::setw(w) << std::setiosflags(std::ios::right) << "max size : " + << std::setiosflags(std::ios::left) << stats.bucket_size_max_; + + // Display the histogram + out << std::endl << std::setw(w) << std::setiosflags(std::ios::right) << "histogram : " + << std::setiosflags(std::ios::left); + for (std::vector >::const_iterator iterator = stats.size_histogram_.begin(), end = + stats.size_histogram_.end(); iterator != end; ++iterator) out << (*iterator)[0] << "-" << (*iterator)[1] << ": " << (*iterator)[2] << ", "; + + return out; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +/** Lsh hash table. As its key is a sub-feature, and as usually + * the size of it is pretty small, we keep it as a continuous memory array. + * The value is an index in the corpus of features (we keep it as an unsigned + * int for pure memory reasons, it could be a size_t) + */ +template +class LshTable +{ +public: + /** A container of all the feature indices. Optimized for space + */ +#if USE_UNORDERED_MAP + typedef std::unordered_map BucketsSpace; +#else + typedef std::map BucketsSpace; +#endif + + /** A container of all the feature indices. Optimized for speed + */ + typedef std::vector BucketsSpeed; + + /** Default constructor + */ + LshTable() + { + key_size_ = 0; + feature_size_ = 0; + speed_level_ = kArray; + } + + /** Default constructor + * Create the mask and allocate the memory + * @param feature_size is the size of the feature (considered as a ElementType[]) + * @param key_size is the number of bits that are turned on in the feature + */ + LshTable(unsigned int feature_size, unsigned int key_size) + { + feature_size_ = feature_size; + CV_UNUSED(key_size); + CV_Error(cv::Error::StsUnsupportedFormat, "LSH is not implemented for that type" ); + } + + /** Add a feature to the table + * @param value the value to store for that feature + * @param feature the feature itself + */ + void add(unsigned int value, const ElementType* feature) + { + // Add the value to the corresponding bucket + BucketKey key = (lsh::BucketKey)getKey(feature); + + switch (speed_level_) { + case kArray: + // That means we get the buckets from an array + buckets_speed_[key].push_back(value); + break; + case kBitsetHash: + // That means we can check the bitset for the presence of a key + key_bitset_.set(key); + buckets_space_[key].push_back(value); + break; + case kHash: + { + // That means we have to check for the hash table for the presence of a key + buckets_space_[key].push_back(value); + break; + } + } + } + + /** Add a set of features to the table + * @param dataset the values to store + */ + void add(Matrix dataset) + { +#if USE_UNORDERED_MAP + buckets_space_.rehash((buckets_space_.size() + dataset.rows) * 1.2); +#endif + // Add the features to the table + for (unsigned int i = 0; i < dataset.rows; ++i) add(i, dataset[i]); + // Now that the table is full, optimize it for speed/space + optimize(); + } + + /** Get a bucket given the key + */ + inline const Bucket* getBucketFromKey(BucketKey key) const + { + // Generate other buckets + switch (speed_level_) { + case kArray: + // That means we get the buckets from an array + return &buckets_speed_[key]; + break; + case kBitsetHash: + // That means we can check the bitset for the presence of a key + if (key_bitset_.test(key)) return &buckets_space_.find(key)->second; + else return 0; + break; + case kHash: + { + // That means we have to check for the hash table for the presence of a key + BucketsSpace::const_iterator bucket_it, bucket_end = buckets_space_.end(); + bucket_it = buckets_space_.find(key); + // Stop here if that bucket does not exist + if (bucket_it == bucket_end) return 0; + else return &bucket_it->second; + break; + } + } + return 0; + } + + /** Compute the sub-signature of a feature + */ + size_t getKey(const ElementType* /*feature*/) const + { + CV_Error(cv::Error::StsUnsupportedFormat, "LSH is not implemented for that type" ); + return 0; + } + + /** Get statistics about the table + */ + LshStats getStats() const; + +private: + /** defines the speed fo the implementation + * kArray uses a vector for storing data + * kBitsetHash uses a hash map but checks for the validity of a key with a bitset + * kHash uses a hash map only + */ + enum SpeedLevel + { + kArray, kBitsetHash, kHash + }; + + /** Initialize some variables + */ + void initialize(size_t key_size) + { + const size_t key_size_lower_bound = 1; + //a value (size_t(1) << key_size) must fit the size_t type so key_size has to be strictly less than size of size_t + const size_t key_size_upper_bound = (std::min)(sizeof(BucketKey) * CHAR_BIT + 1, sizeof(size_t) * CHAR_BIT); + if (key_size < key_size_lower_bound || key_size >= key_size_upper_bound) + { + CV_Error(cv::Error::StsBadArg, cv::format("Invalid key_size (=%d). Valid values for your system are %d <= key_size < %d.", (int)key_size, (int)key_size_lower_bound, (int)key_size_upper_bound)); + } + + speed_level_ = kHash; + key_size_ = (unsigned)key_size; + } + + /** Optimize the table for speed/space + */ + void optimize() + { + // If we are already using the fast storage, no need to do anything + if (speed_level_ == kArray) return; + + // Use an array if it will be more than half full + if (buckets_space_.size() > ((size_t(1) << key_size_) / 2)) { + speed_level_ = kArray; + // Fill the array version of it + buckets_speed_.resize(size_t(1) << key_size_); + for (BucketsSpace::const_iterator key_bucket = buckets_space_.begin(); key_bucket != buckets_space_.end(); ++key_bucket) buckets_speed_[key_bucket->first] = key_bucket->second; + + // Empty the hash table + buckets_space_.clear(); + return; + } + + // If the bitset is going to use less than 10% of the RAM of the hash map (at least 1 size_t for the key and two + // for the vector) or less than 512MB (key_size_ <= 30) + if (((std::max(buckets_space_.size(), buckets_speed_.size()) * CHAR_BIT * 3 * sizeof(BucketKey)) / 10 + >= (size_t(1) << key_size_)) || (key_size_ <= 32)) { + speed_level_ = kBitsetHash; + key_bitset_.resize(size_t(1) << key_size_); + key_bitset_.reset(); + // Try with the BucketsSpace + for (BucketsSpace::const_iterator key_bucket = buckets_space_.begin(); key_bucket != buckets_space_.end(); ++key_bucket) key_bitset_.set(key_bucket->first); + } + else { + speed_level_ = kHash; + key_bitset_.clear(); + } + } + + /** The vector of all the buckets if they are held for speed + */ + BucketsSpeed buckets_speed_; + + /** The hash table of all the buckets in case we cannot use the speed version + */ + BucketsSpace buckets_space_; + + /** What is used to store the data */ + SpeedLevel speed_level_; + + /** If the subkey is small enough, it will keep track of which subkeys are set through that bitset + * That is just a speedup so that we don't look in the hash table (which can be mush slower that checking a bitset) + */ + DynamicBitset key_bitset_; + + /** The size of the sub-signature in bits + */ + unsigned int key_size_; + + unsigned int feature_size_; + + // Members only used for the unsigned char specialization + /** The mask to apply to a feature to get the hash key + * Only used in the unsigned char case + */ + std::vector mask_; +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Specialization for unsigned char + +template<> +inline LshTable::LshTable(unsigned int feature_size, unsigned int subsignature_size) +{ + feature_size_ = feature_size; + initialize(subsignature_size); + // Allocate the mask + mask_ = std::vector((feature_size * sizeof(char) + sizeof(size_t) - 1) / sizeof(size_t), 0); + + // A bit brutal but fast to code + std::vector indices(feature_size * CHAR_BIT); + for (size_t i = 0; i < feature_size * CHAR_BIT; ++i) indices[i] = (int)i; +#ifndef OPENCV_FLANN_USE_STD_RAND + cv::randShuffle(indices); +#else + std::random_shuffle(indices.begin(), indices.end()); +#endif + + // Generate a random set of order of subsignature_size_ bits + for (unsigned int i = 0; i < key_size_; ++i) { + size_t index = indices[i]; + + // Set that bit in the mask + size_t divisor = CHAR_BIT * sizeof(size_t); + size_t idx = index / divisor; //pick the right size_t index + mask_[idx] |= size_t(1) << (index % divisor); //use modulo to find the bit offset + } + + // Set to 1 if you want to display the mask for debug +#if 0 + { + size_t bcount = 0; + BOOST_FOREACH(size_t mask_block, mask_){ + out << std::setw(sizeof(size_t) * CHAR_BIT / 4) << std::setfill('0') << std::hex << mask_block + << std::endl; + bcount += __builtin_popcountll(mask_block); + } + out << "bit count : " << std::dec << bcount << std::endl; + out << "mask size : " << mask_.size() << std::endl; + return out; + } +#endif +} + +/** Return the Subsignature of a feature + * @param feature the feature to analyze + */ +template<> +inline size_t LshTable::getKey(const unsigned char* feature) const +{ + // no need to check if T is dividable by sizeof(size_t) like in the Hamming + // distance computation as we have a mask + // FIXIT: This is bad assumption, because we reading tail bytes after of the allocated features buffer + const size_t* feature_block_ptr = reinterpret_cast ((const void*)feature); + + // Figure out the subsignature of the feature + // Given the feature ABCDEF, and the mask 001011, the output will be + // 000CEF + size_t subsignature = 0; + size_t bit_index = 1; + + for (unsigned i = 0; i < feature_size_; i += sizeof(size_t)) { + // get the mask and signature blocks + size_t feature_block; + if (i <= feature_size_ - sizeof(size_t)) + { + feature_block = *feature_block_ptr; + } + else + { + size_t tmp = 0; + memcpy(&tmp, feature_block_ptr, feature_size_ - i); // preserve bytes order + feature_block = tmp; + } + size_t mask_block = mask_[i / sizeof(size_t)]; + while (mask_block) { + // Get the lowest set bit in the mask block + size_t lowest_bit = mask_block & ~(mask_block - 1); + // Add it to the current subsignature if necessary + subsignature += (feature_block & lowest_bit) ? bit_index : 0; + // Reset the bit in the mask block + mask_block ^= lowest_bit; + // increment the bit index for the subsignature + bit_index <<= 1; + } + // Check the next feature block + ++feature_block_ptr; + } + return subsignature; +} + +template<> +inline LshStats LshTable::getStats() const +{ + LshStats stats; + stats.bucket_size_mean_ = 0; + if ((buckets_speed_.empty()) && (buckets_space_.empty())) { + stats.n_buckets_ = 0; + stats.bucket_size_median_ = 0; + stats.bucket_size_min_ = 0; + stats.bucket_size_max_ = 0; + return stats; + } + + if (!buckets_speed_.empty()) { + for (BucketsSpeed::const_iterator pbucket = buckets_speed_.begin(); pbucket != buckets_speed_.end(); ++pbucket) { + stats.bucket_sizes_.push_back((lsh::FeatureIndex)pbucket->size()); + stats.bucket_size_mean_ += pbucket->size(); + } + stats.bucket_size_mean_ /= buckets_speed_.size(); + stats.n_buckets_ = buckets_speed_.size(); + } + else { + for (BucketsSpace::const_iterator x = buckets_space_.begin(); x != buckets_space_.end(); ++x) { + stats.bucket_sizes_.push_back((lsh::FeatureIndex)x->second.size()); + stats.bucket_size_mean_ += x->second.size(); + } + stats.bucket_size_mean_ /= buckets_space_.size(); + stats.n_buckets_ = buckets_space_.size(); + } + + std::sort(stats.bucket_sizes_.begin(), stats.bucket_sizes_.end()); + + // BOOST_FOREACH(int size, stats.bucket_sizes_) + // std::cout << size << " "; + // std::cout << std::endl; + stats.bucket_size_median_ = stats.bucket_sizes_[stats.bucket_sizes_.size() / 2]; + stats.bucket_size_min_ = stats.bucket_sizes_.front(); + stats.bucket_size_max_ = stats.bucket_sizes_.back(); + + // TODO compute mean and std + /*float mean, stddev; + stats.bucket_size_mean_ = mean; + stats.bucket_size_std_dev = stddev;*/ + + // Include a histogram of the buckets + unsigned int bin_start = 0; + unsigned int bin_end = 20; + bool is_new_bin = true; + for (std::vector::iterator iterator = stats.bucket_sizes_.begin(), end = stats.bucket_sizes_.end(); iterator + != end; ) + if (*iterator < bin_end) { + if (is_new_bin) { + stats.size_histogram_.push_back(std::vector(3, 0)); + stats.size_histogram_.back()[0] = bin_start; + stats.size_histogram_.back()[1] = bin_end - 1; + is_new_bin = false; + } + ++stats.size_histogram_.back()[2]; + ++iterator; + } + else { + bin_start += 20; + bin_end += 20; + is_new_bin = true; + } + + return stats; +} + +// End the two namespaces +} +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +//! @endcond + +#endif /* OPENCV_FLANN_LSH_TABLE_H_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/matrix.h b/3rdParty/opencv-4.11.0/opencv2/flann/matrix.h index bfbf91ef5c..5dc326d63e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/matrix.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/matrix.h @@ -1,121 +1,121 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * 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 ``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 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 OPENCV_FLANN_DATASET_H_ -#define OPENCV_FLANN_DATASET_H_ - -//! @cond IGNORED - -#include - -#include "opencv2/core/cvdef.h" -#include "opencv2/flann/defines.h" - -namespace cvflann -{ - -/** - * Class that implements a simple rectangular matrix stored in a memory buffer and - * provides convenient matrix-like access using the [] operators. - */ -template -class Matrix -{ -public: - typedef T type; - - size_t rows; - size_t cols; - size_t stride; - T* data; - - Matrix() : rows(0), cols(0), stride(0), data(NULL) - { - } - - Matrix(T* data_, size_t rows_, size_t cols_, size_t stride_ = 0) : - rows(rows_), cols(cols_), stride(stride_), data(data_) - { - if (stride==0) stride = cols; - } - - /** - * Convenience function for deallocating the storage data. - */ - CV_DEPRECATED void free() - { - fprintf(stderr, "The cvflann::Matrix::free() method is deprecated " - "and it does not do any memory deallocation any more. You are" - "responsible for deallocating the matrix memory (by doing" - "'delete[] matrix.data' for example)"); - } - - /** - * Operator that return a (pointer to a) row of the data. - */ - T* operator[](size_t index) const - { - return data+index*stride; - } -}; - - -class UntypedMatrix -{ -public: - size_t rows; - size_t cols; - void* data; - flann_datatype_t type; - - UntypedMatrix(void* data_, long rows_, long cols_) : - rows(rows_), cols(cols_), data(data_) - { - } - - ~UntypedMatrix() - { - } - - - template - Matrix as() - { - return Matrix((T*)data, rows, cols); - } -}; - - - -} - -//! @endcond - -#endif //OPENCV_FLANN_DATASET_H_ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * 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 ``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 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 OPENCV_FLANN_DATASET_H_ +#define OPENCV_FLANN_DATASET_H_ + +//! @cond IGNORED + +#include + +#include "opencv2/core/cvdef.h" +#include "opencv2/flann/defines.h" + +namespace cvflann +{ + +/** + * Class that implements a simple rectangular matrix stored in a memory buffer and + * provides convenient matrix-like access using the [] operators. + */ +template +class Matrix +{ +public: + typedef T type; + + size_t rows; + size_t cols; + size_t stride; + T* data; + + Matrix() : rows(0), cols(0), stride(0), data(NULL) + { + } + + Matrix(T* data_, size_t rows_, size_t cols_, size_t stride_ = 0) : + rows(rows_), cols(cols_), stride(stride_), data(data_) + { + if (stride==0) stride = cols; + } + + /** + * Convenience function for deallocating the storage data. + */ + CV_DEPRECATED void free() + { + fprintf(stderr, "The cvflann::Matrix::free() method is deprecated " + "and it does not do any memory deallocation any more. You are" + "responsible for deallocating the matrix memory (by doing" + "'delete[] matrix.data' for example)"); + } + + /** + * Operator that return a (pointer to a) row of the data. + */ + T* operator[](size_t index) const + { + return data+index*stride; + } +}; + + +class UntypedMatrix +{ +public: + size_t rows; + size_t cols; + void* data; + flann_datatype_t type; + + UntypedMatrix(void* data_, long rows_, long cols_) : + rows(rows_), cols(cols_), data(data_) + { + } + + ~UntypedMatrix() + { + } + + + template + Matrix as() + { + return Matrix((T*)data, rows, cols); + } +}; + + + +} + +//! @endcond + +#endif //OPENCV_FLANN_DATASET_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/miniflann.hpp b/3rdParty/opencv-4.11.0/opencv2/flann/miniflann.hpp index b8df92d758..6eea73a060 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/miniflann.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/flann/miniflann.hpp @@ -1,185 +1,185 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_MINIFLANN_HPP -#define OPENCV_MINIFLANN_HPP - -//! @cond IGNORED - -#include "opencv2/core.hpp" -#include "opencv2/flann/defines.h" - -namespace cv -{ - -namespace flann -{ - -enum FlannIndexType { - FLANN_INDEX_TYPE_8U = CV_8U, - FLANN_INDEX_TYPE_8S = CV_8S, - FLANN_INDEX_TYPE_16U = CV_16U, - FLANN_INDEX_TYPE_16S = CV_16S, - FLANN_INDEX_TYPE_32S = CV_32S, - FLANN_INDEX_TYPE_32F = CV_32F, - FLANN_INDEX_TYPE_64F = CV_64F, - FLANN_INDEX_TYPE_STRING, - FLANN_INDEX_TYPE_BOOL, - FLANN_INDEX_TYPE_ALGORITHM, - LAST_VALUE_FLANN_INDEX_TYPE = FLANN_INDEX_TYPE_ALGORITHM -}; - -struct CV_EXPORTS IndexParams -{ - IndexParams(); - ~IndexParams(); - - String getString(const String& key, const String& defaultVal=String()) const; - int getInt(const String& key, int defaultVal=-1) const; - double getDouble(const String& key, double defaultVal=-1) const; - - void setString(const String& key, const String& value); - void setInt(const String& key, int value); - void setDouble(const String& key, double value); - void setFloat(const String& key, float value); - void setBool(const String& key, bool value); - void setAlgorithm(int value); - - // FIXIT: replace by void write(FileStorage& fs) const + read() - void getAll(std::vector& names, - std::vector& types, - std::vector& strValues, - std::vector& numValues) const; - - void* params; - -private: - IndexParams(const IndexParams &); // copy disabled - IndexParams& operator=(const IndexParams &); // assign disabled -}; - -struct CV_EXPORTS KDTreeIndexParams : public IndexParams -{ - KDTreeIndexParams(int trees=4); -}; - -struct CV_EXPORTS LinearIndexParams : public IndexParams -{ - LinearIndexParams(); -}; - -struct CV_EXPORTS CompositeIndexParams : public IndexParams -{ - CompositeIndexParams(int trees = 4, int branching = 32, int iterations = 11, - cvflann::flann_centers_init_t centers_init = cvflann::FLANN_CENTERS_RANDOM, float cb_index = 0.2f ); -}; - -struct CV_EXPORTS AutotunedIndexParams : public IndexParams -{ - AutotunedIndexParams(float target_precision = 0.8f, float build_weight = 0.01f, - float memory_weight = 0, float sample_fraction = 0.1f); -}; - -struct CV_EXPORTS HierarchicalClusteringIndexParams : public IndexParams -{ - HierarchicalClusteringIndexParams(int branching = 32, - cvflann::flann_centers_init_t centers_init = cvflann::FLANN_CENTERS_RANDOM, int trees = 4, int leaf_size = 100 ); -}; - -struct CV_EXPORTS KMeansIndexParams : public IndexParams -{ - KMeansIndexParams(int branching = 32, int iterations = 11, - cvflann::flann_centers_init_t centers_init = cvflann::FLANN_CENTERS_RANDOM, float cb_index = 0.2f ); -}; - -struct CV_EXPORTS LshIndexParams : public IndexParams -{ - LshIndexParams(int table_number, int key_size, int multi_probe_level); -}; - -struct CV_EXPORTS SavedIndexParams : public IndexParams -{ - SavedIndexParams(const String& filename); -}; - -struct CV_EXPORTS SearchParams : public IndexParams -{ - SearchParams( int checks, float eps, bool sorted, bool explore_all_trees ); - SearchParams( int checks = 32, float eps = 0, bool sorted = true ); -}; - -class CV_EXPORTS_W Index -{ -public: - CV_WRAP Index(); - CV_WRAP Index(InputArray features, const IndexParams& params, cvflann::flann_distance_t distType=cvflann::FLANN_DIST_L2); - virtual ~Index(); - - CV_WRAP virtual void build(InputArray features, const IndexParams& params, cvflann::flann_distance_t distType=cvflann::FLANN_DIST_L2); - CV_WRAP virtual void knnSearch(InputArray query, OutputArray indices, - OutputArray dists, int knn, const SearchParams& params=SearchParams()); - - CV_WRAP virtual int radiusSearch(InputArray query, OutputArray indices, - OutputArray dists, double radius, int maxResults, - const SearchParams& params=SearchParams()); - - CV_WRAP virtual void save(const String& filename) const; - CV_WRAP virtual bool load(InputArray features, const String& filename); - CV_WRAP virtual void release(); - CV_WRAP cvflann::flann_distance_t getDistance() const; - CV_WRAP cvflann::flann_algorithm_t getAlgorithm() const; - -protected: - bool load_(const String& filename); - - cvflann::flann_distance_t distType; - cvflann::flann_algorithm_t algo; - int featureType; - void* index; - Mat features_clone; // index may store features pointer internally for searching, so avoid dangling pointers: https://github.com/opencv/opencv/issues/17553 -}; - -} } // namespace cv::flann - -//! @endcond - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_MINIFLANN_HPP +#define OPENCV_MINIFLANN_HPP + +//! @cond IGNORED + +#include "opencv2/core.hpp" +#include "opencv2/flann/defines.h" + +namespace cv +{ + +namespace flann +{ + +enum FlannIndexType { + FLANN_INDEX_TYPE_8U = CV_8U, + FLANN_INDEX_TYPE_8S = CV_8S, + FLANN_INDEX_TYPE_16U = CV_16U, + FLANN_INDEX_TYPE_16S = CV_16S, + FLANN_INDEX_TYPE_32S = CV_32S, + FLANN_INDEX_TYPE_32F = CV_32F, + FLANN_INDEX_TYPE_64F = CV_64F, + FLANN_INDEX_TYPE_STRING, + FLANN_INDEX_TYPE_BOOL, + FLANN_INDEX_TYPE_ALGORITHM, + LAST_VALUE_FLANN_INDEX_TYPE = FLANN_INDEX_TYPE_ALGORITHM +}; + +struct CV_EXPORTS IndexParams +{ + IndexParams(); + ~IndexParams(); + + String getString(const String& key, const String& defaultVal=String()) const; + int getInt(const String& key, int defaultVal=-1) const; + double getDouble(const String& key, double defaultVal=-1) const; + + void setString(const String& key, const String& value); + void setInt(const String& key, int value); + void setDouble(const String& key, double value); + void setFloat(const String& key, float value); + void setBool(const String& key, bool value); + void setAlgorithm(int value); + + // FIXIT: replace by void write(FileStorage& fs) const + read() + void getAll(std::vector& names, + std::vector& types, + std::vector& strValues, + std::vector& numValues) const; + + void* params; + +private: + IndexParams(const IndexParams &); // copy disabled + IndexParams& operator=(const IndexParams &); // assign disabled +}; + +struct CV_EXPORTS KDTreeIndexParams : public IndexParams +{ + KDTreeIndexParams(int trees=4); +}; + +struct CV_EXPORTS LinearIndexParams : public IndexParams +{ + LinearIndexParams(); +}; + +struct CV_EXPORTS CompositeIndexParams : public IndexParams +{ + CompositeIndexParams(int trees = 4, int branching = 32, int iterations = 11, + cvflann::flann_centers_init_t centers_init = cvflann::FLANN_CENTERS_RANDOM, float cb_index = 0.2f ); +}; + +struct CV_EXPORTS AutotunedIndexParams : public IndexParams +{ + AutotunedIndexParams(float target_precision = 0.8f, float build_weight = 0.01f, + float memory_weight = 0, float sample_fraction = 0.1f); +}; + +struct CV_EXPORTS HierarchicalClusteringIndexParams : public IndexParams +{ + HierarchicalClusteringIndexParams(int branching = 32, + cvflann::flann_centers_init_t centers_init = cvflann::FLANN_CENTERS_RANDOM, int trees = 4, int leaf_size = 100 ); +}; + +struct CV_EXPORTS KMeansIndexParams : public IndexParams +{ + KMeansIndexParams(int branching = 32, int iterations = 11, + cvflann::flann_centers_init_t centers_init = cvflann::FLANN_CENTERS_RANDOM, float cb_index = 0.2f ); +}; + +struct CV_EXPORTS LshIndexParams : public IndexParams +{ + LshIndexParams(int table_number, int key_size, int multi_probe_level); +}; + +struct CV_EXPORTS SavedIndexParams : public IndexParams +{ + SavedIndexParams(const String& filename); +}; + +struct CV_EXPORTS SearchParams : public IndexParams +{ + SearchParams( int checks, float eps, bool sorted, bool explore_all_trees ); + SearchParams( int checks = 32, float eps = 0, bool sorted = true ); +}; + +class CV_EXPORTS_W Index +{ +public: + CV_WRAP Index(); + CV_WRAP Index(InputArray features, const IndexParams& params, cvflann::flann_distance_t distType=cvflann::FLANN_DIST_L2); + virtual ~Index(); + + CV_WRAP virtual void build(InputArray features, const IndexParams& params, cvflann::flann_distance_t distType=cvflann::FLANN_DIST_L2); + CV_WRAP virtual void knnSearch(InputArray query, OutputArray indices, + OutputArray dists, int knn, const SearchParams& params=SearchParams()); + + CV_WRAP virtual int radiusSearch(InputArray query, OutputArray indices, + OutputArray dists, double radius, int maxResults, + const SearchParams& params=SearchParams()); + + CV_WRAP virtual void save(const String& filename) const; + CV_WRAP virtual bool load(InputArray features, const String& filename); + CV_WRAP virtual void release(); + CV_WRAP cvflann::flann_distance_t getDistance() const; + CV_WRAP cvflann::flann_algorithm_t getAlgorithm() const; + +protected: + bool load_(const String& filename); + + cvflann::flann_distance_t distType; + cvflann::flann_algorithm_t algo; + int featureType; + void* index; + Mat features_clone; // index may store features pointer internally for searching, so avoid dangling pointers: https://github.com/opencv/opencv/issues/17553 +}; + +} } // namespace cv::flann + +//! @endcond + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/nn_index.h b/3rdParty/opencv-4.11.0/opencv2/flann/nn_index.h index 23a1de7453..ae1dd9efed 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/nn_index.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/nn_index.h @@ -1,180 +1,180 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * 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 ``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 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 OPENCV_FLANN_NNINDEX_H -#define OPENCV_FLANN_NNINDEX_H - -#include "matrix.h" -#include "result_set.h" -#include "params.h" - -//! @cond IGNORED - -namespace cvflann -{ - -/** - * Nearest-neighbour index base class - */ -template -class NNIndex -{ - typedef typename Distance::ElementType ElementType; - typedef typename Distance::ResultType DistanceType; - -public: - - virtual ~NNIndex() {} - - /** - * \brief Builds the index - */ - virtual void buildIndex() = 0; - - /** - * \brief Perform k-nearest neighbor search - * \param[in] queries The query points for which to find the nearest neighbors - * \param[out] indices The indices of the nearest neighbors found - * \param[out] dists Distances to the nearest neighbors found - * \param[in] knn Number of nearest neighbors to return - * \param[in] params Search parameters - */ - virtual void knnSearch(const Matrix& queries, Matrix& indices, Matrix& dists, int knn, const SearchParams& params) - { - CV_Assert(queries.cols == veclen()); - CV_Assert(indices.rows >= queries.rows); - CV_Assert(dists.rows >= queries.rows); - CV_Assert(int(indices.cols) >= knn); - CV_Assert(int(dists.cols) >= knn); - -#if 0 - KNNResultSet resultSet(knn); - for (size_t i = 0; i < queries.rows; i++) { - resultSet.init(indices[i], dists[i]); - findNeighbors(resultSet, queries[i], params); - } -#else - KNNUniqueResultSet resultSet(knn); - for (size_t i = 0; i < queries.rows; i++) { - resultSet.clear(); - findNeighbors(resultSet, queries[i], params); - if (get_param(params,"sorted",true)) resultSet.sortAndCopy(indices[i], dists[i], knn); - else resultSet.copy(indices[i], dists[i], knn); - } -#endif - } - - /** - * \brief Perform radius search - * \param[in] query The query point - * \param[out] indices The indinces of the neighbors found within the given radius - * \param[out] dists The distances to the nearest neighbors found - * \param[in] radius The radius used for search - * \param[in] params Search parameters - * \returns Number of neighbors found - */ - virtual int radiusSearch(const Matrix& query, Matrix& indices, Matrix& dists, float radius, const SearchParams& params) - { - if (query.rows != 1) { - fprintf(stderr, "I can only search one feature at a time for range search\n"); - return -1; - } - CV_Assert(query.cols == veclen()); - CV_Assert(indices.cols == dists.cols); - - int n = 0; - int* indices_ptr = NULL; - DistanceType* dists_ptr = NULL; - if (indices.cols > 0) { - n = (int)indices.cols; - indices_ptr = indices[0]; - dists_ptr = dists[0]; - } - - RadiusUniqueResultSet resultSet((DistanceType)radius); - resultSet.clear(); - findNeighbors(resultSet, query[0], params); - if (n>0) { - if (get_param(params,"sorted",true)) resultSet.sortAndCopy(indices_ptr, dists_ptr, n); - else resultSet.copy(indices_ptr, dists_ptr, n); - } - - return (int)resultSet.size(); - } - - /** - * \brief Saves the index to a stream - * \param stream The stream to save the index to - */ - virtual void saveIndex(FILE* stream) = 0; - - /** - * \brief Loads the index from a stream - * \param stream The stream from which the index is loaded - */ - virtual void loadIndex(FILE* stream) = 0; - - /** - * \returns number of features in this index. - */ - virtual size_t size() const = 0; - - /** - * \returns The dimensionality of the features in this index. - */ - virtual size_t veclen() const = 0; - - /** - * \returns The amount of memory (in bytes) used by the index. - */ - virtual int usedMemory() const = 0; - - /** - * \returns The index type (kdtree, kmeans,...) - */ - virtual flann_algorithm_t getType() const = 0; - - /** - * \returns The index parameters - */ - virtual IndexParams getParameters() const = 0; - - - /** - * \brief Method that searches for nearest-neighbours - */ - virtual void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) = 0; -}; - -} - -//! @endcond - -#endif //OPENCV_FLANN_NNINDEX_H +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * 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 ``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 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 OPENCV_FLANN_NNINDEX_H +#define OPENCV_FLANN_NNINDEX_H + +#include "matrix.h" +#include "result_set.h" +#include "params.h" + +//! @cond IGNORED + +namespace cvflann +{ + +/** + * Nearest-neighbour index base class + */ +template +class NNIndex +{ + typedef typename Distance::ElementType ElementType; + typedef typename Distance::ResultType DistanceType; + +public: + + virtual ~NNIndex() {} + + /** + * \brief Builds the index + */ + virtual void buildIndex() = 0; + + /** + * \brief Perform k-nearest neighbor search + * \param[in] queries The query points for which to find the nearest neighbors + * \param[out] indices The indices of the nearest neighbors found + * \param[out] dists Distances to the nearest neighbors found + * \param[in] knn Number of nearest neighbors to return + * \param[in] params Search parameters + */ + virtual void knnSearch(const Matrix& queries, Matrix& indices, Matrix& dists, int knn, const SearchParams& params) + { + CV_Assert(queries.cols == veclen()); + CV_Assert(indices.rows >= queries.rows); + CV_Assert(dists.rows >= queries.rows); + CV_Assert(int(indices.cols) >= knn); + CV_Assert(int(dists.cols) >= knn); + +#if 0 + KNNResultSet resultSet(knn); + for (size_t i = 0; i < queries.rows; i++) { + resultSet.init(indices[i], dists[i]); + findNeighbors(resultSet, queries[i], params); + } +#else + KNNUniqueResultSet resultSet(knn); + for (size_t i = 0; i < queries.rows; i++) { + resultSet.clear(); + findNeighbors(resultSet, queries[i], params); + if (get_param(params,"sorted",true)) resultSet.sortAndCopy(indices[i], dists[i], knn); + else resultSet.copy(indices[i], dists[i], knn); + } +#endif + } + + /** + * \brief Perform radius search + * \param[in] query The query point + * \param[out] indices The indinces of the neighbors found within the given radius + * \param[out] dists The distances to the nearest neighbors found + * \param[in] radius The radius used for search + * \param[in] params Search parameters + * \returns Number of neighbors found + */ + virtual int radiusSearch(const Matrix& query, Matrix& indices, Matrix& dists, float radius, const SearchParams& params) + { + if (query.rows != 1) { + fprintf(stderr, "I can only search one feature at a time for range search\n"); + return -1; + } + CV_Assert(query.cols == veclen()); + CV_Assert(indices.cols == dists.cols); + + int n = 0; + int* indices_ptr = NULL; + DistanceType* dists_ptr = NULL; + if (indices.cols > 0) { + n = (int)indices.cols; + indices_ptr = indices[0]; + dists_ptr = dists[0]; + } + + RadiusUniqueResultSet resultSet((DistanceType)radius); + resultSet.clear(); + findNeighbors(resultSet, query[0], params); + if (n>0) { + if (get_param(params,"sorted",true)) resultSet.sortAndCopy(indices_ptr, dists_ptr, n); + else resultSet.copy(indices_ptr, dists_ptr, n); + } + + return (int)resultSet.size(); + } + + /** + * \brief Saves the index to a stream + * \param stream The stream to save the index to + */ + virtual void saveIndex(FILE* stream) = 0; + + /** + * \brief Loads the index from a stream + * \param stream The stream from which the index is loaded + */ + virtual void loadIndex(FILE* stream) = 0; + + /** + * \returns number of features in this index. + */ + virtual size_t size() const = 0; + + /** + * \returns The dimensionality of the features in this index. + */ + virtual size_t veclen() const = 0; + + /** + * \returns The amount of memory (in bytes) used by the index. + */ + virtual int usedMemory() const = 0; + + /** + * \returns The index type (kdtree, kmeans,...) + */ + virtual flann_algorithm_t getType() const = 0; + + /** + * \returns The index parameters + */ + virtual IndexParams getParameters() const = 0; + + + /** + * \brief Method that searches for nearest-neighbours + */ + virtual void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) = 0; +}; + +} + +//! @endcond + +#endif //OPENCV_FLANN_NNINDEX_H diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/object_factory.h b/3rdParty/opencv-4.11.0/opencv2/flann/object_factory.h index 5cc45ad1b3..1eb26ad75d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/object_factory.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/object_factory.h @@ -1,95 +1,95 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * 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 ``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 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 OPENCV_FLANN_OBJECT_FACTORY_H_ -#define OPENCV_FLANN_OBJECT_FACTORY_H_ - -//! @cond IGNORED - -#include - -namespace cvflann -{ - -class CreatorNotFound -{ -}; - -template -class ObjectFactory -{ - typedef ObjectFactory ThisClass; - typedef std::map ObjectRegistry; - - // singleton class, private constructor - ObjectFactory() {} - -public: - - bool subscribe(UniqueIdType id, ObjectCreator creator) - { - if (object_registry.find(id) != object_registry.end()) return false; - - object_registry[id] = creator; - return true; - } - - bool unregister(UniqueIdType id) - { - return object_registry.erase(id) == 1; - } - - ObjectCreator create(UniqueIdType id) - { - typename ObjectRegistry::const_iterator iter = object_registry.find(id); - - if (iter == object_registry.end()) { - throw CreatorNotFound(); - } - - return iter->second; - } - - static ThisClass& instance() - { - static ThisClass the_factory; - return the_factory; - } -private: - ObjectRegistry object_registry; -}; - -} - -//! @endcond - -#endif /* OPENCV_FLANN_OBJECT_FACTORY_H_ */ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * 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 ``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 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 OPENCV_FLANN_OBJECT_FACTORY_H_ +#define OPENCV_FLANN_OBJECT_FACTORY_H_ + +//! @cond IGNORED + +#include + +namespace cvflann +{ + +class CreatorNotFound +{ +}; + +template +class ObjectFactory +{ + typedef ObjectFactory ThisClass; + typedef std::map ObjectRegistry; + + // singleton class, private constructor + ObjectFactory() {} + +public: + + bool subscribe(UniqueIdType id, ObjectCreator creator) + { + if (object_registry.find(id) != object_registry.end()) return false; + + object_registry[id] = creator; + return true; + } + + bool unregister(UniqueIdType id) + { + return object_registry.erase(id) == 1; + } + + ObjectCreator create(UniqueIdType id) + { + typename ObjectRegistry::const_iterator iter = object_registry.find(id); + + if (iter == object_registry.end()) { + throw CreatorNotFound(); + } + + return iter->second; + } + + static ThisClass& instance() + { + static ThisClass the_factory; + return the_factory; + } +private: + ObjectRegistry object_registry; +}; + +} + +//! @endcond + +#endif /* OPENCV_FLANN_OBJECT_FACTORY_H_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/params.h b/3rdParty/opencv-4.11.0/opencv2/flann/params.h index 1a8e127035..04aac83a42 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/params.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/params.h @@ -1,126 +1,126 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2011 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2011 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * 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 ``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 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 OPENCV_FLANN_PARAMS_H_ -#define OPENCV_FLANN_PARAMS_H_ - -//! @cond IGNORED - -#include "any.h" -#include "general.h" -#include -#include - - -namespace cvflann -{ - -typedef std::map IndexParams; - -struct SearchParams : public IndexParams -{ - SearchParams(int checks = 32, float eps = 0, bool sorted = true ) - { - init(checks, eps, sorted, false); - } - - SearchParams(int checks, float eps, bool sorted, bool explore_all_trees ) - { - init(checks, eps, sorted, explore_all_trees); - } - - void init(int checks = 32, float eps = 0, bool sorted = true, bool explore_all_trees = false ) - { - // how many leafs to visit when searching for neighbours (-1 for unlimited) - (*this)["checks"] = checks; - // search for eps-approximate neighbours (default: 0) - (*this)["eps"] = eps; - // only for radius search, require neighbours sorted by distance (default: true) - (*this)["sorted"] = sorted; - // if false, search stops at the tree reaching the number of max checks (original behavior). - // When true, we do a descent in each tree and. Like before the alternative paths - // stored in the heap are not be processed further when max checks is reached. - (*this)["explore_all_trees"] = explore_all_trees; - } -}; - - -template -T get_param(const IndexParams& params, const cv::String& name, const T& default_value) -{ - IndexParams::const_iterator it = params.find(name); - if (it != params.end()) { - try { - return it->second.cast(); - } catch (const std::exception& e) { - CV_Error_(cv::Error::StsBadArg, - ("FLANN '%s' param type mismatch: %s", name.c_str(), e.what())); - } - } - else { - return default_value; - } -} - -template -T get_param(const IndexParams& params, const cv::String& name) -{ - IndexParams::const_iterator it = params.find(name); - if (it != params.end()) { - try { - return it->second.cast(); - } catch (const std::exception& e) { - CV_Error_(cv::Error::StsBadArg, - ("FLANN '%s' param type mismatch: %s", name.c_str(), e.what())); - } - } - else { - FLANN_THROW(cv::Error::StsBadArg, cv::String("Missing parameter '")+name+cv::String("' in the parameters given")); - } -} - -inline void print_params(const IndexParams& params, std::ostream& stream) -{ - IndexParams::const_iterator it; - - for(it=params.begin(); it!=params.end(); ++it) { - stream << it->first << " : " << it->second << std::endl; - } -} - -inline void print_params(const IndexParams& params) -{ - print_params(params, std::cout); -} - -} - -//! @endcond - -#endif /* OPENCV_FLANN_PARAMS_H_ */ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2011 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2011 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * 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 ``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 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 OPENCV_FLANN_PARAMS_H_ +#define OPENCV_FLANN_PARAMS_H_ + +//! @cond IGNORED + +#include "any.h" +#include "general.h" +#include +#include + + +namespace cvflann +{ + +typedef std::map IndexParams; + +struct SearchParams : public IndexParams +{ + SearchParams(int checks = 32, float eps = 0, bool sorted = true ) + { + init(checks, eps, sorted, false); + } + + SearchParams(int checks, float eps, bool sorted, bool explore_all_trees ) + { + init(checks, eps, sorted, explore_all_trees); + } + + void init(int checks = 32, float eps = 0, bool sorted = true, bool explore_all_trees = false ) + { + // how many leafs to visit when searching for neighbours (-1 for unlimited) + (*this)["checks"] = checks; + // search for eps-approximate neighbours (default: 0) + (*this)["eps"] = eps; + // only for radius search, require neighbours sorted by distance (default: true) + (*this)["sorted"] = sorted; + // if false, search stops at the tree reaching the number of max checks (original behavior). + // When true, we do a descent in each tree and. Like before the alternative paths + // stored in the heap are not be processed further when max checks is reached. + (*this)["explore_all_trees"] = explore_all_trees; + } +}; + + +template +T get_param(const IndexParams& params, const cv::String& name, const T& default_value) +{ + IndexParams::const_iterator it = params.find(name); + if (it != params.end()) { + try { + return it->second.cast(); + } catch (const std::exception& e) { + CV_Error_(cv::Error::StsBadArg, + ("FLANN '%s' param type mismatch: %s", name.c_str(), e.what())); + } + } + else { + return default_value; + } +} + +template +T get_param(const IndexParams& params, const cv::String& name) +{ + IndexParams::const_iterator it = params.find(name); + if (it != params.end()) { + try { + return it->second.cast(); + } catch (const std::exception& e) { + CV_Error_(cv::Error::StsBadArg, + ("FLANN '%s' param type mismatch: %s", name.c_str(), e.what())); + } + } + else { + FLANN_THROW(cv::Error::StsBadArg, cv::String("Missing parameter '")+name+cv::String("' in the parameters given")); + } +} + +inline void print_params(const IndexParams& params, std::ostream& stream) +{ + IndexParams::const_iterator it; + + for(it=params.begin(); it!=params.end(); ++it) { + stream << it->first << " : " << it->second << std::endl; + } +} + +inline void print_params(const IndexParams& params) +{ + print_params(params, std::cout); +} + +} + +//! @endcond + +#endif /* OPENCV_FLANN_PARAMS_H_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/random.h b/3rdParty/opencv-4.11.0/opencv2/flann/random.h index 5a12ef3046..4ad50c43a0 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/random.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/random.h @@ -1,156 +1,156 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * 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 ``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 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 OPENCV_FLANN_RANDOM_H -#define OPENCV_FLANN_RANDOM_H - -//! @cond IGNORED - -#include -#include -#include - -namespace cvflann -{ - -inline int rand() -{ -#ifndef OPENCV_FLANN_USE_STD_RAND -# if INT_MAX == RAND_MAX - int v = cv::theRNG().next() & INT_MAX; -# else - int v = cv::theRNG().uniform(0, RAND_MAX + 1); -# endif -#else - int v = std::rand(); -#endif // OPENCV_FLANN_USE_STD_RAND - return v; -} - -/** - * Seeds the random number generator - * @param seed Random seed - */ -inline void seed_random(unsigned int seed) -{ -#ifndef OPENCV_FLANN_USE_STD_RAND - cv::theRNG() = cv::RNG(seed); -#else - std::srand(seed); -#endif -} - -/* - * Generates a random double value. - */ -/** - * Generates a random double value. - * @param high Upper limit - * @param low Lower limit - * @return Random double value - */ -inline double rand_double(double high = 1.0, double low = 0) -{ - return low + ((high-low) * (rand() / (RAND_MAX + 1.0))); -} - -/** - * Generates a random integer value. - * @param high Upper limit - * @param low Lower limit - * @return Random integer value - */ -inline int rand_int(int high = RAND_MAX, int low = 0) -{ - return low + (int) ( double(high-low) * (rand() / (RAND_MAX + 1.0))); -} - -/** - * Random number generator that returns a distinct number from - * the [0,n) interval each time. - */ -class UniqueRandom -{ - std::vector vals_; - int size_; - int counter_; - -public: - /** - * Constructor. - * @param n Size of the interval from which to generate - */ - UniqueRandom(int n) - { - init(n); - } - - /** - * Initializes the number generator. - * @param n the size of the interval from which to generate random numbers. - */ - void init(int n) - { - // create and initialize an array of size n - vals_.resize(n); - size_ = n; - for (int i = 0; i < size_; ++i) vals_[i] = i; - - // shuffle the elements in the array -#ifndef OPENCV_FLANN_USE_STD_RAND - cv::randShuffle(vals_); -#else - std::random_shuffle(vals_.begin(), vals_.end()); -#endif - - counter_ = 0; - } - - /** - * Return a distinct random integer in greater or equal to 0 and less - * than 'n' on each call. It should be called maximum 'n' times. - * Returns: a random integer - */ - int next() - { - if (counter_ == size_) { - return -1; - } - else { - return vals_[counter_++]; - } - } -}; - -} - -//! @endcond - -#endif //OPENCV_FLANN_RANDOM_H +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * 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 ``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 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 OPENCV_FLANN_RANDOM_H +#define OPENCV_FLANN_RANDOM_H + +//! @cond IGNORED + +#include +#include +#include + +namespace cvflann +{ + +inline int rand() +{ +#ifndef OPENCV_FLANN_USE_STD_RAND +# if INT_MAX == RAND_MAX + int v = cv::theRNG().next() & INT_MAX; +# else + int v = cv::theRNG().uniform(0, RAND_MAX + 1); +# endif +#else + int v = std::rand(); +#endif // OPENCV_FLANN_USE_STD_RAND + return v; +} + +/** + * Seeds the random number generator + * @param seed Random seed + */ +inline void seed_random(unsigned int seed) +{ +#ifndef OPENCV_FLANN_USE_STD_RAND + cv::theRNG() = cv::RNG(seed); +#else + std::srand(seed); +#endif +} + +/* + * Generates a random double value. + */ +/** + * Generates a random double value. + * @param high Upper limit + * @param low Lower limit + * @return Random double value + */ +inline double rand_double(double high = 1.0, double low = 0) +{ + return low + ((high-low) * (rand() / (RAND_MAX + 1.0))); +} + +/** + * Generates a random integer value. + * @param high Upper limit + * @param low Lower limit + * @return Random integer value + */ +inline int rand_int(int high = RAND_MAX, int low = 0) +{ + return low + (int) ( double(high-low) * (rand() / (RAND_MAX + 1.0))); +} + +/** + * Random number generator that returns a distinct number from + * the [0,n) interval each time. + */ +class UniqueRandom +{ + std::vector vals_; + int size_; + int counter_; + +public: + /** + * Constructor. + * @param n Size of the interval from which to generate + */ + UniqueRandom(int n) + { + init(n); + } + + /** + * Initializes the number generator. + * @param n the size of the interval from which to generate random numbers. + */ + void init(int n) + { + // create and initialize an array of size n + vals_.resize(n); + size_ = n; + for (int i = 0; i < size_; ++i) vals_[i] = i; + + // shuffle the elements in the array +#ifndef OPENCV_FLANN_USE_STD_RAND + cv::randShuffle(vals_); +#else + std::random_shuffle(vals_.begin(), vals_.end()); +#endif + + counter_ = 0; + } + + /** + * Return a distinct random integer in greater or equal to 0 and less + * than 'n' on each call. It should be called maximum 'n' times. + * Returns: a random integer + */ + int next() + { + if (counter_ == size_) { + return -1; + } + else { + return vals_[counter_++]; + } + } +}; + +} + +//! @endcond + +#endif //OPENCV_FLANN_RANDOM_H diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/result_set.h b/3rdParty/opencv-4.11.0/opencv2/flann/result_set.h index aa679df71c..08f711c694 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/result_set.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/result_set.h @@ -1,548 +1,548 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * 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 ``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 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 OPENCV_FLANN_RESULTSET_H -#define OPENCV_FLANN_RESULTSET_H - -//! @cond IGNORED - -#include -#include -#include -#include -#include -#include - -#include "opencv2/core/base.hpp" -#include "opencv2/core/cvdef.h" - -namespace cvflann -{ - -/* This record represents a branch point when finding neighbors in - the tree. It contains a record of the minimum distance to the query - point, as well as the node at which the search resumes. - */ - -template -struct BranchStruct -{ - T node; /* Tree node at which search resumes */ - DistanceType mindist; /* Minimum distance to query for all nodes below. */ - - BranchStruct() {} - BranchStruct(const T& aNode, DistanceType dist) : node(aNode), mindist(dist) {} - - bool operator<(const BranchStruct& rhs) const - { - return mindist -class ResultSet -{ -public: - virtual ~ResultSet() {} - - virtual bool full() const = 0; - - virtual void addPoint(DistanceType dist, int index) = 0; - - virtual DistanceType worstDist() const = 0; - -}; - -/** - * KNNSimpleResultSet does not ensure that the element it holds are unique. - * Is used in those cases where the nearest neighbour algorithm used does not - * attempt to insert the same element multiple times. - */ -template -class KNNSimpleResultSet : public ResultSet -{ - int* indices; - DistanceType* dists; - int capacity; - int count; - DistanceType worst_distance_; - -public: - KNNSimpleResultSet(int capacity_) : capacity(capacity_), count(0) - { - } - - void init(int* indices_, DistanceType* dists_) - { - indices = indices_; - dists = dists_; - count = 0; - worst_distance_ = (std::numeric_limits::max)(); - dists[capacity-1] = worst_distance_; - } - - size_t size() const - { - return count; - } - - bool full() const CV_OVERRIDE - { - return count == capacity; - } - - - void addPoint(DistanceType dist, int index) CV_OVERRIDE - { - if (dist >= worst_distance_) return; - int i; - for (i=count; i>0; --i) { -#ifdef FLANN_FIRST_MATCH - if ( (dists[i-1]>dist) || ((dist==dists[i-1])&&(indices[i-1]>index)) ) -#else - if (dists[i-1]>dist) -#endif - { - if (i -class KNNResultSet : public ResultSet -{ - int* indices; - DistanceType* dists; - int capacity; - int count; - DistanceType worst_distance_; - -public: - KNNResultSet(int capacity_) - : indices(NULL), dists(NULL), capacity(capacity_), count(0), worst_distance_(0) - { - } - - void init(int* indices_, DistanceType* dists_) - { - indices = indices_; - dists = dists_; - count = 0; - worst_distance_ = (std::numeric_limits::max)(); - dists[capacity-1] = worst_distance_; - } - - size_t size() const - { - return count; - } - - bool full() const CV_OVERRIDE - { - return count == capacity; - } - - - void addPoint(DistanceType dist, int index) CV_OVERRIDE - { - CV_DbgAssert(indices); - CV_DbgAssert(dists); - if (dist >= worst_distance_) return; - int i; - for (i = count; i > 0; --i) { -#ifdef FLANN_FIRST_MATCH - if ( (dists[i-1]<=dist) && ((dist!=dists[i-1])||(indices[i-1]<=index)) ) -#else - if (dists[i-1]<=dist) -#endif - { - // Check for duplicate indices - for (int j = i; dists[j] == dist && j--;) { - if (indices[j] == index) { - return; - } - } - break; - } - } - - if (count < capacity) ++count; - for (int j = count-1; j > i; --j) { - dists[j] = dists[j-1]; - indices[j] = indices[j-1]; - } - dists[i] = dist; - indices[i] = index; - worst_distance_ = dists[capacity-1]; - } - - DistanceType worstDist() const CV_OVERRIDE - { - return worst_distance_; - } -}; - - -/** - * A result-set class used when performing a radius based search. - */ -template -class RadiusResultSet : public ResultSet -{ - DistanceType radius; - int* indices; - DistanceType* dists; - size_t capacity; - size_t count; - -public: - RadiusResultSet(DistanceType radius_, int* indices_, DistanceType* dists_, int capacity_) : - radius(radius_), indices(indices_), dists(dists_), capacity(capacity_) - { - init(); - } - - ~RadiusResultSet() - { - } - - void init() - { - count = 0; - } - - size_t size() const - { - return count; - } - - bool full() const - { - return true; - } - - void addPoint(DistanceType dist, int index) - { - if (dist0)&&(count < capacity)) { - dists[count] = dist; - indices[count] = index; - } - count++; - } - } - - DistanceType worstDist() const - { - return radius; - } - -}; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -/** Class that holds the k NN neighbors - * Faster than KNNResultSet as it uses a binary heap and does not maintain two arrays - */ -template -class UniqueResultSet : public ResultSet -{ -public: - struct DistIndex - { - DistIndex(DistanceType dist, unsigned int index) : - dist_(dist), index_(index) - { - } - bool operator<(const DistIndex dist_index) const - { - return (dist_ < dist_index.dist_) || ((dist_ == dist_index.dist_) && index_ < dist_index.index_); - } - DistanceType dist_; - unsigned int index_; - }; - - /** Default constructor */ - UniqueResultSet() : - is_full_(false), worst_distance_(std::numeric_limits::max()) - { - } - - /** Check the status of the set - * @return true if we have k NN - */ - inline bool full() const CV_OVERRIDE - { - return is_full_; - } - - /** Remove all elements in the set - */ - virtual void clear() = 0; - - /** Copy the set to two C arrays - * @param indices pointer to a C array of indices - * @param dist pointer to a C array of distances - * @param n_neighbors the number of neighbors to copy - */ - virtual void copy(int* indices, DistanceType* dist, int n_neighbors = -1) const - { - if (n_neighbors < 0) { - for (typename std::set::const_iterator dist_index = dist_indices_.begin(), dist_index_end = - dist_indices_.end(); dist_index != dist_index_end; ++dist_index, ++indices, ++dist) { - *indices = dist_index->index_; - *dist = dist_index->dist_; - } - } - else { - int i = 0; - for (typename std::set::const_iterator dist_index = dist_indices_.begin(), dist_index_end = - dist_indices_.end(); (dist_index != dist_index_end) && (i < n_neighbors); ++dist_index, ++indices, ++dist, ++i) { - *indices = dist_index->index_; - *dist = dist_index->dist_; - } - } - } - - /** Copy the set to two C arrays but sort it according to the distance first - * @param indices pointer to a C array of indices - * @param dist pointer to a C array of distances - * @param n_neighbors the number of neighbors to copy - */ - virtual void sortAndCopy(int* indices, DistanceType* dist, int n_neighbors = -1) const - { - copy(indices, dist, n_neighbors); - } - - /** The number of neighbors in the set - */ - size_t size() const - { - return dist_indices_.size(); - } - - /** The distance of the furthest neighbor - * If we don't have enough neighbors, it returns the max possible value - */ - inline DistanceType worstDist() const CV_OVERRIDE - { - return worst_distance_; - } -protected: - /** Flag to say if the set is full */ - bool is_full_; - - /** The worst distance found so far */ - DistanceType worst_distance_; - - /** The best candidates so far */ - std::set dist_indices_; -}; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -/** Class that holds the k NN neighbors - * Faster than KNNResultSet as it uses a binary heap and does not maintain two arrays - */ -template -class KNNUniqueResultSet : public UniqueResultSet -{ -public: - /** Constructor - * @param capacity the number of neighbors to store at max - */ - KNNUniqueResultSet(unsigned int capacity) : capacity_(capacity) - { - this->is_full_ = false; - this->clear(); - } - - /** Add a possible candidate to the best neighbors - * @param dist distance for that neighbor - * @param index index of that neighbor - */ - inline void addPoint(DistanceType dist, int index) CV_OVERRIDE - { - // Don't do anything if we are worse than the worst - if (dist >= worst_distance_) return; - dist_indices_.insert(DistIndex(dist, index)); - - if (is_full_) { - if (dist_indices_.size() > capacity_) { - dist_indices_.erase(*dist_indices_.rbegin()); - worst_distance_ = dist_indices_.rbegin()->dist_; - } - } - else if (dist_indices_.size() == capacity_) { - is_full_ = true; - worst_distance_ = dist_indices_.rbegin()->dist_; - } - } - - /** Remove all elements in the set - */ - void clear() CV_OVERRIDE - { - dist_indices_.clear(); - worst_distance_ = std::numeric_limits::max(); - is_full_ = false; - } - -protected: - typedef typename UniqueResultSet::DistIndex DistIndex; - using UniqueResultSet::is_full_; - using UniqueResultSet::worst_distance_; - using UniqueResultSet::dist_indices_; - - /** The number of neighbors to keep */ - unsigned int capacity_; -}; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -/** Class that holds the radius nearest neighbors - * It is more accurate than RadiusResult as it is not limited in the number of neighbors - */ -template -class RadiusUniqueResultSet : public UniqueResultSet -{ -public: - /** Constructor - * @param radius the maximum distance of a neighbor - */ - RadiusUniqueResultSet(DistanceType radius) : - radius_(radius) - { - is_full_ = true; - } - - /** Add a possible candidate to the best neighbors - * @param dist distance for that neighbor - * @param index index of that neighbor - */ - void addPoint(DistanceType dist, int index) CV_OVERRIDE - { - if (dist <= radius_) dist_indices_.insert(DistIndex(dist, index)); - } - - /** Remove all elements in the set - */ - inline void clear() CV_OVERRIDE - { - dist_indices_.clear(); - } - - - /** Check the status of the set - * @return alwys false - */ - inline bool full() const CV_OVERRIDE - { - return true; - } - - /** The distance of the furthest neighbor - * If we don't have enough neighbors, it returns the max possible value - */ - inline DistanceType worstDist() const CV_OVERRIDE - { - return radius_; - } -private: - typedef typename UniqueResultSet::DistIndex DistIndex; - using UniqueResultSet::dist_indices_; - using UniqueResultSet::is_full_; - - /** The furthest distance a neighbor can be */ - DistanceType radius_; -}; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -/** Class that holds the k NN neighbors within a radius distance - */ -template -class KNNRadiusUniqueResultSet : public KNNUniqueResultSet -{ -public: - /** Constructor - * @param capacity the number of neighbors to store at max - * @param radius the maximum distance of a neighbor - */ - KNNRadiusUniqueResultSet(unsigned int capacity, DistanceType radius) - { - this->capacity_ = capacity; - this->radius_ = radius; - this->dist_indices_.reserve(capacity_); - this->clear(); - } - - /** Remove all elements in the set - */ - void clear() - { - dist_indices_.clear(); - worst_distance_ = radius_; - is_full_ = false; - } -private: - using KNNUniqueResultSet::dist_indices_; - using KNNUniqueResultSet::is_full_; - using KNNUniqueResultSet::worst_distance_; - - /** The maximum number of neighbors to consider */ - unsigned int capacity_; - - /** The maximum distance of a neighbor */ - DistanceType radius_; -}; -} - -//! @endcond - -#endif //OPENCV_FLANN_RESULTSET_H +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * 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 ``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 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 OPENCV_FLANN_RESULTSET_H +#define OPENCV_FLANN_RESULTSET_H + +//! @cond IGNORED + +#include +#include +#include +#include +#include +#include + +#include "opencv2/core/base.hpp" +#include "opencv2/core/cvdef.h" + +namespace cvflann +{ + +/* This record represents a branch point when finding neighbors in + the tree. It contains a record of the minimum distance to the query + point, as well as the node at which the search resumes. + */ + +template +struct BranchStruct +{ + T node; /* Tree node at which search resumes */ + DistanceType mindist; /* Minimum distance to query for all nodes below. */ + + BranchStruct() {} + BranchStruct(const T& aNode, DistanceType dist) : node(aNode), mindist(dist) {} + + bool operator<(const BranchStruct& rhs) const + { + return mindist +class ResultSet +{ +public: + virtual ~ResultSet() {} + + virtual bool full() const = 0; + + virtual void addPoint(DistanceType dist, int index) = 0; + + virtual DistanceType worstDist() const = 0; + +}; + +/** + * KNNSimpleResultSet does not ensure that the element it holds are unique. + * Is used in those cases where the nearest neighbour algorithm used does not + * attempt to insert the same element multiple times. + */ +template +class KNNSimpleResultSet : public ResultSet +{ + int* indices; + DistanceType* dists; + int capacity; + int count; + DistanceType worst_distance_; + +public: + KNNSimpleResultSet(int capacity_) : capacity(capacity_), count(0) + { + } + + void init(int* indices_, DistanceType* dists_) + { + indices = indices_; + dists = dists_; + count = 0; + worst_distance_ = (std::numeric_limits::max)(); + dists[capacity-1] = worst_distance_; + } + + size_t size() const + { + return count; + } + + bool full() const CV_OVERRIDE + { + return count == capacity; + } + + + void addPoint(DistanceType dist, int index) CV_OVERRIDE + { + if (dist >= worst_distance_) return; + int i; + for (i=count; i>0; --i) { +#ifdef FLANN_FIRST_MATCH + if ( (dists[i-1]>dist) || ((dist==dists[i-1])&&(indices[i-1]>index)) ) +#else + if (dists[i-1]>dist) +#endif + { + if (i +class KNNResultSet : public ResultSet +{ + int* indices; + DistanceType* dists; + int capacity; + int count; + DistanceType worst_distance_; + +public: + KNNResultSet(int capacity_) + : indices(NULL), dists(NULL), capacity(capacity_), count(0), worst_distance_(0) + { + } + + void init(int* indices_, DistanceType* dists_) + { + indices = indices_; + dists = dists_; + count = 0; + worst_distance_ = (std::numeric_limits::max)(); + dists[capacity-1] = worst_distance_; + } + + size_t size() const + { + return count; + } + + bool full() const CV_OVERRIDE + { + return count == capacity; + } + + + void addPoint(DistanceType dist, int index) CV_OVERRIDE + { + CV_DbgAssert(indices); + CV_DbgAssert(dists); + if (dist >= worst_distance_) return; + int i; + for (i = count; i > 0; --i) { +#ifdef FLANN_FIRST_MATCH + if ( (dists[i-1]<=dist) && ((dist!=dists[i-1])||(indices[i-1]<=index)) ) +#else + if (dists[i-1]<=dist) +#endif + { + // Check for duplicate indices + for (int j = i; dists[j] == dist && j--;) { + if (indices[j] == index) { + return; + } + } + break; + } + } + + if (count < capacity) ++count; + for (int j = count-1; j > i; --j) { + dists[j] = dists[j-1]; + indices[j] = indices[j-1]; + } + dists[i] = dist; + indices[i] = index; + worst_distance_ = dists[capacity-1]; + } + + DistanceType worstDist() const CV_OVERRIDE + { + return worst_distance_; + } +}; + + +/** + * A result-set class used when performing a radius based search. + */ +template +class RadiusResultSet : public ResultSet +{ + DistanceType radius; + int* indices; + DistanceType* dists; + size_t capacity; + size_t count; + +public: + RadiusResultSet(DistanceType radius_, int* indices_, DistanceType* dists_, int capacity_) : + radius(radius_), indices(indices_), dists(dists_), capacity(capacity_) + { + init(); + } + + ~RadiusResultSet() + { + } + + void init() + { + count = 0; + } + + size_t size() const + { + return count; + } + + bool full() const + { + return true; + } + + void addPoint(DistanceType dist, int index) + { + if (dist0)&&(count < capacity)) { + dists[count] = dist; + indices[count] = index; + } + count++; + } + } + + DistanceType worstDist() const + { + return radius; + } + +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +/** Class that holds the k NN neighbors + * Faster than KNNResultSet as it uses a binary heap and does not maintain two arrays + */ +template +class UniqueResultSet : public ResultSet +{ +public: + struct DistIndex + { + DistIndex(DistanceType dist, unsigned int index) : + dist_(dist), index_(index) + { + } + bool operator<(const DistIndex dist_index) const + { + return (dist_ < dist_index.dist_) || ((dist_ == dist_index.dist_) && index_ < dist_index.index_); + } + DistanceType dist_; + unsigned int index_; + }; + + /** Default constructor */ + UniqueResultSet() : + is_full_(false), worst_distance_(std::numeric_limits::max()) + { + } + + /** Check the status of the set + * @return true if we have k NN + */ + inline bool full() const CV_OVERRIDE + { + return is_full_; + } + + /** Remove all elements in the set + */ + virtual void clear() = 0; + + /** Copy the set to two C arrays + * @param indices pointer to a C array of indices + * @param dist pointer to a C array of distances + * @param n_neighbors the number of neighbors to copy + */ + virtual void copy(int* indices, DistanceType* dist, int n_neighbors = -1) const + { + if (n_neighbors < 0) { + for (typename std::set::const_iterator dist_index = dist_indices_.begin(), dist_index_end = + dist_indices_.end(); dist_index != dist_index_end; ++dist_index, ++indices, ++dist) { + *indices = dist_index->index_; + *dist = dist_index->dist_; + } + } + else { + int i = 0; + for (typename std::set::const_iterator dist_index = dist_indices_.begin(), dist_index_end = + dist_indices_.end(); (dist_index != dist_index_end) && (i < n_neighbors); ++dist_index, ++indices, ++dist, ++i) { + *indices = dist_index->index_; + *dist = dist_index->dist_; + } + } + } + + /** Copy the set to two C arrays but sort it according to the distance first + * @param indices pointer to a C array of indices + * @param dist pointer to a C array of distances + * @param n_neighbors the number of neighbors to copy + */ + virtual void sortAndCopy(int* indices, DistanceType* dist, int n_neighbors = -1) const + { + copy(indices, dist, n_neighbors); + } + + /** The number of neighbors in the set + */ + size_t size() const + { + return dist_indices_.size(); + } + + /** The distance of the furthest neighbor + * If we don't have enough neighbors, it returns the max possible value + */ + inline DistanceType worstDist() const CV_OVERRIDE + { + return worst_distance_; + } +protected: + /** Flag to say if the set is full */ + bool is_full_; + + /** The worst distance found so far */ + DistanceType worst_distance_; + + /** The best candidates so far */ + std::set dist_indices_; +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +/** Class that holds the k NN neighbors + * Faster than KNNResultSet as it uses a binary heap and does not maintain two arrays + */ +template +class KNNUniqueResultSet : public UniqueResultSet +{ +public: + /** Constructor + * @param capacity the number of neighbors to store at max + */ + KNNUniqueResultSet(unsigned int capacity) : capacity_(capacity) + { + this->is_full_ = false; + this->clear(); + } + + /** Add a possible candidate to the best neighbors + * @param dist distance for that neighbor + * @param index index of that neighbor + */ + inline void addPoint(DistanceType dist, int index) CV_OVERRIDE + { + // Don't do anything if we are worse than the worst + if (dist >= worst_distance_) return; + dist_indices_.insert(DistIndex(dist, index)); + + if (is_full_) { + if (dist_indices_.size() > capacity_) { + dist_indices_.erase(*dist_indices_.rbegin()); + worst_distance_ = dist_indices_.rbegin()->dist_; + } + } + else if (dist_indices_.size() == capacity_) { + is_full_ = true; + worst_distance_ = dist_indices_.rbegin()->dist_; + } + } + + /** Remove all elements in the set + */ + void clear() CV_OVERRIDE + { + dist_indices_.clear(); + worst_distance_ = std::numeric_limits::max(); + is_full_ = false; + } + +protected: + typedef typename UniqueResultSet::DistIndex DistIndex; + using UniqueResultSet::is_full_; + using UniqueResultSet::worst_distance_; + using UniqueResultSet::dist_indices_; + + /** The number of neighbors to keep */ + unsigned int capacity_; +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +/** Class that holds the radius nearest neighbors + * It is more accurate than RadiusResult as it is not limited in the number of neighbors + */ +template +class RadiusUniqueResultSet : public UniqueResultSet +{ +public: + /** Constructor + * @param radius the maximum distance of a neighbor + */ + RadiusUniqueResultSet(DistanceType radius) : + radius_(radius) + { + is_full_ = true; + } + + /** Add a possible candidate to the best neighbors + * @param dist distance for that neighbor + * @param index index of that neighbor + */ + void addPoint(DistanceType dist, int index) CV_OVERRIDE + { + if (dist <= radius_) dist_indices_.insert(DistIndex(dist, index)); + } + + /** Remove all elements in the set + */ + inline void clear() CV_OVERRIDE + { + dist_indices_.clear(); + } + + + /** Check the status of the set + * @return alwys false + */ + inline bool full() const CV_OVERRIDE + { + return true; + } + + /** The distance of the furthest neighbor + * If we don't have enough neighbors, it returns the max possible value + */ + inline DistanceType worstDist() const CV_OVERRIDE + { + return radius_; + } +private: + typedef typename UniqueResultSet::DistIndex DistIndex; + using UniqueResultSet::dist_indices_; + using UniqueResultSet::is_full_; + + /** The furthest distance a neighbor can be */ + DistanceType radius_; +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +/** Class that holds the k NN neighbors within a radius distance + */ +template +class KNNRadiusUniqueResultSet : public KNNUniqueResultSet +{ +public: + /** Constructor + * @param capacity the number of neighbors to store at max + * @param radius the maximum distance of a neighbor + */ + KNNRadiusUniqueResultSet(unsigned int capacity, DistanceType radius) + { + this->capacity_ = capacity; + this->radius_ = radius; + this->dist_indices_.reserve(capacity_); + this->clear(); + } + + /** Remove all elements in the set + */ + void clear() + { + dist_indices_.clear(); + worst_distance_ = radius_; + is_full_ = false; + } +private: + using KNNUniqueResultSet::dist_indices_; + using KNNUniqueResultSet::is_full_; + using KNNUniqueResultSet::worst_distance_; + + /** The maximum number of neighbors to consider */ + unsigned int capacity_; + + /** The maximum distance of a neighbor */ + DistanceType radius_; +}; +} + +//! @endcond + +#endif //OPENCV_FLANN_RESULTSET_H diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/sampling.h b/3rdParty/opencv-4.11.0/opencv2/flann/sampling.h index 4e452b9bba..c8b3a4fe84 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/sampling.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/sampling.h @@ -1,84 +1,84 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * 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 ``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 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 OPENCV_FLANN_SAMPLING_H_ -#define OPENCV_FLANN_SAMPLING_H_ - -//! @cond IGNORED - -#include "matrix.h" -#include "random.h" - -namespace cvflann -{ - -template -Matrix random_sample(Matrix& srcMatrix, long size, bool remove = false) -{ - Matrix newSet(new T[size * srcMatrix.cols], size,srcMatrix.cols); - - T* src,* dest; - for (long i=0; i -Matrix random_sample(const Matrix& srcMatrix, size_t size) -{ - UniqueRandom rand((int)srcMatrix.rows); - Matrix newSet(new T[size * srcMatrix.cols], size,srcMatrix.cols); - - T* src,* dest; - for (size_t i=0; i +Matrix random_sample(Matrix& srcMatrix, long size, bool remove = false) +{ + Matrix newSet(new T[size * srcMatrix.cols], size,srcMatrix.cols); + + T* src,* dest; + for (long i=0; i +Matrix random_sample(const Matrix& srcMatrix, size_t size) +{ + UniqueRandom rand((int)srcMatrix.rows); + Matrix newSet(new T[size * srcMatrix.cols], size,srcMatrix.cols); + + T* src,* dest; + for (size_t i=0; i -#include - -#include "general.h" -#include "nn_index.h" - -#ifdef FLANN_SIGNATURE_ -#undef FLANN_SIGNATURE_ -#endif -#define FLANN_SIGNATURE_ "FLANN_INDEX" - -namespace cvflann -{ - -template -struct Datatype {}; -template<> -struct Datatype { static flann_datatype_t type() { return FLANN_INT8; } }; -template<> -struct Datatype { static flann_datatype_t type() { return FLANN_INT16; } }; -template<> -struct Datatype { static flann_datatype_t type() { return FLANN_INT32; } }; -template<> -struct Datatype { static flann_datatype_t type() { return FLANN_UINT8; } }; -template<> -struct Datatype { static flann_datatype_t type() { return FLANN_UINT16; } }; -template<> -struct Datatype { static flann_datatype_t type() { return FLANN_UINT32; } }; -template<> -struct Datatype { static flann_datatype_t type() { return FLANN_FLOAT32; } }; -template<> -struct Datatype { static flann_datatype_t type() { return FLANN_FLOAT64; } }; - - -/** - * Structure representing the index header. - */ -struct IndexHeader -{ - char signature[16]; - char version[16]; - flann_datatype_t data_type; - flann_algorithm_t index_type; - size_t rows; - size_t cols; -}; - -/** - * Saves index header to stream - * - * @param stream - Stream to save to - * @param index - The index to save - */ -template -void save_header(FILE* stream, const NNIndex& index) -{ - IndexHeader header; - memset(header.signature, 0, sizeof(header.signature)); - strcpy(header.signature, FLANN_SIGNATURE_); - memset(header.version, 0, sizeof(header.version)); - strcpy(header.version, FLANN_VERSION_); - header.data_type = Datatype::type(); - header.index_type = index.getType(); - header.rows = index.size(); - header.cols = index.veclen(); - - std::fwrite(&header, sizeof(header),1,stream); -} - - -/** - * - * @param stream - Stream to load from - * @return Index header - */ -inline IndexHeader load_header(FILE* stream) -{ - IndexHeader header; - size_t read_size = fread(&header,sizeof(header),1,stream); - - if (read_size!=(size_t)1) { - FLANN_THROW(cv::Error::StsError, "Invalid index file, cannot read"); - } - - if (strcmp(header.signature,FLANN_SIGNATURE_)!=0) { - FLANN_THROW(cv::Error::StsError, "Invalid index file, wrong signature"); - } - - return header; - -} - - -template -void save_value(FILE* stream, const T& value, size_t count = 1) -{ - fwrite(&value, sizeof(value),count, stream); -} - -template -void save_value(FILE* stream, const cvflann::Matrix& value) -{ - fwrite(&value, sizeof(value),1, stream); - fwrite(value.data, sizeof(T),value.rows*value.cols, stream); -} - -template -void save_value(FILE* stream, const std::vector& value) -{ - size_t size = value.size(); - fwrite(&size, sizeof(size_t), 1, stream); - fwrite(&value[0], sizeof(T), size, stream); -} - -template -void load_value(FILE* stream, T& value, size_t count = 1) -{ - size_t read_cnt = fread(&value, sizeof(value), count, stream); - if (read_cnt != count) { - FLANN_THROW(cv::Error::StsParseError, "Cannot read from file"); - } -} - -template -void load_value(FILE* stream, cvflann::Matrix& value) -{ - size_t read_cnt = fread(&value, sizeof(value), 1, stream); - if (read_cnt != 1) { - FLANN_THROW(cv::Error::StsParseError, "Cannot read from file"); - } - value.data = new T[value.rows*value.cols]; - read_cnt = fread(value.data, sizeof(T), value.rows*value.cols, stream); - if (read_cnt != (size_t)(value.rows*value.cols)) { - FLANN_THROW(cv::Error::StsParseError, "Cannot read from file"); - } -} - - -template -void load_value(FILE* stream, std::vector& value) -{ - size_t size; - size_t read_cnt = fread(&size, sizeof(size_t), 1, stream); - if (read_cnt!=1) { - FLANN_THROW(cv::Error::StsError, "Cannot read from file"); - } - value.resize(size); - read_cnt = fread(&value[0], sizeof(T), size, stream); - if (read_cnt != size) { - FLANN_THROW(cv::Error::StsError, "Cannot read from file"); - } -} - -} - -//! @endcond - -#endif /* OPENCV_FLANN_SAVING_H_ */ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * 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 ``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 BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE NNIndexGOODS 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 OPENCV_FLANN_SAVING_H_ +#define OPENCV_FLANN_SAVING_H_ + +//! @cond IGNORED + +#include +#include + +#include "general.h" +#include "nn_index.h" + +#ifdef FLANN_SIGNATURE_ +#undef FLANN_SIGNATURE_ +#endif +#define FLANN_SIGNATURE_ "FLANN_INDEX" + +namespace cvflann +{ + +template +struct Datatype {}; +template<> +struct Datatype { static flann_datatype_t type() { return FLANN_INT8; } }; +template<> +struct Datatype { static flann_datatype_t type() { return FLANN_INT16; } }; +template<> +struct Datatype { static flann_datatype_t type() { return FLANN_INT32; } }; +template<> +struct Datatype { static flann_datatype_t type() { return FLANN_UINT8; } }; +template<> +struct Datatype { static flann_datatype_t type() { return FLANN_UINT16; } }; +template<> +struct Datatype { static flann_datatype_t type() { return FLANN_UINT32; } }; +template<> +struct Datatype { static flann_datatype_t type() { return FLANN_FLOAT32; } }; +template<> +struct Datatype { static flann_datatype_t type() { return FLANN_FLOAT64; } }; + + +/** + * Structure representing the index header. + */ +struct IndexHeader +{ + char signature[16]; + char version[16]; + flann_datatype_t data_type; + flann_algorithm_t index_type; + size_t rows; + size_t cols; +}; + +/** + * Saves index header to stream + * + * @param stream - Stream to save to + * @param index - The index to save + */ +template +void save_header(FILE* stream, const NNIndex& index) +{ + IndexHeader header; + memset(header.signature, 0, sizeof(header.signature)); + strcpy(header.signature, FLANN_SIGNATURE_); + memset(header.version, 0, sizeof(header.version)); + strcpy(header.version, FLANN_VERSION_); + header.data_type = Datatype::type(); + header.index_type = index.getType(); + header.rows = index.size(); + header.cols = index.veclen(); + + std::fwrite(&header, sizeof(header),1,stream); +} + + +/** + * + * @param stream - Stream to load from + * @return Index header + */ +inline IndexHeader load_header(FILE* stream) +{ + IndexHeader header; + size_t read_size = fread(&header,sizeof(header),1,stream); + + if (read_size!=(size_t)1) { + FLANN_THROW(cv::Error::StsError, "Invalid index file, cannot read"); + } + + if (strcmp(header.signature,FLANN_SIGNATURE_)!=0) { + FLANN_THROW(cv::Error::StsError, "Invalid index file, wrong signature"); + } + + return header; + +} + + +template +void save_value(FILE* stream, const T& value, size_t count = 1) +{ + fwrite(&value, sizeof(value),count, stream); +} + +template +void save_value(FILE* stream, const cvflann::Matrix& value) +{ + fwrite(&value, sizeof(value),1, stream); + fwrite(value.data, sizeof(T),value.rows*value.cols, stream); +} + +template +void save_value(FILE* stream, const std::vector& value) +{ + size_t size = value.size(); + fwrite(&size, sizeof(size_t), 1, stream); + fwrite(&value[0], sizeof(T), size, stream); +} + +template +void load_value(FILE* stream, T& value, size_t count = 1) +{ + size_t read_cnt = fread(&value, sizeof(value), count, stream); + if (read_cnt != count) { + FLANN_THROW(cv::Error::StsParseError, "Cannot read from file"); + } +} + +template +void load_value(FILE* stream, cvflann::Matrix& value) +{ + size_t read_cnt = fread(&value, sizeof(value), 1, stream); + if (read_cnt != 1) { + FLANN_THROW(cv::Error::StsParseError, "Cannot read from file"); + } + value.data = new T[value.rows*value.cols]; + read_cnt = fread(value.data, sizeof(T), value.rows*value.cols, stream); + if (read_cnt != (size_t)(value.rows*value.cols)) { + FLANN_THROW(cv::Error::StsParseError, "Cannot read from file"); + } +} + + +template +void load_value(FILE* stream, std::vector& value) +{ + size_t size; + size_t read_cnt = fread(&size, sizeof(size_t), 1, stream); + if (read_cnt!=1) { + FLANN_THROW(cv::Error::StsError, "Cannot read from file"); + } + value.resize(size); + read_cnt = fread(&value[0], sizeof(T), size, stream); + if (read_cnt != size) { + FLANN_THROW(cv::Error::StsError, "Cannot read from file"); + } +} + +} + +//! @endcond + +#endif /* OPENCV_FLANN_SAVING_H_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/simplex_downhill.h b/3rdParty/opencv-4.11.0/opencv2/flann/simplex_downhill.h index 02970148b2..ea5a94b060 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/simplex_downhill.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/simplex_downhill.h @@ -1,190 +1,190 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * 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 ``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 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 OPENCV_FLANN_SIMPLEX_DOWNHILL_H_ -#define OPENCV_FLANN_SIMPLEX_DOWNHILL_H_ - -//! @cond IGNORED - -namespace cvflann -{ - -/** - Adds val to array vals (and point to array points) and keeping the arrays sorted by vals. - */ -template -void addValue(int pos, float val, float* vals, T* point, T* points, int n) -{ - vals[pos] = val; - for (int i=0; i0 && vals[j] -float optimizeSimplexDownhill(T* points, int n, F func, float* vals = NULL ) -{ - const int MAX_ITERATIONS = 10; - - CV_DbgAssert(n>0); - - T* p_o = new T[n]; - T* p_r = new T[n]; - T* p_e = new T[n]; - - int alpha = 1; - - int iterations = 0; - - bool ownVals = false; - if (vals == NULL) { - ownVals = true; - vals = new float[n+1]; - for (int i=0; i MAX_ITERATIONS) break; - - // compute average of simplex points (except the highest point) - for (int j=0; j=vals[0])&&(val_r=vals[n]) { - for (int i=0; i +void addValue(int pos, float val, float* vals, T* point, T* points, int n) +{ + vals[pos] = val; + for (int i=0; i0 && vals[j] +float optimizeSimplexDownhill(T* points, int n, F func, float* vals = NULL ) +{ + const int MAX_ITERATIONS = 10; + + CV_DbgAssert(n>0); + + T* p_o = new T[n]; + T* p_r = new T[n]; + T* p_e = new T[n]; + + int alpha = 1; + + int iterations = 0; + + bool ownVals = false; + if (vals == NULL) { + ownVals = true; + vals = new float[n+1]; + for (int i=0; i MAX_ITERATIONS) break; + + // compute average of simplex points (except the highest point) + for (int j=0; j=vals[0])&&(val_r=vals[n]) { + for (int i=0; i -#include "opencv2/core.hpp" -#include "opencv2/core/utility.hpp" - -namespace cvflann -{ - -/** - * A start-stop timer class. - * - * Can be used to time portions of code. - */ -class StartStopTimer -{ - int64 startTime; - -public: - /** - * Value of the timer. - */ - double value; - - - /** - * Constructor. - */ - StartStopTimer() - : startTime(0) - { - reset(); - } - - /** - * Starts the timer. - */ - void start() - { - startTime = cv::getTickCount(); - } - - /** - * Stops the timer and updates timer value. - */ - void stop() - { - int64 stopTime = cv::getTickCount(); - value += ( (double)stopTime - startTime) / cv::getTickFrequency(); - } - - /** - * Resets the timer value to 0. - */ - void reset() - { - value = 0; - } - -}; - -} - -//! @endcond - -#endif // FLANN_TIMER_H +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * 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 ``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 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 OPENCV_FLANN_TIMER_H +#define OPENCV_FLANN_TIMER_H + +//! @cond IGNORED + +#include +#include "opencv2/core.hpp" +#include "opencv2/core/utility.hpp" + +namespace cvflann +{ + +/** + * A start-stop timer class. + * + * Can be used to time portions of code. + */ +class StartStopTimer +{ + int64 startTime; + +public: + /** + * Value of the timer. + */ + double value; + + + /** + * Constructor. + */ + StartStopTimer() + : startTime(0) + { + reset(); + } + + /** + * Starts the timer. + */ + void start() + { + startTime = cv::getTickCount(); + } + + /** + * Stops the timer and updates timer value. + */ + void stop() + { + int64 stopTime = cv::getTickCount(); + value += ( (double)stopTime - startTime) / cv::getTickFrequency(); + } + + /** + * Resets the timer value to 0. + */ + void reset() + { + value = 0; + } + +}; + +} + +//! @endcond + +#endif // FLANN_TIMER_H diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi.hpp index 2087641023..fa36a92a38 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi.hpp @@ -1,42 +1,42 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2021 Intel Corporation - - -#ifndef OPENCV_GAPI_HPP -#define OPENCV_GAPI_HPP - -#include - -/** \defgroup gapi_ref G-API framework -@{ - @defgroup gapi_main_classes G-API Main Classes - @defgroup gapi_data_objects G-API Data Types - @{ - @defgroup gapi_meta_args G-API Metadata Descriptors - @} - @defgroup gapi_std_backends G-API Standard Backends - @defgroup gapi_compile_args G-API Graph Compilation Arguments - @defgroup gapi_serialization G-API Serialization functionality -@} - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// Include these files here to avoid cyclic dependency between -// Desync & GKernel & GComputation & GStreamingCompiled. -#include -#include - -#endif // OPENCV_GAPI_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2021 Intel Corporation + + +#ifndef OPENCV_GAPI_HPP +#define OPENCV_GAPI_HPP + +#include + +/** \defgroup gapi_ref G-API framework +@{ + @defgroup gapi_main_classes G-API Main Classes + @defgroup gapi_data_objects G-API Data Types + @{ + @defgroup gapi_meta_args G-API Metadata Descriptors + @} + @defgroup gapi_std_backends G-API Standard Backends + @defgroup gapi_compile_args G-API Graph Compilation Arguments + @defgroup gapi_serialization G-API Serialization functionality +@} + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Include these files here to avoid cyclic dependency between +// Desync & GKernel & GComputation & GStreamingCompiled. +#include +#include + +#endif // OPENCV_GAPI_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/core.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/core.hpp index 60bb2c5074..370e4ccf86 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/core.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/core.hpp @@ -1,1911 +1,1911 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2020 Intel Corporation - - -#ifndef OPENCV_GAPI_CORE_HPP -#define OPENCV_GAPI_CORE_HPP - -#include -#include // std::tuple - -#include -#include - -#include -#include -#include -#include - -/** \defgroup gapi_core G-API Core functionality -@{ - @defgroup gapi_math Graph API: Math operations - @defgroup gapi_pixelwise Graph API: Pixelwise operations - @defgroup gapi_matrixop Graph API: Operations on matrices - @defgroup gapi_transform Graph API: Image and channel composition functions -@} - */ - -namespace cv { namespace gapi { -/** - * @brief This namespace contains G-API Operation Types for OpenCV - * Core module functionality. - */ -namespace core { - using GResize = cv::gapi::imgproc::GResize; - using GResizeP = cv::gapi::imgproc::GResizeP; - - using GMat2 = std::tuple; - using GMat3 = std::tuple; // FIXME: how to avoid this? - using GMat4 = std::tuple; - using GMatScalar = std::tuple; - - G_TYPED_KERNEL(GAdd, , "org.opencv.core.math.add") { - static GMatDesc outMeta(GMatDesc a, GMatDesc b, int ddepth) { - if (ddepth == -1) - { - // OpenCV: When the input arrays in add/subtract/multiply/divide - // functions have different depths, the output array depth must be - // explicitly specified! - // See artim_op() @ arithm.cpp - GAPI_Assert(a.chan == b.chan); - GAPI_Assert(a.depth == b.depth); - return a; - } - return a.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GAddC, , "org.opencv.core.math.addC") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc, int ddepth) { - GAPI_Assert(a.chan <= 4); - return a.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GSub, , "org.opencv.core.math.sub") { - static GMatDesc outMeta(GMatDesc a, GMatDesc b, int ddepth) { - if (ddepth == -1) - { - // This macro should select a larger data depth from a and b - // considering the number of channels in the same - // FIXME!!! Clarify if it is valid for sub() - GAPI_Assert(a.chan == b.chan); - ddepth = std::max(a.depth, b.depth); - } - return a.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GSubC, , "org.opencv.core.math.subC") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc, int ddepth) { - return a.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GSubRC,, "org.opencv.core.math.subRC") { - static GMatDesc outMeta(GScalarDesc, GMatDesc b, int ddepth) { - return b.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GMul, , "org.opencv.core.math.mul") { - static GMatDesc outMeta(GMatDesc a, GMatDesc, double, int ddepth) { - return a.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GMulCOld, , "org.opencv.core.math.mulCOld") { - static GMatDesc outMeta(GMatDesc a, double, int ddepth) { - return a.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GMulC, , "org.opencv.core.math.mulC") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc, int ddepth) { - return a.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GMulS, , "org.opencv.core.math.muls") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc) { - return a; - } - }; // FIXME: Merge with MulC - - G_TYPED_KERNEL(GDiv, , "org.opencv.core.math.div") { - static GMatDesc outMeta(GMatDesc a, GMatDesc b, double, int ddepth) { - if (ddepth == -1) - { - GAPI_Assert(a.depth == b.depth); - return b; - } - return a.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GDivC, , "org.opencv.core.math.divC") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc, double, int ddepth) { - return a.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GDivRC, , "org.opencv.core.math.divRC") { - static GMatDesc outMeta(GScalarDesc, GMatDesc b, double, int ddepth) { - return b.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GMean, , "org.opencv.core.math.mean") { - static GScalarDesc outMeta(GMatDesc) { - return empty_scalar_desc(); - } - }; - - G_TYPED_KERNEL_M(GPolarToCart, , "org.opencv.core.math.polarToCart") { - static std::tuple outMeta(GMatDesc, GMatDesc a, bool) { - return std::make_tuple(a, a); - } - }; - - G_TYPED_KERNEL_M(GCartToPolar, , "org.opencv.core.math.cartToPolar") { - static std::tuple outMeta(GMatDesc x, GMatDesc, bool) { - return std::make_tuple(x, x); - } - }; - - G_TYPED_KERNEL(GPhase, , "org.opencv.core.math.phase") { - static GMatDesc outMeta(const GMatDesc &inx, const GMatDesc &, bool) { - return inx; - } - }; - - G_TYPED_KERNEL(GMask, , "org.opencv.core.pixelwise.mask") { - static GMatDesc outMeta(GMatDesc in, GMatDesc) { - return in; - } - }; - - G_TYPED_KERNEL(GCmpGT, , "org.opencv.core.pixelwise.compare.cmpGT") { - static GMatDesc outMeta(GMatDesc a, GMatDesc) { - return a.withDepth(CV_8U); - } - }; - - G_TYPED_KERNEL(GCmpGE, , "org.opencv.core.pixelwise.compare.cmpGE") { - static GMatDesc outMeta(GMatDesc a, GMatDesc) { - return a.withDepth(CV_8U); - } - }; - - G_TYPED_KERNEL(GCmpLE, , "org.opencv.core.pixelwise.compare.cmpLE") { - static GMatDesc outMeta(GMatDesc a, GMatDesc) { - return a.withDepth(CV_8U); - } - }; - - G_TYPED_KERNEL(GCmpLT, , "org.opencv.core.pixelwise.compare.cmpLT") { - static GMatDesc outMeta(GMatDesc a, GMatDesc) { - return a.withDepth(CV_8U); - } - }; - - G_TYPED_KERNEL(GCmpEQ, , "org.opencv.core.pixelwise.compare.cmpEQ") { - static GMatDesc outMeta(GMatDesc a, GMatDesc) { - return a.withDepth(CV_8U); - } - }; - - G_TYPED_KERNEL(GCmpNE, , "org.opencv.core.pixelwise.compare.cmpNE") { - static GMatDesc outMeta(GMatDesc a, GMatDesc) { - return a.withDepth(CV_8U); - } - }; - - G_TYPED_KERNEL(GCmpGTScalar, , "org.opencv.core.pixelwise.compare.cmpGTScalar") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc) { - return a.withDepth(CV_8U); - } - }; - - G_TYPED_KERNEL(GCmpGEScalar, , "org.opencv.core.pixelwise.compare.cmpGEScalar") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc) { - return a.withDepth(CV_8U); - } - }; - - G_TYPED_KERNEL(GCmpLEScalar, , "org.opencv.core.pixelwise.compare.cmpLEScalar") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc) { - return a.withDepth(CV_8U); - } - }; - - G_TYPED_KERNEL(GCmpLTScalar, , "org.opencv.core.pixelwise.compare.cmpLTScalar") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc) { - return a.withDepth(CV_8U); - } - }; - - G_TYPED_KERNEL(GCmpEQScalar, , "org.opencv.core.pixelwise.compare.cmpEQScalar") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc) { - return a.withDepth(CV_8U); - } - }; - - G_TYPED_KERNEL(GCmpNEScalar, , "org.opencv.core.pixelwise.compare.cmpNEScalar") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc) { - return a.withDepth(CV_8U); - } - }; - - G_TYPED_KERNEL(GAnd, , "org.opencv.core.pixelwise.bitwise_and") { - static GMatDesc outMeta(GMatDesc a, GMatDesc) { - return a; - } - }; - - G_TYPED_KERNEL(GAndS, , "org.opencv.core.pixelwise.bitwise_andS") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc) { - return a; - } - }; - - G_TYPED_KERNEL(GOr, , "org.opencv.core.pixelwise.bitwise_or") { - static GMatDesc outMeta(GMatDesc a, GMatDesc) { - return a; - } - }; - - G_TYPED_KERNEL(GOrS, , "org.opencv.core.pixelwise.bitwise_orS") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc) { - return a; - } - }; - - G_TYPED_KERNEL(GXor, , "org.opencv.core.pixelwise.bitwise_xor") { - static GMatDesc outMeta(GMatDesc a, GMatDesc) { - return a; - } - }; - - G_TYPED_KERNEL(GXorS, , "org.opencv.core.pixelwise.bitwise_xorS") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc) { - return a; - } - }; - - G_TYPED_KERNEL(GNot, , "org.opencv.core.pixelwise.bitwise_not") { - static GMatDesc outMeta(GMatDesc a) { - return a; - } - }; - - G_TYPED_KERNEL(GSelect, , "org.opencv.core.pixelwise.select") { - static GMatDesc outMeta(GMatDesc a, GMatDesc, GMatDesc) { - return a; - } - }; - - G_TYPED_KERNEL(GMin, , "org.opencv.core.matrixop.min") { - static GMatDesc outMeta(GMatDesc a, GMatDesc) { - return a; - } - }; - - G_TYPED_KERNEL(GMax, , "org.opencv.core.matrixop.max") { - static GMatDesc outMeta(GMatDesc a, GMatDesc) { - return a; - } - }; - - G_TYPED_KERNEL(GAbsDiff, , "org.opencv.core.matrixop.absdiff") { - static GMatDesc outMeta(GMatDesc a, GMatDesc) { - return a; - } - }; - - G_TYPED_KERNEL(GAbsDiffC, , "org.opencv.core.matrixop.absdiffC") { - static GMatDesc outMeta(const GMatDesc& a, const GScalarDesc&) { - return a; - } - }; - - G_TYPED_KERNEL(GSum, , "org.opencv.core.matrixop.sum") { - static GScalarDesc outMeta(GMatDesc) { - return empty_scalar_desc(); - } - }; - - G_TYPED_KERNEL(GCountNonZero, (GMat)>, "org.opencv.core.matrixop.countNonZero") { - static GOpaqueDesc outMeta(GMatDesc in) { - GAPI_Assert(in.chan == 1); - return empty_gopaque_desc(); - } - }; - - G_TYPED_KERNEL(GAddW, , "org.opencv.core.matrixop.addweighted") { - static GMatDesc outMeta(GMatDesc a, double, GMatDesc b, double, double, int ddepth) { - if (ddepth == -1) - { - // OpenCV: When the input arrays in add/subtract/multiply/divide - // functions have different depths, the output array depth must be - // explicitly specified! - // See artim_op() @ arithm.cpp - GAPI_Assert(a.chan == b.chan); - GAPI_Assert(a.depth == b.depth); - return a; - } - return a.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GNormL1, , "org.opencv.core.matrixop.norml1") { - static GScalarDesc outMeta(GMatDesc) { - return empty_scalar_desc(); - } - }; - - G_TYPED_KERNEL(GNormL2, , "org.opencv.core.matrixop.norml2") { - static GScalarDesc outMeta(GMatDesc) { - return empty_scalar_desc(); - } - }; - - G_TYPED_KERNEL(GNormInf, , "org.opencv.core.matrixop.norminf") { - static GScalarDesc outMeta(GMatDesc) { - return empty_scalar_desc(); - } - }; - - G_TYPED_KERNEL_M(GIntegral, , "org.opencv.core.matrixop.integral") { - static std::tuple outMeta(GMatDesc in, int sd, int sqd) { - return std::make_tuple(in.withSizeDelta(1,1).withDepth(sd), - in.withSizeDelta(1,1).withDepth(sqd)); - } - }; - - G_TYPED_KERNEL(GThreshold, , "org.opencv.core.matrixop.threshold") { - static GMatDesc outMeta(GMatDesc in, GScalarDesc, GScalarDesc, int) { - return in; - } - }; - - - G_TYPED_KERNEL_M(GThresholdOT, , "org.opencv.core.matrixop.thresholdOT") { - static std::tuple outMeta(GMatDesc in, GScalarDesc, int) { - return std::make_tuple(in, empty_scalar_desc()); - } - }; - - G_TYPED_KERNEL(GInRange, , "org.opencv.core.matrixop.inrange") { - static GMatDesc outMeta(GMatDesc in, GScalarDesc, GScalarDesc) { - return in.withType(CV_8U, 1); - } - }; - - G_TYPED_KERNEL_M(GSplit3, , "org.opencv.core.transform.split3") { - static std::tuple outMeta(GMatDesc in) { - const auto out_depth = in.depth; - const auto out_desc = in.withType(out_depth, 1); - return std::make_tuple(out_desc, out_desc, out_desc); - } - }; - - G_TYPED_KERNEL_M(GSplit4, ,"org.opencv.core.transform.split4") { - static std::tuple outMeta(GMatDesc in) { - const auto out_depth = in.depth; - const auto out_desc = in.withType(out_depth, 1); - return std::make_tuple(out_desc, out_desc, out_desc, out_desc); - } - }; - - G_TYPED_KERNEL(GMerge3, , "org.opencv.core.transform.merge3") { - static GMatDesc outMeta(GMatDesc in, GMatDesc, GMatDesc) { - // Preserve depth and add channel component - return in.withType(in.depth, 3); - } - }; - - G_TYPED_KERNEL(GMerge4, , "org.opencv.core.transform.merge4") { - static GMatDesc outMeta(GMatDesc in, GMatDesc, GMatDesc, GMatDesc) { - // Preserve depth and add channel component - return in.withType(in.depth, 4); - } - }; - - G_TYPED_KERNEL(GRemap, , "org.opencv.core.transform.remap") { - static GMatDesc outMeta(GMatDesc in, Mat m1, Mat, int, int, Scalar) { - return in.withSize(m1.size()); - } - }; - - G_TYPED_KERNEL(GFlip, , "org.opencv.core.transform.flip") { - static GMatDesc outMeta(GMatDesc in, int) { - return in; - } - }; - - // TODO: eliminate the need in this kernel (streaming) - G_TYPED_KERNEL(GCrop, , "org.opencv.core.transform.crop") { - static GMatDesc outMeta(GMatDesc in, Rect rc) { - return in.withSize(Size(rc.width, rc.height)); - } - }; - - G_TYPED_KERNEL(GConcatHor, , "org.opencv.imgproc.transform.concatHor") { - static GMatDesc outMeta(GMatDesc l, GMatDesc r) { - return l.withSizeDelta(+r.size.width, 0); - } - }; - - G_TYPED_KERNEL(GConcatVert, , "org.opencv.imgproc.transform.concatVert") { - static GMatDesc outMeta(GMatDesc t, GMatDesc b) { - return t.withSizeDelta(0, +b.size.height); - } - }; - - G_TYPED_KERNEL(GLUT, , "org.opencv.core.transform.LUT") { - static GMatDesc outMeta(GMatDesc in, Mat) { - return in; - } - }; - - G_TYPED_KERNEL(GConvertTo, , "org.opencv.core.transform.convertTo") { - static GMatDesc outMeta(GMatDesc in, int rdepth, double, double) { - return rdepth < 0 ? in : in.withDepth(rdepth); - } - }; - - G_TYPED_KERNEL(GSqrt, , "org.opencv.core.math.sqrt") { - static GMatDesc outMeta(GMatDesc in) { - return in; - } - }; - - G_TYPED_KERNEL(GNormalize, , "org.opencv.core.normalize") { - static GMatDesc outMeta(GMatDesc in, double, double, int, int ddepth) { - // unlike opencv doesn't have a mask as a parameter - return (ddepth < 0 ? in : in.withDepth(ddepth)); - } - }; - - G_TYPED_KERNEL(GWarpPerspective, , "org.opencv.core.warpPerspective") { - static GMatDesc outMeta(GMatDesc in, const Mat&, Size dsize, int, int borderMode, const cv::Scalar&) { - GAPI_Assert((borderMode == cv::BORDER_CONSTANT || borderMode == cv::BORDER_REPLICATE) && - "cv::gapi::warpPerspective supports only cv::BORDER_CONSTANT and cv::BORDER_REPLICATE border modes"); - return in.withType(in.depth, in.chan).withSize(dsize); - } - }; - - G_TYPED_KERNEL(GWarpAffine, , "org.opencv.core.warpAffine") { - static GMatDesc outMeta(GMatDesc in, const Mat&, Size dsize, int, int border_mode, const cv::Scalar&) { - GAPI_Assert(border_mode != cv::BORDER_TRANSPARENT && - "cv::BORDER_TRANSPARENT mode is not supported in cv::gapi::warpAffine"); - return in.withType(in.depth, in.chan).withSize(dsize); - } - }; - - G_TYPED_KERNEL( - GKMeansND, - ,GMat,GMat>(GMat,int,GMat,TermCriteria,int,KmeansFlags)>, - "org.opencv.core.kmeansND") { - - static std::tuple - outMeta(const GMatDesc& in, int K, const GMatDesc& bestLabels, const TermCriteria&, int, - KmeansFlags flags) { - GAPI_Assert(in.depth == CV_32F); - std::vector amount_n_dim = detail::checkVector(in); - int amount = amount_n_dim[0], dim = amount_n_dim[1]; - if (amount == -1) // Mat with height != 1, width != 1, channels != 1 given - { // which means that kmeans will consider the following: - amount = in.size.height; - dim = in.size.width * in.chan; - } - // kmeans sets these labels' sizes when no bestLabels given: - GMatDesc out_labels(CV_32S, 1, Size{1, amount}); - // kmeans always sets these centers' sizes: - GMatDesc centers (CV_32F, 1, Size{dim, K}); - if (flags & KMEANS_USE_INITIAL_LABELS) - { - GAPI_Assert(bestLabels.depth == CV_32S); - int labels_amount = detail::checkVector(bestLabels, 1u); - GAPI_Assert(labels_amount == amount); - out_labels = bestLabels; // kmeans preserves bestLabels' sizes if given - } - return std::make_tuple(empty_gopaque_desc(), out_labels, centers); - } - }; - - G_TYPED_KERNEL( - GKMeansNDNoInit, - ,GMat,GMat>(GMat,int,TermCriteria,int,KmeansFlags)>, - "org.opencv.core.kmeansNDNoInit") { - - static std::tuple - outMeta(const GMatDesc& in, int K, const TermCriteria&, int, KmeansFlags flags) { - GAPI_Assert( !(flags & KMEANS_USE_INITIAL_LABELS) ); - GAPI_Assert(in.depth == CV_32F); - std::vector amount_n_dim = detail::checkVector(in); - int amount = amount_n_dim[0], dim = amount_n_dim[1]; - if (amount == -1) // Mat with height != 1, width != 1, channels != 1 given - { // which means that kmeans will consider the following: - amount = in.size.height; - dim = in.size.width * in.chan; - } - GMatDesc out_labels(CV_32S, 1, Size{1, amount}); - GMatDesc centers (CV_32F, 1, Size{dim, K}); - return std::make_tuple(empty_gopaque_desc(), out_labels, centers); - } - }; - - G_TYPED_KERNEL(GKMeans2D, ,GArray,GArray> - (GArray,int,GArray,TermCriteria,int,KmeansFlags)>, - "org.opencv.core.kmeans2D") { - static std::tuple - outMeta(const GArrayDesc&,int,const GArrayDesc&,const TermCriteria&,int,KmeansFlags) { - return std::make_tuple(empty_gopaque_desc(), empty_array_desc(), empty_array_desc()); - } - }; - - G_TYPED_KERNEL(GKMeans3D, ,GArray,GArray> - (GArray,int,GArray,TermCriteria,int,KmeansFlags)>, - "org.opencv.core.kmeans3D") { - static std::tuple - outMeta(const GArrayDesc&,int,const GArrayDesc&,const TermCriteria&,int,KmeansFlags) { - return std::make_tuple(empty_gopaque_desc(), empty_array_desc(), empty_array_desc()); - } - }; - - G_TYPED_KERNEL(GTranspose, , "org.opencv.core.transpose") { - static GMatDesc outMeta(GMatDesc in) { - return in.withSize({in.size.height, in.size.width}); - } - }; -} // namespace core - -namespace streaming { - -// Operations for Streaming (declared in this header for convenience) -G_TYPED_KERNEL(GSize, (GMat)>, "org.opencv.streaming.size") { - static GOpaqueDesc outMeta(const GMatDesc&) { - return empty_gopaque_desc(); - } -}; - -G_TYPED_KERNEL(GSizeR, (GOpaque)>, "org.opencv.streaming.sizeR") { - static GOpaqueDesc outMeta(const GOpaqueDesc&) { - return empty_gopaque_desc(); - } -}; - -G_TYPED_KERNEL(GSizeMF, (GFrame)>, "org.opencv.streaming.sizeMF") { - static GOpaqueDesc outMeta(const GFrameDesc&) { - return empty_gopaque_desc(); - } -}; -} // namespace streaming - -//! @addtogroup gapi_math -//! @{ - -/** @brief Calculates the per-element sum of two matrices. - -The function add calculates sum of two matrices of the same size and the same number of channels: -\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) + \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0\f] - -The function can be replaced with matrix expressions: - \f[\texttt{dst} = \texttt{src1} + \texttt{src2}\f] - -The input matrices and the output matrix can all have the same or different depths. For example, you -can add a 16-bit unsigned matrix to a 8-bit signed matrix and store the sum as a 32-bit -floating-point matrix. Depth of the output matrix is determined by the ddepth parameter. -If src1.depth() == src2.depth(), ddepth can be set to the default -1. In this case, the output matrix will have -the same depth as the input matrices. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.math.add" -@param src1 first input matrix. -@param src2 second input matrix. -@param ddepth optional depth of the output matrix. -@sa sub, addWeighted -*/ -GAPI_EXPORTS_W GMat add(const GMat& src1, const GMat& src2, int ddepth = -1); - -/** @brief Calculates the per-element sum of matrix and given scalar. - -The function addC adds a given scalar value to each element of given matrix. -The function can be replaced with matrix expressions: - - \f[\texttt{dst} = \texttt{src1} + \texttt{c}\f] - -Depth of the output matrix is determined by the ddepth parameter. -If ddepth is set to default -1, the depth of output matrix will be the same as the depth of input matrix. -The matrices can be single or multi channel. Output matrix must have the same size and number of channels as the input matrix. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.math.addC" -@param src1 first input matrix. -@param c scalar value to be added. -@param ddepth optional depth of the output matrix. -@sa sub, addWeighted -*/ -GAPI_EXPORTS_W GMat addC(const GMat& src1, const GScalar& c, int ddepth = -1); -//! @overload -GAPI_EXPORTS_W GMat addC(const GScalar& c, const GMat& src1, int ddepth = -1); - -/** @brief Calculates the per-element difference between two matrices. - -The function sub calculates difference between two matrices, when both matrices have the same size and the same number of -channels: - \f[\texttt{dst}(I) = \texttt{src1}(I) - \texttt{src2}(I)\f] - -The function can be replaced with matrix expressions: -\f[\texttt{dst} = \texttt{src1} - \texttt{src2}\f] - -The input matrices and the output matrix can all have the same or different depths. For example, you -can subtract two 8-bit unsigned matrices store the result as a 16-bit signed matrix. -Depth of the output matrix is determined by the ddepth parameter. -If src1.depth() == src2.depth(), ddepth can be set to the default -1. In this case, the output matrix will have -the same depth as the input matrices. The matrices can be single or multi channel. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.math.sub" -@param src1 first input matrix. -@param src2 second input matrix. -@param ddepth optional depth of the output matrix. -@sa add, addC - */ -GAPI_EXPORTS_W GMat sub(const GMat& src1, const GMat& src2, int ddepth = -1); - -/** @brief Calculates the per-element difference between matrix and given scalar. - -The function can be replaced with matrix expressions: - \f[\texttt{dst} = \texttt{src} - \texttt{c}\f] - -Depth of the output matrix is determined by the ddepth parameter. -If ddepth is set to default -1, the depth of output matrix will be the same as the depth of input matrix. -The matrices can be single or multi channel. Output matrix must have the same size as src. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.math.subC" -@param src first input matrix. -@param c scalar value to subtracted. -@param ddepth optional depth of the output matrix. -@sa add, addC, subRC - */ -GAPI_EXPORTS_W GMat subC(const GMat& src, const GScalar& c, int ddepth = -1); - -/** @brief Calculates the per-element difference between given scalar and the matrix. - -The function can be replaced with matrix expressions: - \f[\texttt{dst} = \texttt{c} - \texttt{src}\f] - -Depth of the output matrix is determined by the ddepth parameter. -If ddepth is set to default -1, the depth of output matrix will be the same as the depth of input matrix. -The matrices can be single or multi channel. Output matrix must have the same size as src. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.math.subRC" -@param c scalar value to subtract from. -@param src input matrix to be subtracted. -@param ddepth optional depth of the output matrix. -@sa add, addC, subC - */ -GAPI_EXPORTS_W GMat subRC(const GScalar& c, const GMat& src, int ddepth = -1); - -/** @brief Calculates the per-element scaled product of two matrices. - -The function mul calculates the per-element product of two matrices: - -\f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{scale} \cdot \texttt{src1} (I) \cdot \texttt{src2} (I))\f] - -If src1.depth() == src2.depth(), ddepth can be set to the default -1. In this case, the output matrix will have -the same depth as the input matrices. The matrices can be single or multi channel. -Output matrix must have the same size as input matrices. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.math.mul" -@param src1 first input matrix. -@param src2 second input matrix of the same size and the same depth as src1. -@param scale optional scale factor. -@param ddepth optional depth of the output matrix. -@sa add, sub, div, addWeighted -*/ -GAPI_EXPORTS_W GMat mul(const GMat& src1, const GMat& src2, double scale = 1.0, int ddepth = -1); - -/** @brief Multiplies matrix by scalar. - -The function mulC multiplies each element of matrix src by given scalar value: - -\f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{src1} (I) \cdot \texttt{multiplier} )\f] - -The matrices can be single or multi channel. Output matrix must have the same size as src. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.math.mulC" -@param src input matrix. -@param multiplier factor to be multiplied. -@param ddepth optional depth of the output matrix. If -1, the depth of output matrix will be the same as input matrix depth. -@sa add, sub, div, addWeighted -*/ -GAPI_EXPORTS_W GMat mulC(const GMat& src, double multiplier, int ddepth = -1); -//! @overload -GAPI_EXPORTS_W GMat mulC(const GMat& src, const GScalar& multiplier, int ddepth = -1); // FIXME: merge with mulc -//! @overload -GAPI_EXPORTS_W GMat mulC(const GScalar& multiplier, const GMat& src, int ddepth = -1); // FIXME: merge with mulc - -/** @brief Performs per-element division of two matrices. - -The function divides one matrix by another: -\f[\texttt{dst(I) = saturate(src1(I)*scale/src2(I))}\f] - -For integer types when src2(I) is zero, dst(I) will also be zero. -Floating point case returns Inf/NaN (according to IEEE). - -Different channels of -multi-channel matrices are processed independently. -The matrices can be single or multi channel. Output matrix must have the same size and depth as src. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.math.div" -@param src1 first input matrix. -@param src2 second input matrix of the same size and depth as src1. -@param scale scalar factor. -@param ddepth optional depth of the output matrix; you can only pass -1 when src1.depth() == src2.depth(). -@sa mul, add, sub -*/ -GAPI_EXPORTS_W GMat div(const GMat& src1, const GMat& src2, double scale, int ddepth = -1); - -/** @brief Divides matrix by scalar. - -The function divC divides each element of matrix src by given scalar value: - -\f[\texttt{dst(I) = saturate(src(I)*scale/divisor)}\f] - -When divisor is zero, dst(I) will also be zero. Different channels of -multi-channel matrices are processed independently. -The matrices can be single or multi channel. Output matrix must have the same size and depth as src. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.math.divC" -@param src input matrix. -@param divisor number to be divided by. -@param ddepth optional depth of the output matrix. If -1, the depth of output matrix will be the same as input matrix depth. -@param scale scale factor. -@sa add, sub, div, addWeighted -*/ -GAPI_EXPORTS_W GMat divC(const GMat& src, const GScalar& divisor, double scale, int ddepth = -1); - -/** @brief Divides scalar by matrix. - -The function divRC divides given scalar by each element of matrix src and keep the division result in new matrix of the same size and type as src: - -\f[\texttt{dst(I) = saturate(divident*scale/src(I))}\f] - -When src(I) is zero, dst(I) will also be zero. Different channels of -multi-channel matrices are processed independently. -The matrices can be single or multi channel. Output matrix must have the same size and depth as src. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.math.divRC" -@param src input matrix. -@param divident number to be divided. -@param ddepth optional depth of the output matrix. If -1, the depth of output matrix will be the same as input matrix depth. -@param scale scale factor -@sa add, sub, div, addWeighted -*/ -GAPI_EXPORTS_W GMat divRC(const GScalar& divident, const GMat& src, double scale, int ddepth = -1); - -/** @brief Applies a mask to a matrix. - -The function mask set value from given matrix if the corresponding pixel value in mask matrix set to true, -and set the matrix value to 0 otherwise. - -Supported src matrix data types are @ref CV_8UC1, @ref CV_16SC1, @ref CV_16UC1. Supported mask data type is @ref CV_8UC1. - -@note Function textual ID is "org.opencv.core.math.mask" -@param src input matrix. -@param mask input mask matrix. -*/ -GAPI_EXPORTS_W GMat mask(const GMat& src, const GMat& mask); - -/** @brief Calculates an average (mean) of matrix elements. - -The function mean calculates the mean value M of matrix elements, -independently for each channel, and return it. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.math.mean" -@param src input matrix. -@sa countNonZero, min, max -*/ -GAPI_EXPORTS_W GScalar mean(const GMat& src); - -/** @brief Calculates x and y coordinates of 2D vectors from their magnitude and angle. - -The function polarToCart calculates the Cartesian coordinates of each 2D -vector represented by the corresponding elements of magnitude and angle: -\f[\begin{array}{l} \texttt{x} (I) = \texttt{magnitude} (I) \cos ( \texttt{angle} (I)) \\ \texttt{y} (I) = \texttt{magnitude} (I) \sin ( \texttt{angle} (I)) \\ \end{array}\f] - -The relative accuracy of the estimated coordinates is about 1e-6. - -First output is a matrix of x-coordinates of 2D vectors. -Second output is a matrix of y-coordinates of 2D vectors. -Both output must have the same size and depth as input matrices. - -@note Function textual ID is "org.opencv.core.math.polarToCart" - -@param magnitude input floating-point @ref CV_32FC1 matrix (1xN) of magnitudes of 2D vectors; -@param angle input floating-point @ref CV_32FC1 matrix (1xN) of angles of 2D vectors. -@param angleInDegrees when true, the input angles are measured in -degrees, otherwise, they are measured in radians. -@sa cartToPolar, exp, log, pow, sqrt -*/ -GAPI_EXPORTS_W std::tuple polarToCart(const GMat& magnitude, const GMat& angle, - bool angleInDegrees = false); - -/** @brief Calculates the magnitude and angle of 2D vectors. - -The function cartToPolar calculates either the magnitude, angle, or both -for every 2D vector (x(I),y(I)): -\f[\begin{array}{l} \texttt{magnitude} (I)= \sqrt{\texttt{x}(I)^2+\texttt{y}(I)^2} , \\ \texttt{angle} (I)= \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))[ \cdot180 / \pi ] \end{array}\f] - -The angles are calculated with accuracy about 0.3 degrees. For the point -(0,0), the angle is set to 0. - -First output is a matrix of magnitudes of the same size and depth as input x. -Second output is a matrix of angles that has the same size and depth as -x; the angles are measured in radians (from 0 to 2\*Pi) or in degrees (0 to 360 degrees). - -@note Function textual ID is "org.opencv.core.math.cartToPolar" - -@param x matrix of @ref CV_32FC1 x-coordinates. -@param y array of @ref CV_32FC1 y-coordinates. -@param angleInDegrees a flag, indicating whether the angles are measured -in radians (which is by default), or in degrees. -@sa polarToCart -*/ -GAPI_EXPORTS_W std::tuple cartToPolar(const GMat& x, const GMat& y, - bool angleInDegrees = false); - -/** @brief Calculates the rotation angle of 2D vectors. - -The function cv::phase calculates the rotation angle of each 2D vector that -is formed from the corresponding elements of x and y : -\f[\texttt{angle} (I) = \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))\f] - -The angle estimation accuracy is about 0.3 degrees. When x(I)=y(I)=0 , -the corresponding angle(I) is set to 0. -@param x input floating-point array of x-coordinates of 2D vectors. -@param y input array of y-coordinates of 2D vectors; it must have the -same size and the same type as x. -@param angleInDegrees when true, the function calculates the angle in -degrees, otherwise, they are measured in radians. -@return array of vector angles; it has the same size and same type as x. -*/ -GAPI_EXPORTS_W GMat phase(const GMat& x, const GMat &y, bool angleInDegrees = false); - -/** @brief Calculates a square root of array elements. - -The function cv::gapi::sqrt calculates a square root of each input array element. -In case of multi-channel arrays, each channel is processed -independently. The accuracy is approximately the same as of the built-in -std::sqrt . -@param src input floating-point array. -@return output array of the same size and type as src. -*/ -GAPI_EXPORTS_W GMat sqrt(const GMat &src); - -//! @} gapi_math -//! -//! @addtogroup gapi_pixelwise -//! @{ - -/** @brief Performs the per-element comparison of two matrices checking if elements from first matrix are greater compare to elements in second. - -The function compares elements of two matrices src1 and src2 of the same size: - \f[\texttt{dst} (I) = \texttt{src1} (I) > \texttt{src2} (I)\f] - -When the comparison result is true, the corresponding element of output -array is set to 255. The comparison operations can be replaced with the -equivalent matrix expressions: -\f[\texttt{dst} = \texttt{src1} > \texttt{src2}\f] - -Output matrix of depth @ref CV_8U must have the same size and the same number of channels as - the input matrices/matrix. - -Supported input matrix data types are @ref CV_8UC1, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpGT" -@param src1 first input matrix. -@param src2 second input matrix/scalar of the same depth as first input matrix. -@sa min, max, threshold, cmpLE, cmpGE, cmpLT -*/ -GAPI_EXPORTS_W GMat cmpGT(const GMat& src1, const GMat& src2); -/** @overload -@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpGTScalar" -*/ -GAPI_EXPORTS_W GMat cmpGT(const GMat& src1, const GScalar& src2); - -/** @brief Performs the per-element comparison of two matrices checking if elements from first matrix are less than elements in second. - -The function compares elements of two matrices src1 and src2 of the same size: - \f[\texttt{dst} (I) = \texttt{src1} (I) < \texttt{src2} (I)\f] - -When the comparison result is true, the corresponding element of output -array is set to 255. The comparison operations can be replaced with the -equivalent matrix expressions: - \f[\texttt{dst} = \texttt{src1} < \texttt{src2}\f] - -Output matrix of depth @ref CV_8U must have the same size and the same number of channels as - the input matrices/matrix. - -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpLT" -@param src1 first input matrix. -@param src2 second input matrix/scalar of the same depth as first input matrix. -@sa min, max, threshold, cmpLE, cmpGE, cmpGT -*/ -GAPI_EXPORTS_W GMat cmpLT(const GMat& src1, const GMat& src2); -/** @overload -@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpLTScalar" -*/ -GAPI_EXPORTS_W GMat cmpLT(const GMat& src1, const GScalar& src2); - -/** @brief Performs the per-element comparison of two matrices checking if elements from first matrix are greater or equal compare to elements in second. - -The function compares elements of two matrices src1 and src2 of the same size: - \f[\texttt{dst} (I) = \texttt{src1} (I) >= \texttt{src2} (I)\f] - -When the comparison result is true, the corresponding element of output -array is set to 255. The comparison operations can be replaced with the -equivalent matrix expressions: - \f[\texttt{dst} = \texttt{src1} >= \texttt{src2}\f] - -Output matrix of depth @ref CV_8U must have the same size and the same number of channels as - the input matrices. - -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpGE" -@param src1 first input matrix. -@param src2 second input matrix/scalar of the same depth as first input matrix. -@sa min, max, threshold, cmpLE, cmpGT, cmpLT -*/ -GAPI_EXPORTS_W GMat cmpGE(const GMat& src1, const GMat& src2); -/** @overload -@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpLGEcalar" -*/ -GAPI_EXPORTS_W GMat cmpGE(const GMat& src1, const GScalar& src2); - -/** @brief Performs the per-element comparison of two matrices checking if elements from first matrix are less or equal compare to elements in second. - -The function compares elements of two matrices src1 and src2 of the same size: - \f[\texttt{dst} (I) = \texttt{src1} (I) <= \texttt{src2} (I)\f] - -When the comparison result is true, the corresponding element of output -array is set to 255. The comparison operations can be replaced with the -equivalent matrix expressions: - \f[\texttt{dst} = \texttt{src1} <= \texttt{src2}\f] - -Output matrix of depth @ref CV_8U must have the same size and the same number of channels as - the input matrices. - -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpLE" -@param src1 first input matrix. -@param src2 second input matrix/scalar of the same depth as first input matrix. -@sa min, max, threshold, cmpGT, cmpGE, cmpLT -*/ -GAPI_EXPORTS_W GMat cmpLE(const GMat& src1, const GMat& src2); -/** @overload -@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpLEScalar" -*/ -GAPI_EXPORTS_W GMat cmpLE(const GMat& src1, const GScalar& src2); - -/** @brief Performs the per-element comparison of two matrices checking if elements from first matrix are equal to elements in second. - -The function compares elements of two matrices src1 and src2 of the same size: - \f[\texttt{dst} (I) = \texttt{src1} (I) == \texttt{src2} (I)\f] - -When the comparison result is true, the corresponding element of output -array is set to 255. The comparison operations can be replaced with the -equivalent matrix expressions: - \f[\texttt{dst} = \texttt{src1} == \texttt{src2}\f] - -Output matrix of depth @ref CV_8U must have the same size and the same number of channels as - the input matrices. - -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpEQ" -@param src1 first input matrix. -@param src2 second input matrix/scalar of the same depth as first input matrix. -@sa min, max, threshold, cmpNE -*/ -GAPI_EXPORTS_W GMat cmpEQ(const GMat& src1, const GMat& src2); -/** @overload -@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpEQScalar" -*/ -GAPI_EXPORTS_W GMat cmpEQ(const GMat& src1, const GScalar& src2); - -/** @brief Performs the per-element comparison of two matrices checking if elements from first matrix are not equal to elements in second. - -The function compares elements of two matrices src1 and src2 of the same size: - \f[\texttt{dst} (I) = \texttt{src1} (I) != \texttt{src2} (I)\f] - -When the comparison result is true, the corresponding element of output -array is set to 255. The comparison operations can be replaced with the -equivalent matrix expressions: - \f[\texttt{dst} = \texttt{src1} != \texttt{src2}\f] - -Output matrix of depth @ref CV_8U must have the same size and the same number of channels as - the input matrices. - -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpNE" -@param src1 first input matrix. -@param src2 second input matrix/scalar of the same depth as first input matrix. -@sa min, max, threshold, cmpEQ -*/ -GAPI_EXPORTS_W GMat cmpNE(const GMat& src1, const GMat& src2); -/** @overload -@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpNEScalar" -*/ -GAPI_EXPORTS_W GMat cmpNE(const GMat& src1, const GScalar& src2); - -/** @brief computes bitwise conjunction of the two matrixes (src1 & src2) -Calculates the per-element bit-wise logical conjunction of two matrices of the same size. - -In case of floating-point matrices, their machine-specific bit -representations (usually IEEE754-compliant) are used for the operation. -In case of multi-channel matrices, each channel is processed -independently. Output matrix must have the same size and depth as the input -matrices. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.pixelwise.bitwise_and" - -@param src1 first input matrix. -@param src2 second input matrix. -*/ -GAPI_EXPORTS_W GMat bitwise_and(const GMat& src1, const GMat& src2); -/** @overload -@note Function textual ID is "org.opencv.core.pixelwise.bitwise_andS" -@param src1 first input matrix. -@param src2 scalar, which will be per-lemenetly conjuncted with elements of src1. -*/ -GAPI_EXPORTS_W GMat bitwise_and(const GMat& src1, const GScalar& src2); - -/** @brief computes bitwise disjunction of the two matrixes (src1 | src2) -Calculates the per-element bit-wise logical disjunction of two matrices of the same size. - -In case of floating-point matrices, their machine-specific bit -representations (usually IEEE754-compliant) are used for the operation. -In case of multi-channel matrices, each channel is processed -independently. Output matrix must have the same size and depth as the input -matrices. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.pixelwise.bitwise_or" - -@param src1 first input matrix. -@param src2 second input matrix. -*/ -GAPI_EXPORTS_W GMat bitwise_or(const GMat& src1, const GMat& src2); -/** @overload -@note Function textual ID is "org.opencv.core.pixelwise.bitwise_orS" -@param src1 first input matrix. -@param src2 scalar, which will be per-lemenetly disjuncted with elements of src1. -*/ -GAPI_EXPORTS_W GMat bitwise_or(const GMat& src1, const GScalar& src2); - - -/** @brief computes bitwise logical "exclusive or" of the two matrixes (src1 ^ src2) -Calculates the per-element bit-wise logical "exclusive or" of two matrices of the same size. - -In case of floating-point matrices, their machine-specific bit -representations (usually IEEE754-compliant) are used for the operation. -In case of multi-channel matrices, each channel is processed -independently. Output matrix must have the same size and depth as the input -matrices. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.pixelwise.bitwise_xor" - -@param src1 first input matrix. -@param src2 second input matrix. -*/ -GAPI_EXPORTS_W GMat bitwise_xor(const GMat& src1, const GMat& src2); -/** @overload -@note Function textual ID is "org.opencv.core.pixelwise.bitwise_xorS" -@param src1 first input matrix. -@param src2 scalar, for which per-lemenet "logical or" operation on elements of src1 will be performed. -*/ -GAPI_EXPORTS_W GMat bitwise_xor(const GMat& src1, const GScalar& src2); - - -/** @brief Inverts every bit of an array. - -The function bitwise_not calculates per-element bit-wise inversion of the input -matrix: -\f[\texttt{dst} (I) = \neg \texttt{src} (I)\f] - -In case of floating-point matrices, their machine-specific bit -representations (usually IEEE754-compliant) are used for the operation. -In case of multi-channel matrices, each channel is processed -independently. Output matrix must have the same size and depth as the input -matrix. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.pixelwise.bitwise_not" - -@param src input matrix. -*/ -GAPI_EXPORTS_W GMat bitwise_not(const GMat& src); - -/** @brief Select values from either first or second of input matrices by given mask. -The function set to the output matrix either the value from the first input matrix if corresponding value of mask matrix is 255, - or value from the second input matrix (if value of mask matrix set to 0). - -Input mask matrix must be of @ref CV_8UC1 type, two other inout matrices and output matrix should be of the same type. The size should -be the same for all input and output matrices. -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.pixelwise.select" - -@param src1 first input matrix. -@param src2 second input matrix. -@param mask mask input matrix. -*/ -GAPI_EXPORTS_W GMat select(const GMat& src1, const GMat& src2, const GMat& mask); - -//! @} gapi_pixelwise - - -//! @addtogroup gapi_matrixop -//! @{ -/** @brief Calculates per-element minimum of two matrices. - -The function min calculates the per-element minimum of two matrices of the same size, number of channels and depth: -\f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{src2} (I))\f] - where I is a multi-dimensional index of matrix elements. In case of - multi-channel matrices, each channel is processed independently. -Output matrix must be of the same size and depth as src1. - -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.matrixop.min" -@param src1 first input matrix. -@param src2 second input matrix of the same size and depth as src1. -@sa max, cmpEQ, cmpLT, cmpLE -*/ -GAPI_EXPORTS_W GMat min(const GMat& src1, const GMat& src2); - -/** @brief Calculates per-element maximum of two matrices. - -The function max calculates the per-element maximum of two matrices of the same size, number of channels and depth: -\f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{src2} (I))\f] - where I is a multi-dimensional index of matrix elements. In case of - multi-channel matrices, each channel is processed independently. -Output matrix must be of the same size and depth as src1. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.matrixop.max" -@param src1 first input matrix. -@param src2 second input matrix of the same size and depth as src1. -@sa min, compare, cmpEQ, cmpGT, cmpGE -*/ -GAPI_EXPORTS_W GMat max(const GMat& src1, const GMat& src2); - -/** @brief Calculates the per-element absolute difference between two matrices. - -The function absDiff calculates absolute difference between two matrices of the same size and depth: - \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2}(I)|)\f] - where I is a multi-dimensional index of matrix elements. In case of - multi-channel matrices, each channel is processed independently. -Output matrix must have the same size and depth as input matrices. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.matrixop.absdiff" -@param src1 first input matrix. -@param src2 second input matrix. -@sa abs -*/ -GAPI_EXPORTS_W GMat absDiff(const GMat& src1, const GMat& src2); - -/** @brief Calculates absolute value of matrix elements. - -The function abs calculates absolute difference between matrix elements and given scalar value: - \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{matC}(I)|)\f] - where matC is constructed from given scalar c and has the same sizes and depth as input matrix src. - -Output matrix must be of the same size and depth as src. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.matrixop.absdiffC" -@param src input matrix. -@param c scalar to be subtracted. -@sa min, max -*/ -GAPI_EXPORTS_W GMat absDiffC(const GMat& src, const GScalar& c); - -/** @brief Calculates sum of all matrix elements. - -The function sum calculates sum of all matrix elements, independently for each channel. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.matrixop.sum" -@param src input matrix. -@sa countNonZero, mean, min, max -*/ -GAPI_EXPORTS_W GScalar sum(const GMat& src); - -/** @brief Counts non-zero array elements. - -The function returns the number of non-zero elements in src : -\f[\sum _{I: \; \texttt{src} (I) \ne0 } 1\f] - -Supported matrix data types are @ref CV_8UC1, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.matrixop.countNonZero" -@param src input single-channel matrix. -@sa mean, min, max -*/ -GAPI_EXPORTS_W GOpaque countNonZero(const GMat& src); - -/** @brief Calculates the weighted sum of two matrices. - -The function addWeighted calculates the weighted sum of two matrices as follows: -\f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{src1} (I)* \texttt{alpha} + \texttt{src2} (I)* \texttt{beta} + \texttt{gamma} )\f] -where I is a multi-dimensional index of array elements. In case of multi-channel matrices, each -channel is processed independently. - -The function can be replaced with a matrix expression: - \f[\texttt{dst}(I) = \texttt{alpha} * \texttt{src1}(I) - \texttt{beta} * \texttt{src2}(I) + \texttt{gamma} \f] - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.matrixop.addweighted" -@param src1 first input matrix. -@param alpha weight of the first matrix elements. -@param src2 second input matrix of the same size and channel number as src1. -@param beta weight of the second matrix elements. -@param gamma scalar added to each sum. -@param ddepth optional depth of the output matrix. -@sa add, sub -*/ -GAPI_EXPORTS_W GMat addWeighted(const GMat& src1, double alpha, const GMat& src2, double beta, double gamma, int ddepth = -1); - -/** @brief Calculates the absolute L1 norm of a matrix. - -This version of normL1 calculates the absolute L1 norm of src. - -As example for one array consider the function \f$r(x)= \begin{pmatrix} x \\ 1-x \end{pmatrix}, x \in [-1;1]\f$. -The \f$ L_{1} \f$ norm for the sample value \f$r(-1) = \begin{pmatrix} -1 \\ 2 \end{pmatrix}\f$ -is calculated as follows -\f{align*} - \| r(-1) \|_{L_1} &= |-1| + |2| = 3 \\ -\f} -and for \f$r(0.5) = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}\f$ the calculation is -\f{align*} - \| r(0.5) \|_{L_1} &= |0.5| + |0.5| = 1 \\ -\f} - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.matrixop.norml1" -@param src input matrix. -@sa normL2, normInf -*/ -GAPI_EXPORTS_W GScalar normL1(const GMat& src); - -/** @brief Calculates the absolute L2 norm of a matrix. - -This version of normL2 calculates the absolute L2 norm of src. - -As example for one array consider the function \f$r(x)= \begin{pmatrix} x \\ 1-x \end{pmatrix}, x \in [-1;1]\f$. -The \f$ L_{2} \f$ norm for the sample value \f$r(-1) = \begin{pmatrix} -1 \\ 2 \end{pmatrix}\f$ -is calculated as follows -\f{align*} - \| r(-1) \|_{L_2} &= \sqrt{(-1)^{2} + (2)^{2}} = \sqrt{5} \\ -\f} -and for \f$r(0.5) = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}\f$ the calculation is -\f{align*} - \| r(0.5) \|_{L_2} &= \sqrt{(0.5)^{2} + (0.5)^{2}} = \sqrt{0.5} \\ -\f} - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. -@note Function textual ID is "org.opencv.core.matrixop.norml2" -@param src input matrix. -@sa normL1, normInf -*/ -GAPI_EXPORTS_W GScalar normL2(const GMat& src); - -/** @brief Calculates the absolute infinite norm of a matrix. - -This version of normInf calculates the absolute infinite norm of src. - -As example for one array consider the function \f$r(x)= \begin{pmatrix} x \\ 1-x \end{pmatrix}, x \in [-1;1]\f$. -The \f$ L_{\infty} \f$ norm for the sample value \f$r(-1) = \begin{pmatrix} -1 \\ 2 \end{pmatrix}\f$ -is calculated as follows -\f{align*} - \| r(-1) \|_{L_\infty} &= \max(|-1|,|2|) = 2 -\f} -and for \f$r(0.5) = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}\f$ the calculation is -\f{align*} - \| r(0.5) \|_{L_\infty} &= \max(|0.5|,|0.5|) = 0.5. -\f} - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.matrixop.norminf" -@param src input matrix. -@sa normL1, normL2 -*/ -GAPI_EXPORTS_W GScalar normInf(const GMat& src); - -/** @brief Calculates the integral of an image. - -The function calculates one or more integral images for the source image as follows: - -\f[\texttt{sum} (X,Y) = \sum _{x integral(const GMat& src, int sdepth = -1, int sqdepth = -1); - -/** @brief Applies a fixed-level threshold to each matrix element. - -The function applies fixed-level thresholding to a single- or multiple-channel matrix. -The function is typically used to get a bi-level (binary) image out of a grayscale image ( cmp functions could be also used for -this purpose) or for removing a noise, that is, filtering out pixels with too small or too large -values. There are several types of thresholding supported by the function. They are determined by -type parameter. - -Also, the special values cv::THRESH_OTSU or cv::THRESH_TRIANGLE may be combined with one of the -above values. In these cases, the function determines the optimal threshold value using the Otsu's -or Triangle algorithm and uses it instead of the specified thresh . The function returns the -computed threshold value in addititon to thresholded matrix. -The Otsu's and Triangle methods are implemented only for 8-bit matrices. - -Input image should be single channel only in case of cv::THRESH_OTSU or cv::THRESH_TRIANGLE flags. -Output matrix must be of the same size and depth as src. - -@note Function textual ID is "org.opencv.core.matrixop.threshold" - -@param src input matrix (@ref CV_8UC1, @ref CV_8UC3, or @ref CV_32FC1). -@param thresh threshold value. -@param maxval maximum value to use with the cv::THRESH_BINARY and cv::THRESH_BINARY_INV thresholding -types. -@param type thresholding type (see the cv::ThresholdTypes). - -@sa min, max, cmpGT, cmpLE, cmpGE, cmpLT - */ -GAPI_EXPORTS_W GMat threshold(const GMat& src, const GScalar& thresh, const GScalar& maxval, int type); -/** @overload -This function applicable for all threshold types except cv::THRESH_OTSU and cv::THRESH_TRIANGLE -@note Function textual ID is "org.opencv.core.matrixop.thresholdOT" -*/ -GAPI_EXPORTS_W std::tuple threshold(const GMat& src, const GScalar& maxval, int type); - -/** @brief Applies a range-level threshold to each matrix element. - -The function applies range-level thresholding to a single- or multiple-channel matrix. -It sets output pixel value to OxFF if the corresponding pixel value of input matrix is in specified range,or 0 otherwise. - -Input and output matrices must be CV_8UC1. - -@note Function textual ID is "org.opencv.core.matrixop.inRange" - -@param src input matrix (CV_8UC1). -@param threshLow lower boundary value. -@param threshUp upper boundary value. - -@sa threshold - */ -GAPI_EXPORTS_W GMat inRange(const GMat& src, const GScalar& threshLow, const GScalar& threshUp); - -//! @} gapi_matrixop - -//! @addtogroup gapi_transform -//! @{ -/** @brief Creates one 4-channel matrix out of 4 single-channel ones. - -The function merges several matrices to make a single multi-channel matrix. That is, each -element of the output matrix will be a concatenation of the elements of the input matrices, where -elements of i-th input matrix are treated as mv[i].channels()-element vectors. -Output matrix must be of @ref CV_8UC4 type. - -The function split4 does the reverse operation. - -@note - - Function textual ID is "org.opencv.core.transform.merge4" - -@param src1 first input @ref CV_8UC1 matrix to be merged. -@param src2 second input @ref CV_8UC1 matrix to be merged. -@param src3 third input @ref CV_8UC1 matrix to be merged. -@param src4 fourth input @ref CV_8UC1 matrix to be merged. -@sa merge3, split4, split3 -*/ -GAPI_EXPORTS_W GMat merge4(const GMat& src1, const GMat& src2, const GMat& src3, const GMat& src4); - -/** @brief Creates one 3-channel matrix out of 3 single-channel ones. - -The function merges several matrices to make a single multi-channel matrix. That is, each -element of the output matrix will be a concatenation of the elements of the input matrices, where -elements of i-th input matrix are treated as mv[i].channels()-element vectors. -Output matrix must be of @ref CV_8UC3 type. - -The function split3 does the reverse operation. - -@note - - Function textual ID is "org.opencv.core.transform.merge3" - -@param src1 first input @ref CV_8UC1 matrix to be merged. -@param src2 second input @ref CV_8UC1 matrix to be merged. -@param src3 third input @ref CV_8UC1 matrix to be merged. -@sa merge4, split4, split3 -*/ -GAPI_EXPORTS_W GMat merge3(const GMat& src1, const GMat& src2, const GMat& src3); - -/** @brief Divides a 4-channel matrix into 4 single-channel matrices. - -The function splits a 4-channel matrix into 4 single-channel matrices: -\f[\texttt{mv} [c](I) = \texttt{src} (I)_c\f] - -All output matrices must be of @ref CV_8UC1 type. - -The function merge4 does the reverse operation. - -@note - - Function textual ID is "org.opencv.core.transform.split4" - -@param src input @ref CV_8UC4 matrix. -@sa split3, merge3, merge4 -*/ -GAPI_EXPORTS_W std::tuple split4(const GMat& src); - -/** @brief Divides a 3-channel matrix into 3 single-channel matrices. - -The function splits a 3-channel matrix into 3 single-channel matrices: -\f[\texttt{mv} [c](I) = \texttt{src} (I)_c\f] - -All output matrices must be of @ref CV_8UC1 type. - -The function merge3 does the reverse operation. - -@note - - Function textual ID is "org.opencv.core.transform.split3" - -@param src input @ref CV_8UC3 matrix. -@sa split4, merge3, merge4 -*/ -GAPI_EXPORTS_W std::tuple split3(const GMat& src); - -/** @brief Applies a generic geometrical transformation to an image. - -The function remap transforms the source image using the specified map: - -\f[\texttt{dst} (x,y) = \texttt{src} (map_x(x,y),map_y(x,y))\f] - -where values of pixels with non-integer coordinates are computed using one of available -interpolation methods. \f$map_x\f$ and \f$map_y\f$ can be encoded as separate floating-point maps -in \f$map_1\f$ and \f$map_2\f$ respectively, or interleaved floating-point maps of \f$(x,y)\f$ in -\f$map_1\f$, or fixed-point maps created by using convertMaps. The reason you might want to -convert from floating to fixed-point representations of a map is that they can yield much faster -(\~2x) remapping operations. In the converted case, \f$map_1\f$ contains pairs (cvFloor(x), -cvFloor(y)) and \f$map_2\f$ contains indices in a table of interpolation coefficients. -Output image must be of the same size and depth as input one. - -@note - - Function textual ID is "org.opencv.core.transform.remap" - - Due to current implementation limitations the size of an input and output images should be less than 32767x32767. - -@param src Source image. -@param map1 The first map of either (x,y) points or just x values having the type CV_16SC2, -CV_32FC1, or CV_32FC2. -@param map2 The second map of y values having the type CV_16UC1, CV_32FC1, or none (empty map -if map1 is (x,y) points), respectively. -@param interpolation Interpolation method (see cv::InterpolationFlags). The methods #INTER_AREA -and #INTER_LINEAR_EXACT are not supported by this function. -@param borderMode Pixel extrapolation method (see cv::BorderTypes). When -borderMode=BORDER_TRANSPARENT, it means that the pixels in the destination image that -corresponds to the "outliers" in the source image are not modified by the function. -@param borderValue Value used in case of a constant border. By default, it is 0. - */ -GAPI_EXPORTS_W GMat remap(const GMat& src, const Mat& map1, const Mat& map2, - int interpolation, int borderMode = BORDER_CONSTANT, - const Scalar& borderValue = Scalar()); - -/** @brief Flips a 2D matrix around vertical, horizontal, or both axes. - -The function flips the matrix in one of three different ways (row -and column indices are 0-based): -\f[\texttt{dst} _{ij} = -\left\{ -\begin{array}{l l} -\texttt{src} _{\texttt{src.rows}-i-1,j} & if\; \texttt{flipCode} = 0 \\ -\texttt{src} _{i, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} > 0 \\ -\texttt{src} _{ \texttt{src.rows} -i-1, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} < 0 \\ -\end{array} -\right.\f] -The example scenarios of using the function are the following: -* Vertical flipping of the image (flipCode == 0) to switch between - top-left and bottom-left image origin. This is a typical operation - in video processing on Microsoft Windows\* OS. -* Horizontal flipping of the image with the subsequent horizontal - shift and absolute difference calculation to check for a - vertical-axis symmetry (flipCode \> 0). -* Simultaneous horizontal and vertical flipping of the image with - the subsequent shift and absolute difference calculation to check - for a central symmetry (flipCode \< 0). -* Reversing the order of point arrays (flipCode \> 0 or - flipCode == 0). -Output image must be of the same depth as input one, size should be correct for given flipCode. - -@note Function textual ID is "org.opencv.core.transform.flip" - -@param src input matrix. -@param flipCode a flag to specify how to flip the array; 0 means -flipping around the x-axis and positive value (for example, 1) means -flipping around y-axis. Negative value (for example, -1) means flipping -around both axes. -@sa remap -*/ -GAPI_EXPORTS_W GMat flip(const GMat& src, int flipCode); - -/** @brief Crops a 2D matrix. - -The function crops the matrix by given cv::Rect. - -Output matrix must be of the same depth as input one, size is specified by given rect size. - -@note Function textual ID is "org.opencv.core.transform.crop" - -@param src input matrix. -@param rect a rect to crop a matrix to -@sa resize -*/ -GAPI_EXPORTS_W GMat crop(const GMat& src, const Rect& rect); - -/** @brief Applies horizontal concatenation to given matrices. - -The function horizontally concatenates two GMat matrices (with the same number of rows). -@code{.cpp} - GMat A = { 1, 4, - 2, 5, - 3, 6 }; - GMat B = { 7, 10, - 8, 11, - 9, 12 }; - - GMat C = gapi::concatHor(A, B); - //C: - //[1, 4, 7, 10; - // 2, 5, 8, 11; - // 3, 6, 9, 12] -@endcode -Output matrix must the same number of rows and depth as the src1 and src2, and the sum of cols of the src1 and src2. -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.imgproc.transform.concatHor" - -@param src1 first input matrix to be considered for horizontal concatenation. -@param src2 second input matrix to be considered for horizontal concatenation. -@sa concatVert -*/ -GAPI_EXPORTS_W GMat concatHor(const GMat& src1, const GMat& src2); - -/** @overload -The function horizontally concatenates given number of GMat matrices (with the same number of columns). -Output matrix must the same number of columns and depth as the input matrices, and the sum of rows of input matrices. - -@param v vector of input matrices to be concatenated horizontally. -*/ -GAPI_EXPORTS_W GMat concatHor(const std::vector &v); - -/** @brief Applies vertical concatenation to given matrices. - -The function vertically concatenates two GMat matrices (with the same number of cols). - @code{.cpp} - GMat A = { 1, 7, - 2, 8, - 3, 9 }; - GMat B = { 4, 10, - 5, 11, - 6, 12 }; - - GMat C = gapi::concatVert(A, B); - //C: - //[1, 7; - // 2, 8; - // 3, 9; - // 4, 10; - // 5, 11; - // 6, 12] - @endcode - -Output matrix must the same number of cols and depth as the src1 and src2, and the sum of rows of the src1 and src2. -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.imgproc.transform.concatVert" - -@param src1 first input matrix to be considered for vertical concatenation. -@param src2 second input matrix to be considered for vertical concatenation. -@sa concatHor -*/ -GAPI_EXPORTS_W GMat concatVert(const GMat& src1, const GMat& src2); - -/** @overload -The function vertically concatenates given number of GMat matrices (with the same number of columns). -Output matrix must the same number of columns and depth as the input matrices, and the sum of rows of input matrices. - -@param v vector of input matrices to be concatenated vertically. -*/ -GAPI_EXPORTS_W GMat concatVert(const std::vector &v); - - -/** @brief Performs a look-up table transform of a matrix. - -The function LUT fills the output matrix with values from the look-up table. Indices of the entries -are taken from the input matrix. That is, the function processes each element of src as follows: -\f[\texttt{dst} (I) \leftarrow \texttt{lut(src(I))}\f] - -Supported matrix data types are @ref CV_8UC1. -Output is a matrix of the same size and number of channels as src, and the same depth as lut. - -@note Function textual ID is "org.opencv.core.transform.LUT" - -@param src input matrix of 8-bit elements. -@param lut look-up table of 256 elements; in case of multi-channel input array, the table should -either have a single channel (in this case the same table is used for all channels) or the same -number of channels as in the input matrix. -*/ -GAPI_EXPORTS_W GMat LUT(const GMat& src, const Mat& lut); - -/** @brief Converts a matrix to another data depth with optional scaling. - -The method converts source pixel values to the target data depth. saturate_cast\<\> is applied at -the end to avoid possible overflows: - -\f[m(x,y) = saturate \_ cast( \alpha (*this)(x,y) + \beta )\f] -Output matrix must be of the same size as input one. - -@note Function textual ID is "org.opencv.core.transform.convertTo" -@param src input matrix to be converted from. -@param rdepth desired output matrix depth or, rather, the depth since the number of channels are the -same as the input has; if rdepth is negative, the output matrix will have the same depth as the input. -@param alpha optional scale factor. -@param beta optional delta added to the scaled values. - */ -GAPI_EXPORTS_W GMat convertTo(const GMat& src, int rdepth, double alpha=1, double beta=0); - -/** @brief Normalizes the norm or value range of an array. - -The function normalizes scale and shift the input array elements so that -\f[\| \texttt{dst} \| _{L_p}= \texttt{alpha}\f] -(where p=Inf, 1 or 2) when normType=NORM_INF, NORM_L1, or NORM_L2, respectively; or so that -\f[\min _I \texttt{dst} (I)= \texttt{alpha} , \, \, \max _I \texttt{dst} (I)= \texttt{beta}\f] -when normType=NORM_MINMAX (for dense arrays only). - -@note Function textual ID is "org.opencv.core.normalize" - -@param src input array. -@param alpha norm value to normalize to or the lower range boundary in case of the range -normalization. -@param beta upper range boundary in case of the range normalization; it is not used for the norm -normalization. -@param norm_type normalization type (see cv::NormTypes). -@param ddepth when negative, the output array has the same type as src; otherwise, it has the same -number of channels as src and the depth =ddepth. -@sa norm, Mat::convertTo -*/ -GAPI_EXPORTS_W GMat normalize(const GMat& src, double alpha, double beta, - int norm_type, int ddepth = -1); - -/** @brief Applies a perspective transformation to an image. - -The function warpPerspective transforms the source image using the specified matrix: - -\f[\texttt{dst} (x,y) = \texttt{src} \left ( \frac{M_{11} x + M_{12} y + M_{13}}{M_{31} x + M_{32} y + M_{33}} , - \frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}} \right )\f] - -when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted with invert -and then put in the formula above instead of M. The function cannot operate in-place. - -@param src input image. -@param M \f$3\times 3\f$ transformation matrix. -@param dsize size of the output image. -@param flags combination of interpolation methods (#INTER_LINEAR or #INTER_NEAREST) and the -optional flag #WARP_INVERSE_MAP, that sets M as the inverse transformation ( -\f$\texttt{dst}\rightarrow\texttt{src}\f$ ). -@param borderMode pixel extrapolation method (#BORDER_CONSTANT or #BORDER_REPLICATE). -@param borderValue value used in case of a constant border; by default, it equals 0. - -@sa warpAffine, resize, remap, getRectSubPix, perspectiveTransform - */ -GAPI_EXPORTS_W GMat warpPerspective(const GMat& src, const Mat& M, const Size& dsize, int flags = cv::INTER_LINEAR, - int borderMode = cv::BORDER_CONSTANT, const Scalar& borderValue = Scalar()); - -/** @brief Applies an affine transformation to an image. - -The function warpAffine transforms the source image using the specified matrix: - -\f[\texttt{dst} (x,y) = \texttt{src} ( \texttt{M} _{11} x + \texttt{M} _{12} y + \texttt{M} _{13}, \texttt{M} _{21} x + \texttt{M} _{22} y + \texttt{M} _{23})\f] - -when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted -with #invertAffineTransform and then put in the formula above instead of M. The function cannot -operate in-place. - -@param src input image. -@param M \f$2\times 3\f$ transformation matrix. -@param dsize size of the output image. -@param flags combination of interpolation methods (see #InterpolationFlags) and the optional -flag #WARP_INVERSE_MAP that means that M is the inverse transformation ( -\f$\texttt{dst}\rightarrow\texttt{src}\f$ ). -@param borderMode pixel extrapolation method (see #BorderTypes); -borderMode=#BORDER_TRANSPARENT isn't supported -@param borderValue value used in case of a constant border; by default, it is 0. - -@sa warpPerspective, resize, remap, getRectSubPix, transform - */ -GAPI_EXPORTS_W GMat warpAffine(const GMat& src, const Mat& M, const Size& dsize, int flags = cv::INTER_LINEAR, - int borderMode = cv::BORDER_CONSTANT, const Scalar& borderValue = Scalar()); -//! @} gapi_transform - -/** @brief Finds centers of clusters and groups input samples around the clusters. - -The function kmeans implements a k-means algorithm that finds the centers of K clusters -and groups the input samples around the clusters. As an output, \f$\texttt{bestLabels}_i\f$ -contains a 0-based cluster index for the \f$i^{th}\f$ sample. - -@note - - Function textual ID is "org.opencv.core.kmeansND" - - In case of an N-dimentional points' set given, input GMat can have the following traits: -2 dimensions, a single row or column if there are N channels, -or N columns if there is a single channel. Mat should have @ref CV_32F depth. - - Although, if GMat with height != 1, width != 1, channels != 1 given as data, n-dimensional -samples are considered given in amount of A, where A = height, n = width * channels. - - In case of GMat given as data: - - the output labels are returned as 1-channel GMat with sizes -width = 1, height = A, where A is samples amount, or width = bestLabels.width, -height = bestLabels.height if bestLabels given; - - the cluster centers are returned as 1-channel GMat with sizes -width = n, height = K, where n is samples' dimentionality and K is clusters' amount. - - As one of possible usages, if you want to control the initial labels for each attempt -by yourself, you can utilize just the core of the function. To do that, set the number -of attempts to 1, initialize labels each time using a custom algorithm, pass them with the -( flags = #KMEANS_USE_INITIAL_LABELS ) flag, and then choose the best (most-compact) clustering. - -@param data Data for clustering. An array of N-Dimensional points with float coordinates is needed. -Function can take GArray, GArray for 2D and 3D cases or GMat for any -dimentionality and channels. -@param K Number of clusters to split the set by. -@param bestLabels Optional input integer array that can store the supposed initial cluster indices -for every sample. Used when ( flags = #KMEANS_USE_INITIAL_LABELS ) flag is set. -@param criteria The algorithm termination criteria, that is, the maximum number of iterations -and/or the desired accuracy. The accuracy is specified as criteria.epsilon. As soon as each of -the cluster centers moves by less than criteria.epsilon on some iteration, the algorithm stops. -@param attempts Flag to specify the number of times the algorithm is executed using different -initial labellings. The algorithm returns the labels that yield the best compactness (see the first -function return value). -@param flags Flag that can take values of cv::KmeansFlags . - -@return - - Compactness measure that is computed as -\f[\sum _i \| \texttt{samples} _i - \texttt{centers} _{ \texttt{labels} _i} \| ^2\f] -after every attempt. The best (minimum) value is chosen and the corresponding labels and the -compactness value are returned by the function. - - Integer array that stores the cluster indices for every sample. - - Array of the cluster centers. -*/ -GAPI_EXPORTS_W std::tuple,GMat,GMat> -kmeans(const GMat& data, const int K, const GMat& bestLabels, - const TermCriteria& criteria, const int attempts, const KmeansFlags flags); - -/** @overload -@note - - Function textual ID is "org.opencv.core.kmeansNDNoInit" - - #KMEANS_USE_INITIAL_LABELS flag must not be set while using this overload. - */ -GAPI_EXPORTS_W std::tuple,GMat,GMat> -kmeans(const GMat& data, const int K, const TermCriteria& criteria, const int attempts, - const KmeansFlags flags); - -/** @overload -@note Function textual ID is "org.opencv.core.kmeans2D" - */ -GAPI_EXPORTS_W std::tuple,GArray,GArray> -kmeans(const GArray& data, const int K, const GArray& bestLabels, - const TermCriteria& criteria, const int attempts, const KmeansFlags flags); - -/** @overload -@note Function textual ID is "org.opencv.core.kmeans3D" - */ -GAPI_EXPORTS_W std::tuple,GArray,GArray> -kmeans(const GArray& data, const int K, const GArray& bestLabels, - const TermCriteria& criteria, const int attempts, const KmeansFlags flags); - - -/** @brief Transposes a matrix. - -The function transposes the matrix: -\f[\texttt{dst} (i,j) = \texttt{src} (j,i)\f] - -@note - - Function textual ID is "org.opencv.core.transpose" - - No complex conjugation is done in case of a complex matrix. It should be done separately if needed. - -@param src input array. -*/ -GAPI_EXPORTS_W GMat transpose(const GMat& src); - - -namespace streaming { -/** @brief Gets dimensions from Mat. - -@note Function textual ID is "org.opencv.streaming.size" - -@param src Input tensor -@return Size (tensor dimensions). -*/ -GAPI_EXPORTS_W GOpaque size(const GMat& src); - -/** @overload -Gets dimensions from rectangle. - -@note Function textual ID is "org.opencv.streaming.sizeR" - -@param r Input rectangle. -@return Size (rectangle dimensions). -*/ -GAPI_EXPORTS_W GOpaque size(const GOpaque& r); - -/** @brief Gets dimensions from MediaFrame. - -@note Function textual ID is "org.opencv.streaming.sizeMF" - -@param src Input frame -@return Size (frame dimensions). -*/ -GAPI_EXPORTS_W GOpaque size(const GFrame& src); -} //namespace streaming -} //namespace gapi -} //namespace cv - -#endif //OPENCV_GAPI_CORE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2020 Intel Corporation + + +#ifndef OPENCV_GAPI_CORE_HPP +#define OPENCV_GAPI_CORE_HPP + +#include +#include // std::tuple + +#include +#include + +#include +#include +#include +#include + +/** \defgroup gapi_core G-API Core functionality +@{ + @defgroup gapi_math Graph API: Math operations + @defgroup gapi_pixelwise Graph API: Pixelwise operations + @defgroup gapi_matrixop Graph API: Operations on matrices + @defgroup gapi_transform Graph API: Image and channel composition functions +@} + */ + +namespace cv { namespace gapi { +/** + * @brief This namespace contains G-API Operation Types for OpenCV + * Core module functionality. + */ +namespace core { + using GResize = cv::gapi::imgproc::GResize; + using GResizeP = cv::gapi::imgproc::GResizeP; + + using GMat2 = std::tuple; + using GMat3 = std::tuple; // FIXME: how to avoid this? + using GMat4 = std::tuple; + using GMatScalar = std::tuple; + + G_TYPED_KERNEL(GAdd, , "org.opencv.core.math.add") { + static GMatDesc outMeta(GMatDesc a, GMatDesc b, int ddepth) { + if (ddepth == -1) + { + // OpenCV: When the input arrays in add/subtract/multiply/divide + // functions have different depths, the output array depth must be + // explicitly specified! + // See artim_op() @ arithm.cpp + GAPI_Assert(a.chan == b.chan); + GAPI_Assert(a.depth == b.depth); + return a; + } + return a.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GAddC, , "org.opencv.core.math.addC") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc, int ddepth) { + GAPI_Assert(a.chan <= 4); + return a.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GSub, , "org.opencv.core.math.sub") { + static GMatDesc outMeta(GMatDesc a, GMatDesc b, int ddepth) { + if (ddepth == -1) + { + // This macro should select a larger data depth from a and b + // considering the number of channels in the same + // FIXME!!! Clarify if it is valid for sub() + GAPI_Assert(a.chan == b.chan); + ddepth = std::max(a.depth, b.depth); + } + return a.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GSubC, , "org.opencv.core.math.subC") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc, int ddepth) { + return a.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GSubRC,, "org.opencv.core.math.subRC") { + static GMatDesc outMeta(GScalarDesc, GMatDesc b, int ddepth) { + return b.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GMul, , "org.opencv.core.math.mul") { + static GMatDesc outMeta(GMatDesc a, GMatDesc, double, int ddepth) { + return a.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GMulCOld, , "org.opencv.core.math.mulCOld") { + static GMatDesc outMeta(GMatDesc a, double, int ddepth) { + return a.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GMulC, , "org.opencv.core.math.mulC") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc, int ddepth) { + return a.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GMulS, , "org.opencv.core.math.muls") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc) { + return a; + } + }; // FIXME: Merge with MulC + + G_TYPED_KERNEL(GDiv, , "org.opencv.core.math.div") { + static GMatDesc outMeta(GMatDesc a, GMatDesc b, double, int ddepth) { + if (ddepth == -1) + { + GAPI_Assert(a.depth == b.depth); + return b; + } + return a.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GDivC, , "org.opencv.core.math.divC") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc, double, int ddepth) { + return a.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GDivRC, , "org.opencv.core.math.divRC") { + static GMatDesc outMeta(GScalarDesc, GMatDesc b, double, int ddepth) { + return b.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GMean, , "org.opencv.core.math.mean") { + static GScalarDesc outMeta(GMatDesc) { + return empty_scalar_desc(); + } + }; + + G_TYPED_KERNEL_M(GPolarToCart, , "org.opencv.core.math.polarToCart") { + static std::tuple outMeta(GMatDesc, GMatDesc a, bool) { + return std::make_tuple(a, a); + } + }; + + G_TYPED_KERNEL_M(GCartToPolar, , "org.opencv.core.math.cartToPolar") { + static std::tuple outMeta(GMatDesc x, GMatDesc, bool) { + return std::make_tuple(x, x); + } + }; + + G_TYPED_KERNEL(GPhase, , "org.opencv.core.math.phase") { + static GMatDesc outMeta(const GMatDesc &inx, const GMatDesc &, bool) { + return inx; + } + }; + + G_TYPED_KERNEL(GMask, , "org.opencv.core.pixelwise.mask") { + static GMatDesc outMeta(GMatDesc in, GMatDesc) { + return in; + } + }; + + G_TYPED_KERNEL(GCmpGT, , "org.opencv.core.pixelwise.compare.cmpGT") { + static GMatDesc outMeta(GMatDesc a, GMatDesc) { + return a.withDepth(CV_8U); + } + }; + + G_TYPED_KERNEL(GCmpGE, , "org.opencv.core.pixelwise.compare.cmpGE") { + static GMatDesc outMeta(GMatDesc a, GMatDesc) { + return a.withDepth(CV_8U); + } + }; + + G_TYPED_KERNEL(GCmpLE, , "org.opencv.core.pixelwise.compare.cmpLE") { + static GMatDesc outMeta(GMatDesc a, GMatDesc) { + return a.withDepth(CV_8U); + } + }; + + G_TYPED_KERNEL(GCmpLT, , "org.opencv.core.pixelwise.compare.cmpLT") { + static GMatDesc outMeta(GMatDesc a, GMatDesc) { + return a.withDepth(CV_8U); + } + }; + + G_TYPED_KERNEL(GCmpEQ, , "org.opencv.core.pixelwise.compare.cmpEQ") { + static GMatDesc outMeta(GMatDesc a, GMatDesc) { + return a.withDepth(CV_8U); + } + }; + + G_TYPED_KERNEL(GCmpNE, , "org.opencv.core.pixelwise.compare.cmpNE") { + static GMatDesc outMeta(GMatDesc a, GMatDesc) { + return a.withDepth(CV_8U); + } + }; + + G_TYPED_KERNEL(GCmpGTScalar, , "org.opencv.core.pixelwise.compare.cmpGTScalar") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc) { + return a.withDepth(CV_8U); + } + }; + + G_TYPED_KERNEL(GCmpGEScalar, , "org.opencv.core.pixelwise.compare.cmpGEScalar") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc) { + return a.withDepth(CV_8U); + } + }; + + G_TYPED_KERNEL(GCmpLEScalar, , "org.opencv.core.pixelwise.compare.cmpLEScalar") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc) { + return a.withDepth(CV_8U); + } + }; + + G_TYPED_KERNEL(GCmpLTScalar, , "org.opencv.core.pixelwise.compare.cmpLTScalar") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc) { + return a.withDepth(CV_8U); + } + }; + + G_TYPED_KERNEL(GCmpEQScalar, , "org.opencv.core.pixelwise.compare.cmpEQScalar") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc) { + return a.withDepth(CV_8U); + } + }; + + G_TYPED_KERNEL(GCmpNEScalar, , "org.opencv.core.pixelwise.compare.cmpNEScalar") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc) { + return a.withDepth(CV_8U); + } + }; + + G_TYPED_KERNEL(GAnd, , "org.opencv.core.pixelwise.bitwise_and") { + static GMatDesc outMeta(GMatDesc a, GMatDesc) { + return a; + } + }; + + G_TYPED_KERNEL(GAndS, , "org.opencv.core.pixelwise.bitwise_andS") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc) { + return a; + } + }; + + G_TYPED_KERNEL(GOr, , "org.opencv.core.pixelwise.bitwise_or") { + static GMatDesc outMeta(GMatDesc a, GMatDesc) { + return a; + } + }; + + G_TYPED_KERNEL(GOrS, , "org.opencv.core.pixelwise.bitwise_orS") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc) { + return a; + } + }; + + G_TYPED_KERNEL(GXor, , "org.opencv.core.pixelwise.bitwise_xor") { + static GMatDesc outMeta(GMatDesc a, GMatDesc) { + return a; + } + }; + + G_TYPED_KERNEL(GXorS, , "org.opencv.core.pixelwise.bitwise_xorS") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc) { + return a; + } + }; + + G_TYPED_KERNEL(GNot, , "org.opencv.core.pixelwise.bitwise_not") { + static GMatDesc outMeta(GMatDesc a) { + return a; + } + }; + + G_TYPED_KERNEL(GSelect, , "org.opencv.core.pixelwise.select") { + static GMatDesc outMeta(GMatDesc a, GMatDesc, GMatDesc) { + return a; + } + }; + + G_TYPED_KERNEL(GMin, , "org.opencv.core.matrixop.min") { + static GMatDesc outMeta(GMatDesc a, GMatDesc) { + return a; + } + }; + + G_TYPED_KERNEL(GMax, , "org.opencv.core.matrixop.max") { + static GMatDesc outMeta(GMatDesc a, GMatDesc) { + return a; + } + }; + + G_TYPED_KERNEL(GAbsDiff, , "org.opencv.core.matrixop.absdiff") { + static GMatDesc outMeta(GMatDesc a, GMatDesc) { + return a; + } + }; + + G_TYPED_KERNEL(GAbsDiffC, , "org.opencv.core.matrixop.absdiffC") { + static GMatDesc outMeta(const GMatDesc& a, const GScalarDesc&) { + return a; + } + }; + + G_TYPED_KERNEL(GSum, , "org.opencv.core.matrixop.sum") { + static GScalarDesc outMeta(GMatDesc) { + return empty_scalar_desc(); + } + }; + + G_TYPED_KERNEL(GCountNonZero, (GMat)>, "org.opencv.core.matrixop.countNonZero") { + static GOpaqueDesc outMeta(GMatDesc in) { + GAPI_Assert(in.chan == 1); + return empty_gopaque_desc(); + } + }; + + G_TYPED_KERNEL(GAddW, , "org.opencv.core.matrixop.addweighted") { + static GMatDesc outMeta(GMatDesc a, double, GMatDesc b, double, double, int ddepth) { + if (ddepth == -1) + { + // OpenCV: When the input arrays in add/subtract/multiply/divide + // functions have different depths, the output array depth must be + // explicitly specified! + // See artim_op() @ arithm.cpp + GAPI_Assert(a.chan == b.chan); + GAPI_Assert(a.depth == b.depth); + return a; + } + return a.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GNormL1, , "org.opencv.core.matrixop.norml1") { + static GScalarDesc outMeta(GMatDesc) { + return empty_scalar_desc(); + } + }; + + G_TYPED_KERNEL(GNormL2, , "org.opencv.core.matrixop.norml2") { + static GScalarDesc outMeta(GMatDesc) { + return empty_scalar_desc(); + } + }; + + G_TYPED_KERNEL(GNormInf, , "org.opencv.core.matrixop.norminf") { + static GScalarDesc outMeta(GMatDesc) { + return empty_scalar_desc(); + } + }; + + G_TYPED_KERNEL_M(GIntegral, , "org.opencv.core.matrixop.integral") { + static std::tuple outMeta(GMatDesc in, int sd, int sqd) { + return std::make_tuple(in.withSizeDelta(1,1).withDepth(sd), + in.withSizeDelta(1,1).withDepth(sqd)); + } + }; + + G_TYPED_KERNEL(GThreshold, , "org.opencv.core.matrixop.threshold") { + static GMatDesc outMeta(GMatDesc in, GScalarDesc, GScalarDesc, int) { + return in; + } + }; + + + G_TYPED_KERNEL_M(GThresholdOT, , "org.opencv.core.matrixop.thresholdOT") { + static std::tuple outMeta(GMatDesc in, GScalarDesc, int) { + return std::make_tuple(in, empty_scalar_desc()); + } + }; + + G_TYPED_KERNEL(GInRange, , "org.opencv.core.matrixop.inrange") { + static GMatDesc outMeta(GMatDesc in, GScalarDesc, GScalarDesc) { + return in.withType(CV_8U, 1); + } + }; + + G_TYPED_KERNEL_M(GSplit3, , "org.opencv.core.transform.split3") { + static std::tuple outMeta(GMatDesc in) { + const auto out_depth = in.depth; + const auto out_desc = in.withType(out_depth, 1); + return std::make_tuple(out_desc, out_desc, out_desc); + } + }; + + G_TYPED_KERNEL_M(GSplit4, ,"org.opencv.core.transform.split4") { + static std::tuple outMeta(GMatDesc in) { + const auto out_depth = in.depth; + const auto out_desc = in.withType(out_depth, 1); + return std::make_tuple(out_desc, out_desc, out_desc, out_desc); + } + }; + + G_TYPED_KERNEL(GMerge3, , "org.opencv.core.transform.merge3") { + static GMatDesc outMeta(GMatDesc in, GMatDesc, GMatDesc) { + // Preserve depth and add channel component + return in.withType(in.depth, 3); + } + }; + + G_TYPED_KERNEL(GMerge4, , "org.opencv.core.transform.merge4") { + static GMatDesc outMeta(GMatDesc in, GMatDesc, GMatDesc, GMatDesc) { + // Preserve depth and add channel component + return in.withType(in.depth, 4); + } + }; + + G_TYPED_KERNEL(GRemap, , "org.opencv.core.transform.remap") { + static GMatDesc outMeta(GMatDesc in, Mat m1, Mat, int, int, Scalar) { + return in.withSize(m1.size()); + } + }; + + G_TYPED_KERNEL(GFlip, , "org.opencv.core.transform.flip") { + static GMatDesc outMeta(GMatDesc in, int) { + return in; + } + }; + + // TODO: eliminate the need in this kernel (streaming) + G_TYPED_KERNEL(GCrop, , "org.opencv.core.transform.crop") { + static GMatDesc outMeta(GMatDesc in, Rect rc) { + return in.withSize(Size(rc.width, rc.height)); + } + }; + + G_TYPED_KERNEL(GConcatHor, , "org.opencv.imgproc.transform.concatHor") { + static GMatDesc outMeta(GMatDesc l, GMatDesc r) { + return l.withSizeDelta(+r.size.width, 0); + } + }; + + G_TYPED_KERNEL(GConcatVert, , "org.opencv.imgproc.transform.concatVert") { + static GMatDesc outMeta(GMatDesc t, GMatDesc b) { + return t.withSizeDelta(0, +b.size.height); + } + }; + + G_TYPED_KERNEL(GLUT, , "org.opencv.core.transform.LUT") { + static GMatDesc outMeta(GMatDesc in, Mat) { + return in; + } + }; + + G_TYPED_KERNEL(GConvertTo, , "org.opencv.core.transform.convertTo") { + static GMatDesc outMeta(GMatDesc in, int rdepth, double, double) { + return rdepth < 0 ? in : in.withDepth(rdepth); + } + }; + + G_TYPED_KERNEL(GSqrt, , "org.opencv.core.math.sqrt") { + static GMatDesc outMeta(GMatDesc in) { + return in; + } + }; + + G_TYPED_KERNEL(GNormalize, , "org.opencv.core.normalize") { + static GMatDesc outMeta(GMatDesc in, double, double, int, int ddepth) { + // unlike opencv doesn't have a mask as a parameter + return (ddepth < 0 ? in : in.withDepth(ddepth)); + } + }; + + G_TYPED_KERNEL(GWarpPerspective, , "org.opencv.core.warpPerspective") { + static GMatDesc outMeta(GMatDesc in, const Mat&, Size dsize, int, int borderMode, const cv::Scalar&) { + GAPI_Assert((borderMode == cv::BORDER_CONSTANT || borderMode == cv::BORDER_REPLICATE) && + "cv::gapi::warpPerspective supports only cv::BORDER_CONSTANT and cv::BORDER_REPLICATE border modes"); + return in.withType(in.depth, in.chan).withSize(dsize); + } + }; + + G_TYPED_KERNEL(GWarpAffine, , "org.opencv.core.warpAffine") { + static GMatDesc outMeta(GMatDesc in, const Mat&, Size dsize, int, int border_mode, const cv::Scalar&) { + GAPI_Assert(border_mode != cv::BORDER_TRANSPARENT && + "cv::BORDER_TRANSPARENT mode is not supported in cv::gapi::warpAffine"); + return in.withType(in.depth, in.chan).withSize(dsize); + } + }; + + G_TYPED_KERNEL( + GKMeansND, + ,GMat,GMat>(GMat,int,GMat,TermCriteria,int,KmeansFlags)>, + "org.opencv.core.kmeansND") { + + static std::tuple + outMeta(const GMatDesc& in, int K, const GMatDesc& bestLabels, const TermCriteria&, int, + KmeansFlags flags) { + GAPI_Assert(in.depth == CV_32F); + std::vector amount_n_dim = detail::checkVector(in); + int amount = amount_n_dim[0], dim = amount_n_dim[1]; + if (amount == -1) // Mat with height != 1, width != 1, channels != 1 given + { // which means that kmeans will consider the following: + amount = in.size.height; + dim = in.size.width * in.chan; + } + // kmeans sets these labels' sizes when no bestLabels given: + GMatDesc out_labels(CV_32S, 1, Size{1, amount}); + // kmeans always sets these centers' sizes: + GMatDesc centers (CV_32F, 1, Size{dim, K}); + if (flags & KMEANS_USE_INITIAL_LABELS) + { + GAPI_Assert(bestLabels.depth == CV_32S); + int labels_amount = detail::checkVector(bestLabels, 1u); + GAPI_Assert(labels_amount == amount); + out_labels = bestLabels; // kmeans preserves bestLabels' sizes if given + } + return std::make_tuple(empty_gopaque_desc(), out_labels, centers); + } + }; + + G_TYPED_KERNEL( + GKMeansNDNoInit, + ,GMat,GMat>(GMat,int,TermCriteria,int,KmeansFlags)>, + "org.opencv.core.kmeansNDNoInit") { + + static std::tuple + outMeta(const GMatDesc& in, int K, const TermCriteria&, int, KmeansFlags flags) { + GAPI_Assert( !(flags & KMEANS_USE_INITIAL_LABELS) ); + GAPI_Assert(in.depth == CV_32F); + std::vector amount_n_dim = detail::checkVector(in); + int amount = amount_n_dim[0], dim = amount_n_dim[1]; + if (amount == -1) // Mat with height != 1, width != 1, channels != 1 given + { // which means that kmeans will consider the following: + amount = in.size.height; + dim = in.size.width * in.chan; + } + GMatDesc out_labels(CV_32S, 1, Size{1, amount}); + GMatDesc centers (CV_32F, 1, Size{dim, K}); + return std::make_tuple(empty_gopaque_desc(), out_labels, centers); + } + }; + + G_TYPED_KERNEL(GKMeans2D, ,GArray,GArray> + (GArray,int,GArray,TermCriteria,int,KmeansFlags)>, + "org.opencv.core.kmeans2D") { + static std::tuple + outMeta(const GArrayDesc&,int,const GArrayDesc&,const TermCriteria&,int,KmeansFlags) { + return std::make_tuple(empty_gopaque_desc(), empty_array_desc(), empty_array_desc()); + } + }; + + G_TYPED_KERNEL(GKMeans3D, ,GArray,GArray> + (GArray,int,GArray,TermCriteria,int,KmeansFlags)>, + "org.opencv.core.kmeans3D") { + static std::tuple + outMeta(const GArrayDesc&,int,const GArrayDesc&,const TermCriteria&,int,KmeansFlags) { + return std::make_tuple(empty_gopaque_desc(), empty_array_desc(), empty_array_desc()); + } + }; + + G_TYPED_KERNEL(GTranspose, , "org.opencv.core.transpose") { + static GMatDesc outMeta(GMatDesc in) { + return in.withSize({in.size.height, in.size.width}); + } + }; +} // namespace core + +namespace streaming { + +// Operations for Streaming (declared in this header for convenience) +G_TYPED_KERNEL(GSize, (GMat)>, "org.opencv.streaming.size") { + static GOpaqueDesc outMeta(const GMatDesc&) { + return empty_gopaque_desc(); + } +}; + +G_TYPED_KERNEL(GSizeR, (GOpaque)>, "org.opencv.streaming.sizeR") { + static GOpaqueDesc outMeta(const GOpaqueDesc&) { + return empty_gopaque_desc(); + } +}; + +G_TYPED_KERNEL(GSizeMF, (GFrame)>, "org.opencv.streaming.sizeMF") { + static GOpaqueDesc outMeta(const GFrameDesc&) { + return empty_gopaque_desc(); + } +}; +} // namespace streaming + +//! @addtogroup gapi_math +//! @{ + +/** @brief Calculates the per-element sum of two matrices. + +The function add calculates sum of two matrices of the same size and the same number of channels: +\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) + \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0\f] + +The function can be replaced with matrix expressions: + \f[\texttt{dst} = \texttt{src1} + \texttt{src2}\f] + +The input matrices and the output matrix can all have the same or different depths. For example, you +can add a 16-bit unsigned matrix to a 8-bit signed matrix and store the sum as a 32-bit +floating-point matrix. Depth of the output matrix is determined by the ddepth parameter. +If src1.depth() == src2.depth(), ddepth can be set to the default -1. In this case, the output matrix will have +the same depth as the input matrices. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.math.add" +@param src1 first input matrix. +@param src2 second input matrix. +@param ddepth optional depth of the output matrix. +@sa sub, addWeighted +*/ +GAPI_EXPORTS_W GMat add(const GMat& src1, const GMat& src2, int ddepth = -1); + +/** @brief Calculates the per-element sum of matrix and given scalar. + +The function addC adds a given scalar value to each element of given matrix. +The function can be replaced with matrix expressions: + + \f[\texttt{dst} = \texttt{src1} + \texttt{c}\f] + +Depth of the output matrix is determined by the ddepth parameter. +If ddepth is set to default -1, the depth of output matrix will be the same as the depth of input matrix. +The matrices can be single or multi channel. Output matrix must have the same size and number of channels as the input matrix. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.math.addC" +@param src1 first input matrix. +@param c scalar value to be added. +@param ddepth optional depth of the output matrix. +@sa sub, addWeighted +*/ +GAPI_EXPORTS_W GMat addC(const GMat& src1, const GScalar& c, int ddepth = -1); +//! @overload +GAPI_EXPORTS_W GMat addC(const GScalar& c, const GMat& src1, int ddepth = -1); + +/** @brief Calculates the per-element difference between two matrices. + +The function sub calculates difference between two matrices, when both matrices have the same size and the same number of +channels: + \f[\texttt{dst}(I) = \texttt{src1}(I) - \texttt{src2}(I)\f] + +The function can be replaced with matrix expressions: +\f[\texttt{dst} = \texttt{src1} - \texttt{src2}\f] + +The input matrices and the output matrix can all have the same or different depths. For example, you +can subtract two 8-bit unsigned matrices store the result as a 16-bit signed matrix. +Depth of the output matrix is determined by the ddepth parameter. +If src1.depth() == src2.depth(), ddepth can be set to the default -1. In this case, the output matrix will have +the same depth as the input matrices. The matrices can be single or multi channel. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.math.sub" +@param src1 first input matrix. +@param src2 second input matrix. +@param ddepth optional depth of the output matrix. +@sa add, addC + */ +GAPI_EXPORTS_W GMat sub(const GMat& src1, const GMat& src2, int ddepth = -1); + +/** @brief Calculates the per-element difference between matrix and given scalar. + +The function can be replaced with matrix expressions: + \f[\texttt{dst} = \texttt{src} - \texttt{c}\f] + +Depth of the output matrix is determined by the ddepth parameter. +If ddepth is set to default -1, the depth of output matrix will be the same as the depth of input matrix. +The matrices can be single or multi channel. Output matrix must have the same size as src. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.math.subC" +@param src first input matrix. +@param c scalar value to subtracted. +@param ddepth optional depth of the output matrix. +@sa add, addC, subRC + */ +GAPI_EXPORTS_W GMat subC(const GMat& src, const GScalar& c, int ddepth = -1); + +/** @brief Calculates the per-element difference between given scalar and the matrix. + +The function can be replaced with matrix expressions: + \f[\texttt{dst} = \texttt{c} - \texttt{src}\f] + +Depth of the output matrix is determined by the ddepth parameter. +If ddepth is set to default -1, the depth of output matrix will be the same as the depth of input matrix. +The matrices can be single or multi channel. Output matrix must have the same size as src. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.math.subRC" +@param c scalar value to subtract from. +@param src input matrix to be subtracted. +@param ddepth optional depth of the output matrix. +@sa add, addC, subC + */ +GAPI_EXPORTS_W GMat subRC(const GScalar& c, const GMat& src, int ddepth = -1); + +/** @brief Calculates the per-element scaled product of two matrices. + +The function mul calculates the per-element product of two matrices: + +\f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{scale} \cdot \texttt{src1} (I) \cdot \texttt{src2} (I))\f] + +If src1.depth() == src2.depth(), ddepth can be set to the default -1. In this case, the output matrix will have +the same depth as the input matrices. The matrices can be single or multi channel. +Output matrix must have the same size as input matrices. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.math.mul" +@param src1 first input matrix. +@param src2 second input matrix of the same size and the same depth as src1. +@param scale optional scale factor. +@param ddepth optional depth of the output matrix. +@sa add, sub, div, addWeighted +*/ +GAPI_EXPORTS_W GMat mul(const GMat& src1, const GMat& src2, double scale = 1.0, int ddepth = -1); + +/** @brief Multiplies matrix by scalar. + +The function mulC multiplies each element of matrix src by given scalar value: + +\f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{src1} (I) \cdot \texttt{multiplier} )\f] + +The matrices can be single or multi channel. Output matrix must have the same size as src. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.math.mulC" +@param src input matrix. +@param multiplier factor to be multiplied. +@param ddepth optional depth of the output matrix. If -1, the depth of output matrix will be the same as input matrix depth. +@sa add, sub, div, addWeighted +*/ +GAPI_EXPORTS_W GMat mulC(const GMat& src, double multiplier, int ddepth = -1); +//! @overload +GAPI_EXPORTS_W GMat mulC(const GMat& src, const GScalar& multiplier, int ddepth = -1); // FIXME: merge with mulc +//! @overload +GAPI_EXPORTS_W GMat mulC(const GScalar& multiplier, const GMat& src, int ddepth = -1); // FIXME: merge with mulc + +/** @brief Performs per-element division of two matrices. + +The function divides one matrix by another: +\f[\texttt{dst(I) = saturate(src1(I)*scale/src2(I))}\f] + +For integer types when src2(I) is zero, dst(I) will also be zero. +Floating point case returns Inf/NaN (according to IEEE). + +Different channels of +multi-channel matrices are processed independently. +The matrices can be single or multi channel. Output matrix must have the same size and depth as src. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.math.div" +@param src1 first input matrix. +@param src2 second input matrix of the same size and depth as src1. +@param scale scalar factor. +@param ddepth optional depth of the output matrix; you can only pass -1 when src1.depth() == src2.depth(). +@sa mul, add, sub +*/ +GAPI_EXPORTS_W GMat div(const GMat& src1, const GMat& src2, double scale, int ddepth = -1); + +/** @brief Divides matrix by scalar. + +The function divC divides each element of matrix src by given scalar value: + +\f[\texttt{dst(I) = saturate(src(I)*scale/divisor)}\f] + +When divisor is zero, dst(I) will also be zero. Different channels of +multi-channel matrices are processed independently. +The matrices can be single or multi channel. Output matrix must have the same size and depth as src. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.math.divC" +@param src input matrix. +@param divisor number to be divided by. +@param ddepth optional depth of the output matrix. If -1, the depth of output matrix will be the same as input matrix depth. +@param scale scale factor. +@sa add, sub, div, addWeighted +*/ +GAPI_EXPORTS_W GMat divC(const GMat& src, const GScalar& divisor, double scale, int ddepth = -1); + +/** @brief Divides scalar by matrix. + +The function divRC divides given scalar by each element of matrix src and keep the division result in new matrix of the same size and type as src: + +\f[\texttt{dst(I) = saturate(divident*scale/src(I))}\f] + +When src(I) is zero, dst(I) will also be zero. Different channels of +multi-channel matrices are processed independently. +The matrices can be single or multi channel. Output matrix must have the same size and depth as src. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.math.divRC" +@param src input matrix. +@param divident number to be divided. +@param ddepth optional depth of the output matrix. If -1, the depth of output matrix will be the same as input matrix depth. +@param scale scale factor +@sa add, sub, div, addWeighted +*/ +GAPI_EXPORTS_W GMat divRC(const GScalar& divident, const GMat& src, double scale, int ddepth = -1); + +/** @brief Applies a mask to a matrix. + +The function mask set value from given matrix if the corresponding pixel value in mask matrix set to true, +and set the matrix value to 0 otherwise. + +Supported src matrix data types are @ref CV_8UC1, @ref CV_16SC1, @ref CV_16UC1. Supported mask data type is @ref CV_8UC1. + +@note Function textual ID is "org.opencv.core.math.mask" +@param src input matrix. +@param mask input mask matrix. +*/ +GAPI_EXPORTS_W GMat mask(const GMat& src, const GMat& mask); + +/** @brief Calculates an average (mean) of matrix elements. + +The function mean calculates the mean value M of matrix elements, +independently for each channel, and return it. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.math.mean" +@param src input matrix. +@sa countNonZero, min, max +*/ +GAPI_EXPORTS_W GScalar mean(const GMat& src); + +/** @brief Calculates x and y coordinates of 2D vectors from their magnitude and angle. + +The function polarToCart calculates the Cartesian coordinates of each 2D +vector represented by the corresponding elements of magnitude and angle: +\f[\begin{array}{l} \texttt{x} (I) = \texttt{magnitude} (I) \cos ( \texttt{angle} (I)) \\ \texttt{y} (I) = \texttt{magnitude} (I) \sin ( \texttt{angle} (I)) \\ \end{array}\f] + +The relative accuracy of the estimated coordinates is about 1e-6. + +First output is a matrix of x-coordinates of 2D vectors. +Second output is a matrix of y-coordinates of 2D vectors. +Both output must have the same size and depth as input matrices. + +@note Function textual ID is "org.opencv.core.math.polarToCart" + +@param magnitude input floating-point @ref CV_32FC1 matrix (1xN) of magnitudes of 2D vectors; +@param angle input floating-point @ref CV_32FC1 matrix (1xN) of angles of 2D vectors. +@param angleInDegrees when true, the input angles are measured in +degrees, otherwise, they are measured in radians. +@sa cartToPolar, exp, log, pow, sqrt +*/ +GAPI_EXPORTS_W std::tuple polarToCart(const GMat& magnitude, const GMat& angle, + bool angleInDegrees = false); + +/** @brief Calculates the magnitude and angle of 2D vectors. + +The function cartToPolar calculates either the magnitude, angle, or both +for every 2D vector (x(I),y(I)): +\f[\begin{array}{l} \texttt{magnitude} (I)= \sqrt{\texttt{x}(I)^2+\texttt{y}(I)^2} , \\ \texttt{angle} (I)= \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))[ \cdot180 / \pi ] \end{array}\f] + +The angles are calculated with accuracy about 0.3 degrees. For the point +(0,0), the angle is set to 0. + +First output is a matrix of magnitudes of the same size and depth as input x. +Second output is a matrix of angles that has the same size and depth as +x; the angles are measured in radians (from 0 to 2\*Pi) or in degrees (0 to 360 degrees). + +@note Function textual ID is "org.opencv.core.math.cartToPolar" + +@param x matrix of @ref CV_32FC1 x-coordinates. +@param y array of @ref CV_32FC1 y-coordinates. +@param angleInDegrees a flag, indicating whether the angles are measured +in radians (which is by default), or in degrees. +@sa polarToCart +*/ +GAPI_EXPORTS_W std::tuple cartToPolar(const GMat& x, const GMat& y, + bool angleInDegrees = false); + +/** @brief Calculates the rotation angle of 2D vectors. + +The function cv::phase calculates the rotation angle of each 2D vector that +is formed from the corresponding elements of x and y : +\f[\texttt{angle} (I) = \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))\f] + +The angle estimation accuracy is about 0.3 degrees. When x(I)=y(I)=0 , +the corresponding angle(I) is set to 0. +@param x input floating-point array of x-coordinates of 2D vectors. +@param y input array of y-coordinates of 2D vectors; it must have the +same size and the same type as x. +@param angleInDegrees when true, the function calculates the angle in +degrees, otherwise, they are measured in radians. +@return array of vector angles; it has the same size and same type as x. +*/ +GAPI_EXPORTS_W GMat phase(const GMat& x, const GMat &y, bool angleInDegrees = false); + +/** @brief Calculates a square root of array elements. + +The function cv::gapi::sqrt calculates a square root of each input array element. +In case of multi-channel arrays, each channel is processed +independently. The accuracy is approximately the same as of the built-in +std::sqrt . +@param src input floating-point array. +@return output array of the same size and type as src. +*/ +GAPI_EXPORTS_W GMat sqrt(const GMat &src); + +//! @} gapi_math +//! +//! @addtogroup gapi_pixelwise +//! @{ + +/** @brief Performs the per-element comparison of two matrices checking if elements from first matrix are greater compare to elements in second. + +The function compares elements of two matrices src1 and src2 of the same size: + \f[\texttt{dst} (I) = \texttt{src1} (I) > \texttt{src2} (I)\f] + +When the comparison result is true, the corresponding element of output +array is set to 255. The comparison operations can be replaced with the +equivalent matrix expressions: +\f[\texttt{dst} = \texttt{src1} > \texttt{src2}\f] + +Output matrix of depth @ref CV_8U must have the same size and the same number of channels as + the input matrices/matrix. + +Supported input matrix data types are @ref CV_8UC1, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpGT" +@param src1 first input matrix. +@param src2 second input matrix/scalar of the same depth as first input matrix. +@sa min, max, threshold, cmpLE, cmpGE, cmpLT +*/ +GAPI_EXPORTS_W GMat cmpGT(const GMat& src1, const GMat& src2); +/** @overload +@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpGTScalar" +*/ +GAPI_EXPORTS_W GMat cmpGT(const GMat& src1, const GScalar& src2); + +/** @brief Performs the per-element comparison of two matrices checking if elements from first matrix are less than elements in second. + +The function compares elements of two matrices src1 and src2 of the same size: + \f[\texttt{dst} (I) = \texttt{src1} (I) < \texttt{src2} (I)\f] + +When the comparison result is true, the corresponding element of output +array is set to 255. The comparison operations can be replaced with the +equivalent matrix expressions: + \f[\texttt{dst} = \texttt{src1} < \texttt{src2}\f] + +Output matrix of depth @ref CV_8U must have the same size and the same number of channels as + the input matrices/matrix. + +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpLT" +@param src1 first input matrix. +@param src2 second input matrix/scalar of the same depth as first input matrix. +@sa min, max, threshold, cmpLE, cmpGE, cmpGT +*/ +GAPI_EXPORTS_W GMat cmpLT(const GMat& src1, const GMat& src2); +/** @overload +@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpLTScalar" +*/ +GAPI_EXPORTS_W GMat cmpLT(const GMat& src1, const GScalar& src2); + +/** @brief Performs the per-element comparison of two matrices checking if elements from first matrix are greater or equal compare to elements in second. + +The function compares elements of two matrices src1 and src2 of the same size: + \f[\texttt{dst} (I) = \texttt{src1} (I) >= \texttt{src2} (I)\f] + +When the comparison result is true, the corresponding element of output +array is set to 255. The comparison operations can be replaced with the +equivalent matrix expressions: + \f[\texttt{dst} = \texttt{src1} >= \texttt{src2}\f] + +Output matrix of depth @ref CV_8U must have the same size and the same number of channels as + the input matrices. + +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpGE" +@param src1 first input matrix. +@param src2 second input matrix/scalar of the same depth as first input matrix. +@sa min, max, threshold, cmpLE, cmpGT, cmpLT +*/ +GAPI_EXPORTS_W GMat cmpGE(const GMat& src1, const GMat& src2); +/** @overload +@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpLGEcalar" +*/ +GAPI_EXPORTS_W GMat cmpGE(const GMat& src1, const GScalar& src2); + +/** @brief Performs the per-element comparison of two matrices checking if elements from first matrix are less or equal compare to elements in second. + +The function compares elements of two matrices src1 and src2 of the same size: + \f[\texttt{dst} (I) = \texttt{src1} (I) <= \texttt{src2} (I)\f] + +When the comparison result is true, the corresponding element of output +array is set to 255. The comparison operations can be replaced with the +equivalent matrix expressions: + \f[\texttt{dst} = \texttt{src1} <= \texttt{src2}\f] + +Output matrix of depth @ref CV_8U must have the same size and the same number of channels as + the input matrices. + +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpLE" +@param src1 first input matrix. +@param src2 second input matrix/scalar of the same depth as first input matrix. +@sa min, max, threshold, cmpGT, cmpGE, cmpLT +*/ +GAPI_EXPORTS_W GMat cmpLE(const GMat& src1, const GMat& src2); +/** @overload +@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpLEScalar" +*/ +GAPI_EXPORTS_W GMat cmpLE(const GMat& src1, const GScalar& src2); + +/** @brief Performs the per-element comparison of two matrices checking if elements from first matrix are equal to elements in second. + +The function compares elements of two matrices src1 and src2 of the same size: + \f[\texttt{dst} (I) = \texttt{src1} (I) == \texttt{src2} (I)\f] + +When the comparison result is true, the corresponding element of output +array is set to 255. The comparison operations can be replaced with the +equivalent matrix expressions: + \f[\texttt{dst} = \texttt{src1} == \texttt{src2}\f] + +Output matrix of depth @ref CV_8U must have the same size and the same number of channels as + the input matrices. + +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpEQ" +@param src1 first input matrix. +@param src2 second input matrix/scalar of the same depth as first input matrix. +@sa min, max, threshold, cmpNE +*/ +GAPI_EXPORTS_W GMat cmpEQ(const GMat& src1, const GMat& src2); +/** @overload +@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpEQScalar" +*/ +GAPI_EXPORTS_W GMat cmpEQ(const GMat& src1, const GScalar& src2); + +/** @brief Performs the per-element comparison of two matrices checking if elements from first matrix are not equal to elements in second. + +The function compares elements of two matrices src1 and src2 of the same size: + \f[\texttt{dst} (I) = \texttt{src1} (I) != \texttt{src2} (I)\f] + +When the comparison result is true, the corresponding element of output +array is set to 255. The comparison operations can be replaced with the +equivalent matrix expressions: + \f[\texttt{dst} = \texttt{src1} != \texttt{src2}\f] + +Output matrix of depth @ref CV_8U must have the same size and the same number of channels as + the input matrices. + +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpNE" +@param src1 first input matrix. +@param src2 second input matrix/scalar of the same depth as first input matrix. +@sa min, max, threshold, cmpEQ +*/ +GAPI_EXPORTS_W GMat cmpNE(const GMat& src1, const GMat& src2); +/** @overload +@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpNEScalar" +*/ +GAPI_EXPORTS_W GMat cmpNE(const GMat& src1, const GScalar& src2); + +/** @brief computes bitwise conjunction of the two matrixes (src1 & src2) +Calculates the per-element bit-wise logical conjunction of two matrices of the same size. + +In case of floating-point matrices, their machine-specific bit +representations (usually IEEE754-compliant) are used for the operation. +In case of multi-channel matrices, each channel is processed +independently. Output matrix must have the same size and depth as the input +matrices. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.pixelwise.bitwise_and" + +@param src1 first input matrix. +@param src2 second input matrix. +*/ +GAPI_EXPORTS_W GMat bitwise_and(const GMat& src1, const GMat& src2); +/** @overload +@note Function textual ID is "org.opencv.core.pixelwise.bitwise_andS" +@param src1 first input matrix. +@param src2 scalar, which will be per-lemenetly conjuncted with elements of src1. +*/ +GAPI_EXPORTS_W GMat bitwise_and(const GMat& src1, const GScalar& src2); + +/** @brief computes bitwise disjunction of the two matrixes (src1 | src2) +Calculates the per-element bit-wise logical disjunction of two matrices of the same size. + +In case of floating-point matrices, their machine-specific bit +representations (usually IEEE754-compliant) are used for the operation. +In case of multi-channel matrices, each channel is processed +independently. Output matrix must have the same size and depth as the input +matrices. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.pixelwise.bitwise_or" + +@param src1 first input matrix. +@param src2 second input matrix. +*/ +GAPI_EXPORTS_W GMat bitwise_or(const GMat& src1, const GMat& src2); +/** @overload +@note Function textual ID is "org.opencv.core.pixelwise.bitwise_orS" +@param src1 first input matrix. +@param src2 scalar, which will be per-lemenetly disjuncted with elements of src1. +*/ +GAPI_EXPORTS_W GMat bitwise_or(const GMat& src1, const GScalar& src2); + + +/** @brief computes bitwise logical "exclusive or" of the two matrixes (src1 ^ src2) +Calculates the per-element bit-wise logical "exclusive or" of two matrices of the same size. + +In case of floating-point matrices, their machine-specific bit +representations (usually IEEE754-compliant) are used for the operation. +In case of multi-channel matrices, each channel is processed +independently. Output matrix must have the same size and depth as the input +matrices. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.pixelwise.bitwise_xor" + +@param src1 first input matrix. +@param src2 second input matrix. +*/ +GAPI_EXPORTS_W GMat bitwise_xor(const GMat& src1, const GMat& src2); +/** @overload +@note Function textual ID is "org.opencv.core.pixelwise.bitwise_xorS" +@param src1 first input matrix. +@param src2 scalar, for which per-lemenet "logical or" operation on elements of src1 will be performed. +*/ +GAPI_EXPORTS_W GMat bitwise_xor(const GMat& src1, const GScalar& src2); + + +/** @brief Inverts every bit of an array. + +The function bitwise_not calculates per-element bit-wise inversion of the input +matrix: +\f[\texttt{dst} (I) = \neg \texttt{src} (I)\f] + +In case of floating-point matrices, their machine-specific bit +representations (usually IEEE754-compliant) are used for the operation. +In case of multi-channel matrices, each channel is processed +independently. Output matrix must have the same size and depth as the input +matrix. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.pixelwise.bitwise_not" + +@param src input matrix. +*/ +GAPI_EXPORTS_W GMat bitwise_not(const GMat& src); + +/** @brief Select values from either first or second of input matrices by given mask. +The function set to the output matrix either the value from the first input matrix if corresponding value of mask matrix is 255, + or value from the second input matrix (if value of mask matrix set to 0). + +Input mask matrix must be of @ref CV_8UC1 type, two other inout matrices and output matrix should be of the same type. The size should +be the same for all input and output matrices. +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.pixelwise.select" + +@param src1 first input matrix. +@param src2 second input matrix. +@param mask mask input matrix. +*/ +GAPI_EXPORTS_W GMat select(const GMat& src1, const GMat& src2, const GMat& mask); + +//! @} gapi_pixelwise + + +//! @addtogroup gapi_matrixop +//! @{ +/** @brief Calculates per-element minimum of two matrices. + +The function min calculates the per-element minimum of two matrices of the same size, number of channels and depth: +\f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{src2} (I))\f] + where I is a multi-dimensional index of matrix elements. In case of + multi-channel matrices, each channel is processed independently. +Output matrix must be of the same size and depth as src1. + +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.matrixop.min" +@param src1 first input matrix. +@param src2 second input matrix of the same size and depth as src1. +@sa max, cmpEQ, cmpLT, cmpLE +*/ +GAPI_EXPORTS_W GMat min(const GMat& src1, const GMat& src2); + +/** @brief Calculates per-element maximum of two matrices. + +The function max calculates the per-element maximum of two matrices of the same size, number of channels and depth: +\f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{src2} (I))\f] + where I is a multi-dimensional index of matrix elements. In case of + multi-channel matrices, each channel is processed independently. +Output matrix must be of the same size and depth as src1. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.matrixop.max" +@param src1 first input matrix. +@param src2 second input matrix of the same size and depth as src1. +@sa min, compare, cmpEQ, cmpGT, cmpGE +*/ +GAPI_EXPORTS_W GMat max(const GMat& src1, const GMat& src2); + +/** @brief Calculates the per-element absolute difference between two matrices. + +The function absDiff calculates absolute difference between two matrices of the same size and depth: + \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2}(I)|)\f] + where I is a multi-dimensional index of matrix elements. In case of + multi-channel matrices, each channel is processed independently. +Output matrix must have the same size and depth as input matrices. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.matrixop.absdiff" +@param src1 first input matrix. +@param src2 second input matrix. +@sa abs +*/ +GAPI_EXPORTS_W GMat absDiff(const GMat& src1, const GMat& src2); + +/** @brief Calculates absolute value of matrix elements. + +The function abs calculates absolute difference between matrix elements and given scalar value: + \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{matC}(I)|)\f] + where matC is constructed from given scalar c and has the same sizes and depth as input matrix src. + +Output matrix must be of the same size and depth as src. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.matrixop.absdiffC" +@param src input matrix. +@param c scalar to be subtracted. +@sa min, max +*/ +GAPI_EXPORTS_W GMat absDiffC(const GMat& src, const GScalar& c); + +/** @brief Calculates sum of all matrix elements. + +The function sum calculates sum of all matrix elements, independently for each channel. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.matrixop.sum" +@param src input matrix. +@sa countNonZero, mean, min, max +*/ +GAPI_EXPORTS_W GScalar sum(const GMat& src); + +/** @brief Counts non-zero array elements. + +The function returns the number of non-zero elements in src : +\f[\sum _{I: \; \texttt{src} (I) \ne0 } 1\f] + +Supported matrix data types are @ref CV_8UC1, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.matrixop.countNonZero" +@param src input single-channel matrix. +@sa mean, min, max +*/ +GAPI_EXPORTS_W GOpaque countNonZero(const GMat& src); + +/** @brief Calculates the weighted sum of two matrices. + +The function addWeighted calculates the weighted sum of two matrices as follows: +\f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{src1} (I)* \texttt{alpha} + \texttt{src2} (I)* \texttt{beta} + \texttt{gamma} )\f] +where I is a multi-dimensional index of array elements. In case of multi-channel matrices, each +channel is processed independently. + +The function can be replaced with a matrix expression: + \f[\texttt{dst}(I) = \texttt{alpha} * \texttt{src1}(I) - \texttt{beta} * \texttt{src2}(I) + \texttt{gamma} \f] + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.matrixop.addweighted" +@param src1 first input matrix. +@param alpha weight of the first matrix elements. +@param src2 second input matrix of the same size and channel number as src1. +@param beta weight of the second matrix elements. +@param gamma scalar added to each sum. +@param ddepth optional depth of the output matrix. +@sa add, sub +*/ +GAPI_EXPORTS_W GMat addWeighted(const GMat& src1, double alpha, const GMat& src2, double beta, double gamma, int ddepth = -1); + +/** @brief Calculates the absolute L1 norm of a matrix. + +This version of normL1 calculates the absolute L1 norm of src. + +As example for one array consider the function \f$r(x)= \begin{pmatrix} x \\ 1-x \end{pmatrix}, x \in [-1;1]\f$. +The \f$ L_{1} \f$ norm for the sample value \f$r(-1) = \begin{pmatrix} -1 \\ 2 \end{pmatrix}\f$ +is calculated as follows +\f{align*} + \| r(-1) \|_{L_1} &= |-1| + |2| = 3 \\ +\f} +and for \f$r(0.5) = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}\f$ the calculation is +\f{align*} + \| r(0.5) \|_{L_1} &= |0.5| + |0.5| = 1 \\ +\f} + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.matrixop.norml1" +@param src input matrix. +@sa normL2, normInf +*/ +GAPI_EXPORTS_W GScalar normL1(const GMat& src); + +/** @brief Calculates the absolute L2 norm of a matrix. + +This version of normL2 calculates the absolute L2 norm of src. + +As example for one array consider the function \f$r(x)= \begin{pmatrix} x \\ 1-x \end{pmatrix}, x \in [-1;1]\f$. +The \f$ L_{2} \f$ norm for the sample value \f$r(-1) = \begin{pmatrix} -1 \\ 2 \end{pmatrix}\f$ +is calculated as follows +\f{align*} + \| r(-1) \|_{L_2} &= \sqrt{(-1)^{2} + (2)^{2}} = \sqrt{5} \\ +\f} +and for \f$r(0.5) = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}\f$ the calculation is +\f{align*} + \| r(0.5) \|_{L_2} &= \sqrt{(0.5)^{2} + (0.5)^{2}} = \sqrt{0.5} \\ +\f} + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. +@note Function textual ID is "org.opencv.core.matrixop.norml2" +@param src input matrix. +@sa normL1, normInf +*/ +GAPI_EXPORTS_W GScalar normL2(const GMat& src); + +/** @brief Calculates the absolute infinite norm of a matrix. + +This version of normInf calculates the absolute infinite norm of src. + +As example for one array consider the function \f$r(x)= \begin{pmatrix} x \\ 1-x \end{pmatrix}, x \in [-1;1]\f$. +The \f$ L_{\infty} \f$ norm for the sample value \f$r(-1) = \begin{pmatrix} -1 \\ 2 \end{pmatrix}\f$ +is calculated as follows +\f{align*} + \| r(-1) \|_{L_\infty} &= \max(|-1|,|2|) = 2 +\f} +and for \f$r(0.5) = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}\f$ the calculation is +\f{align*} + \| r(0.5) \|_{L_\infty} &= \max(|0.5|,|0.5|) = 0.5. +\f} + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.matrixop.norminf" +@param src input matrix. +@sa normL1, normL2 +*/ +GAPI_EXPORTS_W GScalar normInf(const GMat& src); + +/** @brief Calculates the integral of an image. + +The function calculates one or more integral images for the source image as follows: + +\f[\texttt{sum} (X,Y) = \sum _{x integral(const GMat& src, int sdepth = -1, int sqdepth = -1); + +/** @brief Applies a fixed-level threshold to each matrix element. + +The function applies fixed-level thresholding to a single- or multiple-channel matrix. +The function is typically used to get a bi-level (binary) image out of a grayscale image ( cmp functions could be also used for +this purpose) or for removing a noise, that is, filtering out pixels with too small or too large +values. There are several types of thresholding supported by the function. They are determined by +type parameter. + +Also, the special values cv::THRESH_OTSU or cv::THRESH_TRIANGLE may be combined with one of the +above values. In these cases, the function determines the optimal threshold value using the Otsu's +or Triangle algorithm and uses it instead of the specified thresh . The function returns the +computed threshold value in addititon to thresholded matrix. +The Otsu's and Triangle methods are implemented only for 8-bit matrices. + +Input image should be single channel only in case of cv::THRESH_OTSU or cv::THRESH_TRIANGLE flags. +Output matrix must be of the same size and depth as src. + +@note Function textual ID is "org.opencv.core.matrixop.threshold" + +@param src input matrix (@ref CV_8UC1, @ref CV_8UC3, or @ref CV_32FC1). +@param thresh threshold value. +@param maxval maximum value to use with the cv::THRESH_BINARY and cv::THRESH_BINARY_INV thresholding +types. +@param type thresholding type (see the cv::ThresholdTypes). + +@sa min, max, cmpGT, cmpLE, cmpGE, cmpLT + */ +GAPI_EXPORTS_W GMat threshold(const GMat& src, const GScalar& thresh, const GScalar& maxval, int type); +/** @overload +This function applicable for all threshold types except cv::THRESH_OTSU and cv::THRESH_TRIANGLE +@note Function textual ID is "org.opencv.core.matrixop.thresholdOT" +*/ +GAPI_EXPORTS_W std::tuple threshold(const GMat& src, const GScalar& maxval, int type); + +/** @brief Applies a range-level threshold to each matrix element. + +The function applies range-level thresholding to a single- or multiple-channel matrix. +It sets output pixel value to OxFF if the corresponding pixel value of input matrix is in specified range,or 0 otherwise. + +Input and output matrices must be CV_8UC1. + +@note Function textual ID is "org.opencv.core.matrixop.inRange" + +@param src input matrix (CV_8UC1). +@param threshLow lower boundary value. +@param threshUp upper boundary value. + +@sa threshold + */ +GAPI_EXPORTS_W GMat inRange(const GMat& src, const GScalar& threshLow, const GScalar& threshUp); + +//! @} gapi_matrixop + +//! @addtogroup gapi_transform +//! @{ +/** @brief Creates one 4-channel matrix out of 4 single-channel ones. + +The function merges several matrices to make a single multi-channel matrix. That is, each +element of the output matrix will be a concatenation of the elements of the input matrices, where +elements of i-th input matrix are treated as mv[i].channels()-element vectors. +Output matrix must be of @ref CV_8UC4 type. + +The function split4 does the reverse operation. + +@note + - Function textual ID is "org.opencv.core.transform.merge4" + +@param src1 first input @ref CV_8UC1 matrix to be merged. +@param src2 second input @ref CV_8UC1 matrix to be merged. +@param src3 third input @ref CV_8UC1 matrix to be merged. +@param src4 fourth input @ref CV_8UC1 matrix to be merged. +@sa merge3, split4, split3 +*/ +GAPI_EXPORTS_W GMat merge4(const GMat& src1, const GMat& src2, const GMat& src3, const GMat& src4); + +/** @brief Creates one 3-channel matrix out of 3 single-channel ones. + +The function merges several matrices to make a single multi-channel matrix. That is, each +element of the output matrix will be a concatenation of the elements of the input matrices, where +elements of i-th input matrix are treated as mv[i].channels()-element vectors. +Output matrix must be of @ref CV_8UC3 type. + +The function split3 does the reverse operation. + +@note + - Function textual ID is "org.opencv.core.transform.merge3" + +@param src1 first input @ref CV_8UC1 matrix to be merged. +@param src2 second input @ref CV_8UC1 matrix to be merged. +@param src3 third input @ref CV_8UC1 matrix to be merged. +@sa merge4, split4, split3 +*/ +GAPI_EXPORTS_W GMat merge3(const GMat& src1, const GMat& src2, const GMat& src3); + +/** @brief Divides a 4-channel matrix into 4 single-channel matrices. + +The function splits a 4-channel matrix into 4 single-channel matrices: +\f[\texttt{mv} [c](I) = \texttt{src} (I)_c\f] + +All output matrices must be of @ref CV_8UC1 type. + +The function merge4 does the reverse operation. + +@note + - Function textual ID is "org.opencv.core.transform.split4" + +@param src input @ref CV_8UC4 matrix. +@sa split3, merge3, merge4 +*/ +GAPI_EXPORTS_W std::tuple split4(const GMat& src); + +/** @brief Divides a 3-channel matrix into 3 single-channel matrices. + +The function splits a 3-channel matrix into 3 single-channel matrices: +\f[\texttt{mv} [c](I) = \texttt{src} (I)_c\f] + +All output matrices must be of @ref CV_8UC1 type. + +The function merge3 does the reverse operation. + +@note + - Function textual ID is "org.opencv.core.transform.split3" + +@param src input @ref CV_8UC3 matrix. +@sa split4, merge3, merge4 +*/ +GAPI_EXPORTS_W std::tuple split3(const GMat& src); + +/** @brief Applies a generic geometrical transformation to an image. + +The function remap transforms the source image using the specified map: + +\f[\texttt{dst} (x,y) = \texttt{src} (map_x(x,y),map_y(x,y))\f] + +where values of pixels with non-integer coordinates are computed using one of available +interpolation methods. \f$map_x\f$ and \f$map_y\f$ can be encoded as separate floating-point maps +in \f$map_1\f$ and \f$map_2\f$ respectively, or interleaved floating-point maps of \f$(x,y)\f$ in +\f$map_1\f$, or fixed-point maps created by using convertMaps. The reason you might want to +convert from floating to fixed-point representations of a map is that they can yield much faster +(\~2x) remapping operations. In the converted case, \f$map_1\f$ contains pairs (cvFloor(x), +cvFloor(y)) and \f$map_2\f$ contains indices in a table of interpolation coefficients. +Output image must be of the same size and depth as input one. + +@note + - Function textual ID is "org.opencv.core.transform.remap" + - Due to current implementation limitations the size of an input and output images should be less than 32767x32767. + +@param src Source image. +@param map1 The first map of either (x,y) points or just x values having the type CV_16SC2, +CV_32FC1, or CV_32FC2. +@param map2 The second map of y values having the type CV_16UC1, CV_32FC1, or none (empty map +if map1 is (x,y) points), respectively. +@param interpolation Interpolation method (see cv::InterpolationFlags). The methods #INTER_AREA +and #INTER_LINEAR_EXACT are not supported by this function. +@param borderMode Pixel extrapolation method (see cv::BorderTypes). When +borderMode=BORDER_TRANSPARENT, it means that the pixels in the destination image that +corresponds to the "outliers" in the source image are not modified by the function. +@param borderValue Value used in case of a constant border. By default, it is 0. + */ +GAPI_EXPORTS_W GMat remap(const GMat& src, const Mat& map1, const Mat& map2, + int interpolation, int borderMode = BORDER_CONSTANT, + const Scalar& borderValue = Scalar()); + +/** @brief Flips a 2D matrix around vertical, horizontal, or both axes. + +The function flips the matrix in one of three different ways (row +and column indices are 0-based): +\f[\texttt{dst} _{ij} = +\left\{ +\begin{array}{l l} +\texttt{src} _{\texttt{src.rows}-i-1,j} & if\; \texttt{flipCode} = 0 \\ +\texttt{src} _{i, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} > 0 \\ +\texttt{src} _{ \texttt{src.rows} -i-1, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} < 0 \\ +\end{array} +\right.\f] +The example scenarios of using the function are the following: +* Vertical flipping of the image (flipCode == 0) to switch between + top-left and bottom-left image origin. This is a typical operation + in video processing on Microsoft Windows\* OS. +* Horizontal flipping of the image with the subsequent horizontal + shift and absolute difference calculation to check for a + vertical-axis symmetry (flipCode \> 0). +* Simultaneous horizontal and vertical flipping of the image with + the subsequent shift and absolute difference calculation to check + for a central symmetry (flipCode \< 0). +* Reversing the order of point arrays (flipCode \> 0 or + flipCode == 0). +Output image must be of the same depth as input one, size should be correct for given flipCode. + +@note Function textual ID is "org.opencv.core.transform.flip" + +@param src input matrix. +@param flipCode a flag to specify how to flip the array; 0 means +flipping around the x-axis and positive value (for example, 1) means +flipping around y-axis. Negative value (for example, -1) means flipping +around both axes. +@sa remap +*/ +GAPI_EXPORTS_W GMat flip(const GMat& src, int flipCode); + +/** @brief Crops a 2D matrix. + +The function crops the matrix by given cv::Rect. + +Output matrix must be of the same depth as input one, size is specified by given rect size. + +@note Function textual ID is "org.opencv.core.transform.crop" + +@param src input matrix. +@param rect a rect to crop a matrix to +@sa resize +*/ +GAPI_EXPORTS_W GMat crop(const GMat& src, const Rect& rect); + +/** @brief Applies horizontal concatenation to given matrices. + +The function horizontally concatenates two GMat matrices (with the same number of rows). +@code{.cpp} + GMat A = { 1, 4, + 2, 5, + 3, 6 }; + GMat B = { 7, 10, + 8, 11, + 9, 12 }; + + GMat C = gapi::concatHor(A, B); + //C: + //[1, 4, 7, 10; + // 2, 5, 8, 11; + // 3, 6, 9, 12] +@endcode +Output matrix must the same number of rows and depth as the src1 and src2, and the sum of cols of the src1 and src2. +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.imgproc.transform.concatHor" + +@param src1 first input matrix to be considered for horizontal concatenation. +@param src2 second input matrix to be considered for horizontal concatenation. +@sa concatVert +*/ +GAPI_EXPORTS_W GMat concatHor(const GMat& src1, const GMat& src2); + +/** @overload +The function horizontally concatenates given number of GMat matrices (with the same number of columns). +Output matrix must the same number of columns and depth as the input matrices, and the sum of rows of input matrices. + +@param v vector of input matrices to be concatenated horizontally. +*/ +GAPI_EXPORTS_W GMat concatHor(const std::vector &v); + +/** @brief Applies vertical concatenation to given matrices. + +The function vertically concatenates two GMat matrices (with the same number of cols). + @code{.cpp} + GMat A = { 1, 7, + 2, 8, + 3, 9 }; + GMat B = { 4, 10, + 5, 11, + 6, 12 }; + + GMat C = gapi::concatVert(A, B); + //C: + //[1, 7; + // 2, 8; + // 3, 9; + // 4, 10; + // 5, 11; + // 6, 12] + @endcode + +Output matrix must the same number of cols and depth as the src1 and src2, and the sum of rows of the src1 and src2. +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.imgproc.transform.concatVert" + +@param src1 first input matrix to be considered for vertical concatenation. +@param src2 second input matrix to be considered for vertical concatenation. +@sa concatHor +*/ +GAPI_EXPORTS_W GMat concatVert(const GMat& src1, const GMat& src2); + +/** @overload +The function vertically concatenates given number of GMat matrices (with the same number of columns). +Output matrix must the same number of columns and depth as the input matrices, and the sum of rows of input matrices. + +@param v vector of input matrices to be concatenated vertically. +*/ +GAPI_EXPORTS_W GMat concatVert(const std::vector &v); + + +/** @brief Performs a look-up table transform of a matrix. + +The function LUT fills the output matrix with values from the look-up table. Indices of the entries +are taken from the input matrix. That is, the function processes each element of src as follows: +\f[\texttt{dst} (I) \leftarrow \texttt{lut(src(I))}\f] + +Supported matrix data types are @ref CV_8UC1. +Output is a matrix of the same size and number of channels as src, and the same depth as lut. + +@note Function textual ID is "org.opencv.core.transform.LUT" + +@param src input matrix of 8-bit elements. +@param lut look-up table of 256 elements; in case of multi-channel input array, the table should +either have a single channel (in this case the same table is used for all channels) or the same +number of channels as in the input matrix. +*/ +GAPI_EXPORTS_W GMat LUT(const GMat& src, const Mat& lut); + +/** @brief Converts a matrix to another data depth with optional scaling. + +The method converts source pixel values to the target data depth. saturate_cast\<\> is applied at +the end to avoid possible overflows: + +\f[m(x,y) = saturate \_ cast( \alpha (*this)(x,y) + \beta )\f] +Output matrix must be of the same size as input one. + +@note Function textual ID is "org.opencv.core.transform.convertTo" +@param src input matrix to be converted from. +@param rdepth desired output matrix depth or, rather, the depth since the number of channels are the +same as the input has; if rdepth is negative, the output matrix will have the same depth as the input. +@param alpha optional scale factor. +@param beta optional delta added to the scaled values. + */ +GAPI_EXPORTS_W GMat convertTo(const GMat& src, int rdepth, double alpha=1, double beta=0); + +/** @brief Normalizes the norm or value range of an array. + +The function normalizes scale and shift the input array elements so that +\f[\| \texttt{dst} \| _{L_p}= \texttt{alpha}\f] +(where p=Inf, 1 or 2) when normType=NORM_INF, NORM_L1, or NORM_L2, respectively; or so that +\f[\min _I \texttt{dst} (I)= \texttt{alpha} , \, \, \max _I \texttt{dst} (I)= \texttt{beta}\f] +when normType=NORM_MINMAX (for dense arrays only). + +@note Function textual ID is "org.opencv.core.normalize" + +@param src input array. +@param alpha norm value to normalize to or the lower range boundary in case of the range +normalization. +@param beta upper range boundary in case of the range normalization; it is not used for the norm +normalization. +@param norm_type normalization type (see cv::NormTypes). +@param ddepth when negative, the output array has the same type as src; otherwise, it has the same +number of channels as src and the depth =ddepth. +@sa norm, Mat::convertTo +*/ +GAPI_EXPORTS_W GMat normalize(const GMat& src, double alpha, double beta, + int norm_type, int ddepth = -1); + +/** @brief Applies a perspective transformation to an image. + +The function warpPerspective transforms the source image using the specified matrix: + +\f[\texttt{dst} (x,y) = \texttt{src} \left ( \frac{M_{11} x + M_{12} y + M_{13}}{M_{31} x + M_{32} y + M_{33}} , + \frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}} \right )\f] + +when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted with invert +and then put in the formula above instead of M. The function cannot operate in-place. + +@param src input image. +@param M \f$3\times 3\f$ transformation matrix. +@param dsize size of the output image. +@param flags combination of interpolation methods (#INTER_LINEAR or #INTER_NEAREST) and the +optional flag #WARP_INVERSE_MAP, that sets M as the inverse transformation ( +\f$\texttt{dst}\rightarrow\texttt{src}\f$ ). +@param borderMode pixel extrapolation method (#BORDER_CONSTANT or #BORDER_REPLICATE). +@param borderValue value used in case of a constant border; by default, it equals 0. + +@sa warpAffine, resize, remap, getRectSubPix, perspectiveTransform + */ +GAPI_EXPORTS_W GMat warpPerspective(const GMat& src, const Mat& M, const Size& dsize, int flags = cv::INTER_LINEAR, + int borderMode = cv::BORDER_CONSTANT, const Scalar& borderValue = Scalar()); + +/** @brief Applies an affine transformation to an image. + +The function warpAffine transforms the source image using the specified matrix: + +\f[\texttt{dst} (x,y) = \texttt{src} ( \texttt{M} _{11} x + \texttt{M} _{12} y + \texttt{M} _{13}, \texttt{M} _{21} x + \texttt{M} _{22} y + \texttt{M} _{23})\f] + +when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted +with #invertAffineTransform and then put in the formula above instead of M. The function cannot +operate in-place. + +@param src input image. +@param M \f$2\times 3\f$ transformation matrix. +@param dsize size of the output image. +@param flags combination of interpolation methods (see #InterpolationFlags) and the optional +flag #WARP_INVERSE_MAP that means that M is the inverse transformation ( +\f$\texttt{dst}\rightarrow\texttt{src}\f$ ). +@param borderMode pixel extrapolation method (see #BorderTypes); +borderMode=#BORDER_TRANSPARENT isn't supported +@param borderValue value used in case of a constant border; by default, it is 0. + +@sa warpPerspective, resize, remap, getRectSubPix, transform + */ +GAPI_EXPORTS_W GMat warpAffine(const GMat& src, const Mat& M, const Size& dsize, int flags = cv::INTER_LINEAR, + int borderMode = cv::BORDER_CONSTANT, const Scalar& borderValue = Scalar()); +//! @} gapi_transform + +/** @brief Finds centers of clusters and groups input samples around the clusters. + +The function kmeans implements a k-means algorithm that finds the centers of K clusters +and groups the input samples around the clusters. As an output, \f$\texttt{bestLabels}_i\f$ +contains a 0-based cluster index for the \f$i^{th}\f$ sample. + +@note + - Function textual ID is "org.opencv.core.kmeansND" + - In case of an N-dimentional points' set given, input GMat can have the following traits: +2 dimensions, a single row or column if there are N channels, +or N columns if there is a single channel. Mat should have @ref CV_32F depth. + - Although, if GMat with height != 1, width != 1, channels != 1 given as data, n-dimensional +samples are considered given in amount of A, where A = height, n = width * channels. + - In case of GMat given as data: + - the output labels are returned as 1-channel GMat with sizes +width = 1, height = A, where A is samples amount, or width = bestLabels.width, +height = bestLabels.height if bestLabels given; + - the cluster centers are returned as 1-channel GMat with sizes +width = n, height = K, where n is samples' dimentionality and K is clusters' amount. + - As one of possible usages, if you want to control the initial labels for each attempt +by yourself, you can utilize just the core of the function. To do that, set the number +of attempts to 1, initialize labels each time using a custom algorithm, pass them with the +( flags = #KMEANS_USE_INITIAL_LABELS ) flag, and then choose the best (most-compact) clustering. + +@param data Data for clustering. An array of N-Dimensional points with float coordinates is needed. +Function can take GArray, GArray for 2D and 3D cases or GMat for any +dimentionality and channels. +@param K Number of clusters to split the set by. +@param bestLabels Optional input integer array that can store the supposed initial cluster indices +for every sample. Used when ( flags = #KMEANS_USE_INITIAL_LABELS ) flag is set. +@param criteria The algorithm termination criteria, that is, the maximum number of iterations +and/or the desired accuracy. The accuracy is specified as criteria.epsilon. As soon as each of +the cluster centers moves by less than criteria.epsilon on some iteration, the algorithm stops. +@param attempts Flag to specify the number of times the algorithm is executed using different +initial labellings. The algorithm returns the labels that yield the best compactness (see the first +function return value). +@param flags Flag that can take values of cv::KmeansFlags . + +@return + - Compactness measure that is computed as +\f[\sum _i \| \texttt{samples} _i - \texttt{centers} _{ \texttt{labels} _i} \| ^2\f] +after every attempt. The best (minimum) value is chosen and the corresponding labels and the +compactness value are returned by the function. + - Integer array that stores the cluster indices for every sample. + - Array of the cluster centers. +*/ +GAPI_EXPORTS_W std::tuple,GMat,GMat> +kmeans(const GMat& data, const int K, const GMat& bestLabels, + const TermCriteria& criteria, const int attempts, const KmeansFlags flags); + +/** @overload +@note + - Function textual ID is "org.opencv.core.kmeansNDNoInit" + - #KMEANS_USE_INITIAL_LABELS flag must not be set while using this overload. + */ +GAPI_EXPORTS_W std::tuple,GMat,GMat> +kmeans(const GMat& data, const int K, const TermCriteria& criteria, const int attempts, + const KmeansFlags flags); + +/** @overload +@note Function textual ID is "org.opencv.core.kmeans2D" + */ +GAPI_EXPORTS_W std::tuple,GArray,GArray> +kmeans(const GArray& data, const int K, const GArray& bestLabels, + const TermCriteria& criteria, const int attempts, const KmeansFlags flags); + +/** @overload +@note Function textual ID is "org.opencv.core.kmeans3D" + */ +GAPI_EXPORTS_W std::tuple,GArray,GArray> +kmeans(const GArray& data, const int K, const GArray& bestLabels, + const TermCriteria& criteria, const int attempts, const KmeansFlags flags); + + +/** @brief Transposes a matrix. + +The function transposes the matrix: +\f[\texttt{dst} (i,j) = \texttt{src} (j,i)\f] + +@note + - Function textual ID is "org.opencv.core.transpose" + - No complex conjugation is done in case of a complex matrix. It should be done separately if needed. + +@param src input array. +*/ +GAPI_EXPORTS_W GMat transpose(const GMat& src); + + +namespace streaming { +/** @brief Gets dimensions from Mat. + +@note Function textual ID is "org.opencv.streaming.size" + +@param src Input tensor +@return Size (tensor dimensions). +*/ +GAPI_EXPORTS_W GOpaque size(const GMat& src); + +/** @overload +Gets dimensions from rectangle. + +@note Function textual ID is "org.opencv.streaming.sizeR" + +@param r Input rectangle. +@return Size (rectangle dimensions). +*/ +GAPI_EXPORTS_W GOpaque size(const GOpaque& r); + +/** @brief Gets dimensions from MediaFrame. + +@note Function textual ID is "org.opencv.streaming.sizeMF" + +@param src Input frame +@return Size (frame dimensions). +*/ +GAPI_EXPORTS_W GOpaque size(const GFrame& src); +} //namespace streaming +} //namespace gapi +} //namespace cv + +#endif //OPENCV_GAPI_CORE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/core.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/core.hpp index ee86fb72c2..c30df2a295 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/core.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/core.hpp @@ -1,27 +1,27 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_CPU_CORE_API_HPP -#define OPENCV_GAPI_CPU_CORE_API_HPP - -#include // GKernelPackage -#include // GAPI_EXPORTS - -namespace cv { -namespace gapi { -namespace core { -namespace cpu { - -GAPI_EXPORTS_W cv::GKernelPackage kernels(); - -} // namespace cpu -} // namespace core -} // namespace gapi -} // namespace cv - - -#endif // OPENCV_GAPI_CPU_CORE_API_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_CPU_CORE_API_HPP +#define OPENCV_GAPI_CPU_CORE_API_HPP + +#include // GKernelPackage +#include // GAPI_EXPORTS + +namespace cv { +namespace gapi { +namespace core { +namespace cpu { + +GAPI_EXPORTS_W cv::GKernelPackage kernels(); + +} // namespace cpu +} // namespace core +} // namespace gapi +} // namespace cv + + +#endif // OPENCV_GAPI_CPU_CORE_API_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/gcpukernel.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/gcpukernel.hpp index eb5f784747..86071bf7c4 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/gcpukernel.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/gcpukernel.hpp @@ -1,542 +1,542 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2022 Intel Corporation - - -#ifndef OPENCV_GAPI_GCPUKERNEL_HPP -#define OPENCV_GAPI_GCPUKERNEL_HPP - -#if defined _MSC_VER -#pragma warning(push) -#pragma warning(disable: 4702) // "Unreachable code" on postprocess(...) call inside OCVCallHelper -#endif - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include //suppress_unused_warning -#include - -// FIXME: namespace scheme for backends? -namespace cv { - -namespace gimpl -{ - // Forward-declare an internal class - class GCPUExecutable; -} // namespace gimpl - -namespace gapi -{ -/** - * @brief This namespace contains G-API CPU backend functions, - * structures, and symbols. - */ -namespace cpu -{ - /** - * \addtogroup gapi_std_backends - * @{ - * - * @brief G-API backends available in this OpenCV version - * - * G-API backends play a corner stone role in G-API execution - * stack. Every backend is hardware-oriented and thus can run its - * kernels efficiently on the target platform. - * - * Backends are usually "black boxes" for G-API users -- on the API - * side, all backends are represented as different objects of the - * same class cv::gapi::GBackend. - * User can manipulate with backends by specifying which kernels to use. - * - * @sa @ref gapi_hld - */ - - /** - * @brief Get a reference to CPU (OpenCV) backend. - * - * This is the default backend in G-API at the moment, providing - * broader functional coverage but losing some graph model - * advantages. Provided mostly for reference and prototyping - * purposes. - * - * @sa gapi_std_backends - */ - GAPI_EXPORTS cv::gapi::GBackend backend(); - /** @} */ - - class GOCVFunctor; - - //! @cond IGNORED - template - GOCVFunctor ocv_kernel(const Callable& c); - - template - GOCVFunctor ocv_kernel(Callable& c); - //! @endcond - -} // namespace cpu -} // namespace gapi - -// Represents arguments which are passed to a wrapped CPU function -// FIXME: put into detail? -class GAPI_EXPORTS GCPUContext -{ -public: - // Generic accessor API - template - const T& inArg(int input) { return m_args.at(input).get(); } - - // Syntax sugar - const cv::Mat& inMat(int input); - cv::Mat& outMatR(int output); // FIXME: Avoid cv::Mat m = ctx.outMatR() - - const cv::Scalar& inVal(int input); - cv::Scalar& outValR(int output); // FIXME: Avoid cv::Scalar s = ctx.outValR() - cv::MediaFrame& outFrame(int output); - template std::vector& outVecR(int output) // FIXME: the same issue - { - return outVecRef(output).wref(); - } - template T& outOpaqueR(int output) // FIXME: the same issue - { - return outOpaqueRef(output).wref(); - } - - GArg state() - { - return m_state; - } - -protected: - detail::VectorRef& outVecRef(int output); - detail::OpaqueRef& outOpaqueRef(int output); - - std::vector m_args; - GArg m_state; - - //FIXME: avoid conversion of arguments from internal representation to OpenCV one on each call - //to OCV kernel. (This can be achieved by a two single time conversions in GCPUExecutable::run, - //once on enter for input and output arguments, and once before return for output arguments only - std::unordered_map m_results; - - friend class gimpl::GCPUExecutable; -}; - -class GAPI_EXPORTS GCPUKernel -{ -public: - // This function is a kernel's execution entry point (does the processing work) - using RunF = std::function; - // This function is a stateful kernel's setup routine (configures state) - using SetupF = std::function; - - GCPUKernel(); - GCPUKernel(const RunF& runF, const SetupF& setupF = nullptr); - - RunF m_runF = nullptr; - SetupF m_setupF = nullptr; - - bool m_isStateful = false; -}; - -// FIXME: This is an ugly ad-hoc implementation. TODO: refactor - -namespace detail -{ -template struct get_in; -template<> struct get_in -{ - static cv::Mat get(GCPUContext &ctx, int idx) { return ctx.inMat(idx); } -}; -template<> struct get_in -{ - static cv::Mat get(GCPUContext &ctx, int idx) { return get_in::get(ctx, idx); } -}; -template<> struct get_in -{ - static cv::MediaFrame get(GCPUContext &ctx, int idx) { return ctx.inArg(idx); } -}; -template<> struct get_in -{ - static cv::Scalar get(GCPUContext &ctx, int idx) { return ctx.inVal(idx); } -}; -template struct get_in > -{ - static const std::vector& get(GCPUContext &ctx, int idx) { return ctx.inArg(idx).rref(); } -}; -template struct get_in > -{ - static const U& get(GCPUContext &ctx, int idx) { return ctx.inArg(idx).rref(); } -}; - -//FIXME(dm): GArray/GArray conversion should be done more gracefully in the system -template<> struct get_in >: public get_in > -{ -}; - -//FIXME(dm): GArray/GArray conversion should be done more gracefully in the system -template<> struct get_in >: public get_in > -{ -}; - -// FIXME(dm): GArray>/GArray> conversion should be done more gracefully in the system -template struct get_in> >: public get_in> > -{ -}; - -//FIXME(dm): GOpaque/GOpaque conversion should be done more gracefully in the system -template<> struct get_in >: public get_in > -{ -}; - -//FIXME(dm): GOpaque/GOpaque conversion should be done more gracefully in the system -template<> struct get_in >: public get_in > -{ -}; - -template struct get_in -{ - static T get(GCPUContext &ctx, int idx) { return ctx.inArg(idx); } -}; - -struct tracked_cv_mat{ - tracked_cv_mat(cv::Mat& m) : r{m}, original_data{m.data} {} - cv::Mat r; - uchar* original_data; - - operator cv::Mat& (){ return r;} - void validate() const{ - if (r.data != original_data) - { - util::throw_error - (std::logic_error - ("OpenCV kernel output parameter was reallocated. \n" - "Incorrect meta data was provided ?")); - } - } -}; - -template -void postprocess(Outputs&... outs) -{ - struct - { - void operator()(tracked_cv_mat* bm) { bm->validate(); } - void operator()(...) { } - - } validate; - //dummy array to unfold parameter pack - int dummy[] = { 0, (validate(&outs), 0)... }; - cv::util::suppress_unused_warning(dummy); -} - -template struct get_out; -template<> struct get_out -{ - static tracked_cv_mat get(GCPUContext &ctx, int idx) - { - auto& r = ctx.outMatR(idx); - return {r}; - } -}; -template<> struct get_out -{ - static tracked_cv_mat get(GCPUContext &ctx, int idx) - { - return get_out::get(ctx, idx); - } -}; -template<> struct get_out -{ - static cv::Scalar& get(GCPUContext &ctx, int idx) - { - return ctx.outValR(idx); - } -}; -template<> struct get_out -{ - static cv::MediaFrame& get(GCPUContext &ctx, int idx) - { - return ctx.outFrame(idx); - } -}; -template struct get_out> -{ - static std::vector& get(GCPUContext &ctx, int idx) - { - return ctx.outVecR(idx); - } -}; - -//FIXME(dm): GArray/GArray conversion should be done more gracefully in the system -template<> struct get_out >: public get_out > -{ -}; - -// FIXME(dm): GArray>/GArray> conversion should be done more gracefully in the system -template struct get_out> >: public get_out> > -{ -}; - -template struct get_out> -{ - static U& get(GCPUContext &ctx, int idx) - { - return ctx.outOpaqueR(idx); - } -}; - -template -struct OCVSetupHelper; - -template -struct OCVSetupHelper> -{ - // Using 'auto' return type and 'decltype' specifier in both 'setup_impl' versions - // to check existence of required 'Impl::setup' functions. - // While 'decltype' specifier accepts expression we pass expression with 'comma-operator' - // where first operand of comma-operator is call attempt to desired 'Impl::setup' and - // the second operand is 'void()' expression. - // - // SFINAE for 'Impl::setup' which accepts compile arguments. - template - static auto setup_impl(const GMetaArgs &metaArgs, const GArgs &args, - GArg &state, const GCompileArgs &compileArgs, - detail::Seq) -> - decltype(Impl::setup(detail::get_in_meta(metaArgs, args, IIs)..., - std::declval - >::type - >(), - compileArgs) - , void()) - { - // TODO: unique_ptr <-> shared_ptr conversion ? - // To check: Conversion is possible only if the state which should be passed to - // 'setup' user callback isn't required to have previous value - std::shared_ptr stPtr; - Impl::setup(detail::get_in_meta(metaArgs, args, IIs)..., stPtr, compileArgs); - state = GArg(stPtr); - } - - // SFINAE for 'Impl::setup' which doesn't accept compile arguments. - template - static auto setup_impl(const GMetaArgs &metaArgs, const GArgs &args, - GArg &state, const GCompileArgs &/* compileArgs */, - detail::Seq) -> - decltype(Impl::setup(detail::get_in_meta(metaArgs, args, IIs)..., - std::declval - >::type - >() - ) - , void()) - { - // The same comment as in 'setup' above. - std::shared_ptr stPtr; - Impl::setup(detail::get_in_meta(metaArgs, args, IIs)..., stPtr); - state = GArg(stPtr); - } - - static void setup(const GMetaArgs &metaArgs, const GArgs &args, - GArg& state, const GCompileArgs &compileArgs) - { - setup_impl(metaArgs, args, state, compileArgs, - typename detail::MkSeq::type()); - } -}; - -// OCVCallHelper is a helper class to call stateless OCV kernels and OCV kernel functors. -template -struct OCVCallHelper; - -// FIXME: probably can be simplified with std::apply or analogue. -template -struct OCVCallHelper, std::tuple> -{ - template - struct call_and_postprocess - { - template - static void call(Inputs&&... ins, Outputs&&... outs) - { - //not using a std::forward on outs is deliberate in order to - //cause compilation error, by trying to bind rvalue references to lvalue references - Impl::run(std::forward(ins)..., outs...); - postprocess(outs...); - } - - template - static void call(Impl& impl, Inputs&&... ins, Outputs&&... outs) - { - impl(std::forward(ins)..., outs...); - } - }; - - template - static void call_impl(GCPUContext &ctx, detail::Seq, detail::Seq) - { - //Make sure that OpenCV kernels do not reallocate memory for output parameters - //by comparing it's state (data ptr) before and after the call. - //This is done by converting each output Mat into tracked_cv_mat object, and binding - //them to parameters of ad-hoc function - call_and_postprocess::get(ctx, IIs))...> - ::call(get_in::get(ctx, IIs)..., get_out::get(ctx, OIs)...); - } - - template - static void call_impl(cv::GCPUContext &ctx, Impl& impl, - detail::Seq, detail::Seq) - { - call_and_postprocess::get(ctx, IIs))...> - ::call(impl, get_in::get(ctx, IIs)..., get_out::get(ctx, OIs)...); - } - - static void call(GCPUContext &ctx) - { - call_impl(ctx, - typename detail::MkSeq::type(), - typename detail::MkSeq::type()); - } - - // NB: Same as call but calling the object - // This necessary for kernel implementations that have a state - // and are represented as an object - static void callFunctor(cv::GCPUContext &ctx, Impl& impl) - { - call_impl(ctx, impl, - typename detail::MkSeq::type(), - typename detail::MkSeq::type()); - } -}; - -// OCVStCallHelper is a helper class to call stateful OCV kernels. -template -struct OCVStCallHelper; - -template -struct OCVStCallHelper, std::tuple> : - OCVCallHelper, std::tuple> -{ - template - struct call_and_postprocess - { - template - static void call(typename Impl::State& st, Inputs&&... ins, Outputs&&... outs) - { - Impl::run(std::forward(ins)..., outs..., st); - postprocess(outs...); - } - }; - - template - static void call_impl(GCPUContext &ctx, detail::Seq, detail::Seq) - { - auto& st = *ctx.state().get>(); - call_and_postprocess::get(ctx, IIs))...> - ::call(st, get_in::get(ctx, IIs)..., get_out::get(ctx, OIs)...); - } - - static void call(GCPUContext &ctx) - { - call_impl(ctx, - typename detail::MkSeq::type(), - typename detail::MkSeq::type()); - } -}; - -} // namespace detail - -template -class GCPUKernelImpl: public cv::detail::KernelTag -{ - using CallHelper = cv::detail::OCVCallHelper; - -public: - using API = K; - - static cv::gapi::GBackend backend() { return cv::gapi::cpu::backend(); } - static cv::GCPUKernel kernel() { return GCPUKernel(&CallHelper::call); } -}; - -template -class GCPUStKernelImpl: public cv::detail::KernelTag -{ - using StSetupHelper = detail::OCVSetupHelper; - using StCallHelper = detail::OCVStCallHelper; - -public: - using API = K; - using State = S; - - static cv::gapi::GBackend backend() { return cv::gapi::cpu::backend(); } - static cv::GCPUKernel kernel() { return GCPUKernel(&StCallHelper::call, - &StSetupHelper::setup); } -}; - -#define GAPI_OCV_KERNEL(Name, API) struct Name: public cv::GCPUKernelImpl - -// TODO: Reuse Anatoliy's logic for support of types with commas in macro. -// Retrieve the common part from Anatoliy's logic to the separate place. -#define GAPI_OCV_KERNEL_ST(Name, API, State) \ - struct Name: public cv::GCPUStKernelImpl \ - -/// @private -class gapi::cpu::GOCVFunctor : public gapi::GFunctor -{ -public: - using Impl = std::function; - using Meta = cv::GKernel::M; - - GOCVFunctor(const char* id, const Meta &meta, const Impl& impl) - : gapi::GFunctor(id), impl_{GCPUKernel(impl), meta} - { - } - - GKernelImpl impl() const override { return impl_; } - gapi::GBackend backend() const override { return gapi::cpu::backend(); } - -private: - GKernelImpl impl_; -}; - -//! @cond IGNORED -template -gapi::cpu::GOCVFunctor gapi::cpu::ocv_kernel(Callable& c) -{ - using P = cv::detail::OCVCallHelper; - return GOCVFunctor{ K::id() - , &K::getOutMeta - , std::bind(&P::callFunctor, std::placeholders::_1, std::ref(c)) - }; -} - -template -gapi::cpu::GOCVFunctor gapi::cpu::ocv_kernel(const Callable& c) -{ - using P = cv::detail::OCVCallHelper; - return GOCVFunctor{ K::id() - , &K::getOutMeta - , std::bind(&P::callFunctor, std::placeholders::_1, c) - }; -} -//! @endcond - -} // namespace cv - -#if defined _MSC_VER -#pragma warning(pop) -#endif - -#endif // OPENCV_GAPI_GCPUKERNEL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2022 Intel Corporation + + +#ifndef OPENCV_GAPI_GCPUKERNEL_HPP +#define OPENCV_GAPI_GCPUKERNEL_HPP + +#if defined _MSC_VER +#pragma warning(push) +#pragma warning(disable: 4702) // "Unreachable code" on postprocess(...) call inside OCVCallHelper +#endif + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include //suppress_unused_warning +#include + +// FIXME: namespace scheme for backends? +namespace cv { + +namespace gimpl +{ + // Forward-declare an internal class + class GCPUExecutable; +} // namespace gimpl + +namespace gapi +{ +/** + * @brief This namespace contains G-API CPU backend functions, + * structures, and symbols. + */ +namespace cpu +{ + /** + * \addtogroup gapi_std_backends + * @{ + * + * @brief G-API backends available in this OpenCV version + * + * G-API backends play a corner stone role in G-API execution + * stack. Every backend is hardware-oriented and thus can run its + * kernels efficiently on the target platform. + * + * Backends are usually "black boxes" for G-API users -- on the API + * side, all backends are represented as different objects of the + * same class cv::gapi::GBackend. + * User can manipulate with backends by specifying which kernels to use. + * + * @sa @ref gapi_hld + */ + + /** + * @brief Get a reference to CPU (OpenCV) backend. + * + * This is the default backend in G-API at the moment, providing + * broader functional coverage but losing some graph model + * advantages. Provided mostly for reference and prototyping + * purposes. + * + * @sa gapi_std_backends + */ + GAPI_EXPORTS cv::gapi::GBackend backend(); + /** @} */ + + class GOCVFunctor; + + //! @cond IGNORED + template + GOCVFunctor ocv_kernel(const Callable& c); + + template + GOCVFunctor ocv_kernel(Callable& c); + //! @endcond + +} // namespace cpu +} // namespace gapi + +// Represents arguments which are passed to a wrapped CPU function +// FIXME: put into detail? +class GAPI_EXPORTS GCPUContext +{ +public: + // Generic accessor API + template + const T& inArg(int input) { return m_args.at(input).get(); } + + // Syntax sugar + const cv::Mat& inMat(int input); + cv::Mat& outMatR(int output); // FIXME: Avoid cv::Mat m = ctx.outMatR() + + const cv::Scalar& inVal(int input); + cv::Scalar& outValR(int output); // FIXME: Avoid cv::Scalar s = ctx.outValR() + cv::MediaFrame& outFrame(int output); + template std::vector& outVecR(int output) // FIXME: the same issue + { + return outVecRef(output).wref(); + } + template T& outOpaqueR(int output) // FIXME: the same issue + { + return outOpaqueRef(output).wref(); + } + + GArg state() + { + return m_state; + } + +protected: + detail::VectorRef& outVecRef(int output); + detail::OpaqueRef& outOpaqueRef(int output); + + std::vector m_args; + GArg m_state; + + //FIXME: avoid conversion of arguments from internal representation to OpenCV one on each call + //to OCV kernel. (This can be achieved by a two single time conversions in GCPUExecutable::run, + //once on enter for input and output arguments, and once before return for output arguments only + std::unordered_map m_results; + + friend class gimpl::GCPUExecutable; +}; + +class GAPI_EXPORTS GCPUKernel +{ +public: + // This function is a kernel's execution entry point (does the processing work) + using RunF = std::function; + // This function is a stateful kernel's setup routine (configures state) + using SetupF = std::function; + + GCPUKernel(); + GCPUKernel(const RunF& runF, const SetupF& setupF = nullptr); + + RunF m_runF = nullptr; + SetupF m_setupF = nullptr; + + bool m_isStateful = false; +}; + +// FIXME: This is an ugly ad-hoc implementation. TODO: refactor + +namespace detail +{ +template struct get_in; +template<> struct get_in +{ + static cv::Mat get(GCPUContext &ctx, int idx) { return ctx.inMat(idx); } +}; +template<> struct get_in +{ + static cv::Mat get(GCPUContext &ctx, int idx) { return get_in::get(ctx, idx); } +}; +template<> struct get_in +{ + static cv::MediaFrame get(GCPUContext &ctx, int idx) { return ctx.inArg(idx); } +}; +template<> struct get_in +{ + static cv::Scalar get(GCPUContext &ctx, int idx) { return ctx.inVal(idx); } +}; +template struct get_in > +{ + static const std::vector& get(GCPUContext &ctx, int idx) { return ctx.inArg(idx).rref(); } +}; +template struct get_in > +{ + static const U& get(GCPUContext &ctx, int idx) { return ctx.inArg(idx).rref(); } +}; + +//FIXME(dm): GArray/GArray conversion should be done more gracefully in the system +template<> struct get_in >: public get_in > +{ +}; + +//FIXME(dm): GArray/GArray conversion should be done more gracefully in the system +template<> struct get_in >: public get_in > +{ +}; + +// FIXME(dm): GArray>/GArray> conversion should be done more gracefully in the system +template struct get_in> >: public get_in> > +{ +}; + +//FIXME(dm): GOpaque/GOpaque conversion should be done more gracefully in the system +template<> struct get_in >: public get_in > +{ +}; + +//FIXME(dm): GOpaque/GOpaque conversion should be done more gracefully in the system +template<> struct get_in >: public get_in > +{ +}; + +template struct get_in +{ + static T get(GCPUContext &ctx, int idx) { return ctx.inArg(idx); } +}; + +struct tracked_cv_mat{ + tracked_cv_mat(cv::Mat& m) : r{m}, original_data{m.data} {} + cv::Mat r; + uchar* original_data; + + operator cv::Mat& (){ return r;} + void validate() const{ + if (r.data != original_data) + { + util::throw_error + (std::logic_error + ("OpenCV kernel output parameter was reallocated. \n" + "Incorrect meta data was provided ?")); + } + } +}; + +template +void postprocess(Outputs&... outs) +{ + struct + { + void operator()(tracked_cv_mat* bm) { bm->validate(); } + void operator()(...) { } + + } validate; + //dummy array to unfold parameter pack + int dummy[] = { 0, (validate(&outs), 0)... }; + cv::util::suppress_unused_warning(dummy); +} + +template struct get_out; +template<> struct get_out +{ + static tracked_cv_mat get(GCPUContext &ctx, int idx) + { + auto& r = ctx.outMatR(idx); + return {r}; + } +}; +template<> struct get_out +{ + static tracked_cv_mat get(GCPUContext &ctx, int idx) + { + return get_out::get(ctx, idx); + } +}; +template<> struct get_out +{ + static cv::Scalar& get(GCPUContext &ctx, int idx) + { + return ctx.outValR(idx); + } +}; +template<> struct get_out +{ + static cv::MediaFrame& get(GCPUContext &ctx, int idx) + { + return ctx.outFrame(idx); + } +}; +template struct get_out> +{ + static std::vector& get(GCPUContext &ctx, int idx) + { + return ctx.outVecR(idx); + } +}; + +//FIXME(dm): GArray/GArray conversion should be done more gracefully in the system +template<> struct get_out >: public get_out > +{ +}; + +// FIXME(dm): GArray>/GArray> conversion should be done more gracefully in the system +template struct get_out> >: public get_out> > +{ +}; + +template struct get_out> +{ + static U& get(GCPUContext &ctx, int idx) + { + return ctx.outOpaqueR(idx); + } +}; + +template +struct OCVSetupHelper; + +template +struct OCVSetupHelper> +{ + // Using 'auto' return type and 'decltype' specifier in both 'setup_impl' versions + // to check existence of required 'Impl::setup' functions. + // While 'decltype' specifier accepts expression we pass expression with 'comma-operator' + // where first operand of comma-operator is call attempt to desired 'Impl::setup' and + // the second operand is 'void()' expression. + // + // SFINAE for 'Impl::setup' which accepts compile arguments. + template + static auto setup_impl(const GMetaArgs &metaArgs, const GArgs &args, + GArg &state, const GCompileArgs &compileArgs, + detail::Seq) -> + decltype(Impl::setup(detail::get_in_meta(metaArgs, args, IIs)..., + std::declval + >::type + >(), + compileArgs) + , void()) + { + // TODO: unique_ptr <-> shared_ptr conversion ? + // To check: Conversion is possible only if the state which should be passed to + // 'setup' user callback isn't required to have previous value + std::shared_ptr stPtr; + Impl::setup(detail::get_in_meta(metaArgs, args, IIs)..., stPtr, compileArgs); + state = GArg(stPtr); + } + + // SFINAE for 'Impl::setup' which doesn't accept compile arguments. + template + static auto setup_impl(const GMetaArgs &metaArgs, const GArgs &args, + GArg &state, const GCompileArgs &/* compileArgs */, + detail::Seq) -> + decltype(Impl::setup(detail::get_in_meta(metaArgs, args, IIs)..., + std::declval + >::type + >() + ) + , void()) + { + // The same comment as in 'setup' above. + std::shared_ptr stPtr; + Impl::setup(detail::get_in_meta(metaArgs, args, IIs)..., stPtr); + state = GArg(stPtr); + } + + static void setup(const GMetaArgs &metaArgs, const GArgs &args, + GArg& state, const GCompileArgs &compileArgs) + { + setup_impl(metaArgs, args, state, compileArgs, + typename detail::MkSeq::type()); + } +}; + +// OCVCallHelper is a helper class to call stateless OCV kernels and OCV kernel functors. +template +struct OCVCallHelper; + +// FIXME: probably can be simplified with std::apply or analogue. +template +struct OCVCallHelper, std::tuple> +{ + template + struct call_and_postprocess + { + template + static void call(Inputs&&... ins, Outputs&&... outs) + { + //not using a std::forward on outs is deliberate in order to + //cause compilation error, by trying to bind rvalue references to lvalue references + Impl::run(std::forward(ins)..., outs...); + postprocess(outs...); + } + + template + static void call(Impl& impl, Inputs&&... ins, Outputs&&... outs) + { + impl(std::forward(ins)..., outs...); + } + }; + + template + static void call_impl(GCPUContext &ctx, detail::Seq, detail::Seq) + { + //Make sure that OpenCV kernels do not reallocate memory for output parameters + //by comparing it's state (data ptr) before and after the call. + //This is done by converting each output Mat into tracked_cv_mat object, and binding + //them to parameters of ad-hoc function + call_and_postprocess::get(ctx, IIs))...> + ::call(get_in::get(ctx, IIs)..., get_out::get(ctx, OIs)...); + } + + template + static void call_impl(cv::GCPUContext &ctx, Impl& impl, + detail::Seq, detail::Seq) + { + call_and_postprocess::get(ctx, IIs))...> + ::call(impl, get_in::get(ctx, IIs)..., get_out::get(ctx, OIs)...); + } + + static void call(GCPUContext &ctx) + { + call_impl(ctx, + typename detail::MkSeq::type(), + typename detail::MkSeq::type()); + } + + // NB: Same as call but calling the object + // This necessary for kernel implementations that have a state + // and are represented as an object + static void callFunctor(cv::GCPUContext &ctx, Impl& impl) + { + call_impl(ctx, impl, + typename detail::MkSeq::type(), + typename detail::MkSeq::type()); + } +}; + +// OCVStCallHelper is a helper class to call stateful OCV kernels. +template +struct OCVStCallHelper; + +template +struct OCVStCallHelper, std::tuple> : + OCVCallHelper, std::tuple> +{ + template + struct call_and_postprocess + { + template + static void call(typename Impl::State& st, Inputs&&... ins, Outputs&&... outs) + { + Impl::run(std::forward(ins)..., outs..., st); + postprocess(outs...); + } + }; + + template + static void call_impl(GCPUContext &ctx, detail::Seq, detail::Seq) + { + auto& st = *ctx.state().get>(); + call_and_postprocess::get(ctx, IIs))...> + ::call(st, get_in::get(ctx, IIs)..., get_out::get(ctx, OIs)...); + } + + static void call(GCPUContext &ctx) + { + call_impl(ctx, + typename detail::MkSeq::type(), + typename detail::MkSeq::type()); + } +}; + +} // namespace detail + +template +class GCPUKernelImpl: public cv::detail::KernelTag +{ + using CallHelper = cv::detail::OCVCallHelper; + +public: + using API = K; + + static cv::gapi::GBackend backend() { return cv::gapi::cpu::backend(); } + static cv::GCPUKernel kernel() { return GCPUKernel(&CallHelper::call); } +}; + +template +class GCPUStKernelImpl: public cv::detail::KernelTag +{ + using StSetupHelper = detail::OCVSetupHelper; + using StCallHelper = detail::OCVStCallHelper; + +public: + using API = K; + using State = S; + + static cv::gapi::GBackend backend() { return cv::gapi::cpu::backend(); } + static cv::GCPUKernel kernel() { return GCPUKernel(&StCallHelper::call, + &StSetupHelper::setup); } +}; + +#define GAPI_OCV_KERNEL(Name, API) struct Name: public cv::GCPUKernelImpl + +// TODO: Reuse Anatoliy's logic for support of types with commas in macro. +// Retrieve the common part from Anatoliy's logic to the separate place. +#define GAPI_OCV_KERNEL_ST(Name, API, State) \ + struct Name: public cv::GCPUStKernelImpl \ + +/// @private +class gapi::cpu::GOCVFunctor : public gapi::GFunctor +{ +public: + using Impl = std::function; + using Meta = cv::GKernel::M; + + GOCVFunctor(const char* id, const Meta &meta, const Impl& impl) + : gapi::GFunctor(id), impl_{GCPUKernel(impl), meta} + { + } + + GKernelImpl impl() const override { return impl_; } + gapi::GBackend backend() const override { return gapi::cpu::backend(); } + +private: + GKernelImpl impl_; +}; + +//! @cond IGNORED +template +gapi::cpu::GOCVFunctor gapi::cpu::ocv_kernel(Callable& c) +{ + using P = cv::detail::OCVCallHelper; + return GOCVFunctor{ K::id() + , &K::getOutMeta + , std::bind(&P::callFunctor, std::placeholders::_1, std::ref(c)) + }; +} + +template +gapi::cpu::GOCVFunctor gapi::cpu::ocv_kernel(const Callable& c) +{ + using P = cv::detail::OCVCallHelper; + return GOCVFunctor{ K::id() + , &K::getOutMeta + , std::bind(&P::callFunctor, std::placeholders::_1, c) + }; +} +//! @endcond + +} // namespace cv + +#if defined _MSC_VER +#pragma warning(pop) +#endif + +#endif // OPENCV_GAPI_GCPUKERNEL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/imgproc.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/imgproc.hpp index 0b96db08ae..4001a77d3b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/imgproc.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/imgproc.hpp @@ -1,27 +1,27 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_CPU_IMGPROC_API_HPP -#define OPENCV_GAPI_CPU_IMGPROC_API_HPP - -#include // GAPI_EXPORTS -#include // GKernelPackage - -namespace cv { -namespace gapi { -namespace imgproc { -namespace cpu { - -GAPI_EXPORTS GKernelPackage kernels(); - -} // namespace cpu -} // namespace imgproc -} // namespace gapi -} // namespace cv - - -#endif // OPENCV_GAPI_CPU_IMGPROC_API_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_CPU_IMGPROC_API_HPP +#define OPENCV_GAPI_CPU_IMGPROC_API_HPP + +#include // GAPI_EXPORTS +#include // GKernelPackage + +namespace cv { +namespace gapi { +namespace imgproc { +namespace cpu { + +GAPI_EXPORTS GKernelPackage kernels(); + +} // namespace cpu +} // namespace imgproc +} // namespace gapi +} // namespace cv + + +#endif // OPENCV_GAPI_CPU_IMGPROC_API_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/ot.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/ot.hpp index 03dbe904cc..047e935716 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/ot.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/ot.hpp @@ -1,29 +1,29 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_CPU_OT_API_HPP -#define OPENCV_GAPI_CPU_OT_API_HPP - -#include // GAPI_EXPORTS -#include // GKernelPackage - -namespace cv { -namespace gapi { -/** - * @brief This namespace contains G-API Operation Types for - * VAS Object Tracking module functionality. - */ -namespace ot { -namespace cpu { -GAPI_EXPORTS_W GKernelPackage kernels(); -} // namespace cpu -} // namespace ot -} // namespace gapi -} // namespace cv - - -#endif // OPENCV_GAPI_CPU_OT_API_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_CPU_OT_API_HPP +#define OPENCV_GAPI_CPU_OT_API_HPP + +#include // GAPI_EXPORTS +#include // GKernelPackage + +namespace cv { +namespace gapi { +/** + * @brief This namespace contains G-API Operation Types for + * VAS Object Tracking module functionality. + */ +namespace ot { +namespace cpu { +GAPI_EXPORTS_W GKernelPackage kernels(); +} // namespace cpu +} // namespace ot +} // namespace gapi +} // namespace cv + + +#endif // OPENCV_GAPI_CPU_OT_API_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/stereo.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/stereo.hpp index e2a2242bd0..9a8109c34e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/stereo.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/stereo.hpp @@ -1,48 +1,48 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2021 Intel Corporation - -#ifndef OPENCV_GAPI_CPU_STEREO_API_HPP -#define OPENCV_GAPI_CPU_STEREO_API_HPP - -#include // GKernelPackage - -namespace cv { -namespace gapi { -namespace calib3d { -namespace cpu { - -GAPI_EXPORTS GKernelPackage kernels(); - -/** @brief Structure for the Stereo operation initialization parameters.*/ -struct GAPI_EXPORTS StereoInitParam { - StereoInitParam(int nD, int bS, double bL, double f): - numDisparities(nD), blockSize(bS), baseline(bL), focus(f) {} - - StereoInitParam() = default; - - int numDisparities = 0; - int blockSize = 21; - double baseline = 63.5; - double focus = 3.6; -}; - -} // namespace cpu -} // namespace calib3d -} // namespace gapi - -namespace detail { - - template<> struct CompileArgTag { - static const char* tag() { - return "org.opencv.stereoInit"; - } -}; - -} // namespace detail -} // namespace cv - - -#endif // OPENCV_GAPI_CPU_STEREO_API_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2021 Intel Corporation + +#ifndef OPENCV_GAPI_CPU_STEREO_API_HPP +#define OPENCV_GAPI_CPU_STEREO_API_HPP + +#include // GKernelPackage + +namespace cv { +namespace gapi { +namespace calib3d { +namespace cpu { + +GAPI_EXPORTS GKernelPackage kernels(); + +/** @brief Structure for the Stereo operation initialization parameters.*/ +struct GAPI_EXPORTS StereoInitParam { + StereoInitParam(int nD, int bS, double bL, double f): + numDisparities(nD), blockSize(bS), baseline(bL), focus(f) {} + + StereoInitParam() = default; + + int numDisparities = 0; + int blockSize = 21; + double baseline = 63.5; + double focus = 3.6; +}; + +} // namespace cpu +} // namespace calib3d +} // namespace gapi + +namespace detail { + + template<> struct CompileArgTag { + static const char* tag() { + return "org.opencv.stereoInit"; + } +}; + +} // namespace detail +} // namespace cv + + +#endif // OPENCV_GAPI_CPU_STEREO_API_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/video.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/video.hpp index d3c1f2e670..934822456e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/video.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/video.hpp @@ -1,25 +1,25 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020 Intel Corporation - -#ifndef OPENCV_GAPI_CPU_VIDEO_API_HPP -#define OPENCV_GAPI_CPU_VIDEO_API_HPP - -#include // GKernelPackage - -namespace cv { -namespace gapi { -namespace video { -namespace cpu { - -GAPI_EXPORTS GKernelPackage kernels(); - -} // namespace cpu -} // namespace video -} // namespace gapi -} // namespace cv - - -#endif // OPENCV_GAPI_CPU_VIDEO_API_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020 Intel Corporation + +#ifndef OPENCV_GAPI_CPU_VIDEO_API_HPP +#define OPENCV_GAPI_CPU_VIDEO_API_HPP + +#include // GKernelPackage + +namespace cv { +namespace gapi { +namespace video { +namespace cpu { + +GAPI_EXPORTS GKernelPackage kernels(); + +} // namespace cpu +} // namespace video +} // namespace gapi +} // namespace cv + + +#endif // OPENCV_GAPI_CPU_VIDEO_API_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/core.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/core.hpp index a4329d6f50..634a3a85d0 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/core.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/core.hpp @@ -1,20 +1,20 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_FLUID_CORE_HPP -#define OPENCV_GAPI_FLUID_CORE_HPP - -#include // GKernelPackage -#include // GAPI_EXPORTS - -namespace cv { namespace gapi { namespace core { namespace fluid { - -GAPI_EXPORTS_W cv::GKernelPackage kernels(); - -}}}} - -#endif // OPENCV_GAPI_FLUID_CORE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_FLUID_CORE_HPP +#define OPENCV_GAPI_FLUID_CORE_HPP + +#include // GKernelPackage +#include // GAPI_EXPORTS + +namespace cv { namespace gapi { namespace core { namespace fluid { + +GAPI_EXPORTS_W cv::GKernelPackage kernels(); + +}}}} + +#endif // OPENCV_GAPI_FLUID_CORE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/gfluidbuffer.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/gfluidbuffer.hpp index 551f0a398f..2efd98b50e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/gfluidbuffer.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/gfluidbuffer.hpp @@ -1,154 +1,154 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_FLUID_BUFFER_HPP -#define OPENCV_GAPI_FLUID_BUFFER_HPP - -#include -#include // accumulate -#include // ostream -#include // uint8_t - -#include -#include - -#include - -namespace cv { -namespace gapi { -namespace fluid { - -struct Border -{ - // This constructor is required to support existing kernels which are part of G-API - Border(int _type, cv::Scalar _val) : type(_type), value(_val) {} - - int type; - cv::Scalar value; -}; - -using BorderOpt = util::optional; - -bool operator == (const Border& b1, const Border& b2); - -class GAPI_EXPORTS Buffer; - -class GAPI_EXPORTS View -{ -public: - struct Cache - { - std::vector m_linePtrs; - GMatDesc m_desc; - int m_border_size = 0; - - inline const uint8_t* linePtr(int index) const - { - // "out_of_window" check: - // user must not request the lines which are outside of specified kernel window - GAPI_DbgAssert(index >= -m_border_size - && index < -m_border_size + static_cast(m_linePtrs.size())); - return m_linePtrs[index + m_border_size]; - } - }; - - const inline uint8_t* InLineB(int index) const // -(w-1)/2...0...+(w-1)/2 for Filters - { - return m_cache->linePtr(index); - } - - template const inline T* InLine(int i) const - { - const uint8_t* ptr = this->InLineB(i); - return reinterpret_cast(ptr); - } - - inline operator bool() const { return m_priv != nullptr; } - bool ready() const; - inline int length() const { return m_cache->m_desc.size.width; } - int y() const; - - inline const GMatDesc& meta() const { return m_cache->m_desc; } - - class GAPI_EXPORTS Priv; // internal use only - Priv& priv(); // internal use only - const Priv& priv() const; // internal use only - - View(); - View(std::unique_ptr&& p); - View(View&& v); - View& operator=(View&& v); - ~View(); - -private: - std::unique_ptr m_priv; - const Cache* m_cache = nullptr; -}; - -class GAPI_EXPORTS Buffer -{ -public: - struct Cache - { - std::vector m_linePtrs; - GMatDesc m_desc; - }; - - // Default constructor (executable creation stage, - // all following initialization performed in Priv::init()) - Buffer(); - // Scratch constructor (user kernels) - Buffer(const cv::GMatDesc &desc); - - // Constructor for intermediate buffers (for tests) - Buffer(const cv::GMatDesc &desc, - int max_line_consumption, int border_size, - int skew, - int wlpi, - BorderOpt border); - // Constructor for in/out buffers (for tests) - Buffer(const cv::Mat &data, bool is_input); - ~Buffer(); - Buffer& operator=(Buffer&&); - - inline uint8_t* OutLineB(int index = 0) - { - return m_cache->m_linePtrs[index]; - } - - template inline T* OutLine(int index = 0) - { - uint8_t* ptr = this->OutLineB(index); - return reinterpret_cast(ptr); - } - - int y() const; - - int linesReady() const; - void debug(std::ostream &os) const; - inline int length() const { return m_cache->m_desc.size.width; } - int lpi() const; // LPI for WRITER - - inline const GMatDesc& meta() const { return m_cache->m_desc; } - - View mkView(int borderSize, bool ownStorage); - void addView(const View* v); - - class GAPI_EXPORTS Priv; // internal use only - Priv& priv(); // internal use only - const Priv& priv() const; // internal use only - -private: - std::unique_ptr m_priv; - const Cache* m_cache; -}; - -} // namespace cv::gapi::fluid -} // namespace cv::gapi -} // namespace cv - -#endif // OPENCV_GAPI_FLUID_BUFFER_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_FLUID_BUFFER_HPP +#define OPENCV_GAPI_FLUID_BUFFER_HPP + +#include +#include // accumulate +#include // ostream +#include // uint8_t + +#include +#include + +#include + +namespace cv { +namespace gapi { +namespace fluid { + +struct Border +{ + // This constructor is required to support existing kernels which are part of G-API + Border(int _type, cv::Scalar _val) : type(_type), value(_val) {} + + int type; + cv::Scalar value; +}; + +using BorderOpt = util::optional; + +bool operator == (const Border& b1, const Border& b2); + +class GAPI_EXPORTS Buffer; + +class GAPI_EXPORTS View +{ +public: + struct Cache + { + std::vector m_linePtrs; + GMatDesc m_desc; + int m_border_size = 0; + + inline const uint8_t* linePtr(int index) const + { + // "out_of_window" check: + // user must not request the lines which are outside of specified kernel window + GAPI_DbgAssert(index >= -m_border_size + && index < -m_border_size + static_cast(m_linePtrs.size())); + return m_linePtrs[index + m_border_size]; + } + }; + + const inline uint8_t* InLineB(int index) const // -(w-1)/2...0...+(w-1)/2 for Filters + { + return m_cache->linePtr(index); + } + + template const inline T* InLine(int i) const + { + const uint8_t* ptr = this->InLineB(i); + return reinterpret_cast(ptr); + } + + inline operator bool() const { return m_priv != nullptr; } + bool ready() const; + inline int length() const { return m_cache->m_desc.size.width; } + int y() const; + + inline const GMatDesc& meta() const { return m_cache->m_desc; } + + class GAPI_EXPORTS Priv; // internal use only + Priv& priv(); // internal use only + const Priv& priv() const; // internal use only + + View(); + View(std::unique_ptr&& p); + View(View&& v); + View& operator=(View&& v); + ~View(); + +private: + std::unique_ptr m_priv; + const Cache* m_cache = nullptr; +}; + +class GAPI_EXPORTS Buffer +{ +public: + struct Cache + { + std::vector m_linePtrs; + GMatDesc m_desc; + }; + + // Default constructor (executable creation stage, + // all following initialization performed in Priv::init()) + Buffer(); + // Scratch constructor (user kernels) + Buffer(const cv::GMatDesc &desc); + + // Constructor for intermediate buffers (for tests) + Buffer(const cv::GMatDesc &desc, + int max_line_consumption, int border_size, + int skew, + int wlpi, + BorderOpt border); + // Constructor for in/out buffers (for tests) + Buffer(const cv::Mat &data, bool is_input); + ~Buffer(); + Buffer& operator=(Buffer&&); + + inline uint8_t* OutLineB(int index = 0) + { + return m_cache->m_linePtrs[index]; + } + + template inline T* OutLine(int index = 0) + { + uint8_t* ptr = this->OutLineB(index); + return reinterpret_cast(ptr); + } + + int y() const; + + int linesReady() const; + void debug(std::ostream &os) const; + inline int length() const { return m_cache->m_desc.size.width; } + int lpi() const; // LPI for WRITER + + inline const GMatDesc& meta() const { return m_cache->m_desc; } + + View mkView(int borderSize, bool ownStorage); + void addView(const View* v); + + class GAPI_EXPORTS Priv; // internal use only + Priv& priv(); // internal use only + const Priv& priv() const; // internal use only + +private: + std::unique_ptr m_priv; + const Cache* m_cache; +}; + +} // namespace cv::gapi::fluid +} // namespace cv::gapi +} // namespace cv + +#endif // OPENCV_GAPI_FLUID_BUFFER_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/gfluidkernel.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/gfluidkernel.hpp index c3ae9dfdd6..87d42a6fc5 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/gfluidkernel.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/gfluidkernel.hpp @@ -1,442 +1,442 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2019 Intel Corporation - - -#ifndef OPENCV_GAPI_FLUID_KERNEL_HPP -#define OPENCV_GAPI_FLUID_KERNEL_HPP - -#include -#include -#include -#include - -#include -#include -#include -#include - -#include - -// FIXME: namespace scheme for backends? -namespace cv { - -namespace gapi -{ -/** - * @brief This namespace contains G-API Fluid backend functions, structures, and symbols. - */ -namespace fluid -{ - /** - * \addtogroup gapi_std_backends G-API Standard Backends - * @{ - */ - /** - * @brief Get a reference to Fluid backend. - * - * @sa gapi_std_backends - */ - GAPI_EXPORTS cv::gapi::GBackend backend(); - /** @} */ -} // namespace fluid -} // namespace gapi - - -class GAPI_EXPORTS GFluidKernel -{ -public: - enum class Kind - { - Filter, - Resize, - YUV420toRGB //Color conversion of 4:2:0 chroma sub-sampling formats (NV12, I420 ..etc) to RGB - }; - - // This function is a generic "doWork" callback - using F = std::function &)>; - - // This function is a generic "initScratch" callback - using IS = std::function; - - // This function is a generic "resetScratch" callback - using RS = std::function; - - // This function describes kernel metadata inference rule. - using M = std::function; - - // This function is a generic "getBorder" callback (extracts border-related data from kernel's input parameters) - using B = std::function; - - // This function is a generic "getWindow" callback (extracts window-related data from kernel's input parameters) - using GW = std::function; - - // FIXME: move implementations out of header file - GFluidKernel() {} - GFluidKernel(Kind k, int l, bool scratch, const F& f, const IS &is, const RS &rs, const B& b, const GW& win) - : m_kind(k) - , m_lpi(l) - , m_scratch(scratch) - , m_f(f) - , m_is(is) - , m_rs(rs) - , m_b(b) - , m_gw(win) {} - - Kind m_kind; - const int m_lpi = -1; - const bool m_scratch = false; - - const F m_f; - const IS m_is; - const RS m_rs; - const B m_b; - const GW m_gw; -}; - -// FIXME!!! -// This is the temporary and experimental API -// which should be replaced by runtime roi-based scheduling -/** \addtogroup gapi_compile_args - * @{ - */ -/** - * @brief This structure allows to control the output image region - * which Fluid backend will produce in the graph. - * - * This feature is useful for external tiling and parallelism, but - * will be deprecated in the future releases. - */ -struct GFluidOutputRois -{ - std::vector rois; -}; - -/** - * @brief This structure forces Fluid backend to generate multiple - * parallel output regions in the graph. These regions execute in parallel. - * - * This feature may be deprecated in the future releases. - */ -struct GFluidParallelOutputRois -{ - std::vector parallel_rois; -}; - -/** - * @brief This structure allows to customize the way how Fluid executes - * parallel regions. - * - * For example, user can utilize his own threading runtime via this parameter. - * The `parallel_for` member functor is called by the Fluid runtime with the - * following arguments: - * - * @param size Size of the parallel range to process - * @param f A function which should be called for every integer index - * in this range by the specified parallel_for implementation. - * - * This feature may be deprecated in the future releases. - */ -struct GFluidParallelFor -{ - //this function accepts: - // - size of the "parallel" range as the first argument - // - and a function to be called on the range items, designated by item index - std::function)> parallel_for; -}; -/** @} gapi_compile_args */ - -namespace detail -{ -template<> struct CompileArgTag -{ - static const char* tag() { return "gapi.fluid.outputRois"; } -}; - -template<> struct CompileArgTag -{ - static const char* tag() { return "gapi.fluid.parallelFor"; } -}; - -template<> struct CompileArgTag -{ - static const char* tag() { return "gapi.fluid.parallelOutputRois"; } -}; - -} // namespace detail - -namespace detail -{ -template struct fluid_get_in; -template<> struct fluid_get_in -{ - static const cv::gapi::fluid::View& get(const cv::GArgs &in_args, int idx) - { - return *in_args[idx].unsafe_get(); - } -}; - -template<> struct fluid_get_in -{ - // FIXME: change to return by reference when moved to own::Scalar - static cv::Scalar get(const cv::GArgs &in_args, int idx) - { - return in_args[idx].unsafe_get(); - } -}; - -template struct fluid_get_in> -{ - static const std::vector& get(const cv::GArgs &in_args, int idx) - { - return in_args.at(idx).unsafe_get().rref(); - } -}; - -template struct fluid_get_in> -{ - static const U& get(const cv::GArgs &in_args, int idx) - { - return in_args.at(idx).unsafe_get().rref(); - } -}; - -template struct fluid_get_in -{ - static const T& get(const cv::GArgs &in_args, int idx) - { - return in_args[idx].unsafe_get(); - } -}; - -template -struct scratch_helper; - -template -struct scratch_helper -{ - // Init - template - static void help_init_impl(const cv::GMetaArgs &metas, - const cv::GArgs &in_args, - gapi::fluid::Buffer &scratch_buf, - detail::Seq) - { - Impl::initScratch(get_in_meta(metas, in_args, IIs)..., scratch_buf); - } - - static void help_init(const cv::GMetaArgs &metas, - const cv::GArgs &in_args, - gapi::fluid::Buffer &b) - { - help_init_impl(metas, in_args, b, typename detail::MkSeq::type()); - } - - // Reset - static void help_reset(gapi::fluid::Buffer &b) - { - Impl::resetScratch(b); - } -}; - -template -struct scratch_helper -{ - static void help_init(const cv::GMetaArgs &, - const cv::GArgs &, - gapi::fluid::Buffer &) - { - GAPI_Error("InternalError"); - } - static void help_reset(gapi::fluid::Buffer &) - { - GAPI_Error("InternalError"); - } -}; - -template struct is_gmat_type -{ - static const constexpr bool value = std::is_same::value; -}; - -template -struct get_border_helper; - -template -struct get_border_helper -{ - template - static gapi::fluid::BorderOpt get_border_impl(const GMetaArgs &metas, - const cv::GArgs &in_args, - cv::detail::Seq) - { - return util::make_optional(Impl::getBorder(cv::detail::get_in_meta(metas, in_args, IIs)...)); - } - - static gapi::fluid::BorderOpt help(const GMetaArgs &metas, - const cv::GArgs &in_args) - { - return get_border_impl(metas, in_args, typename detail::MkSeq::type()); - } -}; - -template -struct get_border_helper -{ - static gapi::fluid::BorderOpt help(const cv::GMetaArgs &, - const cv::GArgs &) - { - return {}; - } -}; - -template -struct get_window_helper; - -template -struct get_window_helper -{ - template - static int get_window_impl(const GMetaArgs &metas, - const cv::GArgs &in_args, - cv::detail::Seq) - { - return Impl::getWindow(cv::detail::get_in_meta(metas, in_args, IIs)...); - } - - static int help(const GMetaArgs &metas, const cv::GArgs &in_args) - { - return get_window_impl(metas, in_args, typename detail::MkSeq::type()); - } -}; - -template -struct get_window_helper -{ - static int help(const cv::GMetaArgs &, - const cv::GArgs &) - { - return Impl::Window; - } -}; - -template -struct has_Window -{ -private: - template - static constexpr auto Check(U*) -> typename std::is_same::type; - - template - static constexpr std::false_type Check(...); - - typedef decltype(Check(0)) Result; - -public: - static constexpr bool value = Result::value; -}; - -template -struct callCustomGetBorder; - -template -struct callCustomGetBorder -{ - static constexpr bool value = (Impl::Window != 1); -}; - -template -struct callCustomGetBorder -{ - static constexpr bool value = true; -}; - -template -struct FluidCallHelper; - -template -struct FluidCallHelper, std::tuple, UseScratch> -{ - static_assert(all_satisfy::value, "return type must be GMat"); - static_assert(contains::value, "input must contain at least one GMat"); - - // Execution dispatcher //////////////////////////////////////////////////// - template - static void call_impl(const cv::GArgs &in_args, - const std::vector &out_bufs, - detail::Seq, - detail::Seq) - { - Impl::run(fluid_get_in::get(in_args, IIs)..., *out_bufs[OIs]...); - } - - static void call(const cv::GArgs &in_args, - const std::vector &out_bufs) - { - constexpr int numOuts = (sizeof...(Outs)) + (UseScratch ? 1 : 0); - call_impl(in_args, out_bufs, - typename detail::MkSeq::type(), - typename detail::MkSeq::type()); - } - - // Scratch buffer initialization dispatcher //////////////////////////////// - static void init_scratch(const GMetaArgs &metas, - const cv::GArgs &in_args, - gapi::fluid::Buffer &b) - { - scratch_helper::help_init(metas, in_args, b); - } - - // Scratch buffer reset dispatcher ///////////////////////////////////////// - static void reset_scratch(gapi::fluid::Buffer &scratch_buf) - { - scratch_helper::help_reset(scratch_buf); - } - - static gapi::fluid::BorderOpt getBorder(const GMetaArgs &metas, const cv::GArgs &in_args) - { - constexpr bool hasWindow = has_Window::value; - - // User must provide "init" callback if Window != 1 - // TODO: move to constexpr if when we enable C++17 - return get_border_helper::value, Impl, Ins...>::help(metas, in_args); - } - - static int getWindow(const GMetaArgs &metas, const cv::GArgs &in_args) - { - constexpr bool callCustomGetWindow = !(has_Window::value); - return get_window_helper::help(metas, in_args); - } -}; -} // namespace detail - - -template -class GFluidKernelImpl : public cv::detail::KernelTag -{ - static const int LPI = 1; - static const auto Kind = GFluidKernel::Kind::Filter; - using P = detail::FluidCallHelper; - -public: - using API = K; - - static GFluidKernel kernel() - { - // FIXME: call() and getOutMeta() needs to be renamed so it is clear these - // functions are internal wrappers, not user API - return GFluidKernel(Impl::Kind, Impl::LPI, - UseScratch, - &P::call, &P::init_scratch, &P::reset_scratch, &P::getBorder, &P::getWindow); - } - - static cv::gapi::GBackend backend() { return cv::gapi::fluid::backend(); } -}; - -#define GAPI_FLUID_KERNEL(Name, API, Scratch) struct Name: public cv::GFluidKernelImpl - -} // namespace cv - -#endif // OPENCV_GAPI_GCPUKERNEL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2019 Intel Corporation + + +#ifndef OPENCV_GAPI_FLUID_KERNEL_HPP +#define OPENCV_GAPI_FLUID_KERNEL_HPP + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +// FIXME: namespace scheme for backends? +namespace cv { + +namespace gapi +{ +/** + * @brief This namespace contains G-API Fluid backend functions, structures, and symbols. + */ +namespace fluid +{ + /** + * \addtogroup gapi_std_backends G-API Standard Backends + * @{ + */ + /** + * @brief Get a reference to Fluid backend. + * + * @sa gapi_std_backends + */ + GAPI_EXPORTS cv::gapi::GBackend backend(); + /** @} */ +} // namespace fluid +} // namespace gapi + + +class GAPI_EXPORTS GFluidKernel +{ +public: + enum class Kind + { + Filter, + Resize, + YUV420toRGB //Color conversion of 4:2:0 chroma sub-sampling formats (NV12, I420 ..etc) to RGB + }; + + // This function is a generic "doWork" callback + using F = std::function &)>; + + // This function is a generic "initScratch" callback + using IS = std::function; + + // This function is a generic "resetScratch" callback + using RS = std::function; + + // This function describes kernel metadata inference rule. + using M = std::function; + + // This function is a generic "getBorder" callback (extracts border-related data from kernel's input parameters) + using B = std::function; + + // This function is a generic "getWindow" callback (extracts window-related data from kernel's input parameters) + using GW = std::function; + + // FIXME: move implementations out of header file + GFluidKernel() {} + GFluidKernel(Kind k, int l, bool scratch, const F& f, const IS &is, const RS &rs, const B& b, const GW& win) + : m_kind(k) + , m_lpi(l) + , m_scratch(scratch) + , m_f(f) + , m_is(is) + , m_rs(rs) + , m_b(b) + , m_gw(win) {} + + Kind m_kind; + const int m_lpi = -1; + const bool m_scratch = false; + + const F m_f; + const IS m_is; + const RS m_rs; + const B m_b; + const GW m_gw; +}; + +// FIXME!!! +// This is the temporary and experimental API +// which should be replaced by runtime roi-based scheduling +/** \addtogroup gapi_compile_args + * @{ + */ +/** + * @brief This structure allows to control the output image region + * which Fluid backend will produce in the graph. + * + * This feature is useful for external tiling and parallelism, but + * will be deprecated in the future releases. + */ +struct GFluidOutputRois +{ + std::vector rois; +}; + +/** + * @brief This structure forces Fluid backend to generate multiple + * parallel output regions in the graph. These regions execute in parallel. + * + * This feature may be deprecated in the future releases. + */ +struct GFluidParallelOutputRois +{ + std::vector parallel_rois; +}; + +/** + * @brief This structure allows to customize the way how Fluid executes + * parallel regions. + * + * For example, user can utilize his own threading runtime via this parameter. + * The `parallel_for` member functor is called by the Fluid runtime with the + * following arguments: + * + * @param size Size of the parallel range to process + * @param f A function which should be called for every integer index + * in this range by the specified parallel_for implementation. + * + * This feature may be deprecated in the future releases. + */ +struct GFluidParallelFor +{ + //this function accepts: + // - size of the "parallel" range as the first argument + // - and a function to be called on the range items, designated by item index + std::function)> parallel_for; +}; +/** @} gapi_compile_args */ + +namespace detail +{ +template<> struct CompileArgTag +{ + static const char* tag() { return "gapi.fluid.outputRois"; } +}; + +template<> struct CompileArgTag +{ + static const char* tag() { return "gapi.fluid.parallelFor"; } +}; + +template<> struct CompileArgTag +{ + static const char* tag() { return "gapi.fluid.parallelOutputRois"; } +}; + +} // namespace detail + +namespace detail +{ +template struct fluid_get_in; +template<> struct fluid_get_in +{ + static const cv::gapi::fluid::View& get(const cv::GArgs &in_args, int idx) + { + return *in_args[idx].unsafe_get(); + } +}; + +template<> struct fluid_get_in +{ + // FIXME: change to return by reference when moved to own::Scalar + static cv::Scalar get(const cv::GArgs &in_args, int idx) + { + return in_args[idx].unsafe_get(); + } +}; + +template struct fluid_get_in> +{ + static const std::vector& get(const cv::GArgs &in_args, int idx) + { + return in_args.at(idx).unsafe_get().rref(); + } +}; + +template struct fluid_get_in> +{ + static const U& get(const cv::GArgs &in_args, int idx) + { + return in_args.at(idx).unsafe_get().rref(); + } +}; + +template struct fluid_get_in +{ + static const T& get(const cv::GArgs &in_args, int idx) + { + return in_args[idx].unsafe_get(); + } +}; + +template +struct scratch_helper; + +template +struct scratch_helper +{ + // Init + template + static void help_init_impl(const cv::GMetaArgs &metas, + const cv::GArgs &in_args, + gapi::fluid::Buffer &scratch_buf, + detail::Seq) + { + Impl::initScratch(get_in_meta(metas, in_args, IIs)..., scratch_buf); + } + + static void help_init(const cv::GMetaArgs &metas, + const cv::GArgs &in_args, + gapi::fluid::Buffer &b) + { + help_init_impl(metas, in_args, b, typename detail::MkSeq::type()); + } + + // Reset + static void help_reset(gapi::fluid::Buffer &b) + { + Impl::resetScratch(b); + } +}; + +template +struct scratch_helper +{ + static void help_init(const cv::GMetaArgs &, + const cv::GArgs &, + gapi::fluid::Buffer &) + { + GAPI_Error("InternalError"); + } + static void help_reset(gapi::fluid::Buffer &) + { + GAPI_Error("InternalError"); + } +}; + +template struct is_gmat_type +{ + static const constexpr bool value = std::is_same::value; +}; + +template +struct get_border_helper; + +template +struct get_border_helper +{ + template + static gapi::fluid::BorderOpt get_border_impl(const GMetaArgs &metas, + const cv::GArgs &in_args, + cv::detail::Seq) + { + return util::make_optional(Impl::getBorder(cv::detail::get_in_meta(metas, in_args, IIs)...)); + } + + static gapi::fluid::BorderOpt help(const GMetaArgs &metas, + const cv::GArgs &in_args) + { + return get_border_impl(metas, in_args, typename detail::MkSeq::type()); + } +}; + +template +struct get_border_helper +{ + static gapi::fluid::BorderOpt help(const cv::GMetaArgs &, + const cv::GArgs &) + { + return {}; + } +}; + +template +struct get_window_helper; + +template +struct get_window_helper +{ + template + static int get_window_impl(const GMetaArgs &metas, + const cv::GArgs &in_args, + cv::detail::Seq) + { + return Impl::getWindow(cv::detail::get_in_meta(metas, in_args, IIs)...); + } + + static int help(const GMetaArgs &metas, const cv::GArgs &in_args) + { + return get_window_impl(metas, in_args, typename detail::MkSeq::type()); + } +}; + +template +struct get_window_helper +{ + static int help(const cv::GMetaArgs &, + const cv::GArgs &) + { + return Impl::Window; + } +}; + +template +struct has_Window +{ +private: + template + static constexpr auto Check(U*) -> typename std::is_same::type; + + template + static constexpr std::false_type Check(...); + + typedef decltype(Check(0)) Result; + +public: + static constexpr bool value = Result::value; +}; + +template +struct callCustomGetBorder; + +template +struct callCustomGetBorder +{ + static constexpr bool value = (Impl::Window != 1); +}; + +template +struct callCustomGetBorder +{ + static constexpr bool value = true; +}; + +template +struct FluidCallHelper; + +template +struct FluidCallHelper, std::tuple, UseScratch> +{ + static_assert(all_satisfy::value, "return type must be GMat"); + static_assert(contains::value, "input must contain at least one GMat"); + + // Execution dispatcher //////////////////////////////////////////////////// + template + static void call_impl(const cv::GArgs &in_args, + const std::vector &out_bufs, + detail::Seq, + detail::Seq) + { + Impl::run(fluid_get_in::get(in_args, IIs)..., *out_bufs[OIs]...); + } + + static void call(const cv::GArgs &in_args, + const std::vector &out_bufs) + { + constexpr int numOuts = (sizeof...(Outs)) + (UseScratch ? 1 : 0); + call_impl(in_args, out_bufs, + typename detail::MkSeq::type(), + typename detail::MkSeq::type()); + } + + // Scratch buffer initialization dispatcher //////////////////////////////// + static void init_scratch(const GMetaArgs &metas, + const cv::GArgs &in_args, + gapi::fluid::Buffer &b) + { + scratch_helper::help_init(metas, in_args, b); + } + + // Scratch buffer reset dispatcher ///////////////////////////////////////// + static void reset_scratch(gapi::fluid::Buffer &scratch_buf) + { + scratch_helper::help_reset(scratch_buf); + } + + static gapi::fluid::BorderOpt getBorder(const GMetaArgs &metas, const cv::GArgs &in_args) + { + constexpr bool hasWindow = has_Window::value; + + // User must provide "init" callback if Window != 1 + // TODO: move to constexpr if when we enable C++17 + return get_border_helper::value, Impl, Ins...>::help(metas, in_args); + } + + static int getWindow(const GMetaArgs &metas, const cv::GArgs &in_args) + { + constexpr bool callCustomGetWindow = !(has_Window::value); + return get_window_helper::help(metas, in_args); + } +}; +} // namespace detail + + +template +class GFluidKernelImpl : public cv::detail::KernelTag +{ + static const int LPI = 1; + static const auto Kind = GFluidKernel::Kind::Filter; + using P = detail::FluidCallHelper; + +public: + using API = K; + + static GFluidKernel kernel() + { + // FIXME: call() and getOutMeta() needs to be renamed so it is clear these + // functions are internal wrappers, not user API + return GFluidKernel(Impl::Kind, Impl::LPI, + UseScratch, + &P::call, &P::init_scratch, &P::reset_scratch, &P::getBorder, &P::getWindow); + } + + static cv::gapi::GBackend backend() { return cv::gapi::fluid::backend(); } +}; + +#define GAPI_FLUID_KERNEL(Name, API, Scratch) struct Name: public cv::GFluidKernelImpl + +} // namespace cv + +#endif // OPENCV_GAPI_GCPUKERNEL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/imgproc.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/imgproc.hpp index a4e8ac0f99..31fc2446dc 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/imgproc.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/imgproc.hpp @@ -1,20 +1,20 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_FLUID_IMGPROC_HPP -#define OPENCV_GAPI_FLUID_IMGPROC_HPP - -#include // GKernelPackage -#include // GAPI_EXPORTS - -namespace cv { namespace gapi { namespace imgproc { namespace fluid { - -GAPI_EXPORTS_W GKernelPackage kernels(); - -}}}} - -#endif // OPENCV_GAPI_FLUID_IMGPROC_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_FLUID_IMGPROC_HPP +#define OPENCV_GAPI_FLUID_IMGPROC_HPP + +#include // GKernelPackage +#include // GAPI_EXPORTS + +namespace cv { namespace gapi { namespace imgproc { namespace fluid { + +GAPI_EXPORTS_W GKernelPackage kernels(); + +}}}} + +#endif // OPENCV_GAPI_FLUID_IMGPROC_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/garg.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/garg.hpp index 2a8315f9d8..3c06d851f0 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/garg.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/garg.hpp @@ -1,311 +1,311 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2021 Intel Corporation - - -#ifndef OPENCV_GAPI_GARG_HPP -#define OPENCV_GAPI_GARG_HPP - -#include -#include -#include - -#include -#include -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace cv { - -class GArg; - -namespace detail { - template - using is_garg = std::is_same::type>; -} - -// Parameter holder class for a node -// Depending on platform capabilities, can either support arbitrary types -// (as `boost::any`) or a limited number of types (as `boot::variant`). -// FIXME: put into "details" as a user shouldn't use it in his code -class GAPI_EXPORTS GArg -{ -public: - GArg() {} - - template::value, int>::type = 0> - explicit GArg(const T &t) - : kind(detail::GTypeTraits::kind) - , opaque_kind(detail::GOpaqueTraits::kind) - , value(detail::wrap_gapi_helper::wrap(t)) - { - } - - template::value, int>::type = 0> - explicit GArg(T &&t) - : kind(detail::GTypeTraits::type>::kind) - , opaque_kind(detail::GOpaqueTraits::type>::kind) - , value(detail::wrap_gapi_helper::wrap(t)) - { - } - - template inline T& get() - { - return util::any_cast::type>(value); - } - - template inline const T& get() const - { - return util::any_cast::type>(value); - } - - template inline T& unsafe_get() - { - return util::unsafe_any_cast::type>(value); - } - - template inline const T& unsafe_get() const - { - return util::unsafe_any_cast::type>(value); - } - - detail::ArgKind kind = detail::ArgKind::OPAQUE_VAL; - detail::OpaqueKind opaque_kind = detail::OpaqueKind::CV_UNKNOWN; - -protected: - util::any value; -}; - -using GArgs = std::vector; - -// FIXME: Express as M::type -// FIXME: Move to a separate file! -using GRunArgBase = util::variant< -#if !defined(GAPI_STANDALONE) - cv::UMat, -#endif // !defined(GAPI_STANDALONE) - cv::RMat, - cv::gapi::wip::IStreamSource::Ptr, - cv::Mat, - cv::Scalar, - cv::detail::VectorRef, - cv::detail::OpaqueRef, - cv::MediaFrame - >; - -namespace detail { -template -struct in_variant; - -template -struct in_variant > - : std::integral_constant::value > { -}; -} // namespace detail - -struct GAPI_EXPORTS GRunArg: public GRunArgBase -{ - // Metadata information here - using Meta = std::unordered_map; - Meta meta; - - // Mimic the old GRunArg semantics here, old of the times when - // GRunArg was an alias to variant<> - GRunArg(); - GRunArg(const cv::GRunArg &arg); - GRunArg(cv::GRunArg &&arg); - - GRunArg& operator= (const GRunArg &arg); - GRunArg& operator= (GRunArg &&arg); - - template - GRunArg(const T &t, - const Meta &m = Meta{}, - typename std::enable_if< detail::in_variant::value, int>::type = 0) - : GRunArgBase(t) - , meta(m) - { - } - template - GRunArg(T &&t, - const Meta &m = Meta{}, - typename std::enable_if< detail::in_variant::value, int>::type = 0) - : GRunArgBase(std::move(t)) - , meta(m) - { - } - template auto operator= (const T &t) - -> typename std::enable_if< detail::in_variant::value, cv::GRunArg>::type& - { - GRunArgBase::operator=(t); - return *this; - } - template auto operator= (T&& t) - -> typename std::enable_if< detail::in_variant::value, cv::GRunArg>::type& - { - GRunArgBase::operator=(std::move(t)); - return *this; - } -}; -using GRunArgs = std::vector; - -// TODO: Think about the addition operator -/** - * @brief This operator allows to complement the input vector at runtime. - * - * It's an ordinary overload of addition assignment operator. - * - * Example of usage: - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/dynamic_graph_snippets.cpp GRunArgs usage - * - */ -inline GRunArgs& operator += (GRunArgs &lhs, const GRunArgs &rhs) -{ - lhs.reserve(lhs.size() + rhs.size()); - lhs.insert(lhs.end(), rhs.begin(), rhs.end()); - return lhs; -} - -namespace gapi -{ -namespace wip -{ -/** - * @brief This aggregate type represents all types which G-API can - * handle (via variant). - * - * It only exists to overcome C++ language limitations (where a - * `using`-defined class can't be forward-declared). - */ -struct GAPI_EXPORTS Data: public GRunArg -{ - using GRunArg::GRunArg; - template - Data& operator= (const T& t) { GRunArg::operator=(t); return *this; } - template - Data& operator= (T&& t) { GRunArg::operator=(std::move(t)); return *this; } -}; -} // namespace wip -} // namespace gapi - -using GRunArgP = util::variant< -#if !defined(GAPI_STANDALONE) - cv::UMat*, -#endif // !defined(GAPI_STANDALONE) - cv::Mat*, - cv::RMat*, - cv::Scalar*, - cv::MediaFrame*, - cv::detail::VectorRef, - cv::detail::OpaqueRef - >; -using GRunArgsP = std::vector; - -// TODO: Think about the addition operator -/** - * @brief This operator allows to complement the output vector at runtime. - * - * It's an ordinary overload of addition assignment operator. - * - * Example of usage: - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/dynamic_graph_snippets.cpp GRunArgsP usage - * - */ -inline GRunArgsP& operator += (GRunArgsP &lhs, const GRunArgsP &rhs) -{ - lhs.reserve(lhs.size() + rhs.size()); - lhs.insert(lhs.end(), rhs.begin(), rhs.end()); - return lhs; -} - -namespace gapi -{ -/** - * \addtogroup gapi_serialization - * @{ - * - * @brief G-API functions and classes for serialization and deserialization. - */ - -/** @brief Wraps deserialized output GRunArgs to GRunArgsP which can be used by GCompiled. - * - * Since it's impossible to get modifiable output arguments from deserialization - * it needs to be wrapped by this function. - * - * Example of usage: - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp bind after deserialization - * - * @param out_args deserialized GRunArgs. - * @return the same GRunArgs wrapped in GRunArgsP. - * @see deserialize - */ -GAPI_EXPORTS cv::GRunArgsP bind(cv::GRunArgs &out_args); - -/** @brief Wraps output GRunArgsP available during graph execution to GRunArgs which can be serialized. - * - * GRunArgsP is pointer-to-value, so to be serialized they need to be binded to real values - * which this function does. - * - * Example of usage: - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp bind before serialization - * - * @param out output GRunArgsP available during graph execution. - * @return the same GRunArgsP wrapped in serializable GRunArgs. - * @see serialize - */ -GAPI_EXPORTS cv::GRunArg bind(cv::GRunArgP &out); // FIXME: think more about it -/** @} */ -} - -template inline GRunArgs gin(const Ts&... args) -{ - return GRunArgs{ GRunArg(detail::wrap_host_helper::wrap_in(args))... }; -} - -template inline GRunArgsP gout(Ts&... args) -{ - return GRunArgsP{ GRunArgP(detail::wrap_host_helper::wrap_out(args))... }; -} - -struct GTypeInfo; -using GTypesInfo = std::vector; - -// FIXME: Needed for python bridge, must be moved to more appropriate header -namespace detail { -struct ExtractArgsCallback -{ - cv::GRunArgs operator()(const cv::GTypesInfo& info) const { return c(info); } - using CallBackT = std::function; - CallBackT c; -}; - -struct ExtractMetaCallback -{ - cv::GMetaArgs operator()(const cv::GTypesInfo& info) const { return c(info); } - using CallBackT = std::function; - CallBackT c; -}; - -void constructGraphOutputs(const cv::GTypesInfo &out_info, - cv::GRunArgs &args, - cv::GRunArgsP &outs); -} // namespace detail - -} // namespace cv - -#endif // OPENCV_GAPI_GARG_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2021 Intel Corporation + + +#ifndef OPENCV_GAPI_GARG_HPP +#define OPENCV_GAPI_GARG_HPP + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace cv { + +class GArg; + +namespace detail { + template + using is_garg = std::is_same::type>; +} + +// Parameter holder class for a node +// Depending on platform capabilities, can either support arbitrary types +// (as `boost::any`) or a limited number of types (as `boot::variant`). +// FIXME: put into "details" as a user shouldn't use it in his code +class GAPI_EXPORTS GArg +{ +public: + GArg() {} + + template::value, int>::type = 0> + explicit GArg(const T &t) + : kind(detail::GTypeTraits::kind) + , opaque_kind(detail::GOpaqueTraits::kind) + , value(detail::wrap_gapi_helper::wrap(t)) + { + } + + template::value, int>::type = 0> + explicit GArg(T &&t) + : kind(detail::GTypeTraits::type>::kind) + , opaque_kind(detail::GOpaqueTraits::type>::kind) + , value(detail::wrap_gapi_helper::wrap(t)) + { + } + + template inline T& get() + { + return util::any_cast::type>(value); + } + + template inline const T& get() const + { + return util::any_cast::type>(value); + } + + template inline T& unsafe_get() + { + return util::unsafe_any_cast::type>(value); + } + + template inline const T& unsafe_get() const + { + return util::unsafe_any_cast::type>(value); + } + + detail::ArgKind kind = detail::ArgKind::OPAQUE_VAL; + detail::OpaqueKind opaque_kind = detail::OpaqueKind::CV_UNKNOWN; + +protected: + util::any value; +}; + +using GArgs = std::vector; + +// FIXME: Express as M::type +// FIXME: Move to a separate file! +using GRunArgBase = util::variant< +#if !defined(GAPI_STANDALONE) + cv::UMat, +#endif // !defined(GAPI_STANDALONE) + cv::RMat, + cv::gapi::wip::IStreamSource::Ptr, + cv::Mat, + cv::Scalar, + cv::detail::VectorRef, + cv::detail::OpaqueRef, + cv::MediaFrame + >; + +namespace detail { +template +struct in_variant; + +template +struct in_variant > + : std::integral_constant::value > { +}; +} // namespace detail + +struct GAPI_EXPORTS GRunArg: public GRunArgBase +{ + // Metadata information here + using Meta = std::unordered_map; + Meta meta; + + // Mimic the old GRunArg semantics here, old of the times when + // GRunArg was an alias to variant<> + GRunArg(); + GRunArg(const cv::GRunArg &arg); + GRunArg(cv::GRunArg &&arg); + + GRunArg& operator= (const GRunArg &arg); + GRunArg& operator= (GRunArg &&arg); + + template + GRunArg(const T &t, + const Meta &m = Meta{}, + typename std::enable_if< detail::in_variant::value, int>::type = 0) + : GRunArgBase(t) + , meta(m) + { + } + template + GRunArg(T &&t, + const Meta &m = Meta{}, + typename std::enable_if< detail::in_variant::value, int>::type = 0) + : GRunArgBase(std::move(t)) + , meta(m) + { + } + template auto operator= (const T &t) + -> typename std::enable_if< detail::in_variant::value, cv::GRunArg>::type& + { + GRunArgBase::operator=(t); + return *this; + } + template auto operator= (T&& t) + -> typename std::enable_if< detail::in_variant::value, cv::GRunArg>::type& + { + GRunArgBase::operator=(std::move(t)); + return *this; + } +}; +using GRunArgs = std::vector; + +// TODO: Think about the addition operator +/** + * @brief This operator allows to complement the input vector at runtime. + * + * It's an ordinary overload of addition assignment operator. + * + * Example of usage: + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/dynamic_graph_snippets.cpp GRunArgs usage + * + */ +inline GRunArgs& operator += (GRunArgs &lhs, const GRunArgs &rhs) +{ + lhs.reserve(lhs.size() + rhs.size()); + lhs.insert(lhs.end(), rhs.begin(), rhs.end()); + return lhs; +} + +namespace gapi +{ +namespace wip +{ +/** + * @brief This aggregate type represents all types which G-API can + * handle (via variant). + * + * It only exists to overcome C++ language limitations (where a + * `using`-defined class can't be forward-declared). + */ +struct GAPI_EXPORTS Data: public GRunArg +{ + using GRunArg::GRunArg; + template + Data& operator= (const T& t) { GRunArg::operator=(t); return *this; } + template + Data& operator= (T&& t) { GRunArg::operator=(std::move(t)); return *this; } +}; +} // namespace wip +} // namespace gapi + +using GRunArgP = util::variant< +#if !defined(GAPI_STANDALONE) + cv::UMat*, +#endif // !defined(GAPI_STANDALONE) + cv::Mat*, + cv::RMat*, + cv::Scalar*, + cv::MediaFrame*, + cv::detail::VectorRef, + cv::detail::OpaqueRef + >; +using GRunArgsP = std::vector; + +// TODO: Think about the addition operator +/** + * @brief This operator allows to complement the output vector at runtime. + * + * It's an ordinary overload of addition assignment operator. + * + * Example of usage: + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/dynamic_graph_snippets.cpp GRunArgsP usage + * + */ +inline GRunArgsP& operator += (GRunArgsP &lhs, const GRunArgsP &rhs) +{ + lhs.reserve(lhs.size() + rhs.size()); + lhs.insert(lhs.end(), rhs.begin(), rhs.end()); + return lhs; +} + +namespace gapi +{ +/** + * \addtogroup gapi_serialization + * @{ + * + * @brief G-API functions and classes for serialization and deserialization. + */ + +/** @brief Wraps deserialized output GRunArgs to GRunArgsP which can be used by GCompiled. + * + * Since it's impossible to get modifiable output arguments from deserialization + * it needs to be wrapped by this function. + * + * Example of usage: + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp bind after deserialization + * + * @param out_args deserialized GRunArgs. + * @return the same GRunArgs wrapped in GRunArgsP. + * @see deserialize + */ +GAPI_EXPORTS cv::GRunArgsP bind(cv::GRunArgs &out_args); + +/** @brief Wraps output GRunArgsP available during graph execution to GRunArgs which can be serialized. + * + * GRunArgsP is pointer-to-value, so to be serialized they need to be binded to real values + * which this function does. + * + * Example of usage: + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp bind before serialization + * + * @param out output GRunArgsP available during graph execution. + * @return the same GRunArgsP wrapped in serializable GRunArgs. + * @see serialize + */ +GAPI_EXPORTS cv::GRunArg bind(cv::GRunArgP &out); // FIXME: think more about it +/** @} */ +} + +template inline GRunArgs gin(const Ts&... args) +{ + return GRunArgs{ GRunArg(detail::wrap_host_helper::wrap_in(args))... }; +} + +template inline GRunArgsP gout(Ts&... args) +{ + return GRunArgsP{ GRunArgP(detail::wrap_host_helper::wrap_out(args))... }; +} + +struct GTypeInfo; +using GTypesInfo = std::vector; + +// FIXME: Needed for python bridge, must be moved to more appropriate header +namespace detail { +struct ExtractArgsCallback +{ + cv::GRunArgs operator()(const cv::GTypesInfo& info) const { return c(info); } + using CallBackT = std::function; + CallBackT c; +}; + +struct ExtractMetaCallback +{ + cv::GMetaArgs operator()(const cv::GTypesInfo& info) const { return c(info); } + using CallBackT = std::function; + CallBackT c; +}; + +void constructGraphOutputs(const cv::GTypesInfo &out_info, + cv::GRunArgs &args, + cv::GRunArgsP &outs); +} // namespace detail + +} // namespace cv + +#endif // OPENCV_GAPI_GARG_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/garray.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/garray.hpp index a2951993f2..f04ca521d8 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/garray.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/garray.hpp @@ -1,440 +1,440 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2020 Intel Corporation - - -#ifndef OPENCV_GAPI_GARRAY_HPP -#define OPENCV_GAPI_GARRAY_HPP - -#include -#include -#include -#include - -#include -#include - -#include -#include -#include - -#include // flatten_g only! -#include // flatten_g only! - -namespace cv -{ -// Forward declaration; GNode and GOrigin are an internal -// (user-inaccessible) classes. -class GNode; -struct GOrigin; -template class GArray; - -/** - * \addtogroup gapi_meta_args - * @{ - */ -struct GAPI_EXPORTS_W_SIMPLE GArrayDesc -{ - // FIXME: Body - // FIXME: Also implement proper operator== then - bool operator== (const GArrayDesc&) const { return true; } -}; -template GArrayDesc descr_of(const std::vector &) { return {};} -GAPI_EXPORTS_W inline GArrayDesc empty_array_desc() {return {}; } -/** @} */ - -std::ostream& operator<<(std::ostream& os, const cv::GArrayDesc &desc); - -namespace detail -{ - // ConstructVec is a callback which stores information about T and is used by - // G-API runtime to construct arrays in host memory (T remains opaque for G-API). - // ConstructVec is carried into G-API internals by GArrayU. - // Currently it is suitable for Host (CPU) plugins only, real offload may require - // more information for manual memory allocation on-device. - class VectorRef; - using ConstructVec = std::function; - - // This is the base struct for GArrayU type holder - struct TypeHintBase{virtual ~TypeHintBase() = default;}; - - // This class holds type of initial GArray to be checked from GArrayU - template - struct TypeHint final : public TypeHintBase{}; - - // This class strips type information from GArray and makes it usable - // in the G-API graph compiler (expression unrolling, graph generation, etc). - // Part of GProtoArg. - class GAPI_EXPORTS GArrayU - { - public: - GArrayU(const GNode &n, std::size_t out); // Operation result constructor - - template - bool holds() const; // Check if was created from GArray - - GOrigin& priv(); // Internal use only - const GOrigin& priv() const; // Internal use only - - protected: - GArrayU(); // Default constructor - GArrayU(const detail::VectorRef& vref); // Constant value constructor - template friend class cv::GArray; // (available to GArray only) - - void setConstructFcn(ConstructVec &&cv); // Store T-aware constructor - - template - void specifyType(); // Store type of initial GArray - - template - void storeKind(); - - void setKind(cv::detail::OpaqueKind); - - std::shared_ptr m_priv; - std::shared_ptr m_hint; - }; - - template - bool GArrayU::holds() const{ - GAPI_Assert(m_hint != nullptr); - using U = typename std::decay::type; - return dynamic_cast*>(m_hint.get()) != nullptr; - } - - template - void GArrayU::specifyType(){ - m_hint.reset(new TypeHint::type>); - } - - template - void GArrayU::storeKind(){ - setKind(cv::detail::GOpaqueTraits::kind); - } - - // This class represents a typed STL vector reference. - // Depending on origins, this reference may be either "just a" reference to - // an object created externally, OR actually own the underlying object - // (be value holder). - class BasicVectorRef - { - public: - // These fields are set by the derived class(es) - std::size_t m_elemSize = 0ul; - cv::GArrayDesc m_desc; - virtual ~BasicVectorRef() {} - - virtual void mov(BasicVectorRef &ref) = 0; - virtual const void* ptr() const = 0; - virtual std::size_t size() const = 0; - }; - - template class VectorRefT final: public BasicVectorRef - { - using empty_t = util::monostate; - using ro_ext_t = const std::vector *; - using rw_ext_t = std::vector *; - using rw_own_t = std::vector ; - util::variant m_ref; - - inline bool isEmpty() const { return util::holds_alternative(m_ref); } - inline bool isROExt() const { return util::holds_alternative(m_ref); } - inline bool isRWExt() const { return util::holds_alternative(m_ref); } - inline bool isRWOwn() const { return util::holds_alternative(m_ref); } - - void init(const std::vector* vec = nullptr) - { - m_elemSize = sizeof(T); - if (vec) m_desc = cv::descr_of(*vec); - } - - public: - VectorRefT() { init(); } - virtual ~VectorRefT() {} - - explicit VectorRefT(const std::vector& vec) : m_ref(&vec) { init(&vec); } - explicit VectorRefT(std::vector& vec) : m_ref(&vec) { init(&vec); } - explicit VectorRefT(std::vector&& vec) : m_ref(std::move(vec)) { init(&vec); } - - // Reset a VectorRefT. Called only for objects instantiated - // internally in G-API (e.g. temporary GArray's within a - // computation). Reset here means both initialization - // (creating an object) and reset (discarding its existing - // content before the next execution). Must never be called - // for external VectorRefTs. - void reset() - { - if (isEmpty()) - { - std::vector empty_vector; - m_desc = cv::descr_of(empty_vector); - m_ref = std::move(empty_vector); - GAPI_Assert(isRWOwn()); - } - else if (isRWOwn()) - { - util::get(m_ref).clear(); - } - else GAPI_Error("InternalError"); // shouldn't be called in *EXT modes - } - - // Obtain a WRITE reference to underlying object - // Used by CPU kernel API wrappers when a kernel execution frame - // is created - std::vector& wref() - { - GAPI_Assert(isRWExt() || isRWOwn()); - if (isRWExt()) return *util::get(m_ref); - if (isRWOwn()) return util::get(m_ref); - util::throw_error(std::logic_error("Impossible happened")); - } - - // Obtain a READ reference to underlying object - // Used by CPU kernel API wrappers when a kernel execution frame - // is created - const std::vector& rref() const - { - // ANY vector can be accessed for reading, even if it declared for - // output. Example -- a GComputation from [in] to [out1,out2] - // where [out2] is a result of operation applied to [out1]: - // - // GComputation boundary - // . . . . . . . - // . . - // [in] ----> foo() ----> [out1] - // . . : - // . . . .:. . . - // . V . - // . bar() ---> [out2] - // . . . . . . . . . . . . - // - if (isROExt()) return *util::get(m_ref); - if (isRWExt()) return *util::get(m_ref); - if (isRWOwn()) return util::get(m_ref); - util::throw_error(std::logic_error("Impossible happened")); - } - - virtual void mov(BasicVectorRef &v) override { - VectorRefT *tv = dynamic_cast*>(&v); - GAPI_Assert(tv != nullptr); - wref() = std::move(tv->wref()); - } - - virtual const void* ptr() const override { return &rref(); } - virtual std::size_t size() const override { return rref().size(); } - }; - - // This class strips type information from VectorRefT<> and makes it usable - // in the G-API executables (carrying run-time data/information to kernels). - // Part of GRunArg. - // Its methods are typed proxies to VectorRefT. - // VectorRef maintains "reference" semantics so two copies of VectoRef refer - // to the same underlying object. - // FIXME: Put a good explanation on why cv::OutputArray doesn't fit this role - class VectorRef - { - std::shared_ptr m_ref; - cv::detail::OpaqueKind m_kind = cv::detail::OpaqueKind::CV_UNKNOWN; - - template inline void check() const - { - GAPI_DbgAssert(dynamic_cast*>(m_ref.get()) != nullptr); - GAPI_Assert(sizeof(T) == m_ref->m_elemSize); - } - - public: - VectorRef() = default; - template explicit VectorRef(const std::vector& vec) - : m_ref(new VectorRefT(vec)) - , m_kind(GOpaqueTraits::kind) - {} - template explicit VectorRef(std::vector& vec) - : m_ref(new VectorRefT(vec)) - , m_kind(GOpaqueTraits::kind) - {} - template explicit VectorRef(std::vector&& vec) - : m_ref(new VectorRefT(std::move(vec))) - , m_kind(GOpaqueTraits::kind) - {} - - cv::detail::OpaqueKind getKind() const - { - return m_kind; - } - - template void reset() - { - if (!m_ref) m_ref.reset(new VectorRefT()); - check(); - storeKind(); - static_cast&>(*m_ref).reset(); - } - - template - void storeKind() - { - m_kind = cv::detail::GOpaqueTraits::kind; - } - - template std::vector& wref() - { - check(); - return static_cast&>(*m_ref).wref(); - } - - template const std::vector& rref() const - { - check(); - return static_cast&>(*m_ref).rref(); - } - - // Check if was created for/from std::vector - template bool holds() const - { - if (!m_ref) return false; - using U = typename std::decay::type; - return dynamic_cast*>(m_ref.get()) != nullptr; - } - - void mov(VectorRef &v) - { - m_ref->mov(*v.m_ref); - } - - cv::GArrayDesc descr_of() const - { - return m_ref->m_desc; - } - - std::size_t size() const - { - return m_ref->size(); - } - - // May be used to uniquely identify this object internally - const void *ptr() const { return m_ref->ptr(); } - }; - - // Helper (FIXME: work-around?) - // stripping G types to their host types - // like cv::GArray would still map to std::vector - // but not to std::vector -#if defined(GAPI_STANDALONE) -# define FLATTEN_NS cv::gapi::own -#else -# define FLATTEN_NS cv -#endif - template struct flatten_g; - template<> struct flatten_g { using type = FLATTEN_NS::Mat; }; - template<> struct flatten_g { using type = FLATTEN_NS::Scalar; }; - template struct flatten_g> { using type = std::vector; }; - template struct flatten_g { using type = T; }; -#undef FLATTEN_NS - // FIXME: the above mainly duplicates "ProtoToParam" thing from gtyped.hpp - // but I decided not to include gtyped here - probably worth moving that stuff - // to some common place? (DM) -} // namespace detail - -/** \addtogroup gapi_data_objects - * @{ - */ -/** - * @brief `cv::GArray` template class represents a list of objects - * of class `T` in the graph. - * - * `cv::GArray` describes a functional relationship between - * operations consuming and producing arrays of objects of class - * `T`. The primary purpose of `cv::GArray` is to represent a - * dynamic list of objects -- where the size of the list is not known - * at the graph construction or compile time. Examples include: corner - * and feature detectors (`cv::GArray`), object detection - * and tracking results (`cv::GArray`). Programmers can use - * their own types with `cv::GArray` in the custom operations. - * - * Similar to `cv::GScalar`, `cv::GArray` may be value-initialized - * -- in this case a graph-constant value is associated with the object. - * - * `GArray` is a virtual counterpart of `std::vector`, which is - * usually used to represent the `GArray` data in G-API during the - * execution. - * - * @sa `cv::GOpaque` - */ -template class GArray -{ -public: - // Host type (or Flat type) - the type this GArray is actually - // specified to. - /// @private - using HT = typename detail::flatten_g::type>::type; - - /** - * @brief Constructs a value-initialized `cv::GArray` - * - * `cv::GArray` objects may have their values - * be associated at graph construction time. It is useful when - * some operation has a `cv::GArray` input which doesn't change during - * the program execution, and is set only once. In this case, - * there is no need to declare such `cv::GArray` as a graph input. - * - * @note The value of `cv::GArray` may be overwritten by assigning some - * other `cv::GArray` to the object using `operator=` -- on the - * assignment, the old association or value is discarded. - * - * @param v a std::vector to associate with this - * `cv::GArray` object. Vector data is copied into the - * `cv::GArray` (no reference to the passed data is held). - */ - explicit GArray(const std::vector& v) // Constant value constructor - : m_ref(detail::GArrayU(detail::VectorRef(v))) { putDetails(); } - - /** - * @overload - * @brief Constructs a value-initialized `cv::GArray` - * - * @param v a std::vector to associate with this - * `cv::GArray` object. Vector data is moved into the `cv::GArray`. - */ - explicit GArray(std::vector&& v) // Move-constructor - : m_ref(detail::GArrayU(detail::VectorRef(std::move(v)))) { putDetails(); } - - /** - * @brief Constructs an empty `cv::GArray` - * - * Normally, empty G-API data objects denote a starting point of - * the graph. When an empty `cv::GArray` is assigned to a result - * of some operation, it obtains a functional link to this - * operation (and is not empty anymore). - */ - GArray() { putDetails(); } // Empty constructor - - /// @private - explicit GArray(detail::GArrayU &&ref) // GArrayU-based constructor - : m_ref(ref) { putDetails(); } // (used by GCall, not for users) - - /// @private - detail::GArrayU strip() const { - return m_ref; - } - /// @private - static void VCtor(detail::VectorRef& vref) { - vref.reset(); - } - -private: - void putDetails() { - m_ref.setConstructFcn(&VCtor); - m_ref.specifyType(); // FIXME: to unify those 2 to avoid excessive dynamic_cast - m_ref.storeKind(); // - } - - detail::GArrayU m_ref; -}; - -/** @} */ - -} // namespace cv - -#endif // OPENCV_GAPI_GARRAY_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2020 Intel Corporation + + +#ifndef OPENCV_GAPI_GARRAY_HPP +#define OPENCV_GAPI_GARRAY_HPP + +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +#include // flatten_g only! +#include // flatten_g only! + +namespace cv +{ +// Forward declaration; GNode and GOrigin are an internal +// (user-inaccessible) classes. +class GNode; +struct GOrigin; +template class GArray; + +/** + * \addtogroup gapi_meta_args + * @{ + */ +struct GAPI_EXPORTS_W_SIMPLE GArrayDesc +{ + // FIXME: Body + // FIXME: Also implement proper operator== then + bool operator== (const GArrayDesc&) const { return true; } +}; +template GArrayDesc descr_of(const std::vector &) { return {};} +GAPI_EXPORTS_W inline GArrayDesc empty_array_desc() {return {}; } +/** @} */ + +std::ostream& operator<<(std::ostream& os, const cv::GArrayDesc &desc); + +namespace detail +{ + // ConstructVec is a callback which stores information about T and is used by + // G-API runtime to construct arrays in host memory (T remains opaque for G-API). + // ConstructVec is carried into G-API internals by GArrayU. + // Currently it is suitable for Host (CPU) plugins only, real offload may require + // more information for manual memory allocation on-device. + class VectorRef; + using ConstructVec = std::function; + + // This is the base struct for GArrayU type holder + struct TypeHintBase{virtual ~TypeHintBase() = default;}; + + // This class holds type of initial GArray to be checked from GArrayU + template + struct TypeHint final : public TypeHintBase{}; + + // This class strips type information from GArray and makes it usable + // in the G-API graph compiler (expression unrolling, graph generation, etc). + // Part of GProtoArg. + class GAPI_EXPORTS GArrayU + { + public: + GArrayU(const GNode &n, std::size_t out); // Operation result constructor + + template + bool holds() const; // Check if was created from GArray + + GOrigin& priv(); // Internal use only + const GOrigin& priv() const; // Internal use only + + protected: + GArrayU(); // Default constructor + GArrayU(const detail::VectorRef& vref); // Constant value constructor + template friend class cv::GArray; // (available to GArray only) + + void setConstructFcn(ConstructVec &&cv); // Store T-aware constructor + + template + void specifyType(); // Store type of initial GArray + + template + void storeKind(); + + void setKind(cv::detail::OpaqueKind); + + std::shared_ptr m_priv; + std::shared_ptr m_hint; + }; + + template + bool GArrayU::holds() const{ + GAPI_Assert(m_hint != nullptr); + using U = typename std::decay::type; + return dynamic_cast*>(m_hint.get()) != nullptr; + } + + template + void GArrayU::specifyType(){ + m_hint.reset(new TypeHint::type>); + } + + template + void GArrayU::storeKind(){ + setKind(cv::detail::GOpaqueTraits::kind); + } + + // This class represents a typed STL vector reference. + // Depending on origins, this reference may be either "just a" reference to + // an object created externally, OR actually own the underlying object + // (be value holder). + class BasicVectorRef + { + public: + // These fields are set by the derived class(es) + std::size_t m_elemSize = 0ul; + cv::GArrayDesc m_desc; + virtual ~BasicVectorRef() {} + + virtual void mov(BasicVectorRef &ref) = 0; + virtual const void* ptr() const = 0; + virtual std::size_t size() const = 0; + }; + + template class VectorRefT final: public BasicVectorRef + { + using empty_t = util::monostate; + using ro_ext_t = const std::vector *; + using rw_ext_t = std::vector *; + using rw_own_t = std::vector ; + util::variant m_ref; + + inline bool isEmpty() const { return util::holds_alternative(m_ref); } + inline bool isROExt() const { return util::holds_alternative(m_ref); } + inline bool isRWExt() const { return util::holds_alternative(m_ref); } + inline bool isRWOwn() const { return util::holds_alternative(m_ref); } + + void init(const std::vector* vec = nullptr) + { + m_elemSize = sizeof(T); + if (vec) m_desc = cv::descr_of(*vec); + } + + public: + VectorRefT() { init(); } + virtual ~VectorRefT() {} + + explicit VectorRefT(const std::vector& vec) : m_ref(&vec) { init(&vec); } + explicit VectorRefT(std::vector& vec) : m_ref(&vec) { init(&vec); } + explicit VectorRefT(std::vector&& vec) : m_ref(std::move(vec)) { init(&vec); } + + // Reset a VectorRefT. Called only for objects instantiated + // internally in G-API (e.g. temporary GArray's within a + // computation). Reset here means both initialization + // (creating an object) and reset (discarding its existing + // content before the next execution). Must never be called + // for external VectorRefTs. + void reset() + { + if (isEmpty()) + { + std::vector empty_vector; + m_desc = cv::descr_of(empty_vector); + m_ref = std::move(empty_vector); + GAPI_Assert(isRWOwn()); + } + else if (isRWOwn()) + { + util::get(m_ref).clear(); + } + else GAPI_Error("InternalError"); // shouldn't be called in *EXT modes + } + + // Obtain a WRITE reference to underlying object + // Used by CPU kernel API wrappers when a kernel execution frame + // is created + std::vector& wref() + { + GAPI_Assert(isRWExt() || isRWOwn()); + if (isRWExt()) return *util::get(m_ref); + if (isRWOwn()) return util::get(m_ref); + util::throw_error(std::logic_error("Impossible happened")); + } + + // Obtain a READ reference to underlying object + // Used by CPU kernel API wrappers when a kernel execution frame + // is created + const std::vector& rref() const + { + // ANY vector can be accessed for reading, even if it declared for + // output. Example -- a GComputation from [in] to [out1,out2] + // where [out2] is a result of operation applied to [out1]: + // + // GComputation boundary + // . . . . . . . + // . . + // [in] ----> foo() ----> [out1] + // . . : + // . . . .:. . . + // . V . + // . bar() ---> [out2] + // . . . . . . . . . . . . + // + if (isROExt()) return *util::get(m_ref); + if (isRWExt()) return *util::get(m_ref); + if (isRWOwn()) return util::get(m_ref); + util::throw_error(std::logic_error("Impossible happened")); + } + + virtual void mov(BasicVectorRef &v) override { + VectorRefT *tv = dynamic_cast*>(&v); + GAPI_Assert(tv != nullptr); + wref() = std::move(tv->wref()); + } + + virtual const void* ptr() const override { return &rref(); } + virtual std::size_t size() const override { return rref().size(); } + }; + + // This class strips type information from VectorRefT<> and makes it usable + // in the G-API executables (carrying run-time data/information to kernels). + // Part of GRunArg. + // Its methods are typed proxies to VectorRefT. + // VectorRef maintains "reference" semantics so two copies of VectoRef refer + // to the same underlying object. + // FIXME: Put a good explanation on why cv::OutputArray doesn't fit this role + class VectorRef + { + std::shared_ptr m_ref; + cv::detail::OpaqueKind m_kind = cv::detail::OpaqueKind::CV_UNKNOWN; + + template inline void check() const + { + GAPI_DbgAssert(dynamic_cast*>(m_ref.get()) != nullptr); + GAPI_Assert(sizeof(T) == m_ref->m_elemSize); + } + + public: + VectorRef() = default; + template explicit VectorRef(const std::vector& vec) + : m_ref(new VectorRefT(vec)) + , m_kind(GOpaqueTraits::kind) + {} + template explicit VectorRef(std::vector& vec) + : m_ref(new VectorRefT(vec)) + , m_kind(GOpaqueTraits::kind) + {} + template explicit VectorRef(std::vector&& vec) + : m_ref(new VectorRefT(std::move(vec))) + , m_kind(GOpaqueTraits::kind) + {} + + cv::detail::OpaqueKind getKind() const + { + return m_kind; + } + + template void reset() + { + if (!m_ref) m_ref.reset(new VectorRefT()); + check(); + storeKind(); + static_cast&>(*m_ref).reset(); + } + + template + void storeKind() + { + m_kind = cv::detail::GOpaqueTraits::kind; + } + + template std::vector& wref() + { + check(); + return static_cast&>(*m_ref).wref(); + } + + template const std::vector& rref() const + { + check(); + return static_cast&>(*m_ref).rref(); + } + + // Check if was created for/from std::vector + template bool holds() const + { + if (!m_ref) return false; + using U = typename std::decay::type; + return dynamic_cast*>(m_ref.get()) != nullptr; + } + + void mov(VectorRef &v) + { + m_ref->mov(*v.m_ref); + } + + cv::GArrayDesc descr_of() const + { + return m_ref->m_desc; + } + + std::size_t size() const + { + return m_ref->size(); + } + + // May be used to uniquely identify this object internally + const void *ptr() const { return m_ref->ptr(); } + }; + + // Helper (FIXME: work-around?) + // stripping G types to their host types + // like cv::GArray would still map to std::vector + // but not to std::vector +#if defined(GAPI_STANDALONE) +# define FLATTEN_NS cv::gapi::own +#else +# define FLATTEN_NS cv +#endif + template struct flatten_g; + template<> struct flatten_g { using type = FLATTEN_NS::Mat; }; + template<> struct flatten_g { using type = FLATTEN_NS::Scalar; }; + template struct flatten_g> { using type = std::vector; }; + template struct flatten_g { using type = T; }; +#undef FLATTEN_NS + // FIXME: the above mainly duplicates "ProtoToParam" thing from gtyped.hpp + // but I decided not to include gtyped here - probably worth moving that stuff + // to some common place? (DM) +} // namespace detail + +/** \addtogroup gapi_data_objects + * @{ + */ +/** + * @brief `cv::GArray` template class represents a list of objects + * of class `T` in the graph. + * + * `cv::GArray` describes a functional relationship between + * operations consuming and producing arrays of objects of class + * `T`. The primary purpose of `cv::GArray` is to represent a + * dynamic list of objects -- where the size of the list is not known + * at the graph construction or compile time. Examples include: corner + * and feature detectors (`cv::GArray`), object detection + * and tracking results (`cv::GArray`). Programmers can use + * their own types with `cv::GArray` in the custom operations. + * + * Similar to `cv::GScalar`, `cv::GArray` may be value-initialized + * -- in this case a graph-constant value is associated with the object. + * + * `GArray` is a virtual counterpart of `std::vector`, which is + * usually used to represent the `GArray` data in G-API during the + * execution. + * + * @sa `cv::GOpaque` + */ +template class GArray +{ +public: + // Host type (or Flat type) - the type this GArray is actually + // specified to. + /// @private + using HT = typename detail::flatten_g::type>::type; + + /** + * @brief Constructs a value-initialized `cv::GArray` + * + * `cv::GArray` objects may have their values + * be associated at graph construction time. It is useful when + * some operation has a `cv::GArray` input which doesn't change during + * the program execution, and is set only once. In this case, + * there is no need to declare such `cv::GArray` as a graph input. + * + * @note The value of `cv::GArray` may be overwritten by assigning some + * other `cv::GArray` to the object using `operator=` -- on the + * assignment, the old association or value is discarded. + * + * @param v a std::vector to associate with this + * `cv::GArray` object. Vector data is copied into the + * `cv::GArray` (no reference to the passed data is held). + */ + explicit GArray(const std::vector& v) // Constant value constructor + : m_ref(detail::GArrayU(detail::VectorRef(v))) { putDetails(); } + + /** + * @overload + * @brief Constructs a value-initialized `cv::GArray` + * + * @param v a std::vector to associate with this + * `cv::GArray` object. Vector data is moved into the `cv::GArray`. + */ + explicit GArray(std::vector&& v) // Move-constructor + : m_ref(detail::GArrayU(detail::VectorRef(std::move(v)))) { putDetails(); } + + /** + * @brief Constructs an empty `cv::GArray` + * + * Normally, empty G-API data objects denote a starting point of + * the graph. When an empty `cv::GArray` is assigned to a result + * of some operation, it obtains a functional link to this + * operation (and is not empty anymore). + */ + GArray() { putDetails(); } // Empty constructor + + /// @private + explicit GArray(detail::GArrayU &&ref) // GArrayU-based constructor + : m_ref(ref) { putDetails(); } // (used by GCall, not for users) + + /// @private + detail::GArrayU strip() const { + return m_ref; + } + /// @private + static void VCtor(detail::VectorRef& vref) { + vref.reset(); + } + +private: + void putDetails() { + m_ref.setConstructFcn(&VCtor); + m_ref.specifyType(); // FIXME: to unify those 2 to avoid excessive dynamic_cast + m_ref.storeKind(); // + } + + detail::GArrayU m_ref; +}; + +/** @} */ + +} // namespace cv + +#endif // OPENCV_GAPI_GARRAY_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gasync_context.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gasync_context.hpp index f49b59822d..8f3a10c7d7 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gasync_context.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gasync_context.hpp @@ -1,63 +1,63 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019 Intel Corporation - -#ifndef OPENCV_GAPI_GASYNC_CONTEXT_HPP -#define OPENCV_GAPI_GASYNC_CONTEXT_HPP - -#if !defined(GAPI_STANDALONE) -# include -#else // Without OpenCV -# include -#endif // !defined(GAPI_STANDALONE) - -#include - -namespace cv { -namespace gapi{ - -/** - * @brief This namespace contains experimental G-API functionality, - * functions or structures in this namespace are subjects to change or - * removal in the future releases. This namespace also contains - * functions which API is not stabilized yet. - */ -namespace wip { - -/** - * @brief A class to group async requests to cancel them in a single shot. - * - * GAsyncContext is passed as an argument to async() and async_apply() functions - */ - -class GAPI_EXPORTS GAsyncContext{ - std::atomic cancelation_requested = {false}; -public: - /** - * @brief Start cancellation process for an associated request. - * - * User still has to wait for each individual request (either via callback or according std::future object) to make sure it actually canceled. - * - * @return true if it was a first request to cancel the context - */ - bool cancel(); - - /** - * @brief Returns true if cancellation was requested for this context. - * - * @return true if cancellation was requested for this context - */ - bool isCanceled() const; -}; - -class GAPI_EXPORTS GAsyncCanceled : public std::exception { -public: - virtual const char* what() const noexcept CV_OVERRIDE; -}; -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif //OPENCV_GAPI_GASYNC_CONTEXT_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019 Intel Corporation + +#ifndef OPENCV_GAPI_GASYNC_CONTEXT_HPP +#define OPENCV_GAPI_GASYNC_CONTEXT_HPP + +#if !defined(GAPI_STANDALONE) +# include +#else // Without OpenCV +# include +#endif // !defined(GAPI_STANDALONE) + +#include + +namespace cv { +namespace gapi{ + +/** + * @brief This namespace contains experimental G-API functionality, + * functions or structures in this namespace are subjects to change or + * removal in the future releases. This namespace also contains + * functions which API is not stabilized yet. + */ +namespace wip { + +/** + * @brief A class to group async requests to cancel them in a single shot. + * + * GAsyncContext is passed as an argument to async() and async_apply() functions + */ + +class GAPI_EXPORTS GAsyncContext{ + std::atomic cancelation_requested = {false}; +public: + /** + * @brief Start cancellation process for an associated request. + * + * User still has to wait for each individual request (either via callback or according std::future object) to make sure it actually canceled. + * + * @return true if it was a first request to cancel the context + */ + bool cancel(); + + /** + * @brief Returns true if cancellation was requested for this context. + * + * @return true if cancellation was requested for this context + */ + bool isCanceled() const; +}; + +class GAPI_EXPORTS GAsyncCanceled : public std::exception { +public: + virtual const char* what() const noexcept CV_OVERRIDE; +}; +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif //OPENCV_GAPI_GASYNC_CONTEXT_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gcall.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gcall.hpp index 8d1b8d6010..df6baf6183 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gcall.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gcall.hpp @@ -1,78 +1,78 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_GCALL_HPP -#define OPENCV_GAPI_GCALL_HPP - -#include // GArg -#include // GMat -#include // GScalar -#include // GFrame -#include // GArray -#include // GOpaque - -namespace cv { - -struct GKernel; - -// The whole idea of this class is to represent an operation -// which is applied to arguments. This is part of public API, -// since it is what users should use to define kernel interfaces. - -class GAPI_EXPORTS GCall final -{ -public: - class Priv; - - explicit GCall(const GKernel &k); - ~GCall(); - - template - GCall& pass(Ts&&... args) - { - setArgs({cv::GArg(std::move(args))...}); - return *this; - } - - // A generic yield method - obtain a link to operator's particular GMat output - GMat yield (int output = 0); - GMatP yieldP (int output = 0); - GScalar yieldScalar(int output = 0); - GFrame yieldFrame (int output = 0); - - template GArray yieldArray(int output = 0) - { - return GArray(yieldArray(output)); - } - - template GOpaque yieldOpaque(int output = 0) - { - return GOpaque(yieldOpaque(output)); - } - - // Internal use only - Priv& priv(); - const Priv& priv() const; - - // GKernel and params can be modified, it's needed for infer, - // because information about output shapes doesn't exist in compile time - GKernel& kernel(); - cv::util::any& params(); - - void setArgs(std::vector &&args); - -protected: - std::shared_ptr m_priv; - - // Public versions return a typed array or opaque, those are implementation details - detail::GArrayU yieldArray(int output = 0); - detail::GOpaqueU yieldOpaque(int output = 0); -}; - -} // namespace cv - -#endif // OPENCV_GAPI_GCALL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_GCALL_HPP +#define OPENCV_GAPI_GCALL_HPP + +#include // GArg +#include // GMat +#include // GScalar +#include // GFrame +#include // GArray +#include // GOpaque + +namespace cv { + +struct GKernel; + +// The whole idea of this class is to represent an operation +// which is applied to arguments. This is part of public API, +// since it is what users should use to define kernel interfaces. + +class GAPI_EXPORTS GCall final +{ +public: + class Priv; + + explicit GCall(const GKernel &k); + ~GCall(); + + template + GCall& pass(Ts&&... args) + { + setArgs({cv::GArg(std::move(args))...}); + return *this; + } + + // A generic yield method - obtain a link to operator's particular GMat output + GMat yield (int output = 0); + GMatP yieldP (int output = 0); + GScalar yieldScalar(int output = 0); + GFrame yieldFrame (int output = 0); + + template GArray yieldArray(int output = 0) + { + return GArray(yieldArray(output)); + } + + template GOpaque yieldOpaque(int output = 0) + { + return GOpaque(yieldOpaque(output)); + } + + // Internal use only + Priv& priv(); + const Priv& priv() const; + + // GKernel and params can be modified, it's needed for infer, + // because information about output shapes doesn't exist in compile time + GKernel& kernel(); + cv::util::any& params(); + + void setArgs(std::vector &&args); + +protected: + std::shared_ptr m_priv; + + // Public versions return a typed array or opaque, those are implementation details + detail::GArrayU yieldArray(int output = 0); + detail::GOpaqueU yieldOpaque(int output = 0); +}; + +} // namespace cv + +#endif // OPENCV_GAPI_GCALL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gcommon.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gcommon.hpp index c61110e4d5..97bd9cb2dc 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gcommon.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gcommon.hpp @@ -1,309 +1,309 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2020 Intel Corporation - - -#ifndef OPENCV_GAPI_GCOMMON_HPP -#define OPENCV_GAPI_GCOMMON_HPP - -#include // std::hash -#include // std::vector -#include // decay - -#include - -#include -#include -#include -#include -#include -#include - -namespace cv { - -class GMat; // FIXME: forward declaration for GOpaqueTraits - -namespace detail -{ - // This is a trait-like structure to mark backend-specific compile arguments - // with tags - template struct CompileArgTag; - - // These structures are tags which separate kernels and transformations - struct KernelTag - {}; - struct TransformTag - {}; - - // This enum is utilized mostly by GArray and GOpaque to store and recognize their internal data - // types (aka Host type). Also it is widely used during serialization routine. - enum class OpaqueKind: int - { - CV_UNKNOWN, // Unknown, generic, opaque-to-GAPI data type unsupported in graph seriallization - CV_BOOL, // bool user G-API data - CV_INT, // int user G-API data - CV_INT64, // int64_t user G-API data - CV_DOUBLE, // double user G-API data - CV_FLOAT, // float user G-API data - CV_UINT64, // uint64_t user G-API data - CV_STRING, // std::string user G-API data - CV_POINT, // cv::Point user G-API data - CV_POINT2F, // cv::Point2f user G-API data - CV_POINT3F, // cv::Point3f user G-API data - CV_SIZE, // cv::Size user G-API data - CV_RECT, // cv::Rect user G-API data - CV_SCALAR, // cv::Scalar user G-API data - CV_MAT, // cv::Mat user G-API data - CV_DRAW_PRIM, // cv::gapi::wip::draw::Prim user G-API data - }; - - // Type traits helper which simplifies the extraction of kind from type - template struct GOpaqueTraits; - template struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_UNKNOWN; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_INT; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_INT64; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_DOUBLE; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_FLOAT; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_UINT64; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_BOOL; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_STRING; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_SIZE; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_SCALAR; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_POINT; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_POINT2F; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_POINT3F; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_MAT; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_RECT; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_MAT; }; - template<> struct GOpaqueTraits - { static constexpr const OpaqueKind kind = OpaqueKind::CV_DRAW_PRIM; }; - using GOpaqueTraitsArrayTypes = std::tuple; - // GOpaque is not supporting cv::Mat and cv::Scalar since there are GScalar and GMat types - using GOpaqueTraitsOpaqueTypes = std::tuple; -} // namespace detail - -// This definition is here because it is reused by both public(?) and internal -// modules. Keeping it here wouldn't expose public details (e.g., API-level) -// to components which are internal and operate on a lower-level entities -// (e.g., compiler, backends). -// FIXME: merge with ArgKind? -// FIXME: replace with variant[format desc]? -enum class GShape: int -{ - GMAT, - GSCALAR, - GARRAY, - GOPAQUE, - GFRAME, -}; - -namespace gapi { -namespace s11n { -namespace detail { -template struct wrap_serialize; -} // namespace detail -} // namespace s11n -} // namespace gapi - - -struct GCompileArg; - -namespace detail { - template - using is_compile_arg = std::is_same::type>; -} // namespace detail - -// CompileArg is an unified interface over backend-specific compilation -// information -// FIXME: Move to a separate file? -/** \addtogroup gapi_compile_args - * @{ - * - * @brief Compilation arguments: data structures controlling the - * compilation process - * - * G-API comes with a number of graph compilation options which can be - * passed to cv::GComputation::apply() or - * cv::GComputation::compile(). Known compilation options are listed - * in this page, while extra backends may introduce their own - * compilation options (G-API transparently accepts _everything_ which - * can be passed to cv::compile_args(), it depends on underlying - * backends if an option would be interpreted or not). - * - * For example, if an example computation is executed like this: - * - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp graph_decl_apply - * - * Extra parameter specifying which kernels to compile with can be - * passed like this: - * - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp apply_with_param - */ - -/** - * @brief Represents an arbitrary compilation argument. - * - * Any value can be wrapped into cv::GCompileArg, but only known ones - * (to G-API or its backends) can be interpreted correctly. - * - * Normally objects of this class shouldn't be created manually, use - * cv::compile_args() function which automatically wraps everything - * passed in (a variadic template parameter pack) into a vector of - * cv::GCompileArg objects. - */ -struct GCompileArg -{ -public: - // NB: Required for pythnon bindings - GCompileArg() = default; - - std::string tag; - - // FIXME: use decay in GArg/other trait-based wrapper before leg is shot! - template::value, int>::type = 0> - explicit GCompileArg(T &&t) - : tag(detail::CompileArgTag::type>::tag()) - , serializeF(cv::gapi::s11n::detail::has_S11N_spec::value ? - &cv::gapi::s11n::detail::wrap_serialize::serialize : - nullptr) - , arg(t) - { - } - - template T& get() - { - return util::any_cast(arg); - } - - template const T& get() const - { - return util::any_cast(arg); - } - - void serialize(cv::gapi::s11n::IOStream& os) const - { - if (serializeF) - { - serializeF(os, *this); - } - } - -private: - std::function serializeF; - util::any arg; -}; - -using GCompileArgs = std::vector; - -inline cv::GCompileArgs& operator += ( cv::GCompileArgs &lhs, - const cv::GCompileArgs &rhs) -{ - lhs.reserve(lhs.size() + rhs.size()); - lhs.insert(lhs.end(), rhs.begin(), rhs.end()); - return lhs; -} - -/** - * @brief Wraps a list of arguments (a parameter pack) into a vector of - * compilation arguments (cv::GCompileArg). - */ -template GCompileArgs compile_args(Ts&&... args) -{ - return GCompileArgs{ GCompileArg(args)... }; -} - -namespace gapi -{ -/** - * @brief Retrieves particular compilation argument by its type from - * cv::GCompileArgs - */ -template -inline cv::util::optional getCompileArg(const cv::GCompileArgs &args) -{ - for (auto &compile_arg : args) - { - if (compile_arg.tag == cv::detail::CompileArgTag::tag()) - { - return cv::util::optional(compile_arg.get()); - } - } - return cv::util::optional(); -} - -namespace s11n { -namespace detail { -template struct wrap_serialize -{ - static void serialize(IOStream& os, const GCompileArg& arg) - { - using DT = typename std::decay::type; - S11N
::serialize(os, arg.get
()); - } -}; -} // namespace detail -} // namespace s11n -} // namespace gapi - -/** @} gapi_compile_args */ - -/** - * @brief Ask G-API to dump compiled graph in Graphviz format under - * the given file name. - * - * Specifies a graph dump path (path to .dot file to be generated). - * G-API will dump a .dot file under specified path during a - * compilation process if this flag is passed. - */ -struct graph_dump_path -{ - std::string m_dump_path; -}; - -/** - * @brief Ask G-API to use threaded executor when cv::GComputation - * is compiled via cv::GComputation::compile method. - * - * Specifies a number of threads that should be used by executor. - */ -struct GAPI_EXPORTS use_threaded_executor -{ - use_threaded_executor(); - explicit use_threaded_executor(const uint32_t nthreads); - - uint32_t num_threads; -}; - -namespace detail -{ - template<> struct CompileArgTag - { - static const char* tag() { return "gapi.graph_dump_path"; } - }; - - template<> struct CompileArgTag - { - static const char* tag() { return "gapi.threaded_executor"; } - }; -} - -} // namespace cv - -// std::hash overload for GShape -namespace std -{ -template<> struct hash -{ - size_t operator() (cv::GShape sh) const - { - return std::hash()(static_cast(sh)); - } -}; -} // namespace std - - -#endif // OPENCV_GAPI_GCOMMON_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2020 Intel Corporation + + +#ifndef OPENCV_GAPI_GCOMMON_HPP +#define OPENCV_GAPI_GCOMMON_HPP + +#include // std::hash +#include // std::vector +#include // decay + +#include + +#include +#include +#include +#include +#include +#include + +namespace cv { + +class GMat; // FIXME: forward declaration for GOpaqueTraits + +namespace detail +{ + // This is a trait-like structure to mark backend-specific compile arguments + // with tags + template struct CompileArgTag; + + // These structures are tags which separate kernels and transformations + struct KernelTag + {}; + struct TransformTag + {}; + + // This enum is utilized mostly by GArray and GOpaque to store and recognize their internal data + // types (aka Host type). Also it is widely used during serialization routine. + enum class OpaqueKind: int + { + CV_UNKNOWN, // Unknown, generic, opaque-to-GAPI data type unsupported in graph seriallization + CV_BOOL, // bool user G-API data + CV_INT, // int user G-API data + CV_INT64, // int64_t user G-API data + CV_DOUBLE, // double user G-API data + CV_FLOAT, // float user G-API data + CV_UINT64, // uint64_t user G-API data + CV_STRING, // std::string user G-API data + CV_POINT, // cv::Point user G-API data + CV_POINT2F, // cv::Point2f user G-API data + CV_POINT3F, // cv::Point3f user G-API data + CV_SIZE, // cv::Size user G-API data + CV_RECT, // cv::Rect user G-API data + CV_SCALAR, // cv::Scalar user G-API data + CV_MAT, // cv::Mat user G-API data + CV_DRAW_PRIM, // cv::gapi::wip::draw::Prim user G-API data + }; + + // Type traits helper which simplifies the extraction of kind from type + template struct GOpaqueTraits; + template struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_UNKNOWN; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_INT; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_INT64; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_DOUBLE; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_FLOAT; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_UINT64; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_BOOL; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_STRING; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_SIZE; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_SCALAR; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_POINT; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_POINT2F; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_POINT3F; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_MAT; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_RECT; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_MAT; }; + template<> struct GOpaqueTraits + { static constexpr const OpaqueKind kind = OpaqueKind::CV_DRAW_PRIM; }; + using GOpaqueTraitsArrayTypes = std::tuple; + // GOpaque is not supporting cv::Mat and cv::Scalar since there are GScalar and GMat types + using GOpaqueTraitsOpaqueTypes = std::tuple; +} // namespace detail + +// This definition is here because it is reused by both public(?) and internal +// modules. Keeping it here wouldn't expose public details (e.g., API-level) +// to components which are internal and operate on a lower-level entities +// (e.g., compiler, backends). +// FIXME: merge with ArgKind? +// FIXME: replace with variant[format desc]? +enum class GShape: int +{ + GMAT, + GSCALAR, + GARRAY, + GOPAQUE, + GFRAME, +}; + +namespace gapi { +namespace s11n { +namespace detail { +template struct wrap_serialize; +} // namespace detail +} // namespace s11n +} // namespace gapi + + +struct GCompileArg; + +namespace detail { + template + using is_compile_arg = std::is_same::type>; +} // namespace detail + +// CompileArg is an unified interface over backend-specific compilation +// information +// FIXME: Move to a separate file? +/** \addtogroup gapi_compile_args + * @{ + * + * @brief Compilation arguments: data structures controlling the + * compilation process + * + * G-API comes with a number of graph compilation options which can be + * passed to cv::GComputation::apply() or + * cv::GComputation::compile(). Known compilation options are listed + * in this page, while extra backends may introduce their own + * compilation options (G-API transparently accepts _everything_ which + * can be passed to cv::compile_args(), it depends on underlying + * backends if an option would be interpreted or not). + * + * For example, if an example computation is executed like this: + * + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp graph_decl_apply + * + * Extra parameter specifying which kernels to compile with can be + * passed like this: + * + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp apply_with_param + */ + +/** + * @brief Represents an arbitrary compilation argument. + * + * Any value can be wrapped into cv::GCompileArg, but only known ones + * (to G-API or its backends) can be interpreted correctly. + * + * Normally objects of this class shouldn't be created manually, use + * cv::compile_args() function which automatically wraps everything + * passed in (a variadic template parameter pack) into a vector of + * cv::GCompileArg objects. + */ +struct GCompileArg +{ +public: + // NB: Required for pythnon bindings + GCompileArg() = default; + + std::string tag; + + // FIXME: use decay in GArg/other trait-based wrapper before leg is shot! + template::value, int>::type = 0> + explicit GCompileArg(T &&t) + : tag(detail::CompileArgTag::type>::tag()) + , serializeF(cv::gapi::s11n::detail::has_S11N_spec::value ? + &cv::gapi::s11n::detail::wrap_serialize::serialize : + nullptr) + , arg(t) + { + } + + template T& get() + { + return util::any_cast(arg); + } + + template const T& get() const + { + return util::any_cast(arg); + } + + void serialize(cv::gapi::s11n::IOStream& os) const + { + if (serializeF) + { + serializeF(os, *this); + } + } + +private: + std::function serializeF; + util::any arg; +}; + +using GCompileArgs = std::vector; + +inline cv::GCompileArgs& operator += ( cv::GCompileArgs &lhs, + const cv::GCompileArgs &rhs) +{ + lhs.reserve(lhs.size() + rhs.size()); + lhs.insert(lhs.end(), rhs.begin(), rhs.end()); + return lhs; +} + +/** + * @brief Wraps a list of arguments (a parameter pack) into a vector of + * compilation arguments (cv::GCompileArg). + */ +template GCompileArgs compile_args(Ts&&... args) +{ + return GCompileArgs{ GCompileArg(args)... }; +} + +namespace gapi +{ +/** + * @brief Retrieves particular compilation argument by its type from + * cv::GCompileArgs + */ +template +inline cv::util::optional getCompileArg(const cv::GCompileArgs &args) +{ + for (auto &compile_arg : args) + { + if (compile_arg.tag == cv::detail::CompileArgTag::tag()) + { + return cv::util::optional(compile_arg.get()); + } + } + return cv::util::optional(); +} + +namespace s11n { +namespace detail { +template struct wrap_serialize +{ + static void serialize(IOStream& os, const GCompileArg& arg) + { + using DT = typename std::decay::type; + S11N
::serialize(os, arg.get
()); + } +}; +} // namespace detail +} // namespace s11n +} // namespace gapi + +/** @} gapi_compile_args */ + +/** + * @brief Ask G-API to dump compiled graph in Graphviz format under + * the given file name. + * + * Specifies a graph dump path (path to .dot file to be generated). + * G-API will dump a .dot file under specified path during a + * compilation process if this flag is passed. + */ +struct graph_dump_path +{ + std::string m_dump_path; +}; + +/** + * @brief Ask G-API to use threaded executor when cv::GComputation + * is compiled via cv::GComputation::compile method. + * + * Specifies a number of threads that should be used by executor. + */ +struct GAPI_EXPORTS use_threaded_executor +{ + use_threaded_executor(); + explicit use_threaded_executor(const uint32_t nthreads); + + uint32_t num_threads; +}; + +namespace detail +{ + template<> struct CompileArgTag + { + static const char* tag() { return "gapi.graph_dump_path"; } + }; + + template<> struct CompileArgTag + { + static const char* tag() { return "gapi.threaded_executor"; } + }; +} + +} // namespace cv + +// std::hash overload for GShape +namespace std +{ +template<> struct hash +{ + size_t operator() (cv::GShape sh) const + { + return std::hash()(static_cast(sh)); + } +}; +} // namespace std + + +#endif // OPENCV_GAPI_GCOMMON_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gcompiled.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gcompiled.hpp index ac36783d62..d827e478e4 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gcompiled.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gcompiled.hpp @@ -1,232 +1,232 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2020 Intel Corporation - - -#ifndef OPENCV_GAPI_GCOMPILED_HPP -#define OPENCV_GAPI_GCOMPILED_HPP - -#include - -#include -#include -#include - -namespace cv { - -// This class represents a compiled computation. -// In theory (and ideally), it can be used w/o the rest of APIs. -// In theory (and ideally), it can be serialized/deserialized. -// It can enable scenarious like deployment to an autonomous devince, FuSa, etc. -// -// Currently GCompiled assumes all GMats you used to pass data to G-API -// are valid and not destroyed while you use a GCompiled object. -// -// FIXME: In future, there should be a way to name I/O objects and specify it -// to GCompiled externally (for example, when it is loaded on the target system). - -/** - * \addtogroup gapi_main_classes - * @{ - */ -/** - * @brief Represents a compiled computation (graph). Can only be used - * with image / data formats & resolutions it was compiled for, with - * some exceptions. - * - * This class represents a product of graph compilation (calling - * cv::GComputation::compile()). Objects of this class actually do - * data processing, and graph execution is incapsulated into objects - * of this class. Execution model itself depends on kernels and - * backends which were using during the compilation, see @ref - * gapi_compile_args for details. - * - * In a general case, GCompiled objects can be applied to data only in - * that formats/resolutions they were compiled for (see @ref - * gapi_meta_args). However, if the underlying backends allow, a - * compiled object can be _reshaped_ to handle data (images) of - * different resolution, though formats and types must remain the same. - * - * GCompiled is very similar to `std::function<>` in its semantics -- - * running it looks like a function call in the user code. - * - * At the moment, GCompiled objects are not reentrant -- generally, - * the objects are stateful since graph execution itself is a stateful - * process and this state is now maintained in GCompiled's own memory - * (not on the process stack). - * - * At the same time, two different GCompiled objects produced from the - * single cv::GComputation are completely independent and can be used - * concurrently. - * - * @sa GStreamingCompiled - */ -class GAPI_EXPORTS GCompiled -{ -public: - /// @private - class GAPI_EXPORTS Priv; - - /** - * @brief Constructs an empty object - */ - GCompiled(); - - /** - * @brief Run the compiled computation, a generic version. - * - * @param ins vector of inputs to process. - * @param outs vector of outputs to produce. - * - * Input/output vectors must have the same number of elements as - * defined in the cv::GComputation protocol (at the moment of its - * construction). Shapes of elements also must conform to protocol - * (e.g. cv::Mat needs to be passed where cv::GMat has been - * declared as input, and so on). Run-time exception is generated - * otherwise. - * - * Objects in output vector may remain empty (like cv::Mat) -- - * G-API will automatically initialize output objects to proper formats. - * - * @note Don't construct GRunArgs/GRunArgsP objects manually, use - * cv::gin()/cv::gout() wrappers instead. - */ - void operator() (GRunArgs &&ins, GRunArgsP &&outs); // Generic arg-to-arg -#if !defined(GAPI_STANDALONE) - - /** - * @brief Execute an unary computation - * - * @overload - * @param in input cv::Mat for unary computation - * @param out output cv::Mat for unary computation - * process. - */ - void operator() (cv::Mat in, cv::Mat &out); // Unary overload - - /** - * @brief Execute an unary computation - * - * @overload - * @param in input cv::Mat for unary computation - * @param out output cv::Scalar for unary computation - * process. - */ - void operator() (cv::Mat in, cv::Scalar &out); // Unary overload (scalar) - - /** - * @brief Execute a binary computation - * - * @overload - * @param in1 first input cv::Mat for binary computation - * @param in2 second input cv::Mat for binary computation - * @param out output cv::Mat for binary computation - * process. - */ - void operator() (cv::Mat in1, cv::Mat in2, cv::Mat &out); // Binary overload - - /** - * @brief Execute an binary computation - * - * @overload - * @param in1 first input cv::Mat for binary computation - * @param in2 second input cv::Mat for binary computation - * @param out output cv::Scalar for binary computation - * process. - */ - void operator() (cv::Mat in1, cv::Mat in2, cv::Scalar &out); // Binary overload (scalar) - - /** - * @brief Execute a computation with arbitrary number of - * inputs/outputs. - * - * @overload - * @param ins vector of input cv::Mat objects to process by the - * computation. - * @param outs vector of output cv::Mat objects to produce by the - * computation. - * - * Numbers of elements in ins/outs vectors must match numbers of - * inputs/outputs which were used to define the source GComputation. - */ - void operator() (const std::vector &ins, // Compatibility overload - const std::vector &outs); -#endif // !defined(GAPI_STANDALONE) - /// @private - Priv& priv(); - - /** - * @brief Check if compiled object is valid (non-empty) - * - * @return true if the object is runnable (valid), false otherwise - */ - explicit operator bool () const; - - /** - * @brief Vector of metadata this graph was compiled for. - * - * @return Unless _reshape_ is not supported, return value is the - * same vector which was passed to cv::GComputation::compile() to - * produce this compiled object. Otherwise, it is the latest - * metadata vector passed to reshape() (if that call was - * successful). - */ - const GMetaArgs& metas() const; // Meta passed to compile() - - /** - * @brief Vector of metadata descriptions of graph outputs - * - * @return vector with formats/resolutions of graph's output - * objects, auto-inferred from input metadata vector by - * operations which form this computation. - * - * @note GCompiled objects produced from the same - * cv::GComputiation graph with different input metas may return - * different values in this vector. - */ - const GMetaArgs& outMetas() const; - - /** - * @brief Check if the underlying backends support reshape or not. - * - * @return true if supported, false otherwise. - */ - bool canReshape() const; - - /** - * @brief Reshape a compiled graph to support new image - * resolutions. - * - * Throws an exception if an error occurs. - * - * @param inMetas new metadata to reshape on. Vector size and - * metadata shapes must match the computation's protocol. - * @param args compilation arguments to use. - */ - // FIXME: Why it requires compile args? - void reshape(const GMetaArgs& inMetas, const GCompileArgs& args); - - /** - * @brief Prepare inner kernels states for a new video-stream. - * - * GCompiled objects may be used to process video streams frame by frame. - * In this case, a GCompiled is called on every image frame individually. - * Starting OpenCV 4.4, some kernels in the graph may have their internal - * states (see GAPI_OCV_KERNEL_ST for the OpenCV backend). - * In this case, if user starts processing another video stream with - * this GCompiled, this method needs to be called to let kernels re-initialize - * their internal states to a new video stream. - */ - void prepareForNewStream(); - -protected: - /// @private - std::shared_ptr m_priv; -}; -/** @} */ - -} - -#endif // OPENCV_GAPI_GCOMPILED_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2020 Intel Corporation + + +#ifndef OPENCV_GAPI_GCOMPILED_HPP +#define OPENCV_GAPI_GCOMPILED_HPP + +#include + +#include +#include +#include + +namespace cv { + +// This class represents a compiled computation. +// In theory (and ideally), it can be used w/o the rest of APIs. +// In theory (and ideally), it can be serialized/deserialized. +// It can enable scenarious like deployment to an autonomous devince, FuSa, etc. +// +// Currently GCompiled assumes all GMats you used to pass data to G-API +// are valid and not destroyed while you use a GCompiled object. +// +// FIXME: In future, there should be a way to name I/O objects and specify it +// to GCompiled externally (for example, when it is loaded on the target system). + +/** + * \addtogroup gapi_main_classes + * @{ + */ +/** + * @brief Represents a compiled computation (graph). Can only be used + * with image / data formats & resolutions it was compiled for, with + * some exceptions. + * + * This class represents a product of graph compilation (calling + * cv::GComputation::compile()). Objects of this class actually do + * data processing, and graph execution is incapsulated into objects + * of this class. Execution model itself depends on kernels and + * backends which were using during the compilation, see @ref + * gapi_compile_args for details. + * + * In a general case, GCompiled objects can be applied to data only in + * that formats/resolutions they were compiled for (see @ref + * gapi_meta_args). However, if the underlying backends allow, a + * compiled object can be _reshaped_ to handle data (images) of + * different resolution, though formats and types must remain the same. + * + * GCompiled is very similar to `std::function<>` in its semantics -- + * running it looks like a function call in the user code. + * + * At the moment, GCompiled objects are not reentrant -- generally, + * the objects are stateful since graph execution itself is a stateful + * process and this state is now maintained in GCompiled's own memory + * (not on the process stack). + * + * At the same time, two different GCompiled objects produced from the + * single cv::GComputation are completely independent and can be used + * concurrently. + * + * @sa GStreamingCompiled + */ +class GAPI_EXPORTS GCompiled +{ +public: + /// @private + class GAPI_EXPORTS Priv; + + /** + * @brief Constructs an empty object + */ + GCompiled(); + + /** + * @brief Run the compiled computation, a generic version. + * + * @param ins vector of inputs to process. + * @param outs vector of outputs to produce. + * + * Input/output vectors must have the same number of elements as + * defined in the cv::GComputation protocol (at the moment of its + * construction). Shapes of elements also must conform to protocol + * (e.g. cv::Mat needs to be passed where cv::GMat has been + * declared as input, and so on). Run-time exception is generated + * otherwise. + * + * Objects in output vector may remain empty (like cv::Mat) -- + * G-API will automatically initialize output objects to proper formats. + * + * @note Don't construct GRunArgs/GRunArgsP objects manually, use + * cv::gin()/cv::gout() wrappers instead. + */ + void operator() (GRunArgs &&ins, GRunArgsP &&outs); // Generic arg-to-arg +#if !defined(GAPI_STANDALONE) + + /** + * @brief Execute an unary computation + * + * @overload + * @param in input cv::Mat for unary computation + * @param out output cv::Mat for unary computation + * process. + */ + void operator() (cv::Mat in, cv::Mat &out); // Unary overload + + /** + * @brief Execute an unary computation + * + * @overload + * @param in input cv::Mat for unary computation + * @param out output cv::Scalar for unary computation + * process. + */ + void operator() (cv::Mat in, cv::Scalar &out); // Unary overload (scalar) + + /** + * @brief Execute a binary computation + * + * @overload + * @param in1 first input cv::Mat for binary computation + * @param in2 second input cv::Mat for binary computation + * @param out output cv::Mat for binary computation + * process. + */ + void operator() (cv::Mat in1, cv::Mat in2, cv::Mat &out); // Binary overload + + /** + * @brief Execute an binary computation + * + * @overload + * @param in1 first input cv::Mat for binary computation + * @param in2 second input cv::Mat for binary computation + * @param out output cv::Scalar for binary computation + * process. + */ + void operator() (cv::Mat in1, cv::Mat in2, cv::Scalar &out); // Binary overload (scalar) + + /** + * @brief Execute a computation with arbitrary number of + * inputs/outputs. + * + * @overload + * @param ins vector of input cv::Mat objects to process by the + * computation. + * @param outs vector of output cv::Mat objects to produce by the + * computation. + * + * Numbers of elements in ins/outs vectors must match numbers of + * inputs/outputs which were used to define the source GComputation. + */ + void operator() (const std::vector &ins, // Compatibility overload + const std::vector &outs); +#endif // !defined(GAPI_STANDALONE) + /// @private + Priv& priv(); + + /** + * @brief Check if compiled object is valid (non-empty) + * + * @return true if the object is runnable (valid), false otherwise + */ + explicit operator bool () const; + + /** + * @brief Vector of metadata this graph was compiled for. + * + * @return Unless _reshape_ is not supported, return value is the + * same vector which was passed to cv::GComputation::compile() to + * produce this compiled object. Otherwise, it is the latest + * metadata vector passed to reshape() (if that call was + * successful). + */ + const GMetaArgs& metas() const; // Meta passed to compile() + + /** + * @brief Vector of metadata descriptions of graph outputs + * + * @return vector with formats/resolutions of graph's output + * objects, auto-inferred from input metadata vector by + * operations which form this computation. + * + * @note GCompiled objects produced from the same + * cv::GComputiation graph with different input metas may return + * different values in this vector. + */ + const GMetaArgs& outMetas() const; + + /** + * @brief Check if the underlying backends support reshape or not. + * + * @return true if supported, false otherwise. + */ + bool canReshape() const; + + /** + * @brief Reshape a compiled graph to support new image + * resolutions. + * + * Throws an exception if an error occurs. + * + * @param inMetas new metadata to reshape on. Vector size and + * metadata shapes must match the computation's protocol. + * @param args compilation arguments to use. + */ + // FIXME: Why it requires compile args? + void reshape(const GMetaArgs& inMetas, const GCompileArgs& args); + + /** + * @brief Prepare inner kernels states for a new video-stream. + * + * GCompiled objects may be used to process video streams frame by frame. + * In this case, a GCompiled is called on every image frame individually. + * Starting OpenCV 4.4, some kernels in the graph may have their internal + * states (see GAPI_OCV_KERNEL_ST for the OpenCV backend). + * In this case, if user starts processing another video stream with + * this GCompiled, this method needs to be called to let kernels re-initialize + * their internal states to a new video stream. + */ + void prepareForNewStream(); + +protected: + /// @private + std::shared_ptr m_priv; +}; +/** @} */ + +} + +#endif // OPENCV_GAPI_GCOMPILED_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gcompiled_async.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gcompiled_async.hpp index a0c2917d6a..c3a1c05610 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gcompiled_async.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gcompiled_async.hpp @@ -1,73 +1,73 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019 Intel Corporation - - -#ifndef OPENCV_GAPI_GCOMPILED_ASYNC_HPP -#define OPENCV_GAPI_GCOMPILED_ASYNC_HPP - -#include //for std::future -#include //for std::exception_ptr -#include //for std::function -#include -#include - -namespace cv { - //fwd declaration - class GCompiled; - -namespace gapi{ -namespace wip { - class GAsyncContext; - /** - These functions asynchronously (i.e. probably on a separate thread of execution) call GCompiled::operator() member function of their first argument with copies of rest of arguments (except callback) passed in. - The difference between the function is the way to get the completion notification (via callback or a waiting on std::future object) - If exception is occurred during execution of apply it is transferred to the callback (via function parameter) or passed to future (and will be thrown on call to std::future::get) - - N.B. : - Input arguments are copied on call to async function (actually on call to cv::gin) and thus do not have to outlive the actual completion of asynchronous activity. - While output arguments are "captured" by reference(pointer) and therefore _must_ outlive the asynchronous activity - (i.e. live at least until callback is called or future is unblocked) - - @param gcmpld Compiled computation (graph) to start asynchronously - @param callback Callback to be called when execution of gcmpld is done - @param ins Input parameters for gcmpld - @param outs Output parameters for gcmpld - */ - GAPI_EXPORTS void async(GCompiled& gcmpld, std::function&& callback, GRunArgs &&ins, GRunArgsP &&outs); - - /** @overload - @param gcmpld Compiled computation (graph) to run asynchronously - @param callback Callback to be called when execution of gcmpld is done - @param ins Input parameters for gcmpld - @param outs Output parameters for gcmpld - @param ctx Context this request belongs to - @see async GAsyncContext - */ - GAPI_EXPORTS void async(GCompiled& gcmpld, std::function&& callback, GRunArgs &&ins, GRunArgsP &&outs, GAsyncContext& ctx); - - /** @overload - @param gcmpld Compiled computation (graph) to run asynchronously - @param ins Input parameters for gcmpld - @param outs Output parameters for gcmpld - @return std::future object to wait for completion of async operation - @see async - */ - GAPI_EXPORTS std::future async(GCompiled& gcmpld, GRunArgs &&ins, GRunArgsP &&outs); - - /** - @param gcmpld Compiled computation (graph) to run asynchronously - @param ins Input parameters for gcmpld - @param outs Output parameters for gcmpld - @param ctx Context this request belongs to - @return std::future object to wait for completion of async operation - @see async GAsyncContext - */ - GAPI_EXPORTS std::future async(GCompiled& gcmpld, GRunArgs &&ins, GRunArgsP &&outs, GAsyncContext& ctx); -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_GCOMPILED_ASYNC_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019 Intel Corporation + + +#ifndef OPENCV_GAPI_GCOMPILED_ASYNC_HPP +#define OPENCV_GAPI_GCOMPILED_ASYNC_HPP + +#include //for std::future +#include //for std::exception_ptr +#include //for std::function +#include +#include + +namespace cv { + //fwd declaration + class GCompiled; + +namespace gapi{ +namespace wip { + class GAsyncContext; + /** + These functions asynchronously (i.e. probably on a separate thread of execution) call GCompiled::operator() member function of their first argument with copies of rest of arguments (except callback) passed in. + The difference between the function is the way to get the completion notification (via callback or a waiting on std::future object) + If exception is occurred during execution of apply it is transferred to the callback (via function parameter) or passed to future (and will be thrown on call to std::future::get) + + N.B. : + Input arguments are copied on call to async function (actually on call to cv::gin) and thus do not have to outlive the actual completion of asynchronous activity. + While output arguments are "captured" by reference(pointer) and therefore _must_ outlive the asynchronous activity + (i.e. live at least until callback is called or future is unblocked) + + @param gcmpld Compiled computation (graph) to start asynchronously + @param callback Callback to be called when execution of gcmpld is done + @param ins Input parameters for gcmpld + @param outs Output parameters for gcmpld + */ + GAPI_EXPORTS void async(GCompiled& gcmpld, std::function&& callback, GRunArgs &&ins, GRunArgsP &&outs); + + /** @overload + @param gcmpld Compiled computation (graph) to run asynchronously + @param callback Callback to be called when execution of gcmpld is done + @param ins Input parameters for gcmpld + @param outs Output parameters for gcmpld + @param ctx Context this request belongs to + @see async GAsyncContext + */ + GAPI_EXPORTS void async(GCompiled& gcmpld, std::function&& callback, GRunArgs &&ins, GRunArgsP &&outs, GAsyncContext& ctx); + + /** @overload + @param gcmpld Compiled computation (graph) to run asynchronously + @param ins Input parameters for gcmpld + @param outs Output parameters for gcmpld + @return std::future object to wait for completion of async operation + @see async + */ + GAPI_EXPORTS std::future async(GCompiled& gcmpld, GRunArgs &&ins, GRunArgsP &&outs); + + /** + @param gcmpld Compiled computation (graph) to run asynchronously + @param ins Input parameters for gcmpld + @param outs Output parameters for gcmpld + @param ctx Context this request belongs to + @return std::future object to wait for completion of async operation + @see async GAsyncContext + */ + GAPI_EXPORTS std::future async(GCompiled& gcmpld, GRunArgs &&ins, GRunArgsP &&outs, GAsyncContext& ctx); +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_GCOMPILED_ASYNC_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gcompoundkernel.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gcompoundkernel.hpp index df0ce34045..e286766967 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gcompoundkernel.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gcompoundkernel.hpp @@ -1,139 +1,139 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2019 Intel Corporation - - -#ifndef OPENCV_GAPI_GCOMPOUNDKERNEL_HPP -#define OPENCV_GAPI_GCOMPOUNDKERNEL_HPP - -#include -#include -#include -#include - -namespace cv { -namespace gapi -{ -namespace compound -{ - // FIXME User does not need to know about this function - // Needs that user may define compound kernels(as cpu kernels) - GAPI_EXPORTS cv::gapi::GBackend backend(); -} // namespace compound -} // namespace gapi - -namespace detail -{ - -struct GCompoundContext -{ - explicit GCompoundContext(const GArgs& in_args); - template - const T& inArg(int input) { return m_args.at(input).get(); } - - GArgs m_args; - GArgs m_results; -}; - -class GAPI_EXPORTS GCompoundKernel -{ -// Compound kernel must use all of it's inputs -public: - using F = std::function; - - explicit GCompoundKernel(const F& f); - void apply(GCompoundContext& ctx); - -protected: - F m_f; -}; - -template struct get_compound_in -{ - static T get(GCompoundContext &ctx, int idx) { return ctx.inArg(idx); } -}; - -template struct get_compound_in> -{ - static cv::GArray get(GCompoundContext &ctx, int idx) - { - auto array = cv::GArray(); - ctx.m_args[idx] = GArg(array); - return array; - } -}; - -template struct get_compound_in> -{ - static cv::GOpaque get(GCompoundContext &ctx, int idx) - { - auto opaq = cv::GOpaque(); - ctx.m_args[idx] = GArg(opaq); - return opaq; - } -}; - -template<> struct get_compound_in -{ - static cv::GMatP get(GCompoundContext &ctx, int idx) - { - auto mat = cv::GMatP(); - ctx.m_args[idx] = GArg(mat); - return mat; - } -}; - -template -struct GCompoundCallHelper; - -template -struct GCompoundCallHelper, std::tuple > -{ - template - static void expand_impl(GCompoundContext &ctx, detail::Seq, detail::Seq) - { - auto result = Impl::expand(get_compound_in::get(ctx, IIs)...); - auto tuple_return = tuple_wrap_helper::get(std::move(result)); - ctx.m_results = { cv::GArg(std::get(tuple_return))... }; - } - - static void expand(GCompoundContext &ctx) - { - expand_impl(ctx, - typename detail::MkSeq::type(), - typename detail::MkSeq::type()); - } -}; - -template -class GCompoundKernelImpl: public cv::detail::GCompoundCallHelper, - public cv::detail::KernelTag -{ - using P = cv::detail::GCompoundCallHelper; - -public: - using API = K; - - static cv::gapi::GBackend backend() { return cv::gapi::compound::backend(); } - static GCompoundKernel kernel() { return GCompoundKernel(&P::expand); } -}; - -} // namespace detail - - -/** - * Declares a new compound kernel. See this - * [documentation chapter](@ref gapi_kernel_compound) - * on compound kernels for more details. - * - * @param Name type name for new kernel - * @param API the interface this kernel implements - */ -#define GAPI_COMPOUND_KERNEL(Name, API) \ - struct Name: public cv::detail::GCompoundKernelImpl - -} // namespace cv - -#endif // OPENCV_GAPI_GCOMPOUNDKERNEL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2019 Intel Corporation + + +#ifndef OPENCV_GAPI_GCOMPOUNDKERNEL_HPP +#define OPENCV_GAPI_GCOMPOUNDKERNEL_HPP + +#include +#include +#include +#include + +namespace cv { +namespace gapi +{ +namespace compound +{ + // FIXME User does not need to know about this function + // Needs that user may define compound kernels(as cpu kernels) + GAPI_EXPORTS cv::gapi::GBackend backend(); +} // namespace compound +} // namespace gapi + +namespace detail +{ + +struct GCompoundContext +{ + explicit GCompoundContext(const GArgs& in_args); + template + const T& inArg(int input) { return m_args.at(input).get(); } + + GArgs m_args; + GArgs m_results; +}; + +class GAPI_EXPORTS GCompoundKernel +{ +// Compound kernel must use all of it's inputs +public: + using F = std::function; + + explicit GCompoundKernel(const F& f); + void apply(GCompoundContext& ctx); + +protected: + F m_f; +}; + +template struct get_compound_in +{ + static T get(GCompoundContext &ctx, int idx) { return ctx.inArg(idx); } +}; + +template struct get_compound_in> +{ + static cv::GArray get(GCompoundContext &ctx, int idx) + { + auto array = cv::GArray(); + ctx.m_args[idx] = GArg(array); + return array; + } +}; + +template struct get_compound_in> +{ + static cv::GOpaque get(GCompoundContext &ctx, int idx) + { + auto opaq = cv::GOpaque(); + ctx.m_args[idx] = GArg(opaq); + return opaq; + } +}; + +template<> struct get_compound_in +{ + static cv::GMatP get(GCompoundContext &ctx, int idx) + { + auto mat = cv::GMatP(); + ctx.m_args[idx] = GArg(mat); + return mat; + } +}; + +template +struct GCompoundCallHelper; + +template +struct GCompoundCallHelper, std::tuple > +{ + template + static void expand_impl(GCompoundContext &ctx, detail::Seq, detail::Seq) + { + auto result = Impl::expand(get_compound_in::get(ctx, IIs)...); + auto tuple_return = tuple_wrap_helper::get(std::move(result)); + ctx.m_results = { cv::GArg(std::get(tuple_return))... }; + } + + static void expand(GCompoundContext &ctx) + { + expand_impl(ctx, + typename detail::MkSeq::type(), + typename detail::MkSeq::type()); + } +}; + +template +class GCompoundKernelImpl: public cv::detail::GCompoundCallHelper, + public cv::detail::KernelTag +{ + using P = cv::detail::GCompoundCallHelper; + +public: + using API = K; + + static cv::gapi::GBackend backend() { return cv::gapi::compound::backend(); } + static GCompoundKernel kernel() { return GCompoundKernel(&P::expand); } +}; + +} // namespace detail + + +/** + * Declares a new compound kernel. See this + * [documentation chapter](@ref gapi_kernel_compound) + * on compound kernels for more details. + * + * @param Name type name for new kernel + * @param API the interface this kernel implements + */ +#define GAPI_COMPOUND_KERNEL(Name, API) \ + struct Name: public cv::detail::GCompoundKernelImpl + +} // namespace cv + +#endif // OPENCV_GAPI_GCOMPOUNDKERNEL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gcomputation.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gcomputation.hpp index 196eb37c6b..4803c7d999 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gcomputation.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gcomputation.hpp @@ -1,581 +1,581 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_GCOMPUTATION_HPP -#define OPENCV_GAPI_GCOMPUTATION_HPP - -#include - -#include -#include -#include -#include -#include -#include - -namespace cv { - -namespace detail -{ - // FIXME: move to algorithm, cover with separate tests - // FIXME: replace with O(1) version (both memory and compilation time) - template - struct last_type; - - template - struct last_type { using type = T;}; - - template - struct last_type { using type = typename last_type::type; }; - - template - using last_type_t = typename last_type::type; -} - -// Forward-declare the serialization objects -namespace gapi { -namespace s11n { - struct IIStream; - struct IOStream; -} // namespace s11n -} // namespace gapi - -/** - * \addtogroup gapi_main_classes - * @{ - * - * @brief G-API classes for constructed and compiled graphs. - */ - -/** - * @brief GComputation class represents a captured computation - * graph. GComputation objects form boundaries for expression code - * user writes with G-API, allowing to compile and execute it. - * - * G-API computations are defined with input/output data - * objects. G-API will track automatically which operations connect - * specified outputs to the inputs, forming up a call graph to be - * executed. The below example expresses calculation of Sobel operator - * for edge detection (\f$G = \sqrt{G_x^2 + G_y^2}\f$): - * - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp graph_def - * - * Full pipeline can be now captured with this object declaration: - * - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp graph_cap_full - * - * Input/output data objects on which a call graph should be - * reconstructed are passed using special wrappers cv::GIn and - * cv::GOut. G-API will track automatically which operations form a - * path from inputs to outputs and build the execution graph appropriately. - * - * Note that cv::GComputation doesn't take ownership on data objects - * it is defined. Moreover, multiple GComputation objects may be - * defined on the same expressions, e.g. a smaller pipeline which - * expects that image gradients are already pre-calculated may be - * defined like this: - * - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp graph_cap_sub - * - * The resulting graph would expect two inputs and produce one - * output. In this case, it doesn't matter if gx/gy data objects are - * results of cv::gapi::Sobel operators -- G-API will stop unrolling - * expressions and building the underlying graph one reaching this - * data objects. - * - * The way how GComputation is defined is important as its definition - * specifies graph _protocol_ -- the way how the graph should be - * used. Protocol is defined by number of inputs, number of outputs, - * and shapes of inputs and outputs. - * - * In the above example, sobelEdge expects one Mat on input and - * produces one Mat; while sobelEdgeSub expects two Mats on input and - * produces one Mat. GComputation's protocol defines how other - * computation methods should be used -- cv::GComputation::compile() and - * cv::GComputation::apply(). For example, if a graph is defined on - * two GMat inputs, two cv::Mat objects have to be passed to apply() - * for execution. GComputation checks protocol correctness in runtime - * so passing a different number of objects in apply() or passing - * cv::Scalar instead of cv::Mat there would compile well as a C++ - * source but raise an exception in run-time. G-API also comes with a - * typed wrapper cv::GComputationT<> which introduces this type-checking in - * compile-time. - * - * cv::GComputation itself is a thin object which just captures what - * the graph is. The compiled graph (which actually process data) is - * represented by class GCompiled. Use compile() method to generate a - * compiled graph with given compile options. cv::GComputation can - * also be used to process data with implicit graph compilation - * on-the-fly, see apply() for details. - * - * GComputation is a reference-counted object -- once defined, all its - * copies will refer to the same instance. - * - * @sa GCompiled - */ -class GAPI_EXPORTS_W GComputation -{ -public: - class Priv; - typedef std::function Generator; - - // Various constructors enable different ways to define a computation: ///// - // 1. Generic constructors - /** - * @brief Define a computation using a generator function. - * - * Graph can be defined in-place directly at the moment of its - * construction with a lambda: - * - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp graph_gen - * - * This may be useful since all temporary objects (cv::GMats) and - * namespaces can be localized to scope of lambda, without - * contaminating the parent scope with probably unnecessary objects - * and information. - * - * @param gen generator function which returns a cv::GComputation, - * see Generator. - */ - GComputation(const Generator& gen); // Generator - // overload - - /** - * @brief Generic GComputation constructor. - * - * Constructs a new graph with a given protocol, specified as a - * flow of operations connecting input/output objects. Throws if - * the passed boundaries are invalid, e.g. if there's no - * functional dependency (path) between given outputs and inputs. - * - * @param ins Input data vector. - * @param outs Output data vector. - * - * @note Don't construct GProtoInputArgs/GProtoOutputArgs objects - * directly, use cv::GIn()/cv::GOut() wrapper functions instead. - * - * @sa @ref gapi_data_objects - */ - GAPI_WRAP GComputation(GProtoInputArgs &&ins, - GProtoOutputArgs &&outs); // Arg-to-arg overload - - // 2. Syntax sugar and compatibility overloads - /** - * @brief Defines an unary (one input -- one output) computation - * - * @overload - * @param in input GMat of the defined unary computation - * @param out output GMat of the defined unary computation - */ - GAPI_WRAP GComputation(GMat in, GMat out); // Unary overload - - /** - * @brief Defines an unary (one input -- one output) computation - * - * @overload - * @param in input GMat of the defined unary computation - * @param out output GScalar of the defined unary computation - */ - GAPI_WRAP GComputation(GMat in, GScalar out); // Unary overload (scalar) - - /** - * @brief Defines a binary (two inputs -- one output) computation - * - * @overload - * @param in1 first input GMat of the defined binary computation - * @param in2 second input GMat of the defined binary computation - * @param out output GMat of the defined binary computation - */ - GAPI_WRAP GComputation(GMat in1, GMat in2, GMat out); // Binary overload - - /** - * @brief Defines a binary (two inputs -- one output) computation - * - * @overload - * @param in1 first input GMat of the defined binary computation - * @param in2 second input GMat of the defined binary computation - * @param out output GScalar of the defined binary computation - */ - GComputation(GMat in1, GMat in2, GScalar out); // Binary - // overload - // (scalar) - - /** - * @brief Defines a computation with arbitrary input/output number. - * - * @overload - * @param ins vector of inputs GMats for this computation - * @param outs vector of outputs GMats for this computation - * - * Use this overload for cases when number of computation - * inputs/outputs is not known in compile-time -- e.g. when graph - * is programmatically generated to build an image pyramid with - * the given number of levels, etc. - */ - GComputation(const std::vector &ins, // Compatibility overload - const std::vector &outs); - - // Various versions of apply(): //////////////////////////////////////////// - // 1. Generic apply() - /** - * @brief Compile graph on-the-fly and immediately execute it on - * the inputs data vectors. - * - * Number of input/output data objects must match GComputation's - * protocol, also types of host data objects (cv::Mat, cv::Scalar) - * must match the shapes of data objects from protocol (cv::GMat, - * cv::GScalar). If there's a mismatch, a run-time exception will - * be generated. - * - * Internally, a cv::GCompiled object is created for the given - * input format configuration, which then is executed on the input - * data immediately. cv::GComputation caches compiled objects - * produced within apply() -- if this method would be called next - * time with the same input parameters (image formats, image - * resolution, etc), the underlying compiled graph will be reused - * without recompilation. If new metadata doesn't match the cached - * one, the underlying compiled graph is regenerated. - * - * @note compile() always triggers a compilation process and - * produces a new GCompiled object regardless if a similar one has - * been cached via apply() or not. - * - * @param ins vector of input data to process. Don't create - * GRunArgs object manually, use cv::gin() wrapper instead. - * @param outs vector of output data to fill results in. cv::Mat - * objects may be empty in this vector, G-API will automatically - * initialize it with the required format & dimensions. Don't - * create GRunArgsP object manually, use cv::gout() wrapper instead. - * @param args a list of compilation arguments to pass to the - * underlying compilation process. Don't create GCompileArgs - * object manually, use cv::compile_args() wrapper instead. - * - * @sa @ref gapi_data_objects, @ref gapi_compile_args - */ - void apply(GRunArgs &&ins, GRunArgsP &&outs, GCompileArgs &&args = {}); // Arg-to-arg overload - - /// @private -- Exclude this function from OpenCV documentation - GAPI_WRAP GRunArgs apply(const cv::detail::ExtractArgsCallback &callback, - GCompileArgs &&args = {}); - - /// @private -- Exclude this function from OpenCV documentation - void apply(const std::vector& ins, // Compatibility overload - const std::vector& outs, - GCompileArgs &&args = {}); - - // 2. Syntax sugar and compatibility overloads -#if !defined(GAPI_STANDALONE) - /** - * @brief Execute an unary computation (with compilation on the fly) - * - * @overload - * @param in input cv::Mat for unary computation - * @param out output cv::Mat for unary computation - * @param args compilation arguments for underlying compilation - * process. - */ - void apply(cv::Mat in, cv::Mat &out, GCompileArgs &&args = {}); // Unary overload - - /** - * @brief Execute an unary computation (with compilation on the fly) - * - * @overload - * @param in input cv::Mat for unary computation - * @param out output cv::Scalar for unary computation - * @param args compilation arguments for underlying compilation - * process. - */ - void apply(cv::Mat in, cv::Scalar &out, GCompileArgs &&args = {}); // Unary overload (scalar) - - /** - * @brief Execute a binary computation (with compilation on the fly) - * - * @overload - * @param in1 first input cv::Mat for binary computation - * @param in2 second input cv::Mat for binary computation - * @param out output cv::Mat for binary computation - * @param args compilation arguments for underlying compilation - * process. - */ - void apply(cv::Mat in1, cv::Mat in2, cv::Mat &out, GCompileArgs &&args = {}); // Binary overload - - /** - * @brief Execute an binary computation (with compilation on the fly) - * - * @overload - * @param in1 first input cv::Mat for binary computation - * @param in2 second input cv::Mat for binary computation - * @param out output cv::Scalar for binary computation - * @param args compilation arguments for underlying compilation - * process. - */ - void apply(cv::Mat in1, cv::Mat in2, cv::Scalar &out, GCompileArgs &&args = {}); // Binary overload (scalar) - - /** - * @brief Execute a computation with arbitrary number of - * inputs/outputs (with compilation on-the-fly). - * - * @overload - * @param ins vector of input cv::Mat objects to process by the - * computation. - * @param outs vector of output cv::Mat objects to produce by the - * computation. - * @param args compilation arguments for underlying compilation - * process. - * - * Numbers of elements in ins/outs vectors must match numbers of - * inputs/outputs which were used to define this GComputation. - */ - void apply(const std::vector& ins, // Compatibility overload - std::vector& outs, - GCompileArgs &&args = {}); -#endif // !defined(GAPI_STANDALONE) - // Various versions of compile(): ////////////////////////////////////////// - // 1. Generic compile() - requires metas to be passed as vector - /** - * @brief Compile the computation for specific input format(s). - * - * This method triggers compilation process and produces a new - * GCompiled object which then can process data of the given - * format. Passing data with different format to the compiled - * computation will generate a run-time exception. - * - * @param in_metas vector of input metadata configuration. Grab - * metadata from real data objects (like cv::Mat or cv::Scalar) - * using cv::descr_of(), or create it on your own. - * @param args compilation arguments for this compilation - * process. Compilation arguments directly affect what kind of - * executable object would be produced, e.g. which kernels (and - * thus, devices) would be used to execute computation. - * - * @return GCompiled, an executable computation compiled - * specifically for the given input parameters. - * - * @sa @ref gapi_compile_args - */ - GCompiled compile(GMetaArgs &&in_metas, GCompileArgs &&args = {}); - - // 2. Syntax sugar - variadic list of metas, no extra compile args - // FIXME: SFINAE looks ugly in the generated documentation - /** - * @overload - * - * Takes a variadic parameter pack with metadata - * descriptors for which a compiled object needs to be produced. - * - * @return GCompiled, an executable computation compiled - * specifically for the given input parameters. - */ - template - auto compile(const Ts&... metas) -> - typename std::enable_if::value, GCompiled>::type - { - return compile(GMetaArgs{GMetaArg(metas)...}, GCompileArgs()); - } - - // 3. Syntax sugar - variadic list of metas, extra compile args - // (seems optional parameters don't work well when there's an variadic template - // comes first) - // - // Ideally it should look like: - // - // template - // GCompiled compile(const Ts&... metas, GCompileArgs &&args) - // - // But not all compilers can handle this (and seems they shouldn't be able to). - // FIXME: SFINAE looks ugly in the generated documentation - /** - * @overload - * - * Takes a variadic parameter pack with metadata - * descriptors for which a compiled object needs to be produced, - * followed by GCompileArgs object representing compilation - * arguments for this process. - * - * @return GCompiled, an executable computation compiled - * specifically for the given input parameters. - */ - template - auto compile(const Ts&... meta_and_compile_args) -> - typename std::enable_if::value - && std::is_same >::value, - GCompiled>::type - { - //FIXME: wrapping meta_and_compile_args into a tuple to unwrap them inside a helper function is the overkill - return compile(std::make_tuple(meta_and_compile_args...), - typename detail::MkSeq::type()); - } - - - // FIXME: Document properly in the Doxygen format - // Video-oriented pipeline compilation: - // 1. A generic version - /** - * @brief Compile the computation for streaming mode. - * - * This method triggers compilation process and produces a new - * GStreamingCompiled object which then can process video stream - * data of the given format. Passing a stream in a different - * format to the compiled computation will generate a run-time - * exception. - * - * @param in_metas vector of input metadata configuration. Grab - * metadata from real data objects (like cv::Mat or cv::Scalar) - * using cv::descr_of(), or create it on your own. - * - * @param args compilation arguments for this compilation - * process. Compilation arguments directly affect what kind of - * executable object would be produced, e.g. which kernels (and - * thus, devices) would be used to execute computation. - * - * @return GStreamingCompiled, a streaming-oriented executable - * computation compiled specifically for the given input - * parameters. - * - * @sa @ref gapi_compile_args - */ - GAPI_WRAP GStreamingCompiled compileStreaming(GMetaArgs &&in_metas, GCompileArgs &&args = {}); - - /** - * @brief Compile the computation for streaming mode. - * - * This method triggers compilation process and produces a new - * GStreamingCompiled object which then can process video stream - * data in any format. Underlying mechanisms will be adjusted to - * every new input video stream automatically, but please note that - * _not all_ existing backends support this (see reshape()). - * - * @param args compilation arguments for this compilation - * process. Compilation arguments directly affect what kind of - * executable object would be produced, e.g. which kernels (and - * thus, devices) would be used to execute computation. - * - * @return GStreamingCompiled, a streaming-oriented executable - * computation compiled for any input image format. - * - * @sa @ref gapi_compile_args - */ - GAPI_WRAP GStreamingCompiled compileStreaming(GCompileArgs &&args = {}); - - /// @private -- Exclude this function from OpenCV documentation - GAPI_WRAP GStreamingCompiled compileStreaming(const cv::detail::ExtractMetaCallback &callback, - GCompileArgs &&args = {}); - - // 2. Direct metadata version - /** - * @overload - * - * Takes a variadic parameter pack with metadata - * descriptors for which a compiled object needs to be produced. - * - * @return GStreamingCompiled, a streaming-oriented executable - * computation compiled specifically for the given input - * parameters. - */ - template - auto compileStreaming(const Ts&... metas) -> - typename std::enable_if::value, GStreamingCompiled>::type - { - return compileStreaming(GMetaArgs{GMetaArg(metas)...}, GCompileArgs()); - } - - // 2. Direct metadata + compile arguments version - /** - * @overload - * - * Takes a variadic parameter pack with metadata - * descriptors for which a compiled object needs to be produced, - * followed by GCompileArgs object representing compilation - * arguments for this process. - * - * @return GStreamingCompiled, a streaming-oriented executable - * computation compiled specifically for the given input - * parameters. - */ - template - auto compileStreaming(const Ts&... meta_and_compile_args) -> - typename std::enable_if::value - && std::is_same >::value, - GStreamingCompiled>::type - { - //FIXME: wrapping meta_and_compile_args into a tuple to unwrap them inside a helper function is the overkill - return compileStreaming(std::make_tuple(meta_and_compile_args...), - typename detail::MkSeq::type()); - } - - // Internal use only - /// @private - Priv& priv(); - /// @private - const Priv& priv() const; - /// @private - explicit GComputation(cv::gapi::s11n::IIStream &); - /// @private - void serialize(cv::gapi::s11n::IOStream &) const; - -protected: - - // 4. Helper methods for (3) - /// @private - template - GCompiled compile(const std::tuple &meta_and_compile_args, detail::Seq) - { - GMetaArgs meta_args = {GMetaArg(std::get(meta_and_compile_args))...}; - GCompileArgs comp_args = std::get(meta_and_compile_args); - return compile(std::move(meta_args), std::move(comp_args)); - } - template - GStreamingCompiled compileStreaming(const std::tuple &meta_and_compile_args, detail::Seq) - { - GMetaArgs meta_args = {GMetaArg(std::get(meta_and_compile_args))...}; - GCompileArgs comp_args = std::get(meta_and_compile_args); - return compileStreaming(std::move(meta_args), std::move(comp_args)); - } - void recompile(GMetaArgs&& in_metas, GCompileArgs &&args); - /// @private - std::shared_ptr m_priv; -}; -/** @} */ - -namespace gapi -{ - // FIXME: all these standalone functions need to be added to some - // common documentation section - /** - * @brief Define an tagged island (subgraph) within a computation. - * - * Declare an Island tagged with `name` and defined from `ins` to `outs` - * (exclusively, as ins/outs are data objects, and regioning is done on - * operations level). - * Throws if any operation between `ins` and `outs` are already assigned - * to another island. - * - * Islands allow to partition graph into subgraphs, fine-tuning - * the way it is scheduled by the underlying executor. - * - * @param name name of the Island to create - * @param ins vector of input data objects where the subgraph - * begins - * @param outs vector of output data objects where the subgraph - * ends. - * - * The way how an island is defined is similar to how - * cv::GComputation is defined on input/output data objects. - * Same rules apply here as well -- if there's no functional - * dependency between inputs and outputs or there's not enough - * input data objects were specified to properly calculate all - * outputs, an exception is thrown. - * - * Use cv::GIn() / cv::GOut() to specify input/output vectors. - */ - void GAPI_EXPORTS island(const std::string &name, - GProtoInputArgs &&ins, - GProtoOutputArgs &&outs); -} // namespace gapi - -} // namespace cv -#endif // OPENCV_GAPI_GCOMPUTATION_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_GCOMPUTATION_HPP +#define OPENCV_GAPI_GCOMPUTATION_HPP + +#include + +#include +#include +#include +#include +#include +#include + +namespace cv { + +namespace detail +{ + // FIXME: move to algorithm, cover with separate tests + // FIXME: replace with O(1) version (both memory and compilation time) + template + struct last_type; + + template + struct last_type { using type = T;}; + + template + struct last_type { using type = typename last_type::type; }; + + template + using last_type_t = typename last_type::type; +} + +// Forward-declare the serialization objects +namespace gapi { +namespace s11n { + struct IIStream; + struct IOStream; +} // namespace s11n +} // namespace gapi + +/** + * \addtogroup gapi_main_classes + * @{ + * + * @brief G-API classes for constructed and compiled graphs. + */ + +/** + * @brief GComputation class represents a captured computation + * graph. GComputation objects form boundaries for expression code + * user writes with G-API, allowing to compile and execute it. + * + * G-API computations are defined with input/output data + * objects. G-API will track automatically which operations connect + * specified outputs to the inputs, forming up a call graph to be + * executed. The below example expresses calculation of Sobel operator + * for edge detection (\f$G = \sqrt{G_x^2 + G_y^2}\f$): + * + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp graph_def + * + * Full pipeline can be now captured with this object declaration: + * + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp graph_cap_full + * + * Input/output data objects on which a call graph should be + * reconstructed are passed using special wrappers cv::GIn and + * cv::GOut. G-API will track automatically which operations form a + * path from inputs to outputs and build the execution graph appropriately. + * + * Note that cv::GComputation doesn't take ownership on data objects + * it is defined. Moreover, multiple GComputation objects may be + * defined on the same expressions, e.g. a smaller pipeline which + * expects that image gradients are already pre-calculated may be + * defined like this: + * + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp graph_cap_sub + * + * The resulting graph would expect two inputs and produce one + * output. In this case, it doesn't matter if gx/gy data objects are + * results of cv::gapi::Sobel operators -- G-API will stop unrolling + * expressions and building the underlying graph one reaching this + * data objects. + * + * The way how GComputation is defined is important as its definition + * specifies graph _protocol_ -- the way how the graph should be + * used. Protocol is defined by number of inputs, number of outputs, + * and shapes of inputs and outputs. + * + * In the above example, sobelEdge expects one Mat on input and + * produces one Mat; while sobelEdgeSub expects two Mats on input and + * produces one Mat. GComputation's protocol defines how other + * computation methods should be used -- cv::GComputation::compile() and + * cv::GComputation::apply(). For example, if a graph is defined on + * two GMat inputs, two cv::Mat objects have to be passed to apply() + * for execution. GComputation checks protocol correctness in runtime + * so passing a different number of objects in apply() or passing + * cv::Scalar instead of cv::Mat there would compile well as a C++ + * source but raise an exception in run-time. G-API also comes with a + * typed wrapper cv::GComputationT<> which introduces this type-checking in + * compile-time. + * + * cv::GComputation itself is a thin object which just captures what + * the graph is. The compiled graph (which actually process data) is + * represented by class GCompiled. Use compile() method to generate a + * compiled graph with given compile options. cv::GComputation can + * also be used to process data with implicit graph compilation + * on-the-fly, see apply() for details. + * + * GComputation is a reference-counted object -- once defined, all its + * copies will refer to the same instance. + * + * @sa GCompiled + */ +class GAPI_EXPORTS_W GComputation +{ +public: + class Priv; + typedef std::function Generator; + + // Various constructors enable different ways to define a computation: ///// + // 1. Generic constructors + /** + * @brief Define a computation using a generator function. + * + * Graph can be defined in-place directly at the moment of its + * construction with a lambda: + * + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp graph_gen + * + * This may be useful since all temporary objects (cv::GMats) and + * namespaces can be localized to scope of lambda, without + * contaminating the parent scope with probably unnecessary objects + * and information. + * + * @param gen generator function which returns a cv::GComputation, + * see Generator. + */ + GComputation(const Generator& gen); // Generator + // overload + + /** + * @brief Generic GComputation constructor. + * + * Constructs a new graph with a given protocol, specified as a + * flow of operations connecting input/output objects. Throws if + * the passed boundaries are invalid, e.g. if there's no + * functional dependency (path) between given outputs and inputs. + * + * @param ins Input data vector. + * @param outs Output data vector. + * + * @note Don't construct GProtoInputArgs/GProtoOutputArgs objects + * directly, use cv::GIn()/cv::GOut() wrapper functions instead. + * + * @sa @ref gapi_data_objects + */ + GAPI_WRAP GComputation(GProtoInputArgs &&ins, + GProtoOutputArgs &&outs); // Arg-to-arg overload + + // 2. Syntax sugar and compatibility overloads + /** + * @brief Defines an unary (one input -- one output) computation + * + * @overload + * @param in input GMat of the defined unary computation + * @param out output GMat of the defined unary computation + */ + GAPI_WRAP GComputation(GMat in, GMat out); // Unary overload + + /** + * @brief Defines an unary (one input -- one output) computation + * + * @overload + * @param in input GMat of the defined unary computation + * @param out output GScalar of the defined unary computation + */ + GAPI_WRAP GComputation(GMat in, GScalar out); // Unary overload (scalar) + + /** + * @brief Defines a binary (two inputs -- one output) computation + * + * @overload + * @param in1 first input GMat of the defined binary computation + * @param in2 second input GMat of the defined binary computation + * @param out output GMat of the defined binary computation + */ + GAPI_WRAP GComputation(GMat in1, GMat in2, GMat out); // Binary overload + + /** + * @brief Defines a binary (two inputs -- one output) computation + * + * @overload + * @param in1 first input GMat of the defined binary computation + * @param in2 second input GMat of the defined binary computation + * @param out output GScalar of the defined binary computation + */ + GComputation(GMat in1, GMat in2, GScalar out); // Binary + // overload + // (scalar) + + /** + * @brief Defines a computation with arbitrary input/output number. + * + * @overload + * @param ins vector of inputs GMats for this computation + * @param outs vector of outputs GMats for this computation + * + * Use this overload for cases when number of computation + * inputs/outputs is not known in compile-time -- e.g. when graph + * is programmatically generated to build an image pyramid with + * the given number of levels, etc. + */ + GComputation(const std::vector &ins, // Compatibility overload + const std::vector &outs); + + // Various versions of apply(): //////////////////////////////////////////// + // 1. Generic apply() + /** + * @brief Compile graph on-the-fly and immediately execute it on + * the inputs data vectors. + * + * Number of input/output data objects must match GComputation's + * protocol, also types of host data objects (cv::Mat, cv::Scalar) + * must match the shapes of data objects from protocol (cv::GMat, + * cv::GScalar). If there's a mismatch, a run-time exception will + * be generated. + * + * Internally, a cv::GCompiled object is created for the given + * input format configuration, which then is executed on the input + * data immediately. cv::GComputation caches compiled objects + * produced within apply() -- if this method would be called next + * time with the same input parameters (image formats, image + * resolution, etc), the underlying compiled graph will be reused + * without recompilation. If new metadata doesn't match the cached + * one, the underlying compiled graph is regenerated. + * + * @note compile() always triggers a compilation process and + * produces a new GCompiled object regardless if a similar one has + * been cached via apply() or not. + * + * @param ins vector of input data to process. Don't create + * GRunArgs object manually, use cv::gin() wrapper instead. + * @param outs vector of output data to fill results in. cv::Mat + * objects may be empty in this vector, G-API will automatically + * initialize it with the required format & dimensions. Don't + * create GRunArgsP object manually, use cv::gout() wrapper instead. + * @param args a list of compilation arguments to pass to the + * underlying compilation process. Don't create GCompileArgs + * object manually, use cv::compile_args() wrapper instead. + * + * @sa @ref gapi_data_objects, @ref gapi_compile_args + */ + void apply(GRunArgs &&ins, GRunArgsP &&outs, GCompileArgs &&args = {}); // Arg-to-arg overload + + /// @private -- Exclude this function from OpenCV documentation + GAPI_WRAP GRunArgs apply(const cv::detail::ExtractArgsCallback &callback, + GCompileArgs &&args = {}); + + /// @private -- Exclude this function from OpenCV documentation + void apply(const std::vector& ins, // Compatibility overload + const std::vector& outs, + GCompileArgs &&args = {}); + + // 2. Syntax sugar and compatibility overloads +#if !defined(GAPI_STANDALONE) + /** + * @brief Execute an unary computation (with compilation on the fly) + * + * @overload + * @param in input cv::Mat for unary computation + * @param out output cv::Mat for unary computation + * @param args compilation arguments for underlying compilation + * process. + */ + void apply(cv::Mat in, cv::Mat &out, GCompileArgs &&args = {}); // Unary overload + + /** + * @brief Execute an unary computation (with compilation on the fly) + * + * @overload + * @param in input cv::Mat for unary computation + * @param out output cv::Scalar for unary computation + * @param args compilation arguments for underlying compilation + * process. + */ + void apply(cv::Mat in, cv::Scalar &out, GCompileArgs &&args = {}); // Unary overload (scalar) + + /** + * @brief Execute a binary computation (with compilation on the fly) + * + * @overload + * @param in1 first input cv::Mat for binary computation + * @param in2 second input cv::Mat for binary computation + * @param out output cv::Mat for binary computation + * @param args compilation arguments for underlying compilation + * process. + */ + void apply(cv::Mat in1, cv::Mat in2, cv::Mat &out, GCompileArgs &&args = {}); // Binary overload + + /** + * @brief Execute an binary computation (with compilation on the fly) + * + * @overload + * @param in1 first input cv::Mat for binary computation + * @param in2 second input cv::Mat for binary computation + * @param out output cv::Scalar for binary computation + * @param args compilation arguments for underlying compilation + * process. + */ + void apply(cv::Mat in1, cv::Mat in2, cv::Scalar &out, GCompileArgs &&args = {}); // Binary overload (scalar) + + /** + * @brief Execute a computation with arbitrary number of + * inputs/outputs (with compilation on-the-fly). + * + * @overload + * @param ins vector of input cv::Mat objects to process by the + * computation. + * @param outs vector of output cv::Mat objects to produce by the + * computation. + * @param args compilation arguments for underlying compilation + * process. + * + * Numbers of elements in ins/outs vectors must match numbers of + * inputs/outputs which were used to define this GComputation. + */ + void apply(const std::vector& ins, // Compatibility overload + std::vector& outs, + GCompileArgs &&args = {}); +#endif // !defined(GAPI_STANDALONE) + // Various versions of compile(): ////////////////////////////////////////// + // 1. Generic compile() - requires metas to be passed as vector + /** + * @brief Compile the computation for specific input format(s). + * + * This method triggers compilation process and produces a new + * GCompiled object which then can process data of the given + * format. Passing data with different format to the compiled + * computation will generate a run-time exception. + * + * @param in_metas vector of input metadata configuration. Grab + * metadata from real data objects (like cv::Mat or cv::Scalar) + * using cv::descr_of(), or create it on your own. + * @param args compilation arguments for this compilation + * process. Compilation arguments directly affect what kind of + * executable object would be produced, e.g. which kernels (and + * thus, devices) would be used to execute computation. + * + * @return GCompiled, an executable computation compiled + * specifically for the given input parameters. + * + * @sa @ref gapi_compile_args + */ + GCompiled compile(GMetaArgs &&in_metas, GCompileArgs &&args = {}); + + // 2. Syntax sugar - variadic list of metas, no extra compile args + // FIXME: SFINAE looks ugly in the generated documentation + /** + * @overload + * + * Takes a variadic parameter pack with metadata + * descriptors for which a compiled object needs to be produced. + * + * @return GCompiled, an executable computation compiled + * specifically for the given input parameters. + */ + template + auto compile(const Ts&... metas) -> + typename std::enable_if::value, GCompiled>::type + { + return compile(GMetaArgs{GMetaArg(metas)...}, GCompileArgs()); + } + + // 3. Syntax sugar - variadic list of metas, extra compile args + // (seems optional parameters don't work well when there's an variadic template + // comes first) + // + // Ideally it should look like: + // + // template + // GCompiled compile(const Ts&... metas, GCompileArgs &&args) + // + // But not all compilers can handle this (and seems they shouldn't be able to). + // FIXME: SFINAE looks ugly in the generated documentation + /** + * @overload + * + * Takes a variadic parameter pack with metadata + * descriptors for which a compiled object needs to be produced, + * followed by GCompileArgs object representing compilation + * arguments for this process. + * + * @return GCompiled, an executable computation compiled + * specifically for the given input parameters. + */ + template + auto compile(const Ts&... meta_and_compile_args) -> + typename std::enable_if::value + && std::is_same >::value, + GCompiled>::type + { + //FIXME: wrapping meta_and_compile_args into a tuple to unwrap them inside a helper function is the overkill + return compile(std::make_tuple(meta_and_compile_args...), + typename detail::MkSeq::type()); + } + + + // FIXME: Document properly in the Doxygen format + // Video-oriented pipeline compilation: + // 1. A generic version + /** + * @brief Compile the computation for streaming mode. + * + * This method triggers compilation process and produces a new + * GStreamingCompiled object which then can process video stream + * data of the given format. Passing a stream in a different + * format to the compiled computation will generate a run-time + * exception. + * + * @param in_metas vector of input metadata configuration. Grab + * metadata from real data objects (like cv::Mat or cv::Scalar) + * using cv::descr_of(), or create it on your own. + * + * @param args compilation arguments for this compilation + * process. Compilation arguments directly affect what kind of + * executable object would be produced, e.g. which kernels (and + * thus, devices) would be used to execute computation. + * + * @return GStreamingCompiled, a streaming-oriented executable + * computation compiled specifically for the given input + * parameters. + * + * @sa @ref gapi_compile_args + */ + GAPI_WRAP GStreamingCompiled compileStreaming(GMetaArgs &&in_metas, GCompileArgs &&args = {}); + + /** + * @brief Compile the computation for streaming mode. + * + * This method triggers compilation process and produces a new + * GStreamingCompiled object which then can process video stream + * data in any format. Underlying mechanisms will be adjusted to + * every new input video stream automatically, but please note that + * _not all_ existing backends support this (see reshape()). + * + * @param args compilation arguments for this compilation + * process. Compilation arguments directly affect what kind of + * executable object would be produced, e.g. which kernels (and + * thus, devices) would be used to execute computation. + * + * @return GStreamingCompiled, a streaming-oriented executable + * computation compiled for any input image format. + * + * @sa @ref gapi_compile_args + */ + GAPI_WRAP GStreamingCompiled compileStreaming(GCompileArgs &&args = {}); + + /// @private -- Exclude this function from OpenCV documentation + GAPI_WRAP GStreamingCompiled compileStreaming(const cv::detail::ExtractMetaCallback &callback, + GCompileArgs &&args = {}); + + // 2. Direct metadata version + /** + * @overload + * + * Takes a variadic parameter pack with metadata + * descriptors for which a compiled object needs to be produced. + * + * @return GStreamingCompiled, a streaming-oriented executable + * computation compiled specifically for the given input + * parameters. + */ + template + auto compileStreaming(const Ts&... metas) -> + typename std::enable_if::value, GStreamingCompiled>::type + { + return compileStreaming(GMetaArgs{GMetaArg(metas)...}, GCompileArgs()); + } + + // 2. Direct metadata + compile arguments version + /** + * @overload + * + * Takes a variadic parameter pack with metadata + * descriptors for which a compiled object needs to be produced, + * followed by GCompileArgs object representing compilation + * arguments for this process. + * + * @return GStreamingCompiled, a streaming-oriented executable + * computation compiled specifically for the given input + * parameters. + */ + template + auto compileStreaming(const Ts&... meta_and_compile_args) -> + typename std::enable_if::value + && std::is_same >::value, + GStreamingCompiled>::type + { + //FIXME: wrapping meta_and_compile_args into a tuple to unwrap them inside a helper function is the overkill + return compileStreaming(std::make_tuple(meta_and_compile_args...), + typename detail::MkSeq::type()); + } + + // Internal use only + /// @private + Priv& priv(); + /// @private + const Priv& priv() const; + /// @private + explicit GComputation(cv::gapi::s11n::IIStream &); + /// @private + void serialize(cv::gapi::s11n::IOStream &) const; + +protected: + + // 4. Helper methods for (3) + /// @private + template + GCompiled compile(const std::tuple &meta_and_compile_args, detail::Seq) + { + GMetaArgs meta_args = {GMetaArg(std::get(meta_and_compile_args))...}; + GCompileArgs comp_args = std::get(meta_and_compile_args); + return compile(std::move(meta_args), std::move(comp_args)); + } + template + GStreamingCompiled compileStreaming(const std::tuple &meta_and_compile_args, detail::Seq) + { + GMetaArgs meta_args = {GMetaArg(std::get(meta_and_compile_args))...}; + GCompileArgs comp_args = std::get(meta_and_compile_args); + return compileStreaming(std::move(meta_args), std::move(comp_args)); + } + void recompile(GMetaArgs&& in_metas, GCompileArgs &&args); + /// @private + std::shared_ptr m_priv; +}; +/** @} */ + +namespace gapi +{ + // FIXME: all these standalone functions need to be added to some + // common documentation section + /** + * @brief Define an tagged island (subgraph) within a computation. + * + * Declare an Island tagged with `name` and defined from `ins` to `outs` + * (exclusively, as ins/outs are data objects, and regioning is done on + * operations level). + * Throws if any operation between `ins` and `outs` are already assigned + * to another island. + * + * Islands allow to partition graph into subgraphs, fine-tuning + * the way it is scheduled by the underlying executor. + * + * @param name name of the Island to create + * @param ins vector of input data objects where the subgraph + * begins + * @param outs vector of output data objects where the subgraph + * ends. + * + * The way how an island is defined is similar to how + * cv::GComputation is defined on input/output data objects. + * Same rules apply here as well -- if there's no functional + * dependency between inputs and outputs or there's not enough + * input data objects were specified to properly calculate all + * outputs, an exception is thrown. + * + * Use cv::GIn() / cv::GOut() to specify input/output vectors. + */ + void GAPI_EXPORTS island(const std::string &name, + GProtoInputArgs &&ins, + GProtoOutputArgs &&outs); +} // namespace gapi + +} // namespace cv +#endif // OPENCV_GAPI_GCOMPUTATION_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gcomputation_async.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gcomputation_async.hpp index 8af603efea..c55410ebfa 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gcomputation_async.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gcomputation_async.hpp @@ -1,69 +1,69 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019 Intel Corporation - -#ifndef OPENCV_GAPI_GCOMPUTATION_ASYNC_HPP -#define OPENCV_GAPI_GCOMPUTATION_ASYNC_HPP - - -#include //for std::future -#include //for std::exception_ptr -#include //for std::function -#include //for GRunArgs, GRunArgsP -#include //for GCompileArgs -#include - - -namespace cv { - //fwd declaration - class GComputation; -namespace gapi { -namespace wip { - class GAsyncContext; - /** In contrast to async() functions, these do call GComputation::apply() member function of the GComputation passed in. - - @param gcomp Computation (graph) to run asynchronously - @param callback Callback to be called when execution of gcomp is done - @param ins Input parameters for gcomp - @param outs Output parameters for gcomp - @param args Compile arguments to pass to GComputation::apply() - @see async - */ - GAPI_EXPORTS void async_apply(GComputation& gcomp, std::function&& callback, GRunArgs &&ins, GRunArgsP &&outs, GCompileArgs &&args = {}); - /** @overload - @param gcomp Computation (graph) to run asynchronously - @param callback Callback to be called when execution of gcomp is done - @param ins Input parameters for gcomp - @param outs Output parameters for gcomp - @param args Compile arguments to pass to GComputation::apply() - @param ctx Context this request belongs to - @see async_apply async GAsyncContext - */ - GAPI_EXPORTS void async_apply(GComputation& gcomp, std::function&& callback, GRunArgs &&ins, GRunArgsP &&outs, GCompileArgs &&args, GAsyncContext& ctx); - /** @overload - @param gcomp Computation (graph) to run asynchronously - @param ins Input parameters for gcomp - @param outs Output parameters for gcomp - @param args Compile arguments to pass to GComputation::apply() - @return std::future object to wait for completion of async operation - @see async_apply async - */ - GAPI_EXPORTS std::future async_apply(GComputation& gcomp, GRunArgs &&ins, GRunArgsP &&outs, GCompileArgs &&args = {}); - /** @overload - @param gcomp Computation (graph) to run asynchronously - @param ins Input parameters for gcomp - @param outs Output parameters for gcomp - @param args Compile arguments to pass to GComputation::apply() - @param ctx Context this request belongs to - @return std::future object to wait for completion of async operation - @see async_apply async GAsyncContext - */ - GAPI_EXPORTS std::future async_apply(GComputation& gcomp, GRunArgs &&ins, GRunArgsP &&outs, GCompileArgs &&args, GAsyncContext& ctx); -} // namespace wip -} // namespace gapi -} // namespace cv - - -#endif //OPENCV_GAPI_GCOMPUTATION_ASYNC_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019 Intel Corporation + +#ifndef OPENCV_GAPI_GCOMPUTATION_ASYNC_HPP +#define OPENCV_GAPI_GCOMPUTATION_ASYNC_HPP + + +#include //for std::future +#include //for std::exception_ptr +#include //for std::function +#include //for GRunArgs, GRunArgsP +#include //for GCompileArgs +#include + + +namespace cv { + //fwd declaration + class GComputation; +namespace gapi { +namespace wip { + class GAsyncContext; + /** In contrast to async() functions, these do call GComputation::apply() member function of the GComputation passed in. + + @param gcomp Computation (graph) to run asynchronously + @param callback Callback to be called when execution of gcomp is done + @param ins Input parameters for gcomp + @param outs Output parameters for gcomp + @param args Compile arguments to pass to GComputation::apply() + @see async + */ + GAPI_EXPORTS void async_apply(GComputation& gcomp, std::function&& callback, GRunArgs &&ins, GRunArgsP &&outs, GCompileArgs &&args = {}); + /** @overload + @param gcomp Computation (graph) to run asynchronously + @param callback Callback to be called when execution of gcomp is done + @param ins Input parameters for gcomp + @param outs Output parameters for gcomp + @param args Compile arguments to pass to GComputation::apply() + @param ctx Context this request belongs to + @see async_apply async GAsyncContext + */ + GAPI_EXPORTS void async_apply(GComputation& gcomp, std::function&& callback, GRunArgs &&ins, GRunArgsP &&outs, GCompileArgs &&args, GAsyncContext& ctx); + /** @overload + @param gcomp Computation (graph) to run asynchronously + @param ins Input parameters for gcomp + @param outs Output parameters for gcomp + @param args Compile arguments to pass to GComputation::apply() + @return std::future object to wait for completion of async operation + @see async_apply async + */ + GAPI_EXPORTS std::future async_apply(GComputation& gcomp, GRunArgs &&ins, GRunArgsP &&outs, GCompileArgs &&args = {}); + /** @overload + @param gcomp Computation (graph) to run asynchronously + @param ins Input parameters for gcomp + @param outs Output parameters for gcomp + @param args Compile arguments to pass to GComputation::apply() + @param ctx Context this request belongs to + @return std::future object to wait for completion of async operation + @see async_apply async GAsyncContext + */ + GAPI_EXPORTS std::future async_apply(GComputation& gcomp, GRunArgs &&ins, GRunArgsP &&outs, GCompileArgs &&args, GAsyncContext& ctx); +} // namespace wip +} // namespace gapi +} // namespace cv + + +#endif //OPENCV_GAPI_GCOMPUTATION_ASYNC_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gframe.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gframe.hpp index 54fb30789e..7aefbe9e18 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gframe.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gframe.hpp @@ -1,113 +1,113 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020 Intel Corporation - - -#ifndef OPENCV_GAPI_GFRAME_HPP -#define OPENCV_GAPI_GFRAME_HPP - -#include -#include // std::shared_ptr - -#include -#include // GShape - -#include -#include - -// TODO GAPI_EXPORTS or so -namespace cv -{ -// Forward declaration; GNode and GOrigin are an internal -// (user-inaccessible) classes. -class GNode; -struct GOrigin; - -/** \addtogroup gapi_data_objects - * @{ - */ -/** - * @brief GFrame class represents an image or media frame in the graph. - * - * GFrame doesn't store any data itself, instead it describes a - * functional relationship between operations consuming and producing - * GFrame objects. - * - * GFrame is introduced to handle various media formats (e.g., NV12 or - * I420) under the same type. Various image formats may differ in the - * number of planes (e.g. two for NV12, three for I420) and the pixel - * layout inside. GFrame type allows to handle these media formats in - * the graph uniformly -- the graph structure will not change if the - * media format changes, e.g. a different camera or decoder is used - * with the same graph. G-API provides a number of operations which - * operate directly on GFrame, like `infer<>()` or - * renderFrame(); these operations are expected to handle different - * media formats inside. There is also a number of accessor - * operations like BGR(), Y(), UV() -- these operations provide - * access to frame's data in the familiar cv::GMat form, which can be - * used with the majority of the existing G-API operations. These - * accessor functions may perform color space conversion on the fly if - * the image format of the GFrame they are applied to differs from the - * operation's semantic (e.g. the BGR() accessor is called on an NV12 - * image frame). - * - * GFrame is a virtual counterpart of cv::MediaFrame. - * - * @sa cv::MediaFrame, cv::GFrameDesc, BGR(), Y(), UV(), infer<>(). - */ -class GAPI_EXPORTS_W_SIMPLE GFrame -{ -public: - /** - * @brief Constructs an empty GFrame - * - * Normally, empty G-API data objects denote a starting point of - * the graph. When an empty GFrame is assigned to a result of some - * operation, it obtains a functional link to this operation (and - * is not empty anymore). - */ - GAPI_WRAP GFrame(); // Empty constructor - - /// @private - GFrame(const GNode &n, std::size_t out); // Operation result constructor - /// @private - GOrigin& priv(); // Internal use only - /// @private - const GOrigin& priv() const; // Internal use only - -private: - std::shared_ptr m_priv; -}; -/** @} */ - -enum class MediaFormat: int -{ - BGR = 0, - NV12, - GRAY, -}; - -/** - * \addtogroup gapi_meta_args - * @{ - */ -struct GAPI_EXPORTS GFrameDesc -{ - MediaFormat fmt; - cv::Size size; - - bool operator== (const GFrameDesc &) const; -}; -static inline GFrameDesc empty_gframe_desc() { return GFrameDesc{}; } -/** @} */ - -class MediaFrame; -GAPI_EXPORTS GFrameDesc descr_of(const MediaFrame &frame); - -GAPI_EXPORTS std::ostream& operator<<(std::ostream& os, const cv::GFrameDesc &desc); - -} // namespace cv - -#endif // OPENCV_GAPI_GFRAME_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020 Intel Corporation + + +#ifndef OPENCV_GAPI_GFRAME_HPP +#define OPENCV_GAPI_GFRAME_HPP + +#include +#include // std::shared_ptr + +#include +#include // GShape + +#include +#include + +// TODO GAPI_EXPORTS or so +namespace cv +{ +// Forward declaration; GNode and GOrigin are an internal +// (user-inaccessible) classes. +class GNode; +struct GOrigin; + +/** \addtogroup gapi_data_objects + * @{ + */ +/** + * @brief GFrame class represents an image or media frame in the graph. + * + * GFrame doesn't store any data itself, instead it describes a + * functional relationship between operations consuming and producing + * GFrame objects. + * + * GFrame is introduced to handle various media formats (e.g., NV12 or + * I420) under the same type. Various image formats may differ in the + * number of planes (e.g. two for NV12, three for I420) and the pixel + * layout inside. GFrame type allows to handle these media formats in + * the graph uniformly -- the graph structure will not change if the + * media format changes, e.g. a different camera or decoder is used + * with the same graph. G-API provides a number of operations which + * operate directly on GFrame, like `infer<>()` or + * renderFrame(); these operations are expected to handle different + * media formats inside. There is also a number of accessor + * operations like BGR(), Y(), UV() -- these operations provide + * access to frame's data in the familiar cv::GMat form, which can be + * used with the majority of the existing G-API operations. These + * accessor functions may perform color space conversion on the fly if + * the image format of the GFrame they are applied to differs from the + * operation's semantic (e.g. the BGR() accessor is called on an NV12 + * image frame). + * + * GFrame is a virtual counterpart of cv::MediaFrame. + * + * @sa cv::MediaFrame, cv::GFrameDesc, BGR(), Y(), UV(), infer<>(). + */ +class GAPI_EXPORTS_W_SIMPLE GFrame +{ +public: + /** + * @brief Constructs an empty GFrame + * + * Normally, empty G-API data objects denote a starting point of + * the graph. When an empty GFrame is assigned to a result of some + * operation, it obtains a functional link to this operation (and + * is not empty anymore). + */ + GAPI_WRAP GFrame(); // Empty constructor + + /// @private + GFrame(const GNode &n, std::size_t out); // Operation result constructor + /// @private + GOrigin& priv(); // Internal use only + /// @private + const GOrigin& priv() const; // Internal use only + +private: + std::shared_ptr m_priv; +}; +/** @} */ + +enum class MediaFormat: int +{ + BGR = 0, + NV12, + GRAY, +}; + +/** + * \addtogroup gapi_meta_args + * @{ + */ +struct GAPI_EXPORTS GFrameDesc +{ + MediaFormat fmt; + cv::Size size; + + bool operator== (const GFrameDesc &) const; +}; +static inline GFrameDesc empty_gframe_desc() { return GFrameDesc{}; } +/** @} */ + +class MediaFrame; +GAPI_EXPORTS GFrameDesc descr_of(const MediaFrame &frame); + +GAPI_EXPORTS std::ostream& operator<<(std::ostream& os, const cv::GFrameDesc &desc); + +} // namespace cv + +#endif // OPENCV_GAPI_GFRAME_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gkernel.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gkernel.hpp index 6ec6bf573d..2cfd0fb877 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gkernel.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gkernel.hpp @@ -1,757 +1,757 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2021 Intel Corporation - - -#ifndef OPENCV_GAPI_GKERNEL_HPP -#define OPENCV_GAPI_GKERNEL_HPP - -#include -#include -#include // string -#include // false_type, true_type -#include // map (for GKernelPackage) -#include // tuple - -#include // CompileArgTag -#include // Seq -#include -#include // GArg -#include // GMetaArg -#include // GTypeTraits -#include //suppress_unused_warning -#include - -namespace cv { - -struct GTypeInfo -{ - GShape shape; - cv::detail::OpaqueKind kind; - detail::HostCtor ctor; -}; - -using GShapes = std::vector; -using GKinds = std::vector; -using GCtors = std::vector; -using GTypesInfo = std::vector; - -// GKernel describes kernel API to the system -// FIXME: add attributes of a kernel, (e.g. number and types -// of inputs, etc) -struct GAPI_EXPORTS GKernel -{ - using M = std::function; - - std::string name; // kernel ID, defined by its API (signature) - std::string tag; // some (implementation-specific) tag - M outMeta; // generic adaptor to API::outMeta(...) - GShapes outShapes; // types (shapes) kernel's outputs - GKinds inKinds; // kinds of kernel's inputs (fixme: below) - GCtors outCtors; // captured constructors for template output types - GKinds outKinds; // kinds of kernel's outputs (fixme: below) -}; -// TODO: It's questionable if inKinds should really be here. Instead, -// this information could come from meta. - -// GKernelImpl describes particular kernel implementation to the system -struct GAPI_EXPORTS GKernelImpl -{ - util::any opaque; // backend-specific opaque info - GKernel::M outMeta; // for deserialized graphs, the outMeta is taken here -}; - -template class GKernelTypeM; - -namespace detail -{ - //////////////////////////////////////////////////////////////////////////// - // yield() is used in graph construction time as a generic method to obtain - // lazy "return value" of G-API operations - // - template struct Yield; - template<> struct Yield - { - static inline cv::GMat yield(cv::GCall &call, int i) { return call.yield(i); } - }; - template<> struct Yield - { - static inline cv::GMatP yield(cv::GCall &call, int i) { return call.yieldP(i); } - }; - template<> struct Yield - { - static inline cv::GScalar yield(cv::GCall &call, int i) { return call.yieldScalar(i); } - }; - template struct Yield > - { - static inline cv::GArray yield(cv::GCall &call, int i) { return call.yieldArray(i); } - }; - template struct Yield > - { - static inline cv::GOpaque yield(cv::GCall &call, int i) { return call.yieldOpaque(i); } - }; - template<> struct Yield - { - static inline cv::GFrame yield(cv::GCall &call, int i) { return call.yieldFrame(i); } - }; - - //////////////////////////////////////////////////////////////////////////// - // Helper classes which brings outputMeta() marshalling to kernel - // implementations - // - // 1. MetaType establishes G#Type -> G#Meta mapping between G-API dynamic - // types and its metadata descriptor types. - // This mapping is used to transform types to call outMeta() callback. - template struct MetaType; - template<> struct MetaType { using type = GMatDesc; }; - template<> struct MetaType { using type = GMatDesc; }; - template<> struct MetaType { using type = GFrameDesc; }; - template<> struct MetaType { using type = GScalarDesc; }; - template struct MetaType > { using type = GArrayDesc; }; - template struct MetaType > { using type = GOpaqueDesc; }; - template struct MetaType { using type = T; }; // opaque args passed as-is - // FIXME: Move it to type traits? - - // 2. Hacky test based on MetaType to check if we operate on G-* type or not - template using is_nongapi_type = std::is_same::type>; - - // 3. Two ways to transform input arguments to its meta - for G-* and non-G* types: - template - typename std::enable_if::value, typename MetaType::type> - ::type get_in_meta(const GMetaArgs &in_meta, const GArgs &, int idx) - { - return util::get::type>(in_meta.at(idx)); - } - - template - typename std::enable_if::value, T> - ::type get_in_meta(const GMetaArgs &, const GArgs &in_args, int idx) - { - return in_args.at(idx).template get(); - } - - // 4. The MetaHelper itself: an entity which generates outMeta() call - // based on kernel signature, with arguments properly substituted. - // 4.1 - case for multiple return values - // FIXME: probably can be simplified with std::apply or analogue. - template - struct MetaHelper; - - template - struct MetaHelper, std::tuple > - { - template - static GMetaArgs getOutMeta_impl(const GMetaArgs &in_meta, - const GArgs &in_args, - detail::Seq, - detail::Seq) - { - // FIXME: decay? - using R = std::tuple::type...>; - const R r = K::outMeta( get_in_meta(in_meta, in_args, IIs)... ); - return GMetaArgs{ GMetaArg(std::get(r))... }; - } - // FIXME: help users identify how outMeta must look like (via default impl w/static_assert?) - - static GMetaArgs getOutMeta(const GMetaArgs &in_meta, - const GArgs &in_args) - { - return getOutMeta_impl(in_meta, - in_args, - typename detail::MkSeq::type(), - typename detail::MkSeq::type()); - } - }; - - // 4.1 - case for a single return value - // FIXME: How to avoid duplication here? - template - struct MetaHelper, Out > - { - template - static GMetaArgs getOutMeta_impl(const GMetaArgs &in_meta, - const GArgs &in_args, - detail::Seq) - { - // FIXME: decay? - using R = typename MetaType::type; - const R r = K::outMeta( get_in_meta(in_meta, in_args, IIs)... ); - return GMetaArgs{ GMetaArg(r) }; - } - // FIXME: help users identify how outMeta must look like (via default impl w/static_assert?) - - static GMetaArgs getOutMeta(const GMetaArgs &in_meta, - const GArgs &in_args) - { - return getOutMeta_impl(in_meta, - in_args, - typename detail::MkSeq::type()); - } - }; - - //////////////////////////////////////////////////////////////////////////// - // Helper class to introduce tags to calls. By default there's no tag - struct NoTag { - static constexpr const char *tag() { return ""; } - }; - -} // namespace detail - -// GKernelType and GKernelTypeM are base classes which implement typed ::on() -// method based on kernel signature. GKernelTypeM stands for multiple-return-value kernels -// -// G_TYPED_KERNEL and G_TYPED_KERNEL_M macros inherit user classes from GKernelType and -// GKernelTypeM respectively. - -template -class GKernelTypeM(Args...)> > - : public detail::MetaHelper, std::tuple> - , public detail::NoTag -{ - template - static std::tuple yield(cv::GCall &call, detail::Seq) - { - return std::make_tuple(detail::Yield::yield(call, IIs)...); - } - -public: - using InArgs = std::tuple; - using OutArgs = std::tuple; - - // TODO: Args&&... here? - static std::tuple on(Args... args) - { - cv::GCall call(GKernel{ K::id() - , K::tag() - , &K::getOutMeta - , {detail::GTypeTraits::shape...} - , {detail::GTypeTraits::op_kind...} - , {detail::GObtainCtor::get()...} - , {detail::GTypeTraits::op_kind...}}); - call.pass(args...); // TODO: std::forward() here? - return yield(call, typename detail::MkSeq::type()); - } -}; - -template class GKernelType; - -template -class GKernelType > - : public detail::MetaHelper, R> - , public detail::NoTag -{ -public: - using InArgs = std::tuple; - using OutArgs = std::tuple; - - static R on(Args... args) - { - cv::GCall call(GKernel{ K::id() - , K::tag() - , &K::getOutMeta - , {detail::GTypeTraits::shape} - , {detail::GTypeTraits::op_kind...} - , {detail::GObtainCtor::get()} - , {detail::GTypeTraits::op_kind}}); - call.pass(args...); - return detail::Yield::yield(call, 0); - } -}; - -namespace detail { -// This tiny class eliminates the semantic difference between -// GKernelType and GKernelTypeM. -template class KernelTypeMedium; - -template -class KernelTypeMedium(Args...)>> : - public cv::GKernelTypeM(Args...)>> {}; - -template -class KernelTypeMedium> : - public cv::GKernelType> {}; -} // namespace detail - -} // namespace cv - - -// FIXME: I don't know a better way so far. Feel free to suggest one -// The problem is that every typed kernel should have ::id() but body -// of the class is defined by user (with outMeta, other stuff) - -//! @cond IGNORED -#define G_ID_HELPER_CLASS(Class) Class##IdHelper - -#define G_ID_HELPER_BODY(Class, Id) \ - struct G_ID_HELPER_CLASS(Class) \ - { \ - static constexpr const char * id() {return Id;} \ - }; \ -//! @endcond - -#define GET_G_TYPED_KERNEL(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, NAME, ...) NAME -#define COMBINE_SIGNATURE(...) __VA_ARGS__ -// Ensure correct __VA_ARGS__ expansion on Windows -#define __WRAP_VAARGS(x) x - -/** - * Helper for G_TYPED_KERNEL declares a new G-API Operation. See [Kernel API](@ref gapi_kernel_api) - * for more details. - * - * @param Class type name for this operation. - * @param API an `std::function<>`-like signature for the operation; - * return type is a single value or a tuple of multiple values. - * @param Id string identifier for the operation. Must be unique. - */ -#define G_TYPED_KERNEL_HELPER(Class, API, Id) \ - G_ID_HELPER_BODY(Class, Id) \ - struct Class final: public cv::detail::KernelTypeMedium, \ - public G_ID_HELPER_CLASS(Class) -// {body} is to be defined by user - -#define G_TYPED_KERNEL_HELPER_2(Class, _1, _2, Id) \ -G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2), Id) - -#define G_TYPED_KERNEL_HELPER_3(Class, _1, _2, _3, Id) \ -G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3), Id) - -#define G_TYPED_KERNEL_HELPER_4(Class, _1, _2, _3, _4, Id) \ -G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4), Id) - -#define G_TYPED_KERNEL_HELPER_5(Class, _1, _2, _3, _4, _5, Id) \ -G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5), Id) - -#define G_TYPED_KERNEL_HELPER_6(Class, _1, _2, _3, _4, _5, _6, Id) \ -G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6), Id) - -#define G_TYPED_KERNEL_HELPER_7(Class, _1, _2, _3, _4, _5, _6, _7, Id) \ -G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6, _7), Id) - -#define G_TYPED_KERNEL_HELPER_8(Class, _1, _2, _3, _4, _5, _6, _7, _8, Id) \ -G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6, _7, _8), Id) - -#define G_TYPED_KERNEL_HELPER_9(Class, _1, _2, _3, _4, _5, _6, _7, _8, _9, Id) \ -G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6, _7, _8, _9), Id) - -#define G_TYPED_KERNEL_HELPER_10(Class, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, Id) \ -G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10), Id) - -/** - * Declares a new G-API Operation. See [Kernel API](@ref gapi_kernel_api) - * for more details. - * - * @param Class type name for this operation. - */ -#define G_TYPED_KERNEL(Class, ...) __WRAP_VAARGS(GET_G_TYPED_KERNEL(__VA_ARGS__, \ - G_TYPED_KERNEL_HELPER_10, \ - G_TYPED_KERNEL_HELPER_9, \ - G_TYPED_KERNEL_HELPER_8, \ - G_TYPED_KERNEL_HELPER_7, \ - G_TYPED_KERNEL_HELPER_6, \ - G_TYPED_KERNEL_HELPER_5, \ - G_TYPED_KERNEL_HELPER_4, \ - G_TYPED_KERNEL_HELPER_3, \ - G_TYPED_KERNEL_HELPER_2, \ - G_TYPED_KERNEL_HELPER)(Class, __VA_ARGS__)) \ - -/** - * Declares a new G-API Operation. See [Kernel API](@ref gapi_kernel_api) for more details. - * - * @deprecated This macro is deprecated in favor of `G_TYPED_KERNEL` that is used for declaring any - * G-API Operation. - * - * @param Class type name for this operation. - */ -#define G_TYPED_KERNEL_M G_TYPED_KERNEL - -#define G_API_OP G_TYPED_KERNEL -#define G_API_OP_M G_API_OP - -namespace cv -{ -namespace gapi -{ - // Prework: model "Device" API before it gets to G-API headers. - // FIXME: Don't mix with internal Backends class! - /// @private - class GAPI_EXPORTS GBackend - { - public: - class Priv; - - // TODO: make it template (call `new` within??) - GBackend(); - explicit GBackend(std::shared_ptr &&p); - - Priv& priv(); - const Priv& priv() const; - std::size_t hash() const; - - bool operator== (const GBackend &rhs) const; - - private: - std::shared_ptr m_priv; - }; - - inline bool operator != (const GBackend &lhs, const GBackend &rhs) - { - return !(lhs == rhs); - } -} // namespace gapi -} // namespace cv - -namespace std -{ - template<> struct hash - { - std::size_t operator() (const cv::gapi::GBackend &b) const - { - return b.hash(); - } - }; -} // namespace std - -namespace cv { - class GAPI_EXPORTS_W_SIMPLE GKernelPackage; - -namespace gapi { - GAPI_EXPORTS_W cv::GKernelPackage combine(const cv::GKernelPackage &lhs, - const cv::GKernelPackage &rhs); - - /// @private - class GFunctor - { - public: - virtual cv::GKernelImpl impl() const = 0; - virtual cv::gapi::GBackend backend() const = 0; - const char* id() const { return m_id; } - - virtual ~GFunctor() = default; - protected: - GFunctor(const char* id) : m_id(id) { } - private: - const char* m_id; - }; -} // namespace gapi - - /** \addtogroup gapi_compile_args - * @{ - */ - - // FIXME: Hide implementation - /** - * @brief A container class for heterogeneous kernel - * implementation collections and graph transformations. - * - * GKernelPackage is a special container class which stores kernel - * _implementations_ and graph _transformations_. Objects of this class - * are created and passed to cv::GComputation::compile() to specify - * which kernels to use and which transformations to apply in the - * compiled graph. GKernelPackage may contain kernels of - * different backends, e.g. be heterogeneous. - * - * The most easy way to create a kernel package is to use function - * cv::gapi::kernels(). This template functions takes kernel - * implementations in form of type list (variadic template) and - * generates a kernel package atop of that. - * - * Kernel packages can be also generated programmatically, starting - * with an empty package (created with the default constructor) - * and then by populating it with kernels via call to - * GKernelPackage::include(). Note this method is also a template - * one since G-API kernel and transformation implementations are _types_, - * not objects. - * - * Finally, two kernel packages can be combined into a new one - * with function cv::gapi::combine(). - */ - class GAPI_EXPORTS_W_SIMPLE GKernelPackage - { - - /// @private - using M = std::unordered_map>; - - /// @private - M m_id_kernels; - - /// @private - std::vector m_transformations; - - protected: - /// @private - // Remove ALL implementations of the given API (identified by ID) - void removeAPI(const std::string &id); - - /// @private - // Partial include() specialization for kernels - template - typename std::enable_if<(std::is_base_of::value), void>::type - includeHelper() - { - auto backend = KImpl::backend(); - auto kernel_id = KImpl::API::id(); - auto kernel_impl = GKernelImpl{KImpl::kernel(), &KImpl::API::getOutMeta}; - removeAPI(kernel_id); - - m_id_kernels[kernel_id] = std::make_pair(backend, kernel_impl); - } - - /// @private - // Partial include() specialization for transformations - template - typename std::enable_if<(std::is_base_of::value), void>::type - includeHelper() - { - m_transformations.emplace_back(TImpl::transformation()); - } - - public: - void include(const cv::gapi::GFunctor& functor); - - /** - * @brief Returns total number of kernels - * in the package (across all backends included) - * - * @return a number of kernels in the package - */ - GAPI_WRAP std::size_t size() const; - - /** - * @brief Returns vector of transformations included in the package - * - * @return vector of transformations included in the package - */ - const std::vector& get_transformations() const; - - /** - * @brief Returns vector of kernel ids included in the package - * - * @return vector of kernel ids included in the package - */ - std::vector get_kernel_ids() const; - - /** - * @brief Test if a particular kernel _implementation_ KImpl is - * included in this kernel package. - * - * @sa includesAPI() - * - * @note cannot be applied to transformations - * - * @return true if there is such kernel, false otherwise. - */ - template - bool includes() const - { - static_assert(std::is_base_of::value, - "includes() can be applied to kernels only"); - - auto kernel_it = m_id_kernels.find(KImpl::API::id()); - return kernel_it != m_id_kernels.end() && - kernel_it->second.first == KImpl::backend(); - } - - /** - * @brief Remove all kernels associated with the given backend - * from the package. - * - * Does nothing if there's no kernels of this backend in the package. - * - * @param backend backend which kernels to remove - */ - void remove(const cv::gapi::GBackend& backend); - - /** - * @brief Remove all kernels implementing the given API from - * the package. - * - * Does nothing if there's no kernels implementing the given interface. - */ - template - void remove() - { - removeAPI(KAPI::id()); - } - - // FIXME: Rename to includes() and distinguish API/impl case by - // statically? - /** - * Check if package contains ANY implementation of a kernel API - * by API type. - */ - template - bool includesAPI() const - { - return includesAPI(KAPI::id()); - } - - /// @private - bool includesAPI(const std::string &id) const; - - // FIXME: The below comment is wrong, and who needs this function? - /** - * @brief Find a kernel (by its API) - * - * Returns implementation corresponding id. - * Throws if nothing found. - * - * @return Backend which hosts matching kernel implementation. - * - */ - template - cv::gapi::GBackend lookup() const - { - return lookup(KAPI::id()).first; - } - - /// @private - std::pair - lookup(const std::string &id) const; - - // FIXME: No overwrites allowed? - /** - * @brief Put a new kernel implementation or a new transformation - * KImpl into the package. - */ - template - void include() - { - includeHelper(); - } - - /** - * @brief Adds a new kernel based on it's backend and id into the kernel package - * - * @param backend backend associated with the kernel - * @param kernel_id a name/id of the kernel - */ - void include(const cv::gapi::GBackend& backend, const std::string& kernel_id); - - /** - * @brief Lists all backends which are included into package - * - * @return vector of backends - */ - std::vector backends() const; - - // TODO: Doxygen bug -- it wants me to place this comment - // here, not below. - /** - * @brief Create a new package based on `lhs` and `rhs`. - * - * @param lhs "Left-hand-side" package in the process - * @param rhs "Right-hand-side" package in the process - * @return a new kernel package. - */ - friend GAPI_EXPORTS GKernelPackage cv::gapi::combine(const GKernelPackage &lhs, - const GKernelPackage &rhs); - }; - /** @} */ - -namespace gapi { - using GKernelPackage = cv::GKernelPackage; // Keep backward compatibility - - /** \addtogroup gapi_compile_args - * @{ - */ - - /** - * @brief Create a kernel package object containing kernels - * and transformations specified in variadic template argument. - * - * In G-API, kernel implementations and transformations are _types_. - * Every backend has its own kernel API (like GAPI_OCV_KERNEL() and - * GAPI_FLUID_KERNEL()) but all of that APIs define a new type for - * each kernel implementation. - * - * Use this function to pass kernel implementations (defined in - * either way) and transformations to the system. Example: - * - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp kernels_snippet - * - * Note that kernels() itself is a function returning object, not - * a type, so having `()` at the end is important -- it must be a - * function call. - */ - template GKernelPackage kernels() - { - // FIXME: currently there is no check that transformations' signatures are unique - // and won't be any intersection in graph compilation stage - static_assert(cv::detail::all_unique::value, "Kernels API must be unique"); - - GKernelPackage pkg; - - // For those who wonder - below is a trick to call a number of - // methods based on parameter pack (zeroes just help hiding these - // calls into a sequence which helps to expand this parameter pack). - // Just note that `f(),a` always equals to `a` (with f() called!) - // and parentheses are used to hide function call in the expanded sequence. - // Leading 0 helps to handle case when KK is an empty list (kernels<>()). - int unused[] = { 0, (pkg.include(), 0)... }; - cv::util::suppress_unused_warning(unused); - return pkg; - } - - template - GKernelPackage kernels(FF&... functors) - { - GKernelPackage pkg; - int unused[] = { 0, (pkg.include(functors), 0)... }; - cv::util::suppress_unused_warning(unused); - return pkg; - } - - /** @} */ - - /** - * @brief Combines multiple G-API kernel packages into one - * - * @overload - * - * This function successively combines the passed kernel packages using a right fold. - * Calling `combine(a, b, c)` is equal to `combine(a, combine(b, c))`. - * - * @return The resulting kernel package - */ - template - cv::GKernelPackage combine(const cv::GKernelPackage &a, const cv::GKernelPackage &b, Ps&&... rest) - { - return combine(a, combine(b, rest...)); - } - // NB(DM): Variadic-arg version in Python may require the same - // approach as used in GComputation::compile/apply. - - /** \addtogroup gapi_compile_args - * @{ - */ - /** - * @brief cv::gapi::use_only() is a special combinator which hints G-API to use only - * kernels specified in cv::GComputation::compile() (and not to extend kernels available by - * default with that package). - */ - struct GAPI_EXPORTS use_only - { - GKernelPackage pkg; - }; - /** @} */ - -} // namespace gapi - -namespace detail -{ - template<> struct CompileArgTag - { - static const char* tag() { return "gapi.kernel_package"; } - }; - - template<> struct CompileArgTag - { - static const char* tag() { return "gapi.use_only"; } - }; -} // namespace detail - -} // namespace cv - -#endif // OPENCV_GAPI_GKERNEL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2021 Intel Corporation + + +#ifndef OPENCV_GAPI_GKERNEL_HPP +#define OPENCV_GAPI_GKERNEL_HPP + +#include +#include +#include // string +#include // false_type, true_type +#include // map (for GKernelPackage) +#include // tuple + +#include // CompileArgTag +#include // Seq +#include +#include // GArg +#include // GMetaArg +#include // GTypeTraits +#include //suppress_unused_warning +#include + +namespace cv { + +struct GTypeInfo +{ + GShape shape; + cv::detail::OpaqueKind kind; + detail::HostCtor ctor; +}; + +using GShapes = std::vector; +using GKinds = std::vector; +using GCtors = std::vector; +using GTypesInfo = std::vector; + +// GKernel describes kernel API to the system +// FIXME: add attributes of a kernel, (e.g. number and types +// of inputs, etc) +struct GAPI_EXPORTS GKernel +{ + using M = std::function; + + std::string name; // kernel ID, defined by its API (signature) + std::string tag; // some (implementation-specific) tag + M outMeta; // generic adaptor to API::outMeta(...) + GShapes outShapes; // types (shapes) kernel's outputs + GKinds inKinds; // kinds of kernel's inputs (fixme: below) + GCtors outCtors; // captured constructors for template output types + GKinds outKinds; // kinds of kernel's outputs (fixme: below) +}; +// TODO: It's questionable if inKinds should really be here. Instead, +// this information could come from meta. + +// GKernelImpl describes particular kernel implementation to the system +struct GAPI_EXPORTS GKernelImpl +{ + util::any opaque; // backend-specific opaque info + GKernel::M outMeta; // for deserialized graphs, the outMeta is taken here +}; + +template class GKernelTypeM; + +namespace detail +{ + //////////////////////////////////////////////////////////////////////////// + // yield() is used in graph construction time as a generic method to obtain + // lazy "return value" of G-API operations + // + template struct Yield; + template<> struct Yield + { + static inline cv::GMat yield(cv::GCall &call, int i) { return call.yield(i); } + }; + template<> struct Yield + { + static inline cv::GMatP yield(cv::GCall &call, int i) { return call.yieldP(i); } + }; + template<> struct Yield + { + static inline cv::GScalar yield(cv::GCall &call, int i) { return call.yieldScalar(i); } + }; + template struct Yield > + { + static inline cv::GArray yield(cv::GCall &call, int i) { return call.yieldArray(i); } + }; + template struct Yield > + { + static inline cv::GOpaque yield(cv::GCall &call, int i) { return call.yieldOpaque(i); } + }; + template<> struct Yield + { + static inline cv::GFrame yield(cv::GCall &call, int i) { return call.yieldFrame(i); } + }; + + //////////////////////////////////////////////////////////////////////////// + // Helper classes which brings outputMeta() marshalling to kernel + // implementations + // + // 1. MetaType establishes G#Type -> G#Meta mapping between G-API dynamic + // types and its metadata descriptor types. + // This mapping is used to transform types to call outMeta() callback. + template struct MetaType; + template<> struct MetaType { using type = GMatDesc; }; + template<> struct MetaType { using type = GMatDesc; }; + template<> struct MetaType { using type = GFrameDesc; }; + template<> struct MetaType { using type = GScalarDesc; }; + template struct MetaType > { using type = GArrayDesc; }; + template struct MetaType > { using type = GOpaqueDesc; }; + template struct MetaType { using type = T; }; // opaque args passed as-is + // FIXME: Move it to type traits? + + // 2. Hacky test based on MetaType to check if we operate on G-* type or not + template using is_nongapi_type = std::is_same::type>; + + // 3. Two ways to transform input arguments to its meta - for G-* and non-G* types: + template + typename std::enable_if::value, typename MetaType::type> + ::type get_in_meta(const GMetaArgs &in_meta, const GArgs &, int idx) + { + return util::get::type>(in_meta.at(idx)); + } + + template + typename std::enable_if::value, T> + ::type get_in_meta(const GMetaArgs &, const GArgs &in_args, int idx) + { + return in_args.at(idx).template get(); + } + + // 4. The MetaHelper itself: an entity which generates outMeta() call + // based on kernel signature, with arguments properly substituted. + // 4.1 - case for multiple return values + // FIXME: probably can be simplified with std::apply or analogue. + template + struct MetaHelper; + + template + struct MetaHelper, std::tuple > + { + template + static GMetaArgs getOutMeta_impl(const GMetaArgs &in_meta, + const GArgs &in_args, + detail::Seq, + detail::Seq) + { + // FIXME: decay? + using R = std::tuple::type...>; + const R r = K::outMeta( get_in_meta(in_meta, in_args, IIs)... ); + return GMetaArgs{ GMetaArg(std::get(r))... }; + } + // FIXME: help users identify how outMeta must look like (via default impl w/static_assert?) + + static GMetaArgs getOutMeta(const GMetaArgs &in_meta, + const GArgs &in_args) + { + return getOutMeta_impl(in_meta, + in_args, + typename detail::MkSeq::type(), + typename detail::MkSeq::type()); + } + }; + + // 4.1 - case for a single return value + // FIXME: How to avoid duplication here? + template + struct MetaHelper, Out > + { + template + static GMetaArgs getOutMeta_impl(const GMetaArgs &in_meta, + const GArgs &in_args, + detail::Seq) + { + // FIXME: decay? + using R = typename MetaType::type; + const R r = K::outMeta( get_in_meta(in_meta, in_args, IIs)... ); + return GMetaArgs{ GMetaArg(r) }; + } + // FIXME: help users identify how outMeta must look like (via default impl w/static_assert?) + + static GMetaArgs getOutMeta(const GMetaArgs &in_meta, + const GArgs &in_args) + { + return getOutMeta_impl(in_meta, + in_args, + typename detail::MkSeq::type()); + } + }; + + //////////////////////////////////////////////////////////////////////////// + // Helper class to introduce tags to calls. By default there's no tag + struct NoTag { + static constexpr const char *tag() { return ""; } + }; + +} // namespace detail + +// GKernelType and GKernelTypeM are base classes which implement typed ::on() +// method based on kernel signature. GKernelTypeM stands for multiple-return-value kernels +// +// G_TYPED_KERNEL and G_TYPED_KERNEL_M macros inherit user classes from GKernelType and +// GKernelTypeM respectively. + +template +class GKernelTypeM(Args...)> > + : public detail::MetaHelper, std::tuple> + , public detail::NoTag +{ + template + static std::tuple yield(cv::GCall &call, detail::Seq) + { + return std::make_tuple(detail::Yield::yield(call, IIs)...); + } + +public: + using InArgs = std::tuple; + using OutArgs = std::tuple; + + // TODO: Args&&... here? + static std::tuple on(Args... args) + { + cv::GCall call(GKernel{ K::id() + , K::tag() + , &K::getOutMeta + , {detail::GTypeTraits::shape...} + , {detail::GTypeTraits::op_kind...} + , {detail::GObtainCtor::get()...} + , {detail::GTypeTraits::op_kind...}}); + call.pass(args...); // TODO: std::forward() here? + return yield(call, typename detail::MkSeq::type()); + } +}; + +template class GKernelType; + +template +class GKernelType > + : public detail::MetaHelper, R> + , public detail::NoTag +{ +public: + using InArgs = std::tuple; + using OutArgs = std::tuple; + + static R on(Args... args) + { + cv::GCall call(GKernel{ K::id() + , K::tag() + , &K::getOutMeta + , {detail::GTypeTraits::shape} + , {detail::GTypeTraits::op_kind...} + , {detail::GObtainCtor::get()} + , {detail::GTypeTraits::op_kind}}); + call.pass(args...); + return detail::Yield::yield(call, 0); + } +}; + +namespace detail { +// This tiny class eliminates the semantic difference between +// GKernelType and GKernelTypeM. +template class KernelTypeMedium; + +template +class KernelTypeMedium(Args...)>> : + public cv::GKernelTypeM(Args...)>> {}; + +template +class KernelTypeMedium> : + public cv::GKernelType> {}; +} // namespace detail + +} // namespace cv + + +// FIXME: I don't know a better way so far. Feel free to suggest one +// The problem is that every typed kernel should have ::id() but body +// of the class is defined by user (with outMeta, other stuff) + +//! @cond IGNORED +#define G_ID_HELPER_CLASS(Class) Class##IdHelper + +#define G_ID_HELPER_BODY(Class, Id) \ + struct G_ID_HELPER_CLASS(Class) \ + { \ + static constexpr const char * id() {return Id;} \ + }; \ +//! @endcond + +#define GET_G_TYPED_KERNEL(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, NAME, ...) NAME +#define COMBINE_SIGNATURE(...) __VA_ARGS__ +// Ensure correct __VA_ARGS__ expansion on Windows +#define __WRAP_VAARGS(x) x + +/** + * Helper for G_TYPED_KERNEL declares a new G-API Operation. See [Kernel API](@ref gapi_kernel_api) + * for more details. + * + * @param Class type name for this operation. + * @param API an `std::function<>`-like signature for the operation; + * return type is a single value or a tuple of multiple values. + * @param Id string identifier for the operation. Must be unique. + */ +#define G_TYPED_KERNEL_HELPER(Class, API, Id) \ + G_ID_HELPER_BODY(Class, Id) \ + struct Class final: public cv::detail::KernelTypeMedium, \ + public G_ID_HELPER_CLASS(Class) +// {body} is to be defined by user + +#define G_TYPED_KERNEL_HELPER_2(Class, _1, _2, Id) \ +G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2), Id) + +#define G_TYPED_KERNEL_HELPER_3(Class, _1, _2, _3, Id) \ +G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3), Id) + +#define G_TYPED_KERNEL_HELPER_4(Class, _1, _2, _3, _4, Id) \ +G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4), Id) + +#define G_TYPED_KERNEL_HELPER_5(Class, _1, _2, _3, _4, _5, Id) \ +G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5), Id) + +#define G_TYPED_KERNEL_HELPER_6(Class, _1, _2, _3, _4, _5, _6, Id) \ +G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6), Id) + +#define G_TYPED_KERNEL_HELPER_7(Class, _1, _2, _3, _4, _5, _6, _7, Id) \ +G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6, _7), Id) + +#define G_TYPED_KERNEL_HELPER_8(Class, _1, _2, _3, _4, _5, _6, _7, _8, Id) \ +G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6, _7, _8), Id) + +#define G_TYPED_KERNEL_HELPER_9(Class, _1, _2, _3, _4, _5, _6, _7, _8, _9, Id) \ +G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6, _7, _8, _9), Id) + +#define G_TYPED_KERNEL_HELPER_10(Class, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, Id) \ +G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10), Id) + +/** + * Declares a new G-API Operation. See [Kernel API](@ref gapi_kernel_api) + * for more details. + * + * @param Class type name for this operation. + */ +#define G_TYPED_KERNEL(Class, ...) __WRAP_VAARGS(GET_G_TYPED_KERNEL(__VA_ARGS__, \ + G_TYPED_KERNEL_HELPER_10, \ + G_TYPED_KERNEL_HELPER_9, \ + G_TYPED_KERNEL_HELPER_8, \ + G_TYPED_KERNEL_HELPER_7, \ + G_TYPED_KERNEL_HELPER_6, \ + G_TYPED_KERNEL_HELPER_5, \ + G_TYPED_KERNEL_HELPER_4, \ + G_TYPED_KERNEL_HELPER_3, \ + G_TYPED_KERNEL_HELPER_2, \ + G_TYPED_KERNEL_HELPER)(Class, __VA_ARGS__)) \ + +/** + * Declares a new G-API Operation. See [Kernel API](@ref gapi_kernel_api) for more details. + * + * @deprecated This macro is deprecated in favor of `G_TYPED_KERNEL` that is used for declaring any + * G-API Operation. + * + * @param Class type name for this operation. + */ +#define G_TYPED_KERNEL_M G_TYPED_KERNEL + +#define G_API_OP G_TYPED_KERNEL +#define G_API_OP_M G_API_OP + +namespace cv +{ +namespace gapi +{ + // Prework: model "Device" API before it gets to G-API headers. + // FIXME: Don't mix with internal Backends class! + /// @private + class GAPI_EXPORTS GBackend + { + public: + class Priv; + + // TODO: make it template (call `new` within??) + GBackend(); + explicit GBackend(std::shared_ptr &&p); + + Priv& priv(); + const Priv& priv() const; + std::size_t hash() const; + + bool operator== (const GBackend &rhs) const; + + private: + std::shared_ptr m_priv; + }; + + inline bool operator != (const GBackend &lhs, const GBackend &rhs) + { + return !(lhs == rhs); + } +} // namespace gapi +} // namespace cv + +namespace std +{ + template<> struct hash + { + std::size_t operator() (const cv::gapi::GBackend &b) const + { + return b.hash(); + } + }; +} // namespace std + +namespace cv { + class GAPI_EXPORTS_W_SIMPLE GKernelPackage; + +namespace gapi { + GAPI_EXPORTS_W cv::GKernelPackage combine(const cv::GKernelPackage &lhs, + const cv::GKernelPackage &rhs); + + /// @private + class GFunctor + { + public: + virtual cv::GKernelImpl impl() const = 0; + virtual cv::gapi::GBackend backend() const = 0; + const char* id() const { return m_id; } + + virtual ~GFunctor() = default; + protected: + GFunctor(const char* id) : m_id(id) { } + private: + const char* m_id; + }; +} // namespace gapi + + /** \addtogroup gapi_compile_args + * @{ + */ + + // FIXME: Hide implementation + /** + * @brief A container class for heterogeneous kernel + * implementation collections and graph transformations. + * + * GKernelPackage is a special container class which stores kernel + * _implementations_ and graph _transformations_. Objects of this class + * are created and passed to cv::GComputation::compile() to specify + * which kernels to use and which transformations to apply in the + * compiled graph. GKernelPackage may contain kernels of + * different backends, e.g. be heterogeneous. + * + * The most easy way to create a kernel package is to use function + * cv::gapi::kernels(). This template functions takes kernel + * implementations in form of type list (variadic template) and + * generates a kernel package atop of that. + * + * Kernel packages can be also generated programmatically, starting + * with an empty package (created with the default constructor) + * and then by populating it with kernels via call to + * GKernelPackage::include(). Note this method is also a template + * one since G-API kernel and transformation implementations are _types_, + * not objects. + * + * Finally, two kernel packages can be combined into a new one + * with function cv::gapi::combine(). + */ + class GAPI_EXPORTS_W_SIMPLE GKernelPackage + { + + /// @private + using M = std::unordered_map>; + + /// @private + M m_id_kernels; + + /// @private + std::vector m_transformations; + + protected: + /// @private + // Remove ALL implementations of the given API (identified by ID) + void removeAPI(const std::string &id); + + /// @private + // Partial include() specialization for kernels + template + typename std::enable_if<(std::is_base_of::value), void>::type + includeHelper() + { + auto backend = KImpl::backend(); + auto kernel_id = KImpl::API::id(); + auto kernel_impl = GKernelImpl{KImpl::kernel(), &KImpl::API::getOutMeta}; + removeAPI(kernel_id); + + m_id_kernels[kernel_id] = std::make_pair(backend, kernel_impl); + } + + /// @private + // Partial include() specialization for transformations + template + typename std::enable_if<(std::is_base_of::value), void>::type + includeHelper() + { + m_transformations.emplace_back(TImpl::transformation()); + } + + public: + void include(const cv::gapi::GFunctor& functor); + + /** + * @brief Returns total number of kernels + * in the package (across all backends included) + * + * @return a number of kernels in the package + */ + GAPI_WRAP std::size_t size() const; + + /** + * @brief Returns vector of transformations included in the package + * + * @return vector of transformations included in the package + */ + const std::vector& get_transformations() const; + + /** + * @brief Returns vector of kernel ids included in the package + * + * @return vector of kernel ids included in the package + */ + std::vector get_kernel_ids() const; + + /** + * @brief Test if a particular kernel _implementation_ KImpl is + * included in this kernel package. + * + * @sa includesAPI() + * + * @note cannot be applied to transformations + * + * @return true if there is such kernel, false otherwise. + */ + template + bool includes() const + { + static_assert(std::is_base_of::value, + "includes() can be applied to kernels only"); + + auto kernel_it = m_id_kernels.find(KImpl::API::id()); + return kernel_it != m_id_kernels.end() && + kernel_it->second.first == KImpl::backend(); + } + + /** + * @brief Remove all kernels associated with the given backend + * from the package. + * + * Does nothing if there's no kernels of this backend in the package. + * + * @param backend backend which kernels to remove + */ + void remove(const cv::gapi::GBackend& backend); + + /** + * @brief Remove all kernels implementing the given API from + * the package. + * + * Does nothing if there's no kernels implementing the given interface. + */ + template + void remove() + { + removeAPI(KAPI::id()); + } + + // FIXME: Rename to includes() and distinguish API/impl case by + // statically? + /** + * Check if package contains ANY implementation of a kernel API + * by API type. + */ + template + bool includesAPI() const + { + return includesAPI(KAPI::id()); + } + + /// @private + bool includesAPI(const std::string &id) const; + + // FIXME: The below comment is wrong, and who needs this function? + /** + * @brief Find a kernel (by its API) + * + * Returns implementation corresponding id. + * Throws if nothing found. + * + * @return Backend which hosts matching kernel implementation. + * + */ + template + cv::gapi::GBackend lookup() const + { + return lookup(KAPI::id()).first; + } + + /// @private + std::pair + lookup(const std::string &id) const; + + // FIXME: No overwrites allowed? + /** + * @brief Put a new kernel implementation or a new transformation + * KImpl into the package. + */ + template + void include() + { + includeHelper(); + } + + /** + * @brief Adds a new kernel based on it's backend and id into the kernel package + * + * @param backend backend associated with the kernel + * @param kernel_id a name/id of the kernel + */ + void include(const cv::gapi::GBackend& backend, const std::string& kernel_id); + + /** + * @brief Lists all backends which are included into package + * + * @return vector of backends + */ + std::vector backends() const; + + // TODO: Doxygen bug -- it wants me to place this comment + // here, not below. + /** + * @brief Create a new package based on `lhs` and `rhs`. + * + * @param lhs "Left-hand-side" package in the process + * @param rhs "Right-hand-side" package in the process + * @return a new kernel package. + */ + friend GAPI_EXPORTS GKernelPackage cv::gapi::combine(const GKernelPackage &lhs, + const GKernelPackage &rhs); + }; + /** @} */ + +namespace gapi { + using GKernelPackage = cv::GKernelPackage; // Keep backward compatibility + + /** \addtogroup gapi_compile_args + * @{ + */ + + /** + * @brief Create a kernel package object containing kernels + * and transformations specified in variadic template argument. + * + * In G-API, kernel implementations and transformations are _types_. + * Every backend has its own kernel API (like GAPI_OCV_KERNEL() and + * GAPI_FLUID_KERNEL()) but all of that APIs define a new type for + * each kernel implementation. + * + * Use this function to pass kernel implementations (defined in + * either way) and transformations to the system. Example: + * + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp kernels_snippet + * + * Note that kernels() itself is a function returning object, not + * a type, so having `()` at the end is important -- it must be a + * function call. + */ + template GKernelPackage kernels() + { + // FIXME: currently there is no check that transformations' signatures are unique + // and won't be any intersection in graph compilation stage + static_assert(cv::detail::all_unique::value, "Kernels API must be unique"); + + GKernelPackage pkg; + + // For those who wonder - below is a trick to call a number of + // methods based on parameter pack (zeroes just help hiding these + // calls into a sequence which helps to expand this parameter pack). + // Just note that `f(),a` always equals to `a` (with f() called!) + // and parentheses are used to hide function call in the expanded sequence. + // Leading 0 helps to handle case when KK is an empty list (kernels<>()). + int unused[] = { 0, (pkg.include(), 0)... }; + cv::util::suppress_unused_warning(unused); + return pkg; + } + + template + GKernelPackage kernels(FF&... functors) + { + GKernelPackage pkg; + int unused[] = { 0, (pkg.include(functors), 0)... }; + cv::util::suppress_unused_warning(unused); + return pkg; + } + + /** @} */ + + /** + * @brief Combines multiple G-API kernel packages into one + * + * @overload + * + * This function successively combines the passed kernel packages using a right fold. + * Calling `combine(a, b, c)` is equal to `combine(a, combine(b, c))`. + * + * @return The resulting kernel package + */ + template + cv::GKernelPackage combine(const cv::GKernelPackage &a, const cv::GKernelPackage &b, Ps&&... rest) + { + return combine(a, combine(b, rest...)); + } + // NB(DM): Variadic-arg version in Python may require the same + // approach as used in GComputation::compile/apply. + + /** \addtogroup gapi_compile_args + * @{ + */ + /** + * @brief cv::gapi::use_only() is a special combinator which hints G-API to use only + * kernels specified in cv::GComputation::compile() (and not to extend kernels available by + * default with that package). + */ + struct GAPI_EXPORTS use_only + { + GKernelPackage pkg; + }; + /** @} */ + +} // namespace gapi + +namespace detail +{ + template<> struct CompileArgTag + { + static const char* tag() { return "gapi.kernel_package"; } + }; + + template<> struct CompileArgTag + { + static const char* tag() { return "gapi.use_only"; } + }; +} // namespace detail + +} // namespace cv + +#endif // OPENCV_GAPI_GKERNEL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gmat.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gmat.hpp index 6d6f74ff7f..27ac65e78f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gmat.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gmat.hpp @@ -1,292 +1,292 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2020 Intel Corporation - - -#ifndef OPENCV_GAPI_GMAT_HPP -#define OPENCV_GAPI_GMAT_HPP - -#include -#include // std::shared_ptr - -#include -#include // GShape - -#include - -// TODO GAPI_EXPORTS or so -namespace cv -{ -// Forward declaration; GNode and GOrigin are an internal -// (user-inaccessible) classes. -class GNode; -struct GOrigin; - -/** \addtogroup gapi_data_objects - * @{ - * - * @brief G-API data objects used to build G-API expressions. - * - * These objects do not own any particular data (except compile-time - * associated values like with cv::GScalar or `cv::GArray`) and are - * used only to construct graphs. - * - * Every graph in G-API starts and ends with data objects. - * - * Once constructed and compiled, G-API operates with regular host-side - * data instead. Refer to the below table to find the mapping between - * G-API and regular data types when passing input and output data - * structures to G-API: - * - * G-API data type | I/O data type - * ------------------ | ------------- - * cv::GMat | cv::Mat, cv::UMat, cv::RMat - * cv::GScalar | cv::Scalar - * `cv::GArray` | std::vector - * `cv::GOpaque` | T - * cv::GFrame | cv::MediaFrame - */ - -/** - * @brief GMat class represents image or tensor data in the - * graph. - * - * GMat doesn't store any data itself, instead it describes a - * functional relationship between operations consuming and producing - * GMat objects. - * - * GMat is a virtual counterpart of Mat and UMat, but it - * doesn't mean G-API use Mat or UMat objects internally to represent - * GMat objects -- the internal data representation may be - * backend-specific or optimized out at all. - * - * @sa Mat, GMatDesc - */ -class GAPI_EXPORTS_W_SIMPLE GMat -{ -public: - /** - * @brief Constructs an empty GMat - * - * Normally, empty G-API data objects denote a starting point of - * the graph. When an empty GMat is assigned to a result of some - * operation, it obtains a functional link to this operation (and - * is not empty anymore). - */ - GAPI_WRAP GMat(); // Empty constructor - - /** - * @brief Constructs a value-initialized GMat - * - * GMat may be associated with a buffer at graph construction time. - * It is useful when some operation has a Mat input which doesn't - * change during the program execution, and is set only once. - * In this case, there's no need to declare such GMat as graph input. - * - * @param m a cv::Mat buffer to associate with this GMat object. - */ - GAPI_WRAP explicit GMat(cv::Mat m); // Value-initialization constructor - - /// @private - GMat(const GNode &n, std::size_t out); // Operation result constructor - /// @private - GOrigin& priv(); // Internal use only - /// @private - const GOrigin& priv() const; // Internal use only - -private: - std::shared_ptr m_priv; -}; - -class GAPI_EXPORTS GMatP : public GMat -{ -public: - using GMat::GMat; -}; - -class RMat; - -/** @} */ - -/** - * \addtogroup gapi_meta_args - * @{ - */ -struct GAPI_EXPORTS_W_SIMPLE GMatDesc -{ - // FIXME: Default initializers in C++14 - GAPI_PROP int depth; - GAPI_PROP int chan; - GAPI_PROP cv::Size size; // NB.: no multi-dimensional cases covered yet - GAPI_PROP bool planar; - GAPI_PROP std::vector dims; // FIXME: Maybe it's real questionable to have it here - - GAPI_WRAP GMatDesc(int d, int c, cv::Size s, bool p = false) - : depth(d), chan(c), size(s), planar(p) {} - - GAPI_WRAP GMatDesc(int d, const std::vector &dd) - : depth(d), chan(-1), size{-1,-1}, planar(false), dims(dd) {} - - GAPI_WRAP GMatDesc(int d, std::vector &&dd) - : depth(d), chan(-1), size{-1,-1}, planar(false), dims(std::move(dd)) {} - - GAPI_WRAP GMatDesc() : GMatDesc(-1, -1, {-1,-1}) {} - - inline bool operator== (const GMatDesc &rhs) const - { - return depth == rhs.depth - && chan == rhs.chan - && size == rhs.size - && planar == rhs.planar - && dims == rhs.dims; - } - - inline bool operator!= (const GMatDesc &rhs) const - { - return !(*this == rhs); - } - - bool isND() const { return !dims.empty(); } - - // Checks if the passed mat can be described by this descriptor - // (it handles the case when - // 1-channel mat can be reinterpreted as is (1-channel mat) - // and as a 3-channel planar mat with height divided by 3) - bool canDescribe(const cv::Mat& mat) const; - - bool canDescribe(const cv::RMat& mat) const; - - // Meta combinator: return a new GMatDesc which differs in size by delta - // (all other fields are taken unchanged from this GMatDesc) - // FIXME: a better name? - GAPI_WRAP GMatDesc withSizeDelta(cv::Size delta) const - { - GMatDesc desc(*this); - desc.size += delta; - return desc; - } - // Meta combinator: return a new GMatDesc which differs in size by delta - // (all other fields are taken unchanged from this GMatDesc) - // - // This is an overload. - GAPI_WRAP GMatDesc withSizeDelta(int dx, int dy) const - { - return withSizeDelta(cv::Size{dx,dy}); - } - - GAPI_WRAP GMatDesc withSize(cv::Size sz) const - { - GMatDesc desc(*this); - desc.size = sz; - return desc; - } - - // Meta combinator: return a new GMatDesc with specified data depth. - // (all other fields are taken unchanged from this GMatDesc) - GAPI_WRAP GMatDesc withDepth(int ddepth) const - { - GAPI_Assert(CV_MAT_CN(ddepth) == 1 || ddepth == -1); - GMatDesc desc(*this); - if (ddepth != -1) desc.depth = ddepth; - return desc; - } - - // Meta combinator: return a new GMatDesc with specified data depth - // and number of channels. - // (all other fields are taken unchanged from this GMatDesc) - GAPI_WRAP GMatDesc withType(int ddepth, int dchan) const - { - GAPI_Assert(CV_MAT_CN(ddepth) == 1 || ddepth == -1); - GMatDesc desc = withDepth(ddepth); - desc.chan = dchan; - return desc; - } - - // Meta combinator: return a new GMatDesc with planar flag set - // (no size changes are performed, only channel interpretation is changed - // (interleaved -> planar) - GAPI_WRAP GMatDesc asPlanar() const - { - GAPI_Assert(planar == false); - GMatDesc desc(*this); - desc.planar = true; - return desc; - } - - // Meta combinator: return a new GMatDesc - // reinterpreting 1-channel input as planar image - // (size height is divided by plane number) - GAPI_WRAP GMatDesc asPlanar(int planes) const - { - GAPI_Assert(planar == false); - GAPI_Assert(chan == 1); - GAPI_Assert(planes > 1); - GAPI_Assert(size.height % planes == 0); - GMatDesc desc(*this); - desc.size.height /= planes; - desc.chan = planes; - return desc.asPlanar(); - } - - // Meta combinator: return a new GMatDesc with planar flag set to false - // (no size changes are performed, only channel interpretation is changed - // (planar -> interleaved) - GAPI_WRAP GMatDesc asInterleaved() const - { - GAPI_Assert(planar == true); - GMatDesc desc(*this); - desc.planar = false; - return desc; - } -}; - -static inline GMatDesc empty_gmat_desc() { return GMatDesc{-1,-1,{-1,-1}}; } - -namespace gapi { namespace detail { -/** Checks GMatDesc fields if the passed matrix is a set of n-dimentional points. -@param in GMatDesc to check. -@param n expected dimensionality. -@return the amount of points. In case input matrix can't be described as vector of points -of expected dimensionality, returns -1. - */ -int checkVector(const GMatDesc& in, const size_t n); - -/** @overload - -Checks GMatDesc fields if the passed matrix can be described as a set of points of any -dimensionality. - -@return array of two elements in form of std::vector: the amount of points -and their calculated dimensionality. In case input matrix can't be described as vector of points, -returns {-1, -1}. - */ -std::vector checkVector(const GMatDesc& in); -}} // namespace gapi::detail - -#if !defined(GAPI_STANDALONE) -GAPI_EXPORTS GMatDesc descr_of(const cv::UMat &mat); -#endif // !defined(GAPI_STANDALONE) - -//Fwd declarations -namespace gapi { namespace own { - class Mat; - GAPI_EXPORTS GMatDesc descr_of(const Mat &mat); -}}//gapi::own - -GAPI_EXPORTS GMatDesc descr_of(const RMat &mat); - -#if !defined(GAPI_STANDALONE) -GAPI_EXPORTS GMatDesc descr_of(const cv::Mat &mat); -#else -using gapi::own::descr_of; -#endif - -/** @} */ - -GAPI_EXPORTS std::ostream& operator<<(std::ostream& os, const cv::GMatDesc &desc); - -} // namespace cv - -#endif // OPENCV_GAPI_GMAT_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2020 Intel Corporation + + +#ifndef OPENCV_GAPI_GMAT_HPP +#define OPENCV_GAPI_GMAT_HPP + +#include +#include // std::shared_ptr + +#include +#include // GShape + +#include + +// TODO GAPI_EXPORTS or so +namespace cv +{ +// Forward declaration; GNode and GOrigin are an internal +// (user-inaccessible) classes. +class GNode; +struct GOrigin; + +/** \addtogroup gapi_data_objects + * @{ + * + * @brief G-API data objects used to build G-API expressions. + * + * These objects do not own any particular data (except compile-time + * associated values like with cv::GScalar or `cv::GArray`) and are + * used only to construct graphs. + * + * Every graph in G-API starts and ends with data objects. + * + * Once constructed and compiled, G-API operates with regular host-side + * data instead. Refer to the below table to find the mapping between + * G-API and regular data types when passing input and output data + * structures to G-API: + * + * G-API data type | I/O data type + * ------------------ | ------------- + * cv::GMat | cv::Mat, cv::UMat, cv::RMat + * cv::GScalar | cv::Scalar + * `cv::GArray` | std::vector + * `cv::GOpaque` | T + * cv::GFrame | cv::MediaFrame + */ + +/** + * @brief GMat class represents image or tensor data in the + * graph. + * + * GMat doesn't store any data itself, instead it describes a + * functional relationship between operations consuming and producing + * GMat objects. + * + * GMat is a virtual counterpart of Mat and UMat, but it + * doesn't mean G-API use Mat or UMat objects internally to represent + * GMat objects -- the internal data representation may be + * backend-specific or optimized out at all. + * + * @sa Mat, GMatDesc + */ +class GAPI_EXPORTS_W_SIMPLE GMat +{ +public: + /** + * @brief Constructs an empty GMat + * + * Normally, empty G-API data objects denote a starting point of + * the graph. When an empty GMat is assigned to a result of some + * operation, it obtains a functional link to this operation (and + * is not empty anymore). + */ + GAPI_WRAP GMat(); // Empty constructor + + /** + * @brief Constructs a value-initialized GMat + * + * GMat may be associated with a buffer at graph construction time. + * It is useful when some operation has a Mat input which doesn't + * change during the program execution, and is set only once. + * In this case, there's no need to declare such GMat as graph input. + * + * @param m a cv::Mat buffer to associate with this GMat object. + */ + GAPI_WRAP explicit GMat(cv::Mat m); // Value-initialization constructor + + /// @private + GMat(const GNode &n, std::size_t out); // Operation result constructor + /// @private + GOrigin& priv(); // Internal use only + /// @private + const GOrigin& priv() const; // Internal use only + +private: + std::shared_ptr m_priv; +}; + +class GAPI_EXPORTS GMatP : public GMat +{ +public: + using GMat::GMat; +}; + +class RMat; + +/** @} */ + +/** + * \addtogroup gapi_meta_args + * @{ + */ +struct GAPI_EXPORTS_W_SIMPLE GMatDesc +{ + // FIXME: Default initializers in C++14 + GAPI_PROP int depth; + GAPI_PROP int chan; + GAPI_PROP cv::Size size; // NB.: no multi-dimensional cases covered yet + GAPI_PROP bool planar; + GAPI_PROP std::vector dims; // FIXME: Maybe it's real questionable to have it here + + GAPI_WRAP GMatDesc(int d, int c, cv::Size s, bool p = false) + : depth(d), chan(c), size(s), planar(p) {} + + GAPI_WRAP GMatDesc(int d, const std::vector &dd) + : depth(d), chan(-1), size{-1,-1}, planar(false), dims(dd) {} + + GAPI_WRAP GMatDesc(int d, std::vector &&dd) + : depth(d), chan(-1), size{-1,-1}, planar(false), dims(std::move(dd)) {} + + GAPI_WRAP GMatDesc() : GMatDesc(-1, -1, {-1,-1}) {} + + inline bool operator== (const GMatDesc &rhs) const + { + return depth == rhs.depth + && chan == rhs.chan + && size == rhs.size + && planar == rhs.planar + && dims == rhs.dims; + } + + inline bool operator!= (const GMatDesc &rhs) const + { + return !(*this == rhs); + } + + bool isND() const { return !dims.empty(); } + + // Checks if the passed mat can be described by this descriptor + // (it handles the case when + // 1-channel mat can be reinterpreted as is (1-channel mat) + // and as a 3-channel planar mat with height divided by 3) + bool canDescribe(const cv::Mat& mat) const; + + bool canDescribe(const cv::RMat& mat) const; + + // Meta combinator: return a new GMatDesc which differs in size by delta + // (all other fields are taken unchanged from this GMatDesc) + // FIXME: a better name? + GAPI_WRAP GMatDesc withSizeDelta(cv::Size delta) const + { + GMatDesc desc(*this); + desc.size += delta; + return desc; + } + // Meta combinator: return a new GMatDesc which differs in size by delta + // (all other fields are taken unchanged from this GMatDesc) + // + // This is an overload. + GAPI_WRAP GMatDesc withSizeDelta(int dx, int dy) const + { + return withSizeDelta(cv::Size{dx,dy}); + } + + GAPI_WRAP GMatDesc withSize(cv::Size sz) const + { + GMatDesc desc(*this); + desc.size = sz; + return desc; + } + + // Meta combinator: return a new GMatDesc with specified data depth. + // (all other fields are taken unchanged from this GMatDesc) + GAPI_WRAP GMatDesc withDepth(int ddepth) const + { + GAPI_Assert(CV_MAT_CN(ddepth) == 1 || ddepth == -1); + GMatDesc desc(*this); + if (ddepth != -1) desc.depth = ddepth; + return desc; + } + + // Meta combinator: return a new GMatDesc with specified data depth + // and number of channels. + // (all other fields are taken unchanged from this GMatDesc) + GAPI_WRAP GMatDesc withType(int ddepth, int dchan) const + { + GAPI_Assert(CV_MAT_CN(ddepth) == 1 || ddepth == -1); + GMatDesc desc = withDepth(ddepth); + desc.chan = dchan; + return desc; + } + + // Meta combinator: return a new GMatDesc with planar flag set + // (no size changes are performed, only channel interpretation is changed + // (interleaved -> planar) + GAPI_WRAP GMatDesc asPlanar() const + { + GAPI_Assert(planar == false); + GMatDesc desc(*this); + desc.planar = true; + return desc; + } + + // Meta combinator: return a new GMatDesc + // reinterpreting 1-channel input as planar image + // (size height is divided by plane number) + GAPI_WRAP GMatDesc asPlanar(int planes) const + { + GAPI_Assert(planar == false); + GAPI_Assert(chan == 1); + GAPI_Assert(planes > 1); + GAPI_Assert(size.height % planes == 0); + GMatDesc desc(*this); + desc.size.height /= planes; + desc.chan = planes; + return desc.asPlanar(); + } + + // Meta combinator: return a new GMatDesc with planar flag set to false + // (no size changes are performed, only channel interpretation is changed + // (planar -> interleaved) + GAPI_WRAP GMatDesc asInterleaved() const + { + GAPI_Assert(planar == true); + GMatDesc desc(*this); + desc.planar = false; + return desc; + } +}; + +static inline GMatDesc empty_gmat_desc() { return GMatDesc{-1,-1,{-1,-1}}; } + +namespace gapi { namespace detail { +/** Checks GMatDesc fields if the passed matrix is a set of n-dimentional points. +@param in GMatDesc to check. +@param n expected dimensionality. +@return the amount of points. In case input matrix can't be described as vector of points +of expected dimensionality, returns -1. + */ +int checkVector(const GMatDesc& in, const size_t n); + +/** @overload + +Checks GMatDesc fields if the passed matrix can be described as a set of points of any +dimensionality. + +@return array of two elements in form of std::vector: the amount of points +and their calculated dimensionality. In case input matrix can't be described as vector of points, +returns {-1, -1}. + */ +std::vector checkVector(const GMatDesc& in); +}} // namespace gapi::detail + +#if !defined(GAPI_STANDALONE) +GAPI_EXPORTS GMatDesc descr_of(const cv::UMat &mat); +#endif // !defined(GAPI_STANDALONE) + +//Fwd declarations +namespace gapi { namespace own { + class Mat; + GAPI_EXPORTS GMatDesc descr_of(const Mat &mat); +}}//gapi::own + +GAPI_EXPORTS GMatDesc descr_of(const RMat &mat); + +#if !defined(GAPI_STANDALONE) +GAPI_EXPORTS GMatDesc descr_of(const cv::Mat &mat); +#else +using gapi::own::descr_of; +#endif + +/** @} */ + +GAPI_EXPORTS std::ostream& operator<<(std::ostream& os, const cv::GMatDesc &desc); + +} // namespace cv + +#endif // OPENCV_GAPI_GMAT_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gmetaarg.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gmetaarg.hpp index f21182c19f..f9aac032e4 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gmetaarg.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gmetaarg.hpp @@ -1,80 +1,80 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_GMETAARG_HPP -#define OPENCV_GAPI_GMETAARG_HPP - -#include -#include - -#include -#include - -#include -#include -#include -#include -#include - -namespace cv -{ -// FIXME: Rename to GMeta? -// FIXME: user shouldn't deal with it - put to detail? -// GMetaArg is an union type over descriptions of G-types which can serve as -// GComputation's in/output slots. -// -// GMetaArg objects are passed as arguments to GComputation::compile() -// to specify which data a compiled computation should be specialized on. -// For manual compile(), user must supply this metadata, in case of apply() -// this metadata is taken from arguments computation should operate on. -// -// The first type (monostate) is equal to "uninitialized"/"unresolved" meta. -using GMetaArg = util::variant - < util::monostate - , GMatDesc - , GScalarDesc - , GArrayDesc - , GOpaqueDesc - , GFrameDesc - >; -GAPI_EXPORTS std::ostream& operator<<(std::ostream& os, const GMetaArg &); - -using GMetaArgs = std::vector; - -namespace detail -{ - // These traits are used by GComputation::compile() - - // FIXME: is_constructible doesn't work as variant doesn't do any SFINAE - // in its current template constructor - - template struct is_meta_descr : std::false_type {}; - template<> struct is_meta_descr : std::true_type {}; - template<> struct is_meta_descr : std::true_type {}; - template<> struct is_meta_descr : std::true_type {}; - template<> struct is_meta_descr : std::true_type {}; - - template - using are_meta_descrs = all_satisfy; - - template - using are_meta_descrs_but_last = all_satisfy::type>; - -} // namespace detail - -// Note: descr_of(std::vector<..>) returns a GArrayDesc, while -// descrs_of(std::vector<..>) returns an array of Meta args! -class UMat; -GAPI_EXPORTS cv::GMetaArgs descrs_of(const std::vector &vec); -GAPI_EXPORTS cv::GMetaArgs descrs_of(const std::vector &vec); -namespace gapi { namespace own { - GAPI_EXPORTS cv::GMetaArgs descrs_of(const std::vector &vec); -}} // namespace gapi::own - -} // namespace cv - -#endif // OPENCV_GAPI_GMETAARG_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_GMETAARG_HPP +#define OPENCV_GAPI_GMETAARG_HPP + +#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +namespace cv +{ +// FIXME: Rename to GMeta? +// FIXME: user shouldn't deal with it - put to detail? +// GMetaArg is an union type over descriptions of G-types which can serve as +// GComputation's in/output slots. +// +// GMetaArg objects are passed as arguments to GComputation::compile() +// to specify which data a compiled computation should be specialized on. +// For manual compile(), user must supply this metadata, in case of apply() +// this metadata is taken from arguments computation should operate on. +// +// The first type (monostate) is equal to "uninitialized"/"unresolved" meta. +using GMetaArg = util::variant + < util::monostate + , GMatDesc + , GScalarDesc + , GArrayDesc + , GOpaqueDesc + , GFrameDesc + >; +GAPI_EXPORTS std::ostream& operator<<(std::ostream& os, const GMetaArg &); + +using GMetaArgs = std::vector; + +namespace detail +{ + // These traits are used by GComputation::compile() + + // FIXME: is_constructible doesn't work as variant doesn't do any SFINAE + // in its current template constructor + + template struct is_meta_descr : std::false_type {}; + template<> struct is_meta_descr : std::true_type {}; + template<> struct is_meta_descr : std::true_type {}; + template<> struct is_meta_descr : std::true_type {}; + template<> struct is_meta_descr : std::true_type {}; + + template + using are_meta_descrs = all_satisfy; + + template + using are_meta_descrs_but_last = all_satisfy::type>; + +} // namespace detail + +// Note: descr_of(std::vector<..>) returns a GArrayDesc, while +// descrs_of(std::vector<..>) returns an array of Meta args! +class UMat; +GAPI_EXPORTS cv::GMetaArgs descrs_of(const std::vector &vec); +GAPI_EXPORTS cv::GMetaArgs descrs_of(const std::vector &vec); +namespace gapi { namespace own { + GAPI_EXPORTS cv::GMetaArgs descrs_of(const std::vector &vec); +}} // namespace gapi::own + +} // namespace cv + +#endif // OPENCV_GAPI_GMETAARG_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gopaque.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gopaque.hpp index a3f98a9867..207556f0b7 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gopaque.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gopaque.hpp @@ -1,369 +1,369 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019-2020 Intel Corporation - - -#ifndef OPENCV_GAPI_GOPAQUE_HPP -#define OPENCV_GAPI_GOPAQUE_HPP - -#include -#include -#include - -#include -#include - -#include -#include -#include -#include -#include - -#include // OpaqueKind -#include // TypeHintBase - -namespace cv -{ -// Forward declaration; GNode and GOrigin are an internal -// (user-inaccessible) classes. -class GNode; -struct GOrigin; -template class GOpaque; - -/** - * \addtogroup gapi_meta_args - * @{ - */ -struct GAPI_EXPORTS_W_SIMPLE GOpaqueDesc -{ - // FIXME: Body - // FIXME: Also implement proper operator== then - bool operator== (const GOpaqueDesc&) const { return true; } -}; -template GOpaqueDesc descr_of(const U &) { return {};} -GAPI_EXPORTS_W inline GOpaqueDesc empty_gopaque_desc() {return {}; } -/** @} */ - -std::ostream& operator<<(std::ostream& os, const cv::GOpaqueDesc &desc); - -namespace detail -{ - // ConstructOpaque is a callback which stores information about T and is used by - // G-API runtime to construct an object in host memory (T remains opaque for G-API). - // ConstructOpaque is carried into G-API internals by GOpaqueU. - // Currently it is suitable for Host (CPU) plugins only, real offload may require - // more information for manual memory allocation on-device. - class OpaqueRef; - using ConstructOpaque = std::function; - - // FIXME: garray.hpp already contains hint classes (for actual T type verification), - // need to think where it can be moved (currently opaque uses it from garray) - - // This class strips type information from GOpaque and makes it usable - // in the G-API graph compiler (expression unrolling, graph generation, etc). - // Part of GProtoArg. - class GAPI_EXPORTS GOpaqueU - { - public: - GOpaqueU(const GNode &n, std::size_t out); // Operation result constructor - - template - bool holds() const; // Check if was created from GOpaque - - GOrigin& priv(); // Internal use only - const GOrigin& priv() const; // Internal use only - - protected: - GOpaqueU(); // Default constructor - template friend class cv::GOpaque; // (available for GOpaque only) - - void setConstructFcn(ConstructOpaque &&cv); // Store T-aware constructor - - template - void specifyType(); // Store type of initial GOpaque - - template - void storeKind(); - - void setKind(cv::detail::OpaqueKind); - - std::shared_ptr m_priv; - std::shared_ptr m_hint; - }; - - template - bool GOpaqueU::holds() const{ - GAPI_Assert(m_hint != nullptr); - using U = util::decay_t; - return dynamic_cast*>(m_hint.get()) != nullptr; - } - - template - void GOpaqueU::specifyType(){ - m_hint.reset(new TypeHint>); - } - - template - void GOpaqueU::storeKind(){ - // FIXME: Add assert here on cv::Mat and cv::Scalar? - setKind(cv::detail::GOpaqueTraits::kind); - } - - // This class represents a typed object reference. - // Depending on origins, this reference may be either "just a" reference to - // an object created externally, OR actually own the underlying object - // (be value holder). - class BasicOpaqueRef - { - public: - cv::GOpaqueDesc m_desc; - virtual ~BasicOpaqueRef() {} - - virtual void mov(BasicOpaqueRef &ref) = 0; - virtual const void* ptr() const = 0; - virtual void set(const cv::util::any &a) = 0; - }; - - template class OpaqueRefT final: public BasicOpaqueRef - { - using empty_t = util::monostate; - using ro_ext_t = const T *; - using rw_ext_t = T *; - using rw_own_t = T ; - util::variant m_ref; - - inline bool isEmpty() const { return util::holds_alternative(m_ref); } - inline bool isROExt() const { return util::holds_alternative(m_ref); } - inline bool isRWExt() const { return util::holds_alternative(m_ref); } - inline bool isRWOwn() const { return util::holds_alternative(m_ref); } - - void init(const T* obj = nullptr) - { - if (obj) m_desc = cv::descr_of(*obj); - } - - public: - OpaqueRefT() { init(); } - virtual ~OpaqueRefT() {} - - explicit OpaqueRefT(const T& obj) : m_ref(&obj) { init(&obj); } - explicit OpaqueRefT( T& obj) : m_ref(&obj) { init(&obj); } - explicit OpaqueRefT( T&& obj) : m_ref(std::move(obj)) { init(&obj); } - - // Reset a OpaqueRefT. Called only for objects instantiated - // internally in G-API (e.g. temporary GOpaque's within a - // computation). Reset here means both initialization - // (creating an object) and reset (discarding its existing - // content before the next execution). Must never be called - // for external OpaqueRefTs. - void reset() - { - if (isEmpty()) - { - T empty_obj{}; - m_desc = cv::descr_of(empty_obj); - m_ref = std::move(empty_obj); - GAPI_Assert(isRWOwn()); - } - else if (isRWOwn()) - { - util::get(m_ref) = {}; - } - else GAPI_Error("InternalError"); // shouldn't be called in *EXT modes - } - - // Obtain a WRITE reference to underlying object - // Used by CPU kernel API wrappers when a kernel execution frame - // is created - T& wref() - { - GAPI_Assert(isRWExt() || isRWOwn()); - if (isRWExt()) return *util::get(m_ref); - if (isRWOwn()) return util::get(m_ref); - util::throw_error(std::logic_error("Impossible happened")); - } - - // Obtain a READ reference to underlying object - // Used by CPU kernel API wrappers when a kernel execution frame - // is created - const T& rref() const - { - // ANY object can be accessed for reading, even if it declared for - // output. Example -- a GComputation from [in] to [out1,out2] - // where [out2] is a result of operation applied to [out1]: - // - // GComputation boundary - // . . . . . . . - // . . - // [in] ----> foo() ----> [out1] - // . . : - // . . . .:. . . - // . V . - // . bar() ---> [out2] - // . . . . . . . . . . . . - // - if (isROExt()) return *util::get(m_ref); - if (isRWExt()) return *util::get(m_ref); - if (isRWOwn()) return util::get(m_ref); - util::throw_error(std::logic_error("Impossible happened")); - } - - virtual void mov(BasicOpaqueRef &v) override { - OpaqueRefT *tv = dynamic_cast*>(&v); - GAPI_Assert(tv != nullptr); - wref() = std::move(tv->wref()); - } - - virtual const void* ptr() const override { return &rref(); } - - virtual void set(const cv::util::any &a) override { - wref() = util::any_cast(a); - } - }; - - // This class strips type information from OpaqueRefT<> and makes it usable - // in the G-API executables (carrying run-time data/information to kernels). - // Part of GRunArg. - // Its methods are typed proxies to OpaqueRefT. - // OpaqueRef maintains "reference" semantics so two copies of OpaqueRef refer - // to the same underlying object. - class OpaqueRef - { - std::shared_ptr m_ref; - cv::detail::OpaqueKind m_kind = cv::detail::OpaqueKind::CV_UNKNOWN; - - template inline void check() const - { - GAPI_DbgAssert(dynamic_cast*>(m_ref.get()) != nullptr); - } - - public: - OpaqueRef() = default; - - template< - typename T, - typename = util::are_different_t - > - // FIXME: probably won't work with const object - explicit OpaqueRef(T&& obj) : - m_ref(new OpaqueRefT>(std::forward(obj))), - m_kind(GOpaqueTraits>::kind) {} - - cv::detail::OpaqueKind getKind() const - { - return m_kind; - } - - template void reset() - { - if (!m_ref) m_ref.reset(new OpaqueRefT()); - check(); - storeKind(); - static_cast&>(*m_ref).reset(); - } - - template - void storeKind() - { - m_kind = cv::detail::GOpaqueTraits::kind; - } - - template T& wref() - { - check(); - return static_cast&>(*m_ref).wref(); - } - - template const T& rref() const - { - check(); - return static_cast&>(*m_ref).rref(); - } - - void mov(OpaqueRef &v) - { - m_ref->mov(*v.m_ref); - } - - cv::GOpaqueDesc descr_of() const - { - return m_ref->m_desc; - } - - // May be used to uniquely identify this object internally - const void *ptr() const { return m_ref->ptr(); } - - // Introduced for in-graph meta handling - OpaqueRef& operator= (const cv::util::any &a) - { - m_ref->set(a); - return *this; - } - }; -} // namespace detail - -/** \addtogroup gapi_data_objects - * @{ - */ -/** - * @brief `cv::GOpaque` template class represents an object of - * class `T` in the graph. - * - * `cv::GOpaque` describes a functional relationship between operations - * consuming and producing object of class `T`. `cv::GOpaque` is - * designed to extend G-API with user-defined data types, which are - * often required with user-defined operations. G-API can't apply any - * optimizations to user-defined types since these types are opaque to - * the framework. However, there is a number of G-API operations - * declared with `cv::GOpaque` as a return type, - * e.g. cv::gapi::streaming::timestamp() or cv::gapi::streaming::size(). - * - * @sa `cv::GArray` - */ -template class GOpaque -{ -public: - // Host type (or Flat type) - the type this GOpaque is actually - // specified to. - /// @private - using HT = typename detail::flatten_g>::type; - - /** - * @brief Constructs an empty `cv::GOpaque` - * - * Normally, empty G-API data objects denote a starting point of - * the graph. When an empty `cv::GOpaque` is assigned to a result - * of some operation, it obtains a functional link to this - * operation (and is not empty anymore). - */ - GOpaque() { putDetails(); } // Empty constructor - - /// @private - explicit GOpaque(detail::GOpaqueU &&ref) // GOpaqueU-based constructor - : m_ref(ref) { putDetails(); } // (used by GCall, not for users) - - /// @private - detail::GOpaqueU strip() const { - return m_ref; - } - /// @private - static void Ctor(detail::OpaqueRef& ref) { - ref.reset(); - } -private: - void putDetails() { - m_ref.setConstructFcn(&Ctor); - m_ref.specifyType(); - m_ref.storeKind(); - } - - detail::GOpaqueU m_ref; -}; - -/** @} */ - -} // namespace cv - -#endif // OPENCV_GAPI_GOPAQUE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019-2020 Intel Corporation + + +#ifndef OPENCV_GAPI_GOPAQUE_HPP +#define OPENCV_GAPI_GOPAQUE_HPP + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +#include // OpaqueKind +#include // TypeHintBase + +namespace cv +{ +// Forward declaration; GNode and GOrigin are an internal +// (user-inaccessible) classes. +class GNode; +struct GOrigin; +template class GOpaque; + +/** + * \addtogroup gapi_meta_args + * @{ + */ +struct GAPI_EXPORTS_W_SIMPLE GOpaqueDesc +{ + // FIXME: Body + // FIXME: Also implement proper operator== then + bool operator== (const GOpaqueDesc&) const { return true; } +}; +template GOpaqueDesc descr_of(const U &) { return {};} +GAPI_EXPORTS_W inline GOpaqueDesc empty_gopaque_desc() {return {}; } +/** @} */ + +std::ostream& operator<<(std::ostream& os, const cv::GOpaqueDesc &desc); + +namespace detail +{ + // ConstructOpaque is a callback which stores information about T and is used by + // G-API runtime to construct an object in host memory (T remains opaque for G-API). + // ConstructOpaque is carried into G-API internals by GOpaqueU. + // Currently it is suitable for Host (CPU) plugins only, real offload may require + // more information for manual memory allocation on-device. + class OpaqueRef; + using ConstructOpaque = std::function; + + // FIXME: garray.hpp already contains hint classes (for actual T type verification), + // need to think where it can be moved (currently opaque uses it from garray) + + // This class strips type information from GOpaque and makes it usable + // in the G-API graph compiler (expression unrolling, graph generation, etc). + // Part of GProtoArg. + class GAPI_EXPORTS GOpaqueU + { + public: + GOpaqueU(const GNode &n, std::size_t out); // Operation result constructor + + template + bool holds() const; // Check if was created from GOpaque + + GOrigin& priv(); // Internal use only + const GOrigin& priv() const; // Internal use only + + protected: + GOpaqueU(); // Default constructor + template friend class cv::GOpaque; // (available for GOpaque only) + + void setConstructFcn(ConstructOpaque &&cv); // Store T-aware constructor + + template + void specifyType(); // Store type of initial GOpaque + + template + void storeKind(); + + void setKind(cv::detail::OpaqueKind); + + std::shared_ptr m_priv; + std::shared_ptr m_hint; + }; + + template + bool GOpaqueU::holds() const{ + GAPI_Assert(m_hint != nullptr); + using U = util::decay_t; + return dynamic_cast*>(m_hint.get()) != nullptr; + } + + template + void GOpaqueU::specifyType(){ + m_hint.reset(new TypeHint>); + } + + template + void GOpaqueU::storeKind(){ + // FIXME: Add assert here on cv::Mat and cv::Scalar? + setKind(cv::detail::GOpaqueTraits::kind); + } + + // This class represents a typed object reference. + // Depending on origins, this reference may be either "just a" reference to + // an object created externally, OR actually own the underlying object + // (be value holder). + class BasicOpaqueRef + { + public: + cv::GOpaqueDesc m_desc; + virtual ~BasicOpaqueRef() {} + + virtual void mov(BasicOpaqueRef &ref) = 0; + virtual const void* ptr() const = 0; + virtual void set(const cv::util::any &a) = 0; + }; + + template class OpaqueRefT final: public BasicOpaqueRef + { + using empty_t = util::monostate; + using ro_ext_t = const T *; + using rw_ext_t = T *; + using rw_own_t = T ; + util::variant m_ref; + + inline bool isEmpty() const { return util::holds_alternative(m_ref); } + inline bool isROExt() const { return util::holds_alternative(m_ref); } + inline bool isRWExt() const { return util::holds_alternative(m_ref); } + inline bool isRWOwn() const { return util::holds_alternative(m_ref); } + + void init(const T* obj = nullptr) + { + if (obj) m_desc = cv::descr_of(*obj); + } + + public: + OpaqueRefT() { init(); } + virtual ~OpaqueRefT() {} + + explicit OpaqueRefT(const T& obj) : m_ref(&obj) { init(&obj); } + explicit OpaqueRefT( T& obj) : m_ref(&obj) { init(&obj); } + explicit OpaqueRefT( T&& obj) : m_ref(std::move(obj)) { init(&obj); } + + // Reset a OpaqueRefT. Called only for objects instantiated + // internally in G-API (e.g. temporary GOpaque's within a + // computation). Reset here means both initialization + // (creating an object) and reset (discarding its existing + // content before the next execution). Must never be called + // for external OpaqueRefTs. + void reset() + { + if (isEmpty()) + { + T empty_obj{}; + m_desc = cv::descr_of(empty_obj); + m_ref = std::move(empty_obj); + GAPI_Assert(isRWOwn()); + } + else if (isRWOwn()) + { + util::get(m_ref) = {}; + } + else GAPI_Error("InternalError"); // shouldn't be called in *EXT modes + } + + // Obtain a WRITE reference to underlying object + // Used by CPU kernel API wrappers when a kernel execution frame + // is created + T& wref() + { + GAPI_Assert(isRWExt() || isRWOwn()); + if (isRWExt()) return *util::get(m_ref); + if (isRWOwn()) return util::get(m_ref); + util::throw_error(std::logic_error("Impossible happened")); + } + + // Obtain a READ reference to underlying object + // Used by CPU kernel API wrappers when a kernel execution frame + // is created + const T& rref() const + { + // ANY object can be accessed for reading, even if it declared for + // output. Example -- a GComputation from [in] to [out1,out2] + // where [out2] is a result of operation applied to [out1]: + // + // GComputation boundary + // . . . . . . . + // . . + // [in] ----> foo() ----> [out1] + // . . : + // . . . .:. . . + // . V . + // . bar() ---> [out2] + // . . . . . . . . . . . . + // + if (isROExt()) return *util::get(m_ref); + if (isRWExt()) return *util::get(m_ref); + if (isRWOwn()) return util::get(m_ref); + util::throw_error(std::logic_error("Impossible happened")); + } + + virtual void mov(BasicOpaqueRef &v) override { + OpaqueRefT *tv = dynamic_cast*>(&v); + GAPI_Assert(tv != nullptr); + wref() = std::move(tv->wref()); + } + + virtual const void* ptr() const override { return &rref(); } + + virtual void set(const cv::util::any &a) override { + wref() = util::any_cast(a); + } + }; + + // This class strips type information from OpaqueRefT<> and makes it usable + // in the G-API executables (carrying run-time data/information to kernels). + // Part of GRunArg. + // Its methods are typed proxies to OpaqueRefT. + // OpaqueRef maintains "reference" semantics so two copies of OpaqueRef refer + // to the same underlying object. + class OpaqueRef + { + std::shared_ptr m_ref; + cv::detail::OpaqueKind m_kind = cv::detail::OpaqueKind::CV_UNKNOWN; + + template inline void check() const + { + GAPI_DbgAssert(dynamic_cast*>(m_ref.get()) != nullptr); + } + + public: + OpaqueRef() = default; + + template< + typename T, + typename = util::are_different_t + > + // FIXME: probably won't work with const object + explicit OpaqueRef(T&& obj) : + m_ref(new OpaqueRefT>(std::forward(obj))), + m_kind(GOpaqueTraits>::kind) {} + + cv::detail::OpaqueKind getKind() const + { + return m_kind; + } + + template void reset() + { + if (!m_ref) m_ref.reset(new OpaqueRefT()); + check(); + storeKind(); + static_cast&>(*m_ref).reset(); + } + + template + void storeKind() + { + m_kind = cv::detail::GOpaqueTraits::kind; + } + + template T& wref() + { + check(); + return static_cast&>(*m_ref).wref(); + } + + template const T& rref() const + { + check(); + return static_cast&>(*m_ref).rref(); + } + + void mov(OpaqueRef &v) + { + m_ref->mov(*v.m_ref); + } + + cv::GOpaqueDesc descr_of() const + { + return m_ref->m_desc; + } + + // May be used to uniquely identify this object internally + const void *ptr() const { return m_ref->ptr(); } + + // Introduced for in-graph meta handling + OpaqueRef& operator= (const cv::util::any &a) + { + m_ref->set(a); + return *this; + } + }; +} // namespace detail + +/** \addtogroup gapi_data_objects + * @{ + */ +/** + * @brief `cv::GOpaque` template class represents an object of + * class `T` in the graph. + * + * `cv::GOpaque` describes a functional relationship between operations + * consuming and producing object of class `T`. `cv::GOpaque` is + * designed to extend G-API with user-defined data types, which are + * often required with user-defined operations. G-API can't apply any + * optimizations to user-defined types since these types are opaque to + * the framework. However, there is a number of G-API operations + * declared with `cv::GOpaque` as a return type, + * e.g. cv::gapi::streaming::timestamp() or cv::gapi::streaming::size(). + * + * @sa `cv::GArray` + */ +template class GOpaque +{ +public: + // Host type (or Flat type) - the type this GOpaque is actually + // specified to. + /// @private + using HT = typename detail::flatten_g>::type; + + /** + * @brief Constructs an empty `cv::GOpaque` + * + * Normally, empty G-API data objects denote a starting point of + * the graph. When an empty `cv::GOpaque` is assigned to a result + * of some operation, it obtains a functional link to this + * operation (and is not empty anymore). + */ + GOpaque() { putDetails(); } // Empty constructor + + /// @private + explicit GOpaque(detail::GOpaqueU &&ref) // GOpaqueU-based constructor + : m_ref(ref) { putDetails(); } // (used by GCall, not for users) + + /// @private + detail::GOpaqueU strip() const { + return m_ref; + } + /// @private + static void Ctor(detail::OpaqueRef& ref) { + ref.reset(); + } +private: + void putDetails() { + m_ref.setConstructFcn(&Ctor); + m_ref.specifyType(); + m_ref.storeKind(); + } + + detail::GOpaqueU m_ref; +}; + +/** @} */ + +} // namespace cv + +#endif // OPENCV_GAPI_GOPAQUE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gproto.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gproto.hpp index a2b5d83bc1..fd16f0a7c6 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gproto.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gproto.hpp @@ -1,159 +1,159 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_GPROTO_HPP -#define OPENCV_GAPI_GPROTO_HPP - -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include - -namespace cv { - -// FIXME: user shouldn't deal with it - put to detail? -// GProtoArg is an union type over G-types which can serve as -// GComputation's in/output slots. In other words, GProtoArg -// wraps any type which can serve as G-API exchange type. -// -// In Runtime, GProtoArgs are substituted with appropriate GRunArgs. -// -// GProtoArg objects are constructed in-place when user describes -// (captures) computations, user doesn't interact with these types -// directly. -using GProtoArg = util::variant - < GMat - , GMatP - , GFrame - , GScalar - , detail::GArrayU // instead of GArray - , detail::GOpaqueU // instead of GOpaque - >; - -using GProtoArgs = std::vector; - -namespace detail -{ -template inline GProtoArgs packArgs(Ts... args) -{ - return GProtoArgs{ GProtoArg(wrap_gapi_helper::wrap(args))... }; -} - -} - -template -struct GIOProtoArgs -{ -public: - // NB: Used by python wrapper - GIOProtoArgs() = default; - explicit GIOProtoArgs(const GProtoArgs& args) : m_args(args) {} - explicit GIOProtoArgs(GProtoArgs &&args) : m_args(std::move(args)) {} - - GProtoArgs m_args; - - // TODO: Think about the addition operator - /** - * @brief This operator allows to complement the proto vectors at runtime. - * - * It's an ordinary overload of addition assignment operator. - * - * Example of usage: - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/dynamic_graph_snippets.cpp GIOProtoArgs usage - * - */ - template - friend GIOProtoArgs& operator += (GIOProtoArgs &lhs, const GIOProtoArgs &rhs); -}; - -template -cv::GIOProtoArgs& operator += (cv::GIOProtoArgs &lhs, const cv::GIOProtoArgs &rhs) -{ - lhs.m_args.reserve(lhs.m_args.size() + rhs.m_args.size()); - lhs.m_args.insert(lhs.m_args.end(), rhs.m_args.begin(), rhs.m_args.end()); - return lhs; -} - -struct In_Tag{}; -struct Out_Tag{}; - -using GProtoInputArgs = GIOProtoArgs; -using GProtoOutputArgs = GIOProtoArgs; - -// Perfect forwarding -template inline GProtoInputArgs GIn(Ts&&... ts) -{ - return GProtoInputArgs(detail::packArgs(std::forward(ts)...)); -} - -template inline GProtoOutputArgs GOut(Ts&&... ts) -{ - return GProtoOutputArgs(detail::packArgs(std::forward(ts)...)); -} - -namespace detail -{ - // Extract elements form tuple - // FIXME: Someday utilize a generic tuple_to_vec<> routine - template - static GProtoOutputArgs getGOut_impl(const std::tuple& ts, detail::Seq) - { - return GProtoOutputArgs{ detail::packArgs(std::get(ts)...)}; - } -} - -template inline GProtoOutputArgs GOut(const std::tuple& ts) -{ - // TODO: think of std::forward(ts) - return detail::getGOut_impl(ts, typename detail::MkSeq::type()); -} - -// Takes rvalue as input arg -template inline GProtoOutputArgs GOut(std::tuple&& ts) -{ - // TODO: think of std::forward(ts) - return detail::getGOut_impl(ts, typename detail::MkSeq::type()); -} - -// Extract run-time arguments from node origin -// Can be used to extract constant values associated with G-objects -// (like GScalar) at graph construction time -GRunArg value_of(const GOrigin &origin); - -// Transform run-time computation arguments into a collection of metadata -// extracted from that arguments -GMetaArg GAPI_EXPORTS descr_of(const GRunArg &arg ); -GMetaArgs GAPI_EXPORTS descr_of(const GRunArgs &args); - -// Transform run-time operation result argument into metadata extracted from that argument -// Used to compare the metadata, which generated at compile time with the metadata result operation in run time -GMetaArg GAPI_EXPORTS descr_of(const GRunArgP& argp); - -// Checks if run-time computation argument can be described by metadata -bool GAPI_EXPORTS can_describe(const GMetaArg& meta, const GRunArg& arg); -bool GAPI_EXPORTS can_describe(const GMetaArgs& metas, const GRunArgs& args); - -// Checks if run-time computation result argument can be described by metadata. -// Used to check if the metadata generated at compile time -// coincides with output arguments passed to computation in cpu and ocl backends -bool GAPI_EXPORTS can_describe(const GMetaArg& meta, const GRunArgP& argp); - -// Validates input arguments -void GAPI_EXPORTS validate_input_arg(const GRunArg& arg); -void GAPI_EXPORTS validate_input_args(const GRunArgs& args); - -} // namespace cv - -#endif // OPENCV_GAPI_GPROTO_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_GPROTO_HPP +#define OPENCV_GAPI_GPROTO_HPP + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace cv { + +// FIXME: user shouldn't deal with it - put to detail? +// GProtoArg is an union type over G-types which can serve as +// GComputation's in/output slots. In other words, GProtoArg +// wraps any type which can serve as G-API exchange type. +// +// In Runtime, GProtoArgs are substituted with appropriate GRunArgs. +// +// GProtoArg objects are constructed in-place when user describes +// (captures) computations, user doesn't interact with these types +// directly. +using GProtoArg = util::variant + < GMat + , GMatP + , GFrame + , GScalar + , detail::GArrayU // instead of GArray + , detail::GOpaqueU // instead of GOpaque + >; + +using GProtoArgs = std::vector; + +namespace detail +{ +template inline GProtoArgs packArgs(Ts... args) +{ + return GProtoArgs{ GProtoArg(wrap_gapi_helper::wrap(args))... }; +} + +} + +template +struct GIOProtoArgs +{ +public: + // NB: Used by python wrapper + GIOProtoArgs() = default; + explicit GIOProtoArgs(const GProtoArgs& args) : m_args(args) {} + explicit GIOProtoArgs(GProtoArgs &&args) : m_args(std::move(args)) {} + + GProtoArgs m_args; + + // TODO: Think about the addition operator + /** + * @brief This operator allows to complement the proto vectors at runtime. + * + * It's an ordinary overload of addition assignment operator. + * + * Example of usage: + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/dynamic_graph_snippets.cpp GIOProtoArgs usage + * + */ + template + friend GIOProtoArgs& operator += (GIOProtoArgs &lhs, const GIOProtoArgs &rhs); +}; + +template +cv::GIOProtoArgs& operator += (cv::GIOProtoArgs &lhs, const cv::GIOProtoArgs &rhs) +{ + lhs.m_args.reserve(lhs.m_args.size() + rhs.m_args.size()); + lhs.m_args.insert(lhs.m_args.end(), rhs.m_args.begin(), rhs.m_args.end()); + return lhs; +} + +struct In_Tag{}; +struct Out_Tag{}; + +using GProtoInputArgs = GIOProtoArgs; +using GProtoOutputArgs = GIOProtoArgs; + +// Perfect forwarding +template inline GProtoInputArgs GIn(Ts&&... ts) +{ + return GProtoInputArgs(detail::packArgs(std::forward(ts)...)); +} + +template inline GProtoOutputArgs GOut(Ts&&... ts) +{ + return GProtoOutputArgs(detail::packArgs(std::forward(ts)...)); +} + +namespace detail +{ + // Extract elements form tuple + // FIXME: Someday utilize a generic tuple_to_vec<> routine + template + static GProtoOutputArgs getGOut_impl(const std::tuple& ts, detail::Seq) + { + return GProtoOutputArgs{ detail::packArgs(std::get(ts)...)}; + } +} + +template inline GProtoOutputArgs GOut(const std::tuple& ts) +{ + // TODO: think of std::forward(ts) + return detail::getGOut_impl(ts, typename detail::MkSeq::type()); +} + +// Takes rvalue as input arg +template inline GProtoOutputArgs GOut(std::tuple&& ts) +{ + // TODO: think of std::forward(ts) + return detail::getGOut_impl(ts, typename detail::MkSeq::type()); +} + +// Extract run-time arguments from node origin +// Can be used to extract constant values associated with G-objects +// (like GScalar) at graph construction time +GRunArg value_of(const GOrigin &origin); + +// Transform run-time computation arguments into a collection of metadata +// extracted from that arguments +GMetaArg GAPI_EXPORTS descr_of(const GRunArg &arg ); +GMetaArgs GAPI_EXPORTS descr_of(const GRunArgs &args); + +// Transform run-time operation result argument into metadata extracted from that argument +// Used to compare the metadata, which generated at compile time with the metadata result operation in run time +GMetaArg GAPI_EXPORTS descr_of(const GRunArgP& argp); + +// Checks if run-time computation argument can be described by metadata +bool GAPI_EXPORTS can_describe(const GMetaArg& meta, const GRunArg& arg); +bool GAPI_EXPORTS can_describe(const GMetaArgs& metas, const GRunArgs& args); + +// Checks if run-time computation result argument can be described by metadata. +// Used to check if the metadata generated at compile time +// coincides with output arguments passed to computation in cpu and ocl backends +bool GAPI_EXPORTS can_describe(const GMetaArg& meta, const GRunArgP& argp); + +// Validates input arguments +void GAPI_EXPORTS validate_input_arg(const GRunArg& arg); +void GAPI_EXPORTS validate_input_args(const GRunArgs& args); + +} // namespace cv + +#endif // OPENCV_GAPI_GPROTO_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gpu/core.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gpu/core.hpp index a7ee59577c..c5498fe95f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gpu/core.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gpu/core.hpp @@ -1,27 +1,27 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_GPU_CORE_API_HPP -#define OPENCV_GAPI_GPU_CORE_API_HPP -/** @file -* @deprecated Use instead. -*/ - -#include - -namespace cv { -namespace gapi { -namespace core { -namespace gpu { - using namespace ocl; -} // namespace gpu -} // namespace core -} // namespace gapi -} // namespace cv - - -#endif // OPENCV_GAPI_GPU_CORE_API_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_GPU_CORE_API_HPP +#define OPENCV_GAPI_GPU_CORE_API_HPP +/** @file +* @deprecated Use instead. +*/ + +#include + +namespace cv { +namespace gapi { +namespace core { +namespace gpu { + using namespace ocl; +} // namespace gpu +} // namespace core +} // namespace gapi +} // namespace cv + + +#endif // OPENCV_GAPI_GPU_CORE_API_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gpu/ggpukernel.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gpu/ggpukernel.hpp index b52c21de6b..9373ed79de 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gpu/ggpukernel.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gpu/ggpukernel.hpp @@ -1,18 +1,18 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_GGPUKERNEL_HPP -#define OPENCV_GAPI_GGPUKERNEL_HPP -/** @file -* @deprecated Use instead. -*/ - -#include -#define GAPI_GPU_KERNEL GAPI_OCL_KERNEL - - -#endif // OPENCV_GAPI_GGPUKERNEL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_GGPUKERNEL_HPP +#define OPENCV_GAPI_GGPUKERNEL_HPP +/** @file +* @deprecated Use instead. +*/ + +#include +#define GAPI_GPU_KERNEL GAPI_OCL_KERNEL + + +#endif // OPENCV_GAPI_GGPUKERNEL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gpu/imgproc.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gpu/imgproc.hpp index b0df7ae331..cc0a93d884 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gpu/imgproc.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gpu/imgproc.hpp @@ -1,28 +1,28 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_GPU_IMGPROC_API_HPP -#define OPENCV_GAPI_GPU_IMGPROC_API_HPP -/** @file -* @deprecated Use instead. -*/ - -#include - - -namespace cv { -namespace gapi { -namespace imgproc { -namespace gpu { - using namespace ocl; -} // namespace gpu -} // namespace imgproc -} // namespace gapi -} // namespace cv - - -#endif // OPENCV_GAPI_GPU_IMGPROC_API_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_GPU_IMGPROC_API_HPP +#define OPENCV_GAPI_GPU_IMGPROC_API_HPP +/** @file +* @deprecated Use instead. +*/ + +#include + + +namespace cv { +namespace gapi { +namespace imgproc { +namespace gpu { + using namespace ocl; +} // namespace gpu +} // namespace imgproc +} // namespace gapi +} // namespace cv + + +#endif // OPENCV_GAPI_GPU_IMGPROC_API_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gscalar.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gscalar.hpp index de0dfe1383..03a70dfc32 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gscalar.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gscalar.hpp @@ -1,140 +1,140 @@ -// This file is part of OpenCV project. - -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_GSCALAR_HPP -#define OPENCV_GAPI_GSCALAR_HPP - -#include - -#include -#include // GShape -#include - -namespace cv -{ -// Forward declaration; GNode and GOrigin are an internal -// (user-inaccessible) classes. -class GNode; -struct GOrigin; - -/** \addtogroup gapi_data_objects - * @{ - */ -/** - * @brief GScalar class represents cv::Scalar data in the graph. - * - * GScalar may be associated with a cv::Scalar value, which becomes - * its constant value bound in graph compile time. cv::GScalar describes a - * functional relationship between operations consuming and producing - * GScalar objects. - * - * GScalar is a virtual counterpart of cv::Scalar, which is usually used - * to represent the GScalar data in G-API during the execution. - * - * @sa Scalar - */ -class GAPI_EXPORTS_W_SIMPLE GScalar -{ -public: - /** - * @brief Constructs an empty GScalar - * - * Normally, empty G-API data objects denote a starting point of - * the graph. When an empty GScalar is assigned to a result of some - * operation, it obtains a functional link to this operation (and - * is not empty anymore). - */ - GAPI_WRAP GScalar(); - - /** - * @brief Constructs a value-initialized GScalar - * - * GScalars may have their values be associated at graph - * construction time. It is useful when some operation has a - * GScalar input which doesn't change during the program - * execution, and is set only once. In this case, there is no need - * to declare such GScalar as a graph input. - * - * @note The value of GScalar may be overwritten by assigning some - * other GScalar to the object using `operator=` -- on the - * assignment, the old GScalar value is discarded. - * - * @param s a cv::Scalar value to associate with this GScalar object. - */ - GAPI_WRAP - explicit GScalar(const cv::Scalar& s); - - /** - * @overload - * @brief Constructs a value-initialized GScalar - * - * @param s a cv::Scalar value to associate with this GScalar object. - */ - explicit GScalar(cv::Scalar&& s); // Constant value move-constructor from cv::Scalar - - /** - * @overload - * @brief Constructs a value-initialized GScalar - * - * @param v0 A `double` value to associate with this GScalar. Note - * that only the first component of a four-component cv::Scalar is - * set to this value, with others remain zeros. - * - * This constructor overload is not marked `explicit` and can be - * used in G-API expression code like this: - * - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp gscalar_implicit - * - * Here operator+(GMat,GScalar) is used to wrap cv::gapi::addC() - * and a value-initialized GScalar is created on the fly. - * - * @overload - */ - GScalar(double v0); // Constant value constructor from double - - /// @private - GScalar(const GNode &n, std::size_t out); // Operation result constructor - /// @private - GOrigin& priv(); // Internal use only - /// @private - const GOrigin& priv() const; // Internal use only - -private: - std::shared_ptr m_priv; -}; - -/** @} */ - -/** - * \addtogroup gapi_meta_args - * @{ - */ -struct GAPI_EXPORTS_W_SIMPLE GScalarDesc -{ - // NB.: right now it is empty - - inline bool operator== (const GScalarDesc &) const - { - return true; // NB: implement this method if GScalar meta appears - } - - inline bool operator!= (const GScalarDesc &rhs) const - { - return !(*this == rhs); - } -}; - -GAPI_EXPORTS_W inline GScalarDesc empty_scalar_desc() { return GScalarDesc(); } - -GAPI_EXPORTS GScalarDesc descr_of(const cv::Scalar &scalar); - -std::ostream& operator<<(std::ostream& os, const cv::GScalarDesc &desc); - -} // namespace cv - -#endif // OPENCV_GAPI_GSCALAR_HPP +// This file is part of OpenCV project. + +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_GSCALAR_HPP +#define OPENCV_GAPI_GSCALAR_HPP + +#include + +#include +#include // GShape +#include + +namespace cv +{ +// Forward declaration; GNode and GOrigin are an internal +// (user-inaccessible) classes. +class GNode; +struct GOrigin; + +/** \addtogroup gapi_data_objects + * @{ + */ +/** + * @brief GScalar class represents cv::Scalar data in the graph. + * + * GScalar may be associated with a cv::Scalar value, which becomes + * its constant value bound in graph compile time. cv::GScalar describes a + * functional relationship between operations consuming and producing + * GScalar objects. + * + * GScalar is a virtual counterpart of cv::Scalar, which is usually used + * to represent the GScalar data in G-API during the execution. + * + * @sa Scalar + */ +class GAPI_EXPORTS_W_SIMPLE GScalar +{ +public: + /** + * @brief Constructs an empty GScalar + * + * Normally, empty G-API data objects denote a starting point of + * the graph. When an empty GScalar is assigned to a result of some + * operation, it obtains a functional link to this operation (and + * is not empty anymore). + */ + GAPI_WRAP GScalar(); + + /** + * @brief Constructs a value-initialized GScalar + * + * GScalars may have their values be associated at graph + * construction time. It is useful when some operation has a + * GScalar input which doesn't change during the program + * execution, and is set only once. In this case, there is no need + * to declare such GScalar as a graph input. + * + * @note The value of GScalar may be overwritten by assigning some + * other GScalar to the object using `operator=` -- on the + * assignment, the old GScalar value is discarded. + * + * @param s a cv::Scalar value to associate with this GScalar object. + */ + GAPI_WRAP + explicit GScalar(const cv::Scalar& s); + + /** + * @overload + * @brief Constructs a value-initialized GScalar + * + * @param s a cv::Scalar value to associate with this GScalar object. + */ + explicit GScalar(cv::Scalar&& s); // Constant value move-constructor from cv::Scalar + + /** + * @overload + * @brief Constructs a value-initialized GScalar + * + * @param v0 A `double` value to associate with this GScalar. Note + * that only the first component of a four-component cv::Scalar is + * set to this value, with others remain zeros. + * + * This constructor overload is not marked `explicit` and can be + * used in G-API expression code like this: + * + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp gscalar_implicit + * + * Here operator+(GMat,GScalar) is used to wrap cv::gapi::addC() + * and a value-initialized GScalar is created on the fly. + * + * @overload + */ + GScalar(double v0); // Constant value constructor from double + + /// @private + GScalar(const GNode &n, std::size_t out); // Operation result constructor + /// @private + GOrigin& priv(); // Internal use only + /// @private + const GOrigin& priv() const; // Internal use only + +private: + std::shared_ptr m_priv; +}; + +/** @} */ + +/** + * \addtogroup gapi_meta_args + * @{ + */ +struct GAPI_EXPORTS_W_SIMPLE GScalarDesc +{ + // NB.: right now it is empty + + inline bool operator== (const GScalarDesc &) const + { + return true; // NB: implement this method if GScalar meta appears + } + + inline bool operator!= (const GScalarDesc &rhs) const + { + return !(*this == rhs); + } +}; + +GAPI_EXPORTS_W inline GScalarDesc empty_scalar_desc() { return GScalarDesc(); } + +GAPI_EXPORTS GScalarDesc descr_of(const cv::Scalar &scalar); + +std::ostream& operator<<(std::ostream& os, const cv::GScalarDesc &desc); + +} // namespace cv + +#endif // OPENCV_GAPI_GSCALAR_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gstreaming.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gstreaming.hpp index d413195b81..8d4e15aa99 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gstreaming.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gstreaming.hpp @@ -1,430 +1,430 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2021 Intel Corporation - - -#ifndef OPENCV_GAPI_GSTREAMING_COMPILED_HPP -#define OPENCV_GAPI_GSTREAMING_COMPILED_HPP - -#include -#include - -#include -#include -#include -#include -#include - -namespace cv { - -template using optional = cv::util::optional; - -namespace detail { -template struct wref_spec { - using type = T; -}; -template struct wref_spec > { - using type = T; -}; - -template -struct OptRef { - struct OptHolder { - virtual void mov(RefHolder &h) = 0; - virtual void reset() = 0; - virtual ~OptHolder() = default; - using Ptr = std::shared_ptr; - }; - template struct Holder final: OptHolder { - std::reference_wrapper > m_opt_ref; - - explicit Holder(cv::optional& opt) : m_opt_ref(std::ref(opt)) { - } - virtual void mov(RefHolder &h) override { - using U = typename wref_spec::type; - m_opt_ref.get() = cv::util::make_optional(std::move(h.template wref())); - } - virtual void reset() override { - m_opt_ref.get().reset(); - } - }; - template - explicit OptRef(cv::optional& t) : m_opt{new Holder(t)} {} - void mov(RefHolder &h) { m_opt->mov(h); } - void reset() { m_opt->reset();} -private: - typename OptHolder::Ptr m_opt; -}; -using OptionalVectorRef = OptRef; -using OptionalOpaqueRef = OptRef; -} // namespace detail - -// TODO: Keep it in sync with GRunArgP (derive the type automatically?) -using GOptRunArgP = util::variant< - optional*, - optional*, - optional*, - optional*, - cv::detail::OptionalVectorRef, - cv::detail::OptionalOpaqueRef ->; -using GOptRunArgsP = std::vector; - -using GOptRunArg = util::variant< - optional, - optional, - optional, - optional, - optional, - optional ->; -using GOptRunArgs = std::vector; - -namespace detail { - -template inline GOptRunArgP wrap_opt_arg(optional& arg) { - // By default, T goes to an OpaqueRef. All other types are specialized - return GOptRunArgP{OptionalOpaqueRef(arg)}; -} - -template inline GOptRunArgP wrap_opt_arg(optional >& arg) { - return GOptRunArgP{OptionalVectorRef(arg)}; -} - -template<> inline GOptRunArgP wrap_opt_arg(optional &m) { - return GOptRunArgP{&m}; -} - -template<> inline GOptRunArgP wrap_opt_arg(optional &m) { - return GOptRunArgP{&m}; -} - -template<> inline GOptRunArgP wrap_opt_arg(optional &f) { - return GOptRunArgP{&f}; -} - -template<> inline GOptRunArgP wrap_opt_arg(optional &s) { - return GOptRunArgP{&s}; -} - -} // namespace detail - -// Now cv::gout() may produce an empty vector (see "dynamic graphs"), so -// there may be a conflict between these two. State here that Opt version -// _must_ have at least one input for this overload -template -inline GOptRunArgsP gout(optional&arg, optional&... args) -{ - return GOptRunArgsP{ detail::wrap_opt_arg(arg), detail::wrap_opt_arg(args)... }; -} - -/** - * \addtogroup gapi_main_classes - * @{ - */ -/** - * @brief Represents a computation (graph) compiled for streaming. - * - * This class represents a product of graph compilation (calling - * cv::GComputation::compileStreaming()). Objects of this class - * actually do stream processing, and the whole pipeline execution - * complexity is incapsulated into objects of this class. Execution - * model has two levels: at the very top, the execution of a - * heterogeneous graph is aggressively pipelined; at the very bottom - * the execution of every internal block is determined by its - * associated backend. Backends are selected based on kernel packages - * passed via compilation arguments ( see @ref gapi_compile_args, - * GNetworkPackage, GKernelPackage for details). - * - * GStreamingCompiled objects have a "player" semantics -- there are - * methods like start() and stop(). GStreamingCompiled has a full - * control over a videostream and so is stateful. You need to specify the - * input stream data using setSource() and then call start() to - * actually start processing. After that, use pull() or try_pull() to - * obtain next processed data frame from the graph in a blocking or - * non-blocking way, respectively. - * - * Currently a single GStreamingCompiled can process only one video - * streat at time. Produce multiple GStreamingCompiled objects to run the - * same graph on multiple video streams. - * - * @sa GCompiled - */ -class GAPI_EXPORTS_W_SIMPLE GStreamingCompiled -{ -public: - class GAPI_EXPORTS Priv; - GAPI_WRAP GStreamingCompiled(); - - // FIXME: More overloads? - /** - * @brief Specify the input data to GStreamingCompiled for - * processing, a generic version. - * - * Use gin() to create an input parameter vector. - * - * Input vectors must have the same number of elements as defined - * in the cv::GComputation protocol (at the moment of its - * construction). Shapes of elements also must conform to protocol - * (e.g. cv::Mat needs to be passed where cv::GMat has been - * declared as input, and so on). Run-time exception is generated - * on type mismatch. - * - * In contrast with regular GCompiled, user can also pass an - * object of type GVideoCapture for a GMat parameter of the parent - * GComputation. The compiled pipeline will start fetching data - * from that GVideoCapture and feeding it into the - * pipeline. Pipeline stops when a GVideoCapture marks end of the - * stream (or when stop() is called). - * - * Passing a regular Mat for a GMat parameter makes it "infinite" - * source -- pipeline may run forever feeding with this Mat until - * stopped explicitly. - * - * Currently only a single GVideoCapture is supported as input. If - * the parent GComputation is declared with multiple input GMat's, - * one of those can be specified as GVideoCapture but all others - * must be regular Mat objects. - * - * Throws if pipeline is already running. Use stop() and then - * setSource() to run the graph on a new video stream. - * - * @note This method is not thread-safe (with respect to the user - * side) at the moment. Protect the access if - * start()/stop()/setSource() may be called on the same object in - * multiple threads in your application. - * - * @param ins vector of inputs to process. - * @sa gin - */ - void setSource(GRunArgs &&ins); - - /// @private -- Exclude this function from OpenCV documentation - GAPI_WRAP void setSource(const cv::detail::ExtractArgsCallback& callback); - - /** - * @brief Specify an input video stream for a single-input - * computation pipeline. - * - * Throws if pipeline is already running. Use stop() and then - * setSource() to run the graph on a new video stream. - * - * @overload - * @param s a shared pointer to IStreamSource representing the - * input video stream. - */ - void setSource(const gapi::wip::IStreamSource::Ptr& s); - - /** - * @brief Constructs and specifies an input video stream for a - * single-input computation pipeline with the given parameters. - * - * Throws if pipeline is already running. Use stop() and then - * setSource() to run the graph on a new video stream. - * - * @overload - * @param args arguments used to construct and initialize a stream - * source. - */ - template - void setSource(Args&&... args) { - setSource(cv::gapi::wip::make_src(std::forward(args)...)); - } - - /** - * @brief Start the pipeline execution. - * - * Use pull()/try_pull() to obtain data. Throws an exception if - * a video source was not specified. - * - * setSource() must be called first, even if the pipeline has been - * working already and then stopped (explicitly via stop() or due - * stream completion) - * - * @note This method is not thread-safe (with respect to the user - * side) at the moment. Protect the access if - * start()/stop()/setSource() may be called on the same object in - * multiple threads in your application. - */ - GAPI_WRAP void start(); - - /** - * @brief Get the next processed frame from the pipeline. - * - * Use gout() to create an output parameter vector. - * - * Output vectors must have the same number of elements as defined - * in the cv::GComputation protocol (at the moment of its - * construction). Shapes of elements also must conform to protocol - * (e.g. cv::Mat needs to be passed where cv::GMat has been - * declared as output, and so on). Run-time exception is generated - * on type mismatch. - * - * This method writes new data into objects passed via output - * vector. If there is no data ready yet, this method blocks. Use - * try_pull() if you need a non-blocking version. - * - * @param outs vector of output parameters to obtain. - * @return true if next result has been obtained, - * false marks end of the stream. - */ - bool pull(cv::GRunArgsP &&outs); - - // NB: Used from python - /// @private -- Exclude this function from OpenCV documentation - GAPI_WRAP std::tuple> pull(); - - /** - * @brief Get some next available data from the pipeline. - * - * This method takes a vector of cv::optional object. An object is - * assigned to some value if this value is available (ready) at - * the time of the call, and resets the object to empty() if it is - * not. - * - * This is a blocking method which guarantees that some data has - * been written to the output vector on return. - * - * Using this method only makes sense if the graph has - * desynchronized parts (see cv::gapi::desync). If there is no - * desynchronized parts in the graph, the behavior of this - * method is identical to the regular pull() (all data objects are - * produced synchronously in the output vector). - * - * Use gout() to create an output parameter vector. - * - * Output vectors must have the same number of elements as defined - * in the cv::GComputation protocol (at the moment of its - * construction). Shapes of elements also must conform to protocol - * (e.g. cv::optional needs to be passed where cv::GMat - * has been declared as output, and so on). Run-time exception is - * generated on type mismatch. - * - * This method writes new data into objects passed via output - * vector. If there is no data ready yet, this method blocks. Use - * try_pull() if you need a non-blocking version. - * - * @param outs vector of output parameters to obtain. - * @return true if next result has been obtained, - * false marks end of the stream. - * - * @sa cv::gapi::desync - */ - bool pull(cv::GOptRunArgsP &&outs); - - /** - * @brief Try to get the next processed frame from the pipeline. - * - * Use gout() to create an output parameter vector. - * - * This method writes new data into objects passed via output - * vector. If there is no data ready yet, the output vector - * remains unchanged and false is returned. - * - * @return true if data has been obtained, and false if it was - * not. Note: false here doesn't mark the end of the stream. - */ - bool try_pull(cv::GRunArgsP &&outs); - - /** - * @brief Stop (abort) processing the pipeline. - * - * Note - it is not pause but a complete stop. Calling start() - * will cause G-API to start processing the stream from the early beginning. - * - * Throws if the pipeline is not running. - */ - GAPI_WRAP void stop(); - - /** - * @brief Test if the pipeline is running. - * - * @note This method is not thread-safe (with respect to the user - * side) at the moment. Protect the access if - * start()/stop()/setSource() may be called on the same object in - * multiple threads in your application. - * - * @return true if the current stream is not over yet. - */ - GAPI_WRAP bool running() const; - - /// @private - Priv& priv(); - - /** - * @brief Check if compiled object is valid (non-empty) - * - * @return true if the object is runnable (valid), false otherwise - */ - explicit operator bool () const; - - /** - * @brief Vector of metadata this graph was compiled for. - * - * @return Unless _reshape_ is not supported, return value is the - * same vector which was passed to cv::GComputation::compile() to - * produce this compiled object. Otherwise, it is the latest - * metadata vector passed to reshape() (if that call was - * successful). - */ - const GMetaArgs& metas() const; // Meta passed to compile() - - /** - * @brief Vector of metadata descriptions of graph outputs - * - * @return vector with formats/resolutions of graph's output - * objects, auto-inferred from input metadata vector by - * operations which form this computation. - * - * @note GCompiled objects produced from the same - * cv::GComputiation graph with different input metas may return - * different values in this vector. - */ - const GMetaArgs& outMetas() const; - -protected: - /// @private - std::shared_ptr m_priv; -}; - -namespace gapi { - -/** - * @brief This namespace contains G-API functions, structures, and - * symbols related to the Streaming execution mode. - * - * Some of the operations defined in this namespace (e.g. size(), - * BGR(), etc.) can be used in the traditional execution mode too. - */ -namespace streaming { -/** - * @brief Specify queue capacity for streaming execution. - * - * In the streaming mode the pipeline steps are connected with queues - * and this compile argument controls every queue's size. - */ -struct GAPI_EXPORTS_W_SIMPLE queue_capacity -{ - GAPI_WRAP - explicit queue_capacity(size_t cap = 1) : capacity(cap) { } - GAPI_PROP_RW - size_t capacity; -}; -} // namespace streaming -} // namespace gapi - -namespace detail -{ -template<> struct CompileArgTag -{ - static const char* tag() { return "gapi.queue_capacity"; } -}; -} - -/** @} gapi_main_classes */ - -} - -#endif // OPENCV_GAPI_GSTREAMING_COMPILED_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2021 Intel Corporation + + +#ifndef OPENCV_GAPI_GSTREAMING_COMPILED_HPP +#define OPENCV_GAPI_GSTREAMING_COMPILED_HPP + +#include +#include + +#include +#include +#include +#include +#include + +namespace cv { + +template using optional = cv::util::optional; + +namespace detail { +template struct wref_spec { + using type = T; +}; +template struct wref_spec > { + using type = T; +}; + +template +struct OptRef { + struct OptHolder { + virtual void mov(RefHolder &h) = 0; + virtual void reset() = 0; + virtual ~OptHolder() = default; + using Ptr = std::shared_ptr; + }; + template struct Holder final: OptHolder { + std::reference_wrapper > m_opt_ref; + + explicit Holder(cv::optional& opt) : m_opt_ref(std::ref(opt)) { + } + virtual void mov(RefHolder &h) override { + using U = typename wref_spec::type; + m_opt_ref.get() = cv::util::make_optional(std::move(h.template wref())); + } + virtual void reset() override { + m_opt_ref.get().reset(); + } + }; + template + explicit OptRef(cv::optional& t) : m_opt{new Holder(t)} {} + void mov(RefHolder &h) { m_opt->mov(h); } + void reset() { m_opt->reset();} +private: + typename OptHolder::Ptr m_opt; +}; +using OptionalVectorRef = OptRef; +using OptionalOpaqueRef = OptRef; +} // namespace detail + +// TODO: Keep it in sync with GRunArgP (derive the type automatically?) +using GOptRunArgP = util::variant< + optional*, + optional*, + optional*, + optional*, + cv::detail::OptionalVectorRef, + cv::detail::OptionalOpaqueRef +>; +using GOptRunArgsP = std::vector; + +using GOptRunArg = util::variant< + optional, + optional, + optional, + optional, + optional, + optional +>; +using GOptRunArgs = std::vector; + +namespace detail { + +template inline GOptRunArgP wrap_opt_arg(optional& arg) { + // By default, T goes to an OpaqueRef. All other types are specialized + return GOptRunArgP{OptionalOpaqueRef(arg)}; +} + +template inline GOptRunArgP wrap_opt_arg(optional >& arg) { + return GOptRunArgP{OptionalVectorRef(arg)}; +} + +template<> inline GOptRunArgP wrap_opt_arg(optional &m) { + return GOptRunArgP{&m}; +} + +template<> inline GOptRunArgP wrap_opt_arg(optional &m) { + return GOptRunArgP{&m}; +} + +template<> inline GOptRunArgP wrap_opt_arg(optional &f) { + return GOptRunArgP{&f}; +} + +template<> inline GOptRunArgP wrap_opt_arg(optional &s) { + return GOptRunArgP{&s}; +} + +} // namespace detail + +// Now cv::gout() may produce an empty vector (see "dynamic graphs"), so +// there may be a conflict between these two. State here that Opt version +// _must_ have at least one input for this overload +template +inline GOptRunArgsP gout(optional&arg, optional&... args) +{ + return GOptRunArgsP{ detail::wrap_opt_arg(arg), detail::wrap_opt_arg(args)... }; +} + +/** + * \addtogroup gapi_main_classes + * @{ + */ +/** + * @brief Represents a computation (graph) compiled for streaming. + * + * This class represents a product of graph compilation (calling + * cv::GComputation::compileStreaming()). Objects of this class + * actually do stream processing, and the whole pipeline execution + * complexity is incapsulated into objects of this class. Execution + * model has two levels: at the very top, the execution of a + * heterogeneous graph is aggressively pipelined; at the very bottom + * the execution of every internal block is determined by its + * associated backend. Backends are selected based on kernel packages + * passed via compilation arguments ( see @ref gapi_compile_args, + * GNetworkPackage, GKernelPackage for details). + * + * GStreamingCompiled objects have a "player" semantics -- there are + * methods like start() and stop(). GStreamingCompiled has a full + * control over a videostream and so is stateful. You need to specify the + * input stream data using setSource() and then call start() to + * actually start processing. After that, use pull() or try_pull() to + * obtain next processed data frame from the graph in a blocking or + * non-blocking way, respectively. + * + * Currently a single GStreamingCompiled can process only one video + * streat at time. Produce multiple GStreamingCompiled objects to run the + * same graph on multiple video streams. + * + * @sa GCompiled + */ +class GAPI_EXPORTS_W_SIMPLE GStreamingCompiled +{ +public: + class GAPI_EXPORTS Priv; + GAPI_WRAP GStreamingCompiled(); + + // FIXME: More overloads? + /** + * @brief Specify the input data to GStreamingCompiled for + * processing, a generic version. + * + * Use gin() to create an input parameter vector. + * + * Input vectors must have the same number of elements as defined + * in the cv::GComputation protocol (at the moment of its + * construction). Shapes of elements also must conform to protocol + * (e.g. cv::Mat needs to be passed where cv::GMat has been + * declared as input, and so on). Run-time exception is generated + * on type mismatch. + * + * In contrast with regular GCompiled, user can also pass an + * object of type GVideoCapture for a GMat parameter of the parent + * GComputation. The compiled pipeline will start fetching data + * from that GVideoCapture and feeding it into the + * pipeline. Pipeline stops when a GVideoCapture marks end of the + * stream (or when stop() is called). + * + * Passing a regular Mat for a GMat parameter makes it "infinite" + * source -- pipeline may run forever feeding with this Mat until + * stopped explicitly. + * + * Currently only a single GVideoCapture is supported as input. If + * the parent GComputation is declared with multiple input GMat's, + * one of those can be specified as GVideoCapture but all others + * must be regular Mat objects. + * + * Throws if pipeline is already running. Use stop() and then + * setSource() to run the graph on a new video stream. + * + * @note This method is not thread-safe (with respect to the user + * side) at the moment. Protect the access if + * start()/stop()/setSource() may be called on the same object in + * multiple threads in your application. + * + * @param ins vector of inputs to process. + * @sa gin + */ + void setSource(GRunArgs &&ins); + + /// @private -- Exclude this function from OpenCV documentation + GAPI_WRAP void setSource(const cv::detail::ExtractArgsCallback& callback); + + /** + * @brief Specify an input video stream for a single-input + * computation pipeline. + * + * Throws if pipeline is already running. Use stop() and then + * setSource() to run the graph on a new video stream. + * + * @overload + * @param s a shared pointer to IStreamSource representing the + * input video stream. + */ + void setSource(const gapi::wip::IStreamSource::Ptr& s); + + /** + * @brief Constructs and specifies an input video stream for a + * single-input computation pipeline with the given parameters. + * + * Throws if pipeline is already running. Use stop() and then + * setSource() to run the graph on a new video stream. + * + * @overload + * @param args arguments used to construct and initialize a stream + * source. + */ + template + void setSource(Args&&... args) { + setSource(cv::gapi::wip::make_src(std::forward(args)...)); + } + + /** + * @brief Start the pipeline execution. + * + * Use pull()/try_pull() to obtain data. Throws an exception if + * a video source was not specified. + * + * setSource() must be called first, even if the pipeline has been + * working already and then stopped (explicitly via stop() or due + * stream completion) + * + * @note This method is not thread-safe (with respect to the user + * side) at the moment. Protect the access if + * start()/stop()/setSource() may be called on the same object in + * multiple threads in your application. + */ + GAPI_WRAP void start(); + + /** + * @brief Get the next processed frame from the pipeline. + * + * Use gout() to create an output parameter vector. + * + * Output vectors must have the same number of elements as defined + * in the cv::GComputation protocol (at the moment of its + * construction). Shapes of elements also must conform to protocol + * (e.g. cv::Mat needs to be passed where cv::GMat has been + * declared as output, and so on). Run-time exception is generated + * on type mismatch. + * + * This method writes new data into objects passed via output + * vector. If there is no data ready yet, this method blocks. Use + * try_pull() if you need a non-blocking version. + * + * @param outs vector of output parameters to obtain. + * @return true if next result has been obtained, + * false marks end of the stream. + */ + bool pull(cv::GRunArgsP &&outs); + + // NB: Used from python + /// @private -- Exclude this function from OpenCV documentation + GAPI_WRAP std::tuple> pull(); + + /** + * @brief Get some next available data from the pipeline. + * + * This method takes a vector of cv::optional object. An object is + * assigned to some value if this value is available (ready) at + * the time of the call, and resets the object to empty() if it is + * not. + * + * This is a blocking method which guarantees that some data has + * been written to the output vector on return. + * + * Using this method only makes sense if the graph has + * desynchronized parts (see cv::gapi::desync). If there is no + * desynchronized parts in the graph, the behavior of this + * method is identical to the regular pull() (all data objects are + * produced synchronously in the output vector). + * + * Use gout() to create an output parameter vector. + * + * Output vectors must have the same number of elements as defined + * in the cv::GComputation protocol (at the moment of its + * construction). Shapes of elements also must conform to protocol + * (e.g. cv::optional needs to be passed where cv::GMat + * has been declared as output, and so on). Run-time exception is + * generated on type mismatch. + * + * This method writes new data into objects passed via output + * vector. If there is no data ready yet, this method blocks. Use + * try_pull() if you need a non-blocking version. + * + * @param outs vector of output parameters to obtain. + * @return true if next result has been obtained, + * false marks end of the stream. + * + * @sa cv::gapi::desync + */ + bool pull(cv::GOptRunArgsP &&outs); + + /** + * @brief Try to get the next processed frame from the pipeline. + * + * Use gout() to create an output parameter vector. + * + * This method writes new data into objects passed via output + * vector. If there is no data ready yet, the output vector + * remains unchanged and false is returned. + * + * @return true if data has been obtained, and false if it was + * not. Note: false here doesn't mark the end of the stream. + */ + bool try_pull(cv::GRunArgsP &&outs); + + /** + * @brief Stop (abort) processing the pipeline. + * + * Note - it is not pause but a complete stop. Calling start() + * will cause G-API to start processing the stream from the early beginning. + * + * Throws if the pipeline is not running. + */ + GAPI_WRAP void stop(); + + /** + * @brief Test if the pipeline is running. + * + * @note This method is not thread-safe (with respect to the user + * side) at the moment. Protect the access if + * start()/stop()/setSource() may be called on the same object in + * multiple threads in your application. + * + * @return true if the current stream is not over yet. + */ + GAPI_WRAP bool running() const; + + /// @private + Priv& priv(); + + /** + * @brief Check if compiled object is valid (non-empty) + * + * @return true if the object is runnable (valid), false otherwise + */ + explicit operator bool () const; + + /** + * @brief Vector of metadata this graph was compiled for. + * + * @return Unless _reshape_ is not supported, return value is the + * same vector which was passed to cv::GComputation::compile() to + * produce this compiled object. Otherwise, it is the latest + * metadata vector passed to reshape() (if that call was + * successful). + */ + const GMetaArgs& metas() const; // Meta passed to compile() + + /** + * @brief Vector of metadata descriptions of graph outputs + * + * @return vector with formats/resolutions of graph's output + * objects, auto-inferred from input metadata vector by + * operations which form this computation. + * + * @note GCompiled objects produced from the same + * cv::GComputiation graph with different input metas may return + * different values in this vector. + */ + const GMetaArgs& outMetas() const; + +protected: + /// @private + std::shared_ptr m_priv; +}; + +namespace gapi { + +/** + * @brief This namespace contains G-API functions, structures, and + * symbols related to the Streaming execution mode. + * + * Some of the operations defined in this namespace (e.g. size(), + * BGR(), etc.) can be used in the traditional execution mode too. + */ +namespace streaming { +/** + * @brief Specify queue capacity for streaming execution. + * + * In the streaming mode the pipeline steps are connected with queues + * and this compile argument controls every queue's size. + */ +struct GAPI_EXPORTS_W_SIMPLE queue_capacity +{ + GAPI_WRAP + explicit queue_capacity(size_t cap = 1) : capacity(cap) { } + GAPI_PROP_RW + size_t capacity; +}; +} // namespace streaming +} // namespace gapi + +namespace detail +{ +template<> struct CompileArgTag +{ + static const char* tag() { return "gapi.queue_capacity"; } +}; +} + +/** @} gapi_main_classes */ + +} + +#endif // OPENCV_GAPI_GSTREAMING_COMPILED_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gtransform.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gtransform.hpp index ce88c894d7..ae904d8164 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gtransform.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gtransform.hpp @@ -1,103 +1,103 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019 Intel Corporation - -#ifndef OPENCV_GAPI_GTRANSFORM_HPP -#define OPENCV_GAPI_GTRANSFORM_HPP - -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace cv -{ - -struct GAPI_EXPORTS GTransform -{ - // FIXME: consider another simplified - // class instead of GComputation - using F = std::function; - - std::string description; - F pattern; - F substitute; - - GTransform(const std::string& d, const F &p, const F &s) : description(d), pattern(p), substitute(s) {} -}; - -namespace detail -{ - -template -struct TransHelper; - -template -struct TransHelper, Out> -{ - template - static GComputation invoke(Callable f, Seq, Seq) - { - const std::tuple ins; - const auto r = tuple_wrap_helper::get(f(std::get(ins)...)); - return GComputation(cv::GIn(std::get(ins)...), - cv::GOut(std::get(r)...)); - } - - static GComputation get_pattern() - { - return invoke(K::pattern, typename MkSeq::type(), - typename MkSeq::type>::value>::type()); - } - static GComputation get_substitute() - { - return invoke(K::substitute, typename MkSeq::type(), - typename MkSeq::type>::value>::type()); - } -}; -} // namespace detail - -template -class GTransformImpl; - -template -class GTransformImpl> : public cv::detail::TransHelper, R>, - public cv::detail::TransformTag -{ -public: - // FIXME: currently there is no check that transformations' signatures are unique - // and won't be any intersection in graph compilation stage - using API = K; - - static GTransform transformation() - { - return GTransform(K::descr(), &K::get_pattern, &K::get_substitute); - } -}; -} // namespace cv - -#define G_DESCR_HELPER_CLASS(Class) Class##DescrHelper - -#define G_DESCR_HELPER_BODY(Class, Descr) \ - namespace detail \ - { \ - struct G_DESCR_HELPER_CLASS(Class) \ - { \ - static constexpr const char *descr() { return Descr; } \ - }; \ - } - -#define GAPI_TRANSFORM(Class, API, Descr) \ - G_DESCR_HELPER_BODY(Class, Descr) \ - struct Class final : public cv::GTransformImpl, \ - public detail::G_DESCR_HELPER_CLASS(Class) - -#endif // OPENCV_GAPI_GTRANSFORM_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019 Intel Corporation + +#ifndef OPENCV_GAPI_GTRANSFORM_HPP +#define OPENCV_GAPI_GTRANSFORM_HPP + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace cv +{ + +struct GAPI_EXPORTS GTransform +{ + // FIXME: consider another simplified + // class instead of GComputation + using F = std::function; + + std::string description; + F pattern; + F substitute; + + GTransform(const std::string& d, const F &p, const F &s) : description(d), pattern(p), substitute(s) {} +}; + +namespace detail +{ + +template +struct TransHelper; + +template +struct TransHelper, Out> +{ + template + static GComputation invoke(Callable f, Seq, Seq) + { + const std::tuple ins; + const auto r = tuple_wrap_helper::get(f(std::get(ins)...)); + return GComputation(cv::GIn(std::get(ins)...), + cv::GOut(std::get(r)...)); + } + + static GComputation get_pattern() + { + return invoke(K::pattern, typename MkSeq::type(), + typename MkSeq::type>::value>::type()); + } + static GComputation get_substitute() + { + return invoke(K::substitute, typename MkSeq::type(), + typename MkSeq::type>::value>::type()); + } +}; +} // namespace detail + +template +class GTransformImpl; + +template +class GTransformImpl> : public cv::detail::TransHelper, R>, + public cv::detail::TransformTag +{ +public: + // FIXME: currently there is no check that transformations' signatures are unique + // and won't be any intersection in graph compilation stage + using API = K; + + static GTransform transformation() + { + return GTransform(K::descr(), &K::get_pattern, &K::get_substitute); + } +}; +} // namespace cv + +#define G_DESCR_HELPER_CLASS(Class) Class##DescrHelper + +#define G_DESCR_HELPER_BODY(Class, Descr) \ + namespace detail \ + { \ + struct G_DESCR_HELPER_CLASS(Class) \ + { \ + static constexpr const char *descr() { return Descr; } \ + }; \ + } + +#define GAPI_TRANSFORM(Class, API, Descr) \ + G_DESCR_HELPER_BODY(Class, Descr) \ + struct Class final : public cv::GTransformImpl, \ + public detail::G_DESCR_HELPER_CLASS(Class) + +#endif // OPENCV_GAPI_GTRANSFORM_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gtype_traits.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gtype_traits.hpp index c42d64a761..cbf5f8f417 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gtype_traits.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gtype_traits.hpp @@ -1,242 +1,242 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2020 Intel Corporation - - -#ifndef OPENCV_GAPI_GTYPE_TRAITS_HPP -#define OPENCV_GAPI_GTYPE_TRAITS_HPP - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace cv -{ -namespace detail -{ - template - struct contains_shape_field : std::false_type {}; - - template - struct contains_shape_field> : - std::is_same::type, GShape> - {}; - - template - struct has_gshape : contains_shape_field {}; - - // FIXME: These traits and enum and possible numerous switch(kind) - // block may be replaced with a special Handler object or with - // a double dispatch - enum class ArgKind: int - { - OPAQUE_VAL, // Unknown, generic, opaque-to-GAPI data type - STATIC - // Note: OPAQUE is sometimes defined in Win sys headers -#if !defined(OPAQUE) && !defined(CV_DOXYGEN) - OPAQUE = OPAQUE_VAL, // deprecated value used for compatibility, use OPAQUE_VAL instead -#endif - GOBJREF, // reference to object - GMAT, // a cv::GMat - GMATP, // a cv::GMatP - GFRAME, // a cv::GFrame - GSCALAR, // a cv::GScalar - GARRAY, // a cv::GArrayU (note - exactly GArrayU, not GArray!) - GOPAQUE, // a cv::GOpaqueU (note - exactly GOpaqueU, not GOpaque!) - }; - - // Describe G-API types (G-types) with traits. Mostly used by - // cv::GArg to store meta information about types passed into - // operation arguments. Please note that cv::GComputation is - // defined on GProtoArgs, not GArgs! - template struct GTypeTraits; - template struct GTypeTraits - { - static constexpr const ArgKind kind = ArgKind::OPAQUE_VAL; - static constexpr const OpaqueKind op_kind = OpaqueKind::CV_UNKNOWN; - }; - template<> struct GTypeTraits - { - static constexpr const ArgKind kind = ArgKind::GMAT; - static constexpr const GShape shape = GShape::GMAT; - static constexpr const OpaqueKind op_kind = OpaqueKind::CV_UNKNOWN; - }; - template<> struct GTypeTraits - { - static constexpr const ArgKind kind = ArgKind::GMATP; - static constexpr const GShape shape = GShape::GMAT; - static constexpr const OpaqueKind op_kind = OpaqueKind::CV_UNKNOWN; - }; - template<> struct GTypeTraits - { - static constexpr const ArgKind kind = ArgKind::GFRAME; - static constexpr const GShape shape = GShape::GFRAME; - static constexpr const OpaqueKind op_kind = OpaqueKind::CV_UNKNOWN; - }; - template<> struct GTypeTraits - { - static constexpr const ArgKind kind = ArgKind::GSCALAR; - static constexpr const GShape shape = GShape::GSCALAR; - static constexpr const OpaqueKind op_kind = OpaqueKind::CV_UNKNOWN; - }; - template struct GTypeTraits > - { - static constexpr const ArgKind kind = ArgKind::GARRAY; - static constexpr const GShape shape = GShape::GARRAY; - static constexpr const OpaqueKind op_kind = GOpaqueTraits::kind; - using host_type = std::vector; - using strip_type = cv::detail::VectorRef; - static cv::detail::GArrayU wrap_value(const cv::GArray &t) { return t.strip();} - static cv::detail::VectorRef wrap_in (const std::vector &t) { return detail::VectorRef(t); } - static cv::detail::VectorRef wrap_out ( std::vector &t) { return detail::VectorRef(t); } - }; - template struct GTypeTraits > - { - static constexpr const ArgKind kind = ArgKind::GOPAQUE; - static constexpr const GShape shape = GShape::GOPAQUE; - static constexpr const OpaqueKind op_kind = GOpaqueTraits::kind; - using host_type = T; - using strip_type = cv::detail::OpaqueRef; - static cv::detail::GOpaqueU wrap_value(const cv::GOpaque &t) { return t.strip();} - static cv::detail::OpaqueRef wrap_in (const T &t) { return detail::OpaqueRef(t); } - static cv::detail::OpaqueRef wrap_out ( T &t) { return detail::OpaqueRef(t); } - }; - - // Tests if Trait for type T requires extra marshalling ("custom wrap") or not. - // If Traits has wrap_value() defined, it does. - template struct has_custom_wrap - { - template class check; - template static std::true_type test(check::wrap_value)> *); - template static std::false_type test(...); - using type = decltype(test(nullptr)); - static const constexpr bool value = std::is_same(nullptr))>::value; - }; - - // Resolve a Host type back to its associated G-Type. - // FIXME: Probably it can be avoided - // FIXME: GMatP is not present here. - // (Actually these traits is used only to check - // if associated G-type has custom wrap functions - // and GMat behavior is correct for GMatP) - template struct GTypeOf; -#if !defined(GAPI_STANDALONE) - template<> struct GTypeOf { using type = cv::GMat; }; -#endif // !defined(GAPI_STANDALONE) - template<> struct GTypeOf { using type = cv::GMat; }; - template<> struct GTypeOf { using type = cv::GMat; }; - template<> struct GTypeOf { using type = cv::GScalar; }; - template struct GTypeOf > { using type = cv::GArray; }; - template struct GTypeOf { using type = cv::GOpaque;}; - template<> struct GTypeOf { using type = cv::GFrame; }; - - // FIXME: This is not quite correct since IStreamSource may - // produce not only Mat but also MediaFrame, Scalar and vector - // data. TODO: Extend the type dispatching on these types too. - template<> struct GTypeOf { using type = cv::GMat;}; - template using g_type_of_t = typename GTypeOf::type; - - // Marshalling helper for G-types and its Host types. Helps G-API - // to store G types in internal generic containers for further - // processing. Implements the following callbacks: - // - // * wrap() - converts user-facing G-type into an internal one - // for internal storage. - // Used when G-API operation is instantiated (G::on(), - // etc) during expressing a pipeline. Mostly returns input - // value "as is" except the case when G-type is a template. For - // template G-classes, calls custom wrap() from Traits. - // The value returned by wrap() is then wrapped into GArg() and - // stored in G-API metadata. - // - // Example: - // - cv::GMat arguments are passed as-is. - // - integers, pointers, STL containers, user types are passed as-is. - // - cv::GArray is converted to cv::GArrayU. - // - // * wrap_in() / wrap_out() - convert Host type associated with - // G-type to internal representation type. - // - // - For "simple" (non-template) G-types, returns value as-is. - // Example: cv::GMat has host type cv::Mat, when user passes a - // cv::Mat, system stores it internally as cv::Mat. - // - // - For "complex" (template) G-types, utilizes custom - // wrap_in()/wrap_out() as described in Traits. - // Example: cv::GArray has host type std::vector, when - // user passes a std::vector, system stores it - // internally as VectorRef (with stripped away). - template struct WrapValue - { - static auto wrap(const T& t) -> - typename std::remove_reference::type - { - return static_cast::type>(t); - } - - template static U wrap_in (const U &u) { return u; } - template static U* wrap_out(U &u) { return &u; } - }; - template struct WrapValue::value>::type> - { - static auto wrap(const T& t) -> decltype(GTypeTraits::wrap_value(t)) - { - return GTypeTraits::wrap_value(t); - } - template static auto wrap_in (const U &u) -> typename GTypeTraits::strip_type - { - static_assert(!(cv::detail::has_gshape>::value - || cv::detail::contains::type, GAPI_OWN_TYPES_LIST>::value), - "gin/gout must not be used with G* classes or cv::gapi::own::*"); - return GTypeTraits::wrap_in(u); - } - template static auto wrap_out(U &u) -> typename GTypeTraits::strip_type - { - static_assert(!(cv::detail::has_gshape>::value - || cv::detail::contains::type, GAPI_OWN_TYPES_LIST>::value), - "gin/gout must not be used with G* classes or cv::gapi::own::*"); - return GTypeTraits::wrap_out(u); - } - }; - - template using wrap_gapi_helper = WrapValue::type>; - template using wrap_host_helper = WrapValue >::type>; - -// Union type for various user-defined type constructors (GArray, -// GOpaque, etc) -// -// TODO: Replace construct-only API with a more generic one (probably -// with bits of introspection) -// -// Not required for non-user-defined types (GMat, GScalar, etc) -using HostCtor = util::variant - < util::monostate - , detail::ConstructVec - , detail::ConstructOpaque - >; - -template struct GObtainCtor { - static HostCtor get() { return HostCtor{}; } -}; -template struct GObtainCtor > { - static HostCtor get() { return HostCtor{ConstructVec{&GArray::VCtor}}; } -}; -template struct GObtainCtor > { - static HostCtor get() { return HostCtor{ConstructOpaque{&GOpaque::Ctor}}; } -}; -} // namespace detail -} // namespace cv - -#endif // OPENCV_GAPI_GTYPE_TRAITS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2020 Intel Corporation + + +#ifndef OPENCV_GAPI_GTYPE_TRAITS_HPP +#define OPENCV_GAPI_GTYPE_TRAITS_HPP + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace cv +{ +namespace detail +{ + template + struct contains_shape_field : std::false_type {}; + + template + struct contains_shape_field> : + std::is_same::type, GShape> + {}; + + template + struct has_gshape : contains_shape_field {}; + + // FIXME: These traits and enum and possible numerous switch(kind) + // block may be replaced with a special Handler object or with + // a double dispatch + enum class ArgKind: int + { + OPAQUE_VAL, // Unknown, generic, opaque-to-GAPI data type - STATIC + // Note: OPAQUE is sometimes defined in Win sys headers +#if !defined(OPAQUE) && !defined(CV_DOXYGEN) + OPAQUE = OPAQUE_VAL, // deprecated value used for compatibility, use OPAQUE_VAL instead +#endif + GOBJREF, // reference to object + GMAT, // a cv::GMat + GMATP, // a cv::GMatP + GFRAME, // a cv::GFrame + GSCALAR, // a cv::GScalar + GARRAY, // a cv::GArrayU (note - exactly GArrayU, not GArray!) + GOPAQUE, // a cv::GOpaqueU (note - exactly GOpaqueU, not GOpaque!) + }; + + // Describe G-API types (G-types) with traits. Mostly used by + // cv::GArg to store meta information about types passed into + // operation arguments. Please note that cv::GComputation is + // defined on GProtoArgs, not GArgs! + template struct GTypeTraits; + template struct GTypeTraits + { + static constexpr const ArgKind kind = ArgKind::OPAQUE_VAL; + static constexpr const OpaqueKind op_kind = OpaqueKind::CV_UNKNOWN; + }; + template<> struct GTypeTraits + { + static constexpr const ArgKind kind = ArgKind::GMAT; + static constexpr const GShape shape = GShape::GMAT; + static constexpr const OpaqueKind op_kind = OpaqueKind::CV_UNKNOWN; + }; + template<> struct GTypeTraits + { + static constexpr const ArgKind kind = ArgKind::GMATP; + static constexpr const GShape shape = GShape::GMAT; + static constexpr const OpaqueKind op_kind = OpaqueKind::CV_UNKNOWN; + }; + template<> struct GTypeTraits + { + static constexpr const ArgKind kind = ArgKind::GFRAME; + static constexpr const GShape shape = GShape::GFRAME; + static constexpr const OpaqueKind op_kind = OpaqueKind::CV_UNKNOWN; + }; + template<> struct GTypeTraits + { + static constexpr const ArgKind kind = ArgKind::GSCALAR; + static constexpr const GShape shape = GShape::GSCALAR; + static constexpr const OpaqueKind op_kind = OpaqueKind::CV_UNKNOWN; + }; + template struct GTypeTraits > + { + static constexpr const ArgKind kind = ArgKind::GARRAY; + static constexpr const GShape shape = GShape::GARRAY; + static constexpr const OpaqueKind op_kind = GOpaqueTraits::kind; + using host_type = std::vector; + using strip_type = cv::detail::VectorRef; + static cv::detail::GArrayU wrap_value(const cv::GArray &t) { return t.strip();} + static cv::detail::VectorRef wrap_in (const std::vector &t) { return detail::VectorRef(t); } + static cv::detail::VectorRef wrap_out ( std::vector &t) { return detail::VectorRef(t); } + }; + template struct GTypeTraits > + { + static constexpr const ArgKind kind = ArgKind::GOPAQUE; + static constexpr const GShape shape = GShape::GOPAQUE; + static constexpr const OpaqueKind op_kind = GOpaqueTraits::kind; + using host_type = T; + using strip_type = cv::detail::OpaqueRef; + static cv::detail::GOpaqueU wrap_value(const cv::GOpaque &t) { return t.strip();} + static cv::detail::OpaqueRef wrap_in (const T &t) { return detail::OpaqueRef(t); } + static cv::detail::OpaqueRef wrap_out ( T &t) { return detail::OpaqueRef(t); } + }; + + // Tests if Trait for type T requires extra marshalling ("custom wrap") or not. + // If Traits has wrap_value() defined, it does. + template struct has_custom_wrap + { + template class check; + template static std::true_type test(check::wrap_value)> *); + template static std::false_type test(...); + using type = decltype(test(nullptr)); + static const constexpr bool value = std::is_same(nullptr))>::value; + }; + + // Resolve a Host type back to its associated G-Type. + // FIXME: Probably it can be avoided + // FIXME: GMatP is not present here. + // (Actually these traits is used only to check + // if associated G-type has custom wrap functions + // and GMat behavior is correct for GMatP) + template struct GTypeOf; +#if !defined(GAPI_STANDALONE) + template<> struct GTypeOf { using type = cv::GMat; }; +#endif // !defined(GAPI_STANDALONE) + template<> struct GTypeOf { using type = cv::GMat; }; + template<> struct GTypeOf { using type = cv::GMat; }; + template<> struct GTypeOf { using type = cv::GScalar; }; + template struct GTypeOf > { using type = cv::GArray; }; + template struct GTypeOf { using type = cv::GOpaque;}; + template<> struct GTypeOf { using type = cv::GFrame; }; + + // FIXME: This is not quite correct since IStreamSource may + // produce not only Mat but also MediaFrame, Scalar and vector + // data. TODO: Extend the type dispatching on these types too. + template<> struct GTypeOf { using type = cv::GMat;}; + template using g_type_of_t = typename GTypeOf::type; + + // Marshalling helper for G-types and its Host types. Helps G-API + // to store G types in internal generic containers for further + // processing. Implements the following callbacks: + // + // * wrap() - converts user-facing G-type into an internal one + // for internal storage. + // Used when G-API operation is instantiated (G::on(), + // etc) during expressing a pipeline. Mostly returns input + // value "as is" except the case when G-type is a template. For + // template G-classes, calls custom wrap() from Traits. + // The value returned by wrap() is then wrapped into GArg() and + // stored in G-API metadata. + // + // Example: + // - cv::GMat arguments are passed as-is. + // - integers, pointers, STL containers, user types are passed as-is. + // - cv::GArray is converted to cv::GArrayU. + // + // * wrap_in() / wrap_out() - convert Host type associated with + // G-type to internal representation type. + // + // - For "simple" (non-template) G-types, returns value as-is. + // Example: cv::GMat has host type cv::Mat, when user passes a + // cv::Mat, system stores it internally as cv::Mat. + // + // - For "complex" (template) G-types, utilizes custom + // wrap_in()/wrap_out() as described in Traits. + // Example: cv::GArray has host type std::vector, when + // user passes a std::vector, system stores it + // internally as VectorRef (with stripped away). + template struct WrapValue + { + static auto wrap(const T& t) -> + typename std::remove_reference::type + { + return static_cast::type>(t); + } + + template static U wrap_in (const U &u) { return u; } + template static U* wrap_out(U &u) { return &u; } + }; + template struct WrapValue::value>::type> + { + static auto wrap(const T& t) -> decltype(GTypeTraits::wrap_value(t)) + { + return GTypeTraits::wrap_value(t); + } + template static auto wrap_in (const U &u) -> typename GTypeTraits::strip_type + { + static_assert(!(cv::detail::has_gshape>::value + || cv::detail::contains::type, GAPI_OWN_TYPES_LIST>::value), + "gin/gout must not be used with G* classes or cv::gapi::own::*"); + return GTypeTraits::wrap_in(u); + } + template static auto wrap_out(U &u) -> typename GTypeTraits::strip_type + { + static_assert(!(cv::detail::has_gshape>::value + || cv::detail::contains::type, GAPI_OWN_TYPES_LIST>::value), + "gin/gout must not be used with G* classes or cv::gapi::own::*"); + return GTypeTraits::wrap_out(u); + } + }; + + template using wrap_gapi_helper = WrapValue::type>; + template using wrap_host_helper = WrapValue >::type>; + +// Union type for various user-defined type constructors (GArray, +// GOpaque, etc) +// +// TODO: Replace construct-only API with a more generic one (probably +// with bits of introspection) +// +// Not required for non-user-defined types (GMat, GScalar, etc) +using HostCtor = util::variant + < util::monostate + , detail::ConstructVec + , detail::ConstructOpaque + >; + +template struct GObtainCtor { + static HostCtor get() { return HostCtor{}; } +}; +template struct GObtainCtor > { + static HostCtor get() { return HostCtor{ConstructVec{&GArray::VCtor}}; } +}; +template struct GObtainCtor > { + static HostCtor get() { return HostCtor{ConstructOpaque{&GOpaque::Ctor}}; } +}; +} // namespace detail +} // namespace cv + +#endif // OPENCV_GAPI_GTYPE_TRAITS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gtyped.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gtyped.hpp index 2acc2f7ffb..0bd1cdf7a9 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gtyped.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gtyped.hpp @@ -1,246 +1,246 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_GTYPED_HPP -#define OPENCV_GAPI_GTYPED_HPP -#if !defined(GAPI_STANDALONE) - -#include - -#include -#include -#include -#include - -namespace cv { - -namespace detail -{ - // FIXME: How to prevent coolhackers from extending it by their own types? - // FIXME: ...Should we care? - template struct ProtoToParam; - template<> struct ProtoToParam { using type = cv::Mat; }; - template<> struct ProtoToParam { using type = cv::Scalar; }; - template struct ProtoToParam > { using type = std::vector; }; - template<> struct ProtoToParam> { using type = std::vector; }; - template struct ProtoToParam > { using type = U; }; - template using ProtoToParamT = typename ProtoToParam::type; - - template struct ProtoToMeta; - template<> struct ProtoToMeta { using type = cv::GMatDesc; }; - template<> struct ProtoToMeta { using type = cv::GScalarDesc; }; - template struct ProtoToMeta > { using type = cv::GArrayDesc; }; - template struct ProtoToMeta > { using type = cv::GOpaqueDesc; }; - template using ProtoToMetaT = typename ProtoToMeta::type; - - //workaround for MSVC 19.0 bug - template - auto make_default()->decltype(T{}) {return {};} -} // detail - -/** - * @brief This class is a typed wrapper over a regular GComputation. - * - * `std::function<>`-like template parameter specifies the graph - * signature so methods so the object's constructor, methods like - * `apply()` and the derived `GCompiledT::operator()` also become - * typed. - * - * There is no need to use cv::gin() or cv::gout() modifiers with - * objects of this class. Instead, all input arguments are followed - * by all output arguments in the order from the template argument - * signature. - * - * Refer to the following example. Regular (untyped) code is written this way: - * - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp Untyped_Example - * - * Here: - * - * - cv::GComputation object is created with a lambda constructor - * where it is defined as a two-input, one-output graph. - * - * - Its method `apply()` in fact takes arbitrary number of arguments - * (as vectors) so user can pass wrong number of inputs/outputs - * here. C++ compiler wouldn't notice that since the cv::GComputation - * API is polymorphic, and only a run-time error will be generated. - * - * Now the same code written with typed API: - * - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp Typed_Example - * - * The key difference is: - * - * - Now the constructor lambda *must take* parameters and *must - * return* values as defined in the `GComputationT<>` signature. - * - Its method `apply()` does not require any extra specifiers to - * separate input arguments from the output ones - * - A `GCompiledT` (compilation product) takes input/output - * arguments with no extra specifiers as well. - */ -template class GComputationT; - -// Single return value implementation -template class GComputationT -{ -public: - typedef std::function Gen; - - class GCompiledT - { - private: - friend class GComputationT; - - cv::GCompiled m_comp; - - explicit GCompiledT(const cv::GCompiled &comp) : m_comp(comp) {} - - public: - GCompiledT() {} - - void operator()(detail::ProtoToParamT... inArgs, - detail::ProtoToParamT &outArg) - { - m_comp(cv::gin(inArgs...), cv::gout(outArg)); - } - - explicit operator bool() const - { - return static_cast(m_comp); - } - }; - -private: - typedef std::pair Captured; - - Captured capture(const Gen& g, Args... args) - { - return Captured(g(args...), cv::GIn(args...)); - } - - Captured m_capture; - cv::GComputation m_comp; - -public: - GComputationT(const Gen &generator) - : m_capture(capture(generator, detail::make_default()...)) - , m_comp(cv::GProtoInputArgs(std::move(m_capture.second)), - cv::GOut(m_capture.first)) - { - } - - void apply(detail::ProtoToParamT... inArgs, - detail::ProtoToParamT &outArg, - GCompileArgs &&args) - { - m_comp.apply(cv::gin(inArgs...), cv::gout(outArg), std::move(args)); - } - - void apply(detail::ProtoToParamT... inArgs, - detail::ProtoToParamT &outArg) - { - apply(inArgs..., outArg, GCompileArgs()); - } - - - GCompiledT compile(detail::ProtoToMetaT... inDescs) - { - GMetaArgs inMetas = { GMetaArg(inDescs)... }; - return GCompiledT(m_comp.compile(std::move(inMetas), GCompileArgs())); - } - - GCompiledT compile(detail::ProtoToMetaT... inDescs, GCompileArgs &&args) - { - GMetaArgs inMetas = { GMetaArg(inDescs)... }; - return GCompiledT(m_comp.compile(std::move(inMetas), std::move(args))); - } -}; - -// Multiple (fixed) return value implementation. FIXME: How to avoid copy-paste? -template class GComputationT(Args...)> -{ -public: - typedef std::function(Args...)> Gen; - - class GCompiledT - { - private: - friend class GComputationT(Args...)>; - - cv::GCompiled m_comp; - explicit GCompiledT(const cv::GCompiled &comp) : m_comp(comp) {} - - public: - GCompiledT() {} - - void operator()(detail::ProtoToParamT... inArgs, - detail::ProtoToParamT&... outArgs) - { - m_comp(cv::gin(inArgs...), cv::gout(outArgs...)); - } - - explicit operator bool() const - { - return static_cast(m_comp); - } - }; - -private: - typedef std::pair Captured; - - template - Captured capture(GProtoArgs &&args, const std::tuple &rr, detail::Seq) - { - return Captured(cv::GOut(std::get(rr)...).m_args, args); - } - - Captured capture(const Gen& g, Args... args) - { - return capture(cv::GIn(args...).m_args, g(args...), typename detail::MkSeq::type()); - } - - Captured m_capture; - cv::GComputation m_comp; - -public: - GComputationT(const Gen &generator) - : m_capture(capture(generator, detail::make_default()...)) - , m_comp(cv::GProtoInputArgs(std::move(m_capture.second)), - cv::GProtoOutputArgs(std::move(m_capture.first))) - { - } - - void apply(detail::ProtoToParamT... inArgs, - detail::ProtoToParamT&... outArgs, - GCompileArgs &&args) - { - m_comp.apply(cv::gin(inArgs...), cv::gout(outArgs...), std::move(args)); - } - - void apply(detail::ProtoToParamT... inArgs, - detail::ProtoToParamT&... outArgs) - { - apply(inArgs..., outArgs..., GCompileArgs()); - } - - - GCompiledT compile(detail::ProtoToMetaT... inDescs) - { - GMetaArgs inMetas = { GMetaArg(inDescs)... }; - return GCompiledT(m_comp.compile(std::move(inMetas), GCompileArgs())); - } - - GCompiledT compile(detail::ProtoToMetaT... inDescs, GCompileArgs &&args) - { - GMetaArgs inMetas = { GMetaArg(inDescs)... }; - return GCompiledT(m_comp.compile(std::move(inMetas), std::move(args))); - } -}; - -} // namespace cv -#endif // !defined(GAPI_STANDALONE) -#endif // OPENCV_GAPI_GTYPED_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_GTYPED_HPP +#define OPENCV_GAPI_GTYPED_HPP +#if !defined(GAPI_STANDALONE) + +#include + +#include +#include +#include +#include + +namespace cv { + +namespace detail +{ + // FIXME: How to prevent coolhackers from extending it by their own types? + // FIXME: ...Should we care? + template struct ProtoToParam; + template<> struct ProtoToParam { using type = cv::Mat; }; + template<> struct ProtoToParam { using type = cv::Scalar; }; + template struct ProtoToParam > { using type = std::vector; }; + template<> struct ProtoToParam> { using type = std::vector; }; + template struct ProtoToParam > { using type = U; }; + template using ProtoToParamT = typename ProtoToParam::type; + + template struct ProtoToMeta; + template<> struct ProtoToMeta { using type = cv::GMatDesc; }; + template<> struct ProtoToMeta { using type = cv::GScalarDesc; }; + template struct ProtoToMeta > { using type = cv::GArrayDesc; }; + template struct ProtoToMeta > { using type = cv::GOpaqueDesc; }; + template using ProtoToMetaT = typename ProtoToMeta::type; + + //workaround for MSVC 19.0 bug + template + auto make_default()->decltype(T{}) {return {};} +} // detail + +/** + * @brief This class is a typed wrapper over a regular GComputation. + * + * `std::function<>`-like template parameter specifies the graph + * signature so methods so the object's constructor, methods like + * `apply()` and the derived `GCompiledT::operator()` also become + * typed. + * + * There is no need to use cv::gin() or cv::gout() modifiers with + * objects of this class. Instead, all input arguments are followed + * by all output arguments in the order from the template argument + * signature. + * + * Refer to the following example. Regular (untyped) code is written this way: + * + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp Untyped_Example + * + * Here: + * + * - cv::GComputation object is created with a lambda constructor + * where it is defined as a two-input, one-output graph. + * + * - Its method `apply()` in fact takes arbitrary number of arguments + * (as vectors) so user can pass wrong number of inputs/outputs + * here. C++ compiler wouldn't notice that since the cv::GComputation + * API is polymorphic, and only a run-time error will be generated. + * + * Now the same code written with typed API: + * + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp Typed_Example + * + * The key difference is: + * + * - Now the constructor lambda *must take* parameters and *must + * return* values as defined in the `GComputationT<>` signature. + * - Its method `apply()` does not require any extra specifiers to + * separate input arguments from the output ones + * - A `GCompiledT` (compilation product) takes input/output + * arguments with no extra specifiers as well. + */ +template class GComputationT; + +// Single return value implementation +template class GComputationT +{ +public: + typedef std::function Gen; + + class GCompiledT + { + private: + friend class GComputationT; + + cv::GCompiled m_comp; + + explicit GCompiledT(const cv::GCompiled &comp) : m_comp(comp) {} + + public: + GCompiledT() {} + + void operator()(detail::ProtoToParamT... inArgs, + detail::ProtoToParamT &outArg) + { + m_comp(cv::gin(inArgs...), cv::gout(outArg)); + } + + explicit operator bool() const + { + return static_cast(m_comp); + } + }; + +private: + typedef std::pair Captured; + + Captured capture(const Gen& g, Args... args) + { + return Captured(g(args...), cv::GIn(args...)); + } + + Captured m_capture; + cv::GComputation m_comp; + +public: + GComputationT(const Gen &generator) + : m_capture(capture(generator, detail::make_default()...)) + , m_comp(cv::GProtoInputArgs(std::move(m_capture.second)), + cv::GOut(m_capture.first)) + { + } + + void apply(detail::ProtoToParamT... inArgs, + detail::ProtoToParamT &outArg, + GCompileArgs &&args) + { + m_comp.apply(cv::gin(inArgs...), cv::gout(outArg), std::move(args)); + } + + void apply(detail::ProtoToParamT... inArgs, + detail::ProtoToParamT &outArg) + { + apply(inArgs..., outArg, GCompileArgs()); + } + + + GCompiledT compile(detail::ProtoToMetaT... inDescs) + { + GMetaArgs inMetas = { GMetaArg(inDescs)... }; + return GCompiledT(m_comp.compile(std::move(inMetas), GCompileArgs())); + } + + GCompiledT compile(detail::ProtoToMetaT... inDescs, GCompileArgs &&args) + { + GMetaArgs inMetas = { GMetaArg(inDescs)... }; + return GCompiledT(m_comp.compile(std::move(inMetas), std::move(args))); + } +}; + +// Multiple (fixed) return value implementation. FIXME: How to avoid copy-paste? +template class GComputationT(Args...)> +{ +public: + typedef std::function(Args...)> Gen; + + class GCompiledT + { + private: + friend class GComputationT(Args...)>; + + cv::GCompiled m_comp; + explicit GCompiledT(const cv::GCompiled &comp) : m_comp(comp) {} + + public: + GCompiledT() {} + + void operator()(detail::ProtoToParamT... inArgs, + detail::ProtoToParamT&... outArgs) + { + m_comp(cv::gin(inArgs...), cv::gout(outArgs...)); + } + + explicit operator bool() const + { + return static_cast(m_comp); + } + }; + +private: + typedef std::pair Captured; + + template + Captured capture(GProtoArgs &&args, const std::tuple &rr, detail::Seq) + { + return Captured(cv::GOut(std::get(rr)...).m_args, args); + } + + Captured capture(const Gen& g, Args... args) + { + return capture(cv::GIn(args...).m_args, g(args...), typename detail::MkSeq::type()); + } + + Captured m_capture; + cv::GComputation m_comp; + +public: + GComputationT(const Gen &generator) + : m_capture(capture(generator, detail::make_default()...)) + , m_comp(cv::GProtoInputArgs(std::move(m_capture.second)), + cv::GProtoOutputArgs(std::move(m_capture.first))) + { + } + + void apply(detail::ProtoToParamT... inArgs, + detail::ProtoToParamT&... outArgs, + GCompileArgs &&args) + { + m_comp.apply(cv::gin(inArgs...), cv::gout(outArgs...), std::move(args)); + } + + void apply(detail::ProtoToParamT... inArgs, + detail::ProtoToParamT&... outArgs) + { + apply(inArgs..., outArgs..., GCompileArgs()); + } + + + GCompiledT compile(detail::ProtoToMetaT... inDescs) + { + GMetaArgs inMetas = { GMetaArg(inDescs)... }; + return GCompiledT(m_comp.compile(std::move(inMetas), GCompileArgs())); + } + + GCompiledT compile(detail::ProtoToMetaT... inDescs, GCompileArgs &&args) + { + GMetaArgs inMetas = { GMetaArg(inDescs)... }; + return GCompiledT(m_comp.compile(std::move(inMetas), std::move(args))); + } +}; + +} // namespace cv +#endif // !defined(GAPI_STANDALONE) +#endif // OPENCV_GAPI_GTYPED_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/imgproc.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/imgproc.hpp index 96aaa5a447..67a34fbbc9 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/imgproc.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/imgproc.hpp @@ -1,1769 +1,1769 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2020 Intel Corporation - - -#ifndef OPENCV_GAPI_IMGPROC_HPP -#define OPENCV_GAPI_IMGPROC_HPP - -#include - -#include // std::tuple - -#include -#include -#include - - -/** \defgroup gapi_imgproc G-API Image processing functionality -@{ - @defgroup gapi_filters Graph API: Image filters - @defgroup gapi_colorconvert Graph API: Converting image from one color space to another - @defgroup gapi_feature Graph API: Image Feature Detection - @defgroup gapi_shape Graph API: Image Structural Analysis and Shape Descriptors - @defgroup gapi_transform Graph API: Image and channel composition functions -@} - */ - -namespace { -void validateFindingContoursMeta(const int depth, const int chan, const int mode) -{ - GAPI_Assert(chan == 1); - switch (mode) - { - case cv::RETR_CCOMP: - GAPI_Assert(depth == CV_8U || depth == CV_32S); - break; - case cv::RETR_FLOODFILL: - GAPI_Assert(depth == CV_32S); - break; - default: - GAPI_Assert(depth == CV_8U); - break; - } -} -} // anonymous namespace - -namespace cv { namespace gapi { - -/** - * @brief This namespace contains G-API Operation Types for OpenCV - * ImgProc module functionality. - */ -namespace imgproc { - using GMat2 = std::tuple; - using GMat3 = std::tuple; // FIXME: how to avoid this? - using GFindContoursOutput = std::tuple>,GArray>; - - G_TYPED_KERNEL(GFilter2D, , "org.opencv.imgproc.filters.filter2D") { - static GMatDesc outMeta(GMatDesc in, int ddepth, Mat, Point, Scalar, int, Scalar) { - return in.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GSepFilter, , "org.opencv.imgproc.filters.sepfilter") { - static GMatDesc outMeta(GMatDesc in, int ddepth, Mat, Mat, Point, Scalar, int, Scalar) { - return in.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GBoxFilter, , "org.opencv.imgproc.filters.boxfilter") { - static GMatDesc outMeta(GMatDesc in, int ddepth, Size, Point, bool, int, Scalar) { - return in.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GBlur, , "org.opencv.imgproc.filters.blur") { - static GMatDesc outMeta(GMatDesc in, Size, Point, int, Scalar) { - return in; - } - }; - - G_TYPED_KERNEL(GGaussBlur, , "org.opencv.imgproc.filters.gaussianBlur") { - static GMatDesc outMeta(GMatDesc in, Size, double, double, int, Scalar) { - return in; - } - }; - - G_TYPED_KERNEL(GMedianBlur, , "org.opencv.imgproc.filters.medianBlur") { - static GMatDesc outMeta(GMatDesc in, int) { - return in; - } - }; - - G_TYPED_KERNEL(GErode, , "org.opencv.imgproc.filters.erode") { - static GMatDesc outMeta(GMatDesc in, Mat, Point, int, int, Scalar) { - return in; - } - }; - - G_TYPED_KERNEL(GDilate, , "org.opencv.imgproc.filters.dilate") { - static GMatDesc outMeta(GMatDesc in, Mat, Point, int, int, Scalar) { - return in; - } - }; - - G_TYPED_KERNEL(GMorphologyEx, , - "org.opencv.imgproc.filters.morphologyEx") { - static GMatDesc outMeta(const GMatDesc &in, MorphTypes, Mat, Point, int, - BorderTypes, Scalar) { - return in; - } - }; - - G_TYPED_KERNEL(GSobel, , "org.opencv.imgproc.filters.sobel") { - static GMatDesc outMeta(GMatDesc in, int ddepth, int, int, int, double, double, int, Scalar) { - return in.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL_M(GSobelXY, , "org.opencv.imgproc.filters.sobelxy") { - static std::tuple outMeta(GMatDesc in, int ddepth, int, int, double, double, int, Scalar) { - return std::make_tuple(in.withDepth(ddepth), in.withDepth(ddepth)); - } - }; - - G_TYPED_KERNEL(GLaplacian, , - "org.opencv.imgproc.filters.laplacian") { - static GMatDesc outMeta(GMatDesc in, int ddepth, int, double, double, int) { - return in.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GBilateralFilter, , - "org.opencv.imgproc.filters.bilateralfilter") { - static GMatDesc outMeta(GMatDesc in, int, double, double, int) { - return in; - } - }; - - G_TYPED_KERNEL(GEqHist, , "org.opencv.imgproc.equalizeHist") { - static GMatDesc outMeta(GMatDesc in) { - return in.withType(CV_8U, 1); - } - }; - - G_TYPED_KERNEL(GCanny, , "org.opencv.imgproc.feature.canny") { - static GMatDesc outMeta(GMatDesc in, double, double, int, bool) { - return in.withType(CV_8U, 1); - } - }; - - G_TYPED_KERNEL(GGoodFeatures, - (GMat,int,double,double,Mat,int,bool,double)>, - "org.opencv.imgproc.feature.goodFeaturesToTrack") { - static GArrayDesc outMeta(GMatDesc, int, double, double, const Mat&, int, bool, double) { - return empty_array_desc(); - } - }; - - using RetrMode = RetrievalModes; - using ContMethod = ContourApproximationModes; - G_TYPED_KERNEL(GFindContours, >(GMat,RetrMode,ContMethod,GOpaque)>, - "org.opencv.imgproc.shape.findContours") - { - static GArrayDesc outMeta(GMatDesc in, RetrMode mode, ContMethod, GOpaqueDesc) - { - validateFindingContoursMeta(in.depth, in.chan, mode); - return empty_array_desc(); - } - }; - - // FIXME oc: make default value offset = Point() - G_TYPED_KERNEL(GFindContoursNoOffset, >(GMat,RetrMode,ContMethod)>, - "org.opencv.imgproc.shape.findContoursNoOffset") - { - static GArrayDesc outMeta(GMatDesc in, RetrMode mode, ContMethod) - { - validateFindingContoursMeta(in.depth, in.chan, mode); - return empty_array_desc(); - } - }; - - G_TYPED_KERNEL(GFindContoursH,)>, - "org.opencv.imgproc.shape.findContoursH") - { - static std::tuple - outMeta(GMatDesc in, RetrMode mode, ContMethod, GOpaqueDesc) - { - validateFindingContoursMeta(in.depth, in.chan, mode); - return std::make_tuple(empty_array_desc(), empty_array_desc()); - } - }; - - // FIXME oc: make default value offset = Point() - G_TYPED_KERNEL(GFindContoursHNoOffset,, - "org.opencv.imgproc.shape.findContoursHNoOffset") - { - static std::tuple - outMeta(GMatDesc in, RetrMode mode, ContMethod) - { - validateFindingContoursMeta(in.depth, in.chan, mode); - return std::make_tuple(empty_array_desc(), empty_array_desc()); - } - }; - - G_TYPED_KERNEL(GBoundingRectMat, (GMat)>, - "org.opencv.imgproc.shape.boundingRectMat") { - static GOpaqueDesc outMeta(GMatDesc in) { - if (in.depth == CV_8U) - { - GAPI_Assert(in.chan == 1); - } - else - { - GAPI_Assert (in.depth == CV_32S || in.depth == CV_32F); - int amount = detail::checkVector(in, 2u); - GAPI_Assert(amount != -1 && - "Input Mat can't be described as vector of 2-dimentional points"); - } - return empty_gopaque_desc(); - } - }; - - G_TYPED_KERNEL(GBoundingRectVector32S, (GArray)>, - "org.opencv.imgproc.shape.boundingRectVector32S") { - static GOpaqueDesc outMeta(GArrayDesc) { - return empty_gopaque_desc(); - } - }; - - G_TYPED_KERNEL(GBoundingRectVector32F, (GArray)>, - "org.opencv.imgproc.shape.boundingRectVector32F") { - static GOpaqueDesc outMeta(GArrayDesc) { - return empty_gopaque_desc(); - } - }; - - G_TYPED_KERNEL(GFitLine2DMat, (GMat,DistanceTypes,double,double,double)>, - "org.opencv.imgproc.shape.fitLine2DMat") { - static GOpaqueDesc outMeta(GMatDesc in,DistanceTypes,double,double,double) { - int amount = detail::checkVector(in, 2u); - GAPI_Assert(amount != -1 && - "Input Mat can't be described as vector of 2-dimentional points"); - return empty_gopaque_desc(); - } - }; - - G_TYPED_KERNEL(GFitLine2DVector32S, - (GArray,DistanceTypes,double,double,double)>, - "org.opencv.imgproc.shape.fitLine2DVector32S") { - static GOpaqueDesc outMeta(GArrayDesc,DistanceTypes,double,double,double) { - return empty_gopaque_desc(); - } - }; - - G_TYPED_KERNEL(GFitLine2DVector32F, - (GArray,DistanceTypes,double,double,double)>, - "org.opencv.imgproc.shape.fitLine2DVector32F") { - static GOpaqueDesc outMeta(GArrayDesc,DistanceTypes,double,double,double) { - return empty_gopaque_desc(); - } - }; - - G_TYPED_KERNEL(GFitLine2DVector64F, - (GArray,DistanceTypes,double,double,double)>, - "org.opencv.imgproc.shape.fitLine2DVector64F") { - static GOpaqueDesc outMeta(GArrayDesc,DistanceTypes,double,double,double) { - return empty_gopaque_desc(); - } - }; - - G_TYPED_KERNEL(GFitLine3DMat, (GMat,DistanceTypes,double,double,double)>, - "org.opencv.imgproc.shape.fitLine3DMat") { - static GOpaqueDesc outMeta(GMatDesc in,int,double,double,double) { - int amount = detail::checkVector(in, 3u); - GAPI_Assert(amount != -1 && - "Input Mat can't be described as vector of 3-dimentional points"); - return empty_gopaque_desc(); - } - }; - - G_TYPED_KERNEL(GFitLine3DVector32S, - (GArray,DistanceTypes,double,double,double)>, - "org.opencv.imgproc.shape.fitLine3DVector32S") { - static GOpaqueDesc outMeta(GArrayDesc,DistanceTypes,double,double,double) { - return empty_gopaque_desc(); - } - }; - - G_TYPED_KERNEL(GFitLine3DVector32F, - (GArray,DistanceTypes,double,double,double)>, - "org.opencv.imgproc.shape.fitLine3DVector32F") { - static GOpaqueDesc outMeta(GArrayDesc,DistanceTypes,double,double,double) { - return empty_gopaque_desc(); - } - }; - - G_TYPED_KERNEL(GFitLine3DVector64F, - (GArray,DistanceTypes,double,double,double)>, - "org.opencv.imgproc.shape.fitLine3DVector64F") { - static GOpaqueDesc outMeta(GArrayDesc,DistanceTypes,double,double,double) { - return empty_gopaque_desc(); - } - }; - - G_TYPED_KERNEL(GBGR2RGB, , "org.opencv.imgproc.colorconvert.bgr2rgb") { - static GMatDesc outMeta(GMatDesc in) { - return in; // type still remains CV_8UC3; - } - }; - - G_TYPED_KERNEL(GRGB2YUV, , "org.opencv.imgproc.colorconvert.rgb2yuv") { - static GMatDesc outMeta(GMatDesc in) { - return in; // type still remains CV_8UC3; - } - }; - - G_TYPED_KERNEL(GYUV2RGB, , "org.opencv.imgproc.colorconvert.yuv2rgb") { - static GMatDesc outMeta(GMatDesc in) { - return in; // type still remains CV_8UC3; - } - }; - - G_TYPED_KERNEL(GBGR2I420, , "org.opencv.imgproc.colorconvert.bgr2i420") { - static GMatDesc outMeta(GMatDesc in) { - GAPI_Assert(in.depth == CV_8U); - GAPI_Assert(in.chan == 3); - GAPI_Assert(in.size.height % 2 == 0); - return in.withType(in.depth, 1).withSize(Size(in.size.width, in.size.height * 3 / 2)); - } - }; - - G_TYPED_KERNEL(GRGB2I420, , "org.opencv.imgproc.colorconvert.rgb2i420") { - static GMatDesc outMeta(GMatDesc in) { - GAPI_Assert(in.depth == CV_8U); - GAPI_Assert(in.chan == 3); - GAPI_Assert(in.size.height % 2 == 0); - return in.withType(in.depth, 1).withSize(Size(in.size.width, in.size.height * 3 / 2)); - } - }; - - G_TYPED_KERNEL(GI4202BGR, , "org.opencv.imgproc.colorconvert.i4202bgr") { - static GMatDesc outMeta(GMatDesc in) { - GAPI_Assert(in.depth == CV_8U); - GAPI_Assert(in.chan == 1); - GAPI_Assert(in.size.height % 3 == 0); - return in.withType(in.depth, 3).withSize(Size(in.size.width, in.size.height * 2 / 3)); - } - }; - - G_TYPED_KERNEL(GI4202RGB, , "org.opencv.imgproc.colorconvert.i4202rgb") { - static GMatDesc outMeta(GMatDesc in) { - GAPI_Assert(in.depth == CV_8U); - GAPI_Assert(in.chan == 1); - GAPI_Assert(in.size.height % 3 == 0); - return in.withType(in.depth, 3).withSize(Size(in.size.width, in.size.height * 2 / 3)); - } - }; - - G_TYPED_KERNEL(GNV12toRGB, , "org.opencv.imgproc.colorconvert.nv12torgb") { - static GMatDesc outMeta(GMatDesc in_y, GMatDesc in_uv) { - GAPI_Assert(in_y.chan == 1); - GAPI_Assert(in_uv.chan == 2); - GAPI_Assert(in_y.depth == CV_8U); - GAPI_Assert(in_uv.depth == CV_8U); - // UV size should be aligned with Y - GAPI_Assert(in_y.size.width == 2 * in_uv.size.width); - GAPI_Assert(in_y.size.height == 2 * in_uv.size.height); - return in_y.withType(CV_8U, 3); // type will be CV_8UC3; - } - }; - - G_TYPED_KERNEL(GNV12toBGR, , "org.opencv.imgproc.colorconvert.nv12tobgr") { - static GMatDesc outMeta(GMatDesc in_y, GMatDesc in_uv) { - GAPI_Assert(in_y.chan == 1); - GAPI_Assert(in_uv.chan == 2); - GAPI_Assert(in_y.depth == CV_8U); - GAPI_Assert(in_uv.depth == CV_8U); - // UV size should be aligned with Y - GAPI_Assert(in_y.size.width == 2 * in_uv.size.width); - GAPI_Assert(in_y.size.height == 2 * in_uv.size.height); - return in_y.withType(CV_8U, 3); // type will be CV_8UC3; - } - }; - - G_TYPED_KERNEL(GRGB2Lab, , "org.opencv.imgproc.colorconvert.rgb2lab") { - static GMatDesc outMeta(GMatDesc in) { - return in; // type still remains CV_8UC3; - } - }; - - G_TYPED_KERNEL(GBGR2LUV, , "org.opencv.imgproc.colorconvert.bgr2luv") { - static GMatDesc outMeta(GMatDesc in) { - return in; // type still remains CV_8UC3; - } - }; - - G_TYPED_KERNEL(GLUV2BGR, , "org.opencv.imgproc.colorconvert.luv2bgr") { - static GMatDesc outMeta(GMatDesc in) { - return in; // type still remains CV_8UC3; - } - }; - - G_TYPED_KERNEL(GYUV2BGR, , "org.opencv.imgproc.colorconvert.yuv2bgr") { - static GMatDesc outMeta(GMatDesc in) { - return in; // type still remains CV_8UC3; - } - }; - - G_TYPED_KERNEL(GBGR2YUV, , "org.opencv.imgproc.colorconvert.bgr2yuv") { - static GMatDesc outMeta(GMatDesc in) { - return in; // type still remains CV_8UC3; - } - }; - - G_TYPED_KERNEL(GRGB2Gray, , "org.opencv.imgproc.colorconvert.rgb2gray") { - static GMatDesc outMeta(GMatDesc in) { - return in.withType(CV_8U, 1); - } - }; - - G_TYPED_KERNEL(GRGB2GrayCustom, , "org.opencv.imgproc.colorconvert.rgb2graycustom") { - static GMatDesc outMeta(GMatDesc in, float, float, float) { - return in.withType(CV_8U, 1); - } - }; - - G_TYPED_KERNEL(GBGR2Gray, , "org.opencv.imgproc.colorconvert.bgr2gray") { - static GMatDesc outMeta(GMatDesc in) { - return in.withType(CV_8U, 1); - } - }; - - G_TYPED_KERNEL(GBayerGR2RGB, , "org.opencv.imgproc.colorconvert.bayergr2rgb") { - static cv::GMatDesc outMeta(cv::GMatDesc in) { - return in.withType(CV_8U, 3); - } - }; - - G_TYPED_KERNEL(GRGB2HSV, , "org.opencv.imgproc.colorconvert.rgb2hsv") { - static cv::GMatDesc outMeta(cv::GMatDesc in) { - return in; - } - }; - - G_TYPED_KERNEL(GRGB2YUV422, , "org.opencv.imgproc.colorconvert.rgb2yuv422") { - static cv::GMatDesc outMeta(cv::GMatDesc in) { - GAPI_Assert(in.depth == CV_8U); - GAPI_Assert(in.chan == 3); - return in.withType(in.depth, 2); - } - }; - - G_TYPED_KERNEL(GNV12toRGBp, , "org.opencv.imgproc.colorconvert.nv12torgbp") { - static GMatDesc outMeta(GMatDesc inY, GMatDesc inUV) { - GAPI_Assert(inY.depth == CV_8U); - GAPI_Assert(inUV.depth == CV_8U); - GAPI_Assert(inY.chan == 1); - GAPI_Assert(inY.planar == false); - GAPI_Assert(inUV.chan == 2); - GAPI_Assert(inUV.planar == false); - GAPI_Assert(inY.size.width == 2 * inUV.size.width); - GAPI_Assert(inY.size.height == 2 * inUV.size.height); - return inY.withType(CV_8U, 3).asPlanar(); - } - }; - - G_TYPED_KERNEL(GNV12toGray, , "org.opencv.imgproc.colorconvert.nv12togray") { - static GMatDesc outMeta(GMatDesc inY, GMatDesc inUV) { - GAPI_Assert(inY.depth == CV_8U); - GAPI_Assert(inUV.depth == CV_8U); - GAPI_Assert(inY.chan == 1); - GAPI_Assert(inY.planar == false); - GAPI_Assert(inUV.chan == 2); - GAPI_Assert(inUV.planar == false); - - GAPI_Assert(inY.size.width == 2 * inUV.size.width); - GAPI_Assert(inY.size.height == 2 * inUV.size.height); - return inY.withType(CV_8U, 1); - } - }; - - G_TYPED_KERNEL(GNV12toBGRp, , "org.opencv.imgproc.colorconvert.nv12tobgrp") { - static GMatDesc outMeta(GMatDesc inY, GMatDesc inUV) { - GAPI_Assert(inY.depth == CV_8U); - GAPI_Assert(inUV.depth == CV_8U); - GAPI_Assert(inY.chan == 1); - GAPI_Assert(inY.planar == false); - GAPI_Assert(inUV.chan == 2); - GAPI_Assert(inUV.planar == false); - GAPI_Assert(inY.size.width == 2 * inUV.size.width); - GAPI_Assert(inY.size.height == 2 * inUV.size.height); - return inY.withType(CV_8U, 3).asPlanar(); - } - }; - - G_TYPED_KERNEL(GResize, , "org.opencv.imgproc.transform.resize") { - static GMatDesc outMeta(GMatDesc in, Size sz, double fx, double fy, int /*interp*/) { - if (sz.width != 0 && sz.height != 0) - { - return in.withSize(sz); - } - else - { - int outSz_w = saturate_cast(in.size.width * fx); - int outSz_h = saturate_cast(in.size.height * fy); - GAPI_Assert(outSz_w > 0 && outSz_h > 0); - return in.withSize(Size(outSz_w, outSz_h)); - } - } - }; - - G_TYPED_KERNEL(GResizeP, , "org.opencv.imgproc.transform.resizeP") { - static GMatDesc outMeta(GMatDesc in, Size sz, int interp) { - GAPI_Assert(in.depth == CV_8U); - GAPI_Assert(in.chan == 3); - GAPI_Assert(in.planar); - GAPI_Assert(interp == cv::INTER_LINEAR); - return in.withSize(sz); - } - }; - -} //namespace imgproc - -//! @addtogroup gapi_filters -//! @{ -/** @brief Applies a separable linear filter to a matrix(image). - -The function applies a separable linear filter to the matrix. That is, first, every row of src is -filtered with the 1D kernel kernelX. Then, every column of the result is filtered with the 1D -kernel kernelY. The final result is returned. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. -Output image must have the same type, size, and number of channels as the input image. -@note - - In case of floating-point computation, rounding to nearest even is procedeed -if hardware supports it (if not - to nearest value). - - Function textual ID is "org.opencv.imgproc.filters.sepfilter" -@param src Source image. -@param ddepth desired depth of the destination image (the following combinations of src.depth() and ddepth are supported: - - src.depth() = CV_8U, ddepth = -1/CV_16S/CV_32F/CV_64F - src.depth() = CV_16U/CV_16S, ddepth = -1/CV_32F/CV_64F - src.depth() = CV_32F, ddepth = -1/CV_32F/CV_64F - src.depth() = CV_64F, ddepth = -1/CV_64F - -when ddepth=-1, the output image will have the same depth as the source) -@param kernelX Coefficients for filtering each row. -@param kernelY Coefficients for filtering each column. -@param anchor Anchor position within the kernel. The default value \f$(-1,-1)\f$ means that the anchor -is at the kernel center. -@param delta Value added to the filtered results before storing them. -@param borderType Pixel extrapolation method, see cv::BorderTypes -@param borderValue border value in case of constant border type -@sa boxFilter, gaussianBlur, medianBlur - */ -GAPI_EXPORTS_W GMat sepFilter(const GMat& src, int ddepth, const Mat& kernelX, const Mat& kernelY, const Point& anchor /*FIXME: = Point(-1,-1)*/, - const Scalar& delta /*FIXME = GScalar(0)*/, int borderType = BORDER_DEFAULT, - const Scalar& borderValue = Scalar(0)); - -/** @brief Convolves an image with the kernel. - -The function applies an arbitrary linear filter to an image. When -the aperture is partially outside the image, the function interpolates outlier pixel values -according to the specified border mode. - -The function does actually compute correlation, not the convolution: - -\f[\texttt{dst} (x,y) = \sum _{ \substack{0\leq x' < \texttt{kernel.cols}\\{0\leq y' < \texttt{kernel.rows}}}} \texttt{kernel} (x',y')* \texttt{src} (x+x'- \texttt{anchor.x} ,y+y'- \texttt{anchor.y} )\f] - -That is, the kernel is not mirrored around the anchor point. If you need a real convolution, flip -the kernel using flip and set the new anchor to `(kernel.cols - anchor.x - 1, kernel.rows - -anchor.y - 1)`. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. -Output image must have the same size and number of channels an input image. -@note - - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. - - Function textual ID is "org.opencv.imgproc.filters.filter2D" - -@param src input image. -@param ddepth desired depth of the destination image -@param kernel convolution kernel (or rather a correlation kernel), a single-channel floating point -matrix; if you want to apply different kernels to different channels, split the image into -separate color planes using split and process them individually. -@param anchor anchor of the kernel that indicates the relative position of a filtered point within -the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor -is at the kernel center. -@param delta optional value added to the filtered pixels before storing them in dst. -@param borderType pixel extrapolation method, see cv::BorderTypes -@param borderValue border value in case of constant border type -@sa sepFilter - */ -GAPI_EXPORTS_W GMat filter2D(const GMat& src, int ddepth, const Mat& kernel, const Point& anchor = Point(-1,-1), const Scalar& delta = Scalar(0), - int borderType = BORDER_DEFAULT, const Scalar& borderValue = Scalar(0)); - - -/** @brief Blurs an image using the box filter. - -The function smooths an image using the kernel: - -\f[\texttt{K} = \alpha \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \end{bmatrix}\f] - -where - -\f[\alpha = \begin{cases} \frac{1}{\texttt{ksize.width*ksize.height}} & \texttt{when } \texttt{normalize=true} \\1 & \texttt{otherwise} \end{cases}\f] - -Unnormalized box filter is useful for computing various integral characteristics over each pixel -neighborhood, such as covariance matrices of image derivatives (used in dense optical flow -algorithms, and so on). If you need to compute pixel sums over variable-size windows, use cv::integral. - -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. -Output image must have the same type, size, and number of channels as the input image. -@note - - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. - - Function textual ID is "org.opencv.imgproc.filters.boxfilter" - -@param src Source image. -@param dtype the output image depth (-1 to set the input image data type). -@param ksize blurring kernel size. -@param anchor Anchor position within the kernel. The default value \f$(-1,-1)\f$ means that the anchor -is at the kernel center. -@param normalize flag, specifying whether the kernel is normalized by its area or not. -@param borderType Pixel extrapolation method, see cv::BorderTypes -@param borderValue border value in case of constant border type -@sa sepFilter, gaussianBlur, medianBlur, integral - */ -GAPI_EXPORTS_W GMat boxFilter(const GMat& src, int dtype, const Size& ksize, const Point& anchor = Point(-1,-1), - bool normalize = true, int borderType = BORDER_DEFAULT, - const Scalar& borderValue = Scalar(0)); - -/** @brief Blurs an image using the normalized box filter. - -The function smooths an image using the kernel: - -\f[\texttt{K} = \frac{1}{\texttt{ksize.width*ksize.height}} \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \end{bmatrix}\f] - -The call `blur(src, ksize, anchor, borderType)` is equivalent to `boxFilter(src, src.type(), ksize, anchor, -true, borderType)`. - -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. -Output image must have the same type, size, and number of channels as the input image. -@note - - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. - - Function textual ID is "org.opencv.imgproc.filters.blur" - -@param src Source image. -@param ksize blurring kernel size. -@param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel -center. -@param borderType border mode used to extrapolate pixels outside of the image, see cv::BorderTypes -@param borderValue border value in case of constant border type -@sa boxFilter, bilateralFilter, GaussianBlur, medianBlur - */ -GAPI_EXPORTS_W GMat blur(const GMat& src, const Size& ksize, const Point& anchor = Point(-1,-1), - int borderType = BORDER_DEFAULT, const Scalar& borderValue = Scalar(0)); - - -//GAPI_EXPORTS_W void blur( InputArray src, OutputArray dst, - // Size ksize, Point anchor = Point(-1,-1), - // int borderType = BORDER_DEFAULT ); - - -/** @brief Blurs an image using a Gaussian filter. - -The function filter2Ds the source image with the specified Gaussian kernel. -Output image must have the same type and number of channels an input image. - -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. -Output image must have the same type, size, and number of channels as the input image. -@note - - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. - - Function textual ID is "org.opencv.imgproc.filters.gaussianBlur" - -@param src input image; -@param ksize Gaussian kernel size. ksize.width and ksize.height can differ but they both must be -positive and odd. Or, they can be zero's and then they are computed from sigma. -@param sigmaX Gaussian kernel standard deviation in X direction. -@param sigmaY Gaussian kernel standard deviation in Y direction; if sigmaY is zero, it is set to be -equal to sigmaX, if both sigmas are zeros, they are computed from ksize.width and ksize.height, -respectively (see cv::getGaussianKernel for details); to fully control the result regardless of -possible future modifications of all this semantics, it is recommended to specify all of ksize, -sigmaX, and sigmaY. -@param borderType pixel extrapolation method, see cv::BorderTypes -@param borderValue border value in case of constant border type -@sa sepFilter, boxFilter, medianBlur - */ -GAPI_EXPORTS_W GMat gaussianBlur(const GMat& src, const Size& ksize, double sigmaX, double sigmaY = 0, - int borderType = BORDER_DEFAULT, const Scalar& borderValue = Scalar(0)); - -/** @brief Blurs an image using the median filter. - -The function smoothes an image using the median filter with the \f$\texttt{ksize} \times -\texttt{ksize}\f$ aperture. Each channel of a multi-channel image is processed independently. -Output image must have the same type, size, and number of channels as the input image. -@note - - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. -The median filter uses cv::BORDER_REPLICATE internally to cope with border pixels, see cv::BorderTypes - - Function textual ID is "org.opencv.imgproc.filters.medianBlur" - -@param src input matrix (image) -@param ksize aperture linear size; it must be odd and greater than 1, for example: 3, 5, 7 ... -@sa boxFilter, gaussianBlur - */ -GAPI_EXPORTS_W GMat medianBlur(const GMat& src, int ksize); - -/** @brief Erodes an image by using a specific structuring element. - -The function erodes the source image using the specified structuring element that determines the -shape of a pixel neighborhood over which the minimum is taken: - -\f[\texttt{dst} (x,y) = \min _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f] - -Erosion can be applied several (iterations) times. In case of multi-channel images, each channel is processed independently. -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, and @ref CV_32FC1. -Output image must have the same type, size, and number of channels as the input image. -@note - - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. - - Function textual ID is "org.opencv.imgproc.filters.erode" - -@param src input image -@param kernel structuring element used for erosion; if `element=Mat()`, a `3 x 3` rectangular -structuring element is used. Kernel can be created using getStructuringElement. -@param anchor position of the anchor within the element; default value (-1, -1) means that the -anchor is at the element center. -@param iterations number of times erosion is applied. -@param borderType pixel extrapolation method, see cv::BorderTypes -@param borderValue border value in case of a constant border -@sa dilate, morphologyEx - */ -GAPI_EXPORTS_W GMat erode(const GMat& src, const Mat& kernel, const Point& anchor = Point(-1,-1), int iterations = 1, - int borderType = BORDER_CONSTANT, - const Scalar& borderValue = morphologyDefaultBorderValue()); - -/** @brief Erodes an image by using 3 by 3 rectangular structuring element. - -The function erodes the source image using the rectangular structuring element with rectangle center as an anchor. -Erosion can be applied several (iterations) times. In case of multi-channel images, each channel is processed independently. -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, and @ref CV_32FC1. -Output image must have the same type, size, and number of channels as the input image. -@note - - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. - - Function textual ID is "org.opencv.imgproc.filters.erode" - -@param src input image -@param iterations number of times erosion is applied. -@param borderType pixel extrapolation method, see cv::BorderTypes -@param borderValue border value in case of a constant border -@sa erode, dilate3x3 - */ -GAPI_EXPORTS_W GMat erode3x3(const GMat& src, int iterations = 1, - int borderType = BORDER_CONSTANT, - const Scalar& borderValue = morphologyDefaultBorderValue()); - -/** @brief Dilates an image by using a specific structuring element. - -The function dilates the source image using the specified structuring element that determines the -shape of a pixel neighborhood over which the maximum is taken: -\f[\texttt{dst} (x,y) = \max _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f] - -Dilation can be applied several (iterations) times. In case of multi-channel images, each channel is processed independently. -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, and @ref CV_32FC1. -Output image must have the same type, size, and number of channels as the input image. -@note - - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. - - Function textual ID is "org.opencv.imgproc.filters.dilate" - -@param src input image. -@param kernel structuring element used for dilation; if elemenat=Mat(), a 3 x 3 rectangular -structuring element is used. Kernel can be created using getStructuringElement -@param anchor position of the anchor within the element; default value (-1, -1) means that the -anchor is at the element center. -@param iterations number of times dilation is applied. -@param borderType pixel extrapolation method, see cv::BorderTypes -@param borderValue border value in case of a constant border -@sa erode, morphologyEx, getStructuringElement - */ -GAPI_EXPORTS_W GMat dilate(const GMat& src, const Mat& kernel, const Point& anchor = Point(-1,-1), int iterations = 1, - int borderType = BORDER_CONSTANT, - const Scalar& borderValue = morphologyDefaultBorderValue()); - -/** @brief Dilates an image by using 3 by 3 rectangular structuring element. - -The function dilates the source image using the specified structuring element that determines the -shape of a pixel neighborhood over which the maximum is taken: -\f[\texttt{dst} (x,y) = \max _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f] - -Dilation can be applied several (iterations) times. In case of multi-channel images, each channel is processed independently. -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, and @ref CV_32FC1. -Output image must have the same type, size, and number of channels as the input image. -@note - - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. - - Function textual ID is "org.opencv.imgproc.filters.dilate" - -@param src input image. -@param iterations number of times dilation is applied. -@param borderType pixel extrapolation method, see cv::BorderTypes -@param borderValue border value in case of a constant border -@sa dilate, erode3x3 - */ - -GAPI_EXPORTS_W GMat dilate3x3(const GMat& src, int iterations = 1, - int borderType = BORDER_CONSTANT, - const Scalar& borderValue = morphologyDefaultBorderValue()); - -/** @brief Performs advanced morphological transformations. - -The function can perform advanced morphological transformations using an erosion and dilation as -basic operations. - -Any of the operations can be done in-place. In case of multi-channel images, each channel is -processed independently. - -@note - - Function textual ID is "org.opencv.imgproc.filters.morphologyEx" - - The number of iterations is the number of times erosion or dilatation operation will be -applied. For instance, an opening operation (#MORPH_OPEN) with two iterations is equivalent to -apply successively: erode -> erode -> dilate -> dilate -(and not erode -> dilate -> erode -> dilate). - -@param src Input image. -@param op Type of a morphological operation, see #MorphTypes -@param kernel Structuring element. It can be created using #getStructuringElement. -@param anchor Anchor position within the element. Both negative values mean that the anchor is at -the kernel center. -@param iterations Number of times erosion and dilation are applied. -@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. -@param borderValue Border value in case of a constant border. The default value has a special -meaning. -@sa dilate, erode, getStructuringElement - */ -GAPI_EXPORTS_W GMat morphologyEx(const GMat &src, const MorphTypes op, const Mat &kernel, - const Point &anchor = Point(-1,-1), - const int iterations = 1, - const BorderTypes borderType = BORDER_CONSTANT, - const Scalar &borderValue = morphologyDefaultBorderValue()); - -/** @brief Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator. - -In all cases except one, the \f$\texttt{ksize} \times \texttt{ksize}\f$ separable kernel is used to -calculate the derivative. When \f$\texttt{ksize = 1}\f$, the \f$3 \times 1\f$ or \f$1 \times 3\f$ -kernel is used (that is, no Gaussian smoothing is done). `ksize = 1` can only be used for the first -or the second x- or y- derivatives. - -There is also the special value `ksize = FILTER_SCHARR (-1)` that corresponds to the \f$3\times3\f$ Scharr -filter that may give more accurate results than the \f$3\times3\f$ Sobel. The Scharr aperture is - -\f[\vecthreethree{-3}{0}{3}{-10}{0}{10}{-3}{0}{3}\f] - -for the x-derivative, or transposed for the y-derivative. - -The function calculates an image derivative by convolving the image with the appropriate kernel: - -\f[\texttt{dst} = \frac{\partial^{xorder+yorder} \texttt{src}}{\partial x^{xorder} \partial y^{yorder}}\f] - -The Sobel operators combine Gaussian smoothing and differentiation, so the result is more or less -resistant to the noise. Most often, the function is called with ( xorder = 1, yorder = 0, ksize = 3) -or ( xorder = 0, yorder = 1, ksize = 3) to calculate the first x- or y- image derivative. The first -case corresponds to a kernel of: - -\f[\vecthreethree{-1}{0}{1}{-2}{0}{2}{-1}{0}{1}\f] - -The second case corresponds to a kernel of: - -\f[\vecthreethree{-1}{-2}{-1}{0}{0}{0}{1}{2}{1}\f] - -@note - - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. - - Function textual ID is "org.opencv.imgproc.filters.sobel" - -@param src input image. -@param ddepth output image depth, see @ref filter_depths "combinations"; in the case of - 8-bit input images it will result in truncated derivatives. -@param dx order of the derivative x. -@param dy order of the derivative y. -@param ksize size of the extended Sobel kernel; it must be odd. -@param scale optional scale factor for the computed derivative values; by default, no scaling is -applied (see cv::getDerivKernels for details). -@param delta optional delta value that is added to the results prior to storing them in dst. -@param borderType pixel extrapolation method, see cv::BorderTypes -@param borderValue border value in case of constant border type -@sa filter2D, gaussianBlur, cartToPolar - */ -GAPI_EXPORTS_W GMat Sobel(const GMat& src, int ddepth, int dx, int dy, int ksize = 3, - double scale = 1, double delta = 0, - int borderType = BORDER_DEFAULT, - const Scalar& borderValue = Scalar(0)); - -/** @brief Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator. - -In all cases except one, the \f$\texttt{ksize} \times \texttt{ksize}\f$ separable kernel is used to -calculate the derivative. When \f$\texttt{ksize = 1}\f$, the \f$3 \times 1\f$ or \f$1 \times 3\f$ -kernel is used (that is, no Gaussian smoothing is done). `ksize = 1` can only be used for the first -or the second x- or y- derivatives. - -There is also the special value `ksize = FILTER_SCHARR (-1)` that corresponds to the \f$3\times3\f$ Scharr -filter that may give more accurate results than the \f$3\times3\f$ Sobel. The Scharr aperture is - -\f[\vecthreethree{-3}{0}{3}{-10}{0}{10}{-3}{0}{3}\f] - -for the x-derivative, or transposed for the y-derivative. - -The function calculates an image derivative by convolving the image with the appropriate kernel: - -\f[\texttt{dst} = \frac{\partial^{xorder+yorder} \texttt{src}}{\partial x^{xorder} \partial y^{yorder}}\f] - -The Sobel operators combine Gaussian smoothing and differentiation, so the result is more or less -resistant to the noise. Most often, the function is called with ( xorder = 1, yorder = 0, ksize = 3) -or ( xorder = 0, yorder = 1, ksize = 3) to calculate the first x- or y- image derivative. The first -case corresponds to a kernel of: - -\f[\vecthreethree{-1}{0}{1}{-2}{0}{2}{-1}{0}{1}\f] - -The second case corresponds to a kernel of: - -\f[\vecthreethree{-1}{-2}{-1}{0}{0}{0}{1}{2}{1}\f] - -@note - - First returned matrix correspons to dx derivative while the second one to dy. - - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. - - Function textual ID is "org.opencv.imgproc.filters.sobelxy" - -@param src input image. -@param ddepth output image depth, see @ref filter_depths "combinations"; in the case of - 8-bit input images it will result in truncated derivatives. -@param order order of the derivatives. -@param ksize size of the extended Sobel kernel; it must be odd. -@param scale optional scale factor for the computed derivative values; by default, no scaling is -applied (see cv::getDerivKernels for details). -@param delta optional delta value that is added to the results prior to storing them in dst. -@param borderType pixel extrapolation method, see cv::BorderTypes -@param borderValue border value in case of constant border type -@sa filter2D, gaussianBlur, cartToPolar - */ -GAPI_EXPORTS_W std::tuple SobelXY(const GMat& src, int ddepth, int order, int ksize = 3, - double scale = 1, double delta = 0, - int borderType = BORDER_DEFAULT, - const Scalar& borderValue = Scalar(0)); - -/** @brief Calculates the Laplacian of an image. - -The function calculates the Laplacian of the source image by adding up the second x and y -derivatives calculated using the Sobel operator: - -\f[\texttt{dst} = \Delta \texttt{src} = \frac{\partial^2 \texttt{src}}{\partial x^2} + \frac{\partial^2 \texttt{src}}{\partial y^2}\f] - -This is done when `ksize > 1`. When `ksize == 1`, the Laplacian is computed by filtering the image -with the following \f$3 \times 3\f$ aperture: - -\f[\vecthreethree {0}{1}{0}{1}{-4}{1}{0}{1}{0}\f] - -@note Function textual ID is "org.opencv.imgproc.filters.laplacian" - -@param src Source image. -@param ddepth Desired depth of the destination image. -@param ksize Aperture size used to compute the second-derivative filters. See #getDerivKernels for -details. The size must be positive and odd. -@param scale Optional scale factor for the computed Laplacian values. By default, no scaling is -applied. See #getDerivKernels for details. -@param delta Optional delta value that is added to the results prior to storing them in dst . -@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. -@return Destination image of the same size and the same number of channels as src. -@sa Sobel, Scharr - */ -GAPI_EXPORTS_W GMat Laplacian(const GMat& src, int ddepth, int ksize = 1, - double scale = 1, double delta = 0, int borderType = BORDER_DEFAULT); - -/** @brief Applies the bilateral filter to an image. - -The function applies bilateral filtering to the input image, as described in -http://www.dai.ed.ac.uk/CVonline/LOCAL_COPIES/MANDUCHI1/Bilateral_Filtering.html -bilateralFilter can reduce unwanted noise very well while keeping edges fairly sharp. However, it is -very slow compared to most filters. - -_Sigma values_: For simplicity, you can set the 2 sigma values to be the same. If they are small (\< -10), the filter will not have much effect, whereas if they are large (\> 150), they will have a very -strong effect, making the image look "cartoonish". - -_Filter size_: Large filters (d \> 5) are very slow, so it is recommended to use d=5 for real-time -applications, and perhaps d=9 for offline applications that need heavy noise filtering. - -This filter does not work inplace. - -@note Function textual ID is "org.opencv.imgproc.filters.bilateralfilter" - -@param src Source 8-bit or floating-point, 1-channel or 3-channel image. -@param d Diameter of each pixel neighborhood that is used during filtering. If it is non-positive, -it is computed from sigmaSpace. -@param sigmaColor Filter sigma in the color space. A larger value of the parameter means that -farther colors within the pixel neighborhood (see sigmaSpace) will be mixed together, resulting -in larger areas of semi-equal color. -@param sigmaSpace Filter sigma in the coordinate space. A larger value of the parameter means that -farther pixels will influence each other as long as their colors are close enough (see sigmaColor -). When d\>0, it specifies the neighborhood size regardless of sigmaSpace. Otherwise, d is -proportional to sigmaSpace. -@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes -@return Destination image of the same size and type as src. - */ -GAPI_EXPORTS_W GMat bilateralFilter(const GMat& src, int d, double sigmaColor, double sigmaSpace, - int borderType = BORDER_DEFAULT); - -//! @} gapi_filters - -//! @addtogroup gapi_feature -//! @{ -/** @brief Finds edges in an image using the Canny algorithm. - -The function finds edges in the input image and marks them in the output map edges using the -Canny algorithm. The smallest value between threshold1 and threshold2 is used for edge linking. The -largest value is used to find initial segments of strong edges. See - - -@note Function textual ID is "org.opencv.imgproc.feature.canny" - -@param image 8-bit input image. -@param threshold1 first threshold for the hysteresis procedure. -@param threshold2 second threshold for the hysteresis procedure. -@param apertureSize aperture size for the Sobel operator. -@param L2gradient a flag, indicating whether a more accurate \f$L_2\f$ norm -\f$=\sqrt{(dI/dx)^2 + (dI/dy)^2}\f$ should be used to calculate the image gradient magnitude ( -L2gradient=true ), or whether the default \f$L_1\f$ norm \f$=|dI/dx|+|dI/dy|\f$ is enough ( -L2gradient=false ). - */ -GAPI_EXPORTS_W GMat Canny(const GMat& image, double threshold1, double threshold2, - int apertureSize = 3, bool L2gradient = false); - -/** @brief Determines strong corners on an image. - -The function finds the most prominent corners in the image or in the specified image region, as -described in @cite Shi94 - -- Function calculates the corner quality measure at every source image pixel using the - #cornerMinEigenVal or #cornerHarris . -- Function performs a non-maximum suppression (the local maximums in *3 x 3* neighborhood are - retained). -- The corners with the minimal eigenvalue less than - \f$\texttt{qualityLevel} \cdot \max_{x,y} qualityMeasureMap(x,y)\f$ are rejected. -- The remaining corners are sorted by the quality measure in the descending order. -- Function throws away each corner for which there is a stronger corner at a distance less than - maxDistance. - -The function can be used to initialize a point-based tracker of an object. - -@note - - If the function is called with different values A and B of the parameter qualityLevel , and -A \> B, the vector of returned corners with qualityLevel=A will be the prefix of the output vector -with qualityLevel=B . - - Function textual ID is "org.opencv.imgproc.feature.goodFeaturesToTrack" - -@param image Input 8-bit or floating-point 32-bit, single-channel image. -@param maxCorners Maximum number of corners to return. If there are more corners than are found, -the strongest of them is returned. `maxCorners <= 0` implies that no limit on the maximum is set -and all detected corners are returned. -@param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The -parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue -(see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the -quality measure less than the product are rejected. For example, if the best corner has the -quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure -less than 15 are rejected. -@param minDistance Minimum possible Euclidean distance between the returned corners. -@param mask Optional region of interest. If the image is not empty (it needs to have the type -CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. -@param blockSize Size of an average block for computing a derivative covariation matrix over each -pixel neighborhood. See cornerEigenValsAndVecs . -@param useHarrisDetector Parameter indicating whether to use a Harris detector (see #cornerHarris) -or #cornerMinEigenVal. -@param k Free parameter of the Harris detector. - -@return vector of detected corners. - */ -GAPI_EXPORTS_W GArray goodFeaturesToTrack(const GMat &image, - int maxCorners, - double qualityLevel, - double minDistance, - const Mat &mask = Mat(), - int blockSize = 3, - bool useHarrisDetector = false, - double k = 0.04); - -/** @brief Equalizes the histogram of a grayscale image. - -//! @} gapi_feature - -The function equalizes the histogram of the input image using the following algorithm: - -- Calculate the histogram \f$H\f$ for src . -- Normalize the histogram so that the sum of histogram bins is 255. -- Compute the integral of the histogram: -\f[H'_i = \sum _{0 \le j < i} H(j)\f] -- Transform the image using \f$H'\f$ as a look-up table: \f$\texttt{dst}(x,y) = H'(\texttt{src}(x,y))\f$ - -The algorithm normalizes the brightness and increases the contrast of the image. -@note - - The returned image is of the same size and type as input. - - Function textual ID is "org.opencv.imgproc.equalizeHist" - -@param src Source 8-bit single channel image. - */ -GAPI_EXPORTS_W GMat equalizeHist(const GMat& src); - -//! @addtogroup gapi_shape -//! @{ -/** @brief Finds contours in a binary image. - -The function retrieves contours from the binary image using the algorithm @cite Suzuki85 . -The contours are a useful tool for shape analysis and object detection and recognition. -See squares.cpp in the OpenCV sample directory. - -@note Function textual ID is "org.opencv.imgproc.shape.findContours" - -@param src Input gray-scale image @ref CV_8UC1. Non-zero pixels are treated as 1's. Zero -pixels remain 0's, so the image is treated as binary . You can use #compare, #inRange, #threshold , -#adaptiveThreshold, #Canny, and others to create a binary image out of a grayscale or color one. -If mode equals to #RETR_CCOMP, the input can also be a 32-bit integer -image of labels ( @ref CV_32SC1 ). If #RETR_FLOODFILL then @ref CV_32SC1 is supported only. -@param mode Contour retrieval mode, see #RetrievalModes -@param method Contour approximation method, see #ContourApproximationModes -@param offset Optional offset by which every contour point is shifted. This is useful if the -contours are extracted from the image ROI and then they should be analyzed in the whole image -context. - -@return GArray of detected contours. Each contour is stored as a GArray of points. - */ -GAPI_EXPORTS GArray> -findContours(const GMat &src, const RetrievalModes mode, const ContourApproximationModes method, - const GOpaque &offset); - -// FIXME oc: make default value offset = Point() -/** @overload -@note Function textual ID is "org.opencv.imgproc.shape.findContoursNoOffset" - */ -GAPI_EXPORTS GArray> -findContours(const GMat &src, const RetrievalModes mode, const ContourApproximationModes method); - -/** @brief Finds contours and their hierarchy in a binary image. - -The function retrieves contours from the binary image using the algorithm @cite Suzuki85 -and calculates their hierarchy. -The contours are a useful tool for shape analysis and object detection and recognition. -See squares.cpp in the OpenCV sample directory. - -@note Function textual ID is "org.opencv.imgproc.shape.findContoursH" - -@param src Input gray-scale image @ref CV_8UC1. Non-zero pixels are treated as 1's. Zero -pixels remain 0's, so the image is treated as binary . You can use #compare, #inRange, #threshold , -#adaptiveThreshold, #Canny, and others to create a binary image out of a grayscale or color one. -If mode equals to #RETR_CCOMP, the input can also be a 32-bit integer -image of labels ( @ref CV_32SC1 ). If #RETR_FLOODFILL -- @ref CV_32SC1 supports only. -@param mode Contour retrieval mode, see #RetrievalModes -@param method Contour approximation method, see #ContourApproximationModes -@param offset Optional offset by which every contour point is shifted. This is useful if the -contours are extracted from the image ROI and then they should be analyzed in the whole image -context. - -@return - - GArray of detected contours. Each contour is stored as a GArray of points. - - Optional output GArray of cv::Vec4i, containing information about the image topology. -It has as many elements as the number of contours. For each i-th contour contours[i], the elements -hierarchy[i][0] , hierarchy[i][1] , hierarchy[i][2] , and hierarchy[i][3] are set to 0-based -indices in contours of the next and previous contours at the same hierarchical level, the first -child contour and the parent contour, respectively. If for the contour i there are no next, -previous, parent, or nested contours, the corresponding elements of hierarchy[i] will be negative. - */ -GAPI_EXPORTS std::tuple>,GArray> -findContoursH(const GMat &src, const RetrievalModes mode, const ContourApproximationModes method, - const GOpaque &offset); - -// FIXME oc: make default value offset = Point() -/** @overload -@note Function textual ID is "org.opencv.imgproc.shape.findContoursHNoOffset" - */ -GAPI_EXPORTS std::tuple>,GArray> -findContoursH(const GMat &src, const RetrievalModes mode, const ContourApproximationModes method); - -/** @brief Calculates the up-right bounding rectangle of a point set or non-zero pixels -of gray-scale image. - -The function calculates and returns the minimal up-right bounding rectangle for the specified -point set or non-zero pixels of gray-scale image. - -@note - - Function textual ID is "org.opencv.imgproc.shape.boundingRectMat" - - In case of a 2D points' set given, Mat should be 2-dimensional, have a single row or column -if there are 2 channels, or have 2 columns if there is a single channel. Mat should have either -@ref CV_32S or @ref CV_32F depth - -@param src Input gray-scale image @ref CV_8UC1; or input set of @ref CV_32S or @ref CV_32F -2D points stored in Mat. - */ -GAPI_EXPORTS_W GOpaque boundingRect(const GMat& src); - -/** @overload - -Calculates the up-right bounding rectangle of a point set. - -@note Function textual ID is "org.opencv.imgproc.shape.boundingRectVector32S" - -@param src Input 2D point set, stored in std::vector. - */ -GAPI_EXPORTS_W GOpaque boundingRect(const GArray& src); - -/** @overload - -Calculates the up-right bounding rectangle of a point set. - -@note Function textual ID is "org.opencv.imgproc.shape.boundingRectVector32F" - -@param src Input 2D point set, stored in std::vector. - */ -GAPI_EXPORTS_W GOpaque boundingRect(const GArray& src); - -/** @brief Fits a line to a 2D point set. - -The function fits a line to a 2D point set by minimizing \f$\sum_i \rho(r_i)\f$ where -\f$r_i\f$ is a distance between the \f$i^{th}\f$ point, the line and \f$\rho(r)\f$ is a distance -function, one of the following: -- DIST_L2 -\f[\rho (r) = r^2/2 \quad \text{(the simplest and the fastest least-squares method)}\f] -- DIST_L1 -\f[\rho (r) = r\f] -- DIST_L12 -\f[\rho (r) = 2 \cdot ( \sqrt{1 + \frac{r^2}{2}} - 1)\f] -- DIST_FAIR -\f[\rho \left (r \right ) = C^2 \cdot \left ( \frac{r}{C} - \log{\left(1 + \frac{r}{C}\right)} \right ) \quad \text{where} \quad C=1.3998\f] -- DIST_WELSCH -\f[\rho \left (r \right ) = \frac{C^2}{2} \cdot \left ( 1 - \exp{\left(-\left(\frac{r}{C}\right)^2\right)} \right ) \quad \text{where} \quad C=2.9846\f] -- DIST_HUBER -\f[\rho (r) = \fork{r^2/2}{if \(r < C\)}{C \cdot (r-C/2)}{otherwise} \quad \text{where} \quad C=1.345\f] - -The algorithm is based on the M-estimator ( ) technique -that iteratively fits the line using the weighted least-squares algorithm. After each iteration the -weights \f$w_i\f$ are adjusted to be inversely proportional to \f$\rho(r_i)\f$ . - -@note - - Function textual ID is "org.opencv.imgproc.shape.fitLine2DMat" - - In case of an N-dimentional points' set given, Mat should be 2-dimensional, have a single row -or column if there are N channels, or have N columns if there is a single channel. - -@param src Input set of 2D points stored in one of possible containers: Mat, -std::vector, std::vector, std::vector. -@param distType Distance used by the M-estimator, see #DistanceTypes. @ref DIST_USER -and @ref DIST_C are not supported. -@param param Numerical parameter ( C ) for some types of distances. If it is 0, an optimal value -is chosen. -@param reps Sufficient accuracy for the radius (distance between the coordinate origin and the -line). 1.0 would be a good default value for reps. If it is 0, a default value is chosen. -@param aeps Sufficient accuracy for the angle. 0.01 would be a good default value for aeps. -If it is 0, a default value is chosen. - -@return Output line parameters: a vector of 4 elements (like Vec4f) - (vx, vy, x0, y0), -where (vx, vy) is a normalized vector collinear to the line and (x0, y0) is a point on the line. - */ -GAPI_EXPORTS GOpaque fitLine2D(const GMat& src, const DistanceTypes distType, - const double param = 0., const double reps = 0., - const double aeps = 0.); - -/** @overload - -@note Function textual ID is "org.opencv.imgproc.shape.fitLine2DVector32S" - - */ -GAPI_EXPORTS GOpaque fitLine2D(const GArray& src, const DistanceTypes distType, - const double param = 0., const double reps = 0., - const double aeps = 0.); - -/** @overload - -@note Function textual ID is "org.opencv.imgproc.shape.fitLine2DVector32F" - - */ -GAPI_EXPORTS GOpaque fitLine2D(const GArray& src, const DistanceTypes distType, - const double param = 0., const double reps = 0., - const double aeps = 0.); - -/** @overload - -@note Function textual ID is "org.opencv.imgproc.shape.fitLine2DVector64F" - - */ -GAPI_EXPORTS GOpaque fitLine2D(const GArray& src, const DistanceTypes distType, - const double param = 0., const double reps = 0., - const double aeps = 0.); - -/** @brief Fits a line to a 3D point set. - -The function fits a line to a 3D point set by minimizing \f$\sum_i \rho(r_i)\f$ where -\f$r_i\f$ is a distance between the \f$i^{th}\f$ point, the line and \f$\rho(r)\f$ is a distance -function, one of the following: -- DIST_L2 -\f[\rho (r) = r^2/2 \quad \text{(the simplest and the fastest least-squares method)}\f] -- DIST_L1 -\f[\rho (r) = r\f] -- DIST_L12 -\f[\rho (r) = 2 \cdot ( \sqrt{1 + \frac{r^2}{2}} - 1)\f] -- DIST_FAIR -\f[\rho \left (r \right ) = C^2 \cdot \left ( \frac{r}{C} - \log{\left(1 + \frac{r}{C}\right)} \right ) \quad \text{where} \quad C=1.3998\f] -- DIST_WELSCH -\f[\rho \left (r \right ) = \frac{C^2}{2} \cdot \left ( 1 - \exp{\left(-\left(\frac{r}{C}\right)^2\right)} \right ) \quad \text{where} \quad C=2.9846\f] -- DIST_HUBER -\f[\rho (r) = \fork{r^2/2}{if \(r < C\)}{C \cdot (r-C/2)}{otherwise} \quad \text{where} \quad C=1.345\f] - -The algorithm is based on the M-estimator ( ) technique -that iteratively fits the line using the weighted least-squares algorithm. After each iteration the -weights \f$w_i\f$ are adjusted to be inversely proportional to \f$\rho(r_i)\f$ . - -@note - - Function textual ID is "org.opencv.imgproc.shape.fitLine3DMat" - - In case of an N-dimentional points' set given, Mat should be 2-dimensional, have a single row -or column if there are N channels, or have N columns if there is a single channel. - -@param src Input set of 3D points stored in one of possible containers: Mat, -std::vector, std::vector, std::vector. -@param distType Distance used by the M-estimator, see #DistanceTypes. @ref DIST_USER -and @ref DIST_C are not supported. -@param param Numerical parameter ( C ) for some types of distances. If it is 0, an optimal value -is chosen. -@param reps Sufficient accuracy for the radius (distance between the coordinate origin and the -line). 1.0 would be a good default value for reps. If it is 0, a default value is chosen. -@param aeps Sufficient accuracy for the angle. 0.01 would be a good default value for aeps. -If it is 0, a default value is chosen. - -@return Output line parameters: a vector of 6 elements (like Vec6f) - (vx, vy, vz, x0, y0, z0), -where (vx, vy, vz) is a normalized vector collinear to the line and (x0, y0, z0) is a point on -the line. - */ -GAPI_EXPORTS GOpaque fitLine3D(const GMat& src, const DistanceTypes distType, - const double param = 0., const double reps = 0., - const double aeps = 0.); - -/** @overload - -@note Function textual ID is "org.opencv.imgproc.shape.fitLine3DVector32S" - - */ -GAPI_EXPORTS GOpaque fitLine3D(const GArray& src, const DistanceTypes distType, - const double param = 0., const double reps = 0., - const double aeps = 0.); - -/** @overload - -@note Function textual ID is "org.opencv.imgproc.shape.fitLine3DVector32F" - - */ -GAPI_EXPORTS GOpaque fitLine3D(const GArray& src, const DistanceTypes distType, - const double param = 0., const double reps = 0., - const double aeps = 0.); - -/** @overload - -@note Function textual ID is "org.opencv.imgproc.shape.fitLine3DVector64F" - - */ -GAPI_EXPORTS GOpaque fitLine3D(const GArray& src, const DistanceTypes distType, - const double param = 0., const double reps = 0., - const double aeps = 0.); - -//! @} gapi_shape - -//! @addtogroup gapi_colorconvert -//! @{ -/** @brief Converts an image from BGR color space to RGB color space. - -The function converts an input image from BGR color space to RGB. -The conventional ranges for B, G, and R channel values are 0 to 255. - -Output image is 8-bit unsigned 3-channel image @ref CV_8UC3. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.bgr2rgb" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. -@sa RGB2BGR -*/ -GAPI_EXPORTS_W GMat BGR2RGB(const GMat& src); - -/** @brief Converts an image from RGB color space to gray-scaled. - -The conventional ranges for R, G, and B channel values are 0 to 255. -Resulting gray color value computed as -\f[\texttt{dst} (I)= \texttt{0.299} * \texttt{src}(I).R + \texttt{0.587} * \texttt{src}(I).G + \texttt{0.114} * \texttt{src}(I).B \f] - -@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2gray" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC1. -@sa RGB2YUV - */ -GAPI_EXPORTS_W GMat RGB2Gray(const GMat& src); - -/** @overload -Resulting gray color value computed as -\f[\texttt{dst} (I)= \texttt{rY} * \texttt{src}(I).R + \texttt{gY} * \texttt{src}(I).G + \texttt{bY} * \texttt{src}(I).B \f] - -@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2graycustom" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC1. -@param rY float multiplier for R channel. -@param gY float multiplier for G channel. -@param bY float multiplier for B channel. -@sa RGB2YUV - */ -GAPI_EXPORTS_W GMat RGB2Gray(const GMat& src, float rY, float gY, float bY); - -/** @brief Converts an image from BGR color space to gray-scaled. - -The conventional ranges for B, G, and R channel values are 0 to 255. -Resulting gray color value computed as -\f[\texttt{dst} (I)= \texttt{0.114} * \texttt{src}(I).B + \texttt{0.587} * \texttt{src}(I).G + \texttt{0.299} * \texttt{src}(I).R \f] - -@note Function textual ID is "org.opencv.imgproc.colorconvert.bgr2gray" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC1. -@sa BGR2LUV - */ -GAPI_EXPORTS_W GMat BGR2Gray(const GMat& src); - -/** @brief Converts an image from RGB color space to YUV color space. - -The function converts an input image from RGB color space to YUV. -The conventional ranges for R, G, and B channel values are 0 to 255. - -In case of linear transformations, the range does not matter. But in case of a non-linear -transformation, an input RGB image should be normalized to the proper value range to get the correct -results, like here, at RGB \f$\rightarrow\f$ Y\*u\*v\* transformation. -Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2yuv" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. -@sa YUV2RGB, RGB2Lab -*/ -GAPI_EXPORTS_W GMat RGB2YUV(const GMat& src); - -/** @brief Converts an image from BGR color space to I420 color space. - -The function converts an input image from BGR color space to I420. -The conventional ranges for R, G, and B channel values are 0 to 255. - -Output image must be 8-bit unsigned 1-channel image. @ref CV_8UC1. -Width of I420 output image must be the same as width of input image. -Height of I420 output image must be equal 3/2 from height of input image. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.bgr2i420" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. -@sa I4202BGR -*/ -GAPI_EXPORTS_W GMat BGR2I420(const GMat& src); - -/** @brief Converts an image from RGB color space to I420 color space. - -The function converts an input image from RGB color space to I420. -The conventional ranges for R, G, and B channel values are 0 to 255. - -Output image must be 8-bit unsigned 1-channel image. @ref CV_8UC1. -Width of I420 output image must be the same as width of input image. -Height of I420 output image must be equal 3/2 from height of input image. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2i420" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. -@sa I4202RGB -*/ -GAPI_EXPORTS_W GMat RGB2I420(const GMat& src); - -/** @brief Converts an image from I420 color space to BGR color space. - -The function converts an input image from I420 color space to BGR. -The conventional ranges for B, G, and R channel values are 0 to 255. - -Output image must be 8-bit unsigned 3-channel image. @ref CV_8UC3. -Width of BGR output image must be the same as width of input image. -Height of BGR output image must be equal 2/3 from height of input image. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.i4202bgr" - -@param src input image: 8-bit unsigned 1-channel image @ref CV_8UC1. -@sa BGR2I420 -*/ -GAPI_EXPORTS_W GMat I4202BGR(const GMat& src); - -/** @brief Converts an image from I420 color space to BGR color space. - -The function converts an input image from I420 color space to BGR. -The conventional ranges for B, G, and R channel values are 0 to 255. - -Output image must be 8-bit unsigned 3-channel image. @ref CV_8UC3. -Width of RGB output image must be the same as width of input image. -Height of RGB output image must be equal 2/3 from height of input image. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.i4202rgb" - -@param src input image: 8-bit unsigned 1-channel image @ref CV_8UC1. -@sa RGB2I420 -*/ -GAPI_EXPORTS_W GMat I4202RGB(const GMat& src); - -/** @brief Converts an image from BGR color space to LUV color space. - -The function converts an input image from BGR color space to LUV. -The conventional ranges for B, G, and R channel values are 0 to 255. - -Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.bgr2luv" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. -@sa RGB2Lab, RGB2LUV -*/ -GAPI_EXPORTS_W GMat BGR2LUV(const GMat& src); - -/** @brief Converts an image from LUV color space to BGR color space. - -The function converts an input image from LUV color space to BGR. -The conventional ranges for B, G, and R channel values are 0 to 255. - -Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.luv2bgr" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. -@sa BGR2LUV -*/ -GAPI_EXPORTS_W GMat LUV2BGR(const GMat& src); - -/** @brief Converts an image from YUV color space to BGR color space. - -The function converts an input image from YUV color space to BGR. -The conventional ranges for B, G, and R channel values are 0 to 255. - -Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.yuv2bgr" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. -@sa BGR2YUV -*/ -GAPI_EXPORTS_W GMat YUV2BGR(const GMat& src); - -/** @brief Converts an image from BGR color space to YUV color space. - -The function converts an input image from BGR color space to YUV. -The conventional ranges for B, G, and R channel values are 0 to 255. - -Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.bgr2yuv" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. -@sa YUV2BGR -*/ -GAPI_EXPORTS_W GMat BGR2YUV(const GMat& src); - -/** @brief Converts an image from RGB color space to Lab color space. - -The function converts an input image from BGR color space to Lab. -The conventional ranges for R, G, and B channel values are 0 to 255. - -Output image must be 8-bit unsigned 3-channel image @ref CV_8UC1. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2lab" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC1. -@sa RGB2YUV, RGB2LUV -*/ -GAPI_EXPORTS_W GMat RGB2Lab(const GMat& src); - -/** @brief Converts an image from YUV color space to RGB. -The function converts an input image from YUV color space to RGB. -The conventional ranges for Y, U, and V channel values are 0 to 255. - -Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.yuv2rgb" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. - -@sa RGB2Lab, RGB2YUV -*/ -GAPI_EXPORTS_W GMat YUV2RGB(const GMat& src); - -/** @brief Converts an image from NV12 (YUV420p) color space to RGB. -The function converts an input image from NV12 color space to RGB. -The conventional ranges for Y, U, and V channel values are 0 to 255. - -Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.nv12torgb" - -@param src_y input image: 8-bit unsigned 1-channel image @ref CV_8UC1. -@param src_uv input image: 8-bit unsigned 2-channel image @ref CV_8UC2. - -@sa YUV2RGB, NV12toBGR -*/ -GAPI_EXPORTS_W GMat NV12toRGB(const GMat& src_y, const GMat& src_uv); - -/** @brief Converts an image from NV12 (YUV420p) color space to gray-scaled. -The function converts an input image from NV12 color space to gray-scaled. -The conventional ranges for Y, U, and V channel values are 0 to 255. - -Output image must be 8-bit unsigned 1-channel image @ref CV_8UC1. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.nv12togray" - -@param src_y input image: 8-bit unsigned 1-channel image @ref CV_8UC1. -@param src_uv input image: 8-bit unsigned 2-channel image @ref CV_8UC2. - -@sa YUV2RGB, NV12toBGR -*/ -GAPI_EXPORTS_W GMat NV12toGray(const GMat& src_y, const GMat& src_uv); - -/** @brief Converts an image from NV12 (YUV420p) color space to BGR. -The function converts an input image from NV12 color space to RGB. -The conventional ranges for Y, U, and V channel values are 0 to 255. - -Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.nv12tobgr" - -@param src_y input image: 8-bit unsigned 1-channel image @ref CV_8UC1. -@param src_uv input image: 8-bit unsigned 2-channel image @ref CV_8UC2. - -@sa YUV2BGR, NV12toRGB -*/ -GAPI_EXPORTS_W GMat NV12toBGR(const GMat& src_y, const GMat& src_uv); - -/** @brief Converts an image from BayerGR color space to RGB. -The function converts an input image from BayerGR color space to RGB. -The conventional ranges for G, R, and B channel values are 0 to 255. - -Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.bayergr2rgb" - -@param src_gr input image: 8-bit unsigned 1-channel image @ref CV_8UC1. - -@sa YUV2BGR, NV12toRGB -*/ -GAPI_EXPORTS_W GMat BayerGR2RGB(const GMat& src_gr); - -/** @brief Converts an image from RGB color space to HSV. -The function converts an input image from RGB color space to HSV. -The conventional ranges for R, G, and B channel values are 0 to 255. - -Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2hsv" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. - -@sa YUV2BGR, NV12toRGB -*/ -GAPI_EXPORTS_W GMat RGB2HSV(const GMat& src); - -/** @brief Converts an image from RGB color space to YUV422. -The function converts an input image from RGB color space to YUV422. -The conventional ranges for R, G, and B channel values are 0 to 255. - -Output image must be 8-bit unsigned 2-channel image @ref CV_8UC2. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2yuv422" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. - -@sa YUV2BGR, NV12toRGB -*/ -GAPI_EXPORTS_W GMat RGB2YUV422(const GMat& src); - -/** @brief Converts an image from NV12 (YUV420p) color space to RGB. -The function converts an input image from NV12 color space to RGB. -The conventional ranges for Y, U, and V channel values are 0 to 255. - -Output image must be 8-bit unsigned planar 3-channel image @ref CV_8UC1. -Planar image memory layout is three planes laying in the memory contiguously, -so the image height should be plane_height*plane_number, -image type is @ref CV_8UC1. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.nv12torgbp" - -@param src_y input image: 8-bit unsigned 1-channel image @ref CV_8UC1. -@param src_uv input image: 8-bit unsigned 2-channel image @ref CV_8UC2. - -@sa YUV2RGB, NV12toBGRp, NV12toRGB -*/ -GAPI_EXPORTS GMatP NV12toRGBp(const GMat &src_y, const GMat &src_uv); - -/** @brief Converts an image from NV12 (YUV420p) color space to BGR. -The function converts an input image from NV12 color space to BGR. -The conventional ranges for Y, U, and V channel values are 0 to 255. - -Output image must be 8-bit unsigned planar 3-channel image @ref CV_8UC1. -Planar image memory layout is three planes laying in the memory contiguously, -so the image height should be plane_height*plane_number, -image type is @ref CV_8UC1. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.nv12torgbp" - -@param src_y input image: 8-bit unsigned 1-channel image @ref CV_8UC1. -@param src_uv input image: 8-bit unsigned 2-channel image @ref CV_8UC2. - -@sa YUV2RGB, NV12toRGBp, NV12toBGR -*/ -GAPI_EXPORTS GMatP NV12toBGRp(const GMat &src_y, const GMat &src_uv); - -//! @} gapi_colorconvert -//! @addtogroup gapi_transform -//! @{ -/** @brief Resizes an image. - -The function resizes the image src down to or up to the specified size. - -Output image size will have the size dsize (when dsize is non-zero) or the size computed from -src.size(), fx, and fy; the depth of output is the same as of src. - -If you want to resize src so that it fits the pre-created dst, -you may call the function as follows: -@code - // explicitly specify dsize=dst.size(); fx and fy will be computed from that. - resize(src, dst, dst.size(), 0, 0, interpolation); -@endcode -If you want to decimate the image by factor of 2 in each direction, you can call the function this -way: -@code - // specify fx and fy and let the function compute the destination image size. - resize(src, dst, Size(), 0.5, 0.5, interpolation); -@endcode -To shrink an image, it will generally look best with cv::INTER_AREA interpolation, whereas to -enlarge an image, it will generally look best with cv::INTER_CUBIC (slow) or cv::INTER_LINEAR -(faster but still looks OK). - -@note Function textual ID is "org.opencv.imgproc.transform.resize" - -@param src input image. -@param dsize output image size; if it equals zero, it is computed as: - \f[\texttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}\f] - Either dsize or both fx and fy must be non-zero. -@param fx scale factor along the horizontal axis; when it equals 0, it is computed as -\f[\texttt{(double)dsize.width/src.cols}\f] -@param fy scale factor along the vertical axis; when it equals 0, it is computed as -\f[\texttt{(double)dsize.height/src.rows}\f] -@param interpolation interpolation method, see cv::InterpolationFlags - -@sa warpAffine, warpPerspective, remap, resizeP - */ -GAPI_EXPORTS_W GMat resize(const GMat& src, const Size& dsize, double fx = 0, double fy = 0, int interpolation = INTER_LINEAR); - -/** @brief Resizes a planar image. - -The function resizes the image src down to or up to the specified size. -Planar image memory layout is three planes laying in the memory contiguously, -so the image height should be plane_height*plane_number, image type is @ref CV_8UC1. - -Output image size will have the size dsize, the depth of output is the same as of src. - -@note Function textual ID is "org.opencv.imgproc.transform.resizeP" - -@param src input image, must be of @ref CV_8UC1 type; -@param dsize output image size; -@param interpolation interpolation method, only cv::INTER_LINEAR is supported at the moment - -@sa warpAffine, warpPerspective, remap, resize - */ -GAPI_EXPORTS GMatP resizeP(const GMatP& src, const Size& dsize, int interpolation = cv::INTER_LINEAR); - -//! @} gapi_transform -} //namespace gapi -} //namespace cv - -#endif // OPENCV_GAPI_IMGPROC_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2020 Intel Corporation + + +#ifndef OPENCV_GAPI_IMGPROC_HPP +#define OPENCV_GAPI_IMGPROC_HPP + +#include + +#include // std::tuple + +#include +#include +#include + + +/** \defgroup gapi_imgproc G-API Image processing functionality +@{ + @defgroup gapi_filters Graph API: Image filters + @defgroup gapi_colorconvert Graph API: Converting image from one color space to another + @defgroup gapi_feature Graph API: Image Feature Detection + @defgroup gapi_shape Graph API: Image Structural Analysis and Shape Descriptors + @defgroup gapi_transform Graph API: Image and channel composition functions +@} + */ + +namespace { +void validateFindingContoursMeta(const int depth, const int chan, const int mode) +{ + GAPI_Assert(chan == 1); + switch (mode) + { + case cv::RETR_CCOMP: + GAPI_Assert(depth == CV_8U || depth == CV_32S); + break; + case cv::RETR_FLOODFILL: + GAPI_Assert(depth == CV_32S); + break; + default: + GAPI_Assert(depth == CV_8U); + break; + } +} +} // anonymous namespace + +namespace cv { namespace gapi { + +/** + * @brief This namespace contains G-API Operation Types for OpenCV + * ImgProc module functionality. + */ +namespace imgproc { + using GMat2 = std::tuple; + using GMat3 = std::tuple; // FIXME: how to avoid this? + using GFindContoursOutput = std::tuple>,GArray>; + + G_TYPED_KERNEL(GFilter2D, , "org.opencv.imgproc.filters.filter2D") { + static GMatDesc outMeta(GMatDesc in, int ddepth, Mat, Point, Scalar, int, Scalar) { + return in.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GSepFilter, , "org.opencv.imgproc.filters.sepfilter") { + static GMatDesc outMeta(GMatDesc in, int ddepth, Mat, Mat, Point, Scalar, int, Scalar) { + return in.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GBoxFilter, , "org.opencv.imgproc.filters.boxfilter") { + static GMatDesc outMeta(GMatDesc in, int ddepth, Size, Point, bool, int, Scalar) { + return in.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GBlur, , "org.opencv.imgproc.filters.blur") { + static GMatDesc outMeta(GMatDesc in, Size, Point, int, Scalar) { + return in; + } + }; + + G_TYPED_KERNEL(GGaussBlur, , "org.opencv.imgproc.filters.gaussianBlur") { + static GMatDesc outMeta(GMatDesc in, Size, double, double, int, Scalar) { + return in; + } + }; + + G_TYPED_KERNEL(GMedianBlur, , "org.opencv.imgproc.filters.medianBlur") { + static GMatDesc outMeta(GMatDesc in, int) { + return in; + } + }; + + G_TYPED_KERNEL(GErode, , "org.opencv.imgproc.filters.erode") { + static GMatDesc outMeta(GMatDesc in, Mat, Point, int, int, Scalar) { + return in; + } + }; + + G_TYPED_KERNEL(GDilate, , "org.opencv.imgproc.filters.dilate") { + static GMatDesc outMeta(GMatDesc in, Mat, Point, int, int, Scalar) { + return in; + } + }; + + G_TYPED_KERNEL(GMorphologyEx, , + "org.opencv.imgproc.filters.morphologyEx") { + static GMatDesc outMeta(const GMatDesc &in, MorphTypes, Mat, Point, int, + BorderTypes, Scalar) { + return in; + } + }; + + G_TYPED_KERNEL(GSobel, , "org.opencv.imgproc.filters.sobel") { + static GMatDesc outMeta(GMatDesc in, int ddepth, int, int, int, double, double, int, Scalar) { + return in.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL_M(GSobelXY, , "org.opencv.imgproc.filters.sobelxy") { + static std::tuple outMeta(GMatDesc in, int ddepth, int, int, double, double, int, Scalar) { + return std::make_tuple(in.withDepth(ddepth), in.withDepth(ddepth)); + } + }; + + G_TYPED_KERNEL(GLaplacian, , + "org.opencv.imgproc.filters.laplacian") { + static GMatDesc outMeta(GMatDesc in, int ddepth, int, double, double, int) { + return in.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GBilateralFilter, , + "org.opencv.imgproc.filters.bilateralfilter") { + static GMatDesc outMeta(GMatDesc in, int, double, double, int) { + return in; + } + }; + + G_TYPED_KERNEL(GEqHist, , "org.opencv.imgproc.equalizeHist") { + static GMatDesc outMeta(GMatDesc in) { + return in.withType(CV_8U, 1); + } + }; + + G_TYPED_KERNEL(GCanny, , "org.opencv.imgproc.feature.canny") { + static GMatDesc outMeta(GMatDesc in, double, double, int, bool) { + return in.withType(CV_8U, 1); + } + }; + + G_TYPED_KERNEL(GGoodFeatures, + (GMat,int,double,double,Mat,int,bool,double)>, + "org.opencv.imgproc.feature.goodFeaturesToTrack") { + static GArrayDesc outMeta(GMatDesc, int, double, double, const Mat&, int, bool, double) { + return empty_array_desc(); + } + }; + + using RetrMode = RetrievalModes; + using ContMethod = ContourApproximationModes; + G_TYPED_KERNEL(GFindContours, >(GMat,RetrMode,ContMethod,GOpaque)>, + "org.opencv.imgproc.shape.findContours") + { + static GArrayDesc outMeta(GMatDesc in, RetrMode mode, ContMethod, GOpaqueDesc) + { + validateFindingContoursMeta(in.depth, in.chan, mode); + return empty_array_desc(); + } + }; + + // FIXME oc: make default value offset = Point() + G_TYPED_KERNEL(GFindContoursNoOffset, >(GMat,RetrMode,ContMethod)>, + "org.opencv.imgproc.shape.findContoursNoOffset") + { + static GArrayDesc outMeta(GMatDesc in, RetrMode mode, ContMethod) + { + validateFindingContoursMeta(in.depth, in.chan, mode); + return empty_array_desc(); + } + }; + + G_TYPED_KERNEL(GFindContoursH,)>, + "org.opencv.imgproc.shape.findContoursH") + { + static std::tuple + outMeta(GMatDesc in, RetrMode mode, ContMethod, GOpaqueDesc) + { + validateFindingContoursMeta(in.depth, in.chan, mode); + return std::make_tuple(empty_array_desc(), empty_array_desc()); + } + }; + + // FIXME oc: make default value offset = Point() + G_TYPED_KERNEL(GFindContoursHNoOffset,, + "org.opencv.imgproc.shape.findContoursHNoOffset") + { + static std::tuple + outMeta(GMatDesc in, RetrMode mode, ContMethod) + { + validateFindingContoursMeta(in.depth, in.chan, mode); + return std::make_tuple(empty_array_desc(), empty_array_desc()); + } + }; + + G_TYPED_KERNEL(GBoundingRectMat, (GMat)>, + "org.opencv.imgproc.shape.boundingRectMat") { + static GOpaqueDesc outMeta(GMatDesc in) { + if (in.depth == CV_8U) + { + GAPI_Assert(in.chan == 1); + } + else + { + GAPI_Assert (in.depth == CV_32S || in.depth == CV_32F); + int amount = detail::checkVector(in, 2u); + GAPI_Assert(amount != -1 && + "Input Mat can't be described as vector of 2-dimentional points"); + } + return empty_gopaque_desc(); + } + }; + + G_TYPED_KERNEL(GBoundingRectVector32S, (GArray)>, + "org.opencv.imgproc.shape.boundingRectVector32S") { + static GOpaqueDesc outMeta(GArrayDesc) { + return empty_gopaque_desc(); + } + }; + + G_TYPED_KERNEL(GBoundingRectVector32F, (GArray)>, + "org.opencv.imgproc.shape.boundingRectVector32F") { + static GOpaqueDesc outMeta(GArrayDesc) { + return empty_gopaque_desc(); + } + }; + + G_TYPED_KERNEL(GFitLine2DMat, (GMat,DistanceTypes,double,double,double)>, + "org.opencv.imgproc.shape.fitLine2DMat") { + static GOpaqueDesc outMeta(GMatDesc in,DistanceTypes,double,double,double) { + int amount = detail::checkVector(in, 2u); + GAPI_Assert(amount != -1 && + "Input Mat can't be described as vector of 2-dimentional points"); + return empty_gopaque_desc(); + } + }; + + G_TYPED_KERNEL(GFitLine2DVector32S, + (GArray,DistanceTypes,double,double,double)>, + "org.opencv.imgproc.shape.fitLine2DVector32S") { + static GOpaqueDesc outMeta(GArrayDesc,DistanceTypes,double,double,double) { + return empty_gopaque_desc(); + } + }; + + G_TYPED_KERNEL(GFitLine2DVector32F, + (GArray,DistanceTypes,double,double,double)>, + "org.opencv.imgproc.shape.fitLine2DVector32F") { + static GOpaqueDesc outMeta(GArrayDesc,DistanceTypes,double,double,double) { + return empty_gopaque_desc(); + } + }; + + G_TYPED_KERNEL(GFitLine2DVector64F, + (GArray,DistanceTypes,double,double,double)>, + "org.opencv.imgproc.shape.fitLine2DVector64F") { + static GOpaqueDesc outMeta(GArrayDesc,DistanceTypes,double,double,double) { + return empty_gopaque_desc(); + } + }; + + G_TYPED_KERNEL(GFitLine3DMat, (GMat,DistanceTypes,double,double,double)>, + "org.opencv.imgproc.shape.fitLine3DMat") { + static GOpaqueDesc outMeta(GMatDesc in,int,double,double,double) { + int amount = detail::checkVector(in, 3u); + GAPI_Assert(amount != -1 && + "Input Mat can't be described as vector of 3-dimentional points"); + return empty_gopaque_desc(); + } + }; + + G_TYPED_KERNEL(GFitLine3DVector32S, + (GArray,DistanceTypes,double,double,double)>, + "org.opencv.imgproc.shape.fitLine3DVector32S") { + static GOpaqueDesc outMeta(GArrayDesc,DistanceTypes,double,double,double) { + return empty_gopaque_desc(); + } + }; + + G_TYPED_KERNEL(GFitLine3DVector32F, + (GArray,DistanceTypes,double,double,double)>, + "org.opencv.imgproc.shape.fitLine3DVector32F") { + static GOpaqueDesc outMeta(GArrayDesc,DistanceTypes,double,double,double) { + return empty_gopaque_desc(); + } + }; + + G_TYPED_KERNEL(GFitLine3DVector64F, + (GArray,DistanceTypes,double,double,double)>, + "org.opencv.imgproc.shape.fitLine3DVector64F") { + static GOpaqueDesc outMeta(GArrayDesc,DistanceTypes,double,double,double) { + return empty_gopaque_desc(); + } + }; + + G_TYPED_KERNEL(GBGR2RGB, , "org.opencv.imgproc.colorconvert.bgr2rgb") { + static GMatDesc outMeta(GMatDesc in) { + return in; // type still remains CV_8UC3; + } + }; + + G_TYPED_KERNEL(GRGB2YUV, , "org.opencv.imgproc.colorconvert.rgb2yuv") { + static GMatDesc outMeta(GMatDesc in) { + return in; // type still remains CV_8UC3; + } + }; + + G_TYPED_KERNEL(GYUV2RGB, , "org.opencv.imgproc.colorconvert.yuv2rgb") { + static GMatDesc outMeta(GMatDesc in) { + return in; // type still remains CV_8UC3; + } + }; + + G_TYPED_KERNEL(GBGR2I420, , "org.opencv.imgproc.colorconvert.bgr2i420") { + static GMatDesc outMeta(GMatDesc in) { + GAPI_Assert(in.depth == CV_8U); + GAPI_Assert(in.chan == 3); + GAPI_Assert(in.size.height % 2 == 0); + return in.withType(in.depth, 1).withSize(Size(in.size.width, in.size.height * 3 / 2)); + } + }; + + G_TYPED_KERNEL(GRGB2I420, , "org.opencv.imgproc.colorconvert.rgb2i420") { + static GMatDesc outMeta(GMatDesc in) { + GAPI_Assert(in.depth == CV_8U); + GAPI_Assert(in.chan == 3); + GAPI_Assert(in.size.height % 2 == 0); + return in.withType(in.depth, 1).withSize(Size(in.size.width, in.size.height * 3 / 2)); + } + }; + + G_TYPED_KERNEL(GI4202BGR, , "org.opencv.imgproc.colorconvert.i4202bgr") { + static GMatDesc outMeta(GMatDesc in) { + GAPI_Assert(in.depth == CV_8U); + GAPI_Assert(in.chan == 1); + GAPI_Assert(in.size.height % 3 == 0); + return in.withType(in.depth, 3).withSize(Size(in.size.width, in.size.height * 2 / 3)); + } + }; + + G_TYPED_KERNEL(GI4202RGB, , "org.opencv.imgproc.colorconvert.i4202rgb") { + static GMatDesc outMeta(GMatDesc in) { + GAPI_Assert(in.depth == CV_8U); + GAPI_Assert(in.chan == 1); + GAPI_Assert(in.size.height % 3 == 0); + return in.withType(in.depth, 3).withSize(Size(in.size.width, in.size.height * 2 / 3)); + } + }; + + G_TYPED_KERNEL(GNV12toRGB, , "org.opencv.imgproc.colorconvert.nv12torgb") { + static GMatDesc outMeta(GMatDesc in_y, GMatDesc in_uv) { + GAPI_Assert(in_y.chan == 1); + GAPI_Assert(in_uv.chan == 2); + GAPI_Assert(in_y.depth == CV_8U); + GAPI_Assert(in_uv.depth == CV_8U); + // UV size should be aligned with Y + GAPI_Assert(in_y.size.width == 2 * in_uv.size.width); + GAPI_Assert(in_y.size.height == 2 * in_uv.size.height); + return in_y.withType(CV_8U, 3); // type will be CV_8UC3; + } + }; + + G_TYPED_KERNEL(GNV12toBGR, , "org.opencv.imgproc.colorconvert.nv12tobgr") { + static GMatDesc outMeta(GMatDesc in_y, GMatDesc in_uv) { + GAPI_Assert(in_y.chan == 1); + GAPI_Assert(in_uv.chan == 2); + GAPI_Assert(in_y.depth == CV_8U); + GAPI_Assert(in_uv.depth == CV_8U); + // UV size should be aligned with Y + GAPI_Assert(in_y.size.width == 2 * in_uv.size.width); + GAPI_Assert(in_y.size.height == 2 * in_uv.size.height); + return in_y.withType(CV_8U, 3); // type will be CV_8UC3; + } + }; + + G_TYPED_KERNEL(GRGB2Lab, , "org.opencv.imgproc.colorconvert.rgb2lab") { + static GMatDesc outMeta(GMatDesc in) { + return in; // type still remains CV_8UC3; + } + }; + + G_TYPED_KERNEL(GBGR2LUV, , "org.opencv.imgproc.colorconvert.bgr2luv") { + static GMatDesc outMeta(GMatDesc in) { + return in; // type still remains CV_8UC3; + } + }; + + G_TYPED_KERNEL(GLUV2BGR, , "org.opencv.imgproc.colorconvert.luv2bgr") { + static GMatDesc outMeta(GMatDesc in) { + return in; // type still remains CV_8UC3; + } + }; + + G_TYPED_KERNEL(GYUV2BGR, , "org.opencv.imgproc.colorconvert.yuv2bgr") { + static GMatDesc outMeta(GMatDesc in) { + return in; // type still remains CV_8UC3; + } + }; + + G_TYPED_KERNEL(GBGR2YUV, , "org.opencv.imgproc.colorconvert.bgr2yuv") { + static GMatDesc outMeta(GMatDesc in) { + return in; // type still remains CV_8UC3; + } + }; + + G_TYPED_KERNEL(GRGB2Gray, , "org.opencv.imgproc.colorconvert.rgb2gray") { + static GMatDesc outMeta(GMatDesc in) { + return in.withType(CV_8U, 1); + } + }; + + G_TYPED_KERNEL(GRGB2GrayCustom, , "org.opencv.imgproc.colorconvert.rgb2graycustom") { + static GMatDesc outMeta(GMatDesc in, float, float, float) { + return in.withType(CV_8U, 1); + } + }; + + G_TYPED_KERNEL(GBGR2Gray, , "org.opencv.imgproc.colorconvert.bgr2gray") { + static GMatDesc outMeta(GMatDesc in) { + return in.withType(CV_8U, 1); + } + }; + + G_TYPED_KERNEL(GBayerGR2RGB, , "org.opencv.imgproc.colorconvert.bayergr2rgb") { + static cv::GMatDesc outMeta(cv::GMatDesc in) { + return in.withType(CV_8U, 3); + } + }; + + G_TYPED_KERNEL(GRGB2HSV, , "org.opencv.imgproc.colorconvert.rgb2hsv") { + static cv::GMatDesc outMeta(cv::GMatDesc in) { + return in; + } + }; + + G_TYPED_KERNEL(GRGB2YUV422, , "org.opencv.imgproc.colorconvert.rgb2yuv422") { + static cv::GMatDesc outMeta(cv::GMatDesc in) { + GAPI_Assert(in.depth == CV_8U); + GAPI_Assert(in.chan == 3); + return in.withType(in.depth, 2); + } + }; + + G_TYPED_KERNEL(GNV12toRGBp, , "org.opencv.imgproc.colorconvert.nv12torgbp") { + static GMatDesc outMeta(GMatDesc inY, GMatDesc inUV) { + GAPI_Assert(inY.depth == CV_8U); + GAPI_Assert(inUV.depth == CV_8U); + GAPI_Assert(inY.chan == 1); + GAPI_Assert(inY.planar == false); + GAPI_Assert(inUV.chan == 2); + GAPI_Assert(inUV.planar == false); + GAPI_Assert(inY.size.width == 2 * inUV.size.width); + GAPI_Assert(inY.size.height == 2 * inUV.size.height); + return inY.withType(CV_8U, 3).asPlanar(); + } + }; + + G_TYPED_KERNEL(GNV12toGray, , "org.opencv.imgproc.colorconvert.nv12togray") { + static GMatDesc outMeta(GMatDesc inY, GMatDesc inUV) { + GAPI_Assert(inY.depth == CV_8U); + GAPI_Assert(inUV.depth == CV_8U); + GAPI_Assert(inY.chan == 1); + GAPI_Assert(inY.planar == false); + GAPI_Assert(inUV.chan == 2); + GAPI_Assert(inUV.planar == false); + + GAPI_Assert(inY.size.width == 2 * inUV.size.width); + GAPI_Assert(inY.size.height == 2 * inUV.size.height); + return inY.withType(CV_8U, 1); + } + }; + + G_TYPED_KERNEL(GNV12toBGRp, , "org.opencv.imgproc.colorconvert.nv12tobgrp") { + static GMatDesc outMeta(GMatDesc inY, GMatDesc inUV) { + GAPI_Assert(inY.depth == CV_8U); + GAPI_Assert(inUV.depth == CV_8U); + GAPI_Assert(inY.chan == 1); + GAPI_Assert(inY.planar == false); + GAPI_Assert(inUV.chan == 2); + GAPI_Assert(inUV.planar == false); + GAPI_Assert(inY.size.width == 2 * inUV.size.width); + GAPI_Assert(inY.size.height == 2 * inUV.size.height); + return inY.withType(CV_8U, 3).asPlanar(); + } + }; + + G_TYPED_KERNEL(GResize, , "org.opencv.imgproc.transform.resize") { + static GMatDesc outMeta(GMatDesc in, Size sz, double fx, double fy, int /*interp*/) { + if (sz.width != 0 && sz.height != 0) + { + return in.withSize(sz); + } + else + { + int outSz_w = saturate_cast(in.size.width * fx); + int outSz_h = saturate_cast(in.size.height * fy); + GAPI_Assert(outSz_w > 0 && outSz_h > 0); + return in.withSize(Size(outSz_w, outSz_h)); + } + } + }; + + G_TYPED_KERNEL(GResizeP, , "org.opencv.imgproc.transform.resizeP") { + static GMatDesc outMeta(GMatDesc in, Size sz, int interp) { + GAPI_Assert(in.depth == CV_8U); + GAPI_Assert(in.chan == 3); + GAPI_Assert(in.planar); + GAPI_Assert(interp == cv::INTER_LINEAR); + return in.withSize(sz); + } + }; + +} //namespace imgproc + +//! @addtogroup gapi_filters +//! @{ +/** @brief Applies a separable linear filter to a matrix(image). + +The function applies a separable linear filter to the matrix. That is, first, every row of src is +filtered with the 1D kernel kernelX. Then, every column of the result is filtered with the 1D +kernel kernelY. The final result is returned. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. +Output image must have the same type, size, and number of channels as the input image. +@note + - In case of floating-point computation, rounding to nearest even is procedeed +if hardware supports it (if not - to nearest value). + - Function textual ID is "org.opencv.imgproc.filters.sepfilter" +@param src Source image. +@param ddepth desired depth of the destination image (the following combinations of src.depth() and ddepth are supported: + + src.depth() = CV_8U, ddepth = -1/CV_16S/CV_32F/CV_64F + src.depth() = CV_16U/CV_16S, ddepth = -1/CV_32F/CV_64F + src.depth() = CV_32F, ddepth = -1/CV_32F/CV_64F + src.depth() = CV_64F, ddepth = -1/CV_64F + +when ddepth=-1, the output image will have the same depth as the source) +@param kernelX Coefficients for filtering each row. +@param kernelY Coefficients for filtering each column. +@param anchor Anchor position within the kernel. The default value \f$(-1,-1)\f$ means that the anchor +is at the kernel center. +@param delta Value added to the filtered results before storing them. +@param borderType Pixel extrapolation method, see cv::BorderTypes +@param borderValue border value in case of constant border type +@sa boxFilter, gaussianBlur, medianBlur + */ +GAPI_EXPORTS_W GMat sepFilter(const GMat& src, int ddepth, const Mat& kernelX, const Mat& kernelY, const Point& anchor /*FIXME: = Point(-1,-1)*/, + const Scalar& delta /*FIXME = GScalar(0)*/, int borderType = BORDER_DEFAULT, + const Scalar& borderValue = Scalar(0)); + +/** @brief Convolves an image with the kernel. + +The function applies an arbitrary linear filter to an image. When +the aperture is partially outside the image, the function interpolates outlier pixel values +according to the specified border mode. + +The function does actually compute correlation, not the convolution: + +\f[\texttt{dst} (x,y) = \sum _{ \substack{0\leq x' < \texttt{kernel.cols}\\{0\leq y' < \texttt{kernel.rows}}}} \texttt{kernel} (x',y')* \texttt{src} (x+x'- \texttt{anchor.x} ,y+y'- \texttt{anchor.y} )\f] + +That is, the kernel is not mirrored around the anchor point. If you need a real convolution, flip +the kernel using flip and set the new anchor to `(kernel.cols - anchor.x - 1, kernel.rows - +anchor.y - 1)`. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. +Output image must have the same size and number of channels an input image. +@note + - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. + - Function textual ID is "org.opencv.imgproc.filters.filter2D" + +@param src input image. +@param ddepth desired depth of the destination image +@param kernel convolution kernel (or rather a correlation kernel), a single-channel floating point +matrix; if you want to apply different kernels to different channels, split the image into +separate color planes using split and process them individually. +@param anchor anchor of the kernel that indicates the relative position of a filtered point within +the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor +is at the kernel center. +@param delta optional value added to the filtered pixels before storing them in dst. +@param borderType pixel extrapolation method, see cv::BorderTypes +@param borderValue border value in case of constant border type +@sa sepFilter + */ +GAPI_EXPORTS_W GMat filter2D(const GMat& src, int ddepth, const Mat& kernel, const Point& anchor = Point(-1,-1), const Scalar& delta = Scalar(0), + int borderType = BORDER_DEFAULT, const Scalar& borderValue = Scalar(0)); + + +/** @brief Blurs an image using the box filter. + +The function smooths an image using the kernel: + +\f[\texttt{K} = \alpha \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \end{bmatrix}\f] + +where + +\f[\alpha = \begin{cases} \frac{1}{\texttt{ksize.width*ksize.height}} & \texttt{when } \texttt{normalize=true} \\1 & \texttt{otherwise} \end{cases}\f] + +Unnormalized box filter is useful for computing various integral characteristics over each pixel +neighborhood, such as covariance matrices of image derivatives (used in dense optical flow +algorithms, and so on). If you need to compute pixel sums over variable-size windows, use cv::integral. + +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. +Output image must have the same type, size, and number of channels as the input image. +@note + - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. + - Function textual ID is "org.opencv.imgproc.filters.boxfilter" + +@param src Source image. +@param dtype the output image depth (-1 to set the input image data type). +@param ksize blurring kernel size. +@param anchor Anchor position within the kernel. The default value \f$(-1,-1)\f$ means that the anchor +is at the kernel center. +@param normalize flag, specifying whether the kernel is normalized by its area or not. +@param borderType Pixel extrapolation method, see cv::BorderTypes +@param borderValue border value in case of constant border type +@sa sepFilter, gaussianBlur, medianBlur, integral + */ +GAPI_EXPORTS_W GMat boxFilter(const GMat& src, int dtype, const Size& ksize, const Point& anchor = Point(-1,-1), + bool normalize = true, int borderType = BORDER_DEFAULT, + const Scalar& borderValue = Scalar(0)); + +/** @brief Blurs an image using the normalized box filter. + +The function smooths an image using the kernel: + +\f[\texttt{K} = \frac{1}{\texttt{ksize.width*ksize.height}} \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \end{bmatrix}\f] + +The call `blur(src, ksize, anchor, borderType)` is equivalent to `boxFilter(src, src.type(), ksize, anchor, +true, borderType)`. + +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. +Output image must have the same type, size, and number of channels as the input image. +@note + - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. + - Function textual ID is "org.opencv.imgproc.filters.blur" + +@param src Source image. +@param ksize blurring kernel size. +@param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel +center. +@param borderType border mode used to extrapolate pixels outside of the image, see cv::BorderTypes +@param borderValue border value in case of constant border type +@sa boxFilter, bilateralFilter, GaussianBlur, medianBlur + */ +GAPI_EXPORTS_W GMat blur(const GMat& src, const Size& ksize, const Point& anchor = Point(-1,-1), + int borderType = BORDER_DEFAULT, const Scalar& borderValue = Scalar(0)); + + +//GAPI_EXPORTS_W void blur( InputArray src, OutputArray dst, + // Size ksize, Point anchor = Point(-1,-1), + // int borderType = BORDER_DEFAULT ); + + +/** @brief Blurs an image using a Gaussian filter. + +The function filter2Ds the source image with the specified Gaussian kernel. +Output image must have the same type and number of channels an input image. + +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. +Output image must have the same type, size, and number of channels as the input image. +@note + - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. + - Function textual ID is "org.opencv.imgproc.filters.gaussianBlur" + +@param src input image; +@param ksize Gaussian kernel size. ksize.width and ksize.height can differ but they both must be +positive and odd. Or, they can be zero's and then they are computed from sigma. +@param sigmaX Gaussian kernel standard deviation in X direction. +@param sigmaY Gaussian kernel standard deviation in Y direction; if sigmaY is zero, it is set to be +equal to sigmaX, if both sigmas are zeros, they are computed from ksize.width and ksize.height, +respectively (see cv::getGaussianKernel for details); to fully control the result regardless of +possible future modifications of all this semantics, it is recommended to specify all of ksize, +sigmaX, and sigmaY. +@param borderType pixel extrapolation method, see cv::BorderTypes +@param borderValue border value in case of constant border type +@sa sepFilter, boxFilter, medianBlur + */ +GAPI_EXPORTS_W GMat gaussianBlur(const GMat& src, const Size& ksize, double sigmaX, double sigmaY = 0, + int borderType = BORDER_DEFAULT, const Scalar& borderValue = Scalar(0)); + +/** @brief Blurs an image using the median filter. + +The function smoothes an image using the median filter with the \f$\texttt{ksize} \times +\texttt{ksize}\f$ aperture. Each channel of a multi-channel image is processed independently. +Output image must have the same type, size, and number of channels as the input image. +@note + - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. +The median filter uses cv::BORDER_REPLICATE internally to cope with border pixels, see cv::BorderTypes + - Function textual ID is "org.opencv.imgproc.filters.medianBlur" + +@param src input matrix (image) +@param ksize aperture linear size; it must be odd and greater than 1, for example: 3, 5, 7 ... +@sa boxFilter, gaussianBlur + */ +GAPI_EXPORTS_W GMat medianBlur(const GMat& src, int ksize); + +/** @brief Erodes an image by using a specific structuring element. + +The function erodes the source image using the specified structuring element that determines the +shape of a pixel neighborhood over which the minimum is taken: + +\f[\texttt{dst} (x,y) = \min _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f] + +Erosion can be applied several (iterations) times. In case of multi-channel images, each channel is processed independently. +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, and @ref CV_32FC1. +Output image must have the same type, size, and number of channels as the input image. +@note + - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. + - Function textual ID is "org.opencv.imgproc.filters.erode" + +@param src input image +@param kernel structuring element used for erosion; if `element=Mat()`, a `3 x 3` rectangular +structuring element is used. Kernel can be created using getStructuringElement. +@param anchor position of the anchor within the element; default value (-1, -1) means that the +anchor is at the element center. +@param iterations number of times erosion is applied. +@param borderType pixel extrapolation method, see cv::BorderTypes +@param borderValue border value in case of a constant border +@sa dilate, morphologyEx + */ +GAPI_EXPORTS_W GMat erode(const GMat& src, const Mat& kernel, const Point& anchor = Point(-1,-1), int iterations = 1, + int borderType = BORDER_CONSTANT, + const Scalar& borderValue = morphologyDefaultBorderValue()); + +/** @brief Erodes an image by using 3 by 3 rectangular structuring element. + +The function erodes the source image using the rectangular structuring element with rectangle center as an anchor. +Erosion can be applied several (iterations) times. In case of multi-channel images, each channel is processed independently. +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, and @ref CV_32FC1. +Output image must have the same type, size, and number of channels as the input image. +@note + - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. + - Function textual ID is "org.opencv.imgproc.filters.erode" + +@param src input image +@param iterations number of times erosion is applied. +@param borderType pixel extrapolation method, see cv::BorderTypes +@param borderValue border value in case of a constant border +@sa erode, dilate3x3 + */ +GAPI_EXPORTS_W GMat erode3x3(const GMat& src, int iterations = 1, + int borderType = BORDER_CONSTANT, + const Scalar& borderValue = morphologyDefaultBorderValue()); + +/** @brief Dilates an image by using a specific structuring element. + +The function dilates the source image using the specified structuring element that determines the +shape of a pixel neighborhood over which the maximum is taken: +\f[\texttt{dst} (x,y) = \max _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f] + +Dilation can be applied several (iterations) times. In case of multi-channel images, each channel is processed independently. +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, and @ref CV_32FC1. +Output image must have the same type, size, and number of channels as the input image. +@note + - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. + - Function textual ID is "org.opencv.imgproc.filters.dilate" + +@param src input image. +@param kernel structuring element used for dilation; if elemenat=Mat(), a 3 x 3 rectangular +structuring element is used. Kernel can be created using getStructuringElement +@param anchor position of the anchor within the element; default value (-1, -1) means that the +anchor is at the element center. +@param iterations number of times dilation is applied. +@param borderType pixel extrapolation method, see cv::BorderTypes +@param borderValue border value in case of a constant border +@sa erode, morphologyEx, getStructuringElement + */ +GAPI_EXPORTS_W GMat dilate(const GMat& src, const Mat& kernel, const Point& anchor = Point(-1,-1), int iterations = 1, + int borderType = BORDER_CONSTANT, + const Scalar& borderValue = morphologyDefaultBorderValue()); + +/** @brief Dilates an image by using 3 by 3 rectangular structuring element. + +The function dilates the source image using the specified structuring element that determines the +shape of a pixel neighborhood over which the maximum is taken: +\f[\texttt{dst} (x,y) = \max _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f] + +Dilation can be applied several (iterations) times. In case of multi-channel images, each channel is processed independently. +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, and @ref CV_32FC1. +Output image must have the same type, size, and number of channels as the input image. +@note + - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. + - Function textual ID is "org.opencv.imgproc.filters.dilate" + +@param src input image. +@param iterations number of times dilation is applied. +@param borderType pixel extrapolation method, see cv::BorderTypes +@param borderValue border value in case of a constant border +@sa dilate, erode3x3 + */ + +GAPI_EXPORTS_W GMat dilate3x3(const GMat& src, int iterations = 1, + int borderType = BORDER_CONSTANT, + const Scalar& borderValue = morphologyDefaultBorderValue()); + +/** @brief Performs advanced morphological transformations. + +The function can perform advanced morphological transformations using an erosion and dilation as +basic operations. + +Any of the operations can be done in-place. In case of multi-channel images, each channel is +processed independently. + +@note + - Function textual ID is "org.opencv.imgproc.filters.morphologyEx" + - The number of iterations is the number of times erosion or dilatation operation will be +applied. For instance, an opening operation (#MORPH_OPEN) with two iterations is equivalent to +apply successively: erode -> erode -> dilate -> dilate +(and not erode -> dilate -> erode -> dilate). + +@param src Input image. +@param op Type of a morphological operation, see #MorphTypes +@param kernel Structuring element. It can be created using #getStructuringElement. +@param anchor Anchor position within the element. Both negative values mean that the anchor is at +the kernel center. +@param iterations Number of times erosion and dilation are applied. +@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. +@param borderValue Border value in case of a constant border. The default value has a special +meaning. +@sa dilate, erode, getStructuringElement + */ +GAPI_EXPORTS_W GMat morphologyEx(const GMat &src, const MorphTypes op, const Mat &kernel, + const Point &anchor = Point(-1,-1), + const int iterations = 1, + const BorderTypes borderType = BORDER_CONSTANT, + const Scalar &borderValue = morphologyDefaultBorderValue()); + +/** @brief Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator. + +In all cases except one, the \f$\texttt{ksize} \times \texttt{ksize}\f$ separable kernel is used to +calculate the derivative. When \f$\texttt{ksize = 1}\f$, the \f$3 \times 1\f$ or \f$1 \times 3\f$ +kernel is used (that is, no Gaussian smoothing is done). `ksize = 1` can only be used for the first +or the second x- or y- derivatives. + +There is also the special value `ksize = FILTER_SCHARR (-1)` that corresponds to the \f$3\times3\f$ Scharr +filter that may give more accurate results than the \f$3\times3\f$ Sobel. The Scharr aperture is + +\f[\vecthreethree{-3}{0}{3}{-10}{0}{10}{-3}{0}{3}\f] + +for the x-derivative, or transposed for the y-derivative. + +The function calculates an image derivative by convolving the image with the appropriate kernel: + +\f[\texttt{dst} = \frac{\partial^{xorder+yorder} \texttt{src}}{\partial x^{xorder} \partial y^{yorder}}\f] + +The Sobel operators combine Gaussian smoothing and differentiation, so the result is more or less +resistant to the noise. Most often, the function is called with ( xorder = 1, yorder = 0, ksize = 3) +or ( xorder = 0, yorder = 1, ksize = 3) to calculate the first x- or y- image derivative. The first +case corresponds to a kernel of: + +\f[\vecthreethree{-1}{0}{1}{-2}{0}{2}{-1}{0}{1}\f] + +The second case corresponds to a kernel of: + +\f[\vecthreethree{-1}{-2}{-1}{0}{0}{0}{1}{2}{1}\f] + +@note + - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. + - Function textual ID is "org.opencv.imgproc.filters.sobel" + +@param src input image. +@param ddepth output image depth, see @ref filter_depths "combinations"; in the case of + 8-bit input images it will result in truncated derivatives. +@param dx order of the derivative x. +@param dy order of the derivative y. +@param ksize size of the extended Sobel kernel; it must be odd. +@param scale optional scale factor for the computed derivative values; by default, no scaling is +applied (see cv::getDerivKernels for details). +@param delta optional delta value that is added to the results prior to storing them in dst. +@param borderType pixel extrapolation method, see cv::BorderTypes +@param borderValue border value in case of constant border type +@sa filter2D, gaussianBlur, cartToPolar + */ +GAPI_EXPORTS_W GMat Sobel(const GMat& src, int ddepth, int dx, int dy, int ksize = 3, + double scale = 1, double delta = 0, + int borderType = BORDER_DEFAULT, + const Scalar& borderValue = Scalar(0)); + +/** @brief Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator. + +In all cases except one, the \f$\texttt{ksize} \times \texttt{ksize}\f$ separable kernel is used to +calculate the derivative. When \f$\texttt{ksize = 1}\f$, the \f$3 \times 1\f$ or \f$1 \times 3\f$ +kernel is used (that is, no Gaussian smoothing is done). `ksize = 1` can only be used for the first +or the second x- or y- derivatives. + +There is also the special value `ksize = FILTER_SCHARR (-1)` that corresponds to the \f$3\times3\f$ Scharr +filter that may give more accurate results than the \f$3\times3\f$ Sobel. The Scharr aperture is + +\f[\vecthreethree{-3}{0}{3}{-10}{0}{10}{-3}{0}{3}\f] + +for the x-derivative, or transposed for the y-derivative. + +The function calculates an image derivative by convolving the image with the appropriate kernel: + +\f[\texttt{dst} = \frac{\partial^{xorder+yorder} \texttt{src}}{\partial x^{xorder} \partial y^{yorder}}\f] + +The Sobel operators combine Gaussian smoothing and differentiation, so the result is more or less +resistant to the noise. Most often, the function is called with ( xorder = 1, yorder = 0, ksize = 3) +or ( xorder = 0, yorder = 1, ksize = 3) to calculate the first x- or y- image derivative. The first +case corresponds to a kernel of: + +\f[\vecthreethree{-1}{0}{1}{-2}{0}{2}{-1}{0}{1}\f] + +The second case corresponds to a kernel of: + +\f[\vecthreethree{-1}{-2}{-1}{0}{0}{0}{1}{2}{1}\f] + +@note + - First returned matrix correspons to dx derivative while the second one to dy. + - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. + - Function textual ID is "org.opencv.imgproc.filters.sobelxy" + +@param src input image. +@param ddepth output image depth, see @ref filter_depths "combinations"; in the case of + 8-bit input images it will result in truncated derivatives. +@param order order of the derivatives. +@param ksize size of the extended Sobel kernel; it must be odd. +@param scale optional scale factor for the computed derivative values; by default, no scaling is +applied (see cv::getDerivKernels for details). +@param delta optional delta value that is added to the results prior to storing them in dst. +@param borderType pixel extrapolation method, see cv::BorderTypes +@param borderValue border value in case of constant border type +@sa filter2D, gaussianBlur, cartToPolar + */ +GAPI_EXPORTS_W std::tuple SobelXY(const GMat& src, int ddepth, int order, int ksize = 3, + double scale = 1, double delta = 0, + int borderType = BORDER_DEFAULT, + const Scalar& borderValue = Scalar(0)); + +/** @brief Calculates the Laplacian of an image. + +The function calculates the Laplacian of the source image by adding up the second x and y +derivatives calculated using the Sobel operator: + +\f[\texttt{dst} = \Delta \texttt{src} = \frac{\partial^2 \texttt{src}}{\partial x^2} + \frac{\partial^2 \texttt{src}}{\partial y^2}\f] + +This is done when `ksize > 1`. When `ksize == 1`, the Laplacian is computed by filtering the image +with the following \f$3 \times 3\f$ aperture: + +\f[\vecthreethree {0}{1}{0}{1}{-4}{1}{0}{1}{0}\f] + +@note Function textual ID is "org.opencv.imgproc.filters.laplacian" + +@param src Source image. +@param ddepth Desired depth of the destination image. +@param ksize Aperture size used to compute the second-derivative filters. See #getDerivKernels for +details. The size must be positive and odd. +@param scale Optional scale factor for the computed Laplacian values. By default, no scaling is +applied. See #getDerivKernels for details. +@param delta Optional delta value that is added to the results prior to storing them in dst . +@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. +@return Destination image of the same size and the same number of channels as src. +@sa Sobel, Scharr + */ +GAPI_EXPORTS_W GMat Laplacian(const GMat& src, int ddepth, int ksize = 1, + double scale = 1, double delta = 0, int borderType = BORDER_DEFAULT); + +/** @brief Applies the bilateral filter to an image. + +The function applies bilateral filtering to the input image, as described in +http://www.dai.ed.ac.uk/CVonline/LOCAL_COPIES/MANDUCHI1/Bilateral_Filtering.html +bilateralFilter can reduce unwanted noise very well while keeping edges fairly sharp. However, it is +very slow compared to most filters. + +_Sigma values_: For simplicity, you can set the 2 sigma values to be the same. If they are small (\< +10), the filter will not have much effect, whereas if they are large (\> 150), they will have a very +strong effect, making the image look "cartoonish". + +_Filter size_: Large filters (d \> 5) are very slow, so it is recommended to use d=5 for real-time +applications, and perhaps d=9 for offline applications that need heavy noise filtering. + +This filter does not work inplace. + +@note Function textual ID is "org.opencv.imgproc.filters.bilateralfilter" + +@param src Source 8-bit or floating-point, 1-channel or 3-channel image. +@param d Diameter of each pixel neighborhood that is used during filtering. If it is non-positive, +it is computed from sigmaSpace. +@param sigmaColor Filter sigma in the color space. A larger value of the parameter means that +farther colors within the pixel neighborhood (see sigmaSpace) will be mixed together, resulting +in larger areas of semi-equal color. +@param sigmaSpace Filter sigma in the coordinate space. A larger value of the parameter means that +farther pixels will influence each other as long as their colors are close enough (see sigmaColor +). When d\>0, it specifies the neighborhood size regardless of sigmaSpace. Otherwise, d is +proportional to sigmaSpace. +@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes +@return Destination image of the same size and type as src. + */ +GAPI_EXPORTS_W GMat bilateralFilter(const GMat& src, int d, double sigmaColor, double sigmaSpace, + int borderType = BORDER_DEFAULT); + +//! @} gapi_filters + +//! @addtogroup gapi_feature +//! @{ +/** @brief Finds edges in an image using the Canny algorithm. + +The function finds edges in the input image and marks them in the output map edges using the +Canny algorithm. The smallest value between threshold1 and threshold2 is used for edge linking. The +largest value is used to find initial segments of strong edges. See + + +@note Function textual ID is "org.opencv.imgproc.feature.canny" + +@param image 8-bit input image. +@param threshold1 first threshold for the hysteresis procedure. +@param threshold2 second threshold for the hysteresis procedure. +@param apertureSize aperture size for the Sobel operator. +@param L2gradient a flag, indicating whether a more accurate \f$L_2\f$ norm +\f$=\sqrt{(dI/dx)^2 + (dI/dy)^2}\f$ should be used to calculate the image gradient magnitude ( +L2gradient=true ), or whether the default \f$L_1\f$ norm \f$=|dI/dx|+|dI/dy|\f$ is enough ( +L2gradient=false ). + */ +GAPI_EXPORTS_W GMat Canny(const GMat& image, double threshold1, double threshold2, + int apertureSize = 3, bool L2gradient = false); + +/** @brief Determines strong corners on an image. + +The function finds the most prominent corners in the image or in the specified image region, as +described in @cite Shi94 + +- Function calculates the corner quality measure at every source image pixel using the + #cornerMinEigenVal or #cornerHarris . +- Function performs a non-maximum suppression (the local maximums in *3 x 3* neighborhood are + retained). +- The corners with the minimal eigenvalue less than + \f$\texttt{qualityLevel} \cdot \max_{x,y} qualityMeasureMap(x,y)\f$ are rejected. +- The remaining corners are sorted by the quality measure in the descending order. +- Function throws away each corner for which there is a stronger corner at a distance less than + maxDistance. + +The function can be used to initialize a point-based tracker of an object. + +@note + - If the function is called with different values A and B of the parameter qualityLevel , and +A \> B, the vector of returned corners with qualityLevel=A will be the prefix of the output vector +with qualityLevel=B . + - Function textual ID is "org.opencv.imgproc.feature.goodFeaturesToTrack" + +@param image Input 8-bit or floating-point 32-bit, single-channel image. +@param maxCorners Maximum number of corners to return. If there are more corners than are found, +the strongest of them is returned. `maxCorners <= 0` implies that no limit on the maximum is set +and all detected corners are returned. +@param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The +parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue +(see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the +quality measure less than the product are rejected. For example, if the best corner has the +quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure +less than 15 are rejected. +@param minDistance Minimum possible Euclidean distance between the returned corners. +@param mask Optional region of interest. If the image is not empty (it needs to have the type +CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. +@param blockSize Size of an average block for computing a derivative covariation matrix over each +pixel neighborhood. See cornerEigenValsAndVecs . +@param useHarrisDetector Parameter indicating whether to use a Harris detector (see #cornerHarris) +or #cornerMinEigenVal. +@param k Free parameter of the Harris detector. + +@return vector of detected corners. + */ +GAPI_EXPORTS_W GArray goodFeaturesToTrack(const GMat &image, + int maxCorners, + double qualityLevel, + double minDistance, + const Mat &mask = Mat(), + int blockSize = 3, + bool useHarrisDetector = false, + double k = 0.04); + +/** @brief Equalizes the histogram of a grayscale image. + +//! @} gapi_feature + +The function equalizes the histogram of the input image using the following algorithm: + +- Calculate the histogram \f$H\f$ for src . +- Normalize the histogram so that the sum of histogram bins is 255. +- Compute the integral of the histogram: +\f[H'_i = \sum _{0 \le j < i} H(j)\f] +- Transform the image using \f$H'\f$ as a look-up table: \f$\texttt{dst}(x,y) = H'(\texttt{src}(x,y))\f$ + +The algorithm normalizes the brightness and increases the contrast of the image. +@note + - The returned image is of the same size and type as input. + - Function textual ID is "org.opencv.imgproc.equalizeHist" + +@param src Source 8-bit single channel image. + */ +GAPI_EXPORTS_W GMat equalizeHist(const GMat& src); + +//! @addtogroup gapi_shape +//! @{ +/** @brief Finds contours in a binary image. + +The function retrieves contours from the binary image using the algorithm @cite Suzuki85 . +The contours are a useful tool for shape analysis and object detection and recognition. +See squares.cpp in the OpenCV sample directory. + +@note Function textual ID is "org.opencv.imgproc.shape.findContours" + +@param src Input gray-scale image @ref CV_8UC1. Non-zero pixels are treated as 1's. Zero +pixels remain 0's, so the image is treated as binary . You can use #compare, #inRange, #threshold , +#adaptiveThreshold, #Canny, and others to create a binary image out of a grayscale or color one. +If mode equals to #RETR_CCOMP, the input can also be a 32-bit integer +image of labels ( @ref CV_32SC1 ). If #RETR_FLOODFILL then @ref CV_32SC1 is supported only. +@param mode Contour retrieval mode, see #RetrievalModes +@param method Contour approximation method, see #ContourApproximationModes +@param offset Optional offset by which every contour point is shifted. This is useful if the +contours are extracted from the image ROI and then they should be analyzed in the whole image +context. + +@return GArray of detected contours. Each contour is stored as a GArray of points. + */ +GAPI_EXPORTS GArray> +findContours(const GMat &src, const RetrievalModes mode, const ContourApproximationModes method, + const GOpaque &offset); + +// FIXME oc: make default value offset = Point() +/** @overload +@note Function textual ID is "org.opencv.imgproc.shape.findContoursNoOffset" + */ +GAPI_EXPORTS GArray> +findContours(const GMat &src, const RetrievalModes mode, const ContourApproximationModes method); + +/** @brief Finds contours and their hierarchy in a binary image. + +The function retrieves contours from the binary image using the algorithm @cite Suzuki85 +and calculates their hierarchy. +The contours are a useful tool for shape analysis and object detection and recognition. +See squares.cpp in the OpenCV sample directory. + +@note Function textual ID is "org.opencv.imgproc.shape.findContoursH" + +@param src Input gray-scale image @ref CV_8UC1. Non-zero pixels are treated as 1's. Zero +pixels remain 0's, so the image is treated as binary . You can use #compare, #inRange, #threshold , +#adaptiveThreshold, #Canny, and others to create a binary image out of a grayscale or color one. +If mode equals to #RETR_CCOMP, the input can also be a 32-bit integer +image of labels ( @ref CV_32SC1 ). If #RETR_FLOODFILL -- @ref CV_32SC1 supports only. +@param mode Contour retrieval mode, see #RetrievalModes +@param method Contour approximation method, see #ContourApproximationModes +@param offset Optional offset by which every contour point is shifted. This is useful if the +contours are extracted from the image ROI and then they should be analyzed in the whole image +context. + +@return + - GArray of detected contours. Each contour is stored as a GArray of points. + - Optional output GArray of cv::Vec4i, containing information about the image topology. +It has as many elements as the number of contours. For each i-th contour contours[i], the elements +hierarchy[i][0] , hierarchy[i][1] , hierarchy[i][2] , and hierarchy[i][3] are set to 0-based +indices in contours of the next and previous contours at the same hierarchical level, the first +child contour and the parent contour, respectively. If for the contour i there are no next, +previous, parent, or nested contours, the corresponding elements of hierarchy[i] will be negative. + */ +GAPI_EXPORTS std::tuple>,GArray> +findContoursH(const GMat &src, const RetrievalModes mode, const ContourApproximationModes method, + const GOpaque &offset); + +// FIXME oc: make default value offset = Point() +/** @overload +@note Function textual ID is "org.opencv.imgproc.shape.findContoursHNoOffset" + */ +GAPI_EXPORTS std::tuple>,GArray> +findContoursH(const GMat &src, const RetrievalModes mode, const ContourApproximationModes method); + +/** @brief Calculates the up-right bounding rectangle of a point set or non-zero pixels +of gray-scale image. + +The function calculates and returns the minimal up-right bounding rectangle for the specified +point set or non-zero pixels of gray-scale image. + +@note + - Function textual ID is "org.opencv.imgproc.shape.boundingRectMat" + - In case of a 2D points' set given, Mat should be 2-dimensional, have a single row or column +if there are 2 channels, or have 2 columns if there is a single channel. Mat should have either +@ref CV_32S or @ref CV_32F depth + +@param src Input gray-scale image @ref CV_8UC1; or input set of @ref CV_32S or @ref CV_32F +2D points stored in Mat. + */ +GAPI_EXPORTS_W GOpaque boundingRect(const GMat& src); + +/** @overload + +Calculates the up-right bounding rectangle of a point set. + +@note Function textual ID is "org.opencv.imgproc.shape.boundingRectVector32S" + +@param src Input 2D point set, stored in std::vector. + */ +GAPI_EXPORTS_W GOpaque boundingRect(const GArray& src); + +/** @overload + +Calculates the up-right bounding rectangle of a point set. + +@note Function textual ID is "org.opencv.imgproc.shape.boundingRectVector32F" + +@param src Input 2D point set, stored in std::vector. + */ +GAPI_EXPORTS_W GOpaque boundingRect(const GArray& src); + +/** @brief Fits a line to a 2D point set. + +The function fits a line to a 2D point set by minimizing \f$\sum_i \rho(r_i)\f$ where +\f$r_i\f$ is a distance between the \f$i^{th}\f$ point, the line and \f$\rho(r)\f$ is a distance +function, one of the following: +- DIST_L2 +\f[\rho (r) = r^2/2 \quad \text{(the simplest and the fastest least-squares method)}\f] +- DIST_L1 +\f[\rho (r) = r\f] +- DIST_L12 +\f[\rho (r) = 2 \cdot ( \sqrt{1 + \frac{r^2}{2}} - 1)\f] +- DIST_FAIR +\f[\rho \left (r \right ) = C^2 \cdot \left ( \frac{r}{C} - \log{\left(1 + \frac{r}{C}\right)} \right ) \quad \text{where} \quad C=1.3998\f] +- DIST_WELSCH +\f[\rho \left (r \right ) = \frac{C^2}{2} \cdot \left ( 1 - \exp{\left(-\left(\frac{r}{C}\right)^2\right)} \right ) \quad \text{where} \quad C=2.9846\f] +- DIST_HUBER +\f[\rho (r) = \fork{r^2/2}{if \(r < C\)}{C \cdot (r-C/2)}{otherwise} \quad \text{where} \quad C=1.345\f] + +The algorithm is based on the M-estimator ( ) technique +that iteratively fits the line using the weighted least-squares algorithm. After each iteration the +weights \f$w_i\f$ are adjusted to be inversely proportional to \f$\rho(r_i)\f$ . + +@note + - Function textual ID is "org.opencv.imgproc.shape.fitLine2DMat" + - In case of an N-dimentional points' set given, Mat should be 2-dimensional, have a single row +or column if there are N channels, or have N columns if there is a single channel. + +@param src Input set of 2D points stored in one of possible containers: Mat, +std::vector, std::vector, std::vector. +@param distType Distance used by the M-estimator, see #DistanceTypes. @ref DIST_USER +and @ref DIST_C are not supported. +@param param Numerical parameter ( C ) for some types of distances. If it is 0, an optimal value +is chosen. +@param reps Sufficient accuracy for the radius (distance between the coordinate origin and the +line). 1.0 would be a good default value for reps. If it is 0, a default value is chosen. +@param aeps Sufficient accuracy for the angle. 0.01 would be a good default value for aeps. +If it is 0, a default value is chosen. + +@return Output line parameters: a vector of 4 elements (like Vec4f) - (vx, vy, x0, y0), +where (vx, vy) is a normalized vector collinear to the line and (x0, y0) is a point on the line. + */ +GAPI_EXPORTS GOpaque fitLine2D(const GMat& src, const DistanceTypes distType, + const double param = 0., const double reps = 0., + const double aeps = 0.); + +/** @overload + +@note Function textual ID is "org.opencv.imgproc.shape.fitLine2DVector32S" + + */ +GAPI_EXPORTS GOpaque fitLine2D(const GArray& src, const DistanceTypes distType, + const double param = 0., const double reps = 0., + const double aeps = 0.); + +/** @overload + +@note Function textual ID is "org.opencv.imgproc.shape.fitLine2DVector32F" + + */ +GAPI_EXPORTS GOpaque fitLine2D(const GArray& src, const DistanceTypes distType, + const double param = 0., const double reps = 0., + const double aeps = 0.); + +/** @overload + +@note Function textual ID is "org.opencv.imgproc.shape.fitLine2DVector64F" + + */ +GAPI_EXPORTS GOpaque fitLine2D(const GArray& src, const DistanceTypes distType, + const double param = 0., const double reps = 0., + const double aeps = 0.); + +/** @brief Fits a line to a 3D point set. + +The function fits a line to a 3D point set by minimizing \f$\sum_i \rho(r_i)\f$ where +\f$r_i\f$ is a distance between the \f$i^{th}\f$ point, the line and \f$\rho(r)\f$ is a distance +function, one of the following: +- DIST_L2 +\f[\rho (r) = r^2/2 \quad \text{(the simplest and the fastest least-squares method)}\f] +- DIST_L1 +\f[\rho (r) = r\f] +- DIST_L12 +\f[\rho (r) = 2 \cdot ( \sqrt{1 + \frac{r^2}{2}} - 1)\f] +- DIST_FAIR +\f[\rho \left (r \right ) = C^2 \cdot \left ( \frac{r}{C} - \log{\left(1 + \frac{r}{C}\right)} \right ) \quad \text{where} \quad C=1.3998\f] +- DIST_WELSCH +\f[\rho \left (r \right ) = \frac{C^2}{2} \cdot \left ( 1 - \exp{\left(-\left(\frac{r}{C}\right)^2\right)} \right ) \quad \text{where} \quad C=2.9846\f] +- DIST_HUBER +\f[\rho (r) = \fork{r^2/2}{if \(r < C\)}{C \cdot (r-C/2)}{otherwise} \quad \text{where} \quad C=1.345\f] + +The algorithm is based on the M-estimator ( ) technique +that iteratively fits the line using the weighted least-squares algorithm. After each iteration the +weights \f$w_i\f$ are adjusted to be inversely proportional to \f$\rho(r_i)\f$ . + +@note + - Function textual ID is "org.opencv.imgproc.shape.fitLine3DMat" + - In case of an N-dimentional points' set given, Mat should be 2-dimensional, have a single row +or column if there are N channels, or have N columns if there is a single channel. + +@param src Input set of 3D points stored in one of possible containers: Mat, +std::vector, std::vector, std::vector. +@param distType Distance used by the M-estimator, see #DistanceTypes. @ref DIST_USER +and @ref DIST_C are not supported. +@param param Numerical parameter ( C ) for some types of distances. If it is 0, an optimal value +is chosen. +@param reps Sufficient accuracy for the radius (distance between the coordinate origin and the +line). 1.0 would be a good default value for reps. If it is 0, a default value is chosen. +@param aeps Sufficient accuracy for the angle. 0.01 would be a good default value for aeps. +If it is 0, a default value is chosen. + +@return Output line parameters: a vector of 6 elements (like Vec6f) - (vx, vy, vz, x0, y0, z0), +where (vx, vy, vz) is a normalized vector collinear to the line and (x0, y0, z0) is a point on +the line. + */ +GAPI_EXPORTS GOpaque fitLine3D(const GMat& src, const DistanceTypes distType, + const double param = 0., const double reps = 0., + const double aeps = 0.); + +/** @overload + +@note Function textual ID is "org.opencv.imgproc.shape.fitLine3DVector32S" + + */ +GAPI_EXPORTS GOpaque fitLine3D(const GArray& src, const DistanceTypes distType, + const double param = 0., const double reps = 0., + const double aeps = 0.); + +/** @overload + +@note Function textual ID is "org.opencv.imgproc.shape.fitLine3DVector32F" + + */ +GAPI_EXPORTS GOpaque fitLine3D(const GArray& src, const DistanceTypes distType, + const double param = 0., const double reps = 0., + const double aeps = 0.); + +/** @overload + +@note Function textual ID is "org.opencv.imgproc.shape.fitLine3DVector64F" + + */ +GAPI_EXPORTS GOpaque fitLine3D(const GArray& src, const DistanceTypes distType, + const double param = 0., const double reps = 0., + const double aeps = 0.); + +//! @} gapi_shape + +//! @addtogroup gapi_colorconvert +//! @{ +/** @brief Converts an image from BGR color space to RGB color space. + +The function converts an input image from BGR color space to RGB. +The conventional ranges for B, G, and R channel values are 0 to 255. + +Output image is 8-bit unsigned 3-channel image @ref CV_8UC3. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.bgr2rgb" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. +@sa RGB2BGR +*/ +GAPI_EXPORTS_W GMat BGR2RGB(const GMat& src); + +/** @brief Converts an image from RGB color space to gray-scaled. + +The conventional ranges for R, G, and B channel values are 0 to 255. +Resulting gray color value computed as +\f[\texttt{dst} (I)= \texttt{0.299} * \texttt{src}(I).R + \texttt{0.587} * \texttt{src}(I).G + \texttt{0.114} * \texttt{src}(I).B \f] + +@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2gray" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC1. +@sa RGB2YUV + */ +GAPI_EXPORTS_W GMat RGB2Gray(const GMat& src); + +/** @overload +Resulting gray color value computed as +\f[\texttt{dst} (I)= \texttt{rY} * \texttt{src}(I).R + \texttt{gY} * \texttt{src}(I).G + \texttt{bY} * \texttt{src}(I).B \f] + +@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2graycustom" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC1. +@param rY float multiplier for R channel. +@param gY float multiplier for G channel. +@param bY float multiplier for B channel. +@sa RGB2YUV + */ +GAPI_EXPORTS_W GMat RGB2Gray(const GMat& src, float rY, float gY, float bY); + +/** @brief Converts an image from BGR color space to gray-scaled. + +The conventional ranges for B, G, and R channel values are 0 to 255. +Resulting gray color value computed as +\f[\texttt{dst} (I)= \texttt{0.114} * \texttt{src}(I).B + \texttt{0.587} * \texttt{src}(I).G + \texttt{0.299} * \texttt{src}(I).R \f] + +@note Function textual ID is "org.opencv.imgproc.colorconvert.bgr2gray" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC1. +@sa BGR2LUV + */ +GAPI_EXPORTS_W GMat BGR2Gray(const GMat& src); + +/** @brief Converts an image from RGB color space to YUV color space. + +The function converts an input image from RGB color space to YUV. +The conventional ranges for R, G, and B channel values are 0 to 255. + +In case of linear transformations, the range does not matter. But in case of a non-linear +transformation, an input RGB image should be normalized to the proper value range to get the correct +results, like here, at RGB \f$\rightarrow\f$ Y\*u\*v\* transformation. +Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2yuv" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. +@sa YUV2RGB, RGB2Lab +*/ +GAPI_EXPORTS_W GMat RGB2YUV(const GMat& src); + +/** @brief Converts an image from BGR color space to I420 color space. + +The function converts an input image from BGR color space to I420. +The conventional ranges for R, G, and B channel values are 0 to 255. + +Output image must be 8-bit unsigned 1-channel image. @ref CV_8UC1. +Width of I420 output image must be the same as width of input image. +Height of I420 output image must be equal 3/2 from height of input image. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.bgr2i420" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. +@sa I4202BGR +*/ +GAPI_EXPORTS_W GMat BGR2I420(const GMat& src); + +/** @brief Converts an image from RGB color space to I420 color space. + +The function converts an input image from RGB color space to I420. +The conventional ranges for R, G, and B channel values are 0 to 255. + +Output image must be 8-bit unsigned 1-channel image. @ref CV_8UC1. +Width of I420 output image must be the same as width of input image. +Height of I420 output image must be equal 3/2 from height of input image. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2i420" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. +@sa I4202RGB +*/ +GAPI_EXPORTS_W GMat RGB2I420(const GMat& src); + +/** @brief Converts an image from I420 color space to BGR color space. + +The function converts an input image from I420 color space to BGR. +The conventional ranges for B, G, and R channel values are 0 to 255. + +Output image must be 8-bit unsigned 3-channel image. @ref CV_8UC3. +Width of BGR output image must be the same as width of input image. +Height of BGR output image must be equal 2/3 from height of input image. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.i4202bgr" + +@param src input image: 8-bit unsigned 1-channel image @ref CV_8UC1. +@sa BGR2I420 +*/ +GAPI_EXPORTS_W GMat I4202BGR(const GMat& src); + +/** @brief Converts an image from I420 color space to BGR color space. + +The function converts an input image from I420 color space to BGR. +The conventional ranges for B, G, and R channel values are 0 to 255. + +Output image must be 8-bit unsigned 3-channel image. @ref CV_8UC3. +Width of RGB output image must be the same as width of input image. +Height of RGB output image must be equal 2/3 from height of input image. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.i4202rgb" + +@param src input image: 8-bit unsigned 1-channel image @ref CV_8UC1. +@sa RGB2I420 +*/ +GAPI_EXPORTS_W GMat I4202RGB(const GMat& src); + +/** @brief Converts an image from BGR color space to LUV color space. + +The function converts an input image from BGR color space to LUV. +The conventional ranges for B, G, and R channel values are 0 to 255. + +Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.bgr2luv" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. +@sa RGB2Lab, RGB2LUV +*/ +GAPI_EXPORTS_W GMat BGR2LUV(const GMat& src); + +/** @brief Converts an image from LUV color space to BGR color space. + +The function converts an input image from LUV color space to BGR. +The conventional ranges for B, G, and R channel values are 0 to 255. + +Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.luv2bgr" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. +@sa BGR2LUV +*/ +GAPI_EXPORTS_W GMat LUV2BGR(const GMat& src); + +/** @brief Converts an image from YUV color space to BGR color space. + +The function converts an input image from YUV color space to BGR. +The conventional ranges for B, G, and R channel values are 0 to 255. + +Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.yuv2bgr" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. +@sa BGR2YUV +*/ +GAPI_EXPORTS_W GMat YUV2BGR(const GMat& src); + +/** @brief Converts an image from BGR color space to YUV color space. + +The function converts an input image from BGR color space to YUV. +The conventional ranges for B, G, and R channel values are 0 to 255. + +Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.bgr2yuv" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. +@sa YUV2BGR +*/ +GAPI_EXPORTS_W GMat BGR2YUV(const GMat& src); + +/** @brief Converts an image from RGB color space to Lab color space. + +The function converts an input image from BGR color space to Lab. +The conventional ranges for R, G, and B channel values are 0 to 255. + +Output image must be 8-bit unsigned 3-channel image @ref CV_8UC1. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2lab" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC1. +@sa RGB2YUV, RGB2LUV +*/ +GAPI_EXPORTS_W GMat RGB2Lab(const GMat& src); + +/** @brief Converts an image from YUV color space to RGB. +The function converts an input image from YUV color space to RGB. +The conventional ranges for Y, U, and V channel values are 0 to 255. + +Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.yuv2rgb" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. + +@sa RGB2Lab, RGB2YUV +*/ +GAPI_EXPORTS_W GMat YUV2RGB(const GMat& src); + +/** @brief Converts an image from NV12 (YUV420p) color space to RGB. +The function converts an input image from NV12 color space to RGB. +The conventional ranges for Y, U, and V channel values are 0 to 255. + +Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.nv12torgb" + +@param src_y input image: 8-bit unsigned 1-channel image @ref CV_8UC1. +@param src_uv input image: 8-bit unsigned 2-channel image @ref CV_8UC2. + +@sa YUV2RGB, NV12toBGR +*/ +GAPI_EXPORTS_W GMat NV12toRGB(const GMat& src_y, const GMat& src_uv); + +/** @brief Converts an image from NV12 (YUV420p) color space to gray-scaled. +The function converts an input image from NV12 color space to gray-scaled. +The conventional ranges for Y, U, and V channel values are 0 to 255. + +Output image must be 8-bit unsigned 1-channel image @ref CV_8UC1. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.nv12togray" + +@param src_y input image: 8-bit unsigned 1-channel image @ref CV_8UC1. +@param src_uv input image: 8-bit unsigned 2-channel image @ref CV_8UC2. + +@sa YUV2RGB, NV12toBGR +*/ +GAPI_EXPORTS_W GMat NV12toGray(const GMat& src_y, const GMat& src_uv); + +/** @brief Converts an image from NV12 (YUV420p) color space to BGR. +The function converts an input image from NV12 color space to RGB. +The conventional ranges for Y, U, and V channel values are 0 to 255. + +Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.nv12tobgr" + +@param src_y input image: 8-bit unsigned 1-channel image @ref CV_8UC1. +@param src_uv input image: 8-bit unsigned 2-channel image @ref CV_8UC2. + +@sa YUV2BGR, NV12toRGB +*/ +GAPI_EXPORTS_W GMat NV12toBGR(const GMat& src_y, const GMat& src_uv); + +/** @brief Converts an image from BayerGR color space to RGB. +The function converts an input image from BayerGR color space to RGB. +The conventional ranges for G, R, and B channel values are 0 to 255. + +Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.bayergr2rgb" + +@param src_gr input image: 8-bit unsigned 1-channel image @ref CV_8UC1. + +@sa YUV2BGR, NV12toRGB +*/ +GAPI_EXPORTS_W GMat BayerGR2RGB(const GMat& src_gr); + +/** @brief Converts an image from RGB color space to HSV. +The function converts an input image from RGB color space to HSV. +The conventional ranges for R, G, and B channel values are 0 to 255. + +Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2hsv" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. + +@sa YUV2BGR, NV12toRGB +*/ +GAPI_EXPORTS_W GMat RGB2HSV(const GMat& src); + +/** @brief Converts an image from RGB color space to YUV422. +The function converts an input image from RGB color space to YUV422. +The conventional ranges for R, G, and B channel values are 0 to 255. + +Output image must be 8-bit unsigned 2-channel image @ref CV_8UC2. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2yuv422" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. + +@sa YUV2BGR, NV12toRGB +*/ +GAPI_EXPORTS_W GMat RGB2YUV422(const GMat& src); + +/** @brief Converts an image from NV12 (YUV420p) color space to RGB. +The function converts an input image from NV12 color space to RGB. +The conventional ranges for Y, U, and V channel values are 0 to 255. + +Output image must be 8-bit unsigned planar 3-channel image @ref CV_8UC1. +Planar image memory layout is three planes laying in the memory contiguously, +so the image height should be plane_height*plane_number, +image type is @ref CV_8UC1. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.nv12torgbp" + +@param src_y input image: 8-bit unsigned 1-channel image @ref CV_8UC1. +@param src_uv input image: 8-bit unsigned 2-channel image @ref CV_8UC2. + +@sa YUV2RGB, NV12toBGRp, NV12toRGB +*/ +GAPI_EXPORTS GMatP NV12toRGBp(const GMat &src_y, const GMat &src_uv); + +/** @brief Converts an image from NV12 (YUV420p) color space to BGR. +The function converts an input image from NV12 color space to BGR. +The conventional ranges for Y, U, and V channel values are 0 to 255. + +Output image must be 8-bit unsigned planar 3-channel image @ref CV_8UC1. +Planar image memory layout is three planes laying in the memory contiguously, +so the image height should be plane_height*plane_number, +image type is @ref CV_8UC1. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.nv12torgbp" + +@param src_y input image: 8-bit unsigned 1-channel image @ref CV_8UC1. +@param src_uv input image: 8-bit unsigned 2-channel image @ref CV_8UC2. + +@sa YUV2RGB, NV12toRGBp, NV12toBGR +*/ +GAPI_EXPORTS GMatP NV12toBGRp(const GMat &src_y, const GMat &src_uv); + +//! @} gapi_colorconvert +//! @addtogroup gapi_transform +//! @{ +/** @brief Resizes an image. + +The function resizes the image src down to or up to the specified size. + +Output image size will have the size dsize (when dsize is non-zero) or the size computed from +src.size(), fx, and fy; the depth of output is the same as of src. + +If you want to resize src so that it fits the pre-created dst, +you may call the function as follows: +@code + // explicitly specify dsize=dst.size(); fx and fy will be computed from that. + resize(src, dst, dst.size(), 0, 0, interpolation); +@endcode +If you want to decimate the image by factor of 2 in each direction, you can call the function this +way: +@code + // specify fx and fy and let the function compute the destination image size. + resize(src, dst, Size(), 0.5, 0.5, interpolation); +@endcode +To shrink an image, it will generally look best with cv::INTER_AREA interpolation, whereas to +enlarge an image, it will generally look best with cv::INTER_CUBIC (slow) or cv::INTER_LINEAR +(faster but still looks OK). + +@note Function textual ID is "org.opencv.imgproc.transform.resize" + +@param src input image. +@param dsize output image size; if it equals zero, it is computed as: + \f[\texttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}\f] + Either dsize or both fx and fy must be non-zero. +@param fx scale factor along the horizontal axis; when it equals 0, it is computed as +\f[\texttt{(double)dsize.width/src.cols}\f] +@param fy scale factor along the vertical axis; when it equals 0, it is computed as +\f[\texttt{(double)dsize.height/src.rows}\f] +@param interpolation interpolation method, see cv::InterpolationFlags + +@sa warpAffine, warpPerspective, remap, resizeP + */ +GAPI_EXPORTS_W GMat resize(const GMat& src, const Size& dsize, double fx = 0, double fy = 0, int interpolation = INTER_LINEAR); + +/** @brief Resizes a planar image. + +The function resizes the image src down to or up to the specified size. +Planar image memory layout is three planes laying in the memory contiguously, +so the image height should be plane_height*plane_number, image type is @ref CV_8UC1. + +Output image size will have the size dsize, the depth of output is the same as of src. + +@note Function textual ID is "org.opencv.imgproc.transform.resizeP" + +@param src input image, must be of @ref CV_8UC1 type; +@param dsize output image size; +@param interpolation interpolation method, only cv::INTER_LINEAR is supported at the moment + +@sa warpAffine, warpPerspective, remap, resize + */ +GAPI_EXPORTS GMatP resizeP(const GMatP& src, const Size& dsize, int interpolation = cv::INTER_LINEAR); + +//! @} gapi_transform +} //namespace gapi +} //namespace cv + +#endif // OPENCV_GAPI_IMGPROC_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/infer.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/infer.hpp index abbd32ba20..4aa2484f02 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/infer.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/infer.hpp @@ -1,717 +1,717 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019-2021 Intel Corporation - - -#ifndef OPENCV_GAPI_INFER_HPP -#define OPENCV_GAPI_INFER_HPP - -// FIXME: Inference API is currently only available in full mode -#if !defined(GAPI_STANDALONE) - -#include -#include // string -#include // tuple -#include // is_same, false_type - -#include // all_satisfy -#include // any<> -#include // GKernelType[M], GBackend -#include // GArg -#include // CompileArgTag -#include // GMetaArg - -namespace cv { - -template class GNetworkType; - -namespace detail { - -// Infer /////////////////////////////////////////////////////////////////////// -template -struct accepted_infer_types { - static constexpr const auto value = - std::is_same::type, cv::GMat>::value - || std::is_same::type, cv::GFrame>::value; -}; - -template -using valid_infer_types = all_satisfy; - -// Infer2 ////////////////////////////////////////////////////////////////////// - -template -struct valid_infer2_types; - -// Terminal case 1 (50/50 success) -template -struct valid_infer2_types< std::tuple, std::tuple > { - // By default, Nets are limited to GMat argument types only - // for infer2, every GMat argument may translate to either - // GArray or GArray. GArray<> part is stripped - // already at this point. - static constexpr const auto value = - std::is_same::type, cv::GMat>::value - || std::is_same::type, cv::Rect>::value; -}; - -// Terminal case 2 (100% failure) -template -struct valid_infer2_types< std::tuple<>, std::tuple > - : public std::false_type { -}; - -// Terminal case 3 (100% failure) -template -struct valid_infer2_types< std::tuple, std::tuple<> > - : public std::false_type { -}; - -// Recursion -- generic -template -struct valid_infer2_types< std::tuple, std::tuple > { - static constexpr const auto value = - valid_infer2_types< std::tuple, std::tuple >::value - && valid_infer2_types< std::tuple, std::tuple >::value; -}; - -// Struct stores network input/output names. -// Used by infer -struct InOutInfo -{ - std::vector in_names; - std::vector out_names; -}; - -template -class GInferOutputsTyped -{ -public: - GInferOutputsTyped() = default; - GInferOutputsTyped(std::shared_ptr call) - : m_priv(std::make_shared(std::move(call))) - { - } - - OutT at(const std::string& name) - { - auto it = m_priv->blobs.find(name); - if (it == m_priv->blobs.end()) { - // FIXME: Avoid modifying GKernel - auto shape = cv::detail::GTypeTraits::shape; - auto kind = cv::detail::GTypeTraits::op_kind; - m_priv->call->kernel().outShapes.push_back(shape); - m_priv->call->kernel().outCtors.emplace_back(cv::detail::GObtainCtor::get()); - m_priv->call->kernel().outKinds.emplace_back(kind); - auto out_idx = static_cast(m_priv->blobs.size()); - it = m_priv->blobs.emplace(name, - cv::detail::Yield::yield(*(m_priv->call), out_idx)).first; - m_priv->info->out_names.push_back(name); - } - return it->second; - } -private: - struct Priv - { - Priv(std::shared_ptr c) - : call(std::move(c)), info(cv::util::any_cast(&call->params())) - { - } - - std::shared_ptr call; - InOutInfo* info = nullptr; - std::unordered_map blobs; - }; - - std::shared_ptr m_priv; -}; - -template -class GInferInputsTyped -{ -public: - GInferInputsTyped() - : m_priv(std::make_shared()) - { - } - - template - GInferInputsTyped& setInput(const std::string& name, U in) - { - m_priv->blobs.emplace(std::piecewise_construct, - std::forward_as_tuple(name), - std::forward_as_tuple(in)); - return *this; - } - - using StorageT = cv::util::variant; - StorageT& operator[](const std::string& name) { - return m_priv->blobs[name]; - } - - using Map = std::unordered_map; - const Map& getBlobs() const { - return m_priv->blobs; - } - -private: - struct Priv - { - std::unordered_map blobs; - }; - - std::shared_ptr m_priv; -}; - -template -std::shared_ptr makeCall(const std::string &tag, - std::vector &&args, - std::vector &&names, - cv::GKinds &&kinds) { - auto call = std::make_shared(GKernel{ - InferT::id(), - tag, - InferT::getOutMeta, - {}, // outShape will be filled later - std::move(kinds), - {}, // outCtors will be filled later - {}, // outKinds will be filled later - }); - - call->setArgs(std::move(args)); - call->params() = cv::detail::InOutInfo{std::move(names), {}}; - - return call; -} - -} // namespace detail - -// TODO: maybe tuple_wrap_helper from util.hpp may help with this. -// Multiple-return-value network definition (specialized base class) -template -class GNetworkType(Args...)> > -{ -public: - using InArgs = std::tuple; - using OutArgs = std::tuple; - - using Result = OutArgs; - using API = std::function; - - using ResultL = std::tuple< cv::GArray... >; -}; - -// Single-return-value network definition (specialized base class) -template -class GNetworkType > -{ -public: - using InArgs = std::tuple; - using OutArgs = std::tuple; - - using Result = R; - using API = std::function; - - using ResultL = cv::GArray; -}; - -// InferAPI: Accepts either GMat or GFrame for very individual network's input -template -struct InferAPI { - using type = typename std::enable_if - < detail::valid_infer_types::value - && std::tuple_size::value == sizeof...(Ts) - , std::function - >::type; -}; - -// InferAPIRoi: Accepts a rectangle and either GMat or GFrame -template -struct InferAPIRoi { - using type = typename std::enable_if - < detail::valid_infer_types::value - && std::tuple_size::value == 1u - , std::function, T)> - >::type; -}; - -// InferAPIList: Accepts a list of rectangles and list of GMat/GFrames; -// crops every input. -template -struct InferAPIList { - using type = typename std::enable_if - < detail::valid_infer_types::value - && std::tuple_size::value == sizeof...(Ts) - , std::function, Ts...)> - >::type; -}; - -// APIList2 is also template to allow different calling options -// (GArray vs GArray per input) -template -struct InferAPIList2 { - using type = typename std::enable_if - < detail::valid_infer_types::value && - cv::detail::valid_infer2_types< typename Net::InArgs - , std::tuple >::value, - std::function...)> - >::type; -}; - -// Base "Infer" kernel. Note - for whatever network, kernel ID -// is always the same. Different inference calls are distinguished by -// network _tag_ (an extra field in GCall) -// -// getOutMeta is a stub callback collected by G-API kernel subsystem -// automatically. This is a rare case when this callback is defined by -// a particular backend, not by a network itself. -struct GInferBase { - static constexpr const char * id() { - return "org.opencv.dnn.infer"; // Universal stub - } - static GMetaArgs getOutMeta(const GMetaArgs &, const GArgs &) { - return GMetaArgs{}; // One more universal stub - } -}; - -// Base "InferROI" kernel. -// All notes from "Infer" kernel apply here as well. -struct GInferROIBase { - static constexpr const char * id() { - return "org.opencv.dnn.infer-roi"; // Universal stub - } - static GMetaArgs getOutMeta(const GMetaArgs &, const GArgs &) { - return GMetaArgs{}; // One more universal stub - } -}; - -// Base "Infer list" kernel. -// All notes from "Infer" kernel apply here as well. -struct GInferListBase { - static constexpr const char * id() { - return "org.opencv.dnn.infer-roi-list-1"; // Universal stub - } - static GMetaArgs getOutMeta(const GMetaArgs &, const GArgs &) { - return GMetaArgs{}; // One more universal stub - } -}; - -// Base "Infer list 2" kernel. -// All notes from "Infer" kernel apply here as well. -struct GInferList2Base { - static constexpr const char * id() { - return "org.opencv.dnn.infer-roi-list-2"; // Universal stub - } - static GMetaArgs getOutMeta(const GMetaArgs &, const GArgs &) { - return GMetaArgs{}; // One more universal stub - } -}; - -// A generic inference kernel. API (::on()) is fully defined by the Net -// template parameter. -// Acts as a regular kernel in graph (via KernelTypeMedium). -template -struct GInfer final - : public GInferBase - , public detail::KernelTypeMedium< GInfer - , typename InferAPI::type > { - using GInferBase::getOutMeta; // FIXME: name lookup conflict workaround? - - static constexpr const char* tag() { return Net::tag(); } -}; - -// A specific roi-inference kernel. API (::on()) is fixed here and -// verified against Net. -template -struct GInferROI final - : public GInferROIBase - , public detail::KernelTypeMedium< GInferROI - , typename InferAPIRoi::type > { - using GInferROIBase::getOutMeta; // FIXME: name lookup conflict workaround? - - static constexpr const char* tag() { return Net::tag(); } -}; - - -// A generic roi-list inference kernel. API (::on()) is derived from -// the Net template parameter (see more in infer<> overload). -template -struct GInferList final - : public GInferListBase - , public detail::KernelTypeMedium< GInferList - , typename InferAPIList::type > { - using GInferListBase::getOutMeta; // FIXME: name lookup conflict workaround? - - static constexpr const char* tag() { return Net::tag(); } -}; - -// An even more generic roi-list inference kernel. API (::on()) is -// derived from the Net template parameter (see more in infer<> -// overload). -// Takes an extra variadic template list to reflect how this network -// was called (with Rects or GMats as array parameters) -template -struct GInferList2 final - : public GInferList2Base - , public detail::KernelTypeMedium< GInferList2 - , typename InferAPIList2::type > { - using GInferList2Base::getOutMeta; // FIXME: name lookup conflict workaround? - - static constexpr const char* tag() { return Net::tag(); } -}; - -/** - * @brief G-API object used to collect network inputs - */ -using GInferInputs = cv::detail::GInferInputsTyped; - -/** - * @brief G-API object used to collect the list of network inputs - */ -using GInferListInputs = cv::detail::GInferInputsTyped, cv::GArray>; - -/** - * @brief G-API object used to collect network outputs - */ -using GInferOutputs = cv::detail::GInferOutputsTyped; - -/** - * @brief G-API object used to collect the list of network outputs - */ -using GInferListOutputs = cv::detail::GInferOutputsTyped>; - -namespace detail { -void inline unpackBlobs(const cv::GInferInputs::Map& blobs, - std::vector& args, - std::vector& names, - cv::GKinds& kinds) -{ - for (auto&& p : blobs) { - names.emplace_back(p.first); - switch (p.second.index()) { - case cv::GInferInputs::StorageT::index_of(): - args.emplace_back(cv::util::get(p.second)); - kinds.emplace_back(cv::detail::OpaqueKind::CV_MAT); - break; - case cv::GInferInputs::StorageT::index_of(): - args.emplace_back(cv::util::get(p.second)); - kinds.emplace_back(cv::detail::OpaqueKind::CV_UNKNOWN); - break; - default: - GAPI_Error("InternalError"); - } - } -} - -template -struct InferROITraits; - -template <> -struct InferROITraits -{ - using outType = cv::GInferOutputs; - using inType = cv::GOpaque; -}; - -template <> -struct InferROITraits -{ - using outType = cv::GInferListOutputs; - using inType = cv::GArray; -}; - -template -typename InferROITraits::outType -inferGenericROI(const std::string& tag, - const typename InferROITraits::inType& in, - const cv::GInferInputs& inputs) -{ - std::vector args; - std::vector names; - cv::GKinds kinds; - - args.emplace_back(in); - kinds.emplace_back(cv::detail::OpaqueKind::CV_RECT); - - unpackBlobs(inputs.getBlobs(), args, names, kinds); - - auto call = cv::detail::makeCall(tag, - std::move(args), - std::move(names), - std::move(kinds)); - - return {std::move(call)}; -} - -} // namespace detail -} // namespace cv - -// FIXME: Probably the signature makes a function/tuple/function round-trip -#define G_API_NET(Class, API, Tag) \ - struct Class final: public cv::GNetworkType { \ - static constexpr const char * tag() { return Tag; } \ - } - -namespace cv { -namespace gapi { - -/** @brief Calculates response for the specified network (template - * parameter) for the specified region in the source image. - * Currently expects a single-input network only. - * - * @tparam A network type defined with G_API_NET() macro. - * @param in input image where to take ROI from. - * @param roi an object describing the region of interest - * in the source image. May be calculated in the same graph dynamically. - * @return an object of return type as defined in G_API_NET(). - * If a network has multiple return values (defined with a tuple), a tuple of - * objects of appropriate type is returned. - * @sa G_API_NET() - */ -template -typename Net::Result infer(cv::GOpaque roi, T in) { - return GInferROI::on(roi, in); -} - -/** @brief Calculates responses for the specified network (template - * parameter) for every region in the source image. - * - * @tparam A network type defined with G_API_NET() macro. - * @param roi a list of rectangles describing regions of interest - * in the source image. Usually an output of object detector or tracker. - * @param args network's input parameters as specified in G_API_NET() macro. - * NOTE: verified to work reliably with 1-input topologies only. - * @return a list of objects of return type as defined in G_API_NET(). - * If a network has multiple return values (defined with a tuple), a tuple of - * GArray<> objects is returned with the appropriate types inside. - * @sa G_API_NET() - */ -template -typename Net::ResultL infer(cv::GArray roi, Args&&... args) { - return GInferList::on(roi, std::forward(args)...); -} - -/** @brief Calculates responses for the specified network (template - * parameter) for every region in the source image, extended version. - * - * @tparam A network type defined with G_API_NET() macro. - * @param image A source image containing regions of interest - * @param args GArray<> objects of cv::Rect or cv::GMat, one per every - * network input: - * - If a cv::GArray is passed, the appropriate - * regions are taken from `image` and preprocessed to this particular - * network input; - * - If a cv::GArray is passed, the underlying data traited - * as tensor (no automatic preprocessing happen). - * @return a list of objects of return type as defined in G_API_NET(). - * If a network has multiple return values (defined with a tuple), a tuple of - * GArray<> objects is returned with the appropriate types inside. - * @sa G_API_NET() - */ - -template -typename Net::ResultL infer2(T image, cv::GArray... args) { - // FIXME: Declared as "2" because in the current form it steals - // overloads from the regular infer - return GInferList2::on(image, args...); -} - -/** - * @brief Calculates response for the specified network (template - * parameter) given the input data. - * - * @tparam A network type defined with G_API_NET() macro. - * @param args network's input parameters as specified in G_API_NET() macro. - * @return an object of return type as defined in G_API_NET(). - * If a network has multiple return values (defined with a tuple), a tuple of - * objects of appropriate type is returned. - * @sa G_API_NET() - */ -template -typename Net::Result infer(Args&&... args) { - return GInfer::on(std::forward(args)...); -} - -/** - * @brief Generic network type: input and output layers are configured dynamically at runtime - * - * Unlike the network types defined with G_API_NET macro, this one - * doesn't fix number of network inputs and outputs at the compilation stage - * thus providing user with an opportunity to program them in runtime. - */ -struct Generic { }; - -/** - * @brief Calculates response for generic network - * - * @param tag a network tag - * @param inputs networks's inputs - * @return a GInferOutputs - */ -template cv::GInferOutputs -infer(const std::string& tag, const cv::GInferInputs& inputs) -{ - std::vector args; - std::vector names; - cv::GKinds kinds; - - cv::detail::unpackBlobs(inputs.getBlobs(), args, names, kinds); - - auto call = cv::detail::makeCall(tag, - std::move(args), - std::move(names), - std::move(kinds)); - - return cv::GInferOutputs{std::move(call)}; -} - -/** @brief Calculates response for the generic network - * for the specified region in the source image. - * Currently expects a single-input network only. - * - * @param tag a network tag - * @param roi a an object describing the region of interest - * in the source image. May be calculated in the same graph dynamically. - * @param inputs networks's inputs - * @return a cv::GInferOutputs - */ -template cv::GInferOutputs -infer(const std::string& tag, const cv::GOpaque& roi, const cv::GInferInputs& inputs) -{ - return cv::detail::inferGenericROI(tag, roi, inputs); -} - -/** @brief Calculates responses for the specified network - * for every region in the source image. - * - * @param tag a network tag - * @param rois a list of rectangles describing regions of interest - * in the source image. Usually an output of object detector or tracker. - * @param inputs networks's inputs - * @return a cv::GInferListOutputs - */ -template cv::GInferListOutputs -infer(const std::string& tag, const cv::GArray& rois, const cv::GInferInputs& inputs) -{ - return cv::detail::inferGenericROI(tag, rois, inputs); -} - -/** @brief Calculates responses for the specified network - * for every region in the source image, extended version. - * - * @param tag a network tag - * @param in a source image containing regions of interest. - * @param inputs networks's inputs - * @return a cv::GInferListOutputs - */ -template -typename std::enable_if::value, cv::GInferListOutputs>::type -infer2(const std::string& tag, - const Input& in, - const cv::GInferListInputs& inputs) -{ - std::vector args; - std::vector names; - cv::GKinds kinds; - - args.emplace_back(in); - auto k = cv::detail::GOpaqueTraits::kind; - kinds.emplace_back(k); - - for (auto&& p : inputs.getBlobs()) { - names.emplace_back(p.first); - switch (p.second.index()) { - case cv::GInferListInputs::StorageT::index_of>(): - args.emplace_back(cv::util::get>(p.second)); - kinds.emplace_back(cv::detail::OpaqueKind::CV_MAT); - break; - case cv::GInferListInputs::StorageT::index_of>(): - args.emplace_back(cv::util::get>(p.second)); - kinds.emplace_back(cv::detail::OpaqueKind::CV_RECT); - break; - default: - GAPI_Error("InternalError"); - } - } - - auto call = cv::detail::makeCall(tag, - std::move(args), - std::move(names), - std::move(kinds)); - - return cv::GInferListOutputs{std::move(call)}; -} - -} // namespace gapi -} // namespace cv - -#endif // GAPI_STANDALONE - -namespace cv { -namespace gapi { - -// Note: the below code _is_ part of STANDALONE build, -// just to make our compiler code compileable. - -// A type-erased form of network parameters. -// Similar to how a type-erased GKernel is represented and used. -/// @private -struct GAPI_EXPORTS_W_SIMPLE GNetParam { - std::string tag; // FIXME: const? - GBackend backend; // Specifies the execution model - util::any params; // Backend-interpreted parameter structure -}; - -/** \addtogroup gapi_compile_args - * @{ - */ -/** - * @brief A container class for network configurations. Similar to - * GKernelPackage. Use cv::gapi::networks() to construct this object. - * - * @sa cv::gapi::networks - */ -struct GAPI_EXPORTS_W_SIMPLE GNetPackage { - GAPI_WRAP GNetPackage() = default; - GAPI_WRAP explicit GNetPackage(std::vector nets); - explicit GNetPackage(std::initializer_list ii); - std::vector backends() const; - std::vector networks; -}; -/** @} gapi_compile_args */ -} // namespace gapi - -namespace detail { -template -gapi::GNetParam strip(T&& t) { - return gapi::GNetParam { t.tag() - , t.backend() - , t.params() - }; -} - -template<> struct CompileArgTag { - static const char* tag() { return "gapi.net_package"; } -}; - -} // namespace cv::detail - -namespace gapi { -template -cv::gapi::GNetPackage networks(Args&&... args) { - return cv::gapi::GNetPackage({ cv::detail::strip(args)... }); -} - -inline cv::gapi::GNetPackage& operator += ( cv::gapi::GNetPackage& lhs, - const cv::gapi::GNetPackage& rhs) { - lhs.networks.reserve(lhs.networks.size() + rhs.networks.size()); - lhs.networks.insert(lhs.networks.end(), rhs.networks.begin(), rhs.networks.end()); - return lhs; -} - -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_INFER_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019-2021 Intel Corporation + + +#ifndef OPENCV_GAPI_INFER_HPP +#define OPENCV_GAPI_INFER_HPP + +// FIXME: Inference API is currently only available in full mode +#if !defined(GAPI_STANDALONE) + +#include +#include // string +#include // tuple +#include // is_same, false_type + +#include // all_satisfy +#include // any<> +#include // GKernelType[M], GBackend +#include // GArg +#include // CompileArgTag +#include // GMetaArg + +namespace cv { + +template class GNetworkType; + +namespace detail { + +// Infer /////////////////////////////////////////////////////////////////////// +template +struct accepted_infer_types { + static constexpr const auto value = + std::is_same::type, cv::GMat>::value + || std::is_same::type, cv::GFrame>::value; +}; + +template +using valid_infer_types = all_satisfy; + +// Infer2 ////////////////////////////////////////////////////////////////////// + +template +struct valid_infer2_types; + +// Terminal case 1 (50/50 success) +template +struct valid_infer2_types< std::tuple, std::tuple > { + // By default, Nets are limited to GMat argument types only + // for infer2, every GMat argument may translate to either + // GArray or GArray. GArray<> part is stripped + // already at this point. + static constexpr const auto value = + std::is_same::type, cv::GMat>::value + || std::is_same::type, cv::Rect>::value; +}; + +// Terminal case 2 (100% failure) +template +struct valid_infer2_types< std::tuple<>, std::tuple > + : public std::false_type { +}; + +// Terminal case 3 (100% failure) +template +struct valid_infer2_types< std::tuple, std::tuple<> > + : public std::false_type { +}; + +// Recursion -- generic +template +struct valid_infer2_types< std::tuple, std::tuple > { + static constexpr const auto value = + valid_infer2_types< std::tuple, std::tuple >::value + && valid_infer2_types< std::tuple, std::tuple >::value; +}; + +// Struct stores network input/output names. +// Used by infer +struct InOutInfo +{ + std::vector in_names; + std::vector out_names; +}; + +template +class GInferOutputsTyped +{ +public: + GInferOutputsTyped() = default; + GInferOutputsTyped(std::shared_ptr call) + : m_priv(std::make_shared(std::move(call))) + { + } + + OutT at(const std::string& name) + { + auto it = m_priv->blobs.find(name); + if (it == m_priv->blobs.end()) { + // FIXME: Avoid modifying GKernel + auto shape = cv::detail::GTypeTraits::shape; + auto kind = cv::detail::GTypeTraits::op_kind; + m_priv->call->kernel().outShapes.push_back(shape); + m_priv->call->kernel().outCtors.emplace_back(cv::detail::GObtainCtor::get()); + m_priv->call->kernel().outKinds.emplace_back(kind); + auto out_idx = static_cast(m_priv->blobs.size()); + it = m_priv->blobs.emplace(name, + cv::detail::Yield::yield(*(m_priv->call), out_idx)).first; + m_priv->info->out_names.push_back(name); + } + return it->second; + } +private: + struct Priv + { + Priv(std::shared_ptr c) + : call(std::move(c)), info(cv::util::any_cast(&call->params())) + { + } + + std::shared_ptr call; + InOutInfo* info = nullptr; + std::unordered_map blobs; + }; + + std::shared_ptr m_priv; +}; + +template +class GInferInputsTyped +{ +public: + GInferInputsTyped() + : m_priv(std::make_shared()) + { + } + + template + GInferInputsTyped& setInput(const std::string& name, U in) + { + m_priv->blobs.emplace(std::piecewise_construct, + std::forward_as_tuple(name), + std::forward_as_tuple(in)); + return *this; + } + + using StorageT = cv::util::variant; + StorageT& operator[](const std::string& name) { + return m_priv->blobs[name]; + } + + using Map = std::unordered_map; + const Map& getBlobs() const { + return m_priv->blobs; + } + +private: + struct Priv + { + std::unordered_map blobs; + }; + + std::shared_ptr m_priv; +}; + +template +std::shared_ptr makeCall(const std::string &tag, + std::vector &&args, + std::vector &&names, + cv::GKinds &&kinds) { + auto call = std::make_shared(GKernel{ + InferT::id(), + tag, + InferT::getOutMeta, + {}, // outShape will be filled later + std::move(kinds), + {}, // outCtors will be filled later + {}, // outKinds will be filled later + }); + + call->setArgs(std::move(args)); + call->params() = cv::detail::InOutInfo{std::move(names), {}}; + + return call; +} + +} // namespace detail + +// TODO: maybe tuple_wrap_helper from util.hpp may help with this. +// Multiple-return-value network definition (specialized base class) +template +class GNetworkType(Args...)> > +{ +public: + using InArgs = std::tuple; + using OutArgs = std::tuple; + + using Result = OutArgs; + using API = std::function; + + using ResultL = std::tuple< cv::GArray... >; +}; + +// Single-return-value network definition (specialized base class) +template +class GNetworkType > +{ +public: + using InArgs = std::tuple; + using OutArgs = std::tuple; + + using Result = R; + using API = std::function; + + using ResultL = cv::GArray; +}; + +// InferAPI: Accepts either GMat or GFrame for very individual network's input +template +struct InferAPI { + using type = typename std::enable_if + < detail::valid_infer_types::value + && std::tuple_size::value == sizeof...(Ts) + , std::function + >::type; +}; + +// InferAPIRoi: Accepts a rectangle and either GMat or GFrame +template +struct InferAPIRoi { + using type = typename std::enable_if + < detail::valid_infer_types::value + && std::tuple_size::value == 1u + , std::function, T)> + >::type; +}; + +// InferAPIList: Accepts a list of rectangles and list of GMat/GFrames; +// crops every input. +template +struct InferAPIList { + using type = typename std::enable_if + < detail::valid_infer_types::value + && std::tuple_size::value == sizeof...(Ts) + , std::function, Ts...)> + >::type; +}; + +// APIList2 is also template to allow different calling options +// (GArray vs GArray per input) +template +struct InferAPIList2 { + using type = typename std::enable_if + < detail::valid_infer_types::value && + cv::detail::valid_infer2_types< typename Net::InArgs + , std::tuple >::value, + std::function...)> + >::type; +}; + +// Base "Infer" kernel. Note - for whatever network, kernel ID +// is always the same. Different inference calls are distinguished by +// network _tag_ (an extra field in GCall) +// +// getOutMeta is a stub callback collected by G-API kernel subsystem +// automatically. This is a rare case when this callback is defined by +// a particular backend, not by a network itself. +struct GInferBase { + static constexpr const char * id() { + return "org.opencv.dnn.infer"; // Universal stub + } + static GMetaArgs getOutMeta(const GMetaArgs &, const GArgs &) { + return GMetaArgs{}; // One more universal stub + } +}; + +// Base "InferROI" kernel. +// All notes from "Infer" kernel apply here as well. +struct GInferROIBase { + static constexpr const char * id() { + return "org.opencv.dnn.infer-roi"; // Universal stub + } + static GMetaArgs getOutMeta(const GMetaArgs &, const GArgs &) { + return GMetaArgs{}; // One more universal stub + } +}; + +// Base "Infer list" kernel. +// All notes from "Infer" kernel apply here as well. +struct GInferListBase { + static constexpr const char * id() { + return "org.opencv.dnn.infer-roi-list-1"; // Universal stub + } + static GMetaArgs getOutMeta(const GMetaArgs &, const GArgs &) { + return GMetaArgs{}; // One more universal stub + } +}; + +// Base "Infer list 2" kernel. +// All notes from "Infer" kernel apply here as well. +struct GInferList2Base { + static constexpr const char * id() { + return "org.opencv.dnn.infer-roi-list-2"; // Universal stub + } + static GMetaArgs getOutMeta(const GMetaArgs &, const GArgs &) { + return GMetaArgs{}; // One more universal stub + } +}; + +// A generic inference kernel. API (::on()) is fully defined by the Net +// template parameter. +// Acts as a regular kernel in graph (via KernelTypeMedium). +template +struct GInfer final + : public GInferBase + , public detail::KernelTypeMedium< GInfer + , typename InferAPI::type > { + using GInferBase::getOutMeta; // FIXME: name lookup conflict workaround? + + static constexpr const char* tag() { return Net::tag(); } +}; + +// A specific roi-inference kernel. API (::on()) is fixed here and +// verified against Net. +template +struct GInferROI final + : public GInferROIBase + , public detail::KernelTypeMedium< GInferROI + , typename InferAPIRoi::type > { + using GInferROIBase::getOutMeta; // FIXME: name lookup conflict workaround? + + static constexpr const char* tag() { return Net::tag(); } +}; + + +// A generic roi-list inference kernel. API (::on()) is derived from +// the Net template parameter (see more in infer<> overload). +template +struct GInferList final + : public GInferListBase + , public detail::KernelTypeMedium< GInferList + , typename InferAPIList::type > { + using GInferListBase::getOutMeta; // FIXME: name lookup conflict workaround? + + static constexpr const char* tag() { return Net::tag(); } +}; + +// An even more generic roi-list inference kernel. API (::on()) is +// derived from the Net template parameter (see more in infer<> +// overload). +// Takes an extra variadic template list to reflect how this network +// was called (with Rects or GMats as array parameters) +template +struct GInferList2 final + : public GInferList2Base + , public detail::KernelTypeMedium< GInferList2 + , typename InferAPIList2::type > { + using GInferList2Base::getOutMeta; // FIXME: name lookup conflict workaround? + + static constexpr const char* tag() { return Net::tag(); } +}; + +/** + * @brief G-API object used to collect network inputs + */ +using GInferInputs = cv::detail::GInferInputsTyped; + +/** + * @brief G-API object used to collect the list of network inputs + */ +using GInferListInputs = cv::detail::GInferInputsTyped, cv::GArray>; + +/** + * @brief G-API object used to collect network outputs + */ +using GInferOutputs = cv::detail::GInferOutputsTyped; + +/** + * @brief G-API object used to collect the list of network outputs + */ +using GInferListOutputs = cv::detail::GInferOutputsTyped>; + +namespace detail { +void inline unpackBlobs(const cv::GInferInputs::Map& blobs, + std::vector& args, + std::vector& names, + cv::GKinds& kinds) +{ + for (auto&& p : blobs) { + names.emplace_back(p.first); + switch (p.second.index()) { + case cv::GInferInputs::StorageT::index_of(): + args.emplace_back(cv::util::get(p.second)); + kinds.emplace_back(cv::detail::OpaqueKind::CV_MAT); + break; + case cv::GInferInputs::StorageT::index_of(): + args.emplace_back(cv::util::get(p.second)); + kinds.emplace_back(cv::detail::OpaqueKind::CV_UNKNOWN); + break; + default: + GAPI_Error("InternalError"); + } + } +} + +template +struct InferROITraits; + +template <> +struct InferROITraits +{ + using outType = cv::GInferOutputs; + using inType = cv::GOpaque; +}; + +template <> +struct InferROITraits +{ + using outType = cv::GInferListOutputs; + using inType = cv::GArray; +}; + +template +typename InferROITraits::outType +inferGenericROI(const std::string& tag, + const typename InferROITraits::inType& in, + const cv::GInferInputs& inputs) +{ + std::vector args; + std::vector names; + cv::GKinds kinds; + + args.emplace_back(in); + kinds.emplace_back(cv::detail::OpaqueKind::CV_RECT); + + unpackBlobs(inputs.getBlobs(), args, names, kinds); + + auto call = cv::detail::makeCall(tag, + std::move(args), + std::move(names), + std::move(kinds)); + + return {std::move(call)}; +} + +} // namespace detail +} // namespace cv + +// FIXME: Probably the signature makes a function/tuple/function round-trip +#define G_API_NET(Class, API, Tag) \ + struct Class final: public cv::GNetworkType { \ + static constexpr const char * tag() { return Tag; } \ + } + +namespace cv { +namespace gapi { + +/** @brief Calculates response for the specified network (template + * parameter) for the specified region in the source image. + * Currently expects a single-input network only. + * + * @tparam A network type defined with G_API_NET() macro. + * @param in input image where to take ROI from. + * @param roi an object describing the region of interest + * in the source image. May be calculated in the same graph dynamically. + * @return an object of return type as defined in G_API_NET(). + * If a network has multiple return values (defined with a tuple), a tuple of + * objects of appropriate type is returned. + * @sa G_API_NET() + */ +template +typename Net::Result infer(cv::GOpaque roi, T in) { + return GInferROI::on(roi, in); +} + +/** @brief Calculates responses for the specified network (template + * parameter) for every region in the source image. + * + * @tparam A network type defined with G_API_NET() macro. + * @param roi a list of rectangles describing regions of interest + * in the source image. Usually an output of object detector or tracker. + * @param args network's input parameters as specified in G_API_NET() macro. + * NOTE: verified to work reliably with 1-input topologies only. + * @return a list of objects of return type as defined in G_API_NET(). + * If a network has multiple return values (defined with a tuple), a tuple of + * GArray<> objects is returned with the appropriate types inside. + * @sa G_API_NET() + */ +template +typename Net::ResultL infer(cv::GArray roi, Args&&... args) { + return GInferList::on(roi, std::forward(args)...); +} + +/** @brief Calculates responses for the specified network (template + * parameter) for every region in the source image, extended version. + * + * @tparam A network type defined with G_API_NET() macro. + * @param image A source image containing regions of interest + * @param args GArray<> objects of cv::Rect or cv::GMat, one per every + * network input: + * - If a cv::GArray is passed, the appropriate + * regions are taken from `image` and preprocessed to this particular + * network input; + * - If a cv::GArray is passed, the underlying data traited + * as tensor (no automatic preprocessing happen). + * @return a list of objects of return type as defined in G_API_NET(). + * If a network has multiple return values (defined with a tuple), a tuple of + * GArray<> objects is returned with the appropriate types inside. + * @sa G_API_NET() + */ + +template +typename Net::ResultL infer2(T image, cv::GArray... args) { + // FIXME: Declared as "2" because in the current form it steals + // overloads from the regular infer + return GInferList2::on(image, args...); +} + +/** + * @brief Calculates response for the specified network (template + * parameter) given the input data. + * + * @tparam A network type defined with G_API_NET() macro. + * @param args network's input parameters as specified in G_API_NET() macro. + * @return an object of return type as defined in G_API_NET(). + * If a network has multiple return values (defined with a tuple), a tuple of + * objects of appropriate type is returned. + * @sa G_API_NET() + */ +template +typename Net::Result infer(Args&&... args) { + return GInfer::on(std::forward(args)...); +} + +/** + * @brief Generic network type: input and output layers are configured dynamically at runtime + * + * Unlike the network types defined with G_API_NET macro, this one + * doesn't fix number of network inputs and outputs at the compilation stage + * thus providing user with an opportunity to program them in runtime. + */ +struct Generic { }; + +/** + * @brief Calculates response for generic network + * + * @param tag a network tag + * @param inputs networks's inputs + * @return a GInferOutputs + */ +template cv::GInferOutputs +infer(const std::string& tag, const cv::GInferInputs& inputs) +{ + std::vector args; + std::vector names; + cv::GKinds kinds; + + cv::detail::unpackBlobs(inputs.getBlobs(), args, names, kinds); + + auto call = cv::detail::makeCall(tag, + std::move(args), + std::move(names), + std::move(kinds)); + + return cv::GInferOutputs{std::move(call)}; +} + +/** @brief Calculates response for the generic network + * for the specified region in the source image. + * Currently expects a single-input network only. + * + * @param tag a network tag + * @param roi a an object describing the region of interest + * in the source image. May be calculated in the same graph dynamically. + * @param inputs networks's inputs + * @return a cv::GInferOutputs + */ +template cv::GInferOutputs +infer(const std::string& tag, const cv::GOpaque& roi, const cv::GInferInputs& inputs) +{ + return cv::detail::inferGenericROI(tag, roi, inputs); +} + +/** @brief Calculates responses for the specified network + * for every region in the source image. + * + * @param tag a network tag + * @param rois a list of rectangles describing regions of interest + * in the source image. Usually an output of object detector or tracker. + * @param inputs networks's inputs + * @return a cv::GInferListOutputs + */ +template cv::GInferListOutputs +infer(const std::string& tag, const cv::GArray& rois, const cv::GInferInputs& inputs) +{ + return cv::detail::inferGenericROI(tag, rois, inputs); +} + +/** @brief Calculates responses for the specified network + * for every region in the source image, extended version. + * + * @param tag a network tag + * @param in a source image containing regions of interest. + * @param inputs networks's inputs + * @return a cv::GInferListOutputs + */ +template +typename std::enable_if::value, cv::GInferListOutputs>::type +infer2(const std::string& tag, + const Input& in, + const cv::GInferListInputs& inputs) +{ + std::vector args; + std::vector names; + cv::GKinds kinds; + + args.emplace_back(in); + auto k = cv::detail::GOpaqueTraits::kind; + kinds.emplace_back(k); + + for (auto&& p : inputs.getBlobs()) { + names.emplace_back(p.first); + switch (p.second.index()) { + case cv::GInferListInputs::StorageT::index_of>(): + args.emplace_back(cv::util::get>(p.second)); + kinds.emplace_back(cv::detail::OpaqueKind::CV_MAT); + break; + case cv::GInferListInputs::StorageT::index_of>(): + args.emplace_back(cv::util::get>(p.second)); + kinds.emplace_back(cv::detail::OpaqueKind::CV_RECT); + break; + default: + GAPI_Error("InternalError"); + } + } + + auto call = cv::detail::makeCall(tag, + std::move(args), + std::move(names), + std::move(kinds)); + + return cv::GInferListOutputs{std::move(call)}; +} + +} // namespace gapi +} // namespace cv + +#endif // GAPI_STANDALONE + +namespace cv { +namespace gapi { + +// Note: the below code _is_ part of STANDALONE build, +// just to make our compiler code compileable. + +// A type-erased form of network parameters. +// Similar to how a type-erased GKernel is represented and used. +/// @private +struct GAPI_EXPORTS_W_SIMPLE GNetParam { + std::string tag; // FIXME: const? + GBackend backend; // Specifies the execution model + util::any params; // Backend-interpreted parameter structure +}; + +/** \addtogroup gapi_compile_args + * @{ + */ +/** + * @brief A container class for network configurations. Similar to + * GKernelPackage. Use cv::gapi::networks() to construct this object. + * + * @sa cv::gapi::networks + */ +struct GAPI_EXPORTS_W_SIMPLE GNetPackage { + GAPI_WRAP GNetPackage() = default; + GAPI_WRAP explicit GNetPackage(std::vector nets); + explicit GNetPackage(std::initializer_list ii); + std::vector backends() const; + std::vector networks; +}; +/** @} gapi_compile_args */ +} // namespace gapi + +namespace detail { +template +gapi::GNetParam strip(T&& t) { + return gapi::GNetParam { t.tag() + , t.backend() + , t.params() + }; +} + +template<> struct CompileArgTag { + static const char* tag() { return "gapi.net_package"; } +}; + +} // namespace cv::detail + +namespace gapi { +template +cv::gapi::GNetPackage networks(Args&&... args) { + return cv::gapi::GNetPackage({ cv::detail::strip(args)... }); +} + +inline cv::gapi::GNetPackage& operator += ( cv::gapi::GNetPackage& lhs, + const cv::gapi::GNetPackage& rhs) { + lhs.networks.reserve(lhs.networks.size() + rhs.networks.size()); + lhs.networks.insert(lhs.networks.end(), rhs.networks.begin(), rhs.networks.end()); + return lhs; +} + +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_INFER_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/bindings_ie.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/bindings_ie.hpp index 94272dea55..c2416f388c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/bindings_ie.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/bindings_ie.hpp @@ -1,70 +1,70 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020 Intel Corporation - -#ifndef OPENCV_GAPI_INFER_BINDINGS_IE_HPP -#define OPENCV_GAPI_INFER_BINDINGS_IE_HPP - -#include -#include "opencv2/gapi/own/exports.hpp" // GAPI_EXPORTS -#include // GKernelPackage -#include // Params - -#include - -namespace cv { -namespace gapi { -namespace ie { - -// NB: Used by python wrapper -// This class can be marked as SIMPLE, because it's implemented as pimpl -class GAPI_EXPORTS_W_SIMPLE PyParams { -public: - GAPI_WRAP - PyParams() = default; - - GAPI_WRAP - PyParams(const std::string &tag, - const std::string &model, - const std::string &weights, - const std::string &device); - - GAPI_WRAP - PyParams(const std::string &tag, - const std::string &model, - const std::string &device); - - GAPI_WRAP - PyParams& constInput(const std::string &layer_name, - const cv::Mat &data, - TraitAs hint = TraitAs::TENSOR); - - GAPI_WRAP - PyParams& cfgNumRequests(size_t nireq); - - GAPI_WRAP - PyParams& cfgBatchSize(const size_t size); - - GBackend backend() const; - std::string tag() const; - cv::util::any params() const; - -private: - std::shared_ptr> m_priv; -}; - -GAPI_EXPORTS_W PyParams params(const std::string &tag, - const std::string &model, - const std::string &weights, - const std::string &device); - -GAPI_EXPORTS_W PyParams params(const std::string &tag, - const std::string &model, - const std::string &device); -} // namespace ie -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_INFER_BINDINGS_IE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020 Intel Corporation + +#ifndef OPENCV_GAPI_INFER_BINDINGS_IE_HPP +#define OPENCV_GAPI_INFER_BINDINGS_IE_HPP + +#include +#include "opencv2/gapi/own/exports.hpp" // GAPI_EXPORTS +#include // GKernelPackage +#include // Params + +#include + +namespace cv { +namespace gapi { +namespace ie { + +// NB: Used by python wrapper +// This class can be marked as SIMPLE, because it's implemented as pimpl +class GAPI_EXPORTS_W_SIMPLE PyParams { +public: + GAPI_WRAP + PyParams() = default; + + GAPI_WRAP + PyParams(const std::string &tag, + const std::string &model, + const std::string &weights, + const std::string &device); + + GAPI_WRAP + PyParams(const std::string &tag, + const std::string &model, + const std::string &device); + + GAPI_WRAP + PyParams& constInput(const std::string &layer_name, + const cv::Mat &data, + TraitAs hint = TraitAs::TENSOR); + + GAPI_WRAP + PyParams& cfgNumRequests(size_t nireq); + + GAPI_WRAP + PyParams& cfgBatchSize(const size_t size); + + GBackend backend() const; + std::string tag() const; + cv::util::any params() const; + +private: + std::shared_ptr> m_priv; +}; + +GAPI_EXPORTS_W PyParams params(const std::string &tag, + const std::string &model, + const std::string &weights, + const std::string &device); + +GAPI_EXPORTS_W PyParams params(const std::string &tag, + const std::string &model, + const std::string &device); +} // namespace ie +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_INFER_BINDINGS_IE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/bindings_onnx.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/bindings_onnx.hpp index f7bb259924..4fa0a8db64 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/bindings_onnx.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/bindings_onnx.hpp @@ -1,74 +1,74 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level -// directory of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_GAPI_INFER_BINDINGS_ONNX_HPP -#define OPENCV_GAPI_INFER_BINDINGS_ONNX_HPP - -#include // GKernelPackage -#include // Params -#include "opencv2/gapi/own/exports.hpp" // GAPI_EXPORTS -#include - -#include - -namespace cv { -namespace gapi { -namespace onnx { - -// NB: Used by python wrapper -// This class can be marked as SIMPLE, because it's implemented as pimpl -class GAPI_EXPORTS_W_SIMPLE PyParams { -public: - GAPI_WRAP - PyParams() = default; - - GAPI_WRAP - PyParams(const std::string& tag, const std::string& model_path); - - GAPI_WRAP - PyParams& cfgMeanStd(const std::string &layer_name, - const cv::Scalar &m, - const cv::Scalar &s); - GAPI_WRAP - PyParams& cfgNormalize(const std::string &layer_name, bool flag); - - GAPI_WRAP - PyParams& cfgAddExecutionProvider(ep::OpenVINO ep); - - GAPI_WRAP - PyParams& cfgAddExecutionProvider(ep::DirectML ep); - - GAPI_WRAP - PyParams& cfgAddExecutionProvider(ep::CoreML ep); - - GAPI_WRAP - PyParams& cfgAddExecutionProvider(ep::CUDA ep); - - GAPI_WRAP - PyParams& cfgAddExecutionProvider(ep::TensorRT ep); - - GAPI_WRAP - PyParams& cfgDisableMemPattern(); - - GAPI_WRAP - PyParams& cfgSessionOptions(const std::map& options); - - GAPI_WRAP - PyParams& cfgOptLevel(const int opt_level); - - GBackend backend() const; - std::string tag() const; - cv::util::any params() const; - -private: - std::shared_ptr> m_priv; -}; - -GAPI_EXPORTS_W PyParams params(const std::string& tag, const std::string& model_path); - -} // namespace onnx -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_INFER_BINDINGS_ONNX_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level +// directory of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_GAPI_INFER_BINDINGS_ONNX_HPP +#define OPENCV_GAPI_INFER_BINDINGS_ONNX_HPP + +#include // GKernelPackage +#include // Params +#include "opencv2/gapi/own/exports.hpp" // GAPI_EXPORTS +#include + +#include + +namespace cv { +namespace gapi { +namespace onnx { + +// NB: Used by python wrapper +// This class can be marked as SIMPLE, because it's implemented as pimpl +class GAPI_EXPORTS_W_SIMPLE PyParams { +public: + GAPI_WRAP + PyParams() = default; + + GAPI_WRAP + PyParams(const std::string& tag, const std::string& model_path); + + GAPI_WRAP + PyParams& cfgMeanStd(const std::string &layer_name, + const cv::Scalar &m, + const cv::Scalar &s); + GAPI_WRAP + PyParams& cfgNormalize(const std::string &layer_name, bool flag); + + GAPI_WRAP + PyParams& cfgAddExecutionProvider(ep::OpenVINO ep); + + GAPI_WRAP + PyParams& cfgAddExecutionProvider(ep::DirectML ep); + + GAPI_WRAP + PyParams& cfgAddExecutionProvider(ep::CoreML ep); + + GAPI_WRAP + PyParams& cfgAddExecutionProvider(ep::CUDA ep); + + GAPI_WRAP + PyParams& cfgAddExecutionProvider(ep::TensorRT ep); + + GAPI_WRAP + PyParams& cfgDisableMemPattern(); + + GAPI_WRAP + PyParams& cfgSessionOptions(const std::map& options); + + GAPI_WRAP + PyParams& cfgOptLevel(const int opt_level); + + GBackend backend() const; + std::string tag() const; + cv::util::any params() const; + +private: + std::shared_ptr> m_priv; +}; + +GAPI_EXPORTS_W PyParams params(const std::string& tag, const std::string& model_path); + +} // namespace onnx +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_INFER_BINDINGS_ONNX_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/bindings_ov.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/bindings_ov.hpp index 08f5c83a3f..5cf371f1f2 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/bindings_ov.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/bindings_ov.hpp @@ -1,128 +1,128 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2023 Intel Corporation - -#ifndef OPENCV_GAPI_INFER_BINDINGS_OV_HPP -#define OPENCV_GAPI_INFER_BINDINGS_OV_HPP - -#include -#include "opencv2/gapi/own/exports.hpp" // GAPI_EXPORTS -#include // GKernelPackage -#include // Params - -#include - -namespace cv { -namespace gapi { -namespace ov { - -// NB: Used by python wrapper -// This class can be marked as SIMPLE, because it's implemented as pimpl -class GAPI_EXPORTS_W_SIMPLE PyParams { -public: - GAPI_WRAP - PyParams() = default; - - GAPI_WRAP - PyParams(const std::string &tag, - const std::string &model_path, - const std::string &bin_path, - const std::string &device); - - GAPI_WRAP - PyParams(const std::string &tag, - const std::string &blob_path, - const std::string &device); - - GAPI_WRAP - PyParams& cfgPluginConfig( - const std::map &config); - - GAPI_WRAP - PyParams& cfgInputTensorLayout(std::string tensor_layout); - - GAPI_WRAP - PyParams& cfgInputTensorLayout( - std::map layout_map); - - GAPI_WRAP - PyParams& cfgInputModelLayout(std::string tensor_layout); - - GAPI_WRAP - PyParams& cfgInputModelLayout( - std::map layout_map); - - GAPI_WRAP - PyParams& cfgOutputTensorLayout(std::string tensor_layout); - - GAPI_WRAP - PyParams& cfgOutputTensorLayout( - std::map layout_map); - - GAPI_WRAP - PyParams& cfgOutputModelLayout(std::string tensor_layout); - - GAPI_WRAP - PyParams& cfgOutputModelLayout( - std::map layout_map); - - GAPI_WRAP - PyParams& cfgOutputTensorPrecision(int precision); - - GAPI_WRAP - PyParams& cfgOutputTensorPrecision( - std::map precision_map); - - GAPI_WRAP - PyParams& cfgReshape(std::vector new_shape); - - GAPI_WRAP - PyParams& cfgReshape( - std::map> new_shape_map); - - GAPI_WRAP - PyParams& cfgNumRequests(const size_t nireq); - - GAPI_WRAP - PyParams& cfgMean(std::vector mean_values); - - GAPI_WRAP - PyParams& cfgMean( - std::map> mean_map); - - GAPI_WRAP - PyParams& cfgScale(std::vector scale_values); - - GAPI_WRAP - PyParams& cfgScale( - std::map> scale_map); - - GAPI_WRAP - PyParams& cfgResize(int interpolation); - - GAPI_WRAP - PyParams& cfgResize(std::map interpolation); - - GBackend backend() const; - std::string tag() const; - cv::util::any params() const; - -private: - std::shared_ptr> m_priv; -}; - -GAPI_EXPORTS_W PyParams params(const std::string &tag, - const std::string &model_path, - const std::string &weights, - const std::string &device); - -GAPI_EXPORTS_W PyParams params(const std::string &tag, - const std::string &bin_path, - const std::string &device); -} // namespace ov -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_INFER_BINDINGS_OV_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2023 Intel Corporation + +#ifndef OPENCV_GAPI_INFER_BINDINGS_OV_HPP +#define OPENCV_GAPI_INFER_BINDINGS_OV_HPP + +#include +#include "opencv2/gapi/own/exports.hpp" // GAPI_EXPORTS +#include // GKernelPackage +#include // Params + +#include + +namespace cv { +namespace gapi { +namespace ov { + +// NB: Used by python wrapper +// This class can be marked as SIMPLE, because it's implemented as pimpl +class GAPI_EXPORTS_W_SIMPLE PyParams { +public: + GAPI_WRAP + PyParams() = default; + + GAPI_WRAP + PyParams(const std::string &tag, + const std::string &model_path, + const std::string &bin_path, + const std::string &device); + + GAPI_WRAP + PyParams(const std::string &tag, + const std::string &blob_path, + const std::string &device); + + GAPI_WRAP + PyParams& cfgPluginConfig( + const std::map &config); + + GAPI_WRAP + PyParams& cfgInputTensorLayout(std::string tensor_layout); + + GAPI_WRAP + PyParams& cfgInputTensorLayout( + std::map layout_map); + + GAPI_WRAP + PyParams& cfgInputModelLayout(std::string tensor_layout); + + GAPI_WRAP + PyParams& cfgInputModelLayout( + std::map layout_map); + + GAPI_WRAP + PyParams& cfgOutputTensorLayout(std::string tensor_layout); + + GAPI_WRAP + PyParams& cfgOutputTensorLayout( + std::map layout_map); + + GAPI_WRAP + PyParams& cfgOutputModelLayout(std::string tensor_layout); + + GAPI_WRAP + PyParams& cfgOutputModelLayout( + std::map layout_map); + + GAPI_WRAP + PyParams& cfgOutputTensorPrecision(int precision); + + GAPI_WRAP + PyParams& cfgOutputTensorPrecision( + std::map precision_map); + + GAPI_WRAP + PyParams& cfgReshape(std::vector new_shape); + + GAPI_WRAP + PyParams& cfgReshape( + std::map> new_shape_map); + + GAPI_WRAP + PyParams& cfgNumRequests(const size_t nireq); + + GAPI_WRAP + PyParams& cfgMean(std::vector mean_values); + + GAPI_WRAP + PyParams& cfgMean( + std::map> mean_map); + + GAPI_WRAP + PyParams& cfgScale(std::vector scale_values); + + GAPI_WRAP + PyParams& cfgScale( + std::map> scale_map); + + GAPI_WRAP + PyParams& cfgResize(int interpolation); + + GAPI_WRAP + PyParams& cfgResize(std::map interpolation); + + GBackend backend() const; + std::string tag() const; + cv::util::any params() const; + +private: + std::shared_ptr> m_priv; +}; + +GAPI_EXPORTS_W PyParams params(const std::string &tag, + const std::string &model_path, + const std::string &weights, + const std::string &device); + +GAPI_EXPORTS_W PyParams params(const std::string &tag, + const std::string &bin_path, + const std::string &device); +} // namespace ov +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_INFER_BINDINGS_OV_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/ie.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/ie.hpp index 9f9518d0b8..4552d2db34 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/ie.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/ie.hpp @@ -1,711 +1,711 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019-2023 Intel Corporation - -#ifndef OPENCV_GAPI_INFER_IE_HPP -#define OPENCV_GAPI_INFER_IE_HPP - -#include -#include -#include -#include -#include // tuple, tuple_size -#include - -#include -#include - -#include // GAPI_EXPORTS -#include // GKernelPackage -#include // Generic -#include // Preproc Dev & Ctx - -namespace cv { -namespace gapi { -// FIXME: introduce a new sub-namespace for NN? - -/** - * @brief This namespace contains G-API OpenVINO backend functions, - * structures, and symbols. - */ -namespace ie { - -GAPI_EXPORTS cv::gapi::GBackend backend(); - -/** - * Specifies how G-API and IE should trait input data - * - * In OpenCV, the same cv::Mat is used to represent both - * image and tensor data. Sometimes those are hardly distinguishable, - * so this extra parameter is used to give G-API a hint. - * - * This hint controls how G-API reinterprets the data when converting - * it to IE Blob format (and which layout/etc is assigned to this data). - */ -enum class TraitAs: int -{ - TENSOR, //!< G-API traits an associated cv::Mat as a raw tensor and passes dimensions as-is - IMAGE //!< G-API traits an associated cv::Mat as an image so creates an "image" blob (NCHW/NHWC, etc) -}; - -using IEConfig = std::map; - -enum InferMode {Sync, Async}; - -namespace detail { - -template -using AttrMap = std::map; -// NB: This type is used to hold in/out layers -// attributes such as precision, layout, shape etc. -// -// User can provide attributes either: -// 1. cv::util::monostate - No value specified explicitly. -// 2. Attr - value specified explicitly that should be broadcasted to all layers. -// 3. AttrMap[str->T] - map specifies value for particular layer. -template -using LayerVariantAttr = cv::util::variant< cv::util::monostate - , AttrMap - , Attr>; - -struct ParamDesc { - std::string model_path; - std::string weights_path; - std::string device_id; - - std::vector input_names; - std::vector output_names; - - using ConstInput = std::pair; - std::unordered_map const_inputs; - - std::size_t num_in; - std::size_t num_out; - - enum class Kind {Load, Import}; - Kind kind; - bool is_generic; - IEConfig config; - - std::map> reshape_table; - std::unordered_set layer_names_to_reshape; - - // NB: Number of asyncrhonious infer requests - size_t nireq; - - // NB: An optional config to setup RemoteContext for IE - cv::util::any context_config; - - // NB: batch_size can't be equal to 1 by default, because some of models - // have 2D (Layout::NC) input and if the first dimension not equal to 1 - // net.setBatchSize(1) will overwrite it. - cv::optional batch_size; - - cv::optional vpl_preproc_device; - cv::optional vpl_preproc_ctx; - - InferMode mode; - - using PrecisionT = int; - using PrecisionMapT = std::unordered_map; - // NB: This parameter can contain: - // 1. cv::util::monostate - Don't specify precision, but use default from IR/Blob. - // 2. PrecisionT (CV_8U, CV_32F, ...) - Specifies precision for all output layers. - // 3. PrecisionMapT ({{"layer0", CV_32F}, {"layer1", CV_16F}} - Specifies precision for certain output layer. - // cv::util::monostate is default value that means precision wasn't specified. - using PrecisionVariantT = cv::util::variant; - - PrecisionVariantT output_precision; - LayerVariantAttr input_layout; - LayerVariantAttr output_layout; - LayerVariantAttr interpolation; -}; -} // namespace detail - -// FIXME: this is probably a shared (reusable) thing -template -struct PortCfg { - using In = std::array - < std::string - , std::tuple_size::value >; - using Out = std::array - < std::string - , std::tuple_size::value >; -}; - -/** - * @brief This structure provides functions - * that fill inference parameters for "OpenVINO Toolkit" model. - */ -template class Params { -public: - /** @brief Class constructor. - - Constructs Params based on model information and specifies default values for other - inference description parameters. Model is loaded and compiled using "OpenVINO Toolkit". - - @param model Path to topology IR (.xml file). - @param weights Path to weights (.bin file). - @param device target device to use. - */ - Params(const std::string &model, - const std::string &weights, - const std::string &device) - : desc{ model, weights, device, {}, {}, {} - , std::tuple_size::value // num_in - , std::tuple_size::value // num_out - , detail::ParamDesc::Kind::Load - , false - , {} - , {} - , {} - , 1u - , {} - , {} - , {} - , {} - , InferMode::Async - , {} - , {} - , {} - , {} } { - } - - /** @overload - Use this constructor to work with pre-compiled network. - Model is imported from a pre-compiled blob. - - @param model Path to model. - @param device target device to use. - */ - Params(const std::string &model, - const std::string &device) - : desc{ model, {}, device, {}, {}, {} - , std::tuple_size::value // num_in - , std::tuple_size::value // num_out - , detail::ParamDesc::Kind::Import - , false - , {} - , {} - , {} - , 1u - , {} - , {} - , {} - , {} - , InferMode::Async - , {} - , {} - , {} - , {} } { - } - - /** @brief Specifies sequence of network input layers names for inference. - - The function is used to associate cv::gapi::infer<> inputs with the model inputs. - Number of names has to match the number of network inputs as defined in G_API_NET(). - In case a network has only single input layer, there is no need to specify name manually. - - @param layer_names std::array where N is the number of inputs - as defined in the @ref G_API_NET. Contains names of input layers. - @return reference to this parameter structure. - */ - Params& cfgInputLayers(const typename PortCfg::In &layer_names) { - desc.input_names.clear(); - desc.input_names.reserve(layer_names.size()); - std::copy(layer_names.begin(), layer_names.end(), - std::back_inserter(desc.input_names)); - return *this; - } - - /** @brief Specifies sequence of network output layers names for inference. - - The function is used to associate cv::gapi::infer<> outputs with the model outputs. - Number of names has to match the number of network outputs as defined in G_API_NET(). - In case a network has only single output layer, there is no need to specify name manually. - - @param layer_names std::array where N is the number of outputs - as defined in the @ref G_API_NET. Contains names of output layers. - @return reference to this parameter structure. - */ - Params& cfgOutputLayers(const typename PortCfg::Out &layer_names) { - desc.output_names.clear(); - desc.output_names.reserve(layer_names.size()); - std::copy(layer_names.begin(), layer_names.end(), - std::back_inserter(desc.output_names)); - return *this; - } - - /** @brief Specifies a constant input. - - The function is used to set a constant input. This input has to be - a preprocessed tensor if its type is TENSOR. Need to provide name of the - network layer which will receive provided data. - - @param layer_name Name of network layer. - @param data cv::Mat that contains data which will be associated with network layer. - @param hint Input type @sa cv::gapi::ie::TraitAs. - @return reference to this parameter structure. - */ - Params& constInput(const std::string &layer_name, - const cv::Mat &data, - TraitAs hint = TraitAs::TENSOR) { - desc.const_inputs[layer_name] = {data, hint}; - return *this; - } - - /** @brief Specifies OpenVINO plugin configuration. - - The function is used to set configuration for OpenVINO plugin. Some parameters - can be different for each plugin. Please follow https://docs.openvinotoolkit.org/latest/index.html - to check information about specific plugin. - - @param cfg Map of pairs: (config parameter name, config parameter value). - @return reference to this parameter structure. - */ - Params& pluginConfig(const IEConfig& cfg) { - desc.config = cfg; - return *this; - } - - /** @overload - Function with a rvalue parameter. - - @param cfg rvalue map of pairs: (config parameter name, config parameter value). - @return reference to this parameter structure. - */ - Params& pluginConfig(IEConfig&& cfg) { - desc.config = std::move(cfg); - return *this; - } - - /** @brief Specifies configuration for RemoteContext in InferenceEngine. - - When RemoteContext is configured the backend imports the networks using the context. - It also expects cv::MediaFrames to be actually remote, to operate with blobs via the context. - - @param ctx_cfg cv::util::any value which holds InferenceEngine::ParamMap. - @return reference to this parameter structure. - */ - Params& cfgContextParams(const cv::util::any& ctx_cfg) { - desc.context_config = ctx_cfg; - return *this; - } - - /** @overload - Function with an rvalue parameter. - - @param ctx_cfg cv::util::any value which holds InferenceEngine::ParamMap. - @return reference to this parameter structure. - */ - Params& cfgContextParams(cv::util::any&& ctx_cfg) { - desc.context_config = std::move(ctx_cfg); - return *this; - } - - /** @brief Specifies number of asynchronous inference requests. - - @param nireq Number of inference asynchronous requests. - @return reference to this parameter structure. - */ - Params& cfgNumRequests(size_t nireq) { - GAPI_Assert(nireq > 0 && "Number of infer requests must be greater than zero!"); - desc.nireq = nireq; - return *this; - } - - /** @brief Specifies new input shapes for the network inputs. - - The function is used to specify new input shapes for the network inputs. - Follow https://docs.openvinotoolkit.org/latest/classInferenceEngine_1_1networkNetwork.html - for additional information. - - @param reshape_table Map of pairs: name of corresponding data and its dimension. - @return reference to this parameter structure. - */ - Params& cfgInputReshape(const std::map>& reshape_table) { - desc.reshape_table = reshape_table; - return *this; - } - - /** @overload */ - Params& cfgInputReshape(std::map>&& reshape_table) { - desc.reshape_table = std::move(reshape_table); - return *this; - } - - /** @overload - - @param layer_name Name of layer. - @param layer_dims New dimensions for this layer. - @return reference to this parameter structure. - */ - Params& cfgInputReshape(const std::string& layer_name, const std::vector& layer_dims) { - desc.reshape_table.emplace(layer_name, layer_dims); - return *this; - } - - /** @overload */ - Params& cfgInputReshape(std::string&& layer_name, std::vector&& layer_dims) { - desc.reshape_table.emplace(layer_name, layer_dims); - return *this; - } - - /** @overload - - @param layer_names set of names of network layers that will be used for network reshape. - @return reference to this parameter structure. - */ - Params& cfgInputReshape(const std::unordered_set& layer_names) { - desc.layer_names_to_reshape = layer_names; - return *this; - } - - /** @overload - - @param layer_names rvalue set of the selected layers will be reshaped automatically - its input image size. - @return reference to this parameter structure. - */ - Params& cfgInputReshape(std::unordered_set&& layer_names) { - desc.layer_names_to_reshape = std::move(layer_names); - return *this; - } - - /** @brief Specifies the inference batch size. - - The function is used to specify inference batch size. - Follow https://docs.openvinotoolkit.org/latest/classInferenceEngine_1_1CNNNetwork.html#a8e9d19270a48aab50cb5b1c43eecb8e9 for additional information - - @param size batch size which will be used. - @return reference to this parameter structure. - */ - Params& cfgBatchSize(const size_t size) { - desc.batch_size = cv::util::make_optional(size); - return *this; - } - - Params& cfgPreprocessingParams(const cv::gapi::wip::onevpl::Device &device, - const cv::gapi::wip::onevpl::Context &ctx) { - desc.vpl_preproc_device = cv::util::make_optional(device); - desc.vpl_preproc_ctx = cv::util::make_optional(ctx); - return *this; - } - - /** @brief Specifies which api will be used to run inference. - - The function is used to specify mode for OpenVINO inference. - OpenVINO has two options to run inference: - 1. Asynchronous (using StartAsync: https://docs.openvino.ai/latest/classInferenceEngine_1_1InferRequest.html#doxid-class-inference-engine-1-1-infer-request-1a405293e8423d82a5b45f642a3bef0d24) - 2. Synchronous (using Infer: https://docs.openvino.ai/latest/classInferenceEngine_1_1InferRequest.html#doxid-class-inference-engine-1-1-infer-request-1a3391ce30894abde730523e9ca9371ce8) - By default asynchronous mode is used. - - @param mode Inference mode which will be used. - @return reference to this parameter structure. - */ - Params& cfgInferMode(InferMode mode) { - desc.mode = mode; - return *this; - } - - /** @brief Specifies the output precision for model. - - The function is used to set an output precision for model. - - @param precision Precision in OpenCV format (CV_8U, CV_32F, ...) - will be applied to all output layers. - @return reference to this parameter structure. - */ - Params& cfgOutputPrecision(detail::ParamDesc::PrecisionT precision) { - desc.output_precision = precision; - return *this; - } - - /** @overload - - @param precision_map Map of pairs: name of corresponding output layer - and its precision in OpenCV format (CV_8U, CV_32F, ...) - @return reference to this parameter structure. - */ - Params& - cfgOutputPrecision(detail::ParamDesc::PrecisionMapT precision_map) { - desc.output_precision = precision_map; - return *this; - } - - /** @brief Specifies the input layout for model. - - The function is used to set an input layout for model. - - @param layout Layout in string representation ("NCHW", "NHWC", etc) - will be applied to all input layers. - @return reference to this parameter structure. - */ - Params& cfgInputLayout(std::string layout) { - desc.input_layout = std::move(layout); - return *this; - } - - /** @overload - - @param layout_map Map of pairs: name of corresponding input layer - and its layout in string representation ("NCHW", "NHWC", etc) - @return reference to this parameter structure. - */ - Params& - cfgInputLayout(detail::AttrMap layout_map) { - desc.input_layout = std::move(layout_map); - return *this; - } - - /** @brief Specifies the output layout for model. - - The function is used to set an output layout for model. - - @param layout Layout in string representation ("NCHW", "NHWC", etc) - will be applied to all output layers. - @return reference to this parameter structure. - */ - Params& cfgOutputLayout(std::string layout) { - desc.output_layout = std::move(layout); - return *this; - } - - /** @overload - - @param layout_map Map of pairs: name of corresponding output layer - and its layout in string representation ("NCHW", "NHWC", etc) - @return reference to this parameter structure. - */ - Params& - cfgOutputLayout(detail::AttrMap layout_map) { - desc.output_layout = std::move(layout_map); - return *this; - } - - /** @brief Specifies resize interpolation algorithm. - * - The function is used to configure resize preprocessing for input layer. - - @param interpolation Resize interpolation algorithm. - Supported algorithms: #INTER_LINEAR, #INTER_AREA. - @return reference to this parameter structure. - */ - Params& cfgResize(int interpolation) { - desc.interpolation = interpolation; - return *this; - } - - /** @overload - - @param interpolation Map of pairs: name of corresponding input layer - and its resize algorithm. - @return reference to this parameter structure. - */ - Params& cfgResize(detail::AttrMap interpolation) { - desc.interpolation = std::move(interpolation); - return *this; - } - - // BEGIN(G-API's network parametrization API) - GBackend backend() const { return cv::gapi::ie::backend(); } - std::string tag() const { return Net::tag(); } - cv::util::any params() const { return { desc }; } - // END(G-API's network parametrization API) - -protected: - detail::ParamDesc desc; -}; - -/* -* @brief This structure provides functions for generic network type that -* fill inference parameters. -* @see struct Generic -*/ -template<> -class Params { -public: - /** @brief Class constructor. - - Constructs Params based on model information and sets default values for other - inference description parameters. Model is loaded and compiled using OpenVINO Toolkit. - - @param tag string tag of the network for which these parameters are intended. - @param model path to topology IR (.xml file). - @param weights path to weights (.bin file). - @param device target device to use. - */ - Params(const std::string &tag, - const std::string &model, - const std::string &weights, - const std::string &device) - : desc{ model, weights, device, {}, {}, {}, 0u, 0u, - detail::ParamDesc::Kind::Load, true, {}, {}, {}, 1u, - {}, {}, {}, {}, InferMode::Async, {}, {}, {}, {} }, - m_tag(tag) { - } - - /** @overload - - This constructor for pre-compiled networks. Model is imported from pre-compiled - blob. - - @param tag string tag of the network for which these parameters are intended. - @param model path to model. - @param device target device to use. - */ - Params(const std::string &tag, - const std::string &model, - const std::string &device) - : desc{ model, {}, device, {}, {}, {}, 0u, 0u, - detail::ParamDesc::Kind::Import, true, {}, {}, {}, 1u, - {}, {}, {}, {}, InferMode::Async, {}, {}, {}, {} }, - m_tag(tag) { - } - - /** @see ie::Params::pluginConfig. */ - Params& pluginConfig(const IEConfig& cfg) { - desc.config = cfg; - return *this; - } - - /** @overload */ - Params& pluginConfig(IEConfig&& cfg) { - desc.config = std::move(cfg); - return *this; - } - - /** @see ie::Params::constInput. */ - Params& constInput(const std::string &layer_name, - const cv::Mat &data, - TraitAs hint = TraitAs::TENSOR) { - desc.const_inputs[layer_name] = {data, hint}; - return *this; - } - - /** @see ie::Params::cfgNumRequests. */ - Params& cfgNumRequests(size_t nireq) { - GAPI_Assert(nireq > 0 && "Number of infer requests must be greater than zero!"); - desc.nireq = nireq; - return *this; - } - - /** @see ie::Params::cfgInputReshape */ - Params& cfgInputReshape(const std::map>&reshape_table) { - desc.reshape_table = reshape_table; - return *this; - } - - /** @overload */ - Params& cfgInputReshape(std::map> && reshape_table) { - desc.reshape_table = std::move(reshape_table); - return *this; - } - - /** @overload */ - Params& cfgInputReshape(std::string && layer_name, std::vector && layer_dims) { - desc.reshape_table.emplace(layer_name, layer_dims); - return *this; - } - - /** @overload */ - Params& cfgInputReshape(const std::string & layer_name, const std::vector&layer_dims) { - desc.reshape_table.emplace(layer_name, layer_dims); - return *this; - } - - /** @overload */ - Params& cfgInputReshape(std::unordered_set && layer_names) { - desc.layer_names_to_reshape = std::move(layer_names); - return *this; - } - - /** @overload */ - Params& cfgInputReshape(const std::unordered_set&layer_names) { - desc.layer_names_to_reshape = layer_names; - return *this; - } - - /** @see ie::Params::cfgBatchSize */ - Params& cfgBatchSize(const size_t size) { - desc.batch_size = cv::util::make_optional(size); - return *this; - } - - /** @see ie::Params::cfgInferAPI */ - Params& cfgInferMode(InferMode mode) { - desc.mode = mode; - return *this; - } - - /** @see ie::Params::cfgOutputPrecision */ - Params& cfgOutputPrecision(detail::ParamDesc::PrecisionT precision) { - desc.output_precision = precision; - return *this; - } - - /** @overload */ - Params& - cfgOutputPrecision(detail::ParamDesc::PrecisionMapT precision_map) { - desc.output_precision = precision_map; - return *this; - } - - /** @see ie::Params::cfgInputLayout */ - Params& cfgInputLayout(std::string layout) { - desc.input_layout = std::move(layout); - return *this; - } - - /** @overload */ - Params& - cfgInputLayout(detail::AttrMap layout_map) { - desc.input_layout = std::move(layout_map); - return *this; - } - - /** @see ie::Params::cfgOutputLayout */ - Params& cfgOutputLayout(std::string layout) { - desc.output_layout = std::move(layout); - return *this; - } - - /** @overload */ - Params& - cfgOutputLayout(detail::AttrMap layout_map) { - desc.output_layout = std::move(layout_map); - return *this; - } - - /** @see ie::Params::cfgResize */ - Params& cfgResize(int interpolation) { - desc.interpolation = interpolation; - return *this; - } - - /** @overload */ - Params& cfgResize(detail::AttrMap interpolation) { - desc.interpolation = std::move(interpolation); - return *this; - } - - // BEGIN(G-API's network parametrization API) - GBackend backend() const { return cv::gapi::ie::backend(); } - std::string tag() const { return m_tag; } - cv::util::any params() const { return { desc }; } - // END(G-API's network parametrization API) - -protected: - detail::ParamDesc desc; - std::string m_tag; -}; - -} // namespace ie -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_INFER_IE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019-2023 Intel Corporation + +#ifndef OPENCV_GAPI_INFER_IE_HPP +#define OPENCV_GAPI_INFER_IE_HPP + +#include +#include +#include +#include +#include // tuple, tuple_size +#include + +#include +#include + +#include // GAPI_EXPORTS +#include // GKernelPackage +#include // Generic +#include // Preproc Dev & Ctx + +namespace cv { +namespace gapi { +// FIXME: introduce a new sub-namespace for NN? + +/** + * @brief This namespace contains G-API OpenVINO backend functions, + * structures, and symbols. + */ +namespace ie { + +GAPI_EXPORTS cv::gapi::GBackend backend(); + +/** + * Specifies how G-API and IE should trait input data + * + * In OpenCV, the same cv::Mat is used to represent both + * image and tensor data. Sometimes those are hardly distinguishable, + * so this extra parameter is used to give G-API a hint. + * + * This hint controls how G-API reinterprets the data when converting + * it to IE Blob format (and which layout/etc is assigned to this data). + */ +enum class TraitAs: int +{ + TENSOR, //!< G-API traits an associated cv::Mat as a raw tensor and passes dimensions as-is + IMAGE //!< G-API traits an associated cv::Mat as an image so creates an "image" blob (NCHW/NHWC, etc) +}; + +using IEConfig = std::map; + +enum InferMode {Sync, Async}; + +namespace detail { + +template +using AttrMap = std::map; +// NB: This type is used to hold in/out layers +// attributes such as precision, layout, shape etc. +// +// User can provide attributes either: +// 1. cv::util::monostate - No value specified explicitly. +// 2. Attr - value specified explicitly that should be broadcasted to all layers. +// 3. AttrMap[str->T] - map specifies value for particular layer. +template +using LayerVariantAttr = cv::util::variant< cv::util::monostate + , AttrMap + , Attr>; + +struct ParamDesc { + std::string model_path; + std::string weights_path; + std::string device_id; + + std::vector input_names; + std::vector output_names; + + using ConstInput = std::pair; + std::unordered_map const_inputs; + + std::size_t num_in; + std::size_t num_out; + + enum class Kind {Load, Import}; + Kind kind; + bool is_generic; + IEConfig config; + + std::map> reshape_table; + std::unordered_set layer_names_to_reshape; + + // NB: Number of asyncrhonious infer requests + size_t nireq; + + // NB: An optional config to setup RemoteContext for IE + cv::util::any context_config; + + // NB: batch_size can't be equal to 1 by default, because some of models + // have 2D (Layout::NC) input and if the first dimension not equal to 1 + // net.setBatchSize(1) will overwrite it. + cv::optional batch_size; + + cv::optional vpl_preproc_device; + cv::optional vpl_preproc_ctx; + + InferMode mode; + + using PrecisionT = int; + using PrecisionMapT = std::unordered_map; + // NB: This parameter can contain: + // 1. cv::util::monostate - Don't specify precision, but use default from IR/Blob. + // 2. PrecisionT (CV_8U, CV_32F, ...) - Specifies precision for all output layers. + // 3. PrecisionMapT ({{"layer0", CV_32F}, {"layer1", CV_16F}} - Specifies precision for certain output layer. + // cv::util::monostate is default value that means precision wasn't specified. + using PrecisionVariantT = cv::util::variant; + + PrecisionVariantT output_precision; + LayerVariantAttr input_layout; + LayerVariantAttr output_layout; + LayerVariantAttr interpolation; +}; +} // namespace detail + +// FIXME: this is probably a shared (reusable) thing +template +struct PortCfg { + using In = std::array + < std::string + , std::tuple_size::value >; + using Out = std::array + < std::string + , std::tuple_size::value >; +}; + +/** + * @brief This structure provides functions + * that fill inference parameters for "OpenVINO Toolkit" model. + */ +template class Params { +public: + /** @brief Class constructor. + + Constructs Params based on model information and specifies default values for other + inference description parameters. Model is loaded and compiled using "OpenVINO Toolkit". + + @param model Path to topology IR (.xml file). + @param weights Path to weights (.bin file). + @param device target device to use. + */ + Params(const std::string &model, + const std::string &weights, + const std::string &device) + : desc{ model, weights, device, {}, {}, {} + , std::tuple_size::value // num_in + , std::tuple_size::value // num_out + , detail::ParamDesc::Kind::Load + , false + , {} + , {} + , {} + , 1u + , {} + , {} + , {} + , {} + , InferMode::Async + , {} + , {} + , {} + , {} } { + } + + /** @overload + Use this constructor to work with pre-compiled network. + Model is imported from a pre-compiled blob. + + @param model Path to model. + @param device target device to use. + */ + Params(const std::string &model, + const std::string &device) + : desc{ model, {}, device, {}, {}, {} + , std::tuple_size::value // num_in + , std::tuple_size::value // num_out + , detail::ParamDesc::Kind::Import + , false + , {} + , {} + , {} + , 1u + , {} + , {} + , {} + , {} + , InferMode::Async + , {} + , {} + , {} + , {} } { + } + + /** @brief Specifies sequence of network input layers names for inference. + + The function is used to associate cv::gapi::infer<> inputs with the model inputs. + Number of names has to match the number of network inputs as defined in G_API_NET(). + In case a network has only single input layer, there is no need to specify name manually. + + @param layer_names std::array where N is the number of inputs + as defined in the @ref G_API_NET. Contains names of input layers. + @return reference to this parameter structure. + */ + Params& cfgInputLayers(const typename PortCfg::In &layer_names) { + desc.input_names.clear(); + desc.input_names.reserve(layer_names.size()); + std::copy(layer_names.begin(), layer_names.end(), + std::back_inserter(desc.input_names)); + return *this; + } + + /** @brief Specifies sequence of network output layers names for inference. + + The function is used to associate cv::gapi::infer<> outputs with the model outputs. + Number of names has to match the number of network outputs as defined in G_API_NET(). + In case a network has only single output layer, there is no need to specify name manually. + + @param layer_names std::array where N is the number of outputs + as defined in the @ref G_API_NET. Contains names of output layers. + @return reference to this parameter structure. + */ + Params& cfgOutputLayers(const typename PortCfg::Out &layer_names) { + desc.output_names.clear(); + desc.output_names.reserve(layer_names.size()); + std::copy(layer_names.begin(), layer_names.end(), + std::back_inserter(desc.output_names)); + return *this; + } + + /** @brief Specifies a constant input. + + The function is used to set a constant input. This input has to be + a preprocessed tensor if its type is TENSOR. Need to provide name of the + network layer which will receive provided data. + + @param layer_name Name of network layer. + @param data cv::Mat that contains data which will be associated with network layer. + @param hint Input type @sa cv::gapi::ie::TraitAs. + @return reference to this parameter structure. + */ + Params& constInput(const std::string &layer_name, + const cv::Mat &data, + TraitAs hint = TraitAs::TENSOR) { + desc.const_inputs[layer_name] = {data, hint}; + return *this; + } + + /** @brief Specifies OpenVINO plugin configuration. + + The function is used to set configuration for OpenVINO plugin. Some parameters + can be different for each plugin. Please follow https://docs.openvinotoolkit.org/latest/index.html + to check information about specific plugin. + + @param cfg Map of pairs: (config parameter name, config parameter value). + @return reference to this parameter structure. + */ + Params& pluginConfig(const IEConfig& cfg) { + desc.config = cfg; + return *this; + } + + /** @overload + Function with a rvalue parameter. + + @param cfg rvalue map of pairs: (config parameter name, config parameter value). + @return reference to this parameter structure. + */ + Params& pluginConfig(IEConfig&& cfg) { + desc.config = std::move(cfg); + return *this; + } + + /** @brief Specifies configuration for RemoteContext in InferenceEngine. + + When RemoteContext is configured the backend imports the networks using the context. + It also expects cv::MediaFrames to be actually remote, to operate with blobs via the context. + + @param ctx_cfg cv::util::any value which holds InferenceEngine::ParamMap. + @return reference to this parameter structure. + */ + Params& cfgContextParams(const cv::util::any& ctx_cfg) { + desc.context_config = ctx_cfg; + return *this; + } + + /** @overload + Function with an rvalue parameter. + + @param ctx_cfg cv::util::any value which holds InferenceEngine::ParamMap. + @return reference to this parameter structure. + */ + Params& cfgContextParams(cv::util::any&& ctx_cfg) { + desc.context_config = std::move(ctx_cfg); + return *this; + } + + /** @brief Specifies number of asynchronous inference requests. + + @param nireq Number of inference asynchronous requests. + @return reference to this parameter structure. + */ + Params& cfgNumRequests(size_t nireq) { + GAPI_Assert(nireq > 0 && "Number of infer requests must be greater than zero!"); + desc.nireq = nireq; + return *this; + } + + /** @brief Specifies new input shapes for the network inputs. + + The function is used to specify new input shapes for the network inputs. + Follow https://docs.openvinotoolkit.org/latest/classInferenceEngine_1_1networkNetwork.html + for additional information. + + @param reshape_table Map of pairs: name of corresponding data and its dimension. + @return reference to this parameter structure. + */ + Params& cfgInputReshape(const std::map>& reshape_table) { + desc.reshape_table = reshape_table; + return *this; + } + + /** @overload */ + Params& cfgInputReshape(std::map>&& reshape_table) { + desc.reshape_table = std::move(reshape_table); + return *this; + } + + /** @overload + + @param layer_name Name of layer. + @param layer_dims New dimensions for this layer. + @return reference to this parameter structure. + */ + Params& cfgInputReshape(const std::string& layer_name, const std::vector& layer_dims) { + desc.reshape_table.emplace(layer_name, layer_dims); + return *this; + } + + /** @overload */ + Params& cfgInputReshape(std::string&& layer_name, std::vector&& layer_dims) { + desc.reshape_table.emplace(layer_name, layer_dims); + return *this; + } + + /** @overload + + @param layer_names set of names of network layers that will be used for network reshape. + @return reference to this parameter structure. + */ + Params& cfgInputReshape(const std::unordered_set& layer_names) { + desc.layer_names_to_reshape = layer_names; + return *this; + } + + /** @overload + + @param layer_names rvalue set of the selected layers will be reshaped automatically + its input image size. + @return reference to this parameter structure. + */ + Params& cfgInputReshape(std::unordered_set&& layer_names) { + desc.layer_names_to_reshape = std::move(layer_names); + return *this; + } + + /** @brief Specifies the inference batch size. + + The function is used to specify inference batch size. + Follow https://docs.openvinotoolkit.org/latest/classInferenceEngine_1_1CNNNetwork.html#a8e9d19270a48aab50cb5b1c43eecb8e9 for additional information + + @param size batch size which will be used. + @return reference to this parameter structure. + */ + Params& cfgBatchSize(const size_t size) { + desc.batch_size = cv::util::make_optional(size); + return *this; + } + + Params& cfgPreprocessingParams(const cv::gapi::wip::onevpl::Device &device, + const cv::gapi::wip::onevpl::Context &ctx) { + desc.vpl_preproc_device = cv::util::make_optional(device); + desc.vpl_preproc_ctx = cv::util::make_optional(ctx); + return *this; + } + + /** @brief Specifies which api will be used to run inference. + + The function is used to specify mode for OpenVINO inference. + OpenVINO has two options to run inference: + 1. Asynchronous (using StartAsync: https://docs.openvino.ai/latest/classInferenceEngine_1_1InferRequest.html#doxid-class-inference-engine-1-1-infer-request-1a405293e8423d82a5b45f642a3bef0d24) + 2. Synchronous (using Infer: https://docs.openvino.ai/latest/classInferenceEngine_1_1InferRequest.html#doxid-class-inference-engine-1-1-infer-request-1a3391ce30894abde730523e9ca9371ce8) + By default asynchronous mode is used. + + @param mode Inference mode which will be used. + @return reference to this parameter structure. + */ + Params& cfgInferMode(InferMode mode) { + desc.mode = mode; + return *this; + } + + /** @brief Specifies the output precision for model. + + The function is used to set an output precision for model. + + @param precision Precision in OpenCV format (CV_8U, CV_32F, ...) + will be applied to all output layers. + @return reference to this parameter structure. + */ + Params& cfgOutputPrecision(detail::ParamDesc::PrecisionT precision) { + desc.output_precision = precision; + return *this; + } + + /** @overload + + @param precision_map Map of pairs: name of corresponding output layer + and its precision in OpenCV format (CV_8U, CV_32F, ...) + @return reference to this parameter structure. + */ + Params& + cfgOutputPrecision(detail::ParamDesc::PrecisionMapT precision_map) { + desc.output_precision = precision_map; + return *this; + } + + /** @brief Specifies the input layout for model. + + The function is used to set an input layout for model. + + @param layout Layout in string representation ("NCHW", "NHWC", etc) + will be applied to all input layers. + @return reference to this parameter structure. + */ + Params& cfgInputLayout(std::string layout) { + desc.input_layout = std::move(layout); + return *this; + } + + /** @overload + + @param layout_map Map of pairs: name of corresponding input layer + and its layout in string representation ("NCHW", "NHWC", etc) + @return reference to this parameter structure. + */ + Params& + cfgInputLayout(detail::AttrMap layout_map) { + desc.input_layout = std::move(layout_map); + return *this; + } + + /** @brief Specifies the output layout for model. + + The function is used to set an output layout for model. + + @param layout Layout in string representation ("NCHW", "NHWC", etc) + will be applied to all output layers. + @return reference to this parameter structure. + */ + Params& cfgOutputLayout(std::string layout) { + desc.output_layout = std::move(layout); + return *this; + } + + /** @overload + + @param layout_map Map of pairs: name of corresponding output layer + and its layout in string representation ("NCHW", "NHWC", etc) + @return reference to this parameter structure. + */ + Params& + cfgOutputLayout(detail::AttrMap layout_map) { + desc.output_layout = std::move(layout_map); + return *this; + } + + /** @brief Specifies resize interpolation algorithm. + * + The function is used to configure resize preprocessing for input layer. + + @param interpolation Resize interpolation algorithm. + Supported algorithms: #INTER_LINEAR, #INTER_AREA. + @return reference to this parameter structure. + */ + Params& cfgResize(int interpolation) { + desc.interpolation = interpolation; + return *this; + } + + /** @overload + + @param interpolation Map of pairs: name of corresponding input layer + and its resize algorithm. + @return reference to this parameter structure. + */ + Params& cfgResize(detail::AttrMap interpolation) { + desc.interpolation = std::move(interpolation); + return *this; + } + + // BEGIN(G-API's network parametrization API) + GBackend backend() const { return cv::gapi::ie::backend(); } + std::string tag() const { return Net::tag(); } + cv::util::any params() const { return { desc }; } + // END(G-API's network parametrization API) + +protected: + detail::ParamDesc desc; +}; + +/* +* @brief This structure provides functions for generic network type that +* fill inference parameters. +* @see struct Generic +*/ +template<> +class Params { +public: + /** @brief Class constructor. + + Constructs Params based on model information and sets default values for other + inference description parameters. Model is loaded and compiled using OpenVINO Toolkit. + + @param tag string tag of the network for which these parameters are intended. + @param model path to topology IR (.xml file). + @param weights path to weights (.bin file). + @param device target device to use. + */ + Params(const std::string &tag, + const std::string &model, + const std::string &weights, + const std::string &device) + : desc{ model, weights, device, {}, {}, {}, 0u, 0u, + detail::ParamDesc::Kind::Load, true, {}, {}, {}, 1u, + {}, {}, {}, {}, InferMode::Async, {}, {}, {}, {} }, + m_tag(tag) { + } + + /** @overload + + This constructor for pre-compiled networks. Model is imported from pre-compiled + blob. + + @param tag string tag of the network for which these parameters are intended. + @param model path to model. + @param device target device to use. + */ + Params(const std::string &tag, + const std::string &model, + const std::string &device) + : desc{ model, {}, device, {}, {}, {}, 0u, 0u, + detail::ParamDesc::Kind::Import, true, {}, {}, {}, 1u, + {}, {}, {}, {}, InferMode::Async, {}, {}, {}, {} }, + m_tag(tag) { + } + + /** @see ie::Params::pluginConfig. */ + Params& pluginConfig(const IEConfig& cfg) { + desc.config = cfg; + return *this; + } + + /** @overload */ + Params& pluginConfig(IEConfig&& cfg) { + desc.config = std::move(cfg); + return *this; + } + + /** @see ie::Params::constInput. */ + Params& constInput(const std::string &layer_name, + const cv::Mat &data, + TraitAs hint = TraitAs::TENSOR) { + desc.const_inputs[layer_name] = {data, hint}; + return *this; + } + + /** @see ie::Params::cfgNumRequests. */ + Params& cfgNumRequests(size_t nireq) { + GAPI_Assert(nireq > 0 && "Number of infer requests must be greater than zero!"); + desc.nireq = nireq; + return *this; + } + + /** @see ie::Params::cfgInputReshape */ + Params& cfgInputReshape(const std::map>&reshape_table) { + desc.reshape_table = reshape_table; + return *this; + } + + /** @overload */ + Params& cfgInputReshape(std::map> && reshape_table) { + desc.reshape_table = std::move(reshape_table); + return *this; + } + + /** @overload */ + Params& cfgInputReshape(std::string && layer_name, std::vector && layer_dims) { + desc.reshape_table.emplace(layer_name, layer_dims); + return *this; + } + + /** @overload */ + Params& cfgInputReshape(const std::string & layer_name, const std::vector&layer_dims) { + desc.reshape_table.emplace(layer_name, layer_dims); + return *this; + } + + /** @overload */ + Params& cfgInputReshape(std::unordered_set && layer_names) { + desc.layer_names_to_reshape = std::move(layer_names); + return *this; + } + + /** @overload */ + Params& cfgInputReshape(const std::unordered_set&layer_names) { + desc.layer_names_to_reshape = layer_names; + return *this; + } + + /** @see ie::Params::cfgBatchSize */ + Params& cfgBatchSize(const size_t size) { + desc.batch_size = cv::util::make_optional(size); + return *this; + } + + /** @see ie::Params::cfgInferAPI */ + Params& cfgInferMode(InferMode mode) { + desc.mode = mode; + return *this; + } + + /** @see ie::Params::cfgOutputPrecision */ + Params& cfgOutputPrecision(detail::ParamDesc::PrecisionT precision) { + desc.output_precision = precision; + return *this; + } + + /** @overload */ + Params& + cfgOutputPrecision(detail::ParamDesc::PrecisionMapT precision_map) { + desc.output_precision = precision_map; + return *this; + } + + /** @see ie::Params::cfgInputLayout */ + Params& cfgInputLayout(std::string layout) { + desc.input_layout = std::move(layout); + return *this; + } + + /** @overload */ + Params& + cfgInputLayout(detail::AttrMap layout_map) { + desc.input_layout = std::move(layout_map); + return *this; + } + + /** @see ie::Params::cfgOutputLayout */ + Params& cfgOutputLayout(std::string layout) { + desc.output_layout = std::move(layout); + return *this; + } + + /** @overload */ + Params& + cfgOutputLayout(detail::AttrMap layout_map) { + desc.output_layout = std::move(layout_map); + return *this; + } + + /** @see ie::Params::cfgResize */ + Params& cfgResize(int interpolation) { + desc.interpolation = interpolation; + return *this; + } + + /** @overload */ + Params& cfgResize(detail::AttrMap interpolation) { + desc.interpolation = std::move(interpolation); + return *this; + } + + // BEGIN(G-API's network parametrization API) + GBackend backend() const { return cv::gapi::ie::backend(); } + std::string tag() const { return m_tag; } + cv::util::any params() const { return { desc }; } + // END(G-API's network parametrization API) + +protected: + detail::ParamDesc desc; + std::string m_tag; +}; + +} // namespace ie +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_INFER_IE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/onnx.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/onnx.hpp index eb6316b446..9d93246da1 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/onnx.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/onnx.hpp @@ -1,759 +1,759 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020-2021 Intel Corporation - -#ifndef OPENCV_GAPI_INFER_ONNX_HPP -#define OPENCV_GAPI_INFER_ONNX_HPP - -#include -#include -#include -#include // tuple, tuple_size -#include - -#include -#include -#include - -#include // GAPI_EXPORTS -#include // GKernelPackage -#include // Generic - -namespace cv { -namespace gapi { - -/** - * @brief This namespace contains G-API ONNX Runtime backend functions, structures, and symbols. - */ -namespace onnx { - -/** - * @brief This namespace contains Execution Providers structures for G-API ONNX Runtime backend. - */ -namespace ep { - -/** - * @brief This structure provides functions - * that fill inference options for ONNX CoreML Execution Provider. - * Please follow https://onnxruntime.ai/docs/execution-providers/CoreML-ExecutionProvider.html#coreml-execution-provider - */ -struct GAPI_EXPORTS_W_SIMPLE CoreML { - /** @brief Class constructor. - - Constructs CoreML parameters. - - */ - GAPI_WRAP - CoreML() = default; - - /** @brief Limit CoreML Execution Provider to run on CPU only. - - This function is used to limit CoreML to run on CPU only. - Please follow: https://onnxruntime.ai/docs/execution-providers/CoreML-ExecutionProvider.html#coreml_flag_use_cpu_only - - @return reference to this parameter structure. - */ - GAPI_WRAP - CoreML& cfgUseCPUOnly() { - use_cpu_only = true; - return *this; - } - - /** @brief Enable CoreML EP to run on a subgraph in the body of a control flow ONNX operator (i.e. a Loop, Scan or If operator). - - This function is used to enable CoreML EP to run on - a subgraph of a control flow of ONNX operation. - Please follow: https://onnxruntime.ai/docs/execution-providers/CoreML-ExecutionProvider.html#coreml_flag_enable_on_subgraph - - @return reference to this parameter structure. - */ - GAPI_WRAP - CoreML& cfgEnableOnSubgraph() { - enable_on_subgraph = true; - return *this; - } - - /** @brief Enable CoreML EP to run only on Apple Neural Engine. - - This function is used to enable CoreML EP to run only on Apple Neural Engine. - Please follow: https://onnxruntime.ai/docs/execution-providers/CoreML-ExecutionProvider.html#coreml_flag_only_enable_device_with_ane - - @return reference to this parameter structure. - */ - GAPI_WRAP - CoreML& cfgEnableOnlyNeuralEngine() { - enable_only_ane = true; - return *this; - } - - bool use_cpu_only = false; - bool enable_on_subgraph = false; - bool enable_only_ane = false; -}; - -/** - * @brief This structure provides functions - * that fill inference options for CUDA Execution Provider. - * Please follow https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html#cuda-execution-provider - */ -struct GAPI_EXPORTS_W_SIMPLE CUDA { - // NB: Used from python. - /// @private -- Exclude this constructor from OpenCV documentation - GAPI_WRAP - CUDA() = default; - - /** @brief Class constructor. - - Constructs CUDA parameters based on device type information. - - @param dev_id Target device id to use. - */ - GAPI_WRAP - explicit CUDA(const int dev_id) - : device_id(dev_id) { - } - - int device_id; -}; - -/** - * @brief This structure provides functions - * that fill inference options for TensorRT Execution Provider. - * Please follow https://onnxruntime.ai/docs/execution-providers/TensorRT-ExecutionProvider.html#tensorrt-execution-provider - */ -struct GAPI_EXPORTS_W_SIMPLE TensorRT { - // NB: Used from python. - /// @private -- Exclude this constructor from OpenCV documentation - GAPI_WRAP - TensorRT() = default; - - /** @brief Class constructor. - - Constructs TensorRT parameters based on device type information. - - @param dev_id Target device id to use. - */ - GAPI_WRAP - explicit TensorRT(const int dev_id) - : device_id(dev_id) { - } - - int device_id; -}; - -/** - * @brief This structure provides functions - * that fill inference options for ONNX OpenVINO Execution Provider. - * Please follow https://onnxruntime.ai/docs/execution-providers/OpenVINO-ExecutionProvider.html#summary-of-options - */ -struct GAPI_EXPORTS_W_SIMPLE OpenVINO { - // NB: Used from python. - /// @private -- Exclude this constructor from OpenCV documentation - GAPI_WRAP - OpenVINO() = default; - - /** @brief Class constructor. - - Constructs OpenVINO parameters based on device type information. - - @param dev_type Target device type to use. ("CPU", "GPU", "GPU.0" etc) - */ - GAPI_WRAP - explicit OpenVINO(const std::string &dev_type) - : device_type(dev_type) { - } - - /** @brief Class constructor. - - Constructs OpenVINO parameters based on map of options passed. - - * @param params A map of parameter names and their corresponding string values. - */ - GAPI_WRAP - explicit OpenVINO(const std::map& params) - : params_map(params) { - } - - /** @brief Specifies OpenVINO Execution Provider cache dir. - - This function is used to explicitly specify the path to save and load - the blobs enabling model caching feature. - - @param dir Path to the directory what will be used as cache. - @return reference to this parameter structure. - */ - GAPI_WRAP - OpenVINO& cfgCacheDir(const std::string &dir) { - if (!params_map.empty()) { - cv::util::throw_error(std::logic_error("ep::OpenVINO cannot be changed if" - "created from the parameters map.")); - } - cache_dir = dir; - return *this; - } - - /** @brief Specifies OpenVINO Execution Provider number of threads. - - This function is used to override the accelerator default value - of number of threads with this value at runtime. - - @param nthreads Number of threads. - @return reference to this parameter structure. - */ - GAPI_WRAP - OpenVINO& cfgNumThreads(size_t nthreads) { - if (!params_map.empty()) { - cv::util::throw_error(std::logic_error("ep::OpenVINO cannot be changed if" - "created from the parameters map.")); - } - num_of_threads = nthreads; - return *this; - } - - /** @brief Enables OpenVINO Execution Provider opencl throttling. - - This function is used to enable OpenCL queue throttling for GPU devices - (reduces CPU utilization when using GPU). - - @return reference to this parameter structure. - */ - GAPI_WRAP - OpenVINO& cfgEnableOpenCLThrottling() { - if (!params_map.empty()) { - cv::util::throw_error(std::logic_error("ep::OpenVINO cannot be changed if" - "created from the parameters map.")); - } - enable_opencl_throttling = true; - return *this; - } - - /** @brief Enables OpenVINO Execution Provider dynamic shapes. - - This function is used to enable OpenCL queue throttling for GPU devices - (reduces CPU utilization when using GPU). - This function is used to enable work with dynamic shaped models - whose shape will be set dynamically based on the infer input - image/data shape at run time in CPU. - - @return reference to this parameter structure. - */ - GAPI_WRAP - OpenVINO& cfgEnableDynamicShapes() { - if (!params_map.empty()) { - cv::util::throw_error(std::logic_error("ep::OpenVINO cannot be changed if" - "created from the parameters map.")); - } - enable_dynamic_shapes = true; - return *this; - } - - std::string device_type; - std::string cache_dir; - size_t num_of_threads = 0; - bool enable_opencl_throttling = false; - bool enable_dynamic_shapes = false; - std::map params_map; -}; - -/** - * @brief This structure provides functions - * that fill inference options for ONNX DirectML Execution Provider. - * Please follow https://onnxruntime.ai/docs/execution-providers/DirectML-ExecutionProvider.html#directml-execution-provider - */ -class GAPI_EXPORTS_W_SIMPLE DirectML { -public: - // NB: Used from python. - /// @private -- Exclude this constructor from OpenCV documentation - GAPI_WRAP - DirectML() = default; - - /** @brief Class constructor. - - Constructs DirectML parameters based on device id. - - @param device_id Target device id to use. ("0", "1", etc) - */ - GAPI_WRAP - explicit DirectML(const int device_id) : ddesc(device_id) { }; - - /** @brief Class constructor. - - Constructs DirectML parameters based on adapter name. - - @param adapter_name Target adapter_name to use. - */ - GAPI_WRAP - explicit DirectML(const std::string &adapter_name) : ddesc(adapter_name) { }; - - using DeviceDesc = cv::util::variant; - DeviceDesc ddesc; -}; - -using EP = cv::util::variant< cv::util::monostate - , OpenVINO - , DirectML - , CoreML - , CUDA - , TensorRT>; - -} // namespace ep - -GAPI_EXPORTS cv::gapi::GBackend backend(); - -enum class TraitAs: int { - TENSOR, //!< G-API traits an associated cv::Mat as a raw tensor - // and passes dimensions as-is - IMAGE //!< G-API traits an associated cv::Mat as an image so - // creates an "image" blob (NCHW/NHWC, etc) -}; - -using PostProc = std::function &, - std::unordered_map &)>; - -namespace detail { -/** -* @brief This structure contains description of inference parameters -* which is specific to ONNX models. -*/ -struct ParamDesc { - std::string model_path; //!< Path to model. - - // NB: nun_* may differ from topology's real input/output port numbers - // (e.g. topology's partial execution) - std::size_t num_in; //!< How many inputs are defined in the operation - std::size_t num_out; //!< How many outputs are defined in the operation - - // NB: Here order follows the `Net` API - std::vector input_names; //!< Names of input network layers. - std::vector output_names; //!< Names of output network layers. - - using ConstInput = std::pair; - std::unordered_map const_inputs; //!< Map with pair of name of network layer and ConstInput which will be associated with this. - - std::vector mean; //!< Mean values for preprocessing. - std::vector stdev; //!< Standard deviation values for preprocessing. - - std::vector out_metas; //!< Out meta information about your output (type, dimension). - PostProc custom_post_proc; //!< Post processing function. - - std::vector normalize; //!< Vector of bool values that enabled or disabled normalize of input data. - - std::vector names_to_remap; //!< Names of output layers that will be processed in PostProc function. - - bool is_generic; - - // TODO: Needs to modify the rest of ParamDesc accordingly to support - // both generic and non-generic options without duplication - // (as it was done for the OV IE backend) - // These values are pushed into the respective vector<> fields above - // when the generic infer parameters are unpacked (see GONNXBackendImpl::unpackKernel) - std::unordered_map > generic_mstd; - std::unordered_map generic_norm; - - std::map session_options; - std::vector execution_providers; - bool disable_mem_pattern; - cv::util::optional opt_level; -}; -} // namespace detail - -template -struct PortCfg { - using In = std::array - < std::string - , std::tuple_size::value >; - using Out = std::array - < std::string - , std::tuple_size::value >; - using NormCoefs = std::array - < cv::Scalar - , std::tuple_size::value >; - using Normalize = std::array - < bool - , std::tuple_size::value >; -}; - -/** - * Contains description of inference parameters and kit of functions that - * fill this parameters. - */ -template class Params { -public: - /** @brief Class constructor. - - Constructs Params based on model information and sets default values for other - inference description parameters. - - @param model Path to model (.onnx file). - */ - Params(const std::string &model) { - desc.model_path = model; - desc.num_in = std::tuple_size::value; - desc.num_out = std::tuple_size::value; - desc.is_generic = false; - desc.disable_mem_pattern = false; - } - - /** @brief Specifies sequence of network input layers names for inference. - - The function is used to associate data of graph inputs with input layers of - network topology. Number of names has to match the number of network inputs. If a network - has only one input layer, there is no need to call it as the layer is - associated with input automatically but this doesn't prevent you from - doing it yourself. Count of names has to match to number of network inputs. - - @param layer_names std::array where N is the number of inputs - as defined in the @ref G_API_NET. Contains names of input layers. - @return the reference on modified object. - */ - Params& cfgInputLayers(const typename PortCfg::In &layer_names) { - desc.input_names.assign(layer_names.begin(), layer_names.end()); - return *this; - } - - /** @brief Specifies sequence of output layers names for inference. - - The function is used to associate data of graph outputs with output layers of - network topology. If a network has only one output layer, there is no need to call it - as the layer is associated with output automatically but this doesn't prevent - you from doing it yourself. Count of names has to match to number of network - outputs or you can set your own output but for this case you have to - additionally use @ref cfgPostProc function. - - @param layer_names std::array where N is the number of outputs - as defined in the @ref G_API_NET. Contains names of output layers. - @return the reference on modified object. - */ - Params& cfgOutputLayers(const typename PortCfg::Out &layer_names) { - desc.output_names.assign(layer_names.begin(), layer_names.end()); - return *this; - } - - /** @brief Sets a constant input. - - The function is used to set constant input. This input has to be - a prepared tensor since preprocessing is disabled for this case. You should - provide name of network layer which will receive provided data. - - @param layer_name Name of network layer. - @param data cv::Mat that contains data which will be associated with network layer. - @param hint Type of input (TENSOR). - @return the reference on modified object. - */ - Params& constInput(const std::string &layer_name, - const cv::Mat &data, - TraitAs hint = TraitAs::TENSOR) { - desc.const_inputs[layer_name] = {data, hint}; - return *this; - } - - /** @brief Specifies mean value and standard deviation for preprocessing. - - The function is used to set mean value and standard deviation for preprocessing - of input data. - - @param m std::array where N is the number of inputs - as defined in the @ref G_API_NET. Contains mean values. - @param s std::array where N is the number of inputs - as defined in the @ref G_API_NET. Contains standard deviation values. - @return the reference on modified object. - */ - Params& cfgMeanStd(const typename PortCfg::NormCoefs &m, - const typename PortCfg::NormCoefs &s) { - desc.mean.assign(m.begin(), m.end()); - desc.stdev.assign(s.begin(), s.end()); - return *this; - } - - /** @brief Configures graph output and provides the post processing function from user. - - The function is used when you work with networks with dynamic outputs. - Since we can't know dimensions of inference result needs provide them for - construction of graph output. This dimensions can differ from inference result. - So you have to provide @ref PostProc function that gets information from inference - result and fill output which is constructed by dimensions from out_metas. - - @param out_metas Out meta information about your output (type, dimension). - @param remap_function Post processing function, which has two parameters. First is onnx - result, second is graph output. Both parameters is std::map that contain pair of - layer's name and cv::Mat. - @return the reference on modified object. - */ - Params& cfgPostProc(const std::vector &out_metas, - const PostProc &remap_function) { - desc.out_metas = out_metas; - desc.custom_post_proc = remap_function; - return *this; - } - - /** @overload - Function with a rvalue parameters. - - @param out_metas rvalue out meta information about your output (type, dimension). - @param remap_function rvalue post processing function, which has two parameters. First is onnx - result, second is graph output. Both parameters is std::map that contain pair of - layer's name and cv::Mat. - @return the reference on modified object. - */ - Params& cfgPostProc(std::vector &&out_metas, - PostProc &&remap_function) { - desc.out_metas = std::move(out_metas); - desc.custom_post_proc = std::move(remap_function); - return *this; - } - - /** @overload - The function has additional parameter names_to_remap. This parameter provides - information about output layers which will be used for inference and post - processing function. - - @param out_metas Out meta information. - @param remap_function Post processing function. - @param names_to_remap Names of output layers. network's inference will - be done on these layers. Inference's result will be processed in post processing - function using these names. - @return the reference on modified object. - */ - Params& cfgPostProc(const std::vector &out_metas, - const PostProc &remap_function, - const std::vector &names_to_remap) { - desc.out_metas = out_metas; - desc.custom_post_proc = remap_function; - desc.names_to_remap = names_to_remap; - return *this; - } - - /** @overload - Function with a rvalue parameters and additional parameter names_to_remap. - - @param out_metas rvalue out meta information. - @param remap_function rvalue post processing function. - @param names_to_remap rvalue names of output layers. network's inference will - be done on these layers. Inference's result will be processed in post processing - function using these names. - @return the reference on modified object. - */ - Params& cfgPostProc(std::vector &&out_metas, - PostProc &&remap_function, - std::vector &&names_to_remap) { - desc.out_metas = std::move(out_metas); - desc.custom_post_proc = std::move(remap_function); - desc.names_to_remap = std::move(names_to_remap); - return *this; - } - - /** @brief Specifies normalize parameter for preprocessing. - - The function is used to set normalize parameter for preprocessing of input data. - - @param normalizations std::array where N is the number of inputs - as defined in the @ref G_API_NET. Сontains bool values that enabled or disabled - normalize of input data. - @return the reference on modified object. - */ - Params& cfgNormalize(const typename PortCfg::Normalize &normalizations) { - desc.normalize.assign(normalizations.begin(), normalizations.end()); - return *this; - } - - /** @brief Adds execution provider for runtime. - - The function is used to add ONNX Runtime OpenVINO Execution Provider options. - - @param ep OpenVINO Execution Provider options. - @see cv::gapi::onnx::ep::OpenVINO. - - @return the reference on modified object. - */ - Params& cfgAddExecutionProvider(ep::OpenVINO&& ep) { - desc.execution_providers.emplace_back(std::move(ep)); - return *this; - } - - /** @brief Adds execution provider for runtime. - - The function is used to add ONNX Runtime DirectML Execution Provider options. - - @param ep DirectML Execution Provider options. - @see cv::gapi::onnx::ep::DirectML. - - @return the reference on modified object. - */ - Params& cfgAddExecutionProvider(ep::DirectML&& ep) { - desc.execution_providers.emplace_back(std::move(ep)); - return *this; - } - - /** @brief Adds execution provider for runtime. - - The function is used to add ONNX Runtime CoreML Execution Provider options. - - @param ep CoreML Execution Provider options. - @see cv::gapi::onnx::ep::CoreML. - - @return the reference on modified object. - */ - Params& cfgAddExecutionProvider(ep::CoreML&& ep) { - desc.execution_providers.emplace_back(std::move(ep)); - return *this; - } - - /** @brief Adds execution provider for runtime. - - The function is used to add ONNX Runtime CUDA Execution Provider options. - - @param ep CUDA Execution Provider options. - @see cv::gapi::onnx::ep::CUDA. - - @return the reference on modified object. - */ - Params& cfgAddExecutionProvider(ep::CUDA&& ep) { - desc.execution_providers.emplace_back(std::move(ep)); - return *this; - } - - /** @brief Adds execution provider for runtime. - - The function is used to add ONNX Runtime TensorRT Execution Provider options. - - @param ep TensorRT Execution Provider options. - @see cv::gapi::onnx::ep::TensorRT. - - @return the reference on modified object. - */ - Params& cfgAddExecutionProvider(ep::TensorRT&& ep) { - desc.execution_providers.emplace_back(std::move(ep)); - return *this; - } - - /** @brief Disables the memory pattern optimization. - - @return the reference on modified object. - */ - Params& cfgDisableMemPattern() { - desc.disable_mem_pattern = true; - return *this; - } - - /** @brief Configures session options for ONNX Runtime. - - This function is used to set various session options for the ONNX Runtime - session by accepting a map of key-value pairs. - - @param options A map of session option to be applied to the ONNX Runtime session. - @return the reference on modified object. - */ - Params& cfgSessionOptions(const std::map& options) { - desc.session_options.insert(options.begin(), options.end()); - return *this; - } - - /** @brief Configures optimization level for ONNX Runtime. - - @param opt_level [optimization level]: Valid values are 0 (disable), 1 (basic), 2 (extended), 99 (all). - Please see onnxruntime_c_api.h (enum GraphOptimizationLevel) for the full list of all optimization levels. - @return the reference on modified object. - */ - Params& cfgOptLevel(const int opt_level) { - desc.opt_level = cv::util::make_optional(opt_level); - return *this; - } - - // BEGIN(G-API's network parametrization API) - GBackend backend() const { return cv::gapi::onnx::backend(); } - std::string tag() const { return Net::tag(); } - cv::util::any params() const { return { desc }; } - // END(G-API's network parametrization API) - -protected: - detail::ParamDesc desc; -}; - -/* -* @brief This structure provides functions for generic network type that -* fill inference parameters. -* @see struct Generic -*/ -template<> -class Params { -public: - /** @brief Class constructor. - - Constructs Params based on input information and sets default values for other - inference description parameters. - - @param tag string tag of the network for which these parameters are intended. - @param model_path path to model file (.onnx file). - */ - Params(const std::string& tag, const std::string& model_path) - : desc{ model_path, 0u, 0u, {}, {}, {}, {}, {}, {}, {}, {}, {}, true, {}, {}, {}, {}, false, {} }, m_tag(tag) {} - - /** @see onnx::Params::cfgMeanStdDev. */ - void cfgMeanStdDev(const std::string &layer, - const cv::Scalar &m, - const cv::Scalar &s) { - desc.generic_mstd[layer] = std::make_pair(m, s); - } - - /** @see onnx::Params::cfgNormalize. */ - void cfgNormalize(const std::string &layer, bool flag) { - desc.generic_norm[layer] = flag; - } - - /** @see onnx::Params::cfgAddExecutionProvider. */ - void cfgAddExecutionProvider(ep::OpenVINO&& ep) { - desc.execution_providers.emplace_back(std::move(ep)); - } - - /** @see onnx::Params::cfgAddExecutionProvider. */ - void cfgAddExecutionProvider(ep::DirectML&& ep) { - desc.execution_providers.emplace_back(std::move(ep)); - } - - /** @see onnx::Params::cfgAddExecutionProvider. */ - void cfgAddExecutionProvider(ep::CoreML&& ep) { - desc.execution_providers.emplace_back(std::move(ep)); - } - - /** @see onnx::Params::cfgAddExecutionProvider. */ - void cfgAddExecutionProvider(ep::CUDA&& ep) { - desc.execution_providers.emplace_back(std::move(ep)); - } - - /** @see onnx::Params::cfgAddExecutionProvider. */ - void cfgAddExecutionProvider(ep::TensorRT&& ep) { - desc.execution_providers.emplace_back(std::move(ep)); - } - - /** @see onnx::Params::cfgDisableMemPattern. */ - void cfgDisableMemPattern() { - desc.disable_mem_pattern = true; - } - - /** @see onnx::Params::cfgSessionOptions. */ - void cfgSessionOptions(const std::map& options) { - desc.session_options.insert(options.begin(), options.end()); - } - -/** @see onnx::Params::cfgOptLevel. */ - void cfgOptLevel(const int opt_level) { - desc.opt_level = cv::util::make_optional(opt_level); - } - - // BEGIN(G-API's network parametrization API) - GBackend backend() const { return cv::gapi::onnx::backend(); } - std::string tag() const { return m_tag; } - cv::util::any params() const { return { desc }; } - // END(G-API's network parametrization API) -protected: - detail::ParamDesc desc; - std::string m_tag; -}; - -} // namespace onnx -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_INFER_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020-2021 Intel Corporation + +#ifndef OPENCV_GAPI_INFER_ONNX_HPP +#define OPENCV_GAPI_INFER_ONNX_HPP + +#include +#include +#include +#include // tuple, tuple_size +#include + +#include +#include +#include + +#include // GAPI_EXPORTS +#include // GKernelPackage +#include // Generic + +namespace cv { +namespace gapi { + +/** + * @brief This namespace contains G-API ONNX Runtime backend functions, structures, and symbols. + */ +namespace onnx { + +/** + * @brief This namespace contains Execution Providers structures for G-API ONNX Runtime backend. + */ +namespace ep { + +/** + * @brief This structure provides functions + * that fill inference options for ONNX CoreML Execution Provider. + * Please follow https://onnxruntime.ai/docs/execution-providers/CoreML-ExecutionProvider.html#coreml-execution-provider + */ +struct GAPI_EXPORTS_W_SIMPLE CoreML { + /** @brief Class constructor. + + Constructs CoreML parameters. + + */ + GAPI_WRAP + CoreML() = default; + + /** @brief Limit CoreML Execution Provider to run on CPU only. + + This function is used to limit CoreML to run on CPU only. + Please follow: https://onnxruntime.ai/docs/execution-providers/CoreML-ExecutionProvider.html#coreml_flag_use_cpu_only + + @return reference to this parameter structure. + */ + GAPI_WRAP + CoreML& cfgUseCPUOnly() { + use_cpu_only = true; + return *this; + } + + /** @brief Enable CoreML EP to run on a subgraph in the body of a control flow ONNX operator (i.e. a Loop, Scan or If operator). + + This function is used to enable CoreML EP to run on + a subgraph of a control flow of ONNX operation. + Please follow: https://onnxruntime.ai/docs/execution-providers/CoreML-ExecutionProvider.html#coreml_flag_enable_on_subgraph + + @return reference to this parameter structure. + */ + GAPI_WRAP + CoreML& cfgEnableOnSubgraph() { + enable_on_subgraph = true; + return *this; + } + + /** @brief Enable CoreML EP to run only on Apple Neural Engine. + + This function is used to enable CoreML EP to run only on Apple Neural Engine. + Please follow: https://onnxruntime.ai/docs/execution-providers/CoreML-ExecutionProvider.html#coreml_flag_only_enable_device_with_ane + + @return reference to this parameter structure. + */ + GAPI_WRAP + CoreML& cfgEnableOnlyNeuralEngine() { + enable_only_ane = true; + return *this; + } + + bool use_cpu_only = false; + bool enable_on_subgraph = false; + bool enable_only_ane = false; +}; + +/** + * @brief This structure provides functions + * that fill inference options for CUDA Execution Provider. + * Please follow https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html#cuda-execution-provider + */ +struct GAPI_EXPORTS_W_SIMPLE CUDA { + // NB: Used from python. + /// @private -- Exclude this constructor from OpenCV documentation + GAPI_WRAP + CUDA() = default; + + /** @brief Class constructor. + + Constructs CUDA parameters based on device type information. + + @param dev_id Target device id to use. + */ + GAPI_WRAP + explicit CUDA(const int dev_id) + : device_id(dev_id) { + } + + int device_id; +}; + +/** + * @brief This structure provides functions + * that fill inference options for TensorRT Execution Provider. + * Please follow https://onnxruntime.ai/docs/execution-providers/TensorRT-ExecutionProvider.html#tensorrt-execution-provider + */ +struct GAPI_EXPORTS_W_SIMPLE TensorRT { + // NB: Used from python. + /// @private -- Exclude this constructor from OpenCV documentation + GAPI_WRAP + TensorRT() = default; + + /** @brief Class constructor. + + Constructs TensorRT parameters based on device type information. + + @param dev_id Target device id to use. + */ + GAPI_WRAP + explicit TensorRT(const int dev_id) + : device_id(dev_id) { + } + + int device_id; +}; + +/** + * @brief This structure provides functions + * that fill inference options for ONNX OpenVINO Execution Provider. + * Please follow https://onnxruntime.ai/docs/execution-providers/OpenVINO-ExecutionProvider.html#summary-of-options + */ +struct GAPI_EXPORTS_W_SIMPLE OpenVINO { + // NB: Used from python. + /// @private -- Exclude this constructor from OpenCV documentation + GAPI_WRAP + OpenVINO() = default; + + /** @brief Class constructor. + + Constructs OpenVINO parameters based on device type information. + + @param dev_type Target device type to use. ("CPU", "GPU", "GPU.0" etc) + */ + GAPI_WRAP + explicit OpenVINO(const std::string &dev_type) + : device_type(dev_type) { + } + + /** @brief Class constructor. + + Constructs OpenVINO parameters based on map of options passed. + + * @param params A map of parameter names and their corresponding string values. + */ + GAPI_WRAP + explicit OpenVINO(const std::map& params) + : params_map(params) { + } + + /** @brief Specifies OpenVINO Execution Provider cache dir. + + This function is used to explicitly specify the path to save and load + the blobs enabling model caching feature. + + @param dir Path to the directory what will be used as cache. + @return reference to this parameter structure. + */ + GAPI_WRAP + OpenVINO& cfgCacheDir(const std::string &dir) { + if (!params_map.empty()) { + cv::util::throw_error(std::logic_error("ep::OpenVINO cannot be changed if" + "created from the parameters map.")); + } + cache_dir = dir; + return *this; + } + + /** @brief Specifies OpenVINO Execution Provider number of threads. + + This function is used to override the accelerator default value + of number of threads with this value at runtime. + + @param nthreads Number of threads. + @return reference to this parameter structure. + */ + GAPI_WRAP + OpenVINO& cfgNumThreads(size_t nthreads) { + if (!params_map.empty()) { + cv::util::throw_error(std::logic_error("ep::OpenVINO cannot be changed if" + "created from the parameters map.")); + } + num_of_threads = nthreads; + return *this; + } + + /** @brief Enables OpenVINO Execution Provider opencl throttling. + + This function is used to enable OpenCL queue throttling for GPU devices + (reduces CPU utilization when using GPU). + + @return reference to this parameter structure. + */ + GAPI_WRAP + OpenVINO& cfgEnableOpenCLThrottling() { + if (!params_map.empty()) { + cv::util::throw_error(std::logic_error("ep::OpenVINO cannot be changed if" + "created from the parameters map.")); + } + enable_opencl_throttling = true; + return *this; + } + + /** @brief Enables OpenVINO Execution Provider dynamic shapes. + + This function is used to enable OpenCL queue throttling for GPU devices + (reduces CPU utilization when using GPU). + This function is used to enable work with dynamic shaped models + whose shape will be set dynamically based on the infer input + image/data shape at run time in CPU. + + @return reference to this parameter structure. + */ + GAPI_WRAP + OpenVINO& cfgEnableDynamicShapes() { + if (!params_map.empty()) { + cv::util::throw_error(std::logic_error("ep::OpenVINO cannot be changed if" + "created from the parameters map.")); + } + enable_dynamic_shapes = true; + return *this; + } + + std::string device_type; + std::string cache_dir; + size_t num_of_threads = 0; + bool enable_opencl_throttling = false; + bool enable_dynamic_shapes = false; + std::map params_map; +}; + +/** + * @brief This structure provides functions + * that fill inference options for ONNX DirectML Execution Provider. + * Please follow https://onnxruntime.ai/docs/execution-providers/DirectML-ExecutionProvider.html#directml-execution-provider + */ +class GAPI_EXPORTS_W_SIMPLE DirectML { +public: + // NB: Used from python. + /// @private -- Exclude this constructor from OpenCV documentation + GAPI_WRAP + DirectML() = default; + + /** @brief Class constructor. + + Constructs DirectML parameters based on device id. + + @param device_id Target device id to use. ("0", "1", etc) + */ + GAPI_WRAP + explicit DirectML(const int device_id) : ddesc(device_id) { }; + + /** @brief Class constructor. + + Constructs DirectML parameters based on adapter name. + + @param adapter_name Target adapter_name to use. + */ + GAPI_WRAP + explicit DirectML(const std::string &adapter_name) : ddesc(adapter_name) { }; + + using DeviceDesc = cv::util::variant; + DeviceDesc ddesc; +}; + +using EP = cv::util::variant< cv::util::monostate + , OpenVINO + , DirectML + , CoreML + , CUDA + , TensorRT>; + +} // namespace ep + +GAPI_EXPORTS cv::gapi::GBackend backend(); + +enum class TraitAs: int { + TENSOR, //!< G-API traits an associated cv::Mat as a raw tensor + // and passes dimensions as-is + IMAGE //!< G-API traits an associated cv::Mat as an image so + // creates an "image" blob (NCHW/NHWC, etc) +}; + +using PostProc = std::function &, + std::unordered_map &)>; + +namespace detail { +/** +* @brief This structure contains description of inference parameters +* which is specific to ONNX models. +*/ +struct ParamDesc { + std::string model_path; //!< Path to model. + + // NB: nun_* may differ from topology's real input/output port numbers + // (e.g. topology's partial execution) + std::size_t num_in; //!< How many inputs are defined in the operation + std::size_t num_out; //!< How many outputs are defined in the operation + + // NB: Here order follows the `Net` API + std::vector input_names; //!< Names of input network layers. + std::vector output_names; //!< Names of output network layers. + + using ConstInput = std::pair; + std::unordered_map const_inputs; //!< Map with pair of name of network layer and ConstInput which will be associated with this. + + std::vector mean; //!< Mean values for preprocessing. + std::vector stdev; //!< Standard deviation values for preprocessing. + + std::vector out_metas; //!< Out meta information about your output (type, dimension). + PostProc custom_post_proc; //!< Post processing function. + + std::vector normalize; //!< Vector of bool values that enabled or disabled normalize of input data. + + std::vector names_to_remap; //!< Names of output layers that will be processed in PostProc function. + + bool is_generic; + + // TODO: Needs to modify the rest of ParamDesc accordingly to support + // both generic and non-generic options without duplication + // (as it was done for the OV IE backend) + // These values are pushed into the respective vector<> fields above + // when the generic infer parameters are unpacked (see GONNXBackendImpl::unpackKernel) + std::unordered_map > generic_mstd; + std::unordered_map generic_norm; + + std::map session_options; + std::vector execution_providers; + bool disable_mem_pattern; + cv::util::optional opt_level; +}; +} // namespace detail + +template +struct PortCfg { + using In = std::array + < std::string + , std::tuple_size::value >; + using Out = std::array + < std::string + , std::tuple_size::value >; + using NormCoefs = std::array + < cv::Scalar + , std::tuple_size::value >; + using Normalize = std::array + < bool + , std::tuple_size::value >; +}; + +/** + * Contains description of inference parameters and kit of functions that + * fill this parameters. + */ +template class Params { +public: + /** @brief Class constructor. + + Constructs Params based on model information and sets default values for other + inference description parameters. + + @param model Path to model (.onnx file). + */ + Params(const std::string &model) { + desc.model_path = model; + desc.num_in = std::tuple_size::value; + desc.num_out = std::tuple_size::value; + desc.is_generic = false; + desc.disable_mem_pattern = false; + } + + /** @brief Specifies sequence of network input layers names for inference. + + The function is used to associate data of graph inputs with input layers of + network topology. Number of names has to match the number of network inputs. If a network + has only one input layer, there is no need to call it as the layer is + associated with input automatically but this doesn't prevent you from + doing it yourself. Count of names has to match to number of network inputs. + + @param layer_names std::array where N is the number of inputs + as defined in the @ref G_API_NET. Contains names of input layers. + @return the reference on modified object. + */ + Params& cfgInputLayers(const typename PortCfg::In &layer_names) { + desc.input_names.assign(layer_names.begin(), layer_names.end()); + return *this; + } + + /** @brief Specifies sequence of output layers names for inference. + + The function is used to associate data of graph outputs with output layers of + network topology. If a network has only one output layer, there is no need to call it + as the layer is associated with output automatically but this doesn't prevent + you from doing it yourself. Count of names has to match to number of network + outputs or you can set your own output but for this case you have to + additionally use @ref cfgPostProc function. + + @param layer_names std::array where N is the number of outputs + as defined in the @ref G_API_NET. Contains names of output layers. + @return the reference on modified object. + */ + Params& cfgOutputLayers(const typename PortCfg::Out &layer_names) { + desc.output_names.assign(layer_names.begin(), layer_names.end()); + return *this; + } + + /** @brief Sets a constant input. + + The function is used to set constant input. This input has to be + a prepared tensor since preprocessing is disabled for this case. You should + provide name of network layer which will receive provided data. + + @param layer_name Name of network layer. + @param data cv::Mat that contains data which will be associated with network layer. + @param hint Type of input (TENSOR). + @return the reference on modified object. + */ + Params& constInput(const std::string &layer_name, + const cv::Mat &data, + TraitAs hint = TraitAs::TENSOR) { + desc.const_inputs[layer_name] = {data, hint}; + return *this; + } + + /** @brief Specifies mean value and standard deviation for preprocessing. + + The function is used to set mean value and standard deviation for preprocessing + of input data. + + @param m std::array where N is the number of inputs + as defined in the @ref G_API_NET. Contains mean values. + @param s std::array where N is the number of inputs + as defined in the @ref G_API_NET. Contains standard deviation values. + @return the reference on modified object. + */ + Params& cfgMeanStd(const typename PortCfg::NormCoefs &m, + const typename PortCfg::NormCoefs &s) { + desc.mean.assign(m.begin(), m.end()); + desc.stdev.assign(s.begin(), s.end()); + return *this; + } + + /** @brief Configures graph output and provides the post processing function from user. + + The function is used when you work with networks with dynamic outputs. + Since we can't know dimensions of inference result needs provide them for + construction of graph output. This dimensions can differ from inference result. + So you have to provide @ref PostProc function that gets information from inference + result and fill output which is constructed by dimensions from out_metas. + + @param out_metas Out meta information about your output (type, dimension). + @param remap_function Post processing function, which has two parameters. First is onnx + result, second is graph output. Both parameters is std::map that contain pair of + layer's name and cv::Mat. + @return the reference on modified object. + */ + Params& cfgPostProc(const std::vector &out_metas, + const PostProc &remap_function) { + desc.out_metas = out_metas; + desc.custom_post_proc = remap_function; + return *this; + } + + /** @overload + Function with a rvalue parameters. + + @param out_metas rvalue out meta information about your output (type, dimension). + @param remap_function rvalue post processing function, which has two parameters. First is onnx + result, second is graph output. Both parameters is std::map that contain pair of + layer's name and cv::Mat. + @return the reference on modified object. + */ + Params& cfgPostProc(std::vector &&out_metas, + PostProc &&remap_function) { + desc.out_metas = std::move(out_metas); + desc.custom_post_proc = std::move(remap_function); + return *this; + } + + /** @overload + The function has additional parameter names_to_remap. This parameter provides + information about output layers which will be used for inference and post + processing function. + + @param out_metas Out meta information. + @param remap_function Post processing function. + @param names_to_remap Names of output layers. network's inference will + be done on these layers. Inference's result will be processed in post processing + function using these names. + @return the reference on modified object. + */ + Params& cfgPostProc(const std::vector &out_metas, + const PostProc &remap_function, + const std::vector &names_to_remap) { + desc.out_metas = out_metas; + desc.custom_post_proc = remap_function; + desc.names_to_remap = names_to_remap; + return *this; + } + + /** @overload + Function with a rvalue parameters and additional parameter names_to_remap. + + @param out_metas rvalue out meta information. + @param remap_function rvalue post processing function. + @param names_to_remap rvalue names of output layers. network's inference will + be done on these layers. Inference's result will be processed in post processing + function using these names. + @return the reference on modified object. + */ + Params& cfgPostProc(std::vector &&out_metas, + PostProc &&remap_function, + std::vector &&names_to_remap) { + desc.out_metas = std::move(out_metas); + desc.custom_post_proc = std::move(remap_function); + desc.names_to_remap = std::move(names_to_remap); + return *this; + } + + /** @brief Specifies normalize parameter for preprocessing. + + The function is used to set normalize parameter for preprocessing of input data. + + @param normalizations std::array where N is the number of inputs + as defined in the @ref G_API_NET. Сontains bool values that enabled or disabled + normalize of input data. + @return the reference on modified object. + */ + Params& cfgNormalize(const typename PortCfg::Normalize &normalizations) { + desc.normalize.assign(normalizations.begin(), normalizations.end()); + return *this; + } + + /** @brief Adds execution provider for runtime. + + The function is used to add ONNX Runtime OpenVINO Execution Provider options. + + @param ep OpenVINO Execution Provider options. + @see cv::gapi::onnx::ep::OpenVINO. + + @return the reference on modified object. + */ + Params& cfgAddExecutionProvider(ep::OpenVINO&& ep) { + desc.execution_providers.emplace_back(std::move(ep)); + return *this; + } + + /** @brief Adds execution provider for runtime. + + The function is used to add ONNX Runtime DirectML Execution Provider options. + + @param ep DirectML Execution Provider options. + @see cv::gapi::onnx::ep::DirectML. + + @return the reference on modified object. + */ + Params& cfgAddExecutionProvider(ep::DirectML&& ep) { + desc.execution_providers.emplace_back(std::move(ep)); + return *this; + } + + /** @brief Adds execution provider for runtime. + + The function is used to add ONNX Runtime CoreML Execution Provider options. + + @param ep CoreML Execution Provider options. + @see cv::gapi::onnx::ep::CoreML. + + @return the reference on modified object. + */ + Params& cfgAddExecutionProvider(ep::CoreML&& ep) { + desc.execution_providers.emplace_back(std::move(ep)); + return *this; + } + + /** @brief Adds execution provider for runtime. + + The function is used to add ONNX Runtime CUDA Execution Provider options. + + @param ep CUDA Execution Provider options. + @see cv::gapi::onnx::ep::CUDA. + + @return the reference on modified object. + */ + Params& cfgAddExecutionProvider(ep::CUDA&& ep) { + desc.execution_providers.emplace_back(std::move(ep)); + return *this; + } + + /** @brief Adds execution provider for runtime. + + The function is used to add ONNX Runtime TensorRT Execution Provider options. + + @param ep TensorRT Execution Provider options. + @see cv::gapi::onnx::ep::TensorRT. + + @return the reference on modified object. + */ + Params& cfgAddExecutionProvider(ep::TensorRT&& ep) { + desc.execution_providers.emplace_back(std::move(ep)); + return *this; + } + + /** @brief Disables the memory pattern optimization. + + @return the reference on modified object. + */ + Params& cfgDisableMemPattern() { + desc.disable_mem_pattern = true; + return *this; + } + + /** @brief Configures session options for ONNX Runtime. + + This function is used to set various session options for the ONNX Runtime + session by accepting a map of key-value pairs. + + @param options A map of session option to be applied to the ONNX Runtime session. + @return the reference on modified object. + */ + Params& cfgSessionOptions(const std::map& options) { + desc.session_options.insert(options.begin(), options.end()); + return *this; + } + + /** @brief Configures optimization level for ONNX Runtime. + + @param opt_level [optimization level]: Valid values are 0 (disable), 1 (basic), 2 (extended), 99 (all). + Please see onnxruntime_c_api.h (enum GraphOptimizationLevel) for the full list of all optimization levels. + @return the reference on modified object. + */ + Params& cfgOptLevel(const int opt_level) { + desc.opt_level = cv::util::make_optional(opt_level); + return *this; + } + + // BEGIN(G-API's network parametrization API) + GBackend backend() const { return cv::gapi::onnx::backend(); } + std::string tag() const { return Net::tag(); } + cv::util::any params() const { return { desc }; } + // END(G-API's network parametrization API) + +protected: + detail::ParamDesc desc; +}; + +/* +* @brief This structure provides functions for generic network type that +* fill inference parameters. +* @see struct Generic +*/ +template<> +class Params { +public: + /** @brief Class constructor. + + Constructs Params based on input information and sets default values for other + inference description parameters. + + @param tag string tag of the network for which these parameters are intended. + @param model_path path to model file (.onnx file). + */ + Params(const std::string& tag, const std::string& model_path) + : desc{ model_path, 0u, 0u, {}, {}, {}, {}, {}, {}, {}, {}, {}, true, {}, {}, {}, {}, false, {} }, m_tag(tag) {} + + /** @see onnx::Params::cfgMeanStdDev. */ + void cfgMeanStdDev(const std::string &layer, + const cv::Scalar &m, + const cv::Scalar &s) { + desc.generic_mstd[layer] = std::make_pair(m, s); + } + + /** @see onnx::Params::cfgNormalize. */ + void cfgNormalize(const std::string &layer, bool flag) { + desc.generic_norm[layer] = flag; + } + + /** @see onnx::Params::cfgAddExecutionProvider. */ + void cfgAddExecutionProvider(ep::OpenVINO&& ep) { + desc.execution_providers.emplace_back(std::move(ep)); + } + + /** @see onnx::Params::cfgAddExecutionProvider. */ + void cfgAddExecutionProvider(ep::DirectML&& ep) { + desc.execution_providers.emplace_back(std::move(ep)); + } + + /** @see onnx::Params::cfgAddExecutionProvider. */ + void cfgAddExecutionProvider(ep::CoreML&& ep) { + desc.execution_providers.emplace_back(std::move(ep)); + } + + /** @see onnx::Params::cfgAddExecutionProvider. */ + void cfgAddExecutionProvider(ep::CUDA&& ep) { + desc.execution_providers.emplace_back(std::move(ep)); + } + + /** @see onnx::Params::cfgAddExecutionProvider. */ + void cfgAddExecutionProvider(ep::TensorRT&& ep) { + desc.execution_providers.emplace_back(std::move(ep)); + } + + /** @see onnx::Params::cfgDisableMemPattern. */ + void cfgDisableMemPattern() { + desc.disable_mem_pattern = true; + } + + /** @see onnx::Params::cfgSessionOptions. */ + void cfgSessionOptions(const std::map& options) { + desc.session_options.insert(options.begin(), options.end()); + } + +/** @see onnx::Params::cfgOptLevel. */ + void cfgOptLevel(const int opt_level) { + desc.opt_level = cv::util::make_optional(opt_level); + } + + // BEGIN(G-API's network parametrization API) + GBackend backend() const { return cv::gapi::onnx::backend(); } + std::string tag() const { return m_tag; } + cv::util::any params() const { return { desc }; } + // END(G-API's network parametrization API) +protected: + detail::ParamDesc desc; + std::string m_tag; +}; + +} // namespace onnx +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_INFER_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/ov.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/ov.hpp index 782792489b..9a3fc5659d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/ov.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/ov.hpp @@ -1,709 +1,709 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2023 Intel Corporation - -#ifndef OPENCV_GAPI_INFER_OV_HPP -#define OPENCV_GAPI_INFER_OV_HPP - -#include - -#include -#include // GAPI_EXPORTS -#include // GKernelType[M], GBackend -#include // Generic - -#include - -namespace cv { -namespace gapi { - -/** - * @brief This namespace contains G-API OpenVINO 2.0 backend functions, - * structures, and symbols. - */ -namespace ov { - -GAPI_EXPORTS cv::gapi::GBackend backend(); - -namespace detail { - -template -using AttrMap = std::map; -// NB: This type is supposed to be used to hold in/out layers -// attributes such as precision, layout, shape etc. -// -// User can provide attributes either: -// 1. cv::util::monostate - No value specified explicitly. -// 2. Attr - value specified explicitly that should be broadcasted to all layers. -// 3. AttrMap[str->T] - map specifies value for particular layer. -template -using LayerVariantAttr = cv::util::variant< cv::util::monostate - , AttrMap - , Attr>; - -struct ParamDesc { - struct Model { - - Model(const std::string &model_path_, - const std::string &bin_path_) - : model_path(model_path_), bin_path(bin_path_) { - } - - std::string model_path; - std::string bin_path; - - LayerVariantAttr input_tensor_layout; - LayerVariantAttr input_model_layout; - LayerVariantAttr output_tensor_layout; - LayerVariantAttr output_model_layout; - LayerVariantAttr output_tensor_precision; - - LayerVariantAttr> new_shapes; - - LayerVariantAttr> mean_values; - LayerVariantAttr> scale_values; - - LayerVariantAttr interpolation; - }; - - struct CompiledModel { - std::string blob_path; - }; - - using Kind = cv::util::variant; - - ParamDesc(Kind &&kind_, - const std::string &device_, - const bool is_generic_, - const size_t num_in_, - const size_t num_out_) - : kind(std::move(kind_)), device(device_), - is_generic(is_generic_), - num_in(num_in_), num_out(num_out_) { - } - - Kind kind; - - std::string device; - bool is_generic; - - std::size_t num_in; - std::size_t num_out; - - std::vector input_names; - std::vector output_names; - - using PluginConfigT = std::map; - PluginConfigT config; - - size_t nireq = 1; -}; - -// NB: Just helper to avoid code duplication. -static detail::ParamDesc::Model& -getModelToSetAttrOrThrow(detail::ParamDesc::Kind &kind, - const std::string &attr_name) { - if (cv::util::holds_alternative(kind)) { - cv::util::throw_error( - std::logic_error("Specifying " + attr_name + " isn't" - " possible for compiled model.")); - } - GAPI_Assert(cv::util::holds_alternative(kind)); - return cv::util::get(kind); -} - -} // namespace detail - -/** - * @brief This structure provides functions - * that fill inference parameters for "OpenVINO Toolkit" model. - */ -template struct Params { -public: - /** @brief Class constructor. - - Constructs Params based on model information and specifies default values for other - inference description parameters. Model is loaded and compiled using "OpenVINO Toolkit". - - @param model_path Path to a model. - @param bin_path Path to a data file. - For IR format (*.bin): - If path is empty, will try to read a bin file with the same name as xml. - If the bin file with the same name is not found, will load IR without weights. - For PDPD (*.pdmodel) and ONNX (*.onnx) formats bin_path isn't used. - @param device target device to use. - */ - Params(const std::string &model_path, - const std::string &bin_path, - const std::string &device) - : m_desc( detail::ParamDesc::Kind{detail::ParamDesc::Model{model_path, bin_path}} - , device - , false /* is generic */ - , std::tuple_size::value - , std::tuple_size::value) { - } - - /** @overload - Use this constructor to work with pre-compiled network. - Model is imported from a pre-compiled blob. - - @param blob_path path to the compiled model (*.blob). - @param device target device to use. - */ - Params(const std::string &blob_path, - const std::string &device) - : m_desc( detail::ParamDesc::Kind{detail::ParamDesc::CompiledModel{blob_path}} - , device - , false /* is generic */ - , std::tuple_size::value - , std::tuple_size::value) { - } - - /** @brief Specifies sequence of network input layers names for inference. - - The function is used to associate cv::gapi::infer<> inputs with the model inputs. - Number of names has to match the number of network inputs as defined in G_API_NET(). - In case a network has only single input layer, there is no need to specify name manually. - - @param layer_names std::array where N is the number of inputs - as defined in the @ref G_API_NET. Contains names of input layers. - @return reference to this parameter structure. - */ - Params& cfgInputLayers(const std::vector &layer_names) { - m_desc.input_names = layer_names; - return *this; - } - - /** @brief Specifies sequence of network output layers names for inference. - - The function is used to associate cv::gapi::infer<> outputs with the model outputs. - Number of names has to match the number of network outputs as defined in G_API_NET(). - In case a network has only single output layer, there is no need to specify name manually. - - @param layer_names std::array where N is the number of outputs - as defined in the @ref G_API_NET. Contains names of output layers. - @return reference to this parameter structure. - */ - Params& cfgOutputLayers(const std::vector &layer_names) { - m_desc.output_names = layer_names; - return *this; - } - - /** @brief Specifies OpenVINO plugin configuration. - - The function is used to set configuration for OpenVINO plugin. Some parameters - can be different for each plugin. Please follow https://docs.openvinotoolkit.org/latest/index.html - to check information about specific plugin. - - @param config Map of pairs: (config parameter name, config parameter value). - @return reference to this parameter structure. - */ - Params& cfgPluginConfig(const detail::ParamDesc::PluginConfigT &config) { - m_desc.config = config; - return *this; - } - - /** @brief Specifies tensor layout for an input layer. - - The function is used to set tensor layout for an input layer. - - @param layout Tensor layout ("NCHW", "NWHC", etc) - will be applied to all input layers. - @return reference to this parameter structure. - */ - Params& cfgInputTensorLayout(std::string layout) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "input tensor layout") - .input_tensor_layout = std::move(layout); - return *this; - } - - /** @overload - @param layout_map Map of pairs: name of corresponding input layer - and its tensor layout represented in std::string ("NCHW", "NHWC", etc) - @return reference to this parameter structure. - */ - Params& - cfgInputTensorLayout(detail::AttrMap layout_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "input tensor layout") - .input_tensor_layout = std::move(layout_map); - return *this; - } - - /** @brief Specifies model layout for an input layer. - - The function is used to set model layout for an input layer. - - @param layout Model layout ("NCHW", "NHWC", etc) - will be applied to all input layers. - @return reference to this parameter structure. - */ - Params& cfgInputModelLayout(std::string layout) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "input model layout") - .input_model_layout = std::move(layout); - return *this; - } - - /** @overload - @param layout_map Map of pairs: name of corresponding input layer - and its model layout ("NCHW", "NHWC", etc) - @return reference to this parameter structure. - */ - Params& - cfgInputModelLayout(detail::AttrMap layout_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "input model layout") - .input_model_layout = std::move(layout_map); - return *this; - } - - /** @brief Specifies tensor layout for an output layer. - - The function is used to set tensor layout for an output layer. - - @param layout Tensor layout ("NCHW", "NWHC", etc) - will be applied to all output layers. - @return reference to this parameter structure. - */ - Params& cfgOutputTensorLayout(std::string layout) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor layout") - .output_tensor_layout = std::move(layout); - return *this; - } - - /** @overload - @param layout_map Map of pairs: name of corresponding output layer - and its tensor layout represented in std::string ("NCHW", "NHWC", etc) - @return reference to this parameter structure. - */ - Params& - cfgOutputTensorLayout(detail::AttrMap layout_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor layout") - .output_tensor_layout = std::move(layout_map); - return *this; - } - - /** @brief Specifies model layout for an output layer. - - The function is used to set model layout for an output layer. - - @param layout Model layout ("NCHW", "NHWC", etc) - will be applied to all output layers. - @return reference to this parameter structure. - */ - Params& cfgOutputModelLayout(std::string layout) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "output model layout") - .output_model_layout = std::move(layout); - return *this; - } - - /** @overload - @param layout_map Map of pairs: name of corresponding output layer - and its model layout ("NCHW", "NHWC", etc) - @return reference to this parameter structure. - */ - Params& - cfgOutputModelLayout(detail::AttrMap layout_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "output model layout") - .output_model_layout = std::move(layout_map); - return *this; - } - - /** @brief Specifies tensor precision for an output layer. - - The function is used to set tensor precision for an output layer.. - - @param precision Precision in OpenCV format (CV_8U, CV_32F, ...) - will be applied to all output layers. - @return reference to this parameter structure. - */ - Params& cfgOutputTensorPrecision(int precision) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor precision") - .output_tensor_precision = precision; - return *this; - } - - /** @overload - - @param precision_map Map of pairs: name of corresponding output layer - and its precision in OpenCV format (CV_8U, CV_32F, ...) - @return reference to this parameter structure. - */ - Params& - cfgOutputTensorPrecision(detail::AttrMap precision_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor precision") - .output_tensor_precision = std::move(precision_map); - return *this; - } - - /** @brief Specifies the new shape for input layers. - - The function is used to set new shape for input layers. - - @param new_shape New shape will be applied to all input layers. - @return reference to this parameter structure. - */ - Params& - cfgReshape(std::vector new_shape) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "reshape") - .new_shapes = std::move(new_shape); - return *this; - } - - /** @overload - - @param new_shape_map Map of pairs: name of corresponding output layer - and its new shape. - @return reference to this parameter structure. - */ - Params& - cfgReshape(detail::AttrMap> new_shape_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "reshape") - .new_shapes = std::move(new_shape_map); - return *this; - } - - /** @brief Specifies number of asynchronous inference requests. - - @param nireq Number of inference asynchronous requests. - @return reference to this parameter structure. - */ - Params& cfgNumRequests(const size_t nireq) { - if (nireq == 0) { - cv::util::throw_error( - std::logic_error("Number of inference requests" - " must be greater than zero.")); - } - m_desc.nireq = nireq; - return *this; - } - - /** @brief Specifies mean values for preprocessing. - * - The function is used to set mean values for input layer preprocessing. - - @param mean_values Float vector contains mean values - @return reference to this parameter structure. - */ - Params& cfgMean(std::vector mean_values) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "mean values") - .mean_values = std::move(mean_values); - return *this; - } - - /** @overload - - @param mean_map Map of pairs: name of corresponding input layer - and its mean values. - @return reference to this parameter structure. - */ - Params& cfgMean(detail::AttrMap> mean_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "mean values") - .mean_values = std::move(mean_map); - return *this; - } - - /** @brief Specifies scale values for preprocessing. - * - The function is used to set scale values for input layer preprocessing. - - @param scale_values Float vector contains scale values - @return reference to this parameter structure. - */ - Params& cfgScale(std::vector scale_values) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "scale values") - .scale_values = std::move(scale_values); - return *this; - } - - /** @overload - - @param scale_map Map of pairs: name of corresponding input layer - and its mean values. - @return reference to this parameter structure. - */ - Params& cfgScale(detail::AttrMap> scale_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "scale values") - .scale_values = std::move(scale_map); - return *this; - } - - /** @brief Specifies resize interpolation algorithm. - * - The function is used to configure resize preprocessing for input layer. - - @param interpolation Resize interpolation algorithm. - Supported algorithms: #INTER_NEAREST, #INTER_LINEAR, #INTER_CUBIC. - @return reference to this parameter structure. - */ - Params& cfgResize(int interpolation) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "resize preprocessing") - .interpolation = std::move(interpolation); - return *this; - } - - /** @overload - - @param interpolation Map of pairs: name of corresponding input layer - and its resize algorithm. - @return reference to this parameter structure. - */ - Params& cfgResize(detail::AttrMap interpolation) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "resize preprocessing") - .interpolation = std::move(interpolation); - return *this; - } - - // BEGIN(G-API's network parametrization API) - GBackend backend() const { return cv::gapi::ov::backend(); } - std::string tag() const { return Net::tag(); } - cv::util::any params() const { return { m_desc }; } - // END(G-API's network parametrization API) - -protected: - detail::ParamDesc m_desc; -}; - -/* -* @brief This structure provides functions for generic network type that -* fill inference parameters. -* @see struct Generic -*/ -template<> -class Params { -public: - /** @brief Class constructor. - - Constructs Params based on model information and specifies default values for other - inference description parameters. Model is loaded and compiled using "OpenVINO Toolkit". - - @param tag string tag of the network for which these parameters are intended. - @param model_path Path to a model. - @param bin_path Path to a data file. - For IR format (*.bin): - If path is empty, will try to read a bin file with the same name as xml. - If the bin file with the same name is not found, will load IR without weights. - For PDPD (*.pdmodel) and ONNX (*.onnx) formats bin_path isn't used. - @param device target device to use. - */ - Params(const std::string &tag, - const std::string &model_path, - const std::string &bin_path, - const std::string &device) - : m_tag(tag), - m_desc( detail::ParamDesc::Kind{detail::ParamDesc::Model{model_path, bin_path}} - , device - , true /* is generic */ - , 0u - , 0u) { - } - - /** @overload - - This constructor for pre-compiled networks. Model is imported from pre-compiled - blob. - - @param tag string tag of the network for which these parameters are intended. - @param blob_path path to the compiled model (*.blob). - @param device target device to use. - */ - Params(const std::string &tag, - const std::string &blob_path, - const std::string &device) - : m_tag(tag), - m_desc( detail::ParamDesc::Kind{detail::ParamDesc::CompiledModel{blob_path}} - , device - , true /* is generic */ - , 0u - , 0u) { - } - - /** @see ov::Params::cfgPluginConfig. */ - Params& cfgPluginConfig(const detail::ParamDesc::PluginConfigT &config) { - m_desc.config = config; - return *this; - } - - /** @see ov::Params::cfgInputTensorLayout. */ - Params& cfgInputTensorLayout(std::string layout) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "input tensor layout") - .input_tensor_layout = std::move(layout); - return *this; - } - - /** @overload */ - Params& - cfgInputTensorLayout(detail::AttrMap layout_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "input tensor layout") - .input_tensor_layout = std::move(layout_map); - return *this; - } - - /** @see ov::Params::cfgInputModelLayout. */ - Params& cfgInputModelLayout(std::string layout) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "input model layout") - .input_model_layout = std::move(layout); - return *this; - } - - /** @overload */ - Params& - cfgInputModelLayout(detail::AttrMap layout_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "input model layout") - .input_model_layout = std::move(layout_map); - return *this; - } - - /** @see ov::Params::cfgOutputTensorLayout. */ - Params& cfgOutputTensorLayout(std::string layout) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor layout") - .output_tensor_layout = std::move(layout); - return *this; - } - - /** @overload */ - Params& - cfgOutputTensorLayout(detail::AttrMap layout_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor layout") - .output_tensor_layout = std::move(layout_map); - return *this; - } - - /** @see ov::Params::cfgOutputModelLayout. */ - Params& cfgOutputModelLayout(std::string layout) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "output model layout") - .output_model_layout = std::move(layout); - return *this; - } - - /** @overload */ - Params& - cfgOutputModelLayout(detail::AttrMap layout_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "output model layout") - .output_model_layout = std::move(layout_map); - return *this; - } - - /** @see ov::Params::cfgOutputTensorPrecision. */ - Params& cfgOutputTensorPrecision(int precision) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor precision") - .output_tensor_precision = precision; - return *this; - } - - /** @overload */ - Params& - cfgOutputTensorPrecision(detail::AttrMap precision_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor precision") - .output_tensor_precision = std::move(precision_map); - return *this; - } - - /** @see ov::Params::cfgReshape. */ - Params& cfgReshape(std::vector new_shape) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "reshape") - .new_shapes = std::move(new_shape); - return *this; - } - - /** @overload */ - Params& - cfgReshape(detail::AttrMap> new_shape_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "reshape") - .new_shapes = std::move(new_shape_map); - return *this; - } - - /** @see ov::Params::cfgNumRequests. */ - Params& cfgNumRequests(const size_t nireq) { - if (nireq == 0) { - cv::util::throw_error( - std::logic_error("Number of inference requests" - " must be greater than zero.")); - } - m_desc.nireq = nireq; - return *this; - } - - /** @see ov::Params::cfgMean. */ - Params& cfgMean(std::vector mean_values) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "mean values") - .mean_values = std::move(mean_values); - return *this; - } - - /** @overload */ - Params& cfgMean(detail::AttrMap> mean_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "mean values") - .mean_values = std::move(mean_map); - return *this; - } - - /** @see ov::Params::cfgScale. */ - Params& cfgScale(std::vector scale_values) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "scale values") - .scale_values = std::move(scale_values); - return *this; - } - - /** @overload */ - Params& cfgScale(detail::AttrMap> scale_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "scale values") - .scale_values = std::move(scale_map); - return *this; - } - - /** @see ov::Params::cfgResize. */ - Params& cfgResize(int interpolation) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "resize preprocessing") - .interpolation = std::move(interpolation); - return *this; - } - - /** @overload */ - Params& cfgResize(detail::AttrMap interpolation) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "resize preprocessing") - .interpolation = std::move(interpolation); - return *this; - } - - // BEGIN(G-API's network parametrization API) - GBackend backend() const { return cv::gapi::ov::backend(); } - std::string tag() const { return m_tag; } - cv::util::any params() const { return { m_desc }; } - // END(G-API's network parametrization API) - -protected: - std::string m_tag; - detail::ParamDesc m_desc; -}; - -} // namespace ov - -namespace wip { namespace ov { -/** - * @brief Ask G-API OpenVINO backend to run only inference of model provided. - * - * G-API OpenVINO backend will perform only the inference of the model provided - * without populating input and copying back output data. - * This mode is used to evaluate the pure inference performance of the model without - * taking into account the i/o data transfer. - */ -struct benchmark_mode { }; - -} // namespace ov -} // namespace wip - -} // namespace gapi - -namespace detail -{ - template<> struct CompileArgTag - { - static const char* tag() { return "gapi.wip.ov.benchmark_mode"; } - }; -} - -} // namespace cv - -#endif // OPENCV_GAPI_INFER_OV_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2023 Intel Corporation + +#ifndef OPENCV_GAPI_INFER_OV_HPP +#define OPENCV_GAPI_INFER_OV_HPP + +#include + +#include +#include // GAPI_EXPORTS +#include // GKernelType[M], GBackend +#include // Generic + +#include + +namespace cv { +namespace gapi { + +/** + * @brief This namespace contains G-API OpenVINO 2.0 backend functions, + * structures, and symbols. + */ +namespace ov { + +GAPI_EXPORTS cv::gapi::GBackend backend(); + +namespace detail { + +template +using AttrMap = std::map; +// NB: This type is supposed to be used to hold in/out layers +// attributes such as precision, layout, shape etc. +// +// User can provide attributes either: +// 1. cv::util::monostate - No value specified explicitly. +// 2. Attr - value specified explicitly that should be broadcasted to all layers. +// 3. AttrMap[str->T] - map specifies value for particular layer. +template +using LayerVariantAttr = cv::util::variant< cv::util::monostate + , AttrMap + , Attr>; + +struct ParamDesc { + struct Model { + + Model(const std::string &model_path_, + const std::string &bin_path_) + : model_path(model_path_), bin_path(bin_path_) { + } + + std::string model_path; + std::string bin_path; + + LayerVariantAttr input_tensor_layout; + LayerVariantAttr input_model_layout; + LayerVariantAttr output_tensor_layout; + LayerVariantAttr output_model_layout; + LayerVariantAttr output_tensor_precision; + + LayerVariantAttr> new_shapes; + + LayerVariantAttr> mean_values; + LayerVariantAttr> scale_values; + + LayerVariantAttr interpolation; + }; + + struct CompiledModel { + std::string blob_path; + }; + + using Kind = cv::util::variant; + + ParamDesc(Kind &&kind_, + const std::string &device_, + const bool is_generic_, + const size_t num_in_, + const size_t num_out_) + : kind(std::move(kind_)), device(device_), + is_generic(is_generic_), + num_in(num_in_), num_out(num_out_) { + } + + Kind kind; + + std::string device; + bool is_generic; + + std::size_t num_in; + std::size_t num_out; + + std::vector input_names; + std::vector output_names; + + using PluginConfigT = std::map; + PluginConfigT config; + + size_t nireq = 1; +}; + +// NB: Just helper to avoid code duplication. +static detail::ParamDesc::Model& +getModelToSetAttrOrThrow(detail::ParamDesc::Kind &kind, + const std::string &attr_name) { + if (cv::util::holds_alternative(kind)) { + cv::util::throw_error( + std::logic_error("Specifying " + attr_name + " isn't" + " possible for compiled model.")); + } + GAPI_Assert(cv::util::holds_alternative(kind)); + return cv::util::get(kind); +} + +} // namespace detail + +/** + * @brief This structure provides functions + * that fill inference parameters for "OpenVINO Toolkit" model. + */ +template struct Params { +public: + /** @brief Class constructor. + + Constructs Params based on model information and specifies default values for other + inference description parameters. Model is loaded and compiled using "OpenVINO Toolkit". + + @param model_path Path to a model. + @param bin_path Path to a data file. + For IR format (*.bin): + If path is empty, will try to read a bin file with the same name as xml. + If the bin file with the same name is not found, will load IR without weights. + For PDPD (*.pdmodel) and ONNX (*.onnx) formats bin_path isn't used. + @param device target device to use. + */ + Params(const std::string &model_path, + const std::string &bin_path, + const std::string &device) + : m_desc( detail::ParamDesc::Kind{detail::ParamDesc::Model{model_path, bin_path}} + , device + , false /* is generic */ + , std::tuple_size::value + , std::tuple_size::value) { + } + + /** @overload + Use this constructor to work with pre-compiled network. + Model is imported from a pre-compiled blob. + + @param blob_path path to the compiled model (*.blob). + @param device target device to use. + */ + Params(const std::string &blob_path, + const std::string &device) + : m_desc( detail::ParamDesc::Kind{detail::ParamDesc::CompiledModel{blob_path}} + , device + , false /* is generic */ + , std::tuple_size::value + , std::tuple_size::value) { + } + + /** @brief Specifies sequence of network input layers names for inference. + + The function is used to associate cv::gapi::infer<> inputs with the model inputs. + Number of names has to match the number of network inputs as defined in G_API_NET(). + In case a network has only single input layer, there is no need to specify name manually. + + @param layer_names std::array where N is the number of inputs + as defined in the @ref G_API_NET. Contains names of input layers. + @return reference to this parameter structure. + */ + Params& cfgInputLayers(const std::vector &layer_names) { + m_desc.input_names = layer_names; + return *this; + } + + /** @brief Specifies sequence of network output layers names for inference. + + The function is used to associate cv::gapi::infer<> outputs with the model outputs. + Number of names has to match the number of network outputs as defined in G_API_NET(). + In case a network has only single output layer, there is no need to specify name manually. + + @param layer_names std::array where N is the number of outputs + as defined in the @ref G_API_NET. Contains names of output layers. + @return reference to this parameter structure. + */ + Params& cfgOutputLayers(const std::vector &layer_names) { + m_desc.output_names = layer_names; + return *this; + } + + /** @brief Specifies OpenVINO plugin configuration. + + The function is used to set configuration for OpenVINO plugin. Some parameters + can be different for each plugin. Please follow https://docs.openvinotoolkit.org/latest/index.html + to check information about specific plugin. + + @param config Map of pairs: (config parameter name, config parameter value). + @return reference to this parameter structure. + */ + Params& cfgPluginConfig(const detail::ParamDesc::PluginConfigT &config) { + m_desc.config = config; + return *this; + } + + /** @brief Specifies tensor layout for an input layer. + + The function is used to set tensor layout for an input layer. + + @param layout Tensor layout ("NCHW", "NWHC", etc) + will be applied to all input layers. + @return reference to this parameter structure. + */ + Params& cfgInputTensorLayout(std::string layout) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "input tensor layout") + .input_tensor_layout = std::move(layout); + return *this; + } + + /** @overload + @param layout_map Map of pairs: name of corresponding input layer + and its tensor layout represented in std::string ("NCHW", "NHWC", etc) + @return reference to this parameter structure. + */ + Params& + cfgInputTensorLayout(detail::AttrMap layout_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "input tensor layout") + .input_tensor_layout = std::move(layout_map); + return *this; + } + + /** @brief Specifies model layout for an input layer. + + The function is used to set model layout for an input layer. + + @param layout Model layout ("NCHW", "NHWC", etc) + will be applied to all input layers. + @return reference to this parameter structure. + */ + Params& cfgInputModelLayout(std::string layout) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "input model layout") + .input_model_layout = std::move(layout); + return *this; + } + + /** @overload + @param layout_map Map of pairs: name of corresponding input layer + and its model layout ("NCHW", "NHWC", etc) + @return reference to this parameter structure. + */ + Params& + cfgInputModelLayout(detail::AttrMap layout_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "input model layout") + .input_model_layout = std::move(layout_map); + return *this; + } + + /** @brief Specifies tensor layout for an output layer. + + The function is used to set tensor layout for an output layer. + + @param layout Tensor layout ("NCHW", "NWHC", etc) + will be applied to all output layers. + @return reference to this parameter structure. + */ + Params& cfgOutputTensorLayout(std::string layout) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor layout") + .output_tensor_layout = std::move(layout); + return *this; + } + + /** @overload + @param layout_map Map of pairs: name of corresponding output layer + and its tensor layout represented in std::string ("NCHW", "NHWC", etc) + @return reference to this parameter structure. + */ + Params& + cfgOutputTensorLayout(detail::AttrMap layout_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor layout") + .output_tensor_layout = std::move(layout_map); + return *this; + } + + /** @brief Specifies model layout for an output layer. + + The function is used to set model layout for an output layer. + + @param layout Model layout ("NCHW", "NHWC", etc) + will be applied to all output layers. + @return reference to this parameter structure. + */ + Params& cfgOutputModelLayout(std::string layout) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "output model layout") + .output_model_layout = std::move(layout); + return *this; + } + + /** @overload + @param layout_map Map of pairs: name of corresponding output layer + and its model layout ("NCHW", "NHWC", etc) + @return reference to this parameter structure. + */ + Params& + cfgOutputModelLayout(detail::AttrMap layout_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "output model layout") + .output_model_layout = std::move(layout_map); + return *this; + } + + /** @brief Specifies tensor precision for an output layer. + + The function is used to set tensor precision for an output layer.. + + @param precision Precision in OpenCV format (CV_8U, CV_32F, ...) + will be applied to all output layers. + @return reference to this parameter structure. + */ + Params& cfgOutputTensorPrecision(int precision) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor precision") + .output_tensor_precision = precision; + return *this; + } + + /** @overload + + @param precision_map Map of pairs: name of corresponding output layer + and its precision in OpenCV format (CV_8U, CV_32F, ...) + @return reference to this parameter structure. + */ + Params& + cfgOutputTensorPrecision(detail::AttrMap precision_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor precision") + .output_tensor_precision = std::move(precision_map); + return *this; + } + + /** @brief Specifies the new shape for input layers. + + The function is used to set new shape for input layers. + + @param new_shape New shape will be applied to all input layers. + @return reference to this parameter structure. + */ + Params& + cfgReshape(std::vector new_shape) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "reshape") + .new_shapes = std::move(new_shape); + return *this; + } + + /** @overload + + @param new_shape_map Map of pairs: name of corresponding output layer + and its new shape. + @return reference to this parameter structure. + */ + Params& + cfgReshape(detail::AttrMap> new_shape_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "reshape") + .new_shapes = std::move(new_shape_map); + return *this; + } + + /** @brief Specifies number of asynchronous inference requests. + + @param nireq Number of inference asynchronous requests. + @return reference to this parameter structure. + */ + Params& cfgNumRequests(const size_t nireq) { + if (nireq == 0) { + cv::util::throw_error( + std::logic_error("Number of inference requests" + " must be greater than zero.")); + } + m_desc.nireq = nireq; + return *this; + } + + /** @brief Specifies mean values for preprocessing. + * + The function is used to set mean values for input layer preprocessing. + + @param mean_values Float vector contains mean values + @return reference to this parameter structure. + */ + Params& cfgMean(std::vector mean_values) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "mean values") + .mean_values = std::move(mean_values); + return *this; + } + + /** @overload + + @param mean_map Map of pairs: name of corresponding input layer + and its mean values. + @return reference to this parameter structure. + */ + Params& cfgMean(detail::AttrMap> mean_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "mean values") + .mean_values = std::move(mean_map); + return *this; + } + + /** @brief Specifies scale values for preprocessing. + * + The function is used to set scale values for input layer preprocessing. + + @param scale_values Float vector contains scale values + @return reference to this parameter structure. + */ + Params& cfgScale(std::vector scale_values) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "scale values") + .scale_values = std::move(scale_values); + return *this; + } + + /** @overload + + @param scale_map Map of pairs: name of corresponding input layer + and its mean values. + @return reference to this parameter structure. + */ + Params& cfgScale(detail::AttrMap> scale_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "scale values") + .scale_values = std::move(scale_map); + return *this; + } + + /** @brief Specifies resize interpolation algorithm. + * + The function is used to configure resize preprocessing for input layer. + + @param interpolation Resize interpolation algorithm. + Supported algorithms: #INTER_NEAREST, #INTER_LINEAR, #INTER_CUBIC. + @return reference to this parameter structure. + */ + Params& cfgResize(int interpolation) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "resize preprocessing") + .interpolation = std::move(interpolation); + return *this; + } + + /** @overload + + @param interpolation Map of pairs: name of corresponding input layer + and its resize algorithm. + @return reference to this parameter structure. + */ + Params& cfgResize(detail::AttrMap interpolation) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "resize preprocessing") + .interpolation = std::move(interpolation); + return *this; + } + + // BEGIN(G-API's network parametrization API) + GBackend backend() const { return cv::gapi::ov::backend(); } + std::string tag() const { return Net::tag(); } + cv::util::any params() const { return { m_desc }; } + // END(G-API's network parametrization API) + +protected: + detail::ParamDesc m_desc; +}; + +/* +* @brief This structure provides functions for generic network type that +* fill inference parameters. +* @see struct Generic +*/ +template<> +class Params { +public: + /** @brief Class constructor. + + Constructs Params based on model information and specifies default values for other + inference description parameters. Model is loaded and compiled using "OpenVINO Toolkit". + + @param tag string tag of the network for which these parameters are intended. + @param model_path Path to a model. + @param bin_path Path to a data file. + For IR format (*.bin): + If path is empty, will try to read a bin file with the same name as xml. + If the bin file with the same name is not found, will load IR without weights. + For PDPD (*.pdmodel) and ONNX (*.onnx) formats bin_path isn't used. + @param device target device to use. + */ + Params(const std::string &tag, + const std::string &model_path, + const std::string &bin_path, + const std::string &device) + : m_tag(tag), + m_desc( detail::ParamDesc::Kind{detail::ParamDesc::Model{model_path, bin_path}} + , device + , true /* is generic */ + , 0u + , 0u) { + } + + /** @overload + + This constructor for pre-compiled networks. Model is imported from pre-compiled + blob. + + @param tag string tag of the network for which these parameters are intended. + @param blob_path path to the compiled model (*.blob). + @param device target device to use. + */ + Params(const std::string &tag, + const std::string &blob_path, + const std::string &device) + : m_tag(tag), + m_desc( detail::ParamDesc::Kind{detail::ParamDesc::CompiledModel{blob_path}} + , device + , true /* is generic */ + , 0u + , 0u) { + } + + /** @see ov::Params::cfgPluginConfig. */ + Params& cfgPluginConfig(const detail::ParamDesc::PluginConfigT &config) { + m_desc.config = config; + return *this; + } + + /** @see ov::Params::cfgInputTensorLayout. */ + Params& cfgInputTensorLayout(std::string layout) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "input tensor layout") + .input_tensor_layout = std::move(layout); + return *this; + } + + /** @overload */ + Params& + cfgInputTensorLayout(detail::AttrMap layout_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "input tensor layout") + .input_tensor_layout = std::move(layout_map); + return *this; + } + + /** @see ov::Params::cfgInputModelLayout. */ + Params& cfgInputModelLayout(std::string layout) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "input model layout") + .input_model_layout = std::move(layout); + return *this; + } + + /** @overload */ + Params& + cfgInputModelLayout(detail::AttrMap layout_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "input model layout") + .input_model_layout = std::move(layout_map); + return *this; + } + + /** @see ov::Params::cfgOutputTensorLayout. */ + Params& cfgOutputTensorLayout(std::string layout) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor layout") + .output_tensor_layout = std::move(layout); + return *this; + } + + /** @overload */ + Params& + cfgOutputTensorLayout(detail::AttrMap layout_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor layout") + .output_tensor_layout = std::move(layout_map); + return *this; + } + + /** @see ov::Params::cfgOutputModelLayout. */ + Params& cfgOutputModelLayout(std::string layout) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "output model layout") + .output_model_layout = std::move(layout); + return *this; + } + + /** @overload */ + Params& + cfgOutputModelLayout(detail::AttrMap layout_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "output model layout") + .output_model_layout = std::move(layout_map); + return *this; + } + + /** @see ov::Params::cfgOutputTensorPrecision. */ + Params& cfgOutputTensorPrecision(int precision) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor precision") + .output_tensor_precision = precision; + return *this; + } + + /** @overload */ + Params& + cfgOutputTensorPrecision(detail::AttrMap precision_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor precision") + .output_tensor_precision = std::move(precision_map); + return *this; + } + + /** @see ov::Params::cfgReshape. */ + Params& cfgReshape(std::vector new_shape) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "reshape") + .new_shapes = std::move(new_shape); + return *this; + } + + /** @overload */ + Params& + cfgReshape(detail::AttrMap> new_shape_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "reshape") + .new_shapes = std::move(new_shape_map); + return *this; + } + + /** @see ov::Params::cfgNumRequests. */ + Params& cfgNumRequests(const size_t nireq) { + if (nireq == 0) { + cv::util::throw_error( + std::logic_error("Number of inference requests" + " must be greater than zero.")); + } + m_desc.nireq = nireq; + return *this; + } + + /** @see ov::Params::cfgMean. */ + Params& cfgMean(std::vector mean_values) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "mean values") + .mean_values = std::move(mean_values); + return *this; + } + + /** @overload */ + Params& cfgMean(detail::AttrMap> mean_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "mean values") + .mean_values = std::move(mean_map); + return *this; + } + + /** @see ov::Params::cfgScale. */ + Params& cfgScale(std::vector scale_values) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "scale values") + .scale_values = std::move(scale_values); + return *this; + } + + /** @overload */ + Params& cfgScale(detail::AttrMap> scale_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "scale values") + .scale_values = std::move(scale_map); + return *this; + } + + /** @see ov::Params::cfgResize. */ + Params& cfgResize(int interpolation) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "resize preprocessing") + .interpolation = std::move(interpolation); + return *this; + } + + /** @overload */ + Params& cfgResize(detail::AttrMap interpolation) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "resize preprocessing") + .interpolation = std::move(interpolation); + return *this; + } + + // BEGIN(G-API's network parametrization API) + GBackend backend() const { return cv::gapi::ov::backend(); } + std::string tag() const { return m_tag; } + cv::util::any params() const { return { m_desc }; } + // END(G-API's network parametrization API) + +protected: + std::string m_tag; + detail::ParamDesc m_desc; +}; + +} // namespace ov + +namespace wip { namespace ov { +/** + * @brief Ask G-API OpenVINO backend to run only inference of model provided. + * + * G-API OpenVINO backend will perform only the inference of the model provided + * without populating input and copying back output data. + * This mode is used to evaluate the pure inference performance of the model without + * taking into account the i/o data transfer. + */ +struct benchmark_mode { }; + +} // namespace ov +} // namespace wip + +} // namespace gapi + +namespace detail +{ + template<> struct CompileArgTag + { + static const char* tag() { return "gapi.wip.ov.benchmark_mode"; } + }; +} + +} // namespace cv + +#endif // OPENCV_GAPI_INFER_OV_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/parsers.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/parsers.hpp index e39d6fd4c6..33dfa25e01 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/parsers.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/parsers.hpp @@ -1,138 +1,138 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020 Intel Corporation - - -#ifndef OPENCV_GAPI_PARSERS_HPP -#define OPENCV_GAPI_PARSERS_HPP - -#include // std::tuple - -#include -#include - -namespace cv { namespace gapi { -namespace nn { -namespace parsers { - using GRects = GArray; - using GDetections = std::tuple, GArray>; - - G_TYPED_KERNEL(GParseSSDBL, , float, int)>, - "org.opencv.nn.parsers.parseSSD_BL") { - static std::tuple outMeta(const GMatDesc&, const GOpaqueDesc&, float, int) { - return std::make_tuple(empty_array_desc(), empty_array_desc()); - } - }; - - G_TYPED_KERNEL(GParseSSD, , float, bool, bool)>, - "org.opencv.nn.parsers.parseSSD") { - static GArrayDesc outMeta(const GMatDesc&, const GOpaqueDesc&, float, bool, bool) { - return empty_array_desc(); - } - }; - - G_TYPED_KERNEL(GParseYolo, , float, float, std::vector)>, - "org.opencv.nn.parsers.parseYolo") { - static std::tuple outMeta(const GMatDesc&, const GOpaqueDesc&, - float, float, const std::vector&) { - return std::make_tuple(empty_array_desc(), empty_array_desc()); - } - static const std::vector& defaultAnchors() { - static std::vector anchors { - 0.57273f, 0.677385f, 1.87446f, 2.06253f, 3.33843f, 5.47434f, 7.88282f, 3.52778f, 9.77052f, 9.16828f - }; - return anchors; - } - }; -} // namespace parsers -} // namespace nn - -/** @brief Parses output of SSD network. - -Extracts detection information (box, confidence, label) from SSD output and -filters it by given confidence and label. - -@note Function textual ID is "org.opencv.nn.parsers.parseSSD_BL" - -@param in Input CV_32F tensor with {1,1,N,7} dimensions. -@param inSz Size to project detected boxes to (size of the input image). -@param confidenceThreshold If confidence of the -detection is smaller than confidence threshold, detection is rejected. -@param filterLabel If provided (!= -1), only detections with -given label will get to the output. -@return a tuple with a vector of detected boxes and a vector of appropriate labels. -*/ -GAPI_EXPORTS_W std::tuple, GArray> parseSSD(const GMat& in, - const GOpaque& inSz, - const float confidenceThreshold = 0.5f, - const int filterLabel = -1); - -/** @brief Parses output of SSD network. - -Extracts detection information (box, confidence) from SSD output and -filters it by given confidence and by going out of bounds. - -@note Function textual ID is "org.opencv.nn.parsers.parseSSD" - -@param in Input CV_32F tensor with {1,1,N,7} dimensions. -@param inSz Size to project detected boxes to (size of the input image). -@param confidenceThreshold If confidence of the -detection is smaller than confidence threshold, detection is rejected. -@param alignmentToSquare If provided true, bounding boxes are extended to squares. -The center of the rectangle remains unchanged, the side of the square is -the larger side of the rectangle. -@param filterOutOfBounds If provided true, out-of-frame boxes are filtered. -@return a vector of detected bounding boxes. -*/ -GAPI_EXPORTS_W GArray parseSSD(const GMat& in, - const GOpaque& inSz, - const float confidenceThreshold, - const bool alignmentToSquare, - const bool filterOutOfBounds); - -/** @brief Parses output of Yolo network. - -Extracts detection information (box, confidence, label) from Yolo output, -filters it by given confidence and performs non-maximum suppression for overlapping boxes. - -@note Function textual ID is "org.opencv.nn.parsers.parseYolo" - -@param in Input CV_32F tensor with {1,13,13,N} dimensions, N should satisfy: -\f[\texttt{N} = (\texttt{num_classes} + \texttt{5}) * \texttt{5},\f] -where num_classes - a number of classes Yolo network was trained with. -@param inSz Size to project detected boxes to (size of the input image). -@param confidenceThreshold If confidence of the -detection is smaller than confidence threshold, detection is rejected. -@param nmsThreshold Non-maximum suppression threshold which controls minimum -relative box intersection area required for rejecting the box with a smaller confidence. -If 1.f, nms is not performed and no boxes are rejected. -@param anchors Anchors Yolo network was trained with. -@note The default anchor values are specified for YOLO v2 Tiny as described in Intel Open Model Zoo -documentation. -@return a tuple with a vector of detected boxes and a vector of appropriate labels. -*/ -GAPI_EXPORTS_W std::tuple, GArray> parseYolo(const GMat& in, - const GOpaque& inSz, - const float confidenceThreshold = 0.5f, - const float nmsThreshold = 0.5f, - const std::vector& anchors - = nn::parsers::GParseYolo::defaultAnchors()); - -} // namespace gapi -} // namespace cv - -// Reimport parseSSD & parseYolo under their initial namespace -namespace cv { -namespace gapi { -namespace streaming { - -using cv::gapi::parseSSD; -using cv::gapi::parseYolo; - -} // namespace streaming -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_PARSERS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020 Intel Corporation + + +#ifndef OPENCV_GAPI_PARSERS_HPP +#define OPENCV_GAPI_PARSERS_HPP + +#include // std::tuple + +#include +#include + +namespace cv { namespace gapi { +namespace nn { +namespace parsers { + using GRects = GArray; + using GDetections = std::tuple, GArray>; + + G_TYPED_KERNEL(GParseSSDBL, , float, int)>, + "org.opencv.nn.parsers.parseSSD_BL") { + static std::tuple outMeta(const GMatDesc&, const GOpaqueDesc&, float, int) { + return std::make_tuple(empty_array_desc(), empty_array_desc()); + } + }; + + G_TYPED_KERNEL(GParseSSD, , float, bool, bool)>, + "org.opencv.nn.parsers.parseSSD") { + static GArrayDesc outMeta(const GMatDesc&, const GOpaqueDesc&, float, bool, bool) { + return empty_array_desc(); + } + }; + + G_TYPED_KERNEL(GParseYolo, , float, float, std::vector)>, + "org.opencv.nn.parsers.parseYolo") { + static std::tuple outMeta(const GMatDesc&, const GOpaqueDesc&, + float, float, const std::vector&) { + return std::make_tuple(empty_array_desc(), empty_array_desc()); + } + static const std::vector& defaultAnchors() { + static std::vector anchors { + 0.57273f, 0.677385f, 1.87446f, 2.06253f, 3.33843f, 5.47434f, 7.88282f, 3.52778f, 9.77052f, 9.16828f + }; + return anchors; + } + }; +} // namespace parsers +} // namespace nn + +/** @brief Parses output of SSD network. + +Extracts detection information (box, confidence, label) from SSD output and +filters it by given confidence and label. + +@note Function textual ID is "org.opencv.nn.parsers.parseSSD_BL" + +@param in Input CV_32F tensor with {1,1,N,7} dimensions. +@param inSz Size to project detected boxes to (size of the input image). +@param confidenceThreshold If confidence of the +detection is smaller than confidence threshold, detection is rejected. +@param filterLabel If provided (!= -1), only detections with +given label will get to the output. +@return a tuple with a vector of detected boxes and a vector of appropriate labels. +*/ +GAPI_EXPORTS_W std::tuple, GArray> parseSSD(const GMat& in, + const GOpaque& inSz, + const float confidenceThreshold = 0.5f, + const int filterLabel = -1); + +/** @brief Parses output of SSD network. + +Extracts detection information (box, confidence) from SSD output and +filters it by given confidence and by going out of bounds. + +@note Function textual ID is "org.opencv.nn.parsers.parseSSD" + +@param in Input CV_32F tensor with {1,1,N,7} dimensions. +@param inSz Size to project detected boxes to (size of the input image). +@param confidenceThreshold If confidence of the +detection is smaller than confidence threshold, detection is rejected. +@param alignmentToSquare If provided true, bounding boxes are extended to squares. +The center of the rectangle remains unchanged, the side of the square is +the larger side of the rectangle. +@param filterOutOfBounds If provided true, out-of-frame boxes are filtered. +@return a vector of detected bounding boxes. +*/ +GAPI_EXPORTS_W GArray parseSSD(const GMat& in, + const GOpaque& inSz, + const float confidenceThreshold, + const bool alignmentToSquare, + const bool filterOutOfBounds); + +/** @brief Parses output of Yolo network. + +Extracts detection information (box, confidence, label) from Yolo output, +filters it by given confidence and performs non-maximum suppression for overlapping boxes. + +@note Function textual ID is "org.opencv.nn.parsers.parseYolo" + +@param in Input CV_32F tensor with {1,13,13,N} dimensions, N should satisfy: +\f[\texttt{N} = (\texttt{num_classes} + \texttt{5}) * \texttt{5},\f] +where num_classes - a number of classes Yolo network was trained with. +@param inSz Size to project detected boxes to (size of the input image). +@param confidenceThreshold If confidence of the +detection is smaller than confidence threshold, detection is rejected. +@param nmsThreshold Non-maximum suppression threshold which controls minimum +relative box intersection area required for rejecting the box with a smaller confidence. +If 1.f, nms is not performed and no boxes are rejected. +@param anchors Anchors Yolo network was trained with. +@note The default anchor values are specified for YOLO v2 Tiny as described in Intel Open Model Zoo +documentation. +@return a tuple with a vector of detected boxes and a vector of appropriate labels. +*/ +GAPI_EXPORTS_W std::tuple, GArray> parseYolo(const GMat& in, + const GOpaque& inSz, + const float confidenceThreshold = 0.5f, + const float nmsThreshold = 0.5f, + const std::vector& anchors + = nn::parsers::GParseYolo::defaultAnchors()); + +} // namespace gapi +} // namespace cv + +// Reimport parseSSD & parseYolo under their initial namespace +namespace cv { +namespace gapi { +namespace streaming { + +using cv::gapi::parseSSD; +using cv::gapi::parseYolo; + +} // namespace streaming +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_PARSERS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/media.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/media.hpp index 1470f00d04..c959832ef0 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/media.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/media.hpp @@ -1,258 +1,258 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020 Intel Corporation - -#ifndef OPENCV_GAPI_MEDIA_HPP -#define OPENCV_GAPI_MEDIA_HPP - -#include // unique_ptr<>, shared_ptr<> -#include // array<> -#include // function<> -#include // forward<>() - -#include -#include - -// Forward declaration -namespace cv { -namespace gapi { -namespace s11n { -struct IOStream; -struct IIStream; -} // namespace s11n -} // namespace gapi -} // namespace cv - -namespace cv { - -/** \addtogroup gapi_data_structures - * @{ - * - * @brief Extra G-API data structures used to pass input/output data - * to the graph for processing. - */ - -/** - * @brief cv::MediaFrame class represents an image/media frame - * obtained from an external source. - * - * cv::MediaFrame represents image data as specified in - * cv::MediaFormat. cv::MediaFrame is designed to be a thin wrapper over some - * external memory of buffer; the class itself provides an uniform - * interface over such types of memory. cv::MediaFrame wraps data from - * a camera driver or from a media codec and provides an abstraction - * layer over this memory to G-API. MediaFrame defines a compact interface - * to access and manage the underlying data; the implementation is - * fully defined by the associated Adapter (which is usually - * user-defined). - * - * @sa cv::RMat - */ -class GAPI_EXPORTS MediaFrame { -public: - /// This enum defines different types of cv::MediaFrame provided - /// access to the underlying data. Note that different flags can't - /// be combined in this version. - enum class Access { - R, ///< Access data for reading - W, ///< Access data for writing - }; - class IAdapter; - class View; - using AdapterPtr = std::unique_ptr; - - /** - * @brief Constructs an empty MediaFrame - * - * The constructed object has no any data associated with it. - */ - MediaFrame(); - - /** - * @brief Constructs a MediaFrame with the given - * Adapter. MediaFrame takes ownership over the passed adapter. - * - * @param p an unique pointer to instance of IAdapter derived class. - */ - explicit MediaFrame(AdapterPtr &&p); - - /** - * @overload - * @brief Constructs a MediaFrame with the given parameters for - * the Adapter. The adapter of type `T` is costructed on the fly. - * - * @param args list of arguments to construct an adapter of type - * `T`. - */ - template static cv::MediaFrame Create(Args&&... args); - - /** - * @brief Obtain access to the underlying data with the given - * mode. - * - * Depending on the associated Adapter and the data wrapped, this - * method may be cheap (e.g., the underlying memory is local) or - * costly (if the underlying memory is external or device - * memory). - * - * @param mode an access mode flag - * @return a MediaFrame::View object. The views should be handled - * carefully, refer to the MediaFrame::View documentation for details. - */ - View access(Access mode) const; - - /** - * @brief Returns a media frame descriptor -- the information - * about the media format, dimensions, etc. - * @return a cv::GFrameDesc - */ - cv::GFrameDesc desc() const; - - // FIXME: design a better solution - // Should be used only if the actual adapter provides implementation - /// @private -- exclude from the OpenCV documentation for now. - cv::util::any blobParams() const; - - /** - * @brief Casts and returns the associated MediaFrame adapter to - * the particular adapter type `T`, returns nullptr if the type is - * different. - * - * This method may be useful if the adapter type is known by the - * caller, and some lower level access to the memory is required. - * Depending on the memory type, it may be more efficient than - * access(). - * - * @return a pointer to the adapter object, nullptr if the adapter - * type is different. - */ - template T* get() const { - static_assert(std::is_base_of::value, - "T is not derived from cv::MediaFrame::IAdapter!"); - auto* adapter = getAdapter(); - GAPI_Assert(adapter != nullptr); - return dynamic_cast(adapter); - } - - /** - * @brief Serialize MediaFrame's data to a byte array. - * - * @note The actual logic is implemented by frame's adapter class. - * Does nothing by default. - * - * @param os Bytestream to store serialized MediaFrame data in. - */ - void serialize(cv::gapi::s11n::IOStream& os) const; - -private: - struct Priv; - std::shared_ptr m; - IAdapter* getAdapter() const; -}; - -template -inline cv::MediaFrame cv::MediaFrame::Create(Args&&... args) { - std::unique_ptr ptr(new T(std::forward(args)...)); - return cv::MediaFrame(std::move(ptr)); -} - -/** - * @brief Provides access to the MediaFrame's underlying data. - * - * This object contains the necessary information to access the pixel - * data of the associated MediaFrame: arrays of pointers and strides - * (distance between every plane row, in bytes) for every image - * plane, as defined in cv::MediaFormat. - * There may be up to four image planes in MediaFrame. - * - * Depending on the MediaFrame::Access flag passed in - * MediaFrame::access(), a MediaFrame::View may be read- or - * write-only. - * - * Depending on the MediaFrame::IAdapter implementation associated - * with the parent MediaFrame, writing to memory with - * MediaFrame::Access::R flag may have no effect or lead to - * undefined behavior. Same applies to reading the memory with - * MediaFrame::Access::W flag -- again, depending on the IAdapter - * implementation, the host-side buffer the view provides access to - * may have no current data stored in (so in-place editing of the - * buffer contents may not be possible). - * - * MediaFrame::View objects must be handled carefully, as an external - * resource associated with MediaFrame may be locked for the time the - * MediaFrame::View object exists. Obtaining MediaFrame::View should - * be seen as "map" and destroying it as "unmap" in the "map/unmap" - * idiom (applicable to OpenCL, device memory, remote - * memory). - * - * When a MediaFrame buffer is accessed for writing, and the memory - * under MediaFrame::View::Ptrs is altered, the data synchronization - * of a host-side and device/remote buffer is not guaranteed until the - * MediaFrame::View is destroyed. In other words, the real data on the - * device or in a remote target may be updated at the MediaFrame::View - * destruction only -- but it depends on the associated - * MediaFrame::IAdapter implementation. - */ -class GAPI_EXPORTS MediaFrame::View final { -public: - static constexpr const size_t MAX_PLANES = 4; - using Ptrs = std::array; - using Strides = std::array; // in bytes - using Callback = std::function; - - /// @private - View(Ptrs&& ptrs, Strides&& strs, Callback &&cb = [](){}); - - /// @private - View(const View&) = delete; - - /// @private - View(View&&) = default; - - /// @private - View& operator = (const View&) = delete; - - ~View(); - - Ptrs ptr; ///< Array of image plane pointers - Strides stride; ///< Array of image plane strides, in bytes. - -private: - Callback m_cb; -}; - -/** - * @brief An interface class for MediaFrame data adapters. - * - * Implement this interface to wrap media data in the MediaFrame. It - * makes sense to implement this class if there is a custom - * cv::gapi::wip::IStreamSource defined -- in this case, a stream - * source can produce MediaFrame objects with this adapter and the - * media data may be passed to graph without any copy. For example, a - * GStreamer-based stream source can implement an adapter over - * `GstBuffer` and G-API will transparently use it in the graph. - */ -class GAPI_EXPORTS MediaFrame::IAdapter { -public: - virtual ~IAdapter() = 0; - virtual cv::GFrameDesc meta() const = 0; - virtual MediaFrame::View access(MediaFrame::Access) = 0; - // FIXME: design a better solution - // The default implementation does nothing - virtual cv::util::any blobParams() const; - virtual void serialize(cv::gapi::s11n::IOStream&) { - GAPI_Error("Generic serialize method of MediaFrame::IAdapter does nothing by default. " - "Please, implement it in derived class to properly serialize the object."); - } - virtual void deserialize(cv::gapi::s11n::IIStream&) { - GAPI_Error("Generic deserialize method of MediaFrame::IAdapter does nothing by default. " - "Please, implement it in derived class to properly deserialize the object."); - } -}; -/** @} */ - -} //namespace cv - -#endif // OPENCV_GAPI_MEDIA_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020 Intel Corporation + +#ifndef OPENCV_GAPI_MEDIA_HPP +#define OPENCV_GAPI_MEDIA_HPP + +#include // unique_ptr<>, shared_ptr<> +#include // array<> +#include // function<> +#include // forward<>() + +#include +#include + +// Forward declaration +namespace cv { +namespace gapi { +namespace s11n { +struct IOStream; +struct IIStream; +} // namespace s11n +} // namespace gapi +} // namespace cv + +namespace cv { + +/** \addtogroup gapi_data_structures + * @{ + * + * @brief Extra G-API data structures used to pass input/output data + * to the graph for processing. + */ + +/** + * @brief cv::MediaFrame class represents an image/media frame + * obtained from an external source. + * + * cv::MediaFrame represents image data as specified in + * cv::MediaFormat. cv::MediaFrame is designed to be a thin wrapper over some + * external memory of buffer; the class itself provides an uniform + * interface over such types of memory. cv::MediaFrame wraps data from + * a camera driver or from a media codec and provides an abstraction + * layer over this memory to G-API. MediaFrame defines a compact interface + * to access and manage the underlying data; the implementation is + * fully defined by the associated Adapter (which is usually + * user-defined). + * + * @sa cv::RMat + */ +class GAPI_EXPORTS MediaFrame { +public: + /// This enum defines different types of cv::MediaFrame provided + /// access to the underlying data. Note that different flags can't + /// be combined in this version. + enum class Access { + R, ///< Access data for reading + W, ///< Access data for writing + }; + class IAdapter; + class View; + using AdapterPtr = std::unique_ptr; + + /** + * @brief Constructs an empty MediaFrame + * + * The constructed object has no any data associated with it. + */ + MediaFrame(); + + /** + * @brief Constructs a MediaFrame with the given + * Adapter. MediaFrame takes ownership over the passed adapter. + * + * @param p an unique pointer to instance of IAdapter derived class. + */ + explicit MediaFrame(AdapterPtr &&p); + + /** + * @overload + * @brief Constructs a MediaFrame with the given parameters for + * the Adapter. The adapter of type `T` is costructed on the fly. + * + * @param args list of arguments to construct an adapter of type + * `T`. + */ + template static cv::MediaFrame Create(Args&&... args); + + /** + * @brief Obtain access to the underlying data with the given + * mode. + * + * Depending on the associated Adapter and the data wrapped, this + * method may be cheap (e.g., the underlying memory is local) or + * costly (if the underlying memory is external or device + * memory). + * + * @param mode an access mode flag + * @return a MediaFrame::View object. The views should be handled + * carefully, refer to the MediaFrame::View documentation for details. + */ + View access(Access mode) const; + + /** + * @brief Returns a media frame descriptor -- the information + * about the media format, dimensions, etc. + * @return a cv::GFrameDesc + */ + cv::GFrameDesc desc() const; + + // FIXME: design a better solution + // Should be used only if the actual adapter provides implementation + /// @private -- exclude from the OpenCV documentation for now. + cv::util::any blobParams() const; + + /** + * @brief Casts and returns the associated MediaFrame adapter to + * the particular adapter type `T`, returns nullptr if the type is + * different. + * + * This method may be useful if the adapter type is known by the + * caller, and some lower level access to the memory is required. + * Depending on the memory type, it may be more efficient than + * access(). + * + * @return a pointer to the adapter object, nullptr if the adapter + * type is different. + */ + template T* get() const { + static_assert(std::is_base_of::value, + "T is not derived from cv::MediaFrame::IAdapter!"); + auto* adapter = getAdapter(); + GAPI_Assert(adapter != nullptr); + return dynamic_cast(adapter); + } + + /** + * @brief Serialize MediaFrame's data to a byte array. + * + * @note The actual logic is implemented by frame's adapter class. + * Does nothing by default. + * + * @param os Bytestream to store serialized MediaFrame data in. + */ + void serialize(cv::gapi::s11n::IOStream& os) const; + +private: + struct Priv; + std::shared_ptr m; + IAdapter* getAdapter() const; +}; + +template +inline cv::MediaFrame cv::MediaFrame::Create(Args&&... args) { + std::unique_ptr ptr(new T(std::forward(args)...)); + return cv::MediaFrame(std::move(ptr)); +} + +/** + * @brief Provides access to the MediaFrame's underlying data. + * + * This object contains the necessary information to access the pixel + * data of the associated MediaFrame: arrays of pointers and strides + * (distance between every plane row, in bytes) for every image + * plane, as defined in cv::MediaFormat. + * There may be up to four image planes in MediaFrame. + * + * Depending on the MediaFrame::Access flag passed in + * MediaFrame::access(), a MediaFrame::View may be read- or + * write-only. + * + * Depending on the MediaFrame::IAdapter implementation associated + * with the parent MediaFrame, writing to memory with + * MediaFrame::Access::R flag may have no effect or lead to + * undefined behavior. Same applies to reading the memory with + * MediaFrame::Access::W flag -- again, depending on the IAdapter + * implementation, the host-side buffer the view provides access to + * may have no current data stored in (so in-place editing of the + * buffer contents may not be possible). + * + * MediaFrame::View objects must be handled carefully, as an external + * resource associated with MediaFrame may be locked for the time the + * MediaFrame::View object exists. Obtaining MediaFrame::View should + * be seen as "map" and destroying it as "unmap" in the "map/unmap" + * idiom (applicable to OpenCL, device memory, remote + * memory). + * + * When a MediaFrame buffer is accessed for writing, and the memory + * under MediaFrame::View::Ptrs is altered, the data synchronization + * of a host-side and device/remote buffer is not guaranteed until the + * MediaFrame::View is destroyed. In other words, the real data on the + * device or in a remote target may be updated at the MediaFrame::View + * destruction only -- but it depends on the associated + * MediaFrame::IAdapter implementation. + */ +class GAPI_EXPORTS MediaFrame::View final { +public: + static constexpr const size_t MAX_PLANES = 4; + using Ptrs = std::array; + using Strides = std::array; // in bytes + using Callback = std::function; + + /// @private + View(Ptrs&& ptrs, Strides&& strs, Callback &&cb = [](){}); + + /// @private + View(const View&) = delete; + + /// @private + View(View&&) = default; + + /// @private + View& operator = (const View&) = delete; + + ~View(); + + Ptrs ptr; ///< Array of image plane pointers + Strides stride; ///< Array of image plane strides, in bytes. + +private: + Callback m_cb; +}; + +/** + * @brief An interface class for MediaFrame data adapters. + * + * Implement this interface to wrap media data in the MediaFrame. It + * makes sense to implement this class if there is a custom + * cv::gapi::wip::IStreamSource defined -- in this case, a stream + * source can produce MediaFrame objects with this adapter and the + * media data may be passed to graph without any copy. For example, a + * GStreamer-based stream source can implement an adapter over + * `GstBuffer` and G-API will transparently use it in the graph. + */ +class GAPI_EXPORTS MediaFrame::IAdapter { +public: + virtual ~IAdapter() = 0; + virtual cv::GFrameDesc meta() const = 0; + virtual MediaFrame::View access(MediaFrame::Access) = 0; + // FIXME: design a better solution + // The default implementation does nothing + virtual cv::util::any blobParams() const; + virtual void serialize(cv::gapi::s11n::IOStream&) { + GAPI_Error("Generic serialize method of MediaFrame::IAdapter does nothing by default. " + "Please, implement it in derived class to properly serialize the object."); + } + virtual void deserialize(cv::gapi::s11n::IIStream&) { + GAPI_Error("Generic deserialize method of MediaFrame::IAdapter does nothing by default. " + "Please, implement it in derived class to properly deserialize the object."); + } +}; +/** @} */ + +} //namespace cv + +#endif // OPENCV_GAPI_MEDIA_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/oak/infer.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/oak/infer.hpp index 4a1b9f6db6..28e67bc318 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/oak/infer.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/oak/infer.hpp @@ -1,66 +1,66 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2022 Intel Corporation - -#ifndef OPENCV_GAPI_OAK_INFER_HPP -#define OPENCV_GAPI_OAK_INFER_HPP - -#include -#include -#include -#include - -#include -#include - -#include // GAPI_EXPORTS -#include // GKernelPackage - -namespace cv { -namespace gapi { -namespace oak { - -namespace detail { -/** -* @brief This structure contains description of inference parameters -* which is specific to OAK models. -*/ -struct ParamDesc { - std::string blob_file; -}; -} // namespace detail - -/** - * Contains description of inference parameters and kit of functions that - * fill this parameters. - */ -template class Params { -public: - /** @brief Class constructor. - - Constructs Params based on model information and sets default values for other - inference description parameters. - - @param model Path to model (.blob file) - */ - explicit Params(const std::string &model) { - desc.blob_file = model; - }; - - // BEGIN(G-API's network parametrization API) - GBackend backend() const { return cv::gapi::oak::backend(); } - std::string tag() const { return Net::tag(); } - cv::util::any params() const { return { desc }; } - // END(G-API's network parametrization API) - -protected: - detail::ParamDesc desc; -}; - -} // namespace oak -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_OAK_INFER_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2022 Intel Corporation + +#ifndef OPENCV_GAPI_OAK_INFER_HPP +#define OPENCV_GAPI_OAK_INFER_HPP + +#include +#include +#include +#include + +#include +#include + +#include // GAPI_EXPORTS +#include // GKernelPackage + +namespace cv { +namespace gapi { +namespace oak { + +namespace detail { +/** +* @brief This structure contains description of inference parameters +* which is specific to OAK models. +*/ +struct ParamDesc { + std::string blob_file; +}; +} // namespace detail + +/** + * Contains description of inference parameters and kit of functions that + * fill this parameters. + */ +template class Params { +public: + /** @brief Class constructor. + + Constructs Params based on model information and sets default values for other + inference description parameters. + + @param model Path to model (.blob file) + */ + explicit Params(const std::string &model) { + desc.blob_file = model; + }; + + // BEGIN(G-API's network parametrization API) + GBackend backend() const { return cv::gapi::oak::backend(); } + std::string tag() const { return Net::tag(); } + cv::util::any params() const { return { desc }; } + // END(G-API's network parametrization API) + +protected: + detail::ParamDesc desc; +}; + +} // namespace oak +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_OAK_INFER_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/oak/oak.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/oak/oak.hpp index 8b56b8a365..88d1a5d085 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/oak/oak.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/oak/oak.hpp @@ -1,158 +1,158 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2021 Intel Corporation - -#ifndef OPENCV_GAPI_OAK_HPP -#define OPENCV_GAPI_OAK_HPP - -#include // IStreamSource -#include // GKernelPackage -#include // GOptRunArgsP - -namespace cv { -namespace gapi { -namespace oak { - -// FIXME: copypasted from dai library -struct EncoderConfig { - /** - * Rate control mode specifies if constant or variable bitrate should be used (H264 / H265) - */ - enum class RateControlMode: int { CBR, VBR }; - - /** - * Encoding profile, H264, H265 or MJPEG - */ - enum class Profile: int { H264_BASELINE, H264_HIGH, H264_MAIN, H265_MAIN, MJPEG }; - /** - * Specifies preferred bitrate (kb) of compressed output bitstream - */ - std::int32_t bitrate = 8000; - /** - * Every x number of frames a keyframe will be inserted - */ - std::int32_t keyframeFrequency = 30; - /** - * Specifies maximum bitrate (kb) of compressed output bitstream - */ - std::int32_t maxBitrate = 8000; - /** - * Specifies number of B frames to be inserted - */ - std::int32_t numBFrames = 0; - /** - * This options specifies how many frames are available in this nodes pool (can help if - * receiver node is slow at consuming - */ - std::uint32_t numFramesPool = 4; - /** - * Encoding profile, H264, H265 or MJPEG - */ - Profile profile = Profile::H265_MAIN; - /** - * Value between 0-100% (approximates quality) - */ - std::int32_t quality = 80; - /** - * Lossless mode ([M]JPEG only) - */ - bool lossless = false; - /** - * Rate control mode specifies if constant or variable bitrate should be used (H264 / H265) - */ - RateControlMode rateCtrlMode = RateControlMode::CBR; - /** - * Input and compressed output frame width - */ - std::int32_t width = 1920; - /** - * Input and compressed output frame height - */ - std::int32_t height = 1080; - /** - * Frame rate - */ - float frameRate = 30.0f; -}; - -G_API_OP(GEncFrame, (GFrame, EncoderConfig)>, "org.opencv.oak.enc_frame") { - static GArrayDesc outMeta(const GFrameDesc&, const EncoderConfig&) { - return cv::empty_array_desc(); - } -}; - -G_API_OP(GSobelXY, , "org.opencv.oak.sobelxy") { - static GFrameDesc outMeta(const GFrameDesc& in, const cv::Mat&, const cv::Mat&) { - return in; - } -}; - -G_API_OP(GCopy, , "org.opencv.oak.copy") { - static GFrameDesc outMeta(const GFrameDesc& in) { - return in; - } -}; - -// FIXME: add documentation on operations below - -GAPI_EXPORTS GArray encode(const GFrame& in, const EncoderConfig&); - -GAPI_EXPORTS GFrame sobelXY(const GFrame& in, - const cv::Mat& hk, - const cv::Mat& vk); - -GAPI_EXPORTS GFrame copy(const GFrame& in); - -// OAK backend & kernels //////////////////////////////////////////////////////// -GAPI_EXPORTS cv::gapi::GBackend backend(); -GAPI_EXPORTS cv::gapi::GKernelPackage kernels(); - -// Camera object /////////////////////////////////////////////////////////////// - -struct GAPI_EXPORTS ColorCameraParams { - /** - * Format of the frame one gets from the camera - */ - bool interleaved = false; - - // FIXME: extend - enum class BoardSocket: int { RGB, BGR }; - - BoardSocket board_socket = BoardSocket::RGB; - - // FIXME: extend - enum class Resolution: int { THE_1080_P }; - - Resolution resolution = Resolution::THE_1080_P; -}; - -class GAPI_EXPORTS ColorCamera: public cv::gapi::wip::IStreamSource { - cv::MediaFrame m_dummy; - ColorCameraParams m_params; - - virtual bool pull(cv::gapi::wip::Data &data) override; - virtual GMetaArg descr_of() const override; - -public: - ColorCamera(); - explicit ColorCamera(const ColorCameraParams& params); -}; - -} // namespace oak -} // namespace gapi - -namespace detail { -template<> struct CompileArgTag { - static const char* tag() { return "gapi.oak.colorCameraParams"; } -}; - -template<> struct CompileArgTag { - static const char* tag() { return "gapi.oak.encoderConfig"; } -}; -} // namespace detail - -} // namespace cv - -#endif // OPENCV_GAPI_OAK_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2021 Intel Corporation + +#ifndef OPENCV_GAPI_OAK_HPP +#define OPENCV_GAPI_OAK_HPP + +#include // IStreamSource +#include // GKernelPackage +#include // GOptRunArgsP + +namespace cv { +namespace gapi { +namespace oak { + +// FIXME: copypasted from dai library +struct EncoderConfig { + /** + * Rate control mode specifies if constant or variable bitrate should be used (H264 / H265) + */ + enum class RateControlMode: int { CBR, VBR }; + + /** + * Encoding profile, H264, H265 or MJPEG + */ + enum class Profile: int { H264_BASELINE, H264_HIGH, H264_MAIN, H265_MAIN, MJPEG }; + /** + * Specifies preferred bitrate (kb) of compressed output bitstream + */ + std::int32_t bitrate = 8000; + /** + * Every x number of frames a keyframe will be inserted + */ + std::int32_t keyframeFrequency = 30; + /** + * Specifies maximum bitrate (kb) of compressed output bitstream + */ + std::int32_t maxBitrate = 8000; + /** + * Specifies number of B frames to be inserted + */ + std::int32_t numBFrames = 0; + /** + * This options specifies how many frames are available in this nodes pool (can help if + * receiver node is slow at consuming + */ + std::uint32_t numFramesPool = 4; + /** + * Encoding profile, H264, H265 or MJPEG + */ + Profile profile = Profile::H265_MAIN; + /** + * Value between 0-100% (approximates quality) + */ + std::int32_t quality = 80; + /** + * Lossless mode ([M]JPEG only) + */ + bool lossless = false; + /** + * Rate control mode specifies if constant or variable bitrate should be used (H264 / H265) + */ + RateControlMode rateCtrlMode = RateControlMode::CBR; + /** + * Input and compressed output frame width + */ + std::int32_t width = 1920; + /** + * Input and compressed output frame height + */ + std::int32_t height = 1080; + /** + * Frame rate + */ + float frameRate = 30.0f; +}; + +G_API_OP(GEncFrame, (GFrame, EncoderConfig)>, "org.opencv.oak.enc_frame") { + static GArrayDesc outMeta(const GFrameDesc&, const EncoderConfig&) { + return cv::empty_array_desc(); + } +}; + +G_API_OP(GSobelXY, , "org.opencv.oak.sobelxy") { + static GFrameDesc outMeta(const GFrameDesc& in, const cv::Mat&, const cv::Mat&) { + return in; + } +}; + +G_API_OP(GCopy, , "org.opencv.oak.copy") { + static GFrameDesc outMeta(const GFrameDesc& in) { + return in; + } +}; + +// FIXME: add documentation on operations below + +GAPI_EXPORTS GArray encode(const GFrame& in, const EncoderConfig&); + +GAPI_EXPORTS GFrame sobelXY(const GFrame& in, + const cv::Mat& hk, + const cv::Mat& vk); + +GAPI_EXPORTS GFrame copy(const GFrame& in); + +// OAK backend & kernels //////////////////////////////////////////////////////// +GAPI_EXPORTS cv::gapi::GBackend backend(); +GAPI_EXPORTS cv::gapi::GKernelPackage kernels(); + +// Camera object /////////////////////////////////////////////////////////////// + +struct GAPI_EXPORTS ColorCameraParams { + /** + * Format of the frame one gets from the camera + */ + bool interleaved = false; + + // FIXME: extend + enum class BoardSocket: int { RGB, BGR }; + + BoardSocket board_socket = BoardSocket::RGB; + + // FIXME: extend + enum class Resolution: int { THE_1080_P }; + + Resolution resolution = Resolution::THE_1080_P; +}; + +class GAPI_EXPORTS ColorCamera: public cv::gapi::wip::IStreamSource { + cv::MediaFrame m_dummy; + ColorCameraParams m_params; + + virtual bool pull(cv::gapi::wip::Data &data) override; + virtual GMetaArg descr_of() const override; + +public: + ColorCamera(); + explicit ColorCamera(const ColorCameraParams& params); +}; + +} // namespace oak +} // namespace gapi + +namespace detail { +template<> struct CompileArgTag { + static const char* tag() { return "gapi.oak.colorCameraParams"; } +}; + +template<> struct CompileArgTag { + static const char* tag() { return "gapi.oak.encoderConfig"; } +}; +} // namespace detail + +} // namespace cv + +#endif // OPENCV_GAPI_OAK_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/ocl/core.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/ocl/core.hpp index b79aace0ca..cc48253ff8 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/ocl/core.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/ocl/core.hpp @@ -1,27 +1,27 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_OCL_CORE_API_HPP -#define OPENCV_GAPI_OCL_CORE_API_HPP - -#include // GAPI_EXPORTS -#include // GKernelPackage - -namespace cv { -namespace gapi { -namespace core { -namespace ocl { - -GAPI_EXPORTS_W cv::GKernelPackage kernels(); - -} // namespace ocl -} // namespace core -} // namespace gapi -} // namespace cv - - -#endif // OPENCV_GAPI_OCL_CORE_API_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_OCL_CORE_API_HPP +#define OPENCV_GAPI_OCL_CORE_API_HPP + +#include // GAPI_EXPORTS +#include // GKernelPackage + +namespace cv { +namespace gapi { +namespace core { +namespace ocl { + +GAPI_EXPORTS_W cv::GKernelPackage kernels(); + +} // namespace ocl +} // namespace core +} // namespace gapi +} // namespace cv + + +#endif // OPENCV_GAPI_OCL_CORE_API_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/ocl/goclkernel.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/ocl/goclkernel.hpp index b09082282f..5a0e04ac49 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/ocl/goclkernel.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/ocl/goclkernel.hpp @@ -1,260 +1,260 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2020 Intel Corporation - - -#ifndef OPENCV_GAPI_GOCLKERNEL_HPP -#define OPENCV_GAPI_GOCLKERNEL_HPP - -#include -#include -#include -#include - -#include -#include -#include -#include - -// FIXME: namespace scheme for backends? -namespace cv { - -namespace gimpl -{ - // Forward-declare an internal class - class GOCLExecutable; -} // namespace gimpl - -namespace gapi -{ -/** - * @brief This namespace contains G-API OpenCL backend functions, structures, and symbols. - */ -namespace ocl -{ - /** - * \addtogroup gapi_std_backends G-API Standard Backends - * @{ - */ - /** - * @brief Get a reference to OCL backend. - * - * At the moment, the OCL backend is built atop of OpenCV - * "Transparent API" (T-API), see cv::UMat for details. - * - * @sa gapi_std_backends - */ - GAPI_EXPORTS cv::gapi::GBackend backend(); - /** @} */ -} // namespace ocl -} // namespace gapi - - -// Represents arguments which are passed to a wrapped OCL function -// FIXME: put into detail? -class GAPI_EXPORTS GOCLContext -{ -public: - // Generic accessor API - template - const T& inArg(int input) { return m_args.at(input).get(); } - - // Syntax sugar - const cv::UMat& inMat(int input); - cv::UMat& outMatR(int output); // FIXME: Avoid cv::Mat m = ctx.outMatR() - - const cv::Scalar& inVal(int input); - cv::Scalar& outValR(int output); // FIXME: Avoid cv::Scalar s = ctx.outValR() - template std::vector& outVecR(int output) // FIXME: the same issue - { - return outVecRef(output).wref(); - } - template T& outOpaqueR(int output) // FIXME: the same issue - { - return outOpaqueRef(output).wref(); - } - -protected: - detail::VectorRef& outVecRef(int output); - detail::OpaqueRef& outOpaqueRef(int output); - - std::vector m_args; - std::unordered_map m_results; - - - friend class gimpl::GOCLExecutable; -}; - -class GAPI_EXPORTS GOCLKernel -{ -public: - // This function is kernel's execution entry point (does the processing work) - using F = std::function; - - GOCLKernel(); - explicit GOCLKernel(const F& f); - - void apply(GOCLContext &ctx); - -protected: - F m_f; -}; - -// FIXME: This is an ugly ad-hoc implementation. TODO: refactor - -namespace detail -{ -template struct ocl_get_in; -template<> struct ocl_get_in -{ - static cv::UMat get(GOCLContext &ctx, int idx) { return ctx.inMat(idx); } -}; -template<> struct ocl_get_in -{ - static cv::Scalar get(GOCLContext &ctx, int idx) { return ctx.inVal(idx); } -}; -template struct ocl_get_in > -{ - static const std::vector& get(GOCLContext &ctx, int idx) { return ctx.inArg(idx).rref(); } -}; -template<> struct ocl_get_in -{ - static cv::MediaFrame get(GOCLContext &ctx, int idx) { return ctx.inArg(idx); } -}; -template struct ocl_get_in > -{ - static const U& get(GOCLContext &ctx, int idx) { return ctx.inArg(idx).rref(); } -}; -template struct ocl_get_in -{ - static T get(GOCLContext &ctx, int idx) { return ctx.inArg(idx); } -}; - -struct tracked_cv_umat{ - //TODO Think if T - API could reallocate UMat to a proper size - how do we handle this ? - //tracked_cv_umat(cv::UMat& m) : r{(m)}, original_data{m.getMat(ACCESS_RW).data} {} - tracked_cv_umat(cv::UMat& m) : r(m), original_data{ nullptr } {} - cv::UMat &r; // FIXME: It was a value (not a reference) before. - // Actually OCL backend should allocate its internal data! - uchar* original_data; - - operator cv::UMat& (){ return r;} - void validate() const{ - //if (r.getMat(ACCESS_RW).data != original_data) - //{ - // util::throw_error - // (std::logic_error - // ("OpenCV kernel output parameter was reallocated. \n" - // "Incorrect meta data was provided ?")); - //} - - } -}; - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable: 4702) // unreachable code -#endif -template -void postprocess_ocl(Outputs&... outs) -{ - struct - { - void operator()(tracked_cv_umat* bm) { bm->validate(); } - void operator()(...) { } - - } validate; - //dummy array to unfold parameter pack - int dummy[] = { 0, (validate(&outs), 0)... }; - cv::util::suppress_unused_warning(dummy); -} -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -template struct ocl_get_out; -template<> struct ocl_get_out -{ - static tracked_cv_umat get(GOCLContext &ctx, int idx) - { - auto& r = ctx.outMatR(idx); - return{ r }; - } -}; -template<> struct ocl_get_out -{ - static cv::Scalar& get(GOCLContext &ctx, int idx) - { - return ctx.outValR(idx); - } -}; -template struct ocl_get_out > -{ - static std::vector& get(GOCLContext &ctx, int idx) { return ctx.outVecR(idx); } -}; -template struct ocl_get_out > -{ - static U& get(GOCLContext &ctx, int idx) { return ctx.outOpaqueR(idx); } -}; - -template -struct OCLCallHelper; - -// FIXME: probably can be simplified with std::apply or analogue. -template -struct OCLCallHelper, std::tuple > -{ - template - struct call_and_postprocess - { - template - static void call(Inputs&&... ins, Outputs&&... outs) - { - //not using a std::forward on outs is deliberate in order to - //cause compilation error, by trying to bind rvalue references to lvalue references - Impl::run(std::forward(ins)..., outs...); - - postprocess_ocl(outs...); - } - }; - - template - static void call_impl(GOCLContext &ctx, detail::Seq, detail::Seq) - { - //TODO: Make sure that OpenCV kernels do not reallocate memory for output parameters - //by comparing it's state (data ptr) before and after the call. - //Convert own::Scalar to cv::Scalar before call kernel and run kernel - //convert cv::Scalar to own::Scalar after call kernel and write back results - call_and_postprocess::get(ctx, IIs))...>::call(ocl_get_in::get(ctx, IIs)..., ocl_get_out::get(ctx, OIs)...); - } - - static void call(GOCLContext &ctx) - { - call_impl(ctx, - typename detail::MkSeq::type(), - typename detail::MkSeq::type()); - } -}; - -} // namespace detail - -template -class GOCLKernelImpl: public cv::detail::OCLCallHelper, - public cv::detail::KernelTag -{ - using P = detail::OCLCallHelper; - -public: - using API = K; - - static cv::gapi::GBackend backend() { return cv::gapi::ocl::backend(); } - static cv::GOCLKernel kernel() { return GOCLKernel(&P::call); } -}; - -#define GAPI_OCL_KERNEL(Name, API) struct Name: public cv::GOCLKernelImpl - -} // namespace cv - -#endif // OPENCV_GAPI_GOCLKERNEL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2020 Intel Corporation + + +#ifndef OPENCV_GAPI_GOCLKERNEL_HPP +#define OPENCV_GAPI_GOCLKERNEL_HPP + +#include +#include +#include +#include + +#include +#include +#include +#include + +// FIXME: namespace scheme for backends? +namespace cv { + +namespace gimpl +{ + // Forward-declare an internal class + class GOCLExecutable; +} // namespace gimpl + +namespace gapi +{ +/** + * @brief This namespace contains G-API OpenCL backend functions, structures, and symbols. + */ +namespace ocl +{ + /** + * \addtogroup gapi_std_backends G-API Standard Backends + * @{ + */ + /** + * @brief Get a reference to OCL backend. + * + * At the moment, the OCL backend is built atop of OpenCV + * "Transparent API" (T-API), see cv::UMat for details. + * + * @sa gapi_std_backends + */ + GAPI_EXPORTS cv::gapi::GBackend backend(); + /** @} */ +} // namespace ocl +} // namespace gapi + + +// Represents arguments which are passed to a wrapped OCL function +// FIXME: put into detail? +class GAPI_EXPORTS GOCLContext +{ +public: + // Generic accessor API + template + const T& inArg(int input) { return m_args.at(input).get(); } + + // Syntax sugar + const cv::UMat& inMat(int input); + cv::UMat& outMatR(int output); // FIXME: Avoid cv::Mat m = ctx.outMatR() + + const cv::Scalar& inVal(int input); + cv::Scalar& outValR(int output); // FIXME: Avoid cv::Scalar s = ctx.outValR() + template std::vector& outVecR(int output) // FIXME: the same issue + { + return outVecRef(output).wref(); + } + template T& outOpaqueR(int output) // FIXME: the same issue + { + return outOpaqueRef(output).wref(); + } + +protected: + detail::VectorRef& outVecRef(int output); + detail::OpaqueRef& outOpaqueRef(int output); + + std::vector m_args; + std::unordered_map m_results; + + + friend class gimpl::GOCLExecutable; +}; + +class GAPI_EXPORTS GOCLKernel +{ +public: + // This function is kernel's execution entry point (does the processing work) + using F = std::function; + + GOCLKernel(); + explicit GOCLKernel(const F& f); + + void apply(GOCLContext &ctx); + +protected: + F m_f; +}; + +// FIXME: This is an ugly ad-hoc implementation. TODO: refactor + +namespace detail +{ +template struct ocl_get_in; +template<> struct ocl_get_in +{ + static cv::UMat get(GOCLContext &ctx, int idx) { return ctx.inMat(idx); } +}; +template<> struct ocl_get_in +{ + static cv::Scalar get(GOCLContext &ctx, int idx) { return ctx.inVal(idx); } +}; +template struct ocl_get_in > +{ + static const std::vector& get(GOCLContext &ctx, int idx) { return ctx.inArg(idx).rref(); } +}; +template<> struct ocl_get_in +{ + static cv::MediaFrame get(GOCLContext &ctx, int idx) { return ctx.inArg(idx); } +}; +template struct ocl_get_in > +{ + static const U& get(GOCLContext &ctx, int idx) { return ctx.inArg(idx).rref(); } +}; +template struct ocl_get_in +{ + static T get(GOCLContext &ctx, int idx) { return ctx.inArg(idx); } +}; + +struct tracked_cv_umat{ + //TODO Think if T - API could reallocate UMat to a proper size - how do we handle this ? + //tracked_cv_umat(cv::UMat& m) : r{(m)}, original_data{m.getMat(ACCESS_RW).data} {} + tracked_cv_umat(cv::UMat& m) : r(m), original_data{ nullptr } {} + cv::UMat &r; // FIXME: It was a value (not a reference) before. + // Actually OCL backend should allocate its internal data! + uchar* original_data; + + operator cv::UMat& (){ return r;} + void validate() const{ + //if (r.getMat(ACCESS_RW).data != original_data) + //{ + // util::throw_error + // (std::logic_error + // ("OpenCV kernel output parameter was reallocated. \n" + // "Incorrect meta data was provided ?")); + //} + + } +}; + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable: 4702) // unreachable code +#endif +template +void postprocess_ocl(Outputs&... outs) +{ + struct + { + void operator()(tracked_cv_umat* bm) { bm->validate(); } + void operator()(...) { } + + } validate; + //dummy array to unfold parameter pack + int dummy[] = { 0, (validate(&outs), 0)... }; + cv::util::suppress_unused_warning(dummy); +} +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +template struct ocl_get_out; +template<> struct ocl_get_out +{ + static tracked_cv_umat get(GOCLContext &ctx, int idx) + { + auto& r = ctx.outMatR(idx); + return{ r }; + } +}; +template<> struct ocl_get_out +{ + static cv::Scalar& get(GOCLContext &ctx, int idx) + { + return ctx.outValR(idx); + } +}; +template struct ocl_get_out > +{ + static std::vector& get(GOCLContext &ctx, int idx) { return ctx.outVecR(idx); } +}; +template struct ocl_get_out > +{ + static U& get(GOCLContext &ctx, int idx) { return ctx.outOpaqueR(idx); } +}; + +template +struct OCLCallHelper; + +// FIXME: probably can be simplified with std::apply or analogue. +template +struct OCLCallHelper, std::tuple > +{ + template + struct call_and_postprocess + { + template + static void call(Inputs&&... ins, Outputs&&... outs) + { + //not using a std::forward on outs is deliberate in order to + //cause compilation error, by trying to bind rvalue references to lvalue references + Impl::run(std::forward(ins)..., outs...); + + postprocess_ocl(outs...); + } + }; + + template + static void call_impl(GOCLContext &ctx, detail::Seq, detail::Seq) + { + //TODO: Make sure that OpenCV kernels do not reallocate memory for output parameters + //by comparing it's state (data ptr) before and after the call. + //Convert own::Scalar to cv::Scalar before call kernel and run kernel + //convert cv::Scalar to own::Scalar after call kernel and write back results + call_and_postprocess::get(ctx, IIs))...>::call(ocl_get_in::get(ctx, IIs)..., ocl_get_out::get(ctx, OIs)...); + } + + static void call(GOCLContext &ctx) + { + call_impl(ctx, + typename detail::MkSeq::type(), + typename detail::MkSeq::type()); + } +}; + +} // namespace detail + +template +class GOCLKernelImpl: public cv::detail::OCLCallHelper, + public cv::detail::KernelTag +{ + using P = detail::OCLCallHelper; + +public: + using API = K; + + static cv::gapi::GBackend backend() { return cv::gapi::ocl::backend(); } + static cv::GOCLKernel kernel() { return GOCLKernel(&P::call); } +}; + +#define GAPI_OCL_KERNEL(Name, API) struct Name: public cv::GOCLKernelImpl + +} // namespace cv + +#endif // OPENCV_GAPI_GOCLKERNEL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/ocl/imgproc.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/ocl/imgproc.hpp index 1bb5911b18..10c20bd0f2 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/ocl/imgproc.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/ocl/imgproc.hpp @@ -1,27 +1,27 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_OCL_IMGPROC_API_HPP -#define OPENCV_GAPI_OCL_IMGPROC_API_HPP - -#include // GAPI_EXPORTS -#include // GKernelPackage - -namespace cv { -namespace gapi { -namespace imgproc { -namespace ocl { - - GAPI_EXPORTS GKernelPackage kernels(); - -} // namespace ocl -} // namespace imgproc -} // namespace gapi -} // namespace cv - - -#endif // OPENCV_GAPI_OCL_IMGPROC_API_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_OCL_IMGPROC_API_HPP +#define OPENCV_GAPI_OCL_IMGPROC_API_HPP + +#include // GAPI_EXPORTS +#include // GKernelPackage + +namespace cv { +namespace gapi { +namespace imgproc { +namespace ocl { + + GAPI_EXPORTS GKernelPackage kernels(); + +} // namespace ocl +} // namespace imgproc +} // namespace gapi +} // namespace cv + + +#endif // OPENCV_GAPI_OCL_IMGPROC_API_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/opencv_includes.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/opencv_includes.hpp index 7c2c42d8a2..57b8c857e8 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/opencv_includes.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/opencv_includes.hpp @@ -1,42 +1,42 @@ -// This file is part of OpenCV project. - -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_OPENCV_INCLUDES_HPP -#define OPENCV_GAPI_OPENCV_INCLUDES_HPP - -#if !defined(GAPI_STANDALONE) -# include -# include -# include -# include -#define GAPI_OWN_TYPES_LIST cv::gapi::own::Rect, \ - cv::gapi::own::Size, \ - cv::gapi::own::Point, \ - cv::gapi::own::Point2f, \ - cv::gapi::own::Scalar, \ - cv::gapi::own::Mat -#else // Without OpenCV -# include -# include // cv::gapi::own::Rect/Size/Point -# include // cv::gapi::own::Scalar -# include -// replacement of cv's structures: -namespace cv { - using Rect = gapi::own::Rect; - using Size = gapi::own::Size; - using Point = gapi::own::Point; - using Point2f = gapi::own::Point2f; - using Point3f = gapi::own::Point3f; - using Scalar = gapi::own::Scalar; - using Mat = gapi::own::Mat; -} // namespace cv -#define GAPI_OWN_TYPES_LIST cv::gapi::own::VoidType - -#endif // !defined(GAPI_STANDALONE) - -#endif // OPENCV_GAPI_OPENCV_INCLUDES_HPP +// This file is part of OpenCV project. + +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_OPENCV_INCLUDES_HPP +#define OPENCV_GAPI_OPENCV_INCLUDES_HPP + +#if !defined(GAPI_STANDALONE) +# include +# include +# include +# include +#define GAPI_OWN_TYPES_LIST cv::gapi::own::Rect, \ + cv::gapi::own::Size, \ + cv::gapi::own::Point, \ + cv::gapi::own::Point2f, \ + cv::gapi::own::Scalar, \ + cv::gapi::own::Mat +#else // Without OpenCV +# include +# include // cv::gapi::own::Rect/Size/Point +# include // cv::gapi::own::Scalar +# include +// replacement of cv's structures: +namespace cv { + using Rect = gapi::own::Rect; + using Size = gapi::own::Size; + using Point = gapi::own::Point; + using Point2f = gapi::own::Point2f; + using Point3f = gapi::own::Point3f; + using Scalar = gapi::own::Scalar; + using Mat = gapi::own::Mat; +} // namespace cv +#define GAPI_OWN_TYPES_LIST cv::gapi::own::VoidType + +#endif // !defined(GAPI_STANDALONE) + +#endif // OPENCV_GAPI_OPENCV_INCLUDES_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/operators.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/operators.hpp index 6794b44b6e..525f5ad1fe 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/operators.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/operators.hpp @@ -1,70 +1,70 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_OPERATORS_HPP -#define OPENCV_GAPI_OPERATORS_HPP - -#include -#include - -namespace cv -{ -GAPI_EXPORTS cv::GMat operator+(const cv::GMat& lhs, const cv::GMat& rhs); - -GAPI_EXPORTS cv::GMat operator+(const cv::GMat& lhs, const cv::GScalar& rhs); -GAPI_EXPORTS cv::GMat operator+(const cv::GScalar& lhs, const cv::GMat& rhs); - -GAPI_EXPORTS cv::GMat operator-(const cv::GMat& lhs, const cv::GMat& rhs); - -GAPI_EXPORTS cv::GMat operator-(const cv::GMat& lhs, const cv::GScalar& rhs); -GAPI_EXPORTS cv::GMat operator-(const cv::GScalar& lhs, const cv::GMat& rhs); - -GAPI_EXPORTS cv::GMat operator*(const cv::GMat& lhs, float rhs); -GAPI_EXPORTS cv::GMat operator*(float lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator*(const cv::GMat& lhs, const cv::GScalar& rhs); -GAPI_EXPORTS cv::GMat operator*(const cv::GScalar& lhs, const cv::GMat& rhs); - -GAPI_EXPORTS cv::GMat operator/(const cv::GMat& lhs, const cv::GScalar& rhs); -GAPI_EXPORTS cv::GMat operator/(const cv::GScalar& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator/(const cv::GMat& lhs, const cv::GMat& rhs); - -GAPI_EXPORTS cv::GMat operator&(const cv::GMat& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator|(const cv::GMat& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator^(const cv::GMat& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator~(const cv::GMat& lhs); - -GAPI_EXPORTS cv::GMat operator&(const cv::GScalar& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator|(const cv::GScalar& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator^(const cv::GScalar& lhs, const cv::GMat& rhs); - -GAPI_EXPORTS cv::GMat operator&(const cv::GMat& lhs, const cv::GScalar& rhs); -GAPI_EXPORTS cv::GMat operator|(const cv::GMat& lhs, const cv::GScalar& rhs); -GAPI_EXPORTS cv::GMat operator^(const cv::GMat& lhs, const cv::GScalar& rhs); - -GAPI_EXPORTS cv::GMat operator>(const cv::GMat& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator>=(const cv::GMat& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator<(const cv::GMat& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator<=(const cv::GMat& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator==(const cv::GMat& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator!=(const cv::GMat& lhs, const cv::GMat& rhs); - -GAPI_EXPORTS cv::GMat operator>(const cv::GMat& lhs, const cv::GScalar& rhs); -GAPI_EXPORTS cv::GMat operator>=(const cv::GMat& lhs, const cv::GScalar& rhs); -GAPI_EXPORTS cv::GMat operator<(const cv::GMat& lhs, const cv::GScalar& rhs); -GAPI_EXPORTS cv::GMat operator<=(const cv::GMat& lhs, const cv::GScalar& rhs); -GAPI_EXPORTS cv::GMat operator==(const cv::GMat& lhs, const cv::GScalar& rhs); -GAPI_EXPORTS cv::GMat operator!=(const cv::GMat& lhs, const cv::GScalar& rhs); - -GAPI_EXPORTS cv::GMat operator>(const cv::GScalar& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator>=(const cv::GScalar& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator<(const cv::GScalar& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator<=(const cv::GScalar& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator==(const cv::GScalar& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator!=(const cv::GScalar& lhs, const cv::GMat& rhs); -} // cv - -#endif // OPENCV_GAPI_OPERATORS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_OPERATORS_HPP +#define OPENCV_GAPI_OPERATORS_HPP + +#include +#include + +namespace cv +{ +GAPI_EXPORTS cv::GMat operator+(const cv::GMat& lhs, const cv::GMat& rhs); + +GAPI_EXPORTS cv::GMat operator+(const cv::GMat& lhs, const cv::GScalar& rhs); +GAPI_EXPORTS cv::GMat operator+(const cv::GScalar& lhs, const cv::GMat& rhs); + +GAPI_EXPORTS cv::GMat operator-(const cv::GMat& lhs, const cv::GMat& rhs); + +GAPI_EXPORTS cv::GMat operator-(const cv::GMat& lhs, const cv::GScalar& rhs); +GAPI_EXPORTS cv::GMat operator-(const cv::GScalar& lhs, const cv::GMat& rhs); + +GAPI_EXPORTS cv::GMat operator*(const cv::GMat& lhs, float rhs); +GAPI_EXPORTS cv::GMat operator*(float lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator*(const cv::GMat& lhs, const cv::GScalar& rhs); +GAPI_EXPORTS cv::GMat operator*(const cv::GScalar& lhs, const cv::GMat& rhs); + +GAPI_EXPORTS cv::GMat operator/(const cv::GMat& lhs, const cv::GScalar& rhs); +GAPI_EXPORTS cv::GMat operator/(const cv::GScalar& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator/(const cv::GMat& lhs, const cv::GMat& rhs); + +GAPI_EXPORTS cv::GMat operator&(const cv::GMat& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator|(const cv::GMat& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator^(const cv::GMat& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator~(const cv::GMat& lhs); + +GAPI_EXPORTS cv::GMat operator&(const cv::GScalar& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator|(const cv::GScalar& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator^(const cv::GScalar& lhs, const cv::GMat& rhs); + +GAPI_EXPORTS cv::GMat operator&(const cv::GMat& lhs, const cv::GScalar& rhs); +GAPI_EXPORTS cv::GMat operator|(const cv::GMat& lhs, const cv::GScalar& rhs); +GAPI_EXPORTS cv::GMat operator^(const cv::GMat& lhs, const cv::GScalar& rhs); + +GAPI_EXPORTS cv::GMat operator>(const cv::GMat& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator>=(const cv::GMat& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator<(const cv::GMat& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator<=(const cv::GMat& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator==(const cv::GMat& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator!=(const cv::GMat& lhs, const cv::GMat& rhs); + +GAPI_EXPORTS cv::GMat operator>(const cv::GMat& lhs, const cv::GScalar& rhs); +GAPI_EXPORTS cv::GMat operator>=(const cv::GMat& lhs, const cv::GScalar& rhs); +GAPI_EXPORTS cv::GMat operator<(const cv::GMat& lhs, const cv::GScalar& rhs); +GAPI_EXPORTS cv::GMat operator<=(const cv::GMat& lhs, const cv::GScalar& rhs); +GAPI_EXPORTS cv::GMat operator==(const cv::GMat& lhs, const cv::GScalar& rhs); +GAPI_EXPORTS cv::GMat operator!=(const cv::GMat& lhs, const cv::GScalar& rhs); + +GAPI_EXPORTS cv::GMat operator>(const cv::GScalar& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator>=(const cv::GScalar& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator<(const cv::GScalar& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator<=(const cv::GScalar& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator==(const cv::GScalar& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator!=(const cv::GScalar& lhs, const cv::GMat& rhs); +} // cv + +#endif // OPENCV_GAPI_OPERATORS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/ot.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/ot.hpp index b73d7e6ee0..1da0c18932 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/ot.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/ot.hpp @@ -1,194 +1,194 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2023 Intel Corporation - -#ifndef OPENCV_GAPI_OT_HPP -#define OPENCV_GAPI_OT_HPP - -#include -#include -#include - -namespace cv { -namespace gapi { -/** - * @brief This namespace contains G-API Operation Types for - * VAS Object Tracking module functionality. - */ -namespace ot { - -/** - * @enum TrackingStatus - * - * Tracking status twin for vas::ot::TrackingStatus - */ -enum TrackingStatus -{ - NEW = 0, /**< The object is newly added. */ - TRACKED, /**< The object is being tracked. */ - LOST /**< The object gets lost now. The object can be tracked again - by specifying detected object manually. */ -}; - -struct GAPI_EXPORTS_W_SIMPLE ObjectTrackerParams -{ - /** - * Maximum number of trackable objects in a frame. - * Valid range: 1 <= max_num_objects. Or it can be -1 if there is no limitation - * of maximum number in X86. KMB/TBH has limitation up to 1024. - * Default value is -1 which means there is no limitation in X86. KMB/TBH is -1 means 200. - */ - GAPI_PROP_RW int32_t max_num_objects = -1; - - /** - * Input color format. Supports 0(BGR), 1(NV12), 2(BGRX) and 4(I420) - */ - GAPI_PROP_RW int32_t input_image_format = 0; - - /** - * Specifies whether tracker to use detection class for keeping id of an object. - * If it is true, new detection will be associated from previous tracking only when - * those two have same class. - * class id of an object is fixed across video frames. - * If it is false, new detection can be associated across different-class objects. - * In this case, the class id of an object may change across video frames depending on the tracker input. - * It is recommended to turn this option off when it is likely that detector confuses the class of object. - * For example, when detector confuses bicycle and motorbike. Turning this option off will increase - * the tracking reliability as tracker will ignore the class label of detector. - * @n - * Default value is true. - */ - GAPI_PROP_RW bool tracking_per_class = true; - - bool operator==(const ObjectTrackerParams& other) const - { - return max_num_objects == other.max_num_objects - && input_image_format == other.input_image_format - && tracking_per_class == other.tracking_per_class; - } -}; - -using GTrackedInfo = std::tuple, cv::GArray, cv::GArray, cv::GArray>; - -G_API_OP(GTrackFromMat, , cv::GArray, float)>, "com.intel.track_from_mat") -{ - static std::tuple outMeta(cv::GMatDesc, cv::GArrayDesc, cv::GArrayDesc, float) - { - return std::make_tuple(cv::empty_array_desc(), cv::empty_array_desc(), - cv::empty_array_desc(), cv::empty_array_desc()); - } -}; - -G_API_OP(GTrackFromFrame, , cv::GArray, float)>, "com.intel.track_from_frame") -{ - static std::tuple outMeta(cv::GFrameDesc, cv::GArrayDesc, cv::GArrayDesc, float) - { - return std::make_tuple(cv::empty_array_desc(), cv::empty_array_desc(), - cv::empty_array_desc(), cv::empty_array_desc()); - } -}; - -/** - * @brief Tracks objects with video frames. - * If a detected object is overlapped enough with one of tracked object, the tracked object's - * informationis updated with the input detected object. - * On the other hand, if a detected object is overlapped with none of tracked objects, - * the detected object is newly added and ObjectTracker starts to track the object. - * In zero term tracking type, ObjectTracker clears tracked objects in case that empty - * list of detected objects is passed in. - * - * @param mat Input frame. - * @param detected_rects Detected objects rectangles in the input frame. - * @param detected_class_labels Detected objects class labels in the input frame. - * @param delta Frame_delta_t Delta time between two consecutive tracking in seconds. - * The valid range is [0.005 ~ 0.5]. - * @return Tracking results of target objects. - * cv::GArray Array of rectangles for tracked objects. - * cv::GArray Array of detected objects labels. - * cv::GArray Array of tracking IDs for objects. - * Numbering sequence starts from 1. - * The value 0 means the tracking ID of this object has - * not been assigned. - * cv::GArray Array of tracking statuses for objects. - */ -GAPI_EXPORTS_W std::tuple, - cv::GArray, - cv::GArray, - cv::GArray> - track(const cv::GMat& mat, - const cv::GArray& detected_rects, - const cv::GArray& detected_class_labels, - float delta); - - -/** - @overload - * @brief Tracks objects with video frames. Overload of track(...) for frame as GFrame. - * - * @param frame Input frame. - * @param detected_rects Detected objects rectangles in the input frame. - * @param detected_class_labels Detected objects class labels in the input frame. - * @param delta Frame_delta_t Delta time between two consecutive tracking in seconds. - * The valid range is [0.005 ~ 0.5]. - * @return Tracking results of target objects. - * @return Tracking results of target objects. - * cv::GArray Array of rectangles for tracked objects. - * cv::GArray Array of detected objects labels. - * cv::GArray Array of tracking IDs for objects. - * Numbering sequence starts from 1. - * The value 0 means the tracking ID of this object has - * not been assigned. - * cv::GArray Array of tracking statuses for objects. - */ -GAPI_EXPORTS_W std::tuple, - cv::GArray, - cv::GArray, - cv::GArray> - track(const cv::GFrame& frame, - const cv::GArray& detected_rects, - const cv::GArray& detected_class_labels, - float delta); -} // namespace ot -} // namespace gapi -} // namespace cv - -// FIXME: move to a separate file? -namespace cv -{ -namespace detail -{ -template<> struct CompileArgTag -{ - static const char* tag() - { - return "cv.gapi.ot.object_tracker_params"; - } -}; -} // namespace detail - -namespace gapi -{ -namespace s11n -{ -namespace detail -{ -template<> struct S11N { - static void serialize(IOStream &os, const cv::gapi::ot::ObjectTrackerParams &p) { - os << p. max_num_objects << p.input_image_format << p.tracking_per_class; - } - static cv::gapi::ot::ObjectTrackerParams deserialize(IIStream &is) { - cv::gapi::ot::ObjectTrackerParams p; - is >> p. max_num_objects >> p.input_image_format >> p.tracking_per_class; - return p; - } -}; -} // namespace detail -} // namespace s11n -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_OT_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2023 Intel Corporation + +#ifndef OPENCV_GAPI_OT_HPP +#define OPENCV_GAPI_OT_HPP + +#include +#include +#include + +namespace cv { +namespace gapi { +/** + * @brief This namespace contains G-API Operation Types for + * VAS Object Tracking module functionality. + */ +namespace ot { + +/** + * @enum TrackingStatus + * + * Tracking status twin for vas::ot::TrackingStatus + */ +enum TrackingStatus +{ + NEW = 0, /**< The object is newly added. */ + TRACKED, /**< The object is being tracked. */ + LOST /**< The object gets lost now. The object can be tracked again + by specifying detected object manually. */ +}; + +struct GAPI_EXPORTS_W_SIMPLE ObjectTrackerParams +{ + /** + * Maximum number of trackable objects in a frame. + * Valid range: 1 <= max_num_objects. Or it can be -1 if there is no limitation + * of maximum number in X86. KMB/TBH has limitation up to 1024. + * Default value is -1 which means there is no limitation in X86. KMB/TBH is -1 means 200. + */ + GAPI_PROP_RW int32_t max_num_objects = -1; + + /** + * Input color format. Supports 0(BGR), 1(NV12), 2(BGRX) and 4(I420) + */ + GAPI_PROP_RW int32_t input_image_format = 0; + + /** + * Specifies whether tracker to use detection class for keeping id of an object. + * If it is true, new detection will be associated from previous tracking only when + * those two have same class. + * class id of an object is fixed across video frames. + * If it is false, new detection can be associated across different-class objects. + * In this case, the class id of an object may change across video frames depending on the tracker input. + * It is recommended to turn this option off when it is likely that detector confuses the class of object. + * For example, when detector confuses bicycle and motorbike. Turning this option off will increase + * the tracking reliability as tracker will ignore the class label of detector. + * @n + * Default value is true. + */ + GAPI_PROP_RW bool tracking_per_class = true; + + bool operator==(const ObjectTrackerParams& other) const + { + return max_num_objects == other.max_num_objects + && input_image_format == other.input_image_format + && tracking_per_class == other.tracking_per_class; + } +}; + +using GTrackedInfo = std::tuple, cv::GArray, cv::GArray, cv::GArray>; + +G_API_OP(GTrackFromMat, , cv::GArray, float)>, "com.intel.track_from_mat") +{ + static std::tuple outMeta(cv::GMatDesc, cv::GArrayDesc, cv::GArrayDesc, float) + { + return std::make_tuple(cv::empty_array_desc(), cv::empty_array_desc(), + cv::empty_array_desc(), cv::empty_array_desc()); + } +}; + +G_API_OP(GTrackFromFrame, , cv::GArray, float)>, "com.intel.track_from_frame") +{ + static std::tuple outMeta(cv::GFrameDesc, cv::GArrayDesc, cv::GArrayDesc, float) + { + return std::make_tuple(cv::empty_array_desc(), cv::empty_array_desc(), + cv::empty_array_desc(), cv::empty_array_desc()); + } +}; + +/** + * @brief Tracks objects with video frames. + * If a detected object is overlapped enough with one of tracked object, the tracked object's + * informationis updated with the input detected object. + * On the other hand, if a detected object is overlapped with none of tracked objects, + * the detected object is newly added and ObjectTracker starts to track the object. + * In zero term tracking type, ObjectTracker clears tracked objects in case that empty + * list of detected objects is passed in. + * + * @param mat Input frame. + * @param detected_rects Detected objects rectangles in the input frame. + * @param detected_class_labels Detected objects class labels in the input frame. + * @param delta Frame_delta_t Delta time between two consecutive tracking in seconds. + * The valid range is [0.005 ~ 0.5]. + * @return Tracking results of target objects. + * cv::GArray Array of rectangles for tracked objects. + * cv::GArray Array of detected objects labels. + * cv::GArray Array of tracking IDs for objects. + * Numbering sequence starts from 1. + * The value 0 means the tracking ID of this object has + * not been assigned. + * cv::GArray Array of tracking statuses for objects. + */ +GAPI_EXPORTS_W std::tuple, + cv::GArray, + cv::GArray, + cv::GArray> + track(const cv::GMat& mat, + const cv::GArray& detected_rects, + const cv::GArray& detected_class_labels, + float delta); + + +/** + @overload + * @brief Tracks objects with video frames. Overload of track(...) for frame as GFrame. + * + * @param frame Input frame. + * @param detected_rects Detected objects rectangles in the input frame. + * @param detected_class_labels Detected objects class labels in the input frame. + * @param delta Frame_delta_t Delta time between two consecutive tracking in seconds. + * The valid range is [0.005 ~ 0.5]. + * @return Tracking results of target objects. + * @return Tracking results of target objects. + * cv::GArray Array of rectangles for tracked objects. + * cv::GArray Array of detected objects labels. + * cv::GArray Array of tracking IDs for objects. + * Numbering sequence starts from 1. + * The value 0 means the tracking ID of this object has + * not been assigned. + * cv::GArray Array of tracking statuses for objects. + */ +GAPI_EXPORTS_W std::tuple, + cv::GArray, + cv::GArray, + cv::GArray> + track(const cv::GFrame& frame, + const cv::GArray& detected_rects, + const cv::GArray& detected_class_labels, + float delta); +} // namespace ot +} // namespace gapi +} // namespace cv + +// FIXME: move to a separate file? +namespace cv +{ +namespace detail +{ +template<> struct CompileArgTag +{ + static const char* tag() + { + return "cv.gapi.ot.object_tracker_params"; + } +}; +} // namespace detail + +namespace gapi +{ +namespace s11n +{ +namespace detail +{ +template<> struct S11N { + static void serialize(IOStream &os, const cv::gapi::ot::ObjectTrackerParams &p) { + os << p. max_num_objects << p.input_image_format << p.tracking_per_class; + } + static cv::gapi::ot::ObjectTrackerParams deserialize(IIStream &is) { + cv::gapi::ot::ObjectTrackerParams p; + is >> p. max_num_objects >> p.input_image_format >> p.tracking_per_class; + return p; + } +}; +} // namespace detail +} // namespace s11n +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_OT_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/own/assert.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/own/assert.hpp index ab2fb896f1..9e8be33272 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/own/assert.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/own/assert.hpp @@ -1,60 +1,60 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2020 Intel Corporation - - -#ifndef OPENCV_GAPI_OWN_ASSERT_HPP -#define OPENCV_GAPI_OWN_ASSERT_HPP - -#include - -#define GAPI_DbgAssertNoOp(expr) { \ - constexpr bool _assert_tmp = false && (expr); \ - cv::util::suppress_unused_warning(_assert_tmp); \ -} - -#if !defined(GAPI_STANDALONE) -#include -#define GAPI_Assert CV_Assert - -#if defined _DEBUG || defined CV_STATIC_ANALYSIS -# define GAPI_DbgAssert CV_DbgAssert -#else -# define GAPI_DbgAssert(expr) GAPI_DbgAssertNoOp(expr) -#endif - -#define GAPI_Error(msg) CV_Error(cv::Error::StsError, msg) - -#else -#include -#include -#include - -namespace detail -{ - [[noreturn]] inline void assert_abort(const char* str, int line, const char* file, const char* func) - { - std::stringstream ss; - ss << file << ":" << line << ": Assertion " << str << " in function " << func << " failed\n"; - cv::util::throw_error(std::logic_error(ss.str())); - } -} - -#define GAPI_Assert(expr) \ -{ if (!(expr)) ::detail::assert_abort(#expr, __LINE__, __FILE__, __func__); } - -#ifdef NDEBUG -# define GAPI_DbgAssert(expr) GAPI_DbgAssertNoOp(expr) -#else -# define GAPI_DbgAssert(expr) GAPI_Assert(expr) -#endif - -#define GAPI_Error(msg) { \ - ::detail::assert_abort(msg, __LINE__, __FILE__, __func__); \ -} - -#endif // GAPI_STANDALONE - -#endif // OPENCV_GAPI_OWN_ASSERT_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2020 Intel Corporation + + +#ifndef OPENCV_GAPI_OWN_ASSERT_HPP +#define OPENCV_GAPI_OWN_ASSERT_HPP + +#include + +#define GAPI_DbgAssertNoOp(expr) { \ + constexpr bool _assert_tmp = false && (expr); \ + cv::util::suppress_unused_warning(_assert_tmp); \ +} + +#if !defined(GAPI_STANDALONE) +#include +#define GAPI_Assert CV_Assert + +#if defined _DEBUG || defined CV_STATIC_ANALYSIS +# define GAPI_DbgAssert CV_DbgAssert +#else +# define GAPI_DbgAssert(expr) GAPI_DbgAssertNoOp(expr) +#endif + +#define GAPI_Error(msg) CV_Error(cv::Error::StsError, msg) + +#else +#include +#include +#include + +namespace detail +{ + [[noreturn]] inline void assert_abort(const char* str, int line, const char* file, const char* func) + { + std::stringstream ss; + ss << file << ":" << line << ": Assertion " << str << " in function " << func << " failed\n"; + cv::util::throw_error(std::logic_error(ss.str())); + } +} + +#define GAPI_Assert(expr) \ +{ if (!(expr)) ::detail::assert_abort(#expr, __LINE__, __FILE__, __func__); } + +#ifdef NDEBUG +# define GAPI_DbgAssert(expr) GAPI_DbgAssertNoOp(expr) +#else +# define GAPI_DbgAssert(expr) GAPI_Assert(expr) +#endif + +#define GAPI_Error(msg) { \ + ::detail::assert_abort(msg, __LINE__, __FILE__, __func__); \ +} + +#endif // GAPI_STANDALONE + +#endif // OPENCV_GAPI_OWN_ASSERT_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/own/convert.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/own/convert.hpp index f587e24787..2380a1bbed 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/own/convert.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/own/convert.hpp @@ -1,55 +1,55 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_OWN_CONVERT_HPP -#define OPENCV_GAPI_OWN_CONVERT_HPP - -#if !defined(GAPI_STANDALONE) - -#include -#include - -namespace cv -{ - template - std::vector to_own(const cv::MatSize &sz) { - std::vector result(sz.dims()); - for (int i = 0; i < sz.dims(); i++) { - // Note: cv::MatSize is not iterable - result[i] = static_cast(sz[i]); - } - return result; - } - - cv::gapi::own::Mat to_own(Mat&&) = delete; - - inline cv::gapi::own::Mat to_own(Mat const& m) { - return (m.dims == 2) - ? cv::gapi::own::Mat{m.rows, m.cols, m.type(), m.data, m.step} - : cv::gapi::own::Mat{to_own(m.size), m.type(), m.data}; - } - -namespace gapi -{ -namespace own -{ - - inline cv::Mat to_ocv(Mat const& m) { - return m.dims.empty() - ? cv::Mat{m.rows, m.cols, m.type(), m.data, m.step} - : cv::Mat{m.dims, m.type(), m.data}; - } - - cv::Mat to_ocv(Mat&&) = delete; - -} // namespace own -} // namespace gapi -} // namespace cv - -#endif // !defined(GAPI_STANDALONE) - -#endif // OPENCV_GAPI_OWN_CONVERT_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_OWN_CONVERT_HPP +#define OPENCV_GAPI_OWN_CONVERT_HPP + +#if !defined(GAPI_STANDALONE) + +#include +#include + +namespace cv +{ + template + std::vector to_own(const cv::MatSize &sz) { + std::vector result(sz.dims()); + for (int i = 0; i < sz.dims(); i++) { + // Note: cv::MatSize is not iterable + result[i] = static_cast(sz[i]); + } + return result; + } + + cv::gapi::own::Mat to_own(Mat&&) = delete; + + inline cv::gapi::own::Mat to_own(Mat const& m) { + return (m.dims == 2) + ? cv::gapi::own::Mat{m.rows, m.cols, m.type(), m.data, m.step} + : cv::gapi::own::Mat{to_own(m.size), m.type(), m.data}; + } + +namespace gapi +{ +namespace own +{ + + inline cv::Mat to_ocv(Mat const& m) { + return m.dims.empty() + ? cv::Mat{m.rows, m.cols, m.type(), m.data, m.step} + : cv::Mat{m.dims, m.type(), m.data}; + } + + cv::Mat to_ocv(Mat&&) = delete; + +} // namespace own +} // namespace gapi +} // namespace cv + +#endif // !defined(GAPI_STANDALONE) + +#endif // OPENCV_GAPI_OWN_CONVERT_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/own/cvdefs.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/own/cvdefs.hpp index d3bef98e98..38296c9b7c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/own/cvdefs.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/own/cvdefs.hpp @@ -1,166 +1,166 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_CV_DEFS_HPP -#define OPENCV_GAPI_CV_DEFS_HPP - -#if defined(GAPI_STANDALONE) -// Simulate OpenCV definitions taken from various -// OpenCV interface headers if G-API is built in a -// standalone mode. - -// interface.h: - -typedef unsigned char uchar; -typedef char schar; - -typedef unsigned short ushort; - -#define CV_USRTYPE1 (void)"CV_USRTYPE1 support has been dropped in OpenCV 4.0" - -#define CV_CN_MAX 512 -#define CV_CN_SHIFT 3 -#define CV_DEPTH_MAX (1 << CV_CN_SHIFT) - -#define CV_8U 0 -#define CV_8S 1 -#define CV_16U 2 -#define CV_16S 3 -#define CV_32S 4 -#define CV_32F 5 -#define CV_64F 6 -#define CV_16F 7 - -#define CV_MAT_DEPTH_MASK (CV_DEPTH_MAX - 1) -#define CV_MAT_DEPTH(flags) ((flags) & CV_MAT_DEPTH_MASK) - -#define CV_MAKETYPE(depth,cn) (CV_MAT_DEPTH(depth) + (((cn)-1) << CV_CN_SHIFT)) -#define CV_MAKE_TYPE CV_MAKETYPE - -#define CV_8UC1 CV_MAKETYPE(CV_8U,1) -#define CV_8UC2 CV_MAKETYPE(CV_8U,2) -#define CV_8UC3 CV_MAKETYPE(CV_8U,3) -#define CV_8UC4 CV_MAKETYPE(CV_8U,4) -#define CV_8UC(n) CV_MAKETYPE(CV_8U,(n)) - -#define CV_8SC1 CV_MAKETYPE(CV_8S,1) -#define CV_8SC2 CV_MAKETYPE(CV_8S,2) -#define CV_8SC3 CV_MAKETYPE(CV_8S,3) -#define CV_8SC4 CV_MAKETYPE(CV_8S,4) -#define CV_8SC(n) CV_MAKETYPE(CV_8S,(n)) - -#define CV_16UC1 CV_MAKETYPE(CV_16U,1) -#define CV_16UC2 CV_MAKETYPE(CV_16U,2) -#define CV_16UC3 CV_MAKETYPE(CV_16U,3) -#define CV_16UC4 CV_MAKETYPE(CV_16U,4) -#define CV_16UC(n) CV_MAKETYPE(CV_16U,(n)) - -#define CV_16SC1 CV_MAKETYPE(CV_16S,1) -#define CV_16SC2 CV_MAKETYPE(CV_16S,2) -#define CV_16SC3 CV_MAKETYPE(CV_16S,3) -#define CV_16SC4 CV_MAKETYPE(CV_16S,4) -#define CV_16SC(n) CV_MAKETYPE(CV_16S,(n)) - -#define CV_32SC1 CV_MAKETYPE(CV_32S,1) -#define CV_32SC2 CV_MAKETYPE(CV_32S,2) -#define CV_32SC3 CV_MAKETYPE(CV_32S,3) -#define CV_32SC4 CV_MAKETYPE(CV_32S,4) -#define CV_32SC(n) CV_MAKETYPE(CV_32S,(n)) - -#define CV_16FC1 CV_MAKETYPE(CV_16F,1) -#define CV_16FC2 CV_MAKETYPE(CV_16F,2) -#define CV_16FC3 CV_MAKETYPE(CV_16F,3) -#define CV_16FC4 CV_MAKETYPE(CV_16F,4) -#define CV_16FC(n) CV_MAKETYPE(CV_16F,(n)) - -#define CV_32FC1 CV_MAKETYPE(CV_32F,1) -#define CV_32FC2 CV_MAKETYPE(CV_32F,2) -#define CV_32FC3 CV_MAKETYPE(CV_32F,3) -#define CV_32FC4 CV_MAKETYPE(CV_32F,4) -#define CV_32FC(n) CV_MAKETYPE(CV_32F,(n)) - -#define CV_64FC1 CV_MAKETYPE(CV_64F,1) -#define CV_64FC2 CV_MAKETYPE(CV_64F,2) -#define CV_64FC3 CV_MAKETYPE(CV_64F,3) -#define CV_64FC4 CV_MAKETYPE(CV_64F,4) -#define CV_64FC(n) CV_MAKETYPE(CV_64F,(n)) - -// cvdef.h: - -#ifndef CV_ALWAYS_INLINE -# if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) -# define CV_ALWAYS_INLINE inline __attribute__((always_inline)) -# elif defined(_MSC_VER) -# define CV_ALWAYS_INLINE __forceinline -# else -# define CV_ALWAYS_INLINE inline -# endif -#endif - -#define CV_MAT_CN_MASK ((CV_CN_MAX - 1) << CV_CN_SHIFT) -#define CV_MAT_CN(flags) ((((flags) & CV_MAT_CN_MASK) >> CV_CN_SHIFT) + 1) -#define CV_MAT_TYPE_MASK (CV_DEPTH_MAX*CV_CN_MAX - 1) -#define CV_MAT_TYPE(flags) ((flags) & CV_MAT_TYPE_MASK) -#define CV_MAT_CONT_FLAG_SHIFT 14 -#define CV_MAT_CONT_FLAG (1 << CV_MAT_CONT_FLAG_SHIFT) -#define CV_IS_MAT_CONT(flags) ((flags) & CV_MAT_CONT_FLAG) -#define CV_IS_CONT_MAT CV_IS_MAT_CONT -#define CV_SUBMAT_FLAG_SHIFT 15 -#define CV_SUBMAT_FLAG (1 << CV_SUBMAT_FLAG_SHIFT) -#define CV_IS_SUBMAT(flags) ((flags) & CV_MAT_SUBMAT_FLAG) - -//** Size of each channel item, -// 0x8442211 = 1000 0100 0100 0010 0010 0001 0001 ~ array of sizeof(arr_type_elem) */ -#define CV_ELEM_SIZE1(type) \ - ((((sizeof(size_t)<<28)|0x8442211) >> CV_MAT_DEPTH(type)*4) & 15) - -#define CV_MAT_TYPE(flags) ((flags) & CV_MAT_TYPE_MASK) - -/** 0x3a50 = 11 10 10 01 01 00 00 ~ array of log2(sizeof(arr_type_elem)) */ -#define CV_ELEM_SIZE(type) \ - (CV_MAT_CN(type) << ((((sizeof(size_t)/4+1)*16384|0x3a50) >> CV_MAT_DEPTH(type)*2) & 3)) - -#ifndef CV_OVERRIDE -# define CV_OVERRIDE override -#endif - -// base.h: -namespace cv -{ -enum BorderTypes { - BORDER_CONSTANT = 0, //!< `iiiiii|abcdefgh|iiiiiii` with some specified `i` - BORDER_REPLICATE = 1, //!< `aaaaaa|abcdefgh|hhhhhhh` - BORDER_REFLECT = 2, //!< `fedcba|abcdefgh|hgfedcb` - BORDER_WRAP = 3, //!< `cdefgh|abcdefgh|abcdefg` - BORDER_REFLECT_101 = 4, //!< `gfedcb|abcdefgh|gfedcba` - BORDER_TRANSPARENT = 5, //!< `uvwxyz|abcdefgh|ijklmno` - - BORDER_REFLECT101 = BORDER_REFLECT_101, //!< same as BORDER_REFLECT_101 - BORDER_DEFAULT = BORDER_REFLECT_101, //!< same as BORDER_REFLECT_101 - BORDER_ISOLATED = 16 //!< do not look outside of ROI -}; -// imgproc.hpp: -enum InterpolationFlags{ - INTER_NEAREST = 0, - INTER_LINEAR = 1, - INTER_CUBIC = 2, - INTER_AREA = 3, - INTER_LANCZOS4 = 4, - INTER_LINEAR_EXACT = 5, - INTER_MAX = 7, -}; -} // namespace cv - -static inline int cvFloor( double value ) -{ - int i = (int)value; - return i - (i > value); -} - -#endif // defined(GAPI_STANDALONE) - -#endif // OPENCV_GAPI_CV_DEFS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_CV_DEFS_HPP +#define OPENCV_GAPI_CV_DEFS_HPP + +#if defined(GAPI_STANDALONE) +// Simulate OpenCV definitions taken from various +// OpenCV interface headers if G-API is built in a +// standalone mode. + +// interface.h: + +typedef unsigned char uchar; +typedef char schar; + +typedef unsigned short ushort; + +#define CV_USRTYPE1 (void)"CV_USRTYPE1 support has been dropped in OpenCV 4.0" + +#define CV_CN_MAX 512 +#define CV_CN_SHIFT 3 +#define CV_DEPTH_MAX (1 << CV_CN_SHIFT) + +#define CV_8U 0 +#define CV_8S 1 +#define CV_16U 2 +#define CV_16S 3 +#define CV_32S 4 +#define CV_32F 5 +#define CV_64F 6 +#define CV_16F 7 + +#define CV_MAT_DEPTH_MASK (CV_DEPTH_MAX - 1) +#define CV_MAT_DEPTH(flags) ((flags) & CV_MAT_DEPTH_MASK) + +#define CV_MAKETYPE(depth,cn) (CV_MAT_DEPTH(depth) + (((cn)-1) << CV_CN_SHIFT)) +#define CV_MAKE_TYPE CV_MAKETYPE + +#define CV_8UC1 CV_MAKETYPE(CV_8U,1) +#define CV_8UC2 CV_MAKETYPE(CV_8U,2) +#define CV_8UC3 CV_MAKETYPE(CV_8U,3) +#define CV_8UC4 CV_MAKETYPE(CV_8U,4) +#define CV_8UC(n) CV_MAKETYPE(CV_8U,(n)) + +#define CV_8SC1 CV_MAKETYPE(CV_8S,1) +#define CV_8SC2 CV_MAKETYPE(CV_8S,2) +#define CV_8SC3 CV_MAKETYPE(CV_8S,3) +#define CV_8SC4 CV_MAKETYPE(CV_8S,4) +#define CV_8SC(n) CV_MAKETYPE(CV_8S,(n)) + +#define CV_16UC1 CV_MAKETYPE(CV_16U,1) +#define CV_16UC2 CV_MAKETYPE(CV_16U,2) +#define CV_16UC3 CV_MAKETYPE(CV_16U,3) +#define CV_16UC4 CV_MAKETYPE(CV_16U,4) +#define CV_16UC(n) CV_MAKETYPE(CV_16U,(n)) + +#define CV_16SC1 CV_MAKETYPE(CV_16S,1) +#define CV_16SC2 CV_MAKETYPE(CV_16S,2) +#define CV_16SC3 CV_MAKETYPE(CV_16S,3) +#define CV_16SC4 CV_MAKETYPE(CV_16S,4) +#define CV_16SC(n) CV_MAKETYPE(CV_16S,(n)) + +#define CV_32SC1 CV_MAKETYPE(CV_32S,1) +#define CV_32SC2 CV_MAKETYPE(CV_32S,2) +#define CV_32SC3 CV_MAKETYPE(CV_32S,3) +#define CV_32SC4 CV_MAKETYPE(CV_32S,4) +#define CV_32SC(n) CV_MAKETYPE(CV_32S,(n)) + +#define CV_16FC1 CV_MAKETYPE(CV_16F,1) +#define CV_16FC2 CV_MAKETYPE(CV_16F,2) +#define CV_16FC3 CV_MAKETYPE(CV_16F,3) +#define CV_16FC4 CV_MAKETYPE(CV_16F,4) +#define CV_16FC(n) CV_MAKETYPE(CV_16F,(n)) + +#define CV_32FC1 CV_MAKETYPE(CV_32F,1) +#define CV_32FC2 CV_MAKETYPE(CV_32F,2) +#define CV_32FC3 CV_MAKETYPE(CV_32F,3) +#define CV_32FC4 CV_MAKETYPE(CV_32F,4) +#define CV_32FC(n) CV_MAKETYPE(CV_32F,(n)) + +#define CV_64FC1 CV_MAKETYPE(CV_64F,1) +#define CV_64FC2 CV_MAKETYPE(CV_64F,2) +#define CV_64FC3 CV_MAKETYPE(CV_64F,3) +#define CV_64FC4 CV_MAKETYPE(CV_64F,4) +#define CV_64FC(n) CV_MAKETYPE(CV_64F,(n)) + +// cvdef.h: + +#ifndef CV_ALWAYS_INLINE +# if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) +# define CV_ALWAYS_INLINE inline __attribute__((always_inline)) +# elif defined(_MSC_VER) +# define CV_ALWAYS_INLINE __forceinline +# else +# define CV_ALWAYS_INLINE inline +# endif +#endif + +#define CV_MAT_CN_MASK ((CV_CN_MAX - 1) << CV_CN_SHIFT) +#define CV_MAT_CN(flags) ((((flags) & CV_MAT_CN_MASK) >> CV_CN_SHIFT) + 1) +#define CV_MAT_TYPE_MASK (CV_DEPTH_MAX*CV_CN_MAX - 1) +#define CV_MAT_TYPE(flags) ((flags) & CV_MAT_TYPE_MASK) +#define CV_MAT_CONT_FLAG_SHIFT 14 +#define CV_MAT_CONT_FLAG (1 << CV_MAT_CONT_FLAG_SHIFT) +#define CV_IS_MAT_CONT(flags) ((flags) & CV_MAT_CONT_FLAG) +#define CV_IS_CONT_MAT CV_IS_MAT_CONT +#define CV_SUBMAT_FLAG_SHIFT 15 +#define CV_SUBMAT_FLAG (1 << CV_SUBMAT_FLAG_SHIFT) +#define CV_IS_SUBMAT(flags) ((flags) & CV_MAT_SUBMAT_FLAG) + +//** Size of each channel item, +// 0x8442211 = 1000 0100 0100 0010 0010 0001 0001 ~ array of sizeof(arr_type_elem) */ +#define CV_ELEM_SIZE1(type) \ + ((((sizeof(size_t)<<28)|0x8442211) >> CV_MAT_DEPTH(type)*4) & 15) + +#define CV_MAT_TYPE(flags) ((flags) & CV_MAT_TYPE_MASK) + +/** 0x3a50 = 11 10 10 01 01 00 00 ~ array of log2(sizeof(arr_type_elem)) */ +#define CV_ELEM_SIZE(type) \ + (CV_MAT_CN(type) << ((((sizeof(size_t)/4+1)*16384|0x3a50) >> CV_MAT_DEPTH(type)*2) & 3)) + +#ifndef CV_OVERRIDE +# define CV_OVERRIDE override +#endif + +// base.h: +namespace cv +{ +enum BorderTypes { + BORDER_CONSTANT = 0, //!< `iiiiii|abcdefgh|iiiiiii` with some specified `i` + BORDER_REPLICATE = 1, //!< `aaaaaa|abcdefgh|hhhhhhh` + BORDER_REFLECT = 2, //!< `fedcba|abcdefgh|hgfedcb` + BORDER_WRAP = 3, //!< `cdefgh|abcdefgh|abcdefg` + BORDER_REFLECT_101 = 4, //!< `gfedcb|abcdefgh|gfedcba` + BORDER_TRANSPARENT = 5, //!< `uvwxyz|abcdefgh|ijklmno` + + BORDER_REFLECT101 = BORDER_REFLECT_101, //!< same as BORDER_REFLECT_101 + BORDER_DEFAULT = BORDER_REFLECT_101, //!< same as BORDER_REFLECT_101 + BORDER_ISOLATED = 16 //!< do not look outside of ROI +}; +// imgproc.hpp: +enum InterpolationFlags{ + INTER_NEAREST = 0, + INTER_LINEAR = 1, + INTER_CUBIC = 2, + INTER_AREA = 3, + INTER_LANCZOS4 = 4, + INTER_LINEAR_EXACT = 5, + INTER_MAX = 7, +}; +} // namespace cv + +static inline int cvFloor( double value ) +{ + int i = (int)value; + return i - (i > value); +} + +#endif // defined(GAPI_STANDALONE) + +#endif // OPENCV_GAPI_CV_DEFS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/own/exports.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/own/exports.hpp index c36f4003d0..67534df13f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/own/exports.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/own/exports.hpp @@ -1,42 +1,42 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_OWN_TYPES_HPP -#define OPENCV_GAPI_OWN_TYPES_HPP - -# if defined(__OPENCV_BUILD) -# include -# define GAPI_EXPORTS CV_EXPORTS - /* special informative macros for wrapper generators */ -# define GAPI_PROP CV_PROP -# define GAPI_PROP_RW CV_PROP_RW -# define GAPI_WRAP CV_WRAP -# define GAPI_EXPORTS_W_SIMPLE CV_EXPORTS_W_SIMPLE -# define GAPI_EXPORTS_W CV_EXPORTS_W -# else -# define GAPI_PROP -# define GAPI_PROP_RW -# define GAPI_WRAP -# define GAPI_EXPORTS -# define GAPI_EXPORTS_W_SIMPLE -# define GAPI_EXPORTS_W - -#if 0 // Note: the following version currently is not needed for non-OpenCV build -# if defined _WIN32 -# define GAPI_EXPORTS __declspec(dllexport) -# elif defined __GNUC__ && __GNUC__ >= 4 -# define GAPI_EXPORTS __attribute__ ((visibility ("default"))) -# endif - -# ifndef GAPI_EXPORTS -# define GAPI_EXPORTS -# endif -#endif - -# endif - -#endif // OPENCV_GAPI_OWN_TYPES_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_OWN_TYPES_HPP +#define OPENCV_GAPI_OWN_TYPES_HPP + +# if defined(__OPENCV_BUILD) +# include +# define GAPI_EXPORTS CV_EXPORTS + /* special informative macros for wrapper generators */ +# define GAPI_PROP CV_PROP +# define GAPI_PROP_RW CV_PROP_RW +# define GAPI_WRAP CV_WRAP +# define GAPI_EXPORTS_W_SIMPLE CV_EXPORTS_W_SIMPLE +# define GAPI_EXPORTS_W CV_EXPORTS_W +# else +# define GAPI_PROP +# define GAPI_PROP_RW +# define GAPI_WRAP +# define GAPI_EXPORTS +# define GAPI_EXPORTS_W_SIMPLE +# define GAPI_EXPORTS_W + +#if 0 // Note: the following version currently is not needed for non-OpenCV build +# if defined _WIN32 +# define GAPI_EXPORTS __declspec(dllexport) +# elif defined __GNUC__ && __GNUC__ >= 4 +# define GAPI_EXPORTS __attribute__ ((visibility ("default"))) +# endif + +# ifndef GAPI_EXPORTS +# define GAPI_EXPORTS +# endif +#endif + +# endif + +#endif // OPENCV_GAPI_OWN_TYPES_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/own/mat.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/own/mat.hpp index ce9c0bf362..50adca2d0f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/own/mat.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/own/mat.hpp @@ -1,354 +1,354 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_OWN_MAT_HPP -#define OPENCV_GAPI_OWN_MAT_HPP - -#include -#include -#include -#include -#include - -#include //std::shared_ptr -#include //std::memcpy -#include //std::accumulate -#include -#include - -namespace cv { namespace gapi { namespace own { - namespace detail { - template - void assign_row(void* ptr, int cols, Scalar const& s) - { - auto p = static_cast(ptr); - for (int c = 0; c < cols; c++) - { - for (int ch = 0; ch < channels; ch++) - { - p[c * channels + ch] = saturate(s[ch], roundd); - } - } - } - - inline size_t default_step(int type, int cols) - { - return CV_ELEM_SIZE(type) * cols; - } - //Matrix header, i.e. fields that are unique to each Mat object. - //Devoted class is needed to implement custom behavior on move (erasing state of moved from object) - struct MatHeader{ - enum { AUTO_STEP = 0}; - enum { TYPE_MASK = 0x00000FFF }; - - MatHeader() = default; - - MatHeader(int _rows, int _cols, int type, void* _data, size_t _step) - : flags((type & TYPE_MASK)), rows(_rows), cols(_cols), data((uchar*)_data), step(_step == AUTO_STEP ? detail::default_step(type, _cols) : _step) - {} - - MatHeader(const std::vector &_dims, int type, void* _data) - : flags((type & TYPE_MASK)), data((uchar*)_data), step(0), dims(_dims) - {} - - MatHeader(const MatHeader& ) = default; - MatHeader(MatHeader&& src) : MatHeader(src) // reuse copy constructor here - { - MatHeader empty; //give it a name to call copy(not move) assignment below - src = empty; - } - MatHeader& operator=(const MatHeader& ) = default; - MatHeader& operator=(MatHeader&& src) - { - *this = src; //calling a copy assignment here, not move one - MatHeader empty; //give it a name to call copy(not move) assignment below - src = empty; - return *this; - } - /*! includes several bit-fields: - - depth - - number of channels - */ - int flags = 0; - - //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions - int rows = 0, cols = 0; - //! pointer to the data - uchar* data = nullptr; - size_t step = 0; - //! dimensions (ND-case) - std::vector dims; - }; - } // namespace detail - //concise version of cv::Mat suitable for GAPI needs (used when no dependence on OpenCV is required) - class Mat : public detail::MatHeader{ - public: - - Mat() = default; - - /** @overload - @param _rows Number of rows in a 2D array. - @param _cols Number of columns in a 2D array. - @param _type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - @param _data Pointer to the user data. Matrix constructors that take data and step parameters do not - allocate matrix data. Instead, they just initialize the matrix header that points to the specified - data, which means that no data is copied. This operation is very efficient and can be used to - process external data using OpenCV functions. The external data is not automatically deallocated, so - you should take care of it. - @param _step Number of bytes each matrix row occupies. The value should include the padding bytes at - the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed - and the actual step is calculated as cols*elemSize(). See Mat::elemSize. - */ - Mat(int _rows, int _cols, int _type, void* _data, size_t _step = AUTO_STEP) - : MatHeader (_rows, _cols, _type, _data, _step) - {} - - Mat(const std::vector &_dims, int _type, void* _data) - : MatHeader (_dims, _type, _data) - {} - - Mat(std::vector &&_dims, int _type, void* _data) - : MatHeader (std::move(_dims), _type, _data) - {} - - Mat(Mat const& src, const Rect& roi ) - : Mat(src) - { - rows = roi.height; - cols = roi.width; - data = ptr(roi.y, roi.x); - } - - Mat(Mat const& ) = default; - Mat(Mat&& ) = default; - - Mat& operator=(Mat const& ) = default; - Mat& operator=(Mat&& ) = default; - - /** @brief Sets all or some of the array elements to the specified value. - @param s Assigned scalar converted to the actual array type. - */ - Mat& operator = (const Scalar& s) - { - constexpr unsigned max_channels = 4; //Scalar can't fit more than 4 - using func_p_t = void (*)(void*, int, Scalar const&); - using detail::assign_row; - #define TABLE_ENTRY(type) {assign_row, assign_row, assign_row, assign_row} - static constexpr func_p_t func_tbl[][max_channels] = { - TABLE_ENTRY(uchar), - TABLE_ENTRY(schar), - TABLE_ENTRY(ushort), - TABLE_ENTRY(short), - TABLE_ENTRY(int), - TABLE_ENTRY(float), - TABLE_ENTRY(double) - }; - #undef TABLE_ENTRY - - static_assert(CV_8U == 0 && CV_8S == 1 && CV_16U == 2 && CV_16S == 3 - && CV_32S == 4 && CV_32F == 5 && CV_64F == 6, - "OCV type ids used as indexes to array, thus exact numbers are important!" - ); - - const auto depth = static_cast(this->depth()); - GAPI_Assert(depth < sizeof(func_tbl)/sizeof(func_tbl[0])); - - if (dims.empty()) - { - const auto channels = static_cast(this->channels()); - GAPI_Assert(channels <= max_channels); - - auto* f = func_tbl[depth][channels - 1]; - for (int r = 0; r < rows; ++r) - { - (*f)(static_cast(ptr(r)), cols, s ); - } - } - else - { - auto* f = func_tbl[depth][0]; - // FIXME: better to refactor assign_row to use std::size_t by default - (*f)(static_cast(data), static_cast(total()), s); - } - return *this; - } - - /** @brief Returns the matrix element size in bytes. - - The method returns the matrix element size in bytes. For example, if the matrix type is CV_16SC3 , - the method returns 3\*sizeof(short) or 6. - */ - size_t elemSize() const - { - return CV_ELEM_SIZE(type()); - } - /** @brief Returns the type of a matrix element. - - The method returns a matrix element type. This is an identifier compatible with the CvMat type - system, like CV_16SC3 or 16-bit signed 3-channel array, and so on. - */ - int type() const {return CV_MAT_TYPE(flags);} - - /** @brief Returns the depth of a matrix element. - - The method returns the identifier of the matrix element depth (the type of each individual channel). - For example, for a 16-bit signed element array, the method returns CV_16S . A complete list of - matrix types contains the following values: - - CV_8U - 8-bit unsigned integers ( 0..255 ) - - CV_8S - 8-bit signed integers ( -128..127 ) - - CV_16U - 16-bit unsigned integers ( 0..65535 ) - - CV_16S - 16-bit signed integers ( -32768..32767 ) - - CV_32S - 32-bit signed integers ( -2147483648..2147483647 ) - - CV_32F - 32-bit floating-point numbers ( -FLT_MAX..FLT_MAX, INF, NAN ) - - CV_64F - 64-bit floating-point numbers ( -DBL_MAX..DBL_MAX, INF, NAN ) - */ - int depth() const {return CV_MAT_DEPTH(flags);} - - /** @brief Returns the number of matrix channels. - - The method returns the number of matrix channels. - If matrix is N-dimensional, -1 is returned. - */ - int channels() const {return dims.empty() ? CV_MAT_CN(flags) : -1;} - - /** - @param _rows New number of rows. - @param _cols New number of columns. - @param _type New matrix type. - */ - void create(int _rows, int _cols, int _type) - { - create(Size{_cols, _rows}, _type); - } - /** @overload - @param _size Alternative new matrix size specification: Size(cols, rows) - @param _type New matrix type. - */ - void create(Size _size, int _type) - { - GAPI_Assert(_size.height >= 0 && _size.width >= 0); - if (_size != Size{cols, rows} ) - { - Mat tmp{_size.height, _size.width, _type, nullptr}; - tmp.memory.reset(new uchar[ tmp.step * tmp.rows], [](uchar * p){delete[] p;}); - tmp.data = tmp.memory.get(); - - *this = std::move(tmp); - } - } - - void create(const std::vector &_dims, int _type) - { - // FIXME: make a proper reallocation-on-demands - // WARNING: no tensor views, so no strides - Mat tmp{_dims, _type, nullptr}; - // FIXME: this accumulate duplicates a lot - const auto sz = std::accumulate(_dims.begin(), _dims.end(), 1, std::multiplies()); - tmp.memory.reset(new uchar[CV_ELEM_SIZE(_type)*sz], [](uchar * p){delete[] p;}); - tmp.data = tmp.memory.get(); - *this = std::move(tmp); - } - - /** @brief Creates a full copy of the matrix and the underlying data. - - The method creates a full copy of the matrix. The original step[] is not taken into account. - So, the copy has a continuous buffer occupying total() * elemSize() bytes. - */ - Mat clone() const - { - Mat m; - copyTo(m); - return m; - } - - /** @brief Copies the matrix to another one. - - The method copies the matrix data to another matrix. Before copying the data, the method invokes : - @code - m.create(this->size(), this->type()); - @endcode - so that the destination matrix is reallocated if needed. While m.copyTo(m); works flawlessly, the - function does not handle the case of a partial overlap between the source and the destination - matrices. - */ - void copyTo(Mat& dst) const - { - if (dims.empty()) - { - dst.create(rows, cols, type()); - for (int r = 0; r < rows; ++r) - { - std::copy_n(ptr(r), detail::default_step(type(),cols), dst.ptr(r)); - } - } - else - { - dst.create(dims, depth()); - std::copy_n(data, total()*elemSize(), data); - } - } - - /** @brief Returns true if the array has no elements. - - The method returns true if Mat::total() is 0 or if Mat::data is NULL. Because of pop_back() and - resize() methods `M.total() == 0` does not imply that `M.data == NULL`. - */ - bool empty() const - { - return data == 0 || total() == 0; - } - - /** @brief Returns the total number of array elements. - - The method returns the number of array elements (a number of pixels if the array represents an - image). - */ - size_t total() const - { - return dims.empty() - ? (static_cast(rows) * cols) - : std::accumulate(dims.begin(), dims.end(), static_cast(1), std::multiplies()); - } - - /** @overload - @param roi Extracted submatrix specified as a rectangle. - */ - Mat operator()( const Rect& roi ) const - { - return Mat{*this, roi}; - } - - - /** @brief Returns a pointer to the specified matrix row. - - The methods return `uchar*` or typed pointer to the specified matrix row. See the sample in - Mat::isContinuous to know how to use these methods. - @param row Index along the dimension 0 - @param col Index along the dimension 1 - */ - uchar* ptr(int row, int col = 0) - { - return const_cast(const_cast(this)->ptr(row,col)); - } - /** @overload */ - const uchar* ptr(int row, int col = 0) const - { - return data + step * row + CV_ELEM_SIZE(type()) * col; - } - - - private: - //actual memory allocated for storage, or nullptr if object is non owning view to over memory - std::shared_ptr memory; - }; - -} //namespace own -} //namespace gapi -} //namespace cv - -#endif /* OPENCV_GAPI_OWN_MAT_HPP */ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_OWN_MAT_HPP +#define OPENCV_GAPI_OWN_MAT_HPP + +#include +#include +#include +#include +#include + +#include //std::shared_ptr +#include //std::memcpy +#include //std::accumulate +#include +#include + +namespace cv { namespace gapi { namespace own { + namespace detail { + template + void assign_row(void* ptr, int cols, Scalar const& s) + { + auto p = static_cast(ptr); + for (int c = 0; c < cols; c++) + { + for (int ch = 0; ch < channels; ch++) + { + p[c * channels + ch] = saturate(s[ch], roundd); + } + } + } + + inline size_t default_step(int type, int cols) + { + return CV_ELEM_SIZE(type) * cols; + } + //Matrix header, i.e. fields that are unique to each Mat object. + //Devoted class is needed to implement custom behavior on move (erasing state of moved from object) + struct MatHeader{ + enum { AUTO_STEP = 0}; + enum { TYPE_MASK = 0x00000FFF }; + + MatHeader() = default; + + MatHeader(int _rows, int _cols, int type, void* _data, size_t _step) + : flags((type & TYPE_MASK)), rows(_rows), cols(_cols), data((uchar*)_data), step(_step == AUTO_STEP ? detail::default_step(type, _cols) : _step) + {} + + MatHeader(const std::vector &_dims, int type, void* _data) + : flags((type & TYPE_MASK)), data((uchar*)_data), step(0), dims(_dims) + {} + + MatHeader(const MatHeader& ) = default; + MatHeader(MatHeader&& src) : MatHeader(src) // reuse copy constructor here + { + MatHeader empty; //give it a name to call copy(not move) assignment below + src = empty; + } + MatHeader& operator=(const MatHeader& ) = default; + MatHeader& operator=(MatHeader&& src) + { + *this = src; //calling a copy assignment here, not move one + MatHeader empty; //give it a name to call copy(not move) assignment below + src = empty; + return *this; + } + /*! includes several bit-fields: + - depth + - number of channels + */ + int flags = 0; + + //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions + int rows = 0, cols = 0; + //! pointer to the data + uchar* data = nullptr; + size_t step = 0; + //! dimensions (ND-case) + std::vector dims; + }; + } // namespace detail + //concise version of cv::Mat suitable for GAPI needs (used when no dependence on OpenCV is required) + class Mat : public detail::MatHeader{ + public: + + Mat() = default; + + /** @overload + @param _rows Number of rows in a 2D array. + @param _cols Number of columns in a 2D array. + @param _type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param _data Pointer to the user data. Matrix constructors that take data and step parameters do not + allocate matrix data. Instead, they just initialize the matrix header that points to the specified + data, which means that no data is copied. This operation is very efficient and can be used to + process external data using OpenCV functions. The external data is not automatically deallocated, so + you should take care of it. + @param _step Number of bytes each matrix row occupies. The value should include the padding bytes at + the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed + and the actual step is calculated as cols*elemSize(). See Mat::elemSize. + */ + Mat(int _rows, int _cols, int _type, void* _data, size_t _step = AUTO_STEP) + : MatHeader (_rows, _cols, _type, _data, _step) + {} + + Mat(const std::vector &_dims, int _type, void* _data) + : MatHeader (_dims, _type, _data) + {} + + Mat(std::vector &&_dims, int _type, void* _data) + : MatHeader (std::move(_dims), _type, _data) + {} + + Mat(Mat const& src, const Rect& roi ) + : Mat(src) + { + rows = roi.height; + cols = roi.width; + data = ptr(roi.y, roi.x); + } + + Mat(Mat const& ) = default; + Mat(Mat&& ) = default; + + Mat& operator=(Mat const& ) = default; + Mat& operator=(Mat&& ) = default; + + /** @brief Sets all or some of the array elements to the specified value. + @param s Assigned scalar converted to the actual array type. + */ + Mat& operator = (const Scalar& s) + { + constexpr unsigned max_channels = 4; //Scalar can't fit more than 4 + using func_p_t = void (*)(void*, int, Scalar const&); + using detail::assign_row; + #define TABLE_ENTRY(type) {assign_row, assign_row, assign_row, assign_row} + static constexpr func_p_t func_tbl[][max_channels] = { + TABLE_ENTRY(uchar), + TABLE_ENTRY(schar), + TABLE_ENTRY(ushort), + TABLE_ENTRY(short), + TABLE_ENTRY(int), + TABLE_ENTRY(float), + TABLE_ENTRY(double) + }; + #undef TABLE_ENTRY + + static_assert(CV_8U == 0 && CV_8S == 1 && CV_16U == 2 && CV_16S == 3 + && CV_32S == 4 && CV_32F == 5 && CV_64F == 6, + "OCV type ids used as indexes to array, thus exact numbers are important!" + ); + + const auto depth = static_cast(this->depth()); + GAPI_Assert(depth < sizeof(func_tbl)/sizeof(func_tbl[0])); + + if (dims.empty()) + { + const auto channels = static_cast(this->channels()); + GAPI_Assert(channels <= max_channels); + + auto* f = func_tbl[depth][channels - 1]; + for (int r = 0; r < rows; ++r) + { + (*f)(static_cast(ptr(r)), cols, s ); + } + } + else + { + auto* f = func_tbl[depth][0]; + // FIXME: better to refactor assign_row to use std::size_t by default + (*f)(static_cast(data), static_cast(total()), s); + } + return *this; + } + + /** @brief Returns the matrix element size in bytes. + + The method returns the matrix element size in bytes. For example, if the matrix type is CV_16SC3 , + the method returns 3\*sizeof(short) or 6. + */ + size_t elemSize() const + { + return CV_ELEM_SIZE(type()); + } + /** @brief Returns the type of a matrix element. + + The method returns a matrix element type. This is an identifier compatible with the CvMat type + system, like CV_16SC3 or 16-bit signed 3-channel array, and so on. + */ + int type() const {return CV_MAT_TYPE(flags);} + + /** @brief Returns the depth of a matrix element. + + The method returns the identifier of the matrix element depth (the type of each individual channel). + For example, for a 16-bit signed element array, the method returns CV_16S . A complete list of + matrix types contains the following values: + - CV_8U - 8-bit unsigned integers ( 0..255 ) + - CV_8S - 8-bit signed integers ( -128..127 ) + - CV_16U - 16-bit unsigned integers ( 0..65535 ) + - CV_16S - 16-bit signed integers ( -32768..32767 ) + - CV_32S - 32-bit signed integers ( -2147483648..2147483647 ) + - CV_32F - 32-bit floating-point numbers ( -FLT_MAX..FLT_MAX, INF, NAN ) + - CV_64F - 64-bit floating-point numbers ( -DBL_MAX..DBL_MAX, INF, NAN ) + */ + int depth() const {return CV_MAT_DEPTH(flags);} + + /** @brief Returns the number of matrix channels. + + The method returns the number of matrix channels. + If matrix is N-dimensional, -1 is returned. + */ + int channels() const {return dims.empty() ? CV_MAT_CN(flags) : -1;} + + /** + @param _rows New number of rows. + @param _cols New number of columns. + @param _type New matrix type. + */ + void create(int _rows, int _cols, int _type) + { + create(Size{_cols, _rows}, _type); + } + /** @overload + @param _size Alternative new matrix size specification: Size(cols, rows) + @param _type New matrix type. + */ + void create(Size _size, int _type) + { + GAPI_Assert(_size.height >= 0 && _size.width >= 0); + if (_size != Size{cols, rows} ) + { + Mat tmp{_size.height, _size.width, _type, nullptr}; + tmp.memory.reset(new uchar[ tmp.step * tmp.rows], [](uchar * p){delete[] p;}); + tmp.data = tmp.memory.get(); + + *this = std::move(tmp); + } + } + + void create(const std::vector &_dims, int _type) + { + // FIXME: make a proper reallocation-on-demands + // WARNING: no tensor views, so no strides + Mat tmp{_dims, _type, nullptr}; + // FIXME: this accumulate duplicates a lot + const auto sz = std::accumulate(_dims.begin(), _dims.end(), 1, std::multiplies()); + tmp.memory.reset(new uchar[CV_ELEM_SIZE(_type)*sz], [](uchar * p){delete[] p;}); + tmp.data = tmp.memory.get(); + *this = std::move(tmp); + } + + /** @brief Creates a full copy of the matrix and the underlying data. + + The method creates a full copy of the matrix. The original step[] is not taken into account. + So, the copy has a continuous buffer occupying total() * elemSize() bytes. + */ + Mat clone() const + { + Mat m; + copyTo(m); + return m; + } + + /** @brief Copies the matrix to another one. + + The method copies the matrix data to another matrix. Before copying the data, the method invokes : + @code + m.create(this->size(), this->type()); + @endcode + so that the destination matrix is reallocated if needed. While m.copyTo(m); works flawlessly, the + function does not handle the case of a partial overlap between the source and the destination + matrices. + */ + void copyTo(Mat& dst) const + { + if (dims.empty()) + { + dst.create(rows, cols, type()); + for (int r = 0; r < rows; ++r) + { + std::copy_n(ptr(r), detail::default_step(type(),cols), dst.ptr(r)); + } + } + else + { + dst.create(dims, depth()); + std::copy_n(data, total()*elemSize(), data); + } + } + + /** @brief Returns true if the array has no elements. + + The method returns true if Mat::total() is 0 or if Mat::data is NULL. Because of pop_back() and + resize() methods `M.total() == 0` does not imply that `M.data == NULL`. + */ + bool empty() const + { + return data == 0 || total() == 0; + } + + /** @brief Returns the total number of array elements. + + The method returns the number of array elements (a number of pixels if the array represents an + image). + */ + size_t total() const + { + return dims.empty() + ? (static_cast(rows) * cols) + : std::accumulate(dims.begin(), dims.end(), static_cast(1), std::multiplies()); + } + + /** @overload + @param roi Extracted submatrix specified as a rectangle. + */ + Mat operator()( const Rect& roi ) const + { + return Mat{*this, roi}; + } + + + /** @brief Returns a pointer to the specified matrix row. + + The methods return `uchar*` or typed pointer to the specified matrix row. See the sample in + Mat::isContinuous to know how to use these methods. + @param row Index along the dimension 0 + @param col Index along the dimension 1 + */ + uchar* ptr(int row, int col = 0) + { + return const_cast(const_cast(this)->ptr(row,col)); + } + /** @overload */ + const uchar* ptr(int row, int col = 0) const + { + return data + step * row + CV_ELEM_SIZE(type()) * col; + } + + + private: + //actual memory allocated for storage, or nullptr if object is non owning view to over memory + std::shared_ptr memory; + }; + +} //namespace own +} //namespace gapi +} //namespace cv + +#endif /* OPENCV_GAPI_OWN_MAT_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/own/saturate.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/own/saturate.hpp index 74eaecf57e..e068543e8c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/own/saturate.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/own/saturate.hpp @@ -1,83 +1,83 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_OWN_SATURATE_HPP -#define OPENCV_GAPI_OWN_SATURATE_HPP - -#include - -#include - -#include -#include - -namespace cv { namespace gapi { namespace own { -//----------------------------- -// -// Numeric cast with saturation -// -//----------------------------- - -template::value && - std::is_integral::value && - std::is_integral::value> > -static CV_ALWAYS_INLINE DST saturate(SRC x) -{ - if (sizeof(DST) > sizeof(SRC)) - return static_cast(x); - - // compiler must recognize this saturation, - // so compile saturate(a + b) with adds - // instruction (e.g.: _mm_adds_epi16 if x86) - return x < std::numeric_limits::min()? - std::numeric_limits::min(): - x > std::numeric_limits::max()? - std::numeric_limits::max(): - static_cast(x); -} -template -static CV_ALWAYS_INLINE T saturate(T x) -{ - return x; -} - -template::value, bool> = true > -static CV_ALWAYS_INLINE DST saturate(SRC x, R) -{ - return static_cast(x); -} -template::value && - std::is_integral::value , bool> = true > -static CV_ALWAYS_INLINE DST saturate(SRC x, R) -{ - return saturate(x); -} -// Note, that OpenCV rounds differently: -// - like std::round() for add, subtract -// - like std::rint() for multiply, divide -template::value && - std::is_floating_point::value, bool> = true > -static CV_ALWAYS_INLINE DST saturate(SRC x, R round) -{ - int ix = static_cast(round(x)); - return saturate(ix); -} - -// explicit suffix 'd' for double type -inline double ceild(double x) { return ceil(x); } -inline double floord(double x) { return floor(x); } -inline double roundd(double x) { return round(x); } -inline double rintd(double x) { return rint(x); } - -} //namespace own -} //namespace gapi -} //namespace cv -#endif /* OPENCV_GAPI_OWN_SATURATE_HPP */ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_OWN_SATURATE_HPP +#define OPENCV_GAPI_OWN_SATURATE_HPP + +#include + +#include + +#include +#include + +namespace cv { namespace gapi { namespace own { +//----------------------------- +// +// Numeric cast with saturation +// +//----------------------------- + +template::value && + std::is_integral::value && + std::is_integral::value> > +static CV_ALWAYS_INLINE DST saturate(SRC x) +{ + if (sizeof(DST) > sizeof(SRC)) + return static_cast(x); + + // compiler must recognize this saturation, + // so compile saturate(a + b) with adds + // instruction (e.g.: _mm_adds_epi16 if x86) + return x < std::numeric_limits::min()? + std::numeric_limits::min(): + x > std::numeric_limits::max()? + std::numeric_limits::max(): + static_cast(x); +} +template +static CV_ALWAYS_INLINE T saturate(T x) +{ + return x; +} + +template::value, bool> = true > +static CV_ALWAYS_INLINE DST saturate(SRC x, R) +{ + return static_cast(x); +} +template::value && + std::is_integral::value , bool> = true > +static CV_ALWAYS_INLINE DST saturate(SRC x, R) +{ + return saturate(x); +} +// Note, that OpenCV rounds differently: +// - like std::round() for add, subtract +// - like std::rint() for multiply, divide +template::value && + std::is_floating_point::value, bool> = true > +static CV_ALWAYS_INLINE DST saturate(SRC x, R round) +{ + int ix = static_cast(round(x)); + return saturate(ix); +} + +// explicit suffix 'd' for double type +inline double ceild(double x) { return ceil(x); } +inline double floord(double x) { return floor(x); } +inline double roundd(double x) { return round(x); } +inline double rintd(double x) { return rint(x); } + +} //namespace own +} //namespace gapi +} //namespace cv +#endif /* OPENCV_GAPI_OWN_SATURATE_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/own/scalar.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/own/scalar.hpp index 3b107befcc..02da06ca7a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/own/scalar.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/own/scalar.hpp @@ -1,47 +1,47 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_GAPI_OWN_SCALAR_HPP -#define OPENCV_GAPI_GAPI_OWN_SCALAR_HPP - -#include - -namespace cv -{ -namespace gapi -{ -namespace own -{ - -class GAPI_EXPORTS Scalar -{ -public: - Scalar() = default; - explicit Scalar(double v0) { val[0] = v0; } - Scalar(double v0, double v1, double v2 = 0, double v3 = 0) - : val{v0, v1, v2, v3} - { - } - - const double& operator[](int i) const { return val[i]; } - double& operator[](int i) { return val[i]; } - - static Scalar all(double v0) { return Scalar(v0, v0, v0, v0); } - - double val[4] = {0}; -}; - -inline bool operator==(const Scalar& lhs, const Scalar& rhs) -{ - return std::equal(std::begin(lhs.val), std::end(lhs.val), std::begin(rhs.val)); -} - -} // namespace own -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_GAPI_OWN_SCALAR_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_GAPI_OWN_SCALAR_HPP +#define OPENCV_GAPI_GAPI_OWN_SCALAR_HPP + +#include + +namespace cv +{ +namespace gapi +{ +namespace own +{ + +class GAPI_EXPORTS Scalar +{ +public: + Scalar() = default; + explicit Scalar(double v0) { val[0] = v0; } + Scalar(double v0, double v1, double v2 = 0, double v3 = 0) + : val{v0, v1, v2, v3} + { + } + + const double& operator[](int i) const { return val[i]; } + double& operator[](int i) { return val[i]; } + + static Scalar all(double v0) { return Scalar(v0, v0, v0, v0); } + + double val[4] = {0}; +}; + +inline bool operator==(const Scalar& lhs, const Scalar& rhs) +{ + return std::equal(std::begin(lhs.val), std::end(lhs.val), std::begin(rhs.val)); +} + +} // namespace own +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_GAPI_OWN_SCALAR_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/own/types.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/own/types.hpp index 211b5c85ff..ef01056db1 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/own/types.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/own/types.hpp @@ -1,162 +1,162 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_TYPES_HPP -#define OPENCV_GAPI_TYPES_HPP - -#include // std::max, std::min -#include - -namespace cv -{ -namespace gapi -{ - -/** - * @brief This namespace contains G-API own data structures used in - * its standalone mode build. - */ -namespace own -{ - -class Point -{ -public: - Point() = default; - Point(int _x, int _y) : x(_x), y(_y) {} - - int x = 0; - int y = 0; -}; - -class Point2f -{ -public: - Point2f() = default; - Point2f(float _x, float _y) : x(_x), y(_y) {} - - float x = 0.f; - float y = 0.f; -}; - -class Point3f -{ -public: - Point3f() = default; - Point3f(float _x, float _y, float _z) : x(_x), y(_y), z(_z) {} - - float x = 0.f; - float y = 0.f; - float z = 0.f; -}; - -class Rect -{ -public: - Rect() = default; - Rect(int _x, int _y, int _width, int _height) : x(_x), y(_y), width(_width), height(_height) {} -#if !defined(GAPI_STANDALONE) - Rect(const cv::Rect& other) : x(other.x), y(other.y), width(other.width), height(other.height) {} - inline Rect& operator=(const cv::Rect& other) - { - x = other.x; - y = other.x; - width = other.width; - height = other.height; - return *this; - } -#endif // !defined(GAPI_STANDALONE) - - int x = 0; //!< x coordinate of the top-left corner - int y = 0; //!< y coordinate of the top-left corner - int width = 0; //!< width of the rectangle - int height = 0; //!< height of the rectangle -}; - -inline bool operator==(const Rect& lhs, const Rect& rhs) -{ - return lhs.x == rhs.x && lhs.y == rhs.y && lhs.width == rhs.width && lhs.height == rhs.height; -} - -inline bool operator!=(const Rect& lhs, const Rect& rhs) -{ - return !(lhs == rhs); -} - -inline Rect& operator&=(Rect& lhs, const Rect& rhs) -{ - int x1 = std::max(lhs.x, rhs.x); - int y1 = std::max(lhs.y, rhs.y); - lhs.width = std::min(lhs.x + lhs.width, rhs.x + rhs.width) - x1; - lhs.height = std::min(lhs.y + lhs.height, rhs.y + rhs.height) - y1; - lhs.x = x1; - lhs.y = y1; - if( lhs.width <= 0 || lhs.height <= 0 ) - lhs = Rect(); - return lhs; -} - -inline Rect operator&(const Rect& lhs, const Rect& rhs) -{ - Rect result = lhs; - return result &= rhs; -} - -inline std::ostream& operator<<(std::ostream& o, const Rect& rect) -{ - return o << "[" << rect.width << " x " << rect.height << " from (" << rect.x << ", " << rect.y << ")]"; -} - -class Size -{ -public: - Size() = default; - Size(int _width, int _height) : width(_width), height(_height) {} -#if !defined(GAPI_STANDALONE) - Size(const cv::Size& other) : width(other.width), height(other.height) {} - inline Size& operator=(const cv::Size& rhs) - { - width = rhs.width; - height = rhs.height; - return *this; - } -#endif // !defined(GAPI_STANDALONE) - - int width = 0; - int height = 0; -}; - -inline Size& operator+=(Size& lhs, const Size& rhs) -{ - lhs.width += rhs.width; - lhs.height += rhs.height; - return lhs; -} - -inline bool operator==(const Size& lhs, const Size& rhs) -{ - return lhs.width == rhs.width && lhs.height == rhs.height; -} - -inline bool operator!=(const Size& lhs, const Size& rhs) -{ - return !(lhs == rhs); -} - - -inline std::ostream& operator<<(std::ostream& o, const Size& s) -{ - o << "[" << s.width << " x " << s.height << "]"; - return o; -} - -struct VoidType {}; -} // namespace own -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_TYPES_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_TYPES_HPP +#define OPENCV_GAPI_TYPES_HPP + +#include // std::max, std::min +#include + +namespace cv +{ +namespace gapi +{ + +/** + * @brief This namespace contains G-API own data structures used in + * its standalone mode build. + */ +namespace own +{ + +class Point +{ +public: + Point() = default; + Point(int _x, int _y) : x(_x), y(_y) {} + + int x = 0; + int y = 0; +}; + +class Point2f +{ +public: + Point2f() = default; + Point2f(float _x, float _y) : x(_x), y(_y) {} + + float x = 0.f; + float y = 0.f; +}; + +class Point3f +{ +public: + Point3f() = default; + Point3f(float _x, float _y, float _z) : x(_x), y(_y), z(_z) {} + + float x = 0.f; + float y = 0.f; + float z = 0.f; +}; + +class Rect +{ +public: + Rect() = default; + Rect(int _x, int _y, int _width, int _height) : x(_x), y(_y), width(_width), height(_height) {} +#if !defined(GAPI_STANDALONE) + Rect(const cv::Rect& other) : x(other.x), y(other.y), width(other.width), height(other.height) {} + inline Rect& operator=(const cv::Rect& other) + { + x = other.x; + y = other.x; + width = other.width; + height = other.height; + return *this; + } +#endif // !defined(GAPI_STANDALONE) + + int x = 0; //!< x coordinate of the top-left corner + int y = 0; //!< y coordinate of the top-left corner + int width = 0; //!< width of the rectangle + int height = 0; //!< height of the rectangle +}; + +inline bool operator==(const Rect& lhs, const Rect& rhs) +{ + return lhs.x == rhs.x && lhs.y == rhs.y && lhs.width == rhs.width && lhs.height == rhs.height; +} + +inline bool operator!=(const Rect& lhs, const Rect& rhs) +{ + return !(lhs == rhs); +} + +inline Rect& operator&=(Rect& lhs, const Rect& rhs) +{ + int x1 = std::max(lhs.x, rhs.x); + int y1 = std::max(lhs.y, rhs.y); + lhs.width = std::min(lhs.x + lhs.width, rhs.x + rhs.width) - x1; + lhs.height = std::min(lhs.y + lhs.height, rhs.y + rhs.height) - y1; + lhs.x = x1; + lhs.y = y1; + if( lhs.width <= 0 || lhs.height <= 0 ) + lhs = Rect(); + return lhs; +} + +inline Rect operator&(const Rect& lhs, const Rect& rhs) +{ + Rect result = lhs; + return result &= rhs; +} + +inline std::ostream& operator<<(std::ostream& o, const Rect& rect) +{ + return o << "[" << rect.width << " x " << rect.height << " from (" << rect.x << ", " << rect.y << ")]"; +} + +class Size +{ +public: + Size() = default; + Size(int _width, int _height) : width(_width), height(_height) {} +#if !defined(GAPI_STANDALONE) + Size(const cv::Size& other) : width(other.width), height(other.height) {} + inline Size& operator=(const cv::Size& rhs) + { + width = rhs.width; + height = rhs.height; + return *this; + } +#endif // !defined(GAPI_STANDALONE) + + int width = 0; + int height = 0; +}; + +inline Size& operator+=(Size& lhs, const Size& rhs) +{ + lhs.width += rhs.width; + lhs.height += rhs.height; + return lhs; +} + +inline bool operator==(const Size& lhs, const Size& rhs) +{ + return lhs.width == rhs.width && lhs.height == rhs.height; +} + +inline bool operator!=(const Size& lhs, const Size& rhs) +{ + return !(lhs == rhs); +} + + +inline std::ostream& operator<<(std::ostream& o, const Size& s) +{ + o << "[" << s.width << " x " << s.height << "]"; + return o; +} + +struct VoidType {}; +} // namespace own +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_TYPES_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/plaidml/core.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/plaidml/core.hpp index 20e8812b3a..5a5ca46a0d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/plaidml/core.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/plaidml/core.hpp @@ -1,20 +1,20 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019 Intel Corporation - - -#ifndef OPENCV_GAPI_PLAIDML_CORE_HPP -#define OPENCV_GAPI_PLAIDML_CORE_HPP - -#include // GKernelPackage -#include // GAPI_EXPORTS - -namespace cv { namespace gapi { namespace core { namespace plaidml { - -GAPI_EXPORTS cv::GKernelPackage kernels(); - -}}}} - -#endif // OPENCV_GAPI_PLAIDML_CORE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019 Intel Corporation + + +#ifndef OPENCV_GAPI_PLAIDML_CORE_HPP +#define OPENCV_GAPI_PLAIDML_CORE_HPP + +#include // GKernelPackage +#include // GAPI_EXPORTS + +namespace cv { namespace gapi { namespace core { namespace plaidml { + +GAPI_EXPORTS cv::GKernelPackage kernels(); + +}}}} + +#endif // OPENCV_GAPI_PLAIDML_CORE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/plaidml/gplaidmlkernel.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/plaidml/gplaidmlkernel.hpp index e22ecc7211..f7e0c98e37 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/plaidml/gplaidmlkernel.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/plaidml/gplaidmlkernel.hpp @@ -1,140 +1,140 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019 Intel Corporation -// - - -#ifndef OPENCV_GAPI_GPLAIDMLKERNEL_HPP -#define OPENCV_GAPI_GPLAIDMLKERNEL_HPP - -#include -#include - -namespace plaidml -{ -namespace edsl -{ - class Tensor; -} // namespace edsl -} // namespace plaidml - -namespace cv -{ -namespace gapi -{ -namespace plaidml -{ - -GAPI_EXPORTS cv::gapi::GBackend backend(); - -} // namespace plaidml -} // namespace gapi - -struct GPlaidMLContext -{ - // Generic accessor API - template - const T& inArg(int input) { return m_args.at(input).get(); } - - // Syntax sugar - const plaidml::edsl::Tensor& inTensor(int input) - { - return inArg(input); - } - - plaidml::edsl::Tensor& outTensor(int output) - { - return *(m_results.at(output).get()); - } - - std::vector m_args; - std::unordered_map m_results; -}; - -class GAPI_EXPORTS GPlaidMLKernel -{ -public: - using F = std::function; - - GPlaidMLKernel() = default; - explicit GPlaidMLKernel(const F& f) : m_f(f) {} - - void apply(GPlaidMLContext &ctx) const - { - GAPI_Assert(m_f); - m_f(ctx); - } - -protected: - F m_f; -}; - - -namespace detail -{ - -template struct plaidml_get_in; -template<> struct plaidml_get_in -{ - static const plaidml::edsl::Tensor& get(GPlaidMLContext& ctx, int idx) - { - return ctx.inTensor(idx); - } -}; - -template struct plaidml_get_in -{ - static T get(GPlaidMLContext &ctx, int idx) { return ctx.inArg(idx); } -}; - -template struct plaidml_get_out; -template<> struct plaidml_get_out -{ - static plaidml::edsl::Tensor& get(GPlaidMLContext& ctx, int idx) - { - return ctx.outTensor(idx); - } -}; - -template -struct PlaidMLCallHelper; - -template -struct PlaidMLCallHelper, std::tuple > -{ - template - static void call_impl(GPlaidMLContext &ctx, detail::Seq, detail::Seq) - { - Impl::run(plaidml_get_in::get(ctx, IIs)..., plaidml_get_out::get(ctx, OIs)...); - } - - static void call(GPlaidMLContext& ctx) - { - call_impl(ctx, - typename detail::MkSeq::type(), - typename detail::MkSeq::type()); - } -}; - -} // namespace detail - -template -class GPlaidMLKernelImpl: public cv::detail::PlaidMLCallHelper, - public cv::detail::KernelTag -{ - using P = detail::PlaidMLCallHelper; - -public: - using API = K; - - static cv::gapi::GBackend backend() { return cv::gapi::plaidml::backend(); } - static cv::GPlaidMLKernel kernel() { return GPlaidMLKernel(&P::call); } -}; - -#define GAPI_PLAIDML_KERNEL(Name, API) struct Name: public cv::GPlaidMLKernelImpl - -} // namespace cv - -#endif // OPENCV_GAPI_GPLAIDMLKERNEL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019 Intel Corporation +// + + +#ifndef OPENCV_GAPI_GPLAIDMLKERNEL_HPP +#define OPENCV_GAPI_GPLAIDMLKERNEL_HPP + +#include +#include + +namespace plaidml +{ +namespace edsl +{ + class Tensor; +} // namespace edsl +} // namespace plaidml + +namespace cv +{ +namespace gapi +{ +namespace plaidml +{ + +GAPI_EXPORTS cv::gapi::GBackend backend(); + +} // namespace plaidml +} // namespace gapi + +struct GPlaidMLContext +{ + // Generic accessor API + template + const T& inArg(int input) { return m_args.at(input).get(); } + + // Syntax sugar + const plaidml::edsl::Tensor& inTensor(int input) + { + return inArg(input); + } + + plaidml::edsl::Tensor& outTensor(int output) + { + return *(m_results.at(output).get()); + } + + std::vector m_args; + std::unordered_map m_results; +}; + +class GAPI_EXPORTS GPlaidMLKernel +{ +public: + using F = std::function; + + GPlaidMLKernel() = default; + explicit GPlaidMLKernel(const F& f) : m_f(f) {} + + void apply(GPlaidMLContext &ctx) const + { + GAPI_Assert(m_f); + m_f(ctx); + } + +protected: + F m_f; +}; + + +namespace detail +{ + +template struct plaidml_get_in; +template<> struct plaidml_get_in +{ + static const plaidml::edsl::Tensor& get(GPlaidMLContext& ctx, int idx) + { + return ctx.inTensor(idx); + } +}; + +template struct plaidml_get_in +{ + static T get(GPlaidMLContext &ctx, int idx) { return ctx.inArg(idx); } +}; + +template struct plaidml_get_out; +template<> struct plaidml_get_out +{ + static plaidml::edsl::Tensor& get(GPlaidMLContext& ctx, int idx) + { + return ctx.outTensor(idx); + } +}; + +template +struct PlaidMLCallHelper; + +template +struct PlaidMLCallHelper, std::tuple > +{ + template + static void call_impl(GPlaidMLContext &ctx, detail::Seq, detail::Seq) + { + Impl::run(plaidml_get_in::get(ctx, IIs)..., plaidml_get_out::get(ctx, OIs)...); + } + + static void call(GPlaidMLContext& ctx) + { + call_impl(ctx, + typename detail::MkSeq::type(), + typename detail::MkSeq::type()); + } +}; + +} // namespace detail + +template +class GPlaidMLKernelImpl: public cv::detail::PlaidMLCallHelper, + public cv::detail::KernelTag +{ + using P = detail::PlaidMLCallHelper; + +public: + using API = K; + + static cv::gapi::GBackend backend() { return cv::gapi::plaidml::backend(); } + static cv::GPlaidMLKernel kernel() { return GPlaidMLKernel(&P::call); } +}; + +#define GAPI_PLAIDML_KERNEL(Name, API) struct Name: public cv::GPlaidMLKernelImpl + +} // namespace cv + +#endif // OPENCV_GAPI_GPLAIDMLKERNEL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/plaidml/plaidml.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/plaidml/plaidml.hpp index 3207a8cb2e..67f7a59e7d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/plaidml/plaidml.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/plaidml/plaidml.hpp @@ -1,53 +1,53 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019 Intel Corporation - - -#ifndef OPENCV_GAPI_PLAIDML_PLAIDML_HPP -#define OPENCV_GAPI_PLAIDML_PLAIDML_HPP - -#include -#include // CompileArgTag - -namespace cv -{ -namespace gapi -{ - -/** - * @brief This namespace contains G-API PlaidML backend functions, - * structures, and symbols. - */ -namespace plaidml -{ - -/** \addtogroup gapi_compile_args - * @{ - */ -/** - * @brief This structure represents the basic parameters for the experimental - * PlaidML backend. - */ -struct config -{ - std::string dev_id; //!< Device ID. Refer to PlaidML documentation for details. - std::string trg_id; //!< Target ID. Refer to PlaidML documentation for details. -}; -/** @} gapi_compile_args */ - -} // namespace plaidml -} // namespace gapi - -namespace detail -{ - template<> struct CompileArgTag - { - static const char* tag() { return "gapi.plaidml.config"; } - }; -} // namespace detail - -} // namespace cv - -#endif // OPENCV_GAPI_PLAIDML_PLAIDML_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019 Intel Corporation + + +#ifndef OPENCV_GAPI_PLAIDML_PLAIDML_HPP +#define OPENCV_GAPI_PLAIDML_PLAIDML_HPP + +#include +#include // CompileArgTag + +namespace cv +{ +namespace gapi +{ + +/** + * @brief This namespace contains G-API PlaidML backend functions, + * structures, and symbols. + */ +namespace plaidml +{ + +/** \addtogroup gapi_compile_args + * @{ + */ +/** + * @brief This structure represents the basic parameters for the experimental + * PlaidML backend. + */ +struct config +{ + std::string dev_id; //!< Device ID. Refer to PlaidML documentation for details. + std::string trg_id; //!< Target ID. Refer to PlaidML documentation for details. +}; +/** @} gapi_compile_args */ + +} // namespace plaidml +} // namespace gapi + +namespace detail +{ + template<> struct CompileArgTag + { + static const char* tag() { return "gapi.plaidml.config"; } + }; +} // namespace detail + +} // namespace cv + +#endif // OPENCV_GAPI_PLAIDML_PLAIDML_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/python/python.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/python/python.hpp index 1857a938d5..00d15f849c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/python/python.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/python/python.hpp @@ -1,71 +1,71 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2021 Intel Corporation - - -#ifndef OPENCV_GAPI_PYTHON_API_HPP -#define OPENCV_GAPI_PYTHON_API_HPP - -#include // GKernelPackage -#include // GAPI_EXPORTS - -namespace cv { -namespace gapi { - -/** - * @brief This namespace contains G-API Python backend functions, - * structures, and symbols. - * - * This functionality is required to enable G-API custom operations - * and kernels when using G-API from Python, no need to use it in the - * C++ form. - */ -namespace python { - -GAPI_EXPORTS cv::gapi::GBackend backend(); - -struct GPythonContext -{ - const cv::GArgs &ins; - const cv::GMetaArgs &in_metas; - const cv::GTypesInfo &out_info; - - cv::optional m_state; -}; - -using Impl = std::function; -using Setup = std::function; - -class GAPI_EXPORTS GPythonKernel -{ -public: - GPythonKernel() = default; - GPythonKernel(Impl run, Setup setup); - - Impl run; - Setup setup = nullptr; - bool is_stateful = false; -}; - -class GAPI_EXPORTS GPythonFunctor : public cv::gapi::GFunctor -{ -public: - using Meta = cv::GKernel::M; - - GPythonFunctor(const char* id, const Meta& meta, const Impl& impl, - const Setup& setup = nullptr); - - GKernelImpl impl() const override; - gapi::GBackend backend() const override; - -private: - GKernelImpl impl_; -}; - -} // namespace python -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_PYTHON_API_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2021 Intel Corporation + + +#ifndef OPENCV_GAPI_PYTHON_API_HPP +#define OPENCV_GAPI_PYTHON_API_HPP + +#include // GKernelPackage +#include // GAPI_EXPORTS + +namespace cv { +namespace gapi { + +/** + * @brief This namespace contains G-API Python backend functions, + * structures, and symbols. + * + * This functionality is required to enable G-API custom operations + * and kernels when using G-API from Python, no need to use it in the + * C++ form. + */ +namespace python { + +GAPI_EXPORTS cv::gapi::GBackend backend(); + +struct GPythonContext +{ + const cv::GArgs &ins; + const cv::GMetaArgs &in_metas; + const cv::GTypesInfo &out_info; + + cv::optional m_state; +}; + +using Impl = std::function; +using Setup = std::function; + +class GAPI_EXPORTS GPythonKernel +{ +public: + GPythonKernel() = default; + GPythonKernel(Impl run, Setup setup); + + Impl run; + Setup setup = nullptr; + bool is_stateful = false; +}; + +class GAPI_EXPORTS GPythonFunctor : public cv::gapi::GFunctor +{ +public: + using Meta = cv::GKernel::M; + + GPythonFunctor(const char* id, const Meta& meta, const Impl& impl, + const Setup& setup = nullptr); + + GKernelImpl impl() const override; + gapi::GBackend backend() const override; + +private: + GKernelImpl impl_; +}; + +} // namespace python +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_PYTHON_API_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/render.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/render.hpp index 52e55b0d80..8360e30698 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/render.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/render.hpp @@ -1,14 +1,14 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019 Intel Corporation - -#ifndef OPENCV_GAPI_RENDER_ROOT_HPP -#define OPENCV_GAPI_RENDER_ROOT_HPP - -// This file is just a shortcut to render/render.hpp - -#include - -#endif // OPENCV_GAPI_RENDER_ROOT_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019 Intel Corporation + +#ifndef OPENCV_GAPI_RENDER_ROOT_HPP +#define OPENCV_GAPI_RENDER_ROOT_HPP + +// This file is just a shortcut to render/render.hpp + +#include + +#endif // OPENCV_GAPI_RENDER_ROOT_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/render/render.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/render/render.hpp index 8d93a6efc0..5da8d80244 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/render/render.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/render/render.hpp @@ -1,196 +1,196 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2020 Intel Corporation - - -#ifndef OPENCV_GAPI_RENDER_HPP -#define OPENCV_GAPI_RENDER_HPP - -#include - -#include - -/** \defgroup gapi_draw G-API Drawing and composition functionality - * @{ - * - * @brief Functions for in-graph drawing. - * - * @note This is a Work in Progress functionality and APIs may - * change in the future releases. - * - * G-API can do some in-graph drawing with a generic operations and a - * set of [rendering primitives](@ref gapi_draw_prims). - * In contrast with traditional OpenCV, in G-API user need to form a - * *rendering list* of primitives to draw. This list can be built - * manually or generated within a graph. This list is passed to - * [special operations or functions](@ref gapi_draw_api) where all - * primitives are interpreted and applied to the image. - * - * For example, in a complex pipeline a list of detected objects - * can be translated in-graph to a list of cv::gapi::wip::draw::Rect - * primitives to highlight those with bounding boxes, or a list of - * detected faces can be translated in-graph to a list of - * cv::gapi::wip::draw::Mosaic primitives to hide sensitive content - * or protect privacy. - * - * Like any other operations, rendering in G-API can be reimplemented - * by different backends. Currently only an OpenCV-based backend is - * available. - * - * In addition to the graph-level operations, there are also regular - * (immediate) OpenCV-like functions are available -- see - * cv::gapi::wip::draw::render(). These functions are just wrappers - * over regular G-API and build the rendering graphs on the fly, so - * take compilation arguments as parameters. - * - * Currently this API is more machine-oriented than human-oriented. - * The main purpose is to translate a set of domain-specific objects - * to a list of primitives to draw. For example, in order to generate - * a picture like this: - * - * ![](modules/gapi/doc/pics/render_example.png) - * - * Rendering list needs to be generated as follows: - * - * @include modules/gapi/samples/draw_example.cpp - * - * @defgroup gapi_draw_prims Drawing primitives - * @defgroup gapi_draw_api Drawing operations and functions - * @} - */ - -namespace cv -{ -namespace gapi -{ -namespace wip -{ -namespace draw -{ - -using GMat2 = std::tuple; -using GMatDesc2 = std::tuple; - -//! @addtogroup gapi_draw_api -//! @{ -/** @brief The function renders on the input image passed drawing primitivies - -@param bgr input image: 8-bit unsigned 3-channel image @ref CV_8UC3. -@param prims vector of drawing primitivies -@param args graph compile time parameters -*/ -void GAPI_EXPORTS_W render(cv::Mat& bgr, - const Prims& prims, - cv::GCompileArgs&& args = {}); - -/** @brief The function renders on two NV12 planes passed drawing primitivies - -@param y_plane input image: 8-bit unsigned 1-channel image @ref CV_8UC1. -@param uv_plane input image: 8-bit unsigned 2-channel image @ref CV_8UC2. -@param prims vector of drawing primitivies -@param args graph compile time parameters -*/ -void GAPI_EXPORTS_W render(cv::Mat& y_plane, - cv::Mat& uv_plane, - const Prims& prims, - cv::GCompileArgs&& args = {}); - -/** @brief The function renders on the input media frame passed drawing primitivies - -@param frame input Media Frame : @ref cv::MediaFrame. -@param prims vector of drawing primitivies -@param args graph compile time parameters -*/ -void GAPI_EXPORTS render(cv::MediaFrame& frame, - const Prims& prims, - cv::GCompileArgs&& args = {}); - - -G_TYPED_KERNEL_M(GRenderNV12, )>, "org.opencv.render.nv12") -{ - static GMatDesc2 outMeta(GMatDesc y_plane, GMatDesc uv_plane, GArrayDesc) - { - return std::make_tuple(y_plane, uv_plane); - } -}; - -G_TYPED_KERNEL(GRenderBGR, )>, "org.opencv.render.bgr") -{ - static GMatDesc outMeta(GMatDesc bgr, GArrayDesc) - { - return bgr; - } -}; - -G_TYPED_KERNEL(GRenderFrame, )>, "org.opencv.render.frame") -{ - static GFrameDesc outMeta(GFrameDesc desc, GArrayDesc) - { - return desc; - } -}; - -/** @brief Renders on 3 channels input - -Output image must be 8-bit unsigned planar 3-channel image - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3 -@param prims draw primitives -*/ -GAPI_EXPORTS_W GMat render3ch(const GMat& src, const GArray& prims); - -/** @brief Renders on two planes - -Output y image must be 8-bit unsigned planar 1-channel image @ref CV_8UC1 -uv image must be 8-bit unsigned planar 2-channel image @ref CV_8UC2 - -@param y input image: 8-bit unsigned 1-channel image @ref CV_8UC1 -@param uv input image: 8-bit unsigned 2-channel image @ref CV_8UC2 -@param prims draw primitives -*/ -GAPI_EXPORTS_W GMat2 renderNV12(const GMat& y, - const GMat& uv, - const GArray& prims); - -/** @brief Renders Media Frame - -Output media frame frame cv::MediaFrame - -@param m_frame input image: cv::MediaFrame @ref cv::MediaFrame -@param prims draw primitives -*/ -GAPI_EXPORTS GFrame renderFrame(const GFrame& m_frame, - const GArray& prims); - -//! @} gapi_draw_api - -} // namespace draw -} // namespace wip - -/** - * @brief This namespace contains G-API CPU rendering backend functions, - * structures, and symbols. See @ref gapi_draw for details. - */ -namespace render -{ -namespace ocv -{ - GAPI_EXPORTS_W cv::GKernelPackage kernels(); - -} // namespace ocv -} // namespace render -} // namespace gapi - -namespace detail -{ - template<> struct CompileArgTag - { - static const char* tag() { return "gapi.freetype_font"; } - }; -} // namespace detail - -} // namespace cv - -#endif // OPENCV_GAPI_RENDER_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2020 Intel Corporation + + +#ifndef OPENCV_GAPI_RENDER_HPP +#define OPENCV_GAPI_RENDER_HPP + +#include + +#include + +/** \defgroup gapi_draw G-API Drawing and composition functionality + * @{ + * + * @brief Functions for in-graph drawing. + * + * @note This is a Work in Progress functionality and APIs may + * change in the future releases. + * + * G-API can do some in-graph drawing with a generic operations and a + * set of [rendering primitives](@ref gapi_draw_prims). + * In contrast with traditional OpenCV, in G-API user need to form a + * *rendering list* of primitives to draw. This list can be built + * manually or generated within a graph. This list is passed to + * [special operations or functions](@ref gapi_draw_api) where all + * primitives are interpreted and applied to the image. + * + * For example, in a complex pipeline a list of detected objects + * can be translated in-graph to a list of cv::gapi::wip::draw::Rect + * primitives to highlight those with bounding boxes, or a list of + * detected faces can be translated in-graph to a list of + * cv::gapi::wip::draw::Mosaic primitives to hide sensitive content + * or protect privacy. + * + * Like any other operations, rendering in G-API can be reimplemented + * by different backends. Currently only an OpenCV-based backend is + * available. + * + * In addition to the graph-level operations, there are also regular + * (immediate) OpenCV-like functions are available -- see + * cv::gapi::wip::draw::render(). These functions are just wrappers + * over regular G-API and build the rendering graphs on the fly, so + * take compilation arguments as parameters. + * + * Currently this API is more machine-oriented than human-oriented. + * The main purpose is to translate a set of domain-specific objects + * to a list of primitives to draw. For example, in order to generate + * a picture like this: + * + * ![](modules/gapi/doc/pics/render_example.png) + * + * Rendering list needs to be generated as follows: + * + * @include modules/gapi/samples/draw_example.cpp + * + * @defgroup gapi_draw_prims Drawing primitives + * @defgroup gapi_draw_api Drawing operations and functions + * @} + */ + +namespace cv +{ +namespace gapi +{ +namespace wip +{ +namespace draw +{ + +using GMat2 = std::tuple; +using GMatDesc2 = std::tuple; + +//! @addtogroup gapi_draw_api +//! @{ +/** @brief The function renders on the input image passed drawing primitivies + +@param bgr input image: 8-bit unsigned 3-channel image @ref CV_8UC3. +@param prims vector of drawing primitivies +@param args graph compile time parameters +*/ +void GAPI_EXPORTS_W render(cv::Mat& bgr, + const Prims& prims, + cv::GCompileArgs&& args = {}); + +/** @brief The function renders on two NV12 planes passed drawing primitivies + +@param y_plane input image: 8-bit unsigned 1-channel image @ref CV_8UC1. +@param uv_plane input image: 8-bit unsigned 2-channel image @ref CV_8UC2. +@param prims vector of drawing primitivies +@param args graph compile time parameters +*/ +void GAPI_EXPORTS_W render(cv::Mat& y_plane, + cv::Mat& uv_plane, + const Prims& prims, + cv::GCompileArgs&& args = {}); + +/** @brief The function renders on the input media frame passed drawing primitivies + +@param frame input Media Frame : @ref cv::MediaFrame. +@param prims vector of drawing primitivies +@param args graph compile time parameters +*/ +void GAPI_EXPORTS render(cv::MediaFrame& frame, + const Prims& prims, + cv::GCompileArgs&& args = {}); + + +G_TYPED_KERNEL_M(GRenderNV12, )>, "org.opencv.render.nv12") +{ + static GMatDesc2 outMeta(GMatDesc y_plane, GMatDesc uv_plane, GArrayDesc) + { + return std::make_tuple(y_plane, uv_plane); + } +}; + +G_TYPED_KERNEL(GRenderBGR, )>, "org.opencv.render.bgr") +{ + static GMatDesc outMeta(GMatDesc bgr, GArrayDesc) + { + return bgr; + } +}; + +G_TYPED_KERNEL(GRenderFrame, )>, "org.opencv.render.frame") +{ + static GFrameDesc outMeta(GFrameDesc desc, GArrayDesc) + { + return desc; + } +}; + +/** @brief Renders on 3 channels input + +Output image must be 8-bit unsigned planar 3-channel image + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3 +@param prims draw primitives +*/ +GAPI_EXPORTS_W GMat render3ch(const GMat& src, const GArray& prims); + +/** @brief Renders on two planes + +Output y image must be 8-bit unsigned planar 1-channel image @ref CV_8UC1 +uv image must be 8-bit unsigned planar 2-channel image @ref CV_8UC2 + +@param y input image: 8-bit unsigned 1-channel image @ref CV_8UC1 +@param uv input image: 8-bit unsigned 2-channel image @ref CV_8UC2 +@param prims draw primitives +*/ +GAPI_EXPORTS_W GMat2 renderNV12(const GMat& y, + const GMat& uv, + const GArray& prims); + +/** @brief Renders Media Frame + +Output media frame frame cv::MediaFrame + +@param m_frame input image: cv::MediaFrame @ref cv::MediaFrame +@param prims draw primitives +*/ +GAPI_EXPORTS GFrame renderFrame(const GFrame& m_frame, + const GArray& prims); + +//! @} gapi_draw_api + +} // namespace draw +} // namespace wip + +/** + * @brief This namespace contains G-API CPU rendering backend functions, + * structures, and symbols. See @ref gapi_draw for details. + */ +namespace render +{ +namespace ocv +{ + GAPI_EXPORTS_W cv::GKernelPackage kernels(); + +} // namespace ocv +} // namespace render +} // namespace gapi + +namespace detail +{ + template<> struct CompileArgTag + { + static const char* tag() { return "gapi.freetype_font"; } + }; +} // namespace detail + +} // namespace cv + +#endif // OPENCV_GAPI_RENDER_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/render/render_types.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/render/render_types.hpp index 6d70e3a877..e892fd2652 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/render/render_types.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/render/render_types.hpp @@ -1,359 +1,359 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020 Intel Corporation - - -#ifndef OPENCV_GAPI_RENDER_TYPES_HPP -#define OPENCV_GAPI_RENDER_TYPES_HPP - -#include -#include - -#include -#include -#include - -namespace cv -{ -namespace gapi -{ -namespace wip -{ -namespace draw -{ - -/** - * @brief This structure specifies which FreeType font to use by FText primitives. - */ -struct freetype_font -{ - /*@{*/ - std::string path; //!< The path to the font file (.ttf) - /*@{*/ -}; - -//! @addtogroup gapi_draw_prims -//! @{ -/** - * @brief This structure represents a text string to draw. - * - * Parameters match cv::putText(). - */ -struct GAPI_EXPORTS_W_SIMPLE Text -{ - /** - * @brief Text constructor - * - * @param text_ The text string to be drawn - * @param org_ The bottom-left corner of the text string in the image - * @param ff_ The font type, see #HersheyFonts - * @param fs_ The font scale factor that is multiplied by the font-specific base size - * @param color_ The text color - * @param thick_ The thickness of the lines used to draw a text - * @param lt_ The line type. See #LineTypes - * @param bottom_left_origin_ When true, the image data origin is at the bottom-left corner. Otherwise, it is at the top-left corner - */ - GAPI_WRAP - Text(const std::string& text_, - const cv::Point& org_, - int ff_, - double fs_, - const cv::Scalar& color_, - int thick_ = 1, - int lt_ = 8, - bool bottom_left_origin_ = false) : - text(text_), org(org_), ff(ff_), fs(fs_), - color(color_), thick(thick_), lt(lt_), bottom_left_origin(bottom_left_origin_) - { - } - - GAPI_WRAP - Text() = default; - - /*@{*/ - GAPI_PROP_RW std::string text; //!< The text string to be drawn - GAPI_PROP_RW cv::Point org; //!< The bottom-left corner of the text string in the image - GAPI_PROP_RW int ff; //!< The font type, see #HersheyFonts - GAPI_PROP_RW double fs; //!< The font scale factor that is multiplied by the font-specific base size - GAPI_PROP_RW cv::Scalar color; //!< The text color - GAPI_PROP_RW int thick; //!< The thickness of the lines used to draw a text - GAPI_PROP_RW int lt; //!< The line type. See #LineTypes - GAPI_PROP_RW bool bottom_left_origin; //!< When true, the image data origin is at the bottom-left corner. Otherwise, it is at the top-left corner - /*@{*/ -}; - -/** - * @brief This structure represents a text string to draw using - * FreeType renderer. - * - * If OpenCV is built without FreeType support, this primitive will - * fail at the execution stage. - */ -struct FText -{ - /** - * @brief FText constructor - * - * @param text_ The text string to be drawn - * @param org_ The bottom-left corner of the text string in the image - * @param fh_ The height of text - * @param color_ The text color - */ - FText(const std::wstring& text_, - const cv::Point& org_, - int fh_, - const cv::Scalar& color_) : - text(text_), org(org_), fh(fh_), color(color_) - { - } - - FText() = default; - - /*@{*/ - std::wstring text; //!< The text string to be drawn - cv::Point org; //!< The bottom-left corner of the text string in the image - int fh; //!< The height of text - cv::Scalar color; //!< The text color - /*@{*/ -}; - -/** - * @brief This structure represents a rectangle to draw. - * - * Parameters match cv::rectangle(). - */ -struct GAPI_EXPORTS_W_SIMPLE Rect -{ - /** - * @brief Rect constructor - * - * @param rect_ Coordinates of the rectangle - * @param color_ The bottom-left corner of the text string in the image - * @param thick_ The thickness of lines that make up the rectangle. Negative values, like #FILLED, mean that the function has to draw a filled rectangle - * @param lt_ The type of the line. See #LineTypes - * @param shift_ The number of fractional bits in the point coordinates - */ - Rect(const cv::Rect& rect_, - const cv::Scalar& color_, - int thick_ = 1, - int lt_ = 8, - int shift_ = 0) : - rect(rect_), color(color_), thick(thick_), lt(lt_), shift(shift_) - { - } - - GAPI_WRAP - Rect() = default; - - /*@{*/ - GAPI_PROP_RW cv::Rect rect; //!< Coordinates of the rectangle - GAPI_PROP_RW cv::Scalar color; //!< The rectangle color or brightness (grayscale image) - GAPI_PROP_RW int thick; //!< The thickness of lines that make up the rectangle. Negative values, like #FILLED, mean that the function has to draw a filled rectangle - GAPI_PROP_RW int lt; //!< The type of the line. See #LineTypes - GAPI_PROP_RW int shift; //!< The number of fractional bits in the point coordinates - /*@{*/ -}; - -/** - * @brief This structure represents a circle to draw. - * - * Parameters match cv::circle(). - */ -struct GAPI_EXPORTS_W_SIMPLE Circle -{ - /** - * @brief Circle constructor - * - * @param center_ The center of the circle - * @param radius_ The radius of the circle - * @param color_ The color of the circle - * @param thick_ The thickness of the circle outline, if positive. Negative values, like #FILLED, mean that a filled circle is to be drawn - * @param lt_ The Type of the circle boundary. See #LineTypes - * @param shift_ The Number of fractional bits in the coordinates of the center and in the radius value - */ - GAPI_WRAP - Circle(const cv::Point& center_, - int radius_, - const cv::Scalar& color_, - int thick_ = 1, - int lt_ = 8, - int shift_ = 0) : - center(center_), radius(radius_), color(color_), thick(thick_), lt(lt_), shift(shift_) - { - } - - GAPI_WRAP - Circle() = default; - - /*@{*/ - GAPI_PROP_RW cv::Point center; //!< The center of the circle - GAPI_PROP_RW int radius; //!< The radius of the circle - GAPI_PROP_RW cv::Scalar color; //!< The color of the circle - GAPI_PROP_RW int thick; //!< The thickness of the circle outline, if positive. Negative values, like #FILLED, mean that a filled circle is to be drawn - GAPI_PROP_RW int lt; //!< The Type of the circle boundary. See #LineTypes - GAPI_PROP_RW int shift; //!< The Number of fractional bits in the coordinates of the center and in the radius value - /*@{*/ -}; - -/** - * @brief This structure represents a line to draw. - * - * Parameters match cv::line(). - */ -struct GAPI_EXPORTS_W_SIMPLE Line -{ - /** - * @brief Line constructor - * - * @param pt1_ The first point of the line segment - * @param pt2_ The second point of the line segment - * @param color_ The line color - * @param thick_ The thickness of line - * @param lt_ The Type of the line. See #LineTypes - * @param shift_ The number of fractional bits in the point coordinates - */ - GAPI_WRAP - Line(const cv::Point& pt1_, - const cv::Point& pt2_, - const cv::Scalar& color_, - int thick_ = 1, - int lt_ = 8, - int shift_ = 0) : - pt1(pt1_), pt2(pt2_), color(color_), thick(thick_), lt(lt_), shift(shift_) - { - } - - GAPI_WRAP - Line() = default; - - /*@{*/ - GAPI_PROP_RW cv::Point pt1; //!< The first point of the line segment - GAPI_PROP_RW cv::Point pt2; //!< The second point of the line segment - GAPI_PROP_RW cv::Scalar color; //!< The line color - GAPI_PROP_RW int thick; //!< The thickness of line - GAPI_PROP_RW int lt; //!< The Type of the line. See #LineTypes - GAPI_PROP_RW int shift; //!< The number of fractional bits in the point coordinates - /*@{*/ -}; - -/** - * @brief This structure represents a mosaicing operation. - * - * Mosaicing is a very basic method to obfuscate regions in the image. - */ -struct GAPI_EXPORTS_W_SIMPLE Mosaic -{ - /** - * @brief Mosaic constructor - * - * @param mos_ Coordinates of the mosaic - * @param cellSz_ Cell size (same for X, Y) - * @param decim_ Decimation (0 stands for no decimation) - */ - Mosaic(const cv::Rect& mos_, - int cellSz_, - int decim_) : - mos(mos_), cellSz(cellSz_), decim(decim_) - { - } - - GAPI_WRAP - Mosaic() : cellSz(0), decim(0) {} - - /*@{*/ - GAPI_PROP_RW cv::Rect mos; //!< Coordinates of the mosaic - GAPI_PROP_RW int cellSz; //!< Cell size (same for X, Y) - GAPI_PROP_RW int decim; //!< Decimation (0 stands for no decimation) - /*@{*/ -}; - -/** - * @brief This structure represents an image to draw. - * - * Image is blended on a frame using the specified mask. - */ -struct GAPI_EXPORTS_W_SIMPLE Image -{ - /** - * @brief Mosaic constructor - * - * @param org_ The bottom-left corner of the image - * @param img_ Image to draw - * @param alpha_ Alpha channel for image to draw (same size and number of channels) - */ - GAPI_WRAP - Image(const cv::Point& org_, - const cv::Mat& img_, - const cv::Mat& alpha_) : - org(org_), img(img_), alpha(alpha_) - { - } - - GAPI_WRAP - Image() = default; - - /*@{*/ - GAPI_PROP_RW cv::Point org; //!< The bottom-left corner of the image - GAPI_PROP_RW cv::Mat img; //!< Image to draw - GAPI_PROP_RW cv::Mat alpha; //!< Alpha channel for image to draw (same size and number of channels) - /*@{*/ -}; - -/** - * @brief This structure represents a polygon to draw. - */ -struct GAPI_EXPORTS_W_SIMPLE Poly -{ - /** - * @brief Mosaic constructor - * - * @param points_ Points to connect - * @param color_ The line color - * @param thick_ The thickness of line - * @param lt_ The Type of the line. See #LineTypes - * @param shift_ The number of fractional bits in the point coordinate - */ - GAPI_WRAP - Poly(const std::vector& points_, - const cv::Scalar& color_, - int thick_ = 1, - int lt_ = 8, - int shift_ = 0) : - points(points_), color(color_), thick(thick_), lt(lt_), shift(shift_) - { - } - - GAPI_WRAP - Poly() = default; - - /*@{*/ - GAPI_PROP_RW std::vector points; //!< Points to connect - GAPI_PROP_RW cv::Scalar color; //!< The line color - GAPI_PROP_RW int thick; //!< The thickness of line - GAPI_PROP_RW int lt; //!< The Type of the line. See #LineTypes - GAPI_PROP_RW int shift; //!< The number of fractional bits in the point coordinate - /*@{*/ -}; - -using Prim = util::variant - < Text - , FText - , Rect - , Circle - , Line - , Mosaic - , Image - , Poly - >; - -using Prims = std::vector; -//! @} gapi_draw_prims - -} // namespace draw -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_RENDER_TYPES_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020 Intel Corporation + + +#ifndef OPENCV_GAPI_RENDER_TYPES_HPP +#define OPENCV_GAPI_RENDER_TYPES_HPP + +#include +#include + +#include +#include +#include + +namespace cv +{ +namespace gapi +{ +namespace wip +{ +namespace draw +{ + +/** + * @brief This structure specifies which FreeType font to use by FText primitives. + */ +struct freetype_font +{ + /*@{*/ + std::string path; //!< The path to the font file (.ttf) + /*@{*/ +}; + +//! @addtogroup gapi_draw_prims +//! @{ +/** + * @brief This structure represents a text string to draw. + * + * Parameters match cv::putText(). + */ +struct GAPI_EXPORTS_W_SIMPLE Text +{ + /** + * @brief Text constructor + * + * @param text_ The text string to be drawn + * @param org_ The bottom-left corner of the text string in the image + * @param ff_ The font type, see #HersheyFonts + * @param fs_ The font scale factor that is multiplied by the font-specific base size + * @param color_ The text color + * @param thick_ The thickness of the lines used to draw a text + * @param lt_ The line type. See #LineTypes + * @param bottom_left_origin_ When true, the image data origin is at the bottom-left corner. Otherwise, it is at the top-left corner + */ + GAPI_WRAP + Text(const std::string& text_, + const cv::Point& org_, + int ff_, + double fs_, + const cv::Scalar& color_, + int thick_ = 1, + int lt_ = 8, + bool bottom_left_origin_ = false) : + text(text_), org(org_), ff(ff_), fs(fs_), + color(color_), thick(thick_), lt(lt_), bottom_left_origin(bottom_left_origin_) + { + } + + GAPI_WRAP + Text() = default; + + /*@{*/ + GAPI_PROP_RW std::string text; //!< The text string to be drawn + GAPI_PROP_RW cv::Point org; //!< The bottom-left corner of the text string in the image + GAPI_PROP_RW int ff; //!< The font type, see #HersheyFonts + GAPI_PROP_RW double fs; //!< The font scale factor that is multiplied by the font-specific base size + GAPI_PROP_RW cv::Scalar color; //!< The text color + GAPI_PROP_RW int thick; //!< The thickness of the lines used to draw a text + GAPI_PROP_RW int lt; //!< The line type. See #LineTypes + GAPI_PROP_RW bool bottom_left_origin; //!< When true, the image data origin is at the bottom-left corner. Otherwise, it is at the top-left corner + /*@{*/ +}; + +/** + * @brief This structure represents a text string to draw using + * FreeType renderer. + * + * If OpenCV is built without FreeType support, this primitive will + * fail at the execution stage. + */ +struct FText +{ + /** + * @brief FText constructor + * + * @param text_ The text string to be drawn + * @param org_ The bottom-left corner of the text string in the image + * @param fh_ The height of text + * @param color_ The text color + */ + FText(const std::wstring& text_, + const cv::Point& org_, + int fh_, + const cv::Scalar& color_) : + text(text_), org(org_), fh(fh_), color(color_) + { + } + + FText() = default; + + /*@{*/ + std::wstring text; //!< The text string to be drawn + cv::Point org; //!< The bottom-left corner of the text string in the image + int fh; //!< The height of text + cv::Scalar color; //!< The text color + /*@{*/ +}; + +/** + * @brief This structure represents a rectangle to draw. + * + * Parameters match cv::rectangle(). + */ +struct GAPI_EXPORTS_W_SIMPLE Rect +{ + /** + * @brief Rect constructor + * + * @param rect_ Coordinates of the rectangle + * @param color_ The bottom-left corner of the text string in the image + * @param thick_ The thickness of lines that make up the rectangle. Negative values, like #FILLED, mean that the function has to draw a filled rectangle + * @param lt_ The type of the line. See #LineTypes + * @param shift_ The number of fractional bits in the point coordinates + */ + Rect(const cv::Rect& rect_, + const cv::Scalar& color_, + int thick_ = 1, + int lt_ = 8, + int shift_ = 0) : + rect(rect_), color(color_), thick(thick_), lt(lt_), shift(shift_) + { + } + + GAPI_WRAP + Rect() = default; + + /*@{*/ + GAPI_PROP_RW cv::Rect rect; //!< Coordinates of the rectangle + GAPI_PROP_RW cv::Scalar color; //!< The rectangle color or brightness (grayscale image) + GAPI_PROP_RW int thick; //!< The thickness of lines that make up the rectangle. Negative values, like #FILLED, mean that the function has to draw a filled rectangle + GAPI_PROP_RW int lt; //!< The type of the line. See #LineTypes + GAPI_PROP_RW int shift; //!< The number of fractional bits in the point coordinates + /*@{*/ +}; + +/** + * @brief This structure represents a circle to draw. + * + * Parameters match cv::circle(). + */ +struct GAPI_EXPORTS_W_SIMPLE Circle +{ + /** + * @brief Circle constructor + * + * @param center_ The center of the circle + * @param radius_ The radius of the circle + * @param color_ The color of the circle + * @param thick_ The thickness of the circle outline, if positive. Negative values, like #FILLED, mean that a filled circle is to be drawn + * @param lt_ The Type of the circle boundary. See #LineTypes + * @param shift_ The Number of fractional bits in the coordinates of the center and in the radius value + */ + GAPI_WRAP + Circle(const cv::Point& center_, + int radius_, + const cv::Scalar& color_, + int thick_ = 1, + int lt_ = 8, + int shift_ = 0) : + center(center_), radius(radius_), color(color_), thick(thick_), lt(lt_), shift(shift_) + { + } + + GAPI_WRAP + Circle() = default; + + /*@{*/ + GAPI_PROP_RW cv::Point center; //!< The center of the circle + GAPI_PROP_RW int radius; //!< The radius of the circle + GAPI_PROP_RW cv::Scalar color; //!< The color of the circle + GAPI_PROP_RW int thick; //!< The thickness of the circle outline, if positive. Negative values, like #FILLED, mean that a filled circle is to be drawn + GAPI_PROP_RW int lt; //!< The Type of the circle boundary. See #LineTypes + GAPI_PROP_RW int shift; //!< The Number of fractional bits in the coordinates of the center and in the radius value + /*@{*/ +}; + +/** + * @brief This structure represents a line to draw. + * + * Parameters match cv::line(). + */ +struct GAPI_EXPORTS_W_SIMPLE Line +{ + /** + * @brief Line constructor + * + * @param pt1_ The first point of the line segment + * @param pt2_ The second point of the line segment + * @param color_ The line color + * @param thick_ The thickness of line + * @param lt_ The Type of the line. See #LineTypes + * @param shift_ The number of fractional bits in the point coordinates + */ + GAPI_WRAP + Line(const cv::Point& pt1_, + const cv::Point& pt2_, + const cv::Scalar& color_, + int thick_ = 1, + int lt_ = 8, + int shift_ = 0) : + pt1(pt1_), pt2(pt2_), color(color_), thick(thick_), lt(lt_), shift(shift_) + { + } + + GAPI_WRAP + Line() = default; + + /*@{*/ + GAPI_PROP_RW cv::Point pt1; //!< The first point of the line segment + GAPI_PROP_RW cv::Point pt2; //!< The second point of the line segment + GAPI_PROP_RW cv::Scalar color; //!< The line color + GAPI_PROP_RW int thick; //!< The thickness of line + GAPI_PROP_RW int lt; //!< The Type of the line. See #LineTypes + GAPI_PROP_RW int shift; //!< The number of fractional bits in the point coordinates + /*@{*/ +}; + +/** + * @brief This structure represents a mosaicing operation. + * + * Mosaicing is a very basic method to obfuscate regions in the image. + */ +struct GAPI_EXPORTS_W_SIMPLE Mosaic +{ + /** + * @brief Mosaic constructor + * + * @param mos_ Coordinates of the mosaic + * @param cellSz_ Cell size (same for X, Y) + * @param decim_ Decimation (0 stands for no decimation) + */ + Mosaic(const cv::Rect& mos_, + int cellSz_, + int decim_) : + mos(mos_), cellSz(cellSz_), decim(decim_) + { + } + + GAPI_WRAP + Mosaic() : cellSz(0), decim(0) {} + + /*@{*/ + GAPI_PROP_RW cv::Rect mos; //!< Coordinates of the mosaic + GAPI_PROP_RW int cellSz; //!< Cell size (same for X, Y) + GAPI_PROP_RW int decim; //!< Decimation (0 stands for no decimation) + /*@{*/ +}; + +/** + * @brief This structure represents an image to draw. + * + * Image is blended on a frame using the specified mask. + */ +struct GAPI_EXPORTS_W_SIMPLE Image +{ + /** + * @brief Mosaic constructor + * + * @param org_ The bottom-left corner of the image + * @param img_ Image to draw + * @param alpha_ Alpha channel for image to draw (same size and number of channels) + */ + GAPI_WRAP + Image(const cv::Point& org_, + const cv::Mat& img_, + const cv::Mat& alpha_) : + org(org_), img(img_), alpha(alpha_) + { + } + + GAPI_WRAP + Image() = default; + + /*@{*/ + GAPI_PROP_RW cv::Point org; //!< The bottom-left corner of the image + GAPI_PROP_RW cv::Mat img; //!< Image to draw + GAPI_PROP_RW cv::Mat alpha; //!< Alpha channel for image to draw (same size and number of channels) + /*@{*/ +}; + +/** + * @brief This structure represents a polygon to draw. + */ +struct GAPI_EXPORTS_W_SIMPLE Poly +{ + /** + * @brief Mosaic constructor + * + * @param points_ Points to connect + * @param color_ The line color + * @param thick_ The thickness of line + * @param lt_ The Type of the line. See #LineTypes + * @param shift_ The number of fractional bits in the point coordinate + */ + GAPI_WRAP + Poly(const std::vector& points_, + const cv::Scalar& color_, + int thick_ = 1, + int lt_ = 8, + int shift_ = 0) : + points(points_), color(color_), thick(thick_), lt(lt_), shift(shift_) + { + } + + GAPI_WRAP + Poly() = default; + + /*@{*/ + GAPI_PROP_RW std::vector points; //!< Points to connect + GAPI_PROP_RW cv::Scalar color; //!< The line color + GAPI_PROP_RW int thick; //!< The thickness of line + GAPI_PROP_RW int lt; //!< The Type of the line. See #LineTypes + GAPI_PROP_RW int shift; //!< The number of fractional bits in the point coordinate + /*@{*/ +}; + +using Prim = util::variant + < Text + , FText + , Rect + , Circle + , Line + , Mosaic + , Image + , Poly + >; + +using Prims = std::vector; +//! @} gapi_draw_prims + +} // namespace draw +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_RENDER_TYPES_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/rmat.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/rmat.hpp index 46989191b3..12c700e455 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/rmat.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/rmat.hpp @@ -1,160 +1,160 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020 Intel Corporation - -#ifndef OPENCV_GAPI_RMAT_HPP -#define OPENCV_GAPI_RMAT_HPP - -#include -#include - -// Forward declaration -namespace cv { -namespace gapi { -namespace s11n { -struct IOStream; -struct IIStream; -} // namespace s11n -} // namespace gapi -} // namespace cv - -namespace cv { - -// "Remote Mat", a general class which provides an abstraction layer over the data -// storage and placement (host, remote device etc) and allows to access this data. -// -// The device specific implementation is hidden in the RMat::IAdapter class -// -// The basic flow is the following: -// * Backend which is aware of the remote device: -// - Implements own AdapterT class which is derived from RMat::IAdapter -// - Wraps device memory into RMat via make_rmat utility function: -// cv::RMat rmat = cv::make_rmat(args); -// -// * End user: -// - Writes the code which works with RMats without any knowledge of the remote device: -// void func(const cv::RMat& in_rmat, cv::RMat& out_rmat) { -// // Fetch input data from the device, get mapped memory for output -// cv::RMat::View in_view = in_rmat.access(Access::R); -// cv::RMat::View out_view = out_rmat.access(Access::W); -// performCalculations(in_view, out_view); -// // data from out_view is transferred to the device when out_view is destroyed -// } -/** \addtogroup gapi_data_structures - * @{ - */ -class GAPI_EXPORTS RMat -{ -public: - // A lightweight wrapper on image data: - // - Doesn't own the memory; - // - Doesn't implement copy semantics (it's assumed that a view is created each time - // wrapped data is being accessed); - // - Has an optional callback which is called when the view is destroyed. - class GAPI_EXPORTS View - { - public: - using DestroyCallback = std::function; - using stepsT = std::vector; - - View() = default; - View(const GMatDesc& desc, uchar* data, const stepsT& steps = {}, DestroyCallback&& cb = nullptr); - View(const GMatDesc& desc, uchar* data, size_t step, DestroyCallback&& cb = nullptr); - - View(const View&) = delete; - View& operator=(const View&) = delete; - View(View&&) = default; - View& operator=(View&& v); - ~View() { if (m_cb) m_cb(); } - - cv::Size size() const { return m_desc.size; } - const std::vector& dims() const { return m_desc.dims; } - int cols() const { return m_desc.size.width; } - int rows() const { return m_desc.size.height; } - int type() const; - int depth() const { return m_desc.depth; } - int chan() const { return m_desc.chan; } - size_t elemSize() const { return CV_ELEM_SIZE(type()); } - - template T* ptr(int y = 0) { - return reinterpret_cast(m_data + step()*y); - } - template const T* ptr(int y = 0) const { - return reinterpret_cast(m_data + step()*y); - } - template T* ptr(int y, int x) { - return reinterpret_cast(m_data + step()*y + step(1)*x); - } - template const T* ptr(int y, int x) const { - return reinterpret_cast(m_data + step()*y + step(1)*x); - } - size_t step(size_t i = 0) const { GAPI_DbgAssert(i; - - RMat() = default; - RMat(AdapterP&& a) : m_adapter(std::move(a)) {} - GMatDesc desc() const { return m_adapter->desc(); } - - // Note: When accessed for write there is no guarantee that returned view - // will contain actual snapshot of the mapped device memory - // (no guarantee that fetch from a device is performed). The only - // guaranty is that when the view is destroyed, its data will be - // transferred to the device - View access(Access a) const { return m_adapter->access(a); } - - // Cast underlying RMat adapter to the particular adapter type, - // return nullptr if underlying type is different - template T* get() const - { - static_assert(std::is_base_of::value, "T is not derived from IAdapter!"); - GAPI_Assert(m_adapter != nullptr); - return dynamic_cast(m_adapter.get()); - } - - void serialize(cv::gapi::s11n::IOStream& os) const { - m_adapter->serialize(os); - } - -private: - AdapterP m_adapter = nullptr; -}; - -template -RMat make_rmat(Ts&&... args) { return { std::make_shared(std::forward(args)...) }; } -/** @} */ - -} //namespace cv - -#endif /* OPENCV_GAPI_RMAT_HPP */ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020 Intel Corporation + +#ifndef OPENCV_GAPI_RMAT_HPP +#define OPENCV_GAPI_RMAT_HPP + +#include +#include + +// Forward declaration +namespace cv { +namespace gapi { +namespace s11n { +struct IOStream; +struct IIStream; +} // namespace s11n +} // namespace gapi +} // namespace cv + +namespace cv { + +// "Remote Mat", a general class which provides an abstraction layer over the data +// storage and placement (host, remote device etc) and allows to access this data. +// +// The device specific implementation is hidden in the RMat::IAdapter class +// +// The basic flow is the following: +// * Backend which is aware of the remote device: +// - Implements own AdapterT class which is derived from RMat::IAdapter +// - Wraps device memory into RMat via make_rmat utility function: +// cv::RMat rmat = cv::make_rmat(args); +// +// * End user: +// - Writes the code which works with RMats without any knowledge of the remote device: +// void func(const cv::RMat& in_rmat, cv::RMat& out_rmat) { +// // Fetch input data from the device, get mapped memory for output +// cv::RMat::View in_view = in_rmat.access(Access::R); +// cv::RMat::View out_view = out_rmat.access(Access::W); +// performCalculations(in_view, out_view); +// // data from out_view is transferred to the device when out_view is destroyed +// } +/** \addtogroup gapi_data_structures + * @{ + */ +class GAPI_EXPORTS RMat +{ +public: + // A lightweight wrapper on image data: + // - Doesn't own the memory; + // - Doesn't implement copy semantics (it's assumed that a view is created each time + // wrapped data is being accessed); + // - Has an optional callback which is called when the view is destroyed. + class GAPI_EXPORTS View + { + public: + using DestroyCallback = std::function; + using stepsT = std::vector; + + View() = default; + View(const GMatDesc& desc, uchar* data, const stepsT& steps = {}, DestroyCallback&& cb = nullptr); + View(const GMatDesc& desc, uchar* data, size_t step, DestroyCallback&& cb = nullptr); + + View(const View&) = delete; + View& operator=(const View&) = delete; + View(View&&) = default; + View& operator=(View&& v); + ~View() { if (m_cb) m_cb(); } + + cv::Size size() const { return m_desc.size; } + const std::vector& dims() const { return m_desc.dims; } + int cols() const { return m_desc.size.width; } + int rows() const { return m_desc.size.height; } + int type() const; + int depth() const { return m_desc.depth; } + int chan() const { return m_desc.chan; } + size_t elemSize() const { return CV_ELEM_SIZE(type()); } + + template T* ptr(int y = 0) { + return reinterpret_cast(m_data + step()*y); + } + template const T* ptr(int y = 0) const { + return reinterpret_cast(m_data + step()*y); + } + template T* ptr(int y, int x) { + return reinterpret_cast(m_data + step()*y + step(1)*x); + } + template const T* ptr(int y, int x) const { + return reinterpret_cast(m_data + step()*y + step(1)*x); + } + size_t step(size_t i = 0) const { GAPI_DbgAssert(i; + + RMat() = default; + RMat(AdapterP&& a) : m_adapter(std::move(a)) {} + GMatDesc desc() const { return m_adapter->desc(); } + + // Note: When accessed for write there is no guarantee that returned view + // will contain actual snapshot of the mapped device memory + // (no guarantee that fetch from a device is performed). The only + // guaranty is that when the view is destroyed, its data will be + // transferred to the device + View access(Access a) const { return m_adapter->access(a); } + + // Cast underlying RMat adapter to the particular adapter type, + // return nullptr if underlying type is different + template T* get() const + { + static_assert(std::is_base_of::value, "T is not derived from IAdapter!"); + GAPI_Assert(m_adapter != nullptr); + return dynamic_cast(m_adapter.get()); + } + + void serialize(cv::gapi::s11n::IOStream& os) const { + m_adapter->serialize(os); + } + +private: + AdapterP m_adapter = nullptr; +}; + +template +RMat make_rmat(Ts&&... args) { return { std::make_shared(std::forward(args)...) }; } +/** @} */ + +} //namespace cv + +#endif /* OPENCV_GAPI_RMAT_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/s11n.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/s11n.hpp index a94f55c249..16c162e7f1 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/s11n.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/s11n.hpp @@ -1,513 +1,513 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020-2021 Intel Corporation - -#ifndef OPENCV_GAPI_S11N_HPP -#define OPENCV_GAPI_S11N_HPP - -#include -#include -#include -#include -#include -#include -#include -#include - -// FIXME: caused by deserialize_runarg -#if defined _MSC_VER -#pragma warning(push) -#pragma warning(disable: 4702) -#endif - -namespace cv { -namespace gapi { - -/** -* \addtogroup gapi_serialization -* @{ -*/ - -namespace detail { - GAPI_EXPORTS cv::GComputation getGraph(const std::vector &bytes); - - GAPI_EXPORTS cv::GMetaArgs getMetaArgs(const std::vector &bytes); - - GAPI_EXPORTS cv::GRunArgs getRunArgs(const std::vector &bytes); - - GAPI_EXPORTS std::vector getVectorOfStrings(const std::vector &bytes); - - template - cv::GCompileArgs getCompileArgs(const std::vector &bytes); - - template - cv::GRunArgs getRunArgsWithAdapters(const std::vector &bytes); -} // namespace detail - -/** @brief Serialize a graph represented by GComputation into an array of bytes. - * - * Check different overloads for more examples. - * @param c GComputation to serialize. - * @return serialized vector of bytes. - */ -GAPI_EXPORTS std::vector serialize(const cv::GComputation &c); - -/** @overload - * @param ca GCompileArgs to serialize. - */ -GAPI_EXPORTS std::vector serialize(const cv::GCompileArgs& ca); - -/** @overload - * @param ma GMetaArgs to serialize. - */ -GAPI_EXPORTS std::vector serialize(const cv::GMetaArgs& ma); - -/** @overload - * @param ra GRunArgs to serialize. - */ -GAPI_EXPORTS std::vector serialize(const cv::GRunArgs& ra); - -/** @overload - * @param vs std::vector to serialize. - */ -GAPI_EXPORTS std::vector serialize(const std::vector& vs); - -/** - * @private - */ -template static inline -T deserialize(const std::vector &bytes); - -/** @brief Deserialize GComputation from a byte array. - * - * Check different overloads for more examples. - * @param bytes serialized vector of bytes. - * @return deserialized GComputation object. - */ -template<> inline -cv::GComputation deserialize(const std::vector &bytes) { - return detail::getGraph(bytes); -} - -/** @brief Deserialize GMetaArgs from a byte array. - * - * Check different overloads for more examples. - * @param bytes serialized vector of bytes. - * @return deserialized GMetaArgs object. - */ -template<> inline -cv::GMetaArgs deserialize(const std::vector &bytes) { - return detail::getMetaArgs(bytes); -} - -/** @brief Deserialize GRunArgs from a byte array. - * - * Check different overloads for more examples. - * @param bytes serialized vector of bytes. - * @return deserialized GRunArgs object. - */ -template<> inline -cv::GRunArgs deserialize(const std::vector &bytes) { - return detail::getRunArgs(bytes); -} - -/** @brief Deserialize std::vector from a byte array. - * - * Check different overloads for more examples. - * @param bytes serialized vector of bytes. - * @return deserialized std::vector object. - */ -template<> inline -std::vector deserialize(const std::vector &bytes) { - return detail::getVectorOfStrings(bytes); -} - -/** - * @brief Deserialize GCompileArgs which types were specified in the template from a byte array. - * - * @note cv::gapi::s11n::detail::S11N template specialization must be provided to make a custom type - * in GCompileArgs deserializable. - * - * @param bytes vector of bytes to deserialize GCompileArgs object from. - * @return GCompileArgs object. - * @see GCompileArgs cv::gapi::s11n::detail::S11N - */ -template inline -typename std::enable_if::value, GCompileArgs>:: -type deserialize(const std::vector &bytes) { - return detail::getCompileArgs(bytes); -} - -/** - * @brief Deserialize GRunArgs including RMat and MediaFrame objects if any from a byte array. - * - * Adapter types are specified in the template. - * @note To be used properly specified adapter types must overload their deserialize() method. - * @param bytes vector of bytes to deserialize GRunArgs object from. - * @return GRunArgs including RMat and MediaFrame objects if any. - * @see RMat MediaFrame - */ -template inline -typename std::enable_if::value, GRunArgs>:: -type deserialize(const std::vector &bytes) { - return detail::getRunArgsWithAdapters(bytes); -} -} // namespace gapi -} // namespace cv - -namespace cv { -namespace gapi { -namespace s11n { - -/** @brief This structure is an interface for serialization routines. - * - * It's main purpose is to provide multiple overloads for operator<<() - * with basic C++ in addition to OpenCV/G-API types. - * - * This sctructure can be inherited and further extended with additional types. - * - * For example, it is utilized in cv::gapi::s11n::detail::S11N as input parameter - * in serialize() method. - */ -struct GAPI_EXPORTS IOStream { - virtual ~IOStream() = default; - // Define the native support for basic C++ types at the API level: - virtual IOStream& operator<< (bool) = 0; - virtual IOStream& operator<< (char) = 0; - virtual IOStream& operator<< (unsigned char) = 0; - virtual IOStream& operator<< (short) = 0; - virtual IOStream& operator<< (unsigned short) = 0; - virtual IOStream& operator<< (int) = 0; - virtual IOStream& operator<< (uint32_t) = 0; - virtual IOStream& operator<< (uint64_t) = 0; - virtual IOStream& operator<< (float) = 0; - virtual IOStream& operator<< (double) = 0; - virtual IOStream& operator<< (const std::string&) = 0; -}; - -/** @brief This structure is an interface for deserialization routines. - * - * It's main purpose is to provide multiple overloads for operator>>() - * with basic C++ in addition to OpenCV/G-API types. - * - * This structure can be inherited and further extended with additional types. - * - * For example, it is utilized in cv::gapi::s11n::detail::S11N as input parameter - * in deserialize() method. - */ -struct GAPI_EXPORTS IIStream { - virtual ~IIStream() = default; - virtual IIStream& operator>> (bool &) = 0; - virtual IIStream& operator>> (std::vector::reference) = 0; - virtual IIStream& operator>> (char &) = 0; - virtual IIStream& operator>> (unsigned char &) = 0; - virtual IIStream& operator>> (short &) = 0; - virtual IIStream& operator>> (unsigned short &) = 0; - virtual IIStream& operator>> (int &) = 0; - virtual IIStream& operator>> (float &) = 0; - virtual IIStream& operator>> (double &) = 0; - virtual IIStream& operator >> (uint32_t &) = 0; - virtual IIStream& operator >> (uint64_t &) = 0; - virtual IIStream& operator>> (std::string &) = 0; -}; - -namespace detail { -GAPI_EXPORTS std::unique_ptr getInStream(const std::vector &bytes); -} // namespace detail - -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -// S11N operators -// Note: operators for basic types are defined in IIStream/IOStream - -// OpenCV types //////////////////////////////////////////////////////////////// - -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Point &pt); -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Point &pt); - -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Point2f &pt); -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Point2f &pt); - -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Point3f &pt); -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Point3f &pt); - -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Size &sz); -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Size &sz); - -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Rect &rc); -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Rect &rc); - -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Scalar &s); -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Scalar &s); - -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Mat &m); -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Mat &m); - -// FIXME: for GRunArgs serialization -#if !defined(GAPI_STANDALONE) -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::UMat & um); -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::UMat & um); -#endif // !defined(GAPI_STANDALONE) - -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::RMat &r); -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::RMat &r); - -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::gapi::wip::IStreamSource::Ptr &issptr); -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::gapi::wip::IStreamSource::Ptr &issptr); - -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::detail::VectorRef &vr); -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::detail::VectorRef &vr); - -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::detail::OpaqueRef &opr); -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::detail::OpaqueRef &opr); - -/// @private -- Exclude this function from OpenCV documentation -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::MediaFrame &mf); -/// @private -- Exclude this function from OpenCV documentation -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::MediaFrame &mf); - -// Generic STL types //////////////////////////////////////////////////////////////// -template -IOStream& operator<< (IOStream& os, const std::map &m) { - const uint32_t sz = static_cast(m.size()); - os << sz; - for (const auto& it : m) os << it.first << it.second; - return os; -} -template -IIStream& operator>> (IIStream& is, std::map &m) { - m.clear(); - uint32_t sz = 0u; - is >> sz; - for (std::size_t i = 0; i < sz; ++i) { - K k{}; - V v{}; - is >> k >> v; - m[k] = v; - } - return is; -} - -template -IOStream& operator<< (IOStream& os, const std::unordered_map &m) { - const uint32_t sz = static_cast(m.size()); - os << sz; - for (auto &&it : m) os << it.first << it.second; - return os; -} -template -IIStream& operator>> (IIStream& is, std::unordered_map &m) { - m.clear(); - uint32_t sz = 0u; - is >> sz; - for (std::size_t i = 0; i < sz; ++i) { - K k{}; - V v{}; - is >> k >> v; - m[k] = v; - } - return is; -} - -template -IOStream& operator<< (IOStream& os, const std::vector &ts) { - const uint32_t sz = static_cast(ts.size()); - os << sz; - for (auto &&v : ts) os << v; - return os; -} -template -IIStream& operator>> (IIStream& is, std::vector &ts) { - uint32_t sz = 0u; - is >> sz; - if (sz == 0u) { - ts.clear(); - } - else { - ts.resize(sz); - for (std::size_t i = 0; i < sz; ++i) is >> ts[i]; - } - return is; -} - -// Generic: variant serialization -namespace detail { -template -IOStream& put_v(IOStream&, const V&, std::size_t) { - GAPI_Error("variant>>: requested index is invalid"); -} - -template -IOStream& put_v(IOStream& os, const V& v, std::size_t x) { - return (x == 0u) - ? os << cv::util::get(v) - : put_v(os, v, x-1); -} - -template -IIStream& get_v(IIStream&, V&, std::size_t, std::size_t) { - GAPI_Error("variant<<: requested index is invalid"); -} - -template -IIStream& get_v(IIStream& is, V& v, std::size_t i, std::size_t gi) { - if (i == gi) { - X x{}; - is >> x; - v = V{std::move(x)}; - return is; - } else return get_v(is, v, i+1, gi); -} -} // namespace detail - -//! @overload -template -IOStream& operator<< (IOStream& os, const cv::util::variant &v) { - os << static_cast(v.index()); - return detail::put_v, Ts...>(os, v, v.index()); -} -//! @overload -template -IIStream& operator>> (IIStream& is, cv::util::variant &v) { - int idx = -1; - is >> idx; - GAPI_Assert(idx >= 0 && idx < (int)sizeof...(Ts)); - return detail::get_v, Ts...>(is, v, 0u, idx); -} - -// FIXME: consider a better solution -/// @private -- Exclude this function from OpenCV documentation -template -void getRunArgByIdx (IIStream& is, cv::util::variant &v, uint32_t idx) { - is = detail::get_v, Ts...>(is, v, 0u, idx); -} -} // namespace s11n - -namespace detail -{ -template struct try_deserialize_comparg; - -template<> struct try_deserialize_comparg> { -static cv::util::optional exec(const std::string&, cv::gapi::s11n::IIStream&) { - return { }; - } -}; - -template -struct try_deserialize_comparg> { -static cv::util::optional exec(const std::string& tag, cv::gapi::s11n::IIStream& is) { - if (tag == cv::detail::CompileArgTag::tag()) { - static_assert(cv::gapi::s11n::detail::has_S11N_spec::value, - "cv::gapi::deserialize expects Types to have S11N " - "specializations with deserialization callbacks!"); - return cv::util::optional( - GCompileArg { cv::gapi::s11n::detail::S11N::deserialize(is) }); - } - return try_deserialize_comparg>::exec(tag, is); -} -}; - -template -struct deserialize_arg_with_adapter; - -template -struct deserialize_arg_with_adapter { -static GRunArg exec(cv::gapi::s11n::IIStream& is) { - std::unique_ptr ptr(new TA); - ptr->deserialize(is); - return GRunArg { RA(std::move(ptr)) }; -} -}; - -template -struct deserialize_arg_with_adapter { -static GRunArg exec(cv::gapi::s11n::IIStream&) { - GAPI_Error("No suitable adapter class found during RMat/MediaFrame deserialization. " - "Please, make sure you've passed them in cv::gapi::deserialize() template"); - return GRunArg{}; -} -}; - -template -struct deserialize_runarg { -static GRunArg exec(cv::gapi::s11n::IIStream& is, uint32_t idx) { - if (idx == GRunArg::index_of()) { - // Type or void (if not found) - using TA = typename cv::util::find_adapter_impl::type; - return deserialize_arg_with_adapter::exec(is); - } else if (idx == GRunArg::index_of()) { - // Type or void (if not found) - using TA = typename cv::util::find_adapter_impl::type; - return deserialize_arg_with_adapter::exec(is); - } else { // not an adapter holding type runarg - use default deserialization - GRunArg arg; - getRunArgByIdx(is, arg, idx); - return arg; - } -} -}; - -template -inline cv::util::optional tryDeserializeCompArg(const std::string& tag, - const std::vector& sArg) { - std::unique_ptr pArgIs = cv::gapi::s11n::detail::getInStream(sArg); - return try_deserialize_comparg>::exec(tag, *pArgIs); -} - -template -cv::GCompileArgs getCompileArgs(const std::vector &sArgs) { - cv::GCompileArgs args; - - std::unique_ptr pIs = cv::gapi::s11n::detail::getInStream(sArgs); - cv::gapi::s11n::IIStream& is = *pIs; - - uint32_t sz = 0; - is >> sz; - for (uint32_t i = 0; i < sz; ++i) { - std::string tag; - is >> tag; - - std::vector sArg; - is >> sArg; - - cv::util::optional dArg = - cv::gapi::detail::tryDeserializeCompArg(tag, sArg); - - if (dArg.has_value()) - { - args.push_back(dArg.value()); - } - } - - return args; -} - -template -cv::GRunArgs getRunArgsWithAdapters(const std::vector &bytes) { - std::unique_ptr pIs = cv::gapi::s11n::detail::getInStream(bytes); - cv::gapi::s11n::IIStream& is = *pIs; - cv::GRunArgs args; - - uint32_t sz = 0; - is >> sz; - for (uint32_t i = 0; i < sz; ++i) { - uint32_t idx = 0; - is >> idx; - args.push_back(cv::gapi::detail::deserialize_runarg::exec(is, idx)); - } - - return args; -} -} // namespace detail -/** @} */ - -} // namespace gapi -} // namespace cv - -#if defined _MSC_VER -#pragma warning(pop) -#endif - -#endif // OPENCV_GAPI_S11N_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020-2021 Intel Corporation + +#ifndef OPENCV_GAPI_S11N_HPP +#define OPENCV_GAPI_S11N_HPP + +#include +#include +#include +#include +#include +#include +#include +#include + +// FIXME: caused by deserialize_runarg +#if defined _MSC_VER +#pragma warning(push) +#pragma warning(disable: 4702) +#endif + +namespace cv { +namespace gapi { + +/** +* \addtogroup gapi_serialization +* @{ +*/ + +namespace detail { + GAPI_EXPORTS cv::GComputation getGraph(const std::vector &bytes); + + GAPI_EXPORTS cv::GMetaArgs getMetaArgs(const std::vector &bytes); + + GAPI_EXPORTS cv::GRunArgs getRunArgs(const std::vector &bytes); + + GAPI_EXPORTS std::vector getVectorOfStrings(const std::vector &bytes); + + template + cv::GCompileArgs getCompileArgs(const std::vector &bytes); + + template + cv::GRunArgs getRunArgsWithAdapters(const std::vector &bytes); +} // namespace detail + +/** @brief Serialize a graph represented by GComputation into an array of bytes. + * + * Check different overloads for more examples. + * @param c GComputation to serialize. + * @return serialized vector of bytes. + */ +GAPI_EXPORTS std::vector serialize(const cv::GComputation &c); + +/** @overload + * @param ca GCompileArgs to serialize. + */ +GAPI_EXPORTS std::vector serialize(const cv::GCompileArgs& ca); + +/** @overload + * @param ma GMetaArgs to serialize. + */ +GAPI_EXPORTS std::vector serialize(const cv::GMetaArgs& ma); + +/** @overload + * @param ra GRunArgs to serialize. + */ +GAPI_EXPORTS std::vector serialize(const cv::GRunArgs& ra); + +/** @overload + * @param vs std::vector to serialize. + */ +GAPI_EXPORTS std::vector serialize(const std::vector& vs); + +/** + * @private + */ +template static inline +T deserialize(const std::vector &bytes); + +/** @brief Deserialize GComputation from a byte array. + * + * Check different overloads for more examples. + * @param bytes serialized vector of bytes. + * @return deserialized GComputation object. + */ +template<> inline +cv::GComputation deserialize(const std::vector &bytes) { + return detail::getGraph(bytes); +} + +/** @brief Deserialize GMetaArgs from a byte array. + * + * Check different overloads for more examples. + * @param bytes serialized vector of bytes. + * @return deserialized GMetaArgs object. + */ +template<> inline +cv::GMetaArgs deserialize(const std::vector &bytes) { + return detail::getMetaArgs(bytes); +} + +/** @brief Deserialize GRunArgs from a byte array. + * + * Check different overloads for more examples. + * @param bytes serialized vector of bytes. + * @return deserialized GRunArgs object. + */ +template<> inline +cv::GRunArgs deserialize(const std::vector &bytes) { + return detail::getRunArgs(bytes); +} + +/** @brief Deserialize std::vector from a byte array. + * + * Check different overloads for more examples. + * @param bytes serialized vector of bytes. + * @return deserialized std::vector object. + */ +template<> inline +std::vector deserialize(const std::vector &bytes) { + return detail::getVectorOfStrings(bytes); +} + +/** + * @brief Deserialize GCompileArgs which types were specified in the template from a byte array. + * + * @note cv::gapi::s11n::detail::S11N template specialization must be provided to make a custom type + * in GCompileArgs deserializable. + * + * @param bytes vector of bytes to deserialize GCompileArgs object from. + * @return GCompileArgs object. + * @see GCompileArgs cv::gapi::s11n::detail::S11N + */ +template inline +typename std::enable_if::value, GCompileArgs>:: +type deserialize(const std::vector &bytes) { + return detail::getCompileArgs(bytes); +} + +/** + * @brief Deserialize GRunArgs including RMat and MediaFrame objects if any from a byte array. + * + * Adapter types are specified in the template. + * @note To be used properly specified adapter types must overload their deserialize() method. + * @param bytes vector of bytes to deserialize GRunArgs object from. + * @return GRunArgs including RMat and MediaFrame objects if any. + * @see RMat MediaFrame + */ +template inline +typename std::enable_if::value, GRunArgs>:: +type deserialize(const std::vector &bytes) { + return detail::getRunArgsWithAdapters(bytes); +} +} // namespace gapi +} // namespace cv + +namespace cv { +namespace gapi { +namespace s11n { + +/** @brief This structure is an interface for serialization routines. + * + * It's main purpose is to provide multiple overloads for operator<<() + * with basic C++ in addition to OpenCV/G-API types. + * + * This sctructure can be inherited and further extended with additional types. + * + * For example, it is utilized in cv::gapi::s11n::detail::S11N as input parameter + * in serialize() method. + */ +struct GAPI_EXPORTS IOStream { + virtual ~IOStream() = default; + // Define the native support for basic C++ types at the API level: + virtual IOStream& operator<< (bool) = 0; + virtual IOStream& operator<< (char) = 0; + virtual IOStream& operator<< (unsigned char) = 0; + virtual IOStream& operator<< (short) = 0; + virtual IOStream& operator<< (unsigned short) = 0; + virtual IOStream& operator<< (int) = 0; + virtual IOStream& operator<< (uint32_t) = 0; + virtual IOStream& operator<< (uint64_t) = 0; + virtual IOStream& operator<< (float) = 0; + virtual IOStream& operator<< (double) = 0; + virtual IOStream& operator<< (const std::string&) = 0; +}; + +/** @brief This structure is an interface for deserialization routines. + * + * It's main purpose is to provide multiple overloads for operator>>() + * with basic C++ in addition to OpenCV/G-API types. + * + * This structure can be inherited and further extended with additional types. + * + * For example, it is utilized in cv::gapi::s11n::detail::S11N as input parameter + * in deserialize() method. + */ +struct GAPI_EXPORTS IIStream { + virtual ~IIStream() = default; + virtual IIStream& operator>> (bool &) = 0; + virtual IIStream& operator>> (std::vector::reference) = 0; + virtual IIStream& operator>> (char &) = 0; + virtual IIStream& operator>> (unsigned char &) = 0; + virtual IIStream& operator>> (short &) = 0; + virtual IIStream& operator>> (unsigned short &) = 0; + virtual IIStream& operator>> (int &) = 0; + virtual IIStream& operator>> (float &) = 0; + virtual IIStream& operator>> (double &) = 0; + virtual IIStream& operator >> (uint32_t &) = 0; + virtual IIStream& operator >> (uint64_t &) = 0; + virtual IIStream& operator>> (std::string &) = 0; +}; + +namespace detail { +GAPI_EXPORTS std::unique_ptr getInStream(const std::vector &bytes); +} // namespace detail + +//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// +// S11N operators +// Note: operators for basic types are defined in IIStream/IOStream + +// OpenCV types //////////////////////////////////////////////////////////////// + +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Point &pt); +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Point &pt); + +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Point2f &pt); +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Point2f &pt); + +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Point3f &pt); +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Point3f &pt); + +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Size &sz); +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Size &sz); + +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Rect &rc); +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Rect &rc); + +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Scalar &s); +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Scalar &s); + +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Mat &m); +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Mat &m); + +// FIXME: for GRunArgs serialization +#if !defined(GAPI_STANDALONE) +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::UMat & um); +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::UMat & um); +#endif // !defined(GAPI_STANDALONE) + +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::RMat &r); +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::RMat &r); + +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::gapi::wip::IStreamSource::Ptr &issptr); +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::gapi::wip::IStreamSource::Ptr &issptr); + +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::detail::VectorRef &vr); +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::detail::VectorRef &vr); + +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::detail::OpaqueRef &opr); +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::detail::OpaqueRef &opr); + +/// @private -- Exclude this function from OpenCV documentation +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::MediaFrame &mf); +/// @private -- Exclude this function from OpenCV documentation +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::MediaFrame &mf); + +// Generic STL types //////////////////////////////////////////////////////////////// +template +IOStream& operator<< (IOStream& os, const std::map &m) { + const uint32_t sz = static_cast(m.size()); + os << sz; + for (const auto& it : m) os << it.first << it.second; + return os; +} +template +IIStream& operator>> (IIStream& is, std::map &m) { + m.clear(); + uint32_t sz = 0u; + is >> sz; + for (std::size_t i = 0; i < sz; ++i) { + K k{}; + V v{}; + is >> k >> v; + m[k] = v; + } + return is; +} + +template +IOStream& operator<< (IOStream& os, const std::unordered_map &m) { + const uint32_t sz = static_cast(m.size()); + os << sz; + for (auto &&it : m) os << it.first << it.second; + return os; +} +template +IIStream& operator>> (IIStream& is, std::unordered_map &m) { + m.clear(); + uint32_t sz = 0u; + is >> sz; + for (std::size_t i = 0; i < sz; ++i) { + K k{}; + V v{}; + is >> k >> v; + m[k] = v; + } + return is; +} + +template +IOStream& operator<< (IOStream& os, const std::vector &ts) { + const uint32_t sz = static_cast(ts.size()); + os << sz; + for (auto &&v : ts) os << v; + return os; +} +template +IIStream& operator>> (IIStream& is, std::vector &ts) { + uint32_t sz = 0u; + is >> sz; + if (sz == 0u) { + ts.clear(); + } + else { + ts.resize(sz); + for (std::size_t i = 0; i < sz; ++i) is >> ts[i]; + } + return is; +} + +// Generic: variant serialization +namespace detail { +template +IOStream& put_v(IOStream&, const V&, std::size_t) { + GAPI_Error("variant>>: requested index is invalid"); +} + +template +IOStream& put_v(IOStream& os, const V& v, std::size_t x) { + return (x == 0u) + ? os << cv::util::get(v) + : put_v(os, v, x-1); +} + +template +IIStream& get_v(IIStream&, V&, std::size_t, std::size_t) { + GAPI_Error("variant<<: requested index is invalid"); +} + +template +IIStream& get_v(IIStream& is, V& v, std::size_t i, std::size_t gi) { + if (i == gi) { + X x{}; + is >> x; + v = V{std::move(x)}; + return is; + } else return get_v(is, v, i+1, gi); +} +} // namespace detail + +//! @overload +template +IOStream& operator<< (IOStream& os, const cv::util::variant &v) { + os << static_cast(v.index()); + return detail::put_v, Ts...>(os, v, v.index()); +} +//! @overload +template +IIStream& operator>> (IIStream& is, cv::util::variant &v) { + int idx = -1; + is >> idx; + GAPI_Assert(idx >= 0 && idx < (int)sizeof...(Ts)); + return detail::get_v, Ts...>(is, v, 0u, idx); +} + +// FIXME: consider a better solution +/// @private -- Exclude this function from OpenCV documentation +template +void getRunArgByIdx (IIStream& is, cv::util::variant &v, uint32_t idx) { + is = detail::get_v, Ts...>(is, v, 0u, idx); +} +} // namespace s11n + +namespace detail +{ +template struct try_deserialize_comparg; + +template<> struct try_deserialize_comparg> { +static cv::util::optional exec(const std::string&, cv::gapi::s11n::IIStream&) { + return { }; + } +}; + +template +struct try_deserialize_comparg> { +static cv::util::optional exec(const std::string& tag, cv::gapi::s11n::IIStream& is) { + if (tag == cv::detail::CompileArgTag::tag()) { + static_assert(cv::gapi::s11n::detail::has_S11N_spec::value, + "cv::gapi::deserialize expects Types to have S11N " + "specializations with deserialization callbacks!"); + return cv::util::optional( + GCompileArg { cv::gapi::s11n::detail::S11N::deserialize(is) }); + } + return try_deserialize_comparg>::exec(tag, is); +} +}; + +template +struct deserialize_arg_with_adapter; + +template +struct deserialize_arg_with_adapter { +static GRunArg exec(cv::gapi::s11n::IIStream& is) { + std::unique_ptr ptr(new TA); + ptr->deserialize(is); + return GRunArg { RA(std::move(ptr)) }; +} +}; + +template +struct deserialize_arg_with_adapter { +static GRunArg exec(cv::gapi::s11n::IIStream&) { + GAPI_Error("No suitable adapter class found during RMat/MediaFrame deserialization. " + "Please, make sure you've passed them in cv::gapi::deserialize() template"); + return GRunArg{}; +} +}; + +template +struct deserialize_runarg { +static GRunArg exec(cv::gapi::s11n::IIStream& is, uint32_t idx) { + if (idx == GRunArg::index_of()) { + // Type or void (if not found) + using TA = typename cv::util::find_adapter_impl::type; + return deserialize_arg_with_adapter::exec(is); + } else if (idx == GRunArg::index_of()) { + // Type or void (if not found) + using TA = typename cv::util::find_adapter_impl::type; + return deserialize_arg_with_adapter::exec(is); + } else { // not an adapter holding type runarg - use default deserialization + GRunArg arg; + getRunArgByIdx(is, arg, idx); + return arg; + } +} +}; + +template +inline cv::util::optional tryDeserializeCompArg(const std::string& tag, + const std::vector& sArg) { + std::unique_ptr pArgIs = cv::gapi::s11n::detail::getInStream(sArg); + return try_deserialize_comparg>::exec(tag, *pArgIs); +} + +template +cv::GCompileArgs getCompileArgs(const std::vector &sArgs) { + cv::GCompileArgs args; + + std::unique_ptr pIs = cv::gapi::s11n::detail::getInStream(sArgs); + cv::gapi::s11n::IIStream& is = *pIs; + + uint32_t sz = 0; + is >> sz; + for (uint32_t i = 0; i < sz; ++i) { + std::string tag; + is >> tag; + + std::vector sArg; + is >> sArg; + + cv::util::optional dArg = + cv::gapi::detail::tryDeserializeCompArg(tag, sArg); + + if (dArg.has_value()) + { + args.push_back(dArg.value()); + } + } + + return args; +} + +template +cv::GRunArgs getRunArgsWithAdapters(const std::vector &bytes) { + std::unique_ptr pIs = cv::gapi::s11n::detail::getInStream(bytes); + cv::gapi::s11n::IIStream& is = *pIs; + cv::GRunArgs args; + + uint32_t sz = 0; + is >> sz; + for (uint32_t i = 0; i < sz; ++i) { + uint32_t idx = 0; + is >> idx; + args.push_back(cv::gapi::detail::deserialize_runarg::exec(is, idx)); + } + + return args; +} +} // namespace detail +/** @} */ + +} // namespace gapi +} // namespace cv + +#if defined _MSC_VER +#pragma warning(pop) +#endif + +#endif // OPENCV_GAPI_S11N_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/s11n/base.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/s11n/base.hpp index 760e8515f6..13e8110bfc 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/s11n/base.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/s11n/base.hpp @@ -1,80 +1,80 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020-2021 Intel Corporation - -#ifndef OPENCV_GAPI_S11N_BASE_HPP -#define OPENCV_GAPI_S11N_BASE_HPP - -#include -#include - -namespace cv { -namespace gapi { - -/** - * @brief This namespace contains G-API serialization and - * deserialization functions and data structures. - */ -namespace s11n { -struct IOStream; -struct IIStream; - -namespace detail { - -//! @addtogroup gapi_serialization -//! @{ - -struct NotImplemented { -}; - -/** @brief This structure allows to implement serialization routines for custom types. - * - * The default S11N for custom types is not implemented. - * - * @note When providing an overloaded implementation for S11N with your type - * don't inherit it from NotImplemented structure. - * - * @note There are lots of overloaded >> and << operators for basic and OpenCV/G-API types - * which can be utilized when serializing a custom type. - * - * Example of usage: - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp S11N usage - * - */ -template -struct S11N: public NotImplemented { - /** - * @brief This function allows user to serialize their custom type. - * - * @note The default overload throws an exception if called. User need to - * properly overload the function to use it. - */ - static void serialize(IOStream &, const T &) { - GAPI_Error("No serialization routine is provided!"); - } - /** - * @brief This function allows user to deserialize their custom type. - * - * @note The default overload throws an exception if called. User need to - * properly overload the function to use it. - */ - static T deserialize(IIStream &) { - GAPI_Error("No deserialization routine is provided!"); - } -}; - -/// @private -- Exclude this struct from OpenCV documentation -template struct has_S11N_spec { - static constexpr bool value = !std::is_base_of::type>>::value; -}; -//! @} gapi_serialization - -} // namespace detail -} // namespace s11n -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_S11N_BASE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020-2021 Intel Corporation + +#ifndef OPENCV_GAPI_S11N_BASE_HPP +#define OPENCV_GAPI_S11N_BASE_HPP + +#include +#include + +namespace cv { +namespace gapi { + +/** + * @brief This namespace contains G-API serialization and + * deserialization functions and data structures. + */ +namespace s11n { +struct IOStream; +struct IIStream; + +namespace detail { + +//! @addtogroup gapi_serialization +//! @{ + +struct NotImplemented { +}; + +/** @brief This structure allows to implement serialization routines for custom types. + * + * The default S11N for custom types is not implemented. + * + * @note When providing an overloaded implementation for S11N with your type + * don't inherit it from NotImplemented structure. + * + * @note There are lots of overloaded >> and << operators for basic and OpenCV/G-API types + * which can be utilized when serializing a custom type. + * + * Example of usage: + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp S11N usage + * + */ +template +struct S11N: public NotImplemented { + /** + * @brief This function allows user to serialize their custom type. + * + * @note The default overload throws an exception if called. User need to + * properly overload the function to use it. + */ + static void serialize(IOStream &, const T &) { + GAPI_Error("No serialization routine is provided!"); + } + /** + * @brief This function allows user to deserialize their custom type. + * + * @note The default overload throws an exception if called. User need to + * properly overload the function to use it. + */ + static T deserialize(IIStream &) { + GAPI_Error("No deserialization routine is provided!"); + } +}; + +/// @private -- Exclude this struct from OpenCV documentation +template struct has_S11N_spec { + static constexpr bool value = !std::is_base_of::type>>::value; +}; +//! @} gapi_serialization + +} // namespace detail +} // namespace s11n +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_S11N_BASE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/stereo.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/stereo.hpp index 9b00267082..fce9c37436 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/stereo.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/stereo.hpp @@ -1,85 +1,85 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distereoibution and at http://opencv.org/license.html. -// -// Copyright (C) 2021 Intel Corporation - -#ifndef OPENCV_GAPI_STEREO_HPP -#define OPENCV_GAPI_STEREO_HPP - -#include -#include -#include - -namespace cv { -namespace gapi { - -/** - * The enum specified format of result that you get from @ref cv::gapi::stereo. - */ -enum class StereoOutputFormat { - DEPTH_FLOAT16, ///< Floating point 16 bit value, CV_16FC1. - ///< This identifier is deprecated, use DEPTH_16F instead. - DEPTH_FLOAT32, ///< Floating point 32 bit value, CV_32FC1 - ///< This identifier is deprecated, use DEPTH_16F instead. - DISPARITY_FIXED16_11_5, ///< 16 bit signed: first bit for sign, - ///< 10 bits for integer part, - ///< 5 bits for fractional part. - ///< This identifier is deprecated, - ///< use DISPARITY_16Q_10_5 instead. - DISPARITY_FIXED16_12_4, ///< 16 bit signed: first bit for sign, - ///< 11 bits for integer part, - ///< 4 bits for fractional part. - ///< This identifier is deprecated, - ///< use DISPARITY_16Q_11_4 instead. - DEPTH_16F = DEPTH_FLOAT16, ///< Same as DEPTH_FLOAT16 - DEPTH_32F = DEPTH_FLOAT32, ///< Same as DEPTH_FLOAT32 - DISPARITY_16Q_10_5 = DISPARITY_FIXED16_11_5, ///< Same as DISPARITY_FIXED16_11_5 - DISPARITY_16Q_11_4 = DISPARITY_FIXED16_12_4 ///< Same as DISPARITY_FIXED16_12_4 -}; - - -/** - * @brief This namespace contains G-API Operation Types for Stereo and - * related functionality. - */ -namespace calib3d { - -G_TYPED_KERNEL(GStereo, , "org.opencv.stereo") { - static GMatDesc outMeta(const GMatDesc &left, const GMatDesc &right, const StereoOutputFormat of) { - GAPI_Assert(left.chan == 1); - GAPI_Assert(left.depth == CV_8U); - - GAPI_Assert(right.chan == 1); - GAPI_Assert(right.depth == CV_8U); - - switch(of) { - case StereoOutputFormat::DEPTH_FLOAT16: - return left.withDepth(CV_16FC1); - case StereoOutputFormat::DEPTH_FLOAT32: - return left.withDepth(CV_32FC1); - case StereoOutputFormat::DISPARITY_FIXED16_11_5: - case StereoOutputFormat::DISPARITY_FIXED16_12_4: - return left.withDepth(CV_16SC1); - default: - GAPI_Error("Unknown output format!"); - } - } -}; - -} // namespace calib3d - -/** @brief Computes disparity/depth map for the specified stereo-pair. -The function computes disparity or depth map depending on passed StereoOutputFormat argument. - -@param left 8-bit single-channel left image of @ref CV_8UC1 type. -@param right 8-bit single-channel right image of @ref CV_8UC1 type. -@param of enum to specified output kind: depth or disparity and corresponding type -*/ -GAPI_EXPORTS GMat stereo(const GMat& left, - const GMat& right, - const StereoOutputFormat of = StereoOutputFormat::DEPTH_FLOAT32); -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_STEREO_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distereoibution and at http://opencv.org/license.html. +// +// Copyright (C) 2021 Intel Corporation + +#ifndef OPENCV_GAPI_STEREO_HPP +#define OPENCV_GAPI_STEREO_HPP + +#include +#include +#include + +namespace cv { +namespace gapi { + +/** + * The enum specified format of result that you get from @ref cv::gapi::stereo. + */ +enum class StereoOutputFormat { + DEPTH_FLOAT16, ///< Floating point 16 bit value, CV_16FC1. + ///< This identifier is deprecated, use DEPTH_16F instead. + DEPTH_FLOAT32, ///< Floating point 32 bit value, CV_32FC1 + ///< This identifier is deprecated, use DEPTH_16F instead. + DISPARITY_FIXED16_11_5, ///< 16 bit signed: first bit for sign, + ///< 10 bits for integer part, + ///< 5 bits for fractional part. + ///< This identifier is deprecated, + ///< use DISPARITY_16Q_10_5 instead. + DISPARITY_FIXED16_12_4, ///< 16 bit signed: first bit for sign, + ///< 11 bits for integer part, + ///< 4 bits for fractional part. + ///< This identifier is deprecated, + ///< use DISPARITY_16Q_11_4 instead. + DEPTH_16F = DEPTH_FLOAT16, ///< Same as DEPTH_FLOAT16 + DEPTH_32F = DEPTH_FLOAT32, ///< Same as DEPTH_FLOAT32 + DISPARITY_16Q_10_5 = DISPARITY_FIXED16_11_5, ///< Same as DISPARITY_FIXED16_11_5 + DISPARITY_16Q_11_4 = DISPARITY_FIXED16_12_4 ///< Same as DISPARITY_FIXED16_12_4 +}; + + +/** + * @brief This namespace contains G-API Operation Types for Stereo and + * related functionality. + */ +namespace calib3d { + +G_TYPED_KERNEL(GStereo, , "org.opencv.stereo") { + static GMatDesc outMeta(const GMatDesc &left, const GMatDesc &right, const StereoOutputFormat of) { + GAPI_Assert(left.chan == 1); + GAPI_Assert(left.depth == CV_8U); + + GAPI_Assert(right.chan == 1); + GAPI_Assert(right.depth == CV_8U); + + switch(of) { + case StereoOutputFormat::DEPTH_FLOAT16: + return left.withDepth(CV_16FC1); + case StereoOutputFormat::DEPTH_FLOAT32: + return left.withDepth(CV_32FC1); + case StereoOutputFormat::DISPARITY_FIXED16_11_5: + case StereoOutputFormat::DISPARITY_FIXED16_12_4: + return left.withDepth(CV_16SC1); + default: + GAPI_Error("Unknown output format!"); + } + } +}; + +} // namespace calib3d + +/** @brief Computes disparity/depth map for the specified stereo-pair. +The function computes disparity or depth map depending on passed StereoOutputFormat argument. + +@param left 8-bit single-channel left image of @ref CV_8UC1 type. +@param right 8-bit single-channel right image of @ref CV_8UC1 type. +@param of enum to specified output kind: depth or disparity and corresponding type +*/ +GAPI_EXPORTS GMat stereo(const GMat& left, + const GMat& right, + const StereoOutputFormat of = StereoOutputFormat::DEPTH_FLOAT32); +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_STEREO_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/cap.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/cap.hpp index 9c2185c1ab..6ceb395733 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/cap.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/cap.hpp @@ -1,149 +1,149 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019 Intel Corporation - -#ifndef OPENCV_GAPI_STREAMING_CAP_HPP -#define OPENCV_GAPI_STREAMING_CAP_HPP - -/** - * YOUR ATTENTION PLEASE! - * - * This is a header-only implementation of cv::VideoCapture-based - * Stream source. It is not built by default with G-API as G-API - * doesn't depend on videoio module. - * - * If you want to use it in your application, please make sure - * videioio is available in your OpenCV package and is linked to your - * application. - * - * Note for developers: please don't put videoio dependency in G-API - * because of this file. - */ -#include -#include - -#include -#include -#include - -namespace cv { -namespace gapi { -namespace wip { - -/** - * @brief OpenCV's VideoCapture-based streaming source. - * - * This class implements IStreamSource interface. - * Its constructor takes the same parameters as cv::VideoCapture does. - * - * Please make sure that videoio OpenCV module is available before using - * this in your application (G-API doesn't depend on it directly). - * - * @note stream sources are passed to G-API via shared pointers, so - * please gapi::make_src<> to create objects and ptr() to pass a - * GCaptureSource to cv::gin(). - */ -class GCaptureSource: public IStreamSource -{ -public: - explicit GCaptureSource(int id, const std::map &properties = {}) - : cap(id) { prep(properties); } - - explicit GCaptureSource(const std::string &path, - const std::map &properties = {}) - : cap(path) { prep(properties); } - - void set(int propid, double value) { - cap.set(propid, value); - } - - // TODO: Add more constructor overloads to make it - // fully compatible with VideoCapture's interface. - -protected: - cv::VideoCapture cap; - cv::Mat first; - bool first_pulled = false; - int64_t counter = 0; - - void prep(const std::map &properties) - { - for (const auto &it : properties) { - cap.set(it.first, it.second); - } - - // Prepare first frame to report its meta to engine - // when needed - GAPI_Assert(first.empty()); - cv::Mat tmp; - if (!cap.read(tmp)) - { - GAPI_Error("Couldn't grab the very first frame"); - } - // NOTE: Some decode/media VideoCapture backends continue - // owning the video buffer under cv::Mat so in order to - // process it safely in a highly concurrent pipeline, clone() - // is the only right way. - first = tmp.clone(); - } - - virtual bool pull(cv::gapi::wip::Data &data) override - { - if (!first_pulled) - { - GAPI_Assert(!first.empty()); - first_pulled = true; - data = first; // no need to clone here since it was cloned already - } - else - { - if (!cap.isOpened()) return false; - - cv::Mat frame; - if (!cap.read(frame)) - { - // end-of-stream happened - return false; - } - // Same reason to clone as in prep() - data = frame.clone(); - } - // Tag data with seq_id/ts - const auto now = std::chrono::system_clock::now(); - const auto dur = std::chrono::duration_cast - (now.time_since_epoch()); - data.meta[cv::gapi::streaming::meta_tag::timestamp] = int64_t{dur.count()}; - data.meta[cv::gapi::streaming::meta_tag::seq_id] = int64_t{counter++}; - return true; - } - - virtual GMetaArg descr_of() const override - { - GAPI_Assert(!first.empty()); - return cv::GMetaArg{cv::descr_of(first)}; - } -}; - -// NB: Overload for using from python -GAPI_EXPORTS_W cv::Ptr -inline make_capture_src(const std::string& path, - const std::map& properties = {}) -{ - return make_src(path, properties); -} - -// NB: Overload for using from python -GAPI_EXPORTS_W cv::Ptr -inline make_capture_src(const int id, - const std::map& properties = {}) -{ - return make_src(id, properties); -} - -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_STREAMING_CAP_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019 Intel Corporation + +#ifndef OPENCV_GAPI_STREAMING_CAP_HPP +#define OPENCV_GAPI_STREAMING_CAP_HPP + +/** + * YOUR ATTENTION PLEASE! + * + * This is a header-only implementation of cv::VideoCapture-based + * Stream source. It is not built by default with G-API as G-API + * doesn't depend on videoio module. + * + * If you want to use it in your application, please make sure + * videioio is available in your OpenCV package and is linked to your + * application. + * + * Note for developers: please don't put videoio dependency in G-API + * because of this file. + */ +#include +#include + +#include +#include +#include + +namespace cv { +namespace gapi { +namespace wip { + +/** + * @brief OpenCV's VideoCapture-based streaming source. + * + * This class implements IStreamSource interface. + * Its constructor takes the same parameters as cv::VideoCapture does. + * + * Please make sure that videoio OpenCV module is available before using + * this in your application (G-API doesn't depend on it directly). + * + * @note stream sources are passed to G-API via shared pointers, so + * please gapi::make_src<> to create objects and ptr() to pass a + * GCaptureSource to cv::gin(). + */ +class GCaptureSource: public IStreamSource +{ +public: + explicit GCaptureSource(int id, const std::map &properties = {}) + : cap(id) { prep(properties); } + + explicit GCaptureSource(const std::string &path, + const std::map &properties = {}) + : cap(path) { prep(properties); } + + void set(int propid, double value) { + cap.set(propid, value); + } + + // TODO: Add more constructor overloads to make it + // fully compatible with VideoCapture's interface. + +protected: + cv::VideoCapture cap; + cv::Mat first; + bool first_pulled = false; + int64_t counter = 0; + + void prep(const std::map &properties) + { + for (const auto &it : properties) { + cap.set(it.first, it.second); + } + + // Prepare first frame to report its meta to engine + // when needed + GAPI_Assert(first.empty()); + cv::Mat tmp; + if (!cap.read(tmp)) + { + GAPI_Error("Couldn't grab the very first frame"); + } + // NOTE: Some decode/media VideoCapture backends continue + // owning the video buffer under cv::Mat so in order to + // process it safely in a highly concurrent pipeline, clone() + // is the only right way. + first = tmp.clone(); + } + + virtual bool pull(cv::gapi::wip::Data &data) override + { + if (!first_pulled) + { + GAPI_Assert(!first.empty()); + first_pulled = true; + data = first; // no need to clone here since it was cloned already + } + else + { + if (!cap.isOpened()) return false; + + cv::Mat frame; + if (!cap.read(frame)) + { + // end-of-stream happened + return false; + } + // Same reason to clone as in prep() + data = frame.clone(); + } + // Tag data with seq_id/ts + const auto now = std::chrono::system_clock::now(); + const auto dur = std::chrono::duration_cast + (now.time_since_epoch()); + data.meta[cv::gapi::streaming::meta_tag::timestamp] = int64_t{dur.count()}; + data.meta[cv::gapi::streaming::meta_tag::seq_id] = int64_t{counter++}; + return true; + } + + virtual GMetaArg descr_of() const override + { + GAPI_Assert(!first.empty()); + return cv::GMetaArg{cv::descr_of(first)}; + } +}; + +// NB: Overload for using from python +GAPI_EXPORTS_W cv::Ptr +inline make_capture_src(const std::string& path, + const std::map& properties = {}) +{ + return make_src(path, properties); +} + +// NB: Overload for using from python +GAPI_EXPORTS_W cv::Ptr +inline make_capture_src(const int id, + const std::map& properties = {}) +{ + return make_src(id, properties); +} + +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_STREAMING_CAP_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/desync.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/desync.hpp index 0e04f5beb9..eebb9d8328 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/desync.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/desync.hpp @@ -1,86 +1,86 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020-2021 Intel Corporation - - -#ifndef OPENCV_GAPI_GSTREAMING_DESYNC_HPP -#define OPENCV_GAPI_GSTREAMING_DESYNC_HPP - -#include - -#include -#include -#include -#include -#include - -namespace cv { -namespace gapi { -namespace streaming { - -namespace detail { -struct GDesync { - static const char *id() { - return "org.opencv.streaming.desync"; - } - - // An universal yield for desync. - // Yields output objects according to the input Types... - // Reuses gkernel machinery. - // FIXME: This function can be generic and declared in gkernel.hpp - // (it is there already, but a part of GKernelType[M] - template - static std::tuple yield(cv::GCall &call, cv::detail::Seq) { - return std::make_tuple(cv::detail::Yield::yield(call, IIs)...); - } -}; - -template -G desync(const G &g) { - cv::GKernel k{ - GDesync::id() // kernel id - , "" // kernel tag - , [](const GMetaArgs &a, const GArgs &) {return a;} // outMeta callback - , {cv::detail::GTypeTraits::shape} // output Shape - , {cv::detail::GTypeTraits::op_kind} // input data kinds - , {cv::detail::GObtainCtor::get()} // output template ctors - , {cv::detail::GTypeTraits::op_kind} // output data kinds - }; - cv::GCall call(std::move(k)); - call.pass(g); - return std::get<0>(GDesync::yield(call, cv::detail::MkSeq<1>::type())); -} -} // namespace detail - -/** - * @brief Starts a desynchronized branch in the graph. - * - * This operation takes a single G-API data object and returns a - * graph-level "duplicate" of this object. - * - * Operations which use this data object can be desynchronized - * from the rest of the graph. - * - * This operation has no effect when a GComputation is compiled with - * regular cv::GComputation::compile(), since cv::GCompiled objects - * always produce their full output vectors. - * - * This operation only makes sense when a GComputation is compiled in - * streaming mode with cv::GComputation::compileStreaming(). If this - * operation is used and there are desynchronized outputs, the user - * should use a special version of cv::GStreamingCompiled::pull() - * which produces an array of cv::util::optional<> objects. - * - * @note This feature is highly experimental now and is currently - * limited to a single GMat/GFrame argument only. - */ -GAPI_EXPORTS GMat desync(const GMat &g); -GAPI_EXPORTS GFrame desync(const GFrame &f); - -} // namespace streaming -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_GSTREAMING_DESYNC_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020-2021 Intel Corporation + + +#ifndef OPENCV_GAPI_GSTREAMING_DESYNC_HPP +#define OPENCV_GAPI_GSTREAMING_DESYNC_HPP + +#include + +#include +#include +#include +#include +#include + +namespace cv { +namespace gapi { +namespace streaming { + +namespace detail { +struct GDesync { + static const char *id() { + return "org.opencv.streaming.desync"; + } + + // An universal yield for desync. + // Yields output objects according to the input Types... + // Reuses gkernel machinery. + // FIXME: This function can be generic and declared in gkernel.hpp + // (it is there already, but a part of GKernelType[M] + template + static std::tuple yield(cv::GCall &call, cv::detail::Seq) { + return std::make_tuple(cv::detail::Yield::yield(call, IIs)...); + } +}; + +template +G desync(const G &g) { + cv::GKernel k{ + GDesync::id() // kernel id + , "" // kernel tag + , [](const GMetaArgs &a, const GArgs &) {return a;} // outMeta callback + , {cv::detail::GTypeTraits::shape} // output Shape + , {cv::detail::GTypeTraits::op_kind} // input data kinds + , {cv::detail::GObtainCtor::get()} // output template ctors + , {cv::detail::GTypeTraits::op_kind} // output data kinds + }; + cv::GCall call(std::move(k)); + call.pass(g); + return std::get<0>(GDesync::yield(call, cv::detail::MkSeq<1>::type())); +} +} // namespace detail + +/** + * @brief Starts a desynchronized branch in the graph. + * + * This operation takes a single G-API data object and returns a + * graph-level "duplicate" of this object. + * + * Operations which use this data object can be desynchronized + * from the rest of the graph. + * + * This operation has no effect when a GComputation is compiled with + * regular cv::GComputation::compile(), since cv::GCompiled objects + * always produce their full output vectors. + * + * This operation only makes sense when a GComputation is compiled in + * streaming mode with cv::GComputation::compileStreaming(). If this + * operation is used and there are desynchronized outputs, the user + * should use a special version of cv::GStreamingCompiled::pull() + * which produces an array of cv::util::optional<> objects. + * + * @note This feature is highly experimental now and is currently + * limited to a single GMat/GFrame argument only. + */ +GAPI_EXPORTS GMat desync(const GMat &g); +GAPI_EXPORTS GFrame desync(const GFrame &f); + +} // namespace streaming +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_GSTREAMING_DESYNC_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/format.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/format.hpp index 739a3852a6..27bd110ac2 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/format.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/format.hpp @@ -1,94 +1,94 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020 Intel Corporation - -#ifndef OPENCV_GAPI_GSTREAMING_FORMAT_HPP -#define OPENCV_GAPI_GSTREAMING_FORMAT_HPP - -#include // GKernelPackage - -namespace cv { -namespace gapi { -namespace streaming { - -GAPI_EXPORTS cv::GKernelPackage kernels(); - -G_API_OP(GBGR, , "org.opencv.streaming.BGR") -{ - static GMatDesc outMeta(const GFrameDesc& in) { return GMatDesc{CV_8U, 3, in.size}; } -}; - -G_API_OP(GY, , "org.opencv.streaming.Y") { - static GMatDesc outMeta(const GFrameDesc& frameDesc) { - return GMatDesc { CV_8U, 1, frameDesc.size , false }; - } -}; - -G_API_OP(GUV, , "org.opencv.streaming.UV") { - static GMatDesc outMeta(const GFrameDesc& frameDesc) { - return GMatDesc { CV_8U, 2, cv::Size(frameDesc.size.width / 2, frameDesc.size.height / 2), - false }; - } -}; - -/** @brief Gets bgr plane from input frame - -@note Function textual ID is "org.opencv.streaming.BGR" - -@param in Input frame -@return Image in BGR format -*/ -GAPI_EXPORTS cv::GMat BGR(const cv::GFrame& in); - -/** @brief Extracts Y plane from media frame. - -Output image is 8-bit 1-channel image of @ref CV_8UC1. - -@note Function textual ID is "org.opencv.streaming.Y" - -@param frame input media frame. -*/ -GAPI_EXPORTS GMat Y(const cv::GFrame& frame); - -/** @brief Extracts UV plane from media frame. - -Output image is 8-bit 2-channel image of @ref CV_8UC2. - -@note Function textual ID is "org.opencv.streaming.UV" - -@param frame input media frame. -*/ -GAPI_EXPORTS GMat UV(const cv::GFrame& frame); -} // namespace streaming - -//! @addtogroup gapi_transform -//! @{ -/** @brief Makes a copy of the input image. Note that this copy may be not real -(no actual data copied). Use this function to maintain graph contracts, -e.g when graph's input needs to be passed directly to output, like in Streaming mode. - -@note Function textual ID is "org.opencv.streaming.copy" - -@param in Input image -@return Copy of the input -*/ -GAPI_EXPORTS_W GMat copy(const GMat& in); - -/** @brief Makes a copy of the input frame. Note that this copy may be not real -(no actual data copied). Use this function to maintain graph contracts, -e.g when graph's input needs to be passed directly to output, like in Streaming mode. - -@note Function textual ID is "org.opencv.streaming.copy" - -@param in Input frame -@return Copy of the input -*/ -GAPI_EXPORTS GFrame copy(const GFrame& in); -//! @} gapi_transform - -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_GSTREAMING_FORMAT_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020 Intel Corporation + +#ifndef OPENCV_GAPI_GSTREAMING_FORMAT_HPP +#define OPENCV_GAPI_GSTREAMING_FORMAT_HPP + +#include // GKernelPackage + +namespace cv { +namespace gapi { +namespace streaming { + +GAPI_EXPORTS cv::GKernelPackage kernels(); + +G_API_OP(GBGR, , "org.opencv.streaming.BGR") +{ + static GMatDesc outMeta(const GFrameDesc& in) { return GMatDesc{CV_8U, 3, in.size}; } +}; + +G_API_OP(GY, , "org.opencv.streaming.Y") { + static GMatDesc outMeta(const GFrameDesc& frameDesc) { + return GMatDesc { CV_8U, 1, frameDesc.size , false }; + } +}; + +G_API_OP(GUV, , "org.opencv.streaming.UV") { + static GMatDesc outMeta(const GFrameDesc& frameDesc) { + return GMatDesc { CV_8U, 2, cv::Size(frameDesc.size.width / 2, frameDesc.size.height / 2), + false }; + } +}; + +/** @brief Gets bgr plane from input frame + +@note Function textual ID is "org.opencv.streaming.BGR" + +@param in Input frame +@return Image in BGR format +*/ +GAPI_EXPORTS cv::GMat BGR(const cv::GFrame& in); + +/** @brief Extracts Y plane from media frame. + +Output image is 8-bit 1-channel image of @ref CV_8UC1. + +@note Function textual ID is "org.opencv.streaming.Y" + +@param frame input media frame. +*/ +GAPI_EXPORTS GMat Y(const cv::GFrame& frame); + +/** @brief Extracts UV plane from media frame. + +Output image is 8-bit 2-channel image of @ref CV_8UC2. + +@note Function textual ID is "org.opencv.streaming.UV" + +@param frame input media frame. +*/ +GAPI_EXPORTS GMat UV(const cv::GFrame& frame); +} // namespace streaming + +//! @addtogroup gapi_transform +//! @{ +/** @brief Makes a copy of the input image. Note that this copy may be not real +(no actual data copied). Use this function to maintain graph contracts, +e.g when graph's input needs to be passed directly to output, like in Streaming mode. + +@note Function textual ID is "org.opencv.streaming.copy" + +@param in Input image +@return Copy of the input +*/ +GAPI_EXPORTS_W GMat copy(const GMat& in); + +/** @brief Makes a copy of the input frame. Note that this copy may be not real +(no actual data copied). Use this function to maintain graph contracts, +e.g when graph's input needs to be passed directly to output, like in Streaming mode. + +@note Function textual ID is "org.opencv.streaming.copy" + +@param in Input frame +@return Copy of the input +*/ +GAPI_EXPORTS GFrame copy(const GFrame& in); +//! @} gapi_transform + +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_GSTREAMING_FORMAT_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/gstreamer/gstreamerpipeline.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/gstreamer/gstreamerpipeline.hpp index c566656cb6..d70b783c84 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/gstreamer/gstreamerpipeline.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/gstreamer/gstreamerpipeline.hpp @@ -1,59 +1,59 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2021 Intel Corporation - -#ifndef OPENCV_GAPI_STREAMING_GSTREAMER_GSTREAMERPIPELINE_HPP -#define OPENCV_GAPI_STREAMING_GSTREAMER_GSTREAMERPIPELINE_HPP - -#include -#include - -#include -#include -#include - -namespace cv { -namespace gapi { -namespace wip { -namespace gst { - -class GAPI_EXPORTS_W GStreamerPipeline -{ -public: - class Priv; - - GAPI_WRAP explicit GStreamerPipeline(const std::string& pipeline); - IStreamSource::Ptr getStreamingSource(const std::string& appsinkName, - const GStreamerSource::OutputType outputType = - GStreamerSource::OutputType::MAT); - virtual ~GStreamerPipeline(); - -protected: - explicit GStreamerPipeline(std::unique_ptr priv); - - std::unique_ptr m_priv; -}; - -} // namespace gst - -using GStreamerPipeline = gst::GStreamerPipeline; - -// NB: Function for using from python -// FIXME: a separate function is created due to absence of wrappers for `shared_ptr<> ` -// Ideally would be to wrap the `GStreamerPipeline::getStreamingSource()` method as is -GAPI_EXPORTS_W cv::Ptr -inline get_streaming_source(cv::Ptr& pipeline, - const std::string& appsinkName, - const GStreamerSource::OutputType outputType - = GStreamerSource::OutputType::MAT) -{ - return pipeline->getStreamingSource(appsinkName, outputType); -} - -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_STREAMING_GSTREAMER_GSTREAMERPIPELINE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2021 Intel Corporation + +#ifndef OPENCV_GAPI_STREAMING_GSTREAMER_GSTREAMERPIPELINE_HPP +#define OPENCV_GAPI_STREAMING_GSTREAMER_GSTREAMERPIPELINE_HPP + +#include +#include + +#include +#include +#include + +namespace cv { +namespace gapi { +namespace wip { +namespace gst { + +class GAPI_EXPORTS_W GStreamerPipeline +{ +public: + class Priv; + + GAPI_WRAP explicit GStreamerPipeline(const std::string& pipeline); + IStreamSource::Ptr getStreamingSource(const std::string& appsinkName, + const GStreamerSource::OutputType outputType = + GStreamerSource::OutputType::MAT); + virtual ~GStreamerPipeline(); + +protected: + explicit GStreamerPipeline(std::unique_ptr priv); + + std::unique_ptr m_priv; +}; + +} // namespace gst + +using GStreamerPipeline = gst::GStreamerPipeline; + +// NB: Function for using from python +// FIXME: a separate function is created due to absence of wrappers for `shared_ptr<> ` +// Ideally would be to wrap the `GStreamerPipeline::getStreamingSource()` method as is +GAPI_EXPORTS_W cv::Ptr +inline get_streaming_source(cv::Ptr& pipeline, + const std::string& appsinkName, + const GStreamerSource::OutputType outputType + = GStreamerSource::OutputType::MAT) +{ + return pipeline->getStreamingSource(appsinkName, outputType); +} + +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_STREAMING_GSTREAMER_GSTREAMERPIPELINE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/gstreamer/gstreamersource.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/gstreamer/gstreamersource.hpp index 8b8a5ae312..266131c934 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/gstreamer/gstreamersource.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/gstreamer/gstreamersource.hpp @@ -1,97 +1,97 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2021 Intel Corporation - -#ifndef OPENCV_GAPI_STREAMING_GSTREAMER_GSTREAMERSOURCE_HPP -#define OPENCV_GAPI_STREAMING_GSTREAMER_GSTREAMERSOURCE_HPP - -#include -#include - -#include - -namespace cv { -namespace gapi { -namespace wip { -namespace gst { - -/** - * @brief OpenCV's GStreamer streaming source. - * Streams cv::Mat-s/cv::MediaFrame from passed GStreamer pipeline. - * - * This class implements IStreamSource interface. - * - * To create GStreamerSource instance you need to pass 'pipeline' and, optionally, 'outputType' - * arguments into constructor. - * 'pipeline' should represent GStreamer pipeline in form of textual description. - * Almost any custom pipeline is supported which can be successfully ran via gst-launch. - * The only two limitations are: - * - there should be __one__ appsink element in the pipeline to pass data to OpenCV app. - * Pipeline can actually contain many sink elements, but it must have one and only one - * appsink among them. - * - * - data passed to appsink should be video-frame in NV12 or GRAY8 format. - * - * 'outputType' is used to select type of output data to produce: 'cv::MediaFrame' or 'cv::Mat'. - * To produce 'cv::MediaFrame'-s you need to pass 'GStreamerSource::OutputType::FRAME' and, - * correspondingly, 'GStreamerSource::OutputType::MAT' to produce 'cv::Mat'-s. - * Please note, that in the last case, output 'cv::Mat' will be of BGR format, internal conversion - * from NV12 / GRAY8 GStreamer data will happen. - * Default value for 'outputType' is 'GStreamerSource::OutputType::MAT'. - * - * @note Stream sources are passed to G-API via shared pointers, so please use gapi::make_src<> - * to create objects and ptr() to pass a GStreamerSource to cv::gin(). - * - * @note You need to build OpenCV with GStreamer support to use this class. - */ - -class GStreamerPipelineFacade; - -class GAPI_EXPORTS GStreamerSource : public IStreamSource -{ -public: - class Priv; - - // Indicates what type of data should be produced by GStreamerSource: cv::MediaFrame or cv::Mat - enum class OutputType { - FRAME, - MAT - }; - - GStreamerSource(const std::string& pipeline, - const GStreamerSource::OutputType outputType = - GStreamerSource::OutputType::MAT); - GStreamerSource(std::shared_ptr pipeline, - const std::string& appsinkName, - const GStreamerSource::OutputType outputType = - GStreamerSource::OutputType::MAT); - - bool pull(cv::gapi::wip::Data& data) override; - GMetaArg descr_of() const override; - ~GStreamerSource() override; - -protected: - explicit GStreamerSource(std::unique_ptr priv); - - std::unique_ptr m_priv; -}; - -} // namespace gst - -using GStreamerSource = gst::GStreamerSource; - -// NB: Overload for using from python -GAPI_EXPORTS_W cv::Ptr -inline make_gst_src(const std::string& pipeline, - const GStreamerSource::OutputType outputType = - GStreamerSource::OutputType::MAT) -{ - return make_src(pipeline, outputType); -} -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_STREAMING_GSTREAMER_GSTREAMERSOURCE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2021 Intel Corporation + +#ifndef OPENCV_GAPI_STREAMING_GSTREAMER_GSTREAMERSOURCE_HPP +#define OPENCV_GAPI_STREAMING_GSTREAMER_GSTREAMERSOURCE_HPP + +#include +#include + +#include + +namespace cv { +namespace gapi { +namespace wip { +namespace gst { + +/** + * @brief OpenCV's GStreamer streaming source. + * Streams cv::Mat-s/cv::MediaFrame from passed GStreamer pipeline. + * + * This class implements IStreamSource interface. + * + * To create GStreamerSource instance you need to pass 'pipeline' and, optionally, 'outputType' + * arguments into constructor. + * 'pipeline' should represent GStreamer pipeline in form of textual description. + * Almost any custom pipeline is supported which can be successfully ran via gst-launch. + * The only two limitations are: + * - there should be __one__ appsink element in the pipeline to pass data to OpenCV app. + * Pipeline can actually contain many sink elements, but it must have one and only one + * appsink among them. + * + * - data passed to appsink should be video-frame in NV12 or GRAY8 format. + * + * 'outputType' is used to select type of output data to produce: 'cv::MediaFrame' or 'cv::Mat'. + * To produce 'cv::MediaFrame'-s you need to pass 'GStreamerSource::OutputType::FRAME' and, + * correspondingly, 'GStreamerSource::OutputType::MAT' to produce 'cv::Mat'-s. + * Please note, that in the last case, output 'cv::Mat' will be of BGR format, internal conversion + * from NV12 / GRAY8 GStreamer data will happen. + * Default value for 'outputType' is 'GStreamerSource::OutputType::MAT'. + * + * @note Stream sources are passed to G-API via shared pointers, so please use gapi::make_src<> + * to create objects and ptr() to pass a GStreamerSource to cv::gin(). + * + * @note You need to build OpenCV with GStreamer support to use this class. + */ + +class GStreamerPipelineFacade; + +class GAPI_EXPORTS GStreamerSource : public IStreamSource +{ +public: + class Priv; + + // Indicates what type of data should be produced by GStreamerSource: cv::MediaFrame or cv::Mat + enum class OutputType { + FRAME, + MAT + }; + + GStreamerSource(const std::string& pipeline, + const GStreamerSource::OutputType outputType = + GStreamerSource::OutputType::MAT); + GStreamerSource(std::shared_ptr pipeline, + const std::string& appsinkName, + const GStreamerSource::OutputType outputType = + GStreamerSource::OutputType::MAT); + + bool pull(cv::gapi::wip::Data& data) override; + GMetaArg descr_of() const override; + ~GStreamerSource() override; + +protected: + explicit GStreamerSource(std::unique_ptr priv); + + std::unique_ptr m_priv; +}; + +} // namespace gst + +using GStreamerSource = gst::GStreamerSource; + +// NB: Overload for using from python +GAPI_EXPORTS_W cv::Ptr +inline make_gst_src(const std::string& pipeline, + const GStreamerSource::OutputType outputType = + GStreamerSource::OutputType::MAT) +{ + return make_src(pipeline, outputType); +} +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_STREAMING_GSTREAMER_GSTREAMERSOURCE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/meta.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/meta.hpp index cdd3d371cb..5cae3b4938 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/meta.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/meta.hpp @@ -1,80 +1,80 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020 Intel Corporation - - -#ifndef OPENCV_GAPI_GSTREAMING_META_HPP -#define OPENCV_GAPI_GSTREAMING_META_HPP - -#include -#include -#include -#include - -namespace cv { -namespace gapi { -namespace streaming { - -// FIXME: the name is debatable -namespace meta_tag { -static constexpr const char * timestamp = "org.opencv.gapi.meta.timestamp"; -static constexpr const char * seq_id = "org.opencv.gapi.meta.seq_id"; -} // namespace meta_tag - -namespace detail { -struct GMeta { - static const char *id() { - return "org.opencv.streaming.meta"; - } - // A universal yield for meta(), same as in GDesync - template - static std::tuple yield(cv::GCall &call, cv::detail::Seq) { - return std::make_tuple(cv::detail::Yield::yield(call, IIs)...); - } - // Also a universal outMeta stub here - static GMetaArgs getOutMeta(const GMetaArgs &args, const GArgs &) { - return args; - } -}; -} // namespace detail - -template -cv::GOpaque meta(G g, const std::string &tag) { - using O = cv::GOpaque; - cv::GKernel k{ - detail::GMeta::id() // kernel id - , tag // kernel tag. Use meta tag here - , &detail::GMeta::getOutMeta // outMeta callback - , {cv::detail::GTypeTraits::shape} // output Shape - , {cv::detail::GTypeTraits::op_kind} // input data kinds - , {cv::detail::GObtainCtor::get()} // output template ctors - , {cv::detail::GTypeTraits::op_kind} // output data kind - }; - cv::GCall call(std::move(k)); - call.pass(g); - return std::get<0>(detail::GMeta::yield(call, cv::detail::MkSeq<1>::type())); -} - -template -cv::GOpaque timestamp(G g) { - return meta(g, meta_tag::timestamp); -} - -template -cv::GOpaque seq_id(G g) { - return meta(g, meta_tag::seq_id); -} - -template -cv::GOpaque seqNo(G g) { - // Old name, compatibility only - return seq_id(g); -} - -} // namespace streaming -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_GSTREAMING_META_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020 Intel Corporation + + +#ifndef OPENCV_GAPI_GSTREAMING_META_HPP +#define OPENCV_GAPI_GSTREAMING_META_HPP + +#include +#include +#include +#include + +namespace cv { +namespace gapi { +namespace streaming { + +// FIXME: the name is debatable +namespace meta_tag { +static constexpr const char * timestamp = "org.opencv.gapi.meta.timestamp"; +static constexpr const char * seq_id = "org.opencv.gapi.meta.seq_id"; +} // namespace meta_tag + +namespace detail { +struct GMeta { + static const char *id() { + return "org.opencv.streaming.meta"; + } + // A universal yield for meta(), same as in GDesync + template + static std::tuple yield(cv::GCall &call, cv::detail::Seq) { + return std::make_tuple(cv::detail::Yield::yield(call, IIs)...); + } + // Also a universal outMeta stub here + static GMetaArgs getOutMeta(const GMetaArgs &args, const GArgs &) { + return args; + } +}; +} // namespace detail + +template +cv::GOpaque meta(G g, const std::string &tag) { + using O = cv::GOpaque; + cv::GKernel k{ + detail::GMeta::id() // kernel id + , tag // kernel tag. Use meta tag here + , &detail::GMeta::getOutMeta // outMeta callback + , {cv::detail::GTypeTraits::shape} // output Shape + , {cv::detail::GTypeTraits::op_kind} // input data kinds + , {cv::detail::GObtainCtor::get()} // output template ctors + , {cv::detail::GTypeTraits::op_kind} // output data kind + }; + cv::GCall call(std::move(k)); + call.pass(g); + return std::get<0>(detail::GMeta::yield(call, cv::detail::MkSeq<1>::type())); +} + +template +cv::GOpaque timestamp(G g) { + return meta(g, meta_tag::timestamp); +} + +template +cv::GOpaque seq_id(G g) { + return meta(g, meta_tag::seq_id); +} + +template +cv::GOpaque seqNo(G g) { + // Old name, compatibility only + return seq_id(g); +} + +} // namespace streaming +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_GSTREAMING_META_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/accel_types.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/accel_types.hpp index b670aebd1d..0f850198b6 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/accel_types.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/accel_types.hpp @@ -1,76 +1,76 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2022 Intel Corporation - -#ifndef GAPI_STREAMING_ONEVPL_ACCEL_TYPES_HPP -#define GAPI_STREAMING_ONEVPL_ACCEL_TYPES_HPP - -#include -#include - -#include "opencv2/gapi/own/exports.hpp" // GAPI_EXPORTS - -namespace cv { -namespace gapi { -namespace wip { -namespace onevpl { - -enum class AccelType: uint8_t { - HOST, - DX11, - VAAPI, - - LAST_VALUE = std::numeric_limits::max() -}; - -GAPI_EXPORTS const char* to_cstring(AccelType type); - -struct IDeviceSelector; -struct GAPI_EXPORTS Device { - friend struct IDeviceSelector; - using Ptr = void*; - - ~Device(); - const std::string& get_name() const; - Ptr get_ptr() const; - AccelType get_type() const; -private: - Device(Ptr device_ptr, const std::string& device_name, - AccelType device_type); - - std::string name; - Ptr ptr; - AccelType type; -}; - -struct GAPI_EXPORTS Context { - friend struct IDeviceSelector; - using Ptr = void*; - - ~Context(); - Ptr get_ptr() const; - AccelType get_type() const; -private: - Context(Ptr ctx_ptr, AccelType ctx_type); - Ptr ptr; - AccelType type; -}; - -GAPI_EXPORTS Device create_host_device(); -GAPI_EXPORTS Context create_host_context(); - -GAPI_EXPORTS Device create_dx11_device(Device::Ptr device_ptr, - const std::string& device_name); -GAPI_EXPORTS Context create_dx11_context(Context::Ptr ctx_ptr); - -GAPI_EXPORTS Device create_vaapi_device(Device::Ptr device_ptr, - const std::string& device_name); -GAPI_EXPORTS Context create_vaapi_context(Context::Ptr ctx_ptr); -} // namespace onevpl -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // GAPI_STREAMING_ONEVPL_ACCEL_TYPES_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2022 Intel Corporation + +#ifndef GAPI_STREAMING_ONEVPL_ACCEL_TYPES_HPP +#define GAPI_STREAMING_ONEVPL_ACCEL_TYPES_HPP + +#include +#include + +#include "opencv2/gapi/own/exports.hpp" // GAPI_EXPORTS + +namespace cv { +namespace gapi { +namespace wip { +namespace onevpl { + +enum class AccelType: uint8_t { + HOST, + DX11, + VAAPI, + + LAST_VALUE = std::numeric_limits::max() +}; + +GAPI_EXPORTS const char* to_cstring(AccelType type); + +struct IDeviceSelector; +struct GAPI_EXPORTS Device { + friend struct IDeviceSelector; + using Ptr = void*; + + ~Device(); + const std::string& get_name() const; + Ptr get_ptr() const; + AccelType get_type() const; +private: + Device(Ptr device_ptr, const std::string& device_name, + AccelType device_type); + + std::string name; + Ptr ptr; + AccelType type; +}; + +struct GAPI_EXPORTS Context { + friend struct IDeviceSelector; + using Ptr = void*; + + ~Context(); + Ptr get_ptr() const; + AccelType get_type() const; +private: + Context(Ptr ctx_ptr, AccelType ctx_type); + Ptr ptr; + AccelType type; +}; + +GAPI_EXPORTS Device create_host_device(); +GAPI_EXPORTS Context create_host_context(); + +GAPI_EXPORTS Device create_dx11_device(Device::Ptr device_ptr, + const std::string& device_name); +GAPI_EXPORTS Context create_dx11_context(Context::Ptr ctx_ptr); + +GAPI_EXPORTS Device create_vaapi_device(Device::Ptr device_ptr, + const std::string& device_name); +GAPI_EXPORTS Context create_vaapi_context(Context::Ptr ctx_ptr); +} // namespace onevpl +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // GAPI_STREAMING_ONEVPL_ACCEL_TYPES_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/cfg_params.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/cfg_params.hpp index 0db9a86e58..b55f88e617 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/cfg_params.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/cfg_params.hpp @@ -1,209 +1,209 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2021 Intel Corporation - -#ifndef OPENCV_GAPI_STREAMING_ONEVPL_CFG_PARAMS_HPP -#define OPENCV_GAPI_STREAMING_ONEVPL_CFG_PARAMS_HPP - -#include -#include -#include - -#include -#include - -namespace cv { -namespace gapi { -namespace wip { -namespace onevpl { - -/** - * @brief Public class is using for creation of onevpl::GSource instances. - * - * Class members available through methods @ref CfgParam::get_name() and @ref CfgParam::get_value() are used by - * onevpl::GSource inner logic to create or find oneVPL particular implementation - * (software/hardware, specific API version and etc.). - * - * @note Because oneVPL may provide several implementations which are satisfying with multiple (or single one) @ref CfgParam - * criteria therefore it is possible to configure `preferred` parameters. This kind of CfgParams are created - * using `is_major = false` argument in @ref CfgParam::create method and are not used by creating oneVPL particular implementations. - * Instead they fill out a "score table" to select preferable implementation from available list. Implementation are satisfying - * with most of these optional params would be chosen. - * If no one optional CfgParam params were present then first of available oneVPL implementation would be applied. - * Please get on https://spec.oneapi.io/versions/latest/elements/oneVPL/source/API_ref/VPL_disp_api_func.html?highlight=mfxcreateconfig#mfxsetconfigfilterproperty - * for using OneVPL configuration. In this schema `mfxU8 *name` represents @ref CfgParam::get_name() and - * `mfxVariant value` is @ref CfgParam::get_value() - */ -struct GAPI_EXPORTS CfgParam { - using name_t = std::string; - using value_t = cv::util::variant; - /** - * @brief frames_pool_size_name - * - * Special configuration parameter name for onevp::GSource: - * - * @note frames_pool_size_name allows to allocate surfaces pool appropriate size to keep - * decoded frames in accelerator memory ready before - * they would be consumed by onevp::GSource::pull operation. If you see - * a lot of WARNING about lack of free surface then it's time to increase - * frames_pool_size_name but be aware of accelerator free memory volume. - * If not set then MFX implementation use - * mfxFrameAllocRequest::NumFrameSuggested behavior - * - */ - static constexpr const char *frames_pool_size_name() { return "frames_pool_size"; } - static CfgParam create_frames_pool_size(size_t value); - - /** - * @brief acceleration_mode_name - * - * Special configuration parameter names for onevp::GSource: - * - * @note acceleration_mode_name allows to activate hardware acceleration & - * device memory management. - * Supported values: - * - MFX_ACCEL_MODE_VIA_D3D11 Will activate DX11 acceleration and will produces - * MediaFrames with data allocated in DX11 device memory - * - * If not set then MFX implementation will use default acceleration behavior: - * all decoding operation uses default GPU resources but MediaFrame produces - * data allocated by using host RAM - * - */ - static constexpr const char *acceleration_mode_name() { return "mfxImplDescription.AccelerationMode"; } - static CfgParam create_acceleration_mode(uint32_t value); - static CfgParam create_acceleration_mode(const char* value); - - /** - * @brief decoder_id_name - * - * Special configuration parameter names for onevp::GSource: - * - * @note decoder_id_name allows to specify VPL decoder type which MUST present - * in case of RAW video input data and MUST NOT present as CfgParam if video - * stream incapsulated into container(*.mp4, *.mkv and so on). In latter case - * onevp::GSource will determine it automatically - * Supported values: - * - MFX_CODEC_AVC - * - MFX_CODEC_HEVC - * - MFX_CODEC_MPEG2 - * - MFX_CODEC_VC1 - * - MFX_CODEC_CAPTURE - * - MFX_CODEC_VP9 - * - MFX_CODEC_AV1 - * - */ - static constexpr const char *decoder_id_name() { return "mfxImplDescription.mfxDecoderDescription.decoder.CodecID"; } - static CfgParam create_decoder_id(uint32_t value); - static CfgParam create_decoder_id(const char* value); - - static constexpr const char *implementation_name() { return "mfxImplDescription.Impl"; } - static CfgParam create_implementation(uint32_t value); - static CfgParam create_implementation(const char* value); - - - static constexpr const char *vpp_frames_pool_size_name() { return "vpp_frames_pool_size"; } - static CfgParam create_vpp_frames_pool_size(size_t value); - - static constexpr const char *vpp_in_width_name() { return "vpp.In.Width"; } - static CfgParam create_vpp_in_width(uint16_t value); - - static constexpr const char *vpp_in_height_name() { return "vpp.In.Height"; } - static CfgParam create_vpp_in_height(uint16_t value); - - static constexpr const char *vpp_in_crop_x_name() { return "vpp.In.CropX"; } - static CfgParam create_vpp_in_crop_x(uint16_t value); - - static constexpr const char *vpp_in_crop_y_name() { return "vpp.In.CropY"; } - static CfgParam create_vpp_in_crop_y(uint16_t value); - - static constexpr const char *vpp_in_crop_w_name() { return "vpp.In.CropW"; } - static CfgParam create_vpp_in_crop_w(uint16_t value); - - static constexpr const char *vpp_in_crop_h_name() { return "vpp.In.CropH"; } - static CfgParam create_vpp_in_crop_h(uint16_t value); - - - static constexpr const char *vpp_out_fourcc_name() { return "vpp.Out.FourCC"; } - static CfgParam create_vpp_out_fourcc(uint32_t value); - - static constexpr const char *vpp_out_chroma_format_name() { return "vpp.Out.ChromaFormat"; } - static CfgParam create_vpp_out_chroma_format(uint16_t value); - - static constexpr const char *vpp_out_width_name() { return "vpp.Out.Width"; } - static CfgParam create_vpp_out_width(uint16_t value); - - static constexpr const char *vpp_out_height_name() { return "vpp.Out.Height"; } - static CfgParam create_vpp_out_height(uint16_t value); - - static constexpr const char *vpp_out_crop_x_name() { return "vpp.Out.CropX"; } - static CfgParam create_vpp_out_crop_x(uint16_t value); - - static constexpr const char *vpp_out_crop_y_name() { return "vpp.Out.CropY"; } - static CfgParam create_vpp_out_crop_y(uint16_t value); - - static constexpr const char *vpp_out_crop_w_name() { return "vpp.Out.CropW"; } - static CfgParam create_vpp_out_crop_w(uint16_t value); - - static constexpr const char *vpp_out_crop_h_name() { return "vpp.Out.CropH"; } - static CfgParam create_vpp_out_crop_h(uint16_t value); - - static constexpr const char *vpp_out_pic_struct_name() { return "vpp.Out.PicStruct"; } - static CfgParam create_vpp_out_pic_struct(uint16_t value); - - static constexpr const char *vpp_out_framerate_n_name() { return "vpp.Out.FrameRateExtN"; } - static CfgParam create_vpp_out_framerate_n(uint32_t value); - - static constexpr const char *vpp_out_framerate_d_name() { return "vpp.Out.FrameRateExtD"; } - static CfgParam create_vpp_out_framerate_d(uint32_t value); - - /** - * Create generic onevp::GSource configuration parameter. - * - *@param name name of parameter. - *@param value value of parameter. - *@param is_major TRUE if parameter MUST be provided by OneVPL inner implementation, FALSE for optional (for resolve multiple available implementations). - * - */ - template - static CfgParam create(const std::string& name, ValueType&& value, bool is_major = true) { - CfgParam param(name, CfgParam::value_t(std::forward(value)), is_major); - return param; - } - - struct Priv; - - const name_t& get_name() const; - const value_t& get_value() const; - bool is_major() const; - std::string to_string() const; - - bool operator==(const CfgParam& rhs) const; - bool operator< (const CfgParam& rhs) const; - bool operator!=(const CfgParam& rhs) const; - - CfgParam& operator=(const CfgParam& src); - CfgParam& operator=(CfgParam&& src); - CfgParam(const CfgParam& src); - CfgParam(CfgParam&& src); - ~CfgParam(); -private: - CfgParam(const std::string& param_name, value_t&& param_value, bool is_major_param); - std::shared_ptr m_priv; -}; - -} //namespace onevpl -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_STREAMING_ONEVPL_CFG_PARAMS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2021 Intel Corporation + +#ifndef OPENCV_GAPI_STREAMING_ONEVPL_CFG_PARAMS_HPP +#define OPENCV_GAPI_STREAMING_ONEVPL_CFG_PARAMS_HPP + +#include +#include +#include + +#include +#include + +namespace cv { +namespace gapi { +namespace wip { +namespace onevpl { + +/** + * @brief Public class is using for creation of onevpl::GSource instances. + * + * Class members available through methods @ref CfgParam::get_name() and @ref CfgParam::get_value() are used by + * onevpl::GSource inner logic to create or find oneVPL particular implementation + * (software/hardware, specific API version and etc.). + * + * @note Because oneVPL may provide several implementations which are satisfying with multiple (or single one) @ref CfgParam + * criteria therefore it is possible to configure `preferred` parameters. This kind of CfgParams are created + * using `is_major = false` argument in @ref CfgParam::create method and are not used by creating oneVPL particular implementations. + * Instead they fill out a "score table" to select preferable implementation from available list. Implementation are satisfying + * with most of these optional params would be chosen. + * If no one optional CfgParam params were present then first of available oneVPL implementation would be applied. + * Please get on https://spec.oneapi.io/versions/latest/elements/oneVPL/source/API_ref/VPL_disp_api_func.html?highlight=mfxcreateconfig#mfxsetconfigfilterproperty + * for using OneVPL configuration. In this schema `mfxU8 *name` represents @ref CfgParam::get_name() and + * `mfxVariant value` is @ref CfgParam::get_value() + */ +struct GAPI_EXPORTS CfgParam { + using name_t = std::string; + using value_t = cv::util::variant; + /** + * @brief frames_pool_size_name + * + * Special configuration parameter name for onevp::GSource: + * + * @note frames_pool_size_name allows to allocate surfaces pool appropriate size to keep + * decoded frames in accelerator memory ready before + * they would be consumed by onevp::GSource::pull operation. If you see + * a lot of WARNING about lack of free surface then it's time to increase + * frames_pool_size_name but be aware of accelerator free memory volume. + * If not set then MFX implementation use + * mfxFrameAllocRequest::NumFrameSuggested behavior + * + */ + static constexpr const char *frames_pool_size_name() { return "frames_pool_size"; } + static CfgParam create_frames_pool_size(size_t value); + + /** + * @brief acceleration_mode_name + * + * Special configuration parameter names for onevp::GSource: + * + * @note acceleration_mode_name allows to activate hardware acceleration & + * device memory management. + * Supported values: + * - MFX_ACCEL_MODE_VIA_D3D11 Will activate DX11 acceleration and will produces + * MediaFrames with data allocated in DX11 device memory + * + * If not set then MFX implementation will use default acceleration behavior: + * all decoding operation uses default GPU resources but MediaFrame produces + * data allocated by using host RAM + * + */ + static constexpr const char *acceleration_mode_name() { return "mfxImplDescription.AccelerationMode"; } + static CfgParam create_acceleration_mode(uint32_t value); + static CfgParam create_acceleration_mode(const char* value); + + /** + * @brief decoder_id_name + * + * Special configuration parameter names for onevp::GSource: + * + * @note decoder_id_name allows to specify VPL decoder type which MUST present + * in case of RAW video input data and MUST NOT present as CfgParam if video + * stream incapsulated into container(*.mp4, *.mkv and so on). In latter case + * onevp::GSource will determine it automatically + * Supported values: + * - MFX_CODEC_AVC + * - MFX_CODEC_HEVC + * - MFX_CODEC_MPEG2 + * - MFX_CODEC_VC1 + * - MFX_CODEC_CAPTURE + * - MFX_CODEC_VP9 + * - MFX_CODEC_AV1 + * + */ + static constexpr const char *decoder_id_name() { return "mfxImplDescription.mfxDecoderDescription.decoder.CodecID"; } + static CfgParam create_decoder_id(uint32_t value); + static CfgParam create_decoder_id(const char* value); + + static constexpr const char *implementation_name() { return "mfxImplDescription.Impl"; } + static CfgParam create_implementation(uint32_t value); + static CfgParam create_implementation(const char* value); + + + static constexpr const char *vpp_frames_pool_size_name() { return "vpp_frames_pool_size"; } + static CfgParam create_vpp_frames_pool_size(size_t value); + + static constexpr const char *vpp_in_width_name() { return "vpp.In.Width"; } + static CfgParam create_vpp_in_width(uint16_t value); + + static constexpr const char *vpp_in_height_name() { return "vpp.In.Height"; } + static CfgParam create_vpp_in_height(uint16_t value); + + static constexpr const char *vpp_in_crop_x_name() { return "vpp.In.CropX"; } + static CfgParam create_vpp_in_crop_x(uint16_t value); + + static constexpr const char *vpp_in_crop_y_name() { return "vpp.In.CropY"; } + static CfgParam create_vpp_in_crop_y(uint16_t value); + + static constexpr const char *vpp_in_crop_w_name() { return "vpp.In.CropW"; } + static CfgParam create_vpp_in_crop_w(uint16_t value); + + static constexpr const char *vpp_in_crop_h_name() { return "vpp.In.CropH"; } + static CfgParam create_vpp_in_crop_h(uint16_t value); + + + static constexpr const char *vpp_out_fourcc_name() { return "vpp.Out.FourCC"; } + static CfgParam create_vpp_out_fourcc(uint32_t value); + + static constexpr const char *vpp_out_chroma_format_name() { return "vpp.Out.ChromaFormat"; } + static CfgParam create_vpp_out_chroma_format(uint16_t value); + + static constexpr const char *vpp_out_width_name() { return "vpp.Out.Width"; } + static CfgParam create_vpp_out_width(uint16_t value); + + static constexpr const char *vpp_out_height_name() { return "vpp.Out.Height"; } + static CfgParam create_vpp_out_height(uint16_t value); + + static constexpr const char *vpp_out_crop_x_name() { return "vpp.Out.CropX"; } + static CfgParam create_vpp_out_crop_x(uint16_t value); + + static constexpr const char *vpp_out_crop_y_name() { return "vpp.Out.CropY"; } + static CfgParam create_vpp_out_crop_y(uint16_t value); + + static constexpr const char *vpp_out_crop_w_name() { return "vpp.Out.CropW"; } + static CfgParam create_vpp_out_crop_w(uint16_t value); + + static constexpr const char *vpp_out_crop_h_name() { return "vpp.Out.CropH"; } + static CfgParam create_vpp_out_crop_h(uint16_t value); + + static constexpr const char *vpp_out_pic_struct_name() { return "vpp.Out.PicStruct"; } + static CfgParam create_vpp_out_pic_struct(uint16_t value); + + static constexpr const char *vpp_out_framerate_n_name() { return "vpp.Out.FrameRateExtN"; } + static CfgParam create_vpp_out_framerate_n(uint32_t value); + + static constexpr const char *vpp_out_framerate_d_name() { return "vpp.Out.FrameRateExtD"; } + static CfgParam create_vpp_out_framerate_d(uint32_t value); + + /** + * Create generic onevp::GSource configuration parameter. + * + *@param name name of parameter. + *@param value value of parameter. + *@param is_major TRUE if parameter MUST be provided by OneVPL inner implementation, FALSE for optional (for resolve multiple available implementations). + * + */ + template + static CfgParam create(const std::string& name, ValueType&& value, bool is_major = true) { + CfgParam param(name, CfgParam::value_t(std::forward(value)), is_major); + return param; + } + + struct Priv; + + const name_t& get_name() const; + const value_t& get_value() const; + bool is_major() const; + std::string to_string() const; + + bool operator==(const CfgParam& rhs) const; + bool operator< (const CfgParam& rhs) const; + bool operator!=(const CfgParam& rhs) const; + + CfgParam& operator=(const CfgParam& src); + CfgParam& operator=(CfgParam&& src); + CfgParam(const CfgParam& src); + CfgParam(CfgParam&& src); + ~CfgParam(); +private: + CfgParam(const std::string& param_name, value_t&& param_value, bool is_major_param); + std::shared_ptr m_priv; +}; + +} //namespace onevpl +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_STREAMING_ONEVPL_CFG_PARAMS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/data_provider_interface.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/data_provider_interface.hpp index ec683a7527..89f1b1a330 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/data_provider_interface.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/data_provider_interface.hpp @@ -1,105 +1,105 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2021 Intel Corporation - -#ifndef GAPI_STREAMING_ONEVPL_ONEVPL_DATA_PROVIDER_INTERFACE_HPP -#define GAPI_STREAMING_ONEVPL_ONEVPL_DATA_PROVIDER_INTERFACE_HPP -#include -#include -#include - -#include // GAPI_EXPORTS -namespace cv { -namespace gapi { -namespace wip { -namespace onevpl { - -struct GAPI_EXPORTS DataProviderException : public std::exception { - DataProviderException(const std::string& descr); - DataProviderException(std::string&& descr); - - virtual ~DataProviderException() = default; - virtual const char* what() const noexcept override; -private: - std::string reason; -}; - -struct GAPI_EXPORTS DataProviderSystemErrorException final : public DataProviderException { - DataProviderSystemErrorException(int error_code, const std::string& description = std::string()); - ~DataProviderSystemErrorException() = default; -}; - -struct GAPI_EXPORTS DataProviderUnsupportedException final : public DataProviderException { - DataProviderUnsupportedException(const std::string& description); - ~DataProviderUnsupportedException() = default; -}; - -struct GAPI_EXPORTS DataProviderImplementationException : public DataProviderException { - DataProviderImplementationException(const std::string& description); - ~DataProviderImplementationException() = default; -}; -/** - * @brief Public interface allows to customize extraction of video stream data - * used by onevpl::GSource instead of reading stream from file (by default). - * - * Interface implementation constructor MUST provide consistency and creates fully operable object. - * If error happened implementation MUST throw `DataProviderException` kind exceptions - * - * @note Interface implementation MUST manage stream and other constructed resources by itself to avoid any kind of leak. - * For simple interface implementation example please see `StreamDataProvider` in `tests/streaming/gapi_streaming_tests.cpp` - */ -struct GAPI_EXPORTS IDataProvider { - using Ptr = std::shared_ptr; - using mfx_codec_id_type = uint32_t; - - /** - * NB: here is supposed to be forward declaration of mfxBitstream - * But according to current oneVPL implementation it is impossible to forward - * declare untagged struct mfxBitstream. - * - * IDataProvider makes sense only for HAVE_VPL is ON and to keep IDataProvider - * interface API/ABI compliant between core library and user application layer - * let's introduce wrapper mfx_bitstream which inherits mfxBitstream in private - * G-API code section and declare forward for wrapper mfx_bitstream here - */ - struct mfx_bitstream; - - virtual ~IDataProvider() = default; - - /** - * The function is used by onevpl::GSource to extract codec id from data - * - */ - virtual mfx_codec_id_type get_mfx_codec_id() const = 0; - - /** - * The function is used by onevpl::GSource to extract binary data stream from @ref IDataProvider - * implementation. - * - * It MUST throw `DataProviderException` kind exceptions in fail cases. - * It MUST return MFX_ERR_MORE_DATA in EOF which considered as not-fail case. - * - * @param in_out_bitsream the input-output reference on MFX bitstream buffer which MUST be empty at the first request - * to allow implementation to allocate it by itself and to return back. Subsequent invocation of `fetch_bitstream_data` - * MUST use the previously used in_out_bitsream to avoid skipping rest of frames which haven't been consumed - * @return true for fetched data, false on EOF and throws exception on error - */ - virtual bool fetch_bitstream_data(std::shared_ptr &in_out_bitsream) = 0; - - /** - * The function is used by onevpl::GSource to check more binary data availability. - * - * It MUST return TRUE in case of EOF and NO_THROW exceptions. - * - * @return boolean value which detects end of stream - */ - virtual bool empty() const = 0; -}; -} // namespace onevpl -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // GAPI_STREAMING_ONEVPL_ONEVPL_DATA_PROVIDER_INTERFACE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2021 Intel Corporation + +#ifndef GAPI_STREAMING_ONEVPL_ONEVPL_DATA_PROVIDER_INTERFACE_HPP +#define GAPI_STREAMING_ONEVPL_ONEVPL_DATA_PROVIDER_INTERFACE_HPP +#include +#include +#include + +#include // GAPI_EXPORTS +namespace cv { +namespace gapi { +namespace wip { +namespace onevpl { + +struct GAPI_EXPORTS DataProviderException : public std::exception { + DataProviderException(const std::string& descr); + DataProviderException(std::string&& descr); + + virtual ~DataProviderException() = default; + virtual const char* what() const noexcept override; +private: + std::string reason; +}; + +struct GAPI_EXPORTS DataProviderSystemErrorException final : public DataProviderException { + DataProviderSystemErrorException(int error_code, const std::string& description = std::string()); + ~DataProviderSystemErrorException() = default; +}; + +struct GAPI_EXPORTS DataProviderUnsupportedException final : public DataProviderException { + DataProviderUnsupportedException(const std::string& description); + ~DataProviderUnsupportedException() = default; +}; + +struct GAPI_EXPORTS DataProviderImplementationException : public DataProviderException { + DataProviderImplementationException(const std::string& description); + ~DataProviderImplementationException() = default; +}; +/** + * @brief Public interface allows to customize extraction of video stream data + * used by onevpl::GSource instead of reading stream from file (by default). + * + * Interface implementation constructor MUST provide consistency and creates fully operable object. + * If error happened implementation MUST throw `DataProviderException` kind exceptions + * + * @note Interface implementation MUST manage stream and other constructed resources by itself to avoid any kind of leak. + * For simple interface implementation example please see `StreamDataProvider` in `tests/streaming/gapi_streaming_tests.cpp` + */ +struct GAPI_EXPORTS IDataProvider { + using Ptr = std::shared_ptr; + using mfx_codec_id_type = uint32_t; + + /** + * NB: here is supposed to be forward declaration of mfxBitstream + * But according to current oneVPL implementation it is impossible to forward + * declare untagged struct mfxBitstream. + * + * IDataProvider makes sense only for HAVE_VPL is ON and to keep IDataProvider + * interface API/ABI compliant between core library and user application layer + * let's introduce wrapper mfx_bitstream which inherits mfxBitstream in private + * G-API code section and declare forward for wrapper mfx_bitstream here + */ + struct mfx_bitstream; + + virtual ~IDataProvider() = default; + + /** + * The function is used by onevpl::GSource to extract codec id from data + * + */ + virtual mfx_codec_id_type get_mfx_codec_id() const = 0; + + /** + * The function is used by onevpl::GSource to extract binary data stream from @ref IDataProvider + * implementation. + * + * It MUST throw `DataProviderException` kind exceptions in fail cases. + * It MUST return MFX_ERR_MORE_DATA in EOF which considered as not-fail case. + * + * @param in_out_bitsream the input-output reference on MFX bitstream buffer which MUST be empty at the first request + * to allow implementation to allocate it by itself and to return back. Subsequent invocation of `fetch_bitstream_data` + * MUST use the previously used in_out_bitsream to avoid skipping rest of frames which haven't been consumed + * @return true for fetched data, false on EOF and throws exception on error + */ + virtual bool fetch_bitstream_data(std::shared_ptr &in_out_bitsream) = 0; + + /** + * The function is used by onevpl::GSource to check more binary data availability. + * + * It MUST return TRUE in case of EOF and NO_THROW exceptions. + * + * @return boolean value which detects end of stream + */ + virtual bool empty() const = 0; +}; +} // namespace onevpl +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // GAPI_STREAMING_ONEVPL_ONEVPL_DATA_PROVIDER_INTERFACE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/default.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/default.hpp index 8b547e1aba..4bb099fb3c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/default.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/default.hpp @@ -1,29 +1,29 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2022 Intel Corporation - -#ifndef OPENCV_GAPI_STREAMING_ONEVPL_UTILS_HPP -#define OPENCV_GAPI_STREAMING_ONEVPL_UTILS_HPP - -#include // GAPI_EXPORTS -#include -#include - -namespace cv { -namespace gapi { -namespace wip { -namespace onevpl { - -/** - * @brief Provides default device selector based on config. - */ -GAPI_EXPORTS std::shared_ptr getDefaultDeviceSelector(const std::vector& cfg_params); - -} // namespace onevpl -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_STREAMING_ONEVPL_UTILS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2022 Intel Corporation + +#ifndef OPENCV_GAPI_STREAMING_ONEVPL_UTILS_HPP +#define OPENCV_GAPI_STREAMING_ONEVPL_UTILS_HPP + +#include // GAPI_EXPORTS +#include +#include + +namespace cv { +namespace gapi { +namespace wip { +namespace onevpl { + +/** + * @brief Provides default device selector based on config. + */ +GAPI_EXPORTS std::shared_ptr getDefaultDeviceSelector(const std::vector& cfg_params); + +} // namespace onevpl +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_STREAMING_ONEVPL_UTILS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/device_selector_interface.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/device_selector_interface.hpp index 2e2d879fba..3cde3e4483 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/device_selector_interface.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/device_selector_interface.hpp @@ -1,61 +1,61 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2021 Intel Corporation - -#ifndef GAPI_STREAMING_ONEVPL_DEVICE_SELECTOR_INTERFACE_HPP -#define GAPI_STREAMING_ONEVPL_DEVICE_SELECTOR_INTERFACE_HPP - -#include -#include -#include -#include - -#include - -namespace cv { -namespace gapi { -namespace wip { -namespace onevpl { -struct GAPI_EXPORTS IDeviceSelector { - using Ptr = std::shared_ptr; - - struct GAPI_EXPORTS Score { - friend struct IDeviceSelector; - using Type = int16_t; - static constexpr Type MaxActivePriority = std::numeric_limits::max(); - static constexpr Type MinActivePriority = 0; - static constexpr Type MaxPassivePriority = MinActivePriority - 1; - static constexpr Type MinPassivePriority = std::numeric_limits::min(); - - Score(Type val); - ~Score(); - - operator Type () const; - Type get() const; - friend bool operator< (Score lhs, Score rhs) { - return lhs.get() < rhs.get(); - } - private: - Type value; - }; - - using DeviceScoreTable = std::map; - using DeviceContexts = std::vector; - - virtual ~IDeviceSelector(); - virtual DeviceScoreTable select_devices() const = 0; - virtual DeviceContexts select_context() = 0; -protected: - template - static Entity create(Args &&...args) { - return Entity(std::forward(args)...); - } -}; -} // namespace onevpl -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // GAPI_STREAMING_ONEVPL_DEVICE_SELECTOR_INTERFACE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2021 Intel Corporation + +#ifndef GAPI_STREAMING_ONEVPL_DEVICE_SELECTOR_INTERFACE_HPP +#define GAPI_STREAMING_ONEVPL_DEVICE_SELECTOR_INTERFACE_HPP + +#include +#include +#include +#include + +#include + +namespace cv { +namespace gapi { +namespace wip { +namespace onevpl { +struct GAPI_EXPORTS IDeviceSelector { + using Ptr = std::shared_ptr; + + struct GAPI_EXPORTS Score { + friend struct IDeviceSelector; + using Type = int16_t; + static constexpr Type MaxActivePriority = std::numeric_limits::max(); + static constexpr Type MinActivePriority = 0; + static constexpr Type MaxPassivePriority = MinActivePriority - 1; + static constexpr Type MinPassivePriority = std::numeric_limits::min(); + + Score(Type val); + ~Score(); + + operator Type () const; + Type get() const; + friend bool operator< (Score lhs, Score rhs) { + return lhs.get() < rhs.get(); + } + private: + Type value; + }; + + using DeviceScoreTable = std::map; + using DeviceContexts = std::vector; + + virtual ~IDeviceSelector(); + virtual DeviceScoreTable select_devices() const = 0; + virtual DeviceContexts select_context() = 0; +protected: + template + static Entity create(Args &&...args) { + return Entity(std::forward(args)...); + } +}; +} // namespace onevpl +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // GAPI_STREAMING_ONEVPL_DEVICE_SELECTOR_INTERFACE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/source.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/source.hpp index 04dc2e246d..4d1fa2aad7 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/source.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/source.hpp @@ -1,94 +1,94 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2021 Intel Corporation - -#ifndef OPENCV_GAPI_STREAMING_ONEVPL_ONEVPL_SOURCE_HPP -#define OPENCV_GAPI_STREAMING_ONEVPL_ONEVPL_SOURCE_HPP - -#include -#include -#include -#include -#include -#include - -namespace cv { -namespace gapi { -namespace wip { -namespace onevpl { -using CfgParams = std::vector; - -/** - * @brief G-API streaming source based on OneVPL implementation. - * - * This class implements IStreamSource interface. - * Its constructor takes source file path (in usual way) or @ref onevpl::IDataProvider - * interface implementation (for not file-based sources). It also allows to pass-through - * oneVPL configuration parameters by using several @ref onevpl::CfgParam. - * - * @note stream sources are passed to G-API via shared pointers, so - * please gapi::make_onevpl_src<> to create objects and ptr() to pass a - * GSource to cv::gin(). - */ -class GAPI_EXPORTS GSource : public IStreamSource -{ -public: - struct Priv; - - GSource(const std::string& filePath, - const CfgParams& cfg_params = CfgParams{}); - - GSource(const std::string& filePath, - const CfgParams& cfg_params, - const std::string& device_id, - void* accel_device_ptr, - void* accel_ctx_ptr); - - GSource(const std::string& filePath, - const CfgParams& cfg_params, - const Device &device, const Context &ctx); - - GSource(const std::string& filePath, - const CfgParams& cfg_params, - std::shared_ptr selector); - - - GSource(std::shared_ptr source, - const CfgParams& cfg_params = CfgParams{}); - - GSource(std::shared_ptr source, - const CfgParams& cfg_params, - const std::string& device_id, - void* accel_device_ptr, - void* accel_ctx_ptr); - - GSource(std::shared_ptr source, - const CfgParams& cfg_params, - std::shared_ptr selector); - - ~GSource() override; - - bool pull(cv::gapi::wip::Data& data) override; - GMetaArg descr_of() const override; - -private: - explicit GSource(std::unique_ptr&& impl); - std::unique_ptr m_priv; -}; -} // namespace onevpl - -using GVPLSource = onevpl::GSource; - -template -GAPI_EXPORTS_W cv::Ptr inline make_onevpl_src(Args&&... args) -{ - return make_src(std::forward(args)...); -} - -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_STREAMING_ONEVPL_ONEVPL_SOURCE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2021 Intel Corporation + +#ifndef OPENCV_GAPI_STREAMING_ONEVPL_ONEVPL_SOURCE_HPP +#define OPENCV_GAPI_STREAMING_ONEVPL_ONEVPL_SOURCE_HPP + +#include +#include +#include +#include +#include +#include + +namespace cv { +namespace gapi { +namespace wip { +namespace onevpl { +using CfgParams = std::vector; + +/** + * @brief G-API streaming source based on OneVPL implementation. + * + * This class implements IStreamSource interface. + * Its constructor takes source file path (in usual way) or @ref onevpl::IDataProvider + * interface implementation (for not file-based sources). It also allows to pass-through + * oneVPL configuration parameters by using several @ref onevpl::CfgParam. + * + * @note stream sources are passed to G-API via shared pointers, so + * please gapi::make_onevpl_src<> to create objects and ptr() to pass a + * GSource to cv::gin(). + */ +class GAPI_EXPORTS GSource : public IStreamSource +{ +public: + struct Priv; + + GSource(const std::string& filePath, + const CfgParams& cfg_params = CfgParams{}); + + GSource(const std::string& filePath, + const CfgParams& cfg_params, + const std::string& device_id, + void* accel_device_ptr, + void* accel_ctx_ptr); + + GSource(const std::string& filePath, + const CfgParams& cfg_params, + const Device &device, const Context &ctx); + + GSource(const std::string& filePath, + const CfgParams& cfg_params, + std::shared_ptr selector); + + + GSource(std::shared_ptr source, + const CfgParams& cfg_params = CfgParams{}); + + GSource(std::shared_ptr source, + const CfgParams& cfg_params, + const std::string& device_id, + void* accel_device_ptr, + void* accel_ctx_ptr); + + GSource(std::shared_ptr source, + const CfgParams& cfg_params, + std::shared_ptr selector); + + ~GSource() override; + + bool pull(cv::gapi::wip::Data& data) override; + GMetaArg descr_of() const override; + +private: + explicit GSource(std::unique_ptr&& impl); + std::unique_ptr m_priv; +}; +} // namespace onevpl + +using GVPLSource = onevpl::GSource; + +template +GAPI_EXPORTS_W cv::Ptr inline make_onevpl_src(Args&&... args) +{ + return make_src(std::forward(args)...); +} + +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_STREAMING_ONEVPL_ONEVPL_SOURCE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/queue_source.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/queue_source.hpp index bd385ed16e..e01902fd7f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/queue_source.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/queue_source.hpp @@ -1,67 +1,67 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2023 Intel Corporation - -#ifndef OPENCV_GAPI_STREAMING_QUEUE_SOURCE_HPP -#define OPENCV_GAPI_STREAMING_QUEUE_SOURCE_HPP - -#include // shared_ptr -#include // is_base_of - -#include // GRunArgs -#include // GMetaArg + all descr_of -#include // IStreamSource - -namespace cv { -namespace gapi { -namespace wip { -struct Data; // fwd-declare to avoid circular? header dependencies - -class GAPI_EXPORTS QueueSourceBase: public cv::gapi::wip::IStreamSource { - class Priv; - std::shared_ptr m_priv; - // FIXME: Need to understand how it works with IStreamSource's shared_from_this - // Can we avoid having too many shared_ptrs here? - -public: - explicit QueueSourceBase(const cv::GMetaArg &m); - void push(Data &&data); - virtual bool pull(Data &data) override; - virtual void halt() override; - virtual GMetaArg descr_of() const override; - virtual ~QueueSourceBase() = default; -}; - -/** - * @brief Queued streaming pipeline source. - * - */ -template -class QueueSource final: public QueueSourceBase -{ -public: - using Meta = decltype(cv::descr_of(T{})); - explicit QueueSource(Meta m) : QueueSourceBase(GMetaArg{m}) { - } - void push(T t) { - QueueSourceBase::push(Data{t}); - } -}; - -class GAPI_EXPORTS QueueInput { - std::vector > m_sources; - -public: - explicit QueueInput(const cv::GMetaArgs &args); - - void push(cv::GRunArgs &&ins); - operator cv::GRunArgs(); -}; - -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_STREAMING_SOURCE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2023 Intel Corporation + +#ifndef OPENCV_GAPI_STREAMING_QUEUE_SOURCE_HPP +#define OPENCV_GAPI_STREAMING_QUEUE_SOURCE_HPP + +#include // shared_ptr +#include // is_base_of + +#include // GRunArgs +#include // GMetaArg + all descr_of +#include // IStreamSource + +namespace cv { +namespace gapi { +namespace wip { +struct Data; // fwd-declare to avoid circular? header dependencies + +class GAPI_EXPORTS QueueSourceBase: public cv::gapi::wip::IStreamSource { + class Priv; + std::shared_ptr m_priv; + // FIXME: Need to understand how it works with IStreamSource's shared_from_this + // Can we avoid having too many shared_ptrs here? + +public: + explicit QueueSourceBase(const cv::GMetaArg &m); + void push(Data &&data); + virtual bool pull(Data &data) override; + virtual void halt() override; + virtual GMetaArg descr_of() const override; + virtual ~QueueSourceBase() = default; +}; + +/** + * @brief Queued streaming pipeline source. + * + */ +template +class QueueSource final: public QueueSourceBase +{ +public: + using Meta = decltype(cv::descr_of(T{})); + explicit QueueSource(Meta m) : QueueSourceBase(GMetaArg{m}) { + } + void push(T t) { + QueueSourceBase::push(Data{t}); + } +}; + +class GAPI_EXPORTS QueueInput { + std::vector > m_sources; + +public: + explicit QueueInput(const cv::GMetaArgs &args); + + void push(cv::GRunArgs &&ins); + operator cv::GRunArgs(); +}; + +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_STREAMING_SOURCE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/source.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/source.hpp index 267469ad1b..9b02f03ffc 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/source.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/source.hpp @@ -1,67 +1,67 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019 Intel Corporation - -#ifndef OPENCV_GAPI_STREAMING_SOURCE_HPP -#define OPENCV_GAPI_STREAMING_SOURCE_HPP - -#include // shared_ptr -#include // is_base_of - -#include // GMetaArg - - -namespace cv { -namespace gapi { -namespace wip { -struct Data; // forward-declaration of Data to avoid circular dependencies - -/** - * @brief Abstract streaming pipeline source. - * - * Implement this interface if you want customize the way how data is - * streaming into GStreamingCompiled. - * - * Objects implementing this interface can be passed to - * GStreamingCompiled using setSource() with cv::gin(). Regular - * compiled graphs (GCompiled) don't support input objects of this - * type. - * - * Default cv::VideoCapture-based implementation is available, see - * cv::gapi::wip::GCaptureSource. - * - * @note stream sources are passed to G-API via shared pointers, so - * please use ptr() when passing a IStreamSource implementation to - * cv::gin(). - */ -class IStreamSource: public std::enable_shared_from_this -{ -public: - using Ptr = std::shared_ptr; - Ptr ptr() { return shared_from_this(); } - virtual bool pull(Data &data) = 0; - virtual GMetaArg descr_of() const = 0; - virtual void halt() { - // Do nothing by default to maintain compatibility with the existing sources... - // In fact needs to be decorated atop of the child classes to maintain the behavior - // FIXME: Make it mandatory in OpenCV 5.0 - }; - virtual ~IStreamSource() = default; -}; - -template -IStreamSource::Ptr inline make_src(Args&&... args) -{ - static_assert(std::is_base_of::value, - "T must implement the cv::gapi::IStreamSource interface!"); - auto src_ptr = std::make_shared(std::forward(args)...); - return src_ptr->ptr(); -} - -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_STREAMING_SOURCE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019 Intel Corporation + +#ifndef OPENCV_GAPI_STREAMING_SOURCE_HPP +#define OPENCV_GAPI_STREAMING_SOURCE_HPP + +#include // shared_ptr +#include // is_base_of + +#include // GMetaArg + + +namespace cv { +namespace gapi { +namespace wip { +struct Data; // forward-declaration of Data to avoid circular dependencies + +/** + * @brief Abstract streaming pipeline source. + * + * Implement this interface if you want customize the way how data is + * streaming into GStreamingCompiled. + * + * Objects implementing this interface can be passed to + * GStreamingCompiled using setSource() with cv::gin(). Regular + * compiled graphs (GCompiled) don't support input objects of this + * type. + * + * Default cv::VideoCapture-based implementation is available, see + * cv::gapi::wip::GCaptureSource. + * + * @note stream sources are passed to G-API via shared pointers, so + * please use ptr() when passing a IStreamSource implementation to + * cv::gin(). + */ +class IStreamSource: public std::enable_shared_from_this +{ +public: + using Ptr = std::shared_ptr; + Ptr ptr() { return shared_from_this(); } + virtual bool pull(Data &data) = 0; + virtual GMetaArg descr_of() const = 0; + virtual void halt() { + // Do nothing by default to maintain compatibility with the existing sources... + // In fact needs to be decorated atop of the child classes to maintain the behavior + // FIXME: Make it mandatory in OpenCV 5.0 + }; + virtual ~IStreamSource() = default; +}; + +template +IStreamSource::Ptr inline make_src(Args&&... args) +{ + static_assert(std::is_base_of::value, + "T must implement the cv::gapi::IStreamSource interface!"); + auto src_ptr = std::make_shared(std::forward(args)...); + return src_ptr->ptr(); +} + +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_STREAMING_SOURCE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/sync.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/sync.hpp index 5801e6f00a..921a96c7cb 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/sync.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/sync.hpp @@ -1,30 +1,30 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2021 Intel Corporation - -#ifndef OPENCV_GAPI_STREAMING_SYNC_HPP -#define OPENCV_GAPI_STREAMING_SYNC_HPP - -namespace cv { -namespace gapi { -namespace streaming { - -enum class sync_policy { - dont_sync, - drop -}; - -} // namespace streaming -} // namespace gapi - -namespace detail { - template<> struct CompileArgTag { - static const char* tag() { return "gapi.streaming.sync_policy"; } - }; - -} // namespace detail -} // namespace cv - -#endif // OPENCV_GAPI_STREAMING_SYNC_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2021 Intel Corporation + +#ifndef OPENCV_GAPI_STREAMING_SYNC_HPP +#define OPENCV_GAPI_STREAMING_SYNC_HPP + +namespace cv { +namespace gapi { +namespace streaming { + +enum class sync_policy { + dont_sync, + drop +}; + +} // namespace streaming +} // namespace gapi + +namespace detail { + template<> struct CompileArgTag { + static const char* tag() { return "gapi.streaming.sync_policy"; } + }; + +} // namespace detail +} // namespace cv + +#endif // OPENCV_GAPI_STREAMING_SYNC_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/util/any.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/util/any.hpp index 94451c7717..d5c575ca0a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/util/any.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/util/any.hpp @@ -1,190 +1,190 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_UTIL_ANY_HPP -#define OPENCV_GAPI_UTIL_ANY_HPP - -#include -#include -#include -#include - -#include - -#if defined(_MSC_VER) - // disable MSVC warning on "multiple copy constructors specified" -# pragma warning(disable: 4521) -#endif - -namespace cv -{ - -namespace internal -{ - template - T down_cast(Source operand) - { -#if defined(__GXX_RTTI) || defined(_CPPRTTI) - return dynamic_cast(operand); -#else -#ifdef __GNUC__ -#warning used static cast instead of dynamic because RTTI is disabled -#else -#pragma message("WARNING: used static cast instead of dynamic because RTTI is disabled") -#endif - return static_cast(operand); -#endif - } -} - -namespace util -{ - class bad_any_cast : public std::bad_cast - { - public: - virtual const char* what() const noexcept override - { - return "Bad any cast"; - } - }; - - //modeled against C++17 std::any - - class any - { - private: - struct holder; - using holder_ptr = std::unique_ptr; - struct holder - { - virtual holder_ptr clone() = 0; - virtual ~holder() = default; - }; - - template - struct holder_impl : holder - { - value_t v; - template - holder_impl(arg_t&& a) : v(std::forward(a)) {} - holder_ptr clone() override { return holder_ptr(new holder_impl (v));} - }; - - holder_ptr hldr; - public: - template - any(value_t&& arg) : hldr(new holder_impl::type>( std::forward(arg))) {} - - any(any const& src) : hldr( src.hldr ? src.hldr->clone() : nullptr) {} - //simple hack in order not to write enable_if for the template constructor - any(any & src) : any (const_cast(src)) {} - - any() = default; - any(any&& ) = default; - - any& operator=(any&&) = default; - - any& operator=(any const& src) - { - any copy(src); - swap(*this, copy); - return *this; - } - - template - friend value_t* any_cast(any* operand); - - template - friend const value_t* any_cast(const any* operand); - - template - friend value_t& unsafe_any_cast(any& operand); - - template - friend const value_t& unsafe_any_cast(const any& operand); - - friend void swap(any & lhs, any& rhs) - { - swap(lhs.hldr, rhs.hldr); - } - - }; - - template - value_t* any_cast(any* operand) - { - auto casted = internal::down_cast::type> *>(operand->hldr.get()); - if (casted){ - return & (casted->v); - } - return nullptr; - } - - template - const value_t* any_cast(const any* operand) - { - auto casted = internal::down_cast::type> *>(operand->hldr.get()); - if (casted){ - return & (casted->v); - } - return nullptr; - } - - template - value_t& any_cast(any& operand) - { - auto ptr = any_cast(&operand); - if (ptr) - { - return *ptr; - } - - throw_error(bad_any_cast()); - } - - - template - const value_t& any_cast(const any& operand) - { - auto ptr = any_cast(&operand); - if (ptr) - { - return *ptr; - } - - throw_error(bad_any_cast()); - } - - template - inline value_t& unsafe_any_cast(any& operand) - { -#ifdef DEBUG - return any_cast(operand); -#else - return static_cast::type> *>(operand.hldr.get())->v; -#endif - } - - template - inline const value_t& unsafe_any_cast(const any& operand) - { -#ifdef DEBUG - return any_cast(operand); -#else - return static_cast::type> *>(operand.hldr.get())->v; -#endif - } - -} // namespace util -} // namespace cv - -#if defined(_MSC_VER) - // Enable "multiple copy constructors specified" back -# pragma warning(default: 4521) -#endif - -#endif // OPENCV_GAPI_UTIL_ANY_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_UTIL_ANY_HPP +#define OPENCV_GAPI_UTIL_ANY_HPP + +#include +#include +#include +#include + +#include + +#if defined(_MSC_VER) + // disable MSVC warning on "multiple copy constructors specified" +# pragma warning(disable: 4521) +#endif + +namespace cv +{ + +namespace internal +{ + template + T down_cast(Source operand) + { +#if defined(__GXX_RTTI) || defined(_CPPRTTI) + return dynamic_cast(operand); +#else +#ifdef __GNUC__ +#warning used static cast instead of dynamic because RTTI is disabled +#else +#pragma message("WARNING: used static cast instead of dynamic because RTTI is disabled") +#endif + return static_cast(operand); +#endif + } +} + +namespace util +{ + class bad_any_cast : public std::bad_cast + { + public: + virtual const char* what() const noexcept override + { + return "Bad any cast"; + } + }; + + //modeled against C++17 std::any + + class any + { + private: + struct holder; + using holder_ptr = std::unique_ptr; + struct holder + { + virtual holder_ptr clone() = 0; + virtual ~holder() = default; + }; + + template + struct holder_impl : holder + { + value_t v; + template + holder_impl(arg_t&& a) : v(std::forward(a)) {} + holder_ptr clone() override { return holder_ptr(new holder_impl (v));} + }; + + holder_ptr hldr; + public: + template + any(value_t&& arg) : hldr(new holder_impl::type>( std::forward(arg))) {} + + any(any const& src) : hldr( src.hldr ? src.hldr->clone() : nullptr) {} + //simple hack in order not to write enable_if for the template constructor + any(any & src) : any (const_cast(src)) {} + + any() = default; + any(any&& ) = default; + + any& operator=(any&&) = default; + + any& operator=(any const& src) + { + any copy(src); + swap(*this, copy); + return *this; + } + + template + friend value_t* any_cast(any* operand); + + template + friend const value_t* any_cast(const any* operand); + + template + friend value_t& unsafe_any_cast(any& operand); + + template + friend const value_t& unsafe_any_cast(const any& operand); + + friend void swap(any & lhs, any& rhs) + { + swap(lhs.hldr, rhs.hldr); + } + + }; + + template + value_t* any_cast(any* operand) + { + auto casted = internal::down_cast::type> *>(operand->hldr.get()); + if (casted){ + return & (casted->v); + } + return nullptr; + } + + template + const value_t* any_cast(const any* operand) + { + auto casted = internal::down_cast::type> *>(operand->hldr.get()); + if (casted){ + return & (casted->v); + } + return nullptr; + } + + template + value_t& any_cast(any& operand) + { + auto ptr = any_cast(&operand); + if (ptr) + { + return *ptr; + } + + throw_error(bad_any_cast()); + } + + + template + const value_t& any_cast(const any& operand) + { + auto ptr = any_cast(&operand); + if (ptr) + { + return *ptr; + } + + throw_error(bad_any_cast()); + } + + template + inline value_t& unsafe_any_cast(any& operand) + { +#ifdef DEBUG + return any_cast(operand); +#else + return static_cast::type> *>(operand.hldr.get())->v; +#endif + } + + template + inline const value_t& unsafe_any_cast(const any& operand) + { +#ifdef DEBUG + return any_cast(operand); +#else + return static_cast::type> *>(operand.hldr.get())->v; +#endif + } + +} // namespace util +} // namespace cv + +#if defined(_MSC_VER) + // Enable "multiple copy constructors specified" back +# pragma warning(default: 4521) +#endif + +#endif // OPENCV_GAPI_UTIL_ANY_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/util/compiler_hints.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/util/compiler_hints.hpp index a41a97145d..5f620ff3ed 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/util/compiler_hints.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/util/compiler_hints.hpp @@ -1,19 +1,19 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - -#ifndef OPENCV_GAPI_UTIL_COMPILER_HINTS_HPP -#define OPENCV_GAPI_UTIL_COMPILER_HINTS_HPP - -namespace cv -{ -namespace util -{ - //! Utility template function to prevent "unused" warnings by various compilers. - template void suppress_unused_warning( const T& ) {} -} // namespace util -} // namespace cv - -#endif /* OPENCV_GAPI_UTIL_COMPILER_HINTS_HPP */ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + +#ifndef OPENCV_GAPI_UTIL_COMPILER_HINTS_HPP +#define OPENCV_GAPI_UTIL_COMPILER_HINTS_HPP + +namespace cv +{ +namespace util +{ + //! Utility template function to prevent "unused" warnings by various compilers. + template void suppress_unused_warning( const T& ) {} +} // namespace util +} // namespace cv + +#endif /* OPENCV_GAPI_UTIL_COMPILER_HINTS_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/util/copy_through_move.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/util/copy_through_move.hpp index 1a1121eb21..34a856986f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/util/copy_through_move.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/util/copy_through_move.hpp @@ -1,34 +1,34 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020 Intel Corporation - -#ifndef OPENCV_GAPI_UTIL_COPY_THROUGH_MOVE_HPP -#define OPENCV_GAPI_UTIL_COPY_THROUGH_MOVE_HPP - -#include //decay_t - -namespace cv -{ -namespace util -{ - //This is a tool to move initialize captures of a lambda in C++11 - template - struct copy_through_move_t{ - T value; - const T& get() const {return value;} - T& get() {return value;} - copy_through_move_t(T&& g) : value(std::move(g)) {} - copy_through_move_t(copy_through_move_t&&) = default; - copy_through_move_t(copy_through_move_t const& lhs) : copy_through_move_t(std::move(const_cast(lhs))) {} - }; - - template - copy_through_move_t> copy_through_move(T&& t){ - return std::forward(t); - } -} // namespace util -} // namespace cv - -#endif /* OPENCV_GAPI_UTIL_COPY_THROUGH_MOVE_HPP */ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020 Intel Corporation + +#ifndef OPENCV_GAPI_UTIL_COPY_THROUGH_MOVE_HPP +#define OPENCV_GAPI_UTIL_COPY_THROUGH_MOVE_HPP + +#include //decay_t + +namespace cv +{ +namespace util +{ + //This is a tool to move initialize captures of a lambda in C++11 + template + struct copy_through_move_t{ + T value; + const T& get() const {return value;} + T& get() {return value;} + copy_through_move_t(T&& g) : value(std::move(g)) {} + copy_through_move_t(copy_through_move_t&&) = default; + copy_through_move_t(copy_through_move_t const& lhs) : copy_through_move_t(std::move(const_cast(lhs))) {} + }; + + template + copy_through_move_t> copy_through_move(T&& t){ + return std::forward(t); + } +} // namespace util +} // namespace cv + +#endif /* OPENCV_GAPI_UTIL_COPY_THROUGH_MOVE_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/util/optional.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/util/optional.hpp index dca03cadad..3b6877d2aa 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/util/optional.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/util/optional.hpp @@ -1,178 +1,178 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_UTIL_OPTIONAL_HPP -#define OPENCV_GAPI_UTIL_OPTIONAL_HPP - -#include - -// A poor man's `optional` implementation, incompletely modeled against C++17 spec. -namespace cv -{ -namespace util -{ - class bad_optional_access: public std::exception - { - public: - virtual const char *what() const noexcept override - { - return "Bad optional access"; - } - }; - - // TODO: nullopt_t - - // Interface /////////////////////////////////////////////////////////////// - template class optional - { - public: - // Constructors - // NB.: there were issues with Clang 3.8 when =default() was used - // instead {} - optional() {} - optional(const optional&) = default; - explicit optional(T&&) noexcept; - explicit optional(const T&) noexcept; - optional(optional&&) noexcept; - // TODO: optional(nullopt_t) noexcept; - // TODO: optional(const optional &) - // TODO: optional(optional &&) - // TODO: optional(Args&&...) - // TODO: optional(initializer_list) - // TODO: optional(U&& value); - - // Assignment - optional& operator=(const optional&) = default; - optional& operator=(optional&&); - - // Observers - T* operator-> (); - const T* operator-> () const; - T& operator* (); - const T& operator* () const; - // TODO: && versions - - operator bool() const noexcept; - bool has_value() const noexcept; - - T& value(); - const T& value() const; - // TODO: && versions - - template - T value_or(U &&default_value) const; - - void swap(optional &other) noexcept; - void reset() noexcept; - // TODO: emplace - - // TODO: operator==, !=, <, <=, >, >= - - private: - struct nothing {}; - util::variant m_holder; - }; - - template - optional::type> make_optional(T&& value); - - // TODO: Args... and initializer_list versions - - // Implementation ////////////////////////////////////////////////////////// - template optional::optional(T &&v) noexcept - : m_holder(std::move(v)) - { - } - - template optional::optional(const T &v) noexcept - : m_holder(v) - { - } - - template optional::optional(optional&& rhs) noexcept - : m_holder(std::move(rhs.m_holder)) - { - rhs.reset(); - } - - template optional& optional::operator=(optional&& rhs) - { - m_holder = std::move(rhs.m_holder); - rhs.reset(); - return *this; - } - - template T* optional::operator-> () - { - return & *(*this); - } - - template const T* optional::operator-> () const - { - return & *(*this); - } - - template T& optional::operator* () - { - return this->value(); - } - - template const T& optional::operator* () const - { - return this->value(); - } - - template optional::operator bool() const noexcept - { - return this->has_value(); - } - - template bool optional::has_value() const noexcept - { - return util::holds_alternative(m_holder); - } - - template T& optional::value() - { - if (!this->has_value()) - throw_error(bad_optional_access()); - return util::get(m_holder); - } - - template const T& optional::value() const - { - if (!this->has_value()) - throw_error(bad_optional_access()); - return util::get(m_holder); - } - - template - template T optional::value_or(U &&default_value) const - { - return (this->has_value() ? this->value() : T(default_value)); - } - - template void optional::swap(optional &other) noexcept - { - m_holder.swap(other.m_holder); - } - - template void optional::reset() noexcept - { - if (this->has_value()) - m_holder = nothing{}; - } - - template - optional::type> make_optional(T&& value) - { - return optional::type>(std::forward(value)); - } -} // namespace util -} // namespace cv - -#endif // OPENCV_GAPI_UTIL_OPTIONAL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_UTIL_OPTIONAL_HPP +#define OPENCV_GAPI_UTIL_OPTIONAL_HPP + +#include + +// A poor man's `optional` implementation, incompletely modeled against C++17 spec. +namespace cv +{ +namespace util +{ + class bad_optional_access: public std::exception + { + public: + virtual const char *what() const noexcept override + { + return "Bad optional access"; + } + }; + + // TODO: nullopt_t + + // Interface /////////////////////////////////////////////////////////////// + template class optional + { + public: + // Constructors + // NB.: there were issues with Clang 3.8 when =default() was used + // instead {} + optional() {} + optional(const optional&) = default; + explicit optional(T&&) noexcept; + explicit optional(const T&) noexcept; + optional(optional&&) noexcept; + // TODO: optional(nullopt_t) noexcept; + // TODO: optional(const optional &) + // TODO: optional(optional &&) + // TODO: optional(Args&&...) + // TODO: optional(initializer_list) + // TODO: optional(U&& value); + + // Assignment + optional& operator=(const optional&) = default; + optional& operator=(optional&&); + + // Observers + T* operator-> (); + const T* operator-> () const; + T& operator* (); + const T& operator* () const; + // TODO: && versions + + operator bool() const noexcept; + bool has_value() const noexcept; + + T& value(); + const T& value() const; + // TODO: && versions + + template + T value_or(U &&default_value) const; + + void swap(optional &other) noexcept; + void reset() noexcept; + // TODO: emplace + + // TODO: operator==, !=, <, <=, >, >= + + private: + struct nothing {}; + util::variant m_holder; + }; + + template + optional::type> make_optional(T&& value); + + // TODO: Args... and initializer_list versions + + // Implementation ////////////////////////////////////////////////////////// + template optional::optional(T &&v) noexcept + : m_holder(std::move(v)) + { + } + + template optional::optional(const T &v) noexcept + : m_holder(v) + { + } + + template optional::optional(optional&& rhs) noexcept + : m_holder(std::move(rhs.m_holder)) + { + rhs.reset(); + } + + template optional& optional::operator=(optional&& rhs) + { + m_holder = std::move(rhs.m_holder); + rhs.reset(); + return *this; + } + + template T* optional::operator-> () + { + return & *(*this); + } + + template const T* optional::operator-> () const + { + return & *(*this); + } + + template T& optional::operator* () + { + return this->value(); + } + + template const T& optional::operator* () const + { + return this->value(); + } + + template optional::operator bool() const noexcept + { + return this->has_value(); + } + + template bool optional::has_value() const noexcept + { + return util::holds_alternative(m_holder); + } + + template T& optional::value() + { + if (!this->has_value()) + throw_error(bad_optional_access()); + return util::get(m_holder); + } + + template const T& optional::value() const + { + if (!this->has_value()) + throw_error(bad_optional_access()); + return util::get(m_holder); + } + + template + template T optional::value_or(U &&default_value) const + { + return (this->has_value() ? this->value() : T(default_value)); + } + + template void optional::swap(optional &other) noexcept + { + m_holder.swap(other.m_holder); + } + + template void optional::reset() noexcept + { + if (this->has_value()) + m_holder = nothing{}; + } + + template + optional::type> make_optional(T&& value) + { + return optional::type>(std::forward(value)); + } +} // namespace util +} // namespace cv + +#endif // OPENCV_GAPI_UTIL_OPTIONAL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/util/throw.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/util/throw.hpp index 689bf583cf..bcbcf0adce 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/util/throw.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/util/throw.hpp @@ -1,36 +1,36 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_UTIL_THROW_HPP -#define OPENCV_GAPI_UTIL_THROW_HPP - -#include // std::forward - -#if !defined(__EXCEPTIONS) -#include -#include -#endif - -namespace cv -{ -namespace util -{ -template -[[noreturn]] void throw_error(ExceptionType &&e) -{ -#if defined(__EXCEPTIONS) || defined(_CPPUNWIND) - throw std::forward(e); -#else - fprintf(stderr, "An exception thrown! %s\n" , e.what()); - fflush(stderr); - abort(); -#endif -} -} // namespace util -} // namespace cv - -#endif // OPENCV_GAPI_UTIL_THROW_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_UTIL_THROW_HPP +#define OPENCV_GAPI_UTIL_THROW_HPP + +#include // std::forward + +#if !defined(__EXCEPTIONS) +#include +#include +#endif + +namespace cv +{ +namespace util +{ +template +[[noreturn]] void throw_error(ExceptionType &&e) +{ +#if defined(__EXCEPTIONS) || defined(_CPPUNWIND) + throw std::forward(e); +#else + fprintf(stderr, "An exception thrown! %s\n" , e.what()); + fflush(stderr); + abort(); +#endif +} +} // namespace util +} // namespace cv + +#endif // OPENCV_GAPI_UTIL_THROW_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/util/type_traits.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/util/type_traits.hpp index 637f18460b..43160250d7 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/util/type_traits.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/util/type_traits.hpp @@ -1,31 +1,31 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020 Intel Corporation - - -#ifndef OPENCV_GAPI_UTIL_TYPE_TRAITS_HPP -#define OPENCV_GAPI_UTIL_TYPE_TRAITS_HPP - -#include - -namespace cv -{ -namespace util -{ - //these are C++14 parts of type_traits : - template< bool B, class T = void > - using enable_if_t = typename std::enable_if::type; - - template - using decay_t = typename std::decay::type; - - //this is not part of C++14 but still, of pretty common usage - template - using are_different_t = enable_if_t< !std::is_same, decay_t>::value, V>; - -} // namespace cv -} // namespace util - -#endif // OPENCV_GAPI_UTIL_TYPE_TRAITS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020 Intel Corporation + + +#ifndef OPENCV_GAPI_UTIL_TYPE_TRAITS_HPP +#define OPENCV_GAPI_UTIL_TYPE_TRAITS_HPP + +#include + +namespace cv +{ +namespace util +{ + //these are C++14 parts of type_traits : + template< bool B, class T = void > + using enable_if_t = typename std::enable_if::type; + + template + using decay_t = typename std::decay::type; + + //this is not part of C++14 but still, of pretty common usage + template + using are_different_t = enable_if_t< !std::is_same, decay_t>::value, V>; + +} // namespace cv +} // namespace util + +#endif // OPENCV_GAPI_UTIL_TYPE_TRAITS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/util/util.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/util/util.hpp index 3be46d7ec2..31f518a322 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/util/util.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/util/util.hpp @@ -1,190 +1,190 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2019 Intel Corporation - - -#ifndef OPENCV_GAPI_UTIL_HPP -#define OPENCV_GAPI_UTIL_HPP - -#include - -// \cond HIDDEN_SYMBOLS -// This header file contains some generic utility functions which are -// used in other G-API Public API headers. -// -// PLEASE don't put any stuff here if it is NOT used in public API headers! - -namespace cv -{ -namespace detail -{ - // Recursive integer sequence type, useful for enumerating elements of - // template parameter packs. - template struct Seq { using next = Seq; }; - template struct MkSeq { using type = typename MkSeq::type::next; }; - template<> struct MkSeq<0>{ using type = Seq<>; }; - - // Checks if elements of variadic template satisfy the given Predicate. - // Implemented via tuple, with an interface to accept plain type lists - template class, typename, typename...> struct all_satisfy; - - template class F, typename T, typename... Ts> - struct all_satisfy > - { - static const constexpr bool value = F::value - && all_satisfy >::value; - }; - template class F, typename T> - struct all_satisfy > - { - static const constexpr bool value = F::value; - }; - - template class F, typename T, typename... Ts> - struct all_satisfy: public all_satisfy > {}; - - // Permute given tuple type C with given integer sequence II - // Sequence may be less than tuple C size. - template struct permute_tuple; - - template - struct permute_tuple > - { - using type = std::tuple< typename std::tuple_element::type... >; - }; - - // Given T..., generates a type sequence of sizeof...(T)-1 elements - // which is T... without its last element - // Implemented via tuple, with an interface to accept plain type lists - template struct all_but_last; - - template - struct all_but_last > - { - using C = std::tuple; - using S = typename MkSeq::value - 1>::type; - using type = typename permute_tuple::type; - }; - - template - struct all_but_last: public all_but_last > {}; - - template - using all_but_last_t = typename all_but_last::type; - - // NB.: This is here because there's no constexpr std::max in C++11 - template struct max_of_t - { - static constexpr const std::size_t rest = max_of_t::value; - static constexpr const std::size_t value = rest > S0 ? rest : S0; - }; - template struct max_of_t - { - static constexpr const std::size_t value = S; - }; - - template - struct contains : std::false_type{}; - - template - struct contains : std::integral_constant::value || - contains::value> {}; - template - struct contains> : std::integral_constant::value> {}; - - template - struct all_unique : std::true_type{}; - - template - struct all_unique : std::integral_constant::value && - all_unique::value> {}; - - template - struct tuple_wrap_helper; - - template struct tuple_wrap_helper - { - using type = std::tuple; - static type get(T&& obj) { return std::make_tuple(std::move(obj)); } - }; - - template - struct tuple_wrap_helper> - { - using type = std::tuple; - static type get(std::tuple&& objs) { return std::forward>(objs); } - }; - - template - struct make_void { typedef void type;}; - - template - using void_t = typename make_void::type; - -} // namespace detail - -namespace util -{ -template -struct overload_lamba_set; - -template -struct overload_lamba_set : public L1 -{ - overload_lamba_set(L1&& lambda) : L1(std::move(lambda)) {} - overload_lamba_set(const L1& lambda) : L1(lambda) {} - - using L1::operator(); -}; - -template -struct overload_lamba_set : public L1, public overload_lamba_set -{ - using base_type = overload_lamba_set; - overload_lamba_set(L1 &&lambda1, L&& ...lambdas): - L1(std::move(lambda1)), - base_type(std::forward(lambdas)...) {} - - overload_lamba_set(const L1 &lambda1, L&& ...lambdas): - L1(lambda1), - base_type(std::forward(lambdas)...) {} - - using L1::operator(); - using base_type::operator(); -}; - -template -overload_lamba_set overload_lambdas(L&& ...lambdas) -{ - return overload_lamba_set(std::forward(lambdas)...); -} - -template -struct find_adapter_impl; - -template -struct find_adapter_impl -{ - using type = typename std::conditional::value, - T, - void>::type; - static constexpr bool found = std::is_base_of::value; -}; - -template -struct find_adapter_impl -{ - using type = typename std::conditional::value, - T, - typename find_adapter_impl::type>::type; - static constexpr bool found = std::is_base_of::value || - find_adapter_impl::found; -}; -} // namespace util -} // namespace cv - -// \endcond - -#endif // OPENCV_GAPI_UTIL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2019 Intel Corporation + + +#ifndef OPENCV_GAPI_UTIL_HPP +#define OPENCV_GAPI_UTIL_HPP + +#include + +// \cond HIDDEN_SYMBOLS +// This header file contains some generic utility functions which are +// used in other G-API Public API headers. +// +// PLEASE don't put any stuff here if it is NOT used in public API headers! + +namespace cv +{ +namespace detail +{ + // Recursive integer sequence type, useful for enumerating elements of + // template parameter packs. + template struct Seq { using next = Seq; }; + template struct MkSeq { using type = typename MkSeq::type::next; }; + template<> struct MkSeq<0>{ using type = Seq<>; }; + + // Checks if elements of variadic template satisfy the given Predicate. + // Implemented via tuple, with an interface to accept plain type lists + template class, typename, typename...> struct all_satisfy; + + template class F, typename T, typename... Ts> + struct all_satisfy > + { + static const constexpr bool value = F::value + && all_satisfy >::value; + }; + template class F, typename T> + struct all_satisfy > + { + static const constexpr bool value = F::value; + }; + + template class F, typename T, typename... Ts> + struct all_satisfy: public all_satisfy > {}; + + // Permute given tuple type C with given integer sequence II + // Sequence may be less than tuple C size. + template struct permute_tuple; + + template + struct permute_tuple > + { + using type = std::tuple< typename std::tuple_element::type... >; + }; + + // Given T..., generates a type sequence of sizeof...(T)-1 elements + // which is T... without its last element + // Implemented via tuple, with an interface to accept plain type lists + template struct all_but_last; + + template + struct all_but_last > + { + using C = std::tuple; + using S = typename MkSeq::value - 1>::type; + using type = typename permute_tuple::type; + }; + + template + struct all_but_last: public all_but_last > {}; + + template + using all_but_last_t = typename all_but_last::type; + + // NB.: This is here because there's no constexpr std::max in C++11 + template struct max_of_t + { + static constexpr const std::size_t rest = max_of_t::value; + static constexpr const std::size_t value = rest > S0 ? rest : S0; + }; + template struct max_of_t + { + static constexpr const std::size_t value = S; + }; + + template + struct contains : std::false_type{}; + + template + struct contains : std::integral_constant::value || + contains::value> {}; + template + struct contains> : std::integral_constant::value> {}; + + template + struct all_unique : std::true_type{}; + + template + struct all_unique : std::integral_constant::value && + all_unique::value> {}; + + template + struct tuple_wrap_helper; + + template struct tuple_wrap_helper + { + using type = std::tuple; + static type get(T&& obj) { return std::make_tuple(std::move(obj)); } + }; + + template + struct tuple_wrap_helper> + { + using type = std::tuple; + static type get(std::tuple&& objs) { return std::forward>(objs); } + }; + + template + struct make_void { typedef void type;}; + + template + using void_t = typename make_void::type; + +} // namespace detail + +namespace util +{ +template +struct overload_lamba_set; + +template +struct overload_lamba_set : public L1 +{ + overload_lamba_set(L1&& lambda) : L1(std::move(lambda)) {} + overload_lamba_set(const L1& lambda) : L1(lambda) {} + + using L1::operator(); +}; + +template +struct overload_lamba_set : public L1, public overload_lamba_set +{ + using base_type = overload_lamba_set; + overload_lamba_set(L1 &&lambda1, L&& ...lambdas): + L1(std::move(lambda1)), + base_type(std::forward(lambdas)...) {} + + overload_lamba_set(const L1 &lambda1, L&& ...lambdas): + L1(lambda1), + base_type(std::forward(lambdas)...) {} + + using L1::operator(); + using base_type::operator(); +}; + +template +overload_lamba_set overload_lambdas(L&& ...lambdas) +{ + return overload_lamba_set(std::forward(lambdas)...); +} + +template +struct find_adapter_impl; + +template +struct find_adapter_impl +{ + using type = typename std::conditional::value, + T, + void>::type; + static constexpr bool found = std::is_base_of::value; +}; + +template +struct find_adapter_impl +{ + using type = typename std::conditional::value, + T, + typename find_adapter_impl::type>::type; + static constexpr bool found = std::is_base_of::value || + find_adapter_impl::found; +}; +} // namespace util +} // namespace cv + +// \endcond + +#endif // OPENCV_GAPI_UTIL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/util/variant.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/util/variant.hpp index 48b55646c5..8b68e79ec5 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/util/variant.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/util/variant.hpp @@ -1,667 +1,667 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_UTIL_VARIANT_HPP -#define OPENCV_GAPI_UTIL_VARIANT_HPP - -#include -#include - -#include -#include -#include // max_of_t -#include - -// A poor man's `variant` implementation, incompletely modeled against C++17 spec. -namespace cv -{ -namespace util -{ - namespace detail - { - template - struct type_list_index_helper - { - static const constexpr bool is_same = std::is_same::value; - static const constexpr std::size_t value = - std::conditional, type_list_index_helper>::type::value; - }; - - template - struct type_list_index_helper - { - static_assert(std::is_same::value, "Type not found"); - static const constexpr std::size_t value = I; - }; - } - - template - struct type_list_index - { - static const constexpr std::size_t value = detail::type_list_index_helper<0, Target, Types...>::value; - }; - - template - struct type_list_element - { - using type = typename std::tuple_element >::type; - }; - - class bad_variant_access: public std::exception - { - public: - virtual const char *what() const noexcept override - { - return "Bad variant access"; - } - }; - - // Interface /////////////////////////////////////////////////////////////// - struct monostate {}; - inline bool operator==(const util::monostate&, const util::monostate&) - { - return true; - } - - template // FIXME: no references, arrays, and void - class variant - { - // FIXME: Replace with std::aligned_union after gcc4.8 support is dropped - static constexpr const std::size_t S = cv::detail::max_of_t::value; - static constexpr const std::size_t A = cv::detail::max_of_t::value; - using Memory = typename std::aligned_storage::type[1]; - - template struct cctr_h { - static void help(Memory memory, const Memory from) { - new (memory) T(*reinterpret_cast(from)); - } - }; - - template struct mctr_h { - static void help(Memory memory, void *pval) { - new (memory) T(std::move(*reinterpret_cast(pval))); - } - }; - - //FIXME: unify with cctr_h and mctr_h - template struct cnvrt_ctor_h { - static void help(Memory memory, void* from) { - using util::decay_t; - new (memory) decay_t(std::forward(*reinterpret_cast*>(from))); - } - }; - - template struct copy_h { - static void help(Memory to, const Memory from) { - *reinterpret_cast(to) = *reinterpret_cast(from); - } - }; - - template struct move_h { - static void help(Memory to, Memory from) { - *reinterpret_cast(to) = std::move(*reinterpret_cast(from)); - } - }; - - //FIXME: unify with copy_h and move_h - template struct cnvrt_assign_h { - static void help(Memory to, void* from) { - using util::decay_t; - *reinterpret_cast*>(to) = std::forward(*reinterpret_cast*>(from)); - } - }; - - template struct swap_h { - static void help(Memory to, Memory from) { - std::swap(*reinterpret_cast(to), *reinterpret_cast(from)); - } - }; - - template struct dtor_h { - static void help(Memory memory) { - (void) memory; // MSCV warning - reinterpret_cast(memory)->~T(); - } - }; - - template struct equal_h { - static bool help(const Memory lhs, const Memory rhs) { - const T& t_lhs = *reinterpret_cast(lhs); - const T& t_rhs = *reinterpret_cast(rhs); - return t_lhs == t_rhs; - } - }; - - typedef void (*CCtr) (Memory, const Memory); // Copy c-tor (variant) - typedef void (*MCtr) (Memory, void*); // Generic move c-tor - typedef void (*Copy) (Memory, const Memory); // Copy assignment - typedef void (*Move) (Memory, Memory); // Move assignment - - typedef void (*Swap) (Memory, Memory); // Swap - typedef void (*Dtor) (Memory); // Destructor - - using cnvrt_assgn_t = void (*) (Memory, void*); // Converting assignment (via std::forward) - using cnvrt_ctor_t = void (*) (Memory, void*); // Converting constructor (via std::forward) - - typedef bool (*Equal)(const Memory, const Memory); // Equality test (external) - - static constexpr std::array cctrs(){ return {{(&cctr_h::help)...}};} - static constexpr std::array mctrs(){ return {{(&mctr_h::help)...}};} - static constexpr std::array cpyrs(){ return {{(©_h::help)...}};} - static constexpr std::array mvers(){ return {{(&move_h::help)...}};} - static constexpr std::array swprs(){ return {{(&swap_h::help)...}};} - static constexpr std::array dtors(){ return {{(&dtor_h::help)...}};} - - template - struct conditional_ref : std::conditional::type&, typename std::remove_reference::type > {}; - - template - using conditional_ref_t = typename conditional_ref::type; - - - template - static constexpr std::array cnvrt_assgnrs(){ - return {{(&cnvrt_assign_h>::help)...}}; - } - - template - static constexpr std::array cnvrt_ctors(){ - return {{(&cnvrt_ctor_h>::help)...}}; - } - - std::size_t m_index = 0; - - protected: - template friend T& get(variant &v); - template friend const T& get(const variant &v); - template friend T* get_if(variant *v) noexcept; - template friend const T* get_if(const variant *v) noexcept; - - template friend bool operator==(const variant &lhs, - const variant &rhs); - Memory memory; - - public: - // Constructors - variant() noexcept; - variant(const variant& other); - variant(variant&& other) noexcept; - // are_different_t is a SFINAE trick to avoid variant(T &&t) with T=variant - // for some reason, this version is called instead of variant(variant&& o) when - // variant is used in STL containers (examples: vector assignment). - template< - typename T, - typename = util::are_different_t - > - explicit variant(T&& t); - // template explicit variant(Args&&... args); - // FIXME: other constructors - - // Destructor - ~variant(); - - // Assignment - variant& operator=(const variant& rhs); - variant& operator=(variant &&rhs) noexcept; - - // SFINAE trick to avoid operator=(T&&) with T=variant<>, see comment above - template< - typename T, - typename = util::are_different_t - > - variant& operator=(T&& t) noexcept; - - // Observers - std::size_t index() const noexcept; - // FIXME: valueless_by_exception() - - // Modifiers - // FIXME: emplace() - void swap(variant &rhs) noexcept; - - // Non-C++17x! - template static constexpr std::size_t index_of(); - }; - - // FIMXE: visit - template - T* get_if(util::variant* v) noexcept; - - template - const T* get_if(const util::variant* v) noexcept; - - template - T& get(util::variant &v); - - template - const T& get(const util::variant &v); - - template - typename util::type_list_element::type& get(util::variant &v); - - template - const typename util::type_list_element::type& get(const util::variant &v); - - template - bool holds_alternative(const util::variant &v) noexcept; - - - // Visitor - namespace detail - { - struct visitor_interface {}; - - // Class `visitor_return_type_deduction_helper` - // introduces solution for deduction `return_type` in `visit` function in common way - // for both Lambda and class Visitor and keep one interface invocation point: `visit` only - // his helper class is required to unify return_type deduction mechanism because - // for Lambda it is possible to take type of `decltype(visitor(get<0>(var)))` - // but for class Visitor there is no operator() in base case, - // because it provides `operator() (std::size_t index, ...)` - // So `visitor_return_type_deduction_helper` expose `operator()` - // uses only for class Visitor only for deduction `return type` in visit() - template - struct visitor_return_type_deduction_helper - { - using return_type = R; - - // to be used in Lambda return type deduction context only - template - return_type operator() (T&&); - }; - } - - // Special purpose `static_visitor` can receive additional arguments - template - struct static_visitor : public detail::visitor_interface, - public detail::visitor_return_type_deduction_helper { - - // assign responsibility for return type deduction to helper class - using return_type = typename detail::visitor_return_type_deduction_helper::return_type; - using detail::visitor_return_type_deduction_helper::operator(); - friend Impl; - - template - return_type operator() (std::size_t index, VariantValue&& value, Args&& ...args) - { - suppress_unused_warning(index); - return static_cast(this)-> visit( - std::forward(value), - std::forward(args)...); - } - }; - - // Special purpose `static_indexed_visitor` can receive additional arguments - // And make forwarding current variant index as runtime function argument to its `Impl` - template - struct static_indexed_visitor : public detail::visitor_interface, - public detail::visitor_return_type_deduction_helper { - - // assign responsibility for return type deduction to helper class - using return_type = typename detail::visitor_return_type_deduction_helper::return_type; - using detail::visitor_return_type_deduction_helper::operator(); - friend Impl; - - template - return_type operator() (std::size_t Index, VariantValue&& value, Args&& ...args) - { - return static_cast(this)-> visit(Index, - std::forward(value), - std::forward(args)...); - } - }; - - template - struct variant_size; - - template - struct variant_size> - : std::integral_constant { }; - // FIXME: T&&, const TT&& versions. - - // Implementation ////////////////////////////////////////////////////////// - template - variant::variant() noexcept - { - typedef typename std::tuple_element<0, std::tuple >::type TFirst; - new (memory) TFirst(); - } - - template - variant::variant(const variant &other) - : m_index(other.m_index) - { - (cctrs()[m_index])(memory, other.memory); - } - - template - variant::variant(variant &&other) noexcept - : m_index(other.m_index) - { - (mctrs()[m_index])(memory, other.memory); - } - - template - template - variant::variant(T&& t) - : m_index(util::type_list_index, Ts...>::value) - { - const constexpr bool is_lvalue_arg = std::is_lvalue_reference::value; - (cnvrt_ctors()[m_index])(memory, const_cast *>(&t)); - } - - template - variant::~variant() - { - (dtors()[m_index])(memory); - } - - template - variant& variant::operator=(const variant &rhs) - { - if (m_index != rhs.m_index) - { - (dtors()[ m_index])(memory); - (cctrs()[rhs.m_index])(memory, rhs.memory); - m_index = rhs.m_index; - } - else - { - (cpyrs()[rhs.m_index])(memory, rhs.memory); - } - return *this; - } - - template - variant& variant::operator=(variant &&rhs) noexcept - { - if (m_index != rhs.m_index) - { - (dtors()[ m_index])(memory); - (mctrs()[rhs.m_index])(memory, rhs.memory); - m_index = rhs.m_index; - } - else - { - (mvers()[rhs.m_index])(memory, rhs.memory); - } - return *this; - } - - template - template - variant& variant::operator=(T&& t) noexcept - { - using decayed_t = util::decay_t; - // FIXME: No version with implicit type conversion available! - const constexpr std::size_t t_index = - util::type_list_index::value; - - const constexpr bool is_lvalue_arg = std::is_lvalue_reference::value; - - if (t_index != m_index) - { - (dtors()[m_index])(memory); - (cnvrt_ctors()[t_index])(memory, &t); - m_index = t_index; - } - else - { - (cnvrt_assgnrs()[m_index])(memory, &t); - } - return *this; - - } - - template - std::size_t util::variant::index() const noexcept - { - return m_index; - } - - template - void variant::swap(variant &rhs) noexcept - { - if (m_index == rhs.index()) - { - (swprs()[m_index](memory, rhs.memory)); - } - else - { - variant tmp(std::move(*this)); - *this = std::move(rhs); - rhs = std::move(tmp); - } - } - - template - template - constexpr std::size_t variant::index_of() - { - return util::type_list_index::value; // FIXME: tests! - } - - template - T* get_if(util::variant* v) noexcept - { - const constexpr std::size_t t_index = - util::type_list_index::value; - - if (v && v->index() == t_index) - return (T*)(&v->memory); // workaround for ICC 2019 - // original code: return reinterpret_cast(v.memory); - return nullptr; - } - - template - const T* get_if(const util::variant* v) noexcept - { - const constexpr std::size_t t_index = - util::type_list_index::value; - - if (v && v->index() == t_index) - return (const T*)(&v->memory); // workaround for ICC 2019 - // original code: return reinterpret_cast(v.memory); - return nullptr; - } - - template - T& get(util::variant &v) - { - if (auto* p = get_if(&v)) - return *p; - else - throw_error(bad_variant_access()); - } - - template - const T& get(const util::variant &v) - { - if (auto* p = get_if(&v)) - return *p; - else - throw_error(bad_variant_access()); - } - - template - typename util::type_list_element::type& get(util::variant &v) - { - using ReturnType = typename util::type_list_element::type; - return const_cast(get(static_cast &>(v))); - } - - template - const typename util::type_list_element::type& get(const util::variant &v) - { - static_assert(Index < sizeof...(Types), - "`Index` it out of bound of `util::variant` type list"); - using ReturnType = typename util::type_list_element::type; - return get(v); - } - - template - bool holds_alternative(const util::variant &v) noexcept - { - return v.index() == util::variant::template index_of(); - } - -#if defined(__GNUC__) && (__GNUC__ == 11 || __GNUC__ == 12) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wmaybe-uninitialized" -#endif - - template bool operator==(const variant &lhs, - const variant &rhs) - { - using V = variant; - - // Instantiate table only here since it requires operator== for - // should have operator== only if this one is used, not in general - static const std::array eqs = { - {(&V::template equal_h::help)...} - }; - if (lhs.index() != rhs.index()) - return false; - return (eqs[lhs.index()])(lhs.memory, rhs.memory); - } - -#if defined(__GNUC__) && (__GNUC__ == 11 || __GNUC__ == 12) -#pragma GCC diagnostic pop -#endif - - template bool operator!=(const variant &lhs, - const variant &rhs) - { - return !(lhs == rhs); - } - -namespace detail -{ - // terminate recursion implementation for `non-void` ReturnType - template - ReturnType apply_visitor_impl(Visitor&&, Variant&, - std::true_type, std::false_type, - VisitorArgs&& ...) - { - return {}; - } - - // terminate recursion implementation for `void` ReturnType - template - void apply_visitor_impl(Visitor&&, Variant&, - std::true_type, std::true_type, - VisitorArgs&& ...) - { - } - - // Intermediate resursion processor for Lambda Visitors - template - typename std::enable_if::type>::value, ReturnType>::type - apply_visitor_impl(Visitor&& visitor, Variant&& v, std::false_type not_processed, - std::integral_constant should_no_return, - VisitorArgs&& ...args) - { - static_assert(std::is_same(v)))>::value, - "Different `ReturnType`s detected! All `Visitor::visit` or `overload_lamba_set`" - " must return the same type"); - suppress_unused_warning(not_processed); - if (v.index() == CurIndex) - { - return visitor.operator()(get(v), std::forward(args)... ); - } - - using is_variant_processed_t = std::integral_constant= ElemCount>; - return apply_visitor_impl( - std::forward(visitor), - std::forward(v), - is_variant_processed_t{}, - should_no_return, - std::forward(args)...); - } - - //Visual Studio 2014 compilation fix: cast visitor to base class before invoke operator() - template - typename std::enable_if::type>, - typename std::decay::type>::value, ReturnType>::type - invoke_class_visitor(Visitor& visitor, Value&& v, VisitorArgs&&...args) - { - return static_cast::type>&>(visitor).operator() (CurIndex, std::forward(v), std::forward(args)... ); - } - - //Visual Studio 2014 compilation fix: cast visitor to base class before invoke operator() - template - typename std::enable_if::type>, - typename std::decay::type>::value, ReturnType>::type - invoke_class_visitor(Visitor& visitor, Value&& v, VisitorArgs&&...args) - { - return static_cast::type>&>(visitor).operator() (CurIndex, std::forward(v), std::forward(args)... ); - } - - // Intermediate recursion processor for special case `visitor_interface` derived Visitors - template - typename std::enable_if::type>::value, ReturnType>::type - apply_visitor_impl(Visitor&& visitor, Variant&& v, std::false_type not_processed, - std::integral_constant should_no_return, - VisitorArgs&& ...args) - { - static_assert(std::is_same(v)))>::value, - "Different `ReturnType`s detected! All `Visitor::visit` or `overload_lamba_set`" - " must return the same type"); - suppress_unused_warning(not_processed); - if (v.index() == CurIndex) - { - return invoke_class_visitor(visitor, get(v), std::forward(args)... ); - } - - using is_variant_processed_t = std::integral_constant= ElemCount>; - return apply_visitor_impl( - std::forward(visitor), - std::forward(v), - is_variant_processed_t{}, - should_no_return, - std::forward(args)...); - } -} // namespace detail - - template - auto visit(Visitor &visitor, const Variant& var, VisitorArg &&...args) -> decltype(visitor(get<0>(var))) - { - constexpr std::size_t varsize = util::variant_size::value; - static_assert(varsize != 0, "utils::variant must contains one type at least "); - using is_variant_processed_t = std::false_type; - - using ReturnType = decltype(visitor(get<0>(var))); - using return_t = std::is_same; - return detail::apply_visitor_impl( - std::forward(visitor), - var, is_variant_processed_t{}, - return_t{}, - std::forward(args)...); - } - - template - auto visit(Visitor&& visitor, const Variant& var) -> decltype(visitor(get<0>(var))) - { - constexpr std::size_t varsize = util::variant_size::value; - static_assert(varsize != 0, "utils::variant must contains one type at least "); - using is_variant_processed_t = std::false_type; - - using ReturnType = decltype(visitor(get<0>(var))); - using return_t = std::is_same; - return detail::apply_visitor_impl( - std::forward(visitor), - var, is_variant_processed_t{}, - return_t{}); - } -} // namespace util -} // namespace cv - -#endif // OPENCV_GAPI_UTIL_VARIANT_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_UTIL_VARIANT_HPP +#define OPENCV_GAPI_UTIL_VARIANT_HPP + +#include +#include + +#include +#include +#include // max_of_t +#include + +// A poor man's `variant` implementation, incompletely modeled against C++17 spec. +namespace cv +{ +namespace util +{ + namespace detail + { + template + struct type_list_index_helper + { + static const constexpr bool is_same = std::is_same::value; + static const constexpr std::size_t value = + std::conditional, type_list_index_helper>::type::value; + }; + + template + struct type_list_index_helper + { + static_assert(std::is_same::value, "Type not found"); + static const constexpr std::size_t value = I; + }; + } + + template + struct type_list_index + { + static const constexpr std::size_t value = detail::type_list_index_helper<0, Target, Types...>::value; + }; + + template + struct type_list_element + { + using type = typename std::tuple_element >::type; + }; + + class bad_variant_access: public std::exception + { + public: + virtual const char *what() const noexcept override + { + return "Bad variant access"; + } + }; + + // Interface /////////////////////////////////////////////////////////////// + struct monostate {}; + inline bool operator==(const util::monostate&, const util::monostate&) + { + return true; + } + + template // FIXME: no references, arrays, and void + class variant + { + // FIXME: Replace with std::aligned_union after gcc4.8 support is dropped + static constexpr const std::size_t S = cv::detail::max_of_t::value; + static constexpr const std::size_t A = cv::detail::max_of_t::value; + using Memory = typename std::aligned_storage::type[1]; + + template struct cctr_h { + static void help(Memory memory, const Memory from) { + new (memory) T(*reinterpret_cast(from)); + } + }; + + template struct mctr_h { + static void help(Memory memory, void *pval) { + new (memory) T(std::move(*reinterpret_cast(pval))); + } + }; + + //FIXME: unify with cctr_h and mctr_h + template struct cnvrt_ctor_h { + static void help(Memory memory, void* from) { + using util::decay_t; + new (memory) decay_t(std::forward(*reinterpret_cast*>(from))); + } + }; + + template struct copy_h { + static void help(Memory to, const Memory from) { + *reinterpret_cast(to) = *reinterpret_cast(from); + } + }; + + template struct move_h { + static void help(Memory to, Memory from) { + *reinterpret_cast(to) = std::move(*reinterpret_cast(from)); + } + }; + + //FIXME: unify with copy_h and move_h + template struct cnvrt_assign_h { + static void help(Memory to, void* from) { + using util::decay_t; + *reinterpret_cast*>(to) = std::forward(*reinterpret_cast*>(from)); + } + }; + + template struct swap_h { + static void help(Memory to, Memory from) { + std::swap(*reinterpret_cast(to), *reinterpret_cast(from)); + } + }; + + template struct dtor_h { + static void help(Memory memory) { + (void) memory; // MSCV warning + reinterpret_cast(memory)->~T(); + } + }; + + template struct equal_h { + static bool help(const Memory lhs, const Memory rhs) { + const T& t_lhs = *reinterpret_cast(lhs); + const T& t_rhs = *reinterpret_cast(rhs); + return t_lhs == t_rhs; + } + }; + + typedef void (*CCtr) (Memory, const Memory); // Copy c-tor (variant) + typedef void (*MCtr) (Memory, void*); // Generic move c-tor + typedef void (*Copy) (Memory, const Memory); // Copy assignment + typedef void (*Move) (Memory, Memory); // Move assignment + + typedef void (*Swap) (Memory, Memory); // Swap + typedef void (*Dtor) (Memory); // Destructor + + using cnvrt_assgn_t = void (*) (Memory, void*); // Converting assignment (via std::forward) + using cnvrt_ctor_t = void (*) (Memory, void*); // Converting constructor (via std::forward) + + typedef bool (*Equal)(const Memory, const Memory); // Equality test (external) + + static constexpr std::array cctrs(){ return {{(&cctr_h::help)...}};} + static constexpr std::array mctrs(){ return {{(&mctr_h::help)...}};} + static constexpr std::array cpyrs(){ return {{(©_h::help)...}};} + static constexpr std::array mvers(){ return {{(&move_h::help)...}};} + static constexpr std::array swprs(){ return {{(&swap_h::help)...}};} + static constexpr std::array dtors(){ return {{(&dtor_h::help)...}};} + + template + struct conditional_ref : std::conditional::type&, typename std::remove_reference::type > {}; + + template + using conditional_ref_t = typename conditional_ref::type; + + + template + static constexpr std::array cnvrt_assgnrs(){ + return {{(&cnvrt_assign_h>::help)...}}; + } + + template + static constexpr std::array cnvrt_ctors(){ + return {{(&cnvrt_ctor_h>::help)...}}; + } + + std::size_t m_index = 0; + + protected: + template friend T& get(variant &v); + template friend const T& get(const variant &v); + template friend T* get_if(variant *v) noexcept; + template friend const T* get_if(const variant *v) noexcept; + + template friend bool operator==(const variant &lhs, + const variant &rhs); + Memory memory; + + public: + // Constructors + variant() noexcept; + variant(const variant& other); + variant(variant&& other) noexcept; + // are_different_t is a SFINAE trick to avoid variant(T &&t) with T=variant + // for some reason, this version is called instead of variant(variant&& o) when + // variant is used in STL containers (examples: vector assignment). + template< + typename T, + typename = util::are_different_t + > + explicit variant(T&& t); + // template explicit variant(Args&&... args); + // FIXME: other constructors + + // Destructor + ~variant(); + + // Assignment + variant& operator=(const variant& rhs); + variant& operator=(variant &&rhs) noexcept; + + // SFINAE trick to avoid operator=(T&&) with T=variant<>, see comment above + template< + typename T, + typename = util::are_different_t + > + variant& operator=(T&& t) noexcept; + + // Observers + std::size_t index() const noexcept; + // FIXME: valueless_by_exception() + + // Modifiers + // FIXME: emplace() + void swap(variant &rhs) noexcept; + + // Non-C++17x! + template static constexpr std::size_t index_of(); + }; + + // FIMXE: visit + template + T* get_if(util::variant* v) noexcept; + + template + const T* get_if(const util::variant* v) noexcept; + + template + T& get(util::variant &v); + + template + const T& get(const util::variant &v); + + template + typename util::type_list_element::type& get(util::variant &v); + + template + const typename util::type_list_element::type& get(const util::variant &v); + + template + bool holds_alternative(const util::variant &v) noexcept; + + + // Visitor + namespace detail + { + struct visitor_interface {}; + + // Class `visitor_return_type_deduction_helper` + // introduces solution for deduction `return_type` in `visit` function in common way + // for both Lambda and class Visitor and keep one interface invocation point: `visit` only + // his helper class is required to unify return_type deduction mechanism because + // for Lambda it is possible to take type of `decltype(visitor(get<0>(var)))` + // but for class Visitor there is no operator() in base case, + // because it provides `operator() (std::size_t index, ...)` + // So `visitor_return_type_deduction_helper` expose `operator()` + // uses only for class Visitor only for deduction `return type` in visit() + template + struct visitor_return_type_deduction_helper + { + using return_type = R; + + // to be used in Lambda return type deduction context only + template + return_type operator() (T&&); + }; + } + + // Special purpose `static_visitor` can receive additional arguments + template + struct static_visitor : public detail::visitor_interface, + public detail::visitor_return_type_deduction_helper { + + // assign responsibility for return type deduction to helper class + using return_type = typename detail::visitor_return_type_deduction_helper::return_type; + using detail::visitor_return_type_deduction_helper::operator(); + friend Impl; + + template + return_type operator() (std::size_t index, VariantValue&& value, Args&& ...args) + { + suppress_unused_warning(index); + return static_cast(this)-> visit( + std::forward(value), + std::forward(args)...); + } + }; + + // Special purpose `static_indexed_visitor` can receive additional arguments + // And make forwarding current variant index as runtime function argument to its `Impl` + template + struct static_indexed_visitor : public detail::visitor_interface, + public detail::visitor_return_type_deduction_helper { + + // assign responsibility for return type deduction to helper class + using return_type = typename detail::visitor_return_type_deduction_helper::return_type; + using detail::visitor_return_type_deduction_helper::operator(); + friend Impl; + + template + return_type operator() (std::size_t Index, VariantValue&& value, Args&& ...args) + { + return static_cast(this)-> visit(Index, + std::forward(value), + std::forward(args)...); + } + }; + + template + struct variant_size; + + template + struct variant_size> + : std::integral_constant { }; + // FIXME: T&&, const TT&& versions. + + // Implementation ////////////////////////////////////////////////////////// + template + variant::variant() noexcept + { + typedef typename std::tuple_element<0, std::tuple >::type TFirst; + new (memory) TFirst(); + } + + template + variant::variant(const variant &other) + : m_index(other.m_index) + { + (cctrs()[m_index])(memory, other.memory); + } + + template + variant::variant(variant &&other) noexcept + : m_index(other.m_index) + { + (mctrs()[m_index])(memory, other.memory); + } + + template + template + variant::variant(T&& t) + : m_index(util::type_list_index, Ts...>::value) + { + const constexpr bool is_lvalue_arg = std::is_lvalue_reference::value; + (cnvrt_ctors()[m_index])(memory, const_cast *>(&t)); + } + + template + variant::~variant() + { + (dtors()[m_index])(memory); + } + + template + variant& variant::operator=(const variant &rhs) + { + if (m_index != rhs.m_index) + { + (dtors()[ m_index])(memory); + (cctrs()[rhs.m_index])(memory, rhs.memory); + m_index = rhs.m_index; + } + else + { + (cpyrs()[rhs.m_index])(memory, rhs.memory); + } + return *this; + } + + template + variant& variant::operator=(variant &&rhs) noexcept + { + if (m_index != rhs.m_index) + { + (dtors()[ m_index])(memory); + (mctrs()[rhs.m_index])(memory, rhs.memory); + m_index = rhs.m_index; + } + else + { + (mvers()[rhs.m_index])(memory, rhs.memory); + } + return *this; + } + + template + template + variant& variant::operator=(T&& t) noexcept + { + using decayed_t = util::decay_t; + // FIXME: No version with implicit type conversion available! + const constexpr std::size_t t_index = + util::type_list_index::value; + + const constexpr bool is_lvalue_arg = std::is_lvalue_reference::value; + + if (t_index != m_index) + { + (dtors()[m_index])(memory); + (cnvrt_ctors()[t_index])(memory, &t); + m_index = t_index; + } + else + { + (cnvrt_assgnrs()[m_index])(memory, &t); + } + return *this; + + } + + template + std::size_t util::variant::index() const noexcept + { + return m_index; + } + + template + void variant::swap(variant &rhs) noexcept + { + if (m_index == rhs.index()) + { + (swprs()[m_index](memory, rhs.memory)); + } + else + { + variant tmp(std::move(*this)); + *this = std::move(rhs); + rhs = std::move(tmp); + } + } + + template + template + constexpr std::size_t variant::index_of() + { + return util::type_list_index::value; // FIXME: tests! + } + + template + T* get_if(util::variant* v) noexcept + { + const constexpr std::size_t t_index = + util::type_list_index::value; + + if (v && v->index() == t_index) + return (T*)(&v->memory); // workaround for ICC 2019 + // original code: return reinterpret_cast(v.memory); + return nullptr; + } + + template + const T* get_if(const util::variant* v) noexcept + { + const constexpr std::size_t t_index = + util::type_list_index::value; + + if (v && v->index() == t_index) + return (const T*)(&v->memory); // workaround for ICC 2019 + // original code: return reinterpret_cast(v.memory); + return nullptr; + } + + template + T& get(util::variant &v) + { + if (auto* p = get_if(&v)) + return *p; + else + throw_error(bad_variant_access()); + } + + template + const T& get(const util::variant &v) + { + if (auto* p = get_if(&v)) + return *p; + else + throw_error(bad_variant_access()); + } + + template + typename util::type_list_element::type& get(util::variant &v) + { + using ReturnType = typename util::type_list_element::type; + return const_cast(get(static_cast &>(v))); + } + + template + const typename util::type_list_element::type& get(const util::variant &v) + { + static_assert(Index < sizeof...(Types), + "`Index` it out of bound of `util::variant` type list"); + using ReturnType = typename util::type_list_element::type; + return get(v); + } + + template + bool holds_alternative(const util::variant &v) noexcept + { + return v.index() == util::variant::template index_of(); + } + +#if defined(__GNUC__) && (__GNUC__ == 11 || __GNUC__ == 12) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wmaybe-uninitialized" +#endif + + template bool operator==(const variant &lhs, + const variant &rhs) + { + using V = variant; + + // Instantiate table only here since it requires operator== for + // should have operator== only if this one is used, not in general + static const std::array eqs = { + {(&V::template equal_h::help)...} + }; + if (lhs.index() != rhs.index()) + return false; + return (eqs[lhs.index()])(lhs.memory, rhs.memory); + } + +#if defined(__GNUC__) && (__GNUC__ == 11 || __GNUC__ == 12) +#pragma GCC diagnostic pop +#endif + + template bool operator!=(const variant &lhs, + const variant &rhs) + { + return !(lhs == rhs); + } + +namespace detail +{ + // terminate recursion implementation for `non-void` ReturnType + template + ReturnType apply_visitor_impl(Visitor&&, Variant&, + std::true_type, std::false_type, + VisitorArgs&& ...) + { + return {}; + } + + // terminate recursion implementation for `void` ReturnType + template + void apply_visitor_impl(Visitor&&, Variant&, + std::true_type, std::true_type, + VisitorArgs&& ...) + { + } + + // Intermediate resursion processor for Lambda Visitors + template + typename std::enable_if::type>::value, ReturnType>::type + apply_visitor_impl(Visitor&& visitor, Variant&& v, std::false_type not_processed, + std::integral_constant should_no_return, + VisitorArgs&& ...args) + { + static_assert(std::is_same(v)))>::value, + "Different `ReturnType`s detected! All `Visitor::visit` or `overload_lamba_set`" + " must return the same type"); + suppress_unused_warning(not_processed); + if (v.index() == CurIndex) + { + return visitor.operator()(get(v), std::forward(args)... ); + } + + using is_variant_processed_t = std::integral_constant= ElemCount>; + return apply_visitor_impl( + std::forward(visitor), + std::forward(v), + is_variant_processed_t{}, + should_no_return, + std::forward(args)...); + } + + //Visual Studio 2014 compilation fix: cast visitor to base class before invoke operator() + template + typename std::enable_if::type>, + typename std::decay::type>::value, ReturnType>::type + invoke_class_visitor(Visitor& visitor, Value&& v, VisitorArgs&&...args) + { + return static_cast::type>&>(visitor).operator() (CurIndex, std::forward(v), std::forward(args)... ); + } + + //Visual Studio 2014 compilation fix: cast visitor to base class before invoke operator() + template + typename std::enable_if::type>, + typename std::decay::type>::value, ReturnType>::type + invoke_class_visitor(Visitor& visitor, Value&& v, VisitorArgs&&...args) + { + return static_cast::type>&>(visitor).operator() (CurIndex, std::forward(v), std::forward(args)... ); + } + + // Intermediate recursion processor for special case `visitor_interface` derived Visitors + template + typename std::enable_if::type>::value, ReturnType>::type + apply_visitor_impl(Visitor&& visitor, Variant&& v, std::false_type not_processed, + std::integral_constant should_no_return, + VisitorArgs&& ...args) + { + static_assert(std::is_same(v)))>::value, + "Different `ReturnType`s detected! All `Visitor::visit` or `overload_lamba_set`" + " must return the same type"); + suppress_unused_warning(not_processed); + if (v.index() == CurIndex) + { + return invoke_class_visitor(visitor, get(v), std::forward(args)... ); + } + + using is_variant_processed_t = std::integral_constant= ElemCount>; + return apply_visitor_impl( + std::forward(visitor), + std::forward(v), + is_variant_processed_t{}, + should_no_return, + std::forward(args)...); + } +} // namespace detail + + template + auto visit(Visitor &visitor, const Variant& var, VisitorArg &&...args) -> decltype(visitor(get<0>(var))) + { + constexpr std::size_t varsize = util::variant_size::value; + static_assert(varsize != 0, "utils::variant must contains one type at least "); + using is_variant_processed_t = std::false_type; + + using ReturnType = decltype(visitor(get<0>(var))); + using return_t = std::is_same; + return detail::apply_visitor_impl( + std::forward(visitor), + var, is_variant_processed_t{}, + return_t{}, + std::forward(args)...); + } + + template + auto visit(Visitor&& visitor, const Variant& var) -> decltype(visitor(get<0>(var))) + { + constexpr std::size_t varsize = util::variant_size::value; + static_assert(varsize != 0, "utils::variant must contains one type at least "); + using is_variant_processed_t = std::false_type; + + using ReturnType = decltype(visitor(get<0>(var))); + using return_t = std::is_same; + return detail::apply_visitor_impl( + std::forward(visitor), + var, is_variant_processed_t{}, + return_t{}); + } +} // namespace util +} // namespace cv + +#endif // OPENCV_GAPI_UTIL_VARIANT_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/video.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/video.hpp index 4dcc1d4182..65f0a4b7ec 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/video.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/video.hpp @@ -1,364 +1,364 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020 Intel Corporation - -#ifndef OPENCV_GAPI_VIDEO_HPP -#define OPENCV_GAPI_VIDEO_HPP - -#include // std::tuple - -#include - - -/** \defgroup gapi_video G-API Video processing functionality - */ - -namespace cv { namespace gapi { - -/** @brief Structure for the Kalman filter's initialization parameters.*/ - -struct GAPI_EXPORTS KalmanParams -{ - // initial state - - //! corrected state (x(k)): x(k)=x'(k)+K(k)*(z(k)-H*x'(k)) - Mat state; - //! posteriori error estimate covariance matrix (P(k)): P(k)=(I-K(k)*H)*P'(k) - Mat errorCov; - - // dynamic system description - - //! state transition matrix (A) - Mat transitionMatrix; - //! measurement matrix (H) - Mat measurementMatrix; - //! process noise covariance matrix (Q) - Mat processNoiseCov; - //! measurement noise covariance matrix (R) - Mat measurementNoiseCov; - //! control matrix (B) (Optional: not used if there's no control) - Mat controlMatrix; -}; - -/** - * @brief This namespace contains G-API Operations and functions for - * video-oriented algorithms, like optical flow and background subtraction. - */ -namespace video -{ -using GBuildPyrOutput = std::tuple, GScalar>; - -using GOptFlowLKOutput = std::tuple, - cv::GArray, - cv::GArray>; - -G_TYPED_KERNEL(GBuildOptFlowPyramid, , - "org.opencv.video.buildOpticalFlowPyramid") -{ - static std::tuple - outMeta(GMatDesc,const Size&,GScalarDesc,bool,int,int,bool) - { - return std::make_tuple(empty_array_desc(), empty_scalar_desc()); - } -}; - -G_TYPED_KERNEL(GCalcOptFlowLK, - ,cv::GArray,Size, - GScalar,TermCriteria,int,double)>, - "org.opencv.video.calcOpticalFlowPyrLK") -{ - static std::tuple outMeta(GMatDesc,GMatDesc,GArrayDesc, - GArrayDesc,const Size&,GScalarDesc, - const TermCriteria&,int,double) - { - return std::make_tuple(empty_array_desc(), empty_array_desc(), empty_array_desc()); - } - -}; - -G_TYPED_KERNEL(GCalcOptFlowLKForPyr, - ,cv::GArray, - cv::GArray,cv::GArray,Size,GScalar, - TermCriteria,int,double)>, - "org.opencv.video.calcOpticalFlowPyrLKForPyr") -{ - static std::tuple outMeta(GArrayDesc,GArrayDesc, - GArrayDesc,GArrayDesc, - const Size&,GScalarDesc, - const TermCriteria&,int,double) - { - return std::make_tuple(empty_array_desc(), empty_array_desc(), empty_array_desc()); - } -}; - -enum BackgroundSubtractorType -{ - TYPE_BS_MOG2, - TYPE_BS_KNN -}; - -/** @brief Structure for the Background Subtractor operation's initialization parameters.*/ - -struct BackgroundSubtractorParams -{ - //! Type of the Background Subtractor operation. - BackgroundSubtractorType operation = TYPE_BS_MOG2; - - //! Length of the history. - int history = 500; - - //! For MOG2: Threshold on the squared Mahalanobis distance between the pixel - //! and the model to decide whether a pixel is well described by - //! the background model. - //! For KNN: Threshold on the squared distance between the pixel and the sample - //! to decide whether a pixel is close to that sample. - double threshold = 16; - - //! If true, the algorithm will detect shadows and mark them. - bool detectShadows = true; - - //! The value between 0 and 1 that indicates how fast - //! the background model is learnt. - //! Negative parameter value makes the algorithm use some automatically - //! chosen learning rate. - double learningRate = -1; - - //! default constructor - BackgroundSubtractorParams() {} - - /** Full constructor - @param op MOG2/KNN Background Subtractor type. - @param histLength Length of the history. - @param thrshld For MOG2: Threshold on the squared Mahalanobis distance between - the pixel and the model to decide whether a pixel is well described by the background model. - For KNN: Threshold on the squared distance between the pixel and the sample to decide - whether a pixel is close to that sample. - @param detect If true, the algorithm will detect shadows and mark them. It decreases the - speed a bit, so if you do not need this feature, set the parameter to false. - @param lRate The value between 0 and 1 that indicates how fast the background model is learnt. - Negative parameter value makes the algorithm to use some automatically chosen learning rate. - */ - BackgroundSubtractorParams(BackgroundSubtractorType op, int histLength, - double thrshld, bool detect, double lRate) : operation(op), - history(histLength), - threshold(thrshld), - detectShadows(detect), - learningRate(lRate){} -}; - -G_TYPED_KERNEL(GBackgroundSubtractor, , - "org.opencv.video.BackgroundSubtractor") -{ - static GMatDesc outMeta(const GMatDesc& in, const BackgroundSubtractorParams& bsParams) - { - GAPI_Assert(bsParams.history >= 0); - GAPI_Assert(bsParams.learningRate <= 1); - return in.withType(CV_8U, 1); - } -}; - -void checkParams(const cv::gapi::KalmanParams& kfParams, - const cv::GMatDesc& measurement, const cv::GMatDesc& control = {}); - -G_TYPED_KERNEL(GKalmanFilter, , GMat, KalmanParams)>, - "org.opencv.video.KalmanFilter") -{ - static GMatDesc outMeta(const GMatDesc& measurement, const GOpaqueDesc&, - const GMatDesc& control, const KalmanParams& kfParams) - { - checkParams(kfParams, measurement, control); - return measurement.withSize(Size(1, kfParams.transitionMatrix.rows)); - } -}; - -G_TYPED_KERNEL(GKalmanFilterNoControl, , KalmanParams)>, "org.opencv.video.KalmanFilterNoControl") -{ - static GMatDesc outMeta(const GMatDesc& measurement, const GOpaqueDesc&, const KalmanParams& kfParams) - { - checkParams(kfParams, measurement); - return measurement.withSize(Size(1, kfParams.transitionMatrix.rows)); - } -}; -} //namespace video - -//! @addtogroup gapi_video -//! @{ -/** @brief Constructs the image pyramid which can be passed to calcOpticalFlowPyrLK. - -@note Function textual ID is "org.opencv.video.buildOpticalFlowPyramid" - -@param img 8-bit input image. -@param winSize window size of optical flow algorithm. Must be not less than winSize - argument of calcOpticalFlowPyrLK. It is needed to calculate required - padding for pyramid levels. -@param maxLevel 0-based maximal pyramid level number. -@param withDerivatives set to precompute gradients for the every pyramid level. If pyramid is - constructed without the gradients then calcOpticalFlowPyrLK will calculate - them internally. -@param pyrBorder the border mode for pyramid layers. -@param derivBorder the border mode for gradients. -@param tryReuseInputImage put ROI of input image into the pyramid if possible. You can pass false - to force data copying. - -@return - - output pyramid. - - number of levels in constructed pyramid. Can be less than maxLevel. - */ -GAPI_EXPORTS std::tuple, GScalar> -buildOpticalFlowPyramid(const GMat &img, - const Size &winSize, - const GScalar &maxLevel, - bool withDerivatives = true, - int pyrBorder = BORDER_REFLECT_101, - int derivBorder = BORDER_CONSTANT, - bool tryReuseInputImage = true); - -/** @brief Calculates an optical flow for a sparse feature set using the iterative Lucas-Kanade -method with pyramids. - -See @cite Bouguet00 . - -@note Function textual ID is "org.opencv.video.calcOpticalFlowPyrLK" - -@param prevImg first 8-bit input image (GMat) or pyramid (GArray) constructed by -buildOpticalFlowPyramid. -@param nextImg second input image (GMat) or pyramid (GArray) of the same size and the same -type as prevImg. -@param prevPts GArray of 2D points for which the flow needs to be found; point coordinates must be -single-precision floating-point numbers. -@param predPts GArray of 2D points initial for the flow search; make sense only when -OPTFLOW_USE_INITIAL_FLOW flag is passed; in that case the vector must have the same size as in -the input. -@param winSize size of the search window at each pyramid level. -@param maxLevel 0-based maximal pyramid level number; if set to 0, pyramids are not used (single -level), if set to 1, two levels are used, and so on; if pyramids are passed to input then -algorithm will use as many levels as pyramids have but no more than maxLevel. -@param criteria parameter, specifying the termination criteria of the iterative search algorithm -(after the specified maximum number of iterations criteria.maxCount or when the search window -moves by less than criteria.epsilon). -@param flags operation flags: - - **OPTFLOW_USE_INITIAL_FLOW** uses initial estimations, stored in nextPts; if the flag is - not set, then prevPts is copied to nextPts and is considered the initial estimate. - - **OPTFLOW_LK_GET_MIN_EIGENVALS** use minimum eigen values as an error measure (see - minEigThreshold description); if the flag is not set, then L1 distance between patches - around the original and a moved point, divided by number of pixels in a window, is used as a - error measure. -@param minEigThresh the algorithm calculates the minimum eigen value of a 2x2 normal matrix of -optical flow equations (this matrix is called a spatial gradient matrix in @cite Bouguet00), divided -by number of pixels in a window; if this value is less than minEigThreshold, then a corresponding -feature is filtered out and its flow is not processed, so it allows to remove bad points and get a -performance boost. - -@return - - GArray of 2D points (with single-precision floating-point coordinates) -containing the calculated new positions of input features in the second image. - - status GArray (of unsigned chars); each element of the vector is set to 1 if -the flow for the corresponding features has been found, otherwise, it is set to 0. - - GArray of errors (doubles); each element of the vector is set to an error for the -corresponding feature, type of the error measure can be set in flags parameter; if the flow wasn't -found then the error is not defined (use the status parameter to find such cases). - */ -GAPI_EXPORTS std::tuple, GArray, GArray> -calcOpticalFlowPyrLK(const GMat &prevImg, - const GMat &nextImg, - const GArray &prevPts, - const GArray &predPts, - const Size &winSize = Size(21, 21), - const GScalar &maxLevel = 3, - const TermCriteria &criteria = TermCriteria(TermCriteria::COUNT | - TermCriteria::EPS, - 30, 0.01), - int flags = 0, - double minEigThresh = 1e-4); - -/** -@overload -@note Function textual ID is "org.opencv.video.calcOpticalFlowPyrLKForPyr" -*/ -GAPI_EXPORTS std::tuple, GArray, GArray> -calcOpticalFlowPyrLK(const GArray &prevPyr, - const GArray &nextPyr, - const GArray &prevPts, - const GArray &predPts, - const Size &winSize = Size(21, 21), - const GScalar &maxLevel = 3, - const TermCriteria &criteria = TermCriteria(TermCriteria::COUNT | - TermCriteria::EPS, - 30, 0.01), - int flags = 0, - double minEigThresh = 1e-4); - -/** @brief Gaussian Mixture-based or K-nearest neighbours-based Background/Foreground Segmentation Algorithm. -The operation generates a foreground mask. - -@return Output image is foreground mask, i.e. 8-bit unsigned 1-channel (binary) matrix @ref CV_8UC1. - -@note Functional textual ID is "org.opencv.video.BackgroundSubtractor" - -@param src input image: Floating point frame is used without scaling and should be in range [0,255]. -@param bsParams Set of initialization parameters for Background Subtractor kernel. -*/ -GAPI_EXPORTS GMat BackgroundSubtractor(const GMat& src, const cv::gapi::video::BackgroundSubtractorParams& bsParams); - -/** @brief Standard Kalman filter algorithm . - -@note Functional textual ID is "org.opencv.video.KalmanFilter" - -@param measurement input matrix: 32-bit or 64-bit float 1-channel matrix containing measurements. -@param haveMeasurement dynamic input flag that indicates whether we get measurements -at a particular iteration . -@param control input matrix: 32-bit or 64-bit float 1-channel matrix contains control data -for changing dynamic system. -@param kfParams Set of initialization parameters for Kalman filter kernel. - -@return Output matrix is predicted or corrected state. They can be 32-bit or 64-bit float -1-channel matrix @ref CV_32FC1 or @ref CV_64FC1. - -@details If measurement matrix is given (haveMeasurements == true), corrected state will -be returned which corresponds to the pipeline -cv::KalmanFilter::predict(control) -> cv::KalmanFilter::correct(measurement). -Otherwise, predicted state will be returned which corresponds to the call of -cv::KalmanFilter::predict(control). -@sa cv::KalmanFilter -*/ -GAPI_EXPORTS GMat KalmanFilter(const GMat& measurement, const GOpaque& haveMeasurement, - const GMat& control, const cv::gapi::KalmanParams& kfParams); - -/** @overload -The case of Standard Kalman filter algorithm when there is no control in a dynamic system. -In this case the controlMatrix is empty and control vector is absent. - -@note Function textual ID is "org.opencv.video.KalmanFilterNoControl" - -@param measurement input matrix: 32-bit or 64-bit float 1-channel matrix containing measurements. -@param haveMeasurement dynamic input flag that indicates whether we get measurements -at a particular iteration. -@param kfParams Set of initialization parameters for Kalman filter kernel. - -@return Output matrix is predicted or corrected state. They can be 32-bit or 64-bit float -1-channel matrix @ref CV_32FC1 or @ref CV_64FC1. - -@sa cv::KalmanFilter - */ -GAPI_EXPORTS GMat KalmanFilter(const GMat& measurement, const GOpaque& haveMeasurement, - const cv::gapi::KalmanParams& kfParams); - -//! @} gapi_video -} //namespace gapi -} //namespace cv - - -namespace cv { namespace detail { -template<> struct CompileArgTag -{ - static const char* tag() - { - return "org.opencv.video.background_substractor_params"; - } -}; -} // namespace detail -} // namespace cv - -#endif // OPENCV_GAPI_VIDEO_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020 Intel Corporation + +#ifndef OPENCV_GAPI_VIDEO_HPP +#define OPENCV_GAPI_VIDEO_HPP + +#include // std::tuple + +#include + + +/** \defgroup gapi_video G-API Video processing functionality + */ + +namespace cv { namespace gapi { + +/** @brief Structure for the Kalman filter's initialization parameters.*/ + +struct GAPI_EXPORTS KalmanParams +{ + // initial state + + //! corrected state (x(k)): x(k)=x'(k)+K(k)*(z(k)-H*x'(k)) + Mat state; + //! posteriori error estimate covariance matrix (P(k)): P(k)=(I-K(k)*H)*P'(k) + Mat errorCov; + + // dynamic system description + + //! state transition matrix (A) + Mat transitionMatrix; + //! measurement matrix (H) + Mat measurementMatrix; + //! process noise covariance matrix (Q) + Mat processNoiseCov; + //! measurement noise covariance matrix (R) + Mat measurementNoiseCov; + //! control matrix (B) (Optional: not used if there's no control) + Mat controlMatrix; +}; + +/** + * @brief This namespace contains G-API Operations and functions for + * video-oriented algorithms, like optical flow and background subtraction. + */ +namespace video +{ +using GBuildPyrOutput = std::tuple, GScalar>; + +using GOptFlowLKOutput = std::tuple, + cv::GArray, + cv::GArray>; + +G_TYPED_KERNEL(GBuildOptFlowPyramid, , + "org.opencv.video.buildOpticalFlowPyramid") +{ + static std::tuple + outMeta(GMatDesc,const Size&,GScalarDesc,bool,int,int,bool) + { + return std::make_tuple(empty_array_desc(), empty_scalar_desc()); + } +}; + +G_TYPED_KERNEL(GCalcOptFlowLK, + ,cv::GArray,Size, + GScalar,TermCriteria,int,double)>, + "org.opencv.video.calcOpticalFlowPyrLK") +{ + static std::tuple outMeta(GMatDesc,GMatDesc,GArrayDesc, + GArrayDesc,const Size&,GScalarDesc, + const TermCriteria&,int,double) + { + return std::make_tuple(empty_array_desc(), empty_array_desc(), empty_array_desc()); + } + +}; + +G_TYPED_KERNEL(GCalcOptFlowLKForPyr, + ,cv::GArray, + cv::GArray,cv::GArray,Size,GScalar, + TermCriteria,int,double)>, + "org.opencv.video.calcOpticalFlowPyrLKForPyr") +{ + static std::tuple outMeta(GArrayDesc,GArrayDesc, + GArrayDesc,GArrayDesc, + const Size&,GScalarDesc, + const TermCriteria&,int,double) + { + return std::make_tuple(empty_array_desc(), empty_array_desc(), empty_array_desc()); + } +}; + +enum BackgroundSubtractorType +{ + TYPE_BS_MOG2, + TYPE_BS_KNN +}; + +/** @brief Structure for the Background Subtractor operation's initialization parameters.*/ + +struct BackgroundSubtractorParams +{ + //! Type of the Background Subtractor operation. + BackgroundSubtractorType operation = TYPE_BS_MOG2; + + //! Length of the history. + int history = 500; + + //! For MOG2: Threshold on the squared Mahalanobis distance between the pixel + //! and the model to decide whether a pixel is well described by + //! the background model. + //! For KNN: Threshold on the squared distance between the pixel and the sample + //! to decide whether a pixel is close to that sample. + double threshold = 16; + + //! If true, the algorithm will detect shadows and mark them. + bool detectShadows = true; + + //! The value between 0 and 1 that indicates how fast + //! the background model is learnt. + //! Negative parameter value makes the algorithm use some automatically + //! chosen learning rate. + double learningRate = -1; + + //! default constructor + BackgroundSubtractorParams() {} + + /** Full constructor + @param op MOG2/KNN Background Subtractor type. + @param histLength Length of the history. + @param thrshld For MOG2: Threshold on the squared Mahalanobis distance between + the pixel and the model to decide whether a pixel is well described by the background model. + For KNN: Threshold on the squared distance between the pixel and the sample to decide + whether a pixel is close to that sample. + @param detect If true, the algorithm will detect shadows and mark them. It decreases the + speed a bit, so if you do not need this feature, set the parameter to false. + @param lRate The value between 0 and 1 that indicates how fast the background model is learnt. + Negative parameter value makes the algorithm to use some automatically chosen learning rate. + */ + BackgroundSubtractorParams(BackgroundSubtractorType op, int histLength, + double thrshld, bool detect, double lRate) : operation(op), + history(histLength), + threshold(thrshld), + detectShadows(detect), + learningRate(lRate){} +}; + +G_TYPED_KERNEL(GBackgroundSubtractor, , + "org.opencv.video.BackgroundSubtractor") +{ + static GMatDesc outMeta(const GMatDesc& in, const BackgroundSubtractorParams& bsParams) + { + GAPI_Assert(bsParams.history >= 0); + GAPI_Assert(bsParams.learningRate <= 1); + return in.withType(CV_8U, 1); + } +}; + +void checkParams(const cv::gapi::KalmanParams& kfParams, + const cv::GMatDesc& measurement, const cv::GMatDesc& control = {}); + +G_TYPED_KERNEL(GKalmanFilter, , GMat, KalmanParams)>, + "org.opencv.video.KalmanFilter") +{ + static GMatDesc outMeta(const GMatDesc& measurement, const GOpaqueDesc&, + const GMatDesc& control, const KalmanParams& kfParams) + { + checkParams(kfParams, measurement, control); + return measurement.withSize(Size(1, kfParams.transitionMatrix.rows)); + } +}; + +G_TYPED_KERNEL(GKalmanFilterNoControl, , KalmanParams)>, "org.opencv.video.KalmanFilterNoControl") +{ + static GMatDesc outMeta(const GMatDesc& measurement, const GOpaqueDesc&, const KalmanParams& kfParams) + { + checkParams(kfParams, measurement); + return measurement.withSize(Size(1, kfParams.transitionMatrix.rows)); + } +}; +} //namespace video + +//! @addtogroup gapi_video +//! @{ +/** @brief Constructs the image pyramid which can be passed to calcOpticalFlowPyrLK. + +@note Function textual ID is "org.opencv.video.buildOpticalFlowPyramid" + +@param img 8-bit input image. +@param winSize window size of optical flow algorithm. Must be not less than winSize + argument of calcOpticalFlowPyrLK. It is needed to calculate required + padding for pyramid levels. +@param maxLevel 0-based maximal pyramid level number. +@param withDerivatives set to precompute gradients for the every pyramid level. If pyramid is + constructed without the gradients then calcOpticalFlowPyrLK will calculate + them internally. +@param pyrBorder the border mode for pyramid layers. +@param derivBorder the border mode for gradients. +@param tryReuseInputImage put ROI of input image into the pyramid if possible. You can pass false + to force data copying. + +@return + - output pyramid. + - number of levels in constructed pyramid. Can be less than maxLevel. + */ +GAPI_EXPORTS std::tuple, GScalar> +buildOpticalFlowPyramid(const GMat &img, + const Size &winSize, + const GScalar &maxLevel, + bool withDerivatives = true, + int pyrBorder = BORDER_REFLECT_101, + int derivBorder = BORDER_CONSTANT, + bool tryReuseInputImage = true); + +/** @brief Calculates an optical flow for a sparse feature set using the iterative Lucas-Kanade +method with pyramids. + +See @cite Bouguet00 . + +@note Function textual ID is "org.opencv.video.calcOpticalFlowPyrLK" + +@param prevImg first 8-bit input image (GMat) or pyramid (GArray) constructed by +buildOpticalFlowPyramid. +@param nextImg second input image (GMat) or pyramid (GArray) of the same size and the same +type as prevImg. +@param prevPts GArray of 2D points for which the flow needs to be found; point coordinates must be +single-precision floating-point numbers. +@param predPts GArray of 2D points initial for the flow search; make sense only when +OPTFLOW_USE_INITIAL_FLOW flag is passed; in that case the vector must have the same size as in +the input. +@param winSize size of the search window at each pyramid level. +@param maxLevel 0-based maximal pyramid level number; if set to 0, pyramids are not used (single +level), if set to 1, two levels are used, and so on; if pyramids are passed to input then +algorithm will use as many levels as pyramids have but no more than maxLevel. +@param criteria parameter, specifying the termination criteria of the iterative search algorithm +(after the specified maximum number of iterations criteria.maxCount or when the search window +moves by less than criteria.epsilon). +@param flags operation flags: + - **OPTFLOW_USE_INITIAL_FLOW** uses initial estimations, stored in nextPts; if the flag is + not set, then prevPts is copied to nextPts and is considered the initial estimate. + - **OPTFLOW_LK_GET_MIN_EIGENVALS** use minimum eigen values as an error measure (see + minEigThreshold description); if the flag is not set, then L1 distance between patches + around the original and a moved point, divided by number of pixels in a window, is used as a + error measure. +@param minEigThresh the algorithm calculates the minimum eigen value of a 2x2 normal matrix of +optical flow equations (this matrix is called a spatial gradient matrix in @cite Bouguet00), divided +by number of pixels in a window; if this value is less than minEigThreshold, then a corresponding +feature is filtered out and its flow is not processed, so it allows to remove bad points and get a +performance boost. + +@return + - GArray of 2D points (with single-precision floating-point coordinates) +containing the calculated new positions of input features in the second image. + - status GArray (of unsigned chars); each element of the vector is set to 1 if +the flow for the corresponding features has been found, otherwise, it is set to 0. + - GArray of errors (doubles); each element of the vector is set to an error for the +corresponding feature, type of the error measure can be set in flags parameter; if the flow wasn't +found then the error is not defined (use the status parameter to find such cases). + */ +GAPI_EXPORTS std::tuple, GArray, GArray> +calcOpticalFlowPyrLK(const GMat &prevImg, + const GMat &nextImg, + const GArray &prevPts, + const GArray &predPts, + const Size &winSize = Size(21, 21), + const GScalar &maxLevel = 3, + const TermCriteria &criteria = TermCriteria(TermCriteria::COUNT | + TermCriteria::EPS, + 30, 0.01), + int flags = 0, + double minEigThresh = 1e-4); + +/** +@overload +@note Function textual ID is "org.opencv.video.calcOpticalFlowPyrLKForPyr" +*/ +GAPI_EXPORTS std::tuple, GArray, GArray> +calcOpticalFlowPyrLK(const GArray &prevPyr, + const GArray &nextPyr, + const GArray &prevPts, + const GArray &predPts, + const Size &winSize = Size(21, 21), + const GScalar &maxLevel = 3, + const TermCriteria &criteria = TermCriteria(TermCriteria::COUNT | + TermCriteria::EPS, + 30, 0.01), + int flags = 0, + double minEigThresh = 1e-4); + +/** @brief Gaussian Mixture-based or K-nearest neighbours-based Background/Foreground Segmentation Algorithm. +The operation generates a foreground mask. + +@return Output image is foreground mask, i.e. 8-bit unsigned 1-channel (binary) matrix @ref CV_8UC1. + +@note Functional textual ID is "org.opencv.video.BackgroundSubtractor" + +@param src input image: Floating point frame is used without scaling and should be in range [0,255]. +@param bsParams Set of initialization parameters for Background Subtractor kernel. +*/ +GAPI_EXPORTS GMat BackgroundSubtractor(const GMat& src, const cv::gapi::video::BackgroundSubtractorParams& bsParams); + +/** @brief Standard Kalman filter algorithm . + +@note Functional textual ID is "org.opencv.video.KalmanFilter" + +@param measurement input matrix: 32-bit or 64-bit float 1-channel matrix containing measurements. +@param haveMeasurement dynamic input flag that indicates whether we get measurements +at a particular iteration . +@param control input matrix: 32-bit or 64-bit float 1-channel matrix contains control data +for changing dynamic system. +@param kfParams Set of initialization parameters for Kalman filter kernel. + +@return Output matrix is predicted or corrected state. They can be 32-bit or 64-bit float +1-channel matrix @ref CV_32FC1 or @ref CV_64FC1. + +@details If measurement matrix is given (haveMeasurements == true), corrected state will +be returned which corresponds to the pipeline +cv::KalmanFilter::predict(control) -> cv::KalmanFilter::correct(measurement). +Otherwise, predicted state will be returned which corresponds to the call of +cv::KalmanFilter::predict(control). +@sa cv::KalmanFilter +*/ +GAPI_EXPORTS GMat KalmanFilter(const GMat& measurement, const GOpaque& haveMeasurement, + const GMat& control, const cv::gapi::KalmanParams& kfParams); + +/** @overload +The case of Standard Kalman filter algorithm when there is no control in a dynamic system. +In this case the controlMatrix is empty and control vector is absent. + +@note Function textual ID is "org.opencv.video.KalmanFilterNoControl" + +@param measurement input matrix: 32-bit or 64-bit float 1-channel matrix containing measurements. +@param haveMeasurement dynamic input flag that indicates whether we get measurements +at a particular iteration. +@param kfParams Set of initialization parameters for Kalman filter kernel. + +@return Output matrix is predicted or corrected state. They can be 32-bit or 64-bit float +1-channel matrix @ref CV_32FC1 or @ref CV_64FC1. + +@sa cv::KalmanFilter + */ +GAPI_EXPORTS GMat KalmanFilter(const GMat& measurement, const GOpaque& haveMeasurement, + const cv::gapi::KalmanParams& kfParams); + +//! @} gapi_video +} //namespace gapi +} //namespace cv + + +namespace cv { namespace detail { +template<> struct CompileArgTag +{ + static const char* tag() + { + return "org.opencv.video.background_substractor_params"; + } +}; +} // namespace detail +} // namespace cv + +#endif // OPENCV_GAPI_VIDEO_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/highgui.hpp b/3rdParty/opencv-4.11.0/opencv2/highgui.hpp index 5f69721ce9..81437f4ef1 100644 --- a/3rdParty/opencv-4.11.0/opencv2/highgui.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/highgui.hpp @@ -1,830 +1,830 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_HIGHGUI_HPP -#define OPENCV_HIGHGUI_HPP - -#include "opencv2/core.hpp" -#ifdef HAVE_OPENCV_IMGCODECS -#include "opencv2/imgcodecs.hpp" -#endif -#ifdef HAVE_OPENCV_VIDEOIO -#include "opencv2/videoio.hpp" -#endif - -/** -@defgroup highgui High-level GUI - -While OpenCV was designed for use in full-scale applications and can be used within functionally -rich UI frameworks (such as Qt\*, WinForms\*, or Cocoa\*) or without any UI at all, sometimes there -it is required to try functionality quickly and visualize the results. This is what the HighGUI -module has been designed for. - -It provides easy interface to: - -- Create and manipulate windows that can display images and "remember" their content (no need to - handle repaint events from OS). -- Add trackbars to the windows, handle simple mouse events as well as keyboard commands. - -@{ - @defgroup highgui_window_flags Flags related creating and manipulating HighGUI windows and mouse events - @defgroup highgui_opengl OpenGL support - @defgroup highgui_qt Qt New Functions - - ![image](pics/qtgui.png) - - This figure explains new functionality implemented with Qt\* GUI. The new GUI provides a statusbar, - a toolbar, and a control panel. The control panel can have trackbars and buttonbars attached to it. - If you cannot see the control panel, press Ctrl+P or right-click any Qt window and select **Display - properties window**. - - - To attach a trackbar, the window name parameter must be NULL. - - - To attach a buttonbar, a button must be created. If the last bar attached to the control panel - is a buttonbar, the new button is added to the right of the last button. If the last bar - attached to the control panel is a trackbar, or the control panel is empty, a new buttonbar is - created. Then, a new button is attached to it. - - See below the example used to generate the figure: - - @include highgui_qt.cpp - - @defgroup highgui_winrt WinRT support - - This figure explains new functionality implemented with WinRT GUI. The new GUI provides an Image control, - and a slider panel. Slider panel holds trackbars attached to it. - - Sliders are attached below the image control. Every new slider is added below the previous one. - - See below the example used to generate the figure: - @code - void sample_app::MainPage::ShowWindow() - { - static cv::String windowName("sample"); - cv::winrt_initContainer(this->cvContainer); - cv::namedWindow(windowName); // not required - - cv::Mat image = cv::imread("Assets/sample.jpg"); - cv::Mat converted = cv::Mat(image.rows, image.cols, CV_8UC4); - cv::cvtColor(image, converted, COLOR_BGR2BGRA); - cv::imshow(windowName, converted); // this will create window if it hasn't been created before - - int state = 42; - cv::TrackbarCallback callback = [](int pos, void* userdata) - { - if (pos == 0) { - cv::destroyWindow(windowName); - } - }; - cv::TrackbarCallback callbackTwin = [](int pos, void* userdata) - { - if (pos >= 70) { - cv::destroyAllWindows(); - } - }; - cv::createTrackbar("Sample trackbar", windowName, &state, 100, callback); - cv::createTrackbar("Twin brother", windowName, &state, 100, callbackTwin); - } - @endcode -@} -*/ - -///////////////////////// graphical user interface ////////////////////////// -namespace cv -{ - -//! @addtogroup highgui -//! @{ - -//! @addtogroup highgui_window_flags -//! @{ - -//! Flags for cv::namedWindow -enum WindowFlags { - WINDOW_NORMAL = 0x00000000, //!< the user can resize the window (no constraint) / also use to switch a fullscreen window to a normal size. - WINDOW_AUTOSIZE = 0x00000001, //!< the user cannot resize the window, the size is constrainted by the image displayed. - WINDOW_OPENGL = 0x00001000, //!< window with opengl support. - - WINDOW_FULLSCREEN = 1, //!< change the window to fullscreen. - WINDOW_FREERATIO = 0x00000100, //!< the image expends as much as it can (no ratio constraint). - WINDOW_KEEPRATIO = 0x00000000, //!< the ratio of the image is respected. - WINDOW_GUI_EXPANDED=0x00000000, //!< status bar and tool bar - WINDOW_GUI_NORMAL = 0x00000010, //!< old fashious way - }; - -//! Flags for cv::setWindowProperty / cv::getWindowProperty -enum WindowPropertyFlags { - WND_PROP_FULLSCREEN = 0, //!< fullscreen property (can be WINDOW_NORMAL or WINDOW_FULLSCREEN). - WND_PROP_AUTOSIZE = 1, //!< autosize property (can be WINDOW_NORMAL or WINDOW_AUTOSIZE). - WND_PROP_ASPECT_RATIO = 2, //!< window's aspect ration (can be set to WINDOW_FREERATIO or WINDOW_KEEPRATIO). - WND_PROP_OPENGL = 3, //!< opengl support. - WND_PROP_VISIBLE = 4, //!< checks whether the window exists and is visible - WND_PROP_TOPMOST = 5, //!< property to toggle normal window being topmost or not - WND_PROP_VSYNC = 6 //!< enable or disable VSYNC (in OpenGL mode) - }; - -//! Mouse Events see cv::MouseCallback -enum MouseEventTypes { - EVENT_MOUSEMOVE = 0, //!< indicates that the mouse pointer has moved over the window. - EVENT_LBUTTONDOWN = 1, //!< indicates that the left mouse button is pressed. - EVENT_RBUTTONDOWN = 2, //!< indicates that the right mouse button is pressed. - EVENT_MBUTTONDOWN = 3, //!< indicates that the middle mouse button is pressed. - EVENT_LBUTTONUP = 4, //!< indicates that left mouse button is released. - EVENT_RBUTTONUP = 5, //!< indicates that right mouse button is released. - EVENT_MBUTTONUP = 6, //!< indicates that middle mouse button is released. - EVENT_LBUTTONDBLCLK = 7, //!< indicates that left mouse button is double clicked. - EVENT_RBUTTONDBLCLK = 8, //!< indicates that right mouse button is double clicked. - EVENT_MBUTTONDBLCLK = 9, //!< indicates that middle mouse button is double clicked. - EVENT_MOUSEWHEEL = 10,//!< positive and negative values mean forward and backward scrolling, respectively. - EVENT_MOUSEHWHEEL = 11 //!< positive and negative values mean right and left scrolling, respectively. - }; - -//! Mouse Event Flags see cv::MouseCallback -enum MouseEventFlags { - EVENT_FLAG_LBUTTON = 1, //!< indicates that the left mouse button is down. - EVENT_FLAG_RBUTTON = 2, //!< indicates that the right mouse button is down. - EVENT_FLAG_MBUTTON = 4, //!< indicates that the middle mouse button is down. - EVENT_FLAG_CTRLKEY = 8, //!< indicates that CTRL Key is pressed. - EVENT_FLAG_SHIFTKEY = 16,//!< indicates that SHIFT Key is pressed. - EVENT_FLAG_ALTKEY = 32 //!< indicates that ALT Key is pressed. - }; - -//! @} highgui_window_flags - -//! @addtogroup highgui_qt -//! @{ - -//! Qt font weight -enum QtFontWeights { - QT_FONT_LIGHT = 25, //!< Weight of 25 - QT_FONT_NORMAL = 50, //!< Weight of 50 - QT_FONT_DEMIBOLD = 63, //!< Weight of 63 - QT_FONT_BOLD = 75, //!< Weight of 75 - QT_FONT_BLACK = 87 //!< Weight of 87 - }; - -//! Qt font style -enum QtFontStyles { - QT_STYLE_NORMAL = 0, //!< Normal font. - QT_STYLE_ITALIC = 1, //!< Italic font. - QT_STYLE_OBLIQUE = 2 //!< Oblique font. - }; - -//! Qt "button" type -enum QtButtonTypes { - QT_PUSH_BUTTON = 0, //!< Push button. - QT_CHECKBOX = 1, //!< Checkbox button. - QT_RADIOBOX = 2, //!< Radiobox button. - QT_NEW_BUTTONBAR = 1024 //!< Button should create a new buttonbar - }; - -//! @} highgui_qt - -/** @brief Callback function for mouse events. see cv::setMouseCallback -@param event one of the cv::MouseEventTypes constants. -@param x The x-coordinate of the mouse event. -@param y The y-coordinate of the mouse event. -@param flags one of the cv::MouseEventFlags constants. -@param userdata The optional parameter. - */ -typedef void (*MouseCallback)(int event, int x, int y, int flags, void* userdata); - -/** @brief Callback function for Trackbar see cv::createTrackbar -@param pos current position of the specified trackbar. -@param userdata The optional parameter. - */ -typedef void (*TrackbarCallback)(int pos, void* userdata); - -/** @brief Callback function defined to be called every frame. See cv::setOpenGlDrawCallback -@param userdata The optional parameter. - */ -typedef void (*OpenGlDrawCallback)(void* userdata); - -/** @brief Callback function for a button created by cv::createButton -@param state current state of the button. It could be -1 for a push button, 0 or 1 for a check/radio box button. -@param userdata The optional parameter. - */ -typedef void (*ButtonCallback)(int state, void* userdata); - -/** @brief Creates a window. - -The function namedWindow creates a window that can be used as a placeholder for images and -trackbars. Created windows are referred to by their names. - -If a window with the same name already exists, the function does nothing. - -You can call cv::destroyWindow or cv::destroyAllWindows to close the window and de-allocate any associated -memory usage. For a simple program, you do not really have to call these functions because all the -resources and windows of the application are closed automatically by the operating system upon exit. - -@note Qt backend supports additional flags: - - **WINDOW_NORMAL or WINDOW_AUTOSIZE:** WINDOW_NORMAL enables you to resize the - window, whereas WINDOW_AUTOSIZE adjusts automatically the window size to fit the - displayed image (see imshow ), and you cannot change the window size manually. - - **WINDOW_FREERATIO or WINDOW_KEEPRATIO:** WINDOW_FREERATIO adjusts the image - with no respect to its ratio, whereas WINDOW_KEEPRATIO keeps the image ratio. - - **WINDOW_GUI_NORMAL or WINDOW_GUI_EXPANDED:** WINDOW_GUI_NORMAL is the old way to draw the window - without statusbar and toolbar, whereas WINDOW_GUI_EXPANDED is a new enhanced GUI. -By default, flags == WINDOW_AUTOSIZE | WINDOW_KEEPRATIO | WINDOW_GUI_EXPANDED - -@param winname Name of the window in the window caption that may be used as a window identifier. -@param flags Flags of the window. The supported flags are: (cv::WindowFlags) - */ -CV_EXPORTS_W void namedWindow(const String& winname, int flags = WINDOW_AUTOSIZE); - -/** @brief Destroys the specified window. - -The function destroyWindow destroys the window with the given name. - -@param winname Name of the window to be destroyed. - */ -CV_EXPORTS_W void destroyWindow(const String& winname); - -/** @brief Destroys all of the HighGUI windows. - -The function destroyAllWindows destroys all of the opened HighGUI windows. - */ -CV_EXPORTS_W void destroyAllWindows(); - - -/** @brief HighGUI backend used. - -The function returns HighGUI backend name used: could be COCOA, GTK2/3, QT, WAYLAND or WIN32. -Returns empty string if there is no available UI backend. - */ -CV_EXPORTS_W const std::string currentUIFramework(); - - -CV_EXPORTS_W int startWindowThread(); - -/** @brief Similar to #waitKey, but returns full key code. - -@note Key code is implementation specific and depends on used backend: QT/GTK/Win32/etc - -*/ -CV_EXPORTS_W int waitKeyEx(int delay = 0); - -/** @brief Waits for a pressed key. - -The function waitKey waits for a key event infinitely (when \f$\texttt{delay}\leq 0\f$ ) or for delay -milliseconds, when it is positive. Since the OS has a minimum time between switching threads, the -function will not wait exactly delay ms, it will wait at least delay ms, depending on what else is -running on your computer at that time. It returns the code of the pressed key or -1 if no key was -pressed before the specified time had elapsed. To check for a key press but not wait for it, use -#pollKey. - -@note The functions #waitKey and #pollKey are the only methods in HighGUI that can fetch and handle -GUI events, so one of them needs to be called periodically for normal event processing unless -HighGUI is used within an environment that takes care of event processing. - -@note The function only works if there is at least one HighGUI window created and the window is -active. If there are several HighGUI windows, any of them can be active. - -@param delay Delay in milliseconds. 0 is the special value that means "forever". - */ -CV_EXPORTS_W int waitKey(int delay = 0); - -/** @brief Polls for a pressed key. - -The function pollKey polls for a key event without waiting. It returns the code of the pressed key -or -1 if no key was pressed since the last invocation. To wait until a key was pressed, use #waitKey. - -@note The functions #waitKey and #pollKey are the only methods in HighGUI that can fetch and handle -GUI events, so one of them needs to be called periodically for normal event processing unless -HighGUI is used within an environment that takes care of event processing. - -@note The function only works if there is at least one HighGUI window created and the window is -active. If there are several HighGUI windows, any of them can be active. - */ -CV_EXPORTS_W int pollKey(); - -/** @brief Displays an image in the specified window. - -The function imshow displays an image in the specified window. If the window was created with the -cv::WINDOW_AUTOSIZE flag, the image is shown with its original size, however it is still limited by the screen resolution. -Otherwise, the image is scaled to fit the window. The function may scale the image, depending on its depth: - -- If the image is 8-bit unsigned, it is displayed as is. -- If the image is 16-bit unsigned, the pixels are divided by 256. That is, the - value range [0,255\*256] is mapped to [0,255]. -- If the image is 32-bit or 64-bit floating-point, the pixel values are multiplied by 255. That is, the - value range [0,1] is mapped to [0,255]. -- 32-bit integer images are not processed anymore due to ambiguouty of required transform. - Convert to 8-bit unsigned matrix using a custom preprocessing specific to image's context. - -If window was created with OpenGL support, cv::imshow also support ogl::Buffer , ogl::Texture2D and -cuda::GpuMat as input. - -If the window was not created before this function, it is assumed creating a window with cv::WINDOW_AUTOSIZE. - -If you need to show an image that is bigger than the screen resolution, you will need to call namedWindow("", WINDOW_NORMAL) before the imshow. - -@note This function should be followed by a call to cv::waitKey or cv::pollKey to perform GUI -housekeeping tasks that are necessary to actually show the given image and make the window respond -to mouse and keyboard events. Otherwise, it won't display the image and the window might lock up. -For example, **waitKey(0)** will display the window infinitely until any keypress (it is suitable -for image display). **waitKey(25)** will display a frame and wait approximately 25 ms for a key -press (suitable for displaying a video frame-by-frame). To remove the window, use cv::destroyWindow. - -@note [__Windows Backend Only__] Pressing Ctrl+C will copy the image to the clipboard. Pressing Ctrl+S will show a dialog to save the image. -@note [__Wayland Backend Only__] Supoorting format is extended. -- If the image is 8-bit signed, the pixels are biased by 128. That is, the - value range [-128,127] is mapped to [0,255]. -- If the image is 16-bit signed, the pixels are divided by 256 and biased by 128. That is, the - value range [-32768,32767] is mapped to [0,255]. - -@param winname Name of the window. -@param mat Image to be shown. - */ -CV_EXPORTS_W void imshow(const String& winname, InputArray mat); - -/** @brief Resizes the window to the specified size - -@note The specified window size is for the image area. Toolbars are not counted. -Only windows created without cv::WINDOW_AUTOSIZE flag can be resized. - -@param winname Window name. -@param width The new window width. -@param height The new window height. - */ -CV_EXPORTS_W void resizeWindow(const String& winname, int width, int height); - -/** @overload -@param winname Window name. -@param size The new window size. -*/ -CV_EXPORTS_W void resizeWindow(const String& winname, const cv::Size& size); - -/** @brief Moves the window to the specified position - -@param winname Name of the window. -@param x The new x-coordinate of the window. -@param y The new y-coordinate of the window. - -@note [__Wayland Backend Only__] This function is not supported by the Wayland protocol limitation. - */ -CV_EXPORTS_W void moveWindow(const String& winname, int x, int y); - -/** @brief Changes parameters of a window dynamically. - -The function setWindowProperty enables changing properties of a window. - -@param winname Name of the window. -@param prop_id Window property to edit. The supported operation flags are: (cv::WindowPropertyFlags) -@param prop_value New value of the window property. The supported flags are: (cv::WindowFlags) - -@note [__Wayland Backend Only__] This function is not supported. - */ -CV_EXPORTS_W void setWindowProperty(const String& winname, int prop_id, double prop_value); - -/** @brief Updates window title -@param winname Name of the window. -@param title New title. -*/ -CV_EXPORTS_W void setWindowTitle(const String& winname, const String& title); - -/** @brief Provides parameters of a window. - -The function getWindowProperty returns properties of a window. - -@param winname Name of the window. -@param prop_id Window property to retrieve. The following operation flags are available: (cv::WindowPropertyFlags) - -@sa setWindowProperty - -@note [__Wayland Backend Only__] This function is not supported. - */ -CV_EXPORTS_W double getWindowProperty(const String& winname, int prop_id); - -/** @brief Provides rectangle of image in the window. - -The function getWindowImageRect returns the client screen coordinates, width and height of the image rendering area. - -@param winname Name of the window. - -@sa resizeWindow moveWindow - -@note [__Wayland Backend Only__] This function is not supported by the Wayland protocol limitation. - */ -CV_EXPORTS_W Rect getWindowImageRect(const String& winname); - -/** @example samples/cpp/create_mask.cpp -This program demonstrates using mouse events and how to make and use a mask image (black and white) . -*/ -/** @brief Sets mouse handler for the specified window - -@param winname Name of the window. -@param onMouse Callback function for mouse events. See OpenCV samples on how to specify and use the callback. -@param userdata The optional parameter passed to the callback. - */ -CV_EXPORTS void setMouseCallback(const String& winname, MouseCallback onMouse, void* userdata = 0); - -/** @brief Gets the mouse-wheel motion delta, when handling mouse-wheel events cv::EVENT_MOUSEWHEEL and -cv::EVENT_MOUSEHWHEEL. - -For regular mice with a scroll-wheel, delta will be a multiple of 120. The value 120 corresponds to -a one notch rotation of the wheel or the threshold for action to be taken and one such action should -occur for each delta. Some high-precision mice with higher-resolution freely-rotating wheels may -generate smaller values. - -For cv::EVENT_MOUSEWHEEL positive and negative values mean forward and backward scrolling, -respectively. For cv::EVENT_MOUSEHWHEEL, where available, positive and negative values mean right and -left scrolling, respectively. - -@note Mouse-wheel events are currently supported only on Windows and Cocoa. - -@param flags The mouse callback flags parameter. - */ -CV_EXPORTS int getMouseWheelDelta(int flags); - -/** @brief Allows users to select a ROI on the given image. - -The function creates a window and allows users to select a ROI using the mouse. -Controls: use `space` or `enter` to finish selection, use key `c` to cancel selection (function will return the zero cv::Rect). - -@param windowName name of the window where selection process will be shown. -@param img image to select a ROI. -@param showCrosshair if true crosshair of selection rectangle will be shown. -@param fromCenter if true center of selection will match initial mouse position. In opposite case a corner of -selection rectangle will correspont to the initial mouse position. -@param printNotice if true a notice to select ROI or cancel selection will be printed in console. -@return selected ROI or empty rect if selection canceled. - -@note The function sets it's own mouse callback for specified window using cv::setMouseCallback(windowName, ...). -After finish of work an empty callback will be set for the used window. - */ -CV_EXPORTS_W Rect selectROI(const String& windowName, InputArray img, bool showCrosshair = true, bool fromCenter = false, bool printNotice = true); - -/** @overload - */ -CV_EXPORTS_W Rect selectROI(InputArray img, bool showCrosshair = true, bool fromCenter = false, bool printNotice = true); - -/** @brief Allows users to select multiple ROIs on the given image. - -The function creates a window and allows users to select multiple ROIs using the mouse. -Controls: use `space` or `enter` to finish current selection and start a new one, -use `esc` to terminate multiple ROI selection process. - -@param windowName name of the window where selection process will be shown. -@param img image to select a ROI. -@param boundingBoxes selected ROIs. -@param showCrosshair if true crosshair of selection rectangle will be shown. -@param fromCenter if true center of selection will match initial mouse position. In opposite case a corner of -selection rectangle will correspont to the initial mouse position. -@param printNotice if true a notice to select ROI or cancel selection will be printed in console. - -@note The function sets it's own mouse callback for specified window using cv::setMouseCallback(windowName, ...). -After finish of work an empty callback will be set for the used window. - */ -CV_EXPORTS_W void selectROIs(const String& windowName, InputArray img, - CV_OUT std::vector& boundingBoxes, bool showCrosshair = true, bool fromCenter = false, bool printNotice = true); - -/** @brief Creates a trackbar and attaches it to the specified window. - -The function createTrackbar creates a trackbar (a slider or range control) with the specified name -and range, assigns a variable value to be a position synchronized with the trackbar and specifies -the callback function onChange to be called on the trackbar position change. The created trackbar is -displayed in the specified window winname. - -@note [__Qt Backend Only__] winname can be empty if the trackbar should be attached to the -control panel. - -Clicking the label of each trackbar enables editing the trackbar values manually. - -@param trackbarname Name of the created trackbar. -@param winname Name of the window that will contain the trackbar. -@param value Pointer to the integer value that will be changed by the trackbar. -Pass `nullptr` if the value pointer is not used. In this case, manually handle -the trackbar position in the callback function. -@param count Maximum position of the trackbar. -@param onChange Pointer to the function to be called every time the slider changes position. -This function should have the prototype void Foo(int, void\*);, where the first parameter is -the trackbar position, and the second parameter is the user data (see the next parameter). -If the callback is a nullptr, no callbacks are called, but the trackbar's value will still be -updated automatically. -@param userdata Optional user data that is passed to the callback. -@note If the `value` pointer is `nullptr`, the trackbar position must be manually managed. -Call the callback function manually with the desired initial value to avoid runtime warnings. -@see \ref tutorial_trackbar - */ -CV_EXPORTS int createTrackbar(const String& trackbarname, const String& winname, - int* value, int count, - TrackbarCallback onChange = 0, - void* userdata = 0); - -/** @brief Returns the trackbar position. - -The function returns the current position of the specified trackbar. - -@note [__Qt Backend Only__] winname can be empty if the trackbar is attached to the control -panel. - -@param trackbarname Name of the trackbar. -@param winname Name of the window that is the parent of the trackbar. - */ -CV_EXPORTS_W int getTrackbarPos(const String& trackbarname, const String& winname); - -/** @brief Sets the trackbar position. - -The function sets the position of the specified trackbar in the specified window. - -@note [__Qt Backend Only__] winname can be empty if the trackbar is attached to the control -panel. - -@param trackbarname Name of the trackbar. -@param winname Name of the window that is the parent of trackbar. -@param pos New position. - */ -CV_EXPORTS_W void setTrackbarPos(const String& trackbarname, const String& winname, int pos); - -/** @brief Sets the trackbar maximum position. - -The function sets the maximum position of the specified trackbar in the specified window. - -@note [__Qt Backend Only__] winname can be empty if the trackbar is attached to the control -panel. - -@param trackbarname Name of the trackbar. -@param winname Name of the window that is the parent of trackbar. -@param maxval New maximum position. - */ -CV_EXPORTS_W void setTrackbarMax(const String& trackbarname, const String& winname, int maxval); - -/** @brief Sets the trackbar minimum position. - -The function sets the minimum position of the specified trackbar in the specified window. - -@note [__Qt Backend Only__] winname can be empty if the trackbar is attached to the control -panel. - -@param trackbarname Name of the trackbar. -@param winname Name of the window that is the parent of trackbar. -@param minval New minimum position. - */ -CV_EXPORTS_W void setTrackbarMin(const String& trackbarname, const String& winname, int minval); - -//! @addtogroup highgui_opengl OpenGL support -//! @{ - -/** @brief Displays OpenGL 2D texture in the specified window. - -@param winname Name of the window. -@param tex OpenGL 2D texture data. - */ -CV_EXPORTS void imshow(const String& winname, const ogl::Texture2D& tex); - -/** @brief Sets a callback function to be called to draw on top of displayed image. - -The function setOpenGlDrawCallback can be used to draw 3D data on the window. See the example of -callback function below: -@code - void on_opengl(void* param) - { - glLoadIdentity(); - - glTranslated(0.0, 0.0, -1.0); - - glRotatef( 55, 1, 0, 0 ); - glRotatef( 45, 0, 1, 0 ); - glRotatef( 0, 0, 0, 1 ); - - static const int coords[6][4][3] = { - { { +1, -1, -1 }, { -1, -1, -1 }, { -1, +1, -1 }, { +1, +1, -1 } }, - { { +1, +1, -1 }, { -1, +1, -1 }, { -1, +1, +1 }, { +1, +1, +1 } }, - { { +1, -1, +1 }, { +1, -1, -1 }, { +1, +1, -1 }, { +1, +1, +1 } }, - { { -1, -1, -1 }, { -1, -1, +1 }, { -1, +1, +1 }, { -1, +1, -1 } }, - { { +1, -1, +1 }, { -1, -1, +1 }, { -1, -1, -1 }, { +1, -1, -1 } }, - { { -1, -1, +1 }, { +1, -1, +1 }, { +1, +1, +1 }, { -1, +1, +1 } } - }; - - for (int i = 0; i < 6; ++i) { - glColor3ub( i*20, 100+i*10, i*42 ); - glBegin(GL_QUADS); - for (int j = 0; j < 4; ++j) { - glVertex3d(0.2 * coords[i][j][0], 0.2 * coords[i][j][1], 0.2 * coords[i][j][2]); - } - glEnd(); - } - } -@endcode - -@param winname Name of the window. -@param onOpenGlDraw Pointer to the function to be called every frame. This function should be -prototyped as void Foo(void\*) . -@param userdata Pointer passed to the callback function.(__Optional__) - */ -CV_EXPORTS void setOpenGlDrawCallback(const String& winname, OpenGlDrawCallback onOpenGlDraw, void* userdata = 0); - -/** @brief Sets the specified window as current OpenGL context. - -@param winname Name of the window. - */ -CV_EXPORTS void setOpenGlContext(const String& winname); - -/** @brief Force window to redraw its context and call draw callback ( See cv::setOpenGlDrawCallback ). - -@param winname Name of the window. - */ -CV_EXPORTS void updateWindow(const String& winname); - -//! @} highgui_opengl - -//! @addtogroup highgui_qt -//! @{ - -/** @brief QtFont available only for Qt. See cv::fontQt - */ -struct QtFont -{ - const char* nameFont; //!< Name of the font - Scalar color; //!< Color of the font. Scalar(blue_component, green_component, red_component[, alpha_component]) - int font_face; //!< See cv::QtFontStyles - const int* ascii; //!< font data and metrics - const int* greek; - const int* cyrillic; - float hscale, vscale; - float shear; //!< slope coefficient: 0 - normal, >0 - italic - int thickness; //!< See cv::QtFontWeights - float dx; //!< horizontal interval between letters - int line_type; //!< PointSize -}; - -/** @brief Creates the font to draw a text on an image. - -The function fontQt creates a cv::QtFont object. This cv::QtFont is not compatible with putText . - -A basic usage of this function is the following: : -@code - QtFont font = fontQt("Times"); - addText( img1, "Hello World !", Point(50,50), font); -@endcode - -@param nameFont Name of the font. The name should match the name of a system font (such as -*Times*). If the font is not found, a default one is used. -@param pointSize Size of the font. If not specified, equal zero or negative, the point size of the -font is set to a system-dependent default value. Generally, this is 12 points. -@param color Color of the font in BGRA where A = 255 is fully transparent. Use the macro CV_RGB -for simplicity. -@param weight Font weight. Available operation flags are : cv::QtFontWeights You can also specify a positive integer for better control. -@param style Font style. Available operation flags are : cv::QtFontStyles -@param spacing Spacing between characters. It can be negative or positive. - */ -CV_EXPORTS QtFont fontQt(const String& nameFont, int pointSize = -1, - Scalar color = Scalar::all(0), int weight = QT_FONT_NORMAL, - int style = QT_STYLE_NORMAL, int spacing = 0); - -/** @brief Draws a text on the image. - -The function addText draws *text* on the image *img* using a specific font *font* (see example cv::fontQt -) - -@param img 8-bit 3-channel image where the text should be drawn. -@param text Text to write on an image. -@param org Point(x,y) where the text should start on an image. -@param font Font to use to draw a text. - */ -CV_EXPORTS void addText( const Mat& img, const String& text, Point org, const QtFont& font); - -/** @brief Draws a text on the image. - -@param img 8-bit 3-channel image where the text should be drawn. -@param text Text to write on an image. -@param org Point(x,y) where the text should start on an image. -@param nameFont Name of the font. The name should match the name of a system font (such as -*Times*). If the font is not found, a default one is used. -@param pointSize Size of the font. If not specified, equal zero or negative, the point size of the -font is set to a system-dependent default value. Generally, this is 12 points. -@param color Color of the font in BGRA where A = 255 is fully transparent. -@param weight Font weight. Available operation flags are : cv::QtFontWeights You can also specify a positive integer for better control. -@param style Font style. Available operation flags are : cv::QtFontStyles -@param spacing Spacing between characters. It can be negative or positive. - */ -CV_EXPORTS_W void addText(const Mat& img, const String& text, Point org, const String& nameFont, int pointSize = -1, Scalar color = Scalar::all(0), - int weight = QT_FONT_NORMAL, int style = QT_STYLE_NORMAL, int spacing = 0); - -/** @brief Displays a text on a window image as an overlay for a specified duration. - -The function displayOverlay displays useful information/tips on top of the window for a certain -amount of time *delayms*. The function does not modify the image, displayed in the window, that is, -after the specified delay the original content of the window is restored. - -@param winname Name of the window. -@param text Overlay text to write on a window image. -@param delayms The period (in milliseconds), during which the overlay text is displayed. If this -function is called before the previous overlay text timed out, the timer is restarted and the text -is updated. If this value is zero, the text never disappears. - */ -CV_EXPORTS_W void displayOverlay(const String& winname, const String& text, int delayms = 0); - -/** @brief Displays a text on the window statusbar during the specified period of time. - -The function displayStatusBar displays useful information/tips on top of the window for a certain -amount of time *delayms* . This information is displayed on the window statusbar (the window must be -created with the CV_GUI_EXPANDED flags). - -@param winname Name of the window. -@param text Text to write on the window statusbar. -@param delayms Duration (in milliseconds) to display the text. If this function is called before -the previous text timed out, the timer is restarted and the text is updated. If this value is -zero, the text never disappears. - */ -CV_EXPORTS_W void displayStatusBar(const String& winname, const String& text, int delayms = 0); - -/** @brief Saves parameters of the specified window. - -The function saveWindowParameters saves size, location, flags, trackbars value, zoom and panning -location of the window windowName. - -@param windowName Name of the window. - */ -CV_EXPORTS void saveWindowParameters(const String& windowName); - -/** @brief Loads parameters of the specified window. - -The function loadWindowParameters loads size, location, flags, trackbars value, zoom and panning -location of the window windowName. - -@param windowName Name of the window. - */ -CV_EXPORTS void loadWindowParameters(const String& windowName); - -CV_EXPORTS int startLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[]); - -CV_EXPORTS void stopLoop(); - -/** @brief Attaches a button to the control panel. - -The function createButton attaches a button to the control panel. Each button is added to a -buttonbar to the right of the last button. A new buttonbar is created if nothing was attached to the -control panel before, or if the last element attached to the control panel was a trackbar or if the -QT_NEW_BUTTONBAR flag is added to the type. - -See below various examples of the cv::createButton function call: : -@code - createButton("",callbackButton);//create a push button "button 0", that will call callbackButton. - createButton("button2",callbackButton,NULL,QT_CHECKBOX,0); - createButton("button3",callbackButton,&value); - createButton("button5",callbackButton1,NULL,QT_RADIOBOX); - createButton("button6",callbackButton2,NULL,QT_PUSH_BUTTON,1); - createButton("button6",callbackButton2,NULL,QT_PUSH_BUTTON|QT_NEW_BUTTONBAR);// create a push button in a new row -@endcode - -@param bar_name Name of the button. -@param on_change Pointer to the function to be called every time the button changes its state. -This function should be prototyped as void Foo(int state,\*void); . *state* is the current state -of the button. It could be -1 for a push button, 0 or 1 for a check/radio box button. -@param userdata Pointer passed to the callback function. -@param type Optional type of the button. Available types are: (cv::QtButtonTypes) -@param initial_button_state Default state of the button. Use for checkbox and radiobox. Its -value could be 0 or 1. (__Optional__) -*/ -CV_EXPORTS int createButton( const String& bar_name, ButtonCallback on_change, - void* userdata = 0, int type = QT_PUSH_BUTTON, - bool initial_button_state = false); - -//! @} highgui_qt - -//! @} highgui - -} // cv - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_HIGHGUI_HPP +#define OPENCV_HIGHGUI_HPP + +#include "opencv2/core.hpp" +#ifdef HAVE_OPENCV_IMGCODECS +#include "opencv2/imgcodecs.hpp" +#endif +#ifdef HAVE_OPENCV_VIDEOIO +#include "opencv2/videoio.hpp" +#endif + +/** +@defgroup highgui High-level GUI + +While OpenCV was designed for use in full-scale applications and can be used within functionally +rich UI frameworks (such as Qt\*, WinForms\*, or Cocoa\*) or without any UI at all, sometimes there +it is required to try functionality quickly and visualize the results. This is what the HighGUI +module has been designed for. + +It provides easy interface to: + +- Create and manipulate windows that can display images and "remember" their content (no need to + handle repaint events from OS). +- Add trackbars to the windows, handle simple mouse events as well as keyboard commands. + +@{ + @defgroup highgui_window_flags Flags related creating and manipulating HighGUI windows and mouse events + @defgroup highgui_opengl OpenGL support + @defgroup highgui_qt Qt New Functions + + ![image](pics/qtgui.png) + + This figure explains new functionality implemented with Qt\* GUI. The new GUI provides a statusbar, + a toolbar, and a control panel. The control panel can have trackbars and buttonbars attached to it. + If you cannot see the control panel, press Ctrl+P or right-click any Qt window and select **Display + properties window**. + + - To attach a trackbar, the window name parameter must be NULL. + + - To attach a buttonbar, a button must be created. If the last bar attached to the control panel + is a buttonbar, the new button is added to the right of the last button. If the last bar + attached to the control panel is a trackbar, or the control panel is empty, a new buttonbar is + created. Then, a new button is attached to it. + + See below the example used to generate the figure: + + @include highgui_qt.cpp + + @defgroup highgui_winrt WinRT support + + This figure explains new functionality implemented with WinRT GUI. The new GUI provides an Image control, + and a slider panel. Slider panel holds trackbars attached to it. + + Sliders are attached below the image control. Every new slider is added below the previous one. + + See below the example used to generate the figure: + @code + void sample_app::MainPage::ShowWindow() + { + static cv::String windowName("sample"); + cv::winrt_initContainer(this->cvContainer); + cv::namedWindow(windowName); // not required + + cv::Mat image = cv::imread("Assets/sample.jpg"); + cv::Mat converted = cv::Mat(image.rows, image.cols, CV_8UC4); + cv::cvtColor(image, converted, COLOR_BGR2BGRA); + cv::imshow(windowName, converted); // this will create window if it hasn't been created before + + int state = 42; + cv::TrackbarCallback callback = [](int pos, void* userdata) + { + if (pos == 0) { + cv::destroyWindow(windowName); + } + }; + cv::TrackbarCallback callbackTwin = [](int pos, void* userdata) + { + if (pos >= 70) { + cv::destroyAllWindows(); + } + }; + cv::createTrackbar("Sample trackbar", windowName, &state, 100, callback); + cv::createTrackbar("Twin brother", windowName, &state, 100, callbackTwin); + } + @endcode +@} +*/ + +///////////////////////// graphical user interface ////////////////////////// +namespace cv +{ + +//! @addtogroup highgui +//! @{ + +//! @addtogroup highgui_window_flags +//! @{ + +//! Flags for cv::namedWindow +enum WindowFlags { + WINDOW_NORMAL = 0x00000000, //!< the user can resize the window (no constraint) / also use to switch a fullscreen window to a normal size. + WINDOW_AUTOSIZE = 0x00000001, //!< the user cannot resize the window, the size is constrainted by the image displayed. + WINDOW_OPENGL = 0x00001000, //!< window with opengl support. + + WINDOW_FULLSCREEN = 1, //!< change the window to fullscreen. + WINDOW_FREERATIO = 0x00000100, //!< the image expends as much as it can (no ratio constraint). + WINDOW_KEEPRATIO = 0x00000000, //!< the ratio of the image is respected. + WINDOW_GUI_EXPANDED=0x00000000, //!< status bar and tool bar + WINDOW_GUI_NORMAL = 0x00000010, //!< old fashious way + }; + +//! Flags for cv::setWindowProperty / cv::getWindowProperty +enum WindowPropertyFlags { + WND_PROP_FULLSCREEN = 0, //!< fullscreen property (can be WINDOW_NORMAL or WINDOW_FULLSCREEN). + WND_PROP_AUTOSIZE = 1, //!< autosize property (can be WINDOW_NORMAL or WINDOW_AUTOSIZE). + WND_PROP_ASPECT_RATIO = 2, //!< window's aspect ration (can be set to WINDOW_FREERATIO or WINDOW_KEEPRATIO). + WND_PROP_OPENGL = 3, //!< opengl support. + WND_PROP_VISIBLE = 4, //!< checks whether the window exists and is visible + WND_PROP_TOPMOST = 5, //!< property to toggle normal window being topmost or not + WND_PROP_VSYNC = 6 //!< enable or disable VSYNC (in OpenGL mode) + }; + +//! Mouse Events see cv::MouseCallback +enum MouseEventTypes { + EVENT_MOUSEMOVE = 0, //!< indicates that the mouse pointer has moved over the window. + EVENT_LBUTTONDOWN = 1, //!< indicates that the left mouse button is pressed. + EVENT_RBUTTONDOWN = 2, //!< indicates that the right mouse button is pressed. + EVENT_MBUTTONDOWN = 3, //!< indicates that the middle mouse button is pressed. + EVENT_LBUTTONUP = 4, //!< indicates that left mouse button is released. + EVENT_RBUTTONUP = 5, //!< indicates that right mouse button is released. + EVENT_MBUTTONUP = 6, //!< indicates that middle mouse button is released. + EVENT_LBUTTONDBLCLK = 7, //!< indicates that left mouse button is double clicked. + EVENT_RBUTTONDBLCLK = 8, //!< indicates that right mouse button is double clicked. + EVENT_MBUTTONDBLCLK = 9, //!< indicates that middle mouse button is double clicked. + EVENT_MOUSEWHEEL = 10,//!< positive and negative values mean forward and backward scrolling, respectively. + EVENT_MOUSEHWHEEL = 11 //!< positive and negative values mean right and left scrolling, respectively. + }; + +//! Mouse Event Flags see cv::MouseCallback +enum MouseEventFlags { + EVENT_FLAG_LBUTTON = 1, //!< indicates that the left mouse button is down. + EVENT_FLAG_RBUTTON = 2, //!< indicates that the right mouse button is down. + EVENT_FLAG_MBUTTON = 4, //!< indicates that the middle mouse button is down. + EVENT_FLAG_CTRLKEY = 8, //!< indicates that CTRL Key is pressed. + EVENT_FLAG_SHIFTKEY = 16,//!< indicates that SHIFT Key is pressed. + EVENT_FLAG_ALTKEY = 32 //!< indicates that ALT Key is pressed. + }; + +//! @} highgui_window_flags + +//! @addtogroup highgui_qt +//! @{ + +//! Qt font weight +enum QtFontWeights { + QT_FONT_LIGHT = 25, //!< Weight of 25 + QT_FONT_NORMAL = 50, //!< Weight of 50 + QT_FONT_DEMIBOLD = 63, //!< Weight of 63 + QT_FONT_BOLD = 75, //!< Weight of 75 + QT_FONT_BLACK = 87 //!< Weight of 87 + }; + +//! Qt font style +enum QtFontStyles { + QT_STYLE_NORMAL = 0, //!< Normal font. + QT_STYLE_ITALIC = 1, //!< Italic font. + QT_STYLE_OBLIQUE = 2 //!< Oblique font. + }; + +//! Qt "button" type +enum QtButtonTypes { + QT_PUSH_BUTTON = 0, //!< Push button. + QT_CHECKBOX = 1, //!< Checkbox button. + QT_RADIOBOX = 2, //!< Radiobox button. + QT_NEW_BUTTONBAR = 1024 //!< Button should create a new buttonbar + }; + +//! @} highgui_qt + +/** @brief Callback function for mouse events. see cv::setMouseCallback +@param event one of the cv::MouseEventTypes constants. +@param x The x-coordinate of the mouse event. +@param y The y-coordinate of the mouse event. +@param flags one of the cv::MouseEventFlags constants. +@param userdata The optional parameter. + */ +typedef void (*MouseCallback)(int event, int x, int y, int flags, void* userdata); + +/** @brief Callback function for Trackbar see cv::createTrackbar +@param pos current position of the specified trackbar. +@param userdata The optional parameter. + */ +typedef void (*TrackbarCallback)(int pos, void* userdata); + +/** @brief Callback function defined to be called every frame. See cv::setOpenGlDrawCallback +@param userdata The optional parameter. + */ +typedef void (*OpenGlDrawCallback)(void* userdata); + +/** @brief Callback function for a button created by cv::createButton +@param state current state of the button. It could be -1 for a push button, 0 or 1 for a check/radio box button. +@param userdata The optional parameter. + */ +typedef void (*ButtonCallback)(int state, void* userdata); + +/** @brief Creates a window. + +The function namedWindow creates a window that can be used as a placeholder for images and +trackbars. Created windows are referred to by their names. + +If a window with the same name already exists, the function does nothing. + +You can call cv::destroyWindow or cv::destroyAllWindows to close the window and de-allocate any associated +memory usage. For a simple program, you do not really have to call these functions because all the +resources and windows of the application are closed automatically by the operating system upon exit. + +@note Qt backend supports additional flags: + - **WINDOW_NORMAL or WINDOW_AUTOSIZE:** WINDOW_NORMAL enables you to resize the + window, whereas WINDOW_AUTOSIZE adjusts automatically the window size to fit the + displayed image (see imshow ), and you cannot change the window size manually. + - **WINDOW_FREERATIO or WINDOW_KEEPRATIO:** WINDOW_FREERATIO adjusts the image + with no respect to its ratio, whereas WINDOW_KEEPRATIO keeps the image ratio. + - **WINDOW_GUI_NORMAL or WINDOW_GUI_EXPANDED:** WINDOW_GUI_NORMAL is the old way to draw the window + without statusbar and toolbar, whereas WINDOW_GUI_EXPANDED is a new enhanced GUI. +By default, flags == WINDOW_AUTOSIZE | WINDOW_KEEPRATIO | WINDOW_GUI_EXPANDED + +@param winname Name of the window in the window caption that may be used as a window identifier. +@param flags Flags of the window. The supported flags are: (cv::WindowFlags) + */ +CV_EXPORTS_W void namedWindow(const String& winname, int flags = WINDOW_AUTOSIZE); + +/** @brief Destroys the specified window. + +The function destroyWindow destroys the window with the given name. + +@param winname Name of the window to be destroyed. + */ +CV_EXPORTS_W void destroyWindow(const String& winname); + +/** @brief Destroys all of the HighGUI windows. + +The function destroyAllWindows destroys all of the opened HighGUI windows. + */ +CV_EXPORTS_W void destroyAllWindows(); + + +/** @brief HighGUI backend used. + +The function returns HighGUI backend name used: could be COCOA, GTK2/3, QT, WAYLAND or WIN32. +Returns empty string if there is no available UI backend. + */ +CV_EXPORTS_W const std::string currentUIFramework(); + + +CV_EXPORTS_W int startWindowThread(); + +/** @brief Similar to #waitKey, but returns full key code. + +@note Key code is implementation specific and depends on used backend: QT/GTK/Win32/etc + +*/ +CV_EXPORTS_W int waitKeyEx(int delay = 0); + +/** @brief Waits for a pressed key. + +The function waitKey waits for a key event infinitely (when \f$\texttt{delay}\leq 0\f$ ) or for delay +milliseconds, when it is positive. Since the OS has a minimum time between switching threads, the +function will not wait exactly delay ms, it will wait at least delay ms, depending on what else is +running on your computer at that time. It returns the code of the pressed key or -1 if no key was +pressed before the specified time had elapsed. To check for a key press but not wait for it, use +#pollKey. + +@note The functions #waitKey and #pollKey are the only methods in HighGUI that can fetch and handle +GUI events, so one of them needs to be called periodically for normal event processing unless +HighGUI is used within an environment that takes care of event processing. + +@note The function only works if there is at least one HighGUI window created and the window is +active. If there are several HighGUI windows, any of them can be active. + +@param delay Delay in milliseconds. 0 is the special value that means "forever". + */ +CV_EXPORTS_W int waitKey(int delay = 0); + +/** @brief Polls for a pressed key. + +The function pollKey polls for a key event without waiting. It returns the code of the pressed key +or -1 if no key was pressed since the last invocation. To wait until a key was pressed, use #waitKey. + +@note The functions #waitKey and #pollKey are the only methods in HighGUI that can fetch and handle +GUI events, so one of them needs to be called periodically for normal event processing unless +HighGUI is used within an environment that takes care of event processing. + +@note The function only works if there is at least one HighGUI window created and the window is +active. If there are several HighGUI windows, any of them can be active. + */ +CV_EXPORTS_W int pollKey(); + +/** @brief Displays an image in the specified window. + +The function imshow displays an image in the specified window. If the window was created with the +cv::WINDOW_AUTOSIZE flag, the image is shown with its original size, however it is still limited by the screen resolution. +Otherwise, the image is scaled to fit the window. The function may scale the image, depending on its depth: + +- If the image is 8-bit unsigned, it is displayed as is. +- If the image is 16-bit unsigned, the pixels are divided by 256. That is, the + value range [0,255\*256] is mapped to [0,255]. +- If the image is 32-bit or 64-bit floating-point, the pixel values are multiplied by 255. That is, the + value range [0,1] is mapped to [0,255]. +- 32-bit integer images are not processed anymore due to ambiguouty of required transform. + Convert to 8-bit unsigned matrix using a custom preprocessing specific to image's context. + +If window was created with OpenGL support, cv::imshow also support ogl::Buffer , ogl::Texture2D and +cuda::GpuMat as input. + +If the window was not created before this function, it is assumed creating a window with cv::WINDOW_AUTOSIZE. + +If you need to show an image that is bigger than the screen resolution, you will need to call namedWindow("", WINDOW_NORMAL) before the imshow. + +@note This function should be followed by a call to cv::waitKey or cv::pollKey to perform GUI +housekeeping tasks that are necessary to actually show the given image and make the window respond +to mouse and keyboard events. Otherwise, it won't display the image and the window might lock up. +For example, **waitKey(0)** will display the window infinitely until any keypress (it is suitable +for image display). **waitKey(25)** will display a frame and wait approximately 25 ms for a key +press (suitable for displaying a video frame-by-frame). To remove the window, use cv::destroyWindow. + +@note [__Windows Backend Only__] Pressing Ctrl+C will copy the image to the clipboard. Pressing Ctrl+S will show a dialog to save the image. +@note [__Wayland Backend Only__] Supoorting format is extended. +- If the image is 8-bit signed, the pixels are biased by 128. That is, the + value range [-128,127] is mapped to [0,255]. +- If the image is 16-bit signed, the pixels are divided by 256 and biased by 128. That is, the + value range [-32768,32767] is mapped to [0,255]. + +@param winname Name of the window. +@param mat Image to be shown. + */ +CV_EXPORTS_W void imshow(const String& winname, InputArray mat); + +/** @brief Resizes the window to the specified size + +@note The specified window size is for the image area. Toolbars are not counted. +Only windows created without cv::WINDOW_AUTOSIZE flag can be resized. + +@param winname Window name. +@param width The new window width. +@param height The new window height. + */ +CV_EXPORTS_W void resizeWindow(const String& winname, int width, int height); + +/** @overload +@param winname Window name. +@param size The new window size. +*/ +CV_EXPORTS_W void resizeWindow(const String& winname, const cv::Size& size); + +/** @brief Moves the window to the specified position + +@param winname Name of the window. +@param x The new x-coordinate of the window. +@param y The new y-coordinate of the window. + +@note [__Wayland Backend Only__] This function is not supported by the Wayland protocol limitation. + */ +CV_EXPORTS_W void moveWindow(const String& winname, int x, int y); + +/** @brief Changes parameters of a window dynamically. + +The function setWindowProperty enables changing properties of a window. + +@param winname Name of the window. +@param prop_id Window property to edit. The supported operation flags are: (cv::WindowPropertyFlags) +@param prop_value New value of the window property. The supported flags are: (cv::WindowFlags) + +@note [__Wayland Backend Only__] This function is not supported. + */ +CV_EXPORTS_W void setWindowProperty(const String& winname, int prop_id, double prop_value); + +/** @brief Updates window title +@param winname Name of the window. +@param title New title. +*/ +CV_EXPORTS_W void setWindowTitle(const String& winname, const String& title); + +/** @brief Provides parameters of a window. + +The function getWindowProperty returns properties of a window. + +@param winname Name of the window. +@param prop_id Window property to retrieve. The following operation flags are available: (cv::WindowPropertyFlags) + +@sa setWindowProperty + +@note [__Wayland Backend Only__] This function is not supported. + */ +CV_EXPORTS_W double getWindowProperty(const String& winname, int prop_id); + +/** @brief Provides rectangle of image in the window. + +The function getWindowImageRect returns the client screen coordinates, width and height of the image rendering area. + +@param winname Name of the window. + +@sa resizeWindow moveWindow + +@note [__Wayland Backend Only__] This function is not supported by the Wayland protocol limitation. + */ +CV_EXPORTS_W Rect getWindowImageRect(const String& winname); + +/** @example samples/cpp/create_mask.cpp +This program demonstrates using mouse events and how to make and use a mask image (black and white) . +*/ +/** @brief Sets mouse handler for the specified window + +@param winname Name of the window. +@param onMouse Callback function for mouse events. See OpenCV samples on how to specify and use the callback. +@param userdata The optional parameter passed to the callback. + */ +CV_EXPORTS void setMouseCallback(const String& winname, MouseCallback onMouse, void* userdata = 0); + +/** @brief Gets the mouse-wheel motion delta, when handling mouse-wheel events cv::EVENT_MOUSEWHEEL and +cv::EVENT_MOUSEHWHEEL. + +For regular mice with a scroll-wheel, delta will be a multiple of 120. The value 120 corresponds to +a one notch rotation of the wheel or the threshold for action to be taken and one such action should +occur for each delta. Some high-precision mice with higher-resolution freely-rotating wheels may +generate smaller values. + +For cv::EVENT_MOUSEWHEEL positive and negative values mean forward and backward scrolling, +respectively. For cv::EVENT_MOUSEHWHEEL, where available, positive and negative values mean right and +left scrolling, respectively. + +@note Mouse-wheel events are currently supported only on Windows and Cocoa. + +@param flags The mouse callback flags parameter. + */ +CV_EXPORTS int getMouseWheelDelta(int flags); + +/** @brief Allows users to select a ROI on the given image. + +The function creates a window and allows users to select a ROI using the mouse. +Controls: use `space` or `enter` to finish selection, use key `c` to cancel selection (function will return the zero cv::Rect). + +@param windowName name of the window where selection process will be shown. +@param img image to select a ROI. +@param showCrosshair if true crosshair of selection rectangle will be shown. +@param fromCenter if true center of selection will match initial mouse position. In opposite case a corner of +selection rectangle will correspont to the initial mouse position. +@param printNotice if true a notice to select ROI or cancel selection will be printed in console. +@return selected ROI or empty rect if selection canceled. + +@note The function sets it's own mouse callback for specified window using cv::setMouseCallback(windowName, ...). +After finish of work an empty callback will be set for the used window. + */ +CV_EXPORTS_W Rect selectROI(const String& windowName, InputArray img, bool showCrosshair = true, bool fromCenter = false, bool printNotice = true); + +/** @overload + */ +CV_EXPORTS_W Rect selectROI(InputArray img, bool showCrosshair = true, bool fromCenter = false, bool printNotice = true); + +/** @brief Allows users to select multiple ROIs on the given image. + +The function creates a window and allows users to select multiple ROIs using the mouse. +Controls: use `space` or `enter` to finish current selection and start a new one, +use `esc` to terminate multiple ROI selection process. + +@param windowName name of the window where selection process will be shown. +@param img image to select a ROI. +@param boundingBoxes selected ROIs. +@param showCrosshair if true crosshair of selection rectangle will be shown. +@param fromCenter if true center of selection will match initial mouse position. In opposite case a corner of +selection rectangle will correspont to the initial mouse position. +@param printNotice if true a notice to select ROI or cancel selection will be printed in console. + +@note The function sets it's own mouse callback for specified window using cv::setMouseCallback(windowName, ...). +After finish of work an empty callback will be set for the used window. + */ +CV_EXPORTS_W void selectROIs(const String& windowName, InputArray img, + CV_OUT std::vector& boundingBoxes, bool showCrosshair = true, bool fromCenter = false, bool printNotice = true); + +/** @brief Creates a trackbar and attaches it to the specified window. + +The function createTrackbar creates a trackbar (a slider or range control) with the specified name +and range, assigns a variable value to be a position synchronized with the trackbar and specifies +the callback function onChange to be called on the trackbar position change. The created trackbar is +displayed in the specified window winname. + +@note [__Qt Backend Only__] winname can be empty if the trackbar should be attached to the +control panel. + +Clicking the label of each trackbar enables editing the trackbar values manually. + +@param trackbarname Name of the created trackbar. +@param winname Name of the window that will contain the trackbar. +@param value Pointer to the integer value that will be changed by the trackbar. +Pass `nullptr` if the value pointer is not used. In this case, manually handle +the trackbar position in the callback function. +@param count Maximum position of the trackbar. +@param onChange Pointer to the function to be called every time the slider changes position. +This function should have the prototype void Foo(int, void\*);, where the first parameter is +the trackbar position, and the second parameter is the user data (see the next parameter). +If the callback is a nullptr, no callbacks are called, but the trackbar's value will still be +updated automatically. +@param userdata Optional user data that is passed to the callback. +@note If the `value` pointer is `nullptr`, the trackbar position must be manually managed. +Call the callback function manually with the desired initial value to avoid runtime warnings. +@see \ref tutorial_trackbar + */ +CV_EXPORTS int createTrackbar(const String& trackbarname, const String& winname, + int* value, int count, + TrackbarCallback onChange = 0, + void* userdata = 0); + +/** @brief Returns the trackbar position. + +The function returns the current position of the specified trackbar. + +@note [__Qt Backend Only__] winname can be empty if the trackbar is attached to the control +panel. + +@param trackbarname Name of the trackbar. +@param winname Name of the window that is the parent of the trackbar. + */ +CV_EXPORTS_W int getTrackbarPos(const String& trackbarname, const String& winname); + +/** @brief Sets the trackbar position. + +The function sets the position of the specified trackbar in the specified window. + +@note [__Qt Backend Only__] winname can be empty if the trackbar is attached to the control +panel. + +@param trackbarname Name of the trackbar. +@param winname Name of the window that is the parent of trackbar. +@param pos New position. + */ +CV_EXPORTS_W void setTrackbarPos(const String& trackbarname, const String& winname, int pos); + +/** @brief Sets the trackbar maximum position. + +The function sets the maximum position of the specified trackbar in the specified window. + +@note [__Qt Backend Only__] winname can be empty if the trackbar is attached to the control +panel. + +@param trackbarname Name of the trackbar. +@param winname Name of the window that is the parent of trackbar. +@param maxval New maximum position. + */ +CV_EXPORTS_W void setTrackbarMax(const String& trackbarname, const String& winname, int maxval); + +/** @brief Sets the trackbar minimum position. + +The function sets the minimum position of the specified trackbar in the specified window. + +@note [__Qt Backend Only__] winname can be empty if the trackbar is attached to the control +panel. + +@param trackbarname Name of the trackbar. +@param winname Name of the window that is the parent of trackbar. +@param minval New minimum position. + */ +CV_EXPORTS_W void setTrackbarMin(const String& trackbarname, const String& winname, int minval); + +//! @addtogroup highgui_opengl OpenGL support +//! @{ + +/** @brief Displays OpenGL 2D texture in the specified window. + +@param winname Name of the window. +@param tex OpenGL 2D texture data. + */ +CV_EXPORTS void imshow(const String& winname, const ogl::Texture2D& tex); + +/** @brief Sets a callback function to be called to draw on top of displayed image. + +The function setOpenGlDrawCallback can be used to draw 3D data on the window. See the example of +callback function below: +@code + void on_opengl(void* param) + { + glLoadIdentity(); + + glTranslated(0.0, 0.0, -1.0); + + glRotatef( 55, 1, 0, 0 ); + glRotatef( 45, 0, 1, 0 ); + glRotatef( 0, 0, 0, 1 ); + + static const int coords[6][4][3] = { + { { +1, -1, -1 }, { -1, -1, -1 }, { -1, +1, -1 }, { +1, +1, -1 } }, + { { +1, +1, -1 }, { -1, +1, -1 }, { -1, +1, +1 }, { +1, +1, +1 } }, + { { +1, -1, +1 }, { +1, -1, -1 }, { +1, +1, -1 }, { +1, +1, +1 } }, + { { -1, -1, -1 }, { -1, -1, +1 }, { -1, +1, +1 }, { -1, +1, -1 } }, + { { +1, -1, +1 }, { -1, -1, +1 }, { -1, -1, -1 }, { +1, -1, -1 } }, + { { -1, -1, +1 }, { +1, -1, +1 }, { +1, +1, +1 }, { -1, +1, +1 } } + }; + + for (int i = 0; i < 6; ++i) { + glColor3ub( i*20, 100+i*10, i*42 ); + glBegin(GL_QUADS); + for (int j = 0; j < 4; ++j) { + glVertex3d(0.2 * coords[i][j][0], 0.2 * coords[i][j][1], 0.2 * coords[i][j][2]); + } + glEnd(); + } + } +@endcode + +@param winname Name of the window. +@param onOpenGlDraw Pointer to the function to be called every frame. This function should be +prototyped as void Foo(void\*) . +@param userdata Pointer passed to the callback function.(__Optional__) + */ +CV_EXPORTS void setOpenGlDrawCallback(const String& winname, OpenGlDrawCallback onOpenGlDraw, void* userdata = 0); + +/** @brief Sets the specified window as current OpenGL context. + +@param winname Name of the window. + */ +CV_EXPORTS void setOpenGlContext(const String& winname); + +/** @brief Force window to redraw its context and call draw callback ( See cv::setOpenGlDrawCallback ). + +@param winname Name of the window. + */ +CV_EXPORTS void updateWindow(const String& winname); + +//! @} highgui_opengl + +//! @addtogroup highgui_qt +//! @{ + +/** @brief QtFont available only for Qt. See cv::fontQt + */ +struct QtFont +{ + const char* nameFont; //!< Name of the font + Scalar color; //!< Color of the font. Scalar(blue_component, green_component, red_component[, alpha_component]) + int font_face; //!< See cv::QtFontStyles + const int* ascii; //!< font data and metrics + const int* greek; + const int* cyrillic; + float hscale, vscale; + float shear; //!< slope coefficient: 0 - normal, >0 - italic + int thickness; //!< See cv::QtFontWeights + float dx; //!< horizontal interval between letters + int line_type; //!< PointSize +}; + +/** @brief Creates the font to draw a text on an image. + +The function fontQt creates a cv::QtFont object. This cv::QtFont is not compatible with putText . + +A basic usage of this function is the following: : +@code + QtFont font = fontQt("Times"); + addText( img1, "Hello World !", Point(50,50), font); +@endcode + +@param nameFont Name of the font. The name should match the name of a system font (such as +*Times*). If the font is not found, a default one is used. +@param pointSize Size of the font. If not specified, equal zero or negative, the point size of the +font is set to a system-dependent default value. Generally, this is 12 points. +@param color Color of the font in BGRA where A = 255 is fully transparent. Use the macro CV_RGB +for simplicity. +@param weight Font weight. Available operation flags are : cv::QtFontWeights You can also specify a positive integer for better control. +@param style Font style. Available operation flags are : cv::QtFontStyles +@param spacing Spacing between characters. It can be negative or positive. + */ +CV_EXPORTS QtFont fontQt(const String& nameFont, int pointSize = -1, + Scalar color = Scalar::all(0), int weight = QT_FONT_NORMAL, + int style = QT_STYLE_NORMAL, int spacing = 0); + +/** @brief Draws a text on the image. + +The function addText draws *text* on the image *img* using a specific font *font* (see example cv::fontQt +) + +@param img 8-bit 3-channel image where the text should be drawn. +@param text Text to write on an image. +@param org Point(x,y) where the text should start on an image. +@param font Font to use to draw a text. + */ +CV_EXPORTS void addText( const Mat& img, const String& text, Point org, const QtFont& font); + +/** @brief Draws a text on the image. + +@param img 8-bit 3-channel image where the text should be drawn. +@param text Text to write on an image. +@param org Point(x,y) where the text should start on an image. +@param nameFont Name of the font. The name should match the name of a system font (such as +*Times*). If the font is not found, a default one is used. +@param pointSize Size of the font. If not specified, equal zero or negative, the point size of the +font is set to a system-dependent default value. Generally, this is 12 points. +@param color Color of the font in BGRA where A = 255 is fully transparent. +@param weight Font weight. Available operation flags are : cv::QtFontWeights You can also specify a positive integer for better control. +@param style Font style. Available operation flags are : cv::QtFontStyles +@param spacing Spacing between characters. It can be negative or positive. + */ +CV_EXPORTS_W void addText(const Mat& img, const String& text, Point org, const String& nameFont, int pointSize = -1, Scalar color = Scalar::all(0), + int weight = QT_FONT_NORMAL, int style = QT_STYLE_NORMAL, int spacing = 0); + +/** @brief Displays a text on a window image as an overlay for a specified duration. + +The function displayOverlay displays useful information/tips on top of the window for a certain +amount of time *delayms*. The function does not modify the image, displayed in the window, that is, +after the specified delay the original content of the window is restored. + +@param winname Name of the window. +@param text Overlay text to write on a window image. +@param delayms The period (in milliseconds), during which the overlay text is displayed. If this +function is called before the previous overlay text timed out, the timer is restarted and the text +is updated. If this value is zero, the text never disappears. + */ +CV_EXPORTS_W void displayOverlay(const String& winname, const String& text, int delayms = 0); + +/** @brief Displays a text on the window statusbar during the specified period of time. + +The function displayStatusBar displays useful information/tips on top of the window for a certain +amount of time *delayms* . This information is displayed on the window statusbar (the window must be +created with the CV_GUI_EXPANDED flags). + +@param winname Name of the window. +@param text Text to write on the window statusbar. +@param delayms Duration (in milliseconds) to display the text. If this function is called before +the previous text timed out, the timer is restarted and the text is updated. If this value is +zero, the text never disappears. + */ +CV_EXPORTS_W void displayStatusBar(const String& winname, const String& text, int delayms = 0); + +/** @brief Saves parameters of the specified window. + +The function saveWindowParameters saves size, location, flags, trackbars value, zoom and panning +location of the window windowName. + +@param windowName Name of the window. + */ +CV_EXPORTS void saveWindowParameters(const String& windowName); + +/** @brief Loads parameters of the specified window. + +The function loadWindowParameters loads size, location, flags, trackbars value, zoom and panning +location of the window windowName. + +@param windowName Name of the window. + */ +CV_EXPORTS void loadWindowParameters(const String& windowName); + +CV_EXPORTS int startLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[]); + +CV_EXPORTS void stopLoop(); + +/** @brief Attaches a button to the control panel. + +The function createButton attaches a button to the control panel. Each button is added to a +buttonbar to the right of the last button. A new buttonbar is created if nothing was attached to the +control panel before, or if the last element attached to the control panel was a trackbar or if the +QT_NEW_BUTTONBAR flag is added to the type. + +See below various examples of the cv::createButton function call: : +@code + createButton("",callbackButton);//create a push button "button 0", that will call callbackButton. + createButton("button2",callbackButton,NULL,QT_CHECKBOX,0); + createButton("button3",callbackButton,&value); + createButton("button5",callbackButton1,NULL,QT_RADIOBOX); + createButton("button6",callbackButton2,NULL,QT_PUSH_BUTTON,1); + createButton("button6",callbackButton2,NULL,QT_PUSH_BUTTON|QT_NEW_BUTTONBAR);// create a push button in a new row +@endcode + +@param bar_name Name of the button. +@param on_change Pointer to the function to be called every time the button changes its state. +This function should be prototyped as void Foo(int state,\*void); . *state* is the current state +of the button. It could be -1 for a push button, 0 or 1 for a check/radio box button. +@param userdata Pointer passed to the callback function. +@param type Optional type of the button. Available types are: (cv::QtButtonTypes) +@param initial_button_state Default state of the button. Use for checkbox and radiobox. Its +value could be 0 or 1. (__Optional__) +*/ +CV_EXPORTS int createButton( const String& bar_name, ButtonCallback on_change, + void* userdata = 0, int type = QT_PUSH_BUTTON, + bool initial_button_state = false); + +//! @} highgui_qt + +//! @} highgui + +} // cv + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/highgui/highgui.hpp b/3rdParty/opencv-4.11.0/opencv2/highgui/highgui.hpp index 160c9cf4af..2fba53db0f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/highgui/highgui.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/highgui/highgui.hpp @@ -1,48 +1,48 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifdef __OPENCV_BUILD -#error this is a compatibility header which should not be used inside the OpenCV library -#endif - -#include "opencv2/highgui.hpp" +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/highgui.hpp" diff --git a/3rdParty/opencv-4.11.0/opencv2/highgui/highgui_c.h b/3rdParty/opencv-4.11.0/opencv2/highgui/highgui_c.h index e508e14975..4c7ede3c71 100644 --- a/3rdParty/opencv-4.11.0/opencv2/highgui/highgui_c.h +++ b/3rdParty/opencv-4.11.0/opencv2/highgui/highgui_c.h @@ -1,251 +1,251 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_HIGHGUI_H -#define OPENCV_HIGHGUI_H - -#include "opencv2/core/core_c.h" -#include "opencv2/imgproc/imgproc_c.h" - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/** @addtogroup highgui_c - @{ - */ - -/****************************************************************************************\ -* Basic GUI functions * -\****************************************************************************************/ -//YV -//-----------New for Qt -/* For font */ -enum { CV_FONT_LIGHT = 25,//QFont::Light, - CV_FONT_NORMAL = 50,//QFont::Normal, - CV_FONT_DEMIBOLD = 63,//QFont::DemiBold, - CV_FONT_BOLD = 75,//QFont::Bold, - CV_FONT_BLACK = 87 //QFont::Black -}; - -enum { CV_STYLE_NORMAL = 0,//QFont::StyleNormal, - CV_STYLE_ITALIC = 1,//QFont::StyleItalic, - CV_STYLE_OBLIQUE = 2 //QFont::StyleOblique -}; -/* ---------*/ - -//for color cvScalar(blue_component, green_component, red_component[, alpha_component]) -//and alpha= 0 <-> 0xFF (not transparent <-> transparent) -CVAPI(CvFont) cvFontQt(const char* nameFont, int pointSize CV_DEFAULT(-1), CvScalar color CV_DEFAULT(cvScalarAll(0)), int weight CV_DEFAULT(CV_FONT_NORMAL), int style CV_DEFAULT(CV_STYLE_NORMAL), int spacing CV_DEFAULT(0)); - -CVAPI(void) cvAddText(const CvArr* img, const char* text, CvPoint org, CvFont *arg2); - -CVAPI(void) cvDisplayOverlay(const char* name, const char* text, int delayms CV_DEFAULT(0)); -CVAPI(void) cvDisplayStatusBar(const char* name, const char* text, int delayms CV_DEFAULT(0)); - -CVAPI(void) cvSaveWindowParameters(const char* name); -CVAPI(void) cvLoadWindowParameters(const char* name); -CVAPI(int) cvStartLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[]); -CVAPI(void) cvStopLoop( void ); - -typedef void (CV_CDECL *CvButtonCallback)(int state, void* userdata); -enum {CV_PUSH_BUTTON = 0, CV_CHECKBOX = 1, CV_RADIOBOX = 2}; -CVAPI(int) cvCreateButton( const char* button_name CV_DEFAULT(NULL),CvButtonCallback on_change CV_DEFAULT(NULL), void* userdata CV_DEFAULT(NULL) , int button_type CV_DEFAULT(CV_PUSH_BUTTON), int initial_button_state CV_DEFAULT(0)); -//---------------------- - - -/* this function is used to set some external parameters in case of X Window */ -CVAPI(int) cvInitSystem( int argc, char** argv ); - -CVAPI(int) cvStartWindowThread( void ); - -// --------- YV --------- -enum -{ - //These 3 flags are used by cvSet/GetWindowProperty - CV_WND_PROP_FULLSCREEN = 0, //to change/get window's fullscreen property - CV_WND_PROP_AUTOSIZE = 1, //to change/get window's autosize property - CV_WND_PROP_ASPECTRATIO= 2, //to change/get window's aspectratio property - CV_WND_PROP_OPENGL = 3, //to change/get window's opengl support - CV_WND_PROP_VISIBLE = 4, - - //These 2 flags are used by cvNamedWindow and cvSet/GetWindowProperty - CV_WINDOW_NORMAL = 0x00000000, //the user can resize the window (no constraint) / also use to switch a fullscreen window to a normal size - CV_WINDOW_AUTOSIZE = 0x00000001, //the user cannot resize the window, the size is constrainted by the image displayed - CV_WINDOW_OPENGL = 0x00001000, //window with opengl support - - //Those flags are only for Qt - CV_GUI_EXPANDED = 0x00000000, //status bar and tool bar - CV_GUI_NORMAL = 0x00000010, //old fashious way - - //These 3 flags are used by cvNamedWindow and cvSet/GetWindowProperty - CV_WINDOW_FULLSCREEN = 1,//change the window to fullscreen - CV_WINDOW_FREERATIO = 0x00000100,//the image expends as much as it can (no ratio constraint) - CV_WINDOW_KEEPRATIO = 0x00000000//the ration image is respected. -}; - -/* create window */ -CVAPI(int) cvNamedWindow( const char* name, int flags CV_DEFAULT(CV_WINDOW_AUTOSIZE) ); - -/* Set and Get Property of the window */ -CVAPI(void) cvSetWindowProperty(const char* name, int prop_id, double prop_value); -CVAPI(double) cvGetWindowProperty(const char* name, int prop_id); - -/* display image within window (highgui windows remember their content) */ -CVAPI(void) cvShowImage( const char* name, const CvArr* image ); - -/* resize/move window */ -CVAPI(void) cvResizeWindow( const char* name, int width, int height ); -CVAPI(void) cvMoveWindow( const char* name, int x, int y ); - - -/* destroy window and all the trackers associated with it */ -CVAPI(void) cvDestroyWindow( const char* name ); - -CVAPI(void) cvDestroyAllWindows(void); - -/* get native window handle (HWND in case of Win32 and Widget in case of X Window) */ -CVAPI(void*) cvGetWindowHandle( const char* name ); - -/* get name of highgui window given its native handle */ -CVAPI(const char*) cvGetWindowName( void* window_handle ); - - -typedef void (CV_CDECL *CvTrackbarCallback)(int pos); - -/* create trackbar and display it on top of given window, set callback */ -CVAPI(int) cvCreateTrackbar( const char* trackbar_name, const char* window_name, - int* value, int count, CvTrackbarCallback on_change CV_DEFAULT(NULL)); - -typedef void (CV_CDECL *CvTrackbarCallback2)(int pos, void* userdata); - -CVAPI(int) cvCreateTrackbar2( const char* trackbar_name, const char* window_name, - int* value, int count, CvTrackbarCallback2 on_change, - void* userdata CV_DEFAULT(0)); - -/* retrieve or set trackbar position */ -CVAPI(int) cvGetTrackbarPos( const char* trackbar_name, const char* window_name ); -CVAPI(void) cvSetTrackbarPos( const char* trackbar_name, const char* window_name, int pos ); -CVAPI(void) cvSetTrackbarMax(const char* trackbar_name, const char* window_name, int maxval); -CVAPI(void) cvSetTrackbarMin(const char* trackbar_name, const char* window_name, int minval); - -enum -{ - CV_EVENT_MOUSEMOVE =0, - CV_EVENT_LBUTTONDOWN =1, - CV_EVENT_RBUTTONDOWN =2, - CV_EVENT_MBUTTONDOWN =3, - CV_EVENT_LBUTTONUP =4, - CV_EVENT_RBUTTONUP =5, - CV_EVENT_MBUTTONUP =6, - CV_EVENT_LBUTTONDBLCLK =7, - CV_EVENT_RBUTTONDBLCLK =8, - CV_EVENT_MBUTTONDBLCLK =9, - CV_EVENT_MOUSEWHEEL =10, - CV_EVENT_MOUSEHWHEEL =11 -}; - -enum -{ - CV_EVENT_FLAG_LBUTTON =1, - CV_EVENT_FLAG_RBUTTON =2, - CV_EVENT_FLAG_MBUTTON =4, - CV_EVENT_FLAG_CTRLKEY =8, - CV_EVENT_FLAG_SHIFTKEY =16, - CV_EVENT_FLAG_ALTKEY =32 -}; - - -#define CV_GET_WHEEL_DELTA(flags) ((short)((flags >> 16) & 0xffff)) // upper 16 bits - -typedef void (CV_CDECL *CvMouseCallback )(int event, int x, int y, int flags, void* param); - -/* assign callback for mouse events */ -CVAPI(void) cvSetMouseCallback( const char* window_name, CvMouseCallback on_mouse, - void* param CV_DEFAULT(NULL)); - -/* wait for key event infinitely (delay<=0) or for "delay" milliseconds */ -CVAPI(int) cvWaitKey(int delay CV_DEFAULT(0)); - -// OpenGL support - -typedef void (CV_CDECL *CvOpenGlDrawCallback)(void* userdata); -CVAPI(void) cvSetOpenGlDrawCallback(const char* window_name, CvOpenGlDrawCallback callback, void* userdata CV_DEFAULT(NULL)); - -CVAPI(void) cvSetOpenGlContext(const char* window_name); -CVAPI(void) cvUpdateWindow(const char* window_name); - - -/****************************************************************************************\ - -* Obsolete functions/synonyms * -\****************************************************************************************/ - -#define cvAddSearchPath(path) -#define cvvInitSystem cvInitSystem -#define cvvNamedWindow cvNamedWindow -#define cvvShowImage cvShowImage -#define cvvResizeWindow cvResizeWindow -#define cvvDestroyWindow cvDestroyWindow -#define cvvCreateTrackbar cvCreateTrackbar -#define cvvAddSearchPath cvAddSearchPath -#define cvvWaitKey(name) cvWaitKey(0) -#define cvvWaitKeyEx(name,delay) cvWaitKey(delay) -#define HG_AUTOSIZE CV_WINDOW_AUTOSIZE -#define set_preprocess_func cvSetPreprocessFuncWin32 -#define set_postprocess_func cvSetPostprocessFuncWin32 - -#if defined _WIN32 - -CVAPI(void) cvSetPreprocessFuncWin32_(const void* callback); -CVAPI(void) cvSetPostprocessFuncWin32_(const void* callback); -#define cvSetPreprocessFuncWin32(callback) cvSetPreprocessFuncWin32_((const void*)(callback)) -#define cvSetPostprocessFuncWin32(callback) cvSetPostprocessFuncWin32_((const void*)(callback)) - -#endif - -/** @} highgui_c */ - -#ifdef __cplusplus -} -#endif - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// Intel License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000, Intel Corporation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of Intel Corporation may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_HIGHGUI_H +#define OPENCV_HIGHGUI_H + +#include "opencv2/core/core_c.h" +#include "opencv2/imgproc/imgproc_c.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** @addtogroup highgui_c + @{ + */ + +/****************************************************************************************\ +* Basic GUI functions * +\****************************************************************************************/ +//YV +//-----------New for Qt +/* For font */ +enum { CV_FONT_LIGHT = 25,//QFont::Light, + CV_FONT_NORMAL = 50,//QFont::Normal, + CV_FONT_DEMIBOLD = 63,//QFont::DemiBold, + CV_FONT_BOLD = 75,//QFont::Bold, + CV_FONT_BLACK = 87 //QFont::Black +}; + +enum { CV_STYLE_NORMAL = 0,//QFont::StyleNormal, + CV_STYLE_ITALIC = 1,//QFont::StyleItalic, + CV_STYLE_OBLIQUE = 2 //QFont::StyleOblique +}; +/* ---------*/ + +//for color cvScalar(blue_component, green_component, red_component[, alpha_component]) +//and alpha= 0 <-> 0xFF (not transparent <-> transparent) +CVAPI(CvFont) cvFontQt(const char* nameFont, int pointSize CV_DEFAULT(-1), CvScalar color CV_DEFAULT(cvScalarAll(0)), int weight CV_DEFAULT(CV_FONT_NORMAL), int style CV_DEFAULT(CV_STYLE_NORMAL), int spacing CV_DEFAULT(0)); + +CVAPI(void) cvAddText(const CvArr* img, const char* text, CvPoint org, CvFont *arg2); + +CVAPI(void) cvDisplayOverlay(const char* name, const char* text, int delayms CV_DEFAULT(0)); +CVAPI(void) cvDisplayStatusBar(const char* name, const char* text, int delayms CV_DEFAULT(0)); + +CVAPI(void) cvSaveWindowParameters(const char* name); +CVAPI(void) cvLoadWindowParameters(const char* name); +CVAPI(int) cvStartLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[]); +CVAPI(void) cvStopLoop( void ); + +typedef void (CV_CDECL *CvButtonCallback)(int state, void* userdata); +enum {CV_PUSH_BUTTON = 0, CV_CHECKBOX = 1, CV_RADIOBOX = 2}; +CVAPI(int) cvCreateButton( const char* button_name CV_DEFAULT(NULL),CvButtonCallback on_change CV_DEFAULT(NULL), void* userdata CV_DEFAULT(NULL) , int button_type CV_DEFAULT(CV_PUSH_BUTTON), int initial_button_state CV_DEFAULT(0)); +//---------------------- + + +/* this function is used to set some external parameters in case of X Window */ +CVAPI(int) cvInitSystem( int argc, char** argv ); + +CVAPI(int) cvStartWindowThread( void ); + +// --------- YV --------- +enum +{ + //These 3 flags are used by cvSet/GetWindowProperty + CV_WND_PROP_FULLSCREEN = 0, //to change/get window's fullscreen property + CV_WND_PROP_AUTOSIZE = 1, //to change/get window's autosize property + CV_WND_PROP_ASPECTRATIO= 2, //to change/get window's aspectratio property + CV_WND_PROP_OPENGL = 3, //to change/get window's opengl support + CV_WND_PROP_VISIBLE = 4, + + //These 2 flags are used by cvNamedWindow and cvSet/GetWindowProperty + CV_WINDOW_NORMAL = 0x00000000, //the user can resize the window (no constraint) / also use to switch a fullscreen window to a normal size + CV_WINDOW_AUTOSIZE = 0x00000001, //the user cannot resize the window, the size is constrainted by the image displayed + CV_WINDOW_OPENGL = 0x00001000, //window with opengl support + + //Those flags are only for Qt + CV_GUI_EXPANDED = 0x00000000, //status bar and tool bar + CV_GUI_NORMAL = 0x00000010, //old fashious way + + //These 3 flags are used by cvNamedWindow and cvSet/GetWindowProperty + CV_WINDOW_FULLSCREEN = 1,//change the window to fullscreen + CV_WINDOW_FREERATIO = 0x00000100,//the image expends as much as it can (no ratio constraint) + CV_WINDOW_KEEPRATIO = 0x00000000//the ration image is respected. +}; + +/* create window */ +CVAPI(int) cvNamedWindow( const char* name, int flags CV_DEFAULT(CV_WINDOW_AUTOSIZE) ); + +/* Set and Get Property of the window */ +CVAPI(void) cvSetWindowProperty(const char* name, int prop_id, double prop_value); +CVAPI(double) cvGetWindowProperty(const char* name, int prop_id); + +/* display image within window (highgui windows remember their content) */ +CVAPI(void) cvShowImage( const char* name, const CvArr* image ); + +/* resize/move window */ +CVAPI(void) cvResizeWindow( const char* name, int width, int height ); +CVAPI(void) cvMoveWindow( const char* name, int x, int y ); + + +/* destroy window and all the trackers associated with it */ +CVAPI(void) cvDestroyWindow( const char* name ); + +CVAPI(void) cvDestroyAllWindows(void); + +/* get native window handle (HWND in case of Win32 and Widget in case of X Window) */ +CVAPI(void*) cvGetWindowHandle( const char* name ); + +/* get name of highgui window given its native handle */ +CVAPI(const char*) cvGetWindowName( void* window_handle ); + + +typedef void (CV_CDECL *CvTrackbarCallback)(int pos); + +/* create trackbar and display it on top of given window, set callback */ +CVAPI(int) cvCreateTrackbar( const char* trackbar_name, const char* window_name, + int* value, int count, CvTrackbarCallback on_change CV_DEFAULT(NULL)); + +typedef void (CV_CDECL *CvTrackbarCallback2)(int pos, void* userdata); + +CVAPI(int) cvCreateTrackbar2( const char* trackbar_name, const char* window_name, + int* value, int count, CvTrackbarCallback2 on_change, + void* userdata CV_DEFAULT(0)); + +/* retrieve or set trackbar position */ +CVAPI(int) cvGetTrackbarPos( const char* trackbar_name, const char* window_name ); +CVAPI(void) cvSetTrackbarPos( const char* trackbar_name, const char* window_name, int pos ); +CVAPI(void) cvSetTrackbarMax(const char* trackbar_name, const char* window_name, int maxval); +CVAPI(void) cvSetTrackbarMin(const char* trackbar_name, const char* window_name, int minval); + +enum +{ + CV_EVENT_MOUSEMOVE =0, + CV_EVENT_LBUTTONDOWN =1, + CV_EVENT_RBUTTONDOWN =2, + CV_EVENT_MBUTTONDOWN =3, + CV_EVENT_LBUTTONUP =4, + CV_EVENT_RBUTTONUP =5, + CV_EVENT_MBUTTONUP =6, + CV_EVENT_LBUTTONDBLCLK =7, + CV_EVENT_RBUTTONDBLCLK =8, + CV_EVENT_MBUTTONDBLCLK =9, + CV_EVENT_MOUSEWHEEL =10, + CV_EVENT_MOUSEHWHEEL =11 +}; + +enum +{ + CV_EVENT_FLAG_LBUTTON =1, + CV_EVENT_FLAG_RBUTTON =2, + CV_EVENT_FLAG_MBUTTON =4, + CV_EVENT_FLAG_CTRLKEY =8, + CV_EVENT_FLAG_SHIFTKEY =16, + CV_EVENT_FLAG_ALTKEY =32 +}; + + +#define CV_GET_WHEEL_DELTA(flags) ((short)((flags >> 16) & 0xffff)) // upper 16 bits + +typedef void (CV_CDECL *CvMouseCallback )(int event, int x, int y, int flags, void* param); + +/* assign callback for mouse events */ +CVAPI(void) cvSetMouseCallback( const char* window_name, CvMouseCallback on_mouse, + void* param CV_DEFAULT(NULL)); + +/* wait for key event infinitely (delay<=0) or for "delay" milliseconds */ +CVAPI(int) cvWaitKey(int delay CV_DEFAULT(0)); + +// OpenGL support + +typedef void (CV_CDECL *CvOpenGlDrawCallback)(void* userdata); +CVAPI(void) cvSetOpenGlDrawCallback(const char* window_name, CvOpenGlDrawCallback callback, void* userdata CV_DEFAULT(NULL)); + +CVAPI(void) cvSetOpenGlContext(const char* window_name); +CVAPI(void) cvUpdateWindow(const char* window_name); + + +/****************************************************************************************\ + +* Obsolete functions/synonyms * +\****************************************************************************************/ + +#define cvAddSearchPath(path) +#define cvvInitSystem cvInitSystem +#define cvvNamedWindow cvNamedWindow +#define cvvShowImage cvShowImage +#define cvvResizeWindow cvResizeWindow +#define cvvDestroyWindow cvDestroyWindow +#define cvvCreateTrackbar cvCreateTrackbar +#define cvvAddSearchPath cvAddSearchPath +#define cvvWaitKey(name) cvWaitKey(0) +#define cvvWaitKeyEx(name,delay) cvWaitKey(delay) +#define HG_AUTOSIZE CV_WINDOW_AUTOSIZE +#define set_preprocess_func cvSetPreprocessFuncWin32 +#define set_postprocess_func cvSetPostprocessFuncWin32 + +#if defined _WIN32 + +CVAPI(void) cvSetPreprocessFuncWin32_(const void* callback); +CVAPI(void) cvSetPostprocessFuncWin32_(const void* callback); +#define cvSetPreprocessFuncWin32(callback) cvSetPreprocessFuncWin32_((const void*)(callback)) +#define cvSetPostprocessFuncWin32(callback) cvSetPostprocessFuncWin32_((const void*)(callback)) + +#endif + +/** @} highgui_c */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/imgcodecs.hpp b/3rdParty/opencv-4.11.0/opencv2/imgcodecs.hpp index cd648c2c6e..4f12c18173 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgcodecs.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/imgcodecs.hpp @@ -1,603 +1,603 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_IMGCODECS_HPP -#define OPENCV_IMGCODECS_HPP - -#include "opencv2/core.hpp" - -/** - @defgroup imgcodecs Image file reading and writing - @{ - @defgroup imgcodecs_flags Flags used for image file reading and writing - @defgroup imgcodecs_ios iOS glue - @defgroup imgcodecs_macosx MacOS(OSX) glue - @} -*/ - -//////////////////////////////// image codec //////////////////////////////// -namespace cv -{ - -//! @addtogroup imgcodecs -//! @{ - -//! @addtogroup imgcodecs_flags -//! @{ - -//! Imread flags -enum ImreadModes { - IMREAD_UNCHANGED = -1, //!< If set, return the loaded image as is (with alpha channel, otherwise it gets cropped). Ignore EXIF orientation. - IMREAD_GRAYSCALE = 0, //!< If set, always convert image to the single channel grayscale image (codec internal conversion). - IMREAD_COLOR_BGR = 1, //!< If set, always convert image to the 3 channel BGR color image. - IMREAD_COLOR = 1, //!< Same as IMREAD_COLOR_BGR. - IMREAD_ANYDEPTH = 2, //!< If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit. - IMREAD_ANYCOLOR = 4, //!< If set, the image is read in any possible color format. - IMREAD_LOAD_GDAL = 8, //!< If set, use the gdal driver for loading the image. - IMREAD_REDUCED_GRAYSCALE_2 = 16, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/2. - IMREAD_REDUCED_COLOR_2 = 17, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/2. - IMREAD_REDUCED_GRAYSCALE_4 = 32, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/4. - IMREAD_REDUCED_COLOR_4 = 33, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/4. - IMREAD_REDUCED_GRAYSCALE_8 = 64, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/8. - IMREAD_REDUCED_COLOR_8 = 65, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/8. - IMREAD_IGNORE_ORIENTATION = 128, //!< If set, do not rotate the image according to EXIF's orientation flag. - IMREAD_COLOR_RGB = 256, //!< If set, always convert image to the 3 channel RGB color image. - }; - -//! Imwrite flags -enum ImwriteFlags { - IMWRITE_JPEG_QUALITY = 1, //!< For JPEG, it can be a quality from 0 to 100 (the higher is the better). Default value is 95. - IMWRITE_JPEG_PROGRESSIVE = 2, //!< Enable JPEG features, 0 or 1, default is False. - IMWRITE_JPEG_OPTIMIZE = 3, //!< Enable JPEG features, 0 or 1, default is False. - IMWRITE_JPEG_RST_INTERVAL = 4, //!< JPEG restart interval, 0 - 65535, default is 0 - no restart. - IMWRITE_JPEG_LUMA_QUALITY = 5, //!< Separate luma quality level, 0 - 100, default is -1 - don't use. If JPEG_LIB_VERSION < 70, Not supported. - IMWRITE_JPEG_CHROMA_QUALITY = 6, //!< Separate chroma quality level, 0 - 100, default is -1 - don't use. If JPEG_LIB_VERSION < 70, Not supported. - IMWRITE_JPEG_SAMPLING_FACTOR = 7, //!< For JPEG, set sampling factor. See cv::ImwriteJPEGSamplingFactorParams. - IMWRITE_PNG_COMPRESSION = 16, //!< For PNG, it can be the compression level from 0 to 9. A higher value means a smaller size and longer compression time. If specified, strategy is changed to IMWRITE_PNG_STRATEGY_DEFAULT (Z_DEFAULT_STRATEGY). Default value is 1 (best speed setting). - IMWRITE_PNG_STRATEGY = 17, //!< One of cv::ImwritePNGFlags, default is IMWRITE_PNG_STRATEGY_RLE. - IMWRITE_PNG_BILEVEL = 18, //!< Binary level PNG, 0 or 1, default is 0. - IMWRITE_PXM_BINARY = 32, //!< For PPM, PGM, or PBM, it can be a binary format flag, 0 or 1. Default value is 1. - IMWRITE_EXR_TYPE = (3 << 4) + 0 /* 48 */, //!< override EXR storage type (FLOAT (FP32) is default) - IMWRITE_EXR_COMPRESSION = (3 << 4) + 1 /* 49 */, //!< override EXR compression type (ZIP_COMPRESSION = 3 is default) - IMWRITE_EXR_DWA_COMPRESSION_LEVEL = (3 << 4) + 2 /* 50 */, //!< override EXR DWA compression level (45 is default) - IMWRITE_WEBP_QUALITY = 64, //!< For WEBP, it can be a quality from 1 to 100 (the higher is the better). By default (without any parameter) and for quality above 100 the lossless compression is used. - IMWRITE_HDR_COMPRESSION = (5 << 4) + 0 /* 80 */, //!< specify HDR compression - IMWRITE_PAM_TUPLETYPE = 128,//!< For PAM, sets the TUPLETYPE field to the corresponding string value that is defined for the format - IMWRITE_TIFF_RESUNIT = 256,//!< For TIFF, use to specify which DPI resolution unit to set; see libtiff documentation for valid values - IMWRITE_TIFF_XDPI = 257,//!< For TIFF, use to specify the X direction DPI - IMWRITE_TIFF_YDPI = 258,//!< For TIFF, use to specify the Y direction DPI - IMWRITE_TIFF_COMPRESSION = 259,//!< For TIFF, use to specify the image compression scheme. See cv::ImwriteTiffCompressionFlags. Note, for images whose depth is CV_32F, only libtiff's SGILOG compression scheme is used. For other supported depths, the compression scheme can be specified by this flag; LZW compression is the default. - IMWRITE_TIFF_ROWSPERSTRIP = 278,//!< For TIFF, use to specify the number of rows per strip. - IMWRITE_TIFF_PREDICTOR = 317,//!< For TIFF, use to specify predictor. See cv::ImwriteTiffPredictorFlags. - IMWRITE_JPEG2000_COMPRESSION_X1000 = 272,//!< For JPEG2000, use to specify the target compression rate (multiplied by 1000). The value can be from 0 to 1000. Default is 1000. - IMWRITE_AVIF_QUALITY = 512,//!< For AVIF, it can be a quality between 0 and 100 (the higher the better). Default is 95. - IMWRITE_AVIF_DEPTH = 513,//!< For AVIF, it can be 8, 10 or 12. If >8, it is stored/read as CV_32F. Default is 8. - IMWRITE_AVIF_SPEED = 514,//!< For AVIF, it is between 0 (slowest) and (fastest). Default is 9. - IMWRITE_JPEGXL_QUALITY = 640,//!< For JPEG XL, it can be a quality from 0 to 100 (the higher is the better). Default value is 95. If set, distance parameter is re-calicurated from quality level automatically. This parameter request libjxl v0.10 or later. - IMWRITE_JPEGXL_EFFORT = 641,//!< For JPEG XL, encoder effort/speed level without affecting decoding speed; it is between 1 (fastest) and 10 (slowest). Default is 7. - IMWRITE_JPEGXL_DISTANCE = 642,//!< For JPEG XL, distance level for lossy compression: target max butteraugli distance, lower = higher quality, 0 = lossless; range: 0 .. 25. Default is 1. - IMWRITE_JPEGXL_DECODING_SPEED = 643,//!< For JPEG XL, decoding speed tier for the provided options; minimum is 0 (slowest to decode, best quality/density), and maximum is 4 (fastest to decode, at the cost of some quality/density). Default is 0. - IMWRITE_GIF_LOOP = 1024,//!< For GIF, it can be a loop flag from 0 to 65535. Default is 0 - loop forever. - IMWRITE_GIF_SPEED = 1025,//!< For GIF, it is between 1 (slowest) and 100 (fastest). Default is 96. - IMWRITE_GIF_QUALITY = 1026, //!< For GIF, it can be a quality from 1 to 8. Default is 2. See cv::ImwriteGifCompressionFlags. - IMWRITE_GIF_DITHER = 1027, //!< For GIF, it can be a quality from -1(most dither) to 3(no dither). Default is 0. - IMWRITE_GIF_TRANSPARENCY = 1028, //!< For GIF, the alpha channel lower than this will be set to transparent. Default is 1. - IMWRITE_GIF_COLORTABLE = 1029 //!< For GIF, 0 means global color table is used, 1 means local color table is used. Default is 0. -}; - -enum ImwriteJPEGSamplingFactorParams { - IMWRITE_JPEG_SAMPLING_FACTOR_411 = 0x411111, //!< 4x1,1x1,1x1 - IMWRITE_JPEG_SAMPLING_FACTOR_420 = 0x221111, //!< 2x2,1x1,1x1(Default) - IMWRITE_JPEG_SAMPLING_FACTOR_422 = 0x211111, //!< 2x1,1x1,1x1 - IMWRITE_JPEG_SAMPLING_FACTOR_440 = 0x121111, //!< 1x2,1x1,1x1 - IMWRITE_JPEG_SAMPLING_FACTOR_444 = 0x111111 //!< 1x1,1x1,1x1(No subsampling) - }; - -enum ImwriteTiffCompressionFlags { - IMWRITE_TIFF_COMPRESSION_NONE = 1, //!< dump mode - IMWRITE_TIFF_COMPRESSION_CCITTRLE = 2, //!< CCITT modified Huffman RLE - IMWRITE_TIFF_COMPRESSION_CCITTFAX3 = 3, //!< CCITT Group 3 fax encoding - IMWRITE_TIFF_COMPRESSION_CCITT_T4 = 3, //!< CCITT T.4 (TIFF 6 name) - IMWRITE_TIFF_COMPRESSION_CCITTFAX4 = 4, //!< CCITT Group 4 fax encoding - IMWRITE_TIFF_COMPRESSION_CCITT_T6 = 4, //!< CCITT T.6 (TIFF 6 name) - IMWRITE_TIFF_COMPRESSION_LZW = 5, //!< Lempel-Ziv & Welch - IMWRITE_TIFF_COMPRESSION_OJPEG = 6, //!< !6.0 JPEG - IMWRITE_TIFF_COMPRESSION_JPEG = 7, //!< %JPEG DCT compression - IMWRITE_TIFF_COMPRESSION_T85 = 9, //!< !TIFF/FX T.85 JBIG compression - IMWRITE_TIFF_COMPRESSION_T43 = 10, //!< !TIFF/FX T.43 colour by layered JBIG compression - IMWRITE_TIFF_COMPRESSION_NEXT = 32766, //!< NeXT 2-bit RLE - IMWRITE_TIFF_COMPRESSION_CCITTRLEW = 32771, //!< #1 w/ word alignment - IMWRITE_TIFF_COMPRESSION_PACKBITS = 32773, //!< Macintosh RLE - IMWRITE_TIFF_COMPRESSION_THUNDERSCAN = 32809, //!< ThunderScan RLE - IMWRITE_TIFF_COMPRESSION_IT8CTPAD = 32895, //!< IT8 CT w/padding - IMWRITE_TIFF_COMPRESSION_IT8LW = 32896, //!< IT8 Linework RLE - IMWRITE_TIFF_COMPRESSION_IT8MP = 32897, //!< IT8 Monochrome picture - IMWRITE_TIFF_COMPRESSION_IT8BL = 32898, //!< IT8 Binary line art - IMWRITE_TIFF_COMPRESSION_PIXARFILM = 32908, //!< Pixar companded 10bit LZW - IMWRITE_TIFF_COMPRESSION_PIXARLOG = 32909, //!< Pixar companded 11bit ZIP - IMWRITE_TIFF_COMPRESSION_DEFLATE = 32946, //!< Deflate compression, legacy tag - IMWRITE_TIFF_COMPRESSION_ADOBE_DEFLATE = 8, //!< Deflate compression, as recognized by Adobe - IMWRITE_TIFF_COMPRESSION_DCS = 32947, //!< Kodak DCS encoding - IMWRITE_TIFF_COMPRESSION_JBIG = 34661, //!< ISO JBIG - IMWRITE_TIFF_COMPRESSION_SGILOG = 34676, //!< SGI Log Luminance RLE - IMWRITE_TIFF_COMPRESSION_SGILOG24 = 34677, //!< SGI Log 24-bit packed - IMWRITE_TIFF_COMPRESSION_JP2000 = 34712, //!< Leadtools JPEG2000 - IMWRITE_TIFF_COMPRESSION_LERC = 34887, //!< ESRI Lerc codec: https://github.com/Esri/lerc - IMWRITE_TIFF_COMPRESSION_LZMA = 34925, //!< LZMA2 - IMWRITE_TIFF_COMPRESSION_ZSTD = 50000, //!< ZSTD: WARNING not registered in Adobe-maintained registry - IMWRITE_TIFF_COMPRESSION_WEBP = 50001, //!< WEBP: WARNING not registered in Adobe-maintained registry - IMWRITE_TIFF_COMPRESSION_JXL = 50002 //!< JPEGXL: WARNING not registered in Adobe-maintained registry -}; - -enum ImwriteTiffPredictorFlags { - IMWRITE_TIFF_PREDICTOR_NONE = 1, //!< no prediction scheme used - IMWRITE_TIFF_PREDICTOR_HORIZONTAL = 2, //!< horizontal differencing - IMWRITE_TIFF_PREDICTOR_FLOATINGPOINT = 3 //!< floating point predictor - -}; - -enum ImwriteEXRTypeFlags { - /*IMWRITE_EXR_TYPE_UNIT = 0, //!< not supported */ - IMWRITE_EXR_TYPE_HALF = 1, //!< store as HALF (FP16) - IMWRITE_EXR_TYPE_FLOAT = 2 //!< store as FP32 (default) - }; - -enum ImwriteEXRCompressionFlags { - IMWRITE_EXR_COMPRESSION_NO = 0, //!< no compression - IMWRITE_EXR_COMPRESSION_RLE = 1, //!< run length encoding - IMWRITE_EXR_COMPRESSION_ZIPS = 2, //!< zlib compression, one scan line at a time - IMWRITE_EXR_COMPRESSION_ZIP = 3, //!< zlib compression, in blocks of 16 scan lines - IMWRITE_EXR_COMPRESSION_PIZ = 4, //!< piz-based wavelet compression - IMWRITE_EXR_COMPRESSION_PXR24 = 5, //!< lossy 24-bit float compression - IMWRITE_EXR_COMPRESSION_B44 = 6, //!< lossy 4-by-4 pixel block compression, fixed compression rate - IMWRITE_EXR_COMPRESSION_B44A = 7, //!< lossy 4-by-4 pixel block compression, flat fields are compressed more - IMWRITE_EXR_COMPRESSION_DWAA = 8, //!< lossy DCT based compression, in blocks of 32 scanlines. More efficient for partial buffer access. Supported since OpenEXR 2.2.0. - IMWRITE_EXR_COMPRESSION_DWAB = 9, //!< lossy DCT based compression, in blocks of 256 scanlines. More efficient space wise and faster to decode full frames than DWAA_COMPRESSION. Supported since OpenEXR 2.2.0. - }; - -//! Imwrite PNG specific flags used to tune the compression algorithm. -/** These flags will be modify the way of PNG image compression and will be passed to the underlying zlib processing stage. - -- The effect of IMWRITE_PNG_STRATEGY_FILTERED is to force more Huffman coding and less string matching; it is somewhat intermediate between IMWRITE_PNG_STRATEGY_DEFAULT and IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY. -- IMWRITE_PNG_STRATEGY_RLE is designed to be almost as fast as IMWRITE_PNG_STRATEGY_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. -- IMWRITE_PNG_STRATEGY_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. -*/ -enum ImwritePNGFlags { - IMWRITE_PNG_STRATEGY_DEFAULT = 0, //!< Use this value for normal data. - IMWRITE_PNG_STRATEGY_FILTERED = 1, //!< Use this value for data produced by a filter (or predictor).Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better. - IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY = 2, //!< Use this value to force Huffman encoding only (no string match). - IMWRITE_PNG_STRATEGY_RLE = 3, //!< Use this value to limit match distances to one (run-length encoding). - IMWRITE_PNG_STRATEGY_FIXED = 4 //!< Using this value prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. - }; - -//! Imwrite PAM specific tupletype flags used to define the 'TUPLETYPE' field of a PAM file. -enum ImwritePAMFlags { - IMWRITE_PAM_FORMAT_NULL = 0, - IMWRITE_PAM_FORMAT_BLACKANDWHITE = 1, - IMWRITE_PAM_FORMAT_GRAYSCALE = 2, - IMWRITE_PAM_FORMAT_GRAYSCALE_ALPHA = 3, - IMWRITE_PAM_FORMAT_RGB = 4, - IMWRITE_PAM_FORMAT_RGB_ALPHA = 5 - }; - -//! Imwrite HDR specific values for IMWRITE_HDR_COMPRESSION parameter key -enum ImwriteHDRCompressionFlags { - IMWRITE_HDR_COMPRESSION_NONE = 0, - IMWRITE_HDR_COMPRESSION_RLE = 1 -}; - -//! Imwrite GIF specific values for IMWRITE_GIF_QUALITY parameter key, if larger than 3, then its related to the size of the color table. -enum ImwriteGIFCompressionFlags { - IMWRITE_GIF_FAST_NO_DITHER = 1, - IMWRITE_GIF_FAST_FLOYD_DITHER = 2, - IMWRITE_GIF_COLORTABLE_SIZE_8 = 3, - IMWRITE_GIF_COLORTABLE_SIZE_16 = 4, - IMWRITE_GIF_COLORTABLE_SIZE_32 = 5, - IMWRITE_GIF_COLORTABLE_SIZE_64 = 6, - IMWRITE_GIF_COLORTABLE_SIZE_128 = 7, - IMWRITE_GIF_COLORTABLE_SIZE_256 = 8 -}; - -//! @} imgcodecs_flags - -/** @brief Represents an animation with multiple frames. -The `Animation` struct is designed to store and manage data for animated sequences such as those from animated formats (e.g., GIF, AVIF, APNG, WebP). -It provides support for looping, background color settings, frame timing, and frame storage. -*/ -struct CV_EXPORTS_W_SIMPLE Animation -{ - //! Number of times the animation should loop. 0 means infinite looping. - CV_PROP_RW int loop_count; - //! Background color of the animation in BGRA format. - CV_PROP_RW Scalar bgcolor; - //! Duration for each frame in milliseconds. - CV_PROP_RW std::vector durations; - //! Vector of frames, where each Mat represents a single frame. - CV_PROP_RW std::vector frames; - - /** @brief Constructs an Animation object with optional loop count and background color. - - @param loopCount An integer representing the number of times the animation should loop: - - `0` (default) indicates infinite looping, meaning the animation will replay continuously. - - Positive values denote finite repeat counts, allowing the animation to play a limited number of times. - - If a negative value or a value beyond the maximum of `0xffff` (65535) is provided, it is reset to `0` - (infinite looping) to maintain valid bounds. - - @param bgColor A `Scalar` object representing the background color in BGRA format: - - Defaults to `Scalar()`, indicating an empty color (usually transparent if supported). - - This background color provides a solid fill behind frames that have transparency, ensuring a consistent display appearance. - */ - Animation(int loopCount = 0, Scalar bgColor = Scalar()); -}; - -/** @brief Loads an image from a file. - -@anchor imread - -The `imread` function loads an image from the specified file and returns OpenCV matrix. If the image cannot be -read (because of a missing file, improper permissions, or unsupported/invalid format), the function -returns an empty matrix. - -Currently, the following file formats are supported: - -- Windows bitmaps - \*.bmp, \*.dib (always supported) -- GIF files - \*.gif (always supported) -- JPEG files - \*.jpeg, \*.jpg, \*.jpe (see the *Note* section) -- JPEG 2000 files - \*.jp2 (see the *Note* section) -- Portable Network Graphics - \*.png (see the *Note* section) -- WebP - \*.webp (see the *Note* section) -- AVIF - \*.avif (see the *Note* section) -- Portable image format - \*.pbm, \*.pgm, \*.ppm, \*.pxm, \*.pnm (always supported) -- PFM files - \*.pfm (see the *Note* section) -- Sun rasters - \*.sr, \*.ras (always supported) -- TIFF files - \*.tiff, \*.tif (see the *Note* section) -- OpenEXR Image files - \*.exr (see the *Note* section) -- Radiance HDR - \*.hdr, \*.pic (always supported) -- Raster and Vector geospatial data supported by GDAL (see the *Note* section) - -@note -- The function determines the type of an image by its content, not by the file extension. -- In the case of color images, the decoded images will have the channels stored in **B G R** order. -- When using IMREAD_GRAYSCALE, the codec's internal grayscale conversion will be used, if available. - Results may differ from the output of cvtColor(). -- On Microsoft Windows\* and Mac OS\*, the codecs shipped with OpenCV (libjpeg, libpng, libtiff, - and libjasper) are used by default. So, OpenCV can always read JPEGs, PNGs, and TIFFs. On Mac OS, - there is also an option to use native Mac OS image readers. However, beware that currently these - native image loaders give images with different pixel values because of the color management embedded - into Mac OS. -- On Linux\*, BSD flavors, and other Unix-like open-source operating systems, OpenCV looks for - codecs supplied with the OS. Ensure the relevant packages are installed (including development - files, such as "libjpeg-dev" in Debian\* and Ubuntu\*) to get codec support, or turn - on the OPENCV_BUILD_3RDPARTY_LIBS flag in CMake. -- If the *WITH_GDAL* flag is set to true in CMake and @ref IMREAD_LOAD_GDAL is used to load the image, - the [GDAL](http://www.gdal.org) driver will be used to decode the image, supporting - [Raster](http://www.gdal.org/formats_list.html) and [Vector](http://www.gdal.org/ogr_formats.html) formats. -- If EXIF information is embedded in the image file, the EXIF orientation will be taken into account, - and thus the image will be rotated accordingly unless the flags @ref IMREAD_IGNORE_ORIENTATION - or @ref IMREAD_UNCHANGED are passed. -- Use the IMREAD_UNCHANGED flag to preserve the floating-point values from PFM images. -- By default, the number of pixels must be less than 2^30. This limit can be changed by setting - the environment variable `OPENCV_IO_MAX_IMAGE_PIXELS`. See @ref tutorial_env_reference. - -@param filename Name of the file to be loaded. -@param flags Flag that can take values of `cv::ImreadModes`. -*/ -CV_EXPORTS_W Mat imread( const String& filename, int flags = IMREAD_COLOR_BGR ); - -/** @brief Loads an image from a file. - -This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts and the return value. -@param filename Name of file to be loaded. -@param dst object in which the image will be loaded. -@param flags Flag that can take values of cv::ImreadModes -@note -The image passing through the img parameter can be pre-allocated. The memory is reused if the shape and the type match with the load image. - */ -CV_EXPORTS_W void imread( const String& filename, OutputArray dst, int flags = IMREAD_COLOR_BGR ); - -/** @brief Loads a multi-page image from a file. - -The function imreadmulti loads a multi-page image from the specified file into a vector of Mat objects. -@param filename Name of file to be loaded. -@param mats A vector of Mat objects holding each page. -@param flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR. -@sa cv::imread -*/ -CV_EXPORTS_W bool imreadmulti(const String& filename, CV_OUT std::vector& mats, int flags = IMREAD_ANYCOLOR); - -/** @brief Loads images of a multi-page image from a file. - -The function imreadmulti loads a specified range from a multi-page image from the specified file into a vector of Mat objects. -@param filename Name of file to be loaded. -@param mats A vector of Mat objects holding each page. -@param start Start index of the image to load -@param count Count number of images to load -@param flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR. -@sa cv::imread -*/ -CV_EXPORTS_W bool imreadmulti(const String& filename, CV_OUT std::vector& mats, int start, int count, int flags = IMREAD_ANYCOLOR); - -/** @example samples/cpp/tutorial_code/imgcodecs/animations.cpp -An example to show usage of cv::imreadanimation and cv::imwriteanimation functions. -Check @ref tutorial_animations "the corresponding tutorial" for more details -*/ - -/** @brief Loads frames from an animated image file into an Animation structure. - -The function imreadanimation loads frames from an animated image file (e.g., GIF, AVIF, APNG, WEBP) into the provided Animation struct. - -@param filename A string containing the path to the file. -@param animation A reference to an Animation structure where the loaded frames will be stored. It should be initialized before the function is called. -@param start The index of the first frame to load. This is optional and defaults to 0. -@param count The number of frames to load. This is optional and defaults to 32767. - -@return Returns true if the file was successfully loaded and frames were extracted; returns false otherwise. -*/ -CV_EXPORTS_W bool imreadanimation(const String& filename, CV_OUT Animation& animation, int start = 0, int count = INT16_MAX); - -/** @brief Saves an Animation to a specified file. - -The function imwriteanimation saves the provided Animation data to the specified file in an animated format. -Supported formats depend on the implementation and may include formats like GIF, AVIF, APNG, or WEBP. - -@param filename The name of the file where the animation will be saved. The file extension determines the format. -@param animation A constant reference to an Animation struct containing the frames and metadata to be saved. -@param params Optional format-specific parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, ...). -These parameters are used to specify additional options for the encoding process. Refer to `cv::ImwriteFlags` for details on possible parameters. - -@return Returns true if the animation was successfully saved; returns false otherwise. -*/ -CV_EXPORTS_W bool imwriteanimation(const String& filename, const Animation& animation, const std::vector& params = std::vector()); - -/** @brief Returns the number of images inside the given file - -The function imcount returns the number of pages in a multi-page image (e.g. TIFF), the number of frames in an animation (e.g. AVIF), and 1 otherwise. -If the image cannot be decoded, 0 is returned. -@param filename Name of file to be loaded. -@param flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR. -@todo when cv::IMREAD_LOAD_GDAL flag used the return value will be 0 or 1 because OpenCV's GDAL decoder doesn't support multi-page reading yet. -*/ -CV_EXPORTS_W size_t imcount(const String& filename, int flags = IMREAD_ANYCOLOR); - -/** @brief Saves an image to a specified file. - -The function imwrite saves the image to the specified file. The image format is chosen based on the -filename extension (see cv::imread for the list of extensions). In general, only 8-bit unsigned (CV_8U) -single-channel or 3-channel (with 'BGR' channel order) images -can be saved using this function, with these exceptions: - -- With OpenEXR encoder, only 32-bit float (CV_32F) images can be saved. - - 8-bit unsigned (CV_8U) images are not supported. -- With Radiance HDR encoder, non 64-bit float (CV_64F) images can be saved. - - All images will be converted to 32-bit float (CV_32F). -- With JPEG 2000 encoder, 8-bit unsigned (CV_8U) and 16-bit unsigned (CV_16U) images can be saved. -- With JPEG XL encoder, 8-bit unsigned (CV_8U), 16-bit unsigned (CV_16U) and 32-bit float(CV_32F) images can be saved. - - JPEG XL images with an alpha channel can be saved using this function. - To do this, create 8-bit (or 16-bit, 32-bit float) 4-channel image BGRA, where the alpha channel goes last. - Fully transparent pixels should have alpha set to 0, fully opaque pixels should have alpha set to 255/65535/1.0. -- With PAM encoder, 8-bit unsigned (CV_8U) and 16-bit unsigned (CV_16U) images can be saved. -- With PNG encoder, 8-bit unsigned (CV_8U) and 16-bit unsigned (CV_16U) images can be saved. - - PNG images with an alpha channel can be saved using this function. To do this, create - 8-bit (or 16-bit) 4-channel image BGRA, where the alpha channel goes last. Fully transparent pixels - should have alpha set to 0, fully opaque pixels should have alpha set to 255/65535 (see the code sample below). -- With PGM/PPM encoder, 8-bit unsigned (CV_8U) and 16-bit unsigned (CV_16U) images can be saved. -- With TIFF encoder, 8-bit unsigned (CV_8U), 8-bit signed (CV_8S), - 16-bit unsigned (CV_16U), 16-bit signed (CV_16S), - 32-bit signed (CV_32S), - 32-bit float (CV_32F) and 64-bit float (CV_64F) images can be saved. - - Multiple images (vector of Mat) can be saved in TIFF format (see the code sample below). - - 32-bit float 3-channel (CV_32FC3) TIFF images will be saved - using the LogLuv high dynamic range encoding (4 bytes per pixel) - -If the image format is not supported, the image will be converted to 8-bit unsigned (CV_8U) and saved that way. - -If the format, depth or channel order is different, use -Mat::convertTo and cv::cvtColor to convert it before saving. Or, use the universal FileStorage I/O -functions to save the image to XML or YAML format. - -The sample below shows how to create a BGRA image, how to set custom compression parameters and save it to a PNG file. -It also demonstrates how to save multiple images in a TIFF file: -@include snippets/imgcodecs_imwrite.cpp -@param filename Name of the file. -@param img (Mat or vector of Mat) Image or Images to be saved. -@param params Format-specific parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, ... .) see cv::ImwriteFlags -*/ -CV_EXPORTS_W bool imwrite( const String& filename, InputArray img, - const std::vector& params = std::vector()); - -//! @brief multi-image overload for bindings -CV_WRAP static inline -bool imwritemulti(const String& filename, InputArrayOfArrays img, - const std::vector& params = std::vector()) -{ - return imwrite(filename, img, params); -} - -/** @brief Reads an image from a buffer in memory. - -The function imdecode reads an image from the specified buffer in the memory. If the buffer is too short or -contains invalid data, the function returns an empty matrix ( Mat::data==NULL ). - -See cv::imread for the list of supported formats and flags description. - -@note In the case of color images, the decoded images will have the channels stored in **B G R** order. -@param buf Input array or vector of bytes. -@param flags The same flags as in cv::imread, see cv::ImreadModes. -*/ -CV_EXPORTS_W Mat imdecode( InputArray buf, int flags ); - -/** @overload -@param buf Input array or vector of bytes. -@param flags The same flags as in cv::imread, see cv::ImreadModes. -@param dst The optional output placeholder for the decoded matrix. It can save the image -reallocations when the function is called repeatedly for images of the same size. In case of decoder -failure the function returns empty cv::Mat object, but does not release user-provided dst buffer. -*/ -CV_EXPORTS Mat imdecode( InputArray buf, int flags, Mat* dst); - -/** @brief Reads a multi-page image from a buffer in memory. - -The function imdecodemulti reads a multi-page image from the specified buffer in the memory. If the buffer is too short or -contains invalid data, the function returns false. - -See cv::imreadmulti for the list of supported formats and flags description. - -@note In the case of color images, the decoded images will have the channels stored in **B G R** order. -@param buf Input array or vector of bytes. -@param flags The same flags as in cv::imread, see cv::ImreadModes. -@param mats A vector of Mat objects holding each page, if more than one. -@param range A continuous selection of pages. -*/ -CV_EXPORTS_W bool imdecodemulti(InputArray buf, int flags, CV_OUT std::vector& mats, const cv::Range& range = Range::all()); - -/** @brief Encodes an image into a memory buffer. - -The function imencode compresses the image and stores it in the memory buffer that is resized to fit the -result. See cv::imwrite for the list of supported formats and flags description. - -@param ext File extension that defines the output format. Must include a leading period. -@param img Image to be compressed. -@param buf Output buffer resized to fit the compressed image. -@param params Format-specific parameters. See cv::imwrite and cv::ImwriteFlags. -*/ -CV_EXPORTS_W bool imencode( const String& ext, InputArray img, - CV_OUT std::vector& buf, - const std::vector& params = std::vector()); - -/** @brief Encodes array of images into a memory buffer. - -The function is analog to cv::imencode for in-memory multi-page image compression. -See cv::imwrite for the list of supported formats and flags description. - -@param ext File extension that defines the output format. Must include a leading period. -@param imgs Vector of images to be written. -@param buf Output buffer resized to fit the compressed data. -@param params Format-specific parameters. See cv::imwrite and cv::ImwriteFlags. -*/ -CV_EXPORTS_W bool imencodemulti( const String& ext, InputArrayOfArrays imgs, - CV_OUT std::vector& buf, - const std::vector& params = std::vector()); - -/** @brief Checks if the specified image file can be decoded by OpenCV. - -The function haveImageReader checks if OpenCV is capable of reading the specified file. -This can be useful for verifying support for a given image format before attempting to load an image. - -@param filename The name of the file to be checked. -@return true if an image reader for the specified file is available and the file can be opened, false otherwise. - -@note The function checks the availability of image codecs that are either built into OpenCV or dynamically loaded. -It does not check for the actual existence of the file but rather the ability to read the specified file type. -If the file cannot be opened or the format is unsupported, the function will return false. - -@sa cv::haveImageWriter, cv::imread, cv::imdecode -*/ -CV_EXPORTS_W bool haveImageReader( const String& filename ); - -/** @brief Checks if the specified image file or specified file extension can be encoded by OpenCV. - -The function haveImageWriter checks if OpenCV is capable of writing images with the specified file extension. -This can be useful for verifying support for a given image format before attempting to save an image. - -@param filename The name of the file or the file extension (e.g., ".jpg", ".png"). -It is recommended to provide the file extension rather than the full file name. -@return true if an image writer for the specified extension is available, false otherwise. - -@note The function checks the availability of image codecs that are either built into OpenCV or dynamically loaded. -It does not check for the actual existence of the file but rather the ability to write files of the given type. - -@sa cv::haveImageReader, cv::imwrite, cv::imencode -*/ -CV_EXPORTS_W bool haveImageWriter( const String& filename ); - -/** @brief To read multi-page images on demand - -The ImageCollection class provides iterator API to read multi-page images on demand. Create iterator -to the collection of the images and iterate over the collection. Decode the necessary page with operator*. - -The performance of page decoding is O(1) if collection is increment sequentially. If the user wants to access random page, -then the time Complexity is O(n) because the collection has to be reinitialized every time in order to go to the correct page. -However, the intermediate pages are not decoded during the process, so typically it's quite fast. -This is required because multi-page codecs does not support going backwards. -After decoding the one page, it is stored inside the collection cache. Hence, trying to get Mat object from already decoded page is O(1). -If you need memory, you can use .releaseCache() method to release cached index. -The space complexity is O(n) if all pages are decoded into memory. The user is able to decode and release images on demand. -*/ -class CV_EXPORTS ImageCollection { -public: - struct CV_EXPORTS iterator { - iterator(ImageCollection* col); - iterator(ImageCollection* col, int end); - Mat& operator*(); - Mat* operator->(); - iterator& operator++(); - iterator operator++(int); - friend bool operator== (const iterator& a, const iterator& b) { return a.m_curr == b.m_curr; } - friend bool operator!= (const iterator& a, const iterator& b) { return a.m_curr != b.m_curr; } - - private: - ImageCollection* m_pCollection; - int m_curr; - }; - - ImageCollection(); - ImageCollection(const String& filename, int flags); - void init(const String& img, int flags); - size_t size() const; - const Mat& at(int index); - const Mat& operator[](int index); - void releaseCache(int index); - iterator begin(); - iterator end(); - - class Impl; - Ptr getImpl(); -protected: - Ptr pImpl; -}; - -//! @} imgcodecs - -} // cv - -#endif //OPENCV_IMGCODECS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_IMGCODECS_HPP +#define OPENCV_IMGCODECS_HPP + +#include "opencv2/core.hpp" + +/** + @defgroup imgcodecs Image file reading and writing + @{ + @defgroup imgcodecs_flags Flags used for image file reading and writing + @defgroup imgcodecs_ios iOS glue + @defgroup imgcodecs_macosx MacOS(OSX) glue + @} +*/ + +//////////////////////////////// image codec //////////////////////////////// +namespace cv +{ + +//! @addtogroup imgcodecs +//! @{ + +//! @addtogroup imgcodecs_flags +//! @{ + +//! Imread flags +enum ImreadModes { + IMREAD_UNCHANGED = -1, //!< If set, return the loaded image as is (with alpha channel, otherwise it gets cropped). Ignore EXIF orientation. + IMREAD_GRAYSCALE = 0, //!< If set, always convert image to the single channel grayscale image (codec internal conversion). + IMREAD_COLOR_BGR = 1, //!< If set, always convert image to the 3 channel BGR color image. + IMREAD_COLOR = 1, //!< Same as IMREAD_COLOR_BGR. + IMREAD_ANYDEPTH = 2, //!< If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit. + IMREAD_ANYCOLOR = 4, //!< If set, the image is read in any possible color format. + IMREAD_LOAD_GDAL = 8, //!< If set, use the gdal driver for loading the image. + IMREAD_REDUCED_GRAYSCALE_2 = 16, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/2. + IMREAD_REDUCED_COLOR_2 = 17, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/2. + IMREAD_REDUCED_GRAYSCALE_4 = 32, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/4. + IMREAD_REDUCED_COLOR_4 = 33, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/4. + IMREAD_REDUCED_GRAYSCALE_8 = 64, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/8. + IMREAD_REDUCED_COLOR_8 = 65, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/8. + IMREAD_IGNORE_ORIENTATION = 128, //!< If set, do not rotate the image according to EXIF's orientation flag. + IMREAD_COLOR_RGB = 256, //!< If set, always convert image to the 3 channel RGB color image. + }; + +//! Imwrite flags +enum ImwriteFlags { + IMWRITE_JPEG_QUALITY = 1, //!< For JPEG, it can be a quality from 0 to 100 (the higher is the better). Default value is 95. + IMWRITE_JPEG_PROGRESSIVE = 2, //!< Enable JPEG features, 0 or 1, default is False. + IMWRITE_JPEG_OPTIMIZE = 3, //!< Enable JPEG features, 0 or 1, default is False. + IMWRITE_JPEG_RST_INTERVAL = 4, //!< JPEG restart interval, 0 - 65535, default is 0 - no restart. + IMWRITE_JPEG_LUMA_QUALITY = 5, //!< Separate luma quality level, 0 - 100, default is -1 - don't use. If JPEG_LIB_VERSION < 70, Not supported. + IMWRITE_JPEG_CHROMA_QUALITY = 6, //!< Separate chroma quality level, 0 - 100, default is -1 - don't use. If JPEG_LIB_VERSION < 70, Not supported. + IMWRITE_JPEG_SAMPLING_FACTOR = 7, //!< For JPEG, set sampling factor. See cv::ImwriteJPEGSamplingFactorParams. + IMWRITE_PNG_COMPRESSION = 16, //!< For PNG, it can be the compression level from 0 to 9. A higher value means a smaller size and longer compression time. If specified, strategy is changed to IMWRITE_PNG_STRATEGY_DEFAULT (Z_DEFAULT_STRATEGY). Default value is 1 (best speed setting). + IMWRITE_PNG_STRATEGY = 17, //!< One of cv::ImwritePNGFlags, default is IMWRITE_PNG_STRATEGY_RLE. + IMWRITE_PNG_BILEVEL = 18, //!< Binary level PNG, 0 or 1, default is 0. + IMWRITE_PXM_BINARY = 32, //!< For PPM, PGM, or PBM, it can be a binary format flag, 0 or 1. Default value is 1. + IMWRITE_EXR_TYPE = (3 << 4) + 0 /* 48 */, //!< override EXR storage type (FLOAT (FP32) is default) + IMWRITE_EXR_COMPRESSION = (3 << 4) + 1 /* 49 */, //!< override EXR compression type (ZIP_COMPRESSION = 3 is default) + IMWRITE_EXR_DWA_COMPRESSION_LEVEL = (3 << 4) + 2 /* 50 */, //!< override EXR DWA compression level (45 is default) + IMWRITE_WEBP_QUALITY = 64, //!< For WEBP, it can be a quality from 1 to 100 (the higher is the better). By default (without any parameter) and for quality above 100 the lossless compression is used. + IMWRITE_HDR_COMPRESSION = (5 << 4) + 0 /* 80 */, //!< specify HDR compression + IMWRITE_PAM_TUPLETYPE = 128,//!< For PAM, sets the TUPLETYPE field to the corresponding string value that is defined for the format + IMWRITE_TIFF_RESUNIT = 256,//!< For TIFF, use to specify which DPI resolution unit to set; see libtiff documentation for valid values + IMWRITE_TIFF_XDPI = 257,//!< For TIFF, use to specify the X direction DPI + IMWRITE_TIFF_YDPI = 258,//!< For TIFF, use to specify the Y direction DPI + IMWRITE_TIFF_COMPRESSION = 259,//!< For TIFF, use to specify the image compression scheme. See cv::ImwriteTiffCompressionFlags. Note, for images whose depth is CV_32F, only libtiff's SGILOG compression scheme is used. For other supported depths, the compression scheme can be specified by this flag; LZW compression is the default. + IMWRITE_TIFF_ROWSPERSTRIP = 278,//!< For TIFF, use to specify the number of rows per strip. + IMWRITE_TIFF_PREDICTOR = 317,//!< For TIFF, use to specify predictor. See cv::ImwriteTiffPredictorFlags. + IMWRITE_JPEG2000_COMPRESSION_X1000 = 272,//!< For JPEG2000, use to specify the target compression rate (multiplied by 1000). The value can be from 0 to 1000. Default is 1000. + IMWRITE_AVIF_QUALITY = 512,//!< For AVIF, it can be a quality between 0 and 100 (the higher the better). Default is 95. + IMWRITE_AVIF_DEPTH = 513,//!< For AVIF, it can be 8, 10 or 12. If >8, it is stored/read as CV_32F. Default is 8. + IMWRITE_AVIF_SPEED = 514,//!< For AVIF, it is between 0 (slowest) and (fastest). Default is 9. + IMWRITE_JPEGXL_QUALITY = 640,//!< For JPEG XL, it can be a quality from 0 to 100 (the higher is the better). Default value is 95. If set, distance parameter is re-calicurated from quality level automatically. This parameter request libjxl v0.10 or later. + IMWRITE_JPEGXL_EFFORT = 641,//!< For JPEG XL, encoder effort/speed level without affecting decoding speed; it is between 1 (fastest) and 10 (slowest). Default is 7. + IMWRITE_JPEGXL_DISTANCE = 642,//!< For JPEG XL, distance level for lossy compression: target max butteraugli distance, lower = higher quality, 0 = lossless; range: 0 .. 25. Default is 1. + IMWRITE_JPEGXL_DECODING_SPEED = 643,//!< For JPEG XL, decoding speed tier for the provided options; minimum is 0 (slowest to decode, best quality/density), and maximum is 4 (fastest to decode, at the cost of some quality/density). Default is 0. + IMWRITE_GIF_LOOP = 1024,//!< For GIF, it can be a loop flag from 0 to 65535. Default is 0 - loop forever. + IMWRITE_GIF_SPEED = 1025,//!< For GIF, it is between 1 (slowest) and 100 (fastest). Default is 96. + IMWRITE_GIF_QUALITY = 1026, //!< For GIF, it can be a quality from 1 to 8. Default is 2. See cv::ImwriteGifCompressionFlags. + IMWRITE_GIF_DITHER = 1027, //!< For GIF, it can be a quality from -1(most dither) to 3(no dither). Default is 0. + IMWRITE_GIF_TRANSPARENCY = 1028, //!< For GIF, the alpha channel lower than this will be set to transparent. Default is 1. + IMWRITE_GIF_COLORTABLE = 1029 //!< For GIF, 0 means global color table is used, 1 means local color table is used. Default is 0. +}; + +enum ImwriteJPEGSamplingFactorParams { + IMWRITE_JPEG_SAMPLING_FACTOR_411 = 0x411111, //!< 4x1,1x1,1x1 + IMWRITE_JPEG_SAMPLING_FACTOR_420 = 0x221111, //!< 2x2,1x1,1x1(Default) + IMWRITE_JPEG_SAMPLING_FACTOR_422 = 0x211111, //!< 2x1,1x1,1x1 + IMWRITE_JPEG_SAMPLING_FACTOR_440 = 0x121111, //!< 1x2,1x1,1x1 + IMWRITE_JPEG_SAMPLING_FACTOR_444 = 0x111111 //!< 1x1,1x1,1x1(No subsampling) + }; + +enum ImwriteTiffCompressionFlags { + IMWRITE_TIFF_COMPRESSION_NONE = 1, //!< dump mode + IMWRITE_TIFF_COMPRESSION_CCITTRLE = 2, //!< CCITT modified Huffman RLE + IMWRITE_TIFF_COMPRESSION_CCITTFAX3 = 3, //!< CCITT Group 3 fax encoding + IMWRITE_TIFF_COMPRESSION_CCITT_T4 = 3, //!< CCITT T.4 (TIFF 6 name) + IMWRITE_TIFF_COMPRESSION_CCITTFAX4 = 4, //!< CCITT Group 4 fax encoding + IMWRITE_TIFF_COMPRESSION_CCITT_T6 = 4, //!< CCITT T.6 (TIFF 6 name) + IMWRITE_TIFF_COMPRESSION_LZW = 5, //!< Lempel-Ziv & Welch + IMWRITE_TIFF_COMPRESSION_OJPEG = 6, //!< !6.0 JPEG + IMWRITE_TIFF_COMPRESSION_JPEG = 7, //!< %JPEG DCT compression + IMWRITE_TIFF_COMPRESSION_T85 = 9, //!< !TIFF/FX T.85 JBIG compression + IMWRITE_TIFF_COMPRESSION_T43 = 10, //!< !TIFF/FX T.43 colour by layered JBIG compression + IMWRITE_TIFF_COMPRESSION_NEXT = 32766, //!< NeXT 2-bit RLE + IMWRITE_TIFF_COMPRESSION_CCITTRLEW = 32771, //!< #1 w/ word alignment + IMWRITE_TIFF_COMPRESSION_PACKBITS = 32773, //!< Macintosh RLE + IMWRITE_TIFF_COMPRESSION_THUNDERSCAN = 32809, //!< ThunderScan RLE + IMWRITE_TIFF_COMPRESSION_IT8CTPAD = 32895, //!< IT8 CT w/padding + IMWRITE_TIFF_COMPRESSION_IT8LW = 32896, //!< IT8 Linework RLE + IMWRITE_TIFF_COMPRESSION_IT8MP = 32897, //!< IT8 Monochrome picture + IMWRITE_TIFF_COMPRESSION_IT8BL = 32898, //!< IT8 Binary line art + IMWRITE_TIFF_COMPRESSION_PIXARFILM = 32908, //!< Pixar companded 10bit LZW + IMWRITE_TIFF_COMPRESSION_PIXARLOG = 32909, //!< Pixar companded 11bit ZIP + IMWRITE_TIFF_COMPRESSION_DEFLATE = 32946, //!< Deflate compression, legacy tag + IMWRITE_TIFF_COMPRESSION_ADOBE_DEFLATE = 8, //!< Deflate compression, as recognized by Adobe + IMWRITE_TIFF_COMPRESSION_DCS = 32947, //!< Kodak DCS encoding + IMWRITE_TIFF_COMPRESSION_JBIG = 34661, //!< ISO JBIG + IMWRITE_TIFF_COMPRESSION_SGILOG = 34676, //!< SGI Log Luminance RLE + IMWRITE_TIFF_COMPRESSION_SGILOG24 = 34677, //!< SGI Log 24-bit packed + IMWRITE_TIFF_COMPRESSION_JP2000 = 34712, //!< Leadtools JPEG2000 + IMWRITE_TIFF_COMPRESSION_LERC = 34887, //!< ESRI Lerc codec: https://github.com/Esri/lerc + IMWRITE_TIFF_COMPRESSION_LZMA = 34925, //!< LZMA2 + IMWRITE_TIFF_COMPRESSION_ZSTD = 50000, //!< ZSTD: WARNING not registered in Adobe-maintained registry + IMWRITE_TIFF_COMPRESSION_WEBP = 50001, //!< WEBP: WARNING not registered in Adobe-maintained registry + IMWRITE_TIFF_COMPRESSION_JXL = 50002 //!< JPEGXL: WARNING not registered in Adobe-maintained registry +}; + +enum ImwriteTiffPredictorFlags { + IMWRITE_TIFF_PREDICTOR_NONE = 1, //!< no prediction scheme used + IMWRITE_TIFF_PREDICTOR_HORIZONTAL = 2, //!< horizontal differencing + IMWRITE_TIFF_PREDICTOR_FLOATINGPOINT = 3 //!< floating point predictor + +}; + +enum ImwriteEXRTypeFlags { + /*IMWRITE_EXR_TYPE_UNIT = 0, //!< not supported */ + IMWRITE_EXR_TYPE_HALF = 1, //!< store as HALF (FP16) + IMWRITE_EXR_TYPE_FLOAT = 2 //!< store as FP32 (default) + }; + +enum ImwriteEXRCompressionFlags { + IMWRITE_EXR_COMPRESSION_NO = 0, //!< no compression + IMWRITE_EXR_COMPRESSION_RLE = 1, //!< run length encoding + IMWRITE_EXR_COMPRESSION_ZIPS = 2, //!< zlib compression, one scan line at a time + IMWRITE_EXR_COMPRESSION_ZIP = 3, //!< zlib compression, in blocks of 16 scan lines + IMWRITE_EXR_COMPRESSION_PIZ = 4, //!< piz-based wavelet compression + IMWRITE_EXR_COMPRESSION_PXR24 = 5, //!< lossy 24-bit float compression + IMWRITE_EXR_COMPRESSION_B44 = 6, //!< lossy 4-by-4 pixel block compression, fixed compression rate + IMWRITE_EXR_COMPRESSION_B44A = 7, //!< lossy 4-by-4 pixel block compression, flat fields are compressed more + IMWRITE_EXR_COMPRESSION_DWAA = 8, //!< lossy DCT based compression, in blocks of 32 scanlines. More efficient for partial buffer access. Supported since OpenEXR 2.2.0. + IMWRITE_EXR_COMPRESSION_DWAB = 9, //!< lossy DCT based compression, in blocks of 256 scanlines. More efficient space wise and faster to decode full frames than DWAA_COMPRESSION. Supported since OpenEXR 2.2.0. + }; + +//! Imwrite PNG specific flags used to tune the compression algorithm. +/** These flags will be modify the way of PNG image compression and will be passed to the underlying zlib processing stage. + +- The effect of IMWRITE_PNG_STRATEGY_FILTERED is to force more Huffman coding and less string matching; it is somewhat intermediate between IMWRITE_PNG_STRATEGY_DEFAULT and IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY. +- IMWRITE_PNG_STRATEGY_RLE is designed to be almost as fast as IMWRITE_PNG_STRATEGY_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. +- IMWRITE_PNG_STRATEGY_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. +*/ +enum ImwritePNGFlags { + IMWRITE_PNG_STRATEGY_DEFAULT = 0, //!< Use this value for normal data. + IMWRITE_PNG_STRATEGY_FILTERED = 1, //!< Use this value for data produced by a filter (or predictor).Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better. + IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY = 2, //!< Use this value to force Huffman encoding only (no string match). + IMWRITE_PNG_STRATEGY_RLE = 3, //!< Use this value to limit match distances to one (run-length encoding). + IMWRITE_PNG_STRATEGY_FIXED = 4 //!< Using this value prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. + }; + +//! Imwrite PAM specific tupletype flags used to define the 'TUPLETYPE' field of a PAM file. +enum ImwritePAMFlags { + IMWRITE_PAM_FORMAT_NULL = 0, + IMWRITE_PAM_FORMAT_BLACKANDWHITE = 1, + IMWRITE_PAM_FORMAT_GRAYSCALE = 2, + IMWRITE_PAM_FORMAT_GRAYSCALE_ALPHA = 3, + IMWRITE_PAM_FORMAT_RGB = 4, + IMWRITE_PAM_FORMAT_RGB_ALPHA = 5 + }; + +//! Imwrite HDR specific values for IMWRITE_HDR_COMPRESSION parameter key +enum ImwriteHDRCompressionFlags { + IMWRITE_HDR_COMPRESSION_NONE = 0, + IMWRITE_HDR_COMPRESSION_RLE = 1 +}; + +//! Imwrite GIF specific values for IMWRITE_GIF_QUALITY parameter key, if larger than 3, then its related to the size of the color table. +enum ImwriteGIFCompressionFlags { + IMWRITE_GIF_FAST_NO_DITHER = 1, + IMWRITE_GIF_FAST_FLOYD_DITHER = 2, + IMWRITE_GIF_COLORTABLE_SIZE_8 = 3, + IMWRITE_GIF_COLORTABLE_SIZE_16 = 4, + IMWRITE_GIF_COLORTABLE_SIZE_32 = 5, + IMWRITE_GIF_COLORTABLE_SIZE_64 = 6, + IMWRITE_GIF_COLORTABLE_SIZE_128 = 7, + IMWRITE_GIF_COLORTABLE_SIZE_256 = 8 +}; + +//! @} imgcodecs_flags + +/** @brief Represents an animation with multiple frames. +The `Animation` struct is designed to store and manage data for animated sequences such as those from animated formats (e.g., GIF, AVIF, APNG, WebP). +It provides support for looping, background color settings, frame timing, and frame storage. +*/ +struct CV_EXPORTS_W_SIMPLE Animation +{ + //! Number of times the animation should loop. 0 means infinite looping. + CV_PROP_RW int loop_count; + //! Background color of the animation in BGRA format. + CV_PROP_RW Scalar bgcolor; + //! Duration for each frame in milliseconds. + CV_PROP_RW std::vector durations; + //! Vector of frames, where each Mat represents a single frame. + CV_PROP_RW std::vector frames; + + /** @brief Constructs an Animation object with optional loop count and background color. + + @param loopCount An integer representing the number of times the animation should loop: + - `0` (default) indicates infinite looping, meaning the animation will replay continuously. + - Positive values denote finite repeat counts, allowing the animation to play a limited number of times. + - If a negative value or a value beyond the maximum of `0xffff` (65535) is provided, it is reset to `0` + (infinite looping) to maintain valid bounds. + + @param bgColor A `Scalar` object representing the background color in BGRA format: + - Defaults to `Scalar()`, indicating an empty color (usually transparent if supported). + - This background color provides a solid fill behind frames that have transparency, ensuring a consistent display appearance. + */ + Animation(int loopCount = 0, Scalar bgColor = Scalar()); +}; + +/** @brief Loads an image from a file. + +@anchor imread + +The `imread` function loads an image from the specified file and returns OpenCV matrix. If the image cannot be +read (because of a missing file, improper permissions, or unsupported/invalid format), the function +returns an empty matrix. + +Currently, the following file formats are supported: + +- Windows bitmaps - \*.bmp, \*.dib (always supported) +- GIF files - \*.gif (always supported) +- JPEG files - \*.jpeg, \*.jpg, \*.jpe (see the *Note* section) +- JPEG 2000 files - \*.jp2 (see the *Note* section) +- Portable Network Graphics - \*.png (see the *Note* section) +- WebP - \*.webp (see the *Note* section) +- AVIF - \*.avif (see the *Note* section) +- Portable image format - \*.pbm, \*.pgm, \*.ppm, \*.pxm, \*.pnm (always supported) +- PFM files - \*.pfm (see the *Note* section) +- Sun rasters - \*.sr, \*.ras (always supported) +- TIFF files - \*.tiff, \*.tif (see the *Note* section) +- OpenEXR Image files - \*.exr (see the *Note* section) +- Radiance HDR - \*.hdr, \*.pic (always supported) +- Raster and Vector geospatial data supported by GDAL (see the *Note* section) + +@note +- The function determines the type of an image by its content, not by the file extension. +- In the case of color images, the decoded images will have the channels stored in **B G R** order. +- When using IMREAD_GRAYSCALE, the codec's internal grayscale conversion will be used, if available. + Results may differ from the output of cvtColor(). +- On Microsoft Windows\* and Mac OS\*, the codecs shipped with OpenCV (libjpeg, libpng, libtiff, + and libjasper) are used by default. So, OpenCV can always read JPEGs, PNGs, and TIFFs. On Mac OS, + there is also an option to use native Mac OS image readers. However, beware that currently these + native image loaders give images with different pixel values because of the color management embedded + into Mac OS. +- On Linux\*, BSD flavors, and other Unix-like open-source operating systems, OpenCV looks for + codecs supplied with the OS. Ensure the relevant packages are installed (including development + files, such as "libjpeg-dev" in Debian\* and Ubuntu\*) to get codec support, or turn + on the OPENCV_BUILD_3RDPARTY_LIBS flag in CMake. +- If the *WITH_GDAL* flag is set to true in CMake and @ref IMREAD_LOAD_GDAL is used to load the image, + the [GDAL](http://www.gdal.org) driver will be used to decode the image, supporting + [Raster](http://www.gdal.org/formats_list.html) and [Vector](http://www.gdal.org/ogr_formats.html) formats. +- If EXIF information is embedded in the image file, the EXIF orientation will be taken into account, + and thus the image will be rotated accordingly unless the flags @ref IMREAD_IGNORE_ORIENTATION + or @ref IMREAD_UNCHANGED are passed. +- Use the IMREAD_UNCHANGED flag to preserve the floating-point values from PFM images. +- By default, the number of pixels must be less than 2^30. This limit can be changed by setting + the environment variable `OPENCV_IO_MAX_IMAGE_PIXELS`. See @ref tutorial_env_reference. + +@param filename Name of the file to be loaded. +@param flags Flag that can take values of `cv::ImreadModes`. +*/ +CV_EXPORTS_W Mat imread( const String& filename, int flags = IMREAD_COLOR_BGR ); + +/** @brief Loads an image from a file. + +This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts and the return value. +@param filename Name of file to be loaded. +@param dst object in which the image will be loaded. +@param flags Flag that can take values of cv::ImreadModes +@note +The image passing through the img parameter can be pre-allocated. The memory is reused if the shape and the type match with the load image. + */ +CV_EXPORTS_W void imread( const String& filename, OutputArray dst, int flags = IMREAD_COLOR_BGR ); + +/** @brief Loads a multi-page image from a file. + +The function imreadmulti loads a multi-page image from the specified file into a vector of Mat objects. +@param filename Name of file to be loaded. +@param mats A vector of Mat objects holding each page. +@param flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR. +@sa cv::imread +*/ +CV_EXPORTS_W bool imreadmulti(const String& filename, CV_OUT std::vector& mats, int flags = IMREAD_ANYCOLOR); + +/** @brief Loads images of a multi-page image from a file. + +The function imreadmulti loads a specified range from a multi-page image from the specified file into a vector of Mat objects. +@param filename Name of file to be loaded. +@param mats A vector of Mat objects holding each page. +@param start Start index of the image to load +@param count Count number of images to load +@param flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR. +@sa cv::imread +*/ +CV_EXPORTS_W bool imreadmulti(const String& filename, CV_OUT std::vector& mats, int start, int count, int flags = IMREAD_ANYCOLOR); + +/** @example samples/cpp/tutorial_code/imgcodecs/animations.cpp +An example to show usage of cv::imreadanimation and cv::imwriteanimation functions. +Check @ref tutorial_animations "the corresponding tutorial" for more details +*/ + +/** @brief Loads frames from an animated image file into an Animation structure. + +The function imreadanimation loads frames from an animated image file (e.g., GIF, AVIF, APNG, WEBP) into the provided Animation struct. + +@param filename A string containing the path to the file. +@param animation A reference to an Animation structure where the loaded frames will be stored. It should be initialized before the function is called. +@param start The index of the first frame to load. This is optional and defaults to 0. +@param count The number of frames to load. This is optional and defaults to 32767. + +@return Returns true if the file was successfully loaded and frames were extracted; returns false otherwise. +*/ +CV_EXPORTS_W bool imreadanimation(const String& filename, CV_OUT Animation& animation, int start = 0, int count = INT16_MAX); + +/** @brief Saves an Animation to a specified file. + +The function imwriteanimation saves the provided Animation data to the specified file in an animated format. +Supported formats depend on the implementation and may include formats like GIF, AVIF, APNG, or WEBP. + +@param filename The name of the file where the animation will be saved. The file extension determines the format. +@param animation A constant reference to an Animation struct containing the frames and metadata to be saved. +@param params Optional format-specific parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, ...). +These parameters are used to specify additional options for the encoding process. Refer to `cv::ImwriteFlags` for details on possible parameters. + +@return Returns true if the animation was successfully saved; returns false otherwise. +*/ +CV_EXPORTS_W bool imwriteanimation(const String& filename, const Animation& animation, const std::vector& params = std::vector()); + +/** @brief Returns the number of images inside the given file + +The function imcount returns the number of pages in a multi-page image (e.g. TIFF), the number of frames in an animation (e.g. AVIF), and 1 otherwise. +If the image cannot be decoded, 0 is returned. +@param filename Name of file to be loaded. +@param flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR. +@todo when cv::IMREAD_LOAD_GDAL flag used the return value will be 0 or 1 because OpenCV's GDAL decoder doesn't support multi-page reading yet. +*/ +CV_EXPORTS_W size_t imcount(const String& filename, int flags = IMREAD_ANYCOLOR); + +/** @brief Saves an image to a specified file. + +The function imwrite saves the image to the specified file. The image format is chosen based on the +filename extension (see cv::imread for the list of extensions). In general, only 8-bit unsigned (CV_8U) +single-channel or 3-channel (with 'BGR' channel order) images +can be saved using this function, with these exceptions: + +- With OpenEXR encoder, only 32-bit float (CV_32F) images can be saved. + - 8-bit unsigned (CV_8U) images are not supported. +- With Radiance HDR encoder, non 64-bit float (CV_64F) images can be saved. + - All images will be converted to 32-bit float (CV_32F). +- With JPEG 2000 encoder, 8-bit unsigned (CV_8U) and 16-bit unsigned (CV_16U) images can be saved. +- With JPEG XL encoder, 8-bit unsigned (CV_8U), 16-bit unsigned (CV_16U) and 32-bit float(CV_32F) images can be saved. + - JPEG XL images with an alpha channel can be saved using this function. + To do this, create 8-bit (or 16-bit, 32-bit float) 4-channel image BGRA, where the alpha channel goes last. + Fully transparent pixels should have alpha set to 0, fully opaque pixels should have alpha set to 255/65535/1.0. +- With PAM encoder, 8-bit unsigned (CV_8U) and 16-bit unsigned (CV_16U) images can be saved. +- With PNG encoder, 8-bit unsigned (CV_8U) and 16-bit unsigned (CV_16U) images can be saved. + - PNG images with an alpha channel can be saved using this function. To do this, create + 8-bit (or 16-bit) 4-channel image BGRA, where the alpha channel goes last. Fully transparent pixels + should have alpha set to 0, fully opaque pixels should have alpha set to 255/65535 (see the code sample below). +- With PGM/PPM encoder, 8-bit unsigned (CV_8U) and 16-bit unsigned (CV_16U) images can be saved. +- With TIFF encoder, 8-bit unsigned (CV_8U), 8-bit signed (CV_8S), + 16-bit unsigned (CV_16U), 16-bit signed (CV_16S), + 32-bit signed (CV_32S), + 32-bit float (CV_32F) and 64-bit float (CV_64F) images can be saved. + - Multiple images (vector of Mat) can be saved in TIFF format (see the code sample below). + - 32-bit float 3-channel (CV_32FC3) TIFF images will be saved + using the LogLuv high dynamic range encoding (4 bytes per pixel) + +If the image format is not supported, the image will be converted to 8-bit unsigned (CV_8U) and saved that way. + +If the format, depth or channel order is different, use +Mat::convertTo and cv::cvtColor to convert it before saving. Or, use the universal FileStorage I/O +functions to save the image to XML or YAML format. + +The sample below shows how to create a BGRA image, how to set custom compression parameters and save it to a PNG file. +It also demonstrates how to save multiple images in a TIFF file: +@include snippets/imgcodecs_imwrite.cpp +@param filename Name of the file. +@param img (Mat or vector of Mat) Image or Images to be saved. +@param params Format-specific parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, ... .) see cv::ImwriteFlags +*/ +CV_EXPORTS_W bool imwrite( const String& filename, InputArray img, + const std::vector& params = std::vector()); + +//! @brief multi-image overload for bindings +CV_WRAP static inline +bool imwritemulti(const String& filename, InputArrayOfArrays img, + const std::vector& params = std::vector()) +{ + return imwrite(filename, img, params); +} + +/** @brief Reads an image from a buffer in memory. + +The function imdecode reads an image from the specified buffer in the memory. If the buffer is too short or +contains invalid data, the function returns an empty matrix ( Mat::data==NULL ). + +See cv::imread for the list of supported formats and flags description. + +@note In the case of color images, the decoded images will have the channels stored in **B G R** order. +@param buf Input array or vector of bytes. +@param flags The same flags as in cv::imread, see cv::ImreadModes. +*/ +CV_EXPORTS_W Mat imdecode( InputArray buf, int flags ); + +/** @overload +@param buf Input array or vector of bytes. +@param flags The same flags as in cv::imread, see cv::ImreadModes. +@param dst The optional output placeholder for the decoded matrix. It can save the image +reallocations when the function is called repeatedly for images of the same size. In case of decoder +failure the function returns empty cv::Mat object, but does not release user-provided dst buffer. +*/ +CV_EXPORTS Mat imdecode( InputArray buf, int flags, Mat* dst); + +/** @brief Reads a multi-page image from a buffer in memory. + +The function imdecodemulti reads a multi-page image from the specified buffer in the memory. If the buffer is too short or +contains invalid data, the function returns false. + +See cv::imreadmulti for the list of supported formats and flags description. + +@note In the case of color images, the decoded images will have the channels stored in **B G R** order. +@param buf Input array or vector of bytes. +@param flags The same flags as in cv::imread, see cv::ImreadModes. +@param mats A vector of Mat objects holding each page, if more than one. +@param range A continuous selection of pages. +*/ +CV_EXPORTS_W bool imdecodemulti(InputArray buf, int flags, CV_OUT std::vector& mats, const cv::Range& range = Range::all()); + +/** @brief Encodes an image into a memory buffer. + +The function imencode compresses the image and stores it in the memory buffer that is resized to fit the +result. See cv::imwrite for the list of supported formats and flags description. + +@param ext File extension that defines the output format. Must include a leading period. +@param img Image to be compressed. +@param buf Output buffer resized to fit the compressed image. +@param params Format-specific parameters. See cv::imwrite and cv::ImwriteFlags. +*/ +CV_EXPORTS_W bool imencode( const String& ext, InputArray img, + CV_OUT std::vector& buf, + const std::vector& params = std::vector()); + +/** @brief Encodes array of images into a memory buffer. + +The function is analog to cv::imencode for in-memory multi-page image compression. +See cv::imwrite for the list of supported formats and flags description. + +@param ext File extension that defines the output format. Must include a leading period. +@param imgs Vector of images to be written. +@param buf Output buffer resized to fit the compressed data. +@param params Format-specific parameters. See cv::imwrite and cv::ImwriteFlags. +*/ +CV_EXPORTS_W bool imencodemulti( const String& ext, InputArrayOfArrays imgs, + CV_OUT std::vector& buf, + const std::vector& params = std::vector()); + +/** @brief Checks if the specified image file can be decoded by OpenCV. + +The function haveImageReader checks if OpenCV is capable of reading the specified file. +This can be useful for verifying support for a given image format before attempting to load an image. + +@param filename The name of the file to be checked. +@return true if an image reader for the specified file is available and the file can be opened, false otherwise. + +@note The function checks the availability of image codecs that are either built into OpenCV or dynamically loaded. +It does not check for the actual existence of the file but rather the ability to read the specified file type. +If the file cannot be opened or the format is unsupported, the function will return false. + +@sa cv::haveImageWriter, cv::imread, cv::imdecode +*/ +CV_EXPORTS_W bool haveImageReader( const String& filename ); + +/** @brief Checks if the specified image file or specified file extension can be encoded by OpenCV. + +The function haveImageWriter checks if OpenCV is capable of writing images with the specified file extension. +This can be useful for verifying support for a given image format before attempting to save an image. + +@param filename The name of the file or the file extension (e.g., ".jpg", ".png"). +It is recommended to provide the file extension rather than the full file name. +@return true if an image writer for the specified extension is available, false otherwise. + +@note The function checks the availability of image codecs that are either built into OpenCV or dynamically loaded. +It does not check for the actual existence of the file but rather the ability to write files of the given type. + +@sa cv::haveImageReader, cv::imwrite, cv::imencode +*/ +CV_EXPORTS_W bool haveImageWriter( const String& filename ); + +/** @brief To read multi-page images on demand + +The ImageCollection class provides iterator API to read multi-page images on demand. Create iterator +to the collection of the images and iterate over the collection. Decode the necessary page with operator*. + +The performance of page decoding is O(1) if collection is increment sequentially. If the user wants to access random page, +then the time Complexity is O(n) because the collection has to be reinitialized every time in order to go to the correct page. +However, the intermediate pages are not decoded during the process, so typically it's quite fast. +This is required because multi-page codecs does not support going backwards. +After decoding the one page, it is stored inside the collection cache. Hence, trying to get Mat object from already decoded page is O(1). +If you need memory, you can use .releaseCache() method to release cached index. +The space complexity is O(n) if all pages are decoded into memory. The user is able to decode and release images on demand. +*/ +class CV_EXPORTS ImageCollection { +public: + struct CV_EXPORTS iterator { + iterator(ImageCollection* col); + iterator(ImageCollection* col, int end); + Mat& operator*(); + Mat* operator->(); + iterator& operator++(); + iterator operator++(int); + friend bool operator== (const iterator& a, const iterator& b) { return a.m_curr == b.m_curr; } + friend bool operator!= (const iterator& a, const iterator& b) { return a.m_curr != b.m_curr; } + + private: + ImageCollection* m_pCollection; + int m_curr; + }; + + ImageCollection(); + ImageCollection(const String& filename, int flags); + void init(const String& img, int flags); + size_t size() const; + const Mat& at(int index); + const Mat& operator[](int index); + void releaseCache(int index); + iterator begin(); + iterator end(); + + class Impl; + Ptr getImpl(); +protected: + Ptr pImpl; +}; + +//! @} imgcodecs + +} // cv + +#endif //OPENCV_IMGCODECS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/imgcodecs/imgcodecs.hpp b/3rdParty/opencv-4.11.0/opencv2/imgcodecs/imgcodecs.hpp index a3cd232645..d2ed9f435b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgcodecs/imgcodecs.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/imgcodecs/imgcodecs.hpp @@ -1,48 +1,48 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifdef __OPENCV_BUILD -#error this is a compatibility header which should not be used inside the OpenCV library -#endif - -#include "opencv2/imgcodecs.hpp" +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/imgcodecs.hpp" diff --git a/3rdParty/opencv-4.11.0/opencv2/imgcodecs/imgcodecs_c.h b/3rdParty/opencv-4.11.0/opencv2/imgcodecs/imgcodecs_c.h index c78b3f72fa..e870a3ba24 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgcodecs/imgcodecs_c.h +++ b/3rdParty/opencv-4.11.0/opencv2/imgcodecs/imgcodecs_c.h @@ -1 +1 @@ -#error "This header with legacy C API declarations has been removed from OpenCV. Legacy constants are available from legacy/constants_c.h file." +#error "This header with legacy C API declarations has been removed from OpenCV. Legacy constants are available from legacy/constants_c.h file." diff --git a/3rdParty/opencv-4.11.0/opencv2/imgcodecs/ios.h b/3rdParty/opencv-4.11.0/opencv2/imgcodecs/ios.h index 5f17218170..2bd679a23d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgcodecs/ios.h +++ b/3rdParty/opencv-4.11.0/opencv2/imgcodecs/ios.h @@ -1,59 +1,59 @@ - -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#import -#import -#import -#import -#include "opencv2/core.hpp" - -//! @addtogroup imgcodecs_ios -//! @{ - -CV_EXPORTS CGImageRef MatToCGImage(const cv::Mat& image) CF_RETURNS_RETAINED; -CV_EXPORTS void CGImageToMat(const CGImageRef image, cv::Mat& m, bool alphaExist = false); -CV_EXPORTS UIImage* MatToUIImage(const cv::Mat& image); -CV_EXPORTS void UIImageToMat(const UIImage* image, - cv::Mat& m, bool alphaExist = false); - -//! @} + +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#import +#import +#import +#import +#include "opencv2/core.hpp" + +//! @addtogroup imgcodecs_ios +//! @{ + +CV_EXPORTS CGImageRef MatToCGImage(const cv::Mat& image) CF_RETURNS_RETAINED; +CV_EXPORTS void CGImageToMat(const CGImageRef image, cv::Mat& m, bool alphaExist = false); +CV_EXPORTS UIImage* MatToUIImage(const cv::Mat& image); +CV_EXPORTS void UIImageToMat(const UIImage* image, + cv::Mat& m, bool alphaExist = false); + +//! @} diff --git a/3rdParty/opencv-4.11.0/opencv2/imgcodecs/legacy/constants_c.h b/3rdParty/opencv-4.11.0/opencv2/imgcodecs/legacy/constants_c.h index de7be4f74d..f38c928c9d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgcodecs/legacy/constants_c.h +++ b/3rdParty/opencv-4.11.0/opencv2/imgcodecs/legacy/constants_c.h @@ -1,54 +1,54 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_IMGCODECS_LEGACY_CONSTANTS_H -#define OPENCV_IMGCODECS_LEGACY_CONSTANTS_H - -/* duplicate of "ImreadModes" enumeration for better compatibility with OpenCV 3.x */ -enum -{ -/* 8bit, color or not */ - CV_LOAD_IMAGE_UNCHANGED =-1, -/* 8bit, gray */ - CV_LOAD_IMAGE_GRAYSCALE =0, -/* ?, color */ - CV_LOAD_IMAGE_COLOR =1, -/* any depth, ? */ - CV_LOAD_IMAGE_ANYDEPTH =2, -/* ?, any color */ - CV_LOAD_IMAGE_ANYCOLOR =4, -/* ?, no rotate */ - CV_LOAD_IMAGE_IGNORE_ORIENTATION =128 -}; - -/* duplicate of "ImwriteFlags" enumeration for better compatibility with OpenCV 3.x */ -enum -{ - CV_IMWRITE_JPEG_QUALITY =1, - CV_IMWRITE_JPEG_PROGRESSIVE =2, - CV_IMWRITE_JPEG_OPTIMIZE =3, - CV_IMWRITE_JPEG_RST_INTERVAL =4, - CV_IMWRITE_JPEG_LUMA_QUALITY =5, - CV_IMWRITE_JPEG_CHROMA_QUALITY =6, - CV_IMWRITE_PNG_COMPRESSION =16, - CV_IMWRITE_PNG_STRATEGY =17, - CV_IMWRITE_PNG_BILEVEL =18, - CV_IMWRITE_PNG_STRATEGY_DEFAULT =0, - CV_IMWRITE_PNG_STRATEGY_FILTERED =1, - CV_IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY =2, - CV_IMWRITE_PNG_STRATEGY_RLE =3, - CV_IMWRITE_PNG_STRATEGY_FIXED =4, - CV_IMWRITE_PXM_BINARY =32, - CV_IMWRITE_EXR_TYPE = 48, - CV_IMWRITE_WEBP_QUALITY =64, - CV_IMWRITE_PAM_TUPLETYPE = 128, - CV_IMWRITE_PAM_FORMAT_NULL = 0, - CV_IMWRITE_PAM_FORMAT_BLACKANDWHITE = 1, - CV_IMWRITE_PAM_FORMAT_GRAYSCALE = 2, - CV_IMWRITE_PAM_FORMAT_GRAYSCALE_ALPHA = 3, - CV_IMWRITE_PAM_FORMAT_RGB = 4, - CV_IMWRITE_PAM_FORMAT_RGB_ALPHA = 5, -}; - -#endif // OPENCV_IMGCODECS_LEGACY_CONSTANTS_H +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_IMGCODECS_LEGACY_CONSTANTS_H +#define OPENCV_IMGCODECS_LEGACY_CONSTANTS_H + +/* duplicate of "ImreadModes" enumeration for better compatibility with OpenCV 3.x */ +enum +{ +/* 8bit, color or not */ + CV_LOAD_IMAGE_UNCHANGED =-1, +/* 8bit, gray */ + CV_LOAD_IMAGE_GRAYSCALE =0, +/* ?, color */ + CV_LOAD_IMAGE_COLOR =1, +/* any depth, ? */ + CV_LOAD_IMAGE_ANYDEPTH =2, +/* ?, any color */ + CV_LOAD_IMAGE_ANYCOLOR =4, +/* ?, no rotate */ + CV_LOAD_IMAGE_IGNORE_ORIENTATION =128 +}; + +/* duplicate of "ImwriteFlags" enumeration for better compatibility with OpenCV 3.x */ +enum +{ + CV_IMWRITE_JPEG_QUALITY =1, + CV_IMWRITE_JPEG_PROGRESSIVE =2, + CV_IMWRITE_JPEG_OPTIMIZE =3, + CV_IMWRITE_JPEG_RST_INTERVAL =4, + CV_IMWRITE_JPEG_LUMA_QUALITY =5, + CV_IMWRITE_JPEG_CHROMA_QUALITY =6, + CV_IMWRITE_PNG_COMPRESSION =16, + CV_IMWRITE_PNG_STRATEGY =17, + CV_IMWRITE_PNG_BILEVEL =18, + CV_IMWRITE_PNG_STRATEGY_DEFAULT =0, + CV_IMWRITE_PNG_STRATEGY_FILTERED =1, + CV_IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY =2, + CV_IMWRITE_PNG_STRATEGY_RLE =3, + CV_IMWRITE_PNG_STRATEGY_FIXED =4, + CV_IMWRITE_PXM_BINARY =32, + CV_IMWRITE_EXR_TYPE = 48, + CV_IMWRITE_WEBP_QUALITY =64, + CV_IMWRITE_PAM_TUPLETYPE = 128, + CV_IMWRITE_PAM_FORMAT_NULL = 0, + CV_IMWRITE_PAM_FORMAT_BLACKANDWHITE = 1, + CV_IMWRITE_PAM_FORMAT_GRAYSCALE = 2, + CV_IMWRITE_PAM_FORMAT_GRAYSCALE_ALPHA = 3, + CV_IMWRITE_PAM_FORMAT_RGB = 4, + CV_IMWRITE_PAM_FORMAT_RGB_ALPHA = 5, +}; + +#endif // OPENCV_IMGCODECS_LEGACY_CONSTANTS_H diff --git a/3rdParty/opencv-4.11.0/opencv2/imgcodecs/macosx.h b/3rdParty/opencv-4.11.0/opencv2/imgcodecs/macosx.h index cfb0770700..5bf4cfb2e3 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgcodecs/macosx.h +++ b/3rdParty/opencv-4.11.0/opencv2/imgcodecs/macosx.h @@ -1,20 +1,20 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#if !defined(__APPLE__) || !defined(__MACH__) -#error This header should be used in macOS ObjC/Swift projects. -#endif - -#import -#include "opencv2/core.hpp" - -//! @addtogroup imgcodecs_macosx -//! @{ - -CV_EXPORTS CGImageRef MatToCGImage(const cv::Mat& image) CF_RETURNS_RETAINED; -CV_EXPORTS void CGImageToMat(const CGImageRef image, cv::Mat& m, bool alphaExist = false); -CV_EXPORTS NSImage* MatToNSImage(const cv::Mat& image); -CV_EXPORTS void NSImageToMat(const NSImage* image, cv::Mat& m, bool alphaExist = false); - -//! @} +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#if !defined(__APPLE__) || !defined(__MACH__) +#error This header should be used in macOS ObjC/Swift projects. +#endif + +#import +#include "opencv2/core.hpp" + +//! @addtogroup imgcodecs_macosx +//! @{ + +CV_EXPORTS CGImageRef MatToCGImage(const cv::Mat& image) CF_RETURNS_RETAINED; +CV_EXPORTS void CGImageToMat(const CGImageRef image, cv::Mat& m, bool alphaExist = false); +CV_EXPORTS NSImage* MatToNSImage(const cv::Mat& image); +CV_EXPORTS void NSImageToMat(const NSImage* image, cv::Mat& m, bool alphaExist = false); + +//! @} diff --git a/3rdParty/opencv-4.11.0/opencv2/imgproc.hpp b/3rdParty/opencv-4.11.0/opencv2/imgproc.hpp index 3daa6d1a0d..4f8fe77d26 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgproc.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/imgproc.hpp @@ -1,5101 +1,5101 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_IMGPROC_HPP -#define OPENCV_IMGPROC_HPP - -#include "opencv2/core.hpp" - -/** -@defgroup imgproc Image Processing - -This module offers a comprehensive suite of image processing functions, enabling tasks such as those listed above. - -@{ - @defgroup imgproc_filter Image Filtering - - Functions and classes described in this section are used to perform various linear or non-linear - filtering operations on 2D images (represented as Mat's). It means that for each pixel location - \f$(x,y)\f$ in the source image (normally, rectangular), its neighborhood is considered and used to - compute the response. In case of a linear filter, it is a weighted sum of pixel values. In case of - morphological operations, it is the minimum or maximum values, and so on. The computed response is - stored in the destination image at the same location \f$(x,y)\f$. It means that the output image - will be of the same size as the input image. Normally, the functions support multi-channel arrays, - in which case every channel is processed independently. Therefore, the output image will also have - the same number of channels as the input one. - - Another common feature of the functions and classes described in this section is that, unlike - simple arithmetic functions, they need to extrapolate values of some non-existing pixels. For - example, if you want to smooth an image using a Gaussian \f$3 \times 3\f$ filter, then, when - processing the left-most pixels in each row, you need pixels to the left of them, that is, outside - of the image. You can let these pixels be the same as the left-most image pixels ("replicated - border" extrapolation method), or assume that all the non-existing pixels are zeros ("constant - border" extrapolation method), and so on. OpenCV enables you to specify the extrapolation method. - For details, see #BorderTypes - - @anchor filter_depths - ### Depth combinations - Input depth (src.depth()) | Output depth (ddepth) - --------------------------|---------------------- - CV_8U | -1/CV_16S/CV_32F/CV_64F - CV_16U/CV_16S | -1/CV_32F/CV_64F - CV_32F | -1/CV_32F - CV_64F | -1/CV_64F - - @note when ddepth=-1, the output image will have the same depth as the source. - - @note if you need double floating-point accuracy and using single floating-point input data - (CV_32F input and CV_64F output depth combination), you can use @ref Mat.convertTo to convert - the input data to the desired precision. - - @defgroup imgproc_transform Geometric Image Transformations - - The functions in this section perform various geometrical transformations of 2D images. They do not - change the image content but deform the pixel grid and map this deformed grid to the destination - image. In fact, to avoid sampling artifacts, the mapping is done in the reverse order, from - destination to the source. That is, for each pixel \f$(x, y)\f$ of the destination image, the - functions compute coordinates of the corresponding "donor" pixel in the source image and copy the - pixel value: - - \f[\texttt{dst} (x,y)= \texttt{src} (f_x(x,y), f_y(x,y))\f] - - In case when you specify the forward mapping \f$\left: \texttt{src} \rightarrow - \texttt{dst}\f$, the OpenCV functions first compute the corresponding inverse mapping - \f$\left: \texttt{dst} \rightarrow \texttt{src}\f$ and then use the above formula. - - The actual implementations of the geometrical transformations, from the most generic remap and to - the simplest and the fastest resize, need to solve two main problems with the above formula: - - - Extrapolation of non-existing pixels. Similarly to the filtering functions described in the - previous section, for some \f$(x,y)\f$, either one of \f$f_x(x,y)\f$, or \f$f_y(x,y)\f$, or both - of them may fall outside of the image. In this case, an extrapolation method needs to be used. - OpenCV provides the same selection of extrapolation methods as in the filtering functions. In - addition, it provides the method #BORDER_TRANSPARENT. This means that the corresponding pixels in - the destination image will not be modified at all. - - - Interpolation of pixel values. Usually \f$f_x(x,y)\f$ and \f$f_y(x,y)\f$ are floating-point - numbers. This means that \f$\left\f$ can be either an affine or perspective - transformation, or radial lens distortion correction, and so on. So, a pixel value at fractional - coordinates needs to be retrieved. In the simplest case, the coordinates can be just rounded to the - nearest integer coordinates and the corresponding pixel can be used. This is called a - nearest-neighbor interpolation. However, a better result can be achieved by using more - sophisticated [interpolation methods](http://en.wikipedia.org/wiki/Multivariate_interpolation) , - where a polynomial function is fit into some neighborhood of the computed pixel \f$(f_x(x,y), - f_y(x,y))\f$, and then the value of the polynomial at \f$(f_x(x,y), f_y(x,y))\f$ is taken as the - interpolated pixel value. In OpenCV, you can choose between several interpolation methods. See - #resize for details. - - @note The geometrical transformations do not work with `CV_8S` or `CV_32S` images. - - @defgroup imgproc_misc Miscellaneous Image Transformations - @defgroup imgproc_draw Drawing Functions - - Drawing functions work with matrices/images of arbitrary depth. The boundaries of the shapes can be - rendered with antialiasing (implemented only for 8-bit images for now). All the functions include - the parameter color that uses an RGB value (that may be constructed with the Scalar constructor ) - for color images and brightness for grayscale images. For color images, the channel ordering is - normally *Blue, Green, Red*. This is what imshow, imread, and imwrite expect. So, if you form a - color using the Scalar constructor, it should look like: - - \f[\texttt{Scalar} (blue \_ component, green \_ component, red \_ component[, alpha \_ component])\f] - - If you are using your own image rendering and I/O functions, you can use any channel ordering. The - drawing functions process each channel independently and do not depend on the channel order or even - on the used color space. The whole image can be converted from BGR to RGB or to a different color - space using cvtColor . - - If a drawn figure is partially or completely outside the image, the drawing functions clip it. Also, - many drawing functions can handle pixel coordinates specified with sub-pixel accuracy. This means - that the coordinates can be passed as fixed-point numbers encoded as integers. The number of - fractional bits is specified by the shift parameter and the real point coordinates are calculated as - \f$\texttt{Point}(x,y)\rightarrow\texttt{Point2f}(x*2^{-shift},y*2^{-shift})\f$ . This feature is - especially effective when rendering antialiased shapes. - - @note The functions do not support alpha-transparency when the target image is 4-channel. In this - case, the color[3] is simply copied to the repainted pixels. Thus, if you want to paint - semi-transparent shapes, you can paint them in a separate buffer and then blend it with the main - image. - - @defgroup imgproc_color_conversions Color Space Conversions - @defgroup imgproc_colormap ColorMaps in OpenCV - - The human perception isn't built for observing fine changes in grayscale images. Human eyes are more - sensitive to observing changes between colors, so you often need to recolor your grayscale images to - get a clue about them. OpenCV now comes with various colormaps to enhance the visualization in your - computer vision application. - - In OpenCV you only need applyColorMap to apply a colormap on a given image. The following sample - code reads the path to an image from command line, applies a Jet colormap on it and shows the - result: - - @include snippets/imgproc_applyColorMap.cpp - - @see #ColormapTypes - - @defgroup imgproc_subdiv2d Planar Subdivision - - The Subdiv2D class described in this section is used to perform various planar subdivision on - a set of 2D points (represented as vector of Point2f). OpenCV subdivides a plane into triangles - using the Delaunay's algorithm, which corresponds to the dual graph of the Voronoi diagram. - In the figure below, the Delaunay's triangulation is marked with black lines and the Voronoi - diagram with red lines. - - ![Delaunay triangulation (black) and Voronoi (red)](pics/delaunay_voronoi.png) - - The subdivisions can be used for the 3D piece-wise transformation of a plane, morphing, fast - location of points on the plane, building special graphs (such as NNG,RNG), and so forth. - - @defgroup imgproc_hist Histograms - @defgroup imgproc_shape Structural Analysis and Shape Descriptors - @defgroup imgproc_motion Motion Analysis and Object Tracking - @defgroup imgproc_feature Feature Detection - @defgroup imgproc_object Object Detection - @defgroup imgproc_segmentation Image Segmentation - @defgroup imgproc_hal Hardware Acceleration Layer - @{ - @defgroup imgproc_hal_functions Functions - @defgroup imgproc_hal_interface Interface - @} - @} -*/ - -namespace cv -{ - -/** @addtogroup imgproc -@{ -*/ - -//! @addtogroup imgproc_filter -//! @{ - -enum SpecialFilter { - FILTER_SCHARR = -1 -}; - -//! type of morphological operation -enum MorphTypes{ - MORPH_ERODE = 0, //!< see #erode - MORPH_DILATE = 1, //!< see #dilate - MORPH_OPEN = 2, //!< an opening operation - //!< \f[\texttt{dst} = \mathrm{open} ( \texttt{src} , \texttt{element} )= \mathrm{dilate} ( \mathrm{erode} ( \texttt{src} , \texttt{element} ))\f] - MORPH_CLOSE = 3, //!< a closing operation - //!< \f[\texttt{dst} = \mathrm{close} ( \texttt{src} , \texttt{element} )= \mathrm{erode} ( \mathrm{dilate} ( \texttt{src} , \texttt{element} ))\f] - MORPH_GRADIENT = 4, //!< a morphological gradient - //!< \f[\texttt{dst} = \mathrm{morph\_grad} ( \texttt{src} , \texttt{element} )= \mathrm{dilate} ( \texttt{src} , \texttt{element} )- \mathrm{erode} ( \texttt{src} , \texttt{element} )\f] - MORPH_TOPHAT = 5, //!< "top hat" - //!< \f[\texttt{dst} = \mathrm{tophat} ( \texttt{src} , \texttt{element} )= \texttt{src} - \mathrm{open} ( \texttt{src} , \texttt{element} )\f] - MORPH_BLACKHAT = 6, //!< "black hat" - //!< \f[\texttt{dst} = \mathrm{blackhat} ( \texttt{src} , \texttt{element} )= \mathrm{close} ( \texttt{src} , \texttt{element} )- \texttt{src}\f] - MORPH_HITMISS = 7 //!< "hit or miss" - //!< .- Only supported for CV_8UC1 binary images. A tutorial can be found in the documentation -}; - -//! shape of the structuring element -enum MorphShapes { - MORPH_RECT = 0, //!< a rectangular structuring element: \f[E_{ij}=1\f] - MORPH_CROSS = 1, //!< a cross-shaped structuring element: - //!< \f[E_{ij} = \begin{cases} 1 & \texttt{if } {i=\texttt{anchor.y } {or } {j=\texttt{anchor.x}}} \\0 & \texttt{otherwise} \end{cases}\f] - MORPH_ELLIPSE = 2 //!< an elliptic structuring element, that is, a filled ellipse inscribed - //!< into the rectangle Rect(0, 0, esize.width, esize.height) -}; - -//! @} imgproc_filter - -//! @addtogroup imgproc_transform -//! @{ - -//! interpolation algorithm -enum InterpolationFlags{ - /** nearest neighbor interpolation */ - INTER_NEAREST = 0, - /** bilinear interpolation */ - INTER_LINEAR = 1, - /** bicubic interpolation */ - INTER_CUBIC = 2, - /** resampling using pixel area relation. It may be a preferred method for image decimation, as - it gives moire'-free results. But when the image is zoomed, it is similar to the INTER_NEAREST - method. */ - INTER_AREA = 3, - /** Lanczos interpolation over 8x8 neighborhood */ - INTER_LANCZOS4 = 4, - /** Bit exact bilinear interpolation */ - INTER_LINEAR_EXACT = 5, - /** Bit exact nearest neighbor interpolation. This will produce same results as - the nearest neighbor method in PIL, scikit-image or Matlab. */ - INTER_NEAREST_EXACT = 6, - /** mask for interpolation codes */ - INTER_MAX = 7, - /** flag, fills all of the destination image pixels. If some of them correspond to outliers in the - source image, they are set to zero */ - WARP_FILL_OUTLIERS = 8, - /** flag, inverse transformation - - For example, #linearPolar or #logPolar transforms: - - flag is __not__ set: \f$dst( \rho , \phi ) = src(x,y)\f$ - - flag is set: \f$dst(x,y) = src( \rho , \phi )\f$ - */ - WARP_INVERSE_MAP = 16, - WARP_RELATIVE_MAP = 32 -}; - -/** \brief Specify the polar mapping mode -@sa warpPolar -*/ -enum WarpPolarMode -{ - WARP_POLAR_LINEAR = 0, ///< Remaps an image to/from polar space. - WARP_POLAR_LOG = 256 ///< Remaps an image to/from semilog-polar space. -}; - -enum InterpolationMasks { - INTER_BITS = 5, - INTER_BITS2 = INTER_BITS * 2, - INTER_TAB_SIZE = 1 << INTER_BITS, - INTER_TAB_SIZE2 = INTER_TAB_SIZE * INTER_TAB_SIZE - }; - -//! @} imgproc_transform - -//! @addtogroup imgproc_misc -//! @{ - -//! Distance types for Distance Transform and M-estimators -//! @see distanceTransform, fitLine -enum DistanceTypes { - DIST_USER = -1, //!< User defined distance - DIST_L1 = 1, //!< distance = |x1-x2| + |y1-y2| - DIST_L2 = 2, //!< the simple euclidean distance - DIST_C = 3, //!< distance = max(|x1-x2|,|y1-y2|) - DIST_L12 = 4, //!< L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1)) - DIST_FAIR = 5, //!< distance = c^2(|x|/c-log(1+|x|/c)), c = 1.3998 - DIST_WELSCH = 6, //!< distance = c^2/2(1-exp(-(x/c)^2)), c = 2.9846 - DIST_HUBER = 7 //!< distance = |x| \texttt{thresh}\)}{0}{otherwise}\f] - THRESH_BINARY_INV = 1, //!< \f[\texttt{dst} (x,y) = \fork{0}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{maxval}}{otherwise}\f] - THRESH_TRUNC = 2, //!< \f[\texttt{dst} (x,y) = \fork{\texttt{threshold}}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{src}(x,y)}{otherwise}\f] - THRESH_TOZERO = 3, //!< \f[\texttt{dst} (x,y) = \fork{\texttt{src}(x,y)}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{0}{otherwise}\f] - THRESH_TOZERO_INV = 4, //!< \f[\texttt{dst} (x,y) = \fork{0}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{src}(x,y)}{otherwise}\f] - THRESH_MASK = 7, - THRESH_OTSU = 8, //!< flag, use Otsu algorithm to choose the optimal threshold value - THRESH_TRIANGLE = 16 //!< flag, use Triangle algorithm to choose the optimal threshold value -}; - -//! adaptive threshold algorithm -//! @see adaptiveThreshold -enum AdaptiveThresholdTypes { - /** the threshold value \f$T(x,y)\f$ is a mean of the \f$\texttt{blockSize} \times - \texttt{blockSize}\f$ neighborhood of \f$(x, y)\f$ minus C */ - ADAPTIVE_THRESH_MEAN_C = 0, - /** the threshold value \f$T(x, y)\f$ is a weighted sum (cross-correlation with a Gaussian - window) of the \f$\texttt{blockSize} \times \texttt{blockSize}\f$ neighborhood of \f$(x, y)\f$ - minus C . The default sigma (standard deviation) is used for the specified blockSize . See - #getGaussianKernel*/ - ADAPTIVE_THRESH_GAUSSIAN_C = 1 -}; - -//! class of the pixel in GrabCut algorithm -enum GrabCutClasses { - GC_BGD = 0, //!< an obvious background pixels - GC_FGD = 1, //!< an obvious foreground (object) pixel - GC_PR_BGD = 2, //!< a possible background pixel - GC_PR_FGD = 3 //!< a possible foreground pixel -}; - -//! GrabCut algorithm flags -enum GrabCutModes { - /** The function initializes the state and the mask using the provided rectangle. After that it - runs iterCount iterations of the algorithm. */ - GC_INIT_WITH_RECT = 0, - /** The function initializes the state using the provided mask. Note that GC_INIT_WITH_RECT - and GC_INIT_WITH_MASK can be combined. Then, all the pixels outside of the ROI are - automatically initialized with GC_BGD .*/ - GC_INIT_WITH_MASK = 1, - /** The value means that the algorithm should just resume. */ - GC_EVAL = 2, - /** The value means that the algorithm should just run the grabCut algorithm (a single iteration) with the fixed model */ - GC_EVAL_FREEZE_MODEL = 3 -}; - -//! distanceTransform algorithm flags -enum DistanceTransformLabelTypes { - /** each connected component of zeros in src (as well as all the non-zero pixels closest to the - connected component) will be assigned the same label */ - DIST_LABEL_CCOMP = 0, - /** each zero pixel (and all the non-zero pixels closest to it) gets its own label. */ - DIST_LABEL_PIXEL = 1 -}; - -//! floodfill algorithm flags -enum FloodFillFlags { - /** If set, the difference between the current pixel and seed pixel is considered. Otherwise, - the difference between neighbor pixels is considered (that is, the range is floating). */ - FLOODFILL_FIXED_RANGE = 1 << 16, - /** If set, the function does not change the image ( newVal is ignored), and only fills the - mask with the value specified in bits 8-16 of flags as described above. This option only make - sense in function variants that have the mask parameter. */ - FLOODFILL_MASK_ONLY = 1 << 17 -}; - -//! @} imgproc_misc - -//! @addtogroup imgproc_shape -//! @{ - -//! connected components statistics -enum ConnectedComponentsTypes { - CC_STAT_LEFT = 0, //!< The leftmost (x) coordinate which is the inclusive start of the bounding - //!< box in the horizontal direction. - CC_STAT_TOP = 1, //!< The topmost (y) coordinate which is the inclusive start of the bounding - //!< box in the vertical direction. - CC_STAT_WIDTH = 2, //!< The horizontal size of the bounding box - CC_STAT_HEIGHT = 3, //!< The vertical size of the bounding box - CC_STAT_AREA = 4, //!< The total area (in pixels) of the connected component -#ifndef CV_DOXYGEN - CC_STAT_MAX = 5 //!< Max enumeration value. Used internally only for memory allocation -#endif -}; - -//! connected components algorithm -enum ConnectedComponentsAlgorithmsTypes { - CCL_DEFAULT = -1, //!< Spaghetti @cite Bolelli2019 algorithm for 8-way connectivity, Spaghetti4C @cite Bolelli2021 algorithm for 4-way connectivity. - CCL_WU = 0, //!< SAUF @cite Wu2009 algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity. The parallel implementation described in @cite Bolelli2017 is available for SAUF. - CCL_GRANA = 1, //!< BBDT @cite Grana2010 algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity. The parallel implementation described in @cite Bolelli2017 is available for both BBDT and SAUF. - CCL_BOLELLI = 2, //!< Spaghetti @cite Bolelli2019 algorithm for 8-way connectivity, Spaghetti4C @cite Bolelli2021 algorithm for 4-way connectivity. The parallel implementation described in @cite Bolelli2017 is available for both Spaghetti and Spaghetti4C. - CCL_SAUF = 3, //!< Same as CCL_WU. It is preferable to use the flag with the name of the algorithm (CCL_SAUF) rather than the one with the name of the first author (CCL_WU). - CCL_BBDT = 4, //!< Same as CCL_GRANA. It is preferable to use the flag with the name of the algorithm (CCL_BBDT) rather than the one with the name of the first author (CCL_GRANA). - CCL_SPAGHETTI = 5, //!< Same as CCL_BOLELLI. It is preferable to use the flag with the name of the algorithm (CCL_SPAGHETTI) rather than the one with the name of the first author (CCL_BOLELLI). -}; - -//! mode of the contour retrieval algorithm -enum RetrievalModes { - /** retrieves only the extreme outer contours. It sets `hierarchy[i][2]=hierarchy[i][3]=-1` for - all the contours. */ - RETR_EXTERNAL = 0, - /** retrieves all of the contours without establishing any hierarchical relationships. */ - RETR_LIST = 1, - /** retrieves all of the contours and organizes them into a two-level hierarchy. At the top - level, there are external boundaries of the components. At the second level, there are - boundaries of the holes. If there is another contour inside a hole of a connected component, it - is still put at the top level. */ - RETR_CCOMP = 2, - /** retrieves all of the contours and reconstructs a full hierarchy of nested contours.*/ - RETR_TREE = 3, - RETR_FLOODFILL = 4 //!< -}; - -//! the contour approximation algorithm -enum ContourApproximationModes { - /** stores absolutely all the contour points. That is, any 2 subsequent points (x1,y1) and - (x2,y2) of the contour will be either horizontal, vertical or diagonal neighbors, that is, - max(abs(x1-x2),abs(y2-y1))==1. */ - CHAIN_APPROX_NONE = 1, - /** compresses horizontal, vertical, and diagonal segments and leaves only their end points. - For example, an up-right rectangular contour is encoded with 4 points. */ - CHAIN_APPROX_SIMPLE = 2, - /** applies one of the flavors of the Teh-Chin chain approximation algorithm @cite TehChin89 */ - CHAIN_APPROX_TC89_L1 = 3, - /** applies one of the flavors of the Teh-Chin chain approximation algorithm @cite TehChin89 */ - CHAIN_APPROX_TC89_KCOS = 4 -}; - -/** @brief Shape matching methods - -\f$A\f$ denotes object1,\f$B\f$ denotes object2 - -\f$\begin{array}{l} m^A_i = \mathrm{sign} (h^A_i) \cdot \log{h^A_i} \\ m^B_i = \mathrm{sign} (h^B_i) \cdot \log{h^B_i} \end{array}\f$ - -and \f$h^A_i, h^B_i\f$ are the Hu moments of \f$A\f$ and \f$B\f$ , respectively. -*/ -enum ShapeMatchModes { - CONTOURS_MATCH_I1 =1, //!< \f[I_1(A,B) = \sum _{i=1...7} \left | \frac{1}{m^A_i} - \frac{1}{m^B_i} \right |\f] - CONTOURS_MATCH_I2 =2, //!< \f[I_2(A,B) = \sum _{i=1...7} \left | m^A_i - m^B_i \right |\f] - CONTOURS_MATCH_I3 =3 //!< \f[I_3(A,B) = \max _{i=1...7} \frac{ \left| m^A_i - m^B_i \right| }{ \left| m^A_i \right| }\f] -}; - -//! @} imgproc_shape - -//! @addtogroup imgproc_feature -//! @{ - -//! Variants of a Hough transform -enum HoughModes { - - /** classical or standard Hough transform. Every line is represented by two floating-point - numbers \f$(\rho, \theta)\f$ , where \f$\rho\f$ is a distance between (0,0) point and the line, - and \f$\theta\f$ is the angle between x-axis and the normal to the line. Thus, the matrix must - be (the created sequence will be) of CV_32FC2 type */ - HOUGH_STANDARD = 0, - /** probabilistic Hough transform (more efficient in case if the picture contains a few long - linear segments). It returns line segments rather than the whole line. Each segment is - represented by starting and ending points, and the matrix must be (the created sequence will - be) of the CV_32SC4 type. */ - HOUGH_PROBABILISTIC = 1, - /** multi-scale variant of the classical Hough transform. The lines are encoded the same way as - HOUGH_STANDARD. */ - HOUGH_MULTI_SCALE = 2, - HOUGH_GRADIENT = 3, //!< basically *21HT*, described in @cite Yuen90 - HOUGH_GRADIENT_ALT = 4, //!< variation of HOUGH_GRADIENT to get better accuracy -}; - -//! Variants of Line Segment %Detector -enum LineSegmentDetectorModes { - LSD_REFINE_NONE = 0, //!< No refinement applied - LSD_REFINE_STD = 1, //!< Standard refinement is applied. E.g. breaking arches into smaller straighter line approximations. - LSD_REFINE_ADV = 2 //!< Advanced refinement. Number of false alarms is calculated, lines are - //!< refined through increase of precision, decrement in size, etc. -}; - -//! @} imgproc_feature - -/** Histogram comparison methods - @ingroup imgproc_hist -*/ -enum HistCompMethods { - /** Correlation - \f[d(H_1,H_2) = \frac{\sum_I (H_1(I) - \bar{H_1}) (H_2(I) - \bar{H_2})}{\sqrt{\sum_I(H_1(I) - \bar{H_1})^2 \sum_I(H_2(I) - \bar{H_2})^2}}\f] - where - \f[\bar{H_k} = \frac{1}{N} \sum _J H_k(J)\f] - and \f$N\f$ is a total number of histogram bins. */ - HISTCMP_CORREL = 0, - /** Chi-Square - \f[d(H_1,H_2) = \sum _I \frac{\left(H_1(I)-H_2(I)\right)^2}{H_1(I)}\f] */ - HISTCMP_CHISQR = 1, - /** Intersection - \f[d(H_1,H_2) = \sum _I \min (H_1(I), H_2(I))\f] */ - HISTCMP_INTERSECT = 2, - /** Bhattacharyya distance - (In fact, OpenCV computes Hellinger distance, which is related to Bhattacharyya coefficient.) - \f[d(H_1,H_2) = \sqrt{1 - \frac{1}{\sqrt{\bar{H_1} \bar{H_2} N^2}} \sum_I \sqrt{H_1(I) \cdot H_2(I)}}\f] */ - HISTCMP_BHATTACHARYYA = 3, - HISTCMP_HELLINGER = HISTCMP_BHATTACHARYYA, //!< Synonym for HISTCMP_BHATTACHARYYA - /** Alternative Chi-Square - \f[d(H_1,H_2) = 2 * \sum _I \frac{\left(H_1(I)-H_2(I)\right)^2}{H_1(I)+H_2(I)}\f] - This alternative formula is regularly used for texture comparison. See e.g. @cite Puzicha1997 */ - HISTCMP_CHISQR_ALT = 4, - /** Kullback-Leibler divergence - \f[d(H_1,H_2) = \sum _I H_1(I) \log \left(\frac{H_1(I)}{H_2(I)}\right)\f] */ - HISTCMP_KL_DIV = 5 -}; - -/** the color conversion codes -@see @ref imgproc_color_conversions -@ingroup imgproc_color_conversions - */ -enum ColorConversionCodes { - COLOR_BGR2BGRA = 0, //!< add alpha channel to RGB or BGR image - COLOR_RGB2RGBA = COLOR_BGR2BGRA, - - COLOR_BGRA2BGR = 1, //!< remove alpha channel from RGB or BGR image - COLOR_RGBA2RGB = COLOR_BGRA2BGR, - - COLOR_BGR2RGBA = 2, //!< convert between RGB and BGR color spaces (with or without alpha channel) - COLOR_RGB2BGRA = COLOR_BGR2RGBA, - - COLOR_RGBA2BGR = 3, - COLOR_BGRA2RGB = COLOR_RGBA2BGR, - - COLOR_BGR2RGB = 4, - COLOR_RGB2BGR = COLOR_BGR2RGB, - - COLOR_BGRA2RGBA = 5, - COLOR_RGBA2BGRA = COLOR_BGRA2RGBA, - - COLOR_BGR2GRAY = 6, //!< convert between RGB/BGR and grayscale, @ref color_convert_rgb_gray "color conversions" - COLOR_RGB2GRAY = 7, - COLOR_GRAY2BGR = 8, - COLOR_GRAY2RGB = COLOR_GRAY2BGR, - COLOR_GRAY2BGRA = 9, - COLOR_GRAY2RGBA = COLOR_GRAY2BGRA, - COLOR_BGRA2GRAY = 10, - COLOR_RGBA2GRAY = 11, - - COLOR_BGR2BGR565 = 12, //!< convert between RGB/BGR and BGR565 (16-bit images) - COLOR_RGB2BGR565 = 13, - COLOR_BGR5652BGR = 14, - COLOR_BGR5652RGB = 15, - COLOR_BGRA2BGR565 = 16, - COLOR_RGBA2BGR565 = 17, - COLOR_BGR5652BGRA = 18, - COLOR_BGR5652RGBA = 19, - - COLOR_GRAY2BGR565 = 20, //!< convert between grayscale to BGR565 (16-bit images) - COLOR_BGR5652GRAY = 21, - - COLOR_BGR2BGR555 = 22, //!< convert between RGB/BGR and BGR555 (16-bit images) - COLOR_RGB2BGR555 = 23, - COLOR_BGR5552BGR = 24, - COLOR_BGR5552RGB = 25, - COLOR_BGRA2BGR555 = 26, - COLOR_RGBA2BGR555 = 27, - COLOR_BGR5552BGRA = 28, - COLOR_BGR5552RGBA = 29, - - COLOR_GRAY2BGR555 = 30, //!< convert between grayscale and BGR555 (16-bit images) - COLOR_BGR5552GRAY = 31, - - COLOR_BGR2XYZ = 32, //!< convert RGB/BGR to CIE XYZ, @ref color_convert_rgb_xyz "color conversions" - COLOR_RGB2XYZ = 33, - COLOR_XYZ2BGR = 34, - COLOR_XYZ2RGB = 35, - - COLOR_BGR2YCrCb = 36, //!< convert RGB/BGR to luma-chroma (aka YCC), @ref color_convert_rgb_ycrcb "color conversions" - COLOR_RGB2YCrCb = 37, - COLOR_YCrCb2BGR = 38, - COLOR_YCrCb2RGB = 39, - - COLOR_BGR2HSV = 40, //!< convert RGB/BGR to HSV (hue saturation value) with H range 0..180 if 8 bit image, @ref color_convert_rgb_hsv "color conversions" - COLOR_RGB2HSV = 41, - - COLOR_BGR2Lab = 44, //!< convert RGB/BGR to CIE Lab, @ref color_convert_rgb_lab "color conversions" - COLOR_RGB2Lab = 45, - - COLOR_BGR2Luv = 50, //!< convert RGB/BGR to CIE Luv, @ref color_convert_rgb_luv "color conversions" - COLOR_RGB2Luv = 51, - COLOR_BGR2HLS = 52, //!< convert RGB/BGR to HLS (hue lightness saturation) with H range 0..180 if 8 bit image, @ref color_convert_rgb_hls "color conversions" - COLOR_RGB2HLS = 53, - - COLOR_HSV2BGR = 54, //!< backward conversions HSV to RGB/BGR with H range 0..180 if 8 bit image - COLOR_HSV2RGB = 55, - - COLOR_Lab2BGR = 56, - COLOR_Lab2RGB = 57, - COLOR_Luv2BGR = 58, - COLOR_Luv2RGB = 59, - COLOR_HLS2BGR = 60, //!< backward conversions HLS to RGB/BGR with H range 0..180 if 8 bit image - COLOR_HLS2RGB = 61, - - COLOR_BGR2HSV_FULL = 66, //!< convert RGB/BGR to HSV (hue saturation value) with H range 0..255 if 8 bit image, @ref color_convert_rgb_hsv "color conversions" - COLOR_RGB2HSV_FULL = 67, - COLOR_BGR2HLS_FULL = 68, //!< convert RGB/BGR to HLS (hue lightness saturation) with H range 0..255 if 8 bit image, @ref color_convert_rgb_hls "color conversions" - COLOR_RGB2HLS_FULL = 69, - - COLOR_HSV2BGR_FULL = 70, //!< backward conversions HSV to RGB/BGR with H range 0..255 if 8 bit image - COLOR_HSV2RGB_FULL = 71, - COLOR_HLS2BGR_FULL = 72, //!< backward conversions HLS to RGB/BGR with H range 0..255 if 8 bit image - COLOR_HLS2RGB_FULL = 73, - - COLOR_LBGR2Lab = 74, - COLOR_LRGB2Lab = 75, - COLOR_LBGR2Luv = 76, - COLOR_LRGB2Luv = 77, - - COLOR_Lab2LBGR = 78, - COLOR_Lab2LRGB = 79, - COLOR_Luv2LBGR = 80, - COLOR_Luv2LRGB = 81, - - COLOR_BGR2YUV = 82, //!< convert between RGB/BGR and YUV - COLOR_RGB2YUV = 83, - COLOR_YUV2BGR = 84, - COLOR_YUV2RGB = 85, - - COLOR_YUV2RGB_NV12 = 90, //!< convert between 4:2:0-subsampled YUV NV12 and RGB, two planes (in one or separate arrays): Y and U/V interleaved, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGR_NV12 = 91, //!< convert between 4:2:0-subsampled YUV NV12 and BGR, two planes (in one or separate arrays): Y and U/V interleaved, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2RGB_NV21 = 92, //!< convert between 4:2:0-subsampled YUV NV21 and RGB, two planes (in one or separate arrays): Y and V/U interleaved, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGR_NV21 = 93, //!< convert between 4:2:0-subsampled YUV NV21 and BGR, two planes (in one or separate arrays): Y and V/U interleaved, see @ref color_convert_rgb_yuv_42x - COLOR_YUV420sp2RGB = COLOR_YUV2RGB_NV21, //!< synonym to NV21 - COLOR_YUV420sp2BGR = COLOR_YUV2BGR_NV21, //!< synonym to NV21 - - COLOR_YUV2RGBA_NV12 = 94, //!< convert between 4:2:0-subsampled YUV NV12 and RGBA, two planes (in one or separate arrays): Y and U/V interleaved, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGRA_NV12 = 95, //!< convert between 4:2:0-subsampled YUV NV12 and BGRA, two planes (in one or separate arrays): Y and U/V interleaved, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2RGBA_NV21 = 96, //!< convert between 4:2:0-subsampled YUV NV21 and RGBA, two planes (in one or separate arrays): Y and V/U interleaved, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGRA_NV21 = 97, //!< convert between 4:2:0-subsampled YUV NV21 and BGRA, two planes (in one or separate arrays): Y and V/U interleaved, see @ref color_convert_rgb_yuv_42x - COLOR_YUV420sp2RGBA = COLOR_YUV2RGBA_NV21, //!< synonym to NV21 - COLOR_YUV420sp2BGRA = COLOR_YUV2BGRA_NV21, //!< synonym to NV21 - - COLOR_YUV2RGB_YV12 = 98, //!< convert between 4:2:0-subsampled YUV YV12 and RGB, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGR_YV12 = 99, //!< convert between 4:2:0-subsampled YUV YV12 and BGR, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2RGB_IYUV = 100, //!< convert between 4:2:0-subsampled YUV IYUV and RGB, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGR_IYUV = 101, //!< convert between 4:2:0-subsampled YUV IYUV and BGR, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2RGB_I420 = COLOR_YUV2RGB_IYUV, //!< synonym to IYUV - COLOR_YUV2BGR_I420 = COLOR_YUV2BGR_IYUV, //!< synonym to IYUV - COLOR_YUV420p2RGB = COLOR_YUV2RGB_YV12, //!< synonym to YV12 - COLOR_YUV420p2BGR = COLOR_YUV2BGR_YV12, //!< synonym to YV12 - - COLOR_YUV2RGBA_YV12 = 102, //!< convert between 4:2:0-subsampled YUV YV12 and RGBA, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGRA_YV12 = 103, //!< convert between 4:2:0-subsampled YUV YV12 and BGRA, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2RGBA_IYUV = 104, //!< convert between 4:2:0-subsampled YUV YV12 and RGBA, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGRA_IYUV = 105, //!< convert between 4:2:0-subsampled YUV YV12 and BGRA, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2RGBA_I420 = COLOR_YUV2RGBA_IYUV, //!< synonym to IYUV - COLOR_YUV2BGRA_I420 = COLOR_YUV2BGRA_IYUV, //!< synonym to IYUV - COLOR_YUV420p2RGBA = COLOR_YUV2RGBA_YV12, //!< synonym to YV12 - COLOR_YUV420p2BGRA = COLOR_YUV2BGRA_YV12, //!< synonym to YV12 - - COLOR_YUV2GRAY_420 = 106, //!< extract Y channel from YUV 4:2:0 image - COLOR_YUV2GRAY_NV21 = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 - COLOR_YUV2GRAY_NV12 = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 - COLOR_YUV2GRAY_YV12 = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 - COLOR_YUV2GRAY_IYUV = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 - COLOR_YUV2GRAY_I420 = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 - COLOR_YUV420sp2GRAY = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 - COLOR_YUV420p2GRAY = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 - - COLOR_YUV2RGB_UYVY = 107, //!< convert between YUV UYVY and RGB, YUV is 4:2:2-subsampled and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGR_UYVY = 108, //!< convert between YUV UYVY and BGR, YUV is 4:2:2-subsampled and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x - //COLOR_YUV2RGB_VYUY = 109, //!< convert between YUV VYUY and RGB, YUV is 4:2:2-subsampled and interleaved as V/Y1/U/Y2, see @ref color_convert_rgb_yuv_42x - //COLOR_YUV2BGR_VYUY = 110, //!< convert between YUV VYUY and BGR, YUV is 4:2:2-subsampled and interleaved as V/Y1/U/Y2, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2RGB_Y422 = COLOR_YUV2RGB_UYVY, //!< synonym to UYVY - COLOR_YUV2BGR_Y422 = COLOR_YUV2BGR_UYVY, //!< synonym to UYVY - COLOR_YUV2RGB_UYNV = COLOR_YUV2RGB_UYVY, //!< synonym to UYVY - COLOR_YUV2BGR_UYNV = COLOR_YUV2BGR_UYVY, //!< synonym to UYVY - - COLOR_YUV2RGBA_UYVY = 111, //!< convert between YUV UYVY and RGBA, YUV is 4:2:2-subsampled and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGRA_UYVY = 112, //!< convert between YUV UYVY and BGRA, YUV is 4:2:2-subsampled and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x - //COLOR_YUV2RGBA_VYUY = 113, //!< convert between YUV VYUY and RGBA, YUV is 4:2:2-subsampled and interleaved as V/Y1/U/Y2, see @ref color_convert_rgb_yuv_42x - //COLOR_YUV2BGRA_VYUY = 114, //!< convert between YUV VYUY and BGRA, YUV is 4:2:2-subsampled and interleaved as V/Y1/U/Y2, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2RGBA_Y422 = COLOR_YUV2RGBA_UYVY, //!< synonym to UYVY - COLOR_YUV2BGRA_Y422 = COLOR_YUV2BGRA_UYVY, //!< synonym to UYVY - COLOR_YUV2RGBA_UYNV = COLOR_YUV2RGBA_UYVY, //!< synonym to UYVY - COLOR_YUV2BGRA_UYNV = COLOR_YUV2BGRA_UYVY, //!< synonym to UYVY - - COLOR_YUV2RGB_YUY2 = 115, //!< convert between YUV YUY2 and RGB, YUV is 4:2:2-subsampled and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGR_YUY2 = 116, //!< convert between YUV YUY2 and BGR, YUV is 4:2:2-subsampled and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2RGB_YVYU = 117, //!< convert between YUV YVYU and RGB, YUV is 4:2:2-subsampled and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGR_YVYU = 118, //!< convert between YUV YVYU and BGR, YUV is 4:2:2-subsampled and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2RGB_YUYV = COLOR_YUV2RGB_YUY2, //!< synonym to YUY2 - COLOR_YUV2BGR_YUYV = COLOR_YUV2BGR_YUY2, //!< synonym to YUY2 - COLOR_YUV2RGB_YUNV = COLOR_YUV2RGB_YUY2, //!< synonym to YUY2 - COLOR_YUV2BGR_YUNV = COLOR_YUV2BGR_YUY2, //!< synonym to YUY2 - - COLOR_YUV2RGBA_YUY2 = 119, //!< convert between YUV YUY2 and RGBA, YUV is 4:2:2-subsampled and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGRA_YUY2 = 120, //!< convert between YUV YUY2 and BGRA, YUV is 4:2:2-subsampled and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2RGBA_YVYU = 121, //!< convert between YUV YVYU and RGBA, YUV is 4:2:2-subsampled and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGRA_YVYU = 122, //!< convert between YUV YVYU and BGRA, YUV is 4:2:2-subsampled and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2RGBA_YUYV = COLOR_YUV2RGBA_YUY2, //!< synonym to YUY2 - COLOR_YUV2BGRA_YUYV = COLOR_YUV2BGRA_YUY2, //!< synonym to YUY2 - COLOR_YUV2RGBA_YUNV = COLOR_YUV2RGBA_YUY2, //!< synonym to YUY2 - COLOR_YUV2BGRA_YUNV = COLOR_YUV2BGRA_YUY2, //!< synonym to YUY2 - - COLOR_YUV2GRAY_UYVY = 123, //!< extract Y channel from YUV 4:2:2 image - COLOR_YUV2GRAY_YUY2 = 124, //!< extract Y channel from YUV 4:2:2 image - //CV_YUV2GRAY_VYUY = CV_YUV2GRAY_UYVY, //!< synonym to COLOR_YUV2GRAY_UYVY - COLOR_YUV2GRAY_Y422 = COLOR_YUV2GRAY_UYVY, //!< synonym to COLOR_YUV2GRAY_UYVY - COLOR_YUV2GRAY_UYNV = COLOR_YUV2GRAY_UYVY, //!< synonym to COLOR_YUV2GRAY_UYVY - COLOR_YUV2GRAY_YVYU = COLOR_YUV2GRAY_YUY2, //!< synonym to COLOR_YUV2GRAY_YUY2 - COLOR_YUV2GRAY_YUYV = COLOR_YUV2GRAY_YUY2, //!< synonym to COLOR_YUV2GRAY_YUY2 - COLOR_YUV2GRAY_YUNV = COLOR_YUV2GRAY_YUY2, //!< synonym to COLOR_YUV2GRAY_YUY2 - - //! alpha premultiplication - COLOR_RGBA2mRGBA = 125, - COLOR_mRGBA2RGBA = 126, - - COLOR_RGB2YUV_I420 = 127, //!< convert between RGB and 4:2:0-subsampled YUV I420, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x - COLOR_BGR2YUV_I420 = 128, //!< convert between BGR and 4:2:0-subsampled YUV I420, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x - COLOR_RGB2YUV_IYUV = COLOR_RGB2YUV_I420, //!< synonym to I420 - COLOR_BGR2YUV_IYUV = COLOR_BGR2YUV_I420, //!< synonym to I420 - - COLOR_RGBA2YUV_I420 = 129, //!< convert between RGBA and 4:2:0-subsampled YUV I420, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x - COLOR_BGRA2YUV_I420 = 130, //!< convert between BGRA and 4:2:0-subsampled YUV I420, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x - COLOR_RGBA2YUV_IYUV = COLOR_RGBA2YUV_I420, //!< synonym to I420 - COLOR_BGRA2YUV_IYUV = COLOR_BGRA2YUV_I420, //!< synonym to I420 - COLOR_RGB2YUV_YV12 = 131, //!< convert between RGB and 4:2:0-subsampled YUV YV12, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x - COLOR_BGR2YUV_YV12 = 132, //!< convert between BGR and 4:2:0-subsampled YUV YV12, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x - COLOR_RGBA2YUV_YV12 = 133, //!< convert between RGBA and 4:2:0-subsampled YUV YV12, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x - COLOR_BGRA2YUV_YV12 = 134, //!< convert between BGRA and 4:2:0-subsampled YUV YV12, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x - - //! Demosaicing, see @ref color_convert_bayer "color conversions" for additional information - COLOR_BayerBG2BGR = 46, //!< equivalent to RGGB Bayer pattern - COLOR_BayerGB2BGR = 47, //!< equivalent to GRBG Bayer pattern - COLOR_BayerRG2BGR = 48, //!< equivalent to BGGR Bayer pattern - COLOR_BayerGR2BGR = 49, //!< equivalent to GBRG Bayer pattern - - COLOR_BayerRGGB2BGR = COLOR_BayerBG2BGR, - COLOR_BayerGRBG2BGR = COLOR_BayerGB2BGR, - COLOR_BayerBGGR2BGR = COLOR_BayerRG2BGR, - COLOR_BayerGBRG2BGR = COLOR_BayerGR2BGR, - - COLOR_BayerRGGB2RGB = COLOR_BayerBGGR2BGR, - COLOR_BayerGRBG2RGB = COLOR_BayerGBRG2BGR, - COLOR_BayerBGGR2RGB = COLOR_BayerRGGB2BGR, - COLOR_BayerGBRG2RGB = COLOR_BayerGRBG2BGR, - - COLOR_BayerBG2RGB = COLOR_BayerRG2BGR, //!< equivalent to RGGB Bayer pattern - COLOR_BayerGB2RGB = COLOR_BayerGR2BGR, //!< equivalent to GRBG Bayer pattern - COLOR_BayerRG2RGB = COLOR_BayerBG2BGR, //!< equivalent to BGGR Bayer pattern - COLOR_BayerGR2RGB = COLOR_BayerGB2BGR, //!< equivalent to GBRG Bayer pattern - - COLOR_BayerBG2GRAY = 86, //!< equivalent to RGGB Bayer pattern - COLOR_BayerGB2GRAY = 87, //!< equivalent to GRBG Bayer pattern - COLOR_BayerRG2GRAY = 88, //!< equivalent to BGGR Bayer pattern - COLOR_BayerGR2GRAY = 89, //!< equivalent to GBRG Bayer pattern - - COLOR_BayerRGGB2GRAY = COLOR_BayerBG2GRAY, - COLOR_BayerGRBG2GRAY = COLOR_BayerGB2GRAY, - COLOR_BayerBGGR2GRAY = COLOR_BayerRG2GRAY, - COLOR_BayerGBRG2GRAY = COLOR_BayerGR2GRAY, - - //! Demosaicing using Variable Number of Gradients - COLOR_BayerBG2BGR_VNG = 62, //!< equivalent to RGGB Bayer pattern - COLOR_BayerGB2BGR_VNG = 63, //!< equivalent to GRBG Bayer pattern - COLOR_BayerRG2BGR_VNG = 64, //!< equivalent to BGGR Bayer pattern - COLOR_BayerGR2BGR_VNG = 65, //!< equivalent to GBRG Bayer pattern - - COLOR_BayerRGGB2BGR_VNG = COLOR_BayerBG2BGR_VNG, - COLOR_BayerGRBG2BGR_VNG = COLOR_BayerGB2BGR_VNG, - COLOR_BayerBGGR2BGR_VNG = COLOR_BayerRG2BGR_VNG, - COLOR_BayerGBRG2BGR_VNG = COLOR_BayerGR2BGR_VNG, - - COLOR_BayerRGGB2RGB_VNG = COLOR_BayerBGGR2BGR_VNG, - COLOR_BayerGRBG2RGB_VNG = COLOR_BayerGBRG2BGR_VNG, - COLOR_BayerBGGR2RGB_VNG = COLOR_BayerRGGB2BGR_VNG, - COLOR_BayerGBRG2RGB_VNG = COLOR_BayerGRBG2BGR_VNG, - - COLOR_BayerBG2RGB_VNG = COLOR_BayerRG2BGR_VNG, //!< equivalent to RGGB Bayer pattern - COLOR_BayerGB2RGB_VNG = COLOR_BayerGR2BGR_VNG, //!< equivalent to GRBG Bayer pattern - COLOR_BayerRG2RGB_VNG = COLOR_BayerBG2BGR_VNG, //!< equivalent to BGGR Bayer pattern - COLOR_BayerGR2RGB_VNG = COLOR_BayerGB2BGR_VNG, //!< equivalent to GBRG Bayer pattern - - //! Edge-Aware Demosaicing - COLOR_BayerBG2BGR_EA = 135, //!< equivalent to RGGB Bayer pattern - COLOR_BayerGB2BGR_EA = 136, //!< equivalent to GRBG Bayer pattern - COLOR_BayerRG2BGR_EA = 137, //!< equivalent to BGGR Bayer pattern - COLOR_BayerGR2BGR_EA = 138, //!< equivalent to GBRG Bayer pattern - - COLOR_BayerRGGB2BGR_EA = COLOR_BayerBG2BGR_EA, - COLOR_BayerGRBG2BGR_EA = COLOR_BayerGB2BGR_EA, - COLOR_BayerBGGR2BGR_EA = COLOR_BayerRG2BGR_EA, - COLOR_BayerGBRG2BGR_EA = COLOR_BayerGR2BGR_EA, - - COLOR_BayerRGGB2RGB_EA = COLOR_BayerBGGR2BGR_EA, - COLOR_BayerGRBG2RGB_EA = COLOR_BayerGBRG2BGR_EA, - COLOR_BayerBGGR2RGB_EA = COLOR_BayerRGGB2BGR_EA, - COLOR_BayerGBRG2RGB_EA = COLOR_BayerGRBG2BGR_EA, - - COLOR_BayerBG2RGB_EA = COLOR_BayerRG2BGR_EA, //!< equivalent to RGGB Bayer pattern - COLOR_BayerGB2RGB_EA = COLOR_BayerGR2BGR_EA, //!< equivalent to GRBG Bayer pattern - COLOR_BayerRG2RGB_EA = COLOR_BayerBG2BGR_EA, //!< equivalent to BGGR Bayer pattern - COLOR_BayerGR2RGB_EA = COLOR_BayerGB2BGR_EA, //!< equivalent to GBRG Bayer pattern - - //! Demosaicing with alpha channel - COLOR_BayerBG2BGRA = 139, //!< equivalent to RGGB Bayer pattern - COLOR_BayerGB2BGRA = 140, //!< equivalent to GRBG Bayer pattern - COLOR_BayerRG2BGRA = 141, //!< equivalent to BGGR Bayer pattern - COLOR_BayerGR2BGRA = 142, //!< equivalent to GBRG Bayer pattern - - COLOR_BayerRGGB2BGRA = COLOR_BayerBG2BGRA, - COLOR_BayerGRBG2BGRA = COLOR_BayerGB2BGRA, - COLOR_BayerBGGR2BGRA = COLOR_BayerRG2BGRA, - COLOR_BayerGBRG2BGRA = COLOR_BayerGR2BGRA, - - COLOR_BayerRGGB2RGBA = COLOR_BayerBGGR2BGRA, - COLOR_BayerGRBG2RGBA = COLOR_BayerGBRG2BGRA, - COLOR_BayerBGGR2RGBA = COLOR_BayerRGGB2BGRA, - COLOR_BayerGBRG2RGBA = COLOR_BayerGRBG2BGRA, - - COLOR_BayerBG2RGBA = COLOR_BayerRG2BGRA, //!< equivalent to RGGB Bayer pattern - COLOR_BayerGB2RGBA = COLOR_BayerGR2BGRA, //!< equivalent to GRBG Bayer pattern - COLOR_BayerRG2RGBA = COLOR_BayerBG2BGRA, //!< equivalent to BGGR Bayer pattern - COLOR_BayerGR2RGBA = COLOR_BayerGB2BGRA, //!< equivalent to GBRG Bayer pattern - - COLOR_RGB2YUV_UYVY = 143, //!< convert between RGB and YUV UYVU, YUV is 4:2:2 and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x - COLOR_BGR2YUV_UYVY = 144, //!< convert between BGR and YUV UYVU, YUV is 4:2:2 and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x - COLOR_RGB2YUV_Y422 = COLOR_RGB2YUV_UYVY, //!< synonym to UYVY - COLOR_BGR2YUV_Y422 = COLOR_BGR2YUV_UYVY, //!< synonym to UYVY - COLOR_RGB2YUV_UYNV = COLOR_RGB2YUV_UYVY, //!< synonym to UYVY - COLOR_BGR2YUV_UYNV = COLOR_BGR2YUV_UYVY, //!< synonym to UYVY - - COLOR_RGBA2YUV_UYVY = 145, //!< convert between RGBA and YUV UYVU, YUV is 4:2:2 and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x - COLOR_BGRA2YUV_UYVY = 146, //!< convert between BGRA and YUV UYVU, YUV is 4:2:2 and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x - COLOR_RGBA2YUV_Y422 = COLOR_RGBA2YUV_UYVY, //!< synonym to UYVY - COLOR_BGRA2YUV_Y422 = COLOR_BGRA2YUV_UYVY, //!< synonym to UYVY - COLOR_RGBA2YUV_UYNV = COLOR_RGBA2YUV_UYVY, //!< synonym to UYVY - COLOR_BGRA2YUV_UYNV = COLOR_BGRA2YUV_UYVY, //!< synonym to UYVY - - COLOR_RGB2YUV_YUY2 = 147, //!< convert between RGB and YUV YUY2, YUV is 4:2:2 and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x - COLOR_BGR2YUV_YUY2 = 148, //!< convert between BGR and YUV YUY2, YUV is 4:2:2 and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x - COLOR_RGB2YUV_YVYU = 149, //!< convert between RGB and YUV YVYU, YUV is 4:2:2 and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x - COLOR_BGR2YUV_YVYU = 150, //!< convert between BGR and YUV YVYU, YUV is 4:2:2 and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x - COLOR_RGB2YUV_YUYV = COLOR_RGB2YUV_YUY2, //!< synonym to YUY2 - COLOR_BGR2YUV_YUYV = COLOR_BGR2YUV_YUY2, //!< synonym to YUY2 - COLOR_RGB2YUV_YUNV = COLOR_RGB2YUV_YUY2, //!< synonym to YUY2 - COLOR_BGR2YUV_YUNV = COLOR_BGR2YUV_YUY2, //!< synonym to YUY2 - - COLOR_RGBA2YUV_YUY2 = 151, //!< convert between RGBA and YUV YUY2, YUV is 4:2:2 and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x - COLOR_BGRA2YUV_YUY2 = 152, //!< convert between BGRA and YUV YUY2, YUV is 4:2:2 and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x - COLOR_RGBA2YUV_YVYU = 153, //!< convert between RGBA and YUV YVYU, YUV is 4:2:2 and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x - COLOR_BGRA2YUV_YVYU = 154, //!< convert between BGRA and YUV YVYU, YUV is 4:2:2 and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x - COLOR_RGBA2YUV_YUYV = COLOR_RGBA2YUV_YUY2, //!< synonym to YUY2 - COLOR_BGRA2YUV_YUYV = COLOR_BGRA2YUV_YUY2, //!< synonym to YUY2 - COLOR_RGBA2YUV_YUNV = COLOR_RGBA2YUV_YUY2, //!< synonym to YUY2 - COLOR_BGRA2YUV_YUNV = COLOR_BGRA2YUV_YUY2, //!< synonym to YUY2 - - COLOR_COLORCVT_MAX = 155 -}; - -//! @addtogroup imgproc_shape -//! @{ - -//! types of intersection between rectangles -enum RectanglesIntersectTypes { - INTERSECT_NONE = 0, //!< No intersection - INTERSECT_PARTIAL = 1, //!< There is a partial intersection - INTERSECT_FULL = 2 //!< One of the rectangle is fully enclosed in the other -}; - -/** types of line -@ingroup imgproc_draw -*/ -enum LineTypes { - FILLED = -1, - LINE_4 = 4, //!< 4-connected line - LINE_8 = 8, //!< 8-connected line - LINE_AA = 16 //!< antialiased line -}; - -/** Only a subset of Hershey fonts are supported -@ingroup imgproc_draw -*/ -enum HersheyFonts { - FONT_HERSHEY_SIMPLEX = 0, //!< normal size sans-serif font - FONT_HERSHEY_PLAIN = 1, //!< small size sans-serif font - FONT_HERSHEY_DUPLEX = 2, //!< normal size sans-serif font (more complex than FONT_HERSHEY_SIMPLEX) - FONT_HERSHEY_COMPLEX = 3, //!< normal size serif font - FONT_HERSHEY_TRIPLEX = 4, //!< normal size serif font (more complex than FONT_HERSHEY_COMPLEX) - FONT_HERSHEY_COMPLEX_SMALL = 5, //!< smaller version of FONT_HERSHEY_COMPLEX - FONT_HERSHEY_SCRIPT_SIMPLEX = 6, //!< hand-writing style font - FONT_HERSHEY_SCRIPT_COMPLEX = 7, //!< more complex variant of FONT_HERSHEY_SCRIPT_SIMPLEX - FONT_ITALIC = 16 //!< flag for italic font -}; - -/** Possible set of marker types used for the cv::drawMarker function -@ingroup imgproc_draw -*/ -enum MarkerTypes -{ - MARKER_CROSS = 0, //!< A crosshair marker shape - MARKER_TILTED_CROSS = 1, //!< A 45 degree tilted crosshair marker shape - MARKER_STAR = 2, //!< A star marker shape, combination of cross and tilted cross - MARKER_DIAMOND = 3, //!< A diamond marker shape - MARKER_SQUARE = 4, //!< A square marker shape - MARKER_TRIANGLE_UP = 5, //!< An upwards pointing triangle marker shape - MARKER_TRIANGLE_DOWN = 6 //!< A downwards pointing triangle marker shape -}; - -/** @brief finds arbitrary template in the grayscale image using Generalized Hough Transform -*/ -class CV_EXPORTS_W GeneralizedHough : public Algorithm -{ -public: - //! set template to search - CV_WRAP virtual void setTemplate(InputArray templ, Point templCenter = Point(-1, -1)) = 0; - CV_WRAP virtual void setTemplate(InputArray edges, InputArray dx, InputArray dy, Point templCenter = Point(-1, -1)) = 0; - - //! find template on image - CV_WRAP virtual void detect(InputArray image, OutputArray positions, OutputArray votes = noArray()) = 0; - CV_WRAP virtual void detect(InputArray edges, InputArray dx, InputArray dy, OutputArray positions, OutputArray votes = noArray()) = 0; - - //! Canny low threshold. - CV_WRAP virtual void setCannyLowThresh(int cannyLowThresh) = 0; - CV_WRAP virtual int getCannyLowThresh() const = 0; - - //! Canny high threshold. - CV_WRAP virtual void setCannyHighThresh(int cannyHighThresh) = 0; - CV_WRAP virtual int getCannyHighThresh() const = 0; - - //! Minimum distance between the centers of the detected objects. - CV_WRAP virtual void setMinDist(double minDist) = 0; - CV_WRAP virtual double getMinDist() const = 0; - - //! Inverse ratio of the accumulator resolution to the image resolution. - CV_WRAP virtual void setDp(double dp) = 0; - CV_WRAP virtual double getDp() const = 0; - - //! Maximal size of inner buffers. - CV_WRAP virtual void setMaxBufferSize(int maxBufferSize) = 0; - CV_WRAP virtual int getMaxBufferSize() const = 0; -}; - -/** @brief finds arbitrary template in the grayscale image using Generalized Hough Transform - -Detects position only without translation and rotation @cite Ballard1981 . -*/ -class CV_EXPORTS_W GeneralizedHoughBallard : public GeneralizedHough -{ -public: - //! R-Table levels. - CV_WRAP virtual void setLevels(int levels) = 0; - CV_WRAP virtual int getLevels() const = 0; - - //! The accumulator threshold for the template centers at the detection stage. The smaller it is, the more false positions may be detected. - CV_WRAP virtual void setVotesThreshold(int votesThreshold) = 0; - CV_WRAP virtual int getVotesThreshold() const = 0; -}; - -/** @brief finds arbitrary template in the grayscale image using Generalized Hough Transform - -Detects position, translation and rotation @cite Guil1999 . -*/ -class CV_EXPORTS_W GeneralizedHoughGuil : public GeneralizedHough -{ -public: - //! Angle difference in degrees between two points in feature. - CV_WRAP virtual void setXi(double xi) = 0; - CV_WRAP virtual double getXi() const = 0; - - //! Feature table levels. - CV_WRAP virtual void setLevels(int levels) = 0; - CV_WRAP virtual int getLevels() const = 0; - - //! Maximal difference between angles that treated as equal. - CV_WRAP virtual void setAngleEpsilon(double angleEpsilon) = 0; - CV_WRAP virtual double getAngleEpsilon() const = 0; - - //! Minimal rotation angle to detect in degrees. - CV_WRAP virtual void setMinAngle(double minAngle) = 0; - CV_WRAP virtual double getMinAngle() const = 0; - - //! Maximal rotation angle to detect in degrees. - CV_WRAP virtual void setMaxAngle(double maxAngle) = 0; - CV_WRAP virtual double getMaxAngle() const = 0; - - //! Angle step in degrees. - CV_WRAP virtual void setAngleStep(double angleStep) = 0; - CV_WRAP virtual double getAngleStep() const = 0; - - //! Angle votes threshold. - CV_WRAP virtual void setAngleThresh(int angleThresh) = 0; - CV_WRAP virtual int getAngleThresh() const = 0; - - //! Minimal scale to detect. - CV_WRAP virtual void setMinScale(double minScale) = 0; - CV_WRAP virtual double getMinScale() const = 0; - - //! Maximal scale to detect. - CV_WRAP virtual void setMaxScale(double maxScale) = 0; - CV_WRAP virtual double getMaxScale() const = 0; - - //! Scale step. - CV_WRAP virtual void setScaleStep(double scaleStep) = 0; - CV_WRAP virtual double getScaleStep() const = 0; - - //! Scale votes threshold. - CV_WRAP virtual void setScaleThresh(int scaleThresh) = 0; - CV_WRAP virtual int getScaleThresh() const = 0; - - //! Position votes threshold. - CV_WRAP virtual void setPosThresh(int posThresh) = 0; - CV_WRAP virtual int getPosThresh() const = 0; -}; - -//! @} imgproc_shape - -//! @addtogroup imgproc_hist -//! @{ - -/** @brief Base class for Contrast Limited Adaptive Histogram Equalization. -*/ -class CV_EXPORTS_W CLAHE : public Algorithm -{ -public: - /** @brief Equalizes the histogram of a grayscale image using Contrast Limited Adaptive Histogram Equalization. - - @param src Source image of type CV_8UC1 or CV_16UC1. - @param dst Destination image. - */ - CV_WRAP virtual void apply(InputArray src, OutputArray dst) = 0; - - /** @brief Sets threshold for contrast limiting. - - @param clipLimit threshold value. - */ - CV_WRAP virtual void setClipLimit(double clipLimit) = 0; - - //! Returns threshold value for contrast limiting. - CV_WRAP virtual double getClipLimit() const = 0; - - /** @brief Sets size of grid for histogram equalization. Input image will be divided into - equally sized rectangular tiles. - - @param tileGridSize defines the number of tiles in row and column. - */ - CV_WRAP virtual void setTilesGridSize(Size tileGridSize) = 0; - - //!@brief Returns Size defines the number of tiles in row and column. - CV_WRAP virtual Size getTilesGridSize() const = 0; - - CV_WRAP virtual void collectGarbage() = 0; -}; - -//! @} imgproc_hist - -//! @addtogroup imgproc_subdiv2d -//! @{ - -class CV_EXPORTS_W Subdiv2D -{ -public: - /** Subdiv2D point location cases */ - enum { PTLOC_ERROR = -2, //!< Point location error - PTLOC_OUTSIDE_RECT = -1, //!< Point outside the subdivision bounding rect - PTLOC_INSIDE = 0, //!< Point inside some facet - PTLOC_VERTEX = 1, //!< Point coincides with one of the subdivision vertices - PTLOC_ON_EDGE = 2 //!< Point on some edge - }; - - /** Subdiv2D edge type navigation (see: getEdge()) */ - enum { NEXT_AROUND_ORG = 0x00, - NEXT_AROUND_DST = 0x22, - PREV_AROUND_ORG = 0x11, - PREV_AROUND_DST = 0x33, - NEXT_AROUND_LEFT = 0x13, - NEXT_AROUND_RIGHT = 0x31, - PREV_AROUND_LEFT = 0x20, - PREV_AROUND_RIGHT = 0x02 - }; - - /** creates an empty Subdiv2D object. - To create a new empty Delaunay subdivision you need to use the #initDelaunay function. - */ - CV_WRAP Subdiv2D(); - - /** @overload - - @param rect Rectangle that includes all of the 2D points that are to be added to the subdivision. - - The function creates an empty Delaunay subdivision where 2D points can be added using the function - insert() . All of the points to be added must be within the specified rectangle, otherwise a runtime - error is raised. - */ - CV_WRAP Subdiv2D(Rect rect); - - /** @brief Creates a new empty Delaunay subdivision - - @param rect Rectangle that includes all of the 2D points that are to be added to the subdivision. - - */ - CV_WRAP void initDelaunay(Rect rect); - - /** @brief Insert a single point into a Delaunay triangulation. - - @param pt Point to insert. - - The function inserts a single point into a subdivision and modifies the subdivision topology - appropriately. If a point with the same coordinates exists already, no new point is added. - @returns the ID of the point. - - @note If the point is outside of the triangulation specified rect a runtime error is raised. - */ - CV_WRAP int insert(Point2f pt); - - /** @brief Insert multiple points into a Delaunay triangulation. - - @param ptvec Points to insert. - - The function inserts a vector of points into a subdivision and modifies the subdivision topology - appropriately. - */ - CV_WRAP void insert(const std::vector& ptvec); - - /** @brief Returns the location of a point within a Delaunay triangulation. - - @param pt Point to locate. - @param edge Output edge that the point belongs to or is located to the right of it. - @param vertex Optional output vertex the input point coincides with. - - The function locates the input point within the subdivision and gives one of the triangle edges - or vertices. - - @returns an integer which specify one of the following five cases for point location: - - The point falls into some facet. The function returns #PTLOC_INSIDE and edge will contain one of - edges of the facet. - - The point falls onto the edge. The function returns #PTLOC_ON_EDGE and edge will contain this edge. - - The point coincides with one of the subdivision vertices. The function returns #PTLOC_VERTEX and - vertex will contain a pointer to the vertex. - - The point is outside the subdivision reference rectangle. The function returns #PTLOC_OUTSIDE_RECT - and no pointers are filled. - - One of input arguments is invalid. A runtime error is raised or, if silent or "parent" error - processing mode is selected, #PTLOC_ERROR is returned. - */ - CV_WRAP int locate(Point2f pt, CV_OUT int& edge, CV_OUT int& vertex); - - /** @brief Finds the subdivision vertex closest to the given point. - - @param pt Input point. - @param nearestPt Output subdivision vertex point. - - The function is another function that locates the input point within the subdivision. It finds the - subdivision vertex that is the closest to the input point. It is not necessarily one of vertices - of the facet containing the input point, though the facet (located using locate() ) is used as a - starting point. - - @returns vertex ID. - */ - CV_WRAP int findNearest(Point2f pt, CV_OUT Point2f* nearestPt = 0); - - /** @brief Returns a list of all edges. - - @param edgeList Output vector. - - The function gives each edge as a 4 numbers vector, where each two are one of the edge - vertices. i.e. org_x = v[0], org_y = v[1], dst_x = v[2], dst_y = v[3]. - */ - CV_WRAP void getEdgeList(CV_OUT std::vector& edgeList) const; - - /** @brief Returns a list of the leading edge ID connected to each triangle. - - @param leadingEdgeList Output vector. - - The function gives one edge ID for each triangle. - */ - CV_WRAP void getLeadingEdgeList(CV_OUT std::vector& leadingEdgeList) const; - - /** @brief Returns a list of all triangles. - - @param triangleList Output vector. - - The function gives each triangle as a 6 numbers vector, where each two are one of the triangle - vertices. i.e. p1_x = v[0], p1_y = v[1], p2_x = v[2], p2_y = v[3], p3_x = v[4], p3_y = v[5]. - */ - CV_WRAP void getTriangleList(CV_OUT std::vector& triangleList) const; - - /** @brief Returns a list of all Voronoi facets. - - @param idx Vector of vertices IDs to consider. For all vertices you can pass empty vector. - @param facetList Output vector of the Voronoi facets. - @param facetCenters Output vector of the Voronoi facets center points. - - */ - CV_WRAP void getVoronoiFacetList(const std::vector& idx, CV_OUT std::vector >& facetList, - CV_OUT std::vector& facetCenters); - - /** @brief Returns vertex location from vertex ID. - - @param vertex vertex ID. - @param firstEdge Optional. The first edge ID which is connected to the vertex. - @returns vertex (x,y) - - */ - CV_WRAP Point2f getVertex(int vertex, CV_OUT int* firstEdge = 0) const; - - /** @brief Returns one of the edges related to the given edge. - - @param edge Subdivision edge ID. - @param nextEdgeType Parameter specifying which of the related edges to return. - The following values are possible: - - NEXT_AROUND_ORG next around the edge origin ( eOnext on the picture below if e is the input edge) - - NEXT_AROUND_DST next around the edge vertex ( eDnext ) - - PREV_AROUND_ORG previous around the edge origin (reversed eRnext ) - - PREV_AROUND_DST previous around the edge destination (reversed eLnext ) - - NEXT_AROUND_LEFT next around the left facet ( eLnext ) - - NEXT_AROUND_RIGHT next around the right facet ( eRnext ) - - PREV_AROUND_LEFT previous around the left facet (reversed eOnext ) - - PREV_AROUND_RIGHT previous around the right facet (reversed eDnext ) - - ![sample output](pics/quadedge.png) - - @returns edge ID related to the input edge. - */ - CV_WRAP int getEdge( int edge, int nextEdgeType ) const; - - /** @brief Returns next edge around the edge origin. - - @param edge Subdivision edge ID. - - @returns an integer which is next edge ID around the edge origin: eOnext on the - picture above if e is the input edge). - */ - CV_WRAP int nextEdge(int edge) const; - - /** @brief Returns another edge of the same quad-edge. - - @param edge Subdivision edge ID. - @param rotate Parameter specifying which of the edges of the same quad-edge as the input - one to return. The following values are possible: - - 0 - the input edge ( e on the picture below if e is the input edge) - - 1 - the rotated edge ( eRot ) - - 2 - the reversed edge (reversed e (in green)) - - 3 - the reversed rotated edge (reversed eRot (in green)) - - @returns one of the edges ID of the same quad-edge as the input edge. - */ - CV_WRAP int rotateEdge(int edge, int rotate) const; - CV_WRAP int symEdge(int edge) const; - - /** @brief Returns the edge origin. - - @param edge Subdivision edge ID. - @param orgpt Output vertex location. - - @returns vertex ID. - */ - CV_WRAP int edgeOrg(int edge, CV_OUT Point2f* orgpt = 0) const; - - /** @brief Returns the edge destination. - - @param edge Subdivision edge ID. - @param dstpt Output vertex location. - - @returns vertex ID. - */ - CV_WRAP int edgeDst(int edge, CV_OUT Point2f* dstpt = 0) const; - -protected: - int newEdge(); - void deleteEdge(int edge); - int newPoint(Point2f pt, bool isvirtual, int firstEdge = 0); - void deletePoint(int vtx); - void setEdgePoints( int edge, int orgPt, int dstPt ); - void splice( int edgeA, int edgeB ); - int connectEdges( int edgeA, int edgeB ); - void swapEdges( int edge ); - int isRightOf(Point2f pt, int edge) const; - void calcVoronoi(); - void clearVoronoi(); - void checkSubdiv() const; - - struct CV_EXPORTS Vertex - { - Vertex(); - Vertex(Point2f pt, bool isvirtual, int firstEdge=0); - bool isvirtual() const; - bool isfree() const; - - int firstEdge; - int type; - Point2f pt; - }; - - struct CV_EXPORTS QuadEdge - { - QuadEdge(); - QuadEdge(int edgeidx); - bool isfree() const; - - int next[4]; - int pt[4]; - }; - - //! All of the vertices - std::vector vtx; - //! All of the edges - std::vector qedges; - int freeQEdge; - int freePoint; - bool validGeometry; - - int recentEdge; - //! Top left corner of the bounding rect - Point2f topLeft; - //! Bottom right corner of the bounding rect - Point2f bottomRight; -}; - -//! @} imgproc_subdiv2d - -//! @addtogroup imgproc_feature -//! @{ - -/** @example samples/cpp/lsd_lines.cpp -An example using the LineSegmentDetector -\image html building_lsd.png "Sample output image" width=434 height=300 -*/ - -/** @brief Line segment detector class - -following the algorithm described at @cite Rafael12 . - -@note Implementation has been removed from OpenCV version 3.4.6 to 3.4.15 and version 4.1.0 to 4.5.3 due original code license conflict. -restored again after [Computation of a NFA](https://github.com/rafael-grompone-von-gioi/binomial_nfa) code published under the MIT license. -*/ -class CV_EXPORTS_W LineSegmentDetector : public Algorithm -{ -public: - - /** @brief Finds lines in the input image. - - This is the output of the default parameters of the algorithm on the above shown image. - - ![image](pics/building_lsd.png) - - @param image A grayscale (CV_8UC1) input image. If only a roi needs to be selected, use: - `lsd_ptr-\>detect(image(roi), lines, ...); lines += Scalar(roi.x, roi.y, roi.x, roi.y);` - @param lines A vector of Vec4f elements specifying the beginning and ending point of a line. Where - Vec4f is (x1, y1, x2, y2), point 1 is the start, point 2 - end. Returned lines are strictly - oriented depending on the gradient. - @param width Vector of widths of the regions, where the lines are found. E.g. Width of line. - @param prec Vector of precisions with which the lines are found. - @param nfa Vector containing number of false alarms in the line region, with precision of 10%. The - bigger the value, logarithmically better the detection. - - -1 corresponds to 10 mean false alarms - - 0 corresponds to 1 mean false alarm - - 1 corresponds to 0.1 mean false alarms - This vector will be calculated only when the objects type is #LSD_REFINE_ADV. - */ - CV_WRAP virtual void detect(InputArray image, OutputArray lines, - OutputArray width = noArray(), OutputArray prec = noArray(), - OutputArray nfa = noArray()) = 0; - - /** @brief Draws the line segments on a given image. - @param image The image, where the lines will be drawn. Should be bigger or equal to the image, - where the lines were found. - @param lines A vector of the lines that needed to be drawn. - */ - CV_WRAP virtual void drawSegments(InputOutputArray image, InputArray lines) = 0; - - /** @brief Draws two groups of lines in blue and red, counting the non overlapping (mismatching) pixels. - - @param size The size of the image, where lines1 and lines2 were found. - @param lines1 The first group of lines that needs to be drawn. It is visualized in blue color. - @param lines2 The second group of lines. They visualized in red color. - @param image Optional image, where the lines will be drawn. The image should be color(3-channel) - in order for lines1 and lines2 to be drawn in the above mentioned colors. - */ - CV_WRAP virtual int compareSegments(const Size& size, InputArray lines1, InputArray lines2, InputOutputArray image = noArray()) = 0; - - virtual ~LineSegmentDetector() { } -}; - -/** @brief Creates a smart pointer to a LineSegmentDetector object and initializes it. - -The LineSegmentDetector algorithm is defined using the standard values. Only advanced users may want -to edit those, as to tailor it for their own application. - -@param refine The way found lines will be refined, see #LineSegmentDetectorModes -@param scale The scale of the image that will be used to find the lines. Range (0..1]. -@param sigma_scale Sigma for Gaussian filter. It is computed as sigma = sigma_scale/scale. -@param quant Bound to the quantization error on the gradient norm. -@param ang_th Gradient angle tolerance in degrees. -@param log_eps Detection threshold: -log10(NFA) \> log_eps. Used only when advance refinement is chosen. -@param density_th Minimal density of aligned region points in the enclosing rectangle. -@param n_bins Number of bins in pseudo-ordering of gradient modulus. - */ -CV_EXPORTS_W Ptr createLineSegmentDetector( - int refine = LSD_REFINE_STD, double scale = 0.8, - double sigma_scale = 0.6, double quant = 2.0, double ang_th = 22.5, - double log_eps = 0, double density_th = 0.7, int n_bins = 1024); - -//! @} imgproc_feature - -//! @addtogroup imgproc_filter -//! @{ - -/** @brief Returns Gaussian filter coefficients. - -The function computes and returns the \f$\texttt{ksize} \times 1\f$ matrix of Gaussian filter -coefficients: - -\f[G_i= \alpha *e^{-(i-( \texttt{ksize} -1)/2)^2/(2* \texttt{sigma}^2)},\f] - -where \f$i=0..\texttt{ksize}-1\f$ and \f$\alpha\f$ is the scale factor chosen so that \f$\sum_i G_i=1\f$. - -Two of such generated kernels can be passed to sepFilter2D. Those functions automatically recognize -smoothing kernels (a symmetrical kernel with sum of weights equal to 1) and handle them accordingly. -You may also use the higher-level GaussianBlur. -@param ksize Aperture size. It should be odd ( \f$\texttt{ksize} \mod 2 = 1\f$ ) and positive. -@param sigma Gaussian standard deviation. If it is non-positive, it is computed from ksize as -`sigma = 0.3*((ksize-1)*0.5 - 1) + 0.8`. -@param ktype Type of filter coefficients. It can be CV_32F or CV_64F . -@sa sepFilter2D, getDerivKernels, getStructuringElement, GaussianBlur - */ -CV_EXPORTS_W Mat getGaussianKernel( int ksize, double sigma, int ktype = CV_64F ); - -/** @brief Returns filter coefficients for computing spatial image derivatives. - -The function computes and returns the filter coefficients for spatial image derivatives. When -`ksize=FILTER_SCHARR`, the Scharr \f$3 \times 3\f$ kernels are generated (see #Scharr). Otherwise, Sobel -kernels are generated (see #Sobel). The filters are normally passed to #sepFilter2D or to - -@param kx Output matrix of row filter coefficients. It has the type ktype . -@param ky Output matrix of column filter coefficients. It has the type ktype . -@param dx Derivative order in respect of x. -@param dy Derivative order in respect of y. -@param ksize Aperture size. It can be FILTER_SCHARR, 1, 3, 5, or 7. -@param normalize Flag indicating whether to normalize (scale down) the filter coefficients or not. -Theoretically, the coefficients should have the denominator \f$=2^{ksize*2-dx-dy-2}\f$. If you are -going to filter floating-point images, you are likely to use the normalized kernels. But if you -compute derivatives of an 8-bit image, store the results in a 16-bit image, and wish to preserve -all the fractional bits, you may want to set normalize=false . -@param ktype Type of filter coefficients. It can be CV_32f or CV_64F . - */ -CV_EXPORTS_W void getDerivKernels( OutputArray kx, OutputArray ky, - int dx, int dy, int ksize, - bool normalize = false, int ktype = CV_32F ); - -/** @brief Returns Gabor filter coefficients. - -For more details about gabor filter equations and parameters, see: [Gabor -Filter](http://en.wikipedia.org/wiki/Gabor_filter). - -@param ksize Size of the filter returned. -@param sigma Standard deviation of the gaussian envelope. -@param theta Orientation of the normal to the parallel stripes of a Gabor function. -@param lambd Wavelength of the sinusoidal factor. -@param gamma Spatial aspect ratio. -@param psi Phase offset. -@param ktype Type of filter coefficients. It can be CV_32F or CV_64F . - */ -CV_EXPORTS_W Mat getGaborKernel( Size ksize, double sigma, double theta, double lambd, - double gamma, double psi = CV_PI*0.5, int ktype = CV_64F ); - -//! returns "magic" border value for erosion and dilation. It is automatically transformed to Scalar::all(-DBL_MAX) for dilation. -static inline Scalar morphologyDefaultBorderValue() { return Scalar::all(DBL_MAX); } - -/** @brief Returns a structuring element of the specified size and shape for morphological operations. - -The function constructs and returns the structuring element that can be further passed to #erode, -#dilate or #morphologyEx. But you can also construct an arbitrary binary mask yourself and use it as -the structuring element. - -@param shape Element shape that could be one of #MorphShapes -@param ksize Size of the structuring element. -@param anchor Anchor position within the element. The default value \f$(-1, -1)\f$ means that the -anchor is at the center. Note that only the shape of a cross-shaped element depends on the anchor -position. In other cases the anchor just regulates how much the result of the morphological -operation is shifted. - */ -CV_EXPORTS_W Mat getStructuringElement(int shape, Size ksize, Point anchor = Point(-1,-1)); - -/** @example samples/cpp/tutorial_code/ImgProc/Smoothing/Smoothing.cpp -Sample code for simple filters -![Sample screenshot](Smoothing_Tutorial_Result_Median_Filter.jpg) -Check @ref tutorial_gausian_median_blur_bilateral_filter "the corresponding tutorial" for more details - */ - -/** @brief Blurs an image using the median filter. - -The function smoothes an image using the median filter with the \f$\texttt{ksize} \times -\texttt{ksize}\f$ aperture. Each channel of a multi-channel image is processed independently. -In-place operation is supported. - -@note The median filter uses #BORDER_REPLICATE internally to cope with border pixels, see #BorderTypes - -@param src input 1-, 3-, or 4-channel image; when ksize is 3 or 5, the image depth should be -CV_8U, CV_16U, or CV_32F, for larger aperture sizes, it can only be CV_8U. -@param dst destination array of the same size and type as src. -@param ksize aperture linear size; it must be odd and greater than 1, for example: 3, 5, 7 ... -@sa bilateralFilter, blur, boxFilter, GaussianBlur - */ -CV_EXPORTS_W void medianBlur( InputArray src, OutputArray dst, int ksize ); - -/** @brief Blurs an image using a Gaussian filter. - -The function convolves the source image with the specified Gaussian kernel. In-place filtering is -supported. - -@param src input image; the image can have any number of channels, which are processed -independently, but the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. -@param dst output image of the same size and type as src. -@param ksize Gaussian kernel size. ksize.width and ksize.height can differ but they both must be -positive and odd. Or, they can be zero's and then they are computed from sigma. -@param sigmaX Gaussian kernel standard deviation in X direction. -@param sigmaY Gaussian kernel standard deviation in Y direction; if sigmaY is zero, it is set to be -equal to sigmaX, if both sigmas are zeros, they are computed from ksize.width and ksize.height, -respectively (see #getGaussianKernel for details); to fully control the result regardless of -possible future modifications of all this semantics, it is recommended to specify all of ksize, -sigmaX, and sigmaY. -@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. -@param hint Implementation modfication flags. See #AlgorithmHint - -@sa sepFilter2D, filter2D, blur, boxFilter, bilateralFilter, medianBlur - */ -CV_EXPORTS_W void GaussianBlur( InputArray src, OutputArray dst, Size ksize, - double sigmaX, double sigmaY = 0, - int borderType = BORDER_DEFAULT, - AlgorithmHint hint = cv::ALGO_HINT_DEFAULT ); - -/** @brief Applies the bilateral filter to an image. - -The function applies bilateral filtering to the input image, as described in -http://www.dai.ed.ac.uk/CVonline/LOCAL_COPIES/MANDUCHI1/Bilateral_Filtering.html -bilateralFilter can reduce unwanted noise very well while keeping edges fairly sharp. However, it is -very slow compared to most filters. - -_Sigma values_: For simplicity, you can set the 2 sigma values to be the same. If they are small (\< -10), the filter will not have much effect, whereas if they are large (\> 150), they will have a very -strong effect, making the image look "cartoonish". - -_Filter size_: Large filters (d \> 5) are very slow, so it is recommended to use d=5 for real-time -applications, and perhaps d=9 for offline applications that need heavy noise filtering. - -This filter does not work inplace. -@param src Source 8-bit or floating-point, 1-channel or 3-channel image. -@param dst Destination image of the same size and type as src . -@param d Diameter of each pixel neighborhood that is used during filtering. If it is non-positive, -it is computed from sigmaSpace. -@param sigmaColor Filter sigma in the color space. A larger value of the parameter means that -farther colors within the pixel neighborhood (see sigmaSpace) will be mixed together, resulting -in larger areas of semi-equal color. -@param sigmaSpace Filter sigma in the coordinate space. A larger value of the parameter means that -farther pixels will influence each other as long as their colors are close enough (see sigmaColor -). When d\>0, it specifies the neighborhood size regardless of sigmaSpace. Otherwise, d is -proportional to sigmaSpace. -@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes - */ -CV_EXPORTS_W void bilateralFilter( InputArray src, OutputArray dst, int d, - double sigmaColor, double sigmaSpace, - int borderType = BORDER_DEFAULT ); - -/** @brief Blurs an image using the box filter. - -The function smooths an image using the kernel: - -\f[\texttt{K} = \alpha \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \end{bmatrix}\f] - -where - -\f[\alpha = \begin{cases} \frac{1}{\texttt{ksize.width*ksize.height}} & \texttt{when } \texttt{normalize=true} \\1 & \texttt{otherwise}\end{cases}\f] - -Unnormalized box filter is useful for computing various integral characteristics over each pixel -neighborhood, such as covariance matrices of image derivatives (used in dense optical flow -algorithms, and so on). If you need to compute pixel sums over variable-size windows, use #integral. - -@param src input image. -@param dst output image of the same size and type as src. -@param ddepth the output image depth (-1 to use src.depth()). -@param ksize blurring kernel size. -@param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel -center. -@param normalize flag, specifying whether the kernel is normalized by its area or not. -@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes. #BORDER_WRAP is not supported. -@sa blur, bilateralFilter, GaussianBlur, medianBlur, integral - */ -CV_EXPORTS_W void boxFilter( InputArray src, OutputArray dst, int ddepth, - Size ksize, Point anchor = Point(-1,-1), - bool normalize = true, - int borderType = BORDER_DEFAULT ); - -/** @brief Calculates the normalized sum of squares of the pixel values overlapping the filter. - -For every pixel \f$ (x, y) \f$ in the source image, the function calculates the sum of squares of those neighboring -pixel values which overlap the filter placed over the pixel \f$ (x, y) \f$. - -The unnormalized square box filter can be useful in computing local image statistics such as the local -variance and standard deviation around the neighborhood of a pixel. - -@param src input image -@param dst output image of the same size and type as src -@param ddepth the output image depth (-1 to use src.depth()) -@param ksize kernel size -@param anchor kernel anchor point. The default value of Point(-1, -1) denotes that the anchor is at the kernel -center. -@param normalize flag, specifying whether the kernel is to be normalized by it's area or not. -@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes. #BORDER_WRAP is not supported. -@sa boxFilter -*/ -CV_EXPORTS_W void sqrBoxFilter( InputArray src, OutputArray dst, int ddepth, - Size ksize, Point anchor = Point(-1, -1), - bool normalize = true, - int borderType = BORDER_DEFAULT ); - -/** @brief Blurs an image using the normalized box filter. - -The function smooths an image using the kernel: - -\f[\texttt{K} = \frac{1}{\texttt{ksize.width*ksize.height}} \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \end{bmatrix}\f] - -The call `blur(src, dst, ksize, anchor, borderType)` is equivalent to `boxFilter(src, dst, src.type(), ksize, -anchor, true, borderType)`. - -@param src input image; it can have any number of channels, which are processed independently, but -the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. -@param dst output image of the same size and type as src. -@param ksize blurring kernel size. -@param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel -center. -@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes. #BORDER_WRAP is not supported. -@sa boxFilter, bilateralFilter, GaussianBlur, medianBlur - */ -CV_EXPORTS_W void blur( InputArray src, OutputArray dst, - Size ksize, Point anchor = Point(-1,-1), - int borderType = BORDER_DEFAULT ); - -/** @brief Blurs an image using the stackBlur. - -The function applies and stackBlur to an image. -stackBlur can generate similar results as Gaussian blur, and the time consumption does not increase with the increase of kernel size. -It creates a kind of moving stack of colors whilst scanning through the image. Thereby it just has to add one new block of color to the right side -of the stack and remove the leftmost color. The remaining colors on the topmost layer of the stack are either added on or reduced by one, -depending on if they are on the right or on the left side of the stack. The only supported borderType is BORDER_REPLICATE. -Original paper was proposed by Mario Klingemann, which can be found http://underdestruction.com/2004/02/25/stackblur-2004. - -@param src input image. The number of channels can be arbitrary, but the depth should be one of -CV_8U, CV_16U, CV_16S or CV_32F. -@param dst output image of the same size and type as src. -@param ksize stack-blurring kernel size. The ksize.width and ksize.height can differ but they both must be -positive and odd. -*/ -CV_EXPORTS_W void stackBlur(InputArray src, OutputArray dst, Size ksize); - -/** @brief Convolves an image with the kernel. - -The function applies an arbitrary linear filter to an image. In-place operation is supported. When -the aperture is partially outside the image, the function interpolates outlier pixel values -according to the specified border mode. - -The function does actually compute correlation, not the convolution: - -\f[\texttt{dst} (x,y) = \sum _{ \substack{0\leq x' < \texttt{kernel.cols}\\{0\leq y' < \texttt{kernel.rows}}}} \texttt{kernel} (x',y')* \texttt{src} (x+x'- \texttt{anchor.x} ,y+y'- \texttt{anchor.y} )\f] - -That is, the kernel is not mirrored around the anchor point. If you need a real convolution, flip -the kernel using #flip and set the new anchor to `(kernel.cols - anchor.x - 1, kernel.rows - -anchor.y - 1)`. - -The function uses the DFT-based algorithm in case of sufficiently large kernels (~`11 x 11` or -larger) and the direct algorithm for small kernels. - -@param src input image. -@param dst output image of the same size and the same number of channels as src. -@param ddepth desired depth of the destination image, see @ref filter_depths "combinations" -@param kernel convolution kernel (or rather a correlation kernel), a single-channel floating point -matrix; if you want to apply different kernels to different channels, split the image into -separate color planes using split and process them individually. -@param anchor anchor of the kernel that indicates the relative position of a filtered point within -the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor -is at the kernel center. -@param delta optional value added to the filtered pixels before storing them in dst. -@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. -@sa sepFilter2D, dft, matchTemplate - */ -CV_EXPORTS_W void filter2D( InputArray src, OutputArray dst, int ddepth, - InputArray kernel, Point anchor = Point(-1,-1), - double delta = 0, int borderType = BORDER_DEFAULT ); - -/** @brief Applies a separable linear filter to an image. - -The function applies a separable linear filter to the image. That is, first, every row of src is -filtered with the 1D kernel kernelX. Then, every column of the result is filtered with the 1D -kernel kernelY. The final result shifted by delta is stored in dst . - -@param src Source image. -@param dst Destination image of the same size and the same number of channels as src . -@param ddepth Destination image depth, see @ref filter_depths "combinations" -@param kernelX Coefficients for filtering each row. -@param kernelY Coefficients for filtering each column. -@param anchor Anchor position within the kernel. The default value \f$(-1,-1)\f$ means that the anchor -is at the kernel center. -@param delta Value added to the filtered results before storing them. -@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. -@sa filter2D, Sobel, GaussianBlur, boxFilter, blur - */ -CV_EXPORTS_W void sepFilter2D( InputArray src, OutputArray dst, int ddepth, - InputArray kernelX, InputArray kernelY, - Point anchor = Point(-1,-1), - double delta = 0, int borderType = BORDER_DEFAULT ); - -/** @example samples/cpp/tutorial_code/ImgTrans/Sobel_Demo.cpp -Sample code using Sobel and/or Scharr OpenCV functions to make a simple Edge Detector -![Sample screenshot](Sobel_Derivatives_Tutorial_Result.jpg) -Check @ref tutorial_sobel_derivatives "the corresponding tutorial" for more details -*/ - -/** @brief Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator. - -In all cases except one, the \f$\texttt{ksize} \times \texttt{ksize}\f$ separable kernel is used to -calculate the derivative. When \f$\texttt{ksize = 1}\f$, the \f$3 \times 1\f$ or \f$1 \times 3\f$ -kernel is used (that is, no Gaussian smoothing is done). `ksize = 1` can only be used for the first -or the second x- or y- derivatives. - -There is also the special value `ksize = #FILTER_SCHARR (-1)` that corresponds to the \f$3\times3\f$ Scharr -filter that may give more accurate results than the \f$3\times3\f$ Sobel. The Scharr aperture is - -\f[\vecthreethree{-3}{0}{3}{-10}{0}{10}{-3}{0}{3}\f] - -for the x-derivative, or transposed for the y-derivative. - -The function calculates an image derivative by convolving the image with the appropriate kernel: - -\f[\texttt{dst} = \frac{\partial^{xorder+yorder} \texttt{src}}{\partial x^{xorder} \partial y^{yorder}}\f] - -The Sobel operators combine Gaussian smoothing and differentiation, so the result is more or less -resistant to the noise. Most often, the function is called with ( xorder = 1, yorder = 0, ksize = 3) -or ( xorder = 0, yorder = 1, ksize = 3) to calculate the first x- or y- image derivative. The first -case corresponds to a kernel of: - -\f[\vecthreethree{-1}{0}{1}{-2}{0}{2}{-1}{0}{1}\f] - -The second case corresponds to a kernel of: - -\f[\vecthreethree{-1}{-2}{-1}{0}{0}{0}{1}{2}{1}\f] - -@param src input image. -@param dst output image of the same size and the same number of channels as src . -@param ddepth output image depth, see @ref filter_depths "combinations"; in the case of - 8-bit input images it will result in truncated derivatives. -@param dx order of the derivative x. -@param dy order of the derivative y. -@param ksize size of the extended Sobel kernel; it must be 1, 3, 5, or 7. -@param scale optional scale factor for the computed derivative values; by default, no scaling is -applied (see #getDerivKernels for details). -@param delta optional delta value that is added to the results prior to storing them in dst. -@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. -@sa Scharr, Laplacian, sepFilter2D, filter2D, GaussianBlur, cartToPolar - */ -CV_EXPORTS_W void Sobel( InputArray src, OutputArray dst, int ddepth, - int dx, int dy, int ksize = 3, - double scale = 1, double delta = 0, - int borderType = BORDER_DEFAULT ); - -/** @brief Calculates the first order image derivative in both x and y using a Sobel operator - -Equivalent to calling: - -@code -Sobel( src, dx, CV_16SC1, 1, 0, 3 ); -Sobel( src, dy, CV_16SC1, 0, 1, 3 ); -@endcode - -@param src input image. -@param dx output image with first-order derivative in x. -@param dy output image with first-order derivative in y. -@param ksize size of Sobel kernel. It must be 3. -@param borderType pixel extrapolation method, see #BorderTypes. - Only #BORDER_DEFAULT=#BORDER_REFLECT_101 and #BORDER_REPLICATE are supported. - -@sa Sobel - */ - -CV_EXPORTS_W void spatialGradient( InputArray src, OutputArray dx, - OutputArray dy, int ksize = 3, - int borderType = BORDER_DEFAULT ); - -/** @brief Calculates the first x- or y- image derivative using Scharr operator. - -The function computes the first x- or y- spatial image derivative using the Scharr operator. The -call - -\f[\texttt{Scharr(src, dst, ddepth, dx, dy, scale, delta, borderType)}\f] - -is equivalent to - -\f[\texttt{Sobel(src, dst, ddepth, dx, dy, FILTER_SCHARR, scale, delta, borderType)} .\f] - -@param src input image. -@param dst output image of the same size and the same number of channels as src. -@param ddepth output image depth, see @ref filter_depths "combinations" -@param dx order of the derivative x. -@param dy order of the derivative y. -@param scale optional scale factor for the computed derivative values; by default, no scaling is -applied (see #getDerivKernels for details). -@param delta optional delta value that is added to the results prior to storing them in dst. -@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. -@sa cartToPolar - */ -CV_EXPORTS_W void Scharr( InputArray src, OutputArray dst, int ddepth, - int dx, int dy, double scale = 1, double delta = 0, - int borderType = BORDER_DEFAULT ); - -/** @example samples/cpp/laplace.cpp -An example using Laplace transformations for edge detection -*/ - -/** @brief Calculates the Laplacian of an image. - -The function calculates the Laplacian of the source image by adding up the second x and y -derivatives calculated using the Sobel operator: - -\f[\texttt{dst} = \Delta \texttt{src} = \frac{\partial^2 \texttt{src}}{\partial x^2} + \frac{\partial^2 \texttt{src}}{\partial y^2}\f] - -This is done when `ksize > 1`. When `ksize == 1`, the Laplacian is computed by filtering the image -with the following \f$3 \times 3\f$ aperture: - -\f[\vecthreethree {0}{1}{0}{1}{-4}{1}{0}{1}{0}\f] - -@param src Source image. -@param dst Destination image of the same size and the same number of channels as src . -@param ddepth Desired depth of the destination image, see @ref filter_depths "combinations". -@param ksize Aperture size used to compute the second-derivative filters. See #getDerivKernels for -details. The size must be positive and odd. -@param scale Optional scale factor for the computed Laplacian values. By default, no scaling is -applied. See #getDerivKernels for details. -@param delta Optional delta value that is added to the results prior to storing them in dst . -@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. -@sa Sobel, Scharr - */ -CV_EXPORTS_W void Laplacian( InputArray src, OutputArray dst, int ddepth, - int ksize = 1, double scale = 1, double delta = 0, - int borderType = BORDER_DEFAULT ); - -//! @} imgproc_filter - -//! @addtogroup imgproc_feature -//! @{ - -/** @example samples/cpp/edge.cpp -This program demonstrates usage of the Canny edge detector - -Check @ref tutorial_canny_detector "the corresponding tutorial" for more details -*/ - -/** @brief Finds edges in an image using the Canny algorithm @cite Canny86 . - -The function finds edges in the input image and marks them in the output map edges using the -Canny algorithm. The smallest value between threshold1 and threshold2 is used for edge linking. The -largest value is used to find initial segments of strong edges. See - - -@param image 8-bit input image. -@param edges output edge map; single channels 8-bit image, which has the same size as image . -@param threshold1 first threshold for the hysteresis procedure. -@param threshold2 second threshold for the hysteresis procedure. -@param apertureSize aperture size for the Sobel operator. -@param L2gradient a flag, indicating whether a more accurate \f$L_2\f$ norm -\f$=\sqrt{(dI/dx)^2 + (dI/dy)^2}\f$ should be used to calculate the image gradient magnitude ( -L2gradient=true ), or whether the default \f$L_1\f$ norm \f$=|dI/dx|+|dI/dy|\f$ is enough ( -L2gradient=false ). - */ -CV_EXPORTS_W void Canny( InputArray image, OutputArray edges, - double threshold1, double threshold2, - int apertureSize = 3, bool L2gradient = false ); - -/** \overload - -Finds edges in an image using the Canny algorithm with custom image gradient. - -@param dx 16-bit x derivative of input image (CV_16SC1 or CV_16SC3). -@param dy 16-bit y derivative of input image (same type as dx). -@param edges output edge map; single channels 8-bit image, which has the same size as image . -@param threshold1 first threshold for the hysteresis procedure. -@param threshold2 second threshold for the hysteresis procedure. -@param L2gradient a flag, indicating whether a more accurate \f$L_2\f$ norm -\f$=\sqrt{(dI/dx)^2 + (dI/dy)^2}\f$ should be used to calculate the image gradient magnitude ( -L2gradient=true ), or whether the default \f$L_1\f$ norm \f$=|dI/dx|+|dI/dy|\f$ is enough ( -L2gradient=false ). - */ -CV_EXPORTS_W void Canny( InputArray dx, InputArray dy, - OutputArray edges, - double threshold1, double threshold2, - bool L2gradient = false ); - -/** @brief Calculates the minimal eigenvalue of gradient matrices for corner detection. - -The function is similar to cornerEigenValsAndVecs but it calculates and stores only the minimal -eigenvalue of the covariance matrix of derivatives, that is, \f$\min(\lambda_1, \lambda_2)\f$ in terms -of the formulae in the cornerEigenValsAndVecs description. - -@param src Input single-channel 8-bit or floating-point image. -@param dst Image to store the minimal eigenvalues. It has the type CV_32FC1 and the same size as -src . -@param blockSize Neighborhood size (see the details on #cornerEigenValsAndVecs ). -@param ksize Aperture parameter for the Sobel operator. -@param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported. - */ -CV_EXPORTS_W void cornerMinEigenVal( InputArray src, OutputArray dst, - int blockSize, int ksize = 3, - int borderType = BORDER_DEFAULT ); - -/** @brief Harris corner detector. - -The function runs the Harris corner detector on the image. Similarly to cornerMinEigenVal and -cornerEigenValsAndVecs , for each pixel \f$(x, y)\f$ it calculates a \f$2\times2\f$ gradient covariance -matrix \f$M^{(x,y)}\f$ over a \f$\texttt{blockSize} \times \texttt{blockSize}\f$ neighborhood. Then, it -computes the following characteristic: - -\f[\texttt{dst} (x,y) = \mathrm{det} M^{(x,y)} - k \cdot \left ( \mathrm{tr} M^{(x,y)} \right )^2\f] - -Corners in the image can be found as the local maxima of this response map. - -@param src Input single-channel 8-bit or floating-point image. -@param dst Image to store the Harris detector responses. It has the type CV_32FC1 and the same -size as src . -@param blockSize Neighborhood size (see the details on #cornerEigenValsAndVecs ). -@param ksize Aperture parameter for the Sobel operator. -@param k Harris detector free parameter. See the formula above. -@param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported. - */ -CV_EXPORTS_W void cornerHarris( InputArray src, OutputArray dst, int blockSize, - int ksize, double k, - int borderType = BORDER_DEFAULT ); - -/** @brief Calculates eigenvalues and eigenvectors of image blocks for corner detection. - -For every pixel \f$p\f$ , the function cornerEigenValsAndVecs considers a blockSize \f$\times\f$ blockSize -neighborhood \f$S(p)\f$ . It calculates the covariation matrix of derivatives over the neighborhood as: - -\f[M = \begin{bmatrix} \sum _{S(p)}(dI/dx)^2 & \sum _{S(p)}dI/dx dI/dy \\ \sum _{S(p)}dI/dx dI/dy & \sum _{S(p)}(dI/dy)^2 \end{bmatrix}\f] - -where the derivatives are computed using the Sobel operator. - -After that, it finds eigenvectors and eigenvalues of \f$M\f$ and stores them in the destination image as -\f$(\lambda_1, \lambda_2, x_1, y_1, x_2, y_2)\f$ where - -- \f$\lambda_1, \lambda_2\f$ are the non-sorted eigenvalues of \f$M\f$ -- \f$x_1, y_1\f$ are the eigenvectors corresponding to \f$\lambda_1\f$ -- \f$x_2, y_2\f$ are the eigenvectors corresponding to \f$\lambda_2\f$ - -The output of the function can be used for robust edge or corner detection. - -@param src Input single-channel 8-bit or floating-point image. -@param dst Image to store the results. It has the same size as src and the type CV_32FC(6) . -@param blockSize Neighborhood size (see details below). -@param ksize Aperture parameter for the Sobel operator. -@param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported. - -@sa cornerMinEigenVal, cornerHarris, preCornerDetect - */ -CV_EXPORTS_W void cornerEigenValsAndVecs( InputArray src, OutputArray dst, - int blockSize, int ksize, - int borderType = BORDER_DEFAULT ); - -/** @brief Calculates a feature map for corner detection. - -The function calculates the complex spatial derivative-based function of the source image - -\f[\texttt{dst} = (D_x \texttt{src} )^2 \cdot D_{yy} \texttt{src} + (D_y \texttt{src} )^2 \cdot D_{xx} \texttt{src} - 2 D_x \texttt{src} \cdot D_y \texttt{src} \cdot D_{xy} \texttt{src}\f] - -where \f$D_x\f$,\f$D_y\f$ are the first image derivatives, \f$D_{xx}\f$,\f$D_{yy}\f$ are the second image -derivatives, and \f$D_{xy}\f$ is the mixed derivative. - -The corners can be found as local maximums of the functions, as shown below: -@code - Mat corners, dilated_corners; - preCornerDetect(image, corners, 3); - // dilation with 3x3 rectangular structuring element - dilate(corners, dilated_corners, Mat(), 1); - Mat corner_mask = corners == dilated_corners; -@endcode - -@param src Source single-channel 8-bit of floating-point image. -@param dst Output image that has the type CV_32F and the same size as src . -@param ksize %Aperture size of the Sobel . -@param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported. - */ -CV_EXPORTS_W void preCornerDetect( InputArray src, OutputArray dst, int ksize, - int borderType = BORDER_DEFAULT ); - -/** @brief Refines the corner locations. - -The function iterates to find the sub-pixel accurate location of corners or radial saddle -points as described in @cite forstner1987fast, and as shown on the figure below. - -![image](pics/cornersubpix.png) - -Sub-pixel accurate corner locator is based on the observation that every vector from the center \f$q\f$ -to a point \f$p\f$ located within a neighborhood of \f$q\f$ is orthogonal to the image gradient at \f$p\f$ -subject to image and measurement noise. Consider the expression: - -\f[\epsilon _i = {DI_{p_i}}^T \cdot (q - p_i)\f] - -where \f${DI_{p_i}}\f$ is an image gradient at one of the points \f$p_i\f$ in a neighborhood of \f$q\f$ . The -value of \f$q\f$ is to be found so that \f$\epsilon_i\f$ is minimized. A system of equations may be set up -with \f$\epsilon_i\f$ set to zero: - -\f[\sum _i(DI_{p_i} \cdot {DI_{p_i}}^T) \cdot q - \sum _i(DI_{p_i} \cdot {DI_{p_i}}^T \cdot p_i)\f] - -where the gradients are summed within a neighborhood ("search window") of \f$q\f$ . Calling the first -gradient term \f$G\f$ and the second gradient term \f$b\f$ gives: - -\f[q = G^{-1} \cdot b\f] - -The algorithm sets the center of the neighborhood window at this new center \f$q\f$ and then iterates -until the center stays within a set threshold. - -@param image Input single-channel, 8-bit or float image. -@param corners Initial coordinates of the input corners and refined coordinates provided for -output. -@param winSize Half of the side length of the search window. For example, if winSize=Size(5,5) , -then a \f$(5*2+1) \times (5*2+1) = 11 \times 11\f$ search window is used. -@param zeroZone Half of the size of the dead region in the middle of the search zone over which -the summation in the formula below is not done. It is used sometimes to avoid possible -singularities of the autocorrelation matrix. The value of (-1,-1) indicates that there is no such -a size. -@param criteria Criteria for termination of the iterative process of corner refinement. That is, -the process of corner position refinement stops either after criteria.maxCount iterations or when -the corner position moves by less than criteria.epsilon on some iteration. - */ -CV_EXPORTS_W void cornerSubPix( InputArray image, InputOutputArray corners, - Size winSize, Size zeroZone, - TermCriteria criteria ); - -/** @brief Determines strong corners on an image. - -The function finds the most prominent corners in the image or in the specified image region, as -described in @cite Shi94 - -- Function calculates the corner quality measure at every source image pixel using the - #cornerMinEigenVal or #cornerHarris . -- Function performs a non-maximum suppression (the local maximums in *3 x 3* neighborhood are - retained). -- The corners with the minimal eigenvalue less than - \f$\texttt{qualityLevel} \cdot \max_{x,y} qualityMeasureMap(x,y)\f$ are rejected. -- The remaining corners are sorted by the quality measure in the descending order. -- Function throws away each corner for which there is a stronger corner at a distance less than - maxDistance. - -The function can be used to initialize a point-based tracker of an object. - -@note If the function is called with different values A and B of the parameter qualityLevel , and -A \> B, the vector of returned corners with qualityLevel=A will be the prefix of the output vector -with qualityLevel=B . - -@param image Input 8-bit or floating-point 32-bit, single-channel image. -@param corners Output vector of detected corners. -@param maxCorners Maximum number of corners to return. If there are more corners than are found, -the strongest of them is returned. `maxCorners <= 0` implies that no limit on the maximum is set -and all detected corners are returned. -@param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The -parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue -(see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the -quality measure less than the product are rejected. For example, if the best corner has the -quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure -less than 15 are rejected. -@param minDistance Minimum possible Euclidean distance between the returned corners. -@param mask Optional region of interest. If the image is not empty (it needs to have the type -CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. -@param blockSize Size of an average block for computing a derivative covariation matrix over each -pixel neighborhood. See cornerEigenValsAndVecs . -@param useHarrisDetector Parameter indicating whether to use a Harris detector (see #cornerHarris) -or #cornerMinEigenVal. -@param k Free parameter of the Harris detector. - -@sa cornerMinEigenVal, cornerHarris, calcOpticalFlowPyrLK, estimateRigidTransform, - */ - -CV_EXPORTS_W void goodFeaturesToTrack( InputArray image, OutputArray corners, - int maxCorners, double qualityLevel, double minDistance, - InputArray mask = noArray(), int blockSize = 3, - bool useHarrisDetector = false, double k = 0.04 ); - -CV_EXPORTS_W void goodFeaturesToTrack( InputArray image, OutputArray corners, - int maxCorners, double qualityLevel, double minDistance, - InputArray mask, int blockSize, - int gradientSize, bool useHarrisDetector = false, - double k = 0.04 ); - -/** @brief Same as above, but returns also quality measure of the detected corners. - -@param image Input 8-bit or floating-point 32-bit, single-channel image. -@param corners Output vector of detected corners. -@param maxCorners Maximum number of corners to return. If there are more corners than are found, -the strongest of them is returned. `maxCorners <= 0` implies that no limit on the maximum is set -and all detected corners are returned. -@param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The -parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue -(see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the -quality measure less than the product are rejected. For example, if the best corner has the -quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure -less than 15 are rejected. -@param minDistance Minimum possible Euclidean distance between the returned corners. -@param mask Region of interest. If the image is not empty (it needs to have the type -CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. -@param cornersQuality Output vector of quality measure of the detected corners. -@param blockSize Size of an average block for computing a derivative covariation matrix over each -pixel neighborhood. See cornerEigenValsAndVecs . -@param gradientSize Aperture parameter for the Sobel operator used for derivatives computation. -See cornerEigenValsAndVecs . -@param useHarrisDetector Parameter indicating whether to use a Harris detector (see #cornerHarris) -or #cornerMinEigenVal. -@param k Free parameter of the Harris detector. - */ -CV_EXPORTS CV_WRAP_AS(goodFeaturesToTrackWithQuality) void goodFeaturesToTrack( - InputArray image, OutputArray corners, - int maxCorners, double qualityLevel, double minDistance, - InputArray mask, OutputArray cornersQuality, int blockSize = 3, - int gradientSize = 3, bool useHarrisDetector = false, double k = 0.04); - -/** @example samples/cpp/tutorial_code/ImgTrans/houghlines.cpp -An example using the Hough line detector -![Sample input image](Hough_Lines_Tutorial_Original_Image.jpg) ![Output image](Hough_Lines_Tutorial_Result.jpg) -*/ - -/** @brief Finds lines in a binary image using the standard Hough transform. - -The function implements the standard or standard multi-scale Hough transform algorithm for line -detection. See for a good explanation of Hough -transform. - -@param image 8-bit, single-channel binary source image. The image may be modified by the function. -@param lines Output vector of lines. Each line is represented by a 2 or 3 element vector -\f$(\rho, \theta)\f$ or \f$(\rho, \theta, \textrm{votes})\f$, where \f$\rho\f$ is the distance from -the coordinate origin \f$(0,0)\f$ (top-left corner of the image), \f$\theta\f$ is the line rotation -angle in radians ( \f$0 \sim \textrm{vertical line}, \pi/2 \sim \textrm{horizontal line}\f$ ), and -\f$\textrm{votes}\f$ is the value of accumulator. -@param rho Distance resolution of the accumulator in pixels. -@param theta Angle resolution of the accumulator in radians. -@param threshold %Accumulator threshold parameter. Only those lines are returned that get enough -votes ( \f$>\texttt{threshold}\f$ ). -@param srn For the multi-scale Hough transform, it is a divisor for the distance resolution rho. -The coarse accumulator distance resolution is rho and the accurate accumulator resolution is -rho/srn. If both srn=0 and stn=0, the classical Hough transform is used. Otherwise, both these -parameters should be positive. -@param stn For the multi-scale Hough transform, it is a divisor for the distance resolution theta. -@param min_theta For standard and multi-scale Hough transform, minimum angle to check for lines. -Must fall between 0 and max_theta. -@param max_theta For standard and multi-scale Hough transform, an upper bound for the angle. -Must fall between min_theta and CV_PI. The actual maximum angle in the accumulator may be slightly -less than max_theta, depending on the parameters min_theta and theta. -@param use_edgeval True if you want to use weighted Hough transform. - */ -CV_EXPORTS_W void HoughLines( InputArray image, OutputArray lines, - double rho, double theta, int threshold, - double srn = 0, double stn = 0, - double min_theta = 0, double max_theta = CV_PI, - bool use_edgeval = false ); - -/** @brief Finds line segments in a binary image using the probabilistic Hough transform. - -The function implements the probabilistic Hough transform algorithm for line detection, described -in @cite Matas00 - -See the line detection example below: -@include snippets/imgproc_HoughLinesP.cpp -This is a sample picture the function parameters have been tuned for: - -![image](pics/building.jpg) - -And this is the output of the above program in case of the probabilistic Hough transform: - -![image](pics/houghp.png) - -@param image 8-bit, single-channel binary source image. The image may be modified by the function. -@param lines Output vector of lines. Each line is represented by a 4-element vector -\f$(x_1, y_1, x_2, y_2)\f$ , where \f$(x_1,y_1)\f$ and \f$(x_2, y_2)\f$ are the ending points of each detected -line segment. -@param rho Distance resolution of the accumulator in pixels. -@param theta Angle resolution of the accumulator in radians. -@param threshold %Accumulator threshold parameter. Only those lines are returned that get enough -votes ( \f$>\texttt{threshold}\f$ ). -@param minLineLength Minimum line length. Line segments shorter than that are rejected. -@param maxLineGap Maximum allowed gap between points on the same line to link them. - -@sa LineSegmentDetector - */ -CV_EXPORTS_W void HoughLinesP( InputArray image, OutputArray lines, - double rho, double theta, int threshold, - double minLineLength = 0, double maxLineGap = 0 ); - -/** @brief Finds lines in a set of points using the standard Hough transform. - -The function finds lines in a set of points using a modification of the Hough transform. -@include snippets/imgproc_HoughLinesPointSet.cpp -@param point Input vector of points. Each vector must be encoded as a Point vector \f$(x,y)\f$. Type must be CV_32FC2 or CV_32SC2. -@param lines Output vector of found lines. Each vector is encoded as a vector \f$(votes, rho, theta)\f$. -The larger the value of 'votes', the higher the reliability of the Hough line. -@param lines_max Max count of Hough lines. -@param threshold %Accumulator threshold parameter. Only those lines are returned that get enough -votes ( \f$>\texttt{threshold}\f$ ). -@param min_rho Minimum value for \f$\rho\f$ for the accumulator (Note: \f$\rho\f$ can be negative. The absolute value \f$|\rho|\f$ is the distance of a line to the origin.). -@param max_rho Maximum value for \f$\rho\f$ for the accumulator. -@param rho_step Distance resolution of the accumulator. -@param min_theta Minimum angle value of the accumulator in radians. -@param max_theta Upper bound for the angle value of the accumulator in radians. The actual maximum -angle may be slightly less than max_theta, depending on the parameters min_theta and theta_step. -@param theta_step Angle resolution of the accumulator in radians. - */ -CV_EXPORTS_W void HoughLinesPointSet( InputArray point, OutputArray lines, int lines_max, int threshold, - double min_rho, double max_rho, double rho_step, - double min_theta, double max_theta, double theta_step ); - -/** @example samples/cpp/tutorial_code/ImgTrans/houghcircles.cpp -An example using the Hough circle detector -*/ - -/** @brief Finds circles in a grayscale image using the Hough transform. - -The function finds circles in a grayscale image using a modification of the Hough transform. - -Example: : -@include snippets/imgproc_HoughLinesCircles.cpp - -@note Usually the function detects the centers of circles well. However, it may fail to find correct -radii. You can assist to the function by specifying the radius range ( minRadius and maxRadius ) if -you know it. Or, in the case of #HOUGH_GRADIENT method you may set maxRadius to a negative number -to return centers only without radius search, and find the correct radius using an additional procedure. - -It also helps to smooth image a bit unless it's already soft. For example, -GaussianBlur() with 7x7 kernel and 1.5x1.5 sigma or similar blurring may help. - -@param image 8-bit, single-channel, grayscale input image. -@param circles Output vector of found circles. Each vector is encoded as 3 or 4 element -floating-point vector \f$(x, y, radius)\f$ or \f$(x, y, radius, votes)\f$ . -@param method Detection method, see #HoughModes. The available methods are #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT. -@param dp Inverse ratio of the accumulator resolution to the image resolution. For example, if -dp=1 , the accumulator has the same resolution as the input image. If dp=2 , the accumulator has -half as big width and height. For #HOUGH_GRADIENT_ALT the recommended value is dp=1.5, -unless some small very circles need to be detected. -@param minDist Minimum distance between the centers of the detected circles. If the parameter is -too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is -too large, some circles may be missed. -@param param1 First method-specific parameter. In case of #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT, -it is the higher threshold of the two passed to the Canny edge detector (the lower one is twice smaller). -Note that #HOUGH_GRADIENT_ALT uses #Scharr algorithm to compute image derivatives, so the threshold value -should normally be higher, such as 300 or normally exposed and contrasty images. -@param param2 Second method-specific parameter. In case of #HOUGH_GRADIENT, it is the -accumulator threshold for the circle centers at the detection stage. The smaller it is, the more -false circles may be detected. Circles, corresponding to the larger accumulator values, will be -returned first. In the case of #HOUGH_GRADIENT_ALT algorithm, this is the circle "perfectness" measure. -The closer it to 1, the better shaped circles algorithm selects. In most cases 0.9 should be fine. -If you want get better detection of small circles, you may decrease it to 0.85, 0.8 or even less. -But then also try to limit the search range [minRadius, maxRadius] to avoid many false circles. -@param minRadius Minimum circle radius. -@param maxRadius Maximum circle radius. If <= 0, uses the maximum image dimension. If < 0, #HOUGH_GRADIENT returns -centers without finding the radius. #HOUGH_GRADIENT_ALT always computes circle radiuses. - -@sa fitEllipse, minEnclosingCircle - */ -CV_EXPORTS_W void HoughCircles( InputArray image, OutputArray circles, - int method, double dp, double minDist, - double param1 = 100, double param2 = 100, - int minRadius = 0, int maxRadius = 0 ); - -//! @} imgproc_feature - -//! @addtogroup imgproc_filter -//! @{ - -/** @example samples/cpp/tutorial_code/ImgProc/Morphology_2.cpp -Advanced morphology Transformations sample code -![Sample screenshot](Morphology_2_Tutorial_Result.jpg) -Check @ref tutorial_opening_closing_hats "the corresponding tutorial" for more details -*/ - -/** @brief Erodes an image by using a specific structuring element. - -The function erodes the source image using the specified structuring element that determines the -shape of a pixel neighborhood over which the minimum is taken: - -\f[\texttt{dst} (x,y) = \min _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f] - -The function supports the in-place mode. Erosion can be applied several ( iterations ) times. In -case of multi-channel images, each channel is processed independently. - -@param src input image; the number of channels can be arbitrary, but the depth should be one of -CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. -@param dst output image of the same size and type as src. -@param kernel structuring element used for erosion; if `element=Mat()`, a `3 x 3` rectangular -structuring element is used. Kernel can be created using #getStructuringElement. -@param anchor position of the anchor within the element; default value (-1, -1) means that the -anchor is at the element center. -@param iterations number of times erosion is applied. -@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. -@param borderValue border value in case of a constant border -@sa dilate, morphologyEx, getStructuringElement - */ -CV_EXPORTS_W void erode( InputArray src, OutputArray dst, InputArray kernel, - Point anchor = Point(-1,-1), int iterations = 1, - int borderType = BORDER_CONSTANT, - const Scalar& borderValue = morphologyDefaultBorderValue() ); - -/** @example samples/cpp/tutorial_code/ImgProc/Morphology_1.cpp -Erosion and Dilation sample code -![Sample Screenshot-Erosion](Morphology_1_Tutorial_Erosion_Result.jpg)![Sample Screenshot-Dilation](Morphology_1_Tutorial_Dilation_Result.jpg) -Check @ref tutorial_erosion_dilatation "the corresponding tutorial" for more details -*/ - -/** @brief Dilates an image by using a specific structuring element. - -The function dilates the source image using the specified structuring element that determines the -shape of a pixel neighborhood over which the maximum is taken: -\f[\texttt{dst} (x,y) = \max _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f] - -The function supports the in-place mode. Dilation can be applied several ( iterations ) times. In -case of multi-channel images, each channel is processed independently. - -@param src input image; the number of channels can be arbitrary, but the depth should be one of -CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. -@param dst output image of the same size and type as src. -@param kernel structuring element used for dilation; if element=Mat(), a 3 x 3 rectangular -structuring element is used. Kernel can be created using #getStructuringElement -@param anchor position of the anchor within the element; default value (-1, -1) means that the -anchor is at the element center. -@param iterations number of times dilation is applied. -@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not suported. -@param borderValue border value in case of a constant border -@sa erode, morphologyEx, getStructuringElement - */ -CV_EXPORTS_W void dilate( InputArray src, OutputArray dst, InputArray kernel, - Point anchor = Point(-1,-1), int iterations = 1, - int borderType = BORDER_CONSTANT, - const Scalar& borderValue = morphologyDefaultBorderValue() ); - -/** @brief Performs advanced morphological transformations. - -The function cv::morphologyEx can perform advanced morphological transformations using an erosion and dilation as -basic operations. - -Any of the operations can be done in-place. In case of multi-channel images, each channel is -processed independently. - -@param src Source image. The number of channels can be arbitrary. The depth should be one of -CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. -@param dst Destination image of the same size and type as source image. -@param op Type of a morphological operation, see #MorphTypes -@param kernel Structuring element. It can be created using #getStructuringElement. -@param anchor Anchor position with the kernel. Negative values mean that the anchor is at the -kernel center. -@param iterations Number of times erosion and dilation are applied. -@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. -@param borderValue Border value in case of a constant border. The default value has a special -meaning. -@sa dilate, erode, getStructuringElement -@note The number of iterations is the number of times erosion or dilatation operation will be applied. -For instance, an opening operation (#MORPH_OPEN) with two iterations is equivalent to apply -successively: erode -> erode -> dilate -> dilate (and not erode -> dilate -> erode -> dilate). - */ -CV_EXPORTS_W void morphologyEx( InputArray src, OutputArray dst, - int op, InputArray kernel, - Point anchor = Point(-1,-1), int iterations = 1, - int borderType = BORDER_CONSTANT, - const Scalar& borderValue = morphologyDefaultBorderValue() ); - -//! @} imgproc_filter - -//! @addtogroup imgproc_transform -//! @{ - -/** @brief Resizes an image. - -The function resize resizes the image src down to or up to the specified size. Note that the -initial dst type or size are not taken into account. Instead, the size and type are derived from -the `src`,`dsize`,`fx`, and `fy`. If you want to resize src so that it fits the pre-created dst, -you may call the function as follows: -@code - // explicitly specify dsize=dst.size(); fx and fy will be computed from that. - resize(src, dst, dst.size(), 0, 0, interpolation); -@endcode -If you want to decimate the image by factor of 2 in each direction, you can call the function this -way: -@code - // specify fx and fy and let the function compute the destination image size. - resize(src, dst, Size(), 0.5, 0.5, interpolation); -@endcode -To shrink an image, it will generally look best with #INTER_AREA interpolation, whereas to -enlarge an image, it will generally look best with #INTER_CUBIC (slow) or #INTER_LINEAR -(faster but still looks OK). - -@param src input image. -@param dst output image; it has the size dsize (when it is non-zero) or the size computed from -src.size(), fx, and fy; the type of dst is the same as of src. -@param dsize output image size; if it equals zero (`None` in Python), it is computed as: - \f[\texttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}\f] - Either dsize or both fx and fy must be non-zero. -@param fx scale factor along the horizontal axis; when it equals 0, it is computed as -\f[\texttt{(double)dsize.width/src.cols}\f] -@param fy scale factor along the vertical axis; when it equals 0, it is computed as -\f[\texttt{(double)dsize.height/src.rows}\f] -@param interpolation interpolation method, see #InterpolationFlags - -@sa warpAffine, warpPerspective, remap - */ -CV_EXPORTS_W void resize( InputArray src, OutputArray dst, - Size dsize, double fx = 0, double fy = 0, - int interpolation = INTER_LINEAR ); - -/** @brief Applies an affine transformation to an image. - -The function warpAffine transforms the source image using the specified matrix: - -\f[\texttt{dst} (x,y) = \texttt{src} ( \texttt{M} _{11} x + \texttt{M} _{12} y + \texttt{M} _{13}, \texttt{M} _{21} x + \texttt{M} _{22} y + \texttt{M} _{23})\f] - -when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted -with #invertAffineTransform and then put in the formula above instead of M. The function cannot -operate in-place. - -@param src input image. -@param dst output image that has the size dsize and the same type as src . -@param M \f$2\times 3\f$ transformation matrix. -@param dsize size of the output image. -@param flags combination of interpolation methods (see #InterpolationFlags) and the optional -flag #WARP_INVERSE_MAP that means that M is the inverse transformation ( -\f$\texttt{dst}\rightarrow\texttt{src}\f$ ). -@param borderMode pixel extrapolation method (see #BorderTypes); when -borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image corresponding to -the "outliers" in the source image are not modified by the function. -@param borderValue value used in case of a constant border; by default, it is 0. - -@sa warpPerspective, resize, remap, getRectSubPix, transform - */ -CV_EXPORTS_W void warpAffine( InputArray src, OutputArray dst, - InputArray M, Size dsize, - int flags = INTER_LINEAR, - int borderMode = BORDER_CONSTANT, - const Scalar& borderValue = Scalar()); - -/** @example samples/cpp/warpPerspective_demo.cpp -An example program shows using cv::getPerspectiveTransform and cv::warpPerspective for image warping -*/ - -/** @brief Applies a perspective transformation to an image. - -The function warpPerspective transforms the source image using the specified matrix: - -\f[\texttt{dst} (x,y) = \texttt{src} \left ( \frac{M_{11} x + M_{12} y + M_{13}}{M_{31} x + M_{32} y + M_{33}} , - \frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}} \right )\f] - -when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted with invert -and then put in the formula above instead of M. The function cannot operate in-place. - -@param src input image. -@param dst output image that has the size dsize and the same type as src . -@param M \f$3\times 3\f$ transformation matrix. -@param dsize size of the output image. -@param flags combination of interpolation methods (#INTER_LINEAR or #INTER_NEAREST) and the -optional flag #WARP_INVERSE_MAP, that sets M as the inverse transformation ( -\f$\texttt{dst}\rightarrow\texttt{src}\f$ ). -@param borderMode pixel extrapolation method (#BORDER_CONSTANT or #BORDER_REPLICATE). -@param borderValue value used in case of a constant border; by default, it equals 0. - -@sa warpAffine, resize, remap, getRectSubPix, perspectiveTransform - */ -CV_EXPORTS_W void warpPerspective( InputArray src, OutputArray dst, - InputArray M, Size dsize, - int flags = INTER_LINEAR, - int borderMode = BORDER_CONSTANT, - const Scalar& borderValue = Scalar()); - -/** @brief Applies a generic geometrical transformation to an image. - -The function remap transforms the source image using the specified map: - -\f[\texttt{dst} (x,y) = \texttt{src} (map_x(x,y),map_y(x,y))\f] - -with the WARP_RELATIVE_MAP flag : - -\f[\texttt{dst} (x,y) = \texttt{src} (x+map_x(x,y),y+map_y(x,y))\f] - -where values of pixels with non-integer coordinates are computed using one of available -interpolation methods. \f$map_x\f$ and \f$map_y\f$ can be encoded as separate floating-point maps -in \f$map_1\f$ and \f$map_2\f$ respectively, or interleaved floating-point maps of \f$(x,y)\f$ in -\f$map_1\f$, or fixed-point maps created by using #convertMaps. The reason you might want to -convert from floating to fixed-point representations of a map is that they can yield much faster -(\~2x) remapping operations. In the converted case, \f$map_1\f$ contains pairs (cvFloor(x), -cvFloor(y)) and \f$map_2\f$ contains indices in a table of interpolation coefficients. - -This function cannot operate in-place. - -@param src Source image. -@param dst Destination image. It has the same size as map1 and the same type as src . -@param map1 The first map of either (x,y) points or just x values having the type CV_16SC2 , -CV_32FC1, or CV_32FC2. See #convertMaps for details on converting a floating point -representation to fixed-point for speed. -@param map2 The second map of y values having the type CV_16UC1, CV_32FC1, or none (empty map -if map1 is (x,y) points), respectively. -@param interpolation Interpolation method (see #InterpolationFlags). The methods #INTER_AREA -#INTER_LINEAR_EXACT and #INTER_NEAREST_EXACT are not supported by this function. -The extra flag WARP_RELATIVE_MAP can be ORed to the interpolation method -(e.g. INTER_LINEAR | WARP_RELATIVE_MAP) -@param borderMode Pixel extrapolation method (see #BorderTypes). When -borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image that -corresponds to the "outliers" in the source image are not modified by the function. -@param borderValue Value used in case of a constant border. By default, it is 0. -@note -Due to current implementation limitations the size of an input and output images should be less than 32767x32767. - */ -CV_EXPORTS_W void remap( InputArray src, OutputArray dst, - InputArray map1, InputArray map2, - int interpolation, int borderMode = BORDER_CONSTANT, - const Scalar& borderValue = Scalar()); - -/** @brief Converts image transformation maps from one representation to another. - -The function converts a pair of maps for remap from one representation to another. The following -options ( (map1.type(), map2.type()) \f$\rightarrow\f$ (dstmap1.type(), dstmap2.type()) ) are -supported: - -- \f$\texttt{(CV_32FC1, CV_32FC1)} \rightarrow \texttt{(CV_16SC2, CV_16UC1)}\f$. This is the -most frequently used conversion operation, in which the original floating-point maps (see #remap) -are converted to a more compact and much faster fixed-point representation. The first output array -contains the rounded coordinates and the second array (created only when nninterpolation=false ) -contains indices in the interpolation tables. - -- \f$\texttt{(CV_32FC2)} \rightarrow \texttt{(CV_16SC2, CV_16UC1)}\f$. The same as above but -the original maps are stored in one 2-channel matrix. - -- Reverse conversion. Obviously, the reconstructed floating-point maps will not be exactly the same -as the originals. - -@param map1 The first input map of type CV_16SC2, CV_32FC1, or CV_32FC2 . -@param map2 The second input map of type CV_16UC1, CV_32FC1, or none (empty matrix), -respectively. -@param dstmap1 The first output map that has the type dstmap1type and the same size as src . -@param dstmap2 The second output map. -@param dstmap1type Type of the first output map that should be CV_16SC2, CV_32FC1, or -CV_32FC2 . -@param nninterpolation Flag indicating whether the fixed-point maps are used for the -nearest-neighbor or for a more complex interpolation. - -@sa remap, undistort, initUndistortRectifyMap - */ -CV_EXPORTS_W void convertMaps( InputArray map1, InputArray map2, - OutputArray dstmap1, OutputArray dstmap2, - int dstmap1type, bool nninterpolation = false ); - -/** @brief Calculates an affine matrix of 2D rotation. - -The function calculates the following matrix: - -\f[\begin{bmatrix} \alpha & \beta & (1- \alpha ) \cdot \texttt{center.x} - \beta \cdot \texttt{center.y} \\ - \beta & \alpha & \beta \cdot \texttt{center.x} + (1- \alpha ) \cdot \texttt{center.y} \end{bmatrix}\f] - -where - -\f[\begin{array}{l} \alpha = \texttt{scale} \cdot \cos \texttt{angle} , \\ \beta = \texttt{scale} \cdot \sin \texttt{angle} \end{array}\f] - -The transformation maps the rotation center to itself. If this is not the target, adjust the shift. - -@param center Center of the rotation in the source image. -@param angle Rotation angle in degrees. Positive values mean counter-clockwise rotation (the -coordinate origin is assumed to be the top-left corner). -@param scale Isotropic scale factor. - -@sa getAffineTransform, warpAffine, transform - */ -CV_EXPORTS_W Mat getRotationMatrix2D(Point2f center, double angle, double scale); - -/** @sa getRotationMatrix2D */ -CV_EXPORTS Matx23d getRotationMatrix2D_(Point2f center, double angle, double scale); - -inline -Mat getRotationMatrix2D(Point2f center, double angle, double scale) -{ - return Mat(getRotationMatrix2D_(center, angle, scale), true); -} - -/** @brief Calculates an affine transform from three pairs of the corresponding points. - -The function calculates the \f$2 \times 3\f$ matrix of an affine transform so that: - -\f[\begin{bmatrix} x'_i \\ y'_i \end{bmatrix} = \texttt{map_matrix} \cdot \begin{bmatrix} x_i \\ y_i \\ 1 \end{bmatrix}\f] - -where - -\f[dst(i)=(x'_i,y'_i), src(i)=(x_i, y_i), i=0,1,2\f] - -@param src Coordinates of triangle vertices in the source image. -@param dst Coordinates of the corresponding triangle vertices in the destination image. - -@sa warpAffine, transform - */ -CV_EXPORTS Mat getAffineTransform( const Point2f src[], const Point2f dst[] ); - -/** @brief Inverts an affine transformation. - -The function computes an inverse affine transformation represented by \f$2 \times 3\f$ matrix M: - -\f[\begin{bmatrix} a_{11} & a_{12} & b_1 \\ a_{21} & a_{22} & b_2 \end{bmatrix}\f] - -The result is also a \f$2 \times 3\f$ matrix of the same type as M. - -@param M Original affine transformation. -@param iM Output reverse affine transformation. - */ -CV_EXPORTS_W void invertAffineTransform( InputArray M, OutputArray iM ); - -/** @brief Calculates a perspective transform from four pairs of the corresponding points. - -The function calculates the \f$3 \times 3\f$ matrix of a perspective transform so that: - -\f[\begin{bmatrix} t_i x'_i \\ t_i y'_i \\ t_i \end{bmatrix} = \texttt{map_matrix} \cdot \begin{bmatrix} x_i \\ y_i \\ 1 \end{bmatrix}\f] - -where - -\f[dst(i)=(x'_i,y'_i), src(i)=(x_i, y_i), i=0,1,2,3\f] - -@param src Coordinates of quadrangle vertices in the source image. -@param dst Coordinates of the corresponding quadrangle vertices in the destination image. -@param solveMethod method passed to cv::solve (#DecompTypes) - -@sa findHomography, warpPerspective, perspectiveTransform - */ -CV_EXPORTS_W Mat getPerspectiveTransform(InputArray src, InputArray dst, int solveMethod = DECOMP_LU); - -/** @overload */ -CV_EXPORTS Mat getPerspectiveTransform(const Point2f src[], const Point2f dst[], int solveMethod = DECOMP_LU); - - -CV_EXPORTS_W Mat getAffineTransform( InputArray src, InputArray dst ); - -/** @brief Retrieves a pixel rectangle from an image with sub-pixel accuracy. - -The function getRectSubPix extracts pixels from src: - -\f[patch(x, y) = src(x + \texttt{center.x} - ( \texttt{dst.cols} -1)*0.5, y + \texttt{center.y} - ( \texttt{dst.rows} -1)*0.5)\f] - -where the values of the pixels at non-integer coordinates are retrieved using bilinear -interpolation. Every channel of multi-channel images is processed independently. Also -the image should be a single channel or three channel image. While the center of the -rectangle must be inside the image, parts of the rectangle may be outside. - -@param image Source image. -@param patchSize Size of the extracted patch. -@param center Floating point coordinates of the center of the extracted rectangle within the -source image. The center must be inside the image. -@param patch Extracted patch that has the size patchSize and the same number of channels as src . -@param patchType Depth of the extracted pixels. By default, they have the same depth as src . - -@sa warpAffine, warpPerspective - */ -CV_EXPORTS_W void getRectSubPix( InputArray image, Size patchSize, - Point2f center, OutputArray patch, int patchType = -1 ); - -/** @example samples/cpp/polar_transforms.cpp -An example using the cv::linearPolar and cv::logPolar operations -*/ - -/** @brief Remaps an image to semilog-polar coordinates space. - -@deprecated This function produces same result as cv::warpPolar(src, dst, src.size(), center, maxRadius, flags+WARP_POLAR_LOG); - -@internal -Transform the source image using the following transformation (See @ref polar_remaps_reference_image "Polar remaps reference image d)"): -\f[\begin{array}{l} - dst( \rho , \phi ) = src(x,y) \\ - dst.size() \leftarrow src.size() -\end{array}\f] - -where -\f[\begin{array}{l} - I = (dx,dy) = (x - center.x,y - center.y) \\ - \rho = M \cdot log_e(\texttt{magnitude} (I)) ,\\ - \phi = Kangle \cdot \texttt{angle} (I) \\ -\end{array}\f] - -and -\f[\begin{array}{l} - M = src.cols / log_e(maxRadius) \\ - Kangle = src.rows / 2\Pi \\ -\end{array}\f] - -The function emulates the human "foveal" vision and can be used for fast scale and -rotation-invariant template matching, for object tracking and so forth. -@param src Source image -@param dst Destination image. It will have same size and type as src. -@param center The transformation center; where the output precision is maximal -@param M Magnitude scale parameter. It determines the radius of the bounding circle to transform too. -@param flags A combination of interpolation methods, see #InterpolationFlags - -@note -- The function can not operate in-place. -- To calculate magnitude and angle in degrees #cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees. - -@sa cv::linearPolar -@endinternal -*/ -CV_EXPORTS_W void logPolar( InputArray src, OutputArray dst, - Point2f center, double M, int flags ); - -/** @brief Remaps an image to polar coordinates space. - -@deprecated This function produces same result as cv::warpPolar(src, dst, src.size(), center, maxRadius, flags) - -@internal -Transform the source image using the following transformation (See @ref polar_remaps_reference_image "Polar remaps reference image c)"): -\f[\begin{array}{l} - dst( \rho , \phi ) = src(x,y) \\ - dst.size() \leftarrow src.size() -\end{array}\f] - -where -\f[\begin{array}{l} - I = (dx,dy) = (x - center.x,y - center.y) \\ - \rho = Kmag \cdot \texttt{magnitude} (I) ,\\ - \phi = angle \cdot \texttt{angle} (I) -\end{array}\f] - -and -\f[\begin{array}{l} - Kx = src.cols / maxRadius \\ - Ky = src.rows / 2\Pi -\end{array}\f] - - -@param src Source image -@param dst Destination image. It will have same size and type as src. -@param center The transformation center; -@param maxRadius The radius of the bounding circle to transform. It determines the inverse magnitude scale parameter too. -@param flags A combination of interpolation methods, see #InterpolationFlags - -@note -- The function can not operate in-place. -- To calculate magnitude and angle in degrees #cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees. - -@sa cv::logPolar -@endinternal -*/ -CV_EXPORTS_W void linearPolar( InputArray src, OutputArray dst, - Point2f center, double maxRadius, int flags ); - - -/** \brief Remaps an image to polar or semilog-polar coordinates space - -@anchor polar_remaps_reference_image -![Polar remaps reference](pics/polar_remap_doc.png) - -Transform the source image using the following transformation: -\f[ -dst(\rho , \phi ) = src(x,y) -\f] - -where -\f[ -\begin{array}{l} -\vec{I} = (x - center.x, \;y - center.y) \\ -\phi = Kangle \cdot \texttt{angle} (\vec{I}) \\ -\rho = \left\{\begin{matrix} -Klin \cdot \texttt{magnitude} (\vec{I}) & default \\ -Klog \cdot log_e(\texttt{magnitude} (\vec{I})) & if \; semilog \\ -\end{matrix}\right. -\end{array} -\f] - -and -\f[ -\begin{array}{l} -Kangle = dsize.height / 2\Pi \\ -Klin = dsize.width / maxRadius \\ -Klog = dsize.width / log_e(maxRadius) \\ -\end{array} -\f] - - -\par Linear vs semilog mapping - -Polar mapping can be linear or semi-log. Add one of #WarpPolarMode to `flags` to specify the polar mapping mode. - -Linear is the default mode. - -The semilog mapping emulates the human "foveal" vision that permit very high acuity on the line of sight (central vision) -in contrast to peripheral vision where acuity is minor. - -\par Option on `dsize`: - -- if both values in `dsize <=0 ` (default), -the destination image will have (almost) same area of source bounding circle: -\f[\begin{array}{l} -dsize.area \leftarrow (maxRadius^2 \cdot \Pi) \\ -dsize.width = \texttt{cvRound}(maxRadius) \\ -dsize.height = \texttt{cvRound}(maxRadius \cdot \Pi) \\ -\end{array}\f] - - -- if only `dsize.height <= 0`, -the destination image area will be proportional to the bounding circle area but scaled by `Kx * Kx`: -\f[\begin{array}{l} -dsize.height = \texttt{cvRound}(dsize.width \cdot \Pi) \\ -\end{array} -\f] - -- if both values in `dsize > 0 `, -the destination image will have the given size therefore the area of the bounding circle will be scaled to `dsize`. - - -\par Reverse mapping - -You can get reverse mapping adding #WARP_INVERSE_MAP to `flags` -\snippet polar_transforms.cpp InverseMap - -In addiction, to calculate the original coordinate from a polar mapped coordinate \f$(rho, phi)->(x, y)\f$: -\snippet polar_transforms.cpp InverseCoordinate - -@param src Source image. -@param dst Destination image. It will have same type as src. -@param dsize The destination image size (see description for valid options). -@param center The transformation center. -@param maxRadius The radius of the bounding circle to transform. It determines the inverse magnitude scale parameter too. -@param flags A combination of interpolation methods, #InterpolationFlags + #WarpPolarMode. - - Add #WARP_POLAR_LINEAR to select linear polar mapping (default) - - Add #WARP_POLAR_LOG to select semilog polar mapping - - Add #WARP_INVERSE_MAP for reverse mapping. -@note -- The function can not operate in-place. -- To calculate magnitude and angle in degrees #cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees. -- This function uses #remap. Due to current implementation limitations the size of an input and output images should be less than 32767x32767. - -@sa cv::remap -*/ -CV_EXPORTS_W void warpPolar(InputArray src, OutputArray dst, Size dsize, - Point2f center, double maxRadius, int flags); - - -//! @} imgproc_transform - -//! @addtogroup imgproc_misc -//! @{ - -/** @brief Calculates the integral of an image. - -The function calculates one or more integral images for the source image as follows: - -\f[\texttt{sum} (X,Y) = \sum _{x - -Calculates the cross-power spectrum of two supplied source arrays. The arrays are padded if needed -with getOptimalDFTSize. - -The function performs the following equations: -- First it applies a Hanning window (see ) to each -image to remove possible edge effects. This window is cached until the array size changes to speed -up processing time. -- Next it computes the forward DFTs of each source array: -\f[\mathbf{G}_a = \mathcal{F}\{src_1\}, \; \mathbf{G}_b = \mathcal{F}\{src_2\}\f] -where \f$\mathcal{F}\f$ is the forward DFT. -- It then computes the cross-power spectrum of each frequency domain array: -\f[R = \frac{ \mathbf{G}_a \mathbf{G}_b^*}{|\mathbf{G}_a \mathbf{G}_b^*|}\f] -- Next the cross-correlation is converted back into the time domain via the inverse DFT: -\f[r = \mathcal{F}^{-1}\{R\}\f] -- Finally, it computes the peak location and computes a 5x5 weighted centroid around the peak to -achieve sub-pixel accuracy. -\f[(\Delta x, \Delta y) = \texttt{weightedCentroid} \{\arg \max_{(x, y)}\{r\}\}\f] -- If non-zero, the response parameter is computed as the sum of the elements of r within the 5x5 -centroid around the peak location. It is normalized to a maximum of 1 (meaning there is a single -peak) and will be smaller when there are multiple peaks. - -@param src1 Source floating point array (CV_32FC1 or CV_64FC1) -@param src2 Source floating point array (CV_32FC1 or CV_64FC1) -@param window Floating point array with windowing coefficients to reduce edge effects (optional). -@param response Signal power within the 5x5 centroid around the peak, between 0 and 1 (optional). -@returns detected phase shift (sub-pixel) between the two arrays. - -@sa dft, getOptimalDFTSize, idft, mulSpectrums createHanningWindow - */ -CV_EXPORTS_W Point2d phaseCorrelate(InputArray src1, InputArray src2, - InputArray window = noArray(), CV_OUT double* response = 0); - -/** @brief This function computes a Hanning window coefficients in two dimensions. - -See (http://en.wikipedia.org/wiki/Hann_function) and (http://en.wikipedia.org/wiki/Window_function) -for more information. - -An example is shown below: -@code - // create hanning window of size 100x100 and type CV_32F - Mat hann; - createHanningWindow(hann, Size(100, 100), CV_32F); -@endcode -@param dst Destination array to place Hann coefficients in -@param winSize The window size specifications (both width and height must be > 1) -@param type Created array type - */ -CV_EXPORTS_W void createHanningWindow(OutputArray dst, Size winSize, int type); - -/** @brief Performs the per-element division of the first Fourier spectrum by the second Fourier spectrum. - -The function cv::divSpectrums performs the per-element division of the first array by the second array. -The arrays are CCS-packed or complex matrices that are results of a real or complex Fourier transform. - -@param a first input array. -@param b second input array of the same size and type as src1 . -@param c output array of the same size and type as src1 . -@param flags operation flags; currently, the only supported flag is cv::DFT_ROWS, which indicates that -each row of src1 and src2 is an independent 1D Fourier spectrum. If you do not want to use this flag, then simply add a `0` as value. -@param conjB optional flag that conjugates the second input array before the multiplication (true) -or not (false). -*/ -CV_EXPORTS_W void divSpectrums(InputArray a, InputArray b, OutputArray c, - int flags, bool conjB = false); - -//! @} imgproc_motion - -//! @addtogroup imgproc_misc -//! @{ - -/** @brief Applies a fixed-level threshold to each array element. - -The function applies fixed-level thresholding to a multiple-channel array. The function is typically -used to get a bi-level (binary) image out of a grayscale image ( #compare could be also used for -this purpose) or for removing a noise, that is, filtering out pixels with too small or too large -values. There are several types of thresholding supported by the function. They are determined by -type parameter. - -Also, the special values #THRESH_OTSU or #THRESH_TRIANGLE may be combined with one of the -above values. In these cases, the function determines the optimal threshold value using the Otsu's -or Triangle algorithm and uses it instead of the specified thresh. - -@note Currently, the Otsu's and Triangle methods are implemented only for 8-bit single-channel images. - -@param src input array (multiple-channel, 8-bit or 32-bit floating point). -@param dst output array of the same size and type and the same number of channels as src. -@param thresh threshold value. -@param maxval maximum value to use with the #THRESH_BINARY and #THRESH_BINARY_INV thresholding -types. -@param type thresholding type (see #ThresholdTypes). -@return the computed threshold value if Otsu's or Triangle methods used. - -@sa adaptiveThreshold, findContours, compare, min, max - */ -CV_EXPORTS_W double threshold( InputArray src, OutputArray dst, - double thresh, double maxval, int type ); - - -/** @brief Applies an adaptive threshold to an array. - -The function transforms a grayscale image to a binary image according to the formulae: -- **THRESH_BINARY** - \f[dst(x,y) = \fork{\texttt{maxValue}}{if \(src(x,y) > T(x,y)\)}{0}{otherwise}\f] -- **THRESH_BINARY_INV** - \f[dst(x,y) = \fork{0}{if \(src(x,y) > T(x,y)\)}{\texttt{maxValue}}{otherwise}\f] -where \f$T(x,y)\f$ is a threshold calculated individually for each pixel (see adaptiveMethod parameter). - -The function can process the image in-place. - -@param src Source 8-bit single-channel image. -@param dst Destination image of the same size and the same type as src. -@param maxValue Non-zero value assigned to the pixels for which the condition is satisfied -@param adaptiveMethod Adaptive thresholding algorithm to use, see #AdaptiveThresholdTypes. -The #BORDER_REPLICATE | #BORDER_ISOLATED is used to process boundaries. -@param thresholdType Thresholding type that must be either #THRESH_BINARY or #THRESH_BINARY_INV, -see #ThresholdTypes. -@param blockSize Size of a pixel neighborhood that is used to calculate a threshold value for the -pixel: 3, 5, 7, and so on. -@param C Constant subtracted from the mean or weighted mean (see the details below). Normally, it -is positive but may be zero or negative as well. - -@sa threshold, blur, GaussianBlur - */ -CV_EXPORTS_W void adaptiveThreshold( InputArray src, OutputArray dst, - double maxValue, int adaptiveMethod, - int thresholdType, int blockSize, double C ); - -//! @} imgproc_misc - -//! @addtogroup imgproc_filter -//! @{ - -/** @example samples/cpp/tutorial_code/ImgProc/Pyramids/Pyramids.cpp -An example using pyrDown and pyrUp functions -*/ - -/** @brief Blurs an image and downsamples it. - -By default, size of the output image is computed as `Size((src.cols+1)/2, (src.rows+1)/2)`, but in -any case, the following conditions should be satisfied: - -\f[\begin{array}{l} | \texttt{dstsize.width} *2-src.cols| \leq 2 \\ | \texttt{dstsize.height} *2-src.rows| \leq 2 \end{array}\f] - -The function performs the downsampling step of the Gaussian pyramid construction. First, it -convolves the source image with the kernel: - -\f[\frac{1}{256} \begin{bmatrix} 1 & 4 & 6 & 4 & 1 \\ 4 & 16 & 24 & 16 & 4 \\ 6 & 24 & 36 & 24 & 6 \\ 4 & 16 & 24 & 16 & 4 \\ 1 & 4 & 6 & 4 & 1 \end{bmatrix}\f] - -Then, it downsamples the image by rejecting even rows and columns. - -@param src input image. -@param dst output image; it has the specified size and the same type as src. -@param dstsize size of the output image. -@param borderType Pixel extrapolation method, see #BorderTypes (#BORDER_CONSTANT isn't supported) - */ -CV_EXPORTS_W void pyrDown( InputArray src, OutputArray dst, - const Size& dstsize = Size(), int borderType = BORDER_DEFAULT ); - -/** @brief Upsamples an image and then blurs it. - -By default, size of the output image is computed as `Size(src.cols\*2, (src.rows\*2)`, but in any -case, the following conditions should be satisfied: - -\f[\begin{array}{l} | \texttt{dstsize.width} -src.cols*2| \leq ( \texttt{dstsize.width} \mod 2) \\ | \texttt{dstsize.height} -src.rows*2| \leq ( \texttt{dstsize.height} \mod 2) \end{array}\f] - -The function performs the upsampling step of the Gaussian pyramid construction, though it can -actually be used to construct the Laplacian pyramid. First, it upsamples the source image by -injecting even zero rows and columns and then convolves the result with the same kernel as in -pyrDown multiplied by 4. - -@param src input image. -@param dst output image. It has the specified size and the same type as src . -@param dstsize size of the output image. -@param borderType Pixel extrapolation method, see #BorderTypes (only #BORDER_DEFAULT is supported) - */ -CV_EXPORTS_W void pyrUp( InputArray src, OutputArray dst, - const Size& dstsize = Size(), int borderType = BORDER_DEFAULT ); - -/** @brief Constructs the Gaussian pyramid for an image. - -The function constructs a vector of images and builds the Gaussian pyramid by recursively applying -pyrDown to the previously built pyramid layers, starting from `dst[0]==src`. - -@param src Source image. Check pyrDown for the list of supported types. -@param dst Destination vector of maxlevel+1 images of the same type as src. dst[0] will be the -same as src. dst[1] is the next pyramid layer, a smoothed and down-sized src, and so on. -@param maxlevel 0-based index of the last (the smallest) pyramid layer. It must be non-negative. -@param borderType Pixel extrapolation method, see #BorderTypes (#BORDER_CONSTANT isn't supported) - */ -CV_EXPORTS void buildPyramid( InputArray src, OutputArrayOfArrays dst, - int maxlevel, int borderType = BORDER_DEFAULT ); - -//! @} imgproc_filter - -//! @addtogroup imgproc_hist -//! @{ - -/** @example samples/cpp/demhist.cpp -An example for creating histograms of an image -*/ - -/** @brief Calculates a histogram of a set of arrays. - -The function cv::calcHist calculates the histogram of one or more arrays. The elements of a tuple used -to increment a histogram bin are taken from the corresponding input arrays at the same location. The -sample below shows how to compute a 2D Hue-Saturation histogram for a color image. : -@include snippets/imgproc_calcHist.cpp - -@param images Source arrays. They all should have the same depth, CV_8U, CV_16U or CV_32F , and the same -size. Each of them can have an arbitrary number of channels. -@param nimages Number of source images. -@param channels List of the dims channels used to compute the histogram. The first array channels -are numerated from 0 to images[0].channels()-1 , the second array channels are counted from -images[0].channels() to images[0].channels() + images[1].channels()-1, and so on. -@param mask Optional mask. If the matrix is not empty, it must be an 8-bit array of the same size -as images[i] . The non-zero mask elements mark the array elements counted in the histogram. -@param hist Output histogram, which is a dense or sparse dims -dimensional array. -@param dims Histogram dimensionality that must be positive and not greater than CV_MAX_DIMS -(equal to 32 in the current OpenCV version). -@param histSize Array of histogram sizes in each dimension. -@param ranges Array of the dims arrays of the histogram bin boundaries in each dimension. When the -histogram is uniform ( uniform =true), then for each dimension i it is enough to specify the lower -(inclusive) boundary \f$L_0\f$ of the 0-th histogram bin and the upper (exclusive) boundary -\f$U_{\texttt{histSize}[i]-1}\f$ for the last histogram bin histSize[i]-1 . That is, in case of a -uniform histogram each of ranges[i] is an array of 2 elements. When the histogram is not uniform ( -uniform=false ), then each of ranges[i] contains histSize[i]+1 elements: -\f$L_0, U_0=L_1, U_1=L_2, ..., U_{\texttt{histSize[i]}-2}=L_{\texttt{histSize[i]}-1}, U_{\texttt{histSize[i]}-1}\f$ -. The array elements, that are not between \f$L_0\f$ and \f$U_{\texttt{histSize[i]}-1}\f$ , are not -counted in the histogram. -@param uniform Flag indicating whether the histogram is uniform or not (see above). -@param accumulate Accumulation flag. If it is set, the histogram is not cleared in the beginning -when it is allocated. This feature enables you to compute a single histogram from several sets of -arrays, or to update the histogram in time. -*/ -CV_EXPORTS void calcHist( const Mat* images, int nimages, - const int* channels, InputArray mask, - OutputArray hist, int dims, const int* histSize, - const float** ranges, bool uniform = true, bool accumulate = false ); - -/** @overload - -this variant uses %SparseMat for output -*/ -CV_EXPORTS void calcHist( const Mat* images, int nimages, - const int* channels, InputArray mask, - SparseMat& hist, int dims, - const int* histSize, const float** ranges, - bool uniform = true, bool accumulate = false ); - -/** @overload - -this variant supports only uniform histograms. - -ranges argument is either empty vector or a flattened vector of histSize.size()*2 elements -(histSize.size() element pairs). The first and second elements of each pair specify the lower and -upper boundaries. -*/ -CV_EXPORTS_W void calcHist( InputArrayOfArrays images, - const std::vector& channels, - InputArray mask, OutputArray hist, - const std::vector& histSize, - const std::vector& ranges, - bool accumulate = false ); - -/** @brief Calculates the back projection of a histogram. - -The function cv::calcBackProject calculates the back project of the histogram. That is, similarly to -#calcHist , at each location (x, y) the function collects the values from the selected channels -in the input images and finds the corresponding histogram bin. But instead of incrementing it, the -function reads the bin value, scales it by scale , and stores in backProject(x,y) . In terms of -statistics, the function computes probability of each element value in respect with the empirical -probability distribution represented by the histogram. See how, for example, you can find and track -a bright-colored object in a scene: - -- Before tracking, show the object to the camera so that it covers almost the whole frame. -Calculate a hue histogram. The histogram may have strong maximums, corresponding to the dominant -colors in the object. - -- When tracking, calculate a back projection of a hue plane of each input video frame using that -pre-computed histogram. Threshold the back projection to suppress weak colors. It may also make -sense to suppress pixels with non-sufficient color saturation and too dark or too bright pixels. - -- Find connected components in the resulting picture and choose, for example, the largest -component. - -This is an approximate algorithm of the CamShift color object tracker. - -@param images Source arrays. They all should have the same depth, CV_8U, CV_16U or CV_32F , and the same -size. Each of them can have an arbitrary number of channels. -@param nimages Number of source images. -@param channels The list of channels used to compute the back projection. The number of channels -must match the histogram dimensionality. The first array channels are numerated from 0 to -images[0].channels()-1 , the second array channels are counted from images[0].channels() to -images[0].channels() + images[1].channels()-1, and so on. -@param hist Input histogram that can be dense or sparse. -@param backProject Destination back projection array that is a single-channel array of the same -size and depth as images[0] . -@param ranges Array of arrays of the histogram bin boundaries in each dimension. See #calcHist . -@param scale Optional scale factor for the output back projection. -@param uniform Flag indicating whether the histogram is uniform or not (see #calcHist). - -@sa calcHist, compareHist - */ -CV_EXPORTS void calcBackProject( const Mat* images, int nimages, - const int* channels, InputArray hist, - OutputArray backProject, const float** ranges, - double scale = 1, bool uniform = true ); - -/** @overload */ -CV_EXPORTS void calcBackProject( const Mat* images, int nimages, - const int* channels, const SparseMat& hist, - OutputArray backProject, const float** ranges, - double scale = 1, bool uniform = true ); - -/** @overload */ -CV_EXPORTS_W void calcBackProject( InputArrayOfArrays images, const std::vector& channels, - InputArray hist, OutputArray dst, - const std::vector& ranges, - double scale ); - -/** @brief Compares two histograms. - -The function cv::compareHist compares two dense or two sparse histograms using the specified method. - -The function returns \f$d(H_1, H_2)\f$ . - -While the function works well with 1-, 2-, 3-dimensional dense histograms, it may not be suitable -for high-dimensional sparse histograms. In such histograms, because of aliasing and sampling -problems, the coordinates of non-zero histogram bins can slightly shift. To compare such histograms -or more general sparse configurations of weighted points, consider using the #EMD function. - -@param H1 First compared histogram. -@param H2 Second compared histogram of the same size as H1 . -@param method Comparison method, see #HistCompMethods - */ -CV_EXPORTS_W double compareHist( InputArray H1, InputArray H2, int method ); - -/** @overload */ -CV_EXPORTS double compareHist( const SparseMat& H1, const SparseMat& H2, int method ); - -/** @brief Equalizes the histogram of a grayscale image. - -The function equalizes the histogram of the input image using the following algorithm: - -- Calculate the histogram \f$H\f$ for src . -- Normalize the histogram so that the sum of histogram bins is 255. -- Compute the integral of the histogram: -\f[H'_i = \sum _{0 \le j < i} H(j)\f] -- Transform the image using \f$H'\f$ as a look-up table: \f$\texttt{dst}(x,y) = H'(\texttt{src}(x,y))\f$ - -The algorithm normalizes the brightness and increases the contrast of the image. - -@param src Source 8-bit single channel image. -@param dst Destination image of the same size and type as src . - */ -CV_EXPORTS_W void equalizeHist( InputArray src, OutputArray dst ); - -/** @brief Creates a smart pointer to a cv::CLAHE class and initializes it. - -@param clipLimit Threshold for contrast limiting. -@param tileGridSize Size of grid for histogram equalization. Input image will be divided into -equally sized rectangular tiles. tileGridSize defines the number of tiles in row and column. - */ -CV_EXPORTS_W Ptr createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8)); - -/** @brief Computes the "minimal work" distance between two weighted point configurations. - -The function computes the earth mover distance and/or a lower boundary of the distance between the -two weighted point configurations. One of the applications described in @cite RubnerSept98, -@cite Rubner2000 is multi-dimensional histogram comparison for image retrieval. EMD is a transportation -problem that is solved using some modification of a simplex algorithm, thus the complexity is -exponential in the worst case, though, on average it is much faster. In the case of a real metric -the lower boundary can be calculated even faster (using linear-time algorithm) and it can be used -to determine roughly whether the two signatures are far enough so that they cannot relate to the -same object. - -@param signature1 First signature, a \f$\texttt{size1}\times \texttt{dims}+1\f$ floating-point matrix. -Each row stores the point weight followed by the point coordinates. The matrix is allowed to have -a single column (weights only) if the user-defined cost matrix is used. The weights must be -non-negative and have at least one non-zero value. -@param signature2 Second signature of the same format as signature1 , though the number of rows -may be different. The total weights may be different. In this case an extra "dummy" point is added -to either signature1 or signature2. The weights must be non-negative and have at least one non-zero -value. -@param distType Used metric. See #DistanceTypes. -@param cost User-defined \f$\texttt{size1}\times \texttt{size2}\f$ cost matrix. Also, if a cost matrix -is used, lower boundary lowerBound cannot be calculated because it needs a metric function. -@param lowerBound Optional input/output parameter: lower boundary of a distance between the two -signatures that is a distance between mass centers. The lower boundary may not be calculated if -the user-defined cost matrix is used, the total weights of point configurations are not equal, or -if the signatures consist of weights only (the signature matrices have a single column). You -**must** initialize \*lowerBound . If the calculated distance between mass centers is greater or -equal to \*lowerBound (it means that the signatures are far enough), the function does not -calculate EMD. In any case \*lowerBound is set to the calculated distance between mass centers on -return. Thus, if you want to calculate both distance between mass centers and EMD, \*lowerBound -should be set to 0. -@param flow Resultant \f$\texttt{size1} \times \texttt{size2}\f$ flow matrix: \f$\texttt{flow}_{i,j}\f$ is -a flow from \f$i\f$ -th point of signature1 to \f$j\f$ -th point of signature2 . - */ -CV_EXPORTS float EMD( InputArray signature1, InputArray signature2, - int distType, InputArray cost=noArray(), - float* lowerBound = 0, OutputArray flow = noArray() ); - -CV_EXPORTS_AS(EMD) float wrapperEMD( InputArray signature1, InputArray signature2, - int distType, InputArray cost=noArray(), - CV_IN_OUT Ptr lowerBound = Ptr(), OutputArray flow = noArray() ); - -//! @} imgproc_hist - -//! @addtogroup imgproc_segmentation -//! @{ - -/** @example samples/cpp/watershed.cpp -An example using the watershed algorithm -*/ - -/** @brief Performs a marker-based image segmentation using the watershed algorithm. - -The function implements one of the variants of watershed, non-parametric marker-based segmentation -algorithm, described in @cite Meyer92 . - -Before passing the image to the function, you have to roughly outline the desired regions in the -image markers with positive (\>0) indices. So, every region is represented as one or more connected -components with the pixel values 1, 2, 3, and so on. Such markers can be retrieved from a binary -mask using #findContours and #drawContours (see the watershed.cpp demo). The markers are "seeds" of -the future image regions. All the other pixels in markers , whose relation to the outlined regions -is not known and should be defined by the algorithm, should be set to 0's. In the function output, -each pixel in markers is set to a value of the "seed" components or to -1 at boundaries between the -regions. - -@note Any two neighbor connected components are not necessarily separated by a watershed boundary -(-1's pixels); for example, they can touch each other in the initial marker image passed to the -function. - -@param image Input 8-bit 3-channel image. -@param markers Input/output 32-bit single-channel image (map) of markers. It should have the same -size as image . - -@sa findContours - */ -CV_EXPORTS_W void watershed( InputArray image, InputOutputArray markers ); - -//! @} imgproc_segmentation - -//! @addtogroup imgproc_filter -//! @{ - -/** @brief Performs initial step of meanshift segmentation of an image. - -The function implements the filtering stage of meanshift segmentation, that is, the output of the -function is the filtered "posterized" image with color gradients and fine-grain texture flattened. -At every pixel (X,Y) of the input image (or down-sized input image, see below) the function executes -meanshift iterations, that is, the pixel (X,Y) neighborhood in the joint space-color hyperspace is -considered: - -\f[(x,y): X- \texttt{sp} \le x \le X+ \texttt{sp} , Y- \texttt{sp} \le y \le Y+ \texttt{sp} , ||(R,G,B)-(r,g,b)|| \le \texttt{sr}\f] - -where (R,G,B) and (r,g,b) are the vectors of color components at (X,Y) and (x,y), respectively -(though, the algorithm does not depend on the color space used, so any 3-component color space can -be used instead). Over the neighborhood the average spatial value (X',Y') and average color vector -(R',G',B') are found and they act as the neighborhood center on the next iteration: - -\f[(X,Y)~(X',Y'), (R,G,B)~(R',G',B').\f] - -After the iterations over, the color components of the initial pixel (that is, the pixel from where -the iterations started) are set to the final value (average color at the last iteration): - -\f[I(X,Y) <- (R*,G*,B*)\f] - -When maxLevel \> 0, the gaussian pyramid of maxLevel+1 levels is built, and the above procedure is -run on the smallest layer first. After that, the results are propagated to the larger layer and the -iterations are run again only on those pixels where the layer colors differ by more than sr from the -lower-resolution layer of the pyramid. That makes boundaries of color regions sharper. Note that the -results will be actually different from the ones obtained by running the meanshift procedure on the -whole original image (i.e. when maxLevel==0). - -@param src The source 8-bit, 3-channel image. -@param dst The destination image of the same format and the same size as the source. -@param sp The spatial window radius. -@param sr The color window radius. -@param maxLevel Maximum level of the pyramid for the segmentation. -@param termcrit Termination criteria: when to stop meanshift iterations. - */ -CV_EXPORTS_W void pyrMeanShiftFiltering( InputArray src, OutputArray dst, - double sp, double sr, int maxLevel = 1, - TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5,1) ); - -//! @} - -//! @addtogroup imgproc_segmentation -//! @{ - -/** @example samples/cpp/grabcut.cpp -An example using the GrabCut algorithm -![Sample Screenshot](grabcut_output1.jpg) -*/ - -/** @brief Runs the GrabCut algorithm. - -The function implements the [GrabCut image segmentation algorithm](http://en.wikipedia.org/wiki/GrabCut). - -@param img Input 8-bit 3-channel image. -@param mask Input/output 8-bit single-channel mask. The mask is initialized by the function when -mode is set to #GC_INIT_WITH_RECT. Its elements may have one of the #GrabCutClasses. -@param rect ROI containing a segmented object. The pixels outside of the ROI are marked as -"obvious background". The parameter is only used when mode==#GC_INIT_WITH_RECT . -@param bgdModel Temporary array for the background model. Do not modify it while you are -processing the same image. -@param fgdModel Temporary arrays for the foreground model. Do not modify it while you are -processing the same image. -@param iterCount Number of iterations the algorithm should make before returning the result. Note -that the result can be refined with further calls with mode==#GC_INIT_WITH_MASK or -mode==GC_EVAL . -@param mode Operation mode that could be one of the #GrabCutModes - */ -CV_EXPORTS_W void grabCut( InputArray img, InputOutputArray mask, Rect rect, - InputOutputArray bgdModel, InputOutputArray fgdModel, - int iterCount, int mode = GC_EVAL ); - -//! @} imgproc_segmentation - -//! @addtogroup imgproc_misc -//! @{ - -/** @example samples/cpp/distrans.cpp -An example on using the distance transform -*/ - -/** @brief Calculates the distance to the closest zero pixel for each pixel of the source image. - -The function cv::distanceTransform calculates the approximate or precise distance from every binary -image pixel to the nearest zero pixel. For zero image pixels, the distance will obviously be zero. - -When maskSize == #DIST_MASK_PRECISE and distanceType == #DIST_L2 , the function runs the -algorithm described in @cite Felzenszwalb04 . This algorithm is parallelized with the TBB library. - -In other cases, the algorithm @cite Borgefors86 is used. This means that for a pixel the function -finds the shortest path to the nearest zero pixel consisting of basic shifts: horizontal, vertical, -diagonal, or knight's move (the latest is available for a \f$5\times 5\f$ mask). The overall -distance is calculated as a sum of these basic distances. Since the distance function should be -symmetric, all of the horizontal and vertical shifts must have the same cost (denoted as a ), all -the diagonal shifts must have the same cost (denoted as `b`), and all knight's moves must have the -same cost (denoted as `c`). For the #DIST_C and #DIST_L1 types, the distance is calculated -precisely, whereas for #DIST_L2 (Euclidean distance) the distance can be calculated only with a -relative error (a \f$5\times 5\f$ mask gives more accurate results). For `a`,`b`, and `c`, OpenCV -uses the values suggested in the original paper: -- DIST_L1: `a = 1, b = 2` -- DIST_L2: - - `3 x 3`: `a=0.955, b=1.3693` - - `5 x 5`: `a=1, b=1.4, c=2.1969` -- DIST_C: `a = 1, b = 1` - -Typically, for a fast, coarse distance estimation #DIST_L2, a \f$3\times 3\f$ mask is used. For a -more accurate distance estimation #DIST_L2, a \f$5\times 5\f$ mask or the precise algorithm is used. -Note that both the precise and the approximate algorithms are linear on the number of pixels. - -This variant of the function does not only compute the minimum distance for each pixel \f$(x, y)\f$ -but also identifies the nearest connected component consisting of zero pixels -(labelType==#DIST_LABEL_CCOMP) or the nearest zero pixel (labelType==#DIST_LABEL_PIXEL). Index of the -component/pixel is stored in `labels(x, y)`. When labelType==#DIST_LABEL_CCOMP, the function -automatically finds connected components of zero pixels in the input image and marks them with -distinct labels. When labelType==#DIST_LABEL_PIXEL, the function scans through the input image and -marks all the zero pixels with distinct labels. - -In this mode, the complexity is still linear. That is, the function provides a very fast way to -compute the Voronoi diagram for a binary image. Currently, the second variant can use only the -approximate distance transform algorithm, i.e. maskSize=#DIST_MASK_PRECISE is not supported -yet. - -@param src 8-bit, single-channel (binary) source image. -@param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point, -single-channel image of the same size as src. -@param labels Output 2D array of labels (the discrete Voronoi diagram). It has the type -CV_32SC1 and the same size as src. -@param distanceType Type of distance, see #DistanceTypes -@param maskSize Size of the distance transform mask, see #DistanceTransformMasks. -#DIST_MASK_PRECISE is not supported by this variant. In case of the #DIST_L1 or #DIST_C distance type, -the parameter is forced to 3 because a \f$3\times 3\f$ mask gives the same result as \f$5\times -5\f$ or any larger aperture. -@param labelType Type of the label array to build, see #DistanceTransformLabelTypes. - */ -CV_EXPORTS_AS(distanceTransformWithLabels) void distanceTransform( InputArray src, OutputArray dst, - OutputArray labels, int distanceType, int maskSize, - int labelType = DIST_LABEL_CCOMP ); - -/** @overload -@param src 8-bit, single-channel (binary) source image. -@param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point, -single-channel image of the same size as src . -@param distanceType Type of distance, see #DistanceTypes -@param maskSize Size of the distance transform mask, see #DistanceTransformMasks. In case of the -#DIST_L1 or #DIST_C distance type, the parameter is forced to 3 because a \f$3\times 3\f$ mask gives -the same result as \f$5\times 5\f$ or any larger aperture. -@param dstType Type of output image. It can be CV_8U or CV_32F. Type CV_8U can be used only for -the first variant of the function and distanceType == #DIST_L1. -*/ -CV_EXPORTS_W void distanceTransform( InputArray src, OutputArray dst, - int distanceType, int maskSize, int dstType=CV_32F); - -/** @brief Fills a connected component with the given color. - -The function cv::floodFill fills a connected component starting from the seed point with the specified -color. The connectivity is determined by the color/brightness closeness of the neighbor pixels. The -pixel at \f$(x,y)\f$ is considered to belong to the repainted domain if: - -- in case of a grayscale image and floating range -\f[\texttt{src} (x',y')- \texttt{loDiff} \leq \texttt{src} (x,y) \leq \texttt{src} (x',y')+ \texttt{upDiff}\f] - - -- in case of a grayscale image and fixed range -\f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)- \texttt{loDiff} \leq \texttt{src} (x,y) \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)+ \texttt{upDiff}\f] - - -- in case of a color image and floating range -\f[\texttt{src} (x',y')_r- \texttt{loDiff} _r \leq \texttt{src} (x,y)_r \leq \texttt{src} (x',y')_r+ \texttt{upDiff} _r,\f] -\f[\texttt{src} (x',y')_g- \texttt{loDiff} _g \leq \texttt{src} (x,y)_g \leq \texttt{src} (x',y')_g+ \texttt{upDiff} _g\f] -and -\f[\texttt{src} (x',y')_b- \texttt{loDiff} _b \leq \texttt{src} (x,y)_b \leq \texttt{src} (x',y')_b+ \texttt{upDiff} _b\f] - - -- in case of a color image and fixed range -\f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_r- \texttt{loDiff} _r \leq \texttt{src} (x,y)_r \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_r+ \texttt{upDiff} _r,\f] -\f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_g- \texttt{loDiff} _g \leq \texttt{src} (x,y)_g \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_g+ \texttt{upDiff} _g\f] -and -\f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b- \texttt{loDiff} _b \leq \texttt{src} (x,y)_b \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b+ \texttt{upDiff} _b\f] - - -where \f$src(x',y')\f$ is the value of one of pixel neighbors that is already known to belong to the -component. That is, to be added to the connected component, a color/brightness of the pixel should -be close enough to: -- Color/brightness of one of its neighbors that already belong to the connected component in case -of a floating range. -- Color/brightness of the seed point in case of a fixed range. - -Use these functions to either mark a connected component with the specified color in-place, or build -a mask and then extract the contour, or copy the region to another image, and so on. - -@param image Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the -function unless the #FLOODFILL_MASK_ONLY flag is set in the second variant of the function. See -the details below. -@param mask Operation mask that should be a single-channel 8-bit image, 2 pixels wider and 2 pixels -taller than image. If an empty Mat is passed it will be created automatically. Since this is both an -input and output parameter, you must take responsibility of initializing it. -Flood-filling cannot go across non-zero pixels in the input mask. For example, -an edge detector output can be used as a mask to stop filling at edges. On output, pixels in the -mask corresponding to filled pixels in the image are set to 1 or to the specified value in flags -as described below. Additionally, the function fills the border of the mask with ones to simplify -internal processing. It is therefore possible to use the same mask in multiple calls to the function -to make sure the filled areas do not overlap. -@param seedPoint Starting point. -@param newVal New value of the repainted domain pixels. -@param loDiff Maximal lower brightness/color difference between the currently observed pixel and -one of its neighbors belonging to the component, or a seed pixel being added to the component. -@param upDiff Maximal upper brightness/color difference between the currently observed pixel and -one of its neighbors belonging to the component, or a seed pixel being added to the component. -@param rect Optional output parameter set by the function to the minimum bounding rectangle of the -repainted domain. -@param flags Operation flags. The first 8 bits contain a connectivity value. The default value of -4 means that only the four nearest neighbor pixels (those that share an edge) are considered. A -connectivity value of 8 means that the eight nearest neighbor pixels (those that share a corner) -will be considered. The next 8 bits (8-16) contain a value between 1 and 255 with which to fill -the mask (the default value is 1). For example, 4 | ( 255 \<\< 8 ) will consider 4 nearest -neighbours and fill the mask with a value of 255. The following additional options occupy higher -bits and therefore may be further combined with the connectivity and mask fill values using -bit-wise or (|), see #FloodFillFlags. - -@note Since the mask is larger than the filled image, a pixel \f$(x, y)\f$ in image corresponds to the -pixel \f$(x+1, y+1)\f$ in the mask . - -@sa findContours - */ -CV_EXPORTS_W int floodFill( InputOutputArray image, InputOutputArray mask, - Point seedPoint, Scalar newVal, CV_OUT Rect* rect=0, - Scalar loDiff = Scalar(), Scalar upDiff = Scalar(), - int flags = 4 ); - -/** @example samples/cpp/ffilldemo.cpp -An example using the FloodFill technique -*/ - -/** @overload - -variant without `mask` parameter -*/ -CV_EXPORTS int floodFill( InputOutputArray image, - Point seedPoint, Scalar newVal, CV_OUT Rect* rect = 0, - Scalar loDiff = Scalar(), Scalar upDiff = Scalar(), - int flags = 4 ); - -//! Performs linear blending of two images: -//! \f[ \texttt{dst}(i,j) = \texttt{weights1}(i,j)*\texttt{src1}(i,j) + \texttt{weights2}(i,j)*\texttt{src2}(i,j) \f] -//! @param src1 It has a type of CV_8UC(n) or CV_32FC(n), where n is a positive integer. -//! @param src2 It has the same type and size as src1. -//! @param weights1 It has a type of CV_32FC1 and the same size with src1. -//! @param weights2 It has a type of CV_32FC1 and the same size with src1. -//! @param dst It is created if it does not have the same size and type with src1. -CV_EXPORTS_W void blendLinear(InputArray src1, InputArray src2, InputArray weights1, InputArray weights2, OutputArray dst); - -//! @} imgproc_misc - -//! @addtogroup imgproc_color_conversions -//! @{ - -/** @brief Converts an image from one color space to another. - -The function converts an input image from one color space to another. In case of a transformation -to-from RGB color space, the order of the channels should be specified explicitly (RGB or BGR). Note -that the default color format in OpenCV is often referred to as RGB but it is actually BGR (the -bytes are reversed). So the first byte in a standard (24-bit) color image will be an 8-bit Blue -component, the second byte will be Green, and the third byte will be Red. The fourth, fifth, and -sixth bytes would then be the second pixel (Blue, then Green, then Red), and so on. - -The conventional ranges for R, G, and B channel values are: -- 0 to 255 for CV_8U images -- 0 to 65535 for CV_16U images -- 0 to 1 for CV_32F images - -In case of linear transformations, the range does not matter. But in case of a non-linear -transformation, an input RGB image should be normalized to the proper value range to get the correct -results, for example, for RGB \f$\rightarrow\f$ L\*u\*v\* transformation. For example, if you have a -32-bit floating-point image directly converted from an 8-bit image without any scaling, then it will -have the 0..255 value range instead of 0..1 assumed by the function. So, before calling #cvtColor , -you need first to scale the image down: -@code - img *= 1./255; - cvtColor(img, img, COLOR_BGR2Luv); -@endcode -If you use #cvtColor with 8-bit images, the conversion will have some information lost. For many -applications, this will not be noticeable but it is recommended to use 32-bit images in applications -that need the full range of colors or that convert an image before an operation and then convert -back. - -If conversion adds the alpha channel, its value will set to the maximum of corresponding channel -range: 255 for CV_8U, 65535 for CV_16U, 1 for CV_32F. - -@param src input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC... ), or single-precision -floating-point. -@param dst output image of the same size and depth as src. -@param code color space conversion code (see #ColorConversionCodes). -@param dstCn number of channels in the destination image; if the parameter is 0, the number of the -channels is derived automatically from src and code. -@param hint Implementation modfication flags. See #AlgorithmHint - -@see @ref imgproc_color_conversions - */ -CV_EXPORTS_W void cvtColor( InputArray src, OutputArray dst, int code, int dstCn = 0, AlgorithmHint hint = cv::ALGO_HINT_DEFAULT ); - -/** @brief Converts an image from one color space to another where the source image is -stored in two planes. - -This function only supports YUV420 to RGB conversion as of now. - -@param src1 8-bit image (#CV_8U) of the Y plane. -@param src2 image containing interleaved U/V plane. -@param dst output image. -@param code Specifies the type of conversion. It can take any of the following values: -- #COLOR_YUV2BGR_NV12 -- #COLOR_YUV2RGB_NV12 -- #COLOR_YUV2BGRA_NV12 -- #COLOR_YUV2RGBA_NV12 -- #COLOR_YUV2BGR_NV21 -- #COLOR_YUV2RGB_NV21 -- #COLOR_YUV2BGRA_NV21 -- #COLOR_YUV2RGBA_NV21 -@param hint Implementation modfication flags. See #AlgorithmHint -*/ -CV_EXPORTS_W void cvtColorTwoPlane( InputArray src1, InputArray src2, OutputArray dst, int code, AlgorithmHint hint = cv::ALGO_HINT_DEFAULT ); - -/** @brief main function for all demosaicing processes - -@param src input image: 8-bit unsigned or 16-bit unsigned. -@param dst output image of the same size and depth as src. -@param code Color space conversion code (see the description below). -@param dstCn number of channels in the destination image; if the parameter is 0, the number of the -channels is derived automatically from src and code. - -The function can do the following transformations: - -- Demosaicing using bilinear interpolation - - #COLOR_BayerBG2BGR , #COLOR_BayerGB2BGR , #COLOR_BayerRG2BGR , #COLOR_BayerGR2BGR - - #COLOR_BayerBG2GRAY , #COLOR_BayerGB2GRAY , #COLOR_BayerRG2GRAY , #COLOR_BayerGR2GRAY - -- Demosaicing using Variable Number of Gradients. - - #COLOR_BayerBG2BGR_VNG , #COLOR_BayerGB2BGR_VNG , #COLOR_BayerRG2BGR_VNG , #COLOR_BayerGR2BGR_VNG - -- Edge-Aware Demosaicing. - - #COLOR_BayerBG2BGR_EA , #COLOR_BayerGB2BGR_EA , #COLOR_BayerRG2BGR_EA , #COLOR_BayerGR2BGR_EA - -- Demosaicing with alpha channel - - #COLOR_BayerBG2BGRA , #COLOR_BayerGB2BGRA , #COLOR_BayerRG2BGRA , #COLOR_BayerGR2BGRA - -@sa cvtColor -*/ -CV_EXPORTS_W void demosaicing(InputArray src, OutputArray dst, int code, int dstCn = 0); - -//! @} imgproc_color_conversions - -//! @addtogroup imgproc_shape -//! @{ - -/** @brief Calculates all of the moments up to the third order of a polygon or rasterized shape. - -The function computes moments, up to the 3rd order, of a vector shape or a rasterized shape. The -results are returned in the structure cv::Moments. - -@param array Single chanel raster image (CV_8U, CV_16U, CV_16S, CV_32F, CV_64F) or an array ( -\f$1 \times N\f$ or \f$N \times 1\f$ ) of 2D points (Point or Point2f). -@param binaryImage If it is true, all non-zero image pixels are treated as 1's. The parameter is -used for images only. -@returns moments. - -@note Only applicable to contour moments calculations from Python bindings: Note that the numpy -type for the input array should be either np.int32 or np.float32. - -@sa contourArea, arcLength - */ -CV_EXPORTS_W Moments moments( InputArray array, bool binaryImage = false ); - -/** @brief Calculates seven Hu invariants. - -The function calculates seven Hu invariants (introduced in @cite Hu62; see also -) defined as: - -\f[\begin{array}{l} hu[0]= \eta _{20}+ \eta _{02} \\ hu[1]=( \eta _{20}- \eta _{02})^{2}+4 \eta _{11}^{2} \\ hu[2]=( \eta _{30}-3 \eta _{12})^{2}+ (3 \eta _{21}- \eta _{03})^{2} \\ hu[3]=( \eta _{30}+ \eta _{12})^{2}+ ( \eta _{21}+ \eta _{03})^{2} \\ hu[4]=( \eta _{30}-3 \eta _{12})( \eta _{30}+ \eta _{12})[( \eta _{30}+ \eta _{12})^{2}-3( \eta _{21}+ \eta _{03})^{2}]+(3 \eta _{21}- \eta _{03})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}] \\ hu[5]=( \eta _{20}- \eta _{02})[( \eta _{30}+ \eta _{12})^{2}- ( \eta _{21}+ \eta _{03})^{2}]+4 \eta _{11}( \eta _{30}+ \eta _{12})( \eta _{21}+ \eta _{03}) \\ hu[6]=(3 \eta _{21}- \eta _{03})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}]-( \eta _{30}-3 \eta _{12})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}] \\ \end{array}\f] - -where \f$\eta_{ji}\f$ stands for \f$\texttt{Moments::nu}_{ji}\f$ . - -These values are proved to be invariants to the image scale, rotation, and reflection except the -seventh one, whose sign is changed by reflection. This invariance is proved with the assumption of -infinite image resolution. In case of raster images, the computed Hu invariants for the original and -transformed images are a bit different. - -@param moments Input moments computed with moments . -@param hu Output Hu invariants. - -@sa matchShapes - */ -CV_EXPORTS void HuMoments( const Moments& moments, double hu[7] ); - -/** @overload */ -CV_EXPORTS_W void HuMoments( const Moments& m, OutputArray hu ); - -//! @} imgproc_shape - -//! @addtogroup imgproc_object -//! @{ - -//! type of the template matching operation -enum TemplateMatchModes { - TM_SQDIFF = 0, /*!< \f[R(x,y)= \sum _{x',y'} (T(x',y')-I(x+x',y+y'))^2\f] - with mask: - \f[R(x,y)= \sum _{x',y'} \left( (T(x',y')-I(x+x',y+y')) \cdot - M(x',y') \right)^2\f] */ - TM_SQDIFF_NORMED = 1, /*!< \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y')-I(x+x',y+y'))^2}{\sqrt{\sum_{ - x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}\f] - with mask: - \f[R(x,y)= \frac{\sum _{x',y'} \left( (T(x',y')-I(x+x',y+y')) \cdot - M(x',y') \right)^2}{\sqrt{\sum_{x',y'} \left( T(x',y') \cdot - M(x',y') \right)^2 \cdot \sum_{x',y'} \left( I(x+x',y+y') \cdot - M(x',y') \right)^2}}\f] */ - TM_CCORR = 2, /*!< \f[R(x,y)= \sum _{x',y'} (T(x',y') \cdot I(x+x',y+y'))\f] - with mask: - \f[R(x,y)= \sum _{x',y'} (T(x',y') \cdot I(x+x',y+y') \cdot M(x',y') - ^2)\f] */ - TM_CCORR_NORMED = 3, /*!< \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y') \cdot I(x+x',y+y'))}{\sqrt{ - \sum_{x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}\f] - with mask: - \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y') \cdot I(x+x',y+y') \cdot - M(x',y')^2)}{\sqrt{\sum_{x',y'} \left( T(x',y') \cdot M(x',y') - \right)^2 \cdot \sum_{x',y'} \left( I(x+x',y+y') \cdot M(x',y') - \right)^2}}\f] */ - TM_CCOEFF = 4, /*!< \f[R(x,y)= \sum _{x',y'} (T'(x',y') \cdot I'(x+x',y+y'))\f] - where - \f[\begin{array}{l} T'(x',y')=T(x',y') - 1/(w \cdot h) \cdot \sum _{ - x'',y''} T(x'',y'') \\ I'(x+x',y+y')=I(x+x',y+y') - 1/(w \cdot h) - \cdot \sum _{x'',y''} I(x+x'',y+y'') \end{array}\f] - with mask: - \f[\begin{array}{l} T'(x',y')=M(x',y') \cdot \left( T(x',y') - - \frac{1}{\sum _{x'',y''} M(x'',y'')} \cdot \sum _{x'',y''} - (T(x'',y'') \cdot M(x'',y'')) \right) \\ I'(x+x',y+y')=M(x',y') - \cdot \left( I(x+x',y+y') - \frac{1}{\sum _{x'',y''} M(x'',y'')} - \cdot \sum _{x'',y''} (I(x+x'',y+y'') \cdot M(x'',y'')) \right) - \end{array} \f] */ - TM_CCOEFF_NORMED = 5 /*!< \f[R(x,y)= \frac{ \sum_{x',y'} (T'(x',y') \cdot I'(x+x',y+y')) }{ - \sqrt{\sum_{x',y'}T'(x',y')^2 \cdot \sum_{x',y'} I'(x+x',y+y')^2} - }\f] */ -}; - -/** @example samples/cpp/tutorial_code/Histograms_Matching/MatchTemplate_Demo.cpp -An example using Template Matching algorithm -*/ - -/** @brief Compares a template against overlapped image regions. - -The function slides through image , compares the overlapped patches of size \f$w \times h\f$ against -templ using the specified method and stores the comparison results in result . #TemplateMatchModes -describes the formulae for the available comparison methods ( \f$I\f$ denotes image, \f$T\f$ -template, \f$R\f$ result, \f$M\f$ the optional mask ). The summation is done over template and/or -the image patch: \f$x' = 0...w-1, y' = 0...h-1\f$ - -After the function finishes the comparison, the best matches can be found as global minimums (when -#TM_SQDIFF was used) or maximums (when #TM_CCORR or #TM_CCOEFF was used) using the -#minMaxLoc function. In case of a color image, template summation in the numerator and each sum in -the denominator is done over all of the channels and separate mean values are used for each channel. -That is, the function can take a color template and a color image. The result will still be a -single-channel image, which is easier to analyze. - -@param image Image where the search is running. It must be 8-bit or 32-bit floating-point. -@param templ Searched template. It must be not greater than the source image and have the same -data type. -@param result Map of comparison results. It must be single-channel 32-bit floating-point. If image -is \f$W \times H\f$ and templ is \f$w \times h\f$ , then result is \f$(W-w+1) \times (H-h+1)\f$ . -@param method Parameter specifying the comparison method, see #TemplateMatchModes -@param mask Optional mask. It must have the same size as templ. It must either have the same number - of channels as template or only one channel, which is then used for all template and - image channels. If the data type is #CV_8U, the mask is interpreted as a binary mask, - meaning only elements where mask is nonzero are used and are kept unchanged independent - of the actual mask value (weight equals 1). For data tpye #CV_32F, the mask values are - used as weights. The exact formulas are documented in #TemplateMatchModes. - */ -CV_EXPORTS_W void matchTemplate( InputArray image, InputArray templ, - OutputArray result, int method, InputArray mask = noArray() ); - -//! @} - -//! @addtogroup imgproc_shape -//! @{ - -/** @example samples/cpp/connected_components.cpp -This program demonstrates connected components and use of the trackbar -*/ - -/** @brief computes the connected components labeled image of boolean image - -image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 -represents the background label. ltype specifies the output label image type, an important -consideration based on the total number of labels or alternatively the total number of pixels in -the source image. ccltype specifies the connected components labeling algorithm to use, currently -Bolelli (Spaghetti) @cite Bolelli2019, Grana (BBDT) @cite Grana2010 and Wu's (SAUF) @cite Wu2009 algorithms -are supported, see the #ConnectedComponentsAlgorithmsTypes for details. Note that SAUF algorithm forces -a row major ordering of labels while Spaghetti and BBDT do not. -This function uses parallel version of the algorithms if at least one allowed -parallel framework is enabled and if the rows of the image are at least twice the number returned by #getNumberOfCPUs. - -@param image the 8-bit single-channel image to be labeled -@param labels destination labeled image -@param connectivity 8 or 4 for 8-way or 4-way connectivity respectively -@param ltype output image label type. Currently CV_32S and CV_16U are supported. -@param ccltype connected components algorithm type (see the #ConnectedComponentsAlgorithmsTypes). -*/ -CV_EXPORTS_AS(connectedComponentsWithAlgorithm) int connectedComponents(InputArray image, OutputArray labels, - int connectivity, int ltype, int ccltype); - - -/** @overload - -@param image the 8-bit single-channel image to be labeled -@param labels destination labeled image -@param connectivity 8 or 4 for 8-way or 4-way connectivity respectively -@param ltype output image label type. Currently CV_32S and CV_16U are supported. -*/ -CV_EXPORTS_W int connectedComponents(InputArray image, OutputArray labels, - int connectivity = 8, int ltype = CV_32S); - - -/** @brief computes the connected components labeled image of boolean image and also produces a statistics output for each label - -image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 -represents the background label. ltype specifies the output label image type, an important -consideration based on the total number of labels or alternatively the total number of pixels in -the source image. ccltype specifies the connected components labeling algorithm to use, currently -Bolelli (Spaghetti) @cite Bolelli2019, Grana (BBDT) @cite Grana2010 and Wu's (SAUF) @cite Wu2009 algorithms -are supported, see the #ConnectedComponentsAlgorithmsTypes for details. Note that SAUF algorithm forces -a row major ordering of labels while Spaghetti and BBDT do not. -This function uses parallel version of the algorithms (statistics included) if at least one allowed -parallel framework is enabled and if the rows of the image are at least twice the number returned by #getNumberOfCPUs. - -@param image the 8-bit single-channel image to be labeled -@param labels destination labeled image -@param stats statistics output for each label, including the background label. -Statistics are accessed via stats(label, COLUMN) where COLUMN is one of -#ConnectedComponentsTypes, selecting the statistic. The data type is CV_32S. -@param centroids centroid output for each label, including the background label. Centroids are -accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F. -@param connectivity 8 or 4 for 8-way or 4-way connectivity respectively -@param ltype output image label type. Currently CV_32S and CV_16U are supported. -@param ccltype connected components algorithm type (see #ConnectedComponentsAlgorithmsTypes). -*/ -CV_EXPORTS_AS(connectedComponentsWithStatsWithAlgorithm) int connectedComponentsWithStats(InputArray image, OutputArray labels, - OutputArray stats, OutputArray centroids, - int connectivity, int ltype, int ccltype); - -/** @overload -@param image the 8-bit single-channel image to be labeled -@param labels destination labeled image -@param stats statistics output for each label, including the background label. -Statistics are accessed via stats(label, COLUMN) where COLUMN is one of -#ConnectedComponentsTypes, selecting the statistic. The data type is CV_32S. -@param centroids centroid output for each label, including the background label. Centroids are -accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F. -@param connectivity 8 or 4 for 8-way or 4-way connectivity respectively -@param ltype output image label type. Currently CV_32S and CV_16U are supported. -*/ -CV_EXPORTS_W int connectedComponentsWithStats(InputArray image, OutputArray labels, - OutputArray stats, OutputArray centroids, - int connectivity = 8, int ltype = CV_32S); - - -/** @brief Finds contours in a binary image. - -The function retrieves contours from the binary image using the algorithm @cite Suzuki85 . The contours -are a useful tool for shape analysis and object detection and recognition. See squares.cpp in the -OpenCV sample directory. -@note Since opencv 3.2 source image is not modified by this function. - -@param image Source, an 8-bit single-channel image. Non-zero pixels are treated as 1's. Zero -pixels remain 0's, so the image is treated as binary . You can use #compare, #inRange, #threshold , -#adaptiveThreshold, #Canny, and others to create a binary image out of a grayscale or color one. -If mode equals to #RETR_CCOMP or #RETR_FLOODFILL, the input can also be a 32-bit integer image of labels (CV_32SC1). -@param contours Detected contours. Each contour is stored as a vector of points (e.g. -std::vector >). -@param hierarchy Optional output vector (e.g. std::vector), containing information about the image topology. It has -as many elements as the number of contours. For each i-th contour contours[i], the elements -hierarchy[i][0] , hierarchy[i][1] , hierarchy[i][2] , and hierarchy[i][3] are set to 0-based indices -in contours of the next and previous contours at the same hierarchical level, the first child -contour and the parent contour, respectively. If for the contour i there are no next, previous, -parent, or nested contours, the corresponding elements of hierarchy[i] will be negative. -@note In Python, hierarchy is nested inside a top level array. Use hierarchy[0][i] to access hierarchical elements of i-th contour. -@param mode Contour retrieval mode, see #RetrievalModes -@param method Contour approximation method, see #ContourApproximationModes -@param offset Optional offset by which every contour point is shifted. This is useful if the -contours are extracted from the image ROI and then they should be analyzed in the whole image -context. - */ -CV_EXPORTS_W void findContours( InputArray image, OutputArrayOfArrays contours, - OutputArray hierarchy, int mode, - int method, Point offset = Point()); - -/** @overload */ -CV_EXPORTS void findContours( InputArray image, OutputArrayOfArrays contours, - int mode, int method, Point offset = Point()); - -//! @brief Find contours using link runs algorithm -//! -//! This function implements an algorithm different from cv::findContours: -//! - doesn't allocate temporary image internally, thus it has reduced memory consumption -//! - supports CV_8UC1 images only -//! - outputs 2-level hierarhy only (RETR_CCOMP mode) -//! - doesn't support approximation change other than CHAIN_APPROX_SIMPLE -//! In all other aspects this function is compatible with cv::findContours. -CV_EXPORTS_W void findContoursLinkRuns(InputArray image, OutputArrayOfArrays contours, OutputArray hierarchy); - -//! @overload -CV_EXPORTS_W void findContoursLinkRuns(InputArray image, OutputArrayOfArrays contours); - -/** @brief Approximates a polygonal curve(s) with the specified precision. - -The function cv::approxPolyDP approximates a curve or a polygon with another curve/polygon with less -vertices so that the distance between them is less or equal to the specified precision. It uses the -Douglas-Peucker algorithm - -@param curve Input vector of a 2D point stored in std::vector or Mat -@param approxCurve Result of the approximation. The type should match the type of the input curve. -@param epsilon Parameter specifying the approximation accuracy. This is the maximum distance -between the original curve and its approximation. -@param closed If true, the approximated curve is closed (its first and last vertices are -connected). Otherwise, it is not closed. - */ -CV_EXPORTS_W void approxPolyDP( InputArray curve, - OutputArray approxCurve, - double epsilon, bool closed ); - -/** @brief Approximates a polygon with a convex hull with a specified accuracy and number of sides. - -The cv::approxPolyN function approximates a polygon with a convex hull -so that the difference between the contour area of the original contour and the new polygon is minimal. -It uses a greedy algorithm for contracting two vertices into one in such a way that the additional area is minimal. -Straight lines formed by each edge of the convex contour are drawn and the areas of the resulting triangles are considered. -Each vertex will lie either on the original contour or outside it. - -The algorithm based on the paper @cite LowIlie2003 . - -@param curve Input vector of a 2D points stored in std::vector or Mat, points must be float or integer. -@param approxCurve Result of the approximation. The type is vector of a 2D point (Point2f or Point) in std::vector or Mat. -@param nsides The parameter defines the number of sides of the result polygon. -@param epsilon_percentage defines the percentage of the maximum of additional area. -If it equals -1, it is not used. Otherwise algorighm stops if additional area is greater than contourArea(_curve) * percentage. -If additional area exceeds the limit, algorithm returns as many vertices as there were at the moment the limit was exceeded. -@param ensure_convex If it is true, algorithm creates a convex hull of input contour. Otherwise input vector should be convex. - */ -CV_EXPORTS_W void approxPolyN(InputArray curve, OutputArray approxCurve, - int nsides, float epsilon_percentage = -1.0, - bool ensure_convex = true); - -/** @brief Calculates a contour perimeter or a curve length. - -The function computes a curve length or a closed contour perimeter. - -@param curve Input vector of 2D points, stored in std::vector or Mat. -@param closed Flag indicating whether the curve is closed or not. - */ -CV_EXPORTS_W double arcLength( InputArray curve, bool closed ); - -/** @brief Calculates the up-right bounding rectangle of a point set or non-zero pixels of gray-scale image. - -The function calculates and returns the minimal up-right bounding rectangle for the specified point set or -non-zero pixels of gray-scale image. - -@param array Input gray-scale image or 2D point set, stored in std::vector or Mat. - */ -CV_EXPORTS_W Rect boundingRect( InputArray array ); - -/** @brief Calculates a contour area. - -The function computes a contour area. Similarly to moments , the area is computed using the Green -formula. Thus, the returned area and the number of non-zero pixels, if you draw the contour using -#drawContours or #fillPoly , can be different. Also, the function will most certainly give a wrong -results for contours with self-intersections. - -Example: -@code - vector contour; - contour.push_back(Point2f(0, 0)); - contour.push_back(Point2f(10, 0)); - contour.push_back(Point2f(10, 10)); - contour.push_back(Point2f(5, 4)); - - double area0 = contourArea(contour); - vector approx; - approxPolyDP(contour, approx, 5, true); - double area1 = contourArea(approx); - - cout << "area0 =" << area0 << endl << - "area1 =" << area1 << endl << - "approx poly vertices" << approx.size() << endl; -@endcode -@param contour Input vector of 2D points (contour vertices), stored in std::vector or Mat. -@param oriented Oriented area flag. If it is true, the function returns a signed area value, -depending on the contour orientation (clockwise or counter-clockwise). Using this feature you can -determine orientation of a contour by taking the sign of an area. By default, the parameter is -false, which means that the absolute value is returned. - */ -CV_EXPORTS_W double contourArea( InputArray contour, bool oriented = false ); - -/** @brief Finds a rotated rectangle of the minimum area enclosing the input 2D point set. - -The function calculates and returns the minimum-area bounding rectangle (possibly rotated) for a -specified point set. Developer should keep in mind that the returned RotatedRect can contain negative -indices when data is close to the containing Mat element boundary. - -@param points Input vector of 2D points, stored in std::vector\<\> or Mat - */ -CV_EXPORTS_W RotatedRect minAreaRect( InputArray points ); - -/** @brief Finds the four vertices of a rotated rect. Useful to draw the rotated rectangle. - -The function finds the four vertices of a rotated rectangle. This function is useful to draw the -rectangle. In C++, instead of using this function, you can directly use RotatedRect::points method. Please -visit the @ref tutorial_bounding_rotated_ellipses "tutorial on Creating Bounding rotated boxes and ellipses for contours" for more information. - -@param box The input rotated rectangle. It may be the output of @ref minAreaRect. -@param points The output array of four vertices of rectangles. - */ -CV_EXPORTS_W void boxPoints(RotatedRect box, OutputArray points); - -/** @brief Finds a circle of the minimum area enclosing a 2D point set. - -The function finds the minimal enclosing circle of a 2D point set using an iterative algorithm. - -@param points Input vector of 2D points, stored in std::vector\<\> or Mat -@param center Output center of the circle. -@param radius Output radius of the circle. - */ -CV_EXPORTS_W void minEnclosingCircle( InputArray points, - CV_OUT Point2f& center, CV_OUT float& radius ); - -/** @example samples/cpp/minarea.cpp -*/ - -/** @brief Finds a triangle of minimum area enclosing a 2D point set and returns its area. - -The function finds a triangle of minimum area enclosing the given set of 2D points and returns its -area. The output for a given 2D point set is shown in the image below. 2D points are depicted in -*red* and the enclosing triangle in *yellow*. - -![Sample output of the minimum enclosing triangle function](pics/minenclosingtriangle.png) - -The implementation of the algorithm is based on O'Rourke's @cite ORourke86 and Klee and Laskowski's -@cite KleeLaskowski85 papers. O'Rourke provides a \f$\theta(n)\f$ algorithm for finding the minimal -enclosing triangle of a 2D convex polygon with n vertices. Since the #minEnclosingTriangle function -takes a 2D point set as input an additional preprocessing step of computing the convex hull of the -2D point set is required. The complexity of the #convexHull function is \f$O(n log(n))\f$ which is higher -than \f$\theta(n)\f$. Thus the overall complexity of the function is \f$O(n log(n))\f$. - -@param points Input vector of 2D points with depth CV_32S or CV_32F, stored in std::vector\<\> or Mat -@param triangle Output vector of three 2D points defining the vertices of the triangle. The depth -of the OutputArray must be CV_32F. - */ -CV_EXPORTS_W double minEnclosingTriangle( InputArray points, CV_OUT OutputArray triangle ); - -/** @brief Compares two shapes. - -The function compares two shapes. All three implemented methods use the Hu invariants (see #HuMoments) - -@param contour1 First contour or grayscale image. -@param contour2 Second contour or grayscale image. -@param method Comparison method, see #ShapeMatchModes -@param parameter Method-specific parameter (not supported now). - */ -CV_EXPORTS_W double matchShapes( InputArray contour1, InputArray contour2, - int method, double parameter ); - -/** @example samples/cpp/convexhull.cpp -An example using the convexHull functionality -*/ - -/** @brief Finds the convex hull of a point set. - -The function cv::convexHull finds the convex hull of a 2D point set using the Sklansky's algorithm @cite Sklansky82 -that has *O(N logN)* complexity in the current implementation. - -@param points Input 2D point set, stored in std::vector or Mat. -@param hull Output convex hull. It is either an integer vector of indices or vector of points. In -the first case, the hull elements are 0-based indices of the convex hull points in the original -array (since the set of convex hull points is a subset of the original point set). In the second -case, hull elements are the convex hull points themselves. -@param clockwise Orientation flag. If it is true, the output convex hull is oriented clockwise. -Otherwise, it is oriented counter-clockwise. The assumed coordinate system has its X axis pointing -to the right, and its Y axis pointing upwards. -@param returnPoints Operation flag. In case of a matrix, when the flag is true, the function -returns convex hull points. Otherwise, it returns indices of the convex hull points. When the -output array is std::vector, the flag is ignored, and the output depends on the type of the -vector: std::vector\ implies returnPoints=false, std::vector\ implies -returnPoints=true. - -@note `points` and `hull` should be different arrays, inplace processing isn't supported. - -Check @ref tutorial_hull "the corresponding tutorial" for more details. - -useful links: - -https://www.learnopencv.com/convex-hull-using-opencv-in-python-and-c/ - */ -CV_EXPORTS_W void convexHull( InputArray points, OutputArray hull, - bool clockwise = false, bool returnPoints = true ); - -/** @brief Finds the convexity defects of a contour. - -The figure below displays convexity defects of a hand contour: - -![image](pics/defects.png) - -@param contour Input contour. -@param convexhull Convex hull obtained using convexHull that should contain indices of the contour -points that make the hull. -@param convexityDefects The output vector of convexity defects. In C++ and the new Python/Java -interface each convexity defect is represented as 4-element integer vector (a.k.a. #Vec4i): -(start_index, end_index, farthest_pt_index, fixpt_depth), where indices are 0-based indices -in the original contour of the convexity defect beginning, end and the farthest point, and -fixpt_depth is fixed-point approximation (with 8 fractional bits) of the distance between the -farthest contour point and the hull. That is, to get the floating-point value of the depth will be -fixpt_depth/256.0. - */ -CV_EXPORTS_W void convexityDefects( InputArray contour, InputArray convexhull, OutputArray convexityDefects ); - -/** @brief Tests a contour convexity. - -The function tests whether the input contour is convex or not. The contour must be simple, that is, -without self-intersections. Otherwise, the function output is undefined. - -@param contour Input vector of 2D points, stored in std::vector\<\> or Mat - */ -CV_EXPORTS_W bool isContourConvex( InputArray contour ); - -/** @example samples/cpp/intersectExample.cpp -Examples of how intersectConvexConvex works -*/ - -/** @brief Finds intersection of two convex polygons - -@param p1 First polygon -@param p2 Second polygon -@param p12 Output polygon describing the intersecting area -@param handleNested When true, an intersection is found if one of the polygons is fully enclosed in the other. -When false, no intersection is found. If the polygons share a side or the vertex of one polygon lies on an edge -of the other, they are not considered nested and an intersection will be found regardless of the value of handleNested. - -@returns Area of intersecting polygon. May be negative, if algorithm has not converged, e.g. non-convex input. - -@note intersectConvexConvex doesn't confirm that both polygons are convex and will return invalid results if they aren't. - */ -CV_EXPORTS_W float intersectConvexConvex( InputArray p1, InputArray p2, - OutputArray p12, bool handleNested = true ); - -/** @example samples/cpp/fitellipse.cpp -An example using the fitEllipse technique -*/ - -/** @brief Fits an ellipse around a set of 2D points. - -The function calculates the ellipse that fits (in a least-squares sense) a set of 2D points best of -all. It returns the rotated rectangle in which the ellipse is inscribed. The first algorithm described by @cite Fitzgibbon95 -is used. Developer should keep in mind that it is possible that the returned -ellipse/rotatedRect data contains negative indices, due to the data points being close to the -border of the containing Mat element. - -@param points Input 2D point set, stored in std::vector\<\> or Mat - */ -CV_EXPORTS_W RotatedRect fitEllipse( InputArray points ); - -/** @brief Fits an ellipse around a set of 2D points. - - The function calculates the ellipse that fits a set of 2D points. - It returns the rotated rectangle in which the ellipse is inscribed. - The Approximate Mean Square (AMS) proposed by @cite Taubin1991 is used. - - For an ellipse, this basis set is \f$ \chi= \left(x^2, x y, y^2, x, y, 1\right) \f$, - which is a set of six free coefficients \f$ A^T=\left\{A_{\text{xx}},A_{\text{xy}},A_{\text{yy}},A_x,A_y,A_0\right\} \f$. - However, to specify an ellipse, all that is needed is five numbers; the major and minor axes lengths \f$ (a,b) \f$, - the position \f$ (x_0,y_0) \f$, and the orientation \f$ \theta \f$. This is because the basis set includes lines, - quadratics, parabolic and hyperbolic functions as well as elliptical functions as possible fits. - If the fit is found to be a parabolic or hyperbolic function then the standard #fitEllipse method is used. - The AMS method restricts the fit to parabolic, hyperbolic and elliptical curves - by imposing the condition that \f$ A^T ( D_x^T D_x + D_y^T D_y) A = 1 \f$ where - the matrices \f$ Dx \f$ and \f$ Dy \f$ are the partial derivatives of the design matrix \f$ D \f$ with - respect to x and y. The matrices are formed row by row applying the following to - each of the points in the set: - \f{align*}{ - D(i,:)&=\left\{x_i^2, x_i y_i, y_i^2, x_i, y_i, 1\right\} & - D_x(i,:)&=\left\{2 x_i,y_i,0,1,0,0\right\} & - D_y(i,:)&=\left\{0,x_i,2 y_i,0,1,0\right\} - \f} - The AMS method minimizes the cost function - \f{equation*}{ - \epsilon ^2=\frac{ A^T D^T D A }{ A^T (D_x^T D_x + D_y^T D_y) A^T } - \f} - - The minimum cost is found by solving the generalized eigenvalue problem. - - \f{equation*}{ - D^T D A = \lambda \left( D_x^T D_x + D_y^T D_y\right) A - \f} - - @param points Input 2D point set, stored in std::vector\<\> or Mat - */ -CV_EXPORTS_W RotatedRect fitEllipseAMS( InputArray points ); - - -/** @brief Fits an ellipse around a set of 2D points. - - The function calculates the ellipse that fits a set of 2D points. - It returns the rotated rectangle in which the ellipse is inscribed. - The Direct least square (Direct) method by @cite oy1998NumericallySD is used. - - For an ellipse, this basis set is \f$ \chi= \left(x^2, x y, y^2, x, y, 1\right) \f$, - which is a set of six free coefficients \f$ A^T=\left\{A_{\text{xx}},A_{\text{xy}},A_{\text{yy}},A_x,A_y,A_0\right\} \f$. - However, to specify an ellipse, all that is needed is five numbers; the major and minor axes lengths \f$ (a,b) \f$, - the position \f$ (x_0,y_0) \f$, and the orientation \f$ \theta \f$. This is because the basis set includes lines, - quadratics, parabolic and hyperbolic functions as well as elliptical functions as possible fits. - The Direct method confines the fit to ellipses by ensuring that \f$ 4 A_{xx} A_{yy}- A_{xy}^2 > 0 \f$. - The condition imposed is that \f$ 4 A_{xx} A_{yy}- A_{xy}^2=1 \f$ which satisfies the inequality - and as the coefficients can be arbitrarily scaled is not overly restrictive. - - \f{equation*}{ - \epsilon ^2= A^T D^T D A \quad \text{with} \quad A^T C A =1 \quad \text{and} \quad C=\left(\begin{matrix} - 0 & 0 & 2 & 0 & 0 & 0 \\ - 0 & -1 & 0 & 0 & 0 & 0 \\ - 2 & 0 & 0 & 0 & 0 & 0 \\ - 0 & 0 & 0 & 0 & 0 & 0 \\ - 0 & 0 & 0 & 0 & 0 & 0 \\ - 0 & 0 & 0 & 0 & 0 & 0 - \end{matrix} \right) - \f} - - The minimum cost is found by solving the generalized eigenvalue problem. - - \f{equation*}{ - D^T D A = \lambda \left( C\right) A - \f} - - The system produces only one positive eigenvalue \f$ \lambda\f$ which is chosen as the solution - with its eigenvector \f$\mathbf{u}\f$. These are used to find the coefficients - - \f{equation*}{ - A = \sqrt{\frac{1}{\mathbf{u}^T C \mathbf{u}}} \mathbf{u} - \f} - The scaling factor guarantees that \f$A^T C A =1\f$. - - @param points Input 2D point set, stored in std::vector\<\> or Mat - */ -CV_EXPORTS_W RotatedRect fitEllipseDirect( InputArray points ); - -/** @brief Fits a line to a 2D or 3D point set. - -The function fitLine fits a line to a 2D or 3D point set by minimizing \f$\sum_i \rho(r_i)\f$ where -\f$r_i\f$ is a distance between the \f$i^{th}\f$ point, the line and \f$\rho(r)\f$ is a distance function, one -of the following: -- DIST_L2 -\f[\rho (r) = r^2/2 \quad \text{(the simplest and the fastest least-squares method)}\f] -- DIST_L1 -\f[\rho (r) = r\f] -- DIST_L12 -\f[\rho (r) = 2 \cdot ( \sqrt{1 + \frac{r^2}{2}} - 1)\f] -- DIST_FAIR -\f[\rho \left (r \right ) = C^2 \cdot \left ( \frac{r}{C} - \log{\left(1 + \frac{r}{C}\right)} \right ) \quad \text{where} \quad C=1.3998\f] -- DIST_WELSCH -\f[\rho \left (r \right ) = \frac{C^2}{2} \cdot \left ( 1 - \exp{\left(-\left(\frac{r}{C}\right)^2\right)} \right ) \quad \text{where} \quad C=2.9846\f] -- DIST_HUBER -\f[\rho (r) = \fork{r^2/2}{if \(r < C\)}{C \cdot (r-C/2)}{otherwise} \quad \text{where} \quad C=1.345\f] - -The algorithm is based on the M-estimator ( ) technique -that iteratively fits the line using the weighted least-squares algorithm. After each iteration the -weights \f$w_i\f$ are adjusted to be inversely proportional to \f$\rho(r_i)\f$ . - -@param points Input vector of 2D or 3D points, stored in std::vector\<\> or Mat. -@param line Output line parameters. In case of 2D fitting, it should be a vector of 4 elements -(like Vec4f) - (vx, vy, x0, y0), where (vx, vy) is a normalized vector collinear to the line and -(x0, y0) is a point on the line. In case of 3D fitting, it should be a vector of 6 elements (like -Vec6f) - (vx, vy, vz, x0, y0, z0), where (vx, vy, vz) is a normalized vector collinear to the line -and (x0, y0, z0) is a point on the line. -@param distType Distance used by the M-estimator, see #DistanceTypes -@param param Numerical parameter ( C ) for some types of distances. If it is 0, an optimal value -is chosen. -@param reps Sufficient accuracy for the radius (distance between the coordinate origin and the line). -@param aeps Sufficient accuracy for the angle. 0.01 would be a good default value for reps and aeps. - */ -CV_EXPORTS_W void fitLine( InputArray points, OutputArray line, int distType, - double param, double reps, double aeps ); - -/** @brief Performs a point-in-contour test. - -The function determines whether the point is inside a contour, outside, or lies on an edge (or -coincides with a vertex). It returns positive (inside), negative (outside), or zero (on an edge) -value, correspondingly. When measureDist=false , the return value is +1, -1, and 0, respectively. -Otherwise, the return value is a signed distance between the point and the nearest contour edge. - -See below a sample output of the function where each image pixel is tested against the contour: - -![sample output](pics/pointpolygon.png) - -@param contour Input contour. -@param pt Point tested against the contour. -@param measureDist If true, the function estimates the signed distance from the point to the -nearest contour edge. Otherwise, the function only checks if the point is inside a contour or not. - */ -CV_EXPORTS_W double pointPolygonTest( InputArray contour, Point2f pt, bool measureDist ); - -/** @brief Finds out if there is any intersection between two rotated rectangles. - -If there is then the vertices of the intersecting region are returned as well. - -Below are some examples of intersection configurations. The hatched pattern indicates the -intersecting region and the red vertices are returned by the function. - -![intersection examples](pics/intersection.png) - -@param rect1 First rectangle -@param rect2 Second rectangle -@param intersectingRegion The output array of the vertices of the intersecting region. It returns -at most 8 vertices. Stored as std::vector\ or cv::Mat as Mx1 of type CV_32FC2. -@returns One of #RectanglesIntersectTypes - */ -CV_EXPORTS_W int rotatedRectangleIntersection( const RotatedRect& rect1, const RotatedRect& rect2, OutputArray intersectingRegion ); - -/** @brief Creates a smart pointer to a cv::GeneralizedHoughBallard class and initializes it. -*/ -CV_EXPORTS_W Ptr createGeneralizedHoughBallard(); - -/** @brief Creates a smart pointer to a cv::GeneralizedHoughGuil class and initializes it. -*/ -CV_EXPORTS_W Ptr createGeneralizedHoughGuil(); - -//! @} imgproc_shape - -//! @addtogroup imgproc_colormap -//! @{ - -//! GNU Octave/MATLAB equivalent colormaps -enum ColormapTypes -{ - COLORMAP_AUTUMN = 0, //!< ![autumn](pics/colormaps/colorscale_autumn.jpg) - COLORMAP_BONE = 1, //!< ![bone](pics/colormaps/colorscale_bone.jpg) - COLORMAP_JET = 2, //!< ![jet](pics/colormaps/colorscale_jet.jpg) - COLORMAP_WINTER = 3, //!< ![winter](pics/colormaps/colorscale_winter.jpg) - COLORMAP_RAINBOW = 4, //!< ![rainbow](pics/colormaps/colorscale_rainbow.jpg) - COLORMAP_OCEAN = 5, //!< ![ocean](pics/colormaps/colorscale_ocean.jpg) - COLORMAP_SUMMER = 6, //!< ![summer](pics/colormaps/colorscale_summer.jpg) - COLORMAP_SPRING = 7, //!< ![spring](pics/colormaps/colorscale_spring.jpg) - COLORMAP_COOL = 8, //!< ![cool](pics/colormaps/colorscale_cool.jpg) - COLORMAP_HSV = 9, //!< ![HSV](pics/colormaps/colorscale_hsv.jpg) - COLORMAP_PINK = 10, //!< ![pink](pics/colormaps/colorscale_pink.jpg) - COLORMAP_HOT = 11, //!< ![hot](pics/colormaps/colorscale_hot.jpg) - COLORMAP_PARULA = 12, //!< ![parula](pics/colormaps/colorscale_parula.jpg) - COLORMAP_MAGMA = 13, //!< ![magma](pics/colormaps/colorscale_magma.jpg) - COLORMAP_INFERNO = 14, //!< ![inferno](pics/colormaps/colorscale_inferno.jpg) - COLORMAP_PLASMA = 15, //!< ![plasma](pics/colormaps/colorscale_plasma.jpg) - COLORMAP_VIRIDIS = 16, //!< ![viridis](pics/colormaps/colorscale_viridis.jpg) - COLORMAP_CIVIDIS = 17, //!< ![cividis](pics/colormaps/colorscale_cividis.jpg) - COLORMAP_TWILIGHT = 18, //!< ![twilight](pics/colormaps/colorscale_twilight.jpg) - COLORMAP_TWILIGHT_SHIFTED = 19, //!< ![twilight shifted](pics/colormaps/colorscale_twilight_shifted.jpg) - COLORMAP_TURBO = 20, //!< ![turbo](pics/colormaps/colorscale_turbo.jpg) - COLORMAP_DEEPGREEN = 21 //!< ![deepgreen](pics/colormaps/colorscale_deepgreen.jpg) -}; - -/** @example samples/cpp/falsecolor.cpp -An example using applyColorMap function -*/ - -/** @brief Applies a GNU Octave/MATLAB equivalent colormap on a given image. - -@param src The source image, grayscale or colored of type CV_8UC1 or CV_8UC3. If CV_8UC3, then the CV_8UC1 image is generated internally using cv::COLOR_BGR2GRAY. -@param dst The result is the colormapped source image. Note: Mat::create is called on dst. -@param colormap The colormap to apply, see #ColormapTypes -*/ -CV_EXPORTS_W void applyColorMap(InputArray src, OutputArray dst, int colormap); - -/** @brief Applies a user colormap on a given image. - -@param src The source image, grayscale or colored of type CV_8UC1 or CV_8UC3. If CV_8UC3, then the CV_8UC1 image is generated internally using cv::COLOR_BGR2GRAY. -@param dst The result is the colormapped source image of the same number of channels as userColor. Note: Mat::create is called on dst. -@param userColor The colormap to apply of type CV_8UC1 or CV_8UC3 and size 256 -*/ -CV_EXPORTS_W void applyColorMap(InputArray src, OutputArray dst, InputArray userColor); - -//! @} imgproc_colormap - -//! @addtogroup imgproc_draw -//! @{ - - -/** OpenCV color channel order is BGR[A] */ -#define CV_RGB(r, g, b) cv::Scalar((b), (g), (r), 0) - -/** @brief Draws a line segment connecting two points. - -The function line draws the line segment between pt1 and pt2 points in the image. The line is -clipped by the image boundaries. For non-antialiased lines with integer coordinates, the 8-connected -or 4-connected Bresenham algorithm is used. Thick lines are drawn with rounding endings. Antialiased -lines are drawn using Gaussian filtering. - -@param img Image. -@param pt1 First point of the line segment. -@param pt2 Second point of the line segment. -@param color Line color. -@param thickness Line thickness. -@param lineType Type of the line. See #LineTypes. -@param shift Number of fractional bits in the point coordinates. - */ -CV_EXPORTS_W void line(InputOutputArray img, Point pt1, Point pt2, const Scalar& color, - int thickness = 1, int lineType = LINE_8, int shift = 0); - -/** @brief Draws an arrow segment pointing from the first point to the second one. - -The function cv::arrowedLine draws an arrow between pt1 and pt2 points in the image. See also #line. - -@param img Image. -@param pt1 The point the arrow starts from. -@param pt2 The point the arrow points to. -@param color Line color. -@param thickness Line thickness. -@param line_type Type of the line. See #LineTypes -@param shift Number of fractional bits in the point coordinates. -@param tipLength The length of the arrow tip in relation to the arrow length - */ -CV_EXPORTS_W void arrowedLine(InputOutputArray img, Point pt1, Point pt2, const Scalar& color, - int thickness=1, int line_type=8, int shift=0, double tipLength=0.1); - -/** @brief Draws a simple, thick, or filled up-right rectangle. - -The function cv::rectangle draws a rectangle outline or a filled rectangle whose two opposite corners -are pt1 and pt2. - -@param img Image. -@param pt1 Vertex of the rectangle. -@param pt2 Vertex of the rectangle opposite to pt1 . -@param color Rectangle color or brightness (grayscale image). -@param thickness Thickness of lines that make up the rectangle. Negative values, like #FILLED, -mean that the function has to draw a filled rectangle. -@param lineType Type of the line. See #LineTypes -@param shift Number of fractional bits in the point coordinates. - */ -CV_EXPORTS_W void rectangle(InputOutputArray img, Point pt1, Point pt2, - const Scalar& color, int thickness = 1, - int lineType = LINE_8, int shift = 0); - -/** @overload - -use `rec` parameter as alternative specification of the drawn rectangle: `r.tl() and -r.br()-Point(1,1)` are opposite corners -*/ -CV_EXPORTS_W void rectangle(InputOutputArray img, Rect rec, - const Scalar& color, int thickness = 1, - int lineType = LINE_8, int shift = 0); - -/** @example samples/cpp/tutorial_code/ImgProc/basic_drawing/Drawing_2.cpp -An example using drawing functions -*/ - -/** @brief Draws a circle. - -The function cv::circle draws a simple or filled circle with a given center and radius. -@param img Image where the circle is drawn. -@param center Center of the circle. -@param radius Radius of the circle. -@param color Circle color. -@param thickness Thickness of the circle outline, if positive. Negative values, like #FILLED, -mean that a filled circle is to be drawn. -@param lineType Type of the circle boundary. See #LineTypes -@param shift Number of fractional bits in the coordinates of the center and in the radius value. - */ -CV_EXPORTS_W void circle(InputOutputArray img, Point center, int radius, - const Scalar& color, int thickness = 1, - int lineType = LINE_8, int shift = 0); - -/** @brief Draws a simple or thick elliptic arc or fills an ellipse sector. - -The function cv::ellipse with more parameters draws an ellipse outline, a filled ellipse, an elliptic -arc, or a filled ellipse sector. The drawing code uses general parametric form. -A piecewise-linear curve is used to approximate the elliptic arc -boundary. If you need more control of the ellipse rendering, you can retrieve the curve using -#ellipse2Poly and then render it with #polylines or fill it with #fillPoly. If you use the first -variant of the function and want to draw the whole ellipse, not an arc, pass `startAngle=0` and -`endAngle=360`. If `startAngle` is greater than `endAngle`, they are swapped. The figure below explains -the meaning of the parameters to draw the blue arc. - -![Parameters of Elliptic Arc](pics/ellipse.svg) - -@param img Image. -@param center Center of the ellipse. -@param axes Half of the size of the ellipse main axes. -@param angle Ellipse rotation angle in degrees. -@param startAngle Starting angle of the elliptic arc in degrees. -@param endAngle Ending angle of the elliptic arc in degrees. -@param color Ellipse color. -@param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that -a filled ellipse sector is to be drawn. -@param lineType Type of the ellipse boundary. See #LineTypes -@param shift Number of fractional bits in the coordinates of the center and values of axes. - */ -CV_EXPORTS_W void ellipse(InputOutputArray img, Point center, Size axes, - double angle, double startAngle, double endAngle, - const Scalar& color, int thickness = 1, - int lineType = LINE_8, int shift = 0); - -/** @overload -@param img Image. -@param box Alternative ellipse representation via RotatedRect. This means that the function draws -an ellipse inscribed in the rotated rectangle. -@param color Ellipse color. -@param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that -a filled ellipse sector is to be drawn. -@param lineType Type of the ellipse boundary. See #LineTypes -*/ -CV_EXPORTS_W void ellipse(InputOutputArray img, const RotatedRect& box, const Scalar& color, - int thickness = 1, int lineType = LINE_8); - -/* ----------------------------------------------------------------------------------------- */ -/* ADDING A SET OF PREDEFINED MARKERS WHICH COULD BE USED TO HIGHLIGHT POSITIONS IN AN IMAGE */ -/* ----------------------------------------------------------------------------------------- */ - -/** @brief Draws a marker on a predefined position in an image. - -The function cv::drawMarker draws a marker on a given position in the image. For the moment several -marker types are supported, see #MarkerTypes for more information. - -@param img Image. -@param position The point where the crosshair is positioned. -@param color Line color. -@param markerType The specific type of marker you want to use, see #MarkerTypes -@param thickness Line thickness. -@param line_type Type of the line, See #LineTypes -@param markerSize The length of the marker axis [default = 20 pixels] - */ -CV_EXPORTS_W void drawMarker(InputOutputArray img, Point position, const Scalar& color, - int markerType = MARKER_CROSS, int markerSize=20, int thickness=1, - int line_type=8); - -/* ----------------------------------------------------------------------------------------- */ -/* END OF MARKER SECTION */ -/* ----------------------------------------------------------------------------------------- */ - -/** @brief Fills a convex polygon. - -The function cv::fillConvexPoly draws a filled convex polygon. This function is much faster than the -function #fillPoly . It can fill not only convex polygons but any monotonic polygon without -self-intersections, that is, a polygon whose contour intersects every horizontal line (scan line) -twice at the most (though, its top-most and/or the bottom edge could be horizontal). - -@param img Image. -@param points Polygon vertices. -@param color Polygon color. -@param lineType Type of the polygon boundaries. See #LineTypes -@param shift Number of fractional bits in the vertex coordinates. - */ -CV_EXPORTS_W void fillConvexPoly(InputOutputArray img, InputArray points, - const Scalar& color, int lineType = LINE_8, - int shift = 0); - -/** @overload */ -CV_EXPORTS void fillConvexPoly(InputOutputArray img, const Point* pts, int npts, - const Scalar& color, int lineType = LINE_8, - int shift = 0); - -/** @example samples/cpp/tutorial_code/ImgProc/basic_drawing/Drawing_1.cpp -An example using drawing functions -Check @ref tutorial_random_generator_and_text "the corresponding tutorial" for more details -*/ - -/** @brief Fills the area bounded by one or more polygons. - -The function cv::fillPoly fills an area bounded by several polygonal contours. The function can fill -complex areas, for example, areas with holes, contours with self-intersections (some of their -parts), and so forth. - -@param img Image. -@param pts Array of polygons where each polygon is represented as an array of points. -@param color Polygon color. -@param lineType Type of the polygon boundaries. See #LineTypes -@param shift Number of fractional bits in the vertex coordinates. -@param offset Optional offset of all points of the contours. - */ -CV_EXPORTS_W void fillPoly(InputOutputArray img, InputArrayOfArrays pts, - const Scalar& color, int lineType = LINE_8, int shift = 0, - Point offset = Point() ); - -/** @overload */ -CV_EXPORTS void fillPoly(InputOutputArray img, const Point** pts, - const int* npts, int ncontours, - const Scalar& color, int lineType = LINE_8, int shift = 0, - Point offset = Point() ); - -/** @brief Draws several polygonal curves. - -@param img Image. -@param pts Array of polygonal curves. -@param isClosed Flag indicating whether the drawn polylines are closed or not. If they are closed, -the function draws a line from the last vertex of each curve to its first vertex. -@param color Polyline color. -@param thickness Thickness of the polyline edges. -@param lineType Type of the line segments. See #LineTypes -@param shift Number of fractional bits in the vertex coordinates. - -The function cv::polylines draws one or more polygonal curves. - */ -CV_EXPORTS_W void polylines(InputOutputArray img, InputArrayOfArrays pts, - bool isClosed, const Scalar& color, - int thickness = 1, int lineType = LINE_8, int shift = 0 ); - -/** @overload */ -CV_EXPORTS void polylines(InputOutputArray img, const Point* const* pts, const int* npts, - int ncontours, bool isClosed, const Scalar& color, - int thickness = 1, int lineType = LINE_8, int shift = 0 ); - -/** @example samples/cpp/contours2.cpp -An example program illustrates the use of cv::findContours and cv::drawContours -\image html WindowsQtContoursOutput.png "Screenshot of the program" -*/ - -/** @example samples/cpp/segment_objects.cpp -An example using drawContours to clean up a background segmentation result -*/ - -/** @brief Draws contours outlines or filled contours. - -The function draws contour outlines in the image if \f$\texttt{thickness} \ge 0\f$ or fills the area -bounded by the contours if \f$\texttt{thickness}<0\f$ . The example below shows how to retrieve -connected components from the binary image and label them: : -@include snippets/imgproc_drawContours.cpp - -@param image Destination image. -@param contours All the input contours. Each contour is stored as a point vector. -@param contourIdx Parameter indicating a contour to draw. If it is negative, all the contours are drawn. -@param color Color of the contours. -@param thickness Thickness of lines the contours are drawn with. If it is negative (for example, -thickness=#FILLED ), the contour interiors are drawn. -@param lineType Line connectivity. See #LineTypes -@param hierarchy Optional information about hierarchy. It is only needed if you want to draw only -some of the contours (see maxLevel ). -@param maxLevel Maximal level for drawn contours. If it is 0, only the specified contour is drawn. -If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function -draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This -parameter is only taken into account when there is hierarchy available. -@param offset Optional contour shift parameter. Shift all the drawn contours by the specified -\f$\texttt{offset}=(dx,dy)\f$ . -@note When thickness=#FILLED, the function is designed to handle connected components with holes correctly -even when no hierarchy data is provided. This is done by analyzing all the outlines together -using even-odd rule. This may give incorrect results if you have a joint collection of separately retrieved -contours. In order to solve this problem, you need to call #drawContours separately for each sub-group -of contours, or iterate over the collection using contourIdx parameter. - */ -CV_EXPORTS_W void drawContours( InputOutputArray image, InputArrayOfArrays contours, - int contourIdx, const Scalar& color, - int thickness = 1, int lineType = LINE_8, - InputArray hierarchy = noArray(), - int maxLevel = INT_MAX, Point offset = Point() ); - -/** @brief Clips the line against the image rectangle. - -The function cv::clipLine calculates a part of the line segment that is entirely within the specified -rectangle. It returns false if the line segment is completely outside the rectangle. Otherwise, -it returns true . -@param imgSize Image size. The image rectangle is Rect(0, 0, imgSize.width, imgSize.height) . -@param pt1 First line point. -@param pt2 Second line point. - */ -CV_EXPORTS bool clipLine(Size imgSize, CV_IN_OUT Point& pt1, CV_IN_OUT Point& pt2); - -/** @overload -@param imgSize Image size. The image rectangle is Rect(0, 0, imgSize.width, imgSize.height) . -@param pt1 First line point. -@param pt2 Second line point. -*/ -CV_EXPORTS bool clipLine(Size2l imgSize, CV_IN_OUT Point2l& pt1, CV_IN_OUT Point2l& pt2); - -/** @overload -@param imgRect Image rectangle. -@param pt1 First line point. -@param pt2 Second line point. -*/ -CV_EXPORTS_W bool clipLine(Rect imgRect, CV_OUT CV_IN_OUT Point& pt1, CV_OUT CV_IN_OUT Point& pt2); - -/** @brief Approximates an elliptic arc with a polyline. - -The function ellipse2Poly computes the vertices of a polyline that approximates the specified -elliptic arc. It is used by #ellipse. If `arcStart` is greater than `arcEnd`, they are swapped. - -@param center Center of the arc. -@param axes Half of the size of the ellipse main axes. See #ellipse for details. -@param angle Rotation angle of the ellipse in degrees. See #ellipse for details. -@param arcStart Starting angle of the elliptic arc in degrees. -@param arcEnd Ending angle of the elliptic arc in degrees. -@param delta Angle between the subsequent polyline vertices. It defines the approximation -accuracy. -@param pts Output vector of polyline vertices. - */ -CV_EXPORTS_W void ellipse2Poly( Point center, Size axes, int angle, - int arcStart, int arcEnd, int delta, - CV_OUT std::vector& pts ); - -/** @overload -@param center Center of the arc. -@param axes Half of the size of the ellipse main axes. See #ellipse for details. -@param angle Rotation angle of the ellipse in degrees. See #ellipse for details. -@param arcStart Starting angle of the elliptic arc in degrees. -@param arcEnd Ending angle of the elliptic arc in degrees. -@param delta Angle between the subsequent polyline vertices. It defines the approximation accuracy. -@param pts Output vector of polyline vertices. -*/ -CV_EXPORTS void ellipse2Poly(Point2d center, Size2d axes, int angle, - int arcStart, int arcEnd, int delta, - CV_OUT std::vector& pts); - -/** @brief Draws a text string. - -The function cv::putText renders the specified text string in the image. Symbols that cannot be rendered -using the specified font are replaced by question marks. See #getTextSize for a text rendering code -example. - -@param img Image. -@param text Text string to be drawn. -@param org Bottom-left corner of the text string in the image. -@param fontFace Font type, see #HersheyFonts. -@param fontScale Font scale factor that is multiplied by the font-specific base size. -@param color Text color. -@param thickness Thickness of the lines used to draw a text. -@param lineType Line type. See #LineTypes -@param bottomLeftOrigin When true, the image data origin is at the bottom-left corner. Otherwise, -it is at the top-left corner. - */ -CV_EXPORTS_W void putText( InputOutputArray img, const String& text, Point org, - int fontFace, double fontScale, Scalar color, - int thickness = 1, int lineType = LINE_8, - bool bottomLeftOrigin = false ); - -/** @brief Calculates the width and height of a text string. - -The function cv::getTextSize calculates and returns the size of a box that contains the specified text. -That is, the following code renders some text, the tight box surrounding it, and the baseline: : -@code - String text = "Funny text inside the box"; - int fontFace = FONT_HERSHEY_SCRIPT_SIMPLEX; - double fontScale = 2; - int thickness = 3; - - Mat img(600, 800, CV_8UC3, Scalar::all(0)); - - int baseline=0; - Size textSize = getTextSize(text, fontFace, - fontScale, thickness, &baseline); - baseline += thickness; - - // center the text - Point textOrg((img.cols - textSize.width)/2, - (img.rows + textSize.height)/2); - - // draw the box - rectangle(img, textOrg + Point(0, baseline), - textOrg + Point(textSize.width, -textSize.height), - Scalar(0,0,255)); - // ... and the baseline first - line(img, textOrg + Point(0, thickness), - textOrg + Point(textSize.width, thickness), - Scalar(0, 0, 255)); - - // then put the text itself - putText(img, text, textOrg, fontFace, fontScale, - Scalar::all(255), thickness, 8); -@endcode - -@param text Input text string. -@param fontFace Font to use, see #HersheyFonts. -@param fontScale Font scale factor that is multiplied by the font-specific base size. -@param thickness Thickness of lines used to render the text. See #putText for details. -@param[out] baseLine y-coordinate of the baseline relative to the bottom-most text -point. -@return The size of a box that contains the specified text. - -@see putText - */ -CV_EXPORTS_W Size getTextSize(const String& text, int fontFace, - double fontScale, int thickness, - CV_OUT int* baseLine); - - -/** @brief Calculates the font-specific size to use to achieve a given height in pixels. - -@param fontFace Font to use, see cv::HersheyFonts. -@param pixelHeight Pixel height to compute the fontScale for -@param thickness Thickness of lines used to render the text.See putText for details. -@return The fontSize to use for cv::putText - -@see cv::putText -*/ -CV_EXPORTS_W double getFontScaleFromHeight(const int fontFace, - const int pixelHeight, - const int thickness = 1); - -/** @brief Class for iterating over all pixels on a raster line segment. - -The class LineIterator is used to get each pixel of a raster line connecting -two specified points. -It can be treated as a versatile implementation of the Bresenham algorithm -where you can stop at each pixel and do some extra processing, for -example, grab pixel values along the line or draw a line with an effect -(for example, with XOR operation). - -The number of pixels along the line is stored in LineIterator::count. -The method LineIterator::pos returns the current position in the image: - -@code{.cpp} -// grabs pixels along the line (pt1, pt2) -// from 8-bit 3-channel image to the buffer -LineIterator it(img, pt1, pt2, 8); -LineIterator it2 = it; -vector buf(it.count); - -for(int i = 0; i < it.count; i++, ++it) - buf[i] = *(const Vec3b*)*it; - -// alternative way of iterating through the line -for(int i = 0; i < it2.count; i++, ++it2) -{ - Vec3b val = img.at(it2.pos()); - CV_Assert(buf[i] == val); -} -@endcode -*/ -class CV_EXPORTS LineIterator -{ -public: - /** @brief Initializes iterator object for the given line and image. - - The returned iterator can be used to traverse all pixels on a line that - connects the given two points. - The line will be clipped on the image boundaries. - - @param img Underlying image. - @param pt1 First endpoint of the line. - @param pt2 The other endpoint of the line. - @param connectivity Pixel connectivity of the iterator. Valid values are 4 (iterator can move - up, down, left and right) and 8 (iterator can also move diagonally). - @param leftToRight If true, the line is traversed from the leftmost endpoint to the rightmost - endpoint. Otherwise, the line is traversed from \p pt1 to \p pt2. - */ - LineIterator( const Mat& img, Point pt1, Point pt2, - int connectivity = 8, bool leftToRight = false ) - { - init(&img, Rect(0, 0, img.cols, img.rows), pt1, pt2, connectivity, leftToRight); - ptmode = false; - } - LineIterator( Point pt1, Point pt2, - int connectivity = 8, bool leftToRight = false ) - { - init(0, Rect(std::min(pt1.x, pt2.x), - std::min(pt1.y, pt2.y), - std::max(pt1.x, pt2.x) - std::min(pt1.x, pt2.x) + 1, - std::max(pt1.y, pt2.y) - std::min(pt1.y, pt2.y) + 1), - pt1, pt2, connectivity, leftToRight); - ptmode = true; - } - LineIterator( Size boundingAreaSize, Point pt1, Point pt2, - int connectivity = 8, bool leftToRight = false ) - { - init(0, Rect(0, 0, boundingAreaSize.width, boundingAreaSize.height), - pt1, pt2, connectivity, leftToRight); - ptmode = true; - } - LineIterator( Rect boundingAreaRect, Point pt1, Point pt2, - int connectivity = 8, bool leftToRight = false ) - { - init(0, boundingAreaRect, pt1, pt2, connectivity, leftToRight); - ptmode = true; - } - void init(const Mat* img, Rect boundingAreaRect, Point pt1, Point pt2, int connectivity, bool leftToRight); - - /** @brief Returns pointer to the current pixel. - */ - uchar* operator *(); - - /** @brief Moves iterator to the next pixel on the line. - - This is the prefix version (++it). - */ - LineIterator& operator ++(); - - /** @brief Moves iterator to the next pixel on the line. - - This is the postfix version (it++). - */ - LineIterator operator ++(int); - - /** @brief Returns coordinates of the current pixel. - */ - Point pos() const; - - uchar* ptr; - const uchar* ptr0; - int step, elemSize; - int err, count; - int minusDelta, plusDelta; - int minusStep, plusStep; - int minusShift, plusShift; - Point p; - bool ptmode; -}; - -//! @cond IGNORED - -// === LineIterator implementation === - -inline -uchar* LineIterator::operator *() -{ - return ptmode ? 0 : ptr; -} - -inline -LineIterator& LineIterator::operator ++() -{ - int mask = err < 0 ? -1 : 0; - err += minusDelta + (plusDelta & mask); - if(!ptmode) - { - ptr += minusStep + (plusStep & mask); - } - else - { - p.x += minusShift + (plusShift & mask); - p.y += minusStep + (plusStep & mask); - } - return *this; -} - -inline -LineIterator LineIterator::operator ++(int) -{ - LineIterator it = *this; - ++(*this); - return it; -} - -inline -Point LineIterator::pos() const -{ - if(!ptmode) - { - size_t offset = (size_t)(ptr - ptr0); - int y = (int)(offset/step); - int x = (int)((offset - (size_t)y*step)/elemSize); - return Point(x, y); - } - return p; -} - -//! @endcond - -//! @} imgproc_draw - -//! @} imgproc - -} // cv - - -#include "./imgproc/segmentation.hpp" - - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_IMGPROC_HPP +#define OPENCV_IMGPROC_HPP + +#include "opencv2/core.hpp" + +/** +@defgroup imgproc Image Processing + +This module offers a comprehensive suite of image processing functions, enabling tasks such as those listed above. + +@{ + @defgroup imgproc_filter Image Filtering + + Functions and classes described in this section are used to perform various linear or non-linear + filtering operations on 2D images (represented as Mat's). It means that for each pixel location + \f$(x,y)\f$ in the source image (normally, rectangular), its neighborhood is considered and used to + compute the response. In case of a linear filter, it is a weighted sum of pixel values. In case of + morphological operations, it is the minimum or maximum values, and so on. The computed response is + stored in the destination image at the same location \f$(x,y)\f$. It means that the output image + will be of the same size as the input image. Normally, the functions support multi-channel arrays, + in which case every channel is processed independently. Therefore, the output image will also have + the same number of channels as the input one. + + Another common feature of the functions and classes described in this section is that, unlike + simple arithmetic functions, they need to extrapolate values of some non-existing pixels. For + example, if you want to smooth an image using a Gaussian \f$3 \times 3\f$ filter, then, when + processing the left-most pixels in each row, you need pixels to the left of them, that is, outside + of the image. You can let these pixels be the same as the left-most image pixels ("replicated + border" extrapolation method), or assume that all the non-existing pixels are zeros ("constant + border" extrapolation method), and so on. OpenCV enables you to specify the extrapolation method. + For details, see #BorderTypes + + @anchor filter_depths + ### Depth combinations + Input depth (src.depth()) | Output depth (ddepth) + --------------------------|---------------------- + CV_8U | -1/CV_16S/CV_32F/CV_64F + CV_16U/CV_16S | -1/CV_32F/CV_64F + CV_32F | -1/CV_32F + CV_64F | -1/CV_64F + + @note when ddepth=-1, the output image will have the same depth as the source. + + @note if you need double floating-point accuracy and using single floating-point input data + (CV_32F input and CV_64F output depth combination), you can use @ref Mat.convertTo to convert + the input data to the desired precision. + + @defgroup imgproc_transform Geometric Image Transformations + + The functions in this section perform various geometrical transformations of 2D images. They do not + change the image content but deform the pixel grid and map this deformed grid to the destination + image. In fact, to avoid sampling artifacts, the mapping is done in the reverse order, from + destination to the source. That is, for each pixel \f$(x, y)\f$ of the destination image, the + functions compute coordinates of the corresponding "donor" pixel in the source image and copy the + pixel value: + + \f[\texttt{dst} (x,y)= \texttt{src} (f_x(x,y), f_y(x,y))\f] + + In case when you specify the forward mapping \f$\left: \texttt{src} \rightarrow + \texttt{dst}\f$, the OpenCV functions first compute the corresponding inverse mapping + \f$\left: \texttt{dst} \rightarrow \texttt{src}\f$ and then use the above formula. + + The actual implementations of the geometrical transformations, from the most generic remap and to + the simplest and the fastest resize, need to solve two main problems with the above formula: + + - Extrapolation of non-existing pixels. Similarly to the filtering functions described in the + previous section, for some \f$(x,y)\f$, either one of \f$f_x(x,y)\f$, or \f$f_y(x,y)\f$, or both + of them may fall outside of the image. In this case, an extrapolation method needs to be used. + OpenCV provides the same selection of extrapolation methods as in the filtering functions. In + addition, it provides the method #BORDER_TRANSPARENT. This means that the corresponding pixels in + the destination image will not be modified at all. + + - Interpolation of pixel values. Usually \f$f_x(x,y)\f$ and \f$f_y(x,y)\f$ are floating-point + numbers. This means that \f$\left\f$ can be either an affine or perspective + transformation, or radial lens distortion correction, and so on. So, a pixel value at fractional + coordinates needs to be retrieved. In the simplest case, the coordinates can be just rounded to the + nearest integer coordinates and the corresponding pixel can be used. This is called a + nearest-neighbor interpolation. However, a better result can be achieved by using more + sophisticated [interpolation methods](http://en.wikipedia.org/wiki/Multivariate_interpolation) , + where a polynomial function is fit into some neighborhood of the computed pixel \f$(f_x(x,y), + f_y(x,y))\f$, and then the value of the polynomial at \f$(f_x(x,y), f_y(x,y))\f$ is taken as the + interpolated pixel value. In OpenCV, you can choose between several interpolation methods. See + #resize for details. + + @note The geometrical transformations do not work with `CV_8S` or `CV_32S` images. + + @defgroup imgproc_misc Miscellaneous Image Transformations + @defgroup imgproc_draw Drawing Functions + + Drawing functions work with matrices/images of arbitrary depth. The boundaries of the shapes can be + rendered with antialiasing (implemented only for 8-bit images for now). All the functions include + the parameter color that uses an RGB value (that may be constructed with the Scalar constructor ) + for color images and brightness for grayscale images. For color images, the channel ordering is + normally *Blue, Green, Red*. This is what imshow, imread, and imwrite expect. So, if you form a + color using the Scalar constructor, it should look like: + + \f[\texttt{Scalar} (blue \_ component, green \_ component, red \_ component[, alpha \_ component])\f] + + If you are using your own image rendering and I/O functions, you can use any channel ordering. The + drawing functions process each channel independently and do not depend on the channel order or even + on the used color space. The whole image can be converted from BGR to RGB or to a different color + space using cvtColor . + + If a drawn figure is partially or completely outside the image, the drawing functions clip it. Also, + many drawing functions can handle pixel coordinates specified with sub-pixel accuracy. This means + that the coordinates can be passed as fixed-point numbers encoded as integers. The number of + fractional bits is specified by the shift parameter and the real point coordinates are calculated as + \f$\texttt{Point}(x,y)\rightarrow\texttt{Point2f}(x*2^{-shift},y*2^{-shift})\f$ . This feature is + especially effective when rendering antialiased shapes. + + @note The functions do not support alpha-transparency when the target image is 4-channel. In this + case, the color[3] is simply copied to the repainted pixels. Thus, if you want to paint + semi-transparent shapes, you can paint them in a separate buffer and then blend it with the main + image. + + @defgroup imgproc_color_conversions Color Space Conversions + @defgroup imgproc_colormap ColorMaps in OpenCV + + The human perception isn't built for observing fine changes in grayscale images. Human eyes are more + sensitive to observing changes between colors, so you often need to recolor your grayscale images to + get a clue about them. OpenCV now comes with various colormaps to enhance the visualization in your + computer vision application. + + In OpenCV you only need applyColorMap to apply a colormap on a given image. The following sample + code reads the path to an image from command line, applies a Jet colormap on it and shows the + result: + + @include snippets/imgproc_applyColorMap.cpp + + @see #ColormapTypes + + @defgroup imgproc_subdiv2d Planar Subdivision + + The Subdiv2D class described in this section is used to perform various planar subdivision on + a set of 2D points (represented as vector of Point2f). OpenCV subdivides a plane into triangles + using the Delaunay's algorithm, which corresponds to the dual graph of the Voronoi diagram. + In the figure below, the Delaunay's triangulation is marked with black lines and the Voronoi + diagram with red lines. + + ![Delaunay triangulation (black) and Voronoi (red)](pics/delaunay_voronoi.png) + + The subdivisions can be used for the 3D piece-wise transformation of a plane, morphing, fast + location of points on the plane, building special graphs (such as NNG,RNG), and so forth. + + @defgroup imgproc_hist Histograms + @defgroup imgproc_shape Structural Analysis and Shape Descriptors + @defgroup imgproc_motion Motion Analysis and Object Tracking + @defgroup imgproc_feature Feature Detection + @defgroup imgproc_object Object Detection + @defgroup imgproc_segmentation Image Segmentation + @defgroup imgproc_hal Hardware Acceleration Layer + @{ + @defgroup imgproc_hal_functions Functions + @defgroup imgproc_hal_interface Interface + @} + @} +*/ + +namespace cv +{ + +/** @addtogroup imgproc +@{ +*/ + +//! @addtogroup imgproc_filter +//! @{ + +enum SpecialFilter { + FILTER_SCHARR = -1 +}; + +//! type of morphological operation +enum MorphTypes{ + MORPH_ERODE = 0, //!< see #erode + MORPH_DILATE = 1, //!< see #dilate + MORPH_OPEN = 2, //!< an opening operation + //!< \f[\texttt{dst} = \mathrm{open} ( \texttt{src} , \texttt{element} )= \mathrm{dilate} ( \mathrm{erode} ( \texttt{src} , \texttt{element} ))\f] + MORPH_CLOSE = 3, //!< a closing operation + //!< \f[\texttt{dst} = \mathrm{close} ( \texttt{src} , \texttt{element} )= \mathrm{erode} ( \mathrm{dilate} ( \texttt{src} , \texttt{element} ))\f] + MORPH_GRADIENT = 4, //!< a morphological gradient + //!< \f[\texttt{dst} = \mathrm{morph\_grad} ( \texttt{src} , \texttt{element} )= \mathrm{dilate} ( \texttt{src} , \texttt{element} )- \mathrm{erode} ( \texttt{src} , \texttt{element} )\f] + MORPH_TOPHAT = 5, //!< "top hat" + //!< \f[\texttt{dst} = \mathrm{tophat} ( \texttt{src} , \texttt{element} )= \texttt{src} - \mathrm{open} ( \texttt{src} , \texttt{element} )\f] + MORPH_BLACKHAT = 6, //!< "black hat" + //!< \f[\texttt{dst} = \mathrm{blackhat} ( \texttt{src} , \texttt{element} )= \mathrm{close} ( \texttt{src} , \texttt{element} )- \texttt{src}\f] + MORPH_HITMISS = 7 //!< "hit or miss" + //!< .- Only supported for CV_8UC1 binary images. A tutorial can be found in the documentation +}; + +//! shape of the structuring element +enum MorphShapes { + MORPH_RECT = 0, //!< a rectangular structuring element: \f[E_{ij}=1\f] + MORPH_CROSS = 1, //!< a cross-shaped structuring element: + //!< \f[E_{ij} = \begin{cases} 1 & \texttt{if } {i=\texttt{anchor.y } {or } {j=\texttt{anchor.x}}} \\0 & \texttt{otherwise} \end{cases}\f] + MORPH_ELLIPSE = 2 //!< an elliptic structuring element, that is, a filled ellipse inscribed + //!< into the rectangle Rect(0, 0, esize.width, esize.height) +}; + +//! @} imgproc_filter + +//! @addtogroup imgproc_transform +//! @{ + +//! interpolation algorithm +enum InterpolationFlags{ + /** nearest neighbor interpolation */ + INTER_NEAREST = 0, + /** bilinear interpolation */ + INTER_LINEAR = 1, + /** bicubic interpolation */ + INTER_CUBIC = 2, + /** resampling using pixel area relation. It may be a preferred method for image decimation, as + it gives moire'-free results. But when the image is zoomed, it is similar to the INTER_NEAREST + method. */ + INTER_AREA = 3, + /** Lanczos interpolation over 8x8 neighborhood */ + INTER_LANCZOS4 = 4, + /** Bit exact bilinear interpolation */ + INTER_LINEAR_EXACT = 5, + /** Bit exact nearest neighbor interpolation. This will produce same results as + the nearest neighbor method in PIL, scikit-image or Matlab. */ + INTER_NEAREST_EXACT = 6, + /** mask for interpolation codes */ + INTER_MAX = 7, + /** flag, fills all of the destination image pixels. If some of them correspond to outliers in the + source image, they are set to zero */ + WARP_FILL_OUTLIERS = 8, + /** flag, inverse transformation + + For example, #linearPolar or #logPolar transforms: + - flag is __not__ set: \f$dst( \rho , \phi ) = src(x,y)\f$ + - flag is set: \f$dst(x,y) = src( \rho , \phi )\f$ + */ + WARP_INVERSE_MAP = 16, + WARP_RELATIVE_MAP = 32 +}; + +/** \brief Specify the polar mapping mode +@sa warpPolar +*/ +enum WarpPolarMode +{ + WARP_POLAR_LINEAR = 0, ///< Remaps an image to/from polar space. + WARP_POLAR_LOG = 256 ///< Remaps an image to/from semilog-polar space. +}; + +enum InterpolationMasks { + INTER_BITS = 5, + INTER_BITS2 = INTER_BITS * 2, + INTER_TAB_SIZE = 1 << INTER_BITS, + INTER_TAB_SIZE2 = INTER_TAB_SIZE * INTER_TAB_SIZE + }; + +//! @} imgproc_transform + +//! @addtogroup imgproc_misc +//! @{ + +//! Distance types for Distance Transform and M-estimators +//! @see distanceTransform, fitLine +enum DistanceTypes { + DIST_USER = -1, //!< User defined distance + DIST_L1 = 1, //!< distance = |x1-x2| + |y1-y2| + DIST_L2 = 2, //!< the simple euclidean distance + DIST_C = 3, //!< distance = max(|x1-x2|,|y1-y2|) + DIST_L12 = 4, //!< L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1)) + DIST_FAIR = 5, //!< distance = c^2(|x|/c-log(1+|x|/c)), c = 1.3998 + DIST_WELSCH = 6, //!< distance = c^2/2(1-exp(-(x/c)^2)), c = 2.9846 + DIST_HUBER = 7 //!< distance = |x| \texttt{thresh}\)}{0}{otherwise}\f] + THRESH_BINARY_INV = 1, //!< \f[\texttt{dst} (x,y) = \fork{0}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{maxval}}{otherwise}\f] + THRESH_TRUNC = 2, //!< \f[\texttt{dst} (x,y) = \fork{\texttt{threshold}}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{src}(x,y)}{otherwise}\f] + THRESH_TOZERO = 3, //!< \f[\texttt{dst} (x,y) = \fork{\texttt{src}(x,y)}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{0}{otherwise}\f] + THRESH_TOZERO_INV = 4, //!< \f[\texttt{dst} (x,y) = \fork{0}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{src}(x,y)}{otherwise}\f] + THRESH_MASK = 7, + THRESH_OTSU = 8, //!< flag, use Otsu algorithm to choose the optimal threshold value + THRESH_TRIANGLE = 16 //!< flag, use Triangle algorithm to choose the optimal threshold value +}; + +//! adaptive threshold algorithm +//! @see adaptiveThreshold +enum AdaptiveThresholdTypes { + /** the threshold value \f$T(x,y)\f$ is a mean of the \f$\texttt{blockSize} \times + \texttt{blockSize}\f$ neighborhood of \f$(x, y)\f$ minus C */ + ADAPTIVE_THRESH_MEAN_C = 0, + /** the threshold value \f$T(x, y)\f$ is a weighted sum (cross-correlation with a Gaussian + window) of the \f$\texttt{blockSize} \times \texttt{blockSize}\f$ neighborhood of \f$(x, y)\f$ + minus C . The default sigma (standard deviation) is used for the specified blockSize . See + #getGaussianKernel*/ + ADAPTIVE_THRESH_GAUSSIAN_C = 1 +}; + +//! class of the pixel in GrabCut algorithm +enum GrabCutClasses { + GC_BGD = 0, //!< an obvious background pixels + GC_FGD = 1, //!< an obvious foreground (object) pixel + GC_PR_BGD = 2, //!< a possible background pixel + GC_PR_FGD = 3 //!< a possible foreground pixel +}; + +//! GrabCut algorithm flags +enum GrabCutModes { + /** The function initializes the state and the mask using the provided rectangle. After that it + runs iterCount iterations of the algorithm. */ + GC_INIT_WITH_RECT = 0, + /** The function initializes the state using the provided mask. Note that GC_INIT_WITH_RECT + and GC_INIT_WITH_MASK can be combined. Then, all the pixels outside of the ROI are + automatically initialized with GC_BGD .*/ + GC_INIT_WITH_MASK = 1, + /** The value means that the algorithm should just resume. */ + GC_EVAL = 2, + /** The value means that the algorithm should just run the grabCut algorithm (a single iteration) with the fixed model */ + GC_EVAL_FREEZE_MODEL = 3 +}; + +//! distanceTransform algorithm flags +enum DistanceTransformLabelTypes { + /** each connected component of zeros in src (as well as all the non-zero pixels closest to the + connected component) will be assigned the same label */ + DIST_LABEL_CCOMP = 0, + /** each zero pixel (and all the non-zero pixels closest to it) gets its own label. */ + DIST_LABEL_PIXEL = 1 +}; + +//! floodfill algorithm flags +enum FloodFillFlags { + /** If set, the difference between the current pixel and seed pixel is considered. Otherwise, + the difference between neighbor pixels is considered (that is, the range is floating). */ + FLOODFILL_FIXED_RANGE = 1 << 16, + /** If set, the function does not change the image ( newVal is ignored), and only fills the + mask with the value specified in bits 8-16 of flags as described above. This option only make + sense in function variants that have the mask parameter. */ + FLOODFILL_MASK_ONLY = 1 << 17 +}; + +//! @} imgproc_misc + +//! @addtogroup imgproc_shape +//! @{ + +//! connected components statistics +enum ConnectedComponentsTypes { + CC_STAT_LEFT = 0, //!< The leftmost (x) coordinate which is the inclusive start of the bounding + //!< box in the horizontal direction. + CC_STAT_TOP = 1, //!< The topmost (y) coordinate which is the inclusive start of the bounding + //!< box in the vertical direction. + CC_STAT_WIDTH = 2, //!< The horizontal size of the bounding box + CC_STAT_HEIGHT = 3, //!< The vertical size of the bounding box + CC_STAT_AREA = 4, //!< The total area (in pixels) of the connected component +#ifndef CV_DOXYGEN + CC_STAT_MAX = 5 //!< Max enumeration value. Used internally only for memory allocation +#endif +}; + +//! connected components algorithm +enum ConnectedComponentsAlgorithmsTypes { + CCL_DEFAULT = -1, //!< Spaghetti @cite Bolelli2019 algorithm for 8-way connectivity, Spaghetti4C @cite Bolelli2021 algorithm for 4-way connectivity. + CCL_WU = 0, //!< SAUF @cite Wu2009 algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity. The parallel implementation described in @cite Bolelli2017 is available for SAUF. + CCL_GRANA = 1, //!< BBDT @cite Grana2010 algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity. The parallel implementation described in @cite Bolelli2017 is available for both BBDT and SAUF. + CCL_BOLELLI = 2, //!< Spaghetti @cite Bolelli2019 algorithm for 8-way connectivity, Spaghetti4C @cite Bolelli2021 algorithm for 4-way connectivity. The parallel implementation described in @cite Bolelli2017 is available for both Spaghetti and Spaghetti4C. + CCL_SAUF = 3, //!< Same as CCL_WU. It is preferable to use the flag with the name of the algorithm (CCL_SAUF) rather than the one with the name of the first author (CCL_WU). + CCL_BBDT = 4, //!< Same as CCL_GRANA. It is preferable to use the flag with the name of the algorithm (CCL_BBDT) rather than the one with the name of the first author (CCL_GRANA). + CCL_SPAGHETTI = 5, //!< Same as CCL_BOLELLI. It is preferable to use the flag with the name of the algorithm (CCL_SPAGHETTI) rather than the one with the name of the first author (CCL_BOLELLI). +}; + +//! mode of the contour retrieval algorithm +enum RetrievalModes { + /** retrieves only the extreme outer contours. It sets `hierarchy[i][2]=hierarchy[i][3]=-1` for + all the contours. */ + RETR_EXTERNAL = 0, + /** retrieves all of the contours without establishing any hierarchical relationships. */ + RETR_LIST = 1, + /** retrieves all of the contours and organizes them into a two-level hierarchy. At the top + level, there are external boundaries of the components. At the second level, there are + boundaries of the holes. If there is another contour inside a hole of a connected component, it + is still put at the top level. */ + RETR_CCOMP = 2, + /** retrieves all of the contours and reconstructs a full hierarchy of nested contours.*/ + RETR_TREE = 3, + RETR_FLOODFILL = 4 //!< +}; + +//! the contour approximation algorithm +enum ContourApproximationModes { + /** stores absolutely all the contour points. That is, any 2 subsequent points (x1,y1) and + (x2,y2) of the contour will be either horizontal, vertical or diagonal neighbors, that is, + max(abs(x1-x2),abs(y2-y1))==1. */ + CHAIN_APPROX_NONE = 1, + /** compresses horizontal, vertical, and diagonal segments and leaves only their end points. + For example, an up-right rectangular contour is encoded with 4 points. */ + CHAIN_APPROX_SIMPLE = 2, + /** applies one of the flavors of the Teh-Chin chain approximation algorithm @cite TehChin89 */ + CHAIN_APPROX_TC89_L1 = 3, + /** applies one of the flavors of the Teh-Chin chain approximation algorithm @cite TehChin89 */ + CHAIN_APPROX_TC89_KCOS = 4 +}; + +/** @brief Shape matching methods + +\f$A\f$ denotes object1,\f$B\f$ denotes object2 + +\f$\begin{array}{l} m^A_i = \mathrm{sign} (h^A_i) \cdot \log{h^A_i} \\ m^B_i = \mathrm{sign} (h^B_i) \cdot \log{h^B_i} \end{array}\f$ + +and \f$h^A_i, h^B_i\f$ are the Hu moments of \f$A\f$ and \f$B\f$ , respectively. +*/ +enum ShapeMatchModes { + CONTOURS_MATCH_I1 =1, //!< \f[I_1(A,B) = \sum _{i=1...7} \left | \frac{1}{m^A_i} - \frac{1}{m^B_i} \right |\f] + CONTOURS_MATCH_I2 =2, //!< \f[I_2(A,B) = \sum _{i=1...7} \left | m^A_i - m^B_i \right |\f] + CONTOURS_MATCH_I3 =3 //!< \f[I_3(A,B) = \max _{i=1...7} \frac{ \left| m^A_i - m^B_i \right| }{ \left| m^A_i \right| }\f] +}; + +//! @} imgproc_shape + +//! @addtogroup imgproc_feature +//! @{ + +//! Variants of a Hough transform +enum HoughModes { + + /** classical or standard Hough transform. Every line is represented by two floating-point + numbers \f$(\rho, \theta)\f$ , where \f$\rho\f$ is a distance between (0,0) point and the line, + and \f$\theta\f$ is the angle between x-axis and the normal to the line. Thus, the matrix must + be (the created sequence will be) of CV_32FC2 type */ + HOUGH_STANDARD = 0, + /** probabilistic Hough transform (more efficient in case if the picture contains a few long + linear segments). It returns line segments rather than the whole line. Each segment is + represented by starting and ending points, and the matrix must be (the created sequence will + be) of the CV_32SC4 type. */ + HOUGH_PROBABILISTIC = 1, + /** multi-scale variant of the classical Hough transform. The lines are encoded the same way as + HOUGH_STANDARD. */ + HOUGH_MULTI_SCALE = 2, + HOUGH_GRADIENT = 3, //!< basically *21HT*, described in @cite Yuen90 + HOUGH_GRADIENT_ALT = 4, //!< variation of HOUGH_GRADIENT to get better accuracy +}; + +//! Variants of Line Segment %Detector +enum LineSegmentDetectorModes { + LSD_REFINE_NONE = 0, //!< No refinement applied + LSD_REFINE_STD = 1, //!< Standard refinement is applied. E.g. breaking arches into smaller straighter line approximations. + LSD_REFINE_ADV = 2 //!< Advanced refinement. Number of false alarms is calculated, lines are + //!< refined through increase of precision, decrement in size, etc. +}; + +//! @} imgproc_feature + +/** Histogram comparison methods + @ingroup imgproc_hist +*/ +enum HistCompMethods { + /** Correlation + \f[d(H_1,H_2) = \frac{\sum_I (H_1(I) - \bar{H_1}) (H_2(I) - \bar{H_2})}{\sqrt{\sum_I(H_1(I) - \bar{H_1})^2 \sum_I(H_2(I) - \bar{H_2})^2}}\f] + where + \f[\bar{H_k} = \frac{1}{N} \sum _J H_k(J)\f] + and \f$N\f$ is a total number of histogram bins. */ + HISTCMP_CORREL = 0, + /** Chi-Square + \f[d(H_1,H_2) = \sum _I \frac{\left(H_1(I)-H_2(I)\right)^2}{H_1(I)}\f] */ + HISTCMP_CHISQR = 1, + /** Intersection + \f[d(H_1,H_2) = \sum _I \min (H_1(I), H_2(I))\f] */ + HISTCMP_INTERSECT = 2, + /** Bhattacharyya distance + (In fact, OpenCV computes Hellinger distance, which is related to Bhattacharyya coefficient.) + \f[d(H_1,H_2) = \sqrt{1 - \frac{1}{\sqrt{\bar{H_1} \bar{H_2} N^2}} \sum_I \sqrt{H_1(I) \cdot H_2(I)}}\f] */ + HISTCMP_BHATTACHARYYA = 3, + HISTCMP_HELLINGER = HISTCMP_BHATTACHARYYA, //!< Synonym for HISTCMP_BHATTACHARYYA + /** Alternative Chi-Square + \f[d(H_1,H_2) = 2 * \sum _I \frac{\left(H_1(I)-H_2(I)\right)^2}{H_1(I)+H_2(I)}\f] + This alternative formula is regularly used for texture comparison. See e.g. @cite Puzicha1997 */ + HISTCMP_CHISQR_ALT = 4, + /** Kullback-Leibler divergence + \f[d(H_1,H_2) = \sum _I H_1(I) \log \left(\frac{H_1(I)}{H_2(I)}\right)\f] */ + HISTCMP_KL_DIV = 5 +}; + +/** the color conversion codes +@see @ref imgproc_color_conversions +@ingroup imgproc_color_conversions + */ +enum ColorConversionCodes { + COLOR_BGR2BGRA = 0, //!< add alpha channel to RGB or BGR image + COLOR_RGB2RGBA = COLOR_BGR2BGRA, + + COLOR_BGRA2BGR = 1, //!< remove alpha channel from RGB or BGR image + COLOR_RGBA2RGB = COLOR_BGRA2BGR, + + COLOR_BGR2RGBA = 2, //!< convert between RGB and BGR color spaces (with or without alpha channel) + COLOR_RGB2BGRA = COLOR_BGR2RGBA, + + COLOR_RGBA2BGR = 3, + COLOR_BGRA2RGB = COLOR_RGBA2BGR, + + COLOR_BGR2RGB = 4, + COLOR_RGB2BGR = COLOR_BGR2RGB, + + COLOR_BGRA2RGBA = 5, + COLOR_RGBA2BGRA = COLOR_BGRA2RGBA, + + COLOR_BGR2GRAY = 6, //!< convert between RGB/BGR and grayscale, @ref color_convert_rgb_gray "color conversions" + COLOR_RGB2GRAY = 7, + COLOR_GRAY2BGR = 8, + COLOR_GRAY2RGB = COLOR_GRAY2BGR, + COLOR_GRAY2BGRA = 9, + COLOR_GRAY2RGBA = COLOR_GRAY2BGRA, + COLOR_BGRA2GRAY = 10, + COLOR_RGBA2GRAY = 11, + + COLOR_BGR2BGR565 = 12, //!< convert between RGB/BGR and BGR565 (16-bit images) + COLOR_RGB2BGR565 = 13, + COLOR_BGR5652BGR = 14, + COLOR_BGR5652RGB = 15, + COLOR_BGRA2BGR565 = 16, + COLOR_RGBA2BGR565 = 17, + COLOR_BGR5652BGRA = 18, + COLOR_BGR5652RGBA = 19, + + COLOR_GRAY2BGR565 = 20, //!< convert between grayscale to BGR565 (16-bit images) + COLOR_BGR5652GRAY = 21, + + COLOR_BGR2BGR555 = 22, //!< convert between RGB/BGR and BGR555 (16-bit images) + COLOR_RGB2BGR555 = 23, + COLOR_BGR5552BGR = 24, + COLOR_BGR5552RGB = 25, + COLOR_BGRA2BGR555 = 26, + COLOR_RGBA2BGR555 = 27, + COLOR_BGR5552BGRA = 28, + COLOR_BGR5552RGBA = 29, + + COLOR_GRAY2BGR555 = 30, //!< convert between grayscale and BGR555 (16-bit images) + COLOR_BGR5552GRAY = 31, + + COLOR_BGR2XYZ = 32, //!< convert RGB/BGR to CIE XYZ, @ref color_convert_rgb_xyz "color conversions" + COLOR_RGB2XYZ = 33, + COLOR_XYZ2BGR = 34, + COLOR_XYZ2RGB = 35, + + COLOR_BGR2YCrCb = 36, //!< convert RGB/BGR to luma-chroma (aka YCC), @ref color_convert_rgb_ycrcb "color conversions" + COLOR_RGB2YCrCb = 37, + COLOR_YCrCb2BGR = 38, + COLOR_YCrCb2RGB = 39, + + COLOR_BGR2HSV = 40, //!< convert RGB/BGR to HSV (hue saturation value) with H range 0..180 if 8 bit image, @ref color_convert_rgb_hsv "color conversions" + COLOR_RGB2HSV = 41, + + COLOR_BGR2Lab = 44, //!< convert RGB/BGR to CIE Lab, @ref color_convert_rgb_lab "color conversions" + COLOR_RGB2Lab = 45, + + COLOR_BGR2Luv = 50, //!< convert RGB/BGR to CIE Luv, @ref color_convert_rgb_luv "color conversions" + COLOR_RGB2Luv = 51, + COLOR_BGR2HLS = 52, //!< convert RGB/BGR to HLS (hue lightness saturation) with H range 0..180 if 8 bit image, @ref color_convert_rgb_hls "color conversions" + COLOR_RGB2HLS = 53, + + COLOR_HSV2BGR = 54, //!< backward conversions HSV to RGB/BGR with H range 0..180 if 8 bit image + COLOR_HSV2RGB = 55, + + COLOR_Lab2BGR = 56, + COLOR_Lab2RGB = 57, + COLOR_Luv2BGR = 58, + COLOR_Luv2RGB = 59, + COLOR_HLS2BGR = 60, //!< backward conversions HLS to RGB/BGR with H range 0..180 if 8 bit image + COLOR_HLS2RGB = 61, + + COLOR_BGR2HSV_FULL = 66, //!< convert RGB/BGR to HSV (hue saturation value) with H range 0..255 if 8 bit image, @ref color_convert_rgb_hsv "color conversions" + COLOR_RGB2HSV_FULL = 67, + COLOR_BGR2HLS_FULL = 68, //!< convert RGB/BGR to HLS (hue lightness saturation) with H range 0..255 if 8 bit image, @ref color_convert_rgb_hls "color conversions" + COLOR_RGB2HLS_FULL = 69, + + COLOR_HSV2BGR_FULL = 70, //!< backward conversions HSV to RGB/BGR with H range 0..255 if 8 bit image + COLOR_HSV2RGB_FULL = 71, + COLOR_HLS2BGR_FULL = 72, //!< backward conversions HLS to RGB/BGR with H range 0..255 if 8 bit image + COLOR_HLS2RGB_FULL = 73, + + COLOR_LBGR2Lab = 74, + COLOR_LRGB2Lab = 75, + COLOR_LBGR2Luv = 76, + COLOR_LRGB2Luv = 77, + + COLOR_Lab2LBGR = 78, + COLOR_Lab2LRGB = 79, + COLOR_Luv2LBGR = 80, + COLOR_Luv2LRGB = 81, + + COLOR_BGR2YUV = 82, //!< convert between RGB/BGR and YUV + COLOR_RGB2YUV = 83, + COLOR_YUV2BGR = 84, + COLOR_YUV2RGB = 85, + + COLOR_YUV2RGB_NV12 = 90, //!< convert between 4:2:0-subsampled YUV NV12 and RGB, two planes (in one or separate arrays): Y and U/V interleaved, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGR_NV12 = 91, //!< convert between 4:2:0-subsampled YUV NV12 and BGR, two planes (in one or separate arrays): Y and U/V interleaved, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2RGB_NV21 = 92, //!< convert between 4:2:0-subsampled YUV NV21 and RGB, two planes (in one or separate arrays): Y and V/U interleaved, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGR_NV21 = 93, //!< convert between 4:2:0-subsampled YUV NV21 and BGR, two planes (in one or separate arrays): Y and V/U interleaved, see @ref color_convert_rgb_yuv_42x + COLOR_YUV420sp2RGB = COLOR_YUV2RGB_NV21, //!< synonym to NV21 + COLOR_YUV420sp2BGR = COLOR_YUV2BGR_NV21, //!< synonym to NV21 + + COLOR_YUV2RGBA_NV12 = 94, //!< convert between 4:2:0-subsampled YUV NV12 and RGBA, two planes (in one or separate arrays): Y and U/V interleaved, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGRA_NV12 = 95, //!< convert between 4:2:0-subsampled YUV NV12 and BGRA, two planes (in one or separate arrays): Y and U/V interleaved, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2RGBA_NV21 = 96, //!< convert between 4:2:0-subsampled YUV NV21 and RGBA, two planes (in one or separate arrays): Y and V/U interleaved, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGRA_NV21 = 97, //!< convert between 4:2:0-subsampled YUV NV21 and BGRA, two planes (in one or separate arrays): Y and V/U interleaved, see @ref color_convert_rgb_yuv_42x + COLOR_YUV420sp2RGBA = COLOR_YUV2RGBA_NV21, //!< synonym to NV21 + COLOR_YUV420sp2BGRA = COLOR_YUV2BGRA_NV21, //!< synonym to NV21 + + COLOR_YUV2RGB_YV12 = 98, //!< convert between 4:2:0-subsampled YUV YV12 and RGB, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGR_YV12 = 99, //!< convert between 4:2:0-subsampled YUV YV12 and BGR, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2RGB_IYUV = 100, //!< convert between 4:2:0-subsampled YUV IYUV and RGB, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGR_IYUV = 101, //!< convert between 4:2:0-subsampled YUV IYUV and BGR, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2RGB_I420 = COLOR_YUV2RGB_IYUV, //!< synonym to IYUV + COLOR_YUV2BGR_I420 = COLOR_YUV2BGR_IYUV, //!< synonym to IYUV + COLOR_YUV420p2RGB = COLOR_YUV2RGB_YV12, //!< synonym to YV12 + COLOR_YUV420p2BGR = COLOR_YUV2BGR_YV12, //!< synonym to YV12 + + COLOR_YUV2RGBA_YV12 = 102, //!< convert between 4:2:0-subsampled YUV YV12 and RGBA, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGRA_YV12 = 103, //!< convert between 4:2:0-subsampled YUV YV12 and BGRA, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2RGBA_IYUV = 104, //!< convert between 4:2:0-subsampled YUV YV12 and RGBA, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGRA_IYUV = 105, //!< convert between 4:2:0-subsampled YUV YV12 and BGRA, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2RGBA_I420 = COLOR_YUV2RGBA_IYUV, //!< synonym to IYUV + COLOR_YUV2BGRA_I420 = COLOR_YUV2BGRA_IYUV, //!< synonym to IYUV + COLOR_YUV420p2RGBA = COLOR_YUV2RGBA_YV12, //!< synonym to YV12 + COLOR_YUV420p2BGRA = COLOR_YUV2BGRA_YV12, //!< synonym to YV12 + + COLOR_YUV2GRAY_420 = 106, //!< extract Y channel from YUV 4:2:0 image + COLOR_YUV2GRAY_NV21 = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 + COLOR_YUV2GRAY_NV12 = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 + COLOR_YUV2GRAY_YV12 = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 + COLOR_YUV2GRAY_IYUV = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 + COLOR_YUV2GRAY_I420 = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 + COLOR_YUV420sp2GRAY = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 + COLOR_YUV420p2GRAY = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 + + COLOR_YUV2RGB_UYVY = 107, //!< convert between YUV UYVY and RGB, YUV is 4:2:2-subsampled and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGR_UYVY = 108, //!< convert between YUV UYVY and BGR, YUV is 4:2:2-subsampled and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x + //COLOR_YUV2RGB_VYUY = 109, //!< convert between YUV VYUY and RGB, YUV is 4:2:2-subsampled and interleaved as V/Y1/U/Y2, see @ref color_convert_rgb_yuv_42x + //COLOR_YUV2BGR_VYUY = 110, //!< convert between YUV VYUY and BGR, YUV is 4:2:2-subsampled and interleaved as V/Y1/U/Y2, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2RGB_Y422 = COLOR_YUV2RGB_UYVY, //!< synonym to UYVY + COLOR_YUV2BGR_Y422 = COLOR_YUV2BGR_UYVY, //!< synonym to UYVY + COLOR_YUV2RGB_UYNV = COLOR_YUV2RGB_UYVY, //!< synonym to UYVY + COLOR_YUV2BGR_UYNV = COLOR_YUV2BGR_UYVY, //!< synonym to UYVY + + COLOR_YUV2RGBA_UYVY = 111, //!< convert between YUV UYVY and RGBA, YUV is 4:2:2-subsampled and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGRA_UYVY = 112, //!< convert between YUV UYVY and BGRA, YUV is 4:2:2-subsampled and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x + //COLOR_YUV2RGBA_VYUY = 113, //!< convert between YUV VYUY and RGBA, YUV is 4:2:2-subsampled and interleaved as V/Y1/U/Y2, see @ref color_convert_rgb_yuv_42x + //COLOR_YUV2BGRA_VYUY = 114, //!< convert between YUV VYUY and BGRA, YUV is 4:2:2-subsampled and interleaved as V/Y1/U/Y2, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2RGBA_Y422 = COLOR_YUV2RGBA_UYVY, //!< synonym to UYVY + COLOR_YUV2BGRA_Y422 = COLOR_YUV2BGRA_UYVY, //!< synonym to UYVY + COLOR_YUV2RGBA_UYNV = COLOR_YUV2RGBA_UYVY, //!< synonym to UYVY + COLOR_YUV2BGRA_UYNV = COLOR_YUV2BGRA_UYVY, //!< synonym to UYVY + + COLOR_YUV2RGB_YUY2 = 115, //!< convert between YUV YUY2 and RGB, YUV is 4:2:2-subsampled and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGR_YUY2 = 116, //!< convert between YUV YUY2 and BGR, YUV is 4:2:2-subsampled and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2RGB_YVYU = 117, //!< convert between YUV YVYU and RGB, YUV is 4:2:2-subsampled and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGR_YVYU = 118, //!< convert between YUV YVYU and BGR, YUV is 4:2:2-subsampled and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2RGB_YUYV = COLOR_YUV2RGB_YUY2, //!< synonym to YUY2 + COLOR_YUV2BGR_YUYV = COLOR_YUV2BGR_YUY2, //!< synonym to YUY2 + COLOR_YUV2RGB_YUNV = COLOR_YUV2RGB_YUY2, //!< synonym to YUY2 + COLOR_YUV2BGR_YUNV = COLOR_YUV2BGR_YUY2, //!< synonym to YUY2 + + COLOR_YUV2RGBA_YUY2 = 119, //!< convert between YUV YUY2 and RGBA, YUV is 4:2:2-subsampled and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGRA_YUY2 = 120, //!< convert between YUV YUY2 and BGRA, YUV is 4:2:2-subsampled and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2RGBA_YVYU = 121, //!< convert between YUV YVYU and RGBA, YUV is 4:2:2-subsampled and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGRA_YVYU = 122, //!< convert between YUV YVYU and BGRA, YUV is 4:2:2-subsampled and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2RGBA_YUYV = COLOR_YUV2RGBA_YUY2, //!< synonym to YUY2 + COLOR_YUV2BGRA_YUYV = COLOR_YUV2BGRA_YUY2, //!< synonym to YUY2 + COLOR_YUV2RGBA_YUNV = COLOR_YUV2RGBA_YUY2, //!< synonym to YUY2 + COLOR_YUV2BGRA_YUNV = COLOR_YUV2BGRA_YUY2, //!< synonym to YUY2 + + COLOR_YUV2GRAY_UYVY = 123, //!< extract Y channel from YUV 4:2:2 image + COLOR_YUV2GRAY_YUY2 = 124, //!< extract Y channel from YUV 4:2:2 image + //CV_YUV2GRAY_VYUY = CV_YUV2GRAY_UYVY, //!< synonym to COLOR_YUV2GRAY_UYVY + COLOR_YUV2GRAY_Y422 = COLOR_YUV2GRAY_UYVY, //!< synonym to COLOR_YUV2GRAY_UYVY + COLOR_YUV2GRAY_UYNV = COLOR_YUV2GRAY_UYVY, //!< synonym to COLOR_YUV2GRAY_UYVY + COLOR_YUV2GRAY_YVYU = COLOR_YUV2GRAY_YUY2, //!< synonym to COLOR_YUV2GRAY_YUY2 + COLOR_YUV2GRAY_YUYV = COLOR_YUV2GRAY_YUY2, //!< synonym to COLOR_YUV2GRAY_YUY2 + COLOR_YUV2GRAY_YUNV = COLOR_YUV2GRAY_YUY2, //!< synonym to COLOR_YUV2GRAY_YUY2 + + //! alpha premultiplication + COLOR_RGBA2mRGBA = 125, + COLOR_mRGBA2RGBA = 126, + + COLOR_RGB2YUV_I420 = 127, //!< convert between RGB and 4:2:0-subsampled YUV I420, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x + COLOR_BGR2YUV_I420 = 128, //!< convert between BGR and 4:2:0-subsampled YUV I420, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x + COLOR_RGB2YUV_IYUV = COLOR_RGB2YUV_I420, //!< synonym to I420 + COLOR_BGR2YUV_IYUV = COLOR_BGR2YUV_I420, //!< synonym to I420 + + COLOR_RGBA2YUV_I420 = 129, //!< convert between RGBA and 4:2:0-subsampled YUV I420, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x + COLOR_BGRA2YUV_I420 = 130, //!< convert between BGRA and 4:2:0-subsampled YUV I420, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x + COLOR_RGBA2YUV_IYUV = COLOR_RGBA2YUV_I420, //!< synonym to I420 + COLOR_BGRA2YUV_IYUV = COLOR_BGRA2YUV_I420, //!< synonym to I420 + COLOR_RGB2YUV_YV12 = 131, //!< convert between RGB and 4:2:0-subsampled YUV YV12, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x + COLOR_BGR2YUV_YV12 = 132, //!< convert between BGR and 4:2:0-subsampled YUV YV12, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x + COLOR_RGBA2YUV_YV12 = 133, //!< convert between RGBA and 4:2:0-subsampled YUV YV12, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x + COLOR_BGRA2YUV_YV12 = 134, //!< convert between BGRA and 4:2:0-subsampled YUV YV12, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x + + //! Demosaicing, see @ref color_convert_bayer "color conversions" for additional information + COLOR_BayerBG2BGR = 46, //!< equivalent to RGGB Bayer pattern + COLOR_BayerGB2BGR = 47, //!< equivalent to GRBG Bayer pattern + COLOR_BayerRG2BGR = 48, //!< equivalent to BGGR Bayer pattern + COLOR_BayerGR2BGR = 49, //!< equivalent to GBRG Bayer pattern + + COLOR_BayerRGGB2BGR = COLOR_BayerBG2BGR, + COLOR_BayerGRBG2BGR = COLOR_BayerGB2BGR, + COLOR_BayerBGGR2BGR = COLOR_BayerRG2BGR, + COLOR_BayerGBRG2BGR = COLOR_BayerGR2BGR, + + COLOR_BayerRGGB2RGB = COLOR_BayerBGGR2BGR, + COLOR_BayerGRBG2RGB = COLOR_BayerGBRG2BGR, + COLOR_BayerBGGR2RGB = COLOR_BayerRGGB2BGR, + COLOR_BayerGBRG2RGB = COLOR_BayerGRBG2BGR, + + COLOR_BayerBG2RGB = COLOR_BayerRG2BGR, //!< equivalent to RGGB Bayer pattern + COLOR_BayerGB2RGB = COLOR_BayerGR2BGR, //!< equivalent to GRBG Bayer pattern + COLOR_BayerRG2RGB = COLOR_BayerBG2BGR, //!< equivalent to BGGR Bayer pattern + COLOR_BayerGR2RGB = COLOR_BayerGB2BGR, //!< equivalent to GBRG Bayer pattern + + COLOR_BayerBG2GRAY = 86, //!< equivalent to RGGB Bayer pattern + COLOR_BayerGB2GRAY = 87, //!< equivalent to GRBG Bayer pattern + COLOR_BayerRG2GRAY = 88, //!< equivalent to BGGR Bayer pattern + COLOR_BayerGR2GRAY = 89, //!< equivalent to GBRG Bayer pattern + + COLOR_BayerRGGB2GRAY = COLOR_BayerBG2GRAY, + COLOR_BayerGRBG2GRAY = COLOR_BayerGB2GRAY, + COLOR_BayerBGGR2GRAY = COLOR_BayerRG2GRAY, + COLOR_BayerGBRG2GRAY = COLOR_BayerGR2GRAY, + + //! Demosaicing using Variable Number of Gradients + COLOR_BayerBG2BGR_VNG = 62, //!< equivalent to RGGB Bayer pattern + COLOR_BayerGB2BGR_VNG = 63, //!< equivalent to GRBG Bayer pattern + COLOR_BayerRG2BGR_VNG = 64, //!< equivalent to BGGR Bayer pattern + COLOR_BayerGR2BGR_VNG = 65, //!< equivalent to GBRG Bayer pattern + + COLOR_BayerRGGB2BGR_VNG = COLOR_BayerBG2BGR_VNG, + COLOR_BayerGRBG2BGR_VNG = COLOR_BayerGB2BGR_VNG, + COLOR_BayerBGGR2BGR_VNG = COLOR_BayerRG2BGR_VNG, + COLOR_BayerGBRG2BGR_VNG = COLOR_BayerGR2BGR_VNG, + + COLOR_BayerRGGB2RGB_VNG = COLOR_BayerBGGR2BGR_VNG, + COLOR_BayerGRBG2RGB_VNG = COLOR_BayerGBRG2BGR_VNG, + COLOR_BayerBGGR2RGB_VNG = COLOR_BayerRGGB2BGR_VNG, + COLOR_BayerGBRG2RGB_VNG = COLOR_BayerGRBG2BGR_VNG, + + COLOR_BayerBG2RGB_VNG = COLOR_BayerRG2BGR_VNG, //!< equivalent to RGGB Bayer pattern + COLOR_BayerGB2RGB_VNG = COLOR_BayerGR2BGR_VNG, //!< equivalent to GRBG Bayer pattern + COLOR_BayerRG2RGB_VNG = COLOR_BayerBG2BGR_VNG, //!< equivalent to BGGR Bayer pattern + COLOR_BayerGR2RGB_VNG = COLOR_BayerGB2BGR_VNG, //!< equivalent to GBRG Bayer pattern + + //! Edge-Aware Demosaicing + COLOR_BayerBG2BGR_EA = 135, //!< equivalent to RGGB Bayer pattern + COLOR_BayerGB2BGR_EA = 136, //!< equivalent to GRBG Bayer pattern + COLOR_BayerRG2BGR_EA = 137, //!< equivalent to BGGR Bayer pattern + COLOR_BayerGR2BGR_EA = 138, //!< equivalent to GBRG Bayer pattern + + COLOR_BayerRGGB2BGR_EA = COLOR_BayerBG2BGR_EA, + COLOR_BayerGRBG2BGR_EA = COLOR_BayerGB2BGR_EA, + COLOR_BayerBGGR2BGR_EA = COLOR_BayerRG2BGR_EA, + COLOR_BayerGBRG2BGR_EA = COLOR_BayerGR2BGR_EA, + + COLOR_BayerRGGB2RGB_EA = COLOR_BayerBGGR2BGR_EA, + COLOR_BayerGRBG2RGB_EA = COLOR_BayerGBRG2BGR_EA, + COLOR_BayerBGGR2RGB_EA = COLOR_BayerRGGB2BGR_EA, + COLOR_BayerGBRG2RGB_EA = COLOR_BayerGRBG2BGR_EA, + + COLOR_BayerBG2RGB_EA = COLOR_BayerRG2BGR_EA, //!< equivalent to RGGB Bayer pattern + COLOR_BayerGB2RGB_EA = COLOR_BayerGR2BGR_EA, //!< equivalent to GRBG Bayer pattern + COLOR_BayerRG2RGB_EA = COLOR_BayerBG2BGR_EA, //!< equivalent to BGGR Bayer pattern + COLOR_BayerGR2RGB_EA = COLOR_BayerGB2BGR_EA, //!< equivalent to GBRG Bayer pattern + + //! Demosaicing with alpha channel + COLOR_BayerBG2BGRA = 139, //!< equivalent to RGGB Bayer pattern + COLOR_BayerGB2BGRA = 140, //!< equivalent to GRBG Bayer pattern + COLOR_BayerRG2BGRA = 141, //!< equivalent to BGGR Bayer pattern + COLOR_BayerGR2BGRA = 142, //!< equivalent to GBRG Bayer pattern + + COLOR_BayerRGGB2BGRA = COLOR_BayerBG2BGRA, + COLOR_BayerGRBG2BGRA = COLOR_BayerGB2BGRA, + COLOR_BayerBGGR2BGRA = COLOR_BayerRG2BGRA, + COLOR_BayerGBRG2BGRA = COLOR_BayerGR2BGRA, + + COLOR_BayerRGGB2RGBA = COLOR_BayerBGGR2BGRA, + COLOR_BayerGRBG2RGBA = COLOR_BayerGBRG2BGRA, + COLOR_BayerBGGR2RGBA = COLOR_BayerRGGB2BGRA, + COLOR_BayerGBRG2RGBA = COLOR_BayerGRBG2BGRA, + + COLOR_BayerBG2RGBA = COLOR_BayerRG2BGRA, //!< equivalent to RGGB Bayer pattern + COLOR_BayerGB2RGBA = COLOR_BayerGR2BGRA, //!< equivalent to GRBG Bayer pattern + COLOR_BayerRG2RGBA = COLOR_BayerBG2BGRA, //!< equivalent to BGGR Bayer pattern + COLOR_BayerGR2RGBA = COLOR_BayerGB2BGRA, //!< equivalent to GBRG Bayer pattern + + COLOR_RGB2YUV_UYVY = 143, //!< convert between RGB and YUV UYVU, YUV is 4:2:2 and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x + COLOR_BGR2YUV_UYVY = 144, //!< convert between BGR and YUV UYVU, YUV is 4:2:2 and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x + COLOR_RGB2YUV_Y422 = COLOR_RGB2YUV_UYVY, //!< synonym to UYVY + COLOR_BGR2YUV_Y422 = COLOR_BGR2YUV_UYVY, //!< synonym to UYVY + COLOR_RGB2YUV_UYNV = COLOR_RGB2YUV_UYVY, //!< synonym to UYVY + COLOR_BGR2YUV_UYNV = COLOR_BGR2YUV_UYVY, //!< synonym to UYVY + + COLOR_RGBA2YUV_UYVY = 145, //!< convert between RGBA and YUV UYVU, YUV is 4:2:2 and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x + COLOR_BGRA2YUV_UYVY = 146, //!< convert between BGRA and YUV UYVU, YUV is 4:2:2 and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x + COLOR_RGBA2YUV_Y422 = COLOR_RGBA2YUV_UYVY, //!< synonym to UYVY + COLOR_BGRA2YUV_Y422 = COLOR_BGRA2YUV_UYVY, //!< synonym to UYVY + COLOR_RGBA2YUV_UYNV = COLOR_RGBA2YUV_UYVY, //!< synonym to UYVY + COLOR_BGRA2YUV_UYNV = COLOR_BGRA2YUV_UYVY, //!< synonym to UYVY + + COLOR_RGB2YUV_YUY2 = 147, //!< convert between RGB and YUV YUY2, YUV is 4:2:2 and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x + COLOR_BGR2YUV_YUY2 = 148, //!< convert between BGR and YUV YUY2, YUV is 4:2:2 and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x + COLOR_RGB2YUV_YVYU = 149, //!< convert between RGB and YUV YVYU, YUV is 4:2:2 and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x + COLOR_BGR2YUV_YVYU = 150, //!< convert between BGR and YUV YVYU, YUV is 4:2:2 and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x + COLOR_RGB2YUV_YUYV = COLOR_RGB2YUV_YUY2, //!< synonym to YUY2 + COLOR_BGR2YUV_YUYV = COLOR_BGR2YUV_YUY2, //!< synonym to YUY2 + COLOR_RGB2YUV_YUNV = COLOR_RGB2YUV_YUY2, //!< synonym to YUY2 + COLOR_BGR2YUV_YUNV = COLOR_BGR2YUV_YUY2, //!< synonym to YUY2 + + COLOR_RGBA2YUV_YUY2 = 151, //!< convert between RGBA and YUV YUY2, YUV is 4:2:2 and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x + COLOR_BGRA2YUV_YUY2 = 152, //!< convert between BGRA and YUV YUY2, YUV is 4:2:2 and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x + COLOR_RGBA2YUV_YVYU = 153, //!< convert between RGBA and YUV YVYU, YUV is 4:2:2 and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x + COLOR_BGRA2YUV_YVYU = 154, //!< convert between BGRA and YUV YVYU, YUV is 4:2:2 and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x + COLOR_RGBA2YUV_YUYV = COLOR_RGBA2YUV_YUY2, //!< synonym to YUY2 + COLOR_BGRA2YUV_YUYV = COLOR_BGRA2YUV_YUY2, //!< synonym to YUY2 + COLOR_RGBA2YUV_YUNV = COLOR_RGBA2YUV_YUY2, //!< synonym to YUY2 + COLOR_BGRA2YUV_YUNV = COLOR_BGRA2YUV_YUY2, //!< synonym to YUY2 + + COLOR_COLORCVT_MAX = 155 +}; + +//! @addtogroup imgproc_shape +//! @{ + +//! types of intersection between rectangles +enum RectanglesIntersectTypes { + INTERSECT_NONE = 0, //!< No intersection + INTERSECT_PARTIAL = 1, //!< There is a partial intersection + INTERSECT_FULL = 2 //!< One of the rectangle is fully enclosed in the other +}; + +/** types of line +@ingroup imgproc_draw +*/ +enum LineTypes { + FILLED = -1, + LINE_4 = 4, //!< 4-connected line + LINE_8 = 8, //!< 8-connected line + LINE_AA = 16 //!< antialiased line +}; + +/** Only a subset of Hershey fonts are supported +@ingroup imgproc_draw +*/ +enum HersheyFonts { + FONT_HERSHEY_SIMPLEX = 0, //!< normal size sans-serif font + FONT_HERSHEY_PLAIN = 1, //!< small size sans-serif font + FONT_HERSHEY_DUPLEX = 2, //!< normal size sans-serif font (more complex than FONT_HERSHEY_SIMPLEX) + FONT_HERSHEY_COMPLEX = 3, //!< normal size serif font + FONT_HERSHEY_TRIPLEX = 4, //!< normal size serif font (more complex than FONT_HERSHEY_COMPLEX) + FONT_HERSHEY_COMPLEX_SMALL = 5, //!< smaller version of FONT_HERSHEY_COMPLEX + FONT_HERSHEY_SCRIPT_SIMPLEX = 6, //!< hand-writing style font + FONT_HERSHEY_SCRIPT_COMPLEX = 7, //!< more complex variant of FONT_HERSHEY_SCRIPT_SIMPLEX + FONT_ITALIC = 16 //!< flag for italic font +}; + +/** Possible set of marker types used for the cv::drawMarker function +@ingroup imgproc_draw +*/ +enum MarkerTypes +{ + MARKER_CROSS = 0, //!< A crosshair marker shape + MARKER_TILTED_CROSS = 1, //!< A 45 degree tilted crosshair marker shape + MARKER_STAR = 2, //!< A star marker shape, combination of cross and tilted cross + MARKER_DIAMOND = 3, //!< A diamond marker shape + MARKER_SQUARE = 4, //!< A square marker shape + MARKER_TRIANGLE_UP = 5, //!< An upwards pointing triangle marker shape + MARKER_TRIANGLE_DOWN = 6 //!< A downwards pointing triangle marker shape +}; + +/** @brief finds arbitrary template in the grayscale image using Generalized Hough Transform +*/ +class CV_EXPORTS_W GeneralizedHough : public Algorithm +{ +public: + //! set template to search + CV_WRAP virtual void setTemplate(InputArray templ, Point templCenter = Point(-1, -1)) = 0; + CV_WRAP virtual void setTemplate(InputArray edges, InputArray dx, InputArray dy, Point templCenter = Point(-1, -1)) = 0; + + //! find template on image + CV_WRAP virtual void detect(InputArray image, OutputArray positions, OutputArray votes = noArray()) = 0; + CV_WRAP virtual void detect(InputArray edges, InputArray dx, InputArray dy, OutputArray positions, OutputArray votes = noArray()) = 0; + + //! Canny low threshold. + CV_WRAP virtual void setCannyLowThresh(int cannyLowThresh) = 0; + CV_WRAP virtual int getCannyLowThresh() const = 0; + + //! Canny high threshold. + CV_WRAP virtual void setCannyHighThresh(int cannyHighThresh) = 0; + CV_WRAP virtual int getCannyHighThresh() const = 0; + + //! Minimum distance between the centers of the detected objects. + CV_WRAP virtual void setMinDist(double minDist) = 0; + CV_WRAP virtual double getMinDist() const = 0; + + //! Inverse ratio of the accumulator resolution to the image resolution. + CV_WRAP virtual void setDp(double dp) = 0; + CV_WRAP virtual double getDp() const = 0; + + //! Maximal size of inner buffers. + CV_WRAP virtual void setMaxBufferSize(int maxBufferSize) = 0; + CV_WRAP virtual int getMaxBufferSize() const = 0; +}; + +/** @brief finds arbitrary template in the grayscale image using Generalized Hough Transform + +Detects position only without translation and rotation @cite Ballard1981 . +*/ +class CV_EXPORTS_W GeneralizedHoughBallard : public GeneralizedHough +{ +public: + //! R-Table levels. + CV_WRAP virtual void setLevels(int levels) = 0; + CV_WRAP virtual int getLevels() const = 0; + + //! The accumulator threshold for the template centers at the detection stage. The smaller it is, the more false positions may be detected. + CV_WRAP virtual void setVotesThreshold(int votesThreshold) = 0; + CV_WRAP virtual int getVotesThreshold() const = 0; +}; + +/** @brief finds arbitrary template in the grayscale image using Generalized Hough Transform + +Detects position, translation and rotation @cite Guil1999 . +*/ +class CV_EXPORTS_W GeneralizedHoughGuil : public GeneralizedHough +{ +public: + //! Angle difference in degrees between two points in feature. + CV_WRAP virtual void setXi(double xi) = 0; + CV_WRAP virtual double getXi() const = 0; + + //! Feature table levels. + CV_WRAP virtual void setLevels(int levels) = 0; + CV_WRAP virtual int getLevels() const = 0; + + //! Maximal difference between angles that treated as equal. + CV_WRAP virtual void setAngleEpsilon(double angleEpsilon) = 0; + CV_WRAP virtual double getAngleEpsilon() const = 0; + + //! Minimal rotation angle to detect in degrees. + CV_WRAP virtual void setMinAngle(double minAngle) = 0; + CV_WRAP virtual double getMinAngle() const = 0; + + //! Maximal rotation angle to detect in degrees. + CV_WRAP virtual void setMaxAngle(double maxAngle) = 0; + CV_WRAP virtual double getMaxAngle() const = 0; + + //! Angle step in degrees. + CV_WRAP virtual void setAngleStep(double angleStep) = 0; + CV_WRAP virtual double getAngleStep() const = 0; + + //! Angle votes threshold. + CV_WRAP virtual void setAngleThresh(int angleThresh) = 0; + CV_WRAP virtual int getAngleThresh() const = 0; + + //! Minimal scale to detect. + CV_WRAP virtual void setMinScale(double minScale) = 0; + CV_WRAP virtual double getMinScale() const = 0; + + //! Maximal scale to detect. + CV_WRAP virtual void setMaxScale(double maxScale) = 0; + CV_WRAP virtual double getMaxScale() const = 0; + + //! Scale step. + CV_WRAP virtual void setScaleStep(double scaleStep) = 0; + CV_WRAP virtual double getScaleStep() const = 0; + + //! Scale votes threshold. + CV_WRAP virtual void setScaleThresh(int scaleThresh) = 0; + CV_WRAP virtual int getScaleThresh() const = 0; + + //! Position votes threshold. + CV_WRAP virtual void setPosThresh(int posThresh) = 0; + CV_WRAP virtual int getPosThresh() const = 0; +}; + +//! @} imgproc_shape + +//! @addtogroup imgproc_hist +//! @{ + +/** @brief Base class for Contrast Limited Adaptive Histogram Equalization. +*/ +class CV_EXPORTS_W CLAHE : public Algorithm +{ +public: + /** @brief Equalizes the histogram of a grayscale image using Contrast Limited Adaptive Histogram Equalization. + + @param src Source image of type CV_8UC1 or CV_16UC1. + @param dst Destination image. + */ + CV_WRAP virtual void apply(InputArray src, OutputArray dst) = 0; + + /** @brief Sets threshold for contrast limiting. + + @param clipLimit threshold value. + */ + CV_WRAP virtual void setClipLimit(double clipLimit) = 0; + + //! Returns threshold value for contrast limiting. + CV_WRAP virtual double getClipLimit() const = 0; + + /** @brief Sets size of grid for histogram equalization. Input image will be divided into + equally sized rectangular tiles. + + @param tileGridSize defines the number of tiles in row and column. + */ + CV_WRAP virtual void setTilesGridSize(Size tileGridSize) = 0; + + //!@brief Returns Size defines the number of tiles in row and column. + CV_WRAP virtual Size getTilesGridSize() const = 0; + + CV_WRAP virtual void collectGarbage() = 0; +}; + +//! @} imgproc_hist + +//! @addtogroup imgproc_subdiv2d +//! @{ + +class CV_EXPORTS_W Subdiv2D +{ +public: + /** Subdiv2D point location cases */ + enum { PTLOC_ERROR = -2, //!< Point location error + PTLOC_OUTSIDE_RECT = -1, //!< Point outside the subdivision bounding rect + PTLOC_INSIDE = 0, //!< Point inside some facet + PTLOC_VERTEX = 1, //!< Point coincides with one of the subdivision vertices + PTLOC_ON_EDGE = 2 //!< Point on some edge + }; + + /** Subdiv2D edge type navigation (see: getEdge()) */ + enum { NEXT_AROUND_ORG = 0x00, + NEXT_AROUND_DST = 0x22, + PREV_AROUND_ORG = 0x11, + PREV_AROUND_DST = 0x33, + NEXT_AROUND_LEFT = 0x13, + NEXT_AROUND_RIGHT = 0x31, + PREV_AROUND_LEFT = 0x20, + PREV_AROUND_RIGHT = 0x02 + }; + + /** creates an empty Subdiv2D object. + To create a new empty Delaunay subdivision you need to use the #initDelaunay function. + */ + CV_WRAP Subdiv2D(); + + /** @overload + + @param rect Rectangle that includes all of the 2D points that are to be added to the subdivision. + + The function creates an empty Delaunay subdivision where 2D points can be added using the function + insert() . All of the points to be added must be within the specified rectangle, otherwise a runtime + error is raised. + */ + CV_WRAP Subdiv2D(Rect rect); + + /** @brief Creates a new empty Delaunay subdivision + + @param rect Rectangle that includes all of the 2D points that are to be added to the subdivision. + + */ + CV_WRAP void initDelaunay(Rect rect); + + /** @brief Insert a single point into a Delaunay triangulation. + + @param pt Point to insert. + + The function inserts a single point into a subdivision and modifies the subdivision topology + appropriately. If a point with the same coordinates exists already, no new point is added. + @returns the ID of the point. + + @note If the point is outside of the triangulation specified rect a runtime error is raised. + */ + CV_WRAP int insert(Point2f pt); + + /** @brief Insert multiple points into a Delaunay triangulation. + + @param ptvec Points to insert. + + The function inserts a vector of points into a subdivision and modifies the subdivision topology + appropriately. + */ + CV_WRAP void insert(const std::vector& ptvec); + + /** @brief Returns the location of a point within a Delaunay triangulation. + + @param pt Point to locate. + @param edge Output edge that the point belongs to or is located to the right of it. + @param vertex Optional output vertex the input point coincides with. + + The function locates the input point within the subdivision and gives one of the triangle edges + or vertices. + + @returns an integer which specify one of the following five cases for point location: + - The point falls into some facet. The function returns #PTLOC_INSIDE and edge will contain one of + edges of the facet. + - The point falls onto the edge. The function returns #PTLOC_ON_EDGE and edge will contain this edge. + - The point coincides with one of the subdivision vertices. The function returns #PTLOC_VERTEX and + vertex will contain a pointer to the vertex. + - The point is outside the subdivision reference rectangle. The function returns #PTLOC_OUTSIDE_RECT + and no pointers are filled. + - One of input arguments is invalid. A runtime error is raised or, if silent or "parent" error + processing mode is selected, #PTLOC_ERROR is returned. + */ + CV_WRAP int locate(Point2f pt, CV_OUT int& edge, CV_OUT int& vertex); + + /** @brief Finds the subdivision vertex closest to the given point. + + @param pt Input point. + @param nearestPt Output subdivision vertex point. + + The function is another function that locates the input point within the subdivision. It finds the + subdivision vertex that is the closest to the input point. It is not necessarily one of vertices + of the facet containing the input point, though the facet (located using locate() ) is used as a + starting point. + + @returns vertex ID. + */ + CV_WRAP int findNearest(Point2f pt, CV_OUT Point2f* nearestPt = 0); + + /** @brief Returns a list of all edges. + + @param edgeList Output vector. + + The function gives each edge as a 4 numbers vector, where each two are one of the edge + vertices. i.e. org_x = v[0], org_y = v[1], dst_x = v[2], dst_y = v[3]. + */ + CV_WRAP void getEdgeList(CV_OUT std::vector& edgeList) const; + + /** @brief Returns a list of the leading edge ID connected to each triangle. + + @param leadingEdgeList Output vector. + + The function gives one edge ID for each triangle. + */ + CV_WRAP void getLeadingEdgeList(CV_OUT std::vector& leadingEdgeList) const; + + /** @brief Returns a list of all triangles. + + @param triangleList Output vector. + + The function gives each triangle as a 6 numbers vector, where each two are one of the triangle + vertices. i.e. p1_x = v[0], p1_y = v[1], p2_x = v[2], p2_y = v[3], p3_x = v[4], p3_y = v[5]. + */ + CV_WRAP void getTriangleList(CV_OUT std::vector& triangleList) const; + + /** @brief Returns a list of all Voronoi facets. + + @param idx Vector of vertices IDs to consider. For all vertices you can pass empty vector. + @param facetList Output vector of the Voronoi facets. + @param facetCenters Output vector of the Voronoi facets center points. + + */ + CV_WRAP void getVoronoiFacetList(const std::vector& idx, CV_OUT std::vector >& facetList, + CV_OUT std::vector& facetCenters); + + /** @brief Returns vertex location from vertex ID. + + @param vertex vertex ID. + @param firstEdge Optional. The first edge ID which is connected to the vertex. + @returns vertex (x,y) + + */ + CV_WRAP Point2f getVertex(int vertex, CV_OUT int* firstEdge = 0) const; + + /** @brief Returns one of the edges related to the given edge. + + @param edge Subdivision edge ID. + @param nextEdgeType Parameter specifying which of the related edges to return. + The following values are possible: + - NEXT_AROUND_ORG next around the edge origin ( eOnext on the picture below if e is the input edge) + - NEXT_AROUND_DST next around the edge vertex ( eDnext ) + - PREV_AROUND_ORG previous around the edge origin (reversed eRnext ) + - PREV_AROUND_DST previous around the edge destination (reversed eLnext ) + - NEXT_AROUND_LEFT next around the left facet ( eLnext ) + - NEXT_AROUND_RIGHT next around the right facet ( eRnext ) + - PREV_AROUND_LEFT previous around the left facet (reversed eOnext ) + - PREV_AROUND_RIGHT previous around the right facet (reversed eDnext ) + + ![sample output](pics/quadedge.png) + + @returns edge ID related to the input edge. + */ + CV_WRAP int getEdge( int edge, int nextEdgeType ) const; + + /** @brief Returns next edge around the edge origin. + + @param edge Subdivision edge ID. + + @returns an integer which is next edge ID around the edge origin: eOnext on the + picture above if e is the input edge). + */ + CV_WRAP int nextEdge(int edge) const; + + /** @brief Returns another edge of the same quad-edge. + + @param edge Subdivision edge ID. + @param rotate Parameter specifying which of the edges of the same quad-edge as the input + one to return. The following values are possible: + - 0 - the input edge ( e on the picture below if e is the input edge) + - 1 - the rotated edge ( eRot ) + - 2 - the reversed edge (reversed e (in green)) + - 3 - the reversed rotated edge (reversed eRot (in green)) + + @returns one of the edges ID of the same quad-edge as the input edge. + */ + CV_WRAP int rotateEdge(int edge, int rotate) const; + CV_WRAP int symEdge(int edge) const; + + /** @brief Returns the edge origin. + + @param edge Subdivision edge ID. + @param orgpt Output vertex location. + + @returns vertex ID. + */ + CV_WRAP int edgeOrg(int edge, CV_OUT Point2f* orgpt = 0) const; + + /** @brief Returns the edge destination. + + @param edge Subdivision edge ID. + @param dstpt Output vertex location. + + @returns vertex ID. + */ + CV_WRAP int edgeDst(int edge, CV_OUT Point2f* dstpt = 0) const; + +protected: + int newEdge(); + void deleteEdge(int edge); + int newPoint(Point2f pt, bool isvirtual, int firstEdge = 0); + void deletePoint(int vtx); + void setEdgePoints( int edge, int orgPt, int dstPt ); + void splice( int edgeA, int edgeB ); + int connectEdges( int edgeA, int edgeB ); + void swapEdges( int edge ); + int isRightOf(Point2f pt, int edge) const; + void calcVoronoi(); + void clearVoronoi(); + void checkSubdiv() const; + + struct CV_EXPORTS Vertex + { + Vertex(); + Vertex(Point2f pt, bool isvirtual, int firstEdge=0); + bool isvirtual() const; + bool isfree() const; + + int firstEdge; + int type; + Point2f pt; + }; + + struct CV_EXPORTS QuadEdge + { + QuadEdge(); + QuadEdge(int edgeidx); + bool isfree() const; + + int next[4]; + int pt[4]; + }; + + //! All of the vertices + std::vector vtx; + //! All of the edges + std::vector qedges; + int freeQEdge; + int freePoint; + bool validGeometry; + + int recentEdge; + //! Top left corner of the bounding rect + Point2f topLeft; + //! Bottom right corner of the bounding rect + Point2f bottomRight; +}; + +//! @} imgproc_subdiv2d + +//! @addtogroup imgproc_feature +//! @{ + +/** @example samples/cpp/lsd_lines.cpp +An example using the LineSegmentDetector +\image html building_lsd.png "Sample output image" width=434 height=300 +*/ + +/** @brief Line segment detector class + +following the algorithm described at @cite Rafael12 . + +@note Implementation has been removed from OpenCV version 3.4.6 to 3.4.15 and version 4.1.0 to 4.5.3 due original code license conflict. +restored again after [Computation of a NFA](https://github.com/rafael-grompone-von-gioi/binomial_nfa) code published under the MIT license. +*/ +class CV_EXPORTS_W LineSegmentDetector : public Algorithm +{ +public: + + /** @brief Finds lines in the input image. + + This is the output of the default parameters of the algorithm on the above shown image. + + ![image](pics/building_lsd.png) + + @param image A grayscale (CV_8UC1) input image. If only a roi needs to be selected, use: + `lsd_ptr-\>detect(image(roi), lines, ...); lines += Scalar(roi.x, roi.y, roi.x, roi.y);` + @param lines A vector of Vec4f elements specifying the beginning and ending point of a line. Where + Vec4f is (x1, y1, x2, y2), point 1 is the start, point 2 - end. Returned lines are strictly + oriented depending on the gradient. + @param width Vector of widths of the regions, where the lines are found. E.g. Width of line. + @param prec Vector of precisions with which the lines are found. + @param nfa Vector containing number of false alarms in the line region, with precision of 10%. The + bigger the value, logarithmically better the detection. + - -1 corresponds to 10 mean false alarms + - 0 corresponds to 1 mean false alarm + - 1 corresponds to 0.1 mean false alarms + This vector will be calculated only when the objects type is #LSD_REFINE_ADV. + */ + CV_WRAP virtual void detect(InputArray image, OutputArray lines, + OutputArray width = noArray(), OutputArray prec = noArray(), + OutputArray nfa = noArray()) = 0; + + /** @brief Draws the line segments on a given image. + @param image The image, where the lines will be drawn. Should be bigger or equal to the image, + where the lines were found. + @param lines A vector of the lines that needed to be drawn. + */ + CV_WRAP virtual void drawSegments(InputOutputArray image, InputArray lines) = 0; + + /** @brief Draws two groups of lines in blue and red, counting the non overlapping (mismatching) pixels. + + @param size The size of the image, where lines1 and lines2 were found. + @param lines1 The first group of lines that needs to be drawn. It is visualized in blue color. + @param lines2 The second group of lines. They visualized in red color. + @param image Optional image, where the lines will be drawn. The image should be color(3-channel) + in order for lines1 and lines2 to be drawn in the above mentioned colors. + */ + CV_WRAP virtual int compareSegments(const Size& size, InputArray lines1, InputArray lines2, InputOutputArray image = noArray()) = 0; + + virtual ~LineSegmentDetector() { } +}; + +/** @brief Creates a smart pointer to a LineSegmentDetector object and initializes it. + +The LineSegmentDetector algorithm is defined using the standard values. Only advanced users may want +to edit those, as to tailor it for their own application. + +@param refine The way found lines will be refined, see #LineSegmentDetectorModes +@param scale The scale of the image that will be used to find the lines. Range (0..1]. +@param sigma_scale Sigma for Gaussian filter. It is computed as sigma = sigma_scale/scale. +@param quant Bound to the quantization error on the gradient norm. +@param ang_th Gradient angle tolerance in degrees. +@param log_eps Detection threshold: -log10(NFA) \> log_eps. Used only when advance refinement is chosen. +@param density_th Minimal density of aligned region points in the enclosing rectangle. +@param n_bins Number of bins in pseudo-ordering of gradient modulus. + */ +CV_EXPORTS_W Ptr createLineSegmentDetector( + int refine = LSD_REFINE_STD, double scale = 0.8, + double sigma_scale = 0.6, double quant = 2.0, double ang_th = 22.5, + double log_eps = 0, double density_th = 0.7, int n_bins = 1024); + +//! @} imgproc_feature + +//! @addtogroup imgproc_filter +//! @{ + +/** @brief Returns Gaussian filter coefficients. + +The function computes and returns the \f$\texttt{ksize} \times 1\f$ matrix of Gaussian filter +coefficients: + +\f[G_i= \alpha *e^{-(i-( \texttt{ksize} -1)/2)^2/(2* \texttt{sigma}^2)},\f] + +where \f$i=0..\texttt{ksize}-1\f$ and \f$\alpha\f$ is the scale factor chosen so that \f$\sum_i G_i=1\f$. + +Two of such generated kernels can be passed to sepFilter2D. Those functions automatically recognize +smoothing kernels (a symmetrical kernel with sum of weights equal to 1) and handle them accordingly. +You may also use the higher-level GaussianBlur. +@param ksize Aperture size. It should be odd ( \f$\texttt{ksize} \mod 2 = 1\f$ ) and positive. +@param sigma Gaussian standard deviation. If it is non-positive, it is computed from ksize as +`sigma = 0.3*((ksize-1)*0.5 - 1) + 0.8`. +@param ktype Type of filter coefficients. It can be CV_32F or CV_64F . +@sa sepFilter2D, getDerivKernels, getStructuringElement, GaussianBlur + */ +CV_EXPORTS_W Mat getGaussianKernel( int ksize, double sigma, int ktype = CV_64F ); + +/** @brief Returns filter coefficients for computing spatial image derivatives. + +The function computes and returns the filter coefficients for spatial image derivatives. When +`ksize=FILTER_SCHARR`, the Scharr \f$3 \times 3\f$ kernels are generated (see #Scharr). Otherwise, Sobel +kernels are generated (see #Sobel). The filters are normally passed to #sepFilter2D or to + +@param kx Output matrix of row filter coefficients. It has the type ktype . +@param ky Output matrix of column filter coefficients. It has the type ktype . +@param dx Derivative order in respect of x. +@param dy Derivative order in respect of y. +@param ksize Aperture size. It can be FILTER_SCHARR, 1, 3, 5, or 7. +@param normalize Flag indicating whether to normalize (scale down) the filter coefficients or not. +Theoretically, the coefficients should have the denominator \f$=2^{ksize*2-dx-dy-2}\f$. If you are +going to filter floating-point images, you are likely to use the normalized kernels. But if you +compute derivatives of an 8-bit image, store the results in a 16-bit image, and wish to preserve +all the fractional bits, you may want to set normalize=false . +@param ktype Type of filter coefficients. It can be CV_32f or CV_64F . + */ +CV_EXPORTS_W void getDerivKernels( OutputArray kx, OutputArray ky, + int dx, int dy, int ksize, + bool normalize = false, int ktype = CV_32F ); + +/** @brief Returns Gabor filter coefficients. + +For more details about gabor filter equations and parameters, see: [Gabor +Filter](http://en.wikipedia.org/wiki/Gabor_filter). + +@param ksize Size of the filter returned. +@param sigma Standard deviation of the gaussian envelope. +@param theta Orientation of the normal to the parallel stripes of a Gabor function. +@param lambd Wavelength of the sinusoidal factor. +@param gamma Spatial aspect ratio. +@param psi Phase offset. +@param ktype Type of filter coefficients. It can be CV_32F or CV_64F . + */ +CV_EXPORTS_W Mat getGaborKernel( Size ksize, double sigma, double theta, double lambd, + double gamma, double psi = CV_PI*0.5, int ktype = CV_64F ); + +//! returns "magic" border value for erosion and dilation. It is automatically transformed to Scalar::all(-DBL_MAX) for dilation. +static inline Scalar morphologyDefaultBorderValue() { return Scalar::all(DBL_MAX); } + +/** @brief Returns a structuring element of the specified size and shape for morphological operations. + +The function constructs and returns the structuring element that can be further passed to #erode, +#dilate or #morphologyEx. But you can also construct an arbitrary binary mask yourself and use it as +the structuring element. + +@param shape Element shape that could be one of #MorphShapes +@param ksize Size of the structuring element. +@param anchor Anchor position within the element. The default value \f$(-1, -1)\f$ means that the +anchor is at the center. Note that only the shape of a cross-shaped element depends on the anchor +position. In other cases the anchor just regulates how much the result of the morphological +operation is shifted. + */ +CV_EXPORTS_W Mat getStructuringElement(int shape, Size ksize, Point anchor = Point(-1,-1)); + +/** @example samples/cpp/tutorial_code/ImgProc/Smoothing/Smoothing.cpp +Sample code for simple filters +![Sample screenshot](Smoothing_Tutorial_Result_Median_Filter.jpg) +Check @ref tutorial_gausian_median_blur_bilateral_filter "the corresponding tutorial" for more details + */ + +/** @brief Blurs an image using the median filter. + +The function smoothes an image using the median filter with the \f$\texttt{ksize} \times +\texttt{ksize}\f$ aperture. Each channel of a multi-channel image is processed independently. +In-place operation is supported. + +@note The median filter uses #BORDER_REPLICATE internally to cope with border pixels, see #BorderTypes + +@param src input 1-, 3-, or 4-channel image; when ksize is 3 or 5, the image depth should be +CV_8U, CV_16U, or CV_32F, for larger aperture sizes, it can only be CV_8U. +@param dst destination array of the same size and type as src. +@param ksize aperture linear size; it must be odd and greater than 1, for example: 3, 5, 7 ... +@sa bilateralFilter, blur, boxFilter, GaussianBlur + */ +CV_EXPORTS_W void medianBlur( InputArray src, OutputArray dst, int ksize ); + +/** @brief Blurs an image using a Gaussian filter. + +The function convolves the source image with the specified Gaussian kernel. In-place filtering is +supported. + +@param src input image; the image can have any number of channels, which are processed +independently, but the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. +@param dst output image of the same size and type as src. +@param ksize Gaussian kernel size. ksize.width and ksize.height can differ but they both must be +positive and odd. Or, they can be zero's and then they are computed from sigma. +@param sigmaX Gaussian kernel standard deviation in X direction. +@param sigmaY Gaussian kernel standard deviation in Y direction; if sigmaY is zero, it is set to be +equal to sigmaX, if both sigmas are zeros, they are computed from ksize.width and ksize.height, +respectively (see #getGaussianKernel for details); to fully control the result regardless of +possible future modifications of all this semantics, it is recommended to specify all of ksize, +sigmaX, and sigmaY. +@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. +@param hint Implementation modfication flags. See #AlgorithmHint + +@sa sepFilter2D, filter2D, blur, boxFilter, bilateralFilter, medianBlur + */ +CV_EXPORTS_W void GaussianBlur( InputArray src, OutputArray dst, Size ksize, + double sigmaX, double sigmaY = 0, + int borderType = BORDER_DEFAULT, + AlgorithmHint hint = cv::ALGO_HINT_DEFAULT ); + +/** @brief Applies the bilateral filter to an image. + +The function applies bilateral filtering to the input image, as described in +http://www.dai.ed.ac.uk/CVonline/LOCAL_COPIES/MANDUCHI1/Bilateral_Filtering.html +bilateralFilter can reduce unwanted noise very well while keeping edges fairly sharp. However, it is +very slow compared to most filters. + +_Sigma values_: For simplicity, you can set the 2 sigma values to be the same. If they are small (\< +10), the filter will not have much effect, whereas if they are large (\> 150), they will have a very +strong effect, making the image look "cartoonish". + +_Filter size_: Large filters (d \> 5) are very slow, so it is recommended to use d=5 for real-time +applications, and perhaps d=9 for offline applications that need heavy noise filtering. + +This filter does not work inplace. +@param src Source 8-bit or floating-point, 1-channel or 3-channel image. +@param dst Destination image of the same size and type as src . +@param d Diameter of each pixel neighborhood that is used during filtering. If it is non-positive, +it is computed from sigmaSpace. +@param sigmaColor Filter sigma in the color space. A larger value of the parameter means that +farther colors within the pixel neighborhood (see sigmaSpace) will be mixed together, resulting +in larger areas of semi-equal color. +@param sigmaSpace Filter sigma in the coordinate space. A larger value of the parameter means that +farther pixels will influence each other as long as their colors are close enough (see sigmaColor +). When d\>0, it specifies the neighborhood size regardless of sigmaSpace. Otherwise, d is +proportional to sigmaSpace. +@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes + */ +CV_EXPORTS_W void bilateralFilter( InputArray src, OutputArray dst, int d, + double sigmaColor, double sigmaSpace, + int borderType = BORDER_DEFAULT ); + +/** @brief Blurs an image using the box filter. + +The function smooths an image using the kernel: + +\f[\texttt{K} = \alpha \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \end{bmatrix}\f] + +where + +\f[\alpha = \begin{cases} \frac{1}{\texttt{ksize.width*ksize.height}} & \texttt{when } \texttt{normalize=true} \\1 & \texttt{otherwise}\end{cases}\f] + +Unnormalized box filter is useful for computing various integral characteristics over each pixel +neighborhood, such as covariance matrices of image derivatives (used in dense optical flow +algorithms, and so on). If you need to compute pixel sums over variable-size windows, use #integral. + +@param src input image. +@param dst output image of the same size and type as src. +@param ddepth the output image depth (-1 to use src.depth()). +@param ksize blurring kernel size. +@param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel +center. +@param normalize flag, specifying whether the kernel is normalized by its area or not. +@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes. #BORDER_WRAP is not supported. +@sa blur, bilateralFilter, GaussianBlur, medianBlur, integral + */ +CV_EXPORTS_W void boxFilter( InputArray src, OutputArray dst, int ddepth, + Size ksize, Point anchor = Point(-1,-1), + bool normalize = true, + int borderType = BORDER_DEFAULT ); + +/** @brief Calculates the normalized sum of squares of the pixel values overlapping the filter. + +For every pixel \f$ (x, y) \f$ in the source image, the function calculates the sum of squares of those neighboring +pixel values which overlap the filter placed over the pixel \f$ (x, y) \f$. + +The unnormalized square box filter can be useful in computing local image statistics such as the local +variance and standard deviation around the neighborhood of a pixel. + +@param src input image +@param dst output image of the same size and type as src +@param ddepth the output image depth (-1 to use src.depth()) +@param ksize kernel size +@param anchor kernel anchor point. The default value of Point(-1, -1) denotes that the anchor is at the kernel +center. +@param normalize flag, specifying whether the kernel is to be normalized by it's area or not. +@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes. #BORDER_WRAP is not supported. +@sa boxFilter +*/ +CV_EXPORTS_W void sqrBoxFilter( InputArray src, OutputArray dst, int ddepth, + Size ksize, Point anchor = Point(-1, -1), + bool normalize = true, + int borderType = BORDER_DEFAULT ); + +/** @brief Blurs an image using the normalized box filter. + +The function smooths an image using the kernel: + +\f[\texttt{K} = \frac{1}{\texttt{ksize.width*ksize.height}} \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \end{bmatrix}\f] + +The call `blur(src, dst, ksize, anchor, borderType)` is equivalent to `boxFilter(src, dst, src.type(), ksize, +anchor, true, borderType)`. + +@param src input image; it can have any number of channels, which are processed independently, but +the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. +@param dst output image of the same size and type as src. +@param ksize blurring kernel size. +@param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel +center. +@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes. #BORDER_WRAP is not supported. +@sa boxFilter, bilateralFilter, GaussianBlur, medianBlur + */ +CV_EXPORTS_W void blur( InputArray src, OutputArray dst, + Size ksize, Point anchor = Point(-1,-1), + int borderType = BORDER_DEFAULT ); + +/** @brief Blurs an image using the stackBlur. + +The function applies and stackBlur to an image. +stackBlur can generate similar results as Gaussian blur, and the time consumption does not increase with the increase of kernel size. +It creates a kind of moving stack of colors whilst scanning through the image. Thereby it just has to add one new block of color to the right side +of the stack and remove the leftmost color. The remaining colors on the topmost layer of the stack are either added on or reduced by one, +depending on if they are on the right or on the left side of the stack. The only supported borderType is BORDER_REPLICATE. +Original paper was proposed by Mario Klingemann, which can be found http://underdestruction.com/2004/02/25/stackblur-2004. + +@param src input image. The number of channels can be arbitrary, but the depth should be one of +CV_8U, CV_16U, CV_16S or CV_32F. +@param dst output image of the same size and type as src. +@param ksize stack-blurring kernel size. The ksize.width and ksize.height can differ but they both must be +positive and odd. +*/ +CV_EXPORTS_W void stackBlur(InputArray src, OutputArray dst, Size ksize); + +/** @brief Convolves an image with the kernel. + +The function applies an arbitrary linear filter to an image. In-place operation is supported. When +the aperture is partially outside the image, the function interpolates outlier pixel values +according to the specified border mode. + +The function does actually compute correlation, not the convolution: + +\f[\texttt{dst} (x,y) = \sum _{ \substack{0\leq x' < \texttt{kernel.cols}\\{0\leq y' < \texttt{kernel.rows}}}} \texttt{kernel} (x',y')* \texttt{src} (x+x'- \texttt{anchor.x} ,y+y'- \texttt{anchor.y} )\f] + +That is, the kernel is not mirrored around the anchor point. If you need a real convolution, flip +the kernel using #flip and set the new anchor to `(kernel.cols - anchor.x - 1, kernel.rows - +anchor.y - 1)`. + +The function uses the DFT-based algorithm in case of sufficiently large kernels (~`11 x 11` or +larger) and the direct algorithm for small kernels. + +@param src input image. +@param dst output image of the same size and the same number of channels as src. +@param ddepth desired depth of the destination image, see @ref filter_depths "combinations" +@param kernel convolution kernel (or rather a correlation kernel), a single-channel floating point +matrix; if you want to apply different kernels to different channels, split the image into +separate color planes using split and process them individually. +@param anchor anchor of the kernel that indicates the relative position of a filtered point within +the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor +is at the kernel center. +@param delta optional value added to the filtered pixels before storing them in dst. +@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. +@sa sepFilter2D, dft, matchTemplate + */ +CV_EXPORTS_W void filter2D( InputArray src, OutputArray dst, int ddepth, + InputArray kernel, Point anchor = Point(-1,-1), + double delta = 0, int borderType = BORDER_DEFAULT ); + +/** @brief Applies a separable linear filter to an image. + +The function applies a separable linear filter to the image. That is, first, every row of src is +filtered with the 1D kernel kernelX. Then, every column of the result is filtered with the 1D +kernel kernelY. The final result shifted by delta is stored in dst . + +@param src Source image. +@param dst Destination image of the same size and the same number of channels as src . +@param ddepth Destination image depth, see @ref filter_depths "combinations" +@param kernelX Coefficients for filtering each row. +@param kernelY Coefficients for filtering each column. +@param anchor Anchor position within the kernel. The default value \f$(-1,-1)\f$ means that the anchor +is at the kernel center. +@param delta Value added to the filtered results before storing them. +@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. +@sa filter2D, Sobel, GaussianBlur, boxFilter, blur + */ +CV_EXPORTS_W void sepFilter2D( InputArray src, OutputArray dst, int ddepth, + InputArray kernelX, InputArray kernelY, + Point anchor = Point(-1,-1), + double delta = 0, int borderType = BORDER_DEFAULT ); + +/** @example samples/cpp/tutorial_code/ImgTrans/Sobel_Demo.cpp +Sample code using Sobel and/or Scharr OpenCV functions to make a simple Edge Detector +![Sample screenshot](Sobel_Derivatives_Tutorial_Result.jpg) +Check @ref tutorial_sobel_derivatives "the corresponding tutorial" for more details +*/ + +/** @brief Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator. + +In all cases except one, the \f$\texttt{ksize} \times \texttt{ksize}\f$ separable kernel is used to +calculate the derivative. When \f$\texttt{ksize = 1}\f$, the \f$3 \times 1\f$ or \f$1 \times 3\f$ +kernel is used (that is, no Gaussian smoothing is done). `ksize = 1` can only be used for the first +or the second x- or y- derivatives. + +There is also the special value `ksize = #FILTER_SCHARR (-1)` that corresponds to the \f$3\times3\f$ Scharr +filter that may give more accurate results than the \f$3\times3\f$ Sobel. The Scharr aperture is + +\f[\vecthreethree{-3}{0}{3}{-10}{0}{10}{-3}{0}{3}\f] + +for the x-derivative, or transposed for the y-derivative. + +The function calculates an image derivative by convolving the image with the appropriate kernel: + +\f[\texttt{dst} = \frac{\partial^{xorder+yorder} \texttt{src}}{\partial x^{xorder} \partial y^{yorder}}\f] + +The Sobel operators combine Gaussian smoothing and differentiation, so the result is more or less +resistant to the noise. Most often, the function is called with ( xorder = 1, yorder = 0, ksize = 3) +or ( xorder = 0, yorder = 1, ksize = 3) to calculate the first x- or y- image derivative. The first +case corresponds to a kernel of: + +\f[\vecthreethree{-1}{0}{1}{-2}{0}{2}{-1}{0}{1}\f] + +The second case corresponds to a kernel of: + +\f[\vecthreethree{-1}{-2}{-1}{0}{0}{0}{1}{2}{1}\f] + +@param src input image. +@param dst output image of the same size and the same number of channels as src . +@param ddepth output image depth, see @ref filter_depths "combinations"; in the case of + 8-bit input images it will result in truncated derivatives. +@param dx order of the derivative x. +@param dy order of the derivative y. +@param ksize size of the extended Sobel kernel; it must be 1, 3, 5, or 7. +@param scale optional scale factor for the computed derivative values; by default, no scaling is +applied (see #getDerivKernels for details). +@param delta optional delta value that is added to the results prior to storing them in dst. +@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. +@sa Scharr, Laplacian, sepFilter2D, filter2D, GaussianBlur, cartToPolar + */ +CV_EXPORTS_W void Sobel( InputArray src, OutputArray dst, int ddepth, + int dx, int dy, int ksize = 3, + double scale = 1, double delta = 0, + int borderType = BORDER_DEFAULT ); + +/** @brief Calculates the first order image derivative in both x and y using a Sobel operator + +Equivalent to calling: + +@code +Sobel( src, dx, CV_16SC1, 1, 0, 3 ); +Sobel( src, dy, CV_16SC1, 0, 1, 3 ); +@endcode + +@param src input image. +@param dx output image with first-order derivative in x. +@param dy output image with first-order derivative in y. +@param ksize size of Sobel kernel. It must be 3. +@param borderType pixel extrapolation method, see #BorderTypes. + Only #BORDER_DEFAULT=#BORDER_REFLECT_101 and #BORDER_REPLICATE are supported. + +@sa Sobel + */ + +CV_EXPORTS_W void spatialGradient( InputArray src, OutputArray dx, + OutputArray dy, int ksize = 3, + int borderType = BORDER_DEFAULT ); + +/** @brief Calculates the first x- or y- image derivative using Scharr operator. + +The function computes the first x- or y- spatial image derivative using the Scharr operator. The +call + +\f[\texttt{Scharr(src, dst, ddepth, dx, dy, scale, delta, borderType)}\f] + +is equivalent to + +\f[\texttt{Sobel(src, dst, ddepth, dx, dy, FILTER_SCHARR, scale, delta, borderType)} .\f] + +@param src input image. +@param dst output image of the same size and the same number of channels as src. +@param ddepth output image depth, see @ref filter_depths "combinations" +@param dx order of the derivative x. +@param dy order of the derivative y. +@param scale optional scale factor for the computed derivative values; by default, no scaling is +applied (see #getDerivKernels for details). +@param delta optional delta value that is added to the results prior to storing them in dst. +@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. +@sa cartToPolar + */ +CV_EXPORTS_W void Scharr( InputArray src, OutputArray dst, int ddepth, + int dx, int dy, double scale = 1, double delta = 0, + int borderType = BORDER_DEFAULT ); + +/** @example samples/cpp/laplace.cpp +An example using Laplace transformations for edge detection +*/ + +/** @brief Calculates the Laplacian of an image. + +The function calculates the Laplacian of the source image by adding up the second x and y +derivatives calculated using the Sobel operator: + +\f[\texttt{dst} = \Delta \texttt{src} = \frac{\partial^2 \texttt{src}}{\partial x^2} + \frac{\partial^2 \texttt{src}}{\partial y^2}\f] + +This is done when `ksize > 1`. When `ksize == 1`, the Laplacian is computed by filtering the image +with the following \f$3 \times 3\f$ aperture: + +\f[\vecthreethree {0}{1}{0}{1}{-4}{1}{0}{1}{0}\f] + +@param src Source image. +@param dst Destination image of the same size and the same number of channels as src . +@param ddepth Desired depth of the destination image, see @ref filter_depths "combinations". +@param ksize Aperture size used to compute the second-derivative filters. See #getDerivKernels for +details. The size must be positive and odd. +@param scale Optional scale factor for the computed Laplacian values. By default, no scaling is +applied. See #getDerivKernels for details. +@param delta Optional delta value that is added to the results prior to storing them in dst . +@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. +@sa Sobel, Scharr + */ +CV_EXPORTS_W void Laplacian( InputArray src, OutputArray dst, int ddepth, + int ksize = 1, double scale = 1, double delta = 0, + int borderType = BORDER_DEFAULT ); + +//! @} imgproc_filter + +//! @addtogroup imgproc_feature +//! @{ + +/** @example samples/cpp/edge.cpp +This program demonstrates usage of the Canny edge detector + +Check @ref tutorial_canny_detector "the corresponding tutorial" for more details +*/ + +/** @brief Finds edges in an image using the Canny algorithm @cite Canny86 . + +The function finds edges in the input image and marks them in the output map edges using the +Canny algorithm. The smallest value between threshold1 and threshold2 is used for edge linking. The +largest value is used to find initial segments of strong edges. See + + +@param image 8-bit input image. +@param edges output edge map; single channels 8-bit image, which has the same size as image . +@param threshold1 first threshold for the hysteresis procedure. +@param threshold2 second threshold for the hysteresis procedure. +@param apertureSize aperture size for the Sobel operator. +@param L2gradient a flag, indicating whether a more accurate \f$L_2\f$ norm +\f$=\sqrt{(dI/dx)^2 + (dI/dy)^2}\f$ should be used to calculate the image gradient magnitude ( +L2gradient=true ), or whether the default \f$L_1\f$ norm \f$=|dI/dx|+|dI/dy|\f$ is enough ( +L2gradient=false ). + */ +CV_EXPORTS_W void Canny( InputArray image, OutputArray edges, + double threshold1, double threshold2, + int apertureSize = 3, bool L2gradient = false ); + +/** \overload + +Finds edges in an image using the Canny algorithm with custom image gradient. + +@param dx 16-bit x derivative of input image (CV_16SC1 or CV_16SC3). +@param dy 16-bit y derivative of input image (same type as dx). +@param edges output edge map; single channels 8-bit image, which has the same size as image . +@param threshold1 first threshold for the hysteresis procedure. +@param threshold2 second threshold for the hysteresis procedure. +@param L2gradient a flag, indicating whether a more accurate \f$L_2\f$ norm +\f$=\sqrt{(dI/dx)^2 + (dI/dy)^2}\f$ should be used to calculate the image gradient magnitude ( +L2gradient=true ), or whether the default \f$L_1\f$ norm \f$=|dI/dx|+|dI/dy|\f$ is enough ( +L2gradient=false ). + */ +CV_EXPORTS_W void Canny( InputArray dx, InputArray dy, + OutputArray edges, + double threshold1, double threshold2, + bool L2gradient = false ); + +/** @brief Calculates the minimal eigenvalue of gradient matrices for corner detection. + +The function is similar to cornerEigenValsAndVecs but it calculates and stores only the minimal +eigenvalue of the covariance matrix of derivatives, that is, \f$\min(\lambda_1, \lambda_2)\f$ in terms +of the formulae in the cornerEigenValsAndVecs description. + +@param src Input single-channel 8-bit or floating-point image. +@param dst Image to store the minimal eigenvalues. It has the type CV_32FC1 and the same size as +src . +@param blockSize Neighborhood size (see the details on #cornerEigenValsAndVecs ). +@param ksize Aperture parameter for the Sobel operator. +@param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported. + */ +CV_EXPORTS_W void cornerMinEigenVal( InputArray src, OutputArray dst, + int blockSize, int ksize = 3, + int borderType = BORDER_DEFAULT ); + +/** @brief Harris corner detector. + +The function runs the Harris corner detector on the image. Similarly to cornerMinEigenVal and +cornerEigenValsAndVecs , for each pixel \f$(x, y)\f$ it calculates a \f$2\times2\f$ gradient covariance +matrix \f$M^{(x,y)}\f$ over a \f$\texttt{blockSize} \times \texttt{blockSize}\f$ neighborhood. Then, it +computes the following characteristic: + +\f[\texttt{dst} (x,y) = \mathrm{det} M^{(x,y)} - k \cdot \left ( \mathrm{tr} M^{(x,y)} \right )^2\f] + +Corners in the image can be found as the local maxima of this response map. + +@param src Input single-channel 8-bit or floating-point image. +@param dst Image to store the Harris detector responses. It has the type CV_32FC1 and the same +size as src . +@param blockSize Neighborhood size (see the details on #cornerEigenValsAndVecs ). +@param ksize Aperture parameter for the Sobel operator. +@param k Harris detector free parameter. See the formula above. +@param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported. + */ +CV_EXPORTS_W void cornerHarris( InputArray src, OutputArray dst, int blockSize, + int ksize, double k, + int borderType = BORDER_DEFAULT ); + +/** @brief Calculates eigenvalues and eigenvectors of image blocks for corner detection. + +For every pixel \f$p\f$ , the function cornerEigenValsAndVecs considers a blockSize \f$\times\f$ blockSize +neighborhood \f$S(p)\f$ . It calculates the covariation matrix of derivatives over the neighborhood as: + +\f[M = \begin{bmatrix} \sum _{S(p)}(dI/dx)^2 & \sum _{S(p)}dI/dx dI/dy \\ \sum _{S(p)}dI/dx dI/dy & \sum _{S(p)}(dI/dy)^2 \end{bmatrix}\f] + +where the derivatives are computed using the Sobel operator. + +After that, it finds eigenvectors and eigenvalues of \f$M\f$ and stores them in the destination image as +\f$(\lambda_1, \lambda_2, x_1, y_1, x_2, y_2)\f$ where + +- \f$\lambda_1, \lambda_2\f$ are the non-sorted eigenvalues of \f$M\f$ +- \f$x_1, y_1\f$ are the eigenvectors corresponding to \f$\lambda_1\f$ +- \f$x_2, y_2\f$ are the eigenvectors corresponding to \f$\lambda_2\f$ + +The output of the function can be used for robust edge or corner detection. + +@param src Input single-channel 8-bit or floating-point image. +@param dst Image to store the results. It has the same size as src and the type CV_32FC(6) . +@param blockSize Neighborhood size (see details below). +@param ksize Aperture parameter for the Sobel operator. +@param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported. + +@sa cornerMinEigenVal, cornerHarris, preCornerDetect + */ +CV_EXPORTS_W void cornerEigenValsAndVecs( InputArray src, OutputArray dst, + int blockSize, int ksize, + int borderType = BORDER_DEFAULT ); + +/** @brief Calculates a feature map for corner detection. + +The function calculates the complex spatial derivative-based function of the source image + +\f[\texttt{dst} = (D_x \texttt{src} )^2 \cdot D_{yy} \texttt{src} + (D_y \texttt{src} )^2 \cdot D_{xx} \texttt{src} - 2 D_x \texttt{src} \cdot D_y \texttt{src} \cdot D_{xy} \texttt{src}\f] + +where \f$D_x\f$,\f$D_y\f$ are the first image derivatives, \f$D_{xx}\f$,\f$D_{yy}\f$ are the second image +derivatives, and \f$D_{xy}\f$ is the mixed derivative. + +The corners can be found as local maximums of the functions, as shown below: +@code + Mat corners, dilated_corners; + preCornerDetect(image, corners, 3); + // dilation with 3x3 rectangular structuring element + dilate(corners, dilated_corners, Mat(), 1); + Mat corner_mask = corners == dilated_corners; +@endcode + +@param src Source single-channel 8-bit of floating-point image. +@param dst Output image that has the type CV_32F and the same size as src . +@param ksize %Aperture size of the Sobel . +@param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported. + */ +CV_EXPORTS_W void preCornerDetect( InputArray src, OutputArray dst, int ksize, + int borderType = BORDER_DEFAULT ); + +/** @brief Refines the corner locations. + +The function iterates to find the sub-pixel accurate location of corners or radial saddle +points as described in @cite forstner1987fast, and as shown on the figure below. + +![image](pics/cornersubpix.png) + +Sub-pixel accurate corner locator is based on the observation that every vector from the center \f$q\f$ +to a point \f$p\f$ located within a neighborhood of \f$q\f$ is orthogonal to the image gradient at \f$p\f$ +subject to image and measurement noise. Consider the expression: + +\f[\epsilon _i = {DI_{p_i}}^T \cdot (q - p_i)\f] + +where \f${DI_{p_i}}\f$ is an image gradient at one of the points \f$p_i\f$ in a neighborhood of \f$q\f$ . The +value of \f$q\f$ is to be found so that \f$\epsilon_i\f$ is minimized. A system of equations may be set up +with \f$\epsilon_i\f$ set to zero: + +\f[\sum _i(DI_{p_i} \cdot {DI_{p_i}}^T) \cdot q - \sum _i(DI_{p_i} \cdot {DI_{p_i}}^T \cdot p_i)\f] + +where the gradients are summed within a neighborhood ("search window") of \f$q\f$ . Calling the first +gradient term \f$G\f$ and the second gradient term \f$b\f$ gives: + +\f[q = G^{-1} \cdot b\f] + +The algorithm sets the center of the neighborhood window at this new center \f$q\f$ and then iterates +until the center stays within a set threshold. + +@param image Input single-channel, 8-bit or float image. +@param corners Initial coordinates of the input corners and refined coordinates provided for +output. +@param winSize Half of the side length of the search window. For example, if winSize=Size(5,5) , +then a \f$(5*2+1) \times (5*2+1) = 11 \times 11\f$ search window is used. +@param zeroZone Half of the size of the dead region in the middle of the search zone over which +the summation in the formula below is not done. It is used sometimes to avoid possible +singularities of the autocorrelation matrix. The value of (-1,-1) indicates that there is no such +a size. +@param criteria Criteria for termination of the iterative process of corner refinement. That is, +the process of corner position refinement stops either after criteria.maxCount iterations or when +the corner position moves by less than criteria.epsilon on some iteration. + */ +CV_EXPORTS_W void cornerSubPix( InputArray image, InputOutputArray corners, + Size winSize, Size zeroZone, + TermCriteria criteria ); + +/** @brief Determines strong corners on an image. + +The function finds the most prominent corners in the image or in the specified image region, as +described in @cite Shi94 + +- Function calculates the corner quality measure at every source image pixel using the + #cornerMinEigenVal or #cornerHarris . +- Function performs a non-maximum suppression (the local maximums in *3 x 3* neighborhood are + retained). +- The corners with the minimal eigenvalue less than + \f$\texttt{qualityLevel} \cdot \max_{x,y} qualityMeasureMap(x,y)\f$ are rejected. +- The remaining corners are sorted by the quality measure in the descending order. +- Function throws away each corner for which there is a stronger corner at a distance less than + maxDistance. + +The function can be used to initialize a point-based tracker of an object. + +@note If the function is called with different values A and B of the parameter qualityLevel , and +A \> B, the vector of returned corners with qualityLevel=A will be the prefix of the output vector +with qualityLevel=B . + +@param image Input 8-bit or floating-point 32-bit, single-channel image. +@param corners Output vector of detected corners. +@param maxCorners Maximum number of corners to return. If there are more corners than are found, +the strongest of them is returned. `maxCorners <= 0` implies that no limit on the maximum is set +and all detected corners are returned. +@param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The +parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue +(see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the +quality measure less than the product are rejected. For example, if the best corner has the +quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure +less than 15 are rejected. +@param minDistance Minimum possible Euclidean distance between the returned corners. +@param mask Optional region of interest. If the image is not empty (it needs to have the type +CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. +@param blockSize Size of an average block for computing a derivative covariation matrix over each +pixel neighborhood. See cornerEigenValsAndVecs . +@param useHarrisDetector Parameter indicating whether to use a Harris detector (see #cornerHarris) +or #cornerMinEigenVal. +@param k Free parameter of the Harris detector. + +@sa cornerMinEigenVal, cornerHarris, calcOpticalFlowPyrLK, estimateRigidTransform, + */ + +CV_EXPORTS_W void goodFeaturesToTrack( InputArray image, OutputArray corners, + int maxCorners, double qualityLevel, double minDistance, + InputArray mask = noArray(), int blockSize = 3, + bool useHarrisDetector = false, double k = 0.04 ); + +CV_EXPORTS_W void goodFeaturesToTrack( InputArray image, OutputArray corners, + int maxCorners, double qualityLevel, double minDistance, + InputArray mask, int blockSize, + int gradientSize, bool useHarrisDetector = false, + double k = 0.04 ); + +/** @brief Same as above, but returns also quality measure of the detected corners. + +@param image Input 8-bit or floating-point 32-bit, single-channel image. +@param corners Output vector of detected corners. +@param maxCorners Maximum number of corners to return. If there are more corners than are found, +the strongest of them is returned. `maxCorners <= 0` implies that no limit on the maximum is set +and all detected corners are returned. +@param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The +parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue +(see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the +quality measure less than the product are rejected. For example, if the best corner has the +quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure +less than 15 are rejected. +@param minDistance Minimum possible Euclidean distance between the returned corners. +@param mask Region of interest. If the image is not empty (it needs to have the type +CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. +@param cornersQuality Output vector of quality measure of the detected corners. +@param blockSize Size of an average block for computing a derivative covariation matrix over each +pixel neighborhood. See cornerEigenValsAndVecs . +@param gradientSize Aperture parameter for the Sobel operator used for derivatives computation. +See cornerEigenValsAndVecs . +@param useHarrisDetector Parameter indicating whether to use a Harris detector (see #cornerHarris) +or #cornerMinEigenVal. +@param k Free parameter of the Harris detector. + */ +CV_EXPORTS CV_WRAP_AS(goodFeaturesToTrackWithQuality) void goodFeaturesToTrack( + InputArray image, OutputArray corners, + int maxCorners, double qualityLevel, double minDistance, + InputArray mask, OutputArray cornersQuality, int blockSize = 3, + int gradientSize = 3, bool useHarrisDetector = false, double k = 0.04); + +/** @example samples/cpp/tutorial_code/ImgTrans/houghlines.cpp +An example using the Hough line detector +![Sample input image](Hough_Lines_Tutorial_Original_Image.jpg) ![Output image](Hough_Lines_Tutorial_Result.jpg) +*/ + +/** @brief Finds lines in a binary image using the standard Hough transform. + +The function implements the standard or standard multi-scale Hough transform algorithm for line +detection. See for a good explanation of Hough +transform. + +@param image 8-bit, single-channel binary source image. The image may be modified by the function. +@param lines Output vector of lines. Each line is represented by a 2 or 3 element vector +\f$(\rho, \theta)\f$ or \f$(\rho, \theta, \textrm{votes})\f$, where \f$\rho\f$ is the distance from +the coordinate origin \f$(0,0)\f$ (top-left corner of the image), \f$\theta\f$ is the line rotation +angle in radians ( \f$0 \sim \textrm{vertical line}, \pi/2 \sim \textrm{horizontal line}\f$ ), and +\f$\textrm{votes}\f$ is the value of accumulator. +@param rho Distance resolution of the accumulator in pixels. +@param theta Angle resolution of the accumulator in radians. +@param threshold %Accumulator threshold parameter. Only those lines are returned that get enough +votes ( \f$>\texttt{threshold}\f$ ). +@param srn For the multi-scale Hough transform, it is a divisor for the distance resolution rho. +The coarse accumulator distance resolution is rho and the accurate accumulator resolution is +rho/srn. If both srn=0 and stn=0, the classical Hough transform is used. Otherwise, both these +parameters should be positive. +@param stn For the multi-scale Hough transform, it is a divisor for the distance resolution theta. +@param min_theta For standard and multi-scale Hough transform, minimum angle to check for lines. +Must fall between 0 and max_theta. +@param max_theta For standard and multi-scale Hough transform, an upper bound for the angle. +Must fall between min_theta and CV_PI. The actual maximum angle in the accumulator may be slightly +less than max_theta, depending on the parameters min_theta and theta. +@param use_edgeval True if you want to use weighted Hough transform. + */ +CV_EXPORTS_W void HoughLines( InputArray image, OutputArray lines, + double rho, double theta, int threshold, + double srn = 0, double stn = 0, + double min_theta = 0, double max_theta = CV_PI, + bool use_edgeval = false ); + +/** @brief Finds line segments in a binary image using the probabilistic Hough transform. + +The function implements the probabilistic Hough transform algorithm for line detection, described +in @cite Matas00 + +See the line detection example below: +@include snippets/imgproc_HoughLinesP.cpp +This is a sample picture the function parameters have been tuned for: + +![image](pics/building.jpg) + +And this is the output of the above program in case of the probabilistic Hough transform: + +![image](pics/houghp.png) + +@param image 8-bit, single-channel binary source image. The image may be modified by the function. +@param lines Output vector of lines. Each line is represented by a 4-element vector +\f$(x_1, y_1, x_2, y_2)\f$ , where \f$(x_1,y_1)\f$ and \f$(x_2, y_2)\f$ are the ending points of each detected +line segment. +@param rho Distance resolution of the accumulator in pixels. +@param theta Angle resolution of the accumulator in radians. +@param threshold %Accumulator threshold parameter. Only those lines are returned that get enough +votes ( \f$>\texttt{threshold}\f$ ). +@param minLineLength Minimum line length. Line segments shorter than that are rejected. +@param maxLineGap Maximum allowed gap between points on the same line to link them. + +@sa LineSegmentDetector + */ +CV_EXPORTS_W void HoughLinesP( InputArray image, OutputArray lines, + double rho, double theta, int threshold, + double minLineLength = 0, double maxLineGap = 0 ); + +/** @brief Finds lines in a set of points using the standard Hough transform. + +The function finds lines in a set of points using a modification of the Hough transform. +@include snippets/imgproc_HoughLinesPointSet.cpp +@param point Input vector of points. Each vector must be encoded as a Point vector \f$(x,y)\f$. Type must be CV_32FC2 or CV_32SC2. +@param lines Output vector of found lines. Each vector is encoded as a vector \f$(votes, rho, theta)\f$. +The larger the value of 'votes', the higher the reliability of the Hough line. +@param lines_max Max count of Hough lines. +@param threshold %Accumulator threshold parameter. Only those lines are returned that get enough +votes ( \f$>\texttt{threshold}\f$ ). +@param min_rho Minimum value for \f$\rho\f$ for the accumulator (Note: \f$\rho\f$ can be negative. The absolute value \f$|\rho|\f$ is the distance of a line to the origin.). +@param max_rho Maximum value for \f$\rho\f$ for the accumulator. +@param rho_step Distance resolution of the accumulator. +@param min_theta Minimum angle value of the accumulator in radians. +@param max_theta Upper bound for the angle value of the accumulator in radians. The actual maximum +angle may be slightly less than max_theta, depending on the parameters min_theta and theta_step. +@param theta_step Angle resolution of the accumulator in radians. + */ +CV_EXPORTS_W void HoughLinesPointSet( InputArray point, OutputArray lines, int lines_max, int threshold, + double min_rho, double max_rho, double rho_step, + double min_theta, double max_theta, double theta_step ); + +/** @example samples/cpp/tutorial_code/ImgTrans/houghcircles.cpp +An example using the Hough circle detector +*/ + +/** @brief Finds circles in a grayscale image using the Hough transform. + +The function finds circles in a grayscale image using a modification of the Hough transform. + +Example: : +@include snippets/imgproc_HoughLinesCircles.cpp + +@note Usually the function detects the centers of circles well. However, it may fail to find correct +radii. You can assist to the function by specifying the radius range ( minRadius and maxRadius ) if +you know it. Or, in the case of #HOUGH_GRADIENT method you may set maxRadius to a negative number +to return centers only without radius search, and find the correct radius using an additional procedure. + +It also helps to smooth image a bit unless it's already soft. For example, +GaussianBlur() with 7x7 kernel and 1.5x1.5 sigma or similar blurring may help. + +@param image 8-bit, single-channel, grayscale input image. +@param circles Output vector of found circles. Each vector is encoded as 3 or 4 element +floating-point vector \f$(x, y, radius)\f$ or \f$(x, y, radius, votes)\f$ . +@param method Detection method, see #HoughModes. The available methods are #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT. +@param dp Inverse ratio of the accumulator resolution to the image resolution. For example, if +dp=1 , the accumulator has the same resolution as the input image. If dp=2 , the accumulator has +half as big width and height. For #HOUGH_GRADIENT_ALT the recommended value is dp=1.5, +unless some small very circles need to be detected. +@param minDist Minimum distance between the centers of the detected circles. If the parameter is +too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is +too large, some circles may be missed. +@param param1 First method-specific parameter. In case of #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT, +it is the higher threshold of the two passed to the Canny edge detector (the lower one is twice smaller). +Note that #HOUGH_GRADIENT_ALT uses #Scharr algorithm to compute image derivatives, so the threshold value +should normally be higher, such as 300 or normally exposed and contrasty images. +@param param2 Second method-specific parameter. In case of #HOUGH_GRADIENT, it is the +accumulator threshold for the circle centers at the detection stage. The smaller it is, the more +false circles may be detected. Circles, corresponding to the larger accumulator values, will be +returned first. In the case of #HOUGH_GRADIENT_ALT algorithm, this is the circle "perfectness" measure. +The closer it to 1, the better shaped circles algorithm selects. In most cases 0.9 should be fine. +If you want get better detection of small circles, you may decrease it to 0.85, 0.8 or even less. +But then also try to limit the search range [minRadius, maxRadius] to avoid many false circles. +@param minRadius Minimum circle radius. +@param maxRadius Maximum circle radius. If <= 0, uses the maximum image dimension. If < 0, #HOUGH_GRADIENT returns +centers without finding the radius. #HOUGH_GRADIENT_ALT always computes circle radiuses. + +@sa fitEllipse, minEnclosingCircle + */ +CV_EXPORTS_W void HoughCircles( InputArray image, OutputArray circles, + int method, double dp, double minDist, + double param1 = 100, double param2 = 100, + int minRadius = 0, int maxRadius = 0 ); + +//! @} imgproc_feature + +//! @addtogroup imgproc_filter +//! @{ + +/** @example samples/cpp/tutorial_code/ImgProc/Morphology_2.cpp +Advanced morphology Transformations sample code +![Sample screenshot](Morphology_2_Tutorial_Result.jpg) +Check @ref tutorial_opening_closing_hats "the corresponding tutorial" for more details +*/ + +/** @brief Erodes an image by using a specific structuring element. + +The function erodes the source image using the specified structuring element that determines the +shape of a pixel neighborhood over which the minimum is taken: + +\f[\texttt{dst} (x,y) = \min _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f] + +The function supports the in-place mode. Erosion can be applied several ( iterations ) times. In +case of multi-channel images, each channel is processed independently. + +@param src input image; the number of channels can be arbitrary, but the depth should be one of +CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. +@param dst output image of the same size and type as src. +@param kernel structuring element used for erosion; if `element=Mat()`, a `3 x 3` rectangular +structuring element is used. Kernel can be created using #getStructuringElement. +@param anchor position of the anchor within the element; default value (-1, -1) means that the +anchor is at the element center. +@param iterations number of times erosion is applied. +@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. +@param borderValue border value in case of a constant border +@sa dilate, morphologyEx, getStructuringElement + */ +CV_EXPORTS_W void erode( InputArray src, OutputArray dst, InputArray kernel, + Point anchor = Point(-1,-1), int iterations = 1, + int borderType = BORDER_CONSTANT, + const Scalar& borderValue = morphologyDefaultBorderValue() ); + +/** @example samples/cpp/tutorial_code/ImgProc/Morphology_1.cpp +Erosion and Dilation sample code +![Sample Screenshot-Erosion](Morphology_1_Tutorial_Erosion_Result.jpg)![Sample Screenshot-Dilation](Morphology_1_Tutorial_Dilation_Result.jpg) +Check @ref tutorial_erosion_dilatation "the corresponding tutorial" for more details +*/ + +/** @brief Dilates an image by using a specific structuring element. + +The function dilates the source image using the specified structuring element that determines the +shape of a pixel neighborhood over which the maximum is taken: +\f[\texttt{dst} (x,y) = \max _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f] + +The function supports the in-place mode. Dilation can be applied several ( iterations ) times. In +case of multi-channel images, each channel is processed independently. + +@param src input image; the number of channels can be arbitrary, but the depth should be one of +CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. +@param dst output image of the same size and type as src. +@param kernel structuring element used for dilation; if element=Mat(), a 3 x 3 rectangular +structuring element is used. Kernel can be created using #getStructuringElement +@param anchor position of the anchor within the element; default value (-1, -1) means that the +anchor is at the element center. +@param iterations number of times dilation is applied. +@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not suported. +@param borderValue border value in case of a constant border +@sa erode, morphologyEx, getStructuringElement + */ +CV_EXPORTS_W void dilate( InputArray src, OutputArray dst, InputArray kernel, + Point anchor = Point(-1,-1), int iterations = 1, + int borderType = BORDER_CONSTANT, + const Scalar& borderValue = morphologyDefaultBorderValue() ); + +/** @brief Performs advanced morphological transformations. + +The function cv::morphologyEx can perform advanced morphological transformations using an erosion and dilation as +basic operations. + +Any of the operations can be done in-place. In case of multi-channel images, each channel is +processed independently. + +@param src Source image. The number of channels can be arbitrary. The depth should be one of +CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. +@param dst Destination image of the same size and type as source image. +@param op Type of a morphological operation, see #MorphTypes +@param kernel Structuring element. It can be created using #getStructuringElement. +@param anchor Anchor position with the kernel. Negative values mean that the anchor is at the +kernel center. +@param iterations Number of times erosion and dilation are applied. +@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. +@param borderValue Border value in case of a constant border. The default value has a special +meaning. +@sa dilate, erode, getStructuringElement +@note The number of iterations is the number of times erosion or dilatation operation will be applied. +For instance, an opening operation (#MORPH_OPEN) with two iterations is equivalent to apply +successively: erode -> erode -> dilate -> dilate (and not erode -> dilate -> erode -> dilate). + */ +CV_EXPORTS_W void morphologyEx( InputArray src, OutputArray dst, + int op, InputArray kernel, + Point anchor = Point(-1,-1), int iterations = 1, + int borderType = BORDER_CONSTANT, + const Scalar& borderValue = morphologyDefaultBorderValue() ); + +//! @} imgproc_filter + +//! @addtogroup imgproc_transform +//! @{ + +/** @brief Resizes an image. + +The function resize resizes the image src down to or up to the specified size. Note that the +initial dst type or size are not taken into account. Instead, the size and type are derived from +the `src`,`dsize`,`fx`, and `fy`. If you want to resize src so that it fits the pre-created dst, +you may call the function as follows: +@code + // explicitly specify dsize=dst.size(); fx and fy will be computed from that. + resize(src, dst, dst.size(), 0, 0, interpolation); +@endcode +If you want to decimate the image by factor of 2 in each direction, you can call the function this +way: +@code + // specify fx and fy and let the function compute the destination image size. + resize(src, dst, Size(), 0.5, 0.5, interpolation); +@endcode +To shrink an image, it will generally look best with #INTER_AREA interpolation, whereas to +enlarge an image, it will generally look best with #INTER_CUBIC (slow) or #INTER_LINEAR +(faster but still looks OK). + +@param src input image. +@param dst output image; it has the size dsize (when it is non-zero) or the size computed from +src.size(), fx, and fy; the type of dst is the same as of src. +@param dsize output image size; if it equals zero (`None` in Python), it is computed as: + \f[\texttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}\f] + Either dsize or both fx and fy must be non-zero. +@param fx scale factor along the horizontal axis; when it equals 0, it is computed as +\f[\texttt{(double)dsize.width/src.cols}\f] +@param fy scale factor along the vertical axis; when it equals 0, it is computed as +\f[\texttt{(double)dsize.height/src.rows}\f] +@param interpolation interpolation method, see #InterpolationFlags + +@sa warpAffine, warpPerspective, remap + */ +CV_EXPORTS_W void resize( InputArray src, OutputArray dst, + Size dsize, double fx = 0, double fy = 0, + int interpolation = INTER_LINEAR ); + +/** @brief Applies an affine transformation to an image. + +The function warpAffine transforms the source image using the specified matrix: + +\f[\texttt{dst} (x,y) = \texttt{src} ( \texttt{M} _{11} x + \texttt{M} _{12} y + \texttt{M} _{13}, \texttt{M} _{21} x + \texttt{M} _{22} y + \texttt{M} _{23})\f] + +when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted +with #invertAffineTransform and then put in the formula above instead of M. The function cannot +operate in-place. + +@param src input image. +@param dst output image that has the size dsize and the same type as src . +@param M \f$2\times 3\f$ transformation matrix. +@param dsize size of the output image. +@param flags combination of interpolation methods (see #InterpolationFlags) and the optional +flag #WARP_INVERSE_MAP that means that M is the inverse transformation ( +\f$\texttt{dst}\rightarrow\texttt{src}\f$ ). +@param borderMode pixel extrapolation method (see #BorderTypes); when +borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image corresponding to +the "outliers" in the source image are not modified by the function. +@param borderValue value used in case of a constant border; by default, it is 0. + +@sa warpPerspective, resize, remap, getRectSubPix, transform + */ +CV_EXPORTS_W void warpAffine( InputArray src, OutputArray dst, + InputArray M, Size dsize, + int flags = INTER_LINEAR, + int borderMode = BORDER_CONSTANT, + const Scalar& borderValue = Scalar()); + +/** @example samples/cpp/warpPerspective_demo.cpp +An example program shows using cv::getPerspectiveTransform and cv::warpPerspective for image warping +*/ + +/** @brief Applies a perspective transformation to an image. + +The function warpPerspective transforms the source image using the specified matrix: + +\f[\texttt{dst} (x,y) = \texttt{src} \left ( \frac{M_{11} x + M_{12} y + M_{13}}{M_{31} x + M_{32} y + M_{33}} , + \frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}} \right )\f] + +when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted with invert +and then put in the formula above instead of M. The function cannot operate in-place. + +@param src input image. +@param dst output image that has the size dsize and the same type as src . +@param M \f$3\times 3\f$ transformation matrix. +@param dsize size of the output image. +@param flags combination of interpolation methods (#INTER_LINEAR or #INTER_NEAREST) and the +optional flag #WARP_INVERSE_MAP, that sets M as the inverse transformation ( +\f$\texttt{dst}\rightarrow\texttt{src}\f$ ). +@param borderMode pixel extrapolation method (#BORDER_CONSTANT or #BORDER_REPLICATE). +@param borderValue value used in case of a constant border; by default, it equals 0. + +@sa warpAffine, resize, remap, getRectSubPix, perspectiveTransform + */ +CV_EXPORTS_W void warpPerspective( InputArray src, OutputArray dst, + InputArray M, Size dsize, + int flags = INTER_LINEAR, + int borderMode = BORDER_CONSTANT, + const Scalar& borderValue = Scalar()); + +/** @brief Applies a generic geometrical transformation to an image. + +The function remap transforms the source image using the specified map: + +\f[\texttt{dst} (x,y) = \texttt{src} (map_x(x,y),map_y(x,y))\f] + +with the WARP_RELATIVE_MAP flag : + +\f[\texttt{dst} (x,y) = \texttt{src} (x+map_x(x,y),y+map_y(x,y))\f] + +where values of pixels with non-integer coordinates are computed using one of available +interpolation methods. \f$map_x\f$ and \f$map_y\f$ can be encoded as separate floating-point maps +in \f$map_1\f$ and \f$map_2\f$ respectively, or interleaved floating-point maps of \f$(x,y)\f$ in +\f$map_1\f$, or fixed-point maps created by using #convertMaps. The reason you might want to +convert from floating to fixed-point representations of a map is that they can yield much faster +(\~2x) remapping operations. In the converted case, \f$map_1\f$ contains pairs (cvFloor(x), +cvFloor(y)) and \f$map_2\f$ contains indices in a table of interpolation coefficients. + +This function cannot operate in-place. + +@param src Source image. +@param dst Destination image. It has the same size as map1 and the same type as src . +@param map1 The first map of either (x,y) points or just x values having the type CV_16SC2 , +CV_32FC1, or CV_32FC2. See #convertMaps for details on converting a floating point +representation to fixed-point for speed. +@param map2 The second map of y values having the type CV_16UC1, CV_32FC1, or none (empty map +if map1 is (x,y) points), respectively. +@param interpolation Interpolation method (see #InterpolationFlags). The methods #INTER_AREA +#INTER_LINEAR_EXACT and #INTER_NEAREST_EXACT are not supported by this function. +The extra flag WARP_RELATIVE_MAP can be ORed to the interpolation method +(e.g. INTER_LINEAR | WARP_RELATIVE_MAP) +@param borderMode Pixel extrapolation method (see #BorderTypes). When +borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image that +corresponds to the "outliers" in the source image are not modified by the function. +@param borderValue Value used in case of a constant border. By default, it is 0. +@note +Due to current implementation limitations the size of an input and output images should be less than 32767x32767. + */ +CV_EXPORTS_W void remap( InputArray src, OutputArray dst, + InputArray map1, InputArray map2, + int interpolation, int borderMode = BORDER_CONSTANT, + const Scalar& borderValue = Scalar()); + +/** @brief Converts image transformation maps from one representation to another. + +The function converts a pair of maps for remap from one representation to another. The following +options ( (map1.type(), map2.type()) \f$\rightarrow\f$ (dstmap1.type(), dstmap2.type()) ) are +supported: + +- \f$\texttt{(CV_32FC1, CV_32FC1)} \rightarrow \texttt{(CV_16SC2, CV_16UC1)}\f$. This is the +most frequently used conversion operation, in which the original floating-point maps (see #remap) +are converted to a more compact and much faster fixed-point representation. The first output array +contains the rounded coordinates and the second array (created only when nninterpolation=false ) +contains indices in the interpolation tables. + +- \f$\texttt{(CV_32FC2)} \rightarrow \texttt{(CV_16SC2, CV_16UC1)}\f$. The same as above but +the original maps are stored in one 2-channel matrix. + +- Reverse conversion. Obviously, the reconstructed floating-point maps will not be exactly the same +as the originals. + +@param map1 The first input map of type CV_16SC2, CV_32FC1, or CV_32FC2 . +@param map2 The second input map of type CV_16UC1, CV_32FC1, or none (empty matrix), +respectively. +@param dstmap1 The first output map that has the type dstmap1type and the same size as src . +@param dstmap2 The second output map. +@param dstmap1type Type of the first output map that should be CV_16SC2, CV_32FC1, or +CV_32FC2 . +@param nninterpolation Flag indicating whether the fixed-point maps are used for the +nearest-neighbor or for a more complex interpolation. + +@sa remap, undistort, initUndistortRectifyMap + */ +CV_EXPORTS_W void convertMaps( InputArray map1, InputArray map2, + OutputArray dstmap1, OutputArray dstmap2, + int dstmap1type, bool nninterpolation = false ); + +/** @brief Calculates an affine matrix of 2D rotation. + +The function calculates the following matrix: + +\f[\begin{bmatrix} \alpha & \beta & (1- \alpha ) \cdot \texttt{center.x} - \beta \cdot \texttt{center.y} \\ - \beta & \alpha & \beta \cdot \texttt{center.x} + (1- \alpha ) \cdot \texttt{center.y} \end{bmatrix}\f] + +where + +\f[\begin{array}{l} \alpha = \texttt{scale} \cdot \cos \texttt{angle} , \\ \beta = \texttt{scale} \cdot \sin \texttt{angle} \end{array}\f] + +The transformation maps the rotation center to itself. If this is not the target, adjust the shift. + +@param center Center of the rotation in the source image. +@param angle Rotation angle in degrees. Positive values mean counter-clockwise rotation (the +coordinate origin is assumed to be the top-left corner). +@param scale Isotropic scale factor. + +@sa getAffineTransform, warpAffine, transform + */ +CV_EXPORTS_W Mat getRotationMatrix2D(Point2f center, double angle, double scale); + +/** @sa getRotationMatrix2D */ +CV_EXPORTS Matx23d getRotationMatrix2D_(Point2f center, double angle, double scale); + +inline +Mat getRotationMatrix2D(Point2f center, double angle, double scale) +{ + return Mat(getRotationMatrix2D_(center, angle, scale), true); +} + +/** @brief Calculates an affine transform from three pairs of the corresponding points. + +The function calculates the \f$2 \times 3\f$ matrix of an affine transform so that: + +\f[\begin{bmatrix} x'_i \\ y'_i \end{bmatrix} = \texttt{map_matrix} \cdot \begin{bmatrix} x_i \\ y_i \\ 1 \end{bmatrix}\f] + +where + +\f[dst(i)=(x'_i,y'_i), src(i)=(x_i, y_i), i=0,1,2\f] + +@param src Coordinates of triangle vertices in the source image. +@param dst Coordinates of the corresponding triangle vertices in the destination image. + +@sa warpAffine, transform + */ +CV_EXPORTS Mat getAffineTransform( const Point2f src[], const Point2f dst[] ); + +/** @brief Inverts an affine transformation. + +The function computes an inverse affine transformation represented by \f$2 \times 3\f$ matrix M: + +\f[\begin{bmatrix} a_{11} & a_{12} & b_1 \\ a_{21} & a_{22} & b_2 \end{bmatrix}\f] + +The result is also a \f$2 \times 3\f$ matrix of the same type as M. + +@param M Original affine transformation. +@param iM Output reverse affine transformation. + */ +CV_EXPORTS_W void invertAffineTransform( InputArray M, OutputArray iM ); + +/** @brief Calculates a perspective transform from four pairs of the corresponding points. + +The function calculates the \f$3 \times 3\f$ matrix of a perspective transform so that: + +\f[\begin{bmatrix} t_i x'_i \\ t_i y'_i \\ t_i \end{bmatrix} = \texttt{map_matrix} \cdot \begin{bmatrix} x_i \\ y_i \\ 1 \end{bmatrix}\f] + +where + +\f[dst(i)=(x'_i,y'_i), src(i)=(x_i, y_i), i=0,1,2,3\f] + +@param src Coordinates of quadrangle vertices in the source image. +@param dst Coordinates of the corresponding quadrangle vertices in the destination image. +@param solveMethod method passed to cv::solve (#DecompTypes) + +@sa findHomography, warpPerspective, perspectiveTransform + */ +CV_EXPORTS_W Mat getPerspectiveTransform(InputArray src, InputArray dst, int solveMethod = DECOMP_LU); + +/** @overload */ +CV_EXPORTS Mat getPerspectiveTransform(const Point2f src[], const Point2f dst[], int solveMethod = DECOMP_LU); + + +CV_EXPORTS_W Mat getAffineTransform( InputArray src, InputArray dst ); + +/** @brief Retrieves a pixel rectangle from an image with sub-pixel accuracy. + +The function getRectSubPix extracts pixels from src: + +\f[patch(x, y) = src(x + \texttt{center.x} - ( \texttt{dst.cols} -1)*0.5, y + \texttt{center.y} - ( \texttt{dst.rows} -1)*0.5)\f] + +where the values of the pixels at non-integer coordinates are retrieved using bilinear +interpolation. Every channel of multi-channel images is processed independently. Also +the image should be a single channel or three channel image. While the center of the +rectangle must be inside the image, parts of the rectangle may be outside. + +@param image Source image. +@param patchSize Size of the extracted patch. +@param center Floating point coordinates of the center of the extracted rectangle within the +source image. The center must be inside the image. +@param patch Extracted patch that has the size patchSize and the same number of channels as src . +@param patchType Depth of the extracted pixels. By default, they have the same depth as src . + +@sa warpAffine, warpPerspective + */ +CV_EXPORTS_W void getRectSubPix( InputArray image, Size patchSize, + Point2f center, OutputArray patch, int patchType = -1 ); + +/** @example samples/cpp/polar_transforms.cpp +An example using the cv::linearPolar and cv::logPolar operations +*/ + +/** @brief Remaps an image to semilog-polar coordinates space. + +@deprecated This function produces same result as cv::warpPolar(src, dst, src.size(), center, maxRadius, flags+WARP_POLAR_LOG); + +@internal +Transform the source image using the following transformation (See @ref polar_remaps_reference_image "Polar remaps reference image d)"): +\f[\begin{array}{l} + dst( \rho , \phi ) = src(x,y) \\ + dst.size() \leftarrow src.size() +\end{array}\f] + +where +\f[\begin{array}{l} + I = (dx,dy) = (x - center.x,y - center.y) \\ + \rho = M \cdot log_e(\texttt{magnitude} (I)) ,\\ + \phi = Kangle \cdot \texttt{angle} (I) \\ +\end{array}\f] + +and +\f[\begin{array}{l} + M = src.cols / log_e(maxRadius) \\ + Kangle = src.rows / 2\Pi \\ +\end{array}\f] + +The function emulates the human "foveal" vision and can be used for fast scale and +rotation-invariant template matching, for object tracking and so forth. +@param src Source image +@param dst Destination image. It will have same size and type as src. +@param center The transformation center; where the output precision is maximal +@param M Magnitude scale parameter. It determines the radius of the bounding circle to transform too. +@param flags A combination of interpolation methods, see #InterpolationFlags + +@note +- The function can not operate in-place. +- To calculate magnitude and angle in degrees #cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees. + +@sa cv::linearPolar +@endinternal +*/ +CV_EXPORTS_W void logPolar( InputArray src, OutputArray dst, + Point2f center, double M, int flags ); + +/** @brief Remaps an image to polar coordinates space. + +@deprecated This function produces same result as cv::warpPolar(src, dst, src.size(), center, maxRadius, flags) + +@internal +Transform the source image using the following transformation (See @ref polar_remaps_reference_image "Polar remaps reference image c)"): +\f[\begin{array}{l} + dst( \rho , \phi ) = src(x,y) \\ + dst.size() \leftarrow src.size() +\end{array}\f] + +where +\f[\begin{array}{l} + I = (dx,dy) = (x - center.x,y - center.y) \\ + \rho = Kmag \cdot \texttt{magnitude} (I) ,\\ + \phi = angle \cdot \texttt{angle} (I) +\end{array}\f] + +and +\f[\begin{array}{l} + Kx = src.cols / maxRadius \\ + Ky = src.rows / 2\Pi +\end{array}\f] + + +@param src Source image +@param dst Destination image. It will have same size and type as src. +@param center The transformation center; +@param maxRadius The radius of the bounding circle to transform. It determines the inverse magnitude scale parameter too. +@param flags A combination of interpolation methods, see #InterpolationFlags + +@note +- The function can not operate in-place. +- To calculate magnitude and angle in degrees #cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees. + +@sa cv::logPolar +@endinternal +*/ +CV_EXPORTS_W void linearPolar( InputArray src, OutputArray dst, + Point2f center, double maxRadius, int flags ); + + +/** \brief Remaps an image to polar or semilog-polar coordinates space + +@anchor polar_remaps_reference_image +![Polar remaps reference](pics/polar_remap_doc.png) + +Transform the source image using the following transformation: +\f[ +dst(\rho , \phi ) = src(x,y) +\f] + +where +\f[ +\begin{array}{l} +\vec{I} = (x - center.x, \;y - center.y) \\ +\phi = Kangle \cdot \texttt{angle} (\vec{I}) \\ +\rho = \left\{\begin{matrix} +Klin \cdot \texttt{magnitude} (\vec{I}) & default \\ +Klog \cdot log_e(\texttt{magnitude} (\vec{I})) & if \; semilog \\ +\end{matrix}\right. +\end{array} +\f] + +and +\f[ +\begin{array}{l} +Kangle = dsize.height / 2\Pi \\ +Klin = dsize.width / maxRadius \\ +Klog = dsize.width / log_e(maxRadius) \\ +\end{array} +\f] + + +\par Linear vs semilog mapping + +Polar mapping can be linear or semi-log. Add one of #WarpPolarMode to `flags` to specify the polar mapping mode. + +Linear is the default mode. + +The semilog mapping emulates the human "foveal" vision that permit very high acuity on the line of sight (central vision) +in contrast to peripheral vision where acuity is minor. + +\par Option on `dsize`: + +- if both values in `dsize <=0 ` (default), +the destination image will have (almost) same area of source bounding circle: +\f[\begin{array}{l} +dsize.area \leftarrow (maxRadius^2 \cdot \Pi) \\ +dsize.width = \texttt{cvRound}(maxRadius) \\ +dsize.height = \texttt{cvRound}(maxRadius \cdot \Pi) \\ +\end{array}\f] + + +- if only `dsize.height <= 0`, +the destination image area will be proportional to the bounding circle area but scaled by `Kx * Kx`: +\f[\begin{array}{l} +dsize.height = \texttt{cvRound}(dsize.width \cdot \Pi) \\ +\end{array} +\f] + +- if both values in `dsize > 0 `, +the destination image will have the given size therefore the area of the bounding circle will be scaled to `dsize`. + + +\par Reverse mapping + +You can get reverse mapping adding #WARP_INVERSE_MAP to `flags` +\snippet polar_transforms.cpp InverseMap + +In addiction, to calculate the original coordinate from a polar mapped coordinate \f$(rho, phi)->(x, y)\f$: +\snippet polar_transforms.cpp InverseCoordinate + +@param src Source image. +@param dst Destination image. It will have same type as src. +@param dsize The destination image size (see description for valid options). +@param center The transformation center. +@param maxRadius The radius of the bounding circle to transform. It determines the inverse magnitude scale parameter too. +@param flags A combination of interpolation methods, #InterpolationFlags + #WarpPolarMode. + - Add #WARP_POLAR_LINEAR to select linear polar mapping (default) + - Add #WARP_POLAR_LOG to select semilog polar mapping + - Add #WARP_INVERSE_MAP for reverse mapping. +@note +- The function can not operate in-place. +- To calculate magnitude and angle in degrees #cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees. +- This function uses #remap. Due to current implementation limitations the size of an input and output images should be less than 32767x32767. + +@sa cv::remap +*/ +CV_EXPORTS_W void warpPolar(InputArray src, OutputArray dst, Size dsize, + Point2f center, double maxRadius, int flags); + + +//! @} imgproc_transform + +//! @addtogroup imgproc_misc +//! @{ + +/** @brief Calculates the integral of an image. + +The function calculates one or more integral images for the source image as follows: + +\f[\texttt{sum} (X,Y) = \sum _{x + +Calculates the cross-power spectrum of two supplied source arrays. The arrays are padded if needed +with getOptimalDFTSize. + +The function performs the following equations: +- First it applies a Hanning window (see ) to each +image to remove possible edge effects. This window is cached until the array size changes to speed +up processing time. +- Next it computes the forward DFTs of each source array: +\f[\mathbf{G}_a = \mathcal{F}\{src_1\}, \; \mathbf{G}_b = \mathcal{F}\{src_2\}\f] +where \f$\mathcal{F}\f$ is the forward DFT. +- It then computes the cross-power spectrum of each frequency domain array: +\f[R = \frac{ \mathbf{G}_a \mathbf{G}_b^*}{|\mathbf{G}_a \mathbf{G}_b^*|}\f] +- Next the cross-correlation is converted back into the time domain via the inverse DFT: +\f[r = \mathcal{F}^{-1}\{R\}\f] +- Finally, it computes the peak location and computes a 5x5 weighted centroid around the peak to +achieve sub-pixel accuracy. +\f[(\Delta x, \Delta y) = \texttt{weightedCentroid} \{\arg \max_{(x, y)}\{r\}\}\f] +- If non-zero, the response parameter is computed as the sum of the elements of r within the 5x5 +centroid around the peak location. It is normalized to a maximum of 1 (meaning there is a single +peak) and will be smaller when there are multiple peaks. + +@param src1 Source floating point array (CV_32FC1 or CV_64FC1) +@param src2 Source floating point array (CV_32FC1 or CV_64FC1) +@param window Floating point array with windowing coefficients to reduce edge effects (optional). +@param response Signal power within the 5x5 centroid around the peak, between 0 and 1 (optional). +@returns detected phase shift (sub-pixel) between the two arrays. + +@sa dft, getOptimalDFTSize, idft, mulSpectrums createHanningWindow + */ +CV_EXPORTS_W Point2d phaseCorrelate(InputArray src1, InputArray src2, + InputArray window = noArray(), CV_OUT double* response = 0); + +/** @brief This function computes a Hanning window coefficients in two dimensions. + +See (http://en.wikipedia.org/wiki/Hann_function) and (http://en.wikipedia.org/wiki/Window_function) +for more information. + +An example is shown below: +@code + // create hanning window of size 100x100 and type CV_32F + Mat hann; + createHanningWindow(hann, Size(100, 100), CV_32F); +@endcode +@param dst Destination array to place Hann coefficients in +@param winSize The window size specifications (both width and height must be > 1) +@param type Created array type + */ +CV_EXPORTS_W void createHanningWindow(OutputArray dst, Size winSize, int type); + +/** @brief Performs the per-element division of the first Fourier spectrum by the second Fourier spectrum. + +The function cv::divSpectrums performs the per-element division of the first array by the second array. +The arrays are CCS-packed or complex matrices that are results of a real or complex Fourier transform. + +@param a first input array. +@param b second input array of the same size and type as src1 . +@param c output array of the same size and type as src1 . +@param flags operation flags; currently, the only supported flag is cv::DFT_ROWS, which indicates that +each row of src1 and src2 is an independent 1D Fourier spectrum. If you do not want to use this flag, then simply add a `0` as value. +@param conjB optional flag that conjugates the second input array before the multiplication (true) +or not (false). +*/ +CV_EXPORTS_W void divSpectrums(InputArray a, InputArray b, OutputArray c, + int flags, bool conjB = false); + +//! @} imgproc_motion + +//! @addtogroup imgproc_misc +//! @{ + +/** @brief Applies a fixed-level threshold to each array element. + +The function applies fixed-level thresholding to a multiple-channel array. The function is typically +used to get a bi-level (binary) image out of a grayscale image ( #compare could be also used for +this purpose) or for removing a noise, that is, filtering out pixels with too small or too large +values. There are several types of thresholding supported by the function. They are determined by +type parameter. + +Also, the special values #THRESH_OTSU or #THRESH_TRIANGLE may be combined with one of the +above values. In these cases, the function determines the optimal threshold value using the Otsu's +or Triangle algorithm and uses it instead of the specified thresh. + +@note Currently, the Otsu's and Triangle methods are implemented only for 8-bit single-channel images. + +@param src input array (multiple-channel, 8-bit or 32-bit floating point). +@param dst output array of the same size and type and the same number of channels as src. +@param thresh threshold value. +@param maxval maximum value to use with the #THRESH_BINARY and #THRESH_BINARY_INV thresholding +types. +@param type thresholding type (see #ThresholdTypes). +@return the computed threshold value if Otsu's or Triangle methods used. + +@sa adaptiveThreshold, findContours, compare, min, max + */ +CV_EXPORTS_W double threshold( InputArray src, OutputArray dst, + double thresh, double maxval, int type ); + + +/** @brief Applies an adaptive threshold to an array. + +The function transforms a grayscale image to a binary image according to the formulae: +- **THRESH_BINARY** + \f[dst(x,y) = \fork{\texttt{maxValue}}{if \(src(x,y) > T(x,y)\)}{0}{otherwise}\f] +- **THRESH_BINARY_INV** + \f[dst(x,y) = \fork{0}{if \(src(x,y) > T(x,y)\)}{\texttt{maxValue}}{otherwise}\f] +where \f$T(x,y)\f$ is a threshold calculated individually for each pixel (see adaptiveMethod parameter). + +The function can process the image in-place. + +@param src Source 8-bit single-channel image. +@param dst Destination image of the same size and the same type as src. +@param maxValue Non-zero value assigned to the pixels for which the condition is satisfied +@param adaptiveMethod Adaptive thresholding algorithm to use, see #AdaptiveThresholdTypes. +The #BORDER_REPLICATE | #BORDER_ISOLATED is used to process boundaries. +@param thresholdType Thresholding type that must be either #THRESH_BINARY or #THRESH_BINARY_INV, +see #ThresholdTypes. +@param blockSize Size of a pixel neighborhood that is used to calculate a threshold value for the +pixel: 3, 5, 7, and so on. +@param C Constant subtracted from the mean or weighted mean (see the details below). Normally, it +is positive but may be zero or negative as well. + +@sa threshold, blur, GaussianBlur + */ +CV_EXPORTS_W void adaptiveThreshold( InputArray src, OutputArray dst, + double maxValue, int adaptiveMethod, + int thresholdType, int blockSize, double C ); + +//! @} imgproc_misc + +//! @addtogroup imgproc_filter +//! @{ + +/** @example samples/cpp/tutorial_code/ImgProc/Pyramids/Pyramids.cpp +An example using pyrDown and pyrUp functions +*/ + +/** @brief Blurs an image and downsamples it. + +By default, size of the output image is computed as `Size((src.cols+1)/2, (src.rows+1)/2)`, but in +any case, the following conditions should be satisfied: + +\f[\begin{array}{l} | \texttt{dstsize.width} *2-src.cols| \leq 2 \\ | \texttt{dstsize.height} *2-src.rows| \leq 2 \end{array}\f] + +The function performs the downsampling step of the Gaussian pyramid construction. First, it +convolves the source image with the kernel: + +\f[\frac{1}{256} \begin{bmatrix} 1 & 4 & 6 & 4 & 1 \\ 4 & 16 & 24 & 16 & 4 \\ 6 & 24 & 36 & 24 & 6 \\ 4 & 16 & 24 & 16 & 4 \\ 1 & 4 & 6 & 4 & 1 \end{bmatrix}\f] + +Then, it downsamples the image by rejecting even rows and columns. + +@param src input image. +@param dst output image; it has the specified size and the same type as src. +@param dstsize size of the output image. +@param borderType Pixel extrapolation method, see #BorderTypes (#BORDER_CONSTANT isn't supported) + */ +CV_EXPORTS_W void pyrDown( InputArray src, OutputArray dst, + const Size& dstsize = Size(), int borderType = BORDER_DEFAULT ); + +/** @brief Upsamples an image and then blurs it. + +By default, size of the output image is computed as `Size(src.cols\*2, (src.rows\*2)`, but in any +case, the following conditions should be satisfied: + +\f[\begin{array}{l} | \texttt{dstsize.width} -src.cols*2| \leq ( \texttt{dstsize.width} \mod 2) \\ | \texttt{dstsize.height} -src.rows*2| \leq ( \texttt{dstsize.height} \mod 2) \end{array}\f] + +The function performs the upsampling step of the Gaussian pyramid construction, though it can +actually be used to construct the Laplacian pyramid. First, it upsamples the source image by +injecting even zero rows and columns and then convolves the result with the same kernel as in +pyrDown multiplied by 4. + +@param src input image. +@param dst output image. It has the specified size and the same type as src . +@param dstsize size of the output image. +@param borderType Pixel extrapolation method, see #BorderTypes (only #BORDER_DEFAULT is supported) + */ +CV_EXPORTS_W void pyrUp( InputArray src, OutputArray dst, + const Size& dstsize = Size(), int borderType = BORDER_DEFAULT ); + +/** @brief Constructs the Gaussian pyramid for an image. + +The function constructs a vector of images and builds the Gaussian pyramid by recursively applying +pyrDown to the previously built pyramid layers, starting from `dst[0]==src`. + +@param src Source image. Check pyrDown for the list of supported types. +@param dst Destination vector of maxlevel+1 images of the same type as src. dst[0] will be the +same as src. dst[1] is the next pyramid layer, a smoothed and down-sized src, and so on. +@param maxlevel 0-based index of the last (the smallest) pyramid layer. It must be non-negative. +@param borderType Pixel extrapolation method, see #BorderTypes (#BORDER_CONSTANT isn't supported) + */ +CV_EXPORTS void buildPyramid( InputArray src, OutputArrayOfArrays dst, + int maxlevel, int borderType = BORDER_DEFAULT ); + +//! @} imgproc_filter + +//! @addtogroup imgproc_hist +//! @{ + +/** @example samples/cpp/demhist.cpp +An example for creating histograms of an image +*/ + +/** @brief Calculates a histogram of a set of arrays. + +The function cv::calcHist calculates the histogram of one or more arrays. The elements of a tuple used +to increment a histogram bin are taken from the corresponding input arrays at the same location. The +sample below shows how to compute a 2D Hue-Saturation histogram for a color image. : +@include snippets/imgproc_calcHist.cpp + +@param images Source arrays. They all should have the same depth, CV_8U, CV_16U or CV_32F , and the same +size. Each of them can have an arbitrary number of channels. +@param nimages Number of source images. +@param channels List of the dims channels used to compute the histogram. The first array channels +are numerated from 0 to images[0].channels()-1 , the second array channels are counted from +images[0].channels() to images[0].channels() + images[1].channels()-1, and so on. +@param mask Optional mask. If the matrix is not empty, it must be an 8-bit array of the same size +as images[i] . The non-zero mask elements mark the array elements counted in the histogram. +@param hist Output histogram, which is a dense or sparse dims -dimensional array. +@param dims Histogram dimensionality that must be positive and not greater than CV_MAX_DIMS +(equal to 32 in the current OpenCV version). +@param histSize Array of histogram sizes in each dimension. +@param ranges Array of the dims arrays of the histogram bin boundaries in each dimension. When the +histogram is uniform ( uniform =true), then for each dimension i it is enough to specify the lower +(inclusive) boundary \f$L_0\f$ of the 0-th histogram bin and the upper (exclusive) boundary +\f$U_{\texttt{histSize}[i]-1}\f$ for the last histogram bin histSize[i]-1 . That is, in case of a +uniform histogram each of ranges[i] is an array of 2 elements. When the histogram is not uniform ( +uniform=false ), then each of ranges[i] contains histSize[i]+1 elements: +\f$L_0, U_0=L_1, U_1=L_2, ..., U_{\texttt{histSize[i]}-2}=L_{\texttt{histSize[i]}-1}, U_{\texttt{histSize[i]}-1}\f$ +. The array elements, that are not between \f$L_0\f$ and \f$U_{\texttt{histSize[i]}-1}\f$ , are not +counted in the histogram. +@param uniform Flag indicating whether the histogram is uniform or not (see above). +@param accumulate Accumulation flag. If it is set, the histogram is not cleared in the beginning +when it is allocated. This feature enables you to compute a single histogram from several sets of +arrays, or to update the histogram in time. +*/ +CV_EXPORTS void calcHist( const Mat* images, int nimages, + const int* channels, InputArray mask, + OutputArray hist, int dims, const int* histSize, + const float** ranges, bool uniform = true, bool accumulate = false ); + +/** @overload + +this variant uses %SparseMat for output +*/ +CV_EXPORTS void calcHist( const Mat* images, int nimages, + const int* channels, InputArray mask, + SparseMat& hist, int dims, + const int* histSize, const float** ranges, + bool uniform = true, bool accumulate = false ); + +/** @overload + +this variant supports only uniform histograms. + +ranges argument is either empty vector or a flattened vector of histSize.size()*2 elements +(histSize.size() element pairs). The first and second elements of each pair specify the lower and +upper boundaries. +*/ +CV_EXPORTS_W void calcHist( InputArrayOfArrays images, + const std::vector& channels, + InputArray mask, OutputArray hist, + const std::vector& histSize, + const std::vector& ranges, + bool accumulate = false ); + +/** @brief Calculates the back projection of a histogram. + +The function cv::calcBackProject calculates the back project of the histogram. That is, similarly to +#calcHist , at each location (x, y) the function collects the values from the selected channels +in the input images and finds the corresponding histogram bin. But instead of incrementing it, the +function reads the bin value, scales it by scale , and stores in backProject(x,y) . In terms of +statistics, the function computes probability of each element value in respect with the empirical +probability distribution represented by the histogram. See how, for example, you can find and track +a bright-colored object in a scene: + +- Before tracking, show the object to the camera so that it covers almost the whole frame. +Calculate a hue histogram. The histogram may have strong maximums, corresponding to the dominant +colors in the object. + +- When tracking, calculate a back projection of a hue plane of each input video frame using that +pre-computed histogram. Threshold the back projection to suppress weak colors. It may also make +sense to suppress pixels with non-sufficient color saturation and too dark or too bright pixels. + +- Find connected components in the resulting picture and choose, for example, the largest +component. + +This is an approximate algorithm of the CamShift color object tracker. + +@param images Source arrays. They all should have the same depth, CV_8U, CV_16U or CV_32F , and the same +size. Each of them can have an arbitrary number of channels. +@param nimages Number of source images. +@param channels The list of channels used to compute the back projection. The number of channels +must match the histogram dimensionality. The first array channels are numerated from 0 to +images[0].channels()-1 , the second array channels are counted from images[0].channels() to +images[0].channels() + images[1].channels()-1, and so on. +@param hist Input histogram that can be dense or sparse. +@param backProject Destination back projection array that is a single-channel array of the same +size and depth as images[0] . +@param ranges Array of arrays of the histogram bin boundaries in each dimension. See #calcHist . +@param scale Optional scale factor for the output back projection. +@param uniform Flag indicating whether the histogram is uniform or not (see #calcHist). + +@sa calcHist, compareHist + */ +CV_EXPORTS void calcBackProject( const Mat* images, int nimages, + const int* channels, InputArray hist, + OutputArray backProject, const float** ranges, + double scale = 1, bool uniform = true ); + +/** @overload */ +CV_EXPORTS void calcBackProject( const Mat* images, int nimages, + const int* channels, const SparseMat& hist, + OutputArray backProject, const float** ranges, + double scale = 1, bool uniform = true ); + +/** @overload */ +CV_EXPORTS_W void calcBackProject( InputArrayOfArrays images, const std::vector& channels, + InputArray hist, OutputArray dst, + const std::vector& ranges, + double scale ); + +/** @brief Compares two histograms. + +The function cv::compareHist compares two dense or two sparse histograms using the specified method. + +The function returns \f$d(H_1, H_2)\f$ . + +While the function works well with 1-, 2-, 3-dimensional dense histograms, it may not be suitable +for high-dimensional sparse histograms. In such histograms, because of aliasing and sampling +problems, the coordinates of non-zero histogram bins can slightly shift. To compare such histograms +or more general sparse configurations of weighted points, consider using the #EMD function. + +@param H1 First compared histogram. +@param H2 Second compared histogram of the same size as H1 . +@param method Comparison method, see #HistCompMethods + */ +CV_EXPORTS_W double compareHist( InputArray H1, InputArray H2, int method ); + +/** @overload */ +CV_EXPORTS double compareHist( const SparseMat& H1, const SparseMat& H2, int method ); + +/** @brief Equalizes the histogram of a grayscale image. + +The function equalizes the histogram of the input image using the following algorithm: + +- Calculate the histogram \f$H\f$ for src . +- Normalize the histogram so that the sum of histogram bins is 255. +- Compute the integral of the histogram: +\f[H'_i = \sum _{0 \le j < i} H(j)\f] +- Transform the image using \f$H'\f$ as a look-up table: \f$\texttt{dst}(x,y) = H'(\texttt{src}(x,y))\f$ + +The algorithm normalizes the brightness and increases the contrast of the image. + +@param src Source 8-bit single channel image. +@param dst Destination image of the same size and type as src . + */ +CV_EXPORTS_W void equalizeHist( InputArray src, OutputArray dst ); + +/** @brief Creates a smart pointer to a cv::CLAHE class and initializes it. + +@param clipLimit Threshold for contrast limiting. +@param tileGridSize Size of grid for histogram equalization. Input image will be divided into +equally sized rectangular tiles. tileGridSize defines the number of tiles in row and column. + */ +CV_EXPORTS_W Ptr createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8)); + +/** @brief Computes the "minimal work" distance between two weighted point configurations. + +The function computes the earth mover distance and/or a lower boundary of the distance between the +two weighted point configurations. One of the applications described in @cite RubnerSept98, +@cite Rubner2000 is multi-dimensional histogram comparison for image retrieval. EMD is a transportation +problem that is solved using some modification of a simplex algorithm, thus the complexity is +exponential in the worst case, though, on average it is much faster. In the case of a real metric +the lower boundary can be calculated even faster (using linear-time algorithm) and it can be used +to determine roughly whether the two signatures are far enough so that they cannot relate to the +same object. + +@param signature1 First signature, a \f$\texttt{size1}\times \texttt{dims}+1\f$ floating-point matrix. +Each row stores the point weight followed by the point coordinates. The matrix is allowed to have +a single column (weights only) if the user-defined cost matrix is used. The weights must be +non-negative and have at least one non-zero value. +@param signature2 Second signature of the same format as signature1 , though the number of rows +may be different. The total weights may be different. In this case an extra "dummy" point is added +to either signature1 or signature2. The weights must be non-negative and have at least one non-zero +value. +@param distType Used metric. See #DistanceTypes. +@param cost User-defined \f$\texttt{size1}\times \texttt{size2}\f$ cost matrix. Also, if a cost matrix +is used, lower boundary lowerBound cannot be calculated because it needs a metric function. +@param lowerBound Optional input/output parameter: lower boundary of a distance between the two +signatures that is a distance between mass centers. The lower boundary may not be calculated if +the user-defined cost matrix is used, the total weights of point configurations are not equal, or +if the signatures consist of weights only (the signature matrices have a single column). You +**must** initialize \*lowerBound . If the calculated distance between mass centers is greater or +equal to \*lowerBound (it means that the signatures are far enough), the function does not +calculate EMD. In any case \*lowerBound is set to the calculated distance between mass centers on +return. Thus, if you want to calculate both distance between mass centers and EMD, \*lowerBound +should be set to 0. +@param flow Resultant \f$\texttt{size1} \times \texttt{size2}\f$ flow matrix: \f$\texttt{flow}_{i,j}\f$ is +a flow from \f$i\f$ -th point of signature1 to \f$j\f$ -th point of signature2 . + */ +CV_EXPORTS float EMD( InputArray signature1, InputArray signature2, + int distType, InputArray cost=noArray(), + float* lowerBound = 0, OutputArray flow = noArray() ); + +CV_EXPORTS_AS(EMD) float wrapperEMD( InputArray signature1, InputArray signature2, + int distType, InputArray cost=noArray(), + CV_IN_OUT Ptr lowerBound = Ptr(), OutputArray flow = noArray() ); + +//! @} imgproc_hist + +//! @addtogroup imgproc_segmentation +//! @{ + +/** @example samples/cpp/watershed.cpp +An example using the watershed algorithm +*/ + +/** @brief Performs a marker-based image segmentation using the watershed algorithm. + +The function implements one of the variants of watershed, non-parametric marker-based segmentation +algorithm, described in @cite Meyer92 . + +Before passing the image to the function, you have to roughly outline the desired regions in the +image markers with positive (\>0) indices. So, every region is represented as one or more connected +components with the pixel values 1, 2, 3, and so on. Such markers can be retrieved from a binary +mask using #findContours and #drawContours (see the watershed.cpp demo). The markers are "seeds" of +the future image regions. All the other pixels in markers , whose relation to the outlined regions +is not known and should be defined by the algorithm, should be set to 0's. In the function output, +each pixel in markers is set to a value of the "seed" components or to -1 at boundaries between the +regions. + +@note Any two neighbor connected components are not necessarily separated by a watershed boundary +(-1's pixels); for example, they can touch each other in the initial marker image passed to the +function. + +@param image Input 8-bit 3-channel image. +@param markers Input/output 32-bit single-channel image (map) of markers. It should have the same +size as image . + +@sa findContours + */ +CV_EXPORTS_W void watershed( InputArray image, InputOutputArray markers ); + +//! @} imgproc_segmentation + +//! @addtogroup imgproc_filter +//! @{ + +/** @brief Performs initial step of meanshift segmentation of an image. + +The function implements the filtering stage of meanshift segmentation, that is, the output of the +function is the filtered "posterized" image with color gradients and fine-grain texture flattened. +At every pixel (X,Y) of the input image (or down-sized input image, see below) the function executes +meanshift iterations, that is, the pixel (X,Y) neighborhood in the joint space-color hyperspace is +considered: + +\f[(x,y): X- \texttt{sp} \le x \le X+ \texttt{sp} , Y- \texttt{sp} \le y \le Y+ \texttt{sp} , ||(R,G,B)-(r,g,b)|| \le \texttt{sr}\f] + +where (R,G,B) and (r,g,b) are the vectors of color components at (X,Y) and (x,y), respectively +(though, the algorithm does not depend on the color space used, so any 3-component color space can +be used instead). Over the neighborhood the average spatial value (X',Y') and average color vector +(R',G',B') are found and they act as the neighborhood center on the next iteration: + +\f[(X,Y)~(X',Y'), (R,G,B)~(R',G',B').\f] + +After the iterations over, the color components of the initial pixel (that is, the pixel from where +the iterations started) are set to the final value (average color at the last iteration): + +\f[I(X,Y) <- (R*,G*,B*)\f] + +When maxLevel \> 0, the gaussian pyramid of maxLevel+1 levels is built, and the above procedure is +run on the smallest layer first. After that, the results are propagated to the larger layer and the +iterations are run again only on those pixels where the layer colors differ by more than sr from the +lower-resolution layer of the pyramid. That makes boundaries of color regions sharper. Note that the +results will be actually different from the ones obtained by running the meanshift procedure on the +whole original image (i.e. when maxLevel==0). + +@param src The source 8-bit, 3-channel image. +@param dst The destination image of the same format and the same size as the source. +@param sp The spatial window radius. +@param sr The color window radius. +@param maxLevel Maximum level of the pyramid for the segmentation. +@param termcrit Termination criteria: when to stop meanshift iterations. + */ +CV_EXPORTS_W void pyrMeanShiftFiltering( InputArray src, OutputArray dst, + double sp, double sr, int maxLevel = 1, + TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5,1) ); + +//! @} + +//! @addtogroup imgproc_segmentation +//! @{ + +/** @example samples/cpp/grabcut.cpp +An example using the GrabCut algorithm +![Sample Screenshot](grabcut_output1.jpg) +*/ + +/** @brief Runs the GrabCut algorithm. + +The function implements the [GrabCut image segmentation algorithm](http://en.wikipedia.org/wiki/GrabCut). + +@param img Input 8-bit 3-channel image. +@param mask Input/output 8-bit single-channel mask. The mask is initialized by the function when +mode is set to #GC_INIT_WITH_RECT. Its elements may have one of the #GrabCutClasses. +@param rect ROI containing a segmented object. The pixels outside of the ROI are marked as +"obvious background". The parameter is only used when mode==#GC_INIT_WITH_RECT . +@param bgdModel Temporary array for the background model. Do not modify it while you are +processing the same image. +@param fgdModel Temporary arrays for the foreground model. Do not modify it while you are +processing the same image. +@param iterCount Number of iterations the algorithm should make before returning the result. Note +that the result can be refined with further calls with mode==#GC_INIT_WITH_MASK or +mode==GC_EVAL . +@param mode Operation mode that could be one of the #GrabCutModes + */ +CV_EXPORTS_W void grabCut( InputArray img, InputOutputArray mask, Rect rect, + InputOutputArray bgdModel, InputOutputArray fgdModel, + int iterCount, int mode = GC_EVAL ); + +//! @} imgproc_segmentation + +//! @addtogroup imgproc_misc +//! @{ + +/** @example samples/cpp/distrans.cpp +An example on using the distance transform +*/ + +/** @brief Calculates the distance to the closest zero pixel for each pixel of the source image. + +The function cv::distanceTransform calculates the approximate or precise distance from every binary +image pixel to the nearest zero pixel. For zero image pixels, the distance will obviously be zero. + +When maskSize == #DIST_MASK_PRECISE and distanceType == #DIST_L2 , the function runs the +algorithm described in @cite Felzenszwalb04 . This algorithm is parallelized with the TBB library. + +In other cases, the algorithm @cite Borgefors86 is used. This means that for a pixel the function +finds the shortest path to the nearest zero pixel consisting of basic shifts: horizontal, vertical, +diagonal, or knight's move (the latest is available for a \f$5\times 5\f$ mask). The overall +distance is calculated as a sum of these basic distances. Since the distance function should be +symmetric, all of the horizontal and vertical shifts must have the same cost (denoted as a ), all +the diagonal shifts must have the same cost (denoted as `b`), and all knight's moves must have the +same cost (denoted as `c`). For the #DIST_C and #DIST_L1 types, the distance is calculated +precisely, whereas for #DIST_L2 (Euclidean distance) the distance can be calculated only with a +relative error (a \f$5\times 5\f$ mask gives more accurate results). For `a`,`b`, and `c`, OpenCV +uses the values suggested in the original paper: +- DIST_L1: `a = 1, b = 2` +- DIST_L2: + - `3 x 3`: `a=0.955, b=1.3693` + - `5 x 5`: `a=1, b=1.4, c=2.1969` +- DIST_C: `a = 1, b = 1` + +Typically, for a fast, coarse distance estimation #DIST_L2, a \f$3\times 3\f$ mask is used. For a +more accurate distance estimation #DIST_L2, a \f$5\times 5\f$ mask or the precise algorithm is used. +Note that both the precise and the approximate algorithms are linear on the number of pixels. + +This variant of the function does not only compute the minimum distance for each pixel \f$(x, y)\f$ +but also identifies the nearest connected component consisting of zero pixels +(labelType==#DIST_LABEL_CCOMP) or the nearest zero pixel (labelType==#DIST_LABEL_PIXEL). Index of the +component/pixel is stored in `labels(x, y)`. When labelType==#DIST_LABEL_CCOMP, the function +automatically finds connected components of zero pixels in the input image and marks them with +distinct labels. When labelType==#DIST_LABEL_PIXEL, the function scans through the input image and +marks all the zero pixels with distinct labels. + +In this mode, the complexity is still linear. That is, the function provides a very fast way to +compute the Voronoi diagram for a binary image. Currently, the second variant can use only the +approximate distance transform algorithm, i.e. maskSize=#DIST_MASK_PRECISE is not supported +yet. + +@param src 8-bit, single-channel (binary) source image. +@param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point, +single-channel image of the same size as src. +@param labels Output 2D array of labels (the discrete Voronoi diagram). It has the type +CV_32SC1 and the same size as src. +@param distanceType Type of distance, see #DistanceTypes +@param maskSize Size of the distance transform mask, see #DistanceTransformMasks. +#DIST_MASK_PRECISE is not supported by this variant. In case of the #DIST_L1 or #DIST_C distance type, +the parameter is forced to 3 because a \f$3\times 3\f$ mask gives the same result as \f$5\times +5\f$ or any larger aperture. +@param labelType Type of the label array to build, see #DistanceTransformLabelTypes. + */ +CV_EXPORTS_AS(distanceTransformWithLabels) void distanceTransform( InputArray src, OutputArray dst, + OutputArray labels, int distanceType, int maskSize, + int labelType = DIST_LABEL_CCOMP ); + +/** @overload +@param src 8-bit, single-channel (binary) source image. +@param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point, +single-channel image of the same size as src . +@param distanceType Type of distance, see #DistanceTypes +@param maskSize Size of the distance transform mask, see #DistanceTransformMasks. In case of the +#DIST_L1 or #DIST_C distance type, the parameter is forced to 3 because a \f$3\times 3\f$ mask gives +the same result as \f$5\times 5\f$ or any larger aperture. +@param dstType Type of output image. It can be CV_8U or CV_32F. Type CV_8U can be used only for +the first variant of the function and distanceType == #DIST_L1. +*/ +CV_EXPORTS_W void distanceTransform( InputArray src, OutputArray dst, + int distanceType, int maskSize, int dstType=CV_32F); + +/** @brief Fills a connected component with the given color. + +The function cv::floodFill fills a connected component starting from the seed point with the specified +color. The connectivity is determined by the color/brightness closeness of the neighbor pixels. The +pixel at \f$(x,y)\f$ is considered to belong to the repainted domain if: + +- in case of a grayscale image and floating range +\f[\texttt{src} (x',y')- \texttt{loDiff} \leq \texttt{src} (x,y) \leq \texttt{src} (x',y')+ \texttt{upDiff}\f] + + +- in case of a grayscale image and fixed range +\f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)- \texttt{loDiff} \leq \texttt{src} (x,y) \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)+ \texttt{upDiff}\f] + + +- in case of a color image and floating range +\f[\texttt{src} (x',y')_r- \texttt{loDiff} _r \leq \texttt{src} (x,y)_r \leq \texttt{src} (x',y')_r+ \texttt{upDiff} _r,\f] +\f[\texttt{src} (x',y')_g- \texttt{loDiff} _g \leq \texttt{src} (x,y)_g \leq \texttt{src} (x',y')_g+ \texttt{upDiff} _g\f] +and +\f[\texttt{src} (x',y')_b- \texttt{loDiff} _b \leq \texttt{src} (x,y)_b \leq \texttt{src} (x',y')_b+ \texttt{upDiff} _b\f] + + +- in case of a color image and fixed range +\f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_r- \texttt{loDiff} _r \leq \texttt{src} (x,y)_r \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_r+ \texttt{upDiff} _r,\f] +\f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_g- \texttt{loDiff} _g \leq \texttt{src} (x,y)_g \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_g+ \texttt{upDiff} _g\f] +and +\f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b- \texttt{loDiff} _b \leq \texttt{src} (x,y)_b \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b+ \texttt{upDiff} _b\f] + + +where \f$src(x',y')\f$ is the value of one of pixel neighbors that is already known to belong to the +component. That is, to be added to the connected component, a color/brightness of the pixel should +be close enough to: +- Color/brightness of one of its neighbors that already belong to the connected component in case +of a floating range. +- Color/brightness of the seed point in case of a fixed range. + +Use these functions to either mark a connected component with the specified color in-place, or build +a mask and then extract the contour, or copy the region to another image, and so on. + +@param image Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the +function unless the #FLOODFILL_MASK_ONLY flag is set in the second variant of the function. See +the details below. +@param mask Operation mask that should be a single-channel 8-bit image, 2 pixels wider and 2 pixels +taller than image. If an empty Mat is passed it will be created automatically. Since this is both an +input and output parameter, you must take responsibility of initializing it. +Flood-filling cannot go across non-zero pixels in the input mask. For example, +an edge detector output can be used as a mask to stop filling at edges. On output, pixels in the +mask corresponding to filled pixels in the image are set to 1 or to the specified value in flags +as described below. Additionally, the function fills the border of the mask with ones to simplify +internal processing. It is therefore possible to use the same mask in multiple calls to the function +to make sure the filled areas do not overlap. +@param seedPoint Starting point. +@param newVal New value of the repainted domain pixels. +@param loDiff Maximal lower brightness/color difference between the currently observed pixel and +one of its neighbors belonging to the component, or a seed pixel being added to the component. +@param upDiff Maximal upper brightness/color difference between the currently observed pixel and +one of its neighbors belonging to the component, or a seed pixel being added to the component. +@param rect Optional output parameter set by the function to the minimum bounding rectangle of the +repainted domain. +@param flags Operation flags. The first 8 bits contain a connectivity value. The default value of +4 means that only the four nearest neighbor pixels (those that share an edge) are considered. A +connectivity value of 8 means that the eight nearest neighbor pixels (those that share a corner) +will be considered. The next 8 bits (8-16) contain a value between 1 and 255 with which to fill +the mask (the default value is 1). For example, 4 | ( 255 \<\< 8 ) will consider 4 nearest +neighbours and fill the mask with a value of 255. The following additional options occupy higher +bits and therefore may be further combined with the connectivity and mask fill values using +bit-wise or (|), see #FloodFillFlags. + +@note Since the mask is larger than the filled image, a pixel \f$(x, y)\f$ in image corresponds to the +pixel \f$(x+1, y+1)\f$ in the mask . + +@sa findContours + */ +CV_EXPORTS_W int floodFill( InputOutputArray image, InputOutputArray mask, + Point seedPoint, Scalar newVal, CV_OUT Rect* rect=0, + Scalar loDiff = Scalar(), Scalar upDiff = Scalar(), + int flags = 4 ); + +/** @example samples/cpp/ffilldemo.cpp +An example using the FloodFill technique +*/ + +/** @overload + +variant without `mask` parameter +*/ +CV_EXPORTS int floodFill( InputOutputArray image, + Point seedPoint, Scalar newVal, CV_OUT Rect* rect = 0, + Scalar loDiff = Scalar(), Scalar upDiff = Scalar(), + int flags = 4 ); + +//! Performs linear blending of two images: +//! \f[ \texttt{dst}(i,j) = \texttt{weights1}(i,j)*\texttt{src1}(i,j) + \texttt{weights2}(i,j)*\texttt{src2}(i,j) \f] +//! @param src1 It has a type of CV_8UC(n) or CV_32FC(n), where n is a positive integer. +//! @param src2 It has the same type and size as src1. +//! @param weights1 It has a type of CV_32FC1 and the same size with src1. +//! @param weights2 It has a type of CV_32FC1 and the same size with src1. +//! @param dst It is created if it does not have the same size and type with src1. +CV_EXPORTS_W void blendLinear(InputArray src1, InputArray src2, InputArray weights1, InputArray weights2, OutputArray dst); + +//! @} imgproc_misc + +//! @addtogroup imgproc_color_conversions +//! @{ + +/** @brief Converts an image from one color space to another. + +The function converts an input image from one color space to another. In case of a transformation +to-from RGB color space, the order of the channels should be specified explicitly (RGB or BGR). Note +that the default color format in OpenCV is often referred to as RGB but it is actually BGR (the +bytes are reversed). So the first byte in a standard (24-bit) color image will be an 8-bit Blue +component, the second byte will be Green, and the third byte will be Red. The fourth, fifth, and +sixth bytes would then be the second pixel (Blue, then Green, then Red), and so on. + +The conventional ranges for R, G, and B channel values are: +- 0 to 255 for CV_8U images +- 0 to 65535 for CV_16U images +- 0 to 1 for CV_32F images + +In case of linear transformations, the range does not matter. But in case of a non-linear +transformation, an input RGB image should be normalized to the proper value range to get the correct +results, for example, for RGB \f$\rightarrow\f$ L\*u\*v\* transformation. For example, if you have a +32-bit floating-point image directly converted from an 8-bit image without any scaling, then it will +have the 0..255 value range instead of 0..1 assumed by the function. So, before calling #cvtColor , +you need first to scale the image down: +@code + img *= 1./255; + cvtColor(img, img, COLOR_BGR2Luv); +@endcode +If you use #cvtColor with 8-bit images, the conversion will have some information lost. For many +applications, this will not be noticeable but it is recommended to use 32-bit images in applications +that need the full range of colors or that convert an image before an operation and then convert +back. + +If conversion adds the alpha channel, its value will set to the maximum of corresponding channel +range: 255 for CV_8U, 65535 for CV_16U, 1 for CV_32F. + +@param src input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC... ), or single-precision +floating-point. +@param dst output image of the same size and depth as src. +@param code color space conversion code (see #ColorConversionCodes). +@param dstCn number of channels in the destination image; if the parameter is 0, the number of the +channels is derived automatically from src and code. +@param hint Implementation modfication flags. See #AlgorithmHint + +@see @ref imgproc_color_conversions + */ +CV_EXPORTS_W void cvtColor( InputArray src, OutputArray dst, int code, int dstCn = 0, AlgorithmHint hint = cv::ALGO_HINT_DEFAULT ); + +/** @brief Converts an image from one color space to another where the source image is +stored in two planes. + +This function only supports YUV420 to RGB conversion as of now. + +@param src1 8-bit image (#CV_8U) of the Y plane. +@param src2 image containing interleaved U/V plane. +@param dst output image. +@param code Specifies the type of conversion. It can take any of the following values: +- #COLOR_YUV2BGR_NV12 +- #COLOR_YUV2RGB_NV12 +- #COLOR_YUV2BGRA_NV12 +- #COLOR_YUV2RGBA_NV12 +- #COLOR_YUV2BGR_NV21 +- #COLOR_YUV2RGB_NV21 +- #COLOR_YUV2BGRA_NV21 +- #COLOR_YUV2RGBA_NV21 +@param hint Implementation modfication flags. See #AlgorithmHint +*/ +CV_EXPORTS_W void cvtColorTwoPlane( InputArray src1, InputArray src2, OutputArray dst, int code, AlgorithmHint hint = cv::ALGO_HINT_DEFAULT ); + +/** @brief main function for all demosaicing processes + +@param src input image: 8-bit unsigned or 16-bit unsigned. +@param dst output image of the same size and depth as src. +@param code Color space conversion code (see the description below). +@param dstCn number of channels in the destination image; if the parameter is 0, the number of the +channels is derived automatically from src and code. + +The function can do the following transformations: + +- Demosaicing using bilinear interpolation + + #COLOR_BayerBG2BGR , #COLOR_BayerGB2BGR , #COLOR_BayerRG2BGR , #COLOR_BayerGR2BGR + + #COLOR_BayerBG2GRAY , #COLOR_BayerGB2GRAY , #COLOR_BayerRG2GRAY , #COLOR_BayerGR2GRAY + +- Demosaicing using Variable Number of Gradients. + + #COLOR_BayerBG2BGR_VNG , #COLOR_BayerGB2BGR_VNG , #COLOR_BayerRG2BGR_VNG , #COLOR_BayerGR2BGR_VNG + +- Edge-Aware Demosaicing. + + #COLOR_BayerBG2BGR_EA , #COLOR_BayerGB2BGR_EA , #COLOR_BayerRG2BGR_EA , #COLOR_BayerGR2BGR_EA + +- Demosaicing with alpha channel + + #COLOR_BayerBG2BGRA , #COLOR_BayerGB2BGRA , #COLOR_BayerRG2BGRA , #COLOR_BayerGR2BGRA + +@sa cvtColor +*/ +CV_EXPORTS_W void demosaicing(InputArray src, OutputArray dst, int code, int dstCn = 0); + +//! @} imgproc_color_conversions + +//! @addtogroup imgproc_shape +//! @{ + +/** @brief Calculates all of the moments up to the third order of a polygon or rasterized shape. + +The function computes moments, up to the 3rd order, of a vector shape or a rasterized shape. The +results are returned in the structure cv::Moments. + +@param array Single chanel raster image (CV_8U, CV_16U, CV_16S, CV_32F, CV_64F) or an array ( +\f$1 \times N\f$ or \f$N \times 1\f$ ) of 2D points (Point or Point2f). +@param binaryImage If it is true, all non-zero image pixels are treated as 1's. The parameter is +used for images only. +@returns moments. + +@note Only applicable to contour moments calculations from Python bindings: Note that the numpy +type for the input array should be either np.int32 or np.float32. + +@sa contourArea, arcLength + */ +CV_EXPORTS_W Moments moments( InputArray array, bool binaryImage = false ); + +/** @brief Calculates seven Hu invariants. + +The function calculates seven Hu invariants (introduced in @cite Hu62; see also +) defined as: + +\f[\begin{array}{l} hu[0]= \eta _{20}+ \eta _{02} \\ hu[1]=( \eta _{20}- \eta _{02})^{2}+4 \eta _{11}^{2} \\ hu[2]=( \eta _{30}-3 \eta _{12})^{2}+ (3 \eta _{21}- \eta _{03})^{2} \\ hu[3]=( \eta _{30}+ \eta _{12})^{2}+ ( \eta _{21}+ \eta _{03})^{2} \\ hu[4]=( \eta _{30}-3 \eta _{12})( \eta _{30}+ \eta _{12})[( \eta _{30}+ \eta _{12})^{2}-3( \eta _{21}+ \eta _{03})^{2}]+(3 \eta _{21}- \eta _{03})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}] \\ hu[5]=( \eta _{20}- \eta _{02})[( \eta _{30}+ \eta _{12})^{2}- ( \eta _{21}+ \eta _{03})^{2}]+4 \eta _{11}( \eta _{30}+ \eta _{12})( \eta _{21}+ \eta _{03}) \\ hu[6]=(3 \eta _{21}- \eta _{03})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}]-( \eta _{30}-3 \eta _{12})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}] \\ \end{array}\f] + +where \f$\eta_{ji}\f$ stands for \f$\texttt{Moments::nu}_{ji}\f$ . + +These values are proved to be invariants to the image scale, rotation, and reflection except the +seventh one, whose sign is changed by reflection. This invariance is proved with the assumption of +infinite image resolution. In case of raster images, the computed Hu invariants for the original and +transformed images are a bit different. + +@param moments Input moments computed with moments . +@param hu Output Hu invariants. + +@sa matchShapes + */ +CV_EXPORTS void HuMoments( const Moments& moments, double hu[7] ); + +/** @overload */ +CV_EXPORTS_W void HuMoments( const Moments& m, OutputArray hu ); + +//! @} imgproc_shape + +//! @addtogroup imgproc_object +//! @{ + +//! type of the template matching operation +enum TemplateMatchModes { + TM_SQDIFF = 0, /*!< \f[R(x,y)= \sum _{x',y'} (T(x',y')-I(x+x',y+y'))^2\f] + with mask: + \f[R(x,y)= \sum _{x',y'} \left( (T(x',y')-I(x+x',y+y')) \cdot + M(x',y') \right)^2\f] */ + TM_SQDIFF_NORMED = 1, /*!< \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y')-I(x+x',y+y'))^2}{\sqrt{\sum_{ + x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}\f] + with mask: + \f[R(x,y)= \frac{\sum _{x',y'} \left( (T(x',y')-I(x+x',y+y')) \cdot + M(x',y') \right)^2}{\sqrt{\sum_{x',y'} \left( T(x',y') \cdot + M(x',y') \right)^2 \cdot \sum_{x',y'} \left( I(x+x',y+y') \cdot + M(x',y') \right)^2}}\f] */ + TM_CCORR = 2, /*!< \f[R(x,y)= \sum _{x',y'} (T(x',y') \cdot I(x+x',y+y'))\f] + with mask: + \f[R(x,y)= \sum _{x',y'} (T(x',y') \cdot I(x+x',y+y') \cdot M(x',y') + ^2)\f] */ + TM_CCORR_NORMED = 3, /*!< \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y') \cdot I(x+x',y+y'))}{\sqrt{ + \sum_{x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}\f] + with mask: + \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y') \cdot I(x+x',y+y') \cdot + M(x',y')^2)}{\sqrt{\sum_{x',y'} \left( T(x',y') \cdot M(x',y') + \right)^2 \cdot \sum_{x',y'} \left( I(x+x',y+y') \cdot M(x',y') + \right)^2}}\f] */ + TM_CCOEFF = 4, /*!< \f[R(x,y)= \sum _{x',y'} (T'(x',y') \cdot I'(x+x',y+y'))\f] + where + \f[\begin{array}{l} T'(x',y')=T(x',y') - 1/(w \cdot h) \cdot \sum _{ + x'',y''} T(x'',y'') \\ I'(x+x',y+y')=I(x+x',y+y') - 1/(w \cdot h) + \cdot \sum _{x'',y''} I(x+x'',y+y'') \end{array}\f] + with mask: + \f[\begin{array}{l} T'(x',y')=M(x',y') \cdot \left( T(x',y') - + \frac{1}{\sum _{x'',y''} M(x'',y'')} \cdot \sum _{x'',y''} + (T(x'',y'') \cdot M(x'',y'')) \right) \\ I'(x+x',y+y')=M(x',y') + \cdot \left( I(x+x',y+y') - \frac{1}{\sum _{x'',y''} M(x'',y'')} + \cdot \sum _{x'',y''} (I(x+x'',y+y'') \cdot M(x'',y'')) \right) + \end{array} \f] */ + TM_CCOEFF_NORMED = 5 /*!< \f[R(x,y)= \frac{ \sum_{x',y'} (T'(x',y') \cdot I'(x+x',y+y')) }{ + \sqrt{\sum_{x',y'}T'(x',y')^2 \cdot \sum_{x',y'} I'(x+x',y+y')^2} + }\f] */ +}; + +/** @example samples/cpp/tutorial_code/Histograms_Matching/MatchTemplate_Demo.cpp +An example using Template Matching algorithm +*/ + +/** @brief Compares a template against overlapped image regions. + +The function slides through image , compares the overlapped patches of size \f$w \times h\f$ against +templ using the specified method and stores the comparison results in result . #TemplateMatchModes +describes the formulae for the available comparison methods ( \f$I\f$ denotes image, \f$T\f$ +template, \f$R\f$ result, \f$M\f$ the optional mask ). The summation is done over template and/or +the image patch: \f$x' = 0...w-1, y' = 0...h-1\f$ + +After the function finishes the comparison, the best matches can be found as global minimums (when +#TM_SQDIFF was used) or maximums (when #TM_CCORR or #TM_CCOEFF was used) using the +#minMaxLoc function. In case of a color image, template summation in the numerator and each sum in +the denominator is done over all of the channels and separate mean values are used for each channel. +That is, the function can take a color template and a color image. The result will still be a +single-channel image, which is easier to analyze. + +@param image Image where the search is running. It must be 8-bit or 32-bit floating-point. +@param templ Searched template. It must be not greater than the source image and have the same +data type. +@param result Map of comparison results. It must be single-channel 32-bit floating-point. If image +is \f$W \times H\f$ and templ is \f$w \times h\f$ , then result is \f$(W-w+1) \times (H-h+1)\f$ . +@param method Parameter specifying the comparison method, see #TemplateMatchModes +@param mask Optional mask. It must have the same size as templ. It must either have the same number + of channels as template or only one channel, which is then used for all template and + image channels. If the data type is #CV_8U, the mask is interpreted as a binary mask, + meaning only elements where mask is nonzero are used and are kept unchanged independent + of the actual mask value (weight equals 1). For data tpye #CV_32F, the mask values are + used as weights. The exact formulas are documented in #TemplateMatchModes. + */ +CV_EXPORTS_W void matchTemplate( InputArray image, InputArray templ, + OutputArray result, int method, InputArray mask = noArray() ); + +//! @} + +//! @addtogroup imgproc_shape +//! @{ + +/** @example samples/cpp/connected_components.cpp +This program demonstrates connected components and use of the trackbar +*/ + +/** @brief computes the connected components labeled image of boolean image + +image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 +represents the background label. ltype specifies the output label image type, an important +consideration based on the total number of labels or alternatively the total number of pixels in +the source image. ccltype specifies the connected components labeling algorithm to use, currently +Bolelli (Spaghetti) @cite Bolelli2019, Grana (BBDT) @cite Grana2010 and Wu's (SAUF) @cite Wu2009 algorithms +are supported, see the #ConnectedComponentsAlgorithmsTypes for details. Note that SAUF algorithm forces +a row major ordering of labels while Spaghetti and BBDT do not. +This function uses parallel version of the algorithms if at least one allowed +parallel framework is enabled and if the rows of the image are at least twice the number returned by #getNumberOfCPUs. + +@param image the 8-bit single-channel image to be labeled +@param labels destination labeled image +@param connectivity 8 or 4 for 8-way or 4-way connectivity respectively +@param ltype output image label type. Currently CV_32S and CV_16U are supported. +@param ccltype connected components algorithm type (see the #ConnectedComponentsAlgorithmsTypes). +*/ +CV_EXPORTS_AS(connectedComponentsWithAlgorithm) int connectedComponents(InputArray image, OutputArray labels, + int connectivity, int ltype, int ccltype); + + +/** @overload + +@param image the 8-bit single-channel image to be labeled +@param labels destination labeled image +@param connectivity 8 or 4 for 8-way or 4-way connectivity respectively +@param ltype output image label type. Currently CV_32S and CV_16U are supported. +*/ +CV_EXPORTS_W int connectedComponents(InputArray image, OutputArray labels, + int connectivity = 8, int ltype = CV_32S); + + +/** @brief computes the connected components labeled image of boolean image and also produces a statistics output for each label + +image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 +represents the background label. ltype specifies the output label image type, an important +consideration based on the total number of labels or alternatively the total number of pixels in +the source image. ccltype specifies the connected components labeling algorithm to use, currently +Bolelli (Spaghetti) @cite Bolelli2019, Grana (BBDT) @cite Grana2010 and Wu's (SAUF) @cite Wu2009 algorithms +are supported, see the #ConnectedComponentsAlgorithmsTypes for details. Note that SAUF algorithm forces +a row major ordering of labels while Spaghetti and BBDT do not. +This function uses parallel version of the algorithms (statistics included) if at least one allowed +parallel framework is enabled and if the rows of the image are at least twice the number returned by #getNumberOfCPUs. + +@param image the 8-bit single-channel image to be labeled +@param labels destination labeled image +@param stats statistics output for each label, including the background label. +Statistics are accessed via stats(label, COLUMN) where COLUMN is one of +#ConnectedComponentsTypes, selecting the statistic. The data type is CV_32S. +@param centroids centroid output for each label, including the background label. Centroids are +accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F. +@param connectivity 8 or 4 for 8-way or 4-way connectivity respectively +@param ltype output image label type. Currently CV_32S and CV_16U are supported. +@param ccltype connected components algorithm type (see #ConnectedComponentsAlgorithmsTypes). +*/ +CV_EXPORTS_AS(connectedComponentsWithStatsWithAlgorithm) int connectedComponentsWithStats(InputArray image, OutputArray labels, + OutputArray stats, OutputArray centroids, + int connectivity, int ltype, int ccltype); + +/** @overload +@param image the 8-bit single-channel image to be labeled +@param labels destination labeled image +@param stats statistics output for each label, including the background label. +Statistics are accessed via stats(label, COLUMN) where COLUMN is one of +#ConnectedComponentsTypes, selecting the statistic. The data type is CV_32S. +@param centroids centroid output for each label, including the background label. Centroids are +accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F. +@param connectivity 8 or 4 for 8-way or 4-way connectivity respectively +@param ltype output image label type. Currently CV_32S and CV_16U are supported. +*/ +CV_EXPORTS_W int connectedComponentsWithStats(InputArray image, OutputArray labels, + OutputArray stats, OutputArray centroids, + int connectivity = 8, int ltype = CV_32S); + + +/** @brief Finds contours in a binary image. + +The function retrieves contours from the binary image using the algorithm @cite Suzuki85 . The contours +are a useful tool for shape analysis and object detection and recognition. See squares.cpp in the +OpenCV sample directory. +@note Since opencv 3.2 source image is not modified by this function. + +@param image Source, an 8-bit single-channel image. Non-zero pixels are treated as 1's. Zero +pixels remain 0's, so the image is treated as binary . You can use #compare, #inRange, #threshold , +#adaptiveThreshold, #Canny, and others to create a binary image out of a grayscale or color one. +If mode equals to #RETR_CCOMP or #RETR_FLOODFILL, the input can also be a 32-bit integer image of labels (CV_32SC1). +@param contours Detected contours. Each contour is stored as a vector of points (e.g. +std::vector >). +@param hierarchy Optional output vector (e.g. std::vector), containing information about the image topology. It has +as many elements as the number of contours. For each i-th contour contours[i], the elements +hierarchy[i][0] , hierarchy[i][1] , hierarchy[i][2] , and hierarchy[i][3] are set to 0-based indices +in contours of the next and previous contours at the same hierarchical level, the first child +contour and the parent contour, respectively. If for the contour i there are no next, previous, +parent, or nested contours, the corresponding elements of hierarchy[i] will be negative. +@note In Python, hierarchy is nested inside a top level array. Use hierarchy[0][i] to access hierarchical elements of i-th contour. +@param mode Contour retrieval mode, see #RetrievalModes +@param method Contour approximation method, see #ContourApproximationModes +@param offset Optional offset by which every contour point is shifted. This is useful if the +contours are extracted from the image ROI and then they should be analyzed in the whole image +context. + */ +CV_EXPORTS_W void findContours( InputArray image, OutputArrayOfArrays contours, + OutputArray hierarchy, int mode, + int method, Point offset = Point()); + +/** @overload */ +CV_EXPORTS void findContours( InputArray image, OutputArrayOfArrays contours, + int mode, int method, Point offset = Point()); + +//! @brief Find contours using link runs algorithm +//! +//! This function implements an algorithm different from cv::findContours: +//! - doesn't allocate temporary image internally, thus it has reduced memory consumption +//! - supports CV_8UC1 images only +//! - outputs 2-level hierarhy only (RETR_CCOMP mode) +//! - doesn't support approximation change other than CHAIN_APPROX_SIMPLE +//! In all other aspects this function is compatible with cv::findContours. +CV_EXPORTS_W void findContoursLinkRuns(InputArray image, OutputArrayOfArrays contours, OutputArray hierarchy); + +//! @overload +CV_EXPORTS_W void findContoursLinkRuns(InputArray image, OutputArrayOfArrays contours); + +/** @brief Approximates a polygonal curve(s) with the specified precision. + +The function cv::approxPolyDP approximates a curve or a polygon with another curve/polygon with less +vertices so that the distance between them is less or equal to the specified precision. It uses the +Douglas-Peucker algorithm + +@param curve Input vector of a 2D point stored in std::vector or Mat +@param approxCurve Result of the approximation. The type should match the type of the input curve. +@param epsilon Parameter specifying the approximation accuracy. This is the maximum distance +between the original curve and its approximation. +@param closed If true, the approximated curve is closed (its first and last vertices are +connected). Otherwise, it is not closed. + */ +CV_EXPORTS_W void approxPolyDP( InputArray curve, + OutputArray approxCurve, + double epsilon, bool closed ); + +/** @brief Approximates a polygon with a convex hull with a specified accuracy and number of sides. + +The cv::approxPolyN function approximates a polygon with a convex hull +so that the difference between the contour area of the original contour and the new polygon is minimal. +It uses a greedy algorithm for contracting two vertices into one in such a way that the additional area is minimal. +Straight lines formed by each edge of the convex contour are drawn and the areas of the resulting triangles are considered. +Each vertex will lie either on the original contour or outside it. + +The algorithm based on the paper @cite LowIlie2003 . + +@param curve Input vector of a 2D points stored in std::vector or Mat, points must be float or integer. +@param approxCurve Result of the approximation. The type is vector of a 2D point (Point2f or Point) in std::vector or Mat. +@param nsides The parameter defines the number of sides of the result polygon. +@param epsilon_percentage defines the percentage of the maximum of additional area. +If it equals -1, it is not used. Otherwise algorighm stops if additional area is greater than contourArea(_curve) * percentage. +If additional area exceeds the limit, algorithm returns as many vertices as there were at the moment the limit was exceeded. +@param ensure_convex If it is true, algorithm creates a convex hull of input contour. Otherwise input vector should be convex. + */ +CV_EXPORTS_W void approxPolyN(InputArray curve, OutputArray approxCurve, + int nsides, float epsilon_percentage = -1.0, + bool ensure_convex = true); + +/** @brief Calculates a contour perimeter or a curve length. + +The function computes a curve length or a closed contour perimeter. + +@param curve Input vector of 2D points, stored in std::vector or Mat. +@param closed Flag indicating whether the curve is closed or not. + */ +CV_EXPORTS_W double arcLength( InputArray curve, bool closed ); + +/** @brief Calculates the up-right bounding rectangle of a point set or non-zero pixels of gray-scale image. + +The function calculates and returns the minimal up-right bounding rectangle for the specified point set or +non-zero pixels of gray-scale image. + +@param array Input gray-scale image or 2D point set, stored in std::vector or Mat. + */ +CV_EXPORTS_W Rect boundingRect( InputArray array ); + +/** @brief Calculates a contour area. + +The function computes a contour area. Similarly to moments , the area is computed using the Green +formula. Thus, the returned area and the number of non-zero pixels, if you draw the contour using +#drawContours or #fillPoly , can be different. Also, the function will most certainly give a wrong +results for contours with self-intersections. + +Example: +@code + vector contour; + contour.push_back(Point2f(0, 0)); + contour.push_back(Point2f(10, 0)); + contour.push_back(Point2f(10, 10)); + contour.push_back(Point2f(5, 4)); + + double area0 = contourArea(contour); + vector approx; + approxPolyDP(contour, approx, 5, true); + double area1 = contourArea(approx); + + cout << "area0 =" << area0 << endl << + "area1 =" << area1 << endl << + "approx poly vertices" << approx.size() << endl; +@endcode +@param contour Input vector of 2D points (contour vertices), stored in std::vector or Mat. +@param oriented Oriented area flag. If it is true, the function returns a signed area value, +depending on the contour orientation (clockwise or counter-clockwise). Using this feature you can +determine orientation of a contour by taking the sign of an area. By default, the parameter is +false, which means that the absolute value is returned. + */ +CV_EXPORTS_W double contourArea( InputArray contour, bool oriented = false ); + +/** @brief Finds a rotated rectangle of the minimum area enclosing the input 2D point set. + +The function calculates and returns the minimum-area bounding rectangle (possibly rotated) for a +specified point set. Developer should keep in mind that the returned RotatedRect can contain negative +indices when data is close to the containing Mat element boundary. + +@param points Input vector of 2D points, stored in std::vector\<\> or Mat + */ +CV_EXPORTS_W RotatedRect minAreaRect( InputArray points ); + +/** @brief Finds the four vertices of a rotated rect. Useful to draw the rotated rectangle. + +The function finds the four vertices of a rotated rectangle. This function is useful to draw the +rectangle. In C++, instead of using this function, you can directly use RotatedRect::points method. Please +visit the @ref tutorial_bounding_rotated_ellipses "tutorial on Creating Bounding rotated boxes and ellipses for contours" for more information. + +@param box The input rotated rectangle. It may be the output of @ref minAreaRect. +@param points The output array of four vertices of rectangles. + */ +CV_EXPORTS_W void boxPoints(RotatedRect box, OutputArray points); + +/** @brief Finds a circle of the minimum area enclosing a 2D point set. + +The function finds the minimal enclosing circle of a 2D point set using an iterative algorithm. + +@param points Input vector of 2D points, stored in std::vector\<\> or Mat +@param center Output center of the circle. +@param radius Output radius of the circle. + */ +CV_EXPORTS_W void minEnclosingCircle( InputArray points, + CV_OUT Point2f& center, CV_OUT float& radius ); + +/** @example samples/cpp/minarea.cpp +*/ + +/** @brief Finds a triangle of minimum area enclosing a 2D point set and returns its area. + +The function finds a triangle of minimum area enclosing the given set of 2D points and returns its +area. The output for a given 2D point set is shown in the image below. 2D points are depicted in +*red* and the enclosing triangle in *yellow*. + +![Sample output of the minimum enclosing triangle function](pics/minenclosingtriangle.png) + +The implementation of the algorithm is based on O'Rourke's @cite ORourke86 and Klee and Laskowski's +@cite KleeLaskowski85 papers. O'Rourke provides a \f$\theta(n)\f$ algorithm for finding the minimal +enclosing triangle of a 2D convex polygon with n vertices. Since the #minEnclosingTriangle function +takes a 2D point set as input an additional preprocessing step of computing the convex hull of the +2D point set is required. The complexity of the #convexHull function is \f$O(n log(n))\f$ which is higher +than \f$\theta(n)\f$. Thus the overall complexity of the function is \f$O(n log(n))\f$. + +@param points Input vector of 2D points with depth CV_32S or CV_32F, stored in std::vector\<\> or Mat +@param triangle Output vector of three 2D points defining the vertices of the triangle. The depth +of the OutputArray must be CV_32F. + */ +CV_EXPORTS_W double minEnclosingTriangle( InputArray points, CV_OUT OutputArray triangle ); + +/** @brief Compares two shapes. + +The function compares two shapes. All three implemented methods use the Hu invariants (see #HuMoments) + +@param contour1 First contour or grayscale image. +@param contour2 Second contour or grayscale image. +@param method Comparison method, see #ShapeMatchModes +@param parameter Method-specific parameter (not supported now). + */ +CV_EXPORTS_W double matchShapes( InputArray contour1, InputArray contour2, + int method, double parameter ); + +/** @example samples/cpp/convexhull.cpp +An example using the convexHull functionality +*/ + +/** @brief Finds the convex hull of a point set. + +The function cv::convexHull finds the convex hull of a 2D point set using the Sklansky's algorithm @cite Sklansky82 +that has *O(N logN)* complexity in the current implementation. + +@param points Input 2D point set, stored in std::vector or Mat. +@param hull Output convex hull. It is either an integer vector of indices or vector of points. In +the first case, the hull elements are 0-based indices of the convex hull points in the original +array (since the set of convex hull points is a subset of the original point set). In the second +case, hull elements are the convex hull points themselves. +@param clockwise Orientation flag. If it is true, the output convex hull is oriented clockwise. +Otherwise, it is oriented counter-clockwise. The assumed coordinate system has its X axis pointing +to the right, and its Y axis pointing upwards. +@param returnPoints Operation flag. In case of a matrix, when the flag is true, the function +returns convex hull points. Otherwise, it returns indices of the convex hull points. When the +output array is std::vector, the flag is ignored, and the output depends on the type of the +vector: std::vector\ implies returnPoints=false, std::vector\ implies +returnPoints=true. + +@note `points` and `hull` should be different arrays, inplace processing isn't supported. + +Check @ref tutorial_hull "the corresponding tutorial" for more details. + +useful links: + +https://www.learnopencv.com/convex-hull-using-opencv-in-python-and-c/ + */ +CV_EXPORTS_W void convexHull( InputArray points, OutputArray hull, + bool clockwise = false, bool returnPoints = true ); + +/** @brief Finds the convexity defects of a contour. + +The figure below displays convexity defects of a hand contour: + +![image](pics/defects.png) + +@param contour Input contour. +@param convexhull Convex hull obtained using convexHull that should contain indices of the contour +points that make the hull. +@param convexityDefects The output vector of convexity defects. In C++ and the new Python/Java +interface each convexity defect is represented as 4-element integer vector (a.k.a. #Vec4i): +(start_index, end_index, farthest_pt_index, fixpt_depth), where indices are 0-based indices +in the original contour of the convexity defect beginning, end and the farthest point, and +fixpt_depth is fixed-point approximation (with 8 fractional bits) of the distance between the +farthest contour point and the hull. That is, to get the floating-point value of the depth will be +fixpt_depth/256.0. + */ +CV_EXPORTS_W void convexityDefects( InputArray contour, InputArray convexhull, OutputArray convexityDefects ); + +/** @brief Tests a contour convexity. + +The function tests whether the input contour is convex or not. The contour must be simple, that is, +without self-intersections. Otherwise, the function output is undefined. + +@param contour Input vector of 2D points, stored in std::vector\<\> or Mat + */ +CV_EXPORTS_W bool isContourConvex( InputArray contour ); + +/** @example samples/cpp/intersectExample.cpp +Examples of how intersectConvexConvex works +*/ + +/** @brief Finds intersection of two convex polygons + +@param p1 First polygon +@param p2 Second polygon +@param p12 Output polygon describing the intersecting area +@param handleNested When true, an intersection is found if one of the polygons is fully enclosed in the other. +When false, no intersection is found. If the polygons share a side or the vertex of one polygon lies on an edge +of the other, they are not considered nested and an intersection will be found regardless of the value of handleNested. + +@returns Area of intersecting polygon. May be negative, if algorithm has not converged, e.g. non-convex input. + +@note intersectConvexConvex doesn't confirm that both polygons are convex and will return invalid results if they aren't. + */ +CV_EXPORTS_W float intersectConvexConvex( InputArray p1, InputArray p2, + OutputArray p12, bool handleNested = true ); + +/** @example samples/cpp/fitellipse.cpp +An example using the fitEllipse technique +*/ + +/** @brief Fits an ellipse around a set of 2D points. + +The function calculates the ellipse that fits (in a least-squares sense) a set of 2D points best of +all. It returns the rotated rectangle in which the ellipse is inscribed. The first algorithm described by @cite Fitzgibbon95 +is used. Developer should keep in mind that it is possible that the returned +ellipse/rotatedRect data contains negative indices, due to the data points being close to the +border of the containing Mat element. + +@param points Input 2D point set, stored in std::vector\<\> or Mat + */ +CV_EXPORTS_W RotatedRect fitEllipse( InputArray points ); + +/** @brief Fits an ellipse around a set of 2D points. + + The function calculates the ellipse that fits a set of 2D points. + It returns the rotated rectangle in which the ellipse is inscribed. + The Approximate Mean Square (AMS) proposed by @cite Taubin1991 is used. + + For an ellipse, this basis set is \f$ \chi= \left(x^2, x y, y^2, x, y, 1\right) \f$, + which is a set of six free coefficients \f$ A^T=\left\{A_{\text{xx}},A_{\text{xy}},A_{\text{yy}},A_x,A_y,A_0\right\} \f$. + However, to specify an ellipse, all that is needed is five numbers; the major and minor axes lengths \f$ (a,b) \f$, + the position \f$ (x_0,y_0) \f$, and the orientation \f$ \theta \f$. This is because the basis set includes lines, + quadratics, parabolic and hyperbolic functions as well as elliptical functions as possible fits. + If the fit is found to be a parabolic or hyperbolic function then the standard #fitEllipse method is used. + The AMS method restricts the fit to parabolic, hyperbolic and elliptical curves + by imposing the condition that \f$ A^T ( D_x^T D_x + D_y^T D_y) A = 1 \f$ where + the matrices \f$ Dx \f$ and \f$ Dy \f$ are the partial derivatives of the design matrix \f$ D \f$ with + respect to x and y. The matrices are formed row by row applying the following to + each of the points in the set: + \f{align*}{ + D(i,:)&=\left\{x_i^2, x_i y_i, y_i^2, x_i, y_i, 1\right\} & + D_x(i,:)&=\left\{2 x_i,y_i,0,1,0,0\right\} & + D_y(i,:)&=\left\{0,x_i,2 y_i,0,1,0\right\} + \f} + The AMS method minimizes the cost function + \f{equation*}{ + \epsilon ^2=\frac{ A^T D^T D A }{ A^T (D_x^T D_x + D_y^T D_y) A^T } + \f} + + The minimum cost is found by solving the generalized eigenvalue problem. + + \f{equation*}{ + D^T D A = \lambda \left( D_x^T D_x + D_y^T D_y\right) A + \f} + + @param points Input 2D point set, stored in std::vector\<\> or Mat + */ +CV_EXPORTS_W RotatedRect fitEllipseAMS( InputArray points ); + + +/** @brief Fits an ellipse around a set of 2D points. + + The function calculates the ellipse that fits a set of 2D points. + It returns the rotated rectangle in which the ellipse is inscribed. + The Direct least square (Direct) method by @cite oy1998NumericallySD is used. + + For an ellipse, this basis set is \f$ \chi= \left(x^2, x y, y^2, x, y, 1\right) \f$, + which is a set of six free coefficients \f$ A^T=\left\{A_{\text{xx}},A_{\text{xy}},A_{\text{yy}},A_x,A_y,A_0\right\} \f$. + However, to specify an ellipse, all that is needed is five numbers; the major and minor axes lengths \f$ (a,b) \f$, + the position \f$ (x_0,y_0) \f$, and the orientation \f$ \theta \f$. This is because the basis set includes lines, + quadratics, parabolic and hyperbolic functions as well as elliptical functions as possible fits. + The Direct method confines the fit to ellipses by ensuring that \f$ 4 A_{xx} A_{yy}- A_{xy}^2 > 0 \f$. + The condition imposed is that \f$ 4 A_{xx} A_{yy}- A_{xy}^2=1 \f$ which satisfies the inequality + and as the coefficients can be arbitrarily scaled is not overly restrictive. + + \f{equation*}{ + \epsilon ^2= A^T D^T D A \quad \text{with} \quad A^T C A =1 \quad \text{and} \quad C=\left(\begin{matrix} + 0 & 0 & 2 & 0 & 0 & 0 \\ + 0 & -1 & 0 & 0 & 0 & 0 \\ + 2 & 0 & 0 & 0 & 0 & 0 \\ + 0 & 0 & 0 & 0 & 0 & 0 \\ + 0 & 0 & 0 & 0 & 0 & 0 \\ + 0 & 0 & 0 & 0 & 0 & 0 + \end{matrix} \right) + \f} + + The minimum cost is found by solving the generalized eigenvalue problem. + + \f{equation*}{ + D^T D A = \lambda \left( C\right) A + \f} + + The system produces only one positive eigenvalue \f$ \lambda\f$ which is chosen as the solution + with its eigenvector \f$\mathbf{u}\f$. These are used to find the coefficients + + \f{equation*}{ + A = \sqrt{\frac{1}{\mathbf{u}^T C \mathbf{u}}} \mathbf{u} + \f} + The scaling factor guarantees that \f$A^T C A =1\f$. + + @param points Input 2D point set, stored in std::vector\<\> or Mat + */ +CV_EXPORTS_W RotatedRect fitEllipseDirect( InputArray points ); + +/** @brief Fits a line to a 2D or 3D point set. + +The function fitLine fits a line to a 2D or 3D point set by minimizing \f$\sum_i \rho(r_i)\f$ where +\f$r_i\f$ is a distance between the \f$i^{th}\f$ point, the line and \f$\rho(r)\f$ is a distance function, one +of the following: +- DIST_L2 +\f[\rho (r) = r^2/2 \quad \text{(the simplest and the fastest least-squares method)}\f] +- DIST_L1 +\f[\rho (r) = r\f] +- DIST_L12 +\f[\rho (r) = 2 \cdot ( \sqrt{1 + \frac{r^2}{2}} - 1)\f] +- DIST_FAIR +\f[\rho \left (r \right ) = C^2 \cdot \left ( \frac{r}{C} - \log{\left(1 + \frac{r}{C}\right)} \right ) \quad \text{where} \quad C=1.3998\f] +- DIST_WELSCH +\f[\rho \left (r \right ) = \frac{C^2}{2} \cdot \left ( 1 - \exp{\left(-\left(\frac{r}{C}\right)^2\right)} \right ) \quad \text{where} \quad C=2.9846\f] +- DIST_HUBER +\f[\rho (r) = \fork{r^2/2}{if \(r < C\)}{C \cdot (r-C/2)}{otherwise} \quad \text{where} \quad C=1.345\f] + +The algorithm is based on the M-estimator ( ) technique +that iteratively fits the line using the weighted least-squares algorithm. After each iteration the +weights \f$w_i\f$ are adjusted to be inversely proportional to \f$\rho(r_i)\f$ . + +@param points Input vector of 2D or 3D points, stored in std::vector\<\> or Mat. +@param line Output line parameters. In case of 2D fitting, it should be a vector of 4 elements +(like Vec4f) - (vx, vy, x0, y0), where (vx, vy) is a normalized vector collinear to the line and +(x0, y0) is a point on the line. In case of 3D fitting, it should be a vector of 6 elements (like +Vec6f) - (vx, vy, vz, x0, y0, z0), where (vx, vy, vz) is a normalized vector collinear to the line +and (x0, y0, z0) is a point on the line. +@param distType Distance used by the M-estimator, see #DistanceTypes +@param param Numerical parameter ( C ) for some types of distances. If it is 0, an optimal value +is chosen. +@param reps Sufficient accuracy for the radius (distance between the coordinate origin and the line). +@param aeps Sufficient accuracy for the angle. 0.01 would be a good default value for reps and aeps. + */ +CV_EXPORTS_W void fitLine( InputArray points, OutputArray line, int distType, + double param, double reps, double aeps ); + +/** @brief Performs a point-in-contour test. + +The function determines whether the point is inside a contour, outside, or lies on an edge (or +coincides with a vertex). It returns positive (inside), negative (outside), or zero (on an edge) +value, correspondingly. When measureDist=false , the return value is +1, -1, and 0, respectively. +Otherwise, the return value is a signed distance between the point and the nearest contour edge. + +See below a sample output of the function where each image pixel is tested against the contour: + +![sample output](pics/pointpolygon.png) + +@param contour Input contour. +@param pt Point tested against the contour. +@param measureDist If true, the function estimates the signed distance from the point to the +nearest contour edge. Otherwise, the function only checks if the point is inside a contour or not. + */ +CV_EXPORTS_W double pointPolygonTest( InputArray contour, Point2f pt, bool measureDist ); + +/** @brief Finds out if there is any intersection between two rotated rectangles. + +If there is then the vertices of the intersecting region are returned as well. + +Below are some examples of intersection configurations. The hatched pattern indicates the +intersecting region and the red vertices are returned by the function. + +![intersection examples](pics/intersection.png) + +@param rect1 First rectangle +@param rect2 Second rectangle +@param intersectingRegion The output array of the vertices of the intersecting region. It returns +at most 8 vertices. Stored as std::vector\ or cv::Mat as Mx1 of type CV_32FC2. +@returns One of #RectanglesIntersectTypes + */ +CV_EXPORTS_W int rotatedRectangleIntersection( const RotatedRect& rect1, const RotatedRect& rect2, OutputArray intersectingRegion ); + +/** @brief Creates a smart pointer to a cv::GeneralizedHoughBallard class and initializes it. +*/ +CV_EXPORTS_W Ptr createGeneralizedHoughBallard(); + +/** @brief Creates a smart pointer to a cv::GeneralizedHoughGuil class and initializes it. +*/ +CV_EXPORTS_W Ptr createGeneralizedHoughGuil(); + +//! @} imgproc_shape + +//! @addtogroup imgproc_colormap +//! @{ + +//! GNU Octave/MATLAB equivalent colormaps +enum ColormapTypes +{ + COLORMAP_AUTUMN = 0, //!< ![autumn](pics/colormaps/colorscale_autumn.jpg) + COLORMAP_BONE = 1, //!< ![bone](pics/colormaps/colorscale_bone.jpg) + COLORMAP_JET = 2, //!< ![jet](pics/colormaps/colorscale_jet.jpg) + COLORMAP_WINTER = 3, //!< ![winter](pics/colormaps/colorscale_winter.jpg) + COLORMAP_RAINBOW = 4, //!< ![rainbow](pics/colormaps/colorscale_rainbow.jpg) + COLORMAP_OCEAN = 5, //!< ![ocean](pics/colormaps/colorscale_ocean.jpg) + COLORMAP_SUMMER = 6, //!< ![summer](pics/colormaps/colorscale_summer.jpg) + COLORMAP_SPRING = 7, //!< ![spring](pics/colormaps/colorscale_spring.jpg) + COLORMAP_COOL = 8, //!< ![cool](pics/colormaps/colorscale_cool.jpg) + COLORMAP_HSV = 9, //!< ![HSV](pics/colormaps/colorscale_hsv.jpg) + COLORMAP_PINK = 10, //!< ![pink](pics/colormaps/colorscale_pink.jpg) + COLORMAP_HOT = 11, //!< ![hot](pics/colormaps/colorscale_hot.jpg) + COLORMAP_PARULA = 12, //!< ![parula](pics/colormaps/colorscale_parula.jpg) + COLORMAP_MAGMA = 13, //!< ![magma](pics/colormaps/colorscale_magma.jpg) + COLORMAP_INFERNO = 14, //!< ![inferno](pics/colormaps/colorscale_inferno.jpg) + COLORMAP_PLASMA = 15, //!< ![plasma](pics/colormaps/colorscale_plasma.jpg) + COLORMAP_VIRIDIS = 16, //!< ![viridis](pics/colormaps/colorscale_viridis.jpg) + COLORMAP_CIVIDIS = 17, //!< ![cividis](pics/colormaps/colorscale_cividis.jpg) + COLORMAP_TWILIGHT = 18, //!< ![twilight](pics/colormaps/colorscale_twilight.jpg) + COLORMAP_TWILIGHT_SHIFTED = 19, //!< ![twilight shifted](pics/colormaps/colorscale_twilight_shifted.jpg) + COLORMAP_TURBO = 20, //!< ![turbo](pics/colormaps/colorscale_turbo.jpg) + COLORMAP_DEEPGREEN = 21 //!< ![deepgreen](pics/colormaps/colorscale_deepgreen.jpg) +}; + +/** @example samples/cpp/falsecolor.cpp +An example using applyColorMap function +*/ + +/** @brief Applies a GNU Octave/MATLAB equivalent colormap on a given image. + +@param src The source image, grayscale or colored of type CV_8UC1 or CV_8UC3. If CV_8UC3, then the CV_8UC1 image is generated internally using cv::COLOR_BGR2GRAY. +@param dst The result is the colormapped source image. Note: Mat::create is called on dst. +@param colormap The colormap to apply, see #ColormapTypes +*/ +CV_EXPORTS_W void applyColorMap(InputArray src, OutputArray dst, int colormap); + +/** @brief Applies a user colormap on a given image. + +@param src The source image, grayscale or colored of type CV_8UC1 or CV_8UC3. If CV_8UC3, then the CV_8UC1 image is generated internally using cv::COLOR_BGR2GRAY. +@param dst The result is the colormapped source image of the same number of channels as userColor. Note: Mat::create is called on dst. +@param userColor The colormap to apply of type CV_8UC1 or CV_8UC3 and size 256 +*/ +CV_EXPORTS_W void applyColorMap(InputArray src, OutputArray dst, InputArray userColor); + +//! @} imgproc_colormap + +//! @addtogroup imgproc_draw +//! @{ + + +/** OpenCV color channel order is BGR[A] */ +#define CV_RGB(r, g, b) cv::Scalar((b), (g), (r), 0) + +/** @brief Draws a line segment connecting two points. + +The function line draws the line segment between pt1 and pt2 points in the image. The line is +clipped by the image boundaries. For non-antialiased lines with integer coordinates, the 8-connected +or 4-connected Bresenham algorithm is used. Thick lines are drawn with rounding endings. Antialiased +lines are drawn using Gaussian filtering. + +@param img Image. +@param pt1 First point of the line segment. +@param pt2 Second point of the line segment. +@param color Line color. +@param thickness Line thickness. +@param lineType Type of the line. See #LineTypes. +@param shift Number of fractional bits in the point coordinates. + */ +CV_EXPORTS_W void line(InputOutputArray img, Point pt1, Point pt2, const Scalar& color, + int thickness = 1, int lineType = LINE_8, int shift = 0); + +/** @brief Draws an arrow segment pointing from the first point to the second one. + +The function cv::arrowedLine draws an arrow between pt1 and pt2 points in the image. See also #line. + +@param img Image. +@param pt1 The point the arrow starts from. +@param pt2 The point the arrow points to. +@param color Line color. +@param thickness Line thickness. +@param line_type Type of the line. See #LineTypes +@param shift Number of fractional bits in the point coordinates. +@param tipLength The length of the arrow tip in relation to the arrow length + */ +CV_EXPORTS_W void arrowedLine(InputOutputArray img, Point pt1, Point pt2, const Scalar& color, + int thickness=1, int line_type=8, int shift=0, double tipLength=0.1); + +/** @brief Draws a simple, thick, or filled up-right rectangle. + +The function cv::rectangle draws a rectangle outline or a filled rectangle whose two opposite corners +are pt1 and pt2. + +@param img Image. +@param pt1 Vertex of the rectangle. +@param pt2 Vertex of the rectangle opposite to pt1 . +@param color Rectangle color or brightness (grayscale image). +@param thickness Thickness of lines that make up the rectangle. Negative values, like #FILLED, +mean that the function has to draw a filled rectangle. +@param lineType Type of the line. See #LineTypes +@param shift Number of fractional bits in the point coordinates. + */ +CV_EXPORTS_W void rectangle(InputOutputArray img, Point pt1, Point pt2, + const Scalar& color, int thickness = 1, + int lineType = LINE_8, int shift = 0); + +/** @overload + +use `rec` parameter as alternative specification of the drawn rectangle: `r.tl() and +r.br()-Point(1,1)` are opposite corners +*/ +CV_EXPORTS_W void rectangle(InputOutputArray img, Rect rec, + const Scalar& color, int thickness = 1, + int lineType = LINE_8, int shift = 0); + +/** @example samples/cpp/tutorial_code/ImgProc/basic_drawing/Drawing_2.cpp +An example using drawing functions +*/ + +/** @brief Draws a circle. + +The function cv::circle draws a simple or filled circle with a given center and radius. +@param img Image where the circle is drawn. +@param center Center of the circle. +@param radius Radius of the circle. +@param color Circle color. +@param thickness Thickness of the circle outline, if positive. Negative values, like #FILLED, +mean that a filled circle is to be drawn. +@param lineType Type of the circle boundary. See #LineTypes +@param shift Number of fractional bits in the coordinates of the center and in the radius value. + */ +CV_EXPORTS_W void circle(InputOutputArray img, Point center, int radius, + const Scalar& color, int thickness = 1, + int lineType = LINE_8, int shift = 0); + +/** @brief Draws a simple or thick elliptic arc or fills an ellipse sector. + +The function cv::ellipse with more parameters draws an ellipse outline, a filled ellipse, an elliptic +arc, or a filled ellipse sector. The drawing code uses general parametric form. +A piecewise-linear curve is used to approximate the elliptic arc +boundary. If you need more control of the ellipse rendering, you can retrieve the curve using +#ellipse2Poly and then render it with #polylines or fill it with #fillPoly. If you use the first +variant of the function and want to draw the whole ellipse, not an arc, pass `startAngle=0` and +`endAngle=360`. If `startAngle` is greater than `endAngle`, they are swapped. The figure below explains +the meaning of the parameters to draw the blue arc. + +![Parameters of Elliptic Arc](pics/ellipse.svg) + +@param img Image. +@param center Center of the ellipse. +@param axes Half of the size of the ellipse main axes. +@param angle Ellipse rotation angle in degrees. +@param startAngle Starting angle of the elliptic arc in degrees. +@param endAngle Ending angle of the elliptic arc in degrees. +@param color Ellipse color. +@param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that +a filled ellipse sector is to be drawn. +@param lineType Type of the ellipse boundary. See #LineTypes +@param shift Number of fractional bits in the coordinates of the center and values of axes. + */ +CV_EXPORTS_W void ellipse(InputOutputArray img, Point center, Size axes, + double angle, double startAngle, double endAngle, + const Scalar& color, int thickness = 1, + int lineType = LINE_8, int shift = 0); + +/** @overload +@param img Image. +@param box Alternative ellipse representation via RotatedRect. This means that the function draws +an ellipse inscribed in the rotated rectangle. +@param color Ellipse color. +@param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that +a filled ellipse sector is to be drawn. +@param lineType Type of the ellipse boundary. See #LineTypes +*/ +CV_EXPORTS_W void ellipse(InputOutputArray img, const RotatedRect& box, const Scalar& color, + int thickness = 1, int lineType = LINE_8); + +/* ----------------------------------------------------------------------------------------- */ +/* ADDING A SET OF PREDEFINED MARKERS WHICH COULD BE USED TO HIGHLIGHT POSITIONS IN AN IMAGE */ +/* ----------------------------------------------------------------------------------------- */ + +/** @brief Draws a marker on a predefined position in an image. + +The function cv::drawMarker draws a marker on a given position in the image. For the moment several +marker types are supported, see #MarkerTypes for more information. + +@param img Image. +@param position The point where the crosshair is positioned. +@param color Line color. +@param markerType The specific type of marker you want to use, see #MarkerTypes +@param thickness Line thickness. +@param line_type Type of the line, See #LineTypes +@param markerSize The length of the marker axis [default = 20 pixels] + */ +CV_EXPORTS_W void drawMarker(InputOutputArray img, Point position, const Scalar& color, + int markerType = MARKER_CROSS, int markerSize=20, int thickness=1, + int line_type=8); + +/* ----------------------------------------------------------------------------------------- */ +/* END OF MARKER SECTION */ +/* ----------------------------------------------------------------------------------------- */ + +/** @brief Fills a convex polygon. + +The function cv::fillConvexPoly draws a filled convex polygon. This function is much faster than the +function #fillPoly . It can fill not only convex polygons but any monotonic polygon without +self-intersections, that is, a polygon whose contour intersects every horizontal line (scan line) +twice at the most (though, its top-most and/or the bottom edge could be horizontal). + +@param img Image. +@param points Polygon vertices. +@param color Polygon color. +@param lineType Type of the polygon boundaries. See #LineTypes +@param shift Number of fractional bits in the vertex coordinates. + */ +CV_EXPORTS_W void fillConvexPoly(InputOutputArray img, InputArray points, + const Scalar& color, int lineType = LINE_8, + int shift = 0); + +/** @overload */ +CV_EXPORTS void fillConvexPoly(InputOutputArray img, const Point* pts, int npts, + const Scalar& color, int lineType = LINE_8, + int shift = 0); + +/** @example samples/cpp/tutorial_code/ImgProc/basic_drawing/Drawing_1.cpp +An example using drawing functions +Check @ref tutorial_random_generator_and_text "the corresponding tutorial" for more details +*/ + +/** @brief Fills the area bounded by one or more polygons. + +The function cv::fillPoly fills an area bounded by several polygonal contours. The function can fill +complex areas, for example, areas with holes, contours with self-intersections (some of their +parts), and so forth. + +@param img Image. +@param pts Array of polygons where each polygon is represented as an array of points. +@param color Polygon color. +@param lineType Type of the polygon boundaries. See #LineTypes +@param shift Number of fractional bits in the vertex coordinates. +@param offset Optional offset of all points of the contours. + */ +CV_EXPORTS_W void fillPoly(InputOutputArray img, InputArrayOfArrays pts, + const Scalar& color, int lineType = LINE_8, int shift = 0, + Point offset = Point() ); + +/** @overload */ +CV_EXPORTS void fillPoly(InputOutputArray img, const Point** pts, + const int* npts, int ncontours, + const Scalar& color, int lineType = LINE_8, int shift = 0, + Point offset = Point() ); + +/** @brief Draws several polygonal curves. + +@param img Image. +@param pts Array of polygonal curves. +@param isClosed Flag indicating whether the drawn polylines are closed or not. If they are closed, +the function draws a line from the last vertex of each curve to its first vertex. +@param color Polyline color. +@param thickness Thickness of the polyline edges. +@param lineType Type of the line segments. See #LineTypes +@param shift Number of fractional bits in the vertex coordinates. + +The function cv::polylines draws one or more polygonal curves. + */ +CV_EXPORTS_W void polylines(InputOutputArray img, InputArrayOfArrays pts, + bool isClosed, const Scalar& color, + int thickness = 1, int lineType = LINE_8, int shift = 0 ); + +/** @overload */ +CV_EXPORTS void polylines(InputOutputArray img, const Point* const* pts, const int* npts, + int ncontours, bool isClosed, const Scalar& color, + int thickness = 1, int lineType = LINE_8, int shift = 0 ); + +/** @example samples/cpp/contours2.cpp +An example program illustrates the use of cv::findContours and cv::drawContours +\image html WindowsQtContoursOutput.png "Screenshot of the program" +*/ + +/** @example samples/cpp/segment_objects.cpp +An example using drawContours to clean up a background segmentation result +*/ + +/** @brief Draws contours outlines or filled contours. + +The function draws contour outlines in the image if \f$\texttt{thickness} \ge 0\f$ or fills the area +bounded by the contours if \f$\texttt{thickness}<0\f$ . The example below shows how to retrieve +connected components from the binary image and label them: : +@include snippets/imgproc_drawContours.cpp + +@param image Destination image. +@param contours All the input contours. Each contour is stored as a point vector. +@param contourIdx Parameter indicating a contour to draw. If it is negative, all the contours are drawn. +@param color Color of the contours. +@param thickness Thickness of lines the contours are drawn with. If it is negative (for example, +thickness=#FILLED ), the contour interiors are drawn. +@param lineType Line connectivity. See #LineTypes +@param hierarchy Optional information about hierarchy. It is only needed if you want to draw only +some of the contours (see maxLevel ). +@param maxLevel Maximal level for drawn contours. If it is 0, only the specified contour is drawn. +If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function +draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This +parameter is only taken into account when there is hierarchy available. +@param offset Optional contour shift parameter. Shift all the drawn contours by the specified +\f$\texttt{offset}=(dx,dy)\f$ . +@note When thickness=#FILLED, the function is designed to handle connected components with holes correctly +even when no hierarchy data is provided. This is done by analyzing all the outlines together +using even-odd rule. This may give incorrect results if you have a joint collection of separately retrieved +contours. In order to solve this problem, you need to call #drawContours separately for each sub-group +of contours, or iterate over the collection using contourIdx parameter. + */ +CV_EXPORTS_W void drawContours( InputOutputArray image, InputArrayOfArrays contours, + int contourIdx, const Scalar& color, + int thickness = 1, int lineType = LINE_8, + InputArray hierarchy = noArray(), + int maxLevel = INT_MAX, Point offset = Point() ); + +/** @brief Clips the line against the image rectangle. + +The function cv::clipLine calculates a part of the line segment that is entirely within the specified +rectangle. It returns false if the line segment is completely outside the rectangle. Otherwise, +it returns true . +@param imgSize Image size. The image rectangle is Rect(0, 0, imgSize.width, imgSize.height) . +@param pt1 First line point. +@param pt2 Second line point. + */ +CV_EXPORTS bool clipLine(Size imgSize, CV_IN_OUT Point& pt1, CV_IN_OUT Point& pt2); + +/** @overload +@param imgSize Image size. The image rectangle is Rect(0, 0, imgSize.width, imgSize.height) . +@param pt1 First line point. +@param pt2 Second line point. +*/ +CV_EXPORTS bool clipLine(Size2l imgSize, CV_IN_OUT Point2l& pt1, CV_IN_OUT Point2l& pt2); + +/** @overload +@param imgRect Image rectangle. +@param pt1 First line point. +@param pt2 Second line point. +*/ +CV_EXPORTS_W bool clipLine(Rect imgRect, CV_OUT CV_IN_OUT Point& pt1, CV_OUT CV_IN_OUT Point& pt2); + +/** @brief Approximates an elliptic arc with a polyline. + +The function ellipse2Poly computes the vertices of a polyline that approximates the specified +elliptic arc. It is used by #ellipse. If `arcStart` is greater than `arcEnd`, they are swapped. + +@param center Center of the arc. +@param axes Half of the size of the ellipse main axes. See #ellipse for details. +@param angle Rotation angle of the ellipse in degrees. See #ellipse for details. +@param arcStart Starting angle of the elliptic arc in degrees. +@param arcEnd Ending angle of the elliptic arc in degrees. +@param delta Angle between the subsequent polyline vertices. It defines the approximation +accuracy. +@param pts Output vector of polyline vertices. + */ +CV_EXPORTS_W void ellipse2Poly( Point center, Size axes, int angle, + int arcStart, int arcEnd, int delta, + CV_OUT std::vector& pts ); + +/** @overload +@param center Center of the arc. +@param axes Half of the size of the ellipse main axes. See #ellipse for details. +@param angle Rotation angle of the ellipse in degrees. See #ellipse for details. +@param arcStart Starting angle of the elliptic arc in degrees. +@param arcEnd Ending angle of the elliptic arc in degrees. +@param delta Angle between the subsequent polyline vertices. It defines the approximation accuracy. +@param pts Output vector of polyline vertices. +*/ +CV_EXPORTS void ellipse2Poly(Point2d center, Size2d axes, int angle, + int arcStart, int arcEnd, int delta, + CV_OUT std::vector& pts); + +/** @brief Draws a text string. + +The function cv::putText renders the specified text string in the image. Symbols that cannot be rendered +using the specified font are replaced by question marks. See #getTextSize for a text rendering code +example. + +@param img Image. +@param text Text string to be drawn. +@param org Bottom-left corner of the text string in the image. +@param fontFace Font type, see #HersheyFonts. +@param fontScale Font scale factor that is multiplied by the font-specific base size. +@param color Text color. +@param thickness Thickness of the lines used to draw a text. +@param lineType Line type. See #LineTypes +@param bottomLeftOrigin When true, the image data origin is at the bottom-left corner. Otherwise, +it is at the top-left corner. + */ +CV_EXPORTS_W void putText( InputOutputArray img, const String& text, Point org, + int fontFace, double fontScale, Scalar color, + int thickness = 1, int lineType = LINE_8, + bool bottomLeftOrigin = false ); + +/** @brief Calculates the width and height of a text string. + +The function cv::getTextSize calculates and returns the size of a box that contains the specified text. +That is, the following code renders some text, the tight box surrounding it, and the baseline: : +@code + String text = "Funny text inside the box"; + int fontFace = FONT_HERSHEY_SCRIPT_SIMPLEX; + double fontScale = 2; + int thickness = 3; + + Mat img(600, 800, CV_8UC3, Scalar::all(0)); + + int baseline=0; + Size textSize = getTextSize(text, fontFace, + fontScale, thickness, &baseline); + baseline += thickness; + + // center the text + Point textOrg((img.cols - textSize.width)/2, + (img.rows + textSize.height)/2); + + // draw the box + rectangle(img, textOrg + Point(0, baseline), + textOrg + Point(textSize.width, -textSize.height), + Scalar(0,0,255)); + // ... and the baseline first + line(img, textOrg + Point(0, thickness), + textOrg + Point(textSize.width, thickness), + Scalar(0, 0, 255)); + + // then put the text itself + putText(img, text, textOrg, fontFace, fontScale, + Scalar::all(255), thickness, 8); +@endcode + +@param text Input text string. +@param fontFace Font to use, see #HersheyFonts. +@param fontScale Font scale factor that is multiplied by the font-specific base size. +@param thickness Thickness of lines used to render the text. See #putText for details. +@param[out] baseLine y-coordinate of the baseline relative to the bottom-most text +point. +@return The size of a box that contains the specified text. + +@see putText + */ +CV_EXPORTS_W Size getTextSize(const String& text, int fontFace, + double fontScale, int thickness, + CV_OUT int* baseLine); + + +/** @brief Calculates the font-specific size to use to achieve a given height in pixels. + +@param fontFace Font to use, see cv::HersheyFonts. +@param pixelHeight Pixel height to compute the fontScale for +@param thickness Thickness of lines used to render the text.See putText for details. +@return The fontSize to use for cv::putText + +@see cv::putText +*/ +CV_EXPORTS_W double getFontScaleFromHeight(const int fontFace, + const int pixelHeight, + const int thickness = 1); + +/** @brief Class for iterating over all pixels on a raster line segment. + +The class LineIterator is used to get each pixel of a raster line connecting +two specified points. +It can be treated as a versatile implementation of the Bresenham algorithm +where you can stop at each pixel and do some extra processing, for +example, grab pixel values along the line or draw a line with an effect +(for example, with XOR operation). + +The number of pixels along the line is stored in LineIterator::count. +The method LineIterator::pos returns the current position in the image: + +@code{.cpp} +// grabs pixels along the line (pt1, pt2) +// from 8-bit 3-channel image to the buffer +LineIterator it(img, pt1, pt2, 8); +LineIterator it2 = it; +vector buf(it.count); + +for(int i = 0; i < it.count; i++, ++it) + buf[i] = *(const Vec3b*)*it; + +// alternative way of iterating through the line +for(int i = 0; i < it2.count; i++, ++it2) +{ + Vec3b val = img.at(it2.pos()); + CV_Assert(buf[i] == val); +} +@endcode +*/ +class CV_EXPORTS LineIterator +{ +public: + /** @brief Initializes iterator object for the given line and image. + + The returned iterator can be used to traverse all pixels on a line that + connects the given two points. + The line will be clipped on the image boundaries. + + @param img Underlying image. + @param pt1 First endpoint of the line. + @param pt2 The other endpoint of the line. + @param connectivity Pixel connectivity of the iterator. Valid values are 4 (iterator can move + up, down, left and right) and 8 (iterator can also move diagonally). + @param leftToRight If true, the line is traversed from the leftmost endpoint to the rightmost + endpoint. Otherwise, the line is traversed from \p pt1 to \p pt2. + */ + LineIterator( const Mat& img, Point pt1, Point pt2, + int connectivity = 8, bool leftToRight = false ) + { + init(&img, Rect(0, 0, img.cols, img.rows), pt1, pt2, connectivity, leftToRight); + ptmode = false; + } + LineIterator( Point pt1, Point pt2, + int connectivity = 8, bool leftToRight = false ) + { + init(0, Rect(std::min(pt1.x, pt2.x), + std::min(pt1.y, pt2.y), + std::max(pt1.x, pt2.x) - std::min(pt1.x, pt2.x) + 1, + std::max(pt1.y, pt2.y) - std::min(pt1.y, pt2.y) + 1), + pt1, pt2, connectivity, leftToRight); + ptmode = true; + } + LineIterator( Size boundingAreaSize, Point pt1, Point pt2, + int connectivity = 8, bool leftToRight = false ) + { + init(0, Rect(0, 0, boundingAreaSize.width, boundingAreaSize.height), + pt1, pt2, connectivity, leftToRight); + ptmode = true; + } + LineIterator( Rect boundingAreaRect, Point pt1, Point pt2, + int connectivity = 8, bool leftToRight = false ) + { + init(0, boundingAreaRect, pt1, pt2, connectivity, leftToRight); + ptmode = true; + } + void init(const Mat* img, Rect boundingAreaRect, Point pt1, Point pt2, int connectivity, bool leftToRight); + + /** @brief Returns pointer to the current pixel. + */ + uchar* operator *(); + + /** @brief Moves iterator to the next pixel on the line. + + This is the prefix version (++it). + */ + LineIterator& operator ++(); + + /** @brief Moves iterator to the next pixel on the line. + + This is the postfix version (it++). + */ + LineIterator operator ++(int); + + /** @brief Returns coordinates of the current pixel. + */ + Point pos() const; + + uchar* ptr; + const uchar* ptr0; + int step, elemSize; + int err, count; + int minusDelta, plusDelta; + int minusStep, plusStep; + int minusShift, plusShift; + Point p; + bool ptmode; +}; + +//! @cond IGNORED + +// === LineIterator implementation === + +inline +uchar* LineIterator::operator *() +{ + return ptmode ? 0 : ptr; +} + +inline +LineIterator& LineIterator::operator ++() +{ + int mask = err < 0 ? -1 : 0; + err += minusDelta + (plusDelta & mask); + if(!ptmode) + { + ptr += minusStep + (plusStep & mask); + } + else + { + p.x += minusShift + (plusShift & mask); + p.y += minusStep + (plusStep & mask); + } + return *this; +} + +inline +LineIterator LineIterator::operator ++(int) +{ + LineIterator it = *this; + ++(*this); + return it; +} + +inline +Point LineIterator::pos() const +{ + if(!ptmode) + { + size_t offset = (size_t)(ptr - ptr0); + int y = (int)(offset/step); + int x = (int)((offset - (size_t)y*step)/elemSize); + return Point(x, y); + } + return p; +} + +//! @endcond + +//! @} imgproc_draw + +//! @} imgproc + +} // cv + + +#include "./imgproc/segmentation.hpp" + + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/imgproc/bindings.hpp b/3rdParty/opencv-4.11.0/opencv2/imgproc/bindings.hpp index c69527a779..b0dd395112 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgproc/bindings.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/imgproc/bindings.hpp @@ -1,34 +1,34 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_IMGPROC_BINDINGS_HPP -#define OPENCV_IMGPROC_BINDINGS_HPP - -// This file contains special overloads for OpenCV bindings -// No need to use these functions in C++ code. - -namespace cv { - -/** @brief Finds lines in a binary image using the standard Hough transform and get accumulator. - * - * @note This function is for bindings use only. Use original function in C++ code - * - * @sa HoughLines - */ -CV_WRAP static inline -void HoughLinesWithAccumulator( - InputArray image, OutputArray lines, - double rho, double theta, int threshold, - double srn = 0, double stn = 0, - double min_theta = 0, double max_theta = CV_PI -) -{ - std::vector lines_acc; - HoughLines(image, lines_acc, rho, theta, threshold, srn, stn, min_theta, max_theta); - Mat(lines_acc).copyTo(lines); -} - -} // namespace - -#endif // OPENCV_IMGPROC_BINDINGS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_IMGPROC_BINDINGS_HPP +#define OPENCV_IMGPROC_BINDINGS_HPP + +// This file contains special overloads for OpenCV bindings +// No need to use these functions in C++ code. + +namespace cv { + +/** @brief Finds lines in a binary image using the standard Hough transform and get accumulator. + * + * @note This function is for bindings use only. Use original function in C++ code + * + * @sa HoughLines + */ +CV_WRAP static inline +void HoughLinesWithAccumulator( + InputArray image, OutputArray lines, + double rho, double theta, int threshold, + double srn = 0, double stn = 0, + double min_theta = 0, double max_theta = CV_PI +) +{ + std::vector lines_acc; + HoughLines(image, lines_acc, rho, theta, threshold, srn, stn, min_theta, max_theta); + Mat(lines_acc).copyTo(lines); +} + +} // namespace + +#endif // OPENCV_IMGPROC_BINDINGS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/imgproc/detail/gcgraph.hpp b/3rdParty/opencv-4.11.0/opencv2/imgproc/detail/gcgraph.hpp index f17c6e7afb..4c30f37b97 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgproc/detail/gcgraph.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/imgproc/detail/gcgraph.hpp @@ -1,395 +1,395 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_IMGPROC_DETAIL_GCGRAPH_HPP -#define OPENCV_IMGPROC_DETAIL_GCGRAPH_HPP - -//! @cond IGNORED - -namespace cv { namespace detail { -template class GCGraph -{ -public: - GCGraph(); - GCGraph( unsigned int vtxCount, unsigned int edgeCount ); - ~GCGraph(); - void create( unsigned int vtxCount, unsigned int edgeCount ); - int addVtx(); - void addEdges( int i, int j, TWeight w, TWeight revw ); - void addTermWeights( int i, TWeight sourceW, TWeight sinkW ); - TWeight maxFlow(); - bool inSourceSegment( int i ); -private: - class Vtx - { - public: - Vtx *next; // initialized and used in maxFlow() only - int parent; - int first; - int ts; - int dist; - TWeight weight; - uchar t; - }; - class Edge - { - public: - int dst; - int next; - TWeight weight; - }; - - std::vector vtcs; - std::vector edges; - TWeight flow; -}; - -template -GCGraph::GCGraph() -{ - flow = 0; -} -template -GCGraph::GCGraph( unsigned int vtxCount, unsigned int edgeCount ) -{ - create( vtxCount, edgeCount ); -} -template -GCGraph::~GCGraph() -{ -} -template -void GCGraph::create( unsigned int vtxCount, unsigned int edgeCount ) -{ - vtcs.reserve( vtxCount ); - edges.reserve( edgeCount + 2 ); - flow = 0; -} - -template -int GCGraph::addVtx() -{ - Vtx v; - memset( &v, 0, sizeof(Vtx)); - vtcs.push_back(v); - return (int)vtcs.size() - 1; -} - -template -void GCGraph::addEdges( int i, int j, TWeight w, TWeight revw ) -{ - CV_Assert( i>=0 && i<(int)vtcs.size() ); - CV_Assert( j>=0 && j<(int)vtcs.size() ); - CV_Assert( w>=0 && revw>=0 ); - CV_Assert( i != j ); - - if( !edges.size() ) - edges.resize( 2 ); - - Edge fromI, toI; - fromI.dst = j; - fromI.next = vtcs[i].first; - fromI.weight = w; - vtcs[i].first = (int)edges.size(); - edges.push_back( fromI ); - - toI.dst = i; - toI.next = vtcs[j].first; - toI.weight = revw; - vtcs[j].first = (int)edges.size(); - edges.push_back( toI ); -} - -template -void GCGraph::addTermWeights( int i, TWeight sourceW, TWeight sinkW ) -{ - CV_Assert( i>=0 && i<(int)vtcs.size() ); - - TWeight dw = vtcs[i].weight; - if( dw > 0 ) - sourceW += dw; - else - sinkW -= dw; - flow += (sourceW < sinkW) ? sourceW : sinkW; - vtcs[i].weight = sourceW - sinkW; -} - -template -TWeight GCGraph::maxFlow() -{ - CV_Assert(!vtcs.empty()); - CV_Assert(!edges.empty()); - const int TERMINAL = -1, ORPHAN = -2; - Vtx stub, *nilNode = &stub, *first = nilNode, *last = nilNode; - int curr_ts = 0; - stub.next = nilNode; - Vtx *vtxPtr = &vtcs[0]; - Edge *edgePtr = &edges[0]; - - std::vector orphans; - - // initialize the active queue and the graph vertices - for( int i = 0; i < (int)vtcs.size(); i++ ) - { - Vtx* v = vtxPtr + i; - v->ts = 0; - if( v->weight != 0 ) - { - last = last->next = v; - v->dist = 1; - v->parent = TERMINAL; - v->t = v->weight < 0; - } - else - v->parent = 0; - } - first = first->next; - last->next = nilNode; - nilNode->next = 0; - - // run the search-path -> augment-graph -> restore-trees loop - for(;;) - { - Vtx* v, *u; - int e0 = -1, ei = 0, ej = 0; - TWeight minWeight, weight; - uchar vt; - - // grow S & T search trees, find an edge connecting them - while( first != nilNode ) - { - v = first; - if( v->parent ) - { - vt = v->t; - for( ei = v->first; ei != 0; ei = edgePtr[ei].next ) - { - if( edgePtr[ei^vt].weight == 0 ) - continue; - u = vtxPtr+edgePtr[ei].dst; - if( !u->parent ) - { - u->t = vt; - u->parent = ei ^ 1; - u->ts = v->ts; - u->dist = v->dist + 1; - if( !u->next ) - { - u->next = nilNode; - last = last->next = u; - } - continue; - } - - if( u->t != vt ) - { - e0 = ei ^ vt; - break; - } - - if( u->dist > v->dist+1 && u->ts <= v->ts ) - { - // reassign the parent - u->parent = ei ^ 1; - u->ts = v->ts; - u->dist = v->dist + 1; - } - } - if( e0 > 0 ) - break; - } - // exclude the vertex from the active list - first = first->next; - v->next = 0; - } - - if( e0 <= 0 ) - break; - - // find the minimum edge weight along the path - minWeight = edgePtr[e0].weight; - CV_Assert( minWeight > 0 ); - // k = 1: source tree, k = 0: destination tree - for( int k = 1; k >= 0; k-- ) - { - for( v = vtxPtr+edgePtr[e0^k].dst;; v = vtxPtr+edgePtr[ei].dst ) - { - if( (ei = v->parent) < 0 ) - break; - weight = edgePtr[ei^k].weight; - minWeight = MIN(minWeight, weight); - CV_Assert( minWeight > 0 ); - } - weight = fabs(v->weight); - minWeight = MIN(minWeight, weight); - CV_Assert( minWeight > 0 ); - } - - // modify weights of the edges along the path and collect orphans - edgePtr[e0].weight -= minWeight; - edgePtr[e0^1].weight += minWeight; - flow += minWeight; - - // k = 1: source tree, k = 0: destination tree - for( int k = 1; k >= 0; k-- ) - { - for( v = vtxPtr+edgePtr[e0^k].dst;; v = vtxPtr+edgePtr[ei].dst ) - { - if( (ei = v->parent) < 0 ) - break; - edgePtr[ei^(k^1)].weight += minWeight; - if( (edgePtr[ei^k].weight -= minWeight) == 0 ) - { - orphans.push_back(v); - v->parent = ORPHAN; - } - } - - v->weight = v->weight + minWeight*(1-k*2); - if( v->weight == 0 ) - { - orphans.push_back(v); - v->parent = ORPHAN; - } - } - - // restore the search trees by finding new parents for the orphans - curr_ts++; - while( !orphans.empty() ) - { - Vtx* v2 = orphans.back(); - orphans.pop_back(); - - int d, minDist = INT_MAX; - e0 = 0; - vt = v2->t; - - for( ei = v2->first; ei != 0; ei = edgePtr[ei].next ) - { - if( edgePtr[ei^(vt^1)].weight == 0 ) - continue; - u = vtxPtr+edgePtr[ei].dst; - if( u->t != vt || u->parent == 0 ) - continue; - // compute the distance to the tree root - for( d = 0;; ) - { - if( u->ts == curr_ts ) - { - d += u->dist; - break; - } - ej = u->parent; - d++; - if( ej < 0 ) - { - if( ej == ORPHAN ) - d = INT_MAX-1; - else - { - u->ts = curr_ts; - u->dist = 1; - } - break; - } - u = vtxPtr+edgePtr[ej].dst; - } - - // update the distance - if( ++d < INT_MAX ) - { - if( d < minDist ) - { - minDist = d; - e0 = ei; - } - for( u = vtxPtr+edgePtr[ei].dst; u->ts != curr_ts; u = vtxPtr+edgePtr[u->parent].dst ) - { - u->ts = curr_ts; - u->dist = --d; - } - } - } - - if( (v2->parent = e0) > 0 ) - { - v2->ts = curr_ts; - v2->dist = minDist; - continue; - } - - /* no parent is found */ - v2->ts = 0; - for( ei = v2->first; ei != 0; ei = edgePtr[ei].next ) - { - u = vtxPtr+edgePtr[ei].dst; - ej = u->parent; - if( u->t != vt || !ej ) - continue; - if( edgePtr[ei^(vt^1)].weight && !u->next ) - { - u->next = nilNode; - last = last->next = u; - } - if( ej > 0 && vtxPtr+edgePtr[ej].dst == v2 ) - { - orphans.push_back(u); - u->parent = ORPHAN; - } - } - } - } - return flow; -} - -template -bool GCGraph::inSourceSegment( int i ) -{ - CV_Assert( i>=0 && i<(int)vtcs.size() ); - return vtcs[i].t == 0; -} - -}} // namespace detail, cv - - -//! @endcond - -#endif // OPENCV_IMGPROC_DETAIL_GCGRAPH_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// Intel License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000, Intel Corporation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of Intel Corporation may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_IMGPROC_DETAIL_GCGRAPH_HPP +#define OPENCV_IMGPROC_DETAIL_GCGRAPH_HPP + +//! @cond IGNORED + +namespace cv { namespace detail { +template class GCGraph +{ +public: + GCGraph(); + GCGraph( unsigned int vtxCount, unsigned int edgeCount ); + ~GCGraph(); + void create( unsigned int vtxCount, unsigned int edgeCount ); + int addVtx(); + void addEdges( int i, int j, TWeight w, TWeight revw ); + void addTermWeights( int i, TWeight sourceW, TWeight sinkW ); + TWeight maxFlow(); + bool inSourceSegment( int i ); +private: + class Vtx + { + public: + Vtx *next; // initialized and used in maxFlow() only + int parent; + int first; + int ts; + int dist; + TWeight weight; + uchar t; + }; + class Edge + { + public: + int dst; + int next; + TWeight weight; + }; + + std::vector vtcs; + std::vector edges; + TWeight flow; +}; + +template +GCGraph::GCGraph() +{ + flow = 0; +} +template +GCGraph::GCGraph( unsigned int vtxCount, unsigned int edgeCount ) +{ + create( vtxCount, edgeCount ); +} +template +GCGraph::~GCGraph() +{ +} +template +void GCGraph::create( unsigned int vtxCount, unsigned int edgeCount ) +{ + vtcs.reserve( vtxCount ); + edges.reserve( edgeCount + 2 ); + flow = 0; +} + +template +int GCGraph::addVtx() +{ + Vtx v; + memset( &v, 0, sizeof(Vtx)); + vtcs.push_back(v); + return (int)vtcs.size() - 1; +} + +template +void GCGraph::addEdges( int i, int j, TWeight w, TWeight revw ) +{ + CV_Assert( i>=0 && i<(int)vtcs.size() ); + CV_Assert( j>=0 && j<(int)vtcs.size() ); + CV_Assert( w>=0 && revw>=0 ); + CV_Assert( i != j ); + + if( !edges.size() ) + edges.resize( 2 ); + + Edge fromI, toI; + fromI.dst = j; + fromI.next = vtcs[i].first; + fromI.weight = w; + vtcs[i].first = (int)edges.size(); + edges.push_back( fromI ); + + toI.dst = i; + toI.next = vtcs[j].first; + toI.weight = revw; + vtcs[j].first = (int)edges.size(); + edges.push_back( toI ); +} + +template +void GCGraph::addTermWeights( int i, TWeight sourceW, TWeight sinkW ) +{ + CV_Assert( i>=0 && i<(int)vtcs.size() ); + + TWeight dw = vtcs[i].weight; + if( dw > 0 ) + sourceW += dw; + else + sinkW -= dw; + flow += (sourceW < sinkW) ? sourceW : sinkW; + vtcs[i].weight = sourceW - sinkW; +} + +template +TWeight GCGraph::maxFlow() +{ + CV_Assert(!vtcs.empty()); + CV_Assert(!edges.empty()); + const int TERMINAL = -1, ORPHAN = -2; + Vtx stub, *nilNode = &stub, *first = nilNode, *last = nilNode; + int curr_ts = 0; + stub.next = nilNode; + Vtx *vtxPtr = &vtcs[0]; + Edge *edgePtr = &edges[0]; + + std::vector orphans; + + // initialize the active queue and the graph vertices + for( int i = 0; i < (int)vtcs.size(); i++ ) + { + Vtx* v = vtxPtr + i; + v->ts = 0; + if( v->weight != 0 ) + { + last = last->next = v; + v->dist = 1; + v->parent = TERMINAL; + v->t = v->weight < 0; + } + else + v->parent = 0; + } + first = first->next; + last->next = nilNode; + nilNode->next = 0; + + // run the search-path -> augment-graph -> restore-trees loop + for(;;) + { + Vtx* v, *u; + int e0 = -1, ei = 0, ej = 0; + TWeight minWeight, weight; + uchar vt; + + // grow S & T search trees, find an edge connecting them + while( first != nilNode ) + { + v = first; + if( v->parent ) + { + vt = v->t; + for( ei = v->first; ei != 0; ei = edgePtr[ei].next ) + { + if( edgePtr[ei^vt].weight == 0 ) + continue; + u = vtxPtr+edgePtr[ei].dst; + if( !u->parent ) + { + u->t = vt; + u->parent = ei ^ 1; + u->ts = v->ts; + u->dist = v->dist + 1; + if( !u->next ) + { + u->next = nilNode; + last = last->next = u; + } + continue; + } + + if( u->t != vt ) + { + e0 = ei ^ vt; + break; + } + + if( u->dist > v->dist+1 && u->ts <= v->ts ) + { + // reassign the parent + u->parent = ei ^ 1; + u->ts = v->ts; + u->dist = v->dist + 1; + } + } + if( e0 > 0 ) + break; + } + // exclude the vertex from the active list + first = first->next; + v->next = 0; + } + + if( e0 <= 0 ) + break; + + // find the minimum edge weight along the path + minWeight = edgePtr[e0].weight; + CV_Assert( minWeight > 0 ); + // k = 1: source tree, k = 0: destination tree + for( int k = 1; k >= 0; k-- ) + { + for( v = vtxPtr+edgePtr[e0^k].dst;; v = vtxPtr+edgePtr[ei].dst ) + { + if( (ei = v->parent) < 0 ) + break; + weight = edgePtr[ei^k].weight; + minWeight = MIN(minWeight, weight); + CV_Assert( minWeight > 0 ); + } + weight = fabs(v->weight); + minWeight = MIN(minWeight, weight); + CV_Assert( minWeight > 0 ); + } + + // modify weights of the edges along the path and collect orphans + edgePtr[e0].weight -= minWeight; + edgePtr[e0^1].weight += minWeight; + flow += minWeight; + + // k = 1: source tree, k = 0: destination tree + for( int k = 1; k >= 0; k-- ) + { + for( v = vtxPtr+edgePtr[e0^k].dst;; v = vtxPtr+edgePtr[ei].dst ) + { + if( (ei = v->parent) < 0 ) + break; + edgePtr[ei^(k^1)].weight += minWeight; + if( (edgePtr[ei^k].weight -= minWeight) == 0 ) + { + orphans.push_back(v); + v->parent = ORPHAN; + } + } + + v->weight = v->weight + minWeight*(1-k*2); + if( v->weight == 0 ) + { + orphans.push_back(v); + v->parent = ORPHAN; + } + } + + // restore the search trees by finding new parents for the orphans + curr_ts++; + while( !orphans.empty() ) + { + Vtx* v2 = orphans.back(); + orphans.pop_back(); + + int d, minDist = INT_MAX; + e0 = 0; + vt = v2->t; + + for( ei = v2->first; ei != 0; ei = edgePtr[ei].next ) + { + if( edgePtr[ei^(vt^1)].weight == 0 ) + continue; + u = vtxPtr+edgePtr[ei].dst; + if( u->t != vt || u->parent == 0 ) + continue; + // compute the distance to the tree root + for( d = 0;; ) + { + if( u->ts == curr_ts ) + { + d += u->dist; + break; + } + ej = u->parent; + d++; + if( ej < 0 ) + { + if( ej == ORPHAN ) + d = INT_MAX-1; + else + { + u->ts = curr_ts; + u->dist = 1; + } + break; + } + u = vtxPtr+edgePtr[ej].dst; + } + + // update the distance + if( ++d < INT_MAX ) + { + if( d < minDist ) + { + minDist = d; + e0 = ei; + } + for( u = vtxPtr+edgePtr[ei].dst; u->ts != curr_ts; u = vtxPtr+edgePtr[u->parent].dst ) + { + u->ts = curr_ts; + u->dist = --d; + } + } + } + + if( (v2->parent = e0) > 0 ) + { + v2->ts = curr_ts; + v2->dist = minDist; + continue; + } + + /* no parent is found */ + v2->ts = 0; + for( ei = v2->first; ei != 0; ei = edgePtr[ei].next ) + { + u = vtxPtr+edgePtr[ei].dst; + ej = u->parent; + if( u->t != vt || !ej ) + continue; + if( edgePtr[ei^(vt^1)].weight && !u->next ) + { + u->next = nilNode; + last = last->next = u; + } + if( ej > 0 && vtxPtr+edgePtr[ej].dst == v2 ) + { + orphans.push_back(u); + u->parent = ORPHAN; + } + } + } + } + return flow; +} + +template +bool GCGraph::inSourceSegment( int i ) +{ + CV_Assert( i>=0 && i<(int)vtcs.size() ); + return vtcs[i].t == 0; +} + +}} // namespace detail, cv + + +//! @endcond + +#endif // OPENCV_IMGPROC_DETAIL_GCGRAPH_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/imgproc/detail/legacy.hpp b/3rdParty/opencv-4.11.0/opencv2/imgproc/detail/legacy.hpp index 029d9c90e8..9917c8f0f2 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgproc/detail/legacy.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/imgproc/detail/legacy.hpp @@ -1,38 +1,38 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -#ifndef OPENCV_IMGPROC_DETAIL_LEGACY_HPP -#define OPENCV_IMGPROC_DETAIL_LEGACY_HPP - -#include "opencv2/imgproc.hpp" - -namespace cv { - -#ifdef __OPENCV_BUILD - -CV_EXPORTS void findContours_legacy(InputArray _image, - OutputArrayOfArrays _contours, - OutputArray _hierarchy, - int mode, - int method, - Point offset = Point()); -CV_EXPORTS void findContours_legacy(InputArray image, - OutputArrayOfArrays contours, - int mode, - int method, - Point offset = Point()); - -CV_EXPORTS float EMD_legacy( InputArray _signature1, InputArray _signature2, - int distType, InputArray _cost, - float* lowerBound, OutputArray _flow ); - -CV_EXPORTS float wrapperEMD_legacy(InputArray _signature1, InputArray _signature2, - int distType, InputArray _cost, - Ptr lowerBound, OutputArray _flow); - -#endif - -} // namespace cv - -#endif // OPENCV_IMGPROC_DETAIL_LEGACY_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +#ifndef OPENCV_IMGPROC_DETAIL_LEGACY_HPP +#define OPENCV_IMGPROC_DETAIL_LEGACY_HPP + +#include "opencv2/imgproc.hpp" + +namespace cv { + +#ifdef __OPENCV_BUILD + +CV_EXPORTS void findContours_legacy(InputArray _image, + OutputArrayOfArrays _contours, + OutputArray _hierarchy, + int mode, + int method, + Point offset = Point()); +CV_EXPORTS void findContours_legacy(InputArray image, + OutputArrayOfArrays contours, + int mode, + int method, + Point offset = Point()); + +CV_EXPORTS float EMD_legacy( InputArray _signature1, InputArray _signature2, + int distType, InputArray _cost, + float* lowerBound, OutputArray _flow ); + +CV_EXPORTS float wrapperEMD_legacy(InputArray _signature1, InputArray _signature2, + int distType, InputArray _cost, + Ptr lowerBound, OutputArray _flow); + +#endif + +} // namespace cv + +#endif // OPENCV_IMGPROC_DETAIL_LEGACY_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/imgproc/hal/hal.hpp b/3rdParty/opencv-4.11.0/opencv2/imgproc/hal/hal.hpp index 1d1db5e3a0..814b19ea7e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgproc/hal/hal.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/imgproc/hal/hal.hpp @@ -1,269 +1,269 @@ -#ifndef CV_IMGPROC_HAL_HPP -#define CV_IMGPROC_HAL_HPP - -#include "opencv2/core/cvdef.h" -#include "opencv2/core/cvstd.hpp" -#include "opencv2/core/utility.hpp" -#include "opencv2/core/hal/interface.h" - -namespace cv { namespace hal { - -//! @addtogroup imgproc_hal_functions -//! @{ - -//--------------------------- -//! @cond IGNORED - -struct CV_EXPORTS Filter2D -{ - CV_DEPRECATED static Ptr create(uchar * , size_t , int , - int , int , - int , int , - int , int , - int , double , - int , int , - bool , bool ); - virtual void apply(uchar * , size_t , - uchar * , size_t , - int , int , - int , int , - int , int ) = 0; - virtual ~Filter2D() {} -}; - -struct CV_EXPORTS SepFilter2D -{ - CV_DEPRECATED static Ptr create(int , int , int , - uchar * , int , - uchar * , int , - int , int , - double , int ); - virtual void apply(uchar * , size_t , - uchar * , size_t , - int , int , - int , int , - int , int ) = 0; - virtual ~SepFilter2D() {} -}; - - -struct CV_EXPORTS Morph -{ - CV_DEPRECATED static Ptr create(int , int , int , int , int , - int , uchar * , size_t , - int , int , - int , int , - int , const double *, - int , bool , bool ); - virtual void apply(uchar * , size_t , uchar * , size_t , int , int , - int , int , int , int , - int , int , int , int ) = 0; - virtual ~Morph() {} -}; - -//! @endcond -//--------------------------- - -CV_EXPORTS void filter2D(int stype, int dtype, int kernel_type, - uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int full_width, int full_height, - int offset_x, int offset_y, - uchar * kernel_data, size_t kernel_step, - int kernel_width, int kernel_height, - int anchor_x, int anchor_y, - double delta, int borderType, - bool isSubmatrix); - -CV_EXPORTS void sepFilter2D(int stype, int dtype, int ktype, - uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int full_width, int full_height, - int offset_x, int offset_y, - uchar * kernelx_data, int kernelx_len, - uchar * kernely_data, int kernely_len, - int anchor_x, int anchor_y, - double delta, int borderType); - -CV_EXPORTS void morph(int op, int src_type, int dst_type, - uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int roi_width, int roi_height, int roi_x, int roi_y, - int roi_width2, int roi_height2, int roi_x2, int roi_y2, - int kernel_type, uchar * kernel_data, size_t kernel_step, - int kernel_width, int kernel_height, int anchor_x, int anchor_y, - int borderType, const double borderValue[4], - int iterations, bool isSubmatrix); - - -CV_EXPORTS void resize(int src_type, - const uchar * src_data, size_t src_step, int src_width, int src_height, - uchar * dst_data, size_t dst_step, int dst_width, int dst_height, - double inv_scale_x, double inv_scale_y, int interpolation); - -CV_EXPORTS void warpAffine(int src_type, - const uchar * src_data, size_t src_step, int src_width, int src_height, - uchar * dst_data, size_t dst_step, int dst_width, int dst_height, - const double M[6], int interpolation, int borderType, const double borderValue[4]); - -CV_EXPORTS void warpAffineBlocklineNN(int *adelta, int *bdelta, short* xy, int X0, int Y0, int bw); - -CV_EXPORTS void warpAffineBlockline(int *adelta, int *bdelta, short* xy, short* alpha, int X0, int Y0, int bw); - -CV_EXPORTS void warpPerspective(int src_type, - const uchar * src_data, size_t src_step, int src_width, int src_height, - uchar * dst_data, size_t dst_step, int dst_width, int dst_height, - const double M[9], int interpolation, int borderType, const double borderValue[4]); - -CV_EXPORTS void warpPerspectiveBlocklineNN(const double *M, short* xy, double X0, double Y0, double W0, int bw); - -CV_EXPORTS void warpPerspectiveBlockline(const double *M, short* xy, short* alpha, double X0, double Y0, double W0, int bw); - -CV_EXPORTS void cvtBGRtoBGR(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int depth, int scn, int dcn, bool swapBlue); - -CV_EXPORTS void cvtBGRtoBGR5x5(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int scn, bool swapBlue, int greenBits); - -CV_EXPORTS void cvtBGR5x5toBGR(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int dcn, bool swapBlue, int greenBits); - -CV_EXPORTS void cvtBGRtoGray(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int depth, int scn, bool swapBlue); - -CV_EXPORTS void cvtGraytoBGR(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int depth, int dcn); - -CV_EXPORTS void cvtBGR5x5toGray(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int greenBits); - -CV_EXPORTS void cvtGraytoBGR5x5(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int greenBits); -CV_EXPORTS void cvtBGRtoYUV(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int depth, int scn, bool swapBlue, bool isCbCr, - AlgorithmHint hint = ALGO_HINT_DEFAULT); - -CV_EXPORTS void cvtYUVtoBGR(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int depth, int dcn, bool swapBlue, bool isCbCr, - AlgorithmHint hint = ALGO_HINT_DEFAULT); - -CV_EXPORTS void cvtBGRtoXYZ(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int depth, int scn, bool swapBlue); - -CV_EXPORTS void cvtXYZtoBGR(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int depth, int dcn, bool swapBlue); - -CV_EXPORTS void cvtBGRtoHSV(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int depth, int scn, bool swapBlue, bool isFullRange, bool isHSV); - -CV_EXPORTS void cvtHSVtoBGR(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int depth, int dcn, bool swapBlue, bool isFullRange, bool isHSV); - -CV_EXPORTS void cvtBGRtoLab(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int depth, int scn, bool swapBlue, bool isLab, bool srgb); - -CV_EXPORTS void cvtLabtoBGR(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int depth, int dcn, bool swapBlue, bool isLab, bool srgb); - -CV_EXPORTS void cvtTwoPlaneYUVtoBGR(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int dst_width, int dst_height, - int dcn, bool swapBlue, int uIdx, - AlgorithmHint hint = ALGO_HINT_DEFAULT); - -//! Separate Y and UV planes -CV_EXPORTS void cvtTwoPlaneYUVtoBGR(const uchar * y_data, const uchar * uv_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int dst_width, int dst_height, - int dcn, bool swapBlue, int uIdx, - AlgorithmHint hint = ALGO_HINT_DEFAULT); - -CV_EXPORTS void cvtTwoPlaneYUVtoBGR(const uchar * y_data, size_t y_step, const uchar * uv_data, size_t uv_step, - uchar * dst_data, size_t dst_step, - int dst_width, int dst_height, - int dcn, bool swapBlue, int uIdx, - AlgorithmHint hint = ALGO_HINT_DEFAULT); - -CV_EXPORTS void cvtThreePlaneYUVtoBGR(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int dst_width, int dst_height, - int dcn, bool swapBlue, int uIdx, - AlgorithmHint hint = ALGO_HINT_DEFAULT); - -CV_EXPORTS void cvtBGRtoThreePlaneYUV(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int scn, bool swapBlue, int uIdx, - AlgorithmHint hint = ALGO_HINT_DEFAULT); - -//! Separate Y and UV planes -CV_EXPORTS void cvtBGRtoTwoPlaneYUV(const uchar * src_data, size_t src_step, - uchar * y_data, uchar * uv_data, size_t dst_step, - int width, int height, - int scn, bool swapBlue, int uIdx); - -CV_EXPORTS void cvtOnePlaneYUVtoBGR(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int dcn, bool swapBlue, int uIdx, int ycn, - AlgorithmHint hint = ALGO_HINT_DEFAULT); - -CV_EXPORTS void cvtOnePlaneBGRtoYUV(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int scn, bool swapBlue, int uIdx, int ycn, - AlgorithmHint hint = ALGO_HINT_DEFAULT); - -CV_EXPORTS void cvtRGBAtoMultipliedRGBA(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height); - -CV_EXPORTS void cvtMultipliedRGBAtoRGBA(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height); - -CV_EXPORTS void integral(int depth, int sdepth, int sqdepth, - const uchar* src, size_t srcstep, - uchar* sum, size_t sumstep, - uchar* sqsum, size_t sqsumstep, - uchar* tilted, size_t tstep, - int width, int height, int cn); - -//! @} - -}} - -#endif // CV_IMGPROC_HAL_HPP +#ifndef CV_IMGPROC_HAL_HPP +#define CV_IMGPROC_HAL_HPP + +#include "opencv2/core/cvdef.h" +#include "opencv2/core/cvstd.hpp" +#include "opencv2/core/utility.hpp" +#include "opencv2/core/hal/interface.h" + +namespace cv { namespace hal { + +//! @addtogroup imgproc_hal_functions +//! @{ + +//--------------------------- +//! @cond IGNORED + +struct CV_EXPORTS Filter2D +{ + CV_DEPRECATED static Ptr create(uchar * , size_t , int , + int , int , + int , int , + int , int , + int , double , + int , int , + bool , bool ); + virtual void apply(uchar * , size_t , + uchar * , size_t , + int , int , + int , int , + int , int ) = 0; + virtual ~Filter2D() {} +}; + +struct CV_EXPORTS SepFilter2D +{ + CV_DEPRECATED static Ptr create(int , int , int , + uchar * , int , + uchar * , int , + int , int , + double , int ); + virtual void apply(uchar * , size_t , + uchar * , size_t , + int , int , + int , int , + int , int ) = 0; + virtual ~SepFilter2D() {} +}; + + +struct CV_EXPORTS Morph +{ + CV_DEPRECATED static Ptr create(int , int , int , int , int , + int , uchar * , size_t , + int , int , + int , int , + int , const double *, + int , bool , bool ); + virtual void apply(uchar * , size_t , uchar * , size_t , int , int , + int , int , int , int , + int , int , int , int ) = 0; + virtual ~Morph() {} +}; + +//! @endcond +//--------------------------- + +CV_EXPORTS void filter2D(int stype, int dtype, int kernel_type, + uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int full_width, int full_height, + int offset_x, int offset_y, + uchar * kernel_data, size_t kernel_step, + int kernel_width, int kernel_height, + int anchor_x, int anchor_y, + double delta, int borderType, + bool isSubmatrix); + +CV_EXPORTS void sepFilter2D(int stype, int dtype, int ktype, + uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int full_width, int full_height, + int offset_x, int offset_y, + uchar * kernelx_data, int kernelx_len, + uchar * kernely_data, int kernely_len, + int anchor_x, int anchor_y, + double delta, int borderType); + +CV_EXPORTS void morph(int op, int src_type, int dst_type, + uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int roi_width, int roi_height, int roi_x, int roi_y, + int roi_width2, int roi_height2, int roi_x2, int roi_y2, + int kernel_type, uchar * kernel_data, size_t kernel_step, + int kernel_width, int kernel_height, int anchor_x, int anchor_y, + int borderType, const double borderValue[4], + int iterations, bool isSubmatrix); + + +CV_EXPORTS void resize(int src_type, + const uchar * src_data, size_t src_step, int src_width, int src_height, + uchar * dst_data, size_t dst_step, int dst_width, int dst_height, + double inv_scale_x, double inv_scale_y, int interpolation); + +CV_EXPORTS void warpAffine(int src_type, + const uchar * src_data, size_t src_step, int src_width, int src_height, + uchar * dst_data, size_t dst_step, int dst_width, int dst_height, + const double M[6], int interpolation, int borderType, const double borderValue[4]); + +CV_EXPORTS void warpAffineBlocklineNN(int *adelta, int *bdelta, short* xy, int X0, int Y0, int bw); + +CV_EXPORTS void warpAffineBlockline(int *adelta, int *bdelta, short* xy, short* alpha, int X0, int Y0, int bw); + +CV_EXPORTS void warpPerspective(int src_type, + const uchar * src_data, size_t src_step, int src_width, int src_height, + uchar * dst_data, size_t dst_step, int dst_width, int dst_height, + const double M[9], int interpolation, int borderType, const double borderValue[4]); + +CV_EXPORTS void warpPerspectiveBlocklineNN(const double *M, short* xy, double X0, double Y0, double W0, int bw); + +CV_EXPORTS void warpPerspectiveBlockline(const double *M, short* xy, short* alpha, double X0, double Y0, double W0, int bw); + +CV_EXPORTS void cvtBGRtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int scn, int dcn, bool swapBlue); + +CV_EXPORTS void cvtBGRtoBGR5x5(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int scn, bool swapBlue, int greenBits); + +CV_EXPORTS void cvtBGR5x5toBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int dcn, bool swapBlue, int greenBits); + +CV_EXPORTS void cvtBGRtoGray(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int scn, bool swapBlue); + +CV_EXPORTS void cvtGraytoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int dcn); + +CV_EXPORTS void cvtBGR5x5toGray(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int greenBits); + +CV_EXPORTS void cvtGraytoBGR5x5(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int greenBits); +CV_EXPORTS void cvtBGRtoYUV(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int scn, bool swapBlue, bool isCbCr, + AlgorithmHint hint = ALGO_HINT_DEFAULT); + +CV_EXPORTS void cvtYUVtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int dcn, bool swapBlue, bool isCbCr, + AlgorithmHint hint = ALGO_HINT_DEFAULT); + +CV_EXPORTS void cvtBGRtoXYZ(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int scn, bool swapBlue); + +CV_EXPORTS void cvtXYZtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int dcn, bool swapBlue); + +CV_EXPORTS void cvtBGRtoHSV(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int scn, bool swapBlue, bool isFullRange, bool isHSV); + +CV_EXPORTS void cvtHSVtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int dcn, bool swapBlue, bool isFullRange, bool isHSV); + +CV_EXPORTS void cvtBGRtoLab(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int scn, bool swapBlue, bool isLab, bool srgb); + +CV_EXPORTS void cvtLabtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int dcn, bool swapBlue, bool isLab, bool srgb); + +CV_EXPORTS void cvtTwoPlaneYUVtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int dst_width, int dst_height, + int dcn, bool swapBlue, int uIdx, + AlgorithmHint hint = ALGO_HINT_DEFAULT); + +//! Separate Y and UV planes +CV_EXPORTS void cvtTwoPlaneYUVtoBGR(const uchar * y_data, const uchar * uv_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int dst_width, int dst_height, + int dcn, bool swapBlue, int uIdx, + AlgorithmHint hint = ALGO_HINT_DEFAULT); + +CV_EXPORTS void cvtTwoPlaneYUVtoBGR(const uchar * y_data, size_t y_step, const uchar * uv_data, size_t uv_step, + uchar * dst_data, size_t dst_step, + int dst_width, int dst_height, + int dcn, bool swapBlue, int uIdx, + AlgorithmHint hint = ALGO_HINT_DEFAULT); + +CV_EXPORTS void cvtThreePlaneYUVtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int dst_width, int dst_height, + int dcn, bool swapBlue, int uIdx, + AlgorithmHint hint = ALGO_HINT_DEFAULT); + +CV_EXPORTS void cvtBGRtoThreePlaneYUV(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int scn, bool swapBlue, int uIdx, + AlgorithmHint hint = ALGO_HINT_DEFAULT); + +//! Separate Y and UV planes +CV_EXPORTS void cvtBGRtoTwoPlaneYUV(const uchar * src_data, size_t src_step, + uchar * y_data, uchar * uv_data, size_t dst_step, + int width, int height, + int scn, bool swapBlue, int uIdx); + +CV_EXPORTS void cvtOnePlaneYUVtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int dcn, bool swapBlue, int uIdx, int ycn, + AlgorithmHint hint = ALGO_HINT_DEFAULT); + +CV_EXPORTS void cvtOnePlaneBGRtoYUV(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int scn, bool swapBlue, int uIdx, int ycn, + AlgorithmHint hint = ALGO_HINT_DEFAULT); + +CV_EXPORTS void cvtRGBAtoMultipliedRGBA(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height); + +CV_EXPORTS void cvtMultipliedRGBAtoRGBA(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height); + +CV_EXPORTS void integral(int depth, int sdepth, int sqdepth, + const uchar* src, size_t srcstep, + uchar* sum, size_t sumstep, + uchar* sqsum, size_t sqsumstep, + uchar* tilted, size_t tstep, + int width, int height, int cn); + +//! @} + +}} + +#endif // CV_IMGPROC_HAL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/imgproc/hal/interface.h b/3rdParty/opencv-4.11.0/opencv2/imgproc/hal/interface.h index 8e485b9fca..29773aa34d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgproc/hal/interface.h +++ b/3rdParty/opencv-4.11.0/opencv2/imgproc/hal/interface.h @@ -1,52 +1,52 @@ -#ifndef OPENCV_IMGPROC_HAL_INTERFACE_H -#define OPENCV_IMGPROC_HAL_INTERFACE_H - -//! @addtogroup imgproc_hal_interface -//! @{ - -//! @name Interpolation modes -//! @sa cv::InterpolationFlags -//! @{ -#define CV_HAL_INTER_NEAREST 0 -#define CV_HAL_INTER_LINEAR 1 -#define CV_HAL_INTER_CUBIC 2 -#define CV_HAL_INTER_AREA 3 -#define CV_HAL_INTER_LANCZOS4 4 -#define CV_HAL_INTER_LINEAR_EXACT 5 -#define CV_HAL_INTER_NEAREST_EXACT 6 -#define CV_HAL_INTER_MAX 7 -#define CV_HAL_WARP_FILL_OUTLIERS 8 -#define CV_HAL_WARP_INVERSE_MAP 16 -#define CV_HAL_WARP_RELATIVE_MAP 32 -//! @} - -//! @name Morphology operations -//! @sa cv::MorphTypes -//! @{ -#define CV_HAL_MORPH_ERODE 0 -#define CV_HAL_MORPH_DILATE 1 -//! @} - -//! @name Threshold types -//! @sa cv::ThresholdTypes -//! @{ -#define CV_HAL_THRESH_BINARY 0 -#define CV_HAL_THRESH_BINARY_INV 1 -#define CV_HAL_THRESH_TRUNC 2 -#define CV_HAL_THRESH_TOZERO 3 -#define CV_HAL_THRESH_TOZERO_INV 4 -#define CV_HAL_THRESH_MASK 7 -#define CV_HAL_THRESH_OTSU 8 -#define CV_HAL_THRESH_TRIANGLE 16 -//! @} - -//! @name Adaptive threshold algorithm -//! @sa cv::AdaptiveThresholdTypes -//! @{ -#define CV_HAL_ADAPTIVE_THRESH_MEAN_C 0 -#define CV_HAL_ADAPTIVE_THRESH_GAUSSIAN_C 1 -//! @} - -//! @} - -#endif +#ifndef OPENCV_IMGPROC_HAL_INTERFACE_H +#define OPENCV_IMGPROC_HAL_INTERFACE_H + +//! @addtogroup imgproc_hal_interface +//! @{ + +//! @name Interpolation modes +//! @sa cv::InterpolationFlags +//! @{ +#define CV_HAL_INTER_NEAREST 0 +#define CV_HAL_INTER_LINEAR 1 +#define CV_HAL_INTER_CUBIC 2 +#define CV_HAL_INTER_AREA 3 +#define CV_HAL_INTER_LANCZOS4 4 +#define CV_HAL_INTER_LINEAR_EXACT 5 +#define CV_HAL_INTER_NEAREST_EXACT 6 +#define CV_HAL_INTER_MAX 7 +#define CV_HAL_WARP_FILL_OUTLIERS 8 +#define CV_HAL_WARP_INVERSE_MAP 16 +#define CV_HAL_WARP_RELATIVE_MAP 32 +//! @} + +//! @name Morphology operations +//! @sa cv::MorphTypes +//! @{ +#define CV_HAL_MORPH_ERODE 0 +#define CV_HAL_MORPH_DILATE 1 +//! @} + +//! @name Threshold types +//! @sa cv::ThresholdTypes +//! @{ +#define CV_HAL_THRESH_BINARY 0 +#define CV_HAL_THRESH_BINARY_INV 1 +#define CV_HAL_THRESH_TRUNC 2 +#define CV_HAL_THRESH_TOZERO 3 +#define CV_HAL_THRESH_TOZERO_INV 4 +#define CV_HAL_THRESH_MASK 7 +#define CV_HAL_THRESH_OTSU 8 +#define CV_HAL_THRESH_TRIANGLE 16 +//! @} + +//! @name Adaptive threshold algorithm +//! @sa cv::AdaptiveThresholdTypes +//! @{ +#define CV_HAL_ADAPTIVE_THRESH_MEAN_C 0 +#define CV_HAL_ADAPTIVE_THRESH_GAUSSIAN_C 1 +//! @} + +//! @} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/imgproc/imgproc.hpp b/3rdParty/opencv-4.11.0/opencv2/imgproc/imgproc.hpp index 4175bd0bc0..d661014131 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgproc/imgproc.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/imgproc/imgproc.hpp @@ -1,48 +1,48 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifdef __OPENCV_BUILD -#error this is a compatibility header which should not be used inside the OpenCV library -#endif - -#include "opencv2/imgproc.hpp" +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/imgproc.hpp" diff --git a/3rdParty/opencv-4.11.0/opencv2/imgproc/imgproc_c.h b/3rdParty/opencv-4.11.0/opencv2/imgproc/imgproc_c.h index 9085b0fa74..1dbb6d7059 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgproc/imgproc_c.h +++ b/3rdParty/opencv-4.11.0/opencv2/imgproc/imgproc_c.h @@ -1,1185 +1,1185 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_IMGPROC_IMGPROC_C_H -#define OPENCV_IMGPROC_IMGPROC_C_H - -#include "opencv2/imgproc/types_c.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** @addtogroup imgproc_c -@{ -*/ - -/*********************** Background statistics accumulation *****************************/ - -/** @brief Adds image to accumulator -@see cv::accumulate -*/ -CVAPI(void) cvAcc( const CvArr* image, CvArr* sum, - const CvArr* mask CV_DEFAULT(NULL) ); - -/** @brief Adds squared image to accumulator -@see cv::accumulateSquare -*/ -CVAPI(void) cvSquareAcc( const CvArr* image, CvArr* sqsum, - const CvArr* mask CV_DEFAULT(NULL) ); - -/** @brief Adds a product of two images to accumulator -@see cv::accumulateProduct -*/ -CVAPI(void) cvMultiplyAcc( const CvArr* image1, const CvArr* image2, CvArr* acc, - const CvArr* mask CV_DEFAULT(NULL) ); - -/** @brief Adds image to accumulator with weights: acc = acc*(1-alpha) + image*alpha -@see cv::accumulateWeighted -*/ -CVAPI(void) cvRunningAvg( const CvArr* image, CvArr* acc, double alpha, - const CvArr* mask CV_DEFAULT(NULL) ); - -/****************************************************************************************\ -* Image Processing * -\****************************************************************************************/ - -/** Copies source 2D array inside of the larger destination array and - makes a border of the specified type (IPL_BORDER_*) around the copied area. */ -CVAPI(void) cvCopyMakeBorder( const CvArr* src, CvArr* dst, CvPoint offset, - int bordertype, CvScalar value CV_DEFAULT(cvScalarAll(0))); - -/** @brief Smooths the image in one of several ways. - -@param src The source image -@param dst The destination image -@param smoothtype Type of the smoothing, see SmoothMethod_c -@param size1 The first parameter of the smoothing operation, the aperture width. Must be a -positive odd number (1, 3, 5, ...) -@param size2 The second parameter of the smoothing operation, the aperture height. Ignored by -CV_MEDIAN and CV_BILATERAL methods. In the case of simple scaled/non-scaled and Gaussian blur if -size2 is zero, it is set to size1. Otherwise it must be a positive odd number. -@param sigma1 In the case of a Gaussian parameter this parameter may specify Gaussian \f$\sigma\f$ -(standard deviation). If it is zero, it is calculated from the kernel size: -\f[\sigma = 0.3 (n/2 - 1) + 0.8 \quad \text{where} \quad n= \begin{array}{l l} \mbox{\texttt{size1} for horizontal kernel} \\ \mbox{\texttt{size2} for vertical kernel} \end{array}\f] -Using standard sigma for small kernels ( \f$3\times 3\f$ to \f$7\times 7\f$ ) gives better speed. If -sigma1 is not zero, while size1 and size2 are zeros, the kernel size is calculated from the -sigma (to provide accurate enough operation). -@param sigma2 additional parameter for bilateral filtering - -@see cv::GaussianBlur, cv::blur, cv::medianBlur, cv::bilateralFilter. - */ -CVAPI(void) cvSmooth( const CvArr* src, CvArr* dst, - int smoothtype CV_DEFAULT(CV_GAUSSIAN), - int size1 CV_DEFAULT(3), - int size2 CV_DEFAULT(0), - double sigma1 CV_DEFAULT(0), - double sigma2 CV_DEFAULT(0)); - -/** @brief Convolves an image with the kernel. - -@param src input image. -@param dst output image of the same size and the same number of channels as src. -@param kernel convolution kernel (or rather a correlation kernel), a single-channel floating point -matrix; if you want to apply different kernels to different channels, split the image into -separate color planes using split and process them individually. -@param anchor anchor of the kernel that indicates the relative position of a filtered point within -the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor -is at the kernel center. - -@see cv::filter2D - */ -CVAPI(void) cvFilter2D( const CvArr* src, CvArr* dst, const CvMat* kernel, - CvPoint anchor CV_DEFAULT(cvPoint(-1,-1))); - -/** @brief Finds integral image: SUM(X,Y) = sum(x \texttt{hist1}(I)\)}{\frac{\texttt{hist2}(I) \cdot \texttt{scale}}{\texttt{hist1}(I)}}{if \(\texttt{hist1}(I) \ne 0\) and \(\texttt{hist2}(I) \le \texttt{hist1}(I)\)}\f] - -@param hist1 First histogram (the divisor). -@param hist2 Second histogram. -@param dst_hist Destination histogram. -@param scale Scale factor for the destination histogram. - */ -CVAPI(void) cvCalcProbDensity( const CvHistogram* hist1, const CvHistogram* hist2, - CvHistogram* dst_hist, double scale CV_DEFAULT(255) ); - -/** @brief equalizes histogram of 8-bit single-channel image -@see cv::equalizeHist -*/ -CVAPI(void) cvEqualizeHist( const CvArr* src, CvArr* dst ); - - -/** @brief Applies distance transform to binary image -@see cv::distanceTransform -*/ -CVAPI(void) cvDistTransform( const CvArr* src, CvArr* dst, - int distance_type CV_DEFAULT(CV_DIST_L2), - int mask_size CV_DEFAULT(3), - const float* mask CV_DEFAULT(NULL), - CvArr* labels CV_DEFAULT(NULL), - int labelType CV_DEFAULT(CV_DIST_LABEL_CCOMP)); - - -/** @brief Applies fixed-level threshold to grayscale image. - - This is a basic operation applied before retrieving contours -@see cv::threshold -*/ -CVAPI(double) cvThreshold( const CvArr* src, CvArr* dst, - double threshold, double max_value, - int threshold_type ); - -/** @brief Applies adaptive threshold to grayscale image. - - The two parameters for methods CV_ADAPTIVE_THRESH_MEAN_C and - CV_ADAPTIVE_THRESH_GAUSSIAN_C are: - neighborhood size (3, 5, 7 etc.), - and a constant subtracted from mean (...,-3,-2,-1,0,1,2,3,...) -@see cv::adaptiveThreshold -*/ -CVAPI(void) cvAdaptiveThreshold( const CvArr* src, CvArr* dst, double max_value, - int adaptive_method CV_DEFAULT(CV_ADAPTIVE_THRESH_MEAN_C), - int threshold_type CV_DEFAULT(CV_THRESH_BINARY), - int block_size CV_DEFAULT(3), - double param1 CV_DEFAULT(5)); - -/** @brief Fills the connected component until the color difference gets large enough -@see cv::floodFill -*/ -CVAPI(void) cvFloodFill( CvArr* image, CvPoint seed_point, - CvScalar new_val, CvScalar lo_diff CV_DEFAULT(cvScalarAll(0)), - CvScalar up_diff CV_DEFAULT(cvScalarAll(0)), - CvConnectedComp* comp CV_DEFAULT(NULL), - int flags CV_DEFAULT(4), - CvArr* mask CV_DEFAULT(NULL)); - -/****************************************************************************************\ -* Feature detection * -\****************************************************************************************/ - -/** @brief Runs canny edge detector -@see cv::Canny -*/ -CVAPI(void) cvCanny( const CvArr* image, CvArr* edges, double threshold1, - double threshold2, int aperture_size CV_DEFAULT(3) ); - -/** @brief Calculates constraint image for corner detection - - Dx^2 * Dyy + Dxx * Dy^2 - 2 * Dx * Dy * Dxy. - Applying threshold to the result gives coordinates of corners -@see cv::preCornerDetect -*/ -CVAPI(void) cvPreCornerDetect( const CvArr* image, CvArr* corners, - int aperture_size CV_DEFAULT(3) ); - -/** @brief Calculates eigen values and vectors of 2x2 - gradient covariation matrix at every image pixel -@see cv::cornerEigenValsAndVecs -*/ -CVAPI(void) cvCornerEigenValsAndVecs( const CvArr* image, CvArr* eigenvv, - int block_size, int aperture_size CV_DEFAULT(3) ); - -/** @brief Calculates minimal eigenvalue for 2x2 gradient covariation matrix at - every image pixel -@see cv::cornerMinEigenVal -*/ -CVAPI(void) cvCornerMinEigenVal( const CvArr* image, CvArr* eigenval, - int block_size, int aperture_size CV_DEFAULT(3) ); - -/** @brief Harris corner detector: - - Calculates det(M) - k*(trace(M)^2), where M is 2x2 gradient covariation matrix for each pixel -@see cv::cornerHarris -*/ -CVAPI(void) cvCornerHarris( const CvArr* image, CvArr* harris_response, - int block_size, int aperture_size CV_DEFAULT(3), - double k CV_DEFAULT(0.04) ); - -/** @brief Adjust corner position using some sort of gradient search -@see cv::cornerSubPix -*/ -CVAPI(void) cvFindCornerSubPix( const CvArr* image, CvPoint2D32f* corners, - int count, CvSize win, CvSize zero_zone, - CvTermCriteria criteria ); - -/** @brief Finds a sparse set of points within the selected region - that seem to be easy to track -@see cv::goodFeaturesToTrack -*/ -CVAPI(void) cvGoodFeaturesToTrack( const CvArr* image, CvArr* eig_image, - CvArr* temp_image, CvPoint2D32f* corners, - int* corner_count, double quality_level, - double min_distance, - const CvArr* mask CV_DEFAULT(NULL), - int block_size CV_DEFAULT(3), - int use_harris CV_DEFAULT(0), - double k CV_DEFAULT(0.04) ); - -/** @brief Finds lines on binary image using one of several methods. - - line_storage is either memory storage or 1 x _max number of lines_ CvMat, its - number of columns is changed by the function. - method is one of CV_HOUGH_*; - rho, theta and threshold are used for each of those methods; - param1 ~ line length, param2 ~ line gap - for probabilistic, - param1 ~ srn, param2 ~ stn - for multi-scale -@see cv::HoughLines -*/ -CVAPI(CvSeq*) cvHoughLines2( CvArr* image, void* line_storage, int method, - double rho, double theta, int threshold, - double param1 CV_DEFAULT(0), double param2 CV_DEFAULT(0), - double min_theta CV_DEFAULT(0), double max_theta CV_DEFAULT(CV_PI)); - -/** @brief Finds circles in the image -@see cv::HoughCircles -*/ -CVAPI(CvSeq*) cvHoughCircles( CvArr* image, void* circle_storage, - int method, double dp, double min_dist, - double param1 CV_DEFAULT(100), - double param2 CV_DEFAULT(100), - int min_radius CV_DEFAULT(0), - int max_radius CV_DEFAULT(0)); - -/** @brief Fits a line into set of 2d or 3d points in a robust way (M-estimator technique) -@see cv::fitLine -*/ -CVAPI(void) cvFitLine( const CvArr* points, int dist_type, double param, - double reps, double aeps, float* line ); - -/****************************************************************************************\ -* Drawing * -\****************************************************************************************/ - -/****************************************************************************************\ -* Drawing functions work with images/matrices of arbitrary type. * -* For color images the channel order is BGR[A] * -* Antialiasing is supported only for 8-bit image now. * -* All the functions include parameter color that means rgb value (that may be * -* constructed with CV_RGB macro) for color images and brightness * -* for grayscale images. * -* If a drawn figure is partially or completely outside of the image, it is clipped.* -\****************************************************************************************/ - -#define CV_FILLED -1 - -#define CV_AA 16 - -/** @brief Draws 4-connected, 8-connected or antialiased line segment connecting two points -@see cv::line -*/ -CVAPI(void) cvLine( CvArr* img, CvPoint pt1, CvPoint pt2, - CvScalar color, int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) ); - -/** @brief Draws a rectangle given two opposite corners of the rectangle (pt1 & pt2) - - if thickness<0 (e.g. thickness == CV_FILLED), the filled box is drawn -@see cv::rectangle -*/ -CVAPI(void) cvRectangle( CvArr* img, CvPoint pt1, CvPoint pt2, - CvScalar color, int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), - int shift CV_DEFAULT(0)); - -/** @brief Draws a rectangle specified by a CvRect structure -@see cv::rectangle -*/ -CVAPI(void) cvRectangleR( CvArr* img, CvRect r, - CvScalar color, int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), - int shift CV_DEFAULT(0)); - - -/** @brief Draws a circle with specified center and radius. - - Thickness works in the same way as with cvRectangle -@see cv::circle -*/ -CVAPI(void) cvCircle( CvArr* img, CvPoint center, int radius, - CvScalar color, int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0)); - -/** @brief Draws ellipse outline, filled ellipse, elliptic arc or filled elliptic sector - - depending on _thickness_, _start_angle_ and _end_angle_ parameters. The resultant figure - is rotated by _angle_. All the angles are in degrees -@see cv::ellipse -*/ -CVAPI(void) cvEllipse( CvArr* img, CvPoint center, CvSize axes, - double angle, double start_angle, double end_angle, - CvScalar color, int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0)); - -CV_INLINE void cvEllipseBox( CvArr* img, CvBox2D box, CvScalar color, - int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) ) -{ - CvSize axes = cvSize( - cvRound(box.size.width*0.5), - cvRound(box.size.height*0.5) - ); - - cvEllipse( img, cvPointFrom32f( box.center ), axes, box.angle, - 0, 360, color, thickness, line_type, shift ); -} - -/** @brief Fills convex or monotonous polygon. -@see cv::fillConvexPoly -*/ -CVAPI(void) cvFillConvexPoly( CvArr* img, const CvPoint* pts, int npts, CvScalar color, - int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0)); - -/** @brief Fills an area bounded by one or more arbitrary polygons -@see cv::fillPoly -*/ -CVAPI(void) cvFillPoly( CvArr* img, CvPoint** pts, const int* npts, - int contours, CvScalar color, - int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) ); - -/** @brief Draws one or more polygonal curves -@see cv::polylines -*/ -CVAPI(void) cvPolyLine( CvArr* img, CvPoint** pts, const int* npts, int contours, - int is_closed, CvScalar color, int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) ); - -#define cvDrawRect cvRectangle -#define cvDrawLine cvLine -#define cvDrawCircle cvCircle -#define cvDrawEllipse cvEllipse -#define cvDrawPolyLine cvPolyLine - -/** @brief Clips the line segment connecting *pt1 and *pt2 - by the rectangular window - - (0<=xptr will point to pt1 (or pt2, see left_to_right description) location in -the image. Returns the number of pixels on the line between the ending points. -@see cv::LineIterator -*/ -CVAPI(int) cvInitLineIterator( const CvArr* image, CvPoint pt1, CvPoint pt2, - CvLineIterator* line_iterator, - int connectivity CV_DEFAULT(8), - int left_to_right CV_DEFAULT(0)); - -#define CV_NEXT_LINE_POINT( line_iterator ) \ -{ \ - int _line_iterator_mask = (line_iterator).err < 0 ? -1 : 0; \ - (line_iterator).err += (line_iterator).minus_delta + \ - ((line_iterator).plus_delta & _line_iterator_mask); \ - (line_iterator).ptr += (line_iterator).minus_step + \ - ((line_iterator).plus_step & _line_iterator_mask); \ -} - - -#define CV_FONT_HERSHEY_SIMPLEX 0 -#define CV_FONT_HERSHEY_PLAIN 1 -#define CV_FONT_HERSHEY_DUPLEX 2 -#define CV_FONT_HERSHEY_COMPLEX 3 -#define CV_FONT_HERSHEY_TRIPLEX 4 -#define CV_FONT_HERSHEY_COMPLEX_SMALL 5 -#define CV_FONT_HERSHEY_SCRIPT_SIMPLEX 6 -#define CV_FONT_HERSHEY_SCRIPT_COMPLEX 7 - -#define CV_FONT_ITALIC 16 - -#define CV_FONT_VECTOR0 CV_FONT_HERSHEY_SIMPLEX - - -/** Font structure */ -typedef struct CvFont -{ - const char* nameFont; //Qt:nameFont - CvScalar color; //Qt:ColorFont -> cvScalar(blue_component, green_component, red_component[, alpha_component]) - int font_face; //Qt: bool italic /** =CV_FONT_* */ - const int* ascii; //!< font data and metrics - const int* greek; - const int* cyrillic; - float hscale, vscale; - float shear; //!< slope coefficient: 0 - normal, >0 - italic - int thickness; //!< Qt: weight /** letters thickness */ - float dx; //!< horizontal interval between letters - int line_type; //!< Qt: PointSize -} -CvFont; - -/** @brief Initializes font structure (OpenCV 1.x API). - -The function initializes the font structure that can be passed to text rendering functions. - -@param font Pointer to the font structure initialized by the function -@param font_face Font name identifier. See cv::HersheyFonts and corresponding old CV_* identifiers. -@param hscale Horizontal scale. If equal to 1.0f , the characters have the original width -depending on the font type. If equal to 0.5f , the characters are of half the original width. -@param vscale Vertical scale. If equal to 1.0f , the characters have the original height depending -on the font type. If equal to 0.5f , the characters are of half the original height. -@param shear Approximate tangent of the character slope relative to the vertical line. A zero -value means a non-italic font, 1.0f means about a 45 degree slope, etc. -@param thickness Thickness of the text strokes -@param line_type Type of the strokes, see line description - -@sa cvPutText - */ -CVAPI(void) cvInitFont( CvFont* font, int font_face, - double hscale, double vscale, - double shear CV_DEFAULT(0), - int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8)); - -CV_INLINE CvFont cvFont( double scale, int thickness CV_DEFAULT(1) ) -{ - CvFont font; - cvInitFont( &font, CV_FONT_HERSHEY_PLAIN, scale, scale, 0, thickness, CV_AA ); - return font; -} - -/** @brief Renders text stroke with specified font and color at specified location. - CvFont should be initialized with cvInitFont -@see cvInitFont, cvGetTextSize, cvFont, cv::putText -*/ -CVAPI(void) cvPutText( CvArr* img, const char* text, CvPoint org, - const CvFont* font, CvScalar color ); - -/** @brief Calculates bounding box of text stroke (useful for alignment) -@see cv::getTextSize -*/ -CVAPI(void) cvGetTextSize( const char* text_string, const CvFont* font, - CvSize* text_size, int* baseline ); - -/** @brief Unpacks color value - -if arrtype is CV_8UC?, _color_ is treated as packed color value, otherwise the first channels -(depending on arrtype) of destination scalar are set to the same value = _color_ -*/ -CVAPI(CvScalar) cvColorToScalar( double packed_color, int arrtype ); - -/** @brief Returns the polygon points which make up the given ellipse. - -The ellipse is define by the box of size 'axes' rotated 'angle' around the 'center'. A partial -sweep of the ellipse arc can be done by specifying arc_start and arc_end to be something other than -0 and 360, respectively. The input array 'pts' must be large enough to hold the result. The total -number of points stored into 'pts' is returned by this function. -@see cv::ellipse2Poly -*/ -CVAPI(int) cvEllipse2Poly( CvPoint center, CvSize axes, - int angle, int arc_start, int arc_end, CvPoint * pts, int delta ); - -/** @brief Draws contour outlines or filled interiors on the image -@see cv::drawContours -*/ -CVAPI(void) cvDrawContours( CvArr *img, CvSeq* contour, - CvScalar external_color, CvScalar hole_color, - int max_level, int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), - CvPoint offset CV_DEFAULT(cvPoint(0,0))); - -/** @} */ - -#ifdef __cplusplus -} -#endif - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_IMGPROC_IMGPROC_C_H +#define OPENCV_IMGPROC_IMGPROC_C_H + +#include "opencv2/imgproc/types_c.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @addtogroup imgproc_c +@{ +*/ + +/*********************** Background statistics accumulation *****************************/ + +/** @brief Adds image to accumulator +@see cv::accumulate +*/ +CVAPI(void) cvAcc( const CvArr* image, CvArr* sum, + const CvArr* mask CV_DEFAULT(NULL) ); + +/** @brief Adds squared image to accumulator +@see cv::accumulateSquare +*/ +CVAPI(void) cvSquareAcc( const CvArr* image, CvArr* sqsum, + const CvArr* mask CV_DEFAULT(NULL) ); + +/** @brief Adds a product of two images to accumulator +@see cv::accumulateProduct +*/ +CVAPI(void) cvMultiplyAcc( const CvArr* image1, const CvArr* image2, CvArr* acc, + const CvArr* mask CV_DEFAULT(NULL) ); + +/** @brief Adds image to accumulator with weights: acc = acc*(1-alpha) + image*alpha +@see cv::accumulateWeighted +*/ +CVAPI(void) cvRunningAvg( const CvArr* image, CvArr* acc, double alpha, + const CvArr* mask CV_DEFAULT(NULL) ); + +/****************************************************************************************\ +* Image Processing * +\****************************************************************************************/ + +/** Copies source 2D array inside of the larger destination array and + makes a border of the specified type (IPL_BORDER_*) around the copied area. */ +CVAPI(void) cvCopyMakeBorder( const CvArr* src, CvArr* dst, CvPoint offset, + int bordertype, CvScalar value CV_DEFAULT(cvScalarAll(0))); + +/** @brief Smooths the image in one of several ways. + +@param src The source image +@param dst The destination image +@param smoothtype Type of the smoothing, see SmoothMethod_c +@param size1 The first parameter of the smoothing operation, the aperture width. Must be a +positive odd number (1, 3, 5, ...) +@param size2 The second parameter of the smoothing operation, the aperture height. Ignored by +CV_MEDIAN and CV_BILATERAL methods. In the case of simple scaled/non-scaled and Gaussian blur if +size2 is zero, it is set to size1. Otherwise it must be a positive odd number. +@param sigma1 In the case of a Gaussian parameter this parameter may specify Gaussian \f$\sigma\f$ +(standard deviation). If it is zero, it is calculated from the kernel size: +\f[\sigma = 0.3 (n/2 - 1) + 0.8 \quad \text{where} \quad n= \begin{array}{l l} \mbox{\texttt{size1} for horizontal kernel} \\ \mbox{\texttt{size2} for vertical kernel} \end{array}\f] +Using standard sigma for small kernels ( \f$3\times 3\f$ to \f$7\times 7\f$ ) gives better speed. If +sigma1 is not zero, while size1 and size2 are zeros, the kernel size is calculated from the +sigma (to provide accurate enough operation). +@param sigma2 additional parameter for bilateral filtering + +@see cv::GaussianBlur, cv::blur, cv::medianBlur, cv::bilateralFilter. + */ +CVAPI(void) cvSmooth( const CvArr* src, CvArr* dst, + int smoothtype CV_DEFAULT(CV_GAUSSIAN), + int size1 CV_DEFAULT(3), + int size2 CV_DEFAULT(0), + double sigma1 CV_DEFAULT(0), + double sigma2 CV_DEFAULT(0)); + +/** @brief Convolves an image with the kernel. + +@param src input image. +@param dst output image of the same size and the same number of channels as src. +@param kernel convolution kernel (or rather a correlation kernel), a single-channel floating point +matrix; if you want to apply different kernels to different channels, split the image into +separate color planes using split and process them individually. +@param anchor anchor of the kernel that indicates the relative position of a filtered point within +the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor +is at the kernel center. + +@see cv::filter2D + */ +CVAPI(void) cvFilter2D( const CvArr* src, CvArr* dst, const CvMat* kernel, + CvPoint anchor CV_DEFAULT(cvPoint(-1,-1))); + +/** @brief Finds integral image: SUM(X,Y) = sum(x \texttt{hist1}(I)\)}{\frac{\texttt{hist2}(I) \cdot \texttt{scale}}{\texttt{hist1}(I)}}{if \(\texttt{hist1}(I) \ne 0\) and \(\texttt{hist2}(I) \le \texttt{hist1}(I)\)}\f] + +@param hist1 First histogram (the divisor). +@param hist2 Second histogram. +@param dst_hist Destination histogram. +@param scale Scale factor for the destination histogram. + */ +CVAPI(void) cvCalcProbDensity( const CvHistogram* hist1, const CvHistogram* hist2, + CvHistogram* dst_hist, double scale CV_DEFAULT(255) ); + +/** @brief equalizes histogram of 8-bit single-channel image +@see cv::equalizeHist +*/ +CVAPI(void) cvEqualizeHist( const CvArr* src, CvArr* dst ); + + +/** @brief Applies distance transform to binary image +@see cv::distanceTransform +*/ +CVAPI(void) cvDistTransform( const CvArr* src, CvArr* dst, + int distance_type CV_DEFAULT(CV_DIST_L2), + int mask_size CV_DEFAULT(3), + const float* mask CV_DEFAULT(NULL), + CvArr* labels CV_DEFAULT(NULL), + int labelType CV_DEFAULT(CV_DIST_LABEL_CCOMP)); + + +/** @brief Applies fixed-level threshold to grayscale image. + + This is a basic operation applied before retrieving contours +@see cv::threshold +*/ +CVAPI(double) cvThreshold( const CvArr* src, CvArr* dst, + double threshold, double max_value, + int threshold_type ); + +/** @brief Applies adaptive threshold to grayscale image. + + The two parameters for methods CV_ADAPTIVE_THRESH_MEAN_C and + CV_ADAPTIVE_THRESH_GAUSSIAN_C are: + neighborhood size (3, 5, 7 etc.), + and a constant subtracted from mean (...,-3,-2,-1,0,1,2,3,...) +@see cv::adaptiveThreshold +*/ +CVAPI(void) cvAdaptiveThreshold( const CvArr* src, CvArr* dst, double max_value, + int adaptive_method CV_DEFAULT(CV_ADAPTIVE_THRESH_MEAN_C), + int threshold_type CV_DEFAULT(CV_THRESH_BINARY), + int block_size CV_DEFAULT(3), + double param1 CV_DEFAULT(5)); + +/** @brief Fills the connected component until the color difference gets large enough +@see cv::floodFill +*/ +CVAPI(void) cvFloodFill( CvArr* image, CvPoint seed_point, + CvScalar new_val, CvScalar lo_diff CV_DEFAULT(cvScalarAll(0)), + CvScalar up_diff CV_DEFAULT(cvScalarAll(0)), + CvConnectedComp* comp CV_DEFAULT(NULL), + int flags CV_DEFAULT(4), + CvArr* mask CV_DEFAULT(NULL)); + +/****************************************************************************************\ +* Feature detection * +\****************************************************************************************/ + +/** @brief Runs canny edge detector +@see cv::Canny +*/ +CVAPI(void) cvCanny( const CvArr* image, CvArr* edges, double threshold1, + double threshold2, int aperture_size CV_DEFAULT(3) ); + +/** @brief Calculates constraint image for corner detection + + Dx^2 * Dyy + Dxx * Dy^2 - 2 * Dx * Dy * Dxy. + Applying threshold to the result gives coordinates of corners +@see cv::preCornerDetect +*/ +CVAPI(void) cvPreCornerDetect( const CvArr* image, CvArr* corners, + int aperture_size CV_DEFAULT(3) ); + +/** @brief Calculates eigen values and vectors of 2x2 + gradient covariation matrix at every image pixel +@see cv::cornerEigenValsAndVecs +*/ +CVAPI(void) cvCornerEigenValsAndVecs( const CvArr* image, CvArr* eigenvv, + int block_size, int aperture_size CV_DEFAULT(3) ); + +/** @brief Calculates minimal eigenvalue for 2x2 gradient covariation matrix at + every image pixel +@see cv::cornerMinEigenVal +*/ +CVAPI(void) cvCornerMinEigenVal( const CvArr* image, CvArr* eigenval, + int block_size, int aperture_size CV_DEFAULT(3) ); + +/** @brief Harris corner detector: + + Calculates det(M) - k*(trace(M)^2), where M is 2x2 gradient covariation matrix for each pixel +@see cv::cornerHarris +*/ +CVAPI(void) cvCornerHarris( const CvArr* image, CvArr* harris_response, + int block_size, int aperture_size CV_DEFAULT(3), + double k CV_DEFAULT(0.04) ); + +/** @brief Adjust corner position using some sort of gradient search +@see cv::cornerSubPix +*/ +CVAPI(void) cvFindCornerSubPix( const CvArr* image, CvPoint2D32f* corners, + int count, CvSize win, CvSize zero_zone, + CvTermCriteria criteria ); + +/** @brief Finds a sparse set of points within the selected region + that seem to be easy to track +@see cv::goodFeaturesToTrack +*/ +CVAPI(void) cvGoodFeaturesToTrack( const CvArr* image, CvArr* eig_image, + CvArr* temp_image, CvPoint2D32f* corners, + int* corner_count, double quality_level, + double min_distance, + const CvArr* mask CV_DEFAULT(NULL), + int block_size CV_DEFAULT(3), + int use_harris CV_DEFAULT(0), + double k CV_DEFAULT(0.04) ); + +/** @brief Finds lines on binary image using one of several methods. + + line_storage is either memory storage or 1 x _max number of lines_ CvMat, its + number of columns is changed by the function. + method is one of CV_HOUGH_*; + rho, theta and threshold are used for each of those methods; + param1 ~ line length, param2 ~ line gap - for probabilistic, + param1 ~ srn, param2 ~ stn - for multi-scale +@see cv::HoughLines +*/ +CVAPI(CvSeq*) cvHoughLines2( CvArr* image, void* line_storage, int method, + double rho, double theta, int threshold, + double param1 CV_DEFAULT(0), double param2 CV_DEFAULT(0), + double min_theta CV_DEFAULT(0), double max_theta CV_DEFAULT(CV_PI)); + +/** @brief Finds circles in the image +@see cv::HoughCircles +*/ +CVAPI(CvSeq*) cvHoughCircles( CvArr* image, void* circle_storage, + int method, double dp, double min_dist, + double param1 CV_DEFAULT(100), + double param2 CV_DEFAULT(100), + int min_radius CV_DEFAULT(0), + int max_radius CV_DEFAULT(0)); + +/** @brief Fits a line into set of 2d or 3d points in a robust way (M-estimator technique) +@see cv::fitLine +*/ +CVAPI(void) cvFitLine( const CvArr* points, int dist_type, double param, + double reps, double aeps, float* line ); + +/****************************************************************************************\ +* Drawing * +\****************************************************************************************/ + +/****************************************************************************************\ +* Drawing functions work with images/matrices of arbitrary type. * +* For color images the channel order is BGR[A] * +* Antialiasing is supported only for 8-bit image now. * +* All the functions include parameter color that means rgb value (that may be * +* constructed with CV_RGB macro) for color images and brightness * +* for grayscale images. * +* If a drawn figure is partially or completely outside of the image, it is clipped.* +\****************************************************************************************/ + +#define CV_FILLED -1 + +#define CV_AA 16 + +/** @brief Draws 4-connected, 8-connected or antialiased line segment connecting two points +@see cv::line +*/ +CVAPI(void) cvLine( CvArr* img, CvPoint pt1, CvPoint pt2, + CvScalar color, int thickness CV_DEFAULT(1), + int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) ); + +/** @brief Draws a rectangle given two opposite corners of the rectangle (pt1 & pt2) + + if thickness<0 (e.g. thickness == CV_FILLED), the filled box is drawn +@see cv::rectangle +*/ +CVAPI(void) cvRectangle( CvArr* img, CvPoint pt1, CvPoint pt2, + CvScalar color, int thickness CV_DEFAULT(1), + int line_type CV_DEFAULT(8), + int shift CV_DEFAULT(0)); + +/** @brief Draws a rectangle specified by a CvRect structure +@see cv::rectangle +*/ +CVAPI(void) cvRectangleR( CvArr* img, CvRect r, + CvScalar color, int thickness CV_DEFAULT(1), + int line_type CV_DEFAULT(8), + int shift CV_DEFAULT(0)); + + +/** @brief Draws a circle with specified center and radius. + + Thickness works in the same way as with cvRectangle +@see cv::circle +*/ +CVAPI(void) cvCircle( CvArr* img, CvPoint center, int radius, + CvScalar color, int thickness CV_DEFAULT(1), + int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0)); + +/** @brief Draws ellipse outline, filled ellipse, elliptic arc or filled elliptic sector + + depending on _thickness_, _start_angle_ and _end_angle_ parameters. The resultant figure + is rotated by _angle_. All the angles are in degrees +@see cv::ellipse +*/ +CVAPI(void) cvEllipse( CvArr* img, CvPoint center, CvSize axes, + double angle, double start_angle, double end_angle, + CvScalar color, int thickness CV_DEFAULT(1), + int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0)); + +CV_INLINE void cvEllipseBox( CvArr* img, CvBox2D box, CvScalar color, + int thickness CV_DEFAULT(1), + int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) ) +{ + CvSize axes = cvSize( + cvRound(box.size.width*0.5), + cvRound(box.size.height*0.5) + ); + + cvEllipse( img, cvPointFrom32f( box.center ), axes, box.angle, + 0, 360, color, thickness, line_type, shift ); +} + +/** @brief Fills convex or monotonous polygon. +@see cv::fillConvexPoly +*/ +CVAPI(void) cvFillConvexPoly( CvArr* img, const CvPoint* pts, int npts, CvScalar color, + int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0)); + +/** @brief Fills an area bounded by one or more arbitrary polygons +@see cv::fillPoly +*/ +CVAPI(void) cvFillPoly( CvArr* img, CvPoint** pts, const int* npts, + int contours, CvScalar color, + int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) ); + +/** @brief Draws one or more polygonal curves +@see cv::polylines +*/ +CVAPI(void) cvPolyLine( CvArr* img, CvPoint** pts, const int* npts, int contours, + int is_closed, CvScalar color, int thickness CV_DEFAULT(1), + int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) ); + +#define cvDrawRect cvRectangle +#define cvDrawLine cvLine +#define cvDrawCircle cvCircle +#define cvDrawEllipse cvEllipse +#define cvDrawPolyLine cvPolyLine + +/** @brief Clips the line segment connecting *pt1 and *pt2 + by the rectangular window + + (0<=xptr will point to pt1 (or pt2, see left_to_right description) location in +the image. Returns the number of pixels on the line between the ending points. +@see cv::LineIterator +*/ +CVAPI(int) cvInitLineIterator( const CvArr* image, CvPoint pt1, CvPoint pt2, + CvLineIterator* line_iterator, + int connectivity CV_DEFAULT(8), + int left_to_right CV_DEFAULT(0)); + +#define CV_NEXT_LINE_POINT( line_iterator ) \ +{ \ + int _line_iterator_mask = (line_iterator).err < 0 ? -1 : 0; \ + (line_iterator).err += (line_iterator).minus_delta + \ + ((line_iterator).plus_delta & _line_iterator_mask); \ + (line_iterator).ptr += (line_iterator).minus_step + \ + ((line_iterator).plus_step & _line_iterator_mask); \ +} + + +#define CV_FONT_HERSHEY_SIMPLEX 0 +#define CV_FONT_HERSHEY_PLAIN 1 +#define CV_FONT_HERSHEY_DUPLEX 2 +#define CV_FONT_HERSHEY_COMPLEX 3 +#define CV_FONT_HERSHEY_TRIPLEX 4 +#define CV_FONT_HERSHEY_COMPLEX_SMALL 5 +#define CV_FONT_HERSHEY_SCRIPT_SIMPLEX 6 +#define CV_FONT_HERSHEY_SCRIPT_COMPLEX 7 + +#define CV_FONT_ITALIC 16 + +#define CV_FONT_VECTOR0 CV_FONT_HERSHEY_SIMPLEX + + +/** Font structure */ +typedef struct CvFont +{ + const char* nameFont; //Qt:nameFont + CvScalar color; //Qt:ColorFont -> cvScalar(blue_component, green_component, red_component[, alpha_component]) + int font_face; //Qt: bool italic /** =CV_FONT_* */ + const int* ascii; //!< font data and metrics + const int* greek; + const int* cyrillic; + float hscale, vscale; + float shear; //!< slope coefficient: 0 - normal, >0 - italic + int thickness; //!< Qt: weight /** letters thickness */ + float dx; //!< horizontal interval between letters + int line_type; //!< Qt: PointSize +} +CvFont; + +/** @brief Initializes font structure (OpenCV 1.x API). + +The function initializes the font structure that can be passed to text rendering functions. + +@param font Pointer to the font structure initialized by the function +@param font_face Font name identifier. See cv::HersheyFonts and corresponding old CV_* identifiers. +@param hscale Horizontal scale. If equal to 1.0f , the characters have the original width +depending on the font type. If equal to 0.5f , the characters are of half the original width. +@param vscale Vertical scale. If equal to 1.0f , the characters have the original height depending +on the font type. If equal to 0.5f , the characters are of half the original height. +@param shear Approximate tangent of the character slope relative to the vertical line. A zero +value means a non-italic font, 1.0f means about a 45 degree slope, etc. +@param thickness Thickness of the text strokes +@param line_type Type of the strokes, see line description + +@sa cvPutText + */ +CVAPI(void) cvInitFont( CvFont* font, int font_face, + double hscale, double vscale, + double shear CV_DEFAULT(0), + int thickness CV_DEFAULT(1), + int line_type CV_DEFAULT(8)); + +CV_INLINE CvFont cvFont( double scale, int thickness CV_DEFAULT(1) ) +{ + CvFont font; + cvInitFont( &font, CV_FONT_HERSHEY_PLAIN, scale, scale, 0, thickness, CV_AA ); + return font; +} + +/** @brief Renders text stroke with specified font and color at specified location. + CvFont should be initialized with cvInitFont +@see cvInitFont, cvGetTextSize, cvFont, cv::putText +*/ +CVAPI(void) cvPutText( CvArr* img, const char* text, CvPoint org, + const CvFont* font, CvScalar color ); + +/** @brief Calculates bounding box of text stroke (useful for alignment) +@see cv::getTextSize +*/ +CVAPI(void) cvGetTextSize( const char* text_string, const CvFont* font, + CvSize* text_size, int* baseline ); + +/** @brief Unpacks color value + +if arrtype is CV_8UC?, _color_ is treated as packed color value, otherwise the first channels +(depending on arrtype) of destination scalar are set to the same value = _color_ +*/ +CVAPI(CvScalar) cvColorToScalar( double packed_color, int arrtype ); + +/** @brief Returns the polygon points which make up the given ellipse. + +The ellipse is define by the box of size 'axes' rotated 'angle' around the 'center'. A partial +sweep of the ellipse arc can be done by specifying arc_start and arc_end to be something other than +0 and 360, respectively. The input array 'pts' must be large enough to hold the result. The total +number of points stored into 'pts' is returned by this function. +@see cv::ellipse2Poly +*/ +CVAPI(int) cvEllipse2Poly( CvPoint center, CvSize axes, + int angle, int arc_start, int arc_end, CvPoint * pts, int delta ); + +/** @brief Draws contour outlines or filled interiors on the image +@see cv::drawContours +*/ +CVAPI(void) cvDrawContours( CvArr *img, CvSeq* contour, + CvScalar external_color, CvScalar hole_color, + int max_level, int thickness CV_DEFAULT(1), + int line_type CV_DEFAULT(8), + CvPoint offset CV_DEFAULT(cvPoint(0,0))); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/imgproc/segmentation.hpp b/3rdParty/opencv-4.11.0/opencv2/imgproc/segmentation.hpp index b2df4fcaca..916b0e3bbc 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgproc/segmentation.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/imgproc/segmentation.hpp @@ -1,141 +1,141 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_IMGPROC_SEGMENTATION_HPP -#define OPENCV_IMGPROC_SEGMENTATION_HPP - -#include "opencv2/imgproc.hpp" - -namespace cv { - -namespace segmentation { - -//! @addtogroup imgproc_segmentation -//! @{ - - -/** @brief Intelligent Scissors image segmentation - * - * This class is used to find the path (contour) between two points - * which can be used for image segmentation. - * - * Usage example: - * @snippet snippets/imgproc_segmentation.cpp usage_example_intelligent_scissors - * - * Reference: "Intelligent Scissors for Image Composition" - * algorithm designed by Eric N. Mortensen and William A. Barrett, Brigham Young University - * @cite Mortensen95intelligentscissors - */ -class CV_EXPORTS_W_SIMPLE IntelligentScissorsMB -{ -public: - CV_WRAP - IntelligentScissorsMB(); - - /** @brief Specify weights of feature functions - * - * Consider keeping weights normalized (sum of weights equals to 1.0) - * Discrete dynamic programming (DP) goal is minimization of costs between pixels. - * - * @param weight_non_edge Specify cost of non-edge pixels (default: 0.43f) - * @param weight_gradient_direction Specify cost of gradient direction function (default: 0.43f) - * @param weight_gradient_magnitude Specify cost of gradient magnitude function (default: 0.14f) - */ - CV_WRAP - IntelligentScissorsMB& setWeights(float weight_non_edge, float weight_gradient_direction, float weight_gradient_magnitude); - - /** @brief Specify gradient magnitude max value threshold - * - * Zero limit value is used to disable gradient magnitude thresholding (default behavior, as described in original article). - * Otherwize pixels with `gradient magnitude >= threshold` have zero cost. - * - * @note Thresholding should be used for images with irregular regions (to avoid stuck on parameters from high-contract areas, like embedded logos). - * - * @param gradient_magnitude_threshold_max Specify gradient magnitude max value threshold (default: 0, disabled) - */ - CV_WRAP - IntelligentScissorsMB& setGradientMagnitudeMaxLimit(float gradient_magnitude_threshold_max = 0.0f); - - /** @brief Switch to "Laplacian Zero-Crossing" edge feature extractor and specify its parameters - * - * This feature extractor is used by default according to article. - * - * Implementation has additional filtering for regions with low-amplitude noise. - * This filtering is enabled through parameter of minimal gradient amplitude (use some small value 4, 8, 16). - * - * @note Current implementation of this feature extractor is based on processing of grayscale images (color image is converted to grayscale image first). - * - * @note Canny edge detector is a bit slower, but provides better results (especially on color images): use setEdgeFeatureCannyParameters(). - * - * @param gradient_magnitude_min_value Minimal gradient magnitude value for edge pixels (default: 0, check is disabled) - */ - CV_WRAP - IntelligentScissorsMB& setEdgeFeatureZeroCrossingParameters(float gradient_magnitude_min_value = 0.0f); - - /** @brief Switch edge feature extractor to use Canny edge detector - * - * @note "Laplacian Zero-Crossing" feature extractor is used by default (following to original article) - * - * @sa Canny - */ - CV_WRAP - IntelligentScissorsMB& setEdgeFeatureCannyParameters( - double threshold1, double threshold2, - int apertureSize = 3, bool L2gradient = false - ); - - /** @brief Specify input image and extract image features - * - * @param image input image. Type is #CV_8UC1 / #CV_8UC3 - */ - CV_WRAP - IntelligentScissorsMB& applyImage(InputArray image); - - /** @brief Specify custom features of input image - * - * Customized advanced variant of applyImage() call. - * - * @param non_edge Specify cost of non-edge pixels. Type is CV_8UC1. Expected values are `{0, 1}`. - * @param gradient_direction Specify gradient direction feature. Type is CV_32FC2. Values are expected to be normalized: `x^2 + y^2 == 1` - * @param gradient_magnitude Specify cost of gradient magnitude function: Type is CV_32FC1. Values should be in range `[0, 1]`. - * @param image **Optional parameter**. Must be specified if subset of features is specified (non-specified features are calculated internally) - */ - CV_WRAP - IntelligentScissorsMB& applyImageFeatures( - InputArray non_edge, InputArray gradient_direction, InputArray gradient_magnitude, - InputArray image = noArray() - ); - - /** @brief Prepares a map of optimal paths for the given source point on the image - * - * @note applyImage() / applyImageFeatures() must be called before this call - * - * @param sourcePt The source point used to find the paths - */ - CV_WRAP void buildMap(const Point& sourcePt); - - /** @brief Extracts optimal contour for the given target point on the image - * - * @note buildMap() must be called before this call - * - * @param targetPt The target point - * @param[out] contour The list of pixels which contains optimal path between the source and the target points of the image. Type is CV_32SC2 (compatible with `std::vector`) - * @param backward Flag to indicate reverse order of retrieved pixels (use "true" value to fetch points from the target to the source point) - */ - CV_WRAP void getContour(const Point& targetPt, OutputArray contour, bool backward = false) const; - -#ifndef CV_DOXYGEN - struct Impl; - inline Impl* getImpl() const { return impl.get(); } -protected: - std::shared_ptr impl; -#endif -}; - -//! @} - -} // namespace segmentation -} // namespace cv - -#endif // OPENCV_IMGPROC_SEGMENTATION_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_IMGPROC_SEGMENTATION_HPP +#define OPENCV_IMGPROC_SEGMENTATION_HPP + +#include "opencv2/imgproc.hpp" + +namespace cv { + +namespace segmentation { + +//! @addtogroup imgproc_segmentation +//! @{ + + +/** @brief Intelligent Scissors image segmentation + * + * This class is used to find the path (contour) between two points + * which can be used for image segmentation. + * + * Usage example: + * @snippet snippets/imgproc_segmentation.cpp usage_example_intelligent_scissors + * + * Reference: "Intelligent Scissors for Image Composition" + * algorithm designed by Eric N. Mortensen and William A. Barrett, Brigham Young University + * @cite Mortensen95intelligentscissors + */ +class CV_EXPORTS_W_SIMPLE IntelligentScissorsMB +{ +public: + CV_WRAP + IntelligentScissorsMB(); + + /** @brief Specify weights of feature functions + * + * Consider keeping weights normalized (sum of weights equals to 1.0) + * Discrete dynamic programming (DP) goal is minimization of costs between pixels. + * + * @param weight_non_edge Specify cost of non-edge pixels (default: 0.43f) + * @param weight_gradient_direction Specify cost of gradient direction function (default: 0.43f) + * @param weight_gradient_magnitude Specify cost of gradient magnitude function (default: 0.14f) + */ + CV_WRAP + IntelligentScissorsMB& setWeights(float weight_non_edge, float weight_gradient_direction, float weight_gradient_magnitude); + + /** @brief Specify gradient magnitude max value threshold + * + * Zero limit value is used to disable gradient magnitude thresholding (default behavior, as described in original article). + * Otherwize pixels with `gradient magnitude >= threshold` have zero cost. + * + * @note Thresholding should be used for images with irregular regions (to avoid stuck on parameters from high-contract areas, like embedded logos). + * + * @param gradient_magnitude_threshold_max Specify gradient magnitude max value threshold (default: 0, disabled) + */ + CV_WRAP + IntelligentScissorsMB& setGradientMagnitudeMaxLimit(float gradient_magnitude_threshold_max = 0.0f); + + /** @brief Switch to "Laplacian Zero-Crossing" edge feature extractor and specify its parameters + * + * This feature extractor is used by default according to article. + * + * Implementation has additional filtering for regions with low-amplitude noise. + * This filtering is enabled through parameter of minimal gradient amplitude (use some small value 4, 8, 16). + * + * @note Current implementation of this feature extractor is based on processing of grayscale images (color image is converted to grayscale image first). + * + * @note Canny edge detector is a bit slower, but provides better results (especially on color images): use setEdgeFeatureCannyParameters(). + * + * @param gradient_magnitude_min_value Minimal gradient magnitude value for edge pixels (default: 0, check is disabled) + */ + CV_WRAP + IntelligentScissorsMB& setEdgeFeatureZeroCrossingParameters(float gradient_magnitude_min_value = 0.0f); + + /** @brief Switch edge feature extractor to use Canny edge detector + * + * @note "Laplacian Zero-Crossing" feature extractor is used by default (following to original article) + * + * @sa Canny + */ + CV_WRAP + IntelligentScissorsMB& setEdgeFeatureCannyParameters( + double threshold1, double threshold2, + int apertureSize = 3, bool L2gradient = false + ); + + /** @brief Specify input image and extract image features + * + * @param image input image. Type is #CV_8UC1 / #CV_8UC3 + */ + CV_WRAP + IntelligentScissorsMB& applyImage(InputArray image); + + /** @brief Specify custom features of input image + * + * Customized advanced variant of applyImage() call. + * + * @param non_edge Specify cost of non-edge pixels. Type is CV_8UC1. Expected values are `{0, 1}`. + * @param gradient_direction Specify gradient direction feature. Type is CV_32FC2. Values are expected to be normalized: `x^2 + y^2 == 1` + * @param gradient_magnitude Specify cost of gradient magnitude function: Type is CV_32FC1. Values should be in range `[0, 1]`. + * @param image **Optional parameter**. Must be specified if subset of features is specified (non-specified features are calculated internally) + */ + CV_WRAP + IntelligentScissorsMB& applyImageFeatures( + InputArray non_edge, InputArray gradient_direction, InputArray gradient_magnitude, + InputArray image = noArray() + ); + + /** @brief Prepares a map of optimal paths for the given source point on the image + * + * @note applyImage() / applyImageFeatures() must be called before this call + * + * @param sourcePt The source point used to find the paths + */ + CV_WRAP void buildMap(const Point& sourcePt); + + /** @brief Extracts optimal contour for the given target point on the image + * + * @note buildMap() must be called before this call + * + * @param targetPt The target point + * @param[out] contour The list of pixels which contains optimal path between the source and the target points of the image. Type is CV_32SC2 (compatible with `std::vector`) + * @param backward Flag to indicate reverse order of retrieved pixels (use "true" value to fetch points from the target to the source point) + */ + CV_WRAP void getContour(const Point& targetPt, OutputArray contour, bool backward = false) const; + +#ifndef CV_DOXYGEN + struct Impl; + inline Impl* getImpl() const { return impl.get(); } +protected: + std::shared_ptr impl; +#endif +}; + +//! @} + +} // namespace segmentation +} // namespace cv + +#endif // OPENCV_IMGPROC_SEGMENTATION_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/imgproc/types_c.h b/3rdParty/opencv-4.11.0/opencv2/imgproc/types_c.h index 255ed0c37f..af25ac1c1b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgproc/types_c.h +++ b/3rdParty/opencv-4.11.0/opencv2/imgproc/types_c.h @@ -1,660 +1,660 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_IMGPROC_TYPES_C_H -#define OPENCV_IMGPROC_TYPES_C_H - -#include "opencv2/core/core_c.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** @addtogroup imgproc_c - @{ -*/ - -/** Connected component structure */ -typedef struct CvConnectedComp -{ - double area; /** DBL_EPSILON ? 1./std::sqrt(am00) : 0; - } - operator cv::Moments() const - { - return cv::Moments(m00, m10, m01, m20, m11, m02, m30, m21, m12, m03); - } -#endif -} -CvMoments; - -#ifdef __cplusplus -} // extern "C" - -CV_INLINE CvMoments cvMoments() -{ -#if !defined(CV__ENABLE_C_API_CTORS) - CvMoments self = CV_STRUCT_INITIALIZER; return self; -#else - return CvMoments(); -#endif -} - -CV_INLINE CvMoments cvMoments(const cv::Moments& m) -{ -#if !defined(CV__ENABLE_C_API_CTORS) - double am00 = std::abs(m.m00); - CvMoments self = { - m.m00, m.m10, m.m01, m.m20, m.m11, m.m02, m.m30, m.m21, m.m12, m.m03, - m.mu20, m.mu11, m.mu02, m.mu30, m.mu21, m.mu12, m.mu03, - am00 > DBL_EPSILON ? 1./std::sqrt(am00) : 0 - }; - return self; -#else - return CvMoments(m); -#endif -} - -extern "C" { -#endif // __cplusplus - -/** Hu invariants */ -typedef struct CvHuMoments -{ - double hu1, hu2, hu3, hu4, hu5, hu6, hu7; /**< Hu invariants */ -} -CvHuMoments; - -/** Template matching methods */ -enum -{ - CV_TM_SQDIFF =0, - CV_TM_SQDIFF_NORMED =1, - CV_TM_CCORR =2, - CV_TM_CCORR_NORMED =3, - CV_TM_CCOEFF =4, - CV_TM_CCOEFF_NORMED =5 -}; - -typedef float (CV_CDECL * CvDistanceFunction)( const float* a, const float* b, void* user_param ); - -/** Contour retrieval modes */ -enum -{ - CV_RETR_EXTERNAL=0, - CV_RETR_LIST=1, - CV_RETR_CCOMP=2, - CV_RETR_TREE=3, - CV_RETR_FLOODFILL=4 -}; - -/** Contour approximation methods */ -enum -{ - CV_CHAIN_CODE=0, - CV_CHAIN_APPROX_NONE=1, - CV_CHAIN_APPROX_SIMPLE=2, - CV_CHAIN_APPROX_TC89_L1=3, - CV_CHAIN_APPROX_TC89_KCOS=4, - CV_LINK_RUNS=5 -}; - -/* -Internal structure that is used for sequential retrieving contours from the image. -It supports both hierarchical and plane variants of Suzuki algorithm. -*/ -typedef struct _CvContourScanner* CvContourScanner; - -/** Freeman chain reader state */ -typedef struct CvChainPtReader -{ - CV_SEQ_READER_FIELDS() - char code; - CvPoint pt; - schar deltas[8][2]; -} -CvChainPtReader; - -/** initializes 8-element array for fast access to 3x3 neighborhood of a pixel */ -#define CV_INIT_3X3_DELTAS( deltas, step, nch ) \ - ((deltas)[0] = (nch), (deltas)[1] = -(step) + (nch), \ - (deltas)[2] = -(step), (deltas)[3] = -(step) - (nch), \ - (deltas)[4] = -(nch), (deltas)[5] = (step) - (nch), \ - (deltas)[6] = (step), (deltas)[7] = (step) + (nch)) - - -/** Contour approximation algorithms */ -enum -{ - CV_POLY_APPROX_DP = 0 -}; - -/** Shape matching methods */ -enum -{ - CV_CONTOURS_MATCH_I1 =1, //!< \f[I_1(A,B) = \sum _{i=1...7} \left | \frac{1}{m^A_i} - \frac{1}{m^B_i} \right |\f] - CV_CONTOURS_MATCH_I2 =2, //!< \f[I_2(A,B) = \sum _{i=1...7} \left | m^A_i - m^B_i \right |\f] - CV_CONTOURS_MATCH_I3 =3 //!< \f[I_3(A,B) = \max _{i=1...7} \frac{ \left| m^A_i - m^B_i \right| }{ \left| m^A_i \right| }\f] -}; - -/** Shape orientation */ -enum -{ - CV_CLOCKWISE =1, - CV_COUNTER_CLOCKWISE =2 -}; - - -/** Convexity defect */ -typedef struct CvConvexityDefect -{ - CvPoint* start; /**< point of the contour where the defect begins */ - CvPoint* end; /**< point of the contour where the defect ends */ - CvPoint* depth_point; /**< the farthest from the convex hull point within the defect */ - float depth; /**< distance between the farthest point and the convex hull */ -} CvConvexityDefect; - - -/** Histogram comparison methods */ -enum -{ - CV_COMP_CORREL =0, - CV_COMP_CHISQR =1, - CV_COMP_INTERSECT =2, - CV_COMP_BHATTACHARYYA =3, - CV_COMP_HELLINGER =CV_COMP_BHATTACHARYYA, - CV_COMP_CHISQR_ALT =4, - CV_COMP_KL_DIV =5 -}; - -/** Mask size for distance transform */ -enum -{ - CV_DIST_MASK_3 =3, - CV_DIST_MASK_5 =5, - CV_DIST_MASK_PRECISE =0 -}; - -/** Content of output label array: connected components or pixels */ -enum -{ - CV_DIST_LABEL_CCOMP = 0, - CV_DIST_LABEL_PIXEL = 1 -}; - -/** Distance types for Distance Transform and M-estimators */ -enum -{ - CV_DIST_USER =-1, /**< User defined distance */ - CV_DIST_L1 =1, /**< distance = |x1-x2| + |y1-y2| */ - CV_DIST_L2 =2, /**< the simple euclidean distance */ - CV_DIST_C =3, /**< distance = max(|x1-x2|,|y1-y2|) */ - CV_DIST_L12 =4, /**< L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1)) */ - CV_DIST_FAIR =5, /**< distance = c^2(|x|/c-log(1+|x|/c)), c = 1.3998 */ - CV_DIST_WELSCH =6, /**< distance = c^2/2(1-exp(-(x/c)^2)), c = 2.9846 */ - CV_DIST_HUBER =7 /**< distance = |x| threshold ? max_value : 0 */ - CV_THRESH_BINARY_INV =1, /**< value = value > threshold ? 0 : max_value */ - CV_THRESH_TRUNC =2, /**< value = value > threshold ? threshold : value */ - CV_THRESH_TOZERO =3, /**< value = value > threshold ? value : 0 */ - CV_THRESH_TOZERO_INV =4, /**< value = value > threshold ? 0 : value */ - CV_THRESH_MASK =7, - CV_THRESH_OTSU =8, /**< use Otsu algorithm to choose the optimal threshold value; - combine the flag with one of the above CV_THRESH_* values */ - CV_THRESH_TRIANGLE =16 /**< use Triangle algorithm to choose the optimal threshold value; - combine the flag with one of the above CV_THRESH_* values, but not - with CV_THRESH_OTSU */ -}; - -/** Adaptive threshold methods */ -enum -{ - CV_ADAPTIVE_THRESH_MEAN_C =0, - CV_ADAPTIVE_THRESH_GAUSSIAN_C =1 -}; - -/** FloodFill flags */ -enum -{ - CV_FLOODFILL_FIXED_RANGE =(1 << 16), - CV_FLOODFILL_MASK_ONLY =(1 << 17) -}; - - -/** Canny edge detector flags */ -enum -{ - CV_CANNY_L2_GRADIENT =(1 << 31) -}; - -/** Variants of a Hough transform */ -enum -{ - CV_HOUGH_STANDARD =0, - CV_HOUGH_PROBABILISTIC =1, - CV_HOUGH_MULTI_SCALE =2, - CV_HOUGH_GRADIENT =3 -}; - - -/* Fast search data structures */ -struct CvFeatureTree; -struct CvLSH; -struct CvLSHOperations; - -/** @} */ - -#ifdef __cplusplus -} -#endif - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_IMGPROC_TYPES_C_H +#define OPENCV_IMGPROC_TYPES_C_H + +#include "opencv2/core/core_c.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @addtogroup imgproc_c + @{ +*/ + +/** Connected component structure */ +typedef struct CvConnectedComp +{ + double area; /** DBL_EPSILON ? 1./std::sqrt(am00) : 0; + } + operator cv::Moments() const + { + return cv::Moments(m00, m10, m01, m20, m11, m02, m30, m21, m12, m03); + } +#endif +} +CvMoments; + +#ifdef __cplusplus +} // extern "C" + +CV_INLINE CvMoments cvMoments() +{ +#if !defined(CV__ENABLE_C_API_CTORS) + CvMoments self = CV_STRUCT_INITIALIZER; return self; +#else + return CvMoments(); +#endif +} + +CV_INLINE CvMoments cvMoments(const cv::Moments& m) +{ +#if !defined(CV__ENABLE_C_API_CTORS) + double am00 = std::abs(m.m00); + CvMoments self = { + m.m00, m.m10, m.m01, m.m20, m.m11, m.m02, m.m30, m.m21, m.m12, m.m03, + m.mu20, m.mu11, m.mu02, m.mu30, m.mu21, m.mu12, m.mu03, + am00 > DBL_EPSILON ? 1./std::sqrt(am00) : 0 + }; + return self; +#else + return CvMoments(m); +#endif +} + +extern "C" { +#endif // __cplusplus + +/** Hu invariants */ +typedef struct CvHuMoments +{ + double hu1, hu2, hu3, hu4, hu5, hu6, hu7; /**< Hu invariants */ +} +CvHuMoments; + +/** Template matching methods */ +enum +{ + CV_TM_SQDIFF =0, + CV_TM_SQDIFF_NORMED =1, + CV_TM_CCORR =2, + CV_TM_CCORR_NORMED =3, + CV_TM_CCOEFF =4, + CV_TM_CCOEFF_NORMED =5 +}; + +typedef float (CV_CDECL * CvDistanceFunction)( const float* a, const float* b, void* user_param ); + +/** Contour retrieval modes */ +enum +{ + CV_RETR_EXTERNAL=0, + CV_RETR_LIST=1, + CV_RETR_CCOMP=2, + CV_RETR_TREE=3, + CV_RETR_FLOODFILL=4 +}; + +/** Contour approximation methods */ +enum +{ + CV_CHAIN_CODE=0, + CV_CHAIN_APPROX_NONE=1, + CV_CHAIN_APPROX_SIMPLE=2, + CV_CHAIN_APPROX_TC89_L1=3, + CV_CHAIN_APPROX_TC89_KCOS=4, + CV_LINK_RUNS=5 +}; + +/* +Internal structure that is used for sequential retrieving contours from the image. +It supports both hierarchical and plane variants of Suzuki algorithm. +*/ +typedef struct _CvContourScanner* CvContourScanner; + +/** Freeman chain reader state */ +typedef struct CvChainPtReader +{ + CV_SEQ_READER_FIELDS() + char code; + CvPoint pt; + schar deltas[8][2]; +} +CvChainPtReader; + +/** initializes 8-element array for fast access to 3x3 neighborhood of a pixel */ +#define CV_INIT_3X3_DELTAS( deltas, step, nch ) \ + ((deltas)[0] = (nch), (deltas)[1] = -(step) + (nch), \ + (deltas)[2] = -(step), (deltas)[3] = -(step) - (nch), \ + (deltas)[4] = -(nch), (deltas)[5] = (step) - (nch), \ + (deltas)[6] = (step), (deltas)[7] = (step) + (nch)) + + +/** Contour approximation algorithms */ +enum +{ + CV_POLY_APPROX_DP = 0 +}; + +/** Shape matching methods */ +enum +{ + CV_CONTOURS_MATCH_I1 =1, //!< \f[I_1(A,B) = \sum _{i=1...7} \left | \frac{1}{m^A_i} - \frac{1}{m^B_i} \right |\f] + CV_CONTOURS_MATCH_I2 =2, //!< \f[I_2(A,B) = \sum _{i=1...7} \left | m^A_i - m^B_i \right |\f] + CV_CONTOURS_MATCH_I3 =3 //!< \f[I_3(A,B) = \max _{i=1...7} \frac{ \left| m^A_i - m^B_i \right| }{ \left| m^A_i \right| }\f] +}; + +/** Shape orientation */ +enum +{ + CV_CLOCKWISE =1, + CV_COUNTER_CLOCKWISE =2 +}; + + +/** Convexity defect */ +typedef struct CvConvexityDefect +{ + CvPoint* start; /**< point of the contour where the defect begins */ + CvPoint* end; /**< point of the contour where the defect ends */ + CvPoint* depth_point; /**< the farthest from the convex hull point within the defect */ + float depth; /**< distance between the farthest point and the convex hull */ +} CvConvexityDefect; + + +/** Histogram comparison methods */ +enum +{ + CV_COMP_CORREL =0, + CV_COMP_CHISQR =1, + CV_COMP_INTERSECT =2, + CV_COMP_BHATTACHARYYA =3, + CV_COMP_HELLINGER =CV_COMP_BHATTACHARYYA, + CV_COMP_CHISQR_ALT =4, + CV_COMP_KL_DIV =5 +}; + +/** Mask size for distance transform */ +enum +{ + CV_DIST_MASK_3 =3, + CV_DIST_MASK_5 =5, + CV_DIST_MASK_PRECISE =0 +}; + +/** Content of output label array: connected components or pixels */ +enum +{ + CV_DIST_LABEL_CCOMP = 0, + CV_DIST_LABEL_PIXEL = 1 +}; + +/** Distance types for Distance Transform and M-estimators */ +enum +{ + CV_DIST_USER =-1, /**< User defined distance */ + CV_DIST_L1 =1, /**< distance = |x1-x2| + |y1-y2| */ + CV_DIST_L2 =2, /**< the simple euclidean distance */ + CV_DIST_C =3, /**< distance = max(|x1-x2|,|y1-y2|) */ + CV_DIST_L12 =4, /**< L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1)) */ + CV_DIST_FAIR =5, /**< distance = c^2(|x|/c-log(1+|x|/c)), c = 1.3998 */ + CV_DIST_WELSCH =6, /**< distance = c^2/2(1-exp(-(x/c)^2)), c = 2.9846 */ + CV_DIST_HUBER =7 /**< distance = |x| threshold ? max_value : 0 */ + CV_THRESH_BINARY_INV =1, /**< value = value > threshold ? 0 : max_value */ + CV_THRESH_TRUNC =2, /**< value = value > threshold ? threshold : value */ + CV_THRESH_TOZERO =3, /**< value = value > threshold ? value : 0 */ + CV_THRESH_TOZERO_INV =4, /**< value = value > threshold ? 0 : value */ + CV_THRESH_MASK =7, + CV_THRESH_OTSU =8, /**< use Otsu algorithm to choose the optimal threshold value; + combine the flag with one of the above CV_THRESH_* values */ + CV_THRESH_TRIANGLE =16 /**< use Triangle algorithm to choose the optimal threshold value; + combine the flag with one of the above CV_THRESH_* values, but not + with CV_THRESH_OTSU */ +}; + +/** Adaptive threshold methods */ +enum +{ + CV_ADAPTIVE_THRESH_MEAN_C =0, + CV_ADAPTIVE_THRESH_GAUSSIAN_C =1 +}; + +/** FloodFill flags */ +enum +{ + CV_FLOODFILL_FIXED_RANGE =(1 << 16), + CV_FLOODFILL_MASK_ONLY =(1 << 17) +}; + + +/** Canny edge detector flags */ +enum +{ + CV_CANNY_L2_GRADIENT =(1 << 31) +}; + +/** Variants of a Hough transform */ +enum +{ + CV_HOUGH_STANDARD =0, + CV_HOUGH_PROBABILISTIC =1, + CV_HOUGH_MULTI_SCALE =2, + CV_HOUGH_GRADIENT =3 +}; + + +/* Fast search data structures */ +struct CvFeatureTree; +struct CvLSH; +struct CvLSHOperations; + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/ml.hpp b/3rdParty/opencv-4.11.0/opencv2/ml.hpp index d537ab7759..4e62c98dcc 100644 --- a/3rdParty/opencv-4.11.0/opencv2/ml.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/ml.hpp @@ -1,1956 +1,1956 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2014, Itseez Inc, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_ML_HPP -#define OPENCV_ML_HPP - -#ifdef __cplusplus -# include "opencv2/core.hpp" -#endif - -#ifdef __cplusplus - -#include -#include -#include - -/** - @defgroup ml Machine Learning - - The Machine Learning Library (MLL) is a set of classes and functions for statistical - classification, regression, and clustering of data. - - Most of the classification and regression algorithms are implemented as C++ classes. As the - algorithms have different sets of features (like an ability to handle missing measurements or - categorical input variables), there is a little common ground between the classes. This common - ground is defined by the class cv::ml::StatModel that all the other ML classes are derived from. - - See detailed overview here: @ref ml_intro. - */ - -namespace cv -{ - -namespace ml -{ - -//! @addtogroup ml -//! @{ - -/** @brief Variable types */ -enum VariableTypes -{ - VAR_NUMERICAL =0, //!< same as VAR_ORDERED - VAR_ORDERED =0, //!< ordered variables - VAR_CATEGORICAL =1 //!< categorical variables -}; - -/** @brief %Error types */ -enum ErrorTypes -{ - TEST_ERROR = 0, - TRAIN_ERROR = 1 -}; - -/** @brief Sample types */ -enum SampleTypes -{ - ROW_SAMPLE = 0, //!< each training sample is a row of samples - COL_SAMPLE = 1 //!< each training sample occupies a column of samples -}; - -/** @brief The structure represents the logarithmic grid range of statmodel parameters. - -It is used for optimizing statmodel accuracy by varying model parameters, the accuracy estimate -being computed by cross-validation. - */ -class CV_EXPORTS_W ParamGrid -{ -public: - /** @brief Default constructor */ - ParamGrid(); - /** @brief Constructor with parameters */ - ParamGrid(double _minVal, double _maxVal, double _logStep); - - CV_PROP_RW double minVal; //!< Minimum value of the statmodel parameter. Default value is 0. - CV_PROP_RW double maxVal; //!< Maximum value of the statmodel parameter. Default value is 0. - /** @brief Logarithmic step for iterating the statmodel parameter. - - The grid determines the following iteration sequence of the statmodel parameter values: - \f[(minVal, minVal*step, minVal*{step}^2, \dots, minVal*{logStep}^n),\f] - where \f$n\f$ is the maximal index satisfying - \f[\texttt{minVal} * \texttt{logStep} ^n < \texttt{maxVal}\f] - The grid is logarithmic, so logStep must always be greater than 1. Default value is 1. - */ - CV_PROP_RW double logStep; - - /** @brief Creates a ParamGrid Ptr that can be given to the %SVM::trainAuto method - - @param minVal minimum value of the parameter grid - @param maxVal maximum value of the parameter grid - @param logstep Logarithmic step for iterating the statmodel parameter - */ - CV_WRAP static Ptr create(double minVal=0., double maxVal=0., double logstep=1.); -}; - -/** @brief Class encapsulating training data. - -Please note that the class only specifies the interface of training data, but not implementation. -All the statistical model classes in _ml_ module accepts Ptr\ as parameter. In other -words, you can create your own class derived from TrainData and pass smart pointer to the instance -of this class into StatModel::train. - -@sa @ref ml_intro_data - */ -class CV_EXPORTS_W TrainData -{ -public: - static inline float missingValue() { return FLT_MAX; } - virtual ~TrainData(); - - CV_WRAP virtual int getLayout() const = 0; - CV_WRAP virtual int getNTrainSamples() const = 0; - CV_WRAP virtual int getNTestSamples() const = 0; - CV_WRAP virtual int getNSamples() const = 0; - CV_WRAP virtual int getNVars() const = 0; - CV_WRAP virtual int getNAllVars() const = 0; - - CV_WRAP virtual void getSample(InputArray varIdx, int sidx, float* buf) const = 0; - CV_WRAP virtual Mat getSamples() const = 0; - CV_WRAP virtual Mat getMissing() const = 0; - - /** @brief Returns matrix of train samples - - @param layout The requested layout. If it's different from the initial one, the matrix is - transposed. See ml::SampleTypes. - @param compressSamples if true, the function returns only the training samples (specified by - sampleIdx) - @param compressVars if true, the function returns the shorter training samples, containing only - the active variables. - - In current implementation the function tries to avoid physical data copying and returns the - matrix stored inside TrainData (unless the transposition or compression is needed). - */ - CV_WRAP virtual Mat getTrainSamples(int layout=ROW_SAMPLE, - bool compressSamples=true, - bool compressVars=true) const = 0; - - /** @brief Returns the vector of responses - - The function returns ordered or the original categorical responses. Usually it's used in - regression algorithms. - */ - CV_WRAP virtual Mat getTrainResponses() const = 0; - - /** @brief Returns the vector of normalized categorical responses - - The function returns vector of responses. Each response is integer from `0` to `-1`. The actual label value can be retrieved then from the class label vector, see - TrainData::getClassLabels. - */ - CV_WRAP virtual Mat getTrainNormCatResponses() const = 0; - CV_WRAP virtual Mat getTestResponses() const = 0; - CV_WRAP virtual Mat getTestNormCatResponses() const = 0; - CV_WRAP virtual Mat getResponses() const = 0; - CV_WRAP virtual Mat getNormCatResponses() const = 0; - CV_WRAP virtual Mat getSampleWeights() const = 0; - CV_WRAP virtual Mat getTrainSampleWeights() const = 0; - CV_WRAP virtual Mat getTestSampleWeights() const = 0; - CV_WRAP virtual Mat getVarIdx() const = 0; - CV_WRAP virtual Mat getVarType() const = 0; - CV_WRAP virtual Mat getVarSymbolFlags() const = 0; - CV_WRAP virtual int getResponseType() const = 0; - CV_WRAP virtual Mat getTrainSampleIdx() const = 0; - CV_WRAP virtual Mat getTestSampleIdx() const = 0; - CV_WRAP virtual void getValues(int vi, InputArray sidx, float* values) const = 0; - virtual void getNormCatValues(int vi, InputArray sidx, int* values) const = 0; - CV_WRAP virtual Mat getDefaultSubstValues() const = 0; - - CV_WRAP virtual int getCatCount(int vi) const = 0; - - /** @brief Returns the vector of class labels - - The function returns vector of unique labels occurred in the responses. - */ - CV_WRAP virtual Mat getClassLabels() const = 0; - - CV_WRAP virtual Mat getCatOfs() const = 0; - CV_WRAP virtual Mat getCatMap() const = 0; - - /** @brief Splits the training data into the training and test parts - @sa TrainData::setTrainTestSplitRatio - */ - CV_WRAP virtual void setTrainTestSplit(int count, bool shuffle=true) = 0; - - /** @brief Splits the training data into the training and test parts - - The function selects a subset of specified relative size and then returns it as the training - set. If the function is not called, all the data is used for training. Please, note that for - each of TrainData::getTrain\* there is corresponding TrainData::getTest\*, so that the test - subset can be retrieved and processed as well. - @sa TrainData::setTrainTestSplit - */ - CV_WRAP virtual void setTrainTestSplitRatio(double ratio, bool shuffle=true) = 0; - CV_WRAP virtual void shuffleTrainTest() = 0; - - /** @brief Returns matrix of test samples */ - CV_WRAP virtual Mat getTestSamples() const = 0; - - /** @brief Returns vector of symbolic names captured in loadFromCSV() */ - CV_WRAP virtual void getNames(std::vector& names) const = 0; - - /** @brief Extract from 1D vector elements specified by passed indexes. - @param vec input vector (supported types: CV_32S, CV_32F, CV_64F) - @param idx 1D index vector - */ - static CV_WRAP Mat getSubVector(const Mat& vec, const Mat& idx); - - /** @brief Extract from matrix rows/cols specified by passed indexes. - @param matrix input matrix (supported types: CV_32S, CV_32F, CV_64F) - @param idx 1D index vector - @param layout specifies to extract rows (cv::ml::ROW_SAMPLES) or to extract columns (cv::ml::COL_SAMPLES) - */ - static CV_WRAP Mat getSubMatrix(const Mat& matrix, const Mat& idx, int layout); - - /** @brief Reads the dataset from a .csv file and returns the ready-to-use training data. - - @param filename The input file name - @param headerLineCount The number of lines in the beginning to skip; besides the header, the - function also skips empty lines and lines staring with `#` - @param responseStartIdx Index of the first output variable. If -1, the function considers the - last variable as the response - @param responseEndIdx Index of the last output variable + 1. If -1, then there is single - response variable at responseStartIdx. - @param varTypeSpec The optional text string that specifies the variables' types. It has the - format `ord[n1-n2,n3,n4-n5,...]cat[n6,n7-n8,...]`. That is, variables from `n1 to n2` - (inclusive range), `n3`, `n4 to n5` ... are considered ordered and `n6`, `n7 to n8` ... are - considered as categorical. The range `[n1..n2] + [n3] + [n4..n5] + ... + [n6] + [n7..n8]` - should cover all the variables. If varTypeSpec is not specified, then algorithm uses the - following rules: - - all input variables are considered ordered by default. If some column contains has non- - numerical values, e.g. 'apple', 'pear', 'apple', 'apple', 'mango', the corresponding - variable is considered categorical. - - if there are several output variables, they are all considered as ordered. Error is - reported when non-numerical values are used. - - if there is a single output variable, then if its values are non-numerical or are all - integers, then it's considered categorical. Otherwise, it's considered ordered. - @param delimiter The character used to separate values in each line. - @param missch The character used to specify missing measurements. It should not be a digit. - Although it's a non-numerical value, it surely does not affect the decision of whether the - variable ordered or categorical. - @note If the dataset only contains input variables and no responses, use responseStartIdx = -2 - and responseEndIdx = 0. The output variables vector will just contain zeros. - */ - static Ptr loadFromCSV(const String& filename, - int headerLineCount, - int responseStartIdx=-1, - int responseEndIdx=-1, - const String& varTypeSpec=String(), - char delimiter=',', - char missch='?'); - - /** @brief Creates training data from in-memory arrays. - - @param samples matrix of samples. It should have CV_32F type. - @param layout see ml::SampleTypes. - @param responses matrix of responses. If the responses are scalar, they should be stored as a - single row or as a single column. The matrix should have type CV_32F or CV_32S (in the - former case the responses are considered as ordered by default; in the latter case - as - categorical) - @param varIdx vector specifying which variables to use for training. It can be an integer vector - (CV_32S) containing 0-based variable indices or byte vector (CV_8U) containing a mask of - active variables. - @param sampleIdx vector specifying which samples to use for training. It can be an integer - vector (CV_32S) containing 0-based sample indices or byte vector (CV_8U) containing a mask - of training samples. - @param sampleWeights optional vector with weights for each sample. It should have CV_32F type. - @param varType optional vector of type CV_8U and size ` + - `, containing types of each input and output variable. See - ml::VariableTypes. - */ - CV_WRAP static Ptr create(InputArray samples, int layout, InputArray responses, - InputArray varIdx=noArray(), InputArray sampleIdx=noArray(), - InputArray sampleWeights=noArray(), InputArray varType=noArray()); -}; - -/** @brief Base class for statistical models in OpenCV ML. - */ -class CV_EXPORTS_W StatModel : public Algorithm -{ -public: - /** Predict options */ - enum Flags { - UPDATE_MODEL = 1, - RAW_OUTPUT=1, //!< makes the method return the raw results (the sum), not the class label - COMPRESSED_INPUT=2, - PREPROCESSED_INPUT=4 - }; - - /** @brief Returns the number of variables in training samples */ - CV_WRAP virtual int getVarCount() const = 0; - - CV_WRAP virtual bool empty() const CV_OVERRIDE; - - /** @brief Returns true if the model is trained */ - CV_WRAP virtual bool isTrained() const = 0; - /** @brief Returns true if the model is classifier */ - CV_WRAP virtual bool isClassifier() const = 0; - - /** @brief Trains the statistical model - - @param trainData training data that can be loaded from file using TrainData::loadFromCSV or - created with TrainData::create. - @param flags optional flags, depending on the model. Some of the models can be updated with the - new training samples, not completely overwritten (such as NormalBayesClassifier or ANN_MLP). - */ - CV_WRAP virtual bool train( const Ptr& trainData, int flags=0 ); - - /** @brief Trains the statistical model - - @param samples training samples - @param layout See ml::SampleTypes. - @param responses vector of responses associated with the training samples. - */ - CV_WRAP virtual bool train( InputArray samples, int layout, InputArray responses ); - - /** @brief Computes error on the training or test dataset - - @param data the training data - @param test if true, the error is computed over the test subset of the data, otherwise it's - computed over the training subset of the data. Please note that if you loaded a completely - different dataset to evaluate already trained classifier, you will probably want not to set - the test subset at all with TrainData::setTrainTestSplitRatio and specify test=false, so - that the error is computed for the whole new set. Yes, this sounds a bit confusing. - @param resp the optional output responses. - - The method uses StatModel::predict to compute the error. For regression models the error is - computed as RMS, for classifiers - as a percent of missclassified samples (0%-100%). - */ - CV_WRAP virtual float calcError( const Ptr& data, bool test, OutputArray resp ) const; - - /** @brief Predicts response(s) for the provided sample(s) - - @param samples The input samples, floating-point matrix - @param results The optional output matrix of results. - @param flags The optional flags, model-dependent. See cv::ml::StatModel::Flags. - */ - CV_WRAP virtual float predict( InputArray samples, OutputArray results=noArray(), int flags=0 ) const = 0; - - /** @brief Create and train model with default parameters - - The class must implement static `create()` method with no parameters or with all default parameter values - */ - template static Ptr<_Tp> train(const Ptr& data, int flags=0) - { - Ptr<_Tp> model = _Tp::create(); - return !model.empty() && model->train(data, flags) ? model : Ptr<_Tp>(); - } -}; - -/****************************************************************************************\ -* Normal Bayes Classifier * -\****************************************************************************************/ - -/** @brief Bayes classifier for normally distributed data. - -@sa @ref ml_intro_bayes - */ -class CV_EXPORTS_W NormalBayesClassifier : public StatModel -{ -public: - /** @brief Predicts the response for sample(s). - - The method estimates the most probable classes for input vectors. Input vectors (one or more) - are stored as rows of the matrix inputs. In case of multiple input vectors, there should be one - output vector outputs. The predicted class for a single input vector is returned by the method. - The vector outputProbs contains the output probabilities corresponding to each element of - result. - */ - CV_WRAP virtual float predictProb( InputArray inputs, OutputArray outputs, - OutputArray outputProbs, int flags=0 ) const = 0; - - /** Creates empty model - Use StatModel::train to train the model after creation. */ - CV_WRAP static Ptr create(); - - /** @brief Loads and creates a serialized NormalBayesClassifier from a file - * - * Use NormalBayesClassifier::save to serialize and store an NormalBayesClassifier to disk. - * Load the NormalBayesClassifier from this file again, by calling this function with the path to the file. - * Optionally specify the node for the file containing the classifier - * - * @param filepath path to serialized NormalBayesClassifier - * @param nodeName name of node containing the classifier - */ - CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); -}; - -/****************************************************************************************\ -* K-Nearest Neighbour Classifier * -\****************************************************************************************/ - -/** @brief The class implements K-Nearest Neighbors model - -@sa @ref ml_intro_knn - */ -class CV_EXPORTS_W KNearest : public StatModel -{ -public: - - /** Default number of neighbors to use in predict method. */ - /** @see setDefaultK */ - CV_WRAP virtual int getDefaultK() const = 0; - /** @copybrief getDefaultK @see getDefaultK */ - CV_WRAP virtual void setDefaultK(int val) = 0; - - /** Whether classification or regression model should be trained. */ - /** @see setIsClassifier */ - CV_WRAP virtual bool getIsClassifier() const = 0; - /** @copybrief getIsClassifier @see getIsClassifier */ - CV_WRAP virtual void setIsClassifier(bool val) = 0; - - /** Parameter for KDTree implementation. */ - /** @see setEmax */ - CV_WRAP virtual int getEmax() const = 0; - /** @copybrief getEmax @see getEmax */ - CV_WRAP virtual void setEmax(int val) = 0; - - /** %Algorithm type, one of KNearest::Types. */ - /** @see setAlgorithmType */ - CV_WRAP virtual int getAlgorithmType() const = 0; - /** @copybrief getAlgorithmType @see getAlgorithmType */ - CV_WRAP virtual void setAlgorithmType(int val) = 0; - - /** @brief Finds the neighbors and predicts responses for input vectors. - - @param samples Input samples stored by rows. It is a single-precision floating-point matrix of - ` * k` size. - @param k Number of used nearest neighbors. Should be greater than 1. - @param results Vector with results of prediction (regression or classification) for each input - sample. It is a single-precision floating-point vector with `` elements. - @param neighborResponses Optional output values for corresponding neighbors. It is a single- - precision floating-point matrix of ` * k` size. - @param dist Optional output distances from the input vectors to the corresponding neighbors. It - is a single-precision floating-point matrix of ` * k` size. - - For each input vector (a row of the matrix samples), the method finds the k nearest neighbors. - In case of regression, the predicted result is a mean value of the particular vector's neighbor - responses. In case of classification, the class is determined by voting. - - For each input vector, the neighbors are sorted by their distances to the vector. - - In case of C++ interface you can use output pointers to empty matrices and the function will - allocate memory itself. - - If only a single input vector is passed, all output matrices are optional and the predicted - value is returned by the method. - - The function is parallelized with the TBB library. - */ - CV_WRAP virtual float findNearest( InputArray samples, int k, - OutputArray results, - OutputArray neighborResponses=noArray(), - OutputArray dist=noArray() ) const = 0; - - /** @brief Implementations of KNearest algorithm - */ - enum Types - { - BRUTE_FORCE=1, - KDTREE=2 - }; - - /** @brief Creates the empty model - - The static method creates empty %KNearest classifier. It should be then trained using StatModel::train method. - */ - CV_WRAP static Ptr create(); - /** @brief Loads and creates a serialized knearest from a file - * - * Use KNearest::save to serialize and store an KNearest to disk. - * Load the KNearest from this file again, by calling this function with the path to the file. - * - * @param filepath path to serialized KNearest - */ - CV_WRAP static Ptr load(const String& filepath); -}; - -/****************************************************************************************\ -* Support Vector Machines * -\****************************************************************************************/ - -/** @brief Support Vector Machines. - -@sa @ref ml_intro_svm - */ -class CV_EXPORTS_W SVM : public StatModel -{ -public: - - class CV_EXPORTS Kernel : public Algorithm - { - public: - virtual int getType() const = 0; - virtual void calc( int vcount, int n, const float* vecs, const float* another, float* results ) = 0; - }; - - /** Type of a %SVM formulation. - See SVM::Types. Default value is SVM::C_SVC. */ - /** @see setType */ - CV_WRAP virtual int getType() const = 0; - /** @copybrief getType @see getType */ - CV_WRAP virtual void setType(int val) = 0; - - /** Parameter \f$\gamma\f$ of a kernel function. - For SVM::POLY, SVM::RBF, SVM::SIGMOID or SVM::CHI2. Default value is 1. */ - /** @see setGamma */ - CV_WRAP virtual double getGamma() const = 0; - /** @copybrief getGamma @see getGamma */ - CV_WRAP virtual void setGamma(double val) = 0; - - /** Parameter _coef0_ of a kernel function. - For SVM::POLY or SVM::SIGMOID. Default value is 0.*/ - /** @see setCoef0 */ - CV_WRAP virtual double getCoef0() const = 0; - /** @copybrief getCoef0 @see getCoef0 */ - CV_WRAP virtual void setCoef0(double val) = 0; - - /** Parameter _degree_ of a kernel function. - For SVM::POLY. Default value is 0. */ - /** @see setDegree */ - CV_WRAP virtual double getDegree() const = 0; - /** @copybrief getDegree @see getDegree */ - CV_WRAP virtual void setDegree(double val) = 0; - - /** Parameter _C_ of a %SVM optimization problem. - For SVM::C_SVC, SVM::EPS_SVR or SVM::NU_SVR. Default value is 0. */ - /** @see setC */ - CV_WRAP virtual double getC() const = 0; - /** @copybrief getC @see getC */ - CV_WRAP virtual void setC(double val) = 0; - - /** Parameter \f$\nu\f$ of a %SVM optimization problem. - For SVM::NU_SVC, SVM::ONE_CLASS or SVM::NU_SVR. Default value is 0. */ - /** @see setNu */ - CV_WRAP virtual double getNu() const = 0; - /** @copybrief getNu @see getNu */ - CV_WRAP virtual void setNu(double val) = 0; - - /** Parameter \f$\epsilon\f$ of a %SVM optimization problem. - For SVM::EPS_SVR. Default value is 0. */ - /** @see setP */ - CV_WRAP virtual double getP() const = 0; - /** @copybrief getP @see getP */ - CV_WRAP virtual void setP(double val) = 0; - - /** Optional weights in the SVM::C_SVC problem, assigned to particular classes. - They are multiplied by _C_ so the parameter _C_ of class _i_ becomes `classWeights(i) * C`. Thus - these weights affect the misclassification penalty for different classes. The larger weight, - the larger penalty on misclassification of data from the corresponding class. Default value is - empty Mat. */ - /** @see setClassWeights */ - CV_WRAP virtual cv::Mat getClassWeights() const = 0; - /** @copybrief getClassWeights @see getClassWeights */ - CV_WRAP virtual void setClassWeights(const cv::Mat &val) = 0; - - /** Termination criteria of the iterative %SVM training procedure which solves a partial - case of constrained quadratic optimization problem. - You can specify tolerance and/or the maximum number of iterations. Default value is - `TermCriteria( TermCriteria::MAX_ITER + TermCriteria::EPS, 1000, FLT_EPSILON )`; */ - /** @see setTermCriteria */ - CV_WRAP virtual cv::TermCriteria getTermCriteria() const = 0; - /** @copybrief getTermCriteria @see getTermCriteria */ - CV_WRAP virtual void setTermCriteria(const cv::TermCriteria &val) = 0; - - /** Type of a %SVM kernel. - See SVM::KernelTypes. Default value is SVM::RBF. */ - CV_WRAP virtual int getKernelType() const = 0; - - /** Initialize with one of predefined kernels. - See SVM::KernelTypes. */ - CV_WRAP virtual void setKernel(int kernelType) = 0; - - /** Initialize with custom kernel. - See SVM::Kernel class for implementation details */ - virtual void setCustomKernel(const Ptr &_kernel) = 0; - - //! %SVM type - enum Types { - /** C-Support Vector Classification. n-class classification (n \f$\geq\f$ 2), allows - imperfect separation of classes with penalty multiplier C for outliers. */ - C_SVC=100, - /** \f$\nu\f$-Support Vector Classification. n-class classification with possible - imperfect separation. Parameter \f$\nu\f$ (in the range 0..1, the larger the value, the smoother - the decision boundary) is used instead of C. */ - NU_SVC=101, - /** Distribution Estimation (One-class %SVM). All the training data are from - the same class, %SVM builds a boundary that separates the class from the rest of the feature - space. */ - ONE_CLASS=102, - /** \f$\epsilon\f$-Support Vector Regression. The distance between feature vectors - from the training set and the fitting hyper-plane must be less than p. For outliers the - penalty multiplier C is used. */ - EPS_SVR=103, - /** \f$\nu\f$-Support Vector Regression. \f$\nu\f$ is used instead of p. - See @cite LibSVM for details. */ - NU_SVR=104 - }; - - /** @brief %SVM kernel type - - A comparison of different kernels on the following 2D test case with four classes. Four - SVM::C_SVC SVMs have been trained (one against rest) with auto_train. Evaluation on three - different kernels (SVM::CHI2, SVM::INTER, SVM::RBF). The color depicts the class with max score. - Bright means max-score \> 0, dark means max-score \< 0. - ![image](pics/SVM_Comparison.png) - */ - enum KernelTypes { - /** Returned by SVM::getKernelType in case when custom kernel has been set */ - CUSTOM=-1, - /** Linear kernel. No mapping is done, linear discrimination (or regression) is - done in the original feature space. It is the fastest option. \f$K(x_i, x_j) = x_i^T x_j\f$. */ - LINEAR=0, - /** Polynomial kernel: - \f$K(x_i, x_j) = (\gamma x_i^T x_j + coef0)^{degree}, \gamma > 0\f$. */ - POLY=1, - /** Radial basis function (RBF), a good choice in most cases. - \f$K(x_i, x_j) = e^{-\gamma ||x_i - x_j||^2}, \gamma > 0\f$. */ - RBF=2, - /** Sigmoid kernel: \f$K(x_i, x_j) = \tanh(\gamma x_i^T x_j + coef0)\f$. */ - SIGMOID=3, - /** Exponential Chi2 kernel, similar to the RBF kernel: - \f$K(x_i, x_j) = e^{-\gamma \chi^2(x_i,x_j)}, \chi^2(x_i,x_j) = (x_i-x_j)^2/(x_i+x_j), \gamma > 0\f$. */ - CHI2=4, - /** Histogram intersection kernel. A fast kernel. \f$K(x_i, x_j) = min(x_i,x_j)\f$. */ - INTER=5 - }; - - //! %SVM params type - enum ParamTypes { - C=0, - GAMMA=1, - P=2, - NU=3, - COEF=4, - DEGREE=5 - }; - - /** @brief Trains an %SVM with optimal parameters. - - @param data the training data that can be constructed using TrainData::create or - TrainData::loadFromCSV. - @param kFold Cross-validation parameter. The training set is divided into kFold subsets. One - subset is used to test the model, the others form the train set. So, the %SVM algorithm is - executed kFold times. - @param Cgrid grid for C - @param gammaGrid grid for gamma - @param pGrid grid for p - @param nuGrid grid for nu - @param coeffGrid grid for coeff - @param degreeGrid grid for degree - @param balanced If true and the problem is 2-class classification then the method creates more - balanced cross-validation subsets that is proportions between classes in subsets are close - to such proportion in the whole train dataset. - - The method trains the %SVM model automatically by choosing the optimal parameters C, gamma, p, - nu, coef0, degree. Parameters are considered optimal when the cross-validation - estimate of the test set error is minimal. - - If there is no need to optimize a parameter, the corresponding grid step should be set to any - value less than or equal to 1. For example, to avoid optimization in gamma, set `gammaGrid.step - = 0`, `gammaGrid.minVal`, `gamma_grid.maxVal` as arbitrary numbers. In this case, the value - `Gamma` is taken for gamma. - - And, finally, if the optimization in a parameter is required but the corresponding grid is - unknown, you may call the function SVM::getDefaultGrid. To generate a grid, for example, for - gamma, call `SVM::getDefaultGrid(SVM::GAMMA)`. - - This function works for the classification (SVM::C_SVC or SVM::NU_SVC) as well as for the - regression (SVM::EPS_SVR or SVM::NU_SVR). If it is SVM::ONE_CLASS, no optimization is made and - the usual %SVM with parameters specified in params is executed. - */ - virtual bool trainAuto( const Ptr& data, int kFold = 10, - ParamGrid Cgrid = getDefaultGrid(C), - ParamGrid gammaGrid = getDefaultGrid(GAMMA), - ParamGrid pGrid = getDefaultGrid(P), - ParamGrid nuGrid = getDefaultGrid(NU), - ParamGrid coeffGrid = getDefaultGrid(COEF), - ParamGrid degreeGrid = getDefaultGrid(DEGREE), - bool balanced=false) = 0; - - /** @brief Trains an %SVM with optimal parameters - - @param samples training samples - @param layout See ml::SampleTypes. - @param responses vector of responses associated with the training samples. - @param kFold Cross-validation parameter. The training set is divided into kFold subsets. One - subset is used to test the model, the others form the train set. So, the %SVM algorithm is - @param Cgrid grid for C - @param gammaGrid grid for gamma - @param pGrid grid for p - @param nuGrid grid for nu - @param coeffGrid grid for coeff - @param degreeGrid grid for degree - @param balanced If true and the problem is 2-class classification then the method creates more - balanced cross-validation subsets that is proportions between classes in subsets are close - to such proportion in the whole train dataset. - - The method trains the %SVM model automatically by choosing the optimal parameters C, gamma, p, - nu, coef0, degree. Parameters are considered optimal when the cross-validation - estimate of the test set error is minimal. - - This function only makes use of SVM::getDefaultGrid for parameter optimization and thus only - offers rudimentary parameter options. - - This function works for the classification (SVM::C_SVC or SVM::NU_SVC) as well as for the - regression (SVM::EPS_SVR or SVM::NU_SVR). If it is SVM::ONE_CLASS, no optimization is made and - the usual %SVM with parameters specified in params is executed. - */ - CV_WRAP virtual bool trainAuto(InputArray samples, - int layout, - InputArray responses, - int kFold = 10, - Ptr Cgrid = SVM::getDefaultGridPtr(SVM::C), - Ptr gammaGrid = SVM::getDefaultGridPtr(SVM::GAMMA), - Ptr pGrid = SVM::getDefaultGridPtr(SVM::P), - Ptr nuGrid = SVM::getDefaultGridPtr(SVM::NU), - Ptr coeffGrid = SVM::getDefaultGridPtr(SVM::COEF), - Ptr degreeGrid = SVM::getDefaultGridPtr(SVM::DEGREE), - bool balanced=false) = 0; - - /** @brief Retrieves all the support vectors - - The method returns all the support vectors as a floating-point matrix, where support vectors are - stored as matrix rows. - */ - CV_WRAP virtual Mat getSupportVectors() const = 0; - - /** @brief Retrieves all the uncompressed support vectors of a linear %SVM - - The method returns all the uncompressed support vectors of a linear %SVM that the compressed - support vector, used for prediction, was derived from. They are returned in a floating-point - matrix, where the support vectors are stored as matrix rows. - */ - CV_WRAP virtual Mat getUncompressedSupportVectors() const = 0; - - /** @brief Retrieves the decision function - - @param i the index of the decision function. If the problem solved is regression, 1-class or - 2-class classification, then there will be just one decision function and the index should - always be 0. Otherwise, in the case of N-class classification, there will be \f$N(N-1)/2\f$ - decision functions. - @param alpha the optional output vector for weights, corresponding to different support vectors. - In the case of linear %SVM all the alpha's will be 1's. - @param svidx the optional output vector of indices of support vectors within the matrix of - support vectors (which can be retrieved by SVM::getSupportVectors). In the case of linear - %SVM each decision function consists of a single "compressed" support vector. - - The method returns rho parameter of the decision function, a scalar subtracted from the weighted - sum of kernel responses. - */ - CV_WRAP virtual double getDecisionFunction(int i, OutputArray alpha, OutputArray svidx) const = 0; - - /** @brief Generates a grid for %SVM parameters. - - @param param_id %SVM parameters IDs that must be one of the SVM::ParamTypes. The grid is - generated for the parameter with this ID. - - The function generates a grid for the specified parameter of the %SVM algorithm. The grid may be - passed to the function SVM::trainAuto. - */ - static ParamGrid getDefaultGrid( int param_id ); - - /** @brief Generates a grid for %SVM parameters. - - @param param_id %SVM parameters IDs that must be one of the SVM::ParamTypes. The grid is - generated for the parameter with this ID. - - The function generates a grid pointer for the specified parameter of the %SVM algorithm. - The grid may be passed to the function SVM::trainAuto. - */ - CV_WRAP static Ptr getDefaultGridPtr( int param_id ); - - /** Creates empty model. - Use StatModel::train to train the model. Since %SVM has several parameters, you may want to - find the best parameters for your problem, it can be done with SVM::trainAuto. */ - CV_WRAP static Ptr create(); - - /** @brief Loads and creates a serialized svm from a file - * - * Use SVM::save to serialize and store an SVM to disk. - * Load the SVM from this file again, by calling this function with the path to the file. - * - * @param filepath path to serialized svm - */ - CV_WRAP static Ptr load(const String& filepath); -}; - -/****************************************************************************************\ -* Expectation - Maximization * -\****************************************************************************************/ - -/** @brief The class implements the Expectation Maximization algorithm. - -@sa @ref ml_intro_em - */ -class CV_EXPORTS_W EM : public StatModel -{ -public: - //! Type of covariation matrices - enum Types { - /** A scaled identity matrix \f$\mu_k * I\f$. There is the only - parameter \f$\mu_k\f$ to be estimated for each matrix. The option may be used in special cases, - when the constraint is relevant, or as a first step in the optimization (for example in case - when the data is preprocessed with PCA). The results of such preliminary estimation may be - passed again to the optimization procedure, this time with - covMatType=EM::COV_MAT_DIAGONAL. */ - COV_MAT_SPHERICAL=0, - /** A diagonal matrix with positive diagonal elements. The number of - free parameters is d for each matrix. This is most commonly used option yielding good - estimation results. */ - COV_MAT_DIAGONAL=1, - /** A symmetric positively defined matrix. The number of free - parameters in each matrix is about \f$d^2/2\f$. It is not recommended to use this option, unless - there is pretty accurate initial estimation of the parameters and/or a huge number of - training samples. */ - COV_MAT_GENERIC=2, - COV_MAT_DEFAULT=COV_MAT_DIAGONAL - }; - - //! Default parameters - enum {DEFAULT_NCLUSTERS=5, DEFAULT_MAX_ITERS=100}; - - //! The initial step - enum {START_E_STEP=1, START_M_STEP=2, START_AUTO_STEP=0}; - - /** The number of mixture components in the Gaussian mixture model. - Default value of the parameter is EM::DEFAULT_NCLUSTERS=5. Some of %EM implementation could - determine the optimal number of mixtures within a specified value range, but that is not the - case in ML yet. */ - /** @see setClustersNumber */ - CV_WRAP virtual int getClustersNumber() const = 0; - /** @copybrief getClustersNumber @see getClustersNumber */ - CV_WRAP virtual void setClustersNumber(int val) = 0; - - /** Constraint on covariance matrices which defines type of matrices. - See EM::Types. */ - /** @see setCovarianceMatrixType */ - CV_WRAP virtual int getCovarianceMatrixType() const = 0; - /** @copybrief getCovarianceMatrixType @see getCovarianceMatrixType */ - CV_WRAP virtual void setCovarianceMatrixType(int val) = 0; - - /** The termination criteria of the %EM algorithm. - The %EM algorithm can be terminated by the number of iterations termCrit.maxCount (number of - M-steps) or when relative change of likelihood logarithm is less than termCrit.epsilon. Default - maximum number of iterations is EM::DEFAULT_MAX_ITERS=100. */ - /** @see setTermCriteria */ - CV_WRAP virtual TermCriteria getTermCriteria() const = 0; - /** @copybrief getTermCriteria @see getTermCriteria */ - CV_WRAP virtual void setTermCriteria(const TermCriteria &val) = 0; - - /** @brief Returns weights of the mixtures - - Returns vector with the number of elements equal to the number of mixtures. - */ - CV_WRAP virtual Mat getWeights() const = 0; - /** @brief Returns the cluster centers (means of the Gaussian mixture) - - Returns matrix with the number of rows equal to the number of mixtures and number of columns - equal to the space dimensionality. - */ - CV_WRAP virtual Mat getMeans() const = 0; - /** @brief Returns covariation matrices - - Returns vector of covariation matrices. Number of matrices is the number of gaussian mixtures, - each matrix is a square floating-point matrix NxN, where N is the space dimensionality. - */ - CV_WRAP virtual void getCovs(CV_OUT std::vector& covs) const = 0; - - /** @brief Returns posterior probabilities for the provided samples - - @param samples The input samples, floating-point matrix - @param results The optional output \f$ nSamples \times nClusters\f$ matrix of results. It contains - posterior probabilities for each sample from the input - @param flags This parameter will be ignored - */ - CV_WRAP virtual float predict( InputArray samples, OutputArray results=noArray(), int flags=0 ) const CV_OVERRIDE = 0; - - /** @brief Returns a likelihood logarithm value and an index of the most probable mixture component - for the given sample. - - @param sample A sample for classification. It should be a one-channel matrix of - \f$1 \times dims\f$ or \f$dims \times 1\f$ size. - @param probs Optional output matrix that contains posterior probabilities of each component - given the sample. It has \f$1 \times nclusters\f$ size and CV_64FC1 type. - - The method returns a two-element double vector. Zero element is a likelihood logarithm value for - the sample. First element is an index of the most probable mixture component for the given - sample. - */ - CV_WRAP virtual Vec2d predict2(InputArray sample, OutputArray probs) const = 0; - - /** @brief Estimate the Gaussian mixture parameters from a samples set. - - This variation starts with Expectation step. Initial values of the model parameters will be - estimated by the k-means algorithm. - - Unlike many of the ML models, %EM is an unsupervised learning algorithm and it does not take - responses (class labels or function values) as input. Instead, it computes the *Maximum - Likelihood Estimate* of the Gaussian mixture parameters from an input sample set, stores all the - parameters inside the structure: \f$p_{i,k}\f$ in probs, \f$a_k\f$ in means , \f$S_k\f$ in - covs[k], \f$\pi_k\f$ in weights , and optionally computes the output "class label" for each - sample: \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most - probable mixture component for each sample). - - The trained model can be used further for prediction, just like any other classifier. The - trained model is similar to the NormalBayesClassifier. - - @param samples Samples from which the Gaussian mixture model will be estimated. It should be a - one-channel matrix, each row of which is a sample. If the matrix does not have CV_64F type - it will be converted to the inner matrix of such type for the further computing. - @param logLikelihoods The optional output matrix that contains a likelihood logarithm value for - each sample. It has \f$nsamples \times 1\f$ size and CV_64FC1 type. - @param labels The optional output "class label" for each sample: - \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most probable - mixture component for each sample). It has \f$nsamples \times 1\f$ size and CV_32SC1 type. - @param probs The optional output matrix that contains posterior probabilities of each Gaussian - mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and - CV_64FC1 type. - */ - CV_WRAP virtual bool trainEM(InputArray samples, - OutputArray logLikelihoods=noArray(), - OutputArray labels=noArray(), - OutputArray probs=noArray()) = 0; - - /** @brief Estimate the Gaussian mixture parameters from a samples set. - - This variation starts with Expectation step. You need to provide initial means \f$a_k\f$ of - mixture components. Optionally you can pass initial weights \f$\pi_k\f$ and covariance matrices - \f$S_k\f$ of mixture components. - - @param samples Samples from which the Gaussian mixture model will be estimated. It should be a - one-channel matrix, each row of which is a sample. If the matrix does not have CV_64F type - it will be converted to the inner matrix of such type for the further computing. - @param means0 Initial means \f$a_k\f$ of mixture components. It is a one-channel matrix of - \f$nclusters \times dims\f$ size. If the matrix does not have CV_64F type it will be - converted to the inner matrix of such type for the further computing. - @param covs0 The vector of initial covariance matrices \f$S_k\f$ of mixture components. Each of - covariance matrices is a one-channel matrix of \f$dims \times dims\f$ size. If the matrices - do not have CV_64F type they will be converted to the inner matrices of such type for the - further computing. - @param weights0 Initial weights \f$\pi_k\f$ of mixture components. It should be a one-channel - floating-point matrix with \f$1 \times nclusters\f$ or \f$nclusters \times 1\f$ size. - @param logLikelihoods The optional output matrix that contains a likelihood logarithm value for - each sample. It has \f$nsamples \times 1\f$ size and CV_64FC1 type. - @param labels The optional output "class label" for each sample: - \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most probable - mixture component for each sample). It has \f$nsamples \times 1\f$ size and CV_32SC1 type. - @param probs The optional output matrix that contains posterior probabilities of each Gaussian - mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and - CV_64FC1 type. - */ - CV_WRAP virtual bool trainE(InputArray samples, InputArray means0, - InputArray covs0=noArray(), - InputArray weights0=noArray(), - OutputArray logLikelihoods=noArray(), - OutputArray labels=noArray(), - OutputArray probs=noArray()) = 0; - - /** @brief Estimate the Gaussian mixture parameters from a samples set. - - This variation starts with Maximization step. You need to provide initial probabilities - \f$p_{i,k}\f$ to use this option. - - @param samples Samples from which the Gaussian mixture model will be estimated. It should be a - one-channel matrix, each row of which is a sample. If the matrix does not have CV_64F type - it will be converted to the inner matrix of such type for the further computing. - @param probs0 the probabilities - @param logLikelihoods The optional output matrix that contains a likelihood logarithm value for - each sample. It has \f$nsamples \times 1\f$ size and CV_64FC1 type. - @param labels The optional output "class label" for each sample: - \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most probable - mixture component for each sample). It has \f$nsamples \times 1\f$ size and CV_32SC1 type. - @param probs The optional output matrix that contains posterior probabilities of each Gaussian - mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and - CV_64FC1 type. - */ - CV_WRAP virtual bool trainM(InputArray samples, InputArray probs0, - OutputArray logLikelihoods=noArray(), - OutputArray labels=noArray(), - OutputArray probs=noArray()) = 0; - - /** Creates empty %EM model. - The model should be trained then using StatModel::train(traindata, flags) method. Alternatively, you - can use one of the EM::train\* methods or load it from file using Algorithm::load\(filename). - */ - CV_WRAP static Ptr create(); - - /** @brief Loads and creates a serialized EM from a file - * - * Use EM::save to serialize and store an EM to disk. - * Load the EM from this file again, by calling this function with the path to the file. - * Optionally specify the node for the file containing the classifier - * - * @param filepath path to serialized EM - * @param nodeName name of node containing the classifier - */ - CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); -}; - -/****************************************************************************************\ -* Decision Tree * -\****************************************************************************************/ - -/** @brief The class represents a single decision tree or a collection of decision trees. - -The current public interface of the class allows user to train only a single decision tree, however -the class is capable of storing multiple decision trees and using them for prediction (by summing -responses or using a voting schemes), and the derived from DTrees classes (such as RTrees and Boost) -use this capability to implement decision tree ensembles. - -@sa @ref ml_intro_trees -*/ -class CV_EXPORTS_W DTrees : public StatModel -{ -public: - /** Predict options */ - enum Flags { PREDICT_AUTO=0, PREDICT_SUM=(1<<8), PREDICT_MAX_VOTE=(2<<8), PREDICT_MASK=(3<<8) }; - - /** Cluster possible values of a categorical variable into K\<=maxCategories clusters to - find a suboptimal split. - If a discrete variable, on which the training procedure tries to make a split, takes more than - maxCategories values, the precise best subset estimation may take a very long time because the - algorithm is exponential. Instead, many decision trees engines (including our implementation) - try to find sub-optimal split in this case by clustering all the samples into maxCategories - clusters that is some categories are merged together. The clustering is applied only in n \> - 2-class classification problems for categorical variables with N \> max_categories possible - values. In case of regression and 2-class classification the optimal split can be found - efficiently without employing clustering, thus the parameter is not used in these cases. - Default value is 10.*/ - /** @see setMaxCategories */ - CV_WRAP virtual int getMaxCategories() const = 0; - /** @copybrief getMaxCategories @see getMaxCategories */ - CV_WRAP virtual void setMaxCategories(int val) = 0; - - /** The maximum possible depth of the tree. - That is the training algorithms attempts to split a node while its depth is less than maxDepth. - The root node has zero depth. The actual depth may be smaller if the other termination criteria - are met (see the outline of the training procedure @ref ml_intro_trees "here"), and/or if the - tree is pruned. Default value is INT_MAX.*/ - /** @see setMaxDepth */ - CV_WRAP virtual int getMaxDepth() const = 0; - /** @copybrief getMaxDepth @see getMaxDepth */ - CV_WRAP virtual void setMaxDepth(int val) = 0; - - /** If the number of samples in a node is less than this parameter then the node will not be split. - - Default value is 10.*/ - /** @see setMinSampleCount */ - CV_WRAP virtual int getMinSampleCount() const = 0; - /** @copybrief getMinSampleCount @see getMinSampleCount */ - CV_WRAP virtual void setMinSampleCount(int val) = 0; - - /** If CVFolds \> 1 then algorithms prunes the built decision tree using K-fold - cross-validation procedure where K is equal to CVFolds. - Default value is 10.*/ - /** @see setCVFolds */ - CV_WRAP virtual int getCVFolds() const = 0; - /** @copybrief getCVFolds @see getCVFolds */ - CV_WRAP virtual void setCVFolds(int val) = 0; - - /** If true then surrogate splits will be built. - These splits allow to work with missing data and compute variable importance correctly. - Default value is false. - @note currently it's not implemented.*/ - /** @see setUseSurrogates */ - CV_WRAP virtual bool getUseSurrogates() const = 0; - /** @copybrief getUseSurrogates @see getUseSurrogates */ - CV_WRAP virtual void setUseSurrogates(bool val) = 0; - - /** If true then a pruning will be harsher. - This will make a tree more compact and more resistant to the training data noise but a bit less - accurate. Default value is true.*/ - /** @see setUse1SERule */ - CV_WRAP virtual bool getUse1SERule() const = 0; - /** @copybrief getUse1SERule @see getUse1SERule */ - CV_WRAP virtual void setUse1SERule(bool val) = 0; - - /** If true then pruned branches are physically removed from the tree. - Otherwise they are retained and it is possible to get results from the original unpruned (or - pruned less aggressively) tree. Default value is true.*/ - /** @see setTruncatePrunedTree */ - CV_WRAP virtual bool getTruncatePrunedTree() const = 0; - /** @copybrief getTruncatePrunedTree @see getTruncatePrunedTree */ - CV_WRAP virtual void setTruncatePrunedTree(bool val) = 0; - - /** Termination criteria for regression trees. - If all absolute differences between an estimated value in a node and values of train samples - in this node are less than this parameter then the node will not be split further. Default - value is 0.01f*/ - /** @see setRegressionAccuracy */ - CV_WRAP virtual float getRegressionAccuracy() const = 0; - /** @copybrief getRegressionAccuracy @see getRegressionAccuracy */ - CV_WRAP virtual void setRegressionAccuracy(float val) = 0; - - /** @brief The array of a priori class probabilities, sorted by the class label value. - - The parameter can be used to tune the decision tree preferences toward a certain class. For - example, if you want to detect some rare anomaly occurrence, the training base will likely - contain much more normal cases than anomalies, so a very good classification performance - will be achieved just by considering every case as normal. To avoid this, the priors can be - specified, where the anomaly probability is artificially increased (up to 0.5 or even - greater), so the weight of the misclassified anomalies becomes much bigger, and the tree is - adjusted properly. - - You can also think about this parameter as weights of prediction categories which determine - relative weights that you give to misclassification. That is, if the weight of the first - category is 1 and the weight of the second category is 10, then each mistake in predicting - the second category is equivalent to making 10 mistakes in predicting the first category. - Default value is empty Mat.*/ - /** @see setPriors */ - CV_WRAP virtual cv::Mat getPriors() const = 0; - /** @copybrief getPriors @see getPriors */ - CV_WRAP virtual void setPriors(const cv::Mat &val) = 0; - - /** @brief The class represents a decision tree node. - */ - class CV_EXPORTS Node - { - public: - Node(); - double value; //!< Value at the node: a class label in case of classification or estimated - //!< function value in case of regression. - int classIdx; //!< Class index normalized to 0..class_count-1 range and assigned to the - //!< node. It is used internally in classification trees and tree ensembles. - int parent; //!< Index of the parent node - int left; //!< Index of the left child node - int right; //!< Index of right child node - int defaultDir; //!< Default direction where to go (-1: left or +1: right). It helps in the - //!< case of missing values. - int split; //!< Index of the first split - }; - - /** @brief The class represents split in a decision tree. - */ - class CV_EXPORTS Split - { - public: - Split(); - int varIdx; //!< Index of variable on which the split is created. - bool inversed; //!< If true, then the inverse split rule is used (i.e. left and right - //!< branches are exchanged in the rule expressions below). - float quality; //!< The split quality, a positive number. It is used to choose the best split. - int next; //!< Index of the next split in the list of splits for the node - float c; /**< The threshold value in case of split on an ordered variable. - The rule is: - @code{.none} - if var_value < c - then next_node <- left - else next_node <- right - @endcode */ - int subsetOfs; /**< Offset of the bitset used by the split on a categorical variable. - The rule is: - @code{.none} - if bitset[var_value] == 1 - then next_node <- left - else next_node <- right - @endcode */ - }; - - /** @brief Returns indices of root nodes - */ - virtual const std::vector& getRoots() const = 0; - /** @brief Returns all the nodes - - all the node indices are indices in the returned vector - */ - virtual const std::vector& getNodes() const = 0; - /** @brief Returns all the splits - - all the split indices are indices in the returned vector - */ - virtual const std::vector& getSplits() const = 0; - /** @brief Returns all the bitsets for categorical splits - - Split::subsetOfs is an offset in the returned vector - */ - virtual const std::vector& getSubsets() const = 0; - - /** @brief Creates the empty model - - The static method creates empty decision tree with the specified parameters. It should be then - trained using train method (see StatModel::train). Alternatively, you can load the model from - file using Algorithm::load\(filename). - */ - CV_WRAP static Ptr create(); - - /** @brief Loads and creates a serialized DTrees from a file - * - * Use DTree::save to serialize and store an DTree to disk. - * Load the DTree from this file again, by calling this function with the path to the file. - * Optionally specify the node for the file containing the classifier - * - * @param filepath path to serialized DTree - * @param nodeName name of node containing the classifier - */ - CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); -}; - -/****************************************************************************************\ -* Random Trees Classifier * -\****************************************************************************************/ - -/** @brief The class implements the random forest predictor. - -@sa @ref ml_intro_rtrees - */ -class CV_EXPORTS_W RTrees : public DTrees -{ -public: - - /** If true then variable importance will be calculated and then it can be retrieved by RTrees::getVarImportance. - Default value is false.*/ - /** @see setCalculateVarImportance */ - CV_WRAP virtual bool getCalculateVarImportance() const = 0; - /** @copybrief getCalculateVarImportance @see getCalculateVarImportance */ - CV_WRAP virtual void setCalculateVarImportance(bool val) = 0; - - /** The size of the randomly selected subset of features at each tree node and that are used - to find the best split(s). - If you set it to 0 then the size will be set to the square root of the total number of - features. Default value is 0.*/ - /** @see setActiveVarCount */ - CV_WRAP virtual int getActiveVarCount() const = 0; - /** @copybrief getActiveVarCount @see getActiveVarCount */ - CV_WRAP virtual void setActiveVarCount(int val) = 0; - - /** The termination criteria that specifies when the training algorithm stops. - Either when the specified number of trees is trained and added to the ensemble or when - sufficient accuracy (measured as OOB error) is achieved. Typically the more trees you have the - better the accuracy. However, the improvement in accuracy generally diminishes and asymptotes - pass a certain number of trees. Also to keep in mind, the number of tree increases the - prediction time linearly. Default value is TermCriteria(TermCriteria::MAX_ITERS + - TermCriteria::EPS, 50, 0.1)*/ - /** @see setTermCriteria */ - CV_WRAP virtual TermCriteria getTermCriteria() const = 0; - /** @copybrief getTermCriteria @see getTermCriteria */ - CV_WRAP virtual void setTermCriteria(const TermCriteria &val) = 0; - - /** Returns the variable importance array. - The method returns the variable importance vector, computed at the training stage when - CalculateVarImportance is set to true. If this flag was set to false, the empty matrix is - returned. - */ - CV_WRAP virtual Mat getVarImportance() const = 0; - - /** Returns the result of each individual tree in the forest. - In case the model is a regression problem, the method will return each of the trees' - results for each of the sample cases. If the model is a classifier, it will return - a Mat with samples + 1 rows, where the first row gives the class number and the - following rows return the votes each class had for each sample. - @param samples Array containing the samples for which votes will be calculated. - @param results Array where the result of the calculation will be written. - @param flags Flags for defining the type of RTrees. - */ - CV_WRAP virtual void getVotes(InputArray samples, OutputArray results, int flags) const = 0; - - /** Returns the OOB error value, computed at the training stage when calcOOBError is set to true. - * If this flag was set to false, 0 is returned. The OOB error is also scaled by sample weighting. - */ -#if CV_VERSION_MAJOR == 4 - CV_WRAP virtual double getOOBError() const { return 0; } -#else - /*CV_WRAP*/ virtual double getOOBError() const = 0; -#endif - - /** Creates the empty model. - Use StatModel::train to train the model, StatModel::train to create and train the model, - Algorithm::load to load the pre-trained model. - */ - CV_WRAP static Ptr create(); - - /** @brief Loads and creates a serialized RTree from a file - * - * Use RTree::save to serialize and store an RTree to disk. - * Load the RTree from this file again, by calling this function with the path to the file. - * Optionally specify the node for the file containing the classifier - * - * @param filepath path to serialized RTree - * @param nodeName name of node containing the classifier - */ - CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); -}; - -/****************************************************************************************\ -* Boosted tree classifier * -\****************************************************************************************/ - -/** @brief Boosted tree classifier derived from DTrees - -@sa @ref ml_intro_boost - */ -class CV_EXPORTS_W Boost : public DTrees -{ -public: - /** Type of the boosting algorithm. - See Boost::Types. Default value is Boost::REAL. */ - /** @see setBoostType */ - CV_WRAP virtual int getBoostType() const = 0; - /** @copybrief getBoostType @see getBoostType */ - CV_WRAP virtual void setBoostType(int val) = 0; - - /** The number of weak classifiers. - Default value is 100. */ - /** @see setWeakCount */ - CV_WRAP virtual int getWeakCount() const = 0; - /** @copybrief getWeakCount @see getWeakCount */ - CV_WRAP virtual void setWeakCount(int val) = 0; - - /** A threshold between 0 and 1 used to save computational time. - Samples with summary weight \f$\leq 1 - weight_trim_rate\f$ do not participate in the *next* - iteration of training. Set this parameter to 0 to turn off this functionality. Default value is 0.95.*/ - /** @see setWeightTrimRate */ - CV_WRAP virtual double getWeightTrimRate() const = 0; - /** @copybrief getWeightTrimRate @see getWeightTrimRate */ - CV_WRAP virtual void setWeightTrimRate(double val) = 0; - - /** Boosting type. - Gentle AdaBoost and Real AdaBoost are often the preferable choices. */ - enum Types { - DISCRETE=0, //!< Discrete AdaBoost. - REAL=1, //!< Real AdaBoost. It is a technique that utilizes confidence-rated predictions - //!< and works well with categorical data. - LOGIT=2, //!< LogitBoost. It can produce good regression fits. - GENTLE=3 //!< Gentle AdaBoost. It puts less weight on outlier data points and for that - //!(filename) to load the pre-trained model. */ - CV_WRAP static Ptr create(); - - /** @brief Loads and creates a serialized Boost from a file - * - * Use Boost::save to serialize and store an RTree to disk. - * Load the Boost from this file again, by calling this function with the path to the file. - * Optionally specify the node for the file containing the classifier - * - * @param filepath path to serialized Boost - * @param nodeName name of node containing the classifier - */ - CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); -}; - -/****************************************************************************************\ -* Gradient Boosted Trees * -\****************************************************************************************/ - -/*class CV_EXPORTS_W GBTrees : public DTrees -{ -public: - struct CV_EXPORTS_W_MAP Params : public DTrees::Params - { - CV_PROP_RW int weakCount; - CV_PROP_RW int lossFunctionType; - CV_PROP_RW float subsamplePortion; - CV_PROP_RW float shrinkage; - - Params(); - Params( int lossFunctionType, int weakCount, float shrinkage, - float subsamplePortion, int maxDepth, bool useSurrogates ); - }; - - enum {SQUARED_LOSS=0, ABSOLUTE_LOSS, HUBER_LOSS=3, DEVIANCE_LOSS}; - - virtual void setK(int k) = 0; - - virtual float predictSerial( InputArray samples, - OutputArray weakResponses, int flags) const = 0; - - static Ptr create(const Params& p); -};*/ - -/****************************************************************************************\ -* Artificial Neural Networks (ANN) * -\****************************************************************************************/ - -/////////////////////////////////// Multi-Layer Perceptrons ////////////////////////////// - -/** @brief Artificial Neural Networks - Multi-Layer Perceptrons. - -Unlike many other models in ML that are constructed and trained at once, in the MLP model these -steps are separated. First, a network with the specified topology is created using the non-default -constructor or the method ANN_MLP::create. All the weights are set to zeros. Then, the network is -trained using a set of input and output vectors. The training procedure can be repeated more than -once, that is, the weights can be adjusted based on the new training data. - -Additional flags for StatModel::train are available: ANN_MLP::TrainFlags. - -@sa @ref ml_intro_ann - */ -class CV_EXPORTS_W ANN_MLP : public StatModel -{ -public: - /** Available training methods */ - enum TrainingMethods { - BACKPROP=0, //!< The back-propagation algorithm. - RPROP = 1, //!< The RPROP algorithm. See @cite RPROP93 for details. - ANNEAL = 2 //!< The simulated annealing algorithm. See @cite Kirkpatrick83 for details. - }; - - /** Sets training method and common parameters. - @param method Default value is ANN_MLP::RPROP. See ANN_MLP::TrainingMethods. - @param param1 passed to setRpropDW0 for ANN_MLP::RPROP and to setBackpropWeightScale for ANN_MLP::BACKPROP and to initialT for ANN_MLP::ANNEAL. - @param param2 passed to setRpropDWMin for ANN_MLP::RPROP and to setBackpropMomentumScale for ANN_MLP::BACKPROP and to finalT for ANN_MLP::ANNEAL. - */ - CV_WRAP virtual void setTrainMethod(int method, double param1 = 0, double param2 = 0) = 0; - - /** Returns current training method */ - CV_WRAP virtual int getTrainMethod() const = 0; - - /** Initialize the activation function for each neuron. - Currently the default and the only fully supported activation function is ANN_MLP::SIGMOID_SYM. - @param type The type of activation function. See ANN_MLP::ActivationFunctions. - @param param1 The first parameter of the activation function, \f$\alpha\f$. Default value is 0. - @param param2 The second parameter of the activation function, \f$\beta\f$. Default value is 0. - */ - CV_WRAP virtual void setActivationFunction(int type, double param1 = 0, double param2 = 0) = 0; - - /** Integer vector specifying the number of neurons in each layer including the input and output layers. - The very first element specifies the number of elements in the input layer. - The last element - number of elements in the output layer. Default value is empty Mat. - @sa getLayerSizes */ - CV_WRAP virtual void setLayerSizes(InputArray _layer_sizes) = 0; - - /** Integer vector specifying the number of neurons in each layer including the input and output layers. - The very first element specifies the number of elements in the input layer. - The last element - number of elements in the output layer. - @sa setLayerSizes */ - CV_WRAP virtual cv::Mat getLayerSizes() const = 0; - - /** Termination criteria of the training algorithm. - You can specify the maximum number of iterations (maxCount) and/or how much the error could - change between the iterations to make the algorithm continue (epsilon). Default value is - TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 1000, 0.01).*/ - /** @see setTermCriteria */ - CV_WRAP virtual TermCriteria getTermCriteria() const = 0; - /** @copybrief getTermCriteria @see getTermCriteria */ - CV_WRAP virtual void setTermCriteria(TermCriteria val) = 0; - - /** BPROP: Strength of the weight gradient term. - The recommended value is about 0.1. Default value is 0.1.*/ - /** @see setBackpropWeightScale */ - CV_WRAP virtual double getBackpropWeightScale() const = 0; - /** @copybrief getBackpropWeightScale @see getBackpropWeightScale */ - CV_WRAP virtual void setBackpropWeightScale(double val) = 0; - - /** BPROP: Strength of the momentum term (the difference between weights on the 2 previous iterations). - This parameter provides some inertia to smooth the random fluctuations of the weights. It can - vary from 0 (the feature is disabled) to 1 and beyond. The value 0.1 or so is good enough. - Default value is 0.1.*/ - /** @see setBackpropMomentumScale */ - CV_WRAP virtual double getBackpropMomentumScale() const = 0; - /** @copybrief getBackpropMomentumScale @see getBackpropMomentumScale */ - CV_WRAP virtual void setBackpropMomentumScale(double val) = 0; - - /** RPROP: Initial value \f$\Delta_0\f$ of update-values \f$\Delta_{ij}\f$. - Default value is 0.1.*/ - /** @see setRpropDW0 */ - CV_WRAP virtual double getRpropDW0() const = 0; - /** @copybrief getRpropDW0 @see getRpropDW0 */ - CV_WRAP virtual void setRpropDW0(double val) = 0; - - /** RPROP: Increase factor \f$\eta^+\f$. - It must be \>1. Default value is 1.2.*/ - /** @see setRpropDWPlus */ - CV_WRAP virtual double getRpropDWPlus() const = 0; - /** @copybrief getRpropDWPlus @see getRpropDWPlus */ - CV_WRAP virtual void setRpropDWPlus(double val) = 0; - - /** RPROP: Decrease factor \f$\eta^-\f$. - It must be \<1. Default value is 0.5.*/ - /** @see setRpropDWMinus */ - CV_WRAP virtual double getRpropDWMinus() const = 0; - /** @copybrief getRpropDWMinus @see getRpropDWMinus */ - CV_WRAP virtual void setRpropDWMinus(double val) = 0; - - /** RPROP: Update-values lower limit \f$\Delta_{min}\f$. - It must be positive. Default value is FLT_EPSILON.*/ - /** @see setRpropDWMin */ - CV_WRAP virtual double getRpropDWMin() const = 0; - /** @copybrief getRpropDWMin @see getRpropDWMin */ - CV_WRAP virtual void setRpropDWMin(double val) = 0; - - /** RPROP: Update-values upper limit \f$\Delta_{max}\f$. - It must be \>1. Default value is 50.*/ - /** @see setRpropDWMax */ - CV_WRAP virtual double getRpropDWMax() const = 0; - /** @copybrief getRpropDWMax @see getRpropDWMax */ - CV_WRAP virtual void setRpropDWMax(double val) = 0; - - /** ANNEAL: Update initial temperature. - It must be \>=0. Default value is 10.*/ - /** @see setAnnealInitialT */ - CV_WRAP virtual double getAnnealInitialT() const = 0; - /** @copybrief getAnnealInitialT @see getAnnealInitialT */ - CV_WRAP virtual void setAnnealInitialT(double val) = 0; - - /** ANNEAL: Update final temperature. - It must be \>=0 and less than initialT. Default value is 0.1.*/ - /** @see setAnnealFinalT */ - CV_WRAP virtual double getAnnealFinalT() const = 0; - /** @copybrief getAnnealFinalT @see getAnnealFinalT */ - CV_WRAP virtual void setAnnealFinalT(double val) = 0; - - /** ANNEAL: Update cooling ratio. - It must be \>0 and less than 1. Default value is 0.95.*/ - /** @see setAnnealCoolingRatio */ - CV_WRAP virtual double getAnnealCoolingRatio() const = 0; - /** @copybrief getAnnealCoolingRatio @see getAnnealCoolingRatio */ - CV_WRAP virtual void setAnnealCoolingRatio(double val) = 0; - - /** ANNEAL: Update iteration per step. - It must be \>0 . Default value is 10.*/ - /** @see setAnnealItePerStep */ - CV_WRAP virtual int getAnnealItePerStep() const = 0; - /** @copybrief getAnnealItePerStep @see getAnnealItePerStep */ - CV_WRAP virtual void setAnnealItePerStep(int val) = 0; - - /** @brief Set/initialize anneal RNG */ - virtual void setAnnealEnergyRNG(const RNG& rng) = 0; - - /** possible activation functions */ - enum ActivationFunctions { - /** Identity function: \f$f(x)=x\f$ */ - IDENTITY = 0, - /** Symmetrical sigmoid: \f$f(x)=\beta*(1-e^{-\alpha x})/(1+e^{-\alpha x})\f$ - @note - If you are using the default sigmoid activation function with the default parameter values - fparam1=0 and fparam2=0 then the function used is y = 1.7159\*tanh(2/3 \* x), so the output - will range from [-1.7159, 1.7159], instead of [0,1].*/ - SIGMOID_SYM = 1, - /** Gaussian function: \f$f(x)=\beta e^{-\alpha x*x}\f$ */ - GAUSSIAN = 2, - /** ReLU function: \f$f(x)=max(0,x)\f$ */ - RELU = 3, - /** Leaky ReLU function: for x>0 \f$f(x)=x \f$ and x<=0 \f$f(x)=\alpha x \f$*/ - LEAKYRELU= 4 - }; - - /** Train options */ - enum TrainFlags { - /** Update the network weights, rather than compute them from scratch. In the latter case - the weights are initialized using the Nguyen-Widrow algorithm. */ - UPDATE_WEIGHTS = 1, - /** Do not normalize the input vectors. If this flag is not set, the training algorithm - normalizes each input feature independently, shifting its mean value to 0 and making the - standard deviation equal to 1. If the network is assumed to be updated frequently, the new - training data could be much different from original one. In this case, you should take care - of proper normalization. */ - NO_INPUT_SCALE = 2, - /** Do not normalize the output vectors. If the flag is not set, the training algorithm - normalizes each output feature independently, by transforming it to the certain range - depending on the used activation function. */ - NO_OUTPUT_SCALE = 4 - }; - - CV_WRAP virtual Mat getWeights(int layerIdx) const = 0; - - /** @brief Creates empty model - - Use StatModel::train to train the model, Algorithm::load\(filename) to load the pre-trained model. - Note that the train method has optional flags: ANN_MLP::TrainFlags. - */ - CV_WRAP static Ptr create(); - - /** @brief Loads and creates a serialized ANN from a file - * - * Use ANN::save to serialize and store an ANN to disk. - * Load the ANN from this file again, by calling this function with the path to the file. - * - * @param filepath path to serialized ANN - */ - CV_WRAP static Ptr load(const String& filepath); - -}; - -#ifndef DISABLE_OPENCV_3_COMPATIBILITY -typedef ANN_MLP ANN_MLP_ANNEAL; -#endif - -/****************************************************************************************\ -* Logistic Regression * -\****************************************************************************************/ - -/** @brief Implements Logistic Regression classifier. - -@sa @ref ml_intro_lr - */ -class CV_EXPORTS_W LogisticRegression : public StatModel -{ -public: - - /** Learning rate. */ - /** @see setLearningRate */ - CV_WRAP virtual double getLearningRate() const = 0; - /** @copybrief getLearningRate @see getLearningRate */ - CV_WRAP virtual void setLearningRate(double val) = 0; - - /** Number of iterations. */ - /** @see setIterations */ - CV_WRAP virtual int getIterations() const = 0; - /** @copybrief getIterations @see getIterations */ - CV_WRAP virtual void setIterations(int val) = 0; - - /** Kind of regularization to be applied. See LogisticRegression::RegKinds. */ - /** @see setRegularization */ - CV_WRAP virtual int getRegularization() const = 0; - /** @copybrief getRegularization @see getRegularization */ - CV_WRAP virtual void setRegularization(int val) = 0; - - /** Kind of training method used. See LogisticRegression::Methods. */ - /** @see setTrainMethod */ - CV_WRAP virtual int getTrainMethod() const = 0; - /** @copybrief getTrainMethod @see getTrainMethod */ - CV_WRAP virtual void setTrainMethod(int val) = 0; - - /** Specifies the number of training samples taken in each step of Mini-Batch Gradient - Descent. Will only be used if using LogisticRegression::MINI_BATCH training algorithm. It - has to take values less than the total number of training samples. */ - /** @see setMiniBatchSize */ - CV_WRAP virtual int getMiniBatchSize() const = 0; - /** @copybrief getMiniBatchSize @see getMiniBatchSize */ - CV_WRAP virtual void setMiniBatchSize(int val) = 0; - - /** Termination criteria of the algorithm. */ - /** @see setTermCriteria */ - CV_WRAP virtual TermCriteria getTermCriteria() const = 0; - /** @copybrief getTermCriteria @see getTermCriteria */ - CV_WRAP virtual void setTermCriteria(TermCriteria val) = 0; - - //! Regularization kinds - enum RegKinds { - REG_DISABLE = -1, //!< Regularization disabled - REG_L1 = 0, //!< %L1 norm - REG_L2 = 1 //!< %L2 norm - }; - - //! Training methods - enum Methods { - BATCH = 0, - MINI_BATCH = 1 //!< Set MiniBatchSize to a positive integer when using this method. - }; - - /** @brief Predicts responses for input samples and returns a float type. - - @param samples The input data for the prediction algorithm. Matrix [m x n], where each row - contains variables (features) of one object being classified. Should have data type CV_32F. - @param results Predicted labels as a column matrix of type CV_32S. - @param flags Not used. - */ - CV_WRAP virtual float predict( InputArray samples, OutputArray results=noArray(), int flags=0 ) const CV_OVERRIDE = 0; - - /** @brief This function returns the trained parameters arranged across rows. - - For a two class classification problem, it returns a row matrix. It returns learnt parameters of - the Logistic Regression as a matrix of type CV_32F. - */ - CV_WRAP virtual Mat get_learnt_thetas() const = 0; - - /** @brief Creates empty model. - - Creates Logistic Regression model with parameters given. - */ - CV_WRAP static Ptr create(); - - /** @brief Loads and creates a serialized LogisticRegression from a file - * - * Use LogisticRegression::save to serialize and store an LogisticRegression to disk. - * Load the LogisticRegression from this file again, by calling this function with the path to the file. - * Optionally specify the node for the file containing the classifier - * - * @param filepath path to serialized LogisticRegression - * @param nodeName name of node containing the classifier - */ - CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); -}; - - -/****************************************************************************************\ -* Stochastic Gradient Descent SVM Classifier * -\****************************************************************************************/ - -/*! -@brief Stochastic Gradient Descent SVM classifier - -SVMSGD provides a fast and easy-to-use implementation of the SVM classifier using the Stochastic Gradient Descent approach, -as presented in @cite bottou2010large. - -The classifier has following parameters: -- model type, -- margin type, -- margin regularization (\f$\lambda\f$), -- initial step size (\f$\gamma_0\f$), -- step decreasing power (\f$c\f$), -- and termination criteria. - -The model type may have one of the following values: \ref SGD and \ref ASGD. - -- \ref SGD is the classic version of SVMSGD classifier: every next step is calculated by the formula - \f[w_{t+1} = w_t - \gamma(t) \frac{dQ_i}{dw} |_{w = w_t}\f] - where - - \f$w_t\f$ is the weights vector for decision function at step \f$t\f$, - - \f$\gamma(t)\f$ is the step size of model parameters at the iteration \f$t\f$, it is decreased on each step by the formula - \f$\gamma(t) = \gamma_0 (1 + \lambda \gamma_0 t) ^ {-c}\f$ - - \f$Q_i\f$ is the target functional from SVM task for sample with number \f$i\f$, this sample is chosen stochastically on each step of the algorithm. - -- \ref ASGD is Average Stochastic Gradient Descent SVM Classifier. ASGD classifier averages weights vector on each step of algorithm by the formula -\f$\widehat{w}_{t+1} = \frac{t}{1+t}\widehat{w}_{t} + \frac{1}{1+t}w_{t+1}\f$ - -The recommended model type is ASGD (following @cite bottou2010large). - -The margin type may have one of the following values: \ref SOFT_MARGIN or \ref HARD_MARGIN. - -- You should use \ref HARD_MARGIN type, if you have linearly separable sets. -- You should use \ref SOFT_MARGIN type, if you have non-linearly separable sets or sets with outliers. -- In the general case (if you know nothing about linear separability of your sets), use SOFT_MARGIN. - -The other parameters may be described as follows: -- Margin regularization parameter is responsible for weights decreasing at each step and for the strength of restrictions on outliers - (the less the parameter, the less probability that an outlier will be ignored). - Recommended value for SGD model is 0.0001, for ASGD model is 0.00001. - -- Initial step size parameter is the initial value for the step size \f$\gamma(t)\f$. - You will have to find the best initial step for your problem. - -- Step decreasing power is the power parameter for \f$\gamma(t)\f$ decreasing by the formula, mentioned above. - Recommended value for SGD model is 1, for ASGD model is 0.75. - -- Termination criteria can be TermCriteria::COUNT, TermCriteria::EPS or TermCriteria::COUNT + TermCriteria::EPS. - You will have to find the best termination criteria for your problem. - -Note that the parameters margin regularization, initial step size, and step decreasing power should be positive. - -To use SVMSGD algorithm do as follows: - -- first, create the SVMSGD object. The algorithm will set optimal parameters by default, but you can set your own parameters via functions setSvmsgdType(), - setMarginType(), setMarginRegularization(), setInitialStepSize(), and setStepDecreasingPower(). - -- then the SVM model can be trained using the train features and the correspondent labels by the method train(). - -- after that, the label of a new feature vector can be predicted using the method predict(). - -@code -// Create empty object -cv::Ptr svmsgd = SVMSGD::create(); - -// Train the Stochastic Gradient Descent SVM -svmsgd->train(trainData); - -// Predict labels for the new samples -svmsgd->predict(samples, responses); -@endcode - -*/ - -class CV_EXPORTS_W SVMSGD : public cv::ml::StatModel -{ -public: - - /** SVMSGD type. - ASGD is often the preferable choice. */ - enum SvmsgdType - { - SGD, //!< Stochastic Gradient Descent - ASGD //!< Average Stochastic Gradient Descent - }; - - /** Margin type.*/ - enum MarginType - { - SOFT_MARGIN, //!< General case, suits to the case of non-linearly separable sets, allows outliers. - HARD_MARGIN //!< More accurate for the case of linearly separable sets. - }; - - /** - * @return the weights of the trained model (decision function f(x) = weights * x + shift). - */ - CV_WRAP virtual Mat getWeights() = 0; - - /** - * @return the shift of the trained model (decision function f(x) = weights * x + shift). - */ - CV_WRAP virtual float getShift() = 0; - - /** @brief Creates empty model. - * Use StatModel::train to train the model. Since %SVMSGD has several parameters, you may want to - * find the best parameters for your problem or use setOptimalParameters() to set some default parameters. - */ - CV_WRAP static Ptr create(); - - /** @brief Loads and creates a serialized SVMSGD from a file - * - * Use SVMSGD::save to serialize and store an SVMSGD to disk. - * Load the SVMSGD from this file again, by calling this function with the path to the file. - * Optionally specify the node for the file containing the classifier - * - * @param filepath path to serialized SVMSGD - * @param nodeName name of node containing the classifier - */ - CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); - - /** @brief Function sets optimal parameters values for chosen SVM SGD model. - * @param svmsgdType is the type of SVMSGD classifier. - * @param marginType is the type of margin constraint. - */ - CV_WRAP virtual void setOptimalParameters(int svmsgdType = SVMSGD::ASGD, int marginType = SVMSGD::SOFT_MARGIN) = 0; - - /** @brief %Algorithm type, one of SVMSGD::SvmsgdType. */ - /** @see setSvmsgdType */ - CV_WRAP virtual int getSvmsgdType() const = 0; - /** @copybrief getSvmsgdType @see getSvmsgdType */ - CV_WRAP virtual void setSvmsgdType(int svmsgdType) = 0; - - /** @brief %Margin type, one of SVMSGD::MarginType. */ - /** @see setMarginType */ - CV_WRAP virtual int getMarginType() const = 0; - /** @copybrief getMarginType @see getMarginType */ - CV_WRAP virtual void setMarginType(int marginType) = 0; - - /** @brief Parameter marginRegularization of a %SVMSGD optimization problem. */ - /** @see setMarginRegularization */ - CV_WRAP virtual float getMarginRegularization() const = 0; - /** @copybrief getMarginRegularization @see getMarginRegularization */ - CV_WRAP virtual void setMarginRegularization(float marginRegularization) = 0; - - /** @brief Parameter initialStepSize of a %SVMSGD optimization problem. */ - /** @see setInitialStepSize */ - CV_WRAP virtual float getInitialStepSize() const = 0; - /** @copybrief getInitialStepSize @see getInitialStepSize */ - CV_WRAP virtual void setInitialStepSize(float InitialStepSize) = 0; - - /** @brief Parameter stepDecreasingPower of a %SVMSGD optimization problem. */ - /** @see setStepDecreasingPower */ - CV_WRAP virtual float getStepDecreasingPower() const = 0; - /** @copybrief getStepDecreasingPower @see getStepDecreasingPower */ - CV_WRAP virtual void setStepDecreasingPower(float stepDecreasingPower) = 0; - - /** @brief Termination criteria of the training algorithm. - You can specify the maximum number of iterations (maxCount) and/or how much the error could - change between the iterations to make the algorithm continue (epsilon).*/ - /** @see setTermCriteria */ - CV_WRAP virtual TermCriteria getTermCriteria() const = 0; - /** @copybrief getTermCriteria @see getTermCriteria */ - CV_WRAP virtual void setTermCriteria(const cv::TermCriteria &val) = 0; -}; - - -/****************************************************************************************\ -* Auxiliary functions declarations * -\****************************************************************************************/ - -/** @brief Generates _sample_ from multivariate normal distribution - -@param mean an average row vector -@param cov symmetric covariation matrix -@param nsamples returned samples count -@param samples returned samples array -*/ -CV_EXPORTS void randMVNormal( InputArray mean, InputArray cov, int nsamples, OutputArray samples); - -/** @brief Creates test set */ -CV_EXPORTS void createConcentricSpheresTestSet( int nsamples, int nfeatures, int nclasses, - OutputArray samples, OutputArray responses); - - -/****************************************************************************************\ -* Simulated annealing solver * -\****************************************************************************************/ - -#ifdef CV_DOXYGEN -/** @brief This class declares example interface for system state used in simulated annealing optimization algorithm. - -@note This class is not defined in C++ code and can't be use directly - you need your own implementation with the same methods. -*/ -struct SimulatedAnnealingSolverSystem -{ - /** Give energy value for a state of system.*/ - double energy() const; - /** Function which change the state of system (random perturbation).*/ - void changeState(); - /** Function to reverse to the previous state. Can be called once only after changeState(). */ - void reverseState(); -}; -#endif // CV_DOXYGEN - -/** @brief The class implements simulated annealing for optimization. - -@cite Kirkpatrick83 for details - -@param solverSystem optimization system (see SimulatedAnnealingSolverSystem) -@param initialTemperature initial temperature -@param finalTemperature final temperature -@param coolingRatio temperature step multiplies -@param iterationsPerStep number of iterations per temperature changing step -@param lastTemperature optional output for last used temperature -@param rngEnergy specify custom random numbers generator (cv::theRNG() by default) -*/ -template -int simulatedAnnealingSolver(SimulatedAnnealingSolverSystem& solverSystem, - double initialTemperature, double finalTemperature, double coolingRatio, - size_t iterationsPerStep, - CV_OUT double* lastTemperature = NULL, - cv::RNG& rngEnergy = cv::theRNG() -); - -//! @} ml - -} -} - -#include - -#endif // __cplusplus -#endif // OPENCV_ML_HPP - -/* End of file. */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000, Intel Corporation, all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2014, Itseez Inc, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_ML_HPP +#define OPENCV_ML_HPP + +#ifdef __cplusplus +# include "opencv2/core.hpp" +#endif + +#ifdef __cplusplus + +#include +#include +#include + +/** + @defgroup ml Machine Learning + + The Machine Learning Library (MLL) is a set of classes and functions for statistical + classification, regression, and clustering of data. + + Most of the classification and regression algorithms are implemented as C++ classes. As the + algorithms have different sets of features (like an ability to handle missing measurements or + categorical input variables), there is a little common ground between the classes. This common + ground is defined by the class cv::ml::StatModel that all the other ML classes are derived from. + + See detailed overview here: @ref ml_intro. + */ + +namespace cv +{ + +namespace ml +{ + +//! @addtogroup ml +//! @{ + +/** @brief Variable types */ +enum VariableTypes +{ + VAR_NUMERICAL =0, //!< same as VAR_ORDERED + VAR_ORDERED =0, //!< ordered variables + VAR_CATEGORICAL =1 //!< categorical variables +}; + +/** @brief %Error types */ +enum ErrorTypes +{ + TEST_ERROR = 0, + TRAIN_ERROR = 1 +}; + +/** @brief Sample types */ +enum SampleTypes +{ + ROW_SAMPLE = 0, //!< each training sample is a row of samples + COL_SAMPLE = 1 //!< each training sample occupies a column of samples +}; + +/** @brief The structure represents the logarithmic grid range of statmodel parameters. + +It is used for optimizing statmodel accuracy by varying model parameters, the accuracy estimate +being computed by cross-validation. + */ +class CV_EXPORTS_W ParamGrid +{ +public: + /** @brief Default constructor */ + ParamGrid(); + /** @brief Constructor with parameters */ + ParamGrid(double _minVal, double _maxVal, double _logStep); + + CV_PROP_RW double minVal; //!< Minimum value of the statmodel parameter. Default value is 0. + CV_PROP_RW double maxVal; //!< Maximum value of the statmodel parameter. Default value is 0. + /** @brief Logarithmic step for iterating the statmodel parameter. + + The grid determines the following iteration sequence of the statmodel parameter values: + \f[(minVal, minVal*step, minVal*{step}^2, \dots, minVal*{logStep}^n),\f] + where \f$n\f$ is the maximal index satisfying + \f[\texttt{minVal} * \texttt{logStep} ^n < \texttt{maxVal}\f] + The grid is logarithmic, so logStep must always be greater than 1. Default value is 1. + */ + CV_PROP_RW double logStep; + + /** @brief Creates a ParamGrid Ptr that can be given to the %SVM::trainAuto method + + @param minVal minimum value of the parameter grid + @param maxVal maximum value of the parameter grid + @param logstep Logarithmic step for iterating the statmodel parameter + */ + CV_WRAP static Ptr create(double minVal=0., double maxVal=0., double logstep=1.); +}; + +/** @brief Class encapsulating training data. + +Please note that the class only specifies the interface of training data, but not implementation. +All the statistical model classes in _ml_ module accepts Ptr\ as parameter. In other +words, you can create your own class derived from TrainData and pass smart pointer to the instance +of this class into StatModel::train. + +@sa @ref ml_intro_data + */ +class CV_EXPORTS_W TrainData +{ +public: + static inline float missingValue() { return FLT_MAX; } + virtual ~TrainData(); + + CV_WRAP virtual int getLayout() const = 0; + CV_WRAP virtual int getNTrainSamples() const = 0; + CV_WRAP virtual int getNTestSamples() const = 0; + CV_WRAP virtual int getNSamples() const = 0; + CV_WRAP virtual int getNVars() const = 0; + CV_WRAP virtual int getNAllVars() const = 0; + + CV_WRAP virtual void getSample(InputArray varIdx, int sidx, float* buf) const = 0; + CV_WRAP virtual Mat getSamples() const = 0; + CV_WRAP virtual Mat getMissing() const = 0; + + /** @brief Returns matrix of train samples + + @param layout The requested layout. If it's different from the initial one, the matrix is + transposed. See ml::SampleTypes. + @param compressSamples if true, the function returns only the training samples (specified by + sampleIdx) + @param compressVars if true, the function returns the shorter training samples, containing only + the active variables. + + In current implementation the function tries to avoid physical data copying and returns the + matrix stored inside TrainData (unless the transposition or compression is needed). + */ + CV_WRAP virtual Mat getTrainSamples(int layout=ROW_SAMPLE, + bool compressSamples=true, + bool compressVars=true) const = 0; + + /** @brief Returns the vector of responses + + The function returns ordered or the original categorical responses. Usually it's used in + regression algorithms. + */ + CV_WRAP virtual Mat getTrainResponses() const = 0; + + /** @brief Returns the vector of normalized categorical responses + + The function returns vector of responses. Each response is integer from `0` to `-1`. The actual label value can be retrieved then from the class label vector, see + TrainData::getClassLabels. + */ + CV_WRAP virtual Mat getTrainNormCatResponses() const = 0; + CV_WRAP virtual Mat getTestResponses() const = 0; + CV_WRAP virtual Mat getTestNormCatResponses() const = 0; + CV_WRAP virtual Mat getResponses() const = 0; + CV_WRAP virtual Mat getNormCatResponses() const = 0; + CV_WRAP virtual Mat getSampleWeights() const = 0; + CV_WRAP virtual Mat getTrainSampleWeights() const = 0; + CV_WRAP virtual Mat getTestSampleWeights() const = 0; + CV_WRAP virtual Mat getVarIdx() const = 0; + CV_WRAP virtual Mat getVarType() const = 0; + CV_WRAP virtual Mat getVarSymbolFlags() const = 0; + CV_WRAP virtual int getResponseType() const = 0; + CV_WRAP virtual Mat getTrainSampleIdx() const = 0; + CV_WRAP virtual Mat getTestSampleIdx() const = 0; + CV_WRAP virtual void getValues(int vi, InputArray sidx, float* values) const = 0; + virtual void getNormCatValues(int vi, InputArray sidx, int* values) const = 0; + CV_WRAP virtual Mat getDefaultSubstValues() const = 0; + + CV_WRAP virtual int getCatCount(int vi) const = 0; + + /** @brief Returns the vector of class labels + + The function returns vector of unique labels occurred in the responses. + */ + CV_WRAP virtual Mat getClassLabels() const = 0; + + CV_WRAP virtual Mat getCatOfs() const = 0; + CV_WRAP virtual Mat getCatMap() const = 0; + + /** @brief Splits the training data into the training and test parts + @sa TrainData::setTrainTestSplitRatio + */ + CV_WRAP virtual void setTrainTestSplit(int count, bool shuffle=true) = 0; + + /** @brief Splits the training data into the training and test parts + + The function selects a subset of specified relative size and then returns it as the training + set. If the function is not called, all the data is used for training. Please, note that for + each of TrainData::getTrain\* there is corresponding TrainData::getTest\*, so that the test + subset can be retrieved and processed as well. + @sa TrainData::setTrainTestSplit + */ + CV_WRAP virtual void setTrainTestSplitRatio(double ratio, bool shuffle=true) = 0; + CV_WRAP virtual void shuffleTrainTest() = 0; + + /** @brief Returns matrix of test samples */ + CV_WRAP virtual Mat getTestSamples() const = 0; + + /** @brief Returns vector of symbolic names captured in loadFromCSV() */ + CV_WRAP virtual void getNames(std::vector& names) const = 0; + + /** @brief Extract from 1D vector elements specified by passed indexes. + @param vec input vector (supported types: CV_32S, CV_32F, CV_64F) + @param idx 1D index vector + */ + static CV_WRAP Mat getSubVector(const Mat& vec, const Mat& idx); + + /** @brief Extract from matrix rows/cols specified by passed indexes. + @param matrix input matrix (supported types: CV_32S, CV_32F, CV_64F) + @param idx 1D index vector + @param layout specifies to extract rows (cv::ml::ROW_SAMPLES) or to extract columns (cv::ml::COL_SAMPLES) + */ + static CV_WRAP Mat getSubMatrix(const Mat& matrix, const Mat& idx, int layout); + + /** @brief Reads the dataset from a .csv file and returns the ready-to-use training data. + + @param filename The input file name + @param headerLineCount The number of lines in the beginning to skip; besides the header, the + function also skips empty lines and lines staring with `#` + @param responseStartIdx Index of the first output variable. If -1, the function considers the + last variable as the response + @param responseEndIdx Index of the last output variable + 1. If -1, then there is single + response variable at responseStartIdx. + @param varTypeSpec The optional text string that specifies the variables' types. It has the + format `ord[n1-n2,n3,n4-n5,...]cat[n6,n7-n8,...]`. That is, variables from `n1 to n2` + (inclusive range), `n3`, `n4 to n5` ... are considered ordered and `n6`, `n7 to n8` ... are + considered as categorical. The range `[n1..n2] + [n3] + [n4..n5] + ... + [n6] + [n7..n8]` + should cover all the variables. If varTypeSpec is not specified, then algorithm uses the + following rules: + - all input variables are considered ordered by default. If some column contains has non- + numerical values, e.g. 'apple', 'pear', 'apple', 'apple', 'mango', the corresponding + variable is considered categorical. + - if there are several output variables, they are all considered as ordered. Error is + reported when non-numerical values are used. + - if there is a single output variable, then if its values are non-numerical or are all + integers, then it's considered categorical. Otherwise, it's considered ordered. + @param delimiter The character used to separate values in each line. + @param missch The character used to specify missing measurements. It should not be a digit. + Although it's a non-numerical value, it surely does not affect the decision of whether the + variable ordered or categorical. + @note If the dataset only contains input variables and no responses, use responseStartIdx = -2 + and responseEndIdx = 0. The output variables vector will just contain zeros. + */ + static Ptr loadFromCSV(const String& filename, + int headerLineCount, + int responseStartIdx=-1, + int responseEndIdx=-1, + const String& varTypeSpec=String(), + char delimiter=',', + char missch='?'); + + /** @brief Creates training data from in-memory arrays. + + @param samples matrix of samples. It should have CV_32F type. + @param layout see ml::SampleTypes. + @param responses matrix of responses. If the responses are scalar, they should be stored as a + single row or as a single column. The matrix should have type CV_32F or CV_32S (in the + former case the responses are considered as ordered by default; in the latter case - as + categorical) + @param varIdx vector specifying which variables to use for training. It can be an integer vector + (CV_32S) containing 0-based variable indices or byte vector (CV_8U) containing a mask of + active variables. + @param sampleIdx vector specifying which samples to use for training. It can be an integer + vector (CV_32S) containing 0-based sample indices or byte vector (CV_8U) containing a mask + of training samples. + @param sampleWeights optional vector with weights for each sample. It should have CV_32F type. + @param varType optional vector of type CV_8U and size ` + + `, containing types of each input and output variable. See + ml::VariableTypes. + */ + CV_WRAP static Ptr create(InputArray samples, int layout, InputArray responses, + InputArray varIdx=noArray(), InputArray sampleIdx=noArray(), + InputArray sampleWeights=noArray(), InputArray varType=noArray()); +}; + +/** @brief Base class for statistical models in OpenCV ML. + */ +class CV_EXPORTS_W StatModel : public Algorithm +{ +public: + /** Predict options */ + enum Flags { + UPDATE_MODEL = 1, + RAW_OUTPUT=1, //!< makes the method return the raw results (the sum), not the class label + COMPRESSED_INPUT=2, + PREPROCESSED_INPUT=4 + }; + + /** @brief Returns the number of variables in training samples */ + CV_WRAP virtual int getVarCount() const = 0; + + CV_WRAP virtual bool empty() const CV_OVERRIDE; + + /** @brief Returns true if the model is trained */ + CV_WRAP virtual bool isTrained() const = 0; + /** @brief Returns true if the model is classifier */ + CV_WRAP virtual bool isClassifier() const = 0; + + /** @brief Trains the statistical model + + @param trainData training data that can be loaded from file using TrainData::loadFromCSV or + created with TrainData::create. + @param flags optional flags, depending on the model. Some of the models can be updated with the + new training samples, not completely overwritten (such as NormalBayesClassifier or ANN_MLP). + */ + CV_WRAP virtual bool train( const Ptr& trainData, int flags=0 ); + + /** @brief Trains the statistical model + + @param samples training samples + @param layout See ml::SampleTypes. + @param responses vector of responses associated with the training samples. + */ + CV_WRAP virtual bool train( InputArray samples, int layout, InputArray responses ); + + /** @brief Computes error on the training or test dataset + + @param data the training data + @param test if true, the error is computed over the test subset of the data, otherwise it's + computed over the training subset of the data. Please note that if you loaded a completely + different dataset to evaluate already trained classifier, you will probably want not to set + the test subset at all with TrainData::setTrainTestSplitRatio and specify test=false, so + that the error is computed for the whole new set. Yes, this sounds a bit confusing. + @param resp the optional output responses. + + The method uses StatModel::predict to compute the error. For regression models the error is + computed as RMS, for classifiers - as a percent of missclassified samples (0%-100%). + */ + CV_WRAP virtual float calcError( const Ptr& data, bool test, OutputArray resp ) const; + + /** @brief Predicts response(s) for the provided sample(s) + + @param samples The input samples, floating-point matrix + @param results The optional output matrix of results. + @param flags The optional flags, model-dependent. See cv::ml::StatModel::Flags. + */ + CV_WRAP virtual float predict( InputArray samples, OutputArray results=noArray(), int flags=0 ) const = 0; + + /** @brief Create and train model with default parameters + + The class must implement static `create()` method with no parameters or with all default parameter values + */ + template static Ptr<_Tp> train(const Ptr& data, int flags=0) + { + Ptr<_Tp> model = _Tp::create(); + return !model.empty() && model->train(data, flags) ? model : Ptr<_Tp>(); + } +}; + +/****************************************************************************************\ +* Normal Bayes Classifier * +\****************************************************************************************/ + +/** @brief Bayes classifier for normally distributed data. + +@sa @ref ml_intro_bayes + */ +class CV_EXPORTS_W NormalBayesClassifier : public StatModel +{ +public: + /** @brief Predicts the response for sample(s). + + The method estimates the most probable classes for input vectors. Input vectors (one or more) + are stored as rows of the matrix inputs. In case of multiple input vectors, there should be one + output vector outputs. The predicted class for a single input vector is returned by the method. + The vector outputProbs contains the output probabilities corresponding to each element of + result. + */ + CV_WRAP virtual float predictProb( InputArray inputs, OutputArray outputs, + OutputArray outputProbs, int flags=0 ) const = 0; + + /** Creates empty model + Use StatModel::train to train the model after creation. */ + CV_WRAP static Ptr create(); + + /** @brief Loads and creates a serialized NormalBayesClassifier from a file + * + * Use NormalBayesClassifier::save to serialize and store an NormalBayesClassifier to disk. + * Load the NormalBayesClassifier from this file again, by calling this function with the path to the file. + * Optionally specify the node for the file containing the classifier + * + * @param filepath path to serialized NormalBayesClassifier + * @param nodeName name of node containing the classifier + */ + CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); +}; + +/****************************************************************************************\ +* K-Nearest Neighbour Classifier * +\****************************************************************************************/ + +/** @brief The class implements K-Nearest Neighbors model + +@sa @ref ml_intro_knn + */ +class CV_EXPORTS_W KNearest : public StatModel +{ +public: + + /** Default number of neighbors to use in predict method. */ + /** @see setDefaultK */ + CV_WRAP virtual int getDefaultK() const = 0; + /** @copybrief getDefaultK @see getDefaultK */ + CV_WRAP virtual void setDefaultK(int val) = 0; + + /** Whether classification or regression model should be trained. */ + /** @see setIsClassifier */ + CV_WRAP virtual bool getIsClassifier() const = 0; + /** @copybrief getIsClassifier @see getIsClassifier */ + CV_WRAP virtual void setIsClassifier(bool val) = 0; + + /** Parameter for KDTree implementation. */ + /** @see setEmax */ + CV_WRAP virtual int getEmax() const = 0; + /** @copybrief getEmax @see getEmax */ + CV_WRAP virtual void setEmax(int val) = 0; + + /** %Algorithm type, one of KNearest::Types. */ + /** @see setAlgorithmType */ + CV_WRAP virtual int getAlgorithmType() const = 0; + /** @copybrief getAlgorithmType @see getAlgorithmType */ + CV_WRAP virtual void setAlgorithmType(int val) = 0; + + /** @brief Finds the neighbors and predicts responses for input vectors. + + @param samples Input samples stored by rows. It is a single-precision floating-point matrix of + ` * k` size. + @param k Number of used nearest neighbors. Should be greater than 1. + @param results Vector with results of prediction (regression or classification) for each input + sample. It is a single-precision floating-point vector with `` elements. + @param neighborResponses Optional output values for corresponding neighbors. It is a single- + precision floating-point matrix of ` * k` size. + @param dist Optional output distances from the input vectors to the corresponding neighbors. It + is a single-precision floating-point matrix of ` * k` size. + + For each input vector (a row of the matrix samples), the method finds the k nearest neighbors. + In case of regression, the predicted result is a mean value of the particular vector's neighbor + responses. In case of classification, the class is determined by voting. + + For each input vector, the neighbors are sorted by their distances to the vector. + + In case of C++ interface you can use output pointers to empty matrices and the function will + allocate memory itself. + + If only a single input vector is passed, all output matrices are optional and the predicted + value is returned by the method. + + The function is parallelized with the TBB library. + */ + CV_WRAP virtual float findNearest( InputArray samples, int k, + OutputArray results, + OutputArray neighborResponses=noArray(), + OutputArray dist=noArray() ) const = 0; + + /** @brief Implementations of KNearest algorithm + */ + enum Types + { + BRUTE_FORCE=1, + KDTREE=2 + }; + + /** @brief Creates the empty model + + The static method creates empty %KNearest classifier. It should be then trained using StatModel::train method. + */ + CV_WRAP static Ptr create(); + /** @brief Loads and creates a serialized knearest from a file + * + * Use KNearest::save to serialize and store an KNearest to disk. + * Load the KNearest from this file again, by calling this function with the path to the file. + * + * @param filepath path to serialized KNearest + */ + CV_WRAP static Ptr load(const String& filepath); +}; + +/****************************************************************************************\ +* Support Vector Machines * +\****************************************************************************************/ + +/** @brief Support Vector Machines. + +@sa @ref ml_intro_svm + */ +class CV_EXPORTS_W SVM : public StatModel +{ +public: + + class CV_EXPORTS Kernel : public Algorithm + { + public: + virtual int getType() const = 0; + virtual void calc( int vcount, int n, const float* vecs, const float* another, float* results ) = 0; + }; + + /** Type of a %SVM formulation. + See SVM::Types. Default value is SVM::C_SVC. */ + /** @see setType */ + CV_WRAP virtual int getType() const = 0; + /** @copybrief getType @see getType */ + CV_WRAP virtual void setType(int val) = 0; + + /** Parameter \f$\gamma\f$ of a kernel function. + For SVM::POLY, SVM::RBF, SVM::SIGMOID or SVM::CHI2. Default value is 1. */ + /** @see setGamma */ + CV_WRAP virtual double getGamma() const = 0; + /** @copybrief getGamma @see getGamma */ + CV_WRAP virtual void setGamma(double val) = 0; + + /** Parameter _coef0_ of a kernel function. + For SVM::POLY or SVM::SIGMOID. Default value is 0.*/ + /** @see setCoef0 */ + CV_WRAP virtual double getCoef0() const = 0; + /** @copybrief getCoef0 @see getCoef0 */ + CV_WRAP virtual void setCoef0(double val) = 0; + + /** Parameter _degree_ of a kernel function. + For SVM::POLY. Default value is 0. */ + /** @see setDegree */ + CV_WRAP virtual double getDegree() const = 0; + /** @copybrief getDegree @see getDegree */ + CV_WRAP virtual void setDegree(double val) = 0; + + /** Parameter _C_ of a %SVM optimization problem. + For SVM::C_SVC, SVM::EPS_SVR or SVM::NU_SVR. Default value is 0. */ + /** @see setC */ + CV_WRAP virtual double getC() const = 0; + /** @copybrief getC @see getC */ + CV_WRAP virtual void setC(double val) = 0; + + /** Parameter \f$\nu\f$ of a %SVM optimization problem. + For SVM::NU_SVC, SVM::ONE_CLASS or SVM::NU_SVR. Default value is 0. */ + /** @see setNu */ + CV_WRAP virtual double getNu() const = 0; + /** @copybrief getNu @see getNu */ + CV_WRAP virtual void setNu(double val) = 0; + + /** Parameter \f$\epsilon\f$ of a %SVM optimization problem. + For SVM::EPS_SVR. Default value is 0. */ + /** @see setP */ + CV_WRAP virtual double getP() const = 0; + /** @copybrief getP @see getP */ + CV_WRAP virtual void setP(double val) = 0; + + /** Optional weights in the SVM::C_SVC problem, assigned to particular classes. + They are multiplied by _C_ so the parameter _C_ of class _i_ becomes `classWeights(i) * C`. Thus + these weights affect the misclassification penalty for different classes. The larger weight, + the larger penalty on misclassification of data from the corresponding class. Default value is + empty Mat. */ + /** @see setClassWeights */ + CV_WRAP virtual cv::Mat getClassWeights() const = 0; + /** @copybrief getClassWeights @see getClassWeights */ + CV_WRAP virtual void setClassWeights(const cv::Mat &val) = 0; + + /** Termination criteria of the iterative %SVM training procedure which solves a partial + case of constrained quadratic optimization problem. + You can specify tolerance and/or the maximum number of iterations. Default value is + `TermCriteria( TermCriteria::MAX_ITER + TermCriteria::EPS, 1000, FLT_EPSILON )`; */ + /** @see setTermCriteria */ + CV_WRAP virtual cv::TermCriteria getTermCriteria() const = 0; + /** @copybrief getTermCriteria @see getTermCriteria */ + CV_WRAP virtual void setTermCriteria(const cv::TermCriteria &val) = 0; + + /** Type of a %SVM kernel. + See SVM::KernelTypes. Default value is SVM::RBF. */ + CV_WRAP virtual int getKernelType() const = 0; + + /** Initialize with one of predefined kernels. + See SVM::KernelTypes. */ + CV_WRAP virtual void setKernel(int kernelType) = 0; + + /** Initialize with custom kernel. + See SVM::Kernel class for implementation details */ + virtual void setCustomKernel(const Ptr &_kernel) = 0; + + //! %SVM type + enum Types { + /** C-Support Vector Classification. n-class classification (n \f$\geq\f$ 2), allows + imperfect separation of classes with penalty multiplier C for outliers. */ + C_SVC=100, + /** \f$\nu\f$-Support Vector Classification. n-class classification with possible + imperfect separation. Parameter \f$\nu\f$ (in the range 0..1, the larger the value, the smoother + the decision boundary) is used instead of C. */ + NU_SVC=101, + /** Distribution Estimation (One-class %SVM). All the training data are from + the same class, %SVM builds a boundary that separates the class from the rest of the feature + space. */ + ONE_CLASS=102, + /** \f$\epsilon\f$-Support Vector Regression. The distance between feature vectors + from the training set and the fitting hyper-plane must be less than p. For outliers the + penalty multiplier C is used. */ + EPS_SVR=103, + /** \f$\nu\f$-Support Vector Regression. \f$\nu\f$ is used instead of p. + See @cite LibSVM for details. */ + NU_SVR=104 + }; + + /** @brief %SVM kernel type + + A comparison of different kernels on the following 2D test case with four classes. Four + SVM::C_SVC SVMs have been trained (one against rest) with auto_train. Evaluation on three + different kernels (SVM::CHI2, SVM::INTER, SVM::RBF). The color depicts the class with max score. + Bright means max-score \> 0, dark means max-score \< 0. + ![image](pics/SVM_Comparison.png) + */ + enum KernelTypes { + /** Returned by SVM::getKernelType in case when custom kernel has been set */ + CUSTOM=-1, + /** Linear kernel. No mapping is done, linear discrimination (or regression) is + done in the original feature space. It is the fastest option. \f$K(x_i, x_j) = x_i^T x_j\f$. */ + LINEAR=0, + /** Polynomial kernel: + \f$K(x_i, x_j) = (\gamma x_i^T x_j + coef0)^{degree}, \gamma > 0\f$. */ + POLY=1, + /** Radial basis function (RBF), a good choice in most cases. + \f$K(x_i, x_j) = e^{-\gamma ||x_i - x_j||^2}, \gamma > 0\f$. */ + RBF=2, + /** Sigmoid kernel: \f$K(x_i, x_j) = \tanh(\gamma x_i^T x_j + coef0)\f$. */ + SIGMOID=3, + /** Exponential Chi2 kernel, similar to the RBF kernel: + \f$K(x_i, x_j) = e^{-\gamma \chi^2(x_i,x_j)}, \chi^2(x_i,x_j) = (x_i-x_j)^2/(x_i+x_j), \gamma > 0\f$. */ + CHI2=4, + /** Histogram intersection kernel. A fast kernel. \f$K(x_i, x_j) = min(x_i,x_j)\f$. */ + INTER=5 + }; + + //! %SVM params type + enum ParamTypes { + C=0, + GAMMA=1, + P=2, + NU=3, + COEF=4, + DEGREE=5 + }; + + /** @brief Trains an %SVM with optimal parameters. + + @param data the training data that can be constructed using TrainData::create or + TrainData::loadFromCSV. + @param kFold Cross-validation parameter. The training set is divided into kFold subsets. One + subset is used to test the model, the others form the train set. So, the %SVM algorithm is + executed kFold times. + @param Cgrid grid for C + @param gammaGrid grid for gamma + @param pGrid grid for p + @param nuGrid grid for nu + @param coeffGrid grid for coeff + @param degreeGrid grid for degree + @param balanced If true and the problem is 2-class classification then the method creates more + balanced cross-validation subsets that is proportions between classes in subsets are close + to such proportion in the whole train dataset. + + The method trains the %SVM model automatically by choosing the optimal parameters C, gamma, p, + nu, coef0, degree. Parameters are considered optimal when the cross-validation + estimate of the test set error is minimal. + + If there is no need to optimize a parameter, the corresponding grid step should be set to any + value less than or equal to 1. For example, to avoid optimization in gamma, set `gammaGrid.step + = 0`, `gammaGrid.minVal`, `gamma_grid.maxVal` as arbitrary numbers. In this case, the value + `Gamma` is taken for gamma. + + And, finally, if the optimization in a parameter is required but the corresponding grid is + unknown, you may call the function SVM::getDefaultGrid. To generate a grid, for example, for + gamma, call `SVM::getDefaultGrid(SVM::GAMMA)`. + + This function works for the classification (SVM::C_SVC or SVM::NU_SVC) as well as for the + regression (SVM::EPS_SVR or SVM::NU_SVR). If it is SVM::ONE_CLASS, no optimization is made and + the usual %SVM with parameters specified in params is executed. + */ + virtual bool trainAuto( const Ptr& data, int kFold = 10, + ParamGrid Cgrid = getDefaultGrid(C), + ParamGrid gammaGrid = getDefaultGrid(GAMMA), + ParamGrid pGrid = getDefaultGrid(P), + ParamGrid nuGrid = getDefaultGrid(NU), + ParamGrid coeffGrid = getDefaultGrid(COEF), + ParamGrid degreeGrid = getDefaultGrid(DEGREE), + bool balanced=false) = 0; + + /** @brief Trains an %SVM with optimal parameters + + @param samples training samples + @param layout See ml::SampleTypes. + @param responses vector of responses associated with the training samples. + @param kFold Cross-validation parameter. The training set is divided into kFold subsets. One + subset is used to test the model, the others form the train set. So, the %SVM algorithm is + @param Cgrid grid for C + @param gammaGrid grid for gamma + @param pGrid grid for p + @param nuGrid grid for nu + @param coeffGrid grid for coeff + @param degreeGrid grid for degree + @param balanced If true and the problem is 2-class classification then the method creates more + balanced cross-validation subsets that is proportions between classes in subsets are close + to such proportion in the whole train dataset. + + The method trains the %SVM model automatically by choosing the optimal parameters C, gamma, p, + nu, coef0, degree. Parameters are considered optimal when the cross-validation + estimate of the test set error is minimal. + + This function only makes use of SVM::getDefaultGrid for parameter optimization and thus only + offers rudimentary parameter options. + + This function works for the classification (SVM::C_SVC or SVM::NU_SVC) as well as for the + regression (SVM::EPS_SVR or SVM::NU_SVR). If it is SVM::ONE_CLASS, no optimization is made and + the usual %SVM with parameters specified in params is executed. + */ + CV_WRAP virtual bool trainAuto(InputArray samples, + int layout, + InputArray responses, + int kFold = 10, + Ptr Cgrid = SVM::getDefaultGridPtr(SVM::C), + Ptr gammaGrid = SVM::getDefaultGridPtr(SVM::GAMMA), + Ptr pGrid = SVM::getDefaultGridPtr(SVM::P), + Ptr nuGrid = SVM::getDefaultGridPtr(SVM::NU), + Ptr coeffGrid = SVM::getDefaultGridPtr(SVM::COEF), + Ptr degreeGrid = SVM::getDefaultGridPtr(SVM::DEGREE), + bool balanced=false) = 0; + + /** @brief Retrieves all the support vectors + + The method returns all the support vectors as a floating-point matrix, where support vectors are + stored as matrix rows. + */ + CV_WRAP virtual Mat getSupportVectors() const = 0; + + /** @brief Retrieves all the uncompressed support vectors of a linear %SVM + + The method returns all the uncompressed support vectors of a linear %SVM that the compressed + support vector, used for prediction, was derived from. They are returned in a floating-point + matrix, where the support vectors are stored as matrix rows. + */ + CV_WRAP virtual Mat getUncompressedSupportVectors() const = 0; + + /** @brief Retrieves the decision function + + @param i the index of the decision function. If the problem solved is regression, 1-class or + 2-class classification, then there will be just one decision function and the index should + always be 0. Otherwise, in the case of N-class classification, there will be \f$N(N-1)/2\f$ + decision functions. + @param alpha the optional output vector for weights, corresponding to different support vectors. + In the case of linear %SVM all the alpha's will be 1's. + @param svidx the optional output vector of indices of support vectors within the matrix of + support vectors (which can be retrieved by SVM::getSupportVectors). In the case of linear + %SVM each decision function consists of a single "compressed" support vector. + + The method returns rho parameter of the decision function, a scalar subtracted from the weighted + sum of kernel responses. + */ + CV_WRAP virtual double getDecisionFunction(int i, OutputArray alpha, OutputArray svidx) const = 0; + + /** @brief Generates a grid for %SVM parameters. + + @param param_id %SVM parameters IDs that must be one of the SVM::ParamTypes. The grid is + generated for the parameter with this ID. + + The function generates a grid for the specified parameter of the %SVM algorithm. The grid may be + passed to the function SVM::trainAuto. + */ + static ParamGrid getDefaultGrid( int param_id ); + + /** @brief Generates a grid for %SVM parameters. + + @param param_id %SVM parameters IDs that must be one of the SVM::ParamTypes. The grid is + generated for the parameter with this ID. + + The function generates a grid pointer for the specified parameter of the %SVM algorithm. + The grid may be passed to the function SVM::trainAuto. + */ + CV_WRAP static Ptr getDefaultGridPtr( int param_id ); + + /** Creates empty model. + Use StatModel::train to train the model. Since %SVM has several parameters, you may want to + find the best parameters for your problem, it can be done with SVM::trainAuto. */ + CV_WRAP static Ptr create(); + + /** @brief Loads and creates a serialized svm from a file + * + * Use SVM::save to serialize and store an SVM to disk. + * Load the SVM from this file again, by calling this function with the path to the file. + * + * @param filepath path to serialized svm + */ + CV_WRAP static Ptr load(const String& filepath); +}; + +/****************************************************************************************\ +* Expectation - Maximization * +\****************************************************************************************/ + +/** @brief The class implements the Expectation Maximization algorithm. + +@sa @ref ml_intro_em + */ +class CV_EXPORTS_W EM : public StatModel +{ +public: + //! Type of covariation matrices + enum Types { + /** A scaled identity matrix \f$\mu_k * I\f$. There is the only + parameter \f$\mu_k\f$ to be estimated for each matrix. The option may be used in special cases, + when the constraint is relevant, or as a first step in the optimization (for example in case + when the data is preprocessed with PCA). The results of such preliminary estimation may be + passed again to the optimization procedure, this time with + covMatType=EM::COV_MAT_DIAGONAL. */ + COV_MAT_SPHERICAL=0, + /** A diagonal matrix with positive diagonal elements. The number of + free parameters is d for each matrix. This is most commonly used option yielding good + estimation results. */ + COV_MAT_DIAGONAL=1, + /** A symmetric positively defined matrix. The number of free + parameters in each matrix is about \f$d^2/2\f$. It is not recommended to use this option, unless + there is pretty accurate initial estimation of the parameters and/or a huge number of + training samples. */ + COV_MAT_GENERIC=2, + COV_MAT_DEFAULT=COV_MAT_DIAGONAL + }; + + //! Default parameters + enum {DEFAULT_NCLUSTERS=5, DEFAULT_MAX_ITERS=100}; + + //! The initial step + enum {START_E_STEP=1, START_M_STEP=2, START_AUTO_STEP=0}; + + /** The number of mixture components in the Gaussian mixture model. + Default value of the parameter is EM::DEFAULT_NCLUSTERS=5. Some of %EM implementation could + determine the optimal number of mixtures within a specified value range, but that is not the + case in ML yet. */ + /** @see setClustersNumber */ + CV_WRAP virtual int getClustersNumber() const = 0; + /** @copybrief getClustersNumber @see getClustersNumber */ + CV_WRAP virtual void setClustersNumber(int val) = 0; + + /** Constraint on covariance matrices which defines type of matrices. + See EM::Types. */ + /** @see setCovarianceMatrixType */ + CV_WRAP virtual int getCovarianceMatrixType() const = 0; + /** @copybrief getCovarianceMatrixType @see getCovarianceMatrixType */ + CV_WRAP virtual void setCovarianceMatrixType(int val) = 0; + + /** The termination criteria of the %EM algorithm. + The %EM algorithm can be terminated by the number of iterations termCrit.maxCount (number of + M-steps) or when relative change of likelihood logarithm is less than termCrit.epsilon. Default + maximum number of iterations is EM::DEFAULT_MAX_ITERS=100. */ + /** @see setTermCriteria */ + CV_WRAP virtual TermCriteria getTermCriteria() const = 0; + /** @copybrief getTermCriteria @see getTermCriteria */ + CV_WRAP virtual void setTermCriteria(const TermCriteria &val) = 0; + + /** @brief Returns weights of the mixtures + + Returns vector with the number of elements equal to the number of mixtures. + */ + CV_WRAP virtual Mat getWeights() const = 0; + /** @brief Returns the cluster centers (means of the Gaussian mixture) + + Returns matrix with the number of rows equal to the number of mixtures and number of columns + equal to the space dimensionality. + */ + CV_WRAP virtual Mat getMeans() const = 0; + /** @brief Returns covariation matrices + + Returns vector of covariation matrices. Number of matrices is the number of gaussian mixtures, + each matrix is a square floating-point matrix NxN, where N is the space dimensionality. + */ + CV_WRAP virtual void getCovs(CV_OUT std::vector& covs) const = 0; + + /** @brief Returns posterior probabilities for the provided samples + + @param samples The input samples, floating-point matrix + @param results The optional output \f$ nSamples \times nClusters\f$ matrix of results. It contains + posterior probabilities for each sample from the input + @param flags This parameter will be ignored + */ + CV_WRAP virtual float predict( InputArray samples, OutputArray results=noArray(), int flags=0 ) const CV_OVERRIDE = 0; + + /** @brief Returns a likelihood logarithm value and an index of the most probable mixture component + for the given sample. + + @param sample A sample for classification. It should be a one-channel matrix of + \f$1 \times dims\f$ or \f$dims \times 1\f$ size. + @param probs Optional output matrix that contains posterior probabilities of each component + given the sample. It has \f$1 \times nclusters\f$ size and CV_64FC1 type. + + The method returns a two-element double vector. Zero element is a likelihood logarithm value for + the sample. First element is an index of the most probable mixture component for the given + sample. + */ + CV_WRAP virtual Vec2d predict2(InputArray sample, OutputArray probs) const = 0; + + /** @brief Estimate the Gaussian mixture parameters from a samples set. + + This variation starts with Expectation step. Initial values of the model parameters will be + estimated by the k-means algorithm. + + Unlike many of the ML models, %EM is an unsupervised learning algorithm and it does not take + responses (class labels or function values) as input. Instead, it computes the *Maximum + Likelihood Estimate* of the Gaussian mixture parameters from an input sample set, stores all the + parameters inside the structure: \f$p_{i,k}\f$ in probs, \f$a_k\f$ in means , \f$S_k\f$ in + covs[k], \f$\pi_k\f$ in weights , and optionally computes the output "class label" for each + sample: \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most + probable mixture component for each sample). + + The trained model can be used further for prediction, just like any other classifier. The + trained model is similar to the NormalBayesClassifier. + + @param samples Samples from which the Gaussian mixture model will be estimated. It should be a + one-channel matrix, each row of which is a sample. If the matrix does not have CV_64F type + it will be converted to the inner matrix of such type for the further computing. + @param logLikelihoods The optional output matrix that contains a likelihood logarithm value for + each sample. It has \f$nsamples \times 1\f$ size and CV_64FC1 type. + @param labels The optional output "class label" for each sample: + \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most probable + mixture component for each sample). It has \f$nsamples \times 1\f$ size and CV_32SC1 type. + @param probs The optional output matrix that contains posterior probabilities of each Gaussian + mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and + CV_64FC1 type. + */ + CV_WRAP virtual bool trainEM(InputArray samples, + OutputArray logLikelihoods=noArray(), + OutputArray labels=noArray(), + OutputArray probs=noArray()) = 0; + + /** @brief Estimate the Gaussian mixture parameters from a samples set. + + This variation starts with Expectation step. You need to provide initial means \f$a_k\f$ of + mixture components. Optionally you can pass initial weights \f$\pi_k\f$ and covariance matrices + \f$S_k\f$ of mixture components. + + @param samples Samples from which the Gaussian mixture model will be estimated. It should be a + one-channel matrix, each row of which is a sample. If the matrix does not have CV_64F type + it will be converted to the inner matrix of such type for the further computing. + @param means0 Initial means \f$a_k\f$ of mixture components. It is a one-channel matrix of + \f$nclusters \times dims\f$ size. If the matrix does not have CV_64F type it will be + converted to the inner matrix of such type for the further computing. + @param covs0 The vector of initial covariance matrices \f$S_k\f$ of mixture components. Each of + covariance matrices is a one-channel matrix of \f$dims \times dims\f$ size. If the matrices + do not have CV_64F type they will be converted to the inner matrices of such type for the + further computing. + @param weights0 Initial weights \f$\pi_k\f$ of mixture components. It should be a one-channel + floating-point matrix with \f$1 \times nclusters\f$ or \f$nclusters \times 1\f$ size. + @param logLikelihoods The optional output matrix that contains a likelihood logarithm value for + each sample. It has \f$nsamples \times 1\f$ size and CV_64FC1 type. + @param labels The optional output "class label" for each sample: + \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most probable + mixture component for each sample). It has \f$nsamples \times 1\f$ size and CV_32SC1 type. + @param probs The optional output matrix that contains posterior probabilities of each Gaussian + mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and + CV_64FC1 type. + */ + CV_WRAP virtual bool trainE(InputArray samples, InputArray means0, + InputArray covs0=noArray(), + InputArray weights0=noArray(), + OutputArray logLikelihoods=noArray(), + OutputArray labels=noArray(), + OutputArray probs=noArray()) = 0; + + /** @brief Estimate the Gaussian mixture parameters from a samples set. + + This variation starts with Maximization step. You need to provide initial probabilities + \f$p_{i,k}\f$ to use this option. + + @param samples Samples from which the Gaussian mixture model will be estimated. It should be a + one-channel matrix, each row of which is a sample. If the matrix does not have CV_64F type + it will be converted to the inner matrix of such type for the further computing. + @param probs0 the probabilities + @param logLikelihoods The optional output matrix that contains a likelihood logarithm value for + each sample. It has \f$nsamples \times 1\f$ size and CV_64FC1 type. + @param labels The optional output "class label" for each sample: + \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most probable + mixture component for each sample). It has \f$nsamples \times 1\f$ size and CV_32SC1 type. + @param probs The optional output matrix that contains posterior probabilities of each Gaussian + mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and + CV_64FC1 type. + */ + CV_WRAP virtual bool trainM(InputArray samples, InputArray probs0, + OutputArray logLikelihoods=noArray(), + OutputArray labels=noArray(), + OutputArray probs=noArray()) = 0; + + /** Creates empty %EM model. + The model should be trained then using StatModel::train(traindata, flags) method. Alternatively, you + can use one of the EM::train\* methods or load it from file using Algorithm::load\(filename). + */ + CV_WRAP static Ptr create(); + + /** @brief Loads and creates a serialized EM from a file + * + * Use EM::save to serialize and store an EM to disk. + * Load the EM from this file again, by calling this function with the path to the file. + * Optionally specify the node for the file containing the classifier + * + * @param filepath path to serialized EM + * @param nodeName name of node containing the classifier + */ + CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); +}; + +/****************************************************************************************\ +* Decision Tree * +\****************************************************************************************/ + +/** @brief The class represents a single decision tree or a collection of decision trees. + +The current public interface of the class allows user to train only a single decision tree, however +the class is capable of storing multiple decision trees and using them for prediction (by summing +responses or using a voting schemes), and the derived from DTrees classes (such as RTrees and Boost) +use this capability to implement decision tree ensembles. + +@sa @ref ml_intro_trees +*/ +class CV_EXPORTS_W DTrees : public StatModel +{ +public: + /** Predict options */ + enum Flags { PREDICT_AUTO=0, PREDICT_SUM=(1<<8), PREDICT_MAX_VOTE=(2<<8), PREDICT_MASK=(3<<8) }; + + /** Cluster possible values of a categorical variable into K\<=maxCategories clusters to + find a suboptimal split. + If a discrete variable, on which the training procedure tries to make a split, takes more than + maxCategories values, the precise best subset estimation may take a very long time because the + algorithm is exponential. Instead, many decision trees engines (including our implementation) + try to find sub-optimal split in this case by clustering all the samples into maxCategories + clusters that is some categories are merged together. The clustering is applied only in n \> + 2-class classification problems for categorical variables with N \> max_categories possible + values. In case of regression and 2-class classification the optimal split can be found + efficiently without employing clustering, thus the parameter is not used in these cases. + Default value is 10.*/ + /** @see setMaxCategories */ + CV_WRAP virtual int getMaxCategories() const = 0; + /** @copybrief getMaxCategories @see getMaxCategories */ + CV_WRAP virtual void setMaxCategories(int val) = 0; + + /** The maximum possible depth of the tree. + That is the training algorithms attempts to split a node while its depth is less than maxDepth. + The root node has zero depth. The actual depth may be smaller if the other termination criteria + are met (see the outline of the training procedure @ref ml_intro_trees "here"), and/or if the + tree is pruned. Default value is INT_MAX.*/ + /** @see setMaxDepth */ + CV_WRAP virtual int getMaxDepth() const = 0; + /** @copybrief getMaxDepth @see getMaxDepth */ + CV_WRAP virtual void setMaxDepth(int val) = 0; + + /** If the number of samples in a node is less than this parameter then the node will not be split. + + Default value is 10.*/ + /** @see setMinSampleCount */ + CV_WRAP virtual int getMinSampleCount() const = 0; + /** @copybrief getMinSampleCount @see getMinSampleCount */ + CV_WRAP virtual void setMinSampleCount(int val) = 0; + + /** If CVFolds \> 1 then algorithms prunes the built decision tree using K-fold + cross-validation procedure where K is equal to CVFolds. + Default value is 10.*/ + /** @see setCVFolds */ + CV_WRAP virtual int getCVFolds() const = 0; + /** @copybrief getCVFolds @see getCVFolds */ + CV_WRAP virtual void setCVFolds(int val) = 0; + + /** If true then surrogate splits will be built. + These splits allow to work with missing data and compute variable importance correctly. + Default value is false. + @note currently it's not implemented.*/ + /** @see setUseSurrogates */ + CV_WRAP virtual bool getUseSurrogates() const = 0; + /** @copybrief getUseSurrogates @see getUseSurrogates */ + CV_WRAP virtual void setUseSurrogates(bool val) = 0; + + /** If true then a pruning will be harsher. + This will make a tree more compact and more resistant to the training data noise but a bit less + accurate. Default value is true.*/ + /** @see setUse1SERule */ + CV_WRAP virtual bool getUse1SERule() const = 0; + /** @copybrief getUse1SERule @see getUse1SERule */ + CV_WRAP virtual void setUse1SERule(bool val) = 0; + + /** If true then pruned branches are physically removed from the tree. + Otherwise they are retained and it is possible to get results from the original unpruned (or + pruned less aggressively) tree. Default value is true.*/ + /** @see setTruncatePrunedTree */ + CV_WRAP virtual bool getTruncatePrunedTree() const = 0; + /** @copybrief getTruncatePrunedTree @see getTruncatePrunedTree */ + CV_WRAP virtual void setTruncatePrunedTree(bool val) = 0; + + /** Termination criteria for regression trees. + If all absolute differences between an estimated value in a node and values of train samples + in this node are less than this parameter then the node will not be split further. Default + value is 0.01f*/ + /** @see setRegressionAccuracy */ + CV_WRAP virtual float getRegressionAccuracy() const = 0; + /** @copybrief getRegressionAccuracy @see getRegressionAccuracy */ + CV_WRAP virtual void setRegressionAccuracy(float val) = 0; + + /** @brief The array of a priori class probabilities, sorted by the class label value. + + The parameter can be used to tune the decision tree preferences toward a certain class. For + example, if you want to detect some rare anomaly occurrence, the training base will likely + contain much more normal cases than anomalies, so a very good classification performance + will be achieved just by considering every case as normal. To avoid this, the priors can be + specified, where the anomaly probability is artificially increased (up to 0.5 or even + greater), so the weight of the misclassified anomalies becomes much bigger, and the tree is + adjusted properly. + + You can also think about this parameter as weights of prediction categories which determine + relative weights that you give to misclassification. That is, if the weight of the first + category is 1 and the weight of the second category is 10, then each mistake in predicting + the second category is equivalent to making 10 mistakes in predicting the first category. + Default value is empty Mat.*/ + /** @see setPriors */ + CV_WRAP virtual cv::Mat getPriors() const = 0; + /** @copybrief getPriors @see getPriors */ + CV_WRAP virtual void setPriors(const cv::Mat &val) = 0; + + /** @brief The class represents a decision tree node. + */ + class CV_EXPORTS Node + { + public: + Node(); + double value; //!< Value at the node: a class label in case of classification or estimated + //!< function value in case of regression. + int classIdx; //!< Class index normalized to 0..class_count-1 range and assigned to the + //!< node. It is used internally in classification trees and tree ensembles. + int parent; //!< Index of the parent node + int left; //!< Index of the left child node + int right; //!< Index of right child node + int defaultDir; //!< Default direction where to go (-1: left or +1: right). It helps in the + //!< case of missing values. + int split; //!< Index of the first split + }; + + /** @brief The class represents split in a decision tree. + */ + class CV_EXPORTS Split + { + public: + Split(); + int varIdx; //!< Index of variable on which the split is created. + bool inversed; //!< If true, then the inverse split rule is used (i.e. left and right + //!< branches are exchanged in the rule expressions below). + float quality; //!< The split quality, a positive number. It is used to choose the best split. + int next; //!< Index of the next split in the list of splits for the node + float c; /**< The threshold value in case of split on an ordered variable. + The rule is: + @code{.none} + if var_value < c + then next_node <- left + else next_node <- right + @endcode */ + int subsetOfs; /**< Offset of the bitset used by the split on a categorical variable. + The rule is: + @code{.none} + if bitset[var_value] == 1 + then next_node <- left + else next_node <- right + @endcode */ + }; + + /** @brief Returns indices of root nodes + */ + virtual const std::vector& getRoots() const = 0; + /** @brief Returns all the nodes + + all the node indices are indices in the returned vector + */ + virtual const std::vector& getNodes() const = 0; + /** @brief Returns all the splits + + all the split indices are indices in the returned vector + */ + virtual const std::vector& getSplits() const = 0; + /** @brief Returns all the bitsets for categorical splits + + Split::subsetOfs is an offset in the returned vector + */ + virtual const std::vector& getSubsets() const = 0; + + /** @brief Creates the empty model + + The static method creates empty decision tree with the specified parameters. It should be then + trained using train method (see StatModel::train). Alternatively, you can load the model from + file using Algorithm::load\(filename). + */ + CV_WRAP static Ptr create(); + + /** @brief Loads and creates a serialized DTrees from a file + * + * Use DTree::save to serialize and store an DTree to disk. + * Load the DTree from this file again, by calling this function with the path to the file. + * Optionally specify the node for the file containing the classifier + * + * @param filepath path to serialized DTree + * @param nodeName name of node containing the classifier + */ + CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); +}; + +/****************************************************************************************\ +* Random Trees Classifier * +\****************************************************************************************/ + +/** @brief The class implements the random forest predictor. + +@sa @ref ml_intro_rtrees + */ +class CV_EXPORTS_W RTrees : public DTrees +{ +public: + + /** If true then variable importance will be calculated and then it can be retrieved by RTrees::getVarImportance. + Default value is false.*/ + /** @see setCalculateVarImportance */ + CV_WRAP virtual bool getCalculateVarImportance() const = 0; + /** @copybrief getCalculateVarImportance @see getCalculateVarImportance */ + CV_WRAP virtual void setCalculateVarImportance(bool val) = 0; + + /** The size of the randomly selected subset of features at each tree node and that are used + to find the best split(s). + If you set it to 0 then the size will be set to the square root of the total number of + features. Default value is 0.*/ + /** @see setActiveVarCount */ + CV_WRAP virtual int getActiveVarCount() const = 0; + /** @copybrief getActiveVarCount @see getActiveVarCount */ + CV_WRAP virtual void setActiveVarCount(int val) = 0; + + /** The termination criteria that specifies when the training algorithm stops. + Either when the specified number of trees is trained and added to the ensemble or when + sufficient accuracy (measured as OOB error) is achieved. Typically the more trees you have the + better the accuracy. However, the improvement in accuracy generally diminishes and asymptotes + pass a certain number of trees. Also to keep in mind, the number of tree increases the + prediction time linearly. Default value is TermCriteria(TermCriteria::MAX_ITERS + + TermCriteria::EPS, 50, 0.1)*/ + /** @see setTermCriteria */ + CV_WRAP virtual TermCriteria getTermCriteria() const = 0; + /** @copybrief getTermCriteria @see getTermCriteria */ + CV_WRAP virtual void setTermCriteria(const TermCriteria &val) = 0; + + /** Returns the variable importance array. + The method returns the variable importance vector, computed at the training stage when + CalculateVarImportance is set to true. If this flag was set to false, the empty matrix is + returned. + */ + CV_WRAP virtual Mat getVarImportance() const = 0; + + /** Returns the result of each individual tree in the forest. + In case the model is a regression problem, the method will return each of the trees' + results for each of the sample cases. If the model is a classifier, it will return + a Mat with samples + 1 rows, where the first row gives the class number and the + following rows return the votes each class had for each sample. + @param samples Array containing the samples for which votes will be calculated. + @param results Array where the result of the calculation will be written. + @param flags Flags for defining the type of RTrees. + */ + CV_WRAP virtual void getVotes(InputArray samples, OutputArray results, int flags) const = 0; + + /** Returns the OOB error value, computed at the training stage when calcOOBError is set to true. + * If this flag was set to false, 0 is returned. The OOB error is also scaled by sample weighting. + */ +#if CV_VERSION_MAJOR == 4 + CV_WRAP virtual double getOOBError() const { return 0; } +#else + /*CV_WRAP*/ virtual double getOOBError() const = 0; +#endif + + /** Creates the empty model. + Use StatModel::train to train the model, StatModel::train to create and train the model, + Algorithm::load to load the pre-trained model. + */ + CV_WRAP static Ptr create(); + + /** @brief Loads and creates a serialized RTree from a file + * + * Use RTree::save to serialize and store an RTree to disk. + * Load the RTree from this file again, by calling this function with the path to the file. + * Optionally specify the node for the file containing the classifier + * + * @param filepath path to serialized RTree + * @param nodeName name of node containing the classifier + */ + CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); +}; + +/****************************************************************************************\ +* Boosted tree classifier * +\****************************************************************************************/ + +/** @brief Boosted tree classifier derived from DTrees + +@sa @ref ml_intro_boost + */ +class CV_EXPORTS_W Boost : public DTrees +{ +public: + /** Type of the boosting algorithm. + See Boost::Types. Default value is Boost::REAL. */ + /** @see setBoostType */ + CV_WRAP virtual int getBoostType() const = 0; + /** @copybrief getBoostType @see getBoostType */ + CV_WRAP virtual void setBoostType(int val) = 0; + + /** The number of weak classifiers. + Default value is 100. */ + /** @see setWeakCount */ + CV_WRAP virtual int getWeakCount() const = 0; + /** @copybrief getWeakCount @see getWeakCount */ + CV_WRAP virtual void setWeakCount(int val) = 0; + + /** A threshold between 0 and 1 used to save computational time. + Samples with summary weight \f$\leq 1 - weight_trim_rate\f$ do not participate in the *next* + iteration of training. Set this parameter to 0 to turn off this functionality. Default value is 0.95.*/ + /** @see setWeightTrimRate */ + CV_WRAP virtual double getWeightTrimRate() const = 0; + /** @copybrief getWeightTrimRate @see getWeightTrimRate */ + CV_WRAP virtual void setWeightTrimRate(double val) = 0; + + /** Boosting type. + Gentle AdaBoost and Real AdaBoost are often the preferable choices. */ + enum Types { + DISCRETE=0, //!< Discrete AdaBoost. + REAL=1, //!< Real AdaBoost. It is a technique that utilizes confidence-rated predictions + //!< and works well with categorical data. + LOGIT=2, //!< LogitBoost. It can produce good regression fits. + GENTLE=3 //!< Gentle AdaBoost. It puts less weight on outlier data points and for that + //!(filename) to load the pre-trained model. */ + CV_WRAP static Ptr create(); + + /** @brief Loads and creates a serialized Boost from a file + * + * Use Boost::save to serialize and store an RTree to disk. + * Load the Boost from this file again, by calling this function with the path to the file. + * Optionally specify the node for the file containing the classifier + * + * @param filepath path to serialized Boost + * @param nodeName name of node containing the classifier + */ + CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); +}; + +/****************************************************************************************\ +* Gradient Boosted Trees * +\****************************************************************************************/ + +/*class CV_EXPORTS_W GBTrees : public DTrees +{ +public: + struct CV_EXPORTS_W_MAP Params : public DTrees::Params + { + CV_PROP_RW int weakCount; + CV_PROP_RW int lossFunctionType; + CV_PROP_RW float subsamplePortion; + CV_PROP_RW float shrinkage; + + Params(); + Params( int lossFunctionType, int weakCount, float shrinkage, + float subsamplePortion, int maxDepth, bool useSurrogates ); + }; + + enum {SQUARED_LOSS=0, ABSOLUTE_LOSS, HUBER_LOSS=3, DEVIANCE_LOSS}; + + virtual void setK(int k) = 0; + + virtual float predictSerial( InputArray samples, + OutputArray weakResponses, int flags) const = 0; + + static Ptr create(const Params& p); +};*/ + +/****************************************************************************************\ +* Artificial Neural Networks (ANN) * +\****************************************************************************************/ + +/////////////////////////////////// Multi-Layer Perceptrons ////////////////////////////// + +/** @brief Artificial Neural Networks - Multi-Layer Perceptrons. + +Unlike many other models in ML that are constructed and trained at once, in the MLP model these +steps are separated. First, a network with the specified topology is created using the non-default +constructor or the method ANN_MLP::create. All the weights are set to zeros. Then, the network is +trained using a set of input and output vectors. The training procedure can be repeated more than +once, that is, the weights can be adjusted based on the new training data. + +Additional flags for StatModel::train are available: ANN_MLP::TrainFlags. + +@sa @ref ml_intro_ann + */ +class CV_EXPORTS_W ANN_MLP : public StatModel +{ +public: + /** Available training methods */ + enum TrainingMethods { + BACKPROP=0, //!< The back-propagation algorithm. + RPROP = 1, //!< The RPROP algorithm. See @cite RPROP93 for details. + ANNEAL = 2 //!< The simulated annealing algorithm. See @cite Kirkpatrick83 for details. + }; + + /** Sets training method and common parameters. + @param method Default value is ANN_MLP::RPROP. See ANN_MLP::TrainingMethods. + @param param1 passed to setRpropDW0 for ANN_MLP::RPROP and to setBackpropWeightScale for ANN_MLP::BACKPROP and to initialT for ANN_MLP::ANNEAL. + @param param2 passed to setRpropDWMin for ANN_MLP::RPROP and to setBackpropMomentumScale for ANN_MLP::BACKPROP and to finalT for ANN_MLP::ANNEAL. + */ + CV_WRAP virtual void setTrainMethod(int method, double param1 = 0, double param2 = 0) = 0; + + /** Returns current training method */ + CV_WRAP virtual int getTrainMethod() const = 0; + + /** Initialize the activation function for each neuron. + Currently the default and the only fully supported activation function is ANN_MLP::SIGMOID_SYM. + @param type The type of activation function. See ANN_MLP::ActivationFunctions. + @param param1 The first parameter of the activation function, \f$\alpha\f$. Default value is 0. + @param param2 The second parameter of the activation function, \f$\beta\f$. Default value is 0. + */ + CV_WRAP virtual void setActivationFunction(int type, double param1 = 0, double param2 = 0) = 0; + + /** Integer vector specifying the number of neurons in each layer including the input and output layers. + The very first element specifies the number of elements in the input layer. + The last element - number of elements in the output layer. Default value is empty Mat. + @sa getLayerSizes */ + CV_WRAP virtual void setLayerSizes(InputArray _layer_sizes) = 0; + + /** Integer vector specifying the number of neurons in each layer including the input and output layers. + The very first element specifies the number of elements in the input layer. + The last element - number of elements in the output layer. + @sa setLayerSizes */ + CV_WRAP virtual cv::Mat getLayerSizes() const = 0; + + /** Termination criteria of the training algorithm. + You can specify the maximum number of iterations (maxCount) and/or how much the error could + change between the iterations to make the algorithm continue (epsilon). Default value is + TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 1000, 0.01).*/ + /** @see setTermCriteria */ + CV_WRAP virtual TermCriteria getTermCriteria() const = 0; + /** @copybrief getTermCriteria @see getTermCriteria */ + CV_WRAP virtual void setTermCriteria(TermCriteria val) = 0; + + /** BPROP: Strength of the weight gradient term. + The recommended value is about 0.1. Default value is 0.1.*/ + /** @see setBackpropWeightScale */ + CV_WRAP virtual double getBackpropWeightScale() const = 0; + /** @copybrief getBackpropWeightScale @see getBackpropWeightScale */ + CV_WRAP virtual void setBackpropWeightScale(double val) = 0; + + /** BPROP: Strength of the momentum term (the difference between weights on the 2 previous iterations). + This parameter provides some inertia to smooth the random fluctuations of the weights. It can + vary from 0 (the feature is disabled) to 1 and beyond. The value 0.1 or so is good enough. + Default value is 0.1.*/ + /** @see setBackpropMomentumScale */ + CV_WRAP virtual double getBackpropMomentumScale() const = 0; + /** @copybrief getBackpropMomentumScale @see getBackpropMomentumScale */ + CV_WRAP virtual void setBackpropMomentumScale(double val) = 0; + + /** RPROP: Initial value \f$\Delta_0\f$ of update-values \f$\Delta_{ij}\f$. + Default value is 0.1.*/ + /** @see setRpropDW0 */ + CV_WRAP virtual double getRpropDW0() const = 0; + /** @copybrief getRpropDW0 @see getRpropDW0 */ + CV_WRAP virtual void setRpropDW0(double val) = 0; + + /** RPROP: Increase factor \f$\eta^+\f$. + It must be \>1. Default value is 1.2.*/ + /** @see setRpropDWPlus */ + CV_WRAP virtual double getRpropDWPlus() const = 0; + /** @copybrief getRpropDWPlus @see getRpropDWPlus */ + CV_WRAP virtual void setRpropDWPlus(double val) = 0; + + /** RPROP: Decrease factor \f$\eta^-\f$. + It must be \<1. Default value is 0.5.*/ + /** @see setRpropDWMinus */ + CV_WRAP virtual double getRpropDWMinus() const = 0; + /** @copybrief getRpropDWMinus @see getRpropDWMinus */ + CV_WRAP virtual void setRpropDWMinus(double val) = 0; + + /** RPROP: Update-values lower limit \f$\Delta_{min}\f$. + It must be positive. Default value is FLT_EPSILON.*/ + /** @see setRpropDWMin */ + CV_WRAP virtual double getRpropDWMin() const = 0; + /** @copybrief getRpropDWMin @see getRpropDWMin */ + CV_WRAP virtual void setRpropDWMin(double val) = 0; + + /** RPROP: Update-values upper limit \f$\Delta_{max}\f$. + It must be \>1. Default value is 50.*/ + /** @see setRpropDWMax */ + CV_WRAP virtual double getRpropDWMax() const = 0; + /** @copybrief getRpropDWMax @see getRpropDWMax */ + CV_WRAP virtual void setRpropDWMax(double val) = 0; + + /** ANNEAL: Update initial temperature. + It must be \>=0. Default value is 10.*/ + /** @see setAnnealInitialT */ + CV_WRAP virtual double getAnnealInitialT() const = 0; + /** @copybrief getAnnealInitialT @see getAnnealInitialT */ + CV_WRAP virtual void setAnnealInitialT(double val) = 0; + + /** ANNEAL: Update final temperature. + It must be \>=0 and less than initialT. Default value is 0.1.*/ + /** @see setAnnealFinalT */ + CV_WRAP virtual double getAnnealFinalT() const = 0; + /** @copybrief getAnnealFinalT @see getAnnealFinalT */ + CV_WRAP virtual void setAnnealFinalT(double val) = 0; + + /** ANNEAL: Update cooling ratio. + It must be \>0 and less than 1. Default value is 0.95.*/ + /** @see setAnnealCoolingRatio */ + CV_WRAP virtual double getAnnealCoolingRatio() const = 0; + /** @copybrief getAnnealCoolingRatio @see getAnnealCoolingRatio */ + CV_WRAP virtual void setAnnealCoolingRatio(double val) = 0; + + /** ANNEAL: Update iteration per step. + It must be \>0 . Default value is 10.*/ + /** @see setAnnealItePerStep */ + CV_WRAP virtual int getAnnealItePerStep() const = 0; + /** @copybrief getAnnealItePerStep @see getAnnealItePerStep */ + CV_WRAP virtual void setAnnealItePerStep(int val) = 0; + + /** @brief Set/initialize anneal RNG */ + virtual void setAnnealEnergyRNG(const RNG& rng) = 0; + + /** possible activation functions */ + enum ActivationFunctions { + /** Identity function: \f$f(x)=x\f$ */ + IDENTITY = 0, + /** Symmetrical sigmoid: \f$f(x)=\beta*(1-e^{-\alpha x})/(1+e^{-\alpha x})\f$ + @note + If you are using the default sigmoid activation function with the default parameter values + fparam1=0 and fparam2=0 then the function used is y = 1.7159\*tanh(2/3 \* x), so the output + will range from [-1.7159, 1.7159], instead of [0,1].*/ + SIGMOID_SYM = 1, + /** Gaussian function: \f$f(x)=\beta e^{-\alpha x*x}\f$ */ + GAUSSIAN = 2, + /** ReLU function: \f$f(x)=max(0,x)\f$ */ + RELU = 3, + /** Leaky ReLU function: for x>0 \f$f(x)=x \f$ and x<=0 \f$f(x)=\alpha x \f$*/ + LEAKYRELU= 4 + }; + + /** Train options */ + enum TrainFlags { + /** Update the network weights, rather than compute them from scratch. In the latter case + the weights are initialized using the Nguyen-Widrow algorithm. */ + UPDATE_WEIGHTS = 1, + /** Do not normalize the input vectors. If this flag is not set, the training algorithm + normalizes each input feature independently, shifting its mean value to 0 and making the + standard deviation equal to 1. If the network is assumed to be updated frequently, the new + training data could be much different from original one. In this case, you should take care + of proper normalization. */ + NO_INPUT_SCALE = 2, + /** Do not normalize the output vectors. If the flag is not set, the training algorithm + normalizes each output feature independently, by transforming it to the certain range + depending on the used activation function. */ + NO_OUTPUT_SCALE = 4 + }; + + CV_WRAP virtual Mat getWeights(int layerIdx) const = 0; + + /** @brief Creates empty model + + Use StatModel::train to train the model, Algorithm::load\(filename) to load the pre-trained model. + Note that the train method has optional flags: ANN_MLP::TrainFlags. + */ + CV_WRAP static Ptr create(); + + /** @brief Loads and creates a serialized ANN from a file + * + * Use ANN::save to serialize and store an ANN to disk. + * Load the ANN from this file again, by calling this function with the path to the file. + * + * @param filepath path to serialized ANN + */ + CV_WRAP static Ptr load(const String& filepath); + +}; + +#ifndef DISABLE_OPENCV_3_COMPATIBILITY +typedef ANN_MLP ANN_MLP_ANNEAL; +#endif + +/****************************************************************************************\ +* Logistic Regression * +\****************************************************************************************/ + +/** @brief Implements Logistic Regression classifier. + +@sa @ref ml_intro_lr + */ +class CV_EXPORTS_W LogisticRegression : public StatModel +{ +public: + + /** Learning rate. */ + /** @see setLearningRate */ + CV_WRAP virtual double getLearningRate() const = 0; + /** @copybrief getLearningRate @see getLearningRate */ + CV_WRAP virtual void setLearningRate(double val) = 0; + + /** Number of iterations. */ + /** @see setIterations */ + CV_WRAP virtual int getIterations() const = 0; + /** @copybrief getIterations @see getIterations */ + CV_WRAP virtual void setIterations(int val) = 0; + + /** Kind of regularization to be applied. See LogisticRegression::RegKinds. */ + /** @see setRegularization */ + CV_WRAP virtual int getRegularization() const = 0; + /** @copybrief getRegularization @see getRegularization */ + CV_WRAP virtual void setRegularization(int val) = 0; + + /** Kind of training method used. See LogisticRegression::Methods. */ + /** @see setTrainMethod */ + CV_WRAP virtual int getTrainMethod() const = 0; + /** @copybrief getTrainMethod @see getTrainMethod */ + CV_WRAP virtual void setTrainMethod(int val) = 0; + + /** Specifies the number of training samples taken in each step of Mini-Batch Gradient + Descent. Will only be used if using LogisticRegression::MINI_BATCH training algorithm. It + has to take values less than the total number of training samples. */ + /** @see setMiniBatchSize */ + CV_WRAP virtual int getMiniBatchSize() const = 0; + /** @copybrief getMiniBatchSize @see getMiniBatchSize */ + CV_WRAP virtual void setMiniBatchSize(int val) = 0; + + /** Termination criteria of the algorithm. */ + /** @see setTermCriteria */ + CV_WRAP virtual TermCriteria getTermCriteria() const = 0; + /** @copybrief getTermCriteria @see getTermCriteria */ + CV_WRAP virtual void setTermCriteria(TermCriteria val) = 0; + + //! Regularization kinds + enum RegKinds { + REG_DISABLE = -1, //!< Regularization disabled + REG_L1 = 0, //!< %L1 norm + REG_L2 = 1 //!< %L2 norm + }; + + //! Training methods + enum Methods { + BATCH = 0, + MINI_BATCH = 1 //!< Set MiniBatchSize to a positive integer when using this method. + }; + + /** @brief Predicts responses for input samples and returns a float type. + + @param samples The input data for the prediction algorithm. Matrix [m x n], where each row + contains variables (features) of one object being classified. Should have data type CV_32F. + @param results Predicted labels as a column matrix of type CV_32S. + @param flags Not used. + */ + CV_WRAP virtual float predict( InputArray samples, OutputArray results=noArray(), int flags=0 ) const CV_OVERRIDE = 0; + + /** @brief This function returns the trained parameters arranged across rows. + + For a two class classification problem, it returns a row matrix. It returns learnt parameters of + the Logistic Regression as a matrix of type CV_32F. + */ + CV_WRAP virtual Mat get_learnt_thetas() const = 0; + + /** @brief Creates empty model. + + Creates Logistic Regression model with parameters given. + */ + CV_WRAP static Ptr create(); + + /** @brief Loads and creates a serialized LogisticRegression from a file + * + * Use LogisticRegression::save to serialize and store an LogisticRegression to disk. + * Load the LogisticRegression from this file again, by calling this function with the path to the file. + * Optionally specify the node for the file containing the classifier + * + * @param filepath path to serialized LogisticRegression + * @param nodeName name of node containing the classifier + */ + CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); +}; + + +/****************************************************************************************\ +* Stochastic Gradient Descent SVM Classifier * +\****************************************************************************************/ + +/*! +@brief Stochastic Gradient Descent SVM classifier + +SVMSGD provides a fast and easy-to-use implementation of the SVM classifier using the Stochastic Gradient Descent approach, +as presented in @cite bottou2010large. + +The classifier has following parameters: +- model type, +- margin type, +- margin regularization (\f$\lambda\f$), +- initial step size (\f$\gamma_0\f$), +- step decreasing power (\f$c\f$), +- and termination criteria. + +The model type may have one of the following values: \ref SGD and \ref ASGD. + +- \ref SGD is the classic version of SVMSGD classifier: every next step is calculated by the formula + \f[w_{t+1} = w_t - \gamma(t) \frac{dQ_i}{dw} |_{w = w_t}\f] + where + - \f$w_t\f$ is the weights vector for decision function at step \f$t\f$, + - \f$\gamma(t)\f$ is the step size of model parameters at the iteration \f$t\f$, it is decreased on each step by the formula + \f$\gamma(t) = \gamma_0 (1 + \lambda \gamma_0 t) ^ {-c}\f$ + - \f$Q_i\f$ is the target functional from SVM task for sample with number \f$i\f$, this sample is chosen stochastically on each step of the algorithm. + +- \ref ASGD is Average Stochastic Gradient Descent SVM Classifier. ASGD classifier averages weights vector on each step of algorithm by the formula +\f$\widehat{w}_{t+1} = \frac{t}{1+t}\widehat{w}_{t} + \frac{1}{1+t}w_{t+1}\f$ + +The recommended model type is ASGD (following @cite bottou2010large). + +The margin type may have one of the following values: \ref SOFT_MARGIN or \ref HARD_MARGIN. + +- You should use \ref HARD_MARGIN type, if you have linearly separable sets. +- You should use \ref SOFT_MARGIN type, if you have non-linearly separable sets or sets with outliers. +- In the general case (if you know nothing about linear separability of your sets), use SOFT_MARGIN. + +The other parameters may be described as follows: +- Margin regularization parameter is responsible for weights decreasing at each step and for the strength of restrictions on outliers + (the less the parameter, the less probability that an outlier will be ignored). + Recommended value for SGD model is 0.0001, for ASGD model is 0.00001. + +- Initial step size parameter is the initial value for the step size \f$\gamma(t)\f$. + You will have to find the best initial step for your problem. + +- Step decreasing power is the power parameter for \f$\gamma(t)\f$ decreasing by the formula, mentioned above. + Recommended value for SGD model is 1, for ASGD model is 0.75. + +- Termination criteria can be TermCriteria::COUNT, TermCriteria::EPS or TermCriteria::COUNT + TermCriteria::EPS. + You will have to find the best termination criteria for your problem. + +Note that the parameters margin regularization, initial step size, and step decreasing power should be positive. + +To use SVMSGD algorithm do as follows: + +- first, create the SVMSGD object. The algorithm will set optimal parameters by default, but you can set your own parameters via functions setSvmsgdType(), + setMarginType(), setMarginRegularization(), setInitialStepSize(), and setStepDecreasingPower(). + +- then the SVM model can be trained using the train features and the correspondent labels by the method train(). + +- after that, the label of a new feature vector can be predicted using the method predict(). + +@code +// Create empty object +cv::Ptr svmsgd = SVMSGD::create(); + +// Train the Stochastic Gradient Descent SVM +svmsgd->train(trainData); + +// Predict labels for the new samples +svmsgd->predict(samples, responses); +@endcode + +*/ + +class CV_EXPORTS_W SVMSGD : public cv::ml::StatModel +{ +public: + + /** SVMSGD type. + ASGD is often the preferable choice. */ + enum SvmsgdType + { + SGD, //!< Stochastic Gradient Descent + ASGD //!< Average Stochastic Gradient Descent + }; + + /** Margin type.*/ + enum MarginType + { + SOFT_MARGIN, //!< General case, suits to the case of non-linearly separable sets, allows outliers. + HARD_MARGIN //!< More accurate for the case of linearly separable sets. + }; + + /** + * @return the weights of the trained model (decision function f(x) = weights * x + shift). + */ + CV_WRAP virtual Mat getWeights() = 0; + + /** + * @return the shift of the trained model (decision function f(x) = weights * x + shift). + */ + CV_WRAP virtual float getShift() = 0; + + /** @brief Creates empty model. + * Use StatModel::train to train the model. Since %SVMSGD has several parameters, you may want to + * find the best parameters for your problem or use setOptimalParameters() to set some default parameters. + */ + CV_WRAP static Ptr create(); + + /** @brief Loads and creates a serialized SVMSGD from a file + * + * Use SVMSGD::save to serialize and store an SVMSGD to disk. + * Load the SVMSGD from this file again, by calling this function with the path to the file. + * Optionally specify the node for the file containing the classifier + * + * @param filepath path to serialized SVMSGD + * @param nodeName name of node containing the classifier + */ + CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); + + /** @brief Function sets optimal parameters values for chosen SVM SGD model. + * @param svmsgdType is the type of SVMSGD classifier. + * @param marginType is the type of margin constraint. + */ + CV_WRAP virtual void setOptimalParameters(int svmsgdType = SVMSGD::ASGD, int marginType = SVMSGD::SOFT_MARGIN) = 0; + + /** @brief %Algorithm type, one of SVMSGD::SvmsgdType. */ + /** @see setSvmsgdType */ + CV_WRAP virtual int getSvmsgdType() const = 0; + /** @copybrief getSvmsgdType @see getSvmsgdType */ + CV_WRAP virtual void setSvmsgdType(int svmsgdType) = 0; + + /** @brief %Margin type, one of SVMSGD::MarginType. */ + /** @see setMarginType */ + CV_WRAP virtual int getMarginType() const = 0; + /** @copybrief getMarginType @see getMarginType */ + CV_WRAP virtual void setMarginType(int marginType) = 0; + + /** @brief Parameter marginRegularization of a %SVMSGD optimization problem. */ + /** @see setMarginRegularization */ + CV_WRAP virtual float getMarginRegularization() const = 0; + /** @copybrief getMarginRegularization @see getMarginRegularization */ + CV_WRAP virtual void setMarginRegularization(float marginRegularization) = 0; + + /** @brief Parameter initialStepSize of a %SVMSGD optimization problem. */ + /** @see setInitialStepSize */ + CV_WRAP virtual float getInitialStepSize() const = 0; + /** @copybrief getInitialStepSize @see getInitialStepSize */ + CV_WRAP virtual void setInitialStepSize(float InitialStepSize) = 0; + + /** @brief Parameter stepDecreasingPower of a %SVMSGD optimization problem. */ + /** @see setStepDecreasingPower */ + CV_WRAP virtual float getStepDecreasingPower() const = 0; + /** @copybrief getStepDecreasingPower @see getStepDecreasingPower */ + CV_WRAP virtual void setStepDecreasingPower(float stepDecreasingPower) = 0; + + /** @brief Termination criteria of the training algorithm. + You can specify the maximum number of iterations (maxCount) and/or how much the error could + change between the iterations to make the algorithm continue (epsilon).*/ + /** @see setTermCriteria */ + CV_WRAP virtual TermCriteria getTermCriteria() const = 0; + /** @copybrief getTermCriteria @see getTermCriteria */ + CV_WRAP virtual void setTermCriteria(const cv::TermCriteria &val) = 0; +}; + + +/****************************************************************************************\ +* Auxiliary functions declarations * +\****************************************************************************************/ + +/** @brief Generates _sample_ from multivariate normal distribution + +@param mean an average row vector +@param cov symmetric covariation matrix +@param nsamples returned samples count +@param samples returned samples array +*/ +CV_EXPORTS void randMVNormal( InputArray mean, InputArray cov, int nsamples, OutputArray samples); + +/** @brief Creates test set */ +CV_EXPORTS void createConcentricSpheresTestSet( int nsamples, int nfeatures, int nclasses, + OutputArray samples, OutputArray responses); + + +/****************************************************************************************\ +* Simulated annealing solver * +\****************************************************************************************/ + +#ifdef CV_DOXYGEN +/** @brief This class declares example interface for system state used in simulated annealing optimization algorithm. + +@note This class is not defined in C++ code and can't be use directly - you need your own implementation with the same methods. +*/ +struct SimulatedAnnealingSolverSystem +{ + /** Give energy value for a state of system.*/ + double energy() const; + /** Function which change the state of system (random perturbation).*/ + void changeState(); + /** Function to reverse to the previous state. Can be called once only after changeState(). */ + void reverseState(); +}; +#endif // CV_DOXYGEN + +/** @brief The class implements simulated annealing for optimization. + +@cite Kirkpatrick83 for details + +@param solverSystem optimization system (see SimulatedAnnealingSolverSystem) +@param initialTemperature initial temperature +@param finalTemperature final temperature +@param coolingRatio temperature step multiplies +@param iterationsPerStep number of iterations per temperature changing step +@param lastTemperature optional output for last used temperature +@param rngEnergy specify custom random numbers generator (cv::theRNG() by default) +*/ +template +int simulatedAnnealingSolver(SimulatedAnnealingSolverSystem& solverSystem, + double initialTemperature, double finalTemperature, double coolingRatio, + size_t iterationsPerStep, + CV_OUT double* lastTemperature = NULL, + cv::RNG& rngEnergy = cv::theRNG() +); + +//! @} ml + +} +} + +#include + +#endif // __cplusplus +#endif // OPENCV_ML_HPP + +/* End of file. */ diff --git a/3rdParty/opencv-4.11.0/opencv2/ml/ml.hpp b/3rdParty/opencv-4.11.0/opencv2/ml/ml.hpp index f6f9cd8f89..7c84aab559 100644 --- a/3rdParty/opencv-4.11.0/opencv2/ml/ml.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/ml/ml.hpp @@ -1,48 +1,48 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifdef __OPENCV_BUILD -#error this is a compatibility header which should not be used inside the OpenCV library -#endif - -#include "opencv2/ml.hpp" +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/ml.hpp" diff --git a/3rdParty/opencv-4.11.0/opencv2/ml/ml.inl.hpp b/3rdParty/opencv-4.11.0/opencv2/ml/ml.inl.hpp index dc9c78393a..91bab1f5f5 100644 --- a/3rdParty/opencv-4.11.0/opencv2/ml/ml.inl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/ml/ml.inl.hpp @@ -1,60 +1,60 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_ML_INL_HPP -#define OPENCV_ML_INL_HPP - -namespace cv { namespace ml { - -// declared in ml.hpp -template -int simulatedAnnealingSolver(SimulatedAnnealingSolverSystem& solverSystem, - double initialTemperature, double finalTemperature, double coolingRatio, - size_t iterationsPerStep, - CV_OUT double* lastTemperature, - cv::RNG& rngEnergy -) -{ - CV_Assert(finalTemperature > 0); - CV_Assert(initialTemperature > finalTemperature); - CV_Assert(iterationsPerStep > 0); - CV_Assert(coolingRatio < 1.0f); - double Ti = initialTemperature; - double previousEnergy = solverSystem.energy(); - int exchange = 0; - while (Ti > finalTemperature) - { - for (size_t i = 0; i < iterationsPerStep; i++) - { - solverSystem.changeState(); - double newEnergy = solverSystem.energy(); - if (newEnergy < previousEnergy) - { - previousEnergy = newEnergy; - exchange++; - } - else - { - double r = rngEnergy.uniform(0.0, 1.0); - if (r < std::exp(-(newEnergy - previousEnergy) / Ti)) - { - previousEnergy = newEnergy; - exchange++; - } - else - { - solverSystem.reverseState(); - } - } - } - Ti *= coolingRatio; - } - if (lastTemperature) - *lastTemperature = Ti; - return exchange; -} - -}} //namespace - -#endif // OPENCV_ML_INL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_ML_INL_HPP +#define OPENCV_ML_INL_HPP + +namespace cv { namespace ml { + +// declared in ml.hpp +template +int simulatedAnnealingSolver(SimulatedAnnealingSolverSystem& solverSystem, + double initialTemperature, double finalTemperature, double coolingRatio, + size_t iterationsPerStep, + CV_OUT double* lastTemperature, + cv::RNG& rngEnergy +) +{ + CV_Assert(finalTemperature > 0); + CV_Assert(initialTemperature > finalTemperature); + CV_Assert(iterationsPerStep > 0); + CV_Assert(coolingRatio < 1.0f); + double Ti = initialTemperature; + double previousEnergy = solverSystem.energy(); + int exchange = 0; + while (Ti > finalTemperature) + { + for (size_t i = 0; i < iterationsPerStep; i++) + { + solverSystem.changeState(); + double newEnergy = solverSystem.energy(); + if (newEnergy < previousEnergy) + { + previousEnergy = newEnergy; + exchange++; + } + else + { + double r = rngEnergy.uniform(0.0, 1.0); + if (r < std::exp(-(newEnergy - previousEnergy) / Ti)) + { + previousEnergy = newEnergy; + exchange++; + } + else + { + solverSystem.reverseState(); + } + } + } + Ti *= coolingRatio; + } + if (lastTemperature) + *lastTemperature = Ti; + return exchange; +} + +}} //namespace + +#endif // OPENCV_ML_INL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/objdetect.hpp b/3rdParty/opencv-4.11.0/opencv2/objdetect.hpp index 7f11890608..15364fc88b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/objdetect.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/objdetect.hpp @@ -1,873 +1,873 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_OBJDETECT_HPP -#define OPENCV_OBJDETECT_HPP - -#include "opencv2/core.hpp" -#include "opencv2/objdetect/aruco_detector.hpp" -#include "opencv2/objdetect/graphical_code_detector.hpp" - -/** -@defgroup objdetect Object Detection - -@{ - @defgroup objdetect_cascade_classifier Cascade Classifier for Object Detection - - The object detector described below has been initially proposed by Paul Viola @cite Viola01 and - improved by Rainer Lienhart @cite Lienhart02 . - - First, a classifier (namely a *cascade of boosted classifiers working with haar-like features*) is - trained with a few hundred sample views of a particular object (i.e., a face or a car), called - positive examples, that are scaled to the same size (say, 20x20), and negative examples - arbitrary - images of the same size. - - After a classifier is trained, it can be applied to a region of interest (of the same size as used - during the training) in an input image. The classifier outputs a "1" if the region is likely to show - the object (i.e., face/car), and "0" otherwise. To search for the object in the whole image one can - move the search window across the image and check every location using the classifier. The - classifier is designed so that it can be easily "resized" in order to be able to find the objects of - interest at different sizes, which is more efficient than resizing the image itself. So, to find an - object of an unknown size in the image the scan procedure should be done several times at different - scales. - - The word "cascade" in the classifier name means that the resultant classifier consists of several - simpler classifiers (*stages*) that are applied subsequently to a region of interest until at some - stage the candidate is rejected or all the stages are passed. The word "boosted" means that the - classifiers at every stage of the cascade are complex themselves and they are built out of basic - classifiers using one of four different boosting techniques (weighted voting). Currently Discrete - Adaboost, Real Adaboost, Gentle Adaboost and Logitboost are supported. The basic classifiers are - decision-tree classifiers with at least 2 leaves. Haar-like features are the input to the basic - classifiers, and are calculated as described below. The current algorithm uses the following - Haar-like features: - - ![image](pics/haarfeatures.png) - - The feature used in a particular classifier is specified by its shape (1a, 2b etc.), position within - the region of interest and the scale (this scale is not the same as the scale used at the detection - stage, though these two scales are multiplied). For example, in the case of the third line feature - (2c) the response is calculated as the difference between the sum of image pixels under the - rectangle covering the whole feature (including the two white stripes and the black stripe in the - middle) and the sum of the image pixels under the black stripe multiplied by 3 in order to - compensate for the differences in the size of areas. The sums of pixel values over a rectangular - regions are calculated rapidly using integral images (see below and the integral description). - - Check @ref tutorial_cascade_classifier "the corresponding tutorial" for more details. - - The following reference is for the detection part only. There is a separate application called - opencv_traincascade that can train a cascade of boosted classifiers from a set of samples. - - @note In the new C++ interface it is also possible to use LBP (local binary pattern) features in - addition to Haar-like features. .. [Viola01] Paul Viola and Michael J. Jones. Rapid Object Detection - using a Boosted Cascade of Simple Features. IEEE CVPR, 2001. The paper is available online at - - - @defgroup objdetect_hog HOG (Histogram of Oriented Gradients) descriptor and object detector - @defgroup objdetect_barcode Barcode detection and decoding - @defgroup objdetect_qrcode QRCode detection and encoding - @defgroup objdetect_dnn_face DNN-based face detection and recognition - - Check @ref tutorial_dnn_face "the corresponding tutorial" for more details. - - @defgroup objdetect_common Common functions and classes - @defgroup objdetect_aruco ArUco markers and boards detection for robust camera pose estimation - @{ - ArUco Marker Detection - Square fiducial markers (also known as Augmented Reality Markers) are useful for easy, - fast and robust camera pose estimation. - - The main functionality of ArucoDetector class is detection of markers in an image. If the markers are grouped - as a board, then you can try to recover the missing markers with ArucoDetector::refineDetectedMarkers(). - ArUco markers can also be used for advanced chessboard corner finding. To do this, group the markers in the - CharucoBoard and find the corners of the chessboard with the CharucoDetector::detectBoard(). - - The implementation is based on the ArUco Library by R. Muñoz-Salinas and S. Garrido-Jurado @cite Aruco2014. - - Markers can also be detected based on the AprilTag 2 @cite wang2016iros fiducial detection method. - - @sa @cite Aruco2014 - This code has been originally developed by Sergio Garrido-Jurado as a project - for Google Summer of Code 2015 (GSoC 15). - @} - -@} - */ - -typedef struct CvHaarClassifierCascade CvHaarClassifierCascade; - -namespace cv -{ - -//! @addtogroup objdetect_common -//! @{ - -///////////////////////////// Object Detection //////////////////////////// - -/** @brief This class is used for grouping object candidates detected by Cascade Classifier, HOG etc. - -instance of the class is to be passed to cv::partition - */ -class CV_EXPORTS SimilarRects -{ -public: - SimilarRects(double _eps) : eps(_eps) {} - inline bool operator()(const Rect& r1, const Rect& r2) const - { - double delta = eps * ((std::min)(r1.width, r2.width) + (std::min)(r1.height, r2.height)) * 0.5; - return std::abs(r1.x - r2.x) <= delta && - std::abs(r1.y - r2.y) <= delta && - std::abs(r1.x + r1.width - r2.x - r2.width) <= delta && - std::abs(r1.y + r1.height - r2.y - r2.height) <= delta; - } - double eps; -}; - -/** @brief Groups the object candidate rectangles. - -@param rectList Input/output vector of rectangles. Output vector includes retained and grouped -rectangles. (The Python list is not modified in place.) -@param groupThreshold Minimum possible number of rectangles minus 1. The threshold is used in a -group of rectangles to retain it. -@param eps Relative difference between sides of the rectangles to merge them into a group. - -The function is a wrapper for the generic function partition . It clusters all the input rectangles -using the rectangle equivalence criteria that combines rectangles with similar sizes and similar -locations. The similarity is defined by eps. When eps=0 , no clustering is done at all. If -\f$\texttt{eps}\rightarrow +\inf\f$ , all the rectangles are put in one cluster. Then, the small -clusters containing less than or equal to groupThreshold rectangles are rejected. In each other -cluster, the average rectangle is computed and put into the output rectangle list. - */ -CV_EXPORTS void groupRectangles(std::vector& rectList, int groupThreshold, double eps = 0.2); -/** @overload */ -CV_EXPORTS_W void groupRectangles(CV_IN_OUT std::vector& rectList, CV_OUT std::vector& weights, - int groupThreshold, double eps = 0.2); -/** @overload */ -CV_EXPORTS void groupRectangles(std::vector& rectList, int groupThreshold, - double eps, std::vector* weights, std::vector* levelWeights ); -/** @overload */ -CV_EXPORTS void groupRectangles(std::vector& rectList, std::vector& rejectLevels, - std::vector& levelWeights, int groupThreshold, double eps = 0.2); -/** @overload */ -CV_EXPORTS void groupRectangles_meanshift(std::vector& rectList, std::vector& foundWeights, - std::vector& foundScales, - double detectThreshold = 0.0, Size winDetSize = Size(64, 128)); -//! @} - -//! @addtogroup objdetect_cascade_classifier -//! @{ - -template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvHaarClassifierCascade* obj) const; }; - -enum { CASCADE_DO_CANNY_PRUNING = 1, - CASCADE_SCALE_IMAGE = 2, - CASCADE_FIND_BIGGEST_OBJECT = 4, - CASCADE_DO_ROUGH_SEARCH = 8 - }; - -class CV_EXPORTS_W BaseCascadeClassifier : public Algorithm -{ -public: - virtual ~BaseCascadeClassifier(); - virtual bool empty() const CV_OVERRIDE = 0; - virtual bool load( const String& filename ) = 0; - virtual void detectMultiScale( InputArray image, - CV_OUT std::vector& objects, - double scaleFactor, - int minNeighbors, int flags, - Size minSize, Size maxSize ) = 0; - - virtual void detectMultiScale( InputArray image, - CV_OUT std::vector& objects, - CV_OUT std::vector& numDetections, - double scaleFactor, - int minNeighbors, int flags, - Size minSize, Size maxSize ) = 0; - - virtual void detectMultiScale( InputArray image, - CV_OUT std::vector& objects, - CV_OUT std::vector& rejectLevels, - CV_OUT std::vector& levelWeights, - double scaleFactor, - int minNeighbors, int flags, - Size minSize, Size maxSize, - bool outputRejectLevels ) = 0; - - virtual bool isOldFormatCascade() const = 0; - virtual Size getOriginalWindowSize() const = 0; - virtual int getFeatureType() const = 0; - virtual void* getOldCascade() = 0; - - class CV_EXPORTS MaskGenerator - { - public: - virtual ~MaskGenerator() {} - virtual Mat generateMask(const Mat& src)=0; - virtual void initializeMask(const Mat& /*src*/) { } - }; - virtual void setMaskGenerator(const Ptr& maskGenerator) = 0; - virtual Ptr getMaskGenerator() = 0; -}; - -/** @example samples/cpp/facedetect.cpp -This program demonstrates usage of the Cascade classifier class -\image html Cascade_Classifier_Tutorial_Result_Haar.jpg "Sample screenshot" width=321 height=254 -*/ -/** @brief Cascade classifier class for object detection. - */ -class CV_EXPORTS_W CascadeClassifier -{ -public: - CV_WRAP CascadeClassifier(); - /** @brief Loads a classifier from a file. - - @param filename Name of the file from which the classifier is loaded. - */ - CV_WRAP CascadeClassifier(const String& filename); - ~CascadeClassifier(); - /** @brief Checks whether the classifier has been loaded. - */ - CV_WRAP bool empty() const; - /** @brief Loads a classifier from a file. - - @param filename Name of the file from which the classifier is loaded. The file may contain an old - HAAR classifier trained by the haartraining application or a new cascade classifier trained by the - traincascade application. - */ - CV_WRAP bool load( const String& filename ); - /** @brief Reads a classifier from a FileStorage node. - - @note The file may contain a new cascade classifier (trained by the traincascade application) only. - */ - CV_WRAP bool read( const FileNode& node ); - - /** @brief Detects objects of different sizes in the input image. The detected objects are returned as a list - of rectangles. - - @param image Matrix of the type CV_8U containing an image where objects are detected. - @param objects Vector of rectangles where each rectangle contains the detected object, the - rectangles may be partially outside the original image. - @param scaleFactor Parameter specifying how much the image size is reduced at each image scale. - @param minNeighbors Parameter specifying how many neighbors each candidate rectangle should have - to retain it. - @param flags Parameter with the same meaning for an old cascade as in the function - cvHaarDetectObjects. It is not used for a new cascade. - @param minSize Minimum possible object size. Objects smaller than that are ignored. - @param maxSize Maximum possible object size. Objects larger than that are ignored. If `maxSize == minSize` model is evaluated on single scale. - */ - CV_WRAP void detectMultiScale( InputArray image, - CV_OUT std::vector& objects, - double scaleFactor = 1.1, - int minNeighbors = 3, int flags = 0, - Size minSize = Size(), - Size maxSize = Size() ); - - /** @overload - @param image Matrix of the type CV_8U containing an image where objects are detected. - @param objects Vector of rectangles where each rectangle contains the detected object, the - rectangles may be partially outside the original image. - @param numDetections Vector of detection numbers for the corresponding objects. An object's number - of detections is the number of neighboring positively classified rectangles that were joined - together to form the object. - @param scaleFactor Parameter specifying how much the image size is reduced at each image scale. - @param minNeighbors Parameter specifying how many neighbors each candidate rectangle should have - to retain it. - @param flags Parameter with the same meaning for an old cascade as in the function - cvHaarDetectObjects. It is not used for a new cascade. - @param minSize Minimum possible object size. Objects smaller than that are ignored. - @param maxSize Maximum possible object size. Objects larger than that are ignored. If `maxSize == minSize` model is evaluated on single scale. - */ - CV_WRAP_AS(detectMultiScale2) void detectMultiScale( InputArray image, - CV_OUT std::vector& objects, - CV_OUT std::vector& numDetections, - double scaleFactor=1.1, - int minNeighbors=3, int flags=0, - Size minSize=Size(), - Size maxSize=Size() ); - - /** @overload - This function allows you to retrieve the final stage decision certainty of classification. - For this, one needs to set `outputRejectLevels` on true and provide the `rejectLevels` and `levelWeights` parameter. - For each resulting detection, `levelWeights` will then contain the certainty of classification at the final stage. - This value can then be used to separate strong from weaker classifications. - - A code sample on how to use it efficiently can be found below: - @code - Mat img; - vector weights; - vector levels; - vector detections; - CascadeClassifier model("/path/to/your/model.xml"); - model.detectMultiScale(img, detections, levels, weights, 1.1, 3, 0, Size(), Size(), true); - cerr << "Detection " << detections[0] << " with weight " << weights[0] << endl; - @endcode - */ - CV_WRAP_AS(detectMultiScale3) void detectMultiScale( InputArray image, - CV_OUT std::vector& objects, - CV_OUT std::vector& rejectLevels, - CV_OUT std::vector& levelWeights, - double scaleFactor = 1.1, - int minNeighbors = 3, int flags = 0, - Size minSize = Size(), - Size maxSize = Size(), - bool outputRejectLevels = false ); - - CV_WRAP bool isOldFormatCascade() const; - CV_WRAP Size getOriginalWindowSize() const; - CV_WRAP int getFeatureType() const; - void* getOldCascade(); - - CV_WRAP static bool convert(const String& oldcascade, const String& newcascade); - - void setMaskGenerator(const Ptr& maskGenerator); - Ptr getMaskGenerator(); - - Ptr cc; -}; - -CV_EXPORTS Ptr createFaceDetectionMaskGenerator(); -//! @} - -//! @addtogroup objdetect_hog -//! @{ -//////////////// HOG (Histogram-of-Oriented-Gradients) Descriptor and Object Detector ////////////// - -//! struct for detection region of interest (ROI) -struct DetectionROI -{ - //! scale(size) of the bounding box - double scale; - //! set of requested locations to be evaluated - std::vector locations; - //! vector that will contain confidence values for each location - std::vector confidences; -}; - -/**@brief Implementation of HOG (Histogram of Oriented Gradients) descriptor and object detector. - -the HOG descriptor algorithm introduced by Navneet Dalal and Bill Triggs @cite Dalal2005 . - -useful links: - -https://hal.inria.fr/inria-00548512/document/ - -https://en.wikipedia.org/wiki/Histogram_of_oriented_gradients - -https://software.intel.com/en-us/ipp-dev-reference-histogram-of-oriented-gradients-hog-descriptor - -http://www.learnopencv.com/histogram-of-oriented-gradients - -http://www.learnopencv.com/handwritten-digits-classification-an-opencv-c-python-tutorial - - */ -struct CV_EXPORTS_W HOGDescriptor -{ -public: - enum HistogramNormType { L2Hys = 0 //!< Default histogramNormType - }; - enum { DEFAULT_NLEVELS = 64 //!< Default nlevels value. - }; - enum DescriptorStorageFormat { DESCR_FORMAT_COL_BY_COL, DESCR_FORMAT_ROW_BY_ROW }; - - /**@brief Creates the HOG descriptor and detector with default parameters. - - aqual to HOGDescriptor(Size(64,128), Size(16,16), Size(8,8), Size(8,8), 9 ) - */ - CV_WRAP HOGDescriptor() : winSize(64,128), blockSize(16,16), blockStride(8,8), - cellSize(8,8), nbins(9), derivAperture(1), winSigma(-1), - histogramNormType(HOGDescriptor::L2Hys), L2HysThreshold(0.2), gammaCorrection(true), - free_coef(-1.f), nlevels(HOGDescriptor::DEFAULT_NLEVELS), signedGradient(false) - {} - - /** @overload - @param _winSize sets winSize with given value. - @param _blockSize sets blockSize with given value. - @param _blockStride sets blockStride with given value. - @param _cellSize sets cellSize with given value. - @param _nbins sets nbins with given value. - @param _derivAperture sets derivAperture with given value. - @param _winSigma sets winSigma with given value. - @param _histogramNormType sets histogramNormType with given value. - @param _L2HysThreshold sets L2HysThreshold with given value. - @param _gammaCorrection sets gammaCorrection with given value. - @param _nlevels sets nlevels with given value. - @param _signedGradient sets signedGradient with given value. - */ - CV_WRAP HOGDescriptor(Size _winSize, Size _blockSize, Size _blockStride, - Size _cellSize, int _nbins, int _derivAperture=1, double _winSigma=-1, - HOGDescriptor::HistogramNormType _histogramNormType=HOGDescriptor::L2Hys, - double _L2HysThreshold=0.2, bool _gammaCorrection=false, - int _nlevels=HOGDescriptor::DEFAULT_NLEVELS, bool _signedGradient=false) - : winSize(_winSize), blockSize(_blockSize), blockStride(_blockStride), cellSize(_cellSize), - nbins(_nbins), derivAperture(_derivAperture), winSigma(_winSigma), - histogramNormType(_histogramNormType), L2HysThreshold(_L2HysThreshold), - gammaCorrection(_gammaCorrection), free_coef(-1.f), nlevels(_nlevels), signedGradient(_signedGradient) - {} - - /** @overload - - Creates the HOG descriptor and detector and loads HOGDescriptor parameters and coefficients for the linear SVM classifier from a file. - @param filename The file name containing HOGDescriptor properties and coefficients for the linear SVM classifier. - */ - CV_WRAP HOGDescriptor(const String& filename) - { - load(filename); - } - - /** @overload - @param d the HOGDescriptor which cloned to create a new one. - */ - HOGDescriptor(const HOGDescriptor& d) - { - d.copyTo(*this); - } - - /**@brief Default destructor. - */ - virtual ~HOGDescriptor() {} - - /**@brief Returns the number of coefficients required for the classification. - */ - CV_WRAP size_t getDescriptorSize() const; - - /** @brief Checks if detector size equal to descriptor size. - */ - CV_WRAP bool checkDetectorSize() const; - - /** @brief Returns winSigma value - */ - CV_WRAP double getWinSigma() const; - - /**@example samples/cpp/peopledetect.cpp - */ - /**@brief Sets coefficients for the linear SVM classifier. - @param svmdetector coefficients for the linear SVM classifier. - */ - CV_WRAP virtual void setSVMDetector(InputArray svmdetector); - - /** @brief Reads HOGDescriptor parameters and coefficients for the linear SVM classifier from a file node. - @param fn File node - */ - virtual bool read(FileNode& fn); - - /** @brief Stores HOGDescriptor parameters and coefficients for the linear SVM classifier in a file storage. - @param fs File storage - @param objname Object name - */ - virtual void write(FileStorage& fs, const String& objname) const; - - /** @brief loads HOGDescriptor parameters and coefficients for the linear SVM classifier from a file - @param filename Name of the file to read. - @param objname The optional name of the node to read (if empty, the first top-level node will be used). - */ - CV_WRAP virtual bool load(const String& filename, const String& objname = String()); - - /** @brief saves HOGDescriptor parameters and coefficients for the linear SVM classifier to a file - @param filename File name - @param objname Object name - */ - CV_WRAP virtual void save(const String& filename, const String& objname = String()) const; - - /** @brief clones the HOGDescriptor - @param c cloned HOGDescriptor - */ - virtual void copyTo(HOGDescriptor& c) const; - - /**@example samples/cpp/train_HOG.cpp - */ - /** @brief Computes HOG descriptors of given image. - @param img Matrix of the type CV_8U containing an image where HOG features will be calculated. - @param descriptors Matrix of the type CV_32F - @param winStride Window stride. It must be a multiple of block stride. - @param padding Padding - @param locations Vector of Point - */ - CV_WRAP virtual void compute(InputArray img, - CV_OUT std::vector& descriptors, - Size winStride = Size(), Size padding = Size(), - const std::vector& locations = std::vector()) const; - - /** @brief Performs object detection without a multi-scale window. - @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected. - @param foundLocations Vector of point where each point contains left-top corner point of detected object boundaries. - @param weights Vector that will contain confidence values for each detected object. - @param hitThreshold Threshold for the distance between features and SVM classifying plane. - Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient). - But if the free coefficient is omitted (which is allowed), you can specify it manually here. - @param winStride Window stride. It must be a multiple of block stride. - @param padding Padding - @param searchLocations Vector of Point includes set of requested locations to be evaluated. - */ - CV_WRAP virtual void detect(InputArray img, CV_OUT std::vector& foundLocations, - CV_OUT std::vector& weights, - double hitThreshold = 0, Size winStride = Size(), - Size padding = Size(), - const std::vector& searchLocations = std::vector()) const; - - /** @brief Performs object detection without a multi-scale window. - @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected. - @param foundLocations Vector of point where each point contains left-top corner point of detected object boundaries. - @param hitThreshold Threshold for the distance between features and SVM classifying plane. - Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient). - But if the free coefficient is omitted (which is allowed), you can specify it manually here. - @param winStride Window stride. It must be a multiple of block stride. - @param padding Padding - @param searchLocations Vector of Point includes locations to search. - */ - virtual void detect(InputArray img, CV_OUT std::vector& foundLocations, - double hitThreshold = 0, Size winStride = Size(), - Size padding = Size(), - const std::vector& searchLocations=std::vector()) const; - - /** @brief Detects objects of different sizes in the input image. The detected objects are returned as a list - of rectangles. - @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected. - @param foundLocations Vector of rectangles where each rectangle contains the detected object. - @param foundWeights Vector that will contain confidence values for each detected object. - @param hitThreshold Threshold for the distance between features and SVM classifying plane. - Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient). - But if the free coefficient is omitted (which is allowed), you can specify it manually here. - @param winStride Window stride. It must be a multiple of block stride. - @param padding Padding - @param scale Coefficient of the detection window increase. - @param groupThreshold Coefficient to regulate the similarity threshold. When detected, some objects can be covered - by many rectangles. 0 means not to perform grouping. - @param useMeanshiftGrouping indicates grouping algorithm - */ - CV_WRAP virtual void detectMultiScale(InputArray img, CV_OUT std::vector& foundLocations, - CV_OUT std::vector& foundWeights, double hitThreshold = 0, - Size winStride = Size(), Size padding = Size(), double scale = 1.05, - double groupThreshold = 2.0, bool useMeanshiftGrouping = false) const; - - /** @brief Detects objects of different sizes in the input image. The detected objects are returned as a list - of rectangles. - @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected. - @param foundLocations Vector of rectangles where each rectangle contains the detected object. - @param hitThreshold Threshold for the distance between features and SVM classifying plane. - Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient). - But if the free coefficient is omitted (which is allowed), you can specify it manually here. - @param winStride Window stride. It must be a multiple of block stride. - @param padding Padding - @param scale Coefficient of the detection window increase. - @param groupThreshold Coefficient to regulate the similarity threshold. When detected, some objects can be covered - by many rectangles. 0 means not to perform grouping. - @param useMeanshiftGrouping indicates grouping algorithm - */ - virtual void detectMultiScale(InputArray img, CV_OUT std::vector& foundLocations, - double hitThreshold = 0, Size winStride = Size(), - Size padding = Size(), double scale = 1.05, - double groupThreshold = 2.0, bool useMeanshiftGrouping = false) const; - - /** @brief Computes gradients and quantized gradient orientations. - @param img Matrix contains the image to be computed - @param grad Matrix of type CV_32FC2 contains computed gradients - @param angleOfs Matrix of type CV_8UC2 contains quantized gradient orientations - @param paddingTL Padding from top-left - @param paddingBR Padding from bottom-right - */ - CV_WRAP virtual void computeGradient(InputArray img, InputOutputArray grad, InputOutputArray angleOfs, - Size paddingTL = Size(), Size paddingBR = Size()) const; - - /** @brief Returns coefficients of the classifier trained for people detection (for 64x128 windows). - */ - CV_WRAP static std::vector getDefaultPeopleDetector(); - - /**@example samples/tapi/hog.cpp - */ - /** @brief Returns coefficients of the classifier trained for people detection (for 48x96 windows). - */ - CV_WRAP static std::vector getDaimlerPeopleDetector(); - - //! Detection window size. Align to block size and block stride. Default value is Size(64,128). - CV_PROP Size winSize; - - //! Block size in pixels. Align to cell size. Default value is Size(16,16). - CV_PROP Size blockSize; - - //! Block stride. It must be a multiple of cell size. Default value is Size(8,8). - CV_PROP Size blockStride; - - //! Cell size. Default value is Size(8,8). - CV_PROP Size cellSize; - - //! Number of bins used in the calculation of histogram of gradients. Default value is 9. - CV_PROP int nbins; - - //! not documented - CV_PROP int derivAperture; - - //! Gaussian smoothing window parameter. - CV_PROP double winSigma; - - //! histogramNormType - CV_PROP HOGDescriptor::HistogramNormType histogramNormType; - - //! L2-Hys normalization method shrinkage. - CV_PROP double L2HysThreshold; - - //! Flag to specify whether the gamma correction preprocessing is required or not. - CV_PROP bool gammaCorrection; - - //! coefficients for the linear SVM classifier. - CV_PROP std::vector svmDetector; - - //! coefficients for the linear SVM classifier used when OpenCL is enabled - UMat oclSvmDetector; - - //! not documented - float free_coef; - - //! Maximum number of detection window increases. Default value is 64 - CV_PROP int nlevels; - - //! Indicates signed gradient will be used or not - CV_PROP bool signedGradient; - - /** @brief evaluate specified ROI and return confidence value for each location - @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected. - @param locations Vector of Point - @param foundLocations Vector of Point where each Point is detected object's top-left point. - @param confidences confidences - @param hitThreshold Threshold for the distance between features and SVM classifying plane. Usually - it is 0 and should be specified in the detector coefficients (as the last free coefficient). But if - the free coefficient is omitted (which is allowed), you can specify it manually here - @param winStride winStride - @param padding padding - */ - virtual void detectROI(InputArray img, const std::vector &locations, - CV_OUT std::vector& foundLocations, CV_OUT std::vector& confidences, - double hitThreshold = 0, cv::Size winStride = Size(), - cv::Size padding = Size()) const; - - /** @brief evaluate specified ROI and return confidence value for each location in multiple scales - @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected. - @param foundLocations Vector of rectangles where each rectangle contains the detected object. - @param locations Vector of DetectionROI - @param hitThreshold Threshold for the distance between features and SVM classifying plane. Usually it is 0 and should be specified - in the detector coefficients (as the last free coefficient). But if the free coefficient is omitted (which is allowed), you can specify it manually here. - @param groupThreshold Minimum possible number of rectangles minus 1. The threshold is used in a group of rectangles to retain it. - */ - virtual void detectMultiScaleROI(InputArray img, - CV_OUT std::vector& foundLocations, - std::vector& locations, - double hitThreshold = 0, - int groupThreshold = 0) const; - - /** @brief Groups the object candidate rectangles. - @param rectList Input/output vector of rectangles. Output vector includes retained and grouped rectangles. (The Python list is not modified in place.) - @param weights Input/output vector of weights of rectangles. Output vector includes weights of retained and grouped rectangles. (The Python list is not modified in place.) - @param groupThreshold Minimum possible number of rectangles minus 1. The threshold is used in a group of rectangles to retain it. - @param eps Relative difference between sides of the rectangles to merge them into a group. - */ - void groupRectangles(std::vector& rectList, std::vector& weights, int groupThreshold, double eps) const; -}; -//! @} - -//! @addtogroup objdetect_qrcode -//! @{ - -class CV_EXPORTS_W QRCodeEncoder { -protected: - QRCodeEncoder(); // use ::create() -public: - virtual ~QRCodeEncoder(); - - enum EncodeMode { - MODE_AUTO = -1, - MODE_NUMERIC = 1, // 0b0001 - MODE_ALPHANUMERIC = 2, // 0b0010 - MODE_BYTE = 4, // 0b0100 - MODE_ECI = 7, // 0b0111 - MODE_KANJI = 8, // 0b1000 - MODE_STRUCTURED_APPEND = 3 // 0b0011 - }; - - enum CorrectionLevel { - CORRECT_LEVEL_L = 0, - CORRECT_LEVEL_M = 1, - CORRECT_LEVEL_Q = 2, - CORRECT_LEVEL_H = 3 - }; - - enum ECIEncodings { - ECI_UTF8 = 26 - }; - - /** @brief QR code encoder parameters. */ - struct CV_EXPORTS_W_SIMPLE Params - { - CV_WRAP Params(); - - //! The optional version of QR code (by default - maximum possible depending on the length of the string). - CV_PROP_RW int version; - - //! The optional level of error correction (by default - the lowest). - CV_PROP_RW CorrectionLevel correction_level; - - //! The optional encoding mode - Numeric, Alphanumeric, Byte, Kanji, ECI or Structured Append. - CV_PROP_RW EncodeMode mode; - - //! The optional number of QR codes to generate in Structured Append mode. - CV_PROP_RW int structure_number; - }; - - /** @brief Constructor - @param parameters QR code encoder parameters QRCodeEncoder::Params - */ - static CV_WRAP - Ptr create(const QRCodeEncoder::Params& parameters = QRCodeEncoder::Params()); - - /** @brief Generates QR code from input string. - @param encoded_info Input string to encode. - @param qrcode Generated QR code. - */ - CV_WRAP virtual void encode(const String& encoded_info, OutputArray qrcode) = 0; - - /** @brief Generates QR code from input string in Structured Append mode. The encoded message is splitting over a number of QR codes. - @param encoded_info Input string to encode. - @param qrcodes Vector of generated QR codes. - */ - CV_WRAP virtual void encodeStructuredAppend(const String& encoded_info, OutputArrayOfArrays qrcodes) = 0; - -}; -class CV_EXPORTS_W_SIMPLE QRCodeDetector : public GraphicalCodeDetector -{ -public: - CV_WRAP QRCodeDetector(); - - /** @brief sets the epsilon used during the horizontal scan of QR code stop marker detection. - @param epsX Epsilon neighborhood, which allows you to determine the horizontal pattern - of the scheme 1:1:3:1:1 according to QR code standard. - */ - CV_WRAP QRCodeDetector& setEpsX(double epsX); - /** @brief sets the epsilon used during the vertical scan of QR code stop marker detection. - @param epsY Epsilon neighborhood, which allows you to determine the vertical pattern - of the scheme 1:1:3:1:1 according to QR code standard. - */ - CV_WRAP QRCodeDetector& setEpsY(double epsY); - - /** @brief use markers to improve the position of the corners of the QR code - * - * alignmentMarkers using by default - */ - CV_WRAP QRCodeDetector& setUseAlignmentMarkers(bool useAlignmentMarkers); - - /** @brief Decodes QR code on a curved surface in image once it's found by the detect() method. - - Returns UTF8-encoded output string or empty string if the code cannot be decoded. - @param img grayscale or color (BGR) image containing QR code. - @param points Quadrangle vertices found by detect() method (or some other algorithm). - @param straight_qrcode The optional output image containing rectified and binarized QR code - */ - CV_WRAP cv::String decodeCurved(InputArray img, InputArray points, OutputArray straight_qrcode = noArray()); - - /** @brief Both detects and decodes QR code on a curved surface - - @param img grayscale or color (BGR) image containing QR code. - @param points optional output array of vertices of the found QR code quadrangle. Will be empty if not found. - @param straight_qrcode The optional output image containing rectified and binarized QR code - */ - CV_WRAP std::string detectAndDecodeCurved(InputArray img, OutputArray points=noArray(), - OutputArray straight_qrcode = noArray()); -}; - -class CV_EXPORTS_W_SIMPLE QRCodeDetectorAruco : public GraphicalCodeDetector { -public: - CV_WRAP QRCodeDetectorAruco(); - - struct CV_EXPORTS_W_SIMPLE Params { - CV_WRAP Params(); - - /** @brief The minimum allowed pixel size of a QR module in the smallest image in the image pyramid, default 4.f */ - CV_PROP_RW float minModuleSizeInPyramid; - - /** @brief The maximum allowed relative rotation for finder patterns in the same QR code, default pi/12 */ - CV_PROP_RW float maxRotation; - - /** @brief The maximum allowed relative mismatch in module sizes for finder patterns in the same QR code, default 1.75f */ - CV_PROP_RW float maxModuleSizeMismatch; - - /** @brief The maximum allowed module relative mismatch for timing pattern module, default 2.f - * - * If relative mismatch of timing pattern module more this value, penalty points will be added. - * If a lot of penalty points are added, QR code will be rejected. */ - CV_PROP_RW float maxTimingPatternMismatch; - - /** @brief The maximum allowed percentage of penalty points out of total pins in timing pattern, default 0.4f */ - CV_PROP_RW float maxPenalties; - - /** @brief The maximum allowed relative color mismatch in the timing pattern, default 0.2f*/ - CV_PROP_RW float maxColorsMismatch; - - /** @brief The algorithm find QR codes with almost minimum timing pattern score and minimum size, default 0.9f - * - * The QR code with the minimum "timing pattern score" and minimum "size" is selected as the best QR code. - * If for the current QR code "timing pattern score" * scaleTimingPatternScore < "previous timing pattern score" and "size" < "previous size", then - * current QR code set as the best QR code. */ - CV_PROP_RW float scaleTimingPatternScore; - }; - - /** @brief QR code detector constructor for Aruco-based algorithm. See cv::QRCodeDetectorAruco::Params */ - CV_WRAP explicit QRCodeDetectorAruco(const QRCodeDetectorAruco::Params& params); - - /** @brief Detector parameters getter. See cv::QRCodeDetectorAruco::Params */ - CV_WRAP const QRCodeDetectorAruco::Params& getDetectorParameters() const; - - /** @brief Detector parameters setter. See cv::QRCodeDetectorAruco::Params */ - CV_WRAP QRCodeDetectorAruco& setDetectorParameters(const QRCodeDetectorAruco::Params& params); - - /** @brief Aruco detector parameters are used to search for the finder patterns. */ - CV_WRAP const aruco::DetectorParameters& getArucoParameters() const; - - /** @brief Aruco detector parameters are used to search for the finder patterns. */ - CV_WRAP void setArucoParameters(const aruco::DetectorParameters& params); -}; - -//! @} -} - -#include "opencv2/objdetect/detection_based_tracker.hpp" -#include "opencv2/objdetect/face.hpp" -#include "opencv2/objdetect/charuco_detector.hpp" -#include "opencv2/objdetect/barcode.hpp" - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_OBJDETECT_HPP +#define OPENCV_OBJDETECT_HPP + +#include "opencv2/core.hpp" +#include "opencv2/objdetect/aruco_detector.hpp" +#include "opencv2/objdetect/graphical_code_detector.hpp" + +/** +@defgroup objdetect Object Detection + +@{ + @defgroup objdetect_cascade_classifier Cascade Classifier for Object Detection + + The object detector described below has been initially proposed by Paul Viola @cite Viola01 and + improved by Rainer Lienhart @cite Lienhart02 . + + First, a classifier (namely a *cascade of boosted classifiers working with haar-like features*) is + trained with a few hundred sample views of a particular object (i.e., a face or a car), called + positive examples, that are scaled to the same size (say, 20x20), and negative examples - arbitrary + images of the same size. + + After a classifier is trained, it can be applied to a region of interest (of the same size as used + during the training) in an input image. The classifier outputs a "1" if the region is likely to show + the object (i.e., face/car), and "0" otherwise. To search for the object in the whole image one can + move the search window across the image and check every location using the classifier. The + classifier is designed so that it can be easily "resized" in order to be able to find the objects of + interest at different sizes, which is more efficient than resizing the image itself. So, to find an + object of an unknown size in the image the scan procedure should be done several times at different + scales. + + The word "cascade" in the classifier name means that the resultant classifier consists of several + simpler classifiers (*stages*) that are applied subsequently to a region of interest until at some + stage the candidate is rejected or all the stages are passed. The word "boosted" means that the + classifiers at every stage of the cascade are complex themselves and they are built out of basic + classifiers using one of four different boosting techniques (weighted voting). Currently Discrete + Adaboost, Real Adaboost, Gentle Adaboost and Logitboost are supported. The basic classifiers are + decision-tree classifiers with at least 2 leaves. Haar-like features are the input to the basic + classifiers, and are calculated as described below. The current algorithm uses the following + Haar-like features: + + ![image](pics/haarfeatures.png) + + The feature used in a particular classifier is specified by its shape (1a, 2b etc.), position within + the region of interest and the scale (this scale is not the same as the scale used at the detection + stage, though these two scales are multiplied). For example, in the case of the third line feature + (2c) the response is calculated as the difference between the sum of image pixels under the + rectangle covering the whole feature (including the two white stripes and the black stripe in the + middle) and the sum of the image pixels under the black stripe multiplied by 3 in order to + compensate for the differences in the size of areas. The sums of pixel values over a rectangular + regions are calculated rapidly using integral images (see below and the integral description). + + Check @ref tutorial_cascade_classifier "the corresponding tutorial" for more details. + + The following reference is for the detection part only. There is a separate application called + opencv_traincascade that can train a cascade of boosted classifiers from a set of samples. + + @note In the new C++ interface it is also possible to use LBP (local binary pattern) features in + addition to Haar-like features. .. [Viola01] Paul Viola and Michael J. Jones. Rapid Object Detection + using a Boosted Cascade of Simple Features. IEEE CVPR, 2001. The paper is available online at + + + @defgroup objdetect_hog HOG (Histogram of Oriented Gradients) descriptor and object detector + @defgroup objdetect_barcode Barcode detection and decoding + @defgroup objdetect_qrcode QRCode detection and encoding + @defgroup objdetect_dnn_face DNN-based face detection and recognition + + Check @ref tutorial_dnn_face "the corresponding tutorial" for more details. + + @defgroup objdetect_common Common functions and classes + @defgroup objdetect_aruco ArUco markers and boards detection for robust camera pose estimation + @{ + ArUco Marker Detection + Square fiducial markers (also known as Augmented Reality Markers) are useful for easy, + fast and robust camera pose estimation. + + The main functionality of ArucoDetector class is detection of markers in an image. If the markers are grouped + as a board, then you can try to recover the missing markers with ArucoDetector::refineDetectedMarkers(). + ArUco markers can also be used for advanced chessboard corner finding. To do this, group the markers in the + CharucoBoard and find the corners of the chessboard with the CharucoDetector::detectBoard(). + + The implementation is based on the ArUco Library by R. Muñoz-Salinas and S. Garrido-Jurado @cite Aruco2014. + + Markers can also be detected based on the AprilTag 2 @cite wang2016iros fiducial detection method. + + @sa @cite Aruco2014 + This code has been originally developed by Sergio Garrido-Jurado as a project + for Google Summer of Code 2015 (GSoC 15). + @} + +@} + */ + +typedef struct CvHaarClassifierCascade CvHaarClassifierCascade; + +namespace cv +{ + +//! @addtogroup objdetect_common +//! @{ + +///////////////////////////// Object Detection //////////////////////////// + +/** @brief This class is used for grouping object candidates detected by Cascade Classifier, HOG etc. + +instance of the class is to be passed to cv::partition + */ +class CV_EXPORTS SimilarRects +{ +public: + SimilarRects(double _eps) : eps(_eps) {} + inline bool operator()(const Rect& r1, const Rect& r2) const + { + double delta = eps * ((std::min)(r1.width, r2.width) + (std::min)(r1.height, r2.height)) * 0.5; + return std::abs(r1.x - r2.x) <= delta && + std::abs(r1.y - r2.y) <= delta && + std::abs(r1.x + r1.width - r2.x - r2.width) <= delta && + std::abs(r1.y + r1.height - r2.y - r2.height) <= delta; + } + double eps; +}; + +/** @brief Groups the object candidate rectangles. + +@param rectList Input/output vector of rectangles. Output vector includes retained and grouped +rectangles. (The Python list is not modified in place.) +@param groupThreshold Minimum possible number of rectangles minus 1. The threshold is used in a +group of rectangles to retain it. +@param eps Relative difference between sides of the rectangles to merge them into a group. + +The function is a wrapper for the generic function partition . It clusters all the input rectangles +using the rectangle equivalence criteria that combines rectangles with similar sizes and similar +locations. The similarity is defined by eps. When eps=0 , no clustering is done at all. If +\f$\texttt{eps}\rightarrow +\inf\f$ , all the rectangles are put in one cluster. Then, the small +clusters containing less than or equal to groupThreshold rectangles are rejected. In each other +cluster, the average rectangle is computed and put into the output rectangle list. + */ +CV_EXPORTS void groupRectangles(std::vector& rectList, int groupThreshold, double eps = 0.2); +/** @overload */ +CV_EXPORTS_W void groupRectangles(CV_IN_OUT std::vector& rectList, CV_OUT std::vector& weights, + int groupThreshold, double eps = 0.2); +/** @overload */ +CV_EXPORTS void groupRectangles(std::vector& rectList, int groupThreshold, + double eps, std::vector* weights, std::vector* levelWeights ); +/** @overload */ +CV_EXPORTS void groupRectangles(std::vector& rectList, std::vector& rejectLevels, + std::vector& levelWeights, int groupThreshold, double eps = 0.2); +/** @overload */ +CV_EXPORTS void groupRectangles_meanshift(std::vector& rectList, std::vector& foundWeights, + std::vector& foundScales, + double detectThreshold = 0.0, Size winDetSize = Size(64, 128)); +//! @} + +//! @addtogroup objdetect_cascade_classifier +//! @{ + +template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvHaarClassifierCascade* obj) const; }; + +enum { CASCADE_DO_CANNY_PRUNING = 1, + CASCADE_SCALE_IMAGE = 2, + CASCADE_FIND_BIGGEST_OBJECT = 4, + CASCADE_DO_ROUGH_SEARCH = 8 + }; + +class CV_EXPORTS_W BaseCascadeClassifier : public Algorithm +{ +public: + virtual ~BaseCascadeClassifier(); + virtual bool empty() const CV_OVERRIDE = 0; + virtual bool load( const String& filename ) = 0; + virtual void detectMultiScale( InputArray image, + CV_OUT std::vector& objects, + double scaleFactor, + int minNeighbors, int flags, + Size minSize, Size maxSize ) = 0; + + virtual void detectMultiScale( InputArray image, + CV_OUT std::vector& objects, + CV_OUT std::vector& numDetections, + double scaleFactor, + int minNeighbors, int flags, + Size minSize, Size maxSize ) = 0; + + virtual void detectMultiScale( InputArray image, + CV_OUT std::vector& objects, + CV_OUT std::vector& rejectLevels, + CV_OUT std::vector& levelWeights, + double scaleFactor, + int minNeighbors, int flags, + Size minSize, Size maxSize, + bool outputRejectLevels ) = 0; + + virtual bool isOldFormatCascade() const = 0; + virtual Size getOriginalWindowSize() const = 0; + virtual int getFeatureType() const = 0; + virtual void* getOldCascade() = 0; + + class CV_EXPORTS MaskGenerator + { + public: + virtual ~MaskGenerator() {} + virtual Mat generateMask(const Mat& src)=0; + virtual void initializeMask(const Mat& /*src*/) { } + }; + virtual void setMaskGenerator(const Ptr& maskGenerator) = 0; + virtual Ptr getMaskGenerator() = 0; +}; + +/** @example samples/cpp/facedetect.cpp +This program demonstrates usage of the Cascade classifier class +\image html Cascade_Classifier_Tutorial_Result_Haar.jpg "Sample screenshot" width=321 height=254 +*/ +/** @brief Cascade classifier class for object detection. + */ +class CV_EXPORTS_W CascadeClassifier +{ +public: + CV_WRAP CascadeClassifier(); + /** @brief Loads a classifier from a file. + + @param filename Name of the file from which the classifier is loaded. + */ + CV_WRAP CascadeClassifier(const String& filename); + ~CascadeClassifier(); + /** @brief Checks whether the classifier has been loaded. + */ + CV_WRAP bool empty() const; + /** @brief Loads a classifier from a file. + + @param filename Name of the file from which the classifier is loaded. The file may contain an old + HAAR classifier trained by the haartraining application or a new cascade classifier trained by the + traincascade application. + */ + CV_WRAP bool load( const String& filename ); + /** @brief Reads a classifier from a FileStorage node. + + @note The file may contain a new cascade classifier (trained by the traincascade application) only. + */ + CV_WRAP bool read( const FileNode& node ); + + /** @brief Detects objects of different sizes in the input image. The detected objects are returned as a list + of rectangles. + + @param image Matrix of the type CV_8U containing an image where objects are detected. + @param objects Vector of rectangles where each rectangle contains the detected object, the + rectangles may be partially outside the original image. + @param scaleFactor Parameter specifying how much the image size is reduced at each image scale. + @param minNeighbors Parameter specifying how many neighbors each candidate rectangle should have + to retain it. + @param flags Parameter with the same meaning for an old cascade as in the function + cvHaarDetectObjects. It is not used for a new cascade. + @param minSize Minimum possible object size. Objects smaller than that are ignored. + @param maxSize Maximum possible object size. Objects larger than that are ignored. If `maxSize == minSize` model is evaluated on single scale. + */ + CV_WRAP void detectMultiScale( InputArray image, + CV_OUT std::vector& objects, + double scaleFactor = 1.1, + int minNeighbors = 3, int flags = 0, + Size minSize = Size(), + Size maxSize = Size() ); + + /** @overload + @param image Matrix of the type CV_8U containing an image where objects are detected. + @param objects Vector of rectangles where each rectangle contains the detected object, the + rectangles may be partially outside the original image. + @param numDetections Vector of detection numbers for the corresponding objects. An object's number + of detections is the number of neighboring positively classified rectangles that were joined + together to form the object. + @param scaleFactor Parameter specifying how much the image size is reduced at each image scale. + @param minNeighbors Parameter specifying how many neighbors each candidate rectangle should have + to retain it. + @param flags Parameter with the same meaning for an old cascade as in the function + cvHaarDetectObjects. It is not used for a new cascade. + @param minSize Minimum possible object size. Objects smaller than that are ignored. + @param maxSize Maximum possible object size. Objects larger than that are ignored. If `maxSize == minSize` model is evaluated on single scale. + */ + CV_WRAP_AS(detectMultiScale2) void detectMultiScale( InputArray image, + CV_OUT std::vector& objects, + CV_OUT std::vector& numDetections, + double scaleFactor=1.1, + int minNeighbors=3, int flags=0, + Size minSize=Size(), + Size maxSize=Size() ); + + /** @overload + This function allows you to retrieve the final stage decision certainty of classification. + For this, one needs to set `outputRejectLevels` on true and provide the `rejectLevels` and `levelWeights` parameter. + For each resulting detection, `levelWeights` will then contain the certainty of classification at the final stage. + This value can then be used to separate strong from weaker classifications. + + A code sample on how to use it efficiently can be found below: + @code + Mat img; + vector weights; + vector levels; + vector detections; + CascadeClassifier model("/path/to/your/model.xml"); + model.detectMultiScale(img, detections, levels, weights, 1.1, 3, 0, Size(), Size(), true); + cerr << "Detection " << detections[0] << " with weight " << weights[0] << endl; + @endcode + */ + CV_WRAP_AS(detectMultiScale3) void detectMultiScale( InputArray image, + CV_OUT std::vector& objects, + CV_OUT std::vector& rejectLevels, + CV_OUT std::vector& levelWeights, + double scaleFactor = 1.1, + int minNeighbors = 3, int flags = 0, + Size minSize = Size(), + Size maxSize = Size(), + bool outputRejectLevels = false ); + + CV_WRAP bool isOldFormatCascade() const; + CV_WRAP Size getOriginalWindowSize() const; + CV_WRAP int getFeatureType() const; + void* getOldCascade(); + + CV_WRAP static bool convert(const String& oldcascade, const String& newcascade); + + void setMaskGenerator(const Ptr& maskGenerator); + Ptr getMaskGenerator(); + + Ptr cc; +}; + +CV_EXPORTS Ptr createFaceDetectionMaskGenerator(); +//! @} + +//! @addtogroup objdetect_hog +//! @{ +//////////////// HOG (Histogram-of-Oriented-Gradients) Descriptor and Object Detector ////////////// + +//! struct for detection region of interest (ROI) +struct DetectionROI +{ + //! scale(size) of the bounding box + double scale; + //! set of requested locations to be evaluated + std::vector locations; + //! vector that will contain confidence values for each location + std::vector confidences; +}; + +/**@brief Implementation of HOG (Histogram of Oriented Gradients) descriptor and object detector. + +the HOG descriptor algorithm introduced by Navneet Dalal and Bill Triggs @cite Dalal2005 . + +useful links: + +https://hal.inria.fr/inria-00548512/document/ + +https://en.wikipedia.org/wiki/Histogram_of_oriented_gradients + +https://software.intel.com/en-us/ipp-dev-reference-histogram-of-oriented-gradients-hog-descriptor + +http://www.learnopencv.com/histogram-of-oriented-gradients + +http://www.learnopencv.com/handwritten-digits-classification-an-opencv-c-python-tutorial + + */ +struct CV_EXPORTS_W HOGDescriptor +{ +public: + enum HistogramNormType { L2Hys = 0 //!< Default histogramNormType + }; + enum { DEFAULT_NLEVELS = 64 //!< Default nlevels value. + }; + enum DescriptorStorageFormat { DESCR_FORMAT_COL_BY_COL, DESCR_FORMAT_ROW_BY_ROW }; + + /**@brief Creates the HOG descriptor and detector with default parameters. + + aqual to HOGDescriptor(Size(64,128), Size(16,16), Size(8,8), Size(8,8), 9 ) + */ + CV_WRAP HOGDescriptor() : winSize(64,128), blockSize(16,16), blockStride(8,8), + cellSize(8,8), nbins(9), derivAperture(1), winSigma(-1), + histogramNormType(HOGDescriptor::L2Hys), L2HysThreshold(0.2), gammaCorrection(true), + free_coef(-1.f), nlevels(HOGDescriptor::DEFAULT_NLEVELS), signedGradient(false) + {} + + /** @overload + @param _winSize sets winSize with given value. + @param _blockSize sets blockSize with given value. + @param _blockStride sets blockStride with given value. + @param _cellSize sets cellSize with given value. + @param _nbins sets nbins with given value. + @param _derivAperture sets derivAperture with given value. + @param _winSigma sets winSigma with given value. + @param _histogramNormType sets histogramNormType with given value. + @param _L2HysThreshold sets L2HysThreshold with given value. + @param _gammaCorrection sets gammaCorrection with given value. + @param _nlevels sets nlevels with given value. + @param _signedGradient sets signedGradient with given value. + */ + CV_WRAP HOGDescriptor(Size _winSize, Size _blockSize, Size _blockStride, + Size _cellSize, int _nbins, int _derivAperture=1, double _winSigma=-1, + HOGDescriptor::HistogramNormType _histogramNormType=HOGDescriptor::L2Hys, + double _L2HysThreshold=0.2, bool _gammaCorrection=false, + int _nlevels=HOGDescriptor::DEFAULT_NLEVELS, bool _signedGradient=false) + : winSize(_winSize), blockSize(_blockSize), blockStride(_blockStride), cellSize(_cellSize), + nbins(_nbins), derivAperture(_derivAperture), winSigma(_winSigma), + histogramNormType(_histogramNormType), L2HysThreshold(_L2HysThreshold), + gammaCorrection(_gammaCorrection), free_coef(-1.f), nlevels(_nlevels), signedGradient(_signedGradient) + {} + + /** @overload + + Creates the HOG descriptor and detector and loads HOGDescriptor parameters and coefficients for the linear SVM classifier from a file. + @param filename The file name containing HOGDescriptor properties and coefficients for the linear SVM classifier. + */ + CV_WRAP HOGDescriptor(const String& filename) + { + load(filename); + } + + /** @overload + @param d the HOGDescriptor which cloned to create a new one. + */ + HOGDescriptor(const HOGDescriptor& d) + { + d.copyTo(*this); + } + + /**@brief Default destructor. + */ + virtual ~HOGDescriptor() {} + + /**@brief Returns the number of coefficients required for the classification. + */ + CV_WRAP size_t getDescriptorSize() const; + + /** @brief Checks if detector size equal to descriptor size. + */ + CV_WRAP bool checkDetectorSize() const; + + /** @brief Returns winSigma value + */ + CV_WRAP double getWinSigma() const; + + /**@example samples/cpp/peopledetect.cpp + */ + /**@brief Sets coefficients for the linear SVM classifier. + @param svmdetector coefficients for the linear SVM classifier. + */ + CV_WRAP virtual void setSVMDetector(InputArray svmdetector); + + /** @brief Reads HOGDescriptor parameters and coefficients for the linear SVM classifier from a file node. + @param fn File node + */ + virtual bool read(FileNode& fn); + + /** @brief Stores HOGDescriptor parameters and coefficients for the linear SVM classifier in a file storage. + @param fs File storage + @param objname Object name + */ + virtual void write(FileStorage& fs, const String& objname) const; + + /** @brief loads HOGDescriptor parameters and coefficients for the linear SVM classifier from a file + @param filename Name of the file to read. + @param objname The optional name of the node to read (if empty, the first top-level node will be used). + */ + CV_WRAP virtual bool load(const String& filename, const String& objname = String()); + + /** @brief saves HOGDescriptor parameters and coefficients for the linear SVM classifier to a file + @param filename File name + @param objname Object name + */ + CV_WRAP virtual void save(const String& filename, const String& objname = String()) const; + + /** @brief clones the HOGDescriptor + @param c cloned HOGDescriptor + */ + virtual void copyTo(HOGDescriptor& c) const; + + /**@example samples/cpp/train_HOG.cpp + */ + /** @brief Computes HOG descriptors of given image. + @param img Matrix of the type CV_8U containing an image where HOG features will be calculated. + @param descriptors Matrix of the type CV_32F + @param winStride Window stride. It must be a multiple of block stride. + @param padding Padding + @param locations Vector of Point + */ + CV_WRAP virtual void compute(InputArray img, + CV_OUT std::vector& descriptors, + Size winStride = Size(), Size padding = Size(), + const std::vector& locations = std::vector()) const; + + /** @brief Performs object detection without a multi-scale window. + @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected. + @param foundLocations Vector of point where each point contains left-top corner point of detected object boundaries. + @param weights Vector that will contain confidence values for each detected object. + @param hitThreshold Threshold for the distance between features and SVM classifying plane. + Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient). + But if the free coefficient is omitted (which is allowed), you can specify it manually here. + @param winStride Window stride. It must be a multiple of block stride. + @param padding Padding + @param searchLocations Vector of Point includes set of requested locations to be evaluated. + */ + CV_WRAP virtual void detect(InputArray img, CV_OUT std::vector& foundLocations, + CV_OUT std::vector& weights, + double hitThreshold = 0, Size winStride = Size(), + Size padding = Size(), + const std::vector& searchLocations = std::vector()) const; + + /** @brief Performs object detection without a multi-scale window. + @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected. + @param foundLocations Vector of point where each point contains left-top corner point of detected object boundaries. + @param hitThreshold Threshold for the distance between features and SVM classifying plane. + Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient). + But if the free coefficient is omitted (which is allowed), you can specify it manually here. + @param winStride Window stride. It must be a multiple of block stride. + @param padding Padding + @param searchLocations Vector of Point includes locations to search. + */ + virtual void detect(InputArray img, CV_OUT std::vector& foundLocations, + double hitThreshold = 0, Size winStride = Size(), + Size padding = Size(), + const std::vector& searchLocations=std::vector()) const; + + /** @brief Detects objects of different sizes in the input image. The detected objects are returned as a list + of rectangles. + @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected. + @param foundLocations Vector of rectangles where each rectangle contains the detected object. + @param foundWeights Vector that will contain confidence values for each detected object. + @param hitThreshold Threshold for the distance between features and SVM classifying plane. + Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient). + But if the free coefficient is omitted (which is allowed), you can specify it manually here. + @param winStride Window stride. It must be a multiple of block stride. + @param padding Padding + @param scale Coefficient of the detection window increase. + @param groupThreshold Coefficient to regulate the similarity threshold. When detected, some objects can be covered + by many rectangles. 0 means not to perform grouping. + @param useMeanshiftGrouping indicates grouping algorithm + */ + CV_WRAP virtual void detectMultiScale(InputArray img, CV_OUT std::vector& foundLocations, + CV_OUT std::vector& foundWeights, double hitThreshold = 0, + Size winStride = Size(), Size padding = Size(), double scale = 1.05, + double groupThreshold = 2.0, bool useMeanshiftGrouping = false) const; + + /** @brief Detects objects of different sizes in the input image. The detected objects are returned as a list + of rectangles. + @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected. + @param foundLocations Vector of rectangles where each rectangle contains the detected object. + @param hitThreshold Threshold for the distance between features and SVM classifying plane. + Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient). + But if the free coefficient is omitted (which is allowed), you can specify it manually here. + @param winStride Window stride. It must be a multiple of block stride. + @param padding Padding + @param scale Coefficient of the detection window increase. + @param groupThreshold Coefficient to regulate the similarity threshold. When detected, some objects can be covered + by many rectangles. 0 means not to perform grouping. + @param useMeanshiftGrouping indicates grouping algorithm + */ + virtual void detectMultiScale(InputArray img, CV_OUT std::vector& foundLocations, + double hitThreshold = 0, Size winStride = Size(), + Size padding = Size(), double scale = 1.05, + double groupThreshold = 2.0, bool useMeanshiftGrouping = false) const; + + /** @brief Computes gradients and quantized gradient orientations. + @param img Matrix contains the image to be computed + @param grad Matrix of type CV_32FC2 contains computed gradients + @param angleOfs Matrix of type CV_8UC2 contains quantized gradient orientations + @param paddingTL Padding from top-left + @param paddingBR Padding from bottom-right + */ + CV_WRAP virtual void computeGradient(InputArray img, InputOutputArray grad, InputOutputArray angleOfs, + Size paddingTL = Size(), Size paddingBR = Size()) const; + + /** @brief Returns coefficients of the classifier trained for people detection (for 64x128 windows). + */ + CV_WRAP static std::vector getDefaultPeopleDetector(); + + /**@example samples/tapi/hog.cpp + */ + /** @brief Returns coefficients of the classifier trained for people detection (for 48x96 windows). + */ + CV_WRAP static std::vector getDaimlerPeopleDetector(); + + //! Detection window size. Align to block size and block stride. Default value is Size(64,128). + CV_PROP Size winSize; + + //! Block size in pixels. Align to cell size. Default value is Size(16,16). + CV_PROP Size blockSize; + + //! Block stride. It must be a multiple of cell size. Default value is Size(8,8). + CV_PROP Size blockStride; + + //! Cell size. Default value is Size(8,8). + CV_PROP Size cellSize; + + //! Number of bins used in the calculation of histogram of gradients. Default value is 9. + CV_PROP int nbins; + + //! not documented + CV_PROP int derivAperture; + + //! Gaussian smoothing window parameter. + CV_PROP double winSigma; + + //! histogramNormType + CV_PROP HOGDescriptor::HistogramNormType histogramNormType; + + //! L2-Hys normalization method shrinkage. + CV_PROP double L2HysThreshold; + + //! Flag to specify whether the gamma correction preprocessing is required or not. + CV_PROP bool gammaCorrection; + + //! coefficients for the linear SVM classifier. + CV_PROP std::vector svmDetector; + + //! coefficients for the linear SVM classifier used when OpenCL is enabled + UMat oclSvmDetector; + + //! not documented + float free_coef; + + //! Maximum number of detection window increases. Default value is 64 + CV_PROP int nlevels; + + //! Indicates signed gradient will be used or not + CV_PROP bool signedGradient; + + /** @brief evaluate specified ROI and return confidence value for each location + @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected. + @param locations Vector of Point + @param foundLocations Vector of Point where each Point is detected object's top-left point. + @param confidences confidences + @param hitThreshold Threshold for the distance between features and SVM classifying plane. Usually + it is 0 and should be specified in the detector coefficients (as the last free coefficient). But if + the free coefficient is omitted (which is allowed), you can specify it manually here + @param winStride winStride + @param padding padding + */ + virtual void detectROI(InputArray img, const std::vector &locations, + CV_OUT std::vector& foundLocations, CV_OUT std::vector& confidences, + double hitThreshold = 0, cv::Size winStride = Size(), + cv::Size padding = Size()) const; + + /** @brief evaluate specified ROI and return confidence value for each location in multiple scales + @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected. + @param foundLocations Vector of rectangles where each rectangle contains the detected object. + @param locations Vector of DetectionROI + @param hitThreshold Threshold for the distance between features and SVM classifying plane. Usually it is 0 and should be specified + in the detector coefficients (as the last free coefficient). But if the free coefficient is omitted (which is allowed), you can specify it manually here. + @param groupThreshold Minimum possible number of rectangles minus 1. The threshold is used in a group of rectangles to retain it. + */ + virtual void detectMultiScaleROI(InputArray img, + CV_OUT std::vector& foundLocations, + std::vector& locations, + double hitThreshold = 0, + int groupThreshold = 0) const; + + /** @brief Groups the object candidate rectangles. + @param rectList Input/output vector of rectangles. Output vector includes retained and grouped rectangles. (The Python list is not modified in place.) + @param weights Input/output vector of weights of rectangles. Output vector includes weights of retained and grouped rectangles. (The Python list is not modified in place.) + @param groupThreshold Minimum possible number of rectangles minus 1. The threshold is used in a group of rectangles to retain it. + @param eps Relative difference between sides of the rectangles to merge them into a group. + */ + void groupRectangles(std::vector& rectList, std::vector& weights, int groupThreshold, double eps) const; +}; +//! @} + +//! @addtogroup objdetect_qrcode +//! @{ + +class CV_EXPORTS_W QRCodeEncoder { +protected: + QRCodeEncoder(); // use ::create() +public: + virtual ~QRCodeEncoder(); + + enum EncodeMode { + MODE_AUTO = -1, + MODE_NUMERIC = 1, // 0b0001 + MODE_ALPHANUMERIC = 2, // 0b0010 + MODE_BYTE = 4, // 0b0100 + MODE_ECI = 7, // 0b0111 + MODE_KANJI = 8, // 0b1000 + MODE_STRUCTURED_APPEND = 3 // 0b0011 + }; + + enum CorrectionLevel { + CORRECT_LEVEL_L = 0, + CORRECT_LEVEL_M = 1, + CORRECT_LEVEL_Q = 2, + CORRECT_LEVEL_H = 3 + }; + + enum ECIEncodings { + ECI_UTF8 = 26 + }; + + /** @brief QR code encoder parameters. */ + struct CV_EXPORTS_W_SIMPLE Params + { + CV_WRAP Params(); + + //! The optional version of QR code (by default - maximum possible depending on the length of the string). + CV_PROP_RW int version; + + //! The optional level of error correction (by default - the lowest). + CV_PROP_RW CorrectionLevel correction_level; + + //! The optional encoding mode - Numeric, Alphanumeric, Byte, Kanji, ECI or Structured Append. + CV_PROP_RW EncodeMode mode; + + //! The optional number of QR codes to generate in Structured Append mode. + CV_PROP_RW int structure_number; + }; + + /** @brief Constructor + @param parameters QR code encoder parameters QRCodeEncoder::Params + */ + static CV_WRAP + Ptr create(const QRCodeEncoder::Params& parameters = QRCodeEncoder::Params()); + + /** @brief Generates QR code from input string. + @param encoded_info Input string to encode. + @param qrcode Generated QR code. + */ + CV_WRAP virtual void encode(const String& encoded_info, OutputArray qrcode) = 0; + + /** @brief Generates QR code from input string in Structured Append mode. The encoded message is splitting over a number of QR codes. + @param encoded_info Input string to encode. + @param qrcodes Vector of generated QR codes. + */ + CV_WRAP virtual void encodeStructuredAppend(const String& encoded_info, OutputArrayOfArrays qrcodes) = 0; + +}; +class CV_EXPORTS_W_SIMPLE QRCodeDetector : public GraphicalCodeDetector +{ +public: + CV_WRAP QRCodeDetector(); + + /** @brief sets the epsilon used during the horizontal scan of QR code stop marker detection. + @param epsX Epsilon neighborhood, which allows you to determine the horizontal pattern + of the scheme 1:1:3:1:1 according to QR code standard. + */ + CV_WRAP QRCodeDetector& setEpsX(double epsX); + /** @brief sets the epsilon used during the vertical scan of QR code stop marker detection. + @param epsY Epsilon neighborhood, which allows you to determine the vertical pattern + of the scheme 1:1:3:1:1 according to QR code standard. + */ + CV_WRAP QRCodeDetector& setEpsY(double epsY); + + /** @brief use markers to improve the position of the corners of the QR code + * + * alignmentMarkers using by default + */ + CV_WRAP QRCodeDetector& setUseAlignmentMarkers(bool useAlignmentMarkers); + + /** @brief Decodes QR code on a curved surface in image once it's found by the detect() method. + + Returns UTF8-encoded output string or empty string if the code cannot be decoded. + @param img grayscale or color (BGR) image containing QR code. + @param points Quadrangle vertices found by detect() method (or some other algorithm). + @param straight_qrcode The optional output image containing rectified and binarized QR code + */ + CV_WRAP cv::String decodeCurved(InputArray img, InputArray points, OutputArray straight_qrcode = noArray()); + + /** @brief Both detects and decodes QR code on a curved surface + + @param img grayscale or color (BGR) image containing QR code. + @param points optional output array of vertices of the found QR code quadrangle. Will be empty if not found. + @param straight_qrcode The optional output image containing rectified and binarized QR code + */ + CV_WRAP std::string detectAndDecodeCurved(InputArray img, OutputArray points=noArray(), + OutputArray straight_qrcode = noArray()); +}; + +class CV_EXPORTS_W_SIMPLE QRCodeDetectorAruco : public GraphicalCodeDetector { +public: + CV_WRAP QRCodeDetectorAruco(); + + struct CV_EXPORTS_W_SIMPLE Params { + CV_WRAP Params(); + + /** @brief The minimum allowed pixel size of a QR module in the smallest image in the image pyramid, default 4.f */ + CV_PROP_RW float minModuleSizeInPyramid; + + /** @brief The maximum allowed relative rotation for finder patterns in the same QR code, default pi/12 */ + CV_PROP_RW float maxRotation; + + /** @brief The maximum allowed relative mismatch in module sizes for finder patterns in the same QR code, default 1.75f */ + CV_PROP_RW float maxModuleSizeMismatch; + + /** @brief The maximum allowed module relative mismatch for timing pattern module, default 2.f + * + * If relative mismatch of timing pattern module more this value, penalty points will be added. + * If a lot of penalty points are added, QR code will be rejected. */ + CV_PROP_RW float maxTimingPatternMismatch; + + /** @brief The maximum allowed percentage of penalty points out of total pins in timing pattern, default 0.4f */ + CV_PROP_RW float maxPenalties; + + /** @brief The maximum allowed relative color mismatch in the timing pattern, default 0.2f*/ + CV_PROP_RW float maxColorsMismatch; + + /** @brief The algorithm find QR codes with almost minimum timing pattern score and minimum size, default 0.9f + * + * The QR code with the minimum "timing pattern score" and minimum "size" is selected as the best QR code. + * If for the current QR code "timing pattern score" * scaleTimingPatternScore < "previous timing pattern score" and "size" < "previous size", then + * current QR code set as the best QR code. */ + CV_PROP_RW float scaleTimingPatternScore; + }; + + /** @brief QR code detector constructor for Aruco-based algorithm. See cv::QRCodeDetectorAruco::Params */ + CV_WRAP explicit QRCodeDetectorAruco(const QRCodeDetectorAruco::Params& params); + + /** @brief Detector parameters getter. See cv::QRCodeDetectorAruco::Params */ + CV_WRAP const QRCodeDetectorAruco::Params& getDetectorParameters() const; + + /** @brief Detector parameters setter. See cv::QRCodeDetectorAruco::Params */ + CV_WRAP QRCodeDetectorAruco& setDetectorParameters(const QRCodeDetectorAruco::Params& params); + + /** @brief Aruco detector parameters are used to search for the finder patterns. */ + CV_WRAP const aruco::DetectorParameters& getArucoParameters() const; + + /** @brief Aruco detector parameters are used to search for the finder patterns. */ + CV_WRAP void setArucoParameters(const aruco::DetectorParameters& params); +}; + +//! @} +} + +#include "opencv2/objdetect/detection_based_tracker.hpp" +#include "opencv2/objdetect/face.hpp" +#include "opencv2/objdetect/charuco_detector.hpp" +#include "opencv2/objdetect/barcode.hpp" + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/objdetect/aruco_board.hpp b/3rdParty/opencv-4.11.0/opencv2/objdetect/aruco_board.hpp index e8300c82bf..526a55e06c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/objdetect/aruco_board.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/objdetect/aruco_board.hpp @@ -1,199 +1,199 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html -#ifndef OPENCV_OBJDETECT_ARUCO_BOARD_HPP -#define OPENCV_OBJDETECT_ARUCO_BOARD_HPP - -#include - -namespace cv { -namespace aruco { -//! @addtogroup objdetect_aruco -//! @{ - -class Dictionary; - -/** @brief Board of ArUco markers - * - * A board is a set of markers in the 3D space with a common coordinate system. - * The common form of a board of marker is a planar (2D) board, however any 3D layout can be used. - * A Board object is composed by: - * - The object points of the marker corners, i.e. their coordinates respect to the board system. - * - The dictionary which indicates the type of markers of the board - * - The identifier of all the markers in the board. - */ -class CV_EXPORTS_W_SIMPLE Board { -public: - /** @brief Common Board constructor - * - * @param objPoints array of object points of all the marker corners in the board - * @param dictionary the dictionary of markers employed for this board - * @param ids vector of the identifiers of the markers in the board - */ - CV_WRAP Board(InputArrayOfArrays objPoints, const Dictionary& dictionary, InputArray ids); - - /** @brief return the Dictionary of markers employed for this board - */ - CV_WRAP const Dictionary& getDictionary() const; - - /** @brief return array of object points of all the marker corners in the board. - * - * Each marker include its 4 corners in this order: - * - objPoints[i][0] - left-top point of i-th marker - * - objPoints[i][1] - right-top point of i-th marker - * - objPoints[i][2] - right-bottom point of i-th marker - * - objPoints[i][3] - left-bottom point of i-th marker - * - * Markers are placed in a certain order - row by row, left to right in every row. For M markers, the size is Mx4. - */ - CV_WRAP const std::vector >& getObjPoints() const; - - /** @brief vector of the identifiers of the markers in the board (should be the same size as objPoints) - * @return vector of the identifiers of the markers - */ - CV_WRAP const std::vector& getIds() const; - - /** @brief get coordinate of the bottom right corner of the board, is set when calling the function create() - */ - CV_WRAP const Point3f& getRightBottomCorner() const; - - /** @brief Given a board configuration and a set of detected markers, returns the corresponding - * image points and object points, can be used in solvePnP() - * - * @param detectedCorners List of detected marker corners of the board. - * For cv::Board and cv::GridBoard the method expects std::vector> or std::vector with Aruco marker corners. - * For cv::CharucoBoard the method expects std::vector or Mat with ChAruco corners (chess board corners matched with Aruco markers). - * - * @param detectedIds List of identifiers for each marker or charuco corner. - * For any Board class the method expects std::vector or Mat. - * - * @param objPoints Vector of marker points in the board coordinate space. - * For any Board class the method expects std::vector objectPoints or cv::Mat - * - * @param imgPoints Vector of marker points in the image coordinate space. - * For any Board class the method expects std::vector objectPoints or cv::Mat - * - * @sa solvePnP - */ - CV_WRAP void matchImagePoints(InputArrayOfArrays detectedCorners, InputArray detectedIds, - OutputArray objPoints, OutputArray imgPoints) const; - - /** @brief Draw a planar board - * - * @param outSize size of the output image in pixels. - * @param img output image with the board. The size of this image will be outSize - * and the board will be on the center, keeping the board proportions. - * @param marginSize minimum margins (in pixels) of the board in the output image - * @param borderBits width of the marker borders. - * - * This function return the image of the board, ready to be printed. - */ - CV_WRAP void generateImage(Size outSize, OutputArray img, int marginSize = 0, int borderBits = 1) const; - - CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) - Board(); - - struct Impl; -protected: - Board(const Ptr& impl); - Ptr impl; -}; - -/** @brief Planar board with grid arrangement of markers - * - * More common type of board. All markers are placed in the same plane in a grid arrangement. - * The board image can be drawn using generateImage() method. - */ -class CV_EXPORTS_W_SIMPLE GridBoard : public Board { -public: - /** - * @brief GridBoard constructor - * - * @param size number of markers in x and y directions - * @param markerLength marker side length (normally in meters) - * @param markerSeparation separation between two markers (same unit as markerLength) - * @param dictionary dictionary of markers indicating the type of markers - * @param ids set of marker ids in dictionary to use on board. - */ - CV_WRAP GridBoard(const Size& size, float markerLength, float markerSeparation, - const Dictionary &dictionary, InputArray ids = noArray()); - - CV_WRAP Size getGridSize() const; - CV_WRAP float getMarkerLength() const; - CV_WRAP float getMarkerSeparation() const; - - CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) - GridBoard(); -}; - -/** - * @brief ChArUco board is a planar chessboard where the markers are placed inside the white squares of a chessboard. - * - * The benefits of ChArUco boards is that they provide both, ArUco markers versatility and chessboard corner precision, - * which is important for calibration and pose estimation. The board image can be drawn using generateImage() method. - */ -class CV_EXPORTS_W_SIMPLE CharucoBoard : public Board { -public: - /** @brief CharucoBoard constructor - * - * @param size number of chessboard squares in x and y directions - * @param squareLength squareLength chessboard square side length (normally in meters) - * @param markerLength marker side length (same unit than squareLength) - * @param dictionary dictionary of markers indicating the type of markers - * @param ids array of id used markers - * The first markers in the dictionary are used to fill the white chessboard squares. - */ - CV_WRAP CharucoBoard(const Size& size, float squareLength, float markerLength, - const Dictionary &dictionary, InputArray ids = noArray()); - - /** @brief set legacy chessboard pattern. - * - * Legacy setting creates chessboard patterns starting with a white box in the upper left corner - * if there is an even row count of chessboard boxes, otherwise it starts with a black box. - * This setting ensures compatibility to patterns created with OpenCV versions prior OpenCV 4.6.0. - * See https://github.com/opencv/opencv/issues/23152. - * - * Default value: false. - */ - CV_WRAP void setLegacyPattern(bool legacyPattern); - CV_WRAP bool getLegacyPattern() const; - - CV_WRAP Size getChessboardSize() const; - CV_WRAP float getSquareLength() const; - CV_WRAP float getMarkerLength() const; - - /** @brief get CharucoBoard::chessboardCorners - */ - CV_WRAP std::vector getChessboardCorners() const; - - /** @brief get CharucoBoard::nearestMarkerIdx, for each charuco corner, nearest marker index in ids array - */ - CV_PROP std::vector > getNearestMarkerIdx() const; - - /** @brief get CharucoBoard::nearestMarkerCorners, for each charuco corner, nearest marker corner id of each marker - */ - CV_PROP std::vector > getNearestMarkerCorners() const; - - /** @brief check whether the ChArUco markers are collinear - * - * @param charucoIds list of identifiers for each corner in charucoCorners per frame. - * @return bool value, 1 (true) if detected corners form a line, 0 (false) if they do not. - * solvePnP, calibration functions will fail if the corners are collinear (true). - * - * The number of ids in charucoIDs should be <= the number of chessboard corners in the board. - * This functions checks whether the charuco corners are on a straight line (returns true, if so), or not (false). - * Axis parallel, as well as diagonal and other straight lines detected. Degenerate cases: - * for number of charucoIDs <= 2,the function returns true. - */ - CV_WRAP bool checkCharucoCornersCollinear(InputArray charucoIds) const; - - CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) - CharucoBoard(); -}; - -//! @} - -} -} - -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html +#ifndef OPENCV_OBJDETECT_ARUCO_BOARD_HPP +#define OPENCV_OBJDETECT_ARUCO_BOARD_HPP + +#include + +namespace cv { +namespace aruco { +//! @addtogroup objdetect_aruco +//! @{ + +class Dictionary; + +/** @brief Board of ArUco markers + * + * A board is a set of markers in the 3D space with a common coordinate system. + * The common form of a board of marker is a planar (2D) board, however any 3D layout can be used. + * A Board object is composed by: + * - The object points of the marker corners, i.e. their coordinates respect to the board system. + * - The dictionary which indicates the type of markers of the board + * - The identifier of all the markers in the board. + */ +class CV_EXPORTS_W_SIMPLE Board { +public: + /** @brief Common Board constructor + * + * @param objPoints array of object points of all the marker corners in the board + * @param dictionary the dictionary of markers employed for this board + * @param ids vector of the identifiers of the markers in the board + */ + CV_WRAP Board(InputArrayOfArrays objPoints, const Dictionary& dictionary, InputArray ids); + + /** @brief return the Dictionary of markers employed for this board + */ + CV_WRAP const Dictionary& getDictionary() const; + + /** @brief return array of object points of all the marker corners in the board. + * + * Each marker include its 4 corners in this order: + * - objPoints[i][0] - left-top point of i-th marker + * - objPoints[i][1] - right-top point of i-th marker + * - objPoints[i][2] - right-bottom point of i-th marker + * - objPoints[i][3] - left-bottom point of i-th marker + * + * Markers are placed in a certain order - row by row, left to right in every row. For M markers, the size is Mx4. + */ + CV_WRAP const std::vector >& getObjPoints() const; + + /** @brief vector of the identifiers of the markers in the board (should be the same size as objPoints) + * @return vector of the identifiers of the markers + */ + CV_WRAP const std::vector& getIds() const; + + /** @brief get coordinate of the bottom right corner of the board, is set when calling the function create() + */ + CV_WRAP const Point3f& getRightBottomCorner() const; + + /** @brief Given a board configuration and a set of detected markers, returns the corresponding + * image points and object points, can be used in solvePnP() + * + * @param detectedCorners List of detected marker corners of the board. + * For cv::Board and cv::GridBoard the method expects std::vector> or std::vector with Aruco marker corners. + * For cv::CharucoBoard the method expects std::vector or Mat with ChAruco corners (chess board corners matched with Aruco markers). + * + * @param detectedIds List of identifiers for each marker or charuco corner. + * For any Board class the method expects std::vector or Mat. + * + * @param objPoints Vector of marker points in the board coordinate space. + * For any Board class the method expects std::vector objectPoints or cv::Mat + * + * @param imgPoints Vector of marker points in the image coordinate space. + * For any Board class the method expects std::vector objectPoints or cv::Mat + * + * @sa solvePnP + */ + CV_WRAP void matchImagePoints(InputArrayOfArrays detectedCorners, InputArray detectedIds, + OutputArray objPoints, OutputArray imgPoints) const; + + /** @brief Draw a planar board + * + * @param outSize size of the output image in pixels. + * @param img output image with the board. The size of this image will be outSize + * and the board will be on the center, keeping the board proportions. + * @param marginSize minimum margins (in pixels) of the board in the output image + * @param borderBits width of the marker borders. + * + * This function return the image of the board, ready to be printed. + */ + CV_WRAP void generateImage(Size outSize, OutputArray img, int marginSize = 0, int borderBits = 1) const; + + CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) + Board(); + + struct Impl; +protected: + Board(const Ptr& impl); + Ptr impl; +}; + +/** @brief Planar board with grid arrangement of markers + * + * More common type of board. All markers are placed in the same plane in a grid arrangement. + * The board image can be drawn using generateImage() method. + */ +class CV_EXPORTS_W_SIMPLE GridBoard : public Board { +public: + /** + * @brief GridBoard constructor + * + * @param size number of markers in x and y directions + * @param markerLength marker side length (normally in meters) + * @param markerSeparation separation between two markers (same unit as markerLength) + * @param dictionary dictionary of markers indicating the type of markers + * @param ids set of marker ids in dictionary to use on board. + */ + CV_WRAP GridBoard(const Size& size, float markerLength, float markerSeparation, + const Dictionary &dictionary, InputArray ids = noArray()); + + CV_WRAP Size getGridSize() const; + CV_WRAP float getMarkerLength() const; + CV_WRAP float getMarkerSeparation() const; + + CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) + GridBoard(); +}; + +/** + * @brief ChArUco board is a planar chessboard where the markers are placed inside the white squares of a chessboard. + * + * The benefits of ChArUco boards is that they provide both, ArUco markers versatility and chessboard corner precision, + * which is important for calibration and pose estimation. The board image can be drawn using generateImage() method. + */ +class CV_EXPORTS_W_SIMPLE CharucoBoard : public Board { +public: + /** @brief CharucoBoard constructor + * + * @param size number of chessboard squares in x and y directions + * @param squareLength squareLength chessboard square side length (normally in meters) + * @param markerLength marker side length (same unit than squareLength) + * @param dictionary dictionary of markers indicating the type of markers + * @param ids array of id used markers + * The first markers in the dictionary are used to fill the white chessboard squares. + */ + CV_WRAP CharucoBoard(const Size& size, float squareLength, float markerLength, + const Dictionary &dictionary, InputArray ids = noArray()); + + /** @brief set legacy chessboard pattern. + * + * Legacy setting creates chessboard patterns starting with a white box in the upper left corner + * if there is an even row count of chessboard boxes, otherwise it starts with a black box. + * This setting ensures compatibility to patterns created with OpenCV versions prior OpenCV 4.6.0. + * See https://github.com/opencv/opencv/issues/23152. + * + * Default value: false. + */ + CV_WRAP void setLegacyPattern(bool legacyPattern); + CV_WRAP bool getLegacyPattern() const; + + CV_WRAP Size getChessboardSize() const; + CV_WRAP float getSquareLength() const; + CV_WRAP float getMarkerLength() const; + + /** @brief get CharucoBoard::chessboardCorners + */ + CV_WRAP std::vector getChessboardCorners() const; + + /** @brief get CharucoBoard::nearestMarkerIdx, for each charuco corner, nearest marker index in ids array + */ + CV_PROP std::vector > getNearestMarkerIdx() const; + + /** @brief get CharucoBoard::nearestMarkerCorners, for each charuco corner, nearest marker corner id of each marker + */ + CV_PROP std::vector > getNearestMarkerCorners() const; + + /** @brief check whether the ChArUco markers are collinear + * + * @param charucoIds list of identifiers for each corner in charucoCorners per frame. + * @return bool value, 1 (true) if detected corners form a line, 0 (false) if they do not. + * solvePnP, calibration functions will fail if the corners are collinear (true). + * + * The number of ids in charucoIDs should be <= the number of chessboard corners in the board. + * This functions checks whether the charuco corners are on a straight line (returns true, if so), or not (false). + * Axis parallel, as well as diagonal and other straight lines detected. Degenerate cases: + * for number of charucoIDs <= 2,the function returns true. + */ + CV_WRAP bool checkCharucoCornersCollinear(InputArray charucoIds) const; + + CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) + CharucoBoard(); +}; + +//! @} + +} +} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/objdetect/aruco_detector.hpp b/3rdParty/opencv-4.11.0/opencv2/objdetect/aruco_detector.hpp index 9d30d55d17..2eac6e419d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/objdetect/aruco_detector.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/objdetect/aruco_detector.hpp @@ -1,400 +1,400 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html -#ifndef OPENCV_OBJDETECT_ARUCO_DETECTOR_HPP -#define OPENCV_OBJDETECT_ARUCO_DETECTOR_HPP - -#include -#include - -namespace cv { -namespace aruco { - -//! @addtogroup objdetect_aruco -//! @{ - -enum CornerRefineMethod{ - CORNER_REFINE_NONE, ///< Tag and corners detection based on the ArUco approach - CORNER_REFINE_SUBPIX, ///< ArUco approach and refine the corners locations using corner subpixel accuracy - CORNER_REFINE_CONTOUR, ///< ArUco approach and refine the corners locations using the contour-points line fitting - CORNER_REFINE_APRILTAG, ///< Tag and corners detection based on the AprilTag 2 approach @cite wang2016iros -}; - -/** @brief struct DetectorParameters is used by ArucoDetector - */ -struct CV_EXPORTS_W_SIMPLE DetectorParameters { - CV_WRAP DetectorParameters() { - adaptiveThreshWinSizeMin = 3; - adaptiveThreshWinSizeMax = 23; - adaptiveThreshWinSizeStep = 10; - adaptiveThreshConstant = 7; - minMarkerPerimeterRate = 0.03; - maxMarkerPerimeterRate = 4.; - polygonalApproxAccuracyRate = 0.03; - minCornerDistanceRate = 0.05; - minDistanceToBorder = 3; - minMarkerDistanceRate = 0.125; - cornerRefinementMethod = (int)CORNER_REFINE_NONE; - cornerRefinementWinSize = 5; - relativeCornerRefinmentWinSize = 0.3f; - cornerRefinementMaxIterations = 30; - cornerRefinementMinAccuracy = 0.1; - markerBorderBits = 1; - perspectiveRemovePixelPerCell = 4; - perspectiveRemoveIgnoredMarginPerCell = 0.13; - maxErroneousBitsInBorderRate = 0.35; - minOtsuStdDev = 5.0; - errorCorrectionRate = 0.6; - aprilTagQuadDecimate = 0.0; - aprilTagQuadSigma = 0.0; - aprilTagMinClusterPixels = 5; - aprilTagMaxNmaxima = 10; - aprilTagCriticalRad = (float)(10* CV_PI /180); - aprilTagMaxLineFitMse = 10.0; - aprilTagMinWhiteBlackDiff = 5; - aprilTagDeglitch = 0; - detectInvertedMarker = false; - useAruco3Detection = false; - minSideLengthCanonicalImg = 32; - minMarkerLengthRatioOriginalImg = 0.0; - } - - /** @brief Read a new set of DetectorParameters from FileNode (use FileStorage.root()). - */ - CV_WRAP bool readDetectorParameters(const FileNode& fn); - - /** @brief Write a set of DetectorParameters to FileStorage - */ - CV_WRAP bool writeDetectorParameters(FileStorage& fs, const String& name = String()); - - /// minimum window size for adaptive thresholding before finding contours (default 3). - CV_PROP_RW int adaptiveThreshWinSizeMin; - - /// maximum window size for adaptive thresholding before finding contours (default 23). - CV_PROP_RW int adaptiveThreshWinSizeMax; - - /// increments from adaptiveThreshWinSizeMin to adaptiveThreshWinSizeMax during the thresholding (default 10). - CV_PROP_RW int adaptiveThreshWinSizeStep; - - /// constant for adaptive thresholding before finding contours (default 7) - CV_PROP_RW double adaptiveThreshConstant; - - /** @brief determine minimum perimeter for marker contour to be detected. - * - * This is defined as a rate respect to the maximum dimension of the input image (default 0.03). - */ - CV_PROP_RW double minMarkerPerimeterRate; - - /** @brief determine maximum perimeter for marker contour to be detected. - * - * This is defined as a rate respect to the maximum dimension of the input image (default 4.0). - */ - CV_PROP_RW double maxMarkerPerimeterRate; - - /// minimum accuracy during the polygonal approximation process to determine which contours are squares. (default 0.03) - CV_PROP_RW double polygonalApproxAccuracyRate; - - /// minimum distance between corners for detected markers relative to its perimeter (default 0.05) - CV_PROP_RW double minCornerDistanceRate; - - /// minimum distance of any corner to the image border for detected markers (in pixels) (default 3) - CV_PROP_RW int minDistanceToBorder; - - /** @brief minimum average distance between the corners of the two markers to be grouped (default 0.125). - * - * The rate is relative to the smaller perimeter of the two markers. - * Two markers are grouped if average distance between the corners of the two markers is less than - * min(MarkerPerimeter1, MarkerPerimeter2)*minMarkerDistanceRate. - * - * default value is 0.125 because 0.125*MarkerPerimeter = (MarkerPerimeter / 4) * 0.5 = half the side of the marker. - * - * @note default value was changed from 0.05 after 4.8.1 release, because the filtering algorithm has been changed. - * Now a few candidates from the same group can be added to the list of candidates if they are far from each other. - * @sa minGroupDistance. - */ - CV_PROP_RW double minMarkerDistanceRate; - - /** @brief minimum average distance between the corners of the two markers in group to add them to the list of candidates - * - * The average distance between the corners of the two markers is calculated relative to its module size (default 0.21). - */ - CV_PROP_RW float minGroupDistance = 0.21f; - - /** @brief default value CORNER_REFINE_NONE */ - CV_PROP_RW int cornerRefinementMethod; - - /** @brief maximum window size for the corner refinement process (in pixels) (default 5). - * - * The window size may decrease if the ArUco marker is too small, check relativeCornerRefinmentWinSize. - * The final window size is calculated as: - * min(cornerRefinementWinSize, averageArucoModuleSize*relativeCornerRefinmentWinSize), - * where averageArucoModuleSize is average module size of ArUco marker in pixels. - * (ArUco marker is composed of black and white modules) - */ - CV_PROP_RW int cornerRefinementWinSize; - - /** @brief Dynamic window size for corner refinement relative to Aruco module size (default 0.3). - * - * The final window size is calculated as: - * min(cornerRefinementWinSize, averageArucoModuleSize*relativeCornerRefinmentWinSize), - * where averageArucoModuleSize is average module size of ArUco marker in pixels. - * (ArUco marker is composed of black and white modules) - * In the case of markers located far from each other, it may be useful to increase the value of the parameter to 0.4-0.5. - * In the case of markers located close to each other, it may be useful to decrease the parameter value to 0.1-0.2. - */ - CV_PROP_RW float relativeCornerRefinmentWinSize; - - /// maximum number of iterations for stop criteria of the corner refinement process (default 30). - CV_PROP_RW int cornerRefinementMaxIterations; - - /// minimum error for the stop cristeria of the corner refinement process (default: 0.1) - CV_PROP_RW double cornerRefinementMinAccuracy; - - /// number of bits of the marker border, i.e. marker border width (default 1). - CV_PROP_RW int markerBorderBits; - - /// number of bits (per dimension) for each cell of the marker when removing the perspective (default 4). - CV_PROP_RW int perspectiveRemovePixelPerCell; - - /** @brief width of the margin of pixels on each cell not considered for the determination of the cell bit. - * - * Represents the rate respect to the total size of the cell, i.e. perspectiveRemovePixelPerCell (default 0.13) - */ - CV_PROP_RW double perspectiveRemoveIgnoredMarginPerCell; - - /** @brief maximum number of accepted erroneous bits in the border (i.e. number of allowed white bits in the border). - * - * Represented as a rate respect to the total number of bits per marker (default 0.35). - */ - CV_PROP_RW double maxErroneousBitsInBorderRate; - - /** @brief minimun standard deviation in pixels values during the decodification step to apply Otsu - * thresholding (otherwise, all the bits are set to 0 or 1 depending on mean higher than 128 or not) (default 5.0) - */ - CV_PROP_RW double minOtsuStdDev; - - /// error correction rate respect to the maximun error correction capability for each dictionary (default 0.6). - CV_PROP_RW double errorCorrectionRate; - - /** @brief April :: User-configurable parameters. - * - * Detection of quads can be done on a lower-resolution image, improving speed at a cost of - * pose accuracy and a slight decrease in detection rate. Decoding the binary payload is still - */ - CV_PROP_RW float aprilTagQuadDecimate; - - /// what Gaussian blur should be applied to the segmented image (used for quad detection?) - CV_PROP_RW float aprilTagQuadSigma; - - // April :: Internal variables - /// reject quads containing too few pixels (default 5). - CV_PROP_RW int aprilTagMinClusterPixels; - - /// how many corner candidates to consider when segmenting a group of pixels into a quad (default 10). - CV_PROP_RW int aprilTagMaxNmaxima; - - /** @brief reject quads where pairs of edges have angles that are close to straight or close to 180 degrees. - * - * Zero means that no quads are rejected. (In radians) (default 10*PI/180) - */ - CV_PROP_RW float aprilTagCriticalRad; - - /// when fitting lines to the contours, what is the maximum mean squared error - CV_PROP_RW float aprilTagMaxLineFitMse; - - /** @brief add an extra check that the white model must be (overall) brighter than the black model. - * - * When we build our model of black & white pixels, we add an extra check that the white model must be (overall) - * brighter than the black model. How much brighter? (in pixel values, [0,255]), (default 5) - */ - CV_PROP_RW int aprilTagMinWhiteBlackDiff; - - /// should the thresholded image be deglitched? Only useful for very noisy images (default 0). - CV_PROP_RW int aprilTagDeglitch; - - /** @brief to check if there is a white marker. - * - * In order to generate a "white" marker just invert a normal marker by using a tilde, ~markerImage. (default false) - */ - CV_PROP_RW bool detectInvertedMarker; - - /** @brief enable the new and faster Aruco detection strategy. - * - * Proposed in the paper: - * Romero-Ramirez et al: Speeded up detection of squared fiducial markers (2018) - * https://www.researchgate.net/publication/325787310_Speeded_Up_Detection_of_Squared_Fiducial_Markers - */ - CV_PROP_RW bool useAruco3Detection; - - /// minimum side length of a marker in the canonical image. Latter is the binarized image in which contours are searched. - CV_PROP_RW int minSideLengthCanonicalImg; - - /// range [0,1], eq (2) from paper. The parameter tau_i has a direct influence on the processing speed. - CV_PROP_RW float minMarkerLengthRatioOriginalImg; -}; - -/** @brief struct RefineParameters is used by ArucoDetector - */ -struct CV_EXPORTS_W_SIMPLE RefineParameters { - CV_WRAP RefineParameters(float minRepDistance = 10.f, float errorCorrectionRate = 3.f, bool checkAllOrders = true); - - - /** @brief Read a new set of RefineParameters from FileNode (use FileStorage.root()). - */ - CV_WRAP bool readRefineParameters(const FileNode& fn); - - /** @brief Write a set of RefineParameters to FileStorage - */ - CV_WRAP bool writeRefineParameters(FileStorage& fs, const String& name = String()); - - /** @brief minRepDistance minimum distance between the corners of the rejected candidate and the reprojected marker - in order to consider it as a correspondence. - */ - CV_PROP_RW float minRepDistance; - - /** @brief errorCorrectionRate rate of allowed erroneous bits respect to the error correction capability of the used dictionary. - * - * -1 ignores the error correction step. - */ - CV_PROP_RW float errorCorrectionRate; - - /** @brief checkAllOrders consider the four posible corner orders in the rejectedCorners array. - * - * If it set to false, only the provided corner order is considered (default true). - */ - CV_PROP_RW bool checkAllOrders; -}; - -/** @brief The main functionality of ArucoDetector class is detection of markers in an image with detectMarkers() method. - * - * After detecting some markers in the image, you can try to find undetected markers from this dictionary with - * refineDetectedMarkers() method. - * - * @see DetectorParameters, RefineParameters - */ -class CV_EXPORTS_W ArucoDetector : public Algorithm -{ -public: - /** @brief Basic ArucoDetector constructor - * - * @param dictionary indicates the type of markers that will be searched - * @param detectorParams marker detection parameters - * @param refineParams marker refine detection parameters - */ - CV_WRAP ArucoDetector(const Dictionary &dictionary = getPredefinedDictionary(cv::aruco::DICT_4X4_50), - const DetectorParameters &detectorParams = DetectorParameters(), - const RefineParameters& refineParams = RefineParameters()); - - /** @brief Basic marker detection - * - * @param image input image - * @param corners vector of detected marker corners. For each marker, its four corners - * are provided, (e.g std::vector > ). For N detected markers, - * the dimensions of this array is Nx4. The order of the corners is clockwise. - * @param ids vector of identifiers of the detected markers. The identifier is of type int - * (e.g. std::vector). For N detected markers, the size of ids is also N. - * The identifiers have the same order than the markers in the imgPoints array. - * @param rejectedImgPoints contains the imgPoints of those squares whose inner code has not a - * correct codification. Useful for debugging purposes. - * - * Performs marker detection in the input image. Only markers included in the specific dictionary - * are searched. For each detected marker, it returns the 2D position of its corner in the image - * and its corresponding identifier. - * Note that this function does not perform pose estimation. - * @note The function does not correct lens distortion or takes it into account. It's recommended to undistort - * input image with corresponding camera model, if camera parameters are known - * @sa undistort, estimatePoseSingleMarkers, estimatePoseBoard - */ - CV_WRAP void detectMarkers(InputArray image, OutputArrayOfArrays corners, OutputArray ids, - OutputArrayOfArrays rejectedImgPoints = noArray()) const; - - /** @brief Refine not detected markers based on the already detected and the board layout - * - * @param image input image - * @param board layout of markers in the board. - * @param detectedCorners vector of already detected marker corners. - * @param detectedIds vector of already detected marker identifiers. - * @param rejectedCorners vector of rejected candidates during the marker detection process. - * @param cameraMatrix optional input 3x3 floating-point camera matrix - * \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ - * @param distCoeffs optional vector of distortion coefficients - * \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6],[s_1, s_2, s_3, s_4]])\f$ of 4, 5, 8 or 12 elements - * @param recoveredIdxs Optional array to returns the indexes of the recovered candidates in the - * original rejectedCorners array. - * - * This function tries to find markers that were not detected in the basic detecMarkers function. - * First, based on the current detected marker and the board layout, the function interpolates - * the position of the missing markers. Then it tries to find correspondence between the reprojected - * markers and the rejected candidates based on the minRepDistance and errorCorrectionRate parameters. - * If camera parameters and distortion coefficients are provided, missing markers are reprojected - * using projectPoint function. If not, missing marker projections are interpolated using global - * homography, and all the marker corners in the board must have the same Z coordinate. - */ - CV_WRAP void refineDetectedMarkers(InputArray image, const Board &board, - InputOutputArrayOfArrays detectedCorners, - InputOutputArray detectedIds, InputOutputArrayOfArrays rejectedCorners, - InputArray cameraMatrix = noArray(), InputArray distCoeffs = noArray(), - OutputArray recoveredIdxs = noArray()) const; - - CV_WRAP const Dictionary& getDictionary() const; - CV_WRAP void setDictionary(const Dictionary& dictionary); - - CV_WRAP const DetectorParameters& getDetectorParameters() const; - CV_WRAP void setDetectorParameters(const DetectorParameters& detectorParameters); - - CV_WRAP const RefineParameters& getRefineParameters() const; - CV_WRAP void setRefineParameters(const RefineParameters& refineParameters); - - /** @brief Stores algorithm parameters in a file storage - */ - virtual void write(FileStorage& fs) const override; - - /** @brief simplified API for language bindings - */ - CV_WRAP inline void write(FileStorage& fs, const String& name) { Algorithm::write(fs, name); } - - /** @brief Reads algorithm parameters from a file storage - */ - CV_WRAP virtual void read(const FileNode& fn) override; -protected: - struct ArucoDetectorImpl; - Ptr arucoDetectorImpl; -}; - -/** @brief Draw detected markers in image - * - * @param image input/output image. It must have 1 or 3 channels. The number of channels is not altered. - * @param corners positions of marker corners on input image. - * (e.g std::vector > ). For N detected markers, the dimensions of - * this array should be Nx4. The order of the corners should be clockwise. - * @param ids vector of identifiers for markers in markersCorners . - * Optional, if not provided, ids are not painted. - * @param borderColor color of marker borders. Rest of colors (text color and first corner color) - * are calculated based on this one to improve visualization. - * - * Given an array of detected marker corners and its corresponding ids, this functions draws - * the markers in the image. The marker borders are painted and the markers identifiers if provided. - * Useful for debugging purposes. - */ -CV_EXPORTS_W void drawDetectedMarkers(InputOutputArray image, InputArrayOfArrays corners, - InputArray ids = noArray(), Scalar borderColor = Scalar(0, 255, 0)); - -/** @brief Generate a canonical marker image - * - * @param dictionary dictionary of markers indicating the type of markers - * @param id identifier of the marker that will be returned. It has to be a valid id in the specified dictionary. - * @param sidePixels size of the image in pixels - * @param img output image with the marker - * @param borderBits width of the marker border. - * - * This function returns a marker image in its canonical form (i.e. ready to be printed) - */ -CV_EXPORTS_W void generateImageMarker(const Dictionary &dictionary, int id, int sidePixels, OutputArray img, - int borderBits = 1); - -//! @} - -} -} - -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html +#ifndef OPENCV_OBJDETECT_ARUCO_DETECTOR_HPP +#define OPENCV_OBJDETECT_ARUCO_DETECTOR_HPP + +#include +#include + +namespace cv { +namespace aruco { + +//! @addtogroup objdetect_aruco +//! @{ + +enum CornerRefineMethod{ + CORNER_REFINE_NONE, ///< Tag and corners detection based on the ArUco approach + CORNER_REFINE_SUBPIX, ///< ArUco approach and refine the corners locations using corner subpixel accuracy + CORNER_REFINE_CONTOUR, ///< ArUco approach and refine the corners locations using the contour-points line fitting + CORNER_REFINE_APRILTAG, ///< Tag and corners detection based on the AprilTag 2 approach @cite wang2016iros +}; + +/** @brief struct DetectorParameters is used by ArucoDetector + */ +struct CV_EXPORTS_W_SIMPLE DetectorParameters { + CV_WRAP DetectorParameters() { + adaptiveThreshWinSizeMin = 3; + adaptiveThreshWinSizeMax = 23; + adaptiveThreshWinSizeStep = 10; + adaptiveThreshConstant = 7; + minMarkerPerimeterRate = 0.03; + maxMarkerPerimeterRate = 4.; + polygonalApproxAccuracyRate = 0.03; + minCornerDistanceRate = 0.05; + minDistanceToBorder = 3; + minMarkerDistanceRate = 0.125; + cornerRefinementMethod = (int)CORNER_REFINE_NONE; + cornerRefinementWinSize = 5; + relativeCornerRefinmentWinSize = 0.3f; + cornerRefinementMaxIterations = 30; + cornerRefinementMinAccuracy = 0.1; + markerBorderBits = 1; + perspectiveRemovePixelPerCell = 4; + perspectiveRemoveIgnoredMarginPerCell = 0.13; + maxErroneousBitsInBorderRate = 0.35; + minOtsuStdDev = 5.0; + errorCorrectionRate = 0.6; + aprilTagQuadDecimate = 0.0; + aprilTagQuadSigma = 0.0; + aprilTagMinClusterPixels = 5; + aprilTagMaxNmaxima = 10; + aprilTagCriticalRad = (float)(10* CV_PI /180); + aprilTagMaxLineFitMse = 10.0; + aprilTagMinWhiteBlackDiff = 5; + aprilTagDeglitch = 0; + detectInvertedMarker = false; + useAruco3Detection = false; + minSideLengthCanonicalImg = 32; + minMarkerLengthRatioOriginalImg = 0.0; + } + + /** @brief Read a new set of DetectorParameters from FileNode (use FileStorage.root()). + */ + CV_WRAP bool readDetectorParameters(const FileNode& fn); + + /** @brief Write a set of DetectorParameters to FileStorage + */ + CV_WRAP bool writeDetectorParameters(FileStorage& fs, const String& name = String()); + + /// minimum window size for adaptive thresholding before finding contours (default 3). + CV_PROP_RW int adaptiveThreshWinSizeMin; + + /// maximum window size for adaptive thresholding before finding contours (default 23). + CV_PROP_RW int adaptiveThreshWinSizeMax; + + /// increments from adaptiveThreshWinSizeMin to adaptiveThreshWinSizeMax during the thresholding (default 10). + CV_PROP_RW int adaptiveThreshWinSizeStep; + + /// constant for adaptive thresholding before finding contours (default 7) + CV_PROP_RW double adaptiveThreshConstant; + + /** @brief determine minimum perimeter for marker contour to be detected. + * + * This is defined as a rate respect to the maximum dimension of the input image (default 0.03). + */ + CV_PROP_RW double minMarkerPerimeterRate; + + /** @brief determine maximum perimeter for marker contour to be detected. + * + * This is defined as a rate respect to the maximum dimension of the input image (default 4.0). + */ + CV_PROP_RW double maxMarkerPerimeterRate; + + /// minimum accuracy during the polygonal approximation process to determine which contours are squares. (default 0.03) + CV_PROP_RW double polygonalApproxAccuracyRate; + + /// minimum distance between corners for detected markers relative to its perimeter (default 0.05) + CV_PROP_RW double minCornerDistanceRate; + + /// minimum distance of any corner to the image border for detected markers (in pixels) (default 3) + CV_PROP_RW int minDistanceToBorder; + + /** @brief minimum average distance between the corners of the two markers to be grouped (default 0.125). + * + * The rate is relative to the smaller perimeter of the two markers. + * Two markers are grouped if average distance between the corners of the two markers is less than + * min(MarkerPerimeter1, MarkerPerimeter2)*minMarkerDistanceRate. + * + * default value is 0.125 because 0.125*MarkerPerimeter = (MarkerPerimeter / 4) * 0.5 = half the side of the marker. + * + * @note default value was changed from 0.05 after 4.8.1 release, because the filtering algorithm has been changed. + * Now a few candidates from the same group can be added to the list of candidates if they are far from each other. + * @sa minGroupDistance. + */ + CV_PROP_RW double minMarkerDistanceRate; + + /** @brief minimum average distance between the corners of the two markers in group to add them to the list of candidates + * + * The average distance between the corners of the two markers is calculated relative to its module size (default 0.21). + */ + CV_PROP_RW float minGroupDistance = 0.21f; + + /** @brief default value CORNER_REFINE_NONE */ + CV_PROP_RW int cornerRefinementMethod; + + /** @brief maximum window size for the corner refinement process (in pixels) (default 5). + * + * The window size may decrease if the ArUco marker is too small, check relativeCornerRefinmentWinSize. + * The final window size is calculated as: + * min(cornerRefinementWinSize, averageArucoModuleSize*relativeCornerRefinmentWinSize), + * where averageArucoModuleSize is average module size of ArUco marker in pixels. + * (ArUco marker is composed of black and white modules) + */ + CV_PROP_RW int cornerRefinementWinSize; + + /** @brief Dynamic window size for corner refinement relative to Aruco module size (default 0.3). + * + * The final window size is calculated as: + * min(cornerRefinementWinSize, averageArucoModuleSize*relativeCornerRefinmentWinSize), + * where averageArucoModuleSize is average module size of ArUco marker in pixels. + * (ArUco marker is composed of black and white modules) + * In the case of markers located far from each other, it may be useful to increase the value of the parameter to 0.4-0.5. + * In the case of markers located close to each other, it may be useful to decrease the parameter value to 0.1-0.2. + */ + CV_PROP_RW float relativeCornerRefinmentWinSize; + + /// maximum number of iterations for stop criteria of the corner refinement process (default 30). + CV_PROP_RW int cornerRefinementMaxIterations; + + /// minimum error for the stop cristeria of the corner refinement process (default: 0.1) + CV_PROP_RW double cornerRefinementMinAccuracy; + + /// number of bits of the marker border, i.e. marker border width (default 1). + CV_PROP_RW int markerBorderBits; + + /// number of bits (per dimension) for each cell of the marker when removing the perspective (default 4). + CV_PROP_RW int perspectiveRemovePixelPerCell; + + /** @brief width of the margin of pixels on each cell not considered for the determination of the cell bit. + * + * Represents the rate respect to the total size of the cell, i.e. perspectiveRemovePixelPerCell (default 0.13) + */ + CV_PROP_RW double perspectiveRemoveIgnoredMarginPerCell; + + /** @brief maximum number of accepted erroneous bits in the border (i.e. number of allowed white bits in the border). + * + * Represented as a rate respect to the total number of bits per marker (default 0.35). + */ + CV_PROP_RW double maxErroneousBitsInBorderRate; + + /** @brief minimun standard deviation in pixels values during the decodification step to apply Otsu + * thresholding (otherwise, all the bits are set to 0 or 1 depending on mean higher than 128 or not) (default 5.0) + */ + CV_PROP_RW double minOtsuStdDev; + + /// error correction rate respect to the maximun error correction capability for each dictionary (default 0.6). + CV_PROP_RW double errorCorrectionRate; + + /** @brief April :: User-configurable parameters. + * + * Detection of quads can be done on a lower-resolution image, improving speed at a cost of + * pose accuracy and a slight decrease in detection rate. Decoding the binary payload is still + */ + CV_PROP_RW float aprilTagQuadDecimate; + + /// what Gaussian blur should be applied to the segmented image (used for quad detection?) + CV_PROP_RW float aprilTagQuadSigma; + + // April :: Internal variables + /// reject quads containing too few pixels (default 5). + CV_PROP_RW int aprilTagMinClusterPixels; + + /// how many corner candidates to consider when segmenting a group of pixels into a quad (default 10). + CV_PROP_RW int aprilTagMaxNmaxima; + + /** @brief reject quads where pairs of edges have angles that are close to straight or close to 180 degrees. + * + * Zero means that no quads are rejected. (In radians) (default 10*PI/180) + */ + CV_PROP_RW float aprilTagCriticalRad; + + /// when fitting lines to the contours, what is the maximum mean squared error + CV_PROP_RW float aprilTagMaxLineFitMse; + + /** @brief add an extra check that the white model must be (overall) brighter than the black model. + * + * When we build our model of black & white pixels, we add an extra check that the white model must be (overall) + * brighter than the black model. How much brighter? (in pixel values, [0,255]), (default 5) + */ + CV_PROP_RW int aprilTagMinWhiteBlackDiff; + + /// should the thresholded image be deglitched? Only useful for very noisy images (default 0). + CV_PROP_RW int aprilTagDeglitch; + + /** @brief to check if there is a white marker. + * + * In order to generate a "white" marker just invert a normal marker by using a tilde, ~markerImage. (default false) + */ + CV_PROP_RW bool detectInvertedMarker; + + /** @brief enable the new and faster Aruco detection strategy. + * + * Proposed in the paper: + * Romero-Ramirez et al: Speeded up detection of squared fiducial markers (2018) + * https://www.researchgate.net/publication/325787310_Speeded_Up_Detection_of_Squared_Fiducial_Markers + */ + CV_PROP_RW bool useAruco3Detection; + + /// minimum side length of a marker in the canonical image. Latter is the binarized image in which contours are searched. + CV_PROP_RW int minSideLengthCanonicalImg; + + /// range [0,1], eq (2) from paper. The parameter tau_i has a direct influence on the processing speed. + CV_PROP_RW float minMarkerLengthRatioOriginalImg; +}; + +/** @brief struct RefineParameters is used by ArucoDetector + */ +struct CV_EXPORTS_W_SIMPLE RefineParameters { + CV_WRAP RefineParameters(float minRepDistance = 10.f, float errorCorrectionRate = 3.f, bool checkAllOrders = true); + + + /** @brief Read a new set of RefineParameters from FileNode (use FileStorage.root()). + */ + CV_WRAP bool readRefineParameters(const FileNode& fn); + + /** @brief Write a set of RefineParameters to FileStorage + */ + CV_WRAP bool writeRefineParameters(FileStorage& fs, const String& name = String()); + + /** @brief minRepDistance minimum distance between the corners of the rejected candidate and the reprojected marker + in order to consider it as a correspondence. + */ + CV_PROP_RW float minRepDistance; + + /** @brief errorCorrectionRate rate of allowed erroneous bits respect to the error correction capability of the used dictionary. + * + * -1 ignores the error correction step. + */ + CV_PROP_RW float errorCorrectionRate; + + /** @brief checkAllOrders consider the four posible corner orders in the rejectedCorners array. + * + * If it set to false, only the provided corner order is considered (default true). + */ + CV_PROP_RW bool checkAllOrders; +}; + +/** @brief The main functionality of ArucoDetector class is detection of markers in an image with detectMarkers() method. + * + * After detecting some markers in the image, you can try to find undetected markers from this dictionary with + * refineDetectedMarkers() method. + * + * @see DetectorParameters, RefineParameters + */ +class CV_EXPORTS_W ArucoDetector : public Algorithm +{ +public: + /** @brief Basic ArucoDetector constructor + * + * @param dictionary indicates the type of markers that will be searched + * @param detectorParams marker detection parameters + * @param refineParams marker refine detection parameters + */ + CV_WRAP ArucoDetector(const Dictionary &dictionary = getPredefinedDictionary(cv::aruco::DICT_4X4_50), + const DetectorParameters &detectorParams = DetectorParameters(), + const RefineParameters& refineParams = RefineParameters()); + + /** @brief Basic marker detection + * + * @param image input image + * @param corners vector of detected marker corners. For each marker, its four corners + * are provided, (e.g std::vector > ). For N detected markers, + * the dimensions of this array is Nx4. The order of the corners is clockwise. + * @param ids vector of identifiers of the detected markers. The identifier is of type int + * (e.g. std::vector). For N detected markers, the size of ids is also N. + * The identifiers have the same order than the markers in the imgPoints array. + * @param rejectedImgPoints contains the imgPoints of those squares whose inner code has not a + * correct codification. Useful for debugging purposes. + * + * Performs marker detection in the input image. Only markers included in the specific dictionary + * are searched. For each detected marker, it returns the 2D position of its corner in the image + * and its corresponding identifier. + * Note that this function does not perform pose estimation. + * @note The function does not correct lens distortion or takes it into account. It's recommended to undistort + * input image with corresponding camera model, if camera parameters are known + * @sa undistort, estimatePoseSingleMarkers, estimatePoseBoard + */ + CV_WRAP void detectMarkers(InputArray image, OutputArrayOfArrays corners, OutputArray ids, + OutputArrayOfArrays rejectedImgPoints = noArray()) const; + + /** @brief Refine not detected markers based on the already detected and the board layout + * + * @param image input image + * @param board layout of markers in the board. + * @param detectedCorners vector of already detected marker corners. + * @param detectedIds vector of already detected marker identifiers. + * @param rejectedCorners vector of rejected candidates during the marker detection process. + * @param cameraMatrix optional input 3x3 floating-point camera matrix + * \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ + * @param distCoeffs optional vector of distortion coefficients + * \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6],[s_1, s_2, s_3, s_4]])\f$ of 4, 5, 8 or 12 elements + * @param recoveredIdxs Optional array to returns the indexes of the recovered candidates in the + * original rejectedCorners array. + * + * This function tries to find markers that were not detected in the basic detecMarkers function. + * First, based on the current detected marker and the board layout, the function interpolates + * the position of the missing markers. Then it tries to find correspondence between the reprojected + * markers and the rejected candidates based on the minRepDistance and errorCorrectionRate parameters. + * If camera parameters and distortion coefficients are provided, missing markers are reprojected + * using projectPoint function. If not, missing marker projections are interpolated using global + * homography, and all the marker corners in the board must have the same Z coordinate. + */ + CV_WRAP void refineDetectedMarkers(InputArray image, const Board &board, + InputOutputArrayOfArrays detectedCorners, + InputOutputArray detectedIds, InputOutputArrayOfArrays rejectedCorners, + InputArray cameraMatrix = noArray(), InputArray distCoeffs = noArray(), + OutputArray recoveredIdxs = noArray()) const; + + CV_WRAP const Dictionary& getDictionary() const; + CV_WRAP void setDictionary(const Dictionary& dictionary); + + CV_WRAP const DetectorParameters& getDetectorParameters() const; + CV_WRAP void setDetectorParameters(const DetectorParameters& detectorParameters); + + CV_WRAP const RefineParameters& getRefineParameters() const; + CV_WRAP void setRefineParameters(const RefineParameters& refineParameters); + + /** @brief Stores algorithm parameters in a file storage + */ + virtual void write(FileStorage& fs) const override; + + /** @brief simplified API for language bindings + */ + CV_WRAP inline void write(FileStorage& fs, const String& name) { Algorithm::write(fs, name); } + + /** @brief Reads algorithm parameters from a file storage + */ + CV_WRAP virtual void read(const FileNode& fn) override; +protected: + struct ArucoDetectorImpl; + Ptr arucoDetectorImpl; +}; + +/** @brief Draw detected markers in image + * + * @param image input/output image. It must have 1 or 3 channels. The number of channels is not altered. + * @param corners positions of marker corners on input image. + * (e.g std::vector > ). For N detected markers, the dimensions of + * this array should be Nx4. The order of the corners should be clockwise. + * @param ids vector of identifiers for markers in markersCorners . + * Optional, if not provided, ids are not painted. + * @param borderColor color of marker borders. Rest of colors (text color and first corner color) + * are calculated based on this one to improve visualization. + * + * Given an array of detected marker corners and its corresponding ids, this functions draws + * the markers in the image. The marker borders are painted and the markers identifiers if provided. + * Useful for debugging purposes. + */ +CV_EXPORTS_W void drawDetectedMarkers(InputOutputArray image, InputArrayOfArrays corners, + InputArray ids = noArray(), Scalar borderColor = Scalar(0, 255, 0)); + +/** @brief Generate a canonical marker image + * + * @param dictionary dictionary of markers indicating the type of markers + * @param id identifier of the marker that will be returned. It has to be a valid id in the specified dictionary. + * @param sidePixels size of the image in pixels + * @param img output image with the marker + * @param borderBits width of the marker border. + * + * This function returns a marker image in its canonical form (i.e. ready to be printed) + */ +CV_EXPORTS_W void generateImageMarker(const Dictionary &dictionary, int id, int sidePixels, OutputArray img, + int borderBits = 1); + +//! @} + +} +} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/objdetect/aruco_dictionary.hpp b/3rdParty/opencv-4.11.0/opencv2/objdetect/aruco_dictionary.hpp index bc7b934b2a..e6d0fb5f21 100644 --- a/3rdParty/opencv-4.11.0/opencv2/objdetect/aruco_dictionary.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/objdetect/aruco_dictionary.hpp @@ -1,155 +1,155 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html -#ifndef OPENCV_OBJDETECT_DICTIONARY_HPP -#define OPENCV_OBJDETECT_DICTIONARY_HPP - -#include - -namespace cv { -namespace aruco { - -//! @addtogroup objdetect_aruco -//! @{ - - -/** @brief Dictionary is a set of unique ArUco markers of the same size - * - * `bytesList` storing as 2-dimensions Mat with 4-th channels (CV_8UC4 type was used) and contains the marker codewords where: - * - bytesList.rows is the dictionary size - * - each marker is encoded using `nbytes = ceil(markerSize*markerSize/8.)` bytes - * - each row contains all 4 rotations of the marker, so its length is `4*nbytes` - * - the byte order in the bytesList[i] row: - * `//bytes without rotation/bytes with rotation 1/bytes with rotation 2/bytes with rotation 3//` - * So `bytesList.ptr(i)[k*nbytes + j]` is the j-th byte of i-th marker, in its k-th rotation. - * @note Python bindings generate matrix with shape of bytesList `dictionary_size x nbytes x 4`, - * but it should be indexed like C++ version. Python example for j-th byte of i-th marker, in its k-th rotation: - * `aruco_dict.bytesList[id].ravel()[k*nbytes + j]` - */ -class CV_EXPORTS_W_SIMPLE Dictionary { - - public: - CV_PROP_RW Mat bytesList; ///< marker code information. See class description for more details - CV_PROP_RW int markerSize; ///< number of bits per dimension - CV_PROP_RW int maxCorrectionBits; ///< maximum number of bits that can be corrected - - CV_WRAP Dictionary(); - - /** @brief Basic ArUco dictionary constructor - * - * @param bytesList bits for all ArUco markers in dictionary see memory layout in the class description - * @param _markerSize ArUco marker size in units - * @param maxcorr maximum number of bits that can be corrected - */ - CV_WRAP Dictionary(const Mat &bytesList, int _markerSize, int maxcorr = 0); - - /** @brief Read a new dictionary from FileNode. - * - * Dictionary example in YAML format:\n - * nmarkers: 35\n - * markersize: 6\n - * maxCorrectionBits: 5\n - * marker_0: "101011111011111001001001101100000000"\n - * ...\n - * marker_34: "011111010000111011111110110101100101" - */ - CV_WRAP bool readDictionary(const cv::FileNode& fn); - - /** @brief Write a dictionary to FileStorage, format is the same as in readDictionary(). - */ - CV_WRAP void writeDictionary(FileStorage& fs, const String& name = String()); - - /** @brief Given a matrix of bits. Returns whether if marker is identified or not. - * - * Returns reference to the marker id in the dictionary (if any) and its rotation. - */ - CV_WRAP bool identify(const Mat &onlyBits, CV_OUT int &idx, CV_OUT int &rotation, double maxCorrectionRate) const; - - /** @brief Returns Hamming distance of the input bits to the specific id. - * - * If `allRotations` flag is set, the four posible marker rotations are considered - */ - CV_WRAP int getDistanceToId(InputArray bits, int id, bool allRotations = true) const; - - - /** @brief Generate a canonical marker image - */ - CV_WRAP void generateImageMarker(int id, int sidePixels, OutputArray _img, int borderBits = 1) const; - - - /** @brief Transform matrix of bits to list of bytes with 4 marker rotations - */ - CV_WRAP static Mat getByteListFromBits(const Mat &bits); - - - /** @brief Transform list of bytes to matrix of bits - */ - CV_WRAP static Mat getBitsFromByteList(const Mat &byteList, int markerSize); -}; - - - - -/** @brief Predefined markers dictionaries/sets - * - * Each dictionary indicates the number of bits and the number of markers contained - * - DICT_ARUCO_ORIGINAL: standard ArUco Library Markers. 1024 markers, 5x5 bits, 0 minimum - distance - */ -enum PredefinedDictionaryType { - DICT_4X4_50 = 0, ///< 4x4 bits, minimum hamming distance between any two codes = 4, 50 codes - DICT_4X4_100, ///< 4x4 bits, minimum hamming distance between any two codes = 3, 100 codes - DICT_4X4_250, ///< 4x4 bits, minimum hamming distance between any two codes = 3, 250 codes - DICT_4X4_1000, ///< 4x4 bits, minimum hamming distance between any two codes = 2, 1000 codes - DICT_5X5_50, ///< 5x5 bits, minimum hamming distance between any two codes = 8, 50 codes - DICT_5X5_100, ///< 5x5 bits, minimum hamming distance between any two codes = 7, 100 codes - DICT_5X5_250, ///< 5x5 bits, minimum hamming distance between any two codes = 6, 250 codes - DICT_5X5_1000, ///< 5x5 bits, minimum hamming distance between any two codes = 5, 1000 codes - DICT_6X6_50, ///< 6x6 bits, minimum hamming distance between any two codes = 13, 50 codes - DICT_6X6_100, ///< 6x6 bits, minimum hamming distance between any two codes = 12, 100 codes - DICT_6X6_250, ///< 6x6 bits, minimum hamming distance between any two codes = 11, 250 codes - DICT_6X6_1000, ///< 6x6 bits, minimum hamming distance between any two codes = 9, 1000 codes - DICT_7X7_50, ///< 7x7 bits, minimum hamming distance between any two codes = 19, 50 codes - DICT_7X7_100, ///< 7x7 bits, minimum hamming distance between any two codes = 18, 100 codes - DICT_7X7_250, ///< 7x7 bits, minimum hamming distance between any two codes = 17, 250 codes - DICT_7X7_1000, ///< 7x7 bits, minimum hamming distance between any two codes = 14, 1000 codes - DICT_ARUCO_ORIGINAL, ///< 6x6 bits, minimum hamming distance between any two codes = 3, 1024 codes - DICT_APRILTAG_16h5, ///< 4x4 bits, minimum hamming distance between any two codes = 5, 30 codes - DICT_APRILTAG_25h9, ///< 5x5 bits, minimum hamming distance between any two codes = 9, 35 codes - DICT_APRILTAG_36h10, ///< 6x6 bits, minimum hamming distance between any two codes = 10, 2320 codes - DICT_APRILTAG_36h11, ///< 6x6 bits, minimum hamming distance between any two codes = 11, 587 codes - DICT_ARUCO_MIP_36h12 ///< 6x6 bits, minimum hamming distance between any two codes = 12, 250 codes -}; - - -/** @brief Returns one of the predefined dictionaries defined in PredefinedDictionaryType - */ -CV_EXPORTS Dictionary getPredefinedDictionary(PredefinedDictionaryType name); - - -/** @brief Returns one of the predefined dictionaries referenced by DICT_*. - */ -CV_EXPORTS_W Dictionary getPredefinedDictionary(int dict); - -/** @brief Extend base dictionary by new nMarkers - * - * @param nMarkers number of markers in the dictionary - * @param markerSize number of bits per dimension of each markers - * @param baseDictionary Include the markers in this dictionary at the beginning (optional) - * @param randomSeed a user supplied seed for theRNG() - * - * This function creates a new dictionary composed by nMarkers markers and each markers composed - * by markerSize x markerSize bits. If baseDictionary is provided, its markers are directly - * included and the rest are generated based on them. If the size of baseDictionary is higher - * than nMarkers, only the first nMarkers in baseDictionary are taken and no new marker is added. - */ -CV_EXPORTS_W Dictionary extendDictionary(int nMarkers, int markerSize, const Dictionary &baseDictionary = Dictionary(), - int randomSeed=0); - - - -//! @} -} -} - -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html +#ifndef OPENCV_OBJDETECT_DICTIONARY_HPP +#define OPENCV_OBJDETECT_DICTIONARY_HPP + +#include + +namespace cv { +namespace aruco { + +//! @addtogroup objdetect_aruco +//! @{ + + +/** @brief Dictionary is a set of unique ArUco markers of the same size + * + * `bytesList` storing as 2-dimensions Mat with 4-th channels (CV_8UC4 type was used) and contains the marker codewords where: + * - bytesList.rows is the dictionary size + * - each marker is encoded using `nbytes = ceil(markerSize*markerSize/8.)` bytes + * - each row contains all 4 rotations of the marker, so its length is `4*nbytes` + * - the byte order in the bytesList[i] row: + * `//bytes without rotation/bytes with rotation 1/bytes with rotation 2/bytes with rotation 3//` + * So `bytesList.ptr(i)[k*nbytes + j]` is the j-th byte of i-th marker, in its k-th rotation. + * @note Python bindings generate matrix with shape of bytesList `dictionary_size x nbytes x 4`, + * but it should be indexed like C++ version. Python example for j-th byte of i-th marker, in its k-th rotation: + * `aruco_dict.bytesList[id].ravel()[k*nbytes + j]` + */ +class CV_EXPORTS_W_SIMPLE Dictionary { + + public: + CV_PROP_RW Mat bytesList; ///< marker code information. See class description for more details + CV_PROP_RW int markerSize; ///< number of bits per dimension + CV_PROP_RW int maxCorrectionBits; ///< maximum number of bits that can be corrected + + CV_WRAP Dictionary(); + + /** @brief Basic ArUco dictionary constructor + * + * @param bytesList bits for all ArUco markers in dictionary see memory layout in the class description + * @param _markerSize ArUco marker size in units + * @param maxcorr maximum number of bits that can be corrected + */ + CV_WRAP Dictionary(const Mat &bytesList, int _markerSize, int maxcorr = 0); + + /** @brief Read a new dictionary from FileNode. + * + * Dictionary example in YAML format:\n + * nmarkers: 35\n + * markersize: 6\n + * maxCorrectionBits: 5\n + * marker_0: "101011111011111001001001101100000000"\n + * ...\n + * marker_34: "011111010000111011111110110101100101" + */ + CV_WRAP bool readDictionary(const cv::FileNode& fn); + + /** @brief Write a dictionary to FileStorage, format is the same as in readDictionary(). + */ + CV_WRAP void writeDictionary(FileStorage& fs, const String& name = String()); + + /** @brief Given a matrix of bits. Returns whether if marker is identified or not. + * + * Returns reference to the marker id in the dictionary (if any) and its rotation. + */ + CV_WRAP bool identify(const Mat &onlyBits, CV_OUT int &idx, CV_OUT int &rotation, double maxCorrectionRate) const; + + /** @brief Returns Hamming distance of the input bits to the specific id. + * + * If `allRotations` flag is set, the four posible marker rotations are considered + */ + CV_WRAP int getDistanceToId(InputArray bits, int id, bool allRotations = true) const; + + + /** @brief Generate a canonical marker image + */ + CV_WRAP void generateImageMarker(int id, int sidePixels, OutputArray _img, int borderBits = 1) const; + + + /** @brief Transform matrix of bits to list of bytes with 4 marker rotations + */ + CV_WRAP static Mat getByteListFromBits(const Mat &bits); + + + /** @brief Transform list of bytes to matrix of bits + */ + CV_WRAP static Mat getBitsFromByteList(const Mat &byteList, int markerSize); +}; + + + + +/** @brief Predefined markers dictionaries/sets + * + * Each dictionary indicates the number of bits and the number of markers contained + * - DICT_ARUCO_ORIGINAL: standard ArUco Library Markers. 1024 markers, 5x5 bits, 0 minimum + distance + */ +enum PredefinedDictionaryType { + DICT_4X4_50 = 0, ///< 4x4 bits, minimum hamming distance between any two codes = 4, 50 codes + DICT_4X4_100, ///< 4x4 bits, minimum hamming distance between any two codes = 3, 100 codes + DICT_4X4_250, ///< 4x4 bits, minimum hamming distance between any two codes = 3, 250 codes + DICT_4X4_1000, ///< 4x4 bits, minimum hamming distance between any two codes = 2, 1000 codes + DICT_5X5_50, ///< 5x5 bits, minimum hamming distance between any two codes = 8, 50 codes + DICT_5X5_100, ///< 5x5 bits, minimum hamming distance between any two codes = 7, 100 codes + DICT_5X5_250, ///< 5x5 bits, minimum hamming distance between any two codes = 6, 250 codes + DICT_5X5_1000, ///< 5x5 bits, minimum hamming distance between any two codes = 5, 1000 codes + DICT_6X6_50, ///< 6x6 bits, minimum hamming distance between any two codes = 13, 50 codes + DICT_6X6_100, ///< 6x6 bits, minimum hamming distance between any two codes = 12, 100 codes + DICT_6X6_250, ///< 6x6 bits, minimum hamming distance between any two codes = 11, 250 codes + DICT_6X6_1000, ///< 6x6 bits, minimum hamming distance between any two codes = 9, 1000 codes + DICT_7X7_50, ///< 7x7 bits, minimum hamming distance between any two codes = 19, 50 codes + DICT_7X7_100, ///< 7x7 bits, minimum hamming distance between any two codes = 18, 100 codes + DICT_7X7_250, ///< 7x7 bits, minimum hamming distance between any two codes = 17, 250 codes + DICT_7X7_1000, ///< 7x7 bits, minimum hamming distance between any two codes = 14, 1000 codes + DICT_ARUCO_ORIGINAL, ///< 6x6 bits, minimum hamming distance between any two codes = 3, 1024 codes + DICT_APRILTAG_16h5, ///< 4x4 bits, minimum hamming distance between any two codes = 5, 30 codes + DICT_APRILTAG_25h9, ///< 5x5 bits, minimum hamming distance between any two codes = 9, 35 codes + DICT_APRILTAG_36h10, ///< 6x6 bits, minimum hamming distance between any two codes = 10, 2320 codes + DICT_APRILTAG_36h11, ///< 6x6 bits, minimum hamming distance between any two codes = 11, 587 codes + DICT_ARUCO_MIP_36h12 ///< 6x6 bits, minimum hamming distance between any two codes = 12, 250 codes +}; + + +/** @brief Returns one of the predefined dictionaries defined in PredefinedDictionaryType + */ +CV_EXPORTS Dictionary getPredefinedDictionary(PredefinedDictionaryType name); + + +/** @brief Returns one of the predefined dictionaries referenced by DICT_*. + */ +CV_EXPORTS_W Dictionary getPredefinedDictionary(int dict); + +/** @brief Extend base dictionary by new nMarkers + * + * @param nMarkers number of markers in the dictionary + * @param markerSize number of bits per dimension of each markers + * @param baseDictionary Include the markers in this dictionary at the beginning (optional) + * @param randomSeed a user supplied seed for theRNG() + * + * This function creates a new dictionary composed by nMarkers markers and each markers composed + * by markerSize x markerSize bits. If baseDictionary is provided, its markers are directly + * included and the rest are generated based on them. If the size of baseDictionary is higher + * than nMarkers, only the first nMarkers in baseDictionary are taken and no new marker is added. + */ +CV_EXPORTS_W Dictionary extendDictionary(int nMarkers, int markerSize, const Dictionary &baseDictionary = Dictionary(), + int randomSeed=0); + + + +//! @} +} +} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/objdetect/barcode.hpp b/3rdParty/opencv-4.11.0/opencv2/objdetect/barcode.hpp index c20b67c0b2..e36259f286 100644 --- a/3rdParty/opencv-4.11.0/opencv2/objdetect/barcode.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/objdetect/barcode.hpp @@ -1,111 +1,111 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// Copyright (c) 2020-2021 darkliang wangberlinT Certseeds - -#ifndef OPENCV_OBJDETECT_BARCODE_HPP -#define OPENCV_OBJDETECT_BARCODE_HPP - -#include -#include - -namespace cv { -namespace barcode { - -//! @addtogroup objdetect_barcode -//! @{ - -class CV_EXPORTS_W_SIMPLE BarcodeDetector : public cv::GraphicalCodeDetector -{ -public: - /** @brief Initialize the BarcodeDetector. - */ - CV_WRAP BarcodeDetector(); - /** @brief Initialize the BarcodeDetector. - * - * Parameters allow to load _optional_ Super Resolution DNN model for better quality. - * @param prototxt_path prototxt file path for the super resolution model - * @param model_path model file path for the super resolution model - */ - CV_WRAP BarcodeDetector(CV_WRAP_FILE_PATH const std::string &prototxt_path, CV_WRAP_FILE_PATH const std::string &model_path); - ~BarcodeDetector(); - - /** @brief Decodes barcode in image once it's found by the detect() method. - * - * @param img grayscale or color (BGR) image containing bar code. - * @param points vector of rotated rectangle vertices found by detect() method (or some other algorithm). - * For N detected barcodes, the dimensions of this array should be [N][4]. - * Order of four points in vector is bottomLeft, topLeft, topRight, bottomRight. - * @param decoded_info UTF8-encoded output vector of string or empty vector of string if the codes cannot be decoded. - * @param decoded_type vector strings, specifies the type of these barcodes - * @return true if at least one valid barcode have been found - */ - CV_WRAP bool decodeWithType(InputArray img, - InputArray points, - CV_OUT std::vector &decoded_info, - CV_OUT std::vector &decoded_type) const; - - /** @brief Both detects and decodes barcode - - * @param img grayscale or color (BGR) image containing barcode. - * @param decoded_info UTF8-encoded output vector of string(s) or empty vector of string if the codes cannot be decoded. - * @param decoded_type vector of strings, specifies the type of these barcodes - * @param points optional output vector of vertices of the found barcode rectangle. Will be empty if not found. - * @return true if at least one valid barcode have been found - */ - CV_WRAP bool detectAndDecodeWithType(InputArray img, - CV_OUT std::vector &decoded_info, - CV_OUT std::vector &decoded_type, - OutputArray points = noArray()) const; - - /** @brief Get detector downsampling threshold. - * - * @return detector downsampling threshold - */ - CV_WRAP double getDownsamplingThreshold() const; - - /** @brief Set detector downsampling threshold. - * - * By default, the detect method resizes the input image to this limit if the smallest image size is is greater than the threshold. - * Increasing this value can improve detection accuracy and the number of results at the expense of performance. - * Correlates with detector scales. Setting this to a large value will disable downsampling. - * @param thresh downsampling limit to apply (default 512) - * @see setDetectorScales - */ - CV_WRAP BarcodeDetector& setDownsamplingThreshold(double thresh); - - /** @brief Returns detector box filter sizes. - * - * @param sizes output parameter for returning the sizes. - */ - CV_WRAP void getDetectorScales(CV_OUT std::vector& sizes) const; - - /** @brief Set detector box filter sizes. - * - * Adjusts the value and the number of box filters used in the detect step. - * The filter sizes directly correlate with the expected line widths for a barcode. Corresponds to expected barcode distance. - * If the downsampling limit is increased, filter sizes need to be adjusted in an inversely proportional way. - * @param sizes box filter sizes, relative to minimum dimension of the image (default [0.01, 0.03, 0.06, 0.08]) - */ - CV_WRAP BarcodeDetector& setDetectorScales(const std::vector& sizes); - - /** @brief Get detector gradient magnitude threshold. - * - * @return detector gradient magnitude threshold. - */ - CV_WRAP double getGradientThreshold() const; - - /** @brief Set detector gradient magnitude threshold. - * - * Sets the coherence threshold for detected bounding boxes. - * Increasing this value will generate a closer fitted bounding box width and can reduce false-positives. - * Values between 16 and 1024 generally work, while too high of a value will remove valid detections. - * @param thresh gradient magnitude threshold (default 64). - */ - CV_WRAP BarcodeDetector& setGradientThreshold(double thresh); -}; -//! @} - -}} // cv::barcode:: - -#endif // OPENCV_OBJDETECT_BARCODE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// Copyright (c) 2020-2021 darkliang wangberlinT Certseeds + +#ifndef OPENCV_OBJDETECT_BARCODE_HPP +#define OPENCV_OBJDETECT_BARCODE_HPP + +#include +#include + +namespace cv { +namespace barcode { + +//! @addtogroup objdetect_barcode +//! @{ + +class CV_EXPORTS_W_SIMPLE BarcodeDetector : public cv::GraphicalCodeDetector +{ +public: + /** @brief Initialize the BarcodeDetector. + */ + CV_WRAP BarcodeDetector(); + /** @brief Initialize the BarcodeDetector. + * + * Parameters allow to load _optional_ Super Resolution DNN model for better quality. + * @param prototxt_path prototxt file path for the super resolution model + * @param model_path model file path for the super resolution model + */ + CV_WRAP BarcodeDetector(CV_WRAP_FILE_PATH const std::string &prototxt_path, CV_WRAP_FILE_PATH const std::string &model_path); + ~BarcodeDetector(); + + /** @brief Decodes barcode in image once it's found by the detect() method. + * + * @param img grayscale or color (BGR) image containing bar code. + * @param points vector of rotated rectangle vertices found by detect() method (or some other algorithm). + * For N detected barcodes, the dimensions of this array should be [N][4]. + * Order of four points in vector is bottomLeft, topLeft, topRight, bottomRight. + * @param decoded_info UTF8-encoded output vector of string or empty vector of string if the codes cannot be decoded. + * @param decoded_type vector strings, specifies the type of these barcodes + * @return true if at least one valid barcode have been found + */ + CV_WRAP bool decodeWithType(InputArray img, + InputArray points, + CV_OUT std::vector &decoded_info, + CV_OUT std::vector &decoded_type) const; + + /** @brief Both detects and decodes barcode + + * @param img grayscale or color (BGR) image containing barcode. + * @param decoded_info UTF8-encoded output vector of string(s) or empty vector of string if the codes cannot be decoded. + * @param decoded_type vector of strings, specifies the type of these barcodes + * @param points optional output vector of vertices of the found barcode rectangle. Will be empty if not found. + * @return true if at least one valid barcode have been found + */ + CV_WRAP bool detectAndDecodeWithType(InputArray img, + CV_OUT std::vector &decoded_info, + CV_OUT std::vector &decoded_type, + OutputArray points = noArray()) const; + + /** @brief Get detector downsampling threshold. + * + * @return detector downsampling threshold + */ + CV_WRAP double getDownsamplingThreshold() const; + + /** @brief Set detector downsampling threshold. + * + * By default, the detect method resizes the input image to this limit if the smallest image size is is greater than the threshold. + * Increasing this value can improve detection accuracy and the number of results at the expense of performance. + * Correlates with detector scales. Setting this to a large value will disable downsampling. + * @param thresh downsampling limit to apply (default 512) + * @see setDetectorScales + */ + CV_WRAP BarcodeDetector& setDownsamplingThreshold(double thresh); + + /** @brief Returns detector box filter sizes. + * + * @param sizes output parameter for returning the sizes. + */ + CV_WRAP void getDetectorScales(CV_OUT std::vector& sizes) const; + + /** @brief Set detector box filter sizes. + * + * Adjusts the value and the number of box filters used in the detect step. + * The filter sizes directly correlate with the expected line widths for a barcode. Corresponds to expected barcode distance. + * If the downsampling limit is increased, filter sizes need to be adjusted in an inversely proportional way. + * @param sizes box filter sizes, relative to minimum dimension of the image (default [0.01, 0.03, 0.06, 0.08]) + */ + CV_WRAP BarcodeDetector& setDetectorScales(const std::vector& sizes); + + /** @brief Get detector gradient magnitude threshold. + * + * @return detector gradient magnitude threshold. + */ + CV_WRAP double getGradientThreshold() const; + + /** @brief Set detector gradient magnitude threshold. + * + * Sets the coherence threshold for detected bounding boxes. + * Increasing this value will generate a closer fitted bounding box width and can reduce false-positives. + * Values between 16 and 1024 generally work, while too high of a value will remove valid detections. + * @param thresh gradient magnitude threshold (default 64). + */ + CV_WRAP BarcodeDetector& setGradientThreshold(double thresh); +}; +//! @} + +}} // cv::barcode:: + +#endif // OPENCV_OBJDETECT_BARCODE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/objdetect/charuco_detector.hpp b/3rdParty/opencv-4.11.0/opencv2/objdetect/charuco_detector.hpp index e10cb3f025..5adfe2931c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/objdetect/charuco_detector.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/objdetect/charuco_detector.hpp @@ -1,157 +1,157 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html -#ifndef OPENCV_OBJDETECT_CHARUCO_DETECTOR_HPP -#define OPENCV_OBJDETECT_CHARUCO_DETECTOR_HPP - -#include "opencv2/objdetect/aruco_detector.hpp" - -namespace cv { -namespace aruco { - -//! @addtogroup objdetect_aruco -//! @{ - -struct CV_EXPORTS_W_SIMPLE CharucoParameters { - CV_WRAP CharucoParameters() { - minMarkers = 2; - tryRefineMarkers = false; - } - /// cameraMatrix optional 3x3 floating-point camera matrix - CV_PROP_RW Mat cameraMatrix; - - /// distCoeffs optional vector of distortion coefficients - CV_PROP_RW Mat distCoeffs; - - /// minMarkers number of adjacent markers that must be detected to return a charuco corner, default = 2 - CV_PROP_RW int minMarkers; - - /// try to use refine board, default false - CV_PROP_RW bool tryRefineMarkers; -}; - -class CV_EXPORTS_W CharucoDetector : public Algorithm { -public: - /** @brief Basic CharucoDetector constructor - * - * @param board ChAruco board - * @param charucoParams charuco detection parameters - * @param detectorParams marker detection parameters - * @param refineParams marker refine detection parameters - */ - CV_WRAP CharucoDetector(const CharucoBoard& board, - const CharucoParameters& charucoParams = CharucoParameters(), - const DetectorParameters &detectorParams = DetectorParameters(), - const RefineParameters& refineParams = RefineParameters()); - - CV_WRAP const CharucoBoard& getBoard() const; - CV_WRAP void setBoard(const CharucoBoard& board); - - CV_WRAP const CharucoParameters& getCharucoParameters() const; - CV_WRAP void setCharucoParameters(CharucoParameters& charucoParameters); - - CV_WRAP const DetectorParameters& getDetectorParameters() const; - CV_WRAP void setDetectorParameters(const DetectorParameters& detectorParameters); - - CV_WRAP const RefineParameters& getRefineParameters() const; - CV_WRAP void setRefineParameters(const RefineParameters& refineParameters); - - /** - * @brief detect aruco markers and interpolate position of ChArUco board corners - * @param image input image necesary for corner refinement. Note that markers are not detected and - * should be sent in corners and ids parameters. - * @param charucoCorners interpolated chessboard corners. - * @param charucoIds interpolated chessboard corners identifiers. - * @param markerCorners vector of already detected markers corners. For each marker, its four - * corners are provided, (e.g std::vector > ). For N detected markers, the - * dimensions of this array should be Nx4. The order of the corners should be clockwise. - * If markerCorners and markerCorners are empty, the function detect aruco markers and ids. - * @param markerIds list of identifiers for each marker in corners. - * If markerCorners and markerCorners are empty, the function detect aruco markers and ids. - * - * This function receives the detected markers and returns the 2D position of the chessboard corners - * from a ChArUco board using the detected Aruco markers. - * - * If markerCorners and markerCorners are empty, the detectMarkers() will run and detect aruco markers and ids. - * - * If camera parameters are provided, the process is based in an approximated pose estimation, else it is based on local homography. - * Only visible corners are returned. For each corner, its corresponding identifier is also returned in charucoIds. - * @sa findChessboardCorners - * @note After OpenCV 4.6.0, there was an incompatible change in the ChArUco pattern generation algorithm for even row counts. - * Use cv::aruco::CharucoBoard::setLegacyPattern() to ensure compatibility with patterns created using OpenCV versions prior to 4.6.0. - * For more information, see the issue: https://github.com/opencv/opencv/issues/23152 - */ - CV_WRAP void detectBoard(InputArray image, OutputArray charucoCorners, OutputArray charucoIds, - InputOutputArrayOfArrays markerCorners = noArray(), - InputOutputArray markerIds = noArray()) const; - - /** - * @brief Detect ChArUco Diamond markers - * - * @param image input image necessary for corner subpixel. - * @param diamondCorners output list of detected diamond corners (4 corners per diamond). The order - * is the same than in marker corners: top left, top right, bottom right and bottom left. Similar - * format than the corners returned by detectMarkers (e.g std::vector > ). - * @param diamondIds ids of the diamonds in diamondCorners. The id of each diamond is in fact of - * type Vec4i, so each diamond has 4 ids, which are the ids of the aruco markers composing the - * diamond. - * @param markerCorners list of detected marker corners from detectMarkers function. - * If markerCorners and markerCorners are empty, the function detect aruco markers and ids. - * @param markerIds list of marker ids in markerCorners. - * If markerCorners and markerCorners are empty, the function detect aruco markers and ids. - * - * This function detects Diamond markers from the previous detected ArUco markers. The diamonds - * are returned in the diamondCorners and diamondIds parameters. If camera calibration parameters - * are provided, the diamond search is based on reprojection. If not, diamond search is based on - * homography. Homography is faster than reprojection, but less accurate. - */ - CV_WRAP void detectDiamonds(InputArray image, OutputArrayOfArrays diamondCorners, OutputArray diamondIds, - InputOutputArrayOfArrays markerCorners = noArray(), - InputOutputArray markerIds = noArray()) const; -protected: - struct CharucoDetectorImpl; - Ptr charucoDetectorImpl; -}; - -/** - * @brief Draws a set of Charuco corners - * @param image input/output image. It must have 1 or 3 channels. The number of channels is not - * altered. - * @param charucoCorners vector of detected charuco corners - * @param charucoIds list of identifiers for each corner in charucoCorners - * @param cornerColor color of the square surrounding each corner - * - * This function draws a set of detected Charuco corners. If identifiers vector is provided, it also - * draws the id of each corner. - */ -CV_EXPORTS_W void drawDetectedCornersCharuco(InputOutputArray image, InputArray charucoCorners, - InputArray charucoIds = noArray(), Scalar cornerColor = Scalar(255, 0, 0)); - -/** - * @brief Draw a set of detected ChArUco Diamond markers - * - * @param image input/output image. It must have 1 or 3 channels. The number of channels is not - * altered. - * @param diamondCorners positions of diamond corners in the same format returned by - * detectCharucoDiamond(). (e.g std::vector > ). For N detected markers, - * the dimensions of this array should be Nx4. The order of the corners should be clockwise. - * @param diamondIds vector of identifiers for diamonds in diamondCorners, in the same format - * returned by detectCharucoDiamond() (e.g. std::vector). - * Optional, if not provided, ids are not painted. - * @param borderColor color of marker borders. Rest of colors (text color and first corner color) - * are calculated based on this one. - * - * Given an array of detected diamonds, this functions draws them in the image. The marker borders - * are painted and the markers identifiers if provided. - * Useful for debugging purposes. - */ -CV_EXPORTS_W void drawDetectedDiamonds(InputOutputArray image, InputArrayOfArrays diamondCorners, - InputArray diamondIds = noArray(), - Scalar borderColor = Scalar(0, 0, 255)); - -//! @} - -} -} - -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html +#ifndef OPENCV_OBJDETECT_CHARUCO_DETECTOR_HPP +#define OPENCV_OBJDETECT_CHARUCO_DETECTOR_HPP + +#include "opencv2/objdetect/aruco_detector.hpp" + +namespace cv { +namespace aruco { + +//! @addtogroup objdetect_aruco +//! @{ + +struct CV_EXPORTS_W_SIMPLE CharucoParameters { + CV_WRAP CharucoParameters() { + minMarkers = 2; + tryRefineMarkers = false; + } + /// cameraMatrix optional 3x3 floating-point camera matrix + CV_PROP_RW Mat cameraMatrix; + + /// distCoeffs optional vector of distortion coefficients + CV_PROP_RW Mat distCoeffs; + + /// minMarkers number of adjacent markers that must be detected to return a charuco corner, default = 2 + CV_PROP_RW int minMarkers; + + /// try to use refine board, default false + CV_PROP_RW bool tryRefineMarkers; +}; + +class CV_EXPORTS_W CharucoDetector : public Algorithm { +public: + /** @brief Basic CharucoDetector constructor + * + * @param board ChAruco board + * @param charucoParams charuco detection parameters + * @param detectorParams marker detection parameters + * @param refineParams marker refine detection parameters + */ + CV_WRAP CharucoDetector(const CharucoBoard& board, + const CharucoParameters& charucoParams = CharucoParameters(), + const DetectorParameters &detectorParams = DetectorParameters(), + const RefineParameters& refineParams = RefineParameters()); + + CV_WRAP const CharucoBoard& getBoard() const; + CV_WRAP void setBoard(const CharucoBoard& board); + + CV_WRAP const CharucoParameters& getCharucoParameters() const; + CV_WRAP void setCharucoParameters(CharucoParameters& charucoParameters); + + CV_WRAP const DetectorParameters& getDetectorParameters() const; + CV_WRAP void setDetectorParameters(const DetectorParameters& detectorParameters); + + CV_WRAP const RefineParameters& getRefineParameters() const; + CV_WRAP void setRefineParameters(const RefineParameters& refineParameters); + + /** + * @brief detect aruco markers and interpolate position of ChArUco board corners + * @param image input image necesary for corner refinement. Note that markers are not detected and + * should be sent in corners and ids parameters. + * @param charucoCorners interpolated chessboard corners. + * @param charucoIds interpolated chessboard corners identifiers. + * @param markerCorners vector of already detected markers corners. For each marker, its four + * corners are provided, (e.g std::vector > ). For N detected markers, the + * dimensions of this array should be Nx4. The order of the corners should be clockwise. + * If markerCorners and markerCorners are empty, the function detect aruco markers and ids. + * @param markerIds list of identifiers for each marker in corners. + * If markerCorners and markerCorners are empty, the function detect aruco markers and ids. + * + * This function receives the detected markers and returns the 2D position of the chessboard corners + * from a ChArUco board using the detected Aruco markers. + * + * If markerCorners and markerCorners are empty, the detectMarkers() will run and detect aruco markers and ids. + * + * If camera parameters are provided, the process is based in an approximated pose estimation, else it is based on local homography. + * Only visible corners are returned. For each corner, its corresponding identifier is also returned in charucoIds. + * @sa findChessboardCorners + * @note After OpenCV 4.6.0, there was an incompatible change in the ChArUco pattern generation algorithm for even row counts. + * Use cv::aruco::CharucoBoard::setLegacyPattern() to ensure compatibility with patterns created using OpenCV versions prior to 4.6.0. + * For more information, see the issue: https://github.com/opencv/opencv/issues/23152 + */ + CV_WRAP void detectBoard(InputArray image, OutputArray charucoCorners, OutputArray charucoIds, + InputOutputArrayOfArrays markerCorners = noArray(), + InputOutputArray markerIds = noArray()) const; + + /** + * @brief Detect ChArUco Diamond markers + * + * @param image input image necessary for corner subpixel. + * @param diamondCorners output list of detected diamond corners (4 corners per diamond). The order + * is the same than in marker corners: top left, top right, bottom right and bottom left. Similar + * format than the corners returned by detectMarkers (e.g std::vector > ). + * @param diamondIds ids of the diamonds in diamondCorners. The id of each diamond is in fact of + * type Vec4i, so each diamond has 4 ids, which are the ids of the aruco markers composing the + * diamond. + * @param markerCorners list of detected marker corners from detectMarkers function. + * If markerCorners and markerCorners are empty, the function detect aruco markers and ids. + * @param markerIds list of marker ids in markerCorners. + * If markerCorners and markerCorners are empty, the function detect aruco markers and ids. + * + * This function detects Diamond markers from the previous detected ArUco markers. The diamonds + * are returned in the diamondCorners and diamondIds parameters. If camera calibration parameters + * are provided, the diamond search is based on reprojection. If not, diamond search is based on + * homography. Homography is faster than reprojection, but less accurate. + */ + CV_WRAP void detectDiamonds(InputArray image, OutputArrayOfArrays diamondCorners, OutputArray diamondIds, + InputOutputArrayOfArrays markerCorners = noArray(), + InputOutputArray markerIds = noArray()) const; +protected: + struct CharucoDetectorImpl; + Ptr charucoDetectorImpl; +}; + +/** + * @brief Draws a set of Charuco corners + * @param image input/output image. It must have 1 or 3 channels. The number of channels is not + * altered. + * @param charucoCorners vector of detected charuco corners + * @param charucoIds list of identifiers for each corner in charucoCorners + * @param cornerColor color of the square surrounding each corner + * + * This function draws a set of detected Charuco corners. If identifiers vector is provided, it also + * draws the id of each corner. + */ +CV_EXPORTS_W void drawDetectedCornersCharuco(InputOutputArray image, InputArray charucoCorners, + InputArray charucoIds = noArray(), Scalar cornerColor = Scalar(255, 0, 0)); + +/** + * @brief Draw a set of detected ChArUco Diamond markers + * + * @param image input/output image. It must have 1 or 3 channels. The number of channels is not + * altered. + * @param diamondCorners positions of diamond corners in the same format returned by + * detectCharucoDiamond(). (e.g std::vector > ). For N detected markers, + * the dimensions of this array should be Nx4. The order of the corners should be clockwise. + * @param diamondIds vector of identifiers for diamonds in diamondCorners, in the same format + * returned by detectCharucoDiamond() (e.g. std::vector). + * Optional, if not provided, ids are not painted. + * @param borderColor color of marker borders. Rest of colors (text color and first corner color) + * are calculated based on this one. + * + * Given an array of detected diamonds, this functions draws them in the image. The marker borders + * are painted and the markers identifiers if provided. + * Useful for debugging purposes. + */ +CV_EXPORTS_W void drawDetectedDiamonds(InputOutputArray image, InputArrayOfArrays diamondCorners, + InputArray diamondIds = noArray(), + Scalar borderColor = Scalar(0, 0, 255)); + +//! @} + +} +} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/objdetect/detection_based_tracker.hpp b/3rdParty/opencv-4.11.0/opencv2/objdetect/detection_based_tracker.hpp index 8050278b42..8fe43c2c6b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/objdetect/detection_based_tracker.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/objdetect/detection_based_tracker.hpp @@ -1,222 +1,222 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_OBJDETECT_DBT_HPP -#define OPENCV_OBJDETECT_DBT_HPP - -#include - -#include - -namespace cv -{ - -//! @addtogroup objdetect_cascade_classifier -//! @{ - -class CV_EXPORTS DetectionBasedTracker -{ - public: - struct CV_EXPORTS Parameters - { - int maxTrackLifetime; - int minDetectionPeriod; //the minimal time between run of the big object detector (on the whole frame) in ms (1000 mean 1 sec), default=0 - - Parameters(); - }; - - class IDetector - { - public: - IDetector(): - minObjSize(96, 96), - maxObjSize(INT_MAX, INT_MAX), - minNeighbours(2), - scaleFactor(1.1f) - {} - - virtual void detect(const cv::Mat& image, std::vector& objects) = 0; - - void setMinObjectSize(const cv::Size& min) - { - minObjSize = min; - } - void setMaxObjectSize(const cv::Size& max) - { - maxObjSize = max; - } - cv::Size getMinObjectSize() const - { - return minObjSize; - } - cv::Size getMaxObjectSize() const - { - return maxObjSize; - } - float getScaleFactor() - { - return scaleFactor; - } - void setScaleFactor(float value) - { - scaleFactor = value; - } - int getMinNeighbours() - { - return minNeighbours; - } - void setMinNeighbours(int value) - { - minNeighbours = value; - } - virtual ~IDetector() {} - - protected: - cv::Size minObjSize; - cv::Size maxObjSize; - int minNeighbours; - float scaleFactor; - }; - - DetectionBasedTracker(cv::Ptr mainDetector, cv::Ptr trackingDetector, const Parameters& params); - virtual ~DetectionBasedTracker(); - - virtual bool run(); - virtual void stop(); - virtual void resetTracking(); - - virtual void process(const cv::Mat& imageGray); - - bool setParameters(const Parameters& params); - const Parameters& getParameters() const; - - - typedef std::pair Object; - virtual void getObjects(std::vector& result) const; - virtual void getObjects(std::vector& result) const; - - enum ObjectStatus - { - DETECTED_NOT_SHOWN_YET, - DETECTED, - DETECTED_TEMPORARY_LOST, - WRONG_OBJECT - }; - struct ExtObject - { - int id; - cv::Rect location; - ObjectStatus status; - ExtObject(int _id, cv::Rect _location, ObjectStatus _status) - :id(_id), location(_location), status(_status) - { - } - }; - virtual void getObjects(std::vector& result) const; - - - virtual int addObject(const cv::Rect& location); //returns id of the new object - - protected: - class SeparateDetectionWork; - cv::Ptr separateDetectionWork; - friend void* workcycleObjectDetectorFunction(void* p); - - struct InnerParameters - { - int numLastPositionsToTrack; - int numStepsToWaitBeforeFirstShow; - int numStepsToTrackWithoutDetectingIfObjectHasNotBeenShown; - int numStepsToShowWithoutDetecting; - - float coeffTrackingWindowSize; - float coeffObjectSizeToTrack; - float coeffObjectSpeedUsingInPrediction; - - InnerParameters(); - }; - Parameters parameters; - InnerParameters innerParameters; - - struct TrackedObject - { - typedef std::vector PositionsVector; - - PositionsVector lastPositions; - - int numDetectedFrames; - int numFramesNotDetected; - int id; - - TrackedObject(const cv::Rect& rect):numDetectedFrames(1), numFramesNotDetected(0) - { - lastPositions.push_back(rect); - id=getNextId(); - } - - static int getNextId() - { - static int _id=0; - return _id++; - } - }; - - int numTrackedSteps; - std::vector trackedObjects; - - std::vector weightsPositionsSmoothing; - std::vector weightsSizesSmoothing; - - cv::Ptr cascadeForTracking; - - void updateTrackedObjects(const std::vector& detectedObjects); - cv::Rect calcTrackedObjectPositionToShow(int i) const; - cv::Rect calcTrackedObjectPositionToShow(int i, ObjectStatus& status) const; - void detectInRegion(const cv::Mat& img, const cv::Rect& r, std::vector& detectedObjectsInRegions); -}; - -//! @} - -} //end of cv namespace - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_OBJDETECT_DBT_HPP +#define OPENCV_OBJDETECT_DBT_HPP + +#include + +#include + +namespace cv +{ + +//! @addtogroup objdetect_cascade_classifier +//! @{ + +class CV_EXPORTS DetectionBasedTracker +{ + public: + struct CV_EXPORTS Parameters + { + int maxTrackLifetime; + int minDetectionPeriod; //the minimal time between run of the big object detector (on the whole frame) in ms (1000 mean 1 sec), default=0 + + Parameters(); + }; + + class IDetector + { + public: + IDetector(): + minObjSize(96, 96), + maxObjSize(INT_MAX, INT_MAX), + minNeighbours(2), + scaleFactor(1.1f) + {} + + virtual void detect(const cv::Mat& image, std::vector& objects) = 0; + + void setMinObjectSize(const cv::Size& min) + { + minObjSize = min; + } + void setMaxObjectSize(const cv::Size& max) + { + maxObjSize = max; + } + cv::Size getMinObjectSize() const + { + return minObjSize; + } + cv::Size getMaxObjectSize() const + { + return maxObjSize; + } + float getScaleFactor() + { + return scaleFactor; + } + void setScaleFactor(float value) + { + scaleFactor = value; + } + int getMinNeighbours() + { + return minNeighbours; + } + void setMinNeighbours(int value) + { + minNeighbours = value; + } + virtual ~IDetector() {} + + protected: + cv::Size minObjSize; + cv::Size maxObjSize; + int minNeighbours; + float scaleFactor; + }; + + DetectionBasedTracker(cv::Ptr mainDetector, cv::Ptr trackingDetector, const Parameters& params); + virtual ~DetectionBasedTracker(); + + virtual bool run(); + virtual void stop(); + virtual void resetTracking(); + + virtual void process(const cv::Mat& imageGray); + + bool setParameters(const Parameters& params); + const Parameters& getParameters() const; + + + typedef std::pair Object; + virtual void getObjects(std::vector& result) const; + virtual void getObjects(std::vector& result) const; + + enum ObjectStatus + { + DETECTED_NOT_SHOWN_YET, + DETECTED, + DETECTED_TEMPORARY_LOST, + WRONG_OBJECT + }; + struct ExtObject + { + int id; + cv::Rect location; + ObjectStatus status; + ExtObject(int _id, cv::Rect _location, ObjectStatus _status) + :id(_id), location(_location), status(_status) + { + } + }; + virtual void getObjects(std::vector& result) const; + + + virtual int addObject(const cv::Rect& location); //returns id of the new object + + protected: + class SeparateDetectionWork; + cv::Ptr separateDetectionWork; + friend void* workcycleObjectDetectorFunction(void* p); + + struct InnerParameters + { + int numLastPositionsToTrack; + int numStepsToWaitBeforeFirstShow; + int numStepsToTrackWithoutDetectingIfObjectHasNotBeenShown; + int numStepsToShowWithoutDetecting; + + float coeffTrackingWindowSize; + float coeffObjectSizeToTrack; + float coeffObjectSpeedUsingInPrediction; + + InnerParameters(); + }; + Parameters parameters; + InnerParameters innerParameters; + + struct TrackedObject + { + typedef std::vector PositionsVector; + + PositionsVector lastPositions; + + int numDetectedFrames; + int numFramesNotDetected; + int id; + + TrackedObject(const cv::Rect& rect):numDetectedFrames(1), numFramesNotDetected(0) + { + lastPositions.push_back(rect); + id=getNextId(); + } + + static int getNextId() + { + static int _id=0; + return _id++; + } + }; + + int numTrackedSteps; + std::vector trackedObjects; + + std::vector weightsPositionsSmoothing; + std::vector weightsSizesSmoothing; + + cv::Ptr cascadeForTracking; + + void updateTrackedObjects(const std::vector& detectedObjects); + cv::Rect calcTrackedObjectPositionToShow(int i) const; + cv::Rect calcTrackedObjectPositionToShow(int i, ObjectStatus& status) const; + void detectInRegion(const cv::Mat& img, const cv::Rect& r, std::vector& detectedObjectsInRegions); +}; + +//! @} + +} //end of cv namespace + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/objdetect/face.hpp b/3rdParty/opencv-4.11.0/opencv2/objdetect/face.hpp index 566204f7f9..3528d73bc6 100644 --- a/3rdParty/opencv-4.11.0/opencv2/objdetect/face.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/objdetect/face.hpp @@ -1,179 +1,179 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_OBJDETECT_FACE_HPP -#define OPENCV_OBJDETECT_FACE_HPP - -#include - -namespace cv -{ - -//! @addtogroup objdetect_dnn_face -//! @{ - -/** @brief DNN-based face detector - -model download link: https://github.com/opencv/opencv_zoo/tree/master/models/face_detection_yunet - */ -class CV_EXPORTS_W FaceDetectorYN -{ -public: - virtual ~FaceDetectorYN() {} - - /** @brief Set the size for the network input, which overwrites the input size of creating model. Call this method when the size of input image does not match the input size when creating model - * - * @param input_size the size of the input image - */ - CV_WRAP virtual void setInputSize(const Size& input_size) = 0; - - CV_WRAP virtual Size getInputSize() = 0; - - /** @brief Set the score threshold to filter out bounding boxes of score less than the given value - * - * @param score_threshold threshold for filtering out bounding boxes - */ - CV_WRAP virtual void setScoreThreshold(float score_threshold) = 0; - - CV_WRAP virtual float getScoreThreshold() = 0; - - /** @brief Set the Non-maximum-suppression threshold to suppress bounding boxes that have IoU greater than the given value - * - * @param nms_threshold threshold for NMS operation - */ - CV_WRAP virtual void setNMSThreshold(float nms_threshold) = 0; - - CV_WRAP virtual float getNMSThreshold() = 0; - - /** @brief Set the number of bounding boxes preserved before NMS - * - * @param top_k the number of bounding boxes to preserve from top rank based on score - */ - CV_WRAP virtual void setTopK(int top_k) = 0; - - CV_WRAP virtual int getTopK() = 0; - - /** @brief Detects faces in the input image. Following is an example output. - - * ![image](pics/lena-face-detection.jpg) - - * @param image an image to detect - * @param faces detection results stored in a 2D cv::Mat of shape [num_faces, 15] - * - 0-1: x, y of bbox top left corner - * - 2-3: width, height of bbox - * - 4-5: x, y of right eye (blue point in the example image) - * - 6-7: x, y of left eye (red point in the example image) - * - 8-9: x, y of nose tip (green point in the example image) - * - 10-11: x, y of right corner of mouth (pink point in the example image) - * - 12-13: x, y of left corner of mouth (yellow point in the example image) - * - 14: face score - */ - CV_WRAP virtual int detect(InputArray image, OutputArray faces) = 0; - - /** @brief Creates an instance of face detector class with given parameters - * - * @param model the path to the requested model - * @param config the path to the config file for compability, which is not requested for ONNX models - * @param input_size the size of the input image - * @param score_threshold the threshold to filter out bounding boxes of score smaller than the given value - * @param nms_threshold the threshold to suppress bounding boxes of IoU bigger than the given value - * @param top_k keep top K bboxes before NMS - * @param backend_id the id of backend - * @param target_id the id of target device - */ - CV_WRAP static Ptr create(CV_WRAP_FILE_PATH const String& model, - CV_WRAP_FILE_PATH const String& config, - const Size& input_size, - float score_threshold = 0.9f, - float nms_threshold = 0.3f, - int top_k = 5000, - int backend_id = 0, - int target_id = 0); - - /** @overload - * - * @param framework Name of origin framework - * @param bufferModel A buffer with a content of binary file with weights - * @param bufferConfig A buffer with a content of text file contains network configuration - * @param input_size the size of the input image - * @param score_threshold the threshold to filter out bounding boxes of score smaller than the given value - * @param nms_threshold the threshold to suppress bounding boxes of IoU bigger than the given value - * @param top_k keep top K bboxes before NMS - * @param backend_id the id of backend - * @param target_id the id of target device - */ - CV_WRAP static Ptr create(const String& framework, - const std::vector& bufferModel, - const std::vector& bufferConfig, - const Size& input_size, - float score_threshold = 0.9f, - float nms_threshold = 0.3f, - int top_k = 5000, - int backend_id = 0, - int target_id = 0); - -}; - -/** @brief DNN-based face recognizer - -model download link: https://github.com/opencv/opencv_zoo/tree/master/models/face_recognition_sface - */ -class CV_EXPORTS_W FaceRecognizerSF -{ -public: - virtual ~FaceRecognizerSF() {} - - /** @brief Definition of distance used for calculating the distance between two face features - */ - enum DisType { FR_COSINE=0, FR_NORM_L2=1 }; - - /** @brief Aligns detected face with the source input image and crops it - * @param src_img input image - * @param face_box the detected face result from the input image - * @param aligned_img output aligned image - */ - CV_WRAP virtual void alignCrop(InputArray src_img, InputArray face_box, OutputArray aligned_img) const = 0; - - /** @brief Extracts face feature from aligned image - * @param aligned_img input aligned image - * @param face_feature output face feature - */ - CV_WRAP virtual void feature(InputArray aligned_img, OutputArray face_feature) = 0; - - /** @brief Calculates the distance between two face features - * @param face_feature1 the first input feature - * @param face_feature2 the second input feature of the same size and the same type as face_feature1 - * @param dis_type defines how to calculate the distance between two face features with optional values "FR_COSINE" or "FR_NORM_L2" - */ - CV_WRAP virtual double match(InputArray face_feature1, InputArray face_feature2, int dis_type = FaceRecognizerSF::FR_COSINE) const = 0; - - /** @brief Creates an instance of this class with given parameters - * @param model the path of the onnx model used for face recognition - * @param config the path to the config file for compability, which is not requested for ONNX models - * @param backend_id the id of backend - * @param target_id the id of target device - */ - CV_WRAP static Ptr create(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config, int backend_id = 0, int target_id = 0); - - /** - * @brief Creates an instance of this class from a buffer containing the model weights and configuration. - * @param framework Name of the framework (ONNX, etc.) - * @param bufferModel A buffer containing the binary model weights. - * @param bufferConfig A buffer containing the network configuration. - * @param backend_id The id of the backend. - * @param target_id The id of the target device. - * - * @return A pointer to the created instance of FaceRecognizerSF. - */ - CV_WRAP static Ptr create(const String& framework, - const std::vector& bufferModel, - const std::vector& bufferConfig, - int backend_id = 0, - int target_id = 0); -}; - -//! @} -} // namespace cv - -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_OBJDETECT_FACE_HPP +#define OPENCV_OBJDETECT_FACE_HPP + +#include + +namespace cv +{ + +//! @addtogroup objdetect_dnn_face +//! @{ + +/** @brief DNN-based face detector + +model download link: https://github.com/opencv/opencv_zoo/tree/master/models/face_detection_yunet + */ +class CV_EXPORTS_W FaceDetectorYN +{ +public: + virtual ~FaceDetectorYN() {} + + /** @brief Set the size for the network input, which overwrites the input size of creating model. Call this method when the size of input image does not match the input size when creating model + * + * @param input_size the size of the input image + */ + CV_WRAP virtual void setInputSize(const Size& input_size) = 0; + + CV_WRAP virtual Size getInputSize() = 0; + + /** @brief Set the score threshold to filter out bounding boxes of score less than the given value + * + * @param score_threshold threshold for filtering out bounding boxes + */ + CV_WRAP virtual void setScoreThreshold(float score_threshold) = 0; + + CV_WRAP virtual float getScoreThreshold() = 0; + + /** @brief Set the Non-maximum-suppression threshold to suppress bounding boxes that have IoU greater than the given value + * + * @param nms_threshold threshold for NMS operation + */ + CV_WRAP virtual void setNMSThreshold(float nms_threshold) = 0; + + CV_WRAP virtual float getNMSThreshold() = 0; + + /** @brief Set the number of bounding boxes preserved before NMS + * + * @param top_k the number of bounding boxes to preserve from top rank based on score + */ + CV_WRAP virtual void setTopK(int top_k) = 0; + + CV_WRAP virtual int getTopK() = 0; + + /** @brief Detects faces in the input image. Following is an example output. + + * ![image](pics/lena-face-detection.jpg) + + * @param image an image to detect + * @param faces detection results stored in a 2D cv::Mat of shape [num_faces, 15] + * - 0-1: x, y of bbox top left corner + * - 2-3: width, height of bbox + * - 4-5: x, y of right eye (blue point in the example image) + * - 6-7: x, y of left eye (red point in the example image) + * - 8-9: x, y of nose tip (green point in the example image) + * - 10-11: x, y of right corner of mouth (pink point in the example image) + * - 12-13: x, y of left corner of mouth (yellow point in the example image) + * - 14: face score + */ + CV_WRAP virtual int detect(InputArray image, OutputArray faces) = 0; + + /** @brief Creates an instance of face detector class with given parameters + * + * @param model the path to the requested model + * @param config the path to the config file for compability, which is not requested for ONNX models + * @param input_size the size of the input image + * @param score_threshold the threshold to filter out bounding boxes of score smaller than the given value + * @param nms_threshold the threshold to suppress bounding boxes of IoU bigger than the given value + * @param top_k keep top K bboxes before NMS + * @param backend_id the id of backend + * @param target_id the id of target device + */ + CV_WRAP static Ptr create(CV_WRAP_FILE_PATH const String& model, + CV_WRAP_FILE_PATH const String& config, + const Size& input_size, + float score_threshold = 0.9f, + float nms_threshold = 0.3f, + int top_k = 5000, + int backend_id = 0, + int target_id = 0); + + /** @overload + * + * @param framework Name of origin framework + * @param bufferModel A buffer with a content of binary file with weights + * @param bufferConfig A buffer with a content of text file contains network configuration + * @param input_size the size of the input image + * @param score_threshold the threshold to filter out bounding boxes of score smaller than the given value + * @param nms_threshold the threshold to suppress bounding boxes of IoU bigger than the given value + * @param top_k keep top K bboxes before NMS + * @param backend_id the id of backend + * @param target_id the id of target device + */ + CV_WRAP static Ptr create(const String& framework, + const std::vector& bufferModel, + const std::vector& bufferConfig, + const Size& input_size, + float score_threshold = 0.9f, + float nms_threshold = 0.3f, + int top_k = 5000, + int backend_id = 0, + int target_id = 0); + +}; + +/** @brief DNN-based face recognizer + +model download link: https://github.com/opencv/opencv_zoo/tree/master/models/face_recognition_sface + */ +class CV_EXPORTS_W FaceRecognizerSF +{ +public: + virtual ~FaceRecognizerSF() {} + + /** @brief Definition of distance used for calculating the distance between two face features + */ + enum DisType { FR_COSINE=0, FR_NORM_L2=1 }; + + /** @brief Aligns detected face with the source input image and crops it + * @param src_img input image + * @param face_box the detected face result from the input image + * @param aligned_img output aligned image + */ + CV_WRAP virtual void alignCrop(InputArray src_img, InputArray face_box, OutputArray aligned_img) const = 0; + + /** @brief Extracts face feature from aligned image + * @param aligned_img input aligned image + * @param face_feature output face feature + */ + CV_WRAP virtual void feature(InputArray aligned_img, OutputArray face_feature) = 0; + + /** @brief Calculates the distance between two face features + * @param face_feature1 the first input feature + * @param face_feature2 the second input feature of the same size and the same type as face_feature1 + * @param dis_type defines how to calculate the distance between two face features with optional values "FR_COSINE" or "FR_NORM_L2" + */ + CV_WRAP virtual double match(InputArray face_feature1, InputArray face_feature2, int dis_type = FaceRecognizerSF::FR_COSINE) const = 0; + + /** @brief Creates an instance of this class with given parameters + * @param model the path of the onnx model used for face recognition + * @param config the path to the config file for compability, which is not requested for ONNX models + * @param backend_id the id of backend + * @param target_id the id of target device + */ + CV_WRAP static Ptr create(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config, int backend_id = 0, int target_id = 0); + + /** + * @brief Creates an instance of this class from a buffer containing the model weights and configuration. + * @param framework Name of the framework (ONNX, etc.) + * @param bufferModel A buffer containing the binary model weights. + * @param bufferConfig A buffer containing the network configuration. + * @param backend_id The id of the backend. + * @param target_id The id of the target device. + * + * @return A pointer to the created instance of FaceRecognizerSF. + */ + CV_WRAP static Ptr create(const String& framework, + const std::vector& bufferModel, + const std::vector& bufferConfig, + int backend_id = 0, + int target_id = 0); +}; + +//! @} +} // namespace cv + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/objdetect/graphical_code_detector.hpp b/3rdParty/opencv-4.11.0/opencv2/objdetect/graphical_code_detector.hpp index ed697c50c0..e4200a4204 100644 --- a/3rdParty/opencv-4.11.0/opencv2/objdetect/graphical_code_detector.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/objdetect/graphical_code_detector.hpp @@ -1,85 +1,85 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html -#ifndef OPENCV_OBJDETECT_GRAPHICAL_CODE_DETECTOR_HPP -#define OPENCV_OBJDETECT_GRAPHICAL_CODE_DETECTOR_HPP - -#include - -namespace cv { - -//! @addtogroup objdetect_common -//! @{ - -class CV_EXPORTS_W_SIMPLE GraphicalCodeDetector { -public: - CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) - GraphicalCodeDetector(); - - GraphicalCodeDetector(const GraphicalCodeDetector&) = default; - GraphicalCodeDetector(GraphicalCodeDetector&&) = default; - GraphicalCodeDetector& operator=(const GraphicalCodeDetector&) = default; - GraphicalCodeDetector& operator=(GraphicalCodeDetector&&) = default; - - /** @brief Detects graphical code in image and returns the quadrangle containing the code. - @param img grayscale or color (BGR) image containing (or not) graphical code. - @param points Output vector of vertices of the minimum-area quadrangle containing the code. - */ - CV_WRAP bool detect(InputArray img, OutputArray points) const; - - /** @brief Decodes graphical code in image once it's found by the detect() method. - - Returns UTF8-encoded output string or empty string if the code cannot be decoded. - @param img grayscale or color (BGR) image containing graphical code. - @param points Quadrangle vertices found by detect() method (or some other algorithm). - @param straight_code The optional output image containing binarized code, will be empty if not found. - */ - CV_WRAP std::string decode(InputArray img, InputArray points, OutputArray straight_code = noArray()) const; - - /** @brief Both detects and decodes graphical code - - @param img grayscale or color (BGR) image containing graphical code. - @param points optional output array of vertices of the found graphical code quadrangle, will be empty if not found. - @param straight_code The optional output image containing binarized code - */ - CV_WRAP std::string detectAndDecode(InputArray img, OutputArray points = noArray(), - OutputArray straight_code = noArray()) const; - - - /** @brief Detects graphical codes in image and returns the vector of the quadrangles containing the codes. - @param img grayscale or color (BGR) image containing (or not) graphical codes. - @param points Output vector of vector of vertices of the minimum-area quadrangle containing the codes. - */ - CV_WRAP bool detectMulti(InputArray img, OutputArray points) const; - - /** @brief Decodes graphical codes in image once it's found by the detect() method. - @param img grayscale or color (BGR) image containing graphical codes. - @param decoded_info UTF8-encoded output vector of string or empty vector of string if the codes cannot be decoded. - @param points vector of Quadrangle vertices found by detect() method (or some other algorithm). - @param straight_code The optional output vector of images containing binarized codes - */ - CV_WRAP bool decodeMulti(InputArray img, InputArray points, CV_OUT std::vector& decoded_info, - OutputArrayOfArrays straight_code = noArray()) const; - - /** @brief Both detects and decodes graphical codes - @param img grayscale or color (BGR) image containing graphical codes. - @param decoded_info UTF8-encoded output vector of string or empty vector of string if the codes cannot be decoded. - @param points optional output vector of vertices of the found graphical code quadrangles. Will be empty if not found. - @param straight_code The optional vector of images containing binarized codes - - - If there are QR codes encoded with a Structured Append mode on the image and all of them detected and decoded correctly, - method writes a full message to position corresponds to 0-th code in a sequence. The rest of QR codes from the same sequence - have empty string. - */ - CV_WRAP bool detectAndDecodeMulti(InputArray img, CV_OUT std::vector& decoded_info, OutputArray points = noArray(), - OutputArrayOfArrays straight_code = noArray()) const; - struct Impl; -protected: - Ptr p; -}; - -//! @} - -} - -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html +#ifndef OPENCV_OBJDETECT_GRAPHICAL_CODE_DETECTOR_HPP +#define OPENCV_OBJDETECT_GRAPHICAL_CODE_DETECTOR_HPP + +#include + +namespace cv { + +//! @addtogroup objdetect_common +//! @{ + +class CV_EXPORTS_W_SIMPLE GraphicalCodeDetector { +public: + CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) + GraphicalCodeDetector(); + + GraphicalCodeDetector(const GraphicalCodeDetector&) = default; + GraphicalCodeDetector(GraphicalCodeDetector&&) = default; + GraphicalCodeDetector& operator=(const GraphicalCodeDetector&) = default; + GraphicalCodeDetector& operator=(GraphicalCodeDetector&&) = default; + + /** @brief Detects graphical code in image and returns the quadrangle containing the code. + @param img grayscale or color (BGR) image containing (or not) graphical code. + @param points Output vector of vertices of the minimum-area quadrangle containing the code. + */ + CV_WRAP bool detect(InputArray img, OutputArray points) const; + + /** @brief Decodes graphical code in image once it's found by the detect() method. + + Returns UTF8-encoded output string or empty string if the code cannot be decoded. + @param img grayscale or color (BGR) image containing graphical code. + @param points Quadrangle vertices found by detect() method (or some other algorithm). + @param straight_code The optional output image containing binarized code, will be empty if not found. + */ + CV_WRAP std::string decode(InputArray img, InputArray points, OutputArray straight_code = noArray()) const; + + /** @brief Both detects and decodes graphical code + + @param img grayscale or color (BGR) image containing graphical code. + @param points optional output array of vertices of the found graphical code quadrangle, will be empty if not found. + @param straight_code The optional output image containing binarized code + */ + CV_WRAP std::string detectAndDecode(InputArray img, OutputArray points = noArray(), + OutputArray straight_code = noArray()) const; + + + /** @brief Detects graphical codes in image and returns the vector of the quadrangles containing the codes. + @param img grayscale or color (BGR) image containing (or not) graphical codes. + @param points Output vector of vector of vertices of the minimum-area quadrangle containing the codes. + */ + CV_WRAP bool detectMulti(InputArray img, OutputArray points) const; + + /** @brief Decodes graphical codes in image once it's found by the detect() method. + @param img grayscale or color (BGR) image containing graphical codes. + @param decoded_info UTF8-encoded output vector of string or empty vector of string if the codes cannot be decoded. + @param points vector of Quadrangle vertices found by detect() method (or some other algorithm). + @param straight_code The optional output vector of images containing binarized codes + */ + CV_WRAP bool decodeMulti(InputArray img, InputArray points, CV_OUT std::vector& decoded_info, + OutputArrayOfArrays straight_code = noArray()) const; + + /** @brief Both detects and decodes graphical codes + @param img grayscale or color (BGR) image containing graphical codes. + @param decoded_info UTF8-encoded output vector of string or empty vector of string if the codes cannot be decoded. + @param points optional output vector of vertices of the found graphical code quadrangles. Will be empty if not found. + @param straight_code The optional vector of images containing binarized codes + + - If there are QR codes encoded with a Structured Append mode on the image and all of them detected and decoded correctly, + method writes a full message to position corresponds to 0-th code in a sequence. The rest of QR codes from the same sequence + have empty string. + */ + CV_WRAP bool detectAndDecodeMulti(InputArray img, CV_OUT std::vector& decoded_info, OutputArray points = noArray(), + OutputArrayOfArrays straight_code = noArray()) const; + struct Impl; +protected: + Ptr p; +}; + +//! @} + +} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/objdetect/objdetect.hpp b/3rdParty/opencv-4.11.0/opencv2/objdetect/objdetect.hpp index 3ee284f427..2a0dfdd42b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/objdetect/objdetect.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/objdetect/objdetect.hpp @@ -1,48 +1,48 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifdef __OPENCV_BUILD -#error this is a compatibility header which should not be used inside the OpenCV library -#endif - -#include "opencv2/objdetect.hpp" +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/objdetect.hpp" diff --git a/3rdParty/opencv-4.11.0/opencv2/opencv.hpp b/3rdParty/opencv-4.11.0/opencv2/opencv.hpp index d17b94a4ea..801d6a6aa4 100644 --- a/3rdParty/opencv-4.11.0/opencv2/opencv.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/opencv.hpp @@ -1,95 +1,95 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009-2010, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_ALL_HPP -#define OPENCV_ALL_HPP - -// File that defines what modules where included during the build of OpenCV -// These are purely the defines of the correct HAVE_OPENCV_modulename values -#include "opencv2/opencv_modules.hpp" - -// Then the list of defines is checked to include the correct headers -// Core library is always included --> without no OpenCV functionality available -#include "opencv2/core.hpp" - -// Then the optional modules are checked -#ifdef HAVE_OPENCV_CALIB3D -#include "opencv2/calib3d.hpp" -#endif -#ifdef HAVE_OPENCV_FEATURES2D -#include "opencv2/features2d.hpp" -#endif -#ifdef HAVE_OPENCV_DNN -#include "opencv2/dnn.hpp" -#endif -#ifdef HAVE_OPENCV_FLANN -#include "opencv2/flann.hpp" -#endif -#ifdef HAVE_OPENCV_HIGHGUI -#include "opencv2/highgui.hpp" -#endif -#ifdef HAVE_OPENCV_IMGCODECS -#include "opencv2/imgcodecs.hpp" -#endif -#ifdef HAVE_OPENCV_IMGPROC -#include "opencv2/imgproc.hpp" -#endif -#ifdef HAVE_OPENCV_ML -#include "opencv2/ml.hpp" -#endif -#ifdef HAVE_OPENCV_OBJDETECT -#include "opencv2/objdetect.hpp" -#endif -#ifdef HAVE_OPENCV_PHOTO -#include "opencv2/photo.hpp" -#endif -#ifdef HAVE_OPENCV_STITCHING -#include "opencv2/stitching.hpp" -#endif -#ifdef HAVE_OPENCV_VIDEO -#include "opencv2/video.hpp" -#endif -#ifdef HAVE_OPENCV_VIDEOIO -#include "opencv2/videoio.hpp" -#endif - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009-2010, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_ALL_HPP +#define OPENCV_ALL_HPP + +// File that defines what modules where included during the build of OpenCV +// These are purely the defines of the correct HAVE_OPENCV_modulename values +#include "opencv2/opencv_modules.hpp" + +// Then the list of defines is checked to include the correct headers +// Core library is always included --> without no OpenCV functionality available +#include "opencv2/core.hpp" + +// Then the optional modules are checked +#ifdef HAVE_OPENCV_CALIB3D +#include "opencv2/calib3d.hpp" +#endif +#ifdef HAVE_OPENCV_FEATURES2D +#include "opencv2/features2d.hpp" +#endif +#ifdef HAVE_OPENCV_DNN +#include "opencv2/dnn.hpp" +#endif +#ifdef HAVE_OPENCV_FLANN +#include "opencv2/flann.hpp" +#endif +#ifdef HAVE_OPENCV_HIGHGUI +#include "opencv2/highgui.hpp" +#endif +#ifdef HAVE_OPENCV_IMGCODECS +#include "opencv2/imgcodecs.hpp" +#endif +#ifdef HAVE_OPENCV_IMGPROC +#include "opencv2/imgproc.hpp" +#endif +#ifdef HAVE_OPENCV_ML +#include "opencv2/ml.hpp" +#endif +#ifdef HAVE_OPENCV_OBJDETECT +#include "opencv2/objdetect.hpp" +#endif +#ifdef HAVE_OPENCV_PHOTO +#include "opencv2/photo.hpp" +#endif +#ifdef HAVE_OPENCV_STITCHING +#include "opencv2/stitching.hpp" +#endif +#ifdef HAVE_OPENCV_VIDEO +#include "opencv2/video.hpp" +#endif +#ifdef HAVE_OPENCV_VIDEOIO +#include "opencv2/videoio.hpp" +#endif + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/opencv_modules.hpp b/3rdParty/opencv-4.11.0/opencv2/opencv_modules.hpp index c9e24d845f..eb15e4abff 100644 --- a/3rdParty/opencv-4.11.0/opencv2/opencv_modules.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/opencv_modules.hpp @@ -1,30 +1,30 @@ -/* - * ** File generated automatically, do not modify ** - * - * This file defines the list of modules available in current build configuration - * - * -*/ - -// This definition means that OpenCV is built with enabled non-free code. -// For example, patented algorithms for non-profit/non-commercial use only. -/* #undef OPENCV_ENABLE_NONFREE */ - -#define HAVE_OPENCV_CALIB3D -#define HAVE_OPENCV_CORE -#define HAVE_OPENCV_DNN -#define HAVE_OPENCV_FEATURES2D -#define HAVE_OPENCV_FLANN -#define HAVE_OPENCV_GAPI -#define HAVE_OPENCV_HIGHGUI -#define HAVE_OPENCV_IMGCODECS -#define HAVE_OPENCV_IMGPROC -#define HAVE_OPENCV_ML -#define HAVE_OPENCV_OBJDETECT -#define HAVE_OPENCV_PHOTO -#define HAVE_OPENCV_STITCHING -#define HAVE_OPENCV_VIDEO -#define HAVE_OPENCV_VIDEOIO -#define HAVE_OPENCV_WORLD - - +/* + * ** File generated automatically, do not modify ** + * + * This file defines the list of modules available in current build configuration + * + * +*/ + +// This definition means that OpenCV is built with enabled non-free code. +// For example, patented algorithms for non-profit/non-commercial use only. +/* #undef OPENCV_ENABLE_NONFREE */ + +#define HAVE_OPENCV_CALIB3D +#define HAVE_OPENCV_CORE +#define HAVE_OPENCV_DNN +#define HAVE_OPENCV_FEATURES2D +#define HAVE_OPENCV_FLANN +#define HAVE_OPENCV_GAPI +#define HAVE_OPENCV_HIGHGUI +#define HAVE_OPENCV_IMGCODECS +#define HAVE_OPENCV_IMGPROC +#define HAVE_OPENCV_ML +#define HAVE_OPENCV_OBJDETECT +#define HAVE_OPENCV_PHOTO +#define HAVE_OPENCV_STITCHING +#define HAVE_OPENCV_VIDEO +#define HAVE_OPENCV_VIDEOIO +#define HAVE_OPENCV_WORLD + + diff --git a/3rdParty/opencv-4.11.0/opencv2/photo.hpp b/3rdParty/opencv-4.11.0/opencv2/photo.hpp index a8b7c6049a..66f00b7e90 100644 --- a/3rdParty/opencv-4.11.0/opencv2/photo.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/photo.hpp @@ -1,898 +1,898 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2008-2012, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_PHOTO_HPP -#define OPENCV_PHOTO_HPP - -#include "opencv2/core.hpp" -#include "opencv2/imgproc.hpp" - -/** -@defgroup photo Computational Photography - -This module includes photo processing algorithms -@{ - @defgroup photo_inpaint Inpainting - @defgroup photo_denoise Denoising - @defgroup photo_hdr HDR imaging - - This section describes high dynamic range imaging algorithms namely tonemapping, exposure alignment, - camera calibration with multiple exposures and exposure fusion. - - @defgroup photo_decolor Contrast Preserving Decolorization - - Useful links: - - http://www.cse.cuhk.edu.hk/leojia/projects/color2gray/index.html - - @defgroup photo_clone Seamless Cloning - - Useful links: - - https://www.learnopencv.com/seamless-cloning-using-opencv-python-cpp - - @defgroup photo_render Non-Photorealistic Rendering - - Useful links: - - http://www.inf.ufrgs.br/~eslgastal/DomainTransform - - https://www.learnopencv.com/non-photorealistic-rendering-using-opencv-python-c/ - -@} - */ - -namespace cv -{ - -//! @addtogroup photo -//! @{ - -//! @addtogroup photo_inpaint -//! @{ -//! the inpainting algorithm -enum -{ - INPAINT_NS = 0, //!< Use Navier-Stokes based method - INPAINT_TELEA = 1 //!< Use the algorithm proposed by Alexandru Telea @cite Telea04 -}; - -/** @brief Restores the selected region in an image using the region neighborhood. - -@param src Input 8-bit, 16-bit unsigned or 32-bit float 1-channel or 8-bit 3-channel image. -@param inpaintMask Inpainting mask, 8-bit 1-channel image. Non-zero pixels indicate the area that -needs to be inpainted. -@param dst Output image with the same size and type as src . -@param inpaintRadius Radius of a circular neighborhood of each point inpainted that is considered -by the algorithm. -@param flags Inpainting method that could be cv::INPAINT_NS or cv::INPAINT_TELEA - -The function reconstructs the selected image area from the pixel near the area boundary. The -function may be used to remove dust and scratches from a scanned photo, or to remove undesirable -objects from still images or video. See for more details. - -@note - - An example using the inpainting technique can be found at - opencv_source_code/samples/cpp/inpaint.cpp - - (Python) An example using the inpainting technique can be found at - opencv_source_code/samples/python/inpaint.py - */ -CV_EXPORTS_W void inpaint( InputArray src, InputArray inpaintMask, - OutputArray dst, double inpaintRadius, int flags ); - -//! @} photo_inpaint - -//! @addtogroup photo_denoise -//! @{ - -/** @brief Perform image denoising using Non-local Means Denoising algorithm - with several computational -optimizations. Noise expected to be a gaussian white noise - -@param src Input 8-bit 1-channel, 2-channel, 3-channel or 4-channel image. -@param dst Output image with the same size and type as src . -@param templateWindowSize Size in pixels of the template patch that is used to compute weights. -Should be odd. Recommended value 7 pixels -@param searchWindowSize Size in pixels of the window that is used to compute weighted average for -given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater -denoising time. Recommended value 21 pixels -@param h Parameter regulating filter strength. Big h value perfectly removes noise but also -removes image details, smaller h value preserves details but also preserves some noise - -This function expected to be applied to grayscale images. For colored images look at -fastNlMeansDenoisingColored. Advanced usage of this functions can be manual denoising of colored -image in different colorspaces. Such approach is used in fastNlMeansDenoisingColored by converting -image to CIELAB colorspace and then separately denoise L and AB components with different h -parameter. - */ -CV_EXPORTS_W void fastNlMeansDenoising( InputArray src, OutputArray dst, float h = 3, - int templateWindowSize = 7, int searchWindowSize = 21); - -/** @brief Perform image denoising using Non-local Means Denoising algorithm - with several computational -optimizations. Noise expected to be a gaussian white noise - -@param src Input 8-bit or 16-bit (only with NORM_L1) 1-channel, -2-channel, 3-channel or 4-channel image. -@param dst Output image with the same size and type as src . -@param templateWindowSize Size in pixels of the template patch that is used to compute weights. -Should be odd. Recommended value 7 pixels -@param searchWindowSize Size in pixels of the window that is used to compute weighted average for -given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater -denoising time. Recommended value 21 pixels -@param h Array of parameters regulating filter strength, either one -parameter applied to all channels or one per channel in dst. Big h value -perfectly removes noise but also removes image details, smaller h -value preserves details but also preserves some noise -@param normType Type of norm used for weight calculation. Can be either NORM_L2 or NORM_L1 - -This function expected to be applied to grayscale images. For colored images look at -fastNlMeansDenoisingColored. Advanced usage of this functions can be manual denoising of colored -image in different colorspaces. Such approach is used in fastNlMeansDenoisingColored by converting -image to CIELAB colorspace and then separately denoise L and AB components with different h -parameter. - */ -CV_EXPORTS_W void fastNlMeansDenoising( InputArray src, OutputArray dst, - const std::vector& h, - int templateWindowSize = 7, int searchWindowSize = 21, - int normType = NORM_L2); - -/** @brief Modification of fastNlMeansDenoising function for colored images - -@param src Input 8-bit 3-channel image. -@param dst Output image with the same size and type as src . -@param templateWindowSize Size in pixels of the template patch that is used to compute weights. -Should be odd. Recommended value 7 pixels -@param searchWindowSize Size in pixels of the window that is used to compute weighted average for -given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater -denoising time. Recommended value 21 pixels -@param h Parameter regulating filter strength for luminance component. Bigger h value perfectly -removes noise but also removes image details, smaller h value preserves details but also preserves -some noise -@param hColor The same as h but for color components. For most images value equals 10 -will be enough to remove colored noise and do not distort colors - -The function converts image to CIELAB colorspace and then separately denoise L and AB components -with given h parameters using fastNlMeansDenoising function. - */ -CV_EXPORTS_W void fastNlMeansDenoisingColored( InputArray src, OutputArray dst, - float h = 3, float hColor = 3, - int templateWindowSize = 7, int searchWindowSize = 21); - -/** @brief Modification of fastNlMeansDenoising function for images sequence where consecutive images have been -captured in small period of time. For example video. This version of the function is for grayscale -images or for manual manipulation with colorspaces. See @cite Buades2005DenoisingIS for more details -(open access [here](https://static.aminer.org/pdf/PDF/000/317/196/spatio_temporal_wiener_filtering_of_image_sequences_using_a_parametric.pdf)). - -@param srcImgs Input 8-bit 1-channel, 2-channel, 3-channel or -4-channel images sequence. All images should have the same type and -size. -@param imgToDenoiseIndex Target image to denoise index in srcImgs sequence -@param temporalWindowSize Number of surrounding images to use for target image denoising. Should -be odd. Images from imgToDenoiseIndex - temporalWindowSize / 2 to -imgToDenoiseIndex + temporalWindowSize / 2 from srcImgs will be used to denoise -srcImgs[imgToDenoiseIndex] image. -@param dst Output image with the same size and type as srcImgs images. -@param templateWindowSize Size in pixels of the template patch that is used to compute weights. -Should be odd. Recommended value 7 pixels -@param searchWindowSize Size in pixels of the window that is used to compute weighted average for -given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater -denoising time. Recommended value 21 pixels -@param h Parameter regulating filter strength. Bigger h value -perfectly removes noise but also removes image details, smaller h -value preserves details but also preserves some noise - */ -CV_EXPORTS_W void fastNlMeansDenoisingMulti( InputArrayOfArrays srcImgs, OutputArray dst, - int imgToDenoiseIndex, int temporalWindowSize, - float h = 3, int templateWindowSize = 7, int searchWindowSize = 21); - -/** @brief Modification of fastNlMeansDenoising function for images sequence where consecutive images have been -captured in small period of time. For example video. This version of the function is for grayscale -images or for manual manipulation with colorspaces. See @cite Buades2005DenoisingIS for more details -(open access [here](https://static.aminer.org/pdf/PDF/000/317/196/spatio_temporal_wiener_filtering_of_image_sequences_using_a_parametric.pdf)). - -@param srcImgs Input 8-bit or 16-bit (only with NORM_L1) 1-channel, -2-channel, 3-channel or 4-channel images sequence. All images should -have the same type and size. -@param imgToDenoiseIndex Target image to denoise index in srcImgs sequence -@param temporalWindowSize Number of surrounding images to use for target image denoising. Should -be odd. Images from imgToDenoiseIndex - temporalWindowSize / 2 to -imgToDenoiseIndex + temporalWindowSize / 2 from srcImgs will be used to denoise -srcImgs[imgToDenoiseIndex] image. -@param dst Output image with the same size and type as srcImgs images. -@param templateWindowSize Size in pixels of the template patch that is used to compute weights. -Should be odd. Recommended value 7 pixels -@param searchWindowSize Size in pixels of the window that is used to compute weighted average for -given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater -denoising time. Recommended value 21 pixels -@param h Array of parameters regulating filter strength, either one -parameter applied to all channels or one per channel in dst. Big h value -perfectly removes noise but also removes image details, smaller h -value preserves details but also preserves some noise -@param normType Type of norm used for weight calculation. Can be either NORM_L2 or NORM_L1 - */ -CV_EXPORTS_W void fastNlMeansDenoisingMulti( InputArrayOfArrays srcImgs, OutputArray dst, - int imgToDenoiseIndex, int temporalWindowSize, - const std::vector& h, - int templateWindowSize = 7, int searchWindowSize = 21, - int normType = NORM_L2); - -/** @brief Modification of fastNlMeansDenoisingMulti function for colored images sequences - -@param srcImgs Input 8-bit 3-channel images sequence. All images should have the same type and -size. -@param imgToDenoiseIndex Target image to denoise index in srcImgs sequence -@param temporalWindowSize Number of surrounding images to use for target image denoising. Should -be odd. Images from imgToDenoiseIndex - temporalWindowSize / 2 to -imgToDenoiseIndex + temporalWindowSize / 2 from srcImgs will be used to denoise -srcImgs[imgToDenoiseIndex] image. -@param dst Output image with the same size and type as srcImgs images. -@param templateWindowSize Size in pixels of the template patch that is used to compute weights. -Should be odd. Recommended value 7 pixels -@param searchWindowSize Size in pixels of the window that is used to compute weighted average for -given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater -denoising time. Recommended value 21 pixels -@param h Parameter regulating filter strength for luminance component. Bigger h value perfectly -removes noise but also removes image details, smaller h value preserves details but also preserves -some noise. -@param hColor The same as h but for color components. - -The function converts images to CIELAB colorspace and then separately denoise L and AB components -with given h parameters using fastNlMeansDenoisingMulti function. - */ -CV_EXPORTS_W void fastNlMeansDenoisingColoredMulti( InputArrayOfArrays srcImgs, OutputArray dst, - int imgToDenoiseIndex, int temporalWindowSize, - float h = 3, float hColor = 3, - int templateWindowSize = 7, int searchWindowSize = 21); - -/** @brief Primal-dual algorithm is an algorithm for solving special types of variational problems (that is, -finding a function to minimize some functional). As the image denoising, in particular, may be seen -as the variational problem, primal-dual algorithm then can be used to perform denoising and this is -exactly what is implemented. - -It should be noted, that this implementation was taken from the July 2013 blog entry -@cite MA13 , which also contained (slightly more general) ready-to-use source code on Python. -Subsequently, that code was rewritten on C++ with the usage of openCV by Vadim Pisarevsky at the end -of July 2013 and finally it was slightly adapted by later authors. - -Although the thorough discussion and justification of the algorithm involved may be found in -@cite ChambolleEtAl, it might make sense to skim over it here, following @cite MA13 . To begin -with, we consider the 1-byte gray-level images as the functions from the rectangular domain of -pixels (it may be seen as set -\f$\left\{(x,y)\in\mathbb{N}\times\mathbb{N}\mid 1\leq x\leq n,\;1\leq y\leq m\right\}\f$ for some -\f$m,\;n\in\mathbb{N}\f$) into \f$\{0,1,\dots,255\}\f$. We shall denote the noised images as \f$f_i\f$ and with -this view, given some image \f$x\f$ of the same size, we may measure how bad it is by the formula - -\f[\left\|\left\|\nabla x\right\|\right\| + \lambda\sum_i\left\|\left\|x-f_i\right\|\right\|\f] - -\f$\|\|\cdot\|\|\f$ here denotes \f$L_2\f$-norm and as you see, the first addend states that we want our -image to be smooth (ideally, having zero gradient, thus being constant) and the second states that -we want our result to be close to the observations we've got. If we treat \f$x\f$ as a function, this is -exactly the functional what we seek to minimize and here the Primal-Dual algorithm comes into play. - -@param observations This array should contain one or more noised versions of the image that is to -be restored. -@param result Here the denoised image will be stored. There is no need to do pre-allocation of -storage space, as it will be automatically allocated, if necessary. -@param lambda Corresponds to \f$\lambda\f$ in the formulas above. As it is enlarged, the smooth -(blurred) images are treated more favorably than detailed (but maybe more noised) ones. Roughly -speaking, as it becomes smaller, the result will be more blur but more sever outliers will be -removed. -@param niters Number of iterations that the algorithm will run. Of course, as more iterations as -better, but it is hard to quantitatively refine this statement, so just use the default and -increase it if the results are poor. - */ -CV_EXPORTS_W void denoise_TVL1(const std::vector& observations,Mat& result, double lambda=1.0, int niters=30); - -//! @} photo_denoise - -//! @addtogroup photo_hdr -//! @{ - -enum { LDR_SIZE = 256 }; - -/** @brief Base class for tonemapping algorithms - tools that are used to map HDR image to 8-bit range. - */ -class CV_EXPORTS_W Tonemap : public Algorithm -{ -public: - /** @brief Tonemaps image - - @param src source image - CV_32FC3 Mat (float 32 bits 3 channels) - @param dst destination image - CV_32FC3 Mat with values in [0, 1] range - */ - CV_WRAP virtual void process(InputArray src, OutputArray dst) = 0; - - CV_WRAP virtual float getGamma() const = 0; - CV_WRAP virtual void setGamma(float gamma) = 0; -}; - -/** @brief Creates simple linear mapper with gamma correction - -@param gamma positive value for gamma correction. Gamma value of 1.0 implies no correction, gamma -equal to 2.2f is suitable for most displays. -Generally gamma \> 1 brightens the image and gamma \< 1 darkens it. - */ -CV_EXPORTS_W Ptr createTonemap(float gamma = 1.0f); - -/** @brief Adaptive logarithmic mapping is a fast global tonemapping algorithm that scales the image in -logarithmic domain. - -Since it's a global operator the same function is applied to all the pixels, it is controlled by the -bias parameter. - -Optional saturation enhancement is possible as described in @cite FL02 . - -For more information see @cite DM03 . - */ -class CV_EXPORTS_W TonemapDrago : public Tonemap -{ -public: - - CV_WRAP virtual float getSaturation() const = 0; - CV_WRAP virtual void setSaturation(float saturation) = 0; - - CV_WRAP virtual float getBias() const = 0; - CV_WRAP virtual void setBias(float bias) = 0; -}; - -/** @brief Creates TonemapDrago object - -@param gamma gamma value for gamma correction. See createTonemap -@param saturation positive saturation enhancement value. 1.0 preserves saturation, values greater -than 1 increase saturation and values less than 1 decrease it. -@param bias value for bias function in [0, 1] range. Values from 0.7 to 0.9 usually give best -results, default value is 0.85. - */ -CV_EXPORTS_W Ptr createTonemapDrago(float gamma = 1.0f, float saturation = 1.0f, float bias = 0.85f); - - -/** @brief This is a global tonemapping operator that models human visual system. - -Mapping function is controlled by adaptation parameter, that is computed using light adaptation and -color adaptation. - -For more information see @cite RD05 . - */ -class CV_EXPORTS_W TonemapReinhard : public Tonemap -{ -public: - CV_WRAP virtual float getIntensity() const = 0; - CV_WRAP virtual void setIntensity(float intensity) = 0; - - CV_WRAP virtual float getLightAdaptation() const = 0; - CV_WRAP virtual void setLightAdaptation(float light_adapt) = 0; - - CV_WRAP virtual float getColorAdaptation() const = 0; - CV_WRAP virtual void setColorAdaptation(float color_adapt) = 0; -}; - -/** @brief Creates TonemapReinhard object - -@param gamma gamma value for gamma correction. See createTonemap -@param intensity result intensity in [-8, 8] range. Greater intensity produces brighter results. -@param light_adapt light adaptation in [0, 1] range. If 1 adaptation is based only on pixel -value, if 0 it's global, otherwise it's a weighted mean of this two cases. -@param color_adapt chromatic adaptation in [0, 1] range. If 1 channels are treated independently, -if 0 adaptation level is the same for each channel. - */ -CV_EXPORTS_W Ptr -createTonemapReinhard(float gamma = 1.0f, float intensity = 0.0f, float light_adapt = 1.0f, float color_adapt = 0.0f); - -/** @brief This algorithm transforms image to contrast using gradients on all levels of gaussian pyramid, -transforms contrast values to HVS response and scales the response. After this the image is -reconstructed from new contrast values. - -For more information see @cite MM06 . - */ -class CV_EXPORTS_W TonemapMantiuk : public Tonemap -{ -public: - CV_WRAP virtual float getScale() const = 0; - CV_WRAP virtual void setScale(float scale) = 0; - - CV_WRAP virtual float getSaturation() const = 0; - CV_WRAP virtual void setSaturation(float saturation) = 0; -}; - -/** @brief Creates TonemapMantiuk object - -@param gamma gamma value for gamma correction. See createTonemap -@param scale contrast scale factor. HVS response is multiplied by this parameter, thus compressing -dynamic range. Values from 0.6 to 0.9 produce best results. -@param saturation saturation enhancement value. See createTonemapDrago - */ -CV_EXPORTS_W Ptr -createTonemapMantiuk(float gamma = 1.0f, float scale = 0.7f, float saturation = 1.0f); - -/** @brief The base class for algorithms that align images of the same scene with different exposures - */ -class CV_EXPORTS_W AlignExposures : public Algorithm -{ -public: - /** @brief Aligns images - - @param src vector of input images - @param dst vector of aligned images - @param times vector of exposure time values for each image - @param response 256x1 matrix with inverse camera response function for each pixel value, it should - have the same number of channels as images. - */ - CV_WRAP virtual void process(InputArrayOfArrays src, std::vector& dst, - InputArray times, InputArray response) = 0; -}; - -/** @brief This algorithm converts images to median threshold bitmaps (1 for pixels brighter than median -luminance and 0 otherwise) and than aligns the resulting bitmaps using bit operations. - -It is invariant to exposure, so exposure values and camera response are not necessary. - -In this implementation new image regions are filled with zeros. - -For more information see @cite GW03 . - */ -class CV_EXPORTS_W AlignMTB : public AlignExposures -{ -public: - CV_WRAP virtual void process(InputArrayOfArrays src, std::vector& dst, - InputArray times, InputArray response) CV_OVERRIDE = 0; - - /** @brief Short version of process, that doesn't take extra arguments. - - @param src vector of input images - @param dst vector of aligned images - */ - CV_WRAP virtual void process(InputArrayOfArrays src, std::vector& dst) = 0; - - /** @brief Calculates shift between two images, i. e. how to shift the second image to correspond it with the - first. - - @param img0 first image - @param img1 second image - */ - CV_WRAP virtual Point calculateShift(InputArray img0, InputArray img1) = 0; - /** @brief Helper function, that shift Mat filling new regions with zeros. - - @param src input image - @param dst result image - @param shift shift value - */ - CV_WRAP virtual void shiftMat(InputArray src, OutputArray dst, const Point shift) = 0; - /** @brief Computes median threshold and exclude bitmaps of given image. - - @param img input image - @param tb median threshold bitmap - @param eb exclude bitmap - */ - CV_WRAP virtual void computeBitmaps(InputArray img, OutputArray tb, OutputArray eb) = 0; - - CV_WRAP virtual int getMaxBits() const = 0; - CV_WRAP virtual void setMaxBits(int max_bits) = 0; - - CV_WRAP virtual int getExcludeRange() const = 0; - CV_WRAP virtual void setExcludeRange(int exclude_range) = 0; - - CV_WRAP virtual bool getCut() const = 0; - CV_WRAP virtual void setCut(bool value) = 0; -}; - -/** @brief Creates AlignMTB object - -@param max_bits logarithm to the base 2 of maximal shift in each dimension. Values of 5 and 6 are -usually good enough (31 and 63 pixels shift respectively). -@param exclude_range range for exclusion bitmap that is constructed to suppress noise around the -median value. -@param cut if true cuts images, otherwise fills the new regions with zeros. - */ -CV_EXPORTS_W Ptr createAlignMTB(int max_bits = 6, int exclude_range = 4, bool cut = true); - -/** @brief The base class for camera response calibration algorithms. - */ -class CV_EXPORTS_W CalibrateCRF : public Algorithm -{ -public: - /** @brief Recovers inverse camera response. - - @param src vector of input images - @param dst 256x1 matrix with inverse camera response function - @param times vector of exposure time values for each image - */ - CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, InputArray times) = 0; -}; - -/** @brief Inverse camera response function is extracted for each brightness value by minimizing an objective -function as linear system. Objective function is constructed using pixel values on the same position -in all images, extra term is added to make the result smoother. - -For more information see @cite DM97 . - */ -class CV_EXPORTS_W CalibrateDebevec : public CalibrateCRF -{ -public: - CV_WRAP virtual float getLambda() const = 0; - CV_WRAP virtual void setLambda(float lambda) = 0; - - CV_WRAP virtual int getSamples() const = 0; - CV_WRAP virtual void setSamples(int samples) = 0; - - CV_WRAP virtual bool getRandom() const = 0; - CV_WRAP virtual void setRandom(bool random) = 0; -}; - -/** @brief Creates CalibrateDebevec object - -@param samples number of pixel locations to use -@param lambda smoothness term weight. Greater values produce smoother results, but can alter the -response. -@param random if true sample pixel locations are chosen at random, otherwise they form a -rectangular grid. - */ -CV_EXPORTS_W Ptr createCalibrateDebevec(int samples = 70, float lambda = 10.0f, bool random = false); - -/** @brief Inverse camera response function is extracted for each brightness value by minimizing an objective -function as linear system. This algorithm uses all image pixels. - -For more information see @cite RB99 . - */ -class CV_EXPORTS_W CalibrateRobertson : public CalibrateCRF -{ -public: - CV_WRAP virtual int getMaxIter() const = 0; - CV_WRAP virtual void setMaxIter(int max_iter) = 0; - - CV_WRAP virtual float getThreshold() const = 0; - CV_WRAP virtual void setThreshold(float threshold) = 0; - - CV_WRAP virtual Mat getRadiance() const = 0; -}; - -/** @brief Creates CalibrateRobertson object - -@param max_iter maximal number of Gauss-Seidel solver iterations. -@param threshold target difference between results of two successive steps of the minimization. - */ -CV_EXPORTS_W Ptr createCalibrateRobertson(int max_iter = 30, float threshold = 0.01f); - -/** @brief The base class algorithms that can merge exposure sequence to a single image. - */ -class CV_EXPORTS_W MergeExposures : public Algorithm -{ -public: - /** @brief Merges images. - - @param src vector of input images - @param dst result image - @param times vector of exposure time values for each image - @param response 256x1 matrix with inverse camera response function for each pixel value, it should - have the same number of channels as images. - */ - CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, - InputArray times, InputArray response) = 0; -}; - -/** @brief The resulting HDR image is calculated as weighted average of the exposures considering exposure -values and camera response. - -For more information see @cite DM97 . - */ -class CV_EXPORTS_W MergeDebevec : public MergeExposures -{ -public: - CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, - InputArray times, InputArray response) CV_OVERRIDE = 0; - CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, InputArray times) = 0; -}; - -/** @brief Creates MergeDebevec object - */ -CV_EXPORTS_W Ptr createMergeDebevec(); - -/** @brief Pixels are weighted using contrast, saturation and well-exposedness measures, than images are -combined using laplacian pyramids. - -The resulting image weight is constructed as weighted average of contrast, saturation and -well-exposedness measures. - -The resulting image doesn't require tonemapping and can be converted to 8-bit image by multiplying -by 255, but it's recommended to apply gamma correction and/or linear tonemapping. - -For more information see @cite MK07 . - */ -class CV_EXPORTS_W MergeMertens : public MergeExposures -{ -public: - CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, - InputArray times, InputArray response) CV_OVERRIDE = 0; - /** @brief Short version of process, that doesn't take extra arguments. - - @param src vector of input images - @param dst result image - */ - CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst) = 0; - - CV_WRAP virtual float getContrastWeight() const = 0; - CV_WRAP virtual void setContrastWeight(float contrast_weiht) = 0; - - CV_WRAP virtual float getSaturationWeight() const = 0; - CV_WRAP virtual void setSaturationWeight(float saturation_weight) = 0; - - CV_WRAP virtual float getExposureWeight() const = 0; - CV_WRAP virtual void setExposureWeight(float exposure_weight) = 0; -}; - -/** @brief Creates MergeMertens object - -@param contrast_weight contrast measure weight. See MergeMertens. -@param saturation_weight saturation measure weight -@param exposure_weight well-exposedness measure weight - */ -CV_EXPORTS_W Ptr -createMergeMertens(float contrast_weight = 1.0f, float saturation_weight = 1.0f, float exposure_weight = 0.0f); - -/** @brief The resulting HDR image is calculated as weighted average of the exposures considering exposure -values and camera response. - -For more information see @cite RB99 . - */ -class CV_EXPORTS_W MergeRobertson : public MergeExposures -{ -public: - CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, - InputArray times, InputArray response) CV_OVERRIDE = 0; - CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, InputArray times) = 0; -}; - -/** @brief Creates MergeRobertson object - */ -CV_EXPORTS_W Ptr createMergeRobertson(); - -//! @} photo_hdr - -//! @addtogroup photo_decolor -//! @{ - -/** @brief Transforms a color image to a grayscale image. It is a basic tool in digital printing, stylized -black-and-white photograph rendering, and in many single channel image processing applications -@cite CL12 . - -@param src Input 8-bit 3-channel image. -@param grayscale Output 8-bit 1-channel image. -@param color_boost Output 8-bit 3-channel image. - -This function is to be applied on color images. - */ -CV_EXPORTS_W void decolor( InputArray src, OutputArray grayscale, OutputArray color_boost); - -//! @} photo_decolor - -//! @addtogroup photo_clone -//! @{ - - -//! Flags for the seamlessClone algorithm -enum SeamlessCloneFlags -{ - /** - @brief Normal seamless cloning. - This method is ideal for inserting objects with complex outlines into a new background. - It preserves the original appearance and lighting of the inserted object, ensuring a natural blend. - */ - NORMAL_CLONE = 1, - - /** - @brief Mixed seamless cloning. - This method addresses cases where simple color-based selection or alpha masking is time-consuming - and may result in undesirable halos. By combining structure from the source and texture from the - destination, mixed seamless cloning is highly effective, even with loosely defined selections. - */ - MIXED_CLONE = 2, - - /** - @brief Monochrome transfer cloning. - This method allows users to replace specific features of an object, such as grayscale textures - or patterns, with alternative features. It is particularly useful for artistic effects or - targeted object modifications. - */ - MONOCHROME_TRANSFER = 3, - - /** - @brief Enhanced normal seamless cloning. - Similar to `NORMAL_CLONE`, but with an advanced approach to ROI (Region of Interest) calculation. - This mode processes a larger source region by considering the entire mask area instead of only - the bounding rectangle of non-zero pixels. - */ - NORMAL_CLONE_WIDE = 9, - - /** - @brief Enhanced mixed seamless cloning. - Similar to `MIXED_CLONE`, but with an advanced approach to ROI (Region of Interest) calculation. - This mode processes a larger source region by considering the entire mask area instead of only - the bounding rectangle of non-zero pixels. - */ - MIXED_CLONE_WIDE = 10, - - /** - @brief Enhanced monochrome transfer cloning. - Similar to `MONOCHROME_TRANSFER`, but with an advanced approach to ROI (Region of Interest) calculation. - This mode processes a larger source region by considering the entire mask area instead of only - the bounding rectangle of non-zero pixels. - */ - MONOCHROME_TRANSFER_WIDE = 11 -}; - - -/** @example samples/cpp/tutorial_code/photo/seamless_cloning/cloning_demo.cpp -An example using seamlessClone function -*/ -/** @brief Performs seamless cloning to blend a region from a source image into a destination image. -This function is designed for local image editing, allowing changes restricted to a region -(manually selected as the ROI) to be applied effortlessly and seamlessly. These changes can -range from slight distortions to complete replacement by novel content @cite PM03. - -@param src The source image (8-bit 3-channel), from which a region will be blended into the destination. -@param dst The destination image (8-bit 3-channel), where the src image will be blended. -@param mask A binary mask (8-bit, 1, 3, or 4-channel) specifying the region in the source image to blend. -Non-zero pixels indicate the region to be blended. If an empty Mat is provided, a mask with -all non-zero pixels is created internally. -@param p The point where the center of the src image is placed in the dst image. -@param blend The output image that stores the result of the seamless cloning. It has the same size and type as `dst`. -@param flags Flags that control the type of cloning method, can take values of `cv::SeamlessCloneFlags`. - */ -CV_EXPORTS_W void seamlessClone( InputArray src, InputArray dst, InputArray mask, Point p, - OutputArray blend, int flags); - -/** @brief Given an original color image, two differently colored versions of this image can be mixed -seamlessly. - -@param src Input 8-bit 3-channel image. -@param mask Input 8-bit 1 or 3-channel image. -@param dst Output image with the same size and type as src . -@param red_mul R-channel multiply factor. -@param green_mul G-channel multiply factor. -@param blue_mul B-channel multiply factor. - -Multiplication factor is between .5 to 2.5. - */ -CV_EXPORTS_W void colorChange(InputArray src, InputArray mask, OutputArray dst, float red_mul = 1.0f, - float green_mul = 1.0f, float blue_mul = 1.0f); - -/** @brief Applying an appropriate non-linear transformation to the gradient field inside the selection and -then integrating back with a Poisson solver, modifies locally the apparent illumination of an image. - -@param src Input 8-bit 3-channel image. -@param mask Input 8-bit 1 or 3-channel image. -@param dst Output image with the same size and type as src. -@param alpha Value ranges between 0-2. -@param beta Value ranges between 0-2. - -This is useful to highlight under-exposed foreground objects or to reduce specular reflections. - */ -CV_EXPORTS_W void illuminationChange(InputArray src, InputArray mask, OutputArray dst, - float alpha = 0.2f, float beta = 0.4f); - -/** @brief By retaining only the gradients at edge locations, before integrating with the Poisson solver, one -washes out the texture of the selected region, giving its contents a flat aspect. Here Canny Edge %Detector is used. - -@param src Input 8-bit 3-channel image. -@param mask Input 8-bit 1 or 3-channel image. -@param dst Output image with the same size and type as src. -@param low_threshold %Range from 0 to 100. -@param high_threshold Value \> 100. -@param kernel_size The size of the Sobel kernel to be used. - -@note -The algorithm assumes that the color of the source image is close to that of the destination. This -assumption means that when the colors don't match, the source image color gets tinted toward the -color of the destination image. - */ -CV_EXPORTS_W void textureFlattening(InputArray src, InputArray mask, OutputArray dst, - float low_threshold = 30, float high_threshold = 45, - int kernel_size = 3); - -//! @} photo_clone - -//! @addtogroup photo_render -//! @{ - -//! Edge preserving filters -enum -{ - RECURS_FILTER = 1, //!< Recursive Filtering - NORMCONV_FILTER = 2 //!< Normalized Convolution Filtering -}; - -/** @brief Filtering is the fundamental operation in image and video processing. Edge-preserving smoothing -filters are used in many different applications @cite EM11 . - -@param src Input 8-bit 3-channel image. -@param dst Output 8-bit 3-channel image. -@param flags Edge preserving filters: cv::RECURS_FILTER or cv::NORMCONV_FILTER -@param sigma_s %Range between 0 to 200. -@param sigma_r %Range between 0 to 1. - */ -CV_EXPORTS_W void edgePreservingFilter(InputArray src, OutputArray dst, int flags = 1, - float sigma_s = 60, float sigma_r = 0.4f); - -/** @brief This filter enhances the details of a particular image. - -@param src Input 8-bit 3-channel image. -@param dst Output image with the same size and type as src. -@param sigma_s %Range between 0 to 200. -@param sigma_r %Range between 0 to 1. - */ -CV_EXPORTS_W void detailEnhance(InputArray src, OutputArray dst, float sigma_s = 10, - float sigma_r = 0.15f); - -/** @example samples/cpp/tutorial_code/photo/non_photorealistic_rendering/npr_demo.cpp -An example using non-photorealistic line drawing functions -*/ -/** @brief Pencil-like non-photorealistic line drawing - -@param src Input 8-bit 3-channel image. -@param dst1 Output 8-bit 1-channel image. -@param dst2 Output image with the same size and type as src. -@param sigma_s %Range between 0 to 200. -@param sigma_r %Range between 0 to 1. -@param shade_factor %Range between 0 to 0.1. - */ -CV_EXPORTS_W void pencilSketch(InputArray src, OutputArray dst1, OutputArray dst2, - float sigma_s = 60, float sigma_r = 0.07f, float shade_factor = 0.02f); - -/** @brief Stylization aims to produce digital imagery with a wide variety of effects not focused on -photorealism. Edge-aware filters are ideal for stylization, as they can abstract regions of low -contrast while preserving, or enhancing, high-contrast features. - -@param src Input 8-bit 3-channel image. -@param dst Output image with the same size and type as src. -@param sigma_s %Range between 0 to 200. -@param sigma_r %Range between 0 to 1. - */ -CV_EXPORTS_W void stylization(InputArray src, OutputArray dst, float sigma_s = 60, - float sigma_r = 0.45f); - -//! @} photo_render - -//! @} photo - -} // cv - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2008-2012, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_PHOTO_HPP +#define OPENCV_PHOTO_HPP + +#include "opencv2/core.hpp" +#include "opencv2/imgproc.hpp" + +/** +@defgroup photo Computational Photography + +This module includes photo processing algorithms +@{ + @defgroup photo_inpaint Inpainting + @defgroup photo_denoise Denoising + @defgroup photo_hdr HDR imaging + + This section describes high dynamic range imaging algorithms namely tonemapping, exposure alignment, + camera calibration with multiple exposures and exposure fusion. + + @defgroup photo_decolor Contrast Preserving Decolorization + + Useful links: + + http://www.cse.cuhk.edu.hk/leojia/projects/color2gray/index.html + + @defgroup photo_clone Seamless Cloning + + Useful links: + + https://www.learnopencv.com/seamless-cloning-using-opencv-python-cpp + + @defgroup photo_render Non-Photorealistic Rendering + + Useful links: + + http://www.inf.ufrgs.br/~eslgastal/DomainTransform + + https://www.learnopencv.com/non-photorealistic-rendering-using-opencv-python-c/ + +@} + */ + +namespace cv +{ + +//! @addtogroup photo +//! @{ + +//! @addtogroup photo_inpaint +//! @{ +//! the inpainting algorithm +enum +{ + INPAINT_NS = 0, //!< Use Navier-Stokes based method + INPAINT_TELEA = 1 //!< Use the algorithm proposed by Alexandru Telea @cite Telea04 +}; + +/** @brief Restores the selected region in an image using the region neighborhood. + +@param src Input 8-bit, 16-bit unsigned or 32-bit float 1-channel or 8-bit 3-channel image. +@param inpaintMask Inpainting mask, 8-bit 1-channel image. Non-zero pixels indicate the area that +needs to be inpainted. +@param dst Output image with the same size and type as src . +@param inpaintRadius Radius of a circular neighborhood of each point inpainted that is considered +by the algorithm. +@param flags Inpainting method that could be cv::INPAINT_NS or cv::INPAINT_TELEA + +The function reconstructs the selected image area from the pixel near the area boundary. The +function may be used to remove dust and scratches from a scanned photo, or to remove undesirable +objects from still images or video. See for more details. + +@note + - An example using the inpainting technique can be found at + opencv_source_code/samples/cpp/inpaint.cpp + - (Python) An example using the inpainting technique can be found at + opencv_source_code/samples/python/inpaint.py + */ +CV_EXPORTS_W void inpaint( InputArray src, InputArray inpaintMask, + OutputArray dst, double inpaintRadius, int flags ); + +//! @} photo_inpaint + +//! @addtogroup photo_denoise +//! @{ + +/** @brief Perform image denoising using Non-local Means Denoising algorithm + with several computational +optimizations. Noise expected to be a gaussian white noise + +@param src Input 8-bit 1-channel, 2-channel, 3-channel or 4-channel image. +@param dst Output image with the same size and type as src . +@param templateWindowSize Size in pixels of the template patch that is used to compute weights. +Should be odd. Recommended value 7 pixels +@param searchWindowSize Size in pixels of the window that is used to compute weighted average for +given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater +denoising time. Recommended value 21 pixels +@param h Parameter regulating filter strength. Big h value perfectly removes noise but also +removes image details, smaller h value preserves details but also preserves some noise + +This function expected to be applied to grayscale images. For colored images look at +fastNlMeansDenoisingColored. Advanced usage of this functions can be manual denoising of colored +image in different colorspaces. Such approach is used in fastNlMeansDenoisingColored by converting +image to CIELAB colorspace and then separately denoise L and AB components with different h +parameter. + */ +CV_EXPORTS_W void fastNlMeansDenoising( InputArray src, OutputArray dst, float h = 3, + int templateWindowSize = 7, int searchWindowSize = 21); + +/** @brief Perform image denoising using Non-local Means Denoising algorithm + with several computational +optimizations. Noise expected to be a gaussian white noise + +@param src Input 8-bit or 16-bit (only with NORM_L1) 1-channel, +2-channel, 3-channel or 4-channel image. +@param dst Output image with the same size and type as src . +@param templateWindowSize Size in pixels of the template patch that is used to compute weights. +Should be odd. Recommended value 7 pixels +@param searchWindowSize Size in pixels of the window that is used to compute weighted average for +given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater +denoising time. Recommended value 21 pixels +@param h Array of parameters regulating filter strength, either one +parameter applied to all channels or one per channel in dst. Big h value +perfectly removes noise but also removes image details, smaller h +value preserves details but also preserves some noise +@param normType Type of norm used for weight calculation. Can be either NORM_L2 or NORM_L1 + +This function expected to be applied to grayscale images. For colored images look at +fastNlMeansDenoisingColored. Advanced usage of this functions can be manual denoising of colored +image in different colorspaces. Such approach is used in fastNlMeansDenoisingColored by converting +image to CIELAB colorspace and then separately denoise L and AB components with different h +parameter. + */ +CV_EXPORTS_W void fastNlMeansDenoising( InputArray src, OutputArray dst, + const std::vector& h, + int templateWindowSize = 7, int searchWindowSize = 21, + int normType = NORM_L2); + +/** @brief Modification of fastNlMeansDenoising function for colored images + +@param src Input 8-bit 3-channel image. +@param dst Output image with the same size and type as src . +@param templateWindowSize Size in pixels of the template patch that is used to compute weights. +Should be odd. Recommended value 7 pixels +@param searchWindowSize Size in pixels of the window that is used to compute weighted average for +given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater +denoising time. Recommended value 21 pixels +@param h Parameter regulating filter strength for luminance component. Bigger h value perfectly +removes noise but also removes image details, smaller h value preserves details but also preserves +some noise +@param hColor The same as h but for color components. For most images value equals 10 +will be enough to remove colored noise and do not distort colors + +The function converts image to CIELAB colorspace and then separately denoise L and AB components +with given h parameters using fastNlMeansDenoising function. + */ +CV_EXPORTS_W void fastNlMeansDenoisingColored( InputArray src, OutputArray dst, + float h = 3, float hColor = 3, + int templateWindowSize = 7, int searchWindowSize = 21); + +/** @brief Modification of fastNlMeansDenoising function for images sequence where consecutive images have been +captured in small period of time. For example video. This version of the function is for grayscale +images or for manual manipulation with colorspaces. See @cite Buades2005DenoisingIS for more details +(open access [here](https://static.aminer.org/pdf/PDF/000/317/196/spatio_temporal_wiener_filtering_of_image_sequences_using_a_parametric.pdf)). + +@param srcImgs Input 8-bit 1-channel, 2-channel, 3-channel or +4-channel images sequence. All images should have the same type and +size. +@param imgToDenoiseIndex Target image to denoise index in srcImgs sequence +@param temporalWindowSize Number of surrounding images to use for target image denoising. Should +be odd. Images from imgToDenoiseIndex - temporalWindowSize / 2 to +imgToDenoiseIndex + temporalWindowSize / 2 from srcImgs will be used to denoise +srcImgs[imgToDenoiseIndex] image. +@param dst Output image with the same size and type as srcImgs images. +@param templateWindowSize Size in pixels of the template patch that is used to compute weights. +Should be odd. Recommended value 7 pixels +@param searchWindowSize Size in pixels of the window that is used to compute weighted average for +given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater +denoising time. Recommended value 21 pixels +@param h Parameter regulating filter strength. Bigger h value +perfectly removes noise but also removes image details, smaller h +value preserves details but also preserves some noise + */ +CV_EXPORTS_W void fastNlMeansDenoisingMulti( InputArrayOfArrays srcImgs, OutputArray dst, + int imgToDenoiseIndex, int temporalWindowSize, + float h = 3, int templateWindowSize = 7, int searchWindowSize = 21); + +/** @brief Modification of fastNlMeansDenoising function for images sequence where consecutive images have been +captured in small period of time. For example video. This version of the function is for grayscale +images or for manual manipulation with colorspaces. See @cite Buades2005DenoisingIS for more details +(open access [here](https://static.aminer.org/pdf/PDF/000/317/196/spatio_temporal_wiener_filtering_of_image_sequences_using_a_parametric.pdf)). + +@param srcImgs Input 8-bit or 16-bit (only with NORM_L1) 1-channel, +2-channel, 3-channel or 4-channel images sequence. All images should +have the same type and size. +@param imgToDenoiseIndex Target image to denoise index in srcImgs sequence +@param temporalWindowSize Number of surrounding images to use for target image denoising. Should +be odd. Images from imgToDenoiseIndex - temporalWindowSize / 2 to +imgToDenoiseIndex + temporalWindowSize / 2 from srcImgs will be used to denoise +srcImgs[imgToDenoiseIndex] image. +@param dst Output image with the same size and type as srcImgs images. +@param templateWindowSize Size in pixels of the template patch that is used to compute weights. +Should be odd. Recommended value 7 pixels +@param searchWindowSize Size in pixels of the window that is used to compute weighted average for +given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater +denoising time. Recommended value 21 pixels +@param h Array of parameters regulating filter strength, either one +parameter applied to all channels or one per channel in dst. Big h value +perfectly removes noise but also removes image details, smaller h +value preserves details but also preserves some noise +@param normType Type of norm used for weight calculation. Can be either NORM_L2 or NORM_L1 + */ +CV_EXPORTS_W void fastNlMeansDenoisingMulti( InputArrayOfArrays srcImgs, OutputArray dst, + int imgToDenoiseIndex, int temporalWindowSize, + const std::vector& h, + int templateWindowSize = 7, int searchWindowSize = 21, + int normType = NORM_L2); + +/** @brief Modification of fastNlMeansDenoisingMulti function for colored images sequences + +@param srcImgs Input 8-bit 3-channel images sequence. All images should have the same type and +size. +@param imgToDenoiseIndex Target image to denoise index in srcImgs sequence +@param temporalWindowSize Number of surrounding images to use for target image denoising. Should +be odd. Images from imgToDenoiseIndex - temporalWindowSize / 2 to +imgToDenoiseIndex + temporalWindowSize / 2 from srcImgs will be used to denoise +srcImgs[imgToDenoiseIndex] image. +@param dst Output image with the same size and type as srcImgs images. +@param templateWindowSize Size in pixels of the template patch that is used to compute weights. +Should be odd. Recommended value 7 pixels +@param searchWindowSize Size in pixels of the window that is used to compute weighted average for +given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater +denoising time. Recommended value 21 pixels +@param h Parameter regulating filter strength for luminance component. Bigger h value perfectly +removes noise but also removes image details, smaller h value preserves details but also preserves +some noise. +@param hColor The same as h but for color components. + +The function converts images to CIELAB colorspace and then separately denoise L and AB components +with given h parameters using fastNlMeansDenoisingMulti function. + */ +CV_EXPORTS_W void fastNlMeansDenoisingColoredMulti( InputArrayOfArrays srcImgs, OutputArray dst, + int imgToDenoiseIndex, int temporalWindowSize, + float h = 3, float hColor = 3, + int templateWindowSize = 7, int searchWindowSize = 21); + +/** @brief Primal-dual algorithm is an algorithm for solving special types of variational problems (that is, +finding a function to minimize some functional). As the image denoising, in particular, may be seen +as the variational problem, primal-dual algorithm then can be used to perform denoising and this is +exactly what is implemented. + +It should be noted, that this implementation was taken from the July 2013 blog entry +@cite MA13 , which also contained (slightly more general) ready-to-use source code on Python. +Subsequently, that code was rewritten on C++ with the usage of openCV by Vadim Pisarevsky at the end +of July 2013 and finally it was slightly adapted by later authors. + +Although the thorough discussion and justification of the algorithm involved may be found in +@cite ChambolleEtAl, it might make sense to skim over it here, following @cite MA13 . To begin +with, we consider the 1-byte gray-level images as the functions from the rectangular domain of +pixels (it may be seen as set +\f$\left\{(x,y)\in\mathbb{N}\times\mathbb{N}\mid 1\leq x\leq n,\;1\leq y\leq m\right\}\f$ for some +\f$m,\;n\in\mathbb{N}\f$) into \f$\{0,1,\dots,255\}\f$. We shall denote the noised images as \f$f_i\f$ and with +this view, given some image \f$x\f$ of the same size, we may measure how bad it is by the formula + +\f[\left\|\left\|\nabla x\right\|\right\| + \lambda\sum_i\left\|\left\|x-f_i\right\|\right\|\f] + +\f$\|\|\cdot\|\|\f$ here denotes \f$L_2\f$-norm and as you see, the first addend states that we want our +image to be smooth (ideally, having zero gradient, thus being constant) and the second states that +we want our result to be close to the observations we've got. If we treat \f$x\f$ as a function, this is +exactly the functional what we seek to minimize and here the Primal-Dual algorithm comes into play. + +@param observations This array should contain one or more noised versions of the image that is to +be restored. +@param result Here the denoised image will be stored. There is no need to do pre-allocation of +storage space, as it will be automatically allocated, if necessary. +@param lambda Corresponds to \f$\lambda\f$ in the formulas above. As it is enlarged, the smooth +(blurred) images are treated more favorably than detailed (but maybe more noised) ones. Roughly +speaking, as it becomes smaller, the result will be more blur but more sever outliers will be +removed. +@param niters Number of iterations that the algorithm will run. Of course, as more iterations as +better, but it is hard to quantitatively refine this statement, so just use the default and +increase it if the results are poor. + */ +CV_EXPORTS_W void denoise_TVL1(const std::vector& observations,Mat& result, double lambda=1.0, int niters=30); + +//! @} photo_denoise + +//! @addtogroup photo_hdr +//! @{ + +enum { LDR_SIZE = 256 }; + +/** @brief Base class for tonemapping algorithms - tools that are used to map HDR image to 8-bit range. + */ +class CV_EXPORTS_W Tonemap : public Algorithm +{ +public: + /** @brief Tonemaps image + + @param src source image - CV_32FC3 Mat (float 32 bits 3 channels) + @param dst destination image - CV_32FC3 Mat with values in [0, 1] range + */ + CV_WRAP virtual void process(InputArray src, OutputArray dst) = 0; + + CV_WRAP virtual float getGamma() const = 0; + CV_WRAP virtual void setGamma(float gamma) = 0; +}; + +/** @brief Creates simple linear mapper with gamma correction + +@param gamma positive value for gamma correction. Gamma value of 1.0 implies no correction, gamma +equal to 2.2f is suitable for most displays. +Generally gamma \> 1 brightens the image and gamma \< 1 darkens it. + */ +CV_EXPORTS_W Ptr createTonemap(float gamma = 1.0f); + +/** @brief Adaptive logarithmic mapping is a fast global tonemapping algorithm that scales the image in +logarithmic domain. + +Since it's a global operator the same function is applied to all the pixels, it is controlled by the +bias parameter. + +Optional saturation enhancement is possible as described in @cite FL02 . + +For more information see @cite DM03 . + */ +class CV_EXPORTS_W TonemapDrago : public Tonemap +{ +public: + + CV_WRAP virtual float getSaturation() const = 0; + CV_WRAP virtual void setSaturation(float saturation) = 0; + + CV_WRAP virtual float getBias() const = 0; + CV_WRAP virtual void setBias(float bias) = 0; +}; + +/** @brief Creates TonemapDrago object + +@param gamma gamma value for gamma correction. See createTonemap +@param saturation positive saturation enhancement value. 1.0 preserves saturation, values greater +than 1 increase saturation and values less than 1 decrease it. +@param bias value for bias function in [0, 1] range. Values from 0.7 to 0.9 usually give best +results, default value is 0.85. + */ +CV_EXPORTS_W Ptr createTonemapDrago(float gamma = 1.0f, float saturation = 1.0f, float bias = 0.85f); + + +/** @brief This is a global tonemapping operator that models human visual system. + +Mapping function is controlled by adaptation parameter, that is computed using light adaptation and +color adaptation. + +For more information see @cite RD05 . + */ +class CV_EXPORTS_W TonemapReinhard : public Tonemap +{ +public: + CV_WRAP virtual float getIntensity() const = 0; + CV_WRAP virtual void setIntensity(float intensity) = 0; + + CV_WRAP virtual float getLightAdaptation() const = 0; + CV_WRAP virtual void setLightAdaptation(float light_adapt) = 0; + + CV_WRAP virtual float getColorAdaptation() const = 0; + CV_WRAP virtual void setColorAdaptation(float color_adapt) = 0; +}; + +/** @brief Creates TonemapReinhard object + +@param gamma gamma value for gamma correction. See createTonemap +@param intensity result intensity in [-8, 8] range. Greater intensity produces brighter results. +@param light_adapt light adaptation in [0, 1] range. If 1 adaptation is based only on pixel +value, if 0 it's global, otherwise it's a weighted mean of this two cases. +@param color_adapt chromatic adaptation in [0, 1] range. If 1 channels are treated independently, +if 0 adaptation level is the same for each channel. + */ +CV_EXPORTS_W Ptr +createTonemapReinhard(float gamma = 1.0f, float intensity = 0.0f, float light_adapt = 1.0f, float color_adapt = 0.0f); + +/** @brief This algorithm transforms image to contrast using gradients on all levels of gaussian pyramid, +transforms contrast values to HVS response and scales the response. After this the image is +reconstructed from new contrast values. + +For more information see @cite MM06 . + */ +class CV_EXPORTS_W TonemapMantiuk : public Tonemap +{ +public: + CV_WRAP virtual float getScale() const = 0; + CV_WRAP virtual void setScale(float scale) = 0; + + CV_WRAP virtual float getSaturation() const = 0; + CV_WRAP virtual void setSaturation(float saturation) = 0; +}; + +/** @brief Creates TonemapMantiuk object + +@param gamma gamma value for gamma correction. See createTonemap +@param scale contrast scale factor. HVS response is multiplied by this parameter, thus compressing +dynamic range. Values from 0.6 to 0.9 produce best results. +@param saturation saturation enhancement value. See createTonemapDrago + */ +CV_EXPORTS_W Ptr +createTonemapMantiuk(float gamma = 1.0f, float scale = 0.7f, float saturation = 1.0f); + +/** @brief The base class for algorithms that align images of the same scene with different exposures + */ +class CV_EXPORTS_W AlignExposures : public Algorithm +{ +public: + /** @brief Aligns images + + @param src vector of input images + @param dst vector of aligned images + @param times vector of exposure time values for each image + @param response 256x1 matrix with inverse camera response function for each pixel value, it should + have the same number of channels as images. + */ + CV_WRAP virtual void process(InputArrayOfArrays src, std::vector& dst, + InputArray times, InputArray response) = 0; +}; + +/** @brief This algorithm converts images to median threshold bitmaps (1 for pixels brighter than median +luminance and 0 otherwise) and than aligns the resulting bitmaps using bit operations. + +It is invariant to exposure, so exposure values and camera response are not necessary. + +In this implementation new image regions are filled with zeros. + +For more information see @cite GW03 . + */ +class CV_EXPORTS_W AlignMTB : public AlignExposures +{ +public: + CV_WRAP virtual void process(InputArrayOfArrays src, std::vector& dst, + InputArray times, InputArray response) CV_OVERRIDE = 0; + + /** @brief Short version of process, that doesn't take extra arguments. + + @param src vector of input images + @param dst vector of aligned images + */ + CV_WRAP virtual void process(InputArrayOfArrays src, std::vector& dst) = 0; + + /** @brief Calculates shift between two images, i. e. how to shift the second image to correspond it with the + first. + + @param img0 first image + @param img1 second image + */ + CV_WRAP virtual Point calculateShift(InputArray img0, InputArray img1) = 0; + /** @brief Helper function, that shift Mat filling new regions with zeros. + + @param src input image + @param dst result image + @param shift shift value + */ + CV_WRAP virtual void shiftMat(InputArray src, OutputArray dst, const Point shift) = 0; + /** @brief Computes median threshold and exclude bitmaps of given image. + + @param img input image + @param tb median threshold bitmap + @param eb exclude bitmap + */ + CV_WRAP virtual void computeBitmaps(InputArray img, OutputArray tb, OutputArray eb) = 0; + + CV_WRAP virtual int getMaxBits() const = 0; + CV_WRAP virtual void setMaxBits(int max_bits) = 0; + + CV_WRAP virtual int getExcludeRange() const = 0; + CV_WRAP virtual void setExcludeRange(int exclude_range) = 0; + + CV_WRAP virtual bool getCut() const = 0; + CV_WRAP virtual void setCut(bool value) = 0; +}; + +/** @brief Creates AlignMTB object + +@param max_bits logarithm to the base 2 of maximal shift in each dimension. Values of 5 and 6 are +usually good enough (31 and 63 pixels shift respectively). +@param exclude_range range for exclusion bitmap that is constructed to suppress noise around the +median value. +@param cut if true cuts images, otherwise fills the new regions with zeros. + */ +CV_EXPORTS_W Ptr createAlignMTB(int max_bits = 6, int exclude_range = 4, bool cut = true); + +/** @brief The base class for camera response calibration algorithms. + */ +class CV_EXPORTS_W CalibrateCRF : public Algorithm +{ +public: + /** @brief Recovers inverse camera response. + + @param src vector of input images + @param dst 256x1 matrix with inverse camera response function + @param times vector of exposure time values for each image + */ + CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, InputArray times) = 0; +}; + +/** @brief Inverse camera response function is extracted for each brightness value by minimizing an objective +function as linear system. Objective function is constructed using pixel values on the same position +in all images, extra term is added to make the result smoother. + +For more information see @cite DM97 . + */ +class CV_EXPORTS_W CalibrateDebevec : public CalibrateCRF +{ +public: + CV_WRAP virtual float getLambda() const = 0; + CV_WRAP virtual void setLambda(float lambda) = 0; + + CV_WRAP virtual int getSamples() const = 0; + CV_WRAP virtual void setSamples(int samples) = 0; + + CV_WRAP virtual bool getRandom() const = 0; + CV_WRAP virtual void setRandom(bool random) = 0; +}; + +/** @brief Creates CalibrateDebevec object + +@param samples number of pixel locations to use +@param lambda smoothness term weight. Greater values produce smoother results, but can alter the +response. +@param random if true sample pixel locations are chosen at random, otherwise they form a +rectangular grid. + */ +CV_EXPORTS_W Ptr createCalibrateDebevec(int samples = 70, float lambda = 10.0f, bool random = false); + +/** @brief Inverse camera response function is extracted for each brightness value by minimizing an objective +function as linear system. This algorithm uses all image pixels. + +For more information see @cite RB99 . + */ +class CV_EXPORTS_W CalibrateRobertson : public CalibrateCRF +{ +public: + CV_WRAP virtual int getMaxIter() const = 0; + CV_WRAP virtual void setMaxIter(int max_iter) = 0; + + CV_WRAP virtual float getThreshold() const = 0; + CV_WRAP virtual void setThreshold(float threshold) = 0; + + CV_WRAP virtual Mat getRadiance() const = 0; +}; + +/** @brief Creates CalibrateRobertson object + +@param max_iter maximal number of Gauss-Seidel solver iterations. +@param threshold target difference between results of two successive steps of the minimization. + */ +CV_EXPORTS_W Ptr createCalibrateRobertson(int max_iter = 30, float threshold = 0.01f); + +/** @brief The base class algorithms that can merge exposure sequence to a single image. + */ +class CV_EXPORTS_W MergeExposures : public Algorithm +{ +public: + /** @brief Merges images. + + @param src vector of input images + @param dst result image + @param times vector of exposure time values for each image + @param response 256x1 matrix with inverse camera response function for each pixel value, it should + have the same number of channels as images. + */ + CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, + InputArray times, InputArray response) = 0; +}; + +/** @brief The resulting HDR image is calculated as weighted average of the exposures considering exposure +values and camera response. + +For more information see @cite DM97 . + */ +class CV_EXPORTS_W MergeDebevec : public MergeExposures +{ +public: + CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, + InputArray times, InputArray response) CV_OVERRIDE = 0; + CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, InputArray times) = 0; +}; + +/** @brief Creates MergeDebevec object + */ +CV_EXPORTS_W Ptr createMergeDebevec(); + +/** @brief Pixels are weighted using contrast, saturation and well-exposedness measures, than images are +combined using laplacian pyramids. + +The resulting image weight is constructed as weighted average of contrast, saturation and +well-exposedness measures. + +The resulting image doesn't require tonemapping and can be converted to 8-bit image by multiplying +by 255, but it's recommended to apply gamma correction and/or linear tonemapping. + +For more information see @cite MK07 . + */ +class CV_EXPORTS_W MergeMertens : public MergeExposures +{ +public: + CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, + InputArray times, InputArray response) CV_OVERRIDE = 0; + /** @brief Short version of process, that doesn't take extra arguments. + + @param src vector of input images + @param dst result image + */ + CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst) = 0; + + CV_WRAP virtual float getContrastWeight() const = 0; + CV_WRAP virtual void setContrastWeight(float contrast_weiht) = 0; + + CV_WRAP virtual float getSaturationWeight() const = 0; + CV_WRAP virtual void setSaturationWeight(float saturation_weight) = 0; + + CV_WRAP virtual float getExposureWeight() const = 0; + CV_WRAP virtual void setExposureWeight(float exposure_weight) = 0; +}; + +/** @brief Creates MergeMertens object + +@param contrast_weight contrast measure weight. See MergeMertens. +@param saturation_weight saturation measure weight +@param exposure_weight well-exposedness measure weight + */ +CV_EXPORTS_W Ptr +createMergeMertens(float contrast_weight = 1.0f, float saturation_weight = 1.0f, float exposure_weight = 0.0f); + +/** @brief The resulting HDR image is calculated as weighted average of the exposures considering exposure +values and camera response. + +For more information see @cite RB99 . + */ +class CV_EXPORTS_W MergeRobertson : public MergeExposures +{ +public: + CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, + InputArray times, InputArray response) CV_OVERRIDE = 0; + CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, InputArray times) = 0; +}; + +/** @brief Creates MergeRobertson object + */ +CV_EXPORTS_W Ptr createMergeRobertson(); + +//! @} photo_hdr + +//! @addtogroup photo_decolor +//! @{ + +/** @brief Transforms a color image to a grayscale image. It is a basic tool in digital printing, stylized +black-and-white photograph rendering, and in many single channel image processing applications +@cite CL12 . + +@param src Input 8-bit 3-channel image. +@param grayscale Output 8-bit 1-channel image. +@param color_boost Output 8-bit 3-channel image. + +This function is to be applied on color images. + */ +CV_EXPORTS_W void decolor( InputArray src, OutputArray grayscale, OutputArray color_boost); + +//! @} photo_decolor + +//! @addtogroup photo_clone +//! @{ + + +//! Flags for the seamlessClone algorithm +enum SeamlessCloneFlags +{ + /** + @brief Normal seamless cloning. + This method is ideal for inserting objects with complex outlines into a new background. + It preserves the original appearance and lighting of the inserted object, ensuring a natural blend. + */ + NORMAL_CLONE = 1, + + /** + @brief Mixed seamless cloning. + This method addresses cases where simple color-based selection or alpha masking is time-consuming + and may result in undesirable halos. By combining structure from the source and texture from the + destination, mixed seamless cloning is highly effective, even with loosely defined selections. + */ + MIXED_CLONE = 2, + + /** + @brief Monochrome transfer cloning. + This method allows users to replace specific features of an object, such as grayscale textures + or patterns, with alternative features. It is particularly useful for artistic effects or + targeted object modifications. + */ + MONOCHROME_TRANSFER = 3, + + /** + @brief Enhanced normal seamless cloning. + Similar to `NORMAL_CLONE`, but with an advanced approach to ROI (Region of Interest) calculation. + This mode processes a larger source region by considering the entire mask area instead of only + the bounding rectangle of non-zero pixels. + */ + NORMAL_CLONE_WIDE = 9, + + /** + @brief Enhanced mixed seamless cloning. + Similar to `MIXED_CLONE`, but with an advanced approach to ROI (Region of Interest) calculation. + This mode processes a larger source region by considering the entire mask area instead of only + the bounding rectangle of non-zero pixels. + */ + MIXED_CLONE_WIDE = 10, + + /** + @brief Enhanced monochrome transfer cloning. + Similar to `MONOCHROME_TRANSFER`, but with an advanced approach to ROI (Region of Interest) calculation. + This mode processes a larger source region by considering the entire mask area instead of only + the bounding rectangle of non-zero pixels. + */ + MONOCHROME_TRANSFER_WIDE = 11 +}; + + +/** @example samples/cpp/tutorial_code/photo/seamless_cloning/cloning_demo.cpp +An example using seamlessClone function +*/ +/** @brief Performs seamless cloning to blend a region from a source image into a destination image. +This function is designed for local image editing, allowing changes restricted to a region +(manually selected as the ROI) to be applied effortlessly and seamlessly. These changes can +range from slight distortions to complete replacement by novel content @cite PM03. + +@param src The source image (8-bit 3-channel), from which a region will be blended into the destination. +@param dst The destination image (8-bit 3-channel), where the src image will be blended. +@param mask A binary mask (8-bit, 1, 3, or 4-channel) specifying the region in the source image to blend. +Non-zero pixels indicate the region to be blended. If an empty Mat is provided, a mask with +all non-zero pixels is created internally. +@param p The point where the center of the src image is placed in the dst image. +@param blend The output image that stores the result of the seamless cloning. It has the same size and type as `dst`. +@param flags Flags that control the type of cloning method, can take values of `cv::SeamlessCloneFlags`. + */ +CV_EXPORTS_W void seamlessClone( InputArray src, InputArray dst, InputArray mask, Point p, + OutputArray blend, int flags); + +/** @brief Given an original color image, two differently colored versions of this image can be mixed +seamlessly. + +@param src Input 8-bit 3-channel image. +@param mask Input 8-bit 1 or 3-channel image. +@param dst Output image with the same size and type as src . +@param red_mul R-channel multiply factor. +@param green_mul G-channel multiply factor. +@param blue_mul B-channel multiply factor. + +Multiplication factor is between .5 to 2.5. + */ +CV_EXPORTS_W void colorChange(InputArray src, InputArray mask, OutputArray dst, float red_mul = 1.0f, + float green_mul = 1.0f, float blue_mul = 1.0f); + +/** @brief Applying an appropriate non-linear transformation to the gradient field inside the selection and +then integrating back with a Poisson solver, modifies locally the apparent illumination of an image. + +@param src Input 8-bit 3-channel image. +@param mask Input 8-bit 1 or 3-channel image. +@param dst Output image with the same size and type as src. +@param alpha Value ranges between 0-2. +@param beta Value ranges between 0-2. + +This is useful to highlight under-exposed foreground objects or to reduce specular reflections. + */ +CV_EXPORTS_W void illuminationChange(InputArray src, InputArray mask, OutputArray dst, + float alpha = 0.2f, float beta = 0.4f); + +/** @brief By retaining only the gradients at edge locations, before integrating with the Poisson solver, one +washes out the texture of the selected region, giving its contents a flat aspect. Here Canny Edge %Detector is used. + +@param src Input 8-bit 3-channel image. +@param mask Input 8-bit 1 or 3-channel image. +@param dst Output image with the same size and type as src. +@param low_threshold %Range from 0 to 100. +@param high_threshold Value \> 100. +@param kernel_size The size of the Sobel kernel to be used. + +@note +The algorithm assumes that the color of the source image is close to that of the destination. This +assumption means that when the colors don't match, the source image color gets tinted toward the +color of the destination image. + */ +CV_EXPORTS_W void textureFlattening(InputArray src, InputArray mask, OutputArray dst, + float low_threshold = 30, float high_threshold = 45, + int kernel_size = 3); + +//! @} photo_clone + +//! @addtogroup photo_render +//! @{ + +//! Edge preserving filters +enum +{ + RECURS_FILTER = 1, //!< Recursive Filtering + NORMCONV_FILTER = 2 //!< Normalized Convolution Filtering +}; + +/** @brief Filtering is the fundamental operation in image and video processing. Edge-preserving smoothing +filters are used in many different applications @cite EM11 . + +@param src Input 8-bit 3-channel image. +@param dst Output 8-bit 3-channel image. +@param flags Edge preserving filters: cv::RECURS_FILTER or cv::NORMCONV_FILTER +@param sigma_s %Range between 0 to 200. +@param sigma_r %Range between 0 to 1. + */ +CV_EXPORTS_W void edgePreservingFilter(InputArray src, OutputArray dst, int flags = 1, + float sigma_s = 60, float sigma_r = 0.4f); + +/** @brief This filter enhances the details of a particular image. + +@param src Input 8-bit 3-channel image. +@param dst Output image with the same size and type as src. +@param sigma_s %Range between 0 to 200. +@param sigma_r %Range between 0 to 1. + */ +CV_EXPORTS_W void detailEnhance(InputArray src, OutputArray dst, float sigma_s = 10, + float sigma_r = 0.15f); + +/** @example samples/cpp/tutorial_code/photo/non_photorealistic_rendering/npr_demo.cpp +An example using non-photorealistic line drawing functions +*/ +/** @brief Pencil-like non-photorealistic line drawing + +@param src Input 8-bit 3-channel image. +@param dst1 Output 8-bit 1-channel image. +@param dst2 Output image with the same size and type as src. +@param sigma_s %Range between 0 to 200. +@param sigma_r %Range between 0 to 1. +@param shade_factor %Range between 0 to 0.1. + */ +CV_EXPORTS_W void pencilSketch(InputArray src, OutputArray dst1, OutputArray dst2, + float sigma_s = 60, float sigma_r = 0.07f, float shade_factor = 0.02f); + +/** @brief Stylization aims to produce digital imagery with a wide variety of effects not focused on +photorealism. Edge-aware filters are ideal for stylization, as they can abstract regions of low +contrast while preserving, or enhancing, high-contrast features. + +@param src Input 8-bit 3-channel image. +@param dst Output image with the same size and type as src. +@param sigma_s %Range between 0 to 200. +@param sigma_r %Range between 0 to 1. + */ +CV_EXPORTS_W void stylization(InputArray src, OutputArray dst, float sigma_s = 60, + float sigma_r = 0.45f); + +//! @} photo_render + +//! @} photo + +} // cv + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/photo/cuda.hpp b/3rdParty/opencv-4.11.0/opencv2/photo/cuda.hpp index 709ad2d26f..cb1dd9caff 100644 --- a/3rdParty/opencv-4.11.0/opencv2/photo/cuda.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/photo/cuda.hpp @@ -1,157 +1,157 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2008-2012, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_PHOTO_CUDA_HPP -#define OPENCV_PHOTO_CUDA_HPP - -#include "opencv2/core/cuda.hpp" - -namespace cv { namespace cuda { - -//! @addtogroup photo_denoise -//! @{ - -/** @brief Performs pure non local means denoising without any simplification, and thus it is not fast. - -@param src Source image. Supports only CV_8UC1, CV_8UC2 and CV_8UC3. -@param dst Destination image. -@param h Filter sigma regulating filter strength for color. -@param search_window Size of search window. -@param block_size Size of block used for computing weights. -@param borderMode Border type. See borderInterpolate for details. BORDER_REFLECT101 , -BORDER_REPLICATE , BORDER_CONSTANT , BORDER_REFLECT and BORDER_WRAP are supported for now. -@param stream Stream for the asynchronous version. - -@sa - fastNlMeansDenoising - */ -CV_EXPORTS void nonLocalMeans(InputArray src, OutputArray dst, - float h, - int search_window = 21, - int block_size = 7, - int borderMode = BORDER_DEFAULT, - Stream& stream = Stream::Null()); -CV_WRAP inline void nonLocalMeans(const GpuMat& src, CV_OUT GpuMat& dst, - float h, - int search_window = 21, - int block_size = 7, - int borderMode = BORDER_DEFAULT, - Stream& stream = Stream::Null()) -{ - nonLocalMeans(InputArray(src), OutputArray(dst), h, search_window, block_size, borderMode, stream); -} - -/** @brief Perform image denoising using Non-local Means Denoising algorithm - with several computational -optimizations. Noise expected to be a gaussian white noise - -@param src Input 8-bit 1-channel, 2-channel or 3-channel image. -@param dst Output image with the same size and type as src . -@param h Parameter regulating filter strength. Big h value perfectly removes noise but also -removes image details, smaller h value preserves details but also preserves some noise -@param search_window Size in pixels of the window that is used to compute weighted average for -given pixel. Should be odd. Affect performance linearly: greater search_window - greater -denoising time. Recommended value 21 pixels -@param block_size Size in pixels of the template patch that is used to compute weights. Should be -odd. Recommended value 7 pixels -@param stream Stream for the asynchronous invocations. - -This function expected to be applied to grayscale images. For colored images look at -FastNonLocalMeansDenoising::labMethod. - -@sa - fastNlMeansDenoising - */ -CV_EXPORTS void fastNlMeansDenoising(InputArray src, OutputArray dst, - float h, - int search_window = 21, - int block_size = 7, - Stream& stream = Stream::Null()); -CV_WRAP inline void fastNlMeansDenoising(const GpuMat& src, CV_OUT GpuMat& dst, - float h, - int search_window = 21, - int block_size = 7, - Stream& stream = Stream::Null()) -{ - fastNlMeansDenoising(InputArray(src), OutputArray(dst), h, search_window, block_size, stream); -} - -/** @brief Modification of fastNlMeansDenoising function for colored images - -@param src Input 8-bit 3-channel image. -@param dst Output image with the same size and type as src . -@param h_luminance Parameter regulating filter strength. Big h value perfectly removes noise but -also removes image details, smaller h value preserves details but also preserves some noise -@param photo_render float The same as h but for color components. For most images value equals 10 will be -enough to remove colored noise and do not distort colors -@param search_window Size in pixels of the window that is used to compute weighted average for -given pixel. Should be odd. Affect performance linearly: greater search_window - greater -denoising time. Recommended value 21 pixels -@param block_size Size in pixels of the template patch that is used to compute weights. Should be -odd. Recommended value 7 pixels -@param stream Stream for the asynchronous invocations. - -The function converts image to CIELAB colorspace and then separately denoise L and AB components -with given h parameters using FastNonLocalMeansDenoising::simpleMethod function. - -@sa - fastNlMeansDenoisingColored - */ -CV_EXPORTS void fastNlMeansDenoisingColored(InputArray src, OutputArray dst, - float h_luminance, float photo_render, - int search_window = 21, - int block_size = 7, - Stream& stream = Stream::Null()); -CV_WRAP inline void fastNlMeansDenoisingColored(const GpuMat& src, CV_OUT GpuMat& dst, - float h_luminance, float photo_render, - int search_window = 21, - int block_size = 7, - Stream& stream = Stream::Null()) -{ - fastNlMeansDenoisingColored(InputArray(src), OutputArray(dst), h_luminance, photo_render, search_window, block_size, stream); -} - -//! @} photo - -}} // namespace cv { namespace cuda { - -#endif /* OPENCV_PHOTO_CUDA_HPP */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2008-2012, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_PHOTO_CUDA_HPP +#define OPENCV_PHOTO_CUDA_HPP + +#include "opencv2/core/cuda.hpp" + +namespace cv { namespace cuda { + +//! @addtogroup photo_denoise +//! @{ + +/** @brief Performs pure non local means denoising without any simplification, and thus it is not fast. + +@param src Source image. Supports only CV_8UC1, CV_8UC2 and CV_8UC3. +@param dst Destination image. +@param h Filter sigma regulating filter strength for color. +@param search_window Size of search window. +@param block_size Size of block used for computing weights. +@param borderMode Border type. See borderInterpolate for details. BORDER_REFLECT101 , +BORDER_REPLICATE , BORDER_CONSTANT , BORDER_REFLECT and BORDER_WRAP are supported for now. +@param stream Stream for the asynchronous version. + +@sa + fastNlMeansDenoising + */ +CV_EXPORTS void nonLocalMeans(InputArray src, OutputArray dst, + float h, + int search_window = 21, + int block_size = 7, + int borderMode = BORDER_DEFAULT, + Stream& stream = Stream::Null()); +CV_WRAP inline void nonLocalMeans(const GpuMat& src, CV_OUT GpuMat& dst, + float h, + int search_window = 21, + int block_size = 7, + int borderMode = BORDER_DEFAULT, + Stream& stream = Stream::Null()) +{ + nonLocalMeans(InputArray(src), OutputArray(dst), h, search_window, block_size, borderMode, stream); +} + +/** @brief Perform image denoising using Non-local Means Denoising algorithm + with several computational +optimizations. Noise expected to be a gaussian white noise + +@param src Input 8-bit 1-channel, 2-channel or 3-channel image. +@param dst Output image with the same size and type as src . +@param h Parameter regulating filter strength. Big h value perfectly removes noise but also +removes image details, smaller h value preserves details but also preserves some noise +@param search_window Size in pixels of the window that is used to compute weighted average for +given pixel. Should be odd. Affect performance linearly: greater search_window - greater +denoising time. Recommended value 21 pixels +@param block_size Size in pixels of the template patch that is used to compute weights. Should be +odd. Recommended value 7 pixels +@param stream Stream for the asynchronous invocations. + +This function expected to be applied to grayscale images. For colored images look at +FastNonLocalMeansDenoising::labMethod. + +@sa + fastNlMeansDenoising + */ +CV_EXPORTS void fastNlMeansDenoising(InputArray src, OutputArray dst, + float h, + int search_window = 21, + int block_size = 7, + Stream& stream = Stream::Null()); +CV_WRAP inline void fastNlMeansDenoising(const GpuMat& src, CV_OUT GpuMat& dst, + float h, + int search_window = 21, + int block_size = 7, + Stream& stream = Stream::Null()) +{ + fastNlMeansDenoising(InputArray(src), OutputArray(dst), h, search_window, block_size, stream); +} + +/** @brief Modification of fastNlMeansDenoising function for colored images + +@param src Input 8-bit 3-channel image. +@param dst Output image with the same size and type as src . +@param h_luminance Parameter regulating filter strength. Big h value perfectly removes noise but +also removes image details, smaller h value preserves details but also preserves some noise +@param photo_render float The same as h but for color components. For most images value equals 10 will be +enough to remove colored noise and do not distort colors +@param search_window Size in pixels of the window that is used to compute weighted average for +given pixel. Should be odd. Affect performance linearly: greater search_window - greater +denoising time. Recommended value 21 pixels +@param block_size Size in pixels of the template patch that is used to compute weights. Should be +odd. Recommended value 7 pixels +@param stream Stream for the asynchronous invocations. + +The function converts image to CIELAB colorspace and then separately denoise L and AB components +with given h parameters using FastNonLocalMeansDenoising::simpleMethod function. + +@sa + fastNlMeansDenoisingColored + */ +CV_EXPORTS void fastNlMeansDenoisingColored(InputArray src, OutputArray dst, + float h_luminance, float photo_render, + int search_window = 21, + int block_size = 7, + Stream& stream = Stream::Null()); +CV_WRAP inline void fastNlMeansDenoisingColored(const GpuMat& src, CV_OUT GpuMat& dst, + float h_luminance, float photo_render, + int search_window = 21, + int block_size = 7, + Stream& stream = Stream::Null()) +{ + fastNlMeansDenoisingColored(InputArray(src), OutputArray(dst), h_luminance, photo_render, search_window, block_size, stream); +} + +//! @} photo + +}} // namespace cv { namespace cuda { + +#endif /* OPENCV_PHOTO_CUDA_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/photo/legacy/constants_c.h b/3rdParty/opencv-4.11.0/opencv2/photo/legacy/constants_c.h index ec1d4403fd..84515ca3b4 100644 --- a/3rdParty/opencv-4.11.0/opencv2/photo/legacy/constants_c.h +++ b/3rdParty/opencv-4.11.0/opencv2/photo/legacy/constants_c.h @@ -1,14 +1,14 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_PHOTO_LEGACY_CONSTANTS_H -#define OPENCV_PHOTO_LEGACY_CONSTANTS_H - -enum InpaintingModes -{ - CV_INPAINT_NS =0, - CV_INPAINT_TELEA =1 -}; - -#endif // OPENCV_PHOTO_LEGACY_CONSTANTS_H +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_PHOTO_LEGACY_CONSTANTS_H +#define OPENCV_PHOTO_LEGACY_CONSTANTS_H + +enum InpaintingModes +{ + CV_INPAINT_NS =0, + CV_INPAINT_TELEA =1 +}; + +#endif // OPENCV_PHOTO_LEGACY_CONSTANTS_H diff --git a/3rdParty/opencv-4.11.0/opencv2/photo/photo.hpp b/3rdParty/opencv-4.11.0/opencv2/photo/photo.hpp index 8af5e9f0fa..96d4b3bfa9 100644 --- a/3rdParty/opencv-4.11.0/opencv2/photo/photo.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/photo/photo.hpp @@ -1,48 +1,48 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifdef __OPENCV_BUILD -#error this is a compatibility header which should not be used inside the OpenCV library -#endif - -#include "opencv2/photo.hpp" +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/photo.hpp" diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching.hpp index 41f0550618..b38210d9d4 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching.hpp @@ -1,370 +1,370 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_STITCHING_STITCHER_HPP -#define OPENCV_STITCHING_STITCHER_HPP - -#include "opencv2/core.hpp" -#include "opencv2/features2d.hpp" -#include "opencv2/stitching/warpers.hpp" -#include "opencv2/stitching/detail/matchers.hpp" -#include "opencv2/stitching/detail/motion_estimators.hpp" -#include "opencv2/stitching/detail/exposure_compensate.hpp" -#include "opencv2/stitching/detail/seam_finders.hpp" -#include "opencv2/stitching/detail/blenders.hpp" -#include "opencv2/stitching/detail/camera.hpp" - - -#if defined(Status) -# warning Detected X11 'Status' macro definition, it can cause build conflicts. Please, include this header before any X11 headers. -#endif - - -/** -@defgroup stitching Images stitching - -This figure illustrates the stitching module pipeline implemented in the Stitcher class. Using that -class it's possible to configure/remove some steps, i.e. adjust the stitching pipeline according to -the particular needs. All building blocks from the pipeline are available in the detail namespace, -one can combine and use them separately. - -The implemented stitching pipeline is very similar to the one proposed in @cite BL07 . - -![stitching pipeline](StitchingPipeline.jpg) - -Camera models -------------- - -There are currently 2 camera models implemented in stitching pipeline. - -- _Homography model_ expecting perspective transformations between images - implemented in @ref cv::detail::BestOf2NearestMatcher cv::detail::HomographyBasedEstimator - cv::detail::BundleAdjusterReproj cv::detail::BundleAdjusterRay -- _Affine model_ expecting affine transformation with 6 DOF or 4 DOF implemented in - @ref cv::detail::AffineBestOf2NearestMatcher cv::detail::AffineBasedEstimator - cv::detail::BundleAdjusterAffine cv::detail::BundleAdjusterAffinePartial cv::AffineWarper - -Homography model is useful for creating photo panoramas captured by camera, -while affine-based model can be used to stitch scans and object captured by -specialized devices. Use @ref cv::Stitcher::create to get preconfigured pipeline for one -of those models. - -@note -Certain detailed settings of @ref cv::Stitcher might not make sense. Especially -you should not mix classes implementing affine model and classes implementing -Homography model, as they work with different transformations. - -@{ - @defgroup stitching_match Features Finding and Images Matching - @defgroup stitching_rotation Rotation Estimation - @defgroup stitching_autocalib Autocalibration - @defgroup stitching_warp Images Warping - @defgroup stitching_seam Seam Estimation - @defgroup stitching_exposure Exposure Compensation - @defgroup stitching_blend Image Blenders -@} - */ - -namespace cv { - -//! @addtogroup stitching -//! @{ - -/** @example samples/cpp/stitching.cpp -A basic example on image stitching -*/ - -/** @example samples/python/stitching.py -A basic example on image stitching in Python. -*/ - -/** @example samples/cpp/stitching_detailed.cpp -A detailed example on image stitching -*/ - -/** @brief High level image stitcher. - -It's possible to use this class without being aware of the entire stitching pipeline. However, to -be able to achieve higher stitching stability and quality of the final images at least being -familiar with the theory is recommended. - -@note -- A basic example on image stitching can be found at - opencv_source_code/samples/cpp/stitching.cpp -- A basic example on image stitching in Python can be found at - opencv_source_code/samples/python/stitching.py -- A detailed example on image stitching can be found at - opencv_source_code/samples/cpp/stitching_detailed.cpp - */ -class CV_EXPORTS_W Stitcher -{ -public: - /** - * When setting a resolution for stitching, this values is a placeholder - * for preserving the original resolution. - */ -#if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900/*MSVS 2015*/) - static constexpr double ORIG_RESOL = -1.0; -#else - // support MSVS 2013 - static const double ORIG_RESOL; // Initialized in stitcher.cpp -#endif - - enum Status - { - OK = 0, - ERR_NEED_MORE_IMGS = 1, - ERR_HOMOGRAPHY_EST_FAIL = 2, - ERR_CAMERA_PARAMS_ADJUST_FAIL = 3 - }; - - enum Mode - { - /** Mode for creating photo panoramas. Expects images under perspective - transformation and projects resulting pano to sphere. - - @sa detail::BestOf2NearestMatcher SphericalWarper - */ - PANORAMA = 0, - /** Mode for composing scans. Expects images under affine transformation does - not compensate exposure by default. - - @sa detail::AffineBestOf2NearestMatcher AffineWarper - */ - SCANS = 1, - - }; - - /** @brief Creates a Stitcher configured in one of the stitching modes. - - @param mode Scenario for stitcher operation. This is usually determined by source of images - to stitch and their transformation. Default parameters will be chosen for operation in given - scenario. - @return Stitcher class instance. - */ - CV_WRAP static Ptr create(Mode mode = Stitcher::PANORAMA); - - CV_WRAP double registrationResol() const { return registr_resol_; } - CV_WRAP void setRegistrationResol(double resol_mpx) { registr_resol_ = resol_mpx; } - - CV_WRAP double seamEstimationResol() const { return seam_est_resol_; } - CV_WRAP void setSeamEstimationResol(double resol_mpx) { seam_est_resol_ = resol_mpx; } - - CV_WRAP double compositingResol() const { return compose_resol_; } - CV_WRAP void setCompositingResol(double resol_mpx) { compose_resol_ = resol_mpx; } - - CV_WRAP double panoConfidenceThresh() const { return conf_thresh_; } - CV_WRAP void setPanoConfidenceThresh(double conf_thresh) { conf_thresh_ = conf_thresh; } - - CV_WRAP bool waveCorrection() const { return do_wave_correct_; } - CV_WRAP void setWaveCorrection(bool flag) { do_wave_correct_ = flag; } - - CV_WRAP InterpolationFlags interpolationFlags() const { return interp_flags_; } - CV_WRAP void setInterpolationFlags(InterpolationFlags interp_flags) { interp_flags_ = interp_flags; } - - detail::WaveCorrectKind waveCorrectKind() const { return wave_correct_kind_; } - void setWaveCorrectKind(detail::WaveCorrectKind kind) { wave_correct_kind_ = kind; } - - Ptr featuresFinder() { return features_finder_; } - Ptr featuresFinder() const { return features_finder_; } - void setFeaturesFinder(Ptr features_finder) - { features_finder_ = features_finder; } - - Ptr featuresMatcher() { return features_matcher_; } - Ptr featuresMatcher() const { return features_matcher_; } - void setFeaturesMatcher(Ptr features_matcher) - { features_matcher_ = features_matcher; } - - const cv::UMat& matchingMask() const { return matching_mask_; } - void setMatchingMask(const cv::UMat &mask) - { - CV_Assert(mask.type() == CV_8U && mask.cols == mask.rows); - matching_mask_ = mask.clone(); - } - - Ptr bundleAdjuster() { return bundle_adjuster_; } - const Ptr bundleAdjuster() const { return bundle_adjuster_; } - void setBundleAdjuster(Ptr bundle_adjuster) - { bundle_adjuster_ = bundle_adjuster; } - - Ptr estimator() { return estimator_; } - const Ptr estimator() const { return estimator_; } - void setEstimator(Ptr estimator) - { estimator_ = estimator; } - - Ptr warper() { return warper_; } - const Ptr warper() const { return warper_; } - void setWarper(Ptr creator) { warper_ = creator; } - - Ptr exposureCompensator() { return exposure_comp_; } - const Ptr exposureCompensator() const { return exposure_comp_; } - void setExposureCompensator(Ptr exposure_comp) - { exposure_comp_ = exposure_comp; } - - Ptr seamFinder() { return seam_finder_; } - const Ptr seamFinder() const { return seam_finder_; } - void setSeamFinder(Ptr seam_finder) { seam_finder_ = seam_finder; } - - Ptr blender() { return blender_; } - const Ptr blender() const { return blender_; } - void setBlender(Ptr b) { blender_ = b; } - - /** @brief These functions try to match the given images and to estimate rotations of each camera. - - @note Use the functions only if you're aware of the stitching pipeline, otherwise use - Stitcher::stitch. - - @param images Input images. - @param masks Masks for each input image specifying where to look for keypoints (optional). - @return Status code. - */ - CV_WRAP Status estimateTransform(InputArrayOfArrays images, InputArrayOfArrays masks = noArray()); - - /** @brief These function restors camera rotation and camera intrinsics of each camera - * that can be got with @ref Stitcher::cameras call - - @param images Input images. - @param cameras Estimated rotation of cameras for each of the input images. - @param component Indices (0-based) of images constituting the final panorama (optional). - @return Status code. - */ - Status setTransform(InputArrayOfArrays images, - const std::vector &cameras, - const std::vector &component); - /** @overload */ - Status setTransform(InputArrayOfArrays images, const std::vector &cameras); - - /** @overload */ - CV_WRAP Status composePanorama(OutputArray pano); - /** @brief These functions try to compose the given images (or images stored internally from the other function - calls) into the final pano under the assumption that the image transformations were estimated - before. - - @note Use the functions only if you're aware of the stitching pipeline, otherwise use - Stitcher::stitch. - - @param images Input images. - @param pano Final pano. - @return Status code. - */ - CV_WRAP Status composePanorama(InputArrayOfArrays images, OutputArray pano); - - /** @overload */ - CV_WRAP Status stitch(InputArrayOfArrays images, OutputArray pano); - /** @brief These functions try to stitch the given images. - - @param images Input images. - @param masks Masks for each input image specifying where to look for keypoints (optional). - @param pano Final pano. - @return Status code. - */ - CV_WRAP Status stitch(InputArrayOfArrays images, InputArrayOfArrays masks, OutputArray pano); - - /** @brief Returns indeces of input images used in panorama stitching - */ - CV_WRAP std::vector component() const { return indices_; } - - /** Returns estimated camera parameters for all stitched images - */ - CV_WRAP std::vector cameras() const { return cameras_; } - CV_WRAP double workScale() const { return work_scale_; } - - /** @brief Return the mask of the panorama. - - The mask is a 8U UMat with the values: 0xFF (white) for pixels filled by the input images, - 0 (black) for unused pixels. It can be used as the mask for inpaint. - - @return The mask. - */ - UMat resultMask() const { return result_mask_; } - -private: - Status matchImages(); - Status estimateCameraParams(); - - double registr_resol_; - double seam_est_resol_; - double compose_resol_; - double conf_thresh_; - InterpolationFlags interp_flags_; - Ptr features_finder_; - Ptr features_matcher_; - cv::UMat matching_mask_; - Ptr bundle_adjuster_; - Ptr estimator_; - bool do_wave_correct_; - detail::WaveCorrectKind wave_correct_kind_; - Ptr warper_; - Ptr exposure_comp_; - Ptr seam_finder_; - Ptr blender_; - - std::vector imgs_; - std::vector masks_; - std::vector full_img_sizes_; - std::vector features_; - std::vector pairwise_matches_; - std::vector seam_est_imgs_; - std::vector indices_; - std::vector cameras_; - UMat result_mask_; - double work_scale_; - double seam_scale_; - double seam_work_aspect_; - double warped_image_scale_; -}; - -/** - * @deprecated use Stitcher::create - */ -CV_DEPRECATED Ptr createStitcher(bool try_use_gpu = false); - -/** - * @deprecated use Stitcher::create - */ -CV_DEPRECATED Ptr createStitcherScans(bool try_use_gpu = false); - -//! @} stitching - -} // namespace cv - -#endif // OPENCV_STITCHING_STITCHER_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_STITCHING_STITCHER_HPP +#define OPENCV_STITCHING_STITCHER_HPP + +#include "opencv2/core.hpp" +#include "opencv2/features2d.hpp" +#include "opencv2/stitching/warpers.hpp" +#include "opencv2/stitching/detail/matchers.hpp" +#include "opencv2/stitching/detail/motion_estimators.hpp" +#include "opencv2/stitching/detail/exposure_compensate.hpp" +#include "opencv2/stitching/detail/seam_finders.hpp" +#include "opencv2/stitching/detail/blenders.hpp" +#include "opencv2/stitching/detail/camera.hpp" + + +#if defined(Status) +# warning Detected X11 'Status' macro definition, it can cause build conflicts. Please, include this header before any X11 headers. +#endif + + +/** +@defgroup stitching Images stitching + +This figure illustrates the stitching module pipeline implemented in the Stitcher class. Using that +class it's possible to configure/remove some steps, i.e. adjust the stitching pipeline according to +the particular needs. All building blocks from the pipeline are available in the detail namespace, +one can combine and use them separately. + +The implemented stitching pipeline is very similar to the one proposed in @cite BL07 . + +![stitching pipeline](StitchingPipeline.jpg) + +Camera models +------------- + +There are currently 2 camera models implemented in stitching pipeline. + +- _Homography model_ expecting perspective transformations between images + implemented in @ref cv::detail::BestOf2NearestMatcher cv::detail::HomographyBasedEstimator + cv::detail::BundleAdjusterReproj cv::detail::BundleAdjusterRay +- _Affine model_ expecting affine transformation with 6 DOF or 4 DOF implemented in + @ref cv::detail::AffineBestOf2NearestMatcher cv::detail::AffineBasedEstimator + cv::detail::BundleAdjusterAffine cv::detail::BundleAdjusterAffinePartial cv::AffineWarper + +Homography model is useful for creating photo panoramas captured by camera, +while affine-based model can be used to stitch scans and object captured by +specialized devices. Use @ref cv::Stitcher::create to get preconfigured pipeline for one +of those models. + +@note +Certain detailed settings of @ref cv::Stitcher might not make sense. Especially +you should not mix classes implementing affine model and classes implementing +Homography model, as they work with different transformations. + +@{ + @defgroup stitching_match Features Finding and Images Matching + @defgroup stitching_rotation Rotation Estimation + @defgroup stitching_autocalib Autocalibration + @defgroup stitching_warp Images Warping + @defgroup stitching_seam Seam Estimation + @defgroup stitching_exposure Exposure Compensation + @defgroup stitching_blend Image Blenders +@} + */ + +namespace cv { + +//! @addtogroup stitching +//! @{ + +/** @example samples/cpp/stitching.cpp +A basic example on image stitching +*/ + +/** @example samples/python/stitching.py +A basic example on image stitching in Python. +*/ + +/** @example samples/cpp/stitching_detailed.cpp +A detailed example on image stitching +*/ + +/** @brief High level image stitcher. + +It's possible to use this class without being aware of the entire stitching pipeline. However, to +be able to achieve higher stitching stability and quality of the final images at least being +familiar with the theory is recommended. + +@note +- A basic example on image stitching can be found at + opencv_source_code/samples/cpp/stitching.cpp +- A basic example on image stitching in Python can be found at + opencv_source_code/samples/python/stitching.py +- A detailed example on image stitching can be found at + opencv_source_code/samples/cpp/stitching_detailed.cpp + */ +class CV_EXPORTS_W Stitcher +{ +public: + /** + * When setting a resolution for stitching, this values is a placeholder + * for preserving the original resolution. + */ +#if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900/*MSVS 2015*/) + static constexpr double ORIG_RESOL = -1.0; +#else + // support MSVS 2013 + static const double ORIG_RESOL; // Initialized in stitcher.cpp +#endif + + enum Status + { + OK = 0, + ERR_NEED_MORE_IMGS = 1, + ERR_HOMOGRAPHY_EST_FAIL = 2, + ERR_CAMERA_PARAMS_ADJUST_FAIL = 3 + }; + + enum Mode + { + /** Mode for creating photo panoramas. Expects images under perspective + transformation and projects resulting pano to sphere. + + @sa detail::BestOf2NearestMatcher SphericalWarper + */ + PANORAMA = 0, + /** Mode for composing scans. Expects images under affine transformation does + not compensate exposure by default. + + @sa detail::AffineBestOf2NearestMatcher AffineWarper + */ + SCANS = 1, + + }; + + /** @brief Creates a Stitcher configured in one of the stitching modes. + + @param mode Scenario for stitcher operation. This is usually determined by source of images + to stitch and their transformation. Default parameters will be chosen for operation in given + scenario. + @return Stitcher class instance. + */ + CV_WRAP static Ptr create(Mode mode = Stitcher::PANORAMA); + + CV_WRAP double registrationResol() const { return registr_resol_; } + CV_WRAP void setRegistrationResol(double resol_mpx) { registr_resol_ = resol_mpx; } + + CV_WRAP double seamEstimationResol() const { return seam_est_resol_; } + CV_WRAP void setSeamEstimationResol(double resol_mpx) { seam_est_resol_ = resol_mpx; } + + CV_WRAP double compositingResol() const { return compose_resol_; } + CV_WRAP void setCompositingResol(double resol_mpx) { compose_resol_ = resol_mpx; } + + CV_WRAP double panoConfidenceThresh() const { return conf_thresh_; } + CV_WRAP void setPanoConfidenceThresh(double conf_thresh) { conf_thresh_ = conf_thresh; } + + CV_WRAP bool waveCorrection() const { return do_wave_correct_; } + CV_WRAP void setWaveCorrection(bool flag) { do_wave_correct_ = flag; } + + CV_WRAP InterpolationFlags interpolationFlags() const { return interp_flags_; } + CV_WRAP void setInterpolationFlags(InterpolationFlags interp_flags) { interp_flags_ = interp_flags; } + + detail::WaveCorrectKind waveCorrectKind() const { return wave_correct_kind_; } + void setWaveCorrectKind(detail::WaveCorrectKind kind) { wave_correct_kind_ = kind; } + + Ptr featuresFinder() { return features_finder_; } + Ptr featuresFinder() const { return features_finder_; } + void setFeaturesFinder(Ptr features_finder) + { features_finder_ = features_finder; } + + Ptr featuresMatcher() { return features_matcher_; } + Ptr featuresMatcher() const { return features_matcher_; } + void setFeaturesMatcher(Ptr features_matcher) + { features_matcher_ = features_matcher; } + + const cv::UMat& matchingMask() const { return matching_mask_; } + void setMatchingMask(const cv::UMat &mask) + { + CV_Assert(mask.type() == CV_8U && mask.cols == mask.rows); + matching_mask_ = mask.clone(); + } + + Ptr bundleAdjuster() { return bundle_adjuster_; } + const Ptr bundleAdjuster() const { return bundle_adjuster_; } + void setBundleAdjuster(Ptr bundle_adjuster) + { bundle_adjuster_ = bundle_adjuster; } + + Ptr estimator() { return estimator_; } + const Ptr estimator() const { return estimator_; } + void setEstimator(Ptr estimator) + { estimator_ = estimator; } + + Ptr warper() { return warper_; } + const Ptr warper() const { return warper_; } + void setWarper(Ptr creator) { warper_ = creator; } + + Ptr exposureCompensator() { return exposure_comp_; } + const Ptr exposureCompensator() const { return exposure_comp_; } + void setExposureCompensator(Ptr exposure_comp) + { exposure_comp_ = exposure_comp; } + + Ptr seamFinder() { return seam_finder_; } + const Ptr seamFinder() const { return seam_finder_; } + void setSeamFinder(Ptr seam_finder) { seam_finder_ = seam_finder; } + + Ptr blender() { return blender_; } + const Ptr blender() const { return blender_; } + void setBlender(Ptr b) { blender_ = b; } + + /** @brief These functions try to match the given images and to estimate rotations of each camera. + + @note Use the functions only if you're aware of the stitching pipeline, otherwise use + Stitcher::stitch. + + @param images Input images. + @param masks Masks for each input image specifying where to look for keypoints (optional). + @return Status code. + */ + CV_WRAP Status estimateTransform(InputArrayOfArrays images, InputArrayOfArrays masks = noArray()); + + /** @brief These function restors camera rotation and camera intrinsics of each camera + * that can be got with @ref Stitcher::cameras call + + @param images Input images. + @param cameras Estimated rotation of cameras for each of the input images. + @param component Indices (0-based) of images constituting the final panorama (optional). + @return Status code. + */ + Status setTransform(InputArrayOfArrays images, + const std::vector &cameras, + const std::vector &component); + /** @overload */ + Status setTransform(InputArrayOfArrays images, const std::vector &cameras); + + /** @overload */ + CV_WRAP Status composePanorama(OutputArray pano); + /** @brief These functions try to compose the given images (or images stored internally from the other function + calls) into the final pano under the assumption that the image transformations were estimated + before. + + @note Use the functions only if you're aware of the stitching pipeline, otherwise use + Stitcher::stitch. + + @param images Input images. + @param pano Final pano. + @return Status code. + */ + CV_WRAP Status composePanorama(InputArrayOfArrays images, OutputArray pano); + + /** @overload */ + CV_WRAP Status stitch(InputArrayOfArrays images, OutputArray pano); + /** @brief These functions try to stitch the given images. + + @param images Input images. + @param masks Masks for each input image specifying where to look for keypoints (optional). + @param pano Final pano. + @return Status code. + */ + CV_WRAP Status stitch(InputArrayOfArrays images, InputArrayOfArrays masks, OutputArray pano); + + /** @brief Returns indeces of input images used in panorama stitching + */ + CV_WRAP std::vector component() const { return indices_; } + + /** Returns estimated camera parameters for all stitched images + */ + CV_WRAP std::vector cameras() const { return cameras_; } + CV_WRAP double workScale() const { return work_scale_; } + + /** @brief Return the mask of the panorama. + + The mask is a 8U UMat with the values: 0xFF (white) for pixels filled by the input images, + 0 (black) for unused pixels. It can be used as the mask for inpaint. + + @return The mask. + */ + UMat resultMask() const { return result_mask_; } + +private: + Status matchImages(); + Status estimateCameraParams(); + + double registr_resol_; + double seam_est_resol_; + double compose_resol_; + double conf_thresh_; + InterpolationFlags interp_flags_; + Ptr features_finder_; + Ptr features_matcher_; + cv::UMat matching_mask_; + Ptr bundle_adjuster_; + Ptr estimator_; + bool do_wave_correct_; + detail::WaveCorrectKind wave_correct_kind_; + Ptr warper_; + Ptr exposure_comp_; + Ptr seam_finder_; + Ptr blender_; + + std::vector imgs_; + std::vector masks_; + std::vector full_img_sizes_; + std::vector features_; + std::vector pairwise_matches_; + std::vector seam_est_imgs_; + std::vector indices_; + std::vector cameras_; + UMat result_mask_; + double work_scale_; + double seam_scale_; + double seam_work_aspect_; + double warped_image_scale_; +}; + +/** + * @deprecated use Stitcher::create + */ +CV_DEPRECATED Ptr createStitcher(bool try_use_gpu = false); + +/** + * @deprecated use Stitcher::create + */ +CV_DEPRECATED Ptr createStitcherScans(bool try_use_gpu = false); + +//! @} stitching + +} // namespace cv + +#endif // OPENCV_STITCHING_STITCHER_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/autocalib.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/autocalib.hpp index 8eb6212c65..7487560f82 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/autocalib.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/autocalib.hpp @@ -1,86 +1,86 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_STITCHING_AUTOCALIB_HPP -#define OPENCV_STITCHING_AUTOCALIB_HPP - -#include "opencv2/core.hpp" -#include "matchers.hpp" - -namespace cv { -namespace detail { - -//! @addtogroup stitching_autocalib -//! @{ - -/** @brief Tries to estimate focal lengths from the given homography under the assumption that the camera -undergoes rotations around its centre only. - -@param H Homography. -@param f0 Estimated focal length along X axis. -@param f1 Estimated focal length along Y axis. -@param f0_ok True, if f0 was estimated successfully, false otherwise. -@param f1_ok True, if f1 was estimated successfully, false otherwise. - -See "Construction of Panoramic Image Mosaics with Global and Local Alignment" -by Heung-Yeung Shum and Richard Szeliski. - */ -void CV_EXPORTS_W focalsFromHomography(const Mat &H, double &f0, double &f1, bool &f0_ok, bool &f1_ok); - -/** @brief Estimates focal lengths for each given camera. - -@param features Features of images. -@param pairwise_matches Matches between all image pairs. -@param focals Estimated focal lengths for each camera. - */ -void CV_EXPORTS estimateFocal(const std::vector &features, - const std::vector &pairwise_matches, - std::vector &focals); - -bool CV_EXPORTS_W calibrateRotatingCamera(const std::vector &Hs,CV_OUT Mat &K); - -//! @} stitching_autocalib - -} // namespace detail -} // namespace cv - -#endif // OPENCV_STITCHING_AUTOCALIB_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_STITCHING_AUTOCALIB_HPP +#define OPENCV_STITCHING_AUTOCALIB_HPP + +#include "opencv2/core.hpp" +#include "matchers.hpp" + +namespace cv { +namespace detail { + +//! @addtogroup stitching_autocalib +//! @{ + +/** @brief Tries to estimate focal lengths from the given homography under the assumption that the camera +undergoes rotations around its centre only. + +@param H Homography. +@param f0 Estimated focal length along X axis. +@param f1 Estimated focal length along Y axis. +@param f0_ok True, if f0 was estimated successfully, false otherwise. +@param f1_ok True, if f1 was estimated successfully, false otherwise. + +See "Construction of Panoramic Image Mosaics with Global and Local Alignment" +by Heung-Yeung Shum and Richard Szeliski. + */ +void CV_EXPORTS_W focalsFromHomography(const Mat &H, double &f0, double &f1, bool &f0_ok, bool &f1_ok); + +/** @brief Estimates focal lengths for each given camera. + +@param features Features of images. +@param pairwise_matches Matches between all image pairs. +@param focals Estimated focal lengths for each camera. + */ +void CV_EXPORTS estimateFocal(const std::vector &features, + const std::vector &pairwise_matches, + std::vector &focals); + +bool CV_EXPORTS_W calibrateRotatingCamera(const std::vector &Hs,CV_OUT Mat &K); + +//! @} stitching_autocalib + +} // namespace detail +} // namespace cv + +#endif // OPENCV_STITCHING_AUTOCALIB_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/blenders.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/blenders.hpp index ec35aa7cbb..79e1af43e3 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/blenders.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/blenders.hpp @@ -1,184 +1,184 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_STITCHING_BLENDERS_HPP -#define OPENCV_STITCHING_BLENDERS_HPP - -#if defined(NO) -# warning Detected Apple 'NO' macro definition, it can cause build conflicts. Please, include this header before any Apple headers. -#endif - -#include "opencv2/core.hpp" -#include "opencv2/core/cuda.hpp" - -namespace cv { -namespace detail { - -//! @addtogroup stitching_blend -//! @{ - -/** @brief Base class for all blenders. - -Simple blender which puts one image over another -*/ -class CV_EXPORTS_W Blender -{ -public: - virtual ~Blender() {} - - enum { NO, FEATHER, MULTI_BAND }; - CV_WRAP static Ptr createDefault(int type, bool try_gpu = false); - - /** @brief Prepares the blender for blending. - - @param corners Source images top-left corners - @param sizes Source image sizes - */ - CV_WRAP virtual void prepare(const std::vector &corners, const std::vector &sizes); - /** @overload */ - CV_WRAP virtual void prepare(Rect dst_roi); - /** @brief Processes the image. - - @param img Source image - @param mask Source image mask - @param tl Source image top-left corners - */ - CV_WRAP virtual void feed(InputArray img, InputArray mask, Point tl); - /** @brief Blends and returns the final pano. - - @param dst Final pano - @param dst_mask Final pano mask - */ - CV_WRAP virtual void blend(CV_IN_OUT InputOutputArray dst,CV_IN_OUT InputOutputArray dst_mask); - -protected: - UMat dst_, dst_mask_; - Rect dst_roi_; -}; - -/** @brief Simple blender which mixes images at its borders. - */ -class CV_EXPORTS_W FeatherBlender : public Blender -{ -public: - CV_WRAP FeatherBlender(float sharpness = 0.02f); - - CV_WRAP float sharpness() const { return sharpness_; } - CV_WRAP void setSharpness(float val) { sharpness_ = val; } - - CV_WRAP void prepare(Rect dst_roi) CV_OVERRIDE; - CV_WRAP void feed(InputArray img, InputArray mask, Point tl) CV_OVERRIDE; - CV_WRAP void blend(InputOutputArray dst, InputOutputArray dst_mask) CV_OVERRIDE; - - //! Creates weight maps for fixed set of source images by their masks and top-left corners. - //! Final image can be obtained by simple weighting of the source images. - CV_WRAP Rect createWeightMaps(const std::vector &masks, const std::vector &corners, - CV_IN_OUT std::vector &weight_maps); - -private: - float sharpness_; - UMat weight_map_; - UMat dst_weight_map_; -}; - -inline FeatherBlender::FeatherBlender(float _sharpness) { setSharpness(_sharpness); } - -/** @brief Blender which uses multi-band blending algorithm (see @cite BA83). - */ -class CV_EXPORTS_W MultiBandBlender : public Blender -{ -public: - CV_WRAP MultiBandBlender(int try_gpu = false, int num_bands = 5, int weight_type = CV_32F); - - CV_WRAP int numBands() const { return actual_num_bands_; } - CV_WRAP void setNumBands(int val) { actual_num_bands_ = val; } - - CV_WRAP void prepare(Rect dst_roi) CV_OVERRIDE; - CV_WRAP void feed(InputArray img, InputArray mask, Point tl) CV_OVERRIDE; - CV_WRAP void blend(CV_IN_OUT InputOutputArray dst, CV_IN_OUT InputOutputArray dst_mask) CV_OVERRIDE; - -private: - int actual_num_bands_, num_bands_; - std::vector dst_pyr_laplace_; - std::vector dst_band_weights_; - Rect dst_roi_final_; - bool can_use_gpu_; - int weight_type_; //CV_32F or CV_16S -#if defined(HAVE_OPENCV_CUDAARITHM) && defined(HAVE_OPENCV_CUDAWARPING) - std::vector gpu_dst_pyr_laplace_; - std::vector gpu_dst_band_weights_; - std::vector gpu_tl_points_; - std::vector gpu_imgs_with_border_; - std::vector > gpu_weight_pyr_gauss_vec_; - std::vector > gpu_src_pyr_laplace_vec_; - std::vector > gpu_ups_; - cuda::GpuMat gpu_dst_mask_; - cuda::GpuMat gpu_mask_; - cuda::GpuMat gpu_img_; - cuda::GpuMat gpu_weight_map_; - cuda::GpuMat gpu_add_mask_; - int gpu_feed_idx_; - bool gpu_initialized_; -#endif -}; - - -////////////////////////////////////////////////////////////////////////////// -// Auxiliary functions - -void CV_EXPORTS_W normalizeUsingWeightMap(InputArray weight, CV_IN_OUT InputOutputArray src); - -void CV_EXPORTS_W createWeightMap(InputArray mask, float sharpness, CV_IN_OUT InputOutputArray weight); - -void CV_EXPORTS_W createLaplacePyr(InputArray img, int num_levels, CV_IN_OUT std::vector& pyr); -void CV_EXPORTS_W createLaplacePyrGpu(InputArray img, int num_levels, CV_IN_OUT std::vector& pyr); - -// Restores source image -void CV_EXPORTS_W restoreImageFromLaplacePyr(CV_IN_OUT std::vector& pyr); -void CV_EXPORTS_W restoreImageFromLaplacePyrGpu(CV_IN_OUT std::vector& pyr); - -//! @} - -} // namespace detail -} // namespace cv - -#endif // OPENCV_STITCHING_BLENDERS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_STITCHING_BLENDERS_HPP +#define OPENCV_STITCHING_BLENDERS_HPP + +#if defined(NO) +# warning Detected Apple 'NO' macro definition, it can cause build conflicts. Please, include this header before any Apple headers. +#endif + +#include "opencv2/core.hpp" +#include "opencv2/core/cuda.hpp" + +namespace cv { +namespace detail { + +//! @addtogroup stitching_blend +//! @{ + +/** @brief Base class for all blenders. + +Simple blender which puts one image over another +*/ +class CV_EXPORTS_W Blender +{ +public: + virtual ~Blender() {} + + enum { NO, FEATHER, MULTI_BAND }; + CV_WRAP static Ptr createDefault(int type, bool try_gpu = false); + + /** @brief Prepares the blender for blending. + + @param corners Source images top-left corners + @param sizes Source image sizes + */ + CV_WRAP virtual void prepare(const std::vector &corners, const std::vector &sizes); + /** @overload */ + CV_WRAP virtual void prepare(Rect dst_roi); + /** @brief Processes the image. + + @param img Source image + @param mask Source image mask + @param tl Source image top-left corners + */ + CV_WRAP virtual void feed(InputArray img, InputArray mask, Point tl); + /** @brief Blends and returns the final pano. + + @param dst Final pano + @param dst_mask Final pano mask + */ + CV_WRAP virtual void blend(CV_IN_OUT InputOutputArray dst,CV_IN_OUT InputOutputArray dst_mask); + +protected: + UMat dst_, dst_mask_; + Rect dst_roi_; +}; + +/** @brief Simple blender which mixes images at its borders. + */ +class CV_EXPORTS_W FeatherBlender : public Blender +{ +public: + CV_WRAP FeatherBlender(float sharpness = 0.02f); + + CV_WRAP float sharpness() const { return sharpness_; } + CV_WRAP void setSharpness(float val) { sharpness_ = val; } + + CV_WRAP void prepare(Rect dst_roi) CV_OVERRIDE; + CV_WRAP void feed(InputArray img, InputArray mask, Point tl) CV_OVERRIDE; + CV_WRAP void blend(InputOutputArray dst, InputOutputArray dst_mask) CV_OVERRIDE; + + //! Creates weight maps for fixed set of source images by their masks and top-left corners. + //! Final image can be obtained by simple weighting of the source images. + CV_WRAP Rect createWeightMaps(const std::vector &masks, const std::vector &corners, + CV_IN_OUT std::vector &weight_maps); + +private: + float sharpness_; + UMat weight_map_; + UMat dst_weight_map_; +}; + +inline FeatherBlender::FeatherBlender(float _sharpness) { setSharpness(_sharpness); } + +/** @brief Blender which uses multi-band blending algorithm (see @cite BA83). + */ +class CV_EXPORTS_W MultiBandBlender : public Blender +{ +public: + CV_WRAP MultiBandBlender(int try_gpu = false, int num_bands = 5, int weight_type = CV_32F); + + CV_WRAP int numBands() const { return actual_num_bands_; } + CV_WRAP void setNumBands(int val) { actual_num_bands_ = val; } + + CV_WRAP void prepare(Rect dst_roi) CV_OVERRIDE; + CV_WRAP void feed(InputArray img, InputArray mask, Point tl) CV_OVERRIDE; + CV_WRAP void blend(CV_IN_OUT InputOutputArray dst, CV_IN_OUT InputOutputArray dst_mask) CV_OVERRIDE; + +private: + int actual_num_bands_, num_bands_; + std::vector dst_pyr_laplace_; + std::vector dst_band_weights_; + Rect dst_roi_final_; + bool can_use_gpu_; + int weight_type_; //CV_32F or CV_16S +#if defined(HAVE_OPENCV_CUDAARITHM) && defined(HAVE_OPENCV_CUDAWARPING) + std::vector gpu_dst_pyr_laplace_; + std::vector gpu_dst_band_weights_; + std::vector gpu_tl_points_; + std::vector gpu_imgs_with_border_; + std::vector > gpu_weight_pyr_gauss_vec_; + std::vector > gpu_src_pyr_laplace_vec_; + std::vector > gpu_ups_; + cuda::GpuMat gpu_dst_mask_; + cuda::GpuMat gpu_mask_; + cuda::GpuMat gpu_img_; + cuda::GpuMat gpu_weight_map_; + cuda::GpuMat gpu_add_mask_; + int gpu_feed_idx_; + bool gpu_initialized_; +#endif +}; + + +////////////////////////////////////////////////////////////////////////////// +// Auxiliary functions + +void CV_EXPORTS_W normalizeUsingWeightMap(InputArray weight, CV_IN_OUT InputOutputArray src); + +void CV_EXPORTS_W createWeightMap(InputArray mask, float sharpness, CV_IN_OUT InputOutputArray weight); + +void CV_EXPORTS_W createLaplacePyr(InputArray img, int num_levels, CV_IN_OUT std::vector& pyr); +void CV_EXPORTS_W createLaplacePyrGpu(InputArray img, int num_levels, CV_IN_OUT std::vector& pyr); + +// Restores source image +void CV_EXPORTS_W restoreImageFromLaplacePyr(CV_IN_OUT std::vector& pyr); +void CV_EXPORTS_W restoreImageFromLaplacePyrGpu(CV_IN_OUT std::vector& pyr); + +//! @} + +} // namespace detail +} // namespace cv + +#endif // OPENCV_STITCHING_BLENDERS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/camera.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/camera.hpp index 14ecf60f30..3ae7fd29b5 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/camera.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/camera.hpp @@ -1,78 +1,78 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_STITCHING_CAMERA_HPP -#define OPENCV_STITCHING_CAMERA_HPP - -#include "opencv2/core.hpp" - -namespace cv { -namespace detail { - -//! @addtogroup stitching -//! @{ - -/** @brief Describes camera parameters. - -@note Translation is assumed to be zero during the whole stitching pipeline. : - */ -struct CV_EXPORTS_W_SIMPLE CameraParams -{ - CameraParams(); - CameraParams(const CameraParams& other); - CameraParams& operator =(const CameraParams& other); - CV_WRAP Mat K() const; - - CV_PROP_RW double focal; // Focal length - CV_PROP_RW double aspect; // Aspect ratio - CV_PROP_RW double ppx; // Principal point X - CV_PROP_RW double ppy; // Principal point Y - CV_PROP_RW Mat R; // Rotation - CV_PROP_RW Mat t; // Translation -}; - -//! @} - -} // namespace detail -} // namespace cv - -#endif // #ifndef OPENCV_STITCHING_CAMERA_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_STITCHING_CAMERA_HPP +#define OPENCV_STITCHING_CAMERA_HPP + +#include "opencv2/core.hpp" + +namespace cv { +namespace detail { + +//! @addtogroup stitching +//! @{ + +/** @brief Describes camera parameters. + +@note Translation is assumed to be zero during the whole stitching pipeline. : + */ +struct CV_EXPORTS_W_SIMPLE CameraParams +{ + CameraParams(); + CameraParams(const CameraParams& other); + CameraParams& operator =(const CameraParams& other); + CV_WRAP Mat K() const; + + CV_PROP_RW double focal; // Focal length + CV_PROP_RW double aspect; // Aspect ratio + CV_PROP_RW double ppx; // Principal point X + CV_PROP_RW double ppy; // Principal point Y + CV_PROP_RW Mat R; // Rotation + CV_PROP_RW Mat t; // Translation +}; + +//! @} + +} // namespace detail +} // namespace cv + +#endif // #ifndef OPENCV_STITCHING_CAMERA_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/exposure_compensate.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/exposure_compensate.hpp index dea76c957b..fb4eb71eb4 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/exposure_compensate.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/exposure_compensate.hpp @@ -1,245 +1,245 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_STITCHING_EXPOSURE_COMPENSATE_HPP -#define OPENCV_STITCHING_EXPOSURE_COMPENSATE_HPP - -#if defined(NO) -# warning Detected Apple 'NO' macro definition, it can cause build conflicts. Please, include this header before any Apple headers. -#endif - -#include "opencv2/core.hpp" - -namespace cv { -namespace detail { - -//! @addtogroup stitching_exposure -//! @{ - -/** @brief Base class for all exposure compensators. - */ -class CV_EXPORTS_W ExposureCompensator -{ -public: - ExposureCompensator(): updateGain(true) {} - virtual ~ExposureCompensator() {} - - enum { NO, GAIN, GAIN_BLOCKS, CHANNELS, CHANNELS_BLOCKS }; - CV_WRAP static Ptr createDefault(int type); - - /** - @param corners Source image top-left corners - @param images Source images - @param masks Image masks to update (second value in pair specifies the value which should be used - to detect where image is) - */ - CV_WRAP void feed(const std::vector &corners, const std::vector &images, - const std::vector &masks); - /** @overload */ - virtual void feed(const std::vector &corners, const std::vector &images, - const std::vector > &masks) = 0; - /** @brief Compensate exposure in the specified image. - - @param index Image index - @param corner Image top-left corner - @param image Image to process - @param mask Image mask - */ - CV_WRAP virtual void apply(int index, Point corner, InputOutputArray image, InputArray mask) = 0; - CV_WRAP virtual void getMatGains(CV_OUT std::vector& ) {CV_Error(Error::StsInternal, "");} - CV_WRAP virtual void setMatGains(std::vector& ) { CV_Error(Error::StsInternal, ""); } - CV_WRAP void setUpdateGain(bool b) { updateGain = b; } - CV_WRAP bool getUpdateGain() { return updateGain; } -protected : - bool updateGain; -}; - -/** @brief Stub exposure compensator which does nothing. - */ -class CV_EXPORTS_W NoExposureCompensator : public ExposureCompensator -{ -public: - void feed(const std::vector &/*corners*/, const std::vector &/*images*/, - const std::vector > &/*masks*/) CV_OVERRIDE { } - CV_WRAP void apply(int /*index*/, Point /*corner*/, InputOutputArray /*image*/, InputArray /*mask*/) CV_OVERRIDE { } - CV_WRAP void getMatGains(CV_OUT std::vector& umv) CV_OVERRIDE { umv.clear(); return; } - CV_WRAP void setMatGains(std::vector& umv) CV_OVERRIDE { umv.clear(); return; } -}; - -/** @brief Exposure compensator which tries to remove exposure related artifacts by adjusting image -intensities, see @cite BL07 and @cite WJ10 for details. - */ -class CV_EXPORTS_W GainCompensator : public ExposureCompensator -{ -public: - // This Constructor only exists to make source level compatibility detector happy - CV_WRAP GainCompensator() - : GainCompensator(1) {} - CV_WRAP GainCompensator(int nr_feeds) - : nr_feeds_(nr_feeds), similarity_threshold_(1) {} - void feed(const std::vector &corners, const std::vector &images, - const std::vector > &masks) CV_OVERRIDE; - void singleFeed(const std::vector &corners, const std::vector &images, - const std::vector > &masks); - CV_WRAP void apply(int index, Point corner, InputOutputArray image, InputArray mask) CV_OVERRIDE; - CV_WRAP void getMatGains(CV_OUT std::vector& umv) CV_OVERRIDE ; - CV_WRAP void setMatGains(std::vector& umv) CV_OVERRIDE ; - CV_WRAP void setNrFeeds(int nr_feeds) { nr_feeds_ = nr_feeds; } - CV_WRAP int getNrFeeds() { return nr_feeds_; } - CV_WRAP void setSimilarityThreshold(double similarity_threshold) { similarity_threshold_ = similarity_threshold; } - CV_WRAP double getSimilarityThreshold() const { return similarity_threshold_; } - void prepareSimilarityMask(const std::vector &corners, const std::vector &images); - std::vector gains() const; - -private: - UMat buildSimilarityMask(InputArray src_array1, InputArray src_array2); - - Mat_ gains_; - int nr_feeds_; - double similarity_threshold_; - std::vector similarities_; -}; - -/** @brief Exposure compensator which tries to remove exposure related artifacts by adjusting image -intensities on each channel independently. - */ -class CV_EXPORTS_W ChannelsCompensator : public ExposureCompensator -{ -public: - CV_WRAP ChannelsCompensator(int nr_feeds=1) - : nr_feeds_(nr_feeds), similarity_threshold_(1) {} - void feed(const std::vector &corners, const std::vector &images, - const std::vector > &masks) CV_OVERRIDE; - CV_WRAP void apply(int index, Point corner, InputOutputArray image, InputArray mask) CV_OVERRIDE; - CV_WRAP void getMatGains(CV_OUT std::vector& umv) CV_OVERRIDE; - CV_WRAP void setMatGains(std::vector& umv) CV_OVERRIDE; - CV_WRAP void setNrFeeds(int nr_feeds) { nr_feeds_ = nr_feeds; } - CV_WRAP int getNrFeeds() { return nr_feeds_; } - CV_WRAP void setSimilarityThreshold(double similarity_threshold) { similarity_threshold_ = similarity_threshold; } - CV_WRAP double getSimilarityThreshold() const { return similarity_threshold_; } - std::vector gains() const { return gains_; } - -private: - std::vector gains_; - int nr_feeds_; - double similarity_threshold_; -}; - -/** @brief Exposure compensator which tries to remove exposure related artifacts by adjusting image blocks. - */ -class CV_EXPORTS_W BlocksCompensator : public ExposureCompensator -{ -public: - BlocksCompensator(int bl_width=32, int bl_height=32, int nr_feeds=1) - : bl_width_(bl_width), bl_height_(bl_height), nr_feeds_(nr_feeds), nr_gain_filtering_iterations_(2), - similarity_threshold_(1) {} - CV_WRAP void apply(int index, Point corner, InputOutputArray image, InputArray mask) CV_OVERRIDE; - CV_WRAP void getMatGains(CV_OUT std::vector& umv) CV_OVERRIDE; - CV_WRAP void setMatGains(std::vector& umv) CV_OVERRIDE; - CV_WRAP void setNrFeeds(int nr_feeds) { nr_feeds_ = nr_feeds; } - CV_WRAP int getNrFeeds() { return nr_feeds_; } - CV_WRAP void setSimilarityThreshold(double similarity_threshold) { similarity_threshold_ = similarity_threshold; } - CV_WRAP double getSimilarityThreshold() const { return similarity_threshold_; } - CV_WRAP void setBlockSize(int width, int height) { bl_width_ = width; bl_height_ = height; } - CV_WRAP void setBlockSize(Size size) { setBlockSize(size.width, size.height); } - CV_WRAP Size getBlockSize() const { return Size(bl_width_, bl_height_); } - CV_WRAP void setNrGainsFilteringIterations(int nr_iterations) { nr_gain_filtering_iterations_ = nr_iterations; } - CV_WRAP int getNrGainsFilteringIterations() const { return nr_gain_filtering_iterations_; } - -protected: - template - void feed(const std::vector &corners, const std::vector &images, - const std::vector > &masks); - -private: - UMat getGainMap(const GainCompensator& compensator, int bl_idx, Size bl_per_img); - UMat getGainMap(const ChannelsCompensator& compensator, int bl_idx, Size bl_per_img); - - int bl_width_, bl_height_; - std::vector gain_maps_; - int nr_feeds_; - int nr_gain_filtering_iterations_; - double similarity_threshold_; -}; - -/** @brief Exposure compensator which tries to remove exposure related artifacts by adjusting image block -intensities, see @cite UES01 for details. - */ -class CV_EXPORTS_W BlocksGainCompensator : public BlocksCompensator -{ -public: - // This Constructor only exists to make source level compatibility detector happy - CV_WRAP BlocksGainCompensator(int bl_width = 32, int bl_height = 32) - : BlocksGainCompensator(bl_width, bl_height, 1) {} - CV_WRAP BlocksGainCompensator(int bl_width, int bl_height, int nr_feeds) - : BlocksCompensator(bl_width, bl_height, nr_feeds) {} - - void feed(const std::vector &corners, const std::vector &images, - const std::vector > &masks) CV_OVERRIDE; - - // This function only exists to make source level compatibility detector happy - CV_WRAP void apply(int index, Point corner, InputOutputArray image, InputArray mask) CV_OVERRIDE { - BlocksCompensator::apply(index, corner, image, mask); } - // This function only exists to make source level compatibility detector happy - CV_WRAP void getMatGains(CV_OUT std::vector& umv) CV_OVERRIDE { BlocksCompensator::getMatGains(umv); } - // This function only exists to make source level compatibility detector happy - CV_WRAP void setMatGains(std::vector& umv) CV_OVERRIDE { BlocksCompensator::setMatGains(umv); } -}; - -/** @brief Exposure compensator which tries to remove exposure related artifacts by adjusting image block -on each channel. - */ -class CV_EXPORTS_W BlocksChannelsCompensator : public BlocksCompensator -{ -public: - CV_WRAP BlocksChannelsCompensator(int bl_width=32, int bl_height=32, int nr_feeds=1) - : BlocksCompensator(bl_width, bl_height, nr_feeds) {} - - void feed(const std::vector &corners, const std::vector &images, - const std::vector > &masks) CV_OVERRIDE; -}; -//! @} - -} // namespace detail -} // namespace cv - -#endif // OPENCV_STITCHING_EXPOSURE_COMPENSATE_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_STITCHING_EXPOSURE_COMPENSATE_HPP +#define OPENCV_STITCHING_EXPOSURE_COMPENSATE_HPP + +#if defined(NO) +# warning Detected Apple 'NO' macro definition, it can cause build conflicts. Please, include this header before any Apple headers. +#endif + +#include "opencv2/core.hpp" + +namespace cv { +namespace detail { + +//! @addtogroup stitching_exposure +//! @{ + +/** @brief Base class for all exposure compensators. + */ +class CV_EXPORTS_W ExposureCompensator +{ +public: + ExposureCompensator(): updateGain(true) {} + virtual ~ExposureCompensator() {} + + enum { NO, GAIN, GAIN_BLOCKS, CHANNELS, CHANNELS_BLOCKS }; + CV_WRAP static Ptr createDefault(int type); + + /** + @param corners Source image top-left corners + @param images Source images + @param masks Image masks to update (second value in pair specifies the value which should be used + to detect where image is) + */ + CV_WRAP void feed(const std::vector &corners, const std::vector &images, + const std::vector &masks); + /** @overload */ + virtual void feed(const std::vector &corners, const std::vector &images, + const std::vector > &masks) = 0; + /** @brief Compensate exposure in the specified image. + + @param index Image index + @param corner Image top-left corner + @param image Image to process + @param mask Image mask + */ + CV_WRAP virtual void apply(int index, Point corner, InputOutputArray image, InputArray mask) = 0; + CV_WRAP virtual void getMatGains(CV_OUT std::vector& ) {CV_Error(Error::StsInternal, "");} + CV_WRAP virtual void setMatGains(std::vector& ) { CV_Error(Error::StsInternal, ""); } + CV_WRAP void setUpdateGain(bool b) { updateGain = b; } + CV_WRAP bool getUpdateGain() { return updateGain; } +protected : + bool updateGain; +}; + +/** @brief Stub exposure compensator which does nothing. + */ +class CV_EXPORTS_W NoExposureCompensator : public ExposureCompensator +{ +public: + void feed(const std::vector &/*corners*/, const std::vector &/*images*/, + const std::vector > &/*masks*/) CV_OVERRIDE { } + CV_WRAP void apply(int /*index*/, Point /*corner*/, InputOutputArray /*image*/, InputArray /*mask*/) CV_OVERRIDE { } + CV_WRAP void getMatGains(CV_OUT std::vector& umv) CV_OVERRIDE { umv.clear(); return; } + CV_WRAP void setMatGains(std::vector& umv) CV_OVERRIDE { umv.clear(); return; } +}; + +/** @brief Exposure compensator which tries to remove exposure related artifacts by adjusting image +intensities, see @cite BL07 and @cite WJ10 for details. + */ +class CV_EXPORTS_W GainCompensator : public ExposureCompensator +{ +public: + // This Constructor only exists to make source level compatibility detector happy + CV_WRAP GainCompensator() + : GainCompensator(1) {} + CV_WRAP GainCompensator(int nr_feeds) + : nr_feeds_(nr_feeds), similarity_threshold_(1) {} + void feed(const std::vector &corners, const std::vector &images, + const std::vector > &masks) CV_OVERRIDE; + void singleFeed(const std::vector &corners, const std::vector &images, + const std::vector > &masks); + CV_WRAP void apply(int index, Point corner, InputOutputArray image, InputArray mask) CV_OVERRIDE; + CV_WRAP void getMatGains(CV_OUT std::vector& umv) CV_OVERRIDE ; + CV_WRAP void setMatGains(std::vector& umv) CV_OVERRIDE ; + CV_WRAP void setNrFeeds(int nr_feeds) { nr_feeds_ = nr_feeds; } + CV_WRAP int getNrFeeds() { return nr_feeds_; } + CV_WRAP void setSimilarityThreshold(double similarity_threshold) { similarity_threshold_ = similarity_threshold; } + CV_WRAP double getSimilarityThreshold() const { return similarity_threshold_; } + void prepareSimilarityMask(const std::vector &corners, const std::vector &images); + std::vector gains() const; + +private: + UMat buildSimilarityMask(InputArray src_array1, InputArray src_array2); + + Mat_ gains_; + int nr_feeds_; + double similarity_threshold_; + std::vector similarities_; +}; + +/** @brief Exposure compensator which tries to remove exposure related artifacts by adjusting image +intensities on each channel independently. + */ +class CV_EXPORTS_W ChannelsCompensator : public ExposureCompensator +{ +public: + CV_WRAP ChannelsCompensator(int nr_feeds=1) + : nr_feeds_(nr_feeds), similarity_threshold_(1) {} + void feed(const std::vector &corners, const std::vector &images, + const std::vector > &masks) CV_OVERRIDE; + CV_WRAP void apply(int index, Point corner, InputOutputArray image, InputArray mask) CV_OVERRIDE; + CV_WRAP void getMatGains(CV_OUT std::vector& umv) CV_OVERRIDE; + CV_WRAP void setMatGains(std::vector& umv) CV_OVERRIDE; + CV_WRAP void setNrFeeds(int nr_feeds) { nr_feeds_ = nr_feeds; } + CV_WRAP int getNrFeeds() { return nr_feeds_; } + CV_WRAP void setSimilarityThreshold(double similarity_threshold) { similarity_threshold_ = similarity_threshold; } + CV_WRAP double getSimilarityThreshold() const { return similarity_threshold_; } + std::vector gains() const { return gains_; } + +private: + std::vector gains_; + int nr_feeds_; + double similarity_threshold_; +}; + +/** @brief Exposure compensator which tries to remove exposure related artifacts by adjusting image blocks. + */ +class CV_EXPORTS_W BlocksCompensator : public ExposureCompensator +{ +public: + BlocksCompensator(int bl_width=32, int bl_height=32, int nr_feeds=1) + : bl_width_(bl_width), bl_height_(bl_height), nr_feeds_(nr_feeds), nr_gain_filtering_iterations_(2), + similarity_threshold_(1) {} + CV_WRAP void apply(int index, Point corner, InputOutputArray image, InputArray mask) CV_OVERRIDE; + CV_WRAP void getMatGains(CV_OUT std::vector& umv) CV_OVERRIDE; + CV_WRAP void setMatGains(std::vector& umv) CV_OVERRIDE; + CV_WRAP void setNrFeeds(int nr_feeds) { nr_feeds_ = nr_feeds; } + CV_WRAP int getNrFeeds() { return nr_feeds_; } + CV_WRAP void setSimilarityThreshold(double similarity_threshold) { similarity_threshold_ = similarity_threshold; } + CV_WRAP double getSimilarityThreshold() const { return similarity_threshold_; } + CV_WRAP void setBlockSize(int width, int height) { bl_width_ = width; bl_height_ = height; } + CV_WRAP void setBlockSize(Size size) { setBlockSize(size.width, size.height); } + CV_WRAP Size getBlockSize() const { return Size(bl_width_, bl_height_); } + CV_WRAP void setNrGainsFilteringIterations(int nr_iterations) { nr_gain_filtering_iterations_ = nr_iterations; } + CV_WRAP int getNrGainsFilteringIterations() const { return nr_gain_filtering_iterations_; } + +protected: + template + void feed(const std::vector &corners, const std::vector &images, + const std::vector > &masks); + +private: + UMat getGainMap(const GainCompensator& compensator, int bl_idx, Size bl_per_img); + UMat getGainMap(const ChannelsCompensator& compensator, int bl_idx, Size bl_per_img); + + int bl_width_, bl_height_; + std::vector gain_maps_; + int nr_feeds_; + int nr_gain_filtering_iterations_; + double similarity_threshold_; +}; + +/** @brief Exposure compensator which tries to remove exposure related artifacts by adjusting image block +intensities, see @cite UES01 for details. + */ +class CV_EXPORTS_W BlocksGainCompensator : public BlocksCompensator +{ +public: + // This Constructor only exists to make source level compatibility detector happy + CV_WRAP BlocksGainCompensator(int bl_width = 32, int bl_height = 32) + : BlocksGainCompensator(bl_width, bl_height, 1) {} + CV_WRAP BlocksGainCompensator(int bl_width, int bl_height, int nr_feeds) + : BlocksCompensator(bl_width, bl_height, nr_feeds) {} + + void feed(const std::vector &corners, const std::vector &images, + const std::vector > &masks) CV_OVERRIDE; + + // This function only exists to make source level compatibility detector happy + CV_WRAP void apply(int index, Point corner, InputOutputArray image, InputArray mask) CV_OVERRIDE { + BlocksCompensator::apply(index, corner, image, mask); } + // This function only exists to make source level compatibility detector happy + CV_WRAP void getMatGains(CV_OUT std::vector& umv) CV_OVERRIDE { BlocksCompensator::getMatGains(umv); } + // This function only exists to make source level compatibility detector happy + CV_WRAP void setMatGains(std::vector& umv) CV_OVERRIDE { BlocksCompensator::setMatGains(umv); } +}; + +/** @brief Exposure compensator which tries to remove exposure related artifacts by adjusting image block +on each channel. + */ +class CV_EXPORTS_W BlocksChannelsCompensator : public BlocksCompensator +{ +public: + CV_WRAP BlocksChannelsCompensator(int bl_width=32, int bl_height=32, int nr_feeds=1) + : BlocksCompensator(bl_width, bl_height, nr_feeds) {} + + void feed(const std::vector &corners, const std::vector &images, + const std::vector > &masks) CV_OVERRIDE; +}; +//! @} + +} // namespace detail +} // namespace cv + +#endif // OPENCV_STITCHING_EXPOSURE_COMPENSATE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/matchers.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/matchers.hpp index e25668308e..44a623ae6c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/matchers.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/matchers.hpp @@ -1,267 +1,267 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_STITCHING_MATCHERS_HPP -#define OPENCV_STITCHING_MATCHERS_HPP - -#include "opencv2/core.hpp" -#include "opencv2/features2d.hpp" - -#include "opencv2/opencv_modules.hpp" - -namespace cv { -namespace detail { - -//! @addtogroup stitching_match -//! @{ - -/** @brief Structure containing image keypoints and descriptors. */ -struct CV_EXPORTS_W_SIMPLE ImageFeatures -{ - CV_PROP_RW int img_idx; - CV_PROP_RW Size img_size; - CV_PROP_RW std::vector keypoints; - CV_PROP_RW UMat descriptors; - CV_WRAP std::vector getKeypoints() { return keypoints; } -}; -/** @brief - -@param featuresFinder -@param images -@param features -@param masks -*/ -CV_EXPORTS_W void computeImageFeatures( - const Ptr &featuresFinder, - InputArrayOfArrays images, - CV_OUT std::vector &features, - InputArrayOfArrays masks = noArray()); - -/** @brief - -@param featuresFinder -@param image -@param features -@param mask -*/ -CV_EXPORTS_AS(computeImageFeatures2) void computeImageFeatures( - const Ptr &featuresFinder, - InputArray image, - CV_OUT ImageFeatures &features, - InputArray mask = noArray()); - -/** @brief Structure containing information about matches between two images. - -It's assumed that there is a transformation between those images. Transformation may be -homography or affine transformation based on selected matcher. - -@sa detail::FeaturesMatcher -*/ -struct CV_EXPORTS_W_SIMPLE MatchesInfo -{ - MatchesInfo(); - MatchesInfo(const MatchesInfo &other); - MatchesInfo& operator =(const MatchesInfo &other); - - CV_PROP_RW int src_img_idx; - CV_PROP_RW int dst_img_idx; //!< Images indices (optional) - CV_PROP_RW std::vector matches; - CV_PROP_RW std::vector inliers_mask; //!< Geometrically consistent matches mask - CV_PROP_RW int num_inliers; //!< Number of geometrically consistent matches - CV_PROP_RW Mat H; //!< Estimated transformation - CV_PROP_RW double confidence; //!< Confidence two images are from the same panorama - CV_WRAP std::vector getMatches() { return matches; } - CV_WRAP std::vector getInliers() { return inliers_mask; } -}; - -/** @brief Feature matchers base class. */ -class CV_EXPORTS_W FeaturesMatcher -{ -public: - CV_WRAP virtual ~FeaturesMatcher() {} - - /** @overload - @param features1 First image features - @param features2 Second image features - @param matches_info Found matches - */ - CV_WRAP_AS(apply) void operator ()(const ImageFeatures &features1, const ImageFeatures &features2, - CV_OUT MatchesInfo& matches_info) { match(features1, features2, matches_info); } - - /** @brief Performs images matching. - - @param features Features of the source images - @param pairwise_matches Found pairwise matches - @param mask Mask indicating which image pairs must be matched - - The function is parallelized with the TBB library. - - @sa detail::MatchesInfo - */ - CV_WRAP_AS(apply2) void operator ()(const std::vector &features, CV_OUT std::vector &pairwise_matches, - const cv::UMat &mask = cv::UMat()) { match(features, pairwise_matches, mask); } - - /** @return True, if it's possible to use the same matcher instance in parallel, false otherwise - */ - CV_WRAP bool isThreadSafe() const { return is_thread_safe_; } - - /** @brief Frees unused memory allocated before if there is any. - */ - CV_WRAP virtual void collectGarbage() {} - -protected: - FeaturesMatcher(bool is_thread_safe = false) : is_thread_safe_(is_thread_safe) {} - - /** @brief This method must implement matching logic in order to make the wrappers - detail::FeaturesMatcher::operator()_ work. - - @param features1 first image features - @param features2 second image features - @param matches_info found matches - */ - virtual void match(const ImageFeatures &features1, const ImageFeatures &features2, - MatchesInfo& matches_info) = 0; - - /** @brief This method implements logic to match features between arbitrary number of features. - By default this checks every pair of inputs in the input, but the behaviour can be changed by subclasses. - - @param features vector of image features - @param pairwise_matches found matches - @param mask (optional) mask indicating which image pairs should be matched - */ - virtual void match(const std::vector &features, std::vector &pairwise_matches, - const cv::UMat &mask = cv::UMat()); - - bool is_thread_safe_; -}; - -/** @brief Features matcher which finds two best matches for each feature and leaves the best one only if the -ratio between descriptor distances is greater than the threshold match_conf - -@sa detail::FeaturesMatcher - */ -class CV_EXPORTS_W BestOf2NearestMatcher : public FeaturesMatcher -{ -public: - /** @brief Constructs a "best of 2 nearest" matcher. - - @param try_use_gpu Should try to use GPU or not - @param match_conf Match distances ration threshold - @param num_matches_thresh1 Minimum number of matches required for the 2D projective transform - estimation used in the inliers classification step - @param num_matches_thresh2 Minimum number of matches required for the 2D projective transform - re-estimation on inliers - @param matches_confindece_thresh Matching confidence threshold to take the match into account. - The threshold was determined experimentally and set to 3 by default. - */ - CV_WRAP BestOf2NearestMatcher(bool try_use_gpu = false, float match_conf = 0.3f, int num_matches_thresh1 = 6, - int num_matches_thresh2 = 6, double matches_confindece_thresh = 3.); - - CV_WRAP void collectGarbage() CV_OVERRIDE; - CV_WRAP static Ptr create(bool try_use_gpu = false, float match_conf = 0.3f, int num_matches_thresh1 = 6, - int num_matches_thresh2 = 6, double matches_confindece_thresh = 3.); - -protected: - - void match(const ImageFeatures &features1, const ImageFeatures &features2, MatchesInfo &matches_info) CV_OVERRIDE; - int num_matches_thresh1_; - int num_matches_thresh2_; - double matches_confindece_thresh_; - Ptr impl_; -}; - -class CV_EXPORTS_W BestOf2NearestRangeMatcher : public BestOf2NearestMatcher -{ -public: - CV_WRAP BestOf2NearestRangeMatcher(int range_width = 5, bool try_use_gpu = false, float match_conf = 0.3f, - int num_matches_thresh1 = 6, int num_matches_thresh2 = 6); - -protected: - // indicate that we do not want to hide the base class match method with a different signature - using BestOf2NearestMatcher::match; - void match(const std::vector &features, std::vector &pairwise_matches, - const cv::UMat &mask = cv::UMat()) CV_OVERRIDE; - - int range_width_; -}; - -/** @brief Features matcher similar to cv::detail::BestOf2NearestMatcher which -finds two best matches for each feature and leaves the best one only if the -ratio between descriptor distances is greater than the threshold match_conf. - -Unlike cv::detail::BestOf2NearestMatcher this matcher uses affine -transformation (affine transformation estimate will be placed in matches_info). - -@sa cv::detail::FeaturesMatcher cv::detail::BestOf2NearestMatcher - */ -class CV_EXPORTS_W AffineBestOf2NearestMatcher : public BestOf2NearestMatcher -{ -public: - /** @brief Constructs a "best of 2 nearest" matcher that expects affine transformation - between images - - @param full_affine whether to use full affine transformation with 6 degress of freedom or reduced - transformation with 4 degrees of freedom using only rotation, translation and uniform scaling - @param try_use_gpu Should try to use GPU or not - @param match_conf Match distances ration threshold - @param num_matches_thresh1 Minimum number of matches required for the 2D affine transform - estimation used in the inliers classification step - - @sa cv::estimateAffine2D cv::estimateAffinePartial2D - */ - CV_WRAP AffineBestOf2NearestMatcher(bool full_affine = false, bool try_use_gpu = false, - float match_conf = 0.3f, int num_matches_thresh1 = 6) : - BestOf2NearestMatcher(try_use_gpu, match_conf, num_matches_thresh1, num_matches_thresh1), - full_affine_(full_affine) {} - -protected: - void match(const ImageFeatures &features1, const ImageFeatures &features2, MatchesInfo &matches_info) CV_OVERRIDE; - - bool full_affine_; -}; - -//! @} stitching_match - -} // namespace detail -} // namespace cv - -#endif // OPENCV_STITCHING_MATCHERS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_STITCHING_MATCHERS_HPP +#define OPENCV_STITCHING_MATCHERS_HPP + +#include "opencv2/core.hpp" +#include "opencv2/features2d.hpp" + +#include "opencv2/opencv_modules.hpp" + +namespace cv { +namespace detail { + +//! @addtogroup stitching_match +//! @{ + +/** @brief Structure containing image keypoints and descriptors. */ +struct CV_EXPORTS_W_SIMPLE ImageFeatures +{ + CV_PROP_RW int img_idx; + CV_PROP_RW Size img_size; + CV_PROP_RW std::vector keypoints; + CV_PROP_RW UMat descriptors; + CV_WRAP std::vector getKeypoints() { return keypoints; } +}; +/** @brief + +@param featuresFinder +@param images +@param features +@param masks +*/ +CV_EXPORTS_W void computeImageFeatures( + const Ptr &featuresFinder, + InputArrayOfArrays images, + CV_OUT std::vector &features, + InputArrayOfArrays masks = noArray()); + +/** @brief + +@param featuresFinder +@param image +@param features +@param mask +*/ +CV_EXPORTS_AS(computeImageFeatures2) void computeImageFeatures( + const Ptr &featuresFinder, + InputArray image, + CV_OUT ImageFeatures &features, + InputArray mask = noArray()); + +/** @brief Structure containing information about matches between two images. + +It's assumed that there is a transformation between those images. Transformation may be +homography or affine transformation based on selected matcher. + +@sa detail::FeaturesMatcher +*/ +struct CV_EXPORTS_W_SIMPLE MatchesInfo +{ + MatchesInfo(); + MatchesInfo(const MatchesInfo &other); + MatchesInfo& operator =(const MatchesInfo &other); + + CV_PROP_RW int src_img_idx; + CV_PROP_RW int dst_img_idx; //!< Images indices (optional) + CV_PROP_RW std::vector matches; + CV_PROP_RW std::vector inliers_mask; //!< Geometrically consistent matches mask + CV_PROP_RW int num_inliers; //!< Number of geometrically consistent matches + CV_PROP_RW Mat H; //!< Estimated transformation + CV_PROP_RW double confidence; //!< Confidence two images are from the same panorama + CV_WRAP std::vector getMatches() { return matches; } + CV_WRAP std::vector getInliers() { return inliers_mask; } +}; + +/** @brief Feature matchers base class. */ +class CV_EXPORTS_W FeaturesMatcher +{ +public: + CV_WRAP virtual ~FeaturesMatcher() {} + + /** @overload + @param features1 First image features + @param features2 Second image features + @param matches_info Found matches + */ + CV_WRAP_AS(apply) void operator ()(const ImageFeatures &features1, const ImageFeatures &features2, + CV_OUT MatchesInfo& matches_info) { match(features1, features2, matches_info); } + + /** @brief Performs images matching. + + @param features Features of the source images + @param pairwise_matches Found pairwise matches + @param mask Mask indicating which image pairs must be matched + + The function is parallelized with the TBB library. + + @sa detail::MatchesInfo + */ + CV_WRAP_AS(apply2) void operator ()(const std::vector &features, CV_OUT std::vector &pairwise_matches, + const cv::UMat &mask = cv::UMat()) { match(features, pairwise_matches, mask); } + + /** @return True, if it's possible to use the same matcher instance in parallel, false otherwise + */ + CV_WRAP bool isThreadSafe() const { return is_thread_safe_; } + + /** @brief Frees unused memory allocated before if there is any. + */ + CV_WRAP virtual void collectGarbage() {} + +protected: + FeaturesMatcher(bool is_thread_safe = false) : is_thread_safe_(is_thread_safe) {} + + /** @brief This method must implement matching logic in order to make the wrappers + detail::FeaturesMatcher::operator()_ work. + + @param features1 first image features + @param features2 second image features + @param matches_info found matches + */ + virtual void match(const ImageFeatures &features1, const ImageFeatures &features2, + MatchesInfo& matches_info) = 0; + + /** @brief This method implements logic to match features between arbitrary number of features. + By default this checks every pair of inputs in the input, but the behaviour can be changed by subclasses. + + @param features vector of image features + @param pairwise_matches found matches + @param mask (optional) mask indicating which image pairs should be matched + */ + virtual void match(const std::vector &features, std::vector &pairwise_matches, + const cv::UMat &mask = cv::UMat()); + + bool is_thread_safe_; +}; + +/** @brief Features matcher which finds two best matches for each feature and leaves the best one only if the +ratio between descriptor distances is greater than the threshold match_conf + +@sa detail::FeaturesMatcher + */ +class CV_EXPORTS_W BestOf2NearestMatcher : public FeaturesMatcher +{ +public: + /** @brief Constructs a "best of 2 nearest" matcher. + + @param try_use_gpu Should try to use GPU or not + @param match_conf Match distances ration threshold + @param num_matches_thresh1 Minimum number of matches required for the 2D projective transform + estimation used in the inliers classification step + @param num_matches_thresh2 Minimum number of matches required for the 2D projective transform + re-estimation on inliers + @param matches_confindece_thresh Matching confidence threshold to take the match into account. + The threshold was determined experimentally and set to 3 by default. + */ + CV_WRAP BestOf2NearestMatcher(bool try_use_gpu = false, float match_conf = 0.3f, int num_matches_thresh1 = 6, + int num_matches_thresh2 = 6, double matches_confindece_thresh = 3.); + + CV_WRAP void collectGarbage() CV_OVERRIDE; + CV_WRAP static Ptr create(bool try_use_gpu = false, float match_conf = 0.3f, int num_matches_thresh1 = 6, + int num_matches_thresh2 = 6, double matches_confindece_thresh = 3.); + +protected: + + void match(const ImageFeatures &features1, const ImageFeatures &features2, MatchesInfo &matches_info) CV_OVERRIDE; + int num_matches_thresh1_; + int num_matches_thresh2_; + double matches_confindece_thresh_; + Ptr impl_; +}; + +class CV_EXPORTS_W BestOf2NearestRangeMatcher : public BestOf2NearestMatcher +{ +public: + CV_WRAP BestOf2NearestRangeMatcher(int range_width = 5, bool try_use_gpu = false, float match_conf = 0.3f, + int num_matches_thresh1 = 6, int num_matches_thresh2 = 6); + +protected: + // indicate that we do not want to hide the base class match method with a different signature + using BestOf2NearestMatcher::match; + void match(const std::vector &features, std::vector &pairwise_matches, + const cv::UMat &mask = cv::UMat()) CV_OVERRIDE; + + int range_width_; +}; + +/** @brief Features matcher similar to cv::detail::BestOf2NearestMatcher which +finds two best matches for each feature and leaves the best one only if the +ratio between descriptor distances is greater than the threshold match_conf. + +Unlike cv::detail::BestOf2NearestMatcher this matcher uses affine +transformation (affine transformation estimate will be placed in matches_info). + +@sa cv::detail::FeaturesMatcher cv::detail::BestOf2NearestMatcher + */ +class CV_EXPORTS_W AffineBestOf2NearestMatcher : public BestOf2NearestMatcher +{ +public: + /** @brief Constructs a "best of 2 nearest" matcher that expects affine transformation + between images + + @param full_affine whether to use full affine transformation with 6 degress of freedom or reduced + transformation with 4 degrees of freedom using only rotation, translation and uniform scaling + @param try_use_gpu Should try to use GPU or not + @param match_conf Match distances ration threshold + @param num_matches_thresh1 Minimum number of matches required for the 2D affine transform + estimation used in the inliers classification step + + @sa cv::estimateAffine2D cv::estimateAffinePartial2D + */ + CV_WRAP AffineBestOf2NearestMatcher(bool full_affine = false, bool try_use_gpu = false, + float match_conf = 0.3f, int num_matches_thresh1 = 6) : + BestOf2NearestMatcher(try_use_gpu, match_conf, num_matches_thresh1, num_matches_thresh1), + full_affine_(full_affine) {} + +protected: + void match(const ImageFeatures &features1, const ImageFeatures &features2, MatchesInfo &matches_info) CV_OVERRIDE; + + bool full_affine_; +}; + +//! @} stitching_match + +} // namespace detail +} // namespace cv + +#endif // OPENCV_STITCHING_MATCHERS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/motion_estimators.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/motion_estimators.hpp index c03aa52090..00c61343a2 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/motion_estimators.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/motion_estimators.hpp @@ -1,373 +1,373 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_STITCHING_MOTION_ESTIMATORS_HPP -#define OPENCV_STITCHING_MOTION_ESTIMATORS_HPP - -#include "opencv2/core.hpp" -#include "matchers.hpp" -#include "util.hpp" -#include "camera.hpp" - -namespace cv { -namespace detail { - -//! @addtogroup stitching_rotation -//! @{ - -/** @brief Rotation estimator base class. - -It takes features of all images, pairwise matches between all images and estimates rotations of all -cameras. - -@note The coordinate system origin is implementation-dependent, but you can always normalize the -rotations in respect to the first camera, for instance. : - */ -class CV_EXPORTS_W Estimator -{ -public: - virtual ~Estimator() {} - - /** @brief Estimates camera parameters. - - @param features Features of images - @param pairwise_matches Pairwise matches of images - @param cameras Estimated camera parameters - @return True in case of success, false otherwise - */ - CV_WRAP_AS(apply) bool operator ()(const std::vector &features, - const std::vector &pairwise_matches, - CV_OUT CV_IN_OUT std::vector &cameras) - { - return estimate(features, pairwise_matches, cameras); - } - -protected: - /** @brief This method must implement camera parameters estimation logic in order to make the wrapper - detail::Estimator::operator()_ work. - - @param features Features of images - @param pairwise_matches Pairwise matches of images - @param cameras Estimated camera parameters - @return True in case of success, false otherwise - */ - virtual bool estimate(const std::vector &features, - const std::vector &pairwise_matches, - CV_OUT std::vector &cameras) = 0; -}; - -/** @brief Homography based rotation estimator. - */ -class CV_EXPORTS_W HomographyBasedEstimator : public Estimator -{ -public: - CV_WRAP HomographyBasedEstimator(bool is_focals_estimated = false) - : is_focals_estimated_(is_focals_estimated) {} - -private: - virtual bool estimate(const std::vector &features, - const std::vector &pairwise_matches, - std::vector &cameras) CV_OVERRIDE; - - bool is_focals_estimated_; -}; - -/** @brief Affine transformation based estimator. - -This estimator uses pairwise transformations estimated by matcher to estimate -final transformation for each camera. - -@sa cv::detail::HomographyBasedEstimator - */ -class CV_EXPORTS_W AffineBasedEstimator : public Estimator -{ -public: - CV_WRAP AffineBasedEstimator(){} -private: - virtual bool estimate(const std::vector &features, - const std::vector &pairwise_matches, - std::vector &cameras) CV_OVERRIDE; -}; - -/** @brief Base class for all camera parameters refinement methods. - */ -class CV_EXPORTS_W BundleAdjusterBase : public Estimator -{ -public: - CV_WRAP Mat refinementMask() const { return refinement_mask_.clone(); } - CV_WRAP void setRefinementMask(const Mat &mask) - { - CV_Assert(mask.type() == CV_8U && mask.size() == Size(3, 3)); - refinement_mask_ = mask.clone(); - } - - CV_WRAP double confThresh() const { return conf_thresh_; } - CV_WRAP void setConfThresh(double conf_thresh) { conf_thresh_ = conf_thresh; } - - CV_WRAP TermCriteria termCriteria() { return term_criteria_; } - CV_WRAP void setTermCriteria(const TermCriteria& term_criteria) { term_criteria_ = term_criteria; } - -protected: - /** @brief Construct a bundle adjuster base instance. - - @param num_params_per_cam Number of parameters per camera - @param num_errs_per_measurement Number of error terms (components) per match - */ - BundleAdjusterBase(int num_params_per_cam, int num_errs_per_measurement) - : num_images_(0), total_num_matches_(0), - num_params_per_cam_(num_params_per_cam), - num_errs_per_measurement_(num_errs_per_measurement), - features_(0), pairwise_matches_(0), conf_thresh_(0) - { - setRefinementMask(Mat::ones(3, 3, CV_8U)); - setConfThresh(1.); - setTermCriteria(TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 1000, DBL_EPSILON)); - } - - // Runs bundle adjustment - virtual bool estimate(const std::vector &features, - const std::vector &pairwise_matches, - std::vector &cameras) CV_OVERRIDE; - - /** @brief Sets initial camera parameter to refine. - - @param cameras Camera parameters - */ - virtual void setUpInitialCameraParams(const std::vector &cameras) = 0; - /** @brief Gets the refined camera parameters. - - @param cameras Refined camera parameters - */ - virtual void obtainRefinedCameraParams(std::vector &cameras) const = 0; - /** @brief Calculates error vector. - - @param err Error column-vector of length total_num_matches \* num_errs_per_measurement - */ - virtual void calcError(Mat &err) = 0; - /** @brief Calculates the cost function jacobian. - - @param jac Jacobian matrix of dimensions - (total_num_matches \* num_errs_per_measurement) x (num_images \* num_params_per_cam) - */ - virtual void calcJacobian(Mat &jac) = 0; - - // 3x3 8U mask, where 0 means don't refine respective parameter, != 0 means refine - Mat refinement_mask_; - - int num_images_; - int total_num_matches_; - - int num_params_per_cam_; - int num_errs_per_measurement_; - - const ImageFeatures *features_; - const MatchesInfo *pairwise_matches_; - - // Threshold to filter out poorly matched image pairs - double conf_thresh_; - - //Levenberg-Marquardt algorithm termination criteria - TermCriteria term_criteria_; - - // Camera parameters matrix (CV_64F) - Mat cam_params_; - - // Connected images pairs - std::vector > edges_; -}; - - -/** @brief Stub bundle adjuster that does nothing. - */ -class CV_EXPORTS_W NoBundleAdjuster : public BundleAdjusterBase -{ -public: - CV_WRAP NoBundleAdjuster() : BundleAdjusterBase(0, 0) {} - -private: - bool estimate(const std::vector &, const std::vector &, - std::vector &) CV_OVERRIDE - { - return true; - } - void setUpInitialCameraParams(const std::vector &) CV_OVERRIDE {} - void obtainRefinedCameraParams(std::vector &) const CV_OVERRIDE {} - void calcError(Mat &) CV_OVERRIDE {} - void calcJacobian(Mat &) CV_OVERRIDE {} -}; - - -/** @brief Implementation of the camera parameters refinement algorithm which minimizes sum of the reprojection -error squares - -It can estimate focal length, aspect ratio, principal point. -You can affect only on them via the refinement mask. - */ -class CV_EXPORTS_W BundleAdjusterReproj : public BundleAdjusterBase -{ -public: - CV_WRAP BundleAdjusterReproj() : BundleAdjusterBase(7, 2) {} - -private: - void setUpInitialCameraParams(const std::vector &cameras) CV_OVERRIDE; - void obtainRefinedCameraParams(std::vector &cameras) const CV_OVERRIDE; - void calcError(Mat &err) CV_OVERRIDE; - void calcJacobian(Mat &jac) CV_OVERRIDE; - - Mat err1_, err2_; -}; - - -/** @brief Implementation of the camera parameters refinement algorithm which minimizes sum of the distances -between the rays passing through the camera center and a feature. : - -It can estimate focal length. It ignores the refinement mask for now. - */ -class CV_EXPORTS_W BundleAdjusterRay : public BundleAdjusterBase -{ -public: - CV_WRAP BundleAdjusterRay() : BundleAdjusterBase(4, 3) {} - -private: - void setUpInitialCameraParams(const std::vector &cameras) CV_OVERRIDE; - void obtainRefinedCameraParams(std::vector &cameras) const CV_OVERRIDE; - void calcError(Mat &err) CV_OVERRIDE; - void calcJacobian(Mat &jac) CV_OVERRIDE; - - Mat err1_, err2_; -}; - - -/** @brief Bundle adjuster that expects affine transformation -represented in homogeneous coordinates in R for each camera param. Implements -camera parameters refinement algorithm which minimizes sum of the reprojection -error squares - -It estimates all transformation parameters. Refinement mask is ignored. - -@sa AffineBasedEstimator AffineBestOf2NearestMatcher BundleAdjusterAffinePartial - */ -class CV_EXPORTS_W BundleAdjusterAffine : public BundleAdjusterBase -{ -public: - CV_WRAP BundleAdjusterAffine() : BundleAdjusterBase(6, 2) {} - -private: - void setUpInitialCameraParams(const std::vector &cameras) CV_OVERRIDE; - void obtainRefinedCameraParams(std::vector &cameras) const CV_OVERRIDE; - void calcError(Mat &err) CV_OVERRIDE; - void calcJacobian(Mat &jac) CV_OVERRIDE; - - Mat err1_, err2_; -}; - - -/** @brief Bundle adjuster that expects affine transformation with 4 DOF -represented in homogeneous coordinates in R for each camera param. Implements -camera parameters refinement algorithm which minimizes sum of the reprojection -error squares - -It estimates all transformation parameters. Refinement mask is ignored. - -@sa AffineBasedEstimator AffineBestOf2NearestMatcher BundleAdjusterAffine - */ -class CV_EXPORTS_W BundleAdjusterAffinePartial : public BundleAdjusterBase -{ -public: - CV_WRAP BundleAdjusterAffinePartial() : BundleAdjusterBase(4, 2) {} - -private: - void setUpInitialCameraParams(const std::vector &cameras) CV_OVERRIDE; - void obtainRefinedCameraParams(std::vector &cameras) const CV_OVERRIDE; - void calcError(Mat &err) CV_OVERRIDE; - void calcJacobian(Mat &jac) CV_OVERRIDE; - - Mat err1_, err2_; -}; - - -enum WaveCorrectKind -{ - WAVE_CORRECT_HORIZ, - WAVE_CORRECT_VERT, - WAVE_CORRECT_AUTO -}; - -/** @brief Tries to detect the wave correction kind depending -on whether a panorama spans horizontally or vertically - -@param rmats Camera rotation matrices. -@return The correction kind to use for this panorama - */ -CV_EXPORTS -WaveCorrectKind autoDetectWaveCorrectKind(const std::vector &rmats); - -/** @brief Tries to make panorama more horizontal (or vertical). - -@param rmats Camera rotation matrices. -@param kind Correction kind, see detail::WaveCorrectKind. - */ -void CV_EXPORTS_W waveCorrect(CV_IN_OUT std::vector &rmats, WaveCorrectKind kind); - - -////////////////////////////////////////////////////////////////////////////// -// Auxiliary functions - -// Returns matches graph representation in DOT language -String CV_EXPORTS_W matchesGraphAsString(std::vector &paths, std::vector &pairwise_matches, - float conf_threshold); - -CV_EXPORTS_W std::vector leaveBiggestComponent( - std::vector &features, - std::vector &pairwise_matches, - float conf_threshold); - -void CV_EXPORTS findMaxSpanningTree( - int num_images, const std::vector &pairwise_matches, - Graph &span_tree, std::vector ¢ers); - -//! @} stitching_rotation - -} // namespace detail -} // namespace cv - -#endif // OPENCV_STITCHING_MOTION_ESTIMATORS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_STITCHING_MOTION_ESTIMATORS_HPP +#define OPENCV_STITCHING_MOTION_ESTIMATORS_HPP + +#include "opencv2/core.hpp" +#include "matchers.hpp" +#include "util.hpp" +#include "camera.hpp" + +namespace cv { +namespace detail { + +//! @addtogroup stitching_rotation +//! @{ + +/** @brief Rotation estimator base class. + +It takes features of all images, pairwise matches between all images and estimates rotations of all +cameras. + +@note The coordinate system origin is implementation-dependent, but you can always normalize the +rotations in respect to the first camera, for instance. : + */ +class CV_EXPORTS_W Estimator +{ +public: + virtual ~Estimator() {} + + /** @brief Estimates camera parameters. + + @param features Features of images + @param pairwise_matches Pairwise matches of images + @param cameras Estimated camera parameters + @return True in case of success, false otherwise + */ + CV_WRAP_AS(apply) bool operator ()(const std::vector &features, + const std::vector &pairwise_matches, + CV_OUT CV_IN_OUT std::vector &cameras) + { + return estimate(features, pairwise_matches, cameras); + } + +protected: + /** @brief This method must implement camera parameters estimation logic in order to make the wrapper + detail::Estimator::operator()_ work. + + @param features Features of images + @param pairwise_matches Pairwise matches of images + @param cameras Estimated camera parameters + @return True in case of success, false otherwise + */ + virtual bool estimate(const std::vector &features, + const std::vector &pairwise_matches, + CV_OUT std::vector &cameras) = 0; +}; + +/** @brief Homography based rotation estimator. + */ +class CV_EXPORTS_W HomographyBasedEstimator : public Estimator +{ +public: + CV_WRAP HomographyBasedEstimator(bool is_focals_estimated = false) + : is_focals_estimated_(is_focals_estimated) {} + +private: + virtual bool estimate(const std::vector &features, + const std::vector &pairwise_matches, + std::vector &cameras) CV_OVERRIDE; + + bool is_focals_estimated_; +}; + +/** @brief Affine transformation based estimator. + +This estimator uses pairwise transformations estimated by matcher to estimate +final transformation for each camera. + +@sa cv::detail::HomographyBasedEstimator + */ +class CV_EXPORTS_W AffineBasedEstimator : public Estimator +{ +public: + CV_WRAP AffineBasedEstimator(){} +private: + virtual bool estimate(const std::vector &features, + const std::vector &pairwise_matches, + std::vector &cameras) CV_OVERRIDE; +}; + +/** @brief Base class for all camera parameters refinement methods. + */ +class CV_EXPORTS_W BundleAdjusterBase : public Estimator +{ +public: + CV_WRAP Mat refinementMask() const { return refinement_mask_.clone(); } + CV_WRAP void setRefinementMask(const Mat &mask) + { + CV_Assert(mask.type() == CV_8U && mask.size() == Size(3, 3)); + refinement_mask_ = mask.clone(); + } + + CV_WRAP double confThresh() const { return conf_thresh_; } + CV_WRAP void setConfThresh(double conf_thresh) { conf_thresh_ = conf_thresh; } + + CV_WRAP TermCriteria termCriteria() { return term_criteria_; } + CV_WRAP void setTermCriteria(const TermCriteria& term_criteria) { term_criteria_ = term_criteria; } + +protected: + /** @brief Construct a bundle adjuster base instance. + + @param num_params_per_cam Number of parameters per camera + @param num_errs_per_measurement Number of error terms (components) per match + */ + BundleAdjusterBase(int num_params_per_cam, int num_errs_per_measurement) + : num_images_(0), total_num_matches_(0), + num_params_per_cam_(num_params_per_cam), + num_errs_per_measurement_(num_errs_per_measurement), + features_(0), pairwise_matches_(0), conf_thresh_(0) + { + setRefinementMask(Mat::ones(3, 3, CV_8U)); + setConfThresh(1.); + setTermCriteria(TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 1000, DBL_EPSILON)); + } + + // Runs bundle adjustment + virtual bool estimate(const std::vector &features, + const std::vector &pairwise_matches, + std::vector &cameras) CV_OVERRIDE; + + /** @brief Sets initial camera parameter to refine. + + @param cameras Camera parameters + */ + virtual void setUpInitialCameraParams(const std::vector &cameras) = 0; + /** @brief Gets the refined camera parameters. + + @param cameras Refined camera parameters + */ + virtual void obtainRefinedCameraParams(std::vector &cameras) const = 0; + /** @brief Calculates error vector. + + @param err Error column-vector of length total_num_matches \* num_errs_per_measurement + */ + virtual void calcError(Mat &err) = 0; + /** @brief Calculates the cost function jacobian. + + @param jac Jacobian matrix of dimensions + (total_num_matches \* num_errs_per_measurement) x (num_images \* num_params_per_cam) + */ + virtual void calcJacobian(Mat &jac) = 0; + + // 3x3 8U mask, where 0 means don't refine respective parameter, != 0 means refine + Mat refinement_mask_; + + int num_images_; + int total_num_matches_; + + int num_params_per_cam_; + int num_errs_per_measurement_; + + const ImageFeatures *features_; + const MatchesInfo *pairwise_matches_; + + // Threshold to filter out poorly matched image pairs + double conf_thresh_; + + //Levenberg-Marquardt algorithm termination criteria + TermCriteria term_criteria_; + + // Camera parameters matrix (CV_64F) + Mat cam_params_; + + // Connected images pairs + std::vector > edges_; +}; + + +/** @brief Stub bundle adjuster that does nothing. + */ +class CV_EXPORTS_W NoBundleAdjuster : public BundleAdjusterBase +{ +public: + CV_WRAP NoBundleAdjuster() : BundleAdjusterBase(0, 0) {} + +private: + bool estimate(const std::vector &, const std::vector &, + std::vector &) CV_OVERRIDE + { + return true; + } + void setUpInitialCameraParams(const std::vector &) CV_OVERRIDE {} + void obtainRefinedCameraParams(std::vector &) const CV_OVERRIDE {} + void calcError(Mat &) CV_OVERRIDE {} + void calcJacobian(Mat &) CV_OVERRIDE {} +}; + + +/** @brief Implementation of the camera parameters refinement algorithm which minimizes sum of the reprojection +error squares + +It can estimate focal length, aspect ratio, principal point. +You can affect only on them via the refinement mask. + */ +class CV_EXPORTS_W BundleAdjusterReproj : public BundleAdjusterBase +{ +public: + CV_WRAP BundleAdjusterReproj() : BundleAdjusterBase(7, 2) {} + +private: + void setUpInitialCameraParams(const std::vector &cameras) CV_OVERRIDE; + void obtainRefinedCameraParams(std::vector &cameras) const CV_OVERRIDE; + void calcError(Mat &err) CV_OVERRIDE; + void calcJacobian(Mat &jac) CV_OVERRIDE; + + Mat err1_, err2_; +}; + + +/** @brief Implementation of the camera parameters refinement algorithm which minimizes sum of the distances +between the rays passing through the camera center and a feature. : + +It can estimate focal length. It ignores the refinement mask for now. + */ +class CV_EXPORTS_W BundleAdjusterRay : public BundleAdjusterBase +{ +public: + CV_WRAP BundleAdjusterRay() : BundleAdjusterBase(4, 3) {} + +private: + void setUpInitialCameraParams(const std::vector &cameras) CV_OVERRIDE; + void obtainRefinedCameraParams(std::vector &cameras) const CV_OVERRIDE; + void calcError(Mat &err) CV_OVERRIDE; + void calcJacobian(Mat &jac) CV_OVERRIDE; + + Mat err1_, err2_; +}; + + +/** @brief Bundle adjuster that expects affine transformation +represented in homogeneous coordinates in R for each camera param. Implements +camera parameters refinement algorithm which minimizes sum of the reprojection +error squares + +It estimates all transformation parameters. Refinement mask is ignored. + +@sa AffineBasedEstimator AffineBestOf2NearestMatcher BundleAdjusterAffinePartial + */ +class CV_EXPORTS_W BundleAdjusterAffine : public BundleAdjusterBase +{ +public: + CV_WRAP BundleAdjusterAffine() : BundleAdjusterBase(6, 2) {} + +private: + void setUpInitialCameraParams(const std::vector &cameras) CV_OVERRIDE; + void obtainRefinedCameraParams(std::vector &cameras) const CV_OVERRIDE; + void calcError(Mat &err) CV_OVERRIDE; + void calcJacobian(Mat &jac) CV_OVERRIDE; + + Mat err1_, err2_; +}; + + +/** @brief Bundle adjuster that expects affine transformation with 4 DOF +represented in homogeneous coordinates in R for each camera param. Implements +camera parameters refinement algorithm which minimizes sum of the reprojection +error squares + +It estimates all transformation parameters. Refinement mask is ignored. + +@sa AffineBasedEstimator AffineBestOf2NearestMatcher BundleAdjusterAffine + */ +class CV_EXPORTS_W BundleAdjusterAffinePartial : public BundleAdjusterBase +{ +public: + CV_WRAP BundleAdjusterAffinePartial() : BundleAdjusterBase(4, 2) {} + +private: + void setUpInitialCameraParams(const std::vector &cameras) CV_OVERRIDE; + void obtainRefinedCameraParams(std::vector &cameras) const CV_OVERRIDE; + void calcError(Mat &err) CV_OVERRIDE; + void calcJacobian(Mat &jac) CV_OVERRIDE; + + Mat err1_, err2_; +}; + + +enum WaveCorrectKind +{ + WAVE_CORRECT_HORIZ, + WAVE_CORRECT_VERT, + WAVE_CORRECT_AUTO +}; + +/** @brief Tries to detect the wave correction kind depending +on whether a panorama spans horizontally or vertically + +@param rmats Camera rotation matrices. +@return The correction kind to use for this panorama + */ +CV_EXPORTS +WaveCorrectKind autoDetectWaveCorrectKind(const std::vector &rmats); + +/** @brief Tries to make panorama more horizontal (or vertical). + +@param rmats Camera rotation matrices. +@param kind Correction kind, see detail::WaveCorrectKind. + */ +void CV_EXPORTS_W waveCorrect(CV_IN_OUT std::vector &rmats, WaveCorrectKind kind); + + +////////////////////////////////////////////////////////////////////////////// +// Auxiliary functions + +// Returns matches graph representation in DOT language +String CV_EXPORTS_W matchesGraphAsString(std::vector &paths, std::vector &pairwise_matches, + float conf_threshold); + +CV_EXPORTS_W std::vector leaveBiggestComponent( + std::vector &features, + std::vector &pairwise_matches, + float conf_threshold); + +void CV_EXPORTS findMaxSpanningTree( + int num_images, const std::vector &pairwise_matches, + Graph &span_tree, std::vector ¢ers); + +//! @} stitching_rotation + +} // namespace detail +} // namespace cv + +#endif // OPENCV_STITCHING_MOTION_ESTIMATORS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/seam_finders.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/seam_finders.hpp index 9ccfd14424..1c13cce101 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/seam_finders.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/seam_finders.hpp @@ -1,291 +1,291 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_STITCHING_SEAM_FINDERS_HPP -#define OPENCV_STITCHING_SEAM_FINDERS_HPP - -#include -#include "opencv2/core.hpp" -#include "opencv2/opencv_modules.hpp" - -namespace cv { -namespace detail { - -//! @addtogroup stitching_seam -//! @{ - -/** @brief Base class for a seam estimator. - */ -class CV_EXPORTS_W SeamFinder -{ -public: - CV_WRAP virtual ~SeamFinder() {} - enum { NO, VORONOI_SEAM, DP_SEAM }; - /** @brief Estimates seams. - - @param src Source images - @param corners Source image top-left corners - @param masks Source image masks to update - */ - CV_WRAP virtual void find(const std::vector &src, const std::vector &corners, - CV_IN_OUT std::vector &masks) = 0; - CV_WRAP static Ptr createDefault(int type); -}; - -/** @brief Stub seam estimator which does nothing. - */ -class CV_EXPORTS_W NoSeamFinder : public SeamFinder -{ -public: - CV_WRAP void find(const std::vector&, const std::vector&, CV_IN_OUT std::vector&) CV_OVERRIDE {} -}; - -/** @brief Base class for all pairwise seam estimators. - */ -class CV_EXPORTS_W PairwiseSeamFinder : public SeamFinder -{ -public: - CV_WRAP virtual void find(const std::vector &src, const std::vector &corners, - CV_IN_OUT std::vector &masks) CV_OVERRIDE; - -protected: - void run(); - /** @brief Resolves masks intersection of two specified images in the given ROI. - - @param first First image index - @param second Second image index - @param roi Region of interest - */ - virtual void findInPair(size_t first, size_t second, Rect roi) = 0; - - std::vector images_; - std::vector sizes_; - std::vector corners_; - std::vector masks_; -}; - -/** @brief Voronoi diagram-based seam estimator. - */ -class CV_EXPORTS_W VoronoiSeamFinder : public PairwiseSeamFinder -{ -public: - CV_WRAP virtual void find(const std::vector &src, const std::vector &corners, - CV_IN_OUT std::vector &masks) CV_OVERRIDE; - virtual void find(const std::vector &size, const std::vector &corners, - std::vector &masks); -private: - void findInPair(size_t first, size_t second, Rect roi) CV_OVERRIDE; -}; - - -class CV_EXPORTS_W DpSeamFinder : public SeamFinder -{ -public: - enum CostFunction { COLOR, COLOR_GRAD }; - - DpSeamFinder(CostFunction costFunc = COLOR); - CV_WRAP DpSeamFinder(String costFunc ); - - CostFunction costFunction() const { return costFunc_; } - void setCostFunction(CostFunction val) { costFunc_ = val; } - CV_WRAP void setCostFunction(String val); - - virtual void find(const std::vector &src, const std::vector &corners, - std::vector &masks) CV_OVERRIDE; - -private: - enum ComponentState - { - FIRST = 1, SECOND = 2, INTERS = 4, - INTERS_FIRST = INTERS | FIRST, - INTERS_SECOND = INTERS | SECOND - }; - - class ImagePairLess - { - public: - ImagePairLess(const std::vector &images, const std::vector &corners) - : src_(&images[0]), corners_(&corners[0]) {} - - bool operator() (const std::pair &l, const std::pair &r) const - { - Point c1 = corners_[l.first] + Point(src_[l.first].cols / 2, src_[l.first].rows / 2); - Point c2 = corners_[l.second] + Point(src_[l.second].cols / 2, src_[l.second].rows / 2); - int d1 = (c1 - c2).dot(c1 - c2); - - c1 = corners_[r.first] + Point(src_[r.first].cols / 2, src_[r.first].rows / 2); - c2 = corners_[r.second] + Point(src_[r.second].cols / 2, src_[r.second].rows / 2); - int d2 = (c1 - c2).dot(c1 - c2); - - return d1 < d2; - } - - private: - const Mat *src_; - const Point *corners_; - }; - - class ClosePoints - { - public: - ClosePoints(int minDist) : minDist_(minDist) {} - - bool operator() (const Point &p1, const Point &p2) const - { - int dist2 = (p1.x-p2.x) * (p1.x-p2.x) + (p1.y-p2.y) * (p1.y-p2.y); - return dist2 < minDist_ * minDist_; - } - - private: - int minDist_; - }; - - void process( - const Mat &image1, const Mat &image2, Point tl1, Point tl2, Mat &mask1, Mat &mask2); - - void findComponents(); - - void findEdges(); - - void resolveConflicts( - const Mat &image1, const Mat &image2, Point tl1, Point tl2, Mat &mask1, Mat &mask2); - - void computeGradients(const Mat &image1, const Mat &image2); - - bool hasOnlyOneNeighbor(int comp); - - bool closeToContour(int y, int x, const Mat_ &contourMask); - - bool getSeamTips(int comp1, int comp2, Point &p1, Point &p2); - - void computeCosts( - const Mat &image1, const Mat &image2, Point tl1, Point tl2, - int comp, Mat_ &costV, Mat_ &costH); - - bool estimateSeam( - const Mat &image1, const Mat &image2, Point tl1, Point tl2, int comp, - Point p1, Point p2, std::vector &seam, bool &isHorizontal); - - void updateLabelsUsingSeam( - int comp1, int comp2, const std::vector &seam, bool isHorizontalSeam); - - CostFunction costFunc_; - - // processing images pair data - Point unionTl_, unionBr_; - Size unionSize_; - Mat_ mask1_, mask2_; - Mat_ contour1mask_, contour2mask_; - Mat_ gradx1_, grady1_; - Mat_ gradx2_, grady2_; - - // components data - int ncomps_; - Mat_ labels_; - std::vector states_; - std::vector tls_, brs_; - std::vector > contours_; - std::set > edges_; -}; - -/** @brief Base class for all minimum graph-cut-based seam estimators. - */ -class CV_EXPORTS GraphCutSeamFinderBase -{ -public: - enum CostType { COST_COLOR, COST_COLOR_GRAD }; -}; - -/** @brief Minimum graph cut-based seam estimator. See details in @cite V03 . - */ -class CV_EXPORTS_W GraphCutSeamFinder : public GraphCutSeamFinderBase, public SeamFinder -{ -public: - GraphCutSeamFinder(int cost_type = COST_COLOR_GRAD, float terminal_cost = 10000.f, - float bad_region_penalty = 1000.f); - CV_WRAP GraphCutSeamFinder(String cost_type,float terminal_cost = 10000.f, - float bad_region_penalty = 1000.f); - - ~GraphCutSeamFinder(); - - CV_WRAP void find(const std::vector &src, const std::vector &corners, - CV_IN_OUT std::vector &masks) CV_OVERRIDE; - -private: - // To avoid GCGraph dependency - class Impl; - Ptr impl_; -}; - - -#ifdef HAVE_OPENCV_CUDALEGACY -class CV_EXPORTS GraphCutSeamFinderGpu : public GraphCutSeamFinderBase, public PairwiseSeamFinder -{ -public: - GraphCutSeamFinderGpu(int cost_type = COST_COLOR_GRAD, float terminal_cost = 10000.f, - float bad_region_penalty = 1000.f) - : cost_type_(cost_type), terminal_cost_(terminal_cost), - bad_region_penalty_(bad_region_penalty) {} - - void find(const std::vector &src, const std::vector &corners, - std::vector &masks) CV_OVERRIDE; - void findInPair(size_t first, size_t second, Rect roi) CV_OVERRIDE; - -private: - void setGraphWeightsColor(const cv::Mat &img1, const cv::Mat &img2, const cv::Mat &mask1, const cv::Mat &mask2, - cv::Mat &terminals, cv::Mat &leftT, cv::Mat &rightT, cv::Mat &top, cv::Mat &bottom); - void setGraphWeightsColorGrad(const cv::Mat &img1, const cv::Mat &img2, const cv::Mat &dx1, const cv::Mat &dx2, - const cv::Mat &dy1, const cv::Mat &dy2, const cv::Mat &mask1, const cv::Mat &mask2, - cv::Mat &terminals, cv::Mat &leftT, cv::Mat &rightT, cv::Mat &top, cv::Mat &bottom); - std::vector dx_, dy_; - int cost_type_; - float terminal_cost_; - float bad_region_penalty_; -}; -#endif - -//! @} - -} // namespace detail -} // namespace cv - -#endif // OPENCV_STITCHING_SEAM_FINDERS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_STITCHING_SEAM_FINDERS_HPP +#define OPENCV_STITCHING_SEAM_FINDERS_HPP + +#include +#include "opencv2/core.hpp" +#include "opencv2/opencv_modules.hpp" + +namespace cv { +namespace detail { + +//! @addtogroup stitching_seam +//! @{ + +/** @brief Base class for a seam estimator. + */ +class CV_EXPORTS_W SeamFinder +{ +public: + CV_WRAP virtual ~SeamFinder() {} + enum { NO, VORONOI_SEAM, DP_SEAM }; + /** @brief Estimates seams. + + @param src Source images + @param corners Source image top-left corners + @param masks Source image masks to update + */ + CV_WRAP virtual void find(const std::vector &src, const std::vector &corners, + CV_IN_OUT std::vector &masks) = 0; + CV_WRAP static Ptr createDefault(int type); +}; + +/** @brief Stub seam estimator which does nothing. + */ +class CV_EXPORTS_W NoSeamFinder : public SeamFinder +{ +public: + CV_WRAP void find(const std::vector&, const std::vector&, CV_IN_OUT std::vector&) CV_OVERRIDE {} +}; + +/** @brief Base class for all pairwise seam estimators. + */ +class CV_EXPORTS_W PairwiseSeamFinder : public SeamFinder +{ +public: + CV_WRAP virtual void find(const std::vector &src, const std::vector &corners, + CV_IN_OUT std::vector &masks) CV_OVERRIDE; + +protected: + void run(); + /** @brief Resolves masks intersection of two specified images in the given ROI. + + @param first First image index + @param second Second image index + @param roi Region of interest + */ + virtual void findInPair(size_t first, size_t second, Rect roi) = 0; + + std::vector images_; + std::vector sizes_; + std::vector corners_; + std::vector masks_; +}; + +/** @brief Voronoi diagram-based seam estimator. + */ +class CV_EXPORTS_W VoronoiSeamFinder : public PairwiseSeamFinder +{ +public: + CV_WRAP virtual void find(const std::vector &src, const std::vector &corners, + CV_IN_OUT std::vector &masks) CV_OVERRIDE; + virtual void find(const std::vector &size, const std::vector &corners, + std::vector &masks); +private: + void findInPair(size_t first, size_t second, Rect roi) CV_OVERRIDE; +}; + + +class CV_EXPORTS_W DpSeamFinder : public SeamFinder +{ +public: + enum CostFunction { COLOR, COLOR_GRAD }; + + DpSeamFinder(CostFunction costFunc = COLOR); + CV_WRAP DpSeamFinder(String costFunc ); + + CostFunction costFunction() const { return costFunc_; } + void setCostFunction(CostFunction val) { costFunc_ = val; } + CV_WRAP void setCostFunction(String val); + + virtual void find(const std::vector &src, const std::vector &corners, + std::vector &masks) CV_OVERRIDE; + +private: + enum ComponentState + { + FIRST = 1, SECOND = 2, INTERS = 4, + INTERS_FIRST = INTERS | FIRST, + INTERS_SECOND = INTERS | SECOND + }; + + class ImagePairLess + { + public: + ImagePairLess(const std::vector &images, const std::vector &corners) + : src_(&images[0]), corners_(&corners[0]) {} + + bool operator() (const std::pair &l, const std::pair &r) const + { + Point c1 = corners_[l.first] + Point(src_[l.first].cols / 2, src_[l.first].rows / 2); + Point c2 = corners_[l.second] + Point(src_[l.second].cols / 2, src_[l.second].rows / 2); + int d1 = (c1 - c2).dot(c1 - c2); + + c1 = corners_[r.first] + Point(src_[r.first].cols / 2, src_[r.first].rows / 2); + c2 = corners_[r.second] + Point(src_[r.second].cols / 2, src_[r.second].rows / 2); + int d2 = (c1 - c2).dot(c1 - c2); + + return d1 < d2; + } + + private: + const Mat *src_; + const Point *corners_; + }; + + class ClosePoints + { + public: + ClosePoints(int minDist) : minDist_(minDist) {} + + bool operator() (const Point &p1, const Point &p2) const + { + int dist2 = (p1.x-p2.x) * (p1.x-p2.x) + (p1.y-p2.y) * (p1.y-p2.y); + return dist2 < minDist_ * minDist_; + } + + private: + int minDist_; + }; + + void process( + const Mat &image1, const Mat &image2, Point tl1, Point tl2, Mat &mask1, Mat &mask2); + + void findComponents(); + + void findEdges(); + + void resolveConflicts( + const Mat &image1, const Mat &image2, Point tl1, Point tl2, Mat &mask1, Mat &mask2); + + void computeGradients(const Mat &image1, const Mat &image2); + + bool hasOnlyOneNeighbor(int comp); + + bool closeToContour(int y, int x, const Mat_ &contourMask); + + bool getSeamTips(int comp1, int comp2, Point &p1, Point &p2); + + void computeCosts( + const Mat &image1, const Mat &image2, Point tl1, Point tl2, + int comp, Mat_ &costV, Mat_ &costH); + + bool estimateSeam( + const Mat &image1, const Mat &image2, Point tl1, Point tl2, int comp, + Point p1, Point p2, std::vector &seam, bool &isHorizontal); + + void updateLabelsUsingSeam( + int comp1, int comp2, const std::vector &seam, bool isHorizontalSeam); + + CostFunction costFunc_; + + // processing images pair data + Point unionTl_, unionBr_; + Size unionSize_; + Mat_ mask1_, mask2_; + Mat_ contour1mask_, contour2mask_; + Mat_ gradx1_, grady1_; + Mat_ gradx2_, grady2_; + + // components data + int ncomps_; + Mat_ labels_; + std::vector states_; + std::vector tls_, brs_; + std::vector > contours_; + std::set > edges_; +}; + +/** @brief Base class for all minimum graph-cut-based seam estimators. + */ +class CV_EXPORTS GraphCutSeamFinderBase +{ +public: + enum CostType { COST_COLOR, COST_COLOR_GRAD }; +}; + +/** @brief Minimum graph cut-based seam estimator. See details in @cite V03 . + */ +class CV_EXPORTS_W GraphCutSeamFinder : public GraphCutSeamFinderBase, public SeamFinder +{ +public: + GraphCutSeamFinder(int cost_type = COST_COLOR_GRAD, float terminal_cost = 10000.f, + float bad_region_penalty = 1000.f); + CV_WRAP GraphCutSeamFinder(String cost_type,float terminal_cost = 10000.f, + float bad_region_penalty = 1000.f); + + ~GraphCutSeamFinder(); + + CV_WRAP void find(const std::vector &src, const std::vector &corners, + CV_IN_OUT std::vector &masks) CV_OVERRIDE; + +private: + // To avoid GCGraph dependency + class Impl; + Ptr impl_; +}; + + +#ifdef HAVE_OPENCV_CUDALEGACY +class CV_EXPORTS GraphCutSeamFinderGpu : public GraphCutSeamFinderBase, public PairwiseSeamFinder +{ +public: + GraphCutSeamFinderGpu(int cost_type = COST_COLOR_GRAD, float terminal_cost = 10000.f, + float bad_region_penalty = 1000.f) + : cost_type_(cost_type), terminal_cost_(terminal_cost), + bad_region_penalty_(bad_region_penalty) {} + + void find(const std::vector &src, const std::vector &corners, + std::vector &masks) CV_OVERRIDE; + void findInPair(size_t first, size_t second, Rect roi) CV_OVERRIDE; + +private: + void setGraphWeightsColor(const cv::Mat &img1, const cv::Mat &img2, const cv::Mat &mask1, const cv::Mat &mask2, + cv::Mat &terminals, cv::Mat &leftT, cv::Mat &rightT, cv::Mat &top, cv::Mat &bottom); + void setGraphWeightsColorGrad(const cv::Mat &img1, const cv::Mat &img2, const cv::Mat &dx1, const cv::Mat &dx2, + const cv::Mat &dy1, const cv::Mat &dy2, const cv::Mat &mask1, const cv::Mat &mask2, + cv::Mat &terminals, cv::Mat &leftT, cv::Mat &rightT, cv::Mat &top, cv::Mat &bottom); + std::vector dx_, dy_; + int cost_type_; + float terminal_cost_; + float bad_region_penalty_; +}; +#endif + +//! @} + +} // namespace detail +} // namespace cv + +#endif // OPENCV_STITCHING_SEAM_FINDERS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/timelapsers.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/timelapsers.hpp index f6f3da8a8d..479fe14802 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/timelapsers.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/timelapsers.hpp @@ -1,91 +1,91 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - - -#ifndef OPENCV_STITCHING_TIMELAPSERS_HPP -#define OPENCV_STITCHING_TIMELAPSERS_HPP - -#include "opencv2/core.hpp" - -namespace cv { -namespace detail { - -//! @addtogroup stitching -//! @{ - -// Base Timelapser class, takes a sequence of images, applies appropriate shift, stores result in dst_. - -class CV_EXPORTS_W Timelapser -{ -public: - - enum {AS_IS, CROP}; - - virtual ~Timelapser() {} - - CV_WRAP static Ptr createDefault(int type); - - CV_WRAP virtual void initialize(const std::vector &corners, const std::vector &sizes); - CV_WRAP virtual void process(InputArray img, InputArray mask, Point tl); - CV_WRAP virtual const UMat& getDst() {return dst_;} - -protected: - - virtual bool test_point(Point pt); - - UMat dst_; - Rect dst_roi_; -}; - - -class CV_EXPORTS_W TimelapserCrop : public Timelapser -{ -public: - virtual void initialize(const std::vector &corners, const std::vector &sizes) CV_OVERRIDE; -}; - -//! @} - -} // namespace detail -} // namespace cv - -#endif // OPENCV_STITCHING_TIMELAPSERS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + + +#ifndef OPENCV_STITCHING_TIMELAPSERS_HPP +#define OPENCV_STITCHING_TIMELAPSERS_HPP + +#include "opencv2/core.hpp" + +namespace cv { +namespace detail { + +//! @addtogroup stitching +//! @{ + +// Base Timelapser class, takes a sequence of images, applies appropriate shift, stores result in dst_. + +class CV_EXPORTS_W Timelapser +{ +public: + + enum {AS_IS, CROP}; + + virtual ~Timelapser() {} + + CV_WRAP static Ptr createDefault(int type); + + CV_WRAP virtual void initialize(const std::vector &corners, const std::vector &sizes); + CV_WRAP virtual void process(InputArray img, InputArray mask, Point tl); + CV_WRAP virtual const UMat& getDst() {return dst_;} + +protected: + + virtual bool test_point(Point pt); + + UMat dst_; + Rect dst_roi_; +}; + + +class CV_EXPORTS_W TimelapserCrop : public Timelapser +{ +public: + virtual void initialize(const std::vector &corners, const std::vector &sizes) CV_OVERRIDE; +}; + +//! @} + +} // namespace detail +} // namespace cv + +#endif // OPENCV_STITCHING_TIMELAPSERS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/util.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/util.hpp index bf7a39098c..44b29d8513 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/util.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/util.hpp @@ -1,121 +1,121 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_STITCHING_UTIL_HPP -#define OPENCV_STITCHING_UTIL_HPP - -#include -#include "opencv2/core.hpp" - -namespace cv { -namespace detail { - -//! @addtogroup stitching -//! @{ - -class CV_EXPORTS DisjointSets -{ -public: - DisjointSets(int elem_count = 0) { createOneElemSets(elem_count); } - - void createOneElemSets(int elem_count); - int findSetByElem(int elem); - int mergeSets(int set1, int set2); - - std::vector parent; - std::vector size; - -private: - std::vector rank_; -}; - - -struct CV_EXPORTS GraphEdge -{ - GraphEdge(int from, int to, float weight); - bool operator <(const GraphEdge& other) const { return weight < other.weight; } - bool operator >(const GraphEdge& other) const { return weight > other.weight; } - - int from, to; - float weight; -}; - -inline GraphEdge::GraphEdge(int _from, int _to, float _weight) : from(_from), to(_to), weight(_weight) {} - - -class CV_EXPORTS Graph -{ -public: - Graph(int num_vertices = 0) { create(num_vertices); } - void create(int num_vertices) { edges_.assign(num_vertices, std::list()); } - int numVertices() const { return static_cast(edges_.size()); } - void addEdge(int from, int to, float weight); - template B forEach(B body) const; - template B walkBreadthFirst(int from, B body) const; - -private: - std::vector< std::list > edges_; -}; - - -////////////////////////////////////////////////////////////////////////////// -// Auxiliary functions - -CV_EXPORTS_W bool overlapRoi(Point tl1, Point tl2, Size sz1, Size sz2, Rect &roi); -CV_EXPORTS_W Rect resultRoi(const std::vector &corners, const std::vector &images); -CV_EXPORTS_W Rect resultRoi(const std::vector &corners, const std::vector &sizes); -CV_EXPORTS_W Rect resultRoiIntersection(const std::vector &corners, const std::vector &sizes); -CV_EXPORTS_W Point resultTl(const std::vector &corners); - -// Returns random 'count' element subset of the {0,1,...,size-1} set -CV_EXPORTS_W void selectRandomSubset(int count, int size, std::vector &subset); - -CV_EXPORTS_W int& stitchingLogLevel(); - -//! @} - -} // namespace detail -} // namespace cv - -#include "util_inl.hpp" - -#endif // OPENCV_STITCHING_UTIL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_STITCHING_UTIL_HPP +#define OPENCV_STITCHING_UTIL_HPP + +#include +#include "opencv2/core.hpp" + +namespace cv { +namespace detail { + +//! @addtogroup stitching +//! @{ + +class CV_EXPORTS DisjointSets +{ +public: + DisjointSets(int elem_count = 0) { createOneElemSets(elem_count); } + + void createOneElemSets(int elem_count); + int findSetByElem(int elem); + int mergeSets(int set1, int set2); + + std::vector parent; + std::vector size; + +private: + std::vector rank_; +}; + + +struct CV_EXPORTS GraphEdge +{ + GraphEdge(int from, int to, float weight); + bool operator <(const GraphEdge& other) const { return weight < other.weight; } + bool operator >(const GraphEdge& other) const { return weight > other.weight; } + + int from, to; + float weight; +}; + +inline GraphEdge::GraphEdge(int _from, int _to, float _weight) : from(_from), to(_to), weight(_weight) {} + + +class CV_EXPORTS Graph +{ +public: + Graph(int num_vertices = 0) { create(num_vertices); } + void create(int num_vertices) { edges_.assign(num_vertices, std::list()); } + int numVertices() const { return static_cast(edges_.size()); } + void addEdge(int from, int to, float weight); + template B forEach(B body) const; + template B walkBreadthFirst(int from, B body) const; + +private: + std::vector< std::list > edges_; +}; + + +////////////////////////////////////////////////////////////////////////////// +// Auxiliary functions + +CV_EXPORTS_W bool overlapRoi(Point tl1, Point tl2, Size sz1, Size sz2, Rect &roi); +CV_EXPORTS_W Rect resultRoi(const std::vector &corners, const std::vector &images); +CV_EXPORTS_W Rect resultRoi(const std::vector &corners, const std::vector &sizes); +CV_EXPORTS_W Rect resultRoiIntersection(const std::vector &corners, const std::vector &sizes); +CV_EXPORTS_W Point resultTl(const std::vector &corners); + +// Returns random 'count' element subset of the {0,1,...,size-1} set +CV_EXPORTS_W void selectRandomSubset(int count, int size, std::vector &subset); + +CV_EXPORTS_W int& stitchingLogLevel(); + +//! @} + +} // namespace detail +} // namespace cv + +#include "util_inl.hpp" + +#endif // OPENCV_STITCHING_UTIL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/util_inl.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/util_inl.hpp index dafab8b811..a70bf1ad5e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/util_inl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/util_inl.hpp @@ -1,131 +1,131 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_STITCHING_UTIL_INL_HPP -#define OPENCV_STITCHING_UTIL_INL_HPP - -#include -#include "opencv2/core.hpp" -#include "util.hpp" // Make your IDE see declarations - -//! @cond IGNORED - -namespace cv { -namespace detail { - -template -B Graph::forEach(B body) const -{ - for (int i = 0; i < numVertices(); ++i) - { - std::list::const_iterator edge = edges_[i].begin(); - for (; edge != edges_[i].end(); ++edge) - body(*edge); - } - return body; -} - - -template -B Graph::walkBreadthFirst(int from, B body) const -{ - std::vector was(numVertices(), false); - std::queue vertices; - - was[from] = true; - vertices.push(from); - - while (!vertices.empty()) - { - int vertex = vertices.front(); - vertices.pop(); - - std::list::const_iterator edge = edges_[vertex].begin(); - for (; edge != edges_[vertex].end(); ++edge) - { - if (!was[edge->to]) - { - body(*edge); - was[edge->to] = true; - vertices.push(edge->to); - } - } - } - - return body; -} - - -////////////////////////////////////////////////////////////////////////////// -// Some auxiliary math functions - -static inline -float normL2(const Point3f& a) -{ - return a.x * a.x + a.y * a.y + a.z * a.z; -} - - -static inline -float normL2(const Point3f& a, const Point3f& b) -{ - return normL2(a - b); -} - - -static inline -double normL2sq(const Mat &r) -{ - return r.dot(r); -} - - -static inline int sqr(int x) { return x * x; } -static inline float sqr(float x) { return x * x; } -static inline double sqr(double x) { return x * x; } - -} // namespace detail -} // namespace cv - -//! @endcond - -#endif // OPENCV_STITCHING_UTIL_INL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_STITCHING_UTIL_INL_HPP +#define OPENCV_STITCHING_UTIL_INL_HPP + +#include +#include "opencv2/core.hpp" +#include "util.hpp" // Make your IDE see declarations + +//! @cond IGNORED + +namespace cv { +namespace detail { + +template +B Graph::forEach(B body) const +{ + for (int i = 0; i < numVertices(); ++i) + { + std::list::const_iterator edge = edges_[i].begin(); + for (; edge != edges_[i].end(); ++edge) + body(*edge); + } + return body; +} + + +template +B Graph::walkBreadthFirst(int from, B body) const +{ + std::vector was(numVertices(), false); + std::queue vertices; + + was[from] = true; + vertices.push(from); + + while (!vertices.empty()) + { + int vertex = vertices.front(); + vertices.pop(); + + std::list::const_iterator edge = edges_[vertex].begin(); + for (; edge != edges_[vertex].end(); ++edge) + { + if (!was[edge->to]) + { + body(*edge); + was[edge->to] = true; + vertices.push(edge->to); + } + } + } + + return body; +} + + +////////////////////////////////////////////////////////////////////////////// +// Some auxiliary math functions + +static inline +float normL2(const Point3f& a) +{ + return a.x * a.x + a.y * a.y + a.z * a.z; +} + + +static inline +float normL2(const Point3f& a, const Point3f& b) +{ + return normL2(a - b); +} + + +static inline +double normL2sq(const Mat &r) +{ + return r.dot(r); +} + + +static inline int sqr(int x) { return x * x; } +static inline float sqr(float x) { return x * x; } +static inline double sqr(double x) { return x * x; } + +} // namespace detail +} // namespace cv + +//! @endcond + +#endif // OPENCV_STITCHING_UTIL_INL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/warpers.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/warpers.hpp index d0d7869d45..7dd16871e7 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/warpers.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/warpers.hpp @@ -1,706 +1,706 @@ - /*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_STITCHING_WARPERS_HPP -#define OPENCV_STITCHING_WARPERS_HPP - -#include "opencv2/core.hpp" -#include "opencv2/core/cuda.hpp" -#include "opencv2/imgproc.hpp" -#include "opencv2/opencv_modules.hpp" - -namespace cv { -namespace detail { - -//! @addtogroup stitching_warp -//! @{ - -/** @brief Rotation-only model image warper interface. - */ -class CV_EXPORTS RotationWarper -{ -public: - virtual ~RotationWarper() {} - - /** @brief Projects the image point. - - @param pt Source point - @param K Camera intrinsic parameters - @param R Camera rotation matrix - @return Projected point - */ - virtual Point2f warpPoint(const Point2f &pt, InputArray K, InputArray R) = 0; - - /** @brief Projects the image point backward. - - @param pt Projected point - @param K Camera intrinsic parameters - @param R Camera rotation matrix - @return Backward-projected point - */ -#if CV_VERSION_MAJOR == 4 - virtual Point2f warpPointBackward(const Point2f& pt, InputArray K, InputArray R) - { - CV_UNUSED(pt); CV_UNUSED(K); CV_UNUSED(R); - CV_Error(Error::StsNotImplemented, ""); - } -#else - virtual Point2f warpPointBackward(const Point2f& pt, InputArray K, InputArray R) = 0; -#endif - - /** @brief Builds the projection maps according to the given camera data. - - @param src_size Source image size - @param K Camera intrinsic parameters - @param R Camera rotation matrix - @param xmap Projection map for the x axis - @param ymap Projection map for the y axis - @return Projected image minimum bounding box - */ - virtual Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) = 0; - - /** @brief Projects the image. - - @param src Source image - @param K Camera intrinsic parameters - @param R Camera rotation matrix - @param interp_mode Interpolation mode - @param border_mode Border extrapolation mode - @param dst Projected image - @return Project image top-left corner - */ - virtual Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, - CV_OUT OutputArray dst) = 0; - - /** @brief Projects the image backward. - - @param src Projected image - @param K Camera intrinsic parameters - @param R Camera rotation matrix - @param interp_mode Interpolation mode - @param border_mode Border extrapolation mode - @param dst_size Backward-projected image size - @param dst Backward-projected image - */ - virtual void warpBackward(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, - Size dst_size, CV_OUT OutputArray dst) = 0; - - /** - @param src_size Source image bounding box - @param K Camera intrinsic parameters - @param R Camera rotation matrix - @return Projected image minimum bounding box - */ - virtual Rect warpRoi(Size src_size, InputArray K, InputArray R) = 0; - - virtual float getScale() const { return 1.f; } - virtual void setScale(float) {} -}; - -/** @brief Base class for warping logic implementation. - */ -struct CV_EXPORTS_W_SIMPLE ProjectorBase -{ - void setCameraParams(InputArray K = Mat::eye(3, 3, CV_32F), - InputArray R = Mat::eye(3, 3, CV_32F), - InputArray T = Mat::zeros(3, 1, CV_32F)); - - float scale; - float k[9]; - float rinv[9]; - float r_kinv[9]; - float k_rinv[9]; - float t[3]; -}; - -/** @brief Base class for rotation-based warper using a detail::ProjectorBase_ derived class. - */ -template -class CV_EXPORTS_TEMPLATE RotationWarperBase : public RotationWarper -{ -public: - Point2f warpPoint(const Point2f &pt, InputArray K, InputArray R) CV_OVERRIDE; - - Point2f warpPointBackward(const Point2f &pt, InputArray K, InputArray R) CV_OVERRIDE; - - Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) CV_OVERRIDE; - - Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, - OutputArray dst) CV_OVERRIDE; - - void warpBackward(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, - Size dst_size, OutputArray dst) CV_OVERRIDE; - - Rect warpRoi(Size src_size, InputArray K, InputArray R) CV_OVERRIDE; - - float getScale() const CV_OVERRIDE{ return projector_.scale; } - void setScale(float val) CV_OVERRIDE { projector_.scale = val; } - -protected: - - // Detects ROI of the destination image. It's correct for any projection. - virtual void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br); - - // Detects ROI of the destination image by walking over image border. - // Correctness for any projection isn't guaranteed. - void detectResultRoiByBorder(Size src_size, Point &dst_tl, Point &dst_br); - - P projector_; -}; - - -struct CV_EXPORTS PlaneProjector : ProjectorBase -{ - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - -/** @brief Warper that maps an image onto the z = 1 plane. - */ -class CV_EXPORTS PlaneWarper : public RotationWarperBase -{ -public: - /** @brief Construct an instance of the plane warper class. - - @param scale Projected image scale multiplier - */ - PlaneWarper(float scale = 1.f) { projector_.scale = scale; } - - Point2f warpPoint(const Point2f &pt, InputArray K, InputArray R) CV_OVERRIDE; - Point2f warpPoint(const Point2f &pt, InputArray K, InputArray R, InputArray T); - - Point2f warpPointBackward(const Point2f& pt, InputArray K, InputArray R) CV_OVERRIDE; - Point2f warpPointBackward(const Point2f& pt, InputArray K, InputArray R, InputArray T); - - virtual Rect buildMaps(Size src_size, InputArray K, InputArray R, InputArray T, CV_OUT OutputArray xmap, CV_OUT OutputArray ymap); - Rect buildMaps(Size src_size, InputArray K, InputArray R, CV_OUT OutputArray xmap, CV_OUT OutputArray ymap) CV_OVERRIDE; - - Point warp(InputArray src, InputArray K, InputArray R, - int interp_mode, int border_mode, CV_OUT OutputArray dst) CV_OVERRIDE; - virtual Point warp(InputArray src, InputArray K, InputArray R, InputArray T, int interp_mode, int border_mode, - CV_OUT OutputArray dst); - - Rect warpRoi(Size src_size, InputArray K, InputArray R) CV_OVERRIDE; - Rect warpRoi(Size src_size, InputArray K, InputArray R, InputArray T); - -protected: - void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) CV_OVERRIDE; -}; - - -/** @brief Affine warper that uses rotations and translations - - Uses affine transformation in homogeneous coordinates to represent both rotation and - translation in camera rotation matrix. - */ -class CV_EXPORTS AffineWarper : public PlaneWarper -{ -public: - /** @brief Construct an instance of the affine warper class. - - @param scale Projected image scale multiplier - */ - AffineWarper(float scale = 1.f) : PlaneWarper(scale) {} - - /** @brief Projects the image point. - - @param pt Source point - @param K Camera intrinsic parameters - @param H Camera extrinsic parameters - @return Projected point - */ - Point2f warpPoint(const Point2f &pt, InputArray K, InputArray H) CV_OVERRIDE; - - /** @brief Projects the image point backward. - - @param pt Projected point - @param K Camera intrinsic parameters - @param H Camera extrinsic parameters - @return Backward-projected point - */ - Point2f warpPointBackward(const Point2f &pt, InputArray K, InputArray H) CV_OVERRIDE; - - /** @brief Builds the projection maps according to the given camera data. - - @param src_size Source image size - @param K Camera intrinsic parameters - @param H Camera extrinsic parameters - @param xmap Projection map for the x axis - @param ymap Projection map for the y axis - @return Projected image minimum bounding box - */ - Rect buildMaps(Size src_size, InputArray K, InputArray H, OutputArray xmap, OutputArray ymap) CV_OVERRIDE; - - /** @brief Projects the image. - - @param src Source image - @param K Camera intrinsic parameters - @param H Camera extrinsic parameters - @param interp_mode Interpolation mode - @param border_mode Border extrapolation mode - @param dst Projected image - @return Project image top-left corner - */ - Point warp(InputArray src, InputArray K, InputArray H, - int interp_mode, int border_mode, OutputArray dst) CV_OVERRIDE; - - /** - @param src_size Source image bounding box - @param K Camera intrinsic parameters - @param H Camera extrinsic parameters - @return Projected image minimum bounding box - */ - Rect warpRoi(Size src_size, InputArray K, InputArray H) CV_OVERRIDE; - -protected: - /** @brief Extracts rotation and translation matrices from matrix H representing - affine transformation in homogeneous coordinates - */ - void getRTfromHomogeneous(InputArray H, Mat &R, Mat &T); -}; - - -struct CV_EXPORTS_W_SIMPLE SphericalProjector : ProjectorBase -{ - CV_WRAP void mapForward(float x, float y, float &u, float &v); - CV_WRAP void mapBackward(float u, float v, float &x, float &y); -}; - - -/** @brief Warper that maps an image onto the unit sphere located at the origin. - - Projects image onto unit sphere with origin at (0, 0, 0) and radius scale, measured in pixels. - A 360 panorama would therefore have a resulting width of 2 * scale * PI pixels. - Poles are located at (0, -1, 0) and (0, 1, 0) points. -*/ -class CV_EXPORTS SphericalWarper : public RotationWarperBase -{ -public: - /** @brief Construct an instance of the spherical warper class. - - @param scale Radius of the projected sphere, in pixels. An image spanning the - whole sphere will have a width of 2 * scale * PI pixels. - */ - SphericalWarper(float scale) { projector_.scale = scale; } - - Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) CV_OVERRIDE; - Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, OutputArray dst) CV_OVERRIDE; -protected: - void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) CV_OVERRIDE; -}; - - -struct CV_EXPORTS CylindricalProjector : ProjectorBase -{ - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - - -/** @brief Warper that maps an image onto the x\*x + z\*z = 1 cylinder. - */ -class CV_EXPORTS CylindricalWarper : public RotationWarperBase -{ -public: - /** @brief Construct an instance of the cylindrical warper class. - - @param scale Projected image scale multiplier - */ - CylindricalWarper(float scale) { projector_.scale = scale; } - - Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) CV_OVERRIDE; - Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, OutputArray dst) CV_OVERRIDE; -protected: - void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) CV_OVERRIDE - { - RotationWarperBase::detectResultRoiByBorder(src_size, dst_tl, dst_br); - } -}; - - -struct CV_EXPORTS FisheyeProjector : ProjectorBase -{ - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - - -class CV_EXPORTS FisheyeWarper : public RotationWarperBase -{ -public: - FisheyeWarper(float scale) { projector_.scale = scale; } -}; - - -struct CV_EXPORTS StereographicProjector : ProjectorBase -{ - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - - -class CV_EXPORTS StereographicWarper : public RotationWarperBase -{ -public: - StereographicWarper(float scale) { projector_.scale = scale; } -}; - - -struct CV_EXPORTS CompressedRectilinearProjector : ProjectorBase -{ - float a, b; - - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - - -class CV_EXPORTS CompressedRectilinearWarper : public RotationWarperBase -{ -public: - CompressedRectilinearWarper(float scale, float A = 1, float B = 1) - { - projector_.a = A; - projector_.b = B; - projector_.scale = scale; - } -}; - - -struct CV_EXPORTS CompressedRectilinearPortraitProjector : ProjectorBase -{ - float a, b; - - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - - -class CV_EXPORTS CompressedRectilinearPortraitWarper : public RotationWarperBase -{ -public: - CompressedRectilinearPortraitWarper(float scale, float A = 1, float B = 1) - { - projector_.a = A; - projector_.b = B; - projector_.scale = scale; - } -}; - - -struct CV_EXPORTS PaniniProjector : ProjectorBase -{ - float a, b; - - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - - -class CV_EXPORTS PaniniWarper : public RotationWarperBase -{ -public: - PaniniWarper(float scale, float A = 1, float B = 1) - { - projector_.a = A; - projector_.b = B; - projector_.scale = scale; - } -}; - - -struct CV_EXPORTS PaniniPortraitProjector : ProjectorBase -{ - float a, b; - - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - - -class CV_EXPORTS PaniniPortraitWarper : public RotationWarperBase -{ -public: - PaniniPortraitWarper(float scale, float A = 1, float B = 1) - { - projector_.a = A; - projector_.b = B; - projector_.scale = scale; - } - -}; - - -struct CV_EXPORTS MercatorProjector : ProjectorBase -{ - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - - -class CV_EXPORTS MercatorWarper : public RotationWarperBase -{ -public: - MercatorWarper(float scale) { projector_.scale = scale; } -}; - - -struct CV_EXPORTS TransverseMercatorProjector : ProjectorBase -{ - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - - -class CV_EXPORTS TransverseMercatorWarper : public RotationWarperBase -{ -public: - TransverseMercatorWarper(float scale) { projector_.scale = scale; } -}; - - -class CV_EXPORTS PlaneWarperGpu : public PlaneWarper -{ -public: - PlaneWarperGpu(float scale = 1.f) : PlaneWarper(scale) {} - -// WARNING: unreachable code using Ninja -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(push) -#pragma warning(disable: 4702) -#endif - Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) CV_OVERRIDE - { - Rect result = buildMaps(src_size, K, R, d_xmap_, d_ymap_); - d_xmap_.download(xmap); - d_ymap_.download(ymap); - return result; - } - - Rect buildMaps(Size src_size, InputArray K, InputArray R, InputArray T, OutputArray xmap, OutputArray ymap) CV_OVERRIDE - { - Rect result = buildMaps(src_size, K, R, T, d_xmap_, d_ymap_); - d_xmap_.download(xmap); - d_ymap_.download(ymap); - return result; - } - - Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, - OutputArray dst) CV_OVERRIDE - { - d_src_.upload(src); - Point result = warp(d_src_, K, R, interp_mode, border_mode, d_dst_); - d_dst_.download(dst); - return result; - } - - Point warp(InputArray src, InputArray K, InputArray R, InputArray T, int interp_mode, int border_mode, - OutputArray dst) CV_OVERRIDE - { - d_src_.upload(src); - Point result = warp(d_src_, K, R, T, interp_mode, border_mode, d_dst_); - d_dst_.download(dst); - return result; - } -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(pop) -#endif - - Rect buildMaps(Size src_size, InputArray K, InputArray R, cuda::GpuMat & xmap, cuda::GpuMat & ymap); - - Rect buildMaps(Size src_size, InputArray K, InputArray R, InputArray T, cuda::GpuMat & xmap, cuda::GpuMat & ymap); - - Point warp(const cuda::GpuMat & src, InputArray K, InputArray R, int interp_mode, int border_mode, - cuda::GpuMat & dst); - - Point warp(const cuda::GpuMat & src, InputArray K, InputArray R, InputArray T, int interp_mode, int border_mode, - cuda::GpuMat & dst); - -private: - cuda::GpuMat d_xmap_, d_ymap_, d_src_, d_dst_; -}; - - -class CV_EXPORTS SphericalWarperGpu : public SphericalWarper -{ -public: - SphericalWarperGpu(float scale) : SphericalWarper(scale) {} - -// WARNING: unreachable code using Ninja -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(push) -#pragma warning(disable: 4702) -#endif - Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) CV_OVERRIDE - { - Rect result = buildMaps(src_size, K, R, d_xmap_, d_ymap_); - d_xmap_.download(xmap); - d_ymap_.download(ymap); - return result; - } - - Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, - OutputArray dst) CV_OVERRIDE - { - d_src_.upload(src); - Point result = warp(d_src_, K, R, interp_mode, border_mode, d_dst_); - d_dst_.download(dst); - return result; - } -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(pop) -#endif - - Rect buildMaps(Size src_size, InputArray K, InputArray R, cuda::GpuMat & xmap, cuda::GpuMat & ymap); - - Point warp(const cuda::GpuMat & src, InputArray K, InputArray R, int interp_mode, int border_mode, - cuda::GpuMat & dst); - -private: - cuda::GpuMat d_xmap_, d_ymap_, d_src_, d_dst_; -}; - - -class CV_EXPORTS CylindricalWarperGpu : public CylindricalWarper -{ -public: - CylindricalWarperGpu(float scale) : CylindricalWarper(scale) {} - -// WARNING: unreachable code using Ninja -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(push) -#pragma warning(disable: 4702) -#endif - Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) CV_OVERRIDE - { - Rect result = buildMaps(src_size, K, R, d_xmap_, d_ymap_); - d_xmap_.download(xmap); - d_ymap_.download(ymap); - return result; - } - - Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, - OutputArray dst) CV_OVERRIDE - { - d_src_.upload(src); - Point result = warp(d_src_, K, R, interp_mode, border_mode, d_dst_); - d_dst_.download(dst); - return result; - } -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(pop) -#endif - - Rect buildMaps(Size src_size, InputArray K, InputArray R, cuda::GpuMat & xmap, cuda::GpuMat & ymap); - - Point warp(const cuda::GpuMat & src, InputArray K, InputArray R, int interp_mode, int border_mode, - cuda::GpuMat & dst); - -private: - cuda::GpuMat d_xmap_, d_ymap_, d_src_, d_dst_; -}; - - -struct CV_EXPORTS SphericalPortraitProjector : ProjectorBase -{ - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - - -// Projects image onto unit sphere with origin at (0, 0, 0). -// Poles are located NOT at (0, -1, 0) and (0, 1, 0) points, BUT at (1, 0, 0) and (-1, 0, 0) points. -class CV_EXPORTS SphericalPortraitWarper : public RotationWarperBase -{ -public: - SphericalPortraitWarper(float scale) { projector_.scale = scale; } - -protected: - void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) CV_OVERRIDE; -}; - -struct CV_EXPORTS CylindricalPortraitProjector : ProjectorBase -{ - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - - -class CV_EXPORTS CylindricalPortraitWarper : public RotationWarperBase -{ -public: - CylindricalPortraitWarper(float scale) { projector_.scale = scale; } - -protected: - void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) CV_OVERRIDE - { - RotationWarperBase::detectResultRoiByBorder(src_size, dst_tl, dst_br); - } -}; - -struct CV_EXPORTS PlanePortraitProjector : ProjectorBase -{ - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - - -class CV_EXPORTS PlanePortraitWarper : public RotationWarperBase -{ -public: - PlanePortraitWarper(float scale) { projector_.scale = scale; } - -protected: - void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) CV_OVERRIDE - { - RotationWarperBase::detectResultRoiByBorder(src_size, dst_tl, dst_br); - } -}; - -//! @} stitching_warp - -} // namespace detail -} // namespace cv - -#include "warpers_inl.hpp" - -#endif // OPENCV_STITCHING_WARPERS_HPP + /*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_STITCHING_WARPERS_HPP +#define OPENCV_STITCHING_WARPERS_HPP + +#include "opencv2/core.hpp" +#include "opencv2/core/cuda.hpp" +#include "opencv2/imgproc.hpp" +#include "opencv2/opencv_modules.hpp" + +namespace cv { +namespace detail { + +//! @addtogroup stitching_warp +//! @{ + +/** @brief Rotation-only model image warper interface. + */ +class CV_EXPORTS RotationWarper +{ +public: + virtual ~RotationWarper() {} + + /** @brief Projects the image point. + + @param pt Source point + @param K Camera intrinsic parameters + @param R Camera rotation matrix + @return Projected point + */ + virtual Point2f warpPoint(const Point2f &pt, InputArray K, InputArray R) = 0; + + /** @brief Projects the image point backward. + + @param pt Projected point + @param K Camera intrinsic parameters + @param R Camera rotation matrix + @return Backward-projected point + */ +#if CV_VERSION_MAJOR == 4 + virtual Point2f warpPointBackward(const Point2f& pt, InputArray K, InputArray R) + { + CV_UNUSED(pt); CV_UNUSED(K); CV_UNUSED(R); + CV_Error(Error::StsNotImplemented, ""); + } +#else + virtual Point2f warpPointBackward(const Point2f& pt, InputArray K, InputArray R) = 0; +#endif + + /** @brief Builds the projection maps according to the given camera data. + + @param src_size Source image size + @param K Camera intrinsic parameters + @param R Camera rotation matrix + @param xmap Projection map for the x axis + @param ymap Projection map for the y axis + @return Projected image minimum bounding box + */ + virtual Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) = 0; + + /** @brief Projects the image. + + @param src Source image + @param K Camera intrinsic parameters + @param R Camera rotation matrix + @param interp_mode Interpolation mode + @param border_mode Border extrapolation mode + @param dst Projected image + @return Project image top-left corner + */ + virtual Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, + CV_OUT OutputArray dst) = 0; + + /** @brief Projects the image backward. + + @param src Projected image + @param K Camera intrinsic parameters + @param R Camera rotation matrix + @param interp_mode Interpolation mode + @param border_mode Border extrapolation mode + @param dst_size Backward-projected image size + @param dst Backward-projected image + */ + virtual void warpBackward(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, + Size dst_size, CV_OUT OutputArray dst) = 0; + + /** + @param src_size Source image bounding box + @param K Camera intrinsic parameters + @param R Camera rotation matrix + @return Projected image minimum bounding box + */ + virtual Rect warpRoi(Size src_size, InputArray K, InputArray R) = 0; + + virtual float getScale() const { return 1.f; } + virtual void setScale(float) {} +}; + +/** @brief Base class for warping logic implementation. + */ +struct CV_EXPORTS_W_SIMPLE ProjectorBase +{ + void setCameraParams(InputArray K = Mat::eye(3, 3, CV_32F), + InputArray R = Mat::eye(3, 3, CV_32F), + InputArray T = Mat::zeros(3, 1, CV_32F)); + + float scale; + float k[9]; + float rinv[9]; + float r_kinv[9]; + float k_rinv[9]; + float t[3]; +}; + +/** @brief Base class for rotation-based warper using a detail::ProjectorBase_ derived class. + */ +template +class CV_EXPORTS_TEMPLATE RotationWarperBase : public RotationWarper +{ +public: + Point2f warpPoint(const Point2f &pt, InputArray K, InputArray R) CV_OVERRIDE; + + Point2f warpPointBackward(const Point2f &pt, InputArray K, InputArray R) CV_OVERRIDE; + + Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) CV_OVERRIDE; + + Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, + OutputArray dst) CV_OVERRIDE; + + void warpBackward(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, + Size dst_size, OutputArray dst) CV_OVERRIDE; + + Rect warpRoi(Size src_size, InputArray K, InputArray R) CV_OVERRIDE; + + float getScale() const CV_OVERRIDE{ return projector_.scale; } + void setScale(float val) CV_OVERRIDE { projector_.scale = val; } + +protected: + + // Detects ROI of the destination image. It's correct for any projection. + virtual void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br); + + // Detects ROI of the destination image by walking over image border. + // Correctness for any projection isn't guaranteed. + void detectResultRoiByBorder(Size src_size, Point &dst_tl, Point &dst_br); + + P projector_; +}; + + +struct CV_EXPORTS PlaneProjector : ProjectorBase +{ + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + +/** @brief Warper that maps an image onto the z = 1 plane. + */ +class CV_EXPORTS PlaneWarper : public RotationWarperBase +{ +public: + /** @brief Construct an instance of the plane warper class. + + @param scale Projected image scale multiplier + */ + PlaneWarper(float scale = 1.f) { projector_.scale = scale; } + + Point2f warpPoint(const Point2f &pt, InputArray K, InputArray R) CV_OVERRIDE; + Point2f warpPoint(const Point2f &pt, InputArray K, InputArray R, InputArray T); + + Point2f warpPointBackward(const Point2f& pt, InputArray K, InputArray R) CV_OVERRIDE; + Point2f warpPointBackward(const Point2f& pt, InputArray K, InputArray R, InputArray T); + + virtual Rect buildMaps(Size src_size, InputArray K, InputArray R, InputArray T, CV_OUT OutputArray xmap, CV_OUT OutputArray ymap); + Rect buildMaps(Size src_size, InputArray K, InputArray R, CV_OUT OutputArray xmap, CV_OUT OutputArray ymap) CV_OVERRIDE; + + Point warp(InputArray src, InputArray K, InputArray R, + int interp_mode, int border_mode, CV_OUT OutputArray dst) CV_OVERRIDE; + virtual Point warp(InputArray src, InputArray K, InputArray R, InputArray T, int interp_mode, int border_mode, + CV_OUT OutputArray dst); + + Rect warpRoi(Size src_size, InputArray K, InputArray R) CV_OVERRIDE; + Rect warpRoi(Size src_size, InputArray K, InputArray R, InputArray T); + +protected: + void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) CV_OVERRIDE; +}; + + +/** @brief Affine warper that uses rotations and translations + + Uses affine transformation in homogeneous coordinates to represent both rotation and + translation in camera rotation matrix. + */ +class CV_EXPORTS AffineWarper : public PlaneWarper +{ +public: + /** @brief Construct an instance of the affine warper class. + + @param scale Projected image scale multiplier + */ + AffineWarper(float scale = 1.f) : PlaneWarper(scale) {} + + /** @brief Projects the image point. + + @param pt Source point + @param K Camera intrinsic parameters + @param H Camera extrinsic parameters + @return Projected point + */ + Point2f warpPoint(const Point2f &pt, InputArray K, InputArray H) CV_OVERRIDE; + + /** @brief Projects the image point backward. + + @param pt Projected point + @param K Camera intrinsic parameters + @param H Camera extrinsic parameters + @return Backward-projected point + */ + Point2f warpPointBackward(const Point2f &pt, InputArray K, InputArray H) CV_OVERRIDE; + + /** @brief Builds the projection maps according to the given camera data. + + @param src_size Source image size + @param K Camera intrinsic parameters + @param H Camera extrinsic parameters + @param xmap Projection map for the x axis + @param ymap Projection map for the y axis + @return Projected image minimum bounding box + */ + Rect buildMaps(Size src_size, InputArray K, InputArray H, OutputArray xmap, OutputArray ymap) CV_OVERRIDE; + + /** @brief Projects the image. + + @param src Source image + @param K Camera intrinsic parameters + @param H Camera extrinsic parameters + @param interp_mode Interpolation mode + @param border_mode Border extrapolation mode + @param dst Projected image + @return Project image top-left corner + */ + Point warp(InputArray src, InputArray K, InputArray H, + int interp_mode, int border_mode, OutputArray dst) CV_OVERRIDE; + + /** + @param src_size Source image bounding box + @param K Camera intrinsic parameters + @param H Camera extrinsic parameters + @return Projected image minimum bounding box + */ + Rect warpRoi(Size src_size, InputArray K, InputArray H) CV_OVERRIDE; + +protected: + /** @brief Extracts rotation and translation matrices from matrix H representing + affine transformation in homogeneous coordinates + */ + void getRTfromHomogeneous(InputArray H, Mat &R, Mat &T); +}; + + +struct CV_EXPORTS_W_SIMPLE SphericalProjector : ProjectorBase +{ + CV_WRAP void mapForward(float x, float y, float &u, float &v); + CV_WRAP void mapBackward(float u, float v, float &x, float &y); +}; + + +/** @brief Warper that maps an image onto the unit sphere located at the origin. + + Projects image onto unit sphere with origin at (0, 0, 0) and radius scale, measured in pixels. + A 360 panorama would therefore have a resulting width of 2 * scale * PI pixels. + Poles are located at (0, -1, 0) and (0, 1, 0) points. +*/ +class CV_EXPORTS SphericalWarper : public RotationWarperBase +{ +public: + /** @brief Construct an instance of the spherical warper class. + + @param scale Radius of the projected sphere, in pixels. An image spanning the + whole sphere will have a width of 2 * scale * PI pixels. + */ + SphericalWarper(float scale) { projector_.scale = scale; } + + Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) CV_OVERRIDE; + Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, OutputArray dst) CV_OVERRIDE; +protected: + void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) CV_OVERRIDE; +}; + + +struct CV_EXPORTS CylindricalProjector : ProjectorBase +{ + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + + +/** @brief Warper that maps an image onto the x\*x + z\*z = 1 cylinder. + */ +class CV_EXPORTS CylindricalWarper : public RotationWarperBase +{ +public: + /** @brief Construct an instance of the cylindrical warper class. + + @param scale Projected image scale multiplier + */ + CylindricalWarper(float scale) { projector_.scale = scale; } + + Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) CV_OVERRIDE; + Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, OutputArray dst) CV_OVERRIDE; +protected: + void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) CV_OVERRIDE + { + RotationWarperBase::detectResultRoiByBorder(src_size, dst_tl, dst_br); + } +}; + + +struct CV_EXPORTS FisheyeProjector : ProjectorBase +{ + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + + +class CV_EXPORTS FisheyeWarper : public RotationWarperBase +{ +public: + FisheyeWarper(float scale) { projector_.scale = scale; } +}; + + +struct CV_EXPORTS StereographicProjector : ProjectorBase +{ + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + + +class CV_EXPORTS StereographicWarper : public RotationWarperBase +{ +public: + StereographicWarper(float scale) { projector_.scale = scale; } +}; + + +struct CV_EXPORTS CompressedRectilinearProjector : ProjectorBase +{ + float a, b; + + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + + +class CV_EXPORTS CompressedRectilinearWarper : public RotationWarperBase +{ +public: + CompressedRectilinearWarper(float scale, float A = 1, float B = 1) + { + projector_.a = A; + projector_.b = B; + projector_.scale = scale; + } +}; + + +struct CV_EXPORTS CompressedRectilinearPortraitProjector : ProjectorBase +{ + float a, b; + + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + + +class CV_EXPORTS CompressedRectilinearPortraitWarper : public RotationWarperBase +{ +public: + CompressedRectilinearPortraitWarper(float scale, float A = 1, float B = 1) + { + projector_.a = A; + projector_.b = B; + projector_.scale = scale; + } +}; + + +struct CV_EXPORTS PaniniProjector : ProjectorBase +{ + float a, b; + + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + + +class CV_EXPORTS PaniniWarper : public RotationWarperBase +{ +public: + PaniniWarper(float scale, float A = 1, float B = 1) + { + projector_.a = A; + projector_.b = B; + projector_.scale = scale; + } +}; + + +struct CV_EXPORTS PaniniPortraitProjector : ProjectorBase +{ + float a, b; + + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + + +class CV_EXPORTS PaniniPortraitWarper : public RotationWarperBase +{ +public: + PaniniPortraitWarper(float scale, float A = 1, float B = 1) + { + projector_.a = A; + projector_.b = B; + projector_.scale = scale; + } + +}; + + +struct CV_EXPORTS MercatorProjector : ProjectorBase +{ + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + + +class CV_EXPORTS MercatorWarper : public RotationWarperBase +{ +public: + MercatorWarper(float scale) { projector_.scale = scale; } +}; + + +struct CV_EXPORTS TransverseMercatorProjector : ProjectorBase +{ + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + + +class CV_EXPORTS TransverseMercatorWarper : public RotationWarperBase +{ +public: + TransverseMercatorWarper(float scale) { projector_.scale = scale; } +}; + + +class CV_EXPORTS PlaneWarperGpu : public PlaneWarper +{ +public: + PlaneWarperGpu(float scale = 1.f) : PlaneWarper(scale) {} + +// WARNING: unreachable code using Ninja +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(push) +#pragma warning(disable: 4702) +#endif + Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) CV_OVERRIDE + { + Rect result = buildMaps(src_size, K, R, d_xmap_, d_ymap_); + d_xmap_.download(xmap); + d_ymap_.download(ymap); + return result; + } + + Rect buildMaps(Size src_size, InputArray K, InputArray R, InputArray T, OutputArray xmap, OutputArray ymap) CV_OVERRIDE + { + Rect result = buildMaps(src_size, K, R, T, d_xmap_, d_ymap_); + d_xmap_.download(xmap); + d_ymap_.download(ymap); + return result; + } + + Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, + OutputArray dst) CV_OVERRIDE + { + d_src_.upload(src); + Point result = warp(d_src_, K, R, interp_mode, border_mode, d_dst_); + d_dst_.download(dst); + return result; + } + + Point warp(InputArray src, InputArray K, InputArray R, InputArray T, int interp_mode, int border_mode, + OutputArray dst) CV_OVERRIDE + { + d_src_.upload(src); + Point result = warp(d_src_, K, R, T, interp_mode, border_mode, d_dst_); + d_dst_.download(dst); + return result; + } +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(pop) +#endif + + Rect buildMaps(Size src_size, InputArray K, InputArray R, cuda::GpuMat & xmap, cuda::GpuMat & ymap); + + Rect buildMaps(Size src_size, InputArray K, InputArray R, InputArray T, cuda::GpuMat & xmap, cuda::GpuMat & ymap); + + Point warp(const cuda::GpuMat & src, InputArray K, InputArray R, int interp_mode, int border_mode, + cuda::GpuMat & dst); + + Point warp(const cuda::GpuMat & src, InputArray K, InputArray R, InputArray T, int interp_mode, int border_mode, + cuda::GpuMat & dst); + +private: + cuda::GpuMat d_xmap_, d_ymap_, d_src_, d_dst_; +}; + + +class CV_EXPORTS SphericalWarperGpu : public SphericalWarper +{ +public: + SphericalWarperGpu(float scale) : SphericalWarper(scale) {} + +// WARNING: unreachable code using Ninja +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(push) +#pragma warning(disable: 4702) +#endif + Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) CV_OVERRIDE + { + Rect result = buildMaps(src_size, K, R, d_xmap_, d_ymap_); + d_xmap_.download(xmap); + d_ymap_.download(ymap); + return result; + } + + Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, + OutputArray dst) CV_OVERRIDE + { + d_src_.upload(src); + Point result = warp(d_src_, K, R, interp_mode, border_mode, d_dst_); + d_dst_.download(dst); + return result; + } +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(pop) +#endif + + Rect buildMaps(Size src_size, InputArray K, InputArray R, cuda::GpuMat & xmap, cuda::GpuMat & ymap); + + Point warp(const cuda::GpuMat & src, InputArray K, InputArray R, int interp_mode, int border_mode, + cuda::GpuMat & dst); + +private: + cuda::GpuMat d_xmap_, d_ymap_, d_src_, d_dst_; +}; + + +class CV_EXPORTS CylindricalWarperGpu : public CylindricalWarper +{ +public: + CylindricalWarperGpu(float scale) : CylindricalWarper(scale) {} + +// WARNING: unreachable code using Ninja +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(push) +#pragma warning(disable: 4702) +#endif + Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) CV_OVERRIDE + { + Rect result = buildMaps(src_size, K, R, d_xmap_, d_ymap_); + d_xmap_.download(xmap); + d_ymap_.download(ymap); + return result; + } + + Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, + OutputArray dst) CV_OVERRIDE + { + d_src_.upload(src); + Point result = warp(d_src_, K, R, interp_mode, border_mode, d_dst_); + d_dst_.download(dst); + return result; + } +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(pop) +#endif + + Rect buildMaps(Size src_size, InputArray K, InputArray R, cuda::GpuMat & xmap, cuda::GpuMat & ymap); + + Point warp(const cuda::GpuMat & src, InputArray K, InputArray R, int interp_mode, int border_mode, + cuda::GpuMat & dst); + +private: + cuda::GpuMat d_xmap_, d_ymap_, d_src_, d_dst_; +}; + + +struct CV_EXPORTS SphericalPortraitProjector : ProjectorBase +{ + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + + +// Projects image onto unit sphere with origin at (0, 0, 0). +// Poles are located NOT at (0, -1, 0) and (0, 1, 0) points, BUT at (1, 0, 0) and (-1, 0, 0) points. +class CV_EXPORTS SphericalPortraitWarper : public RotationWarperBase +{ +public: + SphericalPortraitWarper(float scale) { projector_.scale = scale; } + +protected: + void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) CV_OVERRIDE; +}; + +struct CV_EXPORTS CylindricalPortraitProjector : ProjectorBase +{ + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + + +class CV_EXPORTS CylindricalPortraitWarper : public RotationWarperBase +{ +public: + CylindricalPortraitWarper(float scale) { projector_.scale = scale; } + +protected: + void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) CV_OVERRIDE + { + RotationWarperBase::detectResultRoiByBorder(src_size, dst_tl, dst_br); + } +}; + +struct CV_EXPORTS PlanePortraitProjector : ProjectorBase +{ + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + + +class CV_EXPORTS PlanePortraitWarper : public RotationWarperBase +{ +public: + PlanePortraitWarper(float scale) { projector_.scale = scale; } + +protected: + void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) CV_OVERRIDE + { + RotationWarperBase::detectResultRoiByBorder(src_size, dst_tl, dst_br); + } +}; + +//! @} stitching_warp + +} // namespace detail +} // namespace cv + +#include "warpers_inl.hpp" + +#endif // OPENCV_STITCHING_WARPERS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/warpers_inl.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/warpers_inl.hpp index 72b5c08672..00c122c6d5 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/warpers_inl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/warpers_inl.hpp @@ -1,782 +1,782 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_STITCHING_WARPERS_INL_HPP -#define OPENCV_STITCHING_WARPERS_INL_HPP - -#include "opencv2/core.hpp" -#include "warpers.hpp" // Make your IDE see declarations -#include - -//! @cond IGNORED - -namespace cv { -namespace detail { - -template -Point2f RotationWarperBase

::warpPoint(const Point2f &pt, InputArray K, InputArray R) -{ - projector_.setCameraParams(K, R); - Point2f uv; - projector_.mapForward(pt.x, pt.y, uv.x, uv.y); - return uv; -} - -template -Point2f RotationWarperBase

::warpPointBackward(const Point2f& pt, InputArray K, InputArray R) -{ - projector_.setCameraParams(K, R); - Point2f xy; - projector_.mapBackward(pt.x, pt.y, xy.x, xy.y); - return xy; -} - -template -Rect RotationWarperBase

::buildMaps(Size src_size, InputArray K, InputArray R, OutputArray _xmap, OutputArray _ymap) -{ - projector_.setCameraParams(K, R); - - Point dst_tl, dst_br; - detectResultRoi(src_size, dst_tl, dst_br); - - _xmap.create(dst_br.y - dst_tl.y + 1, dst_br.x - dst_tl.x + 1, CV_32F); - _ymap.create(dst_br.y - dst_tl.y + 1, dst_br.x - dst_tl.x + 1, CV_32F); - - Mat xmap = _xmap.getMat(), ymap = _ymap.getMat(); - - float x, y; - for (int v = dst_tl.y; v <= dst_br.y; ++v) - { - for (int u = dst_tl.x; u <= dst_br.x; ++u) - { - projector_.mapBackward(static_cast(u), static_cast(v), x, y); - xmap.at(v - dst_tl.y, u - dst_tl.x) = x; - ymap.at(v - dst_tl.y, u - dst_tl.x) = y; - } - } - - return Rect(dst_tl, dst_br); -} - - -template -Point RotationWarperBase

::warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, - OutputArray dst) -{ - UMat xmap, ymap; - Rect dst_roi = buildMaps(src.size(), K, R, xmap, ymap); - - dst.create(dst_roi.height + 1, dst_roi.width + 1, src.type()); - remap(src, dst, xmap, ymap, interp_mode, border_mode); - - return dst_roi.tl(); -} - - -template -void RotationWarperBase

::warpBackward(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, - Size dst_size, OutputArray dst) -{ - projector_.setCameraParams(K, R); - - Point src_tl, src_br; - detectResultRoi(dst_size, src_tl, src_br); - - Size size = src.size(); - CV_Assert(src_br.x - src_tl.x + 1 == size.width && src_br.y - src_tl.y + 1 == size.height); - - Mat xmap(dst_size, CV_32F); - Mat ymap(dst_size, CV_32F); - - float u, v; - for (int y = 0; y < dst_size.height; ++y) - { - for (int x = 0; x < dst_size.width; ++x) - { - projector_.mapForward(static_cast(x), static_cast(y), u, v); - xmap.at(y, x) = u - src_tl.x; - ymap.at(y, x) = v - src_tl.y; - } - } - - dst.create(dst_size, src.type()); - remap(src, dst, xmap, ymap, interp_mode, border_mode); -} - - -template -Rect RotationWarperBase

::warpRoi(Size src_size, InputArray K, InputArray R) -{ - projector_.setCameraParams(K, R); - - Point dst_tl, dst_br; - detectResultRoi(src_size, dst_tl, dst_br); - - return Rect(dst_tl, Point(dst_br.x + 1, dst_br.y + 1)); -} - - -template -void RotationWarperBase

::detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) -{ - float tl_uf = (std::numeric_limits::max)(); - float tl_vf = (std::numeric_limits::max)(); - float br_uf = -(std::numeric_limits::max)(); - float br_vf = -(std::numeric_limits::max)(); - - float u, v; - for (int y = 0; y < src_size.height; ++y) - { - for (int x = 0; x < src_size.width; ++x) - { - projector_.mapForward(static_cast(x), static_cast(y), u, v); - tl_uf = (std::min)(tl_uf, u); tl_vf = (std::min)(tl_vf, v); - br_uf = (std::max)(br_uf, u); br_vf = (std::max)(br_vf, v); - } - } - - dst_tl.x = static_cast(tl_uf); - dst_tl.y = static_cast(tl_vf); - dst_br.x = static_cast(br_uf); - dst_br.y = static_cast(br_vf); -} - - -template -void RotationWarperBase

::detectResultRoiByBorder(Size src_size, Point &dst_tl, Point &dst_br) -{ - float tl_uf = (std::numeric_limits::max)(); - float tl_vf = (std::numeric_limits::max)(); - float br_uf = -(std::numeric_limits::max)(); - float br_vf = -(std::numeric_limits::max)(); - - float u, v; - for (float x = 0; x < src_size.width; ++x) - { - projector_.mapForward(static_cast(x), 0, u, v); - tl_uf = (std::min)(tl_uf, u); tl_vf = (std::min)(tl_vf, v); - br_uf = (std::max)(br_uf, u); br_vf = (std::max)(br_vf, v); - - projector_.mapForward(static_cast(x), static_cast(src_size.height - 1), u, v); - tl_uf = (std::min)(tl_uf, u); tl_vf = (std::min)(tl_vf, v); - br_uf = (std::max)(br_uf, u); br_vf = (std::max)(br_vf, v); - } - for (int y = 0; y < src_size.height; ++y) - { - projector_.mapForward(0, static_cast(y), u, v); - tl_uf = (std::min)(tl_uf, u); tl_vf = (std::min)(tl_vf, v); - br_uf = (std::max)(br_uf, u); br_vf = (std::max)(br_vf, v); - - projector_.mapForward(static_cast(src_size.width - 1), static_cast(y), u, v); - tl_uf = (std::min)(tl_uf, u); tl_vf = (std::min)(tl_vf, v); - br_uf = (std::max)(br_uf, u); br_vf = (std::max)(br_vf, v); - } - - dst_tl.x = static_cast(tl_uf); - dst_tl.y = static_cast(tl_vf); - dst_br.x = static_cast(br_uf); - dst_br.y = static_cast(br_vf); -} - - -inline -void PlaneProjector::mapForward(float x, float y, float &u, float &v) -{ - float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - x_ = t[0] + x_ / z_ * (1 - t[2]); - y_ = t[1] + y_ / z_ * (1 - t[2]); - - u = scale * x_; - v = scale * y_; -} - - -inline -void PlaneProjector::mapBackward(float u, float v, float &x, float &y) -{ - u = u / scale - t[0]; - v = v / scale - t[1]; - - float z; - x = k_rinv[0] * u + k_rinv[1] * v + k_rinv[2] * (1 - t[2]); - y = k_rinv[3] * u + k_rinv[4] * v + k_rinv[5] * (1 - t[2]); - z = k_rinv[6] * u + k_rinv[7] * v + k_rinv[8] * (1 - t[2]); - - x /= z; - y /= z; -} - - -inline -void SphericalProjector::mapForward(float x, float y, float &u, float &v) -{ - float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - u = scale * atan2f(x_, z_); - float w = y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_); - v = scale * (static_cast(CV_PI) - acosf(w == w ? w : 0)); -} - - -inline -void SphericalProjector::mapBackward(float u, float v, float &x, float &y) -{ - u /= scale; - v /= scale; - - float sinv = sinf(static_cast(CV_PI) - v); - float x_ = sinv * sinf(u); - float y_ = cosf(static_cast(CV_PI) - v); - float z_ = sinv * cosf(u); - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - - -inline -void CylindricalProjector::mapForward(float x, float y, float &u, float &v) -{ - float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - u = scale * atan2f(x_, z_); - v = scale * y_ / sqrtf(x_ * x_ + z_ * z_); -} - - -inline -void CylindricalProjector::mapBackward(float u, float v, float &x, float &y) -{ - u /= scale; - v /= scale; - - float x_ = sinf(u); - float y_ = v; - float z_ = cosf(u); - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - -inline -void FisheyeProjector::mapForward(float x, float y, float &u, float &v) -{ - float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - float u_ = atan2f(x_, z_); - float v_ = (float)CV_PI - acosf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); - - u = scale * v_ * cosf(u_); - v = scale * v_ * sinf(u_); -} - -inline -void FisheyeProjector::mapBackward(float u, float v, float &x, float &y) -{ - u /= scale; - v /= scale; - - float u_ = atan2f(v, u); - float v_ = sqrtf(u*u + v*v); - - float sinv = sinf((float)CV_PI - v_); - float x_ = sinv * sinf(u_); - float y_ = cosf((float)CV_PI - v_); - float z_ = sinv * cosf(u_); - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - -inline -void StereographicProjector::mapForward(float x, float y, float &u, float &v) -{ - float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - float u_ = atan2f(x_, z_); - float v_ = (float)CV_PI - acosf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); - - float r = sinf(v_) / (1 - cosf(v_)); - - u = scale * r * std::cos(u_); - v = scale * r * std::sin(u_); -} - -inline -void StereographicProjector::mapBackward(float u, float v, float &x, float &y) -{ - u /= scale; - v /= scale; - - float u_ = atan2f(v, u); - float r = sqrtf(u*u + v*v); - float v_ = 2 * atanf(1.f / r); - - float sinv = sinf((float)CV_PI - v_); - float x_ = sinv * sinf(u_); - float y_ = cosf((float)CV_PI - v_); - float z_ = sinv * cosf(u_); - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - -inline -void CompressedRectilinearProjector::mapForward(float x, float y, float &u, float &v) -{ - float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - float u_ = atan2f(x_, z_); - float v_ = asinf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); - - u = scale * a * tanf(u_ / a); - v = scale * b * tanf(v_) / cosf(u_); -} - -inline -void CompressedRectilinearProjector::mapBackward(float u, float v, float &x, float &y) -{ - u /= scale; - v /= scale; - - float aatg = a * atanf(u / a); - float u_ = aatg; - float v_ = atanf(v * cosf(aatg) / b); - - float cosv = cosf(v_); - float x_ = cosv * sinf(u_); - float y_ = sinf(v_); - float z_ = cosv * cosf(u_); - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - -inline -void CompressedRectilinearPortraitProjector::mapForward(float x, float y, float &u, float &v) -{ - float y_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float x_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - float u_ = atan2f(x_, z_); - float v_ = asinf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); - - u = - scale * a * tanf(u_ / a); - v = scale * b * tanf(v_) / cosf(u_); -} - -inline -void CompressedRectilinearPortraitProjector::mapBackward(float u, float v, float &x, float &y) -{ - u /= - scale; - v /= scale; - - float aatg = a * atanf(u / a); - float u_ = aatg; - float v_ = atanf(v * cosf( aatg ) / b); - - float cosv = cosf(v_); - float y_ = cosv * sinf(u_); - float x_ = sinf(v_); - float z_ = cosv * cosf(u_); - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - -inline -void PaniniProjector::mapForward(float x, float y, float &u, float &v) -{ - float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - float u_ = atan2f(x_, z_); - float v_ = asinf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); - - float tg = a * tanf(u_ / a); - u = scale * tg; - - float sinu = sinf(u_); - if ( fabs(sinu) < 1E-7 ) - v = scale * b * tanf(v_); - else - v = scale * b * tg * tanf(v_) / sinu; -} - -inline -void PaniniProjector::mapBackward(float u, float v, float &x, float &y) -{ - u /= scale; - v /= scale; - - float lamda = a * atanf(u / a); - float u_ = lamda; - - float v_; - if ( fabs(lamda) > 1E-7) - v_ = atanf(v * sinf(lamda) / (b * a * tanf(lamda / a))); - else - v_ = atanf(v / b); - - float cosv = cosf(v_); - float x_ = cosv * sinf(u_); - float y_ = sinf(v_); - float z_ = cosv * cosf(u_); - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - -inline -void PaniniPortraitProjector::mapForward(float x, float y, float &u, float &v) -{ - float y_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float x_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - float u_ = atan2f(x_, z_); - float v_ = asinf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); - - float tg = a * tanf(u_ / a); - u = - scale * tg; - - float sinu = sinf( u_ ); - if ( fabs(sinu) < 1E-7 ) - v = scale * b * tanf(v_); - else - v = scale * b * tg * tanf(v_) / sinu; -} - -inline -void PaniniPortraitProjector::mapBackward(float u, float v, float &x, float &y) -{ - u /= - scale; - v /= scale; - - float lamda = a * atanf(u / a); - float u_ = lamda; - - float v_; - if ( fabs(lamda) > 1E-7) - v_ = atanf(v * sinf(lamda) / (b * a * tanf(lamda/a))); - else - v_ = atanf(v / b); - - float cosv = cosf(v_); - float y_ = cosv * sinf(u_); - float x_ = sinf(v_); - float z_ = cosv * cosf(u_); - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - -inline -void MercatorProjector::mapForward(float x, float y, float &u, float &v) -{ - float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - float u_ = atan2f(x_, z_); - float v_ = asinf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); - - u = scale * u_; - v = scale * logf( tanf( (float)(CV_PI/4) + v_/2 ) ); -} - -inline -void MercatorProjector::mapBackward(float u, float v, float &x, float &y) -{ - u /= scale; - v /= scale; - - float v_ = atanf( sinhf(v) ); - float u_ = u; - - float cosv = cosf(v_); - float x_ = cosv * sinf(u_); - float y_ = sinf(v_); - float z_ = cosv * cosf(u_); - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - -inline -void TransverseMercatorProjector::mapForward(float x, float y, float &u, float &v) -{ - float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - float u_ = atan2f(x_, z_); - float v_ = asinf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); - - float B = cosf(v_) * sinf(u_); - - u = scale / 2 * logf( (1+B) / (1-B) ); - v = scale * atan2f(tanf(v_), cosf(u_)); -} - -inline -void TransverseMercatorProjector::mapBackward(float u, float v, float &x, float &y) -{ - u /= scale; - v /= scale; - - float v_ = asinf( sinf(v) / coshf(u) ); - float u_ = atan2f( sinhf(u), std::cos(v) ); - - float cosv = cosf(v_); - float x_ = cosv * sinf(u_); - float y_ = sinf(v_); - float z_ = cosv * cosf(u_); - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - -inline -void SphericalPortraitProjector::mapForward(float x, float y, float &u0, float &v0) -{ - float x0_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y0_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - float x_ = y0_; - float y_ = x0_; - float u, v; - - u = scale * atan2f(x_, z_); - v = scale * (static_cast(CV_PI) - acosf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_))); - - u0 = -u;//v; - v0 = v;//u; -} - - -inline -void SphericalPortraitProjector::mapBackward(float u0, float v0, float &x, float &y) -{ - float u, v; - u = -u0;//v0; - v = v0;//u0; - - u /= scale; - v /= scale; - - float sinv = sinf(static_cast(CV_PI) - v); - float x0_ = sinv * sinf(u); - float y0_ = cosf(static_cast(CV_PI) - v); - float z_ = sinv * cosf(u); - - float x_ = y0_; - float y_ = x0_; - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - -inline -void CylindricalPortraitProjector::mapForward(float x, float y, float &u0, float &v0) -{ - float x0_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y0_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - float x_ = y0_; - float y_ = x0_; - float u, v; - - u = scale * atan2f(x_, z_); - v = scale * y_ / sqrtf(x_ * x_ + z_ * z_); - - u0 = -u;//v; - v0 = v;//u; -} - - -inline -void CylindricalPortraitProjector::mapBackward(float u0, float v0, float &x, float &y) -{ - float u, v; - u = -u0;//v0; - v = v0;//u0; - - u /= scale; - v /= scale; - - float x0_ = sinf(u); - float y0_ = v; - float z_ = cosf(u); - - float x_ = y0_; - float y_ = x0_; - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - -inline -void PlanePortraitProjector::mapForward(float x, float y, float &u0, float &v0) -{ - float x0_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y0_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - float x_ = y0_; - float y_ = x0_; - - x_ = t[0] + x_ / z_ * (1 - t[2]); - y_ = t[1] + y_ / z_ * (1 - t[2]); - - float u,v; - u = scale * x_; - v = scale * y_; - - u0 = -u; - v0 = v; -} - - -inline -void PlanePortraitProjector::mapBackward(float u0, float v0, float &x, float &y) -{ - float u, v; - u = -u0; - v = v0; - - u = u / scale - t[0]; - v = v / scale - t[1]; - - float z; - x = k_rinv[0] * v + k_rinv[1] * u + k_rinv[2] * (1 - t[2]); - y = k_rinv[3] * v + k_rinv[4] * u + k_rinv[5] * (1 - t[2]); - z = k_rinv[6] * v + k_rinv[7] * u + k_rinv[8] * (1 - t[2]); - - x /= z; - y /= z; -} - - -} // namespace detail -} // namespace cv - -//! @endcond - -#endif // OPENCV_STITCHING_WARPERS_INL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_STITCHING_WARPERS_INL_HPP +#define OPENCV_STITCHING_WARPERS_INL_HPP + +#include "opencv2/core.hpp" +#include "warpers.hpp" // Make your IDE see declarations +#include + +//! @cond IGNORED + +namespace cv { +namespace detail { + +template +Point2f RotationWarperBase

::warpPoint(const Point2f &pt, InputArray K, InputArray R) +{ + projector_.setCameraParams(K, R); + Point2f uv; + projector_.mapForward(pt.x, pt.y, uv.x, uv.y); + return uv; +} + +template +Point2f RotationWarperBase

::warpPointBackward(const Point2f& pt, InputArray K, InputArray R) +{ + projector_.setCameraParams(K, R); + Point2f xy; + projector_.mapBackward(pt.x, pt.y, xy.x, xy.y); + return xy; +} + +template +Rect RotationWarperBase

::buildMaps(Size src_size, InputArray K, InputArray R, OutputArray _xmap, OutputArray _ymap) +{ + projector_.setCameraParams(K, R); + + Point dst_tl, dst_br; + detectResultRoi(src_size, dst_tl, dst_br); + + _xmap.create(dst_br.y - dst_tl.y + 1, dst_br.x - dst_tl.x + 1, CV_32F); + _ymap.create(dst_br.y - dst_tl.y + 1, dst_br.x - dst_tl.x + 1, CV_32F); + + Mat xmap = _xmap.getMat(), ymap = _ymap.getMat(); + + float x, y; + for (int v = dst_tl.y; v <= dst_br.y; ++v) + { + for (int u = dst_tl.x; u <= dst_br.x; ++u) + { + projector_.mapBackward(static_cast(u), static_cast(v), x, y); + xmap.at(v - dst_tl.y, u - dst_tl.x) = x; + ymap.at(v - dst_tl.y, u - dst_tl.x) = y; + } + } + + return Rect(dst_tl, dst_br); +} + + +template +Point RotationWarperBase

::warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, + OutputArray dst) +{ + UMat xmap, ymap; + Rect dst_roi = buildMaps(src.size(), K, R, xmap, ymap); + + dst.create(dst_roi.height + 1, dst_roi.width + 1, src.type()); + remap(src, dst, xmap, ymap, interp_mode, border_mode); + + return dst_roi.tl(); +} + + +template +void RotationWarperBase

::warpBackward(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, + Size dst_size, OutputArray dst) +{ + projector_.setCameraParams(K, R); + + Point src_tl, src_br; + detectResultRoi(dst_size, src_tl, src_br); + + Size size = src.size(); + CV_Assert(src_br.x - src_tl.x + 1 == size.width && src_br.y - src_tl.y + 1 == size.height); + + Mat xmap(dst_size, CV_32F); + Mat ymap(dst_size, CV_32F); + + float u, v; + for (int y = 0; y < dst_size.height; ++y) + { + for (int x = 0; x < dst_size.width; ++x) + { + projector_.mapForward(static_cast(x), static_cast(y), u, v); + xmap.at(y, x) = u - src_tl.x; + ymap.at(y, x) = v - src_tl.y; + } + } + + dst.create(dst_size, src.type()); + remap(src, dst, xmap, ymap, interp_mode, border_mode); +} + + +template +Rect RotationWarperBase

::warpRoi(Size src_size, InputArray K, InputArray R) +{ + projector_.setCameraParams(K, R); + + Point dst_tl, dst_br; + detectResultRoi(src_size, dst_tl, dst_br); + + return Rect(dst_tl, Point(dst_br.x + 1, dst_br.y + 1)); +} + + +template +void RotationWarperBase

::detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) +{ + float tl_uf = (std::numeric_limits::max)(); + float tl_vf = (std::numeric_limits::max)(); + float br_uf = -(std::numeric_limits::max)(); + float br_vf = -(std::numeric_limits::max)(); + + float u, v; + for (int y = 0; y < src_size.height; ++y) + { + for (int x = 0; x < src_size.width; ++x) + { + projector_.mapForward(static_cast(x), static_cast(y), u, v); + tl_uf = (std::min)(tl_uf, u); tl_vf = (std::min)(tl_vf, v); + br_uf = (std::max)(br_uf, u); br_vf = (std::max)(br_vf, v); + } + } + + dst_tl.x = static_cast(tl_uf); + dst_tl.y = static_cast(tl_vf); + dst_br.x = static_cast(br_uf); + dst_br.y = static_cast(br_vf); +} + + +template +void RotationWarperBase

::detectResultRoiByBorder(Size src_size, Point &dst_tl, Point &dst_br) +{ + float tl_uf = (std::numeric_limits::max)(); + float tl_vf = (std::numeric_limits::max)(); + float br_uf = -(std::numeric_limits::max)(); + float br_vf = -(std::numeric_limits::max)(); + + float u, v; + for (float x = 0; x < src_size.width; ++x) + { + projector_.mapForward(static_cast(x), 0, u, v); + tl_uf = (std::min)(tl_uf, u); tl_vf = (std::min)(tl_vf, v); + br_uf = (std::max)(br_uf, u); br_vf = (std::max)(br_vf, v); + + projector_.mapForward(static_cast(x), static_cast(src_size.height - 1), u, v); + tl_uf = (std::min)(tl_uf, u); tl_vf = (std::min)(tl_vf, v); + br_uf = (std::max)(br_uf, u); br_vf = (std::max)(br_vf, v); + } + for (int y = 0; y < src_size.height; ++y) + { + projector_.mapForward(0, static_cast(y), u, v); + tl_uf = (std::min)(tl_uf, u); tl_vf = (std::min)(tl_vf, v); + br_uf = (std::max)(br_uf, u); br_vf = (std::max)(br_vf, v); + + projector_.mapForward(static_cast(src_size.width - 1), static_cast(y), u, v); + tl_uf = (std::min)(tl_uf, u); tl_vf = (std::min)(tl_vf, v); + br_uf = (std::max)(br_uf, u); br_vf = (std::max)(br_vf, v); + } + + dst_tl.x = static_cast(tl_uf); + dst_tl.y = static_cast(tl_vf); + dst_br.x = static_cast(br_uf); + dst_br.y = static_cast(br_vf); +} + + +inline +void PlaneProjector::mapForward(float x, float y, float &u, float &v) +{ + float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + x_ = t[0] + x_ / z_ * (1 - t[2]); + y_ = t[1] + y_ / z_ * (1 - t[2]); + + u = scale * x_; + v = scale * y_; +} + + +inline +void PlaneProjector::mapBackward(float u, float v, float &x, float &y) +{ + u = u / scale - t[0]; + v = v / scale - t[1]; + + float z; + x = k_rinv[0] * u + k_rinv[1] * v + k_rinv[2] * (1 - t[2]); + y = k_rinv[3] * u + k_rinv[4] * v + k_rinv[5] * (1 - t[2]); + z = k_rinv[6] * u + k_rinv[7] * v + k_rinv[8] * (1 - t[2]); + + x /= z; + y /= z; +} + + +inline +void SphericalProjector::mapForward(float x, float y, float &u, float &v) +{ + float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + u = scale * atan2f(x_, z_); + float w = y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_); + v = scale * (static_cast(CV_PI) - acosf(w == w ? w : 0)); +} + + +inline +void SphericalProjector::mapBackward(float u, float v, float &x, float &y) +{ + u /= scale; + v /= scale; + + float sinv = sinf(static_cast(CV_PI) - v); + float x_ = sinv * sinf(u); + float y_ = cosf(static_cast(CV_PI) - v); + float z_ = sinv * cosf(u); + + float z; + x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; + y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; + z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; + + if (z > 0) { x /= z; y /= z; } + else x = y = -1; +} + + +inline +void CylindricalProjector::mapForward(float x, float y, float &u, float &v) +{ + float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + u = scale * atan2f(x_, z_); + v = scale * y_ / sqrtf(x_ * x_ + z_ * z_); +} + + +inline +void CylindricalProjector::mapBackward(float u, float v, float &x, float &y) +{ + u /= scale; + v /= scale; + + float x_ = sinf(u); + float y_ = v; + float z_ = cosf(u); + + float z; + x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; + y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; + z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; + + if (z > 0) { x /= z; y /= z; } + else x = y = -1; +} + +inline +void FisheyeProjector::mapForward(float x, float y, float &u, float &v) +{ + float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + float u_ = atan2f(x_, z_); + float v_ = (float)CV_PI - acosf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); + + u = scale * v_ * cosf(u_); + v = scale * v_ * sinf(u_); +} + +inline +void FisheyeProjector::mapBackward(float u, float v, float &x, float &y) +{ + u /= scale; + v /= scale; + + float u_ = atan2f(v, u); + float v_ = sqrtf(u*u + v*v); + + float sinv = sinf((float)CV_PI - v_); + float x_ = sinv * sinf(u_); + float y_ = cosf((float)CV_PI - v_); + float z_ = sinv * cosf(u_); + + float z; + x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; + y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; + z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; + + if (z > 0) { x /= z; y /= z; } + else x = y = -1; +} + +inline +void StereographicProjector::mapForward(float x, float y, float &u, float &v) +{ + float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + float u_ = atan2f(x_, z_); + float v_ = (float)CV_PI - acosf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); + + float r = sinf(v_) / (1 - cosf(v_)); + + u = scale * r * std::cos(u_); + v = scale * r * std::sin(u_); +} + +inline +void StereographicProjector::mapBackward(float u, float v, float &x, float &y) +{ + u /= scale; + v /= scale; + + float u_ = atan2f(v, u); + float r = sqrtf(u*u + v*v); + float v_ = 2 * atanf(1.f / r); + + float sinv = sinf((float)CV_PI - v_); + float x_ = sinv * sinf(u_); + float y_ = cosf((float)CV_PI - v_); + float z_ = sinv * cosf(u_); + + float z; + x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; + y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; + z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; + + if (z > 0) { x /= z; y /= z; } + else x = y = -1; +} + +inline +void CompressedRectilinearProjector::mapForward(float x, float y, float &u, float &v) +{ + float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + float u_ = atan2f(x_, z_); + float v_ = asinf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); + + u = scale * a * tanf(u_ / a); + v = scale * b * tanf(v_) / cosf(u_); +} + +inline +void CompressedRectilinearProjector::mapBackward(float u, float v, float &x, float &y) +{ + u /= scale; + v /= scale; + + float aatg = a * atanf(u / a); + float u_ = aatg; + float v_ = atanf(v * cosf(aatg) / b); + + float cosv = cosf(v_); + float x_ = cosv * sinf(u_); + float y_ = sinf(v_); + float z_ = cosv * cosf(u_); + + float z; + x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; + y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; + z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; + + if (z > 0) { x /= z; y /= z; } + else x = y = -1; +} + +inline +void CompressedRectilinearPortraitProjector::mapForward(float x, float y, float &u, float &v) +{ + float y_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float x_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + float u_ = atan2f(x_, z_); + float v_ = asinf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); + + u = - scale * a * tanf(u_ / a); + v = scale * b * tanf(v_) / cosf(u_); +} + +inline +void CompressedRectilinearPortraitProjector::mapBackward(float u, float v, float &x, float &y) +{ + u /= - scale; + v /= scale; + + float aatg = a * atanf(u / a); + float u_ = aatg; + float v_ = atanf(v * cosf( aatg ) / b); + + float cosv = cosf(v_); + float y_ = cosv * sinf(u_); + float x_ = sinf(v_); + float z_ = cosv * cosf(u_); + + float z; + x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; + y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; + z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; + + if (z > 0) { x /= z; y /= z; } + else x = y = -1; +} + +inline +void PaniniProjector::mapForward(float x, float y, float &u, float &v) +{ + float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + float u_ = atan2f(x_, z_); + float v_ = asinf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); + + float tg = a * tanf(u_ / a); + u = scale * tg; + + float sinu = sinf(u_); + if ( fabs(sinu) < 1E-7 ) + v = scale * b * tanf(v_); + else + v = scale * b * tg * tanf(v_) / sinu; +} + +inline +void PaniniProjector::mapBackward(float u, float v, float &x, float &y) +{ + u /= scale; + v /= scale; + + float lamda = a * atanf(u / a); + float u_ = lamda; + + float v_; + if ( fabs(lamda) > 1E-7) + v_ = atanf(v * sinf(lamda) / (b * a * tanf(lamda / a))); + else + v_ = atanf(v / b); + + float cosv = cosf(v_); + float x_ = cosv * sinf(u_); + float y_ = sinf(v_); + float z_ = cosv * cosf(u_); + + float z; + x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; + y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; + z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; + + if (z > 0) { x /= z; y /= z; } + else x = y = -1; +} + +inline +void PaniniPortraitProjector::mapForward(float x, float y, float &u, float &v) +{ + float y_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float x_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + float u_ = atan2f(x_, z_); + float v_ = asinf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); + + float tg = a * tanf(u_ / a); + u = - scale * tg; + + float sinu = sinf( u_ ); + if ( fabs(sinu) < 1E-7 ) + v = scale * b * tanf(v_); + else + v = scale * b * tg * tanf(v_) / sinu; +} + +inline +void PaniniPortraitProjector::mapBackward(float u, float v, float &x, float &y) +{ + u /= - scale; + v /= scale; + + float lamda = a * atanf(u / a); + float u_ = lamda; + + float v_; + if ( fabs(lamda) > 1E-7) + v_ = atanf(v * sinf(lamda) / (b * a * tanf(lamda/a))); + else + v_ = atanf(v / b); + + float cosv = cosf(v_); + float y_ = cosv * sinf(u_); + float x_ = sinf(v_); + float z_ = cosv * cosf(u_); + + float z; + x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; + y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; + z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; + + if (z > 0) { x /= z; y /= z; } + else x = y = -1; +} + +inline +void MercatorProjector::mapForward(float x, float y, float &u, float &v) +{ + float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + float u_ = atan2f(x_, z_); + float v_ = asinf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); + + u = scale * u_; + v = scale * logf( tanf( (float)(CV_PI/4) + v_/2 ) ); +} + +inline +void MercatorProjector::mapBackward(float u, float v, float &x, float &y) +{ + u /= scale; + v /= scale; + + float v_ = atanf( sinhf(v) ); + float u_ = u; + + float cosv = cosf(v_); + float x_ = cosv * sinf(u_); + float y_ = sinf(v_); + float z_ = cosv * cosf(u_); + + float z; + x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; + y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; + z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; + + if (z > 0) { x /= z; y /= z; } + else x = y = -1; +} + +inline +void TransverseMercatorProjector::mapForward(float x, float y, float &u, float &v) +{ + float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + float u_ = atan2f(x_, z_); + float v_ = asinf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); + + float B = cosf(v_) * sinf(u_); + + u = scale / 2 * logf( (1+B) / (1-B) ); + v = scale * atan2f(tanf(v_), cosf(u_)); +} + +inline +void TransverseMercatorProjector::mapBackward(float u, float v, float &x, float &y) +{ + u /= scale; + v /= scale; + + float v_ = asinf( sinf(v) / coshf(u) ); + float u_ = atan2f( sinhf(u), std::cos(v) ); + + float cosv = cosf(v_); + float x_ = cosv * sinf(u_); + float y_ = sinf(v_); + float z_ = cosv * cosf(u_); + + float z; + x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; + y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; + z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; + + if (z > 0) { x /= z; y /= z; } + else x = y = -1; +} + +inline +void SphericalPortraitProjector::mapForward(float x, float y, float &u0, float &v0) +{ + float x0_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float y0_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + float x_ = y0_; + float y_ = x0_; + float u, v; + + u = scale * atan2f(x_, z_); + v = scale * (static_cast(CV_PI) - acosf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_))); + + u0 = -u;//v; + v0 = v;//u; +} + + +inline +void SphericalPortraitProjector::mapBackward(float u0, float v0, float &x, float &y) +{ + float u, v; + u = -u0;//v0; + v = v0;//u0; + + u /= scale; + v /= scale; + + float sinv = sinf(static_cast(CV_PI) - v); + float x0_ = sinv * sinf(u); + float y0_ = cosf(static_cast(CV_PI) - v); + float z_ = sinv * cosf(u); + + float x_ = y0_; + float y_ = x0_; + + float z; + x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; + y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; + z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; + + if (z > 0) { x /= z; y /= z; } + else x = y = -1; +} + +inline +void CylindricalPortraitProjector::mapForward(float x, float y, float &u0, float &v0) +{ + float x0_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float y0_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + float x_ = y0_; + float y_ = x0_; + float u, v; + + u = scale * atan2f(x_, z_); + v = scale * y_ / sqrtf(x_ * x_ + z_ * z_); + + u0 = -u;//v; + v0 = v;//u; +} + + +inline +void CylindricalPortraitProjector::mapBackward(float u0, float v0, float &x, float &y) +{ + float u, v; + u = -u0;//v0; + v = v0;//u0; + + u /= scale; + v /= scale; + + float x0_ = sinf(u); + float y0_ = v; + float z_ = cosf(u); + + float x_ = y0_; + float y_ = x0_; + + float z; + x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; + y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; + z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; + + if (z > 0) { x /= z; y /= z; } + else x = y = -1; +} + +inline +void PlanePortraitProjector::mapForward(float x, float y, float &u0, float &v0) +{ + float x0_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float y0_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + float x_ = y0_; + float y_ = x0_; + + x_ = t[0] + x_ / z_ * (1 - t[2]); + y_ = t[1] + y_ / z_ * (1 - t[2]); + + float u,v; + u = scale * x_; + v = scale * y_; + + u0 = -u; + v0 = v; +} + + +inline +void PlanePortraitProjector::mapBackward(float u0, float v0, float &x, float &y) +{ + float u, v; + u = -u0; + v = v0; + + u = u / scale - t[0]; + v = v / scale - t[1]; + + float z; + x = k_rinv[0] * v + k_rinv[1] * u + k_rinv[2] * (1 - t[2]); + y = k_rinv[3] * v + k_rinv[4] * u + k_rinv[5] * (1 - t[2]); + z = k_rinv[6] * v + k_rinv[7] * u + k_rinv[8] * (1 - t[2]); + + x /= z; + y /= z; +} + + +} // namespace detail +} // namespace cv + +//! @endcond + +#endif // OPENCV_STITCHING_WARPERS_INL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/warpers.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/warpers.hpp index 0a5bf63de2..34ef44e8f1 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/warpers.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/warpers.hpp @@ -1,277 +1,277 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_STITCHING_WARPER_CREATORS_HPP -#define OPENCV_STITCHING_WARPER_CREATORS_HPP - -#include "opencv2/stitching/detail/warpers.hpp" -#include - -namespace cv { - class CV_EXPORTS_W PyRotationWarper - { - Ptr rw; - - public: - CV_WRAP PyRotationWarper(String type, float scale); - CV_WRAP PyRotationWarper() {} - ~PyRotationWarper() {} - - /** @brief Projects the image point. - - @param pt Source point - @param K Camera intrinsic parameters - @param R Camera rotation matrix - @return Projected point - */ - CV_WRAP Point2f warpPoint(const Point2f &pt, InputArray K, InputArray R); - - /** @brief Projects the image point backward. - - @param pt Projected point - @param K Camera intrinsic parameters - @param R Camera rotation matrix - @return Backward-projected point - */ -#if CV_VERSION_MAJOR == 4 - CV_WRAP Point2f warpPointBackward(const Point2f& pt, InputArray K, InputArray R) - { - CV_UNUSED(pt); CV_UNUSED(K); CV_UNUSED(R); - CV_Error(Error::StsNotImplemented, ""); - } -#else - CV_WRAP Point2f warpPointBackward(const Point2f &pt, InputArray K, InputArray R); -#endif - /** @brief Builds the projection maps according to the given camera data. - - @param src_size Source image size - @param K Camera intrinsic parameters - @param R Camera rotation matrix - @param xmap Projection map for the x axis - @param ymap Projection map for the y axis - @return Projected image minimum bounding box - */ - CV_WRAP Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap); - - /** @brief Projects the image. - - @param src Source image - @param K Camera intrinsic parameters - @param R Camera rotation matrix - @param interp_mode Interpolation mode - @param border_mode Border extrapolation mode - @param dst Projected image - @return Project image top-left corner - */ - CV_WRAP Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, - CV_OUT OutputArray dst); - - /** @brief Projects the image backward. - - @param src Projected image - @param K Camera intrinsic parameters - @param R Camera rotation matrix - @param interp_mode Interpolation mode - @param border_mode Border extrapolation mode - @param dst_size Backward-projected image size - @param dst Backward-projected image - */ - CV_WRAP void warpBackward(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, - Size dst_size, CV_OUT OutputArray dst); - - /** - @param src_size Source image bounding box - @param K Camera intrinsic parameters - @param R Camera rotation matrix - @return Projected image minimum bounding box - */ - CV_WRAP Rect warpRoi(Size src_size, InputArray K, InputArray R); - - CV_WRAP float getScale() const { return 1.f; } - CV_WRAP void setScale(float) {} - }; - -//! @addtogroup stitching_warp -//! @{ - -/** @brief Image warper factories base class. - */ - -class CV_EXPORTS_W WarperCreator -{ -public: - CV_WRAP virtual ~WarperCreator() {} - virtual Ptr create(float scale) const = 0; -}; - - -/** @brief Plane warper factory class. - @sa detail::PlaneWarper - */ -class CV_EXPORTS PlaneWarper : public WarperCreator -{ -public: - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } -}; - -/** @brief Affine warper factory class. - @sa detail::AffineWarper - */ -class CV_EXPORTS AffineWarper : public WarperCreator -{ -public: - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } -}; - -/** @brief Cylindrical warper factory class. -@sa detail::CylindricalWarper -*/ -class CV_EXPORTS CylindricalWarper: public WarperCreator -{ -public: - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } -}; - -/** @brief Spherical warper factory class */ -class CV_EXPORTS SphericalWarper: public WarperCreator -{ -public: - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } -}; - -class CV_EXPORTS FisheyeWarper : public WarperCreator -{ -public: - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } -}; - -class CV_EXPORTS StereographicWarper: public WarperCreator -{ -public: - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } -}; - -class CV_EXPORTS CompressedRectilinearWarper: public WarperCreator -{ - float a, b; -public: - CompressedRectilinearWarper(float A = 1, float B = 1) - { - a = A; b = B; - } - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale, a, b); } -}; - -class CV_EXPORTS CompressedRectilinearPortraitWarper: public WarperCreator -{ - float a, b; -public: - CompressedRectilinearPortraitWarper(float A = 1, float B = 1) - { - a = A; b = B; - } - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale, a, b); } -}; - -class CV_EXPORTS PaniniWarper: public WarperCreator -{ - float a, b; -public: - PaniniWarper(float A = 1, float B = 1) - { - a = A; b = B; - } - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale, a, b); } -}; - -class CV_EXPORTS PaniniPortraitWarper: public WarperCreator -{ - float a, b; -public: - PaniniPortraitWarper(float A = 1, float B = 1) - { - a = A; b = B; - } - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale, a, b); } -}; - -class CV_EXPORTS MercatorWarper: public WarperCreator -{ -public: - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } -}; - -class CV_EXPORTS TransverseMercatorWarper: public WarperCreator -{ -public: - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } -}; - - - -#ifdef HAVE_OPENCV_CUDAWARPING -class PlaneWarperGpu: public WarperCreator -{ -public: - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } -}; - - -class CylindricalWarperGpu: public WarperCreator -{ -public: - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } -}; - - -class SphericalWarperGpu: public WarperCreator -{ -public: - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } -}; -#endif - -//! @} stitching_warp - -} // namespace cv - -#endif // OPENCV_STITCHING_WARPER_CREATORS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_STITCHING_WARPER_CREATORS_HPP +#define OPENCV_STITCHING_WARPER_CREATORS_HPP + +#include "opencv2/stitching/detail/warpers.hpp" +#include + +namespace cv { + class CV_EXPORTS_W PyRotationWarper + { + Ptr rw; + + public: + CV_WRAP PyRotationWarper(String type, float scale); + CV_WRAP PyRotationWarper() {} + ~PyRotationWarper() {} + + /** @brief Projects the image point. + + @param pt Source point + @param K Camera intrinsic parameters + @param R Camera rotation matrix + @return Projected point + */ + CV_WRAP Point2f warpPoint(const Point2f &pt, InputArray K, InputArray R); + + /** @brief Projects the image point backward. + + @param pt Projected point + @param K Camera intrinsic parameters + @param R Camera rotation matrix + @return Backward-projected point + */ +#if CV_VERSION_MAJOR == 4 + CV_WRAP Point2f warpPointBackward(const Point2f& pt, InputArray K, InputArray R) + { + CV_UNUSED(pt); CV_UNUSED(K); CV_UNUSED(R); + CV_Error(Error::StsNotImplemented, ""); + } +#else + CV_WRAP Point2f warpPointBackward(const Point2f &pt, InputArray K, InputArray R); +#endif + /** @brief Builds the projection maps according to the given camera data. + + @param src_size Source image size + @param K Camera intrinsic parameters + @param R Camera rotation matrix + @param xmap Projection map for the x axis + @param ymap Projection map for the y axis + @return Projected image minimum bounding box + */ + CV_WRAP Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap); + + /** @brief Projects the image. + + @param src Source image + @param K Camera intrinsic parameters + @param R Camera rotation matrix + @param interp_mode Interpolation mode + @param border_mode Border extrapolation mode + @param dst Projected image + @return Project image top-left corner + */ + CV_WRAP Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, + CV_OUT OutputArray dst); + + /** @brief Projects the image backward. + + @param src Projected image + @param K Camera intrinsic parameters + @param R Camera rotation matrix + @param interp_mode Interpolation mode + @param border_mode Border extrapolation mode + @param dst_size Backward-projected image size + @param dst Backward-projected image + */ + CV_WRAP void warpBackward(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, + Size dst_size, CV_OUT OutputArray dst); + + /** + @param src_size Source image bounding box + @param K Camera intrinsic parameters + @param R Camera rotation matrix + @return Projected image minimum bounding box + */ + CV_WRAP Rect warpRoi(Size src_size, InputArray K, InputArray R); + + CV_WRAP float getScale() const { return 1.f; } + CV_WRAP void setScale(float) {} + }; + +//! @addtogroup stitching_warp +//! @{ + +/** @brief Image warper factories base class. + */ + +class CV_EXPORTS_W WarperCreator +{ +public: + CV_WRAP virtual ~WarperCreator() {} + virtual Ptr create(float scale) const = 0; +}; + + +/** @brief Plane warper factory class. + @sa detail::PlaneWarper + */ +class CV_EXPORTS PlaneWarper : public WarperCreator +{ +public: + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } +}; + +/** @brief Affine warper factory class. + @sa detail::AffineWarper + */ +class CV_EXPORTS AffineWarper : public WarperCreator +{ +public: + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } +}; + +/** @brief Cylindrical warper factory class. +@sa detail::CylindricalWarper +*/ +class CV_EXPORTS CylindricalWarper: public WarperCreator +{ +public: + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } +}; + +/** @brief Spherical warper factory class */ +class CV_EXPORTS SphericalWarper: public WarperCreator +{ +public: + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } +}; + +class CV_EXPORTS FisheyeWarper : public WarperCreator +{ +public: + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } +}; + +class CV_EXPORTS StereographicWarper: public WarperCreator +{ +public: + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } +}; + +class CV_EXPORTS CompressedRectilinearWarper: public WarperCreator +{ + float a, b; +public: + CompressedRectilinearWarper(float A = 1, float B = 1) + { + a = A; b = B; + } + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale, a, b); } +}; + +class CV_EXPORTS CompressedRectilinearPortraitWarper: public WarperCreator +{ + float a, b; +public: + CompressedRectilinearPortraitWarper(float A = 1, float B = 1) + { + a = A; b = B; + } + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale, a, b); } +}; + +class CV_EXPORTS PaniniWarper: public WarperCreator +{ + float a, b; +public: + PaniniWarper(float A = 1, float B = 1) + { + a = A; b = B; + } + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale, a, b); } +}; + +class CV_EXPORTS PaniniPortraitWarper: public WarperCreator +{ + float a, b; +public: + PaniniPortraitWarper(float A = 1, float B = 1) + { + a = A; b = B; + } + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale, a, b); } +}; + +class CV_EXPORTS MercatorWarper: public WarperCreator +{ +public: + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } +}; + +class CV_EXPORTS TransverseMercatorWarper: public WarperCreator +{ +public: + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } +}; + + + +#ifdef HAVE_OPENCV_CUDAWARPING +class PlaneWarperGpu: public WarperCreator +{ +public: + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } +}; + + +class CylindricalWarperGpu: public WarperCreator +{ +public: + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } +}; + + +class SphericalWarperGpu: public WarperCreator +{ +public: + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } +}; +#endif + +//! @} stitching_warp + +} // namespace cv + +#endif // OPENCV_STITCHING_WARPER_CREATORS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/video.hpp b/3rdParty/opencv-4.11.0/opencv2/video.hpp index b1c19196d4..8ce49bc284 100644 --- a/3rdParty/opencv-4.11.0/opencv2/video.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/video.hpp @@ -1,58 +1,58 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_VIDEO_HPP -#define OPENCV_VIDEO_HPP - -/** - @defgroup video Video Analysis - @{ - @defgroup video_motion Motion Analysis - @defgroup video_track Object Tracking - @} -*/ - -#include "opencv2/video/tracking.hpp" -#include "opencv2/video/background_segm.hpp" - -#endif //OPENCV_VIDEO_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_VIDEO_HPP +#define OPENCV_VIDEO_HPP + +/** + @defgroup video Video Analysis + @{ + @defgroup video_motion Motion Analysis + @defgroup video_track Object Tracking + @} +*/ + +#include "opencv2/video/tracking.hpp" +#include "opencv2/video/background_segm.hpp" + +#endif //OPENCV_VIDEO_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/video/background_segm.hpp b/3rdParty/opencv-4.11.0/opencv2/video/background_segm.hpp index e1dfa15a9a..7433cd8b08 100644 --- a/3rdParty/opencv-4.11.0/opencv2/video/background_segm.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/video/background_segm.hpp @@ -1,317 +1,317 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_BACKGROUND_SEGM_HPP -#define OPENCV_BACKGROUND_SEGM_HPP - -#include "opencv2/core.hpp" - -namespace cv -{ - -//! @addtogroup video_motion -//! @{ - -/** @brief Base class for background/foreground segmentation. : - -The class is only used to define the common interface for the whole family of background/foreground -segmentation algorithms. - */ -class CV_EXPORTS_W BackgroundSubtractor : public Algorithm -{ -public: - /** @brief Computes a foreground mask. - - @param image Next video frame. - @param fgmask The output foreground mask as an 8-bit binary image. - @param learningRate The value between 0 and 1 that indicates how fast the background model is - learnt. Negative parameter value makes the algorithm to use some automatically chosen learning - rate. 0 means that the background model is not updated at all, 1 means that the background model - is completely reinitialized from the last frame. - */ - CV_WRAP virtual void apply(InputArray image, OutputArray fgmask, double learningRate=-1) = 0; - - /** @brief Computes a background image. - - @param backgroundImage The output background image. - - @note Sometimes the background image can be very blurry, as it contain the average background - statistics. - */ - CV_WRAP virtual void getBackgroundImage(OutputArray backgroundImage) const = 0; -}; - - -/** @brief Gaussian Mixture-based Background/Foreground Segmentation Algorithm. - -The class implements the Gaussian mixture model background subtraction described in @cite Zivkovic2004 -and @cite Zivkovic2006 . - */ -class CV_EXPORTS_W BackgroundSubtractorMOG2 : public BackgroundSubtractor -{ -public: - /** @brief Returns the number of last frames that affect the background model - */ - CV_WRAP virtual int getHistory() const = 0; - /** @brief Sets the number of last frames that affect the background model - */ - CV_WRAP virtual void setHistory(int history) = 0; - - /** @brief Returns the number of gaussian components in the background model - */ - CV_WRAP virtual int getNMixtures() const = 0; - /** @brief Sets the number of gaussian components in the background model. - - The model needs to be reinitalized to reserve memory. - */ - CV_WRAP virtual void setNMixtures(int nmixtures) = 0;//needs reinitialization! - - /** @brief Returns the "background ratio" parameter of the algorithm - - If a foreground pixel keeps semi-constant value for about backgroundRatio\*history frames, it's - considered background and added to the model as a center of a new component. It corresponds to TB - parameter in the paper. - */ - CV_WRAP virtual double getBackgroundRatio() const = 0; - /** @brief Sets the "background ratio" parameter of the algorithm - */ - CV_WRAP virtual void setBackgroundRatio(double ratio) = 0; - - /** @brief Returns the variance threshold for the pixel-model match - - The main threshold on the squared Mahalanobis distance to decide if the sample is well described by - the background model or not. Related to Cthr from the paper. - */ - CV_WRAP virtual double getVarThreshold() const = 0; - /** @brief Sets the variance threshold for the pixel-model match - */ - CV_WRAP virtual void setVarThreshold(double varThreshold) = 0; - - /** @brief Returns the variance threshold for the pixel-model match used for new mixture component generation - - Threshold for the squared Mahalanobis distance that helps decide when a sample is close to the - existing components (corresponds to Tg in the paper). If a pixel is not close to any component, it - is considered foreground or added as a new component. 3 sigma =\> Tg=3\*3=9 is default. A smaller Tg - value generates more components. A higher Tg value may result in a small number of components but - they can grow too large. - */ - CV_WRAP virtual double getVarThresholdGen() const = 0; - /** @brief Sets the variance threshold for the pixel-model match used for new mixture component generation - */ - CV_WRAP virtual void setVarThresholdGen(double varThresholdGen) = 0; - - /** @brief Returns the initial variance of each gaussian component - */ - CV_WRAP virtual double getVarInit() const = 0; - /** @brief Sets the initial variance of each gaussian component - */ - CV_WRAP virtual void setVarInit(double varInit) = 0; - - CV_WRAP virtual double getVarMin() const = 0; - CV_WRAP virtual void setVarMin(double varMin) = 0; - - CV_WRAP virtual double getVarMax() const = 0; - CV_WRAP virtual void setVarMax(double varMax) = 0; - - /** @brief Returns the complexity reduction threshold - - This parameter defines the number of samples needed to accept to prove the component exists. CT=0.05 - is a default value for all the samples. By setting CT=0 you get an algorithm very similar to the - standard Stauffer&Grimson algorithm. - */ - CV_WRAP virtual double getComplexityReductionThreshold() const = 0; - /** @brief Sets the complexity reduction threshold - */ - CV_WRAP virtual void setComplexityReductionThreshold(double ct) = 0; - - /** @brief Returns the shadow detection flag - - If true, the algorithm detects shadows and marks them. See createBackgroundSubtractorMOG2 for - details. - */ - CV_WRAP virtual bool getDetectShadows() const = 0; - /** @brief Enables or disables shadow detection - */ - CV_WRAP virtual void setDetectShadows(bool detectShadows) = 0; - - /** @brief Returns the shadow value - - Shadow value is the value used to mark shadows in the foreground mask. Default value is 127. Value 0 - in the mask always means background, 255 means foreground. - */ - CV_WRAP virtual int getShadowValue() const = 0; - /** @brief Sets the shadow value - */ - CV_WRAP virtual void setShadowValue(int value) = 0; - - /** @brief Returns the shadow threshold - - A shadow is detected if pixel is a darker version of the background. The shadow threshold (Tau in - the paper) is a threshold defining how much darker the shadow can be. Tau= 0.5 means that if a pixel - is more than twice darker then it is not shadow. See Prati, Mikic, Trivedi and Cucchiara, - *Detecting Moving Shadows...*, IEEE PAMI,2003. - */ - CV_WRAP virtual double getShadowThreshold() const = 0; - /** @brief Sets the shadow threshold - */ - CV_WRAP virtual void setShadowThreshold(double threshold) = 0; - - /** @brief Computes a foreground mask. - - @param image Next video frame. Floating point frame will be used without scaling and should be in range \f$[0,255]\f$. - @param fgmask The output foreground mask as an 8-bit binary image. - @param learningRate The value between 0 and 1 that indicates how fast the background model is - learnt. Negative parameter value makes the algorithm to use some automatically chosen learning - rate. 0 means that the background model is not updated at all, 1 means that the background model - is completely reinitialized from the last frame. - */ - CV_WRAP virtual void apply(InputArray image, OutputArray fgmask, double learningRate=-1) CV_OVERRIDE = 0; -}; - -/** @brief Creates MOG2 Background Subtractor - -@param history Length of the history. -@param varThreshold Threshold on the squared Mahalanobis distance between the pixel and the model -to decide whether a pixel is well described by the background model. This parameter does not -affect the background update. -@param detectShadows If true, the algorithm will detect shadows and mark them. It decreases the -speed a bit, so if you do not need this feature, set the parameter to false. - */ -CV_EXPORTS_W Ptr - createBackgroundSubtractorMOG2(int history=500, double varThreshold=16, - bool detectShadows=true); - -/** @brief K-nearest neighbours - based Background/Foreground Segmentation Algorithm. - -The class implements the K-nearest neighbours background subtraction described in @cite Zivkovic2006 . -Very efficient if number of foreground pixels is low. - */ -class CV_EXPORTS_W BackgroundSubtractorKNN : public BackgroundSubtractor -{ -public: - /** @brief Returns the number of last frames that affect the background model - */ - CV_WRAP virtual int getHistory() const = 0; - /** @brief Sets the number of last frames that affect the background model - */ - CV_WRAP virtual void setHistory(int history) = 0; - - /** @brief Returns the number of data samples in the background model - */ - CV_WRAP virtual int getNSamples() const = 0; - /** @brief Sets the number of data samples in the background model. - - The model needs to be reinitalized to reserve memory. - */ - CV_WRAP virtual void setNSamples(int _nN) = 0;//needs reinitialization! - - /** @brief Returns the threshold on the squared distance between the pixel and the sample - - The threshold on the squared distance between the pixel and the sample to decide whether a pixel is - close to a data sample. - */ - CV_WRAP virtual double getDist2Threshold() const = 0; - /** @brief Sets the threshold on the squared distance - */ - CV_WRAP virtual void setDist2Threshold(double _dist2Threshold) = 0; - - /** @brief Returns the number of neighbours, the k in the kNN. - - K is the number of samples that need to be within dist2Threshold in order to decide that that - pixel is matching the kNN background model. - */ - CV_WRAP virtual int getkNNSamples() const = 0; - /** @brief Sets the k in the kNN. How many nearest neighbours need to match. - */ - CV_WRAP virtual void setkNNSamples(int _nkNN) = 0; - - /** @brief Returns the shadow detection flag - - If true, the algorithm detects shadows and marks them. See createBackgroundSubtractorKNN for - details. - */ - CV_WRAP virtual bool getDetectShadows() const = 0; - /** @brief Enables or disables shadow detection - */ - CV_WRAP virtual void setDetectShadows(bool detectShadows) = 0; - - /** @brief Returns the shadow value - - Shadow value is the value used to mark shadows in the foreground mask. Default value is 127. Value 0 - in the mask always means background, 255 means foreground. - */ - CV_WRAP virtual int getShadowValue() const = 0; - /** @brief Sets the shadow value - */ - CV_WRAP virtual void setShadowValue(int value) = 0; - - /** @brief Returns the shadow threshold - - A shadow is detected if pixel is a darker version of the background. The shadow threshold (Tau in - the paper) is a threshold defining how much darker the shadow can be. Tau= 0.5 means that if a pixel - is more than twice darker then it is not shadow. See Prati, Mikic, Trivedi and Cucchiara, - *Detecting Moving Shadows...*, IEEE PAMI,2003. - */ - CV_WRAP virtual double getShadowThreshold() const = 0; - /** @brief Sets the shadow threshold - */ - CV_WRAP virtual void setShadowThreshold(double threshold) = 0; -}; - -/** @brief Creates KNN Background Subtractor - -@param history Length of the history. -@param dist2Threshold Threshold on the squared distance between the pixel and the sample to decide -whether a pixel is close to that sample. This parameter does not affect the background update. -@param detectShadows If true, the algorithm will detect shadows and mark them. It decreases the -speed a bit, so if you do not need this feature, set the parameter to false. - */ -CV_EXPORTS_W Ptr - createBackgroundSubtractorKNN(int history=500, double dist2Threshold=400.0, - bool detectShadows=true); - -//! @} video_motion - -} // cv - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_BACKGROUND_SEGM_HPP +#define OPENCV_BACKGROUND_SEGM_HPP + +#include "opencv2/core.hpp" + +namespace cv +{ + +//! @addtogroup video_motion +//! @{ + +/** @brief Base class for background/foreground segmentation. : + +The class is only used to define the common interface for the whole family of background/foreground +segmentation algorithms. + */ +class CV_EXPORTS_W BackgroundSubtractor : public Algorithm +{ +public: + /** @brief Computes a foreground mask. + + @param image Next video frame. + @param fgmask The output foreground mask as an 8-bit binary image. + @param learningRate The value between 0 and 1 that indicates how fast the background model is + learnt. Negative parameter value makes the algorithm to use some automatically chosen learning + rate. 0 means that the background model is not updated at all, 1 means that the background model + is completely reinitialized from the last frame. + */ + CV_WRAP virtual void apply(InputArray image, OutputArray fgmask, double learningRate=-1) = 0; + + /** @brief Computes a background image. + + @param backgroundImage The output background image. + + @note Sometimes the background image can be very blurry, as it contain the average background + statistics. + */ + CV_WRAP virtual void getBackgroundImage(OutputArray backgroundImage) const = 0; +}; + + +/** @brief Gaussian Mixture-based Background/Foreground Segmentation Algorithm. + +The class implements the Gaussian mixture model background subtraction described in @cite Zivkovic2004 +and @cite Zivkovic2006 . + */ +class CV_EXPORTS_W BackgroundSubtractorMOG2 : public BackgroundSubtractor +{ +public: + /** @brief Returns the number of last frames that affect the background model + */ + CV_WRAP virtual int getHistory() const = 0; + /** @brief Sets the number of last frames that affect the background model + */ + CV_WRAP virtual void setHistory(int history) = 0; + + /** @brief Returns the number of gaussian components in the background model + */ + CV_WRAP virtual int getNMixtures() const = 0; + /** @brief Sets the number of gaussian components in the background model. + + The model needs to be reinitalized to reserve memory. + */ + CV_WRAP virtual void setNMixtures(int nmixtures) = 0;//needs reinitialization! + + /** @brief Returns the "background ratio" parameter of the algorithm + + If a foreground pixel keeps semi-constant value for about backgroundRatio\*history frames, it's + considered background and added to the model as a center of a new component. It corresponds to TB + parameter in the paper. + */ + CV_WRAP virtual double getBackgroundRatio() const = 0; + /** @brief Sets the "background ratio" parameter of the algorithm + */ + CV_WRAP virtual void setBackgroundRatio(double ratio) = 0; + + /** @brief Returns the variance threshold for the pixel-model match + + The main threshold on the squared Mahalanobis distance to decide if the sample is well described by + the background model or not. Related to Cthr from the paper. + */ + CV_WRAP virtual double getVarThreshold() const = 0; + /** @brief Sets the variance threshold for the pixel-model match + */ + CV_WRAP virtual void setVarThreshold(double varThreshold) = 0; + + /** @brief Returns the variance threshold for the pixel-model match used for new mixture component generation + + Threshold for the squared Mahalanobis distance that helps decide when a sample is close to the + existing components (corresponds to Tg in the paper). If a pixel is not close to any component, it + is considered foreground or added as a new component. 3 sigma =\> Tg=3\*3=9 is default. A smaller Tg + value generates more components. A higher Tg value may result in a small number of components but + they can grow too large. + */ + CV_WRAP virtual double getVarThresholdGen() const = 0; + /** @brief Sets the variance threshold for the pixel-model match used for new mixture component generation + */ + CV_WRAP virtual void setVarThresholdGen(double varThresholdGen) = 0; + + /** @brief Returns the initial variance of each gaussian component + */ + CV_WRAP virtual double getVarInit() const = 0; + /** @brief Sets the initial variance of each gaussian component + */ + CV_WRAP virtual void setVarInit(double varInit) = 0; + + CV_WRAP virtual double getVarMin() const = 0; + CV_WRAP virtual void setVarMin(double varMin) = 0; + + CV_WRAP virtual double getVarMax() const = 0; + CV_WRAP virtual void setVarMax(double varMax) = 0; + + /** @brief Returns the complexity reduction threshold + + This parameter defines the number of samples needed to accept to prove the component exists. CT=0.05 + is a default value for all the samples. By setting CT=0 you get an algorithm very similar to the + standard Stauffer&Grimson algorithm. + */ + CV_WRAP virtual double getComplexityReductionThreshold() const = 0; + /** @brief Sets the complexity reduction threshold + */ + CV_WRAP virtual void setComplexityReductionThreshold(double ct) = 0; + + /** @brief Returns the shadow detection flag + + If true, the algorithm detects shadows and marks them. See createBackgroundSubtractorMOG2 for + details. + */ + CV_WRAP virtual bool getDetectShadows() const = 0; + /** @brief Enables or disables shadow detection + */ + CV_WRAP virtual void setDetectShadows(bool detectShadows) = 0; + + /** @brief Returns the shadow value + + Shadow value is the value used to mark shadows in the foreground mask. Default value is 127. Value 0 + in the mask always means background, 255 means foreground. + */ + CV_WRAP virtual int getShadowValue() const = 0; + /** @brief Sets the shadow value + */ + CV_WRAP virtual void setShadowValue(int value) = 0; + + /** @brief Returns the shadow threshold + + A shadow is detected if pixel is a darker version of the background. The shadow threshold (Tau in + the paper) is a threshold defining how much darker the shadow can be. Tau= 0.5 means that if a pixel + is more than twice darker then it is not shadow. See Prati, Mikic, Trivedi and Cucchiara, + *Detecting Moving Shadows...*, IEEE PAMI,2003. + */ + CV_WRAP virtual double getShadowThreshold() const = 0; + /** @brief Sets the shadow threshold + */ + CV_WRAP virtual void setShadowThreshold(double threshold) = 0; + + /** @brief Computes a foreground mask. + + @param image Next video frame. Floating point frame will be used without scaling and should be in range \f$[0,255]\f$. + @param fgmask The output foreground mask as an 8-bit binary image. + @param learningRate The value between 0 and 1 that indicates how fast the background model is + learnt. Negative parameter value makes the algorithm to use some automatically chosen learning + rate. 0 means that the background model is not updated at all, 1 means that the background model + is completely reinitialized from the last frame. + */ + CV_WRAP virtual void apply(InputArray image, OutputArray fgmask, double learningRate=-1) CV_OVERRIDE = 0; +}; + +/** @brief Creates MOG2 Background Subtractor + +@param history Length of the history. +@param varThreshold Threshold on the squared Mahalanobis distance between the pixel and the model +to decide whether a pixel is well described by the background model. This parameter does not +affect the background update. +@param detectShadows If true, the algorithm will detect shadows and mark them. It decreases the +speed a bit, so if you do not need this feature, set the parameter to false. + */ +CV_EXPORTS_W Ptr + createBackgroundSubtractorMOG2(int history=500, double varThreshold=16, + bool detectShadows=true); + +/** @brief K-nearest neighbours - based Background/Foreground Segmentation Algorithm. + +The class implements the K-nearest neighbours background subtraction described in @cite Zivkovic2006 . +Very efficient if number of foreground pixels is low. + */ +class CV_EXPORTS_W BackgroundSubtractorKNN : public BackgroundSubtractor +{ +public: + /** @brief Returns the number of last frames that affect the background model + */ + CV_WRAP virtual int getHistory() const = 0; + /** @brief Sets the number of last frames that affect the background model + */ + CV_WRAP virtual void setHistory(int history) = 0; + + /** @brief Returns the number of data samples in the background model + */ + CV_WRAP virtual int getNSamples() const = 0; + /** @brief Sets the number of data samples in the background model. + + The model needs to be reinitalized to reserve memory. + */ + CV_WRAP virtual void setNSamples(int _nN) = 0;//needs reinitialization! + + /** @brief Returns the threshold on the squared distance between the pixel and the sample + + The threshold on the squared distance between the pixel and the sample to decide whether a pixel is + close to a data sample. + */ + CV_WRAP virtual double getDist2Threshold() const = 0; + /** @brief Sets the threshold on the squared distance + */ + CV_WRAP virtual void setDist2Threshold(double _dist2Threshold) = 0; + + /** @brief Returns the number of neighbours, the k in the kNN. + + K is the number of samples that need to be within dist2Threshold in order to decide that that + pixel is matching the kNN background model. + */ + CV_WRAP virtual int getkNNSamples() const = 0; + /** @brief Sets the k in the kNN. How many nearest neighbours need to match. + */ + CV_WRAP virtual void setkNNSamples(int _nkNN) = 0; + + /** @brief Returns the shadow detection flag + + If true, the algorithm detects shadows and marks them. See createBackgroundSubtractorKNN for + details. + */ + CV_WRAP virtual bool getDetectShadows() const = 0; + /** @brief Enables or disables shadow detection + */ + CV_WRAP virtual void setDetectShadows(bool detectShadows) = 0; + + /** @brief Returns the shadow value + + Shadow value is the value used to mark shadows in the foreground mask. Default value is 127. Value 0 + in the mask always means background, 255 means foreground. + */ + CV_WRAP virtual int getShadowValue() const = 0; + /** @brief Sets the shadow value + */ + CV_WRAP virtual void setShadowValue(int value) = 0; + + /** @brief Returns the shadow threshold + + A shadow is detected if pixel is a darker version of the background. The shadow threshold (Tau in + the paper) is a threshold defining how much darker the shadow can be. Tau= 0.5 means that if a pixel + is more than twice darker then it is not shadow. See Prati, Mikic, Trivedi and Cucchiara, + *Detecting Moving Shadows...*, IEEE PAMI,2003. + */ + CV_WRAP virtual double getShadowThreshold() const = 0; + /** @brief Sets the shadow threshold + */ + CV_WRAP virtual void setShadowThreshold(double threshold) = 0; +}; + +/** @brief Creates KNN Background Subtractor + +@param history Length of the history. +@param dist2Threshold Threshold on the squared distance between the pixel and the sample to decide +whether a pixel is close to that sample. This parameter does not affect the background update. +@param detectShadows If true, the algorithm will detect shadows and mark them. It decreases the +speed a bit, so if you do not need this feature, set the parameter to false. + */ +CV_EXPORTS_W Ptr + createBackgroundSubtractorKNN(int history=500, double dist2Threshold=400.0, + bool detectShadows=true); + +//! @} video_motion + +} // cv + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/video/detail/tracking.detail.hpp b/3rdParty/opencv-4.11.0/opencv2/video/detail/tracking.detail.hpp index 3c7823b7dc..eb954d6a16 100644 --- a/3rdParty/opencv-4.11.0/opencv2/video/detail/tracking.detail.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/video/detail/tracking.detail.hpp @@ -1,406 +1,406 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_VIDEO_DETAIL_TRACKING_HPP -#define OPENCV_VIDEO_DETAIL_TRACKING_HPP - -/* - * Partially based on: - * ==================================================================================================================== - * - [AAM] S. Salti, A. Cavallaro, L. Di Stefano, Adaptive Appearance Modeling for Video Tracking: Survey and Evaluation - * - [AMVOT] X. Li, W. Hu, C. Shen, Z. Zhang, A. Dick, A. van den Hengel, A Survey of Appearance Models in Visual Object Tracking - * - * This Tracking API has been designed with PlantUML. If you modify this API please change UML files under modules/tracking/doc/uml - * - */ - -#include "opencv2/core.hpp" - -namespace cv { -namespace detail { -inline namespace tracking { - -/** @addtogroup tracking_detail -@{ -*/ - -/************************************ TrackerFeature Base Classes ************************************/ - -/** @brief Abstract base class for TrackerFeature that represents the feature. -*/ -class CV_EXPORTS TrackerFeature -{ -public: - virtual ~TrackerFeature(); - - /** @brief Compute the features in the images collection - @param images The images - @param response The output response - */ - void compute(const std::vector& images, Mat& response); - -protected: - virtual bool computeImpl(const std::vector& images, Mat& response) = 0; -}; - -/** @brief Class that manages the extraction and selection of features - -@cite AAM Feature Extraction and Feature Set Refinement (Feature Processing and Feature Selection). -See table I and section III C @cite AMVOT Appearance modelling -\> Visual representation (Table II, -section 3.1 - 3.2) - -TrackerFeatureSet is an aggregation of TrackerFeature - -@sa - TrackerFeature - -*/ -class CV_EXPORTS TrackerFeatureSet -{ -public: - TrackerFeatureSet(); - - ~TrackerFeatureSet(); - - /** @brief Extract features from the images collection - @param images The input images - */ - void extraction(const std::vector& images); - - /** @brief Add TrackerFeature in the collection. Return true if TrackerFeature is added, false otherwise - @param feature The TrackerFeature class - */ - bool addTrackerFeature(const Ptr& feature); - - /** @brief Get the TrackerFeature collection (TrackerFeature name, TrackerFeature pointer) - */ - const std::vector>& getTrackerFeatures() const; - - /** @brief Get the responses - @note Be sure to call extraction before getResponses Example TrackerFeatureSet::getResponses - */ - const std::vector& getResponses() const; - -private: - void clearResponses(); - bool blockAddTrackerFeature; - - std::vector> features; // list of features - std::vector responses; // list of response after compute -}; - -/************************************ TrackerSampler Base Classes ************************************/ - -/** @brief Abstract base class for TrackerSamplerAlgorithm that represents the algorithm for the specific -sampler. -*/ -class CV_EXPORTS TrackerSamplerAlgorithm -{ -public: - virtual ~TrackerSamplerAlgorithm(); - - /** @brief Computes the regions starting from a position in an image. - - Return true if samples are computed, false otherwise - - @param image The current frame - @param boundingBox The bounding box from which regions can be calculated - - @param sample The computed samples @cite AAM Fig. 1 variable Sk - */ - virtual bool sampling(const Mat& image, const Rect& boundingBox, std::vector& sample) = 0; -}; - -/** - * \brief Class that manages the sampler in order to select regions for the update the model of the tracker - * [AAM] Sampling e Labeling. See table I and section III B - */ - -/** @brief Class that manages the sampler in order to select regions for the update the model of the tracker - -@cite AAM Sampling e Labeling. See table I and section III B - -TrackerSampler is an aggregation of TrackerSamplerAlgorithm -@sa - TrackerSamplerAlgorithm - */ -class CV_EXPORTS TrackerSampler -{ -public: - TrackerSampler(); - - ~TrackerSampler(); - - /** @brief Computes the regions starting from a position in an image - @param image The current frame - @param boundingBox The bounding box from which regions can be calculated - */ - void sampling(const Mat& image, Rect boundingBox); - - /** @brief Return the collection of the TrackerSamplerAlgorithm - */ - const std::vector>& getSamplers() const; - - /** @brief Return the samples from all TrackerSamplerAlgorithm, @cite AAM Fig. 1 variable Sk - */ - const std::vector& getSamples() const; - - /** @brief Add TrackerSamplerAlgorithm in the collection. Return true if sampler is added, false otherwise - @param sampler The TrackerSamplerAlgorithm - */ - bool addTrackerSamplerAlgorithm(const Ptr& sampler); - -private: - std::vector> samplers; - std::vector samples; - bool blockAddTrackerSampler; - - void clearSamples(); -}; - -/************************************ TrackerModel Base Classes ************************************/ - -/** @brief Abstract base class for TrackerTargetState that represents a possible state of the target. - -See @cite AAM \f$\hat{x}^{i}_{k}\f$ all the states candidates. - -Inherits this class with your Target state, In own implementation you can add scale variation, -width, height, orientation, etc. -*/ -class CV_EXPORTS TrackerTargetState -{ -public: - virtual ~TrackerTargetState() {} - /** @brief Get the position - * @return The position - */ - Point2f getTargetPosition() const; - - /** @brief Set the position - * @param position The position - */ - void setTargetPosition(const Point2f& position); - /** @brief Get the width of the target - * @return The width of the target - */ - int getTargetWidth() const; - - /** @brief Set the width of the target - * @param width The width of the target - */ - void setTargetWidth(int width); - /** @brief Get the height of the target - * @return The height of the target - */ - int getTargetHeight() const; - - /** @brief Set the height of the target - * @param height The height of the target - */ - void setTargetHeight(int height); - -protected: - Point2f targetPosition; - int targetWidth; - int targetHeight; -}; - -/** @brief Represents the model of the target at frame \f$k\f$ (all states and scores) - -See @cite AAM The set of the pair \f$\langle \hat{x}^{i}_{k}, C^{i}_{k} \rangle\f$ -@sa TrackerTargetState -*/ -typedef std::vector, float>> ConfidenceMap; - -/** @brief Represents the estimate states for all frames - -@cite AAM \f$x_{k}\f$ is the trajectory of the target up to time \f$k\f$ - -@sa TrackerTargetState -*/ -typedef std::vector> Trajectory; - -/** @brief Abstract base class for TrackerStateEstimator that estimates the most likely target state. - -See @cite AAM State estimator - -See @cite AMVOT Statistical modeling (Fig. 3), Table III (generative) - IV (discriminative) - V (hybrid) -*/ -class CV_EXPORTS TrackerStateEstimator -{ -public: - virtual ~TrackerStateEstimator(); - - /** @brief Estimate the most likely target state, return the estimated state - @param confidenceMaps The overall appearance model as a list of :cConfidenceMap - */ - Ptr estimate(const std::vector& confidenceMaps); - - /** @brief Update the ConfidenceMap with the scores - @param confidenceMaps The overall appearance model as a list of :cConfidenceMap - */ - void update(std::vector& confidenceMaps); - - /** @brief Create TrackerStateEstimator by tracker state estimator type - @param trackeStateEstimatorType The TrackerStateEstimator name - - The modes available now: - - - "BOOSTING" -- Boosting-based discriminative appearance models. See @cite AMVOT section 4.4 - - The modes available soon: - - - "SVM" -- SVM-based discriminative appearance models. See @cite AMVOT section 4.5 - */ - static Ptr create(const String& trackeStateEstimatorType); - - /** @brief Get the name of the specific TrackerStateEstimator - */ - String getClassName() const; - -protected: - virtual Ptr estimateImpl(const std::vector& confidenceMaps) = 0; - virtual void updateImpl(std::vector& confidenceMaps) = 0; - String className; -}; - -/** @brief Abstract class that represents the model of the target. - -It must be instantiated by specialized tracker - -See @cite AAM Ak - -Inherits this with your TrackerModel -*/ -class CV_EXPORTS TrackerModel -{ -public: - TrackerModel(); - - virtual ~TrackerModel(); - - /** @brief Set TrackerEstimator, return true if the tracker state estimator is added, false otherwise - @param trackerStateEstimator The TrackerStateEstimator - @note You can add only one TrackerStateEstimator - */ - bool setTrackerStateEstimator(Ptr trackerStateEstimator); - - /** @brief Estimate the most likely target location - - @cite AAM ME, Model Estimation table I - @param responses Features extracted from TrackerFeatureSet - */ - void modelEstimation(const std::vector& responses); - - /** @brief Update the model - - @cite AAM MU, Model Update table I - */ - void modelUpdate(); - - /** @brief Run the TrackerStateEstimator, return true if is possible to estimate a new state, false otherwise - */ - bool runStateEstimator(); - - /** @brief Set the current TrackerTargetState in the Trajectory - @param lastTargetState The current TrackerTargetState - */ - void setLastTargetState(const Ptr& lastTargetState); - - /** @brief Get the last TrackerTargetState from Trajectory - */ - Ptr getLastTargetState() const; - - /** @brief Get the list of the ConfidenceMap - */ - const std::vector& getConfidenceMaps() const; - - /** @brief Get the last ConfidenceMap for the current frame - */ - const ConfidenceMap& getLastConfidenceMap() const; - - /** @brief Get the TrackerStateEstimator - */ - Ptr getTrackerStateEstimator() const; - -private: - void clearCurrentConfidenceMap(); - -protected: - std::vector confidenceMaps; - Ptr stateEstimator; - ConfidenceMap currentConfidenceMap; - Trajectory trajectory; - int maxCMLength; - - virtual void modelEstimationImpl(const std::vector& responses) = 0; - virtual void modelUpdateImpl() = 0; -}; - -/************************************ Specific TrackerStateEstimator Classes ************************************/ - -// None - -/************************************ Specific TrackerSamplerAlgorithm Classes ************************************/ - -/** @brief TrackerSampler based on CSC (current state centered), used by MIL algorithm TrackerMIL - */ -class CV_EXPORTS TrackerSamplerCSC : public TrackerSamplerAlgorithm -{ -public: - ~TrackerSamplerCSC(); - - enum MODE - { - MODE_INIT_POS = 1, //!< mode for init positive samples - MODE_INIT_NEG = 2, //!< mode for init negative samples - MODE_TRACK_POS = 3, //!< mode for update positive samples - MODE_TRACK_NEG = 4, //!< mode for update negative samples - MODE_DETECT = 5 //!< mode for detect samples - }; - - struct CV_EXPORTS Params - { - Params(); - float initInRad; //!< radius for gathering positive instances during init - float trackInPosRad; //!< radius for gathering positive instances during tracking - float searchWinSize; //!< size of search window - int initMaxNegNum; //!< # negative samples to use during init - int trackMaxPosNum; //!< # positive samples to use during training - int trackMaxNegNum; //!< # negative samples to use during training - }; - - /** @brief Constructor - @param parameters TrackerSamplerCSC parameters TrackerSamplerCSC::Params - */ - TrackerSamplerCSC(const TrackerSamplerCSC::Params& parameters = TrackerSamplerCSC::Params()); - - /** @brief Set the sampling mode of TrackerSamplerCSC - @param samplingMode The sampling mode - - The modes are: - - - "MODE_INIT_POS = 1" -- for the positive sampling in initialization step - - "MODE_INIT_NEG = 2" -- for the negative sampling in initialization step - - "MODE_TRACK_POS = 3" -- for the positive sampling in update step - - "MODE_TRACK_NEG = 4" -- for the negative sampling in update step - - "MODE_DETECT = 5" -- for the sampling in detection step - */ - void setMode(int samplingMode); - - bool sampling(const Mat& image, const Rect& boundingBox, std::vector& sample) CV_OVERRIDE; - -private: - Params params; - int mode; - RNG rng; - - std::vector sampleImage(const Mat& img, int x, int y, int w, int h, float inrad, float outrad = 0, int maxnum = 1000000); -}; - -//! @} - -}}} // namespace cv::detail::tracking - -#endif // OPENCV_VIDEO_DETAIL_TRACKING_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_VIDEO_DETAIL_TRACKING_HPP +#define OPENCV_VIDEO_DETAIL_TRACKING_HPP + +/* + * Partially based on: + * ==================================================================================================================== + * - [AAM] S. Salti, A. Cavallaro, L. Di Stefano, Adaptive Appearance Modeling for Video Tracking: Survey and Evaluation + * - [AMVOT] X. Li, W. Hu, C. Shen, Z. Zhang, A. Dick, A. van den Hengel, A Survey of Appearance Models in Visual Object Tracking + * + * This Tracking API has been designed with PlantUML. If you modify this API please change UML files under modules/tracking/doc/uml + * + */ + +#include "opencv2/core.hpp" + +namespace cv { +namespace detail { +inline namespace tracking { + +/** @addtogroup tracking_detail +@{ +*/ + +/************************************ TrackerFeature Base Classes ************************************/ + +/** @brief Abstract base class for TrackerFeature that represents the feature. +*/ +class CV_EXPORTS TrackerFeature +{ +public: + virtual ~TrackerFeature(); + + /** @brief Compute the features in the images collection + @param images The images + @param response The output response + */ + void compute(const std::vector& images, Mat& response); + +protected: + virtual bool computeImpl(const std::vector& images, Mat& response) = 0; +}; + +/** @brief Class that manages the extraction and selection of features + +@cite AAM Feature Extraction and Feature Set Refinement (Feature Processing and Feature Selection). +See table I and section III C @cite AMVOT Appearance modelling -\> Visual representation (Table II, +section 3.1 - 3.2) + +TrackerFeatureSet is an aggregation of TrackerFeature + +@sa + TrackerFeature + +*/ +class CV_EXPORTS TrackerFeatureSet +{ +public: + TrackerFeatureSet(); + + ~TrackerFeatureSet(); + + /** @brief Extract features from the images collection + @param images The input images + */ + void extraction(const std::vector& images); + + /** @brief Add TrackerFeature in the collection. Return true if TrackerFeature is added, false otherwise + @param feature The TrackerFeature class + */ + bool addTrackerFeature(const Ptr& feature); + + /** @brief Get the TrackerFeature collection (TrackerFeature name, TrackerFeature pointer) + */ + const std::vector>& getTrackerFeatures() const; + + /** @brief Get the responses + @note Be sure to call extraction before getResponses Example TrackerFeatureSet::getResponses + */ + const std::vector& getResponses() const; + +private: + void clearResponses(); + bool blockAddTrackerFeature; + + std::vector> features; // list of features + std::vector responses; // list of response after compute +}; + +/************************************ TrackerSampler Base Classes ************************************/ + +/** @brief Abstract base class for TrackerSamplerAlgorithm that represents the algorithm for the specific +sampler. +*/ +class CV_EXPORTS TrackerSamplerAlgorithm +{ +public: + virtual ~TrackerSamplerAlgorithm(); + + /** @brief Computes the regions starting from a position in an image. + + Return true if samples are computed, false otherwise + + @param image The current frame + @param boundingBox The bounding box from which regions can be calculated + + @param sample The computed samples @cite AAM Fig. 1 variable Sk + */ + virtual bool sampling(const Mat& image, const Rect& boundingBox, std::vector& sample) = 0; +}; + +/** + * \brief Class that manages the sampler in order to select regions for the update the model of the tracker + * [AAM] Sampling e Labeling. See table I and section III B + */ + +/** @brief Class that manages the sampler in order to select regions for the update the model of the tracker + +@cite AAM Sampling e Labeling. See table I and section III B + +TrackerSampler is an aggregation of TrackerSamplerAlgorithm +@sa + TrackerSamplerAlgorithm + */ +class CV_EXPORTS TrackerSampler +{ +public: + TrackerSampler(); + + ~TrackerSampler(); + + /** @brief Computes the regions starting from a position in an image + @param image The current frame + @param boundingBox The bounding box from which regions can be calculated + */ + void sampling(const Mat& image, Rect boundingBox); + + /** @brief Return the collection of the TrackerSamplerAlgorithm + */ + const std::vector>& getSamplers() const; + + /** @brief Return the samples from all TrackerSamplerAlgorithm, @cite AAM Fig. 1 variable Sk + */ + const std::vector& getSamples() const; + + /** @brief Add TrackerSamplerAlgorithm in the collection. Return true if sampler is added, false otherwise + @param sampler The TrackerSamplerAlgorithm + */ + bool addTrackerSamplerAlgorithm(const Ptr& sampler); + +private: + std::vector> samplers; + std::vector samples; + bool blockAddTrackerSampler; + + void clearSamples(); +}; + +/************************************ TrackerModel Base Classes ************************************/ + +/** @brief Abstract base class for TrackerTargetState that represents a possible state of the target. + +See @cite AAM \f$\hat{x}^{i}_{k}\f$ all the states candidates. + +Inherits this class with your Target state, In own implementation you can add scale variation, +width, height, orientation, etc. +*/ +class CV_EXPORTS TrackerTargetState +{ +public: + virtual ~TrackerTargetState() {} + /** @brief Get the position + * @return The position + */ + Point2f getTargetPosition() const; + + /** @brief Set the position + * @param position The position + */ + void setTargetPosition(const Point2f& position); + /** @brief Get the width of the target + * @return The width of the target + */ + int getTargetWidth() const; + + /** @brief Set the width of the target + * @param width The width of the target + */ + void setTargetWidth(int width); + /** @brief Get the height of the target + * @return The height of the target + */ + int getTargetHeight() const; + + /** @brief Set the height of the target + * @param height The height of the target + */ + void setTargetHeight(int height); + +protected: + Point2f targetPosition; + int targetWidth; + int targetHeight; +}; + +/** @brief Represents the model of the target at frame \f$k\f$ (all states and scores) + +See @cite AAM The set of the pair \f$\langle \hat{x}^{i}_{k}, C^{i}_{k} \rangle\f$ +@sa TrackerTargetState +*/ +typedef std::vector, float>> ConfidenceMap; + +/** @brief Represents the estimate states for all frames + +@cite AAM \f$x_{k}\f$ is the trajectory of the target up to time \f$k\f$ + +@sa TrackerTargetState +*/ +typedef std::vector> Trajectory; + +/** @brief Abstract base class for TrackerStateEstimator that estimates the most likely target state. + +See @cite AAM State estimator + +See @cite AMVOT Statistical modeling (Fig. 3), Table III (generative) - IV (discriminative) - V (hybrid) +*/ +class CV_EXPORTS TrackerStateEstimator +{ +public: + virtual ~TrackerStateEstimator(); + + /** @brief Estimate the most likely target state, return the estimated state + @param confidenceMaps The overall appearance model as a list of :cConfidenceMap + */ + Ptr estimate(const std::vector& confidenceMaps); + + /** @brief Update the ConfidenceMap with the scores + @param confidenceMaps The overall appearance model as a list of :cConfidenceMap + */ + void update(std::vector& confidenceMaps); + + /** @brief Create TrackerStateEstimator by tracker state estimator type + @param trackeStateEstimatorType The TrackerStateEstimator name + + The modes available now: + + - "BOOSTING" -- Boosting-based discriminative appearance models. See @cite AMVOT section 4.4 + + The modes available soon: + + - "SVM" -- SVM-based discriminative appearance models. See @cite AMVOT section 4.5 + */ + static Ptr create(const String& trackeStateEstimatorType); + + /** @brief Get the name of the specific TrackerStateEstimator + */ + String getClassName() const; + +protected: + virtual Ptr estimateImpl(const std::vector& confidenceMaps) = 0; + virtual void updateImpl(std::vector& confidenceMaps) = 0; + String className; +}; + +/** @brief Abstract class that represents the model of the target. + +It must be instantiated by specialized tracker + +See @cite AAM Ak + +Inherits this with your TrackerModel +*/ +class CV_EXPORTS TrackerModel +{ +public: + TrackerModel(); + + virtual ~TrackerModel(); + + /** @brief Set TrackerEstimator, return true if the tracker state estimator is added, false otherwise + @param trackerStateEstimator The TrackerStateEstimator + @note You can add only one TrackerStateEstimator + */ + bool setTrackerStateEstimator(Ptr trackerStateEstimator); + + /** @brief Estimate the most likely target location + + @cite AAM ME, Model Estimation table I + @param responses Features extracted from TrackerFeatureSet + */ + void modelEstimation(const std::vector& responses); + + /** @brief Update the model + + @cite AAM MU, Model Update table I + */ + void modelUpdate(); + + /** @brief Run the TrackerStateEstimator, return true if is possible to estimate a new state, false otherwise + */ + bool runStateEstimator(); + + /** @brief Set the current TrackerTargetState in the Trajectory + @param lastTargetState The current TrackerTargetState + */ + void setLastTargetState(const Ptr& lastTargetState); + + /** @brief Get the last TrackerTargetState from Trajectory + */ + Ptr getLastTargetState() const; + + /** @brief Get the list of the ConfidenceMap + */ + const std::vector& getConfidenceMaps() const; + + /** @brief Get the last ConfidenceMap for the current frame + */ + const ConfidenceMap& getLastConfidenceMap() const; + + /** @brief Get the TrackerStateEstimator + */ + Ptr getTrackerStateEstimator() const; + +private: + void clearCurrentConfidenceMap(); + +protected: + std::vector confidenceMaps; + Ptr stateEstimator; + ConfidenceMap currentConfidenceMap; + Trajectory trajectory; + int maxCMLength; + + virtual void modelEstimationImpl(const std::vector& responses) = 0; + virtual void modelUpdateImpl() = 0; +}; + +/************************************ Specific TrackerStateEstimator Classes ************************************/ + +// None + +/************************************ Specific TrackerSamplerAlgorithm Classes ************************************/ + +/** @brief TrackerSampler based on CSC (current state centered), used by MIL algorithm TrackerMIL + */ +class CV_EXPORTS TrackerSamplerCSC : public TrackerSamplerAlgorithm +{ +public: + ~TrackerSamplerCSC(); + + enum MODE + { + MODE_INIT_POS = 1, //!< mode for init positive samples + MODE_INIT_NEG = 2, //!< mode for init negative samples + MODE_TRACK_POS = 3, //!< mode for update positive samples + MODE_TRACK_NEG = 4, //!< mode for update negative samples + MODE_DETECT = 5 //!< mode for detect samples + }; + + struct CV_EXPORTS Params + { + Params(); + float initInRad; //!< radius for gathering positive instances during init + float trackInPosRad; //!< radius for gathering positive instances during tracking + float searchWinSize; //!< size of search window + int initMaxNegNum; //!< # negative samples to use during init + int trackMaxPosNum; //!< # positive samples to use during training + int trackMaxNegNum; //!< # negative samples to use during training + }; + + /** @brief Constructor + @param parameters TrackerSamplerCSC parameters TrackerSamplerCSC::Params + */ + TrackerSamplerCSC(const TrackerSamplerCSC::Params& parameters = TrackerSamplerCSC::Params()); + + /** @brief Set the sampling mode of TrackerSamplerCSC + @param samplingMode The sampling mode + + The modes are: + + - "MODE_INIT_POS = 1" -- for the positive sampling in initialization step + - "MODE_INIT_NEG = 2" -- for the negative sampling in initialization step + - "MODE_TRACK_POS = 3" -- for the positive sampling in update step + - "MODE_TRACK_NEG = 4" -- for the negative sampling in update step + - "MODE_DETECT = 5" -- for the sampling in detection step + */ + void setMode(int samplingMode); + + bool sampling(const Mat& image, const Rect& boundingBox, std::vector& sample) CV_OVERRIDE; + +private: + Params params; + int mode; + RNG rng; + + std::vector sampleImage(const Mat& img, int x, int y, int w, int h, float inrad, float outrad = 0, int maxnum = 1000000); +}; + +//! @} + +}}} // namespace cv::detail::tracking + +#endif // OPENCV_VIDEO_DETAIL_TRACKING_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/video/legacy/constants_c.h b/3rdParty/opencv-4.11.0/opencv2/video/legacy/constants_c.h index 1a98f52961..5bdd4a1906 100644 --- a/3rdParty/opencv-4.11.0/opencv2/video/legacy/constants_c.h +++ b/3rdParty/opencv-4.11.0/opencv2/video/legacy/constants_c.h @@ -1,16 +1,16 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_VIDEO_LEGACY_CONSTANTS_H -#define OPENCV_VIDEO_LEGACY_CONSTANTS_H - -enum -{ - CV_LKFLOW_PYR_A_READY = 1, - CV_LKFLOW_PYR_B_READY = 2, - CV_LKFLOW_INITIAL_GUESSES = 4, - CV_LKFLOW_GET_MIN_EIGENVALS = 8 -}; - -#endif // OPENCV_VIDEO_LEGACY_CONSTANTS_H +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_VIDEO_LEGACY_CONSTANTS_H +#define OPENCV_VIDEO_LEGACY_CONSTANTS_H + +enum +{ + CV_LKFLOW_PYR_A_READY = 1, + CV_LKFLOW_PYR_B_READY = 2, + CV_LKFLOW_INITIAL_GUESSES = 4, + CV_LKFLOW_GET_MIN_EIGENVALS = 8 +}; + +#endif // OPENCV_VIDEO_LEGACY_CONSTANTS_H diff --git a/3rdParty/opencv-4.11.0/opencv2/video/tracking.hpp b/3rdParty/opencv-4.11.0/opencv2/video/tracking.hpp index ac3788772a..130bf1bcc0 100644 --- a/3rdParty/opencv-4.11.0/opencv2/video/tracking.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/video/tracking.hpp @@ -1,944 +1,944 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_TRACKING_HPP -#define OPENCV_TRACKING_HPP - -#include "opencv2/core.hpp" -#include "opencv2/imgproc.hpp" - -namespace cv -{ - -//! @addtogroup video_track -//! @{ - -enum { OPTFLOW_USE_INITIAL_FLOW = 4, - OPTFLOW_LK_GET_MIN_EIGENVALS = 8, - OPTFLOW_FARNEBACK_GAUSSIAN = 256 - }; - -/** @brief Finds an object center, size, and orientation. - -@param probImage Back projection of the object histogram. See calcBackProject. -@param window Initial search window. -@param criteria Stop criteria for the underlying meanShift. -returns -(in old interfaces) Number of iterations CAMSHIFT took to converge -The function implements the CAMSHIFT object tracking algorithm @cite Bradski98 . First, it finds an -object center using meanShift and then adjusts the window size and finds the optimal rotation. The -function returns the rotated rectangle structure that includes the object position, size, and -orientation. The next position of the search window can be obtained with RotatedRect::boundingRect() - -See the OpenCV sample camshiftdemo.c that tracks colored objects. - -@note -- (Python) A sample explaining the camshift tracking algorithm can be found at - opencv_source_code/samples/python/camshift.py - */ -CV_EXPORTS_W RotatedRect CamShift( InputArray probImage, CV_IN_OUT Rect& window, - TermCriteria criteria ); -/** @example samples/cpp/camshiftdemo.cpp -An example using the mean-shift tracking algorithm -*/ - -/** @brief Finds an object on a back projection image. - -@param probImage Back projection of the object histogram. See calcBackProject for details. -@param window Initial search window. -@param criteria Stop criteria for the iterative search algorithm. -returns -: Number of iterations CAMSHIFT took to converge. -The function implements the iterative object search algorithm. It takes the input back projection of -an object and the initial position. The mass center in window of the back projection image is -computed and the search window center shifts to the mass center. The procedure is repeated until the -specified number of iterations criteria.maxCount is done or until the window center shifts by less -than criteria.epsilon. The algorithm is used inside CamShift and, unlike CamShift , the search -window size or orientation do not change during the search. You can simply pass the output of -calcBackProject to this function. But better results can be obtained if you pre-filter the back -projection and remove the noise. For example, you can do this by retrieving connected components -with findContours , throwing away contours with small area ( contourArea ), and rendering the -remaining contours with drawContours. - - */ -CV_EXPORTS_W int meanShift( InputArray probImage, CV_IN_OUT Rect& window, TermCriteria criteria ); - -/** @brief Constructs the image pyramid which can be passed to calcOpticalFlowPyrLK. - -@param img 8-bit input image. -@param pyramid output pyramid. -@param winSize window size of optical flow algorithm. Must be not less than winSize argument of -calcOpticalFlowPyrLK. It is needed to calculate required padding for pyramid levels. -@param maxLevel 0-based maximal pyramid level number. -@param withDerivatives set to precompute gradients for the every pyramid level. If pyramid is -constructed without the gradients then calcOpticalFlowPyrLK will calculate them internally. -@param pyrBorder the border mode for pyramid layers. -@param derivBorder the border mode for gradients. -@param tryReuseInputImage put ROI of input image into the pyramid if possible. You can pass false -to force data copying. -@return number of levels in constructed pyramid. Can be less than maxLevel. - */ -CV_EXPORTS_W int buildOpticalFlowPyramid( InputArray img, OutputArrayOfArrays pyramid, - Size winSize, int maxLevel, bool withDerivatives = true, - int pyrBorder = BORDER_REFLECT_101, - int derivBorder = BORDER_CONSTANT, - bool tryReuseInputImage = true ); - -/** @example samples/cpp/lkdemo.cpp -An example using the Lucas-Kanade optical flow algorithm -*/ - -/** @brief Calculates an optical flow for a sparse feature set using the iterative Lucas-Kanade method with -pyramids. - -@param prevImg first 8-bit input image or pyramid constructed by buildOpticalFlowPyramid. -@param nextImg second input image or pyramid of the same size and the same type as prevImg. -@param prevPts vector of 2D points for which the flow needs to be found; point coordinates must be -single-precision floating-point numbers. -@param nextPts output vector of 2D points (with single-precision floating-point coordinates) -containing the calculated new positions of input features in the second image; when -OPTFLOW_USE_INITIAL_FLOW flag is passed, the vector must have the same size as in the input. -@param status output status vector (of unsigned chars); each element of the vector is set to 1 if -the flow for the corresponding features has been found, otherwise, it is set to 0. -@param err output vector of errors; each element of the vector is set to an error for the -corresponding feature, type of the error measure can be set in flags parameter; if the flow wasn't -found then the error is not defined (use the status parameter to find such cases). -@param winSize size of the search window at each pyramid level. -@param maxLevel 0-based maximal pyramid level number; if set to 0, pyramids are not used (single -level), if set to 1, two levels are used, and so on; if pyramids are passed to input then -algorithm will use as many levels as pyramids have but no more than maxLevel. -@param criteria parameter, specifying the termination criteria of the iterative search algorithm -(after the specified maximum number of iterations criteria.maxCount or when the search window -moves by less than criteria.epsilon. -@param flags operation flags: - - **OPTFLOW_USE_INITIAL_FLOW** uses initial estimations, stored in nextPts; if the flag is - not set, then prevPts is copied to nextPts and is considered the initial estimate. - - **OPTFLOW_LK_GET_MIN_EIGENVALS** use minimum eigen values as an error measure (see - minEigThreshold description); if the flag is not set, then L1 distance between patches - around the original and a moved point, divided by number of pixels in a window, is used as a - error measure. -@param minEigThreshold the algorithm calculates the minimum eigen value of a 2x2 normal matrix of -optical flow equations (this matrix is called a spatial gradient matrix in @cite Bouguet00), divided -by number of pixels in a window; if this value is less than minEigThreshold, then a corresponding -feature is filtered out and its flow is not processed, so it allows to remove bad points and get a -performance boost. - -The function implements a sparse iterative version of the Lucas-Kanade optical flow in pyramids. See -@cite Bouguet00 . The function is parallelized with the TBB library. - -@note Some examples: - -- An example using the Lucas-Kanade optical flow algorithm can be found at - opencv_source_code/samples/cpp/lkdemo.cpp -- (Python) An example using the Lucas-Kanade optical flow algorithm can be found at - opencv_source_code/samples/python/lk_track.py -- (Python) An example using the Lucas-Kanade tracker for homography matching can be found at - opencv_source_code/samples/python/lk_homography.py - */ -CV_EXPORTS_W void calcOpticalFlowPyrLK( InputArray prevImg, InputArray nextImg, - InputArray prevPts, InputOutputArray nextPts, - OutputArray status, OutputArray err, - Size winSize = Size(21,21), int maxLevel = 3, - TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01), - int flags = 0, double minEigThreshold = 1e-4 ); - -/** @brief Computes a dense optical flow using the Gunnar Farneback's algorithm. - -@param prev first 8-bit single-channel input image. -@param next second input image of the same size and the same type as prev. -@param flow computed flow image that has the same size as prev and type CV_32FC2. -@param pyr_scale parameter, specifying the image scale (\<1) to build pyramids for each image; -pyr_scale=0.5 means a classical pyramid, where each next layer is twice smaller than the previous -one. -@param levels number of pyramid layers including the initial image; levels=1 means that no extra -layers are created and only the original images are used. -@param winsize averaging window size; larger values increase the algorithm robustness to image -noise and give more chances for fast motion detection, but yield more blurred motion field. -@param iterations number of iterations the algorithm does at each pyramid level. -@param poly_n size of the pixel neighborhood used to find polynomial expansion in each pixel; -larger values mean that the image will be approximated with smoother surfaces, yielding more -robust algorithm and more blurred motion field, typically poly_n =5 or 7. -@param poly_sigma standard deviation of the Gaussian that is used to smooth derivatives used as a -basis for the polynomial expansion; for poly_n=5, you can set poly_sigma=1.1, for poly_n=7, a -good value would be poly_sigma=1.5. -@param flags operation flags that can be a combination of the following: - - **OPTFLOW_USE_INITIAL_FLOW** uses the input flow as an initial flow approximation. - - **OPTFLOW_FARNEBACK_GAUSSIAN** uses the Gaussian \f$\texttt{winsize}\times\texttt{winsize}\f$ - filter instead of a box filter of the same size for optical flow estimation; usually, this - option gives z more accurate flow than with a box filter, at the cost of lower speed; - normally, winsize for a Gaussian window should be set to a larger value to achieve the same - level of robustness. - -The function finds an optical flow for each prev pixel using the @cite Farneback2003 algorithm so that - -\f[\texttt{prev} (y,x) \sim \texttt{next} ( y + \texttt{flow} (y,x)[1], x + \texttt{flow} (y,x)[0])\f] - -@note Some examples: - -- An example using the optical flow algorithm described by Gunnar Farneback can be found at - opencv_source_code/samples/cpp/fback.cpp -- (Python) An example using the optical flow algorithm described by Gunnar Farneback can be - found at opencv_source_code/samples/python/opt_flow.py - */ -CV_EXPORTS_W void calcOpticalFlowFarneback( InputArray prev, InputArray next, InputOutputArray flow, - double pyr_scale, int levels, int winsize, - int iterations, int poly_n, double poly_sigma, - int flags ); - -/** @brief Computes an optimal affine transformation between two 2D point sets. - -@param src First input 2D point set stored in std::vector or Mat, or an image stored in Mat. -@param dst Second input 2D point set of the same size and the same type as A, or another image. -@param fullAffine If true, the function finds an optimal affine transformation with no additional -restrictions (6 degrees of freedom). Otherwise, the class of transformations to choose from is -limited to combinations of translation, rotation, and uniform scaling (4 degrees of freedom). - -The function finds an optimal affine transform *[A|b]* (a 2 x 3 floating-point matrix) that -approximates best the affine transformation between: - -* Two point sets -* Two raster images. In this case, the function first finds some features in the src image and - finds the corresponding features in dst image. After that, the problem is reduced to the first - case. -In case of point sets, the problem is formulated as follows: you need to find a 2x2 matrix *A* and -2x1 vector *b* so that: - -\f[[A^*|b^*] = arg \min _{[A|b]} \sum _i \| \texttt{dst}[i] - A { \texttt{src}[i]}^T - b \| ^2\f] -where src[i] and dst[i] are the i-th points in src and dst, respectively -\f$[A|b]\f$ can be either arbitrary (when fullAffine=true ) or have a form of -\f[\begin{bmatrix} a_{11} & a_{12} & b_1 \\ -a_{12} & a_{11} & b_2 \end{bmatrix}\f] -when fullAffine=false. - -@deprecated Use cv::estimateAffine2D, cv::estimateAffinePartial2D instead. If you are using this function -with images, extract points using cv::calcOpticalFlowPyrLK and then use the estimation functions. - -@sa -estimateAffine2D, estimateAffinePartial2D, getAffineTransform, getPerspectiveTransform, findHomography - */ -CV_DEPRECATED CV_EXPORTS Mat estimateRigidTransform( InputArray src, InputArray dst, bool fullAffine ); - -enum -{ - MOTION_TRANSLATION = 0, - MOTION_EUCLIDEAN = 1, - MOTION_AFFINE = 2, - MOTION_HOMOGRAPHY = 3 -}; - -/** @brief Computes the Enhanced Correlation Coefficient value between two images @cite EP08 . - -@param templateImage single-channel template image; CV_8U or CV_32F array. -@param inputImage single-channel input image to be warped to provide an image similar to - templateImage, same type as templateImage. -@param inputMask An optional mask to indicate valid values of inputImage. - -@sa -findTransformECC - */ - -CV_EXPORTS_W double computeECC(InputArray templateImage, InputArray inputImage, InputArray inputMask = noArray()); - -/** @example samples/cpp/image_alignment.cpp -An example using the image alignment ECC algorithm -*/ - -/** @brief Finds the geometric transform (warp) between two images in terms of the ECC criterion @cite EP08 . - -@param templateImage single-channel template image; CV_8U or CV_32F array. -@param inputImage single-channel input image which should be warped with the final warpMatrix in -order to provide an image similar to templateImage, same type as templateImage. -@param warpMatrix floating-point \f$2\times 3\f$ or \f$3\times 3\f$ mapping matrix (warp). -@param motionType parameter, specifying the type of motion: - - **MOTION_TRANSLATION** sets a translational motion model; warpMatrix is \f$2\times 3\f$ with - the first \f$2\times 2\f$ part being the unity matrix and the rest two parameters being - estimated. - - **MOTION_EUCLIDEAN** sets a Euclidean (rigid) transformation as motion model; three - parameters are estimated; warpMatrix is \f$2\times 3\f$. - - **MOTION_AFFINE** sets an affine motion model (DEFAULT); six parameters are estimated; - warpMatrix is \f$2\times 3\f$. - - **MOTION_HOMOGRAPHY** sets a homography as a motion model; eight parameters are - estimated;\`warpMatrix\` is \f$3\times 3\f$. -@param criteria parameter, specifying the termination criteria of the ECC algorithm; -criteria.epsilon defines the threshold of the increment in the correlation coefficient between two -iterations (a negative criteria.epsilon makes criteria.maxcount the only termination criterion). -Default values are shown in the declaration above. -@param inputMask An optional mask to indicate valid values of inputImage. -@param gaussFiltSize An optional value indicating size of gaussian blur filter; (DEFAULT: 5) - -The function estimates the optimum transformation (warpMatrix) with respect to ECC criterion -(@cite EP08), that is - -\f[\texttt{warpMatrix} = \arg\max_{W} \texttt{ECC}(\texttt{templateImage}(x,y),\texttt{inputImage}(x',y'))\f] - -where - -\f[\begin{bmatrix} x' \\ y' \end{bmatrix} = W \cdot \begin{bmatrix} x \\ y \\ 1 \end{bmatrix}\f] - -(the equation holds with homogeneous coordinates for homography). It returns the final enhanced -correlation coefficient, that is the correlation coefficient between the template image and the -final warped input image. When a \f$3\times 3\f$ matrix is given with motionType =0, 1 or 2, the third -row is ignored. - -Unlike findHomography and estimateRigidTransform, the function findTransformECC implements an -area-based alignment that builds on intensity similarities. In essence, the function updates the -initial transformation that roughly aligns the images. If this information is missing, the identity -warp (unity matrix) is used as an initialization. Note that if images undergo strong -displacements/rotations, an initial transformation that roughly aligns the images is necessary -(e.g., a simple euclidean/similarity transform that allows for the images showing the same image -content approximately). Use inverse warping in the second image to take an image close to the first -one, i.e. use the flag WARP_INVERSE_MAP with warpAffine or warpPerspective. See also the OpenCV -sample image_alignment.cpp that demonstrates the use of the function. Note that the function throws -an exception if algorithm does not converges. - -@sa -computeECC, estimateAffine2D, estimateAffinePartial2D, findHomography - */ -CV_EXPORTS_W double findTransformECC( InputArray templateImage, InputArray inputImage, - InputOutputArray warpMatrix, int motionType, - TermCriteria criteria, - InputArray inputMask, int gaussFiltSize); - -/** @overload */ -CV_EXPORTS_W -double findTransformECC(InputArray templateImage, InputArray inputImage, - InputOutputArray warpMatrix, int motionType = MOTION_AFFINE, - TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 50, 0.001), - InputArray inputMask = noArray()); - -/** @example samples/cpp/kalman.cpp -An example using the standard Kalman filter -*/ - -/** @brief Kalman filter class. - -The class implements a standard Kalman filter , -@cite Welch95 . However, you can modify transitionMatrix, controlMatrix, and measurementMatrix to get -an extended Kalman filter functionality. -@note In C API when CvKalman\* kalmanFilter structure is not needed anymore, it should be released -with cvReleaseKalman(&kalmanFilter) - */ -class CV_EXPORTS_W KalmanFilter -{ -public: - CV_WRAP KalmanFilter(); - /** @overload - @param dynamParams Dimensionality of the state. - @param measureParams Dimensionality of the measurement. - @param controlParams Dimensionality of the control vector. - @param type Type of the created matrices that should be CV_32F or CV_64F. - */ - CV_WRAP KalmanFilter( int dynamParams, int measureParams, int controlParams = 0, int type = CV_32F ); - - /** @brief Re-initializes Kalman filter. The previous content is destroyed. - - @param dynamParams Dimensionality of the state. - @param measureParams Dimensionality of the measurement. - @param controlParams Dimensionality of the control vector. - @param type Type of the created matrices that should be CV_32F or CV_64F. - */ - void init( int dynamParams, int measureParams, int controlParams = 0, int type = CV_32F ); - - /** @brief Computes a predicted state. - - @param control The optional input control - */ - CV_WRAP const Mat& predict( const Mat& control = Mat() ); - - /** @brief Updates the predicted state from the measurement. - - @param measurement The measured system parameters - */ - CV_WRAP const Mat& correct( const Mat& measurement ); - - CV_PROP_RW Mat statePre; //!< predicted state (x'(k)): x(k)=A*x(k-1)+B*u(k) - CV_PROP_RW Mat statePost; //!< corrected state (x(k)): x(k)=x'(k)+K(k)*(z(k)-H*x'(k)) - CV_PROP_RW Mat transitionMatrix; //!< state transition matrix (A) - CV_PROP_RW Mat controlMatrix; //!< control matrix (B) (not used if there is no control) - CV_PROP_RW Mat measurementMatrix; //!< measurement matrix (H) - CV_PROP_RW Mat processNoiseCov; //!< process noise covariance matrix (Q) - CV_PROP_RW Mat measurementNoiseCov;//!< measurement noise covariance matrix (R) - CV_PROP_RW Mat errorCovPre; //!< priori error estimate covariance matrix (P'(k)): P'(k)=A*P(k-1)*At + Q)*/ - CV_PROP_RW Mat gain; //!< Kalman gain matrix (K(k)): K(k)=P'(k)*Ht*inv(H*P'(k)*Ht+R) - CV_PROP_RW Mat errorCovPost; //!< posteriori error estimate covariance matrix (P(k)): P(k)=(I-K(k)*H)*P'(k) - - // temporary matrices - Mat temp1; - Mat temp2; - Mat temp3; - Mat temp4; - Mat temp5; -}; - - -/** @brief Read a .flo file - - @param path Path to the file to be loaded - - The function readOpticalFlow loads a flow field from a file and returns it as a single matrix. - Resulting Mat has a type CV_32FC2 - floating-point, 2-channel. First channel corresponds to the - flow in the horizontal direction (u), second - vertical (v). - */ -CV_EXPORTS_W Mat readOpticalFlow( const String& path ); -/** @brief Write a .flo to disk - - @param path Path to the file to be written - @param flow Flow field to be stored - - The function stores a flow field in a file, returns true on success, false otherwise. - The flow field must be a 2-channel, floating-point matrix (CV_32FC2). First channel corresponds - to the flow in the horizontal direction (u), second - vertical (v). - */ -CV_EXPORTS_W bool writeOpticalFlow( const String& path, InputArray flow ); - -/** - Base class for dense optical flow algorithms -*/ -class CV_EXPORTS_W DenseOpticalFlow : public Algorithm -{ -public: - /** @brief Calculates an optical flow. - - @param I0 first 8-bit single-channel input image. - @param I1 second input image of the same size and the same type as prev. - @param flow computed flow image that has the same size as prev and type CV_32FC2. - */ - CV_WRAP virtual void calc( InputArray I0, InputArray I1, InputOutputArray flow ) = 0; - /** @brief Releases all inner buffers. - */ - CV_WRAP virtual void collectGarbage() = 0; -}; - -/** @brief Base interface for sparse optical flow algorithms. - */ -class CV_EXPORTS_W SparseOpticalFlow : public Algorithm -{ -public: - /** @brief Calculates a sparse optical flow. - - @param prevImg First input image. - @param nextImg Second input image of the same size and the same type as prevImg. - @param prevPts Vector of 2D points for which the flow needs to be found. - @param nextPts Output vector of 2D points containing the calculated new positions of input features in the second image. - @param status Output status vector. Each element of the vector is set to 1 if the - flow for the corresponding features has been found. Otherwise, it is set to 0. - @param err Optional output vector that contains error response for each point (inverse confidence). - */ - CV_WRAP virtual void calc(InputArray prevImg, InputArray nextImg, - InputArray prevPts, InputOutputArray nextPts, - OutputArray status, - OutputArray err = cv::noArray()) = 0; -}; - - -/** @brief Class computing a dense optical flow using the Gunnar Farneback's algorithm. - */ -class CV_EXPORTS_W FarnebackOpticalFlow : public DenseOpticalFlow -{ -public: - CV_WRAP virtual int getNumLevels() const = 0; - CV_WRAP virtual void setNumLevels(int numLevels) = 0; - - CV_WRAP virtual double getPyrScale() const = 0; - CV_WRAP virtual void setPyrScale(double pyrScale) = 0; - - CV_WRAP virtual bool getFastPyramids() const = 0; - CV_WRAP virtual void setFastPyramids(bool fastPyramids) = 0; - - CV_WRAP virtual int getWinSize() const = 0; - CV_WRAP virtual void setWinSize(int winSize) = 0; - - CV_WRAP virtual int getNumIters() const = 0; - CV_WRAP virtual void setNumIters(int numIters) = 0; - - CV_WRAP virtual int getPolyN() const = 0; - CV_WRAP virtual void setPolyN(int polyN) = 0; - - CV_WRAP virtual double getPolySigma() const = 0; - CV_WRAP virtual void setPolySigma(double polySigma) = 0; - - CV_WRAP virtual int getFlags() const = 0; - CV_WRAP virtual void setFlags(int flags) = 0; - - CV_WRAP static Ptr create( - int numLevels = 5, - double pyrScale = 0.5, - bool fastPyramids = false, - int winSize = 13, - int numIters = 10, - int polyN = 5, - double polySigma = 1.1, - int flags = 0); -}; - -/** @brief Variational optical flow refinement - -This class implements variational refinement of the input flow field, i.e. -it uses input flow to initialize the minimization of the following functional: -\f$E(U) = \int_{\Omega} \delta \Psi(E_I) + \gamma \Psi(E_G) + \alpha \Psi(E_S) \f$, -where \f$E_I,E_G,E_S\f$ are color constancy, gradient constancy and smoothness terms -respectively. \f$\Psi(s^2)=\sqrt{s^2+\epsilon^2}\f$ is a robust penalizer to limit the -influence of outliers. A complete formulation and a description of the minimization -procedure can be found in @cite Brox2004 -*/ -class CV_EXPORTS_W VariationalRefinement : public DenseOpticalFlow -{ -public: - /** @brief @ref calc function overload to handle separate horizontal (u) and vertical (v) flow components - (to avoid extra splits/merges) */ - CV_WRAP virtual void calcUV(InputArray I0, InputArray I1, InputOutputArray flow_u, InputOutputArray flow_v) = 0; - - /** @brief Number of outer (fixed-point) iterations in the minimization procedure. - @see setFixedPointIterations */ - CV_WRAP virtual int getFixedPointIterations() const = 0; - /** @copybrief getFixedPointIterations @see getFixedPointIterations */ - CV_WRAP virtual void setFixedPointIterations(int val) = 0; - - /** @brief Number of inner successive over-relaxation (SOR) iterations - in the minimization procedure to solve the respective linear system. - @see setSorIterations */ - CV_WRAP virtual int getSorIterations() const = 0; - /** @copybrief getSorIterations @see getSorIterations */ - CV_WRAP virtual void setSorIterations(int val) = 0; - - /** @brief Relaxation factor in SOR - @see setOmega */ - CV_WRAP virtual float getOmega() const = 0; - /** @copybrief getOmega @see getOmega */ - CV_WRAP virtual void setOmega(float val) = 0; - - /** @brief Weight of the smoothness term - @see setAlpha */ - CV_WRAP virtual float getAlpha() const = 0; - /** @copybrief getAlpha @see getAlpha */ - CV_WRAP virtual void setAlpha(float val) = 0; - - /** @brief Weight of the color constancy term - @see setDelta */ - CV_WRAP virtual float getDelta() const = 0; - /** @copybrief getDelta @see getDelta */ - CV_WRAP virtual void setDelta(float val) = 0; - - /** @brief Weight of the gradient constancy term - @see setGamma */ - CV_WRAP virtual float getGamma() const = 0; - /** @copybrief getGamma @see getGamma */ - CV_WRAP virtual void setGamma(float val) = 0; - - /** @brief Norm value shift for robust penalizer - @see setEpsilon */ - CV_WRAP virtual float getEpsilon() const = 0; - /** @copybrief getEpsilon @see getEpsilon */ - CV_WRAP virtual void setEpsilon(float val) = 0; - - /** @brief Creates an instance of VariationalRefinement - */ - CV_WRAP static Ptr create(); -}; - -/** @brief DIS optical flow algorithm. - -This class implements the Dense Inverse Search (DIS) optical flow algorithm. More -details about the algorithm can be found at @cite Kroeger2016 . Includes three presets with preselected -parameters to provide reasonable trade-off between speed and quality. However, even the slowest preset is -still relatively fast, use DeepFlow if you need better quality and don't care about speed. - -This implementation includes several additional features compared to the algorithm described in the paper, -including spatial propagation of flow vectors (@ref getUseSpatialPropagation), as well as an option to -utilize an initial flow approximation passed to @ref calc (which is, essentially, temporal propagation, -if the previous frame's flow field is passed). -*/ -class CV_EXPORTS_W DISOpticalFlow : public DenseOpticalFlow -{ -public: - enum - { - PRESET_ULTRAFAST = 0, - PRESET_FAST = 1, - PRESET_MEDIUM = 2 - }; - - /** @brief Finest level of the Gaussian pyramid on which the flow is computed (zero level - corresponds to the original image resolution). The final flow is obtained by bilinear upscaling. - @see setFinestScale */ - CV_WRAP virtual int getFinestScale() const = 0; - /** @copybrief getFinestScale @see getFinestScale */ - CV_WRAP virtual void setFinestScale(int val) = 0; - - /** @brief Size of an image patch for matching (in pixels). Normally, default 8x8 patches work well - enough in most cases. - @see setPatchSize */ - CV_WRAP virtual int getPatchSize() const = 0; - /** @copybrief getPatchSize @see getPatchSize */ - CV_WRAP virtual void setPatchSize(int val) = 0; - - /** @brief Stride between neighbor patches. Must be less than patch size. Lower values correspond - to higher flow quality. - @see setPatchStride */ - CV_WRAP virtual int getPatchStride() const = 0; - /** @copybrief getPatchStride @see getPatchStride */ - CV_WRAP virtual void setPatchStride(int val) = 0; - - /** @brief Maximum number of gradient descent iterations in the patch inverse search stage. Higher values - may improve quality in some cases. - @see setGradientDescentIterations */ - CV_WRAP virtual int getGradientDescentIterations() const = 0; - /** @copybrief getGradientDescentIterations @see getGradientDescentIterations */ - CV_WRAP virtual void setGradientDescentIterations(int val) = 0; - - /** @brief Number of fixed point iterations of variational refinement per scale. Set to zero to - disable variational refinement completely. Higher values will typically result in more smooth and - high-quality flow. - @see setGradientDescentIterations */ - CV_WRAP virtual int getVariationalRefinementIterations() const = 0; - /** @copybrief getGradientDescentIterations @see getGradientDescentIterations */ - CV_WRAP virtual void setVariationalRefinementIterations(int val) = 0; - - /** @brief Weight of the smoothness term - @see setVariationalRefinementAlpha */ - CV_WRAP virtual float getVariationalRefinementAlpha() const = 0; - /** @copybrief getVariationalRefinementAlpha @see getVariationalRefinementAlpha */ - CV_WRAP virtual void setVariationalRefinementAlpha(float val) = 0; - - /** @brief Weight of the color constancy term - @see setVariationalRefinementDelta */ - CV_WRAP virtual float getVariationalRefinementDelta() const = 0; - /** @copybrief getVariationalRefinementDelta @see getVariationalRefinementDelta */ - CV_WRAP virtual void setVariationalRefinementDelta(float val) = 0; - - /** @brief Weight of the gradient constancy term - @see setVariationalRefinementGamma */ - CV_WRAP virtual float getVariationalRefinementGamma() const = 0; - /** @copybrief getVariationalRefinementGamma @see getVariationalRefinementGamma */ - CV_WRAP virtual void setVariationalRefinementGamma(float val) = 0; - - /** @brief Norm value shift for robust penalizer - @see setVariationalRefinementEpsilon */ - CV_WRAP virtual float getVariationalRefinementEpsilon() const = 0; - /** @copybrief getVariationalRefinementEpsilon @see getVariationalRefinementEpsilon */ - CV_WRAP virtual void setVariationalRefinementEpsilon(float val) = 0; - - - /** @brief Whether to use mean-normalization of patches when computing patch distance. It is turned on - by default as it typically provides a noticeable quality boost because of increased robustness to - illumination variations. Turn it off if you are certain that your sequence doesn't contain any changes - in illumination. - @see setUseMeanNormalization */ - CV_WRAP virtual bool getUseMeanNormalization() const = 0; - /** @copybrief getUseMeanNormalization @see getUseMeanNormalization */ - CV_WRAP virtual void setUseMeanNormalization(bool val) = 0; - - /** @brief Whether to use spatial propagation of good optical flow vectors. This option is turned on by - default, as it tends to work better on average and can sometimes help recover from major errors - introduced by the coarse-to-fine scheme employed by the DIS optical flow algorithm. Turning this - option off can make the output flow field a bit smoother, however. - @see setUseSpatialPropagation */ - CV_WRAP virtual bool getUseSpatialPropagation() const = 0; - /** @copybrief getUseSpatialPropagation @see getUseSpatialPropagation */ - CV_WRAP virtual void setUseSpatialPropagation(bool val) = 0; - - /** @brief Creates an instance of DISOpticalFlow - - @param preset one of PRESET_ULTRAFAST, PRESET_FAST and PRESET_MEDIUM - */ - CV_WRAP static Ptr create(int preset = DISOpticalFlow::PRESET_FAST); -}; - -/** @brief Class used for calculating a sparse optical flow. - -The class can calculate an optical flow for a sparse feature set using the -iterative Lucas-Kanade method with pyramids. - -@sa calcOpticalFlowPyrLK - -*/ -class CV_EXPORTS_W SparsePyrLKOpticalFlow : public SparseOpticalFlow -{ -public: - CV_WRAP virtual Size getWinSize() const = 0; - CV_WRAP virtual void setWinSize(Size winSize) = 0; - - CV_WRAP virtual int getMaxLevel() const = 0; - CV_WRAP virtual void setMaxLevel(int maxLevel) = 0; - - CV_WRAP virtual TermCriteria getTermCriteria() const = 0; - CV_WRAP virtual void setTermCriteria(TermCriteria& crit) = 0; - - CV_WRAP virtual int getFlags() const = 0; - CV_WRAP virtual void setFlags(int flags) = 0; - - CV_WRAP virtual double getMinEigThreshold() const = 0; - CV_WRAP virtual void setMinEigThreshold(double minEigThreshold) = 0; - - CV_WRAP static Ptr create( - Size winSize = Size(21, 21), - int maxLevel = 3, TermCriteria crit = - TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01), - int flags = 0, - double minEigThreshold = 1e-4); -}; - - - - -/** @brief Base abstract class for the long-term tracker - */ -class CV_EXPORTS_W Tracker -{ -protected: - Tracker(); -public: - virtual ~Tracker(); - - /** @brief Initialize the tracker with a known bounding box that surrounded the target - @param image The initial frame - @param boundingBox The initial bounding box - */ - CV_WRAP virtual - void init(InputArray image, const Rect& boundingBox) = 0; - - /** @brief Update the tracker, find the new most likely bounding box for the target - @param image The current frame - @param boundingBox The bounding box that represent the new target location, if true was returned, not - modified otherwise - - @return True means that target was located and false means that tracker cannot locate target in - current frame. Note, that latter *does not* imply that tracker has failed, maybe target is indeed - missing from the frame (say, out of sight) - */ - CV_WRAP virtual - bool update(InputArray image, CV_OUT Rect& boundingBox) = 0; -}; - - - -/** @brief The MIL algorithm trains a classifier in an online manner to separate the object from the -background. - -Multiple Instance Learning avoids the drift problem for a robust tracking. The implementation is -based on @cite MIL . - -Original code can be found here - */ -class CV_EXPORTS_W TrackerMIL : public Tracker -{ -protected: - TrackerMIL(); // use ::create() -public: - virtual ~TrackerMIL() CV_OVERRIDE; - - struct CV_EXPORTS_W_SIMPLE Params - { - CV_WRAP Params(); - //parameters for sampler - CV_PROP_RW float samplerInitInRadius; //!< radius for gathering positive instances during init - CV_PROP_RW int samplerInitMaxNegNum; //!< # negative samples to use during init - CV_PROP_RW float samplerSearchWinSize; //!< size of search window - CV_PROP_RW float samplerTrackInRadius; //!< radius for gathering positive instances during tracking - CV_PROP_RW int samplerTrackMaxPosNum; //!< # positive samples to use during tracking - CV_PROP_RW int samplerTrackMaxNegNum; //!< # negative samples to use during tracking - CV_PROP_RW int featureSetNumFeatures; //!< # features - }; - - /** @brief Create MIL tracker instance - * @param parameters MIL parameters TrackerMIL::Params - */ - static CV_WRAP - Ptr create(const TrackerMIL::Params ¶meters = TrackerMIL::Params()); - - //void init(InputArray image, const Rect& boundingBox) CV_OVERRIDE; - //bool update(InputArray image, CV_OUT Rect& boundingBox) CV_OVERRIDE; -}; - - - -/** @brief the GOTURN (Generic Object Tracking Using Regression Networks) tracker - * - * GOTURN (@cite GOTURN) is kind of trackers based on Convolutional Neural Networks (CNN). While taking all advantages of CNN trackers, - * GOTURN is much faster due to offline training without online fine-tuning nature. - * GOTURN tracker addresses the problem of single target tracking: given a bounding box label of an object in the first frame of the video, - * we track that object through the rest of the video. NOTE: Current method of GOTURN does not handle occlusions; however, it is fairly - * robust to viewpoint changes, lighting changes, and deformations. - * Inputs of GOTURN are two RGB patches representing Target and Search patches resized to 227x227. - * Outputs of GOTURN are predicted bounding box coordinates, relative to Search patch coordinate system, in format X1,Y1,X2,Y2. - * Original paper is here: - * As long as original authors implementation: - * Implementation of training algorithm is placed in separately here due to 3d-party dependencies: - * - * GOTURN architecture goturn.prototxt and trained model goturn.caffemodel are accessible on opencv_extra GitHub repository. - */ -class CV_EXPORTS_W TrackerGOTURN : public Tracker -{ -protected: - TrackerGOTURN(); // use ::create() -public: - virtual ~TrackerGOTURN() CV_OVERRIDE; - - struct CV_EXPORTS_W_SIMPLE Params - { - CV_WRAP Params(); - CV_PROP_RW std::string modelTxt; - CV_PROP_RW std::string modelBin; - }; - - /** @brief Constructor - @param parameters GOTURN parameters TrackerGOTURN::Params - */ - static CV_WRAP - Ptr create(const TrackerGOTURN::Params& parameters = TrackerGOTURN::Params()); - - //void init(InputArray image, const Rect& boundingBox) CV_OVERRIDE; - //bool update(InputArray image, CV_OUT Rect& boundingBox) CV_OVERRIDE; -}; - -class CV_EXPORTS_W TrackerDaSiamRPN : public Tracker -{ -protected: - TrackerDaSiamRPN(); // use ::create() -public: - virtual ~TrackerDaSiamRPN() CV_OVERRIDE; - - struct CV_EXPORTS_W_SIMPLE Params - { - CV_WRAP Params(); - CV_PROP_RW std::string model; - CV_PROP_RW std::string kernel_cls1; - CV_PROP_RW std::string kernel_r1; - CV_PROP_RW int backend; - CV_PROP_RW int target; - }; - - /** @brief Constructor - @param parameters DaSiamRPN parameters TrackerDaSiamRPN::Params - */ - static CV_WRAP - Ptr create(const TrackerDaSiamRPN::Params& parameters = TrackerDaSiamRPN::Params()); - - /** @brief Return tracking score - */ - CV_WRAP virtual float getTrackingScore() = 0; - - //void init(InputArray image, const Rect& boundingBox) CV_OVERRIDE; - //bool update(InputArray image, CV_OUT Rect& boundingBox) CV_OVERRIDE; -}; - -/** @brief the Nano tracker is a super lightweight dnn-based general object tracking. - * - * Nano tracker is much faster and extremely lightweight due to special model structure, the whole model size is about 1.9 MB. - * Nano tracker needs two models: one for feature extraction (backbone) and the another for localization (neckhead). - * Model download link: https://github.com/HonglinChu/SiamTrackers/tree/master/NanoTrack/models/nanotrackv2 - * Original repo is here: https://github.com/HonglinChu/NanoTrack - * Author: HongLinChu, 1628464345@qq.com - */ -class CV_EXPORTS_W TrackerNano : public Tracker -{ -protected: - TrackerNano(); // use ::create() -public: - virtual ~TrackerNano() CV_OVERRIDE; - - struct CV_EXPORTS_W_SIMPLE Params - { - CV_WRAP Params(); - CV_PROP_RW std::string backbone; - CV_PROP_RW std::string neckhead; - CV_PROP_RW int backend; - CV_PROP_RW int target; - }; - - /** @brief Constructor - @param parameters NanoTrack parameters TrackerNano::Params - */ - static CV_WRAP - Ptr create(const TrackerNano::Params& parameters = TrackerNano::Params()); - - /** @brief Return tracking score - */ - CV_WRAP virtual float getTrackingScore() = 0; - - //void init(InputArray image, const Rect& boundingBox) CV_OVERRIDE; - //bool update(InputArray image, CV_OUT Rect& boundingBox) CV_OVERRIDE; -}; - -/** @brief the VIT tracker is a super lightweight dnn-based general object tracking. - * - * VIT tracker is much faster and extremely lightweight due to special model structure, the model file is about 767KB. - * Model download link: https://github.com/opencv/opencv_zoo/tree/main/models/object_tracking_vittrack - * Author: PengyuLiu, 1872918507@qq.com - */ -class CV_EXPORTS_W TrackerVit : public Tracker -{ -protected: - TrackerVit(); // use ::create() -public: - virtual ~TrackerVit() CV_OVERRIDE; - - struct CV_EXPORTS_W_SIMPLE Params - { - CV_WRAP Params(); - CV_PROP_RW std::string net; - CV_PROP_RW int backend; - CV_PROP_RW int target; - CV_PROP_RW Scalar meanvalue; - CV_PROP_RW Scalar stdvalue; - CV_PROP_RW float tracking_score_threshold; - }; - - /** @brief Constructor - @param parameters vit tracker parameters TrackerVit::Params - */ - static CV_WRAP - Ptr create(const TrackerVit::Params& parameters = TrackerVit::Params()); - - /** @brief Return tracking score - */ - CV_WRAP virtual float getTrackingScore() = 0; - - // void init(InputArray image, const Rect& boundingBox) CV_OVERRIDE; - // bool update(InputArray image, CV_OUT Rect& boundingBox) CV_OVERRIDE; -}; - -//! @} video_track - -} // cv - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_TRACKING_HPP +#define OPENCV_TRACKING_HPP + +#include "opencv2/core.hpp" +#include "opencv2/imgproc.hpp" + +namespace cv +{ + +//! @addtogroup video_track +//! @{ + +enum { OPTFLOW_USE_INITIAL_FLOW = 4, + OPTFLOW_LK_GET_MIN_EIGENVALS = 8, + OPTFLOW_FARNEBACK_GAUSSIAN = 256 + }; + +/** @brief Finds an object center, size, and orientation. + +@param probImage Back projection of the object histogram. See calcBackProject. +@param window Initial search window. +@param criteria Stop criteria for the underlying meanShift. +returns +(in old interfaces) Number of iterations CAMSHIFT took to converge +The function implements the CAMSHIFT object tracking algorithm @cite Bradski98 . First, it finds an +object center using meanShift and then adjusts the window size and finds the optimal rotation. The +function returns the rotated rectangle structure that includes the object position, size, and +orientation. The next position of the search window can be obtained with RotatedRect::boundingRect() + +See the OpenCV sample camshiftdemo.c that tracks colored objects. + +@note +- (Python) A sample explaining the camshift tracking algorithm can be found at + opencv_source_code/samples/python/camshift.py + */ +CV_EXPORTS_W RotatedRect CamShift( InputArray probImage, CV_IN_OUT Rect& window, + TermCriteria criteria ); +/** @example samples/cpp/camshiftdemo.cpp +An example using the mean-shift tracking algorithm +*/ + +/** @brief Finds an object on a back projection image. + +@param probImage Back projection of the object histogram. See calcBackProject for details. +@param window Initial search window. +@param criteria Stop criteria for the iterative search algorithm. +returns +: Number of iterations CAMSHIFT took to converge. +The function implements the iterative object search algorithm. It takes the input back projection of +an object and the initial position. The mass center in window of the back projection image is +computed and the search window center shifts to the mass center. The procedure is repeated until the +specified number of iterations criteria.maxCount is done or until the window center shifts by less +than criteria.epsilon. The algorithm is used inside CamShift and, unlike CamShift , the search +window size or orientation do not change during the search. You can simply pass the output of +calcBackProject to this function. But better results can be obtained if you pre-filter the back +projection and remove the noise. For example, you can do this by retrieving connected components +with findContours , throwing away contours with small area ( contourArea ), and rendering the +remaining contours with drawContours. + + */ +CV_EXPORTS_W int meanShift( InputArray probImage, CV_IN_OUT Rect& window, TermCriteria criteria ); + +/** @brief Constructs the image pyramid which can be passed to calcOpticalFlowPyrLK. + +@param img 8-bit input image. +@param pyramid output pyramid. +@param winSize window size of optical flow algorithm. Must be not less than winSize argument of +calcOpticalFlowPyrLK. It is needed to calculate required padding for pyramid levels. +@param maxLevel 0-based maximal pyramid level number. +@param withDerivatives set to precompute gradients for the every pyramid level. If pyramid is +constructed without the gradients then calcOpticalFlowPyrLK will calculate them internally. +@param pyrBorder the border mode for pyramid layers. +@param derivBorder the border mode for gradients. +@param tryReuseInputImage put ROI of input image into the pyramid if possible. You can pass false +to force data copying. +@return number of levels in constructed pyramid. Can be less than maxLevel. + */ +CV_EXPORTS_W int buildOpticalFlowPyramid( InputArray img, OutputArrayOfArrays pyramid, + Size winSize, int maxLevel, bool withDerivatives = true, + int pyrBorder = BORDER_REFLECT_101, + int derivBorder = BORDER_CONSTANT, + bool tryReuseInputImage = true ); + +/** @example samples/cpp/lkdemo.cpp +An example using the Lucas-Kanade optical flow algorithm +*/ + +/** @brief Calculates an optical flow for a sparse feature set using the iterative Lucas-Kanade method with +pyramids. + +@param prevImg first 8-bit input image or pyramid constructed by buildOpticalFlowPyramid. +@param nextImg second input image or pyramid of the same size and the same type as prevImg. +@param prevPts vector of 2D points for which the flow needs to be found; point coordinates must be +single-precision floating-point numbers. +@param nextPts output vector of 2D points (with single-precision floating-point coordinates) +containing the calculated new positions of input features in the second image; when +OPTFLOW_USE_INITIAL_FLOW flag is passed, the vector must have the same size as in the input. +@param status output status vector (of unsigned chars); each element of the vector is set to 1 if +the flow for the corresponding features has been found, otherwise, it is set to 0. +@param err output vector of errors; each element of the vector is set to an error for the +corresponding feature, type of the error measure can be set in flags parameter; if the flow wasn't +found then the error is not defined (use the status parameter to find such cases). +@param winSize size of the search window at each pyramid level. +@param maxLevel 0-based maximal pyramid level number; if set to 0, pyramids are not used (single +level), if set to 1, two levels are used, and so on; if pyramids are passed to input then +algorithm will use as many levels as pyramids have but no more than maxLevel. +@param criteria parameter, specifying the termination criteria of the iterative search algorithm +(after the specified maximum number of iterations criteria.maxCount or when the search window +moves by less than criteria.epsilon. +@param flags operation flags: + - **OPTFLOW_USE_INITIAL_FLOW** uses initial estimations, stored in nextPts; if the flag is + not set, then prevPts is copied to nextPts and is considered the initial estimate. + - **OPTFLOW_LK_GET_MIN_EIGENVALS** use minimum eigen values as an error measure (see + minEigThreshold description); if the flag is not set, then L1 distance between patches + around the original and a moved point, divided by number of pixels in a window, is used as a + error measure. +@param minEigThreshold the algorithm calculates the minimum eigen value of a 2x2 normal matrix of +optical flow equations (this matrix is called a spatial gradient matrix in @cite Bouguet00), divided +by number of pixels in a window; if this value is less than minEigThreshold, then a corresponding +feature is filtered out and its flow is not processed, so it allows to remove bad points and get a +performance boost. + +The function implements a sparse iterative version of the Lucas-Kanade optical flow in pyramids. See +@cite Bouguet00 . The function is parallelized with the TBB library. + +@note Some examples: + +- An example using the Lucas-Kanade optical flow algorithm can be found at + opencv_source_code/samples/cpp/lkdemo.cpp +- (Python) An example using the Lucas-Kanade optical flow algorithm can be found at + opencv_source_code/samples/python/lk_track.py +- (Python) An example using the Lucas-Kanade tracker for homography matching can be found at + opencv_source_code/samples/python/lk_homography.py + */ +CV_EXPORTS_W void calcOpticalFlowPyrLK( InputArray prevImg, InputArray nextImg, + InputArray prevPts, InputOutputArray nextPts, + OutputArray status, OutputArray err, + Size winSize = Size(21,21), int maxLevel = 3, + TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01), + int flags = 0, double minEigThreshold = 1e-4 ); + +/** @brief Computes a dense optical flow using the Gunnar Farneback's algorithm. + +@param prev first 8-bit single-channel input image. +@param next second input image of the same size and the same type as prev. +@param flow computed flow image that has the same size as prev and type CV_32FC2. +@param pyr_scale parameter, specifying the image scale (\<1) to build pyramids for each image; +pyr_scale=0.5 means a classical pyramid, where each next layer is twice smaller than the previous +one. +@param levels number of pyramid layers including the initial image; levels=1 means that no extra +layers are created and only the original images are used. +@param winsize averaging window size; larger values increase the algorithm robustness to image +noise and give more chances for fast motion detection, but yield more blurred motion field. +@param iterations number of iterations the algorithm does at each pyramid level. +@param poly_n size of the pixel neighborhood used to find polynomial expansion in each pixel; +larger values mean that the image will be approximated with smoother surfaces, yielding more +robust algorithm and more blurred motion field, typically poly_n =5 or 7. +@param poly_sigma standard deviation of the Gaussian that is used to smooth derivatives used as a +basis for the polynomial expansion; for poly_n=5, you can set poly_sigma=1.1, for poly_n=7, a +good value would be poly_sigma=1.5. +@param flags operation flags that can be a combination of the following: + - **OPTFLOW_USE_INITIAL_FLOW** uses the input flow as an initial flow approximation. + - **OPTFLOW_FARNEBACK_GAUSSIAN** uses the Gaussian \f$\texttt{winsize}\times\texttt{winsize}\f$ + filter instead of a box filter of the same size for optical flow estimation; usually, this + option gives z more accurate flow than with a box filter, at the cost of lower speed; + normally, winsize for a Gaussian window should be set to a larger value to achieve the same + level of robustness. + +The function finds an optical flow for each prev pixel using the @cite Farneback2003 algorithm so that + +\f[\texttt{prev} (y,x) \sim \texttt{next} ( y + \texttt{flow} (y,x)[1], x + \texttt{flow} (y,x)[0])\f] + +@note Some examples: + +- An example using the optical flow algorithm described by Gunnar Farneback can be found at + opencv_source_code/samples/cpp/fback.cpp +- (Python) An example using the optical flow algorithm described by Gunnar Farneback can be + found at opencv_source_code/samples/python/opt_flow.py + */ +CV_EXPORTS_W void calcOpticalFlowFarneback( InputArray prev, InputArray next, InputOutputArray flow, + double pyr_scale, int levels, int winsize, + int iterations, int poly_n, double poly_sigma, + int flags ); + +/** @brief Computes an optimal affine transformation between two 2D point sets. + +@param src First input 2D point set stored in std::vector or Mat, or an image stored in Mat. +@param dst Second input 2D point set of the same size and the same type as A, or another image. +@param fullAffine If true, the function finds an optimal affine transformation with no additional +restrictions (6 degrees of freedom). Otherwise, the class of transformations to choose from is +limited to combinations of translation, rotation, and uniform scaling (4 degrees of freedom). + +The function finds an optimal affine transform *[A|b]* (a 2 x 3 floating-point matrix) that +approximates best the affine transformation between: + +* Two point sets +* Two raster images. In this case, the function first finds some features in the src image and + finds the corresponding features in dst image. After that, the problem is reduced to the first + case. +In case of point sets, the problem is formulated as follows: you need to find a 2x2 matrix *A* and +2x1 vector *b* so that: + +\f[[A^*|b^*] = arg \min _{[A|b]} \sum _i \| \texttt{dst}[i] - A { \texttt{src}[i]}^T - b \| ^2\f] +where src[i] and dst[i] are the i-th points in src and dst, respectively +\f$[A|b]\f$ can be either arbitrary (when fullAffine=true ) or have a form of +\f[\begin{bmatrix} a_{11} & a_{12} & b_1 \\ -a_{12} & a_{11} & b_2 \end{bmatrix}\f] +when fullAffine=false. + +@deprecated Use cv::estimateAffine2D, cv::estimateAffinePartial2D instead. If you are using this function +with images, extract points using cv::calcOpticalFlowPyrLK and then use the estimation functions. + +@sa +estimateAffine2D, estimateAffinePartial2D, getAffineTransform, getPerspectiveTransform, findHomography + */ +CV_DEPRECATED CV_EXPORTS Mat estimateRigidTransform( InputArray src, InputArray dst, bool fullAffine ); + +enum +{ + MOTION_TRANSLATION = 0, + MOTION_EUCLIDEAN = 1, + MOTION_AFFINE = 2, + MOTION_HOMOGRAPHY = 3 +}; + +/** @brief Computes the Enhanced Correlation Coefficient value between two images @cite EP08 . + +@param templateImage single-channel template image; CV_8U or CV_32F array. +@param inputImage single-channel input image to be warped to provide an image similar to + templateImage, same type as templateImage. +@param inputMask An optional mask to indicate valid values of inputImage. + +@sa +findTransformECC + */ + +CV_EXPORTS_W double computeECC(InputArray templateImage, InputArray inputImage, InputArray inputMask = noArray()); + +/** @example samples/cpp/image_alignment.cpp +An example using the image alignment ECC algorithm +*/ + +/** @brief Finds the geometric transform (warp) between two images in terms of the ECC criterion @cite EP08 . + +@param templateImage single-channel template image; CV_8U or CV_32F array. +@param inputImage single-channel input image which should be warped with the final warpMatrix in +order to provide an image similar to templateImage, same type as templateImage. +@param warpMatrix floating-point \f$2\times 3\f$ or \f$3\times 3\f$ mapping matrix (warp). +@param motionType parameter, specifying the type of motion: + - **MOTION_TRANSLATION** sets a translational motion model; warpMatrix is \f$2\times 3\f$ with + the first \f$2\times 2\f$ part being the unity matrix and the rest two parameters being + estimated. + - **MOTION_EUCLIDEAN** sets a Euclidean (rigid) transformation as motion model; three + parameters are estimated; warpMatrix is \f$2\times 3\f$. + - **MOTION_AFFINE** sets an affine motion model (DEFAULT); six parameters are estimated; + warpMatrix is \f$2\times 3\f$. + - **MOTION_HOMOGRAPHY** sets a homography as a motion model; eight parameters are + estimated;\`warpMatrix\` is \f$3\times 3\f$. +@param criteria parameter, specifying the termination criteria of the ECC algorithm; +criteria.epsilon defines the threshold of the increment in the correlation coefficient between two +iterations (a negative criteria.epsilon makes criteria.maxcount the only termination criterion). +Default values are shown in the declaration above. +@param inputMask An optional mask to indicate valid values of inputImage. +@param gaussFiltSize An optional value indicating size of gaussian blur filter; (DEFAULT: 5) + +The function estimates the optimum transformation (warpMatrix) with respect to ECC criterion +(@cite EP08), that is + +\f[\texttt{warpMatrix} = \arg\max_{W} \texttt{ECC}(\texttt{templateImage}(x,y),\texttt{inputImage}(x',y'))\f] + +where + +\f[\begin{bmatrix} x' \\ y' \end{bmatrix} = W \cdot \begin{bmatrix} x \\ y \\ 1 \end{bmatrix}\f] + +(the equation holds with homogeneous coordinates for homography). It returns the final enhanced +correlation coefficient, that is the correlation coefficient between the template image and the +final warped input image. When a \f$3\times 3\f$ matrix is given with motionType =0, 1 or 2, the third +row is ignored. + +Unlike findHomography and estimateRigidTransform, the function findTransformECC implements an +area-based alignment that builds on intensity similarities. In essence, the function updates the +initial transformation that roughly aligns the images. If this information is missing, the identity +warp (unity matrix) is used as an initialization. Note that if images undergo strong +displacements/rotations, an initial transformation that roughly aligns the images is necessary +(e.g., a simple euclidean/similarity transform that allows for the images showing the same image +content approximately). Use inverse warping in the second image to take an image close to the first +one, i.e. use the flag WARP_INVERSE_MAP with warpAffine or warpPerspective. See also the OpenCV +sample image_alignment.cpp that demonstrates the use of the function. Note that the function throws +an exception if algorithm does not converges. + +@sa +computeECC, estimateAffine2D, estimateAffinePartial2D, findHomography + */ +CV_EXPORTS_W double findTransformECC( InputArray templateImage, InputArray inputImage, + InputOutputArray warpMatrix, int motionType, + TermCriteria criteria, + InputArray inputMask, int gaussFiltSize); + +/** @overload */ +CV_EXPORTS_W +double findTransformECC(InputArray templateImage, InputArray inputImage, + InputOutputArray warpMatrix, int motionType = MOTION_AFFINE, + TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 50, 0.001), + InputArray inputMask = noArray()); + +/** @example samples/cpp/kalman.cpp +An example using the standard Kalman filter +*/ + +/** @brief Kalman filter class. + +The class implements a standard Kalman filter , +@cite Welch95 . However, you can modify transitionMatrix, controlMatrix, and measurementMatrix to get +an extended Kalman filter functionality. +@note In C API when CvKalman\* kalmanFilter structure is not needed anymore, it should be released +with cvReleaseKalman(&kalmanFilter) + */ +class CV_EXPORTS_W KalmanFilter +{ +public: + CV_WRAP KalmanFilter(); + /** @overload + @param dynamParams Dimensionality of the state. + @param measureParams Dimensionality of the measurement. + @param controlParams Dimensionality of the control vector. + @param type Type of the created matrices that should be CV_32F or CV_64F. + */ + CV_WRAP KalmanFilter( int dynamParams, int measureParams, int controlParams = 0, int type = CV_32F ); + + /** @brief Re-initializes Kalman filter. The previous content is destroyed. + + @param dynamParams Dimensionality of the state. + @param measureParams Dimensionality of the measurement. + @param controlParams Dimensionality of the control vector. + @param type Type of the created matrices that should be CV_32F or CV_64F. + */ + void init( int dynamParams, int measureParams, int controlParams = 0, int type = CV_32F ); + + /** @brief Computes a predicted state. + + @param control The optional input control + */ + CV_WRAP const Mat& predict( const Mat& control = Mat() ); + + /** @brief Updates the predicted state from the measurement. + + @param measurement The measured system parameters + */ + CV_WRAP const Mat& correct( const Mat& measurement ); + + CV_PROP_RW Mat statePre; //!< predicted state (x'(k)): x(k)=A*x(k-1)+B*u(k) + CV_PROP_RW Mat statePost; //!< corrected state (x(k)): x(k)=x'(k)+K(k)*(z(k)-H*x'(k)) + CV_PROP_RW Mat transitionMatrix; //!< state transition matrix (A) + CV_PROP_RW Mat controlMatrix; //!< control matrix (B) (not used if there is no control) + CV_PROP_RW Mat measurementMatrix; //!< measurement matrix (H) + CV_PROP_RW Mat processNoiseCov; //!< process noise covariance matrix (Q) + CV_PROP_RW Mat measurementNoiseCov;//!< measurement noise covariance matrix (R) + CV_PROP_RW Mat errorCovPre; //!< priori error estimate covariance matrix (P'(k)): P'(k)=A*P(k-1)*At + Q)*/ + CV_PROP_RW Mat gain; //!< Kalman gain matrix (K(k)): K(k)=P'(k)*Ht*inv(H*P'(k)*Ht+R) + CV_PROP_RW Mat errorCovPost; //!< posteriori error estimate covariance matrix (P(k)): P(k)=(I-K(k)*H)*P'(k) + + // temporary matrices + Mat temp1; + Mat temp2; + Mat temp3; + Mat temp4; + Mat temp5; +}; + + +/** @brief Read a .flo file + + @param path Path to the file to be loaded + + The function readOpticalFlow loads a flow field from a file and returns it as a single matrix. + Resulting Mat has a type CV_32FC2 - floating-point, 2-channel. First channel corresponds to the + flow in the horizontal direction (u), second - vertical (v). + */ +CV_EXPORTS_W Mat readOpticalFlow( const String& path ); +/** @brief Write a .flo to disk + + @param path Path to the file to be written + @param flow Flow field to be stored + + The function stores a flow field in a file, returns true on success, false otherwise. + The flow field must be a 2-channel, floating-point matrix (CV_32FC2). First channel corresponds + to the flow in the horizontal direction (u), second - vertical (v). + */ +CV_EXPORTS_W bool writeOpticalFlow( const String& path, InputArray flow ); + +/** + Base class for dense optical flow algorithms +*/ +class CV_EXPORTS_W DenseOpticalFlow : public Algorithm +{ +public: + /** @brief Calculates an optical flow. + + @param I0 first 8-bit single-channel input image. + @param I1 second input image of the same size and the same type as prev. + @param flow computed flow image that has the same size as prev and type CV_32FC2. + */ + CV_WRAP virtual void calc( InputArray I0, InputArray I1, InputOutputArray flow ) = 0; + /** @brief Releases all inner buffers. + */ + CV_WRAP virtual void collectGarbage() = 0; +}; + +/** @brief Base interface for sparse optical flow algorithms. + */ +class CV_EXPORTS_W SparseOpticalFlow : public Algorithm +{ +public: + /** @brief Calculates a sparse optical flow. + + @param prevImg First input image. + @param nextImg Second input image of the same size and the same type as prevImg. + @param prevPts Vector of 2D points for which the flow needs to be found. + @param nextPts Output vector of 2D points containing the calculated new positions of input features in the second image. + @param status Output status vector. Each element of the vector is set to 1 if the + flow for the corresponding features has been found. Otherwise, it is set to 0. + @param err Optional output vector that contains error response for each point (inverse confidence). + */ + CV_WRAP virtual void calc(InputArray prevImg, InputArray nextImg, + InputArray prevPts, InputOutputArray nextPts, + OutputArray status, + OutputArray err = cv::noArray()) = 0; +}; + + +/** @brief Class computing a dense optical flow using the Gunnar Farneback's algorithm. + */ +class CV_EXPORTS_W FarnebackOpticalFlow : public DenseOpticalFlow +{ +public: + CV_WRAP virtual int getNumLevels() const = 0; + CV_WRAP virtual void setNumLevels(int numLevels) = 0; + + CV_WRAP virtual double getPyrScale() const = 0; + CV_WRAP virtual void setPyrScale(double pyrScale) = 0; + + CV_WRAP virtual bool getFastPyramids() const = 0; + CV_WRAP virtual void setFastPyramids(bool fastPyramids) = 0; + + CV_WRAP virtual int getWinSize() const = 0; + CV_WRAP virtual void setWinSize(int winSize) = 0; + + CV_WRAP virtual int getNumIters() const = 0; + CV_WRAP virtual void setNumIters(int numIters) = 0; + + CV_WRAP virtual int getPolyN() const = 0; + CV_WRAP virtual void setPolyN(int polyN) = 0; + + CV_WRAP virtual double getPolySigma() const = 0; + CV_WRAP virtual void setPolySigma(double polySigma) = 0; + + CV_WRAP virtual int getFlags() const = 0; + CV_WRAP virtual void setFlags(int flags) = 0; + + CV_WRAP static Ptr create( + int numLevels = 5, + double pyrScale = 0.5, + bool fastPyramids = false, + int winSize = 13, + int numIters = 10, + int polyN = 5, + double polySigma = 1.1, + int flags = 0); +}; + +/** @brief Variational optical flow refinement + +This class implements variational refinement of the input flow field, i.e. +it uses input flow to initialize the minimization of the following functional: +\f$E(U) = \int_{\Omega} \delta \Psi(E_I) + \gamma \Psi(E_G) + \alpha \Psi(E_S) \f$, +where \f$E_I,E_G,E_S\f$ are color constancy, gradient constancy and smoothness terms +respectively. \f$\Psi(s^2)=\sqrt{s^2+\epsilon^2}\f$ is a robust penalizer to limit the +influence of outliers. A complete formulation and a description of the minimization +procedure can be found in @cite Brox2004 +*/ +class CV_EXPORTS_W VariationalRefinement : public DenseOpticalFlow +{ +public: + /** @brief @ref calc function overload to handle separate horizontal (u) and vertical (v) flow components + (to avoid extra splits/merges) */ + CV_WRAP virtual void calcUV(InputArray I0, InputArray I1, InputOutputArray flow_u, InputOutputArray flow_v) = 0; + + /** @brief Number of outer (fixed-point) iterations in the minimization procedure. + @see setFixedPointIterations */ + CV_WRAP virtual int getFixedPointIterations() const = 0; + /** @copybrief getFixedPointIterations @see getFixedPointIterations */ + CV_WRAP virtual void setFixedPointIterations(int val) = 0; + + /** @brief Number of inner successive over-relaxation (SOR) iterations + in the minimization procedure to solve the respective linear system. + @see setSorIterations */ + CV_WRAP virtual int getSorIterations() const = 0; + /** @copybrief getSorIterations @see getSorIterations */ + CV_WRAP virtual void setSorIterations(int val) = 0; + + /** @brief Relaxation factor in SOR + @see setOmega */ + CV_WRAP virtual float getOmega() const = 0; + /** @copybrief getOmega @see getOmega */ + CV_WRAP virtual void setOmega(float val) = 0; + + /** @brief Weight of the smoothness term + @see setAlpha */ + CV_WRAP virtual float getAlpha() const = 0; + /** @copybrief getAlpha @see getAlpha */ + CV_WRAP virtual void setAlpha(float val) = 0; + + /** @brief Weight of the color constancy term + @see setDelta */ + CV_WRAP virtual float getDelta() const = 0; + /** @copybrief getDelta @see getDelta */ + CV_WRAP virtual void setDelta(float val) = 0; + + /** @brief Weight of the gradient constancy term + @see setGamma */ + CV_WRAP virtual float getGamma() const = 0; + /** @copybrief getGamma @see getGamma */ + CV_WRAP virtual void setGamma(float val) = 0; + + /** @brief Norm value shift for robust penalizer + @see setEpsilon */ + CV_WRAP virtual float getEpsilon() const = 0; + /** @copybrief getEpsilon @see getEpsilon */ + CV_WRAP virtual void setEpsilon(float val) = 0; + + /** @brief Creates an instance of VariationalRefinement + */ + CV_WRAP static Ptr create(); +}; + +/** @brief DIS optical flow algorithm. + +This class implements the Dense Inverse Search (DIS) optical flow algorithm. More +details about the algorithm can be found at @cite Kroeger2016 . Includes three presets with preselected +parameters to provide reasonable trade-off between speed and quality. However, even the slowest preset is +still relatively fast, use DeepFlow if you need better quality and don't care about speed. + +This implementation includes several additional features compared to the algorithm described in the paper, +including spatial propagation of flow vectors (@ref getUseSpatialPropagation), as well as an option to +utilize an initial flow approximation passed to @ref calc (which is, essentially, temporal propagation, +if the previous frame's flow field is passed). +*/ +class CV_EXPORTS_W DISOpticalFlow : public DenseOpticalFlow +{ +public: + enum + { + PRESET_ULTRAFAST = 0, + PRESET_FAST = 1, + PRESET_MEDIUM = 2 + }; + + /** @brief Finest level of the Gaussian pyramid on which the flow is computed (zero level + corresponds to the original image resolution). The final flow is obtained by bilinear upscaling. + @see setFinestScale */ + CV_WRAP virtual int getFinestScale() const = 0; + /** @copybrief getFinestScale @see getFinestScale */ + CV_WRAP virtual void setFinestScale(int val) = 0; + + /** @brief Size of an image patch for matching (in pixels). Normally, default 8x8 patches work well + enough in most cases. + @see setPatchSize */ + CV_WRAP virtual int getPatchSize() const = 0; + /** @copybrief getPatchSize @see getPatchSize */ + CV_WRAP virtual void setPatchSize(int val) = 0; + + /** @brief Stride between neighbor patches. Must be less than patch size. Lower values correspond + to higher flow quality. + @see setPatchStride */ + CV_WRAP virtual int getPatchStride() const = 0; + /** @copybrief getPatchStride @see getPatchStride */ + CV_WRAP virtual void setPatchStride(int val) = 0; + + /** @brief Maximum number of gradient descent iterations in the patch inverse search stage. Higher values + may improve quality in some cases. + @see setGradientDescentIterations */ + CV_WRAP virtual int getGradientDescentIterations() const = 0; + /** @copybrief getGradientDescentIterations @see getGradientDescentIterations */ + CV_WRAP virtual void setGradientDescentIterations(int val) = 0; + + /** @brief Number of fixed point iterations of variational refinement per scale. Set to zero to + disable variational refinement completely. Higher values will typically result in more smooth and + high-quality flow. + @see setGradientDescentIterations */ + CV_WRAP virtual int getVariationalRefinementIterations() const = 0; + /** @copybrief getGradientDescentIterations @see getGradientDescentIterations */ + CV_WRAP virtual void setVariationalRefinementIterations(int val) = 0; + + /** @brief Weight of the smoothness term + @see setVariationalRefinementAlpha */ + CV_WRAP virtual float getVariationalRefinementAlpha() const = 0; + /** @copybrief getVariationalRefinementAlpha @see getVariationalRefinementAlpha */ + CV_WRAP virtual void setVariationalRefinementAlpha(float val) = 0; + + /** @brief Weight of the color constancy term + @see setVariationalRefinementDelta */ + CV_WRAP virtual float getVariationalRefinementDelta() const = 0; + /** @copybrief getVariationalRefinementDelta @see getVariationalRefinementDelta */ + CV_WRAP virtual void setVariationalRefinementDelta(float val) = 0; + + /** @brief Weight of the gradient constancy term + @see setVariationalRefinementGamma */ + CV_WRAP virtual float getVariationalRefinementGamma() const = 0; + /** @copybrief getVariationalRefinementGamma @see getVariationalRefinementGamma */ + CV_WRAP virtual void setVariationalRefinementGamma(float val) = 0; + + /** @brief Norm value shift for robust penalizer + @see setVariationalRefinementEpsilon */ + CV_WRAP virtual float getVariationalRefinementEpsilon() const = 0; + /** @copybrief getVariationalRefinementEpsilon @see getVariationalRefinementEpsilon */ + CV_WRAP virtual void setVariationalRefinementEpsilon(float val) = 0; + + + /** @brief Whether to use mean-normalization of patches when computing patch distance. It is turned on + by default as it typically provides a noticeable quality boost because of increased robustness to + illumination variations. Turn it off if you are certain that your sequence doesn't contain any changes + in illumination. + @see setUseMeanNormalization */ + CV_WRAP virtual bool getUseMeanNormalization() const = 0; + /** @copybrief getUseMeanNormalization @see getUseMeanNormalization */ + CV_WRAP virtual void setUseMeanNormalization(bool val) = 0; + + /** @brief Whether to use spatial propagation of good optical flow vectors. This option is turned on by + default, as it tends to work better on average and can sometimes help recover from major errors + introduced by the coarse-to-fine scheme employed by the DIS optical flow algorithm. Turning this + option off can make the output flow field a bit smoother, however. + @see setUseSpatialPropagation */ + CV_WRAP virtual bool getUseSpatialPropagation() const = 0; + /** @copybrief getUseSpatialPropagation @see getUseSpatialPropagation */ + CV_WRAP virtual void setUseSpatialPropagation(bool val) = 0; + + /** @brief Creates an instance of DISOpticalFlow + + @param preset one of PRESET_ULTRAFAST, PRESET_FAST and PRESET_MEDIUM + */ + CV_WRAP static Ptr create(int preset = DISOpticalFlow::PRESET_FAST); +}; + +/** @brief Class used for calculating a sparse optical flow. + +The class can calculate an optical flow for a sparse feature set using the +iterative Lucas-Kanade method with pyramids. + +@sa calcOpticalFlowPyrLK + +*/ +class CV_EXPORTS_W SparsePyrLKOpticalFlow : public SparseOpticalFlow +{ +public: + CV_WRAP virtual Size getWinSize() const = 0; + CV_WRAP virtual void setWinSize(Size winSize) = 0; + + CV_WRAP virtual int getMaxLevel() const = 0; + CV_WRAP virtual void setMaxLevel(int maxLevel) = 0; + + CV_WRAP virtual TermCriteria getTermCriteria() const = 0; + CV_WRAP virtual void setTermCriteria(TermCriteria& crit) = 0; + + CV_WRAP virtual int getFlags() const = 0; + CV_WRAP virtual void setFlags(int flags) = 0; + + CV_WRAP virtual double getMinEigThreshold() const = 0; + CV_WRAP virtual void setMinEigThreshold(double minEigThreshold) = 0; + + CV_WRAP static Ptr create( + Size winSize = Size(21, 21), + int maxLevel = 3, TermCriteria crit = + TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01), + int flags = 0, + double minEigThreshold = 1e-4); +}; + + + + +/** @brief Base abstract class for the long-term tracker + */ +class CV_EXPORTS_W Tracker +{ +protected: + Tracker(); +public: + virtual ~Tracker(); + + /** @brief Initialize the tracker with a known bounding box that surrounded the target + @param image The initial frame + @param boundingBox The initial bounding box + */ + CV_WRAP virtual + void init(InputArray image, const Rect& boundingBox) = 0; + + /** @brief Update the tracker, find the new most likely bounding box for the target + @param image The current frame + @param boundingBox The bounding box that represent the new target location, if true was returned, not + modified otherwise + + @return True means that target was located and false means that tracker cannot locate target in + current frame. Note, that latter *does not* imply that tracker has failed, maybe target is indeed + missing from the frame (say, out of sight) + */ + CV_WRAP virtual + bool update(InputArray image, CV_OUT Rect& boundingBox) = 0; +}; + + + +/** @brief The MIL algorithm trains a classifier in an online manner to separate the object from the +background. + +Multiple Instance Learning avoids the drift problem for a robust tracking. The implementation is +based on @cite MIL . + +Original code can be found here + */ +class CV_EXPORTS_W TrackerMIL : public Tracker +{ +protected: + TrackerMIL(); // use ::create() +public: + virtual ~TrackerMIL() CV_OVERRIDE; + + struct CV_EXPORTS_W_SIMPLE Params + { + CV_WRAP Params(); + //parameters for sampler + CV_PROP_RW float samplerInitInRadius; //!< radius for gathering positive instances during init + CV_PROP_RW int samplerInitMaxNegNum; //!< # negative samples to use during init + CV_PROP_RW float samplerSearchWinSize; //!< size of search window + CV_PROP_RW float samplerTrackInRadius; //!< radius for gathering positive instances during tracking + CV_PROP_RW int samplerTrackMaxPosNum; //!< # positive samples to use during tracking + CV_PROP_RW int samplerTrackMaxNegNum; //!< # negative samples to use during tracking + CV_PROP_RW int featureSetNumFeatures; //!< # features + }; + + /** @brief Create MIL tracker instance + * @param parameters MIL parameters TrackerMIL::Params + */ + static CV_WRAP + Ptr create(const TrackerMIL::Params ¶meters = TrackerMIL::Params()); + + //void init(InputArray image, const Rect& boundingBox) CV_OVERRIDE; + //bool update(InputArray image, CV_OUT Rect& boundingBox) CV_OVERRIDE; +}; + + + +/** @brief the GOTURN (Generic Object Tracking Using Regression Networks) tracker + * + * GOTURN (@cite GOTURN) is kind of trackers based on Convolutional Neural Networks (CNN). While taking all advantages of CNN trackers, + * GOTURN is much faster due to offline training without online fine-tuning nature. + * GOTURN tracker addresses the problem of single target tracking: given a bounding box label of an object in the first frame of the video, + * we track that object through the rest of the video. NOTE: Current method of GOTURN does not handle occlusions; however, it is fairly + * robust to viewpoint changes, lighting changes, and deformations. + * Inputs of GOTURN are two RGB patches representing Target and Search patches resized to 227x227. + * Outputs of GOTURN are predicted bounding box coordinates, relative to Search patch coordinate system, in format X1,Y1,X2,Y2. + * Original paper is here: + * As long as original authors implementation: + * Implementation of training algorithm is placed in separately here due to 3d-party dependencies: + * + * GOTURN architecture goturn.prototxt and trained model goturn.caffemodel are accessible on opencv_extra GitHub repository. + */ +class CV_EXPORTS_W TrackerGOTURN : public Tracker +{ +protected: + TrackerGOTURN(); // use ::create() +public: + virtual ~TrackerGOTURN() CV_OVERRIDE; + + struct CV_EXPORTS_W_SIMPLE Params + { + CV_WRAP Params(); + CV_PROP_RW std::string modelTxt; + CV_PROP_RW std::string modelBin; + }; + + /** @brief Constructor + @param parameters GOTURN parameters TrackerGOTURN::Params + */ + static CV_WRAP + Ptr create(const TrackerGOTURN::Params& parameters = TrackerGOTURN::Params()); + + //void init(InputArray image, const Rect& boundingBox) CV_OVERRIDE; + //bool update(InputArray image, CV_OUT Rect& boundingBox) CV_OVERRIDE; +}; + +class CV_EXPORTS_W TrackerDaSiamRPN : public Tracker +{ +protected: + TrackerDaSiamRPN(); // use ::create() +public: + virtual ~TrackerDaSiamRPN() CV_OVERRIDE; + + struct CV_EXPORTS_W_SIMPLE Params + { + CV_WRAP Params(); + CV_PROP_RW std::string model; + CV_PROP_RW std::string kernel_cls1; + CV_PROP_RW std::string kernel_r1; + CV_PROP_RW int backend; + CV_PROP_RW int target; + }; + + /** @brief Constructor + @param parameters DaSiamRPN parameters TrackerDaSiamRPN::Params + */ + static CV_WRAP + Ptr create(const TrackerDaSiamRPN::Params& parameters = TrackerDaSiamRPN::Params()); + + /** @brief Return tracking score + */ + CV_WRAP virtual float getTrackingScore() = 0; + + //void init(InputArray image, const Rect& boundingBox) CV_OVERRIDE; + //bool update(InputArray image, CV_OUT Rect& boundingBox) CV_OVERRIDE; +}; + +/** @brief the Nano tracker is a super lightweight dnn-based general object tracking. + * + * Nano tracker is much faster and extremely lightweight due to special model structure, the whole model size is about 1.9 MB. + * Nano tracker needs two models: one for feature extraction (backbone) and the another for localization (neckhead). + * Model download link: https://github.com/HonglinChu/SiamTrackers/tree/master/NanoTrack/models/nanotrackv2 + * Original repo is here: https://github.com/HonglinChu/NanoTrack + * Author: HongLinChu, 1628464345@qq.com + */ +class CV_EXPORTS_W TrackerNano : public Tracker +{ +protected: + TrackerNano(); // use ::create() +public: + virtual ~TrackerNano() CV_OVERRIDE; + + struct CV_EXPORTS_W_SIMPLE Params + { + CV_WRAP Params(); + CV_PROP_RW std::string backbone; + CV_PROP_RW std::string neckhead; + CV_PROP_RW int backend; + CV_PROP_RW int target; + }; + + /** @brief Constructor + @param parameters NanoTrack parameters TrackerNano::Params + */ + static CV_WRAP + Ptr create(const TrackerNano::Params& parameters = TrackerNano::Params()); + + /** @brief Return tracking score + */ + CV_WRAP virtual float getTrackingScore() = 0; + + //void init(InputArray image, const Rect& boundingBox) CV_OVERRIDE; + //bool update(InputArray image, CV_OUT Rect& boundingBox) CV_OVERRIDE; +}; + +/** @brief the VIT tracker is a super lightweight dnn-based general object tracking. + * + * VIT tracker is much faster and extremely lightweight due to special model structure, the model file is about 767KB. + * Model download link: https://github.com/opencv/opencv_zoo/tree/main/models/object_tracking_vittrack + * Author: PengyuLiu, 1872918507@qq.com + */ +class CV_EXPORTS_W TrackerVit : public Tracker +{ +protected: + TrackerVit(); // use ::create() +public: + virtual ~TrackerVit() CV_OVERRIDE; + + struct CV_EXPORTS_W_SIMPLE Params + { + CV_WRAP Params(); + CV_PROP_RW std::string net; + CV_PROP_RW int backend; + CV_PROP_RW int target; + CV_PROP_RW Scalar meanvalue; + CV_PROP_RW Scalar stdvalue; + CV_PROP_RW float tracking_score_threshold; + }; + + /** @brief Constructor + @param parameters vit tracker parameters TrackerVit::Params + */ + static CV_WRAP + Ptr create(const TrackerVit::Params& parameters = TrackerVit::Params()); + + /** @brief Return tracking score + */ + CV_WRAP virtual float getTrackingScore() = 0; + + // void init(InputArray image, const Rect& boundingBox) CV_OVERRIDE; + // bool update(InputArray image, CV_OUT Rect& boundingBox) CV_OVERRIDE; +}; + +//! @} video_track + +} // cv + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/video/video.hpp b/3rdParty/opencv-4.11.0/opencv2/video/video.hpp index 8267b85d59..2d7a38be57 100644 --- a/3rdParty/opencv-4.11.0/opencv2/video/video.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/video/video.hpp @@ -1,48 +1,48 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifdef __OPENCV_BUILD -#error this is a compatibility header which should not be used inside the OpenCV library -#endif - -#include "opencv2/video.hpp" +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/video.hpp" diff --git a/3rdParty/opencv-4.11.0/opencv2/videoio.hpp b/3rdParty/opencv-4.11.0/opencv2/videoio.hpp index 6e50f87e44..9fc080c4cf 100644 --- a/3rdParty/opencv-4.11.0/opencv2/videoio.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/videoio.hpp @@ -1,1238 +1,1238 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_VIDEOIO_HPP -#define OPENCV_VIDEOIO_HPP - -#include "opencv2/core.hpp" - -/** - @defgroup videoio Video I/O - - @brief Read and write video or images sequence with OpenCV - - ### See also: - - @ref videoio_overview - - Tutorials: @ref tutorial_table_of_content_app - @{ - @defgroup videoio_flags_base Flags for video I/O - @defgroup videoio_flags_others Additional flags for video I/O API backends - @defgroup videoio_hwaccel Hardware-accelerated video decoding and encoding - @defgroup videoio_c C API for video I/O - @defgroup videoio_ios iOS glue for video I/O - @defgroup videoio_winrt WinRT glue for video I/O - @defgroup videoio_registry Query I/O API backends registry - @} -*/ - -////////////////////////////////// video io ///////////////////////////////// - -typedef struct CvCapture CvCapture; -typedef struct CvVideoWriter CvVideoWriter; - -namespace cv -{ - -//! @addtogroup videoio -//! @{ - -//! @addtogroup videoio_flags_base -//! @{ - - -/** @brief cv::VideoCapture API backends identifier. - -Select preferred API for a capture object. -To be used in the VideoCapture::VideoCapture() constructor or VideoCapture::open() - -@note -- Backends are available only if they have been built with your OpenCV binaries. -See @ref videoio_overview for more information. -- Microsoft Media Foundation backend tries to use hardware accelerated transformations -if possible. Environment flag "OPENCV_VIDEOIO_MSMF_ENABLE_HW_TRANSFORMS" set to 0 -disables it and may improve initialization time. More details: -https://learn.microsoft.com/en-us/windows/win32/medfound/mf-readwrite-enable-hardware-transforms -*/ -enum VideoCaptureAPIs { - CAP_ANY = 0, //!< Auto detect == 0 - CAP_VFW = 200, //!< Video For Windows (obsolete, removed) - CAP_V4L = 200, //!< V4L/V4L2 capturing support - CAP_V4L2 = CAP_V4L, //!< Same as CAP_V4L - CAP_FIREWIRE = 300, //!< IEEE 1394 drivers - CAP_FIREWARE = CAP_FIREWIRE, //!< Same value as CAP_FIREWIRE - CAP_IEEE1394 = CAP_FIREWIRE, //!< Same value as CAP_FIREWIRE - CAP_DC1394 = CAP_FIREWIRE, //!< Same value as CAP_FIREWIRE - CAP_CMU1394 = CAP_FIREWIRE, //!< Same value as CAP_FIREWIRE - CAP_QT = 500, //!< QuickTime (obsolete, removed) - CAP_UNICAP = 600, //!< Unicap drivers (obsolete, removed) - CAP_DSHOW = 700, //!< DirectShow (via videoInput) - CAP_PVAPI = 800, //!< PvAPI, Prosilica GigE SDK - CAP_OPENNI = 900, //!< OpenNI (for Kinect) - CAP_OPENNI_ASUS = 910, //!< OpenNI (for Asus Xtion) - CAP_ANDROID = 1000, //!< MediaNDK (API Level 21+) and NDK Camera (API level 24+) for Android - CAP_XIAPI = 1100, //!< XIMEA Camera API - CAP_AVFOUNDATION = 1200, //!< AVFoundation framework for iOS (OS X Lion will have the same API) - CAP_GIGANETIX = 1300, //!< Smartek Giganetix GigEVisionSDK - CAP_MSMF = 1400, //!< Microsoft Media Foundation (via videoInput). See platform specific notes above. - CAP_WINRT = 1410, //!< Microsoft Windows Runtime using Media Foundation - CAP_INTELPERC = 1500, //!< RealSense (former Intel Perceptual Computing SDK) - CAP_REALSENSE = 1500, //!< Synonym for CAP_INTELPERC - CAP_OPENNI2 = 1600, //!< OpenNI2 (for Kinect) - CAP_OPENNI2_ASUS = 1610, //!< OpenNI2 (for Asus Xtion and Occipital Structure sensors) - CAP_OPENNI2_ASTRA= 1620, //!< OpenNI2 (for Orbbec Astra) - CAP_GPHOTO2 = 1700, //!< gPhoto2 connection - CAP_GSTREAMER = 1800, //!< GStreamer - CAP_FFMPEG = 1900, //!< Open and record video file or stream using the FFMPEG library - CAP_IMAGES = 2000, //!< OpenCV Image Sequence (e.g. img_%02d.jpg) - CAP_ARAVIS = 2100, //!< Aravis SDK - CAP_OPENCV_MJPEG = 2200, //!< Built-in OpenCV MotionJPEG codec - CAP_INTEL_MFX = 2300, //!< Intel MediaSDK - CAP_XINE = 2400, //!< XINE engine (Linux) - CAP_UEYE = 2500, //!< uEye Camera API - CAP_OBSENSOR = 2600, //!< For Orbbec 3D-Sensor device/module (Astra+, Femto, Astra2, Gemini2, Gemini2L, Gemini2XL, Femto Mega) attention: Astra2 cameras currently only support Windows and Linux kernel versions no higher than 4.15, and higher versions of Linux kernel may have exceptions. - }; - - -/** @brief cv::VideoCapture generic properties identifier. - - Reading / writing properties involves many layers. Some unexpected result might happens along this chain. - Effective behaviour depends from device hardware, driver and API Backend. - @sa videoio_flags_others, VideoCapture::get(), VideoCapture::set() -*/ -enum VideoCaptureProperties { - CAP_PROP_POS_MSEC =0, //!< Current position of the video file in milliseconds. - CAP_PROP_POS_FRAMES =1, //!< 0-based index of the frame to be decoded/captured next. When the index i is set in RAW mode (CAP_PROP_FORMAT == -1) this will seek to the key frame k, where k <= i. - CAP_PROP_POS_AVI_RATIO =2, //!< Relative position of the video file: 0=start of the film, 1=end of the film. - CAP_PROP_FRAME_WIDTH =3, //!< Width of the frames in the video stream. - CAP_PROP_FRAME_HEIGHT =4, //!< Height of the frames in the video stream. - CAP_PROP_FPS =5, //!< Frame rate. - CAP_PROP_FOURCC =6, //!< 4-character code of codec. see VideoWriter::fourcc . - CAP_PROP_FRAME_COUNT =7, //!< Number of frames in the video file. - CAP_PROP_FORMAT =8, //!< Format of the %Mat objects (see Mat::type()) returned by VideoCapture::retrieve(). - //!< Set value -1 to fetch undecoded RAW video streams (as Mat 8UC1). - CAP_PROP_MODE =9, //!< Backend-specific value indicating the current capture mode. - CAP_PROP_BRIGHTNESS =10, //!< Brightness of the image (only for those cameras that support). - CAP_PROP_CONTRAST =11, //!< Contrast of the image (only for cameras). - CAP_PROP_SATURATION =12, //!< Saturation of the image (only for cameras). - CAP_PROP_HUE =13, //!< Hue of the image (only for cameras). - CAP_PROP_GAIN =14, //!< Gain of the image (only for those cameras that support). - CAP_PROP_EXPOSURE =15, //!< Exposure (only for those cameras that support). - CAP_PROP_CONVERT_RGB =16, //!< Boolean flags indicating whether images should be converted to RGB.
- //!< *GStreamer note*: The flag is ignored in case if custom pipeline is used. It's user responsibility to interpret pipeline output. - CAP_PROP_WHITE_BALANCE_BLUE_U =17, //!< Currently unsupported. - CAP_PROP_RECTIFICATION =18, //!< Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend currently). - CAP_PROP_MONOCHROME =19, - CAP_PROP_SHARPNESS =20, - CAP_PROP_AUTO_EXPOSURE =21, //!< DC1394: exposure control done by camera, user can adjust reference level using this feature. - CAP_PROP_GAMMA =22, - CAP_PROP_TEMPERATURE =23, - CAP_PROP_TRIGGER =24, - CAP_PROP_TRIGGER_DELAY =25, - CAP_PROP_WHITE_BALANCE_RED_V =26, - CAP_PROP_ZOOM =27, - CAP_PROP_FOCUS =28, - CAP_PROP_GUID =29, - CAP_PROP_ISO_SPEED =30, - CAP_PROP_BACKLIGHT =32, - CAP_PROP_PAN =33, - CAP_PROP_TILT =34, - CAP_PROP_ROLL =35, - CAP_PROP_IRIS =36, - CAP_PROP_SETTINGS =37, //!< Pop up video/camera filter dialog (note: only supported by DSHOW backend currently. The property value is ignored) - CAP_PROP_BUFFERSIZE =38, - CAP_PROP_AUTOFOCUS =39, - CAP_PROP_SAR_NUM =40, //!< Sample aspect ratio: num/den (num) - CAP_PROP_SAR_DEN =41, //!< Sample aspect ratio: num/den (den) - CAP_PROP_BACKEND =42, //!< Current backend (enum VideoCaptureAPIs). Read-only property - CAP_PROP_CHANNEL =43, //!< Video input or Channel Number (only for those cameras that support) - CAP_PROP_AUTO_WB =44, //!< enable/ disable auto white-balance - CAP_PROP_WB_TEMPERATURE=45, //!< white-balance color temperature - CAP_PROP_CODEC_PIXEL_FORMAT =46, //!< (read-only) codec's pixel format. 4-character code - see VideoWriter::fourcc . Subset of [AV_PIX_FMT_*](https://github.com/FFmpeg/FFmpeg/blob/master/libavcodec/raw.c) or -1 if unknown - CAP_PROP_BITRATE =47, //!< (read-only) Video bitrate in kbits/s - CAP_PROP_ORIENTATION_META=48, //!< (read-only) Frame rotation defined by stream meta (applicable for FFmpeg and AVFoundation back-ends only) - CAP_PROP_ORIENTATION_AUTO=49, //!< if true - rotates output frames of CvCapture considering video file's metadata (applicable for FFmpeg and AVFoundation back-ends only) (https://github.com/opencv/opencv/issues/15499) - CAP_PROP_HW_ACCELERATION=50, //!< (**open-only**) Hardware acceleration type (see #VideoAccelerationType). Setting supported only via `params` parameter in cv::VideoCapture constructor / .open() method. Default value is backend-specific. - CAP_PROP_HW_DEVICE =51, //!< (**open-only**) Hardware device index (select GPU if multiple available). Device enumeration is acceleration type specific. - CAP_PROP_HW_ACCELERATION_USE_OPENCL=52, //!< (**open-only**) If non-zero, create new OpenCL context and bind it to current thread. The OpenCL context created with Video Acceleration context attached it (if not attached yet) for optimized GPU data copy between HW accelerated decoder and cv::UMat. - CAP_PROP_OPEN_TIMEOUT_MSEC=53, //!< (**open-only**) timeout in milliseconds for opening a video capture (applicable for FFmpeg and GStreamer back-ends only) - CAP_PROP_READ_TIMEOUT_MSEC=54, //!< (**open-only**) timeout in milliseconds for reading from a video capture (applicable for FFmpeg and GStreamer back-ends only) - CAP_PROP_STREAM_OPEN_TIME_USEC =55, //!< (read-only) time in microseconds since Jan 1 1970 when stream was opened. Applicable for FFmpeg backend only. Useful for RTSP and other live streams - CAP_PROP_VIDEO_TOTAL_CHANNELS = 56, //!< (read-only) Number of video channels - CAP_PROP_VIDEO_STREAM = 57, //!< (**open-only**) Specify video stream, 0-based index. Use -1 to disable video stream from file or IP cameras. Default value is 0. - CAP_PROP_AUDIO_STREAM = 58, //!< (**open-only**) Specify stream in multi-language media files, -1 - disable audio processing or microphone. Default value is -1. - CAP_PROP_AUDIO_POS = 59, //!< (read-only) Audio position is measured in samples. Accurate audio sample timestamp of previous grabbed fragment. See CAP_PROP_AUDIO_SAMPLES_PER_SECOND and CAP_PROP_AUDIO_SHIFT_NSEC. - CAP_PROP_AUDIO_SHIFT_NSEC = 60, //!< (read only) Contains the time difference between the start of the audio stream and the video stream in nanoseconds. Positive value means that audio is started after the first video frame. Negative value means that audio is started before the first video frame. - CAP_PROP_AUDIO_DATA_DEPTH = 61, //!< (open, read) Alternative definition to bits-per-sample, but with clear handling of 32F / 32S - CAP_PROP_AUDIO_SAMPLES_PER_SECOND = 62, //!< (open, read) determined from file/codec input. If not specified, then selected audio sample rate is 44100 - CAP_PROP_AUDIO_BASE_INDEX = 63, //!< (read-only) Index of the first audio channel for .retrieve() calls. That audio channel number continues enumeration after video channels. - CAP_PROP_AUDIO_TOTAL_CHANNELS = 64, //!< (read-only) Number of audio channels in the selected audio stream (mono, stereo, etc) - CAP_PROP_AUDIO_TOTAL_STREAMS = 65, //!< (read-only) Number of audio streams. - CAP_PROP_AUDIO_SYNCHRONIZE = 66, //!< (open, read) Enables audio synchronization. - CAP_PROP_LRF_HAS_KEY_FRAME = 67, //!< FFmpeg back-end only - Indicates whether the Last Raw Frame (LRF), output from VideoCapture::read() when VideoCapture is initialized with VideoCapture::open(CAP_FFMPEG, {CAP_PROP_FORMAT, -1}) or VideoCapture::set(CAP_PROP_FORMAT,-1) is called before the first call to VideoCapture::read(), contains encoded data for a key frame. - CAP_PROP_CODEC_EXTRADATA_INDEX = 68, //!< Positive index indicates that returning extra data is supported by the video back end. This can be retrieved as cap.retrieve(data, ). E.g. When reading from a h264 encoded RTSP stream, the FFmpeg backend could return the SPS and/or PPS if available (if sent in reply to a DESCRIBE request), from calls to cap.retrieve(data, ). - CAP_PROP_FRAME_TYPE = 69, //!< (read-only) FFmpeg back-end only - Frame type ascii code (73 = 'I', 80 = 'P', 66 = 'B' or 63 = '?' if unknown) of the most recently read frame. - CAP_PROP_N_THREADS = 70, //!< (**open-only**) Set the maximum number of threads to use. Use 0 to use as many threads as CPU cores (applicable for FFmpeg back-end only). - CAP_PROP_PTS = 71, //!< (read-only) FFmpeg back-end only - presentation timestamp of the most recently read frame using the FPS time base. e.g. fps = 25, VideoCapture::get(\ref CAP_PROP_PTS) = 3, presentation time = 3/25 seconds. - CAP_PROP_DTS_DELAY = 72, //!< (read-only) FFmpeg back-end only - maximum difference between presentation (pts) and decompression timestamps (dts) using FPS time base. e.g. delay is maximum when frame_num = 0, if true, VideoCapture::get(\ref CAP_PROP_PTS) = 0 and VideoCapture::get(\ref CAP_PROP_DTS_DELAY) = 2, dts = -2. Non zero values usually imply the stream is encoded using B-frames which are not decoded in presentation order. -#ifndef CV_DOXYGEN - CV__CAP_PROP_LATEST -#endif - }; - -/** @brief cv::VideoWriter generic properties identifier. - @sa VideoWriter::get(), VideoWriter::set() -*/ -enum VideoWriterProperties { - VIDEOWRITER_PROP_QUALITY = 1, //!< Current quality (0..100%) of the encoded videostream. Can be adjusted dynamically in some codecs. - VIDEOWRITER_PROP_FRAMEBYTES = 2, //!< (Read-only): Size of just encoded video frame. Note that the encoding order may be different from representation order. - VIDEOWRITER_PROP_NSTRIPES = 3, //!< Number of stripes for parallel encoding. -1 for auto detection. - VIDEOWRITER_PROP_IS_COLOR = 4, //!< If it is not zero, the encoder will expect and encode color frames, otherwise it - //!< will work with grayscale frames. - VIDEOWRITER_PROP_DEPTH = 5, //!< Defaults to \ref CV_8U. - VIDEOWRITER_PROP_HW_ACCELERATION = 6, //!< (**open-only**) Hardware acceleration type (see #VideoAccelerationType). Setting supported only via `params` parameter in VideoWriter constructor / .open() method. Default value is backend-specific. - VIDEOWRITER_PROP_HW_DEVICE = 7, //!< (**open-only**) Hardware device index (select GPU if multiple available). Device enumeration is acceleration type specific. - VIDEOWRITER_PROP_HW_ACCELERATION_USE_OPENCL= 8, //!< (**open-only**) If non-zero, create new OpenCL context and bind it to current thread. The OpenCL context created with Video Acceleration context attached it (if not attached yet) for optimized GPU data copy between cv::UMat and HW accelerated encoder. - VIDEOWRITER_PROP_RAW_VIDEO = 9, //!< (**open-only**) Set to non-zero to enable encapsulation of an encoded raw video stream. Each raw encoded video frame should be passed to VideoWriter::write() as single row or column of a \ref CV_8UC1 Mat. \note If the key frame interval is not 1 then it must be manually specified by the user. This can either be performed during initialization passing \ref VIDEOWRITER_PROP_KEY_INTERVAL as one of the extra encoder params to \ref VideoWriter::VideoWriter(const String &, int, double, const Size &, const std::vector< int > ¶ms) or afterwards by setting the \ref VIDEOWRITER_PROP_KEY_FLAG with \ref VideoWriter::set() before writing each frame. FFMpeg backend only. - VIDEOWRITER_PROP_KEY_INTERVAL = 10, //!< (**open-only**) Set the key frame interval using raw video encapsulation (\ref VIDEOWRITER_PROP_RAW_VIDEO != 0). Defaults to 1 when not set. FFmpeg back-end only. - VIDEOWRITER_PROP_KEY_FLAG = 11, //!< Set to non-zero to signal that the following frames are key frames or zero if not, when encapsulating raw video (\ref VIDEOWRITER_PROP_RAW_VIDEO != 0). FFmpeg back-end only. - VIDEOWRITER_PROP_PTS = 12, //!< Specifies the frame presentation timestamp for each frame using the FPS time base. This property is **only** necessary when encapsulating **externally** encoded video where the decoding order differs from the presentation order, such as in GOP patterns with bi-directional B-frames. The value should be provided by your external encoder and for video sources with fixed frame rates it is equivalent to dividing the current frame's presentation time (\ref CAP_PROP_POS_MSEC) by the frame duration (1000.0 / VideoCapture::get(\ref CAP_PROP_FPS)). It can be queried from the resulting encapsulated video file using VideoCapture::get(\ref CAP_PROP_PTS). FFmpeg back-end only. - VIDEOWRITER_PROP_DTS_DELAY = 13, //!< Specifies the maximum difference between presentation (pts) and decompression timestamps (dts) using the FPS time base. This property is necessary **only** when encapsulating **externally** encoded video where the decoding order differs from the presentation order, such as in GOP patterns with bi-directional B-frames. The value should be calculated based on the specific GOP pattern used during encoding. For example, in a GOP with presentation order IBP and decoding order IPB, this value would be 1, as the B-frame is the second frame presented but the third to be decoded. It can be queried from the resulting encapsulated video file using VideoCapture::get(\ref CAP_PROP_DTS_DELAY). Non-zero values usually imply the stream is encoded using B-frames. FFmpeg back-end only. -#ifndef CV_DOXYGEN - CV__VIDEOWRITER_PROP_LATEST -#endif -}; - -//! @} videoio_flags_base - -//! @addtogroup videoio_flags_others -//! @{ - -/** @name Hardware acceleration support - @{ -*/ - -/** @brief Video Acceleration type - * - * Used as value in #CAP_PROP_HW_ACCELERATION and #VIDEOWRITER_PROP_HW_ACCELERATION - * - * @note In case of FFmpeg backend, it translated to enum AVHWDeviceType (https://github.com/FFmpeg/FFmpeg/blob/master/libavutil/hwcontext.h) - */ -enum VideoAccelerationType -{ - VIDEO_ACCELERATION_NONE = 0, //!< Do not require any specific H/W acceleration, prefer software processing. - //!< Reading of this value means that special H/W accelerated handling is not added or not detected by OpenCV. - - VIDEO_ACCELERATION_ANY = 1, //!< Prefer to use H/W acceleration. If no one supported, then fallback to software processing. - //!< @note H/W acceleration may require special configuration of used environment. - //!< @note Results in encoding scenario may differ between software and hardware accelerated encoders. - - VIDEO_ACCELERATION_D3D11 = 2, //!< DirectX 11 - VIDEO_ACCELERATION_VAAPI = 3, //!< VAAPI - VIDEO_ACCELERATION_MFX = 4, //!< libmfx (Intel MediaSDK/oneVPL) -}; - -//! @} Hardware acceleration support - -/** @name IEEE 1394 drivers - @{ -*/ - -/** @brief Modes of the IEEE 1394 controlling registers -(can be: auto, manual, auto single push, absolute Latter allowed with any other mode) -every feature can have only one mode turned on at a time -*/ -enum { CAP_PROP_DC1394_OFF = -4, //!< turn the feature off (not controlled manually nor automatically). - CAP_PROP_DC1394_MODE_MANUAL = -3, //!< set automatically when a value of the feature is set by the user. - CAP_PROP_DC1394_MODE_AUTO = -2, - CAP_PROP_DC1394_MODE_ONE_PUSH_AUTO = -1, - CAP_PROP_DC1394_MAX = 31 - }; - -//! @} IEEE 1394 drivers - -/** @name OpenNI (for Kinect) - @{ -*/ - -//! OpenNI map generators -enum { CAP_OPENNI_DEPTH_GENERATOR = 1 << 31, - CAP_OPENNI_IMAGE_GENERATOR = 1 << 30, - CAP_OPENNI_IR_GENERATOR = 1 << 29, - CAP_OPENNI_GENERATORS_MASK = CAP_OPENNI_DEPTH_GENERATOR + CAP_OPENNI_IMAGE_GENERATOR + CAP_OPENNI_IR_GENERATOR - }; - -//! Properties of cameras available through OpenNI backend -enum { CAP_PROP_OPENNI_OUTPUT_MODE = 100, - CAP_PROP_OPENNI_FRAME_MAX_DEPTH = 101, //!< In mm - CAP_PROP_OPENNI_BASELINE = 102, //!< In mm - CAP_PROP_OPENNI_FOCAL_LENGTH = 103, //!< In pixels - CAP_PROP_OPENNI_REGISTRATION = 104, //!< Flag that synchronizes the remapping depth map to image map - //!< by changing depth generator's view point (if the flag is "on") or - //!< sets this view point to its normal one (if the flag is "off"). - CAP_PROP_OPENNI_REGISTRATION_ON = CAP_PROP_OPENNI_REGISTRATION, - CAP_PROP_OPENNI_APPROX_FRAME_SYNC = 105, - CAP_PROP_OPENNI_MAX_BUFFER_SIZE = 106, - CAP_PROP_OPENNI_CIRCLE_BUFFER = 107, - CAP_PROP_OPENNI_MAX_TIME_DURATION = 108, - CAP_PROP_OPENNI_GENERATOR_PRESENT = 109, - CAP_PROP_OPENNI2_SYNC = 110, - CAP_PROP_OPENNI2_MIRROR = 111 - }; - -#ifdef _MSC_VER -#pragma warning( push ) -#pragma warning( disable: 5054 ) -#endif -//! OpenNI shortcuts -enum { CAP_OPENNI_IMAGE_GENERATOR_PRESENT = +CAP_OPENNI_IMAGE_GENERATOR + CAP_PROP_OPENNI_GENERATOR_PRESENT, - CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE = +CAP_OPENNI_IMAGE_GENERATOR + CAP_PROP_OPENNI_OUTPUT_MODE, - CAP_OPENNI_DEPTH_GENERATOR_PRESENT = +CAP_OPENNI_DEPTH_GENERATOR + CAP_PROP_OPENNI_GENERATOR_PRESENT, - CAP_OPENNI_DEPTH_GENERATOR_BASELINE = +CAP_OPENNI_DEPTH_GENERATOR + CAP_PROP_OPENNI_BASELINE, - CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH = +CAP_OPENNI_DEPTH_GENERATOR + CAP_PROP_OPENNI_FOCAL_LENGTH, - CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION = +CAP_OPENNI_DEPTH_GENERATOR + CAP_PROP_OPENNI_REGISTRATION, - CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION_ON = CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION, - CAP_OPENNI_IR_GENERATOR_PRESENT = +CAP_OPENNI_IR_GENERATOR + CAP_PROP_OPENNI_GENERATOR_PRESENT - }; -#ifdef _MSC_VER -#pragma warning( pop ) -#endif - -//! OpenNI data given from depth generator -enum { CAP_OPENNI_DEPTH_MAP = 0, //!< Depth values in mm (CV_16UC1) - CAP_OPENNI_POINT_CLOUD_MAP = 1, //!< XYZ in meters (CV_32FC3) - CAP_OPENNI_DISPARITY_MAP = 2, //!< Disparity in pixels (CV_8UC1) - CAP_OPENNI_DISPARITY_MAP_32F = 3, //!< Disparity in pixels (CV_32FC1) - CAP_OPENNI_VALID_DEPTH_MASK = 4, //!< CV_8UC1 - - CAP_OPENNI_BGR_IMAGE = 5, //!< Data given from RGB image generator - CAP_OPENNI_GRAY_IMAGE = 6, //!< Data given from RGB image generator - - CAP_OPENNI_IR_IMAGE = 7 //!< Data given from IR image generator - }; - -//! Supported output modes of OpenNI image generator -enum { CAP_OPENNI_VGA_30HZ = 0, - CAP_OPENNI_SXGA_15HZ = 1, - CAP_OPENNI_SXGA_30HZ = 2, - CAP_OPENNI_QVGA_30HZ = 3, - CAP_OPENNI_QVGA_60HZ = 4 - }; - -//! @} OpenNI - -/** @name GStreamer - @{ -*/ - -enum { CAP_PROP_GSTREAMER_QUEUE_LENGTH = 200 //!< Default is 1 - }; - -//! @} GStreamer - -/** @name PvAPI, Prosilica GigE SDK - @{ -*/ - -//! PVAPI -enum { CAP_PROP_PVAPI_MULTICASTIP = 300, //!< IP for enable multicast master mode. 0 for disable multicast. - CAP_PROP_PVAPI_FRAMESTARTTRIGGERMODE = 301, //!< FrameStartTriggerMode: Determines how a frame is initiated. - CAP_PROP_PVAPI_DECIMATIONHORIZONTAL = 302, //!< Horizontal sub-sampling of the image. - CAP_PROP_PVAPI_DECIMATIONVERTICAL = 303, //!< Vertical sub-sampling of the image. - CAP_PROP_PVAPI_BINNINGX = 304, //!< Horizontal binning factor. - CAP_PROP_PVAPI_BINNINGY = 305, //!< Vertical binning factor. - CAP_PROP_PVAPI_PIXELFORMAT = 306 //!< Pixel format. - }; - -//! PVAPI: FrameStartTriggerMode -enum { CAP_PVAPI_FSTRIGMODE_FREERUN = 0, //!< Freerun - CAP_PVAPI_FSTRIGMODE_SYNCIN1 = 1, //!< SyncIn1 - CAP_PVAPI_FSTRIGMODE_SYNCIN2 = 2, //!< SyncIn2 - CAP_PVAPI_FSTRIGMODE_FIXEDRATE = 3, //!< FixedRate - CAP_PVAPI_FSTRIGMODE_SOFTWARE = 4 //!< Software - }; - -//! PVAPI: DecimationHorizontal, DecimationVertical -enum { CAP_PVAPI_DECIMATION_OFF = 1, //!< Off - CAP_PVAPI_DECIMATION_2OUTOF4 = 2, //!< 2 out of 4 decimation - CAP_PVAPI_DECIMATION_2OUTOF8 = 4, //!< 2 out of 8 decimation - CAP_PVAPI_DECIMATION_2OUTOF16 = 8 //!< 2 out of 16 decimation - }; - -//! PVAPI: PixelFormat -enum { CAP_PVAPI_PIXELFORMAT_MONO8 = 1, //!< Mono8 - CAP_PVAPI_PIXELFORMAT_MONO16 = 2, //!< Mono16 - CAP_PVAPI_PIXELFORMAT_BAYER8 = 3, //!< Bayer8 - CAP_PVAPI_PIXELFORMAT_BAYER16 = 4, //!< Bayer16 - CAP_PVAPI_PIXELFORMAT_RGB24 = 5, //!< Rgb24 - CAP_PVAPI_PIXELFORMAT_BGR24 = 6, //!< Bgr24 - CAP_PVAPI_PIXELFORMAT_RGBA32 = 7, //!< Rgba32 - CAP_PVAPI_PIXELFORMAT_BGRA32 = 8, //!< Bgra32 - }; - -//! @} PvAPI - -/** @name XIMEA Camera API - @{ -*/ - -//! Properties of cameras available through XIMEA SDK backend -enum { CAP_PROP_XI_DOWNSAMPLING = 400, //!< Change image resolution by binning or skipping. - CAP_PROP_XI_DATA_FORMAT = 401, //!< Output data format. - CAP_PROP_XI_OFFSET_X = 402, //!< Horizontal offset from the origin to the area of interest (in pixels). - CAP_PROP_XI_OFFSET_Y = 403, //!< Vertical offset from the origin to the area of interest (in pixels). - CAP_PROP_XI_TRG_SOURCE = 404, //!< Defines source of trigger. - CAP_PROP_XI_TRG_SOFTWARE = 405, //!< Generates an internal trigger. PRM_TRG_SOURCE must be set to TRG_SOFTWARE. - CAP_PROP_XI_GPI_SELECTOR = 406, //!< Selects general purpose input. - CAP_PROP_XI_GPI_MODE = 407, //!< Set general purpose input mode. - CAP_PROP_XI_GPI_LEVEL = 408, //!< Get general purpose level. - CAP_PROP_XI_GPO_SELECTOR = 409, //!< Selects general purpose output. - CAP_PROP_XI_GPO_MODE = 410, //!< Set general purpose output mode. - CAP_PROP_XI_LED_SELECTOR = 411, //!< Selects camera signalling LED. - CAP_PROP_XI_LED_MODE = 412, //!< Define camera signalling LED functionality. - CAP_PROP_XI_MANUAL_WB = 413, //!< Calculates White Balance(must be called during acquisition). - CAP_PROP_XI_AUTO_WB = 414, //!< Automatic white balance. - CAP_PROP_XI_AEAG = 415, //!< Automatic exposure/gain. - CAP_PROP_XI_EXP_PRIORITY = 416, //!< Exposure priority (0.5 - exposure 50%, gain 50%). - CAP_PROP_XI_AE_MAX_LIMIT = 417, //!< Maximum limit of exposure in AEAG procedure. - CAP_PROP_XI_AG_MAX_LIMIT = 418, //!< Maximum limit of gain in AEAG procedure. - CAP_PROP_XI_AEAG_LEVEL = 419, //!< Average intensity of output signal AEAG should achieve(in %). - CAP_PROP_XI_TIMEOUT = 420, //!< Image capture timeout in milliseconds. - CAP_PROP_XI_EXPOSURE = 421, //!< Exposure time in microseconds. - CAP_PROP_XI_EXPOSURE_BURST_COUNT = 422, //!< Sets the number of times of exposure in one frame. - CAP_PROP_XI_GAIN_SELECTOR = 423, //!< Gain selector for parameter Gain allows to select different type of gains. - CAP_PROP_XI_GAIN = 424, //!< Gain in dB. - CAP_PROP_XI_DOWNSAMPLING_TYPE = 426, //!< Change image downsampling type. - CAP_PROP_XI_BINNING_SELECTOR = 427, //!< Binning engine selector. - CAP_PROP_XI_BINNING_VERTICAL = 428, //!< Vertical Binning - number of vertical photo-sensitive cells to combine together. - CAP_PROP_XI_BINNING_HORIZONTAL = 429, //!< Horizontal Binning - number of horizontal photo-sensitive cells to combine together. - CAP_PROP_XI_BINNING_PATTERN = 430, //!< Binning pattern type. - CAP_PROP_XI_DECIMATION_SELECTOR = 431, //!< Decimation engine selector. - CAP_PROP_XI_DECIMATION_VERTICAL = 432, //!< Vertical Decimation - vertical sub-sampling of the image - reduces the vertical resolution of the image by the specified vertical decimation factor. - CAP_PROP_XI_DECIMATION_HORIZONTAL = 433, //!< Horizontal Decimation - horizontal sub-sampling of the image - reduces the horizontal resolution of the image by the specified vertical decimation factor. - CAP_PROP_XI_DECIMATION_PATTERN = 434, //!< Decimation pattern type. - CAP_PROP_XI_TEST_PATTERN_GENERATOR_SELECTOR = 587, //!< Selects which test pattern generator is controlled by the TestPattern feature. - CAP_PROP_XI_TEST_PATTERN = 588, //!< Selects which test pattern type is generated by the selected generator. - CAP_PROP_XI_IMAGE_DATA_FORMAT = 435, //!< Output data format. - CAP_PROP_XI_SHUTTER_TYPE = 436, //!< Change sensor shutter type(CMOS sensor). - CAP_PROP_XI_SENSOR_TAPS = 437, //!< Number of taps. - CAP_PROP_XI_AEAG_ROI_OFFSET_X = 439, //!< Automatic exposure/gain ROI offset X. - CAP_PROP_XI_AEAG_ROI_OFFSET_Y = 440, //!< Automatic exposure/gain ROI offset Y. - CAP_PROP_XI_AEAG_ROI_WIDTH = 441, //!< Automatic exposure/gain ROI Width. - CAP_PROP_XI_AEAG_ROI_HEIGHT = 442, //!< Automatic exposure/gain ROI Height. - CAP_PROP_XI_BPC = 445, //!< Correction of bad pixels. - CAP_PROP_XI_WB_KR = 448, //!< White balance red coefficient. - CAP_PROP_XI_WB_KG = 449, //!< White balance green coefficient. - CAP_PROP_XI_WB_KB = 450, //!< White balance blue coefficient. - CAP_PROP_XI_WIDTH = 451, //!< Width of the Image provided by the device (in pixels). - CAP_PROP_XI_HEIGHT = 452, //!< Height of the Image provided by the device (in pixels). - CAP_PROP_XI_REGION_SELECTOR = 589, //!< Selects Region in Multiple ROI which parameters are set by width, height, ... ,region mode. - CAP_PROP_XI_REGION_MODE = 595, //!< Activates/deactivates Region selected by Region Selector. - CAP_PROP_XI_LIMIT_BANDWIDTH = 459, //!< Set/get bandwidth(datarate)(in Megabits). - CAP_PROP_XI_SENSOR_DATA_BIT_DEPTH = 460, //!< Sensor output data bit depth. - CAP_PROP_XI_OUTPUT_DATA_BIT_DEPTH = 461, //!< Device output data bit depth. - CAP_PROP_XI_IMAGE_DATA_BIT_DEPTH = 462, //!< bitdepth of data returned by function xiGetImage. - CAP_PROP_XI_OUTPUT_DATA_PACKING = 463, //!< Device output data packing (or grouping) enabled. Packing could be enabled if output_data_bit_depth > 8 and packing capability is available. - CAP_PROP_XI_OUTPUT_DATA_PACKING_TYPE = 464, //!< Data packing type. Some cameras supports only specific packing type. - CAP_PROP_XI_IS_COOLED = 465, //!< Returns 1 for cameras that support cooling. - CAP_PROP_XI_COOLING = 466, //!< Start camera cooling. - CAP_PROP_XI_TARGET_TEMP = 467, //!< Set sensor target temperature for cooling. - CAP_PROP_XI_CHIP_TEMP = 468, //!< Camera sensor temperature. - CAP_PROP_XI_HOUS_TEMP = 469, //!< Camera housing temperature. - CAP_PROP_XI_HOUS_BACK_SIDE_TEMP = 590, //!< Camera housing back side temperature. - CAP_PROP_XI_SENSOR_BOARD_TEMP = 596, //!< Camera sensor board temperature. - CAP_PROP_XI_CMS = 470, //!< Mode of color management system. - CAP_PROP_XI_APPLY_CMS = 471, //!< Enable applying of CMS profiles to xiGetImage (see XI_PRM_INPUT_CMS_PROFILE, XI_PRM_OUTPUT_CMS_PROFILE). - CAP_PROP_XI_IMAGE_IS_COLOR = 474, //!< Returns 1 for color cameras. - CAP_PROP_XI_COLOR_FILTER_ARRAY = 475, //!< Returns color filter array type of RAW data. - CAP_PROP_XI_GAMMAY = 476, //!< Luminosity gamma. - CAP_PROP_XI_GAMMAC = 477, //!< Chromaticity gamma. - CAP_PROP_XI_SHARPNESS = 478, //!< Sharpness Strength. - CAP_PROP_XI_CC_MATRIX_00 = 479, //!< Color Correction Matrix element [0][0]. - CAP_PROP_XI_CC_MATRIX_01 = 480, //!< Color Correction Matrix element [0][1]. - CAP_PROP_XI_CC_MATRIX_02 = 481, //!< Color Correction Matrix element [0][2]. - CAP_PROP_XI_CC_MATRIX_03 = 482, //!< Color Correction Matrix element [0][3]. - CAP_PROP_XI_CC_MATRIX_10 = 483, //!< Color Correction Matrix element [1][0]. - CAP_PROP_XI_CC_MATRIX_11 = 484, //!< Color Correction Matrix element [1][1]. - CAP_PROP_XI_CC_MATRIX_12 = 485, //!< Color Correction Matrix element [1][2]. - CAP_PROP_XI_CC_MATRIX_13 = 486, //!< Color Correction Matrix element [1][3]. - CAP_PROP_XI_CC_MATRIX_20 = 487, //!< Color Correction Matrix element [2][0]. - CAP_PROP_XI_CC_MATRIX_21 = 488, //!< Color Correction Matrix element [2][1]. - CAP_PROP_XI_CC_MATRIX_22 = 489, //!< Color Correction Matrix element [2][2]. - CAP_PROP_XI_CC_MATRIX_23 = 490, //!< Color Correction Matrix element [2][3]. - CAP_PROP_XI_CC_MATRIX_30 = 491, //!< Color Correction Matrix element [3][0]. - CAP_PROP_XI_CC_MATRIX_31 = 492, //!< Color Correction Matrix element [3][1]. - CAP_PROP_XI_CC_MATRIX_32 = 493, //!< Color Correction Matrix element [3][2]. - CAP_PROP_XI_CC_MATRIX_33 = 494, //!< Color Correction Matrix element [3][3]. - CAP_PROP_XI_DEFAULT_CC_MATRIX = 495, //!< Set default Color Correction Matrix. - CAP_PROP_XI_TRG_SELECTOR = 498, //!< Selects the type of trigger. - CAP_PROP_XI_ACQ_FRAME_BURST_COUNT = 499, //!< Sets number of frames acquired by burst. This burst is used only if trigger is set to FrameBurstStart. - CAP_PROP_XI_DEBOUNCE_EN = 507, //!< Enable/Disable debounce to selected GPI. - CAP_PROP_XI_DEBOUNCE_T0 = 508, //!< Debounce time (x * 10us). - CAP_PROP_XI_DEBOUNCE_T1 = 509, //!< Debounce time (x * 10us). - CAP_PROP_XI_DEBOUNCE_POL = 510, //!< Debounce polarity (pol = 1 t0 - falling edge, t1 - rising edge). - CAP_PROP_XI_LENS_MODE = 511, //!< Status of lens control interface. This shall be set to XI_ON before any Lens operations. - CAP_PROP_XI_LENS_APERTURE_VALUE = 512, //!< Current lens aperture value in stops. Examples: 2.8, 4, 5.6, 8, 11. - CAP_PROP_XI_LENS_FOCUS_MOVEMENT_VALUE = 513, //!< Lens current focus movement value to be used by XI_PRM_LENS_FOCUS_MOVE in motor steps. - CAP_PROP_XI_LENS_FOCUS_MOVE = 514, //!< Moves lens focus motor by steps set in XI_PRM_LENS_FOCUS_MOVEMENT_VALUE. - CAP_PROP_XI_LENS_FOCUS_DISTANCE = 515, //!< Lens focus distance in cm. - CAP_PROP_XI_LENS_FOCAL_LENGTH = 516, //!< Lens focal distance in mm. - CAP_PROP_XI_LENS_FEATURE_SELECTOR = 517, //!< Selects the current feature which is accessible by XI_PRM_LENS_FEATURE. - CAP_PROP_XI_LENS_FEATURE = 518, //!< Allows access to lens feature value currently selected by XI_PRM_LENS_FEATURE_SELECTOR. - CAP_PROP_XI_DEVICE_MODEL_ID = 521, //!< Returns device model id. - CAP_PROP_XI_DEVICE_SN = 522, //!< Returns device serial number. - CAP_PROP_XI_IMAGE_DATA_FORMAT_RGB32_ALPHA = 529, //!< The alpha channel of RGB32 output image format. - CAP_PROP_XI_IMAGE_PAYLOAD_SIZE = 530, //!< Buffer size in bytes sufficient for output image returned by xiGetImage. - CAP_PROP_XI_TRANSPORT_PIXEL_FORMAT = 531, //!< Current format of pixels on transport layer. - CAP_PROP_XI_SENSOR_CLOCK_FREQ_HZ = 532, //!< Sensor clock frequency in Hz. - CAP_PROP_XI_SENSOR_CLOCK_FREQ_INDEX = 533, //!< Sensor clock frequency index. Sensor with selected frequencies have possibility to set the frequency only by this index. - CAP_PROP_XI_SENSOR_OUTPUT_CHANNEL_COUNT = 534, //!< Number of output channels from sensor used for data transfer. - CAP_PROP_XI_FRAMERATE = 535, //!< Define framerate in Hz. - CAP_PROP_XI_COUNTER_SELECTOR = 536, //!< Select counter. - CAP_PROP_XI_COUNTER_VALUE = 537, //!< Counter status. - CAP_PROP_XI_ACQ_TIMING_MODE = 538, //!< Type of sensor frames timing. - CAP_PROP_XI_AVAILABLE_BANDWIDTH = 539, //!< Calculate and returns available interface bandwidth(int Megabits). - CAP_PROP_XI_BUFFER_POLICY = 540, //!< Data move policy. - CAP_PROP_XI_LUT_EN = 541, //!< Activates LUT. - CAP_PROP_XI_LUT_INDEX = 542, //!< Control the index (offset) of the coefficient to access in the LUT. - CAP_PROP_XI_LUT_VALUE = 543, //!< Value at entry LUTIndex of the LUT. - CAP_PROP_XI_TRG_DELAY = 544, //!< Specifies the delay in microseconds (us) to apply after the trigger reception before activating it. - CAP_PROP_XI_TS_RST_MODE = 545, //!< Defines how time stamp reset engine will be armed. - CAP_PROP_XI_TS_RST_SOURCE = 546, //!< Defines which source will be used for timestamp reset. Writing this parameter will trigger settings of engine (arming). - CAP_PROP_XI_IS_DEVICE_EXIST = 547, //!< Returns 1 if camera connected and works properly. - CAP_PROP_XI_ACQ_BUFFER_SIZE = 548, //!< Acquisition buffer size in buffer_size_unit. Default bytes. - CAP_PROP_XI_ACQ_BUFFER_SIZE_UNIT = 549, //!< Acquisition buffer size unit in bytes. Default 1. E.g. Value 1024 means that buffer_size is in KiBytes. - CAP_PROP_XI_ACQ_TRANSPORT_BUFFER_SIZE = 550, //!< Acquisition transport buffer size in bytes. - CAP_PROP_XI_BUFFERS_QUEUE_SIZE = 551, //!< Queue of field/frame buffers. - CAP_PROP_XI_ACQ_TRANSPORT_BUFFER_COMMIT = 552, //!< Number of buffers to commit to low level. - CAP_PROP_XI_RECENT_FRAME = 553, //!< GetImage returns most recent frame. - CAP_PROP_XI_DEVICE_RESET = 554, //!< Resets the camera to default state. - CAP_PROP_XI_COLUMN_FPN_CORRECTION = 555, //!< Correction of column FPN. - CAP_PROP_XI_ROW_FPN_CORRECTION = 591, //!< Correction of row FPN. - CAP_PROP_XI_SENSOR_MODE = 558, //!< Current sensor mode. Allows to select sensor mode by one integer. Setting of this parameter affects: image dimensions and downsampling. - CAP_PROP_XI_HDR = 559, //!< Enable High Dynamic Range feature. - CAP_PROP_XI_HDR_KNEEPOINT_COUNT = 560, //!< The number of kneepoints in the PWLR. - CAP_PROP_XI_HDR_T1 = 561, //!< Position of first kneepoint(in % of XI_PRM_EXPOSURE). - CAP_PROP_XI_HDR_T2 = 562, //!< Position of second kneepoint (in % of XI_PRM_EXPOSURE). - CAP_PROP_XI_KNEEPOINT1 = 563, //!< Value of first kneepoint (% of sensor saturation). - CAP_PROP_XI_KNEEPOINT2 = 564, //!< Value of second kneepoint (% of sensor saturation). - CAP_PROP_XI_IMAGE_BLACK_LEVEL = 565, //!< Last image black level counts. Can be used for Offline processing to recall it. - CAP_PROP_XI_HW_REVISION = 571, //!< Returns hardware revision number. - CAP_PROP_XI_DEBUG_LEVEL = 572, //!< Set debug level. - CAP_PROP_XI_AUTO_BANDWIDTH_CALCULATION = 573, //!< Automatic bandwidth calculation. - CAP_PROP_XI_FFS_FILE_ID = 594, //!< File number. - CAP_PROP_XI_FFS_FILE_SIZE = 580, //!< Size of file. - CAP_PROP_XI_FREE_FFS_SIZE = 581, //!< Size of free camera FFS. - CAP_PROP_XI_USED_FFS_SIZE = 582, //!< Size of used camera FFS. - CAP_PROP_XI_FFS_ACCESS_KEY = 583, //!< Setting of key enables file operations on some cameras. - CAP_PROP_XI_SENSOR_FEATURE_SELECTOR = 585, //!< Selects the current feature which is accessible by XI_PRM_SENSOR_FEATURE_VALUE. - CAP_PROP_XI_SENSOR_FEATURE_VALUE = 586, //!< Allows access to sensor feature value currently selected by XI_PRM_SENSOR_FEATURE_SELECTOR. - }; - -//! @} XIMEA - - -/** @name ARAVIS Camera API - @{ -*/ - -//! Properties of cameras available through ARAVIS backend -enum { CAP_PROP_ARAVIS_AUTOTRIGGER = 600 //!< Automatically trigger frame capture if camera is configured with software trigger -}; - -//! @} ARAVIS - - -/** @name Android - @{ -*/ - -//! Properties of cameras available through NDK Camera API backend -enum { CAP_PROP_ANDROID_DEVICE_TORCH = 8001, - }; - -//! @} Android - - -/** @name AVFoundation framework for iOS - @{ -*/ - -//! Properties of cameras available through AVFOUNDATION backend -enum { CAP_PROP_IOS_DEVICE_FOCUS = 9001, - CAP_PROP_IOS_DEVICE_EXPOSURE = 9002, - CAP_PROP_IOS_DEVICE_FLASH = 9003, - CAP_PROP_IOS_DEVICE_WHITEBALANCE = 9004, - CAP_PROP_IOS_DEVICE_TORCH = 9005 - }; - -//! @} AVFoundation framework for iOS - - -/** @name Smartek Giganetix GigEVisionSDK - @{ -*/ - -//! Properties of cameras available through Smartek Giganetix Ethernet Vision backend -/* --- Vladimir Litvinenko (litvinenko.vladimir@gmail.com) --- */ -enum { CAP_PROP_GIGA_FRAME_OFFSET_X = 10001, - CAP_PROP_GIGA_FRAME_OFFSET_Y = 10002, - CAP_PROP_GIGA_FRAME_WIDTH_MAX = 10003, - CAP_PROP_GIGA_FRAME_HEIGH_MAX = 10004, - CAP_PROP_GIGA_FRAME_SENS_WIDTH = 10005, - CAP_PROP_GIGA_FRAME_SENS_HEIGH = 10006 - }; - -//! @} Smartek - -/** @name Intel Perceptual Computing SDK - @{ -*/ -enum { CAP_PROP_INTELPERC_PROFILE_COUNT = 11001, - CAP_PROP_INTELPERC_PROFILE_IDX = 11002, - CAP_PROP_INTELPERC_DEPTH_LOW_CONFIDENCE_VALUE = 11003, - CAP_PROP_INTELPERC_DEPTH_SATURATION_VALUE = 11004, - CAP_PROP_INTELPERC_DEPTH_CONFIDENCE_THRESHOLD = 11005, - CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_HORZ = 11006, - CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_VERT = 11007 - }; - -//! Intel Perceptual Streams -enum { CAP_INTELPERC_DEPTH_GENERATOR = 1 << 29, - CAP_INTELPERC_IMAGE_GENERATOR = 1 << 28, - CAP_INTELPERC_IR_GENERATOR = 1 << 27, - CAP_INTELPERC_GENERATORS_MASK = CAP_INTELPERC_DEPTH_GENERATOR + CAP_INTELPERC_IMAGE_GENERATOR + CAP_INTELPERC_IR_GENERATOR - }; - -enum { CAP_INTELPERC_DEPTH_MAP = 0, //!< Each pixel is a 16-bit integer. The value indicates the distance from an object to the camera's XY plane or the Cartesian depth. - CAP_INTELPERC_UVDEPTH_MAP = 1, //!< Each pixel contains two 32-bit floating point values in the range of 0-1, representing the mapping of depth coordinates to the color coordinates. - CAP_INTELPERC_IR_MAP = 2, //!< Each pixel is a 16-bit integer. The value indicates the intensity of the reflected laser beam. - CAP_INTELPERC_IMAGE = 3 - }; - -//! @} Intel Perceptual - -/** @name gPhoto2 connection - @{ -*/ - -/** @brief gPhoto2 properties - -If `propertyId` is less than 0 then work on widget with that __additive inversed__ camera setting ID -Get IDs by using CAP_PROP_GPHOTO2_WIDGET_ENUMERATE. -@see CvCaptureCAM_GPHOTO2 for more info -*/ -enum { CAP_PROP_GPHOTO2_PREVIEW = 17001, //!< Capture only preview from liveview mode. - CAP_PROP_GPHOTO2_WIDGET_ENUMERATE = 17002, //!< Readonly, returns (const char *). - CAP_PROP_GPHOTO2_RELOAD_CONFIG = 17003, //!< Trigger, only by set. Reload camera settings. - CAP_PROP_GPHOTO2_RELOAD_ON_CHANGE = 17004, //!< Reload all settings on set. - CAP_PROP_GPHOTO2_COLLECT_MSGS = 17005, //!< Collect messages with details. - CAP_PROP_GPHOTO2_FLUSH_MSGS = 17006, //!< Readonly, returns (const char *). - CAP_PROP_SPEED = 17007, //!< Exposure speed. Can be readonly, depends on camera program. - CAP_PROP_APERTURE = 17008, //!< Aperture. Can be readonly, depends on camera program. - CAP_PROP_EXPOSUREPROGRAM = 17009, //!< Camera exposure program. - CAP_PROP_VIEWFINDER = 17010 //!< Enter liveview mode. - }; - -//! @} gPhoto2 - - -/** @name Images backend - @{ -*/ - -/** @brief Images backend properties - -*/ -enum { CAP_PROP_IMAGES_BASE = 18000, - CAP_PROP_IMAGES_LAST = 19000 // excluding - }; - -//! @} Images - -/** @name OBSENSOR (for Orbbec 3D-Sensor device/module ) - @{ -*/ -//! OBSENSOR data given from image generator -enum VideoCaptureOBSensorDataType{ - CAP_OBSENSOR_DEPTH_MAP = 0, //!< Depth values in mm (CV_16UC1) - CAP_OBSENSOR_BGR_IMAGE = 1, //!< Data given from BGR stream generator - CAP_OBSENSOR_IR_IMAGE = 2 //!< Data given from IR stream generator(CV_16UC1) -}; - -//! OBSENSOR stream generator -enum VideoCaptureOBSensorGenerators{ - CAP_OBSENSOR_DEPTH_GENERATOR = 1 << 29, - CAP_OBSENSOR_IMAGE_GENERATOR = 1 << 28, - CAP_OBSENSOR_IR_GENERATOR = 1 << 27, - CAP_OBSENSOR_GENERATORS_MASK = CAP_OBSENSOR_DEPTH_GENERATOR + CAP_OBSENSOR_IMAGE_GENERATOR + CAP_OBSENSOR_IR_GENERATOR -}; - -//!OBSENSOR properties -enum VideoCaptureOBSensorProperties{ - // INTRINSIC - CAP_PROP_OBSENSOR_INTRINSIC_FX=26001, - CAP_PROP_OBSENSOR_INTRINSIC_FY=26002, - CAP_PROP_OBSENSOR_INTRINSIC_CX=26003, - CAP_PROP_OBSENSOR_INTRINSIC_CY=26004, -}; - -//! @} OBSENSOR - -//! @} videoio_flags_others - -/** @brief Read data stream interface - */ -class CV_EXPORTS_W IStreamReader -{ -public: - virtual ~IStreamReader(); - - /** @brief Read bytes from stream */ - virtual long long read(char* buffer, long long size) = 0; - - /** @brief Sets the stream position - * - * @param offset Seek offset - * @param origin SEEK_SET / SEEK_END / SEEK_CUR - * - * @see fseek - */ - virtual long long seek(long long offset, int origin) = 0; -}; - -class IVideoCapture; -//! @cond IGNORED -namespace internal { class VideoCapturePrivateAccessor; } -//! @endcond IGNORED - -/** @brief Class for video capturing from video files, image sequences or cameras. - -The class provides C++ API for capturing video from cameras or for reading video files and image sequences. - -Here is how the class can be used: -@include samples/cpp/videocapture_basic.cpp - -@note In @ref videoio_c "C API" the black-box structure `CvCapture` is used instead of %VideoCapture. -@note -- (C++) A basic sample on using the %VideoCapture interface can be found at - `OPENCV_SOURCE_CODE/samples/cpp/videocapture_starter.cpp` -- (Python) A basic sample on using the %VideoCapture interface can be found at - `OPENCV_SOURCE_CODE/samples/python/video.py` -- (Python) A multi threaded video processing sample can be found at - `OPENCV_SOURCE_CODE/samples/python/video_threaded.py` -- (Python) %VideoCapture sample showcasing some features of the Video4Linux2 backend - `OPENCV_SOURCE_CODE/samples/python/video_v4l2.py` - */ -class CV_EXPORTS_W VideoCapture -{ -public: - /** @brief Default constructor - @note In @ref videoio_c "C API", when you finished working with video, release CvCapture structure with - cvReleaseCapture(), or use Ptr\ that calls cvReleaseCapture() automatically in the - destructor. - */ - CV_WRAP VideoCapture(); - - /** @overload - @brief Opens a video file or a capturing device or an IP video stream for video capturing with API Preference - - @param filename it can be: - - name of video file (eg. `video.avi`) - - or image sequence (eg. `img_%02d.jpg`, which will read samples like `img_00.jpg, img_01.jpg, img_02.jpg, ...`) - - or URL of video stream (eg. `protocol://host:port/script_name?script_params|auth`) - - or GStreamer pipeline string in gst-launch tool format in case if GStreamer is used as backend - Note that each video stream or IP camera feed has its own URL scheme. Please refer to the - documentation of source stream to know the right URL. - @param apiPreference preferred Capture API backends to use. Can be used to enforce a specific reader - implementation if multiple are available: e.g. cv::CAP_FFMPEG or cv::CAP_IMAGES or cv::CAP_DSHOW. - - @sa cv::VideoCaptureAPIs - */ - CV_WRAP explicit VideoCapture(const String& filename, int apiPreference = CAP_ANY); - - /** @overload - @brief Opens a video file or a capturing device or an IP video stream for video capturing with API Preference and parameters - - The `params` parameter allows to specify extra parameters encoded as pairs `(paramId_1, paramValue_1, paramId_2, paramValue_2, ...)`. - See cv::VideoCaptureProperties - */ - CV_WRAP explicit VideoCapture(const String& filename, int apiPreference, const std::vector& params); - - /** @overload - @brief Opens a camera for video capturing - - @param index id of the video capturing device to open. To open default camera using default backend just pass 0. - (to backward compatibility usage of camera_id + domain_offset (CAP_*) is valid when apiPreference is CAP_ANY) - @param apiPreference preferred Capture API backends to use. Can be used to enforce a specific reader - implementation if multiple are available: e.g. cv::CAP_DSHOW or cv::CAP_MSMF or cv::CAP_V4L. - - @sa cv::VideoCaptureAPIs - */ - CV_WRAP explicit VideoCapture(int index, int apiPreference = CAP_ANY); - - /** @overload - @brief Opens a camera for video capturing with API Preference and parameters - - The `params` parameter allows to specify extra parameters encoded as pairs `(paramId_1, paramValue_1, paramId_2, paramValue_2, ...)`. - See cv::VideoCaptureProperties - */ - CV_WRAP explicit VideoCapture(int index, int apiPreference, const std::vector& params); - - /** @overload - @brief Opens a video using data stream. - - The `params` parameter allows to specify extra parameters encoded as pairs `(paramId_1, paramValue_1, paramId_2, paramValue_2, ...)`. - See cv::VideoCaptureProperties - */ - CV_WRAP VideoCapture(const Ptr& source, int apiPreference, const std::vector& params); - - /** @brief Default destructor - - The method first calls VideoCapture::release to close the already opened file or camera. - */ - virtual ~VideoCapture(); - - /** @brief Opens a video file or a capturing device or an IP video stream for video capturing. - - @overload - - Parameters are same as the constructor VideoCapture(const String& filename, int apiPreference = CAP_ANY) - @return `true` if the file has been successfully opened - - The method first calls VideoCapture::release to close the already opened file or camera. - */ - CV_WRAP virtual bool open(const String& filename, int apiPreference = CAP_ANY); - - /** @brief Opens a video file or a capturing device or an IP video stream for video capturing with API Preference and parameters - - @overload - - The `params` parameter allows to specify extra parameters encoded as pairs `(paramId_1, paramValue_1, paramId_2, paramValue_2, ...)`. - See cv::VideoCaptureProperties - - @return `true` if the file has been successfully opened - - The method first calls VideoCapture::release to close the already opened file or camera. - */ - CV_WRAP virtual bool open(const String& filename, int apiPreference, const std::vector& params); - - /** @brief Opens a camera for video capturing - - @overload - - Parameters are same as the constructor VideoCapture(int index, int apiPreference = CAP_ANY) - @return `true` if the camera has been successfully opened. - - The method first calls VideoCapture::release to close the already opened file or camera. - */ - CV_WRAP virtual bool open(int index, int apiPreference = CAP_ANY); - - /** @brief Opens a camera for video capturing with API Preference and parameters - - @overload - - The `params` parameter allows to specify extra parameters encoded as pairs `(paramId_1, paramValue_1, paramId_2, paramValue_2, ...)`. - See cv::VideoCaptureProperties - - @return `true` if the camera has been successfully opened. - - The method first calls VideoCapture::release to close the already opened file or camera. - */ - CV_WRAP virtual bool open(int index, int apiPreference, const std::vector& params); - - /** @brief Opens a video using data stream. - - @overload - - The `params` parameter allows to specify extra parameters encoded as pairs `(paramId_1, paramValue_1, paramId_2, paramValue_2, ...)`. - See cv::VideoCaptureProperties - - @return `true` if the file has been successfully opened - - The method first calls VideoCapture::release to close the already opened file or camera. - */ - CV_WRAP virtual bool open(const Ptr& source, int apiPreference, const std::vector& params); - - /** @brief Returns true if video capturing has been initialized already. - - If the previous call to VideoCapture constructor or VideoCapture::open() succeeded, the method returns - true. - */ - CV_WRAP virtual bool isOpened() const; - - /** @brief Closes video file or capturing device. - - The method is automatically called by subsequent VideoCapture::open and by VideoCapture - destructor. - - The C function also deallocates memory and clears \*capture pointer. - */ - CV_WRAP virtual void release(); - - /** @brief Grabs the next frame from video file or capturing device. - - @return `true` (non-zero) in the case of success. - - The method/function grabs the next frame from video file or camera and returns true (non-zero) in - the case of success. - - The primary use of the function is in multi-camera environments, especially when the cameras do not - have hardware synchronization. That is, you call VideoCapture::grab() for each camera and after that - call the slower method VideoCapture::retrieve() to decode and get frame from each camera. This way - the overhead on demosaicing or motion jpeg decompression etc. is eliminated and the retrieved frames - from different cameras will be closer in time. - - Also, when a connected camera is multi-head (for example, a stereo camera or a Kinect device), the - correct way of retrieving data from it is to call VideoCapture::grab() first and then call - VideoCapture::retrieve() one or more times with different values of the channel parameter. - - @ref tutorial_kinect_openni - */ - CV_WRAP virtual bool grab(); - - /** @brief Decodes and returns the grabbed video frame. - - @param [out] image the video frame is returned here. If no frames has been grabbed the image will be empty. - @param flag it could be a frame index or a driver specific flag - @return `false` if no frames has been grabbed - - The method decodes and returns the just grabbed frame. If no frames has been grabbed - (camera has been disconnected, or there are no more frames in video file), the method returns false - and the function returns an empty image (with %cv::Mat, test it with Mat::empty()). - - @sa read() - - @note In @ref videoio_c "C API", functions cvRetrieveFrame() and cv.RetrieveFrame() return image stored inside the video - capturing structure. It is not allowed to modify or release the image! You can copy the frame using - cvCloneImage and then do whatever you want with the copy. - */ - CV_WRAP virtual bool retrieve(OutputArray image, int flag = 0); - - /** @brief Stream operator to read the next video frame. - @sa read() - */ - virtual VideoCapture& operator >> (CV_OUT Mat& image); - - /** @overload - @sa read() - */ - virtual VideoCapture& operator >> (CV_OUT UMat& image); - - /** @brief Grabs, decodes and returns the next video frame. - - @param [out] image the video frame is returned here. If no frames has been grabbed the image will be empty. - @return `false` if no frames has been grabbed - - The method/function combines VideoCapture::grab() and VideoCapture::retrieve() in one call. This is the - most convenient method for reading video files or capturing data from decode and returns the just - grabbed frame. If no frames has been grabbed (camera has been disconnected, or there are no more - frames in video file), the method returns false and the function returns empty image (with %cv::Mat, test it with Mat::empty()). - - @note In @ref videoio_c "C API", functions cvRetrieveFrame() and cv.RetrieveFrame() return image stored inside the video - capturing structure. It is not allowed to modify or release the image! You can copy the frame using - cvCloneImage and then do whatever you want with the copy. - */ - CV_WRAP virtual bool read(OutputArray image); - - /** @brief Sets a property in the VideoCapture. - - @param propId Property identifier from cv::VideoCaptureProperties (eg. cv::CAP_PROP_POS_MSEC, cv::CAP_PROP_POS_FRAMES, ...) - or one from @ref videoio_flags_others - @param value Value of the property. - @return `true` if the property is supported by backend used by the VideoCapture instance. - @note Even if it returns `true` this doesn't ensure that the property - value has been accepted by the capture device. See note in VideoCapture::get() - */ - CV_WRAP virtual bool set(int propId, double value); - - /** @brief Returns the specified VideoCapture property - - @param propId Property identifier from cv::VideoCaptureProperties (eg. cv::CAP_PROP_POS_MSEC, cv::CAP_PROP_POS_FRAMES, ...) - or one from @ref videoio_flags_others - @return Value for the specified property. Value 0 is returned when querying a property that is - not supported by the backend used by the VideoCapture instance. - - @note Reading / writing properties involves many layers. Some unexpected result might happens - along this chain. - @code{.txt} - VideoCapture -> API Backend -> Operating System -> Device Driver -> Device Hardware - @endcode - The returned value might be different from what really used by the device or it could be encoded - using device dependent rules (eg. steps or percentage). Effective behaviour depends from device - driver and API Backend - - */ - CV_WRAP virtual double get(int propId) const; - - /** @brief Returns used backend API name - - @note Stream should be opened. - */ - CV_WRAP String getBackendName() const; - - /** Switches exceptions mode - * - * methods raise exceptions if not successful instead of returning an error code - */ - CV_WRAP void setExceptionMode(bool enable) { throwOnFail = enable; } - - /// query if exception mode is active - CV_WRAP bool getExceptionMode() const { return throwOnFail; } - - - /** @brief Wait for ready frames from VideoCapture. - - @param streams input video streams - @param readyIndex stream indexes with grabbed frames (ready to use .retrieve() to fetch actual frame) - @param timeoutNs number of nanoseconds (0 - infinite) - @return `true` if streamReady is not empty - - @throws Exception %Exception on stream errors (check .isOpened() to filter out malformed streams) or VideoCapture type is not supported - - The primary use of the function is in multi-camera environments. - The method fills the ready state vector, grabs video frame, if camera is ready. - - After this call use VideoCapture::retrieve() to decode and fetch frame data. - */ - CV_WRAP static - bool waitAny( - const std::vector& streams, - CV_OUT std::vector& readyIndex, - int64 timeoutNs = 0); - -protected: - Ptr cap; - Ptr icap; - bool throwOnFail; - - friend class internal::VideoCapturePrivateAccessor; -}; - -class IVideoWriter; - -/** @example samples/cpp/tutorial_code/videoio/video-write/video-write.cpp -Check @ref tutorial_video_write "the corresponding tutorial" for more details -*/ - -/** @example samples/cpp/videowriter_basic.cpp -An example using VideoCapture and VideoWriter class -*/ - -/** @brief Video writer class. - -The class provides C++ API for writing video files or image sequences. -*/ -class CV_EXPORTS_W VideoWriter -{ -public: - /** @brief Default constructors - - The constructors/functions initialize video writers. - - On Linux FFMPEG is used to write videos; - - On Windows FFMPEG or MSWF or DSHOW is used; - - On MacOSX AVFoundation is used. - */ - CV_WRAP VideoWriter(); - - /** @overload - @param filename Name of the output video file. - @param fourcc 4-character code of codec used to compress the frames. For example, - VideoWriter::fourcc('P','I','M','1') is a MPEG-1 codec, VideoWriter::fourcc('M','J','P','G') - is a motion-jpeg codec etc. List of codes can be obtained at - [MSDN](https://docs.microsoft.com/en-us/windows/win32/medfound/video-fourccs) page - or with this [page](https://fourcc.org/codecs.php) - of the fourcc site for a more complete list). FFMPEG backend with MP4 container natively uses - other values as fourcc code: see [ObjectType](http://mp4ra.org/#/codecs), - so you may receive a warning message from OpenCV about fourcc code conversion. - @param fps Framerate of the created video stream. - @param frameSize Size of the video frames. - @param isColor If it is not zero, the encoder will expect and encode color frames, otherwise it - will work with grayscale frames. - - @b Tips: - - With some backends `fourcc=-1` pops up the codec selection dialog from the system. - - To save image sequence use a proper filename (eg. `img_%02d.jpg`) and `fourcc=0` - OR `fps=0`. Use uncompressed image format (eg. `img_%02d.BMP`) to save raw frames. - - Most codecs are lossy. If you want lossless video file you need to use a lossless codecs - (eg. FFMPEG FFV1, Huffman HFYU, Lagarith LAGS, etc...) - - If FFMPEG is enabled, using `codec=0; fps=0;` you can create an uncompressed (raw) video file. - - If FFMPEG is used, we allow frames of odd width or height, but in this case we truncate - the rightmost column/the bottom row. Probably, this should be handled more elegantly, - but some internal functions inside FFMPEG swscale require even width/height. - */ - CV_WRAP VideoWriter(const String& filename, int fourcc, double fps, - Size frameSize, bool isColor = true); - - /** @overload - The `apiPreference` parameter allows to specify API backends to use. Can be used to enforce a specific reader implementation - if multiple are available: e.g. cv::CAP_FFMPEG or cv::CAP_GSTREAMER. - */ - CV_WRAP VideoWriter(const String& filename, int apiPreference, int fourcc, double fps, - Size frameSize, bool isColor = true); - - /** @overload - * The `params` parameter allows to specify extra encoder parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, ... .) - * see cv::VideoWriterProperties - */ - CV_WRAP VideoWriter(const String& filename, int fourcc, double fps, const Size& frameSize, - const std::vector& params); - - /** @overload - */ - CV_WRAP VideoWriter(const String& filename, int apiPreference, int fourcc, double fps, - const Size& frameSize, const std::vector& params); - - /** @brief Default destructor - - The method first calls VideoWriter::release to close the already opened file. - */ - virtual ~VideoWriter(); - - /** @brief Initializes or reinitializes video writer. - - The method opens video writer. Parameters are the same as in the constructor - VideoWriter::VideoWriter. - @return `true` if video writer has been successfully initialized - - The method first calls VideoWriter::release to close the already opened file. - */ - CV_WRAP virtual bool open(const String& filename, int fourcc, double fps, - Size frameSize, bool isColor = true); - - /** @overload - */ - CV_WRAP bool open(const String& filename, int apiPreference, int fourcc, double fps, - Size frameSize, bool isColor = true); - - /** @overload - */ - CV_WRAP bool open(const String& filename, int fourcc, double fps, const Size& frameSize, - const std::vector& params); - - /** @overload - */ - CV_WRAP bool open(const String& filename, int apiPreference, int fourcc, double fps, - const Size& frameSize, const std::vector& params); - - /** @brief Returns true if video writer has been successfully initialized. - */ - CV_WRAP virtual bool isOpened() const; - - /** @brief Closes the video writer. - - The method is automatically called by subsequent VideoWriter::open and by the VideoWriter - destructor. - */ - CV_WRAP virtual void release(); - - /** @brief Stream operator to write the next video frame. - @sa write - */ - virtual VideoWriter& operator << (const Mat& image); - - /** @overload - @sa write - */ - virtual VideoWriter& operator << (const UMat& image); - - /** @brief Writes the next video frame - - @param image The written frame. In general, color images are expected in BGR format. - - The function/method writes the specified image to video file. It must have the same size as has - been specified when opening the video writer. - */ - CV_WRAP virtual void write(InputArray image); - - /** @brief Sets a property in the VideoWriter. - - @param propId Property identifier from cv::VideoWriterProperties (eg. cv::VIDEOWRITER_PROP_QUALITY) - or one of @ref videoio_flags_others - - @param value Value of the property. - @return `true` if the property is supported by the backend used by the VideoWriter instance. - */ - CV_WRAP virtual bool set(int propId, double value); - - /** @brief Returns the specified VideoWriter property - - @param propId Property identifier from cv::VideoWriterProperties (eg. cv::VIDEOWRITER_PROP_QUALITY) - or one of @ref videoio_flags_others - - @return Value for the specified property. Value 0 is returned when querying a property that is - not supported by the backend used by the VideoWriter instance. - */ - CV_WRAP virtual double get(int propId) const; - - /** @brief Concatenates 4 chars to a fourcc code - - @return a fourcc code - - This static method constructs the fourcc code of the codec to be used in the constructor - VideoWriter::VideoWriter or VideoWriter::open. - */ - CV_WRAP static int fourcc(char c1, char c2, char c3, char c4); - - /** @brief Returns used backend API name - - @note Stream should be opened. - */ - CV_WRAP String getBackendName() const; - -protected: - Ptr writer; - Ptr iwriter; - - static Ptr create(const String& filename, int fourcc, double fps, - Size frameSize, bool isColor = true); -}; - -//! @cond IGNORED -template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvCapture* obj) const; }; -template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvVideoWriter* obj) const; }; -//! @endcond IGNORED - -//! @} videoio - -} // cv - -#endif //OPENCV_VIDEOIO_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_VIDEOIO_HPP +#define OPENCV_VIDEOIO_HPP + +#include "opencv2/core.hpp" + +/** + @defgroup videoio Video I/O + + @brief Read and write video or images sequence with OpenCV + + ### See also: + - @ref videoio_overview + - Tutorials: @ref tutorial_table_of_content_app + @{ + @defgroup videoio_flags_base Flags for video I/O + @defgroup videoio_flags_others Additional flags for video I/O API backends + @defgroup videoio_hwaccel Hardware-accelerated video decoding and encoding + @defgroup videoio_c C API for video I/O + @defgroup videoio_ios iOS glue for video I/O + @defgroup videoio_winrt WinRT glue for video I/O + @defgroup videoio_registry Query I/O API backends registry + @} +*/ + +////////////////////////////////// video io ///////////////////////////////// + +typedef struct CvCapture CvCapture; +typedef struct CvVideoWriter CvVideoWriter; + +namespace cv +{ + +//! @addtogroup videoio +//! @{ + +//! @addtogroup videoio_flags_base +//! @{ + + +/** @brief cv::VideoCapture API backends identifier. + +Select preferred API for a capture object. +To be used in the VideoCapture::VideoCapture() constructor or VideoCapture::open() + +@note +- Backends are available only if they have been built with your OpenCV binaries. +See @ref videoio_overview for more information. +- Microsoft Media Foundation backend tries to use hardware accelerated transformations +if possible. Environment flag "OPENCV_VIDEOIO_MSMF_ENABLE_HW_TRANSFORMS" set to 0 +disables it and may improve initialization time. More details: +https://learn.microsoft.com/en-us/windows/win32/medfound/mf-readwrite-enable-hardware-transforms +*/ +enum VideoCaptureAPIs { + CAP_ANY = 0, //!< Auto detect == 0 + CAP_VFW = 200, //!< Video For Windows (obsolete, removed) + CAP_V4L = 200, //!< V4L/V4L2 capturing support + CAP_V4L2 = CAP_V4L, //!< Same as CAP_V4L + CAP_FIREWIRE = 300, //!< IEEE 1394 drivers + CAP_FIREWARE = CAP_FIREWIRE, //!< Same value as CAP_FIREWIRE + CAP_IEEE1394 = CAP_FIREWIRE, //!< Same value as CAP_FIREWIRE + CAP_DC1394 = CAP_FIREWIRE, //!< Same value as CAP_FIREWIRE + CAP_CMU1394 = CAP_FIREWIRE, //!< Same value as CAP_FIREWIRE + CAP_QT = 500, //!< QuickTime (obsolete, removed) + CAP_UNICAP = 600, //!< Unicap drivers (obsolete, removed) + CAP_DSHOW = 700, //!< DirectShow (via videoInput) + CAP_PVAPI = 800, //!< PvAPI, Prosilica GigE SDK + CAP_OPENNI = 900, //!< OpenNI (for Kinect) + CAP_OPENNI_ASUS = 910, //!< OpenNI (for Asus Xtion) + CAP_ANDROID = 1000, //!< MediaNDK (API Level 21+) and NDK Camera (API level 24+) for Android + CAP_XIAPI = 1100, //!< XIMEA Camera API + CAP_AVFOUNDATION = 1200, //!< AVFoundation framework for iOS (OS X Lion will have the same API) + CAP_GIGANETIX = 1300, //!< Smartek Giganetix GigEVisionSDK + CAP_MSMF = 1400, //!< Microsoft Media Foundation (via videoInput). See platform specific notes above. + CAP_WINRT = 1410, //!< Microsoft Windows Runtime using Media Foundation + CAP_INTELPERC = 1500, //!< RealSense (former Intel Perceptual Computing SDK) + CAP_REALSENSE = 1500, //!< Synonym for CAP_INTELPERC + CAP_OPENNI2 = 1600, //!< OpenNI2 (for Kinect) + CAP_OPENNI2_ASUS = 1610, //!< OpenNI2 (for Asus Xtion and Occipital Structure sensors) + CAP_OPENNI2_ASTRA= 1620, //!< OpenNI2 (for Orbbec Astra) + CAP_GPHOTO2 = 1700, //!< gPhoto2 connection + CAP_GSTREAMER = 1800, //!< GStreamer + CAP_FFMPEG = 1900, //!< Open and record video file or stream using the FFMPEG library + CAP_IMAGES = 2000, //!< OpenCV Image Sequence (e.g. img_%02d.jpg) + CAP_ARAVIS = 2100, //!< Aravis SDK + CAP_OPENCV_MJPEG = 2200, //!< Built-in OpenCV MotionJPEG codec + CAP_INTEL_MFX = 2300, //!< Intel MediaSDK + CAP_XINE = 2400, //!< XINE engine (Linux) + CAP_UEYE = 2500, //!< uEye Camera API + CAP_OBSENSOR = 2600, //!< For Orbbec 3D-Sensor device/module (Astra+, Femto, Astra2, Gemini2, Gemini2L, Gemini2XL, Femto Mega) attention: Astra2 cameras currently only support Windows and Linux kernel versions no higher than 4.15, and higher versions of Linux kernel may have exceptions. + }; + + +/** @brief cv::VideoCapture generic properties identifier. + + Reading / writing properties involves many layers. Some unexpected result might happens along this chain. + Effective behaviour depends from device hardware, driver and API Backend. + @sa videoio_flags_others, VideoCapture::get(), VideoCapture::set() +*/ +enum VideoCaptureProperties { + CAP_PROP_POS_MSEC =0, //!< Current position of the video file in milliseconds. + CAP_PROP_POS_FRAMES =1, //!< 0-based index of the frame to be decoded/captured next. When the index i is set in RAW mode (CAP_PROP_FORMAT == -1) this will seek to the key frame k, where k <= i. + CAP_PROP_POS_AVI_RATIO =2, //!< Relative position of the video file: 0=start of the film, 1=end of the film. + CAP_PROP_FRAME_WIDTH =3, //!< Width of the frames in the video stream. + CAP_PROP_FRAME_HEIGHT =4, //!< Height of the frames in the video stream. + CAP_PROP_FPS =5, //!< Frame rate. + CAP_PROP_FOURCC =6, //!< 4-character code of codec. see VideoWriter::fourcc . + CAP_PROP_FRAME_COUNT =7, //!< Number of frames in the video file. + CAP_PROP_FORMAT =8, //!< Format of the %Mat objects (see Mat::type()) returned by VideoCapture::retrieve(). + //!< Set value -1 to fetch undecoded RAW video streams (as Mat 8UC1). + CAP_PROP_MODE =9, //!< Backend-specific value indicating the current capture mode. + CAP_PROP_BRIGHTNESS =10, //!< Brightness of the image (only for those cameras that support). + CAP_PROP_CONTRAST =11, //!< Contrast of the image (only for cameras). + CAP_PROP_SATURATION =12, //!< Saturation of the image (only for cameras). + CAP_PROP_HUE =13, //!< Hue of the image (only for cameras). + CAP_PROP_GAIN =14, //!< Gain of the image (only for those cameras that support). + CAP_PROP_EXPOSURE =15, //!< Exposure (only for those cameras that support). + CAP_PROP_CONVERT_RGB =16, //!< Boolean flags indicating whether images should be converted to RGB.
+ //!< *GStreamer note*: The flag is ignored in case if custom pipeline is used. It's user responsibility to interpret pipeline output. + CAP_PROP_WHITE_BALANCE_BLUE_U =17, //!< Currently unsupported. + CAP_PROP_RECTIFICATION =18, //!< Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend currently). + CAP_PROP_MONOCHROME =19, + CAP_PROP_SHARPNESS =20, + CAP_PROP_AUTO_EXPOSURE =21, //!< DC1394: exposure control done by camera, user can adjust reference level using this feature. + CAP_PROP_GAMMA =22, + CAP_PROP_TEMPERATURE =23, + CAP_PROP_TRIGGER =24, + CAP_PROP_TRIGGER_DELAY =25, + CAP_PROP_WHITE_BALANCE_RED_V =26, + CAP_PROP_ZOOM =27, + CAP_PROP_FOCUS =28, + CAP_PROP_GUID =29, + CAP_PROP_ISO_SPEED =30, + CAP_PROP_BACKLIGHT =32, + CAP_PROP_PAN =33, + CAP_PROP_TILT =34, + CAP_PROP_ROLL =35, + CAP_PROP_IRIS =36, + CAP_PROP_SETTINGS =37, //!< Pop up video/camera filter dialog (note: only supported by DSHOW backend currently. The property value is ignored) + CAP_PROP_BUFFERSIZE =38, + CAP_PROP_AUTOFOCUS =39, + CAP_PROP_SAR_NUM =40, //!< Sample aspect ratio: num/den (num) + CAP_PROP_SAR_DEN =41, //!< Sample aspect ratio: num/den (den) + CAP_PROP_BACKEND =42, //!< Current backend (enum VideoCaptureAPIs). Read-only property + CAP_PROP_CHANNEL =43, //!< Video input or Channel Number (only for those cameras that support) + CAP_PROP_AUTO_WB =44, //!< enable/ disable auto white-balance + CAP_PROP_WB_TEMPERATURE=45, //!< white-balance color temperature + CAP_PROP_CODEC_PIXEL_FORMAT =46, //!< (read-only) codec's pixel format. 4-character code - see VideoWriter::fourcc . Subset of [AV_PIX_FMT_*](https://github.com/FFmpeg/FFmpeg/blob/master/libavcodec/raw.c) or -1 if unknown + CAP_PROP_BITRATE =47, //!< (read-only) Video bitrate in kbits/s + CAP_PROP_ORIENTATION_META=48, //!< (read-only) Frame rotation defined by stream meta (applicable for FFmpeg and AVFoundation back-ends only) + CAP_PROP_ORIENTATION_AUTO=49, //!< if true - rotates output frames of CvCapture considering video file's metadata (applicable for FFmpeg and AVFoundation back-ends only) (https://github.com/opencv/opencv/issues/15499) + CAP_PROP_HW_ACCELERATION=50, //!< (**open-only**) Hardware acceleration type (see #VideoAccelerationType). Setting supported only via `params` parameter in cv::VideoCapture constructor / .open() method. Default value is backend-specific. + CAP_PROP_HW_DEVICE =51, //!< (**open-only**) Hardware device index (select GPU if multiple available). Device enumeration is acceleration type specific. + CAP_PROP_HW_ACCELERATION_USE_OPENCL=52, //!< (**open-only**) If non-zero, create new OpenCL context and bind it to current thread. The OpenCL context created with Video Acceleration context attached it (if not attached yet) for optimized GPU data copy between HW accelerated decoder and cv::UMat. + CAP_PROP_OPEN_TIMEOUT_MSEC=53, //!< (**open-only**) timeout in milliseconds for opening a video capture (applicable for FFmpeg and GStreamer back-ends only) + CAP_PROP_READ_TIMEOUT_MSEC=54, //!< (**open-only**) timeout in milliseconds for reading from a video capture (applicable for FFmpeg and GStreamer back-ends only) + CAP_PROP_STREAM_OPEN_TIME_USEC =55, //!< (read-only) time in microseconds since Jan 1 1970 when stream was opened. Applicable for FFmpeg backend only. Useful for RTSP and other live streams + CAP_PROP_VIDEO_TOTAL_CHANNELS = 56, //!< (read-only) Number of video channels + CAP_PROP_VIDEO_STREAM = 57, //!< (**open-only**) Specify video stream, 0-based index. Use -1 to disable video stream from file or IP cameras. Default value is 0. + CAP_PROP_AUDIO_STREAM = 58, //!< (**open-only**) Specify stream in multi-language media files, -1 - disable audio processing or microphone. Default value is -1. + CAP_PROP_AUDIO_POS = 59, //!< (read-only) Audio position is measured in samples. Accurate audio sample timestamp of previous grabbed fragment. See CAP_PROP_AUDIO_SAMPLES_PER_SECOND and CAP_PROP_AUDIO_SHIFT_NSEC. + CAP_PROP_AUDIO_SHIFT_NSEC = 60, //!< (read only) Contains the time difference between the start of the audio stream and the video stream in nanoseconds. Positive value means that audio is started after the first video frame. Negative value means that audio is started before the first video frame. + CAP_PROP_AUDIO_DATA_DEPTH = 61, //!< (open, read) Alternative definition to bits-per-sample, but with clear handling of 32F / 32S + CAP_PROP_AUDIO_SAMPLES_PER_SECOND = 62, //!< (open, read) determined from file/codec input. If not specified, then selected audio sample rate is 44100 + CAP_PROP_AUDIO_BASE_INDEX = 63, //!< (read-only) Index of the first audio channel for .retrieve() calls. That audio channel number continues enumeration after video channels. + CAP_PROP_AUDIO_TOTAL_CHANNELS = 64, //!< (read-only) Number of audio channels in the selected audio stream (mono, stereo, etc) + CAP_PROP_AUDIO_TOTAL_STREAMS = 65, //!< (read-only) Number of audio streams. + CAP_PROP_AUDIO_SYNCHRONIZE = 66, //!< (open, read) Enables audio synchronization. + CAP_PROP_LRF_HAS_KEY_FRAME = 67, //!< FFmpeg back-end only - Indicates whether the Last Raw Frame (LRF), output from VideoCapture::read() when VideoCapture is initialized with VideoCapture::open(CAP_FFMPEG, {CAP_PROP_FORMAT, -1}) or VideoCapture::set(CAP_PROP_FORMAT,-1) is called before the first call to VideoCapture::read(), contains encoded data for a key frame. + CAP_PROP_CODEC_EXTRADATA_INDEX = 68, //!< Positive index indicates that returning extra data is supported by the video back end. This can be retrieved as cap.retrieve(data, ). E.g. When reading from a h264 encoded RTSP stream, the FFmpeg backend could return the SPS and/or PPS if available (if sent in reply to a DESCRIBE request), from calls to cap.retrieve(data, ). + CAP_PROP_FRAME_TYPE = 69, //!< (read-only) FFmpeg back-end only - Frame type ascii code (73 = 'I', 80 = 'P', 66 = 'B' or 63 = '?' if unknown) of the most recently read frame. + CAP_PROP_N_THREADS = 70, //!< (**open-only**) Set the maximum number of threads to use. Use 0 to use as many threads as CPU cores (applicable for FFmpeg back-end only). + CAP_PROP_PTS = 71, //!< (read-only) FFmpeg back-end only - presentation timestamp of the most recently read frame using the FPS time base. e.g. fps = 25, VideoCapture::get(\ref CAP_PROP_PTS) = 3, presentation time = 3/25 seconds. + CAP_PROP_DTS_DELAY = 72, //!< (read-only) FFmpeg back-end only - maximum difference between presentation (pts) and decompression timestamps (dts) using FPS time base. e.g. delay is maximum when frame_num = 0, if true, VideoCapture::get(\ref CAP_PROP_PTS) = 0 and VideoCapture::get(\ref CAP_PROP_DTS_DELAY) = 2, dts = -2. Non zero values usually imply the stream is encoded using B-frames which are not decoded in presentation order. +#ifndef CV_DOXYGEN + CV__CAP_PROP_LATEST +#endif + }; + +/** @brief cv::VideoWriter generic properties identifier. + @sa VideoWriter::get(), VideoWriter::set() +*/ +enum VideoWriterProperties { + VIDEOWRITER_PROP_QUALITY = 1, //!< Current quality (0..100%) of the encoded videostream. Can be adjusted dynamically in some codecs. + VIDEOWRITER_PROP_FRAMEBYTES = 2, //!< (Read-only): Size of just encoded video frame. Note that the encoding order may be different from representation order. + VIDEOWRITER_PROP_NSTRIPES = 3, //!< Number of stripes for parallel encoding. -1 for auto detection. + VIDEOWRITER_PROP_IS_COLOR = 4, //!< If it is not zero, the encoder will expect and encode color frames, otherwise it + //!< will work with grayscale frames. + VIDEOWRITER_PROP_DEPTH = 5, //!< Defaults to \ref CV_8U. + VIDEOWRITER_PROP_HW_ACCELERATION = 6, //!< (**open-only**) Hardware acceleration type (see #VideoAccelerationType). Setting supported only via `params` parameter in VideoWriter constructor / .open() method. Default value is backend-specific. + VIDEOWRITER_PROP_HW_DEVICE = 7, //!< (**open-only**) Hardware device index (select GPU if multiple available). Device enumeration is acceleration type specific. + VIDEOWRITER_PROP_HW_ACCELERATION_USE_OPENCL= 8, //!< (**open-only**) If non-zero, create new OpenCL context and bind it to current thread. The OpenCL context created with Video Acceleration context attached it (if not attached yet) for optimized GPU data copy between cv::UMat and HW accelerated encoder. + VIDEOWRITER_PROP_RAW_VIDEO = 9, //!< (**open-only**) Set to non-zero to enable encapsulation of an encoded raw video stream. Each raw encoded video frame should be passed to VideoWriter::write() as single row or column of a \ref CV_8UC1 Mat. \note If the key frame interval is not 1 then it must be manually specified by the user. This can either be performed during initialization passing \ref VIDEOWRITER_PROP_KEY_INTERVAL as one of the extra encoder params to \ref VideoWriter::VideoWriter(const String &, int, double, const Size &, const std::vector< int > ¶ms) or afterwards by setting the \ref VIDEOWRITER_PROP_KEY_FLAG with \ref VideoWriter::set() before writing each frame. FFMpeg backend only. + VIDEOWRITER_PROP_KEY_INTERVAL = 10, //!< (**open-only**) Set the key frame interval using raw video encapsulation (\ref VIDEOWRITER_PROP_RAW_VIDEO != 0). Defaults to 1 when not set. FFmpeg back-end only. + VIDEOWRITER_PROP_KEY_FLAG = 11, //!< Set to non-zero to signal that the following frames are key frames or zero if not, when encapsulating raw video (\ref VIDEOWRITER_PROP_RAW_VIDEO != 0). FFmpeg back-end only. + VIDEOWRITER_PROP_PTS = 12, //!< Specifies the frame presentation timestamp for each frame using the FPS time base. This property is **only** necessary when encapsulating **externally** encoded video where the decoding order differs from the presentation order, such as in GOP patterns with bi-directional B-frames. The value should be provided by your external encoder and for video sources with fixed frame rates it is equivalent to dividing the current frame's presentation time (\ref CAP_PROP_POS_MSEC) by the frame duration (1000.0 / VideoCapture::get(\ref CAP_PROP_FPS)). It can be queried from the resulting encapsulated video file using VideoCapture::get(\ref CAP_PROP_PTS). FFmpeg back-end only. + VIDEOWRITER_PROP_DTS_DELAY = 13, //!< Specifies the maximum difference between presentation (pts) and decompression timestamps (dts) using the FPS time base. This property is necessary **only** when encapsulating **externally** encoded video where the decoding order differs from the presentation order, such as in GOP patterns with bi-directional B-frames. The value should be calculated based on the specific GOP pattern used during encoding. For example, in a GOP with presentation order IBP and decoding order IPB, this value would be 1, as the B-frame is the second frame presented but the third to be decoded. It can be queried from the resulting encapsulated video file using VideoCapture::get(\ref CAP_PROP_DTS_DELAY). Non-zero values usually imply the stream is encoded using B-frames. FFmpeg back-end only. +#ifndef CV_DOXYGEN + CV__VIDEOWRITER_PROP_LATEST +#endif +}; + +//! @} videoio_flags_base + +//! @addtogroup videoio_flags_others +//! @{ + +/** @name Hardware acceleration support + @{ +*/ + +/** @brief Video Acceleration type + * + * Used as value in #CAP_PROP_HW_ACCELERATION and #VIDEOWRITER_PROP_HW_ACCELERATION + * + * @note In case of FFmpeg backend, it translated to enum AVHWDeviceType (https://github.com/FFmpeg/FFmpeg/blob/master/libavutil/hwcontext.h) + */ +enum VideoAccelerationType +{ + VIDEO_ACCELERATION_NONE = 0, //!< Do not require any specific H/W acceleration, prefer software processing. + //!< Reading of this value means that special H/W accelerated handling is not added or not detected by OpenCV. + + VIDEO_ACCELERATION_ANY = 1, //!< Prefer to use H/W acceleration. If no one supported, then fallback to software processing. + //!< @note H/W acceleration may require special configuration of used environment. + //!< @note Results in encoding scenario may differ between software and hardware accelerated encoders. + + VIDEO_ACCELERATION_D3D11 = 2, //!< DirectX 11 + VIDEO_ACCELERATION_VAAPI = 3, //!< VAAPI + VIDEO_ACCELERATION_MFX = 4, //!< libmfx (Intel MediaSDK/oneVPL) +}; + +//! @} Hardware acceleration support + +/** @name IEEE 1394 drivers + @{ +*/ + +/** @brief Modes of the IEEE 1394 controlling registers +(can be: auto, manual, auto single push, absolute Latter allowed with any other mode) +every feature can have only one mode turned on at a time +*/ +enum { CAP_PROP_DC1394_OFF = -4, //!< turn the feature off (not controlled manually nor automatically). + CAP_PROP_DC1394_MODE_MANUAL = -3, //!< set automatically when a value of the feature is set by the user. + CAP_PROP_DC1394_MODE_AUTO = -2, + CAP_PROP_DC1394_MODE_ONE_PUSH_AUTO = -1, + CAP_PROP_DC1394_MAX = 31 + }; + +//! @} IEEE 1394 drivers + +/** @name OpenNI (for Kinect) + @{ +*/ + +//! OpenNI map generators +enum { CAP_OPENNI_DEPTH_GENERATOR = 1 << 31, + CAP_OPENNI_IMAGE_GENERATOR = 1 << 30, + CAP_OPENNI_IR_GENERATOR = 1 << 29, + CAP_OPENNI_GENERATORS_MASK = CAP_OPENNI_DEPTH_GENERATOR + CAP_OPENNI_IMAGE_GENERATOR + CAP_OPENNI_IR_GENERATOR + }; + +//! Properties of cameras available through OpenNI backend +enum { CAP_PROP_OPENNI_OUTPUT_MODE = 100, + CAP_PROP_OPENNI_FRAME_MAX_DEPTH = 101, //!< In mm + CAP_PROP_OPENNI_BASELINE = 102, //!< In mm + CAP_PROP_OPENNI_FOCAL_LENGTH = 103, //!< In pixels + CAP_PROP_OPENNI_REGISTRATION = 104, //!< Flag that synchronizes the remapping depth map to image map + //!< by changing depth generator's view point (if the flag is "on") or + //!< sets this view point to its normal one (if the flag is "off"). + CAP_PROP_OPENNI_REGISTRATION_ON = CAP_PROP_OPENNI_REGISTRATION, + CAP_PROP_OPENNI_APPROX_FRAME_SYNC = 105, + CAP_PROP_OPENNI_MAX_BUFFER_SIZE = 106, + CAP_PROP_OPENNI_CIRCLE_BUFFER = 107, + CAP_PROP_OPENNI_MAX_TIME_DURATION = 108, + CAP_PROP_OPENNI_GENERATOR_PRESENT = 109, + CAP_PROP_OPENNI2_SYNC = 110, + CAP_PROP_OPENNI2_MIRROR = 111 + }; + +#ifdef _MSC_VER +#pragma warning( push ) +#pragma warning( disable: 5054 ) +#endif +//! OpenNI shortcuts +enum { CAP_OPENNI_IMAGE_GENERATOR_PRESENT = +CAP_OPENNI_IMAGE_GENERATOR + CAP_PROP_OPENNI_GENERATOR_PRESENT, + CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE = +CAP_OPENNI_IMAGE_GENERATOR + CAP_PROP_OPENNI_OUTPUT_MODE, + CAP_OPENNI_DEPTH_GENERATOR_PRESENT = +CAP_OPENNI_DEPTH_GENERATOR + CAP_PROP_OPENNI_GENERATOR_PRESENT, + CAP_OPENNI_DEPTH_GENERATOR_BASELINE = +CAP_OPENNI_DEPTH_GENERATOR + CAP_PROP_OPENNI_BASELINE, + CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH = +CAP_OPENNI_DEPTH_GENERATOR + CAP_PROP_OPENNI_FOCAL_LENGTH, + CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION = +CAP_OPENNI_DEPTH_GENERATOR + CAP_PROP_OPENNI_REGISTRATION, + CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION_ON = CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION, + CAP_OPENNI_IR_GENERATOR_PRESENT = +CAP_OPENNI_IR_GENERATOR + CAP_PROP_OPENNI_GENERATOR_PRESENT + }; +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +//! OpenNI data given from depth generator +enum { CAP_OPENNI_DEPTH_MAP = 0, //!< Depth values in mm (CV_16UC1) + CAP_OPENNI_POINT_CLOUD_MAP = 1, //!< XYZ in meters (CV_32FC3) + CAP_OPENNI_DISPARITY_MAP = 2, //!< Disparity in pixels (CV_8UC1) + CAP_OPENNI_DISPARITY_MAP_32F = 3, //!< Disparity in pixels (CV_32FC1) + CAP_OPENNI_VALID_DEPTH_MASK = 4, //!< CV_8UC1 + + CAP_OPENNI_BGR_IMAGE = 5, //!< Data given from RGB image generator + CAP_OPENNI_GRAY_IMAGE = 6, //!< Data given from RGB image generator + + CAP_OPENNI_IR_IMAGE = 7 //!< Data given from IR image generator + }; + +//! Supported output modes of OpenNI image generator +enum { CAP_OPENNI_VGA_30HZ = 0, + CAP_OPENNI_SXGA_15HZ = 1, + CAP_OPENNI_SXGA_30HZ = 2, + CAP_OPENNI_QVGA_30HZ = 3, + CAP_OPENNI_QVGA_60HZ = 4 + }; + +//! @} OpenNI + +/** @name GStreamer + @{ +*/ + +enum { CAP_PROP_GSTREAMER_QUEUE_LENGTH = 200 //!< Default is 1 + }; + +//! @} GStreamer + +/** @name PvAPI, Prosilica GigE SDK + @{ +*/ + +//! PVAPI +enum { CAP_PROP_PVAPI_MULTICASTIP = 300, //!< IP for enable multicast master mode. 0 for disable multicast. + CAP_PROP_PVAPI_FRAMESTARTTRIGGERMODE = 301, //!< FrameStartTriggerMode: Determines how a frame is initiated. + CAP_PROP_PVAPI_DECIMATIONHORIZONTAL = 302, //!< Horizontal sub-sampling of the image. + CAP_PROP_PVAPI_DECIMATIONVERTICAL = 303, //!< Vertical sub-sampling of the image. + CAP_PROP_PVAPI_BINNINGX = 304, //!< Horizontal binning factor. + CAP_PROP_PVAPI_BINNINGY = 305, //!< Vertical binning factor. + CAP_PROP_PVAPI_PIXELFORMAT = 306 //!< Pixel format. + }; + +//! PVAPI: FrameStartTriggerMode +enum { CAP_PVAPI_FSTRIGMODE_FREERUN = 0, //!< Freerun + CAP_PVAPI_FSTRIGMODE_SYNCIN1 = 1, //!< SyncIn1 + CAP_PVAPI_FSTRIGMODE_SYNCIN2 = 2, //!< SyncIn2 + CAP_PVAPI_FSTRIGMODE_FIXEDRATE = 3, //!< FixedRate + CAP_PVAPI_FSTRIGMODE_SOFTWARE = 4 //!< Software + }; + +//! PVAPI: DecimationHorizontal, DecimationVertical +enum { CAP_PVAPI_DECIMATION_OFF = 1, //!< Off + CAP_PVAPI_DECIMATION_2OUTOF4 = 2, //!< 2 out of 4 decimation + CAP_PVAPI_DECIMATION_2OUTOF8 = 4, //!< 2 out of 8 decimation + CAP_PVAPI_DECIMATION_2OUTOF16 = 8 //!< 2 out of 16 decimation + }; + +//! PVAPI: PixelFormat +enum { CAP_PVAPI_PIXELFORMAT_MONO8 = 1, //!< Mono8 + CAP_PVAPI_PIXELFORMAT_MONO16 = 2, //!< Mono16 + CAP_PVAPI_PIXELFORMAT_BAYER8 = 3, //!< Bayer8 + CAP_PVAPI_PIXELFORMAT_BAYER16 = 4, //!< Bayer16 + CAP_PVAPI_PIXELFORMAT_RGB24 = 5, //!< Rgb24 + CAP_PVAPI_PIXELFORMAT_BGR24 = 6, //!< Bgr24 + CAP_PVAPI_PIXELFORMAT_RGBA32 = 7, //!< Rgba32 + CAP_PVAPI_PIXELFORMAT_BGRA32 = 8, //!< Bgra32 + }; + +//! @} PvAPI + +/** @name XIMEA Camera API + @{ +*/ + +//! Properties of cameras available through XIMEA SDK backend +enum { CAP_PROP_XI_DOWNSAMPLING = 400, //!< Change image resolution by binning or skipping. + CAP_PROP_XI_DATA_FORMAT = 401, //!< Output data format. + CAP_PROP_XI_OFFSET_X = 402, //!< Horizontal offset from the origin to the area of interest (in pixels). + CAP_PROP_XI_OFFSET_Y = 403, //!< Vertical offset from the origin to the area of interest (in pixels). + CAP_PROP_XI_TRG_SOURCE = 404, //!< Defines source of trigger. + CAP_PROP_XI_TRG_SOFTWARE = 405, //!< Generates an internal trigger. PRM_TRG_SOURCE must be set to TRG_SOFTWARE. + CAP_PROP_XI_GPI_SELECTOR = 406, //!< Selects general purpose input. + CAP_PROP_XI_GPI_MODE = 407, //!< Set general purpose input mode. + CAP_PROP_XI_GPI_LEVEL = 408, //!< Get general purpose level. + CAP_PROP_XI_GPO_SELECTOR = 409, //!< Selects general purpose output. + CAP_PROP_XI_GPO_MODE = 410, //!< Set general purpose output mode. + CAP_PROP_XI_LED_SELECTOR = 411, //!< Selects camera signalling LED. + CAP_PROP_XI_LED_MODE = 412, //!< Define camera signalling LED functionality. + CAP_PROP_XI_MANUAL_WB = 413, //!< Calculates White Balance(must be called during acquisition). + CAP_PROP_XI_AUTO_WB = 414, //!< Automatic white balance. + CAP_PROP_XI_AEAG = 415, //!< Automatic exposure/gain. + CAP_PROP_XI_EXP_PRIORITY = 416, //!< Exposure priority (0.5 - exposure 50%, gain 50%). + CAP_PROP_XI_AE_MAX_LIMIT = 417, //!< Maximum limit of exposure in AEAG procedure. + CAP_PROP_XI_AG_MAX_LIMIT = 418, //!< Maximum limit of gain in AEAG procedure. + CAP_PROP_XI_AEAG_LEVEL = 419, //!< Average intensity of output signal AEAG should achieve(in %). + CAP_PROP_XI_TIMEOUT = 420, //!< Image capture timeout in milliseconds. + CAP_PROP_XI_EXPOSURE = 421, //!< Exposure time in microseconds. + CAP_PROP_XI_EXPOSURE_BURST_COUNT = 422, //!< Sets the number of times of exposure in one frame. + CAP_PROP_XI_GAIN_SELECTOR = 423, //!< Gain selector for parameter Gain allows to select different type of gains. + CAP_PROP_XI_GAIN = 424, //!< Gain in dB. + CAP_PROP_XI_DOWNSAMPLING_TYPE = 426, //!< Change image downsampling type. + CAP_PROP_XI_BINNING_SELECTOR = 427, //!< Binning engine selector. + CAP_PROP_XI_BINNING_VERTICAL = 428, //!< Vertical Binning - number of vertical photo-sensitive cells to combine together. + CAP_PROP_XI_BINNING_HORIZONTAL = 429, //!< Horizontal Binning - number of horizontal photo-sensitive cells to combine together. + CAP_PROP_XI_BINNING_PATTERN = 430, //!< Binning pattern type. + CAP_PROP_XI_DECIMATION_SELECTOR = 431, //!< Decimation engine selector. + CAP_PROP_XI_DECIMATION_VERTICAL = 432, //!< Vertical Decimation - vertical sub-sampling of the image - reduces the vertical resolution of the image by the specified vertical decimation factor. + CAP_PROP_XI_DECIMATION_HORIZONTAL = 433, //!< Horizontal Decimation - horizontal sub-sampling of the image - reduces the horizontal resolution of the image by the specified vertical decimation factor. + CAP_PROP_XI_DECIMATION_PATTERN = 434, //!< Decimation pattern type. + CAP_PROP_XI_TEST_PATTERN_GENERATOR_SELECTOR = 587, //!< Selects which test pattern generator is controlled by the TestPattern feature. + CAP_PROP_XI_TEST_PATTERN = 588, //!< Selects which test pattern type is generated by the selected generator. + CAP_PROP_XI_IMAGE_DATA_FORMAT = 435, //!< Output data format. + CAP_PROP_XI_SHUTTER_TYPE = 436, //!< Change sensor shutter type(CMOS sensor). + CAP_PROP_XI_SENSOR_TAPS = 437, //!< Number of taps. + CAP_PROP_XI_AEAG_ROI_OFFSET_X = 439, //!< Automatic exposure/gain ROI offset X. + CAP_PROP_XI_AEAG_ROI_OFFSET_Y = 440, //!< Automatic exposure/gain ROI offset Y. + CAP_PROP_XI_AEAG_ROI_WIDTH = 441, //!< Automatic exposure/gain ROI Width. + CAP_PROP_XI_AEAG_ROI_HEIGHT = 442, //!< Automatic exposure/gain ROI Height. + CAP_PROP_XI_BPC = 445, //!< Correction of bad pixels. + CAP_PROP_XI_WB_KR = 448, //!< White balance red coefficient. + CAP_PROP_XI_WB_KG = 449, //!< White balance green coefficient. + CAP_PROP_XI_WB_KB = 450, //!< White balance blue coefficient. + CAP_PROP_XI_WIDTH = 451, //!< Width of the Image provided by the device (in pixels). + CAP_PROP_XI_HEIGHT = 452, //!< Height of the Image provided by the device (in pixels). + CAP_PROP_XI_REGION_SELECTOR = 589, //!< Selects Region in Multiple ROI which parameters are set by width, height, ... ,region mode. + CAP_PROP_XI_REGION_MODE = 595, //!< Activates/deactivates Region selected by Region Selector. + CAP_PROP_XI_LIMIT_BANDWIDTH = 459, //!< Set/get bandwidth(datarate)(in Megabits). + CAP_PROP_XI_SENSOR_DATA_BIT_DEPTH = 460, //!< Sensor output data bit depth. + CAP_PROP_XI_OUTPUT_DATA_BIT_DEPTH = 461, //!< Device output data bit depth. + CAP_PROP_XI_IMAGE_DATA_BIT_DEPTH = 462, //!< bitdepth of data returned by function xiGetImage. + CAP_PROP_XI_OUTPUT_DATA_PACKING = 463, //!< Device output data packing (or grouping) enabled. Packing could be enabled if output_data_bit_depth > 8 and packing capability is available. + CAP_PROP_XI_OUTPUT_DATA_PACKING_TYPE = 464, //!< Data packing type. Some cameras supports only specific packing type. + CAP_PROP_XI_IS_COOLED = 465, //!< Returns 1 for cameras that support cooling. + CAP_PROP_XI_COOLING = 466, //!< Start camera cooling. + CAP_PROP_XI_TARGET_TEMP = 467, //!< Set sensor target temperature for cooling. + CAP_PROP_XI_CHIP_TEMP = 468, //!< Camera sensor temperature. + CAP_PROP_XI_HOUS_TEMP = 469, //!< Camera housing temperature. + CAP_PROP_XI_HOUS_BACK_SIDE_TEMP = 590, //!< Camera housing back side temperature. + CAP_PROP_XI_SENSOR_BOARD_TEMP = 596, //!< Camera sensor board temperature. + CAP_PROP_XI_CMS = 470, //!< Mode of color management system. + CAP_PROP_XI_APPLY_CMS = 471, //!< Enable applying of CMS profiles to xiGetImage (see XI_PRM_INPUT_CMS_PROFILE, XI_PRM_OUTPUT_CMS_PROFILE). + CAP_PROP_XI_IMAGE_IS_COLOR = 474, //!< Returns 1 for color cameras. + CAP_PROP_XI_COLOR_FILTER_ARRAY = 475, //!< Returns color filter array type of RAW data. + CAP_PROP_XI_GAMMAY = 476, //!< Luminosity gamma. + CAP_PROP_XI_GAMMAC = 477, //!< Chromaticity gamma. + CAP_PROP_XI_SHARPNESS = 478, //!< Sharpness Strength. + CAP_PROP_XI_CC_MATRIX_00 = 479, //!< Color Correction Matrix element [0][0]. + CAP_PROP_XI_CC_MATRIX_01 = 480, //!< Color Correction Matrix element [0][1]. + CAP_PROP_XI_CC_MATRIX_02 = 481, //!< Color Correction Matrix element [0][2]. + CAP_PROP_XI_CC_MATRIX_03 = 482, //!< Color Correction Matrix element [0][3]. + CAP_PROP_XI_CC_MATRIX_10 = 483, //!< Color Correction Matrix element [1][0]. + CAP_PROP_XI_CC_MATRIX_11 = 484, //!< Color Correction Matrix element [1][1]. + CAP_PROP_XI_CC_MATRIX_12 = 485, //!< Color Correction Matrix element [1][2]. + CAP_PROP_XI_CC_MATRIX_13 = 486, //!< Color Correction Matrix element [1][3]. + CAP_PROP_XI_CC_MATRIX_20 = 487, //!< Color Correction Matrix element [2][0]. + CAP_PROP_XI_CC_MATRIX_21 = 488, //!< Color Correction Matrix element [2][1]. + CAP_PROP_XI_CC_MATRIX_22 = 489, //!< Color Correction Matrix element [2][2]. + CAP_PROP_XI_CC_MATRIX_23 = 490, //!< Color Correction Matrix element [2][3]. + CAP_PROP_XI_CC_MATRIX_30 = 491, //!< Color Correction Matrix element [3][0]. + CAP_PROP_XI_CC_MATRIX_31 = 492, //!< Color Correction Matrix element [3][1]. + CAP_PROP_XI_CC_MATRIX_32 = 493, //!< Color Correction Matrix element [3][2]. + CAP_PROP_XI_CC_MATRIX_33 = 494, //!< Color Correction Matrix element [3][3]. + CAP_PROP_XI_DEFAULT_CC_MATRIX = 495, //!< Set default Color Correction Matrix. + CAP_PROP_XI_TRG_SELECTOR = 498, //!< Selects the type of trigger. + CAP_PROP_XI_ACQ_FRAME_BURST_COUNT = 499, //!< Sets number of frames acquired by burst. This burst is used only if trigger is set to FrameBurstStart. + CAP_PROP_XI_DEBOUNCE_EN = 507, //!< Enable/Disable debounce to selected GPI. + CAP_PROP_XI_DEBOUNCE_T0 = 508, //!< Debounce time (x * 10us). + CAP_PROP_XI_DEBOUNCE_T1 = 509, //!< Debounce time (x * 10us). + CAP_PROP_XI_DEBOUNCE_POL = 510, //!< Debounce polarity (pol = 1 t0 - falling edge, t1 - rising edge). + CAP_PROP_XI_LENS_MODE = 511, //!< Status of lens control interface. This shall be set to XI_ON before any Lens operations. + CAP_PROP_XI_LENS_APERTURE_VALUE = 512, //!< Current lens aperture value in stops. Examples: 2.8, 4, 5.6, 8, 11. + CAP_PROP_XI_LENS_FOCUS_MOVEMENT_VALUE = 513, //!< Lens current focus movement value to be used by XI_PRM_LENS_FOCUS_MOVE in motor steps. + CAP_PROP_XI_LENS_FOCUS_MOVE = 514, //!< Moves lens focus motor by steps set in XI_PRM_LENS_FOCUS_MOVEMENT_VALUE. + CAP_PROP_XI_LENS_FOCUS_DISTANCE = 515, //!< Lens focus distance in cm. + CAP_PROP_XI_LENS_FOCAL_LENGTH = 516, //!< Lens focal distance in mm. + CAP_PROP_XI_LENS_FEATURE_SELECTOR = 517, //!< Selects the current feature which is accessible by XI_PRM_LENS_FEATURE. + CAP_PROP_XI_LENS_FEATURE = 518, //!< Allows access to lens feature value currently selected by XI_PRM_LENS_FEATURE_SELECTOR. + CAP_PROP_XI_DEVICE_MODEL_ID = 521, //!< Returns device model id. + CAP_PROP_XI_DEVICE_SN = 522, //!< Returns device serial number. + CAP_PROP_XI_IMAGE_DATA_FORMAT_RGB32_ALPHA = 529, //!< The alpha channel of RGB32 output image format. + CAP_PROP_XI_IMAGE_PAYLOAD_SIZE = 530, //!< Buffer size in bytes sufficient for output image returned by xiGetImage. + CAP_PROP_XI_TRANSPORT_PIXEL_FORMAT = 531, //!< Current format of pixels on transport layer. + CAP_PROP_XI_SENSOR_CLOCK_FREQ_HZ = 532, //!< Sensor clock frequency in Hz. + CAP_PROP_XI_SENSOR_CLOCK_FREQ_INDEX = 533, //!< Sensor clock frequency index. Sensor with selected frequencies have possibility to set the frequency only by this index. + CAP_PROP_XI_SENSOR_OUTPUT_CHANNEL_COUNT = 534, //!< Number of output channels from sensor used for data transfer. + CAP_PROP_XI_FRAMERATE = 535, //!< Define framerate in Hz. + CAP_PROP_XI_COUNTER_SELECTOR = 536, //!< Select counter. + CAP_PROP_XI_COUNTER_VALUE = 537, //!< Counter status. + CAP_PROP_XI_ACQ_TIMING_MODE = 538, //!< Type of sensor frames timing. + CAP_PROP_XI_AVAILABLE_BANDWIDTH = 539, //!< Calculate and returns available interface bandwidth(int Megabits). + CAP_PROP_XI_BUFFER_POLICY = 540, //!< Data move policy. + CAP_PROP_XI_LUT_EN = 541, //!< Activates LUT. + CAP_PROP_XI_LUT_INDEX = 542, //!< Control the index (offset) of the coefficient to access in the LUT. + CAP_PROP_XI_LUT_VALUE = 543, //!< Value at entry LUTIndex of the LUT. + CAP_PROP_XI_TRG_DELAY = 544, //!< Specifies the delay in microseconds (us) to apply after the trigger reception before activating it. + CAP_PROP_XI_TS_RST_MODE = 545, //!< Defines how time stamp reset engine will be armed. + CAP_PROP_XI_TS_RST_SOURCE = 546, //!< Defines which source will be used for timestamp reset. Writing this parameter will trigger settings of engine (arming). + CAP_PROP_XI_IS_DEVICE_EXIST = 547, //!< Returns 1 if camera connected and works properly. + CAP_PROP_XI_ACQ_BUFFER_SIZE = 548, //!< Acquisition buffer size in buffer_size_unit. Default bytes. + CAP_PROP_XI_ACQ_BUFFER_SIZE_UNIT = 549, //!< Acquisition buffer size unit in bytes. Default 1. E.g. Value 1024 means that buffer_size is in KiBytes. + CAP_PROP_XI_ACQ_TRANSPORT_BUFFER_SIZE = 550, //!< Acquisition transport buffer size in bytes. + CAP_PROP_XI_BUFFERS_QUEUE_SIZE = 551, //!< Queue of field/frame buffers. + CAP_PROP_XI_ACQ_TRANSPORT_BUFFER_COMMIT = 552, //!< Number of buffers to commit to low level. + CAP_PROP_XI_RECENT_FRAME = 553, //!< GetImage returns most recent frame. + CAP_PROP_XI_DEVICE_RESET = 554, //!< Resets the camera to default state. + CAP_PROP_XI_COLUMN_FPN_CORRECTION = 555, //!< Correction of column FPN. + CAP_PROP_XI_ROW_FPN_CORRECTION = 591, //!< Correction of row FPN. + CAP_PROP_XI_SENSOR_MODE = 558, //!< Current sensor mode. Allows to select sensor mode by one integer. Setting of this parameter affects: image dimensions and downsampling. + CAP_PROP_XI_HDR = 559, //!< Enable High Dynamic Range feature. + CAP_PROP_XI_HDR_KNEEPOINT_COUNT = 560, //!< The number of kneepoints in the PWLR. + CAP_PROP_XI_HDR_T1 = 561, //!< Position of first kneepoint(in % of XI_PRM_EXPOSURE). + CAP_PROP_XI_HDR_T2 = 562, //!< Position of second kneepoint (in % of XI_PRM_EXPOSURE). + CAP_PROP_XI_KNEEPOINT1 = 563, //!< Value of first kneepoint (% of sensor saturation). + CAP_PROP_XI_KNEEPOINT2 = 564, //!< Value of second kneepoint (% of sensor saturation). + CAP_PROP_XI_IMAGE_BLACK_LEVEL = 565, //!< Last image black level counts. Can be used for Offline processing to recall it. + CAP_PROP_XI_HW_REVISION = 571, //!< Returns hardware revision number. + CAP_PROP_XI_DEBUG_LEVEL = 572, //!< Set debug level. + CAP_PROP_XI_AUTO_BANDWIDTH_CALCULATION = 573, //!< Automatic bandwidth calculation. + CAP_PROP_XI_FFS_FILE_ID = 594, //!< File number. + CAP_PROP_XI_FFS_FILE_SIZE = 580, //!< Size of file. + CAP_PROP_XI_FREE_FFS_SIZE = 581, //!< Size of free camera FFS. + CAP_PROP_XI_USED_FFS_SIZE = 582, //!< Size of used camera FFS. + CAP_PROP_XI_FFS_ACCESS_KEY = 583, //!< Setting of key enables file operations on some cameras. + CAP_PROP_XI_SENSOR_FEATURE_SELECTOR = 585, //!< Selects the current feature which is accessible by XI_PRM_SENSOR_FEATURE_VALUE. + CAP_PROP_XI_SENSOR_FEATURE_VALUE = 586, //!< Allows access to sensor feature value currently selected by XI_PRM_SENSOR_FEATURE_SELECTOR. + }; + +//! @} XIMEA + + +/** @name ARAVIS Camera API + @{ +*/ + +//! Properties of cameras available through ARAVIS backend +enum { CAP_PROP_ARAVIS_AUTOTRIGGER = 600 //!< Automatically trigger frame capture if camera is configured with software trigger +}; + +//! @} ARAVIS + + +/** @name Android + @{ +*/ + +//! Properties of cameras available through NDK Camera API backend +enum { CAP_PROP_ANDROID_DEVICE_TORCH = 8001, + }; + +//! @} Android + + +/** @name AVFoundation framework for iOS + @{ +*/ + +//! Properties of cameras available through AVFOUNDATION backend +enum { CAP_PROP_IOS_DEVICE_FOCUS = 9001, + CAP_PROP_IOS_DEVICE_EXPOSURE = 9002, + CAP_PROP_IOS_DEVICE_FLASH = 9003, + CAP_PROP_IOS_DEVICE_WHITEBALANCE = 9004, + CAP_PROP_IOS_DEVICE_TORCH = 9005 + }; + +//! @} AVFoundation framework for iOS + + +/** @name Smartek Giganetix GigEVisionSDK + @{ +*/ + +//! Properties of cameras available through Smartek Giganetix Ethernet Vision backend +/* --- Vladimir Litvinenko (litvinenko.vladimir@gmail.com) --- */ +enum { CAP_PROP_GIGA_FRAME_OFFSET_X = 10001, + CAP_PROP_GIGA_FRAME_OFFSET_Y = 10002, + CAP_PROP_GIGA_FRAME_WIDTH_MAX = 10003, + CAP_PROP_GIGA_FRAME_HEIGH_MAX = 10004, + CAP_PROP_GIGA_FRAME_SENS_WIDTH = 10005, + CAP_PROP_GIGA_FRAME_SENS_HEIGH = 10006 + }; + +//! @} Smartek + +/** @name Intel Perceptual Computing SDK + @{ +*/ +enum { CAP_PROP_INTELPERC_PROFILE_COUNT = 11001, + CAP_PROP_INTELPERC_PROFILE_IDX = 11002, + CAP_PROP_INTELPERC_DEPTH_LOW_CONFIDENCE_VALUE = 11003, + CAP_PROP_INTELPERC_DEPTH_SATURATION_VALUE = 11004, + CAP_PROP_INTELPERC_DEPTH_CONFIDENCE_THRESHOLD = 11005, + CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_HORZ = 11006, + CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_VERT = 11007 + }; + +//! Intel Perceptual Streams +enum { CAP_INTELPERC_DEPTH_GENERATOR = 1 << 29, + CAP_INTELPERC_IMAGE_GENERATOR = 1 << 28, + CAP_INTELPERC_IR_GENERATOR = 1 << 27, + CAP_INTELPERC_GENERATORS_MASK = CAP_INTELPERC_DEPTH_GENERATOR + CAP_INTELPERC_IMAGE_GENERATOR + CAP_INTELPERC_IR_GENERATOR + }; + +enum { CAP_INTELPERC_DEPTH_MAP = 0, //!< Each pixel is a 16-bit integer. The value indicates the distance from an object to the camera's XY plane or the Cartesian depth. + CAP_INTELPERC_UVDEPTH_MAP = 1, //!< Each pixel contains two 32-bit floating point values in the range of 0-1, representing the mapping of depth coordinates to the color coordinates. + CAP_INTELPERC_IR_MAP = 2, //!< Each pixel is a 16-bit integer. The value indicates the intensity of the reflected laser beam. + CAP_INTELPERC_IMAGE = 3 + }; + +//! @} Intel Perceptual + +/** @name gPhoto2 connection + @{ +*/ + +/** @brief gPhoto2 properties + +If `propertyId` is less than 0 then work on widget with that __additive inversed__ camera setting ID +Get IDs by using CAP_PROP_GPHOTO2_WIDGET_ENUMERATE. +@see CvCaptureCAM_GPHOTO2 for more info +*/ +enum { CAP_PROP_GPHOTO2_PREVIEW = 17001, //!< Capture only preview from liveview mode. + CAP_PROP_GPHOTO2_WIDGET_ENUMERATE = 17002, //!< Readonly, returns (const char *). + CAP_PROP_GPHOTO2_RELOAD_CONFIG = 17003, //!< Trigger, only by set. Reload camera settings. + CAP_PROP_GPHOTO2_RELOAD_ON_CHANGE = 17004, //!< Reload all settings on set. + CAP_PROP_GPHOTO2_COLLECT_MSGS = 17005, //!< Collect messages with details. + CAP_PROP_GPHOTO2_FLUSH_MSGS = 17006, //!< Readonly, returns (const char *). + CAP_PROP_SPEED = 17007, //!< Exposure speed. Can be readonly, depends on camera program. + CAP_PROP_APERTURE = 17008, //!< Aperture. Can be readonly, depends on camera program. + CAP_PROP_EXPOSUREPROGRAM = 17009, //!< Camera exposure program. + CAP_PROP_VIEWFINDER = 17010 //!< Enter liveview mode. + }; + +//! @} gPhoto2 + + +/** @name Images backend + @{ +*/ + +/** @brief Images backend properties + +*/ +enum { CAP_PROP_IMAGES_BASE = 18000, + CAP_PROP_IMAGES_LAST = 19000 // excluding + }; + +//! @} Images + +/** @name OBSENSOR (for Orbbec 3D-Sensor device/module ) + @{ +*/ +//! OBSENSOR data given from image generator +enum VideoCaptureOBSensorDataType{ + CAP_OBSENSOR_DEPTH_MAP = 0, //!< Depth values in mm (CV_16UC1) + CAP_OBSENSOR_BGR_IMAGE = 1, //!< Data given from BGR stream generator + CAP_OBSENSOR_IR_IMAGE = 2 //!< Data given from IR stream generator(CV_16UC1) +}; + +//! OBSENSOR stream generator +enum VideoCaptureOBSensorGenerators{ + CAP_OBSENSOR_DEPTH_GENERATOR = 1 << 29, + CAP_OBSENSOR_IMAGE_GENERATOR = 1 << 28, + CAP_OBSENSOR_IR_GENERATOR = 1 << 27, + CAP_OBSENSOR_GENERATORS_MASK = CAP_OBSENSOR_DEPTH_GENERATOR + CAP_OBSENSOR_IMAGE_GENERATOR + CAP_OBSENSOR_IR_GENERATOR +}; + +//!OBSENSOR properties +enum VideoCaptureOBSensorProperties{ + // INTRINSIC + CAP_PROP_OBSENSOR_INTRINSIC_FX=26001, + CAP_PROP_OBSENSOR_INTRINSIC_FY=26002, + CAP_PROP_OBSENSOR_INTRINSIC_CX=26003, + CAP_PROP_OBSENSOR_INTRINSIC_CY=26004, +}; + +//! @} OBSENSOR + +//! @} videoio_flags_others + +/** @brief Read data stream interface + */ +class CV_EXPORTS_W IStreamReader +{ +public: + virtual ~IStreamReader(); + + /** @brief Read bytes from stream */ + virtual long long read(char* buffer, long long size) = 0; + + /** @brief Sets the stream position + * + * @param offset Seek offset + * @param origin SEEK_SET / SEEK_END / SEEK_CUR + * + * @see fseek + */ + virtual long long seek(long long offset, int origin) = 0; +}; + +class IVideoCapture; +//! @cond IGNORED +namespace internal { class VideoCapturePrivateAccessor; } +//! @endcond IGNORED + +/** @brief Class for video capturing from video files, image sequences or cameras. + +The class provides C++ API for capturing video from cameras or for reading video files and image sequences. + +Here is how the class can be used: +@include samples/cpp/videocapture_basic.cpp + +@note In @ref videoio_c "C API" the black-box structure `CvCapture` is used instead of %VideoCapture. +@note +- (C++) A basic sample on using the %VideoCapture interface can be found at + `OPENCV_SOURCE_CODE/samples/cpp/videocapture_starter.cpp` +- (Python) A basic sample on using the %VideoCapture interface can be found at + `OPENCV_SOURCE_CODE/samples/python/video.py` +- (Python) A multi threaded video processing sample can be found at + `OPENCV_SOURCE_CODE/samples/python/video_threaded.py` +- (Python) %VideoCapture sample showcasing some features of the Video4Linux2 backend + `OPENCV_SOURCE_CODE/samples/python/video_v4l2.py` + */ +class CV_EXPORTS_W VideoCapture +{ +public: + /** @brief Default constructor + @note In @ref videoio_c "C API", when you finished working with video, release CvCapture structure with + cvReleaseCapture(), or use Ptr\ that calls cvReleaseCapture() automatically in the + destructor. + */ + CV_WRAP VideoCapture(); + + /** @overload + @brief Opens a video file or a capturing device or an IP video stream for video capturing with API Preference + + @param filename it can be: + - name of video file (eg. `video.avi`) + - or image sequence (eg. `img_%02d.jpg`, which will read samples like `img_00.jpg, img_01.jpg, img_02.jpg, ...`) + - or URL of video stream (eg. `protocol://host:port/script_name?script_params|auth`) + - or GStreamer pipeline string in gst-launch tool format in case if GStreamer is used as backend + Note that each video stream or IP camera feed has its own URL scheme. Please refer to the + documentation of source stream to know the right URL. + @param apiPreference preferred Capture API backends to use. Can be used to enforce a specific reader + implementation if multiple are available: e.g. cv::CAP_FFMPEG or cv::CAP_IMAGES or cv::CAP_DSHOW. + + @sa cv::VideoCaptureAPIs + */ + CV_WRAP explicit VideoCapture(const String& filename, int apiPreference = CAP_ANY); + + /** @overload + @brief Opens a video file or a capturing device or an IP video stream for video capturing with API Preference and parameters + + The `params` parameter allows to specify extra parameters encoded as pairs `(paramId_1, paramValue_1, paramId_2, paramValue_2, ...)`. + See cv::VideoCaptureProperties + */ + CV_WRAP explicit VideoCapture(const String& filename, int apiPreference, const std::vector& params); + + /** @overload + @brief Opens a camera for video capturing + + @param index id of the video capturing device to open. To open default camera using default backend just pass 0. + (to backward compatibility usage of camera_id + domain_offset (CAP_*) is valid when apiPreference is CAP_ANY) + @param apiPreference preferred Capture API backends to use. Can be used to enforce a specific reader + implementation if multiple are available: e.g. cv::CAP_DSHOW or cv::CAP_MSMF or cv::CAP_V4L. + + @sa cv::VideoCaptureAPIs + */ + CV_WRAP explicit VideoCapture(int index, int apiPreference = CAP_ANY); + + /** @overload + @brief Opens a camera for video capturing with API Preference and parameters + + The `params` parameter allows to specify extra parameters encoded as pairs `(paramId_1, paramValue_1, paramId_2, paramValue_2, ...)`. + See cv::VideoCaptureProperties + */ + CV_WRAP explicit VideoCapture(int index, int apiPreference, const std::vector& params); + + /** @overload + @brief Opens a video using data stream. + + The `params` parameter allows to specify extra parameters encoded as pairs `(paramId_1, paramValue_1, paramId_2, paramValue_2, ...)`. + See cv::VideoCaptureProperties + */ + CV_WRAP VideoCapture(const Ptr& source, int apiPreference, const std::vector& params); + + /** @brief Default destructor + + The method first calls VideoCapture::release to close the already opened file or camera. + */ + virtual ~VideoCapture(); + + /** @brief Opens a video file or a capturing device or an IP video stream for video capturing. + + @overload + + Parameters are same as the constructor VideoCapture(const String& filename, int apiPreference = CAP_ANY) + @return `true` if the file has been successfully opened + + The method first calls VideoCapture::release to close the already opened file or camera. + */ + CV_WRAP virtual bool open(const String& filename, int apiPreference = CAP_ANY); + + /** @brief Opens a video file or a capturing device or an IP video stream for video capturing with API Preference and parameters + + @overload + + The `params` parameter allows to specify extra parameters encoded as pairs `(paramId_1, paramValue_1, paramId_2, paramValue_2, ...)`. + See cv::VideoCaptureProperties + + @return `true` if the file has been successfully opened + + The method first calls VideoCapture::release to close the already opened file or camera. + */ + CV_WRAP virtual bool open(const String& filename, int apiPreference, const std::vector& params); + + /** @brief Opens a camera for video capturing + + @overload + + Parameters are same as the constructor VideoCapture(int index, int apiPreference = CAP_ANY) + @return `true` if the camera has been successfully opened. + + The method first calls VideoCapture::release to close the already opened file or camera. + */ + CV_WRAP virtual bool open(int index, int apiPreference = CAP_ANY); + + /** @brief Opens a camera for video capturing with API Preference and parameters + + @overload + + The `params` parameter allows to specify extra parameters encoded as pairs `(paramId_1, paramValue_1, paramId_2, paramValue_2, ...)`. + See cv::VideoCaptureProperties + + @return `true` if the camera has been successfully opened. + + The method first calls VideoCapture::release to close the already opened file or camera. + */ + CV_WRAP virtual bool open(int index, int apiPreference, const std::vector& params); + + /** @brief Opens a video using data stream. + + @overload + + The `params` parameter allows to specify extra parameters encoded as pairs `(paramId_1, paramValue_1, paramId_2, paramValue_2, ...)`. + See cv::VideoCaptureProperties + + @return `true` if the file has been successfully opened + + The method first calls VideoCapture::release to close the already opened file or camera. + */ + CV_WRAP virtual bool open(const Ptr& source, int apiPreference, const std::vector& params); + + /** @brief Returns true if video capturing has been initialized already. + + If the previous call to VideoCapture constructor or VideoCapture::open() succeeded, the method returns + true. + */ + CV_WRAP virtual bool isOpened() const; + + /** @brief Closes video file or capturing device. + + The method is automatically called by subsequent VideoCapture::open and by VideoCapture + destructor. + + The C function also deallocates memory and clears \*capture pointer. + */ + CV_WRAP virtual void release(); + + /** @brief Grabs the next frame from video file or capturing device. + + @return `true` (non-zero) in the case of success. + + The method/function grabs the next frame from video file or camera and returns true (non-zero) in + the case of success. + + The primary use of the function is in multi-camera environments, especially when the cameras do not + have hardware synchronization. That is, you call VideoCapture::grab() for each camera and after that + call the slower method VideoCapture::retrieve() to decode and get frame from each camera. This way + the overhead on demosaicing or motion jpeg decompression etc. is eliminated and the retrieved frames + from different cameras will be closer in time. + + Also, when a connected camera is multi-head (for example, a stereo camera or a Kinect device), the + correct way of retrieving data from it is to call VideoCapture::grab() first and then call + VideoCapture::retrieve() one or more times with different values of the channel parameter. + + @ref tutorial_kinect_openni + */ + CV_WRAP virtual bool grab(); + + /** @brief Decodes and returns the grabbed video frame. + + @param [out] image the video frame is returned here. If no frames has been grabbed the image will be empty. + @param flag it could be a frame index or a driver specific flag + @return `false` if no frames has been grabbed + + The method decodes and returns the just grabbed frame. If no frames has been grabbed + (camera has been disconnected, or there are no more frames in video file), the method returns false + and the function returns an empty image (with %cv::Mat, test it with Mat::empty()). + + @sa read() + + @note In @ref videoio_c "C API", functions cvRetrieveFrame() and cv.RetrieveFrame() return image stored inside the video + capturing structure. It is not allowed to modify or release the image! You can copy the frame using + cvCloneImage and then do whatever you want with the copy. + */ + CV_WRAP virtual bool retrieve(OutputArray image, int flag = 0); + + /** @brief Stream operator to read the next video frame. + @sa read() + */ + virtual VideoCapture& operator >> (CV_OUT Mat& image); + + /** @overload + @sa read() + */ + virtual VideoCapture& operator >> (CV_OUT UMat& image); + + /** @brief Grabs, decodes and returns the next video frame. + + @param [out] image the video frame is returned here. If no frames has been grabbed the image will be empty. + @return `false` if no frames has been grabbed + + The method/function combines VideoCapture::grab() and VideoCapture::retrieve() in one call. This is the + most convenient method for reading video files or capturing data from decode and returns the just + grabbed frame. If no frames has been grabbed (camera has been disconnected, or there are no more + frames in video file), the method returns false and the function returns empty image (with %cv::Mat, test it with Mat::empty()). + + @note In @ref videoio_c "C API", functions cvRetrieveFrame() and cv.RetrieveFrame() return image stored inside the video + capturing structure. It is not allowed to modify or release the image! You can copy the frame using + cvCloneImage and then do whatever you want with the copy. + */ + CV_WRAP virtual bool read(OutputArray image); + + /** @brief Sets a property in the VideoCapture. + + @param propId Property identifier from cv::VideoCaptureProperties (eg. cv::CAP_PROP_POS_MSEC, cv::CAP_PROP_POS_FRAMES, ...) + or one from @ref videoio_flags_others + @param value Value of the property. + @return `true` if the property is supported by backend used by the VideoCapture instance. + @note Even if it returns `true` this doesn't ensure that the property + value has been accepted by the capture device. See note in VideoCapture::get() + */ + CV_WRAP virtual bool set(int propId, double value); + + /** @brief Returns the specified VideoCapture property + + @param propId Property identifier from cv::VideoCaptureProperties (eg. cv::CAP_PROP_POS_MSEC, cv::CAP_PROP_POS_FRAMES, ...) + or one from @ref videoio_flags_others + @return Value for the specified property. Value 0 is returned when querying a property that is + not supported by the backend used by the VideoCapture instance. + + @note Reading / writing properties involves many layers. Some unexpected result might happens + along this chain. + @code{.txt} + VideoCapture -> API Backend -> Operating System -> Device Driver -> Device Hardware + @endcode + The returned value might be different from what really used by the device or it could be encoded + using device dependent rules (eg. steps or percentage). Effective behaviour depends from device + driver and API Backend + + */ + CV_WRAP virtual double get(int propId) const; + + /** @brief Returns used backend API name + + @note Stream should be opened. + */ + CV_WRAP String getBackendName() const; + + /** Switches exceptions mode + * + * methods raise exceptions if not successful instead of returning an error code + */ + CV_WRAP void setExceptionMode(bool enable) { throwOnFail = enable; } + + /// query if exception mode is active + CV_WRAP bool getExceptionMode() const { return throwOnFail; } + + + /** @brief Wait for ready frames from VideoCapture. + + @param streams input video streams + @param readyIndex stream indexes with grabbed frames (ready to use .retrieve() to fetch actual frame) + @param timeoutNs number of nanoseconds (0 - infinite) + @return `true` if streamReady is not empty + + @throws Exception %Exception on stream errors (check .isOpened() to filter out malformed streams) or VideoCapture type is not supported + + The primary use of the function is in multi-camera environments. + The method fills the ready state vector, grabs video frame, if camera is ready. + + After this call use VideoCapture::retrieve() to decode and fetch frame data. + */ + CV_WRAP static + bool waitAny( + const std::vector& streams, + CV_OUT std::vector& readyIndex, + int64 timeoutNs = 0); + +protected: + Ptr cap; + Ptr icap; + bool throwOnFail; + + friend class internal::VideoCapturePrivateAccessor; +}; + +class IVideoWriter; + +/** @example samples/cpp/tutorial_code/videoio/video-write/video-write.cpp +Check @ref tutorial_video_write "the corresponding tutorial" for more details +*/ + +/** @example samples/cpp/videowriter_basic.cpp +An example using VideoCapture and VideoWriter class +*/ + +/** @brief Video writer class. + +The class provides C++ API for writing video files or image sequences. +*/ +class CV_EXPORTS_W VideoWriter +{ +public: + /** @brief Default constructors + + The constructors/functions initialize video writers. + - On Linux FFMPEG is used to write videos; + - On Windows FFMPEG or MSWF or DSHOW is used; + - On MacOSX AVFoundation is used. + */ + CV_WRAP VideoWriter(); + + /** @overload + @param filename Name of the output video file. + @param fourcc 4-character code of codec used to compress the frames. For example, + VideoWriter::fourcc('P','I','M','1') is a MPEG-1 codec, VideoWriter::fourcc('M','J','P','G') + is a motion-jpeg codec etc. List of codes can be obtained at + [MSDN](https://docs.microsoft.com/en-us/windows/win32/medfound/video-fourccs) page + or with this [page](https://fourcc.org/codecs.php) + of the fourcc site for a more complete list). FFMPEG backend with MP4 container natively uses + other values as fourcc code: see [ObjectType](http://mp4ra.org/#/codecs), + so you may receive a warning message from OpenCV about fourcc code conversion. + @param fps Framerate of the created video stream. + @param frameSize Size of the video frames. + @param isColor If it is not zero, the encoder will expect and encode color frames, otherwise it + will work with grayscale frames. + + @b Tips: + - With some backends `fourcc=-1` pops up the codec selection dialog from the system. + - To save image sequence use a proper filename (eg. `img_%02d.jpg`) and `fourcc=0` + OR `fps=0`. Use uncompressed image format (eg. `img_%02d.BMP`) to save raw frames. + - Most codecs are lossy. If you want lossless video file you need to use a lossless codecs + (eg. FFMPEG FFV1, Huffman HFYU, Lagarith LAGS, etc...) + - If FFMPEG is enabled, using `codec=0; fps=0;` you can create an uncompressed (raw) video file. + - If FFMPEG is used, we allow frames of odd width or height, but in this case we truncate + the rightmost column/the bottom row. Probably, this should be handled more elegantly, + but some internal functions inside FFMPEG swscale require even width/height. + */ + CV_WRAP VideoWriter(const String& filename, int fourcc, double fps, + Size frameSize, bool isColor = true); + + /** @overload + The `apiPreference` parameter allows to specify API backends to use. Can be used to enforce a specific reader implementation + if multiple are available: e.g. cv::CAP_FFMPEG or cv::CAP_GSTREAMER. + */ + CV_WRAP VideoWriter(const String& filename, int apiPreference, int fourcc, double fps, + Size frameSize, bool isColor = true); + + /** @overload + * The `params` parameter allows to specify extra encoder parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, ... .) + * see cv::VideoWriterProperties + */ + CV_WRAP VideoWriter(const String& filename, int fourcc, double fps, const Size& frameSize, + const std::vector& params); + + /** @overload + */ + CV_WRAP VideoWriter(const String& filename, int apiPreference, int fourcc, double fps, + const Size& frameSize, const std::vector& params); + + /** @brief Default destructor + + The method first calls VideoWriter::release to close the already opened file. + */ + virtual ~VideoWriter(); + + /** @brief Initializes or reinitializes video writer. + + The method opens video writer. Parameters are the same as in the constructor + VideoWriter::VideoWriter. + @return `true` if video writer has been successfully initialized + + The method first calls VideoWriter::release to close the already opened file. + */ + CV_WRAP virtual bool open(const String& filename, int fourcc, double fps, + Size frameSize, bool isColor = true); + + /** @overload + */ + CV_WRAP bool open(const String& filename, int apiPreference, int fourcc, double fps, + Size frameSize, bool isColor = true); + + /** @overload + */ + CV_WRAP bool open(const String& filename, int fourcc, double fps, const Size& frameSize, + const std::vector& params); + + /** @overload + */ + CV_WRAP bool open(const String& filename, int apiPreference, int fourcc, double fps, + const Size& frameSize, const std::vector& params); + + /** @brief Returns true if video writer has been successfully initialized. + */ + CV_WRAP virtual bool isOpened() const; + + /** @brief Closes the video writer. + + The method is automatically called by subsequent VideoWriter::open and by the VideoWriter + destructor. + */ + CV_WRAP virtual void release(); + + /** @brief Stream operator to write the next video frame. + @sa write + */ + virtual VideoWriter& operator << (const Mat& image); + + /** @overload + @sa write + */ + virtual VideoWriter& operator << (const UMat& image); + + /** @brief Writes the next video frame + + @param image The written frame. In general, color images are expected in BGR format. + + The function/method writes the specified image to video file. It must have the same size as has + been specified when opening the video writer. + */ + CV_WRAP virtual void write(InputArray image); + + /** @brief Sets a property in the VideoWriter. + + @param propId Property identifier from cv::VideoWriterProperties (eg. cv::VIDEOWRITER_PROP_QUALITY) + or one of @ref videoio_flags_others + + @param value Value of the property. + @return `true` if the property is supported by the backend used by the VideoWriter instance. + */ + CV_WRAP virtual bool set(int propId, double value); + + /** @brief Returns the specified VideoWriter property + + @param propId Property identifier from cv::VideoWriterProperties (eg. cv::VIDEOWRITER_PROP_QUALITY) + or one of @ref videoio_flags_others + + @return Value for the specified property. Value 0 is returned when querying a property that is + not supported by the backend used by the VideoWriter instance. + */ + CV_WRAP virtual double get(int propId) const; + + /** @brief Concatenates 4 chars to a fourcc code + + @return a fourcc code + + This static method constructs the fourcc code of the codec to be used in the constructor + VideoWriter::VideoWriter or VideoWriter::open. + */ + CV_WRAP static int fourcc(char c1, char c2, char c3, char c4); + + /** @brief Returns used backend API name + + @note Stream should be opened. + */ + CV_WRAP String getBackendName() const; + +protected: + Ptr writer; + Ptr iwriter; + + static Ptr create(const String& filename, int fourcc, double fps, + Size frameSize, bool isColor = true); +}; + +//! @cond IGNORED +template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvCapture* obj) const; }; +template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvVideoWriter* obj) const; }; +//! @endcond IGNORED + +//! @} videoio + +} // cv + +#endif //OPENCV_VIDEOIO_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/videoio/legacy/constants_c.h b/3rdParty/opencv-4.11.0/opencv2/videoio/legacy/constants_c.h index 6bdcc2690b..191cfed7d9 100644 --- a/3rdParty/opencv-4.11.0/opencv2/videoio/legacy/constants_c.h +++ b/3rdParty/opencv-4.11.0/opencv2/videoio/legacy/constants_c.h @@ -1,420 +1,420 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_VIDEOIO_LEGACY_CONSTANTS_H -#define OPENCV_VIDEOIO_LEGACY_CONSTANTS_H - -#include "opencv2/core/cvdef.h" - -enum -{ - CV_CAP_ANY =0, // autodetect - - CV_CAP_MIL =100, // MIL proprietary drivers - - CV_CAP_VFW =200, // platform native - CV_CAP_V4L =200, - CV_CAP_V4L2 =200, - - CV_CAP_FIREWARE =300, // IEEE 1394 drivers - CV_CAP_FIREWIRE =300, - CV_CAP_IEEE1394 =300, - CV_CAP_DC1394 =300, - CV_CAP_CMU1394 =300, - - CV_CAP_STEREO =400, // TYZX proprietary drivers - CV_CAP_TYZX =400, - CV_TYZX_LEFT =400, - CV_TYZX_RIGHT =401, - CV_TYZX_COLOR =402, - CV_TYZX_Z =403, - - CV_CAP_QT =500, // QuickTime - - CV_CAP_UNICAP =600, // Unicap drivers - - CV_CAP_DSHOW =700, // DirectShow (via videoInput) - CV_CAP_MSMF =1400, // Microsoft Media Foundation (via videoInput) - - CV_CAP_PVAPI =800, // PvAPI, Prosilica GigE SDK - - CV_CAP_OPENNI =900, // OpenNI (for Kinect) - CV_CAP_OPENNI_ASUS =910, // OpenNI (for Asus Xtion) - - CV_CAP_ANDROID =1000, // Android - not used - CV_CAP_ANDROID_BACK =CV_CAP_ANDROID+99, // Android back camera - not used - CV_CAP_ANDROID_FRONT =CV_CAP_ANDROID+98, // Android front camera - not used - - CV_CAP_XIAPI =1100, // XIMEA Camera API - - CV_CAP_AVFOUNDATION = 1200, // AVFoundation framework for iOS (OS X Lion will have the same API) - - CV_CAP_GIGANETIX = 1300, // Smartek Giganetix GigEVisionSDK - - CV_CAP_INTELPERC = 1500, // Intel Perceptual Computing - - CV_CAP_OPENNI2 = 1600, // OpenNI2 (for Kinect) - CV_CAP_GPHOTO2 = 1700, - CV_CAP_GSTREAMER = 1800, // GStreamer - CV_CAP_FFMPEG = 1900, // FFMPEG - CV_CAP_IMAGES = 2000, // OpenCV Image Sequence (e.g. img_%02d.jpg) - - CV_CAP_ARAVIS = 2100 // Aravis GigE SDK -}; - -enum -{ - // modes of the controlling registers (can be: auto, manual, auto single push, absolute Latter allowed with any other mode) - // every feature can have only one mode turned on at a time - CV_CAP_PROP_DC1394_OFF = -4, //turn the feature off (not controlled manually nor automatically) - CV_CAP_PROP_DC1394_MODE_MANUAL = -3, //set automatically when a value of the feature is set by the user - CV_CAP_PROP_DC1394_MODE_AUTO = -2, - CV_CAP_PROP_DC1394_MODE_ONE_PUSH_AUTO = -1, - CV_CAP_PROP_POS_MSEC =0, - CV_CAP_PROP_POS_FRAMES =1, - CV_CAP_PROP_POS_AVI_RATIO =2, - CV_CAP_PROP_FRAME_WIDTH =3, - CV_CAP_PROP_FRAME_HEIGHT =4, - CV_CAP_PROP_FPS =5, - CV_CAP_PROP_FOURCC =6, - CV_CAP_PROP_FRAME_COUNT =7, - CV_CAP_PROP_FORMAT =8, - CV_CAP_PROP_MODE =9, - CV_CAP_PROP_BRIGHTNESS =10, - CV_CAP_PROP_CONTRAST =11, - CV_CAP_PROP_SATURATION =12, - CV_CAP_PROP_HUE =13, - CV_CAP_PROP_GAIN =14, - CV_CAP_PROP_EXPOSURE =15, - CV_CAP_PROP_CONVERT_RGB =16, - CV_CAP_PROP_WHITE_BALANCE_BLUE_U =17, - CV_CAP_PROP_RECTIFICATION =18, - CV_CAP_PROP_MONOCHROME =19, - CV_CAP_PROP_SHARPNESS =20, - CV_CAP_PROP_AUTO_EXPOSURE =21, // exposure control done by camera, - // user can adjust reference level - // using this feature - CV_CAP_PROP_GAMMA =22, - CV_CAP_PROP_TEMPERATURE =23, - CV_CAP_PROP_TRIGGER =24, - CV_CAP_PROP_TRIGGER_DELAY =25, - CV_CAP_PROP_WHITE_BALANCE_RED_V =26, - CV_CAP_PROP_ZOOM =27, - CV_CAP_PROP_FOCUS =28, - CV_CAP_PROP_GUID =29, - CV_CAP_PROP_ISO_SPEED =30, - CV_CAP_PROP_MAX_DC1394 =31, - CV_CAP_PROP_BACKLIGHT =32, - CV_CAP_PROP_PAN =33, - CV_CAP_PROP_TILT =34, - CV_CAP_PROP_ROLL =35, - CV_CAP_PROP_IRIS =36, - CV_CAP_PROP_SETTINGS =37, - CV_CAP_PROP_BUFFERSIZE =38, - CV_CAP_PROP_AUTOFOCUS =39, - CV_CAP_PROP_SAR_NUM =40, - CV_CAP_PROP_SAR_DEN =41, - - CV_CAP_PROP_AUTOGRAB =1024, // property for videoio class CvCapture_Android only - CV_CAP_PROP_SUPPORTED_PREVIEW_SIZES_STRING=1025, // readonly, tricky property, returns cpnst char* indeed - CV_CAP_PROP_PREVIEW_FORMAT=1026, // readonly, tricky property, returns cpnst char* indeed - - // OpenNI map generators - CV_CAP_OPENNI_DEPTH_GENERATOR = 1 << 31, - CV_CAP_OPENNI_IMAGE_GENERATOR = 1 << 30, - CV_CAP_OPENNI_IR_GENERATOR = 1 << 29, - CV_CAP_OPENNI_GENERATORS_MASK = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_OPENNI_IR_GENERATOR, - - // Properties of cameras available through OpenNI interfaces - CV_CAP_PROP_OPENNI_OUTPUT_MODE = 100, - CV_CAP_PROP_OPENNI_FRAME_MAX_DEPTH = 101, // in mm - CV_CAP_PROP_OPENNI_BASELINE = 102, // in mm - CV_CAP_PROP_OPENNI_FOCAL_LENGTH = 103, // in pixels - CV_CAP_PROP_OPENNI_REGISTRATION = 104, // flag - CV_CAP_PROP_OPENNI_REGISTRATION_ON = CV_CAP_PROP_OPENNI_REGISTRATION, // flag that synchronizes the remapping depth map to image map - // by changing depth generator's view point (if the flag is "on") or - // sets this view point to its normal one (if the flag is "off"). - CV_CAP_PROP_OPENNI_APPROX_FRAME_SYNC = 105, - CV_CAP_PROP_OPENNI_MAX_BUFFER_SIZE = 106, - CV_CAP_PROP_OPENNI_CIRCLE_BUFFER = 107, - CV_CAP_PROP_OPENNI_MAX_TIME_DURATION = 108, - - CV_CAP_PROP_OPENNI_GENERATOR_PRESENT = 109, - CV_CAP_PROP_OPENNI2_SYNC = 110, - CV_CAP_PROP_OPENNI2_MIRROR = 111, - - CV_CAP_OPENNI_IMAGE_GENERATOR_PRESENT = CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_PROP_OPENNI_GENERATOR_PRESENT, - CV_CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE = CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_PROP_OPENNI_OUTPUT_MODE, - CV_CAP_OPENNI_DEPTH_GENERATOR_PRESENT = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_GENERATOR_PRESENT, - CV_CAP_OPENNI_DEPTH_GENERATOR_BASELINE = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_BASELINE, - CV_CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_FOCAL_LENGTH, - CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_REGISTRATION, - CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION_ON = CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION, - CV_CAP_OPENNI_IR_GENERATOR_PRESENT = CV_CAP_OPENNI_IR_GENERATOR + CV_CAP_PROP_OPENNI_GENERATOR_PRESENT, - - // Properties of cameras available through GStreamer interface - CV_CAP_GSTREAMER_QUEUE_LENGTH = 200, // default is 1 - - // PVAPI - CV_CAP_PROP_PVAPI_MULTICASTIP = 300, // ip for anable multicast master mode. 0 for disable multicast - CV_CAP_PROP_PVAPI_FRAMESTARTTRIGGERMODE = 301, // FrameStartTriggerMode: Determines how a frame is initiated - CV_CAP_PROP_PVAPI_DECIMATIONHORIZONTAL = 302, // Horizontal sub-sampling of the image - CV_CAP_PROP_PVAPI_DECIMATIONVERTICAL = 303, // Vertical sub-sampling of the image - CV_CAP_PROP_PVAPI_BINNINGX = 304, // Horizontal binning factor - CV_CAP_PROP_PVAPI_BINNINGY = 305, // Vertical binning factor - CV_CAP_PROP_PVAPI_PIXELFORMAT = 306, // Pixel format - - // Properties of cameras available through XIMEA SDK interface - CV_CAP_PROP_XI_DOWNSAMPLING = 400, // Change image resolution by binning or skipping. - CV_CAP_PROP_XI_DATA_FORMAT = 401, // Output data format. - CV_CAP_PROP_XI_OFFSET_X = 402, // Horizontal offset from the origin to the area of interest (in pixels). - CV_CAP_PROP_XI_OFFSET_Y = 403, // Vertical offset from the origin to the area of interest (in pixels). - CV_CAP_PROP_XI_TRG_SOURCE = 404, // Defines source of trigger. - CV_CAP_PROP_XI_TRG_SOFTWARE = 405, // Generates an internal trigger. PRM_TRG_SOURCE must be set to TRG_SOFTWARE. - CV_CAP_PROP_XI_GPI_SELECTOR = 406, // Selects general purpose input - CV_CAP_PROP_XI_GPI_MODE = 407, // Set general purpose input mode - CV_CAP_PROP_XI_GPI_LEVEL = 408, // Get general purpose level - CV_CAP_PROP_XI_GPO_SELECTOR = 409, // Selects general purpose output - CV_CAP_PROP_XI_GPO_MODE = 410, // Set general purpose output mode - CV_CAP_PROP_XI_LED_SELECTOR = 411, // Selects camera signalling LED - CV_CAP_PROP_XI_LED_MODE = 412, // Define camera signalling LED functionality - CV_CAP_PROP_XI_MANUAL_WB = 413, // Calculates White Balance(must be called during acquisition) - CV_CAP_PROP_XI_AUTO_WB = 414, // Automatic white balance - CV_CAP_PROP_XI_AEAG = 415, // Automatic exposure/gain - CV_CAP_PROP_XI_EXP_PRIORITY = 416, // Exposure priority (0.5 - exposure 50%, gain 50%). - CV_CAP_PROP_XI_AE_MAX_LIMIT = 417, // Maximum limit of exposure in AEAG procedure - CV_CAP_PROP_XI_AG_MAX_LIMIT = 418, // Maximum limit of gain in AEAG procedure - CV_CAP_PROP_XI_AEAG_LEVEL = 419, // Average intensity of output signal AEAG should achieve(in %) - CV_CAP_PROP_XI_TIMEOUT = 420, // Image capture timeout in milliseconds - CV_CAP_PROP_XI_EXPOSURE = 421, // Exposure time in microseconds - CV_CAP_PROP_XI_EXPOSURE_BURST_COUNT = 422, // Sets the number of times of exposure in one frame. - CV_CAP_PROP_XI_GAIN_SELECTOR = 423, // Gain selector for parameter Gain allows to select different type of gains. - CV_CAP_PROP_XI_GAIN = 424, // Gain in dB - CV_CAP_PROP_XI_DOWNSAMPLING_TYPE = 426, // Change image downsampling type. - CV_CAP_PROP_XI_BINNING_SELECTOR = 427, // Binning engine selector. - CV_CAP_PROP_XI_BINNING_VERTICAL = 428, // Vertical Binning - number of vertical photo-sensitive cells to combine together. - CV_CAP_PROP_XI_BINNING_HORIZONTAL = 429, // Horizontal Binning - number of horizontal photo-sensitive cells to combine together. - CV_CAP_PROP_XI_BINNING_PATTERN = 430, // Binning pattern type. - CV_CAP_PROP_XI_DECIMATION_SELECTOR = 431, // Decimation engine selector. - CV_CAP_PROP_XI_DECIMATION_VERTICAL = 432, // Vertical Decimation - vertical sub-sampling of the image - reduces the vertical resolution of the image by the specified vertical decimation factor. - CV_CAP_PROP_XI_DECIMATION_HORIZONTAL = 433, // Horizontal Decimation - horizontal sub-sampling of the image - reduces the horizontal resolution of the image by the specified vertical decimation factor. - CV_CAP_PROP_XI_DECIMATION_PATTERN = 434, // Decimation pattern type. - CV_CAP_PROP_XI_TEST_PATTERN_GENERATOR_SELECTOR = 587, // Selects which test pattern generator is controlled by the TestPattern feature. - CV_CAP_PROP_XI_TEST_PATTERN = 588, // Selects which test pattern type is generated by the selected generator. - CV_CAP_PROP_XI_IMAGE_DATA_FORMAT = 435, // Output data format. - CV_CAP_PROP_XI_SHUTTER_TYPE = 436, // Change sensor shutter type(CMOS sensor). - CV_CAP_PROP_XI_SENSOR_TAPS = 437, // Number of taps - CV_CAP_PROP_XI_AEAG_ROI_OFFSET_X = 439, // Automatic exposure/gain ROI offset X - CV_CAP_PROP_XI_AEAG_ROI_OFFSET_Y = 440, // Automatic exposure/gain ROI offset Y - CV_CAP_PROP_XI_AEAG_ROI_WIDTH = 441, // Automatic exposure/gain ROI Width - CV_CAP_PROP_XI_AEAG_ROI_HEIGHT = 442, // Automatic exposure/gain ROI Height - CV_CAP_PROP_XI_BPC = 445, // Correction of bad pixels - CV_CAP_PROP_XI_WB_KR = 448, // White balance red coefficient - CV_CAP_PROP_XI_WB_KG = 449, // White balance green coefficient - CV_CAP_PROP_XI_WB_KB = 450, // White balance blue coefficient - CV_CAP_PROP_XI_WIDTH = 451, // Width of the Image provided by the device (in pixels). - CV_CAP_PROP_XI_HEIGHT = 452, // Height of the Image provided by the device (in pixels). - CV_CAP_PROP_XI_REGION_SELECTOR = 589, // Selects Region in Multiple ROI which parameters are set by width, height, ... ,region mode - CV_CAP_PROP_XI_REGION_MODE = 595, // Activates/deactivates Region selected by Region Selector - CV_CAP_PROP_XI_LIMIT_BANDWIDTH = 459, // Set/get bandwidth(datarate)(in Megabits) - CV_CAP_PROP_XI_SENSOR_DATA_BIT_DEPTH = 460, // Sensor output data bit depth. - CV_CAP_PROP_XI_OUTPUT_DATA_BIT_DEPTH = 461, // Device output data bit depth. - CV_CAP_PROP_XI_IMAGE_DATA_BIT_DEPTH = 462, // bitdepth of data returned by function xiGetImage - CV_CAP_PROP_XI_OUTPUT_DATA_PACKING = 463, // Device output data packing (or grouping) enabled. Packing could be enabled if output_data_bit_depth > 8 and packing capability is available. - CV_CAP_PROP_XI_OUTPUT_DATA_PACKING_TYPE = 464, // Data packing type. Some cameras supports only specific packing type. - CV_CAP_PROP_XI_IS_COOLED = 465, // Returns 1 for cameras that support cooling. - CV_CAP_PROP_XI_COOLING = 466, // Start camera cooling. - CV_CAP_PROP_XI_TARGET_TEMP = 467, // Set sensor target temperature for cooling. - CV_CAP_PROP_XI_CHIP_TEMP = 468, // Camera sensor temperature - CV_CAP_PROP_XI_HOUS_TEMP = 469, // Camera housing temperature - CV_CAP_PROP_XI_HOUS_BACK_SIDE_TEMP = 590, // Camera housing back side temperature - CV_CAP_PROP_XI_SENSOR_BOARD_TEMP = 596, // Camera sensor board temperature - CV_CAP_PROP_XI_CMS = 470, // Mode of color management system. - CV_CAP_PROP_XI_APPLY_CMS = 471, // Enable applying of CMS profiles to xiGetImage (see XI_PRM_INPUT_CMS_PROFILE, XI_PRM_OUTPUT_CMS_PROFILE). - CV_CAP_PROP_XI_IMAGE_IS_COLOR = 474, // Returns 1 for color cameras. - CV_CAP_PROP_XI_COLOR_FILTER_ARRAY = 475, // Returns color filter array type of RAW data. - CV_CAP_PROP_XI_GAMMAY = 476, // Luminosity gamma - CV_CAP_PROP_XI_GAMMAC = 477, // Chromaticity gamma - CV_CAP_PROP_XI_SHARPNESS = 478, // Sharpness Strength - CV_CAP_PROP_XI_CC_MATRIX_00 = 479, // Color Correction Matrix element [0][0] - CV_CAP_PROP_XI_CC_MATRIX_01 = 480, // Color Correction Matrix element [0][1] - CV_CAP_PROP_XI_CC_MATRIX_02 = 481, // Color Correction Matrix element [0][2] - CV_CAP_PROP_XI_CC_MATRIX_03 = 482, // Color Correction Matrix element [0][3] - CV_CAP_PROP_XI_CC_MATRIX_10 = 483, // Color Correction Matrix element [1][0] - CV_CAP_PROP_XI_CC_MATRIX_11 = 484, // Color Correction Matrix element [1][1] - CV_CAP_PROP_XI_CC_MATRIX_12 = 485, // Color Correction Matrix element [1][2] - CV_CAP_PROP_XI_CC_MATRIX_13 = 486, // Color Correction Matrix element [1][3] - CV_CAP_PROP_XI_CC_MATRIX_20 = 487, // Color Correction Matrix element [2][0] - CV_CAP_PROP_XI_CC_MATRIX_21 = 488, // Color Correction Matrix element [2][1] - CV_CAP_PROP_XI_CC_MATRIX_22 = 489, // Color Correction Matrix element [2][2] - CV_CAP_PROP_XI_CC_MATRIX_23 = 490, // Color Correction Matrix element [2][3] - CV_CAP_PROP_XI_CC_MATRIX_30 = 491, // Color Correction Matrix element [3][0] - CV_CAP_PROP_XI_CC_MATRIX_31 = 492, // Color Correction Matrix element [3][1] - CV_CAP_PROP_XI_CC_MATRIX_32 = 493, // Color Correction Matrix element [3][2] - CV_CAP_PROP_XI_CC_MATRIX_33 = 494, // Color Correction Matrix element [3][3] - CV_CAP_PROP_XI_DEFAULT_CC_MATRIX = 495, // Set default Color Correction Matrix - CV_CAP_PROP_XI_TRG_SELECTOR = 498, // Selects the type of trigger. - CV_CAP_PROP_XI_ACQ_FRAME_BURST_COUNT = 499, // Sets number of frames acquired by burst. This burst is used only if trigger is set to FrameBurstStart - CV_CAP_PROP_XI_DEBOUNCE_EN = 507, // Enable/Disable debounce to selected GPI - CV_CAP_PROP_XI_DEBOUNCE_T0 = 508, // Debounce time (x * 10us) - CV_CAP_PROP_XI_DEBOUNCE_T1 = 509, // Debounce time (x * 10us) - CV_CAP_PROP_XI_DEBOUNCE_POL = 510, // Debounce polarity (pol = 1 t0 - falling edge, t1 - rising edge) - CV_CAP_PROP_XI_LENS_MODE = 511, // Status of lens control interface. This shall be set to XI_ON before any Lens operations. - CV_CAP_PROP_XI_LENS_APERTURE_VALUE = 512, // Current lens aperture value in stops. Examples: 2.8, 4, 5.6, 8, 11 - CV_CAP_PROP_XI_LENS_FOCUS_MOVEMENT_VALUE = 513, // Lens current focus movement value to be used by XI_PRM_LENS_FOCUS_MOVE in motor steps. - CV_CAP_PROP_XI_LENS_FOCUS_MOVE = 514, // Moves lens focus motor by steps set in XI_PRM_LENS_FOCUS_MOVEMENT_VALUE. - CV_CAP_PROP_XI_LENS_FOCUS_DISTANCE = 515, // Lens focus distance in cm. - CV_CAP_PROP_XI_LENS_FOCAL_LENGTH = 516, // Lens focal distance in mm. - CV_CAP_PROP_XI_LENS_FEATURE_SELECTOR = 517, // Selects the current feature which is accessible by XI_PRM_LENS_FEATURE. - CV_CAP_PROP_XI_LENS_FEATURE = 518, // Allows access to lens feature value currently selected by XI_PRM_LENS_FEATURE_SELECTOR. - CV_CAP_PROP_XI_DEVICE_MODEL_ID = 521, // Return device model id - CV_CAP_PROP_XI_DEVICE_SN = 522, // Return device serial number - CV_CAP_PROP_XI_IMAGE_DATA_FORMAT_RGB32_ALPHA = 529, // The alpha channel of RGB32 output image format. - CV_CAP_PROP_XI_IMAGE_PAYLOAD_SIZE = 530, // Buffer size in bytes sufficient for output image returned by xiGetImage - CV_CAP_PROP_XI_TRANSPORT_PIXEL_FORMAT = 531, // Current format of pixels on transport layer. - CV_CAP_PROP_XI_SENSOR_CLOCK_FREQ_HZ = 532, // Sensor clock frequency in Hz. - CV_CAP_PROP_XI_SENSOR_CLOCK_FREQ_INDEX = 533, // Sensor clock frequency index. Sensor with selected frequencies have possibility to set the frequency only by this index. - CV_CAP_PROP_XI_SENSOR_OUTPUT_CHANNEL_COUNT = 534, // Number of output channels from sensor used for data transfer. - CV_CAP_PROP_XI_FRAMERATE = 535, // Define framerate in Hz - CV_CAP_PROP_XI_COUNTER_SELECTOR = 536, // Select counter - CV_CAP_PROP_XI_COUNTER_VALUE = 537, // Counter status - CV_CAP_PROP_XI_ACQ_TIMING_MODE = 538, // Type of sensor frames timing. - CV_CAP_PROP_XI_AVAILABLE_BANDWIDTH = 539, // Calculate and return available interface bandwidth(int Megabits) - CV_CAP_PROP_XI_BUFFER_POLICY = 540, // Data move policy - CV_CAP_PROP_XI_LUT_EN = 541, // Activates LUT. - CV_CAP_PROP_XI_LUT_INDEX = 542, // Control the index (offset) of the coefficient to access in the LUT. - CV_CAP_PROP_XI_LUT_VALUE = 543, // Value at entry LUTIndex of the LUT - CV_CAP_PROP_XI_TRG_DELAY = 544, // Specifies the delay in microseconds (us) to apply after the trigger reception before activating it. - CV_CAP_PROP_XI_TS_RST_MODE = 545, // Defines how time stamp reset engine will be armed - CV_CAP_PROP_XI_TS_RST_SOURCE = 546, // Defines which source will be used for timestamp reset. Writing this parameter will trigger settings of engine (arming) - CV_CAP_PROP_XI_IS_DEVICE_EXIST = 547, // Returns 1 if camera connected and works properly. - CV_CAP_PROP_XI_ACQ_BUFFER_SIZE = 548, // Acquisition buffer size in buffer_size_unit. Default bytes. - CV_CAP_PROP_XI_ACQ_BUFFER_SIZE_UNIT = 549, // Acquisition buffer size unit in bytes. Default 1. E.g. Value 1024 means that buffer_size is in KiBytes - CV_CAP_PROP_XI_ACQ_TRANSPORT_BUFFER_SIZE = 550, // Acquisition transport buffer size in bytes - CV_CAP_PROP_XI_BUFFERS_QUEUE_SIZE = 551, // Queue of field/frame buffers - CV_CAP_PROP_XI_ACQ_TRANSPORT_BUFFER_COMMIT = 552, // Number of buffers to commit to low level - CV_CAP_PROP_XI_RECENT_FRAME = 553, // GetImage returns most recent frame - CV_CAP_PROP_XI_DEVICE_RESET = 554, // Resets the camera to default state. - CV_CAP_PROP_XI_COLUMN_FPN_CORRECTION = 555, // Correction of column FPN - CV_CAP_PROP_XI_ROW_FPN_CORRECTION = 591, // Correction of row FPN - CV_CAP_PROP_XI_SENSOR_MODE = 558, // Current sensor mode. Allows to select sensor mode by one integer. Setting of this parameter affects: image dimensions and downsampling. - CV_CAP_PROP_XI_HDR = 559, // Enable High Dynamic Range feature. - CV_CAP_PROP_XI_HDR_KNEEPOINT_COUNT = 560, // The number of kneepoints in the PWLR. - CV_CAP_PROP_XI_HDR_T1 = 561, // position of first kneepoint(in % of XI_PRM_EXPOSURE) - CV_CAP_PROP_XI_HDR_T2 = 562, // position of second kneepoint (in % of XI_PRM_EXPOSURE) - CV_CAP_PROP_XI_KNEEPOINT1 = 563, // value of first kneepoint (% of sensor saturation) - CV_CAP_PROP_XI_KNEEPOINT2 = 564, // value of second kneepoint (% of sensor saturation) - CV_CAP_PROP_XI_IMAGE_BLACK_LEVEL = 565, // Last image black level counts. Can be used for Offline processing to recall it. - CV_CAP_PROP_XI_HW_REVISION = 571, // Returns hardware revision number. - CV_CAP_PROP_XI_DEBUG_LEVEL = 572, // Set debug level - CV_CAP_PROP_XI_AUTO_BANDWIDTH_CALCULATION = 573, // Automatic bandwidth calculation, - CV_CAP_PROP_XI_FFS_FILE_ID = 594, // File number. - CV_CAP_PROP_XI_FFS_FILE_SIZE = 580, // Size of file. - CV_CAP_PROP_XI_FREE_FFS_SIZE = 581, // Size of free camera FFS. - CV_CAP_PROP_XI_USED_FFS_SIZE = 582, // Size of used camera FFS. - CV_CAP_PROP_XI_FFS_ACCESS_KEY = 583, // Setting of key enables file operations on some cameras. - CV_CAP_PROP_XI_SENSOR_FEATURE_SELECTOR = 585, // Selects the current feature which is accessible by XI_PRM_SENSOR_FEATURE_VALUE. - CV_CAP_PROP_XI_SENSOR_FEATURE_VALUE = 586, // Allows access to sensor feature value currently selected by XI_PRM_SENSOR_FEATURE_SELECTOR. - - - // Properties for Android cameras - CV_CAP_PROP_ANDROID_FLASH_MODE = 8001, - CV_CAP_PROP_ANDROID_FOCUS_MODE = 8002, - CV_CAP_PROP_ANDROID_WHITE_BALANCE = 8003, - CV_CAP_PROP_ANDROID_ANTIBANDING = 8004, - CV_CAP_PROP_ANDROID_FOCAL_LENGTH = 8005, - CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_NEAR = 8006, - CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_OPTIMAL = 8007, - CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_FAR = 8008, - CV_CAP_PROP_ANDROID_EXPOSE_LOCK = 8009, - CV_CAP_PROP_ANDROID_WHITEBALANCE_LOCK = 8010, - - // Properties of cameras available through AVFOUNDATION interface - CV_CAP_PROP_IOS_DEVICE_FOCUS = 9001, - CV_CAP_PROP_IOS_DEVICE_EXPOSURE = 9002, - CV_CAP_PROP_IOS_DEVICE_FLASH = 9003, - CV_CAP_PROP_IOS_DEVICE_WHITEBALANCE = 9004, - CV_CAP_PROP_IOS_DEVICE_TORCH = 9005, - - // Properties of cameras available through Smartek Giganetix Ethernet Vision interface - /* --- Vladimir Litvinenko (litvinenko.vladimir@gmail.com) --- */ - CV_CAP_PROP_GIGA_FRAME_OFFSET_X = 10001, - CV_CAP_PROP_GIGA_FRAME_OFFSET_Y = 10002, - CV_CAP_PROP_GIGA_FRAME_WIDTH_MAX = 10003, - CV_CAP_PROP_GIGA_FRAME_HEIGH_MAX = 10004, - CV_CAP_PROP_GIGA_FRAME_SENS_WIDTH = 10005, - CV_CAP_PROP_GIGA_FRAME_SENS_HEIGH = 10006, - - CV_CAP_PROP_INTELPERC_PROFILE_COUNT = 11001, - CV_CAP_PROP_INTELPERC_PROFILE_IDX = 11002, - CV_CAP_PROP_INTELPERC_DEPTH_LOW_CONFIDENCE_VALUE = 11003, - CV_CAP_PROP_INTELPERC_DEPTH_SATURATION_VALUE = 11004, - CV_CAP_PROP_INTELPERC_DEPTH_CONFIDENCE_THRESHOLD = 11005, - CV_CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_HORZ = 11006, - CV_CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_VERT = 11007, - - // Intel PerC streams - CV_CAP_INTELPERC_DEPTH_GENERATOR = 1 << 29, - CV_CAP_INTELPERC_IMAGE_GENERATOR = 1 << 28, - CV_CAP_INTELPERC_GENERATORS_MASK = CV_CAP_INTELPERC_DEPTH_GENERATOR + CV_CAP_INTELPERC_IMAGE_GENERATOR -}; - -enum -{ - // Data given from depth generator. - CV_CAP_OPENNI_DEPTH_MAP = 0, // Depth values in mm (CV_16UC1) - CV_CAP_OPENNI_POINT_CLOUD_MAP = 1, // XYZ in meters (CV_32FC3) - CV_CAP_OPENNI_DISPARITY_MAP = 2, // Disparity in pixels (CV_8UC1) - CV_CAP_OPENNI_DISPARITY_MAP_32F = 3, // Disparity in pixels (CV_32FC1) - CV_CAP_OPENNI_VALID_DEPTH_MASK = 4, // CV_8UC1 - - // Data given from RGB image generator. - CV_CAP_OPENNI_BGR_IMAGE = 5, - CV_CAP_OPENNI_GRAY_IMAGE = 6, - - // Data given from IR image generator. - CV_CAP_OPENNI_IR_IMAGE = 7 -}; - -// Supported output modes of OpenNI image generator -enum -{ - CV_CAP_OPENNI_VGA_30HZ = 0, - CV_CAP_OPENNI_SXGA_15HZ = 1, - CV_CAP_OPENNI_SXGA_30HZ = 2, - CV_CAP_OPENNI_QVGA_30HZ = 3, - CV_CAP_OPENNI_QVGA_60HZ = 4 -}; - -enum -{ - CV_CAP_INTELPERC_DEPTH_MAP = 0, // Each pixel is a 16-bit integer. The value indicates the distance from an object to the camera's XY plane or the Cartesian depth. - CV_CAP_INTELPERC_UVDEPTH_MAP = 1, // Each pixel contains two 32-bit floating point values in the range of 0-1, representing the mapping of depth coordinates to the color coordinates. - CV_CAP_INTELPERC_IR_MAP = 2, // Each pixel is a 16-bit integer. The value indicates the intensity of the reflected laser beam. - CV_CAP_INTELPERC_IMAGE = 3 -}; - -// gPhoto2 properties, if propertyId is less than 0 then work on widget with that __additive inversed__ camera setting ID -// Get IDs by using CAP_PROP_GPHOTO2_WIDGET_ENUMERATE. -// @see CvCaptureCAM_GPHOTO2 for more info -enum -{ - CV_CAP_PROP_GPHOTO2_PREVIEW = 17001, // Capture only preview from liveview mode. - CV_CAP_PROP_GPHOTO2_WIDGET_ENUMERATE = 17002, // Readonly, returns (const char *). - CV_CAP_PROP_GPHOTO2_RELOAD_CONFIG = 17003, // Trigger, only by set. Reload camera settings. - CV_CAP_PROP_GPHOTO2_RELOAD_ON_CHANGE = 17004, // Reload all settings on set. - CV_CAP_PROP_GPHOTO2_COLLECT_MSGS = 17005, // Collect messages with details. - CV_CAP_PROP_GPHOTO2_FLUSH_MSGS = 17006, // Readonly, returns (const char *). - CV_CAP_PROP_SPEED = 17007, // Exposure speed. Can be readonly, depends on camera program. - CV_CAP_PROP_APERTURE = 17008, // Aperture. Can be readonly, depends on camera program. - CV_CAP_PROP_EXPOSUREPROGRAM = 17009, // Camera exposure program. - CV_CAP_PROP_VIEWFINDER = 17010 // Enter liveview mode. -}; - -//! (Windows only) Open Codec Selection Dialog -#define CV_FOURCC_PROMPT -1 -//! (Linux only) Use default codec for specified filename -#define CV_FOURCC_DEFAULT CV_FOURCC('I', 'Y', 'U', 'V') - -#endif // OPENCV_VIDEOIO_LEGACY_CONSTANTS_H +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_VIDEOIO_LEGACY_CONSTANTS_H +#define OPENCV_VIDEOIO_LEGACY_CONSTANTS_H + +#include "opencv2/core/cvdef.h" + +enum +{ + CV_CAP_ANY =0, // autodetect + + CV_CAP_MIL =100, // MIL proprietary drivers + + CV_CAP_VFW =200, // platform native + CV_CAP_V4L =200, + CV_CAP_V4L2 =200, + + CV_CAP_FIREWARE =300, // IEEE 1394 drivers + CV_CAP_FIREWIRE =300, + CV_CAP_IEEE1394 =300, + CV_CAP_DC1394 =300, + CV_CAP_CMU1394 =300, + + CV_CAP_STEREO =400, // TYZX proprietary drivers + CV_CAP_TYZX =400, + CV_TYZX_LEFT =400, + CV_TYZX_RIGHT =401, + CV_TYZX_COLOR =402, + CV_TYZX_Z =403, + + CV_CAP_QT =500, // QuickTime + + CV_CAP_UNICAP =600, // Unicap drivers + + CV_CAP_DSHOW =700, // DirectShow (via videoInput) + CV_CAP_MSMF =1400, // Microsoft Media Foundation (via videoInput) + + CV_CAP_PVAPI =800, // PvAPI, Prosilica GigE SDK + + CV_CAP_OPENNI =900, // OpenNI (for Kinect) + CV_CAP_OPENNI_ASUS =910, // OpenNI (for Asus Xtion) + + CV_CAP_ANDROID =1000, // Android - not used + CV_CAP_ANDROID_BACK =CV_CAP_ANDROID+99, // Android back camera - not used + CV_CAP_ANDROID_FRONT =CV_CAP_ANDROID+98, // Android front camera - not used + + CV_CAP_XIAPI =1100, // XIMEA Camera API + + CV_CAP_AVFOUNDATION = 1200, // AVFoundation framework for iOS (OS X Lion will have the same API) + + CV_CAP_GIGANETIX = 1300, // Smartek Giganetix GigEVisionSDK + + CV_CAP_INTELPERC = 1500, // Intel Perceptual Computing + + CV_CAP_OPENNI2 = 1600, // OpenNI2 (for Kinect) + CV_CAP_GPHOTO2 = 1700, + CV_CAP_GSTREAMER = 1800, // GStreamer + CV_CAP_FFMPEG = 1900, // FFMPEG + CV_CAP_IMAGES = 2000, // OpenCV Image Sequence (e.g. img_%02d.jpg) + + CV_CAP_ARAVIS = 2100 // Aravis GigE SDK +}; + +enum +{ + // modes of the controlling registers (can be: auto, manual, auto single push, absolute Latter allowed with any other mode) + // every feature can have only one mode turned on at a time + CV_CAP_PROP_DC1394_OFF = -4, //turn the feature off (not controlled manually nor automatically) + CV_CAP_PROP_DC1394_MODE_MANUAL = -3, //set automatically when a value of the feature is set by the user + CV_CAP_PROP_DC1394_MODE_AUTO = -2, + CV_CAP_PROP_DC1394_MODE_ONE_PUSH_AUTO = -1, + CV_CAP_PROP_POS_MSEC =0, + CV_CAP_PROP_POS_FRAMES =1, + CV_CAP_PROP_POS_AVI_RATIO =2, + CV_CAP_PROP_FRAME_WIDTH =3, + CV_CAP_PROP_FRAME_HEIGHT =4, + CV_CAP_PROP_FPS =5, + CV_CAP_PROP_FOURCC =6, + CV_CAP_PROP_FRAME_COUNT =7, + CV_CAP_PROP_FORMAT =8, + CV_CAP_PROP_MODE =9, + CV_CAP_PROP_BRIGHTNESS =10, + CV_CAP_PROP_CONTRAST =11, + CV_CAP_PROP_SATURATION =12, + CV_CAP_PROP_HUE =13, + CV_CAP_PROP_GAIN =14, + CV_CAP_PROP_EXPOSURE =15, + CV_CAP_PROP_CONVERT_RGB =16, + CV_CAP_PROP_WHITE_BALANCE_BLUE_U =17, + CV_CAP_PROP_RECTIFICATION =18, + CV_CAP_PROP_MONOCHROME =19, + CV_CAP_PROP_SHARPNESS =20, + CV_CAP_PROP_AUTO_EXPOSURE =21, // exposure control done by camera, + // user can adjust reference level + // using this feature + CV_CAP_PROP_GAMMA =22, + CV_CAP_PROP_TEMPERATURE =23, + CV_CAP_PROP_TRIGGER =24, + CV_CAP_PROP_TRIGGER_DELAY =25, + CV_CAP_PROP_WHITE_BALANCE_RED_V =26, + CV_CAP_PROP_ZOOM =27, + CV_CAP_PROP_FOCUS =28, + CV_CAP_PROP_GUID =29, + CV_CAP_PROP_ISO_SPEED =30, + CV_CAP_PROP_MAX_DC1394 =31, + CV_CAP_PROP_BACKLIGHT =32, + CV_CAP_PROP_PAN =33, + CV_CAP_PROP_TILT =34, + CV_CAP_PROP_ROLL =35, + CV_CAP_PROP_IRIS =36, + CV_CAP_PROP_SETTINGS =37, + CV_CAP_PROP_BUFFERSIZE =38, + CV_CAP_PROP_AUTOFOCUS =39, + CV_CAP_PROP_SAR_NUM =40, + CV_CAP_PROP_SAR_DEN =41, + + CV_CAP_PROP_AUTOGRAB =1024, // property for videoio class CvCapture_Android only + CV_CAP_PROP_SUPPORTED_PREVIEW_SIZES_STRING=1025, // readonly, tricky property, returns cpnst char* indeed + CV_CAP_PROP_PREVIEW_FORMAT=1026, // readonly, tricky property, returns cpnst char* indeed + + // OpenNI map generators + CV_CAP_OPENNI_DEPTH_GENERATOR = 1 << 31, + CV_CAP_OPENNI_IMAGE_GENERATOR = 1 << 30, + CV_CAP_OPENNI_IR_GENERATOR = 1 << 29, + CV_CAP_OPENNI_GENERATORS_MASK = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_OPENNI_IR_GENERATOR, + + // Properties of cameras available through OpenNI interfaces + CV_CAP_PROP_OPENNI_OUTPUT_MODE = 100, + CV_CAP_PROP_OPENNI_FRAME_MAX_DEPTH = 101, // in mm + CV_CAP_PROP_OPENNI_BASELINE = 102, // in mm + CV_CAP_PROP_OPENNI_FOCAL_LENGTH = 103, // in pixels + CV_CAP_PROP_OPENNI_REGISTRATION = 104, // flag + CV_CAP_PROP_OPENNI_REGISTRATION_ON = CV_CAP_PROP_OPENNI_REGISTRATION, // flag that synchronizes the remapping depth map to image map + // by changing depth generator's view point (if the flag is "on") or + // sets this view point to its normal one (if the flag is "off"). + CV_CAP_PROP_OPENNI_APPROX_FRAME_SYNC = 105, + CV_CAP_PROP_OPENNI_MAX_BUFFER_SIZE = 106, + CV_CAP_PROP_OPENNI_CIRCLE_BUFFER = 107, + CV_CAP_PROP_OPENNI_MAX_TIME_DURATION = 108, + + CV_CAP_PROP_OPENNI_GENERATOR_PRESENT = 109, + CV_CAP_PROP_OPENNI2_SYNC = 110, + CV_CAP_PROP_OPENNI2_MIRROR = 111, + + CV_CAP_OPENNI_IMAGE_GENERATOR_PRESENT = CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_PROP_OPENNI_GENERATOR_PRESENT, + CV_CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE = CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_PROP_OPENNI_OUTPUT_MODE, + CV_CAP_OPENNI_DEPTH_GENERATOR_PRESENT = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_GENERATOR_PRESENT, + CV_CAP_OPENNI_DEPTH_GENERATOR_BASELINE = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_BASELINE, + CV_CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_FOCAL_LENGTH, + CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_REGISTRATION, + CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION_ON = CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION, + CV_CAP_OPENNI_IR_GENERATOR_PRESENT = CV_CAP_OPENNI_IR_GENERATOR + CV_CAP_PROP_OPENNI_GENERATOR_PRESENT, + + // Properties of cameras available through GStreamer interface + CV_CAP_GSTREAMER_QUEUE_LENGTH = 200, // default is 1 + + // PVAPI + CV_CAP_PROP_PVAPI_MULTICASTIP = 300, // ip for anable multicast master mode. 0 for disable multicast + CV_CAP_PROP_PVAPI_FRAMESTARTTRIGGERMODE = 301, // FrameStartTriggerMode: Determines how a frame is initiated + CV_CAP_PROP_PVAPI_DECIMATIONHORIZONTAL = 302, // Horizontal sub-sampling of the image + CV_CAP_PROP_PVAPI_DECIMATIONVERTICAL = 303, // Vertical sub-sampling of the image + CV_CAP_PROP_PVAPI_BINNINGX = 304, // Horizontal binning factor + CV_CAP_PROP_PVAPI_BINNINGY = 305, // Vertical binning factor + CV_CAP_PROP_PVAPI_PIXELFORMAT = 306, // Pixel format + + // Properties of cameras available through XIMEA SDK interface + CV_CAP_PROP_XI_DOWNSAMPLING = 400, // Change image resolution by binning or skipping. + CV_CAP_PROP_XI_DATA_FORMAT = 401, // Output data format. + CV_CAP_PROP_XI_OFFSET_X = 402, // Horizontal offset from the origin to the area of interest (in pixels). + CV_CAP_PROP_XI_OFFSET_Y = 403, // Vertical offset from the origin to the area of interest (in pixels). + CV_CAP_PROP_XI_TRG_SOURCE = 404, // Defines source of trigger. + CV_CAP_PROP_XI_TRG_SOFTWARE = 405, // Generates an internal trigger. PRM_TRG_SOURCE must be set to TRG_SOFTWARE. + CV_CAP_PROP_XI_GPI_SELECTOR = 406, // Selects general purpose input + CV_CAP_PROP_XI_GPI_MODE = 407, // Set general purpose input mode + CV_CAP_PROP_XI_GPI_LEVEL = 408, // Get general purpose level + CV_CAP_PROP_XI_GPO_SELECTOR = 409, // Selects general purpose output + CV_CAP_PROP_XI_GPO_MODE = 410, // Set general purpose output mode + CV_CAP_PROP_XI_LED_SELECTOR = 411, // Selects camera signalling LED + CV_CAP_PROP_XI_LED_MODE = 412, // Define camera signalling LED functionality + CV_CAP_PROP_XI_MANUAL_WB = 413, // Calculates White Balance(must be called during acquisition) + CV_CAP_PROP_XI_AUTO_WB = 414, // Automatic white balance + CV_CAP_PROP_XI_AEAG = 415, // Automatic exposure/gain + CV_CAP_PROP_XI_EXP_PRIORITY = 416, // Exposure priority (0.5 - exposure 50%, gain 50%). + CV_CAP_PROP_XI_AE_MAX_LIMIT = 417, // Maximum limit of exposure in AEAG procedure + CV_CAP_PROP_XI_AG_MAX_LIMIT = 418, // Maximum limit of gain in AEAG procedure + CV_CAP_PROP_XI_AEAG_LEVEL = 419, // Average intensity of output signal AEAG should achieve(in %) + CV_CAP_PROP_XI_TIMEOUT = 420, // Image capture timeout in milliseconds + CV_CAP_PROP_XI_EXPOSURE = 421, // Exposure time in microseconds + CV_CAP_PROP_XI_EXPOSURE_BURST_COUNT = 422, // Sets the number of times of exposure in one frame. + CV_CAP_PROP_XI_GAIN_SELECTOR = 423, // Gain selector for parameter Gain allows to select different type of gains. + CV_CAP_PROP_XI_GAIN = 424, // Gain in dB + CV_CAP_PROP_XI_DOWNSAMPLING_TYPE = 426, // Change image downsampling type. + CV_CAP_PROP_XI_BINNING_SELECTOR = 427, // Binning engine selector. + CV_CAP_PROP_XI_BINNING_VERTICAL = 428, // Vertical Binning - number of vertical photo-sensitive cells to combine together. + CV_CAP_PROP_XI_BINNING_HORIZONTAL = 429, // Horizontal Binning - number of horizontal photo-sensitive cells to combine together. + CV_CAP_PROP_XI_BINNING_PATTERN = 430, // Binning pattern type. + CV_CAP_PROP_XI_DECIMATION_SELECTOR = 431, // Decimation engine selector. + CV_CAP_PROP_XI_DECIMATION_VERTICAL = 432, // Vertical Decimation - vertical sub-sampling of the image - reduces the vertical resolution of the image by the specified vertical decimation factor. + CV_CAP_PROP_XI_DECIMATION_HORIZONTAL = 433, // Horizontal Decimation - horizontal sub-sampling of the image - reduces the horizontal resolution of the image by the specified vertical decimation factor. + CV_CAP_PROP_XI_DECIMATION_PATTERN = 434, // Decimation pattern type. + CV_CAP_PROP_XI_TEST_PATTERN_GENERATOR_SELECTOR = 587, // Selects which test pattern generator is controlled by the TestPattern feature. + CV_CAP_PROP_XI_TEST_PATTERN = 588, // Selects which test pattern type is generated by the selected generator. + CV_CAP_PROP_XI_IMAGE_DATA_FORMAT = 435, // Output data format. + CV_CAP_PROP_XI_SHUTTER_TYPE = 436, // Change sensor shutter type(CMOS sensor). + CV_CAP_PROP_XI_SENSOR_TAPS = 437, // Number of taps + CV_CAP_PROP_XI_AEAG_ROI_OFFSET_X = 439, // Automatic exposure/gain ROI offset X + CV_CAP_PROP_XI_AEAG_ROI_OFFSET_Y = 440, // Automatic exposure/gain ROI offset Y + CV_CAP_PROP_XI_AEAG_ROI_WIDTH = 441, // Automatic exposure/gain ROI Width + CV_CAP_PROP_XI_AEAG_ROI_HEIGHT = 442, // Automatic exposure/gain ROI Height + CV_CAP_PROP_XI_BPC = 445, // Correction of bad pixels + CV_CAP_PROP_XI_WB_KR = 448, // White balance red coefficient + CV_CAP_PROP_XI_WB_KG = 449, // White balance green coefficient + CV_CAP_PROP_XI_WB_KB = 450, // White balance blue coefficient + CV_CAP_PROP_XI_WIDTH = 451, // Width of the Image provided by the device (in pixels). + CV_CAP_PROP_XI_HEIGHT = 452, // Height of the Image provided by the device (in pixels). + CV_CAP_PROP_XI_REGION_SELECTOR = 589, // Selects Region in Multiple ROI which parameters are set by width, height, ... ,region mode + CV_CAP_PROP_XI_REGION_MODE = 595, // Activates/deactivates Region selected by Region Selector + CV_CAP_PROP_XI_LIMIT_BANDWIDTH = 459, // Set/get bandwidth(datarate)(in Megabits) + CV_CAP_PROP_XI_SENSOR_DATA_BIT_DEPTH = 460, // Sensor output data bit depth. + CV_CAP_PROP_XI_OUTPUT_DATA_BIT_DEPTH = 461, // Device output data bit depth. + CV_CAP_PROP_XI_IMAGE_DATA_BIT_DEPTH = 462, // bitdepth of data returned by function xiGetImage + CV_CAP_PROP_XI_OUTPUT_DATA_PACKING = 463, // Device output data packing (or grouping) enabled. Packing could be enabled if output_data_bit_depth > 8 and packing capability is available. + CV_CAP_PROP_XI_OUTPUT_DATA_PACKING_TYPE = 464, // Data packing type. Some cameras supports only specific packing type. + CV_CAP_PROP_XI_IS_COOLED = 465, // Returns 1 for cameras that support cooling. + CV_CAP_PROP_XI_COOLING = 466, // Start camera cooling. + CV_CAP_PROP_XI_TARGET_TEMP = 467, // Set sensor target temperature for cooling. + CV_CAP_PROP_XI_CHIP_TEMP = 468, // Camera sensor temperature + CV_CAP_PROP_XI_HOUS_TEMP = 469, // Camera housing temperature + CV_CAP_PROP_XI_HOUS_BACK_SIDE_TEMP = 590, // Camera housing back side temperature + CV_CAP_PROP_XI_SENSOR_BOARD_TEMP = 596, // Camera sensor board temperature + CV_CAP_PROP_XI_CMS = 470, // Mode of color management system. + CV_CAP_PROP_XI_APPLY_CMS = 471, // Enable applying of CMS profiles to xiGetImage (see XI_PRM_INPUT_CMS_PROFILE, XI_PRM_OUTPUT_CMS_PROFILE). + CV_CAP_PROP_XI_IMAGE_IS_COLOR = 474, // Returns 1 for color cameras. + CV_CAP_PROP_XI_COLOR_FILTER_ARRAY = 475, // Returns color filter array type of RAW data. + CV_CAP_PROP_XI_GAMMAY = 476, // Luminosity gamma + CV_CAP_PROP_XI_GAMMAC = 477, // Chromaticity gamma + CV_CAP_PROP_XI_SHARPNESS = 478, // Sharpness Strength + CV_CAP_PROP_XI_CC_MATRIX_00 = 479, // Color Correction Matrix element [0][0] + CV_CAP_PROP_XI_CC_MATRIX_01 = 480, // Color Correction Matrix element [0][1] + CV_CAP_PROP_XI_CC_MATRIX_02 = 481, // Color Correction Matrix element [0][2] + CV_CAP_PROP_XI_CC_MATRIX_03 = 482, // Color Correction Matrix element [0][3] + CV_CAP_PROP_XI_CC_MATRIX_10 = 483, // Color Correction Matrix element [1][0] + CV_CAP_PROP_XI_CC_MATRIX_11 = 484, // Color Correction Matrix element [1][1] + CV_CAP_PROP_XI_CC_MATRIX_12 = 485, // Color Correction Matrix element [1][2] + CV_CAP_PROP_XI_CC_MATRIX_13 = 486, // Color Correction Matrix element [1][3] + CV_CAP_PROP_XI_CC_MATRIX_20 = 487, // Color Correction Matrix element [2][0] + CV_CAP_PROP_XI_CC_MATRIX_21 = 488, // Color Correction Matrix element [2][1] + CV_CAP_PROP_XI_CC_MATRIX_22 = 489, // Color Correction Matrix element [2][2] + CV_CAP_PROP_XI_CC_MATRIX_23 = 490, // Color Correction Matrix element [2][3] + CV_CAP_PROP_XI_CC_MATRIX_30 = 491, // Color Correction Matrix element [3][0] + CV_CAP_PROP_XI_CC_MATRIX_31 = 492, // Color Correction Matrix element [3][1] + CV_CAP_PROP_XI_CC_MATRIX_32 = 493, // Color Correction Matrix element [3][2] + CV_CAP_PROP_XI_CC_MATRIX_33 = 494, // Color Correction Matrix element [3][3] + CV_CAP_PROP_XI_DEFAULT_CC_MATRIX = 495, // Set default Color Correction Matrix + CV_CAP_PROP_XI_TRG_SELECTOR = 498, // Selects the type of trigger. + CV_CAP_PROP_XI_ACQ_FRAME_BURST_COUNT = 499, // Sets number of frames acquired by burst. This burst is used only if trigger is set to FrameBurstStart + CV_CAP_PROP_XI_DEBOUNCE_EN = 507, // Enable/Disable debounce to selected GPI + CV_CAP_PROP_XI_DEBOUNCE_T0 = 508, // Debounce time (x * 10us) + CV_CAP_PROP_XI_DEBOUNCE_T1 = 509, // Debounce time (x * 10us) + CV_CAP_PROP_XI_DEBOUNCE_POL = 510, // Debounce polarity (pol = 1 t0 - falling edge, t1 - rising edge) + CV_CAP_PROP_XI_LENS_MODE = 511, // Status of lens control interface. This shall be set to XI_ON before any Lens operations. + CV_CAP_PROP_XI_LENS_APERTURE_VALUE = 512, // Current lens aperture value in stops. Examples: 2.8, 4, 5.6, 8, 11 + CV_CAP_PROP_XI_LENS_FOCUS_MOVEMENT_VALUE = 513, // Lens current focus movement value to be used by XI_PRM_LENS_FOCUS_MOVE in motor steps. + CV_CAP_PROP_XI_LENS_FOCUS_MOVE = 514, // Moves lens focus motor by steps set in XI_PRM_LENS_FOCUS_MOVEMENT_VALUE. + CV_CAP_PROP_XI_LENS_FOCUS_DISTANCE = 515, // Lens focus distance in cm. + CV_CAP_PROP_XI_LENS_FOCAL_LENGTH = 516, // Lens focal distance in mm. + CV_CAP_PROP_XI_LENS_FEATURE_SELECTOR = 517, // Selects the current feature which is accessible by XI_PRM_LENS_FEATURE. + CV_CAP_PROP_XI_LENS_FEATURE = 518, // Allows access to lens feature value currently selected by XI_PRM_LENS_FEATURE_SELECTOR. + CV_CAP_PROP_XI_DEVICE_MODEL_ID = 521, // Return device model id + CV_CAP_PROP_XI_DEVICE_SN = 522, // Return device serial number + CV_CAP_PROP_XI_IMAGE_DATA_FORMAT_RGB32_ALPHA = 529, // The alpha channel of RGB32 output image format. + CV_CAP_PROP_XI_IMAGE_PAYLOAD_SIZE = 530, // Buffer size in bytes sufficient for output image returned by xiGetImage + CV_CAP_PROP_XI_TRANSPORT_PIXEL_FORMAT = 531, // Current format of pixels on transport layer. + CV_CAP_PROP_XI_SENSOR_CLOCK_FREQ_HZ = 532, // Sensor clock frequency in Hz. + CV_CAP_PROP_XI_SENSOR_CLOCK_FREQ_INDEX = 533, // Sensor clock frequency index. Sensor with selected frequencies have possibility to set the frequency only by this index. + CV_CAP_PROP_XI_SENSOR_OUTPUT_CHANNEL_COUNT = 534, // Number of output channels from sensor used for data transfer. + CV_CAP_PROP_XI_FRAMERATE = 535, // Define framerate in Hz + CV_CAP_PROP_XI_COUNTER_SELECTOR = 536, // Select counter + CV_CAP_PROP_XI_COUNTER_VALUE = 537, // Counter status + CV_CAP_PROP_XI_ACQ_TIMING_MODE = 538, // Type of sensor frames timing. + CV_CAP_PROP_XI_AVAILABLE_BANDWIDTH = 539, // Calculate and return available interface bandwidth(int Megabits) + CV_CAP_PROP_XI_BUFFER_POLICY = 540, // Data move policy + CV_CAP_PROP_XI_LUT_EN = 541, // Activates LUT. + CV_CAP_PROP_XI_LUT_INDEX = 542, // Control the index (offset) of the coefficient to access in the LUT. + CV_CAP_PROP_XI_LUT_VALUE = 543, // Value at entry LUTIndex of the LUT + CV_CAP_PROP_XI_TRG_DELAY = 544, // Specifies the delay in microseconds (us) to apply after the trigger reception before activating it. + CV_CAP_PROP_XI_TS_RST_MODE = 545, // Defines how time stamp reset engine will be armed + CV_CAP_PROP_XI_TS_RST_SOURCE = 546, // Defines which source will be used for timestamp reset. Writing this parameter will trigger settings of engine (arming) + CV_CAP_PROP_XI_IS_DEVICE_EXIST = 547, // Returns 1 if camera connected and works properly. + CV_CAP_PROP_XI_ACQ_BUFFER_SIZE = 548, // Acquisition buffer size in buffer_size_unit. Default bytes. + CV_CAP_PROP_XI_ACQ_BUFFER_SIZE_UNIT = 549, // Acquisition buffer size unit in bytes. Default 1. E.g. Value 1024 means that buffer_size is in KiBytes + CV_CAP_PROP_XI_ACQ_TRANSPORT_BUFFER_SIZE = 550, // Acquisition transport buffer size in bytes + CV_CAP_PROP_XI_BUFFERS_QUEUE_SIZE = 551, // Queue of field/frame buffers + CV_CAP_PROP_XI_ACQ_TRANSPORT_BUFFER_COMMIT = 552, // Number of buffers to commit to low level + CV_CAP_PROP_XI_RECENT_FRAME = 553, // GetImage returns most recent frame + CV_CAP_PROP_XI_DEVICE_RESET = 554, // Resets the camera to default state. + CV_CAP_PROP_XI_COLUMN_FPN_CORRECTION = 555, // Correction of column FPN + CV_CAP_PROP_XI_ROW_FPN_CORRECTION = 591, // Correction of row FPN + CV_CAP_PROP_XI_SENSOR_MODE = 558, // Current sensor mode. Allows to select sensor mode by one integer. Setting of this parameter affects: image dimensions and downsampling. + CV_CAP_PROP_XI_HDR = 559, // Enable High Dynamic Range feature. + CV_CAP_PROP_XI_HDR_KNEEPOINT_COUNT = 560, // The number of kneepoints in the PWLR. + CV_CAP_PROP_XI_HDR_T1 = 561, // position of first kneepoint(in % of XI_PRM_EXPOSURE) + CV_CAP_PROP_XI_HDR_T2 = 562, // position of second kneepoint (in % of XI_PRM_EXPOSURE) + CV_CAP_PROP_XI_KNEEPOINT1 = 563, // value of first kneepoint (% of sensor saturation) + CV_CAP_PROP_XI_KNEEPOINT2 = 564, // value of second kneepoint (% of sensor saturation) + CV_CAP_PROP_XI_IMAGE_BLACK_LEVEL = 565, // Last image black level counts. Can be used for Offline processing to recall it. + CV_CAP_PROP_XI_HW_REVISION = 571, // Returns hardware revision number. + CV_CAP_PROP_XI_DEBUG_LEVEL = 572, // Set debug level + CV_CAP_PROP_XI_AUTO_BANDWIDTH_CALCULATION = 573, // Automatic bandwidth calculation, + CV_CAP_PROP_XI_FFS_FILE_ID = 594, // File number. + CV_CAP_PROP_XI_FFS_FILE_SIZE = 580, // Size of file. + CV_CAP_PROP_XI_FREE_FFS_SIZE = 581, // Size of free camera FFS. + CV_CAP_PROP_XI_USED_FFS_SIZE = 582, // Size of used camera FFS. + CV_CAP_PROP_XI_FFS_ACCESS_KEY = 583, // Setting of key enables file operations on some cameras. + CV_CAP_PROP_XI_SENSOR_FEATURE_SELECTOR = 585, // Selects the current feature which is accessible by XI_PRM_SENSOR_FEATURE_VALUE. + CV_CAP_PROP_XI_SENSOR_FEATURE_VALUE = 586, // Allows access to sensor feature value currently selected by XI_PRM_SENSOR_FEATURE_SELECTOR. + + + // Properties for Android cameras + CV_CAP_PROP_ANDROID_FLASH_MODE = 8001, + CV_CAP_PROP_ANDROID_FOCUS_MODE = 8002, + CV_CAP_PROP_ANDROID_WHITE_BALANCE = 8003, + CV_CAP_PROP_ANDROID_ANTIBANDING = 8004, + CV_CAP_PROP_ANDROID_FOCAL_LENGTH = 8005, + CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_NEAR = 8006, + CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_OPTIMAL = 8007, + CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_FAR = 8008, + CV_CAP_PROP_ANDROID_EXPOSE_LOCK = 8009, + CV_CAP_PROP_ANDROID_WHITEBALANCE_LOCK = 8010, + + // Properties of cameras available through AVFOUNDATION interface + CV_CAP_PROP_IOS_DEVICE_FOCUS = 9001, + CV_CAP_PROP_IOS_DEVICE_EXPOSURE = 9002, + CV_CAP_PROP_IOS_DEVICE_FLASH = 9003, + CV_CAP_PROP_IOS_DEVICE_WHITEBALANCE = 9004, + CV_CAP_PROP_IOS_DEVICE_TORCH = 9005, + + // Properties of cameras available through Smartek Giganetix Ethernet Vision interface + /* --- Vladimir Litvinenko (litvinenko.vladimir@gmail.com) --- */ + CV_CAP_PROP_GIGA_FRAME_OFFSET_X = 10001, + CV_CAP_PROP_GIGA_FRAME_OFFSET_Y = 10002, + CV_CAP_PROP_GIGA_FRAME_WIDTH_MAX = 10003, + CV_CAP_PROP_GIGA_FRAME_HEIGH_MAX = 10004, + CV_CAP_PROP_GIGA_FRAME_SENS_WIDTH = 10005, + CV_CAP_PROP_GIGA_FRAME_SENS_HEIGH = 10006, + + CV_CAP_PROP_INTELPERC_PROFILE_COUNT = 11001, + CV_CAP_PROP_INTELPERC_PROFILE_IDX = 11002, + CV_CAP_PROP_INTELPERC_DEPTH_LOW_CONFIDENCE_VALUE = 11003, + CV_CAP_PROP_INTELPERC_DEPTH_SATURATION_VALUE = 11004, + CV_CAP_PROP_INTELPERC_DEPTH_CONFIDENCE_THRESHOLD = 11005, + CV_CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_HORZ = 11006, + CV_CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_VERT = 11007, + + // Intel PerC streams + CV_CAP_INTELPERC_DEPTH_GENERATOR = 1 << 29, + CV_CAP_INTELPERC_IMAGE_GENERATOR = 1 << 28, + CV_CAP_INTELPERC_GENERATORS_MASK = CV_CAP_INTELPERC_DEPTH_GENERATOR + CV_CAP_INTELPERC_IMAGE_GENERATOR +}; + +enum +{ + // Data given from depth generator. + CV_CAP_OPENNI_DEPTH_MAP = 0, // Depth values in mm (CV_16UC1) + CV_CAP_OPENNI_POINT_CLOUD_MAP = 1, // XYZ in meters (CV_32FC3) + CV_CAP_OPENNI_DISPARITY_MAP = 2, // Disparity in pixels (CV_8UC1) + CV_CAP_OPENNI_DISPARITY_MAP_32F = 3, // Disparity in pixels (CV_32FC1) + CV_CAP_OPENNI_VALID_DEPTH_MASK = 4, // CV_8UC1 + + // Data given from RGB image generator. + CV_CAP_OPENNI_BGR_IMAGE = 5, + CV_CAP_OPENNI_GRAY_IMAGE = 6, + + // Data given from IR image generator. + CV_CAP_OPENNI_IR_IMAGE = 7 +}; + +// Supported output modes of OpenNI image generator +enum +{ + CV_CAP_OPENNI_VGA_30HZ = 0, + CV_CAP_OPENNI_SXGA_15HZ = 1, + CV_CAP_OPENNI_SXGA_30HZ = 2, + CV_CAP_OPENNI_QVGA_30HZ = 3, + CV_CAP_OPENNI_QVGA_60HZ = 4 +}; + +enum +{ + CV_CAP_INTELPERC_DEPTH_MAP = 0, // Each pixel is a 16-bit integer. The value indicates the distance from an object to the camera's XY plane or the Cartesian depth. + CV_CAP_INTELPERC_UVDEPTH_MAP = 1, // Each pixel contains two 32-bit floating point values in the range of 0-1, representing the mapping of depth coordinates to the color coordinates. + CV_CAP_INTELPERC_IR_MAP = 2, // Each pixel is a 16-bit integer. The value indicates the intensity of the reflected laser beam. + CV_CAP_INTELPERC_IMAGE = 3 +}; + +// gPhoto2 properties, if propertyId is less than 0 then work on widget with that __additive inversed__ camera setting ID +// Get IDs by using CAP_PROP_GPHOTO2_WIDGET_ENUMERATE. +// @see CvCaptureCAM_GPHOTO2 for more info +enum +{ + CV_CAP_PROP_GPHOTO2_PREVIEW = 17001, // Capture only preview from liveview mode. + CV_CAP_PROP_GPHOTO2_WIDGET_ENUMERATE = 17002, // Readonly, returns (const char *). + CV_CAP_PROP_GPHOTO2_RELOAD_CONFIG = 17003, // Trigger, only by set. Reload camera settings. + CV_CAP_PROP_GPHOTO2_RELOAD_ON_CHANGE = 17004, // Reload all settings on set. + CV_CAP_PROP_GPHOTO2_COLLECT_MSGS = 17005, // Collect messages with details. + CV_CAP_PROP_GPHOTO2_FLUSH_MSGS = 17006, // Readonly, returns (const char *). + CV_CAP_PROP_SPEED = 17007, // Exposure speed. Can be readonly, depends on camera program. + CV_CAP_PROP_APERTURE = 17008, // Aperture. Can be readonly, depends on camera program. + CV_CAP_PROP_EXPOSUREPROGRAM = 17009, // Camera exposure program. + CV_CAP_PROP_VIEWFINDER = 17010 // Enter liveview mode. +}; + +//! (Windows only) Open Codec Selection Dialog +#define CV_FOURCC_PROMPT -1 +//! (Linux only) Use default codec for specified filename +#define CV_FOURCC_DEFAULT CV_FOURCC('I', 'Y', 'U', 'V') + +#endif // OPENCV_VIDEOIO_LEGACY_CONSTANTS_H diff --git a/3rdParty/opencv-4.11.0/opencv2/videoio/registry.hpp b/3rdParty/opencv-4.11.0/opencv2/videoio/registry.hpp index 47e94b1909..a60d0e87bc 100644 --- a/3rdParty/opencv-4.11.0/opencv2/videoio/registry.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/videoio/registry.hpp @@ -1,82 +1,82 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_VIDEOIO_REGISTRY_HPP -#define OPENCV_VIDEOIO_REGISTRY_HPP - -#include - -namespace cv { namespace videoio_registry { -/** @addtogroup videoio_registry -This section contains API description how to query/configure available Video I/O backends. - -Runtime configuration options: -- enable debug mode: `OPENCV_VIDEOIO_DEBUG=1` -- change backend priority: `OPENCV_VIDEOIO_PRIORITY_=9999` -- disable backend: `OPENCV_VIDEOIO_PRIORITY_=0` -- specify list of backends with high priority (>100000): `OPENCV_VIDEOIO_PRIORITY_LIST=FFMPEG,GSTREAMER` - -@{ - */ - - -/** @brief Returns backend API name or "UnknownVideoAPI(xxx)" -@param api backend ID (#VideoCaptureAPIs) -*/ -CV_EXPORTS_W cv::String getBackendName(VideoCaptureAPIs api); - -/** @brief Returns list of all available backends */ -CV_EXPORTS_W std::vector getBackends(); - -/** @brief Returns list of available backends which works via `cv::VideoCapture(int index)` */ -CV_EXPORTS_W std::vector getCameraBackends(); - -/** @brief Returns list of available backends which works via `cv::VideoCapture(filename)` */ -CV_EXPORTS_W std::vector getStreamBackends(); - -/** @brief Returns list of available backends which works via `cv::VideoCapture(buffer)` */ -CV_EXPORTS_W std::vector getStreamBufferedBackends(); - -/** @brief Returns list of available backends which works via `cv::VideoWriter()` */ -CV_EXPORTS_W std::vector getWriterBackends(); - -/** @brief Returns true if backend is available */ -CV_EXPORTS_W bool hasBackend(VideoCaptureAPIs api); - -/** @brief Returns true if backend is built in (false if backend is used as plugin) */ -CV_EXPORTS_W bool isBackendBuiltIn(VideoCaptureAPIs api); - -/** @brief Returns description and ABI/API version of videoio plugin's camera interface */ -CV_EXPORTS_W std::string getCameraBackendPluginVersion( - VideoCaptureAPIs api, - CV_OUT int& version_ABI, - CV_OUT int& version_API -); - -/** @brief Returns description and ABI/API version of videoio plugin's stream capture interface */ -CV_EXPORTS_W std::string getStreamBackendPluginVersion( - VideoCaptureAPIs api, - CV_OUT int& version_ABI, - CV_OUT int& version_API -); - -/** @brief Returns description and ABI/API version of videoio plugin's buffer capture interface */ -CV_EXPORTS_W std::string getStreamBufferedBackendPluginVersion( - VideoCaptureAPIs api, - CV_OUT int& version_ABI, - CV_OUT int& version_API -); - -/** @brief Returns description and ABI/API version of videoio plugin's writer interface */ -CV_EXPORTS_W std::string getWriterBackendPluginVersion( - VideoCaptureAPIs api, - CV_OUT int& version_ABI, - CV_OUT int& version_API -); - - -//! @} -}} // namespace - -#endif // OPENCV_VIDEOIO_REGISTRY_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_VIDEOIO_REGISTRY_HPP +#define OPENCV_VIDEOIO_REGISTRY_HPP + +#include + +namespace cv { namespace videoio_registry { +/** @addtogroup videoio_registry +This section contains API description how to query/configure available Video I/O backends. + +Runtime configuration options: +- enable debug mode: `OPENCV_VIDEOIO_DEBUG=1` +- change backend priority: `OPENCV_VIDEOIO_PRIORITY_=9999` +- disable backend: `OPENCV_VIDEOIO_PRIORITY_=0` +- specify list of backends with high priority (>100000): `OPENCV_VIDEOIO_PRIORITY_LIST=FFMPEG,GSTREAMER` + +@{ + */ + + +/** @brief Returns backend API name or "UnknownVideoAPI(xxx)" +@param api backend ID (#VideoCaptureAPIs) +*/ +CV_EXPORTS_W cv::String getBackendName(VideoCaptureAPIs api); + +/** @brief Returns list of all available backends */ +CV_EXPORTS_W std::vector getBackends(); + +/** @brief Returns list of available backends which works via `cv::VideoCapture(int index)` */ +CV_EXPORTS_W std::vector getCameraBackends(); + +/** @brief Returns list of available backends which works via `cv::VideoCapture(filename)` */ +CV_EXPORTS_W std::vector getStreamBackends(); + +/** @brief Returns list of available backends which works via `cv::VideoCapture(buffer)` */ +CV_EXPORTS_W std::vector getStreamBufferedBackends(); + +/** @brief Returns list of available backends which works via `cv::VideoWriter()` */ +CV_EXPORTS_W std::vector getWriterBackends(); + +/** @brief Returns true if backend is available */ +CV_EXPORTS_W bool hasBackend(VideoCaptureAPIs api); + +/** @brief Returns true if backend is built in (false if backend is used as plugin) */ +CV_EXPORTS_W bool isBackendBuiltIn(VideoCaptureAPIs api); + +/** @brief Returns description and ABI/API version of videoio plugin's camera interface */ +CV_EXPORTS_W std::string getCameraBackendPluginVersion( + VideoCaptureAPIs api, + CV_OUT int& version_ABI, + CV_OUT int& version_API +); + +/** @brief Returns description and ABI/API version of videoio plugin's stream capture interface */ +CV_EXPORTS_W std::string getStreamBackendPluginVersion( + VideoCaptureAPIs api, + CV_OUT int& version_ABI, + CV_OUT int& version_API +); + +/** @brief Returns description and ABI/API version of videoio plugin's buffer capture interface */ +CV_EXPORTS_W std::string getStreamBufferedBackendPluginVersion( + VideoCaptureAPIs api, + CV_OUT int& version_ABI, + CV_OUT int& version_API +); + +/** @brief Returns description and ABI/API version of videoio plugin's writer interface */ +CV_EXPORTS_W std::string getWriterBackendPluginVersion( + VideoCaptureAPIs api, + CV_OUT int& version_ABI, + CV_OUT int& version_API +); + + +//! @} +}} // namespace + +#endif // OPENCV_VIDEOIO_REGISTRY_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/videoio/videoio.hpp b/3rdParty/opencv-4.11.0/opencv2/videoio/videoio.hpp index ec84cf7a68..00593547ac 100644 --- a/3rdParty/opencv-4.11.0/opencv2/videoio/videoio.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/videoio/videoio.hpp @@ -1,48 +1,48 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifdef __OPENCV_BUILD -#error this is a compatibility header which should not be used inside the OpenCV library -#endif - -#include "opencv2/videoio.hpp" +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/videoio.hpp" diff --git a/3rdParty/opencv-4.11.0/opencv2/videoio/videoio_c.h b/3rdParty/opencv-4.11.0/opencv2/videoio/videoio_c.h index cf1a6d0411..3f6efd9d54 100644 --- a/3rdParty/opencv-4.11.0/opencv2/videoio/videoio_c.h +++ b/3rdParty/opencv-4.11.0/opencv2/videoio/videoio_c.h @@ -1,153 +1,153 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_VIDEOIO_H -#define OPENCV_VIDEOIO_H - -#include "opencv2/core/core_c.h" - -#include "opencv2/videoio/legacy/constants_c.h" - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/** - @addtogroup videoio_c - @{ -*/ - -/****************************************************************************************\ -* Working with Video Files and Cameras * -\****************************************************************************************/ - -/** @brief "black box" capture structure - -In C++ use cv::VideoCapture -*/ -typedef struct CvCapture CvCapture; - -/** @brief start capturing frames from video file -*/ -CVAPI(CvCapture*) cvCreateFileCapture( const char* filename ); - -/** @brief start capturing frames from video file. allows specifying a preferred API to use -*/ -CVAPI(CvCapture*) cvCreateFileCaptureWithPreference( const char* filename , int apiPreference); - -/** @brief start capturing frames from camera: index = camera_index + domain_offset (CV_CAP_*) -*/ -CVAPI(CvCapture*) cvCreateCameraCapture( int index ); - -/** @brief grab a frame, return 1 on success, 0 on fail. - - this function is thought to be fast -*/ -CVAPI(int) cvGrabFrame( CvCapture* capture ); - -/** @brief get the frame grabbed with cvGrabFrame(..) - - This function may apply some frame processing like - frame decompression, flipping etc. - @warning !!!DO NOT RELEASE or MODIFY the retrieved frame!!! -*/ -CVAPI(IplImage*) cvRetrieveFrame( CvCapture* capture, int streamIdx CV_DEFAULT(0) ); - -/** @brief Just a combination of cvGrabFrame and cvRetrieveFrame - - @warning !!!DO NOT RELEASE or MODIFY the retrieved frame!!! -*/ -CVAPI(IplImage*) cvQueryFrame( CvCapture* capture ); - -/** @brief stop capturing/reading and free resources -*/ -CVAPI(void) cvReleaseCapture( CvCapture** capture ); - -/** @brief retrieve capture properties -*/ -CVAPI(double) cvGetCaptureProperty( CvCapture* capture, int property_id ); -/** @brief set capture properties -*/ -CVAPI(int) cvSetCaptureProperty( CvCapture* capture, int property_id, double value ); - -/** @brief Return the type of the capturer (eg, ::CV_CAP_VFW, ::CV_CAP_UNICAP) - -It is unknown if created with ::CV_CAP_ANY -*/ -CVAPI(int) cvGetCaptureDomain( CvCapture* capture); - -/** @brief "black box" video file writer structure - -In C++ use cv::VideoWriter -*/ -typedef struct CvVideoWriter CvVideoWriter; - -/** @brief initialize video file writer -*/ -CVAPI(CvVideoWriter*) cvCreateVideoWriter( const char* filename, int fourcc, - double fps, CvSize frame_size, - int is_color CV_DEFAULT(1)); - -/** @brief write frame to video file -*/ -CVAPI(int) cvWriteFrame( CvVideoWriter* writer, const IplImage* image ); - -/** @brief close video file writer -*/ -CVAPI(void) cvReleaseVideoWriter( CvVideoWriter** writer ); - -// *************************************************************************************** -//! @name Obsolete functions/synonyms -//! @{ -#define cvCaptureFromCAM cvCreateCameraCapture //!< @deprecated use cvCreateCameraCapture() instead -#define cvCaptureFromFile cvCreateFileCapture //!< @deprecated use cvCreateFileCapture() instead -#define cvCaptureFromAVI cvCaptureFromFile //!< @deprecated use cvCreateFileCapture() instead -#define cvCreateAVIWriter cvCreateVideoWriter //!< @deprecated use cvCreateVideoWriter() instead -#define cvWriteToAVI cvWriteFrame //!< @deprecated use cvWriteFrame() instead -//! @} Obsolete... - -//! @} videoio_c - -#ifdef __cplusplus -} -#endif - -#endif //OPENCV_VIDEOIO_H +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// Intel License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000, Intel Corporation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of Intel Corporation may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_VIDEOIO_H +#define OPENCV_VIDEOIO_H + +#include "opencv2/core/core_c.h" + +#include "opencv2/videoio/legacy/constants_c.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + @addtogroup videoio_c + @{ +*/ + +/****************************************************************************************\ +* Working with Video Files and Cameras * +\****************************************************************************************/ + +/** @brief "black box" capture structure + +In C++ use cv::VideoCapture +*/ +typedef struct CvCapture CvCapture; + +/** @brief start capturing frames from video file +*/ +CVAPI(CvCapture*) cvCreateFileCapture( const char* filename ); + +/** @brief start capturing frames from video file. allows specifying a preferred API to use +*/ +CVAPI(CvCapture*) cvCreateFileCaptureWithPreference( const char* filename , int apiPreference); + +/** @brief start capturing frames from camera: index = camera_index + domain_offset (CV_CAP_*) +*/ +CVAPI(CvCapture*) cvCreateCameraCapture( int index ); + +/** @brief grab a frame, return 1 on success, 0 on fail. + + this function is thought to be fast +*/ +CVAPI(int) cvGrabFrame( CvCapture* capture ); + +/** @brief get the frame grabbed with cvGrabFrame(..) + + This function may apply some frame processing like + frame decompression, flipping etc. + @warning !!!DO NOT RELEASE or MODIFY the retrieved frame!!! +*/ +CVAPI(IplImage*) cvRetrieveFrame( CvCapture* capture, int streamIdx CV_DEFAULT(0) ); + +/** @brief Just a combination of cvGrabFrame and cvRetrieveFrame + + @warning !!!DO NOT RELEASE or MODIFY the retrieved frame!!! +*/ +CVAPI(IplImage*) cvQueryFrame( CvCapture* capture ); + +/** @brief stop capturing/reading and free resources +*/ +CVAPI(void) cvReleaseCapture( CvCapture** capture ); + +/** @brief retrieve capture properties +*/ +CVAPI(double) cvGetCaptureProperty( CvCapture* capture, int property_id ); +/** @brief set capture properties +*/ +CVAPI(int) cvSetCaptureProperty( CvCapture* capture, int property_id, double value ); + +/** @brief Return the type of the capturer (eg, ::CV_CAP_VFW, ::CV_CAP_UNICAP) + +It is unknown if created with ::CV_CAP_ANY +*/ +CVAPI(int) cvGetCaptureDomain( CvCapture* capture); + +/** @brief "black box" video file writer structure + +In C++ use cv::VideoWriter +*/ +typedef struct CvVideoWriter CvVideoWriter; + +/** @brief initialize video file writer +*/ +CVAPI(CvVideoWriter*) cvCreateVideoWriter( const char* filename, int fourcc, + double fps, CvSize frame_size, + int is_color CV_DEFAULT(1)); + +/** @brief write frame to video file +*/ +CVAPI(int) cvWriteFrame( CvVideoWriter* writer, const IplImage* image ); + +/** @brief close video file writer +*/ +CVAPI(void) cvReleaseVideoWriter( CvVideoWriter** writer ); + +// *************************************************************************************** +//! @name Obsolete functions/synonyms +//! @{ +#define cvCaptureFromCAM cvCreateCameraCapture //!< @deprecated use cvCreateCameraCapture() instead +#define cvCaptureFromFile cvCreateFileCapture //!< @deprecated use cvCreateFileCapture() instead +#define cvCaptureFromAVI cvCaptureFromFile //!< @deprecated use cvCreateFileCapture() instead +#define cvCreateAVIWriter cvCreateVideoWriter //!< @deprecated use cvCreateVideoWriter() instead +#define cvWriteToAVI cvWriteFrame //!< @deprecated use cvWriteFrame() instead +//! @} Obsolete... + +//! @} videoio_c + +#ifdef __cplusplus +} +#endif + +#endif //OPENCV_VIDEOIO_H diff --git a/3rdParty/opencv-4.11.0/opencv2/world.hpp b/3rdParty/opencv-4.11.0/opencv2/world.hpp index 4902c2f2a6..8ee6068939 100644 --- a/3rdParty/opencv-4.11.0/opencv2/world.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/world.hpp @@ -1,58 +1,58 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009-2010, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's 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. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders 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 Intel Corporation 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. -// -//M*/ - -#ifndef OPENCV_WORLD_HPP -#define OPENCV_WORLD_HPP - -#include "opencv2/core.hpp" - -#ifdef __cplusplus -namespace cv -{ - -CV_EXPORTS_W bool initAll(); - -} - -#endif - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009-2010, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's 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. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders 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 Intel Corporation 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. +// +//M*/ + +#ifndef OPENCV_WORLD_HPP +#define OPENCV_WORLD_HPP + +#include "opencv2/core.hpp" + +#ifdef __cplusplus +namespace cv +{ + +CV_EXPORTS_W bool initAll(); + +} + +#endif + +#endif diff --git a/3rdParty/qdarkstyle/dark/__init__.py b/3rdParty/qdarkstyle/dark/__init__.py index faaaf799c7..0bd233716d 100644 --- a/3rdParty/qdarkstyle/dark/__init__.py +++ b/3rdParty/qdarkstyle/dark/__init__.py @@ -1,3 +1,3 @@ -# -*- coding: utf-8 -*- - - +# -*- coding: utf-8 -*- + + diff --git a/3rdParty/qdarkstyle/dark/_variables.scss b/3rdParty/qdarkstyle/dark/_variables.scss index d8f1bbedc8..438b8e5a0f 100644 --- a/3rdParty/qdarkstyle/dark/_variables.scss +++ b/3rdParty/qdarkstyle/dark/_variables.scss @@ -1,33 +1,33 @@ -// --------------------------------------------------------------------------- -// -// WARNING! File created programmatically. All changes made in this file will be lost! -// -// Created by the qtsass compiler v0.3.0 -// -// The definitions are in the "qdarkstyle.palette" module -// -//---------------------------------------------------------------------------- -$ID: 'dark'; -$COLOR_BACKGROUND_6: #60798B; -$COLOR_BACKGROUND_5: #54687A; -$COLOR_BACKGROUND_4: #455364; -$COLOR_BACKGROUND_2: #293544; -$COLOR_BACKGROUND_3: #37414F; -$COLOR_BACKGROUND_1: #19232D; -$COLOR_TEXT_1: #E0E1E3; -$COLOR_TEXT_2: #C9CDD0; -$COLOR_TEXT_3: #ACB1B6; -$COLOR_TEXT_4: #9DA9B5; -$COLOR_ACCENT_1: #26486B; -$COLOR_ACCENT_2: #346792; -$COLOR_ACCENT_3: #1A72BB; -$COLOR_ACCENT_4: #259AE9; -$OPACITY_TOOLTIP: 230; -$SIZE_BORDER_RADIUS: 4px; -$BORDER_1: 1px solid $COLOR_BACKGROUND_1; -$BORDER_2: 1px solid $COLOR_BACKGROUND_4; -$BORDER_3: 1px solid $COLOR_BACKGROUND_6; -$BORDER_SELECTION_3: 1px solid $COLOR_ACCENT_3; -$BORDER_SELECTION_2: 1px solid $COLOR_ACCENT_2; -$BORDER_SELECTION_1: 1px solid $COLOR_ACCENT_1; -$PATH_RESOURCES: ':/qss_icons'; +// --------------------------------------------------------------------------- +// +// WARNING! File created programmatically. All changes made in this file will be lost! +// +// Created by the qtsass compiler v0.3.0 +// +// The definitions are in the "qdarkstyle.palette" module +// +//---------------------------------------------------------------------------- +$ID: 'dark'; +$COLOR_BACKGROUND_6: #60798B; +$COLOR_BACKGROUND_5: #54687A; +$COLOR_BACKGROUND_4: #455364; +$COLOR_BACKGROUND_2: #293544; +$COLOR_BACKGROUND_3: #37414F; +$COLOR_BACKGROUND_1: #19232D; +$COLOR_TEXT_1: #E0E1E3; +$COLOR_TEXT_2: #C9CDD0; +$COLOR_TEXT_3: #ACB1B6; +$COLOR_TEXT_4: #9DA9B5; +$COLOR_ACCENT_1: #26486B; +$COLOR_ACCENT_2: #346792; +$COLOR_ACCENT_3: #1A72BB; +$COLOR_ACCENT_4: #259AE9; +$OPACITY_TOOLTIP: 230; +$SIZE_BORDER_RADIUS: 4px; +$BORDER_1: 1px solid $COLOR_BACKGROUND_1; +$BORDER_2: 1px solid $COLOR_BACKGROUND_4; +$BORDER_3: 1px solid $COLOR_BACKGROUND_6; +$BORDER_SELECTION_3: 1px solid $COLOR_ACCENT_3; +$BORDER_SELECTION_2: 1px solid $COLOR_ACCENT_2; +$BORDER_SELECTION_1: 1px solid $COLOR_ACCENT_1; +$PATH_RESOURCES: ':/qss_icons'; diff --git a/3rdParty/qdarkstyle/dark/darkstyle.qrc b/3rdParty/qdarkstyle/dark/darkstyle.qrc index ce0d85be60..61664aacc2 100644 --- a/3rdParty/qdarkstyle/dark/darkstyle.qrc +++ b/3rdParty/qdarkstyle/dark/darkstyle.qrc @@ -1,216 +1,216 @@ - - - - rc/arrow_down.png - rc/arrow_down@2x.png - rc/arrow_down_disabled.png - rc/arrow_down_disabled@2x.png - rc/arrow_down_focus.png - rc/arrow_down_focus@2x.png - rc/arrow_down_pressed.png - rc/arrow_down_pressed@2x.png - rc/arrow_left.png - rc/arrow_left@2x.png - rc/arrow_left_disabled.png - rc/arrow_left_disabled@2x.png - rc/arrow_left_focus.png - rc/arrow_left_focus@2x.png - rc/arrow_left_pressed.png - rc/arrow_left_pressed@2x.png - rc/arrow_right.png - rc/arrow_right@2x.png - rc/arrow_right_disabled.png - rc/arrow_right_disabled@2x.png - rc/arrow_right_focus.png - rc/arrow_right_focus@2x.png - rc/arrow_right_pressed.png - rc/arrow_right_pressed@2x.png - rc/arrow_up.png - rc/arrow_up@2x.png - rc/arrow_up_disabled.png - rc/arrow_up_disabled@2x.png - rc/arrow_up_focus.png - rc/arrow_up_focus@2x.png - rc/arrow_up_pressed.png - rc/arrow_up_pressed@2x.png - rc/base_icon.png - rc/base_icon@2x.png - rc/base_icon_disabled.png - rc/base_icon_disabled@2x.png - rc/base_icon_focus.png - rc/base_icon_focus@2x.png - rc/base_icon_pressed.png - rc/base_icon_pressed@2x.png - rc/branch_closed.png - rc/branch_closed@2x.png - rc/branch_closed_disabled.png - rc/branch_closed_disabled@2x.png - rc/branch_closed_focus.png - rc/branch_closed_focus@2x.png - rc/branch_closed_pressed.png - rc/branch_closed_pressed@2x.png - rc/branch_end.png - rc/branch_end@2x.png - rc/branch_end_disabled.png - rc/branch_end_disabled@2x.png - rc/branch_end_focus.png - rc/branch_end_focus@2x.png - rc/branch_end_pressed.png - rc/branch_end_pressed@2x.png - rc/branch_line.png - rc/branch_line@2x.png - rc/branch_line_disabled.png - rc/branch_line_disabled@2x.png - rc/branch_line_focus.png - rc/branch_line_focus@2x.png - rc/branch_line_pressed.png - rc/branch_line_pressed@2x.png - rc/branch_more.png - rc/branch_more@2x.png - rc/branch_more_disabled.png - rc/branch_more_disabled@2x.png - rc/branch_more_focus.png - rc/branch_more_focus@2x.png - rc/branch_more_pressed.png - rc/branch_more_pressed@2x.png - rc/branch_open.png - rc/branch_open@2x.png - rc/branch_open_disabled.png - rc/branch_open_disabled@2x.png - rc/branch_open_focus.png - rc/branch_open_focus@2x.png - rc/branch_open_pressed.png - rc/branch_open_pressed@2x.png - rc/checkbox_checked.png - rc/checkbox_checked@2x.png - rc/checkbox_checked_disabled.png - rc/checkbox_checked_disabled@2x.png - rc/checkbox_checked_focus.png - rc/checkbox_checked_focus@2x.png - rc/checkbox_checked_pressed.png - rc/checkbox_checked_pressed@2x.png - rc/checkbox_indeterminate.png - rc/checkbox_indeterminate@2x.png - rc/checkbox_indeterminate_disabled.png - rc/checkbox_indeterminate_disabled@2x.png - rc/checkbox_indeterminate_focus.png - rc/checkbox_indeterminate_focus@2x.png - rc/checkbox_indeterminate_pressed.png - rc/checkbox_indeterminate_pressed@2x.png - rc/checkbox_unchecked.png - rc/checkbox_unchecked@2x.png - rc/checkbox_unchecked_disabled.png - rc/checkbox_unchecked_disabled@2x.png - rc/checkbox_unchecked_focus.png - rc/checkbox_unchecked_focus@2x.png - rc/checkbox_unchecked_pressed.png - rc/checkbox_unchecked_pressed@2x.png - rc/line_horizontal.png - rc/line_horizontal@2x.png - rc/line_horizontal_disabled.png - rc/line_horizontal_disabled@2x.png - rc/line_horizontal_focus.png - rc/line_horizontal_focus@2x.png - rc/line_horizontal_pressed.png - rc/line_horizontal_pressed@2x.png - rc/line_vertical.png - rc/line_vertical@2x.png - rc/line_vertical_disabled.png - rc/line_vertical_disabled@2x.png - rc/line_vertical_focus.png - rc/line_vertical_focus@2x.png - rc/line_vertical_pressed.png - rc/line_vertical_pressed@2x.png - rc/radio_checked.png - rc/radio_checked@2x.png - rc/radio_checked_disabled.png - rc/radio_checked_disabled@2x.png - rc/radio_checked_focus.png - rc/radio_checked_focus@2x.png - rc/radio_checked_pressed.png - rc/radio_checked_pressed@2x.png - rc/radio_unchecked.png - rc/radio_unchecked@2x.png - rc/radio_unchecked_disabled.png - rc/radio_unchecked_disabled@2x.png - rc/radio_unchecked_focus.png - rc/radio_unchecked_focus@2x.png - rc/radio_unchecked_pressed.png - rc/radio_unchecked_pressed@2x.png - rc/toolbar_move_horizontal.png - rc/toolbar_move_horizontal@2x.png - rc/toolbar_move_horizontal_disabled.png - rc/toolbar_move_horizontal_disabled@2x.png - rc/toolbar_move_horizontal_focus.png - rc/toolbar_move_horizontal_focus@2x.png - rc/toolbar_move_horizontal_pressed.png - rc/toolbar_move_horizontal_pressed@2x.png - rc/toolbar_move_vertical.png - rc/toolbar_move_vertical@2x.png - rc/toolbar_move_vertical_disabled.png - rc/toolbar_move_vertical_disabled@2x.png - rc/toolbar_move_vertical_focus.png - rc/toolbar_move_vertical_focus@2x.png - rc/toolbar_move_vertical_pressed.png - rc/toolbar_move_vertical_pressed@2x.png - rc/toolbar_separator_horizontal.png - rc/toolbar_separator_horizontal@2x.png - rc/toolbar_separator_horizontal_disabled.png - rc/toolbar_separator_horizontal_disabled@2x.png - rc/toolbar_separator_horizontal_focus.png - rc/toolbar_separator_horizontal_focus@2x.png - rc/toolbar_separator_horizontal_pressed.png - rc/toolbar_separator_horizontal_pressed@2x.png - rc/toolbar_separator_vertical.png - rc/toolbar_separator_vertical@2x.png - rc/toolbar_separator_vertical_disabled.png - rc/toolbar_separator_vertical_disabled@2x.png - rc/toolbar_separator_vertical_focus.png - rc/toolbar_separator_vertical_focus@2x.png - rc/toolbar_separator_vertical_pressed.png - rc/toolbar_separator_vertical_pressed@2x.png - rc/transparent.png - rc/transparent@2x.png - rc/transparent_disabled.png - rc/transparent_disabled@2x.png - rc/transparent_focus.png - rc/transparent_focus@2x.png - rc/transparent_pressed.png - rc/transparent_pressed@2x.png - rc/window_close.png - rc/window_close@2x.png - rc/window_close_disabled.png - rc/window_close_disabled@2x.png - rc/window_close_focus.png - rc/window_close_focus@2x.png - rc/window_close_pressed.png - rc/window_close_pressed@2x.png - rc/window_grip.png - rc/window_grip@2x.png - rc/window_grip_disabled.png - rc/window_grip_disabled@2x.png - rc/window_grip_focus.png - rc/window_grip_focus@2x.png - rc/window_grip_pressed.png - rc/window_grip_pressed@2x.png - rc/window_minimize.png - rc/window_minimize@2x.png - rc/window_minimize_disabled.png - rc/window_minimize_disabled@2x.png - rc/window_minimize_focus.png - rc/window_minimize_focus@2x.png - rc/window_minimize_pressed.png - rc/window_minimize_pressed@2x.png - rc/window_undock.png - rc/window_undock@2x.png - rc/window_undock_disabled.png - rc/window_undock_disabled@2x.png - rc/window_undock_focus.png - rc/window_undock_focus@2x.png - rc/window_undock_pressed.png - rc/window_undock_pressed@2x.png - - - darkstyle.qss - - + + + + rc/arrow_down.png + rc/arrow_down@2x.png + rc/arrow_down_disabled.png + rc/arrow_down_disabled@2x.png + rc/arrow_down_focus.png + rc/arrow_down_focus@2x.png + rc/arrow_down_pressed.png + rc/arrow_down_pressed@2x.png + rc/arrow_left.png + rc/arrow_left@2x.png + rc/arrow_left_disabled.png + rc/arrow_left_disabled@2x.png + rc/arrow_left_focus.png + rc/arrow_left_focus@2x.png + rc/arrow_left_pressed.png + rc/arrow_left_pressed@2x.png + rc/arrow_right.png + rc/arrow_right@2x.png + rc/arrow_right_disabled.png + rc/arrow_right_disabled@2x.png + rc/arrow_right_focus.png + rc/arrow_right_focus@2x.png + rc/arrow_right_pressed.png + rc/arrow_right_pressed@2x.png + rc/arrow_up.png + rc/arrow_up@2x.png + rc/arrow_up_disabled.png + rc/arrow_up_disabled@2x.png + rc/arrow_up_focus.png + rc/arrow_up_focus@2x.png + rc/arrow_up_pressed.png + rc/arrow_up_pressed@2x.png + rc/base_icon.png + rc/base_icon@2x.png + rc/base_icon_disabled.png + rc/base_icon_disabled@2x.png + rc/base_icon_focus.png + rc/base_icon_focus@2x.png + rc/base_icon_pressed.png + rc/base_icon_pressed@2x.png + rc/branch_closed.png + rc/branch_closed@2x.png + rc/branch_closed_disabled.png + rc/branch_closed_disabled@2x.png + rc/branch_closed_focus.png + rc/branch_closed_focus@2x.png + rc/branch_closed_pressed.png + rc/branch_closed_pressed@2x.png + rc/branch_end.png + rc/branch_end@2x.png + rc/branch_end_disabled.png + rc/branch_end_disabled@2x.png + rc/branch_end_focus.png + rc/branch_end_focus@2x.png + rc/branch_end_pressed.png + rc/branch_end_pressed@2x.png + rc/branch_line.png + rc/branch_line@2x.png + rc/branch_line_disabled.png + rc/branch_line_disabled@2x.png + rc/branch_line_focus.png + rc/branch_line_focus@2x.png + rc/branch_line_pressed.png + rc/branch_line_pressed@2x.png + rc/branch_more.png + rc/branch_more@2x.png + rc/branch_more_disabled.png + rc/branch_more_disabled@2x.png + rc/branch_more_focus.png + rc/branch_more_focus@2x.png + rc/branch_more_pressed.png + rc/branch_more_pressed@2x.png + rc/branch_open.png + rc/branch_open@2x.png + rc/branch_open_disabled.png + rc/branch_open_disabled@2x.png + rc/branch_open_focus.png + rc/branch_open_focus@2x.png + rc/branch_open_pressed.png + rc/branch_open_pressed@2x.png + rc/checkbox_checked.png + rc/checkbox_checked@2x.png + rc/checkbox_checked_disabled.png + rc/checkbox_checked_disabled@2x.png + rc/checkbox_checked_focus.png + rc/checkbox_checked_focus@2x.png + rc/checkbox_checked_pressed.png + rc/checkbox_checked_pressed@2x.png + rc/checkbox_indeterminate.png + rc/checkbox_indeterminate@2x.png + rc/checkbox_indeterminate_disabled.png + rc/checkbox_indeterminate_disabled@2x.png + rc/checkbox_indeterminate_focus.png + rc/checkbox_indeterminate_focus@2x.png + rc/checkbox_indeterminate_pressed.png + rc/checkbox_indeterminate_pressed@2x.png + rc/checkbox_unchecked.png + rc/checkbox_unchecked@2x.png + rc/checkbox_unchecked_disabled.png + rc/checkbox_unchecked_disabled@2x.png + rc/checkbox_unchecked_focus.png + rc/checkbox_unchecked_focus@2x.png + rc/checkbox_unchecked_pressed.png + rc/checkbox_unchecked_pressed@2x.png + rc/line_horizontal.png + rc/line_horizontal@2x.png + rc/line_horizontal_disabled.png + rc/line_horizontal_disabled@2x.png + rc/line_horizontal_focus.png + rc/line_horizontal_focus@2x.png + rc/line_horizontal_pressed.png + rc/line_horizontal_pressed@2x.png + rc/line_vertical.png + rc/line_vertical@2x.png + rc/line_vertical_disabled.png + rc/line_vertical_disabled@2x.png + rc/line_vertical_focus.png + rc/line_vertical_focus@2x.png + rc/line_vertical_pressed.png + rc/line_vertical_pressed@2x.png + rc/radio_checked.png + rc/radio_checked@2x.png + rc/radio_checked_disabled.png + rc/radio_checked_disabled@2x.png + rc/radio_checked_focus.png + rc/radio_checked_focus@2x.png + rc/radio_checked_pressed.png + rc/radio_checked_pressed@2x.png + rc/radio_unchecked.png + rc/radio_unchecked@2x.png + rc/radio_unchecked_disabled.png + rc/radio_unchecked_disabled@2x.png + rc/radio_unchecked_focus.png + rc/radio_unchecked_focus@2x.png + rc/radio_unchecked_pressed.png + rc/radio_unchecked_pressed@2x.png + rc/toolbar_move_horizontal.png + rc/toolbar_move_horizontal@2x.png + rc/toolbar_move_horizontal_disabled.png + rc/toolbar_move_horizontal_disabled@2x.png + rc/toolbar_move_horizontal_focus.png + rc/toolbar_move_horizontal_focus@2x.png + rc/toolbar_move_horizontal_pressed.png + rc/toolbar_move_horizontal_pressed@2x.png + rc/toolbar_move_vertical.png + rc/toolbar_move_vertical@2x.png + rc/toolbar_move_vertical_disabled.png + rc/toolbar_move_vertical_disabled@2x.png + rc/toolbar_move_vertical_focus.png + rc/toolbar_move_vertical_focus@2x.png + rc/toolbar_move_vertical_pressed.png + rc/toolbar_move_vertical_pressed@2x.png + rc/toolbar_separator_horizontal.png + rc/toolbar_separator_horizontal@2x.png + rc/toolbar_separator_horizontal_disabled.png + rc/toolbar_separator_horizontal_disabled@2x.png + rc/toolbar_separator_horizontal_focus.png + rc/toolbar_separator_horizontal_focus@2x.png + rc/toolbar_separator_horizontal_pressed.png + rc/toolbar_separator_horizontal_pressed@2x.png + rc/toolbar_separator_vertical.png + rc/toolbar_separator_vertical@2x.png + rc/toolbar_separator_vertical_disabled.png + rc/toolbar_separator_vertical_disabled@2x.png + rc/toolbar_separator_vertical_focus.png + rc/toolbar_separator_vertical_focus@2x.png + rc/toolbar_separator_vertical_pressed.png + rc/toolbar_separator_vertical_pressed@2x.png + rc/transparent.png + rc/transparent@2x.png + rc/transparent_disabled.png + rc/transparent_disabled@2x.png + rc/transparent_focus.png + rc/transparent_focus@2x.png + rc/transparent_pressed.png + rc/transparent_pressed@2x.png + rc/window_close.png + rc/window_close@2x.png + rc/window_close_disabled.png + rc/window_close_disabled@2x.png + rc/window_close_focus.png + rc/window_close_focus@2x.png + rc/window_close_pressed.png + rc/window_close_pressed@2x.png + rc/window_grip.png + rc/window_grip@2x.png + rc/window_grip_disabled.png + rc/window_grip_disabled@2x.png + rc/window_grip_focus.png + rc/window_grip_focus@2x.png + rc/window_grip_pressed.png + rc/window_grip_pressed@2x.png + rc/window_minimize.png + rc/window_minimize@2x.png + rc/window_minimize_disabled.png + rc/window_minimize_disabled@2x.png + rc/window_minimize_focus.png + rc/window_minimize_focus@2x.png + rc/window_minimize_pressed.png + rc/window_minimize_pressed@2x.png + rc/window_undock.png + rc/window_undock@2x.png + rc/window_undock_disabled.png + rc/window_undock_disabled@2x.png + rc/window_undock_focus.png + rc/window_undock_focus@2x.png + rc/window_undock_pressed.png + rc/window_undock_pressed@2x.png + + + darkstyle.qss + + diff --git a/3rdParty/qdarkstyle/dark/darkstyle.qss b/3rdParty/qdarkstyle/dark/darkstyle.qss index 5fe3464fa1..1fc6099f2b 100644 --- a/3rdParty/qdarkstyle/dark/darkstyle.qss +++ b/3rdParty/qdarkstyle/dark/darkstyle.qss @@ -1,2217 +1,2217 @@ -/* --------------------------------------------------------------------------- - - WARNING! File created programmatically. All changes made in this file will be lost! - - Created by the qtsass compiler v0.3.0 - - The definitions are in the "qdarkstyle.qss._styles.scss" module - ---------------------------------------------------------------------------- */ -/* Light Style - QDarkStyleSheet ------------------------------------------ */ -/* - -See Qt documentation: - - - https://doc.qt.io/qt-5/stylesheet.html - - https://doc.qt.io/qt-5/stylesheet-reference.html - - https://doc.qt.io/qt-5/stylesheet-examples.html - ---------------------------------------------------------------------------- */ -/* Reset elements ------------------------------------------------------------ - -Resetting everything helps to unify styles across different operating systems - ---------------------------------------------------------------------------- */ -* { - padding: 0px; - margin: 0px; - border: 0px; - border-style: none; - border-image: none; - outline: 0; -} - -/* specific reset for elements inside QToolBar */ -QToolBar * { - margin: 0px; - padding: 0px; -} - -/* QWidget ---------------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QWidget { - background-color: #19232D; - border: 0px solid #455364; - padding: 0px; - color: #E0E1E3; - selection-background-color: #346792; - selection-color: #E0E1E3; -} - -QWidget:disabled { - background-color: #19232D; - color: #9DA9B5; - selection-background-color: #26486B; - selection-color: #9DA9B5; -} - -QWidget::item:selected { - background-color: #346792; -} - -QWidget::item:hover:!selected { - background-color: #1A72BB; -} - -/* QMainWindow ------------------------------------------------------------ - -This adjusts the splitter in the dock widget, not qsplitter -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qmainwindow - ---------------------------------------------------------------------------- */ -QMainWindow::separator { - background-color: #455364; - border: 0px solid #19232D; - spacing: 0px; - padding: 2px; -} - -QMainWindow::separator:hover { - background-color: #60798B; - border: 0px solid #1A72BB; -} - -QMainWindow::separator:horizontal { - width: 5px; - margin-top: 2px; - margin-bottom: 2px; - image: url(":/qss_icons/dark/rc/toolbar_separator_vertical.png"); -} - -QMainWindow::separator:vertical { - height: 5px; - margin-left: 2px; - margin-right: 2px; - image: url(":/qss_icons/dark/rc/toolbar_separator_horizontal.png"); -} - -/* QToolTip --------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtooltip - ---------------------------------------------------------------------------- */ -QToolTip { - background-color: #346792; - color: #E0E1E3; - /* If you remove the border property, background stops working on Windows */ - border: none; - /* Remove padding, for fix combo box tooltip */ - padding: 0px; - /* Remove opacity, fix #174 - may need to use RGBA */ -} - -/* QStatusBar ------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qstatusbar - ---------------------------------------------------------------------------- */ -QStatusBar { - border: 1px solid #455364; - /* Fixes Spyder #9120, #9121 */ - background: #455364; - /* Fixes #205, white vertical borders separating items */ -} - -QStatusBar::item { - border: none; -} - -QStatusBar QToolTip { - background-color: #1A72BB; - border: 1px solid #19232D; - color: #19232D; - /* Remove padding, for fix combo box tooltip */ - padding: 0px; - /* Reducing transparency to read better */ - opacity: 230; -} - -QStatusBar QLabel { - /* Fixes Spyder #9120, #9121 */ - background: transparent; -} - -/* QCheckBox -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qcheckbox - ---------------------------------------------------------------------------- */ -QCheckBox { - background-color: #19232D; - color: #E0E1E3; - spacing: 4px; - outline: none; - padding-top: 4px; - padding-bottom: 4px; -} - -QCheckBox:focus { - border: none; -} - -QCheckBox QWidget:disabled { - background-color: #19232D; - color: #9DA9B5; -} - -QCheckBox::indicator { - margin-left: 2px; - height: 14px; - width: 14px; -} - -QCheckBox::indicator:unchecked { - image: url(":/qss_icons/dark/rc/checkbox_unchecked.png"); -} - -QCheckBox::indicator:unchecked:hover, QCheckBox::indicator:unchecked:focus, QCheckBox::indicator:unchecked:pressed { - border: none; - image: url(":/qss_icons/dark/rc/checkbox_unchecked_focus.png"); -} - -QCheckBox::indicator:unchecked:disabled { - image: url(":/qss_icons/dark/rc/checkbox_unchecked_disabled.png"); -} - -QCheckBox::indicator:checked { - image: url(":/qss_icons/dark/rc/checkbox_checked.png"); -} - -QCheckBox::indicator:checked:hover, QCheckBox::indicator:checked:focus, QCheckBox::indicator:checked:pressed { - border: none; - image: url(":/qss_icons/dark/rc/checkbox_checked_focus.png"); -} - -QCheckBox::indicator:checked:disabled { - image: url(":/qss_icons/dark/rc/checkbox_checked_disabled.png"); -} - -QCheckBox::indicator:indeterminate { - image: url(":/qss_icons/dark/rc/checkbox_indeterminate.png"); -} - -QCheckBox::indicator:indeterminate:disabled { - image: url(":/qss_icons/dark/rc/checkbox_indeterminate_disabled.png"); -} - -QCheckBox::indicator:indeterminate:focus, QCheckBox::indicator:indeterminate:hover, QCheckBox::indicator:indeterminate:pressed { - image: url(":/qss_icons/dark/rc/checkbox_indeterminate_focus.png"); -} - -/* QGroupBox -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qgroupbox - ---------------------------------------------------------------------------- */ -QGroupBox { - font-weight: bold; - border: 1px solid #455364; - border-radius: 4px; - padding: 2px; - padding-top: 4px; - margin-top: 6px; - margin-bottom: 4px; -} - -QGroupBox::title { - subcontrol-origin: margin; - subcontrol-position: top left; - left: 4px; - padding-left: 2px; - padding-right: 4px; - padding-top: -4px; -} - -QGroupBox::indicator { - margin-left: 2px; - margin-top: 2px; - padding: 0; - height: 14px; - width: 14px; -} - -QGroupBox::indicator:unchecked { - border: none; - image: url(":/qss_icons/dark/rc/checkbox_unchecked.png"); -} - -QGroupBox::indicator:unchecked:hover, QGroupBox::indicator:unchecked:focus, QGroupBox::indicator:unchecked:pressed { - border: none; - image: url(":/qss_icons/dark/rc/checkbox_unchecked_focus.png"); -} - -QGroupBox::indicator:unchecked:disabled { - image: url(":/qss_icons/dark/rc/checkbox_unchecked_disabled.png"); -} - -QGroupBox::indicator:checked { - border: none; - image: url(":/qss_icons/dark/rc/checkbox_checked.png"); -} - -QGroupBox::indicator:checked:hover, QGroupBox::indicator:checked:focus, QGroupBox::indicator:checked:pressed { - border: none; - image: url(":/qss_icons/dark/rc/checkbox_checked_focus.png"); -} - -QGroupBox::indicator:checked:disabled { - image: url(":/qss_icons/dark/rc/checkbox_checked_disabled.png"); -} - -/* QRadioButton ----------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qradiobutton - ---------------------------------------------------------------------------- */ -QRadioButton { - background-color: #19232D; - color: #E0E1E3; - spacing: 4px; - padding-top: 4px; - padding-bottom: 4px; - border: none; - outline: none; -} - -QRadioButton:focus { - border: none; -} - -QRadioButton:disabled { - background-color: #19232D; - color: #9DA9B5; - border: none; - outline: none; -} - -QRadioButton QWidget { - background-color: #19232D; - color: #E0E1E3; - spacing: 0px; - padding: 0px; - outline: none; - border: none; -} - -QRadioButton::indicator { - border: none; - outline: none; - margin-left: 2px; - height: 14px; - width: 14px; -} - -QRadioButton::indicator:unchecked { - image: url(":/qss_icons/dark/rc/radio_unchecked.png"); -} - -QRadioButton::indicator:unchecked:hover, QRadioButton::indicator:unchecked:focus, QRadioButton::indicator:unchecked:pressed { - border: none; - outline: none; - image: url(":/qss_icons/dark/rc/radio_unchecked_focus.png"); -} - -QRadioButton::indicator:unchecked:disabled { - image: url(":/qss_icons/dark/rc/radio_unchecked_disabled.png"); -} - -QRadioButton::indicator:checked { - border: none; - outline: none; - image: url(":/qss_icons/dark/rc/radio_checked.png"); -} - -QRadioButton::indicator:checked:hover, QRadioButton::indicator:checked:focus, QRadioButton::indicator:checked:pressed { - border: none; - outline: none; - image: url(":/qss_icons/dark/rc/radio_checked_focus.png"); -} - -QRadioButton::indicator:checked:disabled { - outline: none; - image: url(":/qss_icons/dark/rc/radio_checked_disabled.png"); -} - -/* QMenuBar --------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qmenubar - ---------------------------------------------------------------------------- */ -QMenuBar { - background-color: #455364; - padding: 2px; - border: 1px solid #19232D; - color: #E0E1E3; - selection-background-color: #1A72BB; -} - -QMenuBar:focus { - border: 1px solid #346792; -} - -QMenuBar::item { - background: transparent; - padding: 4px; -} - -QMenuBar::item:selected { - padding: 4px; - background: transparent; - border: 0px solid #455364; - background-color: #1A72BB; -} - -QMenuBar::item:pressed { - padding: 4px; - border: 0px solid #455364; - background-color: #1A72BB; - color: #E0E1E3; - margin-bottom: 0px; - padding-bottom: 0px; -} - -/* QMenu ------------------------------------------------------------------ - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qmenu - ---------------------------------------------------------------------------- */ -QMenu { - border: 0px solid #455364; - color: #E0E1E3; - margin: 0px; - background-color: #37414F; - selection-background-color: #1A72BB; -} - -QMenu::separator { - height: 1px; - background-color: #60798B; - color: #E0E1E3; -} - -QMenu::item { - background-color: #37414F; - padding: 4px 24px 4px 28px; - /* Reserve space for selection border */ - border: 1px transparent #455364; -} - -QMenu::item:selected { - color: #E0E1E3; - background-color: #1A72BB; -} - -QMenu::item:pressed { - background-color: #1A72BB; -} - -QMenu::icon { - padding-left: 10px; - width: 14px; - height: 14px; -} - -QMenu::indicator { - padding-left: 8px; - width: 12px; - height: 12px; - /* non-exclusive indicator = check box style indicator (see QActionGroup::setExclusive) */ - /* exclusive indicator = radio button style indicator (see QActionGroup::setExclusive) */ -} - -QMenu::indicator:non-exclusive:unchecked { - image: url(":/qss_icons/dark/rc/checkbox_unchecked.png"); -} - -QMenu::indicator:non-exclusive:unchecked:hover, QMenu::indicator:non-exclusive:unchecked:focus, QMenu::indicator:non-exclusive:unchecked:pressed { - border: none; - image: url(":/qss_icons/dark/rc/checkbox_unchecked_focus.png"); -} - -QMenu::indicator:non-exclusive:unchecked:disabled { - image: url(":/qss_icons/dark/rc/checkbox_unchecked_disabled.png"); -} - -QMenu::indicator:non-exclusive:checked { - image: url(":/qss_icons/dark/rc/checkbox_checked.png"); -} - -QMenu::indicator:non-exclusive:checked:hover, QMenu::indicator:non-exclusive:checked:focus, QMenu::indicator:non-exclusive:checked:pressed { - border: none; - image: url(":/qss_icons/dark/rc/checkbox_checked_focus.png"); -} - -QMenu::indicator:non-exclusive:checked:disabled { - image: url(":/qss_icons/dark/rc/checkbox_checked_disabled.png"); -} - -QMenu::indicator:non-exclusive:indeterminate { - image: url(":/qss_icons/dark/rc/checkbox_indeterminate.png"); -} - -QMenu::indicator:non-exclusive:indeterminate:disabled { - image: url(":/qss_icons/dark/rc/checkbox_indeterminate_disabled.png"); -} - -QMenu::indicator:non-exclusive:indeterminate:focus, QMenu::indicator:non-exclusive:indeterminate:hover, QMenu::indicator:non-exclusive:indeterminate:pressed { - image: url(":/qss_icons/dark/rc/checkbox_indeterminate_focus.png"); -} - -QMenu::indicator:exclusive:unchecked { - image: url(":/qss_icons/dark/rc/radio_unchecked.png"); -} - -QMenu::indicator:exclusive:unchecked:hover, QMenu::indicator:exclusive:unchecked:focus, QMenu::indicator:exclusive:unchecked:pressed { - border: none; - outline: none; - image: url(":/qss_icons/dark/rc/radio_unchecked_focus.png"); -} - -QMenu::indicator:exclusive:unchecked:disabled { - image: url(":/qss_icons/dark/rc/radio_unchecked_disabled.png"); -} - -QMenu::indicator:exclusive:checked { - border: none; - outline: none; - image: url(":/qss_icons/dark/rc/radio_checked.png"); -} - -QMenu::indicator:exclusive:checked:hover, QMenu::indicator:exclusive:checked:focus, QMenu::indicator:exclusive:checked:pressed { - border: none; - outline: none; - image: url(":/qss_icons/dark/rc/radio_checked_focus.png"); -} - -QMenu::indicator:exclusive:checked:disabled { - outline: none; - image: url(":/qss_icons/dark/rc/radio_checked_disabled.png"); -} - -QMenu::right-arrow { - margin: 5px; - padding-left: 12px; - image: url(":/qss_icons/dark/rc/arrow_right.png"); - height: 12px; - width: 12px; -} - -/* QAbstractItemView ------------------------------------------------------ - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qcombobox - ---------------------------------------------------------------------------- */ -QAbstractItemView { - alternate-background-color: #19232D; - color: #E0E1E3; - border: 1px solid #455364; - border-radius: 4px; -} - -QAbstractItemView QLineEdit { - padding: 2px; -} - -/* QAbstractScrollArea ---------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qabstractscrollarea - ---------------------------------------------------------------------------- */ -QAbstractScrollArea { - background-color: #19232D; - border: 1px solid #455364; - border-radius: 4px; - /* fix #159 */ - padding: 2px; - /* remove min-height to fix #244 */ - color: #E0E1E3; -} - -QAbstractScrollArea:disabled { - color: #9DA9B5; -} - -/* QScrollArea ------------------------------------------------------------ - ---------------------------------------------------------------------------- */ -QScrollArea QWidget QWidget:disabled { - background-color: #19232D; -} - -/* QScrollBar ------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qscrollbar - ---------------------------------------------------------------------------- */ -QScrollBar:horizontal { - height: 16px; - margin: 2px 16px 2px 16px; - border: 1px solid #455364; - border-radius: 4px; - background-color: #19232D; -} - -QScrollBar:vertical { - background-color: #19232D; - width: 16px; - margin: 16px 2px 16px 2px; - border: 1px solid #455364; - border-radius: 4px; -} - -QScrollBar::handle:horizontal { - background-color: #60798B; - border: 1px solid #455364; - border-radius: 4px; - min-width: 8px; -} - -QScrollBar::handle:horizontal:hover { - background-color: #346792; - border: #346792; - border-radius: 4px; - min-width: 8px; -} - -QScrollBar::handle:horizontal:focus { - border: 1px solid #1A72BB; -} - -QScrollBar::handle:vertical { - background-color: #60798B; - border: 1px solid #455364; - min-height: 8px; - border-radius: 4px; -} - -QScrollBar::handle:vertical:hover { - background-color: #346792; - border: #346792; - border-radius: 4px; - min-height: 8px; -} - -QScrollBar::handle:vertical:focus { - border: 1px solid #1A72BB; -} - -QScrollBar::add-line:horizontal { - margin: 0px 0px 0px 0px; - border-image: url(":/qss_icons/dark/rc/arrow_right_disabled.png"); - height: 12px; - width: 12px; - subcontrol-position: right; - subcontrol-origin: margin; -} - -QScrollBar::add-line:horizontal:hover, QScrollBar::add-line:horizontal:on { - border-image: url(":/qss_icons/dark/rc/arrow_right.png"); - height: 12px; - width: 12px; - subcontrol-position: right; - subcontrol-origin: margin; -} - -QScrollBar::add-line:vertical { - margin: 3px 0px 3px 0px; - border-image: url(":/qss_icons/dark/rc/arrow_down_disabled.png"); - height: 12px; - width: 12px; - subcontrol-position: bottom; - subcontrol-origin: margin; -} - -QScrollBar::add-line:vertical:hover, QScrollBar::add-line:vertical:on { - border-image: url(":/qss_icons/dark/rc/arrow_down.png"); - height: 12px; - width: 12px; - subcontrol-position: bottom; - subcontrol-origin: margin; -} - -QScrollBar::sub-line:horizontal { - margin: 0px 3px 0px 3px; - border-image: url(":/qss_icons/dark/rc/arrow_left_disabled.png"); - height: 12px; - width: 12px; - subcontrol-position: left; - subcontrol-origin: margin; -} - -QScrollBar::sub-line:horizontal:hover, QScrollBar::sub-line:horizontal:on { - border-image: url(":/qss_icons/dark/rc/arrow_left.png"); - height: 12px; - width: 12px; - subcontrol-position: left; - subcontrol-origin: margin; -} - -QScrollBar::sub-line:vertical { - margin: 3px 0px 3px 0px; - border-image: url(":/qss_icons/dark/rc/arrow_up_disabled.png"); - height: 12px; - width: 12px; - subcontrol-position: top; - subcontrol-origin: margin; -} - -QScrollBar::sub-line:vertical:hover, QScrollBar::sub-line:vertical:on { - border-image: url(":/qss_icons/dark/rc/arrow_up.png"); - height: 12px; - width: 12px; - subcontrol-position: top; - subcontrol-origin: margin; -} - -QScrollBar::up-arrow:horizontal, QScrollBar::down-arrow:horizontal { - background: none; -} - -QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical { - background: none; -} - -QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal { - background: none; -} - -QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { - background: none; -} - -/* QTextEdit -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-specific-widgets - ---------------------------------------------------------------------------- */ -QTextEdit { - background-color: #19232D; - color: #E0E1E3; - border-radius: 4px; - border: 1px solid #455364; -} - -QTextEdit:focus { - border: 1px solid #1A72BB; -} - -QTextEdit:selected { - background: #346792; - color: #455364; -} - -/* QPlainTextEdit --------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QPlainTextEdit { - background-color: #19232D; - color: #E0E1E3; - border-radius: 4px; - border: 1px solid #455364; -} - -QPlainTextEdit:focus { - border: 1px solid #1A72BB; -} - -QPlainTextEdit:selected { - background: #346792; - color: #455364; -} - -/* QSizeGrip -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qsizegrip - ---------------------------------------------------------------------------- */ -QSizeGrip { - background: transparent; - width: 12px; - height: 12px; - image: url(":/qss_icons/dark/rc/window_grip.png"); -} - -/* QStackedWidget --------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QStackedWidget { - padding: 2px; - border: 1px solid #455364; - border: 1px solid #19232D; -} - -/* QToolBar --------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtoolbar - ---------------------------------------------------------------------------- */ -QToolBar { - background-color: #455364; - border-bottom: 1px solid #19232D; - padding: 1px; - font-weight: bold; - spacing: 2px; -} - -QToolBar:disabled { - /* Fixes #272 */ - background-color: #455364; -} - -QToolBar::handle:horizontal { - width: 16px; - image: url(":/qss_icons/dark/rc/toolbar_move_horizontal.png"); -} - -QToolBar::handle:vertical { - height: 16px; - image: url(":/qss_icons/dark/rc/toolbar_move_vertical.png"); -} - -QToolBar::separator:horizontal { - width: 16px; - image: url(":/qss_icons/dark/rc/toolbar_separator_horizontal.png"); -} - -QToolBar::separator:vertical { - height: 16px; - image: url(":/qss_icons/dark/rc/toolbar_separator_vertical.png"); -} - -QToolButton#qt_toolbar_ext_button { - background: #455364; - border: 0px; - color: #E0E1E3; - image: url(":/qss_icons/dark/rc/arrow_right.png"); -} - -/* QAbstractSpinBox ------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QAbstractSpinBox { - background-color: #19232D; - border: 1px solid #455364; - color: #E0E1E3; - /* This fixes 103, 111 */ - padding-top: 2px; - /* This fixes 103, 111 */ - padding-bottom: 2px; - padding-left: 4px; - padding-right: 4px; - border-radius: 4px; - /* min-width: 5px; removed to fix 109 */ -} - -QAbstractSpinBox:up-button { - background-color: transparent #19232D; - subcontrol-origin: border; - subcontrol-position: top right; - border-left: 1px solid #455364; - border-bottom: 1px solid #455364; - border-top-left-radius: 0; - border-bottom-left-radius: 0; - margin: 1px; - width: 12px; - margin-bottom: -1px; -} - -QAbstractSpinBox::up-arrow, QAbstractSpinBox::up-arrow:disabled, QAbstractSpinBox::up-arrow:off { - image: url(":/qss_icons/dark/rc/arrow_up_disabled.png"); - height: 8px; - width: 8px; -} - -QAbstractSpinBox::up-arrow:hover { - image: url(":/qss_icons/dark/rc/arrow_up.png"); -} - -QAbstractSpinBox:down-button { - background-color: transparent #19232D; - subcontrol-origin: border; - subcontrol-position: bottom right; - border-left: 1px solid #455364; - border-top: 1px solid #455364; - border-top-left-radius: 0; - border-bottom-left-radius: 0; - margin: 1px; - width: 12px; - margin-top: -1px; -} - -QAbstractSpinBox::down-arrow, QAbstractSpinBox::down-arrow:disabled, QAbstractSpinBox::down-arrow:off { - image: url(":/qss_icons/dark/rc/arrow_down_disabled.png"); - height: 8px; - width: 8px; -} - -QAbstractSpinBox::down-arrow:hover { - image: url(":/qss_icons/dark/rc/arrow_down.png"); -} - -QAbstractSpinBox:hover { - border: 1px solid #346792; - color: #E0E1E3; -} - -QAbstractSpinBox:focus { - border: 1px solid #1A72BB; -} - -QAbstractSpinBox:selected { - background: #346792; - color: #455364; -} - -/* ------------------------------------------------------------------------ */ -/* DISPLAYS --------------------------------------------------------------- */ -/* ------------------------------------------------------------------------ */ -/* QLabel ----------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qframe - ---------------------------------------------------------------------------- */ -QLabel { - background-color: #19232D; - border: 0px solid #455364; - padding: 0px; - margin: 0px; - color: #E0E1E3; -} - -QLabel:disabled { - background-color: #19232D; - border: 0px solid #455364; - color: #9DA9B5; -} - -/* QTextBrowser ----------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qabstractscrollarea - ---------------------------------------------------------------------------- */ -QTextBrowser { - background-color: #19232D; - border: 1px solid #455364; - color: #E0E1E3; - border-radius: 4px; -} - -QTextBrowser:disabled { - background-color: #19232D; - border: 1px solid #455364; - color: #9DA9B5; - border-radius: 4px; -} - -QTextBrowser:hover, QTextBrowser:!hover, QTextBrowser:selected, QTextBrowser:pressed { - border: 1px solid #455364; -} - -/* QGraphicsView ---------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QGraphicsView { - background-color: #19232D; - border: 1px solid #455364; - color: #E0E1E3; - border-radius: 4px; -} - -QGraphicsView:disabled { - background-color: #19232D; - border: 1px solid #455364; - color: #9DA9B5; - border-radius: 4px; -} - -QGraphicsView:hover, QGraphicsView:!hover, QGraphicsView:selected, QGraphicsView:pressed { - border: 1px solid #455364; -} - -/* QCalendarWidget -------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QCalendarWidget { - border: 1px solid #455364; - border-radius: 4px; -} - -QCalendarWidget:disabled { - background-color: #19232D; - color: #9DA9B5; -} - -/* QLCDNumber ------------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QLCDNumber { - background-color: #19232D; - color: #E0E1E3; -} - -QLCDNumber:disabled { - background-color: #19232D; - color: #9DA9B5; -} - -/* QProgressBar ----------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qprogressbar - ---------------------------------------------------------------------------- */ -QProgressBar { - background-color: #19232D; - border: 1px solid #455364; - color: #E0E1E3; - border-radius: 4px; - text-align: center; -} - -QProgressBar:disabled { - background-color: #19232D; - border: 1px solid #455364; - color: #9DA9B5; - border-radius: 4px; - text-align: center; -} - -QProgressBar::chunk { - background-color: #346792; - color: #19232D; - border-radius: 4px; -} - -QProgressBar::chunk:disabled { - background-color: #26486B; - color: #9DA9B5; - border-radius: 4px; -} - -/* ------------------------------------------------------------------------ */ -/* BUTTONS ---------------------------------------------------------------- */ -/* ------------------------------------------------------------------------ */ -/* QPushButton ------------------------------------------------------------ - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qpushbutton - ---------------------------------------------------------------------------- */ -QPushButton { - background-color: #455364; - color: #E0E1E3; - border-radius: 4px; - padding: 2px; - outline: none; - border: none; -} - -QPushButton:disabled { - background-color: #455364; - color: #9DA9B5; - border-radius: 4px; - padding: 2px; -} - -QPushButton:checked { - background-color: #60798B; - border-radius: 4px; - padding: 2px; - outline: none; -} - -QPushButton:checked:disabled { - background-color: #60798B; - color: #9DA9B5; - border-radius: 4px; - padding: 2px; - outline: none; -} - -QPushButton:checked:selected { - background: #60798B; -} - -QPushButton:hover { - background-color: #54687A; - color: #E0E1E3; -} - -QPushButton:pressed { - background-color: #60798B; -} - -QPushButton:selected { - background: #60798B; - color: #E0E1E3; -} - -QPushButton::menu-indicator { - subcontrol-origin: padding; - subcontrol-position: bottom right; - bottom: 4px; -} - -QDialogButtonBox QPushButton { - /* Issue #194 #248 - Special case of QPushButton inside dialogs, for better UI */ - min-width: 80px; -} - -/* QToolButton ------------------------------------------------------------ - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtoolbutton - ---------------------------------------------------------------------------- */ -QToolButton { - background-color: #455364; - color: #E0E1E3; - border-radius: 4px; - padding: 2px; - outline: none; - border: none; - /* The subcontrols below are used only in the DelayedPopup mode */ - /* The subcontrols below are used only in the MenuButtonPopup mode */ - /* The subcontrol below is used only in the InstantPopup or DelayedPopup mode */ -} - -QToolButton:disabled { - background-color: #455364; - color: #9DA9B5; - border-radius: 4px; - padding: 2px; -} - -QToolButton:checked { - background-color: #60798B; - border-radius: 4px; - padding: 2px; - outline: none; -} - -QToolButton:checked:disabled { - background-color: #60798B; - color: #9DA9B5; - border-radius: 4px; - padding: 2px; - outline: none; -} - -QToolButton:checked:hover { - background-color: #54687A; - color: #E0E1E3; -} - -QToolButton:checked:pressed { - background-color: #60798B; -} - -QToolButton:checked:selected { - background: #60798B; - color: #E0E1E3; -} - -QToolButton:hover { - background-color: #54687A; - color: #E0E1E3; -} - -QToolButton:pressed { - background-color: #60798B; -} - -QToolButton:selected { - background: #60798B; - color: #E0E1E3; -} - -QToolButton[popupMode="0"] { - /* Only for DelayedPopup */ - padding-right: 2px; -} - -QToolButton[popupMode="1"] { - /* Only for MenuButtonPopup */ - padding-right: 20px; -} - -QToolButton[popupMode="1"]::menu-button { - border: none; -} - -QToolButton[popupMode="1"]::menu-button:hover { - border: none; - border-left: 1px solid #455364; - border-radius: 0; -} - -QToolButton[popupMode="2"] { - /* Only for InstantPopup */ - padding-right: 2px; -} - -QToolButton::menu-button { - padding: 2px; - border-radius: 4px; - width: 12px; - border: none; - outline: none; -} - -QToolButton::menu-button:hover { - border: 1px solid #346792; -} - -QToolButton::menu-button:checked:hover { - border: 1px solid #346792; -} - -QToolButton::menu-indicator { - image: url(":/qss_icons/dark/rc/arrow_down.png"); - height: 8px; - width: 8px; - top: 0; - /* Exclude a shift for better image */ - left: -2px; - /* Shift it a bit */ -} - -QToolButton::menu-arrow { - image: url(":/qss_icons/dark/rc/arrow_down.png"); - height: 8px; - width: 8px; -} - -QToolButton::menu-arrow:hover { - image: url(":/qss_icons/dark/rc/arrow_down_focus.png"); -} - -/* QCommandLinkButton ----------------------------------------------------- - ---------------------------------------------------------------------------- */ -QCommandLinkButton { - background-color: transparent; - border: 1px solid #455364; - color: #E0E1E3; - border-radius: 4px; - padding: 0px; - margin: 0px; -} - -QCommandLinkButton:disabled { - background-color: transparent; - color: #9DA9B5; -} - -/* ------------------------------------------------------------------------ */ -/* INPUTS - NO FIELDS ----------------------------------------------------- */ -/* ------------------------------------------------------------------------ */ -/* QComboBox -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qcombobox - ---------------------------------------------------------------------------- */ -QComboBox { - border: 1px solid #455364; - border-radius: 4px; - selection-background-color: #346792; - padding-left: 4px; - padding-right: 4px; - /* padding-right = 36; 4 + 16*2 See scrollbar size */ - /* changed to 4px to fix #239 */ - /* Fixes #103, #111 */ - min-height: 1.5em; - /* padding-top: 2px; removed to fix #132 */ - /* padding-bottom: 2px; removed to fix #132 */ - /* min-width: 75px; removed to fix #109 */ - /* Needed to remove indicator - fix #132 */ -} - -QComboBox QAbstractItemView { - border: 1px solid #455364; - border-radius: 0; - background-color: #19232D; - selection-background-color: #346792; -} - -QComboBox QAbstractItemView:hover { - background-color: #19232D; - color: #E0E1E3; -} - -QComboBox QAbstractItemView:selected { - background: #346792; - color: #455364; -} - -QComboBox QAbstractItemView:alternate { - background: #19232D; -} - -QComboBox:disabled { - background-color: #19232D; - color: #9DA9B5; -} - -QComboBox:hover { - border: 1px solid #346792; -} - -QComboBox:focus { - border: 1px solid #1A72BB; -} - -QComboBox:on { - selection-background-color: #346792; -} - -QComboBox::indicator { - border: none; - border-radius: 0; - background-color: transparent; - selection-background-color: transparent; - color: transparent; - selection-color: transparent; - /* Needed to remove indicator - fix #132 */ -} - -QComboBox::indicator:alternate { - background: #19232D; -} - -QComboBox::item { - /* Remove to fix #282, #285 and MR #288*/ - /*&:checked { - font-weight: bold; - } - - &:selected { - border: 0px solid transparent; - } - */ -} - -QComboBox::item:alternate { - background: #19232D; -} - -QComboBox::drop-down { - subcontrol-origin: padding; - subcontrol-position: top right; - width: 12px; - border-left: 1px solid #455364; -} - -QComboBox::down-arrow { - image: url(":/qss_icons/dark/rc/arrow_down_disabled.png"); - height: 8px; - width: 8px; -} - -QComboBox::down-arrow:on, QComboBox::down-arrow:hover, QComboBox::down-arrow:focus { - image: url(":/qss_icons/dark/rc/arrow_down.png"); -} - -/* QSlider ---------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qslider - ---------------------------------------------------------------------------- */ -QSlider:disabled { - background: #19232D; -} - -QSlider:focus { - border: none; -} - -QSlider::groove:horizontal { - background: #455364; - border: 1px solid #455364; - height: 4px; - margin: 0px; - border-radius: 4px; -} - -QSlider::groove:vertical { - background: #455364; - border: 1px solid #455364; - width: 4px; - margin: 0px; - border-radius: 4px; -} - -QSlider::add-page:vertical { - background: #346792; - border: 1px solid #455364; - width: 4px; - margin: 0px; - border-radius: 4px; -} - -QSlider::add-page:vertical :disabled { - background: #26486B; -} - -QSlider::sub-page:horizontal { - background: #346792; - border: 1px solid #455364; - height: 4px; - margin: 0px; - border-radius: 4px; -} - -QSlider::sub-page:horizontal:disabled { - background: #26486B; -} - -QSlider::handle:horizontal { - background: #9DA9B5; - border: 1px solid #455364; - width: 8px; - height: 8px; - margin: -8px 0px; - border-radius: 4px; -} - -QSlider::handle:horizontal:hover { - background: #346792; - border: 1px solid #346792; -} - -QSlider::handle:horizontal:focus { - border: 1px solid #1A72BB; -} - -QSlider::handle:vertical { - background: #9DA9B5; - border: 1px solid #455364; - width: 8px; - height: 8px; - margin: 0 -8px; - border-radius: 4px; -} - -QSlider::handle:vertical:hover { - background: #346792; - border: 1px solid #346792; -} - -QSlider::handle:vertical:focus { - border: 1px solid #1A72BB; -} - -/* QLineEdit -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qlineedit - ---------------------------------------------------------------------------- */ -QLineEdit { - background-color: #19232D; - padding-top: 2px; - /* This QLineEdit fix 103, 111 */ - padding-bottom: 2px; - /* This QLineEdit fix 103, 111 */ - padding-left: 4px; - padding-right: 4px; - border-style: solid; - border: 1px solid #455364; - border-radius: 4px; - color: #E0E1E3; -} - -QLineEdit:disabled { - background-color: #19232D; - color: #9DA9B5; -} - -QLineEdit:hover { - border: 1px solid #346792; - color: #E0E1E3; -} - -QLineEdit:focus { - border: 1px solid #1A72BB; -} - -QLineEdit:selected { - background-color: #346792; - color: #455364; -} - -/* QTabWiget -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtabwidget-and-qtabbar - ---------------------------------------------------------------------------- */ -QTabWidget { - padding: 2px; - selection-background-color: #455364; -} - -QTabWidget QWidget { - /* Fixes #189 */ - border-radius: 4px; -} - -QTabWidget::pane { - border: 1px solid #455364; - border-radius: 4px; - margin: 0px; - /* Fixes double border inside pane with pyqt5 */ - padding: 0px; -} - -QTabWidget::pane:selected { - background-color: #455364; - border: 1px solid #346792; -} - -/* QTabBar ---------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtabwidget-and-qtabbar - ---------------------------------------------------------------------------- */ -QTabBar, QDockWidget QTabBar { - qproperty-drawBase: 0; - border-radius: 4px; - margin: 0px; - padding: 2px; - border: 0; - /* left: 5px; move to the right by 5px - removed for fix */ -} - -QTabBar::close-button, QDockWidget QTabBar::close-button { - border: 0; - margin: 0; - padding: 4px; - image: url(":/qss_icons/dark/rc/window_close.png"); -} - -QTabBar::close-button:hover, QDockWidget QTabBar::close-button:hover { - image: url(":/qss_icons/dark/rc/window_close_focus.png"); -} - -QTabBar::close-button:pressed, QDockWidget QTabBar::close-button:pressed { - image: url(":/qss_icons/dark/rc/window_close_pressed.png"); -} - -QTabBar::tab, QDockWidget QTabBar::tab { - /* !selected and disabled ----------------------------------------- */ - /* selected ------------------------------------------------------- */ -} - -QTabBar::tab:top:selected:disabled, QDockWidget QTabBar::tab:top:selected:disabled { - border-bottom: 3px solid #26486B; - color: #9DA9B5; - background-color: #455364; -} - -QTabBar::tab:bottom:selected:disabled, QDockWidget QTabBar::tab:bottom:selected:disabled { - border-top: 3px solid #26486B; - color: #9DA9B5; - background-color: #455364; -} - -QTabBar::tab:left:selected:disabled, QDockWidget QTabBar::tab:left:selected:disabled { - border-right: 3px solid #26486B; - color: #9DA9B5; - background-color: #455364; -} - -QTabBar::tab:right:selected:disabled, QDockWidget QTabBar::tab:right:selected:disabled { - border-left: 3px solid #26486B; - color: #9DA9B5; - background-color: #455364; -} - -QTabBar::tab:top:!selected:disabled, QDockWidget QTabBar::tab:top:!selected:disabled { - border-bottom: 3px solid #19232D; - color: #9DA9B5; - background-color: #19232D; -} - -QTabBar::tab:bottom:!selected:disabled, QDockWidget QTabBar::tab:bottom:!selected:disabled { - border-top: 3px solid #19232D; - color: #9DA9B5; - background-color: #19232D; -} - -QTabBar::tab:left:!selected:disabled, QDockWidget QTabBar::tab:left:!selected:disabled { - border-right: 3px solid #19232D; - color: #9DA9B5; - background-color: #19232D; -} - -QTabBar::tab:right:!selected:disabled, QDockWidget QTabBar::tab:right:!selected:disabled { - border-left: 3px solid #19232D; - color: #9DA9B5; - background-color: #19232D; -} - -QTabBar::tab:top:!selected, QDockWidget QTabBar::tab:top:!selected { - border-bottom: 2px solid #19232D; - margin-top: 2px; -} - -QTabBar::tab:bottom:!selected, QDockWidget QTabBar::tab:bottom:!selected { - border-top: 2px solid #19232D; - margin-bottom: 2px; -} - -QTabBar::tab:left:!selected, QDockWidget QTabBar::tab:left:!selected { - border-left: 2px solid #19232D; - margin-right: 2px; -} - -QTabBar::tab:right:!selected, QDockWidget QTabBar::tab:right:!selected { - border-right: 2px solid #19232D; - margin-left: 2px; -} - -QTabBar::tab:top, QDockWidget QTabBar::tab:top { - background-color: #455364; - margin-left: 2px; - padding-left: 4px; - padding-right: 4px; - padding-top: 2px; - padding-bottom: 2px; - min-width: 5px; - border-bottom: 3px solid #455364; - border-top-left-radius: 4px; - border-top-right-radius: 4px; -} - -QTabBar::tab:top:selected, QDockWidget QTabBar::tab:top:selected { - background-color: #54687A; - border-bottom: 3px solid #259AE9; - border-top-left-radius: 4px; - border-top-right-radius: 4px; -} - -QTabBar::tab:top:!selected:hover, QDockWidget QTabBar::tab:top:!selected:hover { - border: 1px solid #1A72BB; - border-bottom: 3px solid #1A72BB; - /* Fixes spyder-ide/spyder#9766 and #243 */ - padding-left: 3px; - padding-right: 3px; -} - -QTabBar::tab:bottom, QDockWidget QTabBar::tab:bottom { - border-top: 3px solid #455364; - background-color: #455364; - margin-left: 2px; - padding-left: 4px; - padding-right: 4px; - padding-top: 2px; - padding-bottom: 2px; - border-bottom-left-radius: 4px; - border-bottom-right-radius: 4px; - min-width: 5px; -} - -QTabBar::tab:bottom:selected, QDockWidget QTabBar::tab:bottom:selected { - background-color: #54687A; - border-top: 3px solid #259AE9; - border-bottom-left-radius: 4px; - border-bottom-right-radius: 4px; -} - -QTabBar::tab:bottom:!selected:hover, QDockWidget QTabBar::tab:bottom:!selected:hover { - border: 1px solid #1A72BB; - border-top: 3px solid #1A72BB; - /* Fixes spyder-ide/spyder#9766 and #243 */ - padding-left: 3px; - padding-right: 3px; -} - -QTabBar::tab:left, QDockWidget QTabBar::tab:left { - background-color: #455364; - margin-top: 2px; - padding-left: 2px; - padding-right: 2px; - padding-top: 4px; - padding-bottom: 4px; - border-top-left-radius: 4px; - border-bottom-left-radius: 4px; - min-height: 5px; -} - -QTabBar::tab:left:selected, QDockWidget QTabBar::tab:left:selected { - background-color: #54687A; - border-right: 3px solid #259AE9; -} - -QTabBar::tab:left:!selected:hover, QDockWidget QTabBar::tab:left:!selected:hover { - border: 1px solid #1A72BB; - border-right: 3px solid #1A72BB; - /* Fixes different behavior #271 */ - margin-right: 0px; - padding-right: -1px; -} - -QTabBar::tab:right, QDockWidget QTabBar::tab:right { - background-color: #455364; - margin-top: 2px; - padding-left: 2px; - padding-right: 2px; - padding-top: 4px; - padding-bottom: 4px; - border-top-right-radius: 4px; - border-bottom-right-radius: 4px; - min-height: 5px; -} - -QTabBar::tab:right:selected, QDockWidget QTabBar::tab:right:selected { - background-color: #54687A; - border-left: 3px solid #259AE9; -} - -QTabBar::tab:right:!selected:hover, QDockWidget QTabBar::tab:right:!selected:hover { - border: 1px solid #1A72BB; - border-left: 3px solid #1A72BB; - /* Fixes different behavior #271 */ - margin-left: 0px; - padding-left: 0px; -} - -QTabBar QToolButton, QDockWidget QTabBar QToolButton { - /* Fixes #136 */ - background-color: #455364; - height: 12px; - width: 12px; -} - -QTabBar QToolButton:pressed, QDockWidget QTabBar QToolButton:pressed { - background-color: #455364; -} - -QTabBar QToolButton:pressed:hover, QDockWidget QTabBar QToolButton:pressed:hover { - border: 1px solid #346792; -} - -QTabBar QToolButton::left-arrow:enabled, QDockWidget QTabBar QToolButton::left-arrow:enabled { - image: url(":/qss_icons/dark/rc/arrow_left.png"); -} - -QTabBar QToolButton::left-arrow:disabled, QDockWidget QTabBar QToolButton::left-arrow:disabled { - image: url(":/qss_icons/dark/rc/arrow_left_disabled.png"); -} - -QTabBar QToolButton::right-arrow:enabled, QDockWidget QTabBar QToolButton::right-arrow:enabled { - image: url(":/qss_icons/dark/rc/arrow_right.png"); -} - -QTabBar QToolButton::right-arrow:disabled, QDockWidget QTabBar QToolButton::right-arrow:disabled { - image: url(":/qss_icons/dark/rc/arrow_right_disabled.png"); -} - -/* QDockWiget ------------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QDockWidget { - outline: 1px solid #455364; - background-color: #19232D; - border: 1px solid #455364; - border-radius: 4px; - titlebar-close-icon: url(":/qss_icons/dark/rc/transparent.png"); - titlebar-normal-icon: url(":/qss_icons/dark/rc/transparent.png"); -} - -QDockWidget::title { - /* Better size for title bar */ - padding: 3px; - spacing: 4px; - border: none; - background-color: #455364; -} - -QDockWidget::close-button { - icon-size: 12px; - border: none; - background: transparent; - background-image: transparent; - border: 0; - margin: 0; - padding: 0; - image: url(":/qss_icons/dark/rc/window_close.png"); -} - -QDockWidget::close-button:hover { - image: url(":/qss_icons/dark/rc/window_close_focus.png"); -} - -QDockWidget::close-button:pressed { - image: url(":/qss_icons/dark/rc/window_close_pressed.png"); -} - -QDockWidget::float-button { - icon-size: 12px; - border: none; - background: transparent; - background-image: transparent; - border: 0; - margin: 0; - padding: 0; - image: url(":/qss_icons/dark/rc/window_undock.png"); -} - -QDockWidget::float-button:hover { - image: url(":/qss_icons/dark/rc/window_undock_focus.png"); -} - -QDockWidget::float-button:pressed { - image: url(":/qss_icons/dark/rc/window_undock_pressed.png"); -} - -/* QTreeView QListView QTableView ----------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtreeview -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qlistview -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtableview - ---------------------------------------------------------------------------- */ -QTreeView:branch:selected, QTreeView:branch:hover { - background: url(":/qss_icons/dark/rc/transparent.png"); -} - -QTreeView:branch:has-siblings:!adjoins-item { - border-image: url(":/qss_icons/dark/rc/branch_line.png") 0; -} - -QTreeView:branch:has-siblings:adjoins-item { - border-image: url(":/qss_icons/dark/rc/branch_more.png") 0; -} - -QTreeView:branch:!has-children:!has-siblings:adjoins-item { - border-image: url(":/qss_icons/dark/rc/branch_end.png") 0; -} - -QTreeView:branch:has-children:!has-siblings:closed, QTreeView:branch:closed:has-children:has-siblings { - border-image: none; - image: url(":/qss_icons/dark/rc/branch_closed.png"); -} - -QTreeView:branch:open:has-children:!has-siblings, QTreeView:branch:open:has-children:has-siblings { - border-image: none; - image: url(":/qss_icons/dark/rc/branch_open.png"); -} - -QTreeView:branch:has-children:!has-siblings:closed:hover, QTreeView:branch:closed:has-children:has-siblings:hover { - image: url(":/qss_icons/dark/rc/branch_closed_focus.png"); -} - -QTreeView:branch:open:has-children:!has-siblings:hover, QTreeView:branch:open:has-children:has-siblings:hover { - image: url(":/qss_icons/dark/rc/branch_open_focus.png"); -} - -QTreeView::indicator:checked, -QListView::indicator:checked, -QTableView::indicator:checked, -QColumnView::indicator:checked { - image: url(":/qss_icons/dark/rc/checkbox_checked.png"); -} - -QTreeView::indicator:checked:hover, QTreeView::indicator:checked:focus, QTreeView::indicator:checked:pressed, -QListView::indicator:checked:hover, -QListView::indicator:checked:focus, -QListView::indicator:checked:pressed, -QTableView::indicator:checked:hover, -QTableView::indicator:checked:focus, -QTableView::indicator:checked:pressed, -QColumnView::indicator:checked:hover, -QColumnView::indicator:checked:focus, -QColumnView::indicator:checked:pressed { - image: url(":/qss_icons/dark/rc/checkbox_checked_focus.png"); -} - -QTreeView::indicator:unchecked, -QListView::indicator:unchecked, -QTableView::indicator:unchecked, -QColumnView::indicator:unchecked { - image: url(":/qss_icons/dark/rc/checkbox_unchecked.png"); -} - -QTreeView::indicator:unchecked:hover, QTreeView::indicator:unchecked:focus, QTreeView::indicator:unchecked:pressed, -QListView::indicator:unchecked:hover, -QListView::indicator:unchecked:focus, -QListView::indicator:unchecked:pressed, -QTableView::indicator:unchecked:hover, -QTableView::indicator:unchecked:focus, -QTableView::indicator:unchecked:pressed, -QColumnView::indicator:unchecked:hover, -QColumnView::indicator:unchecked:focus, -QColumnView::indicator:unchecked:pressed { - image: url(":/qss_icons/dark/rc/checkbox_unchecked_focus.png"); -} - -QTreeView::indicator:indeterminate, -QListView::indicator:indeterminate, -QTableView::indicator:indeterminate, -QColumnView::indicator:indeterminate { - image: url(":/qss_icons/dark/rc/checkbox_indeterminate.png"); -} - -QTreeView::indicator:indeterminate:hover, QTreeView::indicator:indeterminate:focus, QTreeView::indicator:indeterminate:pressed, -QListView::indicator:indeterminate:hover, -QListView::indicator:indeterminate:focus, -QListView::indicator:indeterminate:pressed, -QTableView::indicator:indeterminate:hover, -QTableView::indicator:indeterminate:focus, -QTableView::indicator:indeterminate:pressed, -QColumnView::indicator:indeterminate:hover, -QColumnView::indicator:indeterminate:focus, -QColumnView::indicator:indeterminate:pressed { - image: url(":/qss_icons/dark/rc/checkbox_indeterminate_focus.png"); -} - -QTreeView, -QListView, -QTableView, -QColumnView { - background-color: #19232D; - border: 1px solid #455364; - color: #E0E1E3; - gridline-color: #455364; - border-radius: 4px; -} - -QTreeView:disabled, -QListView:disabled, -QTableView:disabled, -QColumnView:disabled { - background-color: #19232D; - color: #9DA9B5; -} - -QTreeView:selected, -QListView:selected, -QTableView:selected, -QColumnView:selected { - background-color: #346792; - color: #455364; -} - -QTreeView:focus, -QListView:focus, -QTableView:focus, -QColumnView:focus { - border: 1px solid #1A72BB; -} - -QTreeView::item:pressed, -QListView::item:pressed, -QTableView::item:pressed, -QColumnView::item:pressed { - background-color: #346792; -} - -QTreeView::item:selected:active, -QListView::item:selected:active, -QTableView::item:selected:active, -QColumnView::item:selected:active { - background-color: #346792; -} - -QTreeView::item:selected:!active, -QListView::item:selected:!active, -QTableView::item:selected:!active, -QColumnView::item:selected:!active { - color: #E0E1E3; - background-color: #37414F; -} - -QTreeView::item:!selected:hover, -QListView::item:!selected:hover, -QTableView::item:!selected:hover, -QColumnView::item:!selected:hover { - outline: 0; - color: #E0E1E3; - background-color: #37414F; -} - -QTableCornerButton::section { - background-color: #19232D; - border: 1px transparent #455364; - border-radius: 0px; -} - -/* QHeaderView ------------------------------------------------------------ - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qheaderview - ---------------------------------------------------------------------------- */ -QHeaderView { - background-color: #455364; - border: 0px transparent #455364; - padding: 0; - margin: 0; - border-radius: 0; -} - -QHeaderView:disabled { - background-color: #455364; - border: 1px transparent #455364; -} - -QHeaderView::section { - background-color: #455364; - color: #E0E1E3; - border-radius: 0; - text-align: left; - font-size: 13px; -} - -QHeaderView::section::horizontal { - padding-top: 0; - padding-bottom: 0; - padding-left: 4px; - padding-right: 4px; - border-left: 1px solid #19232D; -} - -QHeaderView::section::horizontal::first, QHeaderView::section::horizontal::only-one { - border-left: 1px solid #455364; -} - -QHeaderView::section::horizontal:disabled { - color: #9DA9B5; -} - -QHeaderView::section::vertical { - padding-top: 0; - padding-bottom: 0; - padding-left: 4px; - padding-right: 4px; - border-top: 1px solid #19232D; -} - -QHeaderView::section::vertical::first, QHeaderView::section::vertical::only-one { - border-top: 1px solid #455364; -} - -QHeaderView::section::vertical:disabled { - color: #9DA9B5; -} - -QHeaderView::down-arrow { - /* Those settings (border/width/height/background-color) solve bug */ - /* transparent arrow background and size */ - background-color: #455364; - border: none; - height: 12px; - width: 12px; - padding-left: 2px; - padding-right: 2px; - image: url(":/qss_icons/dark/rc/arrow_down.png"); -} - -QHeaderView::up-arrow { - background-color: #455364; - border: none; - height: 12px; - width: 12px; - padding-left: 2px; - padding-right: 2px; - image: url(":/qss_icons/dark/rc/arrow_up.png"); -} - -/* QToolBox -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtoolbox - ---------------------------------------------------------------------------- */ -QToolBox { - padding: 0px; - border: 0px; - border: 1px solid #455364; -} - -QToolBox:selected { - padding: 0px; - border: 2px solid #346792; -} - -QToolBox::tab { - background-color: #19232D; - border: 1px solid #455364; - color: #E0E1E3; - border-top-left-radius: 4px; - border-top-right-radius: 4px; -} - -QToolBox::tab:disabled { - color: #9DA9B5; -} - -QToolBox::tab:selected { - background-color: #60798B; - border-bottom: 2px solid #346792; -} - -QToolBox::tab:selected:disabled { - background-color: #455364; - border-bottom: 2px solid #26486B; -} - -QToolBox::tab:!selected { - background-color: #455364; - border-bottom: 2px solid #455364; -} - -QToolBox::tab:!selected:disabled { - background-color: #19232D; -} - -QToolBox::tab:hover { - border-color: #1A72BB; - border-bottom: 2px solid #1A72BB; -} - -QToolBox QScrollArea QWidget QWidget { - padding: 0px; - border: 0px; - background-color: #19232D; -} - -/* QFrame ----------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qframe -https://doc.qt.io/qt-5/qframe.html#-prop -https://doc.qt.io/qt-5/qframe.html#details -https://stackoverflow.com/questions/14581498/qt-stylesheet-for-hline-vline-color - ---------------------------------------------------------------------------- */ -/* (dot) .QFrame fix #141, #126, #123 */ -.QFrame { - border-radius: 4px; - border: 1px solid #455364; - /* No frame */ - /* HLine */ - /* HLine */ -} - -.QFrame[frameShape="0"] { - border-radius: 4px; - border: 1px transparent #455364; -} - -.QFrame[frameShape="4"] { - max-height: 2px; - border: none; - background-color: #455364; -} - -.QFrame[frameShape="5"] { - max-width: 2px; - border: none; - background-color: #455364; -} - -/* QSplitter -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qsplitter - ---------------------------------------------------------------------------- */ -QSplitter { - background-color: #455364; - spacing: 0px; - padding: 0px; - margin: 0px; -} - -QSplitter::handle { - background-color: #455364; - border: 0px solid #19232D; - spacing: 0px; - padding: 1px; - margin: 0px; -} - -QSplitter::handle:hover { - background-color: #9DA9B5; -} - -QSplitter::handle:horizontal { - width: 5px; - image: url(":/qss_icons/dark/rc/line_vertical.png"); -} - -QSplitter::handle:vertical { - height: 5px; - image: url(":/qss_icons/dark/rc/line_horizontal.png"); -} - -/* QDateEdit, QDateTimeEdit ----------------------------------------------- - ---------------------------------------------------------------------------- */ -QDateEdit, QDateTimeEdit { - selection-background-color: #346792; - border-style: solid; - border: 1px solid #455364; - border-radius: 4px; - /* This fixes 103, 111 */ - padding-top: 2px; - /* This fixes 103, 111 */ - padding-bottom: 2px; - padding-left: 4px; - padding-right: 4px; - min-width: 10px; -} - -QDateEdit:on, QDateTimeEdit:on { - selection-background-color: #346792; -} - -QDateEdit::drop-down, QDateTimeEdit::drop-down { - subcontrol-origin: padding; - subcontrol-position: top right; - width: 12px; - border-left: 1px solid #455364; -} - -QDateEdit::down-arrow, QDateTimeEdit::down-arrow { - image: url(":/qss_icons/dark/rc/arrow_down_disabled.png"); - height: 8px; - width: 8px; -} - -QDateEdit::down-arrow:on, QDateEdit::down-arrow:hover, QDateEdit::down-arrow:focus, QDateTimeEdit::down-arrow:on, QDateTimeEdit::down-arrow:hover, QDateTimeEdit::down-arrow:focus { - image: url(":/qss_icons/dark/rc/arrow_down.png"); -} - -QDateEdit QAbstractItemView, QDateTimeEdit QAbstractItemView { - background-color: #19232D; - border-radius: 4px; - border: 1px solid #455364; - selection-background-color: #346792; -} - -/* QAbstractView ---------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QAbstractView:hover { - border: 1px solid #346792; - color: #E0E1E3; -} - -QAbstractView:selected { - background: #346792; - color: #455364; -} - -/* PlotWidget ------------------------------------------------------------- - ---------------------------------------------------------------------------- */ -PlotWidget { - /* Fix cut labels in plots #134 */ - padding: 0px; -} +/* --------------------------------------------------------------------------- + + WARNING! File created programmatically. All changes made in this file will be lost! + + Created by the qtsass compiler v0.3.0 + + The definitions are in the "qdarkstyle.qss._styles.scss" module + +--------------------------------------------------------------------------- */ +/* Light Style - QDarkStyleSheet ------------------------------------------ */ +/* + +See Qt documentation: + + - https://doc.qt.io/qt-5/stylesheet.html + - https://doc.qt.io/qt-5/stylesheet-reference.html + - https://doc.qt.io/qt-5/stylesheet-examples.html + +--------------------------------------------------------------------------- */ +/* Reset elements ------------------------------------------------------------ + +Resetting everything helps to unify styles across different operating systems + +--------------------------------------------------------------------------- */ +* { + padding: 0px; + margin: 0px; + border: 0px; + border-style: none; + border-image: none; + outline: 0; +} + +/* specific reset for elements inside QToolBar */ +QToolBar * { + margin: 0px; + padding: 0px; +} + +/* QWidget ---------------------------------------------------------------- + +--------------------------------------------------------------------------- */ +QWidget { + background-color: #19232D; + border: 0px solid #455364; + padding: 0px; + color: #E0E1E3; + selection-background-color: #346792; + selection-color: #E0E1E3; +} + +QWidget:disabled { + background-color: #19232D; + color: #9DA9B5; + selection-background-color: #26486B; + selection-color: #9DA9B5; +} + +QWidget::item:selected { + background-color: #346792; +} + +QWidget::item:hover:!selected { + background-color: #1A72BB; +} + +/* QMainWindow ------------------------------------------------------------ + +This adjusts the splitter in the dock widget, not qsplitter +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qmainwindow + +--------------------------------------------------------------------------- */ +QMainWindow::separator { + background-color: #455364; + border: 0px solid #19232D; + spacing: 0px; + padding: 2px; +} + +QMainWindow::separator:hover { + background-color: #60798B; + border: 0px solid #1A72BB; +} + +QMainWindow::separator:horizontal { + width: 5px; + margin-top: 2px; + margin-bottom: 2px; + image: url(":/qss_icons/dark/rc/toolbar_separator_vertical.png"); +} + +QMainWindow::separator:vertical { + height: 5px; + margin-left: 2px; + margin-right: 2px; + image: url(":/qss_icons/dark/rc/toolbar_separator_horizontal.png"); +} + +/* QToolTip --------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtooltip + +--------------------------------------------------------------------------- */ +QToolTip { + background-color: #346792; + color: #E0E1E3; + /* If you remove the border property, background stops working on Windows */ + border: none; + /* Remove padding, for fix combo box tooltip */ + padding: 0px; + /* Remove opacity, fix #174 - may need to use RGBA */ +} + +/* QStatusBar ------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qstatusbar + +--------------------------------------------------------------------------- */ +QStatusBar { + border: 1px solid #455364; + /* Fixes Spyder #9120, #9121 */ + background: #455364; + /* Fixes #205, white vertical borders separating items */ +} + +QStatusBar::item { + border: none; +} + +QStatusBar QToolTip { + background-color: #1A72BB; + border: 1px solid #19232D; + color: #19232D; + /* Remove padding, for fix combo box tooltip */ + padding: 0px; + /* Reducing transparency to read better */ + opacity: 230; +} + +QStatusBar QLabel { + /* Fixes Spyder #9120, #9121 */ + background: transparent; +} + +/* QCheckBox -------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qcheckbox + +--------------------------------------------------------------------------- */ +QCheckBox { + background-color: #19232D; + color: #E0E1E3; + spacing: 4px; + outline: none; + padding-top: 4px; + padding-bottom: 4px; +} + +QCheckBox:focus { + border: none; +} + +QCheckBox QWidget:disabled { + background-color: #19232D; + color: #9DA9B5; +} + +QCheckBox::indicator { + margin-left: 2px; + height: 14px; + width: 14px; +} + +QCheckBox::indicator:unchecked { + image: url(":/qss_icons/dark/rc/checkbox_unchecked.png"); +} + +QCheckBox::indicator:unchecked:hover, QCheckBox::indicator:unchecked:focus, QCheckBox::indicator:unchecked:pressed { + border: none; + image: url(":/qss_icons/dark/rc/checkbox_unchecked_focus.png"); +} + +QCheckBox::indicator:unchecked:disabled { + image: url(":/qss_icons/dark/rc/checkbox_unchecked_disabled.png"); +} + +QCheckBox::indicator:checked { + image: url(":/qss_icons/dark/rc/checkbox_checked.png"); +} + +QCheckBox::indicator:checked:hover, QCheckBox::indicator:checked:focus, QCheckBox::indicator:checked:pressed { + border: none; + image: url(":/qss_icons/dark/rc/checkbox_checked_focus.png"); +} + +QCheckBox::indicator:checked:disabled { + image: url(":/qss_icons/dark/rc/checkbox_checked_disabled.png"); +} + +QCheckBox::indicator:indeterminate { + image: url(":/qss_icons/dark/rc/checkbox_indeterminate.png"); +} + +QCheckBox::indicator:indeterminate:disabled { + image: url(":/qss_icons/dark/rc/checkbox_indeterminate_disabled.png"); +} + +QCheckBox::indicator:indeterminate:focus, QCheckBox::indicator:indeterminate:hover, QCheckBox::indicator:indeterminate:pressed { + image: url(":/qss_icons/dark/rc/checkbox_indeterminate_focus.png"); +} + +/* QGroupBox -------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qgroupbox + +--------------------------------------------------------------------------- */ +QGroupBox { + font-weight: bold; + border: 1px solid #455364; + border-radius: 4px; + padding: 2px; + padding-top: 4px; + margin-top: 6px; + margin-bottom: 4px; +} + +QGroupBox::title { + subcontrol-origin: margin; + subcontrol-position: top left; + left: 4px; + padding-left: 2px; + padding-right: 4px; + padding-top: -4px; +} + +QGroupBox::indicator { + margin-left: 2px; + margin-top: 2px; + padding: 0; + height: 14px; + width: 14px; +} + +QGroupBox::indicator:unchecked { + border: none; + image: url(":/qss_icons/dark/rc/checkbox_unchecked.png"); +} + +QGroupBox::indicator:unchecked:hover, QGroupBox::indicator:unchecked:focus, QGroupBox::indicator:unchecked:pressed { + border: none; + image: url(":/qss_icons/dark/rc/checkbox_unchecked_focus.png"); +} + +QGroupBox::indicator:unchecked:disabled { + image: url(":/qss_icons/dark/rc/checkbox_unchecked_disabled.png"); +} + +QGroupBox::indicator:checked { + border: none; + image: url(":/qss_icons/dark/rc/checkbox_checked.png"); +} + +QGroupBox::indicator:checked:hover, QGroupBox::indicator:checked:focus, QGroupBox::indicator:checked:pressed { + border: none; + image: url(":/qss_icons/dark/rc/checkbox_checked_focus.png"); +} + +QGroupBox::indicator:checked:disabled { + image: url(":/qss_icons/dark/rc/checkbox_checked_disabled.png"); +} + +/* QRadioButton ----------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qradiobutton + +--------------------------------------------------------------------------- */ +QRadioButton { + background-color: #19232D; + color: #E0E1E3; + spacing: 4px; + padding-top: 4px; + padding-bottom: 4px; + border: none; + outline: none; +} + +QRadioButton:focus { + border: none; +} + +QRadioButton:disabled { + background-color: #19232D; + color: #9DA9B5; + border: none; + outline: none; +} + +QRadioButton QWidget { + background-color: #19232D; + color: #E0E1E3; + spacing: 0px; + padding: 0px; + outline: none; + border: none; +} + +QRadioButton::indicator { + border: none; + outline: none; + margin-left: 2px; + height: 14px; + width: 14px; +} + +QRadioButton::indicator:unchecked { + image: url(":/qss_icons/dark/rc/radio_unchecked.png"); +} + +QRadioButton::indicator:unchecked:hover, QRadioButton::indicator:unchecked:focus, QRadioButton::indicator:unchecked:pressed { + border: none; + outline: none; + image: url(":/qss_icons/dark/rc/radio_unchecked_focus.png"); +} + +QRadioButton::indicator:unchecked:disabled { + image: url(":/qss_icons/dark/rc/radio_unchecked_disabled.png"); +} + +QRadioButton::indicator:checked { + border: none; + outline: none; + image: url(":/qss_icons/dark/rc/radio_checked.png"); +} + +QRadioButton::indicator:checked:hover, QRadioButton::indicator:checked:focus, QRadioButton::indicator:checked:pressed { + border: none; + outline: none; + image: url(":/qss_icons/dark/rc/radio_checked_focus.png"); +} + +QRadioButton::indicator:checked:disabled { + outline: none; + image: url(":/qss_icons/dark/rc/radio_checked_disabled.png"); +} + +/* QMenuBar --------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qmenubar + +--------------------------------------------------------------------------- */ +QMenuBar { + background-color: #455364; + padding: 2px; + border: 1px solid #19232D; + color: #E0E1E3; + selection-background-color: #1A72BB; +} + +QMenuBar:focus { + border: 1px solid #346792; +} + +QMenuBar::item { + background: transparent; + padding: 4px; +} + +QMenuBar::item:selected { + padding: 4px; + background: transparent; + border: 0px solid #455364; + background-color: #1A72BB; +} + +QMenuBar::item:pressed { + padding: 4px; + border: 0px solid #455364; + background-color: #1A72BB; + color: #E0E1E3; + margin-bottom: 0px; + padding-bottom: 0px; +} + +/* QMenu ------------------------------------------------------------------ + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qmenu + +--------------------------------------------------------------------------- */ +QMenu { + border: 0px solid #455364; + color: #E0E1E3; + margin: 0px; + background-color: #37414F; + selection-background-color: #1A72BB; +} + +QMenu::separator { + height: 1px; + background-color: #60798B; + color: #E0E1E3; +} + +QMenu::item { + background-color: #37414F; + padding: 4px 24px 4px 28px; + /* Reserve space for selection border */ + border: 1px transparent #455364; +} + +QMenu::item:selected { + color: #E0E1E3; + background-color: #1A72BB; +} + +QMenu::item:pressed { + background-color: #1A72BB; +} + +QMenu::icon { + padding-left: 10px; + width: 14px; + height: 14px; +} + +QMenu::indicator { + padding-left: 8px; + width: 12px; + height: 12px; + /* non-exclusive indicator = check box style indicator (see QActionGroup::setExclusive) */ + /* exclusive indicator = radio button style indicator (see QActionGroup::setExclusive) */ +} + +QMenu::indicator:non-exclusive:unchecked { + image: url(":/qss_icons/dark/rc/checkbox_unchecked.png"); +} + +QMenu::indicator:non-exclusive:unchecked:hover, QMenu::indicator:non-exclusive:unchecked:focus, QMenu::indicator:non-exclusive:unchecked:pressed { + border: none; + image: url(":/qss_icons/dark/rc/checkbox_unchecked_focus.png"); +} + +QMenu::indicator:non-exclusive:unchecked:disabled { + image: url(":/qss_icons/dark/rc/checkbox_unchecked_disabled.png"); +} + +QMenu::indicator:non-exclusive:checked { + image: url(":/qss_icons/dark/rc/checkbox_checked.png"); +} + +QMenu::indicator:non-exclusive:checked:hover, QMenu::indicator:non-exclusive:checked:focus, QMenu::indicator:non-exclusive:checked:pressed { + border: none; + image: url(":/qss_icons/dark/rc/checkbox_checked_focus.png"); +} + +QMenu::indicator:non-exclusive:checked:disabled { + image: url(":/qss_icons/dark/rc/checkbox_checked_disabled.png"); +} + +QMenu::indicator:non-exclusive:indeterminate { + image: url(":/qss_icons/dark/rc/checkbox_indeterminate.png"); +} + +QMenu::indicator:non-exclusive:indeterminate:disabled { + image: url(":/qss_icons/dark/rc/checkbox_indeterminate_disabled.png"); +} + +QMenu::indicator:non-exclusive:indeterminate:focus, QMenu::indicator:non-exclusive:indeterminate:hover, QMenu::indicator:non-exclusive:indeterminate:pressed { + image: url(":/qss_icons/dark/rc/checkbox_indeterminate_focus.png"); +} + +QMenu::indicator:exclusive:unchecked { + image: url(":/qss_icons/dark/rc/radio_unchecked.png"); +} + +QMenu::indicator:exclusive:unchecked:hover, QMenu::indicator:exclusive:unchecked:focus, QMenu::indicator:exclusive:unchecked:pressed { + border: none; + outline: none; + image: url(":/qss_icons/dark/rc/radio_unchecked_focus.png"); +} + +QMenu::indicator:exclusive:unchecked:disabled { + image: url(":/qss_icons/dark/rc/radio_unchecked_disabled.png"); +} + +QMenu::indicator:exclusive:checked { + border: none; + outline: none; + image: url(":/qss_icons/dark/rc/radio_checked.png"); +} + +QMenu::indicator:exclusive:checked:hover, QMenu::indicator:exclusive:checked:focus, QMenu::indicator:exclusive:checked:pressed { + border: none; + outline: none; + image: url(":/qss_icons/dark/rc/radio_checked_focus.png"); +} + +QMenu::indicator:exclusive:checked:disabled { + outline: none; + image: url(":/qss_icons/dark/rc/radio_checked_disabled.png"); +} + +QMenu::right-arrow { + margin: 5px; + padding-left: 12px; + image: url(":/qss_icons/dark/rc/arrow_right.png"); + height: 12px; + width: 12px; +} + +/* QAbstractItemView ------------------------------------------------------ + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qcombobox + +--------------------------------------------------------------------------- */ +QAbstractItemView { + alternate-background-color: #19232D; + color: #E0E1E3; + border: 1px solid #455364; + border-radius: 4px; +} + +QAbstractItemView QLineEdit { + padding: 2px; +} + +/* QAbstractScrollArea ---------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qabstractscrollarea + +--------------------------------------------------------------------------- */ +QAbstractScrollArea { + background-color: #19232D; + border: 1px solid #455364; + border-radius: 4px; + /* fix #159 */ + padding: 2px; + /* remove min-height to fix #244 */ + color: #E0E1E3; +} + +QAbstractScrollArea:disabled { + color: #9DA9B5; +} + +/* QScrollArea ------------------------------------------------------------ + +--------------------------------------------------------------------------- */ +QScrollArea QWidget QWidget:disabled { + background-color: #19232D; +} + +/* QScrollBar ------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qscrollbar + +--------------------------------------------------------------------------- */ +QScrollBar:horizontal { + height: 16px; + margin: 2px 16px 2px 16px; + border: 1px solid #455364; + border-radius: 4px; + background-color: #19232D; +} + +QScrollBar:vertical { + background-color: #19232D; + width: 16px; + margin: 16px 2px 16px 2px; + border: 1px solid #455364; + border-radius: 4px; +} + +QScrollBar::handle:horizontal { + background-color: #60798B; + border: 1px solid #455364; + border-radius: 4px; + min-width: 8px; +} + +QScrollBar::handle:horizontal:hover { + background-color: #346792; + border: #346792; + border-radius: 4px; + min-width: 8px; +} + +QScrollBar::handle:horizontal:focus { + border: 1px solid #1A72BB; +} + +QScrollBar::handle:vertical { + background-color: #60798B; + border: 1px solid #455364; + min-height: 8px; + border-radius: 4px; +} + +QScrollBar::handle:vertical:hover { + background-color: #346792; + border: #346792; + border-radius: 4px; + min-height: 8px; +} + +QScrollBar::handle:vertical:focus { + border: 1px solid #1A72BB; +} + +QScrollBar::add-line:horizontal { + margin: 0px 0px 0px 0px; + border-image: url(":/qss_icons/dark/rc/arrow_right_disabled.png"); + height: 12px; + width: 12px; + subcontrol-position: right; + subcontrol-origin: margin; +} + +QScrollBar::add-line:horizontal:hover, QScrollBar::add-line:horizontal:on { + border-image: url(":/qss_icons/dark/rc/arrow_right.png"); + height: 12px; + width: 12px; + subcontrol-position: right; + subcontrol-origin: margin; +} + +QScrollBar::add-line:vertical { + margin: 3px 0px 3px 0px; + border-image: url(":/qss_icons/dark/rc/arrow_down_disabled.png"); + height: 12px; + width: 12px; + subcontrol-position: bottom; + subcontrol-origin: margin; +} + +QScrollBar::add-line:vertical:hover, QScrollBar::add-line:vertical:on { + border-image: url(":/qss_icons/dark/rc/arrow_down.png"); + height: 12px; + width: 12px; + subcontrol-position: bottom; + subcontrol-origin: margin; +} + +QScrollBar::sub-line:horizontal { + margin: 0px 3px 0px 3px; + border-image: url(":/qss_icons/dark/rc/arrow_left_disabled.png"); + height: 12px; + width: 12px; + subcontrol-position: left; + subcontrol-origin: margin; +} + +QScrollBar::sub-line:horizontal:hover, QScrollBar::sub-line:horizontal:on { + border-image: url(":/qss_icons/dark/rc/arrow_left.png"); + height: 12px; + width: 12px; + subcontrol-position: left; + subcontrol-origin: margin; +} + +QScrollBar::sub-line:vertical { + margin: 3px 0px 3px 0px; + border-image: url(":/qss_icons/dark/rc/arrow_up_disabled.png"); + height: 12px; + width: 12px; + subcontrol-position: top; + subcontrol-origin: margin; +} + +QScrollBar::sub-line:vertical:hover, QScrollBar::sub-line:vertical:on { + border-image: url(":/qss_icons/dark/rc/arrow_up.png"); + height: 12px; + width: 12px; + subcontrol-position: top; + subcontrol-origin: margin; +} + +QScrollBar::up-arrow:horizontal, QScrollBar::down-arrow:horizontal { + background: none; +} + +QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical { + background: none; +} + +QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal { + background: none; +} + +QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { + background: none; +} + +/* QTextEdit -------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-specific-widgets + +--------------------------------------------------------------------------- */ +QTextEdit { + background-color: #19232D; + color: #E0E1E3; + border-radius: 4px; + border: 1px solid #455364; +} + +QTextEdit:focus { + border: 1px solid #1A72BB; +} + +QTextEdit:selected { + background: #346792; + color: #455364; +} + +/* QPlainTextEdit --------------------------------------------------------- + +--------------------------------------------------------------------------- */ +QPlainTextEdit { + background-color: #19232D; + color: #E0E1E3; + border-radius: 4px; + border: 1px solid #455364; +} + +QPlainTextEdit:focus { + border: 1px solid #1A72BB; +} + +QPlainTextEdit:selected { + background: #346792; + color: #455364; +} + +/* QSizeGrip -------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qsizegrip + +--------------------------------------------------------------------------- */ +QSizeGrip { + background: transparent; + width: 12px; + height: 12px; + image: url(":/qss_icons/dark/rc/window_grip.png"); +} + +/* QStackedWidget --------------------------------------------------------- + +--------------------------------------------------------------------------- */ +QStackedWidget { + padding: 2px; + border: 1px solid #455364; + border: 1px solid #19232D; +} + +/* QToolBar --------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtoolbar + +--------------------------------------------------------------------------- */ +QToolBar { + background-color: #455364; + border-bottom: 1px solid #19232D; + padding: 1px; + font-weight: bold; + spacing: 2px; +} + +QToolBar:disabled { + /* Fixes #272 */ + background-color: #455364; +} + +QToolBar::handle:horizontal { + width: 16px; + image: url(":/qss_icons/dark/rc/toolbar_move_horizontal.png"); +} + +QToolBar::handle:vertical { + height: 16px; + image: url(":/qss_icons/dark/rc/toolbar_move_vertical.png"); +} + +QToolBar::separator:horizontal { + width: 16px; + image: url(":/qss_icons/dark/rc/toolbar_separator_horizontal.png"); +} + +QToolBar::separator:vertical { + height: 16px; + image: url(":/qss_icons/dark/rc/toolbar_separator_vertical.png"); +} + +QToolButton#qt_toolbar_ext_button { + background: #455364; + border: 0px; + color: #E0E1E3; + image: url(":/qss_icons/dark/rc/arrow_right.png"); +} + +/* QAbstractSpinBox ------------------------------------------------------- + +--------------------------------------------------------------------------- */ +QAbstractSpinBox { + background-color: #19232D; + border: 1px solid #455364; + color: #E0E1E3; + /* This fixes 103, 111 */ + padding-top: 2px; + /* This fixes 103, 111 */ + padding-bottom: 2px; + padding-left: 4px; + padding-right: 4px; + border-radius: 4px; + /* min-width: 5px; removed to fix 109 */ +} + +QAbstractSpinBox:up-button { + background-color: transparent #19232D; + subcontrol-origin: border; + subcontrol-position: top right; + border-left: 1px solid #455364; + border-bottom: 1px solid #455364; + border-top-left-radius: 0; + border-bottom-left-radius: 0; + margin: 1px; + width: 12px; + margin-bottom: -1px; +} + +QAbstractSpinBox::up-arrow, QAbstractSpinBox::up-arrow:disabled, QAbstractSpinBox::up-arrow:off { + image: url(":/qss_icons/dark/rc/arrow_up_disabled.png"); + height: 8px; + width: 8px; +} + +QAbstractSpinBox::up-arrow:hover { + image: url(":/qss_icons/dark/rc/arrow_up.png"); +} + +QAbstractSpinBox:down-button { + background-color: transparent #19232D; + subcontrol-origin: border; + subcontrol-position: bottom right; + border-left: 1px solid #455364; + border-top: 1px solid #455364; + border-top-left-radius: 0; + border-bottom-left-radius: 0; + margin: 1px; + width: 12px; + margin-top: -1px; +} + +QAbstractSpinBox::down-arrow, QAbstractSpinBox::down-arrow:disabled, QAbstractSpinBox::down-arrow:off { + image: url(":/qss_icons/dark/rc/arrow_down_disabled.png"); + height: 8px; + width: 8px; +} + +QAbstractSpinBox::down-arrow:hover { + image: url(":/qss_icons/dark/rc/arrow_down.png"); +} + +QAbstractSpinBox:hover { + border: 1px solid #346792; + color: #E0E1E3; +} + +QAbstractSpinBox:focus { + border: 1px solid #1A72BB; +} + +QAbstractSpinBox:selected { + background: #346792; + color: #455364; +} + +/* ------------------------------------------------------------------------ */ +/* DISPLAYS --------------------------------------------------------------- */ +/* ------------------------------------------------------------------------ */ +/* QLabel ----------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qframe + +--------------------------------------------------------------------------- */ +QLabel { + background-color: #19232D; + border: 0px solid #455364; + padding: 0px; + margin: 0px; + color: #E0E1E3; +} + +QLabel:disabled { + background-color: #19232D; + border: 0px solid #455364; + color: #9DA9B5; +} + +/* QTextBrowser ----------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qabstractscrollarea + +--------------------------------------------------------------------------- */ +QTextBrowser { + background-color: #19232D; + border: 1px solid #455364; + color: #E0E1E3; + border-radius: 4px; +} + +QTextBrowser:disabled { + background-color: #19232D; + border: 1px solid #455364; + color: #9DA9B5; + border-radius: 4px; +} + +QTextBrowser:hover, QTextBrowser:!hover, QTextBrowser:selected, QTextBrowser:pressed { + border: 1px solid #455364; +} + +/* QGraphicsView ---------------------------------------------------------- + +--------------------------------------------------------------------------- */ +QGraphicsView { + background-color: #19232D; + border: 1px solid #455364; + color: #E0E1E3; + border-radius: 4px; +} + +QGraphicsView:disabled { + background-color: #19232D; + border: 1px solid #455364; + color: #9DA9B5; + border-radius: 4px; +} + +QGraphicsView:hover, QGraphicsView:!hover, QGraphicsView:selected, QGraphicsView:pressed { + border: 1px solid #455364; +} + +/* QCalendarWidget -------------------------------------------------------- + +--------------------------------------------------------------------------- */ +QCalendarWidget { + border: 1px solid #455364; + border-radius: 4px; +} + +QCalendarWidget:disabled { + background-color: #19232D; + color: #9DA9B5; +} + +/* QLCDNumber ------------------------------------------------------------- + +--------------------------------------------------------------------------- */ +QLCDNumber { + background-color: #19232D; + color: #E0E1E3; +} + +QLCDNumber:disabled { + background-color: #19232D; + color: #9DA9B5; +} + +/* QProgressBar ----------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qprogressbar + +--------------------------------------------------------------------------- */ +QProgressBar { + background-color: #19232D; + border: 1px solid #455364; + color: #E0E1E3; + border-radius: 4px; + text-align: center; +} + +QProgressBar:disabled { + background-color: #19232D; + border: 1px solid #455364; + color: #9DA9B5; + border-radius: 4px; + text-align: center; +} + +QProgressBar::chunk { + background-color: #346792; + color: #19232D; + border-radius: 4px; +} + +QProgressBar::chunk:disabled { + background-color: #26486B; + color: #9DA9B5; + border-radius: 4px; +} + +/* ------------------------------------------------------------------------ */ +/* BUTTONS ---------------------------------------------------------------- */ +/* ------------------------------------------------------------------------ */ +/* QPushButton ------------------------------------------------------------ + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qpushbutton + +--------------------------------------------------------------------------- */ +QPushButton { + background-color: #455364; + color: #E0E1E3; + border-radius: 4px; + padding: 2px; + outline: none; + border: none; +} + +QPushButton:disabled { + background-color: #455364; + color: #9DA9B5; + border-radius: 4px; + padding: 2px; +} + +QPushButton:checked { + background-color: #60798B; + border-radius: 4px; + padding: 2px; + outline: none; +} + +QPushButton:checked:disabled { + background-color: #60798B; + color: #9DA9B5; + border-radius: 4px; + padding: 2px; + outline: none; +} + +QPushButton:checked:selected { + background: #60798B; +} + +QPushButton:hover { + background-color: #54687A; + color: #E0E1E3; +} + +QPushButton:pressed { + background-color: #60798B; +} + +QPushButton:selected { + background: #60798B; + color: #E0E1E3; +} + +QPushButton::menu-indicator { + subcontrol-origin: padding; + subcontrol-position: bottom right; + bottom: 4px; +} + +QDialogButtonBox QPushButton { + /* Issue #194 #248 - Special case of QPushButton inside dialogs, for better UI */ + min-width: 80px; +} + +/* QToolButton ------------------------------------------------------------ + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtoolbutton + +--------------------------------------------------------------------------- */ +QToolButton { + background-color: #455364; + color: #E0E1E3; + border-radius: 4px; + padding: 2px; + outline: none; + border: none; + /* The subcontrols below are used only in the DelayedPopup mode */ + /* The subcontrols below are used only in the MenuButtonPopup mode */ + /* The subcontrol below is used only in the InstantPopup or DelayedPopup mode */ +} + +QToolButton:disabled { + background-color: #455364; + color: #9DA9B5; + border-radius: 4px; + padding: 2px; +} + +QToolButton:checked { + background-color: #60798B; + border-radius: 4px; + padding: 2px; + outline: none; +} + +QToolButton:checked:disabled { + background-color: #60798B; + color: #9DA9B5; + border-radius: 4px; + padding: 2px; + outline: none; +} + +QToolButton:checked:hover { + background-color: #54687A; + color: #E0E1E3; +} + +QToolButton:checked:pressed { + background-color: #60798B; +} + +QToolButton:checked:selected { + background: #60798B; + color: #E0E1E3; +} + +QToolButton:hover { + background-color: #54687A; + color: #E0E1E3; +} + +QToolButton:pressed { + background-color: #60798B; +} + +QToolButton:selected { + background: #60798B; + color: #E0E1E3; +} + +QToolButton[popupMode="0"] { + /* Only for DelayedPopup */ + padding-right: 2px; +} + +QToolButton[popupMode="1"] { + /* Only for MenuButtonPopup */ + padding-right: 20px; +} + +QToolButton[popupMode="1"]::menu-button { + border: none; +} + +QToolButton[popupMode="1"]::menu-button:hover { + border: none; + border-left: 1px solid #455364; + border-radius: 0; +} + +QToolButton[popupMode="2"] { + /* Only for InstantPopup */ + padding-right: 2px; +} + +QToolButton::menu-button { + padding: 2px; + border-radius: 4px; + width: 12px; + border: none; + outline: none; +} + +QToolButton::menu-button:hover { + border: 1px solid #346792; +} + +QToolButton::menu-button:checked:hover { + border: 1px solid #346792; +} + +QToolButton::menu-indicator { + image: url(":/qss_icons/dark/rc/arrow_down.png"); + height: 8px; + width: 8px; + top: 0; + /* Exclude a shift for better image */ + left: -2px; + /* Shift it a bit */ +} + +QToolButton::menu-arrow { + image: url(":/qss_icons/dark/rc/arrow_down.png"); + height: 8px; + width: 8px; +} + +QToolButton::menu-arrow:hover { + image: url(":/qss_icons/dark/rc/arrow_down_focus.png"); +} + +/* QCommandLinkButton ----------------------------------------------------- + +--------------------------------------------------------------------------- */ +QCommandLinkButton { + background-color: transparent; + border: 1px solid #455364; + color: #E0E1E3; + border-radius: 4px; + padding: 0px; + margin: 0px; +} + +QCommandLinkButton:disabled { + background-color: transparent; + color: #9DA9B5; +} + +/* ------------------------------------------------------------------------ */ +/* INPUTS - NO FIELDS ----------------------------------------------------- */ +/* ------------------------------------------------------------------------ */ +/* QComboBox -------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qcombobox + +--------------------------------------------------------------------------- */ +QComboBox { + border: 1px solid #455364; + border-radius: 4px; + selection-background-color: #346792; + padding-left: 4px; + padding-right: 4px; + /* padding-right = 36; 4 + 16*2 See scrollbar size */ + /* changed to 4px to fix #239 */ + /* Fixes #103, #111 */ + min-height: 1.5em; + /* padding-top: 2px; removed to fix #132 */ + /* padding-bottom: 2px; removed to fix #132 */ + /* min-width: 75px; removed to fix #109 */ + /* Needed to remove indicator - fix #132 */ +} + +QComboBox QAbstractItemView { + border: 1px solid #455364; + border-radius: 0; + background-color: #19232D; + selection-background-color: #346792; +} + +QComboBox QAbstractItemView:hover { + background-color: #19232D; + color: #E0E1E3; +} + +QComboBox QAbstractItemView:selected { + background: #346792; + color: #455364; +} + +QComboBox QAbstractItemView:alternate { + background: #19232D; +} + +QComboBox:disabled { + background-color: #19232D; + color: #9DA9B5; +} + +QComboBox:hover { + border: 1px solid #346792; +} + +QComboBox:focus { + border: 1px solid #1A72BB; +} + +QComboBox:on { + selection-background-color: #346792; +} + +QComboBox::indicator { + border: none; + border-radius: 0; + background-color: transparent; + selection-background-color: transparent; + color: transparent; + selection-color: transparent; + /* Needed to remove indicator - fix #132 */ +} + +QComboBox::indicator:alternate { + background: #19232D; +} + +QComboBox::item { + /* Remove to fix #282, #285 and MR #288*/ + /*&:checked { + font-weight: bold; + } + + &:selected { + border: 0px solid transparent; + } + */ +} + +QComboBox::item:alternate { + background: #19232D; +} + +QComboBox::drop-down { + subcontrol-origin: padding; + subcontrol-position: top right; + width: 12px; + border-left: 1px solid #455364; +} + +QComboBox::down-arrow { + image: url(":/qss_icons/dark/rc/arrow_down_disabled.png"); + height: 8px; + width: 8px; +} + +QComboBox::down-arrow:on, QComboBox::down-arrow:hover, QComboBox::down-arrow:focus { + image: url(":/qss_icons/dark/rc/arrow_down.png"); +} + +/* QSlider ---------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qslider + +--------------------------------------------------------------------------- */ +QSlider:disabled { + background: #19232D; +} + +QSlider:focus { + border: none; +} + +QSlider::groove:horizontal { + background: #455364; + border: 1px solid #455364; + height: 4px; + margin: 0px; + border-radius: 4px; +} + +QSlider::groove:vertical { + background: #455364; + border: 1px solid #455364; + width: 4px; + margin: 0px; + border-radius: 4px; +} + +QSlider::add-page:vertical { + background: #346792; + border: 1px solid #455364; + width: 4px; + margin: 0px; + border-radius: 4px; +} + +QSlider::add-page:vertical :disabled { + background: #26486B; +} + +QSlider::sub-page:horizontal { + background: #346792; + border: 1px solid #455364; + height: 4px; + margin: 0px; + border-radius: 4px; +} + +QSlider::sub-page:horizontal:disabled { + background: #26486B; +} + +QSlider::handle:horizontal { + background: #9DA9B5; + border: 1px solid #455364; + width: 8px; + height: 8px; + margin: -8px 0px; + border-radius: 4px; +} + +QSlider::handle:horizontal:hover { + background: #346792; + border: 1px solid #346792; +} + +QSlider::handle:horizontal:focus { + border: 1px solid #1A72BB; +} + +QSlider::handle:vertical { + background: #9DA9B5; + border: 1px solid #455364; + width: 8px; + height: 8px; + margin: 0 -8px; + border-radius: 4px; +} + +QSlider::handle:vertical:hover { + background: #346792; + border: 1px solid #346792; +} + +QSlider::handle:vertical:focus { + border: 1px solid #1A72BB; +} + +/* QLineEdit -------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qlineedit + +--------------------------------------------------------------------------- */ +QLineEdit { + background-color: #19232D; + padding-top: 2px; + /* This QLineEdit fix 103, 111 */ + padding-bottom: 2px; + /* This QLineEdit fix 103, 111 */ + padding-left: 4px; + padding-right: 4px; + border-style: solid; + border: 1px solid #455364; + border-radius: 4px; + color: #E0E1E3; +} + +QLineEdit:disabled { + background-color: #19232D; + color: #9DA9B5; +} + +QLineEdit:hover { + border: 1px solid #346792; + color: #E0E1E3; +} + +QLineEdit:focus { + border: 1px solid #1A72BB; +} + +QLineEdit:selected { + background-color: #346792; + color: #455364; +} + +/* QTabWiget -------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtabwidget-and-qtabbar + +--------------------------------------------------------------------------- */ +QTabWidget { + padding: 2px; + selection-background-color: #455364; +} + +QTabWidget QWidget { + /* Fixes #189 */ + border-radius: 4px; +} + +QTabWidget::pane { + border: 1px solid #455364; + border-radius: 4px; + margin: 0px; + /* Fixes double border inside pane with pyqt5 */ + padding: 0px; +} + +QTabWidget::pane:selected { + background-color: #455364; + border: 1px solid #346792; +} + +/* QTabBar ---------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtabwidget-and-qtabbar + +--------------------------------------------------------------------------- */ +QTabBar, QDockWidget QTabBar { + qproperty-drawBase: 0; + border-radius: 4px; + margin: 0px; + padding: 2px; + border: 0; + /* left: 5px; move to the right by 5px - removed for fix */ +} + +QTabBar::close-button, QDockWidget QTabBar::close-button { + border: 0; + margin: 0; + padding: 4px; + image: url(":/qss_icons/dark/rc/window_close.png"); +} + +QTabBar::close-button:hover, QDockWidget QTabBar::close-button:hover { + image: url(":/qss_icons/dark/rc/window_close_focus.png"); +} + +QTabBar::close-button:pressed, QDockWidget QTabBar::close-button:pressed { + image: url(":/qss_icons/dark/rc/window_close_pressed.png"); +} + +QTabBar::tab, QDockWidget QTabBar::tab { + /* !selected and disabled ----------------------------------------- */ + /* selected ------------------------------------------------------- */ +} + +QTabBar::tab:top:selected:disabled, QDockWidget QTabBar::tab:top:selected:disabled { + border-bottom: 3px solid #26486B; + color: #9DA9B5; + background-color: #455364; +} + +QTabBar::tab:bottom:selected:disabled, QDockWidget QTabBar::tab:bottom:selected:disabled { + border-top: 3px solid #26486B; + color: #9DA9B5; + background-color: #455364; +} + +QTabBar::tab:left:selected:disabled, QDockWidget QTabBar::tab:left:selected:disabled { + border-right: 3px solid #26486B; + color: #9DA9B5; + background-color: #455364; +} + +QTabBar::tab:right:selected:disabled, QDockWidget QTabBar::tab:right:selected:disabled { + border-left: 3px solid #26486B; + color: #9DA9B5; + background-color: #455364; +} + +QTabBar::tab:top:!selected:disabled, QDockWidget QTabBar::tab:top:!selected:disabled { + border-bottom: 3px solid #19232D; + color: #9DA9B5; + background-color: #19232D; +} + +QTabBar::tab:bottom:!selected:disabled, QDockWidget QTabBar::tab:bottom:!selected:disabled { + border-top: 3px solid #19232D; + color: #9DA9B5; + background-color: #19232D; +} + +QTabBar::tab:left:!selected:disabled, QDockWidget QTabBar::tab:left:!selected:disabled { + border-right: 3px solid #19232D; + color: #9DA9B5; + background-color: #19232D; +} + +QTabBar::tab:right:!selected:disabled, QDockWidget QTabBar::tab:right:!selected:disabled { + border-left: 3px solid #19232D; + color: #9DA9B5; + background-color: #19232D; +} + +QTabBar::tab:top:!selected, QDockWidget QTabBar::tab:top:!selected { + border-bottom: 2px solid #19232D; + margin-top: 2px; +} + +QTabBar::tab:bottom:!selected, QDockWidget QTabBar::tab:bottom:!selected { + border-top: 2px solid #19232D; + margin-bottom: 2px; +} + +QTabBar::tab:left:!selected, QDockWidget QTabBar::tab:left:!selected { + border-left: 2px solid #19232D; + margin-right: 2px; +} + +QTabBar::tab:right:!selected, QDockWidget QTabBar::tab:right:!selected { + border-right: 2px solid #19232D; + margin-left: 2px; +} + +QTabBar::tab:top, QDockWidget QTabBar::tab:top { + background-color: #455364; + margin-left: 2px; + padding-left: 4px; + padding-right: 4px; + padding-top: 2px; + padding-bottom: 2px; + min-width: 5px; + border-bottom: 3px solid #455364; + border-top-left-radius: 4px; + border-top-right-radius: 4px; +} + +QTabBar::tab:top:selected, QDockWidget QTabBar::tab:top:selected { + background-color: #54687A; + border-bottom: 3px solid #259AE9; + border-top-left-radius: 4px; + border-top-right-radius: 4px; +} + +QTabBar::tab:top:!selected:hover, QDockWidget QTabBar::tab:top:!selected:hover { + border: 1px solid #1A72BB; + border-bottom: 3px solid #1A72BB; + /* Fixes spyder-ide/spyder#9766 and #243 */ + padding-left: 3px; + padding-right: 3px; +} + +QTabBar::tab:bottom, QDockWidget QTabBar::tab:bottom { + border-top: 3px solid #455364; + background-color: #455364; + margin-left: 2px; + padding-left: 4px; + padding-right: 4px; + padding-top: 2px; + padding-bottom: 2px; + border-bottom-left-radius: 4px; + border-bottom-right-radius: 4px; + min-width: 5px; +} + +QTabBar::tab:bottom:selected, QDockWidget QTabBar::tab:bottom:selected { + background-color: #54687A; + border-top: 3px solid #259AE9; + border-bottom-left-radius: 4px; + border-bottom-right-radius: 4px; +} + +QTabBar::tab:bottom:!selected:hover, QDockWidget QTabBar::tab:bottom:!selected:hover { + border: 1px solid #1A72BB; + border-top: 3px solid #1A72BB; + /* Fixes spyder-ide/spyder#9766 and #243 */ + padding-left: 3px; + padding-right: 3px; +} + +QTabBar::tab:left, QDockWidget QTabBar::tab:left { + background-color: #455364; + margin-top: 2px; + padding-left: 2px; + padding-right: 2px; + padding-top: 4px; + padding-bottom: 4px; + border-top-left-radius: 4px; + border-bottom-left-radius: 4px; + min-height: 5px; +} + +QTabBar::tab:left:selected, QDockWidget QTabBar::tab:left:selected { + background-color: #54687A; + border-right: 3px solid #259AE9; +} + +QTabBar::tab:left:!selected:hover, QDockWidget QTabBar::tab:left:!selected:hover { + border: 1px solid #1A72BB; + border-right: 3px solid #1A72BB; + /* Fixes different behavior #271 */ + margin-right: 0px; + padding-right: -1px; +} + +QTabBar::tab:right, QDockWidget QTabBar::tab:right { + background-color: #455364; + margin-top: 2px; + padding-left: 2px; + padding-right: 2px; + padding-top: 4px; + padding-bottom: 4px; + border-top-right-radius: 4px; + border-bottom-right-radius: 4px; + min-height: 5px; +} + +QTabBar::tab:right:selected, QDockWidget QTabBar::tab:right:selected { + background-color: #54687A; + border-left: 3px solid #259AE9; +} + +QTabBar::tab:right:!selected:hover, QDockWidget QTabBar::tab:right:!selected:hover { + border: 1px solid #1A72BB; + border-left: 3px solid #1A72BB; + /* Fixes different behavior #271 */ + margin-left: 0px; + padding-left: 0px; +} + +QTabBar QToolButton, QDockWidget QTabBar QToolButton { + /* Fixes #136 */ + background-color: #455364; + height: 12px; + width: 12px; +} + +QTabBar QToolButton:pressed, QDockWidget QTabBar QToolButton:pressed { + background-color: #455364; +} + +QTabBar QToolButton:pressed:hover, QDockWidget QTabBar QToolButton:pressed:hover { + border: 1px solid #346792; +} + +QTabBar QToolButton::left-arrow:enabled, QDockWidget QTabBar QToolButton::left-arrow:enabled { + image: url(":/qss_icons/dark/rc/arrow_left.png"); +} + +QTabBar QToolButton::left-arrow:disabled, QDockWidget QTabBar QToolButton::left-arrow:disabled { + image: url(":/qss_icons/dark/rc/arrow_left_disabled.png"); +} + +QTabBar QToolButton::right-arrow:enabled, QDockWidget QTabBar QToolButton::right-arrow:enabled { + image: url(":/qss_icons/dark/rc/arrow_right.png"); +} + +QTabBar QToolButton::right-arrow:disabled, QDockWidget QTabBar QToolButton::right-arrow:disabled { + image: url(":/qss_icons/dark/rc/arrow_right_disabled.png"); +} + +/* QDockWiget ------------------------------------------------------------- + +--------------------------------------------------------------------------- */ +QDockWidget { + outline: 1px solid #455364; + background-color: #19232D; + border: 1px solid #455364; + border-radius: 4px; + titlebar-close-icon: url(":/qss_icons/dark/rc/transparent.png"); + titlebar-normal-icon: url(":/qss_icons/dark/rc/transparent.png"); +} + +QDockWidget::title { + /* Better size for title bar */ + padding: 3px; + spacing: 4px; + border: none; + background-color: #455364; +} + +QDockWidget::close-button { + icon-size: 12px; + border: none; + background: transparent; + background-image: transparent; + border: 0; + margin: 0; + padding: 0; + image: url(":/qss_icons/dark/rc/window_close.png"); +} + +QDockWidget::close-button:hover { + image: url(":/qss_icons/dark/rc/window_close_focus.png"); +} + +QDockWidget::close-button:pressed { + image: url(":/qss_icons/dark/rc/window_close_pressed.png"); +} + +QDockWidget::float-button { + icon-size: 12px; + border: none; + background: transparent; + background-image: transparent; + border: 0; + margin: 0; + padding: 0; + image: url(":/qss_icons/dark/rc/window_undock.png"); +} + +QDockWidget::float-button:hover { + image: url(":/qss_icons/dark/rc/window_undock_focus.png"); +} + +QDockWidget::float-button:pressed { + image: url(":/qss_icons/dark/rc/window_undock_pressed.png"); +} + +/* QTreeView QListView QTableView ----------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtreeview +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qlistview +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtableview + +--------------------------------------------------------------------------- */ +QTreeView:branch:selected, QTreeView:branch:hover { + background: url(":/qss_icons/dark/rc/transparent.png"); +} + +QTreeView:branch:has-siblings:!adjoins-item { + border-image: url(":/qss_icons/dark/rc/branch_line.png") 0; +} + +QTreeView:branch:has-siblings:adjoins-item { + border-image: url(":/qss_icons/dark/rc/branch_more.png") 0; +} + +QTreeView:branch:!has-children:!has-siblings:adjoins-item { + border-image: url(":/qss_icons/dark/rc/branch_end.png") 0; +} + +QTreeView:branch:has-children:!has-siblings:closed, QTreeView:branch:closed:has-children:has-siblings { + border-image: none; + image: url(":/qss_icons/dark/rc/branch_closed.png"); +} + +QTreeView:branch:open:has-children:!has-siblings, QTreeView:branch:open:has-children:has-siblings { + border-image: none; + image: url(":/qss_icons/dark/rc/branch_open.png"); +} + +QTreeView:branch:has-children:!has-siblings:closed:hover, QTreeView:branch:closed:has-children:has-siblings:hover { + image: url(":/qss_icons/dark/rc/branch_closed_focus.png"); +} + +QTreeView:branch:open:has-children:!has-siblings:hover, QTreeView:branch:open:has-children:has-siblings:hover { + image: url(":/qss_icons/dark/rc/branch_open_focus.png"); +} + +QTreeView::indicator:checked, +QListView::indicator:checked, +QTableView::indicator:checked, +QColumnView::indicator:checked { + image: url(":/qss_icons/dark/rc/checkbox_checked.png"); +} + +QTreeView::indicator:checked:hover, QTreeView::indicator:checked:focus, QTreeView::indicator:checked:pressed, +QListView::indicator:checked:hover, +QListView::indicator:checked:focus, +QListView::indicator:checked:pressed, +QTableView::indicator:checked:hover, +QTableView::indicator:checked:focus, +QTableView::indicator:checked:pressed, +QColumnView::indicator:checked:hover, +QColumnView::indicator:checked:focus, +QColumnView::indicator:checked:pressed { + image: url(":/qss_icons/dark/rc/checkbox_checked_focus.png"); +} + +QTreeView::indicator:unchecked, +QListView::indicator:unchecked, +QTableView::indicator:unchecked, +QColumnView::indicator:unchecked { + image: url(":/qss_icons/dark/rc/checkbox_unchecked.png"); +} + +QTreeView::indicator:unchecked:hover, QTreeView::indicator:unchecked:focus, QTreeView::indicator:unchecked:pressed, +QListView::indicator:unchecked:hover, +QListView::indicator:unchecked:focus, +QListView::indicator:unchecked:pressed, +QTableView::indicator:unchecked:hover, +QTableView::indicator:unchecked:focus, +QTableView::indicator:unchecked:pressed, +QColumnView::indicator:unchecked:hover, +QColumnView::indicator:unchecked:focus, +QColumnView::indicator:unchecked:pressed { + image: url(":/qss_icons/dark/rc/checkbox_unchecked_focus.png"); +} + +QTreeView::indicator:indeterminate, +QListView::indicator:indeterminate, +QTableView::indicator:indeterminate, +QColumnView::indicator:indeterminate { + image: url(":/qss_icons/dark/rc/checkbox_indeterminate.png"); +} + +QTreeView::indicator:indeterminate:hover, QTreeView::indicator:indeterminate:focus, QTreeView::indicator:indeterminate:pressed, +QListView::indicator:indeterminate:hover, +QListView::indicator:indeterminate:focus, +QListView::indicator:indeterminate:pressed, +QTableView::indicator:indeterminate:hover, +QTableView::indicator:indeterminate:focus, +QTableView::indicator:indeterminate:pressed, +QColumnView::indicator:indeterminate:hover, +QColumnView::indicator:indeterminate:focus, +QColumnView::indicator:indeterminate:pressed { + image: url(":/qss_icons/dark/rc/checkbox_indeterminate_focus.png"); +} + +QTreeView, +QListView, +QTableView, +QColumnView { + background-color: #19232D; + border: 1px solid #455364; + color: #E0E1E3; + gridline-color: #455364; + border-radius: 4px; +} + +QTreeView:disabled, +QListView:disabled, +QTableView:disabled, +QColumnView:disabled { + background-color: #19232D; + color: #9DA9B5; +} + +QTreeView:selected, +QListView:selected, +QTableView:selected, +QColumnView:selected { + background-color: #346792; + color: #455364; +} + +QTreeView:focus, +QListView:focus, +QTableView:focus, +QColumnView:focus { + border: 1px solid #1A72BB; +} + +QTreeView::item:pressed, +QListView::item:pressed, +QTableView::item:pressed, +QColumnView::item:pressed { + background-color: #346792; +} + +QTreeView::item:selected:active, +QListView::item:selected:active, +QTableView::item:selected:active, +QColumnView::item:selected:active { + background-color: #346792; +} + +QTreeView::item:selected:!active, +QListView::item:selected:!active, +QTableView::item:selected:!active, +QColumnView::item:selected:!active { + color: #E0E1E3; + background-color: #37414F; +} + +QTreeView::item:!selected:hover, +QListView::item:!selected:hover, +QTableView::item:!selected:hover, +QColumnView::item:!selected:hover { + outline: 0; + color: #E0E1E3; + background-color: #37414F; +} + +QTableCornerButton::section { + background-color: #19232D; + border: 1px transparent #455364; + border-radius: 0px; +} + +/* QHeaderView ------------------------------------------------------------ + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qheaderview + +--------------------------------------------------------------------------- */ +QHeaderView { + background-color: #455364; + border: 0px transparent #455364; + padding: 0; + margin: 0; + border-radius: 0; +} + +QHeaderView:disabled { + background-color: #455364; + border: 1px transparent #455364; +} + +QHeaderView::section { + background-color: #455364; + color: #E0E1E3; + border-radius: 0; + text-align: left; + font-size: 13px; +} + +QHeaderView::section::horizontal { + padding-top: 0; + padding-bottom: 0; + padding-left: 4px; + padding-right: 4px; + border-left: 1px solid #19232D; +} + +QHeaderView::section::horizontal::first, QHeaderView::section::horizontal::only-one { + border-left: 1px solid #455364; +} + +QHeaderView::section::horizontal:disabled { + color: #9DA9B5; +} + +QHeaderView::section::vertical { + padding-top: 0; + padding-bottom: 0; + padding-left: 4px; + padding-right: 4px; + border-top: 1px solid #19232D; +} + +QHeaderView::section::vertical::first, QHeaderView::section::vertical::only-one { + border-top: 1px solid #455364; +} + +QHeaderView::section::vertical:disabled { + color: #9DA9B5; +} + +QHeaderView::down-arrow { + /* Those settings (border/width/height/background-color) solve bug */ + /* transparent arrow background and size */ + background-color: #455364; + border: none; + height: 12px; + width: 12px; + padding-left: 2px; + padding-right: 2px; + image: url(":/qss_icons/dark/rc/arrow_down.png"); +} + +QHeaderView::up-arrow { + background-color: #455364; + border: none; + height: 12px; + width: 12px; + padding-left: 2px; + padding-right: 2px; + image: url(":/qss_icons/dark/rc/arrow_up.png"); +} + +/* QToolBox -------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtoolbox + +--------------------------------------------------------------------------- */ +QToolBox { + padding: 0px; + border: 0px; + border: 1px solid #455364; +} + +QToolBox:selected { + padding: 0px; + border: 2px solid #346792; +} + +QToolBox::tab { + background-color: #19232D; + border: 1px solid #455364; + color: #E0E1E3; + border-top-left-radius: 4px; + border-top-right-radius: 4px; +} + +QToolBox::tab:disabled { + color: #9DA9B5; +} + +QToolBox::tab:selected { + background-color: #60798B; + border-bottom: 2px solid #346792; +} + +QToolBox::tab:selected:disabled { + background-color: #455364; + border-bottom: 2px solid #26486B; +} + +QToolBox::tab:!selected { + background-color: #455364; + border-bottom: 2px solid #455364; +} + +QToolBox::tab:!selected:disabled { + background-color: #19232D; +} + +QToolBox::tab:hover { + border-color: #1A72BB; + border-bottom: 2px solid #1A72BB; +} + +QToolBox QScrollArea QWidget QWidget { + padding: 0px; + border: 0px; + background-color: #19232D; +} + +/* QFrame ----------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qframe +https://doc.qt.io/qt-5/qframe.html#-prop +https://doc.qt.io/qt-5/qframe.html#details +https://stackoverflow.com/questions/14581498/qt-stylesheet-for-hline-vline-color + +--------------------------------------------------------------------------- */ +/* (dot) .QFrame fix #141, #126, #123 */ +.QFrame { + border-radius: 4px; + border: 1px solid #455364; + /* No frame */ + /* HLine */ + /* HLine */ +} + +.QFrame[frameShape="0"] { + border-radius: 4px; + border: 1px transparent #455364; +} + +.QFrame[frameShape="4"] { + max-height: 2px; + border: none; + background-color: #455364; +} + +.QFrame[frameShape="5"] { + max-width: 2px; + border: none; + background-color: #455364; +} + +/* QSplitter -------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qsplitter + +--------------------------------------------------------------------------- */ +QSplitter { + background-color: #455364; + spacing: 0px; + padding: 0px; + margin: 0px; +} + +QSplitter::handle { + background-color: #455364; + border: 0px solid #19232D; + spacing: 0px; + padding: 1px; + margin: 0px; +} + +QSplitter::handle:hover { + background-color: #9DA9B5; +} + +QSplitter::handle:horizontal { + width: 5px; + image: url(":/qss_icons/dark/rc/line_vertical.png"); +} + +QSplitter::handle:vertical { + height: 5px; + image: url(":/qss_icons/dark/rc/line_horizontal.png"); +} + +/* QDateEdit, QDateTimeEdit ----------------------------------------------- + +--------------------------------------------------------------------------- */ +QDateEdit, QDateTimeEdit { + selection-background-color: #346792; + border-style: solid; + border: 1px solid #455364; + border-radius: 4px; + /* This fixes 103, 111 */ + padding-top: 2px; + /* This fixes 103, 111 */ + padding-bottom: 2px; + padding-left: 4px; + padding-right: 4px; + min-width: 10px; +} + +QDateEdit:on, QDateTimeEdit:on { + selection-background-color: #346792; +} + +QDateEdit::drop-down, QDateTimeEdit::drop-down { + subcontrol-origin: padding; + subcontrol-position: top right; + width: 12px; + border-left: 1px solid #455364; +} + +QDateEdit::down-arrow, QDateTimeEdit::down-arrow { + image: url(":/qss_icons/dark/rc/arrow_down_disabled.png"); + height: 8px; + width: 8px; +} + +QDateEdit::down-arrow:on, QDateEdit::down-arrow:hover, QDateEdit::down-arrow:focus, QDateTimeEdit::down-arrow:on, QDateTimeEdit::down-arrow:hover, QDateTimeEdit::down-arrow:focus { + image: url(":/qss_icons/dark/rc/arrow_down.png"); +} + +QDateEdit QAbstractItemView, QDateTimeEdit QAbstractItemView { + background-color: #19232D; + border-radius: 4px; + border: 1px solid #455364; + selection-background-color: #346792; +} + +/* QAbstractView ---------------------------------------------------------- + +--------------------------------------------------------------------------- */ +QAbstractView:hover { + border: 1px solid #346792; + color: #E0E1E3; +} + +QAbstractView:selected { + background: #346792; + color: #455364; +} + +/* PlotWidget ------------------------------------------------------------- + +--------------------------------------------------------------------------- */ +PlotWidget { + /* Fix cut labels in plots #134 */ + padding: 0px; +} diff --git a/3rdParty/qdarkstyle/dark/darkstyle_rc.py b/3rdParty/qdarkstyle/dark/darkstyle_rc.py index 7eaf96d61f..8b382a74a8 100644 --- a/3rdParty/qdarkstyle/dark/darkstyle_rc.py +++ b/3rdParty/qdarkstyle/dark/darkstyle_rc.py @@ -1,11382 +1,11382 @@ -# -*- coding: utf-8 -*- - -# Resource object code -# -# Created by: The Resource Compiler for PyQt5 (Qt v5.15.2) -# -# WARNING! All changes made in this file will be lost! - -from qtpy import QtCore - -qt_resource_data = b"\ -\x00\x00\x1a\xa6\ -\x00\ -\x00\xdc\x92\x78\x9c\xd5\x3d\x6b\x6f\xdb\x46\xb6\xdf\x0b\xf4\x3f\ -\xd0\x31\xb0\x68\xbb\x96\x6d\xc9\xb2\x63\xab\xe8\x07\x3b\x8f\x6e\ -\x80\x34\x4d\x6a\x77\x8b\x8b\xc5\x85\x41\x49\x94\xc5\x0d\x45\x2a\ -\x24\x15\xc7\x2d\xee\x7f\xbf\x33\x43\xce\x70\x1e\x67\x5e\x7c\xd8\ -\xa9\x81\xa6\xb6\x34\x73\xde\x73\xce\x3c\xce\x9c\x39\xfa\x21\x18\ -\xf5\xf7\xf3\xed\x37\xdf\x7e\x13\xa0\x9f\x3f\x2e\x7f\x7b\xf7\xe6\ -\xdd\xcf\x7b\xc1\xeb\x38\x89\x82\x45\x1e\x85\x65\xb4\x0c\xb6\x79\ -\x76\x97\x87\x9b\x4d\x58\xc6\x8b\x30\x49\x1e\x0e\x83\xcb\x24\x09\ -\x16\xeb\x30\xbd\x8b\x8a\x60\x13\x2e\xa3\x20\x4e\x83\x72\x1d\x17\ -\xc1\x0a\xf7\xbb\x8f\xd1\xd7\xf3\x28\x48\xb2\xa2\xdc\xa3\xa0\x5f\ -\xd4\xc0\xe6\x0f\xa8\x65\x14\x7c\x2a\x8b\xb0\x28\x82\x45\xb6\xd9\ -\xa2\x2e\x79\xf0\xf9\xf8\xf0\xe4\xf0\x98\x36\xbe\x41\x2d\x96\xd1\ -\x2a\x4e\xe3\x32\xce\xd2\x22\x08\xf3\x1a\x45\x14\x3c\xfb\xb4\x0c\ -\xf3\x8f\x45\xf9\x90\x44\x87\x9f\x8a\xe2\xf0\x96\xfc\x5a\x1c\x16\ -\x8b\xa2\x78\x16\x6c\xb2\xe5\x2e\x89\x30\x98\x1e\xa5\x13\xfc\x70\ -\xf4\xed\x37\x47\x3f\x04\x6f\xe3\xbb\x75\x19\x5c\x63\x7c\xc1\x28\ -\xf8\xf0\x12\xd1\x41\xfe\xb8\x5e\x47\x51\xe9\xa1\x8e\x1a\x1e\xa6\ -\xf2\x3a\x8a\x82\x0f\x65\xb0\xcc\x16\xbb\x4d\x94\x96\x21\x66\x77\ -\x56\x49\x61\x14\xac\xcb\x72\x5b\xcc\x8e\x8e\xd0\xb7\x87\x9f\xca\ -\xc3\x38\x3b\xfa\x54\x8e\x4e\x8f\x2a\x86\x31\xce\xc3\x75\xb9\x49\ -\x1c\xdb\x8e\xf2\x68\x15\xe5\x51\xba\x88\xbc\x7a\x45\x5f\xc2\xcd\ -\x16\xcb\xb7\xea\x34\x88\x5c\x7f\x8b\x0a\x24\xbf\x28\x89\xb0\x08\ -\x8a\x4e\x76\x8d\x29\x24\xe0\xca\x38\xbd\x0b\xa2\xcf\x51\xfe\x80\ -\xec\x12\xfd\xba\x8e\x92\x6d\x11\x94\x59\xb0\x4b\xe3\xd5\x43\x50\ -\x71\x18\x84\x8b\x3c\x43\x56\xb8\x8c\x57\x44\x36\x65\x90\x6d\xa3\ -\x3c\x24\x7d\x8b\x87\xa2\x8c\x36\xc5\x10\x2c\xff\x10\xfc\x85\xc5\ -\xbf\x0d\x97\x4b\x84\x69\x16\x1c\x6f\xbf\xfc\x88\x3f\xd8\x84\xf9\ -\x5d\x9c\x36\x7f\xcf\xb3\x7c\x19\xe5\xf2\xdf\x23\x42\xfb\x2c\x48\ -\xb3\x34\xe2\x3f\x8e\x37\xe1\x1d\xff\x71\xb6\x2b\x93\x38\x45\x9f\ -\x1c\xa3\x3f\xff\x0f\xf3\x81\x44\x5d\x6c\xa3\x45\xbc\x8a\x17\x41\ -\x4e\x64\xbe\xca\xf2\x46\xee\x71\x5a\xc4\x68\x28\x7f\xb8\xc9\xb2\ -\xe4\x2a\xcc\x09\xa9\xcd\x1f\x15\xcd\x32\x89\x12\x0f\x14\xcd\x87\ -\x3f\xe2\xe5\x9d\xd7\x98\x80\x7f\x86\x90\x3e\xa5\x8d\xf0\x33\x0f\ -\x17\x1f\xef\xf2\x6c\x97\x2e\x47\x8b\x2c\xc9\x90\xb0\xf7\xc7\x17\ -\x93\x93\xc9\x4b\x59\x01\x41\x91\x25\xf1\x32\xd8\x9f\x9e\x9e\x9e\ -\x9c\x4d\x21\xde\x83\x80\x42\x78\x75\xfc\x6a\xfc\xea\x84\x7c\x54\ -\x20\xe9\x2e\xf0\xa0\x1e\x01\x98\x4e\xa6\x67\xcf\x2f\x26\x52\x3b\ -\x05\x08\x91\x69\x4d\xf4\x6c\x19\x17\xe1\x3c\x41\x6e\xd4\x81\x7a\ -\xfa\xd1\xc5\xcb\xcb\x8b\xab\x53\x3b\x39\x93\xb3\xe9\xf9\xd9\x95\ -\x86\x1c\x06\x44\x20\x67\x16\xa3\x31\x32\xab\x5a\x1b\x88\x62\x8c\ -\x02\x9d\xd7\x19\x1a\xa4\xb3\x3d\x2b\x8c\xf1\xe5\xf3\xc9\xd5\x15\ -\x6f\x63\xbf\x84\x71\xfa\x47\x9c\x2e\xb3\xfb\xce\x2e\xe3\x06\xc7\ -\xae\x70\xf9\xdf\x5d\x81\xc6\x01\x8e\x32\xc5\x36\x89\xcb\x12\xc5\ -\xa5\x3a\xea\x20\x07\xf9\x11\xc5\x35\x4c\xf7\x01\x1a\x62\x65\xf0\ -\x89\xb6\xf8\xf6\x1b\x4f\x27\xba\xbf\x40\x58\xb2\x4d\xfc\x27\xb2\ -\x9d\xd1\xa7\x0d\x62\xe2\x9e\x30\x31\x88\xad\x37\x32\x9a\x21\x35\ -\x6d\x43\xe4\xdc\xd0\x90\xd7\xc9\x98\x33\x6e\xc0\xf4\x39\xd3\x2a\ -\xb6\xe1\x42\x30\x7d\x36\x16\x26\x8d\x1f\x80\x91\x57\x0a\xd7\x92\ -\x70\x76\xfc\xfc\xe2\xfc\x4a\x4b\x82\x60\x04\x5a\x04\x79\xfc\x67\ -\x86\x82\x69\x52\x61\x41\x6a\x2b\xd7\xb3\xe0\x54\xf0\xb2\xa3\x32\ -\xdb\x52\x6a\xd9\x67\xf3\xac\x44\x9a\x69\x3e\xae\x5d\xea\x2e\x4f\ -\xbe\x7b\x36\x3b\x42\xb3\x8d\xdb\x78\x81\xa6\x23\x47\x78\x06\x72\ -\x94\x2f\x8e\x4a\xe4\x1c\xe7\x61\x7e\xcb\x70\xdf\x22\xd6\xc8\x24\ -\xe9\x70\x9b\xde\x3d\xfb\xde\x42\x28\x6d\x5c\x91\xb9\x8e\xf0\xf4\ -\x42\xa1\x33\x89\x56\xa5\x42\x68\x5e\x35\x6d\x4f\x67\x23\x23\x91\ -\x52\x3c\xae\xb0\xcb\xbf\x89\xb7\x5d\x9d\x37\x06\xd7\x69\x68\x60\ -\xaa\xcb\x78\x3b\xc8\xb8\xa0\x3c\x5a\x3d\x16\xe8\xd5\x91\x94\xde\ -\xac\x82\x87\x6c\x87\xc2\xe8\x06\x99\x33\x71\x11\x95\xb9\xe2\xc9\ -\x32\x9a\x43\x94\x0f\x07\x1c\x58\x34\xdd\xc8\xd0\xec\xe3\x3e\xcb\ -\x3f\xe2\xa9\x45\x96\x06\x95\x31\x14\x84\x98\xc6\xd2\x59\xec\x26\ -\x93\x22\x02\xb9\x1e\x58\x07\x24\x54\xaf\xe2\x2f\x78\xc6\x3c\xcf\ -\x50\x8f\x2f\x41\x2d\x9f\x1a\x86\x12\x8d\x1a\x18\x19\x1e\xad\x98\ -\x22\xdc\x7f\x7f\xfc\x7c\x8a\x66\x7e\x9b\xf0\x21\x48\x23\xe4\x6f\ -\xf1\x94\xa8\x88\x82\xdf\x7e\xbe\xba\x24\x90\x98\x19\x5c\xa3\xd9\ -\xe8\xae\xc0\xb1\xbf\x93\xbc\x3b\x9b\x41\x41\xe8\x40\xe6\x3b\x88\ -\x21\x34\x5c\xfe\xc5\x6b\x62\x0c\x46\x7c\x24\x96\xd7\xf1\x17\x34\ -\x6f\xbc\xde\x3e\x60\x5d\xef\x5f\x8c\x27\xc7\x07\xe4\x7f\x63\xaa\ -\x4a\xa6\xf4\x19\xdc\x75\x7f\x72\x7c\x7a\x10\xdc\xaf\x51\xf0\x0b\ -\x98\x03\xa8\xd0\x16\x41\x3d\x40\xb1\x91\xe0\xe0\x58\x34\x1a\x69\ -\x08\xad\xe2\xa6\x48\x6e\x6d\x38\x52\xcb\xc0\x6a\xe6\xcc\x9f\x82\ -\x9c\x03\x73\x09\xee\xa3\xde\x6c\x74\xb9\xc3\xb1\x24\x28\xf3\x30\ -\x45\x71\x05\x2f\x51\x1e\xb0\x55\xa2\xf5\x22\x5a\x2d\x46\x24\x0a\ -\x57\xdd\x6b\x3b\x46\x7e\xef\xe4\x18\xe2\xf6\x6d\x38\x8f\x6a\x67\ -\xea\xa9\xa9\x06\x77\xc9\x7b\xc2\x17\xeb\x68\xf1\xf1\x0a\xb1\xd1\ -\xcd\xd2\x3a\x0f\x81\x05\xa6\x03\x89\x73\x90\x11\xc0\x98\xf4\x98\ -\x52\xf2\x33\x5c\x3a\x15\x98\xd6\x3a\x65\xeb\x0e\xe6\xcd\x6a\xb5\ -\x57\x21\x77\x2a\xce\x18\x58\xcc\x9d\x72\x13\x07\x4a\xd2\x6c\x85\ -\xd6\xc5\x85\xc1\xd4\x19\xed\xbd\xcc\x8f\x25\xe4\x33\xe4\xa3\xd1\ -\xe8\x64\x13\x26\x30\x20\xd3\xa8\x3d\xa6\x7c\xd5\xb3\x8d\x31\xc8\ -\x4f\x03\x72\xb6\x4b\x89\x56\x29\xa9\xb6\x10\x4e\x4d\xe0\x96\xf5\ -\x93\xa6\x18\x46\x1c\xd5\xa4\xeb\x20\xb0\xb4\x22\xe2\xb6\xb6\xda\ -\xa2\xb5\x63\xc1\x44\x2c\x87\x2e\x7f\x46\x6e\x09\x5a\x2f\x76\x44\ -\x35\xb7\x40\x49\x01\x38\x60\x6d\xa7\x26\x77\x25\xb9\xa8\xc8\x45\ -\x41\x3d\xab\xc7\x57\x39\x1d\x55\xd3\x42\x31\xe8\xb7\x08\x05\x87\ -\x4d\x9c\x86\x28\x96\xfa\xa1\x13\xfa\xfa\xe2\x6a\xcb\xa3\x00\xa4\ -\x35\xa7\x46\x23\x10\x5b\x9a\x4c\x4a\x6c\x29\x18\x4d\x4b\x86\x00\ -\x4b\xc1\x41\xf4\x67\xe4\x80\xb7\x5f\x41\x10\xc5\x81\x60\x3b\x54\ -\x10\x65\x4c\x12\x01\xae\xd0\xca\x6a\x74\x5f\x47\x86\x79\x96\x2c\ -\x75\x33\x2c\x65\xc1\x3d\xca\xc3\x65\xbc\x2b\x94\x30\xa9\xac\x00\ -\x49\x2c\x3d\x83\x97\xaf\x7c\xe8\xa1\x84\xcd\x66\x65\x5c\x26\xf5\ -\x30\x29\x76\x73\xa4\xd0\x32\xcf\x92\x11\x5a\x07\x92\x0d\xbd\x0a\ -\xc4\x8f\xd2\xb7\xdb\xac\x20\x3b\xf0\x68\x86\x94\x6d\x03\x1c\xf9\ -\x48\x8b\x2a\x04\xca\x91\x5c\x0c\x8c\xf4\xd3\x7a\xa9\x2a\x37\x26\ -\xf4\x8f\x60\x4a\x5d\xe2\x2e\xb4\x8a\x6f\xa6\x97\xee\xa1\x19\xc0\ -\x2a\x87\xe6\x1e\x42\x9c\x34\xc6\x8d\x48\xd9\xa8\x35\xb7\xa2\x5e\ -\xc0\xdc\xea\x51\x62\xb5\x99\x84\xa1\x62\x35\x84\xb5\x27\xbd\xb9\ -\x6b\xcd\x45\x67\x2e\x1a\x7b\xc4\xe0\x6d\x42\x3f\x48\xf0\xc6\x41\ -\xe0\x37\xe4\xd6\xb2\xab\x1d\xf2\x4f\x69\x97\x38\xd0\x39\x08\x60\ -\xf7\x9a\xcd\x09\x1d\x83\xc4\x01\x9e\xcf\x9e\xd6\x53\x1e\xab\x27\ -\xc0\x64\xe4\xd5\x58\x65\x03\x1c\x99\xd6\x35\x16\xdf\xb6\xe3\xf1\ -\x83\x3f\x75\x81\xc7\x69\x8d\x49\x98\x9a\xf3\x2a\x68\xb5\x6a\x15\ -\x82\x1c\x9f\xac\x5c\x75\x59\x3a\xc2\x88\x7d\x57\x8f\xc4\xec\xb5\ -\xe1\xc8\x86\x83\x79\x37\x6b\x43\xea\xe2\xac\x0d\xcd\x7e\x4e\x15\ -\xa0\x27\x83\xa0\xe3\xb3\x12\xe5\xe7\xfd\x64\x94\x9a\x30\xa5\xc1\ -\x6a\x8e\x54\x6d\x05\xe0\xa5\x5f\x47\xed\x3a\xea\x76\x58\xcd\xb6\ -\xd0\x2b\xac\xd5\xae\x04\xe8\x43\xdc\x2f\x51\xba\xeb\xbc\x5b\xde\ -\x43\x88\xdb\x20\x3a\x86\xda\x2d\xa7\x3c\xea\xbc\x31\x74\x3a\x3e\ -\x91\x42\x93\x79\x83\xd9\xf5\xec\x5c\x3e\x09\xac\x08\x83\x82\x19\ -\x87\x4f\x3a\x87\xa6\x9d\xf8\x0d\x75\xed\xa6\x30\xc7\x11\xef\x9f\ -\x05\x18\xd2\x49\xb8\xd4\xc1\x0c\xdd\x9c\x6b\xe0\x2e\x81\x8a\x10\ -\x61\x14\xaa\x74\xb4\xc6\x05\x2a\x4a\x5a\x7e\x1e\x6b\xe6\x28\x52\ -\x8a\x08\x26\xb8\x87\x1c\xb6\x5e\xc6\xcb\x60\x83\x45\x34\x45\x58\ -\xde\x5a\x89\x72\x99\x3f\xc0\x09\xe5\xf3\xe9\x78\xfa\xba\xd5\x40\ -\x51\x52\x01\xd8\x4c\x44\x8f\x8e\x3b\x97\xd7\x64\xa8\x54\x90\xa1\ -\xa1\x04\xd1\xcc\xdb\x64\x30\xc1\xff\x90\x5f\xce\xf9\x83\xa1\x22\ -\xca\x3f\x47\x64\x0e\x17\x91\xa3\x25\xc6\x27\x3d\x6b\x15\x4f\x4f\ -\xf1\x40\xe7\x46\x15\x27\x63\x99\x40\x69\x9c\x02\x0a\x70\x15\xa4\ -\x3a\xd8\x9c\x7b\x2e\xe8\x12\x41\xdc\x3f\x19\x1f\x83\xb3\x41\x65\ -\xba\x28\xc0\x12\x27\xa4\x22\xc0\x73\x09\x9e\x32\xfd\x9c\x34\x32\ -\x47\x41\x11\x0d\x95\x45\xb2\x2b\xe2\xcf\x38\xe3\x92\x82\xfd\x29\ -\x20\xf1\x8f\x1c\xe9\x91\x51\xc5\x7d\xf7\x5d\x81\x73\x18\x2f\x89\ -\x62\xc8\xda\x12\x9b\x57\xf9\x8a\x42\xf9\xbe\xd6\x12\x82\x0e\x43\ -\x26\xf1\x35\xa8\xd6\x64\xed\x80\x83\xa2\x98\x09\xbc\xf4\x7e\xdc\ -\xe2\x88\x8d\x4d\xae\x5c\xdb\xd3\x59\x96\x6b\xfb\x47\xd9\xe0\x71\ -\x25\x66\xa8\xad\x1e\x33\xfe\x3e\x0f\x68\x9c\x30\x39\x2a\xd5\x4f\ -\xa5\x8f\xb8\x03\xe4\x46\xc8\x30\x07\x39\x66\xdc\x43\x1d\xe9\x78\ -\x60\x1d\xf4\x70\xc7\x87\x0e\x37\xb3\x81\x0f\x7c\x7c\xfa\x0c\x74\ -\xf4\xa3\xd0\xd0\xda\x17\x9b\x37\x2f\x1c\xd0\x68\xc5\xe2\xe3\x80\ -\xfd\x9d\xef\x30\xbb\x18\x2e\x74\x0d\xb2\x91\xa1\x47\xfc\x98\x7b\ -\x19\x56\x2a\x1c\x94\xed\xae\xea\xa7\xdb\xd4\xb0\xd3\xf4\x18\xfb\ -\x1a\x35\x19\xe4\x0c\x6f\x14\xe6\x79\x76\x2f\x5e\x03\x38\x05\x8f\ -\x00\xc7\xae\x79\xa9\x04\xe2\x2d\x81\xce\xf0\x02\x13\x53\x71\xe6\ -\xca\x16\x90\x97\xf3\x02\x4d\xf7\x17\xe5\x1b\x34\x07\xff\x77\x1c\ -\xb5\xcd\x02\xef\x9e\x9d\x85\xb3\xdd\x86\x3a\x58\x56\x98\x24\xf2\ -\x0f\x13\xe4\x7b\xb1\xe7\x05\x57\x7c\xc6\x5d\x95\x16\xa7\xd0\x95\ -\x29\x28\x94\x7c\x78\x8b\x0c\xee\xd5\x32\x2e\xa5\x5d\x06\x8d\x9a\ -\xae\x17\x79\x96\x24\x97\x79\x14\xb6\x52\x54\x67\x35\x85\x35\x1d\ -\x05\xa1\x03\x2d\x11\xc3\x41\x15\xc6\xb1\xab\x5d\x17\xaa\x37\x4d\ -\xbc\x72\x03\x90\x74\xab\x8c\xde\xd3\x0b\x39\xc1\x92\x5b\xd3\xd5\ -\x29\xca\x28\x52\x8f\xaa\x91\x85\x93\x2b\x49\xbf\xc9\x74\x5a\xf7\ -\xd3\x2c\xe9\x55\x5e\x24\xaf\x03\xa7\xd0\x91\xec\xe1\x6e\xda\xa6\ -\x3f\xc3\xe4\xfc\x36\xb4\xd1\xe3\x25\xff\xfc\x41\x89\xd3\xaf\x20\ -\x4f\x9a\xd0\x31\x58\x9e\x34\xe5\x52\xb9\x5e\xc1\xdc\xb5\x98\x8d\ -\x42\x6c\x90\x7c\xc8\x7e\x69\x6f\xe9\x56\x45\x70\xf4\x89\xb7\x2a\ -\xcc\xc3\x8e\x46\x16\x99\x74\x81\x6c\xd3\x0e\xb6\x9b\xeb\x6c\x88\ -\x9b\xad\xc3\x74\x99\x44\x8a\x10\xdd\x6e\xc2\x78\xc9\x0c\x0f\xf8\ -\x9a\xbf\x73\x47\x5a\x2c\x77\x73\xb8\x4b\x11\x94\x22\xf5\xb3\x5e\ -\xe8\x30\x6f\xe3\x4b\xfb\x69\x2a\x24\xab\x09\x38\xcb\xb6\xf1\x9a\ -\xcd\x46\x9a\x97\xa2\x29\x29\x83\x89\x56\xa4\xce\x4a\x46\x5b\xc9\ -\xa2\xc0\x32\x22\x13\x4c\xd9\x72\xb9\xad\x6a\xfe\x3f\x9e\x6c\x8f\ -\x69\xa0\x3a\x0f\xb5\xce\x07\x35\x09\x6b\x04\x9c\xfc\xb5\x92\xed\ -\xe6\xc2\x27\x5b\x51\x58\x9a\xb1\x94\x0f\x6f\xae\x9f\x9c\x59\x71\ -\xc0\x50\x95\x9e\xd4\xea\x3c\x69\xab\xd2\x65\x76\x9f\xf6\xa7\xd1\ -\xea\x1c\xa9\x07\x2e\x8d\x0a\x65\x8d\x5a\xa9\x13\x73\xfc\x64\x8c\ -\xa2\xc6\xf6\x31\xca\x29\xd5\x5f\xa1\x78\x7d\xd7\x9f\x42\x59\x3e\ -\x69\x57\x2e\x21\x85\x42\xcd\x5a\xa9\x14\x53\xf9\xd4\xac\x0e\x34\ -\x3e\x77\xdb\xfe\x94\x59\x66\xdb\x1e\x18\x34\x6a\xb2\xdb\xd0\xdc\ -\x6d\x9f\x86\xc7\xdd\xb6\xda\x39\xe1\x0c\x51\xe4\x0f\xfb\x0c\xa5\ -\x89\x9a\x8e\x20\xde\xf1\x03\xe0\x53\xf1\x68\xa1\xeb\xa6\x45\x7a\ -\xd8\xd8\x2b\x6e\xb1\x70\x75\xb4\x63\xdd\x48\x0d\x5a\x40\x87\x29\ -\x67\xb0\xdd\xe8\x26\x57\x97\xa3\x2f\x25\xd9\x91\xe8\xb6\xe4\xe9\ -\xba\x16\xa3\x55\x36\x46\x55\xc5\x80\x41\x8a\x88\x34\xbc\x3a\xac\ -\x73\xb4\xfb\x40\xea\x4a\xcb\x30\x1d\xae\x14\x48\xf1\xfa\x4d\x25\ -\x59\x2f\x5d\xa1\x07\xf8\xd2\xb5\x88\x1b\xab\xf8\x7d\x12\xc6\x69\ -\x77\x3d\x0f\xa2\x12\x91\xb6\x47\xd6\x8b\x80\xdc\x4f\x39\x62\xd7\ -\xae\x1a\xba\x8e\xff\x8c\x7e\xce\x3b\x17\x10\xe8\xbe\x21\x82\xe8\ -\xb8\xcb\x07\x2a\x20\xc0\x98\x54\x84\x24\x27\x76\x59\xf3\x2e\x6c\ -\xe1\xab\x2a\x0f\x72\x8b\x59\x51\xb3\x0e\xaf\xcb\x10\xef\xdf\x77\ -\xad\xb7\x33\xd4\xdd\x7a\x8e\xb6\xbf\xc0\x0d\x4a\x97\xad\x0d\x38\ -\x67\x50\xa8\x57\xf1\x35\x24\x5e\xd6\x55\x36\x06\xab\x57\xe1\x98\ -\x78\x59\x3b\x10\x9a\x75\x07\xa7\x5b\x32\x3d\xd0\x94\x2f\xf8\xca\ -\x1a\xcb\x9f\xe7\xcb\xba\xd4\xb4\x48\x7b\xa5\x5c\x81\x83\xe7\x13\ -\xe5\x8a\xbd\x4a\xa8\x08\x4b\xb7\x2f\x26\x6f\xd0\xb9\x56\x3a\xc1\ -\x5b\xde\xda\x22\x27\x0a\x56\xb8\x10\x4b\x3b\xa4\x9a\x0a\x30\x0c\ -\xa5\xb5\x4e\x8d\x37\x5a\x7b\x55\x17\x08\x7b\x4f\x3c\x5b\x4b\xdf\ -\x10\xd4\x24\xb9\x6b\xff\x53\x79\x4b\xbb\xa1\x58\x73\x3b\x07\xaf\ -\xc9\x68\xcb\x10\xe9\x02\x66\x9b\x7d\x16\xf5\x70\x6a\x1b\xa7\x1d\ -\xee\xa8\x0e\x7b\x92\x54\xd3\xe6\x30\x9f\x30\x7b\x53\xb8\x92\xcd\ -\x4d\x55\xb7\x11\x0f\xdd\xf1\xf1\xc9\x41\x30\x1e\x8f\xc5\xd3\x24\ -\xf1\x92\xa5\x53\x0f\xb9\x90\x92\x78\x3e\x2c\x5f\x62\x92\xae\x88\ -\xea\x4f\xbb\xb8\xad\x64\x7c\xf2\x5c\x1f\x6d\x2d\xe9\x81\xd6\xf8\ -\xf8\x82\xcb\x07\x94\xc4\x87\xd7\x49\xb0\xc5\x51\x41\x0a\xb9\xa3\ -\x7c\xb1\x2b\x75\xb5\x57\x91\x68\x5c\x28\x72\x7b\x72\x35\x43\xf5\ -\xe1\xb8\x69\x0f\x1f\x70\xda\x6a\x23\x04\x9c\xc0\x62\x12\x3a\x56\ -\x41\x40\x0d\xd8\xe1\x86\x66\xc9\x2b\xa5\x71\x8f\xc6\xc0\xe1\x2f\ -\x15\x26\x5b\x75\x1e\x28\x63\x88\x5b\x91\xd2\x08\x61\x6c\x94\xad\ -\x56\x6e\x79\x2a\x2e\x7b\x16\x52\xb2\xeb\xb9\x0b\x0b\xfc\xd6\xbc\ -\xf7\x56\x02\x0c\x9b\x2c\xba\x1f\xcd\xda\x2a\x8d\xb5\x32\x38\x32\ -\xb4\x9f\xd2\xda\xaa\x7b\xe0\x46\x53\x6b\x76\x30\x20\x3b\xe2\xf6\ -\x37\x4c\xe6\xc6\x35\xf3\x34\x38\xdb\x26\xb6\x8f\xc9\x09\x5b\x3d\ -\x9e\x46\x27\x6c\x2d\xc3\xf0\xf9\x33\x26\xc3\xed\x17\xfb\x79\x7f\ -\x0d\xcf\x6b\x11\x29\x77\xee\xb8\x8c\xec\x35\x96\x22\x78\x2f\xdf\ -\x5c\xbf\x7f\x7b\xf9\x3f\xd7\x5d\x01\x53\x78\xbd\x10\xc7\xc1\xab\ -\xab\x57\x75\x86\xd7\x79\x19\xb3\xca\xc3\xcd\x20\x15\x94\xf9\xfa\ -\x5c\xbd\xd4\x5d\x15\x5d\x89\x61\x92\x58\x19\x28\x41\xef\x75\x85\ -\xd9\xed\xde\x8e\x9a\xfc\x82\xb7\x52\xae\xd0\x98\x2d\xa2\x4e\xab\ -\xd2\xbf\x4b\xca\x13\xcf\xee\x10\x93\x54\xc3\x81\x3b\x87\xba\x95\ -\x66\xcd\x34\x28\x57\xd7\xad\x34\xd0\xe3\x0b\xfe\xb3\x3d\xe8\x43\ -\xea\x1d\xa5\x8f\xc1\x44\x53\xed\x9e\x5f\x55\x5e\x27\xdc\xae\xe3\ -\x45\xd1\x21\x03\x12\xff\x0c\x62\x18\x02\x6d\x8f\x6c\x19\x3c\xee\ -\x27\x33\x0d\x81\x88\xa6\x46\x08\xf7\xe1\x1e\xf8\x29\x67\x1d\xc2\ -\xe7\xfe\xe6\xf1\x22\x4c\xa2\x14\x4d\x24\x3a\x6e\x10\x0e\x62\x1e\ -\x12\x6d\x56\xa6\x8c\xa2\x16\x81\xf5\x50\x08\x90\xc4\xe4\x17\x2f\ -\xdf\xed\x36\xf3\x6e\x6e\x7c\x20\xe9\x35\xb4\x79\xb0\x28\x87\x44\ -\x0a\xa3\x27\x79\xbd\xc7\x2f\x45\x20\x13\xed\xb8\x1d\xdb\x39\xf0\ -\x6d\x6b\x3a\x86\xda\x8e\xe5\xf9\x7c\x34\xbf\x16\x04\x25\x8a\x14\ -\xa3\x30\x89\xef\xd0\x64\x67\x81\x16\x8e\x64\x51\x58\x1f\xe1\x34\ -\x14\x3d\x81\xb7\x73\x26\x6d\xb6\x58\xef\xd2\x8f\x2e\x69\x70\x5a\ -\x5a\xc1\xd1\xaf\xe2\xb0\x4b\x81\xab\x77\xef\xe5\xd5\x07\x98\xfc\ -\x5f\xfd\x7e\x73\xf3\xeb\xbb\xce\x6b\x93\xe1\x16\x27\xef\x77\xc5\ -\xba\x7b\xf9\xa6\x1e\x06\x36\xa2\x63\xc0\xf2\x4d\x1c\x9b\x3a\xab\ -\x69\x35\x70\x95\x25\x8b\x63\xd9\xa1\x86\x1e\xbb\x39\xb7\x1a\xb6\ -\x60\xdd\x7e\x0e\xab\x78\xb5\xcb\x21\x91\xd6\x9f\x75\x1d\x4e\x3b\ -\xc7\x40\x4d\x02\x6f\x8e\x3d\xe8\x31\x6c\x68\x30\x4a\x94\xce\xe6\ -\xb4\xdf\xd3\xe9\xd9\xf9\xf3\x4b\x53\x84\xe6\x40\xd9\xca\x0c\xe8\ -\x89\x70\xa1\xdc\x85\x82\x19\xae\x95\x31\x92\xaa\x0d\x00\x1b\x96\ -\xb5\x8c\xbd\x76\x2c\xd5\xd2\x95\x2f\xe3\x30\xc9\xee\x2a\xd4\xa4\ -\xc6\xb3\x3c\x3a\x71\x19\xfe\xa2\xd8\x45\x38\x48\x4c\xf1\x75\x96\ -\xf3\x60\x14\x5c\xe3\xdc\x9b\x30\x09\x16\x61\x11\x05\xd9\x4a\xe8\ -\x55\xbf\x70\xb3\x24\x80\x8b\xaa\x5e\x79\x5d\x61\xfc\xf7\x37\xf5\ -\x11\x06\x9f\xae\x2e\x55\x2c\x69\x8e\xb2\x9e\xd6\x09\x92\x43\xb4\ -\xe1\x9c\x20\xc7\xe6\x13\x3b\xc1\xfa\xb4\x29\xe2\x8c\xa8\x40\x0a\ -\x4b\xb2\x7b\xf2\x22\xd8\x0e\x8f\x86\x2c\x4d\x1e\xe8\x2b\x2d\x2f\ -\xa3\x24\x7c\x88\x96\xef\xb3\xed\x6e\x8b\x9f\x02\x8b\x9a\xda\x13\ -\x1e\x50\x48\x25\x1d\xc2\xbf\x1d\x50\x0d\x27\x2e\x54\x30\x6f\xd2\ -\xa2\x0c\xd3\xb2\x82\x81\x0c\x0d\x26\x4e\x3e\x24\x7d\x4c\x3f\xcf\ -\x61\x7d\x34\x3f\xaf\xe2\x7c\x5a\x3f\x0f\xd0\xd3\xd5\x65\x03\x20\ -\x3d\x5d\x37\x00\xa1\x93\x0b\xe7\xe0\xf5\xc8\x5c\x7b\xa6\x7a\x62\ -\xe6\x3f\x5b\x3c\x96\x7e\x41\x43\xe9\xa7\x67\xc7\xcf\xfe\x97\x05\ -\x85\x5f\xf1\x28\x5c\xc9\x43\x4e\x3c\xa1\x16\x5e\xd0\x31\x01\x1e\ -\x43\x80\x65\x17\x01\xc3\x3e\x76\x01\x5e\x07\x55\xe1\xb0\x10\x9a\ -\x0a\xba\x01\x80\x8e\x80\xe4\x87\xe2\x1c\x8e\x05\xf9\xa3\x3c\x13\ -\xfa\x09\x24\x1c\xc1\xf1\x79\x48\x1d\x90\x84\x26\x5d\x4c\x19\xec\ -\xf2\xe1\xa2\x63\xa1\x51\x0d\x6e\xd7\x73\x34\x33\x10\xc8\x9d\xf8\ -\x03\x93\x26\x5b\x9d\x6e\xa1\x80\x27\x95\x41\x40\x8e\x60\x8f\x69\ -\xb8\x25\xb5\x95\x50\x70\x0a\x83\x62\x1d\xaf\x4a\x7e\x8e\x44\x90\ -\xd7\x1a\xad\x8c\x68\xc4\x65\x85\x5c\x93\xe6\x71\x89\x7a\xce\xd1\ -\xbf\x60\x70\xab\x78\xe2\x0a\x09\xf4\xcf\x8f\x09\x67\xbb\x43\x57\ -\x5d\x61\xfb\x17\xd9\x66\x13\xa6\xcb\xb7\x71\xfa\xb1\xcb\xac\x70\ -\x98\xad\x55\x85\x36\x8d\x97\xd6\x95\x21\xec\xba\x55\x65\x79\xdc\ -\xb2\xde\xb3\x95\xa9\xb4\xce\x05\x64\x72\xb5\x5b\x91\xbd\x8a\x13\ -\x2f\x34\xde\xbd\xff\xfd\xe6\x1a\xad\x2f\xde\xfd\x1a\xbc\x7e\xf3\ -\xea\xed\xcb\x96\x9b\x35\x83\xed\xd0\xbc\xc0\x55\x28\xbe\x82\x67\ -\x16\x06\xad\x86\xc1\x98\xd4\xb9\x53\xfb\xb5\x68\xd7\x17\x39\xbd\ -\x52\xd6\x90\x02\x84\x6f\x82\x9f\x82\x93\xb3\x1f\x83\x69\xf0\xcf\ -\x60\x7c\xf6\xc3\x24\xc0\xcf\xfc\xb2\xfb\xf9\x01\x4e\x4c\x6f\x16\ -\x14\xd5\x3b\xca\x24\x89\x0d\x97\x40\x64\xc5\x19\x4e\x2e\x9a\x36\ -\x75\x66\x2d\xc9\xb6\xdb\x6f\xd2\xed\xf8\xfb\xbf\xe3\xc3\xd3\x68\ -\x23\x13\xc3\x32\xf7\xf0\xa3\xca\x72\xba\xdc\xfe\xf8\x64\xd2\xa0\ -\x80\x52\xf7\x2c\x5d\xb8\xa5\xf2\xf3\x53\x8a\x44\xed\x72\xcc\x31\ -\xf2\x2e\x8a\x96\xd5\x77\x75\x59\x8a\x26\xbe\x8d\x44\x0c\xcc\x43\ -\x54\x0a\xd7\x14\x42\xf1\x32\x81\x3a\x73\xc9\xb8\x1f\xee\x66\x1e\ -\x36\xe2\x2c\xd3\x6c\xfb\xc1\x8c\x01\x74\x97\xbc\x1a\x13\x5c\x56\ -\x53\x06\x00\x2c\x15\x5b\xa0\x50\x7a\x79\x6e\x8b\xc2\xf2\x9a\x27\ -\xb1\x5e\x5e\x29\x4a\xac\x17\x8d\x87\x6d\xb4\x6d\xaf\xff\xee\x68\ -\x76\x72\x2c\x33\x11\xa3\x89\x7b\x7a\x10\x9a\x06\x1d\x86\x20\x5f\ -\x8d\xaa\x8d\xad\x70\xa5\x61\x9b\xa7\x03\x99\xb7\x3b\x9f\x1c\xe0\ -\x7f\x4f\x03\x34\x1f\x08\x7e\xf9\x0d\xff\x7e\x4e\xbd\xc6\x3f\xc4\ -\xed\x89\xe6\x07\xbe\xb4\x50\xfd\x10\xec\xf4\x8f\x7f\x48\xa3\xa6\ -\xf9\x51\x53\x7c\x64\x91\x31\x70\xf4\x57\x50\x34\xb8\x0e\x6c\x2b\ -\xa9\x2c\xf3\x6c\x3b\xc2\xd3\xcc\xf6\xbb\xa9\x62\xb6\x31\xbc\x16\ -\x32\xac\xfa\x14\x8a\x58\x92\xe2\x23\xa5\x49\x42\xa8\xd1\x10\x3d\ -\x08\xe0\x6f\xd8\xab\x56\xd0\x97\x9c\x3f\x68\x9b\x56\x49\xae\x55\ -\x21\x11\x75\x3d\xf5\x1f\xf5\x71\x87\x8d\xd0\x31\xcc\xed\x2c\x02\ -\x5a\xeb\xc2\x81\x12\x3b\x55\x07\xdb\x7b\x21\x75\xb3\x19\x02\x83\ -\x14\x65\xbc\x18\x6c\xb9\xea\xc5\x7d\x4b\xad\x68\x0a\xae\x26\x8c\ -\x47\xc3\x12\x3d\xfa\xcb\xc4\xee\xd4\xd4\x36\xdc\x81\x18\xe5\xea\ -\xb3\x39\x9a\x3f\x3e\x39\x26\xbb\x60\x07\xe7\x22\x10\xa7\xbb\xe0\ -\xee\x5c\xf5\xa0\x72\x80\xa2\x16\x7c\x59\x4b\x36\xc1\x8f\xdc\x18\ -\x75\x45\xbd\xa1\xec\x1d\x29\x93\xa3\x73\xb5\xa6\x83\x89\x53\xc7\ -\x52\x4e\x56\xf9\x4b\x73\x1e\x3d\x78\xbf\x3a\x42\x22\x18\x83\xcd\ -\xf7\x2d\xc7\x63\x22\x49\x4f\x29\x9a\x6b\x36\x75\x94\x61\xab\x4a\ -\x4c\x24\x17\x8d\x56\x5b\xec\xe6\xfc\x3b\x87\x24\xbc\x8f\x1a\x21\ -\x3a\x86\x49\x6a\x13\x4a\x4a\x9a\x17\x14\xc6\xeb\x69\x0d\x24\x3c\ -\xbf\x74\xbd\xa7\xe6\xd7\xdb\xe7\x36\x1b\x91\xed\xac\xd2\xae\x83\ -\x79\x6b\x36\x2f\x74\x69\x7c\x35\xb5\x7d\xac\xc7\x18\xac\xae\x97\ -\x49\x18\x20\x2f\x57\xc1\x7a\xe9\x96\xb9\xa6\x5c\x31\x35\xfd\xf5\ -\x26\x9c\xff\x11\x77\xba\x19\x4f\x7e\xba\x1f\xd9\x87\xf3\xaa\x16\ -\xc8\x08\x79\x01\xf2\xe7\x60\x37\xc5\x31\xc7\x86\x0b\xf7\xc6\x25\ -\xaf\x7c\x3b\x9b\xc1\x12\x9e\x61\xe3\x36\xa4\xce\xe9\xde\x8e\x29\ -\x3f\x9e\x42\x99\xcd\xb6\x61\x1a\x69\x2d\xc1\xa1\xa4\xa1\x34\x05\ -\x60\x84\x2c\xb3\x1d\x32\xfb\xba\x1b\x4d\xf3\x20\xc8\xee\xe3\x72\ -\x1d\x6c\x1f\x3e\x95\xa7\xf0\x1b\xf4\x20\x89\x76\xe3\x33\x4f\x15\ -\xc5\x08\x50\xdb\x61\x0f\x25\x0a\xfe\x66\x76\x88\x38\x46\xcb\xb4\ -\x97\xd9\xe2\x23\xb5\xa2\x5a\x0c\x44\xaa\x38\x49\x77\x8b\x82\xe1\ -\xc3\x68\x99\x87\xf7\x57\x61\x11\x49\x77\x0b\x6d\xda\xd7\xd6\x92\ -\x60\x67\x59\x95\x83\x26\x5b\x93\x74\xb7\x01\x67\x66\x54\x5b\xb4\ -\xf3\x07\xfc\x4d\x30\x62\x1b\x96\xf8\xa4\x0b\xbb\x7b\xee\xe4\x8a\ -\x90\x3b\x9b\x2d\x92\xac\x88\xea\x73\x3d\x90\x23\xb1\x89\x68\xe1\ -\xe2\x75\xc8\x63\x91\x74\xca\x9b\x63\x0d\x10\x82\x45\xbe\x60\x0f\ -\x50\xc0\xd6\xc8\x36\x52\x7d\x4e\xc4\x78\x1a\xc0\x9a\xe5\x20\x82\ -\x3a\x4b\xc0\x85\x16\xaf\x97\x08\x04\x6a\xea\x9e\x1a\x7a\x90\x95\ -\x6b\xd0\xa3\x6f\x98\x4b\xdb\x63\x83\x1e\x6f\x41\xb1\x48\xea\x67\ -\xf6\x04\x12\x03\xd4\x65\x00\x29\x2c\xcc\xf0\x3c\x87\x82\xe6\xef\ -\xba\x6a\x18\x83\xdb\xf3\xb6\xc9\xa6\x3f\x27\x8d\xeb\xb2\x24\x45\ -\xbb\x84\x0c\x46\x40\x0d\xde\x87\x66\x5d\x17\x81\x6c\x32\xe1\x1b\ -\x88\x66\xe2\x32\x7c\x28\x86\x3b\x08\xf4\xd6\x33\xc2\x81\x28\xae\ -\xa0\xfb\x90\xac\xe9\x21\xd0\x5c\xb9\xce\x81\x48\xc6\x0a\xdc\xf3\ -\x35\x65\xb5\x83\xcd\x96\x2d\x8f\xd1\x5a\x6b\x4a\x03\x86\xe9\x45\ -\xb5\xb6\x8f\xd1\x9a\xfb\xa4\x9a\x68\xd1\x8b\x66\x4d\x0f\x8b\x3d\ -\xf7\x49\x73\x05\xdd\x8b\x68\x5d\x17\xb3\x45\xf7\x49\xb4\x60\xa0\ -\xae\x86\x0c\xda\xef\x04\x24\x50\x7d\xee\xde\x6e\xa2\x1e\x96\xa9\ -\x1a\xa4\x91\x0c\x71\xd9\x6c\x33\x3b\x67\x6b\x03\xd4\x65\x24\x03\ -\xca\x26\xd3\x5b\x85\xbb\xfd\x40\xc6\x6e\x24\x84\x7f\xd7\x19\xb4\ -\x0d\xb3\x45\xb8\xac\x32\xc0\x17\xa4\xbd\x36\x22\xc0\xed\x12\xdd\ -\x46\x88\x54\x69\xc7\xec\x67\x1d\x8a\x86\x48\xbb\x21\xf8\xfb\xea\ -\x51\x19\xcd\x82\x11\x9c\xc4\x38\xce\x75\x5c\xb2\x5b\x0d\x13\xa0\ -\xd3\x8b\xcb\x57\x17\xc3\x31\xd3\x78\x29\xd3\x1c\x5d\xd3\xda\xbe\ -\x8b\x62\x8c\x87\x4d\x23\xb6\x72\x2e\xb6\x0f\xb8\x35\x5a\x2f\x1f\ -\x55\xbf\xee\x5f\x3c\x3f\x3b\x23\x53\xe0\xfd\xc9\xf4\x04\xdc\xf1\ -\x3a\x81\x0d\xed\xc4\xe8\x97\xac\xde\xc8\x18\x14\xcd\xcf\xd3\x3e\ -\xdd\x38\x31\x94\xc1\x99\x82\x4d\x20\x43\x01\x86\x9b\x75\x32\xed\ -\x3e\x87\xf6\x18\x0e\xca\xc4\x5a\x19\x0b\xdd\x18\x75\x98\x56\xd9\ -\x06\x05\xdc\xc1\x63\x5c\x28\xd3\xad\xa7\x19\x14\xb8\x93\x25\x30\ -\x7a\x84\x05\xd0\x56\xe1\x31\x20\x04\x4d\xc9\xda\xe5\x21\x20\xde\ -\xca\x72\x76\x88\x26\x23\xe1\x53\xd6\x74\xa6\x2e\x2c\xa9\x5c\x97\ -\x5e\x1e\x66\x0e\xac\xc7\xa8\xa1\x5b\xa7\xd0\x36\xfb\x84\x9a\x7b\ -\x58\x27\x30\xb5\x06\xec\x73\x19\xaf\x56\x11\xa9\x1c\x36\x8f\xd6\ -\xe1\xe7\x38\xcb\x71\xd5\x4d\x96\x15\x28\xcc\x8e\xe4\xd7\xb8\xeb\ -\x8f\x85\x92\x5b\xca\x5c\xc8\x36\x57\xfa\xaa\x4d\x13\x76\xb1\xae\ -\x6e\xd8\x66\x9c\xe2\xe2\xd9\x79\x95\xed\x61\x9e\xea\xd2\x5b\x6f\ -\x9d\xf2\xca\xc7\x66\x9e\x60\x7b\x0f\xfb\x54\x17\x51\x6d\xcd\xb3\ -\x82\x24\x5b\x27\xff\x29\xcf\x2d\x7f\xf9\x12\xde\x53\x56\xae\x2d\ -\x72\xa7\x14\x27\x67\x0e\x05\x69\xdd\x1e\x1e\x04\xd0\x19\xb7\x38\ -\xa1\x86\xf6\xd1\x63\x43\x65\xd0\xb3\xbe\xb9\xf3\x1d\x14\x15\x0e\ -\x71\x6b\x75\x86\x55\x94\xea\x97\xe3\xb6\x4e\x3e\x89\x59\xc2\xbb\ -\x1b\x4e\x94\x19\x77\x0a\xac\xbd\x7c\x69\xd3\x3d\x99\x09\xa1\xe3\ -\x1e\xd0\xf4\x90\x1f\xd0\xcb\x87\x48\xa0\xe4\xad\x15\x8d\x87\x08\ -\xa1\x6e\xde\xe4\x69\x84\x88\x8f\xcc\x2a\xfc\x9d\xcf\x6e\x07\x39\ -\xdc\xe2\x64\x43\x38\x66\xd7\xcb\x34\xc7\x99\xfd\xbf\xfd\x58\xc6\ -\x65\x12\xcd\xc3\x7c\x54\x9d\xa0\x60\x01\x9b\xaa\x35\x37\x39\xad\ -\x5c\x6a\x26\x83\x91\x66\xf9\x26\x4c\xda\x00\xa9\x6f\xea\x33\x71\ -\xa0\x28\x83\x81\x32\x0f\x7c\x55\xdd\x1c\x23\x37\x1e\xf0\xf9\x5a\ -\xf5\x2d\xbe\x04\x21\x9d\xc6\xd2\xe9\x33\xab\x38\x2e\x3f\x7c\xd0\ -\x64\x57\x5b\xfd\x26\x4f\x8e\x7a\x2e\x87\x99\x1a\x61\x82\x4c\xf7\ -\x05\x4d\x05\xfd\x39\x02\x6a\x4b\xd7\x5d\xa2\x32\x1e\xfd\x55\x7f\ -\x76\x38\xf8\xd3\xb1\xd9\xeb\x99\x9e\x16\x49\xdf\x87\x75\x3c\xa2\ -\x55\x92\x85\xe5\xdf\x5f\x69\x08\x19\x62\xca\x91\xcf\x16\x5a\xab\ -\xe0\x5b\xd5\x26\x60\x69\xa3\xb6\x1a\x0f\xa8\x37\x92\xdc\x90\x47\ -\x11\x7d\x11\xb8\x28\xab\xdf\x6e\xb0\x57\xf7\xab\x49\xd8\x3d\xb9\ -\x01\xd1\xf1\x19\xa1\xec\x9c\xe0\x56\x94\x3d\x80\x29\xb1\x04\x2a\ -\x38\x43\xa4\x57\xd4\x32\x9f\xcd\x91\x19\x2f\xd6\x42\x3d\x49\xe9\ -\x2b\x4d\x16\x63\x0b\x3f\xaf\x40\x0e\x0b\x34\x28\xe7\x28\xf4\xdd\ -\x15\xb3\xbd\x70\xf9\xdf\x2c\x4e\x8b\x51\x73\xcf\xa3\x8e\x5d\x36\ -\x33\xab\xa0\xdd\xe2\x08\x5a\x21\xe4\xef\x9d\x9b\x50\x76\xc5\xb8\ -\xc9\x72\x3b\xc6\x3d\x8c\x72\xb1\x8e\x93\x25\x92\x48\xf5\x57\x6f\ -\x04\x44\xe9\xd2\x89\x63\x0d\x7a\xe2\x4f\x21\x95\x57\x5f\x88\x5d\ -\xf9\x9e\x10\xad\xce\x0f\xc7\xd7\xb4\x57\x38\x2c\x16\x92\x6d\x6b\ -\xcc\x30\x07\x00\xe9\x6a\x8f\xbe\x09\xc7\x18\x1c\x0c\xdb\x28\xf3\ -\xa6\xd0\xab\xa7\xe4\x7d\xdc\xbc\x20\x68\x38\xe3\xc6\x4f\xdc\x5a\ -\xaa\xcd\x42\x6f\x41\x33\x06\x68\xa6\x98\xbb\x4d\x56\xdf\xee\x3a\ -\x20\xe9\x9f\x55\x00\xd1\x7c\xcd\xa2\x8a\xe6\xfb\x17\x59\xb2\xdb\ -\xa4\x9a\x06\x6e\x0c\x90\xc6\xf3\xec\xcb\x6d\xdd\xcb\x9d\x7e\x55\ -\xba\x40\x1b\x22\x13\x4b\x1b\xba\x9f\x60\x96\x47\x8d\xce\xd2\xa8\ -\xc2\x67\x69\xc4\x21\x34\x49\xb8\xc1\x68\x6c\xc5\x50\x1a\x5b\x71\ -\x38\x8d\x5a\x6b\x90\x9a\x9b\x31\xac\xe6\x66\x5e\xf3\x1f\xd9\x16\ -\x9c\x2d\x7a\x97\x5a\x6c\x5a\x68\x00\xca\x49\x68\x01\xf3\xc4\x9a\ -\x78\x72\xc3\xfa\xf9\x70\x62\xb4\xee\xa6\x95\xc9\xbe\x9b\x56\x16\ -\x0b\x97\x91\x5a\x9b\x19\xad\x1c\x44\x6b\x96\xb9\xc5\xd2\x01\xc4\ -\x96\x76\x56\x6b\x07\x50\xdb\x1a\x5a\x2c\x5e\x41\xde\xd6\x4a\x9c\ -\xad\x1e\xfd\x16\xa1\xd5\xfe\x26\xc6\x77\x60\x75\xda\x50\x1a\x81\ -\x92\x53\x5a\xc1\x3c\x0a\xcd\x3c\xf9\x13\xfa\xfa\x72\x67\x1c\x0d\ -\x62\x4b\xd3\x88\x10\x5b\x5a\x46\x05\x44\x80\x53\x53\xe3\xe8\xd0\ -\x92\x60\xd7\x8b\x65\x94\x68\x88\x70\x68\x6b\x1d\x2d\x1a\x32\x5c\ -\x1a\x5b\x46\x0d\x48\x48\x17\xcb\x32\x8e\x1e\x5e\x29\x82\x6c\x44\ -\x02\x5d\xae\xf3\x78\x17\xee\xb9\xcb\xe3\x25\x5e\x72\x19\xde\x10\ -\x04\x4f\xef\xa9\x19\xb3\xad\x62\xde\xb0\xf8\x0f\x1b\x45\xf3\x9f\ -\x72\x62\xef\xe1\xb6\x12\xa3\x86\xad\x7f\x79\x6a\xf8\x0f\x1b\x6a\ -\xf8\x4f\x39\x6a\xba\x5f\x38\x6a\xa8\x51\x47\x1c\x60\xfe\x90\x25\ -\xfa\xbd\xa9\xdb\x78\x14\x5c\x7e\x00\x76\x1f\xd2\x37\xfc\xe8\x93\ -\xbe\x12\x06\x04\xf7\x9d\x5d\x20\x20\x39\xec\x8c\x31\x5c\x94\xf1\ -\x67\x39\x1e\x68\x5a\xc8\xe4\x01\x4d\x14\x32\xa5\x36\x5d\xc9\xdd\ -\xb3\xd3\xbb\xe7\x40\xf0\x9e\x0b\xc5\x7b\x3c\xc9\x50\x71\x2d\x80\ -\x8b\xe7\xd3\xf1\xf4\xb5\x8e\x0b\xf9\x24\x58\x65\x02\x68\x21\xf3\ -\x00\x34\x51\x58\x00\x8f\x90\xd9\x31\xc8\xb1\xce\xe9\x38\x30\x84\ -\x89\x79\x91\xe5\x69\x94\xd3\x93\xa6\xa2\xba\xb0\xe6\xeb\x05\x85\ -\x17\xd6\x0c\x55\x81\xc4\x22\xbf\xff\x8a\x42\xf4\x6d\xc7\xd7\x54\ -\x7a\xd8\xcc\x5c\x13\x3a\x06\xdb\x3f\xe4\xd8\xb4\x9e\x46\x73\x7b\ -\xe3\x06\xb1\x4a\x7b\xe4\xe2\x06\xba\xb6\xae\x64\x43\x87\x57\xe5\ -\x5b\xbb\x9e\x15\xf0\x56\x33\xf2\xaa\x73\x57\xb1\xc5\xbf\x7a\x80\ -\xcf\x84\xc9\x87\xa4\x2a\x4d\x7d\x56\xc1\xa7\x7f\x01\xb4\xcc\x94\ -\xaa\x02\x42\xd2\x8b\x70\xf8\xc0\x52\x5e\xc4\x4f\x7d\x2e\x21\x2b\ -\x35\x60\xa4\x8c\x76\x0b\x85\xb3\xd9\x2a\xce\x0b\x9c\x1c\x64\x6d\ -\x88\x0b\x21\x8f\x32\xf1\xb2\xa7\xb5\x04\x8d\x0d\xaa\x68\x20\x9a\ -\x19\x01\x08\x44\xac\x38\x30\xa8\x8c\xe5\x17\x15\x5d\x44\xcc\x6a\ -\x02\x98\x05\xdc\x34\x03\xc5\xab\x7d\xcb\xd1\x05\xb3\xb7\x6c\xe5\ -\x2a\x41\xe4\xea\x7c\x56\x44\x41\x11\x95\x25\xd9\xaa\xfd\xae\xa2\ -\xeb\x88\x64\xd1\x1c\x55\xc9\x35\x47\xf2\xb8\xfb\x1e\x53\x8b\x22\ -\xe0\x7c\x77\xd7\x5c\xa0\xe3\x47\x74\x85\xa2\xe9\x46\xb2\x30\xb9\ -\x0a\x7a\x6e\x7e\x82\xed\x11\x5b\x72\x7c\x3c\x53\xd4\x5a\xbf\xdc\ -\xc8\x4b\x92\xbe\x43\xea\xe3\xf7\x9e\x94\x1f\xf9\xf9\x53\x56\x1b\ -\xff\xe9\xab\x4f\x92\xd2\xf8\x03\x15\x9f\xa4\x2c\xf2\x3e\x44\x2e\ -\x47\xa3\xfe\xad\x1f\x90\x35\x3c\x69\xe1\xa1\x05\x3c\xd1\x27\x6c\ -\xd5\x80\x9a\xeb\xac\xc3\x3c\x47\xd4\xf1\x22\x04\x47\xa5\x9b\xbb\ -\x11\x7a\x58\x97\x67\x6a\x89\x7a\xe0\x4a\x95\x41\x72\xda\x0b\x91\ -\x0e\x03\x12\x42\x25\x55\x13\x12\x50\xc9\x57\x8d\x5a\xa2\xd0\x18\ -\x94\x88\xc2\x63\x99\x0d\x80\x51\x32\x07\x9b\x5e\xda\x2b\x27\x13\ -\xfd\x8a\xb5\x1e\x42\x1f\xae\x49\x31\xd4\xcb\x3c\x0a\x59\x69\x09\ -\xa1\xc4\x84\x7d\x78\xd9\xd8\xc0\x4e\xe9\x35\x7e\xca\xf4\xeb\x79\ -\x52\x55\x03\xa3\xfa\xba\xea\x36\xc2\x45\x11\x9c\x5a\x2e\xa3\x32\ -\x8c\x93\xa2\x69\x5b\x94\x48\x24\x58\x5b\xab\x24\xbb\x3f\x5c\x64\ -\x9b\xa3\x4f\xbb\xa8\xc0\x61\xbe\x38\x1a\x4f\x4f\xcf\xc7\xd3\x8b\ -\x73\x0c\x86\x23\x79\x95\xe5\xa3\x35\xd9\x03\xfa\xdc\xec\x04\x0d\ -\xe1\x3b\x91\x32\xbe\x5b\x66\xe5\xf7\xc1\x61\xad\x93\xba\xd0\xe4\ -\x74\x8c\xeb\xd9\x4e\xce\xc8\xbf\xd5\xbd\x0a\xda\x82\x37\x39\xd8\ -\xdf\xe8\x1c\x18\xae\x71\x99\x05\x44\x54\xcd\x94\xe2\x5f\xb8\xb0\ -\x0c\xf4\x27\x31\x96\x1a\xe9\x7f\x48\xa7\xeb\x75\xb8\xe5\x5f\x14\ -\x70\x20\xc2\xb0\x04\x81\x40\x4f\x29\xe8\x4d\xf8\x85\x25\x9c\x3b\ -\xa4\x35\x69\x12\xde\x20\x14\xa7\x3c\x8a\x7a\x4e\xd0\x1e\x03\x29\ -\x89\xb8\x4d\x62\x92\xcc\xd7\xcd\x1e\x3a\x0f\xa6\xa2\xa6\x63\x90\ -\x18\xcf\x98\x74\xf0\xcb\x2c\x55\x51\x29\x48\x62\xaa\x79\x4e\x31\ -\xd0\x82\x60\xbe\xcb\x6f\xf5\x12\xaa\x9e\x8e\xb1\x07\x1d\x96\x92\ -\xc5\x52\x68\x06\x7a\x8b\xeb\x58\xe9\xf2\xa8\x6d\x62\x89\xdd\xcf\ -\x2d\x5d\x8c\x48\x73\x65\x05\x97\xb8\x9a\x13\x2f\x6c\x38\xa2\x6a\ -\xc8\x05\x12\x8f\xc3\x92\x94\xa0\x3a\xa8\x7e\xbd\x89\x37\xad\xea\ -\xae\x0d\x93\x78\xac\xa1\x8d\x48\xc2\xb5\xb4\x79\xaf\x25\xc9\x68\ -\xc9\xb4\x15\xb9\x6b\xa1\xa9\x94\x06\x96\x68\x33\xf6\x90\x2f\x5a\ -\x7a\x2d\xc5\xb9\xeb\x94\x63\xde\xe6\xa9\xf4\xaa\xe2\xb2\xbc\x00\ -\x5b\x55\x84\x66\xe0\x9a\x22\xbe\x32\xd8\xaf\xa6\xbc\x2f\x47\x2b\ -\x5b\xb8\xab\xc4\x3e\x76\xe5\x5f\x88\xaa\x46\x39\xca\x37\xec\xd6\ -\x0b\xf4\x25\x3d\x67\xd5\xb1\x04\x28\x5d\x07\x1b\x6c\xd0\x43\x65\ -\x61\x46\xb8\x5a\x7e\x5d\x1e\xd0\xba\x7a\xf7\x0e\x0b\x3b\xcf\xe9\ -\x92\x87\xc5\x63\xef\x48\xe9\xfa\x1a\xdf\x1b\xe7\x69\xeb\x5c\xbf\ -\x50\x00\xd6\xa5\xe8\x3e\x92\xda\xfb\x24\x2b\x3b\xbe\xc0\x4d\x7e\ -\x86\x90\x1a\x47\x1b\xdd\xc8\x7b\x8d\x26\xe7\x8b\x5d\x19\x24\xe1\ -\x3c\x4a\x0a\xfc\xa0\xdd\x16\x35\x22\x37\xe9\xa6\xda\x32\x7a\xff\ -\x0f\x59\xf9\x35\x4a\ -\x00\x00\x04\x5f\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x11\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4d\x68\x1d\x55\x1c\xc5\x7f\x67\xf2\x90\x14\x95\xa2\xa8\x1b\ -\x51\x57\xa2\xb8\x11\x69\xc9\x47\x45\x49\x45\xab\x55\x0c\xcd\x7b\ -\xa5\xae\x44\x2a\x8a\x76\x21\x2a\x28\x82\x0a\xb1\xb4\x62\x05\xc1\ -\x85\x88\x16\x04\x71\x61\xd1\x90\x2f\x03\x5a\x8d\x4a\x2b\x48\x9b\ -\x3c\x6d\x69\x41\x5c\x14\x44\x5c\x28\xa2\x60\x54\xb0\x46\x9b\x37\ -\xc7\xc5\x6b\x64\x66\x5e\xc1\x44\xe6\xe3\x5a\xdf\x59\x9e\x03\x73\ -\xff\xf7\x77\xef\xdc\xb9\x77\xe6\x3d\xe8\xaa\xab\xae\xfe\xcf\x52\ -\xd5\x05\xac\x54\x7d\x13\x1e\x55\xe4\xa7\x65\x2b\x76\xb4\xbb\xd9\ -\xd0\x33\x79\x5c\xf7\x3f\x01\xa0\x7f\xc2\x1b\x89\xfc\x31\x3e\x5d\ -\xaf\x1d\xcf\x37\x7a\x7a\xf2\xb8\x76\x94\xc7\x45\x8a\x54\xdf\xb8\ -\xd7\x23\xcf\xfc\xdd\x79\x00\x29\xb7\xba\x83\x06\x30\x38\xee\xab\ -\x15\x79\x3f\x70\x5e\xd2\x37\xc4\x79\xb5\x11\x2c\x80\x75\x63\xbe\ -\x3c\x8e\x3c\x0b\x5c\x94\xcd\x04\xce\xab\x9d\x20\x01\xdc\x30\xe6\ -\x8b\x6b\x35\xcf\x02\x97\x15\xdd\x56\xad\xe8\x06\x56\xab\xeb\xdf\ -\xf1\xf9\x7f\xc6\x7e\x0f\x73\x55\x19\xed\x05\x35\x03\x86\x5e\x77\ -\xef\x52\xcb\xd3\x98\xf5\x49\xdf\x39\x4e\xf9\xac\x82\x01\x30\x74\ -\xc0\xb5\xc5\xb5\xde\x07\xdc\x94\x0a\x84\x95\xe3\xa2\x97\x55\x18\ -\x00\x6c\xfd\xbe\x10\xef\x35\x8c\x64\x13\x5c\x5c\xe7\x21\x10\x00\ -\xfd\x53\xf1\xf3\xa0\x7b\x53\xa6\x30\x05\x8e\xfc\xb2\x2a\x07\x30\ -\x30\xe9\x27\x40\x8f\x27\x3d\xb7\xef\xfa\xc2\x3b\x0f\x15\x03\x18\ -\x98\xf4\xfd\xc6\x7b\xb2\xbe\x14\xb5\xca\xaa\xa1\x32\x00\xfd\x53\ -\x6e\x18\xbf\x9a\x32\x0d\x36\x31\x2e\x6c\xd1\xef\x50\x25\x00\x06\ -\xc6\x7d\x33\xf6\xbe\x6c\xfb\x16\xb1\x54\xdc\x23\xef\x4c\x2a\x1d\ -\xc0\xe0\x94\xfb\x2c\x4f\x03\xe7\x24\x7d\x9b\x38\xcf\x2d\xee\x4a\ -\x55\x2a\x80\xfe\x69\x5f\x13\xdb\xfb\x11\xe7\xa6\x02\x97\x3f\xf2\ -\xcb\x2a\x0d\xc0\x86\x09\x5f\x41\xec\x59\xe0\xc2\x74\xa2\x98\x8a\ -\x3a\x0f\x25\x9d\x05\x36\x4c\xfa\x92\x16\xfe\x10\xb8\x34\x9d\x28\ -\xa6\xcc\x15\xef\x0c\x2a\x7c\x06\xac\x1b\xf3\xda\x25\xf9\x7d\xe0\ -\xca\x54\x20\xbb\xea\xce\x43\xc1\x33\x60\x70\xcc\x6b\xe2\x9a\x67\ -\x30\xd7\xa5\x02\x61\xac\x52\x36\x3a\xff\xa4\xc2\x66\xc0\xd0\x01\ -\xd7\xe2\x9a\xdf\x02\x6e\x4c\xfa\x2e\x61\x7f\xbf\x1a\x15\x03\x60\ -\xd4\xd1\xe2\x42\xfc\x1a\x30\x9c\xf2\x0b\x3e\xd9\xfd\x1b\xe5\x0f\ -\xc0\xd6\xc0\xb5\xf1\x0b\x46\xf7\x64\x93\x90\x46\x7e\x59\xb9\x03\ -\x18\x98\xe2\x49\xa3\x47\x53\x66\x7b\xad\x0b\xae\xf3\x90\x33\x80\ -\xbe\x49\x3f\x68\xbc\xbb\x23\x90\x4a\x3b\xdc\xac\x56\xb9\x01\xe8\ -\x9b\x6c\xed\x11\x7e\x25\xeb\x3b\xc0\x69\x9f\x54\x8e\x33\x20\xf3\ -\x42\x83\xf6\xfb\xfb\xaa\xb6\xb8\x2b\x55\x6e\x00\x04\x9d\xd3\x3c\ -\xe8\xae\xb7\x95\x1f\x00\xe9\x61\x32\x5d\x96\x88\x42\xff\xfc\x98\ -\x1b\x80\xb9\x11\x8d\x81\x1e\xea\x4c\x9c\xcb\x47\xcc\xa2\x94\xeb\ -\x53\x60\xbe\xae\x97\x41\xa3\x9d\x49\xb8\x10\x72\xdf\x07\xcc\x8f\ -\xb0\xcb\xf2\x4b\x69\x57\x20\xa2\x10\xef\x86\xfc\x77\x82\x92\x9b\ -\xc7\xa2\x47\x8c\xdf\x4c\xf9\x46\xb8\xfa\xb7\xd0\x59\x15\x53\xd0\ -\x4e\xc5\xad\x1f\xa3\xed\xc0\xbb\x99\x44\x28\x2c\x08\x85\x15\x73\ -\xe4\x01\x9d\x5a\xaa\x69\x1b\xf0\x69\x2a\x68\xff\xd0\x21\x18\x08\ -\x85\x16\x72\x64\x58\x27\xff\x90\xee\x04\x8e\x67\x22\x19\x07\x01\ -\xa1\xf0\x22\x8e\x8d\xe8\xe7\x78\x49\xb7\x19\xbe\x4a\xfa\x42\x32\ -\xaa\x7c\x59\x2c\x65\x14\x3e\xdb\xa6\xef\xa9\xe9\x16\xe0\xbb\xa4\ -\x2f\x1c\x55\x0d\xa1\xb4\x69\xd8\x1c\xd6\xd7\x2d\x74\x2b\xb0\x90\ -\xf4\xd5\xbe\x15\x2a\x83\x50\xea\x7d\xf8\x79\x5d\x5f\x18\xdd\x01\ -\x9c\xcc\xd6\xe1\x8a\x20\x94\xbe\x10\x35\xeb\x3a\xec\x58\x75\xe0\ -\x54\xd2\x17\x44\x76\xf9\x10\x2a\x59\x89\x9b\x5b\xf5\x81\xac\xbb\ -\xc9\x1e\x9e\x2a\x80\x50\xd9\xa3\x68\xae\xa1\xb7\x6d\xed\x48\x99\ -\x5a\x3e\x41\x96\xa7\x4a\x9f\xc5\xcd\x86\xf6\xda\x7a\xaa\x23\x70\ -\x79\x87\xa7\xca\x37\x23\xcd\x3a\xcf\x09\xbf\x98\x32\x75\xfa\xf0\ -\x54\x82\x2a\x07\x80\xe4\xb9\xe3\xd1\x63\xc2\x6f\xa4\xfc\x92\xb6\ -\xcc\xd5\x03\x00\xd8\xa9\xb8\xf7\x82\xe8\x3e\x60\x26\x93\x14\x7e\ -\x78\x0a\x03\x00\x70\x70\xa3\x96\xd6\xfc\xa2\xbb\x0c\x9f\xa4\x02\ -\x23\x17\x58\x67\x30\x00\x00\x0e\x6e\xd7\xa2\x7a\x35\x0c\x1c\x4d\ -\xfa\x2a\x70\x93\x14\x14\x00\x80\xf9\xdb\xf5\x6b\x0f\xda\x0c\x9c\ -\x28\xa3\xbd\xe0\x00\x00\x1c\xaa\xeb\x87\x1e\x6b\x13\xf0\x6d\xd1\ -\x6d\x05\x09\x00\xe0\x50\x43\xdf\x10\x69\x13\xf0\x53\x36\xcb\xf3\ -\xdc\x10\x2c\x00\x80\xf9\x2d\xfa\x32\x92\x36\x63\x7e\x4b\xfa\xca\ -\xb1\xee\xa0\x01\x00\x1c\x1e\x51\x53\xd6\x96\xcc\x0f\xa9\xce\xfe\ -\xbf\xcc\x24\x35\xb7\x55\x1f\x61\xed\xa2\xfd\xf9\xad\x85\xf4\x6c\ -\xd5\x35\x75\xd5\x55\x57\x67\x87\xfe\x02\x8f\xb0\x51\x56\xec\xcd\ -\x17\x8d\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x88\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3a\x49\x44\x41\x54\x58\x85\xed\ -\xcd\xb1\x11\x00\x10\x00\xc0\xc0\x30\x99\xc6\x04\x56\x30\x96\x15\ -\x2c\xe0\xdc\x59\x4d\xa5\x55\x6a\xe4\xab\x74\x01\x49\x92\x7e\x17\ -\x4e\xe4\x52\x17\x90\x1e\x4d\xe7\xe8\x2d\x03\xc4\x17\x43\x49\x92\ -\xa4\x9b\x0d\x00\xac\x05\x04\x1d\x7e\x88\x63\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\xbb\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x6d\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\xbd\x6f\x13\x31\x18\xc6\x9f\xf7\x2e\x15\x13\x08\xa6\x22\x35\ -\xc4\xbd\x88\x05\x06\x40\x82\x85\x1d\xca\x00\x62\x80\xa1\x0b\x12\ -\x7f\x01\x1f\x1b\xb4\x03\x08\x24\x3e\xc4\xc4\xc7\x5f\x80\xc4\xd2\ -\x01\x06\x04\x03\x85\x9d\x05\x24\xca\xd0\x6e\x77\xe7\x24\x1d\x60\ -\x00\xc4\x56\x91\xe4\x61\x48\x24\x2e\x77\x17\x68\xe3\xbb\xb8\xa5\ -\xfe\x6d\x7e\xfd\xc6\x79\xfc\xc4\x67\x5b\x39\x1b\x70\x38\x1c\xdb\ -\x19\x59\x4f\x12\xc9\x8a\xd6\xad\xb3\x14\xce\x0a\xe4\x18\x80\x29\ -\x00\x3b\xca\x95\xb6\x61\xd6\x00\xac\x12\xfc\x20\x94\x05\xa5\xaa\ -\x2f\x45\xa4\xfd\xaf\x0f\xfd\xd3\x00\xad\xf5\x49\x42\x1e\x01\x72\ -\xa0\x10\x99\xe3\x63\x59\xd0\xbd\xaa\x94\x7a\xfb\xb7\x24\x6f\x58\ -\x05\x49\x89\x1b\xad\x79\xc2\x5b\xdc\x82\x9d\x07\x80\x83\x84\xb7\ -\x18\xe9\xd6\x1c\xc9\xa1\x3f\xf4\x50\x03\x74\x73\x75\x0e\xe4\x9d\ -\x72\xb4\x8d\x0f\x01\xef\xc6\x8d\xd5\xeb\xc3\xeb\x73\xe8\x0d\x7b\ -\x6f\x31\x15\xfe\x0e\xe2\x06\xd0\x79\xad\x94\x6a\x88\x48\xa7\x50\ -\xa5\x86\x90\xf4\xb5\xd6\x35\xc0\x3f\x0d\xc1\x6d\x00\x7b\x92\xf5\ -\x82\xee\x4c\xde\xe3\x90\x31\x80\x64\x45\x37\x9a\x9f\x07\x87\x3d\ -\xdf\x75\x3b\xed\x0b\xf5\x7a\xfd\x4b\x09\xda\x0b\x27\x0c\xc3\x49\ -\xcf\xaf\x3c\x03\xe4\x44\x22\xbc\xac\x6a\xd5\xc3\xe9\x89\x31\x63\ -\x40\x1c\x37\xcf\x41\xf0\x3c\x11\xfa\xd6\xfe\x35\x71\x60\xff\xfe\ -\xbd\x5f\xcb\x12\x5c\x06\x3d\x13\x26\x56\x90\x1c\x09\xc4\xf9\xe9\ -\xe9\x7d\x2f\x92\x79\x99\x39\x80\xc2\xd9\xc1\x00\x6e\x6e\xb5\xce\ -\x03\x40\xbd\x5e\xff\x22\xc0\xcd\x64\x2c\xd3\x37\xe4\x18\xd0\x5f\ -\xe7\x13\x74\x5e\x17\x2d\x6e\x5c\x90\x9d\x57\xc9\xb2\x40\x8e\xa6\ -\x73\xf2\x56\x81\xa9\x64\x41\x29\xd5\x28\x58\xd7\xd8\xc8\xd1\x5e\ -\x4d\xe7\xe4\x19\x30\xb0\xc3\xdb\x6c\xb3\xfd\x46\xc8\xd1\x9e\xd9\ -\xbd\x0e\xdd\x07\x6c\x17\x9c\x01\xb6\x05\xd8\xc6\x19\x60\x5b\x80\ -\x6d\x9c\x01\xb6\x05\xd8\xc6\x19\x60\x5b\x80\x6d\x9c\x01\xb6\x05\ -\xd8\xc6\x19\x60\x5b\x80\x6d\x2a\x45\x34\x12\x36\x1a\x33\x1e\xe4\ -\x01\x88\x43\x58\xe7\xbb\x06\x03\x08\x60\xa9\x2b\xbc\x56\xaf\xd5\ -\xd2\xff\x5b\x6e\x18\xe3\x11\x10\xe9\xd6\x45\x8f\xf2\x06\xc4\x61\ -\x94\xdf\x79\xf4\xbf\xe3\x88\x47\x79\x13\xe9\xd6\x45\xd3\xc6\x8c\ -\x0c\x88\xa2\x68\xb7\x80\x4f\x4c\x45\x8c\x8a\x80\x8f\xa3\x28\xda\ -\x6d\xd2\x86\x91\x01\x22\x95\xe3\x00\x76\x9a\xb4\x61\xc8\xae\xbe\ -\x86\x91\xd9\xf6\x93\xa0\x91\x01\x64\xfb\x3d\x80\x9f\x05\x69\x19\ -\x85\x9f\x7d\x0d\x23\x63\x64\x40\x10\x04\x3f\x08\xb9\x6c\xd2\x86\ -\x09\x84\x5c\x0e\x82\xe0\x87\x49\x1b\xc6\x8f\x40\xa0\xaa\x4f\xbb\ -\xc2\x53\x00\x3e\xa1\xb7\x44\x95\x0d\x21\x58\xea\x0a\x4f\x05\xaa\ -\xfa\xd4\xb4\xb1\x42\xf6\x01\xfd\xf5\xd8\x78\x4d\xb6\x81\x9b\x04\ -\x6d\x0b\xb0\x8d\x33\xc0\xb6\x00\xdb\x38\x03\x6c\x0b\xb0\x8d\x33\ -\xc0\xb6\x00\xdb\x38\x03\x6c\x0b\xb0\x8d\x33\xc0\xb6\x00\xdb\x38\ -\x03\x72\x62\x6b\xc9\x02\x49\x7f\x4c\x5a\x0a\x27\x47\xfb\x5a\x3a\ -\x27\xcf\x80\xd5\x64\xa1\x77\xfc\x74\x6b\x92\xa3\xbd\x95\xce\xc9\ -\x1e\x94\x04\x3f\x0c\x46\xfc\xd3\x85\xaa\x1a\x23\x22\xfe\x99\x64\ -\x99\xe0\xc7\x74\x4e\xf6\xa0\x24\x65\x61\x30\x80\xdb\x61\x18\x4e\ -\x16\xae\xae\x64\xc2\x30\x9c\x24\x70\x2b\x19\xcb\xf4\x0d\x39\x06\ -\x28\x55\x7d\x09\x70\x25\x11\xda\xe3\xf9\x95\x67\x5b\xc9\x84\x3f\ -\x87\xa5\x07\x4e\x8c\x2f\xf7\xfa\x36\x48\x76\x04\x88\xb4\x05\xbc\ -\x92\x8a\x9e\xf0\xfc\x89\x15\xad\x9b\x97\xe2\x38\x0e\x36\xe3\xc4\ -\x48\xd2\x8f\xe3\x38\xd0\xba\x79\xa9\x77\x48\x7a\xe0\xa4\x38\x04\ -\xdd\xab\x79\x57\x68\x86\xbe\xca\x8a\x1b\xad\xf9\xff\xe1\xc2\x04\ -\x00\x10\x32\x1f\xa8\xea\xbd\xbc\xba\xa1\xfb\x00\xb5\x6f\xea\x1e\ -\x21\xf3\xe5\xc9\x1a\x0b\x24\x30\x37\x5d\x9b\xba\x3f\x2c\x61\x9d\ -\x97\xa6\xbc\x87\x00\x0e\x16\x2a\xad\x7c\xd6\x75\x69\x6a\x94\x6b\ -\x73\x47\xd1\x3b\x75\xbd\x19\xaf\xcd\xb5\x08\x7e\xdc\xc8\xb5\x39\ -\x87\xc3\xb1\xbd\xf9\x0d\x9c\xbe\x20\xb7\xf5\xf6\x9b\x02\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\xdc\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x8e\x49\x44\x41\x54\x58\x85\xed\ -\x97\x41\x4a\xc3\x50\x10\x86\xbf\x79\x71\xab\x0b\x45\x5d\xd8\xd6\ -\x92\x4b\x28\x28\x5e\xa0\x5e\x41\x0f\x20\xe8\x4a\xd4\x23\x58\xc1\ -\x85\x15\x3c\x88\xd0\x0b\x08\x82\x5e\x22\xe6\x25\xcf\x85\x8a\x82\ -\x74\x9d\x8c\x0b\x1b\x91\x36\x46\xac\xa9\x0a\xe6\x5f\x0d\xf3\x86\ -\x37\x1f\x33\xc3\xe3\x0d\xfc\x77\xc9\xa0\xc3\xda\xdb\x95\x94\x64\ -\x5f\x54\x96\x11\x66\x4b\xc9\xa2\x3c\xa8\xe8\x95\xc1\x6b\x2f\x2e\ -\x2e\x5c\x7e\x08\x10\x86\xd1\x2e\x22\x47\x79\x60\x25\x29\x45\x75\ -\xaf\xd9\x6c\x1c\x0f\x01\x58\x6b\x57\x15\x73\x01\x3c\x0b\xb2\x63\ -\x8c\x76\xeb\xf5\xfa\x53\x19\x59\xe3\x38\x9e\x4e\x53\x69\x29\xda\ -\x01\xa6\x04\xb3\x36\x58\x09\x6e\x6c\x74\x1e\xda\x58\xad\x75\x1b\ -\x65\x24\xcd\x93\xb5\x6e\x33\xb4\xb1\xde\xd8\xe8\x3c\xf3\x99\xcc\ -\x10\x95\x65\x00\x63\xb4\x3b\x2e\x00\xcf\xa3\x0b\x20\xc8\xd2\x10\ -\x40\x36\x70\x65\x95\x3d\x4f\xb5\x5a\xed\xb1\x6f\xce\x0d\x03\xfc\ -\x92\x2a\x80\x0a\xe0\xd7\x01\x26\x3e\x0b\x08\xa3\x68\x0b\x95\x43\ -\x60\xf2\x8b\x77\xf7\x10\x3d\x68\x36\x1a\x67\x45\x41\x85\x15\x08\ -\x82\x60\x1e\x95\xd3\x11\x92\x03\x4c\xa2\xd2\x09\x82\x60\x7e\x64\ -\x80\x9f\x50\x21\x80\xef\xfb\x77\x88\x6e\x03\xbd\x11\xee\xee\x21\ -\xba\xe3\xfb\xfe\x5d\x51\xd0\xa7\x33\xd0\xef\x61\x61\x1f\xbf\xa3\ -\xbf\xdd\x82\x0a\xa0\x02\xf8\x59\x00\xe5\x01\x5e\x3f\x90\xe3\x4a\ -\xe6\x9c\x9b\xe9\x9b\xf7\x43\x00\x2a\x7a\x05\x90\xa6\xd2\x1a\x17\ -\x40\x92\xd0\x02\x50\xf4\x3a\xf3\xbd\x3d\x44\x06\xaf\xad\xa4\xeb\ -\x8a\x76\xac\x75\xe2\x79\x74\xdf\xfd\xe1\xbe\x25\xe7\xdc\x4c\x92\ -\xd0\x52\xf4\x04\x48\x0d\x5e\x3b\x3b\xcb\x5b\x4c\xda\x8c\x6f\x36\ -\x3e\x5e\x4c\x32\xbd\xad\x66\xaf\x5f\xe7\xb9\xc1\xf3\x11\x75\xaf\ -\xe8\x75\xde\x6a\x56\xe9\x05\x72\xdf\x93\xde\xaf\x9f\x93\x4c\x00\ -\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x05\x36\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\xe8\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4f\x4c\x1c\x55\x1c\xc7\xbf\xbf\x99\x59\x4c\x7a\x21\x55\x1a\ -\x52\x69\x7a\x71\x9b\x88\x21\xa9\x48\x6f\xbd\x6c\x5c\x81\x43\x2b\ -\x91\xc0\x46\x8d\xd0\x34\xd9\x8d\xbd\x7a\xb1\x07\x12\x59\x20\x31\ -\xa6\xf5\xe4\xcd\xe8\x12\x1a\x25\x9a\x66\x5b\x30\x84\xc6\x00\x62\ -\x36\x2d\x7a\xa2\x92\x18\x5d\x2e\xc5\x03\x61\x0f\x18\x6c\xc3\xa9\ -\x59\xd8\x99\x9f\x07\xf6\xc9\xec\xec\xec\xce\x2c\xf3\x67\x07\xd9\ -\xcf\xed\xcd\xfc\x66\xde\x6f\xbe\xf9\xfe\xde\x7b\x33\x79\x03\x34\ -\x68\xd0\xe0\x24\x43\x76\x82\x22\x91\xa4\xa2\xb4\xe4\xfa\x88\xf1\ -\x2e\x80\x4b\x00\xda\x00\xbc\xe0\x69\x66\xb5\x93\x07\x90\x03\xb0\ -\xca\x84\xbb\x85\x9d\xb6\xb9\x4c\x66\xbc\x60\x75\x91\xa5\x00\x3d\ -\xfd\x89\x6e\x96\xf0\x05\x80\x76\x17\x92\xf4\x11\xca\x92\xc6\x1f\ -\x2d\xce\xa6\x96\xaa\x45\xc9\xd5\xee\xd0\x3d\x98\x18\x01\xe1\x0e\ -\x80\x33\xae\xe6\xe6\x0f\x67\x40\x18\x0e\xb7\x77\xee\x6d\xac\xaf\ -\xfd\x52\x29\xa8\xa2\x00\xdd\x83\x89\x11\x30\x3e\xf5\x26\x37\x1f\ -\x21\x8a\x86\xdb\x3b\xf3\x1b\xeb\x6b\x2b\xa6\xa7\xcd\x0e\x16\x6d\ -\xbf\x58\x72\x90\xf1\x8c\x89\x47\x25\x89\x1e\x34\x63\x77\x33\x9d\ -\x4e\xab\x1e\xa4\x7b\x64\x62\xb1\x98\xbc\x8b\xe6\xf3\x9a\xc6\x57\ -\x88\x69\x02\x84\xd3\xfa\xf3\xa4\xa1\xc7\xac\x1c\xca\x04\x88\x44\ -\x92\x4a\xe8\xa5\xdc\xef\xd0\xd5\x3c\x01\x3f\xa9\xfb\x18\x5a\x9e\ -\x4b\x6d\x7b\x92\xbd\xcb\x44\xfb\x12\xad\x72\x08\xd3\x0c\xbc\x75\ -\x78\x94\xb2\xfb\xff\xbc\x7c\xd1\x38\x30\x4a\xc6\x8b\x95\x96\x5c\ -\x1f\x4a\x07\xbc\xa7\xd0\x94\x0f\x8e\xcb\xc3\x03\xc0\xf2\x5c\x6a\ -\x5b\xdd\xc7\x10\x18\xcf\x0e\x8f\xf2\x6b\xc5\x67\x2b\xa1\x4c\x80\ -\xe2\x54\x77\x78\x19\x38\xb9\x38\xfb\xe5\xdf\x5e\x24\xea\x25\xcb\ -\x73\xa9\x6d\x06\x25\xf5\xc7\x8c\xcf\x06\x98\x08\x80\x83\x79\xfe\ -\x30\x40\xa2\x07\x2e\xe7\xe6\x1b\x92\xcc\xf3\xfa\x36\x01\x5d\x65\ -\x31\x26\xd7\xb5\xe9\x1b\xcd\xd8\xdd\x74\x39\x2f\xdf\x30\xe6\xce\ -\xc0\x39\x63\x8c\x99\x00\x25\x2b\xbc\xa0\x8d\xf6\xb5\x60\x92\x7b\ -\xd9\xea\xd5\x4c\x80\x13\x85\x52\xef\x04\xec\xd0\x1b\x8b\x87\x35\ -\x4d\x1a\x05\x78\x00\x00\x88\x71\xaf\xa0\x49\x13\x3f\xff\xf0\xd5\ -\x86\xd3\x7b\x07\xde\x01\xdd\x03\x37\x2e\x68\x1a\x3d\x04\x78\x18\ -\xc0\x29\x00\xa7\x98\x70\x4d\x96\xb5\x47\xbd\xb1\x78\xd8\xe9\xfd\ -\x03\x2d\x40\x24\x92\x54\xc0\xea\xf7\x00\xce\x9a\x9c\x3e\xcb\x2a\ -\x7d\xe2\xb4\x8f\x40\x0b\x10\x6a\xc9\xdd\x04\x95\x4f\x5d\x02\x26\ -\x0c\x3a\xed\x23\xb0\x02\xf4\xf4\xc7\x3b\xc0\x18\xf3\xba\x9f\x40\ -\x0a\x10\x89\x24\x15\x26\xba\x03\x20\x64\x11\x9a\x76\xda\x57\x20\ -\x05\xb0\xb2\x7e\x91\x3d\x4d\x52\x6f\x3b\xed\x2b\x70\x02\xd8\xb5\ -\x3e\x31\x8f\x2d\xa7\xa7\xb2\x4e\xfb\x0b\x94\x00\x35\x58\x7f\x75\ -\xef\xe9\xb9\xcf\xdd\xe8\x33\x50\x02\xd8\xb5\xbe\x04\xba\x6e\xe7\ -\x83\xa7\x1d\x02\xb3\x12\xec\xe9\x8f\x77\xb0\x4d\xeb\x2f\xcc\xa4\ -\xfe\x74\xab\xdf\x40\x38\xa0\x1e\xd6\x17\xb8\xe2\x80\x37\xdf\xf9\ -\xf0\x15\x45\xd2\x46\x0f\x17\x26\x74\x5f\x92\xb4\x89\x85\xf4\xe4\ -\x13\x3b\xd7\x87\x5a\x72\x37\xc1\xfe\x5a\x5f\xe0\xd8\x01\xbd\xb1\ -\x78\x58\x96\xb5\x47\x4c\xb8\x86\xe2\x5a\x1d\xe0\x61\x4d\xa3\x87\ -\xdd\x03\x37\x2e\x58\x5d\x5f\xcb\xa8\xbf\x70\xff\x6b\xd7\xac\x2f\ -\x70\x2c\xc0\xc1\x5b\x9a\xf9\x5a\x1d\x50\xbf\x8b\x44\x92\x15\x5d\ -\x56\x4f\xeb\x0b\x5c\x18\x03\x0e\x5e\x51\x2b\x70\xa9\xe9\xc5\xad\ -\x8f\x2b\x9d\xac\xc7\xa8\x6f\xc4\xf3\x41\x90\x89\xc6\x7a\xfa\xe3\ -\x1d\xc6\xe3\xf5\xb6\xbe\xc0\xb1\x00\xc4\xb8\x67\x11\xd2\xc4\x12\ -\x4d\xe9\x4b\x21\x08\xd6\x17\x38\x16\x40\x95\xd5\x5b\x00\xf6\x2c\ -\xc2\x4a\x4a\x21\x08\xd6\x17\x38\x16\x60\x39\x3d\x95\x05\x61\xdc\ -\x2a\x4e\x94\x42\x50\xac\x2f\x70\x65\x0c\xd8\xdf\x69\xbb\x0d\xc6\ -\x63\x8b\xb0\x26\x96\xe8\x5b\x96\xa4\x69\x04\xc0\xfa\x02\x57\x04\ -\xc8\x64\xc6\x0b\xc4\x7c\x1d\xd6\xa5\xf0\x3a\xc0\x17\x2d\x62\x7c\ -\xb1\xbe\xc0\xb5\x59\x60\x71\x76\xf2\x0f\x3b\xa5\x60\x85\x5f\xd6\ -\x17\xb8\x3a\x0d\xda\x2c\x85\x6a\xf8\x66\x7d\x81\xab\x02\xd4\x50\ -\x0a\x66\xf8\x6a\x7d\x81\xeb\x0b\xa1\xa3\x96\x82\xdf\xd6\x17\x78\ -\xb2\x12\x3c\x42\x29\xf8\x6e\x7d\x81\x27\x02\xd4\x58\x0a\x75\xb1\ -\xbe\xc0\xb3\x77\x01\xbb\xa5\x50\x2f\xeb\x0b\x3c\x7d\x19\xb2\x51\ -\x0a\x75\xb3\xbe\xc0\x53\x01\x32\x99\xf1\x82\x24\xf3\x7b\x00\xcc\ -\x36\x59\x6c\x4a\x12\xbf\x5f\x2f\xeb\x0b\x3c\x7f\x1d\x5e\x48\x4f\ -\x3e\x51\x18\x97\x19\x98\x07\xf0\x1c\xc0\x73\x06\xe6\x15\xc6\x65\ -\xbb\x9f\xcc\xbc\xc4\x97\xaf\xc2\x3f\xce\xa4\xb6\x00\xbc\xed\x47\ -\x5f\xb5\x12\x88\xaf\xc2\xf5\xc4\x4c\x80\xbc\xbe\x11\x8b\xc5\xaa\ -\xed\x27\x0e\x34\x26\xb9\xe7\x8d\x31\x66\x02\xe4\xf4\x8d\x5d\x34\ -\x9f\x77\x33\x29\x3f\x31\xe6\x4e\xc0\x96\x31\xc6\x4c\x80\x55\x7d\ -\x43\xd3\xf8\x8a\xcb\x79\xf9\x86\xa6\xd2\x55\x7d\x9b\x51\x3e\x25\ -\x97\x09\xc0\x84\xbb\xfa\x36\x31\x4d\x44\xfb\x12\xad\xee\xa7\xe7\ -\x2d\xd1\xbe\x44\x2b\x81\x4b\x16\x62\xc6\x67\x03\x4c\x04\x28\xec\ -\xb4\xcd\x01\x58\xff\xef\x00\xe1\xb4\x1c\xc2\xf4\x71\x12\x41\x6c\ -\x96\x2e\xdd\x31\x4e\xd9\xe2\xb3\x95\x50\xdb\x76\x79\x50\x52\x92\ -\x79\x3e\xd0\xdb\xe5\x55\xba\x4a\xe0\xf1\x23\x6f\x97\x17\xfc\x6f\ -\x7e\x98\x00\x40\xcc\x23\x8b\x33\x93\x9f\x99\x9d\xab\x38\xc5\xfd\ -\x95\xfd\x6d\x25\xdc\xde\x99\x07\x51\xd4\xbb\xd4\x3c\x87\x19\x18\ -\x59\x9a\x99\xbc\x55\x29\xa0\xea\x1c\xbf\xb1\xbe\xb6\x12\x7e\xf5\ -\x8d\x5f\x41\xd4\x85\x63\xf7\xdf\x10\x65\x49\xc3\xd0\xd2\x4c\xea\ -\x9b\xaa\x51\x76\x6e\xa5\xff\x6d\x8e\x80\xae\xe2\xae\xeb\xc0\xfd\ -\x36\x47\xc0\x16\x03\x8f\x6b\xf9\x6d\xae\x41\x83\x06\x27\x9b\x7f\ -\x01\x0f\x15\x0b\x99\x9e\x82\xdf\x92\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x02\x05\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xb7\x49\x44\x41\x54\x58\x85\xed\ -\x96\xbd\x4a\xc3\x50\x14\xc7\xff\x27\x1f\x53\xc1\x07\xf0\xda\x34\ -\x43\xf7\x82\x93\x08\xe2\x2b\x88\x0e\xd2\xc5\x17\xd0\x45\x10\x71\ -\xe9\xd4\xc1\x41\x74\x29\x3e\x81\x93\x43\x9f\xc0\x45\x90\x82\xa3\ -\x7d\x80\x62\x3e\x50\x33\xb8\xe8\x20\xa1\x69\x7b\x1c\x6c\x42\x13\ -\x9b\x34\xe9\xe7\xd0\xfe\xa7\xfb\x71\xee\xfd\xff\x72\xee\xb9\x97\ -\x00\xcb\x2e\x4a\x9a\x74\x1c\x27\xe7\xba\xed\x2a\x88\xf6\x01\x14\ -\x26\xf4\x32\xc1\x54\x57\x55\xaa\x08\x21\x7e\x46\x02\x38\x8e\x93\ -\x73\xdb\x5e\x03\x8c\xd2\x84\xc6\x61\x11\x9a\xaa\x2c\x6d\xfb\x10\ -\x52\x5c\x9c\xeb\xb6\xab\x53\x37\x07\x00\x46\xc9\xf3\xb8\xea\x77\ -\x63\x01\xfa\x69\x9f\x8d\x88\x0f\xfc\xa6\x92\x10\x16\x3a\x73\xbd\ -\x90\x4f\xac\x97\x51\x32\x4c\x9b\x87\xed\x1d\x9f\x81\x39\x69\x05\ -\xf0\xaf\x06\x5a\xad\x37\x4d\x51\x78\x97\xc1\xa1\x71\xc3\xb0\x4f\ -\x62\x77\x91\xb8\x47\x2c\x37\x35\x6d\xfd\x99\x88\xba\x59\x00\x42\ -\x85\x65\x18\xd6\x19\x88\x2e\x87\x81\xa5\x11\x03\x4f\xc4\xdd\x43\ -\x5d\xd7\x3f\xa2\x73\x91\x22\x0c\x8a\x3a\x38\x82\x57\xcb\x2a\x83\ -\xe8\x6a\x5c\x73\x00\x20\x60\x87\x49\xbe\x67\x66\x39\xed\x9a\x00\ -\x80\x98\xce\xc7\x35\x8e\x42\x58\xd6\xfb\x56\xda\xf8\xc1\xaf\x0d\ -\xbf\x7a\x84\xdb\xd4\xae\x8c\x3d\x00\x22\xe8\x52\xb7\x04\xa0\x91\ -\x15\x20\x54\x0f\xba\x96\x8f\x2f\xba\x88\x0c\xcb\x06\x18\xc7\xc1\ -\x40\x8f\x52\xdf\xae\x85\x5f\xc3\x15\xc0\x0a\x60\xe1\x00\x63\xbf\ -\x7a\x89\x22\xd4\x0c\xd3\xae\x25\x44\x98\x7e\x63\x31\x19\x60\xaa\ -\xfb\xcd\xd9\x64\x20\x49\x84\xa6\xaa\x50\xc5\xef\xce\x33\x03\x26\ -\x98\x6e\x06\xff\x88\xff\x78\xfa\x32\x4c\xfb\x0b\xc0\xda\x34\x9c\ -\x08\x74\x54\x28\x6c\xdc\xa5\x89\x1d\xcc\xc0\xc3\x34\xcc\x01\x74\ -\x3c\x85\x1e\xd3\x06\x07\x00\x1d\x45\x3a\x05\xf0\x39\xb1\x3d\xf3\ -\x45\x51\x08\x3b\x33\x40\x51\x08\xbb\xa3\x48\x9b\x00\xea\x00\xbe\ -\xb3\xda\x02\x78\x61\xe2\xb2\xae\x6b\xd7\x19\xd7\x2e\xb9\x7e\x01\ -\xf9\xaa\x7b\xc5\x23\x95\x73\x7f\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x01\xa6\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x58\x49\x44\x41\x54\x58\x85\xed\ -\xd2\x31\x2f\x43\x51\x18\xc6\xf1\xff\x39\x15\x03\x89\x10\x42\xba\ -\x11\x9b\x89\xb0\x89\x45\xb4\x69\xd0\x44\xb5\xb5\xd5\xc0\x15\x12\ -\x1f\xc0\x66\x12\x1f\xc0\xac\xb5\x34\x62\x68\x99\x08\xad\x44\x42\ -\x48\x37\x11\xc2\xd6\x45\x27\x83\x44\xca\xe4\xde\xfb\x5a\x19\x38\ -\xda\x2e\x12\xe7\x37\x3f\x79\xce\xf3\x26\x07\x2c\xcb\xb2\xac\xff\ -\x4e\x99\x02\xa1\xb8\xb3\x0d\x0c\x2b\x5f\x52\x85\x83\xf4\xdd\x6f\ -\x4a\x23\x33\x2b\xbd\x5e\xc0\xcd\x02\x2f\xc5\xfc\xf6\x34\x20\xdf\ -\x65\xb5\x79\xa1\xb4\x03\x83\xa2\xf5\x65\x38\xe6\x8c\x9b\xf2\xe1\ -\xa4\x33\xec\x35\xb9\x25\x60\x14\xa4\xd3\x94\x37\x0e\xa8\xea\xb6\ -\x14\x8a\x1c\x48\x9b\x68\x8e\x27\x12\xce\xfc\x77\xd9\x89\xd9\xc5\ -\x29\xf1\x39\x47\xe8\x11\xd4\xd9\xbb\xe7\x45\xf8\xe1\x7a\x80\x80\ -\x69\x40\xe5\xbe\xe4\xa6\x92\xd1\x7c\xe5\xe9\xb5\x15\x18\x53\x10\ -\xeb\x1f\x18\x92\xf2\xc3\xf5\xf9\xe7\x5c\x28\xbe\xb4\xa2\x14\x59\ -\xa0\x19\xc8\x76\xe8\x97\xb9\xa3\xfd\xdd\x37\x53\xbf\xf1\x0f\x7c\ -\x7d\xc4\x59\x05\xb6\x00\x8d\xb0\xf3\xdc\xa5\x97\xa7\x83\x41\xef\ -\xea\xb6\xb2\x89\x52\x6b\x00\xa2\x64\xe3\x34\x97\x5e\xc7\x70\x79\ -\x5d\x03\x00\xc2\xf1\xc5\xa8\xa0\xf6\x80\x16\x81\x0b\x05\x55\x60\ -\x12\x70\x15\xb2\x5c\xc8\xa7\x33\xb5\xf4\xd5\x3c\x00\x20\x14\x5f\ -\x18\x01\x7d\x08\x74\x03\x08\x54\x95\xf2\x13\xc5\x5c\xa6\x50\x6b\ -\x57\x5d\x03\x00\xc2\x49\xa7\x4f\x7c\xca\xc0\xa3\xf6\xfd\xe8\xc9\ -\x41\xe6\xa6\xde\xae\x46\x28\x1a\x38\xc2\xb2\x2c\xcb\xfa\x13\x3e\ -\x00\x77\x85\x6b\x30\xd4\xa0\xe5\x67\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x01\xa5\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x57\x49\x44\x41\x54\x58\x85\xed\ -\xd2\xcd\x2b\x44\x51\x1c\xc6\xf1\xef\xb9\x93\xd2\x28\x29\xe5\x65\ -\xc7\x7f\x20\xf7\x92\xb2\xb3\x9a\x30\x3b\x65\x35\x56\x9a\x3b\xc2\ -\x88\x8d\xdd\xac\x64\xa5\xa6\xb9\x77\x33\x23\x79\xa9\x59\x58\x58\ -\x29\x25\x1b\x45\x22\xae\xa2\xac\x6d\x94\x6c\x88\x14\xa9\x3b\xf3\ -\xb3\x30\x0b\xd4\xb8\x33\x63\x25\xe7\xb3\x3c\x3d\x3d\x3d\xa7\x73\ -\x40\xd3\x34\x4d\xfb\xef\x54\x50\xc0\xb2\x33\x2b\x60\x98\xa8\x62\ -\xcc\xcb\xce\x5c\x55\x52\xda\x97\x48\x77\xf8\x12\xca\x83\x7a\xf2\ -\x72\x53\xc3\xa0\xa4\x5c\xd6\x08\x6c\x13\x9a\x40\xba\x10\x75\xd4\ -\x9d\x70\x07\x82\xe2\xdd\x13\x19\xd3\x97\xd0\x09\xd0\x0f\x34\x07\ -\xe5\x03\x07\xd4\x35\x14\x62\xc0\x16\xd0\x68\x88\xec\x5a\xb6\x33\ -\x56\x2e\x6b\xc6\x9d\x21\xa3\xa8\x0e\x80\x56\x60\xdf\x7f\xf3\x23\ -\x3f\xdd\xbe\xa2\x01\xc7\xe9\xb9\x57\xaf\xed\x7e\x54\x50\x4b\x40\ -\x1d\xb0\xd1\x63\x3b\x29\x90\x2f\xcf\x67\xda\x6e\x42\x29\xb6\x81\ -\x30\x48\xfe\xe5\xe1\x3e\x72\xb1\x3e\xfb\x18\xd4\x1f\xf8\x07\x3e\ -\xb3\xe2\x99\x49\x94\x72\x3e\x86\xcb\x9a\x48\xbd\x7d\xde\x7e\x5b\ -\xb0\xee\x9a\x17\x81\xf9\x52\xe1\xc2\x59\x6e\x3a\x15\x74\xf3\x9a\ -\x06\x00\xf4\xd8\x4e\x54\x60\x13\x08\x2b\x38\x14\xd4\x33\xc8\x20\ -\xe0\xa3\xb0\xbd\x6c\x72\xb5\x9a\xbe\xaa\x07\x00\xf4\xda\xae\x25\ -\xc8\x8e\x40\x4b\xe9\xe8\x59\x84\x91\xf3\xe5\xe4\x5e\xb5\x5d\x35\ -\x0d\x00\xe8\x1d\x77\x3b\x8b\x21\xb9\x06\x6e\x0c\x88\x9e\xe6\x92\ -\x97\xb5\x76\xfd\x82\xa8\xef\x9f\x51\xd3\x34\x4d\xfb\x73\xde\x01\ -\x57\x2b\x69\x45\xc4\x74\x4c\x85\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x02\xdb\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\x8d\x49\x44\x41\x54\x58\x85\xe5\ -\x97\x4f\x48\x54\x51\x14\xc6\x7f\xe7\x8d\xb8\x11\x82\x12\x03\x75\ -\x35\xb8\x10\xc9\x4d\x6d\x32\x8c\x28\x9c\xa6\x85\x12\x18\x6f\xb6\ -\x12\xcc\x64\xad\x5c\xa9\x2d\x87\xc1\xd5\x04\x2d\x12\x92\x2c\x27\ -\x28\x17\x19\xc6\xb8\x49\x28\x07\x13\x02\xff\xb4\xa9\x8d\xd5\x4e\ -\xdd\xd8\x42\x29\x68\xe1\x46\x98\x7b\x5a\xf8\xde\xf4\x1c\x9a\x3f\ -\x6f\x7c\xb6\xa8\x6f\xf5\xde\xb9\xe7\x9e\xef\x7b\xdf\xb9\x97\x77\ -\x2f\xfc\xef\x90\xe2\xc0\xd5\x1b\xf1\x6e\x44\xee\x02\x5d\x40\x53\ -\x40\x3c\xbb\xc0\x1a\xaa\xe9\x5c\x36\xb3\xec\x1d\x08\x79\x5f\x22\ -\x76\x7c\x58\x90\x17\x40\x3b\xd0\x10\x10\x39\x4e\xad\x76\x44\x6e\ -\xb6\x75\x9c\xdb\xdb\xf8\xfa\x71\xd5\x1d\x28\x38\x10\x89\x0d\x5e\ -\x14\x63\xde\x03\x3f\x51\x1d\xb2\x42\xcc\xbf\x9d\xcd\xfc\x08\x82\ -\xfd\x5a\x2c\x7e\xca\xe4\xe9\x45\x64\x1c\x38\x81\xea\x25\xd7\x89\ -\xba\x82\x12\x63\x46\x01\x41\x75\x28\x97\xcd\x4c\x07\x41\xec\xc2\ -\xf9\x90\xe9\x88\x9d\x10\x51\x9e\x39\x2d\xbe\x0e\x60\x79\xf2\xba\ -\x00\xac\x10\xf3\x41\x92\x7b\xa1\xf9\x7d\xb7\xf6\x79\x37\xe6\x15\ -\xd0\xe4\x51\x7b\x2c\x58\x9c\x7b\xfe\xdd\x79\x3c\xed\xc6\xea\x4a\ -\xe4\xd6\x8c\xa8\x7d\xab\x4f\x55\x1f\x03\x88\xc8\xe0\xc2\xab\x27\ -\xaf\xcb\xe5\x07\x2a\x20\x1a\x4b\x84\xd5\xe8\x0c\xce\x0e\x72\x84\ -\xb4\x94\x9b\x63\x95\x1b\xf4\x83\x64\x32\x69\xa9\xe1\x29\x3e\xb7\ -\x6f\x60\x02\x56\x3f\x7f\xbb\x03\x5c\xf6\xc6\x14\xc6\xfe\x8a\x80\ -\x68\x2c\x11\x56\xd5\x7b\x87\xc9\x65\xa9\xbb\xb3\x75\xf2\xd8\x05\ -\x94\xb0\x7e\xcf\xb2\x34\x9e\x4a\xa5\x4c\xa5\xf9\x15\x17\x61\xa5\ -\x55\x5d\xc2\xfa\x91\xdc\xec\xd4\x66\x35\x1f\x50\xd1\x01\x87\xbc\ -\x19\x68\x56\xd5\x99\x68\x2c\x11\x2e\x88\x3b\x82\xf5\x2e\xfc\x6e\ -\xc3\x06\x63\x24\x93\x4c\x26\x23\x00\x2b\xeb\xdb\x35\x5b\x5f\xb5\ -\x00\x85\x31\x81\x09\xf7\x5d\xd0\x2b\xcb\xeb\xdb\xb7\x2d\x11\xe1\ -\x08\xd6\xbb\xa8\xd8\x82\xee\xce\xd6\x49\x45\x96\xbc\x31\x81\x09\ -\x55\x7d\x78\x98\xdc\x9f\xf5\x55\x0b\x48\xa5\x52\xc6\xb2\x34\x0e\ -\xec\x95\x49\xf3\x6d\x7d\xd5\x02\x00\x16\x66\xa7\x36\x45\x64\xb4\ -\xd4\xb8\xc2\xc8\x82\x4f\xeb\x7d\x09\x00\xb8\x70\xa6\xe5\x51\x71\ -\x2b\x0e\xc8\x6b\xb3\xde\xb7\x80\x12\xad\xa8\xd9\x7a\xdf\x02\xe0\ -\xa0\x15\xc6\xa8\x0d\xba\x05\xba\x65\x8c\xda\xb5\x5a\xef\xc2\xf7\ -\xef\x78\x71\x2e\xf3\x06\x08\x57\x4c\xac\x12\x5e\x07\x76\xe1\xe0\ -\x00\x19\x54\xf1\x62\xf4\xf4\x0f\x34\x3a\x8f\x3b\x7f\x12\xb0\x06\ -\x60\xf2\xf4\x1e\x97\x00\x09\xd5\xbb\xb5\x3f\xb8\xb1\xdf\x2d\x50\ -\x4d\x23\xd2\x87\xc8\x78\xc4\x4e\x88\xe6\xf7\xe7\x3d\x67\xb8\x23\ -\xa1\xa7\x7f\xa0\x51\x42\xf5\xbd\xa2\x3c\x00\x0c\xaa\xe9\x82\x28\ -\x6f\x62\xc4\x8e\x0f\x8b\x4a\x9a\x00\x0f\x2a\x45\x30\x28\xa3\xb9\ -\xec\xd4\x7d\x37\x70\xe8\x66\xb4\xf1\xe5\xd3\x4a\x5b\xc7\xd9\x45\ -\x44\x9a\x80\x93\x04\x77\x3b\xda\x01\xde\xa1\x9a\xc8\x65\x33\x2f\ -\x03\xaa\xf9\x8f\xe0\x17\xaf\x0f\x09\xa8\xe3\xe3\x70\xe1\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x07\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xb9\x49\x44\x41\x54\x78\x9c\xed\ -\xd9\x51\x0d\x83\x50\x10\x05\xd1\xa5\xc1\x1a\x0a\xb0\x80\xac\x5a\ -\xa8\x02\xc4\x81\x8c\xd3\xe4\xcd\x18\xd8\xc9\xe4\xfe\xed\x0c\xe4\ -\x38\xaf\xe7\x38\xaf\x47\x3a\x7c\xe4\xf1\x7f\xa0\x00\x5a\x40\x53\ -\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\ -\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\ -\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\ -\x02\x9a\xe5\x03\x6c\xf2\xb8\x7e\x8d\xcf\xb4\x80\xd9\xb5\xc0\xcc\ -\xcc\xfd\xfb\xb2\x25\x2e\xbf\x80\x02\x68\x01\x4d\x01\xb4\x80\xa6\ -\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\ -\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\ -\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x96\x0f\ -\xf0\x02\x2e\x56\x08\x76\x9d\x62\x12\xf1\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x86\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x38\x49\x44\x41\x54\x58\x85\xed\ -\xce\x31\x11\x00\x30\x08\x04\x41\x26\x9a\xf0\x84\x1f\x0c\x13\x11\ -\x50\xee\xf5\xff\xb3\x11\x8b\xb2\x7a\xb2\x7a\x36\x1f\x6f\x33\xbe\ -\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xe0\ -\x03\xf8\x62\x04\x97\x5f\x3b\xc3\x6b\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x00\xcb\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x7d\x49\x44\x41\x54\x78\x9c\xed\ -\xd9\xc1\x0d\x80\x20\x14\x05\x41\xb4\x29\xba\xa6\x10\x8b\x12\xcb\ -\x58\x13\x66\x1a\xf8\x2f\x1b\x6e\x8c\x11\x9a\xeb\xdd\x73\xbd\xbb\ -\xdc\x70\x97\xc7\xff\x40\x80\x7a\x40\x4d\x80\x7a\x40\x4d\x80\x7a\ -\x40\x4d\x80\x7a\x40\x4d\x80\x7a\x40\x4d\x80\x7a\x40\x4d\x80\x7a\ -\x40\x4d\x80\x7a\x40\x4d\x80\x7a\x40\x4d\x80\x7a\x40\x4d\x80\x7a\ -\x40\x4d\x80\x7a\x40\x4d\x80\x7a\x40\x4d\x80\x7a\x40\xed\xf8\x00\ -\x57\x79\xbc\xfe\x1a\x1f\xa3\x7f\x01\x4f\x7c\x1f\x00\x00\x00\x00\ -\x00\x00\x00\x4e\xf0\x01\xb9\x04\x09\xb0\x92\x01\xea\x01\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x0c\xd6\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x0c\x88\x49\x44\x41\x54\x78\x9c\xe5\ -\x9b\x5b\x6f\x5b\xc7\x11\x80\xbf\x25\x45\x8a\x94\x28\x89\x92\xad\ -\xbb\x64\xc9\x4e\x9a\xc2\x41\xe0\x26\x45\xd1\xa0\x48\x0a\xf4\xa9\ -\x7d\xe9\x7b\x81\x16\xfd\xa3\x7d\x2a\x50\xb4\x0f\x41\x90\x36\x4e\ -\x52\x20\x69\x92\xc6\x96\x6c\xc9\x37\x5d\x48\x49\xa4\x2e\xe4\xf4\ -\x61\xf6\x1c\xee\xd9\x33\x87\xa4\xe4\xf4\xc9\x03\x10\x24\x77\xf7\ -\xcc\xce\xcc\xee\xce\x6d\xe7\x00\xb2\x05\xe2\x78\xe3\x40\x9c\xf2\ -\x9e\xfe\x78\x93\x84\x90\xe3\xf9\x4d\x12\x42\x96\x57\x97\xed\xe0\ -\x0e\xf0\x18\x9c\x14\x3c\xdc\x00\x6e\x19\x1d\x25\x60\x32\x8b\x2f\ -\x6d\xaf\x0d\xa1\x66\x12\x10\xe0\x62\xc8\x98\x73\xa0\x67\xb4\x77\ -\x81\xbe\xd1\xfe\x12\xdc\xa9\x8d\x2a\xcf\xa3\x1b\x35\x00\x64\x1b\ -\xb8\xed\x09\x3d\x01\x5e\xf8\x89\xa7\x80\x39\xdf\x2e\xc0\x59\xd0\ -\x3e\xeb\xdb\xfa\xbe\x1d\x8f\xa3\x0a\x34\x81\x8a\xef\x3f\xf7\x34\ -\x54\xfd\xf7\x25\x70\x04\x97\xa7\x50\x39\xf2\x6d\x53\xa8\x20\x9d\ -\x9f\xff\xc4\xff\x9f\xf2\x6d\x0e\x68\x01\xa7\xbe\x7d\x29\xe8\x7b\ -\x01\xee\x71\x31\x6f\x85\x52\x92\x2d\x90\x09\x90\x8f\x40\x56\x8d\ -\x31\x6b\x20\x0b\x46\xfb\x06\xc8\xbc\xff\x3d\x05\x72\x0f\xe4\xae\ -\xff\xcc\x80\xdc\x01\x19\xb2\x23\xa4\xee\xc7\x2c\xa8\xe0\xe5\xae\ -\xc7\x31\xe1\xfb\xe7\x40\x36\xf3\x47\x55\x9a\x05\xed\x1b\x20\xbf\ -\x06\x29\x5f\xf3\x88\xcb\x04\xc8\x9f\xf5\xc1\x5c\xdf\x36\x48\xc5\ -\x68\x7f\xdb\x3f\xb7\xe2\x27\x5b\x8e\xf0\xdd\x1b\x73\x72\x3c\xe3\ -\x25\xff\xdb\x79\x46\xb6\xa0\x75\x4b\xdb\xe5\x2d\x83\xd9\x32\xc8\ -\x4f\x8c\xf6\x09\x90\x3f\xda\xbc\x14\x13\xf0\x91\x7f\x30\x92\x9a\ -\xac\x17\x30\x7f\xc7\x7f\xb6\xed\x15\x96\xed\x6b\x4c\x4e\x60\xa2\ -\xe2\xf6\x59\x15\x4e\x7b\x49\xe7\xcb\xf5\x97\xb3\xcf\xa5\xbb\xb9\ -\x02\xf2\xab\x71\x27\xdf\x1e\x6c\xfb\x50\x63\xca\x14\xc8\x6d\x63\ -\xfc\x2a\xc8\x07\xba\x7d\x4d\x7c\xf3\x5e\x79\x5e\x13\x64\x56\xb7\ -\xbc\xd9\x37\x07\xf2\x00\x64\xd1\xe8\x6b\xfa\x67\x23\xcb\x26\x9b\ -\xfa\xc9\x82\x71\x26\xe4\x17\xe0\x3e\x0d\xfe\x27\xca\xa3\x07\xec\ -\x01\x21\xa3\xab\x70\x79\x0b\x2a\x5f\x0e\xe1\x64\x0d\x78\x5a\xd0\ -\x97\xda\xe1\x1b\x3c\x0b\xf0\x00\xba\x4f\xa0\xf6\x2a\x68\xeb\x28\ -\x5d\x94\xc9\x29\xbc\x98\x37\x98\x30\x90\xc6\xc4\x34\x50\xe6\x1f\ -\xa0\x5a\xbd\xed\xc7\x6c\x01\x2f\x54\xa1\x0f\x05\xf1\xc4\x2c\xf9\ -\xff\x89\xe9\x4a\x34\x78\xd8\x46\xd0\xf6\xc2\xa0\x25\x86\x17\x20\ -\x82\x32\xbc\xe7\x9f\x5d\x02\x7e\x06\x7c\x0e\xcc\xa0\x16\x22\x81\ -\x9c\xd9\x8c\x04\x20\x0d\xd4\xcc\x24\xff\x37\x80\x36\xb8\x5d\x3f\ -\x51\x05\x35\x5d\x9b\xc0\xd7\xe0\xae\xf4\x7c\xb9\x13\x72\x20\xce\ -\x8f\x9b\x42\x7d\x81\x6f\x47\x98\x9f\xf8\xd9\x45\x60\x1a\x35\xa9\ -\x7b\xf6\xb3\xd2\x86\xfa\x0b\xd4\x9f\x58\x01\x7e\x00\x16\x80\xcf\ -\x80\xe7\x80\xb7\x3c\xec\xf8\xe7\x7b\xaa\xdb\xdc\x55\xd1\xc4\x5b\ -\x03\xf3\x26\x5b\x59\xcd\x29\x1b\x5e\x0f\x7c\x1c\x29\x46\xcb\x4c\ -\x2e\xa1\xa6\x72\x46\x3f\x37\x05\x59\xf5\xca\x78\x3d\x6b\x55\xd2\ -\xfe\x99\x81\x7e\x91\x09\x90\xdf\x78\x2b\x11\xb6\x07\x8a\x51\xee\ -\xaa\x8e\x18\x40\xc9\x98\xb5\xaf\x13\xb2\x0b\xae\x17\x8d\x5d\x03\ -\xfe\x0e\xdc\x09\x84\x10\xac\xcc\x61\x53\x19\xe7\x10\xdc\x53\xdf\ -\x37\xe6\xaa\x9b\xe0\x9f\x75\x4f\x80\x03\xc5\x7d\xd8\xcc\xf7\x8b\ -\x03\xd6\x81\xbf\x01\xf7\xb2\x73\xba\x9e\xf2\x22\xeb\x18\x47\xc0\ -\x12\xc0\x14\x70\x16\x31\x0f\x7a\xe6\xbf\xf3\x5b\xe9\x31\x59\x21\ -\xa0\x1a\xb9\xd9\x57\xc6\xdd\xe5\xf8\x3c\x8e\x0b\xee\x52\x71\x37\ -\xfb\xd1\x6e\x08\x3d\xbc\x1e\xf0\x04\x3d\x7a\xe1\x90\x1e\xea\x29\ -\x4e\xc7\x58\x2d\x25\x38\xe7\x57\x2f\x00\xd9\x46\x95\x4c\x29\x30\ -\x77\x07\xc0\x7d\xe0\xd2\x9b\xab\x57\xe8\xee\x09\x4d\x9e\x9f\xd0\ -\xdc\x04\x25\xe8\xfa\xe3\x56\x3b\xc4\xf6\xf7\xa7\x81\x2e\x48\x78\ -\x66\xfb\x3a\x56\xee\x03\x47\xe8\xca\x7f\xad\x63\x05\xa0\x03\x9d\ -\x13\xa8\x2f\x92\xd1\x67\xee\x08\xe4\xa7\xf1\x04\x63\x58\x01\x79\ -\x0b\x2e\x2a\x50\x9d\x46\x15\xd3\x29\x83\xad\xbd\x0b\xfc\x0e\xf8\ -\x4b\x01\x03\x01\x74\xe6\xa1\x9e\x04\x3f\x3e\x4e\xa8\x1d\xf9\xce\ -\x79\xd4\x52\xf8\x1d\xd5\x39\x87\xfa\xe1\x10\x64\x5d\xd4\x3c\xfe\ -\x06\xf8\x24\xa0\xd9\x2b\xcf\x7a\x0d\xb8\x0d\x72\x1e\x2d\x66\x6e\ -\x25\x62\x01\xc4\xd1\xe1\x5d\x60\x1a\x26\x1f\xaa\x12\x74\xfb\xd9\ -\xe1\xb2\x0e\xfc\x03\x0d\x70\x8c\x20\x43\x80\xee\x6d\xa8\x4d\x40\ -\xfd\x25\xb8\x4e\x01\x43\x47\xd9\xbf\x52\x07\x16\xe0\xa2\x06\xd5\ -\x93\xbc\xd6\x4e\x7d\x93\xbf\x02\x6b\xe0\xf6\x82\xce\x36\xc8\x09\ -\xba\x63\xdf\xf6\x9e\x6b\x42\x5b\x9f\xe8\xd8\xc7\x3a\xa0\x0a\x9c\ -\xfb\x09\xee\xa1\xab\xf2\x85\x4d\xb3\x2c\xa1\xdb\xbe\x87\xad\x13\ -\xa6\x81\x55\xa8\xb5\x55\x89\x15\x32\x6f\x80\xeb\xe8\x33\xd5\xb6\ -\x32\x18\x1e\xab\x30\xaa\xa3\x87\xfa\x02\x2b\x05\x88\xbe\xf1\x63\ -\xee\xf9\xe7\x3a\x64\x1d\xb9\x22\x2b\xc0\x06\xf0\x0c\xf5\x01\x8c\ -\x03\x7c\xd8\x04\xba\xe0\xba\x9e\xe0\x48\x31\x1e\xcd\x43\xbb\x86\ -\xae\xc2\xf9\x58\x3c\xdb\x70\x01\x3c\x85\xf6\x24\x1c\x2f\x60\x87\ -\xb4\x5d\xe0\x4c\xe7\x8c\xc1\x9d\xa1\x8b\xfa\x83\xe7\x29\xc7\x8b\ -\x25\x80\x06\xea\x3d\x2d\xe6\xb7\x7c\x02\xcd\x29\x70\xad\x6c\x5b\ -\x22\x84\xcb\xf7\x61\xae\x07\xb3\xaf\xcc\x47\x6f\x04\xb3\xaf\x60\ -\xf6\x52\x71\x5b\x47\xcd\xb5\x60\xae\x20\x16\x61\x07\x35\xdf\x2d\ -\xd4\xc2\x65\xc0\x12\xc0\x34\xaa\x3d\x0b\x94\x9a\x2c\xa3\x6e\xaa\ -\x01\xc7\x4d\xa8\x7c\x0f\xcc\x33\x7e\xec\x3d\x06\x88\x03\x16\xa0\ -\xf2\x9d\xce\x61\xc2\x73\xdb\x59\x72\x97\x40\x19\xdc\x31\xba\xb8\ -\x19\xb0\x04\x20\xa8\x69\xd9\x29\x20\x64\xc2\xb6\xf3\x32\x05\xa5\ -\x64\x22\x7f\x1c\xac\x60\xeb\xda\x10\x6e\xfb\x16\x94\x4a\x5e\xbf\ -\xc4\xc3\xae\x94\x36\xb1\x78\x3a\xd4\x23\x34\xda\x0a\x94\x07\x83\ -\x4c\xbf\x7d\x13\xd5\xb2\xe1\x2a\xcc\x82\x74\x81\x15\x98\xd9\x0f\ -\xfa\x5a\xc0\xbb\xc0\x13\xd2\x8c\x4e\x06\x92\xd4\x19\xa8\x4f\x61\ -\xe5\x05\xe7\xd0\x40\xe7\x07\xfd\x2d\xa0\x3b\x73\x03\xe4\x19\x03\ -\x3f\x23\xc1\x7f\xa6\x7d\x1c\x64\xd1\xb8\x63\xef\x0e\x27\x81\x59\ -\x0a\x31\x61\x35\x72\x49\x48\x99\x47\x83\x8d\x65\x4f\x64\x84\x9c\ -\x1e\x74\x66\xa1\x7e\x00\xc4\x41\xc6\x23\x4f\xd0\xd7\xc1\xe4\x2b\ -\x40\x1f\x3a\x67\x50\xdf\x05\x1c\x74\x6f\x41\x2d\xc9\x2f\x3e\xf3\ -\xdf\xce\xcf\xf9\x05\x9a\x2b\x0c\xe1\x15\x74\x66\xa0\x9e\x08\x2d\ -\x9c\xb7\x89\x2a\xbe\xbe\xee\x86\x54\x57\x25\x79\xcb\x4c\xc2\xc6\ -\x5a\x99\x45\xe0\x4b\x90\xaa\x27\xe0\x25\xb8\x43\x34\xd3\x73\x96\ -\x8f\xfc\xa4\x01\xf5\x32\xb8\xe7\x79\x54\x82\x67\x7e\x01\x38\x46\ -\x57\xec\x1b\x63\x77\xb5\xfd\xf8\x32\xba\xe2\x07\x9e\x8e\xff\x68\ -\x5f\x2e\x7a\x3b\xf1\xa6\xcf\x67\x7f\x43\x9a\x64\x1f\x15\x98\x17\ -\x9a\x6c\x02\x4f\xe0\xa4\x03\x8d\x29\xb2\xe1\xb1\xa9\x03\x4a\xa8\ -\x04\x6f\x83\xdb\x09\xec\xf7\x2d\x6c\xe5\x37\x0d\x47\x05\x69\x68\ -\xa5\x00\xcd\xf4\x6e\x01\x4f\x87\x87\xc4\xa9\x2f\x7f\x1f\x0d\x67\ -\x87\x05\x52\x27\x18\xbe\xbd\x5f\x08\x9f\xb9\x72\x27\xa8\xb7\xba\ -\x01\x8d\x03\xf4\x48\x65\xa0\x48\x09\x2e\xe5\xe3\x01\x28\x20\xbe\ -\x01\xf3\x47\x46\x7b\x02\x65\x25\xb4\xf2\x90\x9c\xb3\x94\x9b\x3a\ -\x51\x78\x9f\x61\xdf\x3f\x84\xb4\x14\x08\x20\x37\x4e\x7c\x6a\x7c\ -\xcd\xea\xb5\x04\xb0\x00\x58\xf6\xdf\xba\x84\x18\x07\x56\x18\x24\ -\x34\x0c\x8f\x31\x81\x9c\x93\xf3\x12\x2e\x8c\xd4\x7b\x06\x8a\x84\ -\x69\xd1\xfa\x0a\x43\x60\x05\x47\xe0\x5a\xe1\xec\x28\xc1\xf4\x07\ -\x3b\xa7\x30\x94\x36\x3c\x3c\xd7\x85\xea\xa8\x7c\xdb\x35\x72\x0d\ -\xee\x0c\x55\xe6\x19\x88\x05\x30\x41\x71\x54\x77\x13\x9b\x5e\x83\ -\x6e\x64\xde\x62\x21\x0c\xbd\xb1\xb9\xa9\x1f\x51\xf4\x5c\xae\x3d\ -\xb6\x02\xcb\x70\x65\x69\xf3\xc0\x3f\xc8\xb4\x97\xec\xf6\x14\x9a\ -\x50\x7b\x66\xd0\x21\x20\x8f\xd1\x24\x0b\xc0\xa3\x02\xfd\x32\x62\ -\x85\xbb\x7d\x8d\x34\x73\xd0\xc3\xce\xd6\x8e\x8a\x05\x7a\x15\x98\ -\xb8\xce\xf6\x4f\xec\x75\x11\xf4\x47\xf4\xbf\x26\xd4\x1c\xc5\x47\ -\x70\xac\x79\x23\x01\x94\x9f\xa1\xf6\x37\xc6\xd5\xb3\x11\x8e\xcc\ -\xf2\x1e\x90\x9a\xa4\x10\xd2\x6d\xff\xc8\x7f\x46\x58\x87\x42\x28\ -\x12\x40\x19\xdb\xb3\xcc\xcd\x11\xeb\x80\x2e\x51\xbc\x1c\x40\x11\ -\xb3\xc3\x08\xbf\xca\xcf\x11\x9f\xf9\x51\xd6\x61\x28\x14\x8d\x1f\ -\x5b\x39\xc6\x02\x48\x72\xe7\x39\x6d\x79\x03\x22\x12\xe8\x93\xde\ -\x27\x16\x29\x3c\x4b\x08\x32\x43\xea\xe9\xdd\x78\xee\x00\xc4\xe7\ -\x17\xb3\x60\x99\xc1\x23\x06\xb7\x38\x3f\x06\x3c\x07\x56\x46\x68\ -\x7b\x22\x21\x94\x50\xaf\xcd\xb8\x70\xc9\xc0\x98\xbe\x49\x12\x4e\ -\xe7\x05\x6a\x09\xc0\x01\xfb\xe4\x2f\x12\x8b\xa4\x7d\x00\x6d\x43\ -\x6f\x64\xe0\x25\xf0\x21\x23\x8b\x13\x9c\xa0\x61\xf8\x47\x0c\xbf\ -\x13\xc4\x67\x80\x8e\x8b\x10\x0d\x7e\x8a\x43\xad\xcd\x2e\x63\xe8\ -\x00\x00\xf1\x8e\xd0\x53\x15\x42\x7a\xb3\x73\x80\x79\x1b\xcb\x25\ -\x34\xaa\x43\x28\x4d\xee\xeb\xfe\x05\x6c\x6a\xde\xa0\x08\x64\x8e\ -\xc1\xe5\xcb\xa6\x45\xf0\x00\xe6\x26\x31\xd3\x6d\xed\x45\xd2\x88\ -\x55\x9a\x68\x6e\xe3\x91\xc7\x35\x32\x1f\x00\x9a\xe7\x9f\x04\x77\ -\x0e\xec\x28\x12\xd9\x40\xad\xc3\xbc\x8f\xbd\x43\x44\x4b\xc0\x19\ -\xc8\x3b\x44\x91\x16\x9a\x81\x59\x43\xa3\xba\x26\x70\x01\x17\x5b\ -\x5e\xc7\x58\x4e\xcf\x29\x1a\x19\x2e\xe9\x58\x1e\x00\xff\x06\x89\ -\x4d\x73\x92\xd9\x49\xf2\x01\xc9\xff\x24\x84\xee\x78\xfc\x7b\x7a\ -\xaf\x09\x3e\x83\x9d\xf3\x49\x62\x01\x74\x7c\xdb\x32\x7a\x1e\xd1\ -\x0b\x05\x8e\x3c\xbd\x02\xec\x67\xb7\xb1\xa0\xb9\x43\x59\xcf\xe6\ -\x10\xd3\x73\xf7\x4f\x70\xed\x60\x8e\x82\x3c\xa3\x05\x02\x9a\x38\ -\xd9\x8d\xe6\x5c\xd3\x60\x2d\x61\x3c\x09\x87\xc5\xa1\xbb\xfa\x38\ -\xdb\x0e\x0c\x0a\xb6\x32\xd9\xe9\xf8\x08\x84\x57\xd7\x16\xec\xa1\ -\xc1\x8d\x05\xcf\xc8\x14\x56\xe0\x6f\x65\x5f\xfb\x6e\x30\xb6\x0e\ -\x2b\x14\xe6\x24\x93\xc0\xcb\x84\xe4\x3a\x3e\xa3\x38\x8b\x94\xe0\ -\x85\x6d\x0a\x5d\x5f\x89\xb2\xea\x6d\xdc\x15\xd0\xf2\x67\x30\xc9\ -\xdb\xbf\x0e\xf3\x09\x04\x42\x68\xdd\x46\x13\x24\x56\x4e\xb2\x1c\ -\xd0\x18\xf7\x2d\xa3\xd6\x68\x2c\x25\xd8\x46\xed\xa5\x19\x3f\xfb\ -\x6d\x6e\x64\x5f\x01\x38\x83\xc6\x32\x9c\x9c\x8d\xe1\x25\x5e\x03\ -\x9c\x28\xce\x99\x15\x06\x65\x77\x31\x2c\x53\x7c\xbc\x92\x1a\x85\ -\x9c\x59\xb5\x04\x70\x86\x2a\x97\x72\x41\x86\x15\x38\xee\x90\xbb\ -\xf7\x4f\xb7\xfd\x57\xd0\x38\xd3\x73\xfa\x63\x81\xac\x2a\x4e\xbe\ -\xc2\xf4\x18\xa5\x01\xad\xae\x2d\x74\x99\x83\xb3\x2e\xca\x53\x4e\ -\x78\x45\xf9\x80\xc4\x66\xbe\x6d\x13\xd4\x3c\x54\x84\xc9\x31\xc9\ -\xb9\xb7\xa7\xe8\x96\x5b\x85\x4e\x41\xa1\xd3\x38\x70\x3e\xab\x38\ -\x92\xea\x4f\xd3\x6d\x9e\x04\x66\x61\x2e\x4e\xd6\x26\xb0\x02\x53\ -\xd3\x01\x4f\x19\x88\x05\x70\x41\x9a\x34\x70\xde\x74\xc9\xba\x8d\ -\xd7\xed\x2b\x72\x4a\xd8\xee\xed\x15\xb0\x07\xf5\x4b\x55\x5c\xb2\ -\x38\x9e\xaf\x2f\xce\x8f\x5d\x81\x49\x8f\x23\x3c\xf3\xa1\x10\x28\ -\x01\xab\x76\xfa\x0e\xd4\x34\x5f\x54\xc0\x7d\xeb\x1b\xea\x44\x56\ -\x20\x36\x83\xf1\x95\xd3\x27\x68\x39\x1a\xc0\x32\x5a\x27\xd4\x0f\ -\xc6\x5d\x02\xbf\x45\xaf\xc7\x97\x0d\x9d\x97\xa4\xa0\x4e\xd1\xf8\ -\xfc\x3d\x2f\x84\x61\x89\x0f\x21\xad\x35\xa0\x81\xba\xd1\x56\x4d\ -\xcf\x25\xf0\x7b\xe0\x53\x06\x97\xa3\x89\x19\x4c\xca\x6b\x27\xf5\ -\x66\x3b\x85\x12\xc3\xdd\x67\xd9\x42\x0b\x0f\xc2\xb6\x86\xf7\x08\ -\x37\xa2\xf6\xa4\x0e\x6f\xcd\x7f\x1b\x56\x43\x1a\xdc\xa8\x46\x30\ -\x7d\x7e\x05\xf3\x52\x45\xaa\x68\x09\xed\x1c\xc8\xbb\xb6\x4e\x90\ -\xf7\xf3\xd6\x4a\x3e\x64\x8c\x1a\xa1\x43\x90\x20\x23\xeb\x4e\xe0\ -\xa4\xab\xf5\x80\x29\xa2\xf0\x8a\xba\x0f\xee\x11\xea\x25\xbe\x06\ -\xb3\xe3\x82\xcc\xa0\x29\xfb\xef\xd1\xcc\xcf\x0e\x79\xc5\xb8\x81\ -\xa6\xe0\xc3\x0b\x9e\xe4\x6e\x22\x03\x96\x00\xba\x40\x95\x4c\x49\ -\xec\xcc\x0b\xa8\x4c\x7a\xc9\x16\x85\xb4\xfb\xd0\xaa\xaa\xce\xb8\ -\x56\x5d\xee\x98\x20\x65\xc5\xdd\xaa\x90\xaf\xfa\x08\x14\x63\x7b\ -\x11\xba\x1d\x32\x1a\x5f\x2a\xa8\x6e\xcb\xd5\x28\x58\xb1\x40\x09\ -\xdc\x9e\x6e\x79\x79\x16\x28\xa0\xa7\xa8\x46\xee\x01\xff\x0d\x98\ -\x0f\x24\x3f\x77\xe0\x05\x94\x84\xbf\xa1\x0b\x7c\x13\x48\xbc\xbf\ -\x55\x94\xd1\xa7\x30\x27\x51\xbf\x04\x39\xc6\xfb\xd0\x68\x91\xb9\ -\xbe\x93\x8a\xd2\xe3\x76\x40\xee\x1a\xcc\x66\xe0\x25\x69\x2e\xc0\ -\xed\xa2\x75\x36\xc9\xd6\x17\x54\xf1\x54\xc8\x66\x8d\x22\x1c\x4e\ -\x54\x80\xec\xa3\xb5\x3f\xf7\xc6\x08\x97\x0d\x68\xdd\x46\x9d\x9b\ -\x25\xe0\xb9\xee\xb0\x9c\x9d\x9f\x26\x5d\xd5\xe3\x26\xba\xea\x65\ -\x54\x79\x76\xd0\xda\xe6\x25\x65\x1e\xd0\xcb\xd8\x8c\x33\x14\xed\ -\x00\x77\x9a\x0d\x57\xdd\x1e\x5a\xc3\xbf\x81\x46\x66\x9f\xa3\x42\ -\x78\x00\xe7\x27\x50\x3d\x52\x22\x0b\xcd\x5b\x5f\xe7\x68\x24\x15\ -\x9b\x49\x1b\x80\x83\x0b\xbf\xbb\xaa\xc9\x0b\x14\x21\x1c\x7b\x66\ -\xbc\xa9\x33\x1d\xcb\x65\xc5\x2f\x4b\x1e\x6f\x12\x23\x7c\x00\x3c\ -\x04\x0e\xc0\xbd\x0c\xc6\x97\xe3\x7b\x46\xeb\x08\xc4\xcc\x74\x3d\ -\x21\x0f\xd1\x82\x45\xd0\x2b\xef\x65\xdf\xbe\x1f\xb4\x1b\x20\x62\ -\xf7\x8b\x83\xea\xa4\x67\xb0\x53\xe0\xc5\xad\x8f\xc0\x7d\x05\x4c\ -\xc1\xd1\xf7\xd9\xeb\x39\x71\x9e\xb6\xf8\xcc\x8f\x93\x42\x93\x3b\ -\x03\xe7\x27\x53\x2e\x5f\xcf\x5a\x07\xf0\x66\xe8\x7d\xec\x44\x49\ -\x32\xe6\xff\x50\x2e\x0f\xba\x00\xf2\xf3\xbc\xf9\x95\xa6\x5a\x8a\ -\x5c\xb9\xfc\x1d\xcc\xb2\x5e\x1b\xf9\xc7\xd8\x2f\x4c\xac\x92\x7b\ -\x61\x42\x1c\xfa\x82\x85\xf1\x02\x43\x3a\x66\x7b\xcc\x89\x43\x9c\ -\x05\xcf\x88\x43\xdf\x18\xf9\xa5\xd1\x57\xce\xfa\x2b\xa9\x10\xaa\ -\x8c\xff\xc2\x44\x8a\xe8\x4f\x05\x4e\xc8\x46\x5e\x08\x00\xf2\x1e\ -\xfa\xca\x4a\xee\xa5\x04\x5e\xeb\x95\x99\xb4\xad\xe4\x9d\x9f\xb7\ -\x40\xde\x31\x9c\x9f\xb2\xa5\xe5\x3d\xf3\x7f\xc8\xe3\x2b\x9e\x3c\ -\x91\x5a\x59\xa5\x16\x7b\x80\xe0\x77\x82\x71\x7d\x2d\x1b\x7e\x6b\ -\xde\xd3\x4f\x2b\x74\x9e\x2a\x8c\x7e\x69\x6a\xca\x8f\x09\x04\x2f\ -\x2b\x0c\x5e\xbe\x2a\x7a\x39\x6a\x1e\x33\x66\x91\x2d\xcf\x43\x29\ -\xbf\x9b\x15\x62\x44\x86\x93\x23\x9b\xa8\xb6\xf5\x35\xba\xb4\xfc\ -\xef\x1a\x6a\xe6\x1c\x7a\x01\x72\xc1\xe0\xb5\xb9\x19\x40\xa0\x37\ -\x0d\xe5\xc4\x29\x4a\x4a\x64\x7b\xc1\xff\xe4\xf6\x26\x79\x6d\x2e\ -\x28\x97\x4d\xe9\xeb\xfa\x71\x0e\x35\x61\xa7\xfe\xf7\x24\xaa\xc4\ -\x7d\x01\x06\x1d\x54\xa1\xce\x06\x78\xf6\x06\x4e\x93\xed\xc0\x8d\ -\xb8\xa2\x8e\x41\x26\x30\x4a\xcd\x3c\x9e\x3a\x79\x2d\x1b\xbf\x38\ -\x59\x42\xaf\xca\x92\x23\x54\x65\xe0\x5f\xe0\x99\x38\x24\x6b\xf3\ -\xac\x17\x27\x85\x41\xe2\x33\x06\xa3\xb4\x36\x7d\xac\x88\xc7\x37\ -\xf7\xd5\x59\xab\xe1\x0d\x80\x0c\xcf\x6f\x1a\xf3\x09\xa8\x10\xfe\ -\x07\xb4\x0a\xfd\x7e\xcf\x22\x5b\xc2\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x02\x1b\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xcd\x49\x44\x41\x54\x58\x85\xed\ -\x96\xb1\x4a\x23\x51\x14\x86\xbf\x93\x64\x13\x54\xb0\x70\x8b\x2d\ -\x04\xc5\x17\x30\xa0\x23\x2c\x82\xec\x2b\x2c\x8a\x8a\x85\x96\x8e\ -\x10\x89\x08\x22\x36\x56\x29\xb6\x08\xbb\xab\x23\x2b\x9b\xb4\x56\ -\x2a\x79\x02\x1b\x41\x04\xc1\x04\xf4\x09\x54\x2c\x54\xd0\x42\x0b\ -\x41\x50\x8f\x85\x4e\x4c\xa2\x33\xce\x24\xd1\x14\xe6\xaf\xee\x9d\ -\x39\x73\xff\x6f\xce\x3d\x73\xe6\xc2\x67\x97\xb8\xdd\xec\x1c\x4d\ -\x36\x85\x1b\xc2\x09\x90\x7e\x84\xf6\x8a\x9c\x94\x23\x84\x8c\x6a\ -\x64\x3e\x97\x36\xaf\xdf\x04\xe8\x1c\x4d\x36\x7d\x69\x8c\x6c\x0b\ -\x44\x2b\x32\x7e\xc1\xc1\x3e\x1a\xe9\xb5\x21\x02\x4e\x81\xe1\x86\ -\x70\xa2\xda\xe6\x00\x02\x51\x91\x9b\x84\x3d\x77\x04\x00\xe9\xaf\ -\xb6\x79\x5e\xca\x80\x3d\x0c\x39\xfb\x17\xef\x79\x36\x15\x77\xad\ -\x97\xb7\x64\x98\x96\xbe\xb6\xb6\x4b\x06\x3e\x46\x75\x80\x17\x35\ -\xd0\x3d\xbe\xd0\x26\x01\xf9\x81\x16\x5f\x37\x26\xac\x49\xa7\x45\ -\x44\xe5\x5e\x85\xfd\x8e\x8b\x6f\x3b\xeb\xeb\x43\x77\x65\x03\xf4\ -\x98\x8b\x33\x8a\xfc\x42\x5f\x29\x4e\x65\xc9\x69\x11\x45\x41\xe1\ -\xb0\xe5\x74\xab\x7b\xfc\xef\x70\x2e\x3d\x7d\xe2\x15\x20\xbf\x05\ -\x86\x69\x8d\x28\x92\x2c\x85\xf2\x23\x85\xbe\x80\x04\x57\x07\x07\ -\xd7\x82\xbe\x01\x40\x66\xcb\x35\x2e\x85\x38\xf8\x7a\xf6\xdd\x6b\ -\x7c\xc1\xdb\x6a\x69\xd7\xfb\xe7\xdd\x54\x7e\x0a\xda\x6a\xcf\x45\ -\x89\x02\xdb\x3e\x01\x8a\xff\x0b\xd9\x54\xdc\xb1\xe8\x4a\x65\x98\ -\x16\x40\x2c\x0f\x24\xea\xf9\xeb\xaa\xf9\x67\x58\x07\xa8\x03\xd4\ -\x1c\xa0\xec\xae\xe7\x2a\x65\xc9\x30\x2d\xc7\xd6\x8d\x72\x64\x0f\ -\x6b\x93\x01\x21\x63\x0f\xdf\x27\x03\x2e\x7a\x3a\x94\xce\xdb\xf3\ -\x8f\xcb\xc0\x63\xda\xff\x14\x9e\x88\xa1\xa0\xfd\x1a\xa6\x75\x09\ -\x34\x57\xc5\x4c\x74\x2c\xfb\x7f\x6a\xc5\x4b\xe8\x73\x06\x54\x37\ -\xaa\x62\x0e\xb7\x12\x08\x6d\x7a\x0d\xce\x03\x48\x28\x34\x0d\x9c\ -\x57\xea\xae\xca\xdc\xee\x72\xec\xd8\x37\xc0\xee\x72\xec\x58\x82\ -\xc1\x2e\x54\x33\xc0\x95\x5f\x5f\x90\x3d\x44\x47\x72\xe9\xf8\x6f\ -\x9f\xcf\x7e\x72\x3d\x00\x27\x99\x79\x91\xf6\x77\x59\xd9\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x95\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x47\x49\x44\x41\x54\x58\x85\xed\ -\xd7\xb1\x0d\x00\x20\x0c\x03\x41\x83\xd8\x29\x2d\x13\x67\x02\xa4\ -\x6c\x16\x31\x84\xe9\xf8\xef\x63\x5d\x1b\x89\x8c\x22\xbb\x22\xbb\ -\x9c\x8d\x65\x1a\xb6\x79\xaf\xe9\x0e\x00\x00\x00\x00\x00\x00\x00\ -\x00\x00\x00\x00\x00\x00\x80\x9b\xf7\x19\x0d\x9d\x47\x8e\x8f\xbb\ -\xb2\xd3\x06\x7c\x18\x63\x85\x7e\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x01\x35\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xe7\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\xb1\x11\xc2\x30\x14\xc5\x9e\x19\x22\x13\x31\x01\xc7\x06\xd0\ -\x30\x11\x0d\x23\x70\x4c\xc0\x34\xa9\xb2\x85\x29\x08\x5d\x3a\xdb\ -\x88\x3b\xa4\xea\x17\xff\x12\x7d\xf5\x4e\x44\xe4\x9f\x29\xa3\x7f\ -\xb0\x3f\x9e\x0f\xa5\xe6\x9a\x24\xb5\xe4\xf2\xbc\xdf\x1e\x3d\xf7\ -\x5b\xd9\x8d\xfc\x78\x92\xac\xc7\x4c\x49\xa6\xcf\x61\x3d\xf7\x5b\ -\x19\x1e\x20\xef\x63\xb6\xe6\x5e\xfb\x4d\x7c\x23\xc0\x4f\x63\x00\ -\x5a\x80\xc6\x00\xb4\x00\x8d\x01\x68\x01\x1a\x03\xd0\x02\x34\x06\ -\xa0\x05\x68\x0c\x40\x0b\xd0\x18\x80\x16\xa0\x31\x00\x2d\x40\x63\ -\x00\x5a\x80\xc6\x00\xb4\x00\x8d\x01\x68\x01\x1a\x03\xd0\x02\x34\ -\x06\xa0\x05\x68\x0c\x40\x0b\xd0\x18\x80\x16\xa0\x31\x00\x2d\x40\ -\x63\x00\x5a\x80\xc6\x00\xb4\x00\x8d\x01\x68\x01\x1a\x03\xd0\x02\ -\x34\x06\xa0\x05\x68\x0c\x40\x0b\xd0\x18\x80\x16\xa0\x31\x00\x2d\ -\x40\x63\x00\x5a\x80\x66\xfc\xa3\xa9\x64\xd9\x9a\x7b\xed\xb7\x32\ -\x3c\x40\x4d\x4e\x49\xe6\x24\xf3\x3a\x77\xdd\x17\x11\x69\xe1\x05\ -\x2c\x27\x22\x30\x10\x9e\x42\xf3\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x01\x51\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x03\x49\x44\x41\x54\x78\x9c\xed\ -\xd6\x21\x4e\xc4\x50\x14\x85\xe1\x73\xfb\x9a\x0a\x04\x0a\x3c\x1b\ -\x20\x21\x81\x04\x8b\x83\x05\xb0\x06\xdc\x4c\x48\x58\xc0\x50\xcf\ -\x18\x40\xa2\xf0\x48\x12\x70\xd8\x51\x84\x1d\xa0\x48\xc8\x38\x04\ -\x99\x4c\xda\x5e\x2c\x79\x0f\x70\x7d\x93\xd0\xff\x93\xe7\x56\x9c\ -\x1e\xd3\x4a\x00\x00\x00\x00\x00\x00\x00\x00\x00\xc0\x20\xd8\xdf\ -\x67\xb7\x83\xc9\x79\xc8\x53\xa5\x1f\x4f\x52\xa7\xba\xee\x7e\xbb\ -\xff\x38\xc0\xee\xc9\xc5\x86\x59\x35\x95\x74\x2c\x69\xad\xa7\x6e\ -\xb9\x2c\xe4\x7e\xdf\x56\xc5\xf8\xf9\x7a\xf4\x16\x1f\x93\x01\xf6\ -\x47\x97\xeb\xcd\x52\x2f\x26\x6d\x65\xa9\x97\x8b\x69\x1e\x9a\x6e\ -\x7b\x76\x73\xfa\xfe\x3d\x2e\xe2\xe7\xda\xa5\xea\x7f\xf7\xf2\x92\ -\xe4\xda\x6c\x42\x31\x8d\xe3\x64\x00\xb9\x1d\x66\x29\xb4\x02\x26\ -\x1d\xc5\x59\x3a\xc0\xc0\xa4\x03\x98\x3f\xae\xa0\x47\x16\x2e\x3d\ -\xc4\x59\x32\x40\xa8\x34\x71\xe9\x35\x4b\xa3\x9c\x4c\xf3\xb2\xed\ -\xce\xe2\x38\x19\x60\x76\x35\xfe\x08\x65\xb1\x27\xe9\x56\xd2\x67\ -\x8e\x6e\x3d\x5b\xc8\xfd\xae\x2d\x6d\x27\xfe\x02\x48\xfc\x08\x01\ -\x00\x00\x00\x00\x00\x00\x00\x00\x00\x43\xf1\x05\xad\xf1\x3c\x35\ -\x36\x50\x8e\x69\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\ -\x00\x00\x01\x8b\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x3d\x49\x44\x41\x54\x58\x85\xed\ -\x93\x3f\x2f\x43\x61\x14\x87\x9f\x73\x5b\xc1\xd0\x88\x6f\xd0\x5d\ -\x62\xbb\xda\xc9\x62\x34\x48\x2b\x6c\xc2\x66\xf0\x09\x24\x12\x3a\ -\x58\x7c\x01\x7f\xd2\xc1\xaa\xf4\x76\x31\x4b\x2c\xa2\x9d\xd4\x07\ -\x10\x2c\xc2\xa2\x93\x84\xd4\xfb\x33\x50\x4d\x6c\xf7\xbd\xc9\x5d\ -\xdc\x67\x3b\xc9\x7b\x7e\xe7\xc9\xc9\x79\x21\x23\x23\xe3\xbf\x63\ -\xb1\x5e\x4b\x56\x6a\xc9\x01\xbc\x9b\x4d\xde\x54\xac\x97\x54\x20\ -\x88\xf5\x7a\x67\x28\x3c\x2a\xbd\x2e\x35\x94\x4b\x57\xa0\x66\x4e\ -\xd8\xf2\xa0\x7c\xcc\xab\x9f\xae\x00\xd0\xa9\xda\xa9\xd0\xee\xa0\ -\x2e\x45\xae\x9b\xaa\xc0\xb7\x44\x6e\x0b\xb8\xf8\x29\xa7\xcb\xd1\ -\xe7\xbe\xaf\x40\xbc\x23\xfc\x43\x29\x72\x1a\x26\xd9\x7a\xbb\x62\ -\x47\x71\x33\xbc\x36\x30\xa0\xdd\xb5\xe1\x11\x4a\x87\x61\x53\xb3\ -\xa9\x0a\x50\x33\x37\xde\xb7\xc2\x6f\x98\xe9\x32\x5d\x01\xe0\x05\ -\x3e\x80\x7b\xdf\xfe\x64\x02\x92\x15\x46\x5c\x1d\x28\x02\xcf\x39\ -\x59\x31\x55\x81\x72\xe4\xb6\x91\xad\x00\x6f\x98\xcd\x5f\x2d\xda\ -\x43\xdc\x0c\xef\x5f\x30\x13\x69\xd5\xd0\x31\xe0\x84\x2d\x74\xaa\ -\x76\xee\x93\xe3\xb5\x81\xb0\xa5\x39\x43\x75\x00\x61\x1b\xbe\xc3\ -\xbd\x04\xc2\x33\x4d\x05\x52\x13\xc8\x9b\xb4\xd7\xa9\xda\x81\xef\ -\xf0\xf8\x02\x92\x05\x81\x1a\xc0\x04\xa6\x93\xeb\xdb\x60\x33\xc9\ -\x70\x80\x7c\xdc\x06\x83\x27\xe0\x6e\xac\x17\xac\x51\x33\x97\x54\ -\x20\x23\x23\x23\xe3\x0b\x46\x70\x62\xa1\x9b\x7f\x53\x6a\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\xb2\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x64\x49\x44\x41\x54\x58\x85\xe5\ -\xd6\x31\x4e\xc3\x30\x14\xc6\xf1\xff\x73\x93\x72\x03\x3a\x70\x82\ -\x96\x89\x89\xb9\x8d\xc4\x58\x04\x5c\xa1\x03\xb7\xf0\x35\x90\xe8\ -\x15\x2a\x04\x2c\x88\x42\x7b\x08\xa0\x9c\x80\x01\x26\xf6\xd2\x98\ -\x81\x86\xa2\xa6\x21\x76\xe2\x84\x01\x8f\xf6\x93\x7f\x9f\x6c\xe7\ -\x29\xf0\xdf\x87\xd4\x89\x45\xfd\x41\x4b\x85\xe6\x12\xe4\x65\x3c\ -\x1a\x9e\x00\xa8\x7a\x71\xa6\x20\xfb\x60\x76\x92\xf9\x5a\x02\xac\ -\x70\xda\xc0\x73\x3c\x97\xc3\x64\xad\xf2\x2b\x48\xe3\x74\xef\xaf\ -\x86\xaf\xb5\x04\xc8\xc3\x2b\x0d\x60\x83\x57\x16\xc0\x16\xaf\x24\ -\x80\x0b\xee\x3d\x80\x2b\xee\x35\x40\x11\xdc\x5b\x00\x5b\xfc\xe0\ -\xe8\x74\xdb\xa8\x8f\x1b\x83\xbc\xdf\x8d\xce\x7b\xe0\xa1\x11\x39\ -\xe2\x13\x60\x4f\x30\xcd\x64\xbe\x54\x80\x02\xf8\x2e\xf0\x28\x71\ -\x70\x9c\xac\x15\xbe\x82\x12\x78\x74\x7b\x71\xf6\x56\x2a\x80\x2f\ -\xbc\x50\x00\x37\x7c\x31\x05\xd3\x01\x9e\x24\x0e\x7a\xeb\xb8\x73\ -\x00\xdf\xb8\x53\x80\x2a\x70\xb0\xfc\x0a\x6c\xf1\xa8\x3f\x68\xb9\ -\xe0\x60\x71\x02\x2e\xb8\x0a\x65\xe2\x82\xe7\x06\x28\x86\xcb\x4c\ -\xe2\x46\x77\x13\xee\xd4\x09\x2b\xc2\x53\x9d\x30\xa8\x0f\x5f\x4c\ -\x81\x0e\x6b\x9d\xb0\x51\x0e\x67\xb9\x69\x36\x1e\xf5\x07\x2d\x09\ -\xcc\xcf\x87\x99\xdd\x09\x0b\xe0\x6d\x90\x59\x3c\x37\xbd\xa2\x0f\ -\x53\x36\x6f\xea\x0b\x5f\xd5\x65\x9d\x90\x02\xd0\x5a\x2b\x15\x32\ -\xce\xc3\x01\x51\x21\xd7\x79\xf8\x7a\x5d\x16\xfe\x1d\x60\x39\xb6\ -\x80\x87\xdf\xfe\x64\xb4\xd6\x02\xd2\xfc\xaa\xcb\xc4\x53\x75\x36\ -\xfd\x00\xad\xb5\xc2\xae\x35\x8b\xe7\xba\xbf\x1d\x9f\xf9\xbe\xa6\ -\x95\x85\xff\xbc\x8e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ -\x82\ -\x00\x00\x03\xe0\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x92\x49\x44\x41\x54\x78\x9c\xed\ -\x98\x4d\x68\x5c\x55\x18\x86\x9f\xf7\xde\x50\x12\x45\xa1\xda\x9d\ -\xe8\x56\x5c\xb7\x64\x22\xa9\x68\x54\x4a\x9b\x42\xd2\x49\x20\xe0\ -\x4a\xb4\xfe\x81\x6b\x7f\x41\x44\xac\x60\xba\xd0\xad\x8a\x05\x57\ -\xae\x9a\x8c\xc9\xa2\x15\x4a\x35\x9b\xca\x4c\xd2\x14\x74\xd3\x9f\ -\x9d\xc5\x65\x44\xd2\xb8\x88\x3a\x73\x5f\x17\xa1\x32\xb9\xf7\x26\ -\x99\x99\xdc\x99\x44\x7a\x9e\xe5\xf9\xee\x39\xe7\x7d\xbf\xf3\x73\ -\xcf\x39\x10\x08\x04\x02\x81\x40\x20\x10\x08\x04\x02\x81\x40\x20\ -\x10\xb8\xb7\x50\xba\x60\x70\xc6\x1f\x4a\xfe\x00\x88\x0d\x89\xc0\ -\x7b\xa0\xab\x30\x0c\x12\x44\x40\xc3\xd6\xc7\x8b\x93\xfa\xa8\x39\ -\x9e\x49\x40\x69\x36\xa9\x03\x71\xaf\x04\xf6\x98\x46\x6d\x22\xea\ -\x6b\x2e\x88\xf6\x4a\xc9\x7e\x21\x93\x00\x5b\x67\xd0\xff\x7b\xda\ -\xe7\x22\x6c\xeb\x4c\xb6\x38\x87\xd2\x8c\x47\x90\xe7\x80\x07\x52\ -\x21\x03\x49\x17\xe4\x15\x49\x44\xd6\xd7\x9a\xa4\xb1\x6a\x59\x0b\ -\xe9\x8f\x73\x13\x00\x50\xaa\xf8\x30\xf6\xf7\xc0\xa1\x54\x0d\xe3\ -\xfd\x99\x04\x43\xa4\xac\xa7\x15\xa4\xe3\xb5\xb2\x96\xf3\xea\x6c\ -\x99\x00\x80\x23\x73\x7e\x3c\x6e\xf8\x12\xf0\x68\xaa\x23\x6b\xbf\ -\xcd\x04\x11\xe1\xcd\x7e\x24\x6e\xd7\x23\x1d\xbb\x3a\xae\x9b\x5b\ -\x55\xdb\x76\x13\xbc\x3a\xae\x9b\x49\xa4\x61\xe0\xc6\xe6\xbe\x90\ -\xb5\x7f\x36\x50\xe7\x98\x07\x6e\x34\xa4\xa3\xdb\x99\x87\x1d\x66\ -\xc0\x5d\x0e\xcf\xfb\x50\x5f\xc3\x17\x31\x47\x52\x5d\x03\x6a\xb4\ -\x23\xb6\x78\x1c\xa7\x6d\x08\x96\xfe\xe9\xd3\xe8\xf2\x98\x56\x76\ -\xaa\xdd\xd2\x28\x2e\x8f\x69\xa5\x2f\xd2\xb3\xc0\x0f\x9b\x23\x02\ -\x88\x51\x4b\x79\x2c\x14\x6f\x8c\x78\x9e\xf9\xcb\x71\xac\xe7\x5a\ -\x31\x0f\x6d\x9c\x03\xae\x8c\x6b\x6d\x60\x55\x27\x05\x95\x1c\x35\ -\xb1\x5b\x9c\x4d\x45\x60\x90\xf2\x97\xe0\xec\xc1\x7e\x9d\xbc\x32\ -\xae\xb5\x56\xdb\x6a\x6b\x1d\x2f\xbc\xa4\xf5\xfe\x83\x9a\x92\x7d\ -\x2e\x1d\x93\x89\x9c\x5d\x87\x85\x63\x23\x39\xab\x5b\xf6\xb9\xc7\ -\xea\x9a\xba\x38\xaa\xbf\xda\x69\xaf\x33\xc1\xb6\x4a\x95\x64\x1a\ -\xf4\x56\x8e\xc0\x44\x5d\x3a\x48\x35\x9d\xeb\x37\x21\xfb\x6c\x75\ -\x22\x7a\x17\xa9\xed\x7e\x77\x35\x62\x83\x15\xbf\x2d\x7b\x3a\xa7\ -\xd9\x04\x5c\x68\x12\x8c\x24\x9c\x3d\xb9\x4a\xef\x2c\x96\x75\xb6\ -\xd3\x76\x77\x3d\x65\x87\x66\xfc\x8a\xe5\x2f\xc9\x8c\x4c\x71\x49\ -\xd8\xc2\x7c\x62\xe9\xb5\xc5\xb2\x32\xcb\xb1\x1d\x0a\x59\xb3\xa5\ -\x8a\x27\xb1\xbf\x05\x0e\x34\x97\x5b\xb6\xac\x5d\x1d\x98\x8c\x23\ -\x65\x7f\x33\x7f\x0b\xbd\x50\x9d\xd0\xec\x6e\xda\x86\x02\x77\xee\ -\xa1\xf3\x7e\xde\xf2\x77\x88\xfb\x9b\xcb\x8d\x2d\x3a\x4e\x42\xde\ -\xb9\xfe\xcf\x44\x3a\xb5\x54\xd6\xe5\x0e\xdb\xdc\x44\xa1\xbb\xf6\ -\x93\x15\x0f\x26\xf6\x05\xe0\xe1\x54\xa8\x93\x4b\x54\x9e\xf9\xdf\ -\x13\xeb\xc4\xd2\xa4\x96\x3a\xd5\x98\xa6\xf0\xdf\xd6\xd0\xac\x9f\ -\x30\xbe\x04\x3c\x92\x0a\x19\x91\xec\xf8\x7f\x10\xd8\xb9\x97\x9a\ -\xdf\x84\x8e\x55\x27\x74\xbd\x38\xb5\x5d\x78\x10\xa9\x4e\xe8\x7a\ -\x6c\x0d\x03\xb7\x52\x21\xb1\x61\x6c\x47\x4d\x39\xe6\x6f\xd5\xeb\ -\x1a\x2e\xda\x3c\x74\xe9\x45\xe8\xa7\x49\xfd\x1a\xa3\xa7\x80\x6b\ -\xa9\x90\x8c\xb7\x79\x6e\x73\x9c\x73\xa9\xb9\x76\xa0\xae\xa3\xcb\ -\x53\xba\x5d\xb0\xcc\x0d\x41\xdd\x68\xf4\x2e\xa5\x0b\x7e\xd0\xeb\ -\x9e\x17\x3c\x9d\xd3\x75\xe3\xbf\xf7\x56\x09\x9c\x9b\x98\x05\xfa\ -\x35\x5e\x1b\xd5\x9d\x6e\x69\xec\xea\x95\xb6\x36\xaa\x3b\xf7\xad\ -\xea\x38\x30\x9f\x8d\x3a\x66\x63\x00\xb4\x85\xf9\xb9\x81\x55\x9d\ -\xe8\xa6\x79\xe8\xd1\x05\xe6\x99\x1f\xdd\xb7\xfe\x47\xf2\xb5\xd1\ -\x8b\x2d\x55\xb0\xbf\x19\x78\x28\x7a\x75\x61\x44\xf5\x2e\x4b\xeb\ -\xcd\xa3\xc6\xc2\x88\xea\xd5\x9f\xa3\x97\x85\x3f\xdf\xe9\x5b\xe3\ -\xcf\x6a\xbf\x44\xa7\x7b\x61\x1e\x7a\x78\x85\x05\xc0\xd6\xe0\x2c\ -\xef\x49\xfe\x24\x5f\x8d\xde\xaf\x9d\xe2\xd3\x4e\x2e\x35\x9d\xd2\ -\xfb\x97\x0c\x60\x70\xc6\xaf\x4b\xfe\xa2\xa9\xc8\x48\x6f\xd4\xca\ -\xfa\xaa\xd7\x5a\xf6\x24\x01\x00\x43\x33\x8d\x69\x4b\xa7\x81\x06\ -\xd6\x9b\xb5\x49\x9d\xdf\x2b\x2d\x81\x40\x20\x10\x08\x04\x02\x81\ -\x40\x20\x10\x08\x04\x02\x81\x7b\x89\x7f\x01\x9b\xd6\x34\x0b\xef\ -\xec\xcc\xa6\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\x1d\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\xcf\x49\x44\x41\x54\x78\x9c\xed\ -\x98\x4f\x6c\x54\x55\x18\xc5\xcf\x79\x4f\x06\x89\x85\x05\xd4\x44\ -\xaa\x25\xee\xc0\xa5\x7d\x6f\xea\xc2\xc4\x14\x0d\x0d\x74\xa1\x94\ -\x85\x0b\x56\x16\xc2\xcc\x88\xb1\xba\xc0\xb0\xc2\xb1\x31\x21\x21\ -\x90\xc8\xcc\x0b\x8a\x48\xc0\x98\x18\x17\x35\xca\xaa\x25\x8d\x50\ -\x12\xa8\x89\x69\x47\x97\x86\xc4\x95\x7f\xaa\x89\x92\x98\x00\xa9\ -\x14\xdf\xfd\x5c\x30\x95\x79\x7f\x3a\x9d\x7f\x6f\xa6\xe2\xf7\x5b\ -\xbe\x6f\xee\xbd\xe7\x9c\xb9\xf7\xce\xf7\x06\x50\x14\x45\x51\x14\ -\x45\x51\x14\x45\x51\x14\x45\x51\xfe\x5f\xb0\x53\x0b\xf7\xe7\x0a\ -\xc3\x46\x78\x0a\x80\x45\xe0\xa3\xd9\x0f\x47\x8f\x74\x42\x87\xdd\ -\x89\x45\xd3\xb9\xe2\x01\x11\x7e\x02\x60\x03\x80\x2e\x00\xcf\x6d\ -\x76\x76\xfe\xf2\x6b\xe9\xe2\xb7\xed\xd6\xd2\xf6\x00\x9c\x6c\xf1\ -\x30\x80\x02\x42\xbb\x8f\xe4\x8b\x3d\xe9\xa1\x85\xf9\xb9\xc9\x99\ -\x76\xea\x69\x63\x00\x42\x27\xdb\x7d\x9c\xc0\xdb\x55\x3e\xb4\xa3\ -\xc7\xdd\xf5\xc8\x7c\x69\xe2\x2b\x60\xac\x2d\xaa\xda\x72\x07\x0c\ -\xe4\xf3\x0f\xdd\xfa\x6d\xe3\x19\x80\x23\x35\x0d\x10\x9c\xeb\xda\ -\x7c\x23\x7b\x65\x6c\xec\xef\x84\xa5\x25\x1f\xc0\xc0\x2b\xe7\x1f\ -\xbe\xb5\xf6\xe6\x67\x00\x76\x87\x6b\x02\x31\x00\x41\xc0\x8a\xd6\ -\xf8\xe5\xfa\x3b\x5d\x7b\xaf\x7c\x3c\xf2\x57\x92\xfa\x12\x0d\xe0\ -\x99\xd7\x8b\x1b\xfc\x45\x5c\x00\xb0\x3d\x66\x65\x1f\x72\x5f\x85\ -\x08\xec\xb0\x18\x02\x97\x53\x77\x17\x76\xcf\x9c\x3b\x7c\x33\x29\ -\x8d\x89\x05\xf0\xf4\x48\xf1\x51\x7b\x0d\x26\x41\x38\xc1\x8a\x00\ -\xa0\x1f\xab\x44\xc4\x8e\x91\x34\xe7\x2f\x62\xe8\xbb\xf3\xa3\xbf\ -\x27\xa1\x33\x91\x00\x9c\xcc\xc9\x2d\xa4\x35\x05\x60\x6b\xa8\x24\ -\x00\x4c\x75\x39\x62\xc5\xe8\xba\x4e\xdb\xde\x31\xfb\xfe\x6b\x3f\ -\xb5\x52\x27\x10\x73\xf6\x9a\xa5\xef\xe0\x7b\x4f\x91\xd6\x0c\xea\ -\x36\xbf\xf4\x11\x18\x80\x12\x2a\x6c\x15\xdf\x9f\x71\x32\xde\xb6\ -\x56\xe9\x5c\xa2\xa5\x01\xa4\x0f\x9c\x4c\x5b\xbe\x7d\x15\xc0\x13\ -\xc1\x0a\x6b\x30\x5f\x89\x18\x08\xc2\x21\xf4\x92\x72\xad\x3f\xeb\ -\xb9\x4d\xca\x0c\xd0\xb2\x00\xd2\xd9\xc2\x0b\x62\x59\x97\x01\x6c\ -\xaa\x7c\x2e\x02\x01\xa4\x0e\xf3\x65\x18\xbb\x13\x36\x19\xc8\x74\ -\x5f\xce\x7b\xbe\x09\xa9\x01\x5a\x12\x40\x3a\x5b\xdc\x23\xe0\x04\ -\xee\xb5\xb5\x95\x08\x59\xcf\x37\x1f\x26\x76\x27\x74\x59\x22\x93\ -\xfd\xb9\xc2\x70\xe3\xf3\xde\xa7\xe9\x00\xdc\xac\xb7\x5f\x80\x71\ -\x00\xa9\x40\xe1\x9e\xf1\x26\xcc\x57\x9d\x27\x65\x84\x9f\xbb\xb9\ -\xe2\xbe\x66\xa7\x6f\xaa\x15\x76\x33\xc5\xb7\x40\x78\x88\xdc\xda\ -\x12\xb7\x7d\x9b\x42\x08\x30\xb8\x0e\x01\xbc\xf4\xb8\xbb\xf3\xf6\ -\x7c\xe9\xe2\xd7\x8d\xce\xdb\x60\x00\x42\x37\xb3\xf1\x18\xc8\x77\ -\x22\x15\xc0\xb0\xc5\xe6\x81\xb2\x73\x0a\x00\x86\xc2\xe6\x60\x8f\ -\xbb\x6b\xdd\x7c\x69\xe2\x52\x23\xef\x0f\x75\xf7\x01\xe5\xbe\xfe\ -\x34\xc0\xfd\xe1\x9a\x40\x12\x31\x1f\x58\x83\x20\x25\x7a\x74\x49\ -\x9c\x7d\xf2\xc6\x63\xb9\xf1\xf1\x97\xa3\x4d\x56\x15\xea\x0a\xa0\ -\xdc\xd7\x7f\x0a\x60\x4f\x54\x98\x18\x4a\xb2\xe6\x2b\xd6\x22\x85\ -\x71\xf7\xd7\x17\x7f\xa6\xb0\xf7\x07\x6f\xf4\x4e\xad\x73\xd5\x1c\ -\xc0\xb3\xfb\x8e\xad\x5f\x5c\xb3\xee\x82\x00\xc1\x9f\x20\x01\x84\ -\x30\x44\xe4\xb6\x4e\x14\x81\x90\x88\x0d\xe1\xd2\xda\xbb\x0b\xc3\ -\xb5\xbe\x3f\xd4\x14\x80\x93\x39\xd1\x4d\xa6\x26\x01\x04\x9b\x10\ -\x11\x90\xf4\xdb\xea\x3c\x8c\x88\x1d\xbd\x16\x30\x2b\x66\x71\xa8\ -\x74\xe6\xd0\x1f\x2b\x0d\x5f\x31\x80\xf4\xc1\x53\xbd\xe2\xfb\x53\ -\x00\x42\x6d\x28\x1b\x6b\x70\x12\x40\x40\x8b\x90\xa0\x17\xe1\xf7\ -\xb6\x91\xc1\x6f\xce\x8e\xfe\x5c\x6d\x6c\xd5\x00\x9c\x8c\xb7\x8d\ -\x94\x29\x00\xbd\xa1\x15\x05\xa4\x69\xf3\xae\x5f\x01\x5a\x08\x87\ -\x00\xfc\x08\xcb\x0c\xce\x7d\xf0\xe6\xf5\xe5\x46\x2d\xdb\x08\xf5\ -\x67\x3d\x97\x94\xab\x88\x35\x8f\x55\x66\x1e\x28\xef\xc6\xb0\xa8\ -\x2d\x30\xd6\xb5\xbe\x57\x0b\x4e\xdc\x08\x60\x99\x00\x9c\x4c\x61\ -\xbb\x81\x4c\x03\xe8\x0e\x2c\x81\x25\xf3\xab\x16\x23\xd1\x10\xba\ -\x2d\xc3\x69\x37\xe7\x0d\xc4\x0d\x88\x1c\x81\x74\xae\x70\x44\xc4\ -\x1a\x8b\xd9\x4e\xff\x71\x28\xa4\xc9\xcf\x9e\x7e\xe3\xdd\xca\xa7\ -\xd1\xff\xe2\x0c\xf3\x0f\x9e\x79\xa0\xdc\xa9\xe4\xc3\x4f\xa3\x47\ -\xe0\x01\xb4\xfe\x2f\x31\xde\xa2\x3b\x80\x3c\x2a\xad\x78\x8b\x5b\ -\x65\x08\x60\x84\x3c\xda\x69\x1d\x8a\xa2\x28\x8a\xa2\x28\x8a\xa2\ -\x28\x8a\xa2\x28\x4a\xa7\xf9\x07\xee\x73\x3f\xf5\xa2\x1e\x57\x1f\ -\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\xc0\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\x72\x49\x44\x41\x54\x58\x85\xe5\ -\x97\xcf\x4e\x13\x61\x14\xc5\x7f\xf7\x6b\xbb\x22\x31\x51\xc0\x08\ -\xbb\xbe\x82\xd0\x8a\xd1\x18\x4c\x5c\x09\x71\xc5\x1b\xd0\xd0\x26\ -\x40\x49\x8c\xc2\xb2\x69\x58\x95\x44\x23\x2d\x90\x42\xc0\xc4\xb0\ -\xc1\xbd\x4d\xd8\x28\x89\x89\x8a\x40\x7d\x05\x58\x29\x11\x31\x71\ -\xc1\xaa\x76\xae\x8b\xce\xd4\xb1\xd0\x3f\x53\x06\x17\x7a\x96\xe7\ -\xde\x99\x73\xe6\xdc\x6f\x32\x77\xe0\x7f\x87\xd4\x12\xfd\x89\xdc\ -\x2d\x54\x67\x10\x06\x50\xba\x7d\x52\x39\x42\xd9\x46\x24\xb3\x97\ -\x9f\x7c\x57\xd7\x40\x24\x3e\xff\x48\x91\xb9\xb3\x8c\xf9\x04\x4b\ -\x95\xe9\xe2\x4a\xf2\xc9\x29\x03\x7d\x63\xcf\x6e\x8b\x98\xb7\xc0\ -\x0f\x44\x93\xa1\x52\xb9\xf0\x61\xed\xe1\x77\x3f\x54\x6f\x8e\x3e\ -\xbd\x52\x0a\x05\x86\x50\xc9\x02\x97\x10\xb9\xe3\x24\x11\xac\x3a\ -\x11\x33\x0d\x08\xa2\xc9\xbd\xfc\xd4\xba\x1f\xc2\x0e\xec\x07\x59\ -\xef\x8f\x67\x05\x78\x81\xea\x0c\xf0\x00\xc0\x54\xbb\x84\x01\x80\ -\x50\xa9\x5c\xf0\x53\xdc\x0d\x13\x34\x85\x8a\x14\x37\xaa\x5c\xb5\ -\x6a\x1f\x38\xbf\x62\x3f\x0b\x3b\x8b\x13\xc7\x15\x29\xae\x3a\x5c\ -\xb0\x7e\x7b\x7b\xb8\x9e\x58\x18\x36\x6a\xad\x00\x58\x62\xc6\x3e\ -\xe5\x27\x5e\x35\xea\xf7\xd5\x40\x34\x96\x0b\x5b\x6a\x6d\x00\x1d\ -\x00\xb6\x91\xde\x46\xd7\x98\x46\x45\x4f\x48\xa5\x8c\x15\xd0\xe7\ -\x8e\x78\xab\xf0\xcd\x40\xe4\xb0\x2b\x01\x0c\xba\x39\x55\x66\xff\ -\x8a\x81\x68\x2c\x17\x56\x74\xae\x86\xde\x2a\xf6\x1c\x2f\x5f\xbc\ -\x81\xb3\xa3\x3f\x31\x65\x19\x25\x9d\xb6\x9a\x5d\xde\xf4\x10\x36\ -\x3b\xd5\x91\xc3\xae\x84\xa2\x83\x6e\x4e\x95\xc7\x3b\xab\x93\xfb\ -\xad\xf8\x6f\x9a\x80\x2d\xde\x03\xf4\x18\xb5\x36\xa2\xb1\x5c\xd8\ -\xa9\x9d\x27\x7a\x07\x5e\x5f\xc3\x0e\x2b\xa0\x6b\xa4\x52\xf7\x00\ -\xac\xc3\xf6\xa3\x6f\xd9\x80\x2a\xb3\x22\x2c\xb9\xa8\xbb\x7d\x5f\ -\x3a\xe3\x46\x44\xce\x13\xbd\x83\xa6\x23\xb0\xe3\xdc\x72\x73\x22\ -\x2c\x29\xba\x58\xd3\xea\x29\xfa\x96\x0d\x90\x4e\x5b\xa6\x2c\xa3\ -\xc0\x49\x83\x2e\xcf\xd1\xb7\x6e\x00\xd8\x59\x9d\xdc\x17\x64\xba\ -\x5e\xbd\x9d\xe8\x3d\x19\x00\xd8\xbd\xf6\x2d\x4f\xcd\x28\x6c\xb4\ -\x15\xbd\x67\x03\x75\x46\xd1\x76\xf4\xde\x0d\xe0\x8c\x42\x47\x14\ -\x0e\x14\x0e\x04\x1d\x69\x37\x7a\x07\x9e\x3f\xc7\xbb\xcb\x53\x9b\ -\x40\xb8\x69\x63\x8b\x70\xaf\x64\x47\x50\x59\x20\xfd\xba\x79\x2d\ -\xa2\xe3\x0b\x9d\x15\x29\xbe\x9e\x36\xa0\x6c\x03\x94\x42\x81\xa1\ -\x8b\x32\x60\xfd\xb4\x86\x2a\x52\x7c\x74\xb8\xdf\x23\x10\xc9\xa0\ -\x3a\x8c\x4a\xb6\x3f\x9e\x15\x13\x34\x05\x67\x87\x3b\x2f\xa2\xe3\ -\x0b\x9d\xb6\xf8\x3c\x60\x21\x92\xa9\xca\xba\x1b\xed\x1f\x93\x0c\ -\x7e\x6e\x4a\x7f\xe2\xd4\x8f\x49\xc0\x5d\xfd\x5c\xdc\x7c\xdf\x1b\ -\xb9\xff\x1a\xe8\x16\xb8\x8c\xc7\xf5\xaa\x1e\xec\x99\xbf\x41\x24\ -\x56\x5c\x4e\xbe\xf4\xe3\x9e\xff\x0e\x7e\x01\x29\x72\x01\x2f\x4e\ -\xc0\xa2\xca\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xc0\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x72\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\xb1\x09\x83\x60\x14\x04\xe0\xd3\x21\xc4\x26\xe0\x4c\x59\xc1\ -\xca\x89\xdc\x24\xf3\x08\x69\xc4\x21\x34\xad\xf8\xd7\x2a\xc4\xef\ -\x2b\x8f\x57\xdc\xbb\x04\x00\x00\x00\x00\x00\x00\x78\x82\xea\x18\ -\x4c\xd3\xf7\x9d\x2a\x63\x92\xe6\x86\x3e\x67\x9a\xb3\xa5\xef\xba\ -\xd7\x67\x1f\xd6\xc5\xd9\x7f\x3e\x9f\x24\x6d\xea\x8c\xc7\xb0\x1c\ -\xe0\x61\xca\x01\xb6\x0c\x49\x96\xeb\xab\x9c\x6e\xce\x9a\xe1\xee\ -\x12\x00\x00\x00\x00\x00\x00\x00\xc0\xf5\x7e\x5a\x95\x0d\x08\xf2\ -\x12\x5b\xad\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xa7\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x59\x49\x44\x41\x54\x58\x85\x63\ -\x60\xa0\x00\xb8\x85\xa4\x34\xb8\x85\xa4\x34\x50\x62\x06\x13\x25\ -\x9a\xa9\x01\x46\x1d\x30\xea\x80\x51\x07\x8c\x3a\x60\xd4\x01\xa3\ -\x0e\x18\x70\x07\xb0\x50\x6a\xc0\x7f\x06\x06\x07\x4a\xaa\xe4\xa1\ -\x1f\x02\x8c\x0c\x0c\x07\x76\xad\x99\xd3\x40\xae\xfe\x01\x0f\x81\ -\x51\x07\x8c\x3a\x60\xd4\x01\xa3\x0e\x18\x75\xc0\xa8\x03\x06\xdc\ -\x01\x00\x05\x9e\x09\x3f\xb6\x6d\xc4\xbd\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xf6\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xa8\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\xb1\x0d\x80\x30\x00\xc4\x40\xc2\x1e\x11\xec\x3f\x15\x88\x41\ -\x42\xcb\x06\x47\x61\x77\x5f\xbd\xe5\xb1\x21\xae\xfb\x59\xdf\x7d\ -\x1e\x73\x08\x8f\x5d\x9c\xfe\x89\x02\x68\x01\x4d\x01\xb4\x80\xa6\ -\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\ -\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\ -\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\ -\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\ -\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\ -\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\ -\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\ -\x2f\x70\x51\x04\x80\x66\x61\x99\xa8\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x03\xf4\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\xa6\x49\x44\x41\x54\x58\x85\xe5\ -\x97\x4f\x68\x1c\x55\x18\xc0\x7f\xdf\x9b\xec\x26\x5a\x93\x88\x96\ -\x98\x9a\xdd\xc9\xee\xc6\x80\x86\x3d\x78\x90\x42\x0f\xf5\x4f\x29\ -\x2d\x22\x6d\xaa\xa0\x22\x52\x0b\x55\xf1\xd0\x9b\x20\xa4\x78\xe8\ -\x41\xd1\x80\x27\xa5\x28\x88\x20\x88\x5e\x0d\x36\x6a\xb5\x60\x69\ -\x4f\x52\x1a\x28\xc2\x2a\x91\x6d\xb2\x7f\x66\xb6\xab\x78\x90\xd8\ -\x58\x35\x99\x79\x9f\x87\x9d\x5d\x93\x6c\xd2\x64\xd9\x8d\x97\x7e\ -\x97\xf9\xf8\xe6\x9b\xf7\xfb\xbd\x61\xde\xcc\x1b\xb8\xd5\x43\x5a\ -\x69\xbe\x5a\xa9\x24\x63\x81\x3d\x62\x91\xfd\x82\x26\x51\x12\x08\ -\x06\xa5\x82\xe0\x0b\x5c\x34\x86\xa9\x64\x32\x99\xef\xa8\xc0\xbc\ -\xe7\xed\x36\x96\x49\xe0\xb1\xad\xf4\x2b\x5c\x36\xc8\xc9\xe1\xe1\ -\xc4\x77\x6d\x09\xcc\xcd\xcd\xf5\x3b\x4e\xfc\x03\x84\xe7\xa2\x52\ -\x55\x61\x1a\xd1\xb3\x2a\x32\x1f\x76\x75\x55\x6f\x0b\x43\x1b\x86\ -\xe1\xa0\xaa\x93\x52\xd1\x03\x02\xe3\xc0\x70\xd4\xff\xb5\x0d\x97\ -\x8f\x67\x32\x99\x5f\x5b\x16\xf0\x3c\xef\xbe\xd0\xea\x19\x90\x07\ -\x80\xaa\xc0\x29\xd7\x4d\x7c\x2c\x22\xc1\xcd\xa4\x55\xd5\x14\x3d\ -\xef\x59\x51\x79\x13\xc8\x20\x94\x6d\x20\x87\x33\x99\xc4\x0f\x5b\ -\x16\x28\x95\x4a\x19\xc5\x5c\x02\x76\x0a\x7c\xb1\xb4\xf4\xf7\x0b\ -\xa3\xa3\xa3\x7f\xdc\x0c\xbc\x36\xf2\xf9\x7c\x77\xac\xbb\xe7\x7d\ -\x94\xe3\xc0\x9f\xa8\xd9\x9b\x4a\x0d\x5d\xd9\x54\x20\x9f\xcf\xf7\ -\xc5\xe2\x3d\xdf\x03\x63\x0a\xef\xa6\xdc\xc4\xab\x22\x62\x5b\x81\ -\xd7\x43\x55\xa5\x58\xae\x4c\x08\xfa\x16\xe0\xa3\xe1\xee\x54\x2a\ -\x55\x5d\xd9\x63\xd6\x5e\x14\x8b\xf7\x9c\xae\xc1\x75\xba\x1d\x38\ -\x80\x88\x68\xca\x1d\x9a\x04\x3e\x02\x12\x88\xf3\xa9\xaa\xae\x9a\ -\xf4\x2a\x81\x72\xb9\xfc\x10\x70\x14\xe5\x37\x1b\x2c\x1f\x6d\x07\ -\xbe\x52\x62\xf1\xfa\xc2\x09\x60\x16\xd8\x57\x2a\xf9\x8f\x6f\x28\ -\x60\x95\xb7\x6b\x17\xf1\xc6\xc8\xc8\xc8\x42\xbb\xf0\x7a\x64\xb3\ -\xd9\x25\x94\xd7\x01\x54\x98\x5c\x79\x17\x1a\x49\xb1\x58\xdc\x85\ -\x38\x15\xe0\xf7\xc5\xeb\x0b\xbb\xb2\xd9\xec\x52\xa7\x04\xa0\xf6\ -\x3c\x94\xca\xfe\x4f\xc0\xfd\x36\x94\x07\xeb\xab\xa2\x71\x07\x44\ -\x9c\x43\x91\xd0\x57\x9d\x86\xd7\xc6\x17\x55\x38\x03\x20\x8e\x3e\ -\x59\xaf\x37\x04\x54\x79\xb4\x96\xf0\x4d\xa7\xe1\x0d\x09\x95\x6f\ -\xa3\x74\x5f\x93\x00\x22\xc9\x28\x29\x6c\x97\x80\xea\xf2\x3c\x80\ -\x40\xa2\x59\x20\x2a\xaa\x2e\x57\xd9\xa6\x08\x82\xa0\x3e\xf6\x50\ -\xfd\x41\x6c\x7a\x0f\xfc\x8f\xb1\x56\xc0\x56\x6a\xc7\xd8\xe0\x76\ -\x11\x1d\x67\x47\x34\xb6\x5c\xab\xbf\x63\xfe\x13\x50\xe3\xd5\xba\ -\x6c\x7a\xbb\x04\x8c\xb1\x99\x28\xf5\x1b\xb5\x06\x5f\xb8\x00\x60\ -\x94\x83\xdb\x25\x20\xa2\x07\x00\x14\x3d\xdf\x24\xe0\x88\x9d\xae\ -\x9d\x94\x27\x66\x66\x66\x62\x9d\x86\xab\xaa\x28\x1c\x06\xc0\xca\ -\x54\x93\x80\xeb\xba\xd7\x80\xf3\xc0\xce\xbb\x07\x06\x5e\xea\xb4\ -\x80\xe7\x79\x87\x80\x31\xe0\xc7\x54\x6a\xa8\xb1\x37\x58\xb5\x0a\ -\x8c\xe8\x04\x80\xa8\x39\x95\xcf\xe7\xfb\x3a\x05\xcf\xe5\x72\x71\ -\xab\x52\xfb\xce\x60\x4e\x8a\x88\xae\x2b\xe0\xba\xee\x65\xe0\x33\ -\xd0\x7b\xe2\xf1\x9e\x4f\x54\xb5\xed\x65\xaa\xaa\xd2\xdb\xdb\xf7\ -\x1e\x30\x86\x70\xc1\x75\xef\xfd\x72\xe5\xf9\x26\x40\x18\x2c\x9d\ -\x00\x66\x15\xc6\x4b\xa5\xca\x3b\xed\x48\xa8\xaa\x94\xcb\xfe\x6b\ -\x8a\xbc\x02\x5c\x33\xe8\xf3\x2b\x67\x0f\x1b\x6c\xc9\x6a\xfb\x41\ -\x2e\x01\x77\x21\x7c\x7e\x7b\x4f\xf7\xb1\x81\x81\x81\xc5\x56\xe0\ -\xb9\x5c\x2e\x7e\x47\x6f\xff\x69\xe0\x65\xe0\x86\x11\x7d\xc4\x75\ -\xdd\x99\xb5\x7d\xeb\xce\x2e\x99\x4c\x5e\x0d\x1d\xd9\x03\xfc\x8c\ -\xf2\xd4\x8d\xbf\xfe\x99\x2d\x16\xbd\x17\x55\xb5\x6b\x33\xb0\xaa\ -\x9a\x52\xc9\x7f\x66\x47\x6f\x7f\x2e\x82\xfb\xa8\xb3\x77\x3d\x38\ -\x6c\xb2\x2d\x2f\x14\x0a\x77\x62\x9c\x0f\x05\x79\x3a\x2a\xf9\xa8\ -\x4c\x8b\xc8\x59\x08\xe6\x8d\x31\xd5\x20\x08\x2c\xc4\x07\x71\xc2\ -\x61\xb1\x1c\x44\x64\x1c\xc8\x44\x83\x9f\xb3\x36\x38\x96\x4e\xa7\ -\x7f\xd9\x88\xb1\xa5\x1f\x93\x62\xd1\xdf\x23\xa2\x93\x0a\x0f\x6f\ -\xa5\x1f\xb8\x62\x45\x27\x32\xae\x7b\x6e\xb3\xc6\x96\x7e\xcd\x0a\ -\x85\x42\x0a\x13\x3b\x22\xe8\x7e\x94\x24\x42\x02\x70\x00\x5f\xc0\ -\xb7\xc8\x45\xac\x4c\xa5\xd3\x43\xb3\xad\x8c\x7b\x6b\xc7\xbf\xc1\ -\x7f\x6c\x10\x0e\xdc\xa9\xdc\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x02\x8a\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\x3c\x49\x44\x41\x54\x58\x85\xed\ -\x97\x3d\x6b\x14\x51\x14\x86\x9f\x73\xc7\x2e\x60\x61\x30\xa0\x66\ -\xdc\xd9\x5f\x61\x40\x91\x58\x6f\xca\xb4\xda\x04\xd4\xca\xca\xc4\ -\x1f\x90\x6a\x03\x16\x06\x0c\x2a\x68\x9d\x3a\xb8\x60\x17\x10\x84\ -\xe4\x57\xec\xbd\x99\xb1\x49\x50\xb0\x48\xb9\xf3\x5a\xec\x4e\x4c\ -\x26\xfb\xbd\x13\x1b\x7d\xab\xcb\x39\x77\xe6\x3c\xf3\x9e\x0b\x73\ -\x0f\xfc\xeb\xb2\x72\x20\x84\xef\xf7\x73\x3a\xaf\x4c\xb6\x84\x71\ -\xb3\x92\x2a\xe2\x44\xa6\x03\x47\xd4\xac\xd5\xee\x7c\x1b\x08\xe0\ -\xfd\xd1\x4b\xcc\xb6\xfa\x81\x55\xa4\x1c\x69\x23\x49\xee\xbe\xbe\ -\x04\x10\x42\x78\x20\xdc\x57\xe0\x97\x61\x2f\x9c\x53\x2b\x8e\xe3\ -\x9f\x55\x54\x4d\xd3\xf4\x46\x9e\x5b\x43\x68\x1b\xb8\x6e\xb8\x87\ -\x65\x27\x68\x87\xa3\x3d\x1f\x52\x85\x90\x3d\xae\xa2\x68\x3f\x85\ -\x90\x3d\xf1\x21\x55\x3b\x1c\xed\x15\x31\x57\x2c\x4c\xb6\x04\xe0\ -\x9c\x5a\x57\x05\x10\x45\xb4\x00\x0c\xbb\x77\x09\xa0\x38\x70\x55\ -\xd9\xde\x4f\x8b\x8b\x8b\x3f\x7a\xcb\x85\x22\x76\xad\xea\x22\x21\ -\x64\x2b\x42\x1f\x00\x0c\x7b\x5a\xab\x2d\x7e\x1e\xb6\xbf\x52\x00\ -\xef\x7d\x5d\x68\x17\x98\x03\xe8\x81\xdc\x1e\xf6\x8c\x1b\x96\x9c\ -\x44\x92\x1c\x2e\xfa\x54\x14\x1f\x57\x95\x01\x84\x34\x7d\x8e\x58\ -\xbe\x00\x65\xda\xfc\x2b\x00\xde\xfb\x3a\xb2\xad\x52\x78\x3f\x89\ -\xe3\xf7\x57\x0e\x30\xc0\xfa\x53\xd4\x59\x33\xb3\x7c\xd4\xf3\x23\ -\x0f\xe1\xa8\x53\xdd\xb5\xde\x96\x2f\x40\x99\xd6\xeb\xb5\xa4\x3d\ -\xce\x07\x8c\x74\xa0\x57\xfc\x16\x70\x4b\x68\xd7\x7b\x5f\x2f\x72\ -\xb3\x58\x3f\x36\x40\x49\x73\x58\xf4\x51\x92\x9b\xd5\xfa\x42\x23\ -\x5b\x20\xd3\xa6\xc9\x76\xce\x85\x1e\xf9\x34\x7d\x66\x60\xb3\x58\ -\x5f\x68\xa4\x03\x3d\x3b\xf7\xcf\xc7\x4c\xb6\x83\xec\x6d\x69\xeb\ -\x44\xd6\x8f\x0d\x60\x66\x39\xea\xac\x01\xa7\x43\xb6\x4d\x6c\xfd\ -\xd8\x00\x00\x49\x92\xb4\x31\x6d\x0c\xca\xcb\xb4\x9e\x24\x93\x59\ -\x3f\x11\x00\x40\x2d\x8e\xdf\x51\x6a\x45\x4f\x53\x59\x3f\x31\xc0\ -\x80\x56\x4c\x6d\xfd\xc4\x00\xd0\x6d\x85\x1c\xab\x60\x1e\xcc\xcb\ -\xb1\x3a\xad\xf5\x85\x26\xfe\x1d\xd7\xe3\xf8\x0b\x50\x1f\xb9\x71\ -\x4c\xfd\x71\x40\x9c\x40\xf7\x02\x59\xd5\xcb\xcb\xca\xb2\x6c\xbe\ -\xb7\x3c\xbe\x04\x20\xd3\x01\x40\x9e\x5b\xe3\xaa\x00\x3a\x1d\x1a\ -\x00\x42\x87\x45\xec\xac\x05\x8e\xa8\x29\xf2\x15\xa1\xed\x10\x32\ -\x8b\x22\x5a\xe7\xee\x70\x33\x29\xcb\xb2\xf9\x4e\x87\x86\xd0\x1b\ -\x20\x77\x44\xcd\x22\xd7\x6f\x30\x69\x52\xe1\x45\xa5\xa4\xc1\x83\ -\x49\xa1\xb3\xd1\xac\x7b\x75\x5e\x28\xe7\xa7\xd4\xb1\xd0\x61\xbf\ -\xd1\xec\xbf\x7e\x03\x1f\xb0\x01\x10\x54\x88\x8f\x55\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x89\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3b\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\x01\x09\x00\x20\x10\x04\xc1\xd7\xfe\x21\x15\x83\xf8\x29\xe4\ -\x40\x66\x12\x2c\x5b\x05\x00\x00\x00\x00\x00\x00\xc0\xff\xc6\xda\ -\xe7\xa6\x23\x92\x66\x3a\x20\xcd\x80\x74\x00\x00\x00\x00\x00\x00\ -\x00\x00\xbc\xd7\x42\xd4\x03\xab\xc4\x79\xcd\x85\x00\x00\x00\x00\ -\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x20\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xd2\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\xb1\x15\x82\x50\x10\x44\xd1\x5d\x8b\xa0\x16\xeb\xa0\x05\x22\ -\x2b\xb2\x0b\xea\xb0\x0e\x22\xab\x00\x03\x34\xd3\x94\xeb\x39\xcc\ -\x8d\x7e\xf6\x67\x5f\x55\x44\x9c\x59\xab\x8f\xaf\xf3\x36\x6e\xb5\ -\xdd\xf7\x11\x7d\x7b\x8c\x3d\x8b\x1d\x17\xf1\x69\x55\xd5\xfb\xf8\ -\xa1\xaa\x86\x4f\x08\x81\x05\xa8\xfd\xf8\x6f\xef\x43\xc9\x00\x7f\ -\x21\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\ -\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\ -\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\ -\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\ -\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\ -\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\ -\x2d\x01\xf4\x00\x4d\x06\x78\xfe\x78\x1f\xca\x05\x58\x7b\xea\xae\ -\xa5\xbb\x96\x5a\x7b\x62\x3b\x22\xe2\xd4\x5e\x68\x08\x13\x4e\x3b\ -\x46\xe4\xd2\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\x01\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\xb3\x49\x44\x41\x54\x78\x9c\xed\ -\x99\x4f\x68\x5c\x45\x1c\xc7\xbf\xdf\xd9\x4d\x08\x88\x27\x5b\xb1\ -\xbc\xbc\x9d\x8d\x8d\xb2\x67\x15\x4f\xed\x21\xfe\xa3\x5a\x28\x82\ -\x17\x3d\x09\xc6\x58\xc1\xa3\xa2\xa0\x88\x94\x7a\x69\x05\xbd\x56\ -\xb1\xe0\x49\x10\xa4\xda\x8b\x95\x42\xa5\x5e\x2d\xf5\x2c\x12\x92\ -\x7d\x79\x59\x11\x8d\xa7\x08\x4d\x36\xfb\xe6\xeb\x61\x37\x74\xf7\ -\xbd\xb7\x64\x93\x7d\xbb\x1b\xe9\x7c\x4e\xcb\xfc\x66\xe6\xf7\xfd\ -\xce\x9b\x79\x6f\x66\x16\xf0\x78\x3c\x1e\x8f\xc7\xe3\xf1\x78\x3c\ -\x1e\x8f\xc7\xe3\xf1\xdc\x5b\x30\x5d\x10\x45\x8d\x8f\x44\x7d\x28\ -\xe7\x4a\x24\x1d\x00\x4d\x40\x57\x91\x50\x92\xa1\x31\x09\xc5\xf3\ -\xd6\x06\xe7\x7a\x82\xe9\xda\xf5\x28\x6e\x01\x28\x8d\x4d\xde\x78\ -\x49\xaa\x36\x2c\x77\x17\x98\x49\x29\x39\x2c\x64\x06\x80\xc0\xc7\ -\xf8\xff\x4f\xfb\x3c\xd4\xf1\xd6\x43\x66\x09\x00\x40\xbd\xbe\xbe\ -\x00\xea\x2a\x80\xfb\x53\x7d\x88\xa4\xd3\x21\x1e\x1e\x01\x86\x59\ -\x5f\x9b\x72\x38\x33\x37\x17\xde\x4c\xd7\xcf\x1d\x00\x00\x88\xa2\ -\xe8\x71\xc1\xfc\x08\xe0\x48\xaa\x89\x00\xb9\x02\xb4\x8e\x02\x83\ -\xac\xa7\x0d\xc2\x9d\xb2\xd6\xde\xee\xd7\x20\x17\x6b\xed\x6d\x97\ -\x98\x13\x04\xe2\xde\x88\xc8\x43\xf8\xee\x60\x9e\x79\x62\xcd\x25\ -\xe6\x44\x3f\xf3\xc8\x34\xc8\x61\xb9\xd1\x08\xcb\x2d\x77\x1d\x40\ -\x2d\xd5\x52\x10\xdd\xe4\x5f\x17\x04\x28\x03\x65\xbc\xfc\xd6\x2a\ -\x9b\xe7\xe6\x83\x20\xce\x6d\x76\xb7\xf5\xde\x34\x1a\x8d\x23\x3b\ -\x2d\x77\x0d\xc0\x13\xdd\xe5\x12\x40\x32\x99\xe4\x20\x48\x28\x31\ -\xe5\x42\xc0\xad\xe9\xb2\x79\x21\x08\x82\x8d\xbd\xda\x0f\x34\x95\ -\x83\x20\xd8\xd8\xba\x33\xf3\x14\x80\x9f\xba\xcb\x49\x40\x50\x69\ -\xa0\x51\x2c\x1c\x51\xc8\x9a\x07\x70\x63\xfb\xce\xcc\xd3\x83\x98\ -\x07\xf6\xb1\x96\x6b\xb5\xa3\x9b\x72\xad\xd3\x20\xbe\xeb\x2e\x27\ -\x00\x01\x25\x0d\x38\x9b\x8a\xa0\x9d\x8b\x26\x93\x90\xb8\xb2\xd3\ -\xdc\x3a\x5d\xab\x1d\xdd\x1c\xb4\xaf\x7d\x8b\x96\x54\x8e\xe2\xf5\ -\x4b\x10\x16\x73\xa2\xae\xfd\x95\x18\x25\x22\xc0\xec\x83\x23\x2e\ -\xdb\x70\xf6\x6c\x7b\x49\x0e\xce\xbe\xdf\xe6\x24\x5b\x36\x9c\x5d\ -\x02\xf0\x49\x4e\x34\xef\x33\x54\x24\xb9\xe6\x05\x5c\xb4\xe1\xec\ -\xd2\x7e\xcd\x77\x3a\x3c\x38\x51\x14\xbf\x2b\xe0\x42\x4e\xa8\xf0\ -\x43\x14\xdb\x53\x2b\x6f\xe7\xfa\x9e\xb5\xe1\xc5\x21\xfa\x1d\x8e\ -\x7a\x3d\x7e\x1d\xc4\xe7\x48\x8b\x23\x1d\x54\xd0\x9e\x91\x24\xa4\ -\xb4\x79\x07\xe1\x8d\x6a\x35\xbc\x3c\x54\xd7\xc3\x34\xde\xa5\x5e\ -\x8f\x5f\x02\xf1\x35\x80\xe9\x54\x48\x68\xcf\x86\x83\x23\x18\x30\ -\xa3\xb3\x09\xe1\x95\x6a\x35\xbc\x32\x54\xdf\x28\x70\xbd\x46\x51\ -\xe3\x19\xc1\x7d\x0f\xe0\xbe\x54\x48\x24\xf6\x7d\x7e\x20\x01\x49\ -\xa6\xfd\xab\x87\x7f\x09\xbe\x68\xed\xec\x8d\x21\xe4\xde\xcd\x53\ -\x44\x27\xbb\xac\xc4\xf1\x93\xc6\xe1\x07\x00\x0f\xa4\x42\x07\x99\ -\x09\x79\x2f\xd4\x7f\x0c\xf5\x7c\xa5\x52\xb9\x75\x50\x8d\x79\x49\ -\x0a\xe3\xe1\x30\xfc\x05\x4a\x4e\x02\x68\xa4\x42\x04\x07\xcf\x95\ -\xbb\xaf\x07\xd6\xa1\xe4\x64\x91\xe6\x91\x93\xa4\x10\x56\x56\xfe\ -\xb0\xc6\x24\xd7\x41\x3c\x9a\x4a\x27\x10\x0e\x7d\xd7\x43\x9f\x7d\ -\xbd\xf0\x7b\x92\x98\x67\x8f\x1f\x0f\xd6\x8a\xd6\x3a\xb2\x6f\xf6\ -\xf2\xf2\x9f\x0f\x96\xa7\x9a\xd7\x00\x3e\xd6\x13\x90\x00\x9a\x9c\ -\xf3\x03\x01\xb9\x52\x76\xc9\xeb\xd7\x9d\xe9\xa9\x53\x8f\x1c\x3b\ -\xf6\xf7\x28\x74\x8e\xec\x58\x3b\x3f\xff\xd0\x5f\x3b\xcd\xed\x05\ -\x08\x3f\xf7\x04\x48\x48\xea\xb9\x73\x6c\x6f\xa7\x95\x35\x4f\xdc\ -\xdc\x69\x6e\x2f\x8c\xca\xfc\x6e\xee\x91\xb2\xba\xba\x3a\x03\x33\ -\xf5\x0d\xa1\x33\xdd\xe5\x9d\xe7\xef\x3a\x22\xf2\x36\x38\x57\x9d\ -\x6b\xbd\x3c\x37\x37\xb7\x35\x4a\x7d\x63\x39\xc0\x48\x2a\xaf\xad\ -\xc5\x5f\x0a\x7c\x75\x90\xfa\x04\xbf\xaa\x54\x82\x25\x92\xad\x51\ -\x6b\x1b\xcb\xcd\x0e\xc9\x56\xa5\x12\xbe\x06\xe9\xb3\x3d\x2b\x8b\ -\x9f\x56\x2a\xc1\xe2\x38\xcc\x03\x63\xbc\xda\x22\xe9\xac\x0d\xdf\ -\x06\xf9\x41\xbf\x3a\x02\xdf\xb7\x36\x78\xa7\xf3\x87\xcc\x78\x74\ -\x8d\x2b\x51\x37\xab\xd1\xfa\x59\x42\x97\xba\x8a\x44\xe0\x4d\x6b\ -\xc3\x2f\xc6\xad\x65\x32\x97\x39\x00\x56\xa3\xf8\x02\x81\x45\x00\ -\x09\xc1\xb7\xac\x9d\xfd\x76\x52\x5a\x3c\x1e\x8f\xc7\xe3\xf1\x78\ -\x3c\x1e\x8f\xc7\xe3\xf1\x78\x3c\xf7\x12\xff\x01\x83\xc1\x2a\x8b\ -\xb6\x49\x04\xca\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\ -\x00\x00\x00\x68\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x1a\x49\x44\x41\x54\x58\x85\xed\ -\xc1\x01\x01\x00\x00\x00\x82\x20\xff\xaf\x6e\x48\x40\x01\x00\x00\ -\x00\xef\x06\x10\x20\x00\x01\x47\x01\xa0\x88\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\x5e\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x10\x49\x44\x41\x54\x78\x9c\xed\ -\x99\xd1\x4b\x53\x51\x1c\xc7\xbf\xe7\x6c\x3a\x37\xca\xa2\x88\x1e\ -\xaa\x87\x46\x11\x24\x3d\x54\x90\x91\x09\xd1\x9c\x31\x91\x32\x2f\ -\x23\x7a\x4a\xe9\x6a\x10\x48\x7f\x40\xd0\x1e\xea\x2d\xa2\xde\x8a\ -\xb9\x2d\x1f\xd2\x82\xb5\x19\x8b\x2c\xb7\x52\x1f\xc2\x20\xb0\xa8\ -\xcc\x12\xb4\x1e\xca\x82\xc8\x32\x57\x8e\x9c\x3b\xa7\x27\x69\x5e\ -\xaf\x0d\xc1\x73\xae\xd0\xf9\x3c\x7e\x7f\xb0\xef\xf7\x7e\xef\xd9\ -\xce\xb9\x77\x80\x42\xa1\x50\x28\x14\x0a\x85\x42\xa1\x50\x28\x14\ -\x8a\xff\x0d\x22\xda\xc0\xab\xe9\x1d\x00\x8e\x03\x00\x38\x69\x4c\ -\xc5\x5b\xdb\x44\x7b\x2e\x06\xa1\x05\x1c\x68\x68\x28\x29\x4a\xdb\ -\x33\xf9\x1a\xe5\xec\x60\x77\x3c\xd2\x2b\xd2\x77\x31\x50\xa1\x9f\ -\xfe\xcb\x65\x37\x4a\x8c\xd0\x1e\x4f\x7d\xa3\x5b\xa8\xef\x22\x90\ -\xf1\x15\xe0\x66\xba\x33\xcb\x4a\x13\x89\x48\x5a\xb4\x7f\x21\xc4\ -\xae\x00\x00\xab\xe9\x8f\x79\xab\x00\x00\x32\x45\x74\x32\x10\x08\ -\x08\xf7\x2f\x84\xf0\x00\xd1\x68\x34\x67\x2f\xc9\xac\x32\x9b\xf5\ -\x0f\x8e\xe5\x44\xfb\x17\x42\xca\x1d\xb8\xdf\xde\x3e\x49\x29\xdf\ -\x6a\x36\xf3\x6a\xfa\x63\x19\x19\x16\x42\xda\x12\xec\x8e\x86\x47\ -\x40\x78\x95\xc9\xa8\xa2\x5a\x6b\xba\x28\x2b\x87\x11\x9b\x4c\xb3\ -\x77\x43\xcf\xdf\xbb\xb7\xef\x1c\x27\x20\x35\x86\xd1\xbe\x2d\x65\ -\xbb\x47\x46\x87\x9e\xbd\x92\x99\x07\x90\xb0\x0b\x98\xe1\xd5\xf4\ -\x36\x00\x27\x8c\x3a\xa5\xbc\xbc\x3b\x1a\x7e\x2a\x33\x8b\x25\x05\ -\x00\x80\x57\xd3\x47\x01\xcc\x3f\x0f\x64\xd9\x86\x54\x22\xf2\x49\ -\x56\x0e\xcb\x0a\x00\x16\x3e\x23\xfc\xa4\x2b\x5d\x4f\xa2\x97\x33\ -\x66\xb3\xa5\xc6\xd2\x7d\xf8\xdb\x5a\x5a\x6c\xa6\xaf\x60\xe9\x29\ -\x48\xba\x39\x96\x16\x30\x10\x0c\x66\xb3\xc5\x74\x9d\xd9\xcc\xab\ -\xe9\xdf\x65\x64\xb0\xfc\x24\xd6\x77\x33\xf8\x95\x30\xbe\xc3\x64\ -\xb4\xaa\x4a\xd3\x6f\x89\xf6\xb7\xbc\x00\x00\x48\x76\x86\x07\x39\ -\x41\x9d\x51\x27\xc0\x31\xd1\xde\xcb\xa2\x00\x00\xa0\x9c\x0e\x5b\ -\xe2\x6b\x85\xa9\x11\xcf\x61\x7d\x3d\x07\xeb\x32\x19\xf5\x8b\xf6\ -\xb6\xbc\x80\xda\xda\x66\x17\xb5\x23\x01\x60\xf3\x9c\x01\xc7\xf9\ -\x54\x2c\x54\x21\xda\xdf\xd2\x02\xfc\x7e\xbf\x6d\xda\xc1\x3a\x40\ -\xb0\x27\x5f\x27\xe0\xad\xa9\x78\x28\x20\x23\x83\xa5\x05\x4c\xb0\ -\xd2\x4b\x1c\x38\x92\xaf\x11\x82\x07\xd3\xe3\x1b\x4f\x03\x30\x3d\ -\x24\x2d\x35\x16\x1e\x85\x9b\xce\x00\xfc\xca\x5c\x95\xbc\x70\x66\ -\x73\x95\x32\xdf\x14\x59\xf3\x30\x54\xdf\x74\x14\x84\xc7\x0c\xfe\ -\x1f\x73\xd4\xbe\xb7\x27\x7a\x6d\x4c\x66\x16\xe9\x05\x54\x6b\xcd\ -\xe5\x1c\xac\x17\x80\x73\x56\xe3\x40\x9a\x03\xfb\x1f\xc5\x42\x2f\ -\x65\xe7\x91\xfa\x1b\xe0\xa9\x6f\x74\x73\xb0\xbb\xc8\xbb\x78\x00\ -\x33\x94\x41\xb3\xe2\xe2\x01\x89\x05\x1c\xf2\x9f\x5c\x43\x88\xad\ -\x0b\xc0\x9c\xb3\x3f\x01\x3f\x95\xec\x0c\xa5\x64\xe5\x30\x22\xa5\ -\x00\x9f\xaf\xc5\x91\x63\xe4\x0e\x01\xb6\xe5\xeb\x9c\xf0\x0b\xc9\ -\x58\x38\x22\x23\xc3\x42\x08\x2f\x20\x10\x08\xd0\x19\x57\xe6\x3a\ -\x01\x2a\x0d\xa3\x1b\x0f\x6f\x87\xcf\x89\xf6\x2f\x84\xf0\x02\xfa\ -\x5f\x8f\x9d\xc5\xec\x7f\x83\x7f\xe9\xb3\x4f\x39\x75\x48\xda\xeb\ -\xff\x85\xd0\x5d\xc0\xe7\x6b\x71\xcc\xb8\x32\x13\x00\x4a\xf2\xe4\ -\x37\xc5\x8e\xa2\x8a\x7b\x1d\x57\xa5\x3c\xef\x17\x42\xe8\x0a\xf8\ -\xb2\xe9\x37\xe3\x40\x36\x5f\xb2\xe5\xec\x35\xcb\xe5\xe2\x01\xc1\ -\xaf\xc5\x3f\x0f\x0c\x30\x77\xd9\xae\x61\xc2\xe1\xe1\x04\x1f\x08\ -\x25\x75\xc9\x78\xf0\xad\x48\x4f\x85\x42\xa1\x50\x28\x14\x0a\x85\ -\x42\xa1\x50\x28\x14\x8a\x42\xfc\x01\xea\x12\xdd\x53\xe7\x12\x49\ -\xf2\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x75\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x27\x49\x44\x41\x54\x78\x9c\xed\ -\xc1\x01\x0d\x00\x00\x00\xc2\xa0\xf7\x4f\x6d\x0e\x37\xa0\x00\x00\ -\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x77\x03\ -\x40\x40\x00\x01\x8f\xf2\xc9\x51\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x06\xb5\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x06\x67\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4d\x70\x5b\x57\x15\xc7\x7f\xe7\x2a\x85\x94\xd0\xa4\x4d\x3f\ -\x67\x18\x16\x0c\xbb\x34\x49\x93\x36\xb4\x14\x18\x68\xac\x2f\xa7\ -\x8d\xed\xda\x8a\x76\x6d\x67\x62\xd9\x1e\xd6\xac\xca\x02\x16\x4c\ -\x16\x6c\xd8\x32\x53\x5b\x76\x57\xed\x46\xb6\x34\x0c\x4d\x1b\x3f\ -\xe9\xc9\xe5\xa3\x84\x0e\xe5\xa3\x2d\x30\xcc\x74\x4a\x17\xdd\x51\ -\x0a\xc4\x69\x6a\x3b\x13\xdd\xc3\xc2\x92\x31\xfa\xbc\x4f\x7a\xcf\ -\x36\x83\xff\xcb\x7b\xcf\x3b\xe7\xfc\x7f\xbe\xf7\x3e\x3d\xe9\x19\ -\xf6\xb5\xaf\x7d\xfd\x3f\x4b\xda\x0d\xa6\x9e\x7d\xf6\x90\xae\x7d\ -\xf6\x3b\x28\x23\xc0\x41\x85\xab\xc6\xf0\x43\xaf\x90\xff\x60\x87\ -\xfb\xeb\x4b\xa9\xec\xd4\x97\xac\xe5\x79\x81\xc7\x81\x75\x55\x2e\ -\xdf\x8a\x7d\xe6\x47\xaf\x17\x7e\xfc\x49\x73\x6c\x0b\x80\xd1\xd1\ -\xc9\x3b\xd6\x6e\x33\x3f\x03\x4e\x37\x4d\x5d\x13\x4c\xda\x5b\x9a\ -\x7d\x33\xa2\xbe\x43\x51\x7c\x62\xfa\x2b\x46\xb4\x0c\x1c\xf9\xef\ -\x19\x79\xfb\xc0\xc1\x4f\xbf\xf9\xda\x4b\x2f\xad\x6e\x1f\x35\xcd\ -\x09\xd6\x0e\x98\xe7\x69\x35\x0f\x70\x44\x51\x2f\x95\x99\x79\x2c\ -\xc4\x7e\x43\x55\x67\xf3\x00\xfa\x50\x6d\xfd\xf6\xef\x36\x8f\xb6\ -\x00\x40\x18\xed\x5c\x42\x0f\xef\x55\x08\xdd\xcd\x6f\x4a\x61\xac\ -\x79\xac\x05\x80\xc0\xed\xdd\x4b\x6d\x42\x48\x67\x73\x8f\xf6\xd1\ -\x67\x24\x4a\x66\x26\xcf\xf4\x32\x5f\xd7\xc1\xe6\x81\xd6\x15\xa0\ -\xbc\xd1\xbb\xa4\x1e\xb6\xd6\x94\xf7\x02\x84\x64\x66\xf2\x0c\x98\ -\x0a\xbd\xcd\x03\xad\xde\x5a\x00\xa8\xc4\x2e\x01\xd7\x7a\xe7\xda\ -\x7d\x08\xc1\xcc\xcb\x2a\xc4\x7e\xd0\x3c\xda\x02\xa0\xbc\xf4\xc2\ -\x7b\xc6\x68\x0a\x67\x08\xb2\x2b\xdb\xa1\x6e\xde\x65\xd9\x03\xb2\ -\xaa\xaa\xe9\xf2\xd2\x0b\xef\xb5\xcc\x74\xba\x24\x9d\xcd\x3d\x6a\ -\xad\x29\x83\x1e\x76\xe8\xe7\x9a\x55\x49\xfa\xc5\xb9\xdf\x38\xc4\ -\x0e\xac\x54\x76\xea\x11\xb5\x54\x80\x3b\x7b\xc5\x2a\x5c\x47\x49\ -\x55\x8a\xf9\x5f\xb7\x9b\xef\x08\x00\xf6\x26\x84\x30\xcd\x43\x0f\ -\x00\xb0\xb7\x20\x84\x6d\x1e\x1c\x00\x00\xa4\x32\x33\x8f\x29\xea\ -\xb9\x42\x00\x9b\x28\x2f\x2d\xbc\xe5\x92\xdb\x55\xe9\x89\x99\x87\ -\x2d\xb6\x82\x70\x57\xaf\x58\x85\xeb\x6a\x6c\xda\x2f\x2c\x5c\xed\ -\x15\xeb\x04\x00\x76\x17\x42\x54\xe6\xa1\xdd\xe7\x80\x0e\xf2\x96\ -\x66\xdf\x54\xd5\xf4\xe6\xed\xa4\xa7\x8e\x80\xa9\x6c\x9e\xd4\x83\ -\x29\xa8\x79\x23\x32\xec\x6a\x1e\x02\xac\x80\x86\x12\x13\x53\x5f\ -\x45\xf0\x04\xee\x70\x08\xff\x17\xd8\x64\xbf\x2b\x21\x88\x79\xe0\ -\x13\x11\x49\x7b\x8b\x73\xbf\x0a\x52\x23\x30\x00\x08\x0e\x41\x0c\ -\x09\xaf\x90\xff\x6d\x90\x1a\x3b\x61\x1e\xfa\x04\x00\xd1\x42\x48\ -\x64\x72\xa7\x45\xc5\x8f\xda\x3c\x0c\x00\x00\x20\x9e\x9d\x7c\x5c\ -\xac\x59\x0e\x13\x42\x50\xf3\xa8\x0e\x97\x8b\xf3\x0e\xcf\x2f\xed\ -\x35\x10\x00\x08\x17\xc2\x4e\x9b\x87\x00\x77\x81\x4e\xf2\x0b\x0b\ -\x57\x8d\xc8\xb0\xc2\x75\x87\xf0\x3b\xb5\x46\x39\x3d\x31\xf3\x70\ -\xf3\x44\x22\x93\x3b\x2d\x88\xf3\x9e\x57\x63\xce\x0d\x6a\x1e\x42\ -\x58\x01\x0d\xa5\x2e\x4c\x7f\x4d\x55\x97\x81\xcf\xf7\x0c\x56\xfe\ -\x69\x30\x89\xe5\xe2\xec\xef\x00\x92\xd9\xe9\x53\x58\xf5\x81\xa3\ -\x0e\xa5\x6e\xa8\x31\xc3\x95\xc2\xec\x2f\x07\xeb\x78\x53\xa1\x01\ -\x80\xfe\x20\xd8\x98\xda\xdd\x32\x0f\x21\x03\x80\x80\x10\x44\x57\ -\x51\x00\x71\xf9\x74\x19\xba\x79\x88\x00\x00\x40\x72\x22\xf7\x75\ -\x44\xae\xe0\x02\xc1\x4d\x37\x8c\x70\x6e\x79\x31\xff\x8b\x90\xf2\ -\x6d\x29\x12\x00\x10\x2a\x84\xc8\xcc\x43\x08\x77\x81\x4e\x2a\x17\ -\xe7\xdf\x50\x63\xce\x01\x2d\x3f\x46\x04\xd0\x0d\x51\x7d\x32\x2a\ -\xf3\x10\xe1\x0a\x68\x28\x91\x9d\xf9\x86\x58\x7b\x05\x38\x14\xf0\ -\xd2\x1b\xa2\xfa\xa4\x57\x9c\xff\x79\x14\x7d\x35\x14\x39\x00\xa8\ -\x43\xa8\x59\x0f\xe9\xf5\x95\x7b\x5d\xc2\xba\x58\x4d\x47\x6d\x1e\ -\x22\xdc\x02\xdb\xa5\xd6\xae\x22\x72\xd3\xfd\x02\xbd\xa9\x31\xe3\ -\xf2\xd8\x3d\xb0\x22\x07\x10\xcf\x4c\x9d\x34\x50\x05\x75\xf9\xde\ -\xbe\x2e\x39\x8c\x55\x3f\x99\x9d\x3e\x15\x5d\x67\xf5\x4a\x51\x26\ -\xff\x8f\x79\xee\xee\x33\xc5\x3f\x30\x12\x2f\x17\xe6\xfe\x10\x66\ -\x5f\xdb\x15\xd9\x0a\x88\x67\xa6\x4e\x1a\xc5\xa7\x7f\xf3\x00\x47\ -\xb1\xea\xa7\xc7\x27\x1f\x0a\xab\xaf\x66\x45\x02\x20\x91\x9d\x39\ -\x61\x14\x1f\xe1\x9e\x10\xd2\x1d\xb5\xc6\x54\xa3\x82\x10\x3a\x80\ -\x44\x76\xe6\x84\xd4\x6c\xd5\xc5\xbc\xc0\x86\xc2\x86\x43\xda\xa3\ -\xd6\x98\x48\x56\x42\xa8\x00\x82\x98\x07\xd6\xac\x30\x6c\x54\x53\ -\xc0\xa7\x0e\xf1\x77\x47\x01\x21\xbc\xc7\xe1\xf1\xdc\x71\x15\x59\ -\x71\x35\x6f\xd4\x3e\xb5\x5c\x5c\x58\x01\x48\x66\xa7\xbf\x85\xd5\ -\x57\x81\xcf\x39\x5c\xfb\xb1\x85\x21\x7f\x29\xff\xce\x40\x0d\xd7\ -\x15\x0a\x80\x41\xcc\x37\xb4\x5b\x10\x06\x06\x10\xd4\xbc\x58\xce\ -\x7b\xa5\x7c\xb5\xdd\x64\xe2\xc2\xd4\x13\xa2\x5c\x66\x07\x21\x0c\ -\x74\x06\xa4\xc6\x73\xc7\xd5\x88\xf3\x9e\xef\x66\x1e\xa0\xb2\x98\ -\x7f\x5d\x85\xa7\x70\x3c\x13\x8c\xe2\xc7\x33\x53\x27\x9d\x1b\x6e\ -\xa3\xbe\x01\x6c\x99\x87\x7b\x1d\xc2\xd7\x10\x1d\xe9\x66\xbe\xa1\ -\x6d\x10\xd6\x7a\x66\x15\xee\x31\x8a\x9f\xc8\xce\x9c\x70\xe8\xa1\ -\x43\x8a\x3e\x94\xce\x4c\x3f\x68\xd1\x15\xdc\xcc\xaf\x23\x7a\xbe\ -\xbc\x38\xef\x07\xa9\x51\xdf\x0e\xaf\xd2\xf3\x9d\x25\x40\xf9\xbb\ -\xc6\xcc\x50\xa5\x30\xfb\x6e\x90\x1a\xd0\x07\x80\x9d\x30\xbf\x55\ -\x6b\x62\xf2\xac\x15\x73\x99\x08\x21\x04\x02\x50\x37\x5f\x05\xee\ -\x73\x08\x1f\xc8\xfc\x56\xcd\x80\x10\x44\xf5\xac\x57\x9a\xff\xa3\ -\x6b\x7e\x67\x00\x41\xcd\x5b\x95\x11\xbf\x38\x57\x71\xcd\xdf\x4d\ -\xa9\xf1\xa9\x21\x35\xbc\x42\x04\x10\x9c\x0e\xc1\x78\xf6\xe2\xb1\ -\xdd\x32\x0f\xe0\x95\xf2\x55\xb1\x9c\xc7\xf1\x60\x54\x91\x95\xd4\ -\x78\xee\xb8\x4b\xee\x9e\x00\xe2\xd9\x8b\xc7\x8c\x8d\xad\xe0\x68\ -\x5e\x2c\xa3\x61\x9a\x6f\xc8\x2b\xe5\xab\x88\x8e\xe0\x0a\xc1\x48\ -\xd5\x05\x42\xd7\x2d\xd0\x8f\x79\xaf\x94\x2f\x3b\xc4\xf6\xad\xe4\ -\x85\x5c\x1c\x95\x57\x68\xf3\xd6\x67\x1b\x7d\x24\x56\x87\xba\x6d\ -\x87\x8e\x2b\x20\x9e\xbd\x78\xcc\x68\x2c\xc0\x81\x67\xc7\xa2\x36\ -\x0f\x50\x5e\x9c\xf7\x11\x3d\x0f\xac\x3b\x84\xdf\xab\x46\xaa\xe9\ -\xcc\xf4\x83\x9d\x02\xda\xae\x80\x2d\xf3\xca\xfd\x0e\x45\x36\x10\ -\x3b\x5a\x5e\x5c\xf0\x1c\x62\x43\x53\xd0\x95\x60\x90\xb3\xcb\x4b\ -\x73\x7f\x6a\x9e\x68\x01\x30\x94\xfd\xf6\x17\x0e\xd8\x5b\x6f\x29\ -\x3c\xe0\x90\x78\x57\xcc\x37\x14\x9f\x98\x4e\x18\xd1\x9f\xe2\x06\ -\xe1\x6f\x72\xab\x76\xc6\xfb\xc9\x8b\x1f\x6e\x1f\x6c\xd9\x02\xb1\ -\x5a\xed\x7b\xff\x0b\xe6\x01\xfc\xe2\x5c\xc5\xaa\x8c\xe0\xb6\x1d\ -\xee\xd3\x58\xec\xfb\xcd\x83\x6d\x5e\x96\xd6\x27\x1c\x92\x6d\x28\ -\x32\xb6\x9b\xe6\x1b\xf2\x8b\x73\x15\xb1\x8c\xe2\x00\x41\x84\xb3\ -\xcd\x63\x6d\xfe\x5f\x40\x6a\x3d\xf2\x6c\x28\x32\x56\x59\x9a\x5b\ -\x76\x6f\x33\x5a\x79\xa5\x7c\xd9\x05\x82\x42\x8b\xb7\x56\x00\xa2\ -\xdd\xfe\xaa\x1b\xd6\xea\xd3\x7b\xc9\x7c\x43\x5e\x29\x5f\x46\xec\ -\x18\xdd\x21\x5c\x69\x1e\x68\x01\x50\xab\xdd\xbc\x24\xf0\x7e\x9b\ -\x8b\x37\xac\xd5\xa7\xfd\xd2\x7c\x4b\x92\xbd\xa2\xf2\xe2\x82\xd7\ -\x05\xc2\x07\x07\x4c\xed\x52\xf3\x60\xac\x25\xea\x2f\x6f\xaf\x7d\ -\xf1\xd4\x99\x97\x63\x35\x3d\x04\xdc\x0f\xdc\x44\xd4\x37\x1a\x7b\ -\xae\x5c\x8a\xee\x57\xda\xb0\xf4\xd7\x3f\xff\xfe\xfd\x2f\x1f\x7f\ -\xe4\xb2\xaa\x3c\x20\x9b\xef\x1b\x7d\xac\xaa\x2f\xdf\x16\xb3\xcf\ -\xbc\x56\x78\xf1\xa3\xdd\xee\x6f\x5f\xfb\xda\xd7\xde\xd2\xbf\x01\ -\xee\x83\x44\x52\xf4\x9c\x9a\x3b\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x03\x62\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x14\x49\x44\x41\x54\x78\x9c\xed\ -\x9a\x3b\x68\x14\x51\x18\x85\xcf\x99\x5d\x30\x62\xb0\x11\x11\x31\ -\x85\xc1\x58\x08\x01\x0b\x61\x77\xed\x02\xbe\x30\x85\x8f\x0d\x31\ -\x60\x97\x80\xa8\xa4\xb3\x09\x29\xad\x8c\xa5\x90\x20\x5a\x58\x5a\ -\x24\xee\x86\x20\x24\x82\x0a\x16\x82\xd9\x80\x45\x24\x85\x85\xa2\ -\xc5\x82\x88\x58\x28\x3e\x12\xdc\x9d\x63\x13\x44\x77\x66\x77\x33\ -\x33\x7b\xf7\x26\xce\x7c\xe5\x9d\x9b\xf3\x9f\x39\x99\xc7\xbf\x77\ -\x2e\x90\x90\x90\x10\x67\x18\x55\xa0\x6f\x5a\x9d\xab\x69\x8c\x0a\ -\x1a\x14\xd0\x4b\x60\x5b\x2b\x8c\x85\x45\xc0\x1a\x81\x15\x82\x33\ -\x1d\x15\x4c\x3d\xbb\xc0\x6f\x8d\xe6\x47\x0a\x20\x5b\xd4\x09\x40\ -\xf7\x00\x74\x45\xd1\x31\x48\x19\xe0\x48\x29\xcf\xc7\xf5\x26\x38\ -\x61\x95\xb3\x45\x8d\x00\x7a\x84\xcd\x7b\xf2\x00\xd0\x05\x68\x21\ -\x5b\xd4\x70\xbd\x09\xa1\xae\x80\xec\xac\x4e\x42\x5a\x40\x84\x00\ -\xdb\x4c\x15\xe0\x69\xbf\x2b\x21\x70\x00\x7d\xd3\xea\xfc\x99\xd6\ -\x6b\x00\xfb\x5a\x62\xad\x7d\x94\xb7\x57\x78\xa8\xf6\x99\x10\xf8\ -\x3f\xb8\x9a\xc6\x28\xb6\xde\xc9\x03\x40\xd7\xba\xf7\x7f\x08\x1c\ -\x80\xa0\xc1\xd6\xf8\x69\x3f\x7e\xde\x43\x04\x80\xde\xd6\xd8\x69\ -\x3f\x7e\xde\xd3\x41\x45\x9a\xbd\xe7\x4b\x79\x27\x72\x6f\x11\x85\ -\x6c\xd1\x55\xbd\x63\x7e\xde\xb7\xca\x53\xdc\x18\x49\x00\xb6\x0d\ -\xd8\x26\x09\xc0\xb6\x01\xdb\x24\x01\xd8\x36\x60\x9b\xd8\x07\xd0\ -\xb4\x11\x3a\x52\xd0\xde\xb4\xe3\x5e\x95\xcb\x63\x20\xf6\x34\x9b\ -\x9f\x29\xba\x6f\xc2\x9a\xa1\x20\x10\x65\x81\xf3\xec\xc0\x9d\x52\ -\x3f\xbf\x86\xd5\xda\x70\xcd\x46\x07\x73\x05\x9d\x11\x75\x0f\xc0\ -\x2e\xd3\x46\x3c\x08\xef\x00\x5e\x2c\x0d\x70\x31\xc8\x9f\x35\xea\ -\x04\x01\x6f\xa7\x5a\xf7\x16\xc8\x14\xab\x13\xa2\xe6\x60\xe3\xe4\ -\x01\x80\xe8\x06\xf5\x3c\x53\xd4\x15\x93\x65\x7c\x03\xc8\x15\x34\ -\x44\x70\xcc\x64\xe1\x0d\x92\x22\x34\x99\x2d\x28\x67\xaa\x80\x27\ -\x80\xdc\xac\xf6\x8b\xba\x6b\xaa\x60\x08\x52\x80\xee\x67\xe7\xb5\ -\xd3\x84\xb8\x27\x00\xb9\xee\x38\x00\x23\xc5\x42\x43\x74\x6b\x15\ -\x97\x4d\x48\x7b\x6f\x01\xb2\xdf\x44\xa1\xa8\x10\x32\xe2\xcb\xef\ -\x19\xb0\x39\x57\x79\x65\xc6\x57\xe0\x05\x11\x27\xc5\x83\x26\x8c\ -\xa0\x8a\x1e\x17\x5a\xa8\x77\x58\x8c\xfe\x11\xc7\x8f\xc0\x01\xbc\ -\x38\xcb\xd0\x8d\x4e\x23\x8e\xce\x09\xa8\x9a\x50\x6e\x4c\xec\x5b\ -\xe1\x24\x00\xdb\x06\x6c\x93\x04\x60\xdb\x80\x6d\x92\x00\x6c\x1b\ -\xb0\x4d\x12\x80\x6d\x03\xb6\x49\x02\xb0\x6d\xc0\x36\x49\x00\xb6\ -\x0d\xd8\x26\xf0\xaf\x41\x5b\x10\x38\xd0\x6c\xc5\xb7\x19\x02\xd6\ -\x6a\xc7\x62\x75\x05\x10\x58\xa9\x1d\x8b\x59\x00\x9c\xa9\x1d\x8b\ -\x53\x00\xe5\x8e\x0a\xa6\x6a\x07\xe3\x12\x40\x15\xe0\x88\xdf\xbe\ -\xe1\x38\x04\x50\x05\x78\xa9\xde\x7e\xe1\x2d\xf3\x16\x08\x49\xd3\ -\xcd\xd2\xff\x5d\x00\x7f\x6f\x97\xff\xb1\x03\x93\xaf\x4e\xf1\x7b\ -\xa3\xf9\x9e\xa5\xe6\xa8\xef\x5a\x53\x08\x78\xbb\x94\x77\x7a\x5a\ -\xad\xeb\xfd\x34\x06\x7c\x6a\x75\x91\x96\x20\x7c\x34\x21\xeb\x09\ -\x80\xd0\x13\x13\x85\xa2\x42\x47\x4f\x4d\xe8\xfa\x5c\x01\xce\x4d\ -\x00\xbf\x4c\x14\x8b\xc0\xe7\x8a\xeb\xdc\x36\x21\xec\x09\x60\x29\ -\xcf\x65\x6d\x8e\xbd\x01\x7f\xa0\xc3\xe1\x97\x03\xfc\x60\x42\xdb\ -\xb7\x0f\x58\x5a\xc6\x2d\x00\x0f\x4c\x14\x0c\x8e\x26\x16\xcf\xf1\ -\xa1\x29\x75\xff\x46\xe8\x3a\xdd\xd2\x32\x87\x04\x5e\x83\xbd\xdb\ -\xe1\x0b\xc9\xa1\x52\x3e\x35\x6e\xb2\x48\xd3\x2f\xae\x99\xa2\x0e\ -\x13\xee\x98\xc0\xe3\x04\x76\x9b\x34\xb3\x4e\x19\xd2\x3c\x1d\xe7\ -\xc6\xe2\x79\xbe\x6f\x43\xbd\x84\x84\x84\x18\xf3\x1b\xe9\x0c\xd1\ -\x12\xec\xcb\x09\x01\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ -\x82\ -\x00\x00\x00\x79\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x2b\x49\x44\x41\x54\x58\x85\xed\ -\xce\x41\x01\x00\x20\x0c\xc4\xb0\x0d\x6f\x28\x98\x05\xfc\x5b\x00\ -\x19\xc7\x23\x31\xd0\x56\x01\x00\x61\xbd\xe7\xdc\xe4\xc0\x4a\xc6\ -\x01\x80\x2f\x3c\x1a\xe8\x01\xff\xf7\xcd\x6b\x25\x00\x00\x00\x00\ -\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x0c\xd6\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x0c\x88\x49\x44\x41\x54\x78\x9c\xe5\ -\x9b\x5b\x6f\x5b\xc7\x11\x80\xbf\x25\x45\x8a\x94\x28\x89\x92\xad\ -\xbb\x64\xc9\x4e\x9a\xc2\x41\xe0\x26\x45\xd1\xa0\x48\x0a\xf4\xa9\ -\x7d\xe9\x7b\x81\x16\xfd\xa3\x7d\x2a\x50\xb4\x0f\x41\x90\x36\x4e\ -\x52\x20\x69\x92\xc6\x96\x6c\xc9\x37\x5d\x48\x49\xa4\x2e\xe4\xf4\ -\x61\xf6\x1c\xee\xd9\x33\x87\xa4\xe4\xf4\xc9\x03\x10\x24\x77\xf7\ -\xcc\xce\xcc\xee\xce\x6d\xe7\x00\xb2\x05\xe2\x78\xe3\x40\x9c\xf2\ -\x9e\xfe\x78\x93\x84\x90\xe3\xf9\x4d\x12\x42\x96\x57\x97\xed\xe0\ -\x0e\xf0\x18\x9c\x14\x3c\xdc\x00\x6e\x19\x1d\x25\x60\x32\x8b\x2f\ -\x6d\xaf\x0d\xa1\x66\x12\x10\xe0\x62\xc8\x98\x73\xa0\x67\xb4\x77\ -\x81\xbe\xd1\xfe\x12\xdc\xa9\x8d\x2a\xcf\xa3\x1b\x35\x00\x64\x1b\ -\xb8\xed\x09\x3d\x01\x5e\xf8\x89\xa7\x80\x39\xdf\x2e\xc0\x59\xd0\ -\x3e\xeb\xdb\xfa\xbe\x1d\x8f\xa3\x0a\x34\x81\x8a\xef\x3f\xf7\x34\ -\x54\xfd\xf7\x25\x70\x04\x97\xa7\x50\x39\xf2\x6d\x53\xa8\x20\x9d\ -\x9f\xff\xc4\xff\x9f\xf2\x6d\x0e\x68\x01\xa7\xbe\x7d\x29\xe8\x7b\ -\x01\xee\x71\x31\x6f\x85\x52\x92\x2d\x90\x09\x90\x8f\x40\x56\x8d\ -\x31\x6b\x20\x0b\x46\xfb\x06\xc8\xbc\xff\x3d\x05\x72\x0f\xe4\xae\ -\xff\xcc\x80\xdc\x01\x19\xb2\x23\xa4\xee\xc7\x2c\xa8\xe0\xe5\xae\ -\xc7\x31\xe1\xfb\xe7\x40\x36\xf3\x47\x55\x9a\x05\xed\x1b\x20\xbf\ -\x06\x29\x5f\xf3\x88\xcb\x04\xc8\x9f\xf5\xc1\x5c\xdf\x36\x48\xc5\ -\x68\x7f\xdb\x3f\xb7\xe2\x27\x5b\x8e\xf0\xdd\x1b\x73\x72\x3c\xe3\ -\x25\xff\xdb\x79\x46\xb6\xa0\x75\x4b\xdb\xe5\x2d\x83\xd9\x32\xc8\ -\x4f\x8c\xf6\x09\x90\x3f\xda\xbc\x14\x13\xf0\x91\x7f\x30\x92\x9a\ -\xac\x17\x30\x7f\xc7\x7f\xb6\xed\x15\x96\xed\x6b\x4c\x4e\x60\xa2\ -\xe2\xf6\x59\x15\x4e\x7b\x49\xe7\xcb\xf5\x97\xb3\xcf\xa5\xbb\xb9\ -\x02\xf2\xab\x71\x27\xdf\x1e\x6c\xfb\x50\x63\xca\x14\xc8\x6d\x63\ -\xfc\x2a\xc8\x07\xba\x7d\x4d\x7c\xf3\x5e\x79\x5e\x13\x64\x56\xb7\ -\xbc\xd9\x37\x07\xf2\x00\x64\xd1\xe8\x6b\xfa\x67\x23\xcb\x26\x9b\ -\xfa\xc9\x82\x71\x26\xe4\x17\xe0\x3e\x0d\xfe\x27\xca\xa3\x07\xec\ -\x01\x21\xa3\xab\x70\x79\x0b\x2a\x5f\x0e\xe1\x64\x0d\x78\x5a\xd0\ -\x97\xda\xe1\x1b\x3c\x0b\xf0\x00\xba\x4f\xa0\xf6\x2a\x68\xeb\x28\ -\x5d\x94\xc9\x29\xbc\x98\x37\x98\x30\x90\xc6\xc4\x34\x50\xe6\x1f\ -\xa0\x5a\xbd\xed\xc7\x6c\x01\x2f\x54\xa1\x0f\x05\xf1\xc4\x2c\xf9\ -\xff\x89\xe9\x4a\x34\x78\xd8\x46\xd0\xf6\xc2\xa0\x25\x86\x17\x20\ -\x82\x32\xbc\xe7\x9f\x5d\x02\x7e\x06\x7c\x0e\xcc\xa0\x16\x22\x81\ -\x9c\xd9\x8c\x04\x20\x0d\xd4\xcc\x24\xff\x37\x80\x36\xb8\x5d\x3f\ -\x51\x05\x35\x5d\x9b\xc0\xd7\xe0\xae\xf4\x7c\xb9\x13\x72\x20\xce\ -\x8f\x9b\x42\x7d\x81\x6f\x47\x98\x9f\xf8\xd9\x45\x60\x1a\x35\xa9\ -\x7b\xf6\xb3\xd2\x86\xfa\x0b\xd4\x9f\x58\x01\x7e\x00\x16\x80\xcf\ -\x80\xe7\x80\xb7\x3c\xec\xf8\xe7\x7b\xaa\xdb\xdc\x55\xd1\xc4\x5b\ -\x03\xf3\x26\x5b\x59\xcd\x29\x1b\x5e\x0f\x7c\x1c\x29\x46\xcb\x4c\ -\x2e\xa1\xa6\x72\x46\x3f\x37\x05\x59\xf5\xca\x78\x3d\x6b\x55\xd2\ -\xfe\x99\x81\x7e\x91\x09\x90\xdf\x78\x2b\x11\xb6\x07\x8a\x51\xee\ -\xaa\x8e\x18\x40\xc9\x98\xb5\xaf\x13\xb2\x0b\xae\x17\x8d\x5d\x03\ -\xfe\x0e\xdc\x09\x84\x10\xac\xcc\x61\x53\x19\xe7\x10\xdc\x53\xdf\ -\x37\xe6\xaa\x9b\xe0\x9f\x75\x4f\x80\x03\xc5\x7d\xd8\xcc\xf7\x8b\ -\x03\xd6\x81\xbf\x01\xf7\xb2\x73\xba\x9e\xf2\x22\xeb\x18\x47\xc0\ -\x12\xc0\x14\x70\x16\x31\x0f\x7a\xe6\xbf\xf3\x5b\xe9\x31\x59\x21\ -\xa0\x1a\xb9\xd9\x57\xc6\xdd\xe5\xf8\x3c\x8e\x0b\xee\x52\x71\x37\ -\xfb\xd1\x6e\x08\x3d\xbc\x1e\xf0\x04\x3d\x7a\xe1\x90\x1e\xea\x29\ -\x4e\xc7\x58\x2d\x25\x38\xe7\x57\x2f\x00\xd9\x46\x95\x4c\x29\x30\ -\x77\x07\xc0\x7d\xe0\xd2\x9b\xab\x57\xe8\xee\x09\x4d\x9e\x9f\xd0\ -\xdc\x04\x25\xe8\xfa\xe3\x56\x3b\xc4\xf6\xf7\xa7\x81\x2e\x48\x78\ -\x66\xfb\x3a\x56\xee\x03\x47\xe8\xca\x7f\xad\x63\x05\xa0\x03\x9d\ -\x13\xa8\x2f\x92\xd1\x67\xee\x08\xe4\xa7\xf1\x04\x63\x58\x01\x79\ -\x0b\x2e\x2a\x50\x9d\x46\x15\xd3\x29\x83\xad\xbd\x0b\xfc\x0e\xf8\ -\x4b\x01\x03\x01\x74\xe6\xa1\x9e\x04\x3f\x3e\x4e\xa8\x1d\xf9\xce\ -\x79\xd4\x52\xf8\x1d\xd5\x39\x87\xfa\xe1\x10\x64\x5d\xd4\x3c\xfe\ -\x06\xf8\x24\xa0\xd9\x2b\xcf\x7a\x0d\xb8\x0d\x72\x1e\x2d\x66\x6e\ -\x25\x62\x01\xc4\xd1\xe1\x5d\x60\x1a\x26\x1f\xaa\x12\x74\xfb\xd9\ -\xe1\xb2\x0e\xfc\x03\x0d\x70\x8c\x20\x43\x80\xee\x6d\xa8\x4d\x40\ -\xfd\x25\xb8\x4e\x01\x43\x47\xd9\xbf\x52\x07\x16\xe0\xa2\x06\xd5\ -\x93\xbc\xd6\x4e\x7d\x93\xbf\x02\x6b\xe0\xf6\x82\xce\x36\xc8\x09\ -\xba\x63\xdf\xf6\x9e\x6b\x42\x5b\x9f\xe8\xd8\xc7\x3a\xa0\x0a\x9c\ -\xfb\x09\xee\xa1\xab\xf2\x85\x4d\xb3\x2c\xa1\xdb\xbe\x87\xad\x13\ -\xa6\x81\x55\xa8\xb5\x55\x89\x15\x32\x6f\x80\xeb\xe8\x33\xd5\xb6\ -\x32\x18\x1e\xab\x30\xaa\xa3\x87\xfa\x02\x2b\x05\x88\xbe\xf1\x63\ -\xee\xf9\xe7\x3a\x64\x1d\xb9\x22\x2b\xc0\x06\xf0\x0c\xf5\x01\x8c\ -\x03\x7c\xd8\x04\xba\xe0\xba\x9e\xe0\x48\x31\x1e\xcd\x43\xbb\x86\ -\xae\xc2\xf9\x58\x3c\xdb\x70\x01\x3c\x85\xf6\x24\x1c\x2f\x60\x87\ -\xb4\x5d\xe0\x4c\xe7\x8c\xc1\x9d\xa1\x8b\xfa\x83\xe7\x29\xc7\x8b\ -\x25\x80\x06\xea\x3d\x2d\xe6\xb7\x7c\x02\xcd\x29\x70\xad\x6c\x5b\ -\x22\x84\xcb\xf7\x61\xae\x07\xb3\xaf\xcc\x47\x6f\x04\xb3\xaf\x60\ -\xf6\x52\x71\x5b\x47\xcd\xb5\x60\xae\x20\x16\x61\x07\x35\xdf\x2d\ -\xd4\xc2\x65\xc0\x12\xc0\x34\xaa\x3d\x0b\x94\x9a\x2c\xa3\x6e\xaa\ -\x01\xc7\x4d\xa8\x7c\x0f\xcc\x33\x7e\xec\x3d\x06\x88\x03\x16\xa0\ -\xf2\x9d\xce\x61\xc2\x73\xdb\x59\x72\x97\x40\x19\xdc\x31\xba\xb8\ -\x19\xb0\x04\x20\xa8\x69\xd9\x29\x20\x64\xc2\xb6\xf3\x32\x05\xa5\ -\x64\x22\x7f\x1c\xac\x60\xeb\xda\x10\x6e\xfb\x16\x94\x4a\x5e\xbf\ -\xc4\xc3\xae\x94\x36\xb1\x78\x3a\xd4\x23\x34\xda\x0a\x94\x07\x83\ -\x4c\xbf\x7d\x13\xd5\xb2\xe1\x2a\xcc\x82\x74\x81\x15\x98\xd9\x0f\ -\xfa\x5a\xc0\xbb\xc0\x13\xd2\x8c\x4e\x06\x92\xd4\x19\xa8\x4f\x61\ -\xe5\x05\xe7\xd0\x40\xe7\x07\xfd\x2d\xa0\x3b\x73\x03\xe4\x19\x03\ -\x3f\x23\xc1\x7f\xa6\x7d\x1c\x64\xd1\xb8\x63\xef\x0e\x27\x81\x59\ -\x0a\x31\x61\x35\x72\x49\x48\x99\x47\x83\x8d\x65\x4f\x64\x84\x9c\ -\x1e\x74\x66\xa1\x7e\x00\xc4\x41\xc6\x23\x4f\xd0\xd7\xc1\xe4\x2b\ -\x40\x1f\x3a\x67\x50\xdf\x05\x1c\x74\x6f\x41\x2d\xc9\x2f\x3e\xf3\ -\xdf\xce\xcf\xf9\x05\x9a\x2b\x0c\xe1\x15\x74\x66\xa0\x9e\x08\x2d\ -\x9c\xb7\x89\x2a\xbe\xbe\xee\x86\x54\x57\x25\x79\xcb\x4c\xc2\xc6\ -\x5a\x99\x45\xe0\x4b\x90\xaa\x27\xe0\x25\xb8\x43\x34\xd3\x73\x96\ -\x8f\xfc\xa4\x01\xf5\x32\xb8\xe7\x79\x54\x82\x67\x7e\x01\x38\x46\ -\x57\xec\x1b\x63\x77\xb5\xfd\xf8\x32\xba\xe2\x07\x9e\x8e\xff\x68\ -\x5f\x2e\x7a\x3b\xf1\xa6\xcf\x67\x7f\x43\x9a\x64\x1f\x15\x98\x17\ -\x9a\x6c\x02\x4f\xe0\xa4\x03\x8d\x29\xb2\xe1\xb1\xa9\x03\x4a\xa8\ -\x04\x6f\x83\xdb\x09\xec\xf7\x2d\x6c\xe5\x37\x0d\x47\x05\x69\x68\ -\xa5\x00\xcd\xf4\x6e\x01\x4f\x87\x87\xc4\xa9\x2f\x7f\x1f\x0d\x67\ -\x87\x05\x52\x27\x18\xbe\xbd\x5f\x08\x9f\xb9\x72\x27\xa8\xb7\xba\ -\x01\x8d\x03\xf4\x48\x65\xa0\x48\x09\x2e\xe5\xe3\x01\x28\x20\xbe\ -\x01\xf3\x47\x46\x7b\x02\x65\x25\xb4\xf2\x90\x9c\xb3\x94\x9b\x3a\ -\x51\x78\x9f\x61\xdf\x3f\x84\xb4\x14\x08\x20\x37\x4e\x7c\x6a\x7c\ -\xcd\xea\xb5\x04\xb0\x00\x58\xf6\xdf\xba\x84\x18\x07\x56\x18\x24\ -\x34\x0c\x8f\x31\x81\x9c\x93\xf3\x12\x2e\x8c\xd4\x7b\x06\x8a\x84\ -\x69\xd1\xfa\x0a\x43\x60\x05\x47\xe0\x5a\xe1\xec\x28\xc1\xf4\x07\ -\x3b\xa7\x30\x94\x36\x3c\x3c\xd7\x85\xea\xa8\x7c\xdb\x35\x72\x0d\ -\xee\x0c\x55\xe6\x19\x88\x05\x30\x41\x71\x54\x77\x13\x9b\x5e\x83\ -\x6e\x64\xde\x62\x21\x0c\xbd\xb1\xb9\xa9\x1f\x51\xf4\x5c\xae\x3d\ -\xb6\x02\xcb\x70\x65\x69\xf3\xc0\x3f\xc8\xb4\x97\xec\xf6\x14\x9a\ -\x50\x7b\x66\xd0\x21\x20\x8f\xd1\x24\x0b\xc0\xa3\x02\xfd\x32\x62\ -\x85\xbb\x7d\x8d\x34\x73\xd0\xc3\xce\xd6\x8e\x8a\x05\x7a\x15\x98\ -\xb8\xce\xf6\x4f\xec\x75\x11\xf4\x47\xf4\xbf\x26\xd4\x1c\xc5\x47\ -\x70\xac\x79\x23\x01\x94\x9f\xa1\xf6\x37\xc6\xd5\xb3\x11\x8e\xcc\ -\xf2\x1e\x90\x9a\xa4\x10\xd2\x6d\xff\xc8\x7f\x46\x58\x87\x42\x28\ -\x12\x40\x19\xdb\xb3\xcc\xcd\x11\xeb\x80\x2e\x51\xbc\x1c\x40\x11\ -\xb3\xc3\x08\xbf\xca\xcf\x11\x9f\xf9\x51\xd6\x61\x28\x14\x8d\x1f\ -\x5b\x39\xc6\x02\x48\x72\xe7\x39\x6d\x79\x03\x22\x12\xe8\x93\xde\ -\x27\x16\x29\x3c\x4b\x08\x32\x43\xea\xe9\xdd\x78\xee\x00\xc4\xe7\ -\x17\xb3\x60\x99\xc1\x23\x06\xb7\x38\x3f\x06\x3c\x07\x56\x46\x68\ -\x7b\x22\x21\x94\x50\xaf\xcd\xb8\x70\xc9\xc0\x98\xbe\x49\x12\x4e\ -\xe7\x05\x6a\x09\xc0\x01\xfb\xe4\x2f\x12\x8b\xa4\x7d\x00\x6d\x43\ -\x6f\x64\xe0\x25\xf0\x21\x23\x8b\x13\x9c\xa0\x61\xf8\x47\x0c\xbf\ -\x13\xc4\x67\x80\x8e\x8b\x10\x0d\x7e\x8a\x43\xad\xcd\x2e\x63\xe8\ -\x00\x00\xf1\x8e\xd0\x53\x15\x42\x7a\xb3\x73\x80\x79\x1b\xcb\x25\ -\x34\xaa\x43\x28\x4d\xee\xeb\xfe\x05\x6c\x6a\xde\xa0\x08\x64\x8e\ -\xc1\xe5\xcb\xa6\x45\xf0\x00\xe6\x26\x31\xd3\x6d\xed\x45\xd2\x88\ -\x55\x9a\x68\x6e\xe3\x91\xc7\x35\x32\x1f\x00\x9a\xe7\x9f\x04\x77\ -\x0e\xec\x28\x12\xd9\x40\xad\xc3\xbc\x8f\xbd\x43\x44\x4b\xc0\x19\ -\xc8\x3b\x44\x91\x16\x9a\x81\x59\x43\xa3\xba\x26\x70\x01\x17\x5b\ -\x5e\xc7\x58\x4e\xcf\x29\x1a\x19\x2e\xe9\x58\x1e\x00\xff\x06\x89\ -\x4d\x73\x92\xd9\x49\xf2\x01\xc9\xff\x24\x84\xee\x78\xfc\x7b\x7a\ -\xaf\x09\x3e\x83\x9d\xf3\x49\x62\x01\x74\x7c\xdb\x32\x7a\x1e\xd1\ -\x0b\x05\x8e\x3c\xbd\x02\xec\x67\xb7\xb1\xa0\xb9\x43\x59\xcf\xe6\ -\x10\xd3\x73\xf7\x4f\x70\xed\x60\x8e\x82\x3c\xa3\x05\x02\x9a\x38\ -\xd9\x8d\xe6\x5c\xd3\x60\x2d\x61\x3c\x09\x87\xc5\xa1\xbb\xfa\x38\ -\xdb\x0e\x0c\x0a\xb6\x32\xd9\xe9\xf8\x08\x84\x57\xd7\x16\xec\xa1\ -\xc1\x8d\x05\xcf\xc8\x14\x56\xe0\x6f\x65\x5f\xfb\x6e\x30\xb6\x0e\ -\x2b\x14\xe6\x24\x93\xc0\xcb\x84\xe4\x3a\x3e\xa3\x38\x8b\x94\xe0\ -\x85\x6d\x0a\x5d\x5f\x89\xb2\xea\x6d\xdc\x15\xd0\xf2\x67\x30\xc9\ -\xdb\xbf\x0e\xf3\x09\x04\x42\x68\xdd\x46\x13\x24\x56\x4e\xb2\x1c\ -\xd0\x18\xf7\x2d\xa3\xd6\x68\x2c\x25\xd8\x46\xed\xa5\x19\x3f\xfb\ -\x6d\x6e\x64\x5f\x01\x38\x83\xc6\x32\x9c\x9c\x8d\xe1\x25\x5e\x03\ -\x9c\x28\xce\x99\x15\x06\x65\x77\x31\x2c\x53\x7c\xbc\x92\x1a\x85\ -\x9c\x59\xb5\x04\x70\x86\x2a\x97\x72\x41\x86\x15\x38\xee\x90\xbb\ -\xf7\x4f\xb7\xfd\x57\xd0\x38\xd3\x73\xfa\x63\x81\xac\x2a\x4e\xbe\ -\xc2\xf4\x18\xa5\x01\xad\xae\x2d\x74\x99\x83\xb3\x2e\xca\x53\x4e\ -\x78\x45\xf9\x80\xc4\x66\xbe\x6d\x13\xd4\x3c\x54\x84\xc9\x31\xc9\ -\xb9\xb7\xa7\xe8\x96\x5b\x85\x4e\x41\xa1\xd3\x38\x70\x3e\xab\x38\ -\x92\xea\x4f\xd3\x6d\x9e\x04\x66\x61\x2e\x4e\xd6\x26\xb0\x02\x53\ -\xd3\x01\x4f\x19\x88\x05\x70\x41\x9a\x34\x70\xde\x74\xc9\xba\x8d\ -\xd7\xed\x2b\x72\x4a\xd8\xee\xed\x15\xb0\x07\xf5\x4b\x55\x5c\xb2\ -\x38\x9e\xaf\x2f\xce\x8f\x5d\x81\x49\x8f\x23\x3c\xf3\xa1\x10\x28\ -\x01\xab\x76\xfa\x0e\xd4\x34\x5f\x54\xc0\x7d\xeb\x1b\xea\x44\x56\ -\x20\x36\x83\xf1\x95\xd3\x27\x68\x39\x1a\xc0\x32\x5a\x27\xd4\x0f\ -\xc6\x5d\x02\xbf\x45\xaf\xc7\x97\x0d\x9d\x97\xa4\xa0\x4e\xd1\xf8\ -\xfc\x3d\x2f\x84\x61\x89\x0f\x21\xad\x35\xa0\x81\xba\xd1\x56\x4d\ -\xcf\x25\xf0\x7b\xe0\x53\x06\x97\xa3\x89\x19\x4c\xca\x6b\x27\xf5\ -\x66\x3b\x85\x12\xc3\xdd\x67\xd9\x42\x0b\x0f\xc2\xb6\x86\xf7\x08\ -\x37\xa2\xf6\xa4\x0e\x6f\xcd\x7f\x1b\x56\x43\x1a\xdc\xa8\x46\x30\ -\x7d\x7e\x05\xf3\x52\x45\xaa\x68\x09\xed\x1c\xc8\xbb\xb6\x4e\x90\ -\xf7\xf3\xd6\x4a\x3e\x64\x8c\x1a\xa1\x43\x90\x20\x23\xeb\x4e\xe0\ -\xa4\xab\xf5\x80\x29\xa2\xf0\x8a\xba\x0f\xee\x11\xea\x25\xbe\x06\ -\xb3\xe3\x82\xcc\xa0\x29\xfb\xef\xd1\xcc\xcf\x0e\x79\xc5\xb8\x81\ -\xa6\xe0\xc3\x0b\x9e\xe4\x6e\x22\x03\x96\x00\xba\x40\x95\x4c\x49\ -\xec\xcc\x0b\xa8\x4c\x7a\xc9\x16\x85\xb4\xfb\xd0\xaa\xaa\xce\xb8\ -\x56\x5d\xee\x98\x20\x65\xc5\xdd\xaa\x90\xaf\xfa\x08\x14\x63\x7b\ -\x11\xba\x1d\x32\x1a\x5f\x2a\xa8\x6e\xcb\xd5\x28\x58\xb1\x40\x09\ -\xdc\x9e\x6e\x79\x79\x16\x28\xa0\xa7\xa8\x46\xee\x01\xff\x0d\x98\ -\x0f\x24\x3f\x77\xe0\x05\x94\x84\xbf\xa1\x0b\x7c\x13\x48\xbc\xbf\ -\x55\x94\xd1\xa7\x30\x27\x51\xbf\x04\x39\xc6\xfb\xd0\x68\x91\xb9\ -\xbe\x93\x8a\xd2\xe3\x76\x40\xee\x1a\xcc\x66\xe0\x25\x69\x2e\xc0\ -\xed\xa2\x75\x36\xc9\xd6\x17\x54\xf1\x54\xc8\x66\x8d\x22\x1c\x4e\ -\x54\x80\xec\xa3\xb5\x3f\xf7\xc6\x08\x97\x0d\x68\xdd\x46\x9d\x9b\ -\x25\xe0\xb9\xee\xb0\x9c\x9d\x9f\x26\x5d\xd5\xe3\x26\xba\xea\x65\ -\x54\x79\x76\xd0\xda\xe6\x25\x65\x1e\xd0\xcb\xd8\x8c\x33\x14\xed\ -\x00\x77\x9a\x0d\x57\xdd\x1e\x5a\xc3\xbf\x81\x46\x66\x9f\xa3\x42\ -\x78\x00\xe7\x27\x50\x3d\x52\x22\x0b\xcd\x5b\x5f\xe7\x68\x24\x15\ -\x9b\x49\x1b\x80\x83\x0b\xbf\xbb\xaa\xc9\x0b\x14\x21\x1c\x7b\x66\ -\xbc\xa9\x33\x1d\xcb\x65\xc5\x2f\x4b\x1e\x6f\x12\x23\x7c\x00\x3c\ -\x04\x0e\xc0\xbd\x0c\xc6\x97\xe3\x7b\x46\xeb\x08\xc4\xcc\x74\x3d\ -\x21\x0f\xd1\x82\x45\xd0\x2b\xef\x65\xdf\xbe\x1f\xb4\x1b\x20\x62\ -\xf7\x8b\x83\xea\xa4\x67\xb0\x53\xe0\xc5\xad\x8f\xc0\x7d\x05\x4c\ -\xc1\xd1\xf7\xd9\xeb\x39\x71\x9e\xb6\xf8\xcc\x8f\x93\x42\x93\x3b\ -\x03\xe7\x27\x53\x2e\x5f\xcf\x5a\x07\xf0\x66\xe8\x7d\xec\x44\x49\ -\x32\xe6\xff\x50\x2e\x0f\xba\x00\xf2\xf3\xbc\xf9\x95\xa6\x5a\x8a\ -\x5c\xb9\xfc\x1d\xcc\xb2\x5e\x1b\xf9\xc7\xd8\x2f\x4c\xac\x92\x7b\ -\x61\x42\x1c\xfa\x82\x85\xf1\x02\x43\x3a\x66\x7b\xcc\x89\x43\x9c\ -\x05\xcf\x88\x43\xdf\x18\xf9\xa5\xd1\x57\xce\xfa\x2b\xa9\x10\xaa\ -\x8c\xff\xc2\x44\x8a\xe8\x4f\x05\x4e\xc8\x46\x5e\x08\x00\xf2\x1e\ -\xfa\xca\x4a\xee\xa5\x04\x5e\xeb\x95\x99\xb4\xad\xe4\x9d\x9f\xb7\ -\x40\xde\x31\x9c\x9f\xb2\xa5\xe5\x3d\xf3\x7f\xc8\xe3\x2b\x9e\x3c\ -\x91\x5a\x59\xa5\x16\x7b\x80\xe0\x77\x82\x71\x7d\x2d\x1b\x7e\x6b\ -\xde\xd3\x4f\x2b\x74\x9e\x2a\x8c\x7e\x69\x6a\xca\x8f\x09\x04\x2f\ -\x2b\x0c\x5e\xbe\x2a\x7a\x39\x6a\x1e\x33\x66\x91\x2d\xcf\x43\x29\ -\xbf\x9b\x15\x62\x44\x86\x93\x23\x9b\xa8\xb6\xf5\x35\xba\xb4\xfc\ -\xef\x1a\x6a\xe6\x1c\x7a\x01\x72\xc1\xe0\xb5\xb9\x19\x40\xa0\x37\ -\x0d\xe5\xc4\x29\x4a\x4a\x64\x7b\xc1\xff\xe4\xf6\x26\x79\x6d\x2e\ -\x28\x97\x4d\xe9\xeb\xfa\x71\x0e\x35\x61\xa7\xfe\xf7\x24\xaa\xc4\ -\x7d\x01\x06\x1d\x54\xa1\xce\x06\x78\xf6\x06\x4e\x93\xed\xc0\x8d\ -\xb8\xa2\x8e\x41\x26\x30\x4a\xcd\x3c\x9e\x3a\x79\x2d\x1b\xbf\x38\ -\x59\x42\xaf\xca\x92\x23\x54\x65\xe0\x5f\xe0\x99\x38\x24\x6b\xf3\ -\xac\x17\x27\x85\x41\xe2\x33\x06\xa3\xb4\x36\x7d\xac\x88\xc7\x37\ -\xf7\xd5\x59\xab\xe1\x0d\x80\x0c\xcf\x6f\x1a\xf3\x09\xa8\x10\xfe\ -\x07\xb4\x0a\xfd\x7e\xcf\x22\x5b\xc2\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x01\x98\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x4a\x49\x44\x41\x54\x58\x85\xe5\ -\xd6\x3f\x4a\xc4\x40\x14\xc7\xf1\xef\x4b\x16\xbd\x81\x5b\x78\x02\ -\xd7\xca\x2a\x60\xb7\xf1\x00\x0b\xf1\x40\x7a\x22\x21\xd8\x08\xc2\ -\x6e\x27\xa4\x5e\xff\x9c\xc0\x42\x2b\x0f\xb0\xe1\x59\x84\x28\xc4\ -\xc4\x99\x97\x9d\x89\x85\x53\xce\x3c\xf8\xfc\x98\x79\x3c\x06\xfe\ -\xfb\x92\x29\xb1\xac\xd4\x39\x3b\x2d\x11\x5e\xab\x22\xb9\x04\x48\ -\x26\xc5\x6b\xdd\x20\x64\x28\xc7\xed\xfe\x24\x01\xbe\x70\x38\x01\ -\x5e\x98\xc9\xaa\x3d\x8b\xfe\x04\x3f\xf0\x54\x96\xd5\x4a\xde\x26\ -\x09\xe0\xc2\xa3\x06\xf0\xc1\xa3\x05\xf0\xc5\xa3\x04\xb0\xe0\xc1\ -\x03\x58\xf1\xa0\x01\xc6\xe0\xc1\x02\xf8\xe2\xe7\x37\x7a\xb4\x13\ -\xbd\x13\xe5\xa3\x2a\x92\x1c\x02\x0c\x22\x0b\x5e\xa3\x6b\x51\xce\ -\x80\x83\x76\x7f\x36\x25\x0e\x9c\x0a\x3c\x26\x48\xd1\x9e\x8d\x7e\ -\x82\x3d\xf0\x8b\x87\x42\xde\xf7\x0a\x10\x0a\x1f\x15\xc0\x88\x6f\ -\x80\x05\xf0\x94\x22\x79\x17\x37\x07\x08\x8d\x9b\x02\xc4\xc0\x01\ -\xd2\x90\x78\x56\xea\x5c\xd5\x1f\x07\x8f\x1b\xb0\xe0\xd4\xba\xb6\ -\xe0\xce\x00\x23\xf1\xe7\x14\x59\xf6\xe1\xa6\x49\x18\x03\xf7\x9e\ -\x84\x91\xf0\x0d\xb0\x70\x4e\x42\x23\xde\xd6\x0d\xe2\xae\xde\x90\ -\x9e\x62\x33\x4e\x2a\xf9\xd8\xc6\x94\x4e\x71\x68\xdc\x79\x43\x4d\ -\x13\x5e\x69\x42\xad\xf7\x2e\x1c\x55\x91\x5a\x6f\x5d\x78\xb7\x6e\ -\x08\xff\x0e\xd0\xac\x43\x60\xfb\xeb\x4f\xe6\x1a\xd1\xa6\x83\xb7\ -\x83\x78\x4f\x9d\xcf\x3c\x68\x6e\x41\xd5\x3d\x9a\x55\x25\x68\xdd\ -\x5f\xaf\x4f\xda\x1b\xa3\x91\x9e\x7b\xef\x4a\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xa6\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x58\x49\x44\x41\x54\x58\x85\x63\ -\x60\xa0\x00\xdc\x7f\xf8\xb8\xe1\xfe\xc3\xc7\x0d\x94\x98\xc1\x44\ -\x89\x66\x6a\x80\x51\x07\x8c\x3a\x60\xd4\x01\xa3\x0e\x18\x75\xc0\ -\xa8\x03\x06\xdc\x01\x2c\x14\x9b\xf0\x9f\xc1\x81\x92\x2a\x79\x18\ -\x84\x00\x23\xc3\x01\x45\x79\xd9\x06\x72\xb5\x0f\x78\x08\x8c\x3a\ -\x60\xd4\x01\xa3\x0e\x18\x75\xc0\xa8\x03\x46\x1d\x30\xe0\x0e\x00\ -\x00\xe6\xf7\x0c\x89\x70\x77\x76\x17\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x01\x50\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x02\x49\x44\x41\x54\x78\x9c\xed\ -\xd6\x2d\x4e\x03\x51\x14\xc5\xf1\x73\x29\xe1\x4b\xa0\xc0\xb3\x01\ -\x92\x0a\x7c\xc7\x15\x3c\x86\xd4\x23\x31\x2c\xa0\x99\x05\x74\x07\ -\x4d\x05\x49\x25\xa6\x09\x81\x86\xb0\x08\x76\x80\x22\x21\x75\x08\ -\x98\x66\xca\xbb\x58\xf2\x1e\x04\x35\x8f\x84\xf9\xff\xe4\xb9\x23\ -\xce\x1c\x33\x23\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\xad\x60\ -\xbf\xdd\x8b\x62\xd8\xc9\xd2\xa4\x21\xbd\x9e\x42\x59\x96\xe1\xa7\ -\xfb\xb7\x03\x14\x67\xe7\x7b\x1b\xcb\x30\x72\xd3\xa9\xa4\x9d\xc6\ -\xda\xe5\x51\x99\xfc\xc6\x6b\xbf\xb8\x9f\x4d\x9e\xe3\x63\x32\xc0\ -\xc9\x60\xb0\xbb\xaa\xb6\x1e\x25\x3b\xc8\x50\x2e\xa7\x45\xa8\x75\ -\xf8\x30\x1b\xbf\x7c\x0d\xd7\xe2\xa7\x3e\x96\xdb\xe5\x3f\x7c\x79\ -\x49\xda\xb7\x75\x8d\xe2\x30\x19\xc0\x5d\xfd\x3c\x7d\xf2\x33\xd3\ -\x71\x9c\x25\x03\xb4\x4d\x32\x80\x99\xe6\x7f\x51\x24\x07\x77\xdd\ -\xc5\x59\x32\x40\x67\xf3\x7d\x28\xf9\x53\x96\x46\x79\x2d\x7c\xa5\ -\xcb\x38\x4c\x06\xb8\x9d\x4e\x5f\x43\xa8\x8f\xcc\x75\x25\xe9\x2d\ -\x4b\xb5\x66\x55\x26\xbf\x56\x1d\xba\xf1\x17\x40\xe2\x47\x08\x00\ -\x00\x00\x00\x00\x00\x00\x00\x00\x68\x8b\x4f\xc6\xe5\x42\x89\xb1\ -\xed\x97\x86\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\x75\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x27\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4f\x68\x5c\x55\x14\xc6\x7f\xe7\xcd\xb4\x5a\x8c\x08\xb6\xba\ -\x30\xa8\x2b\x51\xd4\x8d\x50\x84\x22\x48\x6c\x27\x89\x41\x0c\x76\ -\xc6\xd1\x95\xd8\xfc\x99\x50\x17\xa2\x05\x45\xf0\x0f\xe3\xd0\x8a\ -\x15\x04\x17\x22\xb6\x49\xa6\xc6\x45\x8a\x9a\x26\x0d\xa1\x1a\x3b\ -\x49\x64\x0a\x8a\x20\x28\x08\xc5\x85\x20\xe2\xa2\x41\x04\xad\x14\ -\x6d\x0b\x93\xb9\xc7\x45\x1c\x79\xf3\x66\xc0\x14\xdf\xbd\xef\x62\ -\xe6\x5b\x7e\x1f\xdc\x73\xee\x77\xce\xfd\xf7\x98\x81\x0e\x3a\xe8\ -\x60\x33\x43\x92\x4e\x60\xa3\xc8\x64\x47\x8b\x22\xf2\x32\x18\x51\ -\xd5\x43\xcb\x73\xc7\x5e\x8d\x63\xdc\x20\x8e\x41\x6c\xa3\x3f\x3b\ -\xfc\x00\x42\x11\x34\x0d\x92\x12\x09\x5e\x89\x6b\xec\x74\x5c\x03\ -\xd9\x42\x6f\x6e\x78\xa7\x21\x58\x90\xe6\x6e\x8d\xad\x70\x5e\x77\ -\x40\x5f\x6e\xec\x0e\x34\x58\x04\xba\x22\x92\x89\x2b\x86\xb7\x06\ -\x64\xf2\x63\xb7\x28\xa6\x82\xb0\xa3\x8d\xac\x71\xc5\xf1\xd2\x80\ -\x81\xfc\xd0\x0d\x18\x53\x01\x6e\xb6\x1d\xcb\x3b\x03\x06\x07\x87\ -\xaf\x5d\x33\xa9\x4f\x04\x6e\x77\x11\xcf\x2b\x03\x7a\xf6\xed\xbb\ -\xfa\xd2\xd6\x60\x1e\xd8\x19\x91\x62\x6b\xf9\x28\xbc\x31\xa0\xa7\ -\xa7\x98\xde\xf2\x47\xfa\x38\xca\xee\x88\xa4\xc4\xb8\xe9\x45\xe1\ -\x8b\x01\x92\xde\xbe\x7a\x14\x65\x6f\x13\xab\x6a\x75\xf2\xe0\x89\ -\x01\x99\xdc\xe8\x1b\x82\x0e\x47\x68\x45\xc4\xea\xe4\xc1\x03\x03\ -\x7a\x1f\x2d\xbc\x20\xf0\x7c\x1b\xc9\xfa\xe4\x21\x61\x03\x32\xb9\ -\x42\x01\xd5\xc3\x6d\xa4\xba\xab\x1c\x12\x33\x20\x93\x2b\xe4\x04\ -\x3d\xd2\x44\xae\xef\xf5\x4e\x2a\xdf\x40\x22\x06\xec\xc9\x16\x32\ -\x82\x1e\x6f\x89\x1f\x60\xb0\x78\xe4\xb5\x83\x73\x03\xfa\xf3\x23\ -\xf7\x06\xa2\xf3\xc0\xd6\x88\x64\x50\xb7\x93\x07\xc7\x06\xec\xc9\ -\x0f\xdd\x69\x8c\x2c\x02\xd7\x84\x79\xc1\x7d\xe5\x1b\x70\xf6\x1c\ -\xde\x9d\x1d\xb9\x35\x30\x52\x01\xae\x8f\x48\x46\x13\x9a\x3c\x38\ -\xea\x80\xbe\xbd\xfb\x6f\x4c\x09\x4b\x40\x77\x98\x17\x24\xb1\xca\ -\x37\x60\xbd\x03\x32\xf9\xb1\xeb\xd4\xac\x7d\x0a\x72\x5b\xb3\xa2\ -\x9a\x64\xe5\x1b\xb0\xda\x01\xbb\xf2\x07\xb6\x89\x31\x0b\xc0\x3d\ -\x11\x49\xc1\xfe\x2d\x6f\x23\xb0\x66\x40\x4f\x4f\x31\xdd\xa5\x17\ -\x3e\x00\xee\x8f\x48\xd6\xef\xf7\x57\x02\x2b\x06\x14\x8b\xc5\x60\ -\xcb\xf6\x73\x93\xa8\x0c\x46\x24\x6f\x2a\xdf\x80\x0d\x03\xe4\x8b\ -\xb3\xab\x6f\x02\x4f\x36\xb1\xda\xa8\x7c\xe2\xcb\xbe\x09\xb1\x1b\ -\x90\xc9\x8d\xbe\x28\xe8\x81\x16\x41\xfc\x69\xfb\x30\x62\x35\xa0\ -\x37\x57\xd8\x2f\x70\xa8\x55\x11\x67\x8f\x9b\x2b\x45\x6c\x06\xf4\ -\x66\x47\x0e\x83\xbe\x1b\xe5\xc5\xc3\xb6\x0f\x23\xbe\x0e\x10\x89\ -\x7e\xd0\x00\x24\xd1\x5b\xde\x46\x10\x9b\x01\xd2\xf6\x0d\xef\xf5\ -\xdc\x81\x18\x0d\x30\xc8\x33\xb4\xce\x38\xf1\x2f\x4e\xff\x86\xd8\ -\x12\x5c\x9e\x9d\xf8\x08\x78\xba\x55\xd1\x54\x5c\x31\x6c\x20\xd6\ -\x0a\x2d\xcd\x4e\xbe\x03\x5a\x6c\x66\x05\xc0\x5b\x13\x62\x6f\xd1\ -\xa5\xd9\xf2\x41\x11\xde\x8e\xf2\x8a\x7a\xb9\x1c\x6c\x24\xa5\xbb\ -\xee\xea\x7e\x56\x95\xe9\x30\x29\x88\x58\x8a\xf7\x9f\x60\x25\xa1\ -\x52\xa9\x64\xce\xef\x08\x86\x10\xf9\x38\x22\x09\x9e\x75\x82\xb5\ -\x64\xbe\x1e\x1f\xaf\x5d\x75\x59\x1e\x43\xf5\xf3\x66\x45\x44\x3d\ -\xea\x04\xab\x89\x9c\x3a\x35\x7e\xb1\x66\xea\x0f\x83\x7c\x1b\xe6\ -\x05\xc4\x97\x3d\xc1\x7a\x12\xd5\xf9\xa9\xdf\x6b\x41\xed\x41\x81\ -\x1f\xc2\xbc\x20\x22\x1e\xfc\x48\xcb\x49\x15\xaa\x33\x53\x3f\x13\ -\xd0\x8b\xb0\x1a\xe6\x15\x02\x91\x64\x4d\x70\xd6\x86\x95\x99\xc9\ -\x1f\xa5\xae\xfd\x28\xe7\xc3\xbc\x2a\x01\xeb\x27\x44\x22\x70\xba\ -\x0e\x2b\x27\xcb\x67\x4d\xca\x3c\x04\x5c\x6c\x56\x34\x20\xa1\xe5\ -\xe0\x7c\x23\x5a\x99\x39\xf6\xa5\x22\x59\xa0\xd6\x26\x17\xe7\x26\ -\x24\xb2\x13\x2f\xcf\x4e\x9c\x16\xe5\x09\xa2\x8f\x27\x25\x70\xbd\ -\x31\x26\x76\x14\x55\xe6\x26\x3f\x44\xf4\xa9\x26\x52\xd6\x37\x46\ -\x97\x1e\x24\x7a\x16\x2f\x9d\x28\x1f\x45\x78\xa9\x55\x71\xf7\x82\ -\x4c\xfc\x32\xb2\x74\x62\xf2\x75\x45\xde\x6a\x23\x39\xc9\x2d\x71\ -\x03\x00\xbd\xef\xee\x9b\x9e\x03\xde\x8f\xf0\x4e\xae\xcc\x3e\x18\ -\x40\xa9\x54\x32\xb5\x5f\xbb\x47\x11\x5d\x08\xf3\x7f\x6f\x88\x56\ -\x73\xf4\xc2\x00\x80\x6a\xb5\xb4\x56\xeb\xaa\x3f\x8e\x72\x26\x22\ -\x59\x35\xc1\x1b\x03\x00\xaa\x53\x53\x97\xd3\xdb\x2e\x0d\x2a\x7c\ -\x13\x91\xac\x1d\x0b\x5e\x19\x00\xb0\x38\x3d\x7d\x21\x30\xe9\x01\ -\xe0\x7b\x17\xf1\xbc\x33\x00\xa0\x72\xf2\xc8\x2f\x75\xd5\x3e\xe0\ -\x9c\xed\x58\x5e\x1a\x00\xf0\xd9\x5c\xf9\x27\x13\xd4\xfb\x80\xdf\ -\xda\xc8\xb1\x2d\x09\x6f\x0d\x00\x58\x99\x79\xef\xbb\x20\xd0\x01\ -\xe0\xcf\x88\xb4\x39\xfe\x32\x03\x70\x7a\xa6\xfc\x95\x51\x79\x04\ -\xf4\x9f\x77\x83\x6c\x86\xbf\xcc\x84\xb1\x32\x37\xb1\x0c\x1c\x04\ -\xad\x23\xd4\x45\x78\x2d\xe9\x9c\x3a\xe8\xa0\x83\xff\x07\xfe\x02\ -\xec\x35\x2d\x8c\x9b\x14\xe3\x6d\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x00\x8b\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3d\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\x01\x09\x00\x20\x10\x04\xc1\xd7\x6e\x26\xb0\x82\xfd\x2b\xf8\ -\x29\xe4\x40\x66\x12\x2c\x5b\x05\x00\x00\x00\x00\x00\x00\xc0\xff\ -\xc6\xda\xe7\xa6\x23\x92\x66\x3a\x20\xcd\x80\x74\x00\x00\x00\x00\ -\x00\x00\x00\x00\xbc\xd7\xba\x61\x02\x03\x59\xaf\x8c\x6f\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x85\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x37\x49\x44\x41\x54\x58\x85\xed\ -\xce\xb1\x11\x00\x30\x08\x03\x31\x2e\x4b\xb1\x35\x23\x42\x86\x80\ -\x52\xdf\xdb\xa7\x88\x45\x59\x3d\x59\x3d\x9b\x8f\xb7\x19\x5f\x04\ -\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0\x01\ -\x8b\x69\x06\x03\x87\x7c\xe1\xcd\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x04\x32\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\xe4\x49\x44\x41\x54\x78\x9c\xed\ -\x99\xcb\x6f\x5b\x55\x10\xc6\xbf\x39\xb6\x4b\x02\xa1\x42\x24\x6c\ -\x10\xa9\xa0\x41\x6a\xd3\x76\xe3\xb4\xac\x90\x90\x4b\xec\x8b\xda\ -\x45\x5a\x3f\xb2\x80\x2c\xc8\xc3\x0e\xfc\x03\x88\x55\x1b\xd8\x54\ -\x42\xac\x10\x42\x42\xa1\x24\x15\x2c\xb2\x30\x8f\xb6\x0b\x8c\xac\ -\xb6\x89\x68\x61\x01\x28\xde\xd5\x54\x2a\x46\xa2\xcd\x0a\x58\x54\ -\x55\xd5\xa8\xb1\xcf\xb0\x48\x08\xd7\xf7\x1e\x3b\x7e\xdc\x6b\x17\ -\x31\x3f\xc9\x9b\x99\xf3\x98\xf9\x3c\x67\xee\xb9\x36\x20\x08\x82\ -\x20\x08\x82\x20\x08\x82\x20\x08\x82\x20\xfc\xbf\xa0\x6e\x6d\x1c\ -\x4b\x64\xe2\x20\xfe\x08\x04\xc5\xe0\x4f\x2e\x7d\xf1\xe9\xa9\x6e\ -\xc4\x11\xe8\xc6\xa6\xd1\x64\x26\x43\xc4\x9f\x01\xd8\x0d\xa0\x8f\ -\x40\x2f\x0d\x1d\x0c\xaf\x95\xae\x17\x56\x3b\x1d\x4b\xc7\x05\x88\ -\xa5\x32\x6f\x13\xf8\x03\xb8\xaa\x8f\xc6\x86\x86\xc3\xf7\x4b\xc5\ -\xc2\xf7\x9d\x8c\xa7\x93\x02\x90\x95\xcc\xbc\x0f\xf0\xe9\xda\x23\ -\x28\xb6\xf7\xc0\xc8\x63\xa5\xe2\xea\xa5\x8e\x05\xd5\x89\x4d\x22\ -\x91\xb9\x60\xe8\xc9\xb5\x79\x10\xa6\x1a\x19\xcf\xa0\x85\xf2\x5f\ -\x4f\xbf\xb1\xb2\xf2\x6e\xd9\xef\xd8\x7c\x17\x20\x32\x39\xd9\x13\ -\xbc\x1b\x5a\x22\xf0\x49\x83\x5b\x13\x01\xcc\x50\x86\xc8\xbe\xde\ -\xe8\x2b\xbf\xb6\x72\xee\xdc\xba\x9f\xf1\xf9\x2a\xc0\xb1\x89\x89\ -\xdd\x1b\xeb\x8f\x9e\x27\xf0\x51\xbb\x9d\x37\x37\xae\x54\x8f\xe6\ -\x80\xbb\x2d\xe0\x4a\xef\x03\x7d\xf2\xe2\xc5\x85\xbb\x7e\xc5\xe8\ -\x9b\x00\xc7\xc6\xa7\x9e\x2a\x57\x02\x39\x10\x0e\x1b\xdc\x15\x83\ -\x0d\x30\xf7\xa4\x9f\x83\xaa\x72\x3c\x97\x5d\xfc\xc3\xc3\xf0\xb6\ -\xf1\x45\x80\xe8\xf8\xec\x1e\x68\x9d\x27\x60\x9f\xdd\xce\x60\x26\ -\x90\xae\x37\x97\xc1\x8a\x40\x54\x6d\xc3\x0d\x55\xae\xc4\xf2\x17\ -\x16\x6f\x79\x1d\xab\xe7\x02\x44\xe3\xe9\x61\x52\xc8\x03\x78\xc6\ -\xe1\x62\x00\x75\x93\xff\x77\x24\x2b\x10\x39\x63\xbb\x45\x50\x56\ -\xfe\xcb\xf9\x5f\x3c\x08\x73\x1b\x77\xf3\x69\x83\xd1\x44\xe6\x05\ -\x52\xb8\x0a\x67\xf2\xdc\x44\xf2\x00\x40\xa4\x01\x66\x87\x75\x90\ -\xa1\xaf\xc5\x92\xd3\x47\xda\x0e\xd4\x86\x67\x02\xc4\x52\x33\xa3\ -\x8a\xf8\x0a\x80\xfe\x6a\x0f\x33\xa8\x89\xe4\xb7\x21\xcd\x9b\x55\ -\x63\xa7\x1f\x50\xcb\x56\x3c\xfd\x72\xab\x71\x3a\xf1\x44\x80\x68\ -\x2a\x9d\x00\xd3\x37\x00\xfa\xec\x76\x06\x33\x76\x38\xf3\xf5\x20\ -\x40\x33\xbb\x44\xe8\x63\x85\x5c\x2c\x91\x89\xb7\xba\xae\x9d\xb6\ -\x6f\x82\x56\x22\x3d\x03\xe0\x73\x00\x41\xbb\x9d\x00\x0d\x90\x33\ -\xf8\xa6\x21\x02\x6f\xf5\x44\x7b\x4f\x08\x80\x30\xfe\xfc\x81\xf0\ -\xed\x5f\x8b\x85\x42\x3b\xeb\xb7\x25\x80\x95\x4c\xbf\xc5\x84\x0f\ -\x1d\xc1\x6d\x7e\x73\xee\xf2\x6d\x8b\xad\x96\x68\xdf\x87\x00\x3a\ -\xb1\xf7\x60\xf8\x5e\xe9\x7a\xe1\x87\x56\xd7\x6d\x55\x00\x8a\xa5\ -\x32\xef\x01\x78\xc7\xed\x81\x86\xc7\xc9\xdb\x17\x87\x4b\x6c\xb2\ -\x86\x86\xc3\xbd\xa5\x62\xe1\x72\xcb\x2b\x36\x43\x24\x32\x17\x0c\ -\xf5\xaf\x7d\x0c\x60\xc6\xe0\xf6\x31\xf9\x6d\x08\xa6\xde\xc5\x38\ -\xfb\x44\xe0\xce\x9b\xd9\x6c\xb6\xd6\x25\xcb\x48\x53\x15\x10\x99\ -\x9c\xec\x09\x05\xee\x2d\x01\x98\x70\x6c\xee\xf3\x37\x6f\x80\x41\ -\x8e\x03\x31\xb2\xce\x3d\x87\xf6\x3d\xfb\xe2\x85\x9b\x37\x7f\x6c\ -\x58\x84\x86\x2b\x60\x6c\x6c\xfa\xf1\xfb\xbb\xd4\x79\x30\x5c\x8f\ -\x20\x3f\xce\x7c\x03\x98\x2b\x01\xb8\xdc\xbb\xa1\xe3\x8d\xbe\x3f\ -\x34\x24\x40\xe4\xd5\xd9\x81\xd0\x03\x9d\x03\x60\xb8\x84\x50\xa5\ -\xf3\xb9\x57\x61\xaa\xe2\x9f\x36\x76\xa9\xe3\x2b\x4b\xf3\x7f\xee\ -\x34\x79\x47\x01\xac\x13\x53\x83\x1c\x0c\xe4\x01\xec\xaf\x72\x30\ -\x5a\xbc\xe0\xf8\x82\x82\x3b\x97\x62\x90\x61\xe5\xbe\x3a\x7b\xbb\ -\xde\xc4\xba\x02\x58\xc9\xd9\xfd\x0c\x9d\x07\x30\x68\xb7\x33\xc0\ -\xd4\xcc\xd5\xb6\x13\x98\xdf\x1f\x7e\x0f\x28\x6d\x7d\x9b\x5d\xb8\ -\x51\x6b\x5a\xcd\x9b\x60\x2c\x39\x7d\x84\x59\x5f\x85\x33\x79\xc6\ -\x8e\x6f\x74\x5d\x81\xc8\xd4\x84\xf7\x54\x2a\xea\x9a\x35\x9e\x36\ -\xbd\x92\x03\xa8\x21\xc0\x2b\x89\xe9\xa3\x80\x5a\x06\x61\xc0\xe1\ -\x62\x22\xe8\x2e\x9f\xf9\x7a\xb8\x45\x20\x0c\x68\x8d\xe5\x68\x2a\ -\x1d\x31\x4d\x70\x35\x90\xd1\x44\xfa\x14\x13\x2d\x12\xf0\x88\x61\ -\xfc\x3f\x9d\xf7\x61\xfe\xb8\x8e\xf5\x56\x2e\xaf\x3f\x37\x3c\xa2\ -\x7f\x2b\xae\x7e\x67\xf7\xb9\x2a\x40\x11\xe6\xa8\x8b\x7f\x98\xf8\ -\x05\x01\xa4\x08\x73\x4e\xbb\xa7\xbf\x07\xfc\x17\x31\x55\xc0\x19\ -\x7a\x78\x1e\x6f\x9e\x41\x04\xad\x08\x67\xba\x1d\x87\x20\x08\x82\ -\x20\x08\x82\x20\x08\x82\x20\x08\x82\xd0\x6d\xfe\x06\xf7\x21\x1d\ -\x03\xf2\x02\xba\x61\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ -\x82\ -\x00\x00\x03\xe3\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x95\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x3d\x48\x5b\x51\x14\xc7\xff\xe7\xe5\x49\x07\xb1\x2a\x16\x22\ -\x58\x74\xae\x43\x15\x92\x22\xdd\x84\x56\x1d\x14\x37\xeb\x50\x41\ -\x07\x89\x14\x5a\x3f\xa6\x52\x87\x06\x85\x62\xe9\xe2\x47\x1d\xaa\ -\x38\x28\xb8\xa8\x9b\x28\x54\xdb\xa1\x43\xa1\x88\x06\xd4\xc1\xce\ -\x8a\xb6\xa6\x90\xfa\x41\x1d\x6c\x93\x77\x3a\xa8\xe5\xe5\xe5\x45\ -\x93\xdc\x97\x5c\xad\xf7\xb7\xdd\xf3\x4e\x4e\xfe\xf7\xff\xde\xbb\ -\xf7\x92\xdc\x0b\x28\x14\x8a\xeb\x0c\x25\x92\x54\xe9\xf7\xeb\x47\ -\xbb\x05\xf5\x06\xd0\x48\x20\x2f\xc0\x45\x00\x6e\xa4\x59\x5b\xb2\ -\x1c\x03\xb4\xc3\xe0\x15\x0d\x98\xca\x2e\x0c\xcd\x7e\xea\xe9\x09\ -\x5f\xf4\xa1\x0b\x0d\xf0\xb6\x0d\x57\x81\x79\x10\xc4\x77\x9c\xd1\ -\x99\x19\x18\xd8\x20\x68\x9d\x2b\x23\x4f\x3f\x9c\x97\xa7\x9d\x53\ -\x82\xbc\xbe\xa1\x6e\xc0\x58\xbc\x6a\x9d\x07\x00\x02\x4a\x01\x63\ -\xf1\x5e\xdb\xe0\x0b\x80\xe3\xde\x68\x57\xbc\x0b\x5e\x5f\x41\x37\ -\x08\xaf\xd2\x23\x2f\x93\xd0\x83\x22\xef\xd2\xf1\xb7\xc0\xfb\xcf\ -\xb6\x57\xed\x82\xde\xb6\xe1\x2a\xc0\x58\xb4\x84\xf7\x40\x78\xa9\ -\x85\x69\xbe\xe4\xc0\xbd\x35\x33\xf3\x28\xe2\xb8\x56\x01\x1a\x1a\ -\xa6\x5d\x9b\xb9\xc1\x62\x43\xe7\x5a\x30\x7a\x01\xe4\x47\x67\x68\ -\xd5\x76\xaf\x43\x8c\x01\x95\x7e\xbf\xfe\xeb\xfb\xad\xf5\xa8\xc7\ -\x9e\xf0\xd1\x15\x36\x9a\x96\xc6\x3a\x83\xce\x4b\x77\x9e\x8a\xd6\ -\x01\x77\x44\xd7\x26\xc1\x78\x78\x16\x63\x60\x23\xa7\x30\x54\x66\ -\x1d\x18\x63\xc6\x80\xa3\xdd\x82\x7a\xcb\x3b\xff\xf3\x37\xb2\x1e\ -\x5f\x95\xce\x03\xc0\xd2\x58\x67\xd0\x15\x36\x9a\x00\xec\x9d\xc5\ -\x08\x28\x3d\xda\x2d\xa8\xb7\xe6\xc6\x18\x60\x00\x8d\x51\x01\x82\ -\x7f\xfd\xdd\x93\x1f\xe9\x10\x9a\x4e\x96\xc6\x3a\x83\x0c\xf6\x9b\ -\x63\x31\x7d\x83\x8d\x01\x27\xf3\xbc\x29\x21\x4c\xf3\xce\xcb\xcb\ -\x0c\xae\x88\x36\x67\x6e\x13\xe0\xb1\xe6\xd8\x4c\x83\x5c\x64\x6e\ -\x95\x1c\xb8\xb7\x9c\x16\x96\x29\x6c\xb4\xdf\xb6\xe6\xd8\xad\x03\ -\xa2\x56\x78\x97\x6d\xb4\x4f\x06\x1b\xed\x31\xab\xd7\x73\x16\x42\ -\xd7\x03\x65\x80\x6c\x01\xb2\x51\x06\xc8\x16\x20\x1b\x65\x80\x6c\ -\x01\xb2\x51\x06\xc8\x16\x20\x1b\x65\x80\x6c\x01\xb2\x51\x06\xc8\ -\x16\x20\x1b\xdd\x89\x22\x1e\xdf\x50\x35\x08\x6f\x08\xb8\x8b\x04\ -\xff\x6b\x10\x80\x01\x5a\x63\xe6\xe7\x81\xd1\x76\xeb\xef\x96\x49\ -\x23\xfc\x04\x78\x7c\x83\xcd\x44\x58\x20\xa0\x0c\xe9\xef\x3c\x4e\ -\xbe\x83\xcb\x89\xb0\xe0\xf1\x0d\x36\x8b\x16\x13\x32\xa0\xbc\xa5\ -\x3f\x8f\x88\xde\x8a\x8a\x48\x15\x22\x1a\x2a\x6f\xe9\xcf\x13\xa9\ -\x21\x64\x80\x9e\xa5\xdf\x07\x90\x23\x52\x43\x90\x9b\xa7\x1a\x52\ -\xe6\xda\x0f\x82\x42\x06\x84\xff\x84\xbf\x00\x38\x74\x48\x4b\x2a\ -\x1c\x9e\x6a\x48\x19\x21\x03\x56\xc7\xbb\xf6\x99\xb9\x5d\xa4\x86\ -\x08\xcc\xdc\xbe\x3a\xde\xb5\x2f\x52\x43\xf8\x15\x08\x8c\x76\x4c\ -\x30\xa3\x06\xa0\x55\x00\x2c\x5a\x2f\x01\x98\x81\x35\x66\xd4\x04\ -\x46\x3b\x26\x44\x8b\x39\xb2\x0e\x38\x9d\x8f\x85\xe7\x64\x19\xa8\ -\x41\x50\xb6\x00\xd9\x28\x03\x64\x0b\x90\x8d\x32\x40\xb6\x00\xd9\ -\x28\x03\x64\x0b\x90\x8d\x32\x40\xb6\x00\xd9\x28\x03\x64\x0b\x90\ -\x8d\x32\xc0\x26\x76\x6c\x6e\x34\x34\x4c\xc7\xdd\x4e\x7b\xd9\xb1\ -\xd1\x7e\x6c\xcd\xb1\x31\x80\x76\xcc\xad\xcd\xdc\x60\xb1\xa3\xaa\ -\x32\x88\x8d\xf6\x6d\x6b\x4e\x8c\x01\x0c\x5e\x31\xb7\x0d\x9d\x6b\ -\x1d\xd6\x95\x31\x22\x2e\xa3\xce\xdc\x66\x20\x60\xcd\x89\x31\x40\ -\x03\xa6\xa2\x02\x8c\xde\x8a\xd6\x01\xb7\xe3\xea\xd2\x4c\x45\xeb\ -\x80\x9b\x40\x3d\xe6\x58\x4c\xdf\x60\x63\x40\x76\x61\x68\x16\x4c\ -\x5f\x4d\xa1\xfc\x88\xae\x4d\x5e\x25\x13\xfe\x6d\x96\x36\xed\x18\ -\x67\x60\x23\xbb\x30\x34\x6b\xcd\x4d\x6a\xbb\x3c\x83\xfd\xae\x88\ -\x36\x77\x99\xb7\xcb\x47\x5c\x46\xdd\xe9\x9d\x4f\x6d\xbb\xfc\x19\ -\x5e\xdf\xd0\x7f\x72\x60\x02\x20\x70\xf7\xf2\x48\x47\x9f\xdd\xb5\ -\xb8\xeb\x80\x95\xd1\x67\x7d\x04\xee\x4e\x9f\xac\x8c\xc0\xcc\xf4\ -\x62\x79\xa4\xfd\x75\xbc\x84\x84\x0e\x4d\x31\x8c\x81\x93\x33\x38\ -\x57\x87\x44\x0f\x4d\xa5\x70\x6c\x0e\x1e\x9c\xec\xba\xbe\x84\xc7\ -\xe6\xb0\xcd\x40\x20\x99\x63\x73\x0a\x85\xe2\x7a\xf3\x17\x37\xaf\ -\x1e\xac\x94\x31\x9b\x08\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ -\x60\x82\ -\x00\x00\x05\x08\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\xba\x49\x44\x41\x54\x58\x85\xe5\ -\x97\x5b\x6c\x94\x45\x14\xc7\x7f\x67\xbe\xd2\x2a\x78\x21\x2d\x89\ -\x8b\x72\x6d\x40\xb1\x51\xa3\x74\xb7\xe8\x83\x37\x24\x90\x80\x5c\ -\x34\x56\x43\x34\x62\x08\x74\x4b\x61\x0b\x9a\xa0\xa0\xc4\xb5\x01\ -\xb1\xbe\x40\xba\x5d\x5a\x76\x6d\x62\x48\x78\xb2\x89\x0d\x54\x40\ -\x49\x34\xf0\xa4\xa5\xbb\x36\x3c\xd8\x60\x4c\x20\x60\x69\x4b\x84\ -\x26\x1a\x01\xbb\xec\xce\xf1\x61\xbb\xcb\xd7\xfb\x45\xdf\xf8\xbf\ -\x7d\x67\xce\x39\xff\xff\xcc\x37\x33\xe7\x0c\xdc\xe9\x90\xf1\x38\ -\xfb\x2a\x0e\xcc\xb4\xa9\xe4\x1a\x51\x59\x82\x30\x13\x61\x06\x8a\ -\x41\xb9\x8c\x48\x07\xc2\x69\x47\x6d\x53\x4b\x64\xeb\x6f\xff\xab\ -\x00\x6f\x79\xa8\x04\xa5\x1a\x78\x71\x8c\x59\x5b\x45\x75\x67\x6b\ -\x64\xeb\xf7\xff\x49\x40\x71\x59\xe4\x7e\x91\xde\x7a\x60\x6d\x9f\ -\xa9\x0b\xa4\x59\x95\x13\xea\xa4\xce\xeb\x3f\xa6\x6b\xd2\x64\x63\ -\x35\x81\xc7\x8a\x9d\x63\x0c\x4b\xd5\xb2\x1a\x61\x76\x5f\xfa\xe3\ -\x4e\x2a\xb5\xbe\xa5\x61\xdb\x95\x71\x0b\x58\x58\x71\x60\x9e\x49\ -\xda\xa3\x88\x3e\x0a\x74\x89\x10\x9c\xf2\xc0\xb5\x2f\x4f\x55\x55\ -\x25\x47\x9c\x52\x30\x68\xbc\xdd\x05\x6f\x80\xec\x01\x2d\x04\x2e\ -\x19\x58\x75\x26\x52\x79\x76\xcc\x02\xbc\x9b\xf6\x15\x62\x73\x5a\ -\x80\x69\xc0\x11\x27\x97\xb7\x5b\x6a\x2b\xff\x1a\x91\x78\x00\xe6\ -\x05\x42\x79\x53\x7b\xa9\x43\x58\x0f\x5c\x47\x78\x36\x76\xb0\xb2\ -\x6d\x54\x01\x8b\x02\xa1\xfb\x92\x09\x7e\x14\x28\x52\xb4\x26\xee\ -\xe9\x79\x8f\xaa\x2a\x3b\x1e\xf2\xdb\x50\xf1\xf9\x43\x3b\x14\xd9\ -\x0b\x74\xa8\xa6\x4a\xe2\xd1\x77\xbb\xdc\x1e\x39\x03\x43\x52\xbd\ -\x84\x45\x28\x02\x9a\x87\x22\x4f\x9f\x84\xd4\x06\x81\xe5\x02\xb3\ -\x14\x2c\xc8\x45\x55\x8e\x41\xb2\xa1\x3f\x81\x68\x6b\x44\xab\x7d\ -\xe5\xb5\x85\xaa\x6c\x30\xe2\x1c\x06\x5d\x02\xa2\x43\xae\x40\x89\ -\xbf\xd6\x6b\xd1\x56\x84\x3f\xd4\xe6\xcd\x8f\x47\xfd\x7f\x66\x07\ -\x83\x41\xe3\xeb\xce\xff\x40\x91\x8f\x81\xbb\x86\x99\xf2\x75\x55\ -\x3e\x8c\x47\x03\xb5\x6e\x92\xa2\xd2\x60\xee\xe4\xfc\x82\xb3\xc0\ -\x02\xd0\x15\xb1\xc8\xd6\xe3\x99\x31\xe3\x8e\xb6\xa2\x9f\x01\xa8\ -\xea\xee\x81\xe4\xde\xee\xfc\x43\x7d\x4b\x39\x1c\x39\xc0\x14\x11\ -\x6a\xbc\xfe\x50\x1d\x68\x76\x72\xed\x8d\x55\x09\x81\x8f\xfa\xe6\ -\x5c\xed\x1e\xcb\x0a\x28\x2e\xdb\x3f\x1d\xe5\x25\xa0\xe7\x66\x4f\ -\x4f\xc4\x9d\xd5\xd7\x5d\xb0\x0b\xe4\xad\x11\x88\x5d\x50\x40\xca\ -\x7d\xfe\x70\xa5\xdb\xda\x1a\x09\x34\x01\xe7\x80\xc7\x4b\xfc\xb5\ -\x4f\x0c\x12\x20\x98\x95\x80\xa0\x1c\x6b\x6f\xac\x4a\x64\xec\xde\ -\x4d\xfb\x0a\x15\x76\x8d\x8d\x3c\x9d\x29\x2d\x43\x3f\x7d\x6a\x4b\ -\xed\x83\x2e\xbb\xa2\x7a\x14\xc0\x8a\xbe\x32\x48\x00\x22\x2f\xa4\ -\x03\xe5\xdb\x7e\xe9\x34\xa7\x02\x98\x34\x76\x01\x59\x4c\x71\x12\ -\x6c\x74\x1b\xac\x31\xdf\xa5\x73\xca\xe2\xc1\x02\x60\x26\x80\x23\ -\x72\xc1\x1d\xa4\xca\x8a\x09\x90\xa7\x21\xfa\xb2\xfb\x33\x97\xe4\ -\x79\x00\x85\x19\x83\x04\x64\x8c\x46\x6e\xb9\x8e\x91\x0a\x50\x38\ -\x71\x01\x99\x2b\x39\x8d\xab\x93\x9c\x4c\xee\x87\x32\x1b\xd1\x0c\ -\x0a\x72\x23\xf8\x89\x8c\xea\x33\x12\x14\x67\x94\xdc\xee\x4d\xc8\ -\x65\x80\x84\x38\x9e\xac\x53\xfa\x12\xba\x38\x61\x01\xc8\x25\xf7\ -\xd7\xbd\xd6\x78\xd2\xba\xe8\xcc\x5c\x70\xb7\x67\xa7\xf2\x3b\x80\ -\xb1\xcc\x1d\x90\xe4\x38\x13\x85\x68\xbf\x58\x73\x2b\x55\x08\x20\ -\xd0\x91\xb5\xdd\x1e\xd5\x53\x00\x22\xb2\xcc\x1d\xe4\xa0\x07\x81\ -\x89\xd4\x82\x84\x49\x4a\x43\x3f\x01\x86\xa5\x00\x0a\x3f\x0c\x12\ -\x90\xca\x91\x66\x00\x55\x5d\x51\x5c\x16\xc9\x1e\xbb\x96\x48\x65\ -\x3b\x10\x1a\x37\xbd\xca\xde\x33\x0d\x81\x0b\x6e\x83\x55\x59\x05\ -\x60\x6c\xaa\x69\x90\x80\xb6\x70\xa0\x53\xd2\xca\xa6\x41\xef\x86\ -\x7e\xb9\x34\xef\xfd\xf1\xfd\x0a\x6d\x8c\x4d\xbf\xba\xdb\x6d\xf1\ -\x6e\x0a\xaf\x14\x28\x02\x7e\x69\xfd\x62\x5b\xb6\x37\xe8\xbf\xc3\ -\xad\xdd\x01\x20\x42\x70\x51\x20\x74\x5f\xc6\x1c\x8f\xfa\x6f\xa9\ -\xe6\xae\x51\xb4\x86\x91\x7f\x47\x12\x61\xef\xdc\x9e\xe9\x6b\xdd\ -\x55\xb4\xa8\x34\x98\xab\x36\x5d\x67\x04\x76\x0e\x5b\x0d\x01\x8a\ -\xfd\xa1\xc3\x02\x6f\x02\x47\x62\x9e\x6b\xaf\x0e\x2c\xc7\xde\xf2\ -\x9a\xc7\x50\x29\x07\x96\x03\xb3\x48\x5f\xfe\x17\x15\xfd\x46\x8c\ -\xd6\xc7\xea\xb7\xfd\x3a\x60\x35\xc4\x5b\x56\x5b\x8f\xe0\x07\x4e\ -\xc5\x22\x81\xc5\x23\x0b\x48\xf7\x81\x3f\x01\x0b\x80\x7d\x31\xcf\ -\xb5\xed\xc3\x35\x24\xa5\xa5\x5f\x39\x00\x8d\x8d\xaf\xa7\x86\x5e\ -\x10\x15\x6f\x79\x78\x3b\xaa\x9f\xa3\x74\xa6\x72\xc5\xd7\x16\x0e\ -\x74\xba\x3d\x86\x6c\xc9\x16\x56\x1c\x98\x67\x52\xa9\x16\x20\x1f\ -\xf8\xfa\x86\xe3\xac\x6b\xaf\xdb\xfc\xf7\xd0\x24\x43\xa3\xa8\x34\ -\x98\x7b\x77\x7e\x41\x58\x60\x23\x70\xc3\x20\xcf\x9f\x89\x04\x62\ -\x03\xfd\x86\x6d\x4a\x4b\x36\x86\x1f\xb6\xc6\x1e\x05\x1e\x51\xe4\ -\xb2\x40\xf0\x1e\xcf\xd5\x43\x63\x69\x4a\x7d\x57\xf2\x5f\xb3\x2a\ -\x7b\x04\xe6\x03\x1d\xaa\x66\x75\x3c\xba\xe5\xe7\xa1\xdc\x47\x6c\ -\xcb\x9f\x7c\x67\xff\xd4\x9c\x3c\x13\x05\x29\xed\x33\x75\x88\xd0\ -\x8c\x72\x02\x6b\xce\xe7\xd8\x44\xd7\xcd\x94\x58\x27\x37\xc7\xa3\ -\x86\xd9\xc6\xda\x65\x88\x59\xdd\xd7\x0d\x03\x9c\x14\xc7\x59\xd7\ -\x5a\xb7\xb9\x7b\x38\x8e\x31\x3d\x4c\x4a\xfc\xe1\x67\x2c\x5a\x0d\ -\xfa\xdc\x58\xfc\x81\x36\x55\x76\xc4\xa3\x95\x27\x47\x73\x1c\xd7\ -\xd3\xec\xe9\xf2\xfd\x73\x92\xd6\x59\x83\xb0\x04\xed\x7b\x9a\x81\ -\x03\x74\xa4\xaf\x57\x3d\x6d\xd5\x34\xc5\xa3\x81\x73\xe3\xc9\x7b\ -\x67\xe3\x5f\x5e\xef\xd7\x3d\x0b\xb2\x5f\x42\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xf6\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xa8\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\x31\x15\x80\x30\x00\xc4\x50\x5a\x53\xf5\x81\x50\x7c\x60\x0a\ -\xba\xe2\xe0\x33\x24\xdb\x4d\x97\x97\x71\x20\xd6\xf5\xbc\xdf\x7d\ -\x9f\x73\x08\x8f\x29\x4e\xff\x44\x01\xb4\x80\xa6\x00\x5a\x40\x53\ -\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\ -\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\ -\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\ -\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\ -\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\ -\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\ -\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\ -\x0d\x64\x41\x04\x80\xc9\xe4\x92\xad\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x00\x87\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x39\x49\x44\x41\x54\x58\x85\xed\ -\xce\x31\x11\x00\x30\x08\x04\x41\x26\xe2\x50\x80\x04\x84\x20\x3d\ -\x22\xa0\xdc\xeb\xff\x67\x23\x16\x65\xf5\x64\xf5\x6c\x3e\xde\x66\ -\x7c\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ -\xc0\x07\x65\x23\x03\x3b\x58\x7b\xaf\x09\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x75\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x27\x49\x44\x41\x54\x78\x9c\xed\ -\xc1\x01\x0d\x00\x00\x00\xc2\xa0\xf7\x4f\x6d\x0e\x37\xa0\x00\x00\ -\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x77\x03\ -\x40\x40\x00\x01\x8f\xf2\xc9\x51\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x0a\x60\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x0a\x12\x49\x44\x41\x54\x78\x9c\xed\ -\x5b\x6b\x90\x14\xd5\x19\x3d\xe7\xce\xcc\xae\x83\x2c\x88\xf8\x48\ -\x4a\x28\x83\x31\x96\xae\x01\x4c\x70\x99\x5d\x82\x2b\x98\xa4\x54\ -\x82\x2c\xbb\x8b\x1b\x1f\xa5\xe2\x23\x2a\x26\xc6\xc4\x24\x26\x5a\ -\xa5\x8b\x46\x8d\xc6\x08\x96\x55\x06\xb5\x82\xa5\x22\x95\x64\x60\ -\x77\x00\x2d\x51\xab\xc4\xb5\x10\xd9\x5d\x5e\x6a\xf9\xc0\x32\x51\ -\x11\x42\x34\x2a\xca\x43\x79\xcc\xf4\x3d\xf9\xb1\xa0\xdd\x3d\x33\ -\xdd\x33\x3b\x33\x94\x95\x70\xaa\xe6\x47\x7f\xf7\xdc\xef\x9e\xfb\ -\x4d\xf7\xed\xfb\xf8\x1a\x38\x80\x03\x38\x80\xff\x67\x70\x7f\x34\ -\x72\x4a\x52\x87\xef\x89\xa1\x91\xd6\x8e\x94\xc1\xf1\x14\x8f\x11\ -\x70\x08\x80\x41\x00\x22\x00\xb6\xed\xfd\xbd\x27\xe8\x0d\xc0\xbc\ -\x8e\x28\x96\xf7\x4e\xe1\x3b\x95\xd6\x56\xb1\x00\x8c\x4b\xe9\x9b\ -\x8e\xb5\xd3\x41\x4e\x01\x30\xaa\x5f\x4e\x84\x77\x60\xb4\xd4\x5a\ -\xf3\xf0\xaa\x16\xac\x06\xa9\xf2\xaa\x2c\x77\x00\x24\x36\xa4\x70\ -\xba\x85\xae\x03\x30\xb1\x9c\xae\x09\xbc\x2a\x70\x56\xe6\x43\x3c\ -\xb6\xe6\x0a\xa6\xcb\xe8\xb7\x3c\x48\x74\x68\x22\x8c\xfe\x08\xe1\ -\xe4\x72\xf9\xcc\x83\x77\x05\xce\xec\x6d\xc6\xa3\xe5\xb8\x23\x4a\ -\x0e\x40\x62\xb1\x8e\x94\x63\xef\x26\x78\x7e\x00\xcd\x02\x58\x01\ -\xaa\x4b\xd6\xac\x37\x11\xfc\x53\x19\x6c\xb1\x16\xdb\x0f\x02\x9c\ -\x9d\x06\x35\x31\x60\xb0\x0c\x46\x08\x38\x0e\x50\x03\x80\x1f\x02\ -\x88\x07\xf8\x5c\x6e\x2d\x67\xac\x9a\xc6\xd7\x4a\xd1\x5f\x52\x00\ -\x1a\x52\x1a\x6b\xa5\x45\x00\xbe\x9e\xa3\x78\x3b\xa8\x27\x29\xf3\ -\xb8\x05\x9e\xea\x6d\xe1\xc7\x45\xf9\x4e\x2a\xee\x44\x70\x1a\x69\ -\xcf\x02\x38\x25\x4f\x1b\xbb\x44\x5e\xd2\xdb\xcc\xbf\xf6\x47\x3f\ -\x50\x42\x00\xc6\x76\xe8\x3c\x50\x0f\x11\xa8\xf6\x8b\xa2\x74\x6f\ -\xb4\xda\xdc\xf1\xc2\x64\x7e\xd2\x5f\xff\x6e\xd4\x26\x55\x55\x13\ -\xc5\x4f\x00\xdd\x04\xe0\x08\x7f\xb9\xa0\xdb\x7a\x5f\x36\x37\xe1\ -\x66\xda\x62\x7d\x17\x1f\x80\x76\x99\xc4\x28\x7b\x2b\xc8\xeb\x7d\ -\x25\x56\xd0\x43\x94\xb9\xb9\xa7\x95\x9b\x8a\xf6\x5b\x00\xbe\xb7\ -\x58\x35\x69\x8b\x6b\x29\xfd\x1a\xc0\x40\x4f\xa1\xb0\x28\xee\xf0\ -\x82\xae\x36\xee\x28\xc6\x67\x71\x01\x68\x97\x49\x8c\xb6\xf3\x01\ -\x9e\xe3\x2b\xd9\x6c\xc8\xe6\x95\xcd\xec\x2d\xca\x5f\x3f\x91\xe8\ -\xd0\x30\x18\xa5\xfc\x03\xae\x88\x75\xac\xe6\x84\x9e\x49\xdc\x56\ -\xa8\x2f\x53\x54\xc3\x27\xd9\x99\x39\x3a\xdf\x9d\x11\x4f\xde\x5f\ -\x9d\x07\x80\x9e\x56\x6e\x32\x69\x36\x0a\x9a\xef\xb6\x53\xf8\x0e\ -\x77\x69\xfe\xd9\x49\x45\x0a\xf5\x55\x70\x00\xea\x3b\xf4\x63\x88\ -\x37\x7a\x1a\x84\x1e\x89\x6f\xe5\xc4\x35\xad\xfc\x77\xa1\x7e\xca\ -\x85\x95\x6d\xdc\xd9\xdb\x6c\x2e\x10\xf9\x5b\x00\x5f\xbc\x0e\x05\ -\x4c\xde\x18\xb1\xb7\x17\xea\xa7\xa0\x47\x60\xec\x42\x9d\x4c\xa3\ -\xe5\x00\x0e\xfa\xd2\xaa\xc7\x7a\x9a\xcd\x85\x95\x98\x9d\x15\x8b\ -\x44\x87\x7e\x01\x6a\xb6\xdb\x26\xf0\xa2\xde\x16\x3e\x1a\x56\x37\ -\x34\x00\x63\x3b\x35\x94\xd0\xcb\x00\x8e\x72\x99\x7b\xe3\x5b\x79\ -\x6a\xd7\xc5\xdc\x55\x8c\xd0\xfa\x4e\x9d\x60\x85\x66\x1a\x3b\x0a\ -\xe2\x30\x00\xc3\x00\x38\x00\x36\x91\xda\x24\x6b\xd6\x2a\x86\xce\ -\xa2\xd7\x00\x12\x13\x29\x3b\x17\xe0\xc5\x2e\xeb\x1e\x8a\x0d\xdd\ -\xad\x5c\x1b\x54\x35\x34\x00\x89\x4e\x67\x2e\xc0\x4b\x5c\xa6\xcd\ -\xd1\x08\xeb\x56\x34\x71\x73\x21\xda\x6a\x93\xaa\xaa\x89\x61\x06\ -\xa4\x2b\x01\x1c\x5f\x48\x1d\x11\xeb\x0c\x78\xef\xf0\x34\xe6\x2d\ -\x68\xa3\x53\x48\x9d\x33\x9f\x54\xf5\xc7\x3b\xb5\x8c\xc4\x38\x97\ -\x79\x6d\x7c\x08\x13\x5d\x13\x99\xc9\x57\x2f\x30\x00\x89\x4e\x8d\ -\x07\xb4\xdc\xad\x0d\xe2\xb8\x9e\x56\x76\x17\x22\x6a\x6c\x4a\x53\ -\x69\x75\x17\x88\x63\x0b\xe1\xe7\xc0\x4b\x02\x7f\xd5\xdb\xc2\x65\ -\x85\x90\x13\x8b\x75\x24\x1c\xbd\x0a\xe0\xb0\x7d\x36\x82\xd7\x74\ -\xb7\xf0\xde\x7c\x75\xf2\x0f\x82\x12\x01\xfd\xc1\x67\x9c\x5f\x48\ -\xe7\xc7\x3c\xa0\x58\x22\xe5\xdc\x47\x29\x55\x42\xe7\x01\xe0\x24\ -\x42\xcf\xd6\x77\x38\x33\xd1\xae\xd0\x01\xbb\xa7\x89\x1f\x40\xbc\ -\xcd\xa3\x18\xba\x71\xd4\xd3\x3a\x38\x5f\x9d\xbc\x4e\x1b\x52\x68\ -\x04\x30\xde\x65\x4a\x3b\xd6\xb4\x87\x89\x18\xff\x84\x86\xc4\x0e\ -\xd7\x52\x88\x57\x85\x71\x0b\x85\xc8\xf6\xc4\x68\xfd\x7d\xcc\x12\ -\x0d\x08\xe3\xc6\xb7\xe1\x7e\x12\xef\xb9\x4c\x87\x0d\xf8\x0c\x57\ -\xe4\xe3\xe7\x0d\x80\x85\x7e\xe3\xbe\xa6\xf4\xc0\xea\x69\x7c\x3b\ -\xa8\xf1\xda\xa4\xaa\xd2\x7b\xb4\x48\xc0\xf7\xc3\x84\xf6\x03\xd3\ -\xa2\x69\x3d\x1a\x76\x27\xf4\x0d\xcc\xf4\xfc\x51\x82\xae\xcd\x37\ -\x37\xc8\xe9\xac\x2e\xa9\xaf\x01\x38\xc3\x65\x4a\x2b\x6a\x6e\x0d\ -\x94\x27\x71\x60\xd4\xde\x07\xa0\x31\x90\x57\x0a\x88\xd6\xc4\x68\ -\x1b\x7a\x17\x0e\x4f\x63\x1e\x80\xb7\x5c\xa6\xa3\x36\x18\xfc\x20\ -\x17\x37\x67\x00\x22\x51\x9c\x87\xbe\xad\xaa\x7d\x0d\x2f\xeb\x69\ -\xe2\x07\x41\x8d\x26\x16\xe1\x7c\x82\x97\x85\x89\x2b\x1d\xbc\xa9\ -\x7e\xa1\x72\x76\x66\x1f\x16\xb4\xd1\x21\xb4\xc0\x53\xcb\xd8\x8b\ -\x72\x71\x73\x06\x40\xd0\x59\x1e\x83\xe5\x92\xa0\x06\xc7\x2c\xd1\ -\x00\x48\x77\x04\x71\xca\x09\x19\xcd\x0a\x9d\xee\x1a\xe3\xd3\xcc\ -\x49\xb9\xea\x64\x05\x60\xef\x88\xe9\x7e\x97\x22\xe3\xe0\x89\xa0\ -\xb6\x62\x0e\xae\x85\x77\xa2\x54\x69\x8c\xdc\x10\xc3\xf4\x20\x42\ -\xf7\x3a\xac\x02\xe0\xbe\x6b\x07\x6f\x8a\x61\x8c\x9f\x97\x15\x80\ -\xea\xcf\x51\x0f\xa0\xca\x65\x7a\x69\x4d\x1b\xdf\xf3\xf3\xf6\xe1\ -\xec\xa4\x22\x56\xfa\x79\xa8\xe4\x32\x83\xd2\x35\x81\x84\x9b\x69\ -\x29\x79\xfe\x38\x29\x7b\x9f\x32\x2b\x00\x06\xf8\xb6\xa7\x12\x3d\ -\x13\xa1\x2c\x6c\x8c\xe1\x14\x02\x87\x07\x8a\xa9\x0c\x46\x26\x16\ -\xea\x5b\x41\x04\x4b\xe3\xd1\x2e\xda\x13\xfd\x9c\xec\x31\x40\xf6\ -\x04\x0f\xc1\x9a\xb7\xb2\x38\x6e\xba\xec\xb4\x40\x99\x95\x84\x41\ -\x6b\x50\x71\xc4\xc0\xa7\x9d\x27\xf8\x39\xd9\x01\x20\xbf\xe1\xbe\ -\xb4\x40\xe0\xbb\x1f\x62\xa5\x77\x81\x83\x1a\xcf\x7a\xa6\xdd\xc8\ -\xec\xf1\x69\x17\x46\xf8\x39\x59\x01\x90\x45\x8d\x8f\xf0\x69\xa0\ -\x06\xee\xd7\xc1\xcf\x8f\x61\x41\x85\x07\x7f\x96\xa5\xbd\xc6\xcf\ -\xc9\x0a\x00\xe9\x25\x59\x22\xff\x1e\x5b\xdf\xac\x2c\xd7\x6e\xed\ -\xfe\x42\x60\x00\xba\xa6\x63\x37\x00\xf7\x4a\xb0\xaa\x36\x29\xf7\ -\x00\x9f\x23\x00\xbe\x15\x22\x2d\xf2\x6e\x78\x4c\x98\x00\x93\xcb\ -\xc7\x7e\x44\xac\x54\x07\xd9\x8f\x00\xb0\xdd\x7d\xed\xbf\x23\xdc\ -\xd8\xbb\xce\x0e\x9c\x21\x56\x18\x81\xbb\xcf\x13\x1e\x46\x35\x80\ -\xa8\xcb\xb4\xe7\xf5\x36\xee\x71\x73\x72\x0c\x82\xf0\xec\xa8\xda\ -\xbe\x53\xdc\x20\xfc\x2b\xa4\xbc\x92\x08\x0c\xc0\xce\x43\x31\xd8\ -\x67\xda\xee\xe7\x64\x07\xc0\x6a\x83\x8f\x91\x35\x72\xba\x41\xe8\ -\xd5\xa0\xf2\x4a\x42\x21\x6d\xcb\xc1\x31\x3e\xd3\xbb\x7e\x4e\x8e\ -\xe7\xd7\xbc\xe1\xbe\xa2\x6c\xe0\x64\x03\x32\x9d\x81\xe5\x15\x84\ -\x09\x6f\xdb\xa3\x5d\xd0\xfa\x2c\x1f\x59\x55\x08\xdf\x61\x23\xc7\ -\x67\x71\x5c\x38\x68\x1b\x9e\x01\x02\xde\x14\x95\xc3\x86\xee\x16\ -\xac\x0b\x22\x10\x76\xbc\xf7\xda\x64\xdd\x31\x59\x01\x88\x67\xb0\ -\x12\x80\xfb\xfc\xfd\xbb\x89\x0e\xe5\x7d\xdd\x74\x5d\xcc\x5d\x94\ -\x1e\x0e\x95\x5b\x66\x48\x7c\x30\x70\x4b\xbe\x5d\x06\xe0\x64\x6f\ -\x25\x74\xf9\x69\x59\x01\xd8\x7b\xb6\xb6\xd2\x53\x8f\x98\xec\xe7\ -\xb9\x11\x73\xcc\x2d\x00\xb6\x06\x2a\x2e\x2f\x36\x46\x1c\xcc\x0e\ -\x22\xd4\x8d\xc2\x18\x78\xe7\x28\xdb\xe2\x87\x62\xb5\x9f\x97\x67\ -\x3f\x80\x9e\x55\x14\xa1\x29\x41\x8d\x2d\x6f\xe3\x87\x00\x83\x77\ -\x8c\xca\x09\xf2\x86\x95\x6d\xdc\x19\x44\x31\xb0\x1e\xcd\x82\x9e\ -\xca\xb5\x3d\x9e\x33\x00\xb1\x08\xe6\xa3\x2f\xa9\x61\x6f\x65\x9c\ -\x76\x4a\x52\x81\x2b\xbe\xf8\x10\xdc\x03\xe2\xe9\x40\xe1\xe5\x00\ -\x35\xaf\x67\x2a\xe6\x07\x72\xda\x65\x40\x7a\x16\x69\xb4\xe6\x91\ -\x5c\xd4\x9c\x01\x58\xd1\xc4\xcd\x02\x9e\xf9\xa2\x32\x50\x9d\x8e\ -\x5a\xff\x71\xb8\x07\x5d\x13\x99\xd9\xdd\x77\x70\xfa\x66\xa0\xb8\ -\xd2\xd0\x1d\xff\xd4\x5c\x1e\x76\x1c\x57\x3f\x1a\xe7\xc2\x7b\x08\ -\xf3\x7e\x7c\xe8\x97\xfd\x71\x23\xef\x34\x56\xe4\x9f\x3c\xd7\xe0\ -\x4f\xc7\x75\xe8\xe8\xa0\x86\x5f\x6a\xe6\xa7\x8e\xe5\x24\x54\x22\ -\x08\xc4\x6a\x44\x38\x35\xec\x38\xae\x36\xa9\x2a\x49\xbf\x77\xdb\ -\x44\xce\xce\x77\x3a\x94\x37\x00\xab\xa6\x62\x19\xbc\x83\x61\x95\ -\x03\x3b\x33\x4c\xe7\xea\x69\x7c\x7b\x37\x59\x0f\xe4\x8e\x78\xff\ -\xa0\xbf\x99\x34\x1b\xc3\x36\x66\x01\x60\x60\x0c\x97\x83\x9e\xc9\ -\xdb\x96\x98\xc1\x9c\x7c\xfc\xfc\x0b\x19\x52\x24\x6f\xf0\xd9\x2e\ -\x4c\xa4\x82\xd7\xe0\x40\xdf\x9d\x10\x1f\xc2\x1f\x11\xfc\x1d\x72\ -\x4c\x3f\x8b\xc0\x47\x02\x67\xf4\x34\x9b\xf3\xc2\x06\x3d\x00\x18\ -\xb3\x44\x87\x51\xf2\x1c\xe1\x43\xbc\x7d\x45\x13\xf3\x6a\x08\x5c\ -\xc9\x75\x37\xb3\x0b\xd4\x3c\x0f\x5f\x4a\x25\x16\xeb\xc8\x30\x31\ -\x5d\x13\x99\xe9\x6e\xe1\x9d\x11\xf0\x58\x49\x73\x00\x7c\x1e\x56\ -\xc7\x85\xad\x80\xee\xc8\x64\x78\x6c\x6f\x0b\xef\x2f\xe4\x08\xbe\ -\x36\xa9\xaa\x48\x46\x0b\xe1\xcd\x21\x7a\x25\xf3\x11\xf2\x9e\x0b\ -\x02\x05\x9c\x0e\x8f\xeb\xd4\x11\x0e\xf4\x0a\x80\x2f\x3a\x2d\xe1\ -\xc5\xa1\x71\x9e\xb6\x74\x12\x77\x87\xd5\xdf\x87\x31\x4b\x34\x20\ -\x96\xc1\x19\xa0\x6d\x95\x38\x12\x7d\xbb\xc8\x87\x02\x80\x80\x0f\ -\x09\x6c\x06\xb4\x96\x34\x0b\xb6\xa5\xf1\xac\x7f\xd5\x16\x86\xfa\ -\x4e\x67\x8e\xc0\x2b\x5d\xa6\xb4\x21\xc7\x87\x65\xae\x14\x94\x20\ -\x91\xe8\x50\xbd\xa8\x2e\x6f\x46\x98\x1e\xea\x69\x36\x97\x95\x92\ -\x20\xd1\x90\x54\xfc\x90\x81\xb0\xc5\x04\x32\x8f\xbe\xab\x40\xdd\ -\xe7\xb6\x89\xbc\xac\xb7\x99\x73\xc3\xea\x16\x9c\x24\x95\xe8\xd0\ -\x05\xa0\xbc\x19\x17\xd2\x83\xdb\x1d\x73\x75\xb1\xff\x56\xd9\x20\ -\xb1\x3e\x85\xab\x05\xcd\x86\xfb\x71\xa6\xee\xe9\x69\x8e\xfc\xb2\ -\x10\x17\x45\x65\x89\xd5\x77\x38\x77\x8a\xbc\xce\xa3\x01\x78\xde\ -\x89\x72\xda\x9a\x29\xfc\xa8\x18\x5f\xa5\xa2\x36\xa9\xaa\x41\x11\ -\xfb\x67\x91\x97\x7a\x0a\x88\xa7\xe3\x87\x70\x72\x50\x52\x84\x1b\ -\x45\x6d\x67\x0d\x77\xcc\x0d\x04\x52\xde\xf6\x70\x6a\x34\xa3\x55\ -\x0d\x8b\x34\xb2\x18\x5f\xa5\x60\x5c\xa7\x8e\xa8\x89\xea\xd9\xac\ -\xce\x03\xaf\xed\x06\xcf\x29\xb4\xf3\x40\x3f\x12\x25\xcf\x4e\x2a\ -\xb2\x31\x6a\xef\x12\xe8\xbf\xc5\xd2\x80\xe6\x44\x60\x6e\x7b\xb1\ -\x85\xff\x29\xd6\x6f\x21\x68\x48\x2a\xee\x44\xf1\x33\x42\xd7\x03\ -\x18\xe2\x2b\x5e\x9a\xc9\xf0\xdc\x35\x6d\x2c\x6a\x51\xd6\xff\x54\ -\xd9\x94\x2e\x65\xdf\xeb\xcd\xbf\x31\xb9\x83\xd2\xdd\x8a\x9b\x59\ -\xc5\x24\x2c\x06\x61\xc2\x73\x8a\xee\xda\x82\xe9\xa2\x66\x22\xc7\ -\x19\xa4\xa0\x59\x47\x67\xcc\x75\x85\xe6\x13\xb9\x51\x52\xb2\x74\ -\x5d\x87\x1a\x0d\xd5\x09\x60\x68\x8e\xe2\x4f\x00\x3d\x0e\x99\xc7\ -\x11\xc7\x33\xc5\x06\xa3\x36\xa9\xaa\x41\x06\x8d\x32\xf6\x2c\x80\ -\x4d\x00\x72\x4d\xc3\xd3\x22\x67\x14\x32\xda\xe7\x43\xc9\xe9\xf2\ -\x75\x8b\x34\xdc\x58\xdd\x03\xa0\x25\x80\x96\x06\xf1\xbc\x2c\x9f\ -\xa3\xc1\x9b\x12\xfe\x21\x83\x2d\xd5\x51\xec\x48\x1b\x38\x66\x07\ -\x6a\x6c\x15\x06\xcb\xc1\x08\x10\xc7\x11\xb6\x01\xe0\xe9\xe8\xfb\ -\xa4\x26\x9f\xf0\x55\x22\x67\xf4\x34\x73\x4d\x29\xfa\xcb\xf6\xc1\ -\x44\x7d\x4a\x67\x4a\xba\x13\x40\xa5\x07\xc3\xcd\x12\x6f\x39\xda\ -\xc1\x5f\xfa\x73\xcb\xfb\x51\xde\x4f\x66\xda\x65\xc6\x8e\x42\x93\ -\xa1\xae\x17\x50\x57\x56\xdf\xc0\xdb\x00\x67\xc5\xb7\x62\x6e\xb1\ -\x09\x9a\x41\xa8\xd8\x47\x53\x75\x0b\x75\xa2\x31\x76\xfa\xde\x8f\ -\x1d\x8e\xeb\xa7\x9b\xf7\x01\x3d\x69\x65\x1e\x59\xf5\x0a\x5e\xe8\ -\xcf\xf7\x00\x61\xd8\x2f\x9f\xcd\xd5\x2d\xd2\x70\x5a\x4c\x34\xb2\ -\x27\x8a\x3c\x1e\xc0\x08\x12\x83\x25\x0c\x42\xdf\xc9\xcd\x56\xf4\ -\x7d\x36\xb7\x11\xd0\x7a\xd2\xac\x17\xf1\x7c\x4f\x13\xde\xf8\x2a\ -\xe4\x22\x1f\xc0\x01\x1c\xc0\xff\x2e\xfe\x0b\x91\x5a\xc0\x8b\x79\ -\xe5\x16\x6d\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x0c\xd6\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x0c\x88\x49\x44\x41\x54\x78\x9c\xe5\ -\x9b\x5b\x6f\x5b\xc7\x11\x80\xbf\x25\x45\x8a\x94\x28\x89\x92\xad\ -\xbb\x64\xc9\x4e\x9a\xc2\x41\xe0\x26\x45\xd1\xa0\x48\x0a\xf4\xa9\ -\x7d\xe9\x7b\x81\x16\xfd\xa3\x7d\x2a\x50\xb4\x0f\x41\x90\x36\x4e\ -\x52\x20\x69\x92\xc6\x96\x6c\xc9\x37\x5d\x48\x49\xa4\x2e\xe4\xf4\ -\x61\xf6\x1c\xee\xd9\x33\x87\xa4\xe4\xf4\xc9\x03\x10\x24\x77\xf7\ -\xcc\xce\xcc\xee\xce\x6d\xe7\x00\xb2\x05\xe2\x78\xe3\x40\x9c\xf2\ -\x9e\xfe\x78\x93\x84\x90\xe3\xf9\x4d\x12\x42\x96\x57\x97\xed\xe0\ -\x0e\xf0\x18\x9c\x14\x3c\xdc\x00\x6e\x19\x1d\x25\x60\x32\x8b\x2f\ -\x6d\xaf\x0d\xa1\x66\x12\x10\xe0\x62\xc8\x98\x73\xa0\x67\xb4\x77\ -\x81\xbe\xd1\xfe\x12\xdc\xa9\x8d\x2a\xcf\xa3\x1b\x35\x00\x64\x1b\ -\xb8\xed\x09\x3d\x01\x5e\xf8\x89\xa7\x80\x39\xdf\x2e\xc0\x59\xd0\ -\x3e\xeb\xdb\xfa\xbe\x1d\x8f\xa3\x0a\x34\x81\x8a\xef\x3f\xf7\x34\ -\x54\xfd\xf7\x25\x70\x04\x97\xa7\x50\x39\xf2\x6d\x53\xa8\x20\x9d\ -\x9f\xff\xc4\xff\x9f\xf2\x6d\x0e\x68\x01\xa7\xbe\x7d\x29\xe8\x7b\ -\x01\xee\x71\x31\x6f\x85\x52\x92\x2d\x90\x09\x90\x8f\x40\x56\x8d\ -\x31\x6b\x20\x0b\x46\xfb\x06\xc8\xbc\xff\x3d\x05\x72\x0f\xe4\xae\ -\xff\xcc\x80\xdc\x01\x19\xb2\x23\xa4\xee\xc7\x2c\xa8\xe0\xe5\xae\ -\xc7\x31\xe1\xfb\xe7\x40\x36\xf3\x47\x55\x9a\x05\xed\x1b\x20\xbf\ -\x06\x29\x5f\xf3\x88\xcb\x04\xc8\x9f\xf5\xc1\x5c\xdf\x36\x48\xc5\ -\x68\x7f\xdb\x3f\xb7\xe2\x27\x5b\x8e\xf0\xdd\x1b\x73\x72\x3c\xe3\ -\x25\xff\xdb\x79\x46\xb6\xa0\x75\x4b\xdb\xe5\x2d\x83\xd9\x32\xc8\ -\x4f\x8c\xf6\x09\x90\x3f\xda\xbc\x14\x13\xf0\x91\x7f\x30\x92\x9a\ -\xac\x17\x30\x7f\xc7\x7f\xb6\xed\x15\x96\xed\x6b\x4c\x4e\x60\xa2\ -\xe2\xf6\x59\x15\x4e\x7b\x49\xe7\xcb\xf5\x97\xb3\xcf\xa5\xbb\xb9\ -\x02\xf2\xab\x71\x27\xdf\x1e\x6c\xfb\x50\x63\xca\x14\xc8\x6d\x63\ -\xfc\x2a\xc8\x07\xba\x7d\x4d\x7c\xf3\x5e\x79\x5e\x13\x64\x56\xb7\ -\xbc\xd9\x37\x07\xf2\x00\x64\xd1\xe8\x6b\xfa\x67\x23\xcb\x26\x9b\ -\xfa\xc9\x82\x71\x26\xe4\x17\xe0\x3e\x0d\xfe\x27\xca\xa3\x07\xec\ -\x01\x21\xa3\xab\x70\x79\x0b\x2a\x5f\x0e\xe1\x64\x0d\x78\x5a\xd0\ -\x97\xda\xe1\x1b\x3c\x0b\xf0\x00\xba\x4f\xa0\xf6\x2a\x68\xeb\x28\ -\x5d\x94\xc9\x29\xbc\x98\x37\x98\x30\x90\xc6\xc4\x34\x50\xe6\x1f\ -\xa0\x5a\xbd\xed\xc7\x6c\x01\x2f\x54\xa1\x0f\x05\xf1\xc4\x2c\xf9\ -\xff\x89\xe9\x4a\x34\x78\xd8\x46\xd0\xf6\xc2\xa0\x25\x86\x17\x20\ -\x82\x32\xbc\xe7\x9f\x5d\x02\x7e\x06\x7c\x0e\xcc\xa0\x16\x22\x81\ -\x9c\xd9\x8c\x04\x20\x0d\xd4\xcc\x24\xff\x37\x80\x36\xb8\x5d\x3f\ -\x51\x05\x35\x5d\x9b\xc0\xd7\xe0\xae\xf4\x7c\xb9\x13\x72\x20\xce\ -\x8f\x9b\x42\x7d\x81\x6f\x47\x98\x9f\xf8\xd9\x45\x60\x1a\x35\xa9\ -\x7b\xf6\xb3\xd2\x86\xfa\x0b\xd4\x9f\x58\x01\x7e\x00\x16\x80\xcf\ -\x80\xe7\x80\xb7\x3c\xec\xf8\xe7\x7b\xaa\xdb\xdc\x55\xd1\xc4\x5b\ -\x03\xf3\x26\x5b\x59\xcd\x29\x1b\x5e\x0f\x7c\x1c\x29\x46\xcb\x4c\ -\x2e\xa1\xa6\x72\x46\x3f\x37\x05\x59\xf5\xca\x78\x3d\x6b\x55\xd2\ -\xfe\x99\x81\x7e\x91\x09\x90\xdf\x78\x2b\x11\xb6\x07\x8a\x51\xee\ -\xaa\x8e\x18\x40\xc9\x98\xb5\xaf\x13\xb2\x0b\xae\x17\x8d\x5d\x03\ -\xfe\x0e\xdc\x09\x84\x10\xac\xcc\x61\x53\x19\xe7\x10\xdc\x53\xdf\ -\x37\xe6\xaa\x9b\xe0\x9f\x75\x4f\x80\x03\xc5\x7d\xd8\xcc\xf7\x8b\ -\x03\xd6\x81\xbf\x01\xf7\xb2\x73\xba\x9e\xf2\x22\xeb\x18\x47\xc0\ -\x12\xc0\x14\x70\x16\x31\x0f\x7a\xe6\xbf\xf3\x5b\xe9\x31\x59\x21\ -\xa0\x1a\xb9\xd9\x57\xc6\xdd\xe5\xf8\x3c\x8e\x0b\xee\x52\x71\x37\ -\xfb\xd1\x6e\x08\x3d\xbc\x1e\xf0\x04\x3d\x7a\xe1\x90\x1e\xea\x29\ -\x4e\xc7\x58\x2d\x25\x38\xe7\x57\x2f\x00\xd9\x46\x95\x4c\x29\x30\ -\x77\x07\xc0\x7d\xe0\xd2\x9b\xab\x57\xe8\xee\x09\x4d\x9e\x9f\xd0\ -\xdc\x04\x25\xe8\xfa\xe3\x56\x3b\xc4\xf6\xf7\xa7\x81\x2e\x48\x78\ -\x66\xfb\x3a\x56\xee\x03\x47\xe8\xca\x7f\xad\x63\x05\xa0\x03\x9d\ -\x13\xa8\x2f\x92\xd1\x67\xee\x08\xe4\xa7\xf1\x04\x63\x58\x01\x79\ -\x0b\x2e\x2a\x50\x9d\x46\x15\xd3\x29\x83\xad\xbd\x0b\xfc\x0e\xf8\ -\x4b\x01\x03\x01\x74\xe6\xa1\x9e\x04\x3f\x3e\x4e\xa8\x1d\xf9\xce\ -\x79\xd4\x52\xf8\x1d\xd5\x39\x87\xfa\xe1\x10\x64\x5d\xd4\x3c\xfe\ -\x06\xf8\x24\xa0\xd9\x2b\xcf\x7a\x0d\xb8\x0d\x72\x1e\x2d\x66\x6e\ -\x25\x62\x01\xc4\xd1\xe1\x5d\x60\x1a\x26\x1f\xaa\x12\x74\xfb\xd9\ -\xe1\xb2\x0e\xfc\x03\x0d\x70\x8c\x20\x43\x80\xee\x6d\xa8\x4d\x40\ -\xfd\x25\xb8\x4e\x01\x43\x47\xd9\xbf\x52\x07\x16\xe0\xa2\x06\xd5\ -\x93\xbc\xd6\x4e\x7d\x93\xbf\x02\x6b\xe0\xf6\x82\xce\x36\xc8\x09\ -\xba\x63\xdf\xf6\x9e\x6b\x42\x5b\x9f\xe8\xd8\xc7\x3a\xa0\x0a\x9c\ -\xfb\x09\xee\xa1\xab\xf2\x85\x4d\xb3\x2c\xa1\xdb\xbe\x87\xad\x13\ -\xa6\x81\x55\xa8\xb5\x55\x89\x15\x32\x6f\x80\xeb\xe8\x33\xd5\xb6\ -\x32\x18\x1e\xab\x30\xaa\xa3\x87\xfa\x02\x2b\x05\x88\xbe\xf1\x63\ -\xee\xf9\xe7\x3a\x64\x1d\xb9\x22\x2b\xc0\x06\xf0\x0c\xf5\x01\x8c\ -\x03\x7c\xd8\x04\xba\xe0\xba\x9e\xe0\x48\x31\x1e\xcd\x43\xbb\x86\ -\xae\xc2\xf9\x58\x3c\xdb\x70\x01\x3c\x85\xf6\x24\x1c\x2f\x60\x87\ -\xb4\x5d\xe0\x4c\xe7\x8c\xc1\x9d\xa1\x8b\xfa\x83\xe7\x29\xc7\x8b\ -\x25\x80\x06\xea\x3d\x2d\xe6\xb7\x7c\x02\xcd\x29\x70\xad\x6c\x5b\ -\x22\x84\xcb\xf7\x61\xae\x07\xb3\xaf\xcc\x47\x6f\x04\xb3\xaf\x60\ -\xf6\x52\x71\x5b\x47\xcd\xb5\x60\xae\x20\x16\x61\x07\x35\xdf\x2d\ -\xd4\xc2\x65\xc0\x12\xc0\x34\xaa\x3d\x0b\x94\x9a\x2c\xa3\x6e\xaa\ -\x01\xc7\x4d\xa8\x7c\x0f\xcc\x33\x7e\xec\x3d\x06\x88\x03\x16\xa0\ -\xf2\x9d\xce\x61\xc2\x73\xdb\x59\x72\x97\x40\x19\xdc\x31\xba\xb8\ -\x19\xb0\x04\x20\xa8\x69\xd9\x29\x20\x64\xc2\xb6\xf3\x32\x05\xa5\ -\x64\x22\x7f\x1c\xac\x60\xeb\xda\x10\x6e\xfb\x16\x94\x4a\x5e\xbf\ -\xc4\xc3\xae\x94\x36\xb1\x78\x3a\xd4\x23\x34\xda\x0a\x94\x07\x83\ -\x4c\xbf\x7d\x13\xd5\xb2\xe1\x2a\xcc\x82\x74\x81\x15\x98\xd9\x0f\ -\xfa\x5a\xc0\xbb\xc0\x13\xd2\x8c\x4e\x06\x92\xd4\x19\xa8\x4f\x61\ -\xe5\x05\xe7\xd0\x40\xe7\x07\xfd\x2d\xa0\x3b\x73\x03\xe4\x19\x03\ -\x3f\x23\xc1\x7f\xa6\x7d\x1c\x64\xd1\xb8\x63\xef\x0e\x27\x81\x59\ -\x0a\x31\x61\x35\x72\x49\x48\x99\x47\x83\x8d\x65\x4f\x64\x84\x9c\ -\x1e\x74\x66\xa1\x7e\x00\xc4\x41\xc6\x23\x4f\xd0\xd7\xc1\xe4\x2b\ -\x40\x1f\x3a\x67\x50\xdf\x05\x1c\x74\x6f\x41\x2d\xc9\x2f\x3e\xf3\ -\xdf\xce\xcf\xf9\x05\x9a\x2b\x0c\xe1\x15\x74\x66\xa0\x9e\x08\x2d\ -\x9c\xb7\x89\x2a\xbe\xbe\xee\x86\x54\x57\x25\x79\xcb\x4c\xc2\xc6\ -\x5a\x99\x45\xe0\x4b\x90\xaa\x27\xe0\x25\xb8\x43\x34\xd3\x73\x96\ -\x8f\xfc\xa4\x01\xf5\x32\xb8\xe7\x79\x54\x82\x67\x7e\x01\x38\x46\ -\x57\xec\x1b\x63\x77\xb5\xfd\xf8\x32\xba\xe2\x07\x9e\x8e\xff\x68\ -\x5f\x2e\x7a\x3b\xf1\xa6\xcf\x67\x7f\x43\x9a\x64\x1f\x15\x98\x17\ -\x9a\x6c\x02\x4f\xe0\xa4\x03\x8d\x29\xb2\xe1\xb1\xa9\x03\x4a\xa8\ -\x04\x6f\x83\xdb\x09\xec\xf7\x2d\x6c\xe5\x37\x0d\x47\x05\x69\x68\ -\xa5\x00\xcd\xf4\x6e\x01\x4f\x87\x87\xc4\xa9\x2f\x7f\x1f\x0d\x67\ -\x87\x05\x52\x27\x18\xbe\xbd\x5f\x08\x9f\xb9\x72\x27\xa8\xb7\xba\ -\x01\x8d\x03\xf4\x48\x65\xa0\x48\x09\x2e\xe5\xe3\x01\x28\x20\xbe\ -\x01\xf3\x47\x46\x7b\x02\x65\x25\xb4\xf2\x90\x9c\xb3\x94\x9b\x3a\ -\x51\x78\x9f\x61\xdf\x3f\x84\xb4\x14\x08\x20\x37\x4e\x7c\x6a\x7c\ -\xcd\xea\xb5\x04\xb0\x00\x58\xf6\xdf\xba\x84\x18\x07\x56\x18\x24\ -\x34\x0c\x8f\x31\x81\x9c\x93\xf3\x12\x2e\x8c\xd4\x7b\x06\x8a\x84\ -\x69\xd1\xfa\x0a\x43\x60\x05\x47\xe0\x5a\xe1\xec\x28\xc1\xf4\x07\ -\x3b\xa7\x30\x94\x36\x3c\x3c\xd7\x85\xea\xa8\x7c\xdb\x35\x72\x0d\ -\xee\x0c\x55\xe6\x19\x88\x05\x30\x41\x71\x54\x77\x13\x9b\x5e\x83\ -\x6e\x64\xde\x62\x21\x0c\xbd\xb1\xb9\xa9\x1f\x51\xf4\x5c\xae\x3d\ -\xb6\x02\xcb\x70\x65\x69\xf3\xc0\x3f\xc8\xb4\x97\xec\xf6\x14\x9a\ -\x50\x7b\x66\xd0\x21\x20\x8f\xd1\x24\x0b\xc0\xa3\x02\xfd\x32\x62\ -\x85\xbb\x7d\x8d\x34\x73\xd0\xc3\xce\xd6\x8e\x8a\x05\x7a\x15\x98\ -\xb8\xce\xf6\x4f\xec\x75\x11\xf4\x47\xf4\xbf\x26\xd4\x1c\xc5\x47\ -\x70\xac\x79\x23\x01\x94\x9f\xa1\xf6\x37\xc6\xd5\xb3\x11\x8e\xcc\ -\xf2\x1e\x90\x9a\xa4\x10\xd2\x6d\xff\xc8\x7f\x46\x58\x87\x42\x28\ -\x12\x40\x19\xdb\xb3\xcc\xcd\x11\xeb\x80\x2e\x51\xbc\x1c\x40\x11\ -\xb3\xc3\x08\xbf\xca\xcf\x11\x9f\xf9\x51\xd6\x61\x28\x14\x8d\x1f\ -\x5b\x39\xc6\x02\x48\x72\xe7\x39\x6d\x79\x03\x22\x12\xe8\x93\xde\ -\x27\x16\x29\x3c\x4b\x08\x32\x43\xea\xe9\xdd\x78\xee\x00\xc4\xe7\ -\x17\xb3\x60\x99\xc1\x23\x06\xb7\x38\x3f\x06\x3c\x07\x56\x46\x68\ -\x7b\x22\x21\x94\x50\xaf\xcd\xb8\x70\xc9\xc0\x98\xbe\x49\x12\x4e\ -\xe7\x05\x6a\x09\xc0\x01\xfb\xe4\x2f\x12\x8b\xa4\x7d\x00\x6d\x43\ -\x6f\x64\xe0\x25\xf0\x21\x23\x8b\x13\x9c\xa0\x61\xf8\x47\x0c\xbf\ -\x13\xc4\x67\x80\x8e\x8b\x10\x0d\x7e\x8a\x43\xad\xcd\x2e\x63\xe8\ -\x00\x00\xf1\x8e\xd0\x53\x15\x42\x7a\xb3\x73\x80\x79\x1b\xcb\x25\ -\x34\xaa\x43\x28\x4d\xee\xeb\xfe\x05\x6c\x6a\xde\xa0\x08\x64\x8e\ -\xc1\xe5\xcb\xa6\x45\xf0\x00\xe6\x26\x31\xd3\x6d\xed\x45\xd2\x88\ -\x55\x9a\x68\x6e\xe3\x91\xc7\x35\x32\x1f\x00\x9a\xe7\x9f\x04\x77\ -\x0e\xec\x28\x12\xd9\x40\xad\xc3\xbc\x8f\xbd\x43\x44\x4b\xc0\x19\ -\xc8\x3b\x44\x91\x16\x9a\x81\x59\x43\xa3\xba\x26\x70\x01\x17\x5b\ -\x5e\xc7\x58\x4e\xcf\x29\x1a\x19\x2e\xe9\x58\x1e\x00\xff\x06\x89\ -\x4d\x73\x92\xd9\x49\xf2\x01\xc9\xff\x24\x84\xee\x78\xfc\x7b\x7a\ -\xaf\x09\x3e\x83\x9d\xf3\x49\x62\x01\x74\x7c\xdb\x32\x7a\x1e\xd1\ -\x0b\x05\x8e\x3c\xbd\x02\xec\x67\xb7\xb1\xa0\xb9\x43\x59\xcf\xe6\ -\x10\xd3\x73\xf7\x4f\x70\xed\x60\x8e\x82\x3c\xa3\x05\x02\x9a\x38\ -\xd9\x8d\xe6\x5c\xd3\x60\x2d\x61\x3c\x09\x87\xc5\xa1\xbb\xfa\x38\ -\xdb\x0e\x0c\x0a\xb6\x32\xd9\xe9\xf8\x08\x84\x57\xd7\x16\xec\xa1\ -\xc1\x8d\x05\xcf\xc8\x14\x56\xe0\x6f\x65\x5f\xfb\x6e\x30\xb6\x0e\ -\x2b\x14\xe6\x24\x93\xc0\xcb\x84\xe4\x3a\x3e\xa3\x38\x8b\x94\xe0\ -\x85\x6d\x0a\x5d\x5f\x89\xb2\xea\x6d\xdc\x15\xd0\xf2\x67\x30\xc9\ -\xdb\xbf\x0e\xf3\x09\x04\x42\x68\xdd\x46\x13\x24\x56\x4e\xb2\x1c\ -\xd0\x18\xf7\x2d\xa3\xd6\x68\x2c\x25\xd8\x46\xed\xa5\x19\x3f\xfb\ -\x6d\x6e\x64\x5f\x01\x38\x83\xc6\x32\x9c\x9c\x8d\xe1\x25\x5e\x03\ -\x9c\x28\xce\x99\x15\x06\x65\x77\x31\x2c\x53\x7c\xbc\x92\x1a\x85\ -\x9c\x59\xb5\x04\x70\x86\x2a\x97\x72\x41\x86\x15\x38\xee\x90\xbb\ -\xf7\x4f\xb7\xfd\x57\xd0\x38\xd3\x73\xfa\x63\x81\xac\x2a\x4e\xbe\ -\xc2\xf4\x18\xa5\x01\xad\xae\x2d\x74\x99\x83\xb3\x2e\xca\x53\x4e\ -\x78\x45\xf9\x80\xc4\x66\xbe\x6d\x13\xd4\x3c\x54\x84\xc9\x31\xc9\ -\xb9\xb7\xa7\xe8\x96\x5b\x85\x4e\x41\xa1\xd3\x38\x70\x3e\xab\x38\ -\x92\xea\x4f\xd3\x6d\x9e\x04\x66\x61\x2e\x4e\xd6\x26\xb0\x02\x53\ -\xd3\x01\x4f\x19\x88\x05\x70\x41\x9a\x34\x70\xde\x74\xc9\xba\x8d\ -\xd7\xed\x2b\x72\x4a\xd8\xee\xed\x15\xb0\x07\xf5\x4b\x55\x5c\xb2\ -\x38\x9e\xaf\x2f\xce\x8f\x5d\x81\x49\x8f\x23\x3c\xf3\xa1\x10\x28\ -\x01\xab\x76\xfa\x0e\xd4\x34\x5f\x54\xc0\x7d\xeb\x1b\xea\x44\x56\ -\x20\x36\x83\xf1\x95\xd3\x27\x68\x39\x1a\xc0\x32\x5a\x27\xd4\x0f\ -\xc6\x5d\x02\xbf\x45\xaf\xc7\x97\x0d\x9d\x97\xa4\xa0\x4e\xd1\xf8\ -\xfc\x3d\x2f\x84\x61\x89\x0f\x21\xad\x35\xa0\x81\xba\xd1\x56\x4d\ -\xcf\x25\xf0\x7b\xe0\x53\x06\x97\xa3\x89\x19\x4c\xca\x6b\x27\xf5\ -\x66\x3b\x85\x12\xc3\xdd\x67\xd9\x42\x0b\x0f\xc2\xb6\x86\xf7\x08\ -\x37\xa2\xf6\xa4\x0e\x6f\xcd\x7f\x1b\x56\x43\x1a\xdc\xa8\x46\x30\ -\x7d\x7e\x05\xf3\x52\x45\xaa\x68\x09\xed\x1c\xc8\xbb\xb6\x4e\x90\ -\xf7\xf3\xd6\x4a\x3e\x64\x8c\x1a\xa1\x43\x90\x20\x23\xeb\x4e\xe0\ -\xa4\xab\xf5\x80\x29\xa2\xf0\x8a\xba\x0f\xee\x11\xea\x25\xbe\x06\ -\xb3\xe3\x82\xcc\xa0\x29\xfb\xef\xd1\xcc\xcf\x0e\x79\xc5\xb8\x81\ -\xa6\xe0\xc3\x0b\x9e\xe4\x6e\x22\x03\x96\x00\xba\x40\x95\x4c\x49\ -\xec\xcc\x0b\xa8\x4c\x7a\xc9\x16\x85\xb4\xfb\xd0\xaa\xaa\xce\xb8\ -\x56\x5d\xee\x98\x20\x65\xc5\xdd\xaa\x90\xaf\xfa\x08\x14\x63\x7b\ -\x11\xba\x1d\x32\x1a\x5f\x2a\xa8\x6e\xcb\xd5\x28\x58\xb1\x40\x09\ -\xdc\x9e\x6e\x79\x79\x16\x28\xa0\xa7\xa8\x46\xee\x01\xff\x0d\x98\ -\x0f\x24\x3f\x77\xe0\x05\x94\x84\xbf\xa1\x0b\x7c\x13\x48\xbc\xbf\ -\x55\x94\xd1\xa7\x30\x27\x51\xbf\x04\x39\xc6\xfb\xd0\x68\x91\xb9\ -\xbe\x93\x8a\xd2\xe3\x76\x40\xee\x1a\xcc\x66\xe0\x25\x69\x2e\xc0\ -\xed\xa2\x75\x36\xc9\xd6\x17\x54\xf1\x54\xc8\x66\x8d\x22\x1c\x4e\ -\x54\x80\xec\xa3\xb5\x3f\xf7\xc6\x08\x97\x0d\x68\xdd\x46\x9d\x9b\ -\x25\xe0\xb9\xee\xb0\x9c\x9d\x9f\x26\x5d\xd5\xe3\x26\xba\xea\x65\ -\x54\x79\x76\xd0\xda\xe6\x25\x65\x1e\xd0\xcb\xd8\x8c\x33\x14\xed\ -\x00\x77\x9a\x0d\x57\xdd\x1e\x5a\xc3\xbf\x81\x46\x66\x9f\xa3\x42\ -\x78\x00\xe7\x27\x50\x3d\x52\x22\x0b\xcd\x5b\x5f\xe7\x68\x24\x15\ -\x9b\x49\x1b\x80\x83\x0b\xbf\xbb\xaa\xc9\x0b\x14\x21\x1c\x7b\x66\ -\xbc\xa9\x33\x1d\xcb\x65\xc5\x2f\x4b\x1e\x6f\x12\x23\x7c\x00\x3c\ -\x04\x0e\xc0\xbd\x0c\xc6\x97\xe3\x7b\x46\xeb\x08\xc4\xcc\x74\x3d\ -\x21\x0f\xd1\x82\x45\xd0\x2b\xef\x65\xdf\xbe\x1f\xb4\x1b\x20\x62\ -\xf7\x8b\x83\xea\xa4\x67\xb0\x53\xe0\xc5\xad\x8f\xc0\x7d\x05\x4c\ -\xc1\xd1\xf7\xd9\xeb\x39\x71\x9e\xb6\xf8\xcc\x8f\x93\x42\x93\x3b\ -\x03\xe7\x27\x53\x2e\x5f\xcf\x5a\x07\xf0\x66\xe8\x7d\xec\x44\x49\ -\x32\xe6\xff\x50\x2e\x0f\xba\x00\xf2\xf3\xbc\xf9\x95\xa6\x5a\x8a\ -\x5c\xb9\xfc\x1d\xcc\xb2\x5e\x1b\xf9\xc7\xd8\x2f\x4c\xac\x92\x7b\ -\x61\x42\x1c\xfa\x82\x85\xf1\x02\x43\x3a\x66\x7b\xcc\x89\x43\x9c\ -\x05\xcf\x88\x43\xdf\x18\xf9\xa5\xd1\x57\xce\xfa\x2b\xa9\x10\xaa\ -\x8c\xff\xc2\x44\x8a\xe8\x4f\x05\x4e\xc8\x46\x5e\x08\x00\xf2\x1e\ -\xfa\xca\x4a\xee\xa5\x04\x5e\xeb\x95\x99\xb4\xad\xe4\x9d\x9f\xb7\ -\x40\xde\x31\x9c\x9f\xb2\xa5\xe5\x3d\xf3\x7f\xc8\xe3\x2b\x9e\x3c\ -\x91\x5a\x59\xa5\x16\x7b\x80\xe0\x77\x82\x71\x7d\x2d\x1b\x7e\x6b\ -\xde\xd3\x4f\x2b\x74\x9e\x2a\x8c\x7e\x69\x6a\xca\x8f\x09\x04\x2f\ -\x2b\x0c\x5e\xbe\x2a\x7a\x39\x6a\x1e\x33\x66\x91\x2d\xcf\x43\x29\ -\xbf\x9b\x15\x62\x44\x86\x93\x23\x9b\xa8\xb6\xf5\x35\xba\xb4\xfc\ -\xef\x1a\x6a\xe6\x1c\x7a\x01\x72\xc1\xe0\xb5\xb9\x19\x40\xa0\x37\ -\x0d\xe5\xc4\x29\x4a\x4a\x64\x7b\xc1\xff\xe4\xf6\x26\x79\x6d\x2e\ -\x28\x97\x4d\xe9\xeb\xfa\x71\x0e\x35\x61\xa7\xfe\xf7\x24\xaa\xc4\ -\x7d\x01\x06\x1d\x54\xa1\xce\x06\x78\xf6\x06\x4e\x93\xed\xc0\x8d\ -\xb8\xa2\x8e\x41\x26\x30\x4a\xcd\x3c\x9e\x3a\x79\x2d\x1b\xbf\x38\ -\x59\x42\xaf\xca\x92\x23\x54\x65\xe0\x5f\xe0\x99\x38\x24\x6b\xf3\ -\xac\x17\x27\x85\x41\xe2\x33\x06\xa3\xb4\x36\x7d\xac\x88\xc7\x37\ -\xf7\xd5\x59\xab\xe1\x0d\x80\x0c\xcf\x6f\x1a\xf3\x09\xa8\x10\xfe\ -\x07\xb4\x0a\xfd\x7e\xcf\x22\x5b\xc2\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x01\x23\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xd5\x49\x44\x41\x54\x78\x9c\xed\ -\xdb\x31\x11\xc2\x40\x00\x05\xd1\x0d\x22\xa2\x08\x05\x0c\x0e\xa0\ -\x41\x11\x0d\x12\x18\x14\xa0\x26\x15\x2e\x42\x41\xe8\x52\x67\x99\ -\x61\x5f\x75\xdd\xfd\xdb\xfe\x20\xc9\x3f\x1b\xac\x8b\xf7\xc7\xf3\ -\x61\x98\xb9\x02\xcc\x03\x97\xe7\xfd\xf6\x30\x76\xec\x8c\x4b\x01\ -\x96\xc7\x8f\xc0\xf8\x0d\x61\xd0\x02\xf0\x79\xfc\xda\x79\x53\x66\ -\x80\x9f\x50\x00\x7b\x80\xad\x00\xf6\x00\x5b\x01\xec\x01\xb6\x02\ -\xd8\x03\x6c\x05\xb0\x07\xd8\x0a\x60\x0f\xb0\x15\xc0\x1e\x60\x2b\ -\x80\x3d\xc0\x56\x00\x7b\x80\xad\x00\xf6\x00\x5b\x01\xec\x01\xb6\ -\x02\xd8\x03\x6c\x05\xb0\x07\xd8\x0a\x60\x0f\xb0\x15\xc0\x1e\x60\ -\x2b\x80\x3d\xc0\x56\x00\x7b\x80\xad\x00\xf6\x00\x5b\x01\xec\x01\ -\xb6\x02\xd8\x03\x6c\x05\xb0\x07\xd8\x0a\x60\x0f\xb0\x15\xc0\x1e\ -\x60\x2b\x80\x3d\xc0\x56\x00\x7b\x80\xcd\xfb\x34\x05\xaf\xb5\xf3\ -\xd6\xb4\x00\x33\x9c\x80\x09\x98\x96\x73\x92\x6c\xee\x0d\xbb\x93\ -\x11\x50\xe7\xe7\xb7\x79\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ -\x60\x82\ -\x00\x00\x00\x87\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x39\x49\x44\x41\x54\x58\x85\xed\ -\xcd\xa1\x15\x00\x10\x00\x00\xd1\x63\x29\x55\x31\x80\x45\x4d\xe0\ -\x3d\xd9\x52\x9e\xa4\x8a\x8a\xfb\xe9\xda\x81\x24\x49\xbf\x0b\x27\ -\x52\x5b\x03\xc8\x8f\xae\x7d\xd6\x58\x00\xe2\x93\xa1\x24\x49\xd2\ -\xc5\x06\x65\xbc\x05\x04\xc9\x39\x8e\xf8\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\xd0\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x82\x49\x44\x41\x54\x58\x85\xe5\ -\x97\x5d\x88\xd4\x65\x18\xc5\x7f\xe7\x9d\xf1\x2b\xa9\x34\x24\xac\ -\x5c\xab\x25\xfb\x58\x2a\x05\x75\x56\x89\x3e\x34\x51\xd2\x74\x77\ -\x6b\xdb\x88\x22\x41\x14\xa5\x8b\x2e\x82\x4a\x4b\xda\xa2\x32\xbb\ -\x09\xac\xd0\x8a\x20\x04\xaf\xcc\x76\x56\xcd\xed\x03\x0a\xbd\x08\ -\x9d\x5d\xcd\x36\x48\x8a\xc0\xd0\x56\xb7\x0c\x04\x25\xd3\x6c\xe6\ -\x3d\x5d\xcc\xec\x38\xe3\xce\xae\x3b\xd6\x9d\xe7\x66\xf8\x3f\xff\ -\xe7\x3d\xe7\xbc\x5f\xff\xe7\x19\xb8\xd4\xa1\x6a\x92\xa7\xb7\xbb\ -\x26\x91\xa3\xd1\xf2\x1c\x8b\x1a\xcc\x04\x41\x00\x8e\x20\x7a\x8c\ -\x76\x29\x47\x3a\xd3\xac\x9f\xff\x57\x03\x33\xd3\x4e\x45\x7b\x2d\ -\x30\x6b\x88\xa4\x5d\x39\x69\x55\x57\x93\xbe\xfa\x4f\x06\xa6\x6e\ -\xf6\x95\xc9\x64\xdc\x00\x7a\xac\x10\xea\xc5\xde\xee\x10\x3e\x53\ -\x8e\x83\xc3\x23\xbd\x7f\x27\x89\x8e\x8c\x97\xb8\x41\x8a\x73\x41\ -\x0d\xc0\xf5\x05\xf6\x0e\x82\x96\x64\x1a\xf4\x7b\xd5\x06\x66\x6e\ -\xf5\x4d\x31\xe7\x6d\xc0\x6d\x40\xaf\x50\xeb\xc8\xb1\x7c\xb4\x73\ -\x96\xb2\x83\x4e\xa9\xd5\x21\x35\x85\x47\x65\xbf\x06\xd4\x4a\x1c\ -\x8e\xd6\xa2\xce\x87\xd4\x3d\x64\x03\xd3\xb6\xb8\x36\x11\x9c\x01\ -\xc6\x01\x5b\x19\xa9\x27\x33\xf3\x75\x72\x50\xe1\xf3\xf0\x40\x87\ -\x47\x1c\x3f\x13\xd7\x83\x96\x60\x4e\x05\xeb\xee\xdd\xcd\xda\x7f\ -\x41\x03\xf5\x1d\xbe\x82\x33\xde\x0d\xd4\x81\xd7\x65\xba\xc3\x33\ -\xbc\xa2\x58\x8d\x78\x11\xb6\xea\xdb\x59\x89\xbd\x06\xe8\xc9\x5a\ -\xa9\x7d\x0f\xab\xb7\x34\x25\xd9\x6f\xd0\xdf\xf1\x5d\x50\x9d\xcd\ -\xf6\xce\xef\xfb\x8b\x4f\x6f\x77\x4d\x88\x71\x29\xd2\x7c\xcc\x44\ -\x20\x62\x0e\x81\x76\x64\xe1\xc3\x32\x01\xc9\x19\x7b\x6d\x2a\xed\ -\x5a\xa1\xa5\x49\x79\x13\xf6\x1c\x24\x57\x5c\x81\xd4\x16\x4f\x53\ -\x70\x97\xe1\x8f\x5c\x56\x93\xf6\xb5\xe8\x44\xf1\x65\xab\x43\xfd\ -\x14\x9e\xc7\x7e\x09\x18\x59\x79\xc6\x9c\x92\xf4\xc2\x9e\x26\xde\ -\x29\x15\xa9\xdb\xec\xe1\x97\x27\xdd\x0d\xdc\x4a\xd4\x82\x4c\xb3\ -\x3a\xfa\xde\x85\xd2\xf1\x4a\xf8\x0d\x80\x60\xbd\xda\x4f\x7c\x72\ -\xdc\x58\x58\xca\xca\xe2\xf9\xe9\x8c\x36\x5e\x37\x23\x1d\xd7\x63\ -\x17\x27\x77\xa0\x45\x67\x85\x5e\xcc\x2b\x7a\x6d\xe9\xbb\xa2\x81\ -\xa9\x9f\xf8\x1a\xcc\xfd\xc0\xf1\x93\x39\xde\x2f\xe5\xad\x9f\xcc\ -\x6a\xd0\x13\x98\x21\xc1\x68\x45\x7d\x3b\x4f\x97\xc6\xf6\x34\x91\ -\x06\x7e\x04\xee\x48\xa5\xb9\xb3\x9f\x81\x64\x60\x21\x20\xe4\x1d\ -\x07\x5a\x74\xb6\x2f\x3e\x6d\x8b\x6b\xc1\xab\x0b\x33\x1c\x3a\xa2\ -\x5f\xbf\x6b\xab\xaf\x2d\x3e\x4b\x96\xbd\x0d\x20\x38\x36\xf5\x33\ -\x80\xe3\x7d\xf9\x9f\xf0\x79\x29\x4f\x22\x11\x9f\x02\x86\x55\x21\ -\x5d\x10\x64\xf4\x3f\x91\x65\x65\x9e\x14\xbe\x00\xb0\x34\xbb\xbf\ -\x01\x54\x53\x18\xf8\x4b\x19\x91\xb5\xa0\x6a\xf1\xa2\x07\x3f\x58\ -\xfa\x1c\xc4\xc1\x3c\x27\x13\x2a\x18\xc8\x07\x83\x38\x77\x8d\xf2\ -\x87\xa5\xf6\x62\x0d\xd8\x85\x4f\x72\x01\x63\x47\x14\xb8\xc5\x75\ -\x7d\x07\x31\x54\x18\x77\x0e\x2f\xa3\x0b\xe6\x0c\x02\x41\xe2\x02\ -\xdc\x65\xe4\x47\x00\x1c\x19\x5f\x8c\xbc\xa2\x68\x38\x74\xb1\x06\ -\x80\xc3\xa5\x0f\x27\x4e\x17\xb9\x8f\xf6\x7d\xe0\x4a\x0c\xf8\x57\ -\x00\x07\x6e\x2c\xa3\x90\x3b\xb8\x48\x88\xf2\xb1\xb9\x73\xdb\xd9\ -\xd3\x17\x2b\x1a\xb0\xc3\x4e\x80\xe0\x38\xaf\x8c\x44\xe1\x3d\xe0\ -\x62\x6a\xc1\xd9\x98\x0c\x1f\x96\x3b\x8a\x73\x0b\x6a\x5f\xf7\x33\ -\x30\x2c\xc9\x76\x00\xa3\x05\x53\xdf\x77\xf1\xda\x65\x1a\x75\x00\ -\xf9\xed\x6a\xd5\x2d\xad\xe9\x5c\xa4\x73\x37\xca\x16\x68\x11\x40\ -\x54\x48\xf7\x33\xf0\x4d\x83\x8e\x02\x5f\x03\xe3\x86\x5d\xcd\xd2\ -\x52\xb2\xec\xb1\xf0\x1c\xa2\x8a\xad\xf0\xc7\x9d\xdf\xf1\x6a\x69\ -\x64\x46\x1b\x0b\x81\x3a\xe0\x87\xae\x46\x8a\xbd\x41\xd9\x09\x8f\ -\xd6\xca\xbc\x59\xb7\xd6\x77\xf8\x8a\xbe\xf8\xbe\xe5\xfa\x27\x7b\ -\x4c\x8d\xe0\x75\x0c\xbe\x1d\x59\xe1\x35\x13\xb3\xe1\xb1\xd2\x2a\ -\x5a\xb7\xd9\xc3\xad\x7c\x9d\x51\xd0\xaa\x01\xab\x21\x40\xaa\x2d\ -\xb7\x49\xe8\x71\x60\x6b\xa6\x5b\x0f\x9d\x5f\x8e\xa7\xb5\xf9\xf6\ -\x04\x71\x05\xd6\x7c\xc4\x44\xc0\x86\x43\xc2\x9f\xe6\x12\x61\xc3\ -\xde\x06\xfd\x54\xbe\x18\x56\x7d\x3a\x6e\x00\x2d\x07\x76\x66\x9a\ -\x34\x7b\x50\x03\xf9\x3e\xd0\x7b\x80\x5b\x8d\xdf\xea\xec\x0e\xcf\ -\x0e\xd4\x90\x3c\xb2\xd9\x09\x80\x8f\x5b\x94\xab\xb8\x1e\xb6\x52\ -\xed\x3c\x2b\xfb\x4d\xe0\x68\x32\xa1\xe9\x85\xad\x2e\xa2\x62\x79\ -\x29\xf4\x83\x19\xe0\x2a\xa0\x6d\x54\x56\x8b\x77\xb6\xe8\xcf\x8a\ -\x22\x03\x20\xdf\x03\xc4\x77\x41\xcb\x80\xbf\x1c\x75\x6f\x67\xb3\ -\xf6\x9e\x9f\x37\x60\x7d\x4b\xb5\xf9\x66\xe1\x6d\xc0\x2d\xc0\x11\ -\x4b\xad\x97\x8d\x61\xe3\x50\x9a\xd2\x19\x53\x68\x76\xbe\x29\x9d\ -\x04\xf4\xc8\x6a\xd8\xf3\xb0\xbe\xad\x94\x3e\x68\x81\x9d\x92\xf6\ -\x98\x11\x8e\x1f\x80\x1e\x29\x84\x7a\x6c\x6f\x0f\x89\xf0\x59\x2e\ -\xcb\xc1\x64\xa4\xf7\xf4\x30\xe2\xa8\x1c\xe3\x73\x70\x7d\x08\x71\ -\x9e\xf3\x6d\x79\xdf\x07\xe7\xcb\x98\xd5\xe2\xae\x16\xfd\x36\x90\ -\xc6\x90\x2a\x7c\xaa\xcd\x33\x85\xd7\x02\xf7\x0c\x25\xdf\x62\xbf\ -\xd0\xca\x4c\x93\xbe\xbc\x50\x6e\x55\x7f\xcd\x66\xa4\x7d\x83\x23\ -\x8d\xc8\x73\x80\x1a\xf2\x15\x34\x01\xf4\x20\x7a\x40\xbb\x42\x8e\ -\xf4\xee\x66\xfd\x58\x0d\xef\xa5\x8d\x7f\x01\x53\xeb\xdb\x78\xb8\ -\xf8\xe0\x36\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x8c\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3e\x49\x44\x41\x54\x58\x85\xed\ -\xd3\xb1\x11\x00\x10\x00\x04\xc1\xa3\x32\x89\x0a\xb4\xa0\x2c\x2d\ -\x68\xc0\x98\xd1\x9a\x48\x2a\x24\xb9\x8d\x3e\xbb\xe8\x41\x92\xf4\ -\x59\x38\x23\x97\xba\x80\xf4\x28\x3a\x47\x6f\x19\x20\xbe\x08\x4a\ -\x37\xbe\x40\x92\xa4\xef\x36\xf1\x29\x0a\x07\x7b\xbe\x69\xcc\x00\ -\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x0a\x8e\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x0a\x40\x49\x44\x41\x54\x78\x9c\xed\ -\x5b\x7d\x8c\x1c\x65\x19\xff\x3d\xb3\xb7\xd7\xbb\x72\xd7\x03\x29\ -\x07\xf5\x76\x76\x76\xaf\x3d\x02\xa1\x25\x2a\x05\x81\xd4\x13\x50\ -\x03\x12\x28\x20\x24\xf2\x11\xa4\x02\x22\xa0\x88\xf2\x65\xd0\x00\ -\x15\x21\xf2\x21\x85\x90\xd4\x02\xb1\x0d\x50\x1a\x31\x28\x10\x31\ -\x7c\x34\xa1\x94\x54\x85\x40\x2d\x88\x8b\x94\x5c\xbd\xdd\xf9\xd8\ -\xeb\x51\xca\x47\x3f\xb4\xd7\xdd\xd9\xf7\xe7\x1f\x77\x6d\x67\x66\ -\x67\x67\x76\xef\xf6\x2e\x46\xfb\xfb\x6f\x9e\xf7\xf7\x7c\xcc\x33\ -\xef\xce\xbc\xef\xf3\xbc\x0b\xec\xc7\x7e\xec\xc7\xff\x33\x64\x2a\ -\x9c\x0c\x6c\xde\x7c\x48\x72\xb7\xdb\x4f\xc1\x3c\x0d\x72\x84\x02\ -\x7b\x01\x1c\x28\x90\x19\x00\x13\x00\xb6\x03\xd8\x4e\x88\x05\xf0\ -\x3d\x0d\xf2\x0f\xd2\x5d\x97\xc9\x64\xf2\x93\x1d\xdb\xa4\x25\xc0\ -\xb2\xac\xd9\x0a\xda\x22\x28\x2e\x84\xe0\xe8\x71\x9a\xc9\x83\xf2\ -\x82\xa6\xa9\x47\x75\x5d\x5f\x2f\x22\x6c\x6a\x90\x68\x72\x02\x48\ -\x4a\xc1\x71\x4e\x15\x85\x9b\x00\x9c\xdc\x4c\xdb\x00\x72\x14\x2e\ -\xf9\x68\xcb\x96\x27\xe6\xcf\x9f\x5f\x6e\x96\xd1\xa6\x25\xa0\x50\ -\x70\x4e\x86\xf0\x1e\x00\xf3\x9b\x65\x33\x1c\x52\x20\xb0\x38\x93\ -\xee\x79\xbc\x19\x33\x62\xc2\x09\x18\x1c\x1c\x3c\x54\x4b\x24\xef\ -\x03\x70\x51\x04\x4d\x11\xf8\xb3\x88\xac\x85\xe2\x46\x26\xf0\xcf\ -\x16\xe0\x63\xd7\x75\x77\xb8\x6d\x6d\x95\xd6\x52\xa9\x93\x6c\xe9\ -\x02\x54\x96\x82\xc3\x01\x39\x41\xc0\xaf\x01\x68\xaf\x65\x90\xc0\ -\x3a\x0d\xea\x2a\xc3\x30\xde\x9d\x48\xfc\x13\x4a\xc0\xa0\x6d\x1f\ -\xa7\x29\x3c\x0b\x60\x56\xc8\xf0\x0e\x81\x3c\x4f\xf2\xb9\x96\x16\ -\x79\x31\x95\x4a\x7d\xd4\x88\x6d\xdb\xb6\xdb\x2b\x15\x39\x45\x44\ -\x9d\x49\xc8\xc2\x1a\x3e\x46\x28\xbc\x34\x9b\x4e\xff\x66\x3c\xf1\ -\x03\x13\x48\x40\xa1\x60\x5f\x08\xc1\x0a\x00\xd3\xaa\x82\x02\x1e\ -\xd4\xa0\xee\x32\x0c\xe3\x93\xf1\xda\xf7\x22\x97\xcb\xb5\x76\x74\ -\xcc\xf8\x0e\x44\x6e\x05\xd0\x5d\x45\xa0\xdc\x69\x18\x3d\xb7\x8a\ -\x88\x6a\xd4\x76\xc3\x09\x20\xa9\x59\x96\x7d\x07\x21\x37\x07\x86\ -\x14\x80\x15\x2d\x09\xf9\x59\x2a\x95\x72\x1a\xb5\x5b\x0f\x36\x6e\ -\xfc\xb0\xb3\xbd\x7d\xe4\x3a\x02\x37\x00\xe8\xf0\x07\x86\x67\xa7\ -\x4f\x9f\x76\x71\x77\x77\xf7\xce\x46\x6c\x36\x94\x00\x92\x9a\x69\ -\x16\x57\x41\x78\x7e\x60\x68\x48\x69\x38\xa7\x57\xd7\xdf\x68\xc4\ -\xde\x78\xe1\x38\x4e\xca\xad\xf0\x19\x54\xbf\x70\xdf\x2a\x97\x46\ -\x4e\xea\xeb\xeb\xdb\x5e\xaf\x2d\xad\x11\xc7\xa6\x5d\x5c\x5c\x75\ -\xf3\x82\xd7\xc1\xca\xfc\xa9\xba\x79\x00\x48\xa5\x52\x4e\x42\x43\ -\x3f\x80\x55\x81\xa1\xcf\x27\x5b\xdb\x56\x91\x4c\xd4\x6b\xab\xee\ -\x19\x90\xb7\xac\x6f\x0a\xe5\x49\xbf\x32\x1f\x53\xaa\x72\x65\x36\ -\x9b\x1d\xa9\xd7\x4e\x33\x41\x52\x2c\xcb\xb9\x91\xc0\x5d\xf0\xdc\ -\x0b\x81\x7b\xb2\x86\xfe\xe3\x7a\x6c\xd4\x95\x00\xcb\xb2\xe6\x2b\ -\xca\x3a\x00\x6d\x1e\xf1\x13\x46\x3a\xf5\xad\xc9\x58\x9d\x35\x8a\ -\xbc\xe9\xfc\x50\xc0\xfb\xbd\x32\x81\x5c\x62\x18\xa9\xc7\xe3\x74\ -\x63\x13\xe0\x38\xce\xc1\x6e\x85\x7f\x03\xd0\xe3\x51\x7a\x43\x29\ -\xf7\xcb\x8d\x3e\xf9\x42\xa1\x70\x24\xb4\x96\x73\x84\x38\x9a\x50\ -\x29\x40\x52\x00\x2a\x02\x38\x14\x38\x50\xdc\x00\xa8\xa7\x1b\xdd\ -\x03\x90\x14\xd3\x2c\x2e\x87\xf0\xdb\x1e\x71\x09\x4c\x9c\x90\xc9\ -\x7c\x76\x43\x94\x6e\x6c\x02\x0a\x96\xbd\x1c\xc4\xa5\x1e\xd1\x90\ -\x26\x3c\x36\x9d\x4e\x0f\xd5\x13\x5c\x2e\x97\x6b\xed\xec\xec\xba\ -\x8a\xc0\x95\x00\x8e\xa8\x47\x07\xc0\x5b\x14\x3e\x98\xd1\xf5\x95\ -\x22\x52\xa9\x47\x61\x60\x60\x60\x5a\xb2\xb5\x6d\x0d\x80\x13\xf7\ -\x49\xb9\xc1\x48\xeb\x5f\x14\x11\xb7\x96\x5e\x64\x02\x4c\xd3\x5c\ -\x40\x68\xeb\x3c\x22\x52\xc9\x89\xd9\x6c\xea\xf5\x7a\x82\xca\x5b\ -\xd6\xd9\x42\xb9\x17\xc0\x9c\x7a\xf8\x21\x78\x1b\x94\xeb\x33\x99\ -\xd4\x9a\x7a\xc8\x63\xab\xd2\x1c\x80\x99\x7b\x64\x02\x5c\x6b\x18\ -\xfa\x83\xb5\x74\x6a\x7e\x05\x48\x0a\x91\xf8\x45\x40\xbc\xaa\x9e\ -\x9b\x5f\xbf\x7e\x7d\xb2\x50\x70\x96\x0a\xe5\x19\x8c\xff\xe6\x01\ -\xe0\x73\x10\xbe\x9c\x37\xed\xc5\x24\x63\xbf\x58\xbd\xbd\xbd\x1f\ -\x10\x72\xa7\x57\x46\xe0\x96\xe1\xe1\xe1\x03\x6a\xe9\xd4\x34\x5a\ -\x70\x9c\x7e\x80\x0b\x3c\xa2\xb2\x40\xdd\x16\x17\x84\x69\x9a\x07\ -\xcd\x3c\xe4\xd0\x17\x20\xbc\x3a\x8e\x5b\x2f\x04\xb8\xcd\xb4\x9c\ -\xdf\x16\x8b\xc5\xe9\xb1\x64\x55\x7e\x08\x02\xcb\x23\x99\x39\x52\ -\x2a\x7d\xb7\x16\xbd\x66\x02\x44\xe1\xc6\x40\x14\x0f\x1b\x86\x31\ -\x18\xe5\x3b\x97\xcb\xb5\x02\xda\xb3\x00\xbe\x12\x1b\x68\xe3\x38\ -\xaf\xec\xaa\xc7\xe3\x66\x42\x36\x9b\x1d\x21\xe8\x7f\x50\x94\xeb\ -\x6a\xad\x0d\x42\x8d\xe5\xf3\xf9\xc3\x00\x9c\xe6\x11\x95\x95\x5b\ -\xbe\x23\xca\x31\x49\xe9\xe8\xec\x5a\x4a\xa0\x3f\x8a\x37\x41\x9c\ -\x5b\xb0\x9c\xd8\x59\x98\xd1\xf5\x95\x04\x06\x3c\xa2\x9e\x82\x6d\ -\x7f\x35\x8c\x1b\x9a\x00\x49\x24\x2e\x04\xb0\x37\x63\x02\xac\xe9\ -\xed\xed\xfd\x20\xca\xa9\x65\x39\x17\x01\xb8\x3c\x2e\xb8\x89\x42\ -\x80\x5b\x4d\xb3\x18\x7a\x33\x7b\x39\x22\x15\x21\x9f\xf2\xc9\x94\ -\x5c\x12\xc6\xad\x31\x9d\xe4\x4c\xef\x15\x85\x7f\x88\x72\x58\x2c\ -\x16\xa7\x8f\xad\xc6\xa6\x04\x0a\x6a\x49\xdc\x72\x97\x09\xf1\xc7\ -\x2c\x38\x3d\x4c\xa7\x2a\x01\xc3\xc3\xc3\x07\x80\xde\x6f\x29\x50\ -\x29\x27\xfe\x18\xe5\xac\x5c\xae\x5c\x07\xcf\x42\x69\xb2\x21\xc0\ -\x3c\xd3\x74\x16\x45\x71\x32\xa9\xd4\x9b\x80\x78\x67\x6d\x57\xde\ -\x71\x8e\x09\xf2\xaa\x12\xb0\x7b\xb7\x7b\x3c\x80\x56\x8f\xe8\xed\ -\xd9\xb3\x7b\xac\x20\x6f\x0f\x46\xb3\x2a\x3f\x88\x0f\xbb\xb9\xa0\ -\xe0\xda\xa8\x71\x11\x51\x10\xfa\x1e\x5c\x42\x55\xd7\x29\x43\x7e\ -\x02\x9c\x1b\x10\xac\xab\xe6\xec\x43\xa1\xe0\x7c\x09\x82\x43\xa2\ -\x38\x93\x01\x01\xe6\xd9\xb6\xdd\x17\xc5\xe1\xe8\xfe\x65\xdf\x35\ -\x70\x54\x90\x13\x96\x80\x23\x03\x8e\x06\xaa\x39\x9e\xf1\x04\xce\ -\x0b\xe8\x47\xd1\x9b\x0a\x57\xe1\xdc\xa8\x71\xa1\x04\x63\x3f\x32\ -\xc8\x09\x49\x80\x64\xbc\x57\xa4\x44\x7e\xfb\xa1\x82\x45\x89\x29\ -\xe9\xb5\xec\xf1\x54\xf5\x9b\xf6\x82\x2c\x05\x63\xcf\x06\x39\x55\ -\x09\x20\xd0\xe9\x73\x22\xf2\x69\x4c\x14\x53\xf6\xf2\x0b\xf1\x9d\ -\x8a\x61\x04\x63\xef\x0c\x12\x62\x13\x50\xa9\xb0\x66\x8d\x6d\x6c\ -\x55\x16\x56\xad\x9d\x1a\x30\x3a\x01\x99\x4c\x66\x37\x00\xef\x4e\ -\xb0\x75\x74\xb5\xba\x0f\x55\x09\x90\xe0\x1c\x4e\x32\xea\x47\xad\ -\x85\xd9\x98\x3a\x48\x72\xa2\x16\xc2\x82\xdf\xe1\xbd\x48\x28\xad\ -\x6a\xda\xec\x75\x3f\xba\xcf\x8e\x5c\x21\x4e\x2e\x18\x59\x7d\x2e\ -\x14\x0a\xd3\x00\xb4\x78\x44\xa5\xb9\x73\xe7\x96\xbc\x9c\xb0\x19\ -\xe0\xab\xa8\x92\x3c\x30\x26\x8a\x62\xcc\xf8\xa4\x41\x80\xc8\x04\ -\x90\xec\x0a\x88\x76\x04\x39\x55\x09\x50\x80\x19\x30\x53\xf5\xe6\ -\xf4\x07\xc1\x5c\xd4\xf8\x64\x82\x94\x48\xdf\x9a\xd6\xda\x1b\x10\ -\x15\xaa\x38\xd5\x6a\xf2\x9e\xcf\x89\x20\x72\xb1\x21\x82\xa7\xa3\ -\xc6\x27\x17\x5a\xa4\x6f\xa9\x8e\x7d\x63\x95\x85\x6a\x41\xc5\xd7\ -\x6c\x14\x7f\x51\xa4\x0a\x95\x4a\x65\x35\x80\x86\xba\x31\x4d\x82\ -\x69\x18\xb3\xde\x8a\x22\x30\x10\x3b\x81\xaa\x19\x53\x95\x80\xf6\ -\xf6\xf6\xd7\x00\x78\xfa\xef\xf2\x05\xc7\x71\x6a\x7e\x6e\xb2\xd9\ -\xec\x08\x04\x8f\xc6\xc7\xdb\x64\x88\x3c\x12\x55\x92\x1f\xfb\x44\ -\x9f\xe1\x13\x2a\x59\x1b\xe4\x55\x25\xa0\xbb\xbb\x7b\xa7\x00\xaf\ -\x79\x65\x65\x15\x30\x14\x40\x39\xd9\x72\x3b\x80\x6d\xd1\x11\x37\ -\x0f\x02\xd8\x09\xf1\xf7\x01\x82\xb0\x6d\xfb\x18\xf8\xd7\x28\xdb\ -\x33\x99\x9e\xf5\x41\x5e\xe8\x37\x9c\x84\x6f\x17\x25\xe0\xc2\x28\ -\x67\x7d\xb3\x66\x7d\x08\x32\xb2\x62\xd4\x64\xfc\x44\xd7\xf5\x5d\ -\x51\x04\x05\xcd\x17\x33\xc1\x17\xc3\xca\xe3\xa1\x09\xd0\x34\xae\ -\xc2\x68\xb7\x77\x8f\xf6\x29\x03\x9b\x37\x47\xee\xf8\x0c\x43\x7f\ -\x40\x80\x97\xa2\x38\x8d\x23\x74\x86\xaf\x4c\xa7\x53\xc1\x9e\xa0\ -\x5f\x8b\xd4\x40\xfa\x36\x69\x42\x79\x2c\x8c\x1b\x9a\x80\x74\x3a\ -\x3d\x04\x62\xb5\x47\x34\x2d\xb9\xbb\x1c\x6c\x87\xfb\x20\x22\xae\ -\x52\xee\xf9\x00\xde\x8f\xe2\x35\x06\x09\x5e\xbe\x4e\xe5\x5e\x11\ -\xd7\x8e\x33\x4d\xe7\x02\xf8\x9b\x30\xc3\x86\x91\x5a\x1d\xc6\xad\ -\x5d\x15\x16\xf9\x65\x40\xf0\xbd\xc1\xc1\x21\x23\xca\x71\x36\x9b\ -\xfd\x54\xa0\x4e\x47\x53\x93\xb0\x17\xeb\x95\x5b\x3e\x3b\xae\x1d\ -\x97\xcb\xe5\x5a\x21\xf8\xb9\x57\x26\xc0\xfd\xb5\xba\x43\x35\x13\ -\x90\x4e\xf7\xac\x81\xff\x65\xd8\x9a\x48\xa8\xc5\x71\x51\x1a\x86\ -\x31\x48\xe5\x1e\x2f\x40\x68\xc6\xc7\x05\xca\x93\x09\x0d\xfd\x71\ -\x85\x59\x00\xe8\xe8\xe8\xba\x02\xfe\x6d\xef\xc7\xbb\x76\xb5\x2d\ -\xab\xc5\x8f\xdc\xbc\xe7\xf3\xf6\x49\xa2\xe1\x15\x8f\x48\x09\xd4\ -\x71\x86\x61\xfc\x35\x36\x66\xb2\xc5\xb2\x9c\xeb\x09\xfc\x14\x21\ -\xdb\xd0\x3a\xb1\x95\x22\xb7\x64\xf4\x9e\x87\xeb\xe9\x42\x17\x8b\ -\xc5\x99\x65\x57\xbd\x0b\xef\x31\x1a\xf2\x86\x4c\x26\x7d\x5f\x2d\ -\x9d\x98\x26\x83\xbe\x16\xc0\x4a\x3f\x5f\x7b\x66\x70\x70\xf0\xd0\ -\xb8\x60\x44\xc4\x35\x0c\xfd\x6e\xb7\x9c\x9c\x03\xca\x32\x00\xff\ -\x8e\xd3\xf1\x60\x9b\x00\x77\x55\xdc\xd2\x9c\x6c\x3a\xf5\x50\x3d\ -\x37\x9f\xcb\xe5\x5a\xcb\x65\xf5\x3b\xf8\x6e\x1e\xef\x6c\xdd\xba\ -\xa5\x66\x5f\x10\xa8\xa3\x7c\xb3\x69\xd3\x70\x77\x4b\xd2\x7d\x07\ -\xa0\xf7\xa6\xff\x52\x2e\x8d\x9c\xd2\xd7\xd7\xb7\x3b\x4e\x7f\x0f\ -\x8a\xc5\xe2\xf4\x72\x59\x9d\x06\x0d\xe7\x92\x98\x27\xa3\x55\xe4\ -\xcf\x8c\x05\xfa\x21\x34\x0c\x41\xc9\x06\x80\x4f\xed\xdc\xb9\xed\ -\xe5\xe0\xae\x2d\x0e\xa6\x69\x2d\x23\xe4\x4a\x8f\xa8\xac\x34\x2c\ -\x88\x3b\xb9\x52\x57\xfd\x2a\x9f\x77\x8e\x17\x8d\x6b\xe1\x3d\x11\ -\x26\x58\x61\xe8\xa9\xcb\x27\x72\x40\xc2\xb6\xed\xf6\x91\x91\x11\ -\xd5\x48\x22\xc3\x50\xb0\xac\xab\x41\x59\xea\x13\x12\x97\x67\x32\ -\xfa\xf2\x38\xdd\xba\x0b\x78\xa6\xe9\x5c\x4c\xd0\x77\xe2\x82\xc0\ -\x23\xff\xda\xb1\xed\x9a\x46\x9f\x56\xb3\x30\x76\x44\xe6\x1a\x02\ -\xf7\xc3\xf3\x73\x16\xf0\x01\xc3\x48\xff\xa8\x1e\x1b\x0d\x55\x30\ -\xf3\xa6\x7d\xb7\x00\x37\xf9\xa3\xc0\xab\xc9\xa4\x76\x5e\x4f\x4f\ -\xcf\xd6\x46\x6c\x4d\x14\xb9\x5c\xae\xb5\x63\x46\xd7\xaf\x40\x5c\ -\xe6\x95\x0b\xf0\x52\x3a\x9d\x3a\x23\xea\x50\x44\x80\x5f\x3f\x48\ -\x26\x4c\xdb\x79\x0a\xc4\x39\x01\x33\x85\x84\xc6\x85\xba\xae\xff\ -\xbd\x11\x7b\xe3\xc5\xd8\x7b\xe9\xf7\xa8\xde\xa9\xbe\x4b\xe5\x2e\ -\xc8\x66\xb3\xd1\x85\x5c\x0f\xc6\x73\x50\x32\x61\x9a\xf6\xbd\x10\ -\x09\x4e\xb1\x32\x81\x65\x95\x72\xf2\xce\x39\x73\x0e\xdb\xd2\xa8\ -\xdd\x7a\x30\x7a\x7c\x16\xdf\x87\xe0\x66\x00\x07\xf9\x06\x05\x2f\ -\x54\xca\xa5\x0b\x66\xcf\x9e\xdd\xd0\xa6\x6c\x22\x47\x65\x2f\x83\ -\x60\x19\x80\x60\x61\x72\x27\x81\xfb\xdc\xd2\xc8\x92\x46\x0e\x2c\ -\x46\x81\x64\x8b\x69\x3a\x8b\x20\x58\x8c\xb0\x1e\x24\x65\x89\x61\ -\xf4\xdc\x54\xef\x79\x22\x2f\x26\x76\x58\xda\xb2\xfa\x35\xca\xd3\ -\x00\x0e\x0e\x19\xfe\x84\xe0\x73\x1a\xb4\xe7\x4a\xa5\x5d\xab\x1b\ -\x4d\xc6\xe8\xe1\xaa\x83\xfa\x15\xd4\x99\x02\x9c\x05\x20\x6c\x19\ -\x5e\x06\x71\x55\x3d\x6f\xfb\x5a\x98\x70\x1b\x67\x53\xb1\xa8\xb7\ -\x54\xd4\x03\x20\xbe\x11\x41\x2b\x03\x7c\x15\xa2\xbd\x02\xc5\xf7\ -\x95\x92\x4d\x6a\x9a\x7c\x9c\x74\xdd\x9d\xa5\x52\xa9\xd2\xd6\xd6\ -\xd6\xa9\x94\xea\x22\x13\x59\x6a\x38\x1c\x54\x27\x08\xe4\x54\x00\ -\x33\x6a\x19\x24\xf0\xe6\xd8\x71\xf9\xd8\x55\x69\x14\x9a\xf8\x87\ -\x09\xfb\xeb\x14\xdc\x2d\xc0\xbc\x66\xd9\xac\x81\x21\x42\x6e\xcf\ -\xa4\x7b\x7e\x3d\x9e\x29\x1f\x44\xb3\xff\x32\xa3\x99\xa6\x73\x16\ -\x05\x37\x0b\x70\x6c\x33\x6d\x03\x18\x04\xb9\x84\xac\x2c\x6f\xe6\ -\xd1\xdc\x49\xeb\x64\x9a\xa6\x79\x14\x45\x5b\x04\x85\x85\x10\x1c\ -\x3e\x4e\x33\xc3\x10\x3c\xaf\xc0\xc7\xb2\xba\xfe\xa7\xf1\xfc\x1f\ -\x20\x0e\x53\xd2\xca\xdd\x54\x2c\xea\x49\x97\x27\x2b\xf0\x28\x40\ -\x8e\x00\x98\x15\x41\x17\x88\x19\x18\xed\xdc\x6c\x03\xb8\x5d\x20\ -\xb6\x02\x36\x42\xb8\x51\x23\x5f\x4d\xa7\xd3\xef\xfd\x37\x9c\x45\ -\xde\x8f\xfd\xd8\x8f\xff\x5d\xfc\x07\xbb\x1b\xfe\xd4\xc4\x32\xd9\ -\x11\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x3e\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xf0\x49\x44\x41\x54\x58\x85\xed\ -\xd6\x3f\x68\x13\x61\x18\xc7\xf1\xef\xf3\x5e\x62\xa5\x82\x8a\x1d\ -\x14\x5d\x44\x9c\x1c\xfc\x13\xcc\xe0\xe0\x28\x5d\xea\x24\xc1\x45\ -\xd1\x45\xd2\xda\x34\x05\xc1\x51\x4a\x70\x74\x50\x92\x5a\x6b\x40\ -\x10\x75\x10\x8b\x5b\x10\xc5\xd1\xa1\xa0\x6d\xc4\xc5\xc9\xa1\x93\ -\x28\x48\x4b\x87\x8a\x35\xc9\xfd\x1c\xee\xb2\x38\xdd\x5d\x8e\xcb\ -\xa0\x0f\xdc\x76\xcf\xfb\xfb\xf0\xdc\xfb\xde\x1d\xfc\xeb\x65\x51\ -\x6e\x3a\x5d\xae\x6f\x80\x59\xbe\xdb\x39\xb2\xfc\xe8\xc6\x7a\x9a\ -\x00\x17\xf1\xbe\xbd\xa0\x3d\x9d\x5c\xae\x75\xfc\xf2\x9d\x5d\xc3\ -\x00\xf4\xeb\xcc\xc8\xe8\xc8\xcb\x63\xa5\xb9\x1d\xc3\x02\x20\x18\ -\x1f\xdd\x37\xf6\xa4\x54\x7a\xe1\x65\x0e\x10\xf8\x60\x02\x2e\xae\ -\x8d\x7d\x6b\x80\x22\xed\xa1\xd4\x00\x06\x12\xbe\x00\x24\xa6\x8a\ -\x93\xf5\x5a\xa6\x80\x00\x61\x92\xe1\x07\x08\xbb\x55\x2c\x37\x66\ -\x33\x05\x00\x98\x90\x50\x80\x40\xf7\x8a\xe5\xc6\xa5\x4c\x01\xf0\ -\xd7\x24\xd0\xe3\xc2\xe4\xfc\x44\xa6\x00\x08\x26\x81\x10\xe0\x39\ -\xf9\x4b\x85\xa9\xfa\xd9\x4c\x01\x81\x02\x3f\x44\xec\x74\x3e\xad\ -\xe2\xb5\xbb\x27\xb3\x05\x84\x08\xc9\x04\xec\x96\xf3\x5e\x17\xae\ -\xdf\x3f\x9a\x2d\x00\x30\x53\xff\x1d\xb1\xdf\x7a\xbd\xb7\xa7\x2a\ -\x8d\x83\x99\x02\x82\x0a\x4e\x86\xc1\x61\xd7\xd1\xab\x21\x00\x00\ -\x44\x88\x38\x31\x04\x80\x39\x30\x04\x6b\xbd\xbc\x1d\x8a\xd2\x91\ -\x4b\x2b\x5a\xe0\x2c\xf8\x36\x7c\x97\xe7\x9d\xfb\x38\x3f\xfd\x35\ -\x4a\x5f\x5a\x13\x70\x16\xfc\xdc\x6c\x3a\x18\x6f\x2f\x4c\x7f\x89\ -\xdc\x98\x46\x38\x41\xf8\x2f\xdf\x71\xfe\xfd\xc3\xea\xa7\x38\xcd\ -\x83\x3e\x02\x0b\xaf\x9e\x6f\xae\xd4\x7e\x50\x79\x17\x77\x81\xc4\ -\x13\x90\xc9\xfa\xfd\x86\x5d\x6d\x2f\x56\x5a\x49\xd6\x49\x3a\x01\ -\x33\x99\x03\x90\x98\x5d\x69\xce\x3c\x4b\xb8\x4e\x92\x09\xc8\x40\ -\x2e\x54\xdc\x5e\x6d\x56\xeb\x49\xc3\x63\x03\x84\x0c\xf5\xcf\xba\ -\x16\x3e\x2c\x56\xe7\x06\x09\x8f\x0d\x30\x70\x18\x20\x7b\xbe\x7a\ -\x60\x7d\x26\x7c\xf7\x0f\x54\x31\xf7\x80\x61\xf0\x66\x6b\xe3\xc7\ -\x15\x9a\x35\x7f\xd0\x70\x88\xbf\x07\x96\xb7\x7f\x6e\x5f\xf8\xbc\ -\x54\xfb\x9d\x46\x38\x44\x9c\x80\x60\xd3\xc0\xf2\xdd\xee\xc4\xca\ -\xd3\x9b\x5b\x69\x85\xff\x2f\x80\x3f\x94\x18\xa2\x63\x8f\xc5\xfb\ -\x89\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x98\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x4a\x49\x44\x41\x54\x58\x85\xed\ -\xce\x49\x0d\x00\x31\x0c\x04\xc1\x5c\x90\x0c\xca\x2c\x36\x14\x4c\ -\x25\xfc\x72\x80\x98\x95\xfc\xe9\xfa\xcf\xa8\x4b\x11\x98\xc7\x34\ -\x8f\xa9\x7c\x34\x65\xfc\x07\x02\x08\x20\x80\x00\x02\x08\x48\x0f\ -\x18\xf2\xc3\xad\x9f\x79\xe4\x04\xdc\xd3\x57\x6d\x5b\xb9\x00\x00\ -\x00\xf9\x1e\xf2\x23\x09\xdd\x64\x85\x0e\x0a\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xd0\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x82\x49\x44\x41\x54\x78\x9c\xed\ -\xd7\x31\x0e\x82\x50\x10\x04\xd0\x81\x43\x10\x1b\x13\xce\xe4\x15\ -\xa8\x38\x11\x37\xf1\x3c\x24\x36\xc4\x43\x88\xad\xe1\xdb\x22\x86\ -\xff\x5e\x39\xd9\x62\x76\xbb\x4d\x00\x00\x00\x00\x00\xa8\x47\xb3\ -\x0d\xe6\xf9\x71\x4b\x93\x29\x49\x77\x40\x9f\x3d\x2d\x59\x33\xf4\ -\xfd\xf5\xfe\x19\xb6\xc5\xd8\x39\x97\x4f\x92\x4b\xda\x4c\xdb\xb0\ -\x3c\x40\x65\xca\x03\xac\x19\x93\x3c\x7f\x5f\x65\x77\x4b\x5e\x19\ -\x8f\x2e\x01\x00\xfc\x0f\xbf\x40\x31\x76\xce\xe5\x13\xbf\xc0\x77\ -\x7e\x01\x00\x00\x00\x00\x00\x00\x2a\xf1\x06\x74\xea\x1a\x0f\x1a\ -\xcd\x17\x42\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x2e\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xe0\x49\x44\x41\x54\x58\x85\xe5\ -\x96\xbd\x6b\x14\x51\x14\xc5\x7f\x67\x46\x8d\x20\xf1\xab\x90\x85\ -\xcd\xec\x18\xc1\x2e\x85\xa5\x95\x65\x04\x25\x8d\x85\x56\x0a\x76\ -\x36\x42\xfe\x00\xb1\x10\x7b\x11\x04\x4b\x41\x2b\x2d\x6c\x82\x85\ -\xa6\xb3\xb2\x14\xd9\x4e\xc8\x3a\x3b\xbb\xb0\x58\x69\x82\x90\x0f\ -\x76\x8e\xc5\xac\xb5\xfb\x66\x1e\x0a\x7a\xab\x79\xc3\xbc\x73\x7e\ -\xf7\xbe\xfb\xde\x1b\xf8\xdf\x43\xb1\x05\xcb\xb2\x3c\x3d\xad\xd8\ -\x02\xfb\x6c\xde\x3b\xf5\xbb\xef\x0f\xc5\x34\x9f\x4c\x26\xc7\x76\ -\xf7\x0f\xde\x00\x27\xe6\xcd\x2d\x1a\x40\xbf\xdf\x3f\xb2\xb7\x77\ -\xf0\x1a\xb8\x18\x32\x2f\x89\x61\x6e\x3b\x5d\x5c\x3c\xf9\xdc\xb0\ -\x8a\x1d\x34\xb7\x35\x80\x6d\x0d\x87\xe5\x13\xe3\x1b\xf5\x1b\x55\ -\x7f\x14\xa0\x28\xc7\x0f\x8c\xee\x00\x18\x2a\x44\x50\x09\x5a\x01\ -\x0c\x8a\xd1\x3a\xf6\x3d\xdb\x80\x2b\x11\x66\xde\x0a\xa0\x28\x46\ -\x37\x85\x1f\x01\x24\x52\x05\x0a\x36\x6f\x0c\x50\x14\xe3\x35\xe3\ -\x67\xf5\x48\x95\x1b\x64\xde\x18\x60\x6b\x38\xbc\x64\xaa\x57\x40\ -\x5a\x1b\x07\xb6\x7d\x1b\x80\xc1\x60\x74\x21\xb1\x36\x80\xa3\x60\ -\x0b\x82\x3a\xbe\x15\x40\x59\x96\xe7\x95\xf8\x2d\x70\x1c\x70\xe8\ -\x76\x6b\x05\x50\x96\x65\x77\x5a\xb1\x09\x9c\x99\x75\x7a\x14\x73\ -\x98\xf3\x28\x9e\x56\x8c\xea\x27\xe3\x48\x99\xff\x8a\xf9\x96\xc0\ -\x7c\x8a\x69\x1a\x0c\x90\xa6\x5c\x01\x7d\x01\xa1\x48\xf7\x47\x10\ -\x40\x96\x65\xe3\x34\xf1\x2a\xf0\xd5\xf5\x3d\x1b\x0d\x62\x6e\xa1\ -\x2c\xcb\x3e\xbb\xd2\x65\x60\x1b\x10\x8e\x03\x11\x24\xb2\xbc\xbc\ -\xf4\xb1\x92\xd7\x80\x5d\x84\x1c\xa1\x12\xc1\x02\xe7\x7a\xbd\xf7\ -\x22\xb9\x0e\x4c\x05\x52\xcb\xdf\xba\x46\x19\xe4\x79\x77\x43\xe8\ -\x36\xc0\xac\x0a\x8d\x21\x1a\x97\x30\xcf\x97\x5e\x08\xd6\x01\x6c\ -\x37\x86\x68\xb5\x86\x79\x9e\x3d\x46\x7a\x28\x69\xa6\xe5\x60\x88\ -\xd6\x4d\x94\x67\xdd\xfb\x58\x4f\xeb\x91\x12\x3b\xac\x12\xad\x01\ -\x24\x39\xcf\xbb\x77\x85\x5e\xd6\xe3\x30\xcd\x28\x7b\x59\xd2\x74\ -\x67\xe7\xdb\x2d\xc1\xbb\xd0\xb9\xd1\x4e\xb4\x95\x95\x95\xfd\x85\ -\x85\xc3\xd7\x10\x1f\xfe\x0a\x00\x40\xa7\xd3\xf9\x91\x8a\xab\xb6\ -\xb7\xc1\xdf\x63\x6a\xff\xbb\xf1\x13\xb6\x0b\xa1\x01\x61\x9e\xcd\ -\x4b\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x98\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x4a\x49\x44\x41\x54\x58\x85\xed\ -\xce\xc1\x0d\xc0\x30\x08\x04\x41\x82\x5c\x1b\x15\x50\x02\x7d\x98\ -\x9a\x52\xa0\x9d\x22\x2e\x12\x9f\x9d\xff\x9d\xd6\x4c\x10\x59\x1d\ -\x59\xad\x7c\xb8\x32\xfe\x03\x01\x04\x10\x40\x00\x01\x04\x8c\x07\ -\x2c\xf5\xe0\x5e\xdb\x91\x35\x13\xf0\x1c\x7f\xcd\x8f\x72\x01\x00\ -\x00\xe6\x7d\x0c\xb6\x09\x4f\xb2\x71\xd6\x0c\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x75\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x27\x49\x44\x41\x54\x78\x9c\xed\ -\xc1\x01\x0d\x00\x00\x00\xc2\xa0\xf7\x4f\x6d\x0e\x37\xa0\x00\x00\ -\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x77\x03\ -\x40\x40\x00\x01\x8f\xf2\xc9\x51\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x00\x77\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x29\x49\x44\x41\x54\x58\x85\xed\ -\xce\x41\x01\x00\x20\x0c\xc4\xb0\x0d\x53\xb8\x9e\x44\x40\xc6\xf1\ -\x48\x0c\xb4\x55\x00\x40\x58\xef\x39\x37\x39\xb0\x92\x71\x00\xe0\ -\x0b\x0f\xd3\xb2\x02\xe6\x6a\x84\x46\x98\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x9a\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x4c\x49\x44\x41\x54\x58\x85\xed\ -\xd7\xc1\x09\x00\x20\x08\x46\x61\x8b\x76\xf2\xda\xc4\x4d\x10\xb8\ -\x99\xb4\x41\xa6\x74\x7c\xef\xf8\x83\xf0\x5d\x15\xa1\x64\xba\xdc\ -\x74\xb9\xbd\xee\x51\xa3\x60\x98\xc9\xfd\x5a\xaf\x1c\xfd\x0c\x00\ -\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf2\x9f\x51\x93\ -\x9d\xda\x29\xe8\x00\x81\xd7\x0c\xbd\xf7\x79\x8f\x39\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xee\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xa0\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\x41\x11\x00\x20\x00\xc3\x30\x0e\x53\xb8\x46\x22\x20\x23\x3c\ -\x1a\x03\xeb\x6d\x0c\x68\xed\x73\xd7\x3e\x57\x36\x4c\x39\xfe\x83\ -\x0e\xd0\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\ -\x00\x1d\xa0\x75\x80\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\ -\xd0\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\ -\x1d\xa0\x75\x80\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\ -\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\ -\xa0\x75\x80\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\ -\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\ -\x75\x80\x0e\xd0\x3a\x40\x07\x68\x0f\xaf\xe7\x06\x43\x97\x92\x59\ -\xbc\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\xea\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x9c\x49\x44\x41\x54\x58\x85\xe5\ -\x97\x5d\x6c\x14\x55\x14\xc7\x7f\x67\xa6\x5b\xaa\x15\x6a\x94\x34\ -\x68\x77\x66\xa7\x8b\x4d\x90\x54\x9f\x2a\x09\x0f\xf8\x81\x04\x12\ -\x91\x0f\x49\xd4\x10\x8d\x24\x08\x91\xf8\xe0\x83\x09\x0a\x4a\xe4\ -\x01\xc5\xfa\x62\x82\x12\x50\x43\x62\x4c\x78\x33\xb1\x81\x0a\x28\ -\x89\x04\x9e\x90\xd0\x84\x90\x54\x03\x59\xda\xdd\x9d\xd9\xa5\x62\ -\x8d\x09\x22\xa8\xed\xce\x3d\x3e\xec\x07\xb3\xdd\x6e\xbb\xad\xbe\ -\x71\x5e\x76\xe6\xdc\xff\x39\xff\xff\xbd\x77\xee\x3d\x67\xe1\x4e\ -\x37\x99\x09\xf8\x4a\x3e\xef\xc4\x0a\x66\xbd\x41\x56\x08\xea\xa0\ -\xc4\x11\x2c\x94\x3c\x42\x4e\xe0\x8c\x65\xd1\xe7\x38\x4e\xea\x7f\ -\x15\x30\x1c\x04\x4b\x2c\x43\x2f\xf0\x54\x23\x78\x85\xf3\x16\xb2\ -\x33\x91\x88\xff\xf0\x9f\x04\x0c\x0d\x0d\xb5\xd9\x76\xf3\x41\x84\ -\x8d\x25\xd7\x88\x42\x3f\xa2\x27\x54\x64\x38\x6c\x6a\x1a\xb9\x2b\ -\x0c\x4d\x18\x86\x0b\x54\x6d\x4f\x45\x57\x0a\xac\x03\x12\x25\xfc\ -\x71\x13\x8e\x6f\x4e\x26\x93\xd7\x66\x2c\x20\x08\x82\x87\x42\xa3\ -\x47\x41\x1e\x06\x46\x04\x76\xbb\x6e\xfc\x4b\x11\x29\x4c\x25\x5a\ -\x55\xad\x4c\x10\xbc\x28\x2a\xef\x03\x49\x04\xdf\x14\x64\x6d\x32\ -\x19\xbf\xd8\xb0\x80\x6c\x36\x9b\x54\xac\x73\xc0\x7c\x81\x23\x63\ -\x63\x7f\xbf\xd2\xd5\xd5\xf5\xc7\x54\xc4\x13\x2d\x95\x4a\xcd\x89\ -\xcd\x69\x39\x80\xb2\x19\xb8\x89\x5a\xcb\x3c\xaf\xe3\xc2\xb4\x02\ -\x52\xa9\xd4\xbc\x58\x73\xcb\x59\x60\xb1\xc2\x3e\xcf\x8d\xbf\x29\ -\x22\x66\x26\xe4\x65\x53\x55\xc9\xf8\xf9\x1d\x82\xee\x05\x72\x68\ -\xb8\xc4\xf3\xbc\x91\x28\xa6\x69\x62\x50\xac\xb9\x65\x7f\x91\x5c\ -\xfb\x3d\xd7\xa9\x21\xbf\x92\xcf\x3b\x76\xc1\x6c\x11\x78\x06\x70\ -\x01\x83\x92\x05\x3d\x06\xe6\x50\x94\x40\x44\x54\x55\x7b\xb3\x7e\ -\x2e\x09\x6c\x41\xec\xc3\xaa\xba\x42\x44\x74\xd2\x15\xf0\x7d\xbf\ -\xc7\xa8\x9c\x47\x19\x0d\xc3\xb1\xae\x85\x0b\x17\x5e\x8f\xcc\xc6\ -\xca\xf8\xf9\xb7\x05\x7d\x0f\x68\xa9\x33\xe9\x9b\x02\xef\xb8\x6e\ -\xfc\xd3\x28\xc9\xe0\xe0\x60\xf3\x3d\x73\xdb\x2e\x02\x8b\x50\x56\ -\x7b\x9e\x73\xbc\x3c\x66\x45\xa3\x8d\xf2\x61\x51\x39\x7b\x26\x92\ -\x67\xfd\xdc\x57\xa5\xa5\xac\x47\x0e\xd0\xaa\xb0\xcf\xf7\x83\x03\ -\xaa\x5a\x99\x5c\x77\x77\xf7\x18\xca\xbb\x00\x2a\xf4\x46\xc7\x2a\ -\x02\x32\x99\xcc\x03\x20\x4f\x03\xbf\xdf\xb8\x71\xfd\xf3\xea\x95\ -\xc9\xed\x02\x5e\x56\xa5\x21\x53\x64\x9b\xef\xe7\xde\x88\xfa\x12\ -\x89\x78\x1f\x70\x49\xe0\x91\x74\x3a\xff\x68\x8d\x00\x11\x7b\x0d\ -\xc5\x2d\x39\xd6\xdd\xdd\x3d\x56\xf6\x17\x4f\x04\xbb\x8a\x98\xc6\ -\x04\x14\x45\xf0\x81\xef\xfb\x0f\xde\xce\x2f\xaa\x70\x14\x40\x6c\ -\x7d\xae\x46\x80\x2a\x4f\x96\x22\xbf\xab\x4a\x24\xf6\xeb\x40\xac\ -\x71\xea\x8a\xb5\xaa\xca\xd6\xa8\x43\x54\xbe\x2f\x3d\x2e\xaf\x11\ -\x80\x88\x53\x7a\x48\x57\x4f\x45\x57\xcf\x82\xbc\x18\x0a\xcf\x56\ -\xa7\x1a\x1f\x06\x10\x88\xd7\x0a\x28\x39\x55\xc7\x47\x6e\x07\xa8\ -\x00\xc9\xd9\x0a\x40\x2b\x57\x32\x00\x85\x42\xa1\x9c\xbb\xa3\xfc\ -\x21\x5a\x35\x41\xd5\x26\x0d\x60\xa6\x8a\xb6\xa7\xc9\x1d\x4d\x6e\ -\xf2\xc5\xdf\xd8\x82\x0a\xa2\x78\x09\x65\x67\x2d\x00\xfc\xe8\x8b\ -\x6d\xb7\x96\x72\xcb\xd5\xf2\x05\x77\x5b\x80\x5a\x41\x11\x65\x3a\ -\x27\x24\x39\xce\x6c\x4d\xb5\x2a\xd6\xb2\x4c\x79\x3b\x73\x15\x5f\ -\x05\x2b\x9c\x06\xb0\x94\x55\xd1\x20\xc1\x7c\x06\xcc\xa6\x16\x8c\ -\x81\x39\x54\x95\x4b\x74\x25\x80\xa2\xa7\x6a\x04\xd8\x62\xfa\x8b\ -\x83\xb2\x7a\x60\x60\xa0\x72\xec\x12\x89\xc4\xcf\x82\x7e\xd2\x38\ -\xaf\x96\x84\xb3\xd7\xf3\xbc\xca\x89\x52\x55\x51\x58\x0b\x80\x91\ -\xbe\x1a\x01\xae\xeb\x5e\x05\x4e\x01\xf3\xef\x6f\x6f\xdf\x12\x4d\ -\x39\x3a\xfa\xeb\x5b\x34\xbc\x15\x82\xa2\x5f\xbb\x6e\x7c\x4f\xd4\ -\x1b\x04\xc1\x1a\x60\x31\xf0\x93\xe7\x75\x54\x7a\x83\xaa\x2f\xdc\ -\x12\xdd\x01\x20\x6a\xed\x4e\xa5\x52\xf3\xca\xfe\x9e\x9e\x9e\xf1\ -\xdf\x46\xaf\xad\x57\xd8\xc7\xd4\xdb\x51\x40\x75\xaf\xe7\x3a\x1b\ -\xa3\x55\x74\x70\x70\xb0\xd9\xa8\x14\xeb\x0c\xd6\xce\xba\xd5\x10\ -\x20\x93\x0d\x0e\x03\x2f\x09\x1c\x71\xdd\xf8\x86\x89\xe5\xd8\xf7\ -\xfd\x6e\x83\x6c\x43\x2b\xe5\x58\x81\xac\xc2\xb7\x1a\x5a\x07\x93\ -\xc9\x8e\xcb\x51\xbc\xaa\x8a\xef\x07\x07\x15\x79\x0d\xe1\x74\xc2\ -\x89\x2f\x9f\x52\xc0\xd0\xd0\x50\x9b\xdd\xd4\xfc\x23\xb0\x08\x95\ -\x8f\x13\x89\x8e\xed\xf5\x1a\x12\x55\xb5\x01\x44\x24\xac\x33\x2e\ -\xbe\x9f\xdb\xae\xf0\x11\x70\xd5\x12\x7d\xac\xb4\xd5\x15\x9b\xb4\ -\xbc\x14\xfb\x41\xce\x01\xf7\x21\x7c\x73\x77\xcb\x9c\x4d\xed\xed\ -\xed\x7f\x4e\x86\xad\x67\xa5\x1e\x60\x3f\xb0\x15\xb8\x65\x89\x3e\ -\xe1\xba\xee\xc0\x44\xdc\xa4\xb7\x9c\xe3\x38\x57\x42\x5b\x96\x02\ -\x97\x51\x36\xdc\xfa\xeb\x9f\x4b\x99\x4c\xf0\xaa\xaa\xd6\x74\x50\ -\x13\x4d\x55\xad\x6c\x36\xf7\x42\xeb\xdc\xb6\xc1\x12\x79\x0e\xb5\ -\x97\x4d\x46\x0e\xd3\xb4\xe5\xe9\x74\xfa\x5e\x2c\xfb\x0b\x41\x9e\ -\x2f\xb9\x72\xa8\xf4\x8b\xc8\x09\x28\x0c\x5b\x96\x35\x52\x28\x14\ -\x0c\x34\x2f\xc0\x0e\x13\x62\x58\x85\xc8\x3a\x4a\xf5\x43\xe0\xa4\ -\x31\x85\x4d\x9d\x9d\x9d\xbf\xd4\xe3\x68\xa8\xc2\x67\x32\xb9\xa5\ -\x22\xda\xab\xf0\x78\x23\x78\xe0\x82\x11\xdd\x91\x74\xdd\x93\xd3\ -\x01\x67\xf4\xd7\x2c\x9d\x4e\x7b\x58\xb1\xf5\x82\xae\x40\x71\x10\ -\xe2\x80\x0d\xe4\x04\x72\x06\x39\x83\x91\xbe\xce\xce\x8e\x4b\x33\ -\xc9\x7b\x67\xdb\xbf\x21\xb9\xe6\xce\xae\xea\xf6\xd6\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x18\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xca\x49\x44\x41\x54\x58\x85\xed\ -\x96\x3f\x48\xc3\x40\x14\xc6\xbf\x97\x0a\x29\x08\xd5\x5d\xa9\x8b\ -\xb8\x76\x15\x41\x5c\x8c\xae\xd2\x58\xc4\x21\x2e\xad\x2e\xba\x14\ -\x44\x5c\x9c\x3a\x38\x08\x2e\xc5\xa5\x56\x1c\x5c\x94\x92\x82\xd0\ -\x45\xb3\x08\x22\x38\xda\xd1\xc1\xa1\x38\xb8\x08\xfe\x19\x0a\x85\ -\xe6\x9e\x8b\xa9\x35\x35\x69\xd2\xbf\x83\xfd\xa6\x77\xc9\xcb\x7d\ -\xbf\xbc\xbb\x7b\x1c\xf0\xdf\x45\x6e\x2f\x17\x34\x6d\x58\x94\x83\ -\x29\x02\x47\x01\x4c\xb4\xe9\x55\x02\x58\x97\x2b\x81\xbd\x42\x21\ -\x53\x6e\x0a\xb0\xa0\x69\xc3\x5c\x0e\xde\x01\x1c\x69\xd3\xd8\x26\ -\x2a\xca\x15\x9a\xb1\x20\x24\xa7\x34\x51\x0e\xa6\x3a\x6f\x0e\x00\ -\x1c\xa9\xc8\x66\xca\x1a\x39\x02\x7c\x97\xbd\x4b\x22\xd5\x8a\x86\ -\x5c\xb2\x7e\xad\xb9\xa1\x67\x5d\xf7\x4b\x33\x29\x6a\x82\xff\x9a\ -\xdb\xb1\x02\xbd\xd2\x00\xa0\x61\x0f\xcc\xc7\x36\xc2\x64\x9a\x73\ -\x0d\xcf\xd5\xf8\x96\xd3\x24\x12\x49\x82\x85\x28\x8e\x06\x3e\xef\ -\x73\xb9\x9c\xd9\x32\xc0\xfc\x72\x7c\x9b\x84\xd8\x07\x51\x03\x18\ -\x81\xd2\x4e\x93\x30\x33\x40\x84\x37\x31\x72\xbb\x18\xdd\x58\xb9\ -\xca\x67\x5e\xbc\x02\xd4\x96\x40\x51\x13\xab\xc4\x74\x60\x87\xf2\ -\x23\x02\x66\x4d\x12\x17\xb1\x58\x2c\xe0\x1b\x00\xc0\x4e\xab\xc6\ -\x76\x88\x77\x33\x34\xed\x35\xbf\xfe\x6f\xed\x5d\xef\xc8\x87\xef\ -\x12\x80\xb1\x1a\x84\x24\x45\x00\xdc\xf9\x05\xf8\xd5\x68\x0c\x3d\ -\xeb\xb8\xe9\xec\x52\xd4\x04\x00\x6c\x5a\x63\xc1\xc2\xf3\xe9\xea\ -\xfb\x31\x1c\x00\x0c\x00\xfa\x0e\xd0\x72\xd7\x73\x13\x81\xd2\x8a\ -\x9a\x70\x6c\xdd\x00\x4a\x56\xd0\xa7\x0a\xb0\x6e\x45\x5d\xa9\x80\ -\xbb\xa8\x28\x57\xa4\x3d\x6b\xd4\xcb\x0a\x94\x00\x3e\xac\xbf\x11\ -\x03\x75\xed\x57\x51\xd7\x3f\x00\x0e\x75\xc4\x8a\x79\xcd\xc8\x9f\ -\x9c\x79\x49\xad\x55\x80\x20\x8c\x8e\x98\x03\x55\x32\xc5\x8d\xd7\ -\xe4\x9f\x25\xa8\x8a\x24\x18\xaf\x6d\xdb\x33\x76\xaf\x2f\x4f\x9f\ -\xbd\xa6\xd7\x2e\x0e\x4f\x8f\x0f\x9f\x93\x53\x91\x73\x92\x28\x0c\ -\x48\xe3\x00\x64\x5f\xb6\x40\x91\x88\x92\x86\x9e\x3d\xf6\xf1\xdd\ -\x40\xf8\x02\x67\xdb\x80\xa5\xc9\x72\x5a\xc9\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\x34\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\xe6\x49\x44\x41\x54\x58\x85\xe5\ -\x96\xcb\x6e\xd3\x40\x14\x40\xcf\x0d\x2c\x80\xcf\x48\xb3\x69\x0a\ -\x8b\x24\x3b\xd6\x69\x36\x48\xb4\xb5\xc3\x4b\x42\x2d\x10\x5b\xf0\ -\x01\x48\x7c\x03\x4b\x76\x48\x24\x40\x05\xe5\xd5\x26\x1f\xd0\x76\ -\xcb\x36\x29\x8f\xda\xbc\x62\x5e\x12\xfc\x01\xb0\x69\x2e\x8b\xd4\ -\xc1\x8e\xed\xc4\x29\xd9\x20\xee\x6a\x6c\xcf\xdc\x73\xe6\xce\xe8\ -\xca\xf0\xbf\x87\xf8\x83\x4a\xd5\x3e\xa9\xaa\xb7\x81\xa3\x2a\xdc\ -\xd8\xde\xa8\xb7\xa6\x09\x2a\x57\x2d\x43\x94\x9b\xc0\x2f\x54\xaf\ -\x6d\xb5\x1a\xcf\x01\x32\xfe\x04\x55\x6d\x00\x27\x80\x9c\x28\xeb\ -\x15\xc3\x3a\x37\x2d\x78\xa5\x6a\x9f\x17\x65\x1d\xc8\x01\xc7\x11\ -\xa9\xfb\xdf\x32\x7f\xa6\xe9\x91\xc0\x9a\x8c\x0a\x8f\xa6\x21\x51\ -\xa9\xda\xe7\x55\x75\x2d\xcc\xe2\x58\x44\x40\xc9\x5c\x07\x7a\xd3\ -\x94\xa8\x18\xd6\xb9\x18\x78\x0f\xd1\xeb\xfe\xc3\x21\x7f\xe0\xb9\ -\x6d\x77\x26\x5f\x7c\x0f\x2c\xf1\xe7\x6e\x08\xc2\x52\x6e\xb6\xf8\ -\xb6\xeb\xb6\x77\x27\x86\x0b\x8f\x22\x70\x58\xd9\x6a\x36\x9e\x44\ -\x04\xf6\x25\x5e\xc7\x48\x64\x26\x95\xd8\x87\xaf\x0d\xe5\xdf\x87\ -\xd7\x1f\x06\xe7\x86\x04\x7c\x89\xec\x6c\xe1\x83\x88\x44\x24\xb2\ -\xf9\xd2\x1b\x6f\x8c\x44\xd9\xb4\xcf\xd2\xdf\xf9\x58\x78\xac\x40\ -\x5f\xa2\xf3\x2a\x4e\x42\xc0\x18\x25\x51\x36\xed\xb3\x82\x0e\xc3\ -\x35\x09\x9e\x28\xe0\x4b\xe4\xe6\x4a\x5d\x60\x31\x8d\xc4\x7c\xb5\ -\x76\x46\xe0\x71\x0c\x7c\x39\x09\x3e\x52\x00\xa0\xeb\xb4\x13\x25\ -\x66\xe6\x0a\xae\xe7\x74\x1c\x1f\x8e\xca\xc4\x70\x02\x49\x47\xc6\ -\xbc\x69\x5d\x04\x56\x09\xdf\xe8\x3d\x44\x2f\xf4\x51\x31\x70\xd5\ -\x95\xad\x56\xe3\xc1\xb8\xdc\xa9\x04\x92\x24\x04\x7a\xda\x1f\x06\ -\xc5\x52\xc3\x61\xcc\x11\x04\xc3\x73\xdb\x2f\x67\xf2\x45\x8f\xe1\ -\x3e\x11\xde\xc4\x44\xf0\x89\x04\x02\x12\xdd\x21\x89\x01\x5c\x85\ -\x4b\xdb\xcd\xf4\x70\x08\x97\x2e\x55\x28\xf2\x93\xfe\x05\x0b\x87\ -\x88\x66\x7a\xfc\x98\x34\xdf\x44\x15\x28\x9b\xb6\x29\xe8\x93\x84\ -\x75\x82\x60\xe6\x66\x8b\x4e\xd7\x6d\x3b\x53\x17\x28\x57\x2d\x43\ -\xe0\x29\x70\x38\xf0\xda\xaf\x44\xb0\x63\x9a\xd9\x7c\x69\xd7\x73\ -\xdb\x6e\x9a\xbc\xa9\x8e\x60\xff\x67\x22\x02\x17\xf4\xb2\x0a\x97\ -\x08\x1f\xc9\x21\x41\x9f\x96\x4d\xdb\x4c\x93\x7b\x6c\x05\xe6\x0d\ -\x7b\x49\xe0\x59\x1c\x7c\xb3\xd9\x58\xf5\x9c\xf6\x8b\x5c\xbe\xf0\ -\x09\x64\x81\x70\xb3\x4a\x55\x89\x91\x02\xf3\x86\xbd\x84\x68\x04\ -\x8e\xca\x95\xad\x56\x7d\xd5\x7f\xd1\x75\x3b\x49\x12\x46\x36\x5f\ -\x72\x46\x49\x24\x0a\x8c\x86\xdf\xb9\x3f\x3c\xbf\xeb\x76\x5e\xcc\ -\xcc\x96\x3e\x23\x4c\x24\x11\x2b\x50\x31\x6b\x8b\x08\xeb\x69\xe1\ -\x7e\x78\x6e\x7b\x27\x51\x62\xae\xb8\xeb\x39\x51\x89\x88\x40\xc5\ -\xac\x2d\x2a\x12\x81\xab\x50\xdb\x6e\xd6\x13\xe1\x41\x89\xec\x5c\ -\xf1\x8b\xc0\x69\x86\xef\x44\x8c\x44\x48\xa0\x5c\xb5\x16\x40\x36\ -\x62\xe1\x1b\xf5\x7b\xe3\xe0\x03\x09\x27\xbd\xc4\x40\xa0\x6c\xd4\ -\x4e\x09\xd2\xfa\x5b\x78\x50\x22\x97\x2f\x7c\x05\x89\x48\xe4\xf2\ -\x85\x9d\xae\xdb\x79\x07\x81\x3e\x90\x11\xb9\x35\x0c\x17\xd4\x3a\ -\x08\xdc\x8f\xcd\x66\xe3\xae\xa0\x16\xe1\x3e\x71\x58\x91\x5b\x03\ -\xee\x80\x86\x06\x7f\xc9\x55\x50\x6b\xb3\xd9\xb8\x7b\x50\xf8\x18\ -\x89\xbd\x88\x40\x46\xf5\x2a\xe0\x01\xdf\x51\x5d\x99\x06\x3c\x28\ -\x01\x2c\x23\x7c\x03\x3e\x4a\x8f\xab\xd3\xca\xfd\xef\xc7\x6f\xcf\ -\x0b\x86\xc1\xfd\xdf\x90\xb9\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x02\x25\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xd7\x49\x44\x41\x54\x58\x85\xed\ -\x95\x3d\x68\x13\x51\x1c\xc0\x7f\xff\x77\xfd\xc2\xc1\x28\x2d\x3a\ -\x74\x29\xda\x0e\xea\x10\xb1\x9b\xa5\x50\xc4\x24\x94\xc6\xc1\xe6\ -\x4e\xf0\x0b\xc1\x26\xd6\x2e\xdd\x9c\x83\x9b\x7b\xb7\x0c\xd2\xcd\ -\xc5\xa1\x4a\x44\xac\x8b\x07\xe9\x22\xd8\x51\x27\x3f\x26\xc7\xd2\ -\x49\x38\xcf\x7b\x7f\x87\x5c\x6c\x42\xaa\x4d\x0f\xab\x14\xee\xb7\ -\x1c\x77\xf7\xff\xf8\xbd\x7b\xef\xde\x83\x94\x94\x94\x94\xff\x8c\ -\x24\x4d\xbc\xe4\xdd\x1f\x75\x6c\xf4\x02\x34\x4b\x68\x47\x5f\x3f\ -\x7f\xfc\x35\x49\x1d\x93\x24\x29\x57\x5a\x9c\x70\x6c\xd8\x00\xcd\ -\x02\xd0\x2f\x1b\x05\x6f\x61\xfc\x9f\x08\xe4\xbc\xca\x79\x88\x1a\ -\x20\x63\x0a\x28\x00\x32\x66\x55\x1a\x85\xab\x77\xb3\x07\x2a\x50\ -\x70\xcb\xd3\x58\x7c\xe0\x04\xa0\x02\x91\x40\x04\x28\xca\x49\x6b\ -\x8c\x5f\x70\xcb\xd3\x07\x22\x90\x77\x2b\x45\xab\xac\x83\x1e\xd5\ -\xe6\xc0\x6d\xdb\x6b\x0b\xaa\x40\xc6\x2a\xeb\x97\xe7\x17\xe6\xfe\ -\xaa\x40\xae\x54\xbe\xa5\xaa\x6b\xc0\x10\xaa\x2a\x9d\xcd\x63\xc4\ -\xaa\xa2\xc0\x90\x88\x3c\xcb\xbb\x95\x9b\xbd\xd4\x76\xf6\x0a\xc8\ -\x97\xca\xcb\x40\x0d\x30\x8a\xaa\x88\xec\xd2\x3c\x56\x10\x94\xe6\ -\x9f\x65\x80\xf9\x53\x67\x26\xb7\x3e\x7d\xd8\x7c\x9b\x54\x40\x72\ -\xa5\xca\x43\xe0\x51\x7c\x6b\xa5\xb5\xe6\xfe\x8c\x8a\xc4\x3e\xc2\ -\xec\xf8\xb9\x0b\xf2\xf1\xfd\xa6\xbf\x2f\x81\x6a\xb5\x6a\x06\x46\ -\x26\x56\x80\x07\x71\xa9\xd6\x1c\xf7\x8c\xec\x5c\x66\x4e\x9f\x9d\ -\x1c\xbe\x7d\xed\xca\x2b\xdf\xf7\xbb\x6a\x74\x6d\x44\x9e\xe7\x0d\ -\x6c\xdb\xcc\x2a\x70\x3d\x0e\xd9\x77\xf3\xb6\xf2\x02\xda\x5a\x67\ -\x4f\xb6\x86\xcd\x9d\x77\xb5\x5a\xf8\x5b\x81\x62\xf1\xde\x91\x60\ -\x30\x7a\x0a\x32\x8b\x02\x46\x2c\x9a\xb4\xf9\x2f\x07\x51\x55\xd3\ -\x6c\xa4\x2f\x07\x03\xc7\xad\xd7\x6b\xdf\xba\x04\xe6\x6e\x2c\x1d\ -\xff\x1e\x84\x75\xe0\x62\xfc\xc8\xd2\xdb\x9c\xef\xed\x80\x88\xee\ -\x7c\x89\x8d\x30\xfa\x51\x7c\xb3\xb6\xba\x0d\xd0\xd7\x0a\x0a\x82\ -\xf0\xb3\x40\xa6\x2d\x2f\xd1\x36\xbd\x1b\xda\x39\x8e\xa9\x7e\xa7\ -\xef\x0b\x70\xac\xa3\x49\xe2\x53\x29\x25\x25\x25\xe5\xb0\xf3\x13\ -\x19\xff\x9a\x58\xf0\x37\x9f\x0a\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x03\xd3\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x85\x49\x44\x41\x54\x58\x85\xe5\ -\x97\x4d\x68\x9c\x55\x14\x86\x9f\xf7\x66\xd2\x1f\xa1\xb5\x95\xa2\ -\x29\x36\xb4\x06\xad\x9a\x8d\x81\xd4\x49\xb2\xf0\xa7\xa5\xb4\x54\ -\x69\x93\x9a\x18\x11\xa9\x85\xa2\xb8\x70\x27\x08\x29\x2e\xa2\x28\ -\x1a\x70\xa5\x14\x45\x11\x44\xd1\x4d\x68\x33\x69\xa2\xa9\x16\x2c\ -\xe9\x42\xda\x69\xac\xa5\x0b\x43\x41\x88\xa0\x93\x46\x11\x94\x6a\ -\xb5\x3f\xcc\x77\x5f\x17\x33\x49\x93\x4e\x92\x26\x64\xe2\xa6\x67\ -\x73\x3f\xce\x77\xbe\xf3\x3e\xf7\x7e\xf7\xe7\x5c\xb8\xd9\x4d\xf3\ -\x09\x7e\xb0\xd7\xd5\x15\x09\x2d\x96\xb7\x5a\x54\x63\xd6\x09\x02\ -\x30\x8a\xc8\x19\x1d\x57\x42\x26\xdb\xa6\x1f\xcb\x0a\xd0\x94\x71\ -\x3a\xda\x5d\xc0\xe6\x39\x26\x1d\x4a\xa4\xfd\x43\xbb\xf5\xcd\x82\ -\x00\xea\xbb\x7d\x6b\x2a\x15\xdf\x07\x3d\x5d\x74\x8d\x61\xf7\x3b\ -\x84\x23\x4a\x18\x59\x12\x19\xbb\x92\x22\x3a\x52\x25\xb1\x41\x8a\ -\xdb\x40\xcd\xc0\xfa\x62\xf6\x01\x82\xf6\x65\x9b\xf5\xdb\xbc\x01\ -\x9a\x0e\xfb\xee\x98\xb8\x0f\xb8\x1f\x18\x13\xea\x5c\xb6\x9a\x8f\ -\x07\x37\x2b\x3f\x6b\x97\x3a\x1d\xd2\x75\x3c\x25\xfb\x0d\xa0\x46\ -\xe2\xe7\x68\xed\x3a\xf5\x84\xce\xce\x19\x60\xd3\x41\xd7\x54\x04\ -\x67\x81\x35\xc0\x61\x96\xe9\xd9\xec\x63\xfa\x6b\x56\xe1\xeb\x6c\ -\xc7\x80\x97\xfe\x71\x39\xbe\x07\xda\x87\xf9\x27\x58\x0f\x9d\x68\ -\xd3\x99\x1b\x02\x34\x0c\x78\x25\x97\x7d\x02\xa8\x05\xbf\x93\x3d\ -\x1b\x5e\xe2\x35\xc5\xf9\x88\x4f\x98\xad\x86\x5e\x3a\xb0\xdf\x04\ -\x72\x79\x2b\x7d\xba\x55\x63\x93\x43\x42\xc9\x47\x57\xe2\x01\xa0\ -\xd6\xa6\x7f\x41\xe2\x00\x92\xb3\x2d\x74\x19\x7f\x04\xac\x4b\xc9\ -\x9f\x61\x4f\xe9\xf4\x14\x80\xf4\x41\x6f\xc2\xda\x63\xf8\x3d\x49\ -\xb4\x67\x41\xe2\x93\x20\x2e\xe6\xc3\x8b\xc0\x39\x60\x4b\xc3\x21\ -\x76\xcc\x08\xa0\x0a\xbf\x05\x10\xac\xd7\x4f\xb7\xeb\xc2\x82\xc5\ -\x8b\x36\xdc\xae\xab\x42\xaf\x14\x14\xdd\x35\x79\x14\x26\x1e\xea\ -\x0f\x79\x6d\x4a\x1e\x05\xfe\xfc\x3b\xaf\xb5\xc3\xed\xba\x5a\x2e\ -\x00\xa0\x30\x1f\x32\x1e\x06\xee\x33\xaa\x1b\x5f\x15\x13\x23\x90\ -\x0a\xec\x04\x84\xfc\x65\xd9\xc5\x01\x24\xcb\xee\x03\x08\x8e\xbb\ -\xc7\xdd\xd7\x7e\x81\xe3\xa3\x85\x26\x7c\x55\x76\xf1\xa2\x45\x85\ -\xaf\x01\x2c\x6d\x29\x05\x40\xd5\x85\x86\x9f\x16\x0b\x20\x88\x11\ -\x00\xcc\xba\x69\x00\x0a\xce\x20\xc6\x58\x24\x5b\xbd\xb4\x98\x5b\ -\xdc\x39\x3e\x11\x4b\xf7\x81\xff\xcb\x5e\xa5\x04\x60\x14\xc0\x91\ -\xaa\xc5\xd2\xbc\x70\x69\x22\xf7\xf9\xf1\x3d\x66\x12\x80\x7f\x01\ -\x70\xe0\xae\xc5\x02\x48\xa0\xa6\xf8\x98\x1b\xf7\x4d\x00\xd8\x61\ -\x10\x20\x38\x6e\x5f\x2c\x00\x14\xb7\x15\xd5\x8e\x95\x00\x54\xa6\ -\xe8\x07\x30\x7a\xbc\xfe\x03\x57\x96\x5d\xdc\x16\x68\x17\x40\x54\ -\xc8\x94\x00\x7c\xdb\xac\xf3\xc0\x31\x60\x4d\xe5\xed\x3c\x57\x6e\ -\xfd\xc6\x1e\x76\x02\xb5\xc0\x0f\x43\x2d\x4c\xd4\x06\x53\x56\x41\ -\xb4\x3a\x0a\xb0\xee\x6c\x18\xf0\xca\x72\x89\xd7\x76\x7b\x89\x55\ -\x38\x67\x14\xb4\x1f\xc9\xd3\x02\x0c\xb5\x6a\xc8\xf8\x73\xe0\x0e\ -\x2e\xfb\x53\x3a\xbd\xf0\x65\x6a\x6b\x45\x2a\xbe\x4b\xa1\xf7\x83\ -\x27\x9b\xf9\x62\xf2\xeb\x12\x81\xe4\xda\xd1\xd9\x9c\x7e\x20\xbe\ -\xbd\x20\x08\x5b\xe9\x5e\x5e\x06\xbd\x00\x9c\x4f\x55\xe8\x99\xc9\ -\xbd\x87\x19\x4a\xb2\x62\x3d\x98\x05\x6e\x03\x7a\x96\xe7\xb5\x77\ -\xb0\x5d\x17\xe7\xa3\x5d\xdb\xed\x25\x2b\x52\xf1\x00\xe8\x79\xe0\ -\x5f\x47\x3d\x72\xaa\x4d\xdf\x5d\x1f\x37\x63\x51\x9a\xee\xf1\x46\ -\xe1\x3e\xe0\x5e\x60\xd4\x52\xe7\x2d\xab\xf8\x64\x2e\x45\x69\x63\ -\x1d\x6d\x2e\x14\xa5\xf7\x00\x39\x59\xcd\x27\x5b\xf5\xfd\x74\xe1\ -\xb3\x96\xe5\x75\x19\xaf\x5a\xea\xf8\x21\xe8\xc9\xa2\x2b\x67\xbb\ -\x3f\x54\x84\x23\x49\x9e\x91\x54\x64\xec\x52\x25\x71\x79\x42\x55\ -\x02\xeb\x43\x88\xdb\x5d\x28\xcb\xc7\x37\x9c\xa3\x31\xaf\xbd\x43\ -\xed\xfa\x75\x26\x8d\x39\x5d\x4c\xd2\x3d\x6e\x12\xee\x02\x1e\x9e\ -\x4b\xbc\xc5\x19\xa1\x8e\xec\x6e\x1d\xbd\x51\xec\xbc\xae\x66\x8d\ -\x19\x6f\x70\xa4\x05\x79\x2b\x50\x4d\xe1\x04\xad\x00\x72\x88\x1c\ -\xe8\x78\x48\xc8\x9c\x68\xd3\xb9\xf9\xe4\xbd\xb9\xed\x3f\x89\x47\ -\x63\xa6\x91\x26\x12\xd0\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ -\x60\x82\ -\x00\x00\x00\xf0\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xa2\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\x41\x11\x00\x20\x00\xc3\x30\x0e\x6f\x28\xc0\x02\xfe\x2d\x80\ -\x8c\xf0\x68\x0c\xac\xb7\x31\xa0\xb5\xcf\x5d\xfb\x5c\xd9\x30\xe5\ -\xf8\x0f\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\ -\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\ -\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\ -\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\xd0\ -\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\xad\ -\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\xd0\x3a\ -\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\xad\x03\ -\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x3d\x9d\xfa\x04\x75\x0c\ -\x2b\x93\xd0\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x68\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x1a\x49\x44\x41\x54\x58\x85\xed\ -\xc1\x01\x01\x00\x00\x00\x82\x20\xff\xaf\x6e\x48\x40\x01\x00\x00\ -\x00\xef\x06\x10\x20\x00\x01\x47\x01\xa0\x88\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\xe8\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x9a\x49\x44\x41\x54\x58\x85\xc5\ -\x97\xd9\x76\xe2\x46\x10\x86\xbf\x66\x11\x12\x60\x50\x9c\xc4\x9e\ -\xf1\x24\x39\x59\xde\xff\x9d\x72\x31\x9e\x49\x1c\xcf\x18\x6c\x23\ -\x19\x24\xa8\x5c\xd4\xdf\xa8\x91\x71\x72\x97\xd4\x39\x1c\x89\x56\ -\xd7\xf6\xd7\xd6\x0d\x58\x09\x16\xf8\xcf\xc9\x02\x58\x19\xa4\x7c\ -\x09\xac\x21\x58\xf7\x91\x4b\x20\x1a\x96\x25\xef\x93\x44\x4a\x5c\ -\xb3\x64\x6d\x9b\xac\xed\xf4\x7e\x00\x1e\x7a\xf2\x97\xc0\x3a\xf4\ -\x16\x0e\xc0\x05\x30\x00\xaa\x44\x59\x90\x11\x13\xd8\x0d\x21\x8c\ -\x81\x71\xcf\xa5\x16\xac\x81\xac\x95\x11\x51\xb9\x01\x0d\x90\x4b\ -\xfe\x23\x30\x3c\x75\xd8\xf7\x2d\xc0\x7e\x11\x34\x63\xb0\x99\xd6\ -\x33\xb0\xf7\xf0\x50\x82\xe5\x60\x13\xb0\x82\x57\x64\x85\xbe\x4d\ -\xb5\xf7\xca\x79\xc1\xd7\x2c\x93\xec\x5f\xc1\x2e\xfa\x10\x02\xf6\ -\x01\xf8\x24\x24\x0c\x78\x01\x0a\xd8\xbd\x87\xec\xa3\xbc\x00\x58\ -\xc8\x8b\x73\x94\x7e\x9b\xc0\xee\x06\xb2\x5b\x21\x92\x4b\xdf\x1a\ -\xb8\x81\x70\x0b\x30\x92\xf2\x80\xc3\x3e\x96\xf2\x1b\xe0\xde\x19\ -\xb2\xfb\x44\xf9\x04\x0f\x91\x71\x1a\xf7\xe8\xcc\x4c\xca\xf4\xcb\ -\xbe\xc2\xa6\x80\xd9\x18\x78\x07\x7c\x94\x8e\x41\x0f\x01\xfb\x4e\ -\xff\x2b\x08\x15\xd8\xb5\xbe\xfd\x09\xcc\x1d\x8d\xd5\x0c\x4a\x5c\ -\x70\xa8\xcf\x03\x60\x73\xa0\xc5\xf3\xa5\xd2\xf3\x80\x27\xf4\x0e\ -\x78\xc2\xe3\xff\x0d\xb0\x82\xb0\x19\x25\xdc\x63\x29\xcf\xe5\xdd\ -\x1a\xb8\x92\xc5\x39\x94\x4f\x82\x71\x02\x66\x1d\x0f\x24\x08\xe5\ -\xc0\xb3\x94\x95\x42\x38\x03\xee\xf0\xf0\x64\x10\x9e\x12\x07\x3b\ -\x28\xdc\x52\x9b\xc0\xcb\xb5\x18\x83\xa0\x5c\x48\x68\xa4\x39\x1e\ -\x86\xb9\xf8\x07\xfa\x1f\xd7\x22\x6d\xc4\xbb\x93\xac\x00\xdb\xf7\ -\x4a\xcc\x63\xee\xc5\x10\xbc\x73\x41\x15\x30\xfd\x8c\xc7\xb2\x96\ -\xf5\x23\xc1\x56\x43\x75\x09\xd3\xb5\x23\x75\x8e\x6c\x21\x99\x35\ -\x30\x95\x03\x53\xba\xd2\x1b\x49\xf6\x1c\x0f\xc1\x97\x14\x81\x09\ -\xb4\x2f\x49\x6d\x16\x8a\xb5\xe1\x96\x5d\xc3\x74\xe5\x48\xbd\x49\ -\xb1\xce\xbf\x17\x8f\x09\x89\x58\xb6\x2d\x3c\x36\x78\xe8\xfa\x21\ -\x68\x4a\x58\x3c\x74\xc6\x30\x54\x3e\xe4\x78\xd2\xfc\x25\xc1\x85\ -\xfa\x41\xee\x49\x67\xb3\xee\x3f\x05\x9e\x37\x5f\x61\x73\x29\xde\ -\x3c\x91\x09\x2c\x9e\x49\x42\x15\x0d\xc8\xbc\x8b\x91\x0b\xc6\x52\ -\x1e\xb4\x62\x5c\xe1\x89\xf6\x20\x48\x73\x3d\x83\xa0\x9d\xba\x0c\ -\xa6\xae\x9c\x06\x66\x0f\xda\xd7\xe2\x3d\xe5\x12\xef\x31\x43\x68\ -\x4c\xfb\x63\x1f\x20\x40\x50\xd7\x0a\x8f\xde\xb9\x82\x32\xdb\x0c\ -\x82\xfa\xbb\x35\x12\x36\x06\xee\x7b\xbd\xfd\xca\x8d\x8e\x7c\xb4\ -\x60\x7b\x7f\x86\x1d\xd8\x33\x5e\x86\x03\xba\x24\x3f\xa9\x82\x61\ -\x52\xdf\x49\x93\xa9\xd3\x3d\xda\xc7\xbd\x7b\x63\xe9\x30\xbb\x4b\ -\x1c\x8a\x94\x4e\x59\xc9\x0c\x55\xe7\x6c\xc7\x30\x82\xf1\x21\xf1\ -\x86\xe4\xbd\x4d\x84\x8c\x80\xc6\x3d\xb7\x35\xea\x4c\x78\x46\x5b\ -\xd2\x1f\x52\x4a\x1d\x78\x35\x3d\x07\xc9\x73\x7f\x86\xb9\x4f\x87\ -\x9e\xc0\x3e\x9d\x6b\xcf\x96\xbc\xbf\xda\x17\x85\xed\xa0\x51\x57\ -\x0b\xd6\x6d\x0e\x06\xf5\xb0\x67\xc0\x30\x81\x7d\xa5\xdf\x32\x99\ -\x27\x7d\x83\x4f\x46\x6e\xdf\x98\x94\xa1\x55\x29\xf5\xac\x2d\xfa\ -\x75\xdf\xe2\x09\xa7\x79\x1e\x62\xdb\xbe\xa6\x3b\x03\x44\x0a\xaf\ -\xdf\xad\x00\x3b\xee\x8b\x39\x60\xca\x70\x53\x19\xce\x34\x58\xc0\ -\x4b\xb3\x94\xe2\x02\x6f\xb9\x6a\x36\x96\x42\xdc\x00\xdf\x4a\xb8\ -\x49\xb6\x0e\x21\x16\x3b\x20\x32\x76\x1f\xf9\xa2\x01\x3b\x08\x43\ -\x95\xdb\xd6\x0f\x24\x34\xfe\xdf\xc0\x33\x7f\x23\x21\x9f\xff\x61\ -\x1a\xee\x38\x9e\x76\xd6\x25\x2c\xef\x3a\x07\x79\xc0\x4b\x38\xee\ -\xd9\xc1\x49\x08\xc6\x75\xe2\xf5\x16\x35\x0a\x51\x05\x2f\x3f\xc9\ -\xf3\x73\x99\x7e\xb4\x40\x1e\x7e\x80\xe5\x53\xb7\xbc\x2a\xa4\x1c\ -\x37\x6c\xbc\x89\x5f\x06\x09\xe3\x06\xea\xb2\x63\xa2\xf6\x86\x14\ -\x0f\x1a\xf9\x2d\x3e\xdd\xfa\x67\xc1\x94\x22\xd4\x7f\xe0\xed\x36\ -\xf8\xb3\x4c\x86\x57\x36\x93\x31\x27\x21\xd8\xfb\xe6\xe2\x19\xec\ -\x86\x6e\xe0\x14\xf8\x49\xe6\x77\x3c\x9e\x7b\xa0\x74\xa4\xea\x41\ -\x97\xa0\xf5\x50\x02\xd5\x21\x8f\x7b\x7f\xc6\xbb\x9f\x8e\x77\x2c\ -\xa1\xb8\x95\xcc\x6d\x6a\x00\x6e\x40\x78\x06\x1b\xd0\xc5\x7c\x24\ -\x6f\x0e\x10\x36\x60\x2d\xf0\x0c\xe1\xe5\x3c\x00\x36\x77\x19\xa0\ -\x83\xeb\x67\x7c\x96\x6c\x24\x73\xe5\xf9\xd3\x45\x31\x0d\x41\xe3\ -\x93\x2d\x3c\x42\x7d\xe1\x9e\xb2\x96\xf5\x5b\xe5\xc7\x71\x8c\xbe\ -\x4d\x36\x56\xe8\x1a\x3c\xd1\xd6\xc0\x25\x54\x33\x47\xc3\x66\x5a\ -\x3f\x09\xc1\x57\xe0\x07\xdf\x6c\x4b\x60\x06\x2f\x41\x93\x74\x42\ -\x67\xb2\x0e\x97\x55\x05\x85\xd1\x75\xcf\xd8\xac\x0a\x3c\xdb\x77\ -\x38\xf3\xc2\x8d\xaf\xa7\x30\x9d\xe3\x13\x76\xe3\x8e\x87\x4d\x62\ -\x40\x30\xb0\x03\x5e\xeb\x01\xf8\x04\x45\x34\x86\x0e\x56\xf0\x30\ -\x4c\x75\xf4\x36\x21\x18\xe2\x1c\x59\x38\x82\xc7\xbd\x17\x6e\xcc\ -\xf4\x8b\x64\xc5\xd9\x72\xee\x50\x63\x17\xba\x34\xf4\x2f\x26\x0b\ -\xa8\x7e\xec\x2e\x23\xff\x76\x31\x01\xe7\xad\x3e\x74\x65\x7d\x72\ -\x31\xf9\xed\xcc\xc5\xe4\xd8\xdb\xf7\x82\x6d\x20\x2b\x33\x1c\xfe\ -\x81\x7f\x6f\x32\x79\x30\x84\x71\x7a\xf7\xcb\x75\x30\x6e\x7d\xd4\ -\x8e\x6a\xbc\x67\xec\xc5\xdb\xd0\x0d\xa6\x35\xc9\xd5\xec\x8d\xcb\ -\x69\xf4\xe2\x98\x70\xc3\xe4\x7d\xa2\xf7\x09\x6c\x35\x3b\x26\x95\ -\x94\x18\xdd\xe5\x54\x06\xb9\xb0\x18\xf3\x9e\xc3\x6b\xf8\x9f\xaf\ -\xe7\x7f\x03\x88\x7c\xd3\x3b\xed\x32\x4f\xdf\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x8f\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x41\x49\x44\x41\x54\x58\x85\xed\ -\xd3\xa1\x11\xc0\x20\x14\x04\xd1\x85\x9a\x28\x00\x93\x5a\x70\x14\ -\x83\x4a\x31\x99\xa1\x81\x14\x85\xc2\x22\xf9\x66\x9f\x3a\xb7\xea\ -\x40\x92\x14\x2c\xed\x51\xda\x98\x40\xbd\x54\xfd\xfe\xb7\x3f\x00\ -\xf9\x4a\x50\x3a\xf0\x05\x92\x24\x85\x5b\x1c\x18\x0a\x07\xd4\x09\ -\xe9\x09\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xd2\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x84\x49\x44\x41\x54\x58\x85\xed\ -\xd2\xb1\x0d\x82\x50\x18\xc4\xf1\xff\xf7\xdc\x81\xc4\x3d\x18\x80\ -\x4d\x2c\x6c\xe8\x1c\x41\x98\x81\x06\x13\x6b\x67\xb0\xb4\x77\x10\ -\x13\x76\xd0\xb3\x52\x21\x24\x76\x0f\x9a\xfb\x75\x97\xf7\x25\x77\ -\xc5\x03\x33\x33\xb3\x95\xc5\x34\x2a\xaa\x63\xb3\xc9\x59\x78\x6b\ -\x9b\x27\x84\x66\x03\xca\xba\xab\x90\x2e\xc0\x36\xe7\x80\x80\x01\ -\xb4\xbb\x9f\x0e\x57\x80\xf4\x7d\x91\xfa\xdc\xe5\x00\x82\xe2\x45\ -\x3a\x7f\x72\xfa\x77\xbc\x84\xdf\x80\x88\x1a\x78\xe4\x2e\x0c\x18\ -\x14\xec\x47\x79\x6c\xf9\x4f\x68\x66\x66\xb6\xba\x37\x95\x79\x1e\ -\x09\xc0\xb2\x67\x2f\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ -\x82\ -\x00\x00\x00\x85\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x37\x49\x44\x41\x54\x58\x85\xed\ -\xce\xc1\x0d\x00\x30\x08\x03\x31\xd4\xfd\x87\x04\x31\x08\x1d\x02\ -\x9e\xbe\x7f\x22\x47\x2c\xca\xea\xc9\xea\xd9\x7c\xbc\xcd\xf8\x22\ -\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x0f\ -\x7e\x19\x07\x85\xa1\xbf\xac\xe9\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x01\xd2\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x84\x49\x44\x41\x54\x58\x85\xed\ -\x97\xcd\x4a\x23\x41\x14\x85\xbf\xd3\xba\xd5\x85\x32\xfa\x26\xe9\ -\x0c\x8a\x2f\x90\x61\x04\x03\x3e\x84\x60\x56\x62\xe6\x11\x26\x82\ -\x0b\x23\xb8\x1f\xdc\x0d\xd8\xe0\x22\x2f\x30\x20\xa6\x7d\x13\x15\ -\x07\x24\x6b\xfb\xcc\xc2\xae\x20\x49\x6c\x31\x76\x74\xc0\x3e\xab\ -\xe2\xd6\xa5\xce\x57\x3f\x14\xf7\xc2\x67\x97\x46\x03\xf5\x33\xaf\ -\x65\xb8\x8d\xa8\x0b\xbe\x94\x61\x62\xb8\xc5\xf4\x23\xd4\xe9\x37\ -\x75\xf1\x2c\x40\x9c\x78\x0f\x7c\x30\x09\xac\x24\x65\x58\xfb\x69\ -\x53\x87\x63\x00\x71\xe2\x75\xf0\x1f\xe0\x1e\xab\x15\x3d\xd0\xbb\ -\xdc\xd6\xdf\x32\x5c\xbf\xfe\xf6\x52\x36\x47\x03\xb9\x0b\x2c\xca\ -\xda\x08\x27\x31\x1f\x92\x6c\xef\x4b\x08\xab\x95\x36\x75\x5a\x86\ -\x71\x50\xbe\x91\xd3\x5a\x62\x09\xff\xca\x70\x1b\xf8\x0e\x10\x0d\ -\xb3\x44\x1d\x20\x7a\xa0\x57\xa6\xf9\x88\x7a\x00\x12\x71\x08\x0c\ -\x01\xc2\x83\x2b\xeb\xd8\x27\xe9\x6a\x4b\x77\xf9\x70\x65\x0c\xe0\ -\xa3\x54\x01\x54\x00\x1f\x0e\x30\xff\x52\x42\x7c\xe6\x1d\xe4\x9f\ -\xc0\xc2\x2b\xd7\x1e\x60\xfd\x48\x9b\x3a\x29\x4a\x2a\x3c\x81\xf8\ -\xdc\xab\xc8\xc7\x53\x98\x03\x2c\x20\x77\xe3\x73\xaf\x4e\x0d\xf0\ -\x1e\x2a\x04\x48\x37\x75\x8d\xb5\x0b\x0c\xa6\x58\x7b\x80\xd5\x4a\ -\x37\x75\x5d\x94\xf4\xe2\x1b\xc8\xef\xb0\xf0\x1e\xdf\xa2\xff\xfb\ -\x0a\x2a\x80\x0a\xe0\x5d\x01\x0c\xb7\xf0\x58\x40\xce\xca\xac\x96\ -\x78\x39\x1f\xde\x8c\x01\x60\xfa\x00\xd9\x1c\x8d\x59\x01\xc0\xe3\ -\xda\x36\x69\x08\x0c\x3f\xa2\x08\x75\x8c\xbf\x21\x77\x6b\x89\x05\ -\xf4\x9e\xd4\x70\x6f\x52\xbe\xf3\x86\xf0\x11\x90\x45\xa8\x13\xe6\ -\x26\x35\x26\x1d\x66\xf7\x36\x9e\x6f\x4c\x82\x42\x6b\x96\x97\xce\ -\x2b\xa3\xf3\x53\xea\xc6\x26\x9d\xd4\x9a\x55\xfa\x07\xf1\xe4\x84\ -\x86\xea\x09\x57\xf9\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ -\x82\ -\x00\x00\x04\x8a\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x3c\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4f\x88\x1c\x45\x14\xc6\xbf\xd7\x33\x99\xc4\x3f\x2b\x62\x16\ -\x15\x24\x78\x11\xff\x5c\x04\x77\x3b\x7a\xf0\xe0\x22\x26\x12\xc1\ -\x3f\x2c\x22\x1e\x04\x35\x9a\x99\xd9\x24\x33\xbb\x11\x09\x28\xea\ -\xb8\x98\x80\x41\x31\x6e\x8f\xba\x99\x4e\xc4\x1c\x44\xd1\x53\x0c\ -\x62\x64\x83\xb0\x90\x83\x91\xd9\x59\x30\x20\x82\x78\x10\x11\x49\ -\x84\x28\xea\x06\x75\x37\x5d\x9f\x87\x5d\x35\xe9\xea\x68\x26\xa9\ -\xaa\x2e\x70\x7e\xc7\x3a\xd4\xf7\xea\xab\x57\xaf\x5f\x75\xcf\x00\ -\x3d\x7a\xf4\xf8\x3f\x23\xa6\x26\x0a\xcb\x13\xcf\x43\xe4\x19\x01\ -\x48\xca\xb6\x99\xb8\x36\x6e\x6a\x6e\x9b\x04\xc6\x66\x12\x79\x16\ -\x40\x81\x40\x11\x82\x46\x58\x6d\x0e\x19\x9b\xdb\x22\xe6\x0c\x38\ -\x6d\x2e\x0a\xc8\xfd\x03\x23\x13\x83\x06\xe7\xb7\x82\x31\x03\x08\ -\xa8\xd4\x50\x5f\xa0\xe4\xe3\x70\xe4\xd5\xeb\x4c\x69\xd8\xc0\x98\ -\x01\x02\x30\x63\xb8\x1f\x2a\x38\xb8\x7a\xe3\xeb\xab\x4c\xe9\x98\ -\xc6\xe4\x11\x38\x13\xab\x98\x24\x53\x83\xe5\x97\xfb\x1d\x68\x75\ -\x8d\x0b\x03\x00\xe0\x7a\x91\xd2\x81\x5b\xd7\xef\xe8\x73\xa4\x77\ -\xd6\x58\x33\x80\xd4\x8e\x44\x38\xbf\xec\x82\x7d\xd7\xd4\xa2\xe5\ -\xb6\x34\xcf\x05\x6b\x06\x88\x40\x21\x55\x17\x08\xdc\x7e\xe9\x3c\ -\xde\x19\x6a\x34\x8a\xb6\x74\xbb\xc5\xf6\x11\x50\x80\xa4\x33\x61\ -\x78\xee\xe8\x65\xbb\x00\x1a\x6b\xc2\xce\x07\x07\x35\x80\x0a\x4c\ -\x9b\x20\x8f\x85\xe5\xe8\x45\xfb\xda\xff\x8d\x9b\x22\x28\x4c\xf7\ -\x08\x80\xc8\xd6\xb0\xda\xdc\xea\x44\xff\x5f\x70\xf5\x14\x00\x80\ -\x44\x1b\x21\x77\x0c\x96\x27\x1e\x77\x18\x83\x86\x4b\x03\xb2\xba\ -\x45\x88\x48\x6b\x75\x25\x1a\x76\x19\xc7\xa9\x38\x35\x60\xa9\x5b\ -\x4c\x9b\x10\x10\x78\x37\xdc\x10\xdd\xe1\x32\x96\xbf\xc5\x73\xd0\ -\x24\xa0\xd5\x84\x12\x02\xec\x0b\xab\xd1\xcd\xae\x83\xc9\xc3\x00\ -\x00\x42\xea\x85\xf1\x22\x10\x1f\x0d\x6c\xdc\x79\x83\xcb\x48\x72\ -\x32\x00\x10\x0a\x33\x6a\xc2\x4a\x49\x8a\x07\x6f\xda\xf4\xda\xd5\ -\xae\xe2\xc8\xcd\x00\x60\xb1\x26\xa4\x4d\x10\xf0\xaa\xc2\x49\x35\ -\x75\x63\x75\xf2\x72\x17\x31\xe4\x6a\x00\xb0\x64\x82\x7e\x6f\xb8\ -\xb6\xc4\x85\x03\xb7\xd4\xa2\x4b\x6c\xeb\xe7\x6e\x00\xb0\x78\x6f\ -\xa0\xfe\x3e\x61\x20\x59\xc0\xfe\xa1\x47\xde\x5a\x61\x53\xdb\x0b\ -\x03\x00\x40\x00\x85\x74\x26\x10\xb7\xcd\x95\x7e\x7d\xcf\xe6\xe5\ -\xc9\x1b\x03\x00\x00\x92\x61\x82\xe0\x9e\x13\xc7\xfa\xf7\xa0\xd1\ -\xb0\x12\xab\x5f\x06\x00\x80\x88\x62\xea\x06\x49\xf2\xe1\xf0\xe8\ -\xca\x97\x6c\xdc\x20\xfd\x33\x00\x84\x80\x0a\xd4\x5e\x31\x3e\x11\ -\x96\x9b\x4f\x99\x56\xf3\xd0\x80\x45\x44\x24\xd1\xca\xa2\x60\x7b\ -\x58\x8d\x2a\x26\x75\xbc\x35\x80\x00\x32\xba\x45\x80\x98\x0c\x2b\ -\xd1\xfd\xa6\x74\xbc\x35\x00\x00\x24\xbb\x65\x16\x00\x4d\x53\x1a\ -\x5e\x1b\x00\xe0\x4c\x75\xcf\xd8\x63\xd1\x9b\x97\x93\x59\x2c\x2d\ -\x3d\x6b\x93\xde\x34\xa5\xe1\xaf\x01\x02\x28\xa2\x90\xde\x7f\x81\ -\x6c\x6a\xb7\x6a\x6f\x98\x92\xf1\xd4\x00\x01\x49\x6d\xf1\xa4\x3c\ -\x37\x13\x9b\x5b\x3c\xe0\x6f\x0d\x08\xb4\x9d\x17\x44\x9d\x78\xf3\ -\x36\xd3\x42\x1e\x66\x80\x04\x7a\xe5\xe3\xdb\xed\x2b\x7e\xdc\x92\ -\xf1\x8d\xe1\xbc\xf1\x2b\x03\x08\x6d\xf1\x02\x7e\x48\xae\x58\x8f\ -\xf1\x71\xbd\x27\x30\x80\x47\x06\x48\x00\x41\x6a\xf1\x38\x54\xbc\ -\x30\x79\xa0\x13\x57\x16\x6c\xa9\xfa\x71\x04\x88\x00\x72\xfa\xce\ -\x13\xf8\x9c\x5c\x7e\xf7\xa7\x3b\xeb\xbf\xd9\x94\xf6\x21\x03\x24\ -\xbd\xf3\x20\xbe\x2e\x26\xea\xce\x4e\x5c\xf9\xd9\xb6\x78\xae\x06\ -\x70\xb1\xd7\x09\x52\x83\xdf\x17\x83\x64\xcd\x67\x7b\xc6\x8e\xb9\ -\x88\x21\xcf\x23\x20\xa2\x6f\xc0\x4f\xc2\x60\xed\xe1\x5d\xf5\x6f\ -\x5c\x05\x91\x4b\x06\x50\x32\x76\x1e\x38\xa1\x02\xdc\xd5\xde\xbd\ -\xf9\x0b\x97\xb1\xe4\x61\x80\x08\x35\xdd\x05\x12\xc3\xb3\x93\xf5\ -\xc3\xae\x83\x71\xfc\x71\x94\x59\x3b\x4f\x11\x3e\xd4\x89\xeb\x53\ -\x2e\x63\xf9\x0b\xa7\x35\x40\x20\xba\xe1\x64\xb5\xdd\x1a\x7d\xdf\ -\x65\x1c\xa7\xe2\x32\x03\x0a\xe9\x01\x01\x9f\x9e\x89\x47\x63\x87\ -\x31\x68\x38\x31\x80\x59\x3b\x0f\xbc\xd2\x6e\xd5\x73\xff\x99\x8c\ -\x83\x23\x20\x81\x40\xeb\xf2\xf6\x76\x5a\xb5\x27\x6d\x5c\x6e\xba\ -\xc5\x76\x06\x64\xdc\xec\xf0\x41\xdf\x95\xc7\x37\xf8\xb0\x78\xc0\ -\x62\x06\x90\x08\x24\xdd\xe2\x02\xd3\x17\xff\xd1\xf7\xe0\xf4\x78\ -\xfd\xa4\x2d\xdd\x6e\xb1\xf9\x43\xc9\xf4\xe2\x67\x0b\x25\xdc\x3b\ -\xbd\xf7\xd1\xdf\x6d\x69\x9e\x0b\xae\x1e\x83\x5f\xcd\xcb\xb2\x75\ -\x47\x9a\x23\xbf\x38\xd2\x3b\x6b\x5c\x18\xf0\x1d\xa9\xd6\x1c\x69\ -\x8d\xfc\xe0\x40\xab\x6b\x4c\xfe\x61\x22\xeb\x05\xfe\x71\x55\x48\ -\xd6\x76\xe2\xb1\x6f\x4d\xe9\x98\xc6\x58\x06\x64\xdc\xec\xe6\x44\ -\xa9\x75\xb3\xad\x2d\x5f\x9a\xd2\xb0\x81\xc1\x0c\xf8\xe7\x13\x16\ -\x21\x14\xf0\xbe\xf6\xee\xb1\xb6\xa9\xf9\x6d\x61\xf0\x5f\x63\xc1\ -\x76\x21\x12\x40\x12\x80\x2f\xb4\x5b\xa3\x9f\x18\x9b\xbb\x47\x8f\ -\x1e\x3d\x2c\xf1\x27\x17\xaf\x43\xaf\x5e\x06\xce\xc3\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x08\xd7\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x08\x89\x49\x44\x41\x54\x78\x9c\xed\ -\x5b\x6d\x70\x54\xd5\x19\x7e\xde\x73\x77\x37\xb0\x24\x7c\x64\x11\ -\x13\xd4\xd1\xa0\x65\x30\x54\x66\x60\xb3\x50\xd4\x46\xb0\x76\xa4\ -\x1d\xc1\x62\xbb\x56\xed\xa8\x80\x24\x21\x40\x56\x60\xac\x1d\x9c\ -\xd1\x4b\x5a\xa9\xf5\x2b\x26\xbb\x60\x08\x04\x0a\x2a\xd3\x19\xd3\ -\x11\xa6\x38\x80\x4c\x6b\xc3\x50\x0b\x21\x1b\xed\x50\x05\x3a\x7e\ -\x80\x94\x49\x88\x95\xcf\x60\x24\xd9\xdd\xf3\xf6\x47\x10\xee\xc7\ -\xee\x66\x6f\x72\x37\x86\x36\xcf\xbf\xfb\x9c\xe7\xbc\xfb\xdc\x77\ -\xcf\x3d\x7b\xee\x39\xef\x02\x03\x18\xc0\x00\xfe\x9f\x41\x7d\xf1\ -\x21\x13\xe7\x06\xaf\x52\x32\xa8\x10\x90\xb7\x80\x69\x1c\x08\x63\ -\x98\x31\x9c\x80\xa1\x00\x14\x80\xce\x01\x38\x07\xe6\x63\x20\x1c\ -\x02\x70\x50\xc4\x68\xcf\xfe\xda\xb2\x23\xe9\xf6\x96\xb6\x04\x78\ -\x8b\x83\x37\x0a\xc2\x1c\x66\xcc\x02\x61\x42\x0f\xc3\x1c\x61\xf0\ -\x0e\x21\x79\x63\xe3\xba\xc7\xc3\x00\xb1\xad\x26\x61\x7b\x02\x98\ -\x7c\x25\xc1\xbb\x19\xf4\x24\x80\xe9\xf6\xc6\xc6\x87\x04\xaa\x90\ -\xec\x7a\xa3\x69\x6d\x49\xc4\xae\xa0\xb6\x25\xc0\x5b\x5c\x35\x9d\ -\x88\x5e\x00\x50\x60\x57\xcc\x78\x60\xe0\x28\x98\x57\x34\xad\x0d\ -\xbc\x66\xc7\x88\xe8\x75\x02\xa6\xcc\xaf\xbc\x3a\xaa\x88\x97\x09\ -\xf8\x45\x12\x99\x24\xe0\x3d\x10\xd7\x4b\x29\x0e\x03\xb1\x4f\x1d\ -\x44\xa7\xa4\xe2\x68\x8b\x7e\x1d\x8b\x29\x83\xa2\x59\x60\xc7\x30\ -\x62\xe4\x49\xa6\xb1\x04\x9e\x0a\xc2\x0f\x01\x0c\x4e\x62\x7c\x0f\ -\xa4\x28\x6d\x5c\xb7\xf8\xa3\xde\xf8\xef\x55\x02\x0a\x16\x04\x27\ -\x83\xb1\x15\x40\x6e\x9c\xe6\x36\x00\xdb\x89\xb0\x8d\x14\xb1\x73\ -\xff\xea\xc5\x27\xad\xc4\x9e\xba\xb4\x62\x70\xe7\x57\x8e\x3b\x09\ -\x98\x09\xc2\xac\x04\x9f\x71\x01\xc0\xbc\x70\x4d\xe0\x0f\xd6\xdd\ -\x77\xa1\xc7\x09\xf0\x16\x87\x1e\x22\xe2\x0d\x00\x32\x4c\xa6\x98\ -\x83\x1d\x8a\xf3\x77\xff\xac\x5e\x78\xba\xa7\xf1\xb5\xc8\xf7\xab\ -\x2e\xf7\x88\xec\x22\x22\x7a\x86\x81\x51\x26\x01\xd3\xca\x70\xee\ -\x97\xcf\xa0\xbc\x5c\x5a\x8d\x6d\x3d\x01\xaa\x2a\xbc\x27\x46\x3e\ -\x4b\xe0\xe5\x86\x16\x49\x84\x0d\x22\x8a\xf2\x86\xda\xc0\x71\xcb\ -\x71\x53\xc0\x6d\xf3\x9e\xcf\xea\x70\xb8\x97\x81\xf8\x09\x00\x99\ -\x86\xe6\xad\xed\x8a\xf2\xf0\xc1\x57\x17\x9d\xb7\x12\xd3\x5a\x02\ -\x54\x55\x14\xb4\x8c\xdc\x0c\xe2\x07\x74\x3c\xa3\x19\x02\xb3\xc3\ -\x6b\x02\xfb\x2d\xc5\xeb\x21\xa6\xcc\x0f\x5e\x1b\x53\xb0\x05\xe6\ -\x09\xf7\x03\xc5\x85\x69\x0d\xa1\xc0\xb9\x54\x63\x09\x2b\x1f\xec\ -\x6b\xcd\x5e\x61\xbc\x79\x02\xf6\x31\x62\x05\x7d\x75\xf3\x00\xd0\ -\x50\x1b\x38\xee\x74\x47\x0b\x19\xd8\x6c\x68\x9a\x28\x3b\x79\xb3\ -\xdf\xff\xa6\x92\x6a\xac\x94\x85\xbe\x92\xd0\xcf\x19\x08\x69\x39\ -\x22\xda\x34\xa4\x23\xcb\xbf\x77\x7d\xe9\x99\x54\xe3\xd8\x85\xe3\ -\xfb\xde\x89\xb6\x34\x6d\xdf\x32\xda\xd7\xd8\x0e\xe0\x2e\x5c\x1a\ -\xcd\x34\xf6\xcc\xa0\xb6\x41\xcd\x4d\x3b\xff\x9c\x4a\x9c\x94\x1e\ -\x81\xc9\x25\xa1\x02\x09\xde\x03\x60\xd0\x65\x96\xdf\x08\xd7\x04\ -\x1e\x49\xc7\xea\xcc\x2a\x0a\x8a\x83\x4b\x40\x78\xc5\x40\x3f\x1a\ -\xae\x09\xbc\xd6\x5d\xdf\x6e\x1f\x81\xc9\x8b\x56\x79\x62\xc0\x56\ -\xe8\x6e\x1e\xfb\x33\x3b\x86\x16\xf5\x87\x9b\x07\x80\xf0\xda\xb2\ -\x2a\x80\x7f\x6f\xa0\xd7\x79\x8b\x57\x4d\xea\xae\x6f\xb7\x09\x90\ -\x11\xf9\x02\x81\xaf\xb9\x44\x30\x9a\x63\x4e\x9a\x5d\xbf\x71\xee\ -\x05\xeb\x56\xd3\x05\xe2\x33\x2e\x2a\x05\xe1\xef\x1a\xd2\x45\x24\ -\xd7\x4d\x53\x55\x47\xb2\x9e\x49\x13\xe0\x2d\xae\xbc\x1d\x84\x79\ -\x1a\x8a\xa5\x82\x9f\x7e\xb0\xaa\xac\xb9\x37\x76\xd3\x81\x4f\x42\ -\x81\x0e\x25\x2a\xef\x03\xf0\xa5\x86\x9e\xd4\xd6\xe2\x59\x98\xac\ -\x5f\x92\x04\x30\x11\x89\xe7\x0c\xdc\xe6\xf7\xab\x03\xfb\x7a\x6e\ -\x33\xbd\x68\xa8\x5d\xd2\x0a\xc6\x4a\x2d\x47\x84\xa7\x27\x3c\xfc\ -\xe2\x90\x44\x7d\x12\x26\xc0\x57\x14\x2a\x04\x70\xbb\x86\x8a\x40\ -\xc4\xd4\xde\xdb\x4c\x2f\x32\x3b\xb3\xd6\x00\x38\xa6\xa1\x46\x3a\ -\xdd\xae\x92\x44\xfa\x84\x09\x60\x81\x5f\xea\x09\xd4\x84\xab\x97\ -\x7d\xd6\x6b\x87\x69\x46\xfd\xc6\xb9\x17\x88\x60\xf8\xa2\xc4\xb2\ -\x44\x6b\x83\xb8\x09\xf0\x2d\x5c\x9d\x03\x60\x86\x86\x8a\x28\x52\ -\x3e\x6b\x97\xc9\x74\xe3\x86\x93\x39\xaf\x33\xf0\xf1\x37\xd7\x04\ -\xbe\xe6\x53\x4f\xeb\x5d\xf1\xb4\x71\x13\x20\x63\xd1\x87\xa0\x59\ -\x24\x11\xf0\x6e\x43\xed\x92\x56\xdb\x9d\xa6\x09\x75\x75\xf7\xc7\ -\x88\x50\xa7\xe5\x04\xf3\xa3\xf1\xb4\x71\x13\x40\xa0\x99\x06\xe6\ -\x4f\x76\x99\xeb\x2b\xb0\x94\x46\xcf\x3f\x8e\xf7\x18\x98\x12\x70\ -\x71\xc6\xbc\x55\xcb\x49\x8e\xbd\x6d\xaf\xbd\xf4\xa3\x29\xf7\x74\ -\x23\x00\xed\xa8\x1d\x76\xc4\x73\xc2\x6b\xd4\x99\x12\x90\xe1\x76\ -\x7d\x0f\x80\xeb\x32\x43\xff\x68\x5a\xbb\xe4\x98\x51\xd7\xef\x51\ -\x5e\x2e\x01\xd6\x7d\x71\xcc\xe6\x7d\xca\x38\x8f\x80\xf8\xae\x81\ -\xd8\x63\xab\xb1\x3e\x04\xb3\xde\x3b\x31\xc6\x1b\x35\xa6\x04\x30\ -\xf3\xcd\xba\x6b\xc8\x8f\x8d\x9a\x2b\x05\x82\xa1\xf7\x4e\xb8\xd9\ -\xa4\x31\x12\x44\xb8\x41\x47\x30\xf5\xfb\xdf\xfe\x84\x70\x3a\x8c\ -\xde\xf3\x8c\x12\xf3\x08\x20\x64\x69\xaf\x49\x50\x9f\xbf\xeb\xdb\ -\x85\x21\xed\x6e\xa3\xf7\x2c\xa3\xc6\x3c\x07\xb0\x5e\x24\x98\x2d\ -\xed\xb1\xf5\x27\xd4\x6f\x9c\xd3\x01\x20\xaa\xa1\x5c\xf9\x7e\xd5\ -\xa5\xd5\xc4\x5b\x07\xe8\x36\x49\xa2\x42\xf6\x8b\x77\xfe\x74\x21\ -\x5e\x02\xda\x74\x02\x56\x4c\xc3\xe6\x4a\xc1\xb4\x39\x1b\x33\x00\ -\x68\xf7\x03\x3a\x0f\xd6\x95\x77\x6a\x35\xe6\x49\x10\xd0\xed\xa8\ -\xb2\xe4\xe1\xe9\xb1\x97\x7e\x7c\xed\x38\x3b\xcc\x40\xb5\x19\x35\ -\xe6\x49\x10\xf4\xb9\xf6\x9a\x84\x79\xe6\xbc\x52\xc0\x8a\x63\x8c\ -\x9e\xc0\x51\xa3\x26\xce\x24\xc8\x87\xb4\x97\x04\x7c\xc7\x66\x5f\ -\x7d\x06\x09\xa9\xf3\xce\x84\xc3\x46\x8d\x39\x01\x24\x74\x87\x8d\ -\xcc\xba\x4d\x91\x2b\x0a\x0c\x83\x77\xa6\x0f\x8d\x1a\x53\x02\xda\ -\x15\xda\x0b\x40\x7b\xfe\x3e\x69\xca\xfc\xe0\xb5\xb6\xbb\x4b\x37\ -\x54\x55\x10\x70\x8f\x96\x62\x85\xeb\x8d\x32\x53\x02\xba\xce\xd6\ -\x68\xaf\x96\x8b\x2a\x74\x8f\x51\xd7\xdf\xe1\x6b\x1e\xe1\x85\xfe\ -\x44\xf9\xdc\xd0\x51\x27\xc3\x46\x5d\xfc\x2d\x31\xd6\xbf\x45\x11\ -\xf1\x2c\x5b\xdd\xf5\x05\x84\xd0\x79\x66\x60\x67\x7d\x79\x79\xd4\ -\x24\x8b\xd7\x37\xe6\xa2\xcd\x00\x2e\x1f\x35\x33\xee\x9c\x38\x37\ -\x78\x95\xdd\x1e\xd3\x06\x55\x15\x0c\xfc\x4c\x4b\x11\x78\x53\x3c\ -\x69\xdc\x04\x5c\xdc\xf7\xdf\xa5\xa1\x32\x14\xa7\xe9\x38\xbc\xdf\ -\xc2\xd7\xea\x79\x10\xc0\x38\x0d\x75\x22\x33\xe7\xd4\xae\x78\xda\ -\x84\xbb\xc2\x04\x7e\x49\x4f\xd0\xa2\x89\x8b\x56\x5d\x6f\x8b\xc3\ -\x34\x22\xdf\xaf\xba\x98\xf1\x1b\x1d\x49\xf4\x4a\xbc\xe1\x0f\x24\ -\x49\x40\x63\x4d\xe0\x5d\x00\xda\xc9\xd0\x25\xa2\x72\x85\x1d\x26\ -\xd3\x09\xb7\xc7\x53\x0c\xfd\x6b\xef\xa9\x8c\xce\xf6\xea\x44\xfa\ -\x24\x27\x43\xc4\x20\x7a\x4a\xc7\x00\x8f\x4c\x2a\xad\x32\xed\xab\ -\xf5\x17\x78\x8b\x5f\x1a\x49\x8c\xa7\xb5\x1c\x33\x7e\xfb\xde\x86\ -\x5f\x99\x96\xc0\xdf\x20\xe9\xd9\x60\x78\x4d\x59\x3d\x18\xaf\x6b\ -\xf5\x42\xd2\x96\x29\xf3\x2b\xaf\xee\xa5\x57\xdb\x91\xef\x57\x5d\ -\x24\x5c\x7f\xd4\xd5\x10\x31\x0e\x00\x19\xc1\x64\xfd\xba\x3d\x1d\ -\xee\x14\xce\x27\xa0\xdf\x5d\xbd\x2e\xe6\x10\x6f\xdd\x54\x16\x34\ -\x16\x47\x7d\xab\x70\x67\x67\x57\x81\x71\x87\x86\x8a\x40\xa0\xa8\ -\xbb\xa2\xca\x6e\x13\x70\x60\x4d\xe9\x17\x52\xe0\x27\x00\x3a\x2e\ -\x91\x8c\x5b\x87\x77\xe0\x55\x80\xfb\xa4\xd6\xb8\x3b\xf8\x4a\x42\ -\x0b\x01\x5a\xa0\x67\xa9\x34\x95\xb2\x9d\x94\x4a\x64\x5a\xc2\x3b\ -\x8e\x8f\xf6\xcd\xf8\x1c\xa0\xd9\x97\xe3\x63\xe2\xe8\x82\xc6\xdc\ -\xe1\x63\x26\xef\xfa\xcf\xc1\xdd\x31\x8b\x9e\x6d\x02\x93\xb7\xd8\ -\x13\x00\xa1\x0a\xfa\x8d\x9c\xca\x70\x4d\xe0\xb9\x44\xbd\xb4\x48\ -\xb9\x46\xa8\x39\xbc\xf3\xc0\x68\xef\x0c\x37\x88\x6e\xd3\xd0\x5e\ -\xa7\xdb\x5d\x98\x3b\xe9\x07\x6f\xb7\x34\xed\x6a\x4f\x35\x96\x1d\ -\xc8\xf7\xab\xae\xeb\xbf\x7f\xa0\x86\xba\x26\xea\x4b\x37\x4f\xc0\ -\x3b\x99\x39\x27\xe7\x1e\xdd\xbd\x3b\xa5\x9a\x41\x4b\x55\x62\x79\ -\xa7\x73\x9f\x62\xd0\x16\x1d\xc9\xb8\x03\xe4\x6a\xf4\x16\x87\x6e\ -\xb1\x12\xab\x37\x98\xb0\xa0\x7a\x94\x3b\xdb\xf3\x17\x80\x1e\x33\ -\x34\x7d\x14\xe9\x88\x3d\x90\xe8\x37\x3f\x1e\x2c\x3f\xc3\x7e\xff\ -\x9b\xca\x91\x11\x2d\x2f\x82\x68\xa9\xa1\x29\x42\x84\xea\x0e\x38\ -\x57\x1e\x58\x53\xfa\x85\xd5\xb8\xa9\x60\xea\xd2\x8a\xc1\x91\xaf\ -\x1c\x8b\x41\x58\x0e\x60\x84\xae\x91\xb0\x83\x65\xc6\x83\x4d\x6b\ -\x4b\xce\x5a\x89\xd9\xe3\x49\xac\xa0\x24\xf4\x18\xc0\xd5\x00\x9c\ -\x86\xa6\xf3\x20\x7e\x59\x71\x52\x85\x95\x82\xc5\x64\x98\xa6\xaa\ -\x8e\xb6\x96\xec\x39\x20\xb1\x42\x57\xaf\x74\x19\x15\x79\xa7\x72\ -\x9e\xac\xab\xbb\xdf\xf2\x5c\xd4\xab\x59\xdc\x57\x52\x59\xc8\x10\ -\x6f\x01\xf0\xc4\x69\x3e\x0d\x60\x1b\x80\x6d\x8a\x0b\xbb\xac\x26\ -\x23\xdf\xaf\xba\xdc\xc3\x3d\x85\xa4\x60\x26\x4b\xdc\x0b\x42\xbc\ -\x65\x78\x04\xa0\xd2\x70\x4d\xd9\xfa\x1e\xd8\x07\x60\x43\xb9\xbc\ -\x6f\xe1\xea\xeb\x38\x16\xab\x04\x70\x5f\x12\x59\x04\x84\xdd\x90\ -\xf8\x2b\x04\xfd\x4b\x30\x7f\xc2\x8a\x72\xea\x02\xd3\x79\xb7\x23\ -\x1a\x13\x91\x68\x96\x64\xc7\xb0\x28\x23\x8f\x04\x8d\x05\xcb\xa9\ -\x00\xdd\x8d\xae\xbf\xd4\x24\x72\xde\x28\x89\x4b\xdf\xaf\x7e\xbc\ -\xa9\x37\xfe\x6d\xfb\x1d\x2f\x28\x0a\xfd\x08\x82\x9f\x07\x90\xde\ -\xc9\xb0\xab\x2e\xf9\xd7\x79\x27\x73\x6a\x7b\x32\xe4\x8d\xb0\x77\ -\x21\xa3\xaa\x62\x72\x6b\xf6\xbd\x12\xb4\x1c\x0c\x9f\xad\xb1\x41\ -\x9f\x81\x65\x45\x66\xe7\xd0\xf5\x76\xd6\x28\xa6\x6d\x25\xe7\x2b\ -\x5a\x35\x5e\x0a\x9e\x43\xe0\x59\x00\xc6\xf6\x30\xcc\x09\x30\xb6\ -\x13\xc9\x4d\x8d\x39\xa7\xff\xd6\x93\xff\x03\x74\x87\x3e\x59\xca\ -\x5e\x9c\x27\xa6\x83\x79\x3c\x40\xe3\x40\xc8\x03\x30\x0c\x5d\xcf\ -\xb8\x83\x41\x67\x89\x71\x0e\xc4\xff\x26\xc2\x61\x29\x71\xd8\x41\ -\xd8\xdd\x50\x53\x76\xa8\xbf\x94\xe3\x0e\x60\x00\x03\xf8\xdf\xc4\ -\x7f\x01\x33\x41\xc7\xce\x61\x76\x81\xea\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\x77\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x29\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4f\x88\xdb\x45\x14\xc7\xbf\x6f\x92\xad\x55\xd9\x5e\xb6\x78\ -\xa9\xc5\x9b\x7f\xc0\x93\x95\x1e\xbc\x18\x6a\x92\x1a\xa1\x5b\x1b\ -\xb2\xa2\x54\xb0\xdd\x64\xb5\x20\x1e\x14\x29\x28\x6a\x0c\xb6\xa0\ -\x08\x16\x2a\xe8\xba\x49\x64\x0f\x56\x51\x37\xe9\xba\x88\x5b\x93\ -\x2c\x2c\x08\x2a\x88\x82\xd0\x22\x88\x07\x91\x56\x50\x28\x45\x69\ -\x89\x74\x93\x79\x1e\xb2\x5b\xd2\xdf\xfc\x0a\x9b\xee\xcc\xfb\x0d\ -\x34\x9f\xdb\xce\xe1\x7d\xdf\x7c\x99\x79\x33\x6f\x33\x3f\x60\xc8\ -\x90\x21\x37\x32\x64\x2b\x50\x32\x3b\xf9\x3a\x11\xbd\x02\x28\x66\ -\xe6\x23\xad\x7a\xa5\x64\x2b\xb6\x4b\x94\xad\x40\x44\xea\x55\x80\ -\x62\x00\xc7\x41\x28\x26\x73\x85\x84\xad\xd8\x2e\xb1\x66\x40\x7f\ -\x2c\x02\x08\x8c\x85\xf4\x44\x61\x87\xc5\xf8\x4e\xb0\x69\x80\xee\ -\xff\x83\x80\x51\xee\xe2\xd4\xc3\x13\x93\x77\x59\xd4\xb0\x8e\x4d\ -\x03\xd8\x18\x21\x6c\xed\x6a\xd5\x4c\xef\x3d\xb8\xdd\xa2\x8e\x55\ -\x6c\x1a\x70\x2d\xb6\x73\x3c\xd6\x48\x3c\xf1\xf4\x56\x01\xad\x81\ -\x91\x30\x00\x00\xee\x1e\xb9\xac\x17\xc7\xc7\x27\x47\x85\xf4\xd6\ -\x8d\x33\x03\x98\x39\xb8\x25\xee\x6f\x6f\x52\xf3\x99\xcc\x73\x37\ -\xb9\xd2\xbc\x1e\x9c\x19\x40\x44\x1a\xc1\xba\xc0\xd8\xd5\xb9\xa5\ -\xfd\x71\x22\x51\x8c\xbb\xd2\x1d\x14\xd7\x5b\x40\xc3\x5c\x09\xd9\ -\x91\xb1\x73\xd3\xb0\x78\x09\xdb\x08\xee\x6b\x40\xd8\x4a\x00\xf2\ -\xa9\xdc\xd4\x9b\xce\xb5\xd7\x81\x54\x11\xd4\xc6\x08\xf3\xe1\x54\ -\x36\x7f\x58\x48\xff\x9a\x48\x19\x00\x00\x5d\x63\x84\xe8\xad\x54\ -\x2e\x5f\x10\xcc\xc1\x40\xd2\x80\xb5\xed\x70\x35\x4c\x1f\x24\x73\ -\x85\xac\x68\x1e\x7d\xc8\x1a\xc0\xcc\x20\x63\x3b\x28\x62\x7c\xf2\ -\x50\x76\x2a\x29\x9a\xcb\x9a\xb8\xb8\x22\x83\x61\xd6\x84\x4d\x8a\ -\x78\x7e\xf7\x44\x7e\xa7\x74\x3a\xf2\x06\xf4\x60\x32\xb7\xc3\xad\ -\x5a\xd3\x57\xc9\x7d\x85\x7b\x24\x13\x89\xca\x80\xb5\x9b\x62\xd0\ -\x84\x31\x52\x68\xee\xca\xe6\xef\x90\xca\x23\x32\x03\x56\x61\x32\ -\x6b\xc2\xb6\x18\x51\x23\xbd\xef\xd0\x6d\x12\x09\x44\x6d\x00\x98\ -\xc1\x80\x71\x5b\xbc\x53\xab\xce\x62\x66\xff\xfe\x2d\xae\xf5\x23\ -\x37\xa0\x87\x79\x5b\x24\xe0\xbe\x4e\xfb\xe6\x85\xc4\x81\x03\x9b\ -\x5d\x2a\x7b\x62\x00\x00\x40\xf7\x56\x43\x1f\x84\x07\x47\x2e\xc6\ -\x3e\x75\xd9\x3c\xf9\x64\x00\x88\x48\xb3\xd1\x41\xd2\xf8\xc8\xd8\ -\xb9\x4a\xb1\x58\x74\x92\xab\x57\x06\x00\x0c\xea\x9d\x0c\xc1\x9a\ -\xf0\xd4\xb7\xa7\xcf\xbe\x0d\x07\x1d\xa4\x67\x06\x5c\xc1\xbc\x32\ -\x83\x5e\x48\xe5\x0a\x2f\xd9\x16\xf2\xd5\x00\x00\x64\x36\x4f\x8c\ -\xa3\xa9\x5c\xfe\x19\x9b\x2a\x1e\x1b\xc0\x00\xa0\x8d\xcd\xc0\xf4\ -\x7e\x3a\x5b\xc8\xd9\x52\xf1\xd8\x00\x00\xbd\xa2\x10\xdc\x0e\x04\ -\xc2\xbb\xb6\x04\x7c\x37\x00\x14\x52\xf6\x98\x61\xed\x58\xf4\xde\ -\x00\xe6\xb0\x1c\xb9\x6a\x2b\xbe\x37\xff\x9d\x0d\x87\x63\xc1\x93\ -\x8f\x88\x9e\x6d\xd4\x2a\xef\xd9\x52\xf0\x78\x05\x98\x93\x07\xe1\ -\xb5\xc6\x5c\xd9\xda\xe4\x01\x7f\x0d\x50\x21\x77\x9e\xe3\xcd\xb9\ -\xca\x11\x07\x42\x3e\x41\x00\xb3\x82\x39\xfb\x8f\x1e\xb8\x77\xdb\ -\xf3\x08\xfb\x01\x76\x83\x78\x56\x03\xb4\x02\x5d\x5d\xf7\x19\xf8\ -\xf2\xc2\x98\x9a\x2c\x95\x4a\x21\xb7\xc3\x8d\xe3\xcd\x0a\xe0\xde\ -\xb2\x0f\x4e\xfe\x9b\x4b\x6a\xf4\xb1\x1f\x67\x66\x56\x5c\xe9\x7a\ -\x61\x00\x33\x14\x99\x15\xef\x67\x28\xb5\xe7\xbb\xcf\x8f\xb5\x5d\ -\x6a\x47\xbf\x05\x88\x88\xc0\xc1\x3d\xff\x9b\x5e\xe1\xdd\x4b\x0b\ -\xe5\x7f\x5c\xcb\x47\xbb\x02\x88\x68\xb5\xe8\xf5\x8d\xe1\xcf\x58\ -\x37\x9e\x5a\x5a\xa8\xfc\x25\x91\x42\x64\x06\xf4\x1e\x52\x05\x26\ -\xcf\xb8\xa0\x98\xd2\xa7\xe6\xa7\x7f\x97\xca\x23\x2a\x03\x88\x4d\ -\xed\x4b\x0c\x3c\xf2\x75\xad\x7c\x46\x32\x11\x79\x03\x08\x14\xa2\ -\xbb\x02\xd2\xd9\x56\xbd\xf2\xbd\x74\x3a\xd2\x06\x10\xb4\xa1\xc9\ -\x0c\x7a\xb2\x39\xf7\x61\x43\x38\x17\x00\xf2\x06\x28\xe3\xb0\x63\ -\x1c\x6a\xd5\xca\x9f\x09\xe7\x71\x05\xc9\x63\x30\x16\x1c\x20\xe6\ -\x97\x1b\xf5\xea\x8c\x60\x0e\x06\x52\x2b\x20\xac\xa7\x7f\xa7\x51\ -\xaf\x46\xfe\x4c\xc6\xbd\x01\xa1\xcd\x0d\xcf\x36\x6b\xd5\x17\xe1\ -\xa0\xb9\x19\x14\xd7\x06\x18\xcd\x0d\x01\x5f\xac\x9c\xbf\x7d\x0a\ -\x1e\x4c\x1e\x70\xfb\x50\x32\xac\xad\x5d\xbe\x3c\xda\x79\x7c\x79\ -\xb9\xd4\x71\xa5\x3b\x28\x2e\x1f\x4a\x06\x3b\xbb\x9f\xe2\x9b\xdb\ -\x7b\x97\x67\x67\xff\x73\xa5\x79\x3d\x48\x15\xc1\x5f\x95\x8e\x67\ -\x16\x4f\x9c\xf8\x57\x48\x6f\xdd\x48\x18\x70\x96\x95\x4a\x35\x4e\ -\x4e\xff\x2d\xa0\x35\x30\x36\xef\x01\x61\x3f\x5c\x9e\x67\x8d\x74\ -\xab\x36\xf3\x87\x45\x1d\xab\x38\xf9\x64\x66\x95\x8b\x9a\x29\xd3\ -\x3a\x59\xf9\xc5\xa2\x86\x75\xec\x7d\x34\x85\xfe\x57\x5f\xcc\x20\ -\x7e\x74\xa9\x5e\xfe\xc1\x56\x7c\x57\x58\xfc\x6a\x8c\x8f\x82\xd0\ -\x05\xb8\x0b\xe0\x8d\xe6\x5c\x75\xc9\x56\xec\x21\x43\x86\x0c\x71\ -\xc5\xff\x03\xa1\x32\xbd\x29\x9d\x1e\xd2\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x68\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x1a\x49\x44\x41\x54\x58\x85\xed\ -\xc1\x01\x01\x00\x00\x00\x82\x20\xff\xaf\x6e\x48\x40\x01\x00\x00\ -\x00\xef\x06\x10\x20\x00\x01\x47\x01\xa0\x88\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\x17\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\xc9\x49\x44\x41\x54\x78\x9c\xed\ -\xd6\x4d\x48\x54\x51\x18\x06\xe0\xf7\xbd\x5e\x4b\xb2\x20\x82\xa0\ -\x08\x8c\x56\x41\x41\x54\xd2\x38\x1a\x84\x45\x04\x26\x29\x26\xcc\ -\x22\xca\x12\xa2\x9f\x45\x8b\x08\xa2\x82\x90\xa0\x45\x60\x05\x6e\ -\x82\x28\x88\x6a\x11\xf8\x33\x57\xa4\xbf\x4d\xf4\x03\xe6\x38\x30\ -\x81\x9b\x16\x19\x05\xad\xa2\xac\xb0\x20\x35\xaf\xf7\x6d\x23\xe4\ -\x5c\x2b\xcc\xb9\x33\x41\x7d\xcf\xf2\x7c\xe7\xbc\x7c\xe7\xbb\x1c\ -\x66\x00\x63\x8c\x31\xc6\x18\x63\x8c\x31\xc6\x18\x63\x8c\x31\xc6\ -\xfc\x2f\x98\x6b\x40\x45\xb7\x56\x21\xd0\x0d\x00\xcb\x04\x5e\x4c\ -\x37\xe0\x3c\x48\x45\xd0\xdb\x4f\xc5\xba\xd4\x00\xaa\x15\x00\x1c\ -\xf2\x48\xaa\x81\xf7\x72\xc9\xcb\x7d\x00\xc9\xe0\x31\x80\x4d\x3f\ -\x12\x75\xf3\xcb\xb8\xb3\xff\x79\x82\xdf\x72\xcd\xce\x22\x31\xee\ -\xe1\xb8\xa0\x73\x53\x56\x87\xfd\xf7\x5c\x9c\x39\xc8\xf1\xd9\xc6\ -\x3a\x11\xb4\x96\x9d\x21\xee\x59\xe0\xea\xfe\x5a\x4f\x0b\x23\xc8\ -\x06\x00\x54\x3f\x94\x1b\xf7\x82\x4b\xa1\xcb\x03\x11\x7c\xc0\x9c\ -\x07\x30\x01\x1e\x06\xf0\x2e\xb4\xbc\x79\xae\xd4\x5b\xd5\xa5\xe5\ -\xb9\xe6\x57\xb7\x6b\xfe\xc8\x27\x75\x0b\x3c\x34\x75\x5d\xc0\x18\ -\x1d\xee\xce\xe5\xeb\x03\x11\x4c\x10\x00\x62\x3d\x5a\x41\x5f\xf7\ -\x00\xac\x0c\x95\xde\x52\xac\x4d\x35\xf2\xd9\x6c\x72\xcb\xbb\xb4\ -\xd4\xa5\x6e\x03\x58\x1f\x2a\x7d\xa4\x58\x97\x6a\x64\xef\x6c\x72\ -\xa7\x8a\xe2\x09\x20\x5d\xc7\xd7\x8e\xcf\x2a\x00\x4f\x42\xa5\x25\ -\x82\x9e\xc4\xba\x54\xfb\xa7\x99\x1b\x3a\xb5\xba\xd8\x51\x0a\xd3\ -\x2f\xff\x4a\x60\x65\x14\x97\x07\x22\x1a\x00\x00\xf4\x25\xf8\x71\ -\x51\x09\xb7\x01\xba\x95\x55\x20\x4a\x49\xf5\xc4\x3d\x1d\x9e\x69\ -\x56\x2c\xa9\x2d\x8e\xa3\x5e\x09\x65\x59\x05\xa1\x7f\x8e\xcf\x78\ -\x7a\x27\x5f\x44\xd3\x75\x44\x4f\x20\x4b\x8b\x9c\x8a\x35\xc1\x59\ -\x90\x27\xa7\x17\xd5\xda\x3f\xe0\x9c\xc0\x19\x06\xbf\x3a\x1e\x4b\ -\xaa\x89\xd0\x55\x00\xc5\xa1\x46\xbd\x71\x97\xbb\x33\x75\xfc\x1a\ -\x65\xbb\xd1\x0f\x60\x52\x85\xa7\x03\x90\x2e\x01\x28\x9a\xba\x2e\ -\xa8\x7d\xde\xb0\xb3\xf7\x51\x33\x47\xb3\x0e\x48\xac\xf0\x70\x1a\ -\xd0\x99\xe9\x69\x6a\x2b\xf3\x9d\x63\x1d\x09\x4e\x44\xdd\x67\xde\ -\x06\x00\x00\x71\x4f\x35\x0a\xd4\x01\xa2\x34\x54\xea\x15\x58\x9f\ -\xde\xc9\x0f\x00\xb0\xaa\x5d\x73\x16\x14\x05\x97\x41\xee\x0b\xed\ -\x13\xc8\xa3\xfd\x0d\x6c\xcb\x57\x8f\x79\x1d\x00\x00\x54\x76\x6a\ -\x5d\xe0\xe8\x0e\x80\xa5\xa1\xd2\x60\x11\x59\x33\x36\x8e\x21\xb7\ -\x58\x9d\x10\xb6\x86\xea\xa3\x12\x77\xa5\x1b\xe9\xe5\xb3\xbf\xbc\ -\x0f\x00\x00\xca\xdb\x55\xe6\xba\xba\x0b\x60\xf5\x0c\x8f\x0c\x41\ -\xdc\xd1\xdf\xc8\x54\x3e\xfb\x02\x22\xfc\x15\xf8\x9d\x4c\x82\x6f\ -\x7c\x9f\x1b\x09\x3c\x98\xc1\xf6\x41\xa7\x88\x95\x85\xb8\x3c\x50\ -\xa0\x01\x00\x40\x26\xc1\xe1\xcf\x3e\xb7\x13\xba\xfe\xab\x3d\x12\ -\x9e\xfa\x2e\xab\xfa\xea\xf9\xb2\x50\x7d\x15\xe4\x09\x64\x91\x18\ -\x4f\x06\x2d\x22\x5b\x42\x95\x4e\xc7\x67\x53\x5f\x82\x23\x85\x6c\ -\xa7\xf0\x03\x98\x14\x4b\x4e\x5c\x21\xd8\x0c\x40\x82\x2e\xa4\x07\ -\x9c\x53\xbf\xfb\x7f\xf0\x4f\xaa\x7e\x28\xb7\xfa\x9a\x4a\xfe\x76\ -\x1f\xc6\x18\x63\x8c\x31\xc6\x18\x63\x8c\x31\xc6\x18\x63\xcc\x7f\ -\xe2\x3b\x5f\x7a\xf2\xea\xb1\x6e\xd0\x9c\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x08\x6c\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x08\x1e\x49\x44\x41\x54\x78\x9c\xed\ -\x5b\x7d\x8c\x1c\x65\x1d\x7e\x7e\x33\xb7\x7b\x77\x70\x1f\x10\xe8\ -\x51\xb3\x1f\xb3\x7b\xd7\x6b\x4a\x5a\x4c\x2c\xa7\x11\xd2\x54\x4b\ -\x34\xa8\xa1\x87\x45\x12\x05\x03\x34\x90\x2a\x45\x49\x94\x40\x4d\ -\x4d\xc0\xaa\x54\xa1\x4a\x0b\xfc\x41\x55\x04\x2d\xd0\x48\x02\x42\ -\x63\x0d\x60\xff\xc0\x36\x55\x21\x80\xd1\xe8\x62\xcf\x5c\xdd\xdb\ -\xd9\x9d\xbb\x1e\xb5\x14\xfb\x61\x7a\xb7\xb3\xfb\x3e\xfe\xd1\x22\ -\xf3\xb5\x77\xbb\xb7\x33\xc7\x55\xef\xf9\x6f\x9e\xf7\xf7\xfe\xe6\ -\x99\x67\xde\x99\x7d\xe7\x7d\x7f\x0b\xcc\x63\x1e\xf3\xf8\x7f\x86\ -\xcc\xc6\x49\x86\x0f\x1d\x5a\x10\x9b\xac\xac\xa4\xe0\x12\x0d\xb2\ -\x44\x81\xbd\x00\xce\x13\x48\x17\x40\x1d\xc0\x71\x00\xc7\x09\x29\ -\x02\x3c\xa0\x41\xfe\x46\x56\xf6\x67\x32\x99\x91\xa8\xb5\x45\x66\ -\x40\xb1\x58\xec\x53\xd0\xd6\x42\x71\x10\x82\x0f\xce\x30\xcd\x08\ -\x28\x2f\x6a\x9a\xfa\x79\x2a\x95\x7a\x43\x44\x18\xaa\x48\x84\x6c\ -\x00\x49\x29\x58\xd6\x95\xa2\xb0\x01\xc0\xaa\x30\x73\x03\xc8\x51\ -\xb8\xf5\xed\xc3\x87\x9f\x1a\x18\x18\xb0\xc3\x4a\x1a\x9a\x01\x85\ -\x82\xb5\x0a\xc2\x2d\x00\x06\xc2\xca\x19\x0c\x29\x10\xd8\x94\x49\ -\x27\x9e\x08\x63\x44\x34\x6d\x40\x3e\x9f\xbf\x48\xd3\x63\x0f\x00\ -\xf8\xe2\x14\x61\x8a\xc0\xef\x45\x64\x2f\x14\x87\xa8\xe3\x1f\x2d\ -\xc0\xd1\x4a\xa5\x72\xa2\xd2\xd6\x56\x8d\x97\xcb\x9d\x64\x4b\x37\ -\xa0\xb2\x14\x2c\x06\xe4\x32\x01\x3f\x09\xa0\xbd\x56\x42\x02\xfb\ -\x35\xa8\xf5\x86\x61\xbc\xd9\x8c\xfe\xa6\x0c\xc8\x97\x4a\x1f\xd1\ -\x14\x76\x01\xf8\x40\x40\xf3\x09\x81\xbc\x40\x72\x77\x4b\x8b\xbc\ -\x94\x4c\x26\xdf\x6e\x24\x77\xa9\x54\x6a\xaf\x56\xe5\x0a\x11\xb5\ -\x9a\x90\xc1\x1a\xe7\x98\xa0\xf0\xe6\x6c\x3a\xfd\x8b\x99\xe8\x07\ -\x9a\x30\xa0\x50\x28\x5d\x0f\xc1\xe3\x00\x5a\x7d\xa2\x80\x87\x35\ -\xa8\xfb\x0c\xc3\x78\x67\xa6\xf9\x9d\xc8\xe5\x72\xf1\x8e\x8e\xae\ -\x75\x10\xb9\x07\x40\x8f\x2f\x80\xb2\xd9\x30\x12\xf7\x88\x88\x6a\ -\x34\x77\xc3\x06\x90\xd4\x8a\xc5\xd2\xbd\x84\x6c\xf4\x34\x29\x00\ -\x8f\xb7\xe8\xf2\xed\x64\x32\x69\x35\x9a\xb7\x1e\x0c\x0d\xfd\xb3\ -\xb3\xbd\x7d\xe2\x0e\x02\x77\x02\xe8\x70\x0b\xc3\xae\x73\xce\x69\ -\xbd\xa1\xa7\xa7\xe7\x64\x23\x39\x1b\x32\x80\xa4\x66\x9a\xa3\x3b\ -\x21\xfc\x82\xa7\x69\x4c\x69\x58\xd3\x9b\x4a\xbd\xd6\x48\xbe\x99\ -\xc2\xb2\xac\x64\xa5\xca\xe7\xe1\x7f\xe1\xfe\xc9\x2e\x4f\x7c\xbc\ -\xbf\xbf\xff\x78\xbd\xb9\xb4\x46\x4e\x6c\x96\x46\x37\xf9\x2e\x5e\ -\xf0\x2a\x58\x1d\x98\xad\x8b\x07\x80\x64\x32\x69\xe9\x1a\x56\x02\ -\xd8\xe9\x69\xfa\x50\x2c\xde\xb6\x93\xa4\x5e\x6f\xae\xba\x47\xc0\ -\x48\xb1\xf8\x79\xa1\x3c\xed\xee\xcc\x1d\x4a\x55\x6f\xcd\x66\xb3\ -\x13\xf5\xe6\x09\x13\x24\xa5\x58\xb4\xee\x22\x70\x1f\x1c\xd7\x42\ -\x60\x4b\xd6\x48\x7d\xa3\x9e\x1c\x75\x19\x50\x2c\x16\x07\x14\x65\ -\x3f\x80\x36\x07\xfd\x94\x91\x4e\xde\x18\xc5\xec\xac\x51\x8c\x98\ -\xd6\xd7\x04\xdc\xe6\xe4\x04\x72\x93\x61\x24\x9f\x98\xae\xef\xb4\ -\x8f\x80\x65\x59\x17\x28\xca\x2e\x38\x2e\x5e\x80\xd7\xa8\x2a\xeb\ -\xe6\xc2\xc5\x03\x40\x26\x9d\x78\x08\x94\x9f\x39\x39\x82\x8f\x16\ -\x0a\x63\xcb\xa7\xeb\x3b\xad\x01\x15\xc5\x2d\x00\x12\x0e\x6a\x4c\ -\x84\x6b\xde\xaf\x61\x1f\x04\x11\xa1\x6d\x9f\x5a\x0f\xe0\x0f\x0e\ -\x3a\x0e\xa9\x3c\x4a\xb2\x65\xaa\xbe\x53\x1a\x60\x9a\xe6\x0a\x10\ -\x37\x3b\x28\x52\xc9\xe7\xd2\xe9\xf4\x58\x13\x7a\x23\x41\x7f\x7f\ -\xff\xa4\xaa\xda\xd7\x00\x38\xf2\x1e\x2b\xcb\x8b\x45\xeb\xb6\xa9\ -\xfa\xd5\x34\x80\xa4\x10\xfa\xf7\x3d\xf4\xce\x6c\x36\xf9\x6a\x33\ -\x42\xa3\x44\x6f\x6f\xef\x5b\x84\x6c\x76\x72\x04\xee\x1e\x1f\x1f\ -\x3f\xb7\x56\x9f\x9a\x06\x14\x2c\x6b\x25\xc0\x15\x0e\xca\x16\xa8\ -\x6f\x85\xa0\x33\x5a\x28\xfb\x47\x10\x14\x1d\xcc\x85\x13\xe5\xf2\ -\x97\x6b\x85\xd7\x34\x40\x14\xee\x72\x13\xf8\xb1\x61\x18\xf9\xe6\ -\x15\x46\x8b\x6c\x36\x3b\x41\xd0\x7d\xa3\x28\x77\xd4\x9a\x1b\x04\ -\x1a\x30\x32\x32\xb2\x10\xc0\xa7\x1c\x94\xad\x2a\xf6\xbd\xa1\xa9\ -\x8c\x18\x99\x54\xea\x49\x02\xc3\x0e\x2a\x51\x28\x95\x3e\x11\x14\ -\x1b\x68\x80\xe8\xfa\xf5\x00\xfe\xeb\x98\x00\x2f\xf7\xf6\xf6\xbe\ -\x15\xae\xcc\xe8\x20\x22\x55\x21\x9f\x71\x71\x4a\x6e\x0a\x8a\xad\ -\xf1\x08\xc8\x6a\xe7\x11\x85\xbf\x0a\x4b\xdc\x6c\x81\xba\xb8\x35\ -\x0b\x3e\x13\xf4\x18\xf8\x0c\x18\x1f\x1f\x3f\x17\xc4\xe5\x4e\xae\ -\x6a\xeb\xbf\x0e\x5d\x61\xc4\xc8\x24\x93\xaf\x03\xe2\x1c\xb5\xdd\ -\x23\x96\x75\xa9\x37\xce\x67\xc0\xe4\x64\xe5\xa3\x00\xe2\x0e\xea\ -\xcf\x7d\x7d\x89\xa2\x37\x6e\xae\x43\x44\x14\x84\xae\x1b\xa7\x2b\ -\xff\x3a\x65\xc0\x23\xc0\x65\x1e\x62\x7f\xa8\xca\x66\x11\x3c\xfd\ -\xfd\xf2\xde\x31\xb0\xd4\x1b\x13\x64\xc0\xc5\xce\x23\x71\xbf\x4d\ -\xcf\x2a\x08\xc5\xab\xfd\x62\x6f\x4c\x80\x01\x92\x71\x1e\x91\x32\ -\xe7\x7f\xfb\x6b\x81\x2c\x7b\xb5\x67\xbd\x31\x3e\x03\x08\x74\x3a\ -\x8f\x45\xe4\x5f\x21\xeb\x9a\x4d\x78\xb5\x77\x7a\x03\xa6\x35\xa0\ -\x5a\x65\x43\x6b\x6c\x73\x09\x99\x4c\x66\x12\x40\xc5\x41\xc5\x73\ -\xb9\x9c\xf3\x05\xef\x37\x40\xbc\x8b\x24\x31\xce\x89\x6f\xfe\xa8\ -\x10\x34\x11\x3a\xe1\x3c\xd0\x95\xe6\x1b\x36\x67\x0b\x0a\x85\x42\ -\x2b\x00\xe7\x7a\x40\x79\xd9\xb2\x65\x65\x67\x4c\xd0\x08\x70\xad\ -\xa8\x92\x3c\x2f\x1a\x79\xd1\x83\x64\xb7\x87\x3a\xe1\x8d\xf1\x19\ -\xa0\x00\xd3\x93\xc6\xf7\xe6\x3c\x5b\xa0\x69\xf1\x5e\x0f\x55\xf0\ -\xc5\xf8\xbb\xc9\x01\xe7\x11\x05\xfd\x61\x8a\x9a\x4d\x88\x5f\xfb\ -\x90\x37\xc6\x67\x80\x86\xaa\x6b\xb3\x51\xdc\x8b\x22\x67\x15\xe8\ -\xd1\x4e\x20\xe7\x8d\xf1\x19\xd0\xde\xde\xfe\x0a\x00\xc7\xfe\xbb\ -\x2c\xb7\x2c\x2b\x19\x81\xbe\x48\x41\x52\x03\x70\x95\x8b\x54\xb2\ -\xd7\x1b\xe7\x33\xa0\xa7\xa7\xe7\xa4\x00\xaf\x38\x39\x5b\x79\x12\ -\x9d\x05\x28\x95\x4a\x97\xc2\xbd\xa3\x7c\x3c\x93\x49\xbc\xe1\x8d\ -\x0b\x5c\x0f\x20\xe1\xfa\x8a\x12\x70\x30\x5c\x79\xd1\x43\x41\x73\ -\x69\x26\xf8\x92\x88\x54\xbc\x71\x81\x06\x68\x1a\x77\xe2\xf4\x6e\ -\xef\xbb\xbd\xaf\x18\x3e\x74\x68\x41\xd8\x22\xa3\x02\x49\x0d\xe4\ -\xb5\x4e\x4e\x28\x3b\x82\x62\x03\x0d\x48\xa7\xd3\x63\x20\xf6\x38\ -\xa8\xd6\xd8\xa4\xed\xdd\x0e\x9f\xb3\x30\x4d\xeb\x3a\x00\x4b\x1c\ -\xd4\xb8\x61\x24\xf7\x04\xc5\xd6\x5e\x15\x16\xf9\xa1\x87\xf8\x4a\ -\x3e\x3f\x66\x84\xa2\x30\x42\xe4\x72\xb9\x38\x04\xdf\x75\x72\x02\ -\x6c\x0b\x1a\xfe\xc0\x14\x06\xa4\xd3\x89\x97\xe1\x7e\x19\xc6\x75\ -\x5d\x6d\x0a\x45\x65\x84\xe8\xe8\xe8\xfe\x12\xdc\x9f\xbd\x47\x4f\ -\x9d\x6a\xdb\x5e\x2b\x7e\xaa\x11\x40\x2a\x7c\xd3\xc9\x11\xbc\xd1\ -\x34\x4d\xdf\xba\xda\x5c\xc1\xe8\xe8\xe8\x85\x10\xdc\xed\x22\xc9\ -\xef\x2d\x59\xb2\xc0\x37\x05\x7e\x17\x53\xee\x0d\x66\xb3\xa9\xbd\ -\x00\x9e\x74\xc7\x6b\xcf\xe7\xf3\xf9\x8b\x9a\x11\x1a\x05\x72\xb9\ -\x5c\xdc\xb6\xd5\xb3\x70\xd6\x10\x11\x7f\x39\x72\xe4\xf0\xc3\x53\ -\xf5\x9b\x7e\x77\xd8\x8e\xdd\xe9\x5c\x5d\x25\x90\xd2\xf4\xd8\x73\ -\xc3\xc3\xc3\xde\xe2\xa8\xf7\x15\x9d\x9d\x5d\x0f\x41\xf0\x31\x07\ -\x65\x2b\x1d\xeb\xa6\x2b\xaa\x9c\xd6\x80\x45\x8b\x16\x1e\xa6\xc2\ -\x67\x01\x4c\x3a\xe8\xcb\x63\xad\x6d\x8f\x90\x9c\x95\x5a\xe3\xe9\ -\x50\x28\x16\x6f\x23\xe4\x56\x17\x49\xac\xaf\xa7\x6c\xa7\xee\x0b\ -\x30\x4d\xeb\x06\x82\xae\x8a\x0b\x02\x3f\xf9\xf7\x89\x63\xb7\x7b\ -\xbf\xb1\x67\x0b\x67\x4a\x64\x6e\x27\xb0\x0d\x8e\x9b\x29\xe0\x83\ -\x86\x91\xfe\x7a\x3d\x39\x1a\xba\x83\x23\x66\xe9\x7e\x01\x36\xb8\ -\x55\x60\x5f\x2c\xa6\x5d\x9b\x48\x24\x8e\xd4\xe8\x16\x09\x72\xb9\ -\x5c\xbc\xa3\xab\xfb\x11\x10\xb7\x38\x79\x01\x7e\x93\x4e\x27\xaf\ -\xaa\xf5\xb3\xe7\x45\xa3\x65\x72\xba\x59\xb2\x9e\x01\xb1\xc6\x93\ -\xa6\xa0\x6b\x1c\x4c\xa5\x52\x7f\x6d\x24\xdf\x4c\x71\xf0\xe0\x78\ -\x4f\x4b\xac\xf2\x4b\xf8\xbf\x54\xdf\xa4\xaa\xac\xc8\x66\xb3\x75\ -\x2f\xe4\xce\xa4\x50\x52\x37\xcd\xd2\x0f\x20\xe2\x1d\x62\x36\x81\ -\xed\x55\x3b\xb6\x79\xd1\xa2\x85\x87\x1b\xcd\x5b\x0f\x4e\x97\xcf\ -\xe2\xab\x10\x6c\x04\x70\xbe\xab\x51\xf0\x62\xd5\x2e\x5f\xd7\xd7\ -\xd7\x77\xac\x91\x9c\xcd\x94\xca\xde\x02\xc1\x76\x00\x31\x4f\xd3\ -\x49\x02\x0f\x54\xca\x13\x5b\x1b\x29\x58\x9c\x0a\x24\x5b\x4c\xd3\ -\x5a\x0b\xc1\x26\xb8\xeb\x95\xce\x04\xc8\x56\xc3\x48\x6c\x10\x91\ -\x6a\xa3\xb9\x9b\x2b\x96\x2e\x16\x57\x6a\x94\xe7\x00\x5c\x10\xd0\ -\xfc\x0e\xc1\xdd\x1a\xb4\xdd\xe5\xf2\xa9\x3d\x8d\x9a\x91\xcb\xe5\ -\xe2\x9d\x9d\xe7\xaf\x54\x50\xab\x05\xb8\x1a\x40\xd0\x34\xdc\x06\ -\xb1\x3e\x93\x49\x3d\x36\x13\xfd\x40\x08\xe5\xf2\x07\x47\x47\x53\ -\x2d\x55\xf5\x20\x88\x6b\xa6\x08\xb3\x01\xee\x83\x68\xbf\x85\xe2\ -\xdf\x95\x92\x83\xaa\x55\x8e\xc6\x2a\x95\x93\xe5\x72\xb9\xda\xd6\ -\xd6\xd6\xa9\x94\xea\x26\xf5\x2c\x35\x2c\x06\xd5\x65\x02\xb9\x12\ -\x40\x57\xad\x84\x04\x5e\x3f\x53\x2e\xff\xc7\x66\xf4\x87\xf8\x87\ -\x89\xd2\xa7\x29\xb8\x5f\x80\x4b\xc2\xca\x59\x03\x63\x84\x7c\x27\ -\x93\x4e\xfc\x74\x26\x43\xde\x8b\xb0\xff\x32\xa3\x99\xa6\x75\x35\ -\x05\x1b\x05\xf8\x70\x98\xb9\x01\xe4\x41\x6e\x25\xab\x8f\x85\x59\ -\xa3\x18\xd9\x4c\xce\x34\xcd\xa5\x14\x6d\x2d\x14\x06\x21\x58\x3c\ -\xc3\x34\xe3\x10\xbc\xa0\xc0\x1d\xd9\x54\xea\x77\x33\xf9\x3f\xc0\ -\x74\x98\x95\xa9\xec\xc1\xd1\xd1\x54\xac\xc2\x55\x0a\x5c\x0a\xc8\ -\x12\x80\x59\x11\x74\x83\xe8\xc2\xe9\x9d\x9b\x63\x00\x8f\x0b\xa4\ -\xa4\x80\x21\x08\x87\x34\x72\x5f\x3a\x9d\x3e\x30\x57\xca\x71\xe7\ -\x31\x8f\x79\xfc\x6f\xe2\x3f\x21\x7b\x09\x29\x0d\x19\xbe\x1d\x00\ -\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x8d\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3f\x49\x44\x41\x54\x58\x85\xed\ -\xd3\xb1\x11\x00\x10\x10\x44\xd1\xa5\x10\x94\x22\xd1\xb5\x19\xad\ -\x18\x0a\x39\x91\x50\xea\x92\xff\xa2\xcd\x7e\xb4\x12\x00\xc0\x59\ -\xb8\x63\xae\x3d\x64\xaa\x7f\xb2\xd6\x4b\x4e\x4d\x92\xe2\x9f\x20\ -\xf0\xc6\x0b\x00\x00\x70\x77\x00\xa4\x4c\x0e\x07\xff\x04\x59\xb9\ -\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x3e\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xf0\x49\x44\x41\x54\x58\x85\xe5\ -\x96\x31\x68\x53\x51\x14\x86\xbf\x3f\x7d\xad\x52\x41\x31\x82\x08\ -\x2e\x2e\x2e\x0e\xe2\xd0\xa0\x5d\x1c\x2b\x54\xba\x08\xa9\x53\x05\ -\x11\x4d\x96\xb4\xa9\xe0\x26\x8a\xe2\x26\xb4\x4d\x2b\xd8\x87\x83\ -\x60\x27\x1b\x70\x29\x0e\xea\xe6\xa2\xf2\x3a\x48\x07\x17\x41\x1d\ -\x14\x41\xa8\x60\xa1\x45\xdb\xe4\x1d\x87\xa4\x4e\x82\xef\xde\x5c\ -\x22\xe8\xd9\x1e\xdc\xf3\xff\xdf\x3d\xef\xdc\x73\x2f\xfc\xef\xa1\ -\xd0\x82\x83\x17\xa6\xf2\x5b\x51\xef\x3b\x30\x5b\x8e\xc7\xf7\xfe\ -\x69\x7d\x14\xd2\xfc\xe8\xd8\xed\x5d\x8d\x28\x7a\x0c\xb6\x27\x6b\ -\x4e\x2e\x94\xf9\x91\xe2\xf5\xbe\xbe\xfe\x1d\x8f\x0c\x4e\xb8\xe4\ -\x05\x01\x28\x16\x17\x7b\xfa\xf3\xfb\x1e\x00\x43\xae\xb9\x01\x00\ -\x4c\xef\xf3\x9f\xef\x00\x67\x31\x30\x2c\xed\x2a\x40\xa1\x34\x77\ -\x13\x54\x06\xc3\x64\xa9\x90\x75\x0d\x60\xe0\xd2\x6c\xd5\xe0\x2a\ -\x80\x49\xce\xe6\x1d\x01\x0c\x94\x6b\x63\x88\x69\x00\x83\x54\x86\ -\xb3\xb9\x37\x40\xa1\x34\x3b\x82\xe9\x7e\xfb\x33\x15\x7e\xe6\x5e\ -\x00\x85\xd2\xcc\x49\x83\x45\xa0\x87\x96\xb1\xb7\xb9\x33\x40\xe1\ -\xe2\xf4\x31\x23\xb7\x04\xec\x6c\x1b\x3b\x75\xfc\xef\x22\xf3\x24\ -\x3c\x5e\xaa\x1d\x4e\xd1\x13\x60\xb7\x81\x29\x80\x39\x64\xac\xc0\ -\x60\x79\xea\x60\xd3\xf4\xcc\x60\x3f\x16\xce\x1c\x32\x56\x60\xcb\ -\xa2\x8f\xbf\xae\x2d\x85\x33\x87\xac\x3d\x60\xac\x84\x34\x75\x06\ -\xe8\xcd\x35\x86\x0d\x3e\xb4\x61\x82\x5d\x60\x99\x01\x5e\xcc\x5f\ -\xfe\x14\x61\x43\x82\x2f\xb4\xc6\x5d\x30\x88\xcc\x42\xaf\xe2\x89\ -\xb7\xa4\xcd\x53\xc0\x9a\x5a\x0f\x99\x20\x10\x4e\x22\xc9\xbd\xc9\ -\xd7\x22\x1d\x01\xbe\x13\x08\xc2\x59\x20\x89\xab\xcf\x05\xa3\x40\ -\x13\x10\xea\xec\x59\xe7\xb5\x83\x24\x1e\x5f\x42\x76\x1e\xd8\x6e\ -\x4a\x6f\x08\xef\x12\x2e\xcf\x4f\x2c\x08\x55\xb7\x75\xcc\xb3\x12\ -\x1d\xfd\xc3\x24\xae\xd4\x04\xb7\x00\x64\xe6\x05\xd1\x71\x13\x25\ -\x71\xe5\x9a\xc4\x5d\x10\x4a\xc9\xb5\x26\x75\x17\x01\x40\x76\x68\ -\xf5\x40\x05\x78\x88\x40\xc8\x49\x33\xc8\x59\xae\xd7\x47\x9b\x1b\ -\x5f\x57\xcf\x01\x4f\x5d\x73\x83\x4d\xb4\x37\xf5\x1b\x9b\x9b\x1b\ -\x3f\xce\x08\x5e\xfe\x15\x00\x80\x95\x85\x2b\xeb\x51\xa3\x71\x1a\ -\x58\x03\x7d\x0b\xa9\xfd\xef\xc6\x4f\x11\x32\x94\x0c\x6f\x6b\x20\ -\xde\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x95\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x47\x49\x44\x41\x54\x58\x85\xed\ -\xce\xb1\x0d\x00\x20\x0c\x03\x41\x82\x18\x2a\xdb\xc1\x42\x69\xd8\ -\x2f\xc0\x10\x46\x4a\xf3\xd7\xdb\xfa\xd6\x04\x1e\xb9\x3c\x72\x29\ -\x1f\x5d\x19\xff\x40\x00\x01\x04\x10\x40\x00\x01\xe5\x01\x43\x3d\ -\xb8\x66\xd3\x23\xab\x02\xfa\xb6\x7b\xb4\x0b\x00\x00\x50\xed\x01\ -\x74\x44\x0a\xfd\x41\x7d\x20\x9d\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x02\x21\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xd3\x49\x44\x41\x54\x58\x85\xed\ -\xd5\x3b\x8b\x13\x51\x18\xc6\xf1\xff\x33\xf1\x86\x82\xd9\x4e\x50\ -\x0b\x11\x5b\xd1\x56\xc4\x72\x36\xcd\x6a\x61\x76\xb0\x71\x51\x34\ -\x29\x2c\x64\x3f\x81\x48\xf0\x0b\x88\x82\x8d\xd9\x20\xee\x16\x42\ -\x36\x2e\xc8\x22\xce\xc6\xce\xc2\xda\xde\xc2\x4a\xb0\x71\x89\xa0\ -\x78\x21\xe7\xb1\x98\x09\xd8\x99\xcb\x30\x29\xf4\xad\x4e\xf1\x5e\ -\x7e\x9c\x73\xe6\x0c\xfc\xeb\xa1\x71\x92\xe2\x7a\x63\x17\x50\x14\ -\xf9\x64\xda\x5d\xfb\x5c\x24\x20\x1a\x33\x6f\x01\xa8\x7a\xa8\xed\ -\xc5\x95\x95\x43\xf3\x00\x00\x60\x71\xce\xdf\xf6\xf7\x92\x24\xd9\ -\x37\x17\x40\x1e\xb5\xdd\x50\x7d\x9a\x24\x49\xa5\x74\x80\x50\x30\ -\x58\x70\x65\x10\xaa\x0f\x19\xf3\x0e\x15\x06\x30\xb6\x24\x67\x6b\ -\x6e\xc5\x97\x1b\xad\x52\x01\x99\xc2\x06\x05\x00\xc4\x9d\xb8\xde\ -\x5c\x2d\x17\x90\x2b\x04\x21\x5f\xdf\x8f\xeb\x8d\xab\x25\x03\xc0\ -\x60\x69\x84\xe0\xc9\xe2\x72\x73\xa9\x54\x00\x80\x8d\x33\x0b\x15\ -\xdb\xdd\xda\x72\xe3\x42\xa9\x80\x3c\x42\x0e\x39\x10\xac\xed\x38\ -\x69\x9e\x2d\x1b\x40\x76\x14\x36\xf8\x30\xf6\xab\x5a\x72\xf3\x54\ -\xa9\x80\x9c\x11\x00\x63\x8e\x84\x40\x3f\xbe\x74\xe3\x68\xc9\x00\ -\x00\x82\x33\xcc\x09\xf6\x56\x5e\xce\x03\xf0\xc7\xd3\xe8\x33\xf3\ -\x00\xe4\xfd\xfc\x81\x5f\xe1\x58\xa9\x00\x67\xbd\x84\xf8\x14\x45\ -\xc4\xfd\x17\x9d\x8f\xe3\xd4\xed\x29\x66\xba\x23\x49\x02\x06\xd1\ -\x30\xd4\xd2\xad\xce\xfb\x71\x4b\x67\xde\x01\xe3\x88\x6c\xf8\xf7\ -\x48\x5c\x4c\xb7\x3a\xef\x26\xa9\x9f\x11\x20\x09\x09\x18\x4a\x4a\ -\xd2\xcd\xf6\x9b\x49\x3b\xcc\x02\x10\x78\x54\x7f\x7d\x67\xf3\xf1\ -\xf6\x34\x4d\xa6\x05\x68\x54\x2b\x58\xed\xf7\xda\x1b\x53\xf6\x99\ -\x0a\x20\x9c\xd7\x99\x7b\x3b\xbd\xf6\x83\x69\x87\xc3\xa4\x5f\x81\ -\x10\x81\x08\x81\xed\x47\xaf\x9f\xaf\xdd\x9d\x65\x38\x4c\xba\x03\ -\x76\x84\x00\xfb\xd9\xf9\xd3\xc7\x6f\x93\xfd\x8a\x4b\x04\x64\x0f\ -\x6d\xba\x50\xf9\x72\xad\xd5\x6a\x85\xbf\x65\x17\x0e\x90\x79\xab\ -\x83\x3f\xea\xdd\x6e\xf7\x67\x11\xc3\x61\xec\x3b\xa0\x01\x42\x8a\ -\xc2\x52\xba\xbe\xfe\xb5\xa8\xe1\xff\x03\xe0\x37\xff\xea\x99\x56\ -\xb6\x04\x03\xd2\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\ -\x00\x00\x03\x2a\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\xdc\x49\x44\x41\x54\x78\x9c\xed\ -\x99\x4f\x48\x54\x51\x18\xc5\xcf\x79\xf3\xd2\xd1\x20\x49\x88\x16\ -\x41\x50\x10\xad\xaa\x45\xe1\x9b\x30\x21\x22\x08\x25\x1a\x67\x2c\ -\x23\x5a\x54\x10\x08\x41\xb4\x69\x17\xe4\xa2\x76\x11\xb4\x0f\xd2\ -\x45\x48\x58\x8e\xe6\x62\x08\x22\x6d\xa1\x8d\xcf\x72\x51\x04\x21\ -\x14\x44\xff\x16\x25\x16\x0a\x29\xf8\xde\xfd\x5a\x84\x31\x7f\x9e\ -\x0d\x82\xf7\xbe\xa0\xfb\x5b\x7e\x07\xe6\x9c\x39\xef\x3e\xee\x9d\ -\x3b\x80\xc5\x62\xb1\x58\x2c\x16\x8b\xc5\x62\xb1\x58\x2c\x96\xff\ -\x0d\xea\x36\xf0\x72\x61\x1f\xc0\x53\x00\x40\xf2\xdc\x44\x86\xbd\ -\xba\x3d\x57\x83\xd6\x02\x0e\xf6\x48\x72\xa1\x41\x16\x4a\x86\xc2\ -\x43\x7e\x07\x47\x75\xfa\xae\x06\x47\xeb\xa7\xaf\x87\x5b\x31\xa3\ -\x8c\xec\x7b\x20\xdb\xb5\xfa\xae\x02\x03\xaf\x80\x92\xa8\xb9\x9b\ -\xe0\x86\xf1\x34\xe7\x75\xfb\x57\x43\xef\x0a\x00\xb0\x35\x60\xe5\ -\x2a\x00\x10\x84\x32\x87\x6e\xd1\xee\x5f\x0d\xed\x01\xee\x77\x32\ -\x44\x92\x0d\x51\x9a\xb7\x47\x42\xdd\xfe\xd5\x30\xf2\x04\xfc\x36\ -\xce\x39\x09\xee\x88\xd2\xbc\x9c\x1a\x33\x91\x61\x25\x8c\x2d\xc1\ -\x42\x9a\x6f\x15\x79\x38\x42\x6a\xf6\x72\xe1\x0d\x53\x39\xca\x31\ -\xfa\x0e\x3e\xcf\xf0\x89\x90\x17\x2b\x15\x5e\x4e\xe5\xe4\xb4\xc9\ -\x2c\x7f\x9c\xe3\x30\x4d\xe5\xc2\x5e\x01\xcf\x94\xcf\x1d\xd2\x2b\ -\x64\x38\x69\x32\x4b\x2c\x05\x00\x80\x97\x53\xef\x00\x54\x9c\x07\ -\xdc\x04\xb7\x8c\xa7\xf9\xc5\x54\x8e\xd8\x0a\x00\x56\x3e\x23\x38\ -\x01\xeb\x0b\x9d\x5c\x88\xd2\xd6\x9a\x58\xf7\xe1\xe0\x1b\x6b\xa2\ -\xe6\xca\x95\x9f\x10\x31\xf2\x70\x62\x2d\x60\xaa\x8b\x4b\x81\xcb\ -\x4d\x51\x9a\x37\x28\xdf\x4d\x64\x88\xfd\x24\x36\x75\x8c\x33\x21\ -\xb8\x2b\x42\x6a\xf0\x06\xc3\x7b\xba\xfd\x63\x2f\x00\x00\x5e\x64\ -\xf9\x1a\x60\x7b\x85\x20\x3c\xa9\xdb\xfb\x9f\x28\x00\x00\x1c\x85\ -\xe9\x58\x7c\xe3\x30\x2d\xc7\x7b\x28\x9b\x15\x25\x5f\x3e\x17\xc1\ -\x33\xdd\xde\xb1\x17\xb0\x77\x58\xea\x11\xca\x30\x88\x6d\x25\x02\ -\xe5\xda\x64\x87\xd3\xac\xdb\x3f\xd6\x02\x4e\xf4\x4b\xc2\x0d\xa4\ -\x0f\x40\x53\xa9\x22\xb7\xfd\x76\xa7\xdb\x44\x86\x58\x0b\xf8\xe0\ -\xaa\x9b\x00\xd2\xc5\x33\x01\x1e\xd5\x6d\x74\x2e\x80\x8c\x3c\x24\ -\xad\x35\xf1\x1d\x85\x07\xe5\x12\x44\x6e\x95\x8d\x5f\xba\x09\xb6\ -\x98\xbc\x29\x8a\xa5\x80\xa6\x01\xc9\x90\x32\x50\xe6\xff\xc9\x09\ -\x98\x2a\x74\xf2\xb3\xc9\x2c\xc6\x0b\x48\x0d\x89\x27\x4a\x46\x01\ -\xd4\x15\x8d\xe7\xa1\x78\xc0\x3f\xce\x57\xa6\xf3\x24\x4c\x9a\xfd\ -\xbe\x0d\x96\x11\x02\xc5\x57\x64\x01\xc0\xb4\xdf\xc1\x82\xc9\x2c\ -\xcb\x44\x5e\x58\xea\x60\x7f\xbf\x34\x2a\x47\xf2\x00\xca\xce\xfe\ -\xec\xf2\xb3\x7c\x6c\x2a\x47\x39\x46\x76\x81\xd6\xbc\xd4\x2a\x57\ -\x86\x00\xec\x2c\x11\x44\xae\xfb\x59\xde\x31\x91\x61\x25\xf4\x17\ -\xd0\x2d\xce\xec\xa2\xea\x01\xd0\x52\x2a\xc8\x5d\x3f\xeb\x5c\xd5\ -\xee\x5f\x05\xed\x05\x78\xbb\x71\x65\xf9\xbf\xc1\x22\x9e\x36\x26\ -\x9d\xf3\xa6\xf6\xfa\xbf\xa1\x75\x17\x68\xcd\x4b\xed\xec\xa2\xfc\ -\x00\x90\x2c\x1a\xbf\x59\x57\xc3\xe6\xb1\xa3\x34\xf2\x7b\xbf\x1a\ -\x5a\x57\xc0\xd7\x8f\x50\x00\x96\x8a\x47\x24\xdb\xfe\x95\x2f\x0f\ -\x68\x2e\x60\xaa\x8b\x4b\x04\xcf\x02\x98\x01\x30\xad\xc8\x23\x13\ -\x19\xbe\xd7\xe9\x69\xb1\x58\x2c\x16\x8b\xc5\x62\xb1\x58\x2c\x16\ -\x8b\xc5\x52\x8d\x5f\x44\x94\xcc\xbe\xc4\xf9\xa0\xab\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x9b\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x4d\x49\x44\x41\x54\x58\x85\xed\ -\xd7\xb1\x0d\x00\x20\x08\x05\x51\x34\x0e\x66\xc3\x04\xae\xc0\x98\ -\x26\xac\xe6\x06\x22\xc4\xf2\xae\xfc\x09\xc9\x6b\x11\xa1\x64\xba\ -\xcc\x75\x99\xbf\xee\x51\xa3\x60\x98\xc9\xfd\x5a\xaf\x1c\xfd\x0c\ -\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xd2\x9f\x51\ -\x13\xd9\x99\x9d\xa2\x0e\xd8\x07\x09\x21\x90\x7b\x88\xd1\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xf9\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xab\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\x31\x15\x80\x30\x00\xc4\x50\x8a\xb7\x2a\xc0\x02\xb2\xb0\x80\ -\x02\xc4\x95\x15\x07\x9f\x21\xd9\x6e\xba\xbc\x8c\x0d\x31\x8f\x73\ -\x7d\xf7\x73\x5f\x43\x78\xec\xe2\xf4\x4f\x14\x40\x0b\x68\x0a\xa0\ -\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\ -\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\ -\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\ -\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\ -\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\ -\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\ -\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\ -\x2d\xa0\x79\x01\x55\xd1\x04\x80\x1e\x3b\xba\xea\x00\x00\x00\x00\ -\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\xe8\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x9a\x49\x44\x41\x54\x58\x85\xc5\ -\x97\xd9\x76\xe2\x46\x10\x86\xbf\x66\x11\x12\x60\x50\x9c\xc4\x9e\ -\xf1\x24\x39\x59\xde\xff\x9d\x72\x31\x9e\x49\x1c\xcf\x18\x6c\x23\ -\x19\x24\xa8\x5c\xd4\xdf\xa8\x91\x71\x72\x97\xd4\x39\x1c\x89\x56\ -\xd7\xf6\xd7\xd6\x0d\x58\x09\x16\xf8\xcf\xc9\x02\x58\x19\xa4\x7c\ -\x09\xac\x21\x58\xf7\x91\x4b\x20\x1a\x96\x25\xef\x93\x44\x4a\x5c\ -\xb3\x64\x6d\x9b\xac\xed\xf4\x7e\x00\x1e\x7a\xf2\x97\xc0\x3a\xf4\ -\x16\x0e\xc0\x05\x30\x00\xaa\x44\x59\x90\x11\x13\xd8\x0d\x21\x8c\ -\x81\x71\xcf\xa5\x16\xac\x81\xac\x95\x11\x51\xb9\x01\x0d\x90\x4b\ -\xfe\x23\x30\x3c\x75\xd8\xf7\x2d\xc0\x7e\x11\x34\x63\xb0\x99\xd6\ -\x33\xb0\xf7\xf0\x50\x82\xe5\x60\x13\xb0\x82\x57\x64\x85\xbe\x4d\ -\xb5\xf7\xca\x79\xc1\xd7\x2c\x93\xec\x5f\xc1\x2e\xfa\x10\x02\xf6\ -\x01\xf8\x24\x24\x0c\x78\x01\x0a\xd8\xbd\x87\xec\xa3\xbc\x00\x58\ -\xc8\x8b\x73\x94\x7e\x9b\xc0\xee\x06\xb2\x5b\x21\x92\x4b\xdf\x1a\ -\xb8\x81\x70\x0b\x30\x92\xf2\x80\xc3\x3e\x96\xf2\x1b\xe0\xde\x19\ -\xb2\xfb\x44\xf9\x04\x0f\x91\x71\x1a\xf7\xe8\xcc\x4c\xca\xf4\xcb\ -\xbe\xc2\xa6\x80\xd9\x18\x78\x07\x7c\x94\x8e\x41\x0f\x01\xfb\x4e\ -\xff\x2b\x08\x15\xd8\xb5\xbe\xfd\x09\xcc\x1d\x8d\xd5\x0c\x4a\x5c\ -\x70\xa8\xcf\x03\x60\x73\xa0\xc5\xf3\xa5\xd2\xf3\x80\x27\xf4\x0e\ -\x78\xc2\xe3\xff\x0d\xb0\x82\xb0\x19\x25\xdc\x63\x29\xcf\xe5\xdd\ -\x1a\xb8\x92\xc5\x39\x94\x4f\x82\x71\x02\x66\x1d\x0f\x24\x08\xe5\ -\xc0\xb3\x94\x95\x42\x38\x03\xee\xf0\xf0\x64\x10\x9e\x12\x07\x3b\ -\x28\xdc\x52\x9b\xc0\xcb\xb5\x18\x83\xa0\x5c\x48\x68\xa4\x39\x1e\ -\x86\xb9\xf8\x07\xfa\x1f\xd7\x22\x6d\xc4\xbb\x93\xac\x00\xdb\xf7\ -\x4a\xcc\x63\xee\xc5\x10\xbc\x73\x41\x15\x30\xfd\x8c\xc7\xb2\x96\ -\xf5\x23\xc1\x56\x43\x75\x09\xd3\xb5\x23\x75\x8e\x6c\x21\x99\x35\ -\x30\x95\x03\x53\xba\xd2\x1b\x49\xf6\x1c\x0f\xc1\x97\x14\x81\x09\ -\xb4\x2f\x49\x6d\x16\x8a\xb5\xe1\x96\x5d\xc3\x74\xe5\x48\xbd\x49\ -\xb1\xce\xbf\x17\x8f\x09\x89\x58\xb6\x2d\x3c\x36\x78\xe8\xfa\x21\ -\x68\x4a\x58\x3c\x74\xc6\x30\x54\x3e\xe4\x78\xd2\xfc\x25\xc1\x85\ -\xfa\x41\xee\x49\x67\xb3\xee\x3f\x05\x9e\x37\x5f\x61\x73\x29\xde\ -\x3c\x91\x09\x2c\x9e\x49\x42\x15\x0d\xc8\xbc\x8b\x91\x0b\xc6\x52\ -\x1e\xb4\x62\x5c\xe1\x89\xf6\x20\x48\x73\x3d\x83\xa0\x9d\xba\x0c\ -\xa6\xae\x9c\x06\x66\x0f\xda\xd7\xe2\x3d\xe5\x12\xef\x31\x43\x68\ -\x4c\xfb\x63\x1f\x20\x40\x50\xd7\x0a\x8f\xde\xb9\x82\x32\xdb\x0c\ -\x82\xfa\xbb\x35\x12\x36\x06\xee\x7b\xbd\xfd\xca\x8d\x8e\x7c\xb4\ -\x60\x7b\x7f\x86\x1d\xd8\x33\x5e\x86\x03\xba\x24\x3f\xa9\x82\x61\ -\x52\xdf\x49\x93\xa9\xd3\x3d\xda\xc7\xbd\x7b\x63\xe9\x30\xbb\x4b\ -\x1c\x8a\x94\x4e\x59\xc9\x0c\x55\xe7\x6c\xc7\x30\x82\xf1\x21\xf1\ -\x86\xe4\xbd\x4d\x84\x8c\x80\xc6\x3d\xb7\x35\xea\x4c\x78\x46\x5b\ -\xd2\x1f\x52\x4a\x1d\x78\x35\x3d\x07\xc9\x73\x7f\x86\xb9\x4f\x87\ -\x9e\xc0\x3e\x9d\x6b\xcf\x96\xbc\xbf\xda\x17\x85\xed\xa0\x51\x57\ -\x0b\xd6\x6d\x0e\x06\xf5\xb0\x67\xc0\x30\x81\x7d\xa5\xdf\x32\x99\ -\x27\x7d\x83\x4f\x46\x6e\xdf\x98\x94\xa1\x55\x29\xf5\xac\x2d\xfa\ -\x75\xdf\xe2\x09\xa7\x79\x1e\x62\xdb\xbe\xa6\x3b\x03\x44\x0a\xaf\ -\xdf\xad\x00\x3b\xee\x8b\x39\x60\xca\x70\x53\x19\xce\x34\x58\xc0\ -\x4b\xb3\x94\xe2\x02\x6f\xb9\x6a\x36\x96\x42\xdc\x00\xdf\x4a\xb8\ -\x49\xb6\x0e\x21\x16\x3b\x20\x32\x76\x1f\xf9\xa2\x01\x3b\x08\x43\ -\x95\xdb\xd6\x0f\x24\x34\xfe\xdf\xc0\x33\x7f\x23\x21\x9f\xff\x61\ -\x1a\xee\x38\x9e\x76\xd6\x25\x2c\xef\x3a\x07\x79\xc0\x4b\x38\xee\ -\xd9\xc1\x49\x08\xc6\x75\xe2\xf5\x16\x35\x0a\x51\x05\x2f\x3f\xc9\ -\xf3\x73\x99\x7e\xb4\x40\x1e\x7e\x80\xe5\x53\xb7\xbc\x2a\xa4\x1c\ -\x37\x6c\xbc\x89\x5f\x06\x09\xe3\x06\xea\xb2\x63\xa2\xf6\x86\x14\ -\x0f\x1a\xf9\x2d\x3e\xdd\xfa\x67\xc1\x94\x22\xd4\x7f\xe0\xed\x36\ -\xf8\xb3\x4c\x86\x57\x36\x93\x31\x27\x21\xd8\xfb\xe6\xe2\x19\xec\ -\x86\x6e\xe0\x14\xf8\x49\xe6\x77\x3c\x9e\x7b\xa0\x74\xa4\xea\x41\ -\x97\xa0\xf5\x50\x02\xd5\x21\x8f\x7b\x7f\xc6\xbb\x9f\x8e\x77\x2c\ -\xa1\xb8\x95\xcc\x6d\x6a\x00\x6e\x40\x78\x06\x1b\xd0\xc5\x7c\x24\ -\x6f\x0e\x10\x36\x60\x2d\xf0\x0c\xe1\xe5\x3c\x00\x36\x77\x19\xa0\ -\x83\xeb\x67\x7c\x96\x6c\x24\x73\xe5\xf9\xd3\x45\x31\x0d\x41\xe3\ -\x93\x2d\x3c\x42\x7d\xe1\x9e\xb2\x96\xf5\x5b\xe5\xc7\x71\x8c\xbe\ -\x4d\x36\x56\xe8\x1a\x3c\xd1\xd6\xc0\x25\x54\x33\x47\xc3\x66\x5a\ -\x3f\x09\xc1\x57\xe0\x07\xdf\x6c\x4b\x60\x06\x2f\x41\x93\x74\x42\ -\x67\xb2\x0e\x97\x55\x05\x85\xd1\x75\xcf\xd8\xac\x0a\x3c\xdb\x77\ -\x38\xf3\xc2\x8d\xaf\xa7\x30\x9d\xe3\x13\x76\xe3\x8e\x87\x4d\x62\ -\x40\x30\xb0\x03\x5e\xeb\x01\xf8\x04\x45\x34\x86\x0e\x56\xf0\x30\ -\x4c\x75\xf4\x36\x21\x18\xe2\x1c\x59\x38\x82\xc7\xbd\x17\x6e\xcc\ -\xf4\x8b\x64\xc5\xd9\x72\xee\x50\x63\x17\xba\x34\xf4\x2f\x26\x0b\ -\xa8\x7e\xec\x2e\x23\xff\x76\x31\x01\xe7\xad\x3e\x74\x65\x7d\x72\ -\x31\xf9\xed\xcc\xc5\xe4\xd8\xdb\xf7\x82\x6d\x20\x2b\x33\x1c\xfe\ -\x81\x7f\x6f\x32\x79\x30\x84\x71\x7a\xf7\xcb\x75\x30\x6e\x7d\xd4\ -\x8e\x6a\xbc\x67\xec\xc5\xdb\xd0\x0d\xa6\x35\xc9\xd5\xec\x8d\xcb\ -\x69\xf4\xe2\x98\x70\xc3\xe4\x7d\xa2\xf7\x09\x6c\x35\x3b\x26\x95\ -\x94\x18\xdd\xe5\x54\x06\xb9\xb0\x18\xf3\x9e\xc3\x6b\xf8\x9f\xaf\ -\xe7\x7f\x03\x88\x7c\xd3\x3b\xed\x32\x4f\xdf\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x27\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xd9\x49\x44\x41\x54\x58\x85\xe5\ -\x96\x31\x6b\x54\x41\x14\x85\xbf\x33\x59\x45\x09\x2a\x5a\xd8\x58\ -\x58\xd9\x58\x88\x4d\xd8\xa4\xb1\x4c\x40\x09\xb8\x89\xae\x95\x01\ -\x3b\x1b\x21\x3f\x40\x2c\x42\x7a\x11\x04\x4b\x21\xa9\x7c\xba\x89\ -\x10\x2c\xa2\x9d\x8d\x59\xd3\x48\x0a\x1b\x41\x04\x4d\x63\x67\x64\ -\x51\x92\xec\x1c\x8b\x65\xc1\x4a\xdf\xbc\x37\x28\xe8\xa9\xe7\x9e\ -\xfb\xdd\x3b\xf7\xce\x7b\xf0\xbf\x4b\xb9\x0d\x27\x0a\x9f\x88\x0d\ -\xbf\xb7\xf0\xeb\x56\x38\xfe\xbb\xf3\x8d\x9c\xc9\xcf\xad\x7b\x34\ -\xf6\xfc\x0c\x38\x26\x97\x8b\x09\xb9\x92\x9f\x2d\x7c\xf0\x70\xcf\ -\x2b\xc0\x78\x4a\x5c\x16\x80\xab\x85\x47\x8e\x1c\x88\x4b\xc0\x64\ -\xc9\xc2\x33\x02\xd8\xfa\xd8\x88\xf7\xb1\xae\x61\x23\x13\xff\x28\ -\x40\x73\x25\x2e\x18\xdd\x04\x83\x14\x11\x49\x4d\xa8\x05\xd0\xec\ -\x78\x1e\xe9\x36\x80\xad\x08\x69\xc9\x6b\x01\x34\x3b\xbe\x8e\x7c\ -\x97\x41\xd6\xa8\xc4\xca\x6b\x01\x8c\x3f\xf5\x34\xf2\x43\x18\x54\ -\xae\x0a\x95\x0f\x95\xfc\x0e\x8c\x75\x7c\xc1\xd1\x05\x30\x62\xec\ -\xaa\x95\x0f\x95\xd4\x81\xb1\x55\x9f\x0f\xf2\x1a\x70\x08\x6c\xa1\ -\xa4\x89\xaf\x05\xd0\x7c\xe2\x33\xc1\x5e\x07\x8e\x5a\x98\x0c\xc9\ -\x4b\x03\x4c\x14\x3e\x45\xf0\x0b\xe0\x24\xc2\xa9\xbb\xfe\x2b\x95\ -\x9a\x81\xd8\xf0\x27\x00\x63\x72\xb4\xfd\x67\x95\xbd\x82\x2d\x80\ -\xb2\x1f\x98\xec\x00\x61\x5f\x17\x81\x0f\x48\xa5\x63\xb2\x02\xbc\ -\x6a\x6b\x9b\xa8\x49\xe0\x33\x46\x56\x3e\x88\xd2\x46\xdd\x2b\x7a\ -\x17\xa5\x29\x60\x47\x46\xc6\x59\x20\x92\x4c\x36\x5b\x7a\x13\xad\ -\x69\xe0\xbb\x50\x16\x88\x64\x83\xcd\x59\xbd\x54\x50\x1b\xe8\x0f\ -\x20\x54\xeb\xb7\xae\x52\x05\x1b\x97\xb5\x86\x75\x03\x40\x83\x2e\ -\x54\x86\xa8\xdc\xc2\xee\xac\x96\x91\xe6\x87\x3e\xae\x08\x51\xeb\ -\x0e\xbb\x2d\xdd\xc3\x5e\x04\x50\x45\x88\xda\x43\xd4\x9d\x09\x77\ -\x6c\x3f\x00\x90\x9d\x0c\x51\x7f\x95\x24\x9f\xee\x87\x5b\xc8\x8f\ -\x90\x90\xd3\x36\x23\xcb\x2e\x3f\x6e\xab\xff\x75\x2f\xcc\x01\xcf\ -\x53\x97\x22\xdb\x8b\xf6\xb6\xad\xdd\x6f\xa3\x9a\x01\x36\xfe\x0a\ -\x00\xc0\xd6\x94\x7a\x61\x5f\x97\x90\x77\x6c\xbe\xe4\xf4\xfe\x77\ -\xf5\x03\x8b\xca\xad\x03\x49\x73\x42\xef\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\xd8\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\x8a\x49\x44\x41\x54\x58\x85\xe5\ -\x96\x3d\x72\xd3\x40\x18\x86\xdf\xd7\x49\x01\x9c\x83\x12\x5a\x4b\ -\x70\x05\x0a\xa2\x35\xc4\x21\x24\x71\xfe\x66\xc2\x01\x32\xc3\x19\ -\x28\xd3\x51\x24\x01\x3b\xe4\xd7\x48\xce\x0c\x67\x60\xc6\xd6\x21\ -\xa0\x83\x1b\x00\x05\xd6\x4b\xe1\x28\xc8\x2b\xc9\x92\x3c\x6a\x18\ -\xbe\x4a\x5a\x7d\xfb\x3e\x8f\x77\x25\xcf\x02\xff\x7b\x31\xbe\x78\ -\x74\xad\xc7\x51\xa4\xb7\x10\xee\x92\x7c\x3d\x34\x0c\xea\x04\xb9\ -\x81\x8c\xa4\x37\x24\x7e\x41\x7c\x35\x6c\xf1\x33\x00\x34\xe2\x86\ -\x28\xd2\x11\x80\x87\x20\xee\x0b\xea\xbb\xbe\xda\x75\xc1\x9d\x40\ -\x2b\x82\xfa\x93\x6c\x3c\x10\x75\x18\x3f\x6b\x24\xfa\xee\x24\xae\ -\x1b\xa2\xce\xea\x90\x70\x02\xad\x00\x3a\x4d\xb2\x48\xdc\x4b\x0b\ -\x90\xfb\x00\xa2\x3a\x25\x26\x73\xa7\xe1\x00\xa2\x48\xdc\x4f\x09\ -\x8c\x3c\xfa\x22\xd7\x32\x24\x4e\xe7\x91\x70\x7d\xb5\x45\x9d\xd9\ -\x70\x90\x9d\xd0\xb0\x9f\x12\x00\x80\xd0\xe3\x79\x86\xc4\x42\x55\ -\x89\x1b\x78\xea\x97\x83\xec\x8c\x3c\x7e\x48\xf6\x36\x60\x55\xe8\ -\xf1\x5c\xe2\x7a\xa6\xc4\x40\xcb\x85\xf0\x81\x96\x6f\xe0\x0b\x45\ -\x70\x20\xf1\x19\xda\xd5\xf4\xb5\x4a\xea\xc4\x92\x1c\x93\x5c\x1d\ -\x7a\xbc\xca\x85\x4b\x67\x16\x5c\x20\x37\xb2\xe0\x33\x05\x00\xc0\ -\x0d\xf4\x52\x50\xaf\x8c\x44\x33\xd0\x73\x42\xe7\x55\xe0\x85\x02\ -\xb3\x24\x04\xbe\x88\x5f\xa6\x79\xe1\xa5\x04\x00\xc0\x19\x68\x0d\ -\x52\x37\x4b\x62\x12\x92\x01\x17\x3b\xa3\x16\x4f\x8a\xb2\x4b\x09\ -\xe4\x49\x48\x88\x40\x80\xd3\x62\xa5\xe1\x95\x04\x12\x12\xbd\x19\ -\xf3\x2a\xc1\x2b\x0b\xdc\x4a\x00\x3d\x48\xf6\x5c\x09\xdc\x0c\x0d\ -\x7b\x55\xf2\x52\xff\x03\x25\xea\xa7\x24\xd9\x83\x02\x44\xe1\x47\ -\xd5\xb0\x4a\x02\xce\x40\x2d\x48\x17\xcc\x98\x47\xa0\x01\xea\xc2\ -\xf1\xf5\xac\x4a\x66\xe9\x2d\x70\x03\x19\x41\x97\x00\x16\x13\xc3\ -\x02\x09\x6b\x3b\xc6\x20\xdb\x23\x8f\x7e\x99\xdc\x52\x2b\x90\x07\ -\x17\xb8\x25\x61\x13\x40\x72\x4b\x16\x20\x5d\x3a\x03\xb5\x6a\x11\ -\x68\xfa\xf2\xf2\xe0\xa1\x61\x37\x34\xec\x09\xdc\x9a\x57\x62\xa6\ -\x40\xd3\x97\x47\xea\xca\x86\x93\xdc\x0e\x0d\xbb\xf1\x40\x68\xd8\ -\xcd\x91\xb8\x28\x92\xc8\x15\x98\x05\x1f\x7a\x7c\x6f\xf7\x87\x86\ -\x5d\x92\xdb\x96\xc4\x62\x91\x44\xe6\x4b\xd8\x1c\x68\x89\x52\xbf\ -\x2c\x3c\x59\xee\x40\x9b\x92\x8e\xad\xec\xdf\x04\xdb\x59\x07\xdd\ -\xd4\x0a\xe4\xc1\x01\xee\x14\xc1\x01\x60\xd2\xc3\x1d\x58\x2b\x21\ -\xe8\xd2\x0d\x64\xec\xfe\xa9\x15\x70\x02\x3d\x05\xf4\x31\x0b\x3e\ -\x32\x7c\x57\x04\xb7\xb2\xb6\x00\x1d\xa1\x60\x25\x6e\x1f\x36\x7d\ -\x3d\x21\x75\x5d\x07\x3c\x21\xb1\x0d\xe8\x30\x25\xd1\xa0\x19\x2e\ -\xf1\x13\x30\x75\x2a\xd6\x41\x06\x7c\x77\x5e\x38\x00\x8c\x0c\x8f\ -\x01\xee\xc2\xde\x8e\xb1\x0e\xe2\x9b\xbf\x67\xf5\xe9\x33\x60\x0c\ -\x3f\x9e\x17\x5e\x20\x31\x4e\x09\x40\xdc\x03\xf0\x05\xc0\x77\x88\ -\x9d\x3a\xe0\x53\x12\xe4\x06\x80\x6f\x10\xbe\x8a\xdc\xab\x2b\xfb\ -\xdf\xaf\x3f\xf0\x88\x83\xb8\x80\x8e\x5a\x2b\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xa4\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x56\x49\x44\x41\x54\x58\x85\x63\ -\x60\xa0\x00\x58\xac\xfd\xdb\x60\xb1\xf6\x6f\x03\x25\x66\x30\x51\ -\xa2\x99\x1a\x60\xd4\x01\xa3\x0e\x18\x75\xc0\xa8\x03\x46\x1d\x30\ -\xea\x80\x01\x77\x00\x0b\xe5\x46\xfc\x77\xa0\xa4\x4a\x1e\x0e\x21\ -\xc0\x78\xe0\x44\x30\x73\x03\xb9\xba\x07\x3c\x04\x46\x1d\x30\xea\ -\x80\x51\x07\x8c\x3a\x60\xd4\x01\xa3\x0e\x18\x70\x07\x00\x00\x30\ -\xcb\x0b\x07\x89\x28\x47\x47\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x03\xf0\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\xa2\x49\x44\x41\x54\x78\x9c\xed\ -\x97\xbd\x6f\x1c\x45\x18\xc6\x9f\x67\x6e\xb1\x8c\x94\xd0\xc4\x29\ -\xa2\xfb\x8e\xb0\x30\x35\xa1\x87\x20\x2c\x94\x0a\xa7\x4c\x07\x51\ -\x04\x7f\x00\x10\x51\x44\x08\x21\x21\x3e\x6a\xa4\x28\x31\xe9\x10\ -\x05\x08\x68\x88\x25\x4b\xe0\x02\x3a\xa0\xc6\x91\x89\x76\x76\xf7\ -\x4e\x29\x9c\x8e\x02\x07\xdf\xcd\x43\x71\x32\xba\xdb\xdd\xf3\x7d\ -\xf8\xf6\x9c\x8f\xf9\x95\xf3\xee\x3b\xf3\xbc\xcf\xbe\xbb\x33\x03\ -\x78\x3c\x1e\x8f\xc7\xe3\xf1\x78\x3c\x1e\x8f\xc7\xe3\xf1\x78\x9e\ -\x2c\x78\x5c\x0b\x5b\x9b\xac\x81\xf8\x02\xa0\x01\x71\xb3\x51\xab\ -\x5c\x3b\x0e\x1d\xc7\x62\x40\x14\x25\x57\x04\x5c\x07\x60\xfe\x1f\ -\x14\xae\x34\x1a\xd5\xf5\x79\x6b\x31\xa3\x1f\x99\x2d\x51\x94\x5c\ -\x15\x70\x23\xb3\x36\x71\x33\x8a\x92\xf7\xe6\xad\x67\x6e\x1d\x20\ -\x89\x51\xd2\xfa\x0c\xc2\x3b\x23\x1e\xfd\xbc\x5e\xab\x5c\x25\xa9\ -\x79\xe8\x9a\x8b\x01\x92\x82\x28\x6a\xdf\x00\xf5\xc6\x58\x09\xc4\ -\xad\x7a\xb5\xf2\x16\xc9\x4e\xc1\xd2\x8a\x37\x20\x0c\xc3\x45\x32\ -\xf8\x1a\xc4\xeb\xfd\xe3\x02\x40\xc8\xa9\x27\xc1\x64\x84\x10\xdf\ -\xab\xdb\xb9\xd4\x6c\x36\xf7\x8a\xd4\x57\xe8\x3f\x60\x67\x67\xe7\ -\x19\x9a\xe0\x76\xa6\x78\x01\x04\xba\x00\x45\x40\x04\xba\x99\x7e\ -\x17\xd6\x68\x82\x1f\xb7\xb7\x77\x4f\x16\xa9\xb1\xb0\x0e\xd8\xb9\ -\x77\xef\xf4\x53\xff\x76\x36\x00\xbc\x30\x10\x90\x00\x9a\x6e\xaf\ -\x07\x52\x52\xe4\x4a\x60\x46\xd2\xef\xfb\x0b\xc1\x85\xe5\x33\x67\ -\x76\x8b\xd0\x59\x88\x01\x77\xef\xb6\x6b\xa5\xc0\x6d\x02\x78\x2e\ -\xb5\x9a\x00\x3a\x68\xd8\xff\x8d\x00\x65\xa0\x8c\xae\x3b\x9d\xc0\ -\xbc\xfa\x6c\xb9\x9c\xcc\x5a\xeb\xcc\x0d\xb0\xd6\x3e\x0f\x96\x36\ -\x01\x54\x52\x2b\x09\x82\x1b\x53\x94\x51\x4a\x1b\x81\xc4\x39\xb3\ -\xda\x6c\x96\xb7\x67\xa7\x76\xc6\xff\x80\x38\x8e\x5f\x04\x4b\xbf\ -\x20\x5d\x3c\xc6\x2f\xbe\xf7\x30\x1c\x30\xb8\x0d\x0a\xa8\xd2\xb8\ -\x5f\xe3\x38\x3e\x37\x0b\xad\x07\xcc\xcc\x80\x28\x6a\xbd\xe2\xc4\ -\x9f\x01\x9c\x4a\x85\x44\x8e\x5f\xfc\x01\xa4\x1c\xb2\xdf\xca\x29\ -\x27\x6e\x59\xdb\x3a\x3f\xb5\xd0\x14\x33\x31\xc0\xda\xe4\xa2\xa0\ -\xdb\x00\x4e\x0c\x04\x04\x01\x70\x43\x3f\xf9\x43\xe8\xe5\xd0\x41\ -\x99\xec\x13\xa0\x36\xac\x4d\xd6\xa6\x53\x3b\xc8\x91\x0d\xb0\x36\ -\xb9\x0c\xe2\x1b\x00\x0b\x03\x01\xd2\x61\x8a\x37\x9f\x81\x74\x20\ -\xd3\xf3\x2c\x80\xf8\xd6\xda\xf8\xcd\xa3\x4e\x7f\x24\x03\xac\x4d\ -\xde\x05\xb1\x9e\x9e\x87\x40\xde\x9b\x9b\x1e\xa9\xb7\x7b\x0c\x62\ -\x40\x7e\x69\x6d\x3c\xea\x68\x7d\x28\x53\xed\x02\x92\x68\xe3\xd6\ -\x27\x04\xf2\x2e\x2f\x0e\xd9\x4d\x7e\x56\x10\x39\x2f\x4d\xc0\xa7\ -\x8d\x5a\xe5\xfd\x69\xee\x0f\x13\x1b\x20\x29\x88\x92\xd6\x75\x08\ -\x97\x73\x84\x38\x16\x57\xfc\xc1\x1a\x64\x7e\xe7\xae\xd7\x6b\x95\ -\xb7\x49\x76\x27\x99\x6f\x22\x03\xc2\x30\x5c\x64\x29\xf8\x0a\xc2\ -\xc5\x8c\x30\xc1\x91\xc5\x16\xdf\xb7\x16\xc9\x1c\x13\x88\xef\xf6\ -\x1f\xec\x5d\x5a\x5e\x5e\x7e\x30\xee\x5c\x63\x1b\xb0\xbd\xbd\x7b\ -\x72\xf1\xe9\xbd\x1f\x00\xe4\x6c\x41\xca\xec\xdb\xc5\x23\x02\xcc\ -\xeb\x84\x9f\xf6\xfe\x59\x5c\x5b\x59\x39\xfd\xf7\x38\xb3\x8c\x65\ -\x40\xbb\xdd\x5e\xda\xef\xb8\x0d\x00\x03\x87\x10\xf5\xfa\x71\xa2\ -\x96\x9b\x35\x12\x4a\xe9\xeb\x83\x80\xdf\x16\x02\x73\xa1\x5c\x2e\ -\xdf\x1f\x95\x3f\xd2\x80\xbf\xda\xed\x6a\xd0\x71\x9b\x00\x56\x06\ -\x12\x09\x69\x82\xd3\x5d\x91\x90\x30\xca\xdc\x1f\xf4\x67\x50\x32\ -\xab\x95\x4a\xa5\x75\x68\xee\x61\xc1\x30\x6c\xaf\x18\xe3\x36\x05\ -\x54\x53\x69\xea\xb5\xfd\xc3\x04\x4d\xef\xb3\xe8\x1f\x42\xec\x3a\ -\x66\xf5\xec\xd9\xf2\x9d\xa1\x59\xc3\x02\x71\x1c\x9f\x73\xe2\x06\ -\x80\xa5\x54\x48\xc0\xc3\xf1\xe6\x73\x30\xc8\xd6\x74\x9f\x70\xaf\ -\xd5\xeb\xf5\x3f\x86\x25\x64\xb0\xb6\xf5\xb2\x13\xb7\xf0\x68\x15\ -\x0f\xe4\x9f\x41\x96\x04\xb3\x15\x86\xc9\x4b\x79\x09\x99\x0e\xb0\ -\x71\x7c\x0d\xe2\x87\x79\xb1\x47\x1c\x81\xfa\xa0\x51\xab\x7d\xd4\ -\x3f\x98\x29\x32\x8a\x92\x8e\x80\xd2\xfc\x74\xcd\x0f\x02\xdd\x7a\ -\xbd\x1a\xf4\x8f\xe5\x1d\x2b\x1f\x5b\xf2\x6a\xcb\x18\x60\xc8\x8f\ -\x73\x2e\x1e\x8f\x01\x74\xbd\xda\x3c\x1e\x8f\xc7\xe3\xf1\x78\x3c\ -\x1e\x8f\xc7\xe3\xf1\x78\x3c\x4f\x36\xff\x01\x8b\x04\x4e\x83\xb0\ -\x2f\x88\xa2\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\x2d\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\xdf\x49\x44\x41\x54\x78\x9c\xed\ -\xd5\x3f\x88\x14\x67\x18\xc7\xf1\xef\x33\xb3\x77\x08\x7a\x68\x93\ -\x10\xdd\x99\x9b\x59\xb7\x10\xe2\x35\x91\x2b\xa2\x42\x8a\x20\x01\ -\x95\x24\x58\xd8\x48\x34\x29\x44\xb0\xb0\x08\x81\x60\x0a\x91\x40\ -\x0a\xc1\x10\xb0\x11\x42\x6c\xa2\x45\x24\x11\x84\xc4\xc4\x34\x16\ -\x11\x2e\x68\x63\x75\x58\x68\x74\xde\x99\x59\x41\xcf\x53\x38\x14\ -\x3d\x6f\xdd\x7d\x52\x48\xc2\xde\x70\xfe\xe1\x66\x76\x15\x7c\x3e\ -\xe5\xfb\xcc\xfb\xdb\xe7\x7d\x66\x5f\x06\x8c\x31\xc6\x18\x63\x8c\ -\x31\xc6\x18\x63\x8c\x31\xc6\x18\xf3\xba\x90\xb2\x01\x69\x9a\xbe\ -\xad\x78\xc7\x81\x3a\xca\x77\x51\x14\x7c\x2b\x22\x5a\x41\x6f\x0b\ -\x72\x2e\xdf\x86\x70\x18\x00\x65\x5f\x1c\x87\x67\xcb\xe4\x55\x30\ -\x80\xfc\x2f\x85\xf7\x7a\x96\x4e\xdc\xbf\x37\xb3\x7b\x6c\x6c\x6c\ -\xae\x6c\x76\x2f\x55\x95\x2c\x6b\x7d\xa9\x70\xa8\x67\x79\x66\xfa\ -\xf6\xad\x37\xc6\xc7\xc7\xdb\x8b\xcd\xf5\x4a\x37\x86\x14\x33\x76\ -\x2e\x1b\x59\xfe\x67\x92\x24\x2b\xca\x66\xff\xff\x1b\xaa\xb5\x2c\ -\xcb\x8f\x16\x0e\x0f\x15\xbc\xc0\xd2\x01\x59\x96\x8d\x75\x55\xce\ -\x01\x6f\x16\x4a\x97\xbb\x1d\x7f\xcb\xea\xd5\xab\xd2\x32\xf9\x53\ -\x53\x53\xcb\x1e\x3c\x7c\x74\x12\xd8\x5a\x28\x3d\x12\xbc\xed\x51\ -\x54\xff\xad\x4c\x7e\xe9\x01\x00\x38\xe7\x1a\x88\x7f\x16\x58\x53\ -\x28\xdd\x44\xfd\xad\x71\xbc\xea\xd2\x22\x73\x57\x22\xde\x19\x90\ -\x75\x85\xd2\x5d\xc1\xfb\x28\x8a\xea\x13\x8b\x6a\xb8\x47\xe9\x2b\ -\x00\x10\xc7\x71\xe2\x7b\x6c\x10\x38\x5f\x28\xbd\x85\x74\xce\x3b\ -\xd7\x2a\xbe\xbd\xe7\x4a\xd3\x74\x2d\x9e\x7f\x61\x81\xc3\x5f\xef\ -\xf8\xb2\xbe\x8a\xc3\x43\x45\x03\x00\x08\xc3\xf0\xee\xdc\xdc\xec\ -\x07\x28\x3f\x15\x4a\x4b\x11\xfd\x35\xc9\xb2\xbd\x2f\x9a\xe5\x5c\ -\xeb\x7d\xc5\x9b\x40\x19\x9d\x57\x50\x2e\xb6\x87\x6b\xef\x36\x83\ -\xe0\x4a\x15\x3d\x43\x45\x57\xa0\x97\xaa\x7a\x59\x96\x7f\xa3\xc8\ -\x57\x0b\x94\x0f\x47\xa3\xc1\x7e\x11\xe9\x3e\x6d\x7f\x9a\xb6\x76\ -\x29\x7a\x0c\x18\x9a\x57\x10\x4e\x0f\xf9\xde\x27\xf5\x7a\xfd\x41\ -\x95\xfd\x56\x3e\x80\xff\xa4\x69\xbe\x47\xe1\x28\xe0\xf7\xae\x2b\ -\xfa\x33\xdd\xce\xa7\x8d\x46\x63\x76\xde\xfa\x93\xcf\xdc\x01\x85\ -\xaf\x8b\x59\x0a\x47\xe2\xd1\xe0\x0b\x11\xe9\x54\xdd\x67\xdf\x06\ -\x00\xe0\x5c\xbe\x19\xe1\x17\x60\xe9\xfc\x8a\x4e\xd4\x7c\xef\xe3\ -\x20\x08\xee\x00\x4c\x4e\x4e\x0e\x8f\x8c\xac\xf8\x5e\xd1\xcf\x0a\ -\x11\x2a\xf0\x79\x14\x85\x47\xfa\xd5\x63\x5f\x07\x00\xe0\xdc\x8d\ -\x77\x90\xee\xef\xc0\xca\xde\x75\x85\xab\xbe\xe8\xe6\x76\xbb\x3d\ -\xed\xd7\x86\x4e\x81\x6c\x2a\x6c\x9d\x45\xd9\x11\xc7\xe1\xe9\x7e\ -\xf6\xd7\xf7\x01\x00\x5c\xbb\x76\x63\xd4\xaf\x75\xff\x00\xd6\xbe\ -\xe0\x96\x69\xed\xca\x87\x8d\x46\x70\xa1\x9f\x7d\x41\x85\x5f\x81\ -\x67\x69\x36\xeb\x59\xe7\xf1\xdc\x46\xe0\xdc\xf3\x9e\x55\xb8\xea\ -\x7b\xac\x1f\xc4\xe1\x61\x40\x03\x00\x68\x36\x9b\x33\xf7\xef\xcd\ -\x6c\x11\xf4\xc7\x67\x3c\xf6\xf7\x70\xcd\xdb\x10\x86\xe1\x3f\x83\ -\xea\x6b\x20\x57\xa0\x97\xaa\x8a\xcb\x5a\x07\x05\x0e\x16\x4a\xa7\ -\x7c\x8f\x5d\x61\x18\x3e\x1c\x74\x4f\x2f\x85\x4b\xf3\x1f\x5c\x9a\ -\x3f\x76\x69\xde\x4e\xd2\xfc\x90\xaa\x0e\xec\xdf\xf8\xca\x50\xd5\ -\x5a\x92\x24\x4b\x5e\x76\x1f\xc6\x18\x63\x8c\x31\xc6\x18\x63\x8c\ -\x31\xc6\x18\x63\xcc\x6b\xe2\x5f\xd1\x80\xf4\xd2\x90\x91\xe7\x38\ -\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x2d\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xdf\x49\x44\x41\x54\x58\x85\xe5\ -\x96\xb1\x6b\x14\x51\x10\x87\xbf\xdf\xbb\x43\x82\x82\x47\x2c\x6c\ -\xac\xed\x2d\xad\x2c\x24\xb7\x01\x25\xcd\xc5\x8d\xd5\x05\x64\x15\ -\xd3\x08\xf9\x03\xc4\x42\xec\x45\x10\x54\xe2\x21\x78\x95\xae\x77\ -\x4d\xb0\xf0\x36\x58\x58\x59\x8a\xad\x20\x16\xda\xd8\xe8\x05\x0c\ -\x41\x72\x6f\x2c\x56\xc5\x4a\xf7\xed\x3e\x22\xe8\x74\x03\x3b\x33\ -\xdf\xfc\x76\xe6\x31\xf0\xbf\x9b\x62\x27\x5c\x4c\xb3\x23\xde\xeb\ -\x2d\x60\xc5\xe8\xfe\xfc\x9f\xbe\x6f\xc7\x2c\x9e\xf4\xfb\x87\xfc\ -\x8e\x9e\x02\x9d\xaa\x31\x2e\x56\xf1\x34\x4d\x0f\xd8\xce\xdc\x18\ -\x38\x19\x12\x17\x05\x20\x4d\xd3\xd6\x27\xdf\x79\x08\x96\x84\xc6\ -\xc6\x00\xd0\x67\xdf\xb9\x2d\x38\x8f\x01\xe0\xf7\x15\x60\xe1\x5c\ -\x76\x1d\x58\xc3\x00\x27\x0f\xdf\x31\x2a\x5a\xa3\x21\x5c\xe8\x5d\ -\x5c\x97\x71\x15\x00\xc9\x63\x16\x54\x1c\x1a\x28\xd0\xed\x65\x7d\ -\x89\x9b\x3f\x8b\x13\x5e\xbc\x36\x40\xb2\x9c\x2d\x21\x3d\x28\xbd\ -\x7a\x9d\xd7\x06\x48\x7a\xd9\x29\x43\x8f\x81\x96\x61\x56\xb7\xf3\ -\x5a\x00\xdd\xf4\xd2\x09\x93\xdb\x04\xe6\x30\x33\xa1\xa0\x89\x6f\ -\x04\xd0\x5d\xbe\x7c\x1c\x6f\xcf\xc0\x0e\x1b\x58\xf9\xdf\x9b\x5b\ -\x25\x80\xd3\xe9\xda\x31\x98\x15\xc0\x51\xc0\x14\xb8\xeb\xbf\xb3\ -\x4a\x6b\xd8\xf2\x7b\xef\x7f\x71\xa3\x15\x87\x8a\x0a\x08\x5e\x43\ -\xe0\x0b\x13\x13\x60\xcf\xb5\xcf\x80\xbd\x53\x40\x4c\x54\x80\xe7\ -\xf9\xdd\x0f\xd0\x4e\x80\x8f\x80\x2c\x22\x44\xe5\x44\xc5\xe8\xde\ -\x1b\x9c\x16\x41\xdb\x2a\x0f\x99\x28\x10\x41\x49\x8a\x7c\xe3\x95\ -\xcc\x2f\x01\xbb\x80\xcc\x9a\x43\x04\x27\x98\x8c\x07\x2f\x84\xad\ -\x00\x33\x09\x81\x1a\x9d\x75\xb5\x3a\x98\x8c\x06\x9b\x98\x5d\x28\ -\x3d\x73\x34\xb8\x2d\x6b\x4b\x58\x8c\x07\x43\xd0\xfa\x8f\x3c\xa5\ -\x1a\xfb\x08\x00\x50\x8c\x36\x6e\x99\xec\x06\x80\x79\x9c\x6a\x28\ -\xd1\x78\x88\xb6\x9e\x0c\xae\x09\xee\x20\x30\xc3\x11\xa8\x44\x8c\ -\x55\xb2\x8e\x9b\x5e\x31\x78\x84\x80\xc0\xcd\x88\xb2\xcb\x79\x9e\ -\xcf\xe6\xdd\x74\x15\x34\x09\x8d\x8d\xf6\xa2\xe5\x79\xfe\x55\x07\ -\x77\x7b\xc0\xcb\xbf\x02\x00\x30\x19\x0e\xbf\x38\x67\x67\x91\xb6\ -\x81\x69\xcc\xdc\xff\xae\x7d\x03\x68\x47\x95\x0a\x88\x7f\x49\xe0\ -\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\x38\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\xea\x49\x44\x41\x54\x78\x9c\xed\ -\x98\xc1\x6b\x13\x41\x18\xc5\xdf\xb7\x69\xda\xb4\x45\x2a\xa2\xf5\ -\x90\x4c\x36\x09\x04\x4f\xde\x8a\x15\xaa\x17\x11\x04\x2f\x2a\x82\ -\x22\x1e\xec\x41\x10\x04\xe9\xc5\x9b\xa0\x07\xbd\x89\x7f\x81\xa0\ -\x1e\xa4\x78\x11\x44\xa1\x08\xa2\xf5\x20\x1e\xbc\x29\x82\x2d\xb1\ -\xcd\x4e\x36\x11\xb4\x05\x4d\x15\x1b\x9a\x64\x3f\x4f\x62\x93\x6c\ -\x4d\x0b\x99\xd9\x1e\xbe\xdf\xf1\x7d\xb0\xef\xcd\xdb\x59\x66\x58\ -\x40\x10\x04\x41\x10\x04\x41\x10\x04\x41\x10\x04\xa1\xc7\x78\x9e\ -\x3f\xed\x69\x9f\x3d\xed\x73\xb1\x54\x9a\x8c\x3a\x4f\x3b\x64\xf2\ -\xe1\xc5\x62\x31\x41\x4e\xdf\x6a\x8b\xc8\x74\x24\x93\x49\xcd\x9a\ -\xf4\xdd\x0a\x8e\xc9\x87\x0f\x0f\x0f\xf7\x75\x88\xc4\xaf\xb4\xd6\ -\x39\x93\xbe\x5b\xc1\x68\x01\xa3\xa3\xa3\xbf\xc2\x74\x86\xb3\x30\ -\x37\xb7\xb4\xc3\xa4\xf7\x66\x31\x5a\x00\x00\xb8\xe9\x54\xe7\x2e\ -\x00\x90\x18\xac\xad\x30\xb3\x71\xff\x6e\x18\x0f\x40\x44\xcd\xfa\ -\x5a\x6d\x24\x6c\xa6\x4b\xe5\xa6\x69\xff\x6e\x58\x79\x03\xf9\x7c\ -\x7e\x25\xe6\x20\x1f\x36\xf3\x74\xe9\x8d\x8d\x0c\x1b\x61\x6d\x0b\ -\x2a\xa5\x3e\x13\xe8\x68\xe7\x84\x26\xbc\x92\x7f\xdb\x56\x8e\x76\ -\xac\x7e\x83\xae\x9b\x7a\x09\xc6\x95\x8e\x01\xe3\xaa\xe7\xf9\xe7\ -\x6d\x66\xf9\x8b\xd1\x7b\xc0\x46\x68\x5d\x7a\xc0\xa0\x0b\xed\x7a\ -\xe0\x60\x3c\xa7\xd4\x3b\x9b\x59\x22\x29\x00\x00\x3c\xed\x2f\x00\ -\xe8\xb8\x0f\x38\xc4\xc9\x74\x3a\xfd\xc5\x56\x8e\xc8\x0a\x00\x00\ -\x4f\xfb\x1c\xa6\xc7\x1c\x0c\x29\xa5\x56\xc3\x66\xbd\x26\xd2\x73\ -\x78\x79\xe9\x6b\x7f\x98\xde\x0c\xf0\x9b\x99\xad\xbc\x9c\x48\x77\ -\x00\x00\x54\x2a\x95\xdd\xf5\x46\xb0\x14\x32\xaa\x66\x5c\xb5\xd3\ -\xb4\x7f\xe4\x37\xb1\x64\x32\xb9\xec\x10\xef\x0f\x19\x8d\x68\x5d\ -\x7e\x64\xda\x3f\xf2\x02\x00\x20\x9d\x4e\x7f\x64\xe2\x93\xed\x3a\ -\x83\xcf\x9a\xf6\xde\x16\x05\x00\x00\x9a\xb1\xf9\x28\x6c\xb7\x45\ -\x01\x8b\x8b\x8b\x7b\xc9\x09\x66\x42\x46\x6f\x4d\x7b\x47\x5e\x40\ -\xa5\x52\x19\x8a\xc5\xe2\x4f\x01\x64\x5b\x06\x44\x37\x33\xae\x9a\ -\x30\xed\x1f\x69\x01\xcc\x1c\x6b\x34\x82\x69\x06\x0e\xb4\x8d\xee\ -\xba\x2a\x79\xc3\x46\x86\x48\x0b\xf0\x4a\xe5\x3b\x0c\x9c\x68\x11\ -\x19\xcf\xdd\x74\xea\x32\x11\x85\x5e\x92\x7a\x4d\x64\x05\x68\xed\ -\x4f\x11\x30\xd5\x22\x12\xde\xd7\x6a\x89\x33\x44\xd4\xb0\x95\x23\ -\x92\x8b\x90\xe7\xf9\xa7\x40\x78\xdc\xe6\x5f\x8e\x39\x38\xa8\x94\ -\xaa\xd8\xcc\x62\xbd\x80\xa2\xef\x8f\x53\x80\x59\x00\x83\xeb\xe4\ -\x9f\x81\x83\x43\x39\xa5\x3e\xd8\xce\x63\xf5\x13\xd0\x5a\xe7\xa8\ -\x89\x67\x68\x5d\x7c\x83\x10\x9c\x8e\x62\xf1\x80\xc5\x02\x7c\xdf\ -\xdf\xc5\x70\x66\x40\xd8\xd3\x32\x60\xbe\xe4\xba\xee\x0b\x5b\x39\ -\xda\x09\xfd\x63\xdb\x6b\x0a\x85\xc2\x40\x23\xc0\x13\x02\xf6\xb5\ -\x0c\x88\x6e\x65\x5c\x75\xcf\x46\x86\x8d\x30\xbe\x03\x98\xd9\x89\ -\xc7\x13\xf7\x09\x38\xdc\x36\x7a\xe8\xaa\xe4\x75\xd3\xfe\xdd\x30\ -\x5e\x80\xd6\xfe\x35\x10\xce\xb5\x88\x84\xd7\xf5\xb5\xda\x45\x5b\ -\x67\xfd\xff\x30\x7a\x0a\x14\x0a\x85\x81\x78\x7f\xe2\x07\x80\xc4\ -\x3f\x95\x3f\x11\x78\xc2\x75\xdd\xef\x26\xbd\x37\x8b\xd1\x1d\x50\ -\xad\x56\x03\x00\xf5\x75\xd2\x37\x0e\x9a\xc7\xb7\xcb\xe2\x01\xc3\ -\x05\x8c\x8d\x8d\xd5\xc1\x98\x04\xb0\x0c\x60\x9e\x03\x3a\x96\xcd\ -\x66\x3d\x93\x9e\x82\x20\x08\x82\x20\x08\x82\x20\x08\x82\x20\x08\ -\xdd\xf8\x03\x6a\x65\xdc\x45\x31\x50\xc4\x7d\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x9a\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x4c\x49\x44\x41\x54\x58\x85\xed\ -\xd7\xc1\x09\x00\x20\x0c\x04\xc1\x20\x16\x66\xe1\x82\xad\x48\x52\ -\x48\xec\x40\x3d\xf1\xb9\xfb\x3c\x08\xcc\x37\x66\x24\x36\x3d\xc6\ -\xf4\x18\xb7\xfb\xa9\x2a\x0b\xd2\x9a\xb4\x1f\x2a\x2f\x47\x3f\x03\ -\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xfd\x33\xb2\ -\xec\xda\x4e\xfb\x16\xbe\x7b\x13\xbf\x30\xe2\x93\xe7\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x06\xf1\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x06\xa3\x49\x44\x41\x54\x78\x9c\xed\ -\x9a\xcd\x73\x5b\x67\x15\x87\x9f\xf3\xca\xed\x24\x84\x3a\x4d\xbf\ -\x99\xae\xd8\x36\x6d\xda\xea\xc3\x21\x94\x81\xc6\x49\x6d\x27\x8d\ -\xe3\xfe\x01\x85\x45\x07\xf9\x63\x6a\x4b\x86\x55\x59\xc0\x82\xc9\ -\x02\x86\x81\xda\x96\xa7\xb6\x6c\x66\xd8\xf5\x1f\xa0\x09\x89\xbf\ -\x42\x81\x36\xb1\x25\xab\x1f\x40\x37\x9d\x4e\x17\x1d\x86\x19\x4a\ -\x0b\x71\x9a\x26\x4a\xf0\x7b\x58\xc8\x37\x88\x2b\xd9\x7a\xaf\x74\ -\x6f\x6d\x06\x3f\xcb\xf7\x9e\x7b\xde\xf3\xfb\xe9\x9c\x57\xd2\x95\ -\x60\x97\x5d\x76\xf9\x7f\x46\xea\x2d\x1e\xfa\xf6\xcf\xf6\xdd\xb1\ -\x77\xcf\xf7\xc5\x68\x2f\xca\x1e\x90\x4b\x66\x9d\x9f\xac\xfc\x72\ -\xe4\xc3\x2f\xba\xc0\x66\xe8\xf8\x6e\xee\xab\x36\xc6\x4b\xa0\x47\ -\x10\x6e\x60\xe5\xec\xe7\x6d\xe6\xe7\xef\xbd\xf2\xe2\x67\xfe\xd8\ -\x1a\x03\x9e\x7a\xe1\xa7\x77\x95\xef\xd8\xfb\x3a\xf0\xa4\xef\xd2\ -\x15\x55\xdb\xbd\x3a\x33\xba\x1c\x55\xe1\x61\x90\x4a\x8f\xa5\xd4\ -\x98\x79\x60\x7f\xf5\xba\xc2\x3b\x6d\x77\xf2\xcd\xe5\x5c\x66\xad\ -\x7a\xdd\xf8\x13\x94\xef\xdc\xfb\x12\xb5\xe2\x01\xf6\x8b\x98\xb9\ -\x44\xff\xd8\xe1\x50\x2b\x0e\x91\xcd\xc4\x03\x08\x3c\x6e\x6f\xe9\ -\x0f\xfc\xeb\x35\x06\xa0\x9c\xde\x62\x8f\xf6\x9d\x6a\xc2\x56\xe2\ -\x3d\xd4\x9a\x3e\xff\x5a\xad\x01\xb0\xb7\xc1\x5e\xed\x22\x66\x2e\ -\x39\x38\xd1\x11\xb0\xc6\xc8\xe8\x18\xc8\x25\x1b\x89\x07\x40\x74\ -\x8f\x7f\xa9\x9e\x01\x6f\x38\xec\xd9\x8e\x32\xbf\x13\x4c\xe8\x18\ -\xc8\x25\x2d\xba\x40\x23\xf1\x00\x68\x8d\xb6\x1a\x03\x62\xe8\x19\ -\xe0\x8a\xc3\xde\xdb\x6e\x42\x30\xf1\xac\xc5\xe0\xc7\xfe\xc5\x1a\ -\x03\x96\xf3\xd9\xf7\x11\xba\x70\x37\x61\x5b\xc6\x61\x43\x7c\xe3\ -\xb6\xaf\xb0\x66\x0d\xdd\xcb\xf9\xec\xfb\xfe\x0b\xf5\x46\x80\xe2\ -\x74\x66\x65\xc3\x84\xb5\x7a\xd7\x7d\xec\x47\x99\x4b\xa5\xc7\x52\ -\x0e\xb1\xa1\x10\x1f\x1a\x4f\x6c\x88\xbf\xdb\x21\xfc\xaa\x35\x74\ -\x97\xa6\x32\x97\xeb\x5d\xac\xfb\x41\xc8\x23\x39\x38\xd1\x81\x32\ -\x0f\xb4\x3b\x6c\x74\x45\xac\x7d\xa6\x30\x3b\x5a\x70\x88\x6d\x9a\ -\xf8\xd0\x78\xc2\x58\x59\xc0\x5d\x7c\xd7\x66\xe2\xa1\x81\x01\xb0\ -\xb3\x4c\x08\x5b\x3c\x38\x18\x00\x90\xe8\x1f\x3b\x2c\x62\xe6\x70\ -\x34\xc1\x20\xc7\x57\xf2\x23\x45\x97\xdc\xae\x24\xfa\x27\xe3\x22\ -\x76\x01\x38\xe0\x10\x7e\xd5\x60\xba\x57\xf2\xc3\x97\x1a\x05\x3a\ -\x19\x50\x29\x60\xfb\x4c\x88\x4a\x3c\x6c\x72\x08\xd6\x63\x75\x66\ -\x74\xd9\x1a\xba\x71\x3c\x18\x2d\xba\xd0\x31\x90\x4b\xba\xe6\xdf\ -\x8c\xa0\xe2\xc5\x6a\x8f\xab\x78\x08\xd0\x01\x1e\xf1\xa1\x89\xaf\ -\x19\xcb\x1c\x70\x97\x43\xf8\x3f\x0d\xf2\x4c\xb3\x9d\x10\x50\xfc\ -\x67\x62\xb5\xbb\x30\x9b\x7d\x33\xc8\x1e\xce\x1d\xe0\x51\x9a\xca\ -\x5c\xb6\x86\x2e\xe0\xaa\x43\xf8\xdd\x16\x9d\x8f\x0f\x8d\x27\x82\ -\xee\xf3\x45\x88\x87\x26\x3a\xc0\x23\x68\x27\x58\xa3\xc7\x4b\x53\ -\xd9\x55\x97\xdc\xc9\xc1\x89\x27\x51\x16\x89\x58\x3c\x34\xd1\x01\ -\x1e\xa5\xa9\xcc\x65\x83\xe9\xc6\xb1\x13\x8c\x95\x05\x97\x4e\x08\ -\x2a\x1e\x91\x9e\x66\xc5\x43\x0b\x1d\xe0\xd1\x31\x30\x79\xc4\x62\ -\x2f\x10\x42\x27\x34\x23\xbe\x38\x3d\xe2\xf2\xe5\x6d\x53\x9a\xee\ -\x00\x8f\x95\xfc\xf0\x25\xb1\xda\x83\x7b\x27\xcc\x27\xfa\x27\xe3\ -\xfe\x0b\x1b\xe2\x9d\x67\x5e\xd5\x9e\x68\x55\x3c\x84\x60\x00\x40\ -\x61\x36\xfb\xe6\x86\x09\x35\xcf\xdc\xea\x70\x40\xc4\x2e\x54\x9b\ -\x90\x4a\xbf\xfc\xc4\x86\xf8\x7b\x1c\xee\xbf\xa6\x6a\x4f\xac\xce\ -\x8c\xfe\xa1\xd9\x7a\xab\x69\x79\x04\xaa\x49\xa5\xc7\xbf\xae\x46\ -\x2e\x00\x5f\x76\x08\xff\x87\xaa\x39\x6e\xf4\x96\x55\x13\x5b\xc4\ -\x5d\x7c\x4f\x58\xe2\x21\x64\x03\x20\x98\x09\x82\xae\x69\xa5\x04\ -\x97\x4f\x97\xa1\x8b\xaf\xd4\x10\x01\xc9\xc1\xdc\x53\xa8\x9e\xc7\ -\xad\x13\x5c\xb8\x66\x0d\x27\x4a\x53\x99\xdf\x87\x94\xef\x36\x91\ -\x18\x00\xa1\x9a\x10\x99\x78\x08\xe9\x10\xac\x47\x71\x7a\xe4\x0d\ -\x55\x7b\x02\xb7\x83\x71\x33\xae\x09\xf6\x64\x54\xe2\x21\xc2\x0e\ -\xf0\x48\xf4\x8f\x7d\x43\xc4\x9c\x07\xf6\x05\xbc\xf5\x9a\x60\x4f\ -\x16\xf2\xa3\xbf\x8b\xa2\x2e\x8f\xc8\x0d\x80\x8a\x09\xc6\x98\x39\ -\xd5\x86\x8f\xdc\x3d\x6e\x08\xb6\x3b\x6a\xf1\x10\xe1\x08\x54\xa3\ -\x31\xd6\x54\xe5\xa6\xf3\x0d\xc2\x4d\xac\xba\x7c\xed\x6e\x99\xc8\ -\x0d\x88\x0f\x8d\x1d\x32\xd6\x2c\x81\xba\x3c\xbd\xad\xa0\xb4\xab\ -\x89\x2d\xa6\xd2\x2f\x3f\x11\x61\x69\x40\xc4\x23\xf0\x1f\xf1\xdc\ -\xdb\x64\x8a\x4f\xc5\xae\x1f\x2b\xcc\x7e\xef\xed\x30\xeb\xaa\x26\ -\x32\x03\x36\xc4\x2f\x02\xf7\xb5\x98\xea\x53\x03\x9d\x2b\xf9\xcc\ -\x3b\x61\xd4\xe5\x27\x12\x03\x12\xfd\xb9\xc7\x44\x74\x89\xd6\xc5\ -\x7b\x44\x66\x42\xe8\x67\x40\x10\xf1\x0a\x65\x85\xb2\x43\xda\x7b\ -\x2c\x2c\x76\x0c\x4c\x3c\xde\x7a\x85\xff\x4d\xa8\x06\x04\x7c\xe5\ -\xaf\x8b\x48\x8f\xc1\x76\x01\x9f\x3b\xc4\xdf\x1b\x85\x09\xa1\x8d\ -\x40\x72\x70\xfc\x51\x54\x2e\xe2\x28\x5e\x55\x9f\x5d\x9d\xc9\x5e\ -\x04\x48\xa5\x27\xbe\xa5\x86\x73\xc0\x97\x1c\xee\xfd\xc4\x1a\xdb\ -\x59\x9a\x1a\x7d\xb7\x95\x7a\x3d\x42\x31\xa0\x15\xf1\x1e\xdb\x65\ -\x42\xcb\x23\x10\x54\xbc\x15\x39\xe5\x17\x0f\x50\x98\xcd\xbc\x8e\ -\xc8\xb3\x38\x8e\x83\xb1\x66\x29\x3e\x34\x76\x28\x68\xbd\x7e\x5a\ -\x32\x20\x39\x38\xfe\x28\x88\xf3\xcc\x5b\x91\x53\xa5\xe9\x91\xa5\ -\xcd\x02\x8a\xd3\x23\xbf\x0d\x68\xc2\x62\xab\x26\x34\x3d\x02\xb7\ -\xc5\x2b\xf7\x3b\x84\x5f\x17\xb4\xb7\x90\xcf\x2e\xba\xe5\xce\x3d\ -\x8d\xea\x39\x1a\xff\x5d\x07\xe0\xef\xaa\xd2\xb9\x3a\x33\xf2\x47\ -\x97\xdc\x7e\x9a\xea\x80\x54\x7a\xf2\x60\x00\xf1\x37\x82\x88\x87\ -\xdb\x9d\x70\x12\xb8\xee\x10\x7e\x9f\x88\x2e\x25\xfa\x73\x8f\xb9\ -\xe6\xaf\x26\x70\x07\xa4\xd2\x93\x07\x35\x66\x2f\x06\x10\x7f\x2a\ -\x88\xf8\x6a\x12\xfd\xe3\x47\x45\xe4\x2c\x11\x76\x42\x20\x03\x52\ -\xe9\xc9\x83\x18\xbb\xa4\xf0\x80\x43\x78\x4b\xe2\x3d\x82\x9a\x80\ -\xe8\xd1\xe2\x74\xf6\x4f\xae\xf9\x9d\x0d\x08\x2a\x1e\x4b\x6f\x71\ -\x36\xb3\xe0\x9a\x7f\x2b\xe2\x83\xb9\x4e\xa3\xfa\x1a\x11\x98\xe0\ -\x64\xc0\xe1\x81\x89\x47\x2c\x5c\xdc\x0e\xf1\x1e\x51\x99\xd0\xf0\ -\x10\x0c\x2c\x1e\x73\x3a\x6c\xf1\x00\xa5\xe9\x91\x25\x41\x7b\x71\ -\x3c\x18\x41\x96\x2a\xef\x54\x5b\xb3\x65\x07\x34\x25\x3e\x3f\x3c\ -\xef\x10\xdb\x34\xa9\x81\xf1\x63\x8a\xbc\x06\xd4\xfc\xeb\xb3\x06\ -\xe1\x63\xd0\xce\xad\x3a\x61\xd3\x0e\x38\x3c\x30\xf1\xc8\x3a\x38\ -\xcf\xbc\x2a\x7d\x51\x8b\x07\x28\xe4\xb3\x8b\x82\x9e\x02\x6e\x34\ -\x0c\x56\xee\x07\x59\xaa\xbc\x6d\xd7\xa7\x6e\x07\x78\xe2\x81\x07\ -\x1d\x6a\x2a\xab\x72\x7a\x75\x26\x33\xe7\x10\x1b\x1a\x41\x3b\x41\ -\xd6\xcd\xd1\xc2\xec\xf0\x9f\x6b\x2f\xf9\x38\x32\xf8\x8b\x87\x6f\ -\x69\x5b\x11\x78\xc8\xa1\x8e\x6d\x11\xef\x91\x4c\x4f\x1c\xc7\xf0\ -\x6b\x1c\x4c\x10\xf8\x1b\xb1\x58\xb2\xf0\xca\x8b\x1f\x55\xaf\xd7\ -\x8c\xc0\x2d\xdb\xf6\x43\xfe\x07\xc4\x03\x14\x67\x33\x0b\x58\x7a\ -\x71\x18\x07\x85\x07\xb0\xeb\x3f\xf2\xaf\xd7\x9e\x01\xc2\xd3\x0e\ -\x7b\x97\xad\x48\xdf\x76\x8a\xf7\xa8\xbc\xe3\x98\xd3\xb8\x98\xa0\ -\x1c\xf5\xaf\xd5\x18\xa0\xb0\xde\x20\x4f\xd9\x8a\xf4\x95\xa6\x47\ -\x2e\xb8\x97\x19\x2d\x95\xc3\xd7\xc9\x84\x1a\x6d\x35\x06\x08\x6c\ -\xf5\xaa\x96\x05\x7d\x6e\x27\x89\xf7\x28\xe6\x87\xe7\x55\xe9\x63\ -\x0b\x13\x44\x38\xef\x5f\xab\x31\xc0\xb4\x99\x33\xc0\x07\x75\xee\ -\x2f\x0b\xfa\x5c\x21\x9f\xad\x49\xb2\x53\x58\x9d\xc9\xcc\x6d\x61\ -\xc2\x87\xff\x2a\x73\xc6\xbf\x18\xf3\x2f\xfc\xa5\x70\xee\xfa\x57\ -\x12\xc7\x5e\x15\x89\xed\x43\x79\x50\x84\x9b\x28\x8b\x8a\xf9\x4e\ -\x71\x26\xba\x5f\x69\xc3\xe2\xaf\xab\xbf\xf9\xe0\xe1\x78\xd7\x59\ -\xc4\x3c\x04\x1c\x40\xf9\x44\x45\x5f\xb5\x37\xe5\xf9\xb7\x7e\x95\ -\xf9\x78\xbb\xeb\xdb\x65\x97\x5d\x76\x16\xff\x06\x5e\xec\x1f\xa0\ -\xf6\x5e\x26\xad\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\ -\x00\x00\x02\x06\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xb8\x49\x44\x41\x54\x58\x85\xed\ -\x97\xcf\x4a\x1b\x51\x14\x87\xbf\x33\x49\x56\x25\x42\x2b\xa9\xe0\ -\x6b\x34\xff\x8a\xc5\x07\x68\x4a\x5f\xa2\xc1\x94\x6a\x46\x29\x25\ -\xf6\x11\x1a\xa1\x25\x99\xd8\xa2\x45\x17\x92\x95\x0f\x10\x70\xd3\ -\x2e\x04\xab\x69\x93\xd7\x10\x34\x28\x94\x2c\x63\x72\x5c\xcc\x64\ -\x0c\xc6\x8e\x98\x4c\x62\x69\xf3\x5b\xde\x7b\xb8\xdf\x37\xf7\x5c\ -\x86\x7b\xe1\x7f\x8f\x5c\x1f\x88\xbe\x2e\xcd\xa1\xba\x8a\x90\x44\ -\x89\xf8\x44\x69\xa0\x1c\x21\x92\xaf\x6d\x64\x0f\xfe\x28\x10\xcb\ -\x14\xdf\x29\xb2\x76\x93\x98\x4f\xe9\xa8\x92\xab\x7f\x35\x3f\xf6\ -\x09\x3c\x59\x28\x3c\x13\x31\xf6\x81\xdf\x88\x9a\xa1\x56\xbb\x72\ -\xb8\xfd\xf6\xdc\x0f\xea\xd3\x57\x9f\x1e\xb5\x42\x81\x14\x2a\x16\ -\x30\x85\xc8\x7c\x77\x27\x82\xae\x89\x18\x39\x40\x10\x35\x6b\x1b\ -\xcb\x65\x3f\xc0\xdd\x38\x1f\x52\x8e\x66\x2c\x01\x76\x50\x5d\x05\ -\x5e\x02\x18\x6e\x95\x90\x04\x08\xb5\xda\x15\x3f\xe1\xbd\x31\x82\ -\x46\xc5\x46\x91\x70\xc7\xdc\x59\xe7\xc0\xf9\xb5\xed\x37\xe5\xe7\ -\xe7\xa5\x33\x1b\xc5\xe3\x7e\x81\x7b\xca\x44\x60\x22\x70\xef\x02\ -\xc1\xdb\x0a\x62\x99\xd2\x1b\x45\x3f\x00\xe1\x3b\xae\xdd\x14\xe4\ -\xfd\xaf\xcd\xec\x17\xaf\x22\xcf\x1d\x48\xa4\x0b\x33\x8a\x96\x06\ -\x80\x03\x84\x15\xb5\x12\xe9\xc2\xcc\xc0\x02\xe3\x88\xa7\x40\x75\ -\x6b\xe5\x44\x90\x2c\xd0\x1c\x60\xed\xa6\x20\x66\x75\x6b\xe5\xc4\ -\xab\xe8\xd6\x33\xe0\xf4\xd0\xb3\x8f\xc3\xe4\xef\x6e\xc1\x44\x60\ -\x22\x30\x5e\x01\xa1\x01\xf6\x05\x72\x54\xb0\xf8\xe2\xfa\xb4\x8d\ -\xe2\xb4\x5f\x40\x39\x02\x68\x85\x02\xa9\x51\x09\x74\x2e\x3a\x29\ -\x1b\x45\xb5\x3b\x76\xf5\x23\x12\xc9\xa3\xfa\x02\x15\x2b\x9a\xb1\ -\xc4\x08\x1a\x95\xee\x1d\x6e\xd8\xc4\x17\xd7\xa7\x1d\x78\x11\xe8\ -\x20\x92\x77\xb1\xbd\x85\xce\xc3\x24\xcf\xe8\xce\x46\xdf\xc3\x24\ -\xd0\x3b\x7b\x5c\xdf\xfb\x31\x1b\x7b\xfe\x0d\x88\x08\x3c\x04\x1e\ -\xf8\x41\x75\x7a\xfe\x1d\x91\x74\x7d\xd3\xdc\xf5\x63\xcd\x7f\x27\ -\x97\x00\x43\x86\x87\x3f\x9c\xa0\xff\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x02\x37\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xe9\x49\x44\x41\x54\x58\x85\xed\ -\x94\x31\x68\x13\x61\x14\xc7\x7f\xef\x8e\x50\x8d\x20\x75\x50\x8a\ -\x93\x29\xe2\x24\xa2\xa5\x71\x11\xdc\x44\x91\x8e\x8a\x53\x41\x87\ -\xda\xa0\x49\x8a\x83\x93\x08\xea\xea\x60\x4d\x5b\x6b\xeb\xe0\xa0\ -\xa0\x58\xc4\x41\x07\xa5\x53\x71\x50\xa8\x8d\x5a\xc4\xc9\xc1\x45\ -\xa1\x88\x56\x45\x4b\xb5\xb9\xfb\x3b\x24\x67\xcf\x60\x9b\xbb\x58\ -\xec\x72\x3f\x38\xf8\x8e\x7b\xef\xff\xfe\xef\xde\xf7\x7d\x90\x90\ -\x90\x90\xb0\xca\x58\xb0\xe8\x3c\x5e\x9a\xc5\x68\xfd\x2f\x55\xc5\ -\xe7\x67\xa3\xc5\x0d\x00\x4e\xc8\x8a\xb3\x64\xc2\x4a\x13\xaa\xf5\ -\x7b\x91\xaa\x54\x32\x06\x4f\x83\x77\x21\x1f\xf0\x56\xe2\x11\xf8\ -\xa1\xf2\x4f\x52\x95\x4a\x66\xd1\x4b\x88\x1d\xdd\x17\xd7\xb5\xa4\ -\x5b\xee\x0a\xf6\x23\xc0\xe4\x83\xe9\x5f\x9a\x15\x32\xc3\x82\x46\ -\x1f\xfe\x9c\xfb\x71\x68\xfa\xc6\xe9\xef\xc1\x77\x37\x1c\x3c\x33\ -\x3d\xbe\xd0\xda\xbe\xfb\x4e\x6a\x6d\x7a\x1b\xc6\xf6\xaa\xc1\x3f\ -\x3c\xc6\x2b\x6e\x2c\x16\x97\xdd\x9e\x9b\xfd\x78\xe4\xd5\xad\x33\ -\xf3\xe1\x18\xb7\x3e\xe9\xc3\xeb\x09\x6f\x4f\xfb\xb1\x7b\x5f\xd2\ -\xdf\x36\x82\x65\x01\x93\x09\x8b\x69\x44\x60\x56\x1b\xb1\x19\xc3\ -\x99\x4f\x6d\x3d\x13\x63\xf9\x4a\x7d\xdc\x32\xaa\xb2\x6c\xae\x74\ -\x5e\xb2\xb3\xb5\x48\x1f\x11\x6d\x1c\x86\xa1\x6a\x71\xc1\x85\xa9\ -\x91\xc2\xb9\xa5\x46\xd9\xb0\xad\x6c\xef\x40\x9f\x50\x3f\x80\xaa\ -\x03\xf5\x1b\xa4\x38\x81\xae\x44\xdf\xd4\x68\xb1\xb4\xbc\xd7\x08\ -\x74\xe6\x2e\x77\x23\xbb\x0e\xb8\x02\x19\x7f\x37\x21\xe1\x58\x75\ -\x56\x9e\x61\x47\x27\x47\x0a\x37\x1b\x69\x47\x1e\x6c\x47\x6e\xb0\ -\xcb\x91\x3f\x06\xac\x01\x44\xbd\x09\x99\x83\xc9\x80\x79\xdf\x9c\ -\xc3\xe5\xab\xf9\x07\x51\x74\x63\xed\xac\x6c\x6f\xff\x5e\xe1\xdc\ -\x07\xd6\xd7\x99\x08\x7e\xfb\x57\xdf\xa1\xab\x3c\x5c\x7c\x1c\x55\ -\x33\xf6\x19\xcb\xf6\x5c\xda\x89\xe3\x3e\x12\x6c\x02\x54\xdb\xed\ -\x00\x33\xe6\x7b\x07\x26\xaf\x9d\x7a\x11\x47\xaf\xa9\x43\xde\x71\ -\x62\x68\xab\x79\xde\xb8\xc1\x16\x00\xc1\x5b\xb9\xee\xbe\xf2\x95\ -\x93\x6f\xe2\x6a\x35\x7d\xcb\xec\xca\x0f\x6c\x76\x17\xf4\x4e\xf0\ -\xd2\x4f\xd9\xc1\xe7\x83\x85\xf7\xcd\x6a\x25\x24\x24\x24\xac\x2a\ -\xbf\x00\xaf\x38\xac\x82\xe2\x51\x10\x13\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x04\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xb6\x49\x44\x41\x54\x78\x9c\xed\ -\xd9\xd1\x0d\x83\x50\x0c\xc5\xd0\x14\x75\x8d\x0a\xf6\x9f\x0a\xc4\ -\x20\x74\x8c\x83\xf4\xec\x05\x62\x59\xf7\x2f\x33\x90\xf3\xba\x9f\ -\xf3\xba\x1f\xe9\xb0\xc9\xe3\x6f\xa0\x00\x5a\x40\x53\x00\x2d\xa0\ -\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\ -\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\ -\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\xe5\ -\x03\x7c\xe4\x71\xfd\x1a\x9f\x69\x01\xf3\xd5\x02\x33\x33\xc7\xfe\ -\x63\x4b\x5c\x7e\x01\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\ -\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\ -\x0a\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\ -\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x2c\x1f\xe0\x0f\xc7\ -\xa8\x0b\xc6\x03\x24\x5a\xc7\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x00\x8a\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3c\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\x01\x09\x00\x20\x10\x04\xc1\xd7\x4c\x76\xb2\x8f\x85\xfd\x14\ -\x72\x20\x33\x09\x96\xad\x02\x00\x00\x00\x00\x00\x00\xe0\x7f\x63\ -\xed\x73\xd3\x11\x49\x33\x1d\x90\x66\x40\x3a\x00\x00\x00\x00\x00\ -\x00\x00\x00\xde\x6b\x42\xab\x02\x34\xd3\x03\x1d\x60\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\x68\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x1a\x49\x44\x41\x54\x78\x9c\xed\ -\xd6\x4f\x6c\x14\x65\x18\xc7\xf1\xef\x33\xdb\xad\x44\xc4\x34\x01\ -\xa3\x04\x82\x4a\x0f\xc4\x02\x51\xeb\x09\x88\x64\x85\xdd\x25\xa4\ -\xa9\xc8\x6e\x97\x10\x62\xb1\xa6\xdb\x46\x4c\x3c\x18\x13\x6f\xa6\ -\xf1\x46\x82\x91\x70\x69\x42\xff\x24\x04\x4d\x54\xa6\x7f\x38\x28\ -\xe8\x96\x26\x94\xa4\x88\x46\xca\xad\x1e\x80\x9a\x08\x21\x46\x10\ -\xc1\x90\xd0\x52\xf6\x7d\xbc\x70\xd8\x0e\x45\xb0\x33\xbb\x84\xf0\ -\x7c\x8e\xf3\xcc\xfc\xf6\xf7\xbe\xb3\xb3\xb3\x60\x8c\x31\xc6\x18\ -\x63\x8c\x31\xc6\x18\x63\x8c\x31\xc6\x98\xc7\x85\x84\x0d\xd8\x98\ -\x7b\xb7\xce\x2b\xc6\x0e\x8a\xb0\x04\xf8\xbc\xd0\xdf\xf3\x19\xa0\ -\xe1\xab\xcd\x2e\x95\x69\xdb\x2a\xa2\x7b\x00\x10\xf9\xa0\xd0\xd7\ -\x7d\x34\x4c\x5e\xe8\x0d\x48\x65\xf3\x23\xc0\xfa\x92\xc8\x2f\x6a\ -\xbc\x6b\x79\xdf\xf7\x6f\x85\xcd\x0e\x90\x54\x53\xdb\xc7\xa8\xee\ -\x2e\x39\x76\xfd\xea\x42\xef\x99\xd3\x5d\x5d\xd3\x73\x0d\xf5\x42\ -\xd7\x52\x0d\x64\x68\xf3\xdf\xae\xe6\xfb\xc4\x5b\x2d\x35\xa1\xb3\ -\xef\x48\x24\x3a\xaa\x52\xd9\x7c\x67\x60\xf1\x80\x84\xbe\x81\xa1\ -\x37\x40\x94\x5d\xc0\x9f\x33\x8e\xa1\x6f\xc4\x63\xf1\xd1\x0d\x99\ -\xd6\xe7\xc3\xe6\x27\x72\xef\x3f\x15\x5f\x74\xe9\x30\xf0\x5e\x60\ -\x34\x25\xb8\xb7\xc3\xdc\x7d\x88\xe0\x11\x00\x48\xe7\xf2\x2f\x3a\ -\xc7\x51\x81\x15\x81\xf0\x3f\x44\xbd\x86\x1f\x06\xba\xc6\xe6\x92\ -\xbb\x29\xd3\xbe\xb8\x28\xee\x5b\x81\xfa\xc0\xe8\x2a\xaa\x6f\x0e\ -\x0d\xf4\x8e\xce\xb9\xf4\x1d\xe1\x1f\x01\xa0\xe0\xf7\xfc\x16\xf3\ -\x74\x2d\x70\xa2\xf4\xb8\xc2\x73\x4e\xdc\x89\x64\xa6\xb5\xe1\xff\ -\x66\x6e\xca\xb6\xad\x74\xe2\x4e\xcd\xb2\xf8\x09\xe7\x64\x4d\x14\ -\x8b\x07\x88\x45\x11\x02\x70\x7e\xfc\xcc\xcd\x15\x2f\xac\xfb\xca\ -\xc5\x6f\xd7\x02\xab\x4b\x46\xd5\x22\xb2\x7d\x79\x5d\xfd\xe5\x89\ -\x5f\xc7\x7e\x79\x90\xac\xf4\xd6\xfc\x06\x15\x0a\xc0\xb3\x33\x27\ -\xfa\x53\x95\xe7\x36\x16\xfa\x7b\x2f\x44\xd5\x3b\xb2\x0d\x00\x38\ -\x77\xee\xe7\x62\xf3\xb6\xc6\xc1\x0b\x97\x6f\x54\x03\xaf\x97\x8c\ -\x44\xa0\x61\x79\x5d\xfd\xfc\xe6\x6d\x8d\xc3\x23\x23\x23\xf7\x7c\ -\x4d\x26\x9b\xf2\x3b\x11\x0e\x01\x4f\xce\x18\x08\x83\x4f\x4c\xc5\ -\xb6\x1c\x39\xdc\x7b\x3d\xca\xce\x91\xfc\x06\xcc\x26\x9d\xc9\xb7\ -\xab\xd0\xc9\xdd\x9b\x7c\x68\x7a\xc1\xed\x77\x8e\x1f\x38\x30\x19\ -\xec\x92\xca\xb6\x7e\x02\xf2\xe9\xdd\x69\xba\xaf\xc6\xfb\xe7\x23\ -\xdf\xf7\x8b\x51\xf7\x2c\xdb\x06\x00\xa4\x9b\xda\x36\xab\xaa\x0f\ -\xcc\x0f\x8c\x46\x9d\xbb\xb5\x65\x78\xf0\xe0\x5f\x00\xb9\x5c\xae\ -\xfa\x9a\x7b\x7a\x3f\x48\x4b\xe0\x3c\x05\xf9\x70\xa8\xbf\x7b\x5f\ -\xb9\x3a\x96\x75\x03\x00\x92\xd9\xd6\x57\x05\xf9\x0e\x58\x3c\x73\ -\xa2\x67\x8b\xc5\xd8\x66\x2f\xce\x15\xcf\xb9\x3e\x85\x64\xe0\xd2\ -\x49\x54\x76\x0c\x0d\x74\x0f\x96\xb3\x5f\xd9\x37\x00\x20\x99\x6b\ -\x5f\x26\xce\x1d\x01\x56\x3e\xd0\x05\xca\x15\x85\xc6\x63\x03\x3d\ -\xa7\xca\xdb\x2c\xa2\xd7\xe0\xfd\x1c\xf3\xbb\x7e\x57\xcf\x5b\x07\ -\x0c\xdf\xff\x6c\x3d\xeb\xc5\x74\x4d\x25\x16\x0f\x11\xbf\x05\xfe\ -\xcb\xc4\xf8\xe9\xa9\xd7\x56\xd5\x7e\x3d\xa9\xf3\x96\x01\xaf\xdc\ -\xe3\xb4\x93\xd3\xd5\xb1\xd4\xf0\x37\x3d\x17\x2b\xd5\xab\x22\x8f\ -\x40\xf0\x33\xd3\x4d\xf9\x0e\x55\x3a\x02\x4d\xfa\x6e\xc8\x82\x9d\ -\x3f\xfa\x7b\x6f\x56\xb2\x4c\xc5\xbe\x01\xa5\xce\x8f\x8f\x1d\xaf\ -\x7d\xa9\x7e\x29\xc2\xcb\x80\x43\x75\xcf\xda\x55\x4b\x77\x7d\xd9\ -\xb9\x3b\xd4\xff\xfa\x47\x4e\x22\xd1\x51\x95\x68\x69\x99\xf7\xb0\ -\x7b\x18\x63\x8c\x31\xc6\x18\x63\x8c\x31\xc6\x18\x63\x8c\x31\x8f\ -\x89\x7f\x01\x76\x43\xf4\x3d\x50\xc3\x70\x12\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\xe8\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\x9a\x49\x44\x41\x54\x58\x85\xe5\ -\x96\xbb\x72\xd3\x40\x14\x86\xbf\xe3\xa4\x00\x9e\x23\x25\x54\xb1\ -\x52\xf0\x0a\x14\x90\x84\xc4\x21\x64\x72\x23\x44\x6a\x2c\x37\x99\ -\xe1\x19\x28\x65\x35\x92\x27\x09\xd8\x21\xce\xc5\xc0\x30\xc3\x33\ -\x50\x59\x7e\x05\xe8\xe0\x0d\x80\x02\xfb\x50\xc4\x4a\x64\x5d\x6c\ -\xcb\x71\xc3\x70\x2a\x69\xb5\xfb\x7f\x9f\x56\xab\xd9\x85\xff\xbd\ -\x24\xbc\x30\x5e\x3a\x0f\xb5\x20\x1e\xca\x5d\x11\x5e\xb5\x7d\xfb\ -\xe3\x34\x41\x86\x59\x5d\x52\xe5\x35\xc2\x6f\x44\xac\xc0\x2b\x7f\ -\x01\x28\x84\x1d\xb4\x20\x47\xc0\x03\x84\x39\x85\x96\x61\xba\xa5\ -\x69\xc1\x8b\x96\xb3\xa6\xd0\x42\x98\x03\xee\xa3\x7a\x18\x3e\xbb\ -\x11\x80\x3b\x91\x31\x05\x45\x9b\xd3\x90\x28\x5a\xce\x1a\x2a\xa7\ -\x51\x16\x70\x2f\x21\x20\x22\x07\x40\x6f\x9a\x12\x86\xe9\x96\x52\ -\xe0\x3d\x55\x39\x48\x08\x04\x5e\xf9\x03\xb0\x91\x22\x71\x3a\x89\ -\x84\x61\xba\x25\x45\x9b\x71\xb8\x20\x5b\x9d\x5a\xb9\x95\x10\x00\ -\x08\x7c\xfb\x2c\x45\x62\x26\xaf\x44\x1f\x9e\x78\x73\x41\xb6\xda\ -\x7e\xf9\x5d\xb4\xaf\x90\x52\xf3\xfb\xee\xba\x88\x9e\xc4\x02\xba\ -\x22\xba\xde\xf6\x2a\x97\x43\xe1\x96\xb3\xaa\x2a\x4d\x60\x66\x14\ -\x3c\x53\x60\x52\x89\x0c\xb8\x0a\xb2\x99\x06\x27\x16\x3e\x50\x9d\ -\x5a\xb9\x29\xc2\x26\xf1\xcf\xa1\xd2\x34\x2c\x67\x35\x45\x78\x25\ -\x2f\x1c\x86\xcc\x40\x58\x86\x55\x7d\xae\x4a\x23\x26\xdb\x55\x95\ -\x67\xe1\x62\x9a\xdf\x77\x57\x44\xf4\x2c\x2f\x7c\x2c\x01\x00\xc3\ -\x74\x37\x14\xad\xa7\x49\x00\xa4\xc1\x11\xdd\x0a\xbc\xca\xc9\xa8\ -\xec\xb1\x04\xb2\x24\xb4\xff\x79\x64\x50\x6c\x6c\x78\x2e\x81\x88\ -\x44\x63\xc8\xb8\x5c\xf0\xdc\x02\x37\x12\x34\x40\xe3\x63\x15\xd8\ -\x0e\x7c\xbb\x91\x27\x2f\xf3\x2f\xc8\x2a\x15\x7e\x29\xaa\x89\xf6\ -\x2b\x81\x9f\x79\xf3\x72\x09\x14\x2d\x77\x19\xd5\x73\x49\x19\xd7\ -\x6f\x3b\x2f\x9a\xd5\xa7\x79\x32\x73\x2c\xc2\xea\x92\xc2\x05\x30\ -\x1b\x69\x0e\x67\x22\x9a\xd3\x45\xa4\xd4\xdf\x5b\x46\xd6\x58\x33\ -\x90\x05\x57\xd5\x1d\x60\x3b\x22\x02\x30\x83\xea\x45\xd1\x72\x97\ -\xa7\x22\xb0\x60\x39\x8b\x59\xf0\x4e\xad\x52\x0f\x7c\xbb\xd1\x17\ -\x99\x48\x62\xa8\xc0\x82\xe5\x2c\xf6\x54\x2e\xe3\x70\x11\x76\x3b\ -\xb5\x4a\x3d\x6c\xe8\xd4\x2a\xf5\x0c\x89\xf3\x51\x12\x99\x02\xc3\ -\xe0\x6d\xcf\x7e\x1b\xef\xdf\xa9\x55\xea\x22\xec\xc6\x24\x66\x47\ -\x49\x64\x6d\xc7\x4f\x44\xb4\x35\x2e\x3c\x5a\x86\x55\xdd\x56\xe5\ -\x38\x96\xfd\x47\xa0\x94\x76\xd0\x4d\x08\x64\xc2\x91\x17\x6d\xbf\ -\xfc\x66\x18\xfc\x5a\xc2\x74\x77\x14\x3d\x1a\x47\x62\x40\xa0\x68\ -\x3a\x8f\x41\xde\xdf\x06\x9e\x57\xe2\xfa\xe1\xfc\x7e\xf5\x91\x08\ -\x9f\xa6\x01\x0f\xab\x68\x55\x77\x51\x0e\x53\x24\x96\xda\xbe\xfd\ -\x19\x06\x4e\xc5\x38\x71\x38\xc2\xde\xa4\x70\x80\xc0\xb3\x8f\x11\ -\xf6\x88\x2d\x4c\x05\x27\xbc\x49\x6c\xad\x51\x78\xe0\xd9\xc7\x93\ -\xc2\x87\x4a\x28\xdd\x84\x00\xaa\x26\xc8\x57\xe0\xc7\xd5\x96\x7a\ -\x7b\x78\x54\x42\x90\x4d\x94\xef\xc0\xb7\x5e\x41\xcc\x69\x65\xff\ -\xfb\xf5\x17\x4b\x00\x72\xf1\x7d\xf9\x90\x28\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\x89\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x3b\x49\x44\x41\x54\x78\x9c\xed\ -\x9a\xbd\x6b\x14\x41\x18\xc6\x9f\xd9\x0d\x84\xa0\xd8\x88\x04\x63\ -\x0a\x43\x62\xa1\x08\x42\x72\xd1\x94\xe2\x27\x06\xb1\x0b\x8a\x8d\ -\x78\x60\x36\x97\xd3\x53\x0b\x09\xfe\x05\xc6\x2a\xb8\x97\x4b\x72\ -\x29\xd2\x08\x36\xd1\x42\x84\x9c\xa0\x16\x01\x8b\x48\x2e\x29\x24\ -\x88\x85\x82\xc5\x29\x04\xb5\x88\xe4\x83\x33\x99\x7d\x2d\x22\x16\ -\xb7\x7b\x7b\xb7\x1f\x73\x93\x73\xe7\x57\xce\x0d\xcf\xfb\xec\x73\ -\xf3\xc5\xee\x00\x0a\x85\x22\xca\xb0\xa0\x02\x47\x06\x33\xbb\x9b\ -\x38\x4f\x32\x42\x1f\x18\x8e\x02\x68\x0c\xc1\x57\x10\x8a\x20\x2c\ -\x11\xc3\xf4\x86\xae\x67\x3e\x8c\x25\x57\xdd\x3a\x07\x0a\x20\x66\ -\x8c\x9e\x05\xac\x29\x00\xad\x41\x74\x04\x52\x00\xb4\x78\x3e\x7b\ -\xf3\x55\xb9\x0e\x9a\x5f\xe5\xd8\x80\x19\x07\xac\x97\xd8\xb9\x0f\ -\x0f\x00\xad\x80\x95\xeb\x36\xd2\xd7\xcb\x75\xf0\x35\x02\xba\xfa\ -\xcd\x73\x8c\x21\x87\x00\x01\xd6\x18\x0e\x68\x17\x9c\x46\x82\xe7\ -\x00\xb6\xe7\xbc\xf5\x91\x81\x0e\x84\xe3\xad\x66\x14\xd6\x75\xfd\ -\x70\xe9\x9a\xe0\xf9\x1f\x6c\xe2\x3c\x59\x87\x0f\x0f\x00\xad\x4d\ -\x9c\x27\x4b\x1b\x3d\x07\xc0\x08\x7d\xe1\xf8\xa9\x3d\x4e\xde\xbd\ -\xcf\xe1\xed\xad\xae\x3e\x71\xf0\xde\xe0\x43\xc6\x75\x9f\xcf\x67\ -\x53\x81\xcf\x16\x41\x88\x19\x26\xb9\xfc\x6c\xf3\x5e\x2f\xab\xb8\ -\x30\x54\x00\xb2\x0d\xc8\x46\x05\x20\xdb\x80\x6c\x54\x00\xb2\x0d\ -\xc8\x26\xf2\x01\x54\x3c\x08\x75\xf5\x8f\xec\xd7\x34\x2d\x41\x60\ -\xa7\x41\x68\xae\xd4\x3f\x66\x98\x9f\x7c\xbb\x21\x10\x18\x0a\x20\ -\xcc\xe8\x8d\xc8\xbe\x4b\xa7\x7e\xf9\xd6\xaa\x12\xd7\x00\x62\x89\ -\xf4\x25\x58\x34\x45\x84\xbd\x1e\x34\xdb\x7d\xbb\xd9\x3e\x43\x76\ -\x80\xe1\x24\xff\x8d\x44\x67\xc2\xbc\xba\x38\x9e\x9a\xf3\xad\x57\ -\x05\x65\xa7\x40\xcc\x30\x87\x61\xd1\x73\xc0\xd3\xc3\x87\x49\x9b\ -\x66\xe1\x6d\x97\x91\x1e\x10\x59\xc4\x31\x80\x6e\x23\x7d\x19\xc0\ -\x90\xc8\xc2\x55\xa2\x33\xd0\x68\x67\xc2\xec\x11\x55\xc0\x16\x40\ -\xcf\xc0\xc8\x41\x02\x4d\x8a\x2a\xe8\x03\x5d\xb3\xf0\xe4\xc4\x2d\ -\x73\x8f\x08\x71\x5b\x00\x5b\xd4\x70\x1f\x80\x90\x62\x01\x68\xe3\ -\x45\x18\x22\x84\x1d\xa6\x00\xf5\x8a\x28\x14\x18\x06\x21\xbe\x9c\ -\xd6\x80\x9d\xf9\x96\x97\xc4\xf8\xf2\xfc\x42\xc4\xd2\xf5\x43\x22\ -\x8c\xe8\x7c\xab\x83\xc0\x72\x65\x3b\xb0\xe0\x1f\x71\x9c\xf0\x1c\ -\xc0\xe2\x58\xd2\xff\x41\xc7\x85\xce\xc1\x0c\x34\xce\x45\x48\xbb\ -\x12\xf9\xa3\xb0\x0a\x40\xb6\x01\xd9\xa8\x00\x64\x1b\x90\x8d\x0a\ -\x40\xb6\x01\xd9\xa8\x00\x64\x1b\x90\x8d\x0a\x40\xb6\x01\xd9\xa8\ -\x00\x64\x1b\x90\x8d\x9f\xfb\x01\xb2\x68\xaf\xf0\xed\xbf\x1a\x8a\ -\xa5\x0d\xd1\x1a\x01\x84\xa5\xd2\xa6\x48\x05\x40\x0c\xd3\xa5\x6d\ -\x51\x0a\xa0\xb0\xa1\xeb\x99\xd2\xc6\xa8\x04\xc0\x01\x2d\xee\x74\ -\x6f\x38\x0a\x01\x70\x06\x76\xa3\xdc\x7d\xe1\x7a\xda\x05\xfc\x50\ -\x00\xb4\xf8\xbc\xcb\x65\xe9\xff\x31\x80\x7f\xd7\xe5\x37\xd7\x8b\ -\xa3\xef\x1f\xdf\x5b\x73\xeb\x6c\x7b\xd5\x1c\xc2\x5e\x2b\x8a\xcf\ -\xf9\x6c\xaa\x23\x6c\x51\xfb\x1a\xc0\xf0\x3d\xec\x22\xa1\xc0\xb0\ -\x2c\x42\xd6\x1e\x00\xe1\xb5\x88\x42\x41\x61\xa0\x37\x22\x74\x6d\ -\x01\x68\xc0\x43\x00\x9b\x22\x8a\x05\xe0\xa7\x65\x59\xe3\x22\x84\ -\xf5\xd2\x86\xaf\x0b\xb9\xe5\x96\xee\xde\x55\x00\xe7\x45\x14\xf4\ -\x03\x03\xae\xe4\x27\xef\x2c\x88\xd0\x76\x3c\x07\xe4\x9b\x7f\x3c\ -\x02\xf0\x54\x44\x41\xaf\x30\x46\xc3\xf3\xd9\xd4\x0b\x51\xfa\xb6\ -\x11\x00\x00\x98\x9d\xa5\x6f\x17\x8f\x3f\x6b\x59\xdb\xb5\x02\xe0\ -\x54\xd9\x7e\x62\x59\x61\x8c\xae\xcd\x4f\xdc\x36\x45\x16\xa9\xf8\ -\xc5\xf5\xb8\x61\x1e\xb3\x80\x21\x30\x9c\x01\x61\x9f\x48\x33\x7f\ -\x29\x00\x6c\xa6\x81\x6d\x3d\x98\x9b\xb8\xfb\xa5\x06\xf5\x14\x0a\ -\x45\x84\xf9\x03\x3a\xde\xd0\x31\x4b\x14\x34\x6a\x00\x00\x00\x00\ -\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x89\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3b\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\x01\x09\x00\x20\x10\x04\xc1\xd7\x52\xb6\x36\xa2\x7e\x0a\x39\ -\x90\x99\x04\xcb\x56\x01\x00\x00\x00\x00\x00\x00\xf0\xbf\xb1\xf6\ -\xb9\xe9\x88\xa4\x99\x0e\x48\x33\x20\x1d\x00\x00\x00\x00\x00\x00\ -\x00\x00\xef\x35\x86\x6a\x02\xea\xd1\x43\x33\x62\x00\x00\x00\x00\ -\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x08\x4f\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x08\x01\x49\x44\x41\x54\x78\x9c\xed\ -\x5b\x7d\x70\x54\xd5\x1d\x3d\xe7\xee\x26\x61\xab\x01\x0b\x7e\xb4\ -\xa3\x19\x8a\x4e\x19\x0c\x15\x5b\x20\x6c\x42\x11\xc1\x69\xc7\xca\ -\x00\x71\x13\x4c\xd5\x0e\x4a\x75\xa8\xc5\xd6\x99\xd6\xb1\x74\x70\ -\x46\x03\xad\xd8\x6a\x2b\xa8\x7f\x48\x5b\x3f\x2a\x2a\xd3\x99\x85\ -\xcd\x06\xe9\x80\x3a\x53\x09\x83\x7c\x6c\x42\xc6\xd6\x51\xa1\x63\ -\xeb\x07\x30\xa9\x5a\x0a\xe5\xc3\x12\xd8\xdd\x7b\xfa\x47\x50\xdf\ -\x7b\xbb\x9b\xec\x66\xdf\xc6\xa4\xcd\x99\xd9\x3f\xde\xef\x9e\xfb\ -\x7b\xe7\x9e\xf7\xf6\xbe\xfb\xee\xbd\x0f\x18\xc6\x30\x86\xf1\xff\ -\x0c\x0e\xc4\x49\xae\x88\xea\xbc\xd3\x65\x98\x49\x6b\x2f\x93\xc1\ -\x04\x8a\x17\x0b\x38\x07\xc0\x48\x00\x01\x00\xc7\xce\xfc\xf6\x0b\ -\xda\x0b\x98\x37\x11\xc4\xf6\xf6\xf9\x7c\xa7\xd4\xda\x4a\x66\xc0\ -\xf4\xb8\x2e\x49\x5b\xbb\x08\xe4\x7c\x00\x93\xfa\x95\x44\x78\x07\ -\x46\x5b\xac\x35\x4f\x77\x34\x60\x0f\x48\xf9\xab\xd2\x6f\x03\x24\ -\xd6\xc5\x71\xb5\x85\x96\x02\x98\xed\x67\x6a\x02\xaf\x0b\x5c\x95\ -\xfa\x27\x9e\xeb\xbc\x8d\x49\x1f\xf3\xfa\x83\x70\x4c\xb3\x61\xf4\ -\x20\x84\xa9\x7e\xe5\xcc\x81\x77\x05\x2e\x6f\x8f\xe0\x19\x3f\xee\ -\x88\xa2\x0d\x08\x6f\xd4\x05\x4a\xdb\x87\x08\x7e\xa7\x17\x9a\x05\ -\xb0\x03\x54\x9b\xac\xd9\x67\x02\xf8\xbb\x52\x38\x6c\x2d\x8e\x8f\ -\x00\xd2\x27\x0d\x2a\xcb\x80\x51\x32\x18\x27\x60\x3c\xa0\x3a\x00\ -\xdf\x04\x10\xea\x25\xe7\x76\x6b\xb9\xa4\x63\x01\xdf\x28\x46\x7f\ -\x51\x06\xd4\xc5\x35\xcd\x4a\xad\x00\xbe\x98\xa5\xf8\x38\xa8\xcd\ -\x94\xd9\x64\x81\x17\xda\x1b\xf8\xaf\x82\x72\x47\x15\x4a\x07\x70\ -\x15\x69\xe7\x01\x9c\x9f\xe3\x1c\xdd\x22\x6f\x69\x8f\xf0\x0f\xfd\ -\xd1\x0f\x14\x61\xc0\xb4\x98\x6e\x04\xf5\x14\x81\x0a\xaf\x28\x4a\ -\x8f\x06\x2b\xcc\x2f\x5f\x99\xcb\x23\xfd\xcd\xef\x44\x75\x54\xe5\ -\x95\x41\x2c\x06\x74\x2f\x80\xf3\xbd\xe5\x82\x56\xb6\xff\xc5\xdc\ -\x8b\x15\xb4\x85\xe6\x2e\xdc\x80\x66\x99\xf0\x24\x7b\x1f\xc8\x65\ -\x9e\x12\x2b\xe8\x29\xca\xac\x48\x34\xf2\x60\xc1\x79\xf3\xc0\xd7\ -\x37\xaa\x32\x69\x71\x27\xa5\xbb\x00\x9c\xed\x2a\x14\x5a\x43\x69\ -\x2e\x6c\x6b\xe2\x89\x42\x72\x16\x66\x40\xb3\x4c\xf8\x72\xbb\x0e\ -\xe0\xf5\x9e\x92\x2e\x43\x46\x76\x45\xd8\x5e\x50\xbe\x7e\x22\x1c\ -\xd3\x45\x30\x8a\x7b\x3b\x5c\x11\xaf\xb2\x82\xb3\x12\x73\x78\x2c\ -\xdf\x5c\xa6\xa0\x13\x7f\xd5\x2e\xcf\xd2\xf8\xdd\x29\x71\xea\x40\ -\x35\x1e\x00\x12\x8d\x3c\x68\x92\x9c\x29\x68\x9d\x33\x4e\xe1\x6b\ -\xec\xd6\xba\xeb\xa2\x0a\xe4\x9b\x2b\x6f\x03\x6a\x63\xfa\x36\xc4\ -\x7b\x5c\x27\x84\xd6\x86\x8e\x72\x76\x67\x23\xff\x91\x6f\x1e\xbf\ -\xb0\xab\x89\x27\xdb\x23\x66\xa1\xc8\x9f\x02\xf8\xe4\x71\x28\x60\ -\xee\x81\x80\xbd\x3f\xdf\x3c\x79\xfd\x05\xa6\x6d\xd0\x54\x1a\x6d\ -\x07\x30\xe2\xd3\xa8\x9e\x4b\x44\xcc\x4d\xa5\x18\x9d\x15\x8a\x70\ -\x4c\x3f\x02\xb5\xda\x19\x13\x78\x73\x7b\x03\x9f\xe9\xab\x6e\x9f\ -\x77\xc0\xb4\x16\x8d\xa1\x51\x2b\x5c\x8d\x47\x7b\xe8\xa8\x59\x3c\ -\x18\x1a\x0f\x00\x89\x06\x3c\x02\xe8\xf7\xce\x18\xa1\xc7\x6b\x63\ -\x9a\xdc\x57\xdd\x3e\x0d\x20\xec\x83\x00\x2e\x74\x84\xba\x82\x01\ -\x46\xda\xbe\xcb\xee\xc2\xa5\x96\x08\xa4\x46\x8f\x30\x4b\x24\xec\ -\x74\x44\xcb\x45\x3d\x3e\x6b\xab\x82\xbd\x55\xed\xd5\x80\x70\x8b\ -\x66\x00\xbc\xc5\x11\x12\xc4\xc6\x1d\xf5\xec\x2a\x46\x6f\x29\xb0\ -\x65\x0e\x4f\x31\xc8\x06\x00\x87\x1c\xe1\xc9\xdd\x47\x70\x7b\x6f\ -\xf5\x72\x1b\x20\x11\xd0\x2f\x3c\xc1\x75\x89\x46\xee\x2e\x42\x67\ -\x49\x91\xa8\xe7\x07\x10\x57\x3a\x63\x82\xee\x99\xf4\xa2\xce\xca\ -\x55\x27\xa7\x01\x75\x71\xcc\x04\x30\xc3\x11\x4a\xa6\xad\x69\x2e\ -\x5e\x66\x69\x11\x3a\x86\xdf\x90\xd8\xef\x08\x9d\xfb\xb9\x8f\x70\ -\x5b\x2e\x7e\x4e\x03\x2c\xf4\x13\xe7\x31\xa5\xdf\xee\x59\xc0\xb7\ -\x7d\xd0\x58\x52\xf4\xf4\x4d\x74\x5d\x28\x41\x77\xe6\x1a\x1b\x64\ -\x35\xa0\x26\xaa\x2f\x00\xf8\x96\x23\x94\x54\xd0\xdc\xe7\x9f\xcc\ -\xd2\xa2\x2a\x89\x67\x01\xbc\xe5\x08\x5d\xf8\x9e\xc1\x37\xb2\x71\ -\xb3\x1a\x10\x08\xe2\x46\xf4\x4c\x55\xf5\x80\x78\x39\x51\xcf\x0f\ -\xfc\x14\x59\x4a\xac\x6f\x62\x9a\xd0\x7a\x67\x8c\xc6\xde\x9c\x8d\ -\x9b\xd5\x00\x41\xf3\x5c\x01\xcb\xe7\x7d\x53\x37\x50\x30\xc6\xa3\ -\x99\x73\xb2\xfd\x0d\x32\x0c\x38\xd3\x63\x4e\x77\xc6\x52\x69\xfc\ -\xd1\x67\x79\x25\xc7\xee\x57\xd1\x01\xc0\x79\xd7\x8e\x3a\x58\x86\ -\x29\x5e\x5e\x86\x01\x15\xff\x41\x2d\x80\x72\x47\xe8\xcf\x9d\x4d\ -\xdc\xef\xe5\x0d\x7a\xac\xa0\xa5\xe4\xba\x70\x52\xe6\x3c\x65\x86\ -\x01\x06\xf8\x8a\xab\x12\xb5\xdd\x7f\x75\x03\x03\x4b\xe3\xd2\x2e\ -\xda\x89\x5e\x4e\x66\x1f\x20\x7b\xa9\x8b\x60\xcd\x5b\x19\x9c\x21\ -\x82\x80\x81\x47\x3b\x2f\xf5\x72\x32\x0d\x20\xbf\xe4\x3c\xb4\xc0\ -\xa0\x7f\xf6\xe7\x42\xea\xb4\x47\xbb\x30\xce\xcb\xc9\x30\x40\x16\ -\x95\x1e\xc2\xbf\x7d\x57\x36\x40\x38\xeb\xa3\x0c\xed\x95\x5e\x4e\ -\x86\x01\xa4\x9b\x64\x89\x82\xe6\xd8\x06\x13\xda\x16\xe1\x14\x80\ -\x94\x23\x54\x5e\x1d\x95\xb3\x83\xcf\x62\x80\x67\x92\x84\x16\x83\ -\xe2\x9d\xbf\x54\xc8\xfc\x0b\x00\xc7\x9d\xc7\xde\x3b\x62\x28\x61\ -\xd6\xd3\xa8\x00\xe0\x9c\x0f\x38\xfd\x66\x13\x4f\x3b\x39\x59\x3a\ -\x41\xb8\x66\x54\x6d\xcf\x2a\xee\x90\xc4\xc9\xd1\x18\xe5\x09\x1d\ -\xf7\x72\x32\x0d\xb0\x7a\xcf\xc3\xc8\xe8\x39\x87\x0a\x94\xc6\xc5\ -\x9e\xd0\xbb\x5e\x4e\x96\x77\x01\xb3\xd7\x79\x44\xd9\x2f\xfb\x29\ -\x6a\x80\xe1\xd2\x2e\x68\x9f\x97\x90\xed\x2f\xe0\x59\x6c\xe4\x8c\ -\x0c\xce\x10\x01\x61\x67\xb8\x8f\xcd\xeb\x5e\x4e\x86\x01\xa1\x14\ -\x76\x01\x70\xae\xbf\x4f\x0e\xc7\x74\x91\xff\xf2\x4a\x8c\x66\x19\ -\x80\x73\x5d\x31\xa1\xcd\x4b\xcb\x30\xe0\xcc\xda\xda\x2e\x57\x3d\ -\x62\xae\x97\x37\xd8\x51\x33\x09\x53\xe0\x5e\x51\x3e\x16\x1a\x8d\ -\x3d\x5e\x5e\x8e\xf9\x00\xba\xde\xa2\x08\xcd\xf7\x57\x5e\xe9\x61\ -\x60\x5d\x9a\x05\xbd\xd0\x36\x9b\xa9\x4c\x5e\x16\x94\x05\xb0\x0e\ -\x3d\x9b\x1a\xce\x54\xc6\x55\x57\x44\x75\x9e\xef\x2a\x4b\x85\x66\ -\x19\x90\x0b\x9c\x21\x5a\xb3\x36\x1b\x35\xab\x01\x3b\xea\xd9\x25\ -\xe0\xa5\x4f\x2a\x03\x15\xc9\xa0\xf5\x2e\x87\x0f\x5a\xd4\x5e\x8e\ -\x1b\x00\x4c\x70\x84\xde\x0f\x8d\xf9\xb4\x3d\x4e\xe4\x9c\x15\x16\ -\xf9\x6b\xd7\x31\xf8\x83\xe9\x31\x8d\xf5\x47\x62\xe9\x50\x1d\x55\ -\xb9\xa4\x9f\x3b\x63\x22\x57\x67\xbb\xfd\x81\x5e\x0c\xe8\xb8\x16\ -\x2f\xc3\xdd\x19\x96\xa7\x61\x97\xfb\xa2\xb2\x84\x38\xbb\x0c\xdf\ -\x03\x5d\x83\xb7\xc3\x65\x06\x6b\x72\xf1\x73\xaf\x0c\x91\x22\x79\ -\xb7\x27\x76\x53\x38\xae\x8c\x79\xb5\xc1\x82\x29\xcf\xeb\x5c\x4a\ -\xae\x25\x7c\x88\xf7\xef\xa8\x67\xc6\x10\xf8\x63\xf4\xba\x36\xb8\ -\x3b\xc2\x36\x50\xcf\xba\xf8\x52\x3c\xbc\x51\x17\x14\x27\xd5\x7f\ -\x54\x47\x55\x1e\x48\x69\x03\xdc\x7b\x88\x5e\x4b\x1d\xc2\xa3\xbd\ -\xd5\xeb\x73\x75\x38\x20\x73\x17\xdc\xb3\xab\x55\x4a\xa9\xe5\x9a\ -\xcd\xf2\x6e\x8e\xfa\x4c\x31\x32\x68\x1f\x21\x70\xa5\x23\x94\x34\ -\xe4\xe2\xbe\x36\x55\xf6\x69\xc0\xce\x06\x7e\x08\xf1\x5a\x01\xa7\ -\x3e\x8e\x91\x98\x7e\xb8\xdb\x3e\xd6\xb3\x80\xfa\xd9\x23\x1c\xd3\ -\xed\x02\xbf\xef\x8c\x89\x5c\x92\xcf\xb6\x9d\xbc\x1b\x10\x8e\x69\ -\x21\x28\xf7\x8e\x0b\xe9\x77\xc7\xd3\xe6\x0e\xef\x3b\xf6\x80\x41\ -\x62\x6d\x1c\x77\x08\x5a\x0d\xe7\xc5\xa4\x1e\x4e\x44\x02\x3f\xce\ -\x27\x45\x41\x57\xb0\x36\x96\x7e\x40\xe4\x52\x97\x06\x60\x5b\x3a\ -\xc8\x05\x9d\xf3\x79\x28\x57\xbd\x52\xa0\x3a\xaa\xf2\x91\x01\xfb\ -\x98\xc8\x5b\x5d\x05\xc4\x8b\xa1\x73\x38\x37\xd7\x63\xcf\x8b\x82\ -\x76\x89\x55\xa5\xcd\xdd\x04\xe2\xee\xf3\xe1\xca\x60\x4a\x1d\x75\ -\xad\xba\xac\x90\x5c\xc5\x60\x7a\x8b\xce\xaf\x0c\xea\x4f\x19\x8d\ -\x07\xde\x38\x05\x5e\x9f\x6f\xe3\x81\x7e\x6c\x94\xbc\x2e\xaa\xc0\ -\x81\xa0\xfd\x95\x40\xef\x2d\x96\x04\xb4\x26\x00\xb3\x72\x67\x03\ -\x3f\x2c\x34\x6f\x3e\xa8\x8b\x2a\x94\x0e\xe2\x87\x84\x96\x01\xf8\ -\xbc\xa7\x78\x4b\x2a\xc5\x1b\x3a\x9b\x78\xb4\x90\x9c\xfd\xdf\x2a\ -\x1b\xd7\xad\x94\xd6\x00\x28\xf3\x14\x9d\xa0\xf4\x90\x42\x66\x55\ -\x21\x1b\x16\x7b\xc3\xac\xad\x0a\x76\x1f\xc6\x22\x51\xcb\xe1\xde\ -\xaf\x04\x00\x10\xb4\x6a\x6c\xca\x2c\x5d\xdf\xc4\x74\xa1\xb9\x8b\ -\xea\xc5\x6b\x62\x9a\x69\xa8\x16\x00\x63\xb2\x14\x1f\x01\xb4\x09\ -\x32\x9b\x10\xc2\x4b\x85\x9a\x51\x1d\x55\xf9\x48\x83\x99\x32\x76\ -\x1e\xc0\x7a\x00\xd9\x86\xe1\x49\x91\x4b\xda\x23\x7c\xb2\x3f\xfa\ -\x01\x1f\xb6\xcb\xd7\xb4\xaa\xca\x58\x3d\x0c\xa0\xa1\x17\x5a\x12\ -\xc4\x36\x59\x6e\xa5\xc1\x5f\x25\xfc\x4d\x06\x87\x2b\x82\x38\x91\ -\x34\x48\x9b\x13\xa8\xb4\xe5\x18\xa5\x34\xc6\x81\x18\x4f\xd8\x3a\ -\x80\x57\xa3\xe7\x93\x9a\x5c\xc2\x3b\x44\x2e\x49\x44\xd8\x59\x8c\ -\x7e\xdf\x9e\xe3\xb5\x71\x5d\x23\xe9\x01\x00\xa5\xee\x0c\xbb\x24\ -\xfe\x6c\x6c\x1a\x4f\xf4\xe7\x96\xf7\xc2\xdf\x81\x4c\xb3\xcc\xb4\ -\x49\xa8\x37\xd4\x32\x01\x35\xbe\xe6\x06\xde\x06\xb8\x2a\x74\x14\ -\x4f\xfa\xb9\x47\xb1\x64\x23\xb9\x9a\x0d\x9a\x68\x8c\x5d\x74\xe6\ -\x63\x87\xf1\xfd\x4c\xf3\x3e\xa0\xcd\x56\x66\x6d\xc7\x6b\x78\xa5\ -\x3f\xdf\x03\xf4\x85\x01\x19\xca\xd6\xb4\xaa\x8a\x16\xb3\x8d\xec\ -\x44\x91\x13\x00\x8c\x23\x31\x4a\xc2\x48\xf4\xac\xdc\x1c\x45\xcf\ -\x67\x73\x07\x00\xed\x23\xcd\x3e\x11\xdb\x12\xf5\xd8\x3b\x58\xb6\ -\xe3\x0e\x63\x18\xc3\xf8\xdf\xc4\x7f\x01\x16\x1d\xd4\x53\x92\x2f\ -\x1f\x88\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\xeb\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\x9d\x49\x44\x41\x54\x78\x9c\xed\ -\x9a\xbd\x6e\x13\x41\x14\x46\xcf\x75\x08\xa1\x09\x5d\xde\x80\x37\ -\xb0\x5d\xd1\xf0\x08\x34\x58\x36\x09\x08\x1a\x7b\x0b\x6c\x57\x74\ -\xb4\x3c\x80\x6d\x90\x6c\x37\xfc\xe6\x47\x50\x20\xde\x80\x1a\x70\ -\xc5\x73\x20\x21\xd1\x40\x24\x7c\x29\x22\x24\x33\x5e\xc7\xb1\x77\ -\x66\x76\x66\xe3\x5b\xee\xde\xfd\x34\xe7\x68\x76\x76\x35\x1a\xd8\ -\xd4\xa6\x36\x75\x99\x4b\xf2\x1e\x80\xeb\x2a\x37\x07\xb7\x11\x7d\ -\x2a\xc2\x0f\x9d\x4a\x32\x19\xb7\xbf\xcd\xde\xbf\x92\xd7\xc0\x7c\ -\x54\x25\xe9\xd5\x51\x3d\x04\x4a\x28\x48\x49\x87\xc0\xcd\xd9\x9e\ -\x52\x3e\x43\x73\x5f\x67\xf0\x72\x06\xff\xaf\x94\xeb\x66\x5f\x21\ -\x05\xa4\xc2\xc3\x1f\xd0\x27\x66\x6f\xe1\x5e\x81\x45\xf0\xaa\xd2\ -\x98\x8c\x3b\x1f\xcd\xfe\x42\x2d\x82\xe7\xc3\xb7\xdf\xa7\x3d\x53\ -\x18\x01\xeb\xc0\x43\x41\x04\xac\x0b\x0f\x05\x10\x90\x05\x1e\x22\ -\x17\x90\x15\x1e\x22\x16\x60\x03\x1e\x22\x15\x60\x0b\x1e\x22\x14\ -\x60\x13\x1e\x22\x13\x60\x1b\x1e\x22\x12\xe0\x02\x1e\x22\x11\xe0\ -\x0a\x1e\x22\x10\xe0\x12\x1e\x02\x17\xe0\x1a\x1e\x02\x16\xe0\x03\ -\x1e\x02\x15\xe0\x0b\x1e\x02\x14\x60\x1b\xbe\xdc\x1c\xdc\x91\x92\ -\x3e\x07\x28\xa1\xad\xcf\xc3\xee\x87\xd9\xfb\x41\xed\x08\xd9\x86\ -\xaf\x24\xbd\xba\x88\x9e\xa0\xec\xa1\xec\x4d\x91\x91\xd9\x13\x8c\ -\x00\x17\xf0\x29\x79\x73\x15\x84\x00\x4f\xf0\x53\x41\x1f\x99\xbd\ -\xb9\x0b\xf0\x06\x2f\xdc\xff\x32\xec\xbe\x33\xfb\x73\x5d\x04\xfd\ -\xc2\x77\x0e\xd3\x9e\xc9\x4d\x40\x08\xf0\x90\x93\x80\x50\xe0\x21\ -\x07\x01\x21\xc1\x83\x67\x01\xa1\xc1\x83\x47\x01\x21\xc2\x83\x27\ -\x01\xbe\xe0\x55\xe5\xde\x64\xdc\x3e\x5a\x25\xcb\xb9\x80\x90\xe1\ -\xc1\xb1\x80\xd0\xe1\xc1\xa1\x80\x18\xe0\xc1\x91\x80\x58\xe0\xc1\ -\x81\x80\x98\xe0\xc1\xb2\x80\xd8\xe0\xc1\xa2\x80\x18\xe1\xc1\x92\ -\x80\x58\xe1\xc1\xc2\x19\x21\x5f\xf0\xc0\xc1\x64\xdc\x3e\x5e\x35\ -\xaf\x9a\xf4\x6a\x8a\x3c\x03\x07\x7b\x82\x3e\xe1\xbf\x8e\x3a\xab\ -\xc3\xb7\x06\x07\xaa\x72\xec\x64\x4f\x30\x0a\x78\xf4\x15\x4b\x18\ -\xd7\x12\x10\x3c\x7c\xd2\xdf\x4f\x81\xb7\xb3\x27\x18\x05\xbc\xf2\ -\xda\xcc\xb3\xb2\x27\x18\x37\x7c\xc6\x3d\xc1\xd0\xe1\xcb\xcd\xc1\ -\x5d\x11\x7d\x63\xe6\x2d\xfb\x74\x5e\x48\x40\x51\xe1\xe1\x02\x6b\ -\x80\x37\x78\xd1\x7d\xdf\xf0\xb0\x64\x06\x78\x85\x1f\x76\x4f\x56\ -\xcd\xcb\x0a\x0f\xe7\xfc\x09\x86\x0e\x5f\x69\xf5\x1b\x30\x0f\xcf\ -\x8a\x7f\x8c\xa9\x33\x20\x0e\x78\xde\xce\xe5\xad\xb1\x86\x6c\x99\ -\x17\xaa\x49\xaf\x86\xca\x11\x96\xe0\x17\xe4\xad\x0d\x5f\x4d\x7a\ -\x35\x48\xc9\x5b\x73\x01\xfd\x6f\x06\x94\x9b\xa3\x6d\x91\xdf\xdf\ -\x81\xdd\x99\xcb\x19\x0e\x27\xa4\xe6\x65\x78\xe7\xed\xe6\x81\xf1\ -\x15\xd8\x3d\xbd\xba\x05\xec\xcc\x5c\xca\x74\x2c\x25\x25\x2f\xd3\ -\x60\x6d\xe7\x81\x21\xe0\xd3\xcb\x87\xbf\x54\x79\x0c\x9c\x02\x3f\ -\x81\x7a\x96\x33\x39\x66\x9e\x88\x36\xb2\x0c\xd6\x76\xde\xc2\xba\ -\xd1\xee\xef\x94\x9b\xa3\xed\x50\xf3\x6e\x3d\x78\x71\xcd\x66\xde\ -\xa6\x36\x75\x89\xeb\x2f\x57\x3e\x7f\x9e\x34\x61\xbc\xb4\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x87\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x39\x49\x44\x41\x54\x58\x85\xed\ -\xce\x31\x11\x00\x30\x08\x04\x41\x26\xde\x50\x80\x05\xfc\x5b\x20\ -\x22\xa0\xdc\xeb\xff\x67\x23\x16\x65\xf5\x64\xf5\x6c\x3e\xde\x66\ -\x7c\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ -\xc0\x07\xe4\xc6\x04\x35\x1a\x89\x95\x2e\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x86\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x38\x49\x44\x41\x54\x58\x85\xed\ -\xce\x41\x0d\x00\x40\x08\x03\x41\x72\xaa\x90\x87\x21\x24\x92\x9c\ -\x08\x78\xce\xfe\xdb\x4c\xc4\xa2\xec\xa9\xec\xa9\xcd\xc7\xdb\x8c\ -\x2f\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ -\xf8\xac\x79\x05\x03\xdf\x56\x31\xc9\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x03\xa2\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x54\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\xbd\x4f\x53\x51\x18\x87\x9f\xb7\x85\x58\x07\x8d\x9d\x18\x24\ -\x3a\xcb\xa0\x24\x92\x36\x6e\x98\x28\x0c\x1a\x91\x26\xc8\x20\x09\ -\xff\x81\x71\x53\x18\x24\x9a\xf8\x11\x27\x3f\xfe\x02\x12\x17\x31\ -\x82\x18\x1d\x44\x13\x9c\x34\x25\x98\xa0\x03\xce\x12\x1c\x70\xb0\ -\xc4\xc5\x1a\xa4\xaf\x83\x17\x73\xef\xed\xad\xd2\x9e\x7b\x7b\x40\ -\xce\xb3\x9d\xf7\x9e\x9e\xfe\xde\xdf\x3d\x5f\x69\xcf\x01\x87\xc3\ -\xb1\x93\x91\xcd\x54\xea\x9e\xd5\x96\x72\x89\x33\x15\x2a\x83\x82\ -\x74\x29\xec\x17\xd8\x95\xb4\xb8\x7a\x50\xf8\x21\xf0\x59\xd1\xf9\ -\x14\xa9\x87\x99\x2c\x4f\x5f\x1f\x97\x9f\xff\xfa\xdc\x3f\x0d\xc8\ -\x4f\xea\x49\xd0\xbb\xc0\xa1\x58\x94\x36\x8f\x45\x90\x8b\xc5\x82\ -\xbc\xfc\x5b\xa5\x54\xcd\x27\xaa\x92\x7b\xac\xa3\xa0\x33\x6c\xbf\ -\xe4\x01\x3a\x40\x67\xf2\x53\x3a\x82\x6a\xcd\x17\x5d\xd3\x80\xdc\ -\x24\x23\x22\x7a\x3d\x19\x6d\x4d\x44\xf5\x46\xfe\x09\x97\x6b\x3d\ -\x8e\x74\xc6\xeb\xf6\x33\xa1\x70\x49\x45\xae\x90\xe6\xf9\xc1\x32\ -\x4b\x8f\xce\xc9\x7a\xac\x42\x0d\x19\x98\xd0\xf4\xa7\x0c\x07\x58\ -\xe7\x94\xa8\x5e\x03\xb2\xc1\x1a\xd2\x13\x35\x1c\xaa\x0c\xe8\x9e\ -\xd5\x96\xef\x25\xfd\x80\xbf\xdb\x0b\xaf\x48\xc9\x50\xb1\x4f\x56\ -\x62\x57\x9e\x00\xf9\x69\x6d\xa3\xa2\x0f\x50\x4e\xf8\xc2\x8b\xbb\ -\xb3\x72\x24\x3c\x31\x56\x0d\x81\x72\x89\x33\x04\xc7\xfc\xd7\xb4\ -\xca\xf9\xed\x92\x3c\x40\xb1\x4f\x56\x48\xc9\x10\x50\xf2\x85\x3b\ -\xbc\xdc\x02\x54\x19\x50\xa1\x32\xe8\x2f\xab\xc8\xd8\x9b\x82\x7c\ -\x89\x5f\x66\xb2\x14\xfb\x64\x45\x54\xc6\xfc\xb1\x70\x6e\x10\x61\ -\x80\x20\x5d\x81\x40\x9a\xe7\xb1\xab\x6b\x12\x95\x56\x9e\x05\x23\ -\x72\x34\x5c\xa7\xca\x00\x85\xfd\xfe\xf2\xc1\x32\x4b\x71\x0b\x6b\ -\x16\x11\xda\xdb\xc3\x75\x22\x7a\x40\x70\x87\xb7\xd5\x66\xfb\x7a\ -\x08\x6b\x8f\xda\xbd\xd6\xde\x08\xed\x10\x9c\x01\xb6\x05\xd8\xc6\ -\x19\x60\x5b\x80\x6d\x9c\x01\xb6\x05\xd8\xc6\x19\x60\x5b\x80\x6d\ -\x9c\x01\xb6\x05\xd8\xc6\x19\x60\x5b\x80\x6d\x5a\xe2\x68\x24\x3f\ -\xa5\x3d\xa8\xde\x06\x0e\xb3\xc9\xff\x1a\x0c\x50\xe0\x3d\x22\x97\ -\x8a\xfd\x12\xfe\xdd\xb2\x6e\x8c\x7b\x40\x6e\x52\x87\x51\x7d\x01\ -\x1c\x21\xf9\xe4\xf1\xbe\xa3\x13\xd5\x17\xb9\x49\x1d\x36\x6d\xcc\ -\xc8\x80\xce\x29\xdd\x27\xe8\x7d\x53\x11\x8d\x22\xe8\xbd\xce\x29\ -\xdd\x67\xd2\x86\x91\x01\x19\x38\x06\xec\x31\x69\xc3\x90\xbd\x9e\ -\x86\x86\xd9\xf1\x93\xa0\x91\x01\x65\x78\x0b\x7c\x8b\x49\x4b\x23\ -\x7c\xf3\x34\x34\x8c\x91\x01\x0b\xfd\xb2\xaa\xc8\x05\x93\x36\x4c\ -\x50\xe4\xc2\x42\xbf\xac\x9a\xb4\x61\x3c\x04\xe6\x0a\x32\x8e\x48\ -\x2f\xb0\xc0\xef\x25\x2a\x69\x36\x96\xc1\xde\xb9\x82\x8c\x9b\x36\ -\x16\xcb\x3e\xc0\x5b\x8f\x8d\xd7\x64\x1b\xb8\x49\xd0\xb6\x00\xdb\ -\x38\x03\x6c\x0b\xb0\x8d\x33\xc0\xb6\x00\xdb\x38\x03\x6c\x0b\xb0\ -\x8d\x33\xc0\xb6\x00\xdb\x38\x03\x6c\x0b\xb0\x8d\x33\x20\x1c\x50\ -\xf8\xe1\x2f\x0f\x4c\x68\xba\x79\x72\xe2\x25\xac\x3d\x9c\x1b\x44\ -\x1f\x92\xfa\xec\x2f\x7f\xca\x70\x20\x7e\x69\xcd\x21\x42\xfb\x72\ -\xb8\x4e\x44\x0f\xd0\xf9\x40\x60\x9d\x53\xf1\xca\x6a\x1e\xa9\x35\ -\x4e\x07\x23\xfa\xae\xaa\x4e\x75\x20\xf5\xd0\x5f\x16\xd5\x6b\xf9\ -\x69\x6d\x8b\x5b\x5c\xd2\xe4\xa7\xb5\x4d\x45\xaf\xfa\x63\xe1\xdc\ -\x7e\xc7\x42\x64\xb2\x3c\x05\x3e\xfa\x42\x59\x2a\xfa\x60\x3b\x99\ -\xf0\xe7\xb0\x74\xf0\xc4\xf8\xa2\x97\x5b\x80\xba\x8e\xcb\x8b\xca\ -\x58\xa5\x95\x67\x5b\xf9\xb8\x7c\x6a\x8d\xd3\xde\x9b\x6f\xec\xb8\ -\xfc\x06\xb9\xc7\x3a\xfa\x5f\x5c\x98\x00\x10\x19\x2d\xf6\xcb\xcd\ -\xa8\x47\x35\xf7\x01\x73\x05\x6e\x22\x32\x9a\x9c\xaa\xa6\xa0\x20\ -\x23\xc5\xb3\xdc\xaa\x55\x61\xb3\x97\xa6\xee\x00\x1d\xb1\x4a\x4b\ -\x9e\x4d\x5d\x9a\xaa\xfb\xda\x9c\x77\xe4\xbc\x7d\x2b\x5e\x9b\x03\ -\x96\x41\xdf\xd5\x73\x6d\xce\xe1\x70\xec\x6c\x7e\x01\x43\x8d\x07\ -\x87\xbb\xe6\x3f\x9a\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ -\x82\ -\x00\x00\x08\xe5\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x08\x97\x49\x44\x41\x54\x78\x9c\xed\ -\x5b\x6d\x6c\x14\xc7\x19\x7e\xde\xb9\x0f\xdb\xa1\xfe\x68\x21\xa1\ -\xc8\xd0\x06\xac\x20\x28\xa6\x2a\x98\x56\x35\x45\x60\xc0\x9c\xeb\ -\xaa\x98\xf8\x60\xd5\x90\x0a\x62\xe3\x8f\x86\xa4\xad\x4a\x94\x46\ -\x02\x29\x39\xdc\x86\x7e\xa4\x0d\x09\x89\x14\x08\x9c\x8d\x21\xd0\ -\x48\x3d\x6c\x23\x93\xc6\xe1\x6c\xa7\x46\xa4\x80\x42\x20\x55\x02\ -\x36\x51\x52\x87\x50\x6a\x25\x51\xb1\x9d\x03\x81\xed\xbb\x9b\xb7\ -\x3f\xf8\xda\xdd\x5b\x9f\xef\x7c\xbb\xae\x69\xfd\xfc\x9b\x67\xde\ -\x7d\xf7\xd9\xe7\x66\x67\x66\x67\xe6\x80\x31\x8c\x61\x0c\xff\xcf\ -\xa0\x91\xb8\x49\xa1\x52\x7a\x77\x50\xda\x17\x0a\xe2\xd9\x92\x31\ -\x83\x80\x69\x00\x67\x80\x28\x0d\x12\x36\x10\x02\x00\x02\x20\xbe\ -\x00\x89\x0e\x16\xd4\x2e\x08\x47\xfd\x3e\xef\xc7\x56\x6b\xb3\xcc\ -\x80\x25\xf7\x57\x66\x09\x7b\xb8\x44\x30\x15\x31\xf0\xcd\x61\xa6\ -\xf9\x98\x99\x9b\x18\xa2\xb6\xb5\x7e\xd7\x3b\x00\xd8\x4c\x8d\x80\ -\xf9\x06\xd0\xd2\xe2\xb2\x02\x12\xe2\x09\x02\x2f\x36\x39\xf7\x19\ -\x26\x6c\xed\xf9\x8a\xd8\x77\x6a\xe7\xce\xa0\x59\x49\x4d\x33\xa0\ -\xc0\xbd\x6e\xb1\x24\xf1\x0c\x80\x79\x66\xe5\x34\x06\x9f\x27\x60\ -\xb3\xbf\xae\x7a\x2f\x4c\x68\x11\x09\x1b\xb0\xb4\xa8\x7c\x22\xd9\ -\xf1\x2c\x11\x7e\x1c\x25\x4c\x32\xf0\x37\x62\xb4\x31\xf8\x9c\x20\ -\xdb\x3f\x18\xd4\x1d\x14\xfd\x97\x53\x40\xe1\x81\x30\x52\x89\x44\ -\x3a\x88\xa6\x82\x31\x9d\x88\x73\xc1\xb4\x0c\x40\xca\x60\x09\x19\ -\x38\x6a\x03\xad\x3f\x5c\xb7\xeb\x6c\x22\xfa\x13\x32\xa0\x40\x29\ -\xfb\x8e\x94\x74\x10\xc0\x24\x7d\x1d\x03\x97\x01\xbc\x2e\x88\x0e\ -\x85\xc3\xfd\x6f\xb4\x36\xec\xbd\x14\x4f\xee\x5c\x65\x43\xca\xb8\ -\x70\x60\x09\x41\x2c\x07\x71\x91\xd1\x3d\x00\xf4\x01\x58\xd7\x5c\ -\xe7\x7d\x75\x58\x0f\x80\x04\x0c\xc8\x77\x97\x3d\x48\x44\x35\x00\ -\x92\x22\x44\x11\xbd\xe0\x74\xda\x7f\xf7\x97\x3f\x6d\xef\x19\x6e\ -\x7e\x35\x14\x45\x71\xf6\xca\xf4\x0a\x00\x4f\x01\xb8\x47\x5f\x4f\ -\xc0\x96\xdc\xec\xcc\xa7\xaa\xaa\xaa\x64\xbc\xb9\xe3\x36\xc0\xe3\ -\xf1\x88\x63\x67\xbb\x9e\x06\xf3\x46\x5d\x95\x04\xa3\xc6\x0e\x54\ -\x35\xd5\x7b\x2f\xc6\x9b\x37\x16\x14\x15\xad\x4b\xbd\x6a\x17\x8f\ -\x11\xe1\x71\x00\x5f\x52\xd7\x31\xe8\x60\x48\x38\xd6\xb4\xf9\x5e\ -\xba\x12\x4f\xce\xb8\x0c\xf0\x78\x3c\xe2\xd8\xfb\x17\xf7\x83\xe8\ -\x01\x5d\x96\x2e\x41\x5c\x7c\xd8\x57\xfd\x76\x3c\xf9\x86\x8b\x42\ -\x77\xf9\xe4\x10\xa1\x01\x91\x1d\xee\xbb\xf6\xe4\x6b\x79\x4d\xfb\ -\xf7\x07\x62\xcd\x65\x8b\xe7\xc6\xce\xf1\xf7\x55\x81\xe8\x51\x1d\ -\x7d\x42\xb0\x58\x7a\xb8\xce\xfb\x41\x3c\xb9\x12\xc1\x47\x1d\xa7\ -\x03\x13\xb3\x17\xed\x73\xc8\x81\x7b\x89\x34\x73\x8c\x49\xe1\x90\ -\x63\x76\x4e\x76\xd6\x9f\xdb\xdb\xdb\x63\x1a\x21\x62\x36\xc0\xe5\ -\x2e\xff\x11\x08\x2f\xea\xe8\x3d\xc1\xd4\x90\xd2\xfa\x6a\x75\x6f\ -\xac\x79\xcc\xc2\xc5\xf6\x13\xa1\xce\x8e\xd3\x0d\x59\x33\xe7\x5c\ -\x05\x51\x3e\x6e\xb4\x66\x02\xa6\xf7\x21\x25\xb9\xb3\xfd\x74\x4b\ -\x2c\x79\x62\x7a\x05\x96\xad\x5c\x37\x0f\x10\x47\x01\x24\xab\xe8\ -\x7d\xcd\x75\xde\xb5\xb0\x60\x76\x16\x2f\xf2\xdd\xe5\xbf\x20\xc2\ -\x73\x6a\x8e\x09\x0f\xb5\x1c\xf0\xee\x1d\xea\x5a\x31\x54\xc0\xd2\ -\xe2\xb5\xe3\x01\x71\x10\xea\x87\x67\xbc\x1d\x4c\x0d\x55\x60\x14\ -\x3c\x3c\x00\xb4\xd4\x7b\xb7\x81\xb1\x5b\xcd\x11\x63\x57\x81\xbb\ -\x72\xee\x50\xd7\x0e\x69\x00\x89\xa4\x67\x00\x64\xde\x26\xd0\x85\ -\x90\x2c\x6e\xab\xad\xed\x1b\x8e\x58\x8b\xc0\xf6\x6b\x29\xeb\x01\ -\x1c\x53\x71\xce\x30\xc9\x5d\x79\x79\x1e\x7b\xb4\x0b\xa3\x1a\x90\ -\xaf\x54\x2e\x20\xf0\x3a\xf5\x8d\x58\x62\x65\x73\x63\x4d\x57\x02\ -\x62\x2d\x41\x53\xd3\x8b\xfd\x32\x08\x37\x18\xff\xbe\xc9\x11\x30\ -\xd7\x39\xfe\x5f\x8f\x44\xbb\x2e\x9a\x01\x44\xe1\xf0\x6f\x75\xdc\ -\xfe\x96\x7a\xef\x89\x44\x84\x5a\x89\xd6\x46\xef\x67\x0c\x6c\x51\ -\x73\xcc\x78\xd2\xb5\x66\xcd\xb8\xc1\xae\x19\xd4\x80\x65\x4a\xc5\ -\x42\x10\x2d\x50\x51\x41\xc9\x61\x8f\x09\x3a\x2d\x45\x28\x2d\xb4\ -\x03\xc0\x85\x5b\x04\x61\x02\x5f\x4d\xfe\xc9\x60\xf1\x83\xb7\x00\ -\xc6\x2f\xb5\x04\xbd\xdc\x5a\xbf\xbb\x33\x61\x85\x16\xa3\xad\xb6\ -\xb6\x0f\x4c\xba\x1f\x8a\x1f\x53\x14\xc5\x70\xc8\x37\x34\x20\x4f\ -\x29\xf9\x2a\x98\xbf\xaf\xa2\x82\x32\xc8\x4f\x9b\xa6\xd2\x62\x64\ -\xd8\x7a\x5f\x01\xf8\x43\x15\x95\xd9\x23\x33\xf2\x8d\x62\x0d\x0d\ -\x70\x48\xc7\x83\xd0\x4e\x92\xde\x6c\x6d\xf4\x7e\x66\xa2\x46\x4b\ -\xe1\xf3\xf9\xc2\x60\xf2\xa9\x39\x02\x3f\x64\x14\x3b\xc8\x2b\xc0\ -\xcb\x35\x17\x13\x35\x9a\x25\x6e\xa4\x40\x24\xf4\x9a\x7f\x60\xf4\ -\x1a\x44\x18\x70\xa3\xc7\x9c\xaf\xe6\x24\xd1\x6b\xe6\xca\xb3\x1e\ -\xb9\xd9\x93\x4e\x82\xa0\x6e\xb5\xe9\x01\xa4\xe5\xe8\xe3\x22\x0c\ -\xe0\x6b\xce\xef\x02\x70\xaa\xa8\xbf\xb7\xf8\x76\x5e\xd0\xc7\x8d\ -\x76\x54\x55\x55\x49\x30\x34\x3f\x9c\x64\x11\xb1\x4e\x19\xf9\x0a\ -\xb0\xc8\x56\x17\x89\x70\xd4\x74\x75\x23\x04\x02\x6b\xb5\x33\x66\ -\xe9\x63\x0c\x0c\xc0\x4c\x75\x51\x4a\xfa\x30\x22\xe6\x4e\x01\x09\ -\x9d\x76\x9e\xa9\x0f\x89\x34\x80\xf8\x5e\x2d\x21\x47\xfd\xd8\x3f\ -\x18\x06\x28\xa8\xd7\x3e\x55\x1f\x63\x34\x0a\xa4\xaa\x0b\x04\x8c\ -\xf8\xb7\xbe\x69\x18\x17\xa1\x3d\x55\x1f\x32\xa4\x01\x82\x39\xae\ -\x35\xb6\xd1\x84\xb6\xda\xda\x7e\x00\x21\x15\xe5\x54\x14\x45\xdd\ -\xc1\x1b\x1a\xa0\x59\x24\x09\x09\x31\x2a\xbe\xf9\xad\x42\x84\x01\ -\xc4\xb8\xac\x09\x60\x8e\x68\x36\x77\x0a\xf2\x4a\x4a\x92\x00\xa8\ -\xd7\x03\x06\x7c\x3e\xdf\x80\x3a\x26\x72\x1e\x70\x7d\xa7\xf6\x76\ -\x19\xc8\xb0\x46\x9e\xf5\xb0\x75\xdb\xd3\x75\xd4\x65\x7d\x4c\xa4\ -\x01\xc0\x27\x1a\x82\x22\x7b\xce\x3b\x06\x49\x72\x9a\xa6\xcc\x38\ -\xaf\x0f\x31\x9a\x07\x74\xa8\x8b\x04\xba\xcf\x64\x59\x23\x06\x62\ -\xa1\xd1\xce\xc0\x39\x7d\x4c\x84\x01\x82\xa1\xd9\x6c\x64\x60\x81\ -\x3e\xe6\x4e\x81\x60\xd6\x6a\x27\x9c\x89\x88\xd1\x13\x03\x76\xe7\ -\x71\x00\xb7\xf6\xdf\x09\x98\x5b\xe8\x2e\x9f\x6c\x85\x40\x2b\xe1\ -\xf1\x78\x04\x83\x7e\xa8\x21\x19\x6d\xfa\xb8\x08\x03\x6e\xec\xad\ -\x1d\x57\x73\x21\xd2\x25\xba\x03\xf0\xd6\xfb\x5d\x39\xd0\xec\x28\ -\x53\x20\xd4\x9d\xf9\x8e\x3e\xce\x70\x3d\x80\x00\xdd\xe7\xaf\x2c\ -\x32\x55\xdd\x08\x80\x84\x5e\x33\xbf\xd1\xd6\x56\x15\xd2\xc7\x19\ -\x1a\xc0\x41\xb9\x1f\x80\x6a\xab\x99\x96\x14\x2a\xa5\x77\x9b\xaa\ -\xd0\x42\x78\x3c\x1e\x41\x4c\xab\x74\xf4\x1e\xa3\x58\x43\x03\x9a\ -\x1b\x6b\xba\x88\xe0\x57\x51\x49\x41\x69\xd7\x6f\x87\x8f\x5a\x1c\ -\x3f\xdb\xb5\x1a\xc0\x8c\x9b\x65\x02\x3e\x0d\x5e\xca\xf4\x1b\xc5\ -\x0e\xba\x2a\xcc\xe0\x3f\xaa\xcb\x04\x7e\x74\x89\xbb\xec\xeb\xa6\ -\xa9\xb4\x08\x8a\xa2\x38\x99\xf9\xd7\x6a\x8e\x99\x9f\x33\x6a\xfe\ -\x40\x14\x03\x9a\x0f\x54\xbf\x49\xac\xe9\x0c\x9d\x36\xc2\x66\x73\ -\x64\x5a\x87\x1e\x99\x56\x09\xed\x67\x6f\x77\x4a\x88\xb7\x0f\x16\ -\x1f\x6d\x67\x88\xa5\xc0\x26\x2d\x45\x6b\x5d\x4a\x79\xc4\xba\xda\ -\x68\x41\xde\xea\xca\x09\x04\x7a\x52\x43\x32\x7e\xd3\xd8\x58\x13\ -\x31\x05\xbe\x89\xa8\x7b\x83\x2d\x07\xbc\x6d\x00\xbd\xa2\x8e\x67\ -\x89\x86\xa5\x45\xe5\x13\x13\x52\x6a\x01\x14\x45\x71\x3a\xfa\xe5\ -\x01\xa8\xce\x10\x11\xf0\x5e\xf7\x04\xf1\x42\xb4\xeb\x86\xde\x1d\ -\x96\xb6\xc7\x75\xab\xab\x53\x84\x03\xf5\x85\x85\x3f\xd3\x1f\x8e\ -\xfa\xaf\xa2\x57\xa6\x6f\x03\x61\x91\x8a\x0a\x92\xe0\x8a\xa1\x0e\ -\x55\x0e\x69\x80\xbf\x61\xc7\xe7\x2c\x71\x3f\x80\x7e\x15\x3d\x3f\ -\x78\x57\xdf\x4b\x18\xa1\xb3\xc6\x43\xc1\xb5\xaa\xe2\x11\x00\x0f\ -\xab\x39\x62\xac\x8f\xe5\xcc\x52\x4c\x47\x64\x3a\x3b\x4e\x5f\xcc\ -\x9a\x39\xe7\x13\x10\x15\xdf\xba\x01\x30\x67\xda\x37\xe6\x4e\xca\ -\xc9\xce\xf2\xb7\xb7\xb7\x87\xe3\x56\x6d\x0e\xc8\xb5\xb2\xfc\xe7\ -\x0c\x6c\x83\xea\xc7\x20\xc2\xf3\xfe\x3a\xaf\x7e\x67\xdb\x10\x31\ -\x9f\x11\xea\xec\x78\xf7\xbd\xac\x59\x39\x77\x01\xf8\xde\xad\x1b\ -\x01\x39\x7d\x32\x79\xe1\xd7\xbe\x35\xef\xb5\xf3\x67\x4e\x5d\x8d\ -\x47\x79\xa2\x50\x14\xc5\x99\x39\x73\xfe\xcb\x00\x36\x41\xdb\x12\ -\x0f\x07\x2f\x65\x96\x9e\x3f\x7f\x24\xa6\x33\x83\x43\xbe\x02\x6a\ -\x64\x50\xef\x26\x5c\x3f\x9e\x76\x1b\x84\x45\x8e\x81\xf0\xc9\x7c\ -\xa5\x72\x76\x3c\xb9\x12\x81\xab\xf8\xe1\x7b\x7a\xc3\x69\xad\x00\ -\xca\x74\x55\x67\x83\xe1\xd0\x03\x83\x8d\xf9\x46\x88\xfb\x1d\x56\ -\x14\xc5\xd6\x23\x33\xfe\x40\xe0\x0d\xba\xaa\x20\x80\xed\x24\xed\ -\x5b\xfc\x0d\x3b\x3e\x8f\x37\x6f\x2c\xc8\x55\x36\xa4\xa4\xca\xcb\ -\x3f\x65\xc6\x46\x10\xbe\xac\xad\xe5\x26\x16\xb6\xd5\x2d\xbe\x9d\ -\x5f\xc4\x93\x73\xd8\x9d\x98\xcb\x5d\x5e\xc6\x84\xed\x00\x1c\xba\ -\xaa\x2b\x44\x78\xd6\x96\x74\x6d\x6b\x3c\x07\x16\xa3\x21\x2f\xcf\ -\x63\x77\x4c\xb8\x58\x02\xa6\xcd\x50\x9f\x57\xba\x05\xde\x9a\x21\ -\x02\x4f\xf8\x7c\xbe\xb8\xfb\xa2\x84\x7a\x71\x97\xbb\x6c\x21\x13\ -\xd5\x03\x18\x1f\xa9\x09\x3d\x04\x1c\x02\x70\xc8\x96\x72\xcd\x1f\ -\xaf\x19\x8a\xa2\x38\xbb\xc3\x19\x0b\x05\xf1\x72\x00\x2b\x00\x18\ -\x4d\xc3\x83\xc4\x58\xef\xaf\xf7\x56\x0f\x47\x3f\x60\xc2\x30\xe6\ -\x5a\x51\x3a\x85\xed\xb6\xe7\x01\xb8\xa3\x84\x05\x09\x38\xc2\x84\ -\xbf\x32\xd3\x07\x36\x19\xfe\x88\x25\x77\x3b\xc6\x25\x5f\x91\x14\ -\x08\xf7\x0f\xa4\xa6\x12\xfa\xd3\x29\x2c\xa6\x0a\xc2\x74\x66\xca\ -\x05\x51\x01\xc0\x69\x51\x72\x9e\x24\x81\xf5\x7e\x9f\xf7\x54\x22\ -\xfa\x4d\x1b\xc7\x5d\xab\x2a\x0a\x99\xf9\xf7\x00\xac\xed\x0c\x09\ -\x5d\x00\xff\x2a\x83\x02\xde\xe1\x34\xf9\xc8\x74\x26\xe2\xfa\x61\ -\xea\xae\x15\x20\xde\x08\xe0\xdb\x66\xe6\x06\xd0\x09\x60\x6b\x30\ -\x35\x54\x6d\xe6\x19\x45\xcb\x66\x72\x05\x2b\x2b\x66\x31\x50\xc2\ -\xe0\x22\x00\xd3\x87\x93\x83\x80\x4f\x25\xe8\x75\xc1\x72\x4f\xee\ -\xec\xc9\x6f\x0d\xe7\xff\x00\x31\xdc\xc3\x7a\xb8\x56\x94\x4e\x91\ -\x0e\xdb\x62\x02\xcd\x02\xe4\x0c\x30\x4d\x05\x90\x0e\x20\x0d\xd7\ -\x77\x6e\xbe\x00\x10\x00\xe8\x9f\x00\x9f\x63\xe0\x1c\x8b\xf0\x91\ -\x56\xdf\xee\x0e\x8c\x92\xe3\xb8\x63\x18\xc3\x18\xfe\x37\xf1\x1f\ -\x38\xf1\xe0\xe7\x81\x02\x5e\x62\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x00\xcd\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x7f\x49\x44\x41\x54\x78\x9c\xed\ -\xd9\x51\x0d\x80\x30\x10\x05\xc1\x03\xff\xca\x50\x41\x83\x10\x90\ -\xb1\x24\x9d\x31\x70\x2f\x9b\xfe\x75\x26\x74\xaf\xe7\xbd\xd7\xf3\ -\x96\x1b\xce\xf2\xf8\x1f\x08\x50\x0f\xa8\x09\x50\x0f\xa8\x09\x50\ -\x0f\xa8\x09\x50\x0f\xa8\x09\x50\x0f\xa8\x09\x50\x0f\xa8\x09\x50\ -\x0f\xa8\x09\x50\x0f\xa8\x09\x50\x0f\xa8\x09\x50\x0f\xa8\x09\x50\ -\x0f\xa8\x09\x50\x0f\xa8\x09\x50\x0f\xa8\x09\x50\x0f\xa8\x6d\x1f\ -\xe0\x28\x8f\xd7\x5f\xe3\x33\xf1\x0b\x38\x66\xae\xf2\x3e\x00\x00\ -\x00\x00\x00\x00\x00\x6c\xe2\x03\x9c\x6d\x0b\xf4\x94\x3b\x8d\x4b\ -\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x30\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xe2\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\xb1\x0d\xc2\x30\x18\x05\xe1\x67\x86\x48\x87\x94\x99\x58\x21\ -\x15\x13\xb1\x05\x33\x45\xa1\x61\x0b\x53\x80\xa8\xa0\xb2\x9d\x43\ -\xe2\xbe\x2a\xc5\x2f\x78\xbe\x44\xd2\x3f\x2b\xa3\xff\x60\x5d\x6f\ -\xa7\x94\x5c\x92\x24\x35\xe7\x79\x3e\x5e\x7b\xde\xb7\x3a\x8c\xfc\ -\xf1\x24\x79\x3d\x66\x4a\x32\xbd\x1f\xd6\xf3\xbe\xd1\xf8\x00\xcf\ -\xc7\x7c\xfa\xee\x75\xdf\x64\x8f\x00\x3f\xcd\x00\xf4\x00\x9a\x01\ -\xe8\x01\x34\x03\xd0\x03\x68\x06\xa0\x07\xd0\x0c\x40\x0f\xa0\x19\ -\x80\x1e\x40\x33\x00\x3d\x80\x66\x00\x7a\x00\xcd\x00\xf4\x00\x9a\ -\x01\xe8\x01\x34\x03\xd0\x03\x68\x06\xa0\x07\xd0\x0c\x40\x0f\xa0\ -\x19\x80\x1e\x40\x33\x00\x3d\x80\x66\x00\x7a\x00\xcd\x00\xf4\x00\ -\x9a\x01\xe8\x01\x34\x03\xd0\x03\x68\x06\xa0\x07\xd0\x0c\x40\x0f\ -\xa0\x19\x80\x1e\x40\x33\x00\x3d\x80\x66\x00\x7a\x00\xcd\x00\xf4\ -\x00\xda\x1e\x01\xee\x5f\xbe\x7b\xdd\x37\x19\x1f\xa0\x66\x49\xc9\ -\x96\x92\x2d\x35\x4b\xf7\x7b\x49\x6a\xf0\x00\xc5\x3d\x1c\x34\xe1\ -\xa3\xf7\x6f\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\x2c\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\xde\x49\x44\x41\x54\x78\x9c\xed\ -\x98\xcf\x6b\x5c\x55\x14\xc7\x3f\xe7\xbe\x34\x34\x91\x8a\x60\x71\ -\x93\xb6\x2e\xb2\xd0\x90\x22\xc6\x42\x17\xad\x59\xc4\xa6\x69\x0a\ -\x5a\x35\x31\x0b\x17\x22\x4d\x13\xf0\x1f\x10\x7f\x40\x91\xa0\x82\ -\xba\x50\x0a\x2e\x34\x9d\x69\x04\x89\x05\x33\x9d\x74\x84\x9a\x32\ -\x33\x29\x23\xe2\xaa\x36\xe9\xaa\x31\x5d\x04\x6d\x2b\x88\xa6\x0b\ -\x9b\xd2\x40\x66\xe6\x1d\x17\x49\x63\xdf\x9b\x37\xc9\x64\x66\xde\ -\x34\xda\xfb\x59\xbe\xf3\xee\x79\xdf\x73\xef\xb9\xe7\xbe\x7b\xc0\ -\x62\xb1\x58\x2c\x16\x8b\xc5\x62\xb1\x58\x2c\x16\x8b\xc5\xf2\x60\ -\x21\xfe\x07\x9d\x3d\xfd\xef\x89\x31\xc7\x51\x1c\xc0\x05\xb4\xf6\ -\xb2\xaa\x8a\x00\x06\x21\xaf\xae\xfb\x7e\x3a\x7e\x6a\xe8\x5e\x63\ -\x5d\xc1\xdb\xb2\x1a\x3c\x80\xa9\x85\xc2\x9a\xa0\x38\x22\xe6\x38\ -\xe0\x99\x80\xff\x4f\x80\x65\x52\x30\x01\xaa\xee\x07\xa0\xff\xf5\ -\xb4\x0f\x40\x75\x39\x36\x2f\x05\x35\x00\xe0\x50\x4f\x7f\x47\x5e\ -\x4c\x42\x60\x9b\xc7\x05\xa8\x2c\xd7\x85\xcd\x8b\xaa\x41\xc4\x13\ -\x97\xc2\x02\xc2\x91\x74\x2c\x92\xf1\xbf\x1e\x38\x01\x00\x5d\x7d\ -\x03\x7b\x34\xcf\x79\x84\xed\xfe\x2f\x80\x71\x37\x5f\x6d\x14\x40\ -\x0d\xfe\x98\x94\x79\x71\xe8\x4e\x8e\x45\x2e\x15\x1b\x55\x94\xee\ -\xbe\xfe\x27\xf2\xae\x49\x01\x3b\xbd\x4e\x55\x11\xd9\x6c\x99\x50\ -\x18\x3c\x5c\x73\x8c\xdb\x75\x7e\xec\xd4\x6c\xb1\x41\x6b\x4e\x00\ -\x40\xd7\x8b\x47\x77\x6a\x9d\x93\x04\x9e\xf4\x99\x94\xcd\xb3\x1d\ -\x82\x82\xff\x45\x72\xf9\xae\x64\x62\xe4\xfa\x7a\x03\xd7\x24\x99\ -\x18\xb9\x9e\xad\x37\xed\xc0\xcf\x3e\x93\x80\x3a\x41\x63\x6a\x87\ -\xb0\xa2\xc1\x1f\xfc\xc5\x6c\xbd\x69\x5f\x2f\x78\x28\xf1\x18\xcc\ -\x9c\x1e\x9e\x6f\xc8\xba\xcf\x21\x5c\x28\x22\xa0\xe6\x08\x08\xb8\ -\x4e\x40\x12\x4f\x36\x64\xdd\x03\x99\xd3\xc3\xf3\xa5\xf8\x29\x59\ -\xfc\xec\xec\xf4\xd2\xae\xbd\x4f\x7d\xeb\x64\x4d\x2b\xd0\xe2\x91\ -\x02\xa6\x84\xdd\x54\x45\x44\x8a\x7c\x33\x5e\x77\xa7\xa1\xf7\xdc\ -\xb9\x2f\xef\x94\xea\x69\x43\xab\xf7\xeb\xe5\xcb\xb9\x5d\x8f\xbd\ -\x70\xc6\x69\x5c\x68\x02\x9e\x09\x52\x15\x36\x72\xf7\xd7\xb6\x90\ -\xe8\x23\xe6\xef\xd7\x13\x89\x91\xec\x06\xfd\x95\xa7\xa3\xb3\x77\ -\xe0\x63\x81\x37\x03\x1c\xba\x1a\xd6\x19\x29\x08\x1a\x10\xbc\xc8\ -\x27\xa9\xd8\xc9\xb7\x29\xe3\xbb\x65\xef\xdf\xb9\x99\xa9\x54\x73\ -\x4b\xdb\x22\x22\x07\xfd\x72\xc2\xc8\x85\xa2\x2b\xaf\xfa\x56\xea\ -\x4c\x64\xa8\x70\x44\x69\x54\x54\xc0\xe6\x66\xa6\x7f\x6a\x6e\x6d\ -\xfb\x1d\xe4\x79\xbc\xd9\x54\xd5\x19\x10\x10\x2d\x0c\xde\x15\x65\ -\x30\x15\x8f\x7e\x5e\xa1\xef\xca\xe9\xec\x1d\xec\x15\xf4\x1b\xa0\ -\xde\x67\xaa\xf8\x5f\x41\x51\x13\x90\x52\x4b\x2a\xbc\x9a\x8e\x45\ -\xe2\x95\xf8\x86\x2a\xae\xd4\x81\x9e\xc1\x4e\x23\x7a\x16\x78\xc8\ -\x6b\x51\x85\xf2\xfe\x1a\x15\x8c\x14\x6a\xbc\x8d\xe8\x4b\xa9\x58\ -\x74\xb2\x3c\xa5\x5e\xaa\x9a\xaa\x87\xfa\x8e\xed\x75\x5d\xf9\x1e\ -\x78\xd4\x63\x50\x14\xd9\x60\x26\x28\x06\x29\xd0\x77\xd3\x55\x39\ -\x3c\x19\x3f\x79\xb1\x32\xa5\xff\x52\xf5\x6a\xd5\xf9\xf2\x40\x8b\ -\x18\x52\x40\x93\xcf\x54\xfa\x76\x08\xb8\xd1\x01\x37\xd4\xa5\x2b\ -\x3d\x1e\x99\xa9\x82\xcc\x55\xaa\xde\x10\x49\x8f\x47\x66\xf2\xaa\ -\xfb\x81\xab\x3e\x53\xf0\x11\xe6\x43\x09\x0c\xfe\xaa\x1a\xb3\xbf\ -\xda\xc1\x43\x48\x1d\xa1\x0b\xf1\xe8\x6f\xe2\xd6\xb5\x2b\x4c\x79\ -\x0c\xcb\x29\xbd\xd6\xc9\xe3\xf8\x0b\x9e\xc2\x54\x9d\xc9\x3f\x9b\ -\x1e\x1b\xbe\x16\x82\xd4\xf0\x5a\x62\xc9\xf1\x2f\xfe\xdc\xb2\x75\ -\xb1\x03\xe5\x07\xbf\x4d\x03\x27\x21\xf0\x4e\x91\xd9\xb2\x75\xb1\ -\x63\x62\x6c\xe4\xaf\x10\x24\x02\x21\xf7\x04\x27\x46\x47\x6f\x65\ -\x1f\xce\x75\x23\xfa\xdd\xbd\xcf\x57\x96\xd8\x11\x41\x64\x35\x2b\ -\xbc\x59\x2f\x90\xc8\x6e\xcb\x1d\x9e\x18\x1d\xbd\x15\xa6\xc6\xd0\ -\x6f\x72\xcb\xf7\x87\x23\x31\xa7\x71\xe1\x71\xe0\x69\x9f\x59\x08\ -\x2c\xc4\xfa\x55\xf6\xe6\x8e\xd7\x32\x67\x4f\x2c\x85\xad\xaf\x26\ -\x5d\xe1\x4c\x66\x28\xb7\x6f\x77\x53\xbf\x22\x9f\xad\xff\xb6\x7e\ -\xba\x6f\xf7\x8e\x63\x99\xcc\x50\x2e\x7c\x65\xb5\xbd\xc3\x02\xc8\ -\xc1\x57\x06\xde\x41\xf9\x30\xd0\xa8\xfa\x6e\x32\x1e\xfd\x88\x1a\ -\x36\x1c\x6b\xde\xcc\x98\xbb\x32\xf5\x63\x73\x6b\xdb\x1f\x2b\xf7\ -\x87\xbb\xa8\x28\x6f\x24\xe3\xd1\x13\xb5\xd6\x73\x5f\xba\x39\x73\ -\x57\xa6\x2f\x35\xb7\xee\x69\x64\xb9\xcf\x78\x5b\x94\xa3\xc9\x78\ -\xe4\xeb\xfb\xa1\xc5\x62\xb1\x58\x2c\x16\x8b\xc5\x62\xb1\x58\x2c\ -\x16\x8b\xc5\xf2\xa0\xf1\x0f\x64\x76\x37\x12\x6f\xd4\x61\x03\x00\ -\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xc8\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x7a\x49\x44\x41\x54\x58\x85\xed\ -\xd2\xb1\x0d\x83\x40\x10\x44\xd1\xbf\x4b\x0f\x96\x08\x08\xdc\x09\ -\x9d\x10\x90\xb8\x24\x02\xc7\xae\x81\x6e\x08\x1c\x20\xd1\x03\xb7\ -\x8e\x0e\x59\x42\x22\xe3\x2e\x99\x97\x8d\xb4\xd2\x4c\xb0\x20\x22\ -\x22\x52\x99\xfd\x87\x88\x30\xa0\xb9\xb9\x73\x37\xb3\x38\x0d\x58\ -\x96\x6f\x6f\xce\x07\x68\x6f\x1e\xb0\x85\x33\x3c\xbb\x6e\x06\xf0\ -\x63\x89\x33\x15\x28\x07\x78\x58\xe2\x9d\x83\x5f\x5d\x96\x70\x0c\ -\x88\xc4\x0b\x58\x0b\x74\x6e\x61\x31\xe6\x50\xfd\x09\x45\x44\x44\ -\xaa\xfb\x01\x02\x66\x1a\x07\xaf\xc1\xa8\xac\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\x63\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x15\x49\x44\x41\x54\x78\x9c\xed\ -\x99\x5f\x48\x53\x61\x18\xc6\x9f\xef\x9c\xcd\xe9\xa0\x14\x2b\x92\ -\xbc\x52\x8c\xae\xba\xda\x99\x56\x26\x44\x04\xa1\x37\x15\x61\xd1\ -\x55\x46\xe2\x51\x6b\xb3\x24\xe8\x22\x68\x17\x75\x17\x99\x6d\x91\ -\x73\x81\x7a\x11\x12\x49\x10\x05\x26\x04\xd9\x45\x65\xe5\x66\x94\ -\x41\x08\xf6\xe7\xa2\x34\x44\x4b\x34\x1c\xfb\xfb\x76\x63\x31\xb7\ -\x63\x43\xf0\xfb\x8e\xd0\xf7\xbb\xdb\xfb\xc2\x9e\xe7\x7b\xce\xbb\ -\x9d\x77\x67\x80\x44\x22\x91\x48\x24\x12\x89\x44\x22\x91\x48\x24\ -\x92\xff\x0d\xc6\x5b\x40\xd3\xbd\xbd\x00\x8e\x01\x00\x63\x38\x31\ -\xec\x77\xf7\xf0\xd6\x5c\x09\x5c\x03\xd8\x53\xd7\x9d\xfb\xcb\x36\ -\x1f\x4e\xad\x11\xd1\xde\x50\xa0\x65\x90\xa7\xee\x4a\x50\x78\xbe\ -\xf9\x94\x7d\xc1\x92\x5e\x63\x8c\x3d\xd1\x9a\xda\x4a\x79\xea\xae\ -\x04\x11\x1f\x01\x32\xaa\xdb\x62\xe1\xf5\xcf\xbb\xce\xcf\xf3\xd6\ -\xcf\x06\xd7\x09\x00\x80\x92\x1f\x45\x19\x53\x00\x00\x11\x6b\xde\ -\x1c\x3c\x1e\xee\xfa\xd9\xe0\x6e\xa0\xaf\xef\x48\x42\xcd\x41\xbe\ -\x51\x4f\xfb\xbe\x21\xc1\x5b\x3f\x1b\x42\xae\xc0\x2b\x9f\x7b\x2e\ -\xa9\xaa\x5b\x8d\x7a\x9a\xee\x7d\x26\xc2\xc3\x72\x08\x1b\xc1\x91\ -\x9b\xa7\xc6\x19\x68\x9f\x41\xab\xd2\xa1\xfb\xae\x88\xf2\x91\x8e\ -\x2a\x52\x6c\x22\x34\xf0\x79\x8b\xb3\x7a\x06\x40\x4d\x6a\x9d\x01\ -\xbb\x8a\x9d\xd5\xe3\x13\xc1\x47\xa3\x22\xfd\x2c\x6a\x8b\xc7\xd9\ -\xe8\xeb\x21\xa2\xe3\x19\x0d\x86\x8a\xa0\xdf\xfd\x5a\xa4\x17\x53\ -\x02\x00\x00\x4d\xf7\x7d\x04\x28\x63\x1f\x48\x58\x59\xf1\x9b\x1b\ -\xae\x09\x51\x3e\x4c\x0b\x00\x58\x7e\x47\xb0\xda\xe3\xf6\xa1\x6b\ -\xad\x61\xa3\xde\x6a\x63\xea\x7d\x98\xc8\x96\x63\x54\x8f\x2d\x58\ -\x16\x00\x12\x72\x71\x4c\x0d\x20\x14\xd0\x63\x44\xd1\x4d\x46\x3d\ -\x4d\xf7\xfd\x14\xe1\xc1\xf4\x4d\x2c\x14\x38\x37\x0d\x46\xdb\x0d\ -\x5a\xf9\x9a\xee\xbd\xc3\x5b\xdf\xf4\x00\x00\x20\xe8\x6f\x79\x0f\ -\xd0\x41\x83\xd6\x51\xde\xda\x6b\x22\x00\x00\x20\x52\xc6\xcc\xd0\ -\x5d\x13\x01\x54\xd4\xb7\x6f\x66\x8c\xfa\x33\x1a\x0c\x2f\x78\x6b\ -\x9b\x1e\x80\xa3\xa1\xd3\x9e\x50\x95\x07\x00\x4a\x52\xeb\x8c\xd1\ -\xa5\xa0\xdf\x5d\xc9\x5b\xdf\xd4\x00\x6a\x6b\xef\xaa\x8c\x45\x7a\ -\x01\x94\xa7\xd6\x09\xb8\x35\xec\x77\x7b\x44\x78\x30\x35\x80\x4f\ -\x85\x93\x57\x01\x1c\x48\x2b\x0f\xac\x2b\x9a\x69\x06\x98\xe1\x92\ -\xb4\xda\x98\xb6\x09\x3a\x75\x5f\x0b\x81\xda\x53\x6b\x04\xbc\xcd\ -\x8d\x85\xab\x44\x3e\x29\x32\x25\x80\xf2\xc6\xeb\x87\x92\xc4\xee\ -\xa5\xe9\x7f\xb5\xb2\xf8\x8e\x21\x7f\xeb\x37\x91\x5e\x84\x07\xe0\ -\x68\x68\xaf\x60\x4c\x19\x04\x90\x97\x52\x9e\x4f\x2a\xc9\xdd\x23\ -\x1d\x67\xde\x89\xf6\x63\xf8\xbc\x8e\x17\x5a\x53\x5b\x29\x48\x79\ -\x08\x5a\x72\xf8\x38\xa0\x1c\x1e\xe9\x70\x0b\x3f\x3c\x20\xf0\x4b\ -\x70\xe7\xc9\xb6\x42\x24\x2d\xfd\x20\x2c\xdd\xfd\x19\xf4\x60\xe7\ -\xe9\xc7\xa2\x7c\xa4\x23\x64\x02\xca\x5c\x5e\x5b\x3c\x8a\xfb\x00\ -\xb6\xa5\xd6\x19\x70\x79\xd8\xef\xee\x12\xe1\x61\x39\xf8\x4f\x80\ -\xc7\xa3\x14\x44\xd1\x4d\x40\xd5\xd2\x06\xdd\x1e\xee\x74\x5d\xe4\ -\xae\x9f\x05\xee\x01\x38\x26\x37\x5e\xc0\xe2\x7f\x83\x29\x3c\x9d\ -\xcd\x61\xf5\xa2\xee\xf5\xff\x82\xeb\x5d\xa0\xcc\xe5\xb5\x15\x44\ -\x31\x0b\x20\xf7\x6f\x91\xd8\x87\x88\xaa\x56\x8e\x76\x34\x0b\xf9\ -\xbd\x9f\x0d\xae\x13\x90\x1f\xb1\x25\x01\xc4\xfe\xbc\x66\xc0\x94\ -\x45\x89\xd7\xac\x95\xc3\x03\x9c\x03\x08\x05\xf4\x18\x03\xea\x00\ -\x4c\x03\x18\x43\x32\xb1\xff\xa5\xff\xec\x17\x9e\x9a\x12\x89\x44\ -\x22\x91\x48\x24\x12\x89\x44\x22\x91\x48\x24\xd9\xf8\x0d\x59\x9b\ -\xda\x0c\x1f\xf1\x22\x4f\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ -\x60\x82\ -\x00\x00\x01\x89\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x3b\x49\x44\x41\x54\x58\x85\xed\ -\x97\x31\x4e\x02\x41\x14\x86\xbf\xb7\x81\xa5\x74\x69\x56\x0a\x43\ -\x34\xd9\x66\x2f\xe0\x09\x4c\xe4\x0e\x9c\x02\x6b\xb5\x90\x1e\x4e\ -\xc1\x19\x8c\x89\x27\xe0\x02\xdb\x6c\xc0\x80\xc5\x86\x06\x2c\x59\ -\xc8\x3e\x0b\x67\x0d\x2c\x62\xa1\xbb\xb1\x70\xfe\x6a\x32\x33\xc9\ -\xf7\x65\xa6\x79\x3f\xfc\xf7\x48\x71\x63\x3a\x9b\x5d\x3b\x2a\x37\ -\x0a\x97\x80\x57\x12\x67\x25\x30\xce\x44\x07\x17\xed\xf6\xd3\x51\ -\x81\x97\xd9\x6b\x1f\xd5\x5b\x60\x0d\x44\x28\x6f\xa5\xe0\x85\x13\ -\x20\x04\x1a\x88\xf4\xcf\xdb\x67\xf7\x07\x02\xd3\xf9\xbc\x23\x19\ -\x8f\xa0\xcf\xdb\x8d\xdb\x0d\x82\xd6\xa2\x14\xb8\x49\x1c\x27\x7e\ -\xad\x9e\x8e\x40\xae\x54\xb4\x93\xbf\x84\x93\x5f\x70\x32\x7a\xc0\ -\xba\x0a\x38\x40\x10\xb4\x16\xdb\x8d\xdb\x05\x52\x47\xa5\xf7\xc9\ -\xcd\x17\xe6\xcf\xa3\x2a\xe0\xbb\x12\x08\x91\x61\xed\x0b\x00\x5e\ -\x69\x7f\xfe\x5d\x32\x56\x40\xf3\x2b\x81\x3f\x89\x15\xb0\x02\x56\ -\xc0\x0a\x58\x01\x2b\x60\x05\xac\xc0\xae\xc0\xca\x4c\xaf\x55\x13\ -\x3d\x60\x79\x20\x20\x30\x06\xc2\x38\x4e\xfc\xaa\xd8\x71\x9c\xf8\ -\x28\xa1\x61\xed\x0b\x64\xa2\x03\xa0\x51\xab\xa7\xa3\x2a\x24\x26\ -\x93\xc9\xe9\xc7\x58\x8e\x9b\x89\x0e\xf3\xfd\x62\x31\x79\x40\xf5\ -\x0e\x48\x11\x22\x33\x40\xfe\x3e\x0e\x1e\x4a\x08\xb8\x47\x8b\x49\ -\x1e\x53\xcd\x7a\x66\x74\x6e\x16\xcf\x7f\x98\xa5\xa9\x66\xc3\x62\ -\x35\xb3\x79\x07\x25\xbf\x6e\x2c\x3a\x0b\x42\xe7\x00\x00\x00\x00\ -\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xd3\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x85\x49\x44\x41\x54\x78\x9c\xed\ -\xd7\xb1\x0d\xc2\x40\x10\x04\xc0\x7d\xe8\x01\x51\x0a\x75\x20\x3a\ -\x20\x72\x45\xee\x82\x90\x1e\xe8\xc4\xa2\x07\x78\x52\xf4\x26\xb5\ -\x1e\xd9\x33\xe1\xea\x82\xbd\xcb\x2e\x01\x00\x00\x00\x00\x60\x3b\ -\x4a\x1b\x9c\x6e\xf5\x5c\x53\xc7\x24\x87\x0e\x7d\x96\x34\xe5\x5d\ -\xae\x8f\x4b\xb9\x7f\x87\xbb\x76\x6a\xa5\xcb\x27\xc9\xb1\xec\xeb\ -\xd8\x86\xb3\x03\x6c\xcd\xec\x00\x25\x65\x48\xf2\xec\xd0\x65\x69\ -\x53\x7d\x95\xa1\x77\x09\x00\xe0\x7f\xf8\x05\xda\xa9\x95\x2e\x9f\ -\xf8\x05\x7e\xf3\x0b\x00\x00\x00\x00\x00\x00\xb0\x11\x1f\x5d\xbc\ -\x24\x0f\x6c\x9f\x83\x41\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ -\x60\x82\ -\x00\x00\x01\x8c\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x3e\x49\x44\x41\x54\x58\x85\xed\ -\xd2\xbf\x2b\x85\x51\x00\xc6\xf1\xef\xf3\xca\x62\x90\x52\xac\xfc\ -\x05\x14\xbd\xf7\x96\xcd\x24\x3f\x8a\x9b\x98\x58\x29\x7f\x80\xcd\ -\x24\x93\xc9\x2c\x52\x06\x03\x2f\x29\x25\x8b\x22\xf1\x8a\xa2\xcc\ -\x16\x65\xb1\xd0\x1d\xa4\xee\xbd\x8f\x81\x01\xc5\xeb\xde\x4d\xce\ -\x67\x3c\x3d\x3d\x3d\xa7\x73\x20\x08\x82\x20\xf8\xef\x94\x15\xc8\ -\x6f\x95\x97\x2d\x75\x95\xd1\xc4\x45\x41\x37\xbf\x29\xcd\x6f\xbb\ -\xcd\xf6\x3a\xe2\x29\x1d\xd6\x20\x92\xbf\xcb\x46\x59\x65\x46\x4d\ -\x40\x67\x1d\x3e\x89\x13\xf7\x66\xe5\x73\xdb\xee\xb2\x7d\x06\xf4\ -\x50\xa1\x39\x2b\x9f\x39\x20\x2a\x6b\x02\xd8\x04\x1a\x85\xf7\xe3\ -\xc4\x93\xdf\x65\xe3\x2d\x0f\x60\x1f\x01\xad\xc0\xe1\x4b\xa4\xbe\ -\x9f\x6e\xff\xab\x01\xa7\x63\x7a\x4e\xaf\x35\x0e\x5e\x04\xea\x85\ -\xd7\x72\x89\xe7\xb0\x3f\x3d\x5f\x9c\x78\x5a\xf2\x2e\xd0\x00\x5e\ -\x2f\x96\xd4\x77\x35\xa2\xc7\xac\xfe\xcc\x3f\xf0\x51\x2e\xf1\x0c\ -\x78\xe9\x6d\xb8\x57\x4b\x0f\xd1\xd4\xe5\x3d\xe5\xb8\xa3\xb2\x20\ -\x34\x0b\x80\x3d\x9f\x16\xa2\xb9\xac\x9b\xd7\x34\x00\x20\xbf\xe3\ -\x21\x57\xbc\x01\x34\x00\xc7\x88\x22\xa6\x1f\x28\x81\xa6\xd2\x82\ -\x56\xaa\xe9\xab\x7a\x00\x40\xbc\xe9\x6e\x45\xde\x03\x5a\xde\x8f\ -\x8a\x48\xa3\xe9\x88\x0e\xaa\xed\xaa\x69\x00\x40\xbc\xeb\x76\x95\ -\x7c\x0b\xdc\x19\x0d\x9d\x17\x74\x5d\x6b\x57\xed\x6c\x7d\xfd\x8c\ -\x41\x10\x04\xc1\x9f\xf3\x0a\x0d\x2b\x72\x05\x90\xf4\xef\x82\x00\ -\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x21\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xd3\x49\x44\x41\x54\x58\x85\xed\ -\x97\xb1\x6b\x53\x51\x14\xc6\x7f\x5f\x5e\xe9\x22\x15\xb4\xc4\xfe\ -\x01\x1d\x4a\x47\x5d\x2c\x28\x2e\x79\xea\x10\x09\x54\x5e\xd7\x22\ -\xe4\xe9\x20\x98\xa9\x54\xff\x04\x33\x38\x18\xc1\xc5\x64\xd0\x0e\ -\x45\x94\x08\x85\x0c\x1a\xe2\x20\xa8\x75\xd1\x4d\xb7\xee\x6d\x51\ -\x90\xe0\x52\xc8\x3d\x0e\xbe\x17\x9f\x52\x5e\x89\x7d\x69\x45\xf3\ -\x4d\xf7\x9d\x7b\x38\xdf\xef\xde\x73\x79\xdc\x0b\xff\xbb\xf4\x7b\ -\xe0\xfc\xe5\xf2\x19\xa4\x9b\xc0\x1c\x90\xcf\xc8\x67\x1b\x58\xc7\ -\xac\xda\x6e\x36\x5e\x27\x27\xbc\xe4\x87\x1f\x94\x97\x84\x56\x81\ -\x19\xe0\x48\x46\xe6\x44\xb5\x66\x90\xae\x4c\xcf\x9e\xfa\xb6\xf1\ -\xe9\xfd\xdb\x78\xa2\xbf\x03\xfe\xc2\xb5\xb3\x72\xee\x15\xf0\x15\ -\xb3\x4a\xce\xa3\xf5\xfc\x49\xe3\x4b\x16\xee\x17\x17\xca\xc7\x5d\ -\x8f\x22\x52\x0d\x38\x8a\xd9\xb9\x78\x27\xc6\xfa\x24\xce\x2d\x03\ -\xc2\xac\xd2\x6e\x36\x56\xb2\x30\x8e\x15\x2d\x64\xc5\x0f\x42\xc9\ -\x78\x18\xb5\xb8\x04\x90\x4b\xe4\xcd\x01\xe4\x3c\x5a\x59\x9a\x27\ -\x65\xbd\x9d\xb8\xf6\xe9\x38\x96\x04\xc8\x27\x68\x87\xa2\xce\xb3\ -\x47\x9f\xa3\xe1\x89\xdd\x00\x0e\x45\x23\x80\x11\xc0\xa1\x03\x8c\ -\xed\x95\x70\x21\xb8\x7a\xdd\x99\xdd\x16\x4c\x0c\x52\xd8\xa0\x9b\ -\x93\x6e\xbd\x78\xfa\xe0\x7e\x5a\x5e\xea\x0e\x14\x4a\xe1\x94\x99\ -\xdd\x1b\xd4\x1c\x40\x30\x61\x66\xb5\x42\x29\x9c\xfa\x63\x80\x83\ -\x50\x2a\x40\x67\xad\xbe\x29\xe9\x86\x41\x77\xd0\xc2\x06\x5d\x49\ -\x95\xce\x5a\x7d\x33\x2d\x6f\xcf\x33\x10\xf5\x30\xb5\x8f\xfb\xd1\ -\xdf\xdd\x82\x11\xc0\x08\xe0\xa0\x01\xb6\xe1\xc7\x05\x72\x58\x66\ -\x85\xf9\xc5\xc9\x68\xb8\xb5\x1b\xc0\x3a\x80\xeb\x51\x1c\x16\x80\ -\xbc\xf1\xb8\xf6\xbb\x38\xf6\xf3\x47\x64\x56\x45\xba\x84\x54\xf3\ -\x83\x50\xd6\xdb\x69\x25\xee\x70\xfb\x52\x61\x7e\x71\x52\xde\x78\ -\x51\xc6\x5d\xc0\x61\x56\xed\x43\x25\x13\xfd\xa0\xbc\x24\x53\x95\ -\xe1\x9d\x0d\x87\xb1\xdc\x6e\xd6\xef\xc4\x81\x5f\x5e\x46\x1b\x1f\ -\x3f\xbc\x99\x9e\x3d\xd9\x41\xca\x03\xc7\xc8\xee\x75\xb4\x05\xbc\ -\xc4\x2c\x6c\x37\x1b\x8f\x33\xaa\xf9\x8f\xe8\x3b\xaa\x2b\x8c\x73\ -\x1f\xb4\x18\x18\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\ -\x00\x00\x01\xaa\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x5c\x49\x44\x41\x54\x58\x85\xed\ -\x94\x3f\x4b\x42\x51\x18\x87\x9f\x57\xad\x4d\xac\x21\x8a\x5a\x0c\ -\xb7\x6c\x72\x74\x70\x09\x6d\x68\x08\xba\xda\x16\x05\x1a\x41\xdf\ -\xa0\x49\xce\xd0\xd2\x27\xa8\x54\x70\x0a\x32\x8d\x86\x5a\x14\xa4\ -\xbe\x80\xd0\xe4\x94\xd4\x14\xd1\x90\x53\x43\xea\x3d\x4d\x5a\x8d\ -\xf7\x5c\xb8\x4b\xf7\xd9\x5e\x38\xe7\xf7\x3e\xbc\xe7\x0f\xf8\xf8\ -\xf8\xfc\x77\xc4\xe9\xfa\xb4\x55\xb0\x01\x06\xa3\xe1\xec\xfd\x4d\ -\xb5\xef\x56\x20\xe0\x64\x71\xb1\x58\x9c\x08\x4f\x05\x43\x1f\xb9\ -\x5c\x2e\xe8\xa9\x80\x52\xca\x46\xf4\xf6\xb8\xee\xdb\x91\xa1\xa7\ -\x02\x00\xad\x7a\xe5\x4a\xe0\x78\x5c\x67\xac\xc2\xa3\x1b\x01\xa3\ -\x11\x3e\x75\x3b\xed\x58\x3c\x91\x02\x96\x81\xf9\xd8\x4a\x62\xa1\ -\xd7\xed\xdc\x99\x64\x39\xbd\x84\x7f\x48\x5b\x05\x3d\x09\xd2\x1c\ -\x34\xaf\xcb\xe7\x4e\x33\x1c\x1f\xc1\x6f\x92\xab\x4b\x93\x09\x6a\ -\xe1\x2c\xb3\x95\x4f\x79\x2a\xa0\x94\xb2\x07\x81\xe9\xf0\x8f\x84\ -\x3c\x78\x2a\x00\x30\xc7\xfb\x17\xe8\x67\xd3\xfd\x6e\x05\xa4\x6f\ -\xcf\x94\x41\xa2\x08\x6f\x23\xad\xa3\x9e\x0a\x64\xb2\x85\x22\xe8\ -\x1d\xe0\x53\x84\x8d\xf6\x75\xe5\xc5\x69\x86\xf1\x2b\xc8\x58\xf9\ -\x5d\x8d\x54\x01\x5b\x44\x36\x9b\xf5\xd2\xad\x49\x8e\xd1\x3f\x90\ -\xce\xe6\xd7\x40\x6a\x40\x00\xe4\xb0\xd5\x28\x5d\x98\xe4\x80\xc1\ -\x11\xac\x5b\xfb\x71\xb4\x34\x80\x10\x22\x27\xad\x46\xe9\xd4\xb4\ -\xb9\x89\x80\xd8\x50\x03\x22\x1a\x2e\x93\xf1\xc5\x23\x37\xcd\x01\ -\x42\xce\xb7\xe8\x57\x0d\xbd\x61\x78\xb8\xa7\x94\xb2\xdd\x0a\xf8\ -\xf8\xf8\xf8\x7c\x03\xa5\xd7\x5e\xc1\x97\x2b\x14\xb6\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x31\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xe3\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\xb1\x11\x82\x40\x18\x05\xe1\xf7\x5b\x04\xb5\x58\x07\x2d\x18\ -\x59\x91\x5d\x50\x87\x75\x10\x59\x05\x18\xa0\x99\x46\x77\xb0\xce\ -\xb8\x5f\x74\xc1\x0d\xbc\xdb\x44\xd2\x3f\xab\xbd\x7f\x70\x9e\xd6\ -\x71\xcd\x7a\xdb\x7e\x56\xd7\xfb\x58\x53\xcf\xfb\xad\x4e\x7b\x7e\ -\x3c\x49\x5e\x8f\x19\x92\x0c\xef\x87\xf5\xbc\xdf\x6a\xf7\x00\xd9\ -\x1e\xf3\xe9\xdc\xeb\x7e\x93\x23\x02\xfc\x34\x03\xd0\x03\x68\x06\ -\xa0\x07\xd0\x0c\x40\x0f\xa0\x19\x80\x1e\x40\x33\x00\x3d\x80\x66\ -\x00\x7a\x00\xcd\x00\xf4\x00\x9a\x01\xe8\x01\x34\x03\xd0\x03\x68\ -\x06\xa0\x07\xd0\x0c\x40\x0f\xa0\x19\x80\x1e\x40\x33\x00\x3d\x80\ -\x66\x00\x7a\x00\xcd\x00\xf4\x00\x9a\x01\xe8\x01\x34\x03\xd0\x03\ -\x68\x06\xa0\x07\xd0\x0c\x40\x0f\xa0\x19\x80\x1e\x40\x33\x00\x3d\ -\x80\x66\x00\x7a\x00\xcd\x00\xf4\x00\x9a\x01\xe8\x01\x34\x03\xd0\ -\x03\x68\x47\x04\x78\x7c\x39\xf7\xba\xdf\x64\xff\x00\x4b\x5d\xaa\ -\x32\x57\x65\xce\x52\x97\xee\xf7\x25\xa9\xc1\x13\x85\x02\x26\x2c\ -\x67\x7d\xc5\x41\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\ -\x00\x00\x02\xda\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\x8c\x49\x44\x41\x54\x78\x9c\xed\ -\x9a\x3b\x6f\x13\x41\x14\x46\xcf\xb5\x13\x42\x13\xba\xfc\x92\x48\ -\xb6\x25\x1a\x5a\xba\x3c\x44\xe4\x90\x80\x44\x05\x05\x2d\x1d\x2d\ -\xff\x00\x24\x5c\x21\x1e\x79\x08\x84\x57\x34\xd4\x74\x80\x5b\x7e\ -\x07\x12\x12\x0d\x42\x72\x3e\x0a\x84\x64\x36\xeb\x38\xde\x9d\x99\ -\x9d\x59\xfb\x96\xb3\x77\x3f\xcd\x39\xda\x5d\x5b\x57\x03\xcb\x5a\ -\xd6\xb2\x16\xb9\xac\xee\x0d\xf8\xae\x4e\xa6\x2d\x93\x9e\x48\xfc\ -\x68\xb7\xed\xc1\xe7\x2d\xfb\x36\x79\x7d\xa5\xae\x8d\x85\xa8\xee\ -\x50\x7d\xa4\x23\xa0\x65\x06\xe3\xb1\x9e\x03\xd7\x27\x7b\x5a\xf5\ -\x6c\xcd\x7f\x75\x87\xea\xc3\x5f\xf8\x7f\x6b\x2d\xe3\x5a\xbe\xaf\ -\x91\x02\x8a\xe0\x81\xb1\xb0\xc7\xf9\xde\xc6\xbd\x02\x17\xc0\xef\ -\x8f\x76\xec\x43\xbe\xbf\x51\x1f\xc1\x19\xf0\xef\x8a\xee\x69\x8c\ -\x80\x32\xf0\xd0\x10\x01\x65\xe1\xa1\x01\x02\xaa\xc0\x43\xe2\x02\ -\xaa\xc2\x43\xc2\x02\x5c\xc0\x43\xa2\x02\x5c\xc1\x43\x82\x02\x5c\ -\xc2\x43\x62\x02\x5c\xc3\x43\x42\x02\x7c\xc0\x43\x22\x02\x7c\xc1\ -\x43\x02\x02\x7c\xc2\x43\xe4\x02\x7c\xc3\x43\xc4\x02\x42\xc0\x43\ -\xa4\x02\x42\xc1\x43\x84\x02\x5c\xc3\x77\x86\xba\x05\x7a\x06\x80\ -\xec\xfe\x68\xd7\xb2\xc9\xeb\x51\x4d\x84\x5c\xc3\x77\x87\xea\x1b\ -\x3a\x35\xd8\x30\xd8\xc0\x34\xc8\xf7\x44\x23\xc0\x07\x7c\x41\xde\ -\xb9\x8a\x42\x40\x20\xf8\xb3\x96\xd9\xc3\x7c\x6f\xed\x02\x42\xc1\ -\x1b\x76\xf7\xcb\xb6\xbd\xcd\xf7\xd7\xfa\x11\x0c\x0a\xbf\x63\x47\ -\x45\xf7\xd4\x26\x20\x06\x78\xa8\x49\x40\x2c\xf0\x50\x83\x80\x98\ -\xe0\x21\xb0\x80\xd8\xe0\x21\xa0\x80\x18\xe1\x21\x90\x80\x50\xf0\ -\x92\xdd\x19\xed\xda\xf1\x3c\x59\xde\x05\xc4\x0c\x0f\x9e\x05\xc4\ -\x0e\x0f\x1e\x05\xa4\x00\x0f\x9e\x04\xa4\x02\x0f\x1e\x04\xa4\x04\ -\x0f\x8e\x05\xa4\x06\x0f\x0e\x05\xa4\x08\x0f\x8e\x04\xa4\x0a\x0f\ -\x0e\x04\x04\x83\x37\x3b\x1c\x6d\xdb\xc9\xbc\x79\xbd\x4c\x7b\x67\ -\xd2\x53\xc0\xfd\x4c\x30\x76\xf8\x6e\xa6\x43\x49\x27\x5e\x66\x82\ -\x29\xc0\x23\xbd\x64\x06\x63\x29\x01\xb1\xc3\xf7\x86\x3a\x28\x80\ -\x77\x33\x13\x4c\x01\x5e\xe8\x55\x3e\xcf\xc9\x4c\x30\x69\xf8\xaa\ -\x33\xc1\xd8\xe1\x3b\xef\x75\xdb\x4c\xaf\xcf\xe5\xcd\xf8\xe9\xbc\ -\x94\x80\xa6\xc2\xc3\x25\xce\x0a\x87\x82\x07\x3b\x18\x6d\xdb\xe9\ -\xbc\x79\x55\xe0\x61\xc6\x13\x10\x12\xfe\xeb\x4e\x78\x78\xb8\x40\ -\x40\xf4\xf0\x99\xf6\x4d\x7a\x93\xcf\x9b\xf7\x35\x2a\x14\xb0\x28\ -\xf0\x00\xed\xfc\x42\x2f\xd3\x1e\xe8\x18\x47\xf0\x53\xf2\x4a\xc3\ -\xf7\x32\xed\xa1\xf3\x79\x65\x3f\xa0\xff\x3d\x01\x9b\x03\xad\xae\ -\x6c\xe8\x3b\xb0\x3e\xb1\x5c\x1a\x7e\x4a\x5e\x69\x78\xd7\x79\x90\ -\xfb\x27\xb8\x7e\x85\x36\xb0\x36\xb1\x54\xe9\x58\x4a\x41\x5e\xa5\ -\xcd\xba\xce\x83\x9c\x80\x4f\xf7\xec\x97\x61\x8f\x80\xdf\xc0\x4f\ -\x64\xfd\x2a\x67\x72\xf2\x79\x66\xb6\x5f\x65\xb3\xae\xf3\xa6\xd6\ -\xcd\x8f\x5a\xdb\x1c\x68\x35\xd6\xbc\x1b\x2f\x74\xd5\x65\xde\xb2\ -\x96\xb5\xc0\xf5\x07\xd6\x41\x4c\x2b\x6c\xde\x0f\x7f\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\xe8\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x9a\x49\x44\x41\x54\x58\x85\xc5\ -\x97\xd9\x76\xe2\x46\x10\x86\xbf\x66\x11\x12\x60\x50\x9c\xc4\x9e\ -\xf1\x24\x39\x59\xde\xff\x9d\x72\x31\x9e\x49\x1c\xcf\x18\x6c\x23\ -\x19\x24\xa8\x5c\xd4\xdf\xa8\x91\x71\x72\x97\xd4\x39\x1c\x89\x56\ -\xd7\xf6\xd7\xd6\x0d\x58\x09\x16\xf8\xcf\xc9\x02\x58\x19\xa4\x7c\ -\x09\xac\x21\x58\xf7\x91\x4b\x20\x1a\x96\x25\xef\x93\x44\x4a\x5c\ -\xb3\x64\x6d\x9b\xac\xed\xf4\x7e\x00\x1e\x7a\xf2\x97\xc0\x3a\xf4\ -\x16\x0e\xc0\x05\x30\x00\xaa\x44\x59\x90\x11\x13\xd8\x0d\x21\x8c\ -\x81\x71\xcf\xa5\x16\xac\x81\xac\x95\x11\x51\xb9\x01\x0d\x90\x4b\ -\xfe\x23\x30\x3c\x75\xd8\xf7\x2d\xc0\x7e\x11\x34\x63\xb0\x99\xd6\ -\x33\xb0\xf7\xf0\x50\x82\xe5\x60\x13\xb0\x82\x57\x64\x85\xbe\x4d\ -\xb5\xf7\xca\x79\xc1\xd7\x2c\x93\xec\x5f\xc1\x2e\xfa\x10\x02\xf6\ -\x01\xf8\x24\x24\x0c\x78\x01\x0a\xd8\xbd\x87\xec\xa3\xbc\x00\x58\ -\xc8\x8b\x73\x94\x7e\x9b\xc0\xee\x06\xb2\x5b\x21\x92\x4b\xdf\x1a\ -\xb8\x81\x70\x0b\x30\x92\xf2\x80\xc3\x3e\x96\xf2\x1b\xe0\xde\x19\ -\xb2\xfb\x44\xf9\x04\x0f\x91\x71\x1a\xf7\xe8\xcc\x4c\xca\xf4\xcb\ -\xbe\xc2\xa6\x80\xd9\x18\x78\x07\x7c\x94\x8e\x41\x0f\x01\xfb\x4e\ -\xff\x2b\x08\x15\xd8\xb5\xbe\xfd\x09\xcc\x1d\x8d\xd5\x0c\x4a\x5c\ -\x70\xa8\xcf\x03\x60\x73\xa0\xc5\xf3\xa5\xd2\xf3\x80\x27\xf4\x0e\ -\x78\xc2\xe3\xff\x0d\xb0\x82\xb0\x19\x25\xdc\x63\x29\xcf\xe5\xdd\ -\x1a\xb8\x92\xc5\x39\x94\x4f\x82\x71\x02\x66\x1d\x0f\x24\x08\xe5\ -\xc0\xb3\x94\x95\x42\x38\x03\xee\xf0\xf0\x64\x10\x9e\x12\x07\x3b\ -\x28\xdc\x52\x9b\xc0\xcb\xb5\x18\x83\xa0\x5c\x48\x68\xa4\x39\x1e\ -\x86\xb9\xf8\x07\xfa\x1f\xd7\x22\x6d\xc4\xbb\x93\xac\x00\xdb\xf7\ -\x4a\xcc\x63\xee\xc5\x10\xbc\x73\x41\x15\x30\xfd\x8c\xc7\xb2\x96\ -\xf5\x23\xc1\x56\x43\x75\x09\xd3\xb5\x23\x75\x8e\x6c\x21\x99\x35\ -\x30\x95\x03\x53\xba\xd2\x1b\x49\xf6\x1c\x0f\xc1\x97\x14\x81\x09\ -\xb4\x2f\x49\x6d\x16\x8a\xb5\xe1\x96\x5d\xc3\x74\xe5\x48\xbd\x49\ -\xb1\xce\xbf\x17\x8f\x09\x89\x58\xb6\x2d\x3c\x36\x78\xe8\xfa\x21\ -\x68\x4a\x58\x3c\x74\xc6\x30\x54\x3e\xe4\x78\xd2\xfc\x25\xc1\x85\ -\xfa\x41\xee\x49\x67\xb3\xee\x3f\x05\x9e\x37\x5f\x61\x73\x29\xde\ -\x3c\x91\x09\x2c\x9e\x49\x42\x15\x0d\xc8\xbc\x8b\x91\x0b\xc6\x52\ -\x1e\xb4\x62\x5c\xe1\x89\xf6\x20\x48\x73\x3d\x83\xa0\x9d\xba\x0c\ -\xa6\xae\x9c\x06\x66\x0f\xda\xd7\xe2\x3d\xe5\x12\xef\x31\x43\x68\ -\x4c\xfb\x63\x1f\x20\x40\x50\xd7\x0a\x8f\xde\xb9\x82\x32\xdb\x0c\ -\x82\xfa\xbb\x35\x12\x36\x06\xee\x7b\xbd\xfd\xca\x8d\x8e\x7c\xb4\ -\x60\x7b\x7f\x86\x1d\xd8\x33\x5e\x86\x03\xba\x24\x3f\xa9\x82\x61\ -\x52\xdf\x49\x93\xa9\xd3\x3d\xda\xc7\xbd\x7b\x63\xe9\x30\xbb\x4b\ -\x1c\x8a\x94\x4e\x59\xc9\x0c\x55\xe7\x6c\xc7\x30\x82\xf1\x21\xf1\ -\x86\xe4\xbd\x4d\x84\x8c\x80\xc6\x3d\xb7\x35\xea\x4c\x78\x46\x5b\ -\xd2\x1f\x52\x4a\x1d\x78\x35\x3d\x07\xc9\x73\x7f\x86\xb9\x4f\x87\ -\x9e\xc0\x3e\x9d\x6b\xcf\x96\xbc\xbf\xda\x17\x85\xed\xa0\x51\x57\ -\x0b\xd6\x6d\x0e\x06\xf5\xb0\x67\xc0\x30\x81\x7d\xa5\xdf\x32\x99\ -\x27\x7d\x83\x4f\x46\x6e\xdf\x98\x94\xa1\x55\x29\xf5\xac\x2d\xfa\ -\x75\xdf\xe2\x09\xa7\x79\x1e\x62\xdb\xbe\xa6\x3b\x03\x44\x0a\xaf\ -\xdf\xad\x00\x3b\xee\x8b\x39\x60\xca\x70\x53\x19\xce\x34\x58\xc0\ -\x4b\xb3\x94\xe2\x02\x6f\xb9\x6a\x36\x96\x42\xdc\x00\xdf\x4a\xb8\ -\x49\xb6\x0e\x21\x16\x3b\x20\x32\x76\x1f\xf9\xa2\x01\x3b\x08\x43\ -\x95\xdb\xd6\x0f\x24\x34\xfe\xdf\xc0\x33\x7f\x23\x21\x9f\xff\x61\ -\x1a\xee\x38\x9e\x76\xd6\x25\x2c\xef\x3a\x07\x79\xc0\x4b\x38\xee\ -\xd9\xc1\x49\x08\xc6\x75\xe2\xf5\x16\x35\x0a\x51\x05\x2f\x3f\xc9\ -\xf3\x73\x99\x7e\xb4\x40\x1e\x7e\x80\xe5\x53\xb7\xbc\x2a\xa4\x1c\ -\x37\x6c\xbc\x89\x5f\x06\x09\xe3\x06\xea\xb2\x63\xa2\xf6\x86\x14\ -\x0f\x1a\xf9\x2d\x3e\xdd\xfa\x67\xc1\x94\x22\xd4\x7f\xe0\xed\x36\ -\xf8\xb3\x4c\x86\x57\x36\x93\x31\x27\x21\xd8\xfb\xe6\xe2\x19\xec\ -\x86\x6e\xe0\x14\xf8\x49\xe6\x77\x3c\x9e\x7b\xa0\x74\xa4\xea\x41\ -\x97\xa0\xf5\x50\x02\xd5\x21\x8f\x7b\x7f\xc6\xbb\x9f\x8e\x77\x2c\ -\xa1\xb8\x95\xcc\x6d\x6a\x00\x6e\x40\x78\x06\x1b\xd0\xc5\x7c\x24\ -\x6f\x0e\x10\x36\x60\x2d\xf0\x0c\xe1\xe5\x3c\x00\x36\x77\x19\xa0\ -\x83\xeb\x67\x7c\x96\x6c\x24\x73\xe5\xf9\xd3\x45\x31\x0d\x41\xe3\ -\x93\x2d\x3c\x42\x7d\xe1\x9e\xb2\x96\xf5\x5b\xe5\xc7\x71\x8c\xbe\ -\x4d\x36\x56\xe8\x1a\x3c\xd1\xd6\xc0\x25\x54\x33\x47\xc3\x66\x5a\ -\x3f\x09\xc1\x57\xe0\x07\xdf\x6c\x4b\x60\x06\x2f\x41\x93\x74\x42\ -\x67\xb2\x0e\x97\x55\x05\x85\xd1\x75\xcf\xd8\xac\x0a\x3c\xdb\x77\ -\x38\xf3\xc2\x8d\xaf\xa7\x30\x9d\xe3\x13\x76\xe3\x8e\x87\x4d\x62\ -\x40\x30\xb0\x03\x5e\xeb\x01\xf8\x04\x45\x34\x86\x0e\x56\xf0\x30\ -\x4c\x75\xf4\x36\x21\x18\xe2\x1c\x59\x38\x82\xc7\xbd\x17\x6e\xcc\ -\xf4\x8b\x64\xc5\xd9\x72\xee\x50\x63\x17\xba\x34\xf4\x2f\x26\x0b\ -\xa8\x7e\xec\x2e\x23\xff\x76\x31\x01\xe7\xad\x3e\x74\x65\x7d\x72\ -\x31\xf9\xed\xcc\xc5\xe4\xd8\xdb\xf7\x82\x6d\x20\x2b\x33\x1c\xfe\ -\x81\x7f\x6f\x32\x79\x30\x84\x71\x7a\xf7\xcb\x75\x30\x6e\x7d\xd4\ -\x8e\x6a\xbc\x67\xec\xc5\xdb\xd0\x0d\xa6\x35\xc9\xd5\xec\x8d\xcb\ -\x69\xf4\xe2\x98\x70\xc3\xe4\x7d\xa2\xf7\x09\x6c\x35\x3b\x26\x95\ -\x94\x18\xdd\xe5\x54\x06\xb9\xb0\x18\xf3\x9e\xc3\x6b\xf8\x9f\xaf\ -\xe7\x7f\x03\x88\x7c\xd3\x3b\xed\x32\x4f\xdf\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xee\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xa0\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\x41\x0d\x00\x20\x00\x03\x31\x82\x7f\x91\x10\x84\x80\x8c\xf2\ -\xb8\x1a\xd8\x65\x63\x40\x6b\x9f\xbb\xf6\xb9\xb2\x61\xca\xf1\x1f\ -\x74\x80\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\ -\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\ -\x80\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\ -\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\ -\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\ -\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\ -\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\ -\xad\x03\x74\x80\xd6\x01\x3a\x40\x7b\xd6\x8f\x07\xc5\x02\xeb\xa3\ -\x1e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x0a\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xbc\x49\x44\x41\x54\x58\x85\xed\ -\x94\x3d\x6b\x14\x61\x14\x85\x9f\xf3\x6e\x84\x85\x80\x68\x23\x83\ -\x9b\x9d\x37\x0b\xfe\x00\x7f\x81\x9d\x28\x12\xb4\xd1\x52\x48\x2b\ -\x41\xf2\x1f\xf4\x0f\x88\x16\x96\x36\x16\x8a\x58\x69\xa1\x58\x5a\ -\x68\xa9\xbd\x98\xcc\xec\x46\xd6\x4a\x63\x12\x30\xc8\xce\xb1\xd8\ -\x0f\x96\x7c\xed\xce\xfa\x91\x66\x1e\x18\xb8\x33\x5c\xce\x39\xdc\ -\x79\xef\x0b\x15\x15\x15\x15\xc7\x8c\x86\xc5\x7a\x96\x7f\x03\x9d\ -\xfa\x3f\xb6\xfe\xbe\x18\xd3\xd3\x00\x61\xf4\x69\xac\xfe\xe7\xf6\ -\x63\x5e\xa3\x62\x2e\xa8\x85\x78\xdf\xef\x30\x98\x02\xe8\xfd\x95\ -\xc7\x14\xd8\x43\xab\x77\x73\x41\xad\xe1\xcb\xe8\x17\x00\x74\xbb\ -\xdd\xf9\xdd\xdd\x5f\xcf\x0d\x97\x06\x49\x0b\x81\xf9\x03\x0c\x12\ -\x0e\x20\x30\xaf\xea\xf5\x13\xd7\x93\x24\xd9\xd9\x37\x01\x80\x24\ -\x49\x76\xb6\xb6\x36\xaf\x0a\x3d\x1d\xa4\x0b\x7b\x43\x96\xb4\x57\ -\x5f\x43\x60\x3d\xd9\xde\xde\xbc\x36\x6e\xce\x61\xe2\xb6\x6b\x59\ -\xb6\xf1\x00\xf9\x96\x6d\x24\x15\x94\x9c\x84\x40\x85\x1d\x24\x81\ -\xf5\x30\xc6\xc6\x6d\x49\xbd\xbd\x7d\x07\x1e\x3c\x49\xbd\x18\x1b\ -\x2b\x48\x77\x25\x01\x04\x95\x98\x84\x40\x86\x20\x09\xc3\x9d\x18\ -\x1b\x2b\x07\x99\x0f\x7a\x8f\x26\xcb\xda\xab\x86\x7b\x00\x06\x0b\ -\x8a\xa3\xfa\x3d\x16\x56\xb0\x1a\x63\xf3\xfe\x84\xb0\x93\xc9\xb2\ -\xce\x4d\xe3\x47\x40\xad\xef\x71\x48\x08\x13\x10\x02\x7a\x82\xe5\ -\x18\x9b\x8f\x27\x69\x4f\x3d\xd6\x2c\xeb\x2c\x19\x3f\x03\xea\x18\ -\xa3\x7d\x21\x86\x07\xf6\xa7\xd0\x8d\x18\x17\x5e\x4e\xa3\x5b\xea\ -\x84\x7f\xce\xf3\x0b\xc1\x7a\x01\x9c\x44\x78\x70\x57\x80\x08\x18\ -\x01\x3f\x82\xbc\x94\xa6\xe9\xdb\x69\x35\x4b\xaf\xd8\xda\x5a\xe7\ -\xbc\x82\x5f\x03\x67\x40\x76\x7f\xd5\x00\x7d\x75\xc1\xe5\x56\x6b\ -\xe1\x43\x19\xbd\x99\x76\xbc\xdd\x6e\x9f\xeb\x15\x7a\x03\x5e\x1c\ -\xc8\xac\xd7\x82\x2f\x36\x9b\xcd\x4f\x65\xb5\x66\xbe\x64\xf2\x3c\ -\x3f\x5b\x58\x1b\x88\x8f\x01\x5f\x49\xd3\xf4\xcb\xac\x5a\x15\x15\ -\x15\x15\xc7\xca\x6f\xbc\xd7\xa4\x72\xc7\xdc\xd0\xf5\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x78\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x2a\x49\x44\x41\x54\x58\x85\xed\ -\xce\x41\x01\x00\x20\x0c\xc4\xb0\x0d\x4d\x78\x9a\x1f\x0c\x83\x8c\ -\xe3\x91\x18\x68\xab\x00\x80\xb0\xde\x73\x6e\x72\x60\x25\xe3\x00\ -\xc0\x17\x1e\xbe\x17\x02\x30\xed\xb9\x5b\x96\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x20\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xd2\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\xb1\x0d\xc2\x40\x14\x44\xc1\x35\x45\x38\x43\x72\x4d\xb4\xe0\ -\x88\x8a\xe8\x82\x9a\x2c\x93\xd0\x85\x09\x40\x44\x90\x7a\x90\xd8\ -\x89\x2e\xbb\xfd\x2f\xa9\xaa\x7f\x36\xa8\x8f\x97\xe5\x76\xca\x90\ -\x4b\x92\x64\xcb\x79\x9a\x8e\x57\xb1\xe3\x20\x3e\x4d\x92\xd7\xf1\ -\x63\x92\xf1\x1d\x02\x70\x01\x9e\xc7\x7f\x7a\xef\x4a\x06\xf8\x09\ -\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\ -\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\ -\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\ -\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\ -\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\ -\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\ -\x0d\xa0\x07\x68\x32\xc0\xfd\xcb\x7b\x57\x2e\xc0\x96\x39\x43\xd6\ -\x0c\x59\xb3\x65\x66\x3b\xaa\xea\xaf\x3d\x00\x08\x2d\x0e\x52\x29\ -\x6c\xf3\x60\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\x03\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\xb5\x49\x44\x41\x54\x58\x85\xe5\ -\x97\x5d\x68\x9b\x55\x18\xc7\x7f\xcf\x79\xfb\x81\x53\xe7\x6c\x07\ -\x8b\xd8\xb2\x59\xaa\x62\x41\x91\x35\xcd\xf4\xc2\xaf\x39\x36\x44\ -\xb6\x4e\xb0\x88\xc8\x9c\x0c\xd7\x74\xad\xe9\xaa\x20\x74\x78\x11\ -\x83\x43\x0b\x82\xc5\x34\xad\x26\x1b\x88\xa2\x57\x03\x8b\xed\x74\ -\x3a\x50\xba\x2b\xe9\xb2\x58\xbc\xb0\x14\x84\x0a\x9a\x36\x1d\xae\ -\x05\xc5\x6d\x36\xcb\x7b\x1e\x2f\x92\x7e\x66\xed\x5a\x9a\x7a\xb3\ -\xff\xe5\xf3\x3e\xe7\xfc\x7f\xcf\xe1\x3d\xe7\x3c\x07\x6e\x76\xc9\ -\x6a\x92\xeb\x9a\xbb\x2b\xad\x9b\xd9\x2f\x2a\xbb\x10\x2a\x11\x2a\ -\x50\x0c\xca\x18\x22\x49\x84\x73\x8e\xda\xde\xc1\xe8\xd1\x5f\x0b\ -\x0a\xe0\x6d\x0a\xfb\x50\x3a\x80\xa7\x56\x38\x6b\x5c\x54\x8f\xc5\ -\xa3\x47\xbf\x5f\x13\x40\x6d\x63\xf4\x0e\x91\xe9\x8f\x80\x17\x73\ -\xa1\x14\x48\xbf\x2a\x67\xd4\x71\x47\xf5\x5f\x93\x2a\xde\x60\xac\ -\xa6\xf1\x58\xb1\xdb\x8c\x61\xb7\x5a\xea\x11\xb6\xe6\xa6\xff\xc6\ -\x71\xdd\x43\x83\x27\xdb\x2e\xae\x1a\x60\x7b\x73\x77\xb5\xc9\xd8\ -\x3e\x44\x1f\x00\x52\x22\x04\x6f\xdd\x32\xf9\xc9\x40\x28\x94\x59\ -\xb6\xa4\x60\xd0\x78\x27\xca\x5f\x00\x39\x0e\x5a\x05\xfc\x6e\x60\ -\xdf\xf9\x68\xeb\xcf\x2b\x06\xf0\x1e\xf9\xa0\x0a\x5b\x34\x08\x6c\ -\x06\xbe\x72\x4a\x78\x79\xb0\xab\xf5\xef\x65\x8d\x17\xa9\x3a\x10\ -\x2e\xdd\x34\x4d\x0f\xc2\x21\xe0\x32\xc2\x63\x17\x3e\x6e\x1d\xba\ -\x21\xc0\x8e\x40\x78\x63\x26\xcd\x8f\x02\x35\x8a\x7e\x98\xf0\x4c\ -\xbd\x41\x28\x64\x57\x63\x3e\x27\x95\x3a\x7f\xb8\x5d\x91\x77\x81\ -\xa4\xaa\xeb\x4b\xc4\x5e\x4f\xcd\xcf\x30\x8b\x87\xb8\xd3\x44\x04\ -\x6a\x80\xfe\xb5\x99\x03\x88\xc6\xa3\xad\x1d\x22\x9c\x04\x2a\x8c\ -\x38\x9f\x83\x2e\x28\x7a\x01\x80\xcf\xdf\xe5\x45\x38\x80\xf0\xa7\ -\x6a\xe9\x81\xb5\x99\xcf\x41\x5c\x9e\x9c\x6c\x01\x46\x14\x76\x7a\ -\xfd\xe1\x67\x96\x04\xb0\xa2\xef\x01\xa8\xea\x3b\x89\x98\xff\xaf\ -\xb5\x9b\x67\x35\x7c\x2a\x94\x16\x78\x2b\x07\xd4\x31\x7f\x15\x66\ -\x01\x6a\x1b\x3b\xef\x42\x79\x1a\x98\xba\x3a\x35\x15\x2d\x94\xf9\ -\x8c\xe2\xd1\x40\x2f\x30\x02\x3c\xe8\xf3\x77\x3d\x94\x07\x20\x98\ -\xbd\x80\xa0\x7c\x3d\x7c\x2a\x94\x2e\x34\x00\x88\xa2\xda\x07\x60\ -\x45\x9f\xcb\x03\x40\xe4\x49\x00\x45\xbe\x2d\xbc\x79\x56\xd6\x98\ -\xef\xb2\x28\xb2\x33\x1f\x00\x2a\x01\x1c\x91\xdf\xd6\x0b\xa0\x84\ -\xcc\x28\x80\x42\x45\x1e\xc0\x4c\xd0\xc8\xb5\x54\xfe\xd0\xc2\xe8\ -\x52\xb1\x33\x33\xf7\xdd\x33\x3f\x62\xde\x39\xf0\xbf\x29\xf8\xf6\ -\x42\x00\x81\x31\x80\xb4\x38\x9e\xf5\xf2\xbc\xdd\x1a\x0f\x80\xc2\ -\xf8\xcc\x19\x33\xb7\x02\x2a\x7f\x00\x18\xcb\x3d\xeb\x05\x60\xae\ -\xb9\x55\x00\x02\xc9\xd9\xd8\xdc\x57\x1d\x00\x10\x91\x3d\xeb\x06\ -\x60\xd8\x0d\xa0\xf0\x43\x1e\x80\x5b\x24\xfd\x00\xaa\xfa\x6c\x6d\ -\x63\xb4\xb8\xf0\xf6\x2a\x56\x65\x1f\x80\xb1\x6e\x6f\x1e\xc0\x50\ -\x24\x30\x2e\x59\xb2\xcd\x30\xfd\x6a\xa1\xed\xbd\x47\x22\x7b\x73\ -\x97\xdc\x2f\xf1\x13\x6d\xb3\xbd\xc1\xc2\x5d\x60\x6d\x3b\x80\x08\ -\xc1\x1d\x81\xf0\xc6\x42\x99\xd7\x34\x04\x4b\xd4\x66\xef\x19\x81\ -\x63\x20\x7a\x5d\x80\xf8\x89\xb6\xb8\xc2\x17\xc0\x16\x37\xcd\x67\ -\x04\x83\x05\xd8\xa6\x2a\x1b\xee\x2c\x0f\xe7\xaa\x1f\x88\x47\x03\ -\xa7\xe7\x7f\xcd\x37\xd0\xd2\x16\xb2\x97\x46\xbd\x77\xa2\xfc\xfd\ -\xb5\x41\xa8\x78\x9b\x22\x6f\x22\xf8\x51\xc6\xdd\x62\x79\x69\x7e\ -\xf5\xb0\x44\x4b\xb6\xbd\xb9\xbb\xda\xb8\xee\x20\x50\x06\x7c\x79\ -\xc5\x71\x0e\x0e\xf7\xb4\xfc\xb3\x1a\xeb\x9a\x86\x60\xc9\x2d\x65\ -\xe5\x11\x81\xc3\xc0\x15\x83\x3c\x71\x3e\x1a\xb8\xb0\x38\x6f\xc9\ -\xa6\xd4\x77\x38\x72\x9f\x35\xb6\x0f\xb8\x5f\x91\x31\x81\xe0\x6d\ -\x9e\x4b\x9f\xae\xa4\x29\xad\xbb\x58\xf6\xbc\x55\x39\x2e\x70\x2f\ -\x90\x54\x35\xf5\x89\xd8\x6b\x3f\x5d\x2f\x7d\xd9\xb6\xfc\xe1\x57\ -\x3a\x37\x15\x95\x9a\x18\x48\x43\x2e\x94\x14\xa1\x1f\xe5\x0c\xd6\ -\x8c\x16\xd9\x74\xea\xaa\x2b\xd6\x29\x29\xf2\xa8\x61\xab\xb1\x76\ -\x0f\x62\xea\x73\xdd\x30\xc0\x59\x71\x9c\x83\xf1\x9e\x96\x89\xa5\ -\x3c\x56\xf4\x30\xf1\xf9\x23\x8f\x5a\xb4\x03\xf4\xf1\x95\xe4\x03\ -\x43\xaa\xb4\x27\x62\xad\x67\x6f\x94\xb8\xaa\xa7\xd9\x23\x4d\x9d\ -\xdb\x32\xd6\xd9\x8f\xb0\x0b\xcd\x3d\xcd\xc0\x01\x92\xd9\xe3\x55\ -\xcf\x59\x35\xbd\x89\x58\x60\x64\x35\xf3\xde\xdc\xfa\x0f\x80\xbd\ -\x5b\x45\x41\xb4\xc0\xa5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ -\x60\x82\ -\x00\x00\x04\xe8\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x9a\x49\x44\x41\x54\x58\x85\xc5\ -\x97\xd9\x76\xe2\x46\x10\x86\xbf\x66\x11\x12\x60\x50\x9c\xc4\x9e\ -\xf1\x24\x39\x59\xde\xff\x9d\x72\x31\x9e\x49\x1c\xcf\x18\x6c\x23\ -\x19\x24\xa8\x5c\xd4\xdf\xa8\x91\x71\x72\x97\xd4\x39\x1c\x89\x56\ -\xd7\xf6\xd7\xd6\x0d\x58\x09\x16\xf8\xcf\xc9\x02\x58\x19\xa4\x7c\ -\x09\xac\x21\x58\xf7\x91\x4b\x20\x1a\x96\x25\xef\x93\x44\x4a\x5c\ -\xb3\x64\x6d\x9b\xac\xed\xf4\x7e\x00\x1e\x7a\xf2\x97\xc0\x3a\xf4\ -\x16\x0e\xc0\x05\x30\x00\xaa\x44\x59\x90\x11\x13\xd8\x0d\x21\x8c\ -\x81\x71\xcf\xa5\x16\xac\x81\xac\x95\x11\x51\xb9\x01\x0d\x90\x4b\ -\xfe\x23\x30\x3c\x75\xd8\xf7\x2d\xc0\x7e\x11\x34\x63\xb0\x99\xd6\ -\x33\xb0\xf7\xf0\x50\x82\xe5\x60\x13\xb0\x82\x57\x64\x85\xbe\x4d\ -\xb5\xf7\xca\x79\xc1\xd7\x2c\x93\xec\x5f\xc1\x2e\xfa\x10\x02\xf6\ -\x01\xf8\x24\x24\x0c\x78\x01\x0a\xd8\xbd\x87\xec\xa3\xbc\x00\x58\ -\xc8\x8b\x73\x94\x7e\x9b\xc0\xee\x06\xb2\x5b\x21\x92\x4b\xdf\x1a\ -\xb8\x81\x70\x0b\x30\x92\xf2\x80\xc3\x3e\x96\xf2\x1b\xe0\xde\x19\ -\xb2\xfb\x44\xf9\x04\x0f\x91\x71\x1a\xf7\xe8\xcc\x4c\xca\xf4\xcb\ -\xbe\xc2\xa6\x80\xd9\x18\x78\x07\x7c\x94\x8e\x41\x0f\x01\xfb\x4e\ -\xff\x2b\x08\x15\xd8\xb5\xbe\xfd\x09\xcc\x1d\x8d\xd5\x0c\x4a\x5c\ -\x70\xa8\xcf\x03\x60\x73\xa0\xc5\xf3\xa5\xd2\xf3\x80\x27\xf4\x0e\ -\x78\xc2\xe3\xff\x0d\xb0\x82\xb0\x19\x25\xdc\x63\x29\xcf\xe5\xdd\ -\x1a\xb8\x92\xc5\x39\x94\x4f\x82\x71\x02\x66\x1d\x0f\x24\x08\xe5\ -\xc0\xb3\x94\x95\x42\x38\x03\xee\xf0\xf0\x64\x10\x9e\x12\x07\x3b\ -\x28\xdc\x52\x9b\xc0\xcb\xb5\x18\x83\xa0\x5c\x48\x68\xa4\x39\x1e\ -\x86\xb9\xf8\x07\xfa\x1f\xd7\x22\x6d\xc4\xbb\x93\xac\x00\xdb\xf7\ -\x4a\xcc\x63\xee\xc5\x10\xbc\x73\x41\x15\x30\xfd\x8c\xc7\xb2\x96\ -\xf5\x23\xc1\x56\x43\x75\x09\xd3\xb5\x23\x75\x8e\x6c\x21\x99\x35\ -\x30\x95\x03\x53\xba\xd2\x1b\x49\xf6\x1c\x0f\xc1\x97\x14\x81\x09\ -\xb4\x2f\x49\x6d\x16\x8a\xb5\xe1\x96\x5d\xc3\x74\xe5\x48\xbd\x49\ -\xb1\xce\xbf\x17\x8f\x09\x89\x58\xb6\x2d\x3c\x36\x78\xe8\xfa\x21\ -\x68\x4a\x58\x3c\x74\xc6\x30\x54\x3e\xe4\x78\xd2\xfc\x25\xc1\x85\ -\xfa\x41\xee\x49\x67\xb3\xee\x3f\x05\x9e\x37\x5f\x61\x73\x29\xde\ -\x3c\x91\x09\x2c\x9e\x49\x42\x15\x0d\xc8\xbc\x8b\x91\x0b\xc6\x52\ -\x1e\xb4\x62\x5c\xe1\x89\xf6\x20\x48\x73\x3d\x83\xa0\x9d\xba\x0c\ -\xa6\xae\x9c\x06\x66\x0f\xda\xd7\xe2\x3d\xe5\x12\xef\x31\x43\x68\ -\x4c\xfb\x63\x1f\x20\x40\x50\xd7\x0a\x8f\xde\xb9\x82\x32\xdb\x0c\ -\x82\xfa\xbb\x35\x12\x36\x06\xee\x7b\xbd\xfd\xca\x8d\x8e\x7c\xb4\ -\x60\x7b\x7f\x86\x1d\xd8\x33\x5e\x86\x03\xba\x24\x3f\xa9\x82\x61\ -\x52\xdf\x49\x93\xa9\xd3\x3d\xda\xc7\xbd\x7b\x63\xe9\x30\xbb\x4b\ -\x1c\x8a\x94\x4e\x59\xc9\x0c\x55\xe7\x6c\xc7\x30\x82\xf1\x21\xf1\ -\x86\xe4\xbd\x4d\x84\x8c\x80\xc6\x3d\xb7\x35\xea\x4c\x78\x46\x5b\ -\xd2\x1f\x52\x4a\x1d\x78\x35\x3d\x07\xc9\x73\x7f\x86\xb9\x4f\x87\ -\x9e\xc0\x3e\x9d\x6b\xcf\x96\xbc\xbf\xda\x17\x85\xed\xa0\x51\x57\ -\x0b\xd6\x6d\x0e\x06\xf5\xb0\x67\xc0\x30\x81\x7d\xa5\xdf\x32\x99\ -\x27\x7d\x83\x4f\x46\x6e\xdf\x98\x94\xa1\x55\x29\xf5\xac\x2d\xfa\ -\x75\xdf\xe2\x09\xa7\x79\x1e\x62\xdb\xbe\xa6\x3b\x03\x44\x0a\xaf\ -\xdf\xad\x00\x3b\xee\x8b\x39\x60\xca\x70\x53\x19\xce\x34\x58\xc0\ -\x4b\xb3\x94\xe2\x02\x6f\xb9\x6a\x36\x96\x42\xdc\x00\xdf\x4a\xb8\ -\x49\xb6\x0e\x21\x16\x3b\x20\x32\x76\x1f\xf9\xa2\x01\x3b\x08\x43\ -\x95\xdb\xd6\x0f\x24\x34\xfe\xdf\xc0\x33\x7f\x23\x21\x9f\xff\x61\ -\x1a\xee\x38\x9e\x76\xd6\x25\x2c\xef\x3a\x07\x79\xc0\x4b\x38\xee\ -\xd9\xc1\x49\x08\xc6\x75\xe2\xf5\x16\x35\x0a\x51\x05\x2f\x3f\xc9\ -\xf3\x73\x99\x7e\xb4\x40\x1e\x7e\x80\xe5\x53\xb7\xbc\x2a\xa4\x1c\ -\x37\x6c\xbc\x89\x5f\x06\x09\xe3\x06\xea\xb2\x63\xa2\xf6\x86\x14\ -\x0f\x1a\xf9\x2d\x3e\xdd\xfa\x67\xc1\x94\x22\xd4\x7f\xe0\xed\x36\ -\xf8\xb3\x4c\x86\x57\x36\x93\x31\x27\x21\xd8\xfb\xe6\xe2\x19\xec\ -\x86\x6e\xe0\x14\xf8\x49\xe6\x77\x3c\x9e\x7b\xa0\x74\xa4\xea\x41\ -\x97\xa0\xf5\x50\x02\xd5\x21\x8f\x7b\x7f\xc6\xbb\x9f\x8e\x77\x2c\ -\xa1\xb8\x95\xcc\x6d\x6a\x00\x6e\x40\x78\x06\x1b\xd0\xc5\x7c\x24\ -\x6f\x0e\x10\x36\x60\x2d\xf0\x0c\xe1\xe5\x3c\x00\x36\x77\x19\xa0\ -\x83\xeb\x67\x7c\x96\x6c\x24\x73\xe5\xf9\xd3\x45\x31\x0d\x41\xe3\ -\x93\x2d\x3c\x42\x7d\xe1\x9e\xb2\x96\xf5\x5b\xe5\xc7\x71\x8c\xbe\ -\x4d\x36\x56\xe8\x1a\x3c\xd1\xd6\xc0\x25\x54\x33\x47\xc3\x66\x5a\ -\x3f\x09\xc1\x57\xe0\x07\xdf\x6c\x4b\x60\x06\x2f\x41\x93\x74\x42\ -\x67\xb2\x0e\x97\x55\x05\x85\xd1\x75\xcf\xd8\xac\x0a\x3c\xdb\x77\ -\x38\xf3\xc2\x8d\xaf\xa7\x30\x9d\xe3\x13\x76\xe3\x8e\x87\x4d\x62\ -\x40\x30\xb0\x03\x5e\xeb\x01\xf8\x04\x45\x34\x86\x0e\x56\xf0\x30\ -\x4c\x75\xf4\x36\x21\x18\xe2\x1c\x59\x38\x82\xc7\xbd\x17\x6e\xcc\ -\xf4\x8b\x64\xc5\xd9\x72\xee\x50\x63\x17\xba\x34\xf4\x2f\x26\x0b\ -\xa8\x7e\xec\x2e\x23\xff\x76\x31\x01\xe7\xad\x3e\x74\x65\x7d\x72\ -\x31\xf9\xed\xcc\xc5\xe4\xd8\xdb\xf7\x82\x6d\x20\x2b\x33\x1c\xfe\ -\x81\x7f\x6f\x32\x79\x30\x84\x71\x7a\xf7\xcb\x75\x30\x6e\x7d\xd4\ -\x8e\x6a\xbc\x67\xec\xc5\xdb\xd0\x0d\xa6\x35\xc9\xd5\xec\x8d\xcb\ -\x69\xf4\xe2\x98\x70\xc3\xe4\x7d\xa2\xf7\x09\x6c\x35\x3b\x26\x95\ -\x94\x18\xdd\xe5\x54\x06\xb9\xb0\x18\xf3\x9e\xc3\x6b\xf8\x9f\xaf\ -\xe7\x7f\x03\x88\x7c\xd3\x3b\xed\x32\x4f\xdf\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x06\x7b\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x06\x2d\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\xc9\x73\x5c\x57\x15\xc6\x7f\xdf\xb5\x49\x39\x09\x91\x83\x33\ -\x40\x15\x2b\xb6\x78\x48\x9c\x48\x3d\x24\x14\xc4\x8a\x63\xc9\x93\ -\x2c\x75\xab\xf2\x87\xb0\x0a\x0b\x58\x50\x5e\xb0\xc9\x12\xfe\x88\ -\x54\xab\x25\x92\x38\x65\x6b\x34\x09\xa0\x1e\x0c\x45\x18\x56\x29\ -\x2a\x95\x62\x45\x26\xb0\x6c\x63\x29\x46\xf7\xb0\xe8\x6e\xe8\x74\ -\xb7\xf4\xee\xeb\x7e\x4f\xea\x14\xfa\x96\xf7\x9e\x3e\xf7\x7c\xbf\ -\x3a\xe7\xf5\xeb\xa7\x27\x38\xd0\x81\x0e\xf4\xff\x2c\xf5\x5a\x3c\ -\x75\xc3\x1e\x7d\xf8\x2e\x3f\x94\xec\xb2\xc1\x11\xcc\xd6\xed\x6b\ -\xee\x67\xb5\x29\x7d\xb8\xd7\x05\xf6\xa3\xcc\x9b\xf6\x1d\x3d\xf0\ -\xaf\x21\xe5\x05\x9b\x5e\xba\xf6\xc8\x03\x5e\xbf\xf9\xaa\xee\x76\ -\xc6\x76\x01\x78\xf1\x97\xf6\xd8\x03\x6f\xbf\x92\x71\xba\x63\xeb\ -\xb6\x9c\x26\x2a\xd3\xaa\xa6\x56\x79\x02\x1a\x9b\xb3\x31\x27\x5b\ -\x02\x8e\x76\x6c\xbd\xcf\x11\x7d\xbf\x7a\x41\x1b\xed\x8b\xae\x33\ -\xc1\xf6\xb6\x7f\xad\x87\x79\x80\xa3\xe6\x6d\x31\xb7\x60\xd9\x04\ -\xeb\x4d\x54\xbb\x98\x07\x78\x86\x4d\xff\xa3\xce\xc5\x2e\x00\xa0\ -\xa9\x5d\xce\x18\x19\x56\x08\x11\xe6\x9b\xd2\x95\xce\x95\x2e\x00\ -\x1e\x1e\x8e\x38\x6b\xc4\xbc\x2d\xe6\xe7\x2d\x13\xb7\xc8\xb4\x94\ -\x29\xd9\x68\xb4\x79\xc0\x38\xd2\xb9\xd4\x05\x40\xd8\x6f\x02\xce\ -\x1c\xf1\x66\x4b\xc3\x00\x21\x53\xb2\x51\x39\x5b\x26\xca\x3c\x80\ -\xba\xbd\x75\x8f\x80\x77\x57\x81\xdb\x01\x67\xef\x3b\x84\x58\xe6\ -\x61\x03\xef\x7e\xda\xb9\xd8\x05\xa0\x3a\xab\x0f\x9c\x74\x8e\x70\ -\x08\xfb\x32\x0e\x4d\xf3\xd1\x6d\xdf\xd0\x06\xa6\x89\xea\xac\x3e\ -\xe8\xdc\xe8\x79\x1f\x00\x90\x9f\xb7\x8c\x37\x5b\x02\x46\x02\x0e\ -\xb8\xed\x4d\xaf\xd4\x8b\xaa\x07\xc4\x0e\xac\xec\xbc\x3d\x8f\xd9\ -\x32\xf0\x78\x40\xf8\x1d\x4c\xe7\xaa\x45\x55\x7a\x6d\xee\x08\x00\ -\x86\x13\x42\x92\xe6\x21\x02\x00\x0c\x17\x84\xa4\xcd\x43\x00\x00\ -\x80\xdc\x82\x65\xcd\xdb\x22\x81\x10\xcc\xeb\x6c\x6d\x56\xb7\x42\ -\x72\x87\x2a\x37\x67\xcf\x99\x6c\x19\xf8\x46\x40\xf8\x1d\x43\x13\ -\xb5\x82\xd6\xa3\x02\x83\x00\xc0\xfe\x42\x48\xcb\x3c\xf4\xbc\x13\ -\xec\xad\xca\xb4\xaa\x98\x26\x80\x8d\xc8\x60\x38\x2a\x67\xcb\x99\ -\x92\x8d\x86\xe6\xdf\x49\x71\xcd\x3b\xa7\xc9\x50\xf3\x10\xa3\x03\ -\x5a\xca\xce\x59\x0e\xd9\x22\xf0\x58\x40\xf8\x3f\xcd\xeb\x95\x7e\ -\x3b\x21\xa6\xf9\xbb\xce\x69\x62\x7d\x5a\xbf\x8d\x73\x46\x6c\x00\ -\x10\x1f\x02\xd2\xd9\xea\x8c\x7e\x17\xe7\x8c\xbd\x30\x0f\x31\x46\ -\xa0\x5d\xd5\xa2\x2a\x98\xce\x01\x77\x02\xc2\x1f\xc7\x6c\x39\x3b\ -\x6f\xcf\x87\xe6\xcf\x97\xec\xf4\x5e\x98\x87\x3e\x01\x40\x03\x82\ -\xa1\x09\x12\x86\x90\x2f\xd9\x69\xef\x6c\x85\x40\xf3\x32\x4d\xf6\ -\x6b\x1e\xfa\x1c\x81\x76\x65\xca\x96\x17\x76\x83\x04\xc6\xa1\x1f\ -\xf3\x95\xa2\x42\x7e\xbc\xed\xa8\xbe\x3b\xa0\xa5\x5a\x41\xeb\xce\ -\x69\x92\xf0\x4e\x58\xca\xcd\xd9\x73\x9d\x1b\x4d\xf3\xc1\x6d\x0f\ -\x3a\x3f\xa8\x79\x48\xa0\x03\x5a\xca\x2f\xd8\x0b\xde\xdb\x0d\xe0\ -\xeb\x01\xe1\xff\x90\xe9\x6c\xa5\xa8\xdf\x03\x8c\xcd\xdb\xb3\xce\ -\x6c\x05\x38\x16\xf9\x49\xe3\x1e\xd2\x64\xb5\xa0\x5f\x0f\x56\x71\ -\x43\x89\x01\x80\xfe\x20\x6c\x3b\xfc\x7e\x99\x87\x84\x01\x40\x3c\ -\x08\x26\x36\x64\x40\xc8\xdd\x65\x0a\xe6\x21\x05\x00\x00\xb9\x39\ -\x7b\xd1\x64\xd7\x09\xeb\x84\x68\x19\xf7\xec\x90\xce\xd7\xa6\xf5\ -\x5e\x22\xf9\xda\x94\x0a\x00\x48\x10\x42\x8a\xe6\x21\x81\x6f\x81\ -\x9d\xd4\xb8\x42\xeb\x3c\xd0\xf5\xc7\x88\x60\x19\xf7\x3c\xba\x90\ -\x96\x79\x48\xb1\x03\x5a\xca\x96\xed\x7b\x98\x5d\x47\x3c\x1a\xeb\ -\x83\x4d\xf3\xf5\xa2\xde\x4d\xa9\x34\x60\x0f\x00\xc0\x7f\x21\x2c\ -\xa2\xc8\x47\xee\x0d\x19\x9b\x1e\x4d\xa4\x6d\x1e\x52\x1c\x81\x2f\ -\xc9\xb3\x81\xf8\x22\x38\xde\xe9\x0b\x5c\xd0\xcf\xee\x81\x95\x3a\ -\x80\x6c\xc9\x4e\xe1\x6c\x95\xb0\xa7\xb7\x0d\x99\x8d\x38\xb3\x95\ -\xb1\x79\x7b\x36\xbd\xca\x1a\x4a\x75\x04\xda\xcc\x3f\xd1\x67\x8a\ -\xcf\xbd\xf4\x72\x7d\x46\x7f\x48\xb2\xae\x76\xa5\x06\xa0\x69\x7e\ -\x05\x78\x72\xc0\x54\x9f\x1b\x1a\xaf\x15\xf4\x7e\x12\x75\x75\x2a\ -\x95\x11\xc8\x2f\xd8\xc9\x84\xcc\x03\x1c\x13\xb6\x9a\x29\xdb\x33\ -\x09\xe4\xea\x52\xe2\x00\xf2\x0b\x76\xd2\x7b\x5b\x25\xc0\xbc\xc1\ -\x96\x60\x2b\x20\xed\x31\x61\x2b\x69\x40\x48\x14\x40\x1c\xf3\xc0\ -\x7d\x27\x4d\x6e\x37\x9e\x2c\xfd\x2b\x20\xfe\x89\x34\x20\x24\x06\ -\x60\xb4\x6c\x27\xe2\x98\xc7\x74\xb1\x32\xa3\x9b\xf5\xa2\xde\x75\ -\xe8\x02\x31\x20\x64\x4b\x76\x6a\xb0\x6a\xff\xa7\x44\x2e\x82\xa3\ -\x65\x3b\x71\x08\x5b\x23\x86\xf9\x6a\x51\x6b\xed\x8b\xf9\xb2\xfd\ -\xc0\x63\xef\x00\x8f\x04\xe4\xf8\x0c\xaf\xf1\xea\xac\xfe\xd8\x4f\ -\xbd\xed\x1a\x18\x40\x5c\xf3\x86\x2e\xd5\x0a\x5a\xed\xb5\x99\x9b\ -\xb7\x97\xcc\xec\x1a\x7b\x08\x61\xa0\x11\x18\x2d\xdb\x09\x47\x78\ -\xdb\xef\x66\x1e\xa0\x32\xa3\x9b\x92\x2e\x12\x38\x0e\xb8\xc1\xc7\ -\xa1\xef\x0e\x68\x99\x17\x3c\x15\x10\x7e\xdf\x4b\x97\xeb\x33\x5a\ -\x09\xc9\xdd\xec\x84\x77\x88\x7e\x5d\x07\xe0\x53\xe7\x34\xbe\x3e\ -\xad\x3f\x85\xe4\xee\x54\x5f\x00\xc6\x4a\x76\x5c\xce\xd6\x02\xcd\ -\x6f\x7a\xe9\x52\xa8\xf9\x96\xf6\x0a\x42\xec\x11\xd8\x0b\xf3\xd0\ -\x18\x07\x4c\x17\x81\xfb\x01\xe1\x4f\x7a\x6f\xab\xf9\x05\x3b\x19\ -\xf7\x9c\x58\x1d\x30\x56\xb2\xe3\xae\x71\x6f\xff\x74\x40\x78\xdf\ -\xe6\xdb\x95\x9d\xb3\x33\xc8\xae\x11\xd8\x09\xdb\xe8\xcc\xad\x82\ -\xfe\x1c\x9a\x3f\xb8\x03\xe2\x9a\x97\x0f\x9f\xf9\xdd\x54\x2d\x6a\ -\xcd\xd0\x25\x02\x3b\xe1\x10\xb6\x36\x5a\xb6\x13\xa1\xf9\x83\x3a\ -\x20\xbb\x60\xdf\xc5\xdb\x1a\x31\xcc\x57\x66\xb5\x1c\x5a\x44\x88\ -\x32\x65\x1b\x17\xf6\x36\x09\x77\x42\x24\x80\xb8\xe6\x41\x53\xd5\ -\x82\x96\x02\x62\x63\x6b\x6c\xde\x5e\x76\x66\x6f\x11\x00\xc1\xe0\ -\x13\x8f\xc6\xa3\x20\xec\x0a\x60\x98\xcc\xb7\xd4\x84\xf0\x36\x74\ -\xbf\xf5\xd9\xa9\x10\x08\x3b\x5e\x03\x9a\xe6\x83\x67\x1e\xe9\x4a\ -\xda\xe6\x01\xea\x33\x5a\xf1\xd2\x25\x60\x33\x2a\x56\xf0\x94\xc3\ -\x56\xc7\x4a\x76\x7c\x97\x98\x6e\xb5\x99\xff\x66\xd4\x21\x06\x5b\ -\x92\xa6\xaa\x33\x5a\x8c\x8a\x4d\x52\x71\x3b\xc1\xbc\xce\xd4\x67\ -\xf5\x97\xce\xbd\x2e\x00\xf9\x37\xec\xdb\xfe\xb0\xdd\x02\xbe\x15\ -\x90\x78\x5f\xcc\xb7\x94\x2b\xd9\x59\x73\xf6\x16\x01\x10\x80\x8f\ -\xbd\xd3\x68\x7d\x5a\x7f\x6b\x5f\xec\x7e\x5b\xfc\xb0\xff\x31\x5f\ -\x01\xf3\x00\x95\x59\x2d\xcb\xeb\x32\x01\xe3\x00\x3c\x2d\xef\x7f\ -\xd2\xb9\xd8\xeb\xff\x05\x5e\x8a\xca\x64\xb0\x85\xd7\x95\xfd\x34\ -\xdf\x52\xe3\xeb\x56\x53\x04\x41\xd0\x99\xce\x95\x5e\x17\xc1\xed\ -\xdd\x52\xb4\xcc\xd7\x66\x75\x23\xb4\xc8\xb4\xd5\xb8\xf8\x46\x43\ -\x50\x0f\x6f\xdd\x00\x1a\x6f\x7f\xf5\x94\xc1\xd6\x21\x34\x3d\x4c\ -\xe6\x5b\xaa\x16\xb4\x84\x74\x85\x5d\x21\xd8\xf5\xce\x95\x2e\x00\ -\x66\xee\xaa\xc1\x5f\xbb\xd6\x9b\xe6\xd7\x0b\xea\x4a\x32\x2c\xaa\ -\xce\x68\x71\x47\x08\xc6\x87\x0f\xfd\xdb\x5d\xed\x5c\xee\x02\x50\ -\x2b\xe8\xb3\xed\xc3\xca\x81\xfd\x1c\xf8\x08\xf8\x18\x78\xd3\x99\ -\x5e\x18\x66\xf3\x2d\x55\x67\xb4\xe8\xa5\x3c\xc6\x02\xf0\x77\xe0\ -\x23\x64\xbf\x78\x68\x5b\xd9\xf7\x5e\xd5\x27\xfb\x5d\xdf\x81\x0e\ -\x74\xa0\xe1\xd2\x7f\x00\x72\xd2\x49\x30\x2e\xe9\xad\x3a\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\x58\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x0a\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4b\x88\x5c\x45\x18\x85\xcf\xa9\x19\x34\x41\xa2\xa0\x21\x1b\ -\x09\xee\x7c\xac\x04\x13\x7b\xda\xb8\x30\x06\x13\x99\x80\x26\xdd\ -\x1d\x06\x17\x82\xe0\x83\x08\xae\x14\x09\x24\x88\x1a\x4c\x40\x11\ -\x5c\x28\xf8\x42\xd1\x85\x28\x8a\xdd\xf3\x40\x26\x32\x41\x1c\x10\ -\x64\x7a\x9a\x11\xb2\x10\x41\x5c\x04\x11\x41\x83\x09\x11\x25\x0d\ -\xe9\x5b\xc7\x45\xcf\xa8\xdc\x2a\x35\x9d\x54\x55\x17\xd8\xdf\xf2\ -\x2e\xea\xfc\xff\xb9\x55\x7f\xd5\x7f\x1f\xc0\x88\x11\x23\xfe\xcf\ -\x30\xd4\x40\x95\xa6\x9e\x35\xb4\x4f\x89\x94\x2c\x8f\x2c\x37\x78\ -\x38\xd4\xd8\x31\x09\x66\xc0\x44\xb3\x28\x40\x9a\xd5\x51\x45\x70\ -\xc7\x52\x8d\x8b\xa1\xc6\x8f\x85\x09\x36\xd2\x5a\xf2\x00\x20\x50\ -\xd2\xdc\xc4\xb4\xb6\x04\x1b\x3f\x12\xc1\x0c\x10\x60\x4b\x97\x36\ -\x40\xfa\x74\xeb\xac\x6e\x08\xa5\x11\x83\x60\x06\x10\x90\xe7\xf2\ -\xc6\xb1\x42\xc7\x6f\x9d\xd1\xe6\x50\x3a\xa1\x09\xb7\x04\xfe\x99\ -\xcd\xc6\x6a\x61\xcb\x9c\x36\x26\xd0\x1a\x98\x14\x06\x00\xc0\x8d\ -\xe3\x85\x8e\xdd\x3e\xab\x0d\x89\xf4\x2e\x98\x68\x06\xa8\xbc\x24\ -\x84\xad\xbd\x42\x33\x93\xf3\xba\x3c\x96\xe6\xc5\x10\xcd\x00\x02\ -\x16\x74\xea\xc2\x8e\xd3\x5d\xbd\xbf\xfd\x73\x8d\xc7\xd2\x1d\x94\ -\xb8\x4b\x40\xb0\x70\x8b\x63\xbd\x7b\xda\xbe\x0e\x29\xd8\x19\xe4\ -\x52\x48\x51\x03\x9c\x99\x20\xf2\xa1\x6a\xcb\x3e\x9f\x40\xfb\x3f\ -\x49\x53\x04\x05\xab\x72\x49\x20\x0f\x54\xa6\x75\x20\x89\xfe\xbf\ -\x90\x6a\x17\x00\x69\x0a\xe7\x9a\xf4\x42\xb5\xa9\x87\x53\xc5\xe0\ -\x23\x99\x01\x90\x7c\xa7\x45\x88\x7a\xa3\xda\x52\x3d\x59\x1c\x25\ -\xd2\x19\x80\xfe\x69\xd1\x63\x82\x11\xf4\x41\xf5\x63\xdd\x95\x32\ -\x96\x3f\xc5\x53\x0b\x12\xd0\xea\xee\xf0\x77\x2e\x13\x35\x73\xdb\ -\xb4\x2a\xa9\xe3\x49\x6e\x00\x00\x80\x9e\x99\x40\x5c\x61\xa5\xf9\ -\x6a\x4b\x37\xa5\x0c\x65\x38\x06\x60\xad\x79\x62\x79\x26\x5c\x23\ -\xe8\xf8\xb6\xa6\xae\x4b\x15\xc7\xd0\x0c\xe8\x23\x9f\x09\xd7\x16\ -\xd4\xc2\xb6\x96\x36\xa5\x88\x60\xc8\x06\x00\x7d\x13\x54\x3e\x2d\ -\x5e\x5f\x40\xc7\x26\xe6\x75\x65\x6c\xf5\x0c\x0c\x00\x00\x5a\xa7\ -\x79\x02\x6e\x51\x57\x73\xdb\xdf\xd1\xba\x98\xca\x99\x18\xb0\xda\ -\x3c\x95\x4c\x20\x70\xc7\xb9\xab\xf4\x61\xcc\xe6\x29\x1b\x03\x56\ -\xf1\x35\x4f\xf7\x76\xcf\xd8\xb7\xf0\x8c\xa2\xc4\x9a\x9b\x01\x80\ -\xaf\x79\x02\x1f\xa8\xdc\x6c\x5f\x8c\xd1\x41\xe6\x68\x40\xbf\x8d\ -\x2e\xd5\x45\x82\x4f\x54\x5a\x38\x18\x5a\x2a\x4f\x03\x00\x80\x74\ -\x9b\x27\xea\x68\xa5\xa9\xfd\x21\x65\xf2\x35\x00\x80\x04\x5b\xae\ -\x08\xa4\x5e\x9b\x68\x6a\x5f\x28\x8d\xac\x0d\xa0\xef\xc8\x0c\x10\ -\xd4\x2b\xa1\x34\xb2\x36\x00\x00\xe8\x2f\x7b\xc1\xb6\xc5\xbc\x0d\ -\xe8\x67\xef\xc4\x28\xe8\xed\x50\x12\xd9\x3c\x9d\xf5\x22\x8d\xb9\ -\xd7\xf8\xd8\x72\xc3\xbc\x1a\x4a\x22\xe3\x19\xe0\x4d\xfe\xe9\x76\ -\x83\xc1\x92\x07\x72\x34\x80\x80\x08\xe3\xbe\xb9\xd7\xcb\xed\x3a\ -\x8e\x84\x96\xcb\xce\x00\x09\x86\x2a\x67\xaf\xf7\xda\x27\xcc\xe3\ -\x20\x7d\x2f\x60\x2f\x89\xbc\x0c\x20\x0c\x4b\xb7\x9e\xc0\x27\xbd\ -\x53\xe6\x41\x1c\x76\x9e\x1b\x04\x21\x27\x03\x0c\x9c\x3b\x8f\x2f\ -\xd8\xe3\xd4\xca\x7e\x9e\x8f\x25\x9a\xc9\x2e\x20\xe3\xd9\xf1\x4f\ -\xf4\x7a\xbc\x67\x65\x8a\xe7\x62\x2a\x0f\xdd\x00\x81\x2c\x4f\x7b\ -\x08\xdf\x61\x9c\x77\xaf\xd4\x79\x36\xb6\xfe\x50\x97\x40\x3f\x79\ -\xa7\xcf\xff\x91\x86\x3b\xdb\x7b\xf8\x53\x8a\x18\x86\x67\x80\xe0\ -\x4b\xfe\x8c\xb5\xdc\xb5\x54\xe3\xc9\x54\x61\x0c\xc5\x00\x09\x04\ -\x4b\xda\xc2\xef\x10\x77\x77\xf6\xf1\xeb\x94\xb1\x24\xaf\x01\x02\ -\xc8\x72\xf2\xc0\x79\x18\xd6\xdb\x35\x2e\xa5\x8e\x27\xe9\x0c\x90\ -\x40\xca\xd1\x14\xc9\xfb\xdb\x35\x2e\xa4\x8c\x65\x8d\x74\x33\x80\ -\x84\x67\xcd\x03\xe4\xa3\x4b\x35\x7e\x94\x2c\x8e\x12\xc9\x66\x80\ -\x64\xdd\xe6\x86\x3c\xd4\xae\xf1\xcd\x54\x31\xf8\x48\x63\x00\x61\ -\xe8\x6c\xf5\x7a\xa9\xbd\x17\x43\xff\x4c\x26\x85\x01\xee\x11\x57\ -\x7a\x77\xb9\x66\x9e\x8c\xd1\xdc\x0c\x4a\x5c\x03\xfa\xd5\xbe\x7c\ -\xc4\x9d\x5d\x7f\xb5\x79\x24\x87\xe4\x81\xb8\x1f\x4a\xfa\x9a\x9b\ -\xc5\xf5\x67\x79\xdf\xe2\x9d\xec\xc5\xd2\x1d\x94\x68\xbb\x80\x73\ -\xbe\x07\xbe\xc2\x3a\xee\x59\xac\xb3\x1b\x4b\xf3\x62\x48\xb5\x0b\ -\x7c\x3b\x06\x4e\xb6\x77\xf3\xd7\x44\x7a\x17\x4c\x0a\x03\x7e\xe8\ -\xf5\xb8\xf3\xcb\x3a\x7f\x4e\xa0\x35\x30\x21\x7f\x98\xf0\x3d\xc1\ -\xff\x85\xe0\xae\x95\x29\x7e\x1f\x4a\x27\x34\xc1\x6a\x00\x5d\x33\ -\x7f\xb3\xe2\x64\xa7\xc1\x6f\x42\x69\xc4\x20\xe4\x12\xf8\xeb\x99\ -\x1d\x21\x4b\xee\xed\x34\xd8\x09\x38\x7e\x14\x42\xfe\x34\x75\x14\ -\x40\x01\xa0\x80\xf8\x5c\xa7\xc6\xcf\x82\x8d\x3d\x62\xc4\x88\x11\ -\x91\xf8\x03\x6e\xfe\x4e\x7e\xe0\xc6\x25\x53\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xcd\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x7f\x49\x44\x41\x54\x78\x9c\xed\ -\xd9\x51\x0d\x80\x30\x10\x05\xc1\x03\x6f\x55\x80\x05\xd4\x62\xaa\ -\xc8\x58\x12\x66\x0c\xdc\xcb\xa6\x7f\x9d\x09\xad\xeb\xde\xeb\xba\ -\x77\xb9\xe1\x2c\x8f\x7f\x81\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\ -\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\ -\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\ -\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\xda\xef\ -\x03\x1c\xe5\xf1\xfa\x6b\x7c\xa6\x7e\x01\x7b\x9e\xf4\x3e\x00\x00\ -\x00\x00\x00\x00\x00\xfc\xc3\x0b\xb7\x26\x07\xfa\x17\x1e\x2a\x64\ -\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x8f\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\x41\x49\x44\x41\x54\x58\x85\xed\ -\x97\x31\x6b\x14\x51\x14\x85\xbf\x33\x59\xab\x80\x85\x62\x20\x76\ -\xf9\x03\x62\xb5\xbb\xa2\x88\x82\x5d\x42\x8a\x24\xf8\x07\x02\x6a\ -\x95\xca\x24\x65\x08\xa9\x56\xb0\x30\x60\x50\x41\x41\xd2\x04\xc1\ -\x2d\x82\x0b\x76\x01\x41\xb2\xbb\x95\xf8\x07\x92\x3a\x41\xc1\x22\ -\x95\xc9\x1c\x8b\x9d\xb7\xac\x9b\xd9\xec\x4e\x76\xb4\xd1\xaf\x7a\ -\xdc\x77\x67\xee\x99\x73\xdf\xcc\xbc\x07\xff\x3a\xea\x0e\x94\xdf\ -\xfb\x66\x8c\x97\x11\x65\xc1\x95\x3c\x8a\x18\x0e\x31\xf5\x08\x55\ -\xea\xb3\xfa\xdc\x53\x40\xa9\xea\xc7\xe0\x27\x69\xc2\x72\x22\xc6\ -\x5a\x6a\xcc\xea\xe9\x29\x01\xa5\xaa\x6f\x81\x3f\x01\x3f\xb0\x16\ -\xa2\x13\x6a\xbb\xf7\xf5\x3d\x8f\xaa\x37\xde\xf9\x52\x3c\xc2\x24\ -\xf2\x3a\x70\x51\xd6\xed\xe0\x44\x21\x24\xd9\x5e\x92\x10\xd6\x42\ -\x63\x56\x9b\x79\x14\x0e\x24\x0f\xb2\x59\xac\x5a\xc2\x6f\x63\xbc\ -\x0c\x4c\x03\x44\xed\x2c\x51\x06\x88\x4e\xa8\xe5\x59\xbc\x8b\x1a\ -\x80\x44\x29\x04\xda\x02\xc2\x82\xcb\xcb\xf6\x34\x9a\x33\xfa\x96\ -\x0c\xc7\x42\xac\xd0\x23\xf7\xdc\x14\xab\x9e\x12\x7e\x05\x60\xf4\ -\xa0\x39\xa3\x0f\x67\xe5\xe7\x2a\xa0\xb8\xed\x09\xfd\xf4\x16\x62\ -\x14\x20\x11\x72\xf5\xac\x6b\xa2\xb3\x26\x33\xb1\xe2\x48\xc7\x7e\ -\x13\x8a\x0f\x4a\x6e\x02\x4a\xd7\x78\x04\xdc\xe9\x8c\x49\x5a\xfb\ -\x2b\x02\x8a\xdb\x9e\x48\x3e\x60\x9d\xec\xd4\xbf\xf0\xf2\xcf\x0b\ -\x48\xb3\xde\x1c\xb9\xa0\x79\x56\x15\xf7\xbb\xbc\xef\x22\xec\xb7\ -\xaa\x53\xad\x8f\xb4\xd8\x98\xd6\xde\x20\xfa\xfb\x3a\x90\x14\x1f\ -\x07\xc6\x65\x6f\xb5\xec\x4e\xc4\x0d\x61\x7d\x20\xdb\x6b\x28\x46\ -\x75\xec\xd7\xac\xf8\x1e\x40\xaa\xf5\x17\x06\xb3\x7e\x60\x01\x92\ -\xd6\x6c\x6f\x74\x84\xee\x96\xaf\xf3\xd0\x31\x62\x08\xeb\x03\x7d\ -\x5b\x90\xd8\xb9\xd3\x19\xb3\xbd\x81\xfc\xbc\x2b\x35\x93\xf5\x03\ -\x0b\x60\x55\xb1\x0b\x9a\xc7\x1c\xf5\xcc\xc9\xb0\xea\xb3\x0b\x00\ -\x9a\xd3\xda\x03\x2d\xf5\x9a\x57\xa4\xc5\x66\x46\xeb\x33\x09\x00\ -\x68\x7c\xe5\x05\x5d\xad\x48\x38\x97\xf5\x99\x05\xa4\xb6\x62\x08\ -\xeb\xb3\x0b\xa0\xd5\x8a\x48\x9a\x03\xf6\x81\xfd\x48\x9a\x3b\xaf\ -\xf5\x81\xcc\xbf\xe3\xdd\x19\x7d\x04\x26\xfa\x26\x0e\x48\xdb\x01\ -\xc3\x21\xb4\x36\x90\x79\xdd\xbc\x9b\x62\xd5\x97\x93\xe1\xc1\x29\ -\x01\x98\x3a\x40\x3c\xc2\xe4\x9f\x12\x00\xad\x7b\xdb\x34\x42\xa0\ -\xdd\x82\x08\x55\x8c\xa7\x90\xd7\x8b\x55\x0b\xa8\x75\xec\xe1\x86\ -\x22\x79\xf2\x49\xe1\x67\x40\x1c\xa1\x4a\x98\x4b\x3b\x98\x54\xc8\ -\x73\xa7\xf4\x3b\xbd\x0f\x26\x81\x70\x34\x4b\xb6\xce\x63\xdd\xf3\ -\xe7\xe4\xc0\xa6\x91\x76\x34\xfb\xcf\x2f\xa6\x4e\xeb\xad\xb9\x6d\ -\xcb\x1e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x8b\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3d\x49\x44\x41\x54\x58\x85\xed\ -\xd3\x21\x12\x00\x10\x00\x05\xd1\xe5\x52\xaa\xe2\x00\x2e\xea\x04\ -\x66\x64\x97\x32\x92\x2a\x52\xf6\xa5\xdf\x36\x7d\x90\x24\x7d\x16\ -\xce\x48\x6d\x0d\x20\x3f\xaa\xf6\x59\x63\x01\x88\x4f\x82\xd2\x85\ -\x2f\x90\x24\xe9\xbb\x0d\xbb\x58\x0a\x07\x83\x32\x65\x0f\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x26\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xd8\x49\x44\x41\x54\x78\x9c\xed\ -\xd2\xb1\x4d\xc3\x50\x18\x46\xd1\x1f\x86\xf0\x26\x2c\x92\x15\x52\ -\x20\x1a\x86\xa1\x89\xb2\x44\x16\x61\x8b\x54\x6c\x61\x0a\x2c\xa5\ -\x88\x68\x7d\x22\xe5\x1e\xc9\xd2\x73\xf5\x3e\x5f\x79\x26\xc9\x33\ -\x7b\x51\x17\xbf\xbd\x7f\x1d\x66\xe6\xb4\xbd\x7e\x7c\x9f\x3f\x2f\ -\x62\xc7\xab\xb8\x74\x73\x5a\x67\x96\x75\x66\x99\x5b\x88\xdd\xb1\ -\x00\xdb\x87\xdf\x9d\xf7\x26\xff\x80\x87\x50\x00\x3d\x40\x2b\x80\ -\x1e\xa0\x15\x40\x0f\xd0\x0a\xa0\x07\x68\x05\xd0\x03\xb4\x02\xe8\ -\x01\x5a\x01\xf4\x00\xad\x00\x7a\x80\x56\x00\x3d\x40\x2b\x80\x1e\ -\xa0\x15\x40\x0f\xd0\x0a\xa0\x07\x68\x05\xd0\x03\xb4\x02\xe8\x01\ -\x5a\x01\xf4\x00\xad\x00\x7a\x80\x56\x00\x3d\x40\x2b\x80\x1e\xa0\ -\x15\x40\x0f\xd0\x0a\xa0\x07\x68\x05\xd0\x03\xb4\x02\xe8\x01\x5a\ -\x01\xf4\x00\xad\x00\x7a\x80\x56\x00\x3d\x40\x93\x01\x7e\xfe\x39\ -\xef\x0a\x06\x58\x8f\x33\x73\xfd\x7b\xd6\xa3\xdb\x91\xe4\x99\xfd\ -\x02\xc9\x6e\x11\x4a\x9d\x22\x1c\x0a\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x03\x5c\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x0e\x49\x44\x41\x54\x78\x9c\xed\ -\xd5\x4b\x6c\x54\x75\x14\xc7\xf1\xef\xb9\x53\xa6\xda\x81\xd0\xd0\ -\x98\x50\x4d\x4a\x64\x63\x52\x36\xc0\x4c\xc7\x47\xa2\xa9\xcf\xa4\ -\x16\x24\x2c\x70\x41\x04\x4b\x02\x33\x03\xed\x80\x62\xe2\xc2\xc4\ -\x4c\xba\x33\xf1\x51\x3b\x03\xa5\x0f\x89\x04\x16\x18\x0a\x29\x31\ -\x60\xdd\x98\x58\x92\x52\x18\xda\x59\xb2\x00\xa2\x1b\x83\x84\xd0\ -\x0a\x49\x83\x9d\xda\xce\x71\x51\xa3\xd3\x6b\x25\xd8\x7b\x67\xba\ -\xe0\x7c\x96\xff\x73\xef\x6f\x7e\xf7\xcc\x0b\x8c\x31\xc6\x18\x63\ -\x8c\x31\xc6\x18\x63\x8c\x31\xc6\x18\xf3\xa8\x10\xaf\x01\xcf\xc6\ -\xd3\xf5\xb3\xca\x71\x84\xa7\x50\xbe\x18\xed\x4d\x7e\x06\xa2\x7e\ -\x94\x5b\x48\x34\xd1\xb9\xb5\xa0\xf2\x29\x00\x05\x49\x8e\xf6\x25\ -\x07\xbd\xe4\x79\x5e\x40\x24\x9e\x19\x02\x7d\xe9\xef\x03\xe5\xc4\ -\xfd\xdf\xc6\x77\x5f\xed\x6f\x9f\xf6\x9a\x3d\x9f\x4a\x38\x9e\xf9\ -\x50\xe0\x93\xa2\xc3\x7b\xaa\x95\x4f\x8c\xf5\xc6\xff\x58\x6c\xaa\ -\xe3\x43\xb1\xf9\x19\xc2\x8e\xaa\x55\x35\xdf\xaf\x6f\xe9\xa8\xf6\ -\x9e\x3d\xa7\x31\x95\xaa\x88\xc4\xd3\x5d\xae\x87\x9f\x7b\x35\x8f\ -\xbc\x2f\x40\x74\xaf\xc0\x6d\xd7\xe9\xcb\x81\xca\xc0\xf0\x86\xd6\ -\x43\x6b\xbc\xc6\xd7\xef\x3b\xbc\x7c\xf2\x56\xcd\x59\x90\x84\x6b\ -\x94\x17\x78\xc7\xcb\xbb\x0f\x3e\x6c\x10\x20\xba\x3b\xf3\x74\x21\ -\xa0\x83\xc0\x33\xae\xd1\x2d\x55\xa7\x79\xac\xb7\x2d\xb7\x98\xdc\ -\x70\xac\xa3\x56\x24\x70\x0e\xd8\xe8\x1a\x4d\x20\xf2\xd6\x68\x77\ -\x72\x78\x31\xb9\xc5\x7c\xf8\x0a\x40\xf6\xab\xe4\xcf\xcb\x66\x66\ -\x5e\x00\xb9\xe0\x1a\xad\x16\x29\x5c\x08\xc7\xd2\xcd\xff\x37\xb3\ -\x61\xcf\xa1\x75\x22\x81\x4b\xfc\xeb\xe1\xe5\x27\xa7\xe0\x3c\xef\ -\xc7\xc3\x83\x4f\x0b\x00\x18\x39\x7a\x70\xe2\x6e\x50\xdf\x00\x4e\ -\xba\x46\x21\x11\xbe\x0d\xc7\xd2\x7b\x1f\x36\x6b\x63\x22\xf3\x8a\ -\x3a\x85\x61\xa0\x6e\xfe\x44\x2e\xcf\x4e\xeb\x73\xd9\xbe\xb6\x6b\ -\x9e\x0b\xff\x25\xe0\x57\x10\xc0\x44\x76\x70\xf6\xe6\xa6\xe8\x40\ -\xed\x64\x28\x28\xf0\x62\xd1\x48\x44\x68\x7e\x32\xd2\x14\xba\xb9\ -\x29\xfa\x03\x43\x43\xff\xf9\x37\x19\x89\xa7\x77\x0a\x9c\x02\xaa\ -\x8a\xcf\x15\x19\x40\x83\x5b\x72\x47\x5b\xef\xf9\xd9\xd9\x97\xdf\ -\x80\x85\x44\x62\x9d\x31\x44\xba\x70\x2d\x59\xe1\xd4\x8a\xfc\x8a\ -\x77\x7f\x3c\xb6\x6b\x6a\xfe\x1d\x2a\x0d\xf1\xcc\xc7\x0a\xed\xee\ -\x2c\x45\x3b\xd7\x4e\xd4\x7e\xd0\xdf\xff\xf6\xac\xdf\x3d\x4b\xb6\ -\x00\x80\xc8\x9e\x4c\x13\x8e\xf6\x03\x21\xd7\x68\xd8\xa9\x70\xb6\ -\x64\x0f\xb7\x8d\x03\xd4\x6f\x4b\x05\x1f\x5f\x55\xd3\x23\xd0\xe2\ -\xba\x4e\x05\x79\xff\x4a\x4f\xb2\xb3\x54\x1d\x4b\xba\x00\x80\x48\ -\x22\xbd\x01\xe5\x3c\x50\x5b\x7c\xae\x70\x1d\xa5\x09\x2a\xef\x88\ -\x93\x3f\x8d\xf2\x9a\xeb\xd6\x29\x47\x74\x7b\xb6\xfb\xc0\x40\x29\ -\xfb\x95\x7c\x01\x00\xe1\xd8\x97\x75\x22\xce\x77\xc0\xba\x87\xbc\ -\xe5\x4e\xc1\x61\x73\xee\xc8\xfe\x4b\xa5\xec\x05\x65\x5a\x00\x40\ -\x38\xd6\xb3\x52\x24\x7f\x06\x78\xf5\x41\xd7\x29\x5c\xd7\x40\xe0\ -\xcd\x5c\x57\xeb\x8d\x72\xf4\xf2\xf5\x5f\xe0\x41\x7e\x1d\x3b\x97\ -\xaf\x5e\x1b\xfd\x26\x58\x15\xaa\x03\xd6\x2f\x78\x91\x70\x11\x9d\ -\x7e\x3d\xd7\xfd\xde\x2f\xe5\xea\x55\xb6\x4f\xc0\x3f\x54\x22\x89\ -\x74\x0a\x95\x94\x6b\x70\x7a\x59\xd5\xcc\xce\x91\x8e\x83\xbf\x97\ -\xb3\xcd\x12\x2c\x60\x4e\x43\x22\xdd\xa7\xca\x2e\x40\x81\xcf\x47\ -\x57\x8f\x7f\x44\x7b\x7b\x61\xa9\xfa\x2c\x89\xc6\x54\xaa\xa2\xb1\ -\xe5\xeb\xc7\x96\xba\x87\x31\xc6\x18\x63\x8c\x31\xc6\x18\x63\x8c\ -\x31\xc6\x18\xf3\x88\xf8\x13\xba\x50\xdf\xc1\x6b\x55\xb9\xde\x00\ -\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xc4\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x76\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\xc1\x0d\x82\x40\x14\x04\xd0\x59\x8b\x30\x36\x62\x23\xb6\xc0\ -\xc1\x70\xb2\x17\x2f\x84\x46\xa8\x82\x42\x88\x4d\xac\x57\x43\xf6\ -\x0a\x24\xf2\xde\x71\xf2\x0f\xf3\x27\x01\x00\x00\x00\x00\x00\x00\ -\xce\xa0\xac\x83\xfb\xf3\xfd\x48\x32\xd4\xe4\x7a\x40\x9f\x2d\x2d\ -\x49\xed\xe6\xf1\x35\xfd\x86\x97\xc6\xe1\x3f\x3e\x9f\x24\xb7\xa4\ -\x0c\xeb\xb0\x35\xc0\xa9\xb4\x06\xe8\x4b\xf2\xd9\xbd\xc9\xf6\x96\ -\xa4\xf6\x47\x97\x00\x00\x00\x00\x00\x00\x00\x00\xf6\xf7\x05\x16\ -\xa6\x0e\x08\x70\x11\x84\x99\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x00\xd6\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x88\x49\x44\x41\x54\x78\x9c\xed\ -\xd7\xb1\x0d\xc2\x40\x10\x04\xc0\x7d\x8a\x40\x14\x44\x05\x88\x0e\ -\x20\x71\x45\x4e\x68\x81\x94\xc4\x0d\x59\x34\xf1\xa4\xc8\x2f\x42\ -\xeb\x91\x3d\x13\xae\x2e\xd8\xbb\xec\x12\x00\x00\x00\x00\x00\xf6\ -\xa3\x2c\x83\xf3\xf5\x7e\x29\x35\x63\x92\x63\x87\x3e\xab\x29\xc9\ -\x5c\x93\xdb\xf4\x7c\xbc\xbe\xf3\x43\x33\xb8\xc1\xe5\x93\xa4\x26\ -\xa7\x24\xe3\x32\x6f\x0e\xb0\x37\xcd\x01\x6a\xc9\x90\xe4\xdd\xa1\ -\xcb\xaa\x4a\x32\x27\x19\x7a\xf7\x00\x00\xfe\x87\x5f\xa0\x19\xdc\ -\xe0\xf2\x89\x5f\xe0\x27\xbf\x00\x00\x00\x00\x00\x00\x00\x3b\xf1\ -\x01\xd7\x53\x1e\x0f\x14\xfc\xaf\x10\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x02\xc4\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\x76\x49\x44\x41\x54\x78\x9c\xed\ -\x9a\x3d\x6f\xd3\x40\x1c\x87\x9f\x4b\xa8\xca\x02\x4b\x78\x59\x6a\ -\xe7\xfc\x39\xf8\x12\x2c\x54\x0d\x2d\xac\x74\x60\x65\x63\xe5\x1b\ -\x80\xc4\xca\x4b\x0b\x82\x01\xf1\x3d\xbc\x31\x66\x70\xed\x66\x43\ -\x48\x48\x2c\xa8\x52\x7b\x2c\x11\x32\x87\x9d\x36\xf6\xdd\xf9\xce\ -\xf1\x6f\xb3\xfd\xcf\x4f\xf7\x3c\x8a\x9d\xe8\x64\x18\x32\x64\xc8\ -\x26\x47\x74\xbd\x00\xdb\xc9\x8a\xe2\xbe\x50\xe2\x05\xf0\x73\x3c\ -\xe2\x30\x8a\xa2\x6f\xe5\xeb\xd7\x3a\x5a\x97\x93\x64\x45\xb1\x27\ -\x94\x38\x02\x46\x00\xe7\x17\xbc\x06\xee\x95\x67\x46\x5d\x2c\xcc\ -\x45\x74\xf8\x65\x6e\xea\x73\xbd\x14\x50\x03\x7f\xae\x84\x7a\xae\ -\xcf\xf6\xee\x16\xa8\x83\x17\x88\x99\x8c\xa3\xaf\xfa\x7c\xaf\x1e\ -\x82\xab\xe0\xa7\xd3\x9d\xcf\x55\x9f\xe9\x8d\x80\x26\xf0\xd0\x13\ -\x01\x4d\xe1\xa1\x07\x02\xda\xc0\x43\xe0\x02\xda\xc2\x43\xc0\x02\ -\x4c\xc0\x43\xa0\x02\x4c\xc1\x43\x80\x02\x4c\xc2\x43\x60\x02\x4c\ -\xc3\x43\x40\x02\x6c\xc0\x43\x20\x02\x6c\xc1\x43\x00\x02\x6c\xc2\ -\x83\xe7\x02\x6c\xc3\x83\xc7\x02\x5c\xc0\x83\xa7\x02\x5c\xc1\x83\ -\x87\x02\x4c\xc3\xe7\xf9\xe2\x81\x52\xea\xd5\xf2\xf0\x89\x94\xd1\ -\x97\xf2\x75\xaf\x04\x98\x86\xff\xaf\x4f\xf1\x5d\xca\xe8\x4e\x79\ -\xc6\x9b\x2d\x31\xeb\xf0\x35\xf1\x42\x80\x23\xf8\x0b\x21\xc4\x53\ -\x7d\xb6\x73\x01\xae\xe0\x51\x3c\x9e\x4e\x77\x3e\xe9\xf3\x9d\x3e\ -\x03\x5c\xc2\x4b\x19\x1d\x55\x7d\xa6\x33\x01\x3e\xc0\x43\x47\x02\ -\x7c\x81\x87\x0e\x04\xf8\x04\x0f\x8e\x05\xf8\x06\x0f\x0e\x05\xf8\ -\x08\x0f\x8e\x04\x38\x84\x7f\x24\x65\x74\xbc\x4e\x97\x75\x01\x3e\ -\xc3\x83\x65\x01\xbe\xc3\x83\x45\x01\x21\xc0\x83\x25\x01\xa1\xc0\ -\x83\x05\x01\x21\xc1\x83\x61\x01\xa1\xc1\x83\x41\x01\x21\xc2\x83\ -\x21\x01\xa1\xc2\x83\x01\x01\xae\xe0\x95\x50\x07\x49\x1c\x7f\x58\ -\xb7\x2f\xcf\x17\xbb\x4a\xa9\x97\xcb\x43\xb3\x7b\x82\xfe\xc3\x9f\ -\x1e\x28\x78\xf3\xb7\xcf\xe4\x9e\x60\x70\xf0\x35\x69\x24\xc0\x77\ -\xf8\x93\x93\xd3\xfd\x0a\x78\x33\x7b\x82\x21\xc0\x23\x78\xab\xf7\ -\x19\xd9\x13\x0c\x19\xbe\xf5\x9e\x60\x00\xf0\x0f\x11\xbc\xd3\xfb\ -\x2e\xfb\xe9\xbc\x92\x80\xbe\xc2\xc3\x15\x04\x38\x84\xdf\x4f\xe2\ -\xf8\xe3\xba\x7d\x6d\xe0\xe1\x12\x01\x7d\x87\x87\x15\x02\x7c\x87\ -\xcf\x8a\x62\x26\x94\x78\x5f\xd1\xb7\xd6\x6d\x54\x29\x60\x53\xe0\ -\x01\xc6\xfa\x89\x3c\x5f\xec\x02\xc7\x18\x82\xaf\xe9\x6b\x0c\xbf\ -\xa2\xaf\xd1\x03\xf4\x9f\x6f\x40\x9a\xa6\x5b\xb7\x6e\xdf\xfd\x01\ -\xdc\x28\x9d\x6e\x0c\x5f\xd3\xd7\x18\xde\x74\x1f\x68\xff\x04\x27\ -\x93\xc9\x18\xd8\x2e\x9d\x6a\xf5\x5a\x4a\x45\x5f\xab\xc5\x9a\xee\ -\x03\x4d\x40\x92\x24\xbf\x05\x3c\x03\xce\x80\x5f\x02\xb1\xd7\xe6\ -\x9d\x9c\x8a\xbe\x59\x9b\xc5\x9a\xee\xab\xcd\x7c\x3e\xdf\x4e\xd3\ -\x74\xcb\xd7\xbe\x2c\xcb\xae\x9b\xec\x1b\x32\x64\x83\xf3\x07\x17\ -\xa8\x1d\x6f\x59\x60\x0c\x9b\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x0a\xf4\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x0a\xa6\x49\x44\x41\x54\x78\x9c\xed\ -\x5b\x7b\x70\x54\xd5\x19\xff\x7d\xf7\xee\x6e\x60\x93\x08\x64\x11\ -\x83\xd2\x91\xd8\x96\xd1\x58\x98\x21\xbb\x0b\x52\x35\x22\xda\xd1\ -\x5a\xc5\x07\xae\xf5\x31\x28\x51\xd8\x4d\x80\x2c\xc2\x54\x5b\x9d\ -\xa9\x4b\xac\x76\xb4\x6a\x08\xbb\x60\xdc\x08\x18\x41\xa6\xad\x99\ -\x51\xa7\x3a\x8a\x4c\xb5\xa1\xd4\x22\x64\x03\x96\xfa\xc0\xf1\x11\ -\x1f\x34\x90\x4a\xc2\x23\x12\xb2\xd9\xdd\xf3\xf5\x8f\x20\xdc\x7b\ -\xf7\xee\xbd\x77\x93\x5d\xa6\xd3\xf2\xfb\x6f\xbf\xf3\x3b\xdf\xf9\ -\x9d\xef\x9e\x3d\xf7\x3c\xbe\x0b\x9c\xc6\x69\x9c\xc6\xff\x33\xe8\ -\x54\x34\x32\xb5\x2a\x7c\xa6\x5c\x40\x95\x80\x98\x0c\xa6\xf3\x41\ -\x38\x8f\x19\xa3\x09\x38\x03\x80\x0c\xd0\x11\x00\x47\xc0\xfc\x15\ -\x08\x1f\x01\xf8\x50\x4a\xd1\xd6\x1d\x6b\x6a\x3b\xf2\xad\x2d\x6f\ -\x01\x70\xfb\xc3\xdf\x97\x08\xf3\x98\x31\x1b\x84\x29\x43\x74\xd3\ -\xc1\xe0\x37\x24\xc1\xcd\x6d\xcf\x2e\x89\x01\xc4\x39\x15\x89\x9c\ -\x07\x80\xc9\x1b\x08\x5f\xc5\xa0\xfb\x01\x5c\x9e\x5b\xdf\x78\x9f\ -\x40\xf5\x82\x1d\x2f\xb4\x37\x05\x12\xb9\x72\x9a\xb3\x00\xb8\xfd\ -\x2b\x2f\x27\xa2\xdf\x01\xf0\xe4\xca\xa7\x1e\x18\xf8\x02\xcc\xcb\ -\xdb\x9b\x82\xeb\x73\x31\x22\x86\x1d\x80\xe9\xf3\x1b\xce\x4a\xca\ -\xd2\x53\x04\xdc\x61\x40\x13\x04\xbc\x03\xe2\x56\x21\xa4\x3d\x40\ -\xea\x33\x1b\x51\x8f\x90\x6d\xbd\xc9\x63\xa9\x94\x3c\x22\x59\x0c\ -\xb6\x8d\x22\x46\x99\x60\x9a\x44\xe0\x19\x20\xfc\x04\xc0\x48\x03\ -\xe1\x5b\x21\xa4\x9a\xb6\x67\x17\x7f\x30\x1c\xfd\xc3\x0a\x80\xa7\ -\x3a\x3c\x0d\x8c\x57\x00\x8c\xd7\x29\xee\x05\xf0\x3a\x11\x5e\x25\ -\x59\xda\xb4\x63\xf5\xe2\xee\x6c\x7c\xcf\x58\x5a\x3f\x72\xe0\xa8\ -\x6d\x16\x01\xd7\x81\x30\x3b\x43\x1b\xfd\x00\xee\x8e\x45\x83\xbf\ -\xcf\x5e\xfd\x20\x86\x1c\x00\xb7\x3f\x72\x3b\x11\xaf\x03\x50\x90\ -\x26\x8a\x39\x1c\x97\xed\x8f\xfd\xb3\x71\xe1\xc1\xa1\xfa\x57\xa2\ -\xdc\x17\x72\x38\xc7\x94\x2c\x20\xa2\x87\x18\x18\x97\x46\x60\x7a\ -\x34\x36\xfe\xc0\x43\xa8\xab\x13\xd9\xfa\xce\x3e\x00\xa1\x90\xe4\ -\xde\x3f\xf6\x11\x02\x3f\xa0\x29\x11\x44\x58\x27\x25\x51\xb7\x7d\ -\x4d\x70\x6f\xd6\x7e\x2d\xe0\xe2\xbb\x1f\x2f\x8e\xdb\x9c\xcb\x40\ -\xfc\x0b\x00\x45\x9a\xe2\x57\xfa\x64\x79\xee\x87\x4f\x2f\xfa\x36\ -\x1b\x9f\xd9\x05\x20\x14\x92\x3c\xfb\xc6\x6e\x04\xf1\xad\x2a\x3b\ -\xa3\x13\x12\x6e\x8c\x3d\x13\xdc\x91\x95\xbf\x21\x62\xfa\xfc\xf0\ -\x84\x94\x8c\x97\x91\x3e\xe1\xee\x92\x1d\x98\xb9\x3d\x12\x3c\x62\ -\xd5\x97\x94\x4d\xc3\xde\xae\x92\xe5\xda\xce\x13\xf0\x2e\x23\xe5\ -\x39\x55\x9d\x07\x80\xed\x6b\x82\x7b\xed\xce\x64\x25\x03\x1b\x35\ -\x45\x53\xc5\x00\x6f\xf4\xf9\x5e\x94\xad\xfa\xb2\x4c\xf4\x06\x22\ -\x3f\x67\x20\xa2\xb4\x11\xd1\xf3\x85\xf1\x62\xdf\xb6\xb5\x35\x87\ -\xac\xfa\xc9\x15\xf6\xbe\xfb\x66\x72\x5f\xfb\xeb\x2f\x9f\xed\x6d\ -\xeb\x03\x70\x25\x4e\x8c\x66\x9a\x74\x68\x44\xef\x88\xce\xf6\x4d\ -\x7f\xb6\xe2\xc7\xd2\x5f\x60\x5a\x20\xe2\x11\xe0\xad\x00\x46\x9c\ -\xb4\xf2\x0b\xb1\x68\xf0\xce\x7c\xac\xce\xb2\x85\xc7\x1f\xbe\x17\ -\x84\x15\x1a\xf3\x5d\xb1\x68\x70\xbd\x59\x5d\xd3\x00\x4c\x5b\xb4\ -\xca\x95\x4a\xf2\x3f\x08\x7c\x8e\xc2\xbc\xa3\x28\x5e\x7c\x59\x6b\ -\x73\x55\x7f\x36\x42\x2b\x16\xae\xb8\x40\x4a\xca\x37\x1e\x5f\x1a\ -\x4f\x00\x63\x02\x88\x52\x00\xf6\x12\x89\xbd\x42\xd0\x4e\x59\xd0\ -\x4b\xd9\xef\x01\x98\x3c\x81\xf0\x5a\x80\xaa\x14\xc6\x01\x66\x69\ -\x46\x7b\xd3\xe2\x9d\x46\x35\x4d\x03\xe0\xf1\x87\xd7\x82\x70\xf7\ -\xc9\xb6\xd0\x99\x72\x90\x77\xd7\xaa\xda\x4e\x2b\xd2\xca\x7d\x21\ -\x47\x61\xc9\xd8\x1a\x06\x57\x03\x38\xdf\x4a\x1d\x00\xbb\x88\x10\ -\x9e\xd8\x5d\xba\xa1\xa5\xe5\x96\x94\x95\x0a\x3f\xa8\x0d\x17\x8c\ -\x4e\xe0\x6d\x30\x7e\xac\x30\xef\x2c\x2a\xed\x9e\xde\x5a\x57\x97\ -\xcc\x54\xcf\x70\x12\x74\xfb\x1b\x2e\x51\x75\x1e\x60\x21\x63\x8e\ -\xd5\xce\xbb\xfd\x91\x1b\x9c\x63\x5c\x1f\x30\xb8\x01\xd6\x3b\x0f\ -\x00\x53\x99\xf1\x5c\x47\x49\x57\xac\xa2\x3a\x32\xcb\x4a\x85\x4f\ -\x23\xc1\xb8\x9c\x14\x37\x01\x38\xa0\x30\x57\xf4\xee\x73\x2d\x34\ -\xaa\x67\x30\x02\x98\x3c\x81\xc8\x5f\x01\x5c\xa2\xb0\xbd\x10\x8b\ -\x2e\x99\x6b\x26\xc6\xed\x8f\xda\x41\xfd\x0d\x04\x32\x6c\xdc\x32\ -\x88\xeb\x62\x67\xf5\x3c\x6c\x65\xa1\xa3\x33\x1f\x1c\x18\xe8\x8b\ -\x4f\xdc\xbd\xe1\xbe\xa3\x7a\xfc\x8c\x23\xc0\xbb\x20\x52\x09\x55\ -\xe7\x91\x80\x94\x0a\x99\x09\x98\x5c\xf3\xf4\x18\xa2\xf8\x1b\x39\ -\xeb\x3c\x00\x30\x85\x3c\xfb\x5d\x7f\x74\xfb\xa3\x4e\x33\x6a\xd1\ -\x40\xf1\x33\x00\xbe\x52\x98\xc6\xda\x9d\x8e\x40\x26\x7e\xc6\x00\ -\xb0\x84\xfb\xd4\x06\x44\x63\x8d\xcb\x3e\x37\x6a\xbc\xdc\x17\x72\ -\x14\x88\xd4\x2b\x00\xae\x30\x13\x3a\x04\xdc\x4c\xe8\x5f\x8f\x50\ -\xc8\xf0\x6f\xdb\xda\x5c\xd5\x4f\x04\xcd\x83\x92\x96\x65\x5a\x1b\ -\xe8\x3a\xf3\x2e\x5c\x5d\x0a\xe0\x6a\x85\x29\x21\x0b\xf1\x88\xb1\ -\x3e\xa6\x42\x97\x6b\x35\xc0\x95\xc6\xbc\x61\x80\x68\x8e\x7b\xbf\ -\xcb\x74\x14\x4e\xec\x2e\xdd\xc0\xc0\x27\x27\xaa\x81\xcf\xf9\xcc\ -\xd5\x75\xa5\x1e\x57\x37\x00\x22\x95\xbc\x1d\x8a\x45\x12\x01\x6f\ -\x6f\x5f\x73\x6f\x97\x51\xa3\xde\xc0\xaa\x3b\x98\x31\xdf\x4c\xdc\ -\x70\x41\xc0\x43\x9e\x05\x61\xdd\xce\x7c\x87\x96\x96\x5b\x52\x44\ -\x68\x51\xda\x24\xe6\xbb\xf4\xb8\xba\x01\x20\xd0\x75\x1a\xcb\x9f\ -\x8c\x1a\x74\xfb\xa3\x4e\x01\x3c\x66\xc4\xc9\x29\x24\xd4\x9b\x2d\ -\x77\x59\x08\xad\xe6\x6b\xf4\xea\xa4\x05\x60\xca\xdc\x27\x0a\x01\ -\xd5\xbb\x14\x82\x53\xaf\x19\x0a\xa2\xf8\x32\xcd\x42\x29\xdf\x98\ -\xdc\x51\xd2\x35\xcf\x88\xd0\x3e\xfe\x60\x1b\x00\xe5\xa8\x1d\xd5\ -\xe1\xda\xef\xd6\xf2\xd2\x02\x50\xe0\x74\x5c\x04\xc0\x71\xd2\x42\ -\xef\xb5\x37\xdd\xfb\x95\x96\xf7\x1d\x7c\xbe\x17\x65\x22\x04\xcd\ -\x35\xe7\x1a\xbc\xc4\xb0\xb8\xae\x4e\x00\xac\x7a\x70\xcc\xe9\xe7\ -\x94\x3a\x7f\x01\xe9\x47\x1a\xc3\x56\xa3\x76\x3a\x5c\x5d\x97\x82\ -\x71\xa6\xa1\x98\xfc\x60\xf2\xf4\xc0\xca\x1f\x1a\x11\x98\xd5\xda\ -\x89\x71\xa1\x96\x93\x16\x00\x66\xbe\x40\xf5\x1b\xe2\x13\x2d\x47\ -\x53\xe1\x66\xc3\xf2\x3c\x22\xc9\xd2\x1c\xa3\x72\x89\xa1\xd6\x4e\ -\xb8\x20\x8d\xa3\x35\x10\x61\xa2\xca\xc0\x64\xf8\xee\x07\x28\xaf\ -\xa7\xc0\x86\x2d\x13\xa7\xfd\xa7\x55\xb0\xdb\xb4\xda\xcb\xb4\x94\ -\xf4\x11\x40\x28\x56\x35\x22\x91\xc9\x5e\xff\x94\x4e\x7e\x2a\x10\ -\x30\xc1\xa8\xbc\xb0\xcf\xa9\xd5\x5e\xac\xe5\xa4\xcf\x01\xac\x26\ -\x49\xcc\x99\xcf\xd8\x06\x57\x65\x7a\xa7\xb5\xa7\x04\x6c\x12\x80\ -\xd6\xe6\x79\x71\x00\xca\x9d\xa0\xa3\xdc\x17\x72\x28\x39\x7a\xeb\ -\x00\xd5\x06\x29\x29\x89\x8c\x07\x1e\x33\x07\xeb\x67\x75\xac\x96\ -\x63\xd8\x87\xeb\x40\x4f\x7c\xaf\x8a\xc0\x72\xda\xb0\xf9\x0e\xc7\ -\xf7\xd9\x86\x2b\xc4\xbc\x82\x61\x78\xfa\x3c\x73\x5e\x73\x01\x00\ -\x9b\xc2\x34\xf0\x61\x4b\xdd\x80\x92\x93\x3e\x09\x02\xaa\x13\x55\ -\x16\x3c\xda\x44\xc4\xbf\x4c\x85\xe6\x0b\x64\x1c\x80\x63\xb6\xc3\ -\xa3\x34\xa6\x5e\x2d\x27\x7d\x12\x04\x7d\xa9\x6a\x43\x4a\x9f\x39\ -\xd5\xe5\xf4\xbe\x51\x79\x5e\xc1\xc6\x6d\xb3\x6c\x3b\x4f\x6d\xc0\ -\x17\x5a\x8e\xce\x24\xc8\x1f\x29\x7f\x12\x60\xbc\xd8\x20\xbc\x64\ -\x54\x9e\x4f\x30\xc8\xb0\x6d\x01\xa1\xd2\xce\x84\x3d\x5a\x4e\x7a\ -\x00\x48\x52\x5d\x36\x32\xab\x0e\x45\xd2\x50\x74\xac\x68\x33\x80\ -\xac\x6e\x63\x72\x02\xc6\x97\xed\x4d\x8b\x76\x19\x53\x34\xda\x75\ -\x46\x4c\x5a\x00\xfa\x64\xda\x06\x40\x79\xff\x5e\x31\x7d\x7e\x38\ -\xe3\xeb\xa6\xb5\xb9\xaa\x1f\x8c\x66\x33\xbd\x79\x40\x93\xe1\x91\ -\x7c\x28\x24\x11\x70\xad\xd2\xc4\x32\xb7\x6a\x69\x69\x01\x18\xbc\ -\x5b\xa3\x6d\x4a\x5b\x52\xa6\x6b\xb5\x3c\x25\x52\x09\x3c\x0c\xe0\ -\xb0\x89\xe0\x5c\xe2\x6b\x7b\x61\x52\x7b\x0f\xa0\x82\xb7\x73\x8c\ -\x1b\xea\x35\xca\x91\x33\xc6\x75\xc7\xb4\x3c\xfd\x77\x38\xab\x77\ -\x51\x44\x3c\xdb\xa8\xb1\x5d\xcf\x05\xbf\x21\xb0\xc9\x89\x51\xee\ -\x40\xa0\x07\xb7\xad\x58\x76\xcc\x90\x24\x49\x2a\xcd\x0c\x6c\xd2\ -\x3b\x1e\xd7\x0d\x40\xca\x41\x1b\x01\x9c\x3c\x81\x65\xcc\x9a\x5a\ -\x15\x36\xdc\xf1\x15\x96\xf6\x34\x10\xf0\xa6\xa1\xa8\x5c\x80\xb1\ -\xa1\x2d\xba\x58\x7b\x27\xa8\x46\x28\x24\x31\xa0\xda\xa4\x11\xf8\ -\x79\x3d\xaa\x6e\x00\x8e\x9f\xfb\x6f\x56\x98\x0a\x64\x7b\xda\x75\ -\xb8\x0a\xad\x75\x75\xc9\x44\x3c\x75\x2b\x80\x8f\x0d\xc5\x0d\x03\ -\x04\xbc\x5b\x34\x50\xec\x37\xbb\x8e\xf3\x76\xb9\x6e\x83\xfa\x1e\ -\x62\x7f\x51\x69\xcf\x66\x3d\x6e\xc6\x65\x2c\x81\x9f\x54\x1b\x68\ -\xd1\xd4\x45\xab\xce\x35\x6a\xf8\xbd\xe6\xa5\x87\x20\x25\xaf\x41\ -\x7e\x82\x10\x93\x52\xe2\x06\xb3\xeb\xb8\x72\x5f\xc8\xc1\x8c\xdf\ -\xa8\x8c\x44\x2b\x32\xdd\x0e\x65\x0c\x40\x5b\x34\xf8\x36\x00\xe5\ -\x64\xe8\x90\x92\x62\xb9\xa9\xca\xc6\x65\x9f\x27\xe3\xa9\x8b\xa0\ -\x1e\x41\xc3\x03\xd3\x1f\xec\xce\x64\xa5\xd9\xc1\x2c\x00\x38\x5d\ -\x2e\x3f\xd4\xdb\xde\x9e\x82\x81\xbe\xc6\x4c\x7c\x83\x8d\x0c\x31\ -\x88\x1e\x54\x59\x80\x3b\x2b\x6a\x56\x1a\xef\xc1\x31\x38\x12\x8a\ -\x4a\xbb\x7f\xc6\xc0\xaf\xa0\xb3\xfc\xcc\x02\x07\x18\x54\x13\x6b\ -\x5a\x7c\xbb\xe9\xa4\x07\xc0\xed\x7f\x72\x2c\x31\x7e\xad\xb4\x31\ -\xe3\xb7\xef\xac\xfb\x65\x46\x0d\x56\x2e\x47\xd7\x83\xa0\xbc\x0e\ -\xfb\x5a\x4e\x09\xaf\x95\xa7\x01\x00\x53\xaa\x1b\xc7\x15\x20\xb1\ -\x9c\x19\x77\x01\x30\xbd\xd9\x39\x8e\xc3\x44\xdc\x28\xc4\x88\xc7\ -\xda\x9b\x02\x96\x5e\xaf\xe5\xbe\x90\xc3\xe9\x72\x6d\x06\xe3\xb2\ -\x13\x46\xc6\x6e\x46\x81\xc7\x28\xaf\xd0\x34\x00\x53\xaa\x1b\xc7\ -\x39\x38\xb1\x1b\xc0\x59\x8a\x5a\x7f\x3f\x64\xc7\xac\x4f\x23\xc1\ -\xb8\x15\x71\xc0\xe0\xd1\xb9\x44\xf1\xab\x41\x3c\x87\x99\x26\x03\ -\x38\x07\x40\xc9\x71\x7f\xdf\x30\xa3\x93\xc0\x3b\x21\xa4\x96\xbe\ -\x43\x07\xde\xd2\xee\xda\xcc\xe0\x09\xac\x6c\x04\xa8\x5a\x61\x4a\ -\x80\x70\x89\x59\xe6\x8a\xa5\x04\x89\x8a\x9a\xf0\x45\x92\x40\x2b\ -\x94\x19\x61\x8c\x75\xb1\xa6\xda\xf9\xc3\x49\x90\x98\xb1\xb4\x7e\ -\xe4\x37\x49\x9b\xc8\x26\x90\x7a\xf0\x06\x22\x0b\x19\xbc\x5a\x6d\ -\xa5\xf9\xb1\x68\xed\x5a\xb3\xba\x96\x93\xa4\x3c\xd5\x2b\xe7\x82\ -\x49\x93\x71\x41\x4d\x7d\x3d\x07\x6a\xb3\x7d\x5a\xb9\x03\x93\xdb\ -\x1f\xa9\xa5\xc1\xdb\x60\xe5\x7c\xd6\x10\x8b\x06\x97\x5a\xf1\x60\ -\x39\x47\xa8\x33\xb6\x69\xf7\xd9\xee\xab\x9d\x20\xba\x58\x61\x76\ -\xdb\x9d\xce\xca\xf1\x15\x57\xbc\xb6\xaf\x7d\x73\x9f\x55\x5f\xb9\ -\x40\xb9\x2f\xe4\x38\xf7\xd2\xdd\x51\x1a\x9c\xa8\x4f\x3c\x48\x02\ -\xde\x2c\x2a\xed\xae\xfa\x62\xcb\x16\x4b\x39\x83\x59\x1d\x67\x95\ -\x1d\x1c\xff\x20\x83\x5e\x56\x19\x19\x97\x81\x1c\x6d\x6e\x7f\x64\ -\x72\x36\xbe\x86\x83\x29\xd5\x8d\xe3\x9c\x25\xae\xb7\x00\xba\x47\ -\x53\xf4\x41\x22\x9e\xba\xd5\x28\x23\x44\x8b\xac\x13\x25\x7d\xbe\ -\x17\xe5\x8e\x31\xfb\x9e\x00\x91\x76\x88\x25\x88\xd0\x18\x87\xfd\ -\xd1\xdd\xcf\xd4\xfc\x3b\x5b\xbf\x56\x30\x63\x69\xfd\xc8\xc4\x51\ -\xdb\x62\x10\x1e\x00\x30\x46\x55\x48\x78\x83\x45\xc1\x6d\x56\xdf\ -\x1a\x27\xab\x0d\x11\x9e\x40\xe4\x1e\x80\x1b\x91\x7e\x30\xf9\x2d\ -\x88\x9f\x92\xed\x54\x9f\x4d\xc2\xa2\x11\x66\x86\x42\xb6\xde\x7d\ -\x25\xf3\x40\xd2\xf2\x0c\x77\x90\xf5\x65\x3d\xa5\xf7\x5b\xcd\x27\ -\x52\x62\x58\xc9\xd2\xde\x40\x43\x25\x43\x7a\x09\x80\x4b\xa7\xf8\ -\x20\x80\x57\x01\xbc\x2a\x3b\xb0\x39\xdb\x60\x94\xfb\x42\x0e\xe7\ -\x68\x57\x25\xc9\xb8\x8e\x05\xae\x07\x41\x6f\x19\x9e\x00\xa8\xc6\ -\xca\x6c\x9f\x09\xc3\x4e\x97\xf7\x2e\x5c\xfd\x3d\x4e\xa5\x1a\x00\ -\xdc\x64\x40\x4b\x80\xb0\x05\x02\x7f\x81\x44\x1f\x4b\xcc\x9f\xb2\ -\x2c\xf7\xf4\x33\x7d\xeb\xb4\x25\x53\x52\x22\x59\x2c\xd8\x36\x2a\ -\xc9\x28\x23\x89\x26\x81\xc5\x0c\x80\xae\xc2\xe0\x27\x35\x99\x94\ -\xb7\x09\xe2\x9a\x9d\x8d\x4b\xda\x87\xa3\x3f\x67\x1f\x4c\x78\x16\ -\x44\x7e\x0a\x89\x1f\x07\x90\xdf\xc9\x70\x30\x2f\xf9\xe1\xb2\xee\ -\xd2\x35\x43\x19\xf2\x5a\xe4\xf6\x93\x99\x50\x48\x9a\xd6\x55\x72\ -\xbd\x00\x3d\x00\x86\x37\xa7\xbe\x41\x9f\x83\x45\x7d\xd1\xc0\x19\ -\x6b\xb3\x4d\xd0\x34\xf4\x9a\x2b\x47\x5a\x78\x17\xac\xba\x50\x48\ -\x3c\x8f\xc0\xb3\x01\x4c\x1a\xa2\x9b\xfd\x60\xbc\x4e\x24\x9e\x6f\ -\x2b\x3d\xf8\xb7\xa1\x7c\x0f\x60\x86\x53\xf2\xd9\xdc\xf1\x79\xe2\ -\x72\x30\x5f\x08\xd0\xf9\x20\x94\x01\x18\x85\xc1\xff\xb8\x8d\x41\ -\x87\x89\x71\x04\xc4\x5f\x13\x61\x8f\x10\xd8\x63\x23\x6c\xd9\x1e\ -\xad\xfd\xe8\xbf\x21\x17\xf9\x34\x4e\xe3\x34\xfe\x77\xf1\x1f\x1c\ -\x6b\xc6\x54\xc2\x9c\x88\xf8\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x00\x9b\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x4d\x49\x44\x41\x54\x58\x85\xed\ -\xd7\xc1\x09\x00\x20\x08\x46\x61\x8b\x46\x72\x80\xb6\x71\x9f\xe6\ -\x09\x5c\xad\x0d\x32\xa5\xe3\x7b\xc7\x1f\x84\xef\xaa\x08\x25\x53\ -\x5b\xae\xb6\xfc\x75\x8f\x1a\x05\xc3\x4c\xee\xd7\x7a\xe5\xe8\x67\ -\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x90\xff\x8c\ -\x9a\xec\xd4\x4e\x41\x07\x39\xb5\x09\xe5\x39\xad\x0d\x4e\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\xc7\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x79\x49\x44\x41\x54\x58\x85\xe5\ -\xd6\x31\x4e\xc3\x30\x14\xc6\xf1\xff\xb3\x9b\x72\x03\x3a\x70\x82\ -\x82\x84\xc4\xd4\xb9\xe5\x00\x48\x70\x85\x0e\xb0\x54\xdc\x20\x1c\ -\xa1\x1b\x54\xe2\x12\x88\x05\x09\xa9\x99\x91\x3a\x51\x28\x27\x60\ -\x80\x89\xb9\x21\x35\x43\x15\xa1\xb6\x69\x63\xa7\x4e\x18\xf0\x68\ -\x3f\xf9\xf7\xc9\xb6\x9e\x0c\xff\x7d\x48\x95\x58\xab\xdb\x6f\x24\ -\x5a\xdf\x81\x79\x1f\x0d\x7a\x67\x00\xaa\x52\x5c\xe9\x08\x4c\x0b\ -\x64\x2f\x9d\xaf\x55\x8a\x8b\x69\x62\xe4\x4d\xcf\x92\x93\x74\xad\ -\xf4\x2b\xc8\xc0\xdb\x4f\xb7\x97\x1f\x95\x04\xc8\xc3\x4b\x0d\x60\ -\x83\x97\x16\xc0\x16\x2f\x25\x80\x0b\xee\x3d\x80\x2b\xee\x35\x40\ -\x11\xdc\x5b\x00\x5b\xfc\xf0\xfc\x7a\xb7\x6e\xe2\x07\xe0\x6b\x34\ -\xe8\x75\xc0\x43\x27\x74\xc4\x87\xc0\x11\x50\x4f\xe7\xb7\x0a\x50\ -\x00\x3f\x00\x5e\xa6\x12\x9c\xa6\x6b\x85\xaf\x60\x0b\xfc\xf8\xf9\ -\xe6\xe2\x73\xab\x00\xbe\xf0\x42\x01\x5c\xf0\xc0\xc4\x91\xc0\x3e\ -\xf0\x3a\x95\xa0\xb3\x8c\x3b\x07\xf0\x8d\x3b\x05\x28\x03\x07\xd0\ -\x3e\xf1\x56\xb7\xdf\x10\x31\xd6\x38\x58\x9c\x80\x0b\xfe\xad\xd5\ -\xd0\x05\xcf\x0d\x50\x04\x37\x30\x89\x25\x68\x67\xe1\x4e\x9d\xb0\ -\x24\x7c\xa5\x13\x66\xfe\x09\xcb\xc0\x03\x13\x47\xcc\xaf\x67\xa1\ -\x13\xae\x3c\x42\x17\x3c\x51\x3a\x12\xd9\x8c\x67\x3c\xcc\x85\x66\ -\xa4\xb2\x36\xb5\xc5\x11\xd3\x34\x30\xa9\x25\xb3\xcc\x07\x67\xf3\ -\x30\x25\x6b\x53\x57\xdc\xa6\x6e\xdd\x09\xcd\x4f\x20\x0c\x55\xa2\ -\xd5\x63\xfe\x67\xc2\x48\x52\x53\xf7\x79\xf8\x72\xdd\x3a\xfc\x37\ -\xc0\x7c\xec\x00\xe3\x8d\x3f\x99\xf0\x4a\x8c\xa1\x0e\x8c\xd7\xe3\ -\xab\x75\x36\xfd\x00\xc2\x50\x81\xb1\x68\xcd\x46\xfc\xd6\xfd\xf1\ -\xf8\x01\x9a\x8b\x01\xab\xe8\x4a\xa0\x68\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x2a\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xdc\x49\x44\x41\x54\x58\x85\xed\ -\x95\xbf\x6b\x53\x51\x14\xc7\x3f\xdf\x9b\x68\x4a\x07\xab\x06\x2a\ -\xb5\xab\x2e\x82\x54\x92\x06\x51\xe9\x6c\x8b\x9d\x44\x07\x51\x70\ -\x32\x3f\x14\x2b\xfe\x05\x21\x9b\x93\xc5\x18\x85\x66\xea\xe6\xe2\ -\xa0\xa0\x54\xbb\x05\xec\x52\x1a\xd4\xbf\x40\xa7\xaa\x83\xe2\x24\ -\xb4\x4d\xee\x71\xc8\xb3\xa9\x69\xaa\xcd\x6b\xc4\xe5\x7d\xe0\x0d\ -\xef\xde\x7b\xce\xf9\x70\xee\xbb\xef\x42\x44\x44\x44\xc4\x7f\x46\ -\x61\x03\xcf\xe4\xef\x8f\xae\x5b\xfc\xa5\x60\xac\xb9\x4f\xa3\x6f\ -\x2b\xb7\x57\xc3\xe4\x71\x61\x82\x4e\xe7\x1e\x1c\x5f\xb7\xf8\x1b\ -\xc1\x18\x80\xdb\xb0\xa5\xd4\xcd\x47\xc7\xc2\xe4\xea\xb9\x03\x99\ -\x1b\xb3\xa7\x70\xb1\xd7\x06\xc3\x1d\x53\x5f\x1c\x9c\x5f\x9e\x9b\ -\x79\xdf\x4b\xbe\x9e\x3a\x90\x2a\x94\x27\xcc\xc5\x6a\x06\xc3\x18\ -\x06\x34\x5b\x8f\x0c\x38\xe2\xa1\x96\x2a\x94\x27\xfe\x89\x40\x2a\ -\x5f\x99\x76\x9e\x45\xe0\x80\x81\x21\x7c\x7b\xd6\xbc\x99\x0c\x18\ -\x72\x9e\xc5\x74\xb6\x7c\xa1\xaf\x02\x99\xdc\xc3\x6b\xce\xfc\x33\ -\x60\x00\x30\xb1\xb5\x78\x0b\xc9\x7c\xd0\x95\x01\x89\xe7\x99\x7c\ -\xf9\xea\x6e\x72\xc7\xfe\xb6\x20\x9d\x2d\xcf\x20\xaa\x81\xac\xd1\ -\xa5\x78\xdb\x02\xc3\x10\xc2\x01\x17\x47\xc6\x27\xbf\x7d\xaa\xbf\ -\x5a\x0e\x29\x60\x4a\xe7\x92\x25\x89\x7b\xc1\x80\x0f\x04\xfe\x8c\ -\x30\x13\x08\x24\x34\x75\x34\x33\xa9\xd5\x95\x85\x1a\x94\x76\x58\ -\xde\x8d\x62\xd1\x8d\x7f\x4e\x96\x81\x5b\xb4\xaa\x7a\xed\xa6\xf8\ -\x56\x7d\x4c\x42\x2e\x78\xa9\xac\x8c\x7c\xbd\x43\xa9\xb4\x7d\xeb\ -\x3a\x07\x4e\x5c\x2e\xee\x1f\x3c\x9c\x9c\x07\xae\x00\x98\xf0\xb2\ -\xde\x8a\x6f\x4a\x08\xc9\x36\xbf\xb3\x27\x66\x89\xeb\xf5\x6a\x6e\ -\x63\x47\x81\x74\x76\x6e\x50\x6e\xed\x29\xc6\x14\x06\x26\xf3\x6a\ -\x1d\xb1\xd0\xfc\xd6\x09\xb1\x60\x3e\x71\xa9\x5e\xcd\xfd\xd8\x26\ -\x70\xb2\xf0\xf8\x50\xc2\x1a\x2f\x30\xce\x06\x81\x7b\x2e\xde\x96\ -\x40\x6a\x9f\xb8\xa5\xc6\x5a\x73\xfa\xdd\xfc\xdd\xef\x00\xf1\x5f\ -\x8b\x12\xbe\xf1\x01\x18\x6a\x9b\x29\xd4\x6f\xba\x1b\x1d\xfb\x7c\ -\x2e\x9e\x88\x7f\x04\x0e\x42\xc8\xbb\x60\xef\xf4\xa5\xb1\x11\x11\ -\x11\x11\xfd\xe1\x27\x68\xea\x98\xa0\x5e\x6e\x43\xde\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x47\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xf9\x49\x44\x41\x54\x78\x9c\xed\ -\xd6\x21\x4e\xc4\x50\x14\x85\xe1\x73\x5b\xa6\x04\x04\x0a\x6c\x43\ -\x9a\x54\x92\x20\xd8\x03\x2c\x80\x75\x60\x58\x00\x61\x01\xb3\x09\ -\x3c\x92\x64\x58\x06\xba\x06\x53\x12\x32\x0e\x41\x86\x0e\xf3\x2e\ -\x96\xbc\x07\xb8\xbe\x49\xe8\xff\xc9\x73\x2b\x4e\x8f\x69\x25\x00\ -\x00\x00\x00\x00\x00\x00\x00\x00\x60\x12\xec\xaf\xa3\xbb\x9b\xa4\ -\x32\x53\x97\xb1\x04\x33\x0b\xbf\x1d\x7f\x1c\xa0\xef\xfb\xc3\xe1\ -\x73\x33\x37\xd9\xa5\xa4\xfd\xd1\xaa\xe5\xb1\x92\xf4\x50\x98\x5f\ -\xd5\x75\xfd\x12\x1f\x93\x01\xba\xae\x3b\x98\x55\x7b\x4f\x92\x1f\ -\xe7\x68\x97\x8d\x6b\x19\xc2\xfa\xa4\x69\x9a\xd7\xef\x71\x11\x3f\ -\x57\x55\xbb\xb7\xff\xee\xe5\x25\xc9\x74\x54\x94\xb3\x79\x1c\x27\ -\x03\xb8\x74\x9e\xa7\xd1\x56\x5c\xc4\x41\x32\xc0\xd4\x24\x03\x98\ -\xf4\xb8\x8d\x22\x99\x2c\xe2\x20\x19\x60\x18\x3e\x6e\x24\x7b\xce\ -\x52\x27\x27\xd7\x32\x6c\xd6\xd7\x71\x9c\x0c\xd0\xb6\xed\xdb\x4e\ -\xa9\x33\x97\xdf\x49\x7a\xcf\x52\x6e\x5c\x2b\x49\xf7\x45\xe1\xa7\ -\xf1\x17\x40\xe2\x47\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x98\ -\x8a\x2f\xe6\x4f\x38\x6a\x74\xad\x97\x2f\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xef\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xa1\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\x41\x11\x00\x20\x00\xc3\x30\x0e\x4d\x78\xc2\x0f\x86\x41\x46\ -\x78\x34\x06\xd6\xdb\x18\xd0\xda\xe7\xae\x7d\xae\x6c\x98\x72\xfc\ -\x07\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\ -\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\xd0\x3a\x40\x07\x68\ -\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\ -\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\xd0\x3a\x40\x07\x68\x1d\ -\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\ -\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\ -\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\ -\x40\xeb\x00\x1d\xa0\x75\x80\x0e\xd0\x1e\x06\x73\x04\xd7\x28\x98\ -\xcd\x67\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\x52\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x04\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\xbd\x4f\x14\x51\x14\xc5\xcf\x99\xac\x05\x6c\xa9\x1b\xbe\x7a\ -\x1b\x59\x1a\xe2\x62\x21\x35\x35\x9f\x46\x12\xb1\x93\x68\x02\x5a\ -\xc2\x5f\xa0\x35\x98\x08\xa5\x9a\x48\xc2\x67\x2c\xa9\xb1\x20\x24\ -\x34\x2c\x54\xd6\x2c\x12\xb4\xdc\xa5\x60\x9d\x63\xe1\xb2\x3b\xcc\ -\x0c\x1f\x22\xbb\x77\x37\xbc\x5f\xb5\xf7\xdd\x3b\xc9\x79\x27\xef\ -\xcd\x6c\x71\x2f\xe0\x70\x38\x6e\x33\xbc\x4a\x51\xd7\xba\x92\x4d\ -\x79\x8c\x80\x1a\x22\xd0\x29\xa1\x1d\x40\xa2\xca\xda\xfe\x95\x22\ -\x89\x9c\x80\x5d\x88\xcb\xc7\x49\x2c\xee\xf4\x31\x7f\xd9\x43\x17\ -\x1b\x20\x31\xb3\x86\x31\x42\x6f\x01\xb4\xdd\x94\xd2\x1a\x71\x20\ -\x70\x6a\xab\x1f\x9f\x41\xea\xbc\xa2\x73\x0d\xe8\x9e\xd7\x9d\x44\ -\xca\x9f\x05\x38\x5e\x1d\x7d\xb5\x42\xf3\xc5\x23\x6f\x62\x7b\x9c\ -\x27\x71\xd9\xf8\x63\x2c\x31\xb1\xea\xbf\x07\xf8\x22\x94\xc9\x4a\ -\xfa\x46\x7a\x3f\x48\xf8\x37\x2d\xf5\x7f\x90\xe0\x49\x7e\x2b\xc9\ -\xc7\x00\xd2\x95\x0c\xc7\x13\x29\x1f\x90\x5e\xc6\x9d\x84\xd8\x13\ -\x90\x59\xd5\x18\xa1\x8f\x81\xa5\x5f\x12\x27\xb7\x06\xb0\x70\xd1\ -\x71\xaa\x0b\x24\x66\x56\xf1\x94\xd4\x0c\x80\xbb\xe5\x65\xf0\xf9\ -\xd6\x00\x3f\x85\xcb\x23\x06\xfc\x7d\xe1\xe9\x3b\x2a\x77\xfe\x67\ -\x51\xec\xda\x1e\xe4\x41\xd5\x44\x57\x81\xee\x15\xb5\x25\xa8\x1d\ -\x00\xf7\x4a\x4b\xb9\xe3\x24\xef\x87\x5f\x8c\x5e\xf8\xc1\xa6\x3c\ -\x46\x10\x78\xe1\x49\x7c\xdd\x68\x9b\x07\x80\xed\x41\x1e\x10\x7c\ -\x13\x58\x6a\x6f\x2e\x60\x38\x5c\x17\x31\x00\xd4\x50\x20\xca\x6e\ -\x0d\x60\xa1\x0a\xfa\x6a\xc2\x66\x3f\xbe\x00\xc8\x9e\xc6\x82\x2e\ -\x37\x80\x40\x67\x25\xd0\x46\xdd\xdf\xf9\x8b\x20\x05\x6a\xa3\x1c\ -\x0b\x0f\xc2\x25\x11\x03\x4a\x7f\x72\x4a\x81\x77\x58\x2d\x6d\x35\ -\xe3\xec\x1e\x3a\xc2\xe9\xe8\x15\x08\x7c\x1a\xeb\xed\x53\x77\x1d\ -\x42\x7b\x88\x7c\xf6\xe3\x0c\xb8\x55\x38\x03\xac\x05\x58\xe3\x0c\ -\xb0\x16\x60\x8d\x33\xc0\x5a\x80\x35\xce\x00\x6b\x01\xd6\x38\x03\ -\xac\x05\x58\xe3\x0c\xb0\x16\x60\x8d\x33\xc0\x5a\x80\x35\xce\x00\ -\x6b\x01\xd6\x38\x03\xac\x05\x58\xe3\x0c\xb0\x16\x60\x8d\x33\xc0\ -\x5a\x80\x35\xce\x00\x6b\x01\xd6\x38\x03\xac\x05\x58\xe3\x0c\xb0\ -\x16\x60\x8d\x33\xc0\x5a\x80\x35\xce\x00\x6b\x01\xd6\x38\x03\xac\ -\x05\x58\x13\x67\x40\xf1\xf4\x87\xd4\xf8\x06\x85\xf6\x50\x0c\xe7\ -\xa3\x6d\x72\x44\xae\x12\xf8\x2d\xd5\x91\x55\x43\xce\xee\x61\x3f\ -\x9c\x8e\xb6\xc9\x01\xbb\x95\x80\xbd\x90\xae\x34\x53\x50\x97\x48\ -\x84\xd8\x5b\x8e\x89\xbd\x70\x49\xf4\x88\x8b\xcb\x81\x28\xfd\x68\ -\x15\x23\x55\x11\x57\x03\x7a\xd6\xf0\x04\x81\xce\x71\x82\x4b\xe1\ -\x9a\x88\x01\xc7\x49\x2c\x02\x28\xf7\x06\xfb\xd4\x6c\xcf\x57\x35\ -\xdc\x55\x78\xb8\xa8\x56\x41\x33\x81\xa5\x5c\xa1\x19\x97\x1b\xb0\ -\xd3\xc7\xbc\xc0\xa9\xd3\x98\x40\x4a\xbf\x95\xcd\xac\x68\xb4\x21\ -\xae\x83\xc4\xcc\x8a\x46\x99\xd0\x0e\x81\x54\x79\x19\x9c\x8e\x1b\ -\xa1\x89\xdf\x90\xc4\x9e\x35\xff\x43\xcc\xb4\x48\x16\xd4\x06\xe4\ -\x1d\xd6\x5b\x17\xa9\x04\x0f\xf4\x5b\x4a\x77\x3e\x1d\xcc\x11\x9a\ -\xdb\xec\xf7\x5e\xc5\xf5\x3d\xc7\x4f\x8c\x90\x2a\xce\x6b\x22\x91\ -\xf2\x11\x32\x21\x0d\x31\x0d\x08\xaa\xc7\x16\xea\x98\x03\x4a\x68\ -\xee\xe4\xc8\x9b\x3c\xaf\xe9\xfb\x2a\x43\x53\xcf\x08\xbd\x43\xe3\ -\x0d\x4d\xe5\x04\x4e\x5f\x7b\x68\x2a\x48\xd7\xba\x92\xcd\x05\x0c\ -\x0b\x1a\x2e\xb5\x9c\x77\xa0\x0e\xc7\xe6\x00\xec\x83\xd8\x23\xb8\ -\x54\x68\xc6\xd2\x55\xc6\xe6\x1c\x0e\xc7\xed\xe6\x0f\xfd\x5b\xf6\ -\x1a\x3c\xff\xda\x47\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ -\x82\ -\x00\x00\x00\xc5\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x77\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\xb1\x0d\xc2\x40\x10\x04\xc0\x3d\xe8\x01\x51\x0a\x75\x20\x3a\ -\x20\x72\x45\xee\x82\x90\x1e\xe8\xc4\xa2\x07\x78\x52\xf4\x8e\x8d\ -\x25\x3c\x13\xae\x2e\xd8\xdb\x04\x00\x00\x00\x00\x00\x00\xd8\x82\ -\xea\x83\xd3\xad\x9d\x5b\xda\x98\xe4\xb0\x42\x9f\x25\x4d\x79\xd7\ -\xf5\x71\xa9\xfb\x77\xb8\xeb\xaf\xfe\xf4\xf9\x24\x39\xd6\xbe\x8d\ -\x7d\x38\x1b\x60\x6b\x66\x03\x54\x6a\x48\xf2\x5c\xa1\xcb\xd2\xa6\ -\xf6\xaa\x61\xed\x12\x00\x00\x00\x00\x00\x00\x00\xc0\xef\x7d\x00\ -\x4e\xfe\x12\x08\x2a\x3f\xe7\x81\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x05\x27\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\xd9\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4f\x68\x14\x57\x1c\xc7\xbf\xbf\x99\xd1\x42\xd3\x22\x76\x85\ -\xdd\x90\xa2\x87\xc6\x43\x45\xb0\x24\x5b\xf6\xe0\x65\xa1\xb5\x17\ -\x6d\x2e\x6d\x6a\x4b\x55\x3c\x84\xac\x8d\x36\xe6\xd2\x82\x81\x66\ -\xb2\x81\x62\x6b\x2f\xd9\x60\xc4\xb5\x81\x16\x1a\x5a\x34\xf6\x12\ -\x22\x94\xb4\x87\xa0\xbd\x2c\xd9\x78\x90\xba\xbd\xd8\x83\x21\xd6\ -\xac\x10\x45\x30\x48\xc2\xce\xfc\x7a\x48\x5e\x3b\xbb\x3b\xbb\x3b\ -\x9b\xf9\x9b\x66\x3f\xb0\x87\x79\xf3\x9b\x79\xbf\xf9\xee\xf7\x37\ -\xf3\x66\x78\x0f\x68\xd0\xa0\xc1\x56\x86\xac\x04\xc5\x55\x55\x59\ -\x5e\x0c\x75\xe8\xc0\x51\x02\x45\x01\x6e\x01\xf0\x82\xcb\xb9\xd5\ -\xcb\x0a\x40\x0f\x18\x9c\x95\x80\xab\x4d\x91\xa5\xc9\x99\x64\xb2\ -\x50\xeb\xa0\x9a\x02\x44\x13\x17\x0f\x81\x39\x05\xe2\xd7\x9d\xc9\ -\xd3\x1b\x18\xc8\x11\xa4\xbe\x6c\xfa\xcc\xaf\xd5\xe2\xa4\x2a\xa7\ -\xa0\x68\xf7\x48\x3f\xa0\x4f\x6f\xb6\x8b\x07\x00\x02\xf6\x01\xfa\ -\xf4\x9b\x89\xd4\x39\x80\x2b\xfe\xd1\x72\xa5\x1d\xd1\xee\x50\x3f\ -\x08\x5f\xba\x93\x9e\x97\xd0\x5b\x2d\xd1\xcc\xca\xdf\x73\xbf\xfc\ -\x6e\xba\xd7\xac\x31\x9a\xb8\x78\x08\xd0\xa7\x4b\x9a\x9f\x80\x30\ -\x20\x15\xe8\xc6\x9e\xa7\xe1\xf9\x89\x89\x0f\x34\xc7\x73\xb5\x41\ -\x67\xe7\x35\xf9\xfe\x8e\xfc\x6e\x5d\xe1\xc3\x60\x0c\x01\xd8\x59\ -\x1c\x21\xbd\x63\x56\x0e\x65\x02\xc4\x55\x55\x79\xf6\x70\xd7\x9d\ -\x22\xdb\x13\x7e\x93\x0b\xfa\xb1\xcc\x58\x5f\xde\xf9\xd4\x9d\x27\ -\xd6\x35\x1c\xd6\x14\x69\x1c\x8c\xb7\x45\x1b\x03\xb9\x97\x23\x4b\ -\x07\x4a\x6f\x8c\x65\xf7\x80\xe5\xc5\x50\x47\x49\xcd\x3f\x5e\xc5\ -\xb6\x8f\x37\xcb\xc5\x03\x40\x66\xac\x2f\x2f\x17\xf4\x63\x00\x9e\ -\x88\x36\x02\xf6\x2d\x2f\x86\x3a\x4a\x63\xcb\x04\xd0\x81\xa3\x45\ -\x0d\x04\xf5\xce\xe5\x4f\x1e\xb9\x91\xa8\x9b\x64\xc6\xfa\xf2\x0c\ -\x56\x8d\x6d\x65\xd7\x06\x13\x01\xd6\x9e\xf3\x86\x80\x02\xdd\x70\ -\x3e\x3d\x6f\x90\x35\x69\xca\xb8\x4d\x40\x7b\x69\x8c\xc9\x63\x90\ -\x5b\x8c\x5b\x7b\x9e\x86\xe7\x9d\x4e\xcc\x2b\x4c\x72\x7f\xb5\x34\ -\xc6\x6c\x1c\x50\x34\xc2\x0b\xda\xdd\xbe\x1e\x4c\x72\x2f\x1b\xbd\ -\x56\x19\x08\x6d\x0d\x14\xbf\x13\xb0\x42\x5b\xcf\x68\xab\x54\xd0\ -\x06\x40\x78\x6f\xbd\xe9\x3a\x33\x86\xe6\xae\xf4\xfe\x65\xf7\xdc\ -\x81\x77\x40\x2c\x91\xda\x2b\x69\xda\x4d\x10\x8e\x03\x78\x71\xfd\ -\x77\x82\x08\xb7\xda\x7a\x46\x5b\xed\x9e\x3f\xd0\x02\xc4\x55\x55\ -\xd1\x98\x7e\x02\xd0\x6c\xb2\xbb\x59\xd2\xb4\x2f\xec\xf6\x11\x68\ -\x01\x9e\x3d\x0c\x7d\x0e\x2a\x7f\x74\x19\x78\xdf\x6e\x1f\x81\x15\ -\x20\x7a\x2a\xb5\x1f\x84\x41\xb7\xfb\x09\xa4\x00\x71\x55\x55\xa0\ -\xd3\xf7\x00\xb6\x55\x8b\x23\xa2\x09\xbb\x7d\x05\x52\x00\x0b\xd6\ -\x07\x80\x55\x89\xf9\x82\xdd\xbe\x02\x27\x80\x55\xeb\x13\x78\x30\ -\x93\xee\xcd\xd9\xed\x2f\x50\x02\x58\xb5\x3e\x80\x6c\x53\xe4\xf1\ -\x37\x4e\xf4\x19\x28\x01\xac\x5a\x9f\x74\xe9\xa4\x95\x0f\x9e\x56\ -\x08\x8c\x00\xf5\x58\x7f\xf6\xdb\x33\x77\x9d\xea\x37\x10\x02\xf8\ -\x61\x7d\x81\x23\xef\x02\xed\xdd\x23\xaf\x11\x61\x00\x62\x60\xc2\ -\xf8\x59\x57\xe4\xa1\xdb\x97\x4e\xdf\xb3\x72\xbc\x1f\xd6\x17\xd8\ -\x76\x40\x5b\xcf\x68\x2b\x11\x6e\x01\x38\x01\x31\x56\x27\x1c\x97\ -\x34\xed\x66\x2c\x91\xda\x5b\xeb\x78\xbf\xac\x2f\xb0\x2d\x80\x54\ -\xd0\x06\x50\x61\xac\xae\x81\x7e\x8c\xab\x6a\x45\x97\xf9\x69\x7d\ -\x81\xfd\x7b\xc0\x7f\xaf\xa8\x66\x44\x97\x17\x5f\xf9\xac\xd2\x4e\ -\x3f\xad\x2f\x70\xfd\x26\xc8\xa0\xc1\xe8\xa9\xd4\xfe\xd2\x76\xbf\ -\xad\x2f\x70\x42\x80\xeb\x35\xf6\x6f\x07\xd3\x77\xc6\x52\x08\x82\ -\xf5\x05\xb6\x05\x90\x81\xaf\x01\xac\xd6\x08\x2b\x2a\x85\x20\x58\ -\x5f\x60\x5b\x80\x4c\xba\x37\x07\x46\xb2\x56\x9c\x28\x85\xa0\x58\ -\x5f\xe0\xc8\x3d\xe0\xa5\xe6\xa5\x0b\x60\xcc\xd5\x08\xdb\x0e\x96\ -\x7e\x60\xa6\x71\x04\xc0\xfa\x02\x47\x04\x98\x49\x26\x0b\x90\xf8\ -\x24\x6a\x96\x02\xbf\x41\xc0\x81\x1a\xa7\xf3\xc4\xfa\x02\xc7\x9e\ -\x02\xd9\xcb\x67\xff\xb0\x52\x0a\xb5\xf0\xca\xfa\x02\x47\x1f\x83\ -\x16\x4b\xa1\x1a\x9e\x59\x5f\xe0\xa8\x00\xd6\x4b\xc1\x14\x4f\xad\ -\x2f\x70\x7c\x20\xb4\xd1\x52\xf0\xda\xfa\x02\x57\x46\x82\x1b\x28\ -\x05\xcf\xad\x2f\x70\x45\x80\x3a\x4b\xc1\x17\xeb\x0b\x5c\x7b\x17\ -\xb0\x5a\x0a\x7e\x59\x5f\xe0\xea\xcb\x90\x85\x52\xf0\xcd\xfa\x02\ -\x57\x05\x98\x49\x26\x0b\xba\x22\x7f\x08\xc0\x6c\x92\xc5\xbc\x2e\ -\xcb\x1f\xf9\x65\x7d\x81\xeb\xaf\xc3\xb7\x2f\x9d\xbe\x27\x6b\x38\ -\x48\xe0\x29\x00\xcf\x01\x3c\x27\xf0\x94\xac\xe1\xa0\xd5\x4f\x66\ -\x6e\xe2\xc9\xfc\x80\xcc\x58\xef\x02\x80\x77\xbd\xe8\xab\x5e\x02\ -\xf1\x55\xd8\x4f\xcc\x04\x58\x31\x6e\x74\x76\x5e\xab\x38\x9d\x36\ -\xe8\x98\xe4\xbe\x52\x1a\x63\x22\x00\x3d\x30\x6e\xdd\xdf\x91\xdf\ -\xed\x68\x56\x1e\x62\x92\xfb\x42\x69\x4c\x99\x00\x0c\xce\x1a\xb7\ -\x75\x85\x0f\x3b\x9c\x97\x67\x68\xb2\x7e\xc4\xb8\xcd\x28\x7f\x24\ -\x97\x09\x20\x01\x57\x8b\x1a\x18\x43\xb1\xae\xe1\xb0\xe3\xd9\xb9\ -\x4c\xac\x6b\x38\x4c\xa0\xa2\x81\x58\xd9\xb5\xc1\x44\x80\xa6\xc8\ -\xd2\x24\x98\xfe\x34\x34\xed\xd4\x14\x69\x7c\x33\x89\xf0\xef\x64\ -\x69\xc3\x8c\x71\x06\x72\x4d\x91\xa5\xc9\xd2\xd8\xba\xa6\xcb\x33\ -\x58\x95\x35\x69\x2a\xc8\xd3\xe5\x35\x59\x3f\xb2\xfe\xcf\x6f\x6c\ -\xba\xbc\x20\xda\x3d\xf2\x3f\x59\x30\x01\x10\xb8\x7f\x36\x7d\xf6\ -\xbc\xd9\xbe\x8a\xe3\x80\xec\x95\x4f\xcf\x13\xb8\xdf\xbd\xb4\x3c\ -\x81\x99\xe9\xdc\x6c\xba\xf7\xab\x4a\x01\x96\x16\x4d\x31\xf4\xe1\ -\xb5\x35\x38\x9b\x07\xab\x8b\xa6\x36\xb0\x6c\x0e\xed\x58\x9b\x75\ -\x1d\xc0\x65\x73\x58\x60\x60\xae\x9e\x65\x73\x0d\x1a\x34\xd8\xda\ -\xfc\x03\xf8\xad\xf2\xfb\x1a\x49\x36\xd6\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x87\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x39\x49\x44\x41\x54\x58\x85\xed\ -\xd7\xbf\x4e\xc2\x50\x14\xc7\xf1\xef\xb9\x21\x30\x5a\x17\x7c\x86\ -\xbe\x40\x5f\x80\x8a\x4c\x26\xa8\x1b\x23\x98\xb0\xd6\x59\x1d\x64\ -\x87\x95\x44\x57\x46\x65\x34\x22\x4f\xd0\x17\xe8\x3b\xb0\x50\x47\ -\x08\xe1\x38\x94\x2a\x7f\x5d\x6c\xe3\xe0\xfd\x8d\x37\x37\xfd\x7d\ -\xd2\xbb\x9c\x03\xff\x3d\xb2\x7d\xe0\x5f\x5e\x9f\x09\xdc\x80\x7a\ -\x80\x93\x51\x4f\x0c\x12\x2a\x74\xc7\xcf\x8f\x6f\x07\x01\xfe\x55\ -\xb3\x23\x2a\xb7\xc0\x0c\x88\x50\x3e\x32\xa9\x17\x8e\x00\x17\x28\ -\xa1\x74\xde\x5f\x9e\xee\x77\x00\x95\x7a\xb3\x66\x8c\xbc\x0a\x8c\ -\x59\x16\x1a\xa3\x61\x7f\x92\x49\xf9\x2a\xd5\x7a\xbb\x8c\x59\x0c\ -\x14\x7c\x45\x6a\xe9\x9f\x30\xe9\x05\x63\x4c\x00\xcc\xf2\x28\x07\ -\x18\x0d\xfb\x13\x96\x85\x06\x30\x17\x34\xf8\xea\xfd\xbe\xa2\x1e\ -\x10\xe5\x51\xbe\x81\x40\x22\x14\x6f\x0f\x00\x27\xb3\x37\xff\x29\ -\xaa\x31\xc2\xf1\x3e\xc0\x9f\xc4\x02\x2c\xc0\x02\x2c\xc0\x02\x2c\ -\xc0\x02\x2c\x60\x1d\x10\xaf\xa6\xd7\x7c\x23\xe2\xa0\x4c\xf7\x00\ -\x24\x04\xdc\x6a\xbd\x5d\xce\xab\x3b\xf9\xb6\xba\x08\xe1\x0e\x40\ -\xa1\x0b\x94\x30\x8b\x41\x1e\x88\xca\x79\xeb\x04\xb3\x18\x00\x45\ -\x45\x7a\xe9\xf9\xc6\x62\x72\x7a\xd1\x7a\x40\xb8\x03\xe6\xc9\xf4\ -\xaa\x71\x26\xed\x22\x0e\xa8\x0b\x14\x0f\x2e\x26\x69\x92\xd5\x4c\ -\x03\x14\x6f\x7d\x7a\xfd\x55\x94\x29\x42\xa8\x48\x6f\x7b\x35\xb3\ -\xf9\x04\xc3\x25\x66\x2f\xe5\x8f\x2b\x3d\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\x4e\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x00\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4f\x4f\x13\x51\x14\xc5\xcf\x41\x40\x09\x4b\xad\x94\x3f\xb6\ -\x0d\x0b\x37\x80\x2b\x96\xf2\x2d\x00\x23\x89\xb8\x93\x68\x22\xba\ -\x84\x4f\xa0\x6b\x35\x11\x97\x6a\x22\x89\xf0\x2d\x70\xc9\x8a\xc2\ -\xca\x05\x43\x0b\xa5\x50\x5d\x12\xb4\x20\xc7\x05\x2d\x0e\xd3\x81\ -\x56\xe2\xf4\xb6\xf2\x7e\xab\xd7\xfb\xde\x34\xe7\x9e\xbe\x37\xaf\ -\x8b\x7b\x01\x87\xc3\x71\x99\x61\x2d\x8b\xf2\xf9\x7c\xe7\x7e\xb1\ -\x38\x4e\x71\x14\xc4\x20\x84\x1e\x00\xad\x11\x6b\xfb\x5b\x0e\x41\ -\xe4\x20\xac\x8a\x5a\xec\x68\x6f\xff\x1c\x8f\xc7\xf7\xaa\x3d\x74\ -\xae\x01\x92\xe8\x65\xb6\x26\x09\xbd\x00\xd0\xfd\xcf\xa4\xd6\x87\ -\x6d\x82\x33\x89\x44\xef\x47\x92\x3a\x6b\xd1\x99\x06\x2c\x2f\x2f\ -\xb7\xc5\x62\x37\x5f\x0b\x9c\x8a\x46\x5f\x7d\x20\xf4\xae\x50\xd8\ -\x7d\x3a\x3c\x3c\x7c\x10\x36\x1f\xba\x8d\x8f\x7f\xf9\xcd\x37\x02\ -\x1e\x9d\x8a\x03\x69\x8a\x5f\x48\xe5\x25\x1d\x45\x21\xf8\xa2\x90\ -\x6c\x91\x18\x17\x75\x97\xc0\x50\x39\x2e\x70\x2a\x16\xbb\x09\x49\ -\x8f\xc3\x76\x42\xe8\x0e\xd8\xd8\xd8\x9c\x14\xf4\xde\x17\xfa\x0e\ -\x61\x3a\x99\xec\x9b\x3f\x6f\x3b\x35\x02\x92\xb8\xb1\xb1\x79\x1f\ -\xc4\x2b\x00\xd7\xcb\x71\x82\x0f\x93\xc9\xbe\x0f\xc1\xf5\x15\x06\ -\xe4\xf3\xf9\xce\x1f\x3f\x0f\xbe\xe2\xcf\x99\xff\x06\xfd\xba\x93\ -\x4a\xa5\xb6\x23\x53\x1d\x01\x9e\xe7\x75\x83\x57\x56\x00\xdc\x28\ -\x85\x72\xd7\xae\xb6\xdd\x0e\xbe\x18\x5b\x82\x0f\xee\x17\x8b\xe3\ -\xf0\xbf\xf0\x84\x67\xcd\x96\x3c\x00\xa4\x52\xa9\x6d\x08\xcf\x7d\ -\xa1\x9e\xfd\x62\x71\x2c\xb8\xae\xc2\x00\x8a\xa3\xe5\xb1\x80\x74\ -\x32\xd9\x37\x1f\x91\xc6\xc8\x49\x26\xfb\x3e\x09\x48\x97\x3f\x53\ -\xac\x6e\x00\x88\x41\xdf\x03\x4b\x8d\x7e\xe6\xcf\x83\xa4\x28\x2e\ -\xf9\x42\x03\xc1\x35\x95\x06\x1c\xff\xc9\x29\x7d\x81\x76\xa2\x91\ -\x56\x3f\x02\x39\xf4\x06\xe7\x2b\x0d\xf0\x5d\x8d\x8d\x76\xd5\x5d\ -\x84\x40\x0e\x15\xd7\x7e\x98\x01\x97\x0a\x67\x80\xb5\x00\x6b\x9c\ -\x01\xd6\x02\xac\x71\x06\x58\x0b\xb0\xc6\x19\x60\x2d\xc0\x1a\x67\ -\x80\xb5\x00\x6b\x9c\x01\xd6\x02\xac\x71\x06\x58\x0b\xb0\xc6\x19\ -\x60\x2d\xc0\x1a\x67\x80\xb5\x00\x6b\x9c\x01\xd6\x02\xac\x71\x06\ -\x58\x0b\xb0\xc6\x19\x60\x2d\xc0\x1a\x67\x80\xb5\x00\x6b\x9c\x01\ -\xd6\x02\xac\x71\x06\x58\x0b\xb0\xc6\x19\x60\x2d\xc0\x1a\x67\x80\ -\xb5\x00\x6b\xc2\x0c\x38\x2c\x0f\x48\x36\xbd\x41\x81\x1c\x0e\x83\ -\xf3\x61\x65\x72\xb9\xf2\x50\x62\x57\x34\xb2\xea\x47\x20\x87\xad\ -\xe0\x7c\x58\x99\xdc\xea\xc9\x90\x1a\x91\x54\x53\x4f\x41\x23\x22\ -\x89\xa2\x46\x7c\xa1\xb5\xe0\x9a\x0a\x03\x44\x2d\x96\xc7\x04\x86\ -\xbc\x6c\x76\x3c\x22\x7d\x91\xe3\x65\xb3\xf7\x4e\x55\x8e\x53\x0b\ -\xc1\x35\xd5\x8b\xa5\x85\xc2\xd1\xd1\xc1\x50\x7f\x7f\x7f\x53\x15\ -\x4d\xae\xaf\xaf\xc7\xc9\xd6\x15\x10\xb1\x52\xa8\xb6\x62\xe9\x78\ -\x3c\xbe\x47\x70\xe6\x24\x40\xc4\x5a\x5a\xda\xd2\x9e\x97\x9d\x68\ -\x86\xe3\x20\x89\x9e\x97\x9d\x08\x24\x0f\x82\xb3\x61\x2d\x34\xa1\ -\x09\x49\x62\x26\x93\x7d\x1b\xec\x16\x29\x35\x4c\x2c\x91\xda\x69\ -\xb4\x2a\xd2\x52\xc3\x44\x97\xa8\x11\xff\xb6\x07\x00\x42\x73\x89\ -\xc4\xad\x27\x35\x37\x4c\x00\xff\x55\xcb\xcc\x5c\xa1\xb0\x3b\x7d\ -\x56\xcb\x4c\xd5\xa6\xa9\x4c\x66\xeb\x81\xa0\x97\x68\xbe\xa6\xa9\ -\x1c\xc1\xd9\x0b\x37\x4d\xf9\x29\xb5\xcd\x8d\x95\xea\xed\x07\x70\ -\x5c\x75\xdd\x78\x6d\x73\xc7\xf7\xfc\x9a\xa8\x85\x8e\xf6\xf6\x85\ -\x5a\xda\xe6\x1c\x0e\xc7\xe5\xe6\x37\x49\x9a\x11\x82\x28\x6e\xc8\ -\x6e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x78\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x2a\x49\x44\x41\x54\x58\x85\xed\ -\xce\x41\x11\x00\x20\x0c\x04\xb1\x16\xff\x22\xe9\x20\x04\x64\x1c\ -\x8f\xc4\xc0\x6e\x15\x00\x10\xd6\x7b\xce\x4d\x0e\xac\x64\x1c\x00\ -\xf8\xc2\x03\x48\xae\x03\xa7\xd4\xed\xa0\x47\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x06\x65\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x06\x17\x49\x44\x41\x54\x78\x9c\xed\ -\x9a\xc9\x73\x5c\xd5\x15\x87\xbf\x73\x5b\x31\x32\x83\x4c\x6c\x50\ -\x00\xf5\x1b\x5a\x15\x6f\xb0\x31\x93\xc1\x98\xa4\x12\x2c\x1c\x24\ -\x83\x6d\xe5\x6f\x61\x05\x8b\x64\x91\xf2\x82\x0d\xcb\xe4\xef\xa0\ -\x98\xca\xd6\x18\x46\x43\x85\xa4\x42\x80\x2a\xaa\x28\xd4\x6f\x90\ -\x29\x07\xc7\x0e\x96\x71\x2c\x19\xeb\x1e\x16\x52\x3b\xe2\x75\xab\ -\xfb\xbe\xee\xf7\x24\x51\xe8\x5b\xde\x77\xfa\xbe\xf3\xfb\xfa\xdc\ -\x1e\xa4\x86\x6d\xb6\xd9\xe6\xa7\x8c\xb4\x5a\x3c\x7f\xfe\xfc\x6d\ -\x8b\x8b\xd7\x9f\x57\x91\x13\x40\x3f\x70\x56\x74\xf9\xa5\x30\x0c\ -\xeb\x1b\xdb\x5e\x77\x44\x51\x54\x53\xa9\xbc\x00\x1c\x06\x16\x0d\ -\xbc\xb1\x73\xe7\x2d\x2f\x0f\x0e\x0e\x7e\x9b\xad\x6d\x12\xf0\xf9\ -\xe7\x17\xee\xe8\xdf\xb9\xf8\x16\xf0\x70\xe6\xd2\x65\x35\x8c\xd6\ -\x3c\xef\xc3\x72\xda\x2e\x86\x24\x49\x1e\xb3\x2a\x93\xc0\xae\x1f\ -\x5c\x10\x3e\xfe\x6e\x69\xf1\x37\x7b\xf7\xee\x5d\x58\xbb\x6c\xb2\ -\x1b\xf4\xf7\x5f\x7b\x81\xe6\xf0\x00\xbb\xc4\x32\x51\x4f\xd3\x43\ -\x45\x36\x5c\x24\xeb\x86\x07\x50\x1e\xdc\xb1\xa3\xff\xc5\xec\x72\ -\x93\x00\x44\x4e\xb6\xb9\xc7\xc0\x56\x95\xd0\x36\xfc\x2a\x8a\x8e\ -\x67\xd7\x9a\x05\xc0\xce\x0e\xf7\x1a\x10\xcb\xc4\x5c\x9a\x3e\x9e\ -\xb3\xc7\xd2\x48\x92\xe4\x60\xa7\xf0\x2b\x48\x7f\x76\xa5\x49\x80\ -\xa2\xef\x39\xdc\x73\xc0\x58\x26\xb7\x82\x84\xd5\xf0\x53\x74\x0c\ -\x0f\x40\x53\xb6\x26\x01\x7d\x46\x4e\x01\x97\x1d\x36\xdb\x74\x09\ -\x39\xc3\x2f\x54\x0c\x7f\xca\x2e\x36\x09\xf0\x3c\xef\x0b\x6b\x78\ -\x06\x77\x09\x9b\x72\x1c\xdc\xc7\x1e\x80\x05\xb5\x32\xea\x79\xde\ -\x17\xd9\x0b\x2d\x3f\x07\x00\xcc\xa5\xe9\xe3\xc6\x32\x09\x0c\x38\ -\xdc\xe0\xb2\x11\xfd\x9d\xef\xfb\x7f\x73\xa8\xed\x99\x38\x8e\x1f\ -\x55\xcc\x14\x70\xa7\x43\xf9\x15\xb5\xf2\x4c\xad\x56\xfd\xa0\xd5\ -\xc5\x75\x05\xc0\xd6\x94\x50\x64\x78\xe8\x20\x00\xb6\x96\x84\xa2\ -\xc3\x83\x83\x00\x80\x7a\x9a\x1e\x12\xcb\x04\xee\x12\x8e\xfa\xbe\ -\xff\x91\xcb\xde\xae\x44\xd1\x57\x8f\x20\xcb\x53\xc0\xcf\x1d\xca\ -\xaf\xa0\x32\x1a\x86\xd5\xb3\x9d\x0a\x9d\x04\xc0\xe6\x4a\x28\x2b\ -\x3c\xb4\xfe\x20\xd4\x92\x9a\xe7\x7d\xa8\x56\x46\x81\x85\x8e\xc5\ -\xb0\xcb\xaa\x4c\x25\x49\x72\xd0\x75\xff\xf5\xc8\x1f\xde\x8c\xb9\ -\x86\x87\x1c\x13\xd0\xa0\x5e\x9f\x7f\x42\x8c\x4e\x00\x77\x38\x94\ -\x7f\xb3\xfa\x9a\xd0\xd5\x24\xe4\x0c\xff\x2d\x6a\x46\xc3\x70\xe8\ -\xfd\x3c\xf7\xc8\x2d\x00\xf2\x4b\x10\xec\xd1\x20\x08\xfe\x9e\xe7\ -\x1e\x1b\x11\x1e\xba\x14\x00\xe5\x4a\x88\xa2\x73\x0f\x23\x76\x9a\ -\x92\xc3\x43\x0f\x02\x00\xa2\x68\xfe\x30\xa2\x67\x28\x50\x42\xde\ -\xf0\x82\x19\x0b\x82\x21\x97\xef\x2f\x2d\xe9\x49\x00\x14\x2b\x61\ -\xa3\xc3\x43\x8e\x77\x81\xf5\x08\xc3\xea\x59\xd4\x8c\x01\x57\x1c\ -\xca\xef\x54\xcc\x64\x14\x7d\xf5\x48\xf6\xc2\x6a\x78\xe7\x33\x2f\ -\xd8\x63\xbd\x86\x87\x02\x26\xa0\x41\x14\x9d\x7b\x12\xb1\x67\x80\ -\xdb\x1d\xca\xff\x8b\x56\x8e\x86\xe1\x7d\xff\x00\xa8\xd7\xe7\x1f\ -\x12\xa3\xd3\xc0\x6e\x87\xc7\x5e\x15\xec\x58\x10\x04\xef\xf6\xd2\ -\x6f\x83\xc2\x04\x40\x77\x12\x54\xad\xdd\xac\xf0\x50\xb0\x00\xc8\ -\x29\x41\x59\x50\x14\x11\x71\xf9\x74\x59\x78\x78\x28\x41\x00\x40\ -\x1c\x9f\xfb\x95\x62\x4f\xe3\x36\x09\x2e\x5c\x35\xa2\xc7\x7c\xdf\ -\x7f\xa7\xa0\xfd\x6e\x52\x8a\x00\x28\x54\x42\x69\xe1\xa1\x80\x77\ -\x81\xf5\x08\x82\xa1\xf7\x04\x7b\x0c\x68\xfa\x67\x44\x0e\xae\x5a\ -\xd1\x67\xcb\x0a\x0f\x25\x4e\x40\x83\x38\x8e\x7f\xad\x98\xd3\xc0\ -\x6d\x39\x1f\x7a\xd5\x8a\x3e\x3b\xec\xfb\x6f\x97\xd1\x57\x83\xd2\ -\x05\xc0\xaa\x04\x35\x13\x48\xc7\x3f\xb9\x37\x58\xb4\xa2\xa3\x65\ -\x87\x87\x12\x8f\xc0\x5a\x96\x8d\x59\x40\xb8\xee\x5a\xaf\x70\x5d\ -\x96\x8d\xcb\xd7\xee\x9e\x29\x5d\xc0\x5c\x9a\x1e\x30\x96\x19\xdc\ -\xfe\x7a\x0b\x80\xc0\x80\x18\x9d\xae\xd7\xe7\x1f\x2a\xb1\xb5\xc6\ -\xbd\xca\x63\x4d\xf8\x3d\x5d\x6e\x71\x49\xad\x3c\x5d\xab\x55\xff\ -\x59\x64\x5f\x6b\x29\x6d\x02\x56\xc3\x4f\xd3\x7d\x78\x80\xdd\x62\ -\x74\x7a\x6e\x6e\xfe\xc1\xa2\xfa\xca\x52\xca\x04\xa4\x69\xfa\xc0\ -\xf2\xca\x33\x7f\x57\x41\x5b\x5e\xb2\xcb\x32\x32\x3c\x5c\xfd\xb8\ -\xa0\xfd\x6e\x52\xf8\x04\xe4\x0c\xbf\xa4\xaa\x4b\x0e\x75\xbb\x4d\ -\xa5\x9c\x49\x28\x54\x40\xce\xf0\xd7\xd4\x32\xa6\x2b\xff\x86\xfb\ -\x9f\x43\xfd\x9e\x32\x24\x14\x76\x04\x92\x24\xd9\x6f\x55\x66\x71\ -\x0c\x8f\xca\x73\x61\x58\x9d\x05\xa8\xa7\xe9\x6f\xc5\xf2\x26\x70\ -\xab\xc3\x63\x2f\x5a\xc3\xc8\xb0\xe7\xfd\xab\x97\x7e\x1b\x14\x22\ -\xa0\x97\xf0\x0d\x36\x4b\x42\xcf\x47\xa0\x8b\xf0\xc7\xb3\xe1\x01\ -\x6a\x9e\xf7\x96\x5a\x9e\xc3\xf5\x38\x58\x66\xe6\xd2\xf4\x40\xde\ -\x7e\xb3\xf4\x24\x20\x49\x92\xfd\xd6\x8a\xf3\x99\x5f\x0d\x3f\xb3\ -\x5e\x41\xad\xe6\xfd\x35\xa7\x84\xe9\x5e\x25\x74\x7d\x04\x6e\x86\ -\x17\xee\x76\x28\xbf\x26\xc8\x89\x20\xa8\x4e\xbb\xec\x5d\xaf\xa7\ -\x4f\x89\xe1\x4d\x3a\xff\x5c\x07\xe0\x3f\x15\xc3\x88\xe7\x79\x9f\ -\xb8\xec\x9d\xa5\x2b\x01\x71\x1c\xef\x53\x35\xb3\x8e\xe1\x17\x05\ -\x39\xee\x1a\xbe\xc1\x46\x49\xc8\x2d\x60\x23\xc2\x37\x88\xa2\xf9\ -\x23\x88\xbe\x41\x89\x12\x72\x09\x88\xe3\x78\x9f\x62\x66\x80\x41\ -\x87\xf2\x9e\xc2\x37\xc8\x2b\xc1\x88\x1e\xf1\x7d\xff\x53\xd7\xfd\ -\x9d\x5f\x04\xf3\x87\x37\xce\x67\xbe\x1d\x61\x58\x9d\x45\xe5\x38\ -\x70\xcd\xa1\xfc\x2e\xab\x32\x9b\x24\xc9\x7e\xd7\xfd\x9d\x26\x20\ -\x8e\xe3\xfb\x15\x33\x4b\xae\xf0\x43\x53\xae\x4d\xb8\x10\x45\xf3\ -\x23\x88\xbe\x4e\xc1\x93\xd0\x71\x02\xf2\x87\xb7\x27\x8b\x0e\x0f\ -\x10\x86\xd5\x19\x41\x4e\xe0\x3a\x09\x56\x66\x5c\x26\xa1\xed\x04\ -\x74\x17\x3e\x98\x74\xa8\xed\x9a\x38\x9e\x7f\x5a\xd1\xd7\x59\xf9\ -\x15\x7b\x7b\x94\x0b\xc6\xe8\x48\xbb\x49\x58\x77\x02\x56\xc2\x57\ -\x9c\xcf\xbc\x15\x1d\x2f\x3b\x3c\x40\x10\x54\xa7\x05\x39\x0e\x2c\ -\x76\x2c\x16\xee\xb6\x56\x66\xe2\x38\xde\xb7\x7e\x49\x0b\xfe\x1f\ -\x5e\x7f\xe1\xd0\xd3\x92\x15\x3d\x39\xec\xfb\x13\x0e\xb5\x85\x91\ -\x77\x12\x44\xec\x91\x20\x08\x3e\xcb\x5e\x6a\x12\x90\xa6\xe9\xd0\ -\xb2\xe5\x23\xe0\x1e\x87\x3e\x36\x25\x7c\x83\x38\x3e\x77\x54\xb1\ -\xaf\xe1\x22\x01\xbe\xbe\xd1\x67\x0e\xfe\x72\x68\x28\x5d\xbb\xd8\ -\x74\x04\xac\xd5\x3f\xf0\x23\x08\x0f\x10\x04\x43\x53\x82\x39\x81\ -\xcb\x71\x80\xc1\xbe\x1b\xf6\x8f\xd9\xc5\x16\xbf\x16\x97\xa7\x1c\ -\x36\x5b\x52\xd1\xf1\xcd\x0c\xdf\x60\x45\x82\x3d\x89\x9b\x84\x23\ -\xd9\x85\x56\x2f\x82\xcb\x1d\x36\x59\x52\xd1\xf1\x9a\xef\x9f\x71\ -\x69\x70\x23\x08\x82\x60\xd2\x49\x82\x36\x67\x6b\x12\x20\x68\xbb\ -\x67\x75\x49\x0d\xbf\xdf\x4a\xe1\x1b\x04\x41\x30\x69\x45\xc7\x69\ -\x23\x41\x85\xd3\xd9\xb5\x26\x01\x95\x8a\x39\x05\x7c\xd9\xe2\xf1\ -\x2b\xe1\x3d\xaf\x69\x93\xad\xc2\xb0\xef\x4f\xb4\x91\x50\xbf\xb1\ -\xa3\xef\x54\x76\xb1\x49\x40\xb5\x5a\xbd\xf8\xb3\x3e\xf3\x04\xc2\ -\x9f\x81\x18\xf8\x5a\x91\x57\xd1\xca\x93\x5b\x39\x7c\x83\x61\xdf\ -\x9f\x50\x2b\x87\x51\x5e\x01\xf9\x37\x10\xa3\xf2\x97\xef\x76\xf4\ -\x1d\xda\x7b\xef\xbd\x17\x36\xbb\xbf\x6d\xb6\xd9\x66\x6b\xf1\x3d\ -\x64\x29\x23\xc7\x02\xc7\xba\xcb\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x01\x06\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xb8\x49\x44\x41\x54\x78\x9c\xed\ -\xd9\xc1\x0d\x83\x50\x10\xc4\xd0\x0d\xa2\x24\x7a\xe2\x46\x31\xdc\ -\xe8\x29\x3d\x91\x32\x5e\xa4\x6f\x37\xb0\x96\x35\xb7\x9d\x81\x1c\ -\xe7\xfd\x1e\xe7\xfd\x4a\x87\x4d\x1e\xff\x07\x0a\xa0\x05\x34\x05\ -\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\ -\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\ -\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\ -\xa0\x59\x3e\xc0\x47\x1e\xd7\xaf\xf1\x99\x16\x30\xbb\x16\x98\x99\ -\xf9\x3e\x17\x5b\xe2\xf2\x0b\x28\x80\x16\xd0\x14\x40\x0b\x68\x0a\ -\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\ -\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\ -\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\x66\xf9\x00\ -\x3f\xfa\xaa\x08\xd8\xe7\x6a\x2c\xe4\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x04\x72\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x24\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4d\x88\x1c\x55\x14\x85\xbf\x5b\xdd\x09\x8a\x8a\x20\x2a\x62\ -\x4f\x57\x75\x0d\x19\x14\x77\xc2\xe0\x52\x50\x34\x1a\xc4\xe0\x0f\ -\xe8\x4a\x44\x51\xd0\x85\x18\x41\x11\x74\x11\x21\x8a\x11\x04\x17\ -\x22\x1a\x70\xe3\xc2\xa0\xae\xc2\x80\x46\x47\x5d\x08\x82\xe0\x42\ -\x10\x44\x82\x66\xa6\xe7\x75\xcd\x24\xd1\x88\x8a\x60\x18\xec\xee\ -\x77\x5d\xcc\x88\x55\x35\x43\x98\x21\xef\xbd\x7a\x9a\x3e\xcb\x73\ -\xa0\xee\x7d\xa7\xee\x7d\x3f\xf5\x03\x13\x4c\x30\xc1\x04\xff\x01\ -\x18\xb3\xb2\xdf\x0c\x8a\xe1\x92\x29\x46\xc6\x14\x2f\xb8\xba\xae\ -\xb8\xba\x90\x4f\x2c\x2d\x2d\xdf\x84\xe8\xe7\xfc\x9b\xaf\xed\x65\ -\xdd\x96\x8b\x6b\x27\x2e\x2e\xe2\x13\x83\xc1\x60\x16\xd1\x39\x4a\ -\x37\x4b\x55\x9d\xe5\x1d\xb5\x01\xfd\xfe\xca\xb5\x56\xe5\x28\x70\ -\x71\x99\x17\x11\xeb\x2a\x46\xb4\x06\x2c\x2c\xac\xa4\x49\x62\xe7\ -\x81\xcb\x37\x91\xd5\x55\x9c\x28\x0d\xf8\xf1\xe4\xc9\x2b\x5a\x6d\ -\x3b\xaf\xd0\xf5\x1d\x2b\x3a\x03\x8e\x1d\x3b\x7d\xc9\x8e\xbf\x46\ -\x1f\x01\xd7\x84\x88\xd7\x0e\x11\x64\xab\xe8\xf7\xfb\x17\x48\xb2\ -\x7a\x04\x98\xad\x49\x8a\xa7\x15\x2b\x9a\x0a\x50\xd5\xb6\xb4\xda\ -\x87\x81\x9b\xeb\x12\xe0\x6c\xd2\xab\x23\x0a\x03\x54\x55\x4c\xb1\ -\x7c\x08\xe5\xee\xaa\x22\x5e\x07\x0f\x91\x18\x60\x06\xcb\xaf\xa0\ -\x3c\x5c\xe6\x44\x50\x50\xaf\x83\x87\x08\xe6\x00\x63\x8a\x67\x15\ -\x9e\x29\x73\xba\xb6\xc8\x79\x1f\x3c\x34\x5c\x01\xc6\x14\x8f\x2a\ -\x1c\xac\xf3\x22\x8c\x43\xe5\xd0\x98\x01\x4b\x4b\xc5\xbd\x0a\x6f\ -\x6d\x54\xfc\x97\x7d\x19\x8d\x18\x60\xcc\xca\x2d\x08\x87\x37\xc4\ -\x57\xec\xfa\xc4\x17\x0c\xc1\x0d\x58\x2c\x8a\x1b\x14\x7b\x04\xd8\ -\x59\xe6\x15\x2c\xe2\x6e\x8b\xbb\x55\x04\x9d\x04\x8d\x31\xd7\xa9\ -\xe5\x28\x70\x51\x4d\xb2\xe2\x70\x7f\xbf\x1d\x04\xab\x80\xc5\xc5\ -\x13\x99\x92\xcc\x03\x97\x55\x04\xc1\xd2\xd0\xe0\x21\x90\x01\xc7\ -\x8f\x9f\xba\x52\x5a\xe3\x4f\x81\x4e\x99\x17\xb0\x68\x73\x83\x87\ -\x00\x2d\xb0\xb0\xb0\x70\x69\xab\x3d\xfc\x18\x98\xa9\x2a\xaa\x1a\ -\x78\xc2\xdb\x0c\x5e\x0d\x28\x8a\xe2\x42\x6b\x99\x53\xb8\xbe\x26\ -\x29\xb8\x7b\xa8\x71\x2e\xf0\xd6\x02\xaa\xda\x1e\x59\x79\x4f\xe1\ -\xc6\xba\x44\xa0\x5d\xde\x56\xe0\xc5\x00\x55\x4d\x06\x83\xe2\x6d\ -\x41\xf7\x96\x79\x89\x6c\xf0\xe0\xc1\x00\x55\x15\x63\x8a\x57\x15\ -\x79\xb0\xcc\x8b\xa0\x1a\xd9\xe0\xc1\xc3\x1c\x60\x8a\xe2\x39\x44\ -\x9e\x2a\x73\x21\x0f\x37\xdb\x85\xd3\x0a\xe8\x0f\x96\x1f\x43\xe5\ -\xc5\x3a\x1f\xf2\x70\xb3\x5d\x38\x33\xa0\x6f\x8a\x83\xa2\xfa\xe6\ -\x46\x25\xec\xe1\x66\xbb\x70\x66\x80\xd4\x1e\x68\xc0\xfa\xfe\x3e\ -\x82\xb5\xfe\x6c\x70\xd7\x02\x9b\x94\x79\x03\x67\x9b\x6d\xc3\x5d\ -\x05\x20\x4f\x52\xdb\xd3\x2b\x12\xc5\x23\xb7\xb3\xc1\x59\x82\x59\ -\x36\xf5\x01\xaa\x4f\x94\x39\x01\x14\x5a\x31\xbf\x83\x75\x7a\x87\ -\x7a\xbd\xf4\x0d\x81\xfd\x65\x4e\x00\xd4\x46\x6b\x82\xf3\x12\x4d\ -\xd3\xa9\x03\xc0\xeb\x15\x52\x04\xc4\xdd\x1b\x5d\x97\x70\x9e\x94\ -\x88\x68\x96\x4e\xed\x03\xde\xad\x08\x8a\x20\x71\x3c\x86\x2f\xc3\ -\x4b\x42\x22\x62\x7f\x39\xfd\xd3\x43\xc0\x87\x15\x41\x11\x90\x44\ -\x22\xea\x06\x6f\x77\x64\x76\x76\x76\xb8\xa3\x9d\xdc\x07\xf2\x65\ -\x55\x51\x71\xf9\x81\xc3\xb9\xc2\x6b\x22\x9d\x4e\xe7\x8c\xda\xe1\ -\x9d\x08\xdf\x56\x15\x11\x34\x8e\x76\xf0\x9e\x44\x9e\xe7\xbf\xeb\ -\x78\x74\x3b\xb0\x50\x11\x04\x41\x9a\x6f\x86\x20\x77\x21\xcf\xf3\ -\x53\xe8\xf8\x56\xe0\x44\x45\x50\x4d\xd6\x96\x88\xe6\x10\xac\x0c\ -\x7b\xbd\x5e\x3f\x11\xbd\x0d\xf8\xad\xaa\x68\x42\x83\x9b\x84\xa0\ -\x7d\x98\xa6\xe9\x77\xa8\xdc\x01\x9c\xa9\xe7\xa1\x0d\x99\x10\x7c\ -\x22\xea\xf5\xa6\xbe\x52\xd1\x7b\x80\x61\x99\x17\x48\x54\xc3\x9b\ -\xd0\xc8\x4c\x9c\xa7\xe9\x27\x2a\xfa\x00\xb5\xc3\x93\x08\x09\x68\ -\x50\x13\x1a\x5b\x8a\xf2\x34\x7d\x5f\x91\xc7\x37\x2a\x61\x4f\x90\ -\x8d\xae\xc5\x79\x36\x75\x08\x91\xe7\xeb\xbc\x2a\x4e\x3e\x83\xdd\ -\x0a\x1a\xdf\x8c\x64\xdd\xce\xcb\xa8\xbe\x56\xe6\x44\xfe\x69\x07\ -\xff\x68\xdc\x00\x11\xd1\x2c\xeb\x3e\x2d\xe8\x3b\x65\x5e\xd7\xcf\ -\x0d\xbe\xe3\x37\x6e\x00\xac\x1d\x9e\xd2\xb4\xfb\x88\x22\x73\x55\ -\x45\x05\xcf\x39\x46\x61\x00\x80\x88\x8c\xb0\xc3\xfb\x51\xbe\xa8\ -\x4b\x78\xcc\x33\x1a\x03\x00\xf2\x3c\x5f\x1d\x0e\x57\xf7\x82\x7e\ -\x53\x93\xbc\x2d\x8d\x51\x19\x00\x30\x33\x33\xf3\xc7\x68\xb8\x73\ -\x0f\xca\x0f\x21\xe2\x45\x67\x00\xc0\xae\x5d\x57\xfd\x6c\x6d\x6b\ -\x37\xb0\xe2\x3b\x56\x94\x06\x00\x4c\x4f\x5f\x6d\x04\xbb\x1b\xf8\ -\x75\x13\xd9\x59\x4b\x44\x6b\x00\x40\x96\x65\xdf\xdb\x84\x3d\xc0\ -\x9f\x65\xfe\xbc\xf9\x65\x06\x60\xba\xdb\xfd\x5a\x48\xee\x2a\xbf\ -\x62\x3b\x2f\x7e\x99\x29\x23\xcb\x3a\x9f\x09\x72\x00\x18\x83\x8c\ -\x13\x91\x97\x9a\xce\x69\x82\x09\x26\xf8\x7f\xe0\x6f\x3e\x50\x4e\ -\x18\x86\xf9\x70\xa3\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ -\x82\ -\x00\x00\x03\x61\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x13\x49\x44\x41\x54\x78\x9c\xed\ -\x9a\xbf\x6b\x14\x41\x14\xc7\xbf\x6f\x93\x70\x9e\x04\x1b\x31\x46\ -\x72\x9b\xdd\x8d\xb9\x42\x08\xd8\xda\xfb\x03\xb4\xb0\x93\x80\x5d\ -\x0e\x44\x25\x9d\x4d\xc8\x5f\x60\x2c\x85\x04\xd1\x22\xa5\x4d\x6c\ -\x44\x48\x04\xb5\xb3\xb0\x15\x52\x08\xd1\xec\xde\xde\x82\x78\x62\ -\xa1\xa8\xe7\x91\xdc\x8c\x4d\x08\x78\xbb\x77\x97\xdd\xb9\x97\xc9\ -\xb9\xf3\x29\xe7\xe6\xbe\xef\xbb\xdf\xdb\x9d\x7d\xcc\x0d\x60\x30\ -\x18\xf2\x0c\xa9\x0a\xd4\xeb\xf5\xd1\x46\xa3\x39\x2f\x81\x1b\x00\ -\x66\x00\x14\xd4\x6d\x29\xd1\x04\xb0\x49\xc0\x5a\xb1\x58\x58\x19\ -\x1b\x1b\xfb\xd9\x6d\xb2\x52\x00\xd5\x6a\xf5\xb2\x84\xb5\x0a\xa0\ -\xa4\xa2\xc3\x48\x44\x10\x15\xc7\x71\x5e\x75\x9a\x60\x65\x55\x0e\ -\x82\xb0\x22\x61\xbd\xc4\xd1\xbd\x78\x00\x28\x49\x58\x1b\x7e\x18\ -\xce\x75\x9a\x90\xe9\x0e\xd8\x0e\xc3\x2b\x96\xa4\x0d\x28\x04\x78\ -\xc8\xb4\x08\xe2\x6a\xd2\x9d\x90\x3a\x80\x7a\xbd\x3e\xfa\xbb\xd1\ -\xfc\x00\x60\xa2\x2f\xd6\x0e\x8f\xe8\x78\xb1\x70\xae\x7d\x4d\x48\ -\xfd\x0b\x36\x1a\xcd\x79\x0c\xde\xc5\x03\x40\x69\xcf\xfb\x3f\xa4\ -\x0e\x60\x6f\xb5\x1f\x48\x92\xbc\x67\x79\x86\x67\xfa\xe0\x45\x17\ -\x31\xef\xc3\x19\x44\xba\xbe\xe7\x5d\xc7\x56\xee\x2d\x54\x08\xaa\ -\x35\xd9\xe5\xe3\x98\xf7\x41\x59\xc5\xd9\x30\x01\xe8\x36\xa0\x1b\ -\x13\x80\x6e\x03\xba\x31\x01\xe8\x36\xa0\x9b\xdc\x07\xd0\xb3\x11\ -\x0a\x82\xe0\x0c\xac\xe1\xbb\x90\xf2\x22\x80\xd3\x3d\xe7\x57\x6b\ -\x1f\x15\xfc\x48\x10\x22\x08\xac\xef\xec\xfc\x79\x5c\x2e\x97\x7f\ -\x28\x68\x1d\x88\xae\x5d\x5b\x18\x86\xd7\x85\xa4\x55\x00\x27\xb9\ -\x8d\x24\xe0\x4b\x41\x37\x3d\xaf\xf4\x2e\xcd\x97\x7a\x74\x82\xb1\ -\x4e\xb5\xe3\x23\xe0\x57\x6b\x4b\x42\xd2\x73\xe8\xb9\x78\x00\xf0\ -\xc8\x92\x6f\xfd\x30\xba\xc3\x59\x24\x31\x00\x3f\x0c\x67\x09\x58\ -\xe0\x2c\x7c\x40\x86\x48\xca\x65\xdf\x8f\x2e\x70\x15\x88\x05\xe0\ -\xfb\xbe\x4b\x92\x9e\x70\x15\xcc\xc0\x10\x59\xf2\xe9\xd6\xd6\xd6\ -\x09\x0e\xf1\xf8\x1d\x60\x0d\x2f\x02\x60\x29\xa6\x80\x37\x32\x72\ -\xec\x36\x87\x70\x2c\x00\x02\xae\x71\x14\x52\xc6\xe2\xf1\x95\xb4\ -\x06\x1c\xcd\x5d\x5e\xc9\xe3\x2b\xf5\x86\xc8\x90\x85\x32\x87\x91\ -\x5d\x60\x9a\x04\x36\xba\x4c\x61\xd9\x68\x49\x1d\x80\x6d\xdb\x2a\ -\x8d\x4e\x47\x6a\xb5\x1a\x5a\x1c\xc2\x3d\xc8\x7d\x2b\x6c\x02\xd0\ -\x6d\x40\x37\x26\x00\xdd\x06\x74\x63\x02\xd0\x6d\x40\x37\x26\x00\ -\xdd\x06\x74\x63\x02\xd0\x6d\x40\x37\x26\x00\xdd\x06\x74\x93\xe5\ -\x7c\x80\x2e\xce\xf6\xda\xf1\x3d\x00\xcd\xf6\x81\xbc\xdd\x01\x9b\ -\xed\x03\xb9\x0a\x80\x80\xb5\xf6\xb1\x3c\x05\x10\x15\x8b\x85\x95\ -\xf6\xc1\xbc\x04\xd0\x22\x88\x4a\xd2\xb9\xe1\x3c\x04\xd0\x92\x24\ -\x6f\x75\x3a\x2f\x3c\x48\x6f\x81\x2c\x44\x04\x51\x71\x27\x3b\x1f\ -\x96\xfe\x1f\x03\xd8\x3f\x2e\x5f\x28\x8c\x2c\x8f\x8f\x8f\xff\xea\ -\x36\x39\xb6\xd5\xdc\x87\x77\x2d\x17\x9f\x5c\xc7\x9e\xee\xb7\x68\ -\x7c\x0d\x90\xf8\xda\xef\x22\x7d\xe2\x0b\x87\x68\xd2\x22\xf8\x9a\ -\xa3\x90\x32\x44\x6f\x38\x64\x63\x01\x08\x41\x0f\x00\xec\x70\x14\ -\x53\xe0\x1b\xc4\xee\x23\x0e\xe1\x58\x00\x53\x53\xa5\xf7\x92\xe8\ -\x28\x9c\x0d\xd8\x87\x60\xcd\xb9\xae\xfb\x99\x43\x3b\xb1\x0f\x70\ -\xed\x89\x87\x00\x9e\x71\x14\x4c\x0b\x01\x4b\x8e\x33\xf1\x82\x4b\ -\x3f\x31\x00\x22\x12\xce\x64\x69\x56\x12\xdd\x83\xbe\xc7\xe1\x3b\ -\x81\x66\x1d\xc7\x5e\xe4\x2c\xd2\xf3\x1f\xd7\xed\xed\xe8\xbc\x65\ -\xc9\x05\x00\x97\x40\x38\xc5\x69\x66\x8f\x48\x02\xeb\x10\xbb\xf7\ -\x3d\xcf\x0b\x0e\xa1\x9e\xc1\x60\xc8\x31\x7f\x01\x50\x46\xc4\x66\ -\xcc\x07\x14\xea\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\ -\x00\x00\x00\x97\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x49\x49\x44\x41\x54\x58\x85\xed\ -\xce\xc1\x09\xc0\x30\x0c\x04\x41\xc9\x49\xdf\x71\x4d\x6e\x48\x08\ -\xd5\x11\xec\x22\xce\xa0\xcf\xce\xff\x8e\x35\x13\x44\xd6\x8c\xac\ -\xa9\x7c\x0c\x65\x7c\x03\x01\x04\x10\x40\x00\x01\x04\xb4\x07\xbc\ -\xea\x81\x9b\x7d\x91\xd5\x13\xe0\xfb\x59\xdb\x7f\xe5\x02\x00\x00\ -\xf4\x3b\x2b\x9a\x0d\x40\x4d\xe0\x05\x89\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x85\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x37\x49\x44\x41\x54\x58\x85\xed\ -\xce\xc1\x0d\x00\x30\x08\x03\x31\xd4\xc9\xd9\x14\x21\x16\xe9\x10\ -\xf0\xf4\xfd\x13\x39\x62\x51\xf5\x64\xf5\xe4\xe6\xe3\x6d\xc6\x17\ -\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x7c\ -\x9f\x23\x06\x85\x22\x0f\x12\xcb\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x05\x38\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\xea\x49\x44\x41\x54\x58\x85\xe5\ -\x97\x5b\x6c\x54\x55\x14\x86\xbf\xb5\x67\x3a\x20\x24\xe5\x22\x46\ -\x04\x2a\xd0\x80\x29\x04\x4c\x04\x25\x01\x82\xa2\xd0\xd6\x8a\x40\ -\x29\x39\x1a\x52\x22\xf6\x02\x21\x26\xfa\x60\x82\x82\x10\x27\x0d\ -\x0a\xf5\xc5\x04\x45\x94\xda\x16\x8d\xf2\xc2\xf4\xa2\x6d\x28\xd0\ -\x01\xd2\xbe\x80\x04\x6b\x43\xc0\x42\x62\x2c\x17\x4b\xab\x31\x10\ -\x30\x8a\xb4\x9d\xd9\xcb\x87\x99\x29\x67\x7a\x6f\xf1\x8d\xf5\x74\ -\xf6\xda\xeb\xfc\xff\xbf\xd7\xd9\x6b\xaf\x7d\xe0\x41\x37\x19\x4a\ -\x70\xda\xea\x9c\x24\xeb\xf1\x66\x8a\xb1\xcb\x51\x49\x02\xa6\x00\ -\x46\xe0\xba\x42\x0b\xaa\xf5\x88\xb7\x32\x58\xbe\xff\x97\xff\x55\ -\x40\xba\x93\xb7\x20\x6c\x4d\xa1\xa0\xcf\x0f\x12\xf7\x2c\xa2\xdb\ -\x82\x65\x25\x27\xee\x4b\xc0\x72\x67\xd3\x18\xb1\xf6\x73\x60\x5d\ -\xd4\xd5\xa6\x50\x6d\xd0\x23\x61\xa4\xd9\x67\xc2\x6d\x1d\xa1\xb0\ -\xf5\x9a\x11\x13\xc3\x6a\xa7\x89\x48\x1a\xb0\x1a\x98\x1a\x8d\xaf\ -\xb1\x9d\xe4\x9e\xa8\x2a\xfe\x63\xc8\x02\xd2\x9d\xbc\x19\xd6\x4a\ -\x15\x30\x2b\x42\x2c\xfe\xd0\x8d\x49\x07\xea\xea\x0a\x42\xfd\x89\ -\xf6\xfb\xfd\xe6\xd4\x85\xeb\xaf\x02\x1f\x00\xc9\xc0\x35\x63\xed\ -\xaa\x63\x95\xa5\xe7\x06\x2d\x60\x59\x56\x4e\xb2\xc1\x73\x06\x61\ -\x82\xc0\xf7\x9e\x91\xff\xbe\x76\xe4\xe0\xc1\xbf\xfa\x23\xee\x6e\ -\x19\x19\x6f\x8e\xe8\x1c\x75\x77\x9f\xa0\xb9\xc0\x3f\x8a\x2e\x39\ -\x5e\x5e\xd2\x38\xa0\x80\x8c\xec\xec\xc4\xd0\xdd\x51\xa7\x41\x67\ -\x83\xee\x59\x34\x67\xca\xdb\x05\x05\x05\x76\x28\xe4\x6e\xfc\xb4\ -\xac\xbc\xad\x2a\xb2\x0b\x68\x31\x6a\x16\x1c\xab\x28\x6a\x73\x07\ -\x78\xbb\xbf\x11\xba\x3b\x6a\x6f\x84\x9c\xea\xde\xc8\xd3\x56\xe7\ -\x24\xa9\xd7\x9b\x0f\xfa\x12\xf0\xb8\x80\x55\xf4\x2a\x22\x87\x8d\ -\x35\xc5\xdd\x08\xb4\xb6\xa2\xa4\x30\x35\x2b\x3f\x19\x21\xdf\x1a\ -\xfb\x2d\xb0\x1c\xd0\x5e\x33\x90\xba\x36\xf7\x69\x30\x67\x81\x3f\ -\xd5\x98\x99\xc7\x03\x45\xb7\x63\x73\x7e\xbf\xdf\x9c\x3e\xdf\xf2\ -\xae\x8a\xbc\x0f\x8c\xec\x63\xc5\xff\x08\xbc\x57\x5b\x5e\xfc\xa9\ -\x9b\xc4\x71\x1c\xdf\x2d\x3b\xe6\x1c\x90\x02\xac\x08\x96\x17\xd7\ -\xc4\xe6\x4c\x5c\xbe\x30\xbb\x01\x54\x65\x67\x77\xf2\x53\x17\xae\ -\x7f\x1d\x4d\x65\x5f\xe4\x00\xa3\x15\xf6\xa4\xae\xcd\xdf\xe7\x5e\ -\x5c\x20\x10\xe8\x50\x61\x7b\x74\x58\xe8\x9e\xeb\x12\x90\x9e\xb5\ -\xe9\x31\x85\x65\xc0\xcd\x71\x9e\x5b\xfb\xdd\xa8\xa7\x2e\xb4\xec\ -\x00\xd6\xdf\x5b\x53\x3f\x16\x89\xd9\x9c\xba\x76\xe3\x5b\x6e\xf7\ -\xf1\xb2\xe2\x4a\xe0\x12\x30\x37\x7d\x4d\xee\x93\x3d\x04\x28\x76\ -\x65\x44\x99\x1c\x0e\x04\x02\x1d\x31\xff\xb2\xac\x9c\x64\x90\x1d\ -\xc0\xe0\x8e\xad\xae\x18\xfd\x30\x75\x55\xee\xa4\x38\x69\x22\x55\ -\x00\xea\x31\x6b\x7a\x0a\x10\x96\x02\xa8\xda\xa3\x6e\x3c\x63\x3c\ -\x6f\x00\x09\x83\xa0\xee\x6e\xa3\xd5\x6b\x36\xc6\x69\x0b\xeb\x31\ -\x00\xab\xbc\xd0\x43\x00\xaa\x49\x11\x75\x7a\x39\x0e\x46\x59\x31\ -\x0c\xf2\x08\xa1\xf0\xb2\x7b\x6c\xd4\xdb\x0c\x20\x91\x1e\xd2\x4d\ -\x80\x44\x9c\x09\x9d\x3e\x77\x19\x09\x91\xd3\x6c\xb8\x36\xd5\x3d\ -\x90\xf6\x84\x18\xf6\xe4\x28\x76\x7c\x15\x74\x37\xbf\xdf\x2f\x03\ -\xc5\x0c\x60\x9e\x01\xb0\xdd\xe0\x72\x1d\x20\x64\x42\x13\x63\x9e\ -\x82\x82\x02\x2b\x70\xf5\x3e\x04\x5c\x73\x0f\xda\x1f\xba\x13\xc5\ -\xd6\xd6\xd8\x01\xe7\xde\x03\xbf\x01\x88\x30\x3d\x0e\x42\xa8\x61\ -\xb8\xa6\xf1\xef\x26\xa0\xc9\x51\x7f\x4b\xcc\x77\x4f\x80\xa1\x2e\ -\xfa\x94\xee\x7e\x29\x2c\xe1\x2f\x80\xe1\xf4\x82\x0e\xf1\x50\x1c\ -\xa7\x47\x4c\x1a\x00\x62\x4e\xf6\x14\xd0\xa1\xd5\x51\x75\x2b\xe6\ -\x6f\xda\xd4\x55\x76\x27\x02\x07\x9a\x44\xf8\x24\x3a\x37\xa0\xc5\ -\x42\x54\xd9\x55\x1b\x28\x76\x57\x94\x28\xb2\x2a\xca\x5a\xd9\x43\ -\x40\xb0\xaa\xb4\x15\xe1\x24\xc2\x84\x71\x37\x6c\xbe\x1b\xf4\xc6\ -\x78\xf3\x0e\x50\x33\x98\x83\x48\x22\x2a\x02\x8b\xe7\x4e\xde\xe9\ -\xf6\xa7\x66\x6d\x5c\x19\x6d\x72\x3f\x07\x03\x5f\x76\xdd\x0d\xe2\ -\x76\xb8\xb5\xb2\x15\x40\x04\x7f\x46\x76\x76\x62\xcc\xdf\x50\x54\ -\xd4\x79\xf3\x61\x93\x09\xba\x87\xfe\x3f\x47\x08\x65\xd7\x58\xcf\ -\xed\x75\xee\x2e\xea\x38\x8e\x0f\x61\x77\x44\xa0\x6e\xc3\x95\xcb\ -\xb8\x32\xb9\x7c\xf1\xa7\xd6\xe4\x59\xf3\x66\x0a\x2c\xd4\x50\xc2\ -\xec\xf5\xaf\xac\x3c\x54\x5f\x5f\xaf\x00\x6d\x0d\x0d\xb6\xf9\x62\ -\xe3\xd1\x19\x29\x4f\x55\x20\xa2\xc0\x23\x40\x22\x60\x05\x2e\x83\ -\x7e\xe3\x31\x9a\x5b\x5b\x5e\x72\xa8\xa9\xa9\xc9\xfd\xb1\x64\x72\ -\xca\xe2\xcf\x10\xcd\x00\xea\x82\xe5\x25\xdb\xdd\x9c\x3d\x92\x1a\ -\xbd\x07\xfe\x00\xa4\x80\x7e\xbc\x68\xce\x94\x2d\x7d\x5d\x48\x1c\ -\xc7\xf1\x00\x04\x02\x81\x70\x1f\x19\x91\xd4\xac\xbc\x2d\x88\x7c\ -\x84\xd0\x4a\x87\x7d\x26\x58\x55\xda\xda\xaf\x00\xe8\xba\x0f\x9e\ -\x01\xc6\x03\x15\x9d\xc6\xb7\xa1\x2e\xb0\xef\xef\x3e\x48\x7a\x35\ -\xc7\x71\x7c\xb7\x6d\xe2\x5e\x45\x36\x02\x77\xc0\x3e\x17\x2c\x2f\ -\xfd\xb1\x7b\x5c\xaf\x27\xd5\xaf\x4d\x8d\x37\xa7\xa7\xcc\xff\x0e\ -\x21\x4d\x60\x89\x47\xc3\x1b\x66\xcc\x9a\x77\x3b\xe9\xd1\x95\xe7\ -\xaf\x5c\xa9\xef\xb7\x24\xfd\x7e\xbf\x49\x98\xf0\x84\xd3\xae\xbe\ -\x32\x90\x54\x22\x57\xb1\xb4\xda\x8a\xe2\x86\xde\xe2\xfb\xdd\xd7\ -\x4b\x33\x5f\x1f\x9b\x60\xbc\x45\x08\x4e\xd4\xd5\x22\x50\x0d\x7a\ -\x44\x30\xcd\x18\xdb\xd6\xde\x19\xb6\x3e\x8f\x6f\xa2\x45\xa7\x02\ -\xe9\x82\xae\xa6\xab\x7f\x48\x6d\xa7\xe9\xdc\x50\x17\xf8\xea\xf7\ -\xbe\x38\x06\xf5\x63\xb2\xcc\xc9\x5d\x68\xac\x29\x04\x9e\x1d\x4c\ -\x3c\xd0\x88\xd8\xad\xc1\xb2\xd2\xda\x81\x02\x87\xf4\x6b\xf6\x62\ -\xe6\xe6\x69\x21\x13\xca\x14\x23\xcb\x45\x35\x49\x23\x6d\xd5\x03\ -\xb4\x00\x2d\xa2\x5a\x8f\x78\x2a\x6b\xcb\x8b\x2e\x0d\x05\xf7\xc1\ -\xb6\xff\x00\xf7\x80\xda\xb0\x80\x19\xdd\x42\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xcc\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x7e\x49\x44\x41\x54\x78\x9c\xed\ -\xd9\x41\x0d\xc0\x20\x14\x05\x41\x5a\x4d\x78\xc2\x4f\x65\xd5\x14\ -\x95\xb1\x4d\x98\x31\xf0\x5f\x36\xdc\x18\x23\x34\xd7\xb3\xe7\x7a\ -\x76\xb9\xe1\x2e\x8f\xff\x81\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\ -\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\ -\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\ -\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\xda\xf1\ -\x01\xae\xf2\x78\xfd\x35\x3e\x46\xff\x02\xde\xf8\x3e\x00\x00\x00\ -\x00\x00\x00\x00\x9c\xe0\x03\xda\xaf\x07\x8e\xa0\xaf\x15\x04\x00\ -\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x68\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x1a\x49\x44\x41\x54\x58\x85\xed\ -\xc1\x01\x01\x00\x00\x00\x82\x20\xff\xaf\x6e\x48\x40\x01\x00\x00\ -\x00\xef\x06\x10\x20\x00\x01\x47\x01\xa0\x88\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\xf7\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xa9\x49\x44\x41\x54\x58\x85\xed\ -\x96\xb1\x4a\xc3\x50\x14\x86\xff\x93\x64\xb1\x05\x5f\x40\xd4\x37\ -\xa8\x60\xa1\x11\x41\x7c\x03\x29\x0d\x2a\x5d\x7c\x01\x5d\x04\x11\ -\x97\x4e\x1d\x1c\x44\x97\xe2\x13\x38\x59\x49\x3a\x17\x17\x41\x0a\ -\x86\x52\xb0\x8f\x50\x3b\xb8\xb8\x28\xd4\xa9\xb9\xc7\xa1\x26\x36\ -\xb5\xb7\x4d\x4c\x6b\x86\xf6\x9f\x6e\x92\x73\xcf\xff\xe5\xdc\x7b\ -\x0f\x17\x98\x75\xd1\xa8\x8f\xa9\x2a\x27\x13\x1d\x51\x64\x50\x0e\ -\xc0\x6a\x44\xaf\x16\x83\x4d\x47\x53\x0a\x8d\x1d\xfa\x1c\x0b\x90\ -\xaa\x72\x72\xa1\xc3\x35\x00\x6b\x11\x8d\x07\xd5\xec\x6a\xb4\xe9\ -\x42\x28\xb2\xa8\x44\x47\x14\xa7\x60\x0e\x00\x6b\x6a\x57\x14\xdd\ -\x07\x29\xc0\x77\xd9\xa7\x22\x02\x19\xee\x58\x1b\x11\xe7\x5b\x73\ -\x3b\xa7\x8c\xdc\x2f\xe3\xa4\x5b\x82\x87\xe5\x96\x56\xe0\xbf\x34\ -\x07\xf8\xb5\x07\xd2\x65\x5e\xd1\x54\x6c\x03\xec\x7b\x9f\xa9\xf0\ -\x91\x2c\x09\x09\x08\x02\x9a\xcb\x0e\x9e\xee\xf6\xc8\xf9\x33\x80\ -\x6e\xf1\x09\xc0\xe7\xc3\xc0\x88\xb9\x24\xcd\x42\x3d\xdc\x17\x0d\ -\x8f\x69\x93\xf7\x1b\x06\xbd\x06\x05\xf0\x96\x20\x53\xe1\x3c\xc0\ -\x17\xc3\xcc\x43\x68\x4b\x23\xbe\xdd\x2d\xb3\x1a\x1a\x80\x98\x4f\ -\x23\x18\xfb\x20\xda\x2a\x36\x82\x06\xf7\xff\xed\x40\xd7\xe3\xeb\ -\xe0\x9e\x94\x05\xb0\xe4\xcd\xec\xe5\xaa\x85\x05\xf0\x35\x1a\x3b\ -\xa7\x4a\x37\xdd\xa0\x74\xcb\x01\x40\x87\x1e\x80\x12\xfc\x74\xc5\ -\x7e\x0c\xe7\x00\x73\x80\xd8\x01\xa2\x74\x3d\xa9\x88\xb9\xa4\x5b\ -\x42\xde\xba\x81\x96\x3b\x88\xa5\x02\x0c\x36\xe3\x04\x68\x3a\x9a\ -\x52\x88\x03\xa0\xc5\xe0\xab\xfe\x1b\x31\xd0\xd7\x7e\x75\x4b\xbc\ -\x03\x58\x9c\x88\x15\xd3\x81\x6d\xd0\x4d\x90\xd0\x9f\x0a\x30\xee\ -\x27\x62\x0e\x74\x85\x8a\x87\xa0\xc1\x1e\x80\x50\xe9\x18\xc0\x5b\ -\x64\x7b\xa6\xb3\x7a\x96\xda\xa1\x01\xea\x59\x6a\x0b\x85\xd6\xc1\ -\x30\x01\x7c\x84\xb5\x05\xf0\x0c\x50\xde\x36\xe8\x32\xe4\xdc\x19\ -\xd7\x17\x91\x1d\x7b\x32\x62\xe5\x6b\x14\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x94\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x46\x49\x44\x41\x54\x58\x85\xed\ -\xd1\x21\x4b\x43\x51\x18\xc6\xf1\xff\x7b\xc7\x8a\x41\x04\x41\xcb\ -\x76\xdd\xf6\x09\x04\x6d\x36\x93\xa8\x6b\x82\x49\xab\x82\xdf\xc1\ -\x62\x31\xf8\x11\x64\x20\x18\x0c\x26\x41\x10\x8b\xa0\x08\x86\x15\ -\xc1\xec\x7d\xcf\x3d\xd7\xee\x98\x60\x71\x7b\x2d\x1a\x14\xb6\xbb\ -\xbb\x24\x78\x7e\xf1\xf0\xf0\xf0\x1c\x5e\x08\x82\x20\x08\xfe\x3b\ -\xc9\x0b\x68\xea\x8f\x31\x16\x22\xb1\xad\x38\x8e\x9f\x46\x29\x4d\ -\x92\xa4\x26\x51\xe9\x14\xa4\x33\x17\x57\xd6\x45\xc4\x06\x65\xa3\ -\xdc\x36\x63\x0a\x98\xef\x9b\xdc\xab\x66\xcb\x79\x71\xe7\xdc\x82\ -\x44\xe5\x07\x90\x25\x8c\xe9\xbc\x7c\xee\x80\x52\xc4\x16\x70\x0e\ -\x4c\x22\x76\xe5\x5c\xb6\x3d\x28\xab\x9a\xad\x19\xd1\x2d\xd8\x2c\ -\x70\x63\xf6\xb1\x32\xec\xf7\x23\x0d\xa8\x56\xab\xef\x73\x71\x65\ -\x13\xe1\x08\x28\x1b\x76\xe2\x9c\xdf\x37\xb3\x1f\xe7\x4b\xd2\x6c\ -\x17\xb1\x0b\x60\x02\x38\x7d\xeb\x76\x56\xea\xf5\xfa\x6b\x5e\x7f\ -\x21\xaa\xe9\x9e\x3a\xdf\x53\xe7\x4d\x35\x6b\xb5\xdb\xed\xb2\x99\ -\x45\x89\xf3\x87\xea\xbc\xa9\xf3\xa6\x69\x76\xf0\x7b\xdc\x30\x23\ -\x07\xbf\x39\xf7\xd2\x34\xfa\x67\xc0\x84\xc1\x9d\x40\x17\x58\x05\ -\x3e\x30\xdb\xa9\xd5\xe2\x56\x91\xbe\xc2\x03\x00\xd2\x34\x5d\xec\ -\x9b\x5c\x02\x33\x5f\x4f\xdd\xbe\xd8\x46\x23\x8e\xaf\x8b\x76\x8d\ -\x35\x00\x40\x55\xeb\x48\xe9\x59\xc0\xf7\x7a\xd2\x6c\x34\x2a\x8f\ -\xe3\x76\x8d\xcd\xcc\xa4\xc8\xbd\x83\x20\x08\x82\x3f\xe9\x13\xfa\ -\xca\x87\x49\xdf\x83\x3a\x35\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x04\x83\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x35\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4b\x88\x1c\x55\x14\x86\xbf\x53\xdd\x93\x31\x24\x41\x88\xf1\ -\x85\xa8\x2b\x51\x5c\x08\x43\xb7\x11\x11\x64\x14\x8d\x06\x31\xf8\ -\x00\x5d\x89\x4e\x30\xd3\x1d\x92\x9e\x76\x40\x11\x7c\xd0\x36\x89\ -\x98\x80\xf8\xe8\x36\xa6\x7b\x0c\x18\x17\x06\x75\x15\x06\x34\x3a\ -\xba\x48\x40\x90\xcc\x74\xe2\x03\x71\x21\x88\xb8\xd0\xa8\x84\x28\ -\x9a\x09\x66\x66\xba\x7e\x17\x6d\xa0\xaa\x18\x83\xd1\x7a\x5c\x4c\ -\xff\xcb\xff\x40\xdd\x73\xbf\x3a\x7d\xef\x3d\x55\xd5\xd0\x57\x5f\ -\x7d\x9d\xcd\xb2\xac\x13\xf8\xa7\x2a\x8e\x36\x6b\x66\x7a\x4a\x60\ -\x48\x5b\x3b\x13\xd5\x67\xe2\xb8\xae\x17\xc7\x45\x92\x56\x61\xf4\ -\xe5\x9b\x30\x6a\x82\x3c\x90\xc3\xec\xe9\xb8\xae\xed\x3c\x80\xd5\ -\xa5\x66\xd1\xcc\x26\x41\xc1\x6a\x8d\x2d\x6f\xa7\x01\x14\x46\x9b\ -\x57\xf9\x68\x1f\xb0\x3c\xe8\x0b\xfc\xb8\xc6\x70\x16\x40\x61\xf4\ -\xa5\xcb\xcc\x34\x05\xac\x8a\xc6\x0c\x14\xd7\x38\xf9\xb8\x2e\x14\ -\xa7\x86\x46\x1a\xe7\x9b\x31\x05\x5c\x9a\xf4\x58\xce\x55\xc0\x0d\ -\xeb\xb7\xaf\xc8\x2d\xe1\x3d\xe0\xca\x34\xc6\x73\x0a\xc0\xf0\x43\ -\xaf\x9f\x33\x37\xb0\x74\x2f\x50\x0c\xfa\x8a\xb1\xe4\xa3\x72\x06\ -\xc0\x70\xad\x96\xff\x7d\xf0\xf8\x1e\xc1\xcd\x91\x90\x2c\xc6\x45\ -\x2f\x2a\x47\x00\xc8\x8e\x1f\x39\xaf\x6d\xe8\xee\xb0\x6f\x22\xc1\ -\xc9\x83\x23\x00\x8a\xa5\xe6\x76\x8c\xf5\x41\x4f\x98\x40\x89\x4e\ -\x1e\x1c\x00\x50\x28\x35\x1e\x07\x1e\x8b\xfa\x96\xc2\xe4\x21\x63\ -\x00\xd7\x96\x1b\x1b\x0c\xb6\x2d\x12\xea\xa6\x95\x43\x66\x00\x8a\ -\xe5\xe6\xbd\x12\xad\xa8\xaf\x94\xee\xfc\x29\x65\x02\xa0\xb8\xa1\ -\x71\x0b\xd2\x9e\x45\xc6\xf7\xad\xb7\xf0\xa5\xa6\xd4\x01\x14\xcb\ -\x8d\xd5\x78\xec\x05\x96\x04\x7d\x19\x3e\x09\xee\xf7\x7f\xa7\x54\ -\x01\x5c\x57\x6a\x5c\x8d\xd8\x07\x2c\x8b\x84\x7c\x53\xfa\x93\x87\ -\x14\x01\x0c\x6d\x7a\xe5\xf2\x05\x6c\x0a\x58\x19\xf4\xff\xea\xec\ -\x32\x99\x3c\xa4\x04\xe0\x9a\xf2\xce\x0b\xbc\x05\xff\x43\x43\x97\ -\x04\x7d\x81\x1f\x67\x67\xf7\x6f\x94\x78\x37\x58\x18\x6d\x9f\x6b\ -\x3a\xf9\x3e\x70\x45\xd0\x57\xef\x88\x9b\xe9\xe4\x21\xe1\x0a\xb8\ -\x7e\xfc\x85\xa5\x66\x73\x93\xc0\x50\x28\x20\x4b\xf4\x7c\x7f\x26\ -\x4a\x0c\xc0\x70\xad\x96\x9f\x9f\xcd\xbf\x05\xba\x31\xe8\xab\x77\ -\xca\x75\x62\xf2\x90\x14\x80\x5a\xcd\x9b\xfd\x69\xd5\x2e\x8c\x75\ -\x41\x5b\xb8\x73\xe7\x4f\x29\x01\x00\xb2\xe2\x91\x95\xcf\x4b\x7a\ -\x30\xec\xbb\x37\x79\x48\x60\x11\x2c\x96\x1b\x4f\x20\x1b\x0f\x99\ -\x12\x98\x7b\x93\x87\x98\x2b\xa0\x50\x6a\x96\x91\x6d\x0d\x99\x02\ -\x33\x4b\xad\xb9\x39\x53\xc5\x06\xa0\x58\x6a\x6c\x33\xb4\x33\xea\ -\xcb\xf0\x33\xdf\xeb\x4e\xa3\xf8\x2a\x20\xf2\x40\x03\x7a\x9d\x9d\ -\x0b\x7b\xfd\xe9\x14\x1f\x00\xa5\xd7\xc3\xc7\xa9\xd8\x00\x98\xa9\ -\x4a\xe4\x6e\x1b\xe6\xb9\xfe\xfa\x35\x36\x00\x33\xad\xea\x3b\x48\ -\x95\xa8\x2f\x91\x73\x19\x42\xac\xbb\x40\x67\xa2\xba\xc3\xa0\x16\ -\xf4\x0c\x40\xca\xb9\xfa\x26\x3e\xf6\x83\xd0\x4c\xbb\xb2\x05\xac\ -\x19\x76\x0d\x50\xe6\x0f\x60\x17\x53\x02\x49\x99\x3a\x17\x1d\x7d\ -\x44\xf0\x66\x34\x90\xcc\x78\xff\x4d\xc9\x24\x54\xaf\xfb\x68\x70\ -\x04\x78\x37\x12\x31\xe4\x16\x84\xc4\x92\x39\x34\x51\x9a\x97\x06\ -\xef\x03\x3e\x0e\x05\x0c\x03\x73\x06\x42\xa2\x89\x1c\x9a\x28\x9d\ -\x58\x38\xd9\xbd\x53\xf0\x79\x38\x22\x67\x7e\x0e\x89\x27\xf1\xd9\ -\xee\xf1\x5f\xbd\x5c\xee\x76\xe0\x9b\x48\xc8\x7a\xd5\x90\xad\x52\ -\xb9\x0b\x33\xaf\x6e\xfa\xd1\xeb\xda\xad\x88\x1f\x42\x01\xe1\x29\ -\x63\x08\xa9\x95\xe1\xf4\xae\xca\xb7\x78\xba\x0d\xf8\x25\xe8\x9b\ -\xf0\x7a\x8f\x0a\xb2\x51\xaa\xbf\xc3\x4e\xab\xfa\xa5\x87\x77\x07\ -\x70\x22\x14\x90\x79\x22\x1b\x08\xa9\x2f\x44\xd3\xed\xcd\x9f\xf8\ -\x66\xf7\x00\xf3\x41\xdf\x30\x4f\x19\x54\x42\x26\x2b\xf1\xe1\x56\ -\xe5\x03\xc3\x1e\x20\xda\x3c\xc9\x3c\xa5\x7c\x66\xce\x6c\x2b\x9a\ -\x69\x57\xde\xc6\xd8\x18\xf5\x4d\x78\x69\x12\xc8\x74\x2f\xee\xb4\ -\xc6\xda\x88\x27\x43\xa6\x81\xa4\x5c\x5a\x39\x64\x7e\x18\xe9\x4c\ -\x54\x9e\x43\x7a\x31\x64\x9a\xa1\x94\x4e\x8b\x99\x03\x00\x53\xe7\ -\xe2\x63\x8f\x9a\xd9\x1b\x21\x17\xa5\xd2\x37\x38\x00\x00\xa8\xd7\ -\xfd\x65\x17\x1e\x7d\x18\x31\x19\xf2\x2d\xf9\x0e\xd2\x0d\x00\xc0\ -\xfe\x7a\x7d\x61\xf9\xdc\x8a\xfb\x31\x0e\x44\x42\xa6\x04\xf3\x74\ -\x06\x00\xc0\xfe\xdd\x23\x7f\xe4\x06\x58\x07\x1c\x0e\xfa\x96\xe0\ -\xd6\xe8\x14\x00\x80\x83\xcd\xb1\xdf\xe6\x6c\x60\x2d\xf0\x75\x1a\ -\xe3\x39\x07\x00\xe0\x8b\xd6\xc6\x9f\xbb\x79\x6f\x8d\xb0\xef\x93\ -\x1e\xcb\x49\x00\x00\x9f\xee\xd8\xfc\x5d\x1e\xad\x01\x8e\x45\x63\ -\x71\x9e\x16\x9d\x05\x00\x70\xb0\x3d\xf6\x15\xc6\x5a\x60\x36\xe8\ -\xdb\xd9\xf2\x97\x19\x80\x4e\x6b\x6c\x1a\x9f\xbb\x14\xf8\x7e\x30\ -\xce\x8f\x29\x9d\x07\x00\xd0\x79\x6d\xec\x23\xd0\x16\xb0\xae\x89\ -\x2e\xe6\x3d\x9b\x75\x4e\x7d\xf5\xd5\xd7\xff\x43\x7f\x02\x97\x76\ -\x3e\x83\x62\x89\x8e\x83\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ -\x60\x82\ -\x00\x00\x00\x89\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3b\x49\x44\x41\x54\x58\x85\xed\ -\xcd\xb1\x11\x00\x10\x10\x05\xd1\x4f\x21\x28\x45\xa2\x6b\x33\x5a\ -\x31\x14\x72\x22\xa1\xf4\x12\xfb\xa2\xcd\x56\x02\x00\xe0\x77\xe1\ -\xc6\x5c\x7b\xc8\x54\x7d\xb6\xd6\x4b\x4e\x4d\x92\xa2\xcf\x10\x00\ -\x00\xe0\xed\x00\x5a\x36\x07\x04\x97\xc1\x22\x16\x00\x00\x00\x00\ -\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\xca\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\x7c\x49\x44\x41\x54\x58\x85\xed\ -\x97\x4b\x72\xd3\x40\x14\x45\xcf\x73\x32\x00\xb6\x10\x59\x2d\xcd\ -\x60\x0b\x6c\x81\x01\x90\x00\x81\x90\x8a\xf3\x71\x15\x2c\x20\x55\ -\xac\x81\x61\x66\x0c\x20\xc4\xf9\x3b\x21\x14\x55\xac\x81\x35\xc0\ -\x08\xb7\x24\x03\x3b\x00\x06\xc4\x8f\x41\xe4\x20\xeb\x63\x49\x2e\ -\x33\x82\x1e\x59\xaf\xba\xef\x39\x7e\x6a\x5b\x2d\xf8\xd7\x87\x0c\ -\x3f\x58\xfb\xe5\xa6\xca\xe0\x85\xc0\x55\x94\x67\x9e\xd7\x7c\x3b\ -\x4d\x90\xb5\xd1\x3c\xc2\x73\xe0\xa7\xd0\x78\x6a\xcc\xdc\x87\x51\ -\x81\x20\xfa\x08\x5c\x8f\x2f\x07\x2a\xba\xe4\xbb\x6e\x77\x1a\xf0\ -\x5e\x18\x3e\x14\x95\x03\xa0\x11\x97\x3e\x79\xa6\x79\x83\x44\x01\ -\x90\x2b\x89\x35\x0d\x51\x39\xec\x85\xe1\xe2\x5f\x80\x83\x70\xed\ -\x12\x74\x59\x54\xdd\x04\x06\xd3\x94\xe8\x85\xe1\x62\x06\x0e\x03\ -\x51\xd9\xcc\x08\x78\x5e\xf3\x4c\x45\x97\x73\x24\x0e\x26\x91\x88\ -\xe1\x87\x19\x38\xb4\x8c\x71\x4e\x33\x02\x00\xbe\xeb\x1e\xe5\x48\ -\xcc\xd4\x95\x28\xfc\xe6\xd0\x32\xa6\xb9\x9f\x9c\x2b\xe4\x0c\x6b\ -\xa3\x25\x84\xbd\x54\xc0\xb9\x20\x4b\xc6\x38\x27\xe3\xe0\x41\xd0\ -\x7f\xa0\xe8\x21\x30\x53\x06\x2f\x14\x98\x54\xa2\x00\xae\x02\x2b\ -\x79\xf0\xb1\x02\xb1\xc4\x63\x84\xdd\x2a\x12\x41\xd0\xbf\xaf\xe8\ -\x51\x1d\x78\xa9\x40\x89\xc4\xa3\xe1\x66\x9a\x14\x5e\x49\xe0\x02\ -\x10\x2d\x2b\x74\xf2\x24\x00\xf2\xe1\xd2\x32\xc6\xd9\x2b\xcb\xae\ -\x24\x30\x46\x62\xf8\x6b\x49\xd6\x2a\xc3\x6b\x09\x24\x24\x76\xc7\ -\xac\xab\x05\x87\xd4\xff\x40\xd9\x30\xa6\xb9\x2f\xb0\x02\x68\x01\ -\x7c\xb5\x0e\xbc\xb6\x00\x80\x2a\x3f\xf2\x04\xe4\xa2\xf6\xbd\x6e\ -\x5e\x2d\x01\x6b\xa3\x05\x84\xe3\xbc\x75\x0a\x0d\x45\x8f\x83\xa0\ -\x7f\xaf\x4e\x66\xe5\x3d\x10\x3f\xcf\xbb\xc0\xec\x08\x57\x04\x54\ -\x93\x39\xe7\x28\x8b\x9e\xd7\x3c\xab\x92\x5b\xa9\x03\x45\x70\x45\ -\xd6\x44\x59\x65\xf4\x96\xcc\x20\x74\xad\x8d\x16\xa6\x22\x60\x6d\ -\x74\xb7\x08\xee\x1b\xa7\x63\x8c\xb3\xab\xc8\xda\xa4\x12\x63\x05\ -\x62\xf8\x49\x06\x2e\xba\xee\x1b\xa7\x33\x2c\xf8\xc6\xe9\x14\x48\ -\x1c\x97\x49\x14\x0a\x8c\x85\xbb\xee\x4e\x7a\xbe\x6f\x9c\x8e\x8a\ -\xae\xa7\x24\x66\xcb\x24\x72\x37\x61\x2f\x0c\xef\x88\xca\x69\x55\ -\x78\x6a\xed\xaa\xa8\x6c\xa7\xb2\x7f\xc5\x1b\x33\x73\xd0\xcd\x74\ -\x60\x0c\x7c\xa3\x0c\x0e\xe0\xbb\xee\x8e\x8a\x6e\x90\xed\x44\xd7\ -\xda\x68\x3e\x3d\x7f\xa4\x03\xbd\x30\xbc\x2d\x2a\x6f\x0a\xe0\xaf\ -\xcb\xe0\xa9\xac\x35\x51\x79\x45\x49\x27\x12\xef\x05\xfd\x5b\x88\ -\xbe\x9b\x06\xfc\x4f\x66\xb8\x8e\xc8\xcb\xb4\x84\xd0\x98\x37\x66\ -\xee\x3d\x8c\x1c\x95\x75\x2b\x0d\x47\xb5\x3d\x29\x1c\xc0\xf3\xdc\ -\x6d\x54\xdb\xa4\x6e\x87\x32\xd8\x1a\x5e\x5c\x0a\xe8\xe8\x41\x54\ -\x51\x6d\x7b\x9e\xbb\x3d\x29\xbc\x44\xe2\x3c\x23\x20\x2a\x4f\x80\ -\xcf\xc0\x37\x41\x5a\xd3\x80\x27\x25\xe2\xa7\xe8\x57\xa0\xc7\x05\ -\xeb\xff\x00\xe0\x37\x93\x02\x62\x58\xa2\x39\x4a\x39\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xce\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x80\x49\x44\x41\x54\x58\x85\xed\ -\xd2\x21\x0e\xc2\x40\x14\x84\xe1\x7f\x96\x3b\x90\x70\x13\xe4\x9e\ -\x81\x0b\x20\x30\x1c\x09\x81\xc6\xd6\x22\xeb\x38\x0a\x49\xef\x40\ -\x07\xd5\x26\x0d\x09\xae\x5b\x33\x9f\x7b\x6f\x37\x99\x11\x0f\x22\ -\x22\x22\x36\xa6\xc5\x64\xab\xf6\xec\xd6\x0c\xec\x2b\x1f\x24\xff\ -\x14\x38\x76\xae\xb6\x1f\xc0\x61\xcd\x02\xc0\x50\xd0\xf9\x75\xd2\ -\x13\xa0\x4c\x5b\xdb\xb7\x06\xe1\x00\xfb\x11\xdf\xa7\xa1\xfc\xfb\ -\xd9\xc2\x5c\x40\xd2\x15\x78\x37\xc8\x1c\x3c\xea\x32\xe7\x2e\x9e\ -\x36\x38\xc2\x88\x88\x88\xcd\x7d\x01\x5e\x93\x20\x04\x37\xe4\x99\ -\xec\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x0b\x37\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x0a\xe9\x49\x44\x41\x54\x78\x9c\xed\ -\x5b\x7d\x70\x54\xd5\x15\xff\x9d\xbb\x9b\x4d\x22\xe6\x43\xc1\xaf\ -\x06\x3f\x30\xc8\x40\x43\xac\x12\xb4\xc6\xd2\xc8\x47\xb2\x18\x85\ -\x60\x36\xbc\x56\xb1\x68\x20\x9b\x08\x5a\xdb\xe2\xb4\x4e\x65\xa6\ -\xae\xb1\xda\xb1\x1f\x02\x23\xa3\x68\xd8\x40\x44\xa3\x6d\x97\x04\ -\x06\xac\x31\x5f\x76\x53\x14\x1c\x85\xd0\x22\x04\x18\x35\x44\xc5\ -\xd4\x56\x49\x42\x40\x20\xfb\x76\xdf\xe9\x1f\x21\xf0\xf6\xed\xdb\ -\xb7\x6f\x93\x5d\xa6\xd3\xf2\x9b\xd9\x3f\xde\xb9\xbf\x7b\xce\x79\ -\xe7\xdd\x77\xdf\xbd\xe7\x9e\x05\xce\xe3\x3c\xce\xe3\xff\x19\x74\ -\x2e\x8c\x14\x4a\x8b\x2e\x91\x15\x6b\x9e\x20\xce\x56\x18\x13\x09\ -\xb8\x16\xe0\x74\x10\xa5\x42\x81\x05\x84\x7e\x00\xfd\x20\xfe\x0c\ -\x0a\xf6\xb3\xa0\x0e\x41\xd8\xd6\xe4\x71\x1f\x8a\xb7\x6f\x71\x0b\ -\xc0\xcc\xbb\x2a\x32\x85\x35\x50\x2a\x98\x8a\x18\xb8\x7e\x98\x6a\ -\x0e\x31\x73\x03\x43\xd4\xb4\xd6\xaf\xdd\x09\x80\x63\xe9\x23\x10\ -\xfb\x00\xd0\xac\xe2\xb2\xd9\x24\xc4\xa3\x04\x9e\x11\x63\xdd\x7b\ -\x99\xb0\xa2\xf7\x62\xf1\xea\xae\xaa\x2a\x39\x56\x4a\x63\x16\x80\ -\xd9\x8e\xc5\x33\x14\x12\xbf\x03\x30\x35\x56\x3a\xf5\xc1\x5d\x04\ -\x3c\xd1\x54\x57\xbd\x01\x31\x18\x11\x23\x0e\xc0\xac\x22\xe7\x65\ -\x64\xc5\xb3\x44\xb8\xd7\x80\xa6\x30\xf0\x2e\x31\xbc\x0c\x3e\x20\ -\xc8\xf2\x09\x83\x7a\x64\x31\x70\x2c\x19\x14\xf0\x05\x90\x42\x24\ -\xd2\x40\x34\x0e\x8c\x09\x44\x9c\x0b\xa6\x02\x00\xc9\xe1\x14\x32\ -\xb0\xcd\x02\x5a\xda\x58\xb7\x76\xdf\x48\xfc\x1f\x51\x00\x66\x4b\ -\x65\x37\x2b\x0a\x6d\x06\x70\x85\xb6\x8d\x81\x63\x00\xde\x14\x44\ -\x5b\x03\x81\x81\xb7\x5a\x37\x6d\x38\x12\x8d\xee\x5c\x69\x59\xf2\ -\xa8\x40\xff\x4c\x82\x98\x0b\xe2\x22\x3d\x1b\x00\x4e\x01\x58\xdc\ -\x5c\xe7\x7e\x7d\x58\x37\x80\x11\x04\x20\xdf\x51\xb6\x80\x88\xd6\ -\x01\x48\x0c\x71\x8a\xe8\x39\x9b\xcd\xfa\xcc\x5f\x5e\x5b\xd3\x3b\ -\x5c\xfd\x6a\x48\x92\x64\xeb\x53\xd2\xca\x01\x3c\x0e\xe0\x52\x6d\ -\x3b\x01\x4f\xe7\x4e\xce\x78\xbc\xb2\xb2\x52\x89\x56\x77\xd4\x01\ -\x70\xb9\x5c\x62\xfb\xbe\xee\xa7\xc0\xfc\x98\xa6\x49\x01\x63\x9d\ -\x15\xa8\x6c\xa8\x77\x1f\x8e\x56\xaf\x19\x14\x15\x2d\x4e\x39\x61\ -\x15\x8f\x10\xe1\xe7\x00\x2e\x54\xb7\x31\x68\xb3\x5f\x24\x2c\xf4\ -\x7a\x5e\x38\x1e\x8d\xce\xa8\x02\xe0\x72\xb9\xc4\xf6\x0f\x0f\xd7\ -\x82\xe8\x6e\x8d\x96\x6e\x41\x5c\xdc\xe8\xa9\x7e\x3f\x1a\x7d\xc3\ -\x45\xa1\xc3\x39\xd6\x4f\xd8\x84\xd0\x09\x77\xb7\x35\xe9\xe4\xf4\ -\x86\xda\xda\x7e\xb3\xba\x2c\xd1\x18\xb6\x8d\xbe\xae\x12\x44\x0f\ -\x69\xc4\xef\x09\x16\xb3\x1a\xeb\xdc\x07\xa3\xd1\x35\x12\x7c\xbc\ -\xbf\xbd\xff\xb2\xc9\xb7\xbd\x9a\xa0\xf8\xae\x21\x0a\x5a\x63\x5c\ -\x11\xf0\x27\x64\xe7\x4c\xce\xfc\x73\x47\x47\x87\xa9\x2f\x84\xe9\ -\x00\xd8\x1d\xce\x1f\x82\xb0\x5a\x23\x7e\x59\x4e\xf1\x4b\xad\xaf\ -\x57\xf7\x99\xd5\x13\x2b\x1c\xee\x78\xcf\xdf\xb9\xbf\x7d\x53\xe6\ -\xa4\x1b\x4f\x80\x28\x1f\xa7\x47\x33\x01\x13\x4e\x21\x39\xa9\xb3\ -\xa3\xbd\xc5\x8c\x1e\x53\xaf\x40\x41\xc9\xe2\xa9\x80\xd8\x06\x20\ -\x49\x25\x7e\xb5\xb9\xce\x7d\x1f\xe2\xb0\x3a\x8b\x16\xf9\x0e\xe7\ -\xcf\x88\xb0\x52\x2d\x63\xc2\xfd\x2d\x1b\xdd\x1b\x22\xf5\x8d\x18\ -\x80\x59\xc5\xf7\x8d\x16\xc2\xf6\x0f\x00\x19\x67\xb5\xe3\x7d\x39\ -\xd5\x7f\x9b\xb7\xa6\xe6\x54\x54\x8e\x16\x3b\x27\x91\x05\xc5\xcc\ -\xb8\x9e\x80\xb1\x18\xfc\x05\x00\x1c\x26\xe0\x30\x33\xda\xc9\x82\ -\xfa\x61\xec\x01\xa8\xc0\xe1\xac\x06\x61\x91\x4a\xe6\x13\x2c\x72\ -\x1b\xeb\xab\xda\x0d\x3b\x46\x74\xba\xa4\xbc\x9a\xc0\x8b\x55\x3d\ -\xba\xe1\x53\x6e\x6a\xde\xb2\xae\xdb\x8c\x67\x83\x9f\xb0\xf4\xa5\ -\x00\x2f\x01\x30\xd1\x4c\x1f\x00\xbb\xc1\xf4\x5c\xba\xa5\xef\x15\ -\x8f\xc7\x13\x30\xd3\xa1\xb0\xf0\xe1\x44\xff\x05\x27\xdf\x06\x70\ -\xeb\x90\x8c\x81\x76\xff\x91\x8c\xef\x7a\xbd\x95\xfe\x70\xfd\x84\ -\x91\xd2\x7c\xa9\x62\x5a\xd0\xcd\x03\xcc\x0a\x4a\xcc\xde\xbc\xbd\ -\xa4\xec\xae\x3e\x25\x6d\x1f\xc0\xab\x60\xfe\xe6\x01\xe0\x46\x10\ -\xaf\xef\x53\xd2\x76\xda\x8b\x9d\x33\xcd\x74\x68\x68\x58\x3d\xa0\ -\xc8\x70\x80\xf1\xf5\x90\x8c\x80\x29\xb6\xd1\x5f\x3c\x68\xd4\xcf\ -\x68\x12\xa4\xcc\x89\x37\xd4\x82\xe8\x2a\x95\xac\xb6\xa5\xde\xad\ -\x9d\x08\x43\x90\x53\x51\x91\x90\x75\xf5\x0d\xab\x41\xf4\x2c\x80\ -\x8b\x23\x7a\x1f\x1e\x97\x83\x70\xff\xf8\xac\x29\xf4\x23\x69\xee\ -\xdf\xda\xda\xda\x0c\xe7\x9b\x43\x07\xdb\xbf\xb9\x76\xd2\x14\x99\ -\x08\xb7\x9f\x11\x32\x6e\x1a\x3f\x35\xeb\x85\x4f\xf6\xec\xd1\xdd\ -\x40\x85\x1d\x01\x05\x52\x79\x1e\x88\xa6\xa9\x44\xb2\xc2\x01\x57\ -\x24\x8f\xef\x5c\xb0\xf4\xa2\x8b\x8f\x28\x0d\x44\x64\x18\xf9\x68\ -\xc0\x0c\xd7\xf6\x7d\x5f\xfc\x69\xce\x9c\x8a\x0b\x22\x71\xfd\xa9\ -\xfe\x17\x01\x7c\x76\x46\x40\x18\xc3\x27\x92\x1e\x08\xc7\x0f\xff\ -\x0a\x30\x7e\x11\x2c\xa0\x97\x5a\xeb\xd7\x77\x1a\x19\x97\x24\xc9\ -\xe6\x1b\x90\x37\x03\x98\x15\xc9\xd1\xa8\xc1\x98\xef\x4b\x0c\x6c\ -\x70\xb9\x5c\x86\xaf\xad\xb7\xa6\xe6\x14\x98\x34\x0f\x8a\x1f\x91\ -\x24\x49\x77\xb4\xeb\x2a\x9b\x2e\x95\x5e\x0e\xe6\xdb\x55\x22\x59\ -\x91\xf9\xa9\x08\x2e\x52\x5f\x20\xed\x79\x00\x79\x11\x78\xc3\x06\ -\x83\x4a\xb6\xef\xed\x8e\x38\x0a\xd3\x2d\x7d\xaf\x00\xfc\x91\x4a\ -\x94\xd1\xab\xa4\xe7\xeb\x71\x75\x03\x90\xa0\x24\x2c\x40\xf0\xfc\ -\xf0\x76\xeb\x16\xf7\xbf\x8c\x8c\x16\x94\x38\xef\x05\xc1\x19\xc9\ -\xb9\x91\x83\x1f\x9f\xe5\x28\xd7\xbd\x99\x21\x78\x3c\x9e\x00\x98\ -\x3c\x6a\x19\x81\xef\xd7\xe3\x86\x19\x4e\x3c\x37\xa8\x33\xd1\x16\ -\x23\x83\xa7\xdf\xcd\x67\x8c\x38\xb1\x84\x20\x5e\x11\x6e\x48\x0f\ -\x81\x48\x68\x7d\xbe\x43\xaf\x4f\x48\x00\xec\x0b\x17\x8e\x82\xea\ -\x5b\x0a\x00\x0a\xd1\x1b\x46\xc6\x7c\x36\x7e\x04\xea\x85\x52\xfc\ -\x91\x7d\x34\x90\x56\x6a\x44\xc8\x9d\x7c\xc5\x07\x20\xa8\x47\x6d\ -\x5a\x3f\x52\x73\xb4\xbc\x90\x00\xf0\x49\xdb\x2d\x00\x6c\x2a\xd1\ -\xdf\x5b\x3c\x55\x9f\x69\x79\x43\x90\x24\xc9\xc2\xc4\x3f\x89\xec\ -\x73\x6c\xc1\x84\x9f\x1a\xb5\x57\x56\x56\x2a\x60\x04\x3d\x38\x85\ -\x45\x48\x9e\x32\xf4\x15\x60\x31\x59\x7d\x49\x84\x6d\x46\x86\x7a\ -\x39\xed\xfb\x00\x2e\x31\xe2\xc4\x09\xd9\x05\x25\x0f\x5c\x67\x44\ -\x20\x70\xb0\xef\x8c\x2c\x2d\x47\x27\x00\x98\xa4\xbe\x54\x14\xfa\ -\x28\x84\xa3\x36\xc2\x98\x6f\xd4\x1e\x4f\x30\x02\x25\x86\x04\x12\ -\x1a\xdf\x79\x92\x96\x12\x1a\x00\xe2\x6b\x82\x05\x8a\xe1\xb7\x1f\ -\xe0\x38\x67\x81\xc3\x83\x08\x21\xef\xb4\x1a\x3e\x92\xb5\xbe\x8f\ -\xd3\x72\xf4\xbe\x02\x29\x41\x46\x80\x08\x7b\x7d\x3a\x97\x93\x5f\ -\x30\x18\x63\x0d\xdb\x47\x85\xf8\x9e\xa2\xa5\x44\x0c\x80\x60\x0e\ -\x9b\x63\x3b\xbd\x2a\xd3\xcb\xd6\x9e\x2b\x18\x06\xc0\x5b\x53\x33\ -\x00\x40\xbd\x13\xb4\x49\x92\xa4\x9e\xe0\x75\x03\x10\xb4\x45\xf6\ -\x0b\x11\x76\x03\xd2\xd6\x06\x11\x46\xc7\xb9\x01\x21\x61\xa4\x2a\ -\x42\x9c\x27\xc6\xb1\x20\x02\x73\xc8\xb0\x19\x82\xd7\x5b\xe9\x27\ -\xc0\x70\x85\x18\x57\x28\x30\xcc\x3e\x4f\x2f\x2d\x4d\x04\x60\x55\ -\x89\x7c\x1e\x8f\xc7\xa7\xe6\x84\xae\x03\x06\x4f\x6a\xcf\x5e\x03\ -\xe9\x46\x46\x98\xf1\x45\x64\x4f\xe3\x03\x22\xe3\x00\x58\x7a\xac\ -\x69\x1a\xd1\x31\x2d\x27\x34\x00\xc0\xa7\xc1\x56\x42\x67\x4e\x4d\ -\xfb\x5e\xc3\xf6\xf8\xc2\xd8\x76\xa2\x72\x6d\xd0\x35\xa3\x4b\x4b\ -\xd1\x5b\x07\xec\x57\x5f\x12\xc8\x70\xb1\x01\xa6\x7a\xc3\xf6\x38\ -\x82\x58\x18\xda\x26\x16\x41\xbe\x33\x70\x40\xcb\x09\x09\x80\x60\ -\x04\x1d\x36\x32\x30\x4d\xcb\x51\x43\x4e\x95\x9b\x00\x44\x75\x1a\ -\x13\x23\x7c\xda\x58\x5f\xb5\xdb\x88\x20\x98\x83\x7d\xd7\x19\xad\ -\x21\x01\xf0\x59\x6d\x3b\x00\x9c\x49\x1f\x11\x30\xa5\xd0\xe1\x0c\ -\xfb\xb9\x19\xcc\x0c\x53\x8d\x09\x87\x63\x0b\x42\x15\x0c\x52\xf2\ -\x2e\x97\x4b\x30\x68\x4e\x90\x90\xe1\xd5\xf2\x42\x02\x70\xfa\x6c\ -\x6d\x87\x5a\xe6\x27\x8d\x22\x0d\xac\xc2\xff\x24\x80\xa3\x86\x0e\ -\xc7\x16\x9f\x1f\xa7\x94\x95\x46\x84\x77\x3e\xec\xce\x41\xd0\x1a\ -\x85\xfa\xfd\x3d\x19\x3b\xb5\x3c\xdd\x6f\x38\x01\x9a\xed\xaf\x52\ -\x64\x64\xac\xc1\xb3\xfe\x2b\xa6\x88\x19\xa3\x58\x62\xf9\x0e\xcf\ -\xca\x93\x46\x04\x12\x5a\x9f\xf9\x2d\xbd\xf4\xb8\x6e\x00\x58\x56\ -\x6a\x01\xa8\x8e\x9a\x69\x66\xa1\xb4\xc8\x70\xc7\xe7\xff\x7a\xec\ -\x2a\x00\x8d\x46\x9c\xd8\x80\x5e\x69\xae\x73\xd7\x1a\x31\x5c\x2e\ -\x97\x20\x26\xed\x26\xed\x65\x3d\xae\x6e\x00\x9a\xb7\xac\xeb\x26\ -\x42\x93\x4a\x94\x28\x2b\x56\xed\x71\x78\x10\xbc\xde\x4a\xbf\x1c\ -\xf0\xdf\xcd\x40\x3c\x0f\x49\xdf\x93\x53\xe4\x0a\x44\x38\x8e\xdb\ -\xb1\xaf\xfb\x1e\xa8\xce\x21\x08\xf8\x52\x3e\x92\xd1\xa4\xc7\x0d\ -\xbb\x8c\x65\xf0\x1f\xd4\xd7\x04\x7e\x68\xa6\xa3\xec\x6a\x23\xc3\ -\xde\xcd\x35\x7d\xcc\x81\x3b\xe2\x14\x84\x9d\x8a\x8c\xbb\x22\x1d\ -\xc7\x49\x92\x64\x63\xe6\x5f\xab\x65\xcc\xbc\x32\xdc\xe9\x50\xd8\ -\x00\x34\x6f\xac\x7e\x9b\x38\x68\x32\xb4\x59\x08\x4f\x44\xf2\xb2\ -\xb5\x7e\x7d\xa7\x3f\xe0\xbf\x05\x20\xdd\x88\x0f\x0b\xcc\x7f\x3c\ -\x2e\x52\xf2\x22\x25\x66\x01\xa0\x57\x49\xad\x40\xf0\xb6\xb7\x27\ -\xd9\xcf\x6b\xc2\xf1\x8d\x36\x32\xac\x08\x2c\x0f\x16\xd1\x7d\x76\ -\xc9\x69\xb8\x07\x07\x06\x47\x82\x7c\xe4\x5b\x77\x82\xe8\x97\xac\ -\xb3\xfc\x34\x0d\xc6\xd7\x00\x2d\x6d\xae\xaf\x5e\x10\x69\xd2\x03\ -\x80\xe9\xf7\x54\x8c\x21\xd0\xaf\x34\x3a\x7e\xb3\x65\xcb\xba\xb0\ -\x3e\x18\x66\x56\x3b\x3b\xda\xbb\x32\xbf\x9d\x93\x09\xe0\x3b\xa7\ -\x45\x04\x46\xe1\xb8\xeb\xa6\xbc\x76\xe8\x60\xfb\x37\x46\x7d\xbb\ -\xba\xda\x94\xce\x8e\xf6\x77\xc7\x4f\xbc\xb9\x9a\x48\xb9\x10\x40\ -\x16\x60\x7a\xf7\x76\x94\x80\x55\x6c\x11\x3f\x68\xd9\xb8\xf6\x5d\ -\x33\x1d\x24\x49\xb2\xc9\x72\xe2\x56\xd0\xd9\xb4\x17\x01\x7b\x7a\ -\xc6\x88\xb2\x7f\xee\xda\x15\xb6\x76\x28\xe2\xe9\xb0\xbd\x78\xc9\ -\xa5\x6c\xf1\xef\x01\xe3\x32\x95\x78\xbb\xf5\x44\xf2\xcc\x86\x86\ -\xd5\x03\x66\x9c\x03\x06\x53\xe7\xa7\x92\x94\xdb\x05\xa3\x84\x81\ -\x6c\x0c\x66\x91\x87\xce\x0d\xbf\x02\xa8\x1b\xcc\xed\x24\xc8\x93\ -\x46\x7d\xad\xda\x5d\x5b\x24\x14\x94\x38\xd7\x00\x58\xa2\x12\xc9\ -\x42\xf0\xb4\x48\x65\x3b\xa6\x0a\x24\xf2\x1d\xce\x5b\x88\xe0\x85\ -\xaa\x22\x8c\x41\xeb\x5a\xea\xd6\x3a\x31\x82\x02\x89\x5c\x69\x59\ -\x72\xfa\x71\xbf\x12\x4d\x20\xf5\x60\x9f\x5f\xfe\x20\x33\x3f\xaf\ -\x96\x11\xc3\xd9\x54\xef\xae\x8e\xd4\xd7\x74\x91\x54\x81\xa3\x6c\ -\x21\x88\x82\x2a\x2e\x18\xa8\xba\x48\x1c\x7d\x38\xda\xa7\x15\x43\ -\x90\xbd\xc4\xf9\x30\x03\x2b\xa1\x9a\xcf\x88\xb0\xaa\x69\xa3\x7b\ -\x99\x19\x05\xa6\x6b\x84\x3a\xf7\xef\xde\x93\x99\x95\x73\x01\x80\ -\xef\x9d\x31\x04\xe4\x9c\x52\x92\xf2\xae\xba\x61\xea\x1b\x5d\x7b\ -\x77\x9d\x88\xc6\xf3\x91\x42\x92\x24\x5b\xc6\xa4\x5b\x5f\x02\xb0\ -\x1c\xc1\x0f\xb2\x51\x3e\x92\xb1\xa8\xab\xab\xcd\x54\xcd\x60\x54\ -\xe9\xac\x74\xea\x5b\x8e\xc1\xf2\xb4\xb3\x20\xdc\x96\xe0\x0b\x7c\ -\x90\x2f\x55\x64\x47\xa3\x6b\x24\xb0\x17\x2f\xb9\xb4\x2f\x90\xda\ -\x0a\xa0\x4c\xd3\xb4\x4f\x0e\xf8\xef\x36\xaa\x08\xd1\x22\xea\x42\ -\x49\x49\x92\x2c\xbd\x4a\xfa\xef\x09\xac\x1d\x62\x32\x80\x35\xa4\ -\x58\x9f\x6e\xda\xf4\xe2\xbf\xa3\xd5\x6b\x06\xb9\xd2\xb2\xe4\x14\ -\xe5\xd8\x8f\x99\xf1\x18\x08\x17\x05\xb7\x72\x03\x0b\xcb\x3d\x2d\ -\x9e\xaa\xa8\x36\x65\xc3\x2e\x95\xb5\x3b\x9c\x65\x4c\x58\x83\xd0\ -\x4f\xdb\x71\x22\x3c\x6b\x49\x3c\xb9\x22\x9a\x82\x45\x23\x4c\x9f\ -\xee\xb2\x26\x8c\x39\x5c\x0a\xa6\x27\xa0\x7b\x06\xc9\x2b\xd2\x45\ -\xff\xa3\x66\xeb\x89\xd4\x18\x51\xb1\xb4\xdd\x51\x96\xc7\x44\xf5\ -\x00\x46\x87\xfa\x84\x5e\x02\xb6\x02\xd8\x6a\x49\x3e\xd9\x14\x6d\ -\x30\x24\x49\xb2\xf5\x04\xd2\xf3\x04\xf1\x5c\x00\xf3\x00\xe8\x2d\ -\xc3\x65\x62\x2c\x35\x33\xdb\x87\xc3\x88\xcb\xe5\xed\xf3\x16\x5d\ -\xc9\x56\xcb\x2a\x00\x0e\x03\x9a\x4c\x40\x1b\x13\xfe\xca\x4c\x07\ -\x2d\x4a\xe0\x63\x56\xb8\x27\x61\x54\xd2\x71\x85\xfa\x03\x03\xbe\ -\x94\x14\xc2\x40\x1a\x05\xc4\x38\x41\x98\xc0\x4c\xb9\x20\x9a\x0d\ -\x70\xaa\x81\xce\x0f\x48\x60\x69\x93\xc7\xbd\x6b\x24\xfe\xc7\xec\ -\x0f\x13\xf6\xf9\xe5\x85\xcc\xfc\x5b\x0c\x2e\x72\xe2\x07\x42\x37\ -\xc0\x4f\xa6\x53\xbf\x7b\x38\x43\x3e\x54\x5d\x0c\x31\x58\x4c\xdd\ -\x3d\x0f\xc4\x8f\x01\xb8\x29\x96\xba\x01\x74\x02\x58\x21\xa7\xf8\ -\xab\xa3\x2d\xd0\x34\x42\xdc\xfe\x34\x35\xbb\xa4\x3c\x8b\x81\x52\ -\x06\x17\x01\x98\x30\x1c\x1d\x04\x7c\xa9\x80\xde\x14\xac\xbc\x9c\ -\x9b\x3d\xf6\x9d\xe1\xfc\x1f\xc0\x84\x8d\xf8\xc3\x3e\x6f\xd1\x95\ -\x4a\x82\x65\x06\x81\xb2\x00\x65\x22\x98\xc6\x01\x48\x03\x90\x8a\ -\xc1\x93\x9b\xa3\x00\xfa\x01\xfa\x1c\xe0\x03\x0c\x1c\x60\x11\x68\ -\x6b\xf5\xac\xdf\x8f\xff\x82\x5a\xe4\xf3\x38\x8f\xf3\xf8\xdf\xc5\ -\x7f\x00\x80\x02\xea\x80\xb2\xb7\x05\xfa\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\xb2\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x64\x49\x44\x41\x54\x58\x85\xe5\ -\xd6\xb1\x4a\x03\x31\x1c\xc7\xf1\x6f\x72\x97\xfa\x06\x56\x90\x6a\ -\x29\x5d\xaa\x93\x93\x73\xeb\x03\x08\xfa\xa4\xe2\x52\x10\xda\x87\ -\x50\xeb\x52\x6e\x13\xd4\xc9\xfd\xae\xf7\x77\x90\x13\xda\x5e\xbd\ -\x24\x4d\xce\xc1\x8c\xc9\x1f\x3e\x3f\x92\x3f\x7f\x02\xff\x7d\xa9\ -\x36\xb1\x2c\xcb\xba\x5a\x9b\x3b\x34\xaf\xfd\x93\xde\x2d\x80\x6e\ -\x15\x4f\xd2\x39\x8a\x4b\x4a\x8e\xab\xfd\xb4\x55\x1c\x35\x02\x79\ -\x29\xcb\xe2\xba\x3a\x8b\xfe\x04\x5b\xf8\xaa\x18\x0f\x06\x83\xf7\ -\x56\x02\x34\xe1\x51\x03\xd8\xe0\xd1\x02\xd8\xe2\x51\x02\xb8\xe0\ -\xc1\x03\xb8\xe2\x41\x03\xf8\xe0\xc1\x02\xd8\xe2\xcb\xe5\xdb\x61\ -\x6a\xf2\x29\xf0\xd9\x3f\xed\x4d\x20\xc0\x24\x74\xc4\x67\xc0\x05\ -\x48\xa7\xda\xdf\x2b\x80\x07\x7e\x0e\x3c\x15\x79\xe7\xa6\x3a\xf3\ -\x7e\x02\x7f\xdc\x5c\x0d\x87\x47\x1f\x7b\x05\x08\x85\x7b\x05\x70\ -\xc4\xe7\xc0\x19\xf0\x5c\xe4\x66\xb2\x89\x3b\x07\x08\x8d\x3b\x05\ -\x88\x81\x03\x24\x21\xf1\x2c\xcb\xba\x49\x8a\x35\x0e\x16\x37\xe0\ -\x82\xeb\xc4\xcc\x5c\xf0\xc6\x00\x9e\xf8\xa2\xc8\xcd\xb8\x0e\x77\ -\x9a\x84\x91\xf0\xad\x49\x58\xfb\x27\x8c\x84\x57\xbd\xb1\x36\x09\ -\xb7\x9a\xd0\x0d\x4f\xe7\xa0\x7e\xc5\x6b\x1a\x73\x6d\x18\xe9\xcd\ -\x62\x47\x7c\x04\x2c\xca\x55\x5e\xdb\x70\x36\x8d\xa9\xd6\x8b\xfd\ -\x70\x9b\xba\x5d\x37\xa4\x01\x44\x44\xab\xc4\x3c\x34\xe1\x22\xa2\ -\x54\x62\xee\x9b\xf0\xcd\xba\x5d\xf8\x4f\x00\x00\x25\x1c\x08\x3c\ -\x36\xfc\x64\x94\x52\x74\xbe\xeb\xea\xf1\xba\x3a\x9b\x79\x80\x88\ -\x68\x11\x69\x1c\x4c\x22\xa2\x42\xd6\xfd\xf9\xfa\x02\x53\x42\xe8\ -\x88\x61\x1a\x4e\x81\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ -\x82\ -\x00\x00\x03\x5e\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x10\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4d\x4f\x13\x51\x14\x86\xdf\x53\xd1\x21\x74\xa9\x84\x0f\xf7\ -\x6e\xb0\xdd\xb4\xc4\x8d\xfe\x0b\xc1\x48\x52\xdc\x98\x56\x89\xad\ -\xb2\x30\x81\x5f\xa0\x09\x0b\x4d\x5b\x23\xed\x4e\x49\x34\x01\xfe\ -\x05\xee\xa4\x1b\x0a\x2b\xd7\x14\x49\x74\x09\x32\x0a\x7d\x5d\xb4\ -\x94\x61\x66\x4a\x2b\x32\x3d\x6d\xb8\xcf\x6a\x3a\xe7\x4e\xf2\xde\ -\x27\xf7\xf6\x6e\xee\x01\x0c\x06\xc3\x65\x46\xda\x19\x14\x4d\x2c\ -\x84\xad\x81\xfe\x49\x02\xf7\x01\xde\x06\x30\x0a\xa0\x2f\xd8\x68\ -\xff\xcc\x21\x80\x0a\x20\x9b\x02\xac\xda\xfb\x07\xcb\x1b\x4b\x2f\ -\xf7\x5a\x7d\xd4\x42\x00\x25\x96\xcc\x4e\x8b\xc8\x2b\x00\x23\x17\ -\x93\xb3\x63\xec\x00\x98\x5b\x2f\xa4\x97\x00\x61\xb3\x41\x4d\x05\ -\xc4\x92\x85\xab\x02\x3b\x07\x41\x2a\x90\x78\x9d\x82\x28\x10\x56\ -\xba\x54\x4c\xfd\xf1\x2b\x37\x59\xc6\x14\x91\x7c\x1e\x40\xd2\x55\ -\x28\x8b\xe0\x0b\x88\xef\x55\xa0\x7a\xb1\x49\xff\x8f\x10\x10\x82\ -\x60\x98\xc4\x5d\x00\x91\x46\x41\x90\x12\xda\x00\xf8\xd4\x6f\x25\ -\xf8\xae\x80\x78\x2a\x3b\x0d\xe0\x83\xe3\xd5\x4f\x52\x32\xa5\xe2\ -\xb3\xcf\x67\x2d\xa7\xee\x80\x12\x4b\xe6\x1f\x8a\x30\x0b\xe0\xba\ -\xa3\xf0\x68\xbd\x90\xf9\xe8\x1e\xed\x11\x10\x4d\x2c\x84\xaf\x0d\ -\x58\xdf\x70\xb2\xe7\x7f\x90\x47\xd1\x52\x71\x76\x27\x98\xc0\xc1\ -\x10\x4b\xbe\x19\x11\xb9\xb2\x01\xe0\x06\x00\x80\xa8\xfc\xfe\x65\ -\xdf\x72\xff\x31\x86\xdc\x1f\x5a\x03\xfd\x93\x70\xfc\xe1\x91\xf2\ -\xbc\xd7\x26\x0f\x00\xa5\xe2\xec\x8e\x08\x5e\x34\x5e\x08\x46\xad\ -\xb0\x35\xe1\x1e\xe7\x11\x50\x3b\xea\x1a\x94\x6b\xcb\xbe\x37\xf9\ -\xba\x98\xfe\x04\xa0\x7c\xfc\x9b\x94\xd6\x02\xea\xe7\x7c\xed\x09\ -\x5c\xeb\xfe\x3d\x7f\x16\xc2\xda\x1c\xea\x90\x63\xee\x11\x3e\x02\ -\x30\x7a\x52\x94\xdd\x60\x82\x75\x8e\x53\x73\x10\xdc\xf4\xd6\xbd\ -\x34\x8e\xc6\x6e\x3b\xea\xce\x83\x6b\x0e\x9e\x63\xdf\x4f\xc0\xa5\ -\xc2\x08\xd0\x0e\xa0\x8d\x11\xa0\x1d\x40\x1b\x23\x40\x3b\x80\x36\ -\x46\x80\x76\x00\x6d\x8c\x00\xed\x00\xda\x18\x01\xda\x01\xb4\x31\ -\x02\xb4\x03\x68\x63\x04\x68\x07\xd0\xc6\x08\xd0\x0e\xa0\x8d\x11\ -\xa0\x1d\x40\x1b\x23\x40\x3b\x80\x36\x46\x80\x76\x00\x6d\x8c\x00\ -\xed\x00\xda\x18\x01\xda\x01\xb4\x31\x02\xb4\x03\x68\x63\x04\x68\ -\x07\xd0\xc6\x08\xd0\x0e\xa0\x8d\x9f\x80\x43\x47\xb1\xe7\x05\xb9\ -\xe6\x70\xe8\x53\xf7\x50\x39\x7e\xa8\x82\x43\x41\x84\xea\x24\xa7\ -\xe6\x40\x6c\xbb\xeb\x3e\x02\x64\xb3\xf1\x04\xb9\x07\xb0\xad\x9e\ -\x82\xee\x84\x52\x9b\x43\x1d\x91\x2d\xf7\x08\x8f\x00\x01\x56\x1d\ -\x3f\x23\xe3\xa9\xfc\x64\x30\xe1\x82\x27\xfe\x24\xfb\x00\x8e\x9b\ -\xe3\x22\x5c\x71\x8f\xf1\x08\xb0\xf7\x0f\x96\x51\x6b\x36\x00\x00\ -\x50\x98\xbb\xf3\xf8\x6d\xcf\x6d\x85\xf1\x99\x77\xc3\x80\x64\x1b\ -\x2f\x88\x8a\xbd\x67\xb7\x16\x50\xbf\x4d\x3d\xe7\xf8\x70\xf0\xa8\ -\x2f\x54\x8e\x25\x73\x53\xbd\xb1\x1d\x28\xb1\x64\x6e\x8a\xd5\xa3\ -\x0d\x10\x83\x8d\xd7\x82\x79\xbf\x16\x9a\x26\x13\xa2\xc4\x93\xb9\ -\xf7\x3e\xdd\x22\x65\x82\x6b\x21\xc8\x6e\xb7\xdd\x22\x0d\x01\xa1\ -\x2a\x38\x54\xdf\xf3\x91\xd3\x55\x2e\xae\x17\x32\x33\x7e\xf7\x9e\ -\x9b\x74\x8c\x08\x89\x42\x5a\x68\xc3\x25\x21\x22\x90\x08\xd1\x66\ -\xb7\x55\x07\xa9\x65\xf2\x4b\xc5\x45\xb2\x3f\xd3\xec\xd2\x77\xcb\ -\xa6\xa9\x78\x2a\x97\x00\xf0\x1a\xbd\xd6\x34\x45\x54\x20\x98\x3f\ -\x77\xd3\x94\x93\x68\x62\x21\x6c\x85\xad\x09\x52\x26\x40\x8e\xd5\ -\x6f\x5d\x77\x5f\xdb\x1c\xb1\x0d\x91\x2d\x11\xae\xd8\x7b\xf6\x4a\ -\x3b\x6d\x73\x06\x83\xe1\x72\xf3\x17\xf4\xb0\xe5\x26\x61\x1e\x11\ -\x45\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x8d\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x3f\x49\x44\x41\x54\x58\x85\xed\ -\x92\xb1\x4a\x03\x51\x10\x45\xcf\x4d\x02\xa2\x18\x82\xad\xac\xd9\ -\x4d\x5a\xc1\x5f\xb0\xb0\xb4\xb0\xb3\x13\xed\x2c\xfc\x02\x41\xb0\ -\xb2\xf1\x07\x14\x49\x61\xab\x62\x67\x2d\xe8\x1f\xf8\x03\xba\x6f\ -\xb3\x20\xa6\xd1\xca\x42\x93\x37\x56\x09\x62\xb7\x6f\x61\x1b\xf7\ -\x74\x03\x33\x77\x0e\xef\x0d\xd4\xd4\xd4\xfc\x77\x54\xa4\xd9\xcc\ -\xe4\xb2\xdc\x03\x98\x1f\x2f\xf5\x7a\xbd\x8f\xb2\x02\x8d\x82\xfd\ -\x33\x61\x35\x5a\xef\x66\xd6\xac\x54\x40\x92\x17\xda\x9e\xd6\x2e\ -\xcb\xc7\x95\x0a\x00\xc4\x71\x74\x83\xe9\x64\x5a\xa7\xe9\xf0\xa9\ -\x52\x01\x80\x24\x89\x8e\x80\x7b\x00\xc4\x9a\x73\xd9\x59\xa8\x40\ -\xa1\x23\xfc\x4b\xea\x86\xf6\x2b\x68\x3f\x8e\x57\x2e\x2a\x15\x30\ -\xb3\x86\xcb\xf2\xc9\xb4\xf6\xb2\xf5\x7e\xb7\xfb\x58\x24\x23\xe8\ -\x0b\xa6\x48\xf2\x0b\xf3\x73\xed\x59\x98\xe9\xa1\x68\x46\x29\x01\ -\x80\xd1\x68\xf4\x05\x4a\x43\xe7\x4b\x09\x98\x99\x16\xdb\x9d\x01\ -\x58\x02\x7a\xf3\x93\x66\x52\xa9\x40\x9a\xe5\xc7\xc0\x0e\xf0\x29\ -\x26\x9b\xfd\xfe\xb2\x2b\x9a\x11\x7c\x84\x2f\x2e\xdf\x15\x76\x09\ -\x78\xa1\xad\x38\x8e\xee\x42\x72\x82\x5e\xc0\xb9\x7c\x43\xd8\x00\ -\xc0\xa4\x83\xd0\xe5\x41\x02\xce\xb9\x55\xc3\x6e\x81\x96\xc1\x69\ -\xaf\x1b\x9d\x87\x2e\x2f\x2c\x60\x66\x32\x1a\xd7\x40\x47\xe8\x2a\ -\xe9\x46\x87\x65\x96\x03\xb4\x02\x66\x5e\x81\x67\xef\xbf\xf7\x24\ -\xf9\xb2\x02\x35\x35\x35\x35\x3f\x6e\x39\x66\xc8\x1a\xa6\xbc\x56\ -\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x83\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x35\x49\x44\x41\x54\x58\x85\xed\ -\x97\x31\x4e\x02\x51\x14\x45\xcf\x65\x12\x28\x91\x06\xd7\x30\x1b\ -\x18\x22\xb5\x09\xb4\x1a\x3b\x56\x81\xb5\x5a\x48\x2f\xab\xa0\x53\ -\x8c\x95\x31\xb1\x36\x71\x36\xc0\x1e\x68\xc0\x52\x93\x99\x6b\x01\ -\x93\x20\x82\x85\x99\x89\x85\xff\x96\xef\xbf\xfc\x7b\xf2\xfe\x2f\ -\xde\x85\xff\x2e\x6d\x17\x92\x5b\xf7\x54\xf3\x39\x90\x00\x07\x25\ -\xf9\x2c\x81\xd4\xb9\x6e\xd2\x33\x3d\xed\x05\xe8\xdc\x65\x23\xa4\ -\x0b\xc3\xbb\x60\x66\x78\x2b\xc3\x5d\xd0\x34\xc4\x82\x06\xf2\xe8\ -\xf5\x24\xba\xfa\x06\x70\x34\x75\x3f\xc7\x8f\x88\xe7\xc8\x1a\xbc\ -\x9c\x6a\x5e\x86\x79\xa1\xee\xd4\xed\x4c\x9e\x60\x8e\x9d\xab\x5f\ -\x4c\xa2\x56\x34\xe4\x78\x68\x78\xaf\xc2\x1c\xe0\xe5\x54\xf3\xc8\ -\x1a\x00\x1f\x8a\x3c\x2c\xea\xb5\x8d\x9e\x44\x30\xab\xc2\x7c\x13\ -\x02\x98\x61\x92\x5d\x00\x07\x65\xbd\xf9\x4f\xf2\xea\x43\xb6\x76\ -\x01\xfc\x89\x02\x40\x00\x08\x00\x01\x20\x00\x04\x80\x00\x10\x00\ -\x36\x01\x96\x82\x66\xd5\x86\x5a\xad\xfa\x8b\x5d\x00\xa9\x21\xee\ -\x4e\xdd\xae\xca\x7c\x7d\x77\x8c\x48\xbf\x01\x38\xd7\x8d\xa0\x91\ -\xc9\x93\x2a\x20\x3a\x0f\x3e\xcc\xe4\x09\x50\x77\xa6\x71\x51\xff\ -\x1a\x4c\xee\xb3\x6b\xac\x4b\xe0\x83\x55\x30\x59\x96\x61\xbe\x1e\ -\x7b\x0c\xd4\xf7\x06\x93\x42\xc9\xad\x7b\x8a\x3c\x5c\xaf\xce\xad\ -\xed\xf3\x5f\x6a\x81\x48\x9d\x69\xbc\x1d\xcd\x82\x3e\x01\x68\xb1\ -\x6f\x2f\x7c\x41\x27\x3e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ -\x60\x82\ -\x00\x00\x03\xeb\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x9d\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x3f\x6c\x52\x51\x14\xc6\xbf\xf3\x78\xe8\xa4\xd8\xa8\x69\x22\ -\xc6\xa9\x83\x75\x50\x6b\x5d\xdc\x48\x10\x1c\x34\xa4\xa6\x25\x0e\ -\xd6\xd8\x28\xb3\x71\x33\x61\x90\xd4\xc4\x18\xdd\xd4\xc5\x01\x4c\ -\x35\x2e\xa6\xf6\x4f\x88\x0e\x52\x9b\x30\x54\x5d\xaa\x55\x07\x98\ -\xea\x60\x64\xa8\xf1\x1f\x6e\xd8\xf2\x8e\x43\xd1\x3e\x1e\x0f\x5a\ -\x7a\xdf\xe3\xb6\x72\x7f\xdb\x3d\xef\xdc\xc3\x77\xbf\xbc\x77\xef\ -\x4d\xb8\x17\x50\x28\x14\xed\x0c\xad\x25\x29\x10\x48\xe8\xfa\xae\ -\x42\x84\x18\x67\x00\x1c\x05\xe0\x07\xb0\xd5\x55\x65\xcd\x53\x02\ -\x50\x00\x30\xcb\x84\xc7\x4b\x5f\xfd\xe9\x6c\x76\x78\x69\xb5\x4e\ -\xab\x1a\x10\x3e\x1d\x0b\xb1\x86\xdb\x00\xba\x1d\x10\xd9\x42\x28\ -\x47\x06\x5f\xce\x4c\x24\xa7\x1a\x65\x79\x1a\x55\x08\x0d\xc4\xe2\ -\x20\x8c\x00\xd8\xed\xa8\xb6\xd6\xb0\x1b\x84\x73\x5d\xdd\x3d\xbf\ -\xe7\xf3\x73\x2f\xeb\x25\xd5\x35\x20\x34\x10\x8b\x83\x71\xdd\x1d\ -\x6d\x2d\x84\x28\xd8\xd5\xdd\x53\x9a\xcf\xcf\xcd\xd8\x3e\xb6\x0b\ -\x56\x5e\xfb\x4c\x55\x90\xf1\x83\x89\xaf\x6a\x1a\x3d\xf3\xa1\xf8\ -\x69\x74\x74\xb4\xec\x82\xdc\x75\x13\x8d\x46\x3d\x45\xf8\xf6\x19\ -\x06\x9f\x24\xa6\x6b\x20\x74\x98\x9f\x93\x81\xb0\xdd\xe7\x50\x63\ -\x40\x20\x90\xd0\xbd\x3b\x0b\x1f\x60\xfa\xe6\x09\x78\x51\x5e\xc4\ -\xe0\x74\x3a\xb9\xe0\x8a\x7a\x87\x09\x46\x62\x9d\x1e\x2f\x1e\x31\ -\x70\x7c\x25\x4a\xb9\xc5\x6f\x7b\x0e\x59\x27\x46\xcd\xda\x59\xdf\ -\x55\x88\xa0\x7a\xc2\xfb\x0e\x43\x3f\xbb\x59\x06\x0f\x00\xd3\xe9\ -\xe4\x42\x79\x11\x83\x60\xfc\x58\x89\xf2\x81\xca\xd8\xaa\xa8\x31\ -\xa0\xb2\xd4\xad\x74\x03\x27\x32\x13\xf7\xbe\xb8\x21\xd4\x4d\xa6\ -\xd3\xc9\x05\x06\x25\xcc\x31\xeb\xd8\x00\x1b\x03\xb0\xbc\xce\xaf\ -\x24\x68\xf4\xcc\x61\x6d\x2d\x43\xf3\xf0\x53\x73\x9b\x80\xde\x9a\ -\x1c\x9b\x7e\x7e\x73\xc3\x87\xe2\x27\x87\x75\xb5\x0c\xab\x76\x06\ -\xf6\x5a\x73\xec\x0c\xa8\xda\xe1\x6d\xb4\xd9\xbe\x19\x6c\xb4\xd7\ -\xec\x5e\xed\x0c\x68\x2b\x94\x01\xb2\x05\xc8\x46\x19\x20\x5b\x80\ -\x6c\x94\x01\xb2\x05\xc8\x46\x19\x20\x5b\x80\x6c\x94\x01\xb2\x05\ -\xc8\x46\x19\x20\x5b\x80\x6c\x74\x27\x8a\x84\x06\x2e\x84\xc1\x9e\ -\x5b\x00\x1f\xc4\x1a\xff\x6b\x10\x80\x01\xbc\x07\x19\x57\xa6\x9e\ -\xdc\xcf\xac\x9a\xbd\x0a\xc2\x6f\x40\xb8\xff\xe2\x79\xb0\xf6\x1c\ -\xe0\x43\x70\x7f\xf0\xa8\xfc\xc6\x61\xb0\xf6\x3c\xdc\x7f\xf1\xbc\ -\x68\x31\x21\x03\x02\x7d\x43\x3b\x0c\xd0\x5d\x51\x11\xeb\x85\xa1\ -\xdd\x09\xf4\x0d\xed\x10\xa9\x21\x64\xc0\x16\xdd\x7b\x8c\x80\x6d\ -\x22\x35\xc4\xe0\xed\x5b\x74\xef\x31\x91\x0a\x6d\x3f\x09\x0a\x19\ -\xf0\x7b\x69\xf1\x35\x40\xbf\x9c\x12\xd3\x3c\xf4\x6b\x59\xc3\xfa\ -\x11\x32\x20\x3b\x39\xf2\x93\x60\x5c\x12\xa9\x21\x02\xc1\xb8\x94\ -\x9d\x1c\xf9\x29\x52\x43\xf8\x13\xc8\x8c\xa5\x1e\x80\x8c\x13\x00\ -\xde\x61\x79\x89\x72\x1b\x06\xe8\x3d\xc8\x38\x91\x19\x4b\x3d\x10\ -\x2d\xe6\xc8\x3e\xa0\xb2\x1e\x0b\xaf\xc9\x32\x50\x93\xa0\x6c\x01\ -\xb2\x51\x06\xc8\x16\x20\x1b\x65\x80\x6c\x01\xb2\x51\x06\xc8\x16\ -\x20\x1b\x65\x80\x6c\x01\xb2\x51\x06\xc8\x16\x20\x1b\x65\x80\x4d\ -\xac\x64\x6e\x44\xa3\xd1\x46\xe7\x89\x37\x34\x36\xda\x4b\xd6\x1c\ -\x3b\x03\x0a\xe6\x46\x11\xbe\x7d\x4e\x8a\x6a\x25\x56\xed\x04\x7c\ -\xb6\xe6\xd8\x19\x30\x6b\x6e\x18\x06\x9f\x74\x58\x57\xcb\x30\xca\ -\x74\xca\xdc\x66\xe0\x8d\x35\xa7\xc6\x00\x26\x3c\x36\xb7\x89\xe9\ -\x5a\x30\x12\xeb\x74\x5e\x9e\xbb\x04\x23\xb1\x4e\x02\x0f\x9b\x63\ -\xd6\xb1\x01\x36\x06\x2c\x7d\xf5\xa7\x01\xe4\xff\x05\x08\x1d\x1e\ -\x2f\x1e\x6d\x26\x13\xfe\x1e\x96\xae\x3e\x31\x4e\xb9\xca\xd8\xaa\ -\x68\xee\xb8\x3c\x28\xa1\x79\xf8\xe9\x86\x3e\x2e\x5f\xa6\x53\x04\ -\x1e\x5e\xf7\x71\xf9\xbf\xfc\x37\x17\x26\x00\x10\x73\x3c\x33\x9e\ -\xba\x61\xf7\xac\xee\x12\xf7\x31\xf7\x76\xa6\xab\xbb\xa7\x04\xa2\ -\xa0\x7b\xd2\x5c\x87\x19\x88\x4f\x8d\xa7\x6e\xd6\x4b\x68\xb8\xc6\ -\xcf\xe7\xe7\x66\xba\xf6\x1f\x79\x05\xa2\x5e\x6c\xba\x7b\x43\x94\ -\x23\x03\x83\x53\xe3\xc9\x87\x0d\xb3\xd6\x52\xca\x7c\x6d\x8e\x80\ -\xde\xca\xa9\xeb\x0d\x77\x6d\x8e\x80\xcf\x0c\xbc\x69\xe6\xda\x9c\ -\x42\xa1\x68\x6f\xfe\x00\x06\x14\x1b\x10\x41\x9d\x58\x08\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\x15\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\xc7\x49\x44\x41\x54\x58\x85\xe5\ -\x97\x51\x48\x5d\x65\x1c\xc0\x7f\xff\xef\xea\x5d\xf3\xc1\x6d\x21\ -\xcc\x4a\xd9\x26\x2b\xb6\xa8\x1e\x5a\x0c\x0a\x56\x2b\xf5\x9a\x0c\ -\xa7\x33\x0e\x11\x42\x36\x6d\x16\x44\x2f\x41\xe0\xe8\xe1\x20\x45\ -\x13\x7a\x2a\xc6\x62\x4e\x2d\x22\x9f\xae\x57\x4b\x6b\xb6\x7b\x75\ -\x5c\x5f\x16\xc3\x42\x46\x2b\x84\xc8\x46\x5d\xb5\x88\x0d\x8d\x5a\ -\xea\xbd\xf7\xfb\xf7\x70\xaf\x76\xbd\xd7\x39\x2f\x5e\x7b\xd9\xff\ -\xe9\x9c\xef\xfc\xbf\xff\xef\xf7\x1d\xce\x39\xdf\xff\xc0\x9d\x1e\ -\x92\x4d\xb2\xaf\xf6\x78\xa9\xf5\xe4\xd5\x89\xb1\x15\xa8\x94\x02\ -\x25\x80\x11\x98\x52\x88\xa0\x3a\x8a\xe4\xf5\x87\x02\x67\x7f\xcc\ -\xa9\x40\x95\xd3\x7c\x30\x6e\x4d\xbb\xa0\x4f\xaf\xb3\xee\x18\xa2\ -\x27\x43\xbd\x5d\x23\x1b\x12\xa8\x70\x5a\xb6\x89\xb5\x1f\x02\x2f\ -\x24\x87\x66\x14\x06\x0d\x3a\x14\x47\x26\xbd\x26\x3e\xb3\x18\x8b\ -\xdb\x3c\xb3\xa5\x38\xae\x76\xb7\x88\xf8\x80\x5a\x60\x57\x32\xff\ -\xbc\x8d\xd2\x34\x32\xd0\xf9\x7b\xd6\x02\x55\x4e\xf3\x5e\x6b\x65\ -\x00\xd8\x9f\x00\x8b\x1b\xbb\x7e\xef\x47\xe1\x70\x5b\x6c\x2d\x69\ -\xd7\x75\xcd\xa5\xab\x53\xcf\x03\xef\x00\x65\xc0\x2f\xc6\xda\xa3\ -\x17\xfa\xbb\xaf\xac\x5b\xa0\xbc\xfe\x78\x99\xc1\x73\x19\xa1\x48\ -\xe0\x73\xcf\x5d\xff\xbc\x38\xd4\xd3\xf3\xe7\x5a\xe0\xf4\xa8\xae\ -\x7e\x7d\x4b\xb4\x60\xfe\x8c\xa0\x4d\xc0\xdf\x8a\x1e\x1a\x0e\x74\ -\x8d\xdf\x56\xa0\xba\xa1\xa1\x30\x36\x5f\xf0\x35\xe8\x83\xa0\xef\ -\x3f\xf1\x50\xc9\x1b\x6d\x6d\x6d\x36\x1b\x78\x6a\x7d\x5f\x7d\x73\ -\xab\x8a\xbc\x0b\x44\x8c\x9a\x83\x17\xfa\x3a\x66\x52\x13\x4c\xfa\ -\x8c\xd8\x7c\xc1\xe9\x04\x9c\xc1\x0d\xc2\x01\x34\xd8\xd7\xd5\x8e\ -\xd2\x09\x94\x58\x63\x3f\x25\x6d\xd1\x2b\x4e\x2a\x9f\x6b\x7a\x0c\ -\xcc\x18\xf0\x87\x1a\x73\xff\xb0\xbf\x63\x6e\x03\xf0\xe5\x70\x1c\ -\xc7\x3b\x6b\xb7\x5d\x01\xf6\x01\x47\x42\x81\xce\xf3\x4b\xd7\x56\ -\xdc\x01\xc1\x9c\x02\x50\x95\xb7\x73\x05\x07\xf0\xfb\xfd\x8b\x2a\ -\xbc\x95\x3c\x6d\x27\x65\xe1\xcb\x02\x55\xf5\x2d\xf7\x28\x94\x03\ -\x37\x76\x78\x66\xcf\xe6\x0a\xbe\x14\xc3\xbd\x9d\xfd\xc0\x04\xf0\ -\x70\xd5\xb1\xa6\x47\x32\x04\x14\x5b\x93\x30\x93\x2f\xfd\x7e\xff\ -\x62\xae\x05\x00\x45\x64\x00\x40\x3d\xe6\x58\xa6\x80\x70\x18\x40\ -\xd5\x7e\xb5\x09\x70\x00\x24\xae\x17\x00\xac\xf2\x4c\x86\x00\xaa\ -\xa5\x09\x3b\xfd\x79\xb3\x04\x8c\xe6\x4d\x02\x48\x62\x0f\x49\x13\ -\x90\xc4\x60\x7e\xd4\x3b\x93\x31\x33\x47\x21\x0b\xf9\x4b\xb5\xef\ -\x23\xf9\x20\x66\x7c\x07\xfe\xaf\x70\x5d\x37\x5d\x40\xa6\x00\x62\ -\x26\x56\xbc\x59\xd0\x85\xad\x37\x93\xb5\x75\x7a\xe9\x03\x97\xfa\ -\x0c\xfc\x0a\x20\xc2\x9e\xcd\x12\xc8\x47\xcb\x12\x2c\x22\x4b\x63\ -\xff\x09\x18\xc2\xc9\xa3\xaa\xcd\x12\x50\x31\x3e\x00\xc4\x5c\xcc\ -\x14\x58\xd4\xc1\xa4\xdd\x91\x03\x2d\x2d\xf9\x9b\xc0\x17\x45\x8e\ -\x26\xa9\xfd\x19\x02\xa1\x81\xee\x69\x84\x8b\x08\x45\x3b\xae\xdb\ -\x97\x73\x4d\xaf\xac\x3f\x51\x93\xdc\xe4\xbe\x0f\xf9\xcf\x2d\xf7\ -\x06\x2b\xde\x02\x6b\xa5\x15\x40\x04\xb7\xba\xa1\xa1\x30\x57\x70\ -\xc7\x71\xbc\x08\xa7\x00\x04\x3d\x09\xe8\xaa\x02\x23\x7d\xe7\xc6\ -\x54\xe9\x41\xd9\x19\x9f\xdf\xfa\x89\xeb\xba\xb9\x78\x4d\x65\x36\ -\xbe\xfd\x83\xe4\xea\xc3\xc1\x40\xd7\x17\xa9\x17\x33\x01\x1e\xf3\ -\x1a\x30\xa1\x50\x7b\xe9\x6a\xe4\xbd\x0d\x4a\x48\x65\x7d\xf3\x9b\ -\x88\xbe\x82\x30\x4d\xd4\x36\x90\xb2\x7a\xb8\x45\x4b\x96\xec\x07\ -\x2f\x03\x77\x03\x7d\x51\xe3\x6d\x0c\xfb\xcf\xfc\x95\x0d\xd9\x71\ -\x1c\xef\x9c\x2d\x3c\xad\xc8\x09\xe0\x26\xd8\xa7\x42\x81\xee\x6f\ -\xd2\xf3\x3c\xab\x4d\xfe\xe9\x87\xf1\x1b\x7b\xf6\x1d\xf8\x0c\xc1\ -\x27\x70\xc8\xa3\xf1\xc6\xbd\xfb\x1f\x9d\x2b\xdd\x59\xf3\xdd\xb5\ -\x6b\xa3\x6b\x76\x48\xae\xeb\x9a\xfc\xa2\x07\x9c\x05\xf5\xf6\x82\ -\x54\x92\x68\xc5\x7c\xc1\xbe\xce\x6f\x57\xcb\x5f\xb3\x2d\x3f\x5c\ -\xf7\xd2\xf6\x7c\x93\xd7\x81\xe0\x24\x87\x22\x02\x83\xa0\x43\x82\ -\x99\xc4\xd8\x99\x85\x68\xdc\x7a\x3d\xde\x62\x8b\xee\x02\xaa\x04\ -\xad\x25\xd1\x0d\x03\x12\x8c\x9a\x68\x63\xd8\xff\xf1\x6f\xb7\x62\ -\xac\xeb\xc7\xa4\xdc\x69\x7a\xdc\x58\xd3\x0e\x3c\xb9\x9e\x7c\x60\ -\x1c\xb1\xad\xa1\xde\xee\xe0\xed\x12\xb3\xfa\x35\x7b\xb6\xee\xd5\ -\xdd\x31\x13\xab\x13\x23\x15\xa2\x5a\xaa\x89\x6d\xd5\x03\x44\x80\ -\x88\xa8\x8e\x22\x9e\xfe\x60\xa0\x63\x22\x9b\xba\x77\x76\xfc\x0b\ -\xeb\x32\x64\xd4\x54\xc2\x43\x07\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x03\x64\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x16\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\xbf\x4f\x53\x51\x14\xc7\xbf\xdf\x17\x08\x90\x4e\xf2\x23\x02\ -\xee\x2e\x58\x17\x57\x4d\x4c\xac\x75\x73\xa8\x05\x23\x49\xd1\xa4\ -\xa5\x44\x13\xd0\x11\xfe\x02\x9d\xc1\x44\xac\x38\x68\x13\x4d\xa0\ -\xb2\x83\x6c\xb8\xba\x50\x98\x9c\x29\x92\x14\xb6\x0a\x44\xf2\x8e\ -\x03\x7d\x4d\x73\xfb\x6a\x11\x69\x4f\x1b\xee\x67\xba\x3d\xf7\xbe\ -\xf6\x7b\xbe\xbd\xf7\xdd\xe5\x1c\xc0\x62\xb1\x5c\x64\x78\x9a\x45\ -\xe1\x58\x2c\xe0\x1e\x74\x8c\x50\x10\x05\x70\x0d\xc0\x20\x80\xb6\ -\xba\x2a\xfb\x77\x8e\x01\xe4\x00\x6c\x0a\x91\x71\xba\x8e\x16\x57\ -\xd3\xe9\x42\xad\x87\x6a\x19\xc0\xf0\x83\xf8\x98\x80\x2f\x01\x0c\ -\x9c\x87\xca\x06\xb2\x23\xc4\xf4\x5a\x66\x21\x0d\x40\xaa\x2d\xaa\ -\x6a\xc0\x8d\x64\xb2\xbd\x3b\x2f\x73\xa0\x4c\xd4\x45\x5e\xa3\x10\ -\xbe\xdd\xef\xe5\xe4\xf7\x54\xea\xb7\xdf\x74\xb5\x6d\xcc\x4b\x7b\ -\xee\x6b\x10\x49\x23\x9e\x25\xf0\x4d\x20\x3f\x29\x8e\x7b\xbe\x4a\ -\xff\x0f\xa1\xeb\x10\xec\x17\xe0\x26\x80\x60\x69\x82\x32\xd1\x9d\ -\x07\x00\x3c\x85\xcf\x4e\xf0\xdd\x01\xa1\x68\x62\x8c\x82\x0f\x65\ -\xa1\x3d\x11\x99\x5a\x5b\x7e\xff\xd9\xef\x4b\x9a\x0c\x86\x22\xf1\ -\x47\x24\x67\x01\xf4\x78\x41\x21\x1e\xaf\x65\x16\x3e\x56\x2c\x36\ -\x03\xe1\x58\x2c\x20\xbf\x3a\x7e\xc0\x3b\xf3\x82\xbc\x03\xe7\xfa\ -\xca\x72\x6a\xa7\x8e\xa2\xcf\x9d\x7b\x91\xe4\x80\x0b\x77\x03\x44\ -\x2f\x00\x80\xc8\xb1\xeb\xe8\xaa\xf9\x62\x74\xcc\x07\xdd\x83\x8e\ -\x11\x94\xbd\xf0\x04\xf2\xbc\xd5\x92\x07\x80\x95\xe5\xd4\x0e\x1d\ -\xbe\x28\x05\x04\x83\x52\xe8\x1c\x36\xd7\x55\x18\x50\xbc\xea\x3c\ -\xb2\xc5\x6d\xdf\x92\xac\x66\xde\x7d\x02\x90\x2d\x05\x28\xb5\x0d\ -\xc0\xc9\x3d\x0f\x00\x10\x91\x75\x34\xff\x99\xff\x1b\x52\xcc\xc1\ -\x63\xc8\x5c\xe0\x67\xc0\xa0\x37\x20\xb1\x5b\x0f\x55\x8d\xc4\xc8\ -\xe1\x8a\x39\xef\x67\x40\xe9\x6a\x6c\xb6\xab\xee\x2c\x18\x39\x54\ -\x5c\xfb\x7e\x06\x5c\x28\xac\x01\xda\x02\xb4\xb1\x06\x68\x0b\xd0\ -\xc6\x1a\xa0\x2d\x40\x1b\x6b\x80\xb6\x00\x6d\xac\x01\xda\x02\xb4\ -\xb1\x06\x68\x0b\xd0\xc6\x1a\xa0\x2d\x40\x1b\x6b\x80\xb6\x00\x6d\ -\xac\x01\xda\x02\xb4\xb1\x06\x68\x0b\xd0\xc6\x1a\xa0\x2d\x40\x1b\ -\x6b\x80\xb6\x00\x6d\xac\x01\xda\x02\xb4\xb1\x06\x68\x0b\xd0\xc6\ -\x1a\xa0\x2d\x40\x1b\x6b\x80\xb6\x00\x6d\xac\x01\xda\x02\xb4\xf1\ -\x33\xe0\xd8\x1b\x08\xdd\x96\x37\xc8\xc8\xe1\xd8\x9c\xf7\x4b\x30\ -\x57\x7a\x58\x70\xb9\x1e\xa2\x1a\x89\x91\xc3\xb6\x39\xef\x67\xc0\ -\xa6\x37\x20\x79\x0b\xa7\xec\x29\x68\x52\x58\xcc\xc1\x63\xcb\x5c\ -\x50\x61\x80\x10\x99\xb2\x8f\xc1\x70\x24\x31\x52\x0f\x65\x8d\x20\ -\x1c\x1d\x7f\x88\xf2\xca\x71\xe1\x92\xb9\xa6\xc2\x00\xa7\xeb\x68\ -\x11\x40\xa9\x36\x58\x88\xb9\x3b\xf7\x13\x2d\x77\x14\x6e\x0f\x3f\ -\xe9\x17\x91\xd9\x52\x80\xc8\x31\x70\x58\xdb\x80\xd5\x74\xba\x20\ -\xc4\x74\x59\xa8\xcf\x69\x47\x36\x14\x89\x8f\xa2\x35\x8e\x03\x43\ -\x91\xf8\x68\xbb\xdb\xb6\x01\xa0\xcf\x0b\x0a\x30\xe3\xd7\x42\x53\ -\x2d\x21\xde\x8d\x8c\xbf\xf1\xe9\x16\xc9\x8a\xc8\x3a\x89\xdd\x66\ -\xab\x22\x15\xba\x8e\x08\x2e\x17\xcf\x7c\xd0\x98\x9e\xff\xfa\x65\ -\xe1\x19\x7c\xea\x9e\xab\x75\x8c\xc8\x7e\x2f\x27\xbb\xf3\x80\x61\ -\x42\x90\x64\xf0\xe4\x07\x9b\xad\x86\x9a\xa0\xff\xdf\x39\xbf\xdf\ -\xe3\x4c\xa1\x4a\xd1\x77\xcd\xa6\xa9\x50\x34\x11\xa3\xe0\x15\x5a\ -\xad\x69\x8a\xc8\x09\x30\x73\xe6\xa6\xa9\x72\xc2\xb1\x58\x40\x0a\ -\x9d\xc3\xc5\x7a\xfb\x21\x9c\x54\x5d\x37\x63\xdb\xdc\x36\x80\x2d\ -\x08\x97\x18\x38\x5c\x3a\x4d\xdb\x9c\xc5\x62\xb9\xd8\xfc\x01\xdf\ -\x73\xe1\xb5\xcf\x33\xa6\xd1\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x00\xc8\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x7a\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\xb1\x6d\xc2\x60\x14\x85\xd1\xef\x67\x88\x88\x81\x32\x01\x62\ -\x83\xd0\x78\x22\x9a\xac\x90\x36\x0d\x0b\x59\x2c\xe1\xb4\x91\x5d\ -\x83\x25\x38\xa7\xbc\x7a\xc5\x7d\xb7\x00\x00\x00\x00\x00\x00\x80\ -\x77\x30\xd6\xc1\xe7\xf9\x72\x1a\x4b\xd7\xea\x63\x87\x3e\x0f\x33\ -\x6a\x5e\xea\xeb\xf6\xf3\xfd\xfb\x3f\x3f\x6c\x0e\x5f\xf0\xf9\xaa\ -\xa5\x8e\xd5\x75\x9d\x6f\x06\x78\x37\x9b\x01\x96\xd1\x54\xdd\x77\ -\xe8\xf2\x50\xa3\xe6\x6a\xda\xbb\x07\x00\x00\x00\x00\x00\x00\x00\ -\xf0\x7c\x7f\x0b\xd1\x0f\x08\x20\x9f\x5b\xc7\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x04\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xb6\x49\x44\x41\x54\x78\x9c\xed\ -\xd9\x41\x0d\xc3\x40\x10\xc5\xd0\x69\x14\x4e\xe1\x51\xa0\xe1\x11\ -\x52\x9b\xc2\x78\x95\xd6\x26\x30\x96\xf5\x6f\x33\x03\xb9\xee\xf5\ -\x5e\xf7\x7a\xa5\xc3\x21\x8f\xff\x03\x05\xd0\x02\x9a\x02\x68\x01\ -\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\ -\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\ -\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x6c\ -\x1f\xe0\x23\x8f\xeb\xd7\xf8\x4c\x0b\x98\x53\x0b\xcc\xcc\x3c\xdf\ -\x83\x2d\x71\xfb\x05\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\ -\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\ -\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\ -\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\xb3\x7d\x80\x1f\x17\ -\x67\x0a\x44\xf8\xee\xeb\x4c\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x02\x1d\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xcf\x49\x44\x41\x54\x58\x85\xed\ -\xd6\x3d\x8b\x53\x41\x18\xc5\xf1\xff\x99\x44\xf1\x05\x5f\x3a\x41\ -\x1b\x11\x2b\x0b\xb5\x31\x61\x11\x4b\x49\xb3\xb2\x59\x65\xd7\x46\ -\xd0\xd6\x42\xf6\x13\x88\x2c\x7e\x01\x51\xb0\x16\xb1\x90\x15\xcd\ -\x2e\x04\x71\xb1\x14\x89\x49\xa5\x16\x56\x16\x6b\x23\xd8\x28\x8b\ -\xf8\x82\x26\x73\x2c\xe6\x46\x2c\x73\x93\x30\x16\xfa\x14\x97\x5b\ -\xcc\xcc\xf9\xcd\xdc\x67\xe0\xc2\xbf\x5e\x1a\x65\x50\xad\x15\x3f\ -\xc9\x28\xf4\x75\xa8\xb3\xa8\x8f\xd3\x04\x84\x51\x06\xc9\xec\x05\ -\xf6\xc4\xaa\xdb\x47\xd7\xbd\x33\x3b\xe0\x8f\x9a\xd9\xfe\xd5\x0f\ -\x8f\xac\x78\xeb\x5f\x01\x38\x3d\x1a\xbb\xb6\xc4\xbb\x0b\x2b\xae\ -\x64\x07\x60\x22\xc2\x58\xe7\xdf\x55\xe2\x2d\xec\x91\x7a\x68\x6a\ -\x00\x09\x63\x6c\x83\xa4\xcb\xf5\xd5\xb8\x9c\x15\x50\x94\x81\x98\ -\xde\x74\xb5\xde\xf2\x52\x6e\x00\x12\xf6\x6f\x84\x6f\xd4\x5b\xbe\ -\x90\x15\x00\x20\xb0\xd1\x10\x71\xa7\xf6\xc8\xb3\x59\x01\x09\x61\ -\x1b\x1b\xa8\x08\x3f\xa8\xad\xfa\x54\x56\x40\x42\x28\x92\x10\xdb\ -\x14\xdd\x3e\xd1\xf2\xf1\xac\x80\x82\x11\x9d\x9a\x73\x77\xb0\x9f\ -\xcc\xac\xf9\x70\x66\x00\x28\x35\xa5\x81\x7d\x71\xe0\xa7\x27\xd7\ -\xbc\x3f\x2b\xa0\x50\xc4\xf4\x35\x38\xd8\x1f\xf8\x71\x7e\x40\x42\ -\x0c\xeb\x58\x7e\x80\x09\x85\x60\xa3\x5a\xd1\x81\xac\x00\x8b\x40\ -\x4a\xff\x10\x2a\x3a\xfd\x7c\x4e\xef\x33\x02\x1c\x64\x04\x6c\x1a\ -\x35\x3a\x73\x7a\x3b\xea\xcc\xea\xc4\xd1\x38\x08\x09\xf8\xee\xa0\ -\x33\xbd\xa6\x5e\x95\x99\x3f\xd1\x09\xd8\x52\x11\x3e\x30\x5a\xe8\ -\x35\xf5\xac\xec\x1a\x63\x9f\x80\x8d\x24\xa7\x0d\x48\x97\x7a\xf3\ -\x6a\x8f\xb3\xce\xb8\x27\x20\xa5\xa6\x43\x68\xa9\x3b\xaf\x7b\x63\ -\xae\x53\x1e\x60\x23\x18\xee\xdc\xd7\x5f\x9c\xd5\xcd\x71\xc3\x4b\ -\x03\x9c\x7e\x05\xd2\x5d\x97\x6f\x77\x9b\xe1\xda\x24\xe1\xa5\x01\ -\xc2\x21\xf5\x9c\xef\x77\x5f\x86\x2b\x48\xce\x0a\x48\x3b\x67\xfd\ -\x73\x3f\x5c\x64\xb9\xf8\x19\x99\xb0\xca\xde\x82\xce\xb7\x1d\x3a\ -\xf7\xa6\xa1\x1f\xd3\x08\x2f\x03\xd8\x44\x56\xf8\x19\x66\x5f\x37\ -\xf4\x65\x5a\xe1\xff\x0b\xe0\x17\x0f\x9e\xa4\x40\x97\xf1\x9c\xea\ -\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xf8\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xaa\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\x31\x15\x80\x30\x00\xc4\x50\x8a\xa6\x7a\x62\x43\x0c\x1b\x9e\ -\xf0\x54\x56\x1c\x7c\x86\x64\xbb\xe9\xf2\x32\x36\xc4\x3c\xae\xf5\ -\xdd\xcf\x7d\x0e\xe1\xb1\x8b\xd3\x3f\x51\x00\x2d\xa0\x29\x80\x16\ -\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\ -\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\ -\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\ -\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\ -\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\ -\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\ -\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\ -\x80\xe6\x05\x58\xe1\x04\x80\x5c\x86\x43\xbc\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x4d\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xff\x49\x44\x41\x54\x78\x9c\xed\ -\xd6\xa1\x4a\x04\x51\x14\xc6\xf1\xef\xcc\x8c\x08\x06\xd3\xda\x7d\ -\x01\x41\x50\xb0\xda\x5c\xb6\x6c\xf1\x39\x2c\x3e\x80\xec\x03\xec\ -\x4b\xd8\x2d\xc2\x8a\xb6\x29\x86\x8d\xbe\x81\x69\x41\x6c\x06\x19\ -\x41\xef\x31\x58\xe4\x5e\xb5\xcd\x59\x70\xfe\xbf\x78\xce\x84\xef\ -\x7e\xe1\xce\x95\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x41\xb0\ -\x3f\xb7\xee\x76\xdc\xaa\x0e\xca\xd2\x8b\xb6\x55\xd2\xcc\xd2\x6f\ -\xfb\x1f\x0b\x38\xb8\xf6\x51\xf3\x9e\xe6\x92\x9d\x4a\xda\xea\x2d\ -\x5d\x8c\x4e\xae\x45\xd3\xd8\xd9\xfd\xd4\x56\xf9\xb2\x28\xe0\xe8\ -\xc6\xb7\xd5\xf9\x83\xa4\xdd\x88\x74\x51\x5c\x7a\xb6\xda\xf6\x96\ -\x53\x7b\xfa\x3e\xaf\x8a\x2f\xdf\xd2\x4c\xff\xec\xf0\x92\x64\xd2\ -\x8e\x7f\xa4\x79\x3e\x2f\x0b\x70\x3b\x09\x49\xb4\x06\x26\x1b\xe7\ -\xb3\xb2\x80\x81\x29\x0b\x30\xbf\x5b\x43\x8e\x10\x2e\xbf\xcd\x67\ -\x65\x01\x9b\xd5\x85\xa4\xc7\x80\x3c\xa1\xbe\x2e\xc1\xea\x3c\x9f\ -\x17\x05\x2c\x27\xf6\xe2\xb2\x43\xc9\x2f\x25\xbd\x86\xa4\xeb\x57\ -\x27\xd7\xd5\x46\x6d\xfb\xf9\x1f\x40\xe2\x21\x04\x00\x00\x00\x00\ -\x00\x00\x00\x00\x00\x0c\xc5\x27\x17\xb6\x3b\xc1\x0d\x7c\x50\x9f\ -\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x22\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xd4\x49\x44\x41\x54\x58\x85\xed\ -\xd6\x31\x6b\x14\x41\x18\xc6\xf1\xff\x33\x17\x8d\x20\xd1\x74\x1e\ -\xde\xed\xad\x1c\x96\x82\xb6\x16\x96\x92\x26\x56\x22\x36\x82\xb6\ -\x16\x92\x4f\x20\x22\x7e\x01\x51\xb0\x16\xb1\x10\xc4\xee\x10\xc5\ -\xd2\xc2\x5a\xb8\x52\x48\x76\x37\x91\xb3\x51\x03\x11\x8c\x72\xf3\ -\x58\xec\x5d\x5a\x6f\xef\x96\x4d\xa1\xd3\xec\x2e\xcc\x3b\xcf\x6f\ -\xdf\x9d\x81\x85\x7f\x7d\x68\x96\x49\x5b\x59\xfe\x0d\xa4\x56\xa0\ -\x9f\x24\xc9\xd7\x3a\x01\x61\xb6\x69\x5a\x05\x4e\x8e\x23\x83\xd1\ -\x68\x74\xfc\x10\x00\x07\xe3\xe2\xfe\xfe\xef\x57\xc3\xe1\xf0\xe8\ -\xe1\x00\x6c\x0c\x6b\x2b\x2b\xab\xcf\x6c\xb7\x9a\x07\xa0\x28\x61\ -\xe3\xeb\x59\xb6\xf3\xd8\xf6\x4c\x7b\xa8\x3e\x80\x70\x34\x2e\xef\ -\x7d\x3b\x2b\x76\xee\x37\x0b\x00\x04\x06\x47\xdb\x60\xdf\xcd\xb2\ -\x62\xa3\x51\xc0\x84\x61\x29\x44\x00\xc3\xc3\x2c\x2b\x6e\x34\x0c\ -\x00\xb0\x91\xa6\x88\xa7\x59\xb6\xbd\xde\x30\x00\xb0\x4d\xb9\x27\ -\x5a\xc6\x2f\xf3\x3c\xbf\xd4\x2c\x00\x40\x44\xb0\x81\x63\xd1\x1a\ -\x6c\x6e\x6e\x5f\x68\x16\x50\x2a\x22\x60\xe0\x84\x02\x6f\x8a\xa2\ -\x38\xdb\x30\x00\x80\x38\x39\x21\xa7\xc6\x51\xef\xf2\x3c\x3f\xdd\ -\x34\x00\x43\x2c\x1b\xe1\x33\x11\xbd\x6e\x1c\x30\x55\x4c\xae\xe7\ -\x1b\x07\x08\x02\x12\xa0\xad\x20\x77\x66\xa9\x59\xaa\x31\x3f\x18\ -\x04\xfa\xd2\x0a\xbe\x9c\x24\xbd\xcf\x33\x15\xd5\x93\xed\x40\xf9\ -\x73\xb3\x1b\xc7\xac\x25\x49\xf2\x69\xd6\xca\x85\x01\x86\x40\xd9\ -\xf7\x9f\x41\xbe\xd2\xef\x77\x3f\x56\xa9\x5f\x10\x20\xa9\x7c\xf3\ -\xb1\xd0\xb5\x5e\xaf\xf7\xbe\xea\x0a\x8b\x00\x34\x69\x3d\x82\x5b\ -\x69\xda\x1d\xcc\xb3\xc8\xbc\x00\xd9\x07\xe1\x1b\x69\x9a\x3c\x9f\ -\x73\x9d\xea\xa7\xc0\xe5\x07\x0f\x65\xf3\xf5\x20\xed\x75\x1f\xcd\ -\x1b\x0e\x15\x3b\x60\x97\xe1\xe5\x83\x9e\xa4\x49\xe7\xde\x22\xe1\ -\x95\x01\x92\xa7\xe1\x2f\xd2\xb4\x73\x47\x92\xff\x52\x52\x2f\x00\ -\x84\xe0\xed\xde\xde\xf7\x9b\x9a\xfc\x8c\x2c\x3a\xaa\xee\x81\x0f\ -\xcb\xcb\x47\xae\xa6\xe9\xb9\x5f\x75\x84\x57\x00\x78\xd7\x46\x4b\ -\x2d\xad\xb7\xdb\xed\x1f\x75\x85\xff\x1f\x00\x7f\x00\x61\x3f\xa0\ -\x35\x7d\x81\xed\xd8\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ -\x82\ -\x00\x00\x04\xe7\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x99\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\xbd\x6f\x1c\x45\x18\xc6\x9f\x77\xf7\x1c\xa4\x74\xa9\x4c\x74\ -\x1f\x63\x1f\x4e\x91\x28\x52\x90\x92\x2e\x6d\xa0\x09\x50\x60\xa4\ -\x80\x44\xa2\xfc\x03\x11\x69\x40\xd8\x12\x4e\xb0\x14\x02\xa1\x81\ -\xbf\x00\x24\x2c\x50\x44\x42\x11\x39\x8d\xa1\x4a\x5a\xa7\x41\x60\ -\x37\xe1\xd8\x8f\xbb\x22\x14\x50\x22\x87\xdb\x7d\x28\xce\x23\xf6\ -\x6e\xf7\xbc\x7b\xde\x4f\xe3\xfb\x49\x2e\x76\xe6\xbd\x9b\x77\x1f\ -\x3f\xef\xec\xec\x69\x06\x98\x32\x65\xca\x61\x46\x92\x04\x91\xac\ -\xd9\x76\xf7\x0d\x0a\x2f\x09\xe4\x1c\x80\x3a\x80\x17\xf2\x4d\x6d\ -\x62\x76\x00\xf4\x08\x6e\x0a\xe5\xae\x52\x8d\x07\x22\xd2\x8f\xfb\ -\x50\xac\x00\xb6\x6d\xbf\x42\xc8\x97\x80\x9c\xcc\x24\xcd\xe2\xd8\ -\x12\xf8\xd7\x95\x52\x3f\xee\x15\x64\x8c\xeb\x20\x29\x96\xd3\x5d\ -\x26\x8c\x8d\x03\x78\xf3\x00\x70\x8a\x30\x36\x7e\xb7\xbb\x4b\x24\ -\xc7\xfe\xa3\xc7\x0a\x60\xbb\xbd\x25\x90\xb7\xf2\xc9\xad\x38\x04\ -\xfc\xc4\x72\x7a\x1f\x8e\xef\x8f\x60\x60\x7b\x63\x63\xa4\xf9\x2f\ -\x10\x2b\x80\xf7\x50\x29\xe5\x88\x88\x97\x69\xa6\x29\x21\x69\xda\ -\xb6\xdd\x02\xcc\x8b\x10\xac\x02\x38\x16\xec\x17\xf8\xaf\x46\x95\ -\x43\x48\x00\x92\x35\xdb\x71\x7f\x1e\xb6\x3d\x7f\xf2\xbd\xfe\xbb\ -\xed\x76\xfb\x59\x0e\xb9\x67\x4e\xa7\xd3\x99\x35\xcc\xda\x1a\x20\ -\x17\x02\xcd\x5b\xaa\xd5\x38\x33\x3a\x31\x86\x04\xb0\x2c\xf7\x4d\ -\x08\xee\x07\x9a\xfe\xec\xff\x33\x73\x72\x61\xe1\xc5\x3f\xf2\x4a\ -\x38\x0f\x06\x22\xcc\x6c\x23\xe8\x04\x62\x71\x6e\xae\xf9\x43\x30\ -\x2e\x34\x07\x50\x78\x69\xb8\x01\x37\x0e\xda\xcd\x03\x40\xbb\xdd\ -\x7e\x26\xc0\x8d\x60\x5b\xe8\xde\x10\x21\xc0\xee\x73\x3e\x80\xf7\ -\x30\xeb\xe4\x8a\x82\xf4\xd6\x83\xd7\x02\x39\x3b\x1a\x13\xf5\x14\ -\xa8\x07\x2f\x94\x52\x4e\xc6\x79\x15\x46\x44\xee\x8d\xd1\x98\x28\ -\x01\x86\x56\x78\x55\x9b\xed\x27\x21\x22\xf7\xd0\xea\x75\xec\x3a\ -\xe0\xb0\x50\x2b\x3b\x81\x24\xb8\xae\xbb\xe0\xf9\x58\x01\xb0\x08\ -\x00\x04\xef\x99\x82\xd5\x56\xab\xf5\x5b\xda\xef\xae\xbc\x03\x5c\ -\xd7\x3d\xe1\xf9\x78\x04\xe0\x32\x80\xa3\x00\x8e\x0a\xe4\x8a\x4f\ -\x79\xec\xba\xee\x42\xda\xef\xaf\xb4\x00\x24\x6b\x9e\x8f\xef\x00\ -\x1c\x8f\xe8\x3e\xde\xf7\xf9\x51\xda\x31\x2a\x2d\x80\xed\xf6\x3e\ -\x00\x10\x7a\x74\x69\x04\xf2\x56\xda\x31\x2a\x2b\x80\xe3\x38\xa7\ -\x41\xde\xcc\x7b\x9c\x4a\x0a\x40\xb2\xe6\x53\xbe\x06\x30\xb3\x57\ -\x9c\x80\xdf\xa7\x1d\xab\x92\x02\xc4\x59\x7f\x97\xe7\x00\xef\xa4\ -\x1d\xab\x72\x02\x24\xb5\x3e\x21\x37\x95\x52\x5b\x69\xc7\xab\x94\ -\x00\x49\xad\x0f\x60\x73\xae\x55\xff\x3c\x8b\x31\x2b\x25\x40\x52\ -\xeb\x0b\xfc\xab\x49\x7e\xf0\x4c\x42\x65\x04\x98\xd0\xfa\xbf\x66\ -\x35\x6e\x25\x04\x28\xc3\xfa\x9a\x4c\xde\x05\x1c\xc7\x79\xc9\x23\ -\x56\x02\x0b\x93\xfb\xa6\x81\xd5\x66\xb3\xf9\x34\xc9\xe7\xcb\xb0\ -\xbe\x26\xb5\x03\x5c\xd7\x5d\xf0\x29\x8f\x05\x72\x05\xbb\x6b\x75\ -\x00\x97\x3d\x1f\x8f\x5c\xd7\x3d\x11\xf7\xf9\xb2\xac\xaf\x49\x2d\ -\xc0\xee\x5b\x5a\xe4\x5a\xdd\xf3\xf1\x2d\xc9\xb1\x2e\x2b\xd3\xfa\ -\x9a\x2c\xe6\x80\xc5\x3d\xfa\xce\x59\x4e\xef\xfd\x71\x9d\x65\x5a\ -\x5f\x93\xfb\x24\x28\xe0\x4d\xc7\x71\x4e\x8f\xb6\x97\x6d\x7d\x4d\ -\x6a\x01\x08\xde\x8b\x09\x39\xe2\x53\xbe\x0a\x96\x42\x15\xac\xaf\ -\x49\x2d\x80\x01\x7e\x06\xe0\x79\x4c\xd8\x50\x29\x54\xc1\xfa\x9a\ -\xd4\x02\x28\xa5\xb6\x20\xf2\x71\x5c\x9c\x2e\x85\xaa\x58\x5f\x93\ -\xc9\x1c\xa0\x9a\xf5\x3b\x00\x9e\xc4\x84\x1d\xf1\x29\xdf\xf8\x90\ -\x35\x54\xc0\xfa\x9a\x4c\x04\x10\x91\xbe\x21\xbc\x8a\xf8\x52\x78\ -\x19\xc4\x99\x98\x98\x42\xac\xaf\xc9\xec\x29\xd0\x6a\xb5\x7e\x49\ -\x52\x0a\x71\x14\x65\x7d\x4d\xa6\x8f\xc1\x84\xa5\xb0\x17\x85\x59\ -\x5f\x93\xa9\x00\x13\x94\x42\x14\x85\x5a\x5f\x93\xf9\x42\x68\xbf\ -\xa5\x50\xb4\xf5\x35\xb9\xac\x04\xf7\x51\x0a\x85\x5b\x5f\x93\x8b\ -\x00\x13\x96\x42\x29\xd6\xd7\xe4\xf6\x2e\x90\xb4\x14\xca\xb2\xbe\ -\x26\xd7\x97\xa1\x04\xa5\x50\x9a\xf5\x35\xb9\x0a\x20\x22\x7d\xd3\ -\xc0\xdb\x10\x84\x37\x59\x08\x1c\xd3\xc0\x3b\x65\x59\x5f\x93\xfb\ -\xeb\x70\xb3\xd9\x7c\x5a\x33\xe4\x3c\x80\x75\x00\x7f\xef\xfe\xad\ -\xd7\x0c\x39\x9f\xf4\x27\xb3\x3c\x29\x64\x7f\x40\xa3\xd1\xe8\x02\ -\x78\xbd\x88\xb1\x26\xa5\x12\xbf\x0a\x97\x49\x94\x00\x3b\xc1\x0b\ -\x92\x66\x41\xb9\x64\x4e\x44\xee\x3b\xa3\x31\x51\x02\xf4\x82\x17\ -\x83\xed\xa7\x07\x93\x88\xdc\xbb\xa3\x31\xe1\x8d\x92\xe0\xe6\x70\ -\x8b\x79\x31\xd3\xac\x0a\x44\xc4\x7c\x2d\x78\x4d\x30\xf4\x48\x0e\ -\x6f\x94\xa4\xdc\x1d\x6e\xc0\x6a\xa7\xd3\x99\xcd\x3c\xbb\x9c\xe9\ -\x74\x3a\xb3\x04\x86\x16\x62\xa1\x7b\x43\x84\x00\x4a\x35\x1e\x00\ -\xdc\x0e\x34\x1d\x33\xcc\xda\xda\x41\x12\xe1\xbf\xcd\xd2\x43\x3b\ -\xc6\xb7\x06\xf7\x36\x4c\xd8\x01\x22\x7d\x01\xdf\x1b\x69\xbd\x60\ -\x98\x33\xdb\xb6\xed\x5e\xb3\x2c\x6b\xbe\x8a\x13\x23\x49\xd3\xb2\ -\xac\x79\xdb\x76\xaf\x0d\x36\x49\x0f\xed\x14\x87\xc0\xbf\x1e\xb5\ -\xe8\x1a\x7b\x92\xc2\x72\xba\xcb\xff\x87\x03\x13\x00\x40\xc8\xf2\ -\xbc\x6a\xdc\x8e\xea\x1b\xbb\x0e\x50\xcd\xfa\x6d\x42\x96\xf3\x4b\ -\xab\x10\x48\x60\x69\xae\x55\xff\x74\x5c\x40\xc2\x43\x53\xc6\x17\ -\x00\x4e\x65\x9a\x5a\xfe\x24\x3a\x34\xb5\x9f\x63\x73\x67\x31\xd8\ -\x75\x5d\xc5\x63\x73\x5d\x82\x4f\x26\x39\x36\x37\x65\xca\x94\xc3\ -\xcd\xbf\x5b\x3f\xf6\x3c\xa0\xff\x9c\x5c\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\xf5\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\xa7\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\xcf\x6f\x15\x55\x14\xc7\xbf\x67\xa6\x85\xc2\xca\xe7\xa6\x21\ -\x10\x58\x58\x16\x36\x4d\x30\xf1\xa5\x2f\x95\x4d\x9b\xa8\x1b\x90\ -\x96\x02\xa2\x11\x08\x7f\x82\x1b\x89\x6d\x62\x5b\x9b\x28\x8a\x1b\ -\xfd\x0b\x34\xb1\xd1\x00\x6d\xf1\x91\xb2\xa9\x26\x6d\x20\x81\x3c\ -\x2d\x1b\xa3\x75\x83\x0b\x9a\xb2\xa8\x8b\xd6\x15\x2d\xd0\xb9\x5f\ -\x17\x7d\x53\x66\xe6\xcd\x74\xe6\x31\x77\x7e\xd4\xbe\x4f\xf2\x16\ -\x73\xee\x79\xef\x9e\x7b\xde\xf7\xdc\xb9\x33\xb9\x17\x68\xd0\xa0\ -\xc1\x4e\x46\xa2\x38\x75\xcf\xb0\x69\x6d\x05\x27\x14\xd4\x59\x81\ -\x14\x09\xec\x17\x60\x77\xd2\xc1\xd5\x03\x81\x27\x02\x3c\x22\x38\ -\x67\xc0\xb8\xda\x52\xc0\xcd\xd9\x1e\x59\x0f\xfb\x5e\x68\x02\x4a\ -\x93\x7c\x0b\xe0\x37\x00\x5e\xd5\x12\x69\x7a\xcc\x03\xf2\x61\xa5\ -\x5f\x7e\xde\xca\xc9\x08\x6c\x21\xa5\x73\x82\x83\x00\xa7\xb1\xfd\ -\x06\x0f\x00\xed\x00\xa7\x4b\x37\x38\x00\x32\xf0\x8f\x0e\x4c\x40\ -\xe7\x24\x06\x44\xf8\x59\x32\xb1\xa5\x08\xf9\x79\xe9\x27\x7c\x1c\ -\xd4\xec\x9b\x99\xaa\xec\xa7\x3d\xe6\x15\x8a\x0c\xc1\xc4\xad\x43\ -\x6b\x58\xb8\xfe\xae\x58\x5a\x03\x8d\xc9\x99\x6b\x34\x1f\xb6\xe0\ -\x20\x2c\x1c\x13\x72\x14\x40\xc1\xed\x21\x6f\xfb\x95\x43\x4d\x02\ -\xba\x67\xd8\xb4\xba\xc2\xdf\xe1\x94\xbd\xe0\x17\x18\x72\xae\xd2\ -\x2b\x4b\xda\x23\x4f\x80\x52\x99\xad\x50\x1c\x03\xf1\xa6\xc3\x3c\ -\xbf\xa7\x20\x47\xbc\x13\x63\x4d\x09\xac\xad\xe0\x04\xdc\x35\xbf\ -\x6c\x52\x3e\xd8\x2e\x83\x07\x80\x4a\xaf\x2c\xc1\x90\x73\x00\x56\ -\x1c\xe6\xf6\xea\xd8\x5c\xd4\x24\x40\x41\x9d\x75\x5e\x53\x64\xf8\ -\x6e\xbf\xfc\xa3\x3f\xcc\x64\xa9\xf4\xca\x92\x50\x86\x9d\x36\xef\ -\xd8\x00\x9f\x04\x08\xa4\xe8\x32\x98\xb8\xa5\x3d\xba\x94\x50\xcd\ -\x98\x72\x5b\xe4\x75\xaf\x4f\x4d\x02\x08\xec\x77\x5e\x1f\x5a\xc3\ -\x82\xee\xc0\xd2\xc2\x27\xf6\x03\x5e\x1f\x1f\x05\xb8\x57\x78\x79\ -\x9b\xed\xeb\xc1\x1b\xbb\xdf\xea\x35\x78\x21\xb4\x43\x68\xca\x3a\ -\x80\x28\x74\x95\xd9\xa6\x94\x1a\x02\xe5\xd4\x86\x85\xe3\xa6\x18\ -\xa3\x77\x4f\xca\xdf\x71\x7f\x3b\xf7\x0a\x28\x8d\xf3\xb0\xb2\x78\ -\x1b\x94\xf3\x00\xf6\x6e\x7c\xe4\x82\x45\xde\xe9\x2a\xb3\x2d\xee\ -\xef\xe7\x3a\x01\xdd\x33\x6c\x82\xc1\x1f\x01\xec\xf3\x69\xde\xa7\ -\x2c\xf5\x49\xdc\x3e\x72\x9d\x80\xc7\xcb\xb8\x04\xa0\xe6\xd6\xf5\ -\x1c\x39\x1d\xb7\x8f\xdc\xce\x01\xc5\x49\x76\x08\x38\x92\x74\x3f\ -\xb9\x54\x40\xf7\x0c\x9b\x4c\xf0\x3b\x00\xcd\x5b\xf9\x09\x78\x3d\ -\x6e\x5f\xb9\x4c\x40\xb8\xf4\x01\x00\x4f\x69\x18\x57\xe2\xf6\x95\ -\xbb\x12\x88\x2c\x7d\x91\x91\x4a\x9f\xcc\xc7\xed\x2f\x57\x0a\x88\ -\x2a\x7d\x08\xe6\xf6\xbc\x84\xaf\x74\xf4\x99\xab\x04\x44\x95\xbe\ -\xb2\xe4\x62\x94\x17\x9e\x51\xc8\x4d\x09\xd4\x23\xfd\xdf\x4e\xcb\ -\x9f\xba\xfa\xcd\x85\x02\xb2\x90\xbe\x8d\x16\x05\xbc\x71\x83\xaf\ -\x58\x54\x43\x9b\x0b\x13\xe1\x84\x61\x18\xa3\xf7\x7a\xe5\x41\x94\ -\xef\x3f\x5e\xc6\x25\x91\x74\xa5\x6f\x13\x5b\x01\x5d\x65\xb6\x59\ -\xe4\x1d\x40\x2e\xc0\x5e\xab\x53\xce\x2b\x8b\xb7\x4b\xe3\x3c\x1c\ -\xf6\xfd\xe2\x24\x3b\x44\xd2\x97\xbe\x4d\xec\x04\x28\xa5\x86\x10\ -\xb0\x56\x87\xc9\x1f\xba\x67\x18\xa8\xb2\x2c\xa5\x6f\x13\x7f\x0e\ -\xd8\x7c\x44\xf5\x6b\x43\x71\xf5\x5f\x7c\x14\xd4\x9c\xc5\xac\xef\ -\x25\xf9\x49\x90\x1c\x29\x4e\xb2\xc3\x6b\xce\x5a\xfa\x36\x1a\x12\ -\xc0\xf1\x10\x87\x5d\xa6\xf0\x5b\x67\x29\xe4\x41\xfa\x36\xf1\x13\ -\x60\x18\x5f\x02\x78\xba\xa5\x8f\xa7\x14\xf2\x20\x7d\x9b\xd8\x09\ -\xa8\xf4\xc9\x3c\x29\x9f\x86\x3a\x56\x4b\x21\x2f\xd2\xb7\xd1\x32\ -\x07\xec\x7d\x19\x57\x00\xdc\x0f\x71\xdb\x65\x82\xdf\x9b\xe0\x18\ -\x72\x20\x7d\x1b\x2d\x09\x98\xed\x91\x75\x0b\x72\x11\x61\xa5\x00\ -\xbc\x06\xe0\x48\x88\x4f\x2a\xd2\xb7\xd1\x76\x17\x98\xeb\x97\x3f\ -\x22\x95\x42\x18\x29\x49\xdf\x46\xeb\x6d\x30\x62\x29\x04\x93\xa2\ -\xf4\x6d\xb4\x26\xa0\x8e\x52\xf0\x23\x55\xe9\xdb\x68\x5f\x08\xbd\ -\x70\x29\xa4\x2c\x7d\x9b\x44\x56\x82\x75\x97\x42\x06\xd2\xb7\x49\ -\x24\x01\x75\x96\x42\x26\xd2\xb7\x49\xec\x59\x20\x72\x29\x64\x24\ -\x7d\x9b\x44\x1f\x86\x42\x4b\x21\x43\xe9\xdb\x24\x9a\x80\xd9\x1e\ -\x59\x37\x4c\x79\x4f\xa4\x76\x93\x85\x08\x16\x0c\x43\xde\xcf\x4a\ -\xfa\x36\x89\x3f\x0e\xdf\xeb\x95\x07\x54\x72\x54\x80\x29\x00\xab\ -\x00\x56\x05\x98\xa2\x92\xa3\x51\x5f\x99\x25\x49\x2a\x6f\x85\x2b\ -\xa7\x64\x11\xc0\x3b\x69\xf4\x55\x2f\xb9\x78\x2b\x9c\x25\x7e\x9b\ -\xa4\x9e\x38\xaf\xcf\x5c\xa3\x99\x5e\x38\x7a\xf1\xc6\xee\x1d\x1b\ -\xe0\xbf\x49\xea\x91\xf3\xfa\x61\x0b\x0e\xea\x0f\x2d\x1d\x7c\x62\ -\x5f\xf4\xfa\xf8\x28\x80\x73\x2e\x83\x85\x63\x7a\xc3\x4a\x0f\xe3\ -\x19\x8e\xbb\x2d\xac\xb9\x25\xd7\x24\xc0\x80\x71\xd5\x79\x2d\xe4\ -\x68\xa9\xcc\x56\xdd\xc1\x25\x4d\xa9\xcc\x56\x0a\x5d\x0b\x31\xef\ -\xd8\x36\x6c\x1e\x5a\x0a\xb8\x09\xe0\x2f\x87\xa9\x00\xc5\xb1\xed\ -\x94\x84\xcd\xcd\xd2\xee\x1d\xe3\xf3\xd5\xb1\xb9\xa8\x6b\xbb\xbc\ -\x50\x86\x55\x33\xa6\xf2\xbc\x5d\xde\x78\x86\xe3\xd5\x7f\xfe\xc5\ -\xb6\xcb\xdb\x74\x4e\x70\xf0\x7f\x71\x60\x02\x00\x44\x06\x2b\x27\ -\xe5\xb2\x5f\x53\xe0\x3a\xe0\xd7\x7e\x5c\x86\xc8\x60\x72\x51\xa5\ -\x02\x01\x19\xa8\xf4\xe1\x8b\x20\x87\xa8\x87\xa6\xbe\x06\xd0\xae\ -\x35\xb4\xe4\x89\x74\x68\xaa\xee\x63\x73\xd5\x2d\xe7\x07\xf2\x78\ -\x6c\x0e\xc0\x22\xc0\xfb\xf5\x1c\x9b\x6b\xd0\xa0\xc1\xce\xe6\x3f\ -\xb7\x37\xe9\x8b\xf9\x5d\x56\x0e\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x00\x97\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x49\x49\x44\x41\x54\x58\x85\xed\ -\xd7\x41\x0d\x00\x20\x0c\x04\xc1\x83\x20\xa9\x02\x70\x53\x3f\xd5\ -\x43\x52\x6b\x88\x38\x7e\xec\xfe\x7b\x99\x6f\x25\x32\x8a\xac\x8e\ -\xac\x76\x36\x96\x69\xd8\xe6\xbd\xa6\x3b\x00\x00\x00\x00\x00\x00\ -\x00\x00\x00\x00\x00\x00\x00\x00\x6e\xde\x67\x34\x74\x1e\x39\x3e\ -\xee\x02\x8e\xc2\x05\x10\x61\x1a\xbe\x91\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\xde\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x90\x49\x44\x41\x54\x78\x9c\xed\ -\x98\xcf\x6f\x54\x55\x1c\xc5\xcf\xb9\xf3\xd2\xd4\x04\x31\x4a\xdd\ -\x89\x2e\x81\x75\xdb\x99\x31\xc6\x64\xaa\x81\x98\x2e\xb4\xd3\x1a\ -\x16\xec\x90\x10\xfd\x03\x54\xe2\x82\x18\x62\x42\xfc\xb1\x36\x21\ -\x50\x60\x45\x4c\xa0\xf3\xa6\xb8\x60\x92\x26\x32\x24\xd8\xc8\x88\ -\xac\xd5\x35\xee\x24\x1a\xe3\xa2\x55\xda\x7b\x5c\xcc\x80\xd3\x77\ -\x6f\x3b\xbf\xde\x9b\xa9\x78\x3f\xcb\xfb\xee\xfd\x7e\xcf\xf7\xbc\ -\xef\xdc\x77\xef\x00\x81\x40\x20\x10\x08\x04\x02\x81\x40\x20\x10\ -\x08\x04\x02\x81\xff\x17\x1c\x55\xe2\x7c\x45\x65\x52\x5f\x02\x30\ -\x90\x2e\x34\x16\x72\xa7\x47\xa1\x63\x24\x06\x14\x63\x9d\x14\x74\ -\x0e\x80\x79\x2c\x44\x3c\x79\x67\x81\x8b\xc3\xd6\x62\x3a\x4f\x49\ -\x97\x62\xac\x53\x82\xce\x27\x73\x8b\xba\x90\xaf\xea\xc3\x61\xeb\ -\x19\x5e\x07\x48\x2c\x54\xed\xe7\x00\xdf\xef\x30\xf1\x8b\x46\xd9\ -\x9c\x02\xa9\x61\xc8\x1a\x8a\x01\xa5\xba\xa2\xb5\xdf\xed\x79\x80\ -\xc7\xbb\x5b\xa1\x4b\x4f\x3d\x6b\xde\xbd\x35\xc3\x8d\x6c\x95\x0d\ -\xc1\x80\xd2\x65\x8d\xaf\xed\xd5\x57\x20\xe6\x92\xcf\x24\x58\x36\ -\x15\x38\x3f\x45\x02\xd5\xf1\x3f\x78\xec\xd6\x71\xae\x67\xa9\x2f\ -\x53\x03\x0a\x37\xb4\x17\xeb\x5a\x06\x30\xe3\x49\xbd\x09\x3c\xea\ -\x72\x02\x50\xce\x13\xe2\x66\x94\xe3\xdc\xea\x5b\xfc\x33\x2b\x8d\ -\x99\x19\xf0\xea\x55\x3d\xff\x77\xa4\x1a\x80\xc9\xad\x4f\x84\x66\ -\xf1\x3e\x94\x73\x24\x11\x3f\x8c\x3d\xe4\xec\xed\xa3\xfc\x35\x0b\ -\x9d\x99\x18\x30\x79\x55\x2f\x46\x91\x56\x00\x1c\x48\x64\x13\x05\ -\xbb\xe3\xee\x46\x18\xc8\xd1\xf5\xb3\x35\x3c\x7c\x77\x8e\xf7\x53\ -\x96\x9a\xbe\x01\xc5\x58\x87\x04\xad\x00\x78\x21\xf1\x48\x20\x2c\ -\x3a\xed\xed\x04\x24\x18\xba\xda\xee\x1b\xcb\x23\xdf\xbd\xcd\x9f\ -\xd2\x53\x9b\xf2\x39\x60\xba\xa2\x69\x41\xb7\xe1\x2b\x1e\x5d\x14\ -\xdf\x9a\x49\xc0\x82\xce\xec\xfd\xd6\xe8\xdb\xfc\x92\xa6\x52\x11\ -\xdb\x22\x35\x03\xa6\xab\x7a\xdd\x50\x37\x01\xec\x6b\x1f\x17\xd4\ -\x2c\xbe\x57\x04\x0b\x38\x26\xec\xa3\x51\x3d\x1f\xeb\xb5\xbe\x85\ -\x26\x48\xc5\x80\x62\xac\x79\x23\xdd\x00\xb0\xa7\x7d\x5c\x90\x08\ -\xf6\x5e\xfc\xbf\x58\x34\x0d\x6c\x67\x0f\xa1\x5a\xbe\xa2\xf2\x00\ -\x71\x1f\x33\xb0\x01\xf9\xaa\x4e\x08\xba\x06\x60\xac\x7d\x5c\xa0\ -\x1d\xb0\xf8\x16\xb4\x72\xe3\x8c\x91\x5a\x2a\xc4\x7a\x67\xd0\xe8\ -\x03\x19\x90\x8f\xf5\x01\xa5\xc5\x64\x9c\x66\xf1\xce\x9b\xeb\x1b\ -\x42\xf2\x98\x60\x00\x5d\x2c\xc4\xea\x70\xb4\xee\x14\xbb\x1f\x24\ -\x16\x63\xfb\xa9\x48\xe7\xf2\x22\xc0\xd2\xfd\xed\xa6\x05\xe1\x79\ -\x69\x82\x3e\xfb\xbe\x6c\x3e\xea\xe7\xfe\xd0\xb3\x01\xa5\xba\xa2\ -\xf5\xdf\xec\x39\x91\x27\x5c\x21\x99\x16\xdf\xcc\x21\x90\xf4\x9a\ -\xb0\xf8\xd2\x86\x79\xef\xda\xd1\xed\x0e\x59\x7e\x7a\x32\xa0\x74\ -\x59\xe3\x6b\xcf\xe8\x0a\x80\xf9\x44\xf6\x66\xf1\xee\xa7\x2b\x13\ -\x24\x90\x80\xf1\xa8\x8f\x9f\x1b\xe7\xb1\xda\x2c\xff\xea\x36\x56\ -\xd7\x06\xbc\x72\x5d\x4f\x6f\x6c\x6a\x19\x80\xf3\x09\x6a\x5d\x6a\ -\x86\x52\x7c\x5b\x4e\x6f\x27\x10\xf8\x26\x97\x63\xb9\xdb\xfb\x43\ -\x57\x06\x4c\x7e\xad\x89\x68\x53\x35\x08\x5b\x0f\x21\x12\xc0\xde\ -\x5a\x2e\x55\x48\xc0\xda\x1c\xb8\xb5\x0c\x02\x77\x1f\x46\x9c\xbd\ -\xf7\x26\x1f\x74\x0c\xd1\x69\xc2\xf4\xb2\xf6\x1b\xab\x15\x00\x07\ -\x13\x8f\xfa\x3b\xe0\x64\x81\xff\xfe\xf0\x23\xc4\x23\x8d\x05\xfe\ -\xb2\xd3\xd2\x1d\x3f\x83\x2f\x2f\xe9\xa0\xb1\x5a\xc5\x6e\x2e\x1e\ -\xd8\xee\xd4\x78\x88\x46\xab\x53\xd7\x75\xc0\xb7\xe4\x11\xdb\x76\ -\x40\x7e\x49\x53\x34\xaa\x01\x98\x70\xd2\xed\xa6\xe2\xdb\xf1\x77\ -\xc2\x03\x90\x6f\x34\xca\xbc\xe7\x5b\xe2\xed\x80\x42\x45\x33\x34\ -\xaa\x23\x51\xbc\x76\x73\xf1\x00\xd0\xbc\x6a\x27\x3b\x61\x02\x52\ -\xbd\x58\x55\xc9\xb7\xc4\xe9\x80\x42\x45\xa7\x61\x74\xc6\xe3\xe4\ -\x70\xb7\xf9\x01\x71\xc4\x13\x82\xe5\xc7\x8d\x05\x7e\xb2\xe3\xbc\ -\x62\x6c\x37\x04\xf8\xfe\x9e\xfa\xcf\x43\x60\xf3\xce\xbc\x89\xda\ -\xc7\x3c\x27\xaa\x27\x17\x5f\x6d\xee\x1e\x40\x9e\x6d\xed\xaa\x4f\ -\x16\x82\x05\x79\x76\xd4\x32\x02\x81\x40\x20\x10\x08\x04\x02\x81\ -\x40\x20\x10\x08\x04\x02\xa3\xe6\x1f\x3c\x8f\x50\x7d\x3b\xd7\xa3\ -\xf5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\xfc\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\xae\x49\x44\x41\x54\x78\x9c\xed\ -\x9a\x3f\x6e\x13\x41\x14\x87\xbf\xd9\x10\x85\x26\x48\x14\xb9\x01\ -\x15\x25\x29\x69\x90\x88\x2d\xa5\x43\xd8\xa0\x84\x24\x10\xc9\xb1\ -\xa1\x80\x1b\xd0\x72\x03\x90\x00\xc7\x05\x7f\x82\x03\xb1\x8d\x68\ -\xb3\x3e\x44\x24\x2e\xc0\x05\x22\x21\x0a\x8a\x08\xfc\x68\x90\x70\ -\xc6\xde\x18\xef\xce\xcc\xce\x6c\xfc\xca\xf5\xdb\x9f\xe6\xfb\xb4\ -\x9e\x1d\x3d\x2d\xcc\x6a\x56\xb3\x3a\xcf\xa5\xf2\x5e\x80\xed\x2a\ -\x57\x6a\xb7\x84\xe8\x19\xc8\x77\x89\xa2\x47\xfd\x83\xd7\x5f\x87\ -\x7f\xbf\x90\xd7\xc2\x5c\x54\xb9\x5a\x5f\x13\x91\x3d\x90\x08\x40\ -\x0d\x06\x2f\x81\xeb\xc3\x3d\x51\x2e\x2b\x73\x50\xff\xe0\x4f\x31\ -\x5e\xd2\xfb\x0a\x29\x20\x01\xfe\xb7\x28\x9e\xea\xbd\x85\xfb\x0b\ -\x24\xc1\xa3\x64\xbd\xdf\x69\x7d\xd1\xfb\x0b\xb5\x09\x9e\x05\x1f\ -\x77\x5a\x07\xe3\xee\x29\x8c\x80\x34\xf0\x50\x10\x01\x69\xe1\xa1\ -\x00\x02\xb2\xc0\x43\xe0\x02\xb2\xc2\x43\xc0\x02\x4c\xc0\x43\xa0\ -\x02\x4c\xc1\x43\x80\x02\x4c\xc2\x43\x60\x02\x4c\xc3\x43\x40\x02\ -\x6c\xc0\x43\x20\x02\x6c\xc1\x43\x00\x02\x6c\xc2\x83\xe7\x02\x6c\ -\xc3\x83\xc7\x02\x5c\xc0\x83\xa7\x02\x5c\xc1\x83\x87\x02\x4c\xc3\ -\x97\xaa\xb5\x3b\x88\x7a\x01\x80\xa8\x87\x71\xaf\xf9\x79\xf8\x77\ -\xaf\x26\x42\xa6\xe1\xcb\xd5\xfa\x1a\xa2\xf6\x81\x25\x60\x09\x25\ -\xaf\xf4\x1e\x6f\x04\xd8\x80\x1f\x93\x37\x52\x5e\x08\x70\x04\x3f\ -\x10\xd4\x63\xbd\x37\x77\x01\xae\xe0\x95\x52\xf7\xfb\xdd\xe6\x27\ -\xbd\x3f\xd7\x4d\xd0\x25\xfc\x61\xa7\xb9\x37\xee\x9e\xdc\x04\xf8\ -\x00\x0f\x39\x09\xf0\x05\x1e\x72\x10\xe0\x13\x3c\x38\x16\xe0\x1b\ -\x3c\x38\x14\xe0\x23\x3c\x38\x12\xe0\xec\x3d\x2f\xb2\xd5\xef\xb5\ -\x3e\x4c\x93\x65\x5d\x80\xcf\xf0\x60\x59\x80\xef\xf0\x60\x51\x40\ -\x08\xf0\x60\x49\x40\x28\xf0\x60\x41\x40\x48\xf0\x60\x58\x40\x68\ -\xf0\x60\x50\x40\x88\xf0\x60\x48\x40\xa8\xf0\x60\xe0\x1b\x21\x57\ -\xf0\xc0\x66\xbf\xd7\x6a\x4f\x9b\xb7\x52\xa9\xdf\x55\xc8\x73\xc0\ -\xfc\x4c\xd0\x25\x7c\xdc\xdd\x9d\x1a\xbe\x54\xd9\xd9\x54\x48\x1b\ -\x1b\x33\xc1\x10\xe0\x81\x37\x4c\x60\x4c\x25\xc0\x77\xf8\x72\xb5\ -\xbe\xc1\x28\xbc\x99\x99\x60\x08\xf0\x22\xf2\x56\xcf\x33\x32\x13\ -\x0c\x19\x3e\xf3\x4c\xd0\x77\xf8\x95\xdb\xb5\x7b\x4a\xa9\x77\x7a\ -\xde\xa4\x57\xe7\x7f\x09\x28\x2a\x3c\xc0\x5c\xca\xc5\xda\x98\xe4\ -\x6c\xc4\xdd\xdd\xfd\x69\xf3\xb2\xc0\xc3\x84\x27\xc0\x25\xfc\x61\ -\xa7\xe9\x1c\x1e\xce\x38\x09\xfa\x0e\x5f\xaa\xec\xac\x03\x23\xf0\ -\x4c\x79\x62\x1c\xfb\x04\x04\x02\xff\x5e\xcf\x23\xc5\x1e\x32\x22\ -\xe0\xef\xd9\xb9\x8d\x21\xf8\x84\xbc\xf4\x8f\x7d\x42\x1e\x29\x37\ -\xd0\x53\x02\x96\x1b\x8d\xf9\xcb\xc7\x83\x63\x05\x8b\x43\x97\x53\ -\xc3\x27\xe4\xa5\x86\x37\x9d\x07\xda\x49\x70\xf1\xe4\x64\x4e\xc1\ -\xc2\xd0\xa5\x4c\x9f\xa5\x8c\xc9\xcb\xb4\x58\xd3\x79\xa0\xbd\x06\ -\xbf\x1d\x1d\xfd\xba\x72\xf5\xda\x0f\xe0\xa6\xc0\xcf\x48\xd8\x8a\ -\xbb\xad\x4e\xda\x70\x3d\x0f\xd4\x83\xb8\xdb\xfc\xe8\x4b\x5e\x62\ -\xad\xae\x3e\x59\x58\x6e\x34\xe6\x7d\xcd\xbb\xb1\xbd\x7d\xd1\x64\ -\xde\xac\x66\x75\x8e\xeb\x0f\x00\x7d\xea\x19\xbf\xa0\x8f\x59\x00\ -\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x14\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xc6\x49\x44\x41\x54\x58\x85\xed\ -\x94\xb1\x6a\x14\x51\x14\x86\xbf\xff\xee\xa0\x41\xd0\x68\x13\x8b\ -\xb4\xda\xd8\xac\x20\xee\x6e\xd4\xd4\x22\x06\x45\xb1\x11\x05\x4b\ -\x0b\x51\x1f\x41\xf3\x08\x06\x1f\x40\x50\x10\x42\x76\xb3\x91\x88\ -\x98\x2e\xe0\x82\x08\x01\xf5\x05\xb4\x12\xc4\xc6\x4a\x58\xb3\x73\ -\x7f\x8b\x99\x84\x24\xbb\xd1\xec\xb0\x6a\x33\x5f\x75\x87\x7b\xee\ -\xf9\xff\x73\xce\xbd\x03\x25\x25\x25\x25\xff\x19\x15\x3d\x38\x35\ -\xef\xc9\x98\xf8\x25\x50\x4d\x2a\x9a\xec\x5c\xd6\x97\x22\x79\x42\ -\x91\x43\xf5\x05\x1f\x8f\x89\xdf\x00\x55\x80\x5e\xea\xce\xd4\x92\ -\x8f\x15\xc9\x35\x74\x07\x4e\x2f\xfa\x64\xb0\x5f\x03\x13\xd8\x79\ -\x16\x01\x7c\x35\x3a\xff\xee\xaa\x3e\x0c\x93\x6f\xa8\x0e\xd4\xda\ -\x9e\x0e\xf6\x2a\x30\x81\x30\x41\x29\x41\x29\x60\xe0\xa8\xf0\x6a\ -\xad\xed\xe9\xbf\x62\xa0\xd6\xf2\x8c\xa2\x57\x80\x43\x16\xc6\x44\ -\x9c\x4b\x43\x74\xb6\x1a\x57\xf4\x4a\xad\xe9\x8b\x23\x35\x50\x5f\ -\xf4\x4d\xe1\x36\x30\x06\xb6\x4c\xdc\x19\x23\x88\x64\x33\x19\x93\ -\xbc\xd4\x68\xf9\xc6\x48\x0c\x34\x5a\xbe\x87\xfd\x14\xa8\x18\x1b\ -\xd4\x27\xbe\xc5\x46\xcc\x62\xa8\x18\x3f\x6b\x34\x7d\xb7\xb8\x01\ -\x5b\xf5\x56\x3a\x6b\xfc\x28\xff\x8c\xfa\xad\x78\x6e\x01\x45\xe7\ -\x71\x96\xe7\x1a\xcd\xf4\x21\xf6\xae\x97\x7d\xf0\xc6\x03\x87\x7a\ -\x35\xce\x81\xee\x00\x18\xa2\x36\xa6\xbd\x47\x9c\xbd\x8d\x00\x20\ -\xfb\xf1\xdb\x8f\xe1\x3e\xb3\xfd\x05\xf4\x19\x38\x31\xef\x7d\x07\ -\x93\xf8\x04\x74\xdd\x59\xa6\x28\x0d\x27\xbe\x69\xc2\x08\x11\x32\ -\x11\x3f\xef\x7d\x0b\xb7\xd6\x6e\x6b\x7d\x57\x03\xa7\x5e\xf8\x40\ -\xd2\xf3\x02\x70\x21\x1b\xb7\x22\x43\x56\x3e\x00\x81\x43\x2e\xf5\ -\xaa\x97\xe8\xda\xda\x25\xfd\xe8\x33\x70\x6e\xd9\x47\x7e\x76\xbd\ -\x2c\x71\xc6\x80\x4c\xa4\x60\xe5\x3b\xd9\xde\x09\x3a\x5d\x69\xe6\ -\xfd\x15\x7d\x07\x48\x36\x82\xd6\xbb\xfe\x24\x31\xbe\xe9\x4a\xc5\ -\x7e\xd3\x83\xd0\xf6\x41\x9f\xdd\x6f\x7f\x06\x0e\xc3\x96\x57\xe0\ -\xd1\x14\xbb\x27\xec\x7f\xa7\x55\x52\x52\x52\xf2\x47\x7e\x01\x51\ -\xe3\xba\x72\x94\x2f\x72\xc5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x00\xd1\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x83\x49\x44\x41\x54\x78\x9c\xed\ -\xd7\xb1\x0d\xc2\x40\x10\x04\xc0\x7d\x8a\x40\x34\x42\x23\xb4\x40\ -\x80\x1c\xd1\x0b\x89\x45\x23\x54\xe1\x42\x2c\x9a\x78\x52\x64\x7d\ -\x6a\x8c\xfc\x33\xe1\xea\x82\xbd\xcb\x2e\x01\x00\x00\x00\x00\xa0\ -\x1f\x65\x19\x9c\x6f\x8f\x4b\x92\xb1\x26\xc7\x0d\xfa\xac\x69\x4e\ -\xea\x75\x7a\xde\x5f\xdf\xe1\xa1\x31\xb8\xc7\xe5\x93\xe4\x94\x94\ -\x71\x19\xb6\x0e\xd0\x95\xd6\x01\x86\x92\xbc\x7f\xde\x64\x7d\x73\ -\x52\x87\xad\x4b\x00\x00\xff\xc3\x2f\xd0\x18\xdc\xe3\xf2\x89\x5f\ -\xa0\xcd\x2f\x00\x00\x00\x00\x00\x00\x40\x27\x3e\xec\xfd\x1c\x0f\ -\x3a\x57\x98\xc9\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\ -\x00\x00\x01\x34\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xe6\x49\x44\x41\x54\x78\x9c\xed\ -\xd2\xb1\x09\xc2\x40\x00\x46\xe1\x5f\x87\xc8\x26\x2e\xe2\x0a\x29\ -\xc4\xc6\x61\x6c\x82\x4b\xb8\x88\x5b\xa4\x72\x8b\xb3\x30\x60\x21\ -\x36\xde\x5d\x9e\xe0\xfb\x20\x90\xc0\xa1\x7f\x1e\x49\x24\xfd\xb3\ -\x4d\xef\x3f\xd8\x1d\xce\xfb\x24\xd3\xf2\x78\xbc\x5d\x4e\xd7\x96\ -\xe7\x6b\x6d\x7b\xfe\xf8\x62\x2a\xc9\x50\x92\x21\xaf\x17\x6b\x79\ -\xbe\x4a\xf7\x00\xcb\x8b\xbc\xdd\xb7\x3a\x5f\x6b\x8d\x2f\xe0\xa7\ -\x19\x80\x1e\x40\x33\x00\x3d\x80\x66\x00\x7a\x00\xcd\x00\xf4\x00\ -\x9a\x01\xe8\x01\x34\x03\xd0\x03\x68\x06\xa0\x07\xd0\x0c\x40\x0f\ -\xa0\x19\x80\x1e\x40\x33\x00\x3d\x80\x66\x00\x7a\x00\xcd\x00\xf4\ -\x00\x9a\x01\xe8\x01\x34\x03\xd0\x03\x68\x06\xa0\x07\xd0\x0c\x40\ -\x0f\xa0\x19\x80\x1e\x40\x33\x00\x3d\x80\x66\x00\x7a\x00\xcd\x00\ -\xf4\x00\x9a\x01\xe8\x01\x34\x03\xd0\x03\x68\x06\xa0\x07\xd0\x0c\ -\x40\x0f\xa0\x19\x80\x1e\x40\x5b\x23\xc0\xfd\xc3\x7d\xab\xf3\x55\ -\x56\x08\x50\xc6\x24\xf3\xf3\x2a\x63\xfb\xf3\x92\xf4\xbd\x07\x47\ -\xdd\x22\x24\x17\x57\x09\xda\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x04\x2e\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\xe0\x49\x44\x41\x54\x78\x9c\xed\ -\x98\x4d\x68\x5c\x55\x14\xc7\x7f\xe7\xbd\x32\xa9\x9a\xb8\xb1\x94\ -\xb4\x52\xc4\x8d\xd6\x8d\x60\x32\x16\xba\x28\x34\x7e\x84\x88\x52\ -\x94\x4a\x51\x57\xcd\xa2\xe9\xa4\x69\x26\x11\xea\x27\x04\x09\x56\ -\xb0\x5d\xa8\xcd\xd4\x7c\x8c\x94\x44\x84\x82\x9b\x62\x5d\x18\x69\ -\xa9\x4c\x16\xae\xe6\x4d\x0a\x6e\xfc\xc0\x45\x69\x35\x0b\x9b\x48\ -\x21\x81\xa6\x53\xe7\x1d\x17\xc9\x68\xe6\xbd\x97\x4e\x66\xe6\xbd\ -\x49\x4a\xef\x6f\x79\xcf\xbb\xe7\xfe\xcf\xb9\xef\xde\x7b\xee\x05\ -\x83\xc1\x60\x30\x18\x0c\x06\x83\xc1\x60\x30\x18\x0c\x06\xc3\xbd\ -\x85\x78\x1b\xe2\x5d\xa9\x0f\x04\x1d\x50\xc1\x56\x70\x05\x74\x3d\ -\x84\x85\x85\x82\x08\x58\xa2\x14\x14\xf9\xd0\x49\xf7\x0e\xae\xb4\ -\x6f\xf2\xf5\x10\x1d\x50\xb0\x01\x04\xac\x3a\xe9\x8c\x8c\xe2\x0c\ -\xab\x60\x83\x0e\x00\x25\x09\xb8\xeb\x03\xac\x15\x7f\x02\x54\x8f\ -\x2b\x72\x57\xff\xf6\x41\x28\xa2\xa8\x1e\xf7\xb6\xfb\xf6\x00\x80\ -\xd6\xae\x53\x6d\x22\x72\x1e\x68\xf2\x7c\xae\xa0\x6e\x24\x0a\xc3\ -\xc3\xc2\x1f\xd7\x3c\x22\xfb\x9c\xd1\xde\x8c\xf7\xe3\xc0\x04\x00\ -\xb4\x74\x9f\x6a\xb5\x5c\xf9\x1e\xd8\x52\x62\x50\x14\x61\x43\x26\ -\x41\xc1\x12\x7f\x4c\xb3\xae\xa5\x1d\xd3\x23\x7d\xb9\xa0\x3e\xab\ -\x26\x00\x20\xde\xfd\xd9\xe3\xb8\xd6\x45\x60\x87\xa7\x9b\x02\xee\ -\xc6\x39\x20\x64\x39\x78\xf5\xc6\x73\x15\xcb\x6d\x77\x46\xfa\x7f\ -\x5d\xbd\x67\x19\x9e\x3e\xf2\xf9\x0e\x2d\x14\x2e\x00\x3b\x3d\x5d\ -\x37\x48\x12\x04\xc0\xc2\x1f\xfc\x2f\x62\xdb\xed\xd9\xe1\x9e\x6b\ -\x77\xea\x5d\xf6\x14\xc8\x0e\xf7\x5c\x53\xcd\xef\x01\x9c\x52\x8b\ -\x8a\xa2\x76\xf9\x14\x46\x87\x00\x8a\xda\xbe\xe0\x85\xac\x6a\x7e\ -\x4f\xb9\xe0\x61\x8d\xc7\x60\x2e\x7d\x6c\xb6\xe1\xf6\xcd\x67\x04\ -\x7e\xf0\x09\x50\xec\xf5\xc8\x81\x82\xb8\x04\x8e\x7d\xa9\x21\x7f\ -\xf3\xd9\x5c\xfa\xd8\xec\x5a\xfc\x54\xa4\x7d\xef\xc1\xf1\xcd\xf3\ -\x0d\x0b\x67\x05\x7d\xc5\x2f\x48\x5d\xa9\xd3\xf1\xa9\xa8\x08\x12\ -\x34\x79\xe7\x6e\xc4\x78\xe3\xf7\x54\xf2\xd6\x5a\x7d\x55\x54\x08\ -\x65\x26\x3a\x17\x9b\x9a\x67\x0f\x80\x9e\xf1\xda\x04\xb1\xb4\xc2\ -\x84\x56\xc3\x52\x69\x1b\x14\xbc\x9e\x79\xf4\xef\xe6\x03\x95\x04\ -\x0f\x55\x0b\x56\x89\x1f\x4e\x9d\x00\xde\x0a\x10\x18\xd9\xfd\xa1\ -\x58\xd7\xfb\x0d\x7a\xd2\x49\x27\xdf\xa5\x8a\x3f\xb0\xa6\x19\x8b\ -\x27\x52\x6f\xa3\x7a\x22\xc0\xab\x8b\x86\x9d\x04\x15\x82\x66\x5e\ -\xe4\x1d\x67\xb4\xf7\x64\xb5\x5e\xed\x5a\x24\xcd\x38\x93\x3f\x6e\ -\x6b\xed\xf8\x53\x44\x5e\xa2\x34\x99\xa2\x84\xb8\x1e\x84\xa0\xe0\ -\x5d\x90\x43\xce\x58\xef\xe9\xda\x5c\x87\x40\x3c\x91\xda\x8f\xea\ -\x59\x20\xe6\x31\x2d\xd7\x0a\x35\x11\x54\xda\xe6\x05\x5e\xcf\x8e\ -\x25\xcf\xd5\xe8\x3b\xbc\x49\x8a\x1f\x1a\x7a\x0e\x8b\x6f\x80\x07\ -\x56\xb6\xeb\xd2\x96\x5d\x65\x12\x24\xa8\xc0\x59\x10\xf4\xe5\xec\ -\x58\xdf\xa5\xea\x7c\x7a\x46\x08\xc3\x49\x91\x78\x62\x68\x17\xca\ -\x77\xc0\x43\x9e\x61\xaa\xb8\x44\x05\x06\x3f\x27\xae\xfb\x42\xf6\ -\x8b\xfe\x6c\x2d\x3a\x4b\x46\x09\xcb\x51\x91\x96\x23\x9f\x3e\x21\ -\x85\x4d\x17\x05\x7d\xd8\x63\xaa\x60\x39\x04\x06\xff\x87\x6b\x17\ -\xda\xa7\x87\xdf\xfc\x39\x04\x99\xff\x8f\x14\xa6\xb3\x22\x4f\xf5\ -\x9c\x7e\xc4\xfe\xc7\xbd\x00\x3c\x56\x62\x50\x51\xe4\x4e\x7f\x82\ -\x00\x1a\xb4\xe6\x7f\x53\x75\x9f\xcf\xa5\xfb\xaf\x86\x2c\x35\xba\ -\xc2\xe5\xc9\xc4\xc8\xd6\x98\xde\x9e\x04\x5a\x4a\x2d\x0a\x48\x21\ -\x50\x89\xaa\x1d\x20\x69\xba\x90\xa7\xe3\xf2\x78\xf2\x7a\x14\x3a\ -\x23\x7b\x12\xfb\x69\xb4\xfb\x2f\x3b\x46\x1b\xc2\x54\xa9\x45\x00\ -\x4a\x2e\x51\xc5\x3b\x45\x40\xf0\x19\x3b\x46\x5b\x54\xc1\xff\xa7\ -\x26\x4a\xf6\x1e\x1c\xdf\xbc\x10\x9b\xff\x1a\x61\x9f\xd7\xa6\xcb\ -\x7b\xc2\x2a\x8f\xaf\xe7\x1b\x6f\x35\xbd\x96\x99\xe8\x5c\x8c\x52\ -\x5f\xe4\x8f\xa2\x99\x89\xce\xc5\xc6\x6d\x73\xfb\x45\xe4\x4b\xaf\ -\x4d\x96\x5e\x70\x7c\x1a\x14\x26\x1a\x9b\xe7\x5e\x8d\x3a\x78\xa8\ -\xb1\x12\x5c\x2b\x57\xa6\xa6\xdc\x99\x17\x77\x7d\xbb\x7d\xfe\xbe\ -\x07\x11\xd9\x5d\xe6\xf3\x4f\x72\xcd\x73\x47\xaf\x0c\x0e\xfa\xf7\ -\x89\x08\xa8\xf3\x55\x5e\x25\xde\x95\x7a\x0f\xe1\xa3\x60\x31\xfa\ -\x7e\x76\x2c\xf9\x71\x35\x97\x9a\x6a\x59\x97\xf7\x9c\x78\x62\xe8\ -\x30\xca\xe8\x8a\x26\x45\x35\xe1\xa4\xfb\xd2\xf5\xd6\x52\x97\x25\ -\xe0\x65\xc6\x99\xcc\x6d\x6f\xed\xb8\x1f\x91\x9d\x02\x0b\x40\xa7\ -\x93\xee\xfb\x6a\x3d\xb4\x18\x0c\x06\x83\xc1\x60\x30\x18\x0c\x06\ -\x83\xc1\x60\x30\x18\xee\x35\xfe\x05\x2f\xee\x41\x9b\x3f\x6f\x48\ -\xfe\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x22\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xd4\x49\x44\x41\x54\x58\x85\xed\ -\x94\xb1\x6b\x13\x51\x1c\xc7\x3f\xdf\x17\x84\xa0\x20\x71\xd0\xc1\ -\x49\x89\x08\x4a\x06\x25\xb8\x3a\x79\xb5\x48\xe9\x50\x0d\x8e\x82\ -\x6d\x66\xff\x02\x41\xdd\xfc\x0b\x1c\x92\xb8\x56\xbc\x06\xa1\x75\ -\xf0\x7a\x43\x07\x07\x75\x11\xed\x10\x17\x2d\x2e\x0a\x2e\xb5\x64\ -\xb1\xa1\xe6\x7e\x0e\x97\x33\xa7\x6d\x63\x92\x16\xbb\xdc\x17\x0e\ -\xde\xdd\xfb\xbe\xef\xf7\xfb\x7e\xef\xf7\x0e\x32\x64\xc8\x90\xe1\ -\x80\xa1\x64\xe0\x5d\x9f\xfb\x0e\x14\xfe\x93\xef\x46\xd8\xac\x1f\ -\x03\x70\xfd\x28\x72\xbb\xd2\xf7\x1b\x29\xaf\xfe\x40\xd1\x69\xe0\ -\x75\x8a\x16\x01\xdd\xfd\x78\x84\xa2\xdf\xde\xc6\xab\x9e\xd7\x9f\ -\x01\x02\xbf\xb1\xae\xc3\x9d\x2b\x40\x00\x80\xe1\x48\x1d\xd1\x1e\ -\x76\xab\x08\x73\xf1\x90\x17\x1c\xe9\x78\x81\xdf\x58\x4f\xa6\x73\ -\x69\xee\xa7\xd5\xd5\xad\x72\xa9\xf8\xf4\x87\xe5\xcf\x4a\x94\x30\ -\xb4\xb7\x08\x12\x98\x13\x80\xd9\x93\x82\x6b\xdf\x5c\x9a\x9f\xdf\ -\x4c\x33\x72\x7f\x2f\x69\xb5\x5a\xdd\x72\xa9\xf8\xac\x63\xf9\xe3\ -\x88\x4b\x8c\x5b\x05\xc5\xe6\xc4\x02\x8f\x0a\xb9\x76\xd5\xf7\xfd\ -\x9f\xdb\x68\x83\x24\xbc\x99\xb9\xfb\x88\xbb\xbd\xd7\x08\xcc\x86\ -\x75\x4f\xcc\x41\x0f\xc2\x66\xed\x1e\xb0\xe3\xda\x6d\x15\x48\x63\ -\xed\xc3\xdb\x95\xe2\xf9\xf2\x06\x30\xd9\x0b\xab\xdd\x84\x12\x98\ -\xe1\x24\x92\x9d\xdf\x09\x9b\xf5\x87\x83\xf8\x03\x03\xf4\x42\xbc\ -\x29\x9e\xbb\xb8\x86\x34\x0d\xb8\x5e\x5f\xec\x18\xc2\xcc\x9c\x24\ -\x11\x77\xff\xad\xb0\x59\xaf\xfd\x4b\x7f\xe8\xf3\x9d\xb8\x51\x9d\ -\x32\x33\x1f\xc8\x13\x57\x21\x4a\xcf\xa7\xcc\x37\x25\x55\x96\x17\ -\x6a\xcf\x87\xd1\x1d\xa9\xc1\x26\x66\x66\x2f\x9b\xdc\x12\xd8\x51\ -\x33\x33\x29\xbe\xdf\x7d\x73\xb5\x9d\x6c\x2a\x58\xa8\xbf\x1c\x56\ -\x73\xe4\x0e\xf7\x2a\xd5\x0b\x44\x16\x00\x27\x0c\x4c\x89\x86\xf8\ -\x86\x34\x19\xfa\xb5\x77\xa3\xe8\x8d\x75\xc5\xae\x56\x66\xcf\x44\ -\x11\x21\xe8\x54\xfc\xc5\x3e\x3b\x87\x17\xf8\x8d\x8f\xa3\x6a\x8d\ -\xfd\x9b\xf1\xa6\x6f\x9f\xe4\x90\xfb\x02\x7a\xcf\x56\xf7\x5a\xb8\ -\xf8\xf8\xeb\xb8\x5a\x19\x32\x64\xc8\x70\xa0\xf8\x05\xa4\xf1\xa4\ -\x8e\x44\xc6\x51\x5e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ -\x82\ -\x00\x00\x00\x8a\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3c\x49\x44\x41\x54\x58\x85\xed\ -\xcd\x21\x15\x00\x21\x00\xc0\xd0\x41\x26\x02\x60\xc8\x82\xbb\x30\ -\xa7\x08\xc3\x7b\x14\x20\x14\x0a\x8b\xc4\xb0\xaf\xe6\x06\x92\x24\ -\xbd\x2e\xec\x48\xf5\x1f\x40\xbe\x74\xed\xb3\x7d\x05\x20\x5e\x19\ -\x4a\x92\x24\x1d\x2c\x16\x1c\x05\x04\xcb\x08\x93\xc5\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x93\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x45\x49\x44\x41\x54\x58\x85\xed\ -\xd7\xb1\x4e\xc2\x50\x14\xc6\xf1\xff\x29\xa1\x8c\x96\x05\x9f\xa1\ -\x0b\x03\x09\xf8\x02\x26\xf0\x0e\xac\x26\x94\xc1\x18\x9c\xd5\x41\ -\x76\x10\x19\xe8\x0b\xf0\x0c\xc6\xc4\x27\xa8\x89\x03\x4b\xdf\x81\ -\x05\x1c\x29\x81\xe3\x00\x35\x58\xc0\x41\xdb\x38\x78\xbf\xf1\xb4\ -\xc9\xf7\x4b\x6f\x87\x7b\xe0\xbf\x47\x92\x83\x8a\x37\xac\x5b\xaa\ -\xd7\x40\x0d\x70\x52\xea\x99\x03\xc1\x5a\xa4\xf7\xe6\x5f\x3e\x1f\ -\x05\x54\x5b\x8f\x5d\x85\x1b\x60\x01\x12\x22\xfa\x9e\x4a\xbd\xca\ -\x09\xa8\x0b\x14\x44\xb4\xfb\xea\x5f\xdd\xed\x01\xaa\xad\x41\x43\ -\x91\x27\x84\x97\x88\x7c\x73\xe2\xb7\xa7\xa9\x94\x6f\x53\xf6\x46\ -\x25\x9b\xe5\x18\xe5\x7c\x2d\xd2\x88\xbf\x84\xf5\x89\x44\x3a\xc0\ -\x22\x8b\x72\x80\x89\xdf\x9e\x46\xe4\x9b\x40\x94\x53\xed\xc4\x73\ -\x6b\xe7\x9d\x1a\x48\x98\x45\xf9\x2e\x42\x21\xd4\xcd\xff\xb5\x07\ -\x70\x52\x3b\xf3\x6f\x22\xc2\x1c\x28\x1e\x02\xfc\x49\x0c\xc0\x00\ -\x0c\xc0\x00\x0c\xc0\x00\x0c\xc0\x00\x76\x01\xf3\xcd\xed\x35\xdb\ -\xa8\xe2\x00\xb3\x43\x80\x00\xd4\x2d\x7b\xa3\x52\x56\xe5\x65\x6f\ -\x54\x12\x70\x05\x82\x3d\xc0\x5a\xa4\x07\x14\x6c\x96\xe3\x2c\x10\ -\x67\x17\x0f\xa7\x36\xcb\x31\x60\xaf\x44\xfa\xf1\xfc\xeb\x62\xe2\ -\x0d\xee\x55\xe5\x16\x88\x14\xc2\xed\x05\xf2\xd7\x51\xc5\x11\x70\ -\x01\xfb\xe8\x62\x12\xa7\xe2\x0d\xeb\x39\xd5\xce\xf6\xea\x5c\x4c\ -\x3e\xff\x61\x66\x02\xc1\x4a\xa4\x9f\x5c\xcd\x4c\x3e\x00\xa7\x7c\ -\x6e\x32\xdb\xbd\x64\x45\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ -\x60\x82\ -\x00\x00\x00\xa1\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x53\x49\x44\x41\x54\x58\x85\x63\ -\x60\xa0\x00\x98\x64\x4c\x6c\x30\xc9\x98\xd8\x40\x89\x19\x4c\x94\ -\x68\xa6\x06\x18\x75\xc0\xa8\x03\x46\x1d\x30\xea\x80\x51\x07\x8c\ -\x3a\x60\xc0\x1d\xc0\x42\x05\x33\x1c\x28\xa9\x92\x87\x45\x08\x1c\ -\x38\x33\x23\xbf\x81\x5c\xcd\x03\x1e\x02\xa3\x0e\x18\x75\xc0\xa8\ -\x03\x46\x1d\x30\xea\x80\x51\x07\x0c\xb8\x03\x00\xb9\x93\x08\x9d\ -\x47\x2d\xcd\xca\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\ -\x00\x00\x03\x9c\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x4e\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\xcd\x6b\x13\x41\x18\xc6\x9f\x77\xd3\xa8\x85\x52\x0f\x22\x22\ -\xf6\x60\x6d\x3c\xa8\x05\xd1\x93\xde\x8a\x36\x89\x15\x14\x9b\x18\ -\x94\x16\x11\xd2\x54\xfb\xf1\x07\x14\xff\x02\xeb\x51\x69\xfd\x22\ -\xed\xa5\xd4\x83\x31\x55\x11\x5a\x4d\x2a\xb4\xe0\xc1\x8b\x1f\x87\ -\x22\x3d\x58\x11\xcc\xa5\x8a\x87\x96\x8a\xa9\x49\x66\x3c\x18\x04\ -\xb3\x9b\x4d\xb3\xbb\x93\x31\xcd\xfc\x8e\xb3\xc3\xf3\x3e\xfb\x64\ -\x32\x33\xec\xce\x02\x0a\x85\xa2\x96\x21\xbb\x02\x6d\xa1\x81\x06\ -\x37\xcf\x0c\x82\xf1\x10\x08\xad\x00\xb6\x3a\xe0\xcb\x0e\xeb\xe0\ -\x58\x80\x46\xb1\x0c\xb9\x47\xe7\x62\xb7\xd7\xcc\x3a\xdb\x0a\xc0\ -\xd7\x19\xf1\x72\x0d\xe3\x00\x9a\xec\xe8\x08\x24\x45\x0c\xe1\xc4\ -\xe3\x68\xb2\x58\x07\x97\x55\x65\x5f\xb0\x27\xcc\x89\x1e\x02\xd8\ -\x6e\x55\xa3\x02\x34\x82\xd0\xb5\xef\xd0\xd1\x2f\x9f\x3e\xbc\x7d\ -\x6f\xd4\xc1\xd2\x08\xf0\x9e\x0f\xfb\xc0\xb5\x19\x00\x9a\x2d\x7b\ -\x95\x23\x47\x0c\x1d\x46\x23\xa1\xec\x00\xda\x42\x03\x0d\x6e\xf6\ -\x6b\x11\xc0\x1e\x47\xac\x55\x8e\x54\x46\xdb\x72\xa0\x70\x4e\x28\ -\xfb\x17\x74\xf3\xcc\x20\xaa\xef\xe6\x01\xa0\x29\xef\xfd\x1f\xca\ -\x1f\xc2\x8c\x87\x1c\xb1\x23\x03\x03\xef\xe5\x07\xf0\x67\xa9\xab\ -\x4e\x0c\xbc\xd7\x59\x90\x31\x5d\xe7\x93\xf1\xa8\xed\xbd\x85\x1d\ -\xbc\xc1\x08\x37\xb9\xac\xf3\x5e\x2d\xb3\xb8\x30\x54\x00\xb2\x0d\ -\xc8\x46\x05\x20\xdb\x80\x6c\x54\x00\xb2\x0d\xc8\xa6\xe6\x03\x28\ -\xb9\x11\xf2\x07\xae\xec\x66\x60\xfd\x20\x9c\x24\x60\x97\xd9\x2e\ -\x03\x00\x7c\xc1\xc8\x47\xab\x66\x38\xc0\x01\xa4\x08\x98\x76\x6d\ -\xfb\x79\x6f\x66\x72\x72\xd5\xaa\xd6\x46\x31\x0d\xc0\x1b\xe8\x3d\ -\xcb\x88\x8d\x03\xd8\x91\x37\x58\x12\x0e\xb4\xd8\xf4\xe4\xe1\x40\ -\x5b\x36\x5d\xdf\xdf\x1e\x88\x74\xcd\x4e\x45\x5f\xdb\xd4\x33\xa5\ -\xe8\x5f\xc0\x1b\xe8\x19\x06\xf1\xa7\xc8\xdf\xbc\x04\x9a\x89\xf0\ -\xca\x1b\xec\xed\x13\x59\xc4\x30\x00\x5f\x20\x72\x01\x44\x43\x22\ -\x0b\x6f\x10\x17\xc0\x47\xda\x03\x91\x63\xa2\x0a\xe8\x02\x38\x75\ -\xae\x6f\x2f\x27\xba\x2f\xaa\xa0\x05\x5c\x44\x78\xd0\xd1\xdd\xdd\ -\x28\x42\x5c\x17\x40\xd6\x95\xbd\x06\x70\x21\xc5\x6c\xd0\x9c\x4b\ -\xd7\x5f\x15\x21\xac\x0b\x80\x80\xd3\x22\x0a\xd9\x85\x0b\xf2\x65\ -\x34\x07\xfc\xaf\x8f\xb8\x85\xf8\x2a\xfb\x81\x88\xa6\xf1\xfd\x22\ -\x8c\x64\xb3\xf0\x68\x1a\xcd\x14\xbb\x4e\x0e\xbc\xc4\x31\xa2\xec\ -\x00\x5e\xc4\xc6\x2c\x6f\x74\xcc\xf0\x87\x7a\xc0\x98\x08\x65\x73\ -\x6a\x7e\x2b\xac\x02\x90\x6d\x40\x36\x2a\x00\xd9\x06\x64\xa3\x02\ -\x90\x6d\x40\x36\x2a\x00\xd9\x06\x64\xa3\x02\x90\x6d\x40\x36\x2a\ -\x00\xd9\x06\x64\x63\xe5\x7c\x80\x14\x38\xd0\x52\xe2\xdd\xff\x46\ -\x58\x2f\x6c\xa8\xad\x11\xc0\xb1\x50\xd8\x54\x5b\x01\x68\x14\xd3\ -\x35\xc9\xf0\x21\x89\x54\x86\xdc\xa3\x85\x8d\x55\x33\x07\xd8\x24\ -\x47\x0c\xe1\xb9\xb8\xfe\xdc\x70\x2d\x04\x90\xe3\x84\xde\x64\x91\ -\xf3\xc2\x9b\x3d\x80\x14\x31\x84\x8b\xdd\x3c\xb0\x39\x03\xf8\x7b\ -\x5c\x9e\xea\xd3\x23\x89\x89\x89\x1f\x66\x9d\x75\x8f\x9a\x1d\x58\ -\x6b\x85\x40\xc0\x52\x22\x1e\xf5\x38\xad\x6b\xb4\x0a\x7c\x73\xba\ -\x88\x13\x70\x60\x59\x84\xae\x51\x00\xb3\x22\x0a\xd9\x86\xe3\xa5\ -\x08\x59\x5d\x00\x1a\x63\x37\x00\x64\x44\x14\xb3\xc1\x77\x0d\xda\ -\x1d\x11\xc2\xba\x2f\x46\x96\x16\xdf\x2d\x7b\x0e\x1e\x59\x03\xc8\ -\x2f\xa2\xa0\x15\x08\xfc\x62\x62\x2a\xfa\x46\x84\xb6\xe1\x4e\xf0\ -\x78\x6b\xd3\x4d\x10\x1e\x89\x28\x58\x2e\x04\x0c\x27\xe2\x63\xcf\ -\x44\xe9\x1b\x7e\x33\x34\x3f\x3f\xcf\x2f\x85\xce\xc4\x53\x5f\x57\ -\x57\x00\x3a\x51\xac\x9f\x60\x56\x38\xe8\x72\x32\x1e\xbd\x25\xb2\ -\x48\xc9\x37\xae\xfe\xce\xf0\x61\xa6\x69\x43\x00\xda\x01\xec\x14\ -\x69\x26\x4f\x8a\x03\xd3\x75\xb9\xba\xeb\xcf\x9f\xdc\xfd\x5c\x81\ -\x7a\x0a\x85\xa2\x86\xf9\x0d\x29\x0e\xd0\xf4\xc6\x6c\xeb\x8f\x00\ -\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x9f\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x51\x49\x44\x41\x54\x58\x85\xed\ -\x94\x2d\x48\x43\x51\x14\x80\xbf\xf3\x36\x10\x14\x15\x67\xd1\x66\ -\x17\x2c\xbe\x55\x8b\x98\x4d\xb3\x6a\x71\x4f\xd0\x4d\x8c\x82\xe0\ -\x5e\xb0\x98\xdc\x14\xdd\xc6\xc2\xaa\x13\x9b\x59\xb0\xcf\xbf\x64\ -\x53\x9b\x7f\xf8\x93\x06\x8a\xbb\xc7\xb4\x89\xf1\xdd\x07\xaf\xf8\ -\xbe\x76\xe0\xfc\x7c\xdc\x7b\xee\x85\x98\x98\x98\xff\x8e\x04\x4b\ -\x57\x71\xbd\x5d\x03\xf0\xfd\xd9\x1e\xba\xaa\xaf\x7d\x84\x15\x70\ -\x02\x65\x6f\x16\xba\xc2\xc9\x9e\xc4\x7b\x26\xd3\x48\x44\x2b\xe0\ -\xfb\x46\x55\xe6\x3a\xe1\x5d\xea\xf1\x3b\x5a\x01\xe0\xbc\x9a\x3b\ -\x42\x65\xab\x13\xbb\xd9\xd2\x75\xa4\x02\x00\xcd\x6a\x6e\x43\xe0\ -\x14\x00\x61\xc2\xf5\x8a\x07\xb6\x02\x01\x97\xf0\x2f\xae\x57\xd2\ -\x6e\xa0\xea\x35\xab\xab\xd5\xa0\x3d\xac\x4e\xa0\x43\x73\xe4\xf5\ -\x77\x09\x45\x2a\x69\x6f\x67\x2a\x52\x01\x7c\xdf\xb4\x12\x89\xfe\ -\x4e\xa8\x38\x67\xd1\x0a\x00\xbc\x3c\x7f\x29\xdc\xdb\x96\x87\x14\ -\x50\xe9\x1d\x1a\xae\x09\x8c\x01\x4f\xed\xa4\x33\x16\xb4\x43\xa8\ -\x8f\xc4\x5d\x4a\x15\x40\xf2\x40\xcb\x38\x3a\x73\xb9\x9f\xbf\x09\ -\xda\xc3\xfa\x15\x4c\x66\x8b\xf3\x22\x52\x07\x8c\x11\x67\xf6\xa2\ -\xbc\x72\x62\xd3\x27\x69\x53\x94\xf6\x8a\xd3\x8a\xd4\x00\x14\x59\ -\xb6\x1d\x0e\x16\x3b\x90\x5e\xdc\x1b\x57\xe4\x18\x48\xa2\xba\x7d\ -\x5e\xc9\x95\x6d\x87\x5b\x08\xa8\x18\xc7\x34\x80\x41\xe0\xb0\x39\ -\xfa\xb6\x1e\x66\x38\x58\x5c\x81\xc0\x83\xa0\xb7\x7d\x9f\x03\x0b\ -\xf8\x79\x13\x56\x20\x26\x26\x26\xe6\x07\x9e\x35\x61\x37\x0a\x6d\ -\x65\xe5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x97\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x49\x49\x44\x41\x54\x58\x85\xed\ -\xd7\xb1\x0d\x00\x20\x0c\x03\x41\x0b\x31\x18\x83\x23\x65\x15\x94\ -\x0c\x12\x86\x30\x1d\xff\x7d\xac\x6b\x23\x91\xd1\xc9\x8a\x93\x15\ -\xce\xc6\xb4\x04\xad\x65\xdd\x4b\x1a\xee\x00\x00\x00\x00\x00\x00\ -\x00\x00\x00\x00\x00\x00\x00\x00\xb8\x79\x9f\x91\x7a\xbf\x61\xfc\ -\xdc\x05\xd1\x25\x09\xfd\x18\x55\xe2\x51\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x87\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x39\x49\x44\x41\x54\x58\x85\xed\ -\xce\x31\x11\x00\x30\x08\x04\x41\x26\x9a\x10\x85\x0c\x2c\xe0\x38\ -\x22\xa0\xdc\xeb\xff\x67\x23\x16\x65\x4d\x67\x4d\x6f\x3e\xde\x66\ -\x7c\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ -\xc0\x07\x39\x3f\x03\x99\x39\x3b\x26\x1f\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x0d\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xbf\x49\x44\x41\x54\x58\x85\xed\ -\x94\xb1\x6a\x54\x41\x14\x86\xbf\x7f\x36\x4a\x90\xe0\x6a\x13\x8b\ -\x8d\x91\x04\xad\x63\x91\x4a\x49\x2d\x62\x4a\x1b\x51\xf0\x01\x44\ -\x7d\x05\x7d\x04\x83\x0f\x20\x28\xd8\x58\x28\x28\x62\xba\x80\x79\ -\x00\x61\xfb\xdd\xd9\xd9\x15\x02\x29\xac\x6c\xc2\x9d\xdf\xe2\xee\ -\x26\x31\xbb\x01\xf7\xba\x62\x73\xbf\xe2\x32\x70\xee\x9c\xff\x9b\ -\x73\x87\x0b\x35\x35\x35\x35\xff\x19\x55\xdd\x98\x52\x6a\x15\xe6\ -\x13\x66\x2d\xc8\xad\xe5\xe5\xe5\xef\x55\xfa\x84\x8a\xe1\xd7\x8a\ -\xac\xaf\x98\x35\x80\xec\xb0\x9b\x52\xba\x5a\xa5\xd7\xd4\x13\xe8\ -\x74\xfa\xd7\x15\xfc\x05\x58\x04\x1f\x6b\xa3\xbd\x5c\x70\x6b\x75\ -\x75\xe9\xdb\x34\xfd\xa6\x9a\x40\xaf\xd7\xdb\x50\xf0\x0e\xb0\x28\ -\x30\xa8\x00\x15\xe5\xda\x97\x42\xc3\x3b\xbd\x5e\x6f\xe3\x9f\x08\ -\xc4\xd8\xdf\xcc\xd6\x36\x70\x1e\xb0\x21\x8f\x6a\xc3\xb5\x81\x66\ -\xb6\xb6\xbb\xdd\xfe\x9d\x99\x0a\xc4\x98\x1e\x18\xbf\x07\xe6\xcb\ -\xec\xa3\xf0\x63\xe4\x61\x6d\x1e\xf9\x43\xb7\x9b\xee\xcf\x44\x20\ -\xc6\xf4\xc4\xf0\x1a\x68\xb8\x1c\xfb\xa4\xf0\x21\xca\x18\x03\x0d\ -\xc4\x9b\x18\xd3\xe3\xca\x02\xb6\xd5\x89\xe9\xb9\xe1\xc5\xa8\xb9\ -\x26\x9f\xfc\x84\x03\x19\x95\x92\x86\xad\x4e\x4c\xcf\x6c\x9f\x7a\ -\xd9\x27\x16\x6c\x87\x98\xfa\x5b\x98\x47\xb6\x09\x52\xf6\xd1\x95\ -\xff\x43\x24\x3b\x07\x49\x20\x5e\x5e\xb9\xbc\xf4\x54\x1a\x9f\xde\ -\x98\x40\xbb\xdd\x3e\xbb\xb0\xd0\x7c\x85\xb8\x37\xd4\xc9\xa0\x29\ -\xc3\x0f\x8f\x22\x50\x39\x65\xf3\x76\x7f\x7f\xef\xe1\xfa\xfa\xfa\ -\xc1\xa9\x02\x83\xc1\xe0\xdc\x41\x91\xdf\x61\x6e\x97\x7b\xc8\x9a\ -\xfa\xe4\x27\x14\x40\xc2\x01\x04\xe2\xf3\x99\x46\xb8\xdb\x6a\xb5\ -\x7e\x8e\x09\xc4\x18\x2f\x9a\xf0\x11\xb8\x51\x5e\x66\x65\xf4\x77\ -\xe1\xc7\x2c\x04\x0e\x48\x80\x77\x9d\x8b\xcd\x95\x95\x95\x1f\x00\ -\x73\xa3\x77\xb2\x43\x47\xa2\x59\x6a\x09\x2a\xfe\xa6\x27\xa2\xc3\ -\x07\xa0\x9b\x0a\x73\x5d\xe0\xc2\xef\x21\x55\x3f\x73\x05\x3c\xa3\ -\xc1\xd6\xd4\xd4\xd4\xcc\x84\x5f\x30\x7d\xb9\x9b\x4b\x8f\xb2\x18\ -\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x75\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x27\x49\x44\x41\x54\x78\x9c\xed\ -\xc1\x01\x0d\x00\x00\x00\xc2\xa0\xf7\x4f\x6d\x0e\x37\xa0\x00\x00\ -\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x77\x03\ -\x40\x40\x00\x01\x8f\xf2\xc9\x51\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x04\x67\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x19\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4d\x88\x1c\x45\x18\x86\xdf\xb7\x67\x27\x59\x91\x78\x31\x88\ -\x30\x3b\xdd\xd3\x3b\x89\x3f\x57\x5d\xbc\x0a\xc1\x44\x22\xf8\xc3\ -\x22\xe2\x41\x10\xfc\x41\xc1\x93\x22\x01\x3d\xa8\xa0\x01\x45\xf0\ -\xa0\xe0\x1f\x0a\x1e\x44\xd1\x53\x0c\x62\x64\x83\x10\xf0\x22\x08\ -\x82\x07\x31\x38\xcb\x6c\xd7\xf4\x74\x30\x46\x11\x45\x71\xcd\xf4\ -\xd4\xe7\x61\x26\xc6\xed\x6a\xcd\x8e\xa9\xaa\xee\xc3\x3c\xb7\x6d\ -\x96\x7a\xbf\x7a\xa6\xba\xbb\xbe\xee\x19\x60\xce\x9c\x39\x73\x2c\ -\xa0\x54\xfa\x4c\xa2\xd2\x5c\x0d\xd2\x91\x52\xd9\xd3\x55\xd7\xb3\ -\x5d\x68\x6b\xa0\x44\xa5\x63\x00\xc1\xf4\x4f\x11\x8d\x7d\x71\xdc\ -\x3e\x61\x6b\x7c\x57\x04\x17\xfe\x97\xed\x21\x22\xff\x1c\x8b\x0c\ -\x70\x54\x29\x75\xbd\xad\xf1\x5d\x61\x4d\x00\x49\x5d\x38\xb4\x4b\ -\x10\x7c\xda\xef\x67\x57\xdb\xca\x70\x81\x35\x01\x00\xa4\xe4\xd8\ -\xee\x46\x43\x1f\x5f\xcf\xb2\xb6\xc5\x1c\xab\xd8\x14\x50\x8a\x00\ -\xed\x85\x5c\xaf\x65\x59\xb6\xdb\x75\xd6\xff\xc1\xb9\x80\x29\xd7\ -\x8c\x72\x7d\xec\xe4\xc9\x33\xbb\x3c\xe5\x6d\x1b\x97\x02\x8a\xa7\ -\xc4\xca\xe2\x25\x9b\x47\x7a\xbd\xde\x4e\x87\x99\x33\xe3\x52\x80\ -\x86\x29\x61\x5f\x73\xe7\xe2\x7b\x22\xb2\xe0\x30\x77\x26\x5c\x9f\ -\x02\x1a\xe0\x56\x09\x82\x55\x95\x0e\x5f\x17\x11\x6b\x7b\x90\x8b\ -\xc1\xc3\x35\x40\x34\x8b\x2b\x41\x70\x7f\x32\x18\x3e\xef\x3e\xfb\ -\xc2\x78\xb9\x08\x0a\xa0\xa5\x70\x32\x10\x38\xa4\x54\x7a\xc8\x47\ -\xfe\x7f\xe1\xeb\x2e\x00\x12\xe3\xe2\x31\x01\x5e\x48\x92\xf4\x01\ -\x5f\x35\x94\xe1\x4d\xc0\x04\x29\xee\x16\x01\xe2\x8d\x24\x49\x57\ -\xfd\xd6\x71\x1e\xcf\x02\x28\x10\x14\x25\x04\x20\xde\x57\x2a\xbb\ -\xc9\x6f\x2d\xe7\xc2\x7d\x43\x08\x60\x48\xd8\x21\xd0\x47\xfa\x69\ -\x7a\x83\xef\x72\xfc\x0b\x98\x50\x26\xe1\xd2\x40\xe3\x93\x24\x49\ -\xae\xf5\x59\x48\x55\x02\x00\x40\x40\x43\xc2\xe5\x60\xe3\x78\xbf\ -\x7f\x2a\xf2\x55\x44\x95\x02\x00\x81\xd0\x5c\x09\xad\x20\x18\xaf\ -\xad\xaf\x7f\x7f\x85\x8f\x12\xaa\x15\x00\x40\x00\x91\xe2\x46\x89\ -\xb8\x6a\xa1\x79\xf6\x58\xaf\xd7\xbb\xcc\x75\x7e\xe5\x02\x00\x80\ -\xa5\x7d\x03\xaf\x6b\x36\x17\x8f\x6e\x6c\x6c\x2c\xba\xcc\xae\x85\ -\x80\x29\xa6\x04\xe2\x46\x04\xcd\x0f\x5c\x36\x4f\x75\x12\x00\x94\ -\x34\x4f\x84\xdc\x36\x18\xa4\x6f\x15\x9e\x39\x5a\xa3\x6e\x02\x00\ -\x88\x26\xb7\xae\x04\x01\xef\x55\x2a\x7b\xd1\x45\x07\x59\x43\x01\ -\x80\x88\xd9\x3c\x81\xf2\x98\x4a\xb3\x27\x6c\x67\xd5\x52\x00\x50\ -\xde\x3c\x41\xe4\xf0\x86\x1a\x3e\x64\x33\xa7\xb6\x02\x26\x98\xcd\ -\x13\x21\xaf\x29\x35\xbc\xd3\x56\x42\xcd\x05\x50\xc4\x6c\x9e\x28\ -\x90\x57\x6c\x25\xd4\x5c\x00\xfe\xed\xe5\x9d\xb5\xdb\x62\x6d\x1e\ -\x4e\x96\x31\x9d\xbb\xf1\x21\x09\xf0\xb6\xad\x8c\x1a\x0b\x20\x34\ -\xa4\x61\x2c\x00\xca\x23\x71\x18\xbe\x6a\x2b\xa5\xa6\xa7\x00\x21\ -\x52\x32\x79\x91\xa7\x3a\x16\x27\x0f\xd4\x55\x00\x25\x60\x61\xf6\ -\x02\xbc\x1c\x45\xed\xe7\x6c\x47\xd5\x4e\x00\x81\x00\x62\x5c\xfa\ -\xde\xed\x84\x4b\x8f\x92\x2c\x7b\x01\x7b\x51\xd4\x46\xc0\xe4\x13\ -\x67\x20\xe6\x75\xff\xe3\x1f\xcf\x9c\xbe\xaf\xe4\xf5\xbb\x15\x6a\ -\x23\x60\xd2\xec\x6c\xdd\xeb\x0b\xf0\x79\x23\xc0\x5d\x2b\x2b\x2b\ -\x23\x57\xb9\xf5\x10\x20\x12\x9c\x5b\x03\x7f\x43\x7c\xad\xf3\xb3\ -\xb7\xb6\xdb\xed\x3f\x5c\x46\x57\x7f\x1b\x24\x09\x73\xd9\xaf\xeb\ -\x7c\x74\x73\xb7\xdb\xfd\xc5\x75\x7c\xc5\x2b\x80\x84\xd9\xe7\x9f\ -\x12\x9d\xef\x5f\x5e\x5e\x3e\xed\xa3\x82\x2a\x57\x00\x01\x63\xf2\ -\x3f\x13\xfa\x40\x27\x8e\x13\x5f\x45\x54\xb2\x02\xa6\x57\xfa\x62\ -\xf6\xef\xa2\x79\x4b\x14\x45\xdf\xf8\xac\xc5\xbf\x00\x01\x69\xe6\ -\x8e\x34\x65\x35\x8e\x97\xbe\xf0\x5d\x8e\xef\x97\xa3\x04\x8d\x4c\ -\x21\x78\xcf\x72\x18\xae\xf9\xad\x65\x82\xef\x97\xa3\x46\x1e\x81\ -\x87\xa3\x68\xe9\x43\xbf\x75\x9c\xc7\x9b\x00\x11\x34\x8c\x63\xe0\ -\x93\x51\xd4\x7e\xd3\x57\x0d\x65\x78\xb9\x0b\xd0\x5c\xf6\x80\xf0\ -\xa5\x4e\xd4\xaa\xfc\x6b\x32\x1e\x56\x00\x03\x29\x34\x37\x04\xdf\ -\x89\xa2\xd6\xe3\x2e\x9a\x9b\x59\x71\x2d\xc0\xd8\xdf\x13\xf8\x28\ -\x0c\x5b\x0f\xd6\x61\xf2\x80\x5b\x01\x01\x8a\x5b\x5c\xe2\x84\xd6\ -\xf9\xdd\x24\x73\x87\xb9\x33\xe1\x52\x40\xf1\x91\xc6\x57\xa3\x3f\ -\x37\x6f\x8f\xe3\x78\xd3\x61\xe6\xcc\xf8\xd9\x0a\x0b\xbe\xcb\xf3\ -\x1d\x07\xf7\xee\x0d\x7f\xf5\x92\x37\x03\x3e\x6e\x83\xc3\xf1\x38\ -\xd8\xbf\x67\xcf\x95\x3f\x78\xc8\x9a\x19\x9b\x02\xca\x9e\xe0\xff\ -\x04\x19\x1f\xe8\x76\x5b\x03\x8b\x39\x56\x71\xf5\x93\x19\x00\xf8\ -\x2d\xa0\x1c\xec\x74\x3a\xdf\xda\xca\x70\x81\xa3\x9f\xcc\x50\x08\ -\xde\x11\x86\xe1\x97\xb6\xc6\x77\x85\x35\x01\x01\x79\x18\xe0\x18\ -\xc0\x98\xe0\xb3\x51\xb4\xf4\x99\xad\xb1\xe7\xcc\x99\x33\xc7\x15\ -\x7f\x01\x49\x16\x4b\x51\x69\x18\xd5\x52\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x97\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x49\x49\x44\x41\x54\x58\x85\xed\ -\xd7\xb1\x0d\x00\x20\x0c\x03\x41\x83\x18\x8c\x26\x13\x64\x85\x8c\ -\x89\x94\xd5\x18\xc2\x74\xfc\xf7\xb1\xae\x8d\x44\x46\x91\xd5\x91\ -\xd5\xce\xc6\x32\x0d\xdb\xbc\xd7\x74\x07\x00\x00\x00\x00\x00\x00\ -\x00\x00\x00\x00\x00\x00\x00\xc0\xcd\xfa\x8c\x86\x74\x5e\x41\xfe\ -\xed\x02\xdd\xeb\x04\xae\xa2\x49\x76\xdf\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x0c\xd6\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x0c\x88\x49\x44\x41\x54\x78\x9c\xe5\ -\x9b\x5b\x6f\x5b\xc7\x11\x80\xbf\x25\x45\x8a\x94\x28\x89\x92\xad\ -\xbb\x64\xc9\x4e\x9a\xc2\x41\xe0\x26\x45\xd1\xa0\x48\x0a\xf4\xa9\ -\x7d\xe9\x7b\x81\x16\xfd\xa3\x7d\x2a\x50\xb4\x0f\x41\x90\x36\x4e\ -\x52\x20\x69\x92\xc6\x96\x6c\xc9\x37\x5d\x48\x49\xa4\x2e\xe4\xf4\ -\x61\xf6\x1c\xee\xd9\x33\x87\xa4\xe4\xf4\xc9\x03\x10\x24\x77\xf7\ -\xcc\xce\xcc\xee\xce\x6d\xe7\x00\xb2\x05\xe2\x78\xe3\x40\x9c\xf2\ -\x9e\xfe\x78\x93\x84\x90\xe3\xf9\x4d\x12\x42\x96\x57\x97\xed\xe0\ -\x0e\xf0\x18\x9c\x14\x3c\xdc\x00\x6e\x19\x1d\x25\x60\x32\x8b\x2f\ -\x6d\xaf\x0d\xa1\x66\x12\x10\xe0\x62\xc8\x98\x73\xa0\x67\xb4\x77\ -\x81\xbe\xd1\xfe\x12\xdc\xa9\x8d\x2a\xcf\xa3\x1b\x35\x00\x64\x1b\ -\xb8\xed\x09\x3d\x01\x5e\xf8\x89\xa7\x80\x39\xdf\x2e\xc0\x59\xd0\ -\x3e\xeb\xdb\xfa\xbe\x1d\x8f\xa3\x0a\x34\x81\x8a\xef\x3f\xf7\x34\ -\x54\xfd\xf7\x25\x70\x04\x97\xa7\x50\x39\xf2\x6d\x53\xa8\x20\x9d\ -\x9f\xff\xc4\xff\x9f\xf2\x6d\x0e\x68\x01\xa7\xbe\x7d\x29\xe8\x7b\ -\x01\xee\x71\x31\x6f\x85\x52\x92\x2d\x90\x09\x90\x8f\x40\x56\x8d\ -\x31\x6b\x20\x0b\x46\xfb\x06\xc8\xbc\xff\x3d\x05\x72\x0f\xe4\xae\ -\xff\xcc\x80\xdc\x01\x19\xb2\x23\xa4\xee\xc7\x2c\xa8\xe0\xe5\xae\ -\xc7\x31\xe1\xfb\xe7\x40\x36\xf3\x47\x55\x9a\x05\xed\x1b\x20\xbf\ -\x06\x29\x5f\xf3\x88\xcb\x04\xc8\x9f\xf5\xc1\x5c\xdf\x36\x48\xc5\ -\x68\x7f\xdb\x3f\xb7\xe2\x27\x5b\x8e\xf0\xdd\x1b\x73\x72\x3c\xe3\ -\x25\xff\xdb\x79\x46\xb6\xa0\x75\x4b\xdb\xe5\x2d\x83\xd9\x32\xc8\ -\x4f\x8c\xf6\x09\x90\x3f\xda\xbc\x14\x13\xf0\x91\x7f\x30\x92\x9a\ -\xac\x17\x30\x7f\xc7\x7f\xb6\xed\x15\x96\xed\x6b\x4c\x4e\x60\xa2\ -\xe2\xf6\x59\x15\x4e\x7b\x49\xe7\xcb\xf5\x97\xb3\xcf\xa5\xbb\xb9\ -\x02\xf2\xab\x71\x27\xdf\x1e\x6c\xfb\x50\x63\xca\x14\xc8\x6d\x63\ -\xfc\x2a\xc8\x07\xba\x7d\x4d\x7c\xf3\x5e\x79\x5e\x13\x64\x56\xb7\ -\xbc\xd9\x37\x07\xf2\x00\x64\xd1\xe8\x6b\xfa\x67\x23\xcb\x26\x9b\ -\xfa\xc9\x82\x71\x26\xe4\x17\xe0\x3e\x0d\xfe\x27\xca\xa3\x07\xec\ -\x01\x21\xa3\xab\x70\x79\x0b\x2a\x5f\x0e\xe1\x64\x0d\x78\x5a\xd0\ -\x97\xda\xe1\x1b\x3c\x0b\xf0\x00\xba\x4f\xa0\xf6\x2a\x68\xeb\x28\ -\x5d\x94\xc9\x29\xbc\x98\x37\x98\x30\x90\xc6\xc4\x34\x50\xe6\x1f\ -\xa0\x5a\xbd\xed\xc7\x6c\x01\x2f\x54\xa1\x0f\x05\xf1\xc4\x2c\xf9\ -\xff\x89\xe9\x4a\x34\x78\xd8\x46\xd0\xf6\xc2\xa0\x25\x86\x17\x20\ -\x82\x32\xbc\xe7\x9f\x5d\x02\x7e\x06\x7c\x0e\xcc\xa0\x16\x22\x81\ -\x9c\xd9\x8c\x04\x20\x0d\xd4\xcc\x24\xff\x37\x80\x36\xb8\x5d\x3f\ -\x51\x05\x35\x5d\x9b\xc0\xd7\xe0\xae\xf4\x7c\xb9\x13\x72\x20\xce\ -\x8f\x9b\x42\x7d\x81\x6f\x47\x98\x9f\xf8\xd9\x45\x60\x1a\x35\xa9\ -\x7b\xf6\xb3\xd2\x86\xfa\x0b\xd4\x9f\x58\x01\x7e\x00\x16\x80\xcf\ -\x80\xe7\x80\xb7\x3c\xec\xf8\xe7\x7b\xaa\xdb\xdc\x55\xd1\xc4\x5b\ -\x03\xf3\x26\x5b\x59\xcd\x29\x1b\x5e\x0f\x7c\x1c\x29\x46\xcb\x4c\ -\x2e\xa1\xa6\x72\x46\x3f\x37\x05\x59\xf5\xca\x78\x3d\x6b\x55\xd2\ -\xfe\x99\x81\x7e\x91\x09\x90\xdf\x78\x2b\x11\xb6\x07\x8a\x51\xee\ -\xaa\x8e\x18\x40\xc9\x98\xb5\xaf\x13\xb2\x0b\xae\x17\x8d\x5d\x03\ -\xfe\x0e\xdc\x09\x84\x10\xac\xcc\x61\x53\x19\xe7\x10\xdc\x53\xdf\ -\x37\xe6\xaa\x9b\xe0\x9f\x75\x4f\x80\x03\xc5\x7d\xd8\xcc\xf7\x8b\ -\x03\xd6\x81\xbf\x01\xf7\xb2\x73\xba\x9e\xf2\x22\xeb\x18\x47\xc0\ -\x12\xc0\x14\x70\x16\x31\x0f\x7a\xe6\xbf\xf3\x5b\xe9\x31\x59\x21\ -\xa0\x1a\xb9\xd9\x57\xc6\xdd\xe5\xf8\x3c\x8e\x0b\xee\x52\x71\x37\ -\xfb\xd1\x6e\x08\x3d\xbc\x1e\xf0\x04\x3d\x7a\xe1\x90\x1e\xea\x29\ -\x4e\xc7\x58\x2d\x25\x38\xe7\x57\x2f\x00\xd9\x46\x95\x4c\x29\x30\ -\x77\x07\xc0\x7d\xe0\xd2\x9b\xab\x57\xe8\xee\x09\x4d\x9e\x9f\xd0\ -\xdc\x04\x25\xe8\xfa\xe3\x56\x3b\xc4\xf6\xf7\xa7\x81\x2e\x48\x78\ -\x66\xfb\x3a\x56\xee\x03\x47\xe8\xca\x7f\xad\x63\x05\xa0\x03\x9d\ -\x13\xa8\x2f\x92\xd1\x67\xee\x08\xe4\xa7\xf1\x04\x63\x58\x01\x79\ -\x0b\x2e\x2a\x50\x9d\x46\x15\xd3\x29\x83\xad\xbd\x0b\xfc\x0e\xf8\ -\x4b\x01\x03\x01\x74\xe6\xa1\x9e\x04\x3f\x3e\x4e\xa8\x1d\xf9\xce\ -\x79\xd4\x52\xf8\x1d\xd5\x39\x87\xfa\xe1\x10\x64\x5d\xd4\x3c\xfe\ -\x06\xf8\x24\xa0\xd9\x2b\xcf\x7a\x0d\xb8\x0d\x72\x1e\x2d\x66\x6e\ -\x25\x62\x01\xc4\xd1\xe1\x5d\x60\x1a\x26\x1f\xaa\x12\x74\xfb\xd9\ -\xe1\xb2\x0e\xfc\x03\x0d\x70\x8c\x20\x43\x80\xee\x6d\xa8\x4d\x40\ -\xfd\x25\xb8\x4e\x01\x43\x47\xd9\xbf\x52\x07\x16\xe0\xa2\x06\xd5\ -\x93\xbc\xd6\x4e\x7d\x93\xbf\x02\x6b\xe0\xf6\x82\xce\x36\xc8\x09\ -\xba\x63\xdf\xf6\x9e\x6b\x42\x5b\x9f\xe8\xd8\xc7\x3a\xa0\x0a\x9c\ -\xfb\x09\xee\xa1\xab\xf2\x85\x4d\xb3\x2c\xa1\xdb\xbe\x87\xad\x13\ -\xa6\x81\x55\xa8\xb5\x55\x89\x15\x32\x6f\x80\xeb\xe8\x33\xd5\xb6\ -\x32\x18\x1e\xab\x30\xaa\xa3\x87\xfa\x02\x2b\x05\x88\xbe\xf1\x63\ -\xee\xf9\xe7\x3a\x64\x1d\xb9\x22\x2b\xc0\x06\xf0\x0c\xf5\x01\x8c\ -\x03\x7c\xd8\x04\xba\xe0\xba\x9e\xe0\x48\x31\x1e\xcd\x43\xbb\x86\ -\xae\xc2\xf9\x58\x3c\xdb\x70\x01\x3c\x85\xf6\x24\x1c\x2f\x60\x87\ -\xb4\x5d\xe0\x4c\xe7\x8c\xc1\x9d\xa1\x8b\xfa\x83\xe7\x29\xc7\x8b\ -\x25\x80\x06\xea\x3d\x2d\xe6\xb7\x7c\x02\xcd\x29\x70\xad\x6c\x5b\ -\x22\x84\xcb\xf7\x61\xae\x07\xb3\xaf\xcc\x47\x6f\x04\xb3\xaf\x60\ -\xf6\x52\x71\x5b\x47\xcd\xb5\x60\xae\x20\x16\x61\x07\x35\xdf\x2d\ -\xd4\xc2\x65\xc0\x12\xc0\x34\xaa\x3d\x0b\x94\x9a\x2c\xa3\x6e\xaa\ -\x01\xc7\x4d\xa8\x7c\x0f\xcc\x33\x7e\xec\x3d\x06\x88\x03\x16\xa0\ -\xf2\x9d\xce\x61\xc2\x73\xdb\x59\x72\x97\x40\x19\xdc\x31\xba\xb8\ -\x19\xb0\x04\x20\xa8\x69\xd9\x29\x20\x64\xc2\xb6\xf3\x32\x05\xa5\ -\x64\x22\x7f\x1c\xac\x60\xeb\xda\x10\x6e\xfb\x16\x94\x4a\x5e\xbf\ -\xc4\xc3\xae\x94\x36\xb1\x78\x3a\xd4\x23\x34\xda\x0a\x94\x07\x83\ -\x4c\xbf\x7d\x13\xd5\xb2\xe1\x2a\xcc\x82\x74\x81\x15\x98\xd9\x0f\ -\xfa\x5a\xc0\xbb\xc0\x13\xd2\x8c\x4e\x06\x92\xd4\x19\xa8\x4f\x61\ -\xe5\x05\xe7\xd0\x40\xe7\x07\xfd\x2d\xa0\x3b\x73\x03\xe4\x19\x03\ -\x3f\x23\xc1\x7f\xa6\x7d\x1c\x64\xd1\xb8\x63\xef\x0e\x27\x81\x59\ -\x0a\x31\x61\x35\x72\x49\x48\x99\x47\x83\x8d\x65\x4f\x64\x84\x9c\ -\x1e\x74\x66\xa1\x7e\x00\xc4\x41\xc6\x23\x4f\xd0\xd7\xc1\xe4\x2b\ -\x40\x1f\x3a\x67\x50\xdf\x05\x1c\x74\x6f\x41\x2d\xc9\x2f\x3e\xf3\ -\xdf\xce\xcf\xf9\x05\x9a\x2b\x0c\xe1\x15\x74\x66\xa0\x9e\x08\x2d\ -\x9c\xb7\x89\x2a\xbe\xbe\xee\x86\x54\x57\x25\x79\xcb\x4c\xc2\xc6\ -\x5a\x99\x45\xe0\x4b\x90\xaa\x27\xe0\x25\xb8\x43\x34\xd3\x73\x96\ -\x8f\xfc\xa4\x01\xf5\x32\xb8\xe7\x79\x54\x82\x67\x7e\x01\x38\x46\ -\x57\xec\x1b\x63\x77\xb5\xfd\xf8\x32\xba\xe2\x07\x9e\x8e\xff\x68\ -\x5f\x2e\x7a\x3b\xf1\xa6\xcf\x67\x7f\x43\x9a\x64\x1f\x15\x98\x17\ -\x9a\x6c\x02\x4f\xe0\xa4\x03\x8d\x29\xb2\xe1\xb1\xa9\x03\x4a\xa8\ -\x04\x6f\x83\xdb\x09\xec\xf7\x2d\x6c\xe5\x37\x0d\x47\x05\x69\x68\ -\xa5\x00\xcd\xf4\x6e\x01\x4f\x87\x87\xc4\xa9\x2f\x7f\x1f\x0d\x67\ -\x87\x05\x52\x27\x18\xbe\xbd\x5f\x08\x9f\xb9\x72\x27\xa8\xb7\xba\ -\x01\x8d\x03\xf4\x48\x65\xa0\x48\x09\x2e\xe5\xe3\x01\x28\x20\xbe\ -\x01\xf3\x47\x46\x7b\x02\x65\x25\xb4\xf2\x90\x9c\xb3\x94\x9b\x3a\ -\x51\x78\x9f\x61\xdf\x3f\x84\xb4\x14\x08\x20\x37\x4e\x7c\x6a\x7c\ -\xcd\xea\xb5\x04\xb0\x00\x58\xf6\xdf\xba\x84\x18\x07\x56\x18\x24\ -\x34\x0c\x8f\x31\x81\x9c\x93\xf3\x12\x2e\x8c\xd4\x7b\x06\x8a\x84\ -\x69\xd1\xfa\x0a\x43\x60\x05\x47\xe0\x5a\xe1\xec\x28\xc1\xf4\x07\ -\x3b\xa7\x30\x94\x36\x3c\x3c\xd7\x85\xea\xa8\x7c\xdb\x35\x72\x0d\ -\xee\x0c\x55\xe6\x19\x88\x05\x30\x41\x71\x54\x77\x13\x9b\x5e\x83\ -\x6e\x64\xde\x62\x21\x0c\xbd\xb1\xb9\xa9\x1f\x51\xf4\x5c\xae\x3d\ -\xb6\x02\xcb\x70\x65\x69\xf3\xc0\x3f\xc8\xb4\x97\xec\xf6\x14\x9a\ -\x50\x7b\x66\xd0\x21\x20\x8f\xd1\x24\x0b\xc0\xa3\x02\xfd\x32\x62\ -\x85\xbb\x7d\x8d\x34\x73\xd0\xc3\xce\xd6\x8e\x8a\x05\x7a\x15\x98\ -\xb8\xce\xf6\x4f\xec\x75\x11\xf4\x47\xf4\xbf\x26\xd4\x1c\xc5\x47\ -\x70\xac\x79\x23\x01\x94\x9f\xa1\xf6\x37\xc6\xd5\xb3\x11\x8e\xcc\ -\xf2\x1e\x90\x9a\xa4\x10\xd2\x6d\xff\xc8\x7f\x46\x58\x87\x42\x28\ -\x12\x40\x19\xdb\xb3\xcc\xcd\x11\xeb\x80\x2e\x51\xbc\x1c\x40\x11\ -\xb3\xc3\x08\xbf\xca\xcf\x11\x9f\xf9\x51\xd6\x61\x28\x14\x8d\x1f\ -\x5b\x39\xc6\x02\x48\x72\xe7\x39\x6d\x79\x03\x22\x12\xe8\x93\xde\ -\x27\x16\x29\x3c\x4b\x08\x32\x43\xea\xe9\xdd\x78\xee\x00\xc4\xe7\ -\x17\xb3\x60\x99\xc1\x23\x06\xb7\x38\x3f\x06\x3c\x07\x56\x46\x68\ -\x7b\x22\x21\x94\x50\xaf\xcd\xb8\x70\xc9\xc0\x98\xbe\x49\x12\x4e\ -\xe7\x05\x6a\x09\xc0\x01\xfb\xe4\x2f\x12\x8b\xa4\x7d\x00\x6d\x43\ -\x6f\x64\xe0\x25\xf0\x21\x23\x8b\x13\x9c\xa0\x61\xf8\x47\x0c\xbf\ -\x13\xc4\x67\x80\x8e\x8b\x10\x0d\x7e\x8a\x43\xad\xcd\x2e\x63\xe8\ -\x00\x00\xf1\x8e\xd0\x53\x15\x42\x7a\xb3\x73\x80\x79\x1b\xcb\x25\ -\x34\xaa\x43\x28\x4d\xee\xeb\xfe\x05\x6c\x6a\xde\xa0\x08\x64\x8e\ -\xc1\xe5\xcb\xa6\x45\xf0\x00\xe6\x26\x31\xd3\x6d\xed\x45\xd2\x88\ -\x55\x9a\x68\x6e\xe3\x91\xc7\x35\x32\x1f\x00\x9a\xe7\x9f\x04\x77\ -\x0e\xec\x28\x12\xd9\x40\xad\xc3\xbc\x8f\xbd\x43\x44\x4b\xc0\x19\ -\xc8\x3b\x44\x91\x16\x9a\x81\x59\x43\xa3\xba\x26\x70\x01\x17\x5b\ -\x5e\xc7\x58\x4e\xcf\x29\x1a\x19\x2e\xe9\x58\x1e\x00\xff\x06\x89\ -\x4d\x73\x92\xd9\x49\xf2\x01\xc9\xff\x24\x84\xee\x78\xfc\x7b\x7a\ -\xaf\x09\x3e\x83\x9d\xf3\x49\x62\x01\x74\x7c\xdb\x32\x7a\x1e\xd1\ -\x0b\x05\x8e\x3c\xbd\x02\xec\x67\xb7\xb1\xa0\xb9\x43\x59\xcf\xe6\ -\x10\xd3\x73\xf7\x4f\x70\xed\x60\x8e\x82\x3c\xa3\x05\x02\x9a\x38\ -\xd9\x8d\xe6\x5c\xd3\x60\x2d\x61\x3c\x09\x87\xc5\xa1\xbb\xfa\x38\ -\xdb\x0e\x0c\x0a\xb6\x32\xd9\xe9\xf8\x08\x84\x57\xd7\x16\xec\xa1\ -\xc1\x8d\x05\xcf\xc8\x14\x56\xe0\x6f\x65\x5f\xfb\x6e\x30\xb6\x0e\ -\x2b\x14\xe6\x24\x93\xc0\xcb\x84\xe4\x3a\x3e\xa3\x38\x8b\x94\xe0\ -\x85\x6d\x0a\x5d\x5f\x89\xb2\xea\x6d\xdc\x15\xd0\xf2\x67\x30\xc9\ -\xdb\xbf\x0e\xf3\x09\x04\x42\x68\xdd\x46\x13\x24\x56\x4e\xb2\x1c\ -\xd0\x18\xf7\x2d\xa3\xd6\x68\x2c\x25\xd8\x46\xed\xa5\x19\x3f\xfb\ -\x6d\x6e\x64\x5f\x01\x38\x83\xc6\x32\x9c\x9c\x8d\xe1\x25\x5e\x03\ -\x9c\x28\xce\x99\x15\x06\x65\x77\x31\x2c\x53\x7c\xbc\x92\x1a\x85\ -\x9c\x59\xb5\x04\x70\x86\x2a\x97\x72\x41\x86\x15\x38\xee\x90\xbb\ -\xf7\x4f\xb7\xfd\x57\xd0\x38\xd3\x73\xfa\x63\x81\xac\x2a\x4e\xbe\ -\xc2\xf4\x18\xa5\x01\xad\xae\x2d\x74\x99\x83\xb3\x2e\xca\x53\x4e\ -\x78\x45\xf9\x80\xc4\x66\xbe\x6d\x13\xd4\x3c\x54\x84\xc9\x31\xc9\ -\xb9\xb7\xa7\xe8\x96\x5b\x85\x4e\x41\xa1\xd3\x38\x70\x3e\xab\x38\ -\x92\xea\x4f\xd3\x6d\x9e\x04\x66\x61\x2e\x4e\xd6\x26\xb0\x02\x53\ -\xd3\x01\x4f\x19\x88\x05\x70\x41\x9a\x34\x70\xde\x74\xc9\xba\x8d\ -\xd7\xed\x2b\x72\x4a\xd8\xee\xed\x15\xb0\x07\xf5\x4b\x55\x5c\xb2\ -\x38\x9e\xaf\x2f\xce\x8f\x5d\x81\x49\x8f\x23\x3c\xf3\xa1\x10\x28\ -\x01\xab\x76\xfa\x0e\xd4\x34\x5f\x54\xc0\x7d\xeb\x1b\xea\x44\x56\ -\x20\x36\x83\xf1\x95\xd3\x27\x68\x39\x1a\xc0\x32\x5a\x27\xd4\x0f\ -\xc6\x5d\x02\xbf\x45\xaf\xc7\x97\x0d\x9d\x97\xa4\xa0\x4e\xd1\xf8\ -\xfc\x3d\x2f\x84\x61\x89\x0f\x21\xad\x35\xa0\x81\xba\xd1\x56\x4d\ -\xcf\x25\xf0\x7b\xe0\x53\x06\x97\xa3\x89\x19\x4c\xca\x6b\x27\xf5\ -\x66\x3b\x85\x12\xc3\xdd\x67\xd9\x42\x0b\x0f\xc2\xb6\x86\xf7\x08\ -\x37\xa2\xf6\xa4\x0e\x6f\xcd\x7f\x1b\x56\x43\x1a\xdc\xa8\x46\x30\ -\x7d\x7e\x05\xf3\x52\x45\xaa\x68\x09\xed\x1c\xc8\xbb\xb6\x4e\x90\ -\xf7\xf3\xd6\x4a\x3e\x64\x8c\x1a\xa1\x43\x90\x20\x23\xeb\x4e\xe0\ -\xa4\xab\xf5\x80\x29\xa2\xf0\x8a\xba\x0f\xee\x11\xea\x25\xbe\x06\ -\xb3\xe3\x82\xcc\xa0\x29\xfb\xef\xd1\xcc\xcf\x0e\x79\xc5\xb8\x81\ -\xa6\xe0\xc3\x0b\x9e\xe4\x6e\x22\x03\x96\x00\xba\x40\x95\x4c\x49\ -\xec\xcc\x0b\xa8\x4c\x7a\xc9\x16\x85\xb4\xfb\xd0\xaa\xaa\xce\xb8\ -\x56\x5d\xee\x98\x20\x65\xc5\xdd\xaa\x90\xaf\xfa\x08\x14\x63\x7b\ -\x11\xba\x1d\x32\x1a\x5f\x2a\xa8\x6e\xcb\xd5\x28\x58\xb1\x40\x09\ -\xdc\x9e\x6e\x79\x79\x16\x28\xa0\xa7\xa8\x46\xee\x01\xff\x0d\x98\ -\x0f\x24\x3f\x77\xe0\x05\x94\x84\xbf\xa1\x0b\x7c\x13\x48\xbc\xbf\ -\x55\x94\xd1\xa7\x30\x27\x51\xbf\x04\x39\xc6\xfb\xd0\x68\x91\xb9\ -\xbe\x93\x8a\xd2\xe3\x76\x40\xee\x1a\xcc\x66\xe0\x25\x69\x2e\xc0\ -\xed\xa2\x75\x36\xc9\xd6\x17\x54\xf1\x54\xc8\x66\x8d\x22\x1c\x4e\ -\x54\x80\xec\xa3\xb5\x3f\xf7\xc6\x08\x97\x0d\x68\xdd\x46\x9d\x9b\ -\x25\xe0\xb9\xee\xb0\x9c\x9d\x9f\x26\x5d\xd5\xe3\x26\xba\xea\x65\ -\x54\x79\x76\xd0\xda\xe6\x25\x65\x1e\xd0\xcb\xd8\x8c\x33\x14\xed\ -\x00\x77\x9a\x0d\x57\xdd\x1e\x5a\xc3\xbf\x81\x46\x66\x9f\xa3\x42\ -\x78\x00\xe7\x27\x50\x3d\x52\x22\x0b\xcd\x5b\x5f\xe7\x68\x24\x15\ -\x9b\x49\x1b\x80\x83\x0b\xbf\xbb\xaa\xc9\x0b\x14\x21\x1c\x7b\x66\ -\xbc\xa9\x33\x1d\xcb\x65\xc5\x2f\x4b\x1e\x6f\x12\x23\x7c\x00\x3c\ -\x04\x0e\xc0\xbd\x0c\xc6\x97\xe3\x7b\x46\xeb\x08\xc4\xcc\x74\x3d\ -\x21\x0f\xd1\x82\x45\xd0\x2b\xef\x65\xdf\xbe\x1f\xb4\x1b\x20\x62\ -\xf7\x8b\x83\xea\xa4\x67\xb0\x53\xe0\xc5\xad\x8f\xc0\x7d\x05\x4c\ -\xc1\xd1\xf7\xd9\xeb\x39\x71\x9e\xb6\xf8\xcc\x8f\x93\x42\x93\x3b\ -\x03\xe7\x27\x53\x2e\x5f\xcf\x5a\x07\xf0\x66\xe8\x7d\xec\x44\x49\ -\x32\xe6\xff\x50\x2e\x0f\xba\x00\xf2\xf3\xbc\xf9\x95\xa6\x5a\x8a\ -\x5c\xb9\xfc\x1d\xcc\xb2\x5e\x1b\xf9\xc7\xd8\x2f\x4c\xac\x92\x7b\ -\x61\x42\x1c\xfa\x82\x85\xf1\x02\x43\x3a\x66\x7b\xcc\x89\x43\x9c\ -\x05\xcf\x88\x43\xdf\x18\xf9\xa5\xd1\x57\xce\xfa\x2b\xa9\x10\xaa\ -\x8c\xff\xc2\x44\x8a\xe8\x4f\x05\x4e\xc8\x46\x5e\x08\x00\xf2\x1e\ -\xfa\xca\x4a\xee\xa5\x04\x5e\xeb\x95\x99\xb4\xad\xe4\x9d\x9f\xb7\ -\x40\xde\x31\x9c\x9f\xb2\xa5\xe5\x3d\xf3\x7f\xc8\xe3\x2b\x9e\x3c\ -\x91\x5a\x59\xa5\x16\x7b\x80\xe0\x77\x82\x71\x7d\x2d\x1b\x7e\x6b\ -\xde\xd3\x4f\x2b\x74\x9e\x2a\x8c\x7e\x69\x6a\xca\x8f\x09\x04\x2f\ -\x2b\x0c\x5e\xbe\x2a\x7a\x39\x6a\x1e\x33\x66\x91\x2d\xcf\x43\x29\ -\xbf\x9b\x15\x62\x44\x86\x93\x23\x9b\xa8\xb6\xf5\x35\xba\xb4\xfc\ -\xef\x1a\x6a\xe6\x1c\x7a\x01\x72\xc1\xe0\xb5\xb9\x19\x40\xa0\x37\ -\x0d\xe5\xc4\x29\x4a\x4a\x64\x7b\xc1\xff\xe4\xf6\x26\x79\x6d\x2e\ -\x28\x97\x4d\xe9\xeb\xfa\x71\x0e\x35\x61\xa7\xfe\xf7\x24\xaa\xc4\ -\x7d\x01\x06\x1d\x54\xa1\xce\x06\x78\xf6\x06\x4e\x93\xed\xc0\x8d\ -\xb8\xa2\x8e\x41\x26\x30\x4a\xcd\x3c\x9e\x3a\x79\x2d\x1b\xbf\x38\ -\x59\x42\xaf\xca\x92\x23\x54\x65\xe0\x5f\xe0\x99\x38\x24\x6b\xf3\ -\xac\x17\x27\x85\x41\xe2\x33\x06\xa3\xb4\x36\x7d\xac\x88\xc7\x37\ -\xf7\xd5\x59\xab\xe1\x0d\x80\x0c\xcf\x6f\x1a\xf3\x09\xa8\x10\xfe\ -\x07\xb4\x0a\xfd\x7e\xcf\x22\x5b\xc2\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x02\x0b\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xbd\x49\x44\x41\x54\x58\x85\xed\ -\x94\x3d\x6b\x14\x51\x18\x85\x9f\x73\xd7\x42\x09\x88\x36\x16\x16\ -\x41\xc1\x5a\x6c\x92\x45\x04\x3b\x59\x91\xe0\xba\x8b\xa6\x51\xc1\ -\x7f\x90\x5f\x20\xa8\xbf\x40\x6c\x52\xda\x58\x28\xb2\x89\x41\x0b\ -\x43\x4a\x91\x24\x6b\xa3\x29\x52\x59\xd8\x28\x58\x25\xa8\x91\x90\ -\xdd\xbd\xc7\x62\x66\xdd\x65\xa3\x9b\x99\xf5\x23\xcd\x3c\x30\xf0\ -\x32\xdc\x39\xe7\xdc\xfb\xbe\x77\xa0\xa0\xa0\xa0\x60\x9f\x51\xb7\ -\x98\x9c\x8b\x1b\x82\x23\xff\xc3\xd4\xb0\xd9\xac\x87\xa3\x00\xe1\ -\x67\x12\xf5\xea\x7f\x4d\xbf\x57\xaf\x68\xe9\x24\xb0\x92\x26\x04\ -\x13\x81\xce\xdf\x78\x6c\xa2\x7b\xfe\xcb\xa9\x57\x12\xa6\x3f\xd9\ -\xe9\x45\x8f\x1d\xfa\xee\x06\xa6\x82\x8d\x51\x94\x30\x7f\x86\xc0\ -\x01\x84\xe1\xe5\xf6\x98\xae\xae\x55\xb4\xb5\xeb\x04\x00\xd6\x2a\ -\xda\xfa\xda\xd2\x65\xe4\x27\x48\x48\x0e\x83\x21\xf3\x60\x23\x43\ -\x48\x24\xfc\xf8\x5b\x5b\xd5\x7e\xf3\x5d\x01\x00\xd6\xa7\xb5\x33\ -\xde\x0a\xd7\x6d\xcf\xa6\xde\xc1\xce\x1f\xc2\x20\x89\x20\xc0\xf6\ -\xec\x78\x3b\xdc\x58\x9f\xd6\xce\xe0\xba\xdf\x0b\xdb\x2a\x3f\x8b\ -\x77\xb1\x6e\x27\x82\x8a\xc2\x99\xda\x61\x24\xe1\x74\x73\xbe\xb7\ -\x5a\x0b\x77\x90\x7e\xf9\xed\x9e\x3b\x2b\xcf\x7b\x06\xfb\x7e\x37\ -\x15\x28\x0e\x37\x77\x10\x52\x22\xae\x99\x95\xba\x1e\x0c\x5b\x9f\ -\xe9\x68\xcb\x0d\xdf\x44\x7e\x08\x94\x86\x85\xe8\x33\xef\x20\xdd\ -\x5a\xad\xe9\xd1\x5e\xda\x99\x7b\x3b\x39\xe7\x29\xe1\xa7\xc0\x41\ -\x92\x9b\x3a\x18\xa2\x3b\xb0\xdb\x46\xd7\x9a\x75\xbd\xc8\xa2\x9b\ -\x6b\xb8\x26\x1a\x3e\x1f\xe4\xe7\xc0\x61\x83\x95\x86\x30\x04\x25\ -\x5a\x5f\x1c\x34\xd5\xbc\xa2\x57\x59\x35\x73\x4f\xf7\xc4\xbc\xcf\ -\x04\x7b\x11\x38\x86\x30\xd1\xdd\x96\x7f\x8e\xd2\xc5\x37\x35\xbd\ -\xcd\xa3\x37\xd2\x1d\x3f\xbb\xe0\x53\xb1\xe3\x25\xe0\x44\xfa\xea\ -\x43\x28\xe9\xc2\x72\x55\xef\xf3\x6a\x8d\xfc\x93\x39\xb7\xe0\xe3\ -\xed\x8e\x3f\x02\xef\x0e\x94\x74\xe9\x75\x55\x9f\x46\xd5\x2a\x28\ -\x28\x28\xd8\x57\x7e\x00\xa4\xf8\xb1\x06\x78\x8b\xc7\xb8\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xcf\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x81\x49\x44\x41\x54\x58\x85\xed\ -\xd2\x31\x0e\x82\x50\x10\x84\xe1\x7f\x9f\x77\x20\xe1\x36\xaf\xe0\ -\x08\xf6\x16\x5a\x70\x0b\xc2\x2d\x28\xb0\xb5\xb5\xb5\x31\xe1\x36\ -\x26\xdc\x01\x96\x0a\x88\x98\xd8\xf1\x68\xe6\xeb\x76\xb3\xc9\x4c\ -\xb1\x20\x22\x22\x72\x30\xdb\xce\x31\x56\xa7\x3d\x03\xbb\xae\x1e\ -\x00\xff\x29\x50\x9c\x6f\xd1\x9c\x07\x90\xef\x59\x00\xe8\xc7\xd1\ -\x2f\xef\xe7\xfd\x05\x10\x96\xb5\xd3\x24\x08\x07\xc8\x42\xb0\x76\ -\x1e\xc2\xbf\xcb\x14\xd6\x02\x46\x09\x7c\x12\x64\xf6\x8e\x5d\xd7\ -\xd8\x6f\xc9\x9f\x50\x44\x44\xe4\x70\x13\x6a\x59\x1a\x0e\xce\xfb\ -\x3e\xfc\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -" - -qt_resource_name = b"\ -\x00\x09\ -\x09\x5f\x97\x13\ -\x00\x71\ -\x00\x73\x00\x73\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x73\ -\x00\x0a\ -\x09\x24\x4d\x25\ -\x00\x71\ -\x00\x64\x00\x61\x00\x72\x00\x6b\x00\x73\x00\x74\x00\x79\x00\x6c\x00\x65\ -\x00\x04\ -\x00\x06\xa8\x8b\ -\x00\x64\ -\x00\x61\x00\x72\x00\x6b\ -\x00\x0d\ -\x0d\x36\x0c\x63\ -\x00\x64\ -\x00\x61\x00\x72\x00\x6b\x00\x73\x00\x74\x00\x79\x00\x6c\x00\x65\x00\x2e\x00\x71\x00\x73\x00\x73\ -\x00\x02\ -\x00\x00\x07\x83\ -\x00\x72\ -\x00\x63\ -\x00\x17\ -\x0e\xfe\x32\x47\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\ -\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x27\ -\x0d\x0d\x92\xa7\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ -\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1d\ -\x0c\x09\x66\x07\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ -\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x01\x87\xae\x67\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ -\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x20\ -\x0e\xfe\x76\x47\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\ -\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x11\ -\x09\xcb\xcc\xe7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\ -\x00\x18\ -\x07\x8b\xec\xe7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ -\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x0d\x9d\x97\x47\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ -\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1d\ -\x09\x07\x81\x07\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\ -\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1b\ -\x09\x0d\xa6\xc7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ -\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x07\x36\x1b\x47\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\ -\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x0c\xeb\x5f\x67\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\ -\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x10\ -\x05\x3e\x39\x67\ -\x00\x62\ -\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x00\x4f\x29\xc7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x5f\x00\x70\x00\x72\x00\x65\ -\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x26\ -\x04\x24\xf6\xe7\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\ -\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x27\ -\x0e\x3d\xd7\xc7\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ -\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\ -\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1e\ -\x07\x50\x2b\xe7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x5f\x00\x70\ -\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x0d\x6c\x22\x07\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\ -\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x18\ -\x03\xae\x62\xe7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ -\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x0e\x19\x8b\xc7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\ -\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x04\xf8\x32\xc7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\ -\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1c\ -\x02\x75\x51\x87\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\ -\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x21\ -\x01\xf6\xa2\x67\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\ -\x00\x18\ -\x07\x83\xfe\x27\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ -\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x14\ -\x01\xe9\xfd\xe7\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x40\x00\x32\x00\x78\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x13\ -\x08\xc8\x96\xe7\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x2e\x00\x70\ -\x00\x6e\x00\x67\ -\x00\x14\ -\x07\xec\xd1\xc7\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x16\ -\x03\x94\x39\x67\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x40\x00\x32\ -\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x29\ -\x09\x81\xd3\x67\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\ -\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x11\ -\x08\x8f\x96\xa7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\ -\x00\x17\ -\x07\x06\x3d\xa7\ -\x00\x74\ -\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ -\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1d\ -\x0e\x35\xf3\xa7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\ -\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x05\x35\xb6\x67\ -\x00\x74\ -\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ -\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1c\ -\x00\x10\xb9\x67\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\ -\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x0b\x46\x72\x87\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x5f\x00\x66\x00\x6f\x00\x63\ -\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1c\ -\x09\xc8\xa4\xa7\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x64\ -\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x0c\xa5\xc5\x27\ -\x00\x62\ -\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\ -\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x15\ -\x0a\x12\x4a\x67\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ -\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0f\ -\x06\x16\x25\xe7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1f\ -\x04\x8d\x48\xc7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x5f\x00\x64\ -\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x02\xb6\xb5\xa7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ -\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1f\ -\x0c\xa4\x6f\xa7\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x64\ -\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x00\x6c\xa3\xa7\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\ -\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x18\ -\x0e\x0c\xda\xa7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\ -\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x25\ -\x06\x6c\x47\xe7\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ -\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\ -\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x01\x0e\xe5\xa7\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\ -\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x0c\xd5\x5a\x67\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\ -\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x18\ -\x07\x86\x4e\x27\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ -\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x12\ -\x00\x68\xca\xe7\ -\x00\x74\ -\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ -\x00\x67\ -\x00\x1a\ -\x0f\x5a\xb4\xa7\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\ -\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x16\ -\x05\x7a\xd3\x67\ -\x00\x62\ -\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\ -\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x2c\ -\x0c\xa4\x5a\x47\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\ -\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x24\ -\x05\x94\xa0\x47\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x0f\x1e\x9b\x47\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\ -\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x22\ -\x01\x41\xee\x87\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ -\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\ -\x00\x67\ -\x00\x14\ -\x00\x2e\x0a\x07\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x03\x9f\x72\x87\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ -\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x16\ -\x0f\x35\xfb\x07\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ -\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1c\ -\x0f\xd0\x9c\x67\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ -\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0e\ -\x08\xfa\xe1\x27\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x0d\x0d\x28\xa7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ -\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x18\ -\x0f\xd7\x34\x67\ -\x00\x74\ -\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ -\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x0c\x24\xec\x07\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x66\ -\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x21\ -\x05\x70\x30\x27\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ -\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\ -\x00\x18\ -\x06\x60\x39\xe7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ -\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x11\ -\x0a\xe5\x6c\x07\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\ -\x00\x1a\ -\x0a\xa0\x05\x47\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x5f\x00\x64\x00\x69\x00\x73\ -\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x0f\x7e\x6f\xe7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\ -\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x15\ -\x0c\x60\x8e\x27\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\ -\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x0b\x59\x6e\x87\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x66\ -\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1b\ -\x02\x0d\xa6\x67\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ -\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x18\ -\x0e\x31\x43\xa7\ -\x00\x74\ -\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ -\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x13\ -\x0c\x24\x39\x47\ -\x00\x62\ -\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\ -\x00\x6e\x00\x67\ -\x00\x21\ -\x0e\xf1\x37\x67\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ -\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\ -\x00\x1b\ -\x0b\xea\x1b\xe7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x5f\x00\x70\ -\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x11\ -\x05\x2a\x70\x67\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\ -\x00\x20\ -\x09\xd7\x1f\xa7\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ -\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x01\xc7\x25\x47\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ -\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1e\ -\x04\x3c\x09\xc7\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x70\ -\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1b\ -\x0d\xfd\xa2\x07\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ -\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0f\ -\x0c\xe2\x68\x67\ -\x00\x74\ -\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x18\ -\x06\x6d\x9b\x27\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ -\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x16\ -\x0f\x80\x4f\xa7\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x40\x00\x32\ -\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x0e\x26\x93\xe7\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ -\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x16\ -\x06\x14\xad\xc7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ -\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x14\ -\x00\x44\xa0\x47\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x18\ -\x07\xa5\xb1\x27\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ -\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x04\xce\xfa\x67\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\ -\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x24\ -\x04\x0b\x8d\x27\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ -\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x1d\ -\x04\x34\xf0\xc7\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\ -\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x15\ -\x0f\xac\xe3\xc7\ -\x00\x62\ -\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\ -\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x14\ -\x0b\x2d\x81\x07\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x16\ -\x0a\x7a\x87\x67\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\ -\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x15\ -\x06\xf8\x08\xa7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ -\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0f\ -\x01\x40\x2d\xa7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x12\ -\x04\xb5\x9d\x47\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ -\x00\x67\ -\x00\x17\ -\x0f\x18\x45\x87\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ -\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x14\ -\x05\xe4\x2d\xe7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x1b\ -\x07\xac\x39\xa7\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ -\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1b\ -\x0a\x19\xf4\xe7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\ -\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x22\ -\x08\x8a\x08\x27\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ -\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\ -\x00\x67\ -\x00\x16\ -\x0a\x1a\xd6\x47\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ -\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x12\ -\x04\xb1\x94\x27\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ -\x00\x67\ -\x00\x1e\ -\x0c\xd2\xb9\x87\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x70\ -\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1b\ -\x08\x21\xa7\xc7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ -\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x18\ -\x05\x12\xcf\x67\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\ -\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1c\ -\x04\x73\x5f\x47\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x5f\x00\x70\x00\x72\x00\x65\ -\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1c\ -\x08\x2e\xd3\x67\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x66\ -\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1c\ -\x00\x06\x3d\xc7\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x66\ -\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x0a\x14\xed\x47\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ -\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x0d\x33\x2d\xa7\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\ -\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x15\ -\x0b\x78\x08\xe7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ -\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x23\ -\x07\x14\x6d\x87\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ -\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\ -\x00\x6e\x00\x67\ -\x00\x1f\ -\x02\x4f\x6a\xa7\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x64\ -\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x11\ -\x01\xf6\xff\x67\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\ -\x00\x1e\ -\x05\x75\xad\x27\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ -\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x09\x2e\xa9\x47\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ -\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x13\ -\x05\x76\x1e\x67\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x2e\x00\x70\ -\x00\x6e\x00\x67\ -\x00\x1c\ -\x0c\xfb\xa0\x47\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\ -\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x16\ -\x01\x75\xcc\x87\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ -\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x22\ -\x00\xa7\x99\x47\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ -\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ -\x00\x67\ -\x00\x15\ -\x06\x62\x08\x27\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ -\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x23\ -\x06\xf2\x1a\x47\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ -\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\ -\x00\x6e\x00\x67\ -\x00\x1a\ -\x05\x28\x8d\xa7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\ -\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x24\ -\x05\xed\xfa\xe7\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ -\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x18\ -\x02\x48\x15\x27\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ -\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0d\ -\x0b\x72\x3d\x07\ -\x00\x62\ -\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x12\ -\x04\xb3\x4c\x27\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ -\x00\x67\ -\x00\x0e\ -\x06\x0c\xe6\x07\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1b\ -\x0f\x79\xa3\xc7\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x70\ -\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x23\ -\x03\x43\xb9\x67\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\ -\x00\x6e\x00\x67\ -\x00\x1b\ -\x0a\xfb\x2d\x27\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x70\ -\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x16\ -\x04\x9c\xa4\xa7\ -\x00\x62\ -\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\ -\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x0e\x98\x18\x27\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\ -\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x18\ -\x06\x43\xc6\xe7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ -\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x04\x64\xf7\x07\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ -\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x05\x11\xe0\xe7\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\ -\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1f\ -\x06\x75\x64\x87\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ -\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x2b\ -\x03\xd2\xba\xc7\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\ -\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x0f\x9a\xe5\x07\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ -\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x29\ -\x09\xe4\xb0\x07\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ -\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x25\ -\x08\x07\x7e\x87\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ -\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\ -\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x12\ -\x06\xa7\x5a\x47\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ -\x00\x67\ -\x00\x1c\ -\x08\xb5\x77\x67\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\ -\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x23\ -\x03\xa5\x91\x47\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ -\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\ -\x00\x6e\x00\x67\ -\x00\x17\ -\x0d\xdf\xcf\xa7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ -\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x14\ -\x0b\x23\x21\x67\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x16\ -\x07\x09\xf8\x27\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x40\x00\x32\ -\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x02\x38\x25\x07\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ -\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1f\ -\x0b\x48\x50\x87\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ -\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x27\ -\x0c\xeb\xe5\x67\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\ -\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1f\ -\x03\xf7\x18\x07\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\ -\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1f\ -\x0a\xae\x27\x47\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ -\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x0a\x27\x78\x07\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ -\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x13\ -\x0b\x4e\x57\xa7\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x2e\x00\x70\ -\x00\x6e\x00\x67\ -\x00\x13\ -\x00\xcf\x5c\xc7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\ -\x00\x6e\x00\x67\ -\x00\x1a\ -\x07\x88\x25\x07\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ -\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x11\ -\x08\xfc\x49\xe7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\ -\x00\x14\ -\x0a\x20\x6e\x07\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x40\x00\x32\x00\x78\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x0e\ -\x0d\x4e\x71\x87\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0f\ -\x00\xd6\x25\xc7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x0e\xbc\xc3\x67\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\ -\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x09\x5e\xb0\x07\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ -\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x15\ -\x03\x1c\x93\x87\ -\x00\x74\ -\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ -\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x09\x2f\xda\x87\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x5f\x00\x66\x00\x6f\x00\x63\ -\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0f\ -\x06\x53\x25\xa7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x0c\x33\x94\x27\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ -\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1e\ -\x0f\x96\x71\x87\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x10\ -\x00\x55\x62\x07\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x00\x38\x7f\xa7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x5f\x00\x66\ -\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1d\ -\x0a\xd8\x81\x27\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\ -\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0f\ -\x00\x6f\x04\x87\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x21\ -\x0a\x51\x5f\x47\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ -\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\ -\x00\x11\ -\x0b\xda\x30\xa7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\ -\x00\x1c\ -\x08\x3f\xda\x67\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ -\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x26\ -\x07\x4b\x88\xe7\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ -\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\ -\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1c\ -\x01\xe0\x4a\x07\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x64\ -\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x22\ -\x04\x9a\x03\x67\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ -\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ -\x00\x67\ -\x00\x2a\ -\x0f\xc4\xf7\x07\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ -\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x18\ -\x06\x65\x89\xe7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ -\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x15\ -\x04\x90\x0a\xc7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ -\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1c\ -\x07\x5b\xb0\x67\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\ -\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1c\ -\x01\x15\x51\xe7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x5f\x00\x66\ -\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0f\ -\x0f\x2c\x24\xc7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x0b\xf3\xab\x27\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x40\ -\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1d\ -\x08\xe1\xf6\xc7\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\ -\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x28\ -\x0f\x63\x53\xc7\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\ -\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x15\ -\x0d\x86\xf9\xe7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\ -\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1b\ -\x00\xc1\x23\x67\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ -\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x12\ -\x0d\x78\xb6\x87\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\ -\x00\x67\ -\x00\x24\ -\x05\x98\x88\x87\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ -\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x26\ -\x0f\xfb\x22\x07\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ -\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\ -\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x0b\x8a\x15\xe7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ -\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x0f\xff\xfc\x07\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ -\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x26\ -\x0f\x35\xf0\xa7\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ -\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1e\ -\x00\x4f\xcb\xe7\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ -\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x0b\x9d\x16\x67\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ -\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1d\ -\x06\xba\x02\xa7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x5f\x00\x64\x00\x69\x00\x73\ -\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x07\xb7\xa1\x47\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\ -\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x20\ -\x07\x4e\x5a\xc7\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x0b\x9d\x4d\x67\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ -\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0c\ -\x0b\xd0\x7a\xe7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1b\ -\x02\xd4\x90\x87\ -\x00\x74\ -\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ -\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x12\ -\x04\xa2\xb3\x27\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ -\x00\x67\ -\x00\x29\ -\x08\x67\xa4\xa7\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\ -\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x18\ -\x08\xd2\xa3\x27\ -\x00\x62\ -\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\ -\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x14\ -\x06\xe9\x8f\x67\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x1c\ -\x00\xf3\x26\x27\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x5f\x00\x64\ -\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -" - -qt_resource_struct_v1 = b"\ -\x00\x00\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x01\ -\x00\x00\x00\x18\x00\x02\x00\x00\x00\x01\x00\x00\x00\xd5\ -\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\ -\x00\x00\x00\x32\x00\x02\x00\x00\x00\x01\x00\x00\x00\x04\ -\x00\x00\x00\x60\x00\x02\x00\x00\x00\xd0\x00\x00\x00\x05\ -\x00\x00\x18\x4c\x00\x00\x00\x00\x00\x01\x00\x01\x3b\x76\ -\x00\x00\x07\xe8\x00\x00\x00\x00\x00\x01\x00\x00\x68\x2b\ -\x00\x00\x0d\x0e\x00\x00\x00\x00\x00\x01\x00\x00\xb6\x47\ -\x00\x00\x25\xea\x00\x00\x00\x00\x00\x01\x00\x01\xd7\xaf\ -\x00\x00\x13\x62\x00\x00\x00\x00\x00\x01\x00\x01\x04\xe1\ -\x00\x00\x03\x52\x00\x00\x00\x00\x00\x01\x00\x00\x41\xeb\ -\x00\x00\x2c\x2c\x00\x00\x00\x00\x00\x01\x00\x02\x1c\x30\ -\x00\x00\x25\xc4\x00\x00\x00\x00\x00\x01\x00\x01\xd4\xe1\ -\x00\x00\x0b\x4e\x00\x00\x00\x00\x00\x01\x00\x00\x97\x7a\ -\x00\x00\x09\xec\x00\x00\x00\x00\x00\x01\x00\x00\x88\x43\ -\x00\x00\x26\x62\x00\x00\x00\x00\x00\x01\x00\x01\xe3\xbc\ -\x00\x00\x1a\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x60\x51\ -\x00\x00\x2a\x68\x00\x00\x00\x00\x00\x01\x00\x02\x0e\x25\ -\x00\x00\x23\x4e\x00\x00\x00\x00\x00\x01\x00\x01\xb5\x50\ -\x00\x00\x24\x2c\x00\x00\x00\x00\x00\x01\x00\x01\xc5\x39\ -\x00\x00\x2e\xd4\x00\x00\x00\x00\x00\x01\x00\x02\x3b\x4e\ -\x00\x00\x0a\xa6\x00\x00\x00\x00\x00\x01\x00\x00\x90\xe9\ -\x00\x00\x29\x0c\x00\x00\x00\x00\x00\x01\x00\x01\xfc\x4d\ -\x00\x00\x15\x4e\x00\x00\x00\x00\x00\x01\x00\x01\x17\x04\ -\x00\x00\x0c\xc4\x00\x00\x00\x00\x00\x01\x00\x00\xb5\xb7\ -\x00\x00\x1a\xcc\x00\x00\x00\x00\x00\x01\x00\x01\x5e\xc4\ -\x00\x00\x01\x32\x00\x00\x00\x00\x00\x01\x00\x00\x23\x58\ -\x00\x00\x11\xb4\x00\x00\x00\x00\x00\x01\x00\x00\xe4\x33\ -\x00\x00\x27\x86\x00\x00\x00\x00\x00\x01\x00\x01\xef\xdb\ -\x00\x00\x06\x00\x00\x00\x00\x00\x00\x01\x00\x00\x56\xae\ -\x00\x00\x05\x82\x00\x00\x00\x00\x00\x01\x00\x00\x55\x3f\ -\x00\x00\x19\xbe\x00\x00\x00\x00\x00\x01\x00\x01\x54\x5c\ -\x00\x00\x10\x24\x00\x00\x00\x00\x00\x01\x00\x00\xda\x1f\ -\x00\x00\x21\x90\x00\x00\x00\x00\x00\x01\x00\x01\xa5\xba\ -\x00\x00\x1c\x4c\x00\x00\x00\x00\x00\x01\x00\x01\x67\xc0\ -\x00\x00\x19\x7a\x00\x00\x00\x00\x00\x01\x00\x01\x4b\x73\ -\x00\x00\x05\x44\x00\x00\x00\x00\x00\x01\x00\x00\x52\x7b\ -\x00\x00\x09\x6e\x00\x00\x00\x00\x00\x01\x00\x00\x83\x3b\ -\x00\x00\x2d\xb2\x00\x00\x00\x00\x00\x01\x00\x02\x26\xe6\ -\x00\x00\x24\xc2\x00\x00\x00\x00\x00\x01\x00\x01\xcb\xce\ -\x00\x00\x1d\x2a\x00\x00\x00\x00\x00\x01\x00\x01\x73\x06\ -\x00\x00\x06\x88\x00\x00\x00\x00\x00\x01\x00\x00\x5e\x2e\ -\x00\x00\x0d\x3c\x00\x00\x00\x00\x00\x01\x00\x00\xc0\xd9\ -\x00\x00\x20\xb0\x00\x00\x00\x00\x00\x01\x00\x01\x9f\xd7\ -\x00\x00\x04\xa6\x00\x00\x00\x00\x00\x01\x00\x00\x48\xc0\ -\x00\x00\x1f\x0a\x00\x00\x00\x00\x00\x01\x00\x01\x8b\xeb\ -\x00\x00\x22\x62\x00\x00\x00\x00\x00\x01\x00\x01\xaa\xcc\ -\x00\x00\x14\x00\x00\x00\x00\x00\x00\x01\x00\x01\x0a\xcd\ -\x00\x00\x03\x8a\x00\x00\x00\x00\x00\x01\x00\x00\x44\x0a\ -\x00\x00\x14\x4e\x00\x00\x00\x00\x00\x01\x00\x01\x0b\x6c\ -\x00\x00\x11\xee\x00\x00\x00\x00\x00\x01\x00\x00\xe8\xc1\ -\x00\x00\x1e\x52\x00\x00\x00\x00\x00\x01\x00\x01\x87\xf8\ -\x00\x00\x17\xd0\x00\x00\x00\x00\x00\x01\x00\x01\x37\x5c\ -\x00\x00\x09\x2a\x00\x00\x00\x00\x00\x01\x00\x00\x81\xe7\ -\x00\x00\x28\x9e\x00\x00\x00\x00\x00\x01\x00\x01\xf9\x30\ -\x00\x00\x27\xc4\x00\x00\x00\x00\x00\x01\x00\x01\xf3\xf4\ -\x00\x00\x1d\xb2\x00\x00\x00\x00\x00\x01\x00\x01\x78\x31\ -\x00\x00\x2d\xee\x00\x00\x00\x00\x00\x01\x00\x02\x27\x5f\ -\x00\x00\x16\xf2\x00\x00\x00\x00\x00\x01\x00\x01\x2f\x6e\ -\x00\x00\x1c\xa2\x00\x00\x00\x00\x00\x01\x00\x01\x6f\x8a\ -\x00\x00\x15\x72\x00\x00\x00\x00\x00\x01\x00\x01\x1a\xf8\ -\x00\x00\x13\xc6\x00\x00\x00\x00\x00\x01\x00\x01\x07\x9f\ -\x00\x00\x05\x10\x00\x00\x00\x00\x00\x01\x00\x00\x4e\x5a\ -\x00\x00\x1e\x8c\x00\x00\x00\x00\x00\x01\x00\x01\x88\xc9\ -\x00\x00\x17\x9a\x00\x00\x00\x00\x00\x01\x00\x01\x34\x70\ -\x00\x00\x1b\xc4\x00\x00\x00\x00\x00\x01\x00\x01\x64\xdd\ -\x00\x00\x11\x46\x00\x00\x00\x00\x00\x01\x00\x00\xe1\xd4\ -\x00\x00\x07\xae\x00\x00\x00\x00\x00\x01\x00\x00\x67\xb2\ -\x00\x00\x03\x2c\x00\x00\x00\x00\x00\x01\x00\x00\x35\x11\ -\x00\x00\x0e\xa4\x00\x00\x00\x00\x00\x01\x00\x00\xc8\x4d\ -\x00\x00\x19\xe6\x00\x00\x00\x00\x00\x01\x00\x01\x55\x2d\ -\x00\x00\x1a\x62\x00\x00\x00\x00\x00\x01\x00\x01\x5a\x91\ -\x00\x00\x0b\xb2\x00\x00\x00\x00\x00\x01\x00\x00\xa2\x57\ -\x00\x00\x0c\x42\x00\x00\x00\x00\x00\x01\x00\x00\xb0\x58\ -\x00\x00\x2a\xce\x00\x00\x00\x00\x00\x01\x00\x02\x13\x3d\ -\x00\x00\x15\xd0\x00\x00\x00\x00\x00\x01\x00\x01\x20\x5a\ -\x00\x00\x1b\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x66\x8b\ -\x00\x00\x1c\xcc\x00\x00\x00\x00\x00\x01\x00\x01\x70\x7c\ -\x00\x00\x13\x30\x00\x00\x00\x00\x00\x01\x00\x01\x02\x9f\ -\x00\x00\x09\x06\x00\x00\x00\x00\x00\x01\x00\x00\x81\x3d\ -\x00\x00\x1e\x1c\x00\x00\x00\x00\x00\x01\x00\x01\x83\x9c\ -\x00\x00\x25\x26\x00\x00\x00\x00\x00\x01\x00\x01\xce\x35\ -\x00\x00\x0e\xec\x00\x00\x00\x00\x00\x01\x00\x00\xc8\xeb\ -\x00\x00\x1b\x48\x00\x00\x00\x00\x00\x01\x00\x01\x61\x28\ -\x00\x00\x28\x68\x00\x00\x00\x00\x00\x01\x00\x01\xf8\x28\ -\x00\x00\x0a\x56\x00\x00\x00\x00\x00\x01\x00\x00\x8d\x02\ -\x00\x00\x12\x90\x00\x00\x00\x00\x00\x01\x00\x00\xf6\x83\ -\x00\x00\x1e\xc6\x00\x00\x00\x00\x00\x01\x00\x01\x8b\x5c\ -\x00\x00\x20\x48\x00\x00\x00\x00\x00\x01\x00\x01\x92\x17\ -\x00\x00\x2c\xa2\x00\x00\x00\x00\x00\x01\x00\x02\x1e\x6c\ -\x00\x00\x2e\xa6\x00\x00\x00\x00\x00\x01\x00\x02\x39\x3f\ -\x00\x00\x1b\x78\x00\x00\x00\x00\x00\x01\x00\x01\x62\xb8\ -\x00\x00\x15\x1e\x00\x00\x00\x00\x00\x01\x00\x01\x16\x5c\ -\x00\x00\x07\x3a\x00\x00\x00\x00\x00\x01\x00\x00\x63\xe4\ -\x00\x00\x21\x5e\x00\x00\x00\x00\x00\x01\x00\x01\xa4\x6f\ -\x00\x00\x19\x2e\x00\x00\x00\x00\x00\x01\x00\x01\x47\xcd\ -\x00\x00\x02\xc0\x00\x00\x00\x00\x00\x01\x00\x00\x33\xb8\ -\x00\x00\x27\x34\x00\x00\x00\x00\x00\x01\x00\x01\xeb\xec\ -\x00\x00\x2d\x1a\x00\x00\x00\x00\x00\x01\x00\x02\x23\xaf\ -\x00\x00\x04\x30\x00\x00\x00\x00\x00\x01\x00\x00\x45\xdc\ -\x00\x00\x28\xce\x00\x00\x00\x00\x00\x01\x00\x01\xfb\x51\ -\x00\x00\x05\xca\x00\x00\x00\x00\x00\x01\x00\x00\x56\x03\ -\x00\x00\x0b\x18\x00\x00\x00\x00\x00\x01\x00\x00\x96\xef\ -\x00\x00\x23\x7a\x00\x00\x00\x00\x00\x01\x00\x01\xbb\xb9\ -\x00\x00\x01\xda\x00\x00\x00\x00\x00\x01\x00\x00\x2c\x7b\ -\x00\x00\x13\x90\x00\x00\x00\x00\x00\x01\x00\x01\x05\x7a\ -\x00\x00\x15\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x23\x96\ -\x00\x00\x2c\xe2\x00\x00\x00\x00\x00\x01\x00\x02\x22\x0c\ -\x00\x00\x06\x5a\x00\x00\x00\x00\x00\x01\x00\x00\x5b\xa0\ -\x00\x00\x1f\xf8\x00\x00\x00\x00\x00\x01\x00\x01\x91\x3d\ -\x00\x00\x17\x5e\x00\x00\x00\x00\x00\x01\x00\x01\x31\x04\ -\x00\x00\x18\x0e\x00\x00\x00\x00\x00\x01\x00\x01\x3a\xe9\ -\x00\x00\x26\xf6\x00\x00\x00\x00\x00\x01\x00\x01\xea\x65\ -\x00\x00\x2e\x18\x00\x00\x00\x00\x00\x01\x00\x02\x2b\xca\ -\x00\x00\x16\x76\x00\x00\x00\x00\x00\x01\x00\x01\x2b\x29\ -\x00\x00\x07\x12\x00\x00\x00\x00\x00\x01\x00\x00\x5f\xdf\ -\x00\x00\x20\x72\x00\x00\x00\x00\x00\x01\x00\x01\x94\xdf\ -\x00\x00\x06\x2e\x00\x00\x00\x00\x00\x01\x00\x00\x57\xa8\ -\x00\x00\x2e\x70\x00\x00\x00\x00\x00\x01\x00\x02\x2c\x65\ -\x00\x00\x29\xa2\x00\x00\x00\x00\x00\x01\x00\x02\x04\xaf\ -\x00\x00\x0d\xe0\x00\x00\x00\x00\x00\x01\x00\x00\xc4\x8b\ -\x00\x00\x23\xb4\x00\x00\x00\x00\x00\x01\x00\x01\xbc\xc3\ -\x00\x00\x02\x44\x00\x00\x00\x00\x00\x01\x00\x00\x2f\xce\ -\x00\x00\x02\x84\x00\x00\x00\x00\x00\x01\x00\x00\x32\xad\ -\x00\x00\x1a\x28\x00\x00\x00\x00\x00\x01\x00\x01\x56\x61\ -\x00\x00\x24\xf2\x00\x00\x00\x00\x00\x01\x00\x01\xcc\x3a\ -\x00\x00\x24\x8a\x00\x00\x00\x00\x00\x01\x00\x01\xca\xfe\ -\x00\x00\x06\xba\x00\x00\x00\x00\x00\x01\x00\x00\x5e\xbb\ -\x00\x00\x08\x60\x00\x00\x00\x00\x00\x01\x00\x00\x72\x4a\ -\x00\x00\x01\xb2\x00\x00\x00\x00\x00\x01\x00\x00\x2a\x72\ -\x00\x00\x11\x6e\x00\x00\x00\x00\x00\x01\x00\x00\xe2\x5d\ -\x00\x00\x1f\xa0\x00\x00\x00\x00\x00\x01\x00\x01\x90\x75\ -\x00\x00\x08\xd6\x00\x00\x00\x00\x00\x01\x00\x00\x7f\xa1\ -\x00\x00\x18\x8a\x00\x00\x00\x00\x00\x01\x00\x01\x43\xc9\ -\x00\x00\x16\x3a\x00\x00\x00\x00\x00\x01\x00\x01\x24\x34\ -\x00\x00\x16\xc0\x00\x00\x00\x00\x00\x01\x00\x01\x2d\x33\ -\x00\x00\x23\xdc\x00\x00\x00\x00\x00\x01\x00\x01\xc1\x39\ -\x00\x00\x22\xea\x00\x00\x00\x00\x00\x01\x00\x01\xb1\x82\ -\x00\x00\x26\x86\x00\x00\x00\x00\x00\x01\x00\x01\xe5\x72\ -\x00\x00\x14\xec\x00\x00\x00\x00\x00\x01\x00\x01\x13\x80\ -\x00\x00\x0f\x4a\x00\x00\x00\x00\x00\x01\x00\x00\xce\xcb\ -\x00\x00\x22\xa6\x00\x00\x00\x00\x00\x01\x00\x01\xaf\xf7\ -\x00\x00\x26\x22\x00\x00\x00\x00\x00\x01\x00\x01\xd8\x81\ -\x00\x00\x0f\x22\x00\x00\x00\x00\x00\x01\x00\x00\xc9\xdd\ -\x00\x00\x1d\x76\x00\x00\x00\x00\x00\x01\x00\x01\x74\x2a\ -\x00\x00\x21\x30\x00\x00\x00\x00\x00\x01\x00\x01\xa2\x41\ -\x00\x00\x14\xbe\x00\x00\x00\x00\x00\x01\x00\x01\x11\x55\ -\x00\x00\x08\x26\x00\x00\x00\x00\x00\x01\x00\x00\x6e\xe4\ -\x00\x00\x21\xca\x00\x00\x00\x00\x00\x01\x00\x01\xa6\xad\ -\x00\x00\x23\x22\x00\x00\x00\x00\x00\x01\x00\x01\xb4\xd4\ -\x00\x00\x0f\xec\x00\x00\x00\x00\x00\x01\x00\x00\xd6\x48\ -\x00\x00\x1c\x82\x00\x00\x00\x00\x00\x01\x00\x01\x6a\x9e\ -\x00\x00\x18\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x47\x43\ -\x00\x00\x2b\x6e\x00\x00\x00\x00\x00\x01\x00\x02\x15\x4a\ -\x00\x00\x2c\x6e\x00\x00\x00\x00\x00\x01\x00\x02\x1d\xc7\ -\x00\x00\x2d\x60\x00\x00\x00\x00\x00\x01\x00\x02\x24\x4a\ -\x00\x00\x2d\x94\x00\x00\x00\x00\x00\x01\x00\x02\x24\xd5\ -\x00\x00\x26\xce\x00\x00\x00\x00\x00\x01\x00\x01\xe8\xd4\ -\x00\x00\x11\x0a\x00\x00\x00\x00\x00\x01\x00\x00\xe0\xfe\ -\x00\x00\x29\x6e\x00\x00\x00\x00\x00\x01\x00\x01\xff\xc4\ -\x00\x00\x00\xf2\x00\x00\x00\x00\x00\x01\x00\x00\x1f\x99\ -\x00\x00\x10\x96\x00\x00\x00\x00\x00\x01\x00\x00\xdb\x7f\ -\x00\x00\x0e\x6c\x00\x00\x00\x00\x00\x01\x00\x00\xc7\xd2\ -\x00\x00\x25\x4a\x00\x00\x00\x00\x00\x01\x00\x01\xcf\xcd\ -\x00\x00\x0f\xbc\x00\x00\x00\x00\x00\x01\x00\x00\xd4\x1f\ -\x00\x00\x0b\xe4\x00\x00\x00\x00\x00\x01\x00\x00\xaf\x31\ -\x00\x00\x09\xa8\x00\x00\x00\x00\x00\x01\x00\x00\x87\xb4\ -\x00\x00\x08\x9e\x00\x00\x00\x00\x00\x01\x00\x00\x72\xc7\ -\x00\x00\x17\x1c\x00\x00\x00\x00\x00\x01\x00\x01\x30\x76\ -\x00\x00\x0a\xde\x00\x00\x00\x00\x00\x01\x00\x00\x95\xf5\ -\x00\x00\x12\x6c\x00\x00\x00\x00\x00\x01\x00\x00\xf6\x17\ -\x00\x00\x02\xf8\x00\x00\x00\x00\x00\x01\x00\x00\x34\x42\ -\x00\x00\x22\x0e\x00\x00\x00\x00\x00\x01\x00\x01\xaa\x03\ -\x00\x00\x1a\x8e\x00\x00\x00\x00\x00\x01\x00\x01\x5b\x5d\ -\x00\x00\x0e\x02\x00\x00\x00\x00\x00\x01\x00\x00\xc6\xbd\ -\x00\x00\x00\x9e\x00\x00\x00\x00\x00\x01\x00\x00\x1f\x0d\ -\x00\x00\x18\xc4\x00\x00\x00\x00\x00\x01\x00\x01\x46\xb8\ -\x00\x00\x24\x0a\x00\x00\x00\x00\x00\x01\x00\x01\xc4\x9e\ -\x00\x00\x04\x72\x00\x00\x00\x00\x00\x01\x00\x00\x47\x31\ -\x00\x00\x2a\xa4\x00\x00\x00\x00\x00\x01\x00\x02\x11\x25\ -\x00\x00\x2a\x38\x00\x00\x00\x00\x00\x01\x00\x02\x0a\x43\ -\x00\x00\x02\x10\x00\x00\x00\x00\x00\x01\x00\x00\x2e\x25\ -\x00\x00\x20\xfc\x00\x00\x00\x00\x00\x01\x00\x01\xa0\x76\ -\x00\x00\x12\x30\x00\x00\x00\x00\x00\x01\x00\x00\xf1\x9c\ -\x00\x00\x0a\x20\x00\x00\x00\x00\x00\x01\x00\x00\x88\xcc\ -\x00\x00\x04\xdc\x00\x00\x00\x00\x00\x01\x00\x00\x4a\x76\ -\x00\x00\x12\xf8\x00\x00\x00\x00\x00\x01\x00\x01\x02\x0e\ -\x00\x00\x10\x60\x00\x00\x00\x00\x00\x01\x00\x00\xdb\x13\ -\x00\x00\x07\x6e\x00\x00\x00\x00\x00\x01\x00\x00\x64\x50\ -\x00\x00\x03\xdc\x00\x00\x00\x00\x00\x01\x00\x00\x44\xa3\ -\x00\x00\x1d\xe4\x00\x00\x00\x00\x00\x01\x00\x01\x7d\x1d\ -\x00\x00\x24\x50\x00\x00\x00\x00\x00\x01\x00\x01\xc5\xc2\ -\x00\x00\x10\xc2\x00\x00\x00\x00\x00\x01\x00\x00\xe0\x6b\ -\x00\x00\x00\x6a\x00\x00\x00\x00\x00\x01\x00\x00\x1a\xaa\ -\x00\x00\x01\x6c\x00\x00\x00\x00\x00\x01\x00\x00\x25\x38\ -\x00\x00\x15\x9c\x00\x00\x00\x00\x00\x01\x00\x01\x1e\x29\ -\x00\x00\x0c\x90\x00\x00\x00\x00\x00\x01\x00\x00\xb0\xe3\ -\x00\x00\x29\x4a\x00\x00\x00\x00\x00\x01\x00\x01\xfd\x9e\ -\x00\x00\x2b\xda\x00\x00\x00\x00\x00\x01\x00\x02\x1b\xa2\ -\x00\x00\x0d\x70\x00\x00\x00\x00\x00\x01\x00\x00\xc3\x1b\ -\x00\x00\x0b\x78\x00\x00\x00\x00\x00\x01\x00\x00\x97\xf3\ -\x00\x00\x29\xe2\x00\x00\x00\x00\x00\x01\x00\x02\x09\xa8\ -\x00\x00\x1c\xee\x00\x00\x00\x00\x00\x01\x00\x01\x72\x8a\ -\x00\x00\x0f\x84\x00\x00\x00\x00\x00\x01\x00\x00\xd0\xe7\ -\x00\x00\x12\xc6\x00\x00\x00\x00\x00\x01\x00\x00\xf9\x9e\ -\x00\x00\x25\x82\x00\x00\x00\x00\x00\x01\x00\x01\xd4\x54\ -\x00\x00\x1f\x66\x00\x00\x00\x00\x00\x01\x00\x01\x8d\x15\ -\x00\x00\x14\x8e\x00\x00\x00\x00\x00\x01\x00\x01\x0c\x69\ -\x00\x00\x28\x0e\x00\x00\x00\x00\x00\x01\x00\x01\xf7\x5c\ -\x00\x00\x0d\xa2\x00\x00\x00\x00\x00\x01\x00\x00\xc3\xb7\ -\x00\x00\x0e\x36\x00\x00\x00\x00\x00\x01\x00\x00\xc7\x59\ -\x00\x00\x2b\x1c\x00\x00\x00\x00\x00\x01\x00\x02\x14\x12\ -\x00\x00\x2b\xa6\x00\x00\x00\x00\x00\x01\x00\x02\x19\x7c\ -\x00\x00\x00\x32\x00\x02\x00\x00\x00\x01\x00\x00\x00\xd6\ -\x00\x00\x00\x40\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\ -" - -qt_resource_struct_v2 = b"\ -\x00\x00\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x01\ -\x00\x00\x00\x00\x00\x00\x00\x00\ -\x00\x00\x00\x18\x00\x02\x00\x00\x00\x01\x00\x00\x00\xd5\ -\x00\x00\x00\x00\x00\x00\x00\x00\ -\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\ -\x00\x00\x00\x00\x00\x00\x00\x00\ -\x00\x00\x00\x32\x00\x02\x00\x00\x00\x01\x00\x00\x00\x04\ -\x00\x00\x00\x00\x00\x00\x00\x00\ -\x00\x00\x00\x60\x00\x02\x00\x00\x00\xd0\x00\x00\x00\x05\ -\x00\x00\x00\x00\x00\x00\x00\x00\ -\x00\x00\x18\x4c\x00\x00\x00\x00\x00\x01\x00\x01\x3b\x76\ -\x00\x00\x01\x81\x15\x91\x87\xb0\ -\x00\x00\x07\xe8\x00\x00\x00\x00\x00\x01\x00\x00\x68\x2b\ -\x00\x00\x01\x81\x15\x91\x88\x41\ -\x00\x00\x0d\x0e\x00\x00\x00\x00\x00\x01\x00\x00\xb6\x47\ -\x00\x00\x01\x81\x15\x91\x87\x94\ -\x00\x00\x25\xea\x00\x00\x00\x00\x00\x01\x00\x01\xd7\xaf\ -\x00\x00\x01\x81\x15\x91\x86\x7f\ -\x00\x00\x13\x62\x00\x00\x00\x00\x00\x01\x00\x01\x04\xe1\ -\x00\x00\x01\x81\x15\x91\x84\xf5\ -\x00\x00\x03\x52\x00\x00\x00\x00\x00\x01\x00\x00\x41\xeb\ -\x00\x00\x01\x81\x15\x91\x86\x9e\ -\x00\x00\x2c\x2c\x00\x00\x00\x00\x00\x01\x00\x02\x1c\x30\ -\x00\x00\x01\x81\x15\x91\x85\x87\ -\x00\x00\x25\xc4\x00\x00\x00\x00\x00\x01\x00\x01\xd4\xe1\ -\x00\x00\x01\x81\x15\x91\x86\x4c\ -\x00\x00\x0b\x4e\x00\x00\x00\x00\x00\x01\x00\x00\x97\x7a\ -\x00\x00\x01\x81\x15\x91\x88\x2e\ -\x00\x00\x09\xec\x00\x00\x00\x00\x00\x01\x00\x00\x88\x43\ -\x00\x00\x01\x81\x15\x91\x85\xba\ -\x00\x00\x26\x62\x00\x00\x00\x00\x00\x01\x00\x01\xe3\xbc\ -\x00\x00\x01\x81\x15\x91\x86\x5c\ -\x00\x00\x1a\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x60\x51\ -\x00\x00\x01\x81\x15\x91\x87\xe7\ -\x00\x00\x2a\x68\x00\x00\x00\x00\x00\x01\x00\x02\x0e\x25\ -\x00\x00\x01\x81\x15\x91\x88\x51\ -\x00\x00\x23\x4e\x00\x00\x00\x00\x00\x01\x00\x01\xb5\x50\ -\x00\x00\x01\x81\x15\x91\x88\x3d\ -\x00\x00\x24\x2c\x00\x00\x00\x00\x00\x01\x00\x01\xc5\x39\ -\x00\x00\x01\x81\x15\x91\x85\x07\ -\x00\x00\x2e\xd4\x00\x00\x00\x00\x00\x01\x00\x02\x3b\x4e\ -\x00\x00\x01\x81\x15\x91\x86\x7c\ -\x00\x00\x0a\xa6\x00\x00\x00\x00\x00\x01\x00\x00\x90\xe9\ -\x00\x00\x01\x81\x15\x91\x85\xd5\ -\x00\x00\x29\x0c\x00\x00\x00\x00\x00\x01\x00\x01\xfc\x4d\ -\x00\x00\x01\x81\x15\x91\x88\x67\ -\x00\x00\x15\x4e\x00\x00\x00\x00\x00\x01\x00\x01\x17\x04\ -\x00\x00\x01\x81\x15\x91\x86\xbe\ -\x00\x00\x0c\xc4\x00\x00\x00\x00\x00\x01\x00\x00\xb5\xb7\ -\x00\x00\x01\x81\x15\x91\x86\x10\ -\x00\x00\x1a\xcc\x00\x00\x00\x00\x00\x01\x00\x01\x5e\xc4\ -\x00\x00\x01\x81\x15\x91\x85\x6a\ -\x00\x00\x01\x32\x00\x00\x00\x00\x00\x01\x00\x00\x23\x58\ -\x00\x00\x01\x81\x15\x91\x85\x54\ -\x00\x00\x11\xb4\x00\x00\x00\x00\x00\x01\x00\x00\xe4\x33\ -\x00\x00\x01\x81\x15\x91\x86\xbe\ -\x00\x00\x27\x86\x00\x00\x00\x00\x00\x01\x00\x01\xef\xdb\ -\x00\x00\x01\x81\x15\x91\x85\xda\ -\x00\x00\x06\x00\x00\x00\x00\x00\x00\x01\x00\x00\x56\xae\ -\x00\x00\x01\x81\x15\x91\x87\x84\ -\x00\x00\x05\x82\x00\x00\x00\x00\x00\x01\x00\x00\x55\x3f\ -\x00\x00\x01\x81\x15\x91\x88\x17\ -\x00\x00\x19\xbe\x00\x00\x00\x00\x00\x01\x00\x01\x54\x5c\ -\x00\x00\x01\x81\x15\x91\x86\xec\ -\x00\x00\x10\x24\x00\x00\x00\x00\x00\x01\x00\x00\xda\x1f\ -\x00\x00\x01\x81\x15\x91\x86\xfc\ -\x00\x00\x21\x90\x00\x00\x00\x00\x00\x01\x00\x01\xa5\xba\ -\x00\x00\x01\x81\x15\x91\x87\x0c\ -\x00\x00\x1c\x4c\x00\x00\x00\x00\x00\x01\x00\x01\x67\xc0\ -\x00\x00\x01\x81\x15\x91\x88\x57\ -\x00\x00\x19\x7a\x00\x00\x00\x00\x00\x01\x00\x01\x4b\x73\ -\x00\x00\x01\x81\x15\x91\x87\xaa\ -\x00\x00\x05\x44\x00\x00\x00\x00\x00\x01\x00\x00\x52\x7b\ -\x00\x00\x01\x81\x15\x91\x85\x54\ -\x00\x00\x09\x6e\x00\x00\x00\x00\x00\x01\x00\x00\x83\x3b\ -\x00\x00\x01\x81\x15\x91\x86\xae\ -\x00\x00\x2d\xb2\x00\x00\x00\x00\x00\x01\x00\x02\x26\xe6\ -\x00\x00\x01\x81\x15\x91\x88\x33\ -\x00\x00\x24\xc2\x00\x00\x00\x00\x00\x01\x00\x01\xcb\xce\ -\x00\x00\x01\x81\x15\x91\x86\x4c\ -\x00\x00\x1d\x2a\x00\x00\x00\x00\x00\x01\x00\x01\x73\x06\ -\x00\x00\x01\x81\x15\x91\x87\xfb\ -\x00\x00\x06\x88\x00\x00\x00\x00\x00\x01\x00\x00\x5e\x2e\ -\x00\x00\x01\x81\x15\x91\x87\x75\ -\x00\x00\x0d\x3c\x00\x00\x00\x00\x00\x01\x00\x00\xc0\xd9\ -\x00\x00\x01\x81\x15\x91\x84\x9c\ -\x00\x00\x20\xb0\x00\x00\x00\x00\x00\x01\x00\x01\x9f\xd7\ -\x00\x00\x01\x81\x15\x91\x85\xf9\ -\x00\x00\x04\xa6\x00\x00\x00\x00\x00\x01\x00\x00\x48\xc0\ -\x00\x00\x01\x81\x15\x91\x86\x5c\ -\x00\x00\x1f\x0a\x00\x00\x00\x00\x00\x01\x00\x01\x8b\xeb\ -\x00\x00\x01\x81\x15\x91\x88\x13\ -\x00\x00\x22\x62\x00\x00\x00\x00\x00\x01\x00\x01\xaa\xcc\ -\x00\x00\x01\x81\x15\x91\x87\x4e\ -\x00\x00\x14\x00\x00\x00\x00\x00\x00\x01\x00\x01\x0a\xcd\ -\x00\x00\x01\x81\x15\x91\x85\xf9\ -\x00\x00\x03\x8a\x00\x00\x00\x00\x00\x01\x00\x00\x44\x0a\ -\x00\x00\x01\x81\x15\x91\x86\x2b\ -\x00\x00\x14\x4e\x00\x00\x00\x00\x00\x01\x00\x01\x0b\x6c\ -\x00\x00\x01\x81\x15\x91\x87\x88\ -\x00\x00\x11\xee\x00\x00\x00\x00\x00\x01\x00\x00\xe8\xc1\ -\x00\x00\x01\x81\x15\x91\x87\xb5\ -\x00\x00\x1e\x52\x00\x00\x00\x00\x00\x01\x00\x01\x87\xf8\ -\x00\x00\x01\x81\x15\x91\x86\xec\ -\x00\x00\x17\xd0\x00\x00\x00\x00\x00\x01\x00\x01\x37\x5c\ -\x00\x00\x01\x81\x15\x91\x88\x7c\ -\x00\x00\x09\x2a\x00\x00\x00\x00\x00\x01\x00\x00\x81\xe7\ -\x00\x00\x01\x81\x15\x91\x88\x62\ -\x00\x00\x28\x9e\x00\x00\x00\x00\x00\x01\x00\x01\xf9\x30\ -\x00\x00\x01\x81\x15\x91\x84\x9c\ -\x00\x00\x27\xc4\x00\x00\x00\x00\x00\x01\x00\x01\xf3\xf4\ -\x00\x00\x01\x81\x15\x91\x87\x69\ -\x00\x00\x1d\xb2\x00\x00\x00\x00\x00\x01\x00\x01\x78\x31\ -\x00\x00\x01\x81\x15\x91\x84\xbb\ -\x00\x00\x2d\xee\x00\x00\x00\x00\x00\x01\x00\x02\x27\x5f\ -\x00\x00\x01\x81\x15\x91\x86\xae\ -\x00\x00\x16\xf2\x00\x00\x00\x00\x00\x01\x00\x01\x2f\x6e\ -\x00\x00\x01\x81\x15\x91\x87\x0c\ -\x00\x00\x1c\xa2\x00\x00\x00\x00\x00\x01\x00\x01\x6f\x8a\ -\x00\x00\x01\x81\x15\x91\x86\xfc\ -\x00\x00\x15\x72\x00\x00\x00\x00\x00\x01\x00\x01\x1a\xf8\ -\x00\x00\x01\x81\x15\x91\x87\x0c\ -\x00\x00\x13\xc6\x00\x00\x00\x00\x00\x01\x00\x01\x07\x9f\ -\x00\x00\x01\x81\x15\x91\x86\xec\ -\x00\x00\x05\x10\x00\x00\x00\x00\x00\x01\x00\x00\x4e\x5a\ -\x00\x00\x01\x81\x15\x91\x86\xcd\ -\x00\x00\x1e\x8c\x00\x00\x00\x00\x00\x01\x00\x01\x88\xc9\ -\x00\x00\x01\x81\x15\x91\x85\x52\ -\x00\x00\x17\x9a\x00\x00\x00\x00\x00\x01\x00\x01\x34\x70\ -\x00\x00\x01\x81\x15\x91\x86\x5c\ -\x00\x00\x1b\xc4\x00\x00\x00\x00\x00\x01\x00\x01\x64\xdd\ -\x00\x00\x01\x81\x15\x91\x84\xcb\ -\x00\x00\x11\x46\x00\x00\x00\x00\x00\x01\x00\x00\xe1\xd4\ -\x00\x00\x01\x81\x15\x91\x85\xa9\ -\x00\x00\x07\xae\x00\x00\x00\x00\x00\x01\x00\x00\x67\xb2\ -\x00\x00\x01\x81\x15\x91\x88\x39\ -\x00\x00\x03\x2c\x00\x00\x00\x00\x00\x01\x00\x00\x35\x11\ -\x00\x00\x01\x81\x15\x91\x86\xcd\ -\x00\x00\x0e\xa4\x00\x00\x00\x00\x00\x01\x00\x00\xc8\x4d\ -\x00\x00\x01\x81\x15\x91\x85\xf9\ -\x00\x00\x19\xe6\x00\x00\x00\x00\x00\x01\x00\x01\x55\x2d\ -\x00\x00\x01\x81\x15\x91\x87\xc3\ -\x00\x00\x1a\x62\x00\x00\x00\x00\x00\x01\x00\x01\x5a\x91\ -\x00\x00\x01\x81\x15\x91\x86\x6b\ -\x00\x00\x0b\xb2\x00\x00\x00\x00\x00\x01\x00\x00\xa2\x57\ -\x00\x00\x01\x81\x15\x91\x86\xdd\ -\x00\x00\x0c\x42\x00\x00\x00\x00\x00\x01\x00\x00\xb0\x58\ -\x00\x00\x01\x81\x15\x91\x86\x3d\ -\x00\x00\x2a\xce\x00\x00\x00\x00\x00\x01\x00\x02\x13\x3d\ -\x00\x00\x01\x81\x15\x91\x87\xec\ -\x00\x00\x15\xd0\x00\x00\x00\x00\x00\x01\x00\x01\x20\x5a\ -\x00\x00\x01\x81\x15\x91\x86\xdd\ -\x00\x00\x1b\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x66\x8b\ -\x00\x00\x01\x81\x15\x91\x87\xd5\ -\x00\x00\x1c\xcc\x00\x00\x00\x00\x00\x01\x00\x01\x70\x7c\ -\x00\x00\x01\x81\x15\x91\x84\x48\ -\x00\x00\x13\x30\x00\x00\x00\x00\x00\x01\x00\x01\x02\x9f\ -\x00\x00\x01\x81\x15\x91\x84\x87\ -\x00\x00\x09\x06\x00\x00\x00\x00\x00\x01\x00\x00\x81\x3d\ -\x00\x00\x01\x81\x15\x91\x85\x1a\ -\x00\x00\x1e\x1c\x00\x00\x00\x00\x00\x01\x00\x01\x83\x9c\ -\x00\x00\x01\x81\x15\x91\x86\xbe\ -\x00\x00\x25\x26\x00\x00\x00\x00\x00\x01\x00\x01\xce\x35\ -\x00\x00\x01\x81\x15\x91\x85\x2e\ -\x00\x00\x0e\xec\x00\x00\x00\x00\x00\x01\x00\x00\xc8\xeb\ -\x00\x00\x01\x81\x15\x91\x86\xfc\ -\x00\x00\x1b\x48\x00\x00\x00\x00\x00\x01\x00\x01\x61\x28\ -\x00\x00\x01\x81\x15\x91\x85\x34\ -\x00\x00\x28\x68\x00\x00\x00\x00\x00\x01\x00\x01\xf8\x28\ -\x00\x00\x01\x81\x15\x91\x87\x0c\ -\x00\x00\x0a\x56\x00\x00\x00\x00\x00\x01\x00\x00\x8d\x02\ -\x00\x00\x01\x81\x15\x91\x87\x61\ -\x00\x00\x12\x90\x00\x00\x00\x00\x00\x01\x00\x00\xf6\x83\ -\x00\x00\x01\x81\x15\x91\x87\x23\ -\x00\x00\x1e\xc6\x00\x00\x00\x00\x00\x01\x00\x01\x8b\x5c\ -\x00\x00\x01\x81\x15\x91\x86\x13\ -\x00\x00\x20\x48\x00\x00\x00\x00\x00\x01\x00\x01\x92\x17\ -\x00\x00\x01\x81\x15\x91\x88\x4e\ -\x00\x00\x2c\xa2\x00\x00\x00\x00\x00\x01\x00\x02\x1e\x6c\ -\x00\x00\x01\x81\x15\x91\x88\x75\ -\x00\x00\x2e\xa6\x00\x00\x00\x00\x00\x01\x00\x02\x39\x3f\ -\x00\x00\x01\x81\x15\x91\x84\x65\ -\x00\x00\x1b\x78\x00\x00\x00\x00\x00\x01\x00\x01\x62\xb8\ -\x00\x00\x01\x81\x15\x91\x85\x54\ -\x00\x00\x15\x1e\x00\x00\x00\x00\x00\x01\x00\x01\x16\x5c\ -\x00\x00\x01\x81\x15\x91\x85\x27\ -\x00\x00\x07\x3a\x00\x00\x00\x00\x00\x01\x00\x00\x63\xe4\ -\x00\x00\x01\x81\x15\x91\x86\x4c\ -\x00\x00\x21\x5e\x00\x00\x00\x00\x00\x01\x00\x01\xa4\x6f\ -\x00\x00\x01\x81\x15\x91\x88\x5e\ -\x00\x00\x19\x2e\x00\x00\x00\x00\x00\x01\x00\x01\x47\xcd\ -\x00\x00\x01\x81\x15\x91\x87\x5d\ -\x00\x00\x02\xc0\x00\x00\x00\x00\x00\x01\x00\x00\x33\xb8\ -\x00\x00\x01\x81\x15\x91\x85\xbd\ -\x00\x00\x27\x34\x00\x00\x00\x00\x00\x01\x00\x01\xeb\xec\ -\x00\x00\x01\x81\x15\x91\x87\x58\ -\x00\x00\x2d\x1a\x00\x00\x00\x00\x00\x01\x00\x02\x23\xaf\ -\x00\x00\x01\x81\x15\x91\x86\x1f\ -\x00\x00\x04\x30\x00\x00\x00\x00\x00\x01\x00\x00\x45\xdc\ -\x00\x00\x01\x81\x15\x91\x88\x6b\ -\x00\x00\x28\xce\x00\x00\x00\x00\x00\x01\x00\x01\xfb\x51\ -\x00\x00\x01\x81\x15\x91\x87\x90\ -\x00\x00\x05\xca\x00\x00\x00\x00\x00\x01\x00\x00\x56\x03\ -\x00\x00\x01\x81\x15\x91\x85\x1d\ -\x00\x00\x0b\x18\x00\x00\x00\x00\x00\x01\x00\x00\x96\xef\ -\x00\x00\x01\x81\x15\x91\x85\x0a\ -\x00\x00\x23\x7a\x00\x00\x00\x00\x00\x01\x00\x01\xbb\xb9\ -\x00\x00\x01\x81\x15\x91\x87\x0c\ -\x00\x00\x01\xda\x00\x00\x00\x00\x00\x01\x00\x00\x2c\x7b\ -\x00\x00\x01\x81\x15\x91\x85\x31\ -\x00\x00\x13\x90\x00\x00\x00\x00\x00\x01\x00\x01\x05\x7a\ -\x00\x00\x01\x81\x15\x91\x84\x8c\ -\x00\x00\x15\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x23\x96\ -\x00\x00\x01\x81\x15\x91\x85\xe9\ -\x00\x00\x2c\xe2\x00\x00\x00\x00\x00\x01\x00\x02\x22\x0c\ -\x00\x00\x01\x81\x15\x91\x84\xdb\ -\x00\x00\x06\x5a\x00\x00\x00\x00\x00\x01\x00\x00\x5b\xa0\ -\x00\x00\x01\x81\x15\x91\x85\x46\ -\x00\x00\x1f\xf8\x00\x00\x00\x00\x00\x01\x00\x01\x91\x3d\ -\x00\x00\x01\x81\x15\x91\x87\xe3\ -\x00\x00\x17\x5e\x00\x00\x00\x00\x00\x01\x00\x01\x31\x04\ -\x00\x00\x01\x81\x15\x91\x87\x1b\ -\x00\x00\x18\x0e\x00\x00\x00\x00\x00\x01\x00\x01\x3a\xe9\ -\x00\x00\x01\x81\x15\x91\x87\x7d\ -\x00\x00\x26\xf6\x00\x00\x00\x00\x00\x01\x00\x01\xea\x65\ -\x00\x00\x01\x81\x15\x91\x85\x7d\ -\x00\x00\x2e\x18\x00\x00\x00\x00\x00\x01\x00\x02\x2b\xca\ -\x00\x00\x01\x81\x15\x91\x86\x28\ -\x00\x00\x16\x76\x00\x00\x00\x00\x00\x01\x00\x01\x2b\x29\ -\x00\x00\x01\x81\x15\x91\x85\x54\ -\x00\x00\x07\x12\x00\x00\x00\x00\x00\x01\x00\x00\x5f\xdf\ -\x00\x00\x01\x81\x15\x91\x86\x9e\ -\x00\x00\x20\x72\x00\x00\x00\x00\x00\x01\x00\x01\x94\xdf\ -\x00\x00\x01\x81\x15\x91\x87\xa3\ -\x00\x00\x06\x2e\x00\x00\x00\x00\x00\x01\x00\x00\x57\xa8\ -\x00\x00\x01\x81\x15\x91\x85\xda\ -\x00\x00\x2e\x70\x00\x00\x00\x00\x00\x01\x00\x02\x2c\x65\ -\x00\x00\x01\x81\x15\x91\x86\xdd\ -\x00\x00\x29\xa2\x00\x00\x00\x00\x00\x01\x00\x02\x04\xaf\ -\x00\x00\x01\x81\x15\x91\x87\x48\ -\x00\x00\x0d\xe0\x00\x00\x00\x00\x00\x01\x00\x00\xc4\x8b\ -\x00\x00\x01\x81\x15\x91\x84\x7c\ -\x00\x00\x23\xb4\x00\x00\x00\x00\x00\x01\x00\x01\xbc\xc3\ -\x00\x00\x01\x81\x15\x91\x86\xae\ -\x00\x00\x02\x44\x00\x00\x00\x00\x00\x01\x00\x00\x2f\xce\ -\x00\x00\x01\x81\x15\x91\x85\x4f\ -\x00\x00\x02\x84\x00\x00\x00\x00\x00\x01\x00\x00\x32\xad\ -\x00\x00\x01\x81\x15\x91\x87\x0c\ -\x00\x00\x1a\x28\x00\x00\x00\x00\x00\x01\x00\x01\x56\x61\ -\x00\x00\x01\x81\x15\x91\x86\x9e\ -\x00\x00\x24\xf2\x00\x00\x00\x00\x00\x01\x00\x01\xcc\x3a\ -\x00\x00\x01\x81\x15\x91\x86\x8f\ -\x00\x00\x24\x8a\x00\x00\x00\x00\x00\x01\x00\x01\xca\xfe\ -\x00\x00\x01\x81\x15\x91\x86\xfc\ -\x00\x00\x06\xba\x00\x00\x00\x00\x00\x01\x00\x00\x5e\xbb\ -\x00\x00\x01\x81\x15\x91\x88\x0d\ -\x00\x00\x08\x60\x00\x00\x00\x00\x00\x01\x00\x00\x72\x4a\ -\x00\x00\x01\x81\x15\x91\x85\x93\ -\x00\x00\x01\xb2\x00\x00\x00\x00\x00\x01\x00\x00\x2a\x72\ -\x00\x00\x01\x81\x15\x91\x86\x7f\ -\x00\x00\x11\x6e\x00\x00\x00\x00\x00\x01\x00\x00\xe2\x5d\ -\x00\x00\x01\x81\x15\x91\x85\x54\ -\x00\x00\x1f\xa0\x00\x00\x00\x00\x00\x01\x00\x01\x90\x75\ -\x00\x00\x01\x81\x15\x91\x88\x2b\ -\x00\x00\x08\xd6\x00\x00\x00\x00\x00\x01\x00\x00\x7f\xa1\ -\x00\x00\x01\x81\x15\x91\x86\x6b\ -\x00\x00\x18\x8a\x00\x00\x00\x00\x00\x01\x00\x01\x43\xc9\ -\x00\x00\x01\x81\x15\x91\x88\x5b\ -\x00\x00\x16\x3a\x00\x00\x00\x00\x00\x01\x00\x01\x24\x34\ -\x00\x00\x01\x81\x15\x91\x88\x4a\ -\x00\x00\x16\xc0\x00\x00\x00\x00\x00\x01\x00\x01\x2d\x33\ -\x00\x00\x01\x81\x15\x91\x84\x72\ -\x00\x00\x23\xdc\x00\x00\x00\x00\x00\x01\x00\x01\xc1\x39\ -\x00\x00\x01\x81\x15\x91\x88\x70\ -\x00\x00\x22\xea\x00\x00\x00\x00\x00\x01\x00\x01\xb1\x82\ -\x00\x00\x01\x81\x15\x91\x87\x66\ -\x00\x00\x26\x86\x00\x00\x00\x00\x00\x01\x00\x01\xe5\x72\ -\x00\x00\x01\x81\x15\x91\x87\x72\ -\x00\x00\x14\xec\x00\x00\x00\x00\x00\x01\x00\x01\x13\x80\ -\x00\x00\x01\x81\x15\x91\x86\x5c\ -\x00\x00\x0f\x4a\x00\x00\x00\x00\x00\x01\x00\x00\xce\xcb\ -\x00\x00\x01\x81\x15\x91\x86\x8f\ -\x00\x00\x22\xa6\x00\x00\x00\x00\x00\x01\x00\x01\xaf\xf7\ -\x00\x00\x01\x81\x15\x91\x85\x74\ -\x00\x00\x26\x22\x00\x00\x00\x00\x00\x01\x00\x01\xd8\x81\ -\x00\x00\x01\x81\x15\x91\x87\x99\ -\x00\x00\x0f\x22\x00\x00\x00\x00\x00\x01\x00\x00\xc9\xdd\ -\x00\x00\x01\x81\x15\x91\x85\xc6\ -\x00\x00\x1d\x76\x00\x00\x00\x00\x00\x01\x00\x01\x74\x2a\ -\x00\x00\x01\x81\x15\x91\x85\xe9\ -\x00\x00\x21\x30\x00\x00\x00\x00\x00\x01\x00\x01\xa2\x41\ -\x00\x00\x01\x81\x15\x91\x84\xac\ -\x00\x00\x14\xbe\x00\x00\x00\x00\x00\x01\x00\x01\x11\x55\ -\x00\x00\x01\x81\x15\x91\x84\x84\ -\x00\x00\x08\x26\x00\x00\x00\x00\x00\x01\x00\x00\x6e\xe4\ -\x00\x00\x01\x81\x15\x91\x88\x79\ -\x00\x00\x21\xca\x00\x00\x00\x00\x00\x01\x00\x01\xa6\xad\ -\x00\x00\x01\x81\x15\x91\x87\x6e\ -\x00\x00\x23\x22\x00\x00\x00\x00\x00\x01\x00\x01\xb4\xd4\ -\x00\x00\x01\x81\x15\x91\x85\x8b\ -\x00\x00\x0f\xec\x00\x00\x00\x00\x00\x01\x00\x00\xd6\x48\ -\x00\x00\x01\x81\x15\x91\x85\xda\ -\x00\x00\x1c\x82\x00\x00\x00\x00\x00\x01\x00\x01\x6a\x9e\ -\x00\x00\x01\x81\x15\x91\x84\xac\ -\x00\x00\x18\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x47\x43\ -\x00\x00\x01\x81\x15\x91\x85\x0d\ -\x00\x00\x2b\x6e\x00\x00\x00\x00\x00\x01\x00\x02\x15\x4a\ -\x00\x00\x01\x81\x15\x91\x86\x9e\ -\x00\x00\x2c\x6e\x00\x00\x00\x00\x00\x01\x00\x02\x1d\xc7\ -\x00\x00\x01\x81\x15\x91\x85\x2a\ -\x00\x00\x2d\x60\x00\x00\x00\x00\x00\x01\x00\x02\x24\x4a\ -\x00\x00\x01\x81\x15\x91\x85\x17\ -\x00\x00\x2d\x94\x00\x00\x00\x00\x00\x01\x00\x02\x24\xd5\ -\x00\x00\x01\x81\x15\x91\x84\x9c\ -\x00\x00\x26\xce\x00\x00\x00\x00\x00\x01\x00\x01\xe8\xd4\ -\x00\x00\x01\x81\x15\x91\x84\xcb\ -\x00\x00\x11\x0a\x00\x00\x00\x00\x00\x01\x00\x00\xe0\xfe\ -\x00\x00\x01\x81\x15\x91\x86\x7f\ -\x00\x00\x29\x6e\x00\x00\x00\x00\x00\x01\x00\x01\xff\xc4\ -\x00\x00\x01\x81\x15\x91\x87\x3e\ -\x00\x00\x00\xf2\x00\x00\x00\x00\x00\x01\x00\x00\x1f\x99\ -\x00\x00\x01\x81\x15\x91\x87\x53\ -\x00\x00\x10\x96\x00\x00\x00\x00\x00\x01\x00\x00\xdb\x7f\ -\x00\x00\x01\x81\x15\x91\x84\xbb\ -\x00\x00\x0e\x6c\x00\x00\x00\x00\x00\x01\x00\x00\xc7\xd2\ -\x00\x00\x01\x81\x15\x91\x85\x9c\ -\x00\x00\x25\x4a\x00\x00\x00\x00\x00\x01\x00\x01\xcf\xcd\ -\x00\x00\x01\x81\x15\x91\x86\xae\ -\x00\x00\x0f\xbc\x00\x00\x00\x00\x00\x01\x00\x00\xd4\x1f\ -\x00\x00\x01\x81\x15\x91\x84\x9c\ -\x00\x00\x0b\xe4\x00\x00\x00\x00\x00\x01\x00\x00\xaf\x31\ -\x00\x00\x01\x81\x15\x91\x88\x09\ -\x00\x00\x09\xa8\x00\x00\x00\x00\x00\x01\x00\x00\x87\xb4\ -\x00\x00\x01\x81\x15\x91\x87\x79\ -\x00\x00\x08\x9e\x00\x00\x00\x00\x00\x01\x00\x00\x72\xc7\ -\x00\x00\x01\x81\x15\x91\x86\xcd\ -\x00\x00\x17\x1c\x00\x00\x00\x00\x00\x01\x00\x01\x30\x76\ -\x00\x00\x01\x81\x15\x91\x87\x80\ -\x00\x00\x0a\xde\x00\x00\x00\x00\x00\x01\x00\x00\x95\xf5\ -\x00\x00\x01\x81\x15\x91\x87\x8c\ -\x00\x00\x12\x6c\x00\x00\x00\x00\x00\x01\x00\x00\xf6\x17\ -\x00\x00\x01\x81\x15\x91\x86\x3d\ -\x00\x00\x02\xf8\x00\x00\x00\x00\x00\x01\x00\x00\x34\x42\ -\x00\x00\x01\x81\x15\x91\x86\xfc\ -\x00\x00\x22\x0e\x00\x00\x00\x00\x00\x01\x00\x01\xaa\x03\ -\x00\x00\x01\x81\x15\x91\x88\x1f\ -\x00\x00\x1a\x8e\x00\x00\x00\x00\x00\x01\x00\x01\x5b\x5d\ -\x00\x00\x01\x81\x15\x91\x86\xec\ -\x00\x00\x0e\x02\x00\x00\x00\x00\x00\x01\x00\x00\xc6\xbd\ -\x00\x00\x01\x81\x15\x91\x84\xea\ -\x00\x00\x00\x9e\x00\x00\x00\x00\x00\x01\x00\x00\x1f\x0d\ -\x00\x00\x01\x81\x15\x91\x86\x2d\ -\x00\x00\x18\xc4\x00\x00\x00\x00\x00\x01\x00\x01\x46\xb8\ -\x00\x00\x01\x81\x15\x91\x85\xb1\ -\x00\x00\x24\x0a\x00\x00\x00\x00\x00\x01\x00\x01\xc4\x9e\ -\x00\x00\x01\x81\x15\x91\x84\xdb\ -\x00\x00\x04\x72\x00\x00\x00\x00\x00\x01\x00\x00\x47\x31\ -\x00\x00\x01\x81\x15\x91\x84\xdb\ -\x00\x00\x2a\xa4\x00\x00\x00\x00\x00\x01\x00\x02\x11\x25\ -\x00\x00\x01\x81\x15\x91\x84\xac\ -\x00\x00\x2a\x38\x00\x00\x00\x00\x00\x01\x00\x02\x0a\x43\ -\x00\x00\x01\x81\x15\x91\x86\xcd\ -\x00\x00\x02\x10\x00\x00\x00\x00\x00\x01\x00\x00\x2e\x25\ -\x00\x00\x01\x81\x15\x91\x85\x3e\ -\x00\x00\x20\xfc\x00\x00\x00\x00\x00\x01\x00\x01\xa0\x76\ -\x00\x00\x01\x81\x15\x91\x86\x6b\ -\x00\x00\x12\x30\x00\x00\x00\x00\x00\x01\x00\x00\xf1\x9c\ -\x00\x00\x01\x81\x15\x91\x86\xbe\ -\x00\x00\x0a\x20\x00\x00\x00\x00\x00\x01\x00\x00\x88\xcc\ -\x00\x00\x01\x81\x15\x91\x86\xbe\ -\x00\x00\x04\xdc\x00\x00\x00\x00\x00\x01\x00\x00\x4a\x76\ -\x00\x00\x01\x81\x15\x91\x86\x9e\ -\x00\x00\x12\xf8\x00\x00\x00\x00\x00\x01\x00\x01\x02\x0e\ -\x00\x00\x01\x81\x15\x91\x86\x0d\ -\x00\x00\x10\x60\x00\x00\x00\x00\x00\x01\x00\x00\xdb\x13\ -\x00\x00\x01\x81\x15\x91\x86\x3d\ -\x00\x00\x07\x6e\x00\x00\x00\x00\x00\x01\x00\x00\x64\x50\ -\x00\x00\x01\x81\x15\x91\x86\xec\ -\x00\x00\x03\xdc\x00\x00\x00\x00\x00\x01\x00\x00\x44\xa3\ -\x00\x00\x01\x81\x15\x91\x87\xd0\ -\x00\x00\x1d\xe4\x00\x00\x00\x00\x00\x01\x00\x01\x7d\x1d\ -\x00\x00\x01\x81\x15\x91\x88\x46\ -\x00\x00\x24\x50\x00\x00\x00\x00\x00\x01\x00\x01\xc5\xc2\ -\x00\x00\x01\x81\x15\x91\x85\xc9\ -\x00\x00\x10\xc2\x00\x00\x00\x00\x00\x01\x00\x00\xe0\x6b\ -\x00\x00\x01\x81\x15\x91\x86\x16\ -\x00\x00\x00\x6a\x00\x00\x00\x00\x00\x01\x00\x00\x1a\xaa\ -\x00\x00\x01\x81\x15\x91\x86\xae\ -\x00\x00\x01\x6c\x00\x00\x00\x00\x00\x01\x00\x00\x25\x38\ -\x00\x00\x01\x81\x15\x91\x87\x43\ -\x00\x00\x15\x9c\x00\x00\x00\x00\x00\x01\x00\x01\x1e\x29\ -\x00\x00\x01\x81\x15\x91\x84\x81\ -\x00\x00\x0c\x90\x00\x00\x00\x00\x00\x01\x00\x00\xb0\xe3\ -\x00\x00\x01\x81\x15\x91\x85\xcd\ -\x00\x00\x29\x4a\x00\x00\x00\x00\x00\x01\x00\x01\xfd\x9e\ -\x00\x00\x01\x81\x15\x91\x84\x8c\ -\x00\x00\x2b\xda\x00\x00\x00\x00\x00\x01\x00\x02\x1b\xa2\ -\x00\x00\x01\x81\x15\x91\x86\x3d\ -\x00\x00\x0d\x70\x00\x00\x00\x00\x00\x01\x00\x00\xc3\x1b\ -\x00\x00\x01\x81\x15\x91\x84\xfd\ -\x00\x00\x0b\x78\x00\x00\x00\x00\x00\x01\x00\x00\x97\xf3\ -\x00\x00\x01\x81\x15\x91\x87\x9f\ -\x00\x00\x29\xe2\x00\x00\x00\x00\x00\x01\x00\x02\x09\xa8\ -\x00\x00\x01\x81\x15\x91\x86\x2d\ -\x00\x00\x1c\xee\x00\x00\x00\x00\x00\x01\x00\x01\x72\x8a\ -\x00\x00\x01\x81\x15\x91\x85\x9f\ -\x00\x00\x0f\x84\x00\x00\x00\x00\x00\x01\x00\x00\xd0\xe7\ -\x00\x00\x01\x81\x15\x91\x86\x5c\ -\x00\x00\x12\xc6\x00\x00\x00\x00\x00\x01\x00\x00\xf9\x9e\ -\x00\x00\x01\x81\x15\x91\x87\xa7\ -\x00\x00\x25\x82\x00\x00\x00\x00\x00\x01\x00\x01\xd4\x54\ -\x00\x00\x01\x81\x15\x91\x86\x2d\ -\x00\x00\x1f\x66\x00\x00\x00\x00\x00\x01\x00\x01\x8d\x15\ -\x00\x00\x01\x81\x15\x91\x87\x32\ -\x00\x00\x14\x8e\x00\x00\x00\x00\x00\x01\x00\x01\x0c\x69\ -\x00\x00\x01\x81\x15\x91\x84\xbb\ -\x00\x00\x28\x0e\x00\x00\x00\x00\x00\x01\x00\x01\xf7\x5c\ -\x00\x00\x01\x81\x15\x91\x88\x1b\ -\x00\x00\x0d\xa2\x00\x00\x00\x00\x00\x01\x00\x00\xc3\xb7\ -\x00\x00\x01\x81\x15\x91\x87\xdd\ -\x00\x00\x0e\x36\x00\x00\x00\x00\x00\x01\x00\x00\xc7\x59\ -\x00\x00\x01\x81\x15\x91\x88\x36\ -\x00\x00\x2b\x1c\x00\x00\x00\x00\x00\x01\x00\x02\x14\x12\ -\x00\x00\x01\x81\x15\x91\x87\xd9\ -\x00\x00\x2b\xa6\x00\x00\x00\x00\x00\x01\x00\x02\x19\x7c\ -\x00\x00\x01\x81\x15\x91\x84\x53\ -\x00\x00\x00\x32\x00\x02\x00\x00\x00\x01\x00\x00\x00\xd6\ -\x00\x00\x00\x00\x00\x00\x00\x00\ -\x00\x00\x00\x40\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\ -\x00\x00\x01\x81\x15\x91\x89\x29\ -" - -qt_version = [int(v) for v in QtCore.qVersion().split('.')] -if qt_version < [5, 8, 0]: - rcc_version = 1 - qt_resource_struct = qt_resource_struct_v1 -else: - rcc_version = 2 - qt_resource_struct = qt_resource_struct_v2 - -def qInitResources(): - QtCore.qRegisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data) - -def qCleanupResources(): - QtCore.qUnregisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data) - -qInitResources() +# -*- coding: utf-8 -*- + +# Resource object code +# +# Created by: The Resource Compiler for PyQt5 (Qt v5.15.2) +# +# WARNING! All changes made in this file will be lost! + +from qtpy import QtCore + +qt_resource_data = b"\ +\x00\x00\x1a\xa6\ +\x00\ +\x00\xdc\x92\x78\x9c\xd5\x3d\x6b\x6f\xdb\x46\xb6\xdf\x0b\xf4\x3f\ +\xd0\x31\xb0\x68\xbb\x96\x6d\xc9\xb2\x63\xab\xe8\x07\x3b\x8f\x6e\ +\x80\x34\x4d\x6a\x77\x8b\x8b\xc5\x85\x41\x49\x94\xc5\x0d\x45\x2a\ +\x24\x15\xc7\x2d\xee\x7f\xbf\x33\x43\xce\x70\x1e\x67\x5e\x7c\xd8\ +\xa9\x81\xa6\xb6\x34\x73\xde\x73\xce\x3c\xce\x9c\x39\xfa\x21\x18\ +\xf5\xf7\xf3\xed\x37\xdf\x7e\x13\xa0\x9f\x3f\x2e\x7f\x7b\xf7\xe6\ +\xdd\xcf\x7b\xc1\xeb\x38\x89\x82\x45\x1e\x85\x65\xb4\x0c\xb6\x79\ +\x76\x97\x87\x9b\x4d\x58\xc6\x8b\x30\x49\x1e\x0e\x83\xcb\x24\x09\ +\x16\xeb\x30\xbd\x8b\x8a\x60\x13\x2e\xa3\x20\x4e\x83\x72\x1d\x17\ +\xc1\x0a\xf7\xbb\x8f\xd1\xd7\xf3\x28\x48\xb2\xa2\xdc\xa3\xa0\x5f\ +\xd4\xc0\xe6\x0f\xa8\x65\x14\x7c\x2a\x8b\xb0\x28\x82\x45\xb6\xd9\ +\xa2\x2e\x79\xf0\xf9\xf8\xf0\xe4\xf0\x98\x36\xbe\x41\x2d\x96\xd1\ +\x2a\x4e\xe3\x32\xce\xd2\x22\x08\xf3\x1a\x45\x14\x3c\xfb\xb4\x0c\ +\xf3\x8f\x45\xf9\x90\x44\x87\x9f\x8a\xe2\xf0\x96\xfc\x5a\x1c\x16\ +\x8b\xa2\x78\x16\x6c\xb2\xe5\x2e\x89\x30\x98\x1e\xa5\x13\xfc\x70\ +\xf4\xed\x37\x47\x3f\x04\x6f\xe3\xbb\x75\x19\x5c\x63\x7c\xc1\x28\ +\xf8\xf0\x12\xd1\x41\xfe\xb8\x5e\x47\x51\xe9\xa1\x8e\x1a\x1e\xa6\ +\xf2\x3a\x8a\x82\x0f\x65\xb0\xcc\x16\xbb\x4d\x94\x96\x21\x66\x77\ +\x56\x49\x61\x14\xac\xcb\x72\x5b\xcc\x8e\x8e\xd0\xb7\x87\x9f\xca\ +\xc3\x38\x3b\xfa\x54\x8e\x4e\x8f\x2a\x86\x31\xce\xc3\x75\xb9\x49\ +\x1c\xdb\x8e\xf2\x68\x15\xe5\x51\xba\x88\xbc\x7a\x45\x5f\xc2\xcd\ +\x16\xcb\xb7\xea\x34\x88\x5c\x7f\x8b\x0a\x24\xbf\x28\x89\xb0\x08\ +\x8a\x4e\x76\x8d\x29\x24\xe0\xca\x38\xbd\x0b\xa2\xcf\x51\xfe\x80\ +\xec\x12\xfd\xba\x8e\x92\x6d\x11\x94\x59\xb0\x4b\xe3\xd5\x43\x50\ +\x71\x18\x84\x8b\x3c\x43\x56\xb8\x8c\x57\x44\x36\x65\x90\x6d\xa3\ +\x3c\x24\x7d\x8b\x87\xa2\x8c\x36\xc5\x10\x2c\xff\x10\xfc\x85\xc5\ +\xbf\x0d\x97\x4b\x84\x69\x16\x1c\x6f\xbf\xfc\x88\x3f\xd8\x84\xf9\ +\x5d\x9c\x36\x7f\xcf\xb3\x7c\x19\xe5\xf2\xdf\x23\x42\xfb\x2c\x48\ +\xb3\x34\xe2\x3f\x8e\x37\xe1\x1d\xff\x71\xb6\x2b\x93\x38\x45\x9f\ +\x1c\xa3\x3f\xff\x0f\xf3\x81\x44\x5d\x6c\xa3\x45\xbc\x8a\x17\x41\ +\x4e\x64\xbe\xca\xf2\x46\xee\x71\x5a\xc4\x68\x28\x7f\xb8\xc9\xb2\ +\xe4\x2a\xcc\x09\xa9\xcd\x1f\x15\xcd\x32\x89\x12\x0f\x14\xcd\x87\ +\x3f\xe2\xe5\x9d\xd7\x98\x80\x7f\x86\x90\x3e\xa5\x8d\xf0\x33\x0f\ +\x17\x1f\xef\xf2\x6c\x97\x2e\x47\x8b\x2c\xc9\x90\xb0\xf7\xc7\x17\ +\x93\x93\xc9\x4b\x59\x01\x41\x91\x25\xf1\x32\xd8\x9f\x9e\x9e\x9e\ +\x9c\x4d\x21\xde\x83\x80\x42\x78\x75\xfc\x6a\xfc\xea\x84\x7c\x54\ +\x20\xe9\x2e\xf0\xa0\x1e\x01\x98\x4e\xa6\x67\xcf\x2f\x26\x52\x3b\ +\x05\x08\x91\x69\x4d\xf4\x6c\x19\x17\xe1\x3c\x41\x6e\xd4\x81\x7a\ +\xfa\xd1\xc5\xcb\xcb\x8b\xab\x53\x3b\x39\x93\xb3\xe9\xf9\xd9\x95\ +\x86\x1c\x06\x44\x20\x67\x16\xa3\x31\x32\xab\x5a\x1b\x88\x62\x8c\ +\x02\x9d\xd7\x19\x1a\xa4\xb3\x3d\x2b\x8c\xf1\xe5\xf3\xc9\xd5\x15\ +\x6f\x63\xbf\x84\x71\xfa\x47\x9c\x2e\xb3\xfb\xce\x2e\xe3\x06\xc7\ +\xae\x70\xf9\xdf\x5d\x81\xc6\x01\x8e\x32\xc5\x36\x89\xcb\x12\xc5\ +\xa5\x3a\xea\x20\x07\xf9\x11\xc5\x35\x4c\xf7\x01\x1a\x62\x65\xf0\ +\x89\xb6\xf8\xf6\x1b\x4f\x27\xba\xbf\x40\x58\xb2\x4d\xfc\x27\xb2\ +\x9d\xd1\xa7\x0d\x62\xe2\x9e\x30\x31\x88\xad\x37\x32\x9a\x21\x35\ +\x6d\x43\xe4\xdc\xd0\x90\xd7\xc9\x98\x33\x6e\xc0\xf4\x39\xd3\x2a\ +\xb6\xe1\x42\x30\x7d\x36\x16\x26\x8d\x1f\x80\x91\x57\x0a\xd7\x92\ +\x70\x76\xfc\xfc\xe2\xfc\x4a\x4b\x82\x60\x04\x5a\x04\x79\xfc\x67\ +\x86\x82\x69\x52\x61\x41\x6a\x2b\xd7\xb3\xe0\x54\xf0\xb2\xa3\x32\ +\xdb\x52\x6a\xd9\x67\xf3\xac\x44\x9a\x69\x3e\xae\x5d\xea\x2e\x4f\ +\xbe\x7b\x36\x3b\x42\xb3\x8d\xdb\x78\x81\xa6\x23\x47\x78\x06\x72\ +\x94\x2f\x8e\x4a\xe4\x1c\xe7\x61\x7e\xcb\x70\xdf\x22\xd6\xc8\x24\ +\xe9\x70\x9b\xde\x3d\xfb\xde\x42\x28\x6d\x5c\x91\xb9\x8e\xf0\xf4\ +\x42\xa1\x33\x89\x56\xa5\x42\x68\x5e\x35\x6d\x4f\x67\x23\x23\x91\ +\x52\x3c\xae\xb0\xcb\xbf\x89\xb7\x5d\x9d\x37\x06\xd7\x69\x68\x60\ +\xaa\xcb\x78\x3b\xc8\xb8\xa0\x3c\x5a\x3d\x16\xe8\xd5\x91\x94\xde\ +\xac\x82\x87\x6c\x87\xc2\xe8\x06\x99\x33\x71\x11\x95\xb9\xe2\xc9\ +\x32\x9a\x43\x94\x0f\x07\x1c\x58\x34\xdd\xc8\xd0\xec\xe3\x3e\xcb\ +\x3f\xe2\xa9\x45\x96\x06\x95\x31\x14\x84\x98\xc6\xd2\x59\xec\x26\ +\x93\x22\x02\xb9\x1e\x58\x07\x24\x54\xaf\xe2\x2f\x78\xc6\x3c\xcf\ +\x50\x8f\x2f\x41\x2d\x9f\x1a\x86\x12\x8d\x1a\x18\x19\x1e\xad\x98\ +\x22\xdc\x7f\x7f\xfc\x7c\x8a\x66\x7e\x9b\xf0\x21\x48\x23\xe4\x6f\ +\xf1\x94\xa8\x88\x82\xdf\x7e\xbe\xba\x24\x90\x98\x19\x5c\xa3\xd9\ +\xe8\xae\xc0\xb1\xbf\x93\xbc\x3b\x9b\x41\x41\xe8\x40\xe6\x3b\x88\ +\x21\x34\x5c\xfe\xc5\x6b\x62\x0c\x46\x7c\x24\x96\xd7\xf1\x17\x34\ +\x6f\xbc\xde\x3e\x60\x5d\xef\x5f\x8c\x27\xc7\x07\xe4\x7f\x63\xaa\ +\x4a\xa6\xf4\x19\xdc\x75\x7f\x72\x7c\x7a\x10\xdc\xaf\x51\xf0\x0b\ +\x98\x03\xa8\xd0\x16\x41\x3d\x40\xb1\x91\xe0\xe0\x58\x34\x1a\x69\ +\x08\xad\xe2\xa6\x48\x6e\x6d\x38\x52\xcb\xc0\x6a\xe6\xcc\x9f\x82\ +\x9c\x03\x73\x09\xee\xa3\xde\x6c\x74\xb9\xc3\xb1\x24\x28\xf3\x30\ +\x45\x71\x05\x2f\x51\x1e\xb0\x55\xa2\xf5\x22\x5a\x2d\x46\x24\x0a\ +\x57\xdd\x6b\x3b\x46\x7e\xef\xe4\x18\xe2\xf6\x6d\x38\x8f\x6a\x67\ +\xea\xa9\xa9\x06\x77\xc9\x7b\xc2\x17\xeb\x68\xf1\xf1\x0a\xb1\xd1\ +\xcd\xd2\x3a\x0f\x81\x05\xa6\x03\x89\x73\x90\x11\xc0\x98\xf4\x98\ +\x52\xf2\x33\x5c\x3a\x15\x98\xd6\x3a\x65\xeb\x0e\xe6\xcd\x6a\xb5\ +\x57\x21\x77\x2a\xce\x18\x58\xcc\x9d\x72\x13\x07\x4a\xd2\x6c\x85\ +\xd6\xc5\x85\xc1\xd4\x19\xed\xbd\xcc\x8f\x25\xe4\x33\xe4\xa3\xd1\ +\xe8\x64\x13\x26\x30\x20\xd3\xa8\x3d\xa6\x7c\xd5\xb3\x8d\x31\xc8\ +\x4f\x03\x72\xb6\x4b\x89\x56\x29\xa9\xb6\x10\x4e\x4d\xe0\x96\xf5\ +\x93\xa6\x18\x46\x1c\xd5\xa4\xeb\x20\xb0\xb4\x22\xe2\xb6\xb6\xda\ +\xa2\xb5\x63\xc1\x44\x2c\x87\x2e\x7f\x46\x6e\x09\x5a\x2f\x76\x44\ +\x35\xb7\x40\x49\x01\x38\x60\x6d\xa7\x26\x77\x25\xb9\xa8\xc8\x45\ +\x41\x3d\xab\xc7\x57\x39\x1d\x55\xd3\x42\x31\xe8\xb7\x08\x05\x87\ +\x4d\x9c\x86\x28\x96\xfa\xa1\x13\xfa\xfa\xe2\x6a\xcb\xa3\x00\xa4\ +\x35\xa7\x46\x23\x10\x5b\x9a\x4c\x4a\x6c\x29\x18\x4d\x4b\x86\x00\ +\x4b\xc1\x41\xf4\x67\xe4\x80\xb7\x5f\x41\x10\xc5\x81\x60\x3b\x54\ +\x10\x65\x4c\x12\x01\xae\xd0\xca\x6a\x74\x5f\x47\x86\x79\x96\x2c\ +\x75\x33\x2c\x65\xc1\x3d\xca\xc3\x65\xbc\x2b\x94\x30\xa9\xac\x00\ +\x49\x2c\x3d\x83\x97\xaf\x7c\xe8\xa1\x84\xcd\x66\x65\x5c\x26\xf5\ +\x30\x29\x76\x73\xa4\xd0\x32\xcf\x92\x11\x5a\x07\x92\x0d\xbd\x0a\ +\xc4\x8f\xd2\xb7\xdb\xac\x20\x3b\xf0\x68\x86\x94\x6d\x03\x1c\xf9\ +\x48\x8b\x2a\x04\xca\x91\x5c\x0c\x8c\xf4\xd3\x7a\xa9\x2a\x37\x26\ +\xf4\x8f\x60\x4a\x5d\xe2\x2e\xb4\x8a\x6f\xa6\x97\xee\xa1\x19\xc0\ +\x2a\x87\xe6\x1e\x42\x9c\x34\xc6\x8d\x48\xd9\xa8\x35\xb7\xa2\x5e\ +\xc0\xdc\xea\x51\x62\xb5\x99\x84\xa1\x62\x35\x84\xb5\x27\xbd\xb9\ +\x6b\xcd\x45\x67\x2e\x1a\x7b\xc4\xe0\x6d\x42\x3f\x48\xf0\xc6\x41\ +\xe0\x37\xe4\xd6\xb2\xab\x1d\xf2\x4f\x69\x97\x38\xd0\x39\x08\x60\ +\xf7\x9a\xcd\x09\x1d\x83\xc4\x01\x9e\xcf\x9e\xd6\x53\x1e\xab\x27\ +\xc0\x64\xe4\xd5\x58\x65\x03\x1c\x99\xd6\x35\x16\xdf\xb6\xe3\xf1\ +\x83\x3f\x75\x81\xc7\x69\x8d\x49\x98\x9a\xf3\x2a\x68\xb5\x6a\x15\ +\x82\x1c\x9f\xac\x5c\x75\x59\x3a\xc2\x88\x7d\x57\x8f\xc4\xec\xb5\ +\xe1\xc8\x86\x83\x79\x37\x6b\x43\xea\xe2\xac\x0d\xcd\x7e\x4e\x15\ +\xa0\x27\x83\xa0\xe3\xb3\x12\xe5\xe7\xfd\x64\x94\x9a\x30\xa5\xc1\ +\x6a\x8e\x54\x6d\x05\xe0\xa5\x5f\x47\xed\x3a\xea\x76\x58\xcd\xb6\ +\xd0\x2b\xac\xd5\xae\x04\xe8\x43\xdc\x2f\x51\xba\xeb\xbc\x5b\xde\ +\x43\x88\xdb\x20\x3a\x86\xda\x2d\xa7\x3c\xea\xbc\x31\x74\x3a\x3e\ +\x91\x42\x93\x79\x83\xd9\xf5\xec\x5c\x3e\x09\xac\x08\x83\x82\x19\ +\x87\x4f\x3a\x87\xa6\x9d\xf8\x0d\x75\xed\xa6\x30\xc7\x11\xef\x9f\ +\x05\x18\xd2\x49\xb8\xd4\xc1\x0c\xdd\x9c\x6b\xe0\x2e\x81\x8a\x10\ +\x61\x14\xaa\x74\xb4\xc6\x05\x2a\x4a\x5a\x7e\x1e\x6b\xe6\x28\x52\ +\x8a\x08\x26\xb8\x87\x1c\xb6\x5e\xc6\xcb\x60\x83\x45\x34\x45\x58\ +\xde\x5a\x89\x72\x99\x3f\xc0\x09\xe5\xf3\xe9\x78\xfa\xba\xd5\x40\ +\x51\x52\x01\xd8\x4c\x44\x8f\x8e\x3b\x97\xd7\x64\xa8\x54\x90\xa1\ +\xa1\x04\xd1\xcc\xdb\x64\x30\xc1\xff\x90\x5f\xce\xf9\x83\xa1\x22\ +\xca\x3f\x47\x64\x0e\x17\x91\xa3\x25\xc6\x27\x3d\x6b\x15\x4f\x4f\ +\xf1\x40\xe7\x46\x15\x27\x63\x99\x40\x69\x9c\x02\x0a\x70\x15\xa4\ +\x3a\xd8\x9c\x7b\x2e\xe8\x12\x41\xdc\x3f\x19\x1f\x83\xb3\x41\x65\ +\xba\x28\xc0\x12\x27\xa4\x22\xc0\x73\x09\x9e\x32\xfd\x9c\x34\x32\ +\x47\x41\x11\x0d\x95\x45\xb2\x2b\xe2\xcf\x38\xe3\x92\x82\xfd\x29\ +\x20\xf1\x8f\x1c\xe9\x91\x51\xc5\x7d\xf7\x5d\x81\x73\x18\x2f\x89\ +\x62\xc8\xda\x12\x9b\x57\xf9\x8a\x42\xf9\xbe\xd6\x12\x82\x0e\x43\ +\x26\xf1\x35\xa8\xd6\x64\xed\x80\x83\xa2\x98\x09\xbc\xf4\x7e\xdc\ +\xe2\x88\x8d\x4d\xae\x5c\xdb\xd3\x59\x96\x6b\xfb\x47\xd9\xe0\x71\ +\x25\x66\xa8\xad\x1e\x33\xfe\x3e\x0f\x68\x9c\x30\x39\x2a\xd5\x4f\ +\xa5\x8f\xb8\x03\xe4\x46\xc8\x30\x07\x39\x66\xdc\x43\x1d\xe9\x78\ +\x60\x1d\xf4\x70\xc7\x87\x0e\x37\xb3\x81\x0f\x7c\x7c\xfa\x0c\x74\ +\xf4\xa3\xd0\xd0\xda\x17\x9b\x37\x2f\x1c\xd0\x68\xc5\xe2\xe3\x80\ +\xfd\x9d\xef\x30\xbb\x18\x2e\x74\x0d\xb2\x91\xa1\x47\xfc\x98\x7b\ +\x19\x56\x2a\x1c\x94\xed\xae\xea\xa7\xdb\xd4\xb0\xd3\xf4\x18\xfb\ +\x1a\x35\x19\xe4\x0c\x6f\x14\xe6\x79\x76\x2f\x5e\x03\x38\x05\x8f\ +\x00\xc7\xae\x79\xa9\x04\xe2\x2d\x81\xce\xf0\x02\x13\x53\x71\xe6\ +\xca\x16\x90\x97\xf3\x02\x4d\xf7\x17\xe5\x1b\x34\x07\xff\x77\x1c\ +\xb5\xcd\x02\xef\x9e\x9d\x85\xb3\xdd\x86\x3a\x58\x56\x98\x24\xf2\ +\x0f\x13\xe4\x7b\xb1\xe7\x05\x57\x7c\xc6\x5d\x95\x16\xa7\xd0\x95\ +\x29\x28\x94\x7c\x78\x8b\x0c\xee\xd5\x32\x2e\xa5\x5d\x06\x8d\x9a\ +\xae\x17\x79\x96\x24\x97\x79\x14\xb6\x52\x54\x67\x35\x85\x35\x1d\ +\x05\xa1\x03\x2d\x11\xc3\x41\x15\xc6\xb1\xab\x5d\x17\xaa\x37\x4d\ +\xbc\x72\x03\x90\x74\xab\x8c\xde\xd3\x0b\x39\xc1\x92\x5b\xd3\xd5\ +\x29\xca\x28\x52\x8f\xaa\x91\x85\x93\x2b\x49\xbf\xc9\x74\x5a\xf7\ +\xd3\x2c\xe9\x55\x5e\x24\xaf\x03\xa7\xd0\x91\xec\xe1\x6e\xda\xa6\ +\x3f\xc3\xe4\xfc\x36\xb4\xd1\xe3\x25\xff\xfc\x41\x89\xd3\xaf\x20\ +\x4f\x9a\xd0\x31\x58\x9e\x34\xe5\x52\xb9\x5e\xc1\xdc\xb5\x98\x8d\ +\x42\x6c\x90\x7c\xc8\x7e\x69\x6f\xe9\x56\x45\x70\xf4\x89\xb7\x2a\ +\xcc\xc3\x8e\x46\x16\x99\x74\x81\x6c\xd3\x0e\xb6\x9b\xeb\x6c\x88\ +\x9b\xad\xc3\x74\x99\x44\x8a\x10\xdd\x6e\xc2\x78\xc9\x0c\x0f\xf8\ +\x9a\xbf\x73\x47\x5a\x2c\x77\x73\xb8\x4b\x11\x94\x22\xf5\xb3\x5e\ +\xe8\x30\x6f\xe3\x4b\xfb\x69\x2a\x24\xab\x09\x38\xcb\xb6\xf1\x9a\ +\xcd\x46\x9a\x97\xa2\x29\x29\x83\x89\x56\xa4\xce\x4a\x46\x5b\xc9\ +\xa2\xc0\x32\x22\x13\x4c\xd9\x72\xb9\xad\x6a\xfe\x3f\x9e\x6c\x8f\ +\x69\xa0\x3a\x0f\xb5\xce\x07\x35\x09\x6b\x04\x9c\xfc\xb5\x92\xed\ +\xe6\xc2\x27\x5b\x51\x58\x9a\xb1\x94\x0f\x6f\xae\x9f\x9c\x59\x71\ +\xc0\x50\x95\x9e\xd4\xea\x3c\x69\xab\xd2\x65\x76\x9f\xf6\xa7\xd1\ +\xea\x1c\xa9\x07\x2e\x8d\x0a\x65\x8d\x5a\xa9\x13\x73\xfc\x64\x8c\ +\xa2\xc6\xf6\x31\xca\x29\xd5\x5f\xa1\x78\x7d\xd7\x9f\x42\x59\x3e\ +\x69\x57\x2e\x21\x85\x42\xcd\x5a\xa9\x14\x53\xf9\xd4\xac\x0e\x34\ +\x3e\x77\xdb\xfe\x94\x59\x66\xdb\x1e\x18\x34\x6a\xb2\xdb\xd0\xdc\ +\x6d\x9f\x86\xc7\xdd\xb6\xda\x39\xe1\x0c\x51\xe4\x0f\xfb\x0c\xa5\ +\x89\x9a\x8e\x20\xde\xf1\x03\xe0\x53\xf1\x68\xa1\xeb\xa6\x45\x7a\ +\xd8\xd8\x2b\x6e\xb1\x70\x75\xb4\x63\xdd\x48\x0d\x5a\x40\x87\x29\ +\x67\xb0\xdd\xe8\x26\x57\x97\xa3\x2f\x25\xd9\x91\xe8\xb6\xe4\xe9\ +\xba\x16\xa3\x55\x36\x46\x55\xc5\x80\x41\x8a\x88\x34\xbc\x3a\xac\ +\x73\xb4\xfb\x40\xea\x4a\xcb\x30\x1d\xae\x14\x48\xf1\xfa\x4d\x25\ +\x59\x2f\x5d\xa1\x07\xf8\xd2\xb5\x88\x1b\xab\xf8\x7d\x12\xc6\x69\ +\x77\x3d\x0f\xa2\x12\x91\xb6\x47\xd6\x8b\x80\xdc\x4f\x39\x62\xd7\ +\xae\x1a\xba\x8e\xff\x8c\x7e\xce\x3b\x17\x10\xe8\xbe\x21\x82\xe8\ +\xb8\xcb\x07\x2a\x20\xc0\x98\x54\x84\x24\x27\x76\x59\xf3\x2e\x6c\ +\xe1\xab\x2a\x0f\x72\x8b\x59\x51\xb3\x0e\xaf\xcb\x10\xef\xdf\x77\ +\xad\xb7\x33\xd4\xdd\x7a\x8e\xb6\xbf\xc0\x0d\x4a\x97\xad\x0d\x38\ +\x67\x50\xa8\x57\xf1\x35\x24\x5e\xd6\x55\x36\x06\xab\x57\xe1\x98\ +\x78\x59\x3b\x10\x9a\x75\x07\xa7\x5b\x32\x3d\xd0\x94\x2f\xf8\xca\ +\x1a\xcb\x9f\xe7\xcb\xba\xd4\xb4\x48\x7b\xa5\x5c\x81\x83\xe7\x13\ +\xe5\x8a\xbd\x4a\xa8\x08\x4b\xb7\x2f\x26\x6f\xd0\xb9\x56\x3a\xc1\ +\x5b\xde\xda\x22\x27\x0a\x56\xb8\x10\x4b\x3b\xa4\x9a\x0a\x30\x0c\ +\xa5\xb5\x4e\x8d\x37\x5a\x7b\x55\x17\x08\x7b\x4f\x3c\x5b\x4b\xdf\ +\x10\xd4\x24\xb9\x6b\xff\x53\x79\x4b\xbb\xa1\x58\x73\x3b\x07\xaf\ +\xc9\x68\xcb\x10\xe9\x02\x66\x9b\x7d\x16\xf5\x70\x6a\x1b\xa7\x1d\ +\xee\xa8\x0e\x7b\x92\x54\xd3\xe6\x30\x9f\x30\x7b\x53\xb8\x92\xcd\ +\x4d\x55\xb7\x11\x0f\xdd\xf1\xf1\xc9\x41\x30\x1e\x8f\xc5\xd3\x24\ +\xf1\x92\xa5\x53\x0f\xb9\x90\x92\x78\x3e\x2c\x5f\x62\x92\xae\x88\ +\xea\x4f\xbb\xb8\xad\x64\x7c\xf2\x5c\x1f\x6d\x2d\xe9\x81\xd6\xf8\ +\xf8\x82\xcb\x07\x94\xc4\x87\xd7\x49\xb0\xc5\x51\x41\x0a\xb9\xa3\ +\x7c\xb1\x2b\x75\xb5\x57\x91\x68\x5c\x28\x72\x7b\x72\x35\x43\xf5\ +\xe1\xb8\x69\x0f\x1f\x70\xda\x6a\x23\x04\x9c\xc0\x62\x12\x3a\x56\ +\x41\x40\x0d\xd8\xe1\x86\x66\xc9\x2b\xa5\x71\x8f\xc6\xc0\xe1\x2f\ +\x15\x26\x5b\x75\x1e\x28\x63\x88\x5b\x91\xd2\x08\x61\x6c\x94\xad\ +\x56\x6e\x79\x2a\x2e\x7b\x16\x52\xb2\xeb\xb9\x0b\x0b\xfc\xd6\xbc\ +\xf7\x56\x02\x0c\x9b\x2c\xba\x1f\xcd\xda\x2a\x8d\xb5\x32\x38\x32\ +\xb4\x9f\xd2\xda\xaa\x7b\xe0\x46\x53\x6b\x76\x30\x20\x3b\xe2\xf6\ +\x37\x4c\xe6\xc6\x35\xf3\x34\x38\xdb\x26\xb6\x8f\xc9\x09\x5b\x3d\ +\x9e\x46\x27\x6c\x2d\xc3\xf0\xf9\x33\x26\xc3\xed\x17\xfb\x79\x7f\ +\x0d\xcf\x6b\x11\x29\x77\xee\xb8\x8c\xec\x35\x96\x22\x78\x2f\xdf\ +\x5c\xbf\x7f\x7b\xf9\x3f\xd7\x5d\x01\x53\x78\xbd\x10\xc7\xc1\xab\ +\xab\x57\x75\x86\xd7\x79\x19\xb3\xca\xc3\xcd\x20\x15\x94\xf9\xfa\ +\x5c\xbd\xd4\x5d\x15\x5d\x89\x61\x92\x58\x19\x28\x41\xef\x75\x85\ +\xd9\xed\xde\x8e\x9a\xfc\x82\xb7\x52\xae\xd0\x98\x2d\xa2\x4e\xab\ +\xd2\xbf\x4b\xca\x13\xcf\xee\x10\x93\x54\xc3\x81\x3b\x87\xba\x95\ +\x66\xcd\x34\x28\x57\xd7\xad\x34\xd0\xe3\x0b\xfe\xb3\x3d\xe8\x43\ +\xea\x1d\xa5\x8f\xc1\x44\x53\xed\x9e\x5f\x55\x5e\x27\xdc\xae\xe3\ +\x45\xd1\x21\x03\x12\xff\x0c\x62\x18\x02\x6d\x8f\x6c\x19\x3c\xee\ +\x27\x33\x0d\x81\x88\xa6\x46\x08\xf7\xe1\x1e\xf8\x29\x67\x1d\xc2\ +\xe7\xfe\xe6\xf1\x22\x4c\xa2\x14\x4d\x24\x3a\x6e\x10\x0e\x62\x1e\ +\x12\x6d\x56\xa6\x8c\xa2\x16\x81\xf5\x50\x08\x90\xc4\xe4\x17\x2f\ +\xdf\xed\x36\xf3\x6e\x6e\x7c\x20\xe9\x35\xb4\x79\xb0\x28\x87\x44\ +\x0a\xa3\x27\x79\xbd\xc7\x2f\x45\x20\x13\xed\xb8\x1d\xdb\x39\xf0\ +\x6d\x6b\x3a\x86\xda\x8e\xe5\xf9\x7c\x34\xbf\x16\x04\x25\x8a\x14\ +\xa3\x30\x89\xef\xd0\x64\x67\x81\x16\x8e\x64\x51\x58\x1f\xe1\x34\ +\x14\x3d\x81\xb7\x73\x26\x6d\xb6\x58\xef\xd2\x8f\x2e\x69\x70\x5a\ +\x5a\xc1\xd1\xaf\xe2\xb0\x4b\x81\xab\x77\xef\xe5\xd5\x07\x98\xfc\ +\x5f\xfd\x7e\x73\xf3\xeb\xbb\xce\x6b\x93\xe1\x16\x27\xef\x77\xc5\ +\xba\x7b\xf9\xa6\x1e\x06\x36\xa2\x63\xc0\xf2\x4d\x1c\x9b\x3a\xab\ +\x69\x35\x70\x95\x25\x8b\x63\xd9\xa1\x86\x1e\xbb\x39\xb7\x1a\xb6\ +\x60\xdd\x7e\x0e\xab\x78\xb5\xcb\x21\x91\xd6\x9f\x75\x1d\x4e\x3b\ +\xc7\x40\x4d\x02\x6f\x8e\x3d\xe8\x31\x6c\x68\x30\x4a\x94\xce\xe6\ +\xb4\xdf\xd3\xe9\xd9\xf9\xf3\x4b\x53\x84\xe6\x40\xd9\xca\x0c\xe8\ +\x89\x70\xa1\xdc\x85\x82\x19\xae\x95\x31\x92\xaa\x0d\x00\x1b\x96\ +\xb5\x8c\xbd\x76\x2c\xd5\xd2\x95\x2f\xe3\x30\xc9\xee\x2a\xd4\xa4\ +\xc6\xb3\x3c\x3a\x71\x19\xfe\xa2\xd8\x45\x38\x48\x4c\xf1\x75\x96\ +\xf3\x60\x14\x5c\xe3\xdc\x9b\x30\x09\x16\x61\x11\x05\xd9\x4a\xe8\ +\x55\xbf\x70\xb3\x24\x80\x8b\xaa\x5e\x79\x5d\x61\xfc\xf7\x37\xf5\ +\x11\x06\x9f\xae\x2e\x55\x2c\x69\x8e\xb2\x9e\xd6\x09\x92\x43\xb4\ +\xe1\x9c\x20\xc7\xe6\x13\x3b\xc1\xfa\xb4\x29\xe2\x8c\xa8\x40\x0a\ +\x4b\xb2\x7b\xf2\x22\xd8\x0e\x8f\x86\x2c\x4d\x1e\xe8\x2b\x2d\x2f\ +\xa3\x24\x7c\x88\x96\xef\xb3\xed\x6e\x8b\x9f\x02\x8b\x9a\xda\x13\ +\x1e\x50\x48\x25\x1d\xc2\xbf\x1d\x50\x0d\x27\x2e\x54\x30\x6f\xd2\ +\xa2\x0c\xd3\xb2\x82\x81\x0c\x0d\x26\x4e\x3e\x24\x7d\x4c\x3f\xcf\ +\x61\x7d\x34\x3f\xaf\xe2\x7c\x5a\x3f\x0f\xd0\xd3\xd5\x65\x03\x20\ +\x3d\x5d\x37\x00\xa1\x93\x0b\xe7\xe0\xf5\xc8\x5c\x7b\xa6\x7a\x62\ +\xe6\x3f\x5b\x3c\x96\x7e\x41\x43\xe9\xa7\x67\xc7\xcf\xfe\x97\x05\ +\x85\x5f\xf1\x28\x5c\xc9\x43\x4e\x3c\xa1\x16\x5e\xd0\x31\x01\x1e\ +\x43\x80\x65\x17\x01\xc3\x3e\x76\x01\x5e\x07\x55\xe1\xb0\x10\x9a\ +\x0a\xba\x01\x80\x8e\x80\xe4\x87\xe2\x1c\x8e\x05\xf9\xa3\x3c\x13\ +\xfa\x09\x24\x1c\xc1\xf1\x79\x48\x1d\x90\x84\x26\x5d\x4c\x19\xec\ +\xf2\xe1\xa2\x63\xa1\x51\x0d\x6e\xd7\x73\x34\x33\x10\xc8\x9d\xf8\ +\x03\x93\x26\x5b\x9d\x6e\xa1\x80\x27\x95\x41\x40\x8e\x60\x8f\x69\ +\xb8\x25\xb5\x95\x50\x70\x0a\x83\x62\x1d\xaf\x4a\x7e\x8e\x44\x90\ +\xd7\x1a\xad\x8c\x68\xc4\x65\x85\x5c\x93\xe6\x71\x89\x7a\xce\xd1\ +\xbf\x60\x70\xab\x78\xe2\x0a\x09\xf4\xcf\x8f\x09\x67\xbb\x43\x57\ +\x5d\x61\xfb\x17\xd9\x66\x13\xa6\xcb\xb7\x71\xfa\xb1\xcb\xac\x70\ +\x98\xad\x55\x85\x36\x8d\x97\xd6\x95\x21\xec\xba\x55\x65\x79\xdc\ +\xb2\xde\xb3\x95\xa9\xb4\xce\x05\x64\x72\xb5\x5b\x91\xbd\x8a\x13\ +\x2f\x34\xde\xbd\xff\xfd\xe6\x1a\xad\x2f\xde\xfd\x1a\xbc\x7e\xf3\ +\xea\xed\xcb\x96\x9b\x35\x83\xed\xd0\xbc\xc0\x55\x28\xbe\x82\x67\ +\x16\x06\xad\x86\xc1\x98\xd4\xb9\x53\xfb\xb5\x68\xd7\x17\x39\xbd\ +\x52\xd6\x90\x02\x84\x6f\x82\x9f\x82\x93\xb3\x1f\x83\x69\xf0\xcf\ +\x60\x7c\xf6\xc3\x24\xc0\xcf\xfc\xb2\xfb\xf9\x01\x4e\x4c\x6f\x16\ +\x14\xd5\x3b\xca\x24\x89\x0d\x97\x40\x64\xc5\x19\x4e\x2e\x9a\x36\ +\x75\x66\x2d\xc9\xb6\xdb\x6f\xd2\xed\xf8\xfb\xbf\xe3\xc3\xd3\x68\ +\x23\x13\xc3\x32\xf7\xf0\xa3\xca\x72\xba\xdc\xfe\xf8\x64\xd2\xa0\ +\x80\x52\xf7\x2c\x5d\xb8\xa5\xf2\xf3\x53\x8a\x44\xed\x72\xcc\x31\ +\xf2\x2e\x8a\x96\xd5\x77\x75\x59\x8a\x26\xbe\x8d\x44\x0c\xcc\x43\ +\x54\x0a\xd7\x14\x42\xf1\x32\x81\x3a\x73\xc9\xb8\x1f\xee\x66\x1e\ +\x36\xe2\x2c\xd3\x6c\xfb\xc1\x8c\x01\x74\x97\xbc\x1a\x13\x5c\x56\ +\x53\x06\x00\x2c\x15\x5b\xa0\x50\x7a\x79\x6e\x8b\xc2\xf2\x9a\x27\ +\xb1\x5e\x5e\x29\x4a\xac\x17\x8d\x87\x6d\xb4\x6d\xaf\xff\xee\x68\ +\x76\x72\x2c\x33\x11\xa3\x89\x7b\x7a\x10\x9a\x06\x1d\x86\x20\x5f\ +\x8d\xaa\x8d\xad\x70\xa5\x61\x9b\xa7\x03\x99\xb7\x3b\x9f\x1c\xe0\ +\x7f\x4f\x03\x34\x1f\x08\x7e\xf9\x0d\xff\x7e\x4e\xbd\xc6\x3f\xc4\ +\xed\x89\xe6\x07\xbe\xb4\x50\xfd\x10\xec\xf4\x8f\x7f\x48\xa3\xa6\ +\xf9\x51\x53\x7c\x64\x91\x31\x70\xf4\x57\x50\x34\xb8\x0e\x6c\x2b\ +\xa9\x2c\xf3\x6c\x3b\xc2\xd3\xcc\xf6\xbb\xa9\x62\xb6\x31\xbc\x16\ +\x32\xac\xfa\x14\x8a\x58\x92\xe2\x23\xa5\x49\x42\xa8\xd1\x10\x3d\ +\x08\xe0\x6f\xd8\xab\x56\xd0\x97\x9c\x3f\x68\x9b\x56\x49\xae\x55\ +\x21\x11\x75\x3d\xf5\x1f\xf5\x71\x87\x8d\xd0\x31\xcc\xed\x2c\x02\ +\x5a\xeb\xc2\x81\x12\x3b\x55\x07\xdb\x7b\x21\x75\xb3\x19\x02\x83\ +\x14\x65\xbc\x18\x6c\xb9\xea\xc5\x7d\x4b\xad\x68\x0a\xae\x26\x8c\ +\x47\xc3\x12\x3d\xfa\xcb\xc4\xee\xd4\xd4\x36\xdc\x81\x18\xe5\xea\ +\xb3\x39\x9a\x3f\x3e\x39\x26\xbb\x60\x07\xe7\x22\x10\xa7\xbb\xe0\ +\xee\x5c\xf5\xa0\x72\x80\xa2\x16\x7c\x59\x4b\x36\xc1\x8f\xdc\x18\ +\x75\x45\xbd\xa1\xec\x1d\x29\x93\xa3\x73\xb5\xa6\x83\x89\x53\xc7\ +\x52\x4e\x56\xf9\x4b\x73\x1e\x3d\x78\xbf\x3a\x42\x22\x18\x83\xcd\ +\xf7\x2d\xc7\x63\x22\x49\x4f\x29\x9a\x6b\x36\x75\x94\x61\xab\x4a\ +\x4c\x24\x17\x8d\x56\x5b\xec\xe6\xfc\x3b\x87\x24\xbc\x8f\x1a\x21\ +\x3a\x86\x49\x6a\x13\x4a\x4a\x9a\x17\x14\xc6\xeb\x69\x0d\x24\x3c\ +\xbf\x74\xbd\xa7\xe6\xd7\xdb\xe7\x36\x1b\x91\xed\xac\xd2\xae\x83\ +\x79\x6b\x36\x2f\x74\x69\x7c\x35\xb5\x7d\xac\xc7\x18\xac\xae\x97\ +\x49\x18\x20\x2f\x57\xc1\x7a\xe9\x96\xb9\xa6\x5c\x31\x35\xfd\xf5\ +\x26\x9c\xff\x11\x77\xba\x19\x4f\x7e\xba\x1f\xd9\x87\xf3\xaa\x16\ +\xc8\x08\x79\x01\xf2\xe7\x60\x37\xc5\x31\xc7\x86\x0b\xf7\xc6\x25\ +\xaf\x7c\x3b\x9b\xc1\x12\x9e\x61\xe3\x36\xa4\xce\xe9\xde\x8e\x29\ +\x3f\x9e\x42\x99\xcd\xb6\x61\x1a\x69\x2d\xc1\xa1\xa4\xa1\x34\x05\ +\x60\x84\x2c\xb3\x1d\x32\xfb\xba\x1b\x4d\xf3\x20\xc8\xee\xe3\x72\ +\x1d\x6c\x1f\x3e\x95\xa7\xf0\x1b\xf4\x20\x89\x76\xe3\x33\x4f\x15\ +\xc5\x08\x50\xdb\x61\x0f\x25\x0a\xfe\x66\x76\x88\x38\x46\xcb\xb4\ +\x97\xd9\xe2\x23\xb5\xa2\x5a\x0c\x44\xaa\x38\x49\x77\x8b\x82\xe1\ +\xc3\x68\x99\x87\xf7\x57\x61\x11\x49\x77\x0b\x6d\xda\xd7\xd6\x92\ +\x60\x67\x59\x95\x83\x26\x5b\x93\x74\xb7\x01\x67\x66\x54\x5b\xb4\ +\xf3\x07\xfc\x4d\x30\x62\x1b\x96\xf8\xa4\x0b\xbb\x7b\xee\xe4\x8a\ +\x90\x3b\x9b\x2d\x92\xac\x88\xea\x73\x3d\x90\x23\xb1\x89\x68\xe1\ +\xe2\x75\xc8\x63\x91\x74\xca\x9b\x63\x0d\x10\x82\x45\xbe\x60\x0f\ +\x50\xc0\xd6\xc8\x36\x52\x7d\x4e\xc4\x78\x1a\xc0\x9a\xe5\x20\x82\ +\x3a\x4b\xc0\x85\x16\xaf\x97\x08\x04\x6a\xea\x9e\x1a\x7a\x90\x95\ +\x6b\xd0\xa3\x6f\x98\x4b\xdb\x63\x83\x1e\x6f\x41\xb1\x48\xea\x67\ +\xf6\x04\x12\x03\xd4\x65\x00\x29\x2c\xcc\xf0\x3c\x87\x82\xe6\xef\ +\xba\x6a\x18\x83\xdb\xf3\xb6\xc9\xa6\x3f\x27\x8d\xeb\xb2\x24\x45\ +\xbb\x84\x0c\x46\x40\x0d\xde\x87\x66\x5d\x17\x81\x6c\x32\xe1\x1b\ +\x88\x66\xe2\x32\x7c\x28\x86\x3b\x08\xf4\xd6\x33\xc2\x81\x28\xae\ +\xa0\xfb\x90\xac\xe9\x21\xd0\x5c\xb9\xce\x81\x48\xc6\x0a\xdc\xf3\ +\x35\x65\xb5\x83\xcd\x96\x2d\x8f\xd1\x5a\x6b\x4a\x03\x86\xe9\x45\ +\xb5\xb6\x8f\xd1\x9a\xfb\xa4\x9a\x68\xd1\x8b\x66\x4d\x0f\x8b\x3d\ +\xf7\x49\x73\x05\xdd\x8b\x68\x5d\x17\xb3\x45\xf7\x49\xb4\x60\xa0\ +\xae\x86\x0c\xda\xef\x04\x24\x50\x7d\xee\xde\x6e\xa2\x1e\x96\xa9\ +\x1a\xa4\x91\x0c\x71\xd9\x6c\x33\x3b\x67\x6b\x03\xd4\x65\x24\x03\ +\xca\x26\xd3\x5b\x85\xbb\xfd\x40\xc6\x6e\x24\x84\x7f\xd7\x19\xb4\ +\x0d\xb3\x45\xb8\xac\x32\xc0\x17\xa4\xbd\x36\x22\xc0\xed\x12\xdd\ +\x46\x88\x54\x69\xc7\xec\x67\x1d\x8a\x86\x48\xbb\x21\xf8\xfb\xea\ +\x51\x19\xcd\x82\x11\x9c\xc4\x38\xce\x75\x5c\xb2\x5b\x0d\x13\xa0\ +\xd3\x8b\xcb\x57\x17\xc3\x31\xd3\x78\x29\xd3\x1c\x5d\xd3\xda\xbe\ +\x8b\x62\x8c\x87\x4d\x23\xb6\x72\x2e\xb6\x0f\xb8\x35\x5a\x2f\x1f\ +\x55\xbf\xee\x5f\x3c\x3f\x3b\x23\x53\xe0\xfd\xc9\xf4\x04\xdc\xf1\ +\x3a\x81\x0d\xed\xc4\xe8\x97\xac\xde\xc8\x18\x14\xcd\xcf\xd3\x3e\ +\xdd\x38\x31\x94\xc1\x99\x82\x4d\x20\x43\x01\x86\x9b\x75\x32\xed\ +\x3e\x87\xf6\x18\x0e\xca\xc4\x5a\x19\x0b\xdd\x18\x75\x98\x56\xd9\ +\x06\x05\xdc\xc1\x63\x5c\x28\xd3\xad\xa7\x19\x14\xb8\x93\x25\x30\ +\x7a\x84\x05\xd0\x56\xe1\x31\x20\x04\x4d\xc9\xda\xe5\x21\x20\xde\ +\xca\x72\x76\x88\x26\x23\xe1\x53\xd6\x74\xa6\x2e\x2c\xa9\x5c\x97\ +\x5e\x1e\x66\x0e\xac\xc7\xa8\xa1\x5b\xa7\xd0\x36\xfb\x84\x9a\x7b\ +\x58\x27\x30\xb5\x06\xec\x73\x19\xaf\x56\x11\xa9\x1c\x36\x8f\xd6\ +\xe1\xe7\x38\xcb\x71\xd5\x4d\x96\x15\x28\xcc\x8e\xe4\xd7\xb8\xeb\ +\x8f\x85\x92\x5b\xca\x5c\xc8\x36\x57\xfa\xaa\x4d\x13\x76\xb1\xae\ +\x6e\xd8\x66\x9c\xe2\xe2\xd9\x79\x95\xed\x61\x9e\xea\xd2\x5b\x6f\ +\x9d\xf2\xca\xc7\x66\x9e\x60\x7b\x0f\xfb\x54\x17\x51\x6d\xcd\xb3\ +\x82\x24\x5b\x27\xff\x29\xcf\x2d\x7f\xf9\x12\xde\x53\x56\xae\x2d\ +\x72\xa7\x14\x27\x67\x0e\x05\x69\xdd\x1e\x1e\x04\xd0\x19\xb7\x38\ +\xa1\x86\xf6\xd1\x63\x43\x65\xd0\xb3\xbe\xb9\xf3\x1d\x14\x15\x0e\ +\x71\x6b\x75\x86\x55\x94\xea\x97\xe3\xb6\x4e\x3e\x89\x59\xc2\xbb\ +\x1b\x4e\x94\x19\x77\x0a\xac\xbd\x7c\x69\xd3\x3d\x99\x09\xa1\xe3\ +\x1e\xd0\xf4\x90\x1f\xd0\xcb\x87\x48\xa0\xe4\xad\x15\x8d\x87\x08\ +\xa1\x6e\xde\xe4\x69\x84\x88\x8f\xcc\x2a\xfc\x9d\xcf\x6e\x07\x39\ +\xdc\xe2\x64\x43\x38\x66\xd7\xcb\x34\xc7\x99\xfd\xbf\xfd\x58\xc6\ +\x65\x12\xcd\xc3\x7c\x54\x9d\xa0\x60\x01\x9b\xaa\x35\x37\x39\xad\ +\x5c\x6a\x26\x83\x91\x66\xf9\x26\x4c\xda\x00\xa9\x6f\xea\x33\x71\ +\xa0\x28\x83\x81\x32\x0f\x7c\x55\xdd\x1c\x23\x37\x1e\xf0\xf9\x5a\ +\xf5\x2d\xbe\x04\x21\x9d\xc6\xd2\xe9\x33\xab\x38\x2e\x3f\x7c\xd0\ +\x64\x57\x5b\xfd\x26\x4f\x8e\x7a\x2e\x87\x99\x1a\x61\x82\x4c\xf7\ +\x05\x4d\x05\xfd\x39\x02\x6a\x4b\xd7\x5d\xa2\x32\x1e\xfd\x55\x7f\ +\x76\x38\xf8\xd3\xb1\xd9\xeb\x99\x9e\x16\x49\xdf\x87\x75\x3c\xa2\ +\x55\x92\x85\xe5\xdf\x5f\x69\x08\x19\x62\xca\x91\xcf\x16\x5a\xab\ +\xe0\x5b\xd5\x26\x60\x69\xa3\xb6\x1a\x0f\xa8\x37\x92\xdc\x90\x47\ +\x11\x7d\x11\xb8\x28\xab\xdf\x6e\xb0\x57\xf7\xab\x49\xd8\x3d\xb9\ +\x01\xd1\xf1\x19\xa1\xec\x9c\xe0\x56\x94\x3d\x80\x29\xb1\x04\x2a\ +\x38\x43\xa4\x57\xd4\x32\x9f\xcd\x91\x19\x2f\xd6\x42\x3d\x49\xe9\ +\x2b\x4d\x16\x63\x0b\x3f\xaf\x40\x0e\x0b\x34\x28\xe7\x28\xf4\xdd\ +\x15\xb3\xbd\x70\xf9\xdf\x2c\x4e\x8b\x51\x73\xcf\xa3\x8e\x5d\x36\ +\x33\xab\xa0\xdd\xe2\x08\x5a\x21\xe4\xef\x9d\x9b\x50\x76\xc5\xb8\ +\xc9\x72\x3b\xc6\x3d\x8c\x72\xb1\x8e\x93\x25\x92\x48\xf5\x57\x6f\ +\x04\x44\xe9\xd2\x89\x63\x0d\x7a\xe2\x4f\x21\x95\x57\x5f\x88\x5d\ +\xf9\x9e\x10\xad\xce\x0f\xc7\xd7\xb4\x57\x38\x2c\x16\x92\x6d\x6b\ +\xcc\x30\x07\x00\xe9\x6a\x8f\xbe\x09\xc7\x18\x1c\x0c\xdb\x28\xf3\ +\xa6\xd0\xab\xa7\xe4\x7d\xdc\xbc\x20\x68\x38\xe3\xc6\x4f\xdc\x5a\ +\xaa\xcd\x42\x6f\x41\x33\x06\x68\xa6\x98\xbb\x4d\x56\xdf\xee\x3a\ +\x20\xe9\x9f\x55\x00\xd1\x7c\xcd\xa2\x8a\xe6\xfb\x17\x59\xb2\xdb\ +\xa4\x9a\x06\x6e\x0c\x90\xc6\xf3\xec\xcb\x6d\xdd\xcb\x9d\x7e\x55\ +\xba\x40\x1b\x22\x13\x4b\x1b\xba\x9f\x60\x96\x47\x8d\xce\xd2\xa8\ +\xc2\x67\x69\xc4\x21\x34\x49\xb8\xc1\x68\x6c\xc5\x50\x1a\x5b\x71\ +\x38\x8d\x5a\x6b\x90\x9a\x9b\x31\xac\xe6\x66\x5e\xf3\x1f\xd9\x16\ +\x9c\x2d\x7a\x97\x5a\x6c\x5a\x68\x00\xca\x49\x68\x01\xf3\xc4\x9a\ +\x78\x72\xc3\xfa\xf9\x70\x62\xb4\xee\xa6\x95\xc9\xbe\x9b\x56\x16\ +\x0b\x97\x91\x5a\x9b\x19\xad\x1c\x44\x6b\x96\xb9\xc5\xd2\x01\xc4\ +\x96\x76\x56\x6b\x07\x50\xdb\x1a\x5a\x2c\x5e\x41\xde\xd6\x4a\x9c\ +\xad\x1e\xfd\x16\xa1\xd5\xfe\x26\xc6\x77\x60\x75\xda\x50\x1a\x81\ +\x92\x53\x5a\xc1\x3c\x0a\xcd\x3c\xf9\x13\xfa\xfa\x72\x67\x1c\x0d\ +\x62\x4b\xd3\x88\x10\x5b\x5a\x46\x05\x44\x80\x53\x53\xe3\xe8\xd0\ +\x92\x60\xd7\x8b\x65\x94\x68\x88\x70\x68\x6b\x1d\x2d\x1a\x32\x5c\ +\x1a\x5b\x46\x0d\x48\x48\x17\xcb\x32\x8e\x1e\x5e\x29\x82\x6c\x44\ +\x02\x5d\xae\xf3\x78\x17\xee\xb9\xcb\xe3\x25\x5e\x72\x19\xde\x10\ +\x04\x4f\xef\xa9\x19\xb3\xad\x62\xde\xb0\xf8\x0f\x1b\x45\xf3\x9f\ +\x72\x62\xef\xe1\xb6\x12\xa3\x86\xad\x7f\x79\x6a\xf8\x0f\x1b\x6a\ +\xf8\x4f\x39\x6a\xba\x5f\x38\x6a\xa8\x51\x47\x1c\x60\xfe\x90\x25\ +\xfa\xbd\xa9\xdb\x78\x14\x5c\x7e\x00\x76\x1f\xd2\x37\xfc\xe8\x93\ +\xbe\x12\x06\x04\xf7\x9d\x5d\x20\x20\x39\xec\x8c\x31\x5c\x94\xf1\ +\x67\x39\x1e\x68\x5a\xc8\xe4\x01\x4d\x14\x32\xa5\x36\x5d\xc9\xdd\ +\xb3\xd3\xbb\xe7\x40\xf0\x9e\x0b\xc5\x7b\x3c\xc9\x50\x71\x2d\x80\ +\x8b\xe7\xd3\xf1\xf4\xb5\x8e\x0b\xf9\x24\x58\x65\x02\x68\x21\xf3\ +\x00\x34\x51\x58\x00\x8f\x90\xd9\x31\xc8\xb1\xce\xe9\x38\x30\x84\ +\x89\x79\x91\xe5\x69\x94\xd3\x93\xa6\xa2\xba\xb0\xe6\xeb\x05\x85\ +\x17\xd6\x0c\x55\x81\xc4\x22\xbf\xff\x8a\x42\xf4\x6d\xc7\xd7\x54\ +\x7a\xd8\xcc\x5c\x13\x3a\x06\xdb\x3f\xe4\xd8\xb4\x9e\x46\x73\x7b\ +\xe3\x06\xb1\x4a\x7b\xe4\xe2\x06\xba\xb6\xae\x64\x43\x87\x57\xe5\ +\x5b\xbb\x9e\x15\xf0\x56\x33\xf2\xaa\x73\x57\xb1\xc5\xbf\x7a\x80\ +\xcf\x84\xc9\x87\xa4\x2a\x4d\x7d\x56\xc1\xa7\x7f\x01\xb4\xcc\x94\ +\xaa\x02\x42\xd2\x8b\x70\xf8\xc0\x52\x5e\xc4\x4f\x7d\x2e\x21\x2b\ +\x35\x60\xa4\x8c\x76\x0b\x85\xb3\xd9\x2a\xce\x0b\x9c\x1c\x64\x6d\ +\x88\x0b\x21\x8f\x32\xf1\xb2\xa7\xb5\x04\x8d\x0d\xaa\x68\x20\x9a\ +\x19\x01\x08\x44\xac\x38\x30\xa8\x8c\xe5\x17\x15\x5d\x44\xcc\x6a\ +\x02\x98\x05\xdc\x34\x03\xc5\xab\x7d\xcb\xd1\x05\xb3\xb7\x6c\xe5\ +\x2a\x41\xe4\xea\x7c\x56\x44\x41\x11\x95\x25\xd9\xaa\xfd\xae\xa2\ +\xeb\x88\x64\xd1\x1c\x55\xc9\x35\x47\xf2\xb8\xfb\x1e\x53\x8b\x22\ +\xe0\x7c\x77\xd7\x5c\xa0\xe3\x47\x74\x85\xa2\xe9\x46\xb2\x30\xb9\ +\x0a\x7a\x6e\x7e\x82\xed\x11\x5b\x72\x7c\x3c\x53\xd4\x5a\xbf\xdc\ +\xc8\x4b\x92\xbe\x43\xea\xe3\xf7\x9e\x94\x1f\xf9\xf9\x53\x56\x1b\ +\xff\xe9\xab\x4f\x92\xd2\xf8\x03\x15\x9f\xa4\x2c\xf2\x3e\x44\x2e\ +\x47\xa3\xfe\xad\x1f\x90\x35\x3c\x69\xe1\xa1\x05\x3c\xd1\x27\x6c\ +\xd5\x80\x9a\xeb\xac\xc3\x3c\x47\xd4\xf1\x22\x04\x47\xa5\x9b\xbb\ +\x11\x7a\x58\x97\x67\x6a\x89\x7a\xe0\x4a\x95\x41\x72\xda\x0b\x91\ +\x0e\x03\x12\x42\x25\x55\x13\x12\x50\xc9\x57\x8d\x5a\xa2\xd0\x18\ +\x94\x88\xc2\x63\x99\x0d\x80\x51\x32\x07\x9b\x5e\xda\x2b\x27\x13\ +\xfd\x8a\xb5\x1e\x42\x1f\xae\x49\x31\xd4\xcb\x3c\x0a\x59\x69\x09\ +\xa1\xc4\x84\x7d\x78\xd9\xd8\xc0\x4e\xe9\x35\x7e\xca\xf4\xeb\x79\ +\x52\x55\x03\xa3\xfa\xba\xea\x36\xc2\x45\x11\x9c\x5a\x2e\xa3\x32\ +\x8c\x93\xa2\x69\x5b\x94\x48\x24\x58\x5b\xab\x24\xbb\x3f\x5c\x64\ +\x9b\xa3\x4f\xbb\xa8\xc0\x61\xbe\x38\x1a\x4f\x4f\xcf\xc7\xd3\x8b\ +\x73\x0c\x86\x23\x79\x95\xe5\xa3\x35\xd9\x03\xfa\xdc\xec\x04\x0d\ +\xe1\x3b\x91\x32\xbe\x5b\x66\xe5\xf7\xc1\x61\xad\x93\xba\xd0\xe4\ +\x74\x8c\xeb\xd9\x4e\xce\xc8\xbf\xd5\xbd\x0a\xda\x82\x37\x39\xd8\ +\xdf\xe8\x1c\x18\xae\x71\x99\x05\x44\x54\xcd\x94\xe2\x5f\xb8\xb0\ +\x0c\xf4\x27\x31\x96\x1a\xe9\x7f\x48\xa7\xeb\x75\xb8\xe5\x5f\x14\ +\x70\x20\xc2\xb0\x04\x81\x40\x4f\x29\xe8\x4d\xf8\x85\x25\x9c\x3b\ +\xa4\x35\x69\x12\xde\x20\x14\xa7\x3c\x8a\x7a\x4e\xd0\x1e\x03\x29\ +\x89\xb8\x4d\x62\x92\xcc\xd7\xcd\x1e\x3a\x0f\xa6\xa2\xa6\x63\x90\ +\x18\xcf\x98\x74\xf0\xcb\x2c\x55\x51\x29\x48\x62\xaa\x79\x4e\x31\ +\xd0\x82\x60\xbe\xcb\x6f\xf5\x12\xaa\x9e\x8e\xb1\x07\x1d\x96\x92\ +\xc5\x52\x68\x06\x7a\x8b\xeb\x58\xe9\xf2\xa8\x6d\x62\x89\xdd\xcf\ +\x2d\x5d\x8c\x48\x73\x65\x05\x97\xb8\x9a\x13\x2f\x6c\x38\xa2\x6a\ +\xc8\x05\x12\x8f\xc3\x92\x94\xa0\x3a\xa8\x7e\xbd\x89\x37\xad\xea\ +\xae\x0d\x93\x78\xac\xa1\x8d\x48\xc2\xb5\xb4\x79\xaf\x25\xc9\x68\ +\xc9\xb4\x15\xb9\x6b\xa1\xa9\x94\x06\x96\x68\x33\xf6\x90\x2f\x5a\ +\x7a\x2d\xc5\xb9\xeb\x94\x63\xde\xe6\xa9\xf4\xaa\xe2\xb2\xbc\x00\ +\x5b\x55\x84\x66\xe0\x9a\x22\xbe\x32\xd8\xaf\xa6\xbc\x2f\x47\x2b\ +\x5b\xb8\xab\xc4\x3e\x76\xe5\x5f\x88\xaa\x46\x39\xca\x37\xec\xd6\ +\x0b\xf4\x25\x3d\x67\xd5\xb1\x04\x28\x5d\x07\x1b\x6c\xd0\x43\x65\ +\x61\x46\xb8\x5a\x7e\x5d\x1e\xd0\xba\x7a\xf7\x0e\x0b\x3b\xcf\xe9\ +\x92\x87\xc5\x63\xef\x48\xe9\xfa\x1a\xdf\x1b\xe7\x69\xeb\x5c\xbf\ +\x50\x00\xd6\xa5\xe8\x3e\x92\xda\xfb\x24\x2b\x3b\xbe\xc0\x4d\x7e\ +\x86\x90\x1a\x47\x1b\xdd\xc8\x7b\x8d\x26\xe7\x8b\x5d\x19\x24\xe1\ +\x3c\x4a\x0a\xfc\xa0\xdd\x16\x35\x22\x37\xe9\xa6\xda\x32\x7a\xff\ +\x0f\x59\xf9\x35\x4a\ +\x00\x00\x04\x5f\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x11\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4d\x68\x1d\x55\x1c\xc5\x7f\x67\xf2\x90\x14\x95\xa2\xa8\x1b\ +\x51\x57\xa2\xb8\x11\x69\xc9\x47\x45\x49\x45\xab\x55\x0c\xcd\x7b\ +\xa5\xae\x44\x2a\x8a\x76\x21\x2a\x28\x82\x0a\xb1\xb4\x62\x05\xc1\ +\x85\x88\x16\x04\x71\x61\xd1\x90\x2f\x03\x5a\x8d\x4a\x2b\x48\x9b\ +\x3c\x6d\x69\x41\x5c\x14\x44\x5c\x28\xa2\x60\x54\xb0\x46\x9b\x37\ +\xc7\xc5\x6b\x64\x66\x5e\xc1\x44\xe6\xe3\x5a\xdf\x59\x9e\x03\x73\ +\xff\xf7\x77\xef\xdc\xb9\x77\xe6\x3d\xe8\xaa\xab\xae\xfe\xcf\x52\ +\xd5\x05\xac\x54\x7d\x13\x1e\x55\xe4\xa7\x65\x2b\x76\xb4\xbb\xd9\ +\xd0\x33\x79\x5c\xf7\x3f\x01\xa0\x7f\xc2\x1b\x89\xfc\x31\x3e\x5d\ +\xaf\x1d\xcf\x37\x7a\x7a\xf2\xb8\x76\x94\xc7\x45\x8a\x54\xdf\xb8\ +\xd7\x23\xcf\xfc\xdd\x79\x00\x29\xb7\xba\x83\x06\x30\x38\xee\xab\ +\x15\x79\x3f\x70\x5e\xd2\x37\xc4\x79\xb5\x11\x2c\x80\x75\x63\xbe\ +\x3c\x8e\x3c\x0b\x5c\x94\xcd\x04\xce\xab\x9d\x20\x01\xdc\x30\xe6\ +\x8b\x6b\x35\xcf\x02\x97\x15\xdd\x56\xad\xe8\x06\x56\xab\xeb\xdf\ +\xf1\xf9\x7f\xc6\x7e\x0f\x73\x55\x19\xed\x05\x35\x03\x86\x5e\x77\ +\xef\x52\xcb\xd3\x98\xf5\x49\xdf\x39\x4e\xf9\xac\x82\x01\x30\x74\ +\xc0\xb5\xc5\xb5\xde\x07\xdc\x94\x0a\x84\x95\xe3\xa2\x97\x55\x18\ +\x00\x6c\xfd\xbe\x10\xef\x35\x8c\x64\x13\x5c\x5c\xe7\x21\x10\x00\ +\xfd\x53\xf1\xf3\xa0\x7b\x53\xa6\x30\x05\x8e\xfc\xb2\x2a\x07\x30\ +\x30\xe9\x27\x40\x8f\x27\x3d\xb7\xef\xfa\xc2\x3b\x0f\x15\x03\x18\ +\x98\xf4\xfd\xc6\x7b\xb2\xbe\x14\xb5\xca\xaa\xa1\x32\x00\xfd\x53\ +\x6e\x18\xbf\x9a\x32\x0d\x36\x31\x2e\x6c\xd1\xef\x50\x25\x00\x06\ +\xc6\x7d\x33\xf6\xbe\x6c\xfb\x16\xb1\x54\xdc\x23\xef\x4c\x2a\x1d\ +\xc0\xe0\x94\xfb\x2c\x4f\x03\xe7\x24\x7d\x9b\x38\xcf\x2d\xee\x4a\ +\x55\x2a\x80\xfe\x69\x5f\x13\xdb\xfb\x11\xe7\xa6\x02\x97\x3f\xf2\ +\xcb\x2a\x0d\xc0\x86\x09\x5f\x41\xec\x59\xe0\xc2\x74\xa2\x98\x8a\ +\x3a\x0f\x25\x9d\x05\x36\x4c\xfa\x92\x16\xfe\x10\xb8\x34\x9d\x28\ +\xa6\xcc\x15\xef\x0c\x2a\x7c\x06\xac\x1b\xf3\xda\x25\xf9\x7d\xe0\ +\xca\x54\x20\xbb\xea\xce\x43\xc1\x33\x60\x70\xcc\x6b\xe2\x9a\x67\ +\x30\xd7\xa5\x02\x61\xac\x52\x36\x3a\xff\xa4\xc2\x66\xc0\xd0\x01\ +\xd7\xe2\x9a\xdf\x02\x6e\x4c\xfa\x2e\x61\x7f\xbf\x1a\x15\x03\x60\ +\xd4\xd1\xe2\x42\xfc\x1a\x30\x9c\xf2\x0b\x3e\xd9\xfd\x1b\xe5\x0f\ +\xc0\xd6\xc0\xb5\xf1\x0b\x46\xf7\x64\x93\x90\x46\x7e\x59\xb9\x03\ +\x18\x98\xe2\x49\xa3\x47\x53\x66\x7b\xad\x0b\xae\xf3\x90\x33\x80\ +\xbe\x49\x3f\x68\xbc\xbb\x23\x90\x4a\x3b\xdc\xac\x56\xb9\x01\xe8\ +\x9b\x6c\xed\x11\x7e\x25\xeb\x3b\xc0\x69\x9f\x54\x8e\x33\x20\xf3\ +\x42\x83\xf6\xfb\xfb\xaa\xb6\xb8\x2b\x55\x6e\x00\x04\x9d\xd3\x3c\ +\xe8\xae\xb7\x95\x1f\x00\xe9\x61\x32\x5d\x96\x88\x42\xff\xfc\x98\ +\x1b\x80\xb9\x11\x8d\x81\x1e\xea\x4c\x9c\xcb\x47\xcc\xa2\x94\xeb\ +\x53\x60\xbe\xae\x97\x41\xa3\x9d\x49\xb8\x10\x72\xdf\x07\xcc\x8f\ +\xb0\xcb\xf2\x4b\x69\x57\x20\xa2\x10\xef\x86\xfc\x77\x82\x92\x9b\ +\xc7\xa2\x47\x8c\xdf\x4c\xf9\x46\xb8\xfa\xb7\xd0\x59\x15\x53\xd0\ +\x4e\xc5\xad\x1f\xa3\xed\xc0\xbb\x99\x44\x28\x2c\x08\x85\x15\x73\ +\xe4\x01\x9d\x5a\xaa\x69\x1b\xf0\x69\x2a\x68\xff\xd0\x21\x18\x08\ +\x85\x16\x72\x64\x58\x27\xff\x90\xee\x04\x8e\x67\x22\x19\x07\x01\ +\xa1\xf0\x22\x8e\x8d\xe8\xe7\x78\x49\xb7\x19\xbe\x4a\xfa\x42\x32\ +\xaa\x7c\x59\x2c\x65\x14\x3e\xdb\xa6\xef\xa9\xe9\x16\xe0\xbb\xa4\ +\x2f\x1c\x55\x0d\xa1\xb4\x69\xd8\x1c\xd6\xd7\x2d\x74\x2b\xb0\x90\ +\xf4\xd5\xbe\x15\x2a\x83\x50\xea\x7d\xf8\x79\x5d\x5f\x18\xdd\x01\ +\x9c\xcc\xd6\xe1\x8a\x20\x94\xbe\x10\x35\xeb\x3a\xec\x58\x75\xe0\ +\x54\xd2\x17\x44\x76\xf9\x10\x2a\x59\x89\x9b\x5b\xf5\x81\xac\xbb\ +\xc9\x1e\x9e\x2a\x80\x50\xd9\xa3\x68\xae\xa1\xb7\x6d\xed\x48\x99\ +\x5a\x3e\x41\x96\xa7\x4a\x9f\xc5\xcd\x86\xf6\xda\x7a\xaa\x23\x70\ +\x79\x87\xa7\xca\x37\x23\xcd\x3a\xcf\x09\xbf\x98\x32\x75\xfa\xf0\ +\x54\x82\x2a\x07\x80\xe4\xb9\xe3\xd1\x63\xc2\x6f\xa4\xfc\x92\xb6\ +\xcc\xd5\x03\x00\xd8\xa9\xb8\xf7\x82\xe8\x3e\x60\x26\x93\x14\x7e\ +\x78\x0a\x03\x00\x70\x70\xa3\x96\xd6\xfc\xa2\xbb\x0c\x9f\xa4\x02\ +\x23\x17\x58\x67\x30\x00\x00\x0e\x6e\xd7\xa2\x7a\x35\x0c\x1c\x4d\ +\xfa\x2a\x70\x93\x14\x14\x00\x80\xf9\xdb\xf5\x6b\x0f\xda\x0c\x9c\ +\x28\xa3\xbd\xe0\x00\x00\x1c\xaa\xeb\x87\x1e\x6b\x13\xf0\x6d\xd1\ +\x6d\x05\x09\x00\xe0\x50\x43\xdf\x10\x69\x13\xf0\x53\x36\xcb\xf3\ +\xdc\x10\x2c\x00\x80\xf9\x2d\xfa\x32\x92\x36\x63\x7e\x4b\xfa\xca\ +\xb1\xee\xa0\x01\x00\x1c\x1e\x51\x53\xd6\x96\xcc\x0f\xa9\xce\xfe\ +\xbf\xcc\x24\x35\xb7\x55\x1f\x61\xed\xa2\xfd\xf9\xad\x85\xf4\x6c\ +\xd5\x35\x75\xd5\x55\x57\x67\x87\xfe\x02\x8f\xb0\x51\x56\xec\xcd\ +\x17\x8d\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x88\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3a\x49\x44\x41\x54\x58\x85\xed\ +\xcd\xb1\x11\x00\x10\x00\xc0\xc0\x30\x99\xc6\x04\x56\x30\x96\x15\ +\x2c\xe0\xdc\x59\x4d\xa5\x55\x6a\xe4\xab\x74\x01\x49\x92\x7e\x17\ +\x4e\xe4\x52\x17\x90\x1e\x4d\xe7\xe8\x2d\x03\xc4\x17\x43\x49\x92\ +\xa4\x9b\x0d\x00\xac\x05\x04\x1d\x7e\x88\x63\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x03\xbb\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x6d\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\xbd\x6f\x13\x31\x18\xc6\x9f\xf7\x2e\x15\x13\x08\xa6\x22\x35\ +\xc4\xbd\x88\x05\x06\x40\x82\x85\x1d\xca\x00\x62\x80\xa1\x0b\x12\ +\x7f\x01\x1f\x1b\xb4\x03\x08\x24\x3e\xc4\xc4\xc7\x5f\x80\xc4\xd2\ +\x01\x06\x04\x03\x85\x9d\x05\x24\xca\xd0\x6e\x77\xe7\x24\x1d\x60\ +\x00\xc4\x56\x91\xe4\x61\x48\x24\x2e\x77\x17\x68\xe3\xbb\xb8\xa5\ +\xfe\x6d\x7e\xfd\xc6\x79\xfc\xc4\x67\x5b\x39\x1b\x70\x38\x1c\xdb\ +\x19\x59\x4f\x12\xc9\x8a\xd6\xad\xb3\x14\xce\x0a\xe4\x18\x80\x29\ +\x00\x3b\xca\x95\xb6\x61\xd6\x00\xac\x12\xfc\x20\x94\x05\xa5\xaa\ +\x2f\x45\xa4\xfd\xaf\x0f\xfd\xd3\x00\xad\xf5\x49\x42\x1e\x01\x72\ +\xa0\x10\x99\xe3\x63\x59\xd0\xbd\xaa\x94\x7a\xfb\xb7\x24\x6f\x58\ +\x05\x49\x89\x1b\xad\x79\xc2\x5b\xdc\x82\x9d\x07\x80\x83\x84\xb7\ +\x18\xe9\xd6\x1c\xc9\xa1\x3f\xf4\x50\x03\x74\x73\x75\x0e\xe4\x9d\ +\x72\xb4\x8d\x0f\x01\xef\xc6\x8d\xd5\xeb\xc3\xeb\x73\xe8\x0d\x7b\ +\x6f\x31\x15\xfe\x0e\xe2\x06\xd0\x79\xad\x94\x6a\x88\x48\xa7\x50\ +\xa5\x86\x90\xf4\xb5\xd6\x35\xc0\x3f\x0d\xc1\x6d\x00\x7b\x92\xf5\ +\x82\xee\x4c\xde\xe3\x90\x31\x80\x64\x45\x37\x9a\x9f\x07\x87\x3d\ +\xdf\x75\x3b\xed\x0b\xf5\x7a\xfd\x4b\x09\xda\x0b\x27\x0c\xc3\x49\ +\xcf\xaf\x3c\x03\xe4\x44\x22\xbc\xac\x6a\xd5\xc3\xe9\x89\x31\x63\ +\x40\x1c\x37\xcf\x41\xf0\x3c\x11\xfa\xd6\xfe\x35\x71\x60\xff\xfe\ +\xbd\x5f\xcb\x12\x5c\x06\x3d\x13\x26\x56\x90\x1c\x09\xc4\xf9\xe9\ +\xe9\x7d\x2f\x92\x79\x99\x39\x80\xc2\xd9\xc1\x00\x6e\x6e\xb5\xce\ +\x03\x40\xbd\x5e\xff\x22\xc0\xcd\x64\x2c\xd3\x37\xe4\x18\xd0\x5f\ +\xe7\x13\x74\x5e\x17\x2d\x6e\x5c\x90\x9d\x57\xc9\xb2\x40\x8e\xa6\ +\x73\xf2\x56\x81\xa9\x64\x41\x29\xd5\x28\x58\xd7\xd8\xc8\xd1\x5e\ +\x4d\xe7\xe4\x19\x30\xb0\xc3\xdb\x6c\xb3\xfd\x46\xc8\xd1\x9e\xd9\ +\xbd\x0e\xdd\x07\x6c\x17\x9c\x01\xb6\x05\xd8\xc6\x19\x60\x5b\x80\ +\x6d\x9c\x01\xb6\x05\xd8\xc6\x19\x60\x5b\x80\x6d\x9c\x01\xb6\x05\ +\xd8\xc6\x19\x60\x5b\x80\x6d\x2a\x45\x34\x12\x36\x1a\x33\x1e\xe4\ +\x01\x88\x43\x58\xe7\xbb\x06\x03\x08\x60\xa9\x2b\xbc\x56\xaf\xd5\ +\xd2\xff\x5b\x6e\x18\xe3\x11\x10\xe9\xd6\x45\x8f\xf2\x06\xc4\x61\ +\x94\xdf\x79\xf4\xbf\xe3\x88\x47\x79\x13\xe9\xd6\x45\xd3\xc6\x8c\ +\x0c\x88\xa2\x68\xb7\x80\x4f\x4c\x45\x8c\x8a\x80\x8f\xa3\x28\xda\ +\x6d\xd2\x86\x91\x01\x22\x95\xe3\x00\x76\x9a\xb4\x61\xc8\xae\xbe\ +\x86\x91\xd9\xf6\x93\xa0\x91\x01\x64\xfb\x3d\x80\x9f\x05\x69\x19\ +\x85\x9f\x7d\x0d\x23\x63\x64\x40\x10\x04\x3f\x08\xb9\x6c\xd2\x86\ +\x09\x84\x5c\x0e\x82\xe0\x87\x49\x1b\xc6\x8f\x40\xa0\xaa\x4f\xbb\ +\xc2\x53\x00\x3e\xa1\xb7\x44\x95\x0d\x21\x58\xea\x0a\x4f\x05\xaa\ +\xfa\xd4\xb4\xb1\x42\xf6\x01\xfd\xf5\xd8\x78\x4d\xb6\x81\x9b\x04\ +\x6d\x0b\xb0\x8d\x33\xc0\xb6\x00\xdb\x38\x03\x6c\x0b\xb0\x8d\x33\ +\xc0\xb6\x00\xdb\x38\x03\x6c\x0b\xb0\x8d\x33\xc0\xb6\x00\xdb\x38\ +\x03\x72\x62\x6b\xc9\x02\x49\x7f\x4c\x5a\x0a\x27\x47\xfb\x5a\x3a\ +\x27\xcf\x80\xd5\x64\xa1\x77\xfc\x74\x6b\x92\xa3\xbd\x95\xce\xc9\ +\x1e\x94\x04\x3f\x0c\x46\xfc\xd3\x85\xaa\x1a\x23\x22\xfe\x99\x64\ +\x99\xe0\xc7\x74\x4e\xf6\xa0\x24\x65\x61\x30\x80\xdb\x61\x18\x4e\ +\x16\xae\xae\x64\xc2\x30\x9c\x24\x70\x2b\x19\xcb\xf4\x0d\x39\x06\ +\x28\x55\x7d\x09\x70\x25\x11\xda\xe3\xf9\x95\x67\x5b\xc9\x84\x3f\ +\x87\xa5\x07\x4e\x8c\x2f\xf7\xfa\x36\x48\x76\x04\x88\xb4\x05\xbc\ +\x92\x8a\x9e\xf0\xfc\x89\x15\xad\x9b\x97\xe2\x38\x0e\x36\xe3\xc4\ +\x48\xd2\x8f\xe3\x38\xd0\xba\x79\xa9\x77\x48\x7a\xe0\xa4\x38\x04\ +\xdd\xab\x79\x57\x68\x86\xbe\xca\x8a\x1b\xad\xf9\xff\xe1\xc2\x04\ +\x00\x10\x32\x1f\xa8\xea\xbd\xbc\xba\xa1\xfb\x00\xb5\x6f\xea\x1e\ +\x21\xf3\xe5\xc9\x1a\x0b\x24\x30\x37\x5d\x9b\xba\x3f\x2c\x61\x9d\ +\x97\xa6\xbc\x87\x00\x0e\x16\x2a\xad\x7c\xd6\x75\x69\x6a\x94\x6b\ +\x73\x47\xd1\x3b\x75\xbd\x19\xaf\xcd\xb5\x08\x7e\xdc\xc8\xb5\x39\ +\x87\xc3\xb1\xbd\xf9\x0d\x9c\xbe\x20\xb7\xf5\xf6\x9b\x02\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\xdc\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x8e\x49\x44\x41\x54\x58\x85\xed\ +\x97\x41\x4a\xc3\x50\x10\x86\xbf\x79\x71\xab\x0b\x45\x5d\xd8\xd6\ +\x92\x4b\x28\x28\x5e\xa0\x5e\x41\x0f\x20\xe8\x4a\xd4\x23\x58\xc1\ +\x85\x15\x3c\x88\xd0\x0b\x08\x82\x5e\x22\xe6\x25\xcf\x85\x8a\x82\ +\x74\x9d\x8c\x0b\x1b\x91\x36\x46\xac\xa9\x0a\xe6\x5f\x0d\xf3\x86\ +\x37\x1f\x33\xc3\xe3\x0d\xfc\x77\xc9\xa0\xc3\xda\xdb\x95\x94\x64\ +\x5f\x54\x96\x11\x66\x4b\xc9\xa2\x3c\xa8\xe8\x95\xc1\x6b\x2f\x2e\ +\x2e\x5c\x7e\x08\x10\x86\xd1\x2e\x22\x47\x79\x60\x25\x29\x45\x75\ +\xaf\xd9\x6c\x1c\x0f\x01\x58\x6b\x57\x15\x73\x01\x3c\x0b\xb2\x63\ +\x8c\x76\xeb\xf5\xfa\x53\x19\x59\xe3\x38\x9e\x4e\x53\x69\x29\xda\ +\x01\xa6\x04\xb3\x36\x58\x09\x6e\x6c\x74\x1e\xda\x58\xad\x75\x1b\ +\x65\x24\xcd\x93\xb5\x6e\x33\xb4\xb1\xde\xd8\xe8\x3c\xf3\x99\xcc\ +\x10\x95\x65\x00\x63\xb4\x3b\x2e\x00\xcf\xa3\x0b\x20\xc8\xd2\x10\ +\x40\x36\x70\x65\x95\x3d\x4f\xb5\x5a\xed\xb1\x6f\xce\x0d\x03\xfc\ +\x92\x2a\x80\x0a\xe0\xd7\x01\x26\x3e\x0b\x08\xa3\x68\x0b\x95\x43\ +\x60\xf2\x8b\x77\xf7\x10\x3d\x68\x36\x1a\x67\x45\x41\x85\x15\x08\ +\x82\x60\x1e\x95\xd3\x11\x92\x03\x4c\xa2\xd2\x09\x82\x60\x7e\x64\ +\x80\x9f\x50\x21\x80\xef\xfb\x77\x88\x6e\x03\xbd\x11\xee\xee\x21\ +\xba\xe3\xfb\xfe\x5d\x51\xd0\xa7\x33\xd0\xef\x61\x61\x1f\xbf\xa3\ +\xbf\xdd\x82\x0a\xa0\x02\xf8\x59\x00\xe5\x01\x5e\x3f\x90\xe3\x4a\ +\xe6\x9c\x9b\xe9\x9b\xf7\x43\x00\x2a\x7a\x05\x90\xa6\xd2\x1a\x17\ +\x40\x92\xd0\x02\x50\xf4\x3a\xf3\xbd\x3d\x44\x06\xaf\xad\xa4\xeb\ +\x8a\x76\xac\x75\xe2\x79\x74\xdf\xfd\xe1\xbe\x25\xe7\xdc\x4c\x92\ +\xd0\x52\xf4\x04\x48\x0d\x5e\x3b\x3b\xcb\x5b\x4c\xda\x8c\x6f\x36\ +\x3e\x5e\x4c\x32\xbd\xad\x66\xaf\x5f\xe7\xb9\xc1\xf3\x11\x75\xaf\ +\xe8\x75\xde\x6a\x56\xe9\x05\x72\xdf\x93\xde\xaf\x9f\x93\x4c\x00\ +\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x05\x36\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\xe8\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4f\x4c\x1c\x55\x1c\xc7\xbf\xbf\x99\x59\x4c\x7a\x21\x55\x1a\ +\x52\x69\x7a\x71\x9b\x88\x21\xa9\x48\x6f\xbd\x6c\x5c\x81\x43\x2b\ +\x91\xc0\x46\x8d\xd0\x34\xd9\x8d\xbd\x7a\xb1\x07\x12\x59\x20\x31\ +\xa6\xf5\xe4\xcd\xe8\x12\x1a\x25\x9a\x66\x5b\x30\x84\xc6\x00\x62\ +\x36\x2d\x7a\xa2\x92\x18\x5d\x2e\xc5\x03\x61\x0f\x18\x6c\xc3\xa9\ +\x59\xd8\x99\x9f\x07\xf6\xc9\xec\xec\xec\xce\x2c\xf3\x67\x07\xd9\ +\xcf\xed\xcd\xfc\x66\xde\x6f\xbe\xf9\xfe\xde\x7b\x33\x79\x03\x34\ +\x68\xd0\xe0\x24\x43\x76\x82\x22\x91\xa4\xa2\xb4\xe4\xfa\x88\xf1\ +\x2e\x80\x4b\x00\xda\x00\xbc\xe0\x69\x66\xb5\x93\x07\x90\x03\xb0\ +\xca\x84\xbb\x85\x9d\xb6\xb9\x4c\x66\xbc\x60\x75\x91\xa5\x00\x3d\ +\xfd\x89\x6e\x96\xf0\x05\x80\x76\x17\x92\xf4\x11\xca\x92\xc6\x1f\ +\x2d\xce\xa6\x96\xaa\x45\xc9\xd5\xee\xd0\x3d\x98\x18\x01\xe1\x0e\ +\x80\x33\xae\xe6\xe6\x0f\x67\x40\x18\x0e\xb7\x77\xee\x6d\xac\xaf\ +\xfd\x52\x29\xa8\xa2\x00\xdd\x83\x89\x11\x30\x3e\xf5\x26\x37\x1f\ +\x21\x8a\x86\xdb\x3b\xf3\x1b\xeb\x6b\x2b\xa6\xa7\xcd\x0e\x16\x6d\ +\xbf\x58\x72\x90\xf1\x8c\x89\x47\x25\x89\x1e\x34\x63\x77\x33\x9d\ +\x4e\xab\x1e\xa4\x7b\x64\x62\xb1\x98\xbc\x8b\xe6\xf3\x9a\xc6\x57\ +\x88\x69\x02\x84\xd3\xfa\xf3\xa4\xa1\xc7\xac\x1c\xca\x04\x88\x44\ +\x92\x4a\xe8\xa5\xdc\xef\xd0\xd5\x3c\x01\x3f\xa9\xfb\x18\x5a\x9e\ +\x4b\x6d\x7b\x92\xbd\xcb\x44\xfb\x12\xad\x72\x08\xd3\x0c\xbc\x75\ +\x78\x94\xb2\xfb\xff\xbc\x7c\xd1\x38\x30\x4a\xc6\x8b\x95\x96\x5c\ +\x1f\x4a\x07\xbc\xa7\xd0\x94\x0f\x8e\xcb\xc3\x03\xc0\xf2\x5c\x6a\ +\x5b\xdd\xc7\x10\x18\xcf\x0e\x8f\xf2\x6b\xc5\x67\x2b\xa1\x4c\x80\ +\xe2\x54\x77\x78\x19\x38\xb9\x38\xfb\xe5\xdf\x5e\x24\xea\x25\xcb\ +\x73\xa9\x6d\x06\x25\xf5\xc7\x8c\xcf\x06\x98\x08\x80\x83\x79\xfe\ +\x30\x40\xa2\x07\x2e\xe7\xe6\x1b\x92\xcc\xf3\xfa\x36\x01\x5d\x65\ +\x31\x26\xd7\xb5\xe9\x1b\xcd\xd8\xdd\x74\x39\x2f\xdf\x30\xe6\xce\ +\xc0\x39\x63\x8c\x99\x00\x25\x2b\xbc\xa0\x8d\xf6\xb5\x60\x92\x7b\ +\xd9\xea\xd5\x4c\x80\x13\x85\x52\xef\x04\xec\xd0\x1b\x8b\x87\x35\ +\x4d\x1a\x05\x78\x00\x00\x88\x71\xaf\xa0\x49\x13\x3f\xff\xf0\xd5\ +\x86\xd3\x7b\x07\xde\x01\xdd\x03\x37\x2e\x68\x1a\x3d\x04\x78\x18\ +\xc0\x29\x00\xa7\x98\x70\x4d\x96\xb5\x47\xbd\xb1\x78\xd8\xe9\xfd\ +\x03\x2d\x40\x24\x92\x54\xc0\xea\xf7\x00\xce\x9a\x9c\x3e\xcb\x2a\ +\x7d\xe2\xb4\x8f\x40\x0b\x10\x6a\xc9\xdd\x04\x95\x4f\x5d\x02\x26\ +\x0c\x3a\xed\x23\xb0\x02\xf4\xf4\xc7\x3b\xc0\x18\xf3\xba\x9f\x40\ +\x0a\x10\x89\x24\x15\x26\xba\x03\x20\x64\x11\x9a\x76\xda\x57\x20\ +\x05\xb0\xb2\x7e\x91\x3d\x4d\x52\x6f\x3b\xed\x2b\x70\x02\xd8\xb5\ +\x3e\x31\x8f\x2d\xa7\xa7\xb2\x4e\xfb\x0b\x94\x00\x35\x58\x7f\x75\ +\xef\xe9\xb9\xcf\xdd\xe8\x33\x50\x02\xd8\xb5\xbe\x04\xba\x6e\xe7\ +\x83\xa7\x1d\x02\xb3\x12\xec\xe9\x8f\x77\xb0\x4d\xeb\x2f\xcc\xa4\ +\xfe\x74\xab\xdf\x40\x38\xa0\x1e\xd6\x17\xb8\xe2\x80\x37\xdf\xf9\ +\xf0\x15\x45\xd2\x46\x0f\x17\x26\x74\x5f\x92\xb4\x89\x85\xf4\xe4\ +\x13\x3b\xd7\x87\x5a\x72\x37\xc1\xfe\x5a\x5f\xe0\xd8\x01\xbd\xb1\ +\x78\x58\x96\xb5\x47\x4c\xb8\x86\xe2\x5a\x1d\xe0\x61\x4d\xa3\x87\ +\xdd\x03\x37\x2e\x58\x5d\x5f\xcb\xa8\xbf\x70\xff\x6b\xd7\xac\x2f\ +\x70\x2c\xc0\xc1\x5b\x9a\xf9\x5a\x1d\x50\xbf\x8b\x44\x92\x15\x5d\ +\x56\x4f\xeb\x0b\x5c\x18\x03\x0e\x5e\x51\x2b\x70\xa9\xe9\xc5\xad\ +\x8f\x2b\x9d\xac\xc7\xa8\x6f\xc4\xf3\x41\x90\x89\xc6\x7a\xfa\xe3\ +\x1d\xc6\xe3\xf5\xb6\xbe\xc0\xb1\x00\xc4\xb8\x67\x11\xd2\xc4\x12\ +\x4d\xe9\x4b\x21\x08\xd6\x17\x38\x16\x40\x95\xd5\x5b\x00\xf6\x2c\ +\xc2\x4a\x4a\x21\x08\xd6\x17\x38\x16\x60\x39\x3d\x95\x05\x61\xdc\ +\x2a\x4e\x94\x42\x50\xac\x2f\x70\x65\x0c\xd8\xdf\x69\xbb\x0d\xc6\ +\x63\x8b\xb0\x26\x96\xe8\x5b\x96\xa4\x69\x04\xc0\xfa\x02\x57\x04\ +\xc8\x64\xc6\x0b\xc4\x7c\x1d\xd6\xa5\xf0\x3a\xc0\x17\x2d\x62\x7c\ +\xb1\xbe\xc0\xb5\x59\x60\x71\x76\xf2\x0f\x3b\xa5\x60\x85\x5f\xd6\ +\x17\xb8\x3a\x0d\xda\x2c\x85\x6a\xf8\x66\x7d\x81\xab\x02\xd4\x50\ +\x0a\x66\xf8\x6a\x7d\x81\xeb\x0b\xa1\xa3\x96\x82\xdf\xd6\x17\x78\ +\xb2\x12\x3c\x42\x29\xf8\x6e\x7d\x81\x27\x02\xd4\x58\x0a\x75\xb1\ +\xbe\xc0\xb3\x77\x01\xbb\xa5\x50\x2f\xeb\x0b\x3c\x7d\x19\xb2\x51\ +\x0a\x75\xb3\xbe\xc0\x53\x01\x32\x99\xf1\x82\x24\xf3\x7b\x00\xcc\ +\x36\x59\x6c\x4a\x12\xbf\x5f\x2f\xeb\x0b\x3c\x7f\x1d\x5e\x48\x4f\ +\x3e\x51\x18\x97\x19\x98\x07\xf0\x1c\xc0\x73\x06\xe6\x15\xc6\x65\ +\xbb\x9f\xcc\xbc\xc4\x97\xaf\xc2\x3f\xce\xa4\xb6\x00\xbc\xed\x47\ +\x5f\xb5\x12\x88\xaf\xc2\xf5\xc4\x4c\x80\xbc\xbe\x11\x8b\xc5\xaa\ +\xed\x27\x0e\x34\x26\xb9\xe7\x8d\x31\x66\x02\xe4\xf4\x8d\x5d\x34\ +\x9f\x77\x33\x29\x3f\x31\xe6\x4e\xc0\x96\x31\xc6\x4c\x80\x55\x7d\ +\x43\xd3\xf8\x8a\xcb\x79\xf9\x86\xa6\xd2\x55\x7d\x9b\x51\x3e\x25\ +\x97\x09\xc0\x84\xbb\xfa\x36\x31\x4d\x44\xfb\x12\xad\xee\xa7\xe7\ +\x2d\xd1\xbe\x44\x2b\x81\x4b\x16\x62\xc6\x67\x03\x4c\x04\x28\xec\ +\xb4\xcd\x01\x58\xff\xef\x00\xe1\xb4\x1c\xc2\xf4\x71\x12\x41\x6c\ +\x96\x2e\xdd\x31\x4e\xd9\xe2\xb3\x95\x50\xdb\x76\x79\x50\x52\x92\ +\x79\x3e\xd0\xdb\xe5\x55\xba\x4a\xe0\xf1\x23\x6f\x97\x17\xfc\x6f\ +\x7e\x98\x00\x40\xcc\x23\x8b\x33\x93\x9f\x99\x9d\xab\x38\xc5\xfd\ +\x95\xfd\x6d\x25\xdc\xde\x99\x07\x51\xd4\xbb\xd4\x3c\x87\x19\x18\ +\x59\x9a\x99\xbc\x55\x29\xa0\xea\x1c\xbf\xb1\xbe\xb6\x12\x7e\xf5\ +\x8d\x5f\x41\xd4\x85\x63\xf7\xdf\x10\x65\x49\xc3\xd0\xd2\x4c\xea\ +\x9b\xaa\x51\x76\x6e\xa5\xff\x6d\x8e\x80\xae\xe2\xae\xeb\xc0\xfd\ +\x36\x47\xc0\x16\x03\x8f\x6b\xf9\x6d\xae\x41\x83\x06\x27\x9b\x7f\ +\x01\x0f\x15\x0b\x99\x9e\x82\xdf\x92\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x02\x05\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xb7\x49\x44\x41\x54\x58\x85\xed\ +\x96\xbd\x4a\xc3\x50\x14\xc7\xff\x27\x1f\x53\xc1\x07\xf0\xda\x34\ +\x43\xf7\x82\x93\x08\xe2\x2b\x88\x0e\xd2\xc5\x17\xd0\x45\x10\x71\ +\xe9\xd4\xc1\x41\x74\x29\x3e\x81\x93\x43\x9f\xc0\x45\x90\x82\xa3\ +\x7d\x80\x62\x3e\x50\x33\xb8\xe8\x20\xa1\x69\x7b\x1c\x6c\x42\x13\ +\x9b\x34\xe9\xe7\xd0\xfe\xa7\xfb\x71\xee\xfd\xff\x72\xee\xb9\x97\ +\x00\xcb\x2e\x4a\x9a\x74\x1c\x27\xe7\xba\xed\x2a\x88\xf6\x01\x14\ +\x26\xf4\x32\xc1\x54\x57\x55\xaa\x08\x21\x7e\x46\x02\x38\x8e\x93\ +\x73\xdb\x5e\x03\x8c\xd2\x84\xc6\x61\x11\x9a\xaa\x2c\x6d\xfb\x10\ +\x52\x5c\x9c\xeb\xb6\xab\x53\x37\x07\x00\x46\xc9\xf3\xb8\xea\x77\ +\x63\x01\xfa\x69\x9f\x8d\x88\x0f\xfc\xa6\x92\x10\x16\x3a\x73\xbd\ +\x90\x4f\xac\x97\x51\x32\x4c\x9b\x87\xed\x1d\x9f\x81\x39\x69\x05\ +\xf0\xaf\x06\x5a\xad\x37\x4d\x51\x78\x97\xc1\xa1\x71\xc3\xb0\x4f\ +\x62\x77\x91\xb8\x47\x2c\x37\x35\x6d\xfd\x99\x88\xba\x59\x00\x42\ +\x85\x65\x18\xd6\x19\x88\x2e\x87\x81\xa5\x11\x03\x4f\xc4\xdd\x43\ +\x5d\xd7\x3f\xa2\x73\x91\x22\x0c\x8a\x3a\x38\x82\x57\xcb\x2a\x83\ +\xe8\x6a\x5c\x73\x00\x20\x60\x87\x49\xbe\x67\x66\x39\xed\x9a\x00\ +\x80\x98\xce\xc7\x35\x8e\x42\x58\xd6\xfb\x56\xda\xf8\xc1\xaf\x0d\ +\xbf\x7a\x84\xdb\xd4\xae\x8c\x3d\x00\x22\xe8\x52\xb7\x04\xa0\x91\ +\x15\x20\x54\x0f\xba\x96\x8f\x2f\xba\x88\x0c\xcb\x06\x18\xc7\xc1\ +\x40\x8f\x52\xdf\xae\x85\x5f\xc3\x15\xc0\x0a\x60\xe1\x00\x63\xbf\ +\x7a\x89\x22\xd4\x0c\xd3\xae\x25\x44\x98\x7e\x63\x31\x19\x60\xaa\ +\xfb\xcd\xd9\x64\x20\x49\x84\xa6\xaa\x50\xc5\xef\xce\x33\x03\x26\ +\x98\x6e\x06\xff\x88\xff\x78\xfa\x32\x4c\xfb\x0b\xc0\xda\x34\x9c\ +\x08\x74\x54\x28\x6c\xdc\xa5\x89\x1d\xcc\xc0\xc3\x34\xcc\x01\x74\ +\x3c\x85\x1e\xd3\x06\x07\x00\x1d\x45\x3a\x05\xf0\x39\xb1\x3d\xf3\ +\x45\x51\x08\x3b\x33\x40\x51\x08\xbb\xa3\x48\x9b\x00\xea\x00\xbe\ +\xb3\xda\x02\x78\x61\xe2\xb2\xae\x6b\xd7\x19\xd7\x2e\xb9\x7e\x01\ +\xf9\xaa\x7b\xc5\x23\x95\x73\x7f\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x01\xa6\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x58\x49\x44\x41\x54\x58\x85\xed\ +\xd2\x31\x2f\x43\x51\x18\xc6\xf1\xff\x39\x15\x03\x89\x10\x42\xba\ +\x11\x9b\x89\xb0\x89\x45\xb4\x69\xd0\x44\xb5\xb5\xd5\xc0\x15\x12\ +\x1f\xc0\x66\x12\x1f\xc0\xac\xb5\x34\x62\x68\x99\x08\xad\x44\x42\ +\x48\x37\x11\xc2\xd6\x45\x27\x83\x44\xca\xe4\xde\xfb\x5a\x19\x38\ +\xda\x2e\x12\xe7\x37\x3f\x79\xce\xf3\x26\x07\x2c\xcb\xb2\xac\xff\ +\x4e\x99\x02\xa1\xb8\xb3\x0d\x0c\x2b\x5f\x52\x85\x83\xf4\xdd\x6f\ +\x4a\x23\x33\x2b\xbd\x5e\xc0\xcd\x02\x2f\xc5\xfc\xf6\x34\x20\xdf\ +\x65\xb5\x79\xa1\xb4\x03\x83\xa2\xf5\x65\x38\xe6\x8c\x9b\xf2\xe1\ +\xa4\x33\xec\x35\xb9\x25\x60\x14\xa4\xd3\x94\x37\x0e\xa8\xea\xb6\ +\x14\x8a\x1c\x48\x9b\x68\x8e\x27\x12\xce\xfc\x77\xd9\x89\xd9\xc5\ +\x29\xf1\x39\x47\xe8\x11\xd4\xd9\xbb\xe7\x45\xf8\xe1\x7a\x80\x80\ +\x69\x40\xe5\xbe\xe4\xa6\x92\xd1\x7c\xe5\xe9\xb5\x15\x18\x53\x10\ +\xeb\x1f\x18\x92\xf2\xc3\xf5\xf9\xe7\x5c\x28\xbe\xb4\xa2\x14\x59\ +\xa0\x19\xc8\x76\xe8\x97\xb9\xa3\xfd\xdd\x37\x53\xbf\xf1\x0f\x7c\ +\x7d\xc4\x59\x05\xb6\x00\x8d\xb0\xf3\xdc\xa5\x97\xa7\x83\x41\xef\ +\xea\xb6\xb2\x89\x52\x6b\x00\xa2\x64\xe3\x34\x97\x5e\xc7\x70\x79\ +\x5d\x03\x00\xc2\xf1\xc5\xa8\xa0\xf6\x80\x16\x81\x0b\x05\x55\x60\ +\x12\x70\x15\xb2\x5c\xc8\xa7\x33\xb5\xf4\xd5\x3c\x00\x20\x14\x5f\ +\x18\x01\x7d\x08\x74\x03\x08\x54\x95\xf2\x13\xc5\x5c\xa6\x50\x6b\ +\x57\x5d\x03\x00\xc2\x49\xa7\x4f\x7c\xca\xc0\xa3\xf6\xfd\xe8\xc9\ +\x41\xe6\xa6\xde\xae\x46\x28\x1a\x38\xc2\xb2\x2c\xcb\xfa\x13\x3e\ +\x00\x77\x85\x6b\x30\xd4\xa0\xe5\x67\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x01\xa5\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x57\x49\x44\x41\x54\x58\x85\xed\ +\xd2\xcd\x2b\x44\x51\x1c\xc6\xf1\xef\xb9\x93\xd2\x28\x29\xe5\x65\ +\xc7\x7f\x20\xf7\x92\xb2\xb3\x9a\x30\x3b\x65\x35\x56\x9a\x3b\xc2\ +\x88\x8d\xdd\xac\x64\xa5\xa6\xb9\x77\x33\x23\x79\xa9\x59\x58\x58\ +\x29\x25\x1b\x45\x22\xae\xa2\xac\x6d\x94\x6c\x88\x14\xa9\x3b\xf3\ +\xb3\x30\x0b\xd4\xb8\x33\x63\x25\xe7\xb3\x3c\x3d\x3d\x3d\xa7\x73\ +\x40\xd3\x34\x4d\xfb\xef\x54\x50\xc0\xb2\x33\x2b\x60\x98\xa8\x62\ +\xcc\xcb\xce\x5c\x55\x52\xda\x97\x48\x77\xf8\x12\xca\x83\x7a\xf2\ +\x72\x53\xc3\xa0\xa4\x5c\xd6\x08\x6c\x13\x9a\x40\xba\x10\x75\xd4\ +\x9d\x70\x07\x82\xe2\xdd\x13\x19\xd3\x97\xd0\x09\xd0\x0f\x34\x07\ +\xe5\x03\x07\xd4\x35\x14\x62\xc0\x16\xd0\x68\x88\xec\x5a\xb6\x33\ +\x56\x2e\x6b\xc6\x9d\x21\xa3\xa8\x0e\x80\x56\x60\xdf\x7f\xf3\x23\ +\x3f\xdd\xbe\xa2\x01\xc7\xe9\xb9\x57\xaf\xed\x7e\x54\x50\x4b\x40\ +\x1d\xb0\xd1\x63\x3b\x29\x90\x2f\xcf\x67\xda\x6e\x42\x29\xb6\x81\ +\x30\x48\xfe\xe5\xe1\x3e\x72\xb1\x3e\xfb\x18\xd4\x1f\xf8\x07\x3e\ +\xb3\xe2\x99\x49\x94\x72\x3e\x86\xcb\x9a\x48\xbd\x7d\xde\x7e\x5b\ +\xb0\xee\x9a\x17\x81\xf9\x52\xe1\xc2\x59\x6e\x3a\x15\x74\xf3\x9a\ +\x06\x00\xf4\xd8\x4e\x54\x60\x13\x08\x2b\x38\x14\xd4\x33\xc8\x20\ +\xe0\xa3\xb0\xbd\x6c\x72\xb5\x9a\xbe\xaa\x07\x00\xf4\xda\xae\x25\ +\xc8\x8e\x40\x4b\xe9\xe8\x59\x84\x91\xf3\xe5\xe4\x5e\xb5\x5d\x35\ +\x0d\x00\xe8\x1d\x77\x3b\x8b\x21\xb9\x06\x6e\x0c\x88\x9e\xe6\x92\ +\x97\xb5\x76\xfd\x82\xa8\xef\x9f\x51\xd3\x34\x4d\xfb\x73\xde\x01\ +\x57\x2b\x69\x45\xc4\x74\x4c\x85\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x02\xdb\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\x8d\x49\x44\x41\x54\x58\x85\xe5\ +\x97\x4f\x48\x54\x51\x14\xc6\x7f\xe7\x8d\xb8\x11\x82\x12\x03\x75\ +\x35\xb8\x10\xc9\x4d\x6d\x32\x8c\x28\x9c\xa6\x85\x12\x18\x6f\xb6\ +\x12\xcc\x64\xad\x5c\xa9\x2d\x87\xc1\xd5\x04\x2d\x12\x92\x2c\x27\ +\x28\x17\x19\xc6\xb8\x49\x28\x07\x13\x02\xff\xb4\xa9\x8d\xd5\x4e\ +\xdd\xd8\x42\x29\x68\xe1\x46\x98\x7b\x5a\xf8\xde\xf4\x1c\x9a\x3f\ +\x6f\x7c\xb6\xa8\x6f\xf5\xde\xb9\xe7\x9e\xef\x7b\xdf\xb9\x97\x77\ +\x2f\xfc\xef\x90\xe2\xc0\xd5\x1b\xf1\x6e\x44\xee\x02\x5d\x40\x53\ +\x40\x3c\xbb\xc0\x1a\xaa\xe9\x5c\x36\xb3\xec\x1d\x08\x79\x5f\x22\ +\x76\x7c\x58\x90\x17\x40\x3b\xd0\x10\x10\x39\x4e\xad\x76\x44\x6e\ +\xb6\x75\x9c\xdb\xdb\xf8\xfa\x71\xd5\x1d\x28\x38\x10\x89\x0d\x5e\ +\x14\x63\xde\x03\x3f\x51\x1d\xb2\x42\xcc\xbf\x9d\xcd\xfc\x08\x82\ +\xfd\x5a\x2c\x7e\xca\xe4\xe9\x45\x64\x1c\x38\x81\xea\x25\xd7\x89\ +\xba\x82\x12\x63\x46\x01\x41\x75\x28\x97\xcd\x4c\x07\x41\xec\xc2\ +\xf9\x90\xe9\x88\x9d\x10\x51\x9e\x39\x2d\xbe\x0e\x60\x79\xf2\xba\ +\x00\xac\x10\xf3\x41\x92\x7b\xa1\xf9\x7d\xb7\xf6\x79\x37\xe6\x15\ +\xd0\xe4\x51\x7b\x2c\x58\x9c\x7b\xfe\xdd\x79\x3c\xed\xc6\xea\x4a\ +\xe4\xd6\x8c\xa8\x7d\xab\x4f\x55\x1f\x03\x88\xc8\xe0\xc2\xab\x27\ +\xaf\xcb\xe5\x07\x2a\x20\x1a\x4b\x84\xd5\xe8\x0c\xce\x0e\x72\x84\ +\xb4\x94\x9b\x63\x95\x1b\xf4\x83\x64\x32\x69\xa9\xe1\x29\x3e\xb7\ +\x6f\x60\x02\x56\x3f\x7f\xbb\x03\x5c\xf6\xc6\x14\xc6\xfe\x8a\x80\ +\x68\x2c\x11\x56\xd5\x7b\x87\xc9\x65\xa9\xbb\xb3\x75\xf2\xd8\x05\ +\x94\xb0\x7e\xcf\xb2\x34\x9e\x4a\xa5\x4c\xa5\xf9\x15\x17\x61\xa5\ +\x55\x5d\xc2\xfa\x91\xdc\xec\xd4\x66\x35\x1f\x50\xd1\x01\x87\xbc\ +\x19\x68\x56\xd5\x99\x68\x2c\x11\x2e\x88\x3b\x82\xf5\x2e\xfc\x6e\ +\xc3\x06\x63\x24\x93\x4c\x26\x23\x00\x2b\xeb\xdb\x35\x5b\x5f\xb5\ +\x00\x85\x31\x81\x09\xf7\x5d\xd0\x2b\xcb\xeb\xdb\xb7\x2d\x11\xe1\ +\x08\xd6\xbb\xa8\xd8\x82\xee\xce\xd6\x49\x45\x96\xbc\x31\x81\x09\ +\x55\x7d\x78\x98\xdc\x9f\xf5\x55\x0b\x48\xa5\x52\xc6\xb2\x34\x0e\ +\xec\x95\x49\xf3\x6d\x7d\xd5\x02\x00\x16\x66\xa7\x36\x45\x64\xb4\ +\xd4\xb8\xc2\xc8\x82\x4f\xeb\x7d\x09\x00\xb8\x70\xa6\xe5\x51\x71\ +\x2b\x0e\xc8\x6b\xb3\xde\xb7\x80\x12\xad\xa8\xd9\x7a\xdf\x02\xe0\ +\xa0\x15\xc6\xa8\x0d\xba\x05\xba\x65\x8c\xda\xb5\x5a\xef\xc2\xf7\ +\xef\x78\x71\x2e\xf3\x06\x08\x57\x4c\xac\x12\x5e\x07\x76\xe1\xe0\ +\x00\x19\x54\xf1\x62\xf4\xf4\x0f\x34\x3a\x8f\x3b\x7f\x12\xb0\x06\ +\x60\xf2\xf4\x1e\x97\x00\x09\xd5\xbb\xb5\x3f\xb8\xb1\xdf\x2d\x50\ +\x4d\x23\xd2\x87\xc8\x78\xc4\x4e\x88\xe6\xf7\xe7\x3d\x67\xb8\x23\ +\xa1\xa7\x7f\xa0\x51\x42\xf5\xbd\xa2\x3c\x00\x0c\xaa\xe9\x82\x28\ +\x6f\x62\xc4\x8e\x0f\x8b\x4a\x9a\x00\x0f\x2a\x45\x30\x28\xa3\xb9\ +\xec\xd4\x7d\x37\x70\xe8\x66\xb4\xf1\xe5\xd3\x4a\x5b\xc7\xd9\x45\ +\x44\x9a\x80\x93\x04\x77\x3b\xda\x01\xde\xa1\x9a\xc8\x65\x33\x2f\ +\x03\xaa\xf9\x8f\xe0\x17\xaf\x0f\x09\xa8\xe3\xe3\x70\xe1\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x07\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xb9\x49\x44\x41\x54\x78\x9c\xed\ +\xd9\x51\x0d\x83\x50\x10\x05\xd1\xa5\xc1\x1a\x0a\xb0\x80\xac\x5a\ +\xa8\x02\xc4\x81\x8c\xd3\xe4\xcd\x18\xd8\xc9\xe4\xfe\xed\x0c\xe4\ +\x38\xaf\xe7\x38\xaf\x47\x3a\x7c\xe4\xf1\x7f\xa0\x00\x5a\x40\x53\ +\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\ +\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\ +\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\ +\x02\x9a\xe5\x03\x6c\xf2\xb8\x7e\x8d\xcf\xb4\x80\xd9\xb5\xc0\xcc\ +\xcc\xfd\xfb\xb2\x25\x2e\xbf\x80\x02\x68\x01\x4d\x01\xb4\x80\xa6\ +\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\ +\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\ +\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x96\x0f\ +\xf0\x02\x2e\x56\x08\x76\x9d\x62\x12\xf1\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x86\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x38\x49\x44\x41\x54\x58\x85\xed\ +\xce\x31\x11\x00\x30\x08\x04\x41\x26\x9a\xf0\x84\x1f\x0c\x13\x11\ +\x50\xee\xf5\xff\xb3\x11\x8b\xb2\x7a\xb2\x7a\x36\x1f\x6f\x33\xbe\ +\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xe0\ +\x03\xf8\x62\x04\x97\x5f\x3b\xc3\x6b\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x00\xcb\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x7d\x49\x44\x41\x54\x78\x9c\xed\ +\xd9\xc1\x0d\x80\x20\x14\x05\x41\xb4\x29\xba\xa6\x10\x8b\x12\xcb\ +\x58\x13\x66\x1a\xf8\x2f\x1b\x6e\x8c\x11\x9a\xeb\xdd\x73\xbd\xbb\ +\xdc\x70\x97\xc7\xff\x40\x80\x7a\x40\x4d\x80\x7a\x40\x4d\x80\x7a\ +\x40\x4d\x80\x7a\x40\x4d\x80\x7a\x40\x4d\x80\x7a\x40\x4d\x80\x7a\ +\x40\x4d\x80\x7a\x40\x4d\x80\x7a\x40\x4d\x80\x7a\x40\x4d\x80\x7a\ +\x40\x4d\x80\x7a\x40\x4d\x80\x7a\x40\x4d\x80\x7a\x40\xed\xf8\x00\ +\x57\x79\xbc\xfe\x1a\x1f\xa3\x7f\x01\x4f\x7c\x1f\x00\x00\x00\x00\ +\x00\x00\x00\x4e\xf0\x01\xb9\x04\x09\xb0\x92\x01\xea\x01\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x0c\xd6\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x0c\x88\x49\x44\x41\x54\x78\x9c\xe5\ +\x9b\x5b\x6f\x5b\xc7\x11\x80\xbf\x25\x45\x8a\x94\x28\x89\x92\xad\ +\xbb\x64\xc9\x4e\x9a\xc2\x41\xe0\x26\x45\xd1\xa0\x48\x0a\xf4\xa9\ +\x7d\xe9\x7b\x81\x16\xfd\xa3\x7d\x2a\x50\xb4\x0f\x41\x90\x36\x4e\ +\x52\x20\x69\x92\xc6\x96\x6c\xc9\x37\x5d\x48\x49\xa4\x2e\xe4\xf4\ +\x61\xf6\x1c\xee\xd9\x33\x87\xa4\xe4\xf4\xc9\x03\x10\x24\x77\xf7\ +\xcc\xce\xcc\xee\xce\x6d\xe7\x00\xb2\x05\xe2\x78\xe3\x40\x9c\xf2\ +\x9e\xfe\x78\x93\x84\x90\xe3\xf9\x4d\x12\x42\x96\x57\x97\xed\xe0\ +\x0e\xf0\x18\x9c\x14\x3c\xdc\x00\x6e\x19\x1d\x25\x60\x32\x8b\x2f\ +\x6d\xaf\x0d\xa1\x66\x12\x10\xe0\x62\xc8\x98\x73\xa0\x67\xb4\x77\ +\x81\xbe\xd1\xfe\x12\xdc\xa9\x8d\x2a\xcf\xa3\x1b\x35\x00\x64\x1b\ +\xb8\xed\x09\x3d\x01\x5e\xf8\x89\xa7\x80\x39\xdf\x2e\xc0\x59\xd0\ +\x3e\xeb\xdb\xfa\xbe\x1d\x8f\xa3\x0a\x34\x81\x8a\xef\x3f\xf7\x34\ +\x54\xfd\xf7\x25\x70\x04\x97\xa7\x50\x39\xf2\x6d\x53\xa8\x20\x9d\ +\x9f\xff\xc4\xff\x9f\xf2\x6d\x0e\x68\x01\xa7\xbe\x7d\x29\xe8\x7b\ +\x01\xee\x71\x31\x6f\x85\x52\x92\x2d\x90\x09\x90\x8f\x40\x56\x8d\ +\x31\x6b\x20\x0b\x46\xfb\x06\xc8\xbc\xff\x3d\x05\x72\x0f\xe4\xae\ +\xff\xcc\x80\xdc\x01\x19\xb2\x23\xa4\xee\xc7\x2c\xa8\xe0\xe5\xae\ +\xc7\x31\xe1\xfb\xe7\x40\x36\xf3\x47\x55\x9a\x05\xed\x1b\x20\xbf\ +\x06\x29\x5f\xf3\x88\xcb\x04\xc8\x9f\xf5\xc1\x5c\xdf\x36\x48\xc5\ +\x68\x7f\xdb\x3f\xb7\xe2\x27\x5b\x8e\xf0\xdd\x1b\x73\x72\x3c\xe3\ +\x25\xff\xdb\x79\x46\xb6\xa0\x75\x4b\xdb\xe5\x2d\x83\xd9\x32\xc8\ +\x4f\x8c\xf6\x09\x90\x3f\xda\xbc\x14\x13\xf0\x91\x7f\x30\x92\x9a\ +\xac\x17\x30\x7f\xc7\x7f\xb6\xed\x15\x96\xed\x6b\x4c\x4e\x60\xa2\ +\xe2\xf6\x59\x15\x4e\x7b\x49\xe7\xcb\xf5\x97\xb3\xcf\xa5\xbb\xb9\ +\x02\xf2\xab\x71\x27\xdf\x1e\x6c\xfb\x50\x63\xca\x14\xc8\x6d\x63\ +\xfc\x2a\xc8\x07\xba\x7d\x4d\x7c\xf3\x5e\x79\x5e\x13\x64\x56\xb7\ +\xbc\xd9\x37\x07\xf2\x00\x64\xd1\xe8\x6b\xfa\x67\x23\xcb\x26\x9b\ +\xfa\xc9\x82\x71\x26\xe4\x17\xe0\x3e\x0d\xfe\x27\xca\xa3\x07\xec\ +\x01\x21\xa3\xab\x70\x79\x0b\x2a\x5f\x0e\xe1\x64\x0d\x78\x5a\xd0\ +\x97\xda\xe1\x1b\x3c\x0b\xf0\x00\xba\x4f\xa0\xf6\x2a\x68\xeb\x28\ +\x5d\x94\xc9\x29\xbc\x98\x37\x98\x30\x90\xc6\xc4\x34\x50\xe6\x1f\ +\xa0\x5a\xbd\xed\xc7\x6c\x01\x2f\x54\xa1\x0f\x05\xf1\xc4\x2c\xf9\ +\xff\x89\xe9\x4a\x34\x78\xd8\x46\xd0\xf6\xc2\xa0\x25\x86\x17\x20\ +\x82\x32\xbc\xe7\x9f\x5d\x02\x7e\x06\x7c\x0e\xcc\xa0\x16\x22\x81\ +\x9c\xd9\x8c\x04\x20\x0d\xd4\xcc\x24\xff\x37\x80\x36\xb8\x5d\x3f\ +\x51\x05\x35\x5d\x9b\xc0\xd7\xe0\xae\xf4\x7c\xb9\x13\x72\x20\xce\ +\x8f\x9b\x42\x7d\x81\x6f\x47\x98\x9f\xf8\xd9\x45\x60\x1a\x35\xa9\ +\x7b\xf6\xb3\xd2\x86\xfa\x0b\xd4\x9f\x58\x01\x7e\x00\x16\x80\xcf\ +\x80\xe7\x80\xb7\x3c\xec\xf8\xe7\x7b\xaa\xdb\xdc\x55\xd1\xc4\x5b\ +\x03\xf3\x26\x5b\x59\xcd\x29\x1b\x5e\x0f\x7c\x1c\x29\x46\xcb\x4c\ +\x2e\xa1\xa6\x72\x46\x3f\x37\x05\x59\xf5\xca\x78\x3d\x6b\x55\xd2\ +\xfe\x99\x81\x7e\x91\x09\x90\xdf\x78\x2b\x11\xb6\x07\x8a\x51\xee\ +\xaa\x8e\x18\x40\xc9\x98\xb5\xaf\x13\xb2\x0b\xae\x17\x8d\x5d\x03\ +\xfe\x0e\xdc\x09\x84\x10\xac\xcc\x61\x53\x19\xe7\x10\xdc\x53\xdf\ +\x37\xe6\xaa\x9b\xe0\x9f\x75\x4f\x80\x03\xc5\x7d\xd8\xcc\xf7\x8b\ +\x03\xd6\x81\xbf\x01\xf7\xb2\x73\xba\x9e\xf2\x22\xeb\x18\x47\xc0\ +\x12\xc0\x14\x70\x16\x31\x0f\x7a\xe6\xbf\xf3\x5b\xe9\x31\x59\x21\ +\xa0\x1a\xb9\xd9\x57\xc6\xdd\xe5\xf8\x3c\x8e\x0b\xee\x52\x71\x37\ +\xfb\xd1\x6e\x08\x3d\xbc\x1e\xf0\x04\x3d\x7a\xe1\x90\x1e\xea\x29\ +\x4e\xc7\x58\x2d\x25\x38\xe7\x57\x2f\x00\xd9\x46\x95\x4c\x29\x30\ +\x77\x07\xc0\x7d\xe0\xd2\x9b\xab\x57\xe8\xee\x09\x4d\x9e\x9f\xd0\ +\xdc\x04\x25\xe8\xfa\xe3\x56\x3b\xc4\xf6\xf7\xa7\x81\x2e\x48\x78\ +\x66\xfb\x3a\x56\xee\x03\x47\xe8\xca\x7f\xad\x63\x05\xa0\x03\x9d\ +\x13\xa8\x2f\x92\xd1\x67\xee\x08\xe4\xa7\xf1\x04\x63\x58\x01\x79\ +\x0b\x2e\x2a\x50\x9d\x46\x15\xd3\x29\x83\xad\xbd\x0b\xfc\x0e\xf8\ +\x4b\x01\x03\x01\x74\xe6\xa1\x9e\x04\x3f\x3e\x4e\xa8\x1d\xf9\xce\ +\x79\xd4\x52\xf8\x1d\xd5\x39\x87\xfa\xe1\x10\x64\x5d\xd4\x3c\xfe\ +\x06\xf8\x24\xa0\xd9\x2b\xcf\x7a\x0d\xb8\x0d\x72\x1e\x2d\x66\x6e\ +\x25\x62\x01\xc4\xd1\xe1\x5d\x60\x1a\x26\x1f\xaa\x12\x74\xfb\xd9\ +\xe1\xb2\x0e\xfc\x03\x0d\x70\x8c\x20\x43\x80\xee\x6d\xa8\x4d\x40\ +\xfd\x25\xb8\x4e\x01\x43\x47\xd9\xbf\x52\x07\x16\xe0\xa2\x06\xd5\ +\x93\xbc\xd6\x4e\x7d\x93\xbf\x02\x6b\xe0\xf6\x82\xce\x36\xc8\x09\ +\xba\x63\xdf\xf6\x9e\x6b\x42\x5b\x9f\xe8\xd8\xc7\x3a\xa0\x0a\x9c\ +\xfb\x09\xee\xa1\xab\xf2\x85\x4d\xb3\x2c\xa1\xdb\xbe\x87\xad\x13\ +\xa6\x81\x55\xa8\xb5\x55\x89\x15\x32\x6f\x80\xeb\xe8\x33\xd5\xb6\ +\x32\x18\x1e\xab\x30\xaa\xa3\x87\xfa\x02\x2b\x05\x88\xbe\xf1\x63\ +\xee\xf9\xe7\x3a\x64\x1d\xb9\x22\x2b\xc0\x06\xf0\x0c\xf5\x01\x8c\ +\x03\x7c\xd8\x04\xba\xe0\xba\x9e\xe0\x48\x31\x1e\xcd\x43\xbb\x86\ +\xae\xc2\xf9\x58\x3c\xdb\x70\x01\x3c\x85\xf6\x24\x1c\x2f\x60\x87\ +\xb4\x5d\xe0\x4c\xe7\x8c\xc1\x9d\xa1\x8b\xfa\x83\xe7\x29\xc7\x8b\ +\x25\x80\x06\xea\x3d\x2d\xe6\xb7\x7c\x02\xcd\x29\x70\xad\x6c\x5b\ +\x22\x84\xcb\xf7\x61\xae\x07\xb3\xaf\xcc\x47\x6f\x04\xb3\xaf\x60\ +\xf6\x52\x71\x5b\x47\xcd\xb5\x60\xae\x20\x16\x61\x07\x35\xdf\x2d\ +\xd4\xc2\x65\xc0\x12\xc0\x34\xaa\x3d\x0b\x94\x9a\x2c\xa3\x6e\xaa\ +\x01\xc7\x4d\xa8\x7c\x0f\xcc\x33\x7e\xec\x3d\x06\x88\x03\x16\xa0\ +\xf2\x9d\xce\x61\xc2\x73\xdb\x59\x72\x97\x40\x19\xdc\x31\xba\xb8\ +\x19\xb0\x04\x20\xa8\x69\xd9\x29\x20\x64\xc2\xb6\xf3\x32\x05\xa5\ +\x64\x22\x7f\x1c\xac\x60\xeb\xda\x10\x6e\xfb\x16\x94\x4a\x5e\xbf\ +\xc4\xc3\xae\x94\x36\xb1\x78\x3a\xd4\x23\x34\xda\x0a\x94\x07\x83\ +\x4c\xbf\x7d\x13\xd5\xb2\xe1\x2a\xcc\x82\x74\x81\x15\x98\xd9\x0f\ +\xfa\x5a\xc0\xbb\xc0\x13\xd2\x8c\x4e\x06\x92\xd4\x19\xa8\x4f\x61\ +\xe5\x05\xe7\xd0\x40\xe7\x07\xfd\x2d\xa0\x3b\x73\x03\xe4\x19\x03\ +\x3f\x23\xc1\x7f\xa6\x7d\x1c\x64\xd1\xb8\x63\xef\x0e\x27\x81\x59\ +\x0a\x31\x61\x35\x72\x49\x48\x99\x47\x83\x8d\x65\x4f\x64\x84\x9c\ +\x1e\x74\x66\xa1\x7e\x00\xc4\x41\xc6\x23\x4f\xd0\xd7\xc1\xe4\x2b\ +\x40\x1f\x3a\x67\x50\xdf\x05\x1c\x74\x6f\x41\x2d\xc9\x2f\x3e\xf3\ +\xdf\xce\xcf\xf9\x05\x9a\x2b\x0c\xe1\x15\x74\x66\xa0\x9e\x08\x2d\ +\x9c\xb7\x89\x2a\xbe\xbe\xee\x86\x54\x57\x25\x79\xcb\x4c\xc2\xc6\ +\x5a\x99\x45\xe0\x4b\x90\xaa\x27\xe0\x25\xb8\x43\x34\xd3\x73\x96\ +\x8f\xfc\xa4\x01\xf5\x32\xb8\xe7\x79\x54\x82\x67\x7e\x01\x38\x46\ +\x57\xec\x1b\x63\x77\xb5\xfd\xf8\x32\xba\xe2\x07\x9e\x8e\xff\x68\ +\x5f\x2e\x7a\x3b\xf1\xa6\xcf\x67\x7f\x43\x9a\x64\x1f\x15\x98\x17\ +\x9a\x6c\x02\x4f\xe0\xa4\x03\x8d\x29\xb2\xe1\xb1\xa9\x03\x4a\xa8\ +\x04\x6f\x83\xdb\x09\xec\xf7\x2d\x6c\xe5\x37\x0d\x47\x05\x69\x68\ +\xa5\x00\xcd\xf4\x6e\x01\x4f\x87\x87\xc4\xa9\x2f\x7f\x1f\x0d\x67\ +\x87\x05\x52\x27\x18\xbe\xbd\x5f\x08\x9f\xb9\x72\x27\xa8\xb7\xba\ +\x01\x8d\x03\xf4\x48\x65\xa0\x48\x09\x2e\xe5\xe3\x01\x28\x20\xbe\ +\x01\xf3\x47\x46\x7b\x02\x65\x25\xb4\xf2\x90\x9c\xb3\x94\x9b\x3a\ +\x51\x78\x9f\x61\xdf\x3f\x84\xb4\x14\x08\x20\x37\x4e\x7c\x6a\x7c\ +\xcd\xea\xb5\x04\xb0\x00\x58\xf6\xdf\xba\x84\x18\x07\x56\x18\x24\ +\x34\x0c\x8f\x31\x81\x9c\x93\xf3\x12\x2e\x8c\xd4\x7b\x06\x8a\x84\ +\x69\xd1\xfa\x0a\x43\x60\x05\x47\xe0\x5a\xe1\xec\x28\xc1\xf4\x07\ +\x3b\xa7\x30\x94\x36\x3c\x3c\xd7\x85\xea\xa8\x7c\xdb\x35\x72\x0d\ +\xee\x0c\x55\xe6\x19\x88\x05\x30\x41\x71\x54\x77\x13\x9b\x5e\x83\ +\x6e\x64\xde\x62\x21\x0c\xbd\xb1\xb9\xa9\x1f\x51\xf4\x5c\xae\x3d\ +\xb6\x02\xcb\x70\x65\x69\xf3\xc0\x3f\xc8\xb4\x97\xec\xf6\x14\x9a\ +\x50\x7b\x66\xd0\x21\x20\x8f\xd1\x24\x0b\xc0\xa3\x02\xfd\x32\x62\ +\x85\xbb\x7d\x8d\x34\x73\xd0\xc3\xce\xd6\x8e\x8a\x05\x7a\x15\x98\ +\xb8\xce\xf6\x4f\xec\x75\x11\xf4\x47\xf4\xbf\x26\xd4\x1c\xc5\x47\ +\x70\xac\x79\x23\x01\x94\x9f\xa1\xf6\x37\xc6\xd5\xb3\x11\x8e\xcc\ +\xf2\x1e\x90\x9a\xa4\x10\xd2\x6d\xff\xc8\x7f\x46\x58\x87\x42\x28\ +\x12\x40\x19\xdb\xb3\xcc\xcd\x11\xeb\x80\x2e\x51\xbc\x1c\x40\x11\ +\xb3\xc3\x08\xbf\xca\xcf\x11\x9f\xf9\x51\xd6\x61\x28\x14\x8d\x1f\ +\x5b\x39\xc6\x02\x48\x72\xe7\x39\x6d\x79\x03\x22\x12\xe8\x93\xde\ +\x27\x16\x29\x3c\x4b\x08\x32\x43\xea\xe9\xdd\x78\xee\x00\xc4\xe7\ +\x17\xb3\x60\x99\xc1\x23\x06\xb7\x38\x3f\x06\x3c\x07\x56\x46\x68\ +\x7b\x22\x21\x94\x50\xaf\xcd\xb8\x70\xc9\xc0\x98\xbe\x49\x12\x4e\ +\xe7\x05\x6a\x09\xc0\x01\xfb\xe4\x2f\x12\x8b\xa4\x7d\x00\x6d\x43\ +\x6f\x64\xe0\x25\xf0\x21\x23\x8b\x13\x9c\xa0\x61\xf8\x47\x0c\xbf\ +\x13\xc4\x67\x80\x8e\x8b\x10\x0d\x7e\x8a\x43\xad\xcd\x2e\x63\xe8\ +\x00\x00\xf1\x8e\xd0\x53\x15\x42\x7a\xb3\x73\x80\x79\x1b\xcb\x25\ +\x34\xaa\x43\x28\x4d\xee\xeb\xfe\x05\x6c\x6a\xde\xa0\x08\x64\x8e\ +\xc1\xe5\xcb\xa6\x45\xf0\x00\xe6\x26\x31\xd3\x6d\xed\x45\xd2\x88\ +\x55\x9a\x68\x6e\xe3\x91\xc7\x35\x32\x1f\x00\x9a\xe7\x9f\x04\x77\ +\x0e\xec\x28\x12\xd9\x40\xad\xc3\xbc\x8f\xbd\x43\x44\x4b\xc0\x19\ +\xc8\x3b\x44\x91\x16\x9a\x81\x59\x43\xa3\xba\x26\x70\x01\x17\x5b\ +\x5e\xc7\x58\x4e\xcf\x29\x1a\x19\x2e\xe9\x58\x1e\x00\xff\x06\x89\ +\x4d\x73\x92\xd9\x49\xf2\x01\xc9\xff\x24\x84\xee\x78\xfc\x7b\x7a\ +\xaf\x09\x3e\x83\x9d\xf3\x49\x62\x01\x74\x7c\xdb\x32\x7a\x1e\xd1\ +\x0b\x05\x8e\x3c\xbd\x02\xec\x67\xb7\xb1\xa0\xb9\x43\x59\xcf\xe6\ +\x10\xd3\x73\xf7\x4f\x70\xed\x60\x8e\x82\x3c\xa3\x05\x02\x9a\x38\ +\xd9\x8d\xe6\x5c\xd3\x60\x2d\x61\x3c\x09\x87\xc5\xa1\xbb\xfa\x38\ +\xdb\x0e\x0c\x0a\xb6\x32\xd9\xe9\xf8\x08\x84\x57\xd7\x16\xec\xa1\ +\xc1\x8d\x05\xcf\xc8\x14\x56\xe0\x6f\x65\x5f\xfb\x6e\x30\xb6\x0e\ +\x2b\x14\xe6\x24\x93\xc0\xcb\x84\xe4\x3a\x3e\xa3\x38\x8b\x94\xe0\ +\x85\x6d\x0a\x5d\x5f\x89\xb2\xea\x6d\xdc\x15\xd0\xf2\x67\x30\xc9\ +\xdb\xbf\x0e\xf3\x09\x04\x42\x68\xdd\x46\x13\x24\x56\x4e\xb2\x1c\ +\xd0\x18\xf7\x2d\xa3\xd6\x68\x2c\x25\xd8\x46\xed\xa5\x19\x3f\xfb\ +\x6d\x6e\x64\x5f\x01\x38\x83\xc6\x32\x9c\x9c\x8d\xe1\x25\x5e\x03\ +\x9c\x28\xce\x99\x15\x06\x65\x77\x31\x2c\x53\x7c\xbc\x92\x1a\x85\ +\x9c\x59\xb5\x04\x70\x86\x2a\x97\x72\x41\x86\x15\x38\xee\x90\xbb\ +\xf7\x4f\xb7\xfd\x57\xd0\x38\xd3\x73\xfa\x63\x81\xac\x2a\x4e\xbe\ +\xc2\xf4\x18\xa5\x01\xad\xae\x2d\x74\x99\x83\xb3\x2e\xca\x53\x4e\ +\x78\x45\xf9\x80\xc4\x66\xbe\x6d\x13\xd4\x3c\x54\x84\xc9\x31\xc9\ +\xb9\xb7\xa7\xe8\x96\x5b\x85\x4e\x41\xa1\xd3\x38\x70\x3e\xab\x38\ +\x92\xea\x4f\xd3\x6d\x9e\x04\x66\x61\x2e\x4e\xd6\x26\xb0\x02\x53\ +\xd3\x01\x4f\x19\x88\x05\x70\x41\x9a\x34\x70\xde\x74\xc9\xba\x8d\ +\xd7\xed\x2b\x72\x4a\xd8\xee\xed\x15\xb0\x07\xf5\x4b\x55\x5c\xb2\ +\x38\x9e\xaf\x2f\xce\x8f\x5d\x81\x49\x8f\x23\x3c\xf3\xa1\x10\x28\ +\x01\xab\x76\xfa\x0e\xd4\x34\x5f\x54\xc0\x7d\xeb\x1b\xea\x44\x56\ +\x20\x36\x83\xf1\x95\xd3\x27\x68\x39\x1a\xc0\x32\x5a\x27\xd4\x0f\ +\xc6\x5d\x02\xbf\x45\xaf\xc7\x97\x0d\x9d\x97\xa4\xa0\x4e\xd1\xf8\ +\xfc\x3d\x2f\x84\x61\x89\x0f\x21\xad\x35\xa0\x81\xba\xd1\x56\x4d\ +\xcf\x25\xf0\x7b\xe0\x53\x06\x97\xa3\x89\x19\x4c\xca\x6b\x27\xf5\ +\x66\x3b\x85\x12\xc3\xdd\x67\xd9\x42\x0b\x0f\xc2\xb6\x86\xf7\x08\ +\x37\xa2\xf6\xa4\x0e\x6f\xcd\x7f\x1b\x56\x43\x1a\xdc\xa8\x46\x30\ +\x7d\x7e\x05\xf3\x52\x45\xaa\x68\x09\xed\x1c\xc8\xbb\xb6\x4e\x90\ +\xf7\xf3\xd6\x4a\x3e\x64\x8c\x1a\xa1\x43\x90\x20\x23\xeb\x4e\xe0\ +\xa4\xab\xf5\x80\x29\xa2\xf0\x8a\xba\x0f\xee\x11\xea\x25\xbe\x06\ +\xb3\xe3\x82\xcc\xa0\x29\xfb\xef\xd1\xcc\xcf\x0e\x79\xc5\xb8\x81\ +\xa6\xe0\xc3\x0b\x9e\xe4\x6e\x22\x03\x96\x00\xba\x40\x95\x4c\x49\ +\xec\xcc\x0b\xa8\x4c\x7a\xc9\x16\x85\xb4\xfb\xd0\xaa\xaa\xce\xb8\ +\x56\x5d\xee\x98\x20\x65\xc5\xdd\xaa\x90\xaf\xfa\x08\x14\x63\x7b\ +\x11\xba\x1d\x32\x1a\x5f\x2a\xa8\x6e\xcb\xd5\x28\x58\xb1\x40\x09\ +\xdc\x9e\x6e\x79\x79\x16\x28\xa0\xa7\xa8\x46\xee\x01\xff\x0d\x98\ +\x0f\x24\x3f\x77\xe0\x05\x94\x84\xbf\xa1\x0b\x7c\x13\x48\xbc\xbf\ +\x55\x94\xd1\xa7\x30\x27\x51\xbf\x04\x39\xc6\xfb\xd0\x68\x91\xb9\ +\xbe\x93\x8a\xd2\xe3\x76\x40\xee\x1a\xcc\x66\xe0\x25\x69\x2e\xc0\ +\xed\xa2\x75\x36\xc9\xd6\x17\x54\xf1\x54\xc8\x66\x8d\x22\x1c\x4e\ +\x54\x80\xec\xa3\xb5\x3f\xf7\xc6\x08\x97\x0d\x68\xdd\x46\x9d\x9b\ +\x25\xe0\xb9\xee\xb0\x9c\x9d\x9f\x26\x5d\xd5\xe3\x26\xba\xea\x65\ +\x54\x79\x76\xd0\xda\xe6\x25\x65\x1e\xd0\xcb\xd8\x8c\x33\x14\xed\ +\x00\x77\x9a\x0d\x57\xdd\x1e\x5a\xc3\xbf\x81\x46\x66\x9f\xa3\x42\ +\x78\x00\xe7\x27\x50\x3d\x52\x22\x0b\xcd\x5b\x5f\xe7\x68\x24\x15\ +\x9b\x49\x1b\x80\x83\x0b\xbf\xbb\xaa\xc9\x0b\x14\x21\x1c\x7b\x66\ +\xbc\xa9\x33\x1d\xcb\x65\xc5\x2f\x4b\x1e\x6f\x12\x23\x7c\x00\x3c\ +\x04\x0e\xc0\xbd\x0c\xc6\x97\xe3\x7b\x46\xeb\x08\xc4\xcc\x74\x3d\ +\x21\x0f\xd1\x82\x45\xd0\x2b\xef\x65\xdf\xbe\x1f\xb4\x1b\x20\x62\ +\xf7\x8b\x83\xea\xa4\x67\xb0\x53\xe0\xc5\xad\x8f\xc0\x7d\x05\x4c\ +\xc1\xd1\xf7\xd9\xeb\x39\x71\x9e\xb6\xf8\xcc\x8f\x93\x42\x93\x3b\ +\x03\xe7\x27\x53\x2e\x5f\xcf\x5a\x07\xf0\x66\xe8\x7d\xec\x44\x49\ +\x32\xe6\xff\x50\x2e\x0f\xba\x00\xf2\xf3\xbc\xf9\x95\xa6\x5a\x8a\ +\x5c\xb9\xfc\x1d\xcc\xb2\x5e\x1b\xf9\xc7\xd8\x2f\x4c\xac\x92\x7b\ +\x61\x42\x1c\xfa\x82\x85\xf1\x02\x43\x3a\x66\x7b\xcc\x89\x43\x9c\ +\x05\xcf\x88\x43\xdf\x18\xf9\xa5\xd1\x57\xce\xfa\x2b\xa9\x10\xaa\ +\x8c\xff\xc2\x44\x8a\xe8\x4f\x05\x4e\xc8\x46\x5e\x08\x00\xf2\x1e\ +\xfa\xca\x4a\xee\xa5\x04\x5e\xeb\x95\x99\xb4\xad\xe4\x9d\x9f\xb7\ +\x40\xde\x31\x9c\x9f\xb2\xa5\xe5\x3d\xf3\x7f\xc8\xe3\x2b\x9e\x3c\ +\x91\x5a\x59\xa5\x16\x7b\x80\xe0\x77\x82\x71\x7d\x2d\x1b\x7e\x6b\ +\xde\xd3\x4f\x2b\x74\x9e\x2a\x8c\x7e\x69\x6a\xca\x8f\x09\x04\x2f\ +\x2b\x0c\x5e\xbe\x2a\x7a\x39\x6a\x1e\x33\x66\x91\x2d\xcf\x43\x29\ +\xbf\x9b\x15\x62\x44\x86\x93\x23\x9b\xa8\xb6\xf5\x35\xba\xb4\xfc\ +\xef\x1a\x6a\xe6\x1c\x7a\x01\x72\xc1\xe0\xb5\xb9\x19\x40\xa0\x37\ +\x0d\xe5\xc4\x29\x4a\x4a\x64\x7b\xc1\xff\xe4\xf6\x26\x79\x6d\x2e\ +\x28\x97\x4d\xe9\xeb\xfa\x71\x0e\x35\x61\xa7\xfe\xf7\x24\xaa\xc4\ +\x7d\x01\x06\x1d\x54\xa1\xce\x06\x78\xf6\x06\x4e\x93\xed\xc0\x8d\ +\xb8\xa2\x8e\x41\x26\x30\x4a\xcd\x3c\x9e\x3a\x79\x2d\x1b\xbf\x38\ +\x59\x42\xaf\xca\x92\x23\x54\x65\xe0\x5f\xe0\x99\x38\x24\x6b\xf3\ +\xac\x17\x27\x85\x41\xe2\x33\x06\xa3\xb4\x36\x7d\xac\x88\xc7\x37\ +\xf7\xd5\x59\xab\xe1\x0d\x80\x0c\xcf\x6f\x1a\xf3\x09\xa8\x10\xfe\ +\x07\xb4\x0a\xfd\x7e\xcf\x22\x5b\xc2\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x02\x1b\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xcd\x49\x44\x41\x54\x58\x85\xed\ +\x96\xb1\x4a\x23\x51\x14\x86\xbf\x93\x64\x13\x54\xb0\x70\x8b\x2d\ +\x04\xc5\x17\x30\xa0\x23\x2c\x82\xec\x2b\x2c\x8a\x8a\x85\x96\x8e\ +\x10\x89\x08\x22\x36\x56\x29\xb6\x08\xbb\xab\x23\x2b\x9b\xb4\x56\ +\x2a\x79\x02\x1b\x41\x04\xc1\x04\xf4\x09\x54\x2c\x54\xd0\x42\x0b\ +\x41\x50\x8f\x85\x4e\x4c\xa2\x33\xce\x24\xd1\x14\xe6\xaf\xee\x9d\ +\x39\x73\xff\x6f\xce\x3d\x73\xe6\xc2\x67\x97\xb8\xdd\xec\x1c\x4d\ +\x36\x85\x1b\xc2\x09\x90\x7e\x84\xf6\x8a\x9c\x94\x23\x84\x8c\x6a\ +\x64\x3e\x97\x36\xaf\xdf\x04\xe8\x1c\x4d\x36\x7d\x69\x8c\x6c\x0b\ +\x44\x2b\x32\x7e\xc1\xc1\x3e\x1a\xe9\xb5\x21\x02\x4e\x81\xe1\x86\ +\x70\xa2\xda\xe6\x00\x02\x51\x91\x9b\x84\x3d\x77\x04\x00\xe9\xaf\ +\xb6\x79\x5e\xca\x80\x3d\x0c\x39\xfb\x17\xef\x79\x36\x15\x77\xad\ +\x97\xb7\x64\x98\x96\xbe\xb6\xb6\x4b\x06\x3e\x46\x75\x80\x17\x35\ +\xd0\x3d\xbe\xd0\x26\x01\xf9\x81\x16\x5f\x37\x26\xac\x49\xa7\x45\ +\x44\xe5\x5e\x85\xfd\x8e\x8b\x6f\x3b\xeb\xeb\x43\x77\x65\x03\xf4\ +\x98\x8b\x33\x8a\xfc\x42\x5f\x29\x4e\x65\xc9\x69\x11\x45\x41\xe1\ +\xb0\xe5\x74\xab\x7b\xfc\xef\x70\x2e\x3d\x7d\xe2\x15\x20\xbf\x05\ +\x86\x69\x8d\x28\x92\x2c\x85\xf2\x23\x85\xbe\x80\x04\x57\x07\x07\ +\xd7\x82\xbe\x01\x40\x66\xcb\x35\x2e\x85\x38\xf8\x7a\xf6\xdd\x6b\ +\x7c\xc1\xdb\x6a\x69\xd7\xfb\xe7\xdd\x54\x7e\x0a\xda\x6a\xcf\x45\ +\x89\x02\xdb\x3e\x01\x8a\xff\x0b\xd9\x54\xdc\xb1\xe8\x4a\x65\x98\ +\x16\x40\x2c\x0f\x24\xea\xf9\xeb\xaa\xf9\x67\x58\x07\xa8\x03\xd4\ +\x1c\xa0\xec\xae\xe7\x2a\x65\xc9\x30\x2d\xc7\xd6\x8d\x72\x64\x0f\ +\x6b\x93\x01\x21\x63\x0f\xdf\x27\x03\x2e\x7a\x3a\x94\xce\xdb\xf3\ +\x8f\xcb\xc0\x63\xda\xff\x14\x9e\x88\xa1\xa0\xfd\x1a\xa6\x75\x09\ +\x34\x57\xc5\x4c\x74\x2c\xfb\x7f\x6a\xc5\x4b\xe8\x73\x06\x54\x37\ +\xaa\x62\x0e\xb7\x12\x08\x6d\x7a\x0d\xce\x03\x48\x28\x34\x0d\x9c\ +\x57\xea\xae\xca\xdc\xee\x72\xec\xd8\x37\xc0\xee\x72\xec\x58\x82\ +\xc1\x2e\x54\x33\xc0\x95\x5f\x5f\x90\x3d\x44\x47\x72\xe9\xf8\x6f\ +\x9f\xcf\x7e\x72\x3d\x00\x27\x99\x79\x91\xf6\x77\x59\xd9\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x95\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x47\x49\x44\x41\x54\x58\x85\xed\ +\xd7\xb1\x0d\x00\x20\x0c\x03\x41\x83\xd8\x29\x2d\x13\x67\x02\xa4\ +\x6c\x16\x31\x84\xe9\xf8\xef\x63\x5d\x1b\x89\x8c\x22\xbb\x22\xbb\ +\x9c\x8d\x65\x1a\xb6\x79\xaf\xe9\x0e\x00\x00\x00\x00\x00\x00\x00\ +\x00\x00\x00\x00\x00\x00\x80\x9b\xf7\x19\x0d\x9d\x47\x8e\x8f\xbb\ +\xb2\xd3\x06\x7c\x18\x63\x85\x7e\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x01\x35\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xe7\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\xb1\x11\xc2\x30\x14\xc5\x9e\x19\x22\x13\x31\x01\xc7\x06\xd0\ +\x30\x11\x0d\x23\x70\x4c\xc0\x34\xa9\xb2\x85\x29\x08\x5d\x3a\xdb\ +\x88\x3b\xa4\xea\x17\xff\x12\x7d\xf5\x4e\x44\xe4\x9f\x29\xa3\x7f\ +\xb0\x3f\x9e\x0f\xa5\xe6\x9a\x24\xb5\xe4\xf2\xbc\xdf\x1e\x3d\xf7\ +\x5b\xd9\x8d\xfc\x78\x92\xac\xc7\x4c\x49\xa6\xcf\x61\x3d\xf7\x5b\ +\x19\x1e\x20\xef\x63\xb6\xe6\x5e\xfb\x4d\x7c\x23\xc0\x4f\x63\x00\ +\x5a\x80\xc6\x00\xb4\x00\x8d\x01\x68\x01\x1a\x03\xd0\x02\x34\x06\ +\xa0\x05\x68\x0c\x40\x0b\xd0\x18\x80\x16\xa0\x31\x00\x2d\x40\x63\ +\x00\x5a\x80\xc6\x00\xb4\x00\x8d\x01\x68\x01\x1a\x03\xd0\x02\x34\ +\x06\xa0\x05\x68\x0c\x40\x0b\xd0\x18\x80\x16\xa0\x31\x00\x2d\x40\ +\x63\x00\x5a\x80\xc6\x00\xb4\x00\x8d\x01\x68\x01\x1a\x03\xd0\x02\ +\x34\x06\xa0\x05\x68\x0c\x40\x0b\xd0\x18\x80\x16\xa0\x31\x00\x2d\ +\x40\x63\x00\x5a\x80\x66\xfc\xa3\xa9\x64\xd9\x9a\x7b\xed\xb7\x32\ +\x3c\x40\x4d\x4e\x49\xe6\x24\xf3\x3a\x77\xdd\x17\x11\x69\xe1\x05\ +\x2c\x27\x22\x30\x10\x9e\x42\xf3\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x01\x51\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x03\x49\x44\x41\x54\x78\x9c\xed\ +\xd6\x21\x4e\xc4\x50\x14\x85\xe1\x73\xfb\x9a\x0a\x04\x0a\x3c\x1b\ +\x20\x21\x81\x04\x8b\x83\x05\xb0\x06\xdc\x4c\x48\x58\xc0\x50\xcf\ +\x18\x40\xa2\xf0\x48\x12\x70\xd8\x51\x84\x1d\xa0\x48\xc8\x38\x04\ +\x99\x4c\xda\x5e\x2c\x79\x0f\x70\x7d\x93\xd0\xff\x93\xe7\x56\x9c\ +\x1e\xd3\x4a\x00\x00\x00\x00\x00\x00\x00\x00\x00\xc0\x20\xd8\xdf\ +\x67\xb7\x83\xc9\x79\xc8\x53\xa5\x1f\x4f\x52\xa7\xba\xee\x7e\xbb\ +\xff\x38\xc0\xee\xc9\xc5\x86\x59\x35\x95\x74\x2c\x69\xad\xa7\x6e\ +\xb9\x2c\xe4\x7e\xdf\x56\xc5\xf8\xf9\x7a\xf4\x16\x1f\x93\x01\xf6\ +\x47\x97\xeb\xcd\x52\x2f\x26\x6d\x65\xa9\x97\x8b\x69\x1e\x9a\x6e\ +\x7b\x76\x73\xfa\xfe\x3d\x2e\xe2\xe7\xda\xa5\xea\x7f\xf7\xf2\x92\ +\xe4\xda\x6c\x42\x31\x8d\xe3\x64\x00\xb9\x1d\x66\x29\xb4\x02\x26\ +\x1d\xc5\x59\x3a\xc0\xc0\xa4\x03\x98\x3f\xae\xa0\x47\x16\x2e\x3d\ +\xc4\x59\x32\x40\xa8\x34\x71\xe9\x35\x4b\xa3\x9c\x4c\xf3\xb2\xed\ +\xce\xe2\x38\x19\x60\x76\x35\xfe\x08\x65\xb1\x27\xe9\x56\xd2\x67\ +\x8e\x6e\x3d\x5b\xc8\xfd\xae\x2d\x6d\x27\xfe\x02\x48\xfc\x08\x01\ +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x43\xf1\x05\xad\xf1\x3c\x35\ +\x36\x50\x8e\x69\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\ +\x00\x00\x01\x8b\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x3d\x49\x44\x41\x54\x58\x85\xed\ +\x93\x3f\x2f\x43\x61\x14\x87\x9f\x73\x5b\xc1\xd0\x88\x6f\xd0\x5d\ +\x62\xbb\xda\xc9\x62\x34\x48\x2b\x6c\xc2\x66\xf0\x09\x24\x12\x3a\ +\x58\x7c\x01\x7f\xd2\xc1\xaa\xf4\x76\x31\x4b\x2c\xa2\x9d\xd4\x07\ +\x10\x2c\xc2\xa2\x93\x84\xd4\xfb\x33\x50\x4d\x6c\xf7\xbd\xc9\x5d\ +\xdc\x67\x3b\xc9\x7b\x7e\xe7\xc9\xc9\x79\x21\x23\x23\xe3\xbf\x63\ +\xb1\x5e\x4b\x56\x6a\xc9\x01\xbc\x9b\x4d\xde\x54\xac\x97\x54\x20\ +\x88\xf5\x7a\x67\x28\x3c\x2a\xbd\x2e\x35\x94\x4b\x57\xa0\x66\x4e\ +\xd8\xf2\xa0\x7c\xcc\xab\x9f\xae\x00\xd0\xa9\xda\xa9\xd0\xee\xa0\ +\x2e\x45\xae\x9b\xaa\xc0\xb7\x44\x6e\x0b\xb8\xf8\x29\xa7\xcb\xd1\ +\xe7\xbe\xaf\x40\xbc\x23\xfc\x43\x29\x72\x1a\x26\xd9\x7a\xbb\x62\ +\x47\x71\x33\xbc\x36\x30\xa0\xdd\xb5\xe1\x11\x4a\x87\x61\x53\xb3\ +\xa9\x0a\x50\x33\x37\xde\xb7\xc2\x6f\x98\xe9\x32\x5d\x01\xe0\x05\ +\x3e\x80\x7b\xdf\xfe\x64\x02\x92\x15\x46\x5c\x1d\x28\x02\xcf\x39\ +\x59\x31\x55\x81\x72\xe4\xb6\x91\xad\x00\x6f\x98\xcd\x5f\x2d\xda\ +\x43\xdc\x0c\xef\x5f\x30\x13\x69\xd5\xd0\x31\xe0\x84\x2d\x74\xaa\ +\x76\xee\x93\xe3\xb5\x81\xb0\xa5\x39\x43\x75\x00\x61\x1b\xbe\xc3\ +\xbd\x04\xc2\x33\x4d\x05\x52\x13\xc8\x9b\xb4\xd7\xa9\xda\x81\xef\ +\xf0\xf8\x02\x92\x05\x81\x1a\xc0\x04\xa6\x93\xeb\xdb\x60\x33\xc9\ +\x70\x80\x7c\xdc\x06\x83\x27\xe0\x6e\xac\x17\xac\x51\x33\x97\x54\ +\x20\x23\x23\x23\xe3\x0b\x46\x70\x62\xa1\x9b\x7f\x53\x6a\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\xb2\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x64\x49\x44\x41\x54\x58\x85\xe5\ +\xd6\x31\x4e\xc3\x30\x14\xc6\xf1\xff\x73\x93\x72\x03\x3a\x70\x82\ +\x96\x89\x89\xb9\x8d\xc4\x58\x04\x5c\xa1\x03\xb7\xf0\x35\x90\xe8\ +\x15\x2a\x04\x2c\x88\x42\x7b\x08\xa0\x9c\x80\x01\x26\xf6\xd2\x98\ +\x81\x86\xa2\xa6\x21\x76\xe2\x84\x01\x8f\xf6\x93\x7f\x9f\x6c\xe7\ +\x29\xf0\xdf\x87\xd4\x89\x45\xfd\x41\x4b\x85\xe6\x12\xe4\x65\x3c\ +\x1a\x9e\x00\xa8\x7a\x71\xa6\x20\xfb\x60\x76\x92\xf9\x5a\x02\xac\ +\x70\xda\xc0\x73\x3c\x97\xc3\x64\xad\xf2\x2b\x48\xe3\x74\xef\xaf\ +\x86\xaf\xb5\x04\xc8\xc3\x2b\x0d\x60\x83\x57\x16\xc0\x16\xaf\x24\ +\x80\x0b\xee\x3d\x80\x2b\xee\x35\x40\x11\xdc\x5b\x00\x5b\xfc\xe0\ +\xe8\x74\xdb\xa8\x8f\x1b\x83\xbc\xdf\x8d\xce\x7b\xe0\xa1\x11\x39\ +\xe2\x13\x60\x4f\x30\xcd\x64\xbe\x54\x80\x02\xf8\x2e\xf0\x28\x71\ +\x70\x9c\xac\x15\xbe\x82\x12\x78\x74\x7b\x71\xf6\x56\x2a\x80\x2f\ +\xbc\x50\x00\x37\x7c\x31\x05\xd3\x01\x9e\x24\x0e\x7a\xeb\xb8\x73\ +\x00\xdf\xb8\x53\x80\x2a\x70\xb0\xfc\x0a\x6c\xf1\xa8\x3f\x68\xb9\ +\xe0\x60\x71\x02\x2e\xb8\x0a\x65\xe2\x82\xe7\x06\x28\x86\xcb\x4c\ +\xe2\x46\x77\x13\xee\xd4\x09\x2b\xc2\x53\x9d\x30\xa8\x0f\x5f\x4c\ +\x81\x0e\x6b\x9d\xb0\x51\x0e\x67\xb9\x69\x36\x1e\xf5\x07\x2d\x09\ +\xcc\xcf\x87\x99\xdd\x09\x0b\xe0\x6d\x90\x59\x3c\x37\xbd\xa2\x0f\ +\x53\x36\x6f\xea\x0b\x5f\xd5\x65\x9d\x90\x02\xd0\x5a\x2b\x15\x32\ +\xce\xc3\x01\x51\x21\xd7\x79\xf8\x7a\x5d\x16\xfe\x1d\x60\x39\xb6\ +\x80\x87\xdf\xfe\x64\xb4\xd6\x02\xd2\xfc\xaa\xcb\xc4\x53\x75\x36\ +\xfd\x00\xad\xb5\xc2\xae\x35\x8b\xe7\xba\xbf\x1d\x9f\xf9\xbe\xa6\ +\x95\x85\xff\xbc\x8e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ +\x82\ +\x00\x00\x03\xe0\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x92\x49\x44\x41\x54\x78\x9c\xed\ +\x98\x4d\x68\x5c\x55\x18\x86\x9f\xf7\xde\x50\x12\x45\xa1\xda\x9d\ +\xe8\x56\x5c\xb7\x64\x22\xa9\x68\x54\x4a\x9b\x42\xd2\x49\x20\xe0\ +\x4a\xb4\xfe\x81\x6b\x7f\x41\x44\xac\x60\xba\xd0\xad\x8a\x05\x57\ +\xae\x9a\x8c\xc9\xa2\x15\x4a\x35\x9b\xca\x4c\xd2\x14\x74\xd3\x9f\ +\x9d\xc5\x65\x44\xd2\xb8\x88\x3a\x73\x5f\x17\xa1\x32\xb9\xf7\x26\ +\x99\x99\xdc\x99\x44\x7a\x9e\xe5\xf9\xee\x39\xe7\x7d\xbf\xf3\x73\ +\xcf\x39\x10\x08\x04\x02\x81\x40\x20\x10\x08\x04\x02\x81\x40\x20\ +\x10\xb8\xb7\x50\xba\x60\x70\xc6\x1f\x4a\xfe\x00\x88\x0d\x89\xc0\ +\x7b\xa0\xab\x30\x0c\x12\x44\x40\xc3\xd6\xc7\x8b\x93\xfa\xa8\x39\ +\x9e\x49\x40\x69\x36\xa9\x03\x71\xaf\x04\xf6\x98\x46\x6d\x22\xea\ +\x6b\x2e\x88\xf6\x4a\xc9\x7e\x21\x93\x00\x5b\x67\xd0\xff\x7b\xda\ +\xe7\x22\x6c\xeb\x4c\xb6\x38\x87\xd2\x8c\x47\x90\xe7\x80\x07\x52\ +\x21\x03\x49\x17\xe4\x15\x49\x44\xd6\xd7\x9a\xa4\xb1\x6a\x59\x0b\ +\xe9\x8f\x73\x13\x00\x50\xaa\xf8\x30\xf6\xf7\xc0\xa1\x54\x0d\xe3\ +\xfd\x99\x04\x43\xa4\xac\xa7\x15\xa4\xe3\xb5\xb2\x96\xf3\xea\x6c\ +\x99\x00\x80\x23\x73\x7e\x3c\x6e\xf8\x12\xf0\x68\xaa\x23\x6b\xbf\ +\xcd\x04\x11\xe1\xcd\x7e\x24\x6e\xd7\x23\x1d\xbb\x3a\xae\x9b\x5b\ +\x55\xdb\x76\x13\xbc\x3a\xae\x9b\x49\xa4\x61\xe0\xc6\xe6\xbe\x90\ +\xb5\x7f\x36\x50\xe7\x98\x07\x6e\x34\xa4\xa3\xdb\x99\x87\x1d\x66\ +\xc0\x5d\x0e\xcf\xfb\x50\x5f\xc3\x17\x31\x47\x52\x5d\x03\x6a\xb4\ +\x23\xb6\x78\x1c\xa7\x6d\x08\x96\xfe\xe9\xd3\xe8\xf2\x98\x56\x76\ +\xaa\xdd\xd2\x28\x2e\x8f\x69\xa5\x2f\xd2\xb3\xc0\x0f\x9b\x23\x02\ +\x88\x51\x4b\x79\x2c\x14\x6f\x8c\x78\x9e\xf9\xcb\x71\xac\xe7\x5a\ +\x31\x0f\x6d\x9c\x03\xae\x8c\x6b\x6d\x60\x55\x27\x05\x95\x1c\x35\ +\xb1\x5b\x9c\x4d\x45\x60\x90\xf2\x97\xe0\xec\xc1\x7e\x9d\xbc\x32\ +\xae\xb5\x56\xdb\x6a\x6b\x1d\x2f\xbc\xa4\xf5\xfe\x83\x9a\x92\x7d\ +\x2e\x1d\x93\x89\x9c\x5d\x87\x85\x63\x23\x39\xab\x5b\xf6\xb9\xc7\ +\xea\x9a\xba\x38\xaa\xbf\xda\x69\xaf\x33\xc1\xb6\x4a\x95\x64\x1a\ +\xf4\x56\x8e\xc0\x44\x5d\x3a\x48\x35\x9d\xeb\x37\x21\xfb\x6c\x75\ +\x22\x7a\x17\xa9\xed\x7e\x77\x35\x62\x83\x15\xbf\x2d\x7b\x3a\xa7\ +\xd9\x04\x5c\x68\x12\x8c\x24\x9c\x3d\xb9\x4a\xef\x2c\x96\x75\xb6\ +\xd3\x76\x77\x3d\x65\x87\x66\xfc\x8a\xe5\x2f\xc9\x8c\x4c\x71\x49\ +\xd8\xc2\x7c\x62\xe9\xb5\xc5\xb2\x32\xcb\xb1\x1d\x0a\x59\xb3\xa5\ +\x8a\x27\xb1\xbf\x05\x0e\x34\x97\x5b\xb6\xac\x5d\x1d\x98\x8c\x23\ +\x65\x7f\x33\x7f\x0b\xbd\x50\x9d\xd0\xec\x6e\xda\x86\x02\x77\xee\ +\xa1\xf3\x7e\xde\xf2\x77\x88\xfb\x9b\xcb\x8d\x2d\x3a\x4e\x42\xde\ +\xb9\xfe\xcf\x44\x3a\xb5\x54\xd6\xe5\x0e\xdb\xdc\x44\xa1\xbb\xf6\ +\x93\x15\x0f\x26\xf6\x05\xe0\xe1\x54\xa8\x93\x4b\x54\x9e\xf9\xdf\ +\x13\xeb\xc4\xd2\xa4\x96\x3a\xd5\x98\xa6\xf0\xdf\xd6\xd0\xac\x9f\ +\x30\xbe\x04\x3c\x92\x0a\x19\x91\xec\xf8\x7f\x10\xd8\xb9\x97\x9a\ +\xdf\x84\x8e\x55\x27\x74\xbd\x38\xb5\x5d\x78\x10\xa9\x4e\xe8\x7a\ +\x6c\x0d\x03\xb7\x52\x21\xb1\x61\x6c\x47\x4d\x39\xe6\x6f\xd5\xeb\ +\x1a\x2e\xda\x3c\x74\xe9\x45\xe8\xa7\x49\xfd\x1a\xa3\xa7\x80\x6b\ +\xa9\x90\x8c\xb7\x79\x6e\x73\x9c\x73\xa9\xb9\x76\xa0\xae\xa3\xcb\ +\x53\xba\x5d\xb0\xcc\x0d\x41\xdd\x68\xf4\x2e\xa5\x0b\x7e\xd0\xeb\ +\x9e\x17\x3c\x9d\xd3\x75\xe3\xbf\xf7\x56\x09\x9c\x9b\x98\x05\xfa\ +\x35\x5e\x1b\xd5\x9d\x6e\x69\xec\xea\x95\xb6\x36\xaa\x3b\xf7\xad\ +\xea\x38\x30\x9f\x8d\x3a\x66\x63\x00\xb4\x85\xf9\xb9\x81\x55\x9d\ +\xe8\xa6\x79\xe8\xd1\x05\xe6\x99\x1f\xdd\xb7\xfe\x47\xf2\xb5\xd1\ +\x8b\x2d\x55\xb0\xbf\x19\x78\x28\x7a\x75\x61\x44\xf5\x2e\x4b\xeb\ +\xcd\xa3\xc6\xc2\x88\xea\xd5\x9f\xa3\x97\x85\x3f\xdf\xe9\x5b\xe3\ +\xcf\x6a\xbf\x44\xa7\x7b\x61\x1e\x7a\x78\x85\x05\xc0\xd6\xe0\x2c\ +\xef\x49\xfe\x24\x5f\x8d\xde\xaf\x9d\xe2\xd3\x4e\x2e\x35\x9d\xd2\ +\xfb\x97\x0c\x60\x70\xc6\xaf\x4b\xfe\xa2\xa9\xc8\x48\x6f\xd4\xca\ +\xfa\xaa\xd7\x5a\xf6\x24\x01\x00\x43\x33\x8d\x69\x4b\xa7\x81\x06\ +\xd6\x9b\xb5\x49\x9d\xdf\x2b\x2d\x81\x40\x20\x10\x08\x04\x02\x81\ +\x40\x20\x10\x08\x04\x02\x81\x7b\x89\x7f\x01\x9b\xd6\x34\x0b\xef\ +\xec\xcc\xa6\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\x1d\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\xcf\x49\x44\x41\x54\x78\x9c\xed\ +\x98\x4f\x6c\x54\x55\x18\xc5\xcf\x79\x4f\x06\x89\x85\x05\xd4\x44\ +\xaa\x25\xee\xc0\xa5\x7d\x6f\xea\xc2\xc4\x14\x0d\x0d\x74\xa1\x94\ +\x85\x0b\x56\x16\xc2\xcc\x88\xb1\xba\xc0\xb0\xc2\xb1\x31\x21\x21\ +\x90\xc8\xcc\x0b\x8a\x48\xc0\x98\x18\x17\x35\xca\xaa\x25\x8d\x50\ +\x12\xa8\x89\x69\x47\x97\x86\xc4\x95\x7f\xaa\x89\x92\x98\x00\xa9\ +\x14\xdf\xfd\x5c\x30\x95\x79\x7f\x3a\x9d\x7f\x6f\xa6\xe2\xf7\x5b\ +\xbe\x6f\xee\xbd\xe7\x9c\xb9\xf7\xce\xf7\x06\x50\x14\x45\x51\x14\ +\x45\x51\x14\x45\x51\x14\x45\x51\xfe\x5f\xb0\x53\x0b\xf7\xe7\x0a\ +\xc3\x46\x78\x0a\x80\x45\xe0\xa3\xd9\x0f\x47\x8f\x74\x42\x87\xdd\ +\x89\x45\xd3\xb9\xe2\x01\x11\x7e\x02\x60\x03\x80\x2e\x00\xcf\x6d\ +\x76\x76\xfe\xf2\x6b\xe9\xe2\xb7\xed\xd6\xd2\xf6\x00\x9c\x6c\xf1\ +\x30\x80\x02\x42\xbb\x8f\xe4\x8b\x3d\xe9\xa1\x85\xf9\xb9\xc9\x99\ +\x76\xea\x69\x63\x00\x42\x27\xdb\x7d\x9c\xc0\xdb\x55\x3e\xb4\xa3\ +\xc7\xdd\xf5\xc8\x7c\x69\xe2\x2b\x60\xac\x2d\xaa\xda\x72\x07\x0c\ +\xe4\xf3\x0f\xdd\xfa\x6d\xe3\x19\x80\x23\x35\x0d\x10\x9c\xeb\xda\ +\x7c\x23\x7b\x65\x6c\xec\xef\x84\xa5\x25\x1f\xc0\xc0\x2b\xe7\x1f\ +\xbe\xb5\xf6\xe6\x67\x00\x76\x87\x6b\x02\x31\x00\x41\xc0\x8a\xd6\ +\xf8\xe5\xfa\x3b\x5d\x7b\xaf\x7c\x3c\xf2\x57\x92\xfa\x12\x0d\xe0\ +\x99\xd7\x8b\x1b\xfc\x45\x5c\x00\xb0\x3d\x66\x65\x1f\x72\x5f\x85\ +\x08\xec\xb0\x18\x02\x97\x53\x77\x17\x76\xcf\x9c\x3b\x7c\x33\x29\ +\x8d\x89\x05\xf0\xf4\x48\xf1\x51\x7b\x0d\x26\x41\x38\xc1\x8a\x00\ +\xa0\x1f\xab\x44\xc4\x8e\x91\x34\xe7\x2f\x62\xe8\xbb\xf3\xa3\xbf\ +\x27\xa1\x33\x91\x00\x9c\xcc\xc9\x2d\xa4\x35\x05\x60\x6b\xa8\x24\ +\x00\x4c\x75\x39\x62\xc5\xe8\xba\x4e\xdb\xde\x31\xfb\xfe\x6b\x3f\ +\xb5\x52\x27\x10\x73\xf6\x9a\xa5\xef\xe0\x7b\x4f\x91\xd6\x0c\xea\ +\x36\xbf\xf4\x11\x18\x80\x12\x2a\x6c\x15\xdf\x9f\x71\x32\xde\xb6\ +\x56\xe9\x5c\xa2\xa5\x01\xa4\x0f\x9c\x4c\x5b\xbe\x7d\x15\xc0\x13\ +\xc1\x0a\x6b\x30\x5f\x89\x18\x08\xc2\x21\xf4\x92\x72\xad\x3f\xeb\ +\xb9\x4d\xca\x0c\xd0\xb2\x00\xd2\xd9\xc2\x0b\x62\x59\x97\x01\x6c\ +\xaa\x7c\x2e\x02\x01\xa4\x0e\xf3\x65\x18\xbb\x13\x36\x19\xc8\x74\ +\x5f\xce\x7b\xbe\x09\xa9\x01\x5a\x12\x40\x3a\x5b\xdc\x23\xe0\x04\ +\xee\xb5\xb5\x95\x08\x59\xcf\x37\x1f\x26\x76\x27\x74\x59\x22\x93\ +\xfd\xb9\xc2\x70\xe3\xf3\xde\xa7\xe9\x00\xdc\xac\xb7\x5f\x80\x71\ +\x00\xa9\x40\xe1\x9e\xf1\x26\xcc\x57\x9d\x27\x65\x84\x9f\xbb\xb9\ +\xe2\xbe\x66\xa7\x6f\xaa\x15\x76\x33\xc5\xb7\x40\x78\x88\xdc\xda\ +\x12\xb7\x7d\x9b\x42\x08\x30\xb8\x0e\x01\xbc\xf4\xb8\xbb\xf3\xf6\ +\x7c\xe9\xe2\xd7\x8d\xce\xdb\x60\x00\x42\x37\xb3\xf1\x18\xc8\x77\ +\x22\x15\xc0\xb0\xc5\xe6\x81\xb2\x73\x0a\x00\x86\xc2\xe6\x60\x8f\ +\xbb\x6b\xdd\x7c\x69\xe2\x52\x23\xef\x0f\x75\xf7\x01\xe5\xbe\xfe\ +\x34\xc0\xfd\xe1\x9a\x40\x12\x31\x1f\x58\x83\x20\x25\x7a\x74\x49\ +\x9c\x7d\xf2\xc6\x63\xb9\xf1\xf1\x97\xa3\x4d\x56\x15\xea\x0a\xa0\ +\xdc\xd7\x7f\x0a\x60\x4f\x54\x98\x18\x4a\xb2\xe6\x2b\xd6\x22\x85\ +\x71\xf7\xd7\x17\x7f\xa6\xb0\xf7\x07\x6f\xf4\x4e\xad\x73\xd5\x1c\ +\xc0\xb3\xfb\x8e\xad\x5f\x5c\xb3\xee\x82\x00\xc1\x9f\x20\x01\x84\ +\x30\x44\xe4\xb6\x4e\x14\x81\x90\x88\x0d\xe1\xd2\xda\xbb\x0b\xc3\ +\xb5\xbe\x3f\xd4\x14\x80\x93\x39\xd1\x4d\xa6\x26\x01\x04\x9b\x10\ +\x11\x90\xf4\xdb\xea\x3c\x8c\x88\x1d\xbd\x16\x30\x2b\x66\x71\xa8\ +\x74\xe6\xd0\x1f\x2b\x0d\x5f\x31\x80\xf4\xc1\x53\xbd\xe2\xfb\x53\ +\x00\x42\x6d\x28\x1b\x6b\x70\x12\x40\x40\x8b\x90\xa0\x17\xe1\xf7\ +\xb6\x91\xc1\x6f\xce\x8e\xfe\x5c\x6d\x6c\xd5\x00\x9c\x8c\xb7\x8d\ +\x94\x29\x00\xbd\xa1\x15\x05\xa4\x69\xf3\xae\x5f\x01\x5a\x08\x87\ +\x00\xfc\x08\xcb\x0c\xce\x7d\xf0\xe6\xf5\xe5\x46\x2d\xdb\x08\xf5\ +\x67\x3d\x97\x94\xab\x88\x35\x8f\x55\x66\x1e\x28\xef\xc6\xb0\xa8\ +\x2d\x30\xd6\xb5\xbe\x57\x0b\x4e\xdc\x08\x60\x99\x00\x9c\x4c\x61\ +\xbb\x81\x4c\x03\xe8\x0e\x2c\x81\x25\xf3\xab\x16\x23\xd1\x10\xba\ +\x2d\xc3\x69\x37\xe7\x0d\xc4\x0d\x88\x1c\x81\x74\xae\x70\x44\xc4\ +\x1a\x8b\xd9\x4e\xff\x71\x28\xa4\xc9\xcf\x9e\x7e\xe3\xdd\xca\xa7\ +\xd1\xff\xe2\x0c\xf3\x0f\x9e\x79\xa0\xdc\xa9\xe4\xc3\x4f\xa3\x47\ +\xe0\x01\xb4\xfe\x2f\x31\xde\xa2\x3b\x80\x3c\x2a\xad\x78\x8b\x5b\ +\x65\x08\x60\x84\x3c\xda\x69\x1d\x8a\xa2\x28\x8a\xa2\x28\x8a\xa2\ +\x28\x8a\xa2\x28\x4a\xa7\xf9\x07\xee\x73\x3f\xf5\xa2\x1e\x57\x1f\ +\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\xc0\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\x72\x49\x44\x41\x54\x58\x85\xe5\ +\x97\xcf\x4e\x13\x61\x14\xc5\x7f\xf7\x6b\xbb\x22\x31\x51\xc0\x08\ +\xbb\xbe\x82\xd0\x8a\xd1\x18\x4c\x5c\x09\x71\xc5\x1b\xd0\xd0\x26\ +\x40\x49\x8c\xc2\xb2\x69\x58\x95\x44\x23\x2d\x90\x42\xc0\xc4\xb0\ +\xc1\xbd\x4d\xd8\x28\x89\x89\x8a\x40\x7d\x05\x58\x29\x11\x31\x71\ +\xc1\xaa\x76\xae\x8b\xce\xd4\xb1\xd0\x3f\x53\x06\x17\x7a\x96\xe7\ +\xde\x99\x73\xe6\xdc\x6f\x32\x77\xe0\x7f\x87\xd4\x12\xfd\x89\xdc\ +\x2d\x54\x67\x10\x06\x50\xba\x7d\x52\x39\x42\xd9\x46\x24\xb3\x97\ +\x9f\x7c\x57\xd7\x40\x24\x3e\xff\x48\x91\xb9\xb3\x8c\xf9\x04\x4b\ +\x95\xe9\xe2\x4a\xf2\xc9\x29\x03\x7d\x63\xcf\x6e\x8b\x98\xb7\xc0\ +\x0f\x44\x93\xa1\x52\xb9\xf0\x61\xed\xe1\x77\x3f\x54\x6f\x8e\x3e\ +\xbd\x52\x0a\x05\x86\x50\xc9\x02\x97\x10\xb9\xe3\x24\x11\xac\x3a\ +\x11\x33\x0d\x08\xa2\xc9\xbd\xfc\xd4\xba\x1f\xc2\x0e\xec\x07\x59\ +\xef\x8f\x67\x05\x78\x81\xea\x0c\xf0\x00\xc0\x54\xbb\x84\x01\x80\ +\x50\xa9\x5c\xf0\x53\xdc\x0d\x13\x34\x85\x8a\x14\x37\xaa\x5c\xb5\ +\x6a\x1f\x38\xbf\x62\x3f\x0b\x3b\x8b\x13\xc7\x15\x29\xae\x3a\x5c\ +\xb0\x7e\x7b\x7b\xb8\x9e\x58\x18\x36\x6a\xad\x00\x58\x62\xc6\x3e\ +\xe5\x27\x5e\x35\xea\xf7\xd5\x40\x34\x96\x0b\x5b\x6a\x6d\x00\x1d\ +\x00\xb6\x91\xde\x46\xd7\x98\x46\x45\x4f\x48\xa5\x8c\x15\xd0\xe7\ +\x8e\x78\xab\xf0\xcd\x40\xe4\xb0\x2b\x01\x0c\xba\x39\x55\x66\xff\ +\x8a\x81\x68\x2c\x17\x56\x74\xae\x86\xde\x2a\xf6\x1c\x2f\x5f\xbc\ +\x81\xb3\xa3\x3f\x31\x65\x19\x25\x9d\xb6\x9a\x5d\xde\xf4\x10\x36\ +\x3b\xd5\x91\xc3\xae\x84\xa2\x83\x6e\x4e\x95\xc7\x3b\xab\x93\xfb\ +\xad\xf8\x6f\x9a\x80\x2d\xde\x03\xf4\x18\xb5\x36\xa2\xb1\x5c\xd8\ +\xa9\x9d\x27\x7a\x07\x5e\x5f\xc3\x0e\x2b\xa0\x6b\xa4\x52\xf7\x00\ +\xac\xc3\xf6\xa3\x6f\xd9\x80\x2a\xb3\x22\x2c\xb9\xa8\xbb\x7d\x5f\ +\x3a\xe3\x46\x44\xce\x13\xbd\x83\xa6\x23\xb0\xe3\xdc\x72\x73\x22\ +\x2c\x29\xba\x58\xd3\xea\x29\xfa\x96\x0d\x90\x4e\x5b\xa6\x2c\xa3\ +\xc0\x49\x83\x2e\xcf\xd1\xb7\x6e\x00\xd8\x59\x9d\xdc\x17\x64\xba\ +\x5e\xbd\x9d\xe8\x3d\x19\x00\xd8\xbd\xf6\x2d\x4f\xcd\x28\x6c\xb4\ +\x15\xbd\x67\x03\x75\x46\xd1\x76\xf4\xde\x0d\xe0\x8c\x42\x47\x14\ +\x0e\x14\x0e\x04\x1d\x69\x37\x7a\x07\x9e\x3f\xc7\xbb\xcb\x53\x9b\ +\x40\xb8\x69\x63\x8b\x70\xaf\x64\x47\x50\x59\x20\xfd\xba\x79\x2d\ +\xa2\xe3\x0b\x9d\x15\x29\xbe\x9e\x36\xa0\x6c\x03\x94\x42\x81\xa1\ +\x8b\x32\x60\xfd\xb4\x86\x2a\x52\x7c\x74\xb8\xdf\x23\x10\xc9\xa0\ +\x3a\x8c\x4a\xb6\x3f\x9e\x15\x13\x34\x05\x67\x87\x3b\x2f\xa2\xe3\ +\x0b\x9d\xb6\xf8\x3c\x60\x21\x92\xa9\xca\xba\x1b\xed\x1f\x93\x0c\ +\x7e\x6e\x4a\x7f\xe2\xd4\x8f\x49\xc0\x5d\xfd\x5c\xdc\x7c\xdf\x1b\ +\xb9\xff\x1a\xe8\x16\xb8\x8c\xc7\xf5\xaa\x1e\xec\x99\xbf\x41\x24\ +\x56\x5c\x4e\xbe\xf4\xe3\x9e\xff\x0e\x7e\x01\x29\x72\x01\x2f\x4e\ +\xc0\xa2\xca\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xc0\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x72\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\xb1\x09\x83\x60\x14\x04\xe0\xd3\x21\xc4\x26\xe0\x4c\x59\xc1\ +\xca\x89\xdc\x24\xf3\x08\x69\xc4\x21\x34\xad\xf8\xd7\x2a\xc4\xef\ +\x2b\x8f\x57\xdc\xbb\x04\x00\x00\x00\x00\x00\x00\x78\x82\xea\x18\ +\x4c\xd3\xf7\x9d\x2a\x63\x92\xe6\x86\x3e\x67\x9a\xb3\xa5\xef\xba\ +\xd7\x67\x1f\xd6\xc5\xd9\x7f\x3e\x9f\x24\x6d\xea\x8c\xc7\xb0\x1c\ +\xe0\x61\xca\x01\xb6\x0c\x49\x96\xeb\xab\x9c\x6e\xce\x9a\xe1\xee\ +\x12\x00\x00\x00\x00\x00\x00\x00\xc0\xf5\x7e\x5a\x95\x0d\x08\xf2\ +\x12\x5b\xad\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xa7\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x59\x49\x44\x41\x54\x58\x85\x63\ +\x60\xa0\x00\xb8\x85\xa4\x34\xb8\x85\xa4\x34\x50\x62\x06\x13\x25\ +\x9a\xa9\x01\x46\x1d\x30\xea\x80\x51\x07\x8c\x3a\x60\xd4\x01\xa3\ +\x0e\x18\x70\x07\xb0\x50\x6a\xc0\x7f\x06\x06\x07\x4a\xaa\xe4\xa1\ +\x1f\x02\x8c\x0c\x0c\x07\x76\xad\x99\xd3\x40\xae\xfe\x01\x0f\x81\ +\x51\x07\x8c\x3a\x60\xd4\x01\xa3\x0e\x18\x75\xc0\xa8\x03\x06\xdc\ +\x01\x00\x05\x9e\x09\x3f\xb6\x6d\xc4\xbd\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xf6\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xa8\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\xb1\x0d\x80\x30\x00\xc4\x40\xc2\x1e\x11\xec\x3f\x15\x88\x41\ +\x42\xcb\x06\x47\x61\x77\x5f\xbd\xe5\xb1\x21\xae\xfb\x59\xdf\x7d\ +\x1e\x73\x08\x8f\x5d\x9c\xfe\x89\x02\x68\x01\x4d\x01\xb4\x80\xa6\ +\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\ +\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\ +\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\ +\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\ +\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\ +\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\ +\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\ +\x2f\x70\x51\x04\x80\x66\x61\x99\xa8\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x03\xf4\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\xa6\x49\x44\x41\x54\x58\x85\xe5\ +\x97\x4f\x68\x1c\x55\x18\xc0\x7f\xdf\x9b\xec\x26\x5a\x93\x88\x96\ +\x98\x9a\xdd\xc9\xee\xc6\x80\x86\x3d\x78\x90\x42\x0f\xf5\x4f\x29\ +\x2d\x22\x6d\xaa\xa0\x22\x52\x0b\x55\xf1\xd0\x9b\x20\xa4\x78\xe8\ +\x41\xd1\x80\x27\xa5\x28\x88\x20\x88\x5e\x0d\x36\x6a\xb5\x60\x69\ +\x4f\x52\x1a\x28\xc2\x2a\x91\x6d\xb2\x7f\x66\xb6\xab\x78\x90\xd8\ +\x58\x35\x99\x79\x9f\x87\x9d\x5d\x93\x6c\xd2\x64\xd9\x8d\x97\x7e\ +\x97\xf9\xf8\xe6\x9b\xf7\xfb\xbd\x61\xde\xcc\x1b\xb8\xd5\x43\x5a\ +\x69\xbe\x5a\xa9\x24\x63\x81\x3d\x62\x91\xfd\x82\x26\x51\x12\x08\ +\x06\xa5\x82\xe0\x0b\x5c\x34\x86\xa9\x64\x32\x99\xef\xa8\xc0\xbc\ +\xe7\xed\x36\x96\x49\xe0\xb1\xad\xf4\x2b\x5c\x36\xc8\xc9\xe1\xe1\ +\xc4\x77\x6d\x09\xcc\xcd\xcd\xf5\x3b\x4e\xfc\x03\x84\xe7\xa2\x52\ +\x55\x61\x1a\xd1\xb3\x2a\x32\x1f\x76\x75\x55\x6f\x0b\x43\x1b\x86\ +\xe1\xa0\xaa\x93\x52\xd1\x03\x02\xe3\xc0\x70\xd4\xff\xb5\x0d\x97\ +\x8f\x67\x32\x99\x5f\x5b\x16\xf0\x3c\xef\xbe\xd0\xea\x19\x90\x07\ +\x80\xaa\xc0\x29\xd7\x4d\x7c\x2c\x22\xc1\xcd\xa4\x55\xd5\x14\x3d\ +\xef\x59\x51\x79\x13\xc8\x20\x94\x6d\x20\x87\x33\x99\xc4\x0f\x5b\ +\x16\x28\x95\x4a\x19\xc5\x5c\x02\x76\x0a\x7c\xb1\xb4\xf4\xf7\x0b\ +\xa3\xa3\xa3\x7f\xdc\x0c\xbc\x36\xf2\xf9\x7c\x77\xac\xbb\xe7\x7d\ +\x94\xe3\xc0\x9f\xa8\xd9\x9b\x4a\x0d\x5d\xd9\x54\x20\x9f\xcf\xf7\ +\xc5\xe2\x3d\xdf\x03\x63\x0a\xef\xa6\xdc\xc4\xab\x22\x62\x5b\x81\ +\xd7\x43\x55\xa5\x58\xae\x4c\x08\xfa\x16\xe0\xa3\xe1\xee\x54\x2a\ +\x55\x5d\xd9\x63\xd6\x5e\x14\x8b\xf7\x9c\xae\xc1\x75\xba\x1d\x38\ +\x80\x88\x68\xca\x1d\x9a\x04\x3e\x02\x12\x88\xf3\xa9\xaa\xae\x9a\ +\xf4\x2a\x81\x72\xb9\xfc\x10\x70\x14\xe5\x37\x1b\x2c\x1f\x6d\x07\ +\xbe\x52\x62\xf1\xfa\xc2\x09\x60\x16\xd8\x57\x2a\xf9\x8f\x6f\x28\ +\x60\x95\xb7\x6b\x17\xf1\xc6\xc8\xc8\xc8\x42\xbb\xf0\x7a\x64\xb3\ +\xd9\x25\x94\xd7\x01\x54\x98\x5c\x79\x17\x1a\x49\xb1\x58\xdc\x85\ +\x38\x15\xe0\xf7\xc5\xeb\x0b\xbb\xb2\xd9\xec\x52\xa7\x04\xa0\xf6\ +\x3c\x94\xca\xfe\x4f\xc0\xfd\x36\x94\x07\xeb\xab\xa2\x71\x07\x44\ +\x9c\x43\x91\xd0\x57\x9d\x86\xd7\xc6\x17\x55\x38\x03\x20\x8e\x3e\ +\x59\xaf\x37\x04\x54\x79\xb4\x96\xf0\x4d\xa7\xe1\x0d\x09\x95\x6f\ +\xa3\x74\x5f\x93\x00\x22\xc9\x28\x29\x6c\x97\x80\xea\xf2\x3c\x80\ +\x40\xa2\x59\x20\x2a\xaa\x2e\x57\xd9\xa6\x08\x82\xa0\x3e\xf6\x50\ +\xfd\x41\x6c\x7a\x0f\xfc\x8f\xb1\x56\xc0\x56\x6a\xc7\xd8\xe0\x76\ +\x11\x1d\x67\x47\x34\xb6\x5c\xab\xbf\x63\xfe\x13\x50\xe3\xd5\xba\ +\x6c\x7a\xbb\x04\x8c\xb1\x99\x28\xf5\x1b\xb5\x06\x5f\xb8\x00\x60\ +\x94\x83\xdb\x25\x20\xa2\x07\x00\x14\x3d\xdf\x24\xe0\x88\x9d\xae\ +\x9d\x94\x27\x66\x66\x66\x62\x9d\x86\xab\xaa\x28\x1c\x06\xc0\xca\ +\x54\x93\x80\xeb\xba\xd7\x80\xf3\xc0\xce\xbb\x07\x06\x5e\xea\xb4\ +\x80\xe7\x79\x87\x80\x31\xe0\xc7\x54\x6a\xa8\xb1\x37\x58\xb5\x0a\ +\x8c\xe8\x04\x80\xa8\x39\x95\xcf\xe7\xfb\x3a\x05\xcf\xe5\x72\x71\ +\xab\x52\xfb\xce\x60\x4e\x8a\x88\xae\x2b\xe0\xba\xee\x65\xe0\x33\ +\xd0\x7b\xe2\xf1\x9e\x4f\x54\xb5\xed\x65\xaa\xaa\xd2\xdb\xdb\xf7\ +\x1e\x30\x86\x70\xc1\x75\xef\xfd\x72\xe5\xf9\x26\x40\x18\x2c\x9d\ +\x00\x66\x15\xc6\x4b\xa5\xca\x3b\xed\x48\xa8\xaa\x94\xcb\xfe\x6b\ +\x8a\xbc\x02\x5c\x33\xe8\xf3\x2b\x67\x0f\x1b\x6c\xc9\x6a\xfb\x41\ +\x2e\x01\x77\x21\x7c\x7e\x7b\x4f\xf7\xb1\x81\x81\x81\xc5\x56\xe0\ +\xb9\x5c\x2e\x7e\x47\x6f\xff\x69\xe0\x65\xe0\x86\x11\x7d\xc4\x75\ +\xdd\x99\xb5\x7d\xeb\xce\x2e\x99\x4c\x5e\x0d\x1d\xd9\x03\xfc\x8c\ +\xf2\xd4\x8d\xbf\xfe\x99\x2d\x16\xbd\x17\x55\xb5\x6b\x33\xb0\xaa\ +\x9a\x52\xc9\x7f\x66\x47\x6f\x7f\x2e\x82\xfb\xa8\xb3\x77\x3d\x38\ +\x6c\xb2\x2d\x2f\x14\x0a\x77\x62\x9c\x0f\x05\x79\x3a\x2a\xf9\xa8\ +\x4c\x8b\xc8\x59\x08\xe6\x8d\x31\xd5\x20\x08\x2c\xc4\x07\x71\xc2\ +\x61\xb1\x1c\x44\x64\x1c\xc8\x44\x83\x9f\xb3\x36\x38\x96\x4e\xa7\ +\x7f\xd9\x88\xb1\xa5\x1f\x93\x62\xd1\xdf\x23\xa2\x93\x0a\x0f\x6f\ +\xa5\x1f\xb8\x62\x45\x27\x32\xae\x7b\x6e\xb3\xc6\x96\x7e\xcd\x0a\ +\x85\x42\x0a\x13\x3b\x22\xe8\x7e\x94\x24\x42\x02\x70\x00\x5f\xc0\ +\xb7\xc8\x45\xac\x4c\xa5\xd3\x43\xb3\xad\x8c\x7b\x6b\xc7\xbf\xc1\ +\x7f\x6c\x10\x0e\xdc\xa9\xdc\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ +\x42\x60\x82\ +\x00\x00\x02\x8a\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\x3c\x49\x44\x41\x54\x58\x85\xed\ +\x97\x3d\x6b\x14\x51\x14\x86\x9f\x73\xc7\x2e\x60\x61\x30\xa0\x66\ +\xdc\xd9\x5f\x61\x40\x91\x58\x6f\xca\xb4\xda\x04\xd4\xca\xca\xc4\ +\x1f\x90\x6a\x03\x16\x06\x0c\x2a\x68\x9d\x3a\xb8\x60\x17\x10\x84\ +\xe4\x57\xec\xbd\x99\xb1\x49\x50\xb0\x48\xb9\xf3\x5a\xec\x4e\x4c\ +\x26\xfb\xbd\x13\x1b\x7d\xab\xcb\x39\x77\xe6\x3c\xf3\x9e\x0b\x73\ +\x0f\xfc\xeb\xb2\x72\x20\x84\xef\xf7\x73\x3a\xaf\x4c\xb6\x84\x71\ +\xb3\x92\x2a\xe2\x44\xa6\x03\x47\xd4\xac\xd5\xee\x7c\x1b\x08\xe0\ +\xfd\xd1\x4b\xcc\xb6\xfa\x81\x55\xa4\x1c\x69\x23\x49\xee\xbe\xbe\ +\x04\x10\x42\x78\x20\xdc\x57\xe0\x97\x61\x2f\x9c\x53\x2b\x8e\xe3\ +\x9f\x55\x54\x4d\xd3\xf4\x46\x9e\x5b\x43\x68\x1b\xb8\x6e\xb8\x87\ +\x65\x27\x68\x87\xa3\x3d\x1f\x52\x85\x90\x3d\xae\xa2\x68\x3f\x85\ +\x90\x3d\xf1\x21\x55\x3b\x1c\xed\x15\x31\x57\x2c\x4c\xb6\x04\xe0\ +\x9c\x5a\x57\x05\x10\x45\xb4\x00\x0c\xbb\x77\x09\xa0\x38\x70\x55\ +\xd9\xde\x4f\x8b\x8b\x8b\x3f\x7a\xcb\x85\x22\x76\xad\xea\x22\x21\ +\x64\x2b\x42\x1f\x00\x0c\x7b\x5a\xab\x2d\x7e\x1e\xb6\xbf\x52\x00\ +\xef\x7d\x5d\x68\x17\x98\x03\xe8\x81\xdc\x1e\xf6\x8c\x1b\x96\x9c\ +\x44\x92\x1c\x2e\xfa\x54\x14\x1f\x57\x95\x01\x84\x34\x7d\x8e\x58\ +\xbe\x00\x65\xda\xfc\x2b\x00\xde\xfb\x3a\xb2\xad\x52\x78\x3f\x89\ +\xe3\xf7\x57\x0e\x30\xc0\xfa\x53\xd4\x59\x33\xb3\x7c\xd4\xf3\x23\ +\x0f\xe1\xa8\x53\xdd\xb5\xde\x96\x2f\x40\x99\xd6\xeb\xb5\xa4\x3d\ +\xce\x07\x8c\x74\xa0\x57\xfc\x16\x70\x4b\x68\xd7\x7b\x5f\x2f\x72\ +\xb3\x58\x3f\x36\x40\x49\x73\x58\xf4\x51\x92\x9b\xd5\xfa\x42\x23\ +\x5b\x20\xd3\xa6\xc9\x76\xce\x85\x1e\xf9\x34\x7d\x66\x60\xb3\x58\ +\x5f\x68\xa4\x03\x3d\x3b\xf7\xcf\xc7\x4c\xb6\x83\xec\x6d\x69\xeb\ +\x44\xd6\x8f\x0d\x60\x66\x39\xea\xac\x01\xa7\x43\xb6\x4d\x6c\xfd\ +\xd8\x00\x00\x49\x92\xb4\x31\x6d\x0c\xca\xcb\xb4\x9e\x24\x93\x59\ +\x3f\x11\x00\x40\x2d\x8e\xdf\x51\x6a\x45\x4f\x53\x59\x3f\x31\xc0\ +\x80\x56\x4c\x6d\xfd\xc4\x00\xd0\x6d\x85\x1c\xab\x60\x1e\xcc\xcb\ +\xb1\x3a\xad\xf5\x85\x26\xfe\x1d\xd7\xe3\xf8\x0b\x50\x1f\xb9\x71\ +\x4c\xfd\x71\x40\x9c\x40\xf7\x02\x59\xd5\xcb\xcb\xca\xb2\x6c\xbe\ +\xb7\x3c\xbe\x04\x20\xd3\x01\x40\x9e\x5b\xe3\xaa\x00\x3a\x1d\x1a\ +\x00\x42\x87\x45\xec\xac\x05\x8e\xa8\x29\xf2\x15\xa1\xed\x10\x32\ +\x8b\x22\x5a\xe7\xee\x70\x33\x29\xcb\xb2\xf9\x4e\x87\x86\xd0\x1b\ +\x20\x77\x44\xcd\x22\xd7\x6f\x30\x69\x52\xe1\x45\xa5\xa4\xc1\x83\ +\x49\xa1\xb3\xd1\xac\x7b\x75\x5e\x28\xe7\xa7\xd4\xb1\xd0\x61\xbf\ +\xd1\xec\xbf\x7e\x03\x1f\xb0\x01\x10\x54\x88\x8f\x55\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x89\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3b\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\x01\x09\x00\x20\x10\x04\xc1\xd7\xfe\x21\x15\x83\xf8\x29\xe4\ +\x40\x66\x12\x2c\x5b\x05\x00\x00\x00\x00\x00\x00\xc0\xff\xc6\xda\ +\xe7\xa6\x23\x92\x66\x3a\x20\xcd\x80\x74\x00\x00\x00\x00\x00\x00\ +\x00\x00\xbc\xd7\x42\xd4\x03\xab\xc4\x79\xcd\x85\x00\x00\x00\x00\ +\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x20\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xd2\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\xb1\x15\x82\x50\x10\x44\xd1\x5d\x8b\xa0\x16\xeb\xa0\x05\x22\ +\x2b\xb2\x0b\xea\xb0\x0e\x22\xab\x00\x03\x34\xd3\x94\xeb\x39\xcc\ +\x8d\x7e\xf6\x67\x5f\x55\x44\x9c\x59\xab\x8f\xaf\xf3\x36\x6e\xb5\ +\xdd\xf7\x11\x7d\x7b\x8c\x3d\x8b\x1d\x17\xf1\x69\x55\xd5\xfb\xf8\ +\xa1\xaa\x86\x4f\x08\x81\x05\xa8\xfd\xf8\x6f\xef\x43\xc9\x00\x7f\ +\x21\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\ +\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\ +\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\ +\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\ +\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\ +\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\ +\x2d\x01\xf4\x00\x4d\x06\x78\xfe\x78\x1f\xca\x05\x58\x7b\xea\xae\ +\xa5\xbb\x96\x5a\x7b\x62\x3b\x22\xe2\xd4\x5e\x68\x08\x13\x4e\x3b\ +\x46\xe4\xd2\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\x01\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\xb3\x49\x44\x41\x54\x78\x9c\xed\ +\x99\x4f\x68\x5c\x45\x1c\xc7\xbf\xdf\xd9\x4d\x08\x88\x27\x5b\xb1\ +\xbc\xbc\x9d\x8d\x8d\xb2\x67\x15\x4f\xed\x21\xfe\xa3\x5a\x28\x82\ +\x17\x3d\x09\xc6\x58\xc1\xa3\xa2\xa0\x88\x94\x7a\x69\x05\xbd\x56\ +\xb1\xe0\x49\x10\xa4\xda\x8b\x95\x42\xa5\x5e\x2d\xf5\x2c\x12\x92\ +\x7d\x79\x59\x11\x8d\xa7\x08\x4d\x36\xfb\xe6\xeb\x61\x37\x74\xf7\ +\xbd\xb7\x64\x93\x7d\xbb\x1b\xe9\x7c\x4e\xcb\xfc\x66\xe6\xf7\xfd\ +\xce\x9b\x79\x6f\x66\x16\xf0\x78\x3c\x1e\x8f\xc7\xe3\xf1\x78\x3c\ +\x1e\x8f\xc7\xe3\xf1\xdc\x5b\x30\x5d\x10\x45\x8d\x8f\x44\x7d\x28\ +\xe7\x4a\x24\x1d\x00\x4d\x40\x57\x91\x50\x92\xa1\x31\x09\xc5\xf3\ +\xd6\x06\xe7\x7a\x82\xe9\xda\xf5\x28\x6e\x01\x28\x8d\x4d\xde\x78\ +\x49\xaa\x36\x2c\x77\x17\x98\x49\x29\x39\x2c\x64\x06\x80\xc0\xc7\ +\xf8\xff\x4f\xfb\x3c\xd4\xf1\xd6\x43\x66\x09\x00\x40\xbd\xbe\xbe\ +\x00\xea\x2a\x80\xfb\x53\x7d\x88\xa4\xd3\x21\x1e\x1e\x01\x86\x59\ +\x5f\x9b\x72\x38\x33\x37\x17\xde\x4c\xd7\xcf\x1d\x00\x00\x88\xa2\ +\xe8\x71\xc1\xfc\x08\xe0\x48\xaa\x89\x00\xb9\x02\xb4\x8e\x02\x83\ +\xac\xa7\x0d\xc2\x9d\xb2\xd6\xde\xee\xd7\x20\x17\x6b\xed\x6d\x97\ +\x98\x13\x04\xe2\xde\x88\xc8\x43\xf8\xee\x60\x9e\x79\x62\xcd\x25\ +\xe6\x44\x3f\xf3\xc8\x34\xc8\x61\xb9\xd1\x08\xcb\x2d\x77\x1d\x40\ +\x2d\xd5\x52\x10\xdd\xe4\x5f\x17\x04\x28\x03\x65\xbc\xfc\xd6\x2a\ +\x9b\xe7\xe6\x83\x20\xce\x6d\x76\xb7\xf5\xde\x34\x1a\x8d\x23\x3b\ +\x2d\x77\x0d\xc0\x13\xdd\xe5\x12\x40\x32\x99\xe4\x20\x48\x28\x31\ +\xe5\x42\xc0\xad\xe9\xb2\x79\x21\x08\x82\x8d\xbd\xda\x0f\x34\x95\ +\x83\x20\xd8\xd8\xba\x33\xf3\x14\x80\x9f\xba\xcb\x49\x40\x50\x69\ +\xa0\x51\x2c\x1c\x51\xc8\x9a\x07\x70\x63\xfb\xce\xcc\xd3\x83\x98\ +\x07\xf6\xb1\x96\x6b\xb5\xa3\x9b\x72\xad\xd3\x20\xbe\xeb\x2e\x27\ +\x00\x01\x25\x0d\x38\x9b\x8a\xa0\x9d\x8b\x26\x93\x90\xb8\xb2\xd3\ +\xdc\x3a\x5d\xab\x1d\xdd\x1c\xb4\xaf\x7d\x8b\x96\x54\x8e\xe2\xf5\ +\x4b\x10\x16\x73\xa2\xae\xfd\x95\x18\x25\x22\xc0\xec\x83\x23\x2e\ +\xdb\x70\xf6\x6c\x7b\x49\x0e\xce\xbe\xdf\xe6\x24\x5b\x36\x9c\x5d\ +\x02\xf0\x49\x4e\x34\xef\x33\x54\x24\xb9\xe6\x05\x5c\xb4\xe1\xec\ +\xd2\x7e\xcd\x77\x3a\x3c\x38\x51\x14\xbf\x2b\xe0\x42\x4e\xa8\xf0\ +\x43\x14\xdb\x53\x2b\x6f\xe7\xfa\x9e\xb5\xe1\xc5\x21\xfa\x1d\x8e\ +\x7a\x3d\x7e\x1d\xc4\xe7\x48\x8b\x23\x1d\x54\xd0\x9e\x91\x24\xa4\ +\xb4\x79\x07\xe1\x8d\x6a\x35\xbc\x3c\x54\xd7\xc3\x34\xde\xa5\x5e\ +\x8f\x5f\x02\xf1\x35\x80\xe9\x54\x48\x68\xcf\x86\x83\x23\x18\x30\ +\xa3\xb3\x09\xe1\x95\x6a\x35\xbc\x32\x54\xdf\x28\x70\xbd\x46\x51\ +\xe3\x19\xc1\x7d\x0f\xe0\xbe\x54\x48\x24\xf6\x7d\x7e\x20\x01\x49\ +\xa6\xfd\xab\x87\x7f\x09\xbe\x68\xed\xec\x8d\x21\xe4\xde\xcd\x53\ +\x44\x27\xbb\xac\xc4\xf1\x93\xc6\xe1\x07\x00\x0f\xa4\x42\x07\x99\ +\x09\x79\x2f\xd4\x7f\x0c\xf5\x7c\xa5\x52\xb9\x75\x50\x8d\x79\x49\ +\x0a\xe3\xe1\x30\xfc\x05\x4a\x4e\x02\x68\xa4\x42\x04\x07\xcf\x95\ +\xbb\xaf\x07\xd6\xa1\xe4\x64\x91\xe6\x91\x93\xa4\x10\x56\x56\xfe\ +\xb0\xc6\x24\xd7\x41\x3c\x9a\x4a\x27\x10\x0e\x7d\xd7\x43\x9f\x7d\ +\xbd\xf0\x7b\x92\x98\x67\x8f\x1f\x0f\xd6\x8a\xd6\x3a\xb2\x6f\xf6\ +\xf2\xf2\x9f\x0f\x96\xa7\x9a\xd7\x00\x3e\xd6\x13\x90\x00\x9a\x9c\ +\xf3\x03\x01\xb9\x52\x76\xc9\xeb\xd7\x9d\xe9\xa9\x53\x8f\x1c\x3b\ +\xf6\xf7\x28\x74\x8e\xec\x58\x3b\x3f\xff\xd0\x5f\x3b\xcd\xed\x05\ +\x08\x3f\xf7\x04\x48\x48\xea\xb9\x73\x6c\x6f\xa7\x95\x35\x4f\xdc\ +\xdc\x69\x6e\x2f\x8c\xca\xfc\x6e\xee\x91\xb2\xba\xba\x3a\x03\x33\ +\xf5\x0d\xa1\x33\xdd\xe5\x9d\xe7\xef\x3a\x22\xf2\x36\x38\x57\x9d\ +\x6b\xbd\x3c\x37\x37\xb7\x35\x4a\x7d\x63\x39\xc0\x48\x2a\xaf\xad\ +\xc5\x5f\x0a\x7c\x75\x90\xfa\x04\xbf\xaa\x54\x82\x25\x92\xad\x51\ +\x6b\x1b\xcb\xcd\x0e\xc9\x56\xa5\x12\xbe\x06\xe9\xb3\x3d\x2b\x8b\ +\x9f\x56\x2a\xc1\xe2\x38\xcc\x03\x63\xbc\xda\x22\xe9\xac\x0d\xdf\ +\x06\xf9\x41\xbf\x3a\x02\xdf\xb7\x36\x78\xa7\xf3\x87\xcc\x78\x74\ +\x8d\x2b\x51\x37\xab\xd1\xfa\x59\x42\x97\xba\x8a\x44\xe0\x4d\x6b\ +\xc3\x2f\xc6\xad\x65\x32\x97\x39\x00\x56\xa3\xf8\x02\x81\x45\x00\ +\x09\xc1\xb7\xac\x9d\xfd\x76\x52\x5a\x3c\x1e\x8f\xc7\xe3\xf1\x78\ +\x3c\x1e\x8f\xc7\xe3\xf1\x78\x3c\xf7\x12\xff\x01\x83\xc1\x2a\x8b\ +\xb6\x49\x04\xca\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\ +\x00\x00\x00\x68\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x1a\x49\x44\x41\x54\x58\x85\xed\ +\xc1\x01\x01\x00\x00\x00\x82\x20\xff\xaf\x6e\x48\x40\x01\x00\x00\ +\x00\xef\x06\x10\x20\x00\x01\x47\x01\xa0\x88\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x03\x5e\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x10\x49\x44\x41\x54\x78\x9c\xed\ +\x99\xd1\x4b\x53\x51\x1c\xc7\xbf\xe7\x6c\x3a\x37\xca\xa2\x88\x1e\ +\xaa\x87\x46\x11\x24\x3d\x54\x90\x91\x09\xd1\x9c\x31\x91\x32\x2f\ +\x23\x7a\x4a\xe9\x6a\x10\x48\x7f\x40\xd0\x1e\xea\x2d\xa2\xde\x8a\ +\xb9\x2d\x1f\xd2\x82\xb5\x19\x8b\x2c\xb7\x52\x1f\xc2\x20\xb0\xa8\ +\xcc\x12\xb4\x1e\xca\x82\xc8\x32\x57\x8e\x9c\x3b\xa7\x27\x69\x5e\ +\xaf\x0d\xc1\x73\xae\xd0\xf9\x3c\x7e\x7f\xb0\xef\xf7\x7e\xef\xd9\ +\xce\xb9\x77\x80\x42\xa1\x50\x28\x14\x0a\x85\x42\xa1\x50\x28\x14\ +\x8a\xff\x0d\x22\xda\xc0\xab\xe9\x1d\x00\x8e\x03\x00\x38\x69\x4c\ +\xc5\x5b\xdb\x44\x7b\x2e\x06\xa1\x05\x1c\x68\x68\x28\x29\x4a\xdb\ +\x33\xf9\x1a\xe5\xec\x60\x77\x3c\xd2\x2b\xd2\x77\x31\x50\xa1\x9f\ +\xfe\xcb\x65\x37\x4a\x8c\xd0\x1e\x4f\x7d\xa3\x5b\xa8\xef\x22\x90\ +\xf1\x15\xe0\x66\xba\x33\xcb\x4a\x13\x89\x48\x5a\xb4\x7f\x21\xc4\ +\xae\x00\x00\xab\xe9\x8f\x79\xab\x00\x00\x32\x45\x74\x32\x10\x08\ +\x08\xf7\x2f\x84\xf0\x00\xd1\x68\x34\x67\x2f\xc9\xac\x32\x9b\xf5\ +\x0f\x8e\xe5\x44\xfb\x17\x42\xca\x1d\xb8\xdf\xde\x3e\x49\x29\xdf\ +\x6a\x36\xf3\x6a\xfa\x63\x19\x19\x16\x42\xda\x12\xec\x8e\x86\x47\ +\x40\x78\x95\xc9\xa8\xa2\x5a\x6b\xba\x28\x2b\x87\x11\x9b\x4c\xb3\ +\x77\x43\xcf\xdf\xbb\xb7\xef\x1c\x27\x20\x35\x86\xd1\xbe\x2d\x65\ +\xbb\x47\x46\x87\x9e\xbd\x92\x99\x07\x90\xb0\x0b\x98\xe1\xd5\xf4\ +\x36\x00\x27\x8c\x3a\xa5\xbc\xbc\x3b\x1a\x7e\x2a\x33\x8b\x25\x05\ +\x00\x80\x57\xd3\x47\x01\xcc\x3f\x0f\x64\xd9\x86\x54\x22\xf2\x49\ +\x56\x0e\xcb\x0a\x00\x16\x3e\x23\xfc\xa4\x2b\x5d\x4f\xa2\x97\x33\ +\x66\xb3\xa5\xc6\xd2\x7d\xf8\xdb\x5a\x5a\x6c\xa6\xaf\x60\xe9\x29\ +\x48\xba\x39\x96\x16\x30\x10\x0c\x66\xb3\xc5\x74\x9d\xd9\xcc\xab\ +\xe9\xdf\x65\x64\xb0\xfc\x24\xd6\x77\x33\xf8\x95\x30\xbe\xc3\x64\ +\xb4\xaa\x4a\xd3\x6f\x89\xf6\xb7\xbc\x00\x00\x48\x76\x86\x07\x39\ +\x41\x9d\x51\x27\xc0\x31\xd1\xde\xcb\xa2\x00\x00\xa0\x9c\x0e\x5b\ +\xe2\x6b\x85\xa9\x11\xcf\x61\x7d\x3d\x07\xeb\x32\x19\xf5\x8b\xf6\ +\xb6\xbc\x80\xda\xda\x66\x17\xb5\x23\x01\x60\xf3\x9c\x01\xc7\xf9\ +\x54\x2c\x54\x21\xda\xdf\xd2\x02\xfc\x7e\xbf\x6d\xda\xc1\x3a\x40\ +\xb0\x27\x5f\x27\xe0\xad\xa9\x78\x28\x20\x23\x83\xa5\x05\x4c\xb0\ +\xd2\x4b\x1c\x38\x92\xaf\x11\x82\x07\xd3\xe3\x1b\x4f\x03\x30\x3d\ +\x24\x2d\x35\x16\x1e\x85\x9b\xce\x00\xfc\xca\x5c\x95\xbc\x70\x66\ +\x73\x95\x32\xdf\x14\x59\xf3\x30\x54\xdf\x74\x14\x84\xc7\x0c\xfe\ +\x1f\x73\xd4\xbe\xb7\x27\x7a\x6d\x4c\x66\x16\xe9\x05\x54\x6b\xcd\ +\xe5\x1c\xac\x17\x80\x73\x56\xe3\x40\x9a\x03\xfb\x1f\xc5\x42\x2f\ +\x65\xe7\x91\xfa\x1b\xe0\xa9\x6f\x74\x73\xb0\xbb\xc8\xbb\x78\x00\ +\x33\x94\x41\xb3\xe2\xe2\x01\x89\x05\x1c\xf2\x9f\x5c\x43\x88\xad\ +\x0b\xc0\x9c\xb3\x3f\x01\x3f\x95\xec\x0c\xa5\x64\xe5\x30\x22\xa5\ +\x00\x9f\xaf\xc5\x91\x63\xe4\x0e\x01\xb6\xe5\xeb\x9c\xf0\x0b\xc9\ +\x58\x38\x22\x23\xc3\x42\x08\x2f\x20\x10\x08\xd0\x19\x57\xe6\x3a\ +\x01\x2a\x0d\xa3\x1b\x0f\x6f\x87\xcf\x89\xf6\x2f\x84\xf0\x02\xfa\ +\x5f\x8f\x9d\xc5\xec\x7f\x83\x7f\xe9\xb3\x4f\x39\x75\x48\xda\xeb\ +\xff\x85\xd0\x5d\xc0\xe7\x6b\x71\xcc\xb8\x32\x13\x00\x4a\xf2\xe4\ +\x37\xc5\x8e\xa2\x8a\x7b\x1d\x57\xa5\x3c\xef\x17\x42\xe8\x0a\xf8\ +\xb2\xe9\x37\xe3\x40\x36\x5f\xb2\xe5\xec\x35\xcb\xe5\xe2\x01\xc1\ +\xaf\xc5\x3f\x0f\x0c\x30\x77\xd9\xae\x61\xc2\xe1\xe1\x04\x1f\x08\ +\x25\x75\xc9\x78\xf0\xad\x48\x4f\x85\x42\xa1\x50\x28\x14\x0a\x85\ +\x42\xa1\x50\x28\x14\x8a\x42\xfc\x01\xea\x12\xdd\x53\xe7\x12\x49\ +\xf2\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x75\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x27\x49\x44\x41\x54\x78\x9c\xed\ +\xc1\x01\x0d\x00\x00\x00\xc2\xa0\xf7\x4f\x6d\x0e\x37\xa0\x00\x00\ +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x77\x03\ +\x40\x40\x00\x01\x8f\xf2\xc9\x51\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x06\xb5\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x06\x67\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4d\x70\x5b\x57\x15\xc7\x7f\xe7\x2a\x85\x94\xd0\xa4\x4d\x3f\ +\x67\x18\x16\x0c\xbb\x34\x49\x93\x36\xb4\x14\x18\x68\xac\x2f\xa7\ +\x8d\xed\xda\x8a\x76\x6d\x67\x62\xd9\x1e\xd6\xac\xca\x02\x16\x4c\ +\x16\x6c\xd8\x32\x53\x5b\x76\x57\xed\x46\xb6\x34\x0c\x4d\x1b\x3f\ +\xe9\xc9\xe5\xa3\x84\x0e\xe5\xa3\x2d\x30\xcc\x74\x4a\x17\xdd\x51\ +\x0a\xc4\x69\x6a\x3b\x13\xdd\xc3\xc2\x92\x31\xfa\xbc\x4f\x7a\xcf\ +\x36\x83\xff\xcb\x7b\xcf\x3b\xe7\xfc\x7f\xbe\xf7\x3e\x3d\xe9\x19\ +\xf6\xb5\xaf\x7d\xfd\x3f\x4b\xda\x0d\xa6\x9e\x7d\xf6\x90\xae\x7d\ +\xf6\x3b\x28\x23\xc0\x41\x85\xab\xc6\xf0\x43\xaf\x90\xff\x60\x87\ +\xfb\xeb\x4b\xa9\xec\xd4\x97\xac\xe5\x79\x81\xc7\x81\x75\x55\x2e\ +\xdf\x8a\x7d\xe6\x47\xaf\x17\x7e\xfc\x49\x73\x6c\x0b\x80\xd1\xd1\ +\xc9\x3b\xd6\x6e\x33\x3f\x03\x4e\x37\x4d\x5d\x13\x4c\xda\x5b\x9a\ +\x7d\x33\xa2\xbe\x43\x51\x7c\x62\xfa\x2b\x46\xb4\x0c\x1c\xf9\xef\ +\x19\x79\xfb\xc0\xc1\x4f\xbf\xf9\xda\x4b\x2f\xad\x6e\x1f\x35\xcd\ +\x09\xd6\x0e\x98\xe7\x69\x35\x0f\x70\x44\x51\x2f\x95\x99\x79\x2c\ +\xc4\x7e\x43\x55\x67\xf3\x00\xfa\x50\x6d\xfd\xf6\xef\x36\x8f\xb6\ +\x00\x40\x18\xed\x5c\x42\x0f\xef\x55\x08\xdd\xcd\x6f\x4a\x61\xac\ +\x79\xac\x05\x80\xc0\xed\xdd\x4b\x6d\x42\x48\x67\x73\x8f\xf6\xd1\ +\x67\x24\x4a\x66\x26\xcf\xf4\x32\x5f\xd7\xc1\xe6\x81\xd6\x15\xa0\ +\xbc\xd1\xbb\xa4\x1e\xb6\xd6\x94\xf7\x02\x84\x64\x66\xf2\x0c\x98\ +\x0a\xbd\xcd\x03\xad\xde\x5a\x00\xa8\xc4\x2e\x01\xd7\x7a\xe7\xda\ +\x7d\x08\xc1\xcc\xcb\x2a\xc4\x7e\xd0\x3c\xda\x02\xa0\xbc\xf4\xc2\ +\x7b\xc6\x68\x0a\x67\x08\xb2\x2b\xdb\xa1\x6e\xde\x65\xd9\x03\xb2\ +\xaa\xaa\xe9\xf2\xd2\x0b\xef\xb5\xcc\x74\xba\x24\x9d\xcd\x3d\x6a\ +\xad\x29\x83\x1e\x76\xe8\xe7\x9a\x55\x49\xfa\xc5\xb9\xdf\x38\xc4\ +\x0e\xac\x54\x76\xea\x11\xb5\x54\x80\x3b\x7b\xc5\x2a\x5c\x47\x49\ +\x55\x8a\xf9\x5f\xb7\x9b\xef\x08\x00\xf6\x26\x84\x30\xcd\x43\x0f\ +\x00\xb0\xb7\x20\x84\x6d\x1e\x1c\x00\x00\xa4\x32\x33\x8f\x29\xea\ +\xb9\x42\x00\x9b\x28\x2f\x2d\xbc\xe5\x92\xdb\x55\xe9\x89\x99\x87\ +\x2d\xb6\x82\x70\x57\xaf\x58\x85\xeb\x6a\x6c\xda\x2f\x2c\x5c\xed\ +\x15\xeb\x04\x00\x76\x17\x42\x54\xe6\xa1\xdd\xe7\x80\x0e\xf2\x96\ +\x66\xdf\x54\xd5\xf4\xe6\xed\xa4\xa7\x8e\x80\xa9\x6c\x9e\xd4\x83\ +\x29\xa8\x79\x23\x32\xec\x6a\x1e\x02\xac\x80\x86\x12\x13\x53\x5f\ +\x45\xf0\x04\xee\x70\x08\xff\x17\xd8\x64\xbf\x2b\x21\x88\x79\xe0\ +\x13\x11\x49\x7b\x8b\x73\xbf\x0a\x52\x23\x30\x00\x08\x0e\x41\x0c\ +\x09\xaf\x90\xff\x6d\x90\x1a\x3b\x61\x1e\xfa\x04\x00\xd1\x42\x48\ +\x64\x72\xa7\x45\xc5\x8f\xda\x3c\x0c\x00\x00\x20\x9e\x9d\x7c\x5c\ +\xac\x59\x0e\x13\x42\x50\xf3\xa8\x0e\x97\x8b\xf3\x0e\xcf\x2f\xed\ +\x35\x10\x00\x08\x17\xc2\x4e\x9b\x87\x00\x77\x81\x4e\xf2\x0b\x0b\ +\x57\x8d\xc8\xb0\xc2\x75\x87\xf0\x3b\xb5\x46\x39\x3d\x31\xf3\x70\ +\xf3\x44\x22\x93\x3b\x2d\x88\xf3\x9e\x57\x63\xce\x0d\x6a\x1e\x42\ +\x58\x01\x0d\xa5\x2e\x4c\x7f\x4d\x55\x97\x81\xcf\xf7\x0c\x56\xfe\ +\x69\x30\x89\xe5\xe2\xec\xef\x00\x92\xd9\xe9\x53\x58\xf5\x81\xa3\ +\x0e\xa5\x6e\xa8\x31\xc3\x95\xc2\xec\x2f\x07\xeb\x78\x53\xa1\x01\ +\x80\xfe\x20\xd8\x98\xda\xdd\x32\x0f\x21\x03\x80\x80\x10\x44\x57\ +\x51\x00\x71\xf9\x74\x19\xba\x79\x88\x00\x00\x40\x72\x22\xf7\x75\ +\x44\xae\xe0\x02\xc1\x4d\x37\x8c\x70\x6e\x79\x31\xff\x8b\x90\xf2\ +\x6d\x29\x12\x00\x10\x2a\x84\xc8\xcc\x43\x08\x77\x81\x4e\x2a\x17\ +\xe7\xdf\x50\x63\xce\x01\x2d\x3f\x46\x04\xd0\x0d\x51\x7d\x32\x2a\ +\xf3\x10\xe1\x0a\x68\x28\x91\x9d\xf9\x86\x58\x7b\x05\x38\x14\xf0\ +\xd2\x1b\xa2\xfa\xa4\x57\x9c\xff\x79\x14\x7d\x35\x14\x39\x00\xa8\ +\x43\xa8\x59\x0f\xe9\xf5\x95\x7b\x5d\xc2\xba\x58\x4d\x47\x6d\x1e\ +\x22\xdc\x02\xdb\xa5\xd6\xae\x22\x72\xd3\xfd\x02\xbd\xa9\x31\xe3\ +\xf2\xd8\x3d\xb0\x22\x07\x10\xcf\x4c\x9d\x34\x50\x05\x75\xf9\xde\ +\xbe\x2e\x39\x8c\x55\x3f\x99\x9d\x3e\x15\x5d\x67\xf5\x4a\x51\x26\ +\xff\x8f\x79\xee\xee\x33\xc5\x3f\x30\x12\x2f\x17\xe6\xfe\x10\x66\ +\x5f\xdb\x15\xd9\x0a\x88\x67\xa6\x4e\x1a\xc5\xa7\x7f\xf3\x00\x47\ +\xb1\xea\xa7\xc7\x27\x1f\x0a\xab\xaf\x66\x45\x02\x20\x91\x9d\x39\ +\x61\x14\x1f\xe1\x9e\x10\xd2\x1d\xb5\xc6\x54\xa3\x82\x10\x3a\x80\ +\x44\x76\xe6\x84\xd4\x6c\xd5\xc5\xbc\xc0\x86\xc2\x86\x43\xda\xa3\ +\xd6\x98\x48\x56\x42\xa8\x00\x82\x98\x07\xd6\xac\x30\x6c\x54\x53\ +\xc0\xa7\x0e\xf1\x77\x47\x01\x21\xbc\xc7\xe1\xf1\xdc\x71\x15\x59\ +\x71\x35\x6f\xd4\x3e\xb5\x5c\x5c\x58\x01\x48\x66\xa7\xbf\x85\xd5\ +\x57\x81\xcf\x39\x5c\xfb\xb1\x85\x21\x7f\x29\xff\xce\x40\x0d\xd7\ +\x15\x0a\x80\x41\xcc\x37\xb4\x5b\x10\x06\x06\x10\xd4\xbc\x58\xce\ +\x7b\xa5\x7c\xb5\xdd\x64\xe2\xc2\xd4\x13\xa2\x5c\x66\x07\x21\x0c\ +\x74\x06\xa4\xc6\x73\xc7\xd5\x88\xf3\x9e\xef\x66\x1e\xa0\xb2\x98\ +\x7f\x5d\x85\xa7\x70\x3c\x13\x8c\xe2\xc7\x33\x53\x27\x9d\x1b\x6e\ +\xa3\xbe\x01\x6c\x99\x87\x7b\x1d\xc2\xd7\x10\x1d\xe9\x66\xbe\xa1\ +\x6d\x10\xd6\x7a\x66\x15\xee\x31\x8a\x9f\xc8\xce\x9c\x70\xe8\xa1\ +\x43\x8a\x3e\x94\xce\x4c\x3f\x68\xd1\x15\xdc\xcc\xaf\x23\x7a\xbe\ +\xbc\x38\xef\x07\xa9\x51\xdf\x0e\xaf\xd2\xf3\x9d\x25\x40\xf9\xbb\ +\xc6\xcc\x50\xa5\x30\xfb\x6e\x90\x1a\xd0\x07\x80\x9d\x30\xbf\x55\ +\x6b\x62\xf2\xac\x15\x73\x99\x08\x21\x04\x02\x50\x37\x5f\x05\xee\ +\x73\x08\x1f\xc8\xfc\x56\xcd\x80\x10\x44\xf5\xac\x57\x9a\xff\xa3\ +\x6b\x7e\x67\x00\x41\xcd\x5b\x95\x11\xbf\x38\x57\x71\xcd\xdf\x4d\ +\xa9\xf1\xa9\x21\x35\xbc\x42\x04\x10\x9c\x0e\xc1\x78\xf6\xe2\xb1\ +\xdd\x32\x0f\xe0\x95\xf2\x55\xb1\x9c\xc7\xf1\x60\x54\x91\x95\xd4\ +\x78\xee\xb8\x4b\xee\x9e\x00\xe2\xd9\x8b\xc7\x8c\x8d\xad\xe0\x68\ +\x5e\x2c\xa3\x61\x9a\x6f\xc8\x2b\xe5\xab\x88\x8e\xe0\x0a\xc1\x48\ +\xd5\x05\x42\xd7\x2d\xd0\x8f\x79\xaf\x94\x2f\x3b\xc4\xf6\xad\xe4\ +\x85\x5c\x1c\x95\x57\x68\xf3\xd6\x67\x1b\x7d\x24\x56\x87\xba\x6d\ +\x87\x8e\x2b\x20\x9e\xbd\x78\xcc\x68\x2c\xc0\x81\x67\xc7\xa2\x36\ +\x0f\x50\x5e\x9c\xf7\x11\x3d\x0f\xac\x3b\x84\xdf\xab\x46\xaa\xe9\ +\xcc\xf4\x83\x9d\x02\xda\xae\x80\x2d\xf3\xca\xfd\x0e\x45\x36\x10\ +\x3b\x5a\x5e\x5c\xf0\x1c\x62\x43\x53\xd0\x95\x60\x90\xb3\xcb\x4b\ +\x73\x7f\x6a\x9e\x68\x01\x30\x94\xfd\xf6\x17\x0e\xd8\x5b\x6f\x29\ +\x3c\xe0\x90\x78\x57\xcc\x37\x14\x9f\x98\x4e\x18\xd1\x9f\xe2\x06\ +\xe1\x6f\x72\xab\x76\xc6\xfb\xc9\x8b\x1f\x6e\x1f\x6c\xd9\x02\xb1\ +\x5a\xed\x7b\xff\x0b\xe6\x01\xfc\xe2\x5c\xc5\xaa\x8c\xe0\xb6\x1d\ +\xee\xd3\x58\xec\xfb\xcd\x83\x6d\x5e\x96\xd6\x27\x1c\x92\x6d\x28\ +\x32\xb6\x9b\xe6\x1b\xf2\x8b\x73\x15\xb1\x8c\xe2\x00\x41\x84\xb3\ +\xcd\x63\x6d\xfe\x5f\x40\x6a\x3d\xf2\x6c\x28\x32\x56\x59\x9a\x5b\ +\x76\x6f\x33\x5a\x79\xa5\x7c\xd9\x05\x82\x42\x8b\xb7\x56\x00\xa2\ +\xdd\xfe\xaa\x1b\xd6\xea\xd3\x7b\xc9\x7c\x43\x5e\x29\x5f\x46\xec\ +\x18\xdd\x21\x5c\x69\x1e\x68\x01\x50\xab\xdd\xbc\x24\xf0\x7e\x9b\ +\x8b\x37\xac\xd5\xa7\xfd\xd2\x7c\x4b\x92\xbd\xa2\xf2\xe2\x82\xd7\ +\x05\xc2\x07\x07\x4c\xed\x52\xf3\x60\xac\x25\xea\x2f\x6f\xaf\x7d\ +\xf1\xd4\x99\x97\x63\x35\x3d\x04\xdc\x0f\xdc\x44\xd4\x37\x1a\x7b\ +\xae\x5c\x8a\xee\x57\xda\xb0\xf4\xd7\x3f\xff\xfe\xfd\x2f\x1f\x7f\ +\xe4\xb2\xaa\x3c\x20\x9b\xef\x1b\x7d\xac\xaa\x2f\xdf\x16\xb3\xcf\ +\xbc\x56\x78\xf1\xa3\xdd\xee\x6f\x5f\xfb\xda\xd7\xde\xd2\xbf\x01\ +\xee\x83\x44\x52\xf4\x9c\x9a\x3b\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x03\x62\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x14\x49\x44\x41\x54\x78\x9c\xed\ +\x9a\x3b\x68\x14\x51\x18\x85\xcf\x99\x5d\x30\x62\xb0\x11\x11\x31\ +\x85\xc1\x58\x08\x01\x0b\x61\x77\xed\x02\xbe\x30\x85\x8f\x0d\x31\ +\x60\x97\x80\xa8\xa4\xb3\x09\x29\xad\x8c\xa5\x90\x20\x5a\x58\x5a\ +\x24\xee\x86\x20\x24\x82\x0a\x16\x82\xd9\x80\x45\x24\x85\x85\xa2\ +\xc5\x82\x88\x58\x28\x3e\x12\xdc\x9d\x63\x13\x44\x77\x66\x77\x33\ +\x33\x7b\xf7\x26\xce\x7c\xe5\x9d\x9b\xf3\x9f\x39\x99\xc7\xbf\x77\ +\x2e\x90\x90\x90\x10\x67\x18\x55\xa0\x6f\x5a\x9d\xab\x69\x8c\x0a\ +\x1a\x14\xd0\x4b\x60\x5b\x2b\x8c\x85\x45\xc0\x1a\x81\x15\x82\x33\ +\x1d\x15\x4c\x3d\xbb\xc0\x6f\x8d\xe6\x47\x0a\x20\x5b\xd4\x09\x40\ +\xf7\x00\x74\x45\xd1\x31\x48\x19\xe0\x48\x29\xcf\xc7\xf5\x26\x38\ +\x61\x95\xb3\x45\x8d\x00\x7a\x84\xcd\x7b\xf2\x00\xd0\x05\x68\x21\ +\x5b\xd4\x70\xbd\x09\xa1\xae\x80\xec\xac\x4e\x42\x5a\x40\x84\x00\ +\xdb\x4c\x15\xe0\x69\xbf\x2b\x21\x70\x00\x7d\xd3\xea\xfc\x99\xd6\ +\x6b\x00\xfb\x5a\x62\xad\x7d\x94\xb7\x57\x78\xa8\xf6\x99\x10\xf8\ +\x3f\xb8\x9a\xc6\x28\xb6\xde\xc9\x03\x40\xd7\xba\xf7\x7f\x08\x1c\ +\x80\xa0\xc1\xd6\xf8\x69\x3f\x7e\xde\x43\x04\x80\xde\xd6\xd8\x69\ +\x3f\x7e\xde\xd3\x41\x45\x9a\xbd\xe7\x4b\x79\x27\x72\x6f\x11\x85\ +\x6c\xd1\x55\xbd\x63\x7e\xde\xb7\xca\x53\xdc\x18\x49\x00\xb6\x0d\ +\xd8\x26\x09\xc0\xb6\x01\xdb\x24\x01\xd8\x36\x60\x9b\xd8\x07\xd0\ +\xb4\x11\x3a\x52\xd0\xde\xb4\xe3\x5e\x95\xcb\x63\x20\xf6\x34\x9b\ +\x9f\x29\xba\x6f\xc2\x9a\xa1\x20\x10\x65\x81\xf3\xec\xc0\x9d\x52\ +\x3f\xbf\x86\xd5\xda\x70\xcd\x46\x07\x73\x05\x9d\x11\x75\x0f\xc0\ +\x2e\xd3\x46\x3c\x08\xef\x00\x5e\x2c\x0d\x70\x31\xc8\x9f\x35\xea\ +\x04\x01\x6f\xa7\x5a\xf7\x16\xc8\x14\xab\x13\xa2\xe6\x60\xe3\xe4\ +\x01\x80\xe8\x06\xf5\x3c\x53\xd4\x15\x93\x65\x7c\x03\xc8\x15\x34\ +\x44\x70\xcc\x64\xe1\x0d\x92\x22\x34\x99\x2d\x28\x67\xaa\x80\x27\ +\x80\xdc\xac\xf6\x8b\xba\x6b\xaa\x60\x08\x52\x80\xee\x67\xe7\xb5\ +\xd3\x84\xb8\x27\x00\xb9\xee\x38\x00\x23\xc5\x42\x43\x74\x6b\x15\ +\x97\x4d\x48\x7b\x6f\x01\xb2\xdf\x44\xa1\xa8\x10\x32\xe2\xcb\xef\ +\x19\xb0\x39\x57\x79\x65\xc6\x57\xe0\x05\x11\x27\xc5\x83\x26\x8c\ +\xa0\x8a\x1e\x17\x5a\xa8\x77\x58\x8c\xfe\x11\xc7\x8f\xc0\x01\xbc\ +\x38\xcb\xd0\x8d\x4e\x23\x8e\xce\x09\xa8\x9a\x50\x6e\x4c\xec\x5b\ +\xe1\x24\x00\xdb\x06\x6c\x93\x04\x60\xdb\x80\x6d\x92\x00\x6c\x1b\ +\xb0\x4d\x12\x80\x6d\x03\xb6\x49\x02\xb0\x6d\xc0\x36\x49\x00\xb6\ +\x0d\xd8\x26\xf0\xaf\x41\x5b\x10\x38\xd0\x6c\xc5\xb7\x19\x02\xd6\ +\x6a\xc7\x62\x75\x05\x10\x58\xa9\x1d\x8b\x59\x00\x9c\xa9\x1d\x8b\ +\x53\x00\xe5\x8e\x0a\xa6\x6a\x07\xe3\x12\x40\x15\xe0\x88\xdf\xbe\ +\xe1\x38\x04\x50\x05\x78\xa9\xde\x7e\xe1\x2d\xf3\x16\x08\x49\xd3\ +\xcd\xd2\xff\x5d\x00\x7f\x6f\x97\xff\xb1\x03\x93\xaf\x4e\xf1\x7b\ +\xa3\xf9\x9e\xa5\xe6\xa8\xef\x5a\x53\x08\x78\xbb\x94\x77\x7a\x5a\ +\xad\xeb\xfd\x34\x06\x7c\x6a\x75\x91\x96\x20\x7c\x34\x21\xeb\x09\ +\x80\xd0\x13\x13\x85\xa2\x42\x47\x4f\x4d\xe8\xfa\x5c\x01\xce\x4d\ +\x00\xbf\x4c\x14\x8b\xc0\xe7\x8a\xeb\xdc\x36\x21\xec\x09\x60\x29\ +\xcf\x65\x6d\x8e\xbd\x01\x7f\xa0\xc3\xe1\x97\x03\xfc\x60\x42\xdb\ +\xb7\x0f\x58\x5a\xc6\x2d\x00\x0f\x4c\x14\x0c\x8e\x26\x16\xcf\xf1\ +\xa1\x29\x75\xff\x46\xe8\x3a\xdd\xd2\x32\x87\x04\x5e\x83\xbd\xdb\ +\xe1\x0b\xc9\xa1\x52\x3e\x35\x6e\xb2\x48\xd3\x2f\xae\x99\xa2\x0e\ +\x13\xee\x98\xc0\xe3\x04\x76\x9b\x34\xb3\x4e\x19\xd2\x3c\x1d\xe7\ +\xc6\xe2\x79\xbe\x6f\x43\xbd\x84\x84\x84\x18\xf3\x1b\xe9\x0c\xd1\ +\x12\xec\xcb\x09\x01\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ +\x82\ +\x00\x00\x00\x79\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x2b\x49\x44\x41\x54\x58\x85\xed\ +\xce\x41\x01\x00\x20\x0c\xc4\xb0\x0d\x6f\x28\x98\x05\xfc\x5b\x00\ +\x19\xc7\x23\x31\xd0\x56\x01\x00\x61\xbd\xe7\xdc\xe4\xc0\x4a\xc6\ +\x01\x80\x2f\x3c\x1a\xe8\x01\xff\xf7\xcd\x6b\x25\x00\x00\x00\x00\ +\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x0c\xd6\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x0c\x88\x49\x44\x41\x54\x78\x9c\xe5\ +\x9b\x5b\x6f\x5b\xc7\x11\x80\xbf\x25\x45\x8a\x94\x28\x89\x92\xad\ +\xbb\x64\xc9\x4e\x9a\xc2\x41\xe0\x26\x45\xd1\xa0\x48\x0a\xf4\xa9\ +\x7d\xe9\x7b\x81\x16\xfd\xa3\x7d\x2a\x50\xb4\x0f\x41\x90\x36\x4e\ +\x52\x20\x69\x92\xc6\x96\x6c\xc9\x37\x5d\x48\x49\xa4\x2e\xe4\xf4\ +\x61\xf6\x1c\xee\xd9\x33\x87\xa4\xe4\xf4\xc9\x03\x10\x24\x77\xf7\ +\xcc\xce\xcc\xee\xce\x6d\xe7\x00\xb2\x05\xe2\x78\xe3\x40\x9c\xf2\ +\x9e\xfe\x78\x93\x84\x90\xe3\xf9\x4d\x12\x42\x96\x57\x97\xed\xe0\ +\x0e\xf0\x18\x9c\x14\x3c\xdc\x00\x6e\x19\x1d\x25\x60\x32\x8b\x2f\ +\x6d\xaf\x0d\xa1\x66\x12\x10\xe0\x62\xc8\x98\x73\xa0\x67\xb4\x77\ +\x81\xbe\xd1\xfe\x12\xdc\xa9\x8d\x2a\xcf\xa3\x1b\x35\x00\x64\x1b\ +\xb8\xed\x09\x3d\x01\x5e\xf8\x89\xa7\x80\x39\xdf\x2e\xc0\x59\xd0\ +\x3e\xeb\xdb\xfa\xbe\x1d\x8f\xa3\x0a\x34\x81\x8a\xef\x3f\xf7\x34\ +\x54\xfd\xf7\x25\x70\x04\x97\xa7\x50\x39\xf2\x6d\x53\xa8\x20\x9d\ +\x9f\xff\xc4\xff\x9f\xf2\x6d\x0e\x68\x01\xa7\xbe\x7d\x29\xe8\x7b\ +\x01\xee\x71\x31\x6f\x85\x52\x92\x2d\x90\x09\x90\x8f\x40\x56\x8d\ +\x31\x6b\x20\x0b\x46\xfb\x06\xc8\xbc\xff\x3d\x05\x72\x0f\xe4\xae\ +\xff\xcc\x80\xdc\x01\x19\xb2\x23\xa4\xee\xc7\x2c\xa8\xe0\xe5\xae\ +\xc7\x31\xe1\xfb\xe7\x40\x36\xf3\x47\x55\x9a\x05\xed\x1b\x20\xbf\ +\x06\x29\x5f\xf3\x88\xcb\x04\xc8\x9f\xf5\xc1\x5c\xdf\x36\x48\xc5\ +\x68\x7f\xdb\x3f\xb7\xe2\x27\x5b\x8e\xf0\xdd\x1b\x73\x72\x3c\xe3\ +\x25\xff\xdb\x79\x46\xb6\xa0\x75\x4b\xdb\xe5\x2d\x83\xd9\x32\xc8\ +\x4f\x8c\xf6\x09\x90\x3f\xda\xbc\x14\x13\xf0\x91\x7f\x30\x92\x9a\ +\xac\x17\x30\x7f\xc7\x7f\xb6\xed\x15\x96\xed\x6b\x4c\x4e\x60\xa2\ +\xe2\xf6\x59\x15\x4e\x7b\x49\xe7\xcb\xf5\x97\xb3\xcf\xa5\xbb\xb9\ +\x02\xf2\xab\x71\x27\xdf\x1e\x6c\xfb\x50\x63\xca\x14\xc8\x6d\x63\ +\xfc\x2a\xc8\x07\xba\x7d\x4d\x7c\xf3\x5e\x79\x5e\x13\x64\x56\xb7\ +\xbc\xd9\x37\x07\xf2\x00\x64\xd1\xe8\x6b\xfa\x67\x23\xcb\x26\x9b\ +\xfa\xc9\x82\x71\x26\xe4\x17\xe0\x3e\x0d\xfe\x27\xca\xa3\x07\xec\ +\x01\x21\xa3\xab\x70\x79\x0b\x2a\x5f\x0e\xe1\x64\x0d\x78\x5a\xd0\ +\x97\xda\xe1\x1b\x3c\x0b\xf0\x00\xba\x4f\xa0\xf6\x2a\x68\xeb\x28\ +\x5d\x94\xc9\x29\xbc\x98\x37\x98\x30\x90\xc6\xc4\x34\x50\xe6\x1f\ +\xa0\x5a\xbd\xed\xc7\x6c\x01\x2f\x54\xa1\x0f\x05\xf1\xc4\x2c\xf9\ +\xff\x89\xe9\x4a\x34\x78\xd8\x46\xd0\xf6\xc2\xa0\x25\x86\x17\x20\ +\x82\x32\xbc\xe7\x9f\x5d\x02\x7e\x06\x7c\x0e\xcc\xa0\x16\x22\x81\ +\x9c\xd9\x8c\x04\x20\x0d\xd4\xcc\x24\xff\x37\x80\x36\xb8\x5d\x3f\ +\x51\x05\x35\x5d\x9b\xc0\xd7\xe0\xae\xf4\x7c\xb9\x13\x72\x20\xce\ +\x8f\x9b\x42\x7d\x81\x6f\x47\x98\x9f\xf8\xd9\x45\x60\x1a\x35\xa9\ +\x7b\xf6\xb3\xd2\x86\xfa\x0b\xd4\x9f\x58\x01\x7e\x00\x16\x80\xcf\ +\x80\xe7\x80\xb7\x3c\xec\xf8\xe7\x7b\xaa\xdb\xdc\x55\xd1\xc4\x5b\ +\x03\xf3\x26\x5b\x59\xcd\x29\x1b\x5e\x0f\x7c\x1c\x29\x46\xcb\x4c\ +\x2e\xa1\xa6\x72\x46\x3f\x37\x05\x59\xf5\xca\x78\x3d\x6b\x55\xd2\ +\xfe\x99\x81\x7e\x91\x09\x90\xdf\x78\x2b\x11\xb6\x07\x8a\x51\xee\ +\xaa\x8e\x18\x40\xc9\x98\xb5\xaf\x13\xb2\x0b\xae\x17\x8d\x5d\x03\ +\xfe\x0e\xdc\x09\x84\x10\xac\xcc\x61\x53\x19\xe7\x10\xdc\x53\xdf\ +\x37\xe6\xaa\x9b\xe0\x9f\x75\x4f\x80\x03\xc5\x7d\xd8\xcc\xf7\x8b\ +\x03\xd6\x81\xbf\x01\xf7\xb2\x73\xba\x9e\xf2\x22\xeb\x18\x47\xc0\ +\x12\xc0\x14\x70\x16\x31\x0f\x7a\xe6\xbf\xf3\x5b\xe9\x31\x59\x21\ +\xa0\x1a\xb9\xd9\x57\xc6\xdd\xe5\xf8\x3c\x8e\x0b\xee\x52\x71\x37\ +\xfb\xd1\x6e\x08\x3d\xbc\x1e\xf0\x04\x3d\x7a\xe1\x90\x1e\xea\x29\ +\x4e\xc7\x58\x2d\x25\x38\xe7\x57\x2f\x00\xd9\x46\x95\x4c\x29\x30\ +\x77\x07\xc0\x7d\xe0\xd2\x9b\xab\x57\xe8\xee\x09\x4d\x9e\x9f\xd0\ +\xdc\x04\x25\xe8\xfa\xe3\x56\x3b\xc4\xf6\xf7\xa7\x81\x2e\x48\x78\ +\x66\xfb\x3a\x56\xee\x03\x47\xe8\xca\x7f\xad\x63\x05\xa0\x03\x9d\ +\x13\xa8\x2f\x92\xd1\x67\xee\x08\xe4\xa7\xf1\x04\x63\x58\x01\x79\ +\x0b\x2e\x2a\x50\x9d\x46\x15\xd3\x29\x83\xad\xbd\x0b\xfc\x0e\xf8\ +\x4b\x01\x03\x01\x74\xe6\xa1\x9e\x04\x3f\x3e\x4e\xa8\x1d\xf9\xce\ +\x79\xd4\x52\xf8\x1d\xd5\x39\x87\xfa\xe1\x10\x64\x5d\xd4\x3c\xfe\ +\x06\xf8\x24\xa0\xd9\x2b\xcf\x7a\x0d\xb8\x0d\x72\x1e\x2d\x66\x6e\ +\x25\x62\x01\xc4\xd1\xe1\x5d\x60\x1a\x26\x1f\xaa\x12\x74\xfb\xd9\ +\xe1\xb2\x0e\xfc\x03\x0d\x70\x8c\x20\x43\x80\xee\x6d\xa8\x4d\x40\ +\xfd\x25\xb8\x4e\x01\x43\x47\xd9\xbf\x52\x07\x16\xe0\xa2\x06\xd5\ +\x93\xbc\xd6\x4e\x7d\x93\xbf\x02\x6b\xe0\xf6\x82\xce\x36\xc8\x09\ +\xba\x63\xdf\xf6\x9e\x6b\x42\x5b\x9f\xe8\xd8\xc7\x3a\xa0\x0a\x9c\ +\xfb\x09\xee\xa1\xab\xf2\x85\x4d\xb3\x2c\xa1\xdb\xbe\x87\xad\x13\ +\xa6\x81\x55\xa8\xb5\x55\x89\x15\x32\x6f\x80\xeb\xe8\x33\xd5\xb6\ +\x32\x18\x1e\xab\x30\xaa\xa3\x87\xfa\x02\x2b\x05\x88\xbe\xf1\x63\ +\xee\xf9\xe7\x3a\x64\x1d\xb9\x22\x2b\xc0\x06\xf0\x0c\xf5\x01\x8c\ +\x03\x7c\xd8\x04\xba\xe0\xba\x9e\xe0\x48\x31\x1e\xcd\x43\xbb\x86\ +\xae\xc2\xf9\x58\x3c\xdb\x70\x01\x3c\x85\xf6\x24\x1c\x2f\x60\x87\ +\xb4\x5d\xe0\x4c\xe7\x8c\xc1\x9d\xa1\x8b\xfa\x83\xe7\x29\xc7\x8b\ +\x25\x80\x06\xea\x3d\x2d\xe6\xb7\x7c\x02\xcd\x29\x70\xad\x6c\x5b\ +\x22\x84\xcb\xf7\x61\xae\x07\xb3\xaf\xcc\x47\x6f\x04\xb3\xaf\x60\ +\xf6\x52\x71\x5b\x47\xcd\xb5\x60\xae\x20\x16\x61\x07\x35\xdf\x2d\ +\xd4\xc2\x65\xc0\x12\xc0\x34\xaa\x3d\x0b\x94\x9a\x2c\xa3\x6e\xaa\ +\x01\xc7\x4d\xa8\x7c\x0f\xcc\x33\x7e\xec\x3d\x06\x88\x03\x16\xa0\ +\xf2\x9d\xce\x61\xc2\x73\xdb\x59\x72\x97\x40\x19\xdc\x31\xba\xb8\ +\x19\xb0\x04\x20\xa8\x69\xd9\x29\x20\x64\xc2\xb6\xf3\x32\x05\xa5\ +\x64\x22\x7f\x1c\xac\x60\xeb\xda\x10\x6e\xfb\x16\x94\x4a\x5e\xbf\ +\xc4\xc3\xae\x94\x36\xb1\x78\x3a\xd4\x23\x34\xda\x0a\x94\x07\x83\ +\x4c\xbf\x7d\x13\xd5\xb2\xe1\x2a\xcc\x82\x74\x81\x15\x98\xd9\x0f\ +\xfa\x5a\xc0\xbb\xc0\x13\xd2\x8c\x4e\x06\x92\xd4\x19\xa8\x4f\x61\ +\xe5\x05\xe7\xd0\x40\xe7\x07\xfd\x2d\xa0\x3b\x73\x03\xe4\x19\x03\ +\x3f\x23\xc1\x7f\xa6\x7d\x1c\x64\xd1\xb8\x63\xef\x0e\x27\x81\x59\ +\x0a\x31\x61\x35\x72\x49\x48\x99\x47\x83\x8d\x65\x4f\x64\x84\x9c\ +\x1e\x74\x66\xa1\x7e\x00\xc4\x41\xc6\x23\x4f\xd0\xd7\xc1\xe4\x2b\ +\x40\x1f\x3a\x67\x50\xdf\x05\x1c\x74\x6f\x41\x2d\xc9\x2f\x3e\xf3\ +\xdf\xce\xcf\xf9\x05\x9a\x2b\x0c\xe1\x15\x74\x66\xa0\x9e\x08\x2d\ +\x9c\xb7\x89\x2a\xbe\xbe\xee\x86\x54\x57\x25\x79\xcb\x4c\xc2\xc6\ +\x5a\x99\x45\xe0\x4b\x90\xaa\x27\xe0\x25\xb8\x43\x34\xd3\x73\x96\ +\x8f\xfc\xa4\x01\xf5\x32\xb8\xe7\x79\x54\x82\x67\x7e\x01\x38\x46\ +\x57\xec\x1b\x63\x77\xb5\xfd\xf8\x32\xba\xe2\x07\x9e\x8e\xff\x68\ +\x5f\x2e\x7a\x3b\xf1\xa6\xcf\x67\x7f\x43\x9a\x64\x1f\x15\x98\x17\ +\x9a\x6c\x02\x4f\xe0\xa4\x03\x8d\x29\xb2\xe1\xb1\xa9\x03\x4a\xa8\ +\x04\x6f\x83\xdb\x09\xec\xf7\x2d\x6c\xe5\x37\x0d\x47\x05\x69\x68\ +\xa5\x00\xcd\xf4\x6e\x01\x4f\x87\x87\xc4\xa9\x2f\x7f\x1f\x0d\x67\ +\x87\x05\x52\x27\x18\xbe\xbd\x5f\x08\x9f\xb9\x72\x27\xa8\xb7\xba\ +\x01\x8d\x03\xf4\x48\x65\xa0\x48\x09\x2e\xe5\xe3\x01\x28\x20\xbe\ +\x01\xf3\x47\x46\x7b\x02\x65\x25\xb4\xf2\x90\x9c\xb3\x94\x9b\x3a\ +\x51\x78\x9f\x61\xdf\x3f\x84\xb4\x14\x08\x20\x37\x4e\x7c\x6a\x7c\ +\xcd\xea\xb5\x04\xb0\x00\x58\xf6\xdf\xba\x84\x18\x07\x56\x18\x24\ +\x34\x0c\x8f\x31\x81\x9c\x93\xf3\x12\x2e\x8c\xd4\x7b\x06\x8a\x84\ +\x69\xd1\xfa\x0a\x43\x60\x05\x47\xe0\x5a\xe1\xec\x28\xc1\xf4\x07\ +\x3b\xa7\x30\x94\x36\x3c\x3c\xd7\x85\xea\xa8\x7c\xdb\x35\x72\x0d\ +\xee\x0c\x55\xe6\x19\x88\x05\x30\x41\x71\x54\x77\x13\x9b\x5e\x83\ +\x6e\x64\xde\x62\x21\x0c\xbd\xb1\xb9\xa9\x1f\x51\xf4\x5c\xae\x3d\ +\xb6\x02\xcb\x70\x65\x69\xf3\xc0\x3f\xc8\xb4\x97\xec\xf6\x14\x9a\ +\x50\x7b\x66\xd0\x21\x20\x8f\xd1\x24\x0b\xc0\xa3\x02\xfd\x32\x62\ +\x85\xbb\x7d\x8d\x34\x73\xd0\xc3\xce\xd6\x8e\x8a\x05\x7a\x15\x98\ +\xb8\xce\xf6\x4f\xec\x75\x11\xf4\x47\xf4\xbf\x26\xd4\x1c\xc5\x47\ +\x70\xac\x79\x23\x01\x94\x9f\xa1\xf6\x37\xc6\xd5\xb3\x11\x8e\xcc\ +\xf2\x1e\x90\x9a\xa4\x10\xd2\x6d\xff\xc8\x7f\x46\x58\x87\x42\x28\ +\x12\x40\x19\xdb\xb3\xcc\xcd\x11\xeb\x80\x2e\x51\xbc\x1c\x40\x11\ +\xb3\xc3\x08\xbf\xca\xcf\x11\x9f\xf9\x51\xd6\x61\x28\x14\x8d\x1f\ +\x5b\x39\xc6\x02\x48\x72\xe7\x39\x6d\x79\x03\x22\x12\xe8\x93\xde\ +\x27\x16\x29\x3c\x4b\x08\x32\x43\xea\xe9\xdd\x78\xee\x00\xc4\xe7\ +\x17\xb3\x60\x99\xc1\x23\x06\xb7\x38\x3f\x06\x3c\x07\x56\x46\x68\ +\x7b\x22\x21\x94\x50\xaf\xcd\xb8\x70\xc9\xc0\x98\xbe\x49\x12\x4e\ +\xe7\x05\x6a\x09\xc0\x01\xfb\xe4\x2f\x12\x8b\xa4\x7d\x00\x6d\x43\ +\x6f\x64\xe0\x25\xf0\x21\x23\x8b\x13\x9c\xa0\x61\xf8\x47\x0c\xbf\ +\x13\xc4\x67\x80\x8e\x8b\x10\x0d\x7e\x8a\x43\xad\xcd\x2e\x63\xe8\ +\x00\x00\xf1\x8e\xd0\x53\x15\x42\x7a\xb3\x73\x80\x79\x1b\xcb\x25\ +\x34\xaa\x43\x28\x4d\xee\xeb\xfe\x05\x6c\x6a\xde\xa0\x08\x64\x8e\ +\xc1\xe5\xcb\xa6\x45\xf0\x00\xe6\x26\x31\xd3\x6d\xed\x45\xd2\x88\ +\x55\x9a\x68\x6e\xe3\x91\xc7\x35\x32\x1f\x00\x9a\xe7\x9f\x04\x77\ +\x0e\xec\x28\x12\xd9\x40\xad\xc3\xbc\x8f\xbd\x43\x44\x4b\xc0\x19\ +\xc8\x3b\x44\x91\x16\x9a\x81\x59\x43\xa3\xba\x26\x70\x01\x17\x5b\ +\x5e\xc7\x58\x4e\xcf\x29\x1a\x19\x2e\xe9\x58\x1e\x00\xff\x06\x89\ +\x4d\x73\x92\xd9\x49\xf2\x01\xc9\xff\x24\x84\xee\x78\xfc\x7b\x7a\ +\xaf\x09\x3e\x83\x9d\xf3\x49\x62\x01\x74\x7c\xdb\x32\x7a\x1e\xd1\ +\x0b\x05\x8e\x3c\xbd\x02\xec\x67\xb7\xb1\xa0\xb9\x43\x59\xcf\xe6\ +\x10\xd3\x73\xf7\x4f\x70\xed\x60\x8e\x82\x3c\xa3\x05\x02\x9a\x38\ +\xd9\x8d\xe6\x5c\xd3\x60\x2d\x61\x3c\x09\x87\xc5\xa1\xbb\xfa\x38\ +\xdb\x0e\x0c\x0a\xb6\x32\xd9\xe9\xf8\x08\x84\x57\xd7\x16\xec\xa1\ +\xc1\x8d\x05\xcf\xc8\x14\x56\xe0\x6f\x65\x5f\xfb\x6e\x30\xb6\x0e\ +\x2b\x14\xe6\x24\x93\xc0\xcb\x84\xe4\x3a\x3e\xa3\x38\x8b\x94\xe0\ +\x85\x6d\x0a\x5d\x5f\x89\xb2\xea\x6d\xdc\x15\xd0\xf2\x67\x30\xc9\ +\xdb\xbf\x0e\xf3\x09\x04\x42\x68\xdd\x46\x13\x24\x56\x4e\xb2\x1c\ +\xd0\x18\xf7\x2d\xa3\xd6\x68\x2c\x25\xd8\x46\xed\xa5\x19\x3f\xfb\ +\x6d\x6e\x64\x5f\x01\x38\x83\xc6\x32\x9c\x9c\x8d\xe1\x25\x5e\x03\ +\x9c\x28\xce\x99\x15\x06\x65\x77\x31\x2c\x53\x7c\xbc\x92\x1a\x85\ +\x9c\x59\xb5\x04\x70\x86\x2a\x97\x72\x41\x86\x15\x38\xee\x90\xbb\ +\xf7\x4f\xb7\xfd\x57\xd0\x38\xd3\x73\xfa\x63\x81\xac\x2a\x4e\xbe\ +\xc2\xf4\x18\xa5\x01\xad\xae\x2d\x74\x99\x83\xb3\x2e\xca\x53\x4e\ +\x78\x45\xf9\x80\xc4\x66\xbe\x6d\x13\xd4\x3c\x54\x84\xc9\x31\xc9\ +\xb9\xb7\xa7\xe8\x96\x5b\x85\x4e\x41\xa1\xd3\x38\x70\x3e\xab\x38\ +\x92\xea\x4f\xd3\x6d\x9e\x04\x66\x61\x2e\x4e\xd6\x26\xb0\x02\x53\ +\xd3\x01\x4f\x19\x88\x05\x70\x41\x9a\x34\x70\xde\x74\xc9\xba\x8d\ +\xd7\xed\x2b\x72\x4a\xd8\xee\xed\x15\xb0\x07\xf5\x4b\x55\x5c\xb2\ +\x38\x9e\xaf\x2f\xce\x8f\x5d\x81\x49\x8f\x23\x3c\xf3\xa1\x10\x28\ +\x01\xab\x76\xfa\x0e\xd4\x34\x5f\x54\xc0\x7d\xeb\x1b\xea\x44\x56\ +\x20\x36\x83\xf1\x95\xd3\x27\x68\x39\x1a\xc0\x32\x5a\x27\xd4\x0f\ +\xc6\x5d\x02\xbf\x45\xaf\xc7\x97\x0d\x9d\x97\xa4\xa0\x4e\xd1\xf8\ +\xfc\x3d\x2f\x84\x61\x89\x0f\x21\xad\x35\xa0\x81\xba\xd1\x56\x4d\ +\xcf\x25\xf0\x7b\xe0\x53\x06\x97\xa3\x89\x19\x4c\xca\x6b\x27\xf5\ +\x66\x3b\x85\x12\xc3\xdd\x67\xd9\x42\x0b\x0f\xc2\xb6\x86\xf7\x08\ +\x37\xa2\xf6\xa4\x0e\x6f\xcd\x7f\x1b\x56\x43\x1a\xdc\xa8\x46\x30\ +\x7d\x7e\x05\xf3\x52\x45\xaa\x68\x09\xed\x1c\xc8\xbb\xb6\x4e\x90\ +\xf7\xf3\xd6\x4a\x3e\x64\x8c\x1a\xa1\x43\x90\x20\x23\xeb\x4e\xe0\ +\xa4\xab\xf5\x80\x29\xa2\xf0\x8a\xba\x0f\xee\x11\xea\x25\xbe\x06\ +\xb3\xe3\x82\xcc\xa0\x29\xfb\xef\xd1\xcc\xcf\x0e\x79\xc5\xb8\x81\ +\xa6\xe0\xc3\x0b\x9e\xe4\x6e\x22\x03\x96\x00\xba\x40\x95\x4c\x49\ +\xec\xcc\x0b\xa8\x4c\x7a\xc9\x16\x85\xb4\xfb\xd0\xaa\xaa\xce\xb8\ +\x56\x5d\xee\x98\x20\x65\xc5\xdd\xaa\x90\xaf\xfa\x08\x14\x63\x7b\ +\x11\xba\x1d\x32\x1a\x5f\x2a\xa8\x6e\xcb\xd5\x28\x58\xb1\x40\x09\ +\xdc\x9e\x6e\x79\x79\x16\x28\xa0\xa7\xa8\x46\xee\x01\xff\x0d\x98\ +\x0f\x24\x3f\x77\xe0\x05\x94\x84\xbf\xa1\x0b\x7c\x13\x48\xbc\xbf\ +\x55\x94\xd1\xa7\x30\x27\x51\xbf\x04\x39\xc6\xfb\xd0\x68\x91\xb9\ +\xbe\x93\x8a\xd2\xe3\x76\x40\xee\x1a\xcc\x66\xe0\x25\x69\x2e\xc0\ +\xed\xa2\x75\x36\xc9\xd6\x17\x54\xf1\x54\xc8\x66\x8d\x22\x1c\x4e\ +\x54\x80\xec\xa3\xb5\x3f\xf7\xc6\x08\x97\x0d\x68\xdd\x46\x9d\x9b\ +\x25\xe0\xb9\xee\xb0\x9c\x9d\x9f\x26\x5d\xd5\xe3\x26\xba\xea\x65\ +\x54\x79\x76\xd0\xda\xe6\x25\x65\x1e\xd0\xcb\xd8\x8c\x33\x14\xed\ +\x00\x77\x9a\x0d\x57\xdd\x1e\x5a\xc3\xbf\x81\x46\x66\x9f\xa3\x42\ +\x78\x00\xe7\x27\x50\x3d\x52\x22\x0b\xcd\x5b\x5f\xe7\x68\x24\x15\ +\x9b\x49\x1b\x80\x83\x0b\xbf\xbb\xaa\xc9\x0b\x14\x21\x1c\x7b\x66\ +\xbc\xa9\x33\x1d\xcb\x65\xc5\x2f\x4b\x1e\x6f\x12\x23\x7c\x00\x3c\ +\x04\x0e\xc0\xbd\x0c\xc6\x97\xe3\x7b\x46\xeb\x08\xc4\xcc\x74\x3d\ +\x21\x0f\xd1\x82\x45\xd0\x2b\xef\x65\xdf\xbe\x1f\xb4\x1b\x20\x62\ +\xf7\x8b\x83\xea\xa4\x67\xb0\x53\xe0\xc5\xad\x8f\xc0\x7d\x05\x4c\ +\xc1\xd1\xf7\xd9\xeb\x39\x71\x9e\xb6\xf8\xcc\x8f\x93\x42\x93\x3b\ +\x03\xe7\x27\x53\x2e\x5f\xcf\x5a\x07\xf0\x66\xe8\x7d\xec\x44\x49\ +\x32\xe6\xff\x50\x2e\x0f\xba\x00\xf2\xf3\xbc\xf9\x95\xa6\x5a\x8a\ +\x5c\xb9\xfc\x1d\xcc\xb2\x5e\x1b\xf9\xc7\xd8\x2f\x4c\xac\x92\x7b\ +\x61\x42\x1c\xfa\x82\x85\xf1\x02\x43\x3a\x66\x7b\xcc\x89\x43\x9c\ +\x05\xcf\x88\x43\xdf\x18\xf9\xa5\xd1\x57\xce\xfa\x2b\xa9\x10\xaa\ +\x8c\xff\xc2\x44\x8a\xe8\x4f\x05\x4e\xc8\x46\x5e\x08\x00\xf2\x1e\ +\xfa\xca\x4a\xee\xa5\x04\x5e\xeb\x95\x99\xb4\xad\xe4\x9d\x9f\xb7\ +\x40\xde\x31\x9c\x9f\xb2\xa5\xe5\x3d\xf3\x7f\xc8\xe3\x2b\x9e\x3c\ +\x91\x5a\x59\xa5\x16\x7b\x80\xe0\x77\x82\x71\x7d\x2d\x1b\x7e\x6b\ +\xde\xd3\x4f\x2b\x74\x9e\x2a\x8c\x7e\x69\x6a\xca\x8f\x09\x04\x2f\ +\x2b\x0c\x5e\xbe\x2a\x7a\x39\x6a\x1e\x33\x66\x91\x2d\xcf\x43\x29\ +\xbf\x9b\x15\x62\x44\x86\x93\x23\x9b\xa8\xb6\xf5\x35\xba\xb4\xfc\ +\xef\x1a\x6a\xe6\x1c\x7a\x01\x72\xc1\xe0\xb5\xb9\x19\x40\xa0\x37\ +\x0d\xe5\xc4\x29\x4a\x4a\x64\x7b\xc1\xff\xe4\xf6\x26\x79\x6d\x2e\ +\x28\x97\x4d\xe9\xeb\xfa\x71\x0e\x35\x61\xa7\xfe\xf7\x24\xaa\xc4\ +\x7d\x01\x06\x1d\x54\xa1\xce\x06\x78\xf6\x06\x4e\x93\xed\xc0\x8d\ +\xb8\xa2\x8e\x41\x26\x30\x4a\xcd\x3c\x9e\x3a\x79\x2d\x1b\xbf\x38\ +\x59\x42\xaf\xca\x92\x23\x54\x65\xe0\x5f\xe0\x99\x38\x24\x6b\xf3\ +\xac\x17\x27\x85\x41\xe2\x33\x06\xa3\xb4\x36\x7d\xac\x88\xc7\x37\ +\xf7\xd5\x59\xab\xe1\x0d\x80\x0c\xcf\x6f\x1a\xf3\x09\xa8\x10\xfe\ +\x07\xb4\x0a\xfd\x7e\xcf\x22\x5b\xc2\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x01\x98\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x4a\x49\x44\x41\x54\x58\x85\xe5\ +\xd6\x3f\x4a\xc4\x40\x14\xc7\xf1\xef\x4b\x16\xbd\x81\x5b\x78\x02\ +\xd7\xca\x2a\x60\xb7\xf1\x00\x0b\xf1\x40\x7a\x22\x21\xd8\x08\xc2\ +\x6e\x27\xa4\x5e\xff\x9c\xc0\x42\x2b\x0f\xb0\xe1\x59\x84\x28\xc4\ +\xc4\x99\x97\x9d\x89\x85\x53\xce\x3c\xf8\xfc\x98\x79\x3c\x06\xfe\ +\xfb\x92\x29\xb1\xac\xd4\x39\x3b\x2d\x11\x5e\xab\x22\xb9\x04\x48\ +\x26\xc5\x6b\xdd\x20\x64\x28\xc7\xed\xfe\x24\x01\xbe\x70\x38\x01\ +\x5e\x98\xc9\xaa\x3d\x8b\xfe\x04\x3f\xf0\x54\x96\xd5\x4a\xde\x26\ +\x09\xe0\xc2\xa3\x06\xf0\xc1\xa3\x05\xf0\xc5\xa3\x04\xb0\xe0\xc1\ +\x03\x58\xf1\xa0\x01\xc6\xe0\xc1\x02\xf8\xe2\xe7\x37\x7a\xb4\x13\ +\xbd\x13\xe5\xa3\x2a\x92\x1c\x02\x0c\x22\x0b\x5e\xa3\x6b\x51\xce\ +\x80\x83\x76\x7f\x36\x25\x0e\x9c\x0a\x3c\x26\x48\xd1\x9e\x8d\x7e\ +\x82\x3d\xf0\x8b\x87\x42\xde\xf7\x0a\x10\x0a\x1f\x15\xc0\x88\x6f\ +\x80\x05\xf0\x94\x22\x79\x17\x37\x07\x08\x8d\x9b\x02\xc4\xc0\x01\ +\xd2\x90\x78\x56\xea\x5c\xd5\x1f\x07\x8f\x1b\xb0\xe0\xd4\xba\xb6\ +\xe0\xce\x00\x23\xf1\xe7\x14\x59\xf6\xe1\xa6\x49\x18\x03\xf7\x9e\ +\x84\x91\xf0\x0d\xb0\x70\x4e\x42\x23\xde\xd6\x0d\xe2\xae\xde\x90\ +\x9e\x62\x33\x4e\x2a\xf9\xd8\xc6\x94\x4e\x71\x68\xdc\x79\x43\x4d\ +\x13\x5e\x69\x42\xad\xf7\x2e\x1c\x55\x91\x5a\x6f\x5d\x78\xb7\x6e\ +\x08\xff\x0e\xd0\xac\x43\x60\xfb\xeb\x4f\xe6\x1a\xd1\xa6\x83\xb7\ +\x83\x78\x4f\x9d\xcf\x3c\x68\x6e\x41\xd5\x3d\x9a\x55\x25\x68\xdd\ +\x5f\xaf\x4f\xda\x1b\xa3\x91\x9e\x7b\xef\x4a\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xa6\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x58\x49\x44\x41\x54\x58\x85\x63\ +\x60\xa0\x00\xdc\x7f\xf8\xb8\xe1\xfe\xc3\xc7\x0d\x94\x98\xc1\x44\ +\x89\x66\x6a\x80\x51\x07\x8c\x3a\x60\xd4\x01\xa3\x0e\x18\x75\xc0\ +\xa8\x03\x06\xdc\x01\x2c\x14\x9b\xf0\x9f\xc1\x81\x92\x2a\x79\x18\ +\x84\x00\x23\xc3\x01\x45\x79\xd9\x06\x72\xb5\x0f\x78\x08\x8c\x3a\ +\x60\xd4\x01\xa3\x0e\x18\x75\xc0\xa8\x03\x46\x1d\x30\xe0\x0e\x00\ +\x00\xe6\xf7\x0c\x89\x70\x77\x76\x17\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x01\x50\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x02\x49\x44\x41\x54\x78\x9c\xed\ +\xd6\x2d\x4e\x03\x51\x14\xc5\xf1\x73\x29\xe1\x4b\xa0\xc0\xb3\x01\ +\x92\x0a\x7c\xc7\x15\x3c\x86\xd4\x23\x31\x2c\xa0\x99\x05\x74\x07\ +\x4d\x05\x49\x25\xa6\x09\x81\x86\xb0\x08\x76\x80\x22\x21\x75\x08\ +\x98\x66\xca\xbb\x58\xf2\x1e\x04\x35\x8f\x84\xf9\xff\xe4\xb9\x23\ +\xce\x1c\x33\x23\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\xad\x60\ +\xbf\xdd\x8b\x62\xd8\xc9\xd2\xa4\x21\xbd\x9e\x42\x59\x96\xe1\xa7\ +\xfb\xb7\x03\x14\x67\xe7\x7b\x1b\xcb\x30\x72\xd3\xa9\xa4\x9d\xc6\ +\xda\xe5\x51\x99\xfc\xc6\x6b\xbf\xb8\x9f\x4d\x9e\xe3\x63\x32\xc0\ +\xc9\x60\xb0\xbb\xaa\xb6\x1e\x25\x3b\xc8\x50\x2e\xa7\x45\xa8\x75\ +\xf8\x30\x1b\xbf\x7c\x0d\xd7\xe2\xa7\x3e\x96\xdb\xe5\x3f\x7c\x79\ +\x49\xda\xb7\x75\x8d\xe2\x30\x19\xc0\x5d\xfd\x3c\x7d\xf2\x33\xd3\ +\x71\x9c\x25\x03\xb4\x4d\x32\x80\x99\xe6\x7f\x51\x24\x07\x77\xdd\ +\xc5\x59\x32\x40\x67\xf3\x7d\x28\xf9\x53\x96\x46\x79\x2d\x7c\xa5\ +\xcb\x38\x4c\x06\xb8\x9d\x4e\x5f\x43\xa8\x8f\xcc\x75\x25\xe9\x2d\ +\x4b\xb5\x66\x55\x26\xbf\x56\x1d\xba\xf1\x17\x40\xe2\x47\x08\x00\ +\x00\x00\x00\x00\x00\x00\x00\x00\x68\x8b\x4f\xc6\xe5\x42\x89\xb1\ +\xed\x97\x86\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\x75\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x27\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4f\x68\x5c\x55\x14\xc6\x7f\xe7\xcd\xb4\x5a\x8c\x08\xb6\xba\ +\x30\xa8\x2b\x51\xd4\x8d\x50\x84\x22\x48\x6c\x27\x89\x41\x0c\x76\ +\xc6\xd1\x95\xd8\xfc\x99\x50\x17\xa2\x05\x45\xf0\x0f\xe3\xd0\x8a\ +\x15\x04\x17\x22\xb6\x49\xa6\xc6\x45\x8a\x9a\x26\x0d\xa1\x1a\x3b\ +\x49\x64\x0a\x8a\x20\x28\x08\xc5\x85\x20\xe2\xa2\x41\x04\xad\x14\ +\x6d\x0b\x93\xb9\xc7\x45\x1c\x79\xf3\x66\xc0\x14\xdf\xbd\xef\x62\ +\xe6\x5b\x7e\x1f\xdc\x73\xee\x77\xce\xfd\xf7\x98\x81\x0e\x3a\xe8\ +\x60\x33\x43\x92\x4e\x60\xa3\xc8\x64\x47\x8b\x22\xf2\x32\x18\x51\ +\xd5\x43\xcb\x73\xc7\x5e\x8d\x63\xdc\x20\x8e\x41\x6c\xa3\x3f\x3b\ +\xfc\x00\x42\x11\x34\x0d\x92\x12\x09\x5e\x89\x6b\xec\x74\x5c\x03\ +\xd9\x42\x6f\x6e\x78\xa7\x21\x58\x90\xe6\x6e\x8d\xad\x70\x5e\x77\ +\x40\x5f\x6e\xec\x0e\x34\x58\x04\xba\x22\x92\x89\x2b\x86\xb7\x06\ +\x64\xf2\x63\xb7\x28\xa6\x82\xb0\xa3\x8d\xac\x71\xc5\xf1\xd2\x80\ +\x81\xfc\xd0\x0d\x18\x53\x01\x6e\xb6\x1d\xcb\x3b\x03\x06\x07\x87\ +\xaf\x5d\x33\xa9\x4f\x04\x6e\x77\x11\xcf\x2b\x03\x7a\xf6\xed\xbb\ +\xfa\xd2\xd6\x60\x1e\xd8\x19\x91\x62\x6b\xf9\x28\xbc\x31\xa0\xa7\ +\xa7\x98\xde\xf2\x47\xfa\x38\xca\xee\x88\xa4\xc4\xb8\xe9\x45\xe1\ +\x8b\x01\x92\xde\xbe\x7a\x14\x65\x6f\x13\xab\x6a\x75\xf2\xe0\x89\ +\x01\x99\xdc\xe8\x1b\x82\x0e\x47\x68\x45\xc4\xea\xe4\xc1\x03\x03\ +\x7a\x1f\x2d\xbc\x20\xf0\x7c\x1b\xc9\xfa\xe4\x21\x61\x03\x32\xb9\ +\x42\x01\xd5\xc3\x6d\xa4\xba\xab\x1c\x12\x33\x20\x93\x2b\xe4\x04\ +\x3d\xd2\x44\xae\xef\xf5\x4e\x2a\xdf\x40\x22\x06\xec\xc9\x16\x32\ +\x82\x1e\x6f\x89\x1f\x60\xb0\x78\xe4\xb5\x83\x73\x03\xfa\xf3\x23\ +\xf7\x06\xa2\xf3\xc0\xd6\x88\x64\x50\xb7\x93\x07\xc7\x06\xec\xc9\ +\x0f\xdd\x69\x8c\x2c\x02\xd7\x84\x79\xc1\x7d\xe5\x1b\x70\xf6\x1c\ +\xde\x9d\x1d\xb9\x35\x30\x52\x01\xae\x8f\x48\x46\x13\x9a\x3c\x38\ +\xea\x80\xbe\xbd\xfb\x6f\x4c\x09\x4b\x40\x77\x98\x17\x24\xb1\xca\ +\x37\x60\xbd\x03\x32\xf9\xb1\xeb\xd4\xac\x7d\x0a\x72\x5b\xb3\xa2\ +\x9a\x64\xe5\x1b\xb0\xda\x01\xbb\xf2\x07\xb6\x89\x31\x0b\xc0\x3d\ +\x11\x49\xc1\xfe\x2d\x6f\x23\xb0\x66\x40\x4f\x4f\x31\xdd\xa5\x17\ +\x3e\x00\xee\x8f\x48\xd6\xef\xf7\x57\x02\x2b\x06\x14\x8b\xc5\x60\ +\xcb\xf6\x73\x93\xa8\x0c\x46\x24\x6f\x2a\xdf\x80\x0d\x03\xe4\x8b\ +\xb3\xab\x6f\x02\x4f\x36\xb1\xda\xa8\x7c\xe2\xcb\xbe\x09\xb1\x1b\ +\x90\xc9\x8d\xbe\x28\xe8\x81\x16\x41\xfc\x69\xfb\x30\x62\x35\xa0\ +\x37\x57\xd8\x2f\x70\xa8\x55\x11\x67\x8f\x9b\x2b\x45\x6c\x06\xf4\ +\x66\x47\x0e\x83\xbe\x1b\xe5\xc5\xc3\xb6\x0f\x23\xbe\x0e\x10\x89\ +\x7e\xd0\x00\x24\xd1\x5b\xde\x46\x10\x9b\x01\xd2\xf6\x0d\xef\xf5\ +\xdc\x81\x18\x0d\x30\xc8\x33\xb4\xce\x38\xf1\x2f\x4e\xff\x86\xd8\ +\x12\x5c\x9e\x9d\xf8\x08\x78\xba\x55\xd1\x54\x5c\x31\x6c\x20\xd6\ +\x0a\x2d\xcd\x4e\xbe\x03\x5a\x6c\x66\x05\xc0\x5b\x13\x62\x6f\xd1\ +\xa5\xd9\xf2\x41\x11\xde\x8e\xf2\x8a\x7a\xb9\x1c\x6c\x24\xa5\xbb\ +\xee\xea\x7e\x56\x95\xe9\x30\x29\x88\x58\x8a\xf7\x9f\x60\x25\xa1\ +\x52\xa9\x64\xce\xef\x08\x86\x10\xf9\x38\x22\x09\x9e\x75\x82\xb5\ +\x64\xbe\x1e\x1f\xaf\x5d\x75\x59\x1e\x43\xf5\xf3\x66\x45\x44\x3d\ +\xea\x04\xab\x89\x9c\x3a\x35\x7e\xb1\x66\xea\x0f\x83\x7c\x1b\xe6\ +\x05\xc4\x97\x3d\xc1\x7a\x12\xd5\xf9\xa9\xdf\x6b\x41\xed\x41\x81\ +\x1f\xc2\xbc\x20\x22\x1e\xfc\x48\xcb\x49\x15\xaa\x33\x53\x3f\x13\ +\xd0\x8b\xb0\x1a\xe6\x15\x02\x91\x64\x4d\x70\xd6\x86\x95\x99\xc9\ +\x1f\xa5\xae\xfd\x28\xe7\xc3\xbc\x2a\x01\xeb\x27\x44\x22\x70\xba\ +\x0e\x2b\x27\xcb\x67\x4d\xca\x3c\x04\x5c\x6c\x56\x34\x20\xa1\xe5\ +\xe0\x7c\x23\x5a\x99\x39\xf6\xa5\x22\x59\xa0\xd6\x26\x17\xe7\x26\ +\x24\xb2\x13\x2f\xcf\x4e\x9c\x16\xe5\x09\xa2\x8f\x27\x25\x70\xbd\ +\x31\x26\x76\x14\x55\xe6\x26\x3f\x44\xf4\xa9\x26\x52\xd6\x37\x46\ +\x97\x1e\x24\x7a\x16\x2f\x9d\x28\x1f\x45\x78\xa9\x55\x71\xf7\x82\ +\x4c\xfc\x32\xb2\x74\x62\xf2\x75\x45\xde\x6a\x23\x39\xc9\x2d\x71\ +\x03\x00\xbd\xef\xee\x9b\x9e\x03\xde\x8f\xf0\x4e\xae\xcc\x3e\x18\ +\x40\xa9\x54\x32\xb5\x5f\xbb\x47\x11\x5d\x08\xf3\x7f\x6f\x88\x56\ +\x73\xf4\xc2\x00\x80\x6a\xb5\xb4\x56\xeb\xaa\x3f\x8e\x72\x26\x22\ +\x59\x35\xc1\x1b\x03\x00\xaa\x53\x53\x97\xd3\xdb\x2e\x0d\x2a\x7c\ +\x13\x91\xac\x1d\x0b\x5e\x19\x00\xb0\x38\x3d\x7d\x21\x30\xe9\x01\ +\xe0\x7b\x17\xf1\xbc\x33\x00\xa0\x72\xf2\xc8\x2f\x75\xd5\x3e\xe0\ +\x9c\xed\x58\x5e\x1a\x00\xf0\xd9\x5c\xf9\x27\x13\xd4\xfb\x80\xdf\ +\xda\xc8\xb1\x2d\x09\x6f\x0d\x00\x58\x99\x79\xef\xbb\x20\xd0\x01\ +\xe0\xcf\x88\xb4\x39\xfe\x32\x03\x70\x7a\xa6\xfc\x95\x51\x79\x04\ +\xf4\x9f\x77\x83\x6c\x86\xbf\xcc\x84\xb1\x32\x37\xb1\x0c\x1c\x04\ +\xad\x23\xd4\x45\x78\x2d\xe9\x9c\x3a\xe8\xa0\x83\xff\x07\xfe\x02\ +\xec\x35\x2d\x8c\x9b\x14\xe3\x6d\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x00\x8b\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3d\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\x01\x09\x00\x20\x10\x04\xc1\xd7\x6e\x26\xb0\x82\xfd\x2b\xf8\ +\x29\xe4\x40\x66\x12\x2c\x5b\x05\x00\x00\x00\x00\x00\x00\xc0\xff\ +\xc6\xda\xe7\xa6\x23\x92\x66\x3a\x20\xcd\x80\x74\x00\x00\x00\x00\ +\x00\x00\x00\x00\xbc\xd7\xba\x61\x02\x03\x59\xaf\x8c\x6f\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x85\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x37\x49\x44\x41\x54\x58\x85\xed\ +\xce\xb1\x11\x00\x30\x08\x03\x31\x2e\x4b\xb1\x35\x23\x42\x86\x80\ +\x52\xdf\xdb\xa7\x88\x45\x59\x3d\x59\x3d\x9b\x8f\xb7\x19\x5f\x04\ +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0\x01\ +\x8b\x69\x06\x03\x87\x7c\xe1\xcd\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x04\x32\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\xe4\x49\x44\x41\x54\x78\x9c\xed\ +\x99\xcb\x6f\x5b\x55\x10\xc6\xbf\x39\xb6\x4b\x02\xa1\x42\x24\x6c\ +\x10\xa9\xa0\x41\x6a\xd3\x76\xe3\xb4\xac\x90\x90\x4b\xec\x8b\xda\ +\x45\x5a\x3f\xb2\x80\x2c\xc8\xc3\x0e\xfc\x03\x88\x55\x1b\xd8\x54\ +\x42\xac\x10\x42\x42\xa1\x24\x15\x2c\xb2\x30\x8f\xb6\x0b\x8c\xac\ +\xb6\x89\x68\x61\x01\x28\xde\xd5\x54\x2a\x46\xa2\xcd\x0a\x58\x54\ +\x55\xd5\xa8\xb1\xcf\xb0\x48\x08\xd7\xf7\x1e\x3b\x7e\xdc\x6b\x17\ +\x31\x3f\xc9\x9b\x99\xf3\x98\xf9\x3c\x67\xee\xb9\x36\x20\x08\x82\ +\x20\x08\x82\x20\x08\x82\x20\x08\x82\x20\xfc\xbf\xa0\x6e\x6d\x1c\ +\x4b\x64\xe2\x20\xfe\x08\x04\xc5\xe0\x4f\x2e\x7d\xf1\xe9\xa9\x6e\ +\xc4\x11\xe8\xc6\xa6\xd1\x64\x26\x43\xc4\x9f\x01\xd8\x0d\xa0\x8f\ +\x40\x2f\x0d\x1d\x0c\xaf\x95\xae\x17\x56\x3b\x1d\x4b\xc7\x05\x88\ +\xa5\x32\x6f\x13\xf8\x03\xb8\xaa\x8f\xc6\x86\x86\xc3\xf7\x4b\xc5\ +\xc2\xf7\x9d\x8c\xa7\x93\x02\x90\x95\xcc\xbc\x0f\xf0\xe9\xda\x23\ +\x28\xb6\xf7\xc0\xc8\x63\xa5\xe2\xea\xa5\x8e\x05\xd5\x89\x4d\x22\ +\x91\xb9\x60\xe8\xc9\xb5\x79\x10\xa6\x1a\x19\xcf\xa0\x85\xf2\x5f\ +\x4f\xbf\xb1\xb2\xf2\x6e\xd9\xef\xd8\x7c\x17\x20\x32\x39\xd9\x13\ +\xbc\x1b\x5a\x22\xf0\x49\x83\x5b\x13\x01\xcc\x50\x86\xc8\xbe\xde\ +\xe8\x2b\xbf\xb6\x72\xee\xdc\xba\x9f\xf1\xf9\x2a\xc0\xb1\x89\x89\ +\xdd\x1b\xeb\x8f\x9e\x27\xf0\x51\xbb\x9d\x37\x37\xae\x54\x8f\xe6\ +\x80\xbb\x2d\xe0\x4a\xef\x03\x7d\xf2\xe2\xc5\x85\xbb\x7e\xc5\xe8\ +\x9b\x00\xc7\xc6\xa7\x9e\x2a\x57\x02\x39\x10\x0e\x1b\xdc\x15\x83\ +\x0d\x30\xf7\xa4\x9f\x83\xaa\x72\x3c\x97\x5d\xfc\xc3\xc3\xf0\xb6\ +\xf1\x45\x80\xe8\xf8\xec\x1e\x68\x9d\x27\x60\x9f\xdd\xce\x60\x26\ +\x90\xae\x37\x97\xc1\x8a\x40\x54\x6d\xc3\x0d\x55\xae\xc4\xf2\x17\ +\x16\x6f\x79\x1d\xab\xe7\x02\x44\xe3\xe9\x61\x52\xc8\x03\x78\xc6\ +\xe1\x62\x00\x75\x93\xff\x77\x24\x2b\x10\x39\x63\xbb\x45\x50\x56\ +\xfe\xcb\xf9\x5f\x3c\x08\x73\x1b\x77\xf3\x69\x83\xd1\x44\xe6\x05\ +\x52\xb8\x0a\x67\xf2\xdc\x44\xf2\x00\x40\xa4\x01\x66\x87\x75\x90\ +\xa1\xaf\xc5\x92\xd3\x47\xda\x0e\xd4\x86\x67\x02\xc4\x52\x33\xa3\ +\x8a\xf8\x0a\x80\xfe\x6a\x0f\x33\xa8\x89\xe4\xb7\x21\xcd\x9b\x55\ +\x63\xa7\x1f\x50\xcb\x56\x3c\xfd\x72\xab\x71\x3a\xf1\x44\x80\x68\ +\x2a\x9d\x00\xd3\x37\x00\xfa\xec\x76\x06\x33\x76\x38\xf3\xf5\x20\ +\x40\x33\xbb\x44\xe8\x63\x85\x5c\x2c\x91\x89\xb7\xba\xae\x9d\xb6\ +\x6f\x82\x56\x22\x3d\x03\xe0\x73\x00\x41\xbb\x9d\x00\x0d\x90\x33\ +\xf8\xa6\x21\x02\x6f\xf5\x44\x7b\x4f\x08\x80\x30\xfe\xfc\x81\xf0\ +\xed\x5f\x8b\x85\x42\x3b\xeb\xb7\x25\x80\x95\x4c\xbf\xc5\x84\x0f\ +\x1d\xc1\x6d\x7e\x73\xee\xf2\x6d\x8b\xad\x96\x68\xdf\x87\x00\x3a\ +\xb1\xf7\x60\xf8\x5e\xe9\x7a\xe1\x87\x56\xd7\x6d\x55\x00\x8a\xa5\ +\x32\xef\x01\x78\xc7\xed\x81\x86\xc7\xc9\xdb\x17\x87\x4b\x6c\xb2\ +\x86\x86\xc3\xbd\xa5\x62\xe1\x72\xcb\x2b\x36\x43\x24\x32\x17\x0c\ +\xf5\xaf\x7d\x0c\x60\xc6\xe0\xf6\x31\xf9\x6d\x08\xa6\xde\xc5\x38\ +\xfb\x44\xe0\xce\x9b\xd9\x6c\xb6\xd6\x25\xcb\x48\x53\x15\x10\x99\ +\x9c\xec\x09\x05\xee\x2d\x01\x98\x70\x6c\xee\xf3\x37\x6f\x80\x41\ +\x8e\x03\x31\xb2\xce\x3d\x87\xf6\x3d\xfb\xe2\x85\x9b\x37\x7f\x6c\ +\x58\x84\x86\x2b\x60\x6c\x6c\xfa\xf1\xfb\xbb\xd4\x79\x30\x5c\x8f\ +\x20\x3f\xce\x7c\x03\x98\x2b\x01\xb8\xdc\xbb\xa1\xe3\x8d\xbe\x3f\ +\x34\x24\x40\xe4\xd5\xd9\x81\xd0\x03\x9d\x03\x60\xb8\x84\x50\xa5\ +\xf3\xb9\x57\x61\xaa\xe2\x9f\x36\x76\xa9\xe3\x2b\x4b\xf3\x7f\xee\ +\x34\x79\x47\x01\xac\x13\x53\x83\x1c\x0c\xe4\x01\xec\xaf\x72\x30\ +\x5a\xbc\xe0\xf8\x82\x82\x3b\x97\x62\x90\x61\xe5\xbe\x3a\x7b\xbb\ +\xde\xc4\xba\x02\x58\xc9\xd9\xfd\x0c\x9d\x07\x30\x68\xb7\x33\xc0\ +\xd4\xcc\xd5\xb6\x13\x98\xdf\x1f\x7e\x0f\x28\x6d\x7d\x9b\x5d\xb8\ +\x51\x6b\x5a\xcd\x9b\x60\x2c\x39\x7d\x84\x59\x5f\x85\x33\x79\xc6\ +\x8e\x6f\x74\x5d\x81\xc8\xd4\x84\xf7\x54\x2a\xea\x9a\x35\x9e\x36\ +\xbd\x92\x03\xa8\x21\xc0\x2b\x89\xe9\xa3\x80\x5a\x06\x61\xc0\xe1\ +\x62\x22\xe8\x2e\x9f\xf9\x7a\xb8\x45\x20\x0c\x68\x8d\xe5\x68\x2a\ +\x1d\x31\x4d\x70\x35\x90\xd1\x44\xfa\x14\x13\x2d\x12\xf0\x88\x61\ +\xfc\x3f\x9d\xf7\x61\xfe\xb8\x8e\xf5\x56\x2e\xaf\x3f\x37\x3c\xa2\ +\x7f\x2b\xae\x7e\x67\xf7\xb9\x2a\x40\x11\xe6\xa8\x8b\x7f\x98\xf8\ +\x05\x01\xa4\x08\x73\x4e\xbb\xa7\xbf\x07\xfc\x17\x31\x55\xc0\x19\ +\x7a\x78\x1e\x6f\x9e\x41\x04\xad\x08\x67\xba\x1d\x87\x20\x08\x82\ +\x20\x08\x82\x20\x08\x82\x20\x08\x82\xd0\x6d\xfe\x06\xf7\x21\x1d\ +\x03\xf2\x02\xba\x61\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ +\x82\ +\x00\x00\x03\xe3\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x95\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x3d\x48\x5b\x51\x14\xc7\xff\xe7\xe5\x49\x07\xb1\x2a\x16\x22\ +\x58\x74\xae\x43\x15\x92\x22\xdd\x84\x56\x1d\x14\x37\xeb\x50\x41\ +\x07\x89\x14\x5a\x3f\xa6\x52\x87\x06\x85\x62\xe9\xe2\x47\x1d\xaa\ +\x38\x28\xb8\xa8\x9b\x28\x54\xdb\xa1\x43\xa1\x88\x06\xd4\xc1\xce\ +\x8a\xb6\xa6\x90\xfa\x41\x1d\x6c\x93\x77\x3a\xa8\xe5\xe5\xe5\x45\ +\x93\xdc\x97\x5c\xad\xf7\xb7\xdd\xf3\x4e\x4e\xfe\xf7\xff\xde\xbb\ +\xf7\x92\xdc\x0b\x28\x14\x8a\xeb\x0c\x25\x92\x54\xe9\xf7\xeb\x47\ +\xbb\x05\xf5\x06\xd0\x48\x20\x2f\xc0\x45\x00\x6e\xa4\x59\x5b\xb2\ +\x1c\x03\xb4\xc3\xe0\x15\x0d\x98\xca\x2e\x0c\xcd\x7e\xea\xe9\x09\ +\x5f\xf4\xa1\x0b\x0d\xf0\xb6\x0d\x57\x81\x79\x10\xc4\x77\x9c\xd1\ +\x99\x19\x18\xd8\x20\x68\x9d\x2b\x23\x4f\x3f\x9c\x97\xa7\x9d\x53\ +\x82\xbc\xbe\xa1\x6e\xc0\x58\xbc\x6a\x9d\x07\x00\x02\x4a\x01\x63\ +\xf1\x5e\xdb\xe0\x0b\x80\xe3\xde\x68\x57\xbc\x0b\x5e\x5f\x41\x37\ +\x08\xaf\xd2\x23\x2f\x93\xd0\x83\x22\xef\xd2\xf1\xb7\xc0\xfb\xcf\ +\xb6\x57\xed\x82\xde\xb6\xe1\x2a\xc0\x58\xb4\x84\xf7\x40\x78\xa9\ +\x85\x69\xbe\xe4\xc0\xbd\x35\x33\xf3\x28\xe2\xb8\x56\x01\x1a\x1a\ +\xa6\x5d\x9b\xb9\xc1\x62\x43\xe7\x5a\x30\x7a\x01\xe4\x47\x67\x68\ +\xd5\x76\xaf\x43\x8c\x01\x95\x7e\xbf\xfe\xeb\xfb\xad\xf5\xa8\xc7\ +\x9e\xf0\xd1\x15\x36\x9a\x96\xc6\x3a\x83\xce\x4b\x77\x9e\x8a\xd6\ +\x01\x77\x44\xd7\x26\xc1\x78\x78\x16\x63\x60\x23\xa7\x30\x54\x66\ +\x1d\x18\x63\xc6\x80\xa3\xdd\x82\x7a\xcb\x3b\xff\xf3\x37\xb2\x1e\ +\x5f\x95\xce\x03\xc0\xd2\x58\x67\xd0\x15\x36\x9a\x00\xec\x9d\xc5\ +\x08\x28\x3d\xda\x2d\xa8\xb7\xe6\xc6\x18\x60\x00\x8d\x51\x01\x82\ +\x7f\xfd\xdd\x93\x1f\xe9\x10\x9a\x4e\x96\xc6\x3a\x83\x0c\xf6\x9b\ +\x63\x31\x7d\x83\x8d\x01\x27\xf3\xbc\x29\x21\x4c\xf3\xce\xcb\xcb\ +\x0c\xae\x88\x36\x67\x6e\x13\xe0\xb1\xe6\xd8\x4c\x83\x5c\x64\x6e\ +\x95\x1c\xb8\xb7\x9c\x16\x96\x29\x6c\xb4\xdf\xb6\xe6\xd8\xad\x03\ +\xa2\x56\x78\x97\x6d\xb4\x4f\x06\x1b\xed\x31\xab\xd7\x73\x16\x42\ +\xd7\x03\x65\x80\x6c\x01\xb2\x51\x06\xc8\x16\x20\x1b\x65\x80\x6c\ +\x01\xb2\x51\x06\xc8\x16\x20\x1b\x65\x80\x6c\x01\xb2\x51\x06\xc8\ +\x16\x20\x1b\xdd\x89\x22\x1e\xdf\x50\x35\x08\x6f\x08\xb8\x8b\x04\ +\xff\x6b\x10\x80\x01\x5a\x63\xe6\xe7\x81\xd1\x76\xeb\xef\x96\x49\ +\x23\xfc\x04\x78\x7c\x83\xcd\x44\x58\x20\xa0\x0c\xe9\xef\x3c\x4e\ +\xbe\x83\xcb\x89\xb0\xe0\xf1\x0d\x36\x8b\x16\x13\x32\xa0\xbc\xa5\ +\x3f\x8f\x88\xde\x8a\x8a\x48\x15\x22\x1a\x2a\x6f\xe9\xcf\x13\xa9\ +\x21\x64\x80\x9e\xa5\xdf\x07\x90\x23\x52\x43\x90\x9b\xa7\x1a\x52\ +\xe6\xda\x0f\x82\x42\x06\x84\xff\x84\xbf\x00\x38\x74\x48\x4b\x2a\ +\x1c\x9e\x6a\x48\x19\x21\x03\x56\xc7\xbb\xf6\x99\xb9\x5d\xa4\x86\ +\x08\xcc\xdc\xbe\x3a\xde\xb5\x2f\x52\x43\xf8\x15\x08\x8c\x76\x4c\ +\x30\xa3\x06\xa0\x55\x00\x2c\x5a\x2f\x01\x98\x81\x35\x66\xd4\x04\ +\x46\x3b\x26\x44\x8b\x39\xb2\x0e\x38\x9d\x8f\x85\xe7\x64\x19\xa8\ +\x41\x50\xb6\x00\xd9\x28\x03\x64\x0b\x90\x8d\x32\x40\xb6\x00\xd9\ +\x28\x03\x64\x0b\x90\x8d\x32\x40\xb6\x00\xd9\x28\x03\x64\x0b\x90\ +\x8d\x32\xc0\x26\x76\x6c\x6e\x34\x34\x4c\xc7\xdd\x4e\x7b\xd9\xb1\ +\xd1\x7e\x6c\xcd\xb1\x31\x80\x76\xcc\xad\xcd\xdc\x60\xb1\xa3\xaa\ +\x32\x88\x8d\xf6\x6d\x6b\x4e\x8c\x01\x0c\x5e\x31\xb7\x0d\x9d\x6b\ +\x1d\xd6\x95\x31\x22\x2e\xa3\xce\xdc\x66\x20\x60\xcd\x89\x31\x40\ +\x03\xa6\xa2\x02\x8c\xde\x8a\xd6\x01\xb7\xe3\xea\xd2\x4c\x45\xeb\ +\x80\x9b\x40\x3d\xe6\x58\x4c\xdf\x60\x63\x40\x76\x61\x68\x16\x4c\ +\x5f\x4d\xa1\xfc\x88\xae\x4d\x5e\x25\x13\xfe\x6d\x96\x36\xed\x18\ +\x67\x60\x23\xbb\x30\x34\x6b\xcd\x4d\x6a\xbb\x3c\x83\xfd\xae\x88\ +\x36\x77\x99\xb7\xcb\x47\x5c\x46\xdd\xe9\x9d\x4f\x6d\xbb\xfc\x19\ +\x5e\xdf\xd0\x7f\x72\x60\x02\x20\x70\xf7\xf2\x48\x47\x9f\xdd\xb5\ +\xb8\xeb\x80\x95\xd1\x67\x7d\x04\xee\x4e\x9f\xac\x8c\xc0\xcc\xf4\ +\x62\x79\xa4\xfd\x75\xbc\x84\x84\x0e\x4d\x31\x8c\x81\x93\x33\x38\ +\x57\x87\x44\x0f\x4d\xa5\x70\x6c\x0e\x1e\x9c\xec\xba\xbe\x84\xc7\ +\xe6\xb0\xcd\x40\x20\x99\x63\x73\x0a\x85\xe2\x7a\xf3\x17\x37\xaf\ +\x1e\xac\x94\x31\x9b\x08\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ +\x60\x82\ +\x00\x00\x05\x08\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\xba\x49\x44\x41\x54\x58\x85\xe5\ +\x97\x5b\x6c\x94\x45\x14\xc7\x7f\x67\xbe\xd2\x2a\x78\x21\x2d\x89\ +\x8b\x72\x6d\x40\xb1\x51\xa3\x74\xb7\xe8\x83\x37\x24\x90\x80\x5c\ +\x34\x56\x43\x34\x62\x08\x74\x4b\x61\x0b\x9a\xa0\xa0\xc4\xb5\x01\ +\xb1\xbe\x40\xba\x5d\x5a\x76\x6d\x62\x48\x78\xb2\x89\x0d\x54\x40\ +\x49\x34\xf0\xa4\xa5\xbb\x36\x3c\xd8\x60\x4c\x20\x60\x69\x4b\x84\ +\x26\x1a\x01\xbb\xec\xce\xf1\x61\xbb\xcb\xd7\xfb\x45\xdf\xf8\xbf\ +\x7d\x67\xce\x39\xff\xff\xcc\x37\x33\xe7\x0c\xdc\xe9\x90\xf1\x38\ +\xfb\x2a\x0e\xcc\xb4\xa9\xe4\x1a\x51\x59\x82\x30\x13\x61\x06\x8a\ +\x41\xb9\x8c\x48\x07\xc2\x69\x47\x6d\x53\x4b\x64\xeb\x6f\xff\xab\ +\x00\x6f\x79\xa8\x04\xa5\x1a\x78\x71\x8c\x59\x5b\x45\x75\x67\x6b\ +\x64\xeb\xf7\xff\x49\x40\x71\x59\xe4\x7e\x91\xde\x7a\x60\x6d\x9f\ +\xa9\x0b\xa4\x59\x95\x13\xea\xa4\xce\xeb\x3f\xa6\x6b\xd2\x64\x63\ +\x35\x81\xc7\x8a\x9d\x63\x0c\x4b\xd5\xb2\x1a\x61\x76\x5f\xfa\xe3\ +\x4e\x2a\xb5\xbe\xa5\x61\xdb\x95\x71\x0b\x58\x58\x71\x60\x9e\x49\ +\xda\xa3\x88\x3e\x0a\x74\x89\x10\x9c\xf2\xc0\xb5\x2f\x4f\x55\x55\ +\x25\x47\x9c\x52\x30\x68\xbc\xdd\x05\x6f\x80\xec\x01\x2d\x04\x2e\ +\x19\x58\x75\x26\x52\x79\x76\xcc\x02\xbc\x9b\xf6\x15\x62\x73\x5a\ +\x80\x69\xc0\x11\x27\x97\xb7\x5b\x6a\x2b\xff\x1a\x91\x78\x00\xe6\ +\x05\x42\x79\x53\x7b\xa9\x43\x58\x0f\x5c\x47\x78\x36\x76\xb0\xb2\ +\x6d\x54\x01\x8b\x02\xa1\xfb\x92\x09\x7e\x14\x28\x52\xb4\x26\xee\ +\xe9\x79\x8f\xaa\x2a\x3b\x1e\xf2\xdb\x50\xf1\xf9\x43\x3b\x14\xd9\ +\x0b\x74\xa8\xa6\x4a\xe2\xd1\x77\xbb\xdc\x1e\x39\x03\x43\x52\xbd\ +\x84\x45\x28\x02\x9a\x87\x22\x4f\x9f\x84\xd4\x06\x81\xe5\x02\xb3\ +\x14\x2c\xc8\x45\x55\x8e\x41\xb2\xa1\x3f\x81\x68\x6b\x44\xab\x7d\ +\xe5\xb5\x85\xaa\x6c\x30\xe2\x1c\x06\x5d\x02\xa2\x43\xae\x40\x89\ +\xbf\xd6\x6b\xd1\x56\x84\x3f\xd4\xe6\xcd\x8f\x47\xfd\x7f\x66\x07\ +\x83\x41\xe3\xeb\xce\xff\x40\x91\x8f\x81\xbb\x86\x99\xf2\x75\x55\ +\x3e\x8c\x47\x03\xb5\x6e\x92\xa2\xd2\x60\xee\xe4\xfc\x82\xb3\xc0\ +\x02\xd0\x15\xb1\xc8\xd6\xe3\x99\x31\xe3\x8e\xb6\xa2\x9f\x01\xa8\ +\xea\xee\x81\xe4\xde\xee\xfc\x43\x7d\x4b\x39\x1c\x39\xc0\x14\x11\ +\x6a\xbc\xfe\x50\x1d\x68\x76\x72\xed\x8d\x55\x09\x81\x8f\xfa\xe6\ +\x5c\xed\x1e\xcb\x0a\x28\x2e\xdb\x3f\x1d\xe5\x25\xa0\xe7\x66\x4f\ +\x4f\xc4\x9d\xd5\xd7\x5d\xb0\x0b\xe4\xad\x11\x88\x5d\x50\x40\xca\ +\x7d\xfe\x70\xa5\xdb\xda\x1a\x09\x34\x01\xe7\x80\xc7\x4b\xfc\xb5\ +\x4f\x0c\x12\x20\x98\x95\x80\xa0\x1c\x6b\x6f\xac\x4a\x64\xec\xde\ +\x4d\xfb\x0a\x15\x76\x8d\x8d\x3c\x9d\x29\x2d\x43\x3f\x7d\x6a\x4b\ +\xed\x83\x2e\xbb\xa2\x7a\x14\xc0\x8a\xbe\x32\x48\x00\x22\x2f\xa4\ +\x03\xe5\xdb\x7e\xe9\x34\xa7\x02\x98\x34\x76\x01\x59\x4c\x71\x12\ +\x6c\x74\x1b\xac\x31\xdf\xa5\x73\xca\xe2\xc1\x02\x60\x26\x80\x23\ +\x72\xc1\x1d\xa4\xca\x8a\x09\x90\xa7\x21\xfa\xb2\xfb\x33\x97\xe4\ +\x79\x00\x85\x19\x83\x04\x64\x8c\x46\x6e\xb9\x8e\x91\x0a\x50\x38\ +\x71\x01\x99\x2b\x39\x8d\xab\x93\x9c\x4c\xee\x87\x32\x1b\xd1\x0c\ +\x0a\x72\x23\xf8\x89\x8c\xea\x33\x12\x14\x67\x94\xdc\xee\x4d\xc8\ +\x65\x80\x84\x38\x9e\xac\x53\xfa\x12\xba\x38\x61\x01\xc8\x25\xf7\ +\xd7\xbd\xd6\x78\xd2\xba\xe8\xcc\x5c\x70\xb7\x67\xa7\xf2\x3b\x80\ +\xb1\xcc\x1d\x90\xe4\x38\x13\x85\x68\xbf\x58\x73\x2b\x55\x08\x20\ +\xd0\x91\xb5\xdd\x1e\xd5\x53\x00\x22\xb2\xcc\x1d\xe4\xa0\x07\x81\ +\x89\xd4\x82\x84\x49\x4a\x43\x3f\x01\x86\xa5\x00\x0a\x3f\x0c\x12\ +\x90\xca\x91\x66\x00\x55\x5d\x51\x5c\x16\xc9\x1e\xbb\x96\x48\x65\ +\x3b\x10\x1a\x37\xbd\xca\xde\x33\x0d\x81\x0b\x6e\x83\x55\x59\x05\ +\x60\x6c\xaa\x69\x90\x80\xb6\x70\xa0\x53\xd2\xca\xa6\x41\xef\x86\ +\x7e\xb9\x34\xef\xfd\xf1\xfd\x0a\x6d\x8c\x4d\xbf\xba\xdb\x6d\xf1\ +\x6e\x0a\xaf\x14\x28\x02\x7e\x69\xfd\x62\x5b\xb6\x37\xe8\xbf\xc3\ +\xad\xdd\x01\x20\x42\x70\x51\x20\x74\x5f\xc6\x1c\x8f\xfa\x6f\xa9\ +\xe6\xae\x51\xb4\x86\x91\x7f\x47\x12\x61\xef\xdc\x9e\xe9\x6b\xdd\ +\x55\xb4\xa8\x34\x98\xab\x36\x5d\x67\x04\x76\x0e\x5b\x0d\x01\x8a\ +\xfd\xa1\xc3\x02\x6f\x02\x47\x62\x9e\x6b\xaf\x0e\x2c\xc7\xde\xf2\ +\x9a\xc7\x50\x29\x07\x96\x03\xb3\x48\x5f\xfe\x17\x15\xfd\x46\x8c\ +\xd6\xc7\xea\xb7\xfd\x3a\x60\x35\xc4\x5b\x56\x5b\x8f\xe0\x07\x4e\ +\xc5\x22\x81\xc5\x23\x0b\x48\xf7\x81\x3f\x01\x0b\x80\x7d\x31\xcf\ +\xb5\xed\xc3\x35\x24\xa5\xa5\x5f\x39\x00\x8d\x8d\xaf\xa7\x86\x5e\ +\x10\x15\x6f\x79\x78\x3b\xaa\x9f\xa3\x74\xa6\x72\xc5\xd7\x16\x0e\ +\x74\xba\x3d\x86\x6c\xc9\x16\x56\x1c\x98\x67\x52\xa9\x16\x20\x1f\ +\xf8\xfa\x86\xe3\xac\x6b\xaf\xdb\xfc\xf7\xd0\x24\x43\xa3\xa8\x34\ +\x98\x7b\x77\x7e\x41\x58\x60\x23\x70\xc3\x20\xcf\x9f\x89\x04\x62\ +\x03\xfd\x86\x6d\x4a\x4b\x36\x86\x1f\xb6\xc6\x1e\x05\x1e\x51\xe4\ +\xb2\x40\xf0\x1e\xcf\xd5\x43\x63\x69\x4a\x7d\x57\xf2\x5f\xb3\x2a\ +\x7b\x04\xe6\x03\x1d\xaa\x66\x75\x3c\xba\xe5\xe7\xa1\xdc\x47\x6c\ +\xcb\x9f\x7c\x67\xff\xd4\x9c\x3c\x13\x05\x29\xed\x33\x75\x88\xd0\ +\x8c\x72\x02\x6b\xce\xe7\xd8\x44\xd7\xcd\x94\x58\x27\x37\xc7\xa3\ +\x86\xd9\xc6\xda\x65\x88\x59\xdd\xd7\x0d\x03\x9c\x14\xc7\x59\xd7\ +\x5a\xb7\xb9\x7b\x38\x8e\x31\x3d\x4c\x4a\xfc\xe1\x67\x2c\x5a\x0d\ +\xfa\xdc\x58\xfc\x81\x36\x55\x76\xc4\xa3\x95\x27\x47\x73\x1c\xd7\ +\xd3\xec\xe9\xf2\xfd\x73\x92\xd6\x59\x83\xb0\x04\xed\x7b\x9a\x81\ +\x03\x74\xa4\xaf\x57\x3d\x6d\xd5\x34\xc5\xa3\x81\x73\xe3\xc9\x7b\ +\x67\xe3\x5f\x5e\xef\xd7\x3d\x0b\xb2\x5f\x42\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xf6\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xa8\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\x31\x15\x80\x30\x00\xc4\x50\x5a\x53\xf5\x81\x50\x7c\x60\x0a\ +\xba\xe2\xe0\x33\x24\xdb\x4d\x97\x97\x71\x20\xd6\xf5\xbc\xdf\x7d\ +\x9f\x73\x08\x8f\x29\x4e\xff\x44\x01\xb4\x80\xa6\x00\x5a\x40\x53\ +\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\ +\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\ +\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\ +\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\ +\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\ +\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\ +\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\ +\x0d\x64\x41\x04\x80\xc9\xe4\x92\xad\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x00\x87\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x39\x49\x44\x41\x54\x58\x85\xed\ +\xce\x31\x11\x00\x30\x08\x04\x41\x26\xe2\x50\x80\x04\x84\x20\x3d\ +\x22\xa0\xdc\xeb\xff\x67\x23\x16\x65\xf5\x64\xf5\x6c\x3e\xde\x66\ +\x7c\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ +\xc0\x07\x65\x23\x03\x3b\x58\x7b\xaf\x09\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x75\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x27\x49\x44\x41\x54\x78\x9c\xed\ +\xc1\x01\x0d\x00\x00\x00\xc2\xa0\xf7\x4f\x6d\x0e\x37\xa0\x00\x00\ +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x77\x03\ +\x40\x40\x00\x01\x8f\xf2\xc9\x51\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x0a\x60\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x0a\x12\x49\x44\x41\x54\x78\x9c\xed\ +\x5b\x6b\x90\x14\xd5\x19\x3d\xe7\xce\xcc\xae\x83\x2c\x88\xf8\x48\ +\x4a\x28\x83\x31\x96\xae\x01\x4c\x70\x99\x5d\x82\x2b\x98\xa4\x54\ +\x82\x2c\xbb\x8b\x1b\x1f\xa5\xe2\x23\x2a\x26\xc6\xc4\x24\x26\x5a\ +\xa5\x8b\x46\x8d\xc6\x08\x96\x55\x06\xb5\x82\xa5\x22\x95\x64\x60\ +\x77\x00\x2d\x51\xab\xc4\xb5\x10\xd9\x5d\x5e\x6a\xf9\xc0\x32\x51\ +\x11\x42\x34\x2a\xca\x43\x79\xcc\xf4\x3d\xf9\xb1\xa0\xdd\x3d\x33\ +\xdd\x33\x3b\x33\x94\x95\x70\xaa\xe6\x47\x7f\xf7\xdc\xef\x9e\xfb\ +\x4d\xf7\xed\xfb\xf8\x1a\x38\x80\x03\x38\x80\xff\x67\x70\x7f\x34\ +\x72\x4a\x52\x87\xef\x89\xa1\x91\xd6\x8e\x94\xc1\xf1\x14\x8f\x11\ +\x70\x08\x80\x41\x00\x22\x00\xb6\xed\xfd\xbd\x27\xe8\x0d\xc0\xbc\ +\x8e\x28\x96\xf7\x4e\xe1\x3b\x95\xd6\x56\xb1\x00\x8c\x4b\xe9\x9b\ +\x8e\xb5\xd3\x41\x4e\x01\x30\xaa\x5f\x4e\x84\x77\x60\xb4\xd4\x5a\ +\xf3\xf0\xaa\x16\xac\x06\xa9\xf2\xaa\x2c\x77\x00\x24\x36\xa4\x70\ +\xba\x85\xae\x03\x30\xb1\x9c\xae\x09\xbc\x2a\x70\x56\xe6\x43\x3c\ +\xb6\xe6\x0a\xa6\xcb\xe8\xb7\x3c\x48\x74\x68\x22\x8c\xfe\x08\xe1\ +\xe4\x72\xf9\xcc\x83\x77\x05\xce\xec\x6d\xc6\xa3\xe5\xb8\x23\x4a\ +\x0e\x40\x62\xb1\x8e\x94\x63\xef\x26\x78\x7e\x00\xcd\x02\x58\x01\ +\xaa\x4b\xd6\xac\x37\x11\xfc\x53\x19\x6c\xb1\x16\xdb\x0f\x02\x9c\ +\x9d\x06\x35\x31\x60\xb0\x0c\x46\x08\x38\x0e\x50\x03\x80\x1f\x02\ +\x88\x07\xf8\x5c\x6e\x2d\x67\xac\x9a\xc6\xd7\x4a\xd1\x5f\x52\x00\ +\x1a\x52\x1a\x6b\xa5\x45\x00\xbe\x9e\xa3\x78\x3b\xa8\x27\x29\xf3\ +\xb8\x05\x9e\xea\x6d\xe1\xc7\x45\xf9\x4e\x2a\xee\x44\x70\x1a\x69\ +\xcf\x02\x38\x25\x4f\x1b\xbb\x44\x5e\xd2\xdb\xcc\xbf\xf6\x47\x3f\ +\x50\x42\x00\xc6\x76\xe8\x3c\x50\x0f\x11\xa8\xf6\x8b\xa2\x74\x6f\ +\xb4\xda\xdc\xf1\xc2\x64\x7e\xd2\x5f\xff\x6e\xd4\x26\x55\x55\x13\ +\xc5\x4f\x00\xdd\x04\xe0\x08\x7f\xb9\xa0\xdb\x7a\x5f\x36\x37\xe1\ +\x66\xda\x62\x7d\x17\x1f\x80\x76\x99\xc4\x28\x7b\x2b\xc8\xeb\x7d\ +\x25\x56\xd0\x43\x94\xb9\xb9\xa7\x95\x9b\x8a\xf6\x5b\x00\xbe\xb7\ +\x58\x35\x69\x8b\x6b\x29\xfd\x1a\xc0\x40\x4f\xa1\xb0\x28\xee\xf0\ +\x82\xae\x36\xee\x28\xc6\x67\x71\x01\x68\x97\x49\x8c\xb6\xf3\x01\ +\x9e\xe3\x2b\xd9\x6c\xc8\xe6\x95\xcd\xec\x2d\xca\x5f\x3f\x91\xe8\ +\xd0\x30\x18\xa5\xfc\x03\xae\x88\x75\xac\xe6\x84\x9e\x49\xdc\x56\ +\xa8\x2f\x53\x54\xc3\x27\xd9\x99\x39\x3a\xdf\x9d\x11\x4f\xde\x5f\ +\x9d\x07\x80\x9e\x56\x6e\x32\x69\x36\x0a\x9a\xef\xb6\x53\xf8\x0e\ +\x77\x69\xfe\xd9\x49\x45\x0a\xf5\x55\x70\x00\xea\x3b\xf4\x63\x88\ +\x37\x7a\x1a\x84\x1e\x89\x6f\xe5\xc4\x35\xad\xfc\x77\xa1\x7e\xca\ +\x85\x95\x6d\xdc\xd9\xdb\x6c\x2e\x10\xf9\x5b\x00\x5f\xbc\x0e\x05\ +\x4c\xde\x18\xb1\xb7\x17\xea\xa7\xa0\x47\x60\xec\x42\x9d\x4c\xa3\ +\xe5\x00\x0e\xfa\xd2\xaa\xc7\x7a\x9a\xcd\x85\x95\x98\x9d\x15\x8b\ +\x44\x87\x7e\x01\x6a\xb6\xdb\x26\xf0\xa2\xde\x16\x3e\x1a\x56\x37\ +\x34\x00\x63\x3b\x35\x94\xd0\xcb\x00\x8e\x72\x99\x7b\xe3\x5b\x79\ +\x6a\xd7\xc5\xdc\x55\x8c\xd0\xfa\x4e\x9d\x60\x85\x66\x1a\x3b\x0a\ +\xe2\x30\x00\xc3\x00\x38\x00\x36\x91\xda\x24\x6b\xd6\x2a\x86\xce\ +\xa2\xd7\x00\x12\x13\x29\x3b\x17\xe0\xc5\x2e\xeb\x1e\x8a\x0d\xdd\ +\xad\x5c\x1b\x54\x35\x34\x00\x89\x4e\x67\x2e\xc0\x4b\x5c\xa6\xcd\ +\xd1\x08\xeb\x56\x34\x71\x73\x21\xda\x6a\x93\xaa\xaa\x89\x61\x06\ +\xa4\x2b\x01\x1c\x5f\x48\x1d\x11\xeb\x0c\x78\xef\xf0\x34\xe6\x2d\ +\x68\xa3\x53\x48\x9d\x33\x9f\x54\xf5\xc7\x3b\xb5\x8c\xc4\x38\x97\ +\x79\x6d\x7c\x08\x13\x5d\x13\x99\xc9\x57\x2f\x30\x00\x89\x4e\x8d\ +\x07\xb4\xdc\xad\x0d\xe2\xb8\x9e\x56\x76\x17\x22\x6a\x6c\x4a\x53\ +\x69\x75\x17\x88\x63\x0b\xe1\xe7\xc0\x4b\x02\x7f\xd5\xdb\xc2\x65\ +\x85\x90\x13\x8b\x75\x24\x1c\xbd\x0a\xe0\xb0\x7d\x36\x82\xd7\x74\ +\xb7\xf0\xde\x7c\x75\xf2\x0f\x82\x12\x01\xfd\xc1\x67\x9c\x5f\x48\ +\xe7\xc7\x3c\xa0\x58\x22\xe5\xdc\x47\x29\x55\x42\xe7\x01\xe0\x24\ +\x42\xcf\xd6\x77\x38\x33\xd1\xae\xd0\x01\xbb\xa7\x89\x1f\x40\xbc\ +\xcd\xa3\x18\xba\x71\xd4\xd3\x3a\x38\x5f\x9d\xbc\x4e\x1b\x52\x68\ +\x04\x30\xde\x65\x4a\x3b\xd6\xb4\x87\x89\x18\xff\x84\x86\xc4\x0e\ +\xd7\x52\x88\x57\x85\x71\x0b\x85\xc8\xf6\xc4\x68\xfd\x7d\xcc\x12\ +\x0d\x08\xe3\xc6\xb7\xe1\x7e\x12\xef\xb9\x4c\x87\x0d\xf8\x0c\x57\ +\xe4\xe3\xe7\x0d\x80\x85\x7e\xe3\xbe\xa6\xf4\xc0\xea\x69\x7c\x3b\ +\xa8\xf1\xda\xa4\xaa\xd2\x7b\xb4\x48\xc0\xf7\xc3\x84\xf6\x03\xd3\ +\xa2\x69\x3d\x1a\x76\x27\xf4\x0d\xcc\xf4\xfc\x51\x82\xae\xcd\x37\ +\x37\xc8\xe9\xac\x2e\xa9\xaf\x01\x38\xc3\x65\x4a\x2b\x6a\x6e\x0d\ +\x94\x27\x71\x60\xd4\xde\x07\xa0\x31\x90\x57\x0a\x88\xd6\xc4\x68\ +\x1b\x7a\x17\x0e\x4f\x63\x1e\x80\xb7\x5c\xa6\xa3\x36\x18\xfc\x20\ +\x17\x37\x67\x00\x22\x51\x9c\x87\xbe\xad\xaa\x7d\x0d\x2f\xeb\x69\ +\xe2\x07\x41\x8d\x26\x16\xe1\x7c\x82\x97\x85\x89\x2b\x1d\xbc\xa9\ +\x7e\xa1\x72\x76\x66\x1f\x16\xb4\xd1\x21\xb4\xc0\x53\xcb\xd8\x8b\ +\x72\x71\x73\x06\x40\xd0\x59\x1e\x83\xe5\x92\xa0\x06\xc7\x2c\xd1\ +\x00\x48\x77\x04\x71\xca\x09\x19\xcd\x0a\x9d\xee\x1a\xe3\xd3\xcc\ +\x49\xb9\xea\x64\x05\x60\xef\x88\xe9\x7e\x97\x22\xe3\xe0\x89\xa0\ +\xb6\x62\x0e\xae\x85\x77\xa2\x54\x69\x8c\xdc\x10\xc3\xf4\x20\x42\ +\xf7\x3a\xac\x02\xe0\xbe\x6b\x07\x6f\x8a\x61\x8c\x9f\x97\x15\x80\ +\xea\xcf\x51\x0f\xa0\xca\x65\x7a\x69\x4d\x1b\xdf\xf3\xf3\xf6\xe1\ +\xec\xa4\x22\x56\xfa\x79\xa8\xe4\x32\x83\xd2\x35\x81\x84\x9b\x69\ +\x29\x79\xfe\x38\x29\x7b\x9f\x32\x2b\x00\x06\xf8\xb6\xa7\x12\x3d\ +\x13\xa1\x2c\x6c\x8c\xe1\x14\x02\x87\x07\x8a\xa9\x0c\x46\x26\x16\ +\xea\x5b\x41\x04\x4b\xe3\xd1\x2e\xda\x13\xfd\x9c\xec\x31\x40\xf6\ +\x04\x0f\xc1\x9a\xb7\xb2\x38\x6e\xba\xec\xb4\x40\x99\x95\x84\x41\ +\x6b\x50\x71\xc4\xc0\xa7\x9d\x27\xf8\x39\xd9\x01\x20\xbf\xe1\xbe\ +\xb4\x40\xe0\xbb\x1f\x62\xa5\x77\x81\x83\x1a\xcf\x7a\xa6\xdd\xc8\ +\xec\xf1\x69\x17\x46\xf8\x39\x59\x01\x90\x45\x8d\x8f\xf0\x69\xa0\ +\x06\xee\xd7\xc1\xcf\x8f\x61\x41\x85\x07\x7f\x96\xa5\xbd\xc6\xcf\ +\xc9\x0a\x00\xe9\x25\x59\x22\xff\x1e\x5b\xdf\xac\x2c\xd7\x6e\xed\ +\xfe\x42\x60\x00\xba\xa6\x63\x37\x00\xf7\x4a\xb0\xaa\x36\x29\xf7\ +\x00\x9f\x23\x00\xbe\x15\x22\x2d\xf2\x6e\x78\x4c\x98\x00\x93\xcb\ +\xc7\x7e\x44\xac\x54\x07\xd9\x8f\x00\xb0\xdd\x7d\xed\xbf\x23\xdc\ +\xd8\xbb\xce\x0e\x9c\x21\x56\x18\x81\xbb\xcf\x13\x1e\x46\x35\x80\ +\xa8\xcb\xb4\xe7\xf5\x36\xee\x71\x73\x72\x0c\x82\xf0\xec\xa8\xda\ +\xbe\x53\xdc\x20\xfc\x2b\xa4\xbc\x92\x08\x0c\xc0\xce\x43\x31\xd8\ +\x67\xda\xee\xe7\x64\x07\xc0\x6a\x83\x8f\x91\x35\x72\xba\x41\xe8\ +\xd5\xa0\xf2\x4a\x42\x21\x6d\xcb\xc1\x31\x3e\xd3\xbb\x7e\x4e\x8e\ +\xe7\xd7\xbc\xe1\xbe\xa2\x6c\xe0\x64\x03\x32\x9d\x81\xe5\x15\x84\ +\x09\x6f\xdb\xa3\x5d\xd0\xfa\x2c\x1f\x59\x55\x08\xdf\x61\x23\xc7\ +\x67\x71\x5c\x38\x68\x1b\x9e\x01\x02\xde\x14\x95\xc3\x86\xee\x16\ +\xac\x0b\x22\x10\x76\xbc\xf7\xda\x64\xdd\x31\x59\x01\x88\x67\xb0\ +\x12\x80\xfb\xfc\xfd\xbb\x89\x0e\xe5\x7d\xdd\x74\x5d\xcc\x5d\x94\ +\x1e\x0e\x95\x5b\x66\x48\x7c\x30\x70\x4b\xbe\x5d\x06\xe0\x64\x6f\ +\x25\x74\xf9\x69\x59\x01\xd8\x7b\xb6\xb6\xd2\x53\x8f\x98\xec\xe7\ +\xb9\x11\x73\xcc\x2d\x00\xb6\x06\x2a\x2e\x2f\x36\x46\x1c\xcc\x0e\ +\x22\xd4\x8d\xc2\x18\x78\xe7\x28\xdb\xe2\x87\x62\xb5\x9f\x97\x67\ +\x3f\x80\x9e\x55\x14\xa1\x29\x41\x8d\x2d\x6f\xe3\x87\x00\x83\x77\ +\x8c\xca\x09\xf2\x86\x95\x6d\xdc\x19\x44\x31\xb0\x1e\xcd\x82\x9e\ +\xca\xb5\x3d\x9e\x33\x00\xb1\x08\xe6\xa3\x2f\xa9\x61\x6f\x65\x9c\ +\x76\x4a\x52\x81\x2b\xbe\xf8\x10\xdc\x03\xe2\xe9\x40\xe1\xe5\x00\ +\x35\xaf\x67\x2a\xe6\x07\x72\xda\x65\x40\x7a\x16\x69\xb4\xe6\x91\ +\x5c\xd4\x9c\x01\x58\xd1\xc4\xcd\x02\x9e\xf9\xa2\x32\x50\x9d\x8e\ +\x5a\xff\x71\xb8\x07\x5d\x13\x99\xd9\xdd\x77\x70\xfa\x66\xa0\xb8\ +\xd2\xd0\x1d\xff\xd4\x5c\x1e\x76\x1c\x57\x3f\x1a\xe7\xc2\x7b\x08\ +\xf3\x7e\x7c\xe8\x97\xfd\x71\x23\xef\x34\x56\xe4\x9f\x3c\xd7\xe0\ +\x4f\xc7\x75\xe8\xe8\xa0\x86\x5f\x6a\xe6\xa7\x8e\xe5\x24\x54\x22\ +\x08\xc4\x6a\x44\x38\x35\xec\x38\xae\x36\xa9\x2a\x49\xbf\x77\xdb\ +\x44\xce\xce\x77\x3a\x94\x37\x00\xab\xa6\x62\x19\xbc\x83\x61\x95\ +\x03\x3b\x33\x4c\xe7\xea\x69\x7c\x7b\x37\x59\x0f\xe4\x8e\x78\xff\ +\xa0\xbf\x99\x34\x1b\xc3\x36\x66\x01\x60\x60\x0c\x97\x83\x9e\xc9\ +\xdb\x96\x98\xc1\x9c\x7c\xfc\xfc\x0b\x19\x52\x24\x6f\xf0\xd9\x2e\ +\x4c\xa4\x82\xd7\xe0\x40\xdf\x9d\x10\x1f\xc2\x1f\x11\xfc\x1d\x72\ +\x4c\x3f\x8b\xc0\x47\x02\x67\xf4\x34\x9b\xf3\xc2\x06\x3d\x00\x18\ +\xb3\x44\x87\x51\xf2\x1c\xe1\x43\xbc\x7d\x45\x13\xf3\x6a\x08\x5c\ +\xc9\x75\x37\xb3\x0b\xd4\x3c\x0f\x5f\x4a\x25\x16\xeb\xc8\x30\x31\ +\x5d\x13\x99\xe9\x6e\xe1\x9d\x11\xf0\x58\x49\x73\x00\x7c\x1e\x56\ +\xc7\x85\xad\x80\xee\xc8\x64\x78\x6c\x6f\x0b\xef\x2f\xe4\x08\xbe\ +\x36\xa9\xaa\x48\x46\x0b\xe1\xcd\x21\x7a\x25\xf3\x11\xf2\x9e\x0b\ +\x02\x05\x9c\x0e\x8f\xeb\xd4\x11\x0e\xf4\x0a\x80\x2f\x3a\x2d\xe1\ +\xc5\xa1\x71\x9e\xb6\x74\x12\x77\x87\xd5\xdf\x87\x31\x4b\x34\x20\ +\x96\xc1\x19\xa0\x6d\x95\x38\x12\x7d\xbb\xc8\x87\x02\x80\x80\x0f\ +\x09\x6c\x06\xb4\x96\x34\x0b\xb6\xa5\xf1\xac\x7f\xd5\x16\x86\xfa\ +\x4e\x67\x8e\xc0\x2b\x5d\xa6\xb4\x21\xc7\x87\x65\xae\x14\x94\x20\ +\x91\xe8\x50\xbd\xa8\x2e\x6f\x46\x98\x1e\xea\x69\x36\x97\x95\x92\ +\x20\xd1\x90\x54\xfc\x90\x81\xb0\xc5\x04\x32\x8f\xbe\xab\x40\xdd\ +\xe7\xb6\x89\xbc\xac\xb7\x99\x73\xc3\xea\x16\x9c\x24\x95\xe8\xd0\ +\x05\xa0\xbc\x19\x17\xd2\x83\xdb\x1d\x73\x75\xb1\xff\x56\xd9\x20\ +\xb1\x3e\x85\xab\x05\xcd\x86\xfb\x71\xa6\xee\xe9\x69\x8e\xfc\xb2\ +\x10\x17\x45\x65\x89\xd5\x77\x38\x77\x8a\xbc\xce\xa3\x01\x78\xde\ +\x89\x72\xda\x9a\x29\xfc\xa8\x18\x5f\xa5\xa2\x36\xa9\xaa\x41\x11\ +\xfb\x67\x91\x97\x7a\x0a\x88\xa7\xe3\x87\x70\x72\x50\x52\x84\x1b\ +\x45\x6d\x67\x0d\x77\xcc\x0d\x04\x52\xde\xf6\x70\x6a\x34\xa3\x55\ +\x0d\x8b\x34\xb2\x18\x5f\xa5\x60\x5c\xa7\x8e\xa8\x89\xea\xd9\xac\ +\xce\x03\xaf\xed\x06\xcf\x29\xb4\xf3\x40\x3f\x12\x25\xcf\x4e\x2a\ +\xb2\x31\x6a\xef\x12\xe8\xbf\xc5\xd2\x80\xe6\x44\x60\x6e\x7b\xb1\ +\x85\xff\x29\xd6\x6f\x21\x68\x48\x2a\xee\x44\xf1\x33\x42\xd7\x03\ +\x18\xe2\x2b\x5e\x9a\xc9\xf0\xdc\x35\x6d\x2c\x6a\x51\xd6\xff\x54\ +\xd9\x94\x2e\x65\xdf\xeb\xcd\xbf\x31\xb9\x83\xd2\xdd\x8a\x9b\x59\ +\xc5\x24\x2c\x06\x61\xc2\x73\x8a\xee\xda\x82\xe9\xa2\x66\x22\xc7\ +\x19\xa4\xa0\x59\x47\x67\xcc\x75\x85\xe6\x13\xb9\x51\x52\xb2\x74\ +\x5d\x87\x1a\x0d\xd5\x09\x60\x68\x8e\xe2\x4f\x00\x3d\x0e\x99\xc7\ +\x11\xc7\x33\xc5\x06\xa3\x36\xa9\xaa\x41\x06\x8d\x32\xf6\x2c\x80\ +\x4d\x00\x72\x4d\xc3\xd3\x22\x67\x14\x32\xda\xe7\x43\xc9\xe9\xf2\ +\x75\x8b\x34\xdc\x58\xdd\x03\xa0\x25\x80\x96\x06\xf1\xbc\x2c\x9f\ +\xa3\xc1\x9b\x12\xfe\x21\x83\x2d\xd5\x51\xec\x48\x1b\x38\x66\x07\ +\x6a\x6c\x15\x06\xcb\xc1\x08\x10\xc7\x11\xb6\x01\xe0\xe9\xe8\xfb\ +\xa4\x26\x9f\xf0\x55\x22\x67\xf4\x34\x73\x4d\x29\xfa\xcb\xf6\xc1\ +\x44\x7d\x4a\x67\x4a\xba\x13\x40\xa5\x07\xc3\xcd\x12\x6f\x39\xda\ +\xc1\x5f\xfa\x73\xcb\xfb\x51\xde\x4f\x66\xda\x65\xc6\x8e\x42\x93\ +\xa1\xae\x17\x50\x57\x56\xdf\xc0\xdb\x00\x67\xc5\xb7\x62\x6e\xb1\ +\x09\x9a\x41\xa8\xd8\x47\x53\x75\x0b\x75\xa2\x31\x76\xfa\xde\x8f\ +\x1d\x8e\xeb\xa7\x9b\xf7\x01\x3d\x69\x65\x1e\x59\xf5\x0a\x5e\xe8\ +\xcf\xf7\x00\x61\xd8\x2f\x9f\xcd\xd5\x2d\xd2\x70\x5a\x4c\x34\xb2\ +\x27\x8a\x3c\x1e\xc0\x08\x12\x83\x25\x0c\x42\xdf\xc9\xcd\x56\xf4\ +\x7d\x36\xb7\x11\xd0\x7a\xd2\xac\x17\xf1\x7c\x4f\x13\xde\xf8\x2a\ +\xe4\x22\x1f\xc0\x01\x1c\xc0\xff\x2e\xfe\x0b\x91\x5a\xc0\x8b\x79\ +\xe5\x16\x6d\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x0c\xd6\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x0c\x88\x49\x44\x41\x54\x78\x9c\xe5\ +\x9b\x5b\x6f\x5b\xc7\x11\x80\xbf\x25\x45\x8a\x94\x28\x89\x92\xad\ +\xbb\x64\xc9\x4e\x9a\xc2\x41\xe0\x26\x45\xd1\xa0\x48\x0a\xf4\xa9\ +\x7d\xe9\x7b\x81\x16\xfd\xa3\x7d\x2a\x50\xb4\x0f\x41\x90\x36\x4e\ +\x52\x20\x69\x92\xc6\x96\x6c\xc9\x37\x5d\x48\x49\xa4\x2e\xe4\xf4\ +\x61\xf6\x1c\xee\xd9\x33\x87\xa4\xe4\xf4\xc9\x03\x10\x24\x77\xf7\ +\xcc\xce\xcc\xee\xce\x6d\xe7\x00\xb2\x05\xe2\x78\xe3\x40\x9c\xf2\ +\x9e\xfe\x78\x93\x84\x90\xe3\xf9\x4d\x12\x42\x96\x57\x97\xed\xe0\ +\x0e\xf0\x18\x9c\x14\x3c\xdc\x00\x6e\x19\x1d\x25\x60\x32\x8b\x2f\ +\x6d\xaf\x0d\xa1\x66\x12\x10\xe0\x62\xc8\x98\x73\xa0\x67\xb4\x77\ +\x81\xbe\xd1\xfe\x12\xdc\xa9\x8d\x2a\xcf\xa3\x1b\x35\x00\x64\x1b\ +\xb8\xed\x09\x3d\x01\x5e\xf8\x89\xa7\x80\x39\xdf\x2e\xc0\x59\xd0\ +\x3e\xeb\xdb\xfa\xbe\x1d\x8f\xa3\x0a\x34\x81\x8a\xef\x3f\xf7\x34\ +\x54\xfd\xf7\x25\x70\x04\x97\xa7\x50\x39\xf2\x6d\x53\xa8\x20\x9d\ +\x9f\xff\xc4\xff\x9f\xf2\x6d\x0e\x68\x01\xa7\xbe\x7d\x29\xe8\x7b\ +\x01\xee\x71\x31\x6f\x85\x52\x92\x2d\x90\x09\x90\x8f\x40\x56\x8d\ +\x31\x6b\x20\x0b\x46\xfb\x06\xc8\xbc\xff\x3d\x05\x72\x0f\xe4\xae\ +\xff\xcc\x80\xdc\x01\x19\xb2\x23\xa4\xee\xc7\x2c\xa8\xe0\xe5\xae\ +\xc7\x31\xe1\xfb\xe7\x40\x36\xf3\x47\x55\x9a\x05\xed\x1b\x20\xbf\ +\x06\x29\x5f\xf3\x88\xcb\x04\xc8\x9f\xf5\xc1\x5c\xdf\x36\x48\xc5\ +\x68\x7f\xdb\x3f\xb7\xe2\x27\x5b\x8e\xf0\xdd\x1b\x73\x72\x3c\xe3\ +\x25\xff\xdb\x79\x46\xb6\xa0\x75\x4b\xdb\xe5\x2d\x83\xd9\x32\xc8\ +\x4f\x8c\xf6\x09\x90\x3f\xda\xbc\x14\x13\xf0\x91\x7f\x30\x92\x9a\ +\xac\x17\x30\x7f\xc7\x7f\xb6\xed\x15\x96\xed\x6b\x4c\x4e\x60\xa2\ +\xe2\xf6\x59\x15\x4e\x7b\x49\xe7\xcb\xf5\x97\xb3\xcf\xa5\xbb\xb9\ +\x02\xf2\xab\x71\x27\xdf\x1e\x6c\xfb\x50\x63\xca\x14\xc8\x6d\x63\ +\xfc\x2a\xc8\x07\xba\x7d\x4d\x7c\xf3\x5e\x79\x5e\x13\x64\x56\xb7\ +\xbc\xd9\x37\x07\xf2\x00\x64\xd1\xe8\x6b\xfa\x67\x23\xcb\x26\x9b\ +\xfa\xc9\x82\x71\x26\xe4\x17\xe0\x3e\x0d\xfe\x27\xca\xa3\x07\xec\ +\x01\x21\xa3\xab\x70\x79\x0b\x2a\x5f\x0e\xe1\x64\x0d\x78\x5a\xd0\ +\x97\xda\xe1\x1b\x3c\x0b\xf0\x00\xba\x4f\xa0\xf6\x2a\x68\xeb\x28\ +\x5d\x94\xc9\x29\xbc\x98\x37\x98\x30\x90\xc6\xc4\x34\x50\xe6\x1f\ +\xa0\x5a\xbd\xed\xc7\x6c\x01\x2f\x54\xa1\x0f\x05\xf1\xc4\x2c\xf9\ +\xff\x89\xe9\x4a\x34\x78\xd8\x46\xd0\xf6\xc2\xa0\x25\x86\x17\x20\ +\x82\x32\xbc\xe7\x9f\x5d\x02\x7e\x06\x7c\x0e\xcc\xa0\x16\x22\x81\ +\x9c\xd9\x8c\x04\x20\x0d\xd4\xcc\x24\xff\x37\x80\x36\xb8\x5d\x3f\ +\x51\x05\x35\x5d\x9b\xc0\xd7\xe0\xae\xf4\x7c\xb9\x13\x72\x20\xce\ +\x8f\x9b\x42\x7d\x81\x6f\x47\x98\x9f\xf8\xd9\x45\x60\x1a\x35\xa9\ +\x7b\xf6\xb3\xd2\x86\xfa\x0b\xd4\x9f\x58\x01\x7e\x00\x16\x80\xcf\ +\x80\xe7\x80\xb7\x3c\xec\xf8\xe7\x7b\xaa\xdb\xdc\x55\xd1\xc4\x5b\ +\x03\xf3\x26\x5b\x59\xcd\x29\x1b\x5e\x0f\x7c\x1c\x29\x46\xcb\x4c\ +\x2e\xa1\xa6\x72\x46\x3f\x37\x05\x59\xf5\xca\x78\x3d\x6b\x55\xd2\ +\xfe\x99\x81\x7e\x91\x09\x90\xdf\x78\x2b\x11\xb6\x07\x8a\x51\xee\ +\xaa\x8e\x18\x40\xc9\x98\xb5\xaf\x13\xb2\x0b\xae\x17\x8d\x5d\x03\ +\xfe\x0e\xdc\x09\x84\x10\xac\xcc\x61\x53\x19\xe7\x10\xdc\x53\xdf\ +\x37\xe6\xaa\x9b\xe0\x9f\x75\x4f\x80\x03\xc5\x7d\xd8\xcc\xf7\x8b\ +\x03\xd6\x81\xbf\x01\xf7\xb2\x73\xba\x9e\xf2\x22\xeb\x18\x47\xc0\ +\x12\xc0\x14\x70\x16\x31\x0f\x7a\xe6\xbf\xf3\x5b\xe9\x31\x59\x21\ +\xa0\x1a\xb9\xd9\x57\xc6\xdd\xe5\xf8\x3c\x8e\x0b\xee\x52\x71\x37\ +\xfb\xd1\x6e\x08\x3d\xbc\x1e\xf0\x04\x3d\x7a\xe1\x90\x1e\xea\x29\ +\x4e\xc7\x58\x2d\x25\x38\xe7\x57\x2f\x00\xd9\x46\x95\x4c\x29\x30\ +\x77\x07\xc0\x7d\xe0\xd2\x9b\xab\x57\xe8\xee\x09\x4d\x9e\x9f\xd0\ +\xdc\x04\x25\xe8\xfa\xe3\x56\x3b\xc4\xf6\xf7\xa7\x81\x2e\x48\x78\ +\x66\xfb\x3a\x56\xee\x03\x47\xe8\xca\x7f\xad\x63\x05\xa0\x03\x9d\ +\x13\xa8\x2f\x92\xd1\x67\xee\x08\xe4\xa7\xf1\x04\x63\x58\x01\x79\ +\x0b\x2e\x2a\x50\x9d\x46\x15\xd3\x29\x83\xad\xbd\x0b\xfc\x0e\xf8\ +\x4b\x01\x03\x01\x74\xe6\xa1\x9e\x04\x3f\x3e\x4e\xa8\x1d\xf9\xce\ +\x79\xd4\x52\xf8\x1d\xd5\x39\x87\xfa\xe1\x10\x64\x5d\xd4\x3c\xfe\ +\x06\xf8\x24\xa0\xd9\x2b\xcf\x7a\x0d\xb8\x0d\x72\x1e\x2d\x66\x6e\ +\x25\x62\x01\xc4\xd1\xe1\x5d\x60\x1a\x26\x1f\xaa\x12\x74\xfb\xd9\ +\xe1\xb2\x0e\xfc\x03\x0d\x70\x8c\x20\x43\x80\xee\x6d\xa8\x4d\x40\ +\xfd\x25\xb8\x4e\x01\x43\x47\xd9\xbf\x52\x07\x16\xe0\xa2\x06\xd5\ +\x93\xbc\xd6\x4e\x7d\x93\xbf\x02\x6b\xe0\xf6\x82\xce\x36\xc8\x09\ +\xba\x63\xdf\xf6\x9e\x6b\x42\x5b\x9f\xe8\xd8\xc7\x3a\xa0\x0a\x9c\ +\xfb\x09\xee\xa1\xab\xf2\x85\x4d\xb3\x2c\xa1\xdb\xbe\x87\xad\x13\ +\xa6\x81\x55\xa8\xb5\x55\x89\x15\x32\x6f\x80\xeb\xe8\x33\xd5\xb6\ +\x32\x18\x1e\xab\x30\xaa\xa3\x87\xfa\x02\x2b\x05\x88\xbe\xf1\x63\ +\xee\xf9\xe7\x3a\x64\x1d\xb9\x22\x2b\xc0\x06\xf0\x0c\xf5\x01\x8c\ +\x03\x7c\xd8\x04\xba\xe0\xba\x9e\xe0\x48\x31\x1e\xcd\x43\xbb\x86\ +\xae\xc2\xf9\x58\x3c\xdb\x70\x01\x3c\x85\xf6\x24\x1c\x2f\x60\x87\ +\xb4\x5d\xe0\x4c\xe7\x8c\xc1\x9d\xa1\x8b\xfa\x83\xe7\x29\xc7\x8b\ +\x25\x80\x06\xea\x3d\x2d\xe6\xb7\x7c\x02\xcd\x29\x70\xad\x6c\x5b\ +\x22\x84\xcb\xf7\x61\xae\x07\xb3\xaf\xcc\x47\x6f\x04\xb3\xaf\x60\ +\xf6\x52\x71\x5b\x47\xcd\xb5\x60\xae\x20\x16\x61\x07\x35\xdf\x2d\ +\xd4\xc2\x65\xc0\x12\xc0\x34\xaa\x3d\x0b\x94\x9a\x2c\xa3\x6e\xaa\ +\x01\xc7\x4d\xa8\x7c\x0f\xcc\x33\x7e\xec\x3d\x06\x88\x03\x16\xa0\ +\xf2\x9d\xce\x61\xc2\x73\xdb\x59\x72\x97\x40\x19\xdc\x31\xba\xb8\ +\x19\xb0\x04\x20\xa8\x69\xd9\x29\x20\x64\xc2\xb6\xf3\x32\x05\xa5\ +\x64\x22\x7f\x1c\xac\x60\xeb\xda\x10\x6e\xfb\x16\x94\x4a\x5e\xbf\ +\xc4\xc3\xae\x94\x36\xb1\x78\x3a\xd4\x23\x34\xda\x0a\x94\x07\x83\ +\x4c\xbf\x7d\x13\xd5\xb2\xe1\x2a\xcc\x82\x74\x81\x15\x98\xd9\x0f\ +\xfa\x5a\xc0\xbb\xc0\x13\xd2\x8c\x4e\x06\x92\xd4\x19\xa8\x4f\x61\ +\xe5\x05\xe7\xd0\x40\xe7\x07\xfd\x2d\xa0\x3b\x73\x03\xe4\x19\x03\ +\x3f\x23\xc1\x7f\xa6\x7d\x1c\x64\xd1\xb8\x63\xef\x0e\x27\x81\x59\ +\x0a\x31\x61\x35\x72\x49\x48\x99\x47\x83\x8d\x65\x4f\x64\x84\x9c\ +\x1e\x74\x66\xa1\x7e\x00\xc4\x41\xc6\x23\x4f\xd0\xd7\xc1\xe4\x2b\ +\x40\x1f\x3a\x67\x50\xdf\x05\x1c\x74\x6f\x41\x2d\xc9\x2f\x3e\xf3\ +\xdf\xce\xcf\xf9\x05\x9a\x2b\x0c\xe1\x15\x74\x66\xa0\x9e\x08\x2d\ +\x9c\xb7\x89\x2a\xbe\xbe\xee\x86\x54\x57\x25\x79\xcb\x4c\xc2\xc6\ +\x5a\x99\x45\xe0\x4b\x90\xaa\x27\xe0\x25\xb8\x43\x34\xd3\x73\x96\ +\x8f\xfc\xa4\x01\xf5\x32\xb8\xe7\x79\x54\x82\x67\x7e\x01\x38\x46\ +\x57\xec\x1b\x63\x77\xb5\xfd\xf8\x32\xba\xe2\x07\x9e\x8e\xff\x68\ +\x5f\x2e\x7a\x3b\xf1\xa6\xcf\x67\x7f\x43\x9a\x64\x1f\x15\x98\x17\ +\x9a\x6c\x02\x4f\xe0\xa4\x03\x8d\x29\xb2\xe1\xb1\xa9\x03\x4a\xa8\ +\x04\x6f\x83\xdb\x09\xec\xf7\x2d\x6c\xe5\x37\x0d\x47\x05\x69\x68\ +\xa5\x00\xcd\xf4\x6e\x01\x4f\x87\x87\xc4\xa9\x2f\x7f\x1f\x0d\x67\ +\x87\x05\x52\x27\x18\xbe\xbd\x5f\x08\x9f\xb9\x72\x27\xa8\xb7\xba\ +\x01\x8d\x03\xf4\x48\x65\xa0\x48\x09\x2e\xe5\xe3\x01\x28\x20\xbe\ +\x01\xf3\x47\x46\x7b\x02\x65\x25\xb4\xf2\x90\x9c\xb3\x94\x9b\x3a\ +\x51\x78\x9f\x61\xdf\x3f\x84\xb4\x14\x08\x20\x37\x4e\x7c\x6a\x7c\ +\xcd\xea\xb5\x04\xb0\x00\x58\xf6\xdf\xba\x84\x18\x07\x56\x18\x24\ +\x34\x0c\x8f\x31\x81\x9c\x93\xf3\x12\x2e\x8c\xd4\x7b\x06\x8a\x84\ +\x69\xd1\xfa\x0a\x43\x60\x05\x47\xe0\x5a\xe1\xec\x28\xc1\xf4\x07\ +\x3b\xa7\x30\x94\x36\x3c\x3c\xd7\x85\xea\xa8\x7c\xdb\x35\x72\x0d\ +\xee\x0c\x55\xe6\x19\x88\x05\x30\x41\x71\x54\x77\x13\x9b\x5e\x83\ +\x6e\x64\xde\x62\x21\x0c\xbd\xb1\xb9\xa9\x1f\x51\xf4\x5c\xae\x3d\ +\xb6\x02\xcb\x70\x65\x69\xf3\xc0\x3f\xc8\xb4\x97\xec\xf6\x14\x9a\ +\x50\x7b\x66\xd0\x21\x20\x8f\xd1\x24\x0b\xc0\xa3\x02\xfd\x32\x62\ +\x85\xbb\x7d\x8d\x34\x73\xd0\xc3\xce\xd6\x8e\x8a\x05\x7a\x15\x98\ +\xb8\xce\xf6\x4f\xec\x75\x11\xf4\x47\xf4\xbf\x26\xd4\x1c\xc5\x47\ +\x70\xac\x79\x23\x01\x94\x9f\xa1\xf6\x37\xc6\xd5\xb3\x11\x8e\xcc\ +\xf2\x1e\x90\x9a\xa4\x10\xd2\x6d\xff\xc8\x7f\x46\x58\x87\x42\x28\ +\x12\x40\x19\xdb\xb3\xcc\xcd\x11\xeb\x80\x2e\x51\xbc\x1c\x40\x11\ +\xb3\xc3\x08\xbf\xca\xcf\x11\x9f\xf9\x51\xd6\x61\x28\x14\x8d\x1f\ +\x5b\x39\xc6\x02\x48\x72\xe7\x39\x6d\x79\x03\x22\x12\xe8\x93\xde\ +\x27\x16\x29\x3c\x4b\x08\x32\x43\xea\xe9\xdd\x78\xee\x00\xc4\xe7\ +\x17\xb3\x60\x99\xc1\x23\x06\xb7\x38\x3f\x06\x3c\x07\x56\x46\x68\ +\x7b\x22\x21\x94\x50\xaf\xcd\xb8\x70\xc9\xc0\x98\xbe\x49\x12\x4e\ +\xe7\x05\x6a\x09\xc0\x01\xfb\xe4\x2f\x12\x8b\xa4\x7d\x00\x6d\x43\ +\x6f\x64\xe0\x25\xf0\x21\x23\x8b\x13\x9c\xa0\x61\xf8\x47\x0c\xbf\ +\x13\xc4\x67\x80\x8e\x8b\x10\x0d\x7e\x8a\x43\xad\xcd\x2e\x63\xe8\ +\x00\x00\xf1\x8e\xd0\x53\x15\x42\x7a\xb3\x73\x80\x79\x1b\xcb\x25\ +\x34\xaa\x43\x28\x4d\xee\xeb\xfe\x05\x6c\x6a\xde\xa0\x08\x64\x8e\ +\xc1\xe5\xcb\xa6\x45\xf0\x00\xe6\x26\x31\xd3\x6d\xed\x45\xd2\x88\ +\x55\x9a\x68\x6e\xe3\x91\xc7\x35\x32\x1f\x00\x9a\xe7\x9f\x04\x77\ +\x0e\xec\x28\x12\xd9\x40\xad\xc3\xbc\x8f\xbd\x43\x44\x4b\xc0\x19\ +\xc8\x3b\x44\x91\x16\x9a\x81\x59\x43\xa3\xba\x26\x70\x01\x17\x5b\ +\x5e\xc7\x58\x4e\xcf\x29\x1a\x19\x2e\xe9\x58\x1e\x00\xff\x06\x89\ +\x4d\x73\x92\xd9\x49\xf2\x01\xc9\xff\x24\x84\xee\x78\xfc\x7b\x7a\ +\xaf\x09\x3e\x83\x9d\xf3\x49\x62\x01\x74\x7c\xdb\x32\x7a\x1e\xd1\ +\x0b\x05\x8e\x3c\xbd\x02\xec\x67\xb7\xb1\xa0\xb9\x43\x59\xcf\xe6\ +\x10\xd3\x73\xf7\x4f\x70\xed\x60\x8e\x82\x3c\xa3\x05\x02\x9a\x38\ +\xd9\x8d\xe6\x5c\xd3\x60\x2d\x61\x3c\x09\x87\xc5\xa1\xbb\xfa\x38\ +\xdb\x0e\x0c\x0a\xb6\x32\xd9\xe9\xf8\x08\x84\x57\xd7\x16\xec\xa1\ +\xc1\x8d\x05\xcf\xc8\x14\x56\xe0\x6f\x65\x5f\xfb\x6e\x30\xb6\x0e\ +\x2b\x14\xe6\x24\x93\xc0\xcb\x84\xe4\x3a\x3e\xa3\x38\x8b\x94\xe0\ +\x85\x6d\x0a\x5d\x5f\x89\xb2\xea\x6d\xdc\x15\xd0\xf2\x67\x30\xc9\ +\xdb\xbf\x0e\xf3\x09\x04\x42\x68\xdd\x46\x13\x24\x56\x4e\xb2\x1c\ +\xd0\x18\xf7\x2d\xa3\xd6\x68\x2c\x25\xd8\x46\xed\xa5\x19\x3f\xfb\ +\x6d\x6e\x64\x5f\x01\x38\x83\xc6\x32\x9c\x9c\x8d\xe1\x25\x5e\x03\ +\x9c\x28\xce\x99\x15\x06\x65\x77\x31\x2c\x53\x7c\xbc\x92\x1a\x85\ +\x9c\x59\xb5\x04\x70\x86\x2a\x97\x72\x41\x86\x15\x38\xee\x90\xbb\ +\xf7\x4f\xb7\xfd\x57\xd0\x38\xd3\x73\xfa\x63\x81\xac\x2a\x4e\xbe\ +\xc2\xf4\x18\xa5\x01\xad\xae\x2d\x74\x99\x83\xb3\x2e\xca\x53\x4e\ +\x78\x45\xf9\x80\xc4\x66\xbe\x6d\x13\xd4\x3c\x54\x84\xc9\x31\xc9\ +\xb9\xb7\xa7\xe8\x96\x5b\x85\x4e\x41\xa1\xd3\x38\x70\x3e\xab\x38\ +\x92\xea\x4f\xd3\x6d\x9e\x04\x66\x61\x2e\x4e\xd6\x26\xb0\x02\x53\ +\xd3\x01\x4f\x19\x88\x05\x70\x41\x9a\x34\x70\xde\x74\xc9\xba\x8d\ +\xd7\xed\x2b\x72\x4a\xd8\xee\xed\x15\xb0\x07\xf5\x4b\x55\x5c\xb2\ +\x38\x9e\xaf\x2f\xce\x8f\x5d\x81\x49\x8f\x23\x3c\xf3\xa1\x10\x28\ +\x01\xab\x76\xfa\x0e\xd4\x34\x5f\x54\xc0\x7d\xeb\x1b\xea\x44\x56\ +\x20\x36\x83\xf1\x95\xd3\x27\x68\x39\x1a\xc0\x32\x5a\x27\xd4\x0f\ +\xc6\x5d\x02\xbf\x45\xaf\xc7\x97\x0d\x9d\x97\xa4\xa0\x4e\xd1\xf8\ +\xfc\x3d\x2f\x84\x61\x89\x0f\x21\xad\x35\xa0\x81\xba\xd1\x56\x4d\ +\xcf\x25\xf0\x7b\xe0\x53\x06\x97\xa3\x89\x19\x4c\xca\x6b\x27\xf5\ +\x66\x3b\x85\x12\xc3\xdd\x67\xd9\x42\x0b\x0f\xc2\xb6\x86\xf7\x08\ +\x37\xa2\xf6\xa4\x0e\x6f\xcd\x7f\x1b\x56\x43\x1a\xdc\xa8\x46\x30\ +\x7d\x7e\x05\xf3\x52\x45\xaa\x68\x09\xed\x1c\xc8\xbb\xb6\x4e\x90\ +\xf7\xf3\xd6\x4a\x3e\x64\x8c\x1a\xa1\x43\x90\x20\x23\xeb\x4e\xe0\ +\xa4\xab\xf5\x80\x29\xa2\xf0\x8a\xba\x0f\xee\x11\xea\x25\xbe\x06\ +\xb3\xe3\x82\xcc\xa0\x29\xfb\xef\xd1\xcc\xcf\x0e\x79\xc5\xb8\x81\ +\xa6\xe0\xc3\x0b\x9e\xe4\x6e\x22\x03\x96\x00\xba\x40\x95\x4c\x49\ +\xec\xcc\x0b\xa8\x4c\x7a\xc9\x16\x85\xb4\xfb\xd0\xaa\xaa\xce\xb8\ +\x56\x5d\xee\x98\x20\x65\xc5\xdd\xaa\x90\xaf\xfa\x08\x14\x63\x7b\ +\x11\xba\x1d\x32\x1a\x5f\x2a\xa8\x6e\xcb\xd5\x28\x58\xb1\x40\x09\ +\xdc\x9e\x6e\x79\x79\x16\x28\xa0\xa7\xa8\x46\xee\x01\xff\x0d\x98\ +\x0f\x24\x3f\x77\xe0\x05\x94\x84\xbf\xa1\x0b\x7c\x13\x48\xbc\xbf\ +\x55\x94\xd1\xa7\x30\x27\x51\xbf\x04\x39\xc6\xfb\xd0\x68\x91\xb9\ +\xbe\x93\x8a\xd2\xe3\x76\x40\xee\x1a\xcc\x66\xe0\x25\x69\x2e\xc0\ +\xed\xa2\x75\x36\xc9\xd6\x17\x54\xf1\x54\xc8\x66\x8d\x22\x1c\x4e\ +\x54\x80\xec\xa3\xb5\x3f\xf7\xc6\x08\x97\x0d\x68\xdd\x46\x9d\x9b\ +\x25\xe0\xb9\xee\xb0\x9c\x9d\x9f\x26\x5d\xd5\xe3\x26\xba\xea\x65\ +\x54\x79\x76\xd0\xda\xe6\x25\x65\x1e\xd0\xcb\xd8\x8c\x33\x14\xed\ +\x00\x77\x9a\x0d\x57\xdd\x1e\x5a\xc3\xbf\x81\x46\x66\x9f\xa3\x42\ +\x78\x00\xe7\x27\x50\x3d\x52\x22\x0b\xcd\x5b\x5f\xe7\x68\x24\x15\ +\x9b\x49\x1b\x80\x83\x0b\xbf\xbb\xaa\xc9\x0b\x14\x21\x1c\x7b\x66\ +\xbc\xa9\x33\x1d\xcb\x65\xc5\x2f\x4b\x1e\x6f\x12\x23\x7c\x00\x3c\ +\x04\x0e\xc0\xbd\x0c\xc6\x97\xe3\x7b\x46\xeb\x08\xc4\xcc\x74\x3d\ +\x21\x0f\xd1\x82\x45\xd0\x2b\xef\x65\xdf\xbe\x1f\xb4\x1b\x20\x62\ +\xf7\x8b\x83\xea\xa4\x67\xb0\x53\xe0\xc5\xad\x8f\xc0\x7d\x05\x4c\ +\xc1\xd1\xf7\xd9\xeb\x39\x71\x9e\xb6\xf8\xcc\x8f\x93\x42\x93\x3b\ +\x03\xe7\x27\x53\x2e\x5f\xcf\x5a\x07\xf0\x66\xe8\x7d\xec\x44\x49\ +\x32\xe6\xff\x50\x2e\x0f\xba\x00\xf2\xf3\xbc\xf9\x95\xa6\x5a\x8a\ +\x5c\xb9\xfc\x1d\xcc\xb2\x5e\x1b\xf9\xc7\xd8\x2f\x4c\xac\x92\x7b\ +\x61\x42\x1c\xfa\x82\x85\xf1\x02\x43\x3a\x66\x7b\xcc\x89\x43\x9c\ +\x05\xcf\x88\x43\xdf\x18\xf9\xa5\xd1\x57\xce\xfa\x2b\xa9\x10\xaa\ +\x8c\xff\xc2\x44\x8a\xe8\x4f\x05\x4e\xc8\x46\x5e\x08\x00\xf2\x1e\ +\xfa\xca\x4a\xee\xa5\x04\x5e\xeb\x95\x99\xb4\xad\xe4\x9d\x9f\xb7\ +\x40\xde\x31\x9c\x9f\xb2\xa5\xe5\x3d\xf3\x7f\xc8\xe3\x2b\x9e\x3c\ +\x91\x5a\x59\xa5\x16\x7b\x80\xe0\x77\x82\x71\x7d\x2d\x1b\x7e\x6b\ +\xde\xd3\x4f\x2b\x74\x9e\x2a\x8c\x7e\x69\x6a\xca\x8f\x09\x04\x2f\ +\x2b\x0c\x5e\xbe\x2a\x7a\x39\x6a\x1e\x33\x66\x91\x2d\xcf\x43\x29\ +\xbf\x9b\x15\x62\x44\x86\x93\x23\x9b\xa8\xb6\xf5\x35\xba\xb4\xfc\ +\xef\x1a\x6a\xe6\x1c\x7a\x01\x72\xc1\xe0\xb5\xb9\x19\x40\xa0\x37\ +\x0d\xe5\xc4\x29\x4a\x4a\x64\x7b\xc1\xff\xe4\xf6\x26\x79\x6d\x2e\ +\x28\x97\x4d\xe9\xeb\xfa\x71\x0e\x35\x61\xa7\xfe\xf7\x24\xaa\xc4\ +\x7d\x01\x06\x1d\x54\xa1\xce\x06\x78\xf6\x06\x4e\x93\xed\xc0\x8d\ +\xb8\xa2\x8e\x41\x26\x30\x4a\xcd\x3c\x9e\x3a\x79\x2d\x1b\xbf\x38\ +\x59\x42\xaf\xca\x92\x23\x54\x65\xe0\x5f\xe0\x99\x38\x24\x6b\xf3\ +\xac\x17\x27\x85\x41\xe2\x33\x06\xa3\xb4\x36\x7d\xac\x88\xc7\x37\ +\xf7\xd5\x59\xab\xe1\x0d\x80\x0c\xcf\x6f\x1a\xf3\x09\xa8\x10\xfe\ +\x07\xb4\x0a\xfd\x7e\xcf\x22\x5b\xc2\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x01\x23\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xd5\x49\x44\x41\x54\x78\x9c\xed\ +\xdb\x31\x11\xc2\x40\x00\x05\xd1\x0d\x22\xa2\x08\x05\x0c\x0e\xa0\ +\x41\x11\x0d\x12\x18\x14\xa0\x26\x15\x2e\x42\x41\xe8\x52\x67\x99\ +\x61\x5f\x75\xdd\xfd\xdb\xfe\x20\xc9\x3f\x1b\xac\x8b\xf7\xc7\xf3\ +\x61\x98\xb9\x02\xcc\x03\x97\xe7\xfd\xf6\x30\x76\xec\x8c\x4b\x01\ +\x96\xc7\x8f\xc0\xf8\x0d\x61\xd0\x02\xf0\x79\xfc\xda\x79\x53\x66\ +\x80\x9f\x50\x00\x7b\x80\xad\x00\xf6\x00\x5b\x01\xec\x01\xb6\x02\ +\xd8\x03\x6c\x05\xb0\x07\xd8\x0a\x60\x0f\xb0\x15\xc0\x1e\x60\x2b\ +\x80\x3d\xc0\x56\x00\x7b\x80\xad\x00\xf6\x00\x5b\x01\xec\x01\xb6\ +\x02\xd8\x03\x6c\x05\xb0\x07\xd8\x0a\x60\x0f\xb0\x15\xc0\x1e\x60\ +\x2b\x80\x3d\xc0\x56\x00\x7b\x80\xad\x00\xf6\x00\x5b\x01\xec\x01\ +\xb6\x02\xd8\x03\x6c\x05\xb0\x07\xd8\x0a\x60\x0f\xb0\x15\xc0\x1e\ +\x60\x2b\x80\x3d\xc0\x56\x00\x7b\x80\xcd\xfb\x34\x05\xaf\xb5\xf3\ +\xd6\xb4\x00\x33\x9c\x80\x09\x98\x96\x73\x92\x6c\xee\x0d\xbb\x93\ +\x11\x50\xe7\xe7\xb7\x79\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ +\x60\x82\ +\x00\x00\x00\x87\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x39\x49\x44\x41\x54\x58\x85\xed\ +\xcd\xa1\x15\x00\x10\x00\x00\xd1\x63\x29\x55\x31\x80\x45\x4d\xe0\ +\x3d\xd9\x52\x9e\xa4\x8a\x8a\xfb\xe9\xda\x81\x24\x49\xbf\x0b\x27\ +\x52\x5b\x03\xc8\x8f\xae\x7d\xd6\x58\x00\xe2\x93\xa1\x24\x49\xd2\ +\xc5\x06\x65\xbc\x05\x04\xc9\x39\x8e\xf8\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\xd0\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x82\x49\x44\x41\x54\x58\x85\xe5\ +\x97\x5d\x88\xd4\x65\x18\xc5\x7f\xe7\x9d\xf1\x2b\xa9\x34\x24\xac\ +\x5c\xab\x25\xfb\x58\x2a\x05\x75\x56\x89\x3e\x34\x51\xd2\x74\x77\ +\x6b\xdb\x88\x22\x41\x14\xa5\x8b\x2e\x82\x4a\x4b\xda\xa2\x32\xbb\ +\x09\xac\xd0\x8a\x20\x04\xaf\xcc\x76\x56\xcd\xed\x03\x0a\xbd\x08\ +\x9d\x5d\xcd\x36\x48\x8a\xc0\xd0\x56\xb7\x0c\x04\x25\xd3\x6c\xe6\ +\x3d\x5d\xcc\xec\x38\xe3\xce\xae\x3b\xd6\x9d\xe7\x66\xf8\x3f\xff\ +\xe7\x3d\xe7\xbc\x5f\xff\xe7\x19\xb8\xd4\xa1\x6a\x92\xa7\xb7\xbb\ +\x26\x91\xa3\xd1\xf2\x1c\x8b\x1a\xcc\x04\x41\x00\x8e\x20\x7a\x8c\ +\x76\x29\x47\x3a\xd3\xac\x9f\xff\x57\x03\x33\xd3\x4e\x45\x7b\x2d\ +\x30\x6b\x88\xa4\x5d\x39\x69\x55\x57\x93\xbe\xfa\x4f\x06\xa6\x6e\ +\xf6\x95\xc9\x64\xdc\x00\x7a\xac\x10\xea\xc5\xde\xee\x10\x3e\x53\ +\x8e\x83\xc3\x23\xbd\x7f\x27\x89\x8e\x8c\x97\xb8\x41\x8a\x73\x41\ +\x0d\xc0\xf5\x05\xf6\x0e\x82\x96\x64\x1a\xf4\x7b\xd5\x06\x66\x6e\ +\xf5\x4d\x31\xe7\x6d\xc0\x6d\x40\xaf\x50\xeb\xc8\xb1\x7c\xb4\x73\ +\x96\xb2\x83\x4e\xa9\xd5\x21\x35\x85\x47\x65\xbf\x06\xd4\x4a\x1c\ +\x8e\xd6\xa2\xce\x87\xd4\x3d\x64\x03\xd3\xb6\xb8\x36\x11\x9c\x01\ +\xc6\x01\x5b\x19\xa9\x27\x33\xf3\x75\x72\x50\xe1\xf3\xf0\x40\x87\ +\x47\x1c\x3f\x13\xd7\x83\x96\x60\x4e\x05\xeb\xee\xdd\xcd\xda\x7f\ +\x41\x03\xf5\x1d\xbe\x82\x33\xde\x0d\xd4\x81\xd7\x65\xba\xc3\x33\ +\xbc\xa2\x58\x8d\x78\x11\xb6\xea\xdb\x59\x89\xbd\x06\xe8\xc9\x5a\ +\xa9\x7d\x0f\xab\xb7\x34\x25\xd9\x6f\xd0\xdf\xf1\x5d\x50\x9d\xcd\ +\xf6\xce\xef\xfb\x8b\x4f\x6f\x77\x4d\x88\x71\x29\xd2\x7c\xcc\x44\ +\x20\x62\x0e\x81\x76\x64\xe1\xc3\x32\x01\xc9\x19\x7b\x6d\x2a\xed\ +\x5a\xa1\xa5\x49\x79\x13\xf6\x1c\x24\x57\x5c\x81\xd4\x16\x4f\x53\ +\x70\x97\xe1\x8f\x5c\x56\x93\xf6\xb5\xe8\x44\xf1\x65\xab\x43\xfd\ +\x14\x9e\xc7\x7e\x09\x18\x59\x79\xc6\x9c\x92\xf4\xc2\x9e\x26\xde\ +\x29\x15\xa9\xdb\xec\xe1\x97\x27\xdd\x0d\xdc\x4a\xd4\x82\x4c\xb3\ +\x3a\xfa\xde\x85\xd2\xf1\x4a\xf8\x0d\x80\x60\xbd\xda\x4f\x7c\x72\ +\xdc\x58\x58\xca\xca\xe2\xf9\xe9\x8c\x36\x5e\x37\x23\x1d\xd7\x63\ +\x17\x27\x77\xa0\x45\x67\x85\x5e\xcc\x2b\x7a\x6d\xe9\xbb\xa2\x81\ +\xa9\x9f\xf8\x1a\xcc\xfd\xc0\xf1\x93\x39\xde\x2f\xe5\xad\x9f\xcc\ +\x6a\xd0\x13\x98\x21\xc1\x68\x45\x7d\x3b\x4f\x97\xc6\xf6\x34\x91\ +\x06\x7e\x04\xee\x48\xa5\xb9\xb3\x9f\x81\x64\x60\x21\x20\xe4\x1d\ +\x07\x5a\x74\xb6\x2f\x3e\x6d\x8b\x6b\xc1\xab\x0b\x33\x1c\x3a\xa2\ +\x5f\xbf\x6b\xab\xaf\x2d\x3e\x4b\x96\xbd\x0d\x20\x38\x36\xf5\x33\ +\x80\xe3\x7d\xf9\x9f\xf0\x79\x29\x4f\x22\x11\x9f\x02\x86\x55\x21\ +\x5d\x10\x64\xf4\x3f\x91\x65\x65\x9e\x14\xbe\x00\xb0\x34\xbb\xbf\ +\x01\x54\x53\x18\xf8\x4b\x19\x91\xb5\xa0\x6a\xf1\xa2\x07\x3f\x58\ +\xfa\x1c\xc4\xc1\x3c\x27\x13\x2a\x18\xc8\x07\x83\x38\x77\x8d\xf2\ +\x87\xa5\xf6\x62\x0d\xd8\x85\x4f\x72\x01\x63\x47\x14\xb8\xc5\x75\ +\x7d\x07\x31\x54\x18\x77\x0e\x2f\xa3\x0b\xe6\x0c\x02\x41\xe2\x02\ +\xdc\x65\xe4\x47\x00\x1c\x19\x5f\x8c\xbc\xa2\x68\x38\x74\xb1\x06\ +\x80\xc3\xa5\x0f\x27\x4e\x17\xb9\x8f\xf6\x7d\xe0\x4a\x0c\xf8\x57\ +\x00\x07\x6e\x2c\xa3\x90\x3b\xb8\x48\x88\xf2\xb1\xb9\x73\xdb\xd9\ +\xd3\x17\x2b\x1a\xb0\xc3\x4e\x80\xe0\x38\xaf\x8c\x44\xe1\x3d\xe0\ +\x62\x6a\xc1\xd9\x98\x0c\x1f\x96\x3b\x8a\x73\x0b\x6a\x5f\xf7\x33\ +\x30\x2c\xc9\x76\x00\xa3\x05\x53\xdf\x77\xf1\xda\x65\x1a\x75\x00\ +\xf9\xed\x6a\xd5\x2d\xad\xe9\x5c\xa4\x73\x37\xca\x16\x68\x11\x40\ +\x54\x48\xf7\x33\xf0\x4d\x83\x8e\x02\x5f\x03\xe3\x86\x5d\xcd\xd2\ +\x52\xb2\xec\xb1\xf0\x1c\xa2\x8a\xad\xf0\xc7\x9d\xdf\xf1\x6a\x69\ +\x64\x46\x1b\x0b\x81\x3a\xe0\x87\xae\x46\x8a\xbd\x41\xd9\x09\x8f\ +\xd6\xca\xbc\x59\xb7\xd6\x77\xf8\x8a\xbe\xf8\xbe\xe5\xfa\x27\x7b\ +\x4c\x8d\xe0\x75\x0c\xbe\x1d\x59\xe1\x35\x13\xb3\xe1\xb1\xd2\x2a\ +\x5a\xb7\xd9\xc3\xad\x7c\x9d\x51\xd0\xaa\x01\xab\x21\x40\xaa\x2d\ +\xb7\x49\xe8\x71\x60\x6b\xa6\x5b\x0f\x9d\x5f\x8e\xa7\xb5\xf9\xf6\ +\x04\x71\x05\xd6\x7c\xc4\x44\xc0\x86\x43\xc2\x9f\xe6\x12\x61\xc3\ +\xde\x06\xfd\x54\xbe\x18\x56\x7d\x3a\x6e\x00\x2d\x07\x76\x66\x9a\ +\x34\x7b\x50\x03\xf9\x3e\xd0\x7b\x80\x5b\x8d\xdf\xea\xec\x0e\xcf\ +\x0e\xd4\x90\x3c\xb2\xd9\x09\x80\x8f\x5b\x94\xab\xb8\x1e\xb6\x52\ +\xed\x3c\x2b\xfb\x4d\xe0\x68\x32\xa1\xe9\x85\xad\x2e\xa2\x62\x79\ +\x29\xf4\x83\x19\xe0\x2a\xa0\x6d\x54\x56\x8b\x77\xb6\xe8\xcf\x8a\ +\x22\x03\x20\xdf\x03\xc4\x77\x41\xcb\x80\xbf\x1c\x75\x6f\x67\xb3\ +\xf6\x9e\x9f\x37\x60\x7d\x4b\xb5\xf9\x66\xe1\x6d\xc0\x2d\xc0\x11\ +\x4b\xad\x97\x8d\x61\xe3\x50\x9a\xd2\x19\x53\x68\x76\xbe\x29\x9d\ +\x04\xf4\xc8\x6a\xd8\xf3\xb0\xbe\xad\x94\x3e\x68\x81\x9d\x92\xf6\ +\x98\x11\x8e\x1f\x80\x1e\x29\x84\x7a\x6c\x6f\x0f\x89\xf0\x59\x2e\ +\xcb\xc1\x64\xa4\xf7\xf4\x30\xe2\xa8\x1c\xe3\x73\x70\x7d\x08\x71\ +\x9e\xf3\x6d\x79\xdf\x07\xe7\xcb\x98\xd5\xe2\xae\x16\xfd\x36\x90\ +\xc6\x90\x2a\x7c\xaa\xcd\x33\x85\xd7\x02\xf7\x0c\x25\xdf\x62\xbf\ +\xd0\xca\x4c\x93\xbe\xbc\x50\x6e\x55\x7f\xcd\x66\xa4\x7d\x83\x23\ +\x8d\xc8\x73\x80\x1a\xf2\x15\x34\x01\xf4\x20\x7a\x40\xbb\x42\x8e\ +\xf4\xee\x66\xfd\x58\x0d\xef\xa5\x8d\x7f\x01\x53\xeb\xdb\x78\xb8\ +\xf8\xe0\x36\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x8c\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3e\x49\x44\x41\x54\x58\x85\xed\ +\xd3\xb1\x11\x00\x10\x00\x04\xc1\xa3\x32\x89\x0a\xb4\xa0\x2c\x2d\ +\x68\xc0\x98\xd1\x9a\x48\x2a\x24\xb9\x8d\x3e\xbb\xe8\x41\x92\xf4\ +\x59\x38\x23\x97\xba\x80\xf4\x28\x3a\x47\x6f\x19\x20\xbe\x08\x4a\ +\x37\xbe\x40\x92\xa4\xef\x36\xf1\x29\x0a\x07\x7b\xbe\x69\xcc\x00\ +\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x0a\x8e\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x0a\x40\x49\x44\x41\x54\x78\x9c\xed\ +\x5b\x7d\x8c\x1c\x65\x19\xff\x3d\xb3\xb7\xd7\xbb\x72\xd7\x03\x29\ +\x07\xf5\x76\x76\x76\xaf\x3d\x02\xa1\x25\x2a\x05\x81\xd4\x13\x50\ +\x03\x12\x28\x20\x24\xf2\x11\xa4\x02\x22\xa0\x88\xf2\x65\xd0\x00\ +\x15\x21\xf2\x21\x85\x90\xd4\x02\xb1\x0d\x50\x1a\x31\x28\x10\x31\ +\x7c\x34\xa1\x94\x54\x85\x40\x2d\x88\x8b\x94\x5c\xbd\xdd\xf9\xd8\ +\xeb\x51\xca\x47\x3f\xb4\xd7\xdd\xd9\xf7\xe7\x1f\x77\x6d\x67\x66\ +\x67\x67\x76\xef\xf6\x2e\x46\xfb\xfb\x6f\x9e\xf7\xf7\x7c\xcc\x33\ +\xef\xce\xbc\xef\xf3\xbc\x0b\xec\xc7\x7e\xec\xc7\xff\x33\x64\x2a\ +\x9c\x0c\x6c\xde\x7c\x48\x72\xb7\xdb\x4f\xc1\x3c\x0d\x72\x84\x02\ +\x7b\x01\x1c\x28\x90\x19\x00\x13\x00\xb6\x03\xd8\x4e\x88\x05\xf0\ +\x3d\x0d\xf2\x0f\xd2\x5d\x97\xc9\x64\xf2\x93\x1d\xdb\xa4\x25\xc0\ +\xb2\xac\xd9\x0a\xda\x22\x28\x2e\x84\xe0\xe8\x71\x9a\xc9\x83\xf2\ +\x82\xa6\xa9\x47\x75\x5d\x5f\x2f\x22\x6c\x6a\x90\x68\x72\x02\x48\ +\x4a\xc1\x71\x4e\x15\x85\x9b\x00\x9c\xdc\x4c\xdb\x00\x72\x14\x2e\ +\xf9\x68\xcb\x96\x27\xe6\xcf\x9f\x5f\x6e\x96\xd1\xa6\x25\xa0\x50\ +\x70\x4e\x86\xf0\x1e\x00\xf3\x9b\x65\x33\x1c\x52\x20\xb0\x38\x93\ +\xee\x79\xbc\x19\x33\x62\xc2\x09\x18\x1c\x1c\x3c\x54\x4b\x24\xef\ +\x03\x70\x51\x04\x4d\x11\xf8\xb3\x88\xac\x85\xe2\x46\x26\xf0\xcf\ +\x16\xe0\x63\xd7\x75\x77\xb8\x6d\x6d\x95\xd6\x52\xa9\x93\x6c\xe9\ +\x02\x54\x96\x82\xc3\x01\x39\x41\xc0\xaf\x01\x68\xaf\x65\x90\xc0\ +\x3a\x0d\xea\x2a\xc3\x30\xde\x9d\x48\xfc\x13\x4a\xc0\xa0\x6d\x1f\ +\xa7\x29\x3c\x0b\x60\x56\xc8\xf0\x0e\x81\x3c\x4f\xf2\xb9\x96\x16\ +\x79\x31\x95\x4a\x7d\xd4\x88\x6d\xdb\xb6\xdb\x2b\x15\x39\x45\x44\ +\x9d\x49\xc8\xc2\x1a\x3e\x46\x28\xbc\x34\x9b\x4e\xff\x66\x3c\xf1\ +\x03\x13\x48\x40\xa1\x60\x5f\x08\xc1\x0a\x00\xd3\xaa\x82\x02\x1e\ +\xd4\xa0\xee\x32\x0c\xe3\x93\xf1\xda\xf7\x22\x97\xcb\xb5\x76\x74\ +\xcc\xf8\x0e\x44\x6e\x05\xd0\x5d\x45\xa0\xdc\x69\x18\x3d\xb7\x8a\ +\x88\x6a\xd4\x76\xc3\x09\x20\xa9\x59\x96\x7d\x07\x21\x37\x07\x86\ +\x14\x80\x15\x2d\x09\xf9\x59\x2a\x95\x72\x1a\xb5\x5b\x0f\x36\x6e\ +\xfc\xb0\xb3\xbd\x7d\xe4\x3a\x02\x37\x00\xe8\xf0\x07\x86\x67\xa7\ +\x4f\x9f\x76\x71\x77\x77\xf7\xce\x46\x6c\x36\x94\x00\x92\x9a\x69\ +\x16\x57\x41\x78\x7e\x60\x68\x48\x69\x38\xa7\x57\xd7\xdf\x68\xc4\ +\xde\x78\xe1\x38\x4e\xca\xad\xf0\x19\x54\xbf\x70\xdf\x2a\x97\x46\ +\x4e\xea\xeb\xeb\xdb\x5e\xaf\x2d\xad\x11\xc7\xa6\x5d\x5c\x5c\x75\ +\xf3\x82\xd7\xc1\xca\xfc\xa9\xba\x79\x00\x48\xa5\x52\x4e\x42\x43\ +\x3f\x80\x55\x81\xa1\xcf\x27\x5b\xdb\x56\x91\x4c\xd4\x6b\xab\xee\ +\x19\x90\xb7\xac\x6f\x0a\xe5\x49\xbf\x32\x1f\x53\xaa\x72\x65\x36\ +\x9b\x1d\xa9\xd7\x4e\x33\x41\x52\x2c\xcb\xb9\x91\xc0\x5d\xf0\xdc\ +\x0b\x81\x7b\xb2\x86\xfe\xe3\x7a\x6c\xd4\x95\x00\xcb\xb2\xe6\x2b\ +\xca\x3a\x00\x6d\x1e\xf1\x13\x46\x3a\xf5\xad\xc9\x58\x9d\x35\x8a\ +\xbc\xe9\xfc\x50\xc0\xfb\xbd\x32\x81\x5c\x62\x18\xa9\xc7\xe3\x74\ +\x63\x13\xe0\x38\xce\xc1\x6e\x85\x7f\x03\xd0\xe3\x51\x7a\x43\x29\ +\xf7\xcb\x8d\x3e\xf9\x42\xa1\x70\x24\xb4\x96\x73\x84\x38\x9a\x50\ +\x29\x40\x52\x00\x2a\x02\x38\x14\x38\x50\xdc\x00\xa8\xa7\x1b\xdd\ +\x03\x90\x14\xd3\x2c\x2e\x87\xf0\xdb\x1e\x71\x09\x4c\x9c\x90\xc9\ +\x7c\x76\x43\x94\x6e\x6c\x02\x0a\x96\xbd\x1c\xc4\xa5\x1e\xd1\x90\ +\x26\x3c\x36\x9d\x4e\x0f\xd5\x13\x5c\x2e\x97\x6b\xed\xec\xec\xba\ +\x8a\xc0\x95\x00\x8e\xa8\x47\x07\xc0\x5b\x14\x3e\x98\xd1\xf5\x95\ +\x22\x52\xa9\x47\x61\x60\x60\x60\x5a\xb2\xb5\x6d\x0d\x80\x13\xf7\ +\x49\xb9\xc1\x48\xeb\x5f\x14\x11\xb7\x96\x5e\x64\x02\x4c\xd3\x5c\ +\x40\x68\xeb\x3c\x22\x52\xc9\x89\xd9\x6c\xea\xf5\x7a\x82\xca\x5b\ +\xd6\xd9\x42\xb9\x17\xc0\x9c\x7a\xf8\x21\x78\x1b\x94\xeb\x33\x99\ +\xd4\x9a\x7a\xc8\x63\xab\xd2\x1c\x80\x99\x7b\x64\x02\x5c\x6b\x18\ +\xfa\x83\xb5\x74\x6a\x7e\x05\x48\x0a\x91\xf8\x45\x40\xbc\xaa\x9e\ +\x9b\x5f\xbf\x7e\x7d\xb2\x50\x70\x96\x0a\xe5\x19\x8c\xff\xe6\x01\ +\xe0\x73\x10\xbe\x9c\x37\xed\xc5\x24\x63\xbf\x58\xbd\xbd\xbd\x1f\ +\x10\x72\xa7\x57\x46\xe0\x96\xe1\xe1\xe1\x03\x6a\xe9\xd4\x34\x5a\ +\x70\x9c\x7e\x80\x0b\x3c\xa2\xb2\x40\xdd\x16\x17\x84\x69\x9a\x07\ +\xcd\x3c\xe4\xd0\x17\x20\xbc\x3a\x8e\x5b\x2f\x04\xb8\xcd\xb4\x9c\ +\xdf\x16\x8b\xc5\xe9\xb1\x64\x55\x7e\x08\x02\xcb\x23\x99\x39\x52\ +\x2a\x7d\xb7\x16\xbd\x66\x02\x44\xe1\xc6\x40\x14\x0f\x1b\x86\x31\ +\x18\xe5\x3b\x97\xcb\xb5\x02\xda\xb3\x00\xbe\x12\x1b\x68\xe3\x38\ +\xaf\xec\xaa\xc7\xe3\x66\x42\x36\x9b\x1d\x21\xe8\x7f\x50\x94\xeb\ +\x6a\xad\x0d\x42\x8d\xe5\xf3\xf9\xc3\x00\x9c\xe6\x11\x95\x95\x5b\ +\xbe\x23\xca\x31\x49\xe9\xe8\xec\x5a\x4a\xa0\x3f\x8a\x37\x41\x9c\ +\x5b\xb0\x9c\xd8\x59\x98\xd1\xf5\x95\x04\x06\x3c\xa2\x9e\x82\x6d\ +\x7f\x35\x8c\x1b\x9a\x00\x49\x24\x2e\x04\xb0\x37\x63\x02\xac\xe9\ +\xed\xed\xfd\x20\xca\xa9\x65\x39\x17\x01\xb8\x3c\x2e\xb8\x89\x42\ +\x80\x5b\x4d\xb3\x18\x7a\x33\x7b\x39\x22\x15\x21\x9f\xf2\xc9\x94\ +\x5c\x12\xc6\xad\x31\x9d\xe4\x4c\xef\x15\x85\x7f\x88\x72\x58\x2c\ +\x16\xa7\x8f\xad\xc6\xa6\x04\x0a\x6a\x49\xdc\x72\x97\x09\xf1\xc7\ +\x2c\x38\x3d\x4c\xa7\x2a\x01\xc3\xc3\xc3\x07\x80\xde\x6f\x29\x50\ +\x29\x27\xfe\x18\xe5\xac\x5c\xae\x5c\x07\xcf\x42\x69\xb2\x21\xc0\ +\x3c\xd3\x74\x16\x45\x71\x32\xa9\xd4\x9b\x80\x78\x67\x6d\x57\xde\ +\x71\x8e\x09\xf2\xaa\x12\xb0\x7b\xb7\x7b\x3c\x80\x56\x8f\xe8\xed\ +\xd9\xb3\x7b\xac\x20\x6f\x0f\x46\xb3\x2a\x3f\x88\x0f\xbb\xb9\xa0\ +\xe0\xda\xa8\x71\x11\x51\x10\xfa\x1e\x5c\x42\x55\xd7\x29\x43\x7e\ +\x02\x9c\x1b\x10\xac\xab\xe6\xec\x43\xa1\xe0\x7c\x09\x82\x43\xa2\ +\x38\x93\x01\x01\xe6\xd9\xb6\xdd\x17\xc5\xe1\xe8\xfe\x65\xdf\x35\ +\x70\x54\x90\x13\x96\x80\x23\x03\x8e\x06\xaa\x39\x9e\xf1\x04\xce\ +\x0b\xe8\x47\xd1\x9b\x0a\x57\xe1\xdc\xa8\x71\xa1\x04\x63\x3f\x32\ +\xc8\x09\x49\x80\x64\xbc\x57\xa4\x44\x7e\xfb\xa1\x82\x45\x89\x29\ +\xe9\xb5\xec\xf1\x54\xf5\x9b\xf6\x82\x2c\x05\x63\xcf\x06\x39\x55\ +\x09\x20\xd0\xe9\x73\x22\xf2\x69\x4c\x14\x53\xf6\xf2\x0b\xf1\x9d\ +\x8a\x61\x04\x63\xef\x0c\x12\x62\x13\x50\xa9\xb0\x66\x8d\x6d\x6c\ +\x55\x16\x56\xad\x9d\x1a\x30\x3a\x01\x99\x4c\x66\x37\x00\xef\x4e\ +\xb0\x75\x74\xb5\xba\x0f\x55\x09\x90\xe0\x1c\x4e\x32\xea\x47\xad\ +\x85\xd9\x98\x3a\x48\x72\xa2\x16\xc2\x82\xdf\xe1\xbd\x48\x28\xad\ +\x6a\xda\xec\x75\x3f\xba\xcf\x8e\x5c\x21\x4e\x2e\x18\x59\x7d\x2e\ +\x14\x0a\xd3\x00\xb4\x78\x44\xa5\xb9\x73\xe7\x96\xbc\x9c\xb0\x19\ +\xe0\xab\xa8\x92\x3c\x30\x26\x8a\x62\xcc\xf8\xa4\x41\x80\xc8\x04\ +\x90\xec\x0a\x88\x76\x04\x39\x55\x09\x50\x80\x19\x30\x53\xf5\xe6\ +\xf4\x07\xc1\x5c\xd4\xf8\x64\x82\x94\x48\xdf\x9a\xd6\xda\x1b\x10\ +\x15\xaa\x38\xd5\x6a\xf2\x9e\xcf\x89\x20\x72\xb1\x21\x82\xa7\xa3\ +\xc6\x27\x17\x5a\xa4\x6f\xa9\x8e\x7d\x63\x95\x85\x6a\x41\xc5\xd7\ +\x6c\x14\x7f\x51\xa4\x0a\x95\x4a\x65\x35\x80\x86\xba\x31\x4d\x82\ +\x69\x18\xb3\xde\x8a\x22\x30\x10\x3b\x81\xaa\x19\x53\x95\x80\xf6\ +\xf6\xf6\xd7\x00\x78\xfa\xef\xf2\x05\xc7\x71\x6a\x7e\x6e\xb2\xd9\ +\xec\x08\x04\x8f\xc6\xc7\xdb\x64\x88\x3c\x12\x55\x92\x1f\xfb\x44\ +\x9f\xe1\x13\x2a\x59\x1b\xe4\x55\x25\xa0\xbb\xbb\x7b\xa7\x00\xaf\ +\x79\x65\x65\x15\x30\x14\x40\x39\xd9\x72\x3b\x80\x6d\xd1\x11\x37\ +\x0f\x02\xd8\x09\xf1\xf7\x01\x82\xb0\x6d\xfb\x18\xf8\xd7\x28\xdb\ +\x33\x99\x9e\xf5\x41\x5e\xe8\x37\x9c\x84\x6f\x17\x25\xe0\xc2\x28\ +\x67\x7d\xb3\x66\x7d\x08\x32\xb2\x62\xd4\x64\xfc\x44\xd7\xf5\x5d\ +\x51\x04\x05\xcd\x17\x33\xc1\x17\xc3\xca\xe3\xa1\x09\xd0\x34\xae\ +\xc2\x68\xb7\x77\x8f\xf6\x29\x03\x9b\x37\x47\xee\xf8\x0c\x43\x7f\ +\x40\x80\x97\xa2\x38\x8d\x23\x74\x86\xaf\x4c\xa7\x53\xc1\x9e\xa0\ +\x5f\x8b\xd4\x40\xfa\x36\x69\x42\x79\x2c\x8c\x1b\x9a\x80\x74\x3a\ +\x3d\x04\x62\xb5\x47\x34\x2d\xb9\xbb\x1c\x6c\x87\xfb\x20\x22\xae\ +\x52\xee\xf9\x00\xde\x8f\xe2\x35\x06\x09\x5e\xbe\x4e\xe5\x5e\x11\ +\xd7\x8e\x33\x4d\xe7\x02\xf8\x9b\x30\xc3\x86\x91\x5a\x1d\xc6\xad\ +\x5d\x15\x16\xf9\x65\x40\xf0\xbd\xc1\xc1\x21\x23\xca\x71\x36\x9b\ +\xfd\x54\xa0\x4e\x47\x53\x93\xb0\x17\xeb\x95\x5b\x3e\x3b\xae\x1d\ +\x97\xcb\xe5\x5a\x21\xf8\xb9\x57\x26\xc0\xfd\xb5\xba\x43\x35\x13\ +\x90\x4e\xf7\xac\x81\xff\x65\xd8\x9a\x48\xa8\xc5\x71\x51\x1a\x86\ +\x31\x48\xe5\x1e\x2f\x40\x68\xc6\xc7\x05\xca\x93\x09\x0d\xfd\x71\ +\x85\x59\x00\xe8\xe8\xe8\xba\x02\xfe\x6d\xef\xc7\xbb\x76\xb5\x2d\ +\xab\xc5\x8f\xdc\xbc\xe7\xf3\xf6\x49\xa2\xe1\x15\x8f\x48\x09\xd4\ +\x71\x86\x61\xfc\x35\x36\x66\xb2\xc5\xb2\x9c\xeb\x09\xfc\x14\x21\ +\xdb\xd0\x3a\xb1\x95\x22\xb7\x64\xf4\x9e\x87\xeb\xe9\x42\x17\x8b\ +\xc5\x99\x65\x57\xbd\x0b\xef\x31\x1a\xf2\x86\x4c\x26\x7d\x5f\x2d\ +\x9d\x98\x26\x83\xbe\x16\xc0\x4a\x3f\x5f\x7b\x66\x70\x70\xf0\xd0\ +\xb8\x60\x44\xc4\x35\x0c\xfd\x6e\xb7\x9c\x9c\x03\xca\x32\x00\xff\ +\x8e\xd3\xf1\x60\x9b\x00\x77\x55\xdc\xd2\x9c\x6c\x3a\xf5\x50\x3d\ +\x37\x9f\xcb\xe5\x5a\xcb\x65\xf5\x3b\xf8\x6e\x1e\xef\x6c\xdd\xba\ +\xa5\x66\x5f\x10\xa8\xa3\x7c\xb3\x69\xd3\x70\x77\x4b\xd2\x7d\x07\ +\xa0\xf7\xa6\xff\x52\x2e\x8d\x9c\xd2\xd7\xd7\xb7\x3b\x4e\x7f\x0f\ +\x8a\xc5\xe2\xf4\x72\x59\x9d\x06\x0d\xe7\x92\x98\x27\xa3\x55\xe4\ +\xcf\x8c\x05\xfa\x21\x34\x0c\x41\xc9\x06\x80\x4f\xed\xdc\xb9\xed\ +\xe5\xe0\xae\x2d\x0e\xa6\x69\x2d\x23\xe4\x4a\x8f\xa8\xac\x34\x2c\ +\x88\x3b\xb9\x52\x57\xfd\x2a\x9f\x77\x8e\x17\x8d\x6b\xe1\x3d\x11\ +\x26\x58\x61\xe8\xa9\xcb\x27\x72\x40\xc2\xb6\xed\xf6\x91\x91\x11\ +\xd5\x48\x22\xc3\x50\xb0\xac\xab\x41\x59\xea\x13\x12\x97\x67\x32\ +\xfa\xf2\x38\xdd\xba\x0b\x78\xa6\xe9\x5c\x4c\xd0\x77\xe2\x82\xc0\ +\x23\xff\xda\xb1\xed\x9a\x46\x9f\x56\xb3\x30\x76\x44\xe6\x1a\x02\ +\xf7\xc3\xf3\x73\x16\xf0\x01\xc3\x48\xff\xa8\x1e\x1b\x0d\x55\x30\ +\xf3\xa6\x7d\xb7\x00\x37\xf9\xa3\xc0\xab\xc9\xa4\x76\x5e\x4f\x4f\ +\xcf\xd6\x46\x6c\x4d\x14\xb9\x5c\xae\xb5\x63\x46\xd7\xaf\x40\x5c\ +\xe6\x95\x0b\xf0\x52\x3a\x9d\x3a\x23\xea\x50\x44\x80\x5f\x3f\x48\ +\x26\x4c\xdb\x79\x0a\xc4\x39\x01\x33\x85\x84\xc6\x85\xba\xae\xff\ +\xbd\x11\x7b\xe3\xc5\xd8\x7b\xe9\xf7\xa8\xde\xa9\xbe\x4b\xe5\x2e\ +\xc8\x66\xb3\xd1\x85\x5c\x0f\xc6\x73\x50\x32\x61\x9a\xf6\xbd\x10\ +\x09\x4e\xb1\x32\x81\x65\x95\x72\xf2\xce\x39\x73\x0e\xdb\xd2\xa8\ +\xdd\x7a\x30\x7a\x7c\x16\xdf\x87\xe0\x66\x00\x07\xf9\x06\x05\x2f\ +\x54\xca\xa5\x0b\x66\xcf\x9e\xdd\xd0\xa6\x6c\x22\x47\x65\x2f\x83\ +\x60\x19\x80\x60\x61\x72\x27\x81\xfb\xdc\xd2\xc8\x92\x46\x0e\x2c\ +\x46\x81\x64\x8b\x69\x3a\x8b\x20\x58\x8c\xb0\x1e\x24\x65\x89\x61\ +\xf4\xdc\x54\xef\x79\x22\x2f\x26\x76\x58\xda\xb2\xfa\x35\xca\xd3\ +\x00\x0e\x0e\x19\xfe\x84\xe0\x73\x1a\xb4\xe7\x4a\xa5\x5d\xab\x1b\ +\x4d\xc6\xe8\xe1\xaa\x83\xfa\x15\xd4\x99\x02\x9c\x05\x20\x6c\x19\ +\x5e\x06\x71\x55\x3d\x6f\xfb\x5a\x98\x70\x1b\x67\x53\xb1\xa8\xb7\ +\x54\xd4\x03\x20\xbe\x11\x41\x2b\x03\x7c\x15\xa2\xbd\x02\xc5\xf7\ +\x95\x92\x4d\x6a\x9a\x7c\x9c\x74\xdd\x9d\xa5\x52\xa9\xd2\xd6\xd6\ +\xd6\xa9\x94\xea\x22\x13\x59\x6a\x38\x1c\x54\x27\x08\xe4\x54\x00\ +\x33\x6a\x19\x24\xf0\xe6\xd8\x71\xf9\xd8\x55\x69\x14\x9a\xf8\x87\ +\x09\xfb\xeb\x14\xdc\x2d\xc0\xbc\x66\xd9\xac\x81\x21\x42\x6e\xcf\ +\xa4\x7b\x7e\x3d\x9e\x29\x1f\x44\xb3\xff\x32\xa3\x99\xa6\x73\x16\ +\x05\x37\x0b\x70\x6c\x33\x6d\x03\x18\x04\xb9\x84\xac\x2c\x6f\xe6\ +\xd1\xdc\x49\xeb\x64\x9a\xa6\x79\x14\x45\x5b\x04\x85\x85\x10\x1c\ +\x3e\x4e\x33\xc3\x10\x3c\xaf\xc0\xc7\xb2\xba\xfe\xa7\xf1\xfc\x1f\ +\x20\x0e\x53\xd2\xca\xdd\x54\x2c\xea\x49\x97\x27\x2b\xf0\x28\x40\ +\x8e\x00\x98\x15\x41\x17\x88\x19\x18\xed\xdc\x6c\x03\xb8\x5d\x20\ +\xb6\x02\x36\x42\xb8\x51\x23\x5f\x4d\xa7\xd3\xef\xfd\x37\x9c\x45\ +\xde\x8f\xfd\xd8\x8f\xff\x5d\xfc\x07\xbb\x1b\xfe\xd4\xc4\x32\xd9\ +\x11\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x3e\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xf0\x49\x44\x41\x54\x58\x85\xed\ +\xd6\x3f\x68\x13\x61\x18\xc7\xf1\xef\xf3\x5e\x62\xa5\x82\x8a\x1d\ +\x14\x5d\x44\x9c\x1c\xfc\x13\xcc\xe0\xe0\x28\x5d\xea\x24\xc1\x45\ +\xd1\x45\xd2\xda\x34\x05\xc1\x51\x4a\x70\x74\x50\x92\x5a\x6b\x40\ +\x10\x75\x10\x8b\x5b\x10\xc5\xd1\xa1\xa0\x6d\xc4\xc5\xc9\xa1\x93\ +\x28\x48\x4b\x87\x8a\x35\xc9\xfd\x1c\xee\xb2\x38\xdd\x5d\x8e\xcb\ +\xa0\x0f\xdc\x76\xcf\xfb\xfb\xf0\xdc\xfb\xde\x1d\xfc\xeb\x65\x51\ +\x6e\x3a\x5d\xae\x6f\x80\x59\xbe\xdb\x39\xb2\xfc\xe8\xc6\x7a\x9a\ +\x00\x17\xf1\xbe\xbd\xa0\x3d\x9d\x5c\xae\x75\xfc\xf2\x9d\x5d\xc3\ +\x00\xf4\xeb\xcc\xc8\xe8\xc8\xcb\x63\xa5\xb9\x1d\xc3\x02\x20\x18\ +\x1f\xdd\x37\xf6\xa4\x54\x7a\xe1\x65\x0e\x10\xf8\x60\x02\x2e\xae\ +\x8d\x7d\x6b\x80\x22\xed\xa1\xd4\x00\x06\x12\xbe\x00\x24\xa6\x8a\ +\x93\xf5\x5a\xa6\x80\x00\x61\x92\xe1\x07\x08\xbb\x55\x2c\x37\x66\ +\x33\x05\x00\x98\x90\x50\x80\x40\xf7\x8a\xe5\xc6\xa5\x4c\x01\xf0\ +\xd7\x24\xd0\xe3\xc2\xe4\xfc\x44\xa6\x00\x08\x26\x81\x10\xe0\x39\ +\xf9\x4b\x85\xa9\xfa\xd9\x4c\x01\x81\x02\x3f\x44\xec\x74\x3e\xad\ +\xe2\xb5\xbb\x27\xb3\x05\x84\x08\xc9\x04\xec\x96\xf3\x5e\x17\xae\ +\xdf\x3f\x9a\x2d\x00\x30\x53\xff\x1d\xb1\xdf\x7a\xbd\xb7\xa7\x2a\ +\x8d\x83\x99\x02\x82\x0a\x4e\x86\xc1\x61\xd7\xd1\xab\x21\x00\x00\ +\x44\x88\x38\x31\x04\x80\x39\x30\x04\x6b\xbd\xbc\x1d\x8a\xd2\x91\ +\x4b\x2b\x5a\xe0\x2c\xf8\x36\x7c\x97\xe7\x9d\xfb\x38\x3f\xfd\x35\ +\x4a\x5f\x5a\x13\x70\x16\xfc\xdc\x6c\x3a\x18\x6f\x2f\x4c\x7f\x89\ +\xdc\x98\x46\x38\x41\xf8\x2f\xdf\x71\xfe\xfd\xc3\xea\xa7\x38\xcd\ +\x83\x3e\x02\x0b\xaf\x9e\x6f\xae\xd4\x7e\x50\x79\x17\x77\x81\xc4\ +\x13\x90\xc9\xfa\xfd\x86\x5d\x6d\x2f\x56\x5a\x49\xd6\x49\x3a\x01\ +\x33\x99\x03\x90\x98\x5d\x69\xce\x3c\x4b\xb8\x4e\x92\x09\xc8\x40\ +\x2e\x54\xdc\x5e\x6d\x56\xeb\x49\xc3\x63\x03\x84\x0c\xf5\xcf\xba\ +\x16\x3e\x2c\x56\xe7\x06\x09\x8f\x0d\x30\x70\x18\x20\x7b\xbe\x7a\ +\x60\x7d\x26\x7c\xf7\x0f\x54\x31\xf7\x80\x61\xf0\x66\x6b\xe3\xc7\ +\x15\x9a\x35\x7f\xd0\x70\x88\xbf\x07\x96\xb7\x7f\x6e\x5f\xf8\xbc\ +\x54\xfb\x9d\x46\x38\x44\x9c\x80\x60\xd3\xc0\xf2\xdd\xee\xc4\xca\ +\xd3\x9b\x5b\x69\x85\xff\x2f\x80\x3f\x94\x18\xa2\x63\x8f\xc5\xfb\ +\x89\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x98\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x4a\x49\x44\x41\x54\x58\x85\xed\ +\xce\x49\x0d\x00\x31\x0c\x04\xc1\x5c\x90\x0c\xca\x2c\x36\x14\x4c\ +\x25\xfc\x72\x80\x98\x95\xfc\xe9\xfa\xcf\xa8\x4b\x11\x98\xc7\x34\ +\x8f\xa9\x7c\x34\x65\xfc\x07\x02\x08\x20\x80\x00\x02\x08\x48\x0f\ +\x18\xf2\xc3\xad\x9f\x79\xe4\x04\xdc\xd3\x57\x6d\x5b\xb9\x00\x00\ +\x00\xf9\x1e\xf2\x23\x09\xdd\x64\x85\x0e\x0a\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xd0\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x82\x49\x44\x41\x54\x78\x9c\xed\ +\xd7\x31\x0e\x82\x50\x10\x04\xd0\x81\x43\x10\x1b\x13\xce\xe4\x15\ +\xa8\x38\x11\x37\xf1\x3c\x24\x36\xc4\x43\x88\xad\xe1\xdb\x22\x86\ +\xff\x5e\x39\xd9\x62\x76\xbb\x4d\x00\x00\x00\x00\x00\xa8\x47\xb3\ +\x0d\xe6\xf9\x71\x4b\x93\x29\x49\x77\x40\x9f\x3d\x2d\x59\x33\xf4\ +\xfd\xf5\xfe\x19\xb6\xc5\xd8\x39\x97\x4f\x92\x4b\xda\x4c\xdb\xb0\ +\x3c\x40\x65\xca\x03\xac\x19\x93\x3c\x7f\x5f\x65\x77\x4b\x5e\x19\ +\x8f\x2e\x01\x00\xfc\x0f\xbf\x40\x31\x76\xce\xe5\x13\xbf\xc0\x77\ +\x7e\x01\x00\x00\x00\x00\x00\x00\x2a\xf1\x06\x74\xea\x1a\x0f\x1a\ +\xcd\x17\x42\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x2e\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xe0\x49\x44\x41\x54\x58\x85\xe5\ +\x96\xbd\x6b\x14\x51\x14\xc5\x7f\x67\x46\x8d\x20\xf1\xab\x90\x85\ +\xcd\xec\x18\xc1\x2e\x85\xa5\x95\x65\x04\x25\x8d\x85\x56\x0a\x76\ +\x36\x42\xfe\x00\xb1\x10\x7b\x11\x04\x4b\x41\x2b\x2d\x6c\x82\x85\ +\xa6\xb3\xb2\x14\xd9\x4e\xc8\x3a\x3b\xbb\xb0\x58\x69\x82\x90\x0f\ +\x76\x8e\xc5\xac\xb5\xfb\x66\x1e\x0a\x7a\xab\x79\xc3\xbc\x73\x7e\ +\xf7\xbe\xfb\xde\x1b\xf8\xdf\x43\xb1\x05\xcb\xb2\x3c\x3d\xad\xd8\ +\x02\xfb\x6c\xde\x3b\xf5\xbb\xef\x0f\xc5\x34\x9f\x4c\x26\xc7\x76\ +\xf7\x0f\xde\x00\x27\xe6\xcd\x2d\x1a\x40\xbf\xdf\x3f\xb2\xb7\x77\ +\xf0\x1a\xb8\x18\x32\x2f\x89\x61\x6e\x3b\x5d\x5c\x3c\xf9\xdc\xb0\ +\x8a\x1d\x34\xb7\x35\x80\x6d\x0d\x87\xe5\x13\xe3\x1b\xf5\x1b\x55\ +\x7f\x14\xa0\x28\xc7\x0f\x8c\xee\x00\x18\x2a\x44\x50\x09\x5a\x01\ +\x0c\x8a\xd1\x3a\xf6\x3d\xdb\x80\x2b\x11\x66\xde\x0a\xa0\x28\x46\ +\x37\x85\x1f\x01\x24\x52\x05\x0a\x36\x6f\x0c\x50\x14\xe3\x35\xe3\ +\x67\xf5\x48\x95\x1b\x64\xde\x18\x60\x6b\x38\xbc\x64\xaa\x57\x40\ +\x5a\x1b\x07\xb6\x7d\x1b\x80\xc1\x60\x74\x21\xb1\x36\x80\xa3\x60\ +\x0b\x82\x3a\xbe\x15\x40\x59\x96\xe7\x95\xf8\x2d\x70\x1c\x70\xe8\ +\x76\x6b\x05\x50\x96\x65\x77\x5a\xb1\x09\x9c\x99\x75\x7a\x14\x73\ +\x98\xf3\x28\x9e\x56\x8c\xea\x27\xe3\x48\x99\xff\x8a\xf9\x96\xc0\ +\x7c\x8a\x69\x1a\x0c\x90\xa6\x5c\x01\x7d\x01\xa1\x48\xf7\x47\x10\ +\x40\x96\x65\xe3\x34\xf1\x2a\xf0\xd5\xf5\x3d\x1b\x0d\x62\x6e\xa1\ +\x2c\xcb\x3e\xbb\xd2\x65\x60\x1b\x10\x8e\x03\x11\x24\xb2\xbc\xbc\ +\xf4\xb1\x92\xd7\x80\x5d\x84\x1c\xa1\x12\xc1\x02\xe7\x7a\xbd\xf7\ +\x22\xb9\x0e\x4c\x05\x52\xcb\xdf\xba\x46\x19\xe4\x79\x77\x43\xe8\ +\x36\xc0\xac\x0a\x8d\x21\x1a\x97\x30\xcf\x97\x5e\x08\xd6\x01\x6c\ +\x37\x86\x68\xb5\x86\x79\x9e\x3d\x46\x7a\x28\x69\xa6\xe5\x60\x88\ +\xd6\x4d\x94\x67\xdd\xfb\x58\x4f\xeb\x91\x12\x3b\xac\x12\xad\x01\ +\x24\x39\xcf\xbb\x77\x85\x5e\xd6\xe3\x30\xcd\x28\x7b\x59\xd2\x74\ +\x67\xe7\xdb\x2d\xc1\xbb\xd0\xb9\xd1\x4e\xb4\x95\x95\x95\xfd\x85\ +\x85\xc3\xd7\x10\x1f\xfe\x0a\x00\x40\xa7\xd3\xf9\x91\x8a\xab\xb6\ +\xb7\xc1\xdf\x63\x6a\xff\xbb\xf1\x13\xb6\x0b\xa1\x01\x61\x9e\xcd\ +\x4b\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x98\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x4a\x49\x44\x41\x54\x58\x85\xed\ +\xce\xc1\x0d\xc0\x30\x08\x04\x41\x82\x5c\x1b\x15\x50\x02\x7d\x98\ +\x9a\x52\xa0\x9d\x22\x2e\x12\x9f\x9d\xff\x9d\xd6\x4c\x10\x59\x1d\ +\x59\xad\x7c\xb8\x32\xfe\x03\x01\x04\x10\x40\x00\x01\x04\x8c\x07\ +\x2c\xf5\xe0\x5e\xdb\x91\x35\x13\xf0\x1c\x7f\xcd\x8f\x72\x01\x00\ +\x00\xe6\x7d\x0c\xb6\x09\x4f\xb2\x71\xd6\x0c\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x75\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x27\x49\x44\x41\x54\x78\x9c\xed\ +\xc1\x01\x0d\x00\x00\x00\xc2\xa0\xf7\x4f\x6d\x0e\x37\xa0\x00\x00\ +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x77\x03\ +\x40\x40\x00\x01\x8f\xf2\xc9\x51\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x00\x77\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x29\x49\x44\x41\x54\x58\x85\xed\ +\xce\x41\x01\x00\x20\x0c\xc4\xb0\x0d\x53\xb8\x9e\x44\x40\xc6\xf1\ +\x48\x0c\xb4\x55\x00\x40\x58\xef\x39\x37\x39\xb0\x92\x71\x00\xe0\ +\x0b\x0f\xd3\xb2\x02\xe6\x6a\x84\x46\x98\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x9a\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x4c\x49\x44\x41\x54\x58\x85\xed\ +\xd7\xc1\x09\x00\x20\x08\x46\x61\x8b\x76\xf2\xda\xc4\x4d\x10\xb8\ +\x99\xb4\x41\xa6\x74\x7c\xef\xf8\x83\xf0\x5d\x15\xa1\x64\xba\xdc\ +\x74\xb9\xbd\xee\x51\xa3\x60\x98\xc9\xfd\x5a\xaf\x1c\xfd\x0c\x00\ +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf2\x9f\x51\x93\ +\x9d\xda\x29\xe8\x00\x81\xd7\x0c\xbd\xf7\x79\x8f\x39\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xee\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xa0\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\x41\x11\x00\x20\x00\xc3\x30\x0e\x53\xb8\x46\x22\x20\x23\x3c\ +\x1a\x03\xeb\x6d\x0c\x68\xed\x73\xd7\x3e\x57\x36\x4c\x39\xfe\x83\ +\x0e\xd0\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\ +\x00\x1d\xa0\x75\x80\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\ +\xd0\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\ +\x1d\xa0\x75\x80\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\ +\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\ +\xa0\x75\x80\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\ +\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\ +\x75\x80\x0e\xd0\x3a\x40\x07\x68\x0f\xaf\xe7\x06\x43\x97\x92\x59\ +\xbc\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\xea\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x9c\x49\x44\x41\x54\x58\x85\xe5\ +\x97\x5d\x6c\x14\x55\x14\xc7\x7f\x67\xa6\x5b\xaa\x15\x6a\x94\x34\ +\x68\x77\x66\xa7\x8b\x4d\x90\x54\x9f\x2a\x09\x0f\xf8\x81\x04\x12\ +\x91\x0f\x49\xd4\x10\x8d\x24\x08\x91\xf8\xe0\x83\x09\x0a\x4a\xe4\ +\x01\xc5\xfa\x62\x82\x12\x50\x43\x62\x4c\x78\x33\xb1\x81\x0a\x28\ +\x89\x04\x9e\x90\xd0\x84\x90\x54\x03\x59\xda\xdd\x9d\xd9\xa5\x62\ +\x8d\x09\x22\xa8\xed\xce\x3d\x3e\xec\x07\xb3\xdd\x6e\xbb\xad\xbe\ +\x71\x5e\x76\xe6\xdc\xff\x39\xff\xff\xbd\x77\xee\x3d\x67\xe1\x4e\ +\x37\x99\x09\xf8\x4a\x3e\xef\xc4\x0a\x66\xbd\x41\x56\x08\xea\xa0\ +\xc4\x11\x2c\x94\x3c\x42\x4e\xe0\x8c\x65\xd1\xe7\x38\x4e\xea\x7f\ +\x15\x30\x1c\x04\x4b\x2c\x43\x2f\xf0\x54\x23\x78\x85\xf3\x16\xb2\ +\x33\x91\x88\xff\xf0\x9f\x04\x0c\x0d\x0d\xb5\xd9\x76\xf3\x41\x84\ +\x8d\x25\xd7\x88\x42\x3f\xa2\x27\x54\x64\x38\x6c\x6a\x1a\xb9\x2b\ +\x0c\x4d\x18\x86\x0b\x54\x6d\x4f\x45\x57\x0a\xac\x03\x12\x25\xfc\ +\x71\x13\x8e\x6f\x4e\x26\x93\xd7\x66\x2c\x20\x08\x82\x87\x42\xa3\ +\x47\x41\x1e\x06\x46\x04\x76\xbb\x6e\xfc\x4b\x11\x29\x4c\x25\x5a\ +\x55\xad\x4c\x10\xbc\x28\x2a\xef\x03\x49\x04\xdf\x14\x64\x6d\x32\ +\x19\xbf\xd8\xb0\x80\x6c\x36\x9b\x54\xac\x73\xc0\x7c\x81\x23\x63\ +\x63\x7f\xbf\xd2\xd5\xd5\xf5\xc7\x54\xc4\x13\x2d\x95\x4a\xcd\x89\ +\xcd\x69\x39\x80\xb2\x19\xb8\x89\x5a\xcb\x3c\xaf\xe3\xc2\xb4\x02\ +\x52\xa9\xd4\xbc\x58\x73\xcb\x59\x60\xb1\xc2\x3e\xcf\x8d\xbf\x29\ +\x22\x66\x26\xe4\x65\x53\x55\xc9\xf8\xf9\x1d\x82\xee\x05\x72\x68\ +\xb8\xc4\xf3\xbc\x91\x28\xa6\x69\x62\x50\xac\xb9\x65\x7f\x91\x5c\ +\xfb\x3d\xd7\xa9\x21\xbf\x92\xcf\x3b\x76\xc1\x6c\x11\x78\x06\x70\ +\x01\x83\x92\x05\x3d\x06\xe6\x50\x94\x40\x44\x54\x55\x7b\xb3\x7e\ +\x2e\x09\x6c\x41\xec\xc3\xaa\xba\x42\x44\x74\xd2\x15\xf0\x7d\xbf\ +\xc7\xa8\x9c\x47\x19\x0d\xc3\xb1\xae\x85\x0b\x17\x5e\x8f\xcc\xc6\ +\xca\xf8\xf9\xb7\x05\x7d\x0f\x68\xa9\x33\xe9\x9b\x02\xef\xb8\x6e\ +\xfc\xd3\x28\xc9\xe0\xe0\x60\xf3\x3d\x73\xdb\x2e\x02\x8b\x50\x56\ +\x7b\x9e\x73\xbc\x3c\x66\x45\xa3\x8d\xf2\x61\x51\x39\x7b\x26\x92\ +\x67\xfd\xdc\x57\xa5\xa5\xac\x47\x0e\xd0\xaa\xb0\xcf\xf7\x83\x03\ +\xaa\x5a\x99\x5c\x77\x77\xf7\x18\xca\xbb\x00\x2a\xf4\x46\xc7\x2a\ +\x02\x32\x99\xcc\x03\x20\x4f\x03\xbf\xdf\xb8\x71\xfd\xf3\xea\x95\ +\xc9\xed\x02\x5e\x56\xa5\x21\x53\x64\x9b\xef\xe7\xde\x88\xfa\x12\ +\x89\x78\x1f\x70\x49\xe0\x91\x74\x3a\xff\x68\x8d\x00\x11\x7b\x0d\ +\xc5\x2d\x39\xd6\xdd\xdd\x3d\x56\xf6\x17\x4f\x04\xbb\x8a\x98\xc6\ +\x04\x14\x45\xf0\x81\xef\xfb\x0f\xde\xce\x2f\xaa\x70\x14\x40\x6c\ +\x7d\xae\x46\x80\x2a\x4f\x96\x22\xbf\xab\x4a\x24\xf6\xeb\x40\xac\ +\x71\xea\x8a\xb5\xaa\xca\xd6\xa8\x43\x54\xbe\x2f\x3d\x2e\xaf\x11\ +\x80\x88\x53\x7a\x48\x57\x4f\x45\x57\xcf\x82\xbc\x18\x0a\xcf\x56\ +\xa7\x1a\x1f\x06\x10\x88\xd7\x0a\x28\x39\x55\xc7\x47\x6e\x07\xa8\ +\x00\xc9\xd9\x0a\x40\x2b\x57\x32\x00\x85\x42\xa1\x9c\xbb\xa3\xfc\ +\x21\x5a\x35\x41\xd5\x26\x0d\x60\xa6\x8a\xb6\xa7\xc9\x1d\x4d\x6e\ +\xf2\xc5\xdf\xd8\x82\x0a\xa2\x78\x09\x65\x67\x2d\x00\xfc\xe8\x8b\ +\x6d\xb7\x96\x72\xcb\xd5\xf2\x05\x77\x5b\x80\x5a\x41\x11\x65\x3a\ +\x27\x24\x39\xce\x6c\x4d\xb5\x2a\xd6\xb2\x4c\x79\x3b\x73\x15\x5f\ +\x05\x2b\x9c\x06\xb0\x94\x55\xd1\x20\xc1\x7c\x06\xcc\xa6\x16\x8c\ +\x81\x39\x54\x95\x4b\x74\x25\x80\xa2\xa7\x6a\x04\xd8\x62\xfa\x8b\ +\x83\xb2\x7a\x60\x60\xa0\x72\xec\x12\x89\xc4\xcf\x82\x7e\xd2\x38\ +\xaf\x96\x84\xb3\xd7\xf3\xbc\xca\x89\x52\x55\x51\x58\x0b\x80\x91\ +\xbe\x1a\x01\xae\xeb\x5e\x05\x4e\x01\xf3\xef\x6f\x6f\xdf\x12\x4d\ +\x39\x3a\xfa\xeb\x5b\x34\xbc\x15\x82\xa2\x5f\xbb\x6e\x7c\x4f\xd4\ +\x1b\x04\xc1\x1a\x60\x31\xf0\x93\xe7\x75\x54\x7a\x83\xaa\x2f\xdc\ +\x12\xdd\x01\x20\x6a\xed\x4e\xa5\x52\xf3\xca\xfe\x9e\x9e\x9e\xf1\ +\xdf\x46\xaf\xad\x57\xd8\xc7\xd4\xdb\x51\x40\x75\xaf\xe7\x3a\x1b\ +\xa3\x55\x74\x70\x70\xb0\xd9\xa8\x14\xeb\x0c\xd6\xce\xba\xd5\x10\ +\x20\x93\x0d\x0e\x03\x2f\x09\x1c\x71\xdd\xf8\x86\x89\xe5\xd8\xf7\ +\xfd\x6e\x83\x6c\x43\x2b\xe5\x58\x81\xac\xc2\xb7\x1a\x5a\x07\x93\ +\xc9\x8e\xcb\x51\xbc\xaa\x8a\xef\x07\x07\x15\x79\x0d\xe1\x74\xc2\ +\x89\x2f\x9f\x52\xc0\xd0\xd0\x50\x9b\xdd\xd4\xfc\x23\xb0\x08\x95\ +\x8f\x13\x89\x8e\xed\xf5\x1a\x12\x55\xb5\x01\x44\x24\xac\x33\x2e\ +\xbe\x9f\xdb\xae\xf0\x11\x70\xd5\x12\x7d\xac\xb4\xd5\x15\x9b\xb4\ +\xbc\x14\xfb\x41\xce\x01\xf7\x21\x7c\x73\x77\xcb\x9c\x4d\xed\xed\ +\xed\x7f\x4e\x86\xad\x67\xa5\x1e\x60\x3f\xb0\x15\xb8\x65\x89\x3e\ +\xe1\xba\xee\xc0\x44\xdc\xa4\xb7\x9c\xe3\x38\x57\x42\x5b\x96\x02\ +\x97\x51\x36\xdc\xfa\xeb\x9f\x4b\x99\x4c\xf0\xaa\xaa\xd6\x74\x50\ +\x13\x4d\x55\xad\x6c\x36\xf7\x42\xeb\xdc\xb6\xc1\x12\x79\x0e\xb5\ +\x97\x4d\x46\x0e\xd3\xb4\xe5\xe9\x74\xfa\x5e\x2c\xfb\x0b\x41\x9e\ +\x2f\xb9\x72\xa8\xf4\x8b\xc8\x09\x28\x0c\x5b\x96\x35\x52\x28\x14\ +\x0c\x34\x2f\xc0\x0e\x13\x62\x58\x85\xc8\x3a\x4a\xf5\x43\xe0\xa4\ +\x31\x85\x4d\x9d\x9d\x9d\xbf\xd4\xe3\x68\xa8\xc2\x67\x32\xb9\xa5\ +\x22\xda\xab\xf0\x78\x23\x78\xe0\x82\x11\xdd\x91\x74\xdd\x93\xd3\ +\x01\x67\xf4\xd7\x2c\x9d\x4e\x7b\x58\xb1\xf5\x82\xae\x40\x71\x10\ +\xe2\x80\x0d\xe4\x04\x72\x06\x39\x83\x91\xbe\xce\xce\x8e\x4b\x33\ +\xc9\x7b\x67\xdb\xbf\x21\xb9\xe6\xce\xae\xea\xf6\xd6\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x18\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xca\x49\x44\x41\x54\x58\x85\xed\ +\x96\x3f\x48\xc3\x40\x14\xc6\xbf\x97\x0a\x29\x08\xd5\x5d\xa9\x8b\ +\xb8\x76\x15\x41\x5c\x8c\xae\xd2\x58\xc4\x21\x2e\xad\x2e\xba\x14\ +\x44\x5c\x9c\x3a\x38\x08\x2e\xc5\xa5\x56\x1c\x5c\x94\x92\x82\xd0\ +\x45\xb3\x08\x22\x38\xda\xd1\xc1\xa1\x38\xb8\x08\xfe\x19\x0a\x85\ +\xe6\x9e\x8b\xa9\x35\x35\x69\xd2\xbf\x83\xfd\xa6\x77\xc9\xcb\x7d\ +\xbf\xbc\xbb\x7b\x1c\xf0\xdf\x45\x6e\x2f\x17\x34\x6d\x58\x94\x83\ +\x29\x02\x47\x01\x4c\xb4\xe9\x55\x02\x58\x97\x2b\x81\xbd\x42\x21\ +\x53\x6e\x0a\xb0\xa0\x69\xc3\x5c\x0e\xde\x01\x1c\x69\xd3\xd8\x26\ +\x2a\xca\x15\x9a\xb1\x20\x24\xa7\x34\x51\x0e\xa6\x3a\x6f\x0e\x00\ +\x1c\xa9\xc8\x66\xca\x1a\x39\x02\x7c\x97\xbd\x4b\x22\xd5\x8a\x86\ +\x5c\xb2\x7e\xad\xb9\xa1\x67\x5d\xf7\x4b\x33\x29\x6a\x82\xff\x9a\ +\xdb\xb1\x02\xbd\xd2\x00\xa0\x61\x0f\xcc\xc7\x36\xc2\x64\x9a\x73\ +\x0d\xcf\xd5\xf8\x96\xd3\x24\x12\x49\x82\x85\x28\x8e\x06\x3e\xef\ +\x73\xb9\x9c\xd9\x32\xc0\xfc\x72\x7c\x9b\x84\xd8\x07\x51\x03\x18\ +\x81\xd2\x4e\x93\x30\x33\x40\x84\x37\x31\x72\xbb\x18\xdd\x58\xb9\ +\xca\x67\x5e\xbc\x02\xd4\x96\x40\x51\x13\xab\xc4\x74\x60\x87\xf2\ +\x23\x02\x66\x4d\x12\x17\xb1\x58\x2c\xe0\x1b\x00\xc0\x4e\xab\xc6\ +\x76\x88\x77\x33\x34\xed\x35\xbf\xfe\x6f\xed\x5d\xef\xc8\x87\xef\ +\x12\x80\xb1\x1a\x84\x24\x45\x00\xdc\xf9\x05\xf8\xd5\x68\x0c\x3d\ +\xeb\xb8\xe9\xec\x52\xd4\x04\x00\x6c\x5a\x63\xc1\xc2\xf3\xe9\xea\ +\xfb\x31\x1c\x00\x0c\x00\xfa\x0e\xd0\x72\xd7\x73\x13\x81\xd2\x8a\ +\x9a\x70\x6c\xdd\x00\x4a\x56\xd0\xa7\x0a\xb0\x6e\x45\x5d\xa9\x80\ +\xbb\xa8\x28\x57\xa4\x3d\x6b\xd4\xcb\x0a\x94\x00\x3e\xac\xbf\x11\ +\x03\x75\xed\x57\x51\xd7\x3f\x00\x0e\x75\xc4\x8a\x79\xcd\xc8\x9f\ +\x9c\x79\x49\xad\x55\x80\x20\x8c\x8e\x98\x03\x55\x32\xc5\x8d\xd7\ +\xe4\x9f\x25\xa8\x8a\x24\x18\xaf\x6d\xdb\x33\x76\xaf\x2f\x4f\x9f\ +\xbd\xa6\xd7\x2e\x0e\x4f\x8f\x0f\x9f\x93\x53\x91\x73\x92\x28\x0c\ +\x48\xe3\x00\x64\x5f\xb6\x40\x91\x88\x92\x86\x9e\x3d\xf6\xf1\xdd\ +\x40\xf8\x02\x67\xdb\x80\xa5\xc9\x72\x5a\xc9\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x03\x34\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\xe6\x49\x44\x41\x54\x58\x85\xe5\ +\x96\xcb\x6e\xd3\x40\x14\x40\xcf\x0d\x2c\x80\xcf\x48\xb3\x69\x0a\ +\x8b\x24\x3b\xd6\x69\x36\x48\xb4\xb5\xc3\x4b\x42\x2d\x10\x5b\xf0\ +\x01\x48\x7c\x03\x4b\x76\x48\x24\x40\x05\xe5\xd5\x26\x1f\xd0\x76\ +\xcb\x36\x29\x8f\xda\xbc\x62\x5e\x12\xfc\x01\xb0\x69\x2e\x8b\xd4\ +\xc1\x8e\xed\xc4\x29\xd9\x20\xee\x6a\x6c\xcf\xdc\x73\xe6\xce\xe8\ +\xca\xf0\xbf\x87\xf8\x83\x4a\xd5\x3e\xa9\xaa\xb7\x81\xa3\x2a\xdc\ +\xd8\xde\xa8\xb7\xa6\x09\x2a\x57\x2d\x43\x94\x9b\xc0\x2f\x54\xaf\ +\x6d\xb5\x1a\xcf\x01\x32\xfe\x04\x55\x6d\x00\x27\x80\x9c\x28\xeb\ +\x15\xc3\x3a\x37\x2d\x78\xa5\x6a\x9f\x17\x65\x1d\xc8\x01\xc7\x11\ +\xa9\xfb\xdf\x32\x7f\xa6\xe9\x91\xc0\x9a\x8c\x0a\x8f\xa6\x21\x51\ +\xa9\xda\xe7\x55\x75\x2d\xcc\xe2\x58\x44\x40\xc9\x5c\x07\x7a\xd3\ +\x94\xa8\x18\xd6\xb9\x18\x78\x0f\xd1\xeb\xfe\xc3\x21\x7f\xe0\xb9\ +\x6d\x77\x26\x5f\x7c\x0f\x2c\xf1\xe7\x6e\x08\xc2\x52\x6e\xb6\xf8\ +\xb6\xeb\xb6\x77\x27\x86\x0b\x8f\x22\x70\x58\xd9\x6a\x36\x9e\x44\ +\x04\xf6\x25\x5e\xc7\x48\x64\x26\x95\xd8\x87\xaf\x0d\xe5\xdf\x87\ +\xd7\x1f\x06\xe7\x86\x04\x7c\x89\xec\x6c\xe1\x83\x88\x44\x24\xb2\ +\xf9\xd2\x1b\x6f\x8c\x44\xd9\xb4\xcf\xd2\xdf\xf9\x58\x78\xac\x40\ +\x5f\xa2\xf3\x2a\x4e\x42\xc0\x18\x25\x51\x36\xed\xb3\x82\x0e\xc3\ +\x35\x09\x9e\x28\xe0\x4b\xe4\xe6\x4a\x5d\x60\x31\x8d\xc4\x7c\xb5\ +\x76\x46\xe0\x71\x0c\x7c\x39\x09\x3e\x52\x00\xa0\xeb\xb4\x13\x25\ +\x66\xe6\x0a\xae\xe7\x74\x1c\x1f\x8e\xca\xc4\x70\x02\x49\x47\xc6\ +\xbc\x69\x5d\x04\x56\x09\xdf\xe8\x3d\x44\x2f\xf4\x51\x31\x70\xd5\ +\x95\xad\x56\xe3\xc1\xb8\xdc\xa9\x04\x92\x24\x04\x7a\xda\x1f\x06\ +\xc5\x52\xc3\x61\xcc\x11\x04\xc3\x73\xdb\x2f\x67\xf2\x45\x8f\xe1\ +\x3e\x11\xde\xc4\x44\xf0\x89\x04\x02\x12\xdd\x21\x89\x01\x5c\x85\ +\x4b\xdb\xcd\xf4\x70\x08\x97\x2e\x55\x28\xf2\x93\xfe\x05\x0b\x87\ +\x88\x66\x7a\xfc\x98\x34\xdf\x44\x15\x28\x9b\xb6\x29\xe8\x93\x84\ +\x75\x82\x60\xe6\x66\x8b\x4e\xd7\x6d\x3b\x53\x17\x28\x57\x2d\x43\ +\xe0\x29\x70\x38\xf0\xda\xaf\x44\xb0\x63\x9a\xd9\x7c\x69\xd7\x73\ +\xdb\x6e\x9a\xbc\xa9\x8e\x60\xff\x67\x22\x02\x17\xf4\xb2\x0a\x97\ +\x08\x1f\xc9\x21\x41\x9f\x96\x4d\xdb\x4c\x93\x7b\x6c\x05\xe6\x0d\ +\x7b\x49\xe0\x59\x1c\x7c\xb3\xd9\x58\xf5\x9c\xf6\x8b\x5c\xbe\xf0\ +\x09\x64\x81\x70\xb3\x4a\x55\x89\x91\x02\xf3\x86\xbd\x84\x68\x04\ +\x8e\xca\x95\xad\x56\x7d\xd5\x7f\xd1\x75\x3b\x49\x12\x46\x36\x5f\ +\x72\x46\x49\x24\x0a\x8c\x86\xdf\xb9\x3f\x3c\xbf\xeb\x76\x5e\xcc\ +\xcc\x96\x3e\x23\x4c\x24\x11\x2b\x50\x31\x6b\x8b\x08\xeb\x69\xe1\ +\x7e\x78\x6e\x7b\x27\x51\x62\xae\xb8\xeb\x39\x51\x89\x88\x40\xc5\ +\xac\x2d\x2a\x12\x81\xab\x50\xdb\x6e\xd6\x13\xe1\x41\x89\xec\x5c\ +\xf1\x8b\xc0\x69\x86\xef\x44\x8c\x44\x48\xa0\x5c\xb5\x16\x40\x36\ +\x62\xe1\x1b\xf5\x7b\xe3\xe0\x03\x09\x27\xbd\xc4\x40\xa0\x6c\xd4\ +\x4e\x09\xd2\xfa\x5b\x78\x50\x22\x97\x2f\x7c\x05\x89\x48\xe4\xf2\ +\x85\x9d\xae\xdb\x79\x07\x81\x3e\x90\x11\xb9\x35\x0c\x17\xd4\x3a\ +\x08\xdc\x8f\xcd\x66\xe3\xae\xa0\x16\xe1\x3e\x71\x58\x91\x5b\x03\ +\xee\x80\x86\x06\x7f\xc9\x55\x50\x6b\xb3\xd9\xb8\x7b\x50\xf8\x18\ +\x89\xbd\x88\x40\x46\xf5\x2a\xe0\x01\xdf\x51\x5d\x99\x06\x3c\x28\ +\x01\x2c\x23\x7c\x03\x3e\x4a\x8f\xab\xd3\xca\xfd\xef\xc7\x6f\xcf\ +\x0b\x86\xc1\xfd\xdf\x90\xb9\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ +\x42\x60\x82\ +\x00\x00\x02\x25\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xd7\x49\x44\x41\x54\x58\x85\xed\ +\x95\x3d\x68\x13\x51\x1c\xc0\x7f\xff\x77\xfd\xc2\xc1\x28\x2d\x3a\ +\x74\x29\xda\x0e\xea\x10\xb1\x9b\xa5\x50\xc4\x24\x94\xc6\xc1\xe6\ +\x4e\xf0\x0b\xc1\x26\xd6\x2e\xdd\x9c\x83\x9b\x7b\xb7\x0c\xd2\xcd\ +\xc5\xa1\x4a\x44\xac\x8b\x07\xe9\x22\xd8\x51\x27\x3f\x26\xc7\xd2\ +\x49\x38\xcf\x7b\x7f\x87\x5c\x6c\x42\xaa\x4d\x0f\xab\x14\xee\xb7\ +\x1c\x77\xf7\xff\xf8\xbd\x7b\xef\xde\x83\x94\x94\x94\x94\xff\x8c\ +\x24\x4d\xbc\xe4\xdd\x1f\x75\x6c\xf4\x02\x34\x4b\x68\x47\x5f\x3f\ +\x7f\xfc\x35\x49\x1d\x93\x24\x29\x57\x5a\x9c\x70\x6c\xd8\x00\xcd\ +\x02\xd0\x2f\x1b\x05\x6f\x61\xfc\x9f\x08\xe4\xbc\xca\x79\x88\x1a\ +\x20\x63\x0a\x28\x00\x32\x66\x55\x1a\x85\xab\x77\xb3\x07\x2a\x50\ +\x70\xcb\xd3\x58\x7c\xe0\x04\xa0\x02\x91\x40\x04\x28\xca\x49\x6b\ +\x8c\x5f\x70\xcb\xd3\x07\x22\x90\x77\x2b\x45\xab\xac\x83\x1e\xd5\ +\xe6\xc0\x6d\xdb\x6b\x0b\xaa\x40\xc6\x2a\xeb\x97\xe7\x17\xe6\xfe\ +\xaa\x40\xae\x54\xbe\xa5\xaa\x6b\xc0\x10\xaa\x2a\x9d\xcd\x63\xc4\ +\xaa\xa2\xc0\x90\x88\x3c\xcb\xbb\x95\x9b\xbd\xd4\x76\xf6\x0a\xc8\ +\x97\xca\xcb\x40\x0d\x30\x8a\xaa\x88\xec\xd2\x3c\x56\x10\x94\xe6\ +\x9f\x65\x80\xf9\x53\x67\x26\xb7\x3e\x7d\xd8\x7c\x9b\x54\x40\x72\ +\xa5\xca\x43\xe0\x51\x7c\x6b\xa5\xb5\xe6\xfe\x8c\x8a\xc4\x3e\xc2\ +\xec\xf8\xb9\x0b\xf2\xf1\xfd\xa6\xbf\x2f\x81\x6a\xb5\x6a\x06\x46\ +\x26\x56\x80\x07\x71\xa9\xd6\x1c\xf7\x8c\xec\x5c\x66\x4e\x9f\x9d\ +\x1c\xbe\x7d\xed\xca\x2b\xdf\xf7\xbb\x6a\x74\x6d\x44\x9e\xe7\x0d\ +\x6c\xdb\xcc\x2a\x70\x3d\x0e\xd9\x77\xf3\xb6\xf2\x02\xda\x5a\x67\ +\x4f\xb6\x86\xcd\x9d\x77\xb5\x5a\xf8\x5b\x81\x62\xf1\xde\x91\x60\ +\x30\x7a\x0a\x32\x8b\x02\x46\x2c\x9a\xb4\xf9\x2f\x07\x51\x55\xd3\ +\x6c\xa4\x2f\x07\x03\xc7\xad\xd7\x6b\xdf\xba\x04\xe6\x6e\x2c\x1d\ +\xff\x1e\x84\x75\xe0\x62\xfc\xc8\xd2\xdb\x9c\xef\xed\x80\x88\xee\ +\x7c\x89\x8d\x30\xfa\x51\x7c\xb3\xb6\xba\x0d\xd0\xd7\x0a\x0a\x82\ +\xf0\xb3\x40\xa6\x2d\x2f\xd1\x36\xbd\x1b\xda\x39\x8e\xa9\x7e\xa7\ +\xef\x0b\x70\xac\xa3\x49\xe2\x53\x29\x25\x25\x25\xe5\xb0\xf3\x13\ +\x19\xff\x9a\x58\xf0\x37\x9f\x0a\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x03\xd3\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x85\x49\x44\x41\x54\x58\x85\xe5\ +\x97\x4d\x68\x9c\x55\x14\x86\x9f\xf7\x66\xd2\x1f\xa1\xb5\x95\xa2\ +\x29\x36\xb4\x06\xad\x9a\x8d\x81\xd4\x49\xb2\xf0\xa7\xa5\xb4\x54\ +\x69\x93\x9a\x18\x11\xa9\x85\xa2\xb8\x70\x27\x08\x29\x2e\xa2\x28\ +\x1a\x70\xa5\x14\x45\x11\x44\xd1\x4d\x68\x33\x69\xa2\xa9\x16\x2c\ +\xe9\x42\xda\x69\xac\xa5\x0b\x43\x41\x88\xa0\x93\x46\x11\x94\x6a\ +\xb5\x3f\xcc\x77\x5f\x17\x33\x49\x93\x4e\x92\x26\x64\xe2\xa6\x67\ +\x73\x3f\xce\x77\xbe\xf3\x3e\xf7\x7e\xf7\xe7\x5c\xb8\xd9\x4d\xf3\ +\x09\x7e\xb0\xd7\xd5\x15\x09\x2d\x96\xb7\x5a\x54\x63\xd6\x09\x02\ +\x30\x8a\xc8\x19\x1d\x57\x42\x26\xdb\xa6\x1f\xcb\x0a\xd0\x94\x71\ +\x3a\xda\x5d\xc0\xe6\x39\x26\x1d\x4a\xa4\xfd\x43\xbb\xf5\xcd\x82\ +\x00\xea\xbb\x7d\x6b\x2a\x15\xdf\x07\x3d\x5d\x74\x8d\x61\xf7\x3b\ +\x84\x23\x4a\x18\x59\x12\x19\xbb\x92\x22\x3a\x52\x25\xb1\x41\x8a\ +\xdb\x40\xcd\xc0\xfa\x62\xf6\x01\x82\xf6\x65\x9b\xf5\xdb\xbc\x01\ +\x9a\x0e\xfb\xee\x98\xb8\x0f\xb8\x1f\x18\x13\xea\x5c\xb6\x9a\x8f\ +\x07\x37\x2b\x3f\x6b\x97\x3a\x1d\xd2\x75\x3c\x25\xfb\x0d\xa0\x46\ +\xe2\xe7\x68\xed\x3a\xf5\x84\xce\xce\x19\x60\xd3\x41\xd7\x54\x04\ +\x67\x81\x35\xc0\x61\x96\xe9\xd9\xec\x63\xfa\x6b\x56\xe1\xeb\x6c\ +\xc7\x80\x97\xfe\x71\x39\xbe\x07\xda\x87\xf9\x27\x58\x0f\x9d\x68\ +\xd3\x99\x1b\x02\x34\x0c\x78\x25\x97\x7d\x02\xa8\x05\xbf\x93\x3d\ +\x1b\x5e\xe2\x35\xc5\xf9\x88\x4f\x98\xad\x86\x5e\x3a\xb0\xdf\x04\ +\x72\x79\x2b\x7d\xba\x55\x63\x93\x43\x42\xc9\x47\x57\xe2\x01\xa0\ +\xd6\xa6\x7f\x41\xe2\x00\x92\xb3\x2d\x74\x19\x7f\x04\xac\x4b\xc9\ +\x9f\x61\x4f\xe9\xf4\x14\x80\xf4\x41\x6f\xc2\xda\x63\xf8\x3d\x49\ +\xb4\x67\x41\xe2\x93\x20\x2e\xe6\xc3\x8b\xc0\x39\x60\x4b\xc3\x21\ +\x76\xcc\x08\xa0\x0a\xbf\x05\x10\xac\xd7\x4f\xb7\xeb\xc2\x82\xc5\ +\x8b\x36\xdc\xae\xab\x42\xaf\x14\x14\xdd\x35\x79\x14\x26\x1e\xea\ +\x0f\x79\x6d\x4a\x1e\x05\xfe\xfc\x3b\xaf\xb5\xc3\xed\xba\x5a\x2e\ +\x00\xa0\x30\x1f\x32\x1e\x06\xee\x33\xaa\x1b\x5f\x15\x13\x23\x90\ +\x0a\xec\x04\x84\xfc\x65\xd9\xc5\x01\x24\xcb\xee\x03\x08\x8e\xbb\ +\xc7\xdd\xd7\x7e\x81\xe3\xa3\x85\x26\x7c\x55\x76\xf1\xa2\x45\x85\ +\xaf\x01\x2c\x6d\x29\x05\x40\xd5\x85\x86\x9f\x16\x0b\x20\x88\x11\ +\x00\xcc\xba\x69\x00\x0a\xce\x20\xc6\x58\x24\x5b\xbd\xb4\x98\x5b\ +\xdc\x39\x3e\x11\x4b\xf7\x81\xff\xcb\x5e\xa5\x04\x60\x14\xc0\x91\ +\xaa\xc5\xd2\xbc\x70\x69\x22\xf7\xf9\xf1\x3d\x66\x12\x80\x7f\x01\ +\x70\xe0\xae\xc5\x02\x48\xa0\xa6\xf8\x98\x1b\xf7\x4d\x00\xd8\x61\ +\x10\x20\x38\x6e\x5f\x2c\x00\x14\xb7\x15\xd5\x8e\x95\x00\x54\xa6\ +\xe8\x07\x30\x7a\xbc\xfe\x03\x57\x96\x5d\xdc\x16\x68\x17\x40\x54\ +\xc8\x94\x00\x7c\xdb\xac\xf3\xc0\x31\x60\x4d\xe5\xed\x3c\x57\x6e\ +\xfd\xc6\x1e\x76\x02\xb5\xc0\x0f\x43\x2d\x4c\xd4\x06\x53\x56\x41\ +\xb4\x3a\x0a\xb0\xee\x6c\x18\xf0\xca\x72\x89\xd7\x76\x7b\x89\x55\ +\x38\x67\x14\xb4\x1f\xc9\xd3\x02\x0c\xb5\x6a\xc8\xf8\x73\xe0\x0e\ +\x2e\xfb\x53\x3a\xbd\xf0\x65\x6a\x6b\x45\x2a\xbe\x4b\xa1\xf7\x83\ +\x27\x9b\xf9\x62\xf2\xeb\x12\x81\xe4\xda\xd1\xd9\x9c\x7e\x20\xbe\ +\xbd\x20\x08\x5b\xe9\x5e\x5e\x06\xbd\x00\x9c\x4f\x55\xe8\x99\xc9\ +\xbd\x87\x19\x4a\xb2\x62\x3d\x98\x05\x6e\x03\x7a\x96\xe7\xb5\x77\ +\xb0\x5d\x17\xe7\xa3\x5d\xdb\xed\x25\x2b\x52\xf1\x00\xe8\x79\xe0\ +\x5f\x47\x3d\x72\xaa\x4d\xdf\x5d\x1f\x37\x63\x51\x9a\xee\xf1\x46\ +\xe1\x3e\xe0\x5e\x60\xd4\x52\xe7\x2d\xab\xf8\x64\x2e\x45\x69\x63\ +\x1d\x6d\x2e\x14\xa5\xf7\x00\x39\x59\xcd\x27\x5b\xf5\xfd\x74\xe1\ +\xb3\x96\xe5\x75\x19\xaf\x5a\xea\xf8\x21\xe8\xc9\xa2\x2b\x67\xbb\ +\x3f\x54\x84\x23\x49\x9e\x91\x54\x64\xec\x52\x25\x71\x79\x42\x55\ +\x02\xeb\x43\x88\xdb\x5d\x28\xcb\xc7\x37\x9c\xa3\x31\xaf\xbd\x43\ +\xed\xfa\x75\x26\x8d\x39\x5d\x4c\xd2\x3d\x6e\x12\xee\x02\x1e\x9e\ +\x4b\xbc\xc5\x19\xa1\x8e\xec\x6e\x1d\xbd\x51\xec\xbc\xae\x66\x8d\ +\x19\x6f\x70\xa4\x05\x79\x2b\x50\x4d\xe1\x04\xad\x00\x72\x88\x1c\ +\xe8\x78\x48\xc8\x9c\x68\xd3\xb9\xf9\xe4\xbd\xb9\xed\x3f\x89\x47\ +\x63\xa6\x91\x26\x12\xd0\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ +\x60\x82\ +\x00\x00\x00\xf0\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xa2\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\x41\x11\x00\x20\x00\xc3\x30\x0e\x6f\x28\xc0\x02\xfe\x2d\x80\ +\x8c\xf0\x68\x0c\xac\xb7\x31\xa0\xb5\xcf\x5d\xfb\x5c\xd9\x30\xe5\ +\xf8\x0f\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\ +\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\ +\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\ +\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\xd0\ +\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\xad\ +\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\xd0\x3a\ +\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\xad\x03\ +\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x3d\x9d\xfa\x04\x75\x0c\ +\x2b\x93\xd0\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x68\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x1a\x49\x44\x41\x54\x58\x85\xed\ +\xc1\x01\x01\x00\x00\x00\x82\x20\xff\xaf\x6e\x48\x40\x01\x00\x00\ +\x00\xef\x06\x10\x20\x00\x01\x47\x01\xa0\x88\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\xe8\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x9a\x49\x44\x41\x54\x58\x85\xc5\ +\x97\xd9\x76\xe2\x46\x10\x86\xbf\x66\x11\x12\x60\x50\x9c\xc4\x9e\ +\xf1\x24\x39\x59\xde\xff\x9d\x72\x31\x9e\x49\x1c\xcf\x18\x6c\x23\ +\x19\x24\xa8\x5c\xd4\xdf\xa8\x91\x71\x72\x97\xd4\x39\x1c\x89\x56\ +\xd7\xf6\xd7\xd6\x0d\x58\x09\x16\xf8\xcf\xc9\x02\x58\x19\xa4\x7c\ +\x09\xac\x21\x58\xf7\x91\x4b\x20\x1a\x96\x25\xef\x93\x44\x4a\x5c\ +\xb3\x64\x6d\x9b\xac\xed\xf4\x7e\x00\x1e\x7a\xf2\x97\xc0\x3a\xf4\ +\x16\x0e\xc0\x05\x30\x00\xaa\x44\x59\x90\x11\x13\xd8\x0d\x21\x8c\ +\x81\x71\xcf\xa5\x16\xac\x81\xac\x95\x11\x51\xb9\x01\x0d\x90\x4b\ +\xfe\x23\x30\x3c\x75\xd8\xf7\x2d\xc0\x7e\x11\x34\x63\xb0\x99\xd6\ +\x33\xb0\xf7\xf0\x50\x82\xe5\x60\x13\xb0\x82\x57\x64\x85\xbe\x4d\ +\xb5\xf7\xca\x79\xc1\xd7\x2c\x93\xec\x5f\xc1\x2e\xfa\x10\x02\xf6\ +\x01\xf8\x24\x24\x0c\x78\x01\x0a\xd8\xbd\x87\xec\xa3\xbc\x00\x58\ +\xc8\x8b\x73\x94\x7e\x9b\xc0\xee\x06\xb2\x5b\x21\x92\x4b\xdf\x1a\ +\xb8\x81\x70\x0b\x30\x92\xf2\x80\xc3\x3e\x96\xf2\x1b\xe0\xde\x19\ +\xb2\xfb\x44\xf9\x04\x0f\x91\x71\x1a\xf7\xe8\xcc\x4c\xca\xf4\xcb\ +\xbe\xc2\xa6\x80\xd9\x18\x78\x07\x7c\x94\x8e\x41\x0f\x01\xfb\x4e\ +\xff\x2b\x08\x15\xd8\xb5\xbe\xfd\x09\xcc\x1d\x8d\xd5\x0c\x4a\x5c\ +\x70\xa8\xcf\x03\x60\x73\xa0\xc5\xf3\xa5\xd2\xf3\x80\x27\xf4\x0e\ +\x78\xc2\xe3\xff\x0d\xb0\x82\xb0\x19\x25\xdc\x63\x29\xcf\xe5\xdd\ +\x1a\xb8\x92\xc5\x39\x94\x4f\x82\x71\x02\x66\x1d\x0f\x24\x08\xe5\ +\xc0\xb3\x94\x95\x42\x38\x03\xee\xf0\xf0\x64\x10\x9e\x12\x07\x3b\ +\x28\xdc\x52\x9b\xc0\xcb\xb5\x18\x83\xa0\x5c\x48\x68\xa4\x39\x1e\ +\x86\xb9\xf8\x07\xfa\x1f\xd7\x22\x6d\xc4\xbb\x93\xac\x00\xdb\xf7\ +\x4a\xcc\x63\xee\xc5\x10\xbc\x73\x41\x15\x30\xfd\x8c\xc7\xb2\x96\ +\xf5\x23\xc1\x56\x43\x75\x09\xd3\xb5\x23\x75\x8e\x6c\x21\x99\x35\ +\x30\x95\x03\x53\xba\xd2\x1b\x49\xf6\x1c\x0f\xc1\x97\x14\x81\x09\ +\xb4\x2f\x49\x6d\x16\x8a\xb5\xe1\x96\x5d\xc3\x74\xe5\x48\xbd\x49\ +\xb1\xce\xbf\x17\x8f\x09\x89\x58\xb6\x2d\x3c\x36\x78\xe8\xfa\x21\ +\x68\x4a\x58\x3c\x74\xc6\x30\x54\x3e\xe4\x78\xd2\xfc\x25\xc1\x85\ +\xfa\x41\xee\x49\x67\xb3\xee\x3f\x05\x9e\x37\x5f\x61\x73\x29\xde\ +\x3c\x91\x09\x2c\x9e\x49\x42\x15\x0d\xc8\xbc\x8b\x91\x0b\xc6\x52\ +\x1e\xb4\x62\x5c\xe1\x89\xf6\x20\x48\x73\x3d\x83\xa0\x9d\xba\x0c\ +\xa6\xae\x9c\x06\x66\x0f\xda\xd7\xe2\x3d\xe5\x12\xef\x31\x43\x68\ +\x4c\xfb\x63\x1f\x20\x40\x50\xd7\x0a\x8f\xde\xb9\x82\x32\xdb\x0c\ +\x82\xfa\xbb\x35\x12\x36\x06\xee\x7b\xbd\xfd\xca\x8d\x8e\x7c\xb4\ +\x60\x7b\x7f\x86\x1d\xd8\x33\x5e\x86\x03\xba\x24\x3f\xa9\x82\x61\ +\x52\xdf\x49\x93\xa9\xd3\x3d\xda\xc7\xbd\x7b\x63\xe9\x30\xbb\x4b\ +\x1c\x8a\x94\x4e\x59\xc9\x0c\x55\xe7\x6c\xc7\x30\x82\xf1\x21\xf1\ +\x86\xe4\xbd\x4d\x84\x8c\x80\xc6\x3d\xb7\x35\xea\x4c\x78\x46\x5b\ +\xd2\x1f\x52\x4a\x1d\x78\x35\x3d\x07\xc9\x73\x7f\x86\xb9\x4f\x87\ +\x9e\xc0\x3e\x9d\x6b\xcf\x96\xbc\xbf\xda\x17\x85\xed\xa0\x51\x57\ +\x0b\xd6\x6d\x0e\x06\xf5\xb0\x67\xc0\x30\x81\x7d\xa5\xdf\x32\x99\ +\x27\x7d\x83\x4f\x46\x6e\xdf\x98\x94\xa1\x55\x29\xf5\xac\x2d\xfa\ +\x75\xdf\xe2\x09\xa7\x79\x1e\x62\xdb\xbe\xa6\x3b\x03\x44\x0a\xaf\ +\xdf\xad\x00\x3b\xee\x8b\x39\x60\xca\x70\x53\x19\xce\x34\x58\xc0\ +\x4b\xb3\x94\xe2\x02\x6f\xb9\x6a\x36\x96\x42\xdc\x00\xdf\x4a\xb8\ +\x49\xb6\x0e\x21\x16\x3b\x20\x32\x76\x1f\xf9\xa2\x01\x3b\x08\x43\ +\x95\xdb\xd6\x0f\x24\x34\xfe\xdf\xc0\x33\x7f\x23\x21\x9f\xff\x61\ +\x1a\xee\x38\x9e\x76\xd6\x25\x2c\xef\x3a\x07\x79\xc0\x4b\x38\xee\ +\xd9\xc1\x49\x08\xc6\x75\xe2\xf5\x16\x35\x0a\x51\x05\x2f\x3f\xc9\ +\xf3\x73\x99\x7e\xb4\x40\x1e\x7e\x80\xe5\x53\xb7\xbc\x2a\xa4\x1c\ +\x37\x6c\xbc\x89\x5f\x06\x09\xe3\x06\xea\xb2\x63\xa2\xf6\x86\x14\ +\x0f\x1a\xf9\x2d\x3e\xdd\xfa\x67\xc1\x94\x22\xd4\x7f\xe0\xed\x36\ +\xf8\xb3\x4c\x86\x57\x36\x93\x31\x27\x21\xd8\xfb\xe6\xe2\x19\xec\ +\x86\x6e\xe0\x14\xf8\x49\xe6\x77\x3c\x9e\x7b\xa0\x74\xa4\xea\x41\ +\x97\xa0\xf5\x50\x02\xd5\x21\x8f\x7b\x7f\xc6\xbb\x9f\x8e\x77\x2c\ +\xa1\xb8\x95\xcc\x6d\x6a\x00\x6e\x40\x78\x06\x1b\xd0\xc5\x7c\x24\ +\x6f\x0e\x10\x36\x60\x2d\xf0\x0c\xe1\xe5\x3c\x00\x36\x77\x19\xa0\ +\x83\xeb\x67\x7c\x96\x6c\x24\x73\xe5\xf9\xd3\x45\x31\x0d\x41\xe3\ +\x93\x2d\x3c\x42\x7d\xe1\x9e\xb2\x96\xf5\x5b\xe5\xc7\x71\x8c\xbe\ +\x4d\x36\x56\xe8\x1a\x3c\xd1\xd6\xc0\x25\x54\x33\x47\xc3\x66\x5a\ +\x3f\x09\xc1\x57\xe0\x07\xdf\x6c\x4b\x60\x06\x2f\x41\x93\x74\x42\ +\x67\xb2\x0e\x97\x55\x05\x85\xd1\x75\xcf\xd8\xac\x0a\x3c\xdb\x77\ +\x38\xf3\xc2\x8d\xaf\xa7\x30\x9d\xe3\x13\x76\xe3\x8e\x87\x4d\x62\ +\x40\x30\xb0\x03\x5e\xeb\x01\xf8\x04\x45\x34\x86\x0e\x56\xf0\x30\ +\x4c\x75\xf4\x36\x21\x18\xe2\x1c\x59\x38\x82\xc7\xbd\x17\x6e\xcc\ +\xf4\x8b\x64\xc5\xd9\x72\xee\x50\x63\x17\xba\x34\xf4\x2f\x26\x0b\ +\xa8\x7e\xec\x2e\x23\xff\x76\x31\x01\xe7\xad\x3e\x74\x65\x7d\x72\ +\x31\xf9\xed\xcc\xc5\xe4\xd8\xdb\xf7\x82\x6d\x20\x2b\x33\x1c\xfe\ +\x81\x7f\x6f\x32\x79\x30\x84\x71\x7a\xf7\xcb\x75\x30\x6e\x7d\xd4\ +\x8e\x6a\xbc\x67\xec\xc5\xdb\xd0\x0d\xa6\x35\xc9\xd5\xec\x8d\xcb\ +\x69\xf4\xe2\x98\x70\xc3\xe4\x7d\xa2\xf7\x09\x6c\x35\x3b\x26\x95\ +\x94\x18\xdd\xe5\x54\x06\xb9\xb0\x18\xf3\x9e\xc3\x6b\xf8\x9f\xaf\ +\xe7\x7f\x03\x88\x7c\xd3\x3b\xed\x32\x4f\xdf\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x8f\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x41\x49\x44\x41\x54\x58\x85\xed\ +\xd3\xa1\x11\xc0\x20\x14\x04\xd1\x85\x9a\x28\x00\x93\x5a\x70\x14\ +\x83\x4a\x31\x99\xa1\x81\x14\x85\xc2\x22\xf9\x66\x9f\x3a\xb7\xea\ +\x40\x92\x14\x2c\xed\x51\xda\x98\x40\xbd\x54\xfd\xfe\xb7\x3f\x00\ +\xf9\x4a\x50\x3a\xf0\x05\x92\x24\x85\x5b\x1c\x18\x0a\x07\xd4\x09\ +\xe9\x09\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xd2\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x84\x49\x44\x41\x54\x58\x85\xed\ +\xd2\xb1\x0d\x82\x50\x18\xc4\xf1\xff\xf7\xdc\x81\xc4\x3d\x18\x80\ +\x4d\x2c\x6c\xe8\x1c\x41\x98\x81\x06\x13\x6b\x67\xb0\xb4\x77\x10\ +\x13\x76\xd0\xb3\x52\x21\x24\x76\x0f\x9a\xfb\x75\x97\xf7\x25\x77\ +\xc5\x03\x33\x33\xb3\x95\xc5\x34\x2a\xaa\x63\xb3\xc9\x59\x78\x6b\ +\x9b\x27\x84\x66\x03\xca\xba\xab\x90\x2e\xc0\x36\xe7\x80\x80\x01\ +\xb4\xbb\x9f\x0e\x57\x80\xf4\x7d\x91\xfa\xdc\xe5\x00\x82\xe2\x45\ +\x3a\x7f\x72\xfa\x77\xbc\x84\xdf\x80\x88\x1a\x78\xe4\x2e\x0c\x18\ +\x14\xec\x47\x79\x6c\xf9\x4f\x68\x66\x66\xb6\xba\x37\x95\x79\x1e\ +\x09\xc0\xb2\x67\x2f\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ +\x82\ +\x00\x00\x00\x85\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x37\x49\x44\x41\x54\x58\x85\xed\ +\xce\xc1\x0d\x00\x30\x08\x03\x31\xd4\xfd\x87\x04\x31\x08\x1d\x02\ +\x9e\xbe\x7f\x22\x47\x2c\xca\xea\xc9\xea\xd9\x7c\xbc\xcd\xf8\x22\ +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x0f\ +\x7e\x19\x07\x85\xa1\xbf\xac\xe9\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x01\xd2\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x84\x49\x44\x41\x54\x58\x85\xed\ +\x97\xcd\x4a\x23\x41\x14\x85\xbf\xd3\xba\xd5\x85\x32\xfa\x26\xe9\ +\x0c\x8a\x2f\x90\x61\x04\x03\x3e\x84\x60\x56\x62\xe6\x11\x26\x82\ +\x0b\x23\xb8\x1f\xdc\x0d\xd8\xe0\x22\x2f\x30\x20\xa6\x7d\x13\x15\ +\x07\x24\x6b\xfb\xcc\xc2\xae\x20\x49\x6c\x31\x76\x74\xc0\x3e\xab\ +\xe2\xd6\xa5\xce\x57\x3f\x14\xf7\xc2\x67\x97\x46\x03\xf5\x33\xaf\ +\x65\xb8\x8d\xa8\x0b\xbe\x94\x61\x62\xb8\xc5\xf4\x23\xd4\xe9\x37\ +\x75\xf1\x2c\x40\x9c\x78\x0f\x7c\x30\x09\xac\x24\x65\x58\xfb\x69\ +\x53\x87\x63\x00\x71\xe2\x75\xf0\x1f\xe0\x1e\xab\x15\x3d\xd0\xbb\ +\xdc\xd6\xdf\x32\x5c\xbf\xfe\xf6\x52\x36\x47\x03\xb9\x0b\x2c\xca\ +\xda\x08\x27\x31\x1f\x92\x6c\xef\x4b\x08\xab\x95\x36\x75\x5a\x86\ +\x71\x50\xbe\x91\xd3\x5a\x62\x09\xff\xca\x70\x1b\xf8\x0e\x10\x0d\ +\xb3\x44\x1d\x20\x7a\xa0\x57\xa6\xf9\x88\x7a\x00\x12\x71\x08\x0c\ +\x01\xc2\x83\x2b\xeb\xd8\x27\xe9\x6a\x4b\x77\xf9\x70\x65\x0c\xe0\ +\xa3\x54\x01\x54\x00\x1f\x0e\x30\xff\x52\x42\x7c\xe6\x1d\xe4\x9f\ +\xc0\xc2\x2b\xd7\x1e\x60\xfd\x48\x9b\x3a\x29\x4a\x2a\x3c\x81\xf8\ +\xdc\xab\xc8\xc7\x53\x98\x03\x2c\x20\x77\xe3\x73\xaf\x4e\x0d\xf0\ +\x1e\x2a\x04\x48\x37\x75\x8d\xb5\x0b\x0c\xa6\x58\x7b\x80\xd5\x4a\ +\x37\x75\x5d\x94\xf4\xe2\x1b\xc8\xef\xb0\xf0\x1e\xdf\xa2\xff\xfb\ +\x0a\x2a\x80\x0a\xe0\x5d\x01\x0c\xb7\xf0\x58\x40\xce\xca\xac\x96\ +\x78\x39\x1f\xde\x8c\x01\x60\xfa\x00\xd9\x1c\x8d\x59\x01\xc0\xe3\ +\xda\x36\x69\x08\x0c\x3f\xa2\x08\x75\x8c\xbf\x21\x77\x6b\x89\x05\ +\xf4\x9e\xd4\x70\x6f\x52\xbe\xf3\x86\xf0\x11\x90\x45\xa8\x13\xe6\ +\x26\x35\x26\x1d\x66\xf7\x36\x9e\x6f\x4c\x82\x42\x6b\x96\x97\xce\ +\x2b\xa3\xf3\x53\xea\xc6\x26\x9d\xd4\x9a\x55\xfa\x07\xf1\xe4\x84\ +\x86\xea\x09\x57\xf9\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ +\x82\ +\x00\x00\x04\x8a\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x3c\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4f\x88\x1c\x45\x14\xc6\xbf\xd7\x33\x99\xc4\x3f\x2b\x62\x16\ +\x15\x24\x78\x11\xff\x5c\x04\x77\x3b\x7a\xf0\xe0\x22\x26\x12\xc1\ +\x3f\x2c\x22\x1e\x04\x35\x9a\x99\xd9\x24\x33\xbb\x11\x09\x28\xea\ +\xb8\x98\x80\x41\x31\x6e\x8f\xba\x99\x4e\xc4\x1c\x44\xd1\x53\x0c\ +\x62\x64\x83\xb0\x90\x83\x91\xd9\x59\x30\x20\x82\x78\x10\x11\x49\ +\x84\x28\xea\x06\x75\x37\x5d\x9f\x87\x5d\x35\xe9\xea\x68\x26\xa9\ +\xaa\x2e\x70\x7e\xc7\x3a\xd4\xf7\xea\xab\x57\xaf\x5f\x75\xcf\x00\ +\x3d\x7a\xf4\xf8\x3f\x23\xa6\x26\x0a\xcb\x13\xcf\x43\xe4\x19\x01\ +\x48\xca\xb6\x99\xb8\x36\x6e\x6a\x6e\x9b\x04\xc6\x66\x12\x79\x16\ +\x40\x81\x40\x11\x82\x46\x58\x6d\x0e\x19\x9b\xdb\x22\xe6\x0c\x38\ +\x6d\x2e\x0a\xc8\xfd\x03\x23\x13\x83\x06\xe7\xb7\x82\x31\x03\x08\ +\xa8\xd4\x50\x5f\xa0\xe4\xe3\x70\xe4\xd5\xeb\x4c\x69\xd8\xc0\x98\ +\x01\x02\x30\x63\xb8\x1f\x2a\x38\xb8\x7a\xe3\xeb\xab\x4c\xe9\x98\ +\xc6\xe4\x11\x38\x13\xab\x98\x24\x53\x83\xe5\x97\xfb\x1d\x68\x75\ +\x8d\x0b\x03\x00\xe0\x7a\x91\xd2\x81\x5b\xd7\xef\xe8\x73\xa4\x77\ +\xd6\x58\x33\x80\xd4\x8e\x44\x38\xbf\xec\x82\x7d\xd7\xd4\xa2\xe5\ +\xb6\x34\xcf\x05\x6b\x06\x88\x40\x21\x55\x17\x08\xdc\x7e\xe9\x3c\ +\xde\x19\x6a\x34\x8a\xb6\x74\xbb\xc5\xf6\x11\x50\x80\xa4\x33\x61\ +\x78\xee\xe8\x65\xbb\x00\x1a\x6b\xc2\xce\x07\x07\x35\x80\x0a\x4c\ +\x9b\x20\x8f\x85\xe5\xe8\x45\xfb\xda\xff\x8d\x9b\x22\x28\x4c\xf7\ +\x08\x80\xc8\xd6\xb0\xda\xdc\xea\x44\xff\x5f\x70\xf5\x14\x00\x80\ +\x44\x1b\x21\x77\x0c\x96\x27\x1e\x77\x18\x83\x86\x4b\x03\xb2\xba\ +\x45\x88\x48\x6b\x75\x25\x1a\x76\x19\xc7\xa9\x38\x35\x60\xa9\x5b\ +\x4c\x9b\x10\x10\x78\x37\xdc\x10\xdd\xe1\x32\x96\xbf\xc5\x73\xd0\ +\x24\xa0\xd5\x84\x12\x02\xec\x0b\xab\xd1\xcd\xae\x83\xc9\xc3\x00\ +\x00\x42\xea\x85\xf1\x22\x10\x1f\x0d\x6c\xdc\x79\x83\xcb\x48\x72\ +\x32\x00\x10\x0a\x33\x6a\xc2\x4a\x49\x8a\x07\x6f\xda\xf4\xda\xd5\ +\xae\xe2\xc8\xcd\x00\x60\xb1\x26\xa4\x4d\x10\xf0\xaa\xc2\x49\x35\ +\x75\x63\x75\xf2\x72\x17\x31\xe4\x6a\x00\xb0\x64\x82\x7e\x6f\xb8\ +\xb6\xc4\x85\x03\xb7\xd4\xa2\x4b\x6c\xeb\xe7\x6e\x00\xb0\x78\x6f\ +\xa0\xfe\x3e\x61\x20\x59\xc0\xfe\xa1\x47\xde\x5a\x61\x53\xdb\x0b\ +\x03\x00\x40\x00\x85\x74\x26\x10\xb7\xcd\x95\x7e\x7d\xcf\xe6\xe5\ +\xc9\x1b\x03\x00\x00\x92\x61\x82\xe0\x9e\x13\xc7\xfa\xf7\xa0\xd1\ +\xb0\x12\xab\x5f\x06\x00\x80\x88\x62\xea\x06\x49\xf2\xe1\xf0\xe8\ +\xca\x97\x6c\xdc\x20\xfd\x33\x00\x84\x80\x0a\xd4\x5e\x31\x3e\x11\ +\x96\x9b\x4f\x99\x56\xf3\xd0\x80\x45\x44\x24\xd1\xca\xa2\x60\x7b\ +\x58\x8d\x2a\x26\x75\xbc\x35\x80\x00\x32\xba\x45\x80\x98\x0c\x2b\ +\xd1\xfd\xa6\x74\xbc\x35\x00\x00\x24\xbb\x65\x16\x00\x4d\x53\x1a\ +\x5e\x1b\x00\xe0\x4c\x75\xcf\xd8\x63\xd1\x9b\x97\x93\x59\x2c\x2d\ +\x3d\x6b\x93\xde\x34\xa5\xe1\xaf\x01\x02\x28\xa2\x90\xde\x7f\x81\ +\x6c\x6a\xb7\x6a\x6f\x98\x92\xf1\xd4\x00\x01\x49\x6d\xf1\xa4\x3c\ +\x37\x13\x9b\x5b\x3c\xe0\x6f\x0d\x08\xb4\x9d\x17\x44\x9d\x78\xf3\ +\x36\xd3\x42\x1e\x66\x80\x04\x7a\xe5\xe3\xdb\xed\x2b\x7e\xdc\x92\ +\xf1\x8d\xe1\xbc\xf1\x2b\x03\x08\x6d\xf1\x02\x7e\x48\xae\x58\x8f\ +\xf1\x71\xbd\x27\x30\x80\x47\x06\x48\x00\x41\x6a\xf1\x38\x54\xbc\ +\x30\x79\xa0\x13\x57\x16\x6c\xa9\xfa\x71\x04\x88\x00\x72\xfa\xce\ +\x13\xf8\x9c\x5c\x7e\xf7\xa7\x3b\xeb\xbf\xd9\x94\xf6\x21\x03\x24\ +\xbd\xf3\x20\xbe\x2e\x26\xea\xce\x4e\x5c\xf9\xd9\xb6\x78\xae\x06\ +\x70\xb1\xd7\x09\x52\x83\xdf\x17\x83\x64\xcd\x67\x7b\xc6\x8e\xb9\ +\x88\x21\xcf\x23\x20\xa2\x6f\xc0\x4f\xc2\x60\xed\xe1\x5d\xf5\x6f\ +\x5c\x05\x91\x4b\x06\x50\x32\x76\x1e\x38\xa1\x02\xdc\xd5\xde\xbd\ +\xf9\x0b\x97\xb1\xe4\x61\x80\x08\x35\xdd\x05\x12\xc3\xb3\x93\xf5\ +\xc3\xae\x83\x71\xfc\x71\x94\x59\x3b\x4f\x11\x3e\xd4\x89\xeb\x53\ +\x2e\x63\xf9\x0b\xa7\x35\x40\x20\xba\xe1\x64\xb5\xdd\x1a\x7d\xdf\ +\x65\x1c\xa7\xe2\x32\x03\x0a\xe9\x01\x01\x9f\x9e\x89\x47\x63\x87\ +\x31\x68\x38\x31\x80\x59\x3b\x0f\xbc\xd2\x6e\xd5\x73\xff\x99\x8c\ +\x83\x23\x20\x81\x40\xeb\xf2\xf6\x76\x5a\xb5\x27\x6d\x5c\x6e\xba\ +\xc5\x76\x06\x64\xdc\xec\xf0\x41\xdf\x95\xc7\x37\xf8\xb0\x78\xc0\ +\x62\x06\x90\x08\x24\xdd\xe2\x02\xd3\x17\xff\xd1\xf7\xe0\xf4\x78\ +\xfd\xa4\x2d\xdd\x6e\xb1\xf9\x43\xc9\xf4\xe2\x67\x0b\x25\xdc\x3b\ +\xbd\xf7\xd1\xdf\x6d\x69\x9e\x0b\xae\x1e\x83\x5f\xcd\xcb\xb2\x75\ +\x47\x9a\x23\xbf\x38\xd2\x3b\x6b\x5c\x18\xf0\x1d\xa9\xd6\x1c\x69\ +\x8d\xfc\xe0\x40\xab\x6b\x4c\xfe\x61\x22\xeb\x05\xfe\x71\x55\x48\ +\xd6\x76\xe2\xb1\x6f\x4d\xe9\x98\xc6\x58\x06\x64\xdc\xec\xe6\x44\ +\xa9\x75\xb3\xad\x2d\x5f\x9a\xd2\xb0\x81\xc1\x0c\xf8\xe7\x13\x16\ +\x21\x14\xf0\xbe\xf6\xee\xb1\xb6\xa9\xf9\x6d\x61\xf0\x5f\x63\xc1\ +\x76\x21\x12\x40\x12\x80\x2f\xb4\x5b\xa3\x9f\x18\x9b\xbb\x47\x8f\ +\x1e\x3d\x2c\xf1\x27\x17\xaf\x43\xaf\x5e\x06\xce\xc3\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x08\xd7\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x08\x89\x49\x44\x41\x54\x78\x9c\xed\ +\x5b\x6d\x70\x54\xd5\x19\x7e\xde\x73\x77\x37\xb0\x24\x7c\x64\x11\ +\x13\xd4\xd1\xa0\x65\x30\x54\x66\x60\xb3\x50\xd4\x46\xb0\x76\xa4\ +\x1d\xc1\x62\xbb\x56\xed\xa8\x80\x24\x21\x40\x56\x60\xac\x1d\x9c\ +\xd1\x4b\x5a\xa9\xf5\x2b\x26\xbb\x60\x08\x04\x0a\x2a\xd3\x19\xd3\ +\x11\xa6\x38\x80\x4c\x6b\xc3\x50\x0b\x21\x1b\xed\x50\x05\x3a\x7e\ +\x80\x94\x49\x88\x95\xcf\x60\x24\xd9\xdd\xf3\xf6\x47\x10\xee\xc7\ +\xee\x66\x6f\x72\x37\x86\x36\xcf\xbf\xfb\x9c\xe7\xbc\xfb\xdc\x77\ +\xcf\x3d\x7b\xee\x39\xef\x02\x03\x18\xc0\x00\xfe\x9f\x41\x7d\xf1\ +\x21\x13\xe7\x06\xaf\x52\x32\xa8\x10\x90\xb7\x80\x69\x1c\x08\x63\ +\x98\x31\x9c\x80\xa1\x00\x14\x80\xce\x01\x38\x07\xe6\x63\x20\x1c\ +\x02\x70\x50\xc4\x68\xcf\xfe\xda\xb2\x23\xe9\xf6\x96\xb6\x04\x78\ +\x8b\x83\x37\x0a\xc2\x1c\x66\xcc\x02\x61\x42\x0f\xc3\x1c\x61\xf0\ +\x0e\x21\x79\x63\xe3\xba\xc7\xc3\x00\xb1\xad\x26\x61\x7b\x02\x98\ +\x7c\x25\xc1\xbb\x19\xf4\x24\x80\xe9\xf6\xc6\xc6\x87\x04\xaa\x90\ +\xec\x7a\xa3\x69\x6d\x49\xc4\xae\xa0\xb6\x25\xc0\x5b\x5c\x35\x9d\ +\x88\x5e\x00\x50\x60\x57\xcc\x78\x60\xe0\x28\x98\x57\x34\xad\x0d\ +\xbc\x66\xc7\x88\xe8\x75\x02\xa6\xcc\xaf\xbc\x3a\xaa\x88\x97\x09\ +\xf8\x45\x12\x99\x24\xe0\x3d\x10\xd7\x4b\x29\x0e\x03\xb1\x4f\x1d\ +\x44\xa7\xa4\xe2\x68\x8b\x7e\x1d\x8b\x29\x83\xa2\x59\x60\xc7\x30\ +\x62\xe4\x49\xa6\xb1\x04\x9e\x0a\xc2\x0f\x01\x0c\x4e\x62\x7c\x0f\ +\xa4\x28\x6d\x5c\xb7\xf8\xa3\xde\xf8\xef\x55\x02\x0a\x16\x04\x27\ +\x83\xb1\x15\x40\x6e\x9c\xe6\x36\x00\xdb\x89\xb0\x8d\x14\xb1\x73\ +\xff\xea\xc5\x27\xad\xc4\x9e\xba\xb4\x62\x70\xe7\x57\x8e\x3b\x09\ +\x98\x09\xc2\xac\x04\x9f\x71\x01\xc0\xbc\x70\x4d\xe0\x0f\xd6\xdd\ +\x77\xa1\xc7\x09\xf0\x16\x87\x1e\x22\xe2\x0d\x00\x32\x4c\xa6\x98\ +\x83\x1d\x8a\xf3\x77\xff\xac\x5e\x78\xba\xa7\xf1\xb5\xc8\xf7\xab\ +\x2e\xf7\x88\xec\x22\x22\x7a\x86\x81\x51\x26\x01\xd3\xca\x70\xee\ +\x97\xcf\xa0\xbc\x5c\x5a\x8d\x6d\x3d\x01\xaa\x2a\xbc\x27\x46\x3e\ +\x4b\xe0\xe5\x86\x16\x49\x84\x0d\x22\x8a\xf2\x86\xda\xc0\x71\xcb\ +\x71\x53\xc0\x6d\xf3\x9e\xcf\xea\x70\xb8\x97\x81\xf8\x09\x00\x99\ +\x86\xe6\xad\xed\x8a\xf2\xf0\xc1\x57\x17\x9d\xb7\x12\xd3\x5a\x02\ +\x54\x55\x14\xb4\x8c\xdc\x0c\xe2\x07\x74\x3c\xa3\x19\x02\xb3\xc3\ +\x6b\x02\xfb\x2d\xc5\xeb\x21\xa6\xcc\x0f\x5e\x1b\x53\xb0\x05\xe6\ +\x09\xf7\x03\xc5\x85\x69\x0d\xa1\xc0\xb9\x54\x63\x09\x2b\x1f\xec\ +\x6b\xcd\x5e\x61\xbc\x79\x02\xf6\x31\x62\x05\x7d\x75\xf3\x00\xd0\ +\x50\x1b\x38\xee\x74\x47\x0b\x19\xd8\x6c\x68\x9a\x28\x3b\x79\xb3\ +\xdf\xff\xa6\x92\x6a\xac\x94\x85\xbe\x92\xd0\xcf\x19\x08\x69\x39\ +\x22\xda\x34\xa4\x23\xcb\xbf\x77\x7d\xe9\x99\x54\xe3\xd8\x85\xe3\ +\xfb\xde\x89\xb6\x34\x6d\xdf\x32\xda\xd7\xd8\x0e\xe0\x2e\x5c\x1a\ +\xcd\x34\xf6\xcc\xa0\xb6\x41\xcd\x4d\x3b\xff\x9c\x4a\x9c\x94\x1e\ +\x81\xc9\x25\xa1\x02\x09\xde\x03\x60\xd0\x65\x96\xdf\x08\xd7\x04\ +\x1e\x49\xc7\xea\xcc\x2a\x0a\x8a\x83\x4b\x40\x78\xc5\x40\x3f\x1a\ +\xae\x09\xbc\xd6\x5d\xdf\x6e\x1f\x81\xc9\x8b\x56\x79\x62\xc0\x56\ +\xe8\x6e\x1e\xfb\x33\x3b\x86\x16\xf5\x87\x9b\x07\x80\xf0\xda\xb2\ +\x2a\x80\x7f\x6f\xa0\xd7\x79\x8b\x57\x4d\xea\xae\x6f\xb7\x09\x90\ +\x11\xf9\x02\x81\xaf\xb9\x44\x30\x9a\x63\x4e\x9a\x5d\xbf\x71\xee\ +\x05\xeb\x56\xd3\x05\xe2\x33\x2e\x2a\x05\xe1\xef\x1a\xd2\x45\x24\ +\xd7\x4d\x53\x55\x47\xb2\x9e\x49\x13\xe0\x2d\xae\xbc\x1d\x84\x79\ +\x1a\x8a\xa5\x82\x9f\x7e\xb0\xaa\xac\xb9\x37\x76\xd3\x81\x4f\x42\ +\x81\x0e\x25\x2a\xef\x03\xf0\xa5\x86\x9e\xd4\xd6\xe2\x59\x98\xac\ +\x5f\x92\x04\x30\x11\x89\xe7\x0c\xdc\xe6\xf7\xab\x03\xfb\x7a\x6e\ +\x33\xbd\x68\xa8\x5d\xd2\x0a\xc6\x4a\x2d\x47\x84\xa7\x27\x3c\xfc\ +\xe2\x90\x44\x7d\x12\x26\xc0\x57\x14\x2a\x04\x70\xbb\x86\x8a\x40\ +\xc4\xd4\xde\xdb\x4c\x2f\x32\x3b\xb3\xd6\x00\x38\xa6\xa1\x46\x3a\ +\xdd\xae\x92\x44\xfa\x84\x09\x60\x81\x5f\xea\x09\xd4\x84\xab\x97\ +\x7d\xd6\x6b\x87\x69\x46\xfd\xc6\xb9\x17\x88\x60\xf8\xa2\xc4\xb2\ +\x44\x6b\x83\xb8\x09\xf0\x2d\x5c\x9d\x03\x60\x86\x86\x8a\x28\x52\ +\x3e\x6b\x97\xc9\x74\xe3\x86\x93\x39\xaf\x33\xf0\xf1\x37\xd7\x04\ +\xbe\xe6\x53\x4f\xeb\x5d\xf1\xb4\x71\x13\x20\x63\xd1\x87\xa0\x59\ +\x24\x11\xf0\x6e\x43\xed\x92\x56\xdb\x9d\xa6\x09\x75\x75\xf7\xc7\ +\x88\x50\xa7\xe5\x04\xf3\xa3\xf1\xb4\x71\x13\x40\xa0\x99\x06\xe6\ +\x4f\x76\x99\xeb\x2b\xb0\x94\x46\xcf\x3f\x8e\xf7\x18\x98\x12\x70\ +\x71\xc6\xbc\x55\xcb\x49\x8e\xbd\x6d\xaf\xbd\xf4\xa3\x29\xf7\x74\ +\x23\x00\xed\xa8\x1d\x76\xc4\x73\xc2\x6b\xd4\x99\x12\x90\xe1\x76\ +\x7d\x0f\x80\xeb\x32\x43\xff\x68\x5a\xbb\xe4\x98\x51\xd7\xef\x51\ +\x5e\x2e\x01\xd6\x7d\x71\xcc\xe6\x7d\xca\x38\x8f\x80\xf8\xae\x81\ +\xd8\x63\xab\xb1\x3e\x04\xb3\xde\x3b\x31\xc6\x1b\x35\xa6\x04\x30\ +\xf3\xcd\xba\x6b\xc8\x8f\x8d\x9a\x2b\x05\x82\xa1\xf7\x4e\xb8\xd9\ +\xa4\x31\x12\x44\xb8\x41\x47\x30\xf5\xfb\xdf\xfe\x84\x70\x3a\x8c\ +\xde\xf3\x8c\x12\xf3\x08\x20\x64\x69\xaf\x49\x50\x9f\xbf\xeb\xdb\ +\x85\x21\xed\x6e\xa3\xf7\x2c\xa3\xc6\x3c\x07\xb0\x5e\x24\x98\x2d\ +\xed\xb1\xf5\x27\xd4\x6f\x9c\xd3\x01\x20\xaa\xa1\x5c\xf9\x7e\xd5\ +\xa5\xd5\xc4\x5b\x07\xe8\x36\x49\xa2\x42\xf6\x8b\x77\xfe\x74\x21\ +\x5e\x02\xda\x74\x02\x56\x4c\xc3\xe6\x4a\xc1\xb4\x39\x1b\x33\x00\ +\x68\xf7\x03\x3a\x0f\xd6\x95\x77\x6a\x35\xe6\x49\x10\xd0\xed\xa8\ +\xb2\xe4\xe1\xe9\xb1\x97\x7e\x7c\xed\x38\x3b\xcc\x40\xb5\x19\x35\ +\xe6\x49\x10\xf4\xb9\xf6\x9a\x84\x79\xe6\xbc\x52\xc0\x8a\x63\x8c\ +\x9e\xc0\x51\xa3\x26\xce\x24\xc8\x87\xb4\x97\x04\x7c\xc7\x66\x5f\ +\x7d\x06\x09\xa9\xf3\xce\x84\xc3\x46\x8d\x39\x01\x24\x74\x87\x8d\ +\xcc\xba\x4d\x91\x2b\x0a\x0c\x83\x77\xa6\x0f\x8d\x1a\x53\x02\xda\ +\x15\xda\x0b\x40\x7b\xfe\x3e\x69\xca\xfc\xe0\xb5\xb6\xbb\x4b\x37\ +\x54\x55\x10\x70\x8f\x96\x62\x85\xeb\x8d\x32\x53\x02\xba\xce\xd6\ +\x68\xaf\x96\x8b\x2a\x74\x8f\x51\xd7\xdf\xe1\x6b\x1e\xe1\x85\xfe\ +\x44\xf9\xdc\xd0\x51\x27\xc3\x46\x5d\xfc\x2d\x31\xd6\xbf\x45\x11\ +\xf1\x2c\x5b\xdd\xf5\x05\x84\xd0\x79\x66\x60\x67\x7d\x79\x79\xd4\ +\x24\x8b\xd7\x37\xe6\xa2\xcd\x00\x2e\x1f\x35\x33\xee\x9c\x38\x37\ +\x78\x95\xdd\x1e\xd3\x06\x55\x15\x0c\xfc\x4c\x4b\x11\x78\x53\x3c\ +\x69\xdc\x04\x5c\xdc\xf7\xdf\xa5\xa1\x32\x14\xa7\xe9\x38\xbc\xdf\ +\xc2\xd7\xea\x79\x10\xc0\x38\x0d\x75\x22\x33\xe7\xd4\xae\x78\xda\ +\x84\xbb\xc2\x04\x7e\x49\x4f\xd0\xa2\x89\x8b\x56\x5d\x6f\x8b\xc3\ +\x34\x22\xdf\xaf\xba\x98\xf1\x1b\x1d\x49\xf4\x4a\xbc\xe1\x0f\x24\ +\x49\x40\x63\x4d\xe0\x5d\x00\xda\xc9\xd0\x25\xa2\x72\x85\x1d\x26\ +\xd3\x09\xb7\xc7\x53\x0c\xfd\x6b\xef\xa9\x8c\xce\xf6\xea\x44\xfa\ +\x24\x27\x43\xc4\x20\x7a\x4a\xc7\x00\x8f\x4c\x2a\xad\x32\xed\xab\ +\xf5\x17\x78\x8b\x5f\x1a\x49\x8c\xa7\xb5\x1c\x33\x7e\xfb\xde\x86\ +\x5f\x99\x96\xc0\xdf\x20\xe9\xd9\x60\x78\x4d\x59\x3d\x18\xaf\x6b\ +\xf5\x42\xd2\x96\x29\xf3\x2b\xaf\xee\xa5\x57\xdb\x91\xef\x57\x5d\ +\x24\x5c\x7f\xd4\xd5\x10\x31\x0e\x00\x19\xc1\x64\xfd\xba\x3d\x1d\ +\xee\x14\xce\x27\xa0\xdf\x5d\xbd\x2e\xe6\x10\x6f\xdd\x54\x16\x34\ +\x16\x47\x7d\xab\x70\x67\x67\x57\x81\x71\x87\x86\x8a\x40\xa0\xa8\ +\xbb\xa2\xca\x6e\x13\x70\x60\x4d\xe9\x17\x52\xe0\x27\x00\x3a\x2e\ +\x91\x8c\x5b\x87\x77\xe0\x55\x80\xfb\xa4\xd6\xb8\x3b\xf8\x4a\x42\ +\x0b\x01\x5a\xa0\x67\xa9\x34\x95\xb2\x9d\x94\x4a\x64\x5a\xc2\x3b\ +\x8e\x8f\xf6\xcd\xf8\x1c\xa0\xd9\x97\xe3\x63\xe2\xe8\x82\xc6\xdc\ +\xe1\x63\x26\xef\xfa\xcf\xc1\xdd\x31\x8b\x9e\x6d\x02\x93\xb7\xd8\ +\x13\x00\xa1\x0a\xfa\x8d\x9c\xca\x70\x4d\xe0\xb9\x44\xbd\xb4\x48\ +\xb9\x46\xa8\x39\xbc\xf3\xc0\x68\xef\x0c\x37\x88\x6e\xd3\xd0\x5e\ +\xa7\xdb\x5d\x98\x3b\xe9\x07\x6f\xb7\x34\xed\x6a\x4f\x35\x96\x1d\ +\xc8\xf7\xab\xae\xeb\xbf\x7f\xa0\x86\xba\x26\xea\x4b\x37\x4f\xc0\ +\x3b\x99\x39\x27\xe7\x1e\xdd\xbd\x3b\xa5\x9a\x41\x4b\x55\x62\x79\ +\xa7\x73\x9f\x62\xd0\x16\x1d\xc9\xb8\x03\xe4\x6a\xf4\x16\x87\x6e\ +\xb1\x12\xab\x37\x98\xb0\xa0\x7a\x94\x3b\xdb\xf3\x17\x80\x1e\x33\ +\x34\x7d\x14\xe9\x88\x3d\x90\xe8\x37\x3f\x1e\x2c\x3f\xc3\x7e\xff\ +\x9b\xca\x91\x11\x2d\x2f\x82\x68\xa9\xa1\x29\x42\x84\xea\x0e\x38\ +\x57\x1e\x58\x53\xfa\x85\xd5\xb8\xa9\x60\xea\xd2\x8a\xc1\x91\xaf\ +\x1c\x8b\x41\x58\x0e\x60\x84\xae\x91\xb0\x83\x65\xc6\x83\x4d\x6b\ +\x4b\xce\x5a\x89\xd9\xe3\x49\xac\xa0\x24\xf4\x18\xc0\xd5\x00\x9c\ +\x86\xa6\xf3\x20\x7e\x59\x71\x52\x85\x95\x82\xc5\x64\x98\xa6\xaa\ +\x8e\xb6\x96\xec\x39\x20\xb1\x42\x57\xaf\x74\x19\x15\x79\xa7\x72\ +\x9e\xac\xab\xbb\xdf\xf2\x5c\xd4\xab\x59\xdc\x57\x52\x59\xc8\x10\ +\x6f\x01\xf0\xc4\x69\x3e\x0d\x60\x1b\x80\x6d\x8a\x0b\xbb\xac\x26\ +\x23\xdf\xaf\xba\xdc\xc3\x3d\x85\xa4\x60\x26\x4b\xdc\x0b\x42\xbc\ +\x65\x78\x04\xa0\xd2\x70\x4d\xd9\xfa\x1e\xd8\x07\x60\x43\xb9\xbc\ +\x6f\xe1\xea\xeb\x38\x16\xab\x04\x70\x5f\x12\x59\x04\x84\xdd\x90\ +\xf8\x2b\x04\xfd\x4b\x30\x7f\xc2\x8a\x72\xea\x02\xd3\x79\xb7\x23\ +\x1a\x13\x91\x68\x96\x64\xc7\xb0\x28\x23\x8f\x04\x8d\x05\xcb\xa9\ +\x00\xdd\x8d\xae\xbf\xd4\x24\x72\xde\x28\x89\x4b\xdf\xaf\x7e\xbc\ +\xa9\x37\xfe\x6d\xfb\x1d\x2f\x28\x0a\xfd\x08\x82\x9f\x07\x90\xde\ +\xc9\xb0\xab\x2e\xf9\xd7\x79\x27\x73\x6a\x7b\x32\xe4\x8d\xb0\x77\ +\x21\xa3\xaa\x62\x72\x6b\xf6\xbd\x12\xb4\x1c\x0c\x9f\xad\xb1\x41\ +\x9f\x81\x65\x45\x66\xe7\xd0\xf5\x76\xd6\x28\xa6\x6d\x25\xe7\x2b\ +\x5a\x35\x5e\x0a\x9e\x43\xe0\x59\x00\xc6\xf6\x30\xcc\x09\x30\xb6\ +\x13\xc9\x4d\x8d\x39\xa7\xff\xd6\x93\xff\x03\x74\x87\x3e\x59\xca\ +\x5e\x9c\x27\xa6\x83\x79\x3c\x40\xe3\x40\xc8\x03\x30\x0c\x5d\xcf\ +\xb8\x83\x41\x67\x89\x71\x0e\xc4\xff\x26\xc2\x61\x29\x71\xd8\x41\ +\xd8\xdd\x50\x53\x76\xa8\xbf\x94\xe3\x0e\x60\x00\x03\xf8\xdf\xc4\ +\x7f\x01\x33\x41\xc7\xce\x61\x76\x81\xea\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\x77\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x29\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4f\x88\xdb\x45\x14\xc7\xbf\x6f\x92\xad\x55\xd9\x5e\xb6\x78\ +\xa9\xc5\x9b\x7f\xc0\x93\x95\x1e\xbc\x18\x6a\x92\x1a\xa1\x5b\x1b\ +\xb2\xa2\x54\xb0\xdd\x64\xb5\x20\x1e\x14\x29\x28\x6a\x0c\xb6\xa0\ +\x08\x16\x2a\xe8\xba\x49\x64\x0f\x56\x51\x37\xe9\xba\x88\x5b\x93\ +\x2c\x2c\x08\x2a\x88\x82\xd0\x22\x88\x07\x91\x56\x50\x28\x45\x69\ +\x89\x74\x93\x79\x1e\xb2\x5b\xd2\xdf\xfc\x0a\x9b\xee\xcc\xfb\x0d\ +\x34\x9f\xdb\xce\xe1\x7d\xdf\x7c\x99\x79\x33\x6f\x33\x3f\x60\xc8\ +\x90\x21\x37\x32\x64\x2b\x50\x32\x3b\xf9\x3a\x11\xbd\x02\x28\x66\ +\xe6\x23\xad\x7a\xa5\x64\x2b\xb6\x4b\x94\xad\x40\x44\xea\x55\x80\ +\x62\x00\xc7\x41\x28\x26\x73\x85\x84\xad\xd8\x2e\xb1\x66\x40\x7f\ +\x2c\x02\x08\x8c\x85\xf4\x44\x61\x87\xc5\xf8\x4e\xb0\x69\x80\xee\ +\xff\x83\x80\x51\xee\xe2\xd4\xc3\x13\x93\x77\x59\xd4\xb0\x8e\x4d\ +\x03\xd8\x18\x21\x6c\xed\x6a\xd5\x4c\xef\x3d\xb8\xdd\xa2\x8e\x55\ +\x6c\x1a\x70\x2d\xb6\x73\x3c\xd6\x48\x3c\xf1\xf4\x56\x01\xad\x81\ +\x91\x30\x00\x00\xee\x1e\xb9\xac\x17\xc7\xc7\x27\x47\x85\xf4\xd6\ +\x8d\x33\x03\x98\x39\xb8\x25\xee\x6f\x6f\x52\xf3\x99\xcc\x73\x37\ +\xb9\xd2\xbc\x1e\x9c\x19\x40\x44\x1a\xc1\xba\xc0\xd8\xd5\xb9\xa5\ +\xfd\x71\x22\x51\x8c\xbb\xd2\x1d\x14\xd7\x5b\x40\xc3\x5c\x09\xd9\ +\x91\xb1\x73\xd3\xb0\x78\x09\xdb\x08\xee\x6b\x40\xd8\x4a\x00\xf2\ +\xa9\xdc\xd4\x9b\xce\xb5\xd7\x81\x54\x11\xd4\xc6\x08\xf3\xe1\x54\ +\x36\x7f\x58\x48\xff\x9a\x48\x19\x00\x00\x5d\x63\x84\xe8\xad\x54\ +\x2e\x5f\x10\xcc\xc1\x40\xd2\x80\xb5\xed\x70\x35\x4c\x1f\x24\x73\ +\x85\xac\x68\x1e\x7d\xc8\x1a\xc0\xcc\x20\x63\x3b\x28\x62\x7c\xf2\ +\x50\x76\x2a\x29\x9a\xcb\x9a\xb8\xb8\x22\x83\x61\xd6\x84\x4d\x8a\ +\x78\x7e\xf7\x44\x7e\xa7\x74\x3a\xf2\x06\xf4\x60\x32\xb7\xc3\xad\ +\x5a\xd3\x57\xc9\x7d\x85\x7b\x24\x13\x89\xca\x80\xb5\x9b\x62\xd0\ +\x84\x31\x52\x68\xee\xca\xe6\xef\x90\xca\x23\x32\x03\x56\x61\x32\ +\x6b\xc2\xb6\x18\x51\x23\xbd\xef\xd0\x6d\x12\x09\x44\x6d\x00\x98\ +\xc1\x80\x71\x5b\xbc\x53\xab\xce\x62\x66\xff\xfe\x2d\xae\xf5\x23\ +\x37\xa0\x87\x79\x5b\x24\xe0\xbe\x4e\xfb\xe6\x85\xc4\x81\x03\x9b\ +\x5d\x2a\x7b\x62\x00\x00\x40\xf7\x56\x43\x1f\x84\x07\x47\x2e\xc6\ +\x3e\x75\xd9\x3c\xf9\x64\x00\x88\x48\xb3\xd1\x41\xd2\xf8\xc8\xd8\ +\xb9\x4a\xb1\x58\x74\x92\xab\x57\x06\x00\x0c\xea\x9d\x0c\xc1\x9a\ +\xf0\xd4\xb7\xa7\xcf\xbe\x0d\x07\x1d\xa4\x67\x06\x5c\xc1\xbc\x32\ +\x83\x5e\x48\xe5\x0a\x2f\xd9\x16\xf2\xd5\x00\x00\x64\x36\x4f\x8c\ +\xa3\xa9\x5c\xfe\x19\x9b\x2a\x1e\x1b\xc0\x00\xa0\x8d\xcd\xc0\xf4\ +\x7e\x3a\x5b\xc8\xd9\x52\xf1\xd8\x00\x00\xbd\xa2\x10\xdc\x0e\x04\ +\xc2\xbb\xb6\x04\x7c\x37\x00\x14\x52\xf6\x98\x61\xed\x58\xf4\xde\ +\x00\xe6\xb0\x1c\xb9\x6a\x2b\xbe\x37\xff\x9d\x0d\x87\x63\xc1\x93\ +\x8f\x88\x9e\x6d\xd4\x2a\xef\xd9\x52\xf0\x78\x05\x98\x93\x07\xe1\ +\xb5\xc6\x5c\xd9\xda\xe4\x01\x7f\x0d\x50\x21\x77\x9e\xe3\xcd\xb9\ +\xca\x11\x07\x42\x3e\x41\x00\xb3\x82\x39\xfb\x8f\x1e\xb8\x77\xdb\ +\xf3\x08\xfb\x01\x76\x83\x78\x56\x03\xb4\x02\x5d\x5d\xf7\x19\xf8\ +\xf2\xc2\x98\x9a\x2c\x95\x4a\x21\xb7\xc3\x8d\xe3\xcd\x0a\xe0\xde\ +\xb2\x0f\x4e\xfe\x9b\x4b\x6a\xf4\xb1\x1f\x67\x66\x56\x5c\xe9\x7a\ +\x61\x00\x33\x14\x99\x15\xef\x67\x28\xb5\xe7\xbb\xcf\x8f\xb5\x5d\ +\x6a\x47\xbf\x05\x88\x88\xc0\xc1\x3d\xff\x9b\x5e\xe1\xdd\x4b\x0b\ +\xe5\x7f\x5c\xcb\x47\xbb\x02\x88\x68\xb5\xe8\xf5\x8d\xe1\xcf\x58\ +\x37\x9e\x5a\x5a\xa8\xfc\x25\x91\x42\x64\x06\xf4\x1e\x52\x05\x26\ +\xcf\xb8\xa0\x98\xd2\xa7\xe6\xa7\x7f\x97\xca\x23\x2a\x03\x88\x4d\ +\xed\x4b\x0c\x3c\xf2\x75\xad\x7c\x46\x32\x11\x79\x03\x08\x14\xa2\ +\xbb\x02\xd2\xd9\x56\xbd\xf2\xbd\x74\x3a\xd2\x06\x10\xb4\xa1\xc9\ +\x0c\x7a\xb2\x39\xf7\x61\x43\x38\x17\x00\xf2\x06\x28\xe3\xb0\x63\ +\x1c\x6a\xd5\xca\x9f\x09\xe7\x71\x05\xc9\x63\x30\x16\x1c\x20\xe6\ +\x97\x1b\xf5\xea\x8c\x60\x0e\x06\x52\x2b\x20\xac\xa7\x7f\xa7\x51\ +\xaf\x46\xfe\x4c\xc6\xbd\x01\xa1\xcd\x0d\xcf\x36\x6b\xd5\x17\xe1\ +\xa0\xb9\x19\x14\xd7\x06\x18\xcd\x0d\x01\x5f\xac\x9c\xbf\x7d\x0a\ +\x1e\x4c\x1e\x70\xfb\x50\x32\xac\xad\x5d\xbe\x3c\xda\x79\x7c\x79\ +\xb9\xd4\x71\xa5\x3b\x28\x2e\x1f\x4a\x06\x3b\xbb\x9f\xe2\x9b\xdb\ +\x7b\x97\x67\x67\xff\x73\xa5\x79\x3d\x48\x15\xc1\x5f\x95\x8e\x67\ +\x16\x4f\x9c\xf8\x57\x48\x6f\xdd\x48\x18\x70\x96\x95\x4a\x35\x4e\ +\x4e\xff\x2d\xa0\x35\x30\x36\xef\x01\x61\x3f\x5c\x9e\x67\x8d\x74\ +\xab\x36\xf3\x87\x45\x1d\xab\x38\xf9\x64\x66\x95\x8b\x9a\x29\xd3\ +\x3a\x59\xf9\xc5\xa2\x86\x75\xec\x7d\x34\x85\xfe\x57\x5f\xcc\x20\ +\x7e\x74\xa9\x5e\xfe\xc1\x56\x7c\x57\x58\xfc\x6a\x8c\x8f\x82\xd0\ +\x05\xb8\x0b\xe0\x8d\xe6\x5c\x75\xc9\x56\xec\x21\x43\x86\x0c\x71\ +\xc5\xff\x03\xa1\x32\xbd\x29\x9d\x1e\xd2\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x68\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x1a\x49\x44\x41\x54\x58\x85\xed\ +\xc1\x01\x01\x00\x00\x00\x82\x20\xff\xaf\x6e\x48\x40\x01\x00\x00\ +\x00\xef\x06\x10\x20\x00\x01\x47\x01\xa0\x88\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x03\x17\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\xc9\x49\x44\x41\x54\x78\x9c\xed\ +\xd6\x4d\x48\x54\x51\x18\x06\xe0\xf7\xbd\x5e\x4b\xb2\x20\x82\xa0\ +\x08\x8c\x56\x41\x41\x54\xd2\x38\x1a\x84\x45\x04\x26\x29\x26\xcc\ +\x22\xca\x12\xa2\x9f\x45\x8b\x08\xa2\x82\x90\xa0\x45\x60\x05\x6e\ +\x82\x28\x88\x6a\x11\xf8\x33\x57\xa4\xbf\x4d\xf4\x03\xe6\x38\x30\ +\x81\x9b\x16\x19\x05\xad\xa2\xac\xb0\x20\x35\xaf\xf7\x6d\x23\xe4\ +\x5c\x2b\xcc\xb9\x33\x41\x7d\xcf\xf2\x7c\xe7\xbc\x7c\xe7\xbb\x1c\ +\x66\x00\x63\x8c\x31\xc6\x18\x63\x8c\x31\xc6\x18\x63\x8c\x31\xc6\ +\xfc\x2f\x98\x6b\x40\x45\xb7\x56\x21\xd0\x0d\x00\xcb\x04\x5e\x4c\ +\x37\xe0\x3c\x48\x45\xd0\xdb\x4f\xc5\xba\xd4\x00\xaa\x15\x00\x1c\ +\xf2\x48\xaa\x81\xf7\x72\xc9\xcb\x7d\x00\xc9\xe0\x31\x80\x4d\x3f\ +\x12\x75\xf3\xcb\xb8\xb3\xff\x79\x82\xdf\x72\xcd\xce\x22\x31\xee\ +\xe1\xb8\xa0\x73\x53\x56\x87\xfd\xf7\x5c\x9c\x39\xc8\xf1\xd9\xc6\ +\x3a\x11\xb4\x96\x9d\x21\xee\x59\xe0\xea\xfe\x5a\x4f\x0b\x23\xc8\ +\x06\x00\x54\x3f\x94\x1b\xf7\x82\x4b\xa1\xcb\x03\x11\x7c\xc0\x9c\ +\x07\x30\x01\x1e\x06\xf0\x2e\xb4\xbc\x79\xae\xd4\x5b\xd5\xa5\xe5\ +\xb9\xe6\x57\xb7\x6b\xfe\xc8\x27\x75\x0b\x3c\x34\x75\x5d\xc0\x18\ +\x1d\xee\xce\xe5\xeb\x03\x11\x4c\x10\x00\x62\x3d\x5a\x41\x5f\xf7\ +\x00\xac\x0c\x95\xde\x52\xac\x4d\x35\xf2\xd9\x6c\x72\xcb\xbb\xb4\ +\xd4\xa5\x6e\x03\x58\x1f\x2a\x7d\xa4\x58\x97\x6a\x64\xef\x6c\x72\ +\xa7\x8a\xe2\x09\x20\x5d\xc7\xd7\x8e\xcf\x2a\x00\x4f\x42\xa5\x25\ +\x82\x9e\xc4\xba\x54\xfb\xa7\x99\x1b\x3a\xb5\xba\xd8\x51\x0a\xd3\ +\x2f\xff\x4a\x60\x65\x14\x97\x07\x22\x1a\x00\x00\xf4\x25\xf8\x71\ +\x51\x09\xb7\x01\xba\x95\x55\x20\x4a\x49\xf5\xc4\x3d\x1d\x9e\x69\ +\x56\x2c\xa9\x2d\x8e\xa3\x5e\x09\x65\x59\x05\xa1\x7f\x8e\xcf\x78\ +\x7a\x27\x5f\x44\xd3\x75\x44\x4f\x20\x4b\x8b\x9c\x8a\x35\xc1\x59\ +\x90\x27\xa7\x17\xd5\xda\x3f\xe0\x9c\xc0\x19\x06\xbf\x3a\x1e\x4b\ +\xaa\x89\xd0\x55\x00\xc5\xa1\x46\xbd\x71\x97\xbb\x33\x75\xfc\x1a\ +\x65\xbb\xd1\x0f\x60\x52\x85\xa7\x03\x90\x2e\x01\x28\x9a\xba\x2e\ +\xa8\x7d\xde\xb0\xb3\xf7\x51\x33\x47\xb3\x0e\x48\xac\xf0\x70\x1a\ +\xd0\x99\xe9\x69\x6a\x2b\xf3\x9d\x63\x1d\x09\x4e\x44\xdd\x67\xde\ +\x06\x00\x00\x71\x4f\x35\x0a\xd4\x01\xa2\x34\x54\xea\x15\x58\x9f\ +\xde\xc9\x0f\x00\xb0\xaa\x5d\x73\x16\x14\x05\x97\x41\xee\x0b\xed\ +\x13\xc8\xa3\xfd\x0d\x6c\xcb\x57\x8f\x79\x1d\x00\x00\x54\x76\x6a\ +\x5d\xe0\xe8\x0e\x80\xa5\xa1\xd2\x60\x11\x59\x33\x36\x8e\x21\xb7\ +\x58\x9d\x10\xb6\x86\xea\xa3\x12\x77\xa5\x1b\xe9\xe5\xb3\xbf\xbc\ +\x0f\x00\x00\xca\xdb\x55\xe6\xba\xba\x0b\x60\xf5\x0c\x8f\x0c\x41\ +\xdc\xd1\xdf\xc8\x54\x3e\xfb\x02\x22\xfc\x15\xf8\x9d\x4c\x82\x6f\ +\x7c\x9f\x1b\x09\x3c\x98\xc1\xf6\x41\xa7\x88\x95\x85\xb8\x3c\x50\ +\xa0\x01\x00\x40\x26\xc1\xe1\xcf\x3e\xb7\x13\xba\xfe\xab\x3d\x12\ +\x9e\xfa\x2e\xab\xfa\xea\xf9\xb2\x50\x7d\x15\xe4\x09\x64\x91\x18\ +\x4f\x06\x2d\x22\x5b\x42\x95\x4e\xc7\x67\x53\x5f\x82\x23\x85\x6c\ +\xa7\xf0\x03\x98\x14\x4b\x4e\x5c\x21\xd8\x0c\x40\x82\x2e\xa4\x07\ +\x9c\x53\xbf\xfb\x7f\xf0\x4f\xaa\x7e\x28\xb7\xfa\x9a\x4a\xfe\x76\ +\x1f\xc6\x18\x63\x8c\x31\xc6\x18\x63\x8c\x31\xc6\x18\x63\xcc\x7f\ +\xe2\x3b\x5f\x7a\xf2\xea\xb1\x6e\xd0\x9c\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x08\x6c\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x08\x1e\x49\x44\x41\x54\x78\x9c\xed\ +\x5b\x7d\x8c\x1c\x65\x1d\x7e\x7e\x33\xb7\x7b\x77\x70\x1f\x10\xe8\ +\x51\xb3\x1f\xb3\x7b\xd7\x6b\x4a\x5a\x4c\x2c\xa7\x11\xd2\x54\x4b\ +\x34\xa8\xa1\x87\x45\x12\x05\x03\x34\x90\x2a\x45\x49\x94\x40\x4d\ +\x4d\xc0\xaa\x54\xa1\x4a\x0b\xfc\x41\x55\x04\x2d\xd0\x48\x02\x42\ +\x63\x0d\x60\xff\xc0\x36\x55\x21\x80\xd1\xe8\x62\xcf\x5c\xdd\xdb\ +\xd9\x9d\xbb\x1e\xb5\x14\xfb\x61\x7a\xb7\xb3\xfb\x3e\xfe\xd1\x22\ +\xf3\xb5\x77\xbb\xb7\x33\xc7\x55\xef\xf9\x6f\x9e\xf7\xf7\xfe\xe6\ +\x99\x67\xde\x99\x7d\xe7\x7d\x7f\x0b\xcc\x63\x1e\xf3\xf8\x7f\x86\ +\xcc\xc6\x49\x86\x0f\x1d\x5a\x10\x9b\xac\xac\xa4\xe0\x12\x0d\xb2\ +\x44\x81\xbd\x00\xce\x13\x48\x17\x40\x1d\xc0\x71\x00\xc7\x09\x29\ +\x02\x3c\xa0\x41\xfe\x46\x56\xf6\x67\x32\x99\x91\xa8\xb5\x45\x66\ +\x40\xb1\x58\xec\x53\xd0\xd6\x42\x71\x10\x82\x0f\xce\x30\xcd\x08\ +\x28\x2f\x6a\x9a\xfa\x79\x2a\x95\x7a\x43\x44\x18\xaa\x48\x84\x6c\ +\x00\x49\x29\x58\xd6\x95\xa2\xb0\x01\xc0\xaa\x30\x73\x03\xc8\x51\ +\xb8\xf5\xed\xc3\x87\x9f\x1a\x18\x18\xb0\xc3\x4a\x1a\x9a\x01\x85\ +\x82\xb5\x0a\xc2\x2d\x00\x06\xc2\xca\x19\x0c\x29\x10\xd8\x94\x49\ +\x27\x9e\x08\x63\x44\x34\x6d\x40\x3e\x9f\xbf\x48\xd3\x63\x0f\x00\ +\xf8\xe2\x14\x61\x8a\xc0\xef\x45\x64\x2f\x14\x87\xa8\xe3\x1f\x2d\ +\xc0\xd1\x4a\xa5\x72\xa2\xd2\xd6\x56\x8d\x97\xcb\x9d\x64\x4b\x37\ +\xa0\xb2\x14\x2c\x06\xe4\x32\x01\x3f\x09\xa0\xbd\x56\x42\x02\xfb\ +\x35\xa8\xf5\x86\x61\xbc\xd9\x8c\xfe\xa6\x0c\xc8\x97\x4a\x1f\xd1\ +\x14\x76\x01\xf8\x40\x40\xf3\x09\x81\xbc\x40\x72\x77\x4b\x8b\xbc\ +\x94\x4c\x26\xdf\x6e\x24\x77\xa9\x54\x6a\xaf\x56\xe5\x0a\x11\xb5\ +\x9a\x90\xc1\x1a\xe7\x98\xa0\xf0\xe6\x6c\x3a\xfd\x8b\x99\xe8\x07\ +\x9a\x30\xa0\x50\x28\x5d\x0f\xc1\xe3\x00\x5a\x7d\xa2\x80\x87\x35\ +\xa8\xfb\x0c\xc3\x78\x67\xa6\xf9\x9d\xc8\xe5\x72\xf1\x8e\x8e\xae\ +\x75\x10\xb9\x07\x40\x8f\x2f\x80\xb2\xd9\x30\x12\xf7\x88\x88\x6a\ +\x34\x77\xc3\x06\x90\xd4\x8a\xc5\xd2\xbd\x84\x6c\xf4\x34\x29\x00\ +\x8f\xb7\xe8\xf2\xed\x64\x32\x69\x35\x9a\xb7\x1e\x0c\x0d\xfd\xb3\ +\xb3\xbd\x7d\xe2\x0e\x02\x77\x02\xe8\x70\x0b\xc3\xae\x73\xce\x69\ +\xbd\xa1\xa7\xa7\xe7\x64\x23\x39\x1b\x32\x80\xa4\x66\x9a\xa3\x3b\ +\x21\xfc\x82\xa7\x69\x4c\x69\x58\xd3\x9b\x4a\xbd\xd6\x48\xbe\x99\ +\xc2\xb2\xac\x64\xa5\xca\xe7\xe1\x7f\xe1\xfe\xc9\x2e\x4f\x7c\xbc\ +\xbf\xbf\xff\x78\xbd\xb9\xb4\x46\x4e\x6c\x96\x46\x37\xf9\x2e\x5e\ +\xf0\x2a\x58\x1d\x98\xad\x8b\x07\x80\x64\x32\x69\xe9\x1a\x56\x02\ +\xd8\xe9\x69\xfa\x50\x2c\xde\xb6\x93\xa4\x5e\x6f\xae\xba\x47\xc0\ +\x48\xb1\xf8\x79\xa1\x3c\xed\xee\xcc\x1d\x4a\x55\x6f\xcd\x66\xb3\ +\x13\xf5\xe6\x09\x13\x24\xa5\x58\xb4\xee\x22\x70\x1f\x1c\xd7\x42\ +\x60\x4b\xd6\x48\x7d\xa3\x9e\x1c\x75\x19\x50\x2c\x16\x07\x14\x65\ +\x3f\x80\x36\x07\xfd\x94\x91\x4e\xde\x18\xc5\xec\xac\x51\x8c\x98\ +\xd6\xd7\x04\xdc\xe6\xe4\x04\x72\x93\x61\x24\x9f\x98\xae\xef\xb4\ +\x8f\x80\x65\x59\x17\x28\xca\x2e\x38\x2e\x5e\x80\xd7\xa8\x2a\xeb\ +\xe6\xc2\xc5\x03\x40\x26\x9d\x78\x08\x94\x9f\x39\x39\x82\x8f\x16\ +\x0a\x63\xcb\xa7\xeb\x3b\xad\x01\x15\xc5\x2d\x00\x12\x0e\x6a\x4c\ +\x84\x6b\xde\xaf\x61\x1f\x04\x11\xa1\x6d\x9f\x5a\x0f\xe0\x0f\x0e\ +\x3a\x0e\xa9\x3c\x4a\xb2\x65\xaa\xbe\x53\x1a\x60\x9a\xe6\x0a\x10\ +\x37\x3b\x28\x52\xc9\xe7\xd2\xe9\xf4\x58\x13\x7a\x23\x41\x7f\x7f\ +\xff\xa4\xaa\xda\xd7\x00\x38\xf2\x1e\x2b\xcb\x8b\x45\xeb\xb6\xa9\ +\xfa\xd5\x34\x80\xa4\x10\xfa\xf7\x3d\xf4\xce\x6c\x36\xf9\x6a\x33\ +\x42\xa3\x44\x6f\x6f\xef\x5b\x84\x6c\x76\x72\x04\xee\x1e\x1f\x1f\ +\x3f\xb7\x56\x9f\x9a\x06\x14\x2c\x6b\x25\xc0\x15\x0e\xca\x16\xa8\ +\x6f\x85\xa0\x33\x5a\x28\xfb\x47\x10\x14\x1d\xcc\x85\x13\xe5\xf2\ +\x97\x6b\x85\xd7\x34\x40\x14\xee\x72\x13\xf8\xb1\x61\x18\xf9\xe6\ +\x15\x46\x8b\x6c\x36\x3b\x41\xd0\x7d\xa3\x28\x77\xd4\x9a\x1b\x04\ +\x1a\x30\x32\x32\xb2\x10\xc0\xa7\x1c\x94\xad\x2a\xf6\xbd\xa1\xa9\ +\x8c\x18\x99\x54\xea\x49\x02\xc3\x0e\x2a\x51\x28\x95\x3e\x11\x14\ +\x1b\x68\x80\xe8\xfa\xf5\x00\xfe\xeb\x98\x00\x2f\xf7\xf6\xf6\xbe\ +\x15\xae\xcc\xe8\x20\x22\x55\x21\x9f\x71\x71\x4a\x6e\x0a\x8a\xad\ +\xf1\x08\xc8\x6a\xe7\x11\x85\xbf\x0a\x4b\xdc\x6c\x81\xba\xb8\x35\ +\x0b\x3e\x13\xf4\x18\xf8\x0c\x18\x1f\x1f\x3f\x17\xc4\xe5\x4e\xae\ +\x6a\xeb\xbf\x0e\x5d\x61\xc4\xc8\x24\x93\xaf\x03\xe2\x1c\xb5\xdd\ +\x23\x96\x75\xa9\x37\xce\x67\xc0\xe4\x64\xe5\xa3\x00\xe2\x0e\xea\ +\xcf\x7d\x7d\x89\xa2\x37\x6e\xae\x43\x44\x14\x84\xae\x1b\xa7\x2b\ +\xff\x3a\x65\xc0\x23\xc0\x65\x1e\x62\x7f\xa8\xca\x66\x11\x3c\xfd\ +\xfd\xf2\xde\x31\xb0\xd4\x1b\x13\x64\xc0\xc5\xce\x23\x71\xbf\x4d\ +\xcf\x2a\x08\xc5\xab\xfd\x62\x6f\x4c\x80\x01\x92\x71\x1e\x91\x32\ +\xe7\x7f\xfb\x6b\x81\x2c\x7b\xb5\x67\xbd\x31\x3e\x03\x08\x74\x3a\ +\x8f\x45\xe4\x5f\x21\xeb\x9a\x4d\x78\xb5\x77\x7a\x03\xa6\x35\xa0\ +\x5a\x65\x43\x6b\x6c\x73\x09\x99\x4c\x66\x12\x40\xc5\x41\xc5\x73\ +\xb9\x9c\xf3\x05\xef\x37\x40\xbc\x8b\x24\x31\xce\x89\x6f\xfe\xa8\ +\x10\x34\x11\x3a\xe1\x3c\xd0\x95\xe6\x1b\x36\x67\x0b\x0a\x85\x42\ +\x2b\x00\xe7\x7a\x40\x79\xd9\xb2\x65\x65\x67\x4c\xd0\x08\x70\xad\ +\xa8\x92\x3c\x2f\x1a\x79\xd1\x83\x64\xb7\x87\x3a\xe1\x8d\xf1\x19\ +\xa0\x00\xd3\x93\xc6\xf7\xe6\x3c\x5b\xa0\x69\xf1\x5e\x0f\x55\xf0\ +\xc5\xf8\xbb\xc9\x01\xe7\x11\x05\xfd\x61\x8a\x9a\x4d\x88\x5f\xfb\ +\x90\x37\xc6\x67\x80\x86\xaa\x6b\xb3\x51\xdc\x8b\x22\x67\x15\xe8\ +\xd1\x4e\x20\xe7\x8d\xf1\x19\xd0\xde\xde\xfe\x0a\x00\xc7\xfe\xbb\ +\x2c\xb7\x2c\x2b\x19\x81\xbe\x48\x41\x52\x03\x70\x95\x8b\x54\xb2\ +\xd7\x1b\xe7\x33\xa0\xa7\xa7\xe7\xa4\x00\xaf\x38\x39\x5b\x79\x12\ +\x9d\x05\x28\x95\x4a\x97\xc2\xbd\xa3\x7c\x3c\x93\x49\xbc\xe1\x8d\ +\x0b\x5c\x0f\x20\xe1\xfa\x8a\x12\x70\x30\x5c\x79\xd1\x43\x41\x73\ +\x69\x26\xf8\x92\x88\x54\xbc\x71\x81\x06\x68\x1a\x77\xe2\xf4\x6e\ +\xef\xbb\xbd\xaf\x18\x3e\x74\x68\x41\xd8\x22\xa3\x02\x49\x0d\xe4\ +\xb5\x4e\x4e\x28\x3b\x82\x62\x03\x0d\x48\xa7\xd3\x63\x20\xf6\x38\ +\xa8\xd6\xd8\xa4\xed\xdd\x0e\x9f\xb3\x30\x4d\xeb\x3a\x00\x4b\x1c\ +\xd4\xb8\x61\x24\xf7\x04\xc5\xd6\x5e\x15\x16\xf9\xa1\x87\xf8\x4a\ +\x3e\x3f\x66\x84\xa2\x30\x42\xe4\x72\xb9\x38\x04\xdf\x75\x72\x02\ +\x6c\x0b\x1a\xfe\xc0\x14\x06\xa4\xd3\x89\x97\xe1\x7e\x19\xc6\x75\ +\x5d\x6d\x0a\x45\x65\x84\xe8\xe8\xe8\xfe\x12\xdc\x9f\xbd\x47\x4f\ +\x9d\x6a\xdb\x5e\x2b\x7e\xaa\x11\x40\x2a\x7c\xd3\xc9\x11\xbc\xd1\ +\x34\x4d\xdf\xba\xda\x5c\xc1\xe8\xe8\xe8\x85\x10\xdc\xed\x22\xc9\ +\xef\x2d\x59\xb2\xc0\x37\x05\x7e\x17\x53\xee\x0d\x66\xb3\xa9\xbd\ +\x00\x9e\x74\xc7\x6b\xcf\xe7\xf3\xf9\x8b\x9a\x11\x1a\x05\x72\xb9\ +\x5c\xdc\xb6\xd5\xb3\x70\xd6\x10\x11\x7f\x39\x72\xe4\xf0\xc3\x53\ +\xf5\x9b\x7e\x77\xd8\x8e\xdd\xe9\x5c\x5d\x25\x90\xd2\xf4\xd8\x73\ +\xc3\xc3\xc3\xde\xe2\xa8\xf7\x15\x9d\x9d\x5d\x0f\x41\xf0\x31\x07\ +\x65\x2b\x1d\xeb\xa6\x2b\xaa\x9c\xd6\x80\x45\x8b\x16\x1e\xa6\xc2\ +\x67\x01\x4c\x3a\xe8\xcb\x63\xad\x6d\x8f\x90\x9c\x95\x5a\xe3\xe9\ +\x50\x28\x16\x6f\x23\xe4\x56\x17\x49\xac\xaf\xa7\x6c\xa7\xee\x0b\ +\x30\x4d\xeb\x06\x82\xae\x8a\x0b\x02\x3f\xf9\xf7\x89\x63\xb7\x7b\ +\xbf\xb1\x67\x0b\x67\x4a\x64\x6e\x27\xb0\x0d\x8e\x9b\x29\xe0\x83\ +\x86\x91\xfe\x7a\x3d\x39\x1a\xba\x83\x23\x66\xe9\x7e\x01\x36\xb8\ +\x55\x60\x5f\x2c\xa6\x5d\x9b\x48\x24\x8e\xd4\xe8\x16\x09\x72\xb9\ +\x5c\xbc\xa3\xab\xfb\x11\x10\xb7\x38\x79\x01\x7e\x93\x4e\x27\xaf\ +\xaa\xf5\xb3\xe7\x45\xa3\x65\x72\xba\x59\xb2\x9e\x01\xb1\xc6\x93\ +\xa6\xa0\x6b\x1c\x4c\xa5\x52\x7f\x6d\x24\xdf\x4c\x71\xf0\xe0\x78\ +\x4f\x4b\xac\xf2\x4b\xf8\xbf\x54\xdf\xa4\xaa\xac\xc8\x66\xb3\x75\ +\x2f\xe4\xce\xa4\x50\x52\x37\xcd\xd2\x0f\x20\xe2\x1d\x62\x36\x81\ +\xed\x55\x3b\xb6\x79\xd1\xa2\x85\x87\x1b\xcd\x5b\x0f\x4e\x97\xcf\ +\xe2\xab\x10\x6c\x04\x70\xbe\xab\x51\xf0\x62\xd5\x2e\x5f\xd7\xd7\ +\xd7\x77\xac\x91\x9c\xcd\x94\xca\xde\x02\xc1\x76\x00\x31\x4f\xd3\ +\x49\x02\x0f\x54\xca\x13\x5b\x1b\x29\x58\x9c\x0a\x24\x5b\x4c\xd3\ +\x5a\x0b\xc1\x26\xb8\xeb\x95\xce\x04\xc8\x56\xc3\x48\x6c\x10\x91\ +\x6a\xa3\xb9\x9b\x2b\x96\x2e\x16\x57\x6a\x94\xe7\x00\x5c\x10\xd0\ +\xfc\x0e\xc1\xdd\x1a\xb4\xdd\xe5\xf2\xa9\x3d\x8d\x9a\x91\xcb\xe5\ +\xe2\x9d\x9d\xe7\xaf\x54\x50\xab\x05\xb8\x1a\x40\xd0\x34\xdc\x06\ +\xb1\x3e\x93\x49\x3d\x36\x13\xfd\x40\x08\xe5\xf2\x07\x47\x47\x53\ +\x2d\x55\xf5\x20\x88\x6b\xa6\x08\xb3\x01\xee\x83\x68\xbf\x85\xe2\ +\xdf\x95\x92\x83\xaa\x55\x8e\xc6\x2a\x95\x93\xe5\x72\xb9\xda\xd6\ +\xd6\xd6\xa9\x94\xea\x26\xf5\x2c\x35\x2c\x06\xd5\x65\x02\xb9\x12\ +\x40\x57\xad\x84\x04\x5e\x3f\x53\x2e\xff\xc7\x66\xf4\x87\xf8\x87\ +\x89\xd2\xa7\x29\xb8\x5f\x80\x4b\xc2\xca\x59\x03\x63\x84\x7c\x27\ +\x93\x4e\xfc\x74\x26\x43\xde\x8b\xb0\xff\x32\xa3\x99\xa6\x75\x35\ +\x05\x1b\x05\xf8\x70\x98\xb9\x01\xe4\x41\x6e\x25\xab\x8f\x85\x59\ +\xa3\x18\xd9\x4c\xce\x34\xcd\xa5\x14\x6d\x2d\x14\x06\x21\x58\x3c\ +\xc3\x34\xe3\x10\xbc\xa0\xc0\x1d\xd9\x54\xea\x77\x33\xf9\x3f\xc0\ +\x74\x98\x95\xa9\xec\xc1\xd1\xd1\x54\xac\xc2\x55\x0a\x5c\x0a\xc8\ +\x12\x80\x59\x11\x74\x83\xe8\xc2\xe9\x9d\x9b\x63\x00\x8f\x0b\xa4\ +\xa4\x80\x21\x08\x87\x34\x72\x5f\x3a\x9d\x3e\x30\x57\xca\x71\xe7\ +\x31\x8f\x79\xfc\x6f\xe2\x3f\x21\x7b\x09\x29\x0d\x19\xbe\x1d\x00\ +\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x8d\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3f\x49\x44\x41\x54\x58\x85\xed\ +\xd3\xb1\x11\x00\x10\x10\x44\xd1\xa5\x10\x94\x22\xd1\xb5\x19\xad\ +\x18\x0a\x39\x91\x50\xea\x92\xff\xa2\xcd\x7e\xb4\x12\x00\xc0\x59\ +\xb8\x63\xae\x3d\x64\xaa\x7f\xb2\xd6\x4b\x4e\x4d\x92\xe2\x9f\x20\ +\xf0\xc6\x0b\x00\x00\x70\x77\x00\xa4\x4c\x0e\x07\xff\x04\x59\xb9\ +\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x3e\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xf0\x49\x44\x41\x54\x58\x85\xe5\ +\x96\x31\x68\x53\x51\x14\x86\xbf\x3f\x7d\xad\x52\x41\x31\x82\x08\ +\x2e\x2e\x2e\x0e\xe2\xd0\xa0\x5d\x1c\x2b\x54\xba\x08\xa9\x53\x05\ +\x11\x4d\x96\xb4\xa9\xe0\x26\x8a\xe2\x26\xb4\x4d\x2b\xd8\x87\x83\ +\x60\x27\x1b\x70\x29\x0e\xea\xe6\xa2\xf2\x3a\x48\x07\x17\x41\x1d\ +\x14\x41\xa8\x60\xa1\x45\xdb\xe4\x1d\x87\xa4\x4e\x82\xef\xde\x5c\ +\x22\xe8\xd9\x1e\xdc\xf3\xff\xdf\x3d\xef\xdc\x73\x2f\xfc\xef\xa1\ +\xd0\x82\x83\x17\xa6\xf2\x5b\x51\xef\x3b\x30\x5b\x8e\xc7\xf7\xfe\ +\x69\x7d\x14\xd2\xfc\xe8\xd8\xed\x5d\x8d\x28\x7a\x0c\xb6\x27\x6b\ +\x4e\x2e\x94\xf9\x91\xe2\xf5\xbe\xbe\xfe\x1d\x8f\x0c\x4e\xb8\xe4\ +\x05\x01\x28\x16\x17\x7b\xfa\xf3\xfb\x1e\x00\x43\xae\xb9\x01\x00\ +\x4c\xef\xf3\x9f\xef\x00\x67\x31\x30\x2c\xed\x2a\x40\xa1\x34\x77\ +\x13\x54\x06\xc3\x64\xa9\x90\x75\x0d\x60\xe0\xd2\x6c\xd5\xe0\x2a\ +\x80\x49\xce\xe6\x1d\x01\x0c\x94\x6b\x63\x88\x69\x00\x83\x54\x86\ +\xb3\xb9\x37\x40\xa1\x34\x3b\x82\xe9\x7e\xfb\x33\x15\x7e\xe6\x5e\ +\x00\x85\xd2\xcc\x49\x83\x45\xa0\x87\x96\xb1\xb7\xb9\x33\x40\xe1\ +\xe2\xf4\x31\x23\xb7\x04\xec\x6c\x1b\x3b\x75\xfc\xef\x22\xf3\x24\ +\x3c\x5e\xaa\x1d\x4e\xd1\x13\x60\xb7\x81\x29\x80\x39\x64\xac\xc0\ +\x60\x79\xea\x60\xd3\xf4\xcc\x60\x3f\x16\xce\x1c\x32\x56\x60\xcb\ +\xa2\x8f\xbf\xae\x2d\x85\x33\x87\xac\x3d\x60\xac\x84\x34\x75\x06\ +\xe8\xcd\x35\x86\x0d\x3e\xb4\x61\x82\x5d\x60\x99\x01\x5e\xcc\x5f\ +\xfe\x14\x61\x43\x82\x2f\xb4\xc6\x5d\x30\x88\xcc\x42\xaf\xe2\x89\ +\xb7\xa4\xcd\x53\xc0\x9a\x5a\x0f\x99\x20\x10\x4e\x22\xc9\xbd\xc9\ +\xd7\x22\x1d\x01\xbe\x13\x08\xc2\x59\x20\x89\xab\xcf\x05\xa3\x40\ +\x13\x10\xea\xec\x59\xe7\xb5\x83\x24\x1e\x5f\x42\x76\x1e\xd8\x6e\ +\x4a\x6f\x08\xef\x12\x2e\xcf\x4f\x2c\x08\x55\xb7\x75\xcc\xb3\x12\ +\x1d\xfd\xc3\x24\xae\xd4\x04\xb7\x00\x64\xe6\x05\xd1\x71\x13\x25\ +\x71\xe5\x9a\xc4\x5d\x10\x4a\xc9\xb5\x26\x75\x17\x01\x40\x76\x68\ +\xf5\x40\x05\x78\x88\x40\xc8\x49\x33\xc8\x59\xae\xd7\x47\x9b\x1b\ +\x5f\x57\xcf\x01\x4f\x5d\x73\x83\x4d\xb4\x37\xf5\x1b\x9b\x9b\x1b\ +\x3f\xce\x08\x5e\xfe\x15\x00\x80\x95\x85\x2b\xeb\x51\xa3\x71\x1a\ +\x58\x03\x7d\x0b\xa9\xfd\xef\xc6\x4f\x11\x32\x94\x0c\x6f\x6b\x20\ +\xde\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x95\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x47\x49\x44\x41\x54\x58\x85\xed\ +\xce\xb1\x0d\x00\x20\x0c\x03\x41\x82\x18\x2a\xdb\xc1\x42\x69\xd8\ +\x2f\xc0\x10\x46\x4a\xf3\xd7\xdb\xfa\xd6\x04\x1e\xb9\x3c\x72\x29\ +\x1f\x5d\x19\xff\x40\x00\x01\x04\x10\x40\x00\x01\xe5\x01\x43\x3d\ +\xb8\x66\xd3\x23\xab\x02\xfa\xb6\x7b\xb4\x0b\x00\x00\x50\xed\x01\ +\x74\x44\x0a\xfd\x41\x7d\x20\x9d\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x02\x21\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xd3\x49\x44\x41\x54\x58\x85\xed\ +\xd5\x3b\x8b\x13\x51\x18\xc6\xf1\xff\x33\xf1\x86\x82\xd9\x4e\x50\ +\x0b\x11\x5b\xd1\x56\xc4\x72\x36\xcd\x6a\x61\x76\xb0\x71\x51\x34\ +\x29\x2c\x64\x3f\x81\x48\xf0\x0b\x88\x82\x8d\xd9\x20\xee\x16\x42\ +\x36\x2e\xc8\x22\xce\xc6\xce\xc2\xda\xde\xc2\x4a\xb0\x71\x89\xa0\ +\x78\x21\xe7\xb1\x98\x09\xd8\x99\xcb\x30\x29\xf4\xad\x4e\xf1\x5e\ +\x7e\x9c\x73\xe6\x0c\xfc\xeb\xa1\x71\x92\xe2\x7a\x63\x17\x50\x14\ +\xf9\x64\xda\x5d\xfb\x5c\x24\x20\x1a\x33\x6f\x01\xa8\x7a\xa8\xed\ +\xc5\x95\x95\x43\xf3\x00\x00\x60\x71\xce\xdf\xf6\xf7\x92\x24\xd9\ +\x37\x17\x40\x1e\xb5\xdd\x50\x7d\x9a\x24\x49\xa5\x74\x80\x50\x30\ +\x58\x70\x65\x10\xaa\x0f\x19\xf3\x0e\x15\x06\x30\xb6\x24\x67\x6b\ +\x6e\xc5\x97\x1b\xad\x52\x01\x99\xc2\x06\x05\x00\xc4\x9d\xb8\xde\ +\x5c\x2d\x17\x90\x2b\x04\x21\x5f\xdf\x8f\xeb\x8d\xab\x25\x03\xc0\ +\x60\x69\x84\xe0\xc9\xe2\x72\x73\xa9\x54\x00\x80\x8d\x33\x0b\x15\ +\xdb\xdd\xda\x72\xe3\x42\xa9\x80\x3c\x42\x0e\x39\x10\xac\xed\x38\ +\x69\x9e\x2d\x1b\x40\x76\x14\x36\xf8\x30\xf6\xab\x5a\x72\xf3\x54\ +\xa9\x80\x9c\x11\x00\x63\x8e\x84\x40\x3f\xbe\x74\xe3\x68\xc9\x00\ +\x00\x82\x33\xcc\x09\xf6\x56\x5e\xce\x03\xf0\xc7\xd3\xe8\x33\xf3\ +\x00\xe4\xfd\xfc\x81\x5f\xe1\x58\xa9\x00\x67\xbd\x84\xf8\x14\x45\ +\xc4\xfd\x17\x9d\x8f\xe3\xd4\xed\x29\x66\xba\x23\x49\x02\x06\xd1\ +\x30\xd4\xd2\xad\xce\xfb\x71\x4b\x67\xde\x01\xe3\x88\x6c\xf8\xf7\ +\x48\x5c\x4c\xb7\x3a\xef\x26\xa9\x9f\x11\x20\x09\x09\x18\x4a\x4a\ +\xd2\xcd\xf6\x9b\x49\x3b\xcc\x02\x10\x78\x54\x7f\x7d\x67\xf3\xf1\ +\xf6\x34\x4d\xa6\x05\x68\x54\x2b\x58\xed\xf7\xda\x1b\x53\xf6\x99\ +\x0a\x20\x9c\xd7\x99\x7b\x3b\xbd\xf6\x83\x69\x87\xc3\xa4\x5f\x81\ +\x10\x81\x08\x81\xed\x47\xaf\x9f\xaf\xdd\x9d\x65\x38\x4c\xba\x03\ +\x76\x84\x00\xfb\xd9\xf9\xd3\xc7\x6f\x93\xfd\x8a\x4b\x04\x64\x0f\ +\x6d\xba\x50\xf9\x72\xad\xd5\x6a\x85\xbf\x65\x17\x0e\x90\x79\xab\ +\x83\x3f\xea\xdd\x6e\xf7\x67\x11\xc3\x61\xec\x3b\xa0\x01\x42\x8a\ +\xc2\x52\xba\xbe\xfe\xb5\xa8\xe1\xff\x03\xe0\x37\xff\xea\x99\x56\ +\xb6\x04\x03\xd2\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\ +\x00\x00\x03\x2a\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\xdc\x49\x44\x41\x54\x78\x9c\xed\ +\x99\x4f\x48\x54\x51\x18\xc5\xcf\x79\xf3\xd2\xd1\x20\x49\x88\x16\ +\x41\x50\x10\xad\xaa\x45\xe1\x9b\x30\x21\x22\x08\x25\x1a\x67\x2c\ +\x23\x5a\x54\x10\x08\x41\xb4\x69\x17\xe4\xa2\x76\x11\xb4\x0f\xd2\ +\x45\x48\x58\x8e\xe6\x62\x08\x22\x6d\xa1\x8d\xcf\x72\x51\x04\x21\ +\x14\x44\xff\x16\x25\x16\x0a\x29\xf8\xde\xfd\x5a\x84\x31\x7f\x9e\ +\x0d\x82\xf7\xbe\xa0\xfb\x5b\x7e\x07\xe6\x9c\x39\xef\x3e\xee\x9d\ +\x3b\x80\xc5\x62\xb1\x58\x2c\x16\x8b\xc5\x62\xb1\x58\x2c\x96\xff\ +\x0d\xea\x36\xf0\x72\x61\x1f\xc0\x53\x00\x40\xf2\xdc\x44\x86\xbd\ +\xba\x3d\x57\x83\xd6\x02\x0e\xf6\x48\x72\xa1\x41\x16\x4a\x86\xc2\ +\x43\x7e\x07\x47\x75\xfa\xae\x06\x47\xeb\xa7\xaf\x87\x5b\x31\xa3\ +\x8c\xec\x7b\x20\xdb\xb5\xfa\xae\x02\x03\xaf\x80\x92\xa8\xb9\x9b\ +\xe0\x86\xf1\x34\xe7\x75\xfb\x57\x43\xef\x0a\x00\xb0\x35\x60\xe5\ +\x2a\x00\x10\x84\x32\x87\x6e\xd1\xee\x5f\x0d\xed\x01\xee\x77\x32\ +\x44\x92\x0d\x51\x9a\xb7\x47\x42\xdd\xfe\xd5\x30\xf2\x04\xfc\x36\ +\xce\x39\x09\xee\x88\xd2\xbc\x9c\x1a\x33\x91\x61\x25\x8c\x2d\xc1\ +\x42\x9a\x6f\x15\x79\x38\x42\x6a\xf6\x72\xe1\x0d\x53\x39\xca\x31\ +\xfa\x0e\x3e\xcf\xf0\x89\x90\x17\x2b\x15\x5e\x4e\xe5\xe4\xb4\xc9\ +\x2c\x7f\x9c\xe3\x30\x4d\xe5\xc2\x5e\x01\xcf\x94\xcf\x1d\xd2\x2b\ +\x64\x38\x69\x32\x4b\x2c\x05\x00\x80\x97\x53\xef\x00\x54\x9c\x07\ +\xdc\x04\xb7\x8c\xa7\xf9\xc5\x54\x8e\xd8\x0a\x00\x56\x3e\x23\x38\ +\x01\xeb\x0b\x9d\x5c\x88\xd2\xd6\x9a\x58\xf7\xe1\xe0\x1b\x6b\xa2\ +\xe6\xca\x95\x9f\x10\x31\xf2\x70\x62\x2d\x60\xaa\x8b\x4b\x81\xcb\ +\x4d\x51\x9a\x37\x28\xdf\x4d\x64\x88\xfd\x24\x36\x75\x8c\x33\x21\ +\xb8\x2b\x42\x6a\xf0\x06\xc3\x7b\xba\xfd\x63\x2f\x00\x00\x5e\x64\ +\xf9\x1a\x60\x7b\x85\x20\x3c\xa9\xdb\xfb\x9f\x28\x00\x00\x1c\x85\ +\xe9\x58\x7c\xe3\x30\x2d\xc7\x7b\x28\x9b\x15\x25\x5f\x3e\x17\xc1\ +\x33\xdd\xde\xb1\x17\xb0\x77\x58\xea\x11\xca\x30\x88\x6d\x25\x02\ +\xe5\xda\x64\x87\xd3\xac\xdb\x3f\xd6\x02\x4e\xf4\x4b\xc2\x0d\xa4\ +\x0f\x40\x53\xa9\x22\xb7\xfd\x76\xa7\xdb\x44\x86\x58\x0b\xf8\xe0\ +\xaa\x9b\x00\xd2\xc5\x33\x01\x1e\xd5\x6d\x74\x2e\x80\x8c\x3c\x24\ +\xad\x35\xf1\x1d\x85\x07\xe5\x12\x44\x6e\x95\x8d\x5f\xba\x09\xb6\ +\x98\xbc\x29\x8a\xa5\x80\xa6\x01\xc9\x90\x32\x50\xe6\xff\xc9\x09\ +\x98\x2a\x74\xf2\xb3\xc9\x2c\xc6\x0b\x48\x0d\x89\x27\x4a\x46\x01\ +\xd4\x15\x8d\xe7\xa1\x78\xc0\x3f\xce\x57\xa6\xf3\x24\x4c\x9a\xfd\ +\xbe\x0d\x96\x11\x02\xc5\x57\x64\x01\xc0\xb4\xdf\xc1\x82\xc9\x2c\ +\xcb\x44\x5e\x58\xea\x60\x7f\xbf\x34\x2a\x47\xf2\x00\xca\xce\xfe\ +\xec\xf2\xb3\x7c\x6c\x2a\x47\x39\x46\x76\x81\xd6\xbc\xd4\x2a\x57\ +\x86\x00\xec\x2c\x11\x44\xae\xfb\x59\xde\x31\x91\x61\x25\xf4\x17\ +\xd0\x2d\xce\xec\xa2\xea\x01\xd0\x52\x2a\xc8\x5d\x3f\xeb\x5c\xd5\ +\xee\x5f\x05\xed\x05\x78\xbb\x71\x65\xf9\xbf\xc1\x22\x9e\x36\x26\ +\x9d\xf3\xa6\xf6\xfa\xbf\xa1\x75\x17\x68\xcd\x4b\xed\xec\xa2\xfc\ +\x00\x90\x2c\x1a\xbf\x59\x57\xc3\xe6\xb1\xa3\x34\xf2\x7b\xbf\x1a\ +\x5a\x57\xc0\xd7\x8f\x50\x00\x96\x8a\x47\x24\xdb\xfe\x95\x2f\x0f\ +\x68\x2e\x60\xaa\x8b\x4b\x04\xcf\x02\x98\x01\x30\xad\xc8\x23\x13\ +\x19\xbe\xd7\xe9\x69\xb1\x58\x2c\x16\x8b\xc5\x62\xb1\x58\x2c\x16\ +\x8b\xc5\x52\x8d\x5f\x44\x94\xcc\xbe\xc4\xf9\xa0\xab\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x9b\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x4d\x49\x44\x41\x54\x58\x85\xed\ +\xd7\xb1\x0d\x00\x20\x08\x05\x51\x34\x0e\x66\xc3\x04\xae\xc0\x98\ +\x26\xac\xe6\x06\x22\xc4\xf2\xae\xfc\x09\xc9\x6b\x11\xa1\x64\xba\ +\xcc\x75\x99\xbf\xee\x51\xa3\x60\x98\xc9\xfd\x5a\xaf\x1c\xfd\x0c\ +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xd2\x9f\x51\ +\x13\xd9\x99\x9d\xa2\x0e\xd8\x07\x09\x21\x90\x7b\x88\xd1\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xf9\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xab\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\x31\x15\x80\x30\x00\xc4\x50\x8a\xb7\x2a\xc0\x02\xb2\xb0\x80\ +\x02\xc4\x95\x15\x07\x9f\x21\xd9\x6e\xba\xbc\x8c\x0d\x31\x8f\x73\ +\x7d\xf7\x73\x5f\x43\x78\xec\xe2\xf4\x4f\x14\x40\x0b\x68\x0a\xa0\ +\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\ +\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\ +\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\ +\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\ +\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\ +\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\ +\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\ +\x2d\xa0\x79\x01\x55\xd1\x04\x80\x1e\x3b\xba\xea\x00\x00\x00\x00\ +\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\xe8\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x9a\x49\x44\x41\x54\x58\x85\xc5\ +\x97\xd9\x76\xe2\x46\x10\x86\xbf\x66\x11\x12\x60\x50\x9c\xc4\x9e\ +\xf1\x24\x39\x59\xde\xff\x9d\x72\x31\x9e\x49\x1c\xcf\x18\x6c\x23\ +\x19\x24\xa8\x5c\xd4\xdf\xa8\x91\x71\x72\x97\xd4\x39\x1c\x89\x56\ +\xd7\xf6\xd7\xd6\x0d\x58\x09\x16\xf8\xcf\xc9\x02\x58\x19\xa4\x7c\ +\x09\xac\x21\x58\xf7\x91\x4b\x20\x1a\x96\x25\xef\x93\x44\x4a\x5c\ +\xb3\x64\x6d\x9b\xac\xed\xf4\x7e\x00\x1e\x7a\xf2\x97\xc0\x3a\xf4\ +\x16\x0e\xc0\x05\x30\x00\xaa\x44\x59\x90\x11\x13\xd8\x0d\x21\x8c\ +\x81\x71\xcf\xa5\x16\xac\x81\xac\x95\x11\x51\xb9\x01\x0d\x90\x4b\ +\xfe\x23\x30\x3c\x75\xd8\xf7\x2d\xc0\x7e\x11\x34\x63\xb0\x99\xd6\ +\x33\xb0\xf7\xf0\x50\x82\xe5\x60\x13\xb0\x82\x57\x64\x85\xbe\x4d\ +\xb5\xf7\xca\x79\xc1\xd7\x2c\x93\xec\x5f\xc1\x2e\xfa\x10\x02\xf6\ +\x01\xf8\x24\x24\x0c\x78\x01\x0a\xd8\xbd\x87\xec\xa3\xbc\x00\x58\ +\xc8\x8b\x73\x94\x7e\x9b\xc0\xee\x06\xb2\x5b\x21\x92\x4b\xdf\x1a\ +\xb8\x81\x70\x0b\x30\x92\xf2\x80\xc3\x3e\x96\xf2\x1b\xe0\xde\x19\ +\xb2\xfb\x44\xf9\x04\x0f\x91\x71\x1a\xf7\xe8\xcc\x4c\xca\xf4\xcb\ +\xbe\xc2\xa6\x80\xd9\x18\x78\x07\x7c\x94\x8e\x41\x0f\x01\xfb\x4e\ +\xff\x2b\x08\x15\xd8\xb5\xbe\xfd\x09\xcc\x1d\x8d\xd5\x0c\x4a\x5c\ +\x70\xa8\xcf\x03\x60\x73\xa0\xc5\xf3\xa5\xd2\xf3\x80\x27\xf4\x0e\ +\x78\xc2\xe3\xff\x0d\xb0\x82\xb0\x19\x25\xdc\x63\x29\xcf\xe5\xdd\ +\x1a\xb8\x92\xc5\x39\x94\x4f\x82\x71\x02\x66\x1d\x0f\x24\x08\xe5\ +\xc0\xb3\x94\x95\x42\x38\x03\xee\xf0\xf0\x64\x10\x9e\x12\x07\x3b\ +\x28\xdc\x52\x9b\xc0\xcb\xb5\x18\x83\xa0\x5c\x48\x68\xa4\x39\x1e\ +\x86\xb9\xf8\x07\xfa\x1f\xd7\x22\x6d\xc4\xbb\x93\xac\x00\xdb\xf7\ +\x4a\xcc\x63\xee\xc5\x10\xbc\x73\x41\x15\x30\xfd\x8c\xc7\xb2\x96\ +\xf5\x23\xc1\x56\x43\x75\x09\xd3\xb5\x23\x75\x8e\x6c\x21\x99\x35\ +\x30\x95\x03\x53\xba\xd2\x1b\x49\xf6\x1c\x0f\xc1\x97\x14\x81\x09\ +\xb4\x2f\x49\x6d\x16\x8a\xb5\xe1\x96\x5d\xc3\x74\xe5\x48\xbd\x49\ +\xb1\xce\xbf\x17\x8f\x09\x89\x58\xb6\x2d\x3c\x36\x78\xe8\xfa\x21\ +\x68\x4a\x58\x3c\x74\xc6\x30\x54\x3e\xe4\x78\xd2\xfc\x25\xc1\x85\ +\xfa\x41\xee\x49\x67\xb3\xee\x3f\x05\x9e\x37\x5f\x61\x73\x29\xde\ +\x3c\x91\x09\x2c\x9e\x49\x42\x15\x0d\xc8\xbc\x8b\x91\x0b\xc6\x52\ +\x1e\xb4\x62\x5c\xe1\x89\xf6\x20\x48\x73\x3d\x83\xa0\x9d\xba\x0c\ +\xa6\xae\x9c\x06\x66\x0f\xda\xd7\xe2\x3d\xe5\x12\xef\x31\x43\x68\ +\x4c\xfb\x63\x1f\x20\x40\x50\xd7\x0a\x8f\xde\xb9\x82\x32\xdb\x0c\ +\x82\xfa\xbb\x35\x12\x36\x06\xee\x7b\xbd\xfd\xca\x8d\x8e\x7c\xb4\ +\x60\x7b\x7f\x86\x1d\xd8\x33\x5e\x86\x03\xba\x24\x3f\xa9\x82\x61\ +\x52\xdf\x49\x93\xa9\xd3\x3d\xda\xc7\xbd\x7b\x63\xe9\x30\xbb\x4b\ +\x1c\x8a\x94\x4e\x59\xc9\x0c\x55\xe7\x6c\xc7\x30\x82\xf1\x21\xf1\ +\x86\xe4\xbd\x4d\x84\x8c\x80\xc6\x3d\xb7\x35\xea\x4c\x78\x46\x5b\ +\xd2\x1f\x52\x4a\x1d\x78\x35\x3d\x07\xc9\x73\x7f\x86\xb9\x4f\x87\ +\x9e\xc0\x3e\x9d\x6b\xcf\x96\xbc\xbf\xda\x17\x85\xed\xa0\x51\x57\ +\x0b\xd6\x6d\x0e\x06\xf5\xb0\x67\xc0\x30\x81\x7d\xa5\xdf\x32\x99\ +\x27\x7d\x83\x4f\x46\x6e\xdf\x98\x94\xa1\x55\x29\xf5\xac\x2d\xfa\ +\x75\xdf\xe2\x09\xa7\x79\x1e\x62\xdb\xbe\xa6\x3b\x03\x44\x0a\xaf\ +\xdf\xad\x00\x3b\xee\x8b\x39\x60\xca\x70\x53\x19\xce\x34\x58\xc0\ +\x4b\xb3\x94\xe2\x02\x6f\xb9\x6a\x36\x96\x42\xdc\x00\xdf\x4a\xb8\ +\x49\xb6\x0e\x21\x16\x3b\x20\x32\x76\x1f\xf9\xa2\x01\x3b\x08\x43\ +\x95\xdb\xd6\x0f\x24\x34\xfe\xdf\xc0\x33\x7f\x23\x21\x9f\xff\x61\ +\x1a\xee\x38\x9e\x76\xd6\x25\x2c\xef\x3a\x07\x79\xc0\x4b\x38\xee\ +\xd9\xc1\x49\x08\xc6\x75\xe2\xf5\x16\x35\x0a\x51\x05\x2f\x3f\xc9\ +\xf3\x73\x99\x7e\xb4\x40\x1e\x7e\x80\xe5\x53\xb7\xbc\x2a\xa4\x1c\ +\x37\x6c\xbc\x89\x5f\x06\x09\xe3\x06\xea\xb2\x63\xa2\xf6\x86\x14\ +\x0f\x1a\xf9\x2d\x3e\xdd\xfa\x67\xc1\x94\x22\xd4\x7f\xe0\xed\x36\ +\xf8\xb3\x4c\x86\x57\x36\x93\x31\x27\x21\xd8\xfb\xe6\xe2\x19\xec\ +\x86\x6e\xe0\x14\xf8\x49\xe6\x77\x3c\x9e\x7b\xa0\x74\xa4\xea\x41\ +\x97\xa0\xf5\x50\x02\xd5\x21\x8f\x7b\x7f\xc6\xbb\x9f\x8e\x77\x2c\ +\xa1\xb8\x95\xcc\x6d\x6a\x00\x6e\x40\x78\x06\x1b\xd0\xc5\x7c\x24\ +\x6f\x0e\x10\x36\x60\x2d\xf0\x0c\xe1\xe5\x3c\x00\x36\x77\x19\xa0\ +\x83\xeb\x67\x7c\x96\x6c\x24\x73\xe5\xf9\xd3\x45\x31\x0d\x41\xe3\ +\x93\x2d\x3c\x42\x7d\xe1\x9e\xb2\x96\xf5\x5b\xe5\xc7\x71\x8c\xbe\ +\x4d\x36\x56\xe8\x1a\x3c\xd1\xd6\xc0\x25\x54\x33\x47\xc3\x66\x5a\ +\x3f\x09\xc1\x57\xe0\x07\xdf\x6c\x4b\x60\x06\x2f\x41\x93\x74\x42\ +\x67\xb2\x0e\x97\x55\x05\x85\xd1\x75\xcf\xd8\xac\x0a\x3c\xdb\x77\ +\x38\xf3\xc2\x8d\xaf\xa7\x30\x9d\xe3\x13\x76\xe3\x8e\x87\x4d\x62\ +\x40\x30\xb0\x03\x5e\xeb\x01\xf8\x04\x45\x34\x86\x0e\x56\xf0\x30\ +\x4c\x75\xf4\x36\x21\x18\xe2\x1c\x59\x38\x82\xc7\xbd\x17\x6e\xcc\ +\xf4\x8b\x64\xc5\xd9\x72\xee\x50\x63\x17\xba\x34\xf4\x2f\x26\x0b\ +\xa8\x7e\xec\x2e\x23\xff\x76\x31\x01\xe7\xad\x3e\x74\x65\x7d\x72\ +\x31\xf9\xed\xcc\xc5\xe4\xd8\xdb\xf7\x82\x6d\x20\x2b\x33\x1c\xfe\ +\x81\x7f\x6f\x32\x79\x30\x84\x71\x7a\xf7\xcb\x75\x30\x6e\x7d\xd4\ +\x8e\x6a\xbc\x67\xec\xc5\xdb\xd0\x0d\xa6\x35\xc9\xd5\xec\x8d\xcb\ +\x69\xf4\xe2\x98\x70\xc3\xe4\x7d\xa2\xf7\x09\x6c\x35\x3b\x26\x95\ +\x94\x18\xdd\xe5\x54\x06\xb9\xb0\x18\xf3\x9e\xc3\x6b\xf8\x9f\xaf\ +\xe7\x7f\x03\x88\x7c\xd3\x3b\xed\x32\x4f\xdf\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x27\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xd9\x49\x44\x41\x54\x58\x85\xe5\ +\x96\x31\x6b\x54\x41\x14\x85\xbf\x33\x59\x45\x09\x2a\x5a\xd8\x58\ +\x58\xd9\x58\x88\x4d\xd8\xa4\xb1\x4c\x40\x09\xb8\x89\xae\x95\x01\ +\x3b\x1b\x21\x3f\x40\x2c\x42\x7a\x11\x04\x4b\x21\xa9\x7c\xba\x89\ +\x10\x2c\xa2\x9d\x8d\x59\xd3\x48\x0a\x1b\x41\x04\x4d\x63\x67\x64\ +\x51\x92\xec\x1c\x8b\x65\xc1\x4a\xdf\xbc\x37\x28\xe8\xa9\xe7\x9e\ +\xfb\xdd\x3b\xf7\xce\x7b\xf0\xbf\x4b\xb9\x0d\x27\x0a\x9f\x88\x0d\ +\xbf\xb7\xf0\xeb\x56\x38\xfe\xbb\xf3\x8d\x9c\xc9\xcf\xad\x7b\x34\ +\xf6\xfc\x0c\x38\x26\x97\x8b\x09\xb9\x92\x9f\x2d\x7c\xf0\x70\xcf\ +\x2b\xc0\x78\x4a\x5c\x16\x80\xab\x85\x47\x8e\x1c\x88\x4b\xc0\x64\ +\xc9\xc2\x33\x02\xd8\xfa\xd8\x88\xf7\xb1\xae\x61\x23\x13\xff\x28\ +\x40\x73\x25\x2e\x18\xdd\x04\x83\x14\x11\x49\x4d\xa8\x05\xd0\xec\ +\x78\x1e\xe9\x36\x80\xad\x08\x69\xc9\x6b\x01\x34\x3b\xbe\x8e\x7c\ +\x97\x41\xd6\xa8\xc4\xca\x6b\x01\x8c\x3f\xf5\x34\xf2\x43\x18\x54\ +\xae\x0a\x95\x0f\x95\xfc\x0e\x8c\x75\x7c\xc1\xd1\x05\x30\x62\xec\ +\xaa\x95\x0f\x95\xd4\x81\xb1\x55\x9f\x0f\xf2\x1a\x70\x08\x6c\xa1\ +\xa4\x89\xaf\x05\xd0\x7c\xe2\x33\xc1\x5e\x07\x8e\x5a\x98\x0c\xc9\ +\x4b\x03\x4c\x14\x3e\x45\xf0\x0b\xe0\x24\xc2\xa9\xbb\xfe\x2b\x95\ +\x9a\x81\xd8\xf0\x27\x00\x63\x72\xb4\xfd\x67\x95\xbd\x82\x2d\x80\ +\xb2\x1f\x98\xec\x00\x61\x5f\x17\x81\x0f\x48\xa5\x63\xb2\x02\xbc\ +\x6a\x6b\x9b\xa8\x49\xe0\x33\x46\x56\x3e\x88\xd2\x46\xdd\x2b\x7a\ +\x17\xa5\x29\x60\x47\x46\xc6\x59\x20\x92\x4c\x36\x5b\x7a\x13\xad\ +\x69\xe0\xbb\x50\x16\x88\x64\x83\xcd\x59\xbd\x54\x50\x1b\xe8\x0f\ +\x20\x54\xeb\xb7\xae\x52\x05\x1b\x97\xb5\x86\x75\x03\x40\x83\x2e\ +\x54\x86\xa8\xdc\xc2\xee\xac\x96\x91\xe6\x87\x3e\xae\x08\x51\xeb\ +\x0e\xbb\x2d\xdd\xc3\x5e\x04\x50\x45\x88\xda\x43\xd4\x9d\x09\x77\ +\x6c\x3f\x00\x90\x9d\x0c\x51\x7f\x95\x24\x9f\xee\x87\x5b\xc8\x8f\ +\x90\x90\xd3\x36\x23\xcb\x2e\x3f\x6e\xab\xff\x75\x2f\xcc\x01\xcf\ +\x53\x97\x22\xdb\x8b\xf6\xb6\xad\xdd\x6f\xa3\x9a\x01\x36\xfe\x0a\ +\x00\xc0\xd6\x94\x7a\x61\x5f\x97\x90\x77\x6c\xbe\xe4\xf4\xfe\x77\ +\xf5\x03\x8b\xca\xad\x03\x49\x73\x42\xef\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\xd8\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\x8a\x49\x44\x41\x54\x58\x85\xe5\ +\x96\x3d\x72\xd3\x40\x18\x86\xdf\xd7\x49\x01\x9c\x83\x12\x5a\x4b\ +\x70\x05\x0a\xa2\x35\xc4\x21\x24\x71\xfe\x66\xc2\x01\x32\xc3\x19\ +\x28\xd3\x51\x24\x01\x3b\xe4\xd7\x48\xce\x0c\x67\x60\xc6\xd6\x21\ +\xa0\x83\x1b\x00\x05\xd6\x4b\xe1\x28\xc8\x2b\xc9\x92\x3c\x6a\x18\ +\xbe\x4a\x5a\x7d\xfb\x3e\x8f\x77\x25\xcf\x02\xff\x7b\x31\xbe\x78\ +\x74\xad\xc7\x51\xa4\xb7\x10\xee\x92\x7c\x3d\x34\x0c\xea\x04\xb9\ +\x81\x8c\xa4\x37\x24\x7e\x41\x7c\x35\x6c\xf1\x33\x00\x34\xe2\x86\ +\x28\xd2\x11\x80\x87\x20\xee\x0b\xea\xbb\xbe\xda\x75\xc1\x9d\x40\ +\x2b\x82\xfa\x93\x6c\x3c\x10\x75\x18\x3f\x6b\x24\xfa\xee\x24\xae\ +\x1b\xa2\xce\xea\x90\x70\x02\xad\x00\x3a\x4d\xb2\x48\xdc\x4b\x0b\ +\x90\xfb\x00\xa2\x3a\x25\x26\x73\xa7\xe1\x00\xa2\x48\xdc\x4f\x09\ +\x8c\x3c\xfa\x22\xd7\x32\x24\x4e\xe7\x91\x70\x7d\xb5\x45\x9d\xd9\ +\x70\x90\x9d\xd0\xb0\x9f\x12\x00\x80\xd0\xe3\x79\x86\xc4\x42\x55\ +\x89\x1b\x78\xea\x97\x83\xec\x8c\x3c\x7e\x48\xf6\x36\x60\x55\xe8\ +\xf1\x5c\xe2\x7a\xa6\xc4\x40\xcb\x85\xf0\x81\x96\x6f\xe0\x0b\x45\ +\x70\x20\xf1\x19\xda\xd5\xf4\xb5\x4a\xea\xc4\x92\x1c\x93\x5c\x1d\ +\x7a\xbc\xca\x85\x4b\x67\x16\x5c\x20\x37\xb2\xe0\x33\x05\x00\xc0\ +\x0d\xf4\x52\x50\xaf\x8c\x44\x33\xd0\x73\x42\xe7\x55\xe0\x85\x02\ +\xb3\x24\x04\xbe\x88\x5f\xa6\x79\xe1\xa5\x04\x00\xc0\x19\x68\x0d\ +\x52\x37\x4b\x62\x12\x92\x01\x17\x3b\xa3\x16\x4f\x8a\xb2\x4b\x09\ +\xe4\x49\x48\x88\x40\x80\xd3\x62\xa5\xe1\x95\x04\x12\x12\xbd\x19\ +\xf3\x2a\xc1\x2b\x0b\xdc\x4a\x00\x3d\x48\xf6\x5c\x09\xdc\x0c\x0d\ +\x7b\x55\xf2\x52\xff\x03\x25\xea\xa7\x24\xd9\x83\x02\x44\xe1\x47\ +\xd5\xb0\x4a\x02\xce\x40\x2d\x48\x17\xcc\x98\x47\xa0\x01\xea\xc2\ +\xf1\xf5\xac\x4a\x66\xe9\x2d\x70\x03\x19\x41\x97\x00\x16\x13\xc3\ +\x02\x09\x6b\x3b\xc6\x20\xdb\x23\x8f\x7e\x99\xdc\x52\x2b\x90\x07\ +\x17\xb8\x25\x61\x13\x40\x72\x4b\x16\x20\x5d\x3a\x03\xb5\x6a\x11\ +\x68\xfa\xf2\xf2\xe0\xa1\x61\x37\x34\xec\x09\xdc\x9a\x57\x62\xa6\ +\x40\xd3\x97\x47\xea\xca\x86\x93\xdc\x0e\x0d\xbb\xf1\x40\x68\xd8\ +\xcd\x91\xb8\x28\x92\xc8\x15\x98\x05\x1f\x7a\x7c\x6f\xf7\x87\x86\ +\x5d\x92\xdb\x96\xc4\x62\x91\x44\xe6\x4b\xd8\x1c\x68\x89\x52\xbf\ +\x2c\x3c\x59\xee\x40\x9b\x92\x8e\xad\xec\xdf\x04\xdb\x59\x07\xdd\ +\xd4\x0a\xe4\xc1\x01\xee\x14\xc1\x01\x60\xd2\xc3\x1d\x58\x2b\x21\ +\xe8\xd2\x0d\x64\xec\xfe\xa9\x15\x70\x02\x3d\x05\xf4\x31\x0b\x3e\ +\x32\x7c\x57\x04\xb7\xb2\xb6\x00\x1d\xa1\x60\x25\x6e\x1f\x36\x7d\ +\x3d\x21\x75\x5d\x07\x3c\x21\xb1\x0d\xe8\x30\x25\xd1\xa0\x19\x2e\ +\xf1\x13\x30\x75\x2a\xd6\x41\x06\x7c\x77\x5e\x38\x00\x8c\x0c\x8f\ +\x01\xee\xc2\xde\x8e\xb1\x0e\xe2\x9b\xbf\x67\xf5\xe9\x33\x60\x0c\ +\x3f\x9e\x17\x5e\x20\x31\x4e\x09\x40\xdc\x03\xf0\x05\xc0\x77\x88\ +\x9d\x3a\xe0\x53\x12\xe4\x06\x80\x6f\x10\xbe\x8a\xdc\xab\x2b\xfb\ +\xdf\xaf\x3f\xf0\x88\x83\xb8\x80\x8e\x5a\x2b\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xa4\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x56\x49\x44\x41\x54\x58\x85\x63\ +\x60\xa0\x00\x58\xac\xfd\xdb\x60\xb1\xf6\x6f\x03\x25\x66\x30\x51\ +\xa2\x99\x1a\x60\xd4\x01\xa3\x0e\x18\x75\xc0\xa8\x03\x46\x1d\x30\ +\xea\x80\x01\x77\x00\x0b\xe5\x46\xfc\x77\xa0\xa4\x4a\x1e\x0e\x21\ +\xc0\x78\xe0\x44\x30\x73\x03\xb9\xba\x07\x3c\x04\x46\x1d\x30\xea\ +\x80\x51\x07\x8c\x3a\x60\xd4\x01\xa3\x0e\x18\x70\x07\x00\x00\x30\ +\xcb\x0b\x07\x89\x28\x47\x47\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ +\x42\x60\x82\ +\x00\x00\x03\xf0\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\xa2\x49\x44\x41\x54\x78\x9c\xed\ +\x97\xbd\x6f\x1c\x45\x18\xc6\x9f\x67\x6e\xb1\x8c\x94\xd0\xc4\x29\ +\xa2\xfb\x8e\xb0\x30\x35\xa1\x87\x20\x2c\x94\x0a\xa7\x4c\x07\x51\ +\x04\x7f\x00\x10\x51\x44\x08\x21\x21\x3e\x6a\xa4\x28\x31\xe9\x10\ +\x05\x08\x68\x88\x25\x4b\xe0\x02\x3a\xa0\xc6\x91\x89\x76\x76\xf7\ +\x4e\x29\x9c\x8e\x02\x07\xdf\xcd\x43\x71\x32\xba\xdb\xdd\xf3\x7d\ +\xf8\xf6\x9c\x8f\xf9\x95\xf3\xee\x3b\xf3\xbc\xcf\xbe\xbb\x33\x03\ +\x78\x3c\x1e\x8f\xc7\xe3\xf1\x78\x3c\x1e\x8f\xc7\xe3\xf1\x78\x9e\ +\x2c\x78\x5c\x0b\x5b\x9b\xac\x81\xf8\x02\xa0\x01\x71\xb3\x51\xab\ +\x5c\x3b\x0e\x1d\xc7\x62\x40\x14\x25\x57\x04\x5c\x07\x60\xfe\x1f\ +\x14\xae\x34\x1a\xd5\xf5\x79\x6b\x31\xa3\x1f\x99\x2d\x51\x94\x5c\ +\x15\x70\x23\xb3\x36\x71\x33\x8a\x92\xf7\xe6\xad\x67\x6e\x1d\x20\ +\x89\x51\xd2\xfa\x0c\xc2\x3b\x23\x1e\xfd\xbc\x5e\xab\x5c\x25\xa9\ +\x79\xe8\x9a\x8b\x01\x92\x82\x28\x6a\xdf\x00\xf5\xc6\x58\x09\xc4\ +\xad\x7a\xb5\xf2\x16\xc9\x4e\xc1\xd2\x8a\x37\x20\x0c\xc3\x45\x32\ +\xf8\x1a\xc4\xeb\xfd\xe3\x02\x40\xc8\xa9\x27\xc1\x64\x84\x10\xdf\ +\xab\xdb\xb9\xd4\x6c\x36\xf7\x8a\xd4\x57\xe8\x3f\x60\x67\x67\xe7\ +\x19\x9a\xe0\x76\xa6\x78\x01\x04\xba\x00\x45\x40\x04\xba\x99\x7e\ +\x17\xd6\x68\x82\x1f\xb7\xb7\x77\x4f\x16\xa9\xb1\xb0\x0e\xd8\xb9\ +\x77\xef\xf4\x53\xff\x76\x36\x00\xbc\x30\x10\x90\x00\x9a\x6e\xaf\ +\x07\x52\x52\xe4\x4a\x60\x46\xd2\xef\xfb\x0b\xc1\x85\xe5\x33\x67\ +\x76\x8b\xd0\x59\x88\x01\x77\xef\xb6\x6b\xa5\xc0\x6d\x02\x78\x2e\ +\xb5\x9a\x00\x3a\x68\xd8\xff\x8d\x00\x65\xa0\x8c\xae\x3b\x9d\xc0\ +\xbc\xfa\x6c\xb9\x9c\xcc\x5a\xeb\xcc\x0d\xb0\xd6\x3e\x0f\x96\x36\ +\x01\x54\x52\x2b\x09\x82\x1b\x53\x94\x51\x4a\x1b\x81\xc4\x39\xb3\ +\xda\x6c\x96\xb7\x67\xa7\x76\xc6\xff\x80\x38\x8e\x5f\x04\x4b\xbf\ +\x20\x5d\x3c\xc6\x2f\xbe\xf7\x30\x1c\x30\xb8\x0d\x0a\xa8\xd2\xb8\ +\x5f\xe3\x38\x3e\x37\x0b\xad\x07\xcc\xcc\x80\x28\x6a\xbd\xe2\xc4\ +\x9f\x01\x9c\x4a\x85\x44\x8e\x5f\xfc\x01\xa4\x1c\xb2\xdf\xca\x29\ +\x27\x6e\x59\xdb\x3a\x3f\xb5\xd0\x14\x33\x31\xc0\xda\xe4\xa2\xa0\ +\xdb\x00\x4e\x0c\x04\x04\x01\x70\x43\x3f\xf9\x43\xe8\xe5\xd0\x41\ +\x99\xec\x13\xa0\x36\xac\x4d\xd6\xa6\x53\x3b\xc8\x91\x0d\xb0\x36\ +\xb9\x0c\xe2\x1b\x00\x0b\x03\x01\xd2\x61\x8a\x37\x9f\x81\x74\x20\ +\xd3\xf3\x2c\x80\xf8\xd6\xda\xf8\xcd\xa3\x4e\x7f\x24\x03\xac\x4d\ +\xde\x05\xb1\x9e\x9e\x87\x40\xde\x9b\x9b\x1e\xa9\xb7\x7b\x0c\x62\ +\x40\x7e\x69\x6d\x3c\xea\x68\x7d\x28\x53\xed\x02\x92\x68\xe3\xd6\ +\x27\x04\xf2\x2e\x2f\x0e\xd9\x4d\x7e\x56\x10\x39\x2f\x4d\xc0\xa7\ +\x8d\x5a\xe5\xfd\x69\xee\x0f\x13\x1b\x20\x29\x88\x92\xd6\x75\x08\ +\x97\x73\x84\x38\x16\x57\xfc\xc1\x1a\x64\x7e\xe7\xae\xd7\x6b\x95\ +\xb7\x49\x76\x27\x99\x6f\x22\x03\xc2\x30\x5c\x64\x29\xf8\x0a\xc2\ +\xc5\x8c\x30\xc1\x91\xc5\x16\xdf\xb7\x16\xc9\x1c\x13\x88\xef\xf6\ +\x1f\xec\x5d\x5a\x5e\x5e\x7e\x30\xee\x5c\x63\x1b\xb0\xbd\xbd\x7b\ +\x72\xf1\xe9\xbd\x1f\x00\xe4\x6c\x41\xca\xec\xdb\xc5\x23\x02\xcc\ +\xeb\x84\x9f\xf6\xfe\x59\x5c\x5b\x59\x39\xfd\xf7\x38\xb3\x8c\x65\ +\x40\xbb\xdd\x5e\xda\xef\xb8\x0d\x00\x03\x87\x10\xf5\xfa\x71\xa2\ +\x96\x9b\x35\x12\x4a\xe9\xeb\x83\x80\xdf\x16\x02\x73\xa1\x5c\x2e\ +\xdf\x1f\x95\x3f\xd2\x80\xbf\xda\xed\x6a\xd0\x71\x9b\x00\x56\x06\ +\x12\x09\x69\x82\xd3\x5d\x91\x90\x30\xca\xdc\x1f\xf4\x67\x50\x32\ +\xab\x95\x4a\xa5\x75\x68\xee\x61\xc1\x30\x6c\xaf\x18\xe3\x36\x05\ +\x54\x53\x69\xea\xb5\xfd\xc3\x04\x4d\xef\xb3\xe8\x1f\x42\xec\x3a\ +\x66\xf5\xec\xd9\xf2\x9d\xa1\x59\xc3\x02\x71\x1c\x9f\x73\xe2\x06\ +\x80\xa5\x54\x48\xc0\xc3\xf1\xe6\x73\x30\xc8\xd6\x74\x9f\x70\xaf\ +\xd5\xeb\xf5\x3f\x86\x25\x64\xb0\xb6\xf5\xb2\x13\xb7\xf0\x68\x15\ +\x0f\xe4\x9f\x41\x96\x04\xb3\x15\x86\xc9\x4b\x79\x09\x99\x0e\xb0\ +\x71\x7c\x0d\xe2\x87\x79\xb1\x47\x1c\x81\xfa\xa0\x51\xab\x7d\xd4\ +\x3f\x98\x29\x32\x8a\x92\x8e\x80\xd2\xfc\x74\xcd\x0f\x02\xdd\x7a\ +\xbd\x1a\xf4\x8f\xe5\x1d\x2b\x1f\x5b\xf2\x6a\xcb\x18\x60\xc8\x8f\ +\x73\x2e\x1e\x8f\x01\x74\xbd\xda\x3c\x1e\x8f\xc7\xe3\xf1\x78\x3c\ +\x1e\x8f\xc7\xe3\xf1\x78\x3c\x4f\x36\xff\x01\x8b\x04\x4e\x83\xb0\ +\x2f\x88\xa2\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x03\x2d\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\xdf\x49\x44\x41\x54\x78\x9c\xed\ +\xd5\x3f\x88\x14\x67\x18\xc7\xf1\xef\x33\xb3\x77\x08\x7a\x68\x93\ +\x10\xdd\x99\x9b\x59\xb7\x10\xe2\x35\x91\x2b\xa2\x42\x8a\x20\x01\ +\x95\x24\x58\xd8\x48\x34\x29\x44\xb0\xb0\x08\x81\x60\x0a\x91\x40\ +\x0a\xc1\x10\xb0\x11\x42\x6c\xa2\x45\x24\x11\x84\xc4\xc4\x34\x16\ +\x11\x2e\x68\x63\x75\x58\x68\x74\xde\x99\x59\x41\xcf\x53\x38\x14\ +\x3d\x6f\xdd\x7d\x52\x48\xc2\xde\x70\xfe\xe1\x66\x76\x15\x7c\x3e\ +\xe5\xfb\xcc\xfb\xdb\xe7\x7d\x66\x5f\x06\x8c\x31\xc6\x18\x63\x8c\ +\x31\xc6\x18\x63\x8c\x31\xc6\x18\xf3\xba\x90\xb2\x01\x69\x9a\xbe\ +\xad\x78\xc7\x81\x3a\xca\x77\x51\x14\x7c\x2b\x22\x5a\x41\x6f\x0b\ +\x72\x2e\xdf\x86\x70\x18\x00\x65\x5f\x1c\x87\x67\xcb\xe4\x55\x30\ +\x80\xfc\x2f\x85\xf7\x7a\x96\x4e\xdc\xbf\x37\xb3\x7b\x6c\x6c\x6c\ +\xae\x6c\x76\x2f\x55\x95\x2c\x6b\x7d\xa9\x70\xa8\x67\x79\x66\xfa\ +\xf6\xad\x37\xc6\xc7\xc7\xdb\x8b\xcd\xf5\x4a\x37\x86\x14\x33\x76\ +\x2e\x1b\x59\xfe\x67\x92\x24\x2b\xca\x66\xff\xff\x1b\xaa\xb5\x2c\ +\xcb\x8f\x16\x0e\x0f\x15\xbc\xc0\xd2\x01\x59\x96\x8d\x75\x55\xce\ +\x01\x6f\x16\x4a\x97\xbb\x1d\x7f\xcb\xea\xd5\xab\xd2\x32\xf9\x53\ +\x53\x53\xcb\x1e\x3c\x7c\x74\x12\xd8\x5a\x28\x3d\x12\xbc\xed\x51\ +\x54\xff\xad\x4c\x7e\xe9\x01\x00\x38\xe7\x1a\x88\x7f\x16\x58\x53\ +\x28\xdd\x44\xfd\xad\x71\xbc\xea\xd2\x22\x73\x57\x22\xde\x19\x90\ +\x75\x85\xd2\x5d\xc1\xfb\x28\x8a\xea\x13\x8b\x6a\xb8\x47\xe9\x2b\ +\x00\x10\xc7\x71\xe2\x7b\x6c\x10\x38\x5f\x28\xbd\x85\x74\xce\x3b\ +\xd7\x2a\xbe\xbd\xe7\x4a\xd3\x74\x2d\x9e\x7f\x61\x81\xc3\x5f\xef\ +\xf8\xb2\xbe\x8a\xc3\x43\x45\x03\x00\x08\xc3\xf0\xee\xdc\xdc\xec\ +\x07\x28\x3f\x15\x4a\x4b\x11\xfd\x35\xc9\xb2\xbd\x2f\x9a\xe5\x5c\ +\xeb\x7d\xc5\x9b\x40\x19\x9d\x57\x50\x2e\xb6\x87\x6b\xef\x36\x83\ +\xe0\x4a\x15\x3d\x43\x45\x57\xa0\x97\xaa\x7a\x59\x96\x7f\xa3\xc8\ +\x57\x0b\x94\x0f\x47\xa3\xc1\x7e\x11\xe9\x3e\x6d\x7f\x9a\xb6\x76\ +\x29\x7a\x0c\x18\x9a\x57\x10\x4e\x0f\xf9\xde\x27\xf5\x7a\xfd\x41\ +\x95\xfd\x56\x3e\x80\xff\xa4\x69\xbe\x47\xe1\x28\xe0\xf7\xae\x2b\ +\xfa\x33\xdd\xce\xa7\x8d\x46\x63\x76\xde\xfa\x93\xcf\xdc\x01\x85\ +\xaf\x8b\x59\x0a\x47\xe2\xd1\xe0\x0b\x11\xe9\x54\xdd\x67\xdf\x06\ +\x00\xe0\x5c\xbe\x19\xe1\x17\x60\xe9\xfc\x8a\x4e\xd4\x7c\xef\xe3\ +\x20\x08\xee\x00\x4c\x4e\x4e\x0e\x8f\x8c\xac\xf8\x5e\xd1\xcf\x0a\ +\x11\x2a\xf0\x79\x14\x85\x47\xfa\xd5\x63\x5f\x07\x00\xe0\xdc\x8d\ +\x77\x90\xee\xef\xc0\xca\xde\x75\x85\xab\xbe\xe8\xe6\x76\xbb\x3d\ +\xed\xd7\x86\x4e\x81\x6c\x2a\x6c\x9d\x45\xd9\x11\xc7\xe1\xe9\x7e\ +\xf6\xd7\xf7\x01\x00\x5c\xbb\x76\x63\xd4\xaf\x75\xff\x00\xd6\xbe\ +\xe0\x96\x69\xed\xca\x87\x8d\x46\x70\xa1\x9f\x7d\x41\x85\x5f\x81\ +\x67\x69\x36\xeb\x59\xe7\xf1\xdc\x46\xe0\xdc\xf3\x9e\x55\xb8\xea\ +\x7b\xac\x1f\xc4\xe1\x61\x40\x03\x00\x68\x36\x9b\x33\xf7\xef\xcd\ +\x6c\x11\xf4\xc7\x67\x3c\xf6\xf7\x70\xcd\xdb\x10\x86\xe1\x3f\x83\ +\xea\x6b\x20\x57\xa0\x97\xaa\x8a\xcb\x5a\x07\x05\x0e\x16\x4a\xa7\ +\x7c\x8f\x5d\x61\x18\x3e\x1c\x74\x4f\x2f\x85\x4b\xf3\x1f\x5c\x9a\ +\x3f\x76\x69\xde\x4e\xd2\xfc\x90\xaa\x0e\xec\xdf\xf8\xca\x50\xd5\ +\x5a\x92\x24\x4b\x5e\x76\x1f\xc6\x18\x63\x8c\x31\xc6\x18\x63\x8c\ +\x31\xc6\x18\x63\xcc\x6b\xe2\x5f\xd1\x80\xf4\xd2\x90\x91\xe7\x38\ +\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x2d\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xdf\x49\x44\x41\x54\x58\x85\xe5\ +\x96\xb1\x6b\x14\x51\x10\x87\xbf\xdf\xbb\x43\x82\x82\x47\x2c\x6c\ +\xac\xed\x2d\xad\x2c\x24\xb7\x01\x25\xcd\xc5\x8d\xd5\x05\x64\x15\ +\xd3\x08\xf9\x03\xc4\x42\xec\x45\x10\x54\xe2\x21\x78\x95\xae\x77\ +\x4d\xb0\xf0\x36\x58\x58\x59\x8a\xad\x20\x16\xda\xd8\xe8\x05\x0c\ +\x41\x72\x6f\x2c\x56\xc5\x4a\xf7\xed\x3e\x22\xe8\x74\x03\x3b\x33\ +\xdf\xfc\x76\xe6\x31\xf0\xbf\x9b\x62\x27\x5c\x4c\xb3\x23\xde\xeb\ +\x2d\x60\xc5\xe8\xfe\xfc\x9f\xbe\x6f\xc7\x2c\x9e\xf4\xfb\x87\xfc\ +\x8e\x9e\x02\x9d\xaa\x31\x2e\x56\xf1\x34\x4d\x0f\xd8\xce\xdc\x18\ +\x38\x19\x12\x17\x05\x20\x4d\xd3\xd6\x27\xdf\x79\x08\x96\x84\xc6\ +\xc6\x00\xd0\x67\xdf\xb9\x2d\x38\x8f\x01\xe0\xf7\x15\x60\xe1\x5c\ +\x76\x1d\x58\xc3\x00\x27\x0f\xdf\x31\x2a\x5a\xa3\x21\x5c\xe8\x5d\ +\x5c\x97\x71\x15\x00\xc9\x63\x16\x54\x1c\x1a\x28\xd0\xed\x65\x7d\ +\x89\x9b\x3f\x8b\x13\x5e\xbc\x36\x40\xb2\x9c\x2d\x21\x3d\x28\xbd\ +\x7a\x9d\xd7\x06\x48\x7a\xd9\x29\x43\x8f\x81\x96\x61\x56\xb7\xf3\ +\x5a\x00\xdd\xf4\xd2\x09\x93\xdb\x04\xe6\x30\x33\xa1\xa0\x89\x6f\ +\x04\xd0\x5d\xbe\x7c\x1c\x6f\xcf\xc0\x0e\x1b\x58\xf9\xdf\x9b\x5b\ +\x25\x80\xd3\xe9\xda\x31\x98\x15\xc0\x51\xc0\x14\xb8\xeb\xbf\xb3\ +\x4a\x6b\xd8\xf2\x7b\xef\x7f\x71\xa3\x15\x87\x8a\x0a\x08\x5e\x43\ +\xe0\x0b\x13\x13\x60\xcf\xb5\xcf\x80\xbd\x53\x40\x4c\x54\x80\xe7\ +\xf9\xdd\x0f\xd0\x4e\x80\x8f\x80\x2c\x22\x44\xe5\x44\xc5\xe8\xde\ +\x1b\x9c\x16\x41\xdb\x2a\x0f\x99\x28\x10\x41\x49\x8a\x7c\xe3\x95\ +\xcc\x2f\x01\xbb\x80\xcc\x9a\x43\x04\x27\x98\x8c\x07\x2f\x84\xad\ +\x00\x33\x09\x81\x1a\x9d\x75\xb5\x3a\x98\x8c\x06\x9b\x98\x5d\x28\ +\x3d\x73\x34\xb8\x2d\x6b\x4b\x58\x8c\x07\x43\xd0\xfa\x8f\x3c\xa5\ +\x1a\xfb\x08\x00\x50\x8c\x36\x6e\x99\xec\x06\x80\x79\x9c\x6a\x28\ +\xd1\x78\x88\xb6\x9e\x0c\xae\x09\xee\x20\x30\xc3\x11\xa8\x44\x8c\ +\x55\xb2\x8e\x9b\x5e\x31\x78\x84\x80\xc0\xcd\x88\xb2\xcb\x79\x9e\ +\xcf\xe6\xdd\x74\x15\x34\x09\x8d\x8d\xf6\xa2\xe5\x79\xfe\x55\x07\ +\x77\x7b\xc0\xcb\xbf\x02\x00\x30\x19\x0e\xbf\x38\x67\x67\x91\xb6\ +\x81\x69\xcc\xdc\xff\xae\x7d\x03\x68\x47\x95\x0a\x88\x7f\x49\xe0\ +\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x03\x38\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\xea\x49\x44\x41\x54\x78\x9c\xed\ +\x98\xc1\x6b\x13\x41\x18\xc5\xdf\xb7\x69\xda\xb4\x45\x2a\xa2\xf5\ +\x90\x4c\x36\x09\x04\x4f\xde\x8a\x15\xaa\x17\x11\x04\x2f\x2a\x82\ +\x22\x1e\xec\x41\x10\x04\xe9\xc5\x9b\xa0\x07\xbd\x89\x7f\x81\xa0\ +\x1e\xa4\x78\x11\x44\xa1\x08\xa2\xf5\x20\x1e\xbc\x29\x82\x2d\xb1\ +\xcd\x4e\x36\x11\xb4\x05\x4d\x15\x1b\x9a\x64\x3f\x4f\x62\x93\x6c\ +\x4d\x0b\x99\xd9\x1e\xbe\xdf\xf1\x7d\xb0\xef\xcd\xdb\x59\x66\x58\ +\x40\x10\x04\x41\x10\x04\x41\x10\x04\x41\x10\x04\xa1\xc7\x78\x9e\ +\x3f\xed\x69\x9f\x3d\xed\x73\xb1\x54\x9a\x8c\x3a\x4f\x3b\x64\xf2\ +\xe1\xc5\x62\x31\x41\x4e\xdf\x6a\x8b\xc8\x74\x24\x93\x49\xcd\x9a\ +\xf4\xdd\x0a\x8e\xc9\x87\x0f\x0f\x0f\xf7\x75\x88\xc4\xaf\xb4\xd6\ +\x39\x93\xbe\x5b\xc1\x68\x01\xa3\xa3\xa3\xbf\xc2\x74\x86\xb3\x30\ +\x37\xb7\xb4\xc3\xa4\xf7\x66\x31\x5a\x00\x00\xb8\xe9\x54\xe7\x2e\ +\x00\x90\x18\xac\xad\x30\xb3\x71\xff\x6e\x18\x0f\x40\x44\xcd\xfa\ +\x5a\x6d\x24\x6c\xa6\x4b\xe5\xa6\x69\xff\x6e\x58\x79\x03\xf9\x7c\ +\x7e\x25\xe6\x20\x1f\x36\xf3\x74\xe9\x8d\x8d\x0c\x1b\x61\x6d\x0b\ +\x2a\xa5\x3e\x13\xe8\x68\xe7\x84\x26\xbc\x92\x7f\xdb\x56\x8e\x76\ +\xac\x7e\x83\xae\x9b\x7a\x09\xc6\x95\x8e\x01\xe3\xaa\xe7\xf9\xe7\ +\x6d\x66\xf9\x8b\xd1\x7b\xc0\x46\x68\x5d\x7a\xc0\xa0\x0b\xed\x7a\ +\xe0\x60\x3c\xa7\xd4\x3b\x9b\x59\x22\x29\x00\x00\x3c\xed\x2f\x00\ +\xe8\xb8\x0f\x38\xc4\xc9\x74\x3a\xfd\xc5\x56\x8e\xc8\x0a\x00\x00\ +\x4f\xfb\x1c\xa6\xc7\x1c\x0c\x29\xa5\x56\xc3\x66\xbd\x26\xd2\x73\ +\x78\x79\xe9\x6b\x7f\x98\xde\x0c\xf0\x9b\x99\xad\xbc\x9c\x48\x77\ +\x00\x00\x54\x2a\x95\xdd\xf5\x46\xb0\x14\x32\xaa\x66\x5c\xb5\xd3\ +\xb4\x7f\xe4\x37\xb1\x64\x32\xb9\xec\x10\xef\x0f\x19\x8d\x68\x5d\ +\x7e\x64\xda\x3f\xf2\x02\x00\x20\x9d\x4e\x7f\x64\xe2\x93\xed\x3a\ +\x83\xcf\x9a\xf6\xde\x16\x05\x00\x00\x9a\xb1\xf9\x28\x6c\xb7\x45\ +\x01\x8b\x8b\x8b\x7b\xc9\x09\x66\x42\x46\x6f\x4d\x7b\x47\x5e\x40\ +\xa5\x52\x19\x8a\xc5\xe2\x4f\x01\x64\x5b\x06\x44\x37\x33\xae\x9a\ +\x30\xed\x1f\x69\x01\xcc\x1c\x6b\x34\x82\x69\x06\x0e\xb4\x8d\xee\ +\xba\x2a\x79\xc3\x46\x86\x48\x0b\xf0\x4a\xe5\x3b\x0c\x9c\x68\x11\ +\x19\xcf\xdd\x74\xea\x32\x11\x85\x5e\x92\x7a\x4d\x64\x05\x68\xed\ +\x4f\x11\x30\xd5\x22\x12\xde\xd7\x6a\x89\x33\x44\xd4\xb0\x95\x23\ +\x92\x8b\x90\xe7\xf9\xa7\x40\x78\xdc\xe6\x5f\x8e\x39\x38\xa8\x94\ +\xaa\xd8\xcc\x62\xbd\x80\xa2\xef\x8f\x53\x80\x59\x00\x83\xeb\xe4\ +\x9f\x81\x83\x43\x39\xa5\x3e\xd8\xce\x63\xf5\x13\xd0\x5a\xe7\xa8\ +\x89\x67\x68\x5d\x7c\x83\x10\x9c\x8e\x62\xf1\x80\xc5\x02\x7c\xdf\ +\xdf\xc5\x70\x66\x40\xd8\xd3\x32\x60\xbe\xe4\xba\xee\x0b\x5b\x39\ +\xda\x09\xfd\x63\xdb\x6b\x0a\x85\xc2\x40\x23\xc0\x13\x02\xf6\xb5\ +\x0c\x88\x6e\x65\x5c\x75\xcf\x46\x86\x8d\x30\xbe\x03\x98\xd9\x89\ +\xc7\x13\xf7\x09\x38\xdc\x36\x7a\xe8\xaa\xe4\x75\xd3\xfe\xdd\x30\ +\x5e\x80\xd6\xfe\x35\x10\xce\xb5\x88\x84\xd7\xf5\xb5\xda\x45\x5b\ +\x67\xfd\xff\x30\x7a\x0a\x14\x0a\x85\x81\x78\x7f\xe2\x07\x80\xc4\ +\x3f\x95\x3f\x11\x78\xc2\x75\xdd\xef\x26\xbd\x37\x8b\xd1\x1d\x50\ +\xad\x56\x03\x00\xf5\x75\xd2\x37\x0e\x9a\xc7\xb7\xcb\xe2\x01\xc3\ +\x05\x8c\x8d\x8d\xd5\xc1\x98\x04\xb0\x0c\x60\x9e\x03\x3a\x96\xcd\ +\x66\x3d\x93\x9e\x82\x20\x08\x82\x20\x08\x82\x20\x08\x82\x20\x08\ +\xdd\xf8\x03\x6a\x65\xdc\x45\x31\x50\xc4\x7d\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x9a\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x4c\x49\x44\x41\x54\x58\x85\xed\ +\xd7\xc1\x09\x00\x20\x0c\x04\xc1\x20\x16\x66\xe1\x82\xad\x48\x52\ +\x48\xec\x40\x3d\xf1\xb9\xfb\x3c\x08\xcc\x37\x66\x24\x36\x3d\xc6\ +\xf4\x18\xb7\xfb\xa9\x2a\x0b\xd2\x9a\xb4\x1f\x2a\x2f\x47\x3f\x03\ +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xfd\x33\xb2\ +\xec\xda\x4e\xfb\x16\xbe\x7b\x13\xbf\x30\xe2\x93\xe7\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x06\xf1\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x06\xa3\x49\x44\x41\x54\x78\x9c\xed\ +\x9a\xcd\x73\x5b\x67\x15\x87\x9f\xf3\xca\xed\x24\x84\x3a\x4d\xbf\ +\x99\xae\xd8\x36\x6d\xda\xea\xc3\x21\x94\x81\xc6\x49\x6d\x27\x8d\ +\xe3\xfe\x01\x85\x45\x07\xf9\x63\x6a\x4b\x86\x55\x59\xc0\x82\xc9\ +\x02\x86\x81\xda\x96\xa7\xb6\x6c\x66\xd8\xf5\x1f\xa0\x09\x89\xbf\ +\x42\x81\x36\xb1\x25\xab\x1f\x40\x37\x9d\x4e\x17\x1d\x86\x19\x4a\ +\x0b\x71\x9a\x26\x4a\xf0\x7b\x58\xc8\x37\x88\x2b\xd9\x7a\xaf\x74\ +\x6f\x6d\x06\x3f\xcb\xf7\x9e\x7b\xde\xf3\xfb\xe9\x9c\x57\xd2\x95\ +\x60\x97\x5d\x76\xf9\x7f\x46\xea\x2d\x1e\xfa\xf6\xcf\xf6\xdd\xb1\ +\x77\xcf\xf7\xc5\x68\x2f\xca\x1e\x90\x4b\x66\x9d\x9f\xac\xfc\x72\ +\xe4\xc3\x2f\xba\xc0\x66\xe8\xf8\x6e\xee\xab\x36\xc6\x4b\xa0\x47\ +\x10\x6e\x60\xe5\xec\xe7\x6d\xe6\xe7\xef\xbd\xf2\xe2\x67\xfe\xd8\ +\x1a\x03\x9e\x7a\xe1\xa7\x77\x95\xef\xd8\xfb\x3a\xf0\xa4\xef\xd2\ +\x15\x55\xdb\xbd\x3a\x33\xba\x1c\x55\xe1\x61\x90\x4a\x8f\xa5\xd4\ +\x98\x79\x60\x7f\xf5\xba\xc2\x3b\x6d\x77\xf2\xcd\xe5\x5c\x66\xad\ +\x7a\xdd\xf8\x13\x94\xef\xdc\xfb\x12\xb5\xe2\x01\xf6\x8b\x98\xb9\ +\x44\xff\xd8\xe1\x50\x2b\x0e\x91\xcd\xc4\x03\x08\x3c\x6e\x6f\xe9\ +\x0f\xfc\xeb\x35\x06\xa0\x9c\xde\x62\x8f\xf6\x9d\x6a\xc2\x56\xe2\ +\x3d\xd4\x9a\x3e\xff\x5a\xad\x01\xb0\xb7\xc1\x5e\xed\x22\x66\x2e\ +\x39\x38\xd1\x11\xb0\xc6\xc8\xe8\x18\xc8\x25\x1b\x89\x07\x40\x74\ +\x8f\x7f\xa9\x9e\x01\x6f\x38\xec\xd9\x8e\x32\xbf\x13\x4c\xe8\x18\ +\xc8\x25\x2d\xba\x40\x23\xf1\x00\x68\x8d\xb6\x1a\x03\x62\xe8\x19\ +\xe0\x8a\xc3\xde\xdb\x6e\x42\x30\xf1\xac\xc5\xe0\xc7\xfe\xc5\x1a\ +\x03\x96\xf3\xd9\xf7\x11\xba\x70\x37\x61\x5b\xc6\x61\x43\x7c\xe3\ +\xb6\xaf\xb0\x66\x0d\xdd\xcb\xf9\xec\xfb\xfe\x0b\xf5\x46\x80\xe2\ +\x74\x66\x65\xc3\x84\xb5\x7a\xd7\x7d\xec\x47\x99\x4b\xa5\xc7\x52\ +\x0e\xb1\xa1\x10\x1f\x1a\x4f\x6c\x88\xbf\xdb\x21\xfc\xaa\x35\x74\ +\x97\xa6\x32\x97\xeb\x5d\xac\xfb\x41\xc8\x23\x39\x38\xd1\x81\x32\ +\x0f\xb4\x3b\x6c\x74\x45\xac\x7d\xa6\x30\x3b\x5a\x70\x88\x6d\x9a\ +\xf8\xd0\x78\xc2\x58\x59\xc0\x5d\x7c\xd7\x66\xe2\xa1\x81\x01\xb0\ +\xb3\x4c\x08\x5b\x3c\x38\x18\x00\x90\xe8\x1f\x3b\x2c\x62\xe6\x70\ +\x34\xc1\x20\xc7\x57\xf2\x23\x45\x97\xdc\xae\x24\xfa\x27\xe3\x22\ +\x76\x01\x38\xe0\x10\x7e\xd5\x60\xba\x57\xf2\xc3\x97\x1a\x05\x3a\ +\x19\x50\x29\x60\xfb\x4c\x88\x4a\x3c\x6c\x72\x08\xd6\x63\x75\x66\ +\x74\xd9\x1a\xba\x71\x3c\x18\x2d\xba\xd0\x31\x90\x4b\xba\xe6\xdf\ +\x8c\xa0\xe2\xc5\x6a\x8f\xab\x78\x08\xd0\x01\x1e\xf1\xa1\x89\xaf\ +\x19\xcb\x1c\x70\x97\x43\xf8\x3f\x0d\xf2\x4c\xb3\x9d\x10\x50\xfc\ +\x67\x62\xb5\xbb\x30\x9b\x7d\x33\xc8\x1e\xce\x1d\xe0\x51\x9a\xca\ +\x5c\xb6\x86\x2e\xe0\xaa\x43\xf8\xdd\x16\x9d\x8f\x0f\x8d\x27\x82\ +\xee\xf3\x45\x88\x87\x26\x3a\xc0\x23\x68\x27\x58\xa3\xc7\x4b\x53\ +\xd9\x55\x97\xdc\xc9\xc1\x89\x27\x51\x16\x89\x58\x3c\x34\xd1\x01\ +\x1e\xa5\xa9\xcc\x65\x83\xe9\xc6\xb1\x13\x8c\x95\x05\x97\x4e\x08\ +\x2a\x1e\x91\x9e\x66\xc5\x43\x0b\x1d\xe0\xd1\x31\x30\x79\xc4\x62\ +\x2f\x10\x42\x27\x34\x23\xbe\x38\x3d\xe2\xf2\xe5\x6d\x53\x9a\xee\ +\x00\x8f\x95\xfc\xf0\x25\xb1\xda\x83\x7b\x27\xcc\x27\xfa\x27\xe3\ +\xfe\x0b\x1b\xe2\x9d\x67\x5e\xd5\x9e\x68\x55\x3c\x84\x60\x00\x40\ +\x61\x36\xfb\xe6\x86\x09\x35\xcf\xdc\xea\x70\x40\xc4\x2e\x54\x9b\ +\x90\x4a\xbf\xfc\xc4\x86\xf8\x7b\x1c\xee\xbf\xa6\x6a\x4f\xac\xce\ +\x8c\xfe\xa1\xd9\x7a\xab\x69\x79\x04\xaa\x49\xa5\xc7\xbf\xae\x46\ +\x2e\x00\x5f\x76\x08\xff\x87\xaa\x39\x6e\xf4\x96\x55\x13\x5b\xc4\ +\x5d\x7c\x4f\x58\xe2\x21\x64\x03\x20\x98\x09\x82\xae\x69\xa5\x04\ +\x97\x4f\x97\xa1\x8b\xaf\xd4\x10\x01\xc9\xc1\xdc\x53\xa8\x9e\xc7\ +\xad\x13\x5c\xb8\x66\x0d\x27\x4a\x53\x99\xdf\x87\x94\xef\x36\x91\ +\x18\x00\xa1\x9a\x10\x99\x78\x08\xe9\x10\xac\x47\x71\x7a\xe4\x0d\ +\x55\x7b\x02\xb7\x83\x71\x33\xae\x09\xf6\x64\x54\xe2\x21\xc2\x0e\ +\xf0\x48\xf4\x8f\x7d\x43\xc4\x9c\x07\xf6\x05\xbc\xf5\x9a\x60\x4f\ +\x16\xf2\xa3\xbf\x8b\xa2\x2e\x8f\xc8\x0d\x80\x8a\x09\xc6\x98\x39\ +\xd5\x86\x8f\xdc\x3d\x6e\x08\xb6\x3b\x6a\xf1\x10\xe1\x08\x54\xa3\ +\x31\xd6\x54\xe5\xa6\xf3\x0d\xc2\x4d\xac\xba\x7c\xed\x6e\x99\xc8\ +\x0d\x88\x0f\x8d\x1d\x32\xd6\x2c\x81\xba\x3c\xbd\xad\xa0\xb4\xab\ +\x89\x2d\xa6\xd2\x2f\x3f\x11\x61\x69\x40\xc4\x23\xf0\x1f\xf1\xdc\ +\xdb\x64\x8a\x4f\xc5\xae\x1f\x2b\xcc\x7e\xef\xed\x30\xeb\xaa\x26\ +\x32\x03\x36\xc4\x2f\x02\xf7\xb5\x98\xea\x53\x03\x9d\x2b\xf9\xcc\ +\x3b\x61\xd4\xe5\x27\x12\x03\x12\xfd\xb9\xc7\x44\x74\x89\xd6\xc5\ +\x7b\x44\x66\x42\xe8\x67\x40\x10\xf1\x0a\x65\x85\xb2\x43\xda\x7b\ +\x2c\x2c\x76\x0c\x4c\x3c\xde\x7a\x85\xff\x4d\xa8\x06\x04\x7c\xe5\ +\xaf\x8b\x48\x8f\xc1\x76\x01\x9f\x3b\xc4\xdf\x1b\x85\x09\xa1\x8d\ +\x40\x72\x70\xfc\x51\x54\x2e\xe2\x28\x5e\x55\x9f\x5d\x9d\xc9\x5e\ +\x04\x48\xa5\x27\xbe\xa5\x86\x73\xc0\x97\x1c\xee\xfd\xc4\x1a\xdb\ +\x59\x9a\x1a\x7d\xb7\x95\x7a\x3d\x42\x31\xa0\x15\xf1\x1e\xdb\x65\ +\x42\xcb\x23\x10\x54\xbc\x15\x39\xe5\x17\x0f\x50\x98\xcd\xbc\x8e\ +\xc8\xb3\x38\x8e\x83\xb1\x66\x29\x3e\x34\x76\x28\x68\xbd\x7e\x5a\ +\x32\x20\x39\x38\xfe\x28\x88\xf3\xcc\x5b\x91\x53\xa5\xe9\x91\xa5\ +\xcd\x02\x8a\xd3\x23\xbf\x0d\x68\xc2\x62\xab\x26\x34\x3d\x02\xb7\ +\xc5\x2b\xf7\x3b\x84\x5f\x17\xb4\xb7\x90\xcf\x2e\xba\xe5\xce\x3d\ +\x8d\xea\x39\x1a\xff\x5d\x07\xe0\xef\xaa\xd2\xb9\x3a\x33\xf2\x47\ +\x97\xdc\x7e\x9a\xea\x80\x54\x7a\xf2\x60\x00\xf1\x37\x82\x88\x87\ +\xdb\x9d\x70\x12\xb8\xee\x10\x7e\x9f\x88\x2e\x25\xfa\x73\x8f\xb9\ +\xe6\xaf\x26\x70\x07\xa4\xd2\x93\x07\x35\x66\x2f\x06\x10\x7f\x2a\ +\x88\xf8\x6a\x12\xfd\xe3\x47\x45\xe4\x2c\x11\x76\x42\x20\x03\x52\ +\xe9\xc9\x83\x18\xbb\xa4\xf0\x80\x43\x78\x4b\xe2\x3d\x82\x9a\x80\ +\xe8\xd1\xe2\x74\xf6\x4f\xae\xf9\x9d\x0d\x08\x2a\x1e\x4b\x6f\x71\ +\x36\xb3\xe0\x9a\x7f\x2b\xe2\x83\xb9\x4e\xa3\xfa\x1a\x11\x98\xe0\ +\x64\xc0\xe1\x81\x89\x47\x2c\x5c\xdc\x0e\xf1\x1e\x51\x99\xd0\xf0\ +\x10\x0c\x2c\x1e\x73\x3a\x6c\xf1\x00\xa5\xe9\x91\x25\x41\x7b\x71\ +\x3c\x18\x41\x96\x2a\xef\x54\x5b\xb3\x65\x07\x34\x25\x3e\x3f\x3c\ +\xef\x10\xdb\x34\xa9\x81\xf1\x63\x8a\xbc\x06\xd4\xfc\xeb\xb3\x06\ +\xe1\x63\xd0\xce\xad\x3a\x61\xd3\x0e\x38\x3c\x30\xf1\xc8\x3a\x38\ +\xcf\xbc\x2a\x7d\x51\x8b\x07\x28\xe4\xb3\x8b\x82\x9e\x02\x6e\x34\ +\x0c\x56\xee\x07\x59\xaa\xbc\x6d\xd7\xa7\x6e\x07\x78\xe2\x81\x07\ +\x1d\x6a\x2a\xab\x72\x7a\x75\x26\x33\xe7\x10\x1b\x1a\x41\x3b\x41\ +\xd6\xcd\xd1\xc2\xec\xf0\x9f\x6b\x2f\xf9\x38\x32\xf8\x8b\x87\x6f\ +\x69\x5b\x11\x78\xc8\xa1\x8e\x6d\x11\xef\x91\x4c\x4f\x1c\xc7\xf0\ +\x6b\x1c\x4c\x10\xf8\x1b\xb1\x58\xb2\xf0\xca\x8b\x1f\x55\xaf\xd7\ +\x8c\xc0\x2d\xdb\xf6\x43\xfe\x07\xc4\x03\x14\x67\x33\x0b\x58\x7a\ +\x71\x18\x07\x85\x07\xb0\xeb\x3f\xf2\xaf\xd7\x9e\x01\xc2\xd3\x0e\ +\x7b\x97\xad\x48\xdf\x76\x8a\xf7\xa8\xbc\xe3\x98\xd3\xb8\x98\xa0\ +\x1c\xf5\xaf\xd5\x18\xa0\xb0\xde\x20\x4f\xd9\x8a\xf4\x95\xa6\x47\ +\x2e\xb8\x97\x19\x2d\x95\xc3\xd7\xc9\x84\x1a\x6d\x35\x06\x08\x6c\ +\xf5\xaa\x96\x05\x7d\x6e\x27\x89\xf7\x28\xe6\x87\xe7\x55\xe9\x63\ +\x0b\x13\x44\x38\xef\x5f\xab\x31\xc0\xb4\x99\x33\xc0\x07\x75\xee\ +\x2f\x0b\xfa\x5c\x21\x9f\xad\x49\xb2\x53\x58\x9d\xc9\xcc\x6d\x61\ +\xc2\x87\xff\x2a\x73\xc6\xbf\x18\xf3\x2f\xfc\xa5\x70\xee\xfa\x57\ +\x12\xc7\x5e\x15\x89\xed\x43\x79\x50\x84\x9b\x28\x8b\x8a\xf9\x4e\ +\x71\x26\xba\x5f\x69\xc3\xe2\xaf\xab\xbf\xf9\xe0\xe1\x78\xd7\x59\ +\xc4\x3c\x04\x1c\x40\xf9\x44\x45\x5f\xb5\x37\xe5\xf9\xb7\x7e\x95\ +\xf9\x78\xbb\xeb\xdb\x65\x97\x5d\x76\x16\xff\x06\x5e\xec\x1f\xa0\ +\xf6\x5e\x26\xad\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\ +\x00\x00\x02\x06\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xb8\x49\x44\x41\x54\x58\x85\xed\ +\x97\xcf\x4a\x1b\x51\x14\x87\xbf\x33\x49\x56\x25\x42\x2b\xa9\xe0\ +\x6b\x34\xff\x8a\xc5\x07\x68\x4a\x5f\xa2\xc1\x94\x6a\x46\x29\x25\ +\xf6\x11\x1a\xa1\x25\x99\xd8\xa2\x45\x17\x92\x95\x0f\x10\x70\xd3\ +\x2e\x04\xab\x69\x93\xd7\x10\x34\x28\x94\x2c\x63\x72\x5c\xcc\x64\ +\x0c\xc6\x8e\x98\x4c\x62\x69\xf3\x5b\xde\x7b\xb8\xdf\x37\xf7\x5c\ +\x86\x7b\xe1\x7f\x8f\x5c\x1f\x88\xbe\x2e\xcd\xa1\xba\x8a\x90\x44\ +\x89\xf8\x44\x69\xa0\x1c\x21\x92\xaf\x6d\x64\x0f\xfe\x28\x10\xcb\ +\x14\xdf\x29\xb2\x76\x93\x98\x4f\xe9\xa8\x92\xab\x7f\x35\x3f\xf6\ +\x09\x3c\x59\x28\x3c\x13\x31\xf6\x81\xdf\x88\x9a\xa1\x56\xbb\x72\ +\xb8\xfd\xf6\xdc\x0f\xea\xd3\x57\x9f\x1e\xb5\x42\x81\x14\x2a\x16\ +\x30\x85\xc8\x7c\x77\x27\x82\xae\x89\x18\x39\x40\x10\x35\x6b\x1b\ +\xcb\x65\x3f\xc0\xdd\x38\x1f\x52\x8e\x66\x2c\x01\x76\x50\x5d\x05\ +\x5e\x02\x18\x6e\x95\x90\x04\x08\xb5\xda\x15\x3f\xe1\xbd\x31\x82\ +\x46\xc5\x46\x91\x70\xc7\xdc\x59\xe7\xc0\xf9\xb5\xed\x37\xe5\xe7\ +\xe7\xa5\x33\x1b\xc5\xe3\x7e\x81\x7b\xca\x44\x60\x22\x70\xef\x02\ +\xc1\xdb\x0a\x62\x99\xd2\x1b\x45\x3f\x00\xe1\x3b\xae\xdd\x14\xe4\ +\xfd\xaf\xcd\xec\x17\xaf\x22\xcf\x1d\x48\xa4\x0b\x33\x8a\x96\x06\ +\x80\x03\x84\x15\xb5\x12\xe9\xc2\xcc\xc0\x02\xe3\x88\xa7\x40\x75\ +\x6b\xe5\x44\x90\x2c\xd0\x1c\x60\xed\xa6\x20\x66\x75\x6b\xe5\xc4\ +\xab\xe8\xd6\x33\xe0\xf4\xd0\xb3\x8f\xc3\xe4\xef\x6e\xc1\x44\x60\ +\x22\x30\x5e\x01\xa1\x01\xf6\x05\x72\x54\xb0\xf8\xe2\xfa\xb4\x8d\ +\xe2\xb4\x5f\x40\x39\x02\x68\x85\x02\xa9\x51\x09\x74\x2e\x3a\x29\ +\x1b\x45\xb5\x3b\x76\xf5\x23\x12\xc9\xa3\xfa\x02\x15\x2b\x9a\xb1\ +\xc4\x08\x1a\x95\xee\x1d\x6e\xd8\xc4\x17\xd7\xa7\x1d\x78\x11\xe8\ +\x20\x92\x77\xb1\xbd\x85\xce\xc3\x24\xcf\xe8\xce\x46\xdf\xc3\x24\ +\xd0\x3b\x7b\x5c\xdf\xfb\x31\x1b\x7b\xfe\x0d\x88\x08\x3c\x04\x1e\ +\xf8\x41\x75\x7a\xfe\x1d\x91\x74\x7d\xd3\xdc\xf5\x63\xcd\x7f\x27\ +\x97\x00\x43\x86\x87\x3f\x9c\xa0\xff\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x02\x37\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xe9\x49\x44\x41\x54\x58\x85\xed\ +\x94\x31\x68\x13\x61\x14\xc7\x7f\xef\x8e\x50\x8d\x20\x75\x50\x8a\ +\x93\x29\xe2\x24\xa2\xa5\x71\x11\xdc\x44\x91\x8e\x8a\x53\x41\x87\ +\xda\xa0\x49\x8a\x83\x93\x08\xea\xea\x60\x4d\x5b\x6b\xeb\xe0\xa0\ +\xa0\x58\xc4\x41\x07\xa5\x53\x71\x50\xa8\x8d\x5a\xc4\xc9\xc1\x45\ +\xa1\x88\x56\x45\x4b\xb5\xb9\xfb\x3b\x24\x67\xcf\x60\x9b\xbb\x58\ +\xec\x72\x3f\x38\xf8\x8e\x7b\xef\xff\xfe\xef\xde\xf7\x7d\x90\x90\ +\x90\x90\xb0\xca\x58\xb0\xe8\x3c\x5e\x9a\xc5\x68\xfd\x2f\x55\xc5\ +\xe7\x67\xa3\xc5\x0d\x00\x4e\xc8\x8a\xb3\x64\xc2\x4a\x13\xaa\xf5\ +\x7b\x91\xaa\x54\x32\x06\x4f\x83\x77\x21\x1f\xf0\x56\xe2\x11\xf8\ +\xa1\xf2\x4f\x52\x95\x4a\x66\xd1\x4b\x88\x1d\xdd\x17\xd7\xb5\xa4\ +\x5b\xee\x0a\xf6\x23\xc0\xe4\x83\xe9\x5f\x9a\x15\x32\xc3\x82\x46\ +\x1f\xfe\x9c\xfb\x71\x68\xfa\xc6\xe9\xef\xc1\x77\x37\x1c\x3c\x33\ +\x3d\xbe\xd0\xda\xbe\xfb\x4e\x6a\x6d\x7a\x1b\xc6\xf6\xaa\xc1\x3f\ +\x3c\xc6\x2b\x6e\x2c\x16\x97\xdd\x9e\x9b\xfd\x78\xe4\xd5\xad\x33\ +\xf3\xe1\x18\xb7\x3e\xe9\xc3\xeb\x09\x6f\x4f\xfb\xb1\x7b\x5f\xd2\ +\xdf\x36\x82\x65\x01\x93\x09\x8b\x69\x44\x60\x56\x1b\xb1\x19\xc3\ +\x99\x4f\x6d\x3d\x13\x63\xf9\x4a\x7d\xdc\x32\xaa\xb2\x6c\xae\x74\ +\x5e\xb2\xb3\xb5\x48\x1f\x11\x6d\x1c\x86\xa1\x6a\x71\xc1\x85\xa9\ +\x91\xc2\xb9\xa5\x46\xd9\xb0\xad\x6c\xef\x40\x9f\x50\x3f\x80\xaa\ +\x03\xf5\x1b\xa4\x38\x81\xae\x44\xdf\xd4\x68\xb1\xb4\xbc\xd7\x08\ +\x74\xe6\x2e\x77\x23\xbb\x0e\xb8\x02\x19\x7f\x37\x21\xe1\x58\x75\ +\x56\x9e\x61\x47\x27\x47\x0a\x37\x1b\x69\x47\x1e\x6c\x47\x6e\xb0\ +\xcb\x91\x3f\x06\xac\x01\x44\xbd\x09\x99\x83\xc9\x80\x79\xdf\x9c\ +\xc3\xe5\xab\xf9\x07\x51\x74\x63\xed\xac\x6c\x6f\xff\x5e\xe1\xdc\ +\x07\xd6\xd7\x99\x08\x7e\xfb\x57\xdf\xa1\xab\x3c\x5c\x7c\x1c\x55\ +\x33\xf6\x19\xcb\xf6\x5c\xda\x89\xe3\x3e\x12\x6c\x02\x54\xdb\xed\ +\x00\x33\xe6\x7b\x07\x26\xaf\x9d\x7a\x11\x47\xaf\xa9\x43\xde\x71\ +\x62\x68\xab\x79\xde\xb8\xc1\x16\x00\xc1\x5b\xb9\xee\xbe\xf2\x95\ +\x93\x6f\xe2\x6a\x35\x7d\xcb\xec\xca\x0f\x6c\x76\x17\xf4\x4e\xf0\ +\xd2\x4f\xd9\xc1\xe7\x83\x85\xf7\xcd\x6a\x25\x24\x24\x24\xac\x2a\ +\xbf\x00\xaf\x38\xac\x82\xe2\x51\x10\x13\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x04\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xb6\x49\x44\x41\x54\x78\x9c\xed\ +\xd9\xd1\x0d\x83\x50\x0c\xc5\xd0\x14\x75\x8d\x0a\xf6\x9f\x0a\xc4\ +\x20\x74\x8c\x83\xf4\xec\x05\x62\x59\xf7\x2f\x33\x90\xf3\xba\x9f\ +\xf3\xba\x1f\xe9\xb0\xc9\xe3\x6f\xa0\x00\x5a\x40\x53\x00\x2d\xa0\ +\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\ +\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\ +\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\xe5\ +\x03\x7c\xe4\x71\xfd\x1a\x9f\x69\x01\xf3\xd5\x02\x33\x33\xc7\xfe\ +\x63\x4b\x5c\x7e\x01\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\ +\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\ +\x0a\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\ +\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x2c\x1f\xe0\x0f\xc7\ +\xa8\x0b\xc6\x03\x24\x5a\xc7\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ +\x42\x60\x82\ +\x00\x00\x00\x8a\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3c\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\x01\x09\x00\x20\x10\x04\xc1\xd7\x4c\x76\xb2\x8f\x85\xfd\x14\ +\x72\x20\x33\x09\x96\xad\x02\x00\x00\x00\x00\x00\x00\xe0\x7f\x63\ +\xed\x73\xd3\x11\x49\x33\x1d\x90\x66\x40\x3a\x00\x00\x00\x00\x00\ +\x00\x00\x00\xde\x6b\x42\xab\x02\x34\xd3\x03\x1d\x60\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x03\x68\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x1a\x49\x44\x41\x54\x78\x9c\xed\ +\xd6\x4f\x6c\x14\x65\x18\xc7\xf1\xef\x33\xdb\xad\x44\xc4\x34\x01\ +\xa3\x04\x82\x4a\x0f\xc4\x02\x51\xeb\x09\x88\x64\x85\xdd\x25\xa4\ +\xa9\xc8\x6e\x97\x10\x62\xb1\xa6\xdb\x46\x4c\x3c\x18\x13\x6f\xa6\ +\xf1\x46\x82\x91\x70\x69\x42\xff\x24\x04\x4d\x54\xa6\x7f\x38\x28\ +\xe8\x96\x26\x94\xa4\x88\x46\xca\xad\x1e\x80\x9a\x08\x21\x46\x10\ +\xc1\x90\xd0\x52\xf6\x7d\xbc\x70\xd8\x0e\x45\xb0\x33\xbb\x84\xf0\ +\x7c\x8e\xf3\xcc\xfc\xf6\xf7\xbe\xb3\xb3\xb3\x60\x8c\x31\xc6\x18\ +\x63\x8c\x31\xc6\x18\x63\x8c\x31\xc6\x98\xc7\x85\x84\x0d\xd8\x98\ +\x7b\xb7\xce\x2b\xc6\x0e\x8a\xb0\x04\xf8\xbc\xd0\xdf\xf3\x19\xa0\ +\xe1\xab\xcd\x2e\x95\x69\xdb\x2a\xa2\x7b\x00\x10\xf9\xa0\xd0\xd7\ +\x7d\x34\x4c\x5e\xe8\x0d\x48\x65\xf3\x23\xc0\xfa\x92\xc8\x2f\x6a\ +\xbc\x6b\x79\xdf\xf7\x6f\x85\xcd\x0e\x90\x54\x53\xdb\xc7\xa8\xee\ +\x2e\x39\x76\xfd\xea\x42\xef\x99\xd3\x5d\x5d\xd3\x73\x0d\xf5\x42\ +\xd7\x52\x0d\x64\x68\xf3\xdf\xae\xe6\xfb\xc4\x5b\x2d\x35\xa1\xb3\ +\xef\x48\x24\x3a\xaa\x52\xd9\x7c\x67\x60\xf1\x80\x84\xbe\x81\xa1\ +\x37\x40\x94\x5d\xc0\x9f\x33\x8e\xa1\x6f\xc4\x63\xf1\xd1\x0d\x99\ +\xd6\xe7\xc3\xe6\x27\x72\xef\x3f\x15\x5f\x74\xe9\x30\xf0\x5e\x60\ +\x34\x25\xb8\xb7\xc3\xdc\x7d\x88\xe0\x11\x00\x48\xe7\xf2\x2f\x3a\ +\xc7\x51\x81\x15\x81\xf0\x3f\x44\xbd\x86\x1f\x06\xba\xc6\xe6\x92\ +\xbb\x29\xd3\xbe\xb8\x28\xee\x5b\x81\xfa\xc0\xe8\x2a\xaa\x6f\x0e\ +\x0d\xf4\x8e\xce\xb9\xf4\x1d\xe1\x1f\x01\xa0\xe0\xf7\xfc\x16\xf3\ +\x74\x2d\x70\xa2\xf4\xb8\xc2\x73\x4e\xdc\x89\x64\xa6\xb5\xe1\xff\ +\x66\x6e\xca\xb6\xad\x74\xe2\x4e\xcd\xb2\xf8\x09\xe7\x64\x4d\x14\ +\x8b\x07\x88\x45\x11\x02\x70\x7e\xfc\xcc\xcd\x15\x2f\xac\xfb\xca\ +\xc5\x6f\xd7\x02\xab\x4b\x46\xd5\x22\xb2\x7d\x79\x5d\xfd\xe5\x89\ +\x5f\xc7\x7e\x79\x90\xac\xf4\xd6\xfc\x06\x15\x0a\xc0\xb3\x33\x27\ +\xfa\x53\x95\xe7\x36\x16\xfa\x7b\x2f\x44\xd5\x3b\xb2\x0d\x00\x38\ +\x77\xee\xe7\x62\xf3\xb6\xc6\xc1\x0b\x97\x6f\x54\x03\xaf\x97\x8c\ +\x44\xa0\x61\x79\x5d\xfd\xfc\xe6\x6d\x8d\xc3\x23\x23\x23\xf7\x7c\ +\x4d\x26\x9b\xf2\x3b\x11\x0e\x01\x4f\xce\x18\x08\x83\x4f\x4c\xc5\ +\xb6\x1c\x39\xdc\x7b\x3d\xca\xce\x91\xfc\x06\xcc\x26\x9d\xc9\xb7\ +\xab\xd0\xc9\xdd\x9b\x7c\x68\x7a\xc1\xed\x77\x8e\x1f\x38\x30\x19\ +\xec\x92\xca\xb6\x7e\x02\xf2\xe9\xdd\x69\xba\xaf\xc6\xfb\xe7\x23\ +\xdf\xf7\x8b\x51\xf7\x2c\xdb\x06\x00\xa4\x9b\xda\x36\xab\xaa\x0f\ +\xcc\x0f\x8c\x46\x9d\xbb\xb5\x65\x78\xf0\xe0\x5f\x00\xb9\x5c\xae\ +\xfa\x9a\x7b\x7a\x3f\x48\x4b\xe0\x3c\x05\xf9\x70\xa8\xbf\x7b\x5f\ +\xb9\x3a\x96\x75\x03\x00\x92\xd9\xd6\x57\x05\xf9\x0e\x58\x3c\x73\ +\xa2\x67\x8b\xc5\xd8\x66\x2f\xce\x15\xcf\xb9\x3e\x85\x64\xe0\xd2\ +\x49\x54\x76\x0c\x0d\x74\x0f\x96\xb3\x5f\xd9\x37\x00\x20\x99\x6b\ +\x5f\x26\xce\x1d\x01\x56\x3e\xd0\x05\xca\x15\x85\xc6\x63\x03\x3d\ +\xa7\xca\xdb\x2c\xa2\xd7\xe0\xfd\x1c\xf3\xbb\x7e\x57\xcf\x5b\x07\ +\x0c\xdf\xff\x6c\x3d\xeb\xc5\x74\x4d\x25\x16\x0f\x11\xbf\x05\xfe\ +\xcb\xc4\xf8\xe9\xa9\xd7\x56\xd5\x7e\x3d\xa9\xf3\x96\x01\xaf\xdc\ +\xe3\xb4\x93\xd3\xd5\xb1\xd4\xf0\x37\x3d\x17\x2b\xd5\xab\x22\x8f\ +\x40\xf0\x33\xd3\x4d\xf9\x0e\x55\x3a\x02\x4d\xfa\x6e\xc8\x82\x9d\ +\x3f\xfa\x7b\x6f\x56\xb2\x4c\xc5\xbe\x01\xa5\xce\x8f\x8f\x1d\xaf\ +\x7d\xa9\x7e\x29\xc2\xcb\x80\x43\x75\xcf\xda\x55\x4b\x77\x7d\xd9\ +\xb9\x3b\xd4\xff\xfa\x47\x4e\x22\xd1\x51\x95\x68\x69\x99\xf7\xb0\ +\x7b\x18\x63\x8c\x31\xc6\x18\x63\x8c\x31\xc6\x18\x63\x8c\x31\x8f\ +\x89\x7f\x01\x76\x43\xf4\x3d\x50\xc3\x70\x12\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\xe8\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\x9a\x49\x44\x41\x54\x58\x85\xe5\ +\x96\xbb\x72\xd3\x40\x14\x86\xbf\xe3\xa4\x00\x9e\x23\x25\x54\xb1\ +\x52\xf0\x0a\x14\x90\x84\xc4\x21\x64\x72\x23\x44\x6a\x2c\x37\x99\ +\xe1\x19\x28\x65\x35\x92\x27\x09\xd8\x21\xce\xc5\xc0\x30\xc3\x33\ +\x50\x59\x7e\x05\xe8\xe0\x0d\x80\x02\xfb\x50\xc4\x4a\x64\x5d\x6c\ +\xcb\x71\xc3\x70\x2a\x69\xb5\xfb\x7f\x9f\x56\xab\xd9\x85\xff\xbd\ +\x24\xbc\x30\x5e\x3a\x0f\xb5\x20\x1e\xca\x5d\x11\x5e\xb5\x7d\xfb\ +\xe3\x34\x41\x86\x59\x5d\x52\xe5\x35\xc2\x6f\x44\xac\xc0\x2b\x7f\ +\x01\x28\x84\x1d\xb4\x20\x47\xc0\x03\x84\x39\x85\x96\x61\xba\xa5\ +\x69\xc1\x8b\x96\xb3\xa6\xd0\x42\x98\x03\xee\xa3\x7a\x18\x3e\xbb\ +\x11\x80\x3b\x91\x31\x05\x45\x9b\xd3\x90\x28\x5a\xce\x1a\x2a\xa7\ +\x51\x16\x70\x2f\x21\x20\x22\x07\x40\x6f\x9a\x12\x86\xe9\x96\x52\ +\xe0\x3d\x55\x39\x48\x08\x04\x5e\xf9\x03\xb0\x91\x22\x71\x3a\x89\ +\x84\x61\xba\x25\x45\x9b\x71\xb8\x20\x5b\x9d\x5a\xb9\x95\x10\x00\ +\x08\x7c\xfb\x2c\x45\x62\x26\xaf\x44\x1f\x9e\x78\x73\x41\xb6\xda\ +\x7e\xf9\x5d\xb4\xaf\x90\x52\xf3\xfb\xee\xba\x88\x9e\xc4\x02\xba\ +\x22\xba\xde\xf6\x2a\x97\x43\xe1\x96\xb3\xaa\x2a\x4d\x60\x66\x14\ +\x3c\x53\x60\x52\x89\x0c\xb8\x0a\xb2\x99\x06\x27\x16\x3e\x50\x9d\ +\x5a\xb9\x29\xc2\x26\xf1\xcf\xa1\xd2\x34\x2c\x67\x35\x45\x78\x25\ +\x2f\x1c\x86\xcc\x40\x58\x86\x55\x7d\xae\x4a\x23\x26\xdb\x55\x95\ +\x67\xe1\x62\x9a\xdf\x77\x57\x44\xf4\x2c\x2f\x7c\x2c\x01\x00\xc3\ +\x74\x37\x14\xad\xa7\x49\x00\xa4\xc1\x11\xdd\x0a\xbc\xca\xc9\xa8\ +\xec\xb1\x04\xb2\x24\xb4\xff\x79\x64\x50\x6c\x6c\x78\x2e\x81\x88\ +\x44\x63\xc8\xb8\x5c\xf0\xdc\x02\x37\x12\x34\x40\xe3\x63\x15\xd8\ +\x0e\x7c\xbb\x91\x27\x2f\xf3\x2f\xc8\x2a\x15\x7e\x29\xaa\x89\xf6\ +\x2b\x81\x9f\x79\xf3\x72\x09\x14\x2d\x77\x19\xd5\x73\x49\x19\xd7\ +\x6f\x3b\x2f\x9a\xd5\xa7\x79\x32\x73\x2c\xc2\xea\x92\xc2\x05\x30\ +\x1b\x69\x0e\x67\x22\x9a\xd3\x45\xa4\xd4\xdf\x5b\x46\xd6\x58\x33\ +\x90\x05\x57\xd5\x1d\x60\x3b\x22\x02\x30\x83\xea\x45\xd1\x72\x97\ +\xa7\x22\xb0\x60\x39\x8b\x59\xf0\x4e\xad\x52\x0f\x7c\xbb\xd1\x17\ +\x99\x48\x62\xa8\xc0\x82\xe5\x2c\xf6\x54\x2e\xe3\x70\x11\x76\x3b\ +\xb5\x4a\x3d\x6c\xe8\xd4\x2a\xf5\x0c\x89\xf3\x51\x12\x99\x02\xc3\ +\xe0\x6d\xcf\x7e\x1b\xef\xdf\xa9\x55\xea\x22\xec\xc6\x24\x66\x47\ +\x49\x64\x6d\xc7\x4f\x44\xb4\x35\x2e\x3c\x5a\x86\x55\xdd\x56\xe5\ +\x38\x96\xfd\x47\xa0\x94\x76\xd0\x4d\x08\x64\xc2\x91\x17\x6d\xbf\ +\xfc\x66\x18\xfc\x5a\xc2\x74\x77\x14\x3d\x1a\x47\x62\x40\xa0\x68\ +\x3a\x8f\x41\xde\xdf\x06\x9e\x57\xe2\xfa\xe1\xfc\x7e\xf5\x91\x08\ +\x9f\xa6\x01\x0f\xab\x68\x55\x77\x51\x0e\x53\x24\x96\xda\xbe\xfd\ +\x19\x06\x4e\xc5\x38\x71\x38\xc2\xde\xa4\x70\x80\xc0\xb3\x8f\x11\ +\xf6\x88\x2d\x4c\x05\x27\xbc\x49\x6c\xad\x51\x78\xe0\xd9\xc7\x93\ +\xc2\x87\x4a\x28\xdd\x84\x00\xaa\x26\xc8\x57\xe0\xc7\xd5\x96\x7a\ +\x7b\x78\x54\x42\x90\x4d\x94\xef\xc0\xb7\x5e\x41\xcc\x69\x65\xff\ +\xfb\xf5\x17\x4b\x00\x72\xf1\x7d\xf9\x90\x28\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x03\x89\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x3b\x49\x44\x41\x54\x78\x9c\xed\ +\x9a\xbd\x6b\x14\x41\x18\xc6\x9f\xd9\x0d\x84\xa0\xd8\x88\x04\x63\ +\x0a\x43\x62\xa1\x08\x42\x72\xd1\x94\xe2\x27\x06\xb1\x0b\x8a\x8d\ +\x78\x60\x36\x97\xd3\x53\x0b\x09\xfe\x05\xc6\x2a\xb8\x97\x4b\x72\ +\x29\xd2\x08\x36\xd1\x42\x84\x9c\xa0\x16\x01\x8b\x48\x2e\x29\x24\ +\x88\x85\x82\xc5\x29\x04\xb5\x88\xe4\x83\x33\x99\x7d\x2d\x22\x16\ +\xb7\x7b\x7b\xb7\x1f\x73\x93\x73\xe7\x57\xce\x0d\xcf\xfb\xec\x73\ +\xf3\xc5\xee\x00\x0a\x85\x22\xca\xb0\xa0\x02\x47\x06\x33\xbb\x9b\ +\x38\x4f\x32\x42\x1f\x18\x8e\x02\x68\x0c\xc1\x57\x10\x8a\x20\x2c\ +\x11\xc3\xf4\x86\xae\x67\x3e\x8c\x25\x57\xdd\x3a\x07\x0a\x20\x66\ +\x8c\x9e\x05\xac\x29\x00\xad\x41\x74\x04\x52\x00\xb4\x78\x3e\x7b\ +\xf3\x55\xb9\x0e\x9a\x5f\xe5\xd8\x80\x19\x07\xac\x97\xd8\xb9\x0f\ +\x0f\x00\xad\x80\x95\xeb\x36\xd2\xd7\xcb\x75\xf0\x35\x02\xba\xfa\ +\xcd\x73\x8c\x21\x87\x00\x01\xd6\x18\x0e\x68\x17\x9c\x46\x82\xe7\ +\x00\xb6\xe7\xbc\xf5\x91\x81\x0e\x84\xe3\xad\x66\x14\xd6\x75\xfd\ +\x70\xe9\x9a\xe0\xf9\x1f\x6c\xe2\x3c\x59\x87\x0f\x0f\x00\xad\x4d\ +\x9c\x27\x4b\x1b\x3d\x07\xc0\x08\x7d\xe1\xf8\xa9\x3d\x4e\xde\xbd\ +\xcf\xe1\xed\xad\xae\x3e\x71\xf0\xde\xe0\x43\xc6\x75\x9f\xcf\x67\ +\x53\x81\xcf\x16\x41\x88\x19\x26\xb9\xfc\x6c\xf3\x5e\x2f\xab\xb8\ +\x30\x54\x00\xb2\x0d\xc8\x46\x05\x20\xdb\x80\x6c\x54\x00\xb2\x0d\ +\xc8\x26\xf2\x01\x54\x3c\x08\x75\xf5\x8f\xec\xd7\x34\x2d\x41\x60\ +\xa7\x41\x68\xae\xd4\x3f\x66\x98\x9f\x7c\xbb\x21\x10\x18\x0a\x20\ +\xcc\xe8\x8d\xc8\xbe\x4b\xa7\x7e\xf9\xd6\xaa\x12\xd7\x00\x62\x89\ +\xf4\x25\x58\x34\x45\x84\xbd\x1e\x34\xdb\x7d\xbb\xd9\x3e\x43\x76\ +\x80\xe1\x24\xff\x8d\x44\x67\xc2\xbc\xba\x38\x9e\x9a\xf3\xad\x57\ +\x05\x65\xa7\x40\xcc\x30\x87\x61\xd1\x73\xc0\xd3\xc3\x87\x49\x9b\ +\x66\xe1\x6d\x97\x91\x1e\x10\x59\xc4\x31\x80\x6e\x23\x7d\x19\xc0\ +\x90\xc8\xc2\x55\xa2\x33\xd0\x68\x67\xc2\xec\x11\x55\xc0\x16\x40\ +\xcf\xc0\xc8\x41\x02\x4d\x8a\x2a\xe8\x03\x5d\xb3\xf0\xe4\xc4\x2d\ +\x73\x8f\x08\x71\x5b\x00\x5b\xd4\x70\x1f\x80\x90\x62\x01\x68\xe3\ +\x45\x18\x22\x84\x1d\xa6\x00\xf5\x8a\x28\x14\x18\x06\x21\xbe\x9c\ +\xd6\x80\x9d\xf9\x96\x97\xc4\xf8\xf2\xfc\x42\xc4\xd2\xf5\x43\x22\ +\x8c\xe8\x7c\xab\x83\xc0\x72\x65\x3b\xb0\xe0\x1f\x71\x9c\xf0\x1c\ +\xc0\xe2\x58\xd2\xff\x41\xc7\x85\xce\xc1\x0c\x34\xce\x45\x48\xbb\ +\x12\xf9\xa3\xb0\x0a\x40\xb6\x01\xd9\xa8\x00\x64\x1b\x90\x8d\x0a\ +\x40\xb6\x01\xd9\xa8\x00\x64\x1b\x90\x8d\x0a\x40\xb6\x01\xd9\xa8\ +\x00\x64\x1b\x90\x8d\x9f\xfb\x01\xb2\x68\xaf\xf0\xed\xbf\x1a\x8a\ +\xa5\x0d\xd1\x1a\x01\x84\xa5\xd2\xa6\x48\x05\x40\x0c\xd3\xa5\x6d\ +\x51\x0a\xa0\xb0\xa1\xeb\x99\xd2\xc6\xa8\x04\xc0\x01\x2d\xee\x74\ +\x6f\x38\x0a\x01\x70\x06\x76\xa3\xdc\x7d\xe1\x7a\xda\x05\xfc\x50\ +\x00\xb4\xf8\xbc\xcb\x65\xe9\xff\x31\x80\x7f\xd7\xe5\x37\xd7\x8b\ +\xa3\xef\x1f\xdf\x5b\x73\xeb\x6c\x7b\xd5\x1c\xc2\x5e\x2b\x8a\xcf\ +\xf9\x6c\xaa\x23\x6c\x51\xfb\x1a\xc0\xf0\x3d\xec\x22\xa1\xc0\xb0\ +\x2c\x42\xd6\x1e\x00\xe1\xb5\x88\x42\x41\x61\xa0\x37\x22\x74\x6d\ +\x01\x68\xc0\x43\x00\x9b\x22\x8a\x05\xe0\xa7\x65\x59\xe3\x22\x84\ +\xf5\xd2\x86\xaf\x0b\xb9\xe5\x96\xee\xde\x55\x00\xe7\x45\x14\xf4\ +\x03\x03\xae\xe4\x27\xef\x2c\x88\xd0\x76\x3c\x07\xe4\x9b\x7f\x3c\ +\x02\xf0\x54\x44\x41\xaf\x30\x46\xc3\xf3\xd9\xd4\x0b\x51\xfa\xb6\ +\x11\x00\x00\x98\x9d\xa5\x6f\x17\x8f\x3f\x6b\x59\xdb\xb5\x02\xe0\ +\x54\xd9\x7e\x62\x59\x61\x8c\xae\xcd\x4f\xdc\x36\x45\x16\xa9\xf8\ +\xc5\xf5\xb8\x61\x1e\xb3\x80\x21\x30\x9c\x01\x61\x9f\x48\x33\x7f\ +\x29\x00\x6c\xa6\x81\x6d\x3d\x98\x9b\xb8\xfb\xa5\x06\xf5\x14\x0a\ +\x45\x84\xf9\x03\x3a\xde\xd0\x31\x4b\x14\x34\x6a\x00\x00\x00\x00\ +\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x89\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3b\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\x01\x09\x00\x20\x10\x04\xc1\xd7\x52\xb6\x36\xa2\x7e\x0a\x39\ +\x90\x99\x04\xcb\x56\x01\x00\x00\x00\x00\x00\x00\xf0\xbf\xb1\xf6\ +\xb9\xe9\x88\xa4\x99\x0e\x48\x33\x20\x1d\x00\x00\x00\x00\x00\x00\ +\x00\x00\xef\x35\x86\x6a\x02\xea\xd1\x43\x33\x62\x00\x00\x00\x00\ +\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x08\x4f\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x08\x01\x49\x44\x41\x54\x78\x9c\xed\ +\x5b\x7d\x70\x54\xd5\x1d\x3d\xe7\xee\x26\x61\xab\x01\x0b\x7e\xb4\ +\xa3\x19\x8a\x4e\x19\x0c\x15\x5b\x20\x6c\x42\x11\xc1\x69\xc7\xca\ +\x00\x71\x13\x4c\xd5\x0e\x4a\x75\xa8\xc5\xd6\x99\xd6\xb1\x74\x70\ +\x46\x03\xad\xd8\x6a\x2b\xa8\x7f\x48\x5b\x3f\x2a\x2a\xd3\x99\x85\ +\xcd\x06\xe9\x80\x3a\x53\x09\x83\x7c\x6c\x42\xc6\xd6\x51\xa1\x63\ +\xeb\x07\x30\xa9\x5a\x0a\xe5\xc3\x12\xd8\xdd\x7b\xfa\x47\x50\xdf\ +\x7b\xbb\x9b\xec\x66\xdf\xc6\xa4\xcd\x99\xd9\x3f\xde\xef\x9e\xfb\ +\x7b\xe7\x9e\xf7\xf6\xbe\xfb\xee\xbd\x0f\x18\xc6\x30\x86\xf1\xff\ +\x0c\x0e\xc4\x49\xae\x88\xea\xbc\xd3\x65\x98\x49\x6b\x2f\x93\xc1\ +\x04\x8a\x17\x0b\x38\x07\xc0\x48\x00\x01\x00\xc7\xce\xfc\xf6\x0b\ +\xda\x0b\x98\x37\x11\xc4\xf6\xf6\xf9\x7c\xa7\xd4\xda\x4a\x66\xc0\ +\xf4\xb8\x2e\x49\x5b\xbb\x08\xe4\x7c\x00\x93\xfa\x95\x44\x78\x07\ +\x46\x5b\xac\x35\x4f\x77\x34\x60\x0f\x48\xf9\xab\xd2\x6f\x03\x24\ +\xd6\xc5\x71\xb5\x85\x96\x02\x98\xed\x67\x6a\x02\xaf\x0b\x5c\x95\ +\xfa\x27\x9e\xeb\xbc\x8d\x49\x1f\xf3\xfa\x83\x70\x4c\xb3\x61\xf4\ +\x20\x84\xa9\x7e\xe5\xcc\x81\x77\x05\x2e\x6f\x8f\xe0\x19\x3f\xee\ +\x88\xa2\x0d\x08\x6f\xd4\x05\x4a\xdb\x87\x08\x7e\xa7\x17\x9a\x05\ +\xb0\x03\x54\x9b\xac\xd9\x67\x02\xf8\xbb\x52\x38\x6c\x2d\x8e\x8f\ +\x00\xd2\x27\x0d\x2a\xcb\x80\x51\x32\x18\x27\x60\x3c\xa0\x3a\x00\ +\xdf\x04\x10\xea\x25\xe7\x76\x6b\xb9\xa4\x63\x01\xdf\x28\x46\x7f\ +\x51\x06\xd4\xc5\x35\xcd\x4a\xad\x00\xbe\x98\xa5\xf8\x38\xa8\xcd\ +\x94\xd9\x64\x81\x17\xda\x1b\xf8\xaf\x82\x72\x47\x15\x4a\x07\x70\ +\x15\x69\xe7\x01\x9c\x9f\xe3\x1c\xdd\x22\x6f\x69\x8f\xf0\x0f\xfd\ +\xd1\x0f\x14\x61\xc0\xb4\x98\x6e\x04\xf5\x14\x81\x0a\xaf\x28\x4a\ +\x8f\x06\x2b\xcc\x2f\x5f\x99\xcb\x23\xfd\xcd\xef\x44\x75\x54\xe5\ +\x95\x41\x2c\x06\x74\x2f\x80\xf3\xbd\xe5\x82\x56\xb6\xff\xc5\xdc\ +\x8b\x15\xb4\x85\xe6\x2e\xdc\x80\x66\x99\xf0\x24\x7b\x1f\xc8\x65\ +\x9e\x12\x2b\xe8\x29\xca\xac\x48\x34\xf2\x60\xc1\x79\xf3\xc0\xd7\ +\x37\xaa\x32\x69\x71\x27\xa5\xbb\x00\x9c\xed\x2a\x14\x5a\x43\x69\ +\x2e\x6c\x6b\xe2\x89\x42\x72\x16\x66\x40\xb3\x4c\xf8\x72\xbb\x0e\ +\xe0\xf5\x9e\x92\x2e\x43\x46\x76\x45\xd8\x5e\x50\xbe\x7e\x22\x1c\ +\xd3\x45\x30\x8a\x7b\x3b\x5c\x11\xaf\xb2\x82\xb3\x12\x73\x78\x2c\ +\xdf\x5c\xa6\xa0\x13\x7f\xd5\x2e\xcf\xd2\xf8\xdd\x29\x71\xea\x40\ +\x35\x1e\x00\x12\x8d\x3c\x68\x92\x9c\x29\x68\x9d\x33\x4e\xe1\x6b\ +\xec\xd6\xba\xeb\xa2\x0a\xe4\x9b\x2b\x6f\x03\x6a\x63\xfa\x36\xc4\ +\x7b\x5c\x27\x84\xd6\x86\x8e\x72\x76\x67\x23\xff\x91\x6f\x1e\xbf\ +\xb0\xab\x89\x27\xdb\x23\x66\xa1\xc8\x9f\x02\xf8\xe4\x71\x28\x60\ +\xee\x81\x80\xbd\x3f\xdf\x3c\x79\xfd\x05\xa6\x6d\xd0\x54\x1a\x6d\ +\x07\x30\xe2\xd3\xa8\x9e\x4b\x44\xcc\x4d\xa5\x18\x9d\x15\x8a\x70\ +\x4c\x3f\x02\xb5\xda\x19\x13\x78\x73\x7b\x03\x9f\xe9\xab\x6e\x9f\ +\x77\xc0\xb4\x16\x8d\xa1\x51\x2b\x5c\x8d\x47\x7b\xe8\xa8\x59\x3c\ +\x18\x1a\x0f\x00\x89\x06\x3c\x02\xe8\xf7\xce\x18\xa1\xc7\x6b\x63\ +\x9a\xdc\x57\xdd\x3e\x0d\x20\xec\x83\x00\x2e\x74\x84\xba\x82\x01\ +\x46\xda\xbe\xcb\xee\xc2\xa5\x96\x08\xa4\x46\x8f\x30\x4b\x24\xec\ +\x74\x44\xcb\x45\x3d\x3e\x6b\xab\x82\xbd\x55\xed\xd5\x80\x70\x8b\ +\x66\x00\xbc\xc5\x11\x12\xc4\xc6\x1d\xf5\xec\x2a\x46\x6f\x29\xb0\ +\x65\x0e\x4f\x31\xc8\x06\x00\x87\x1c\xe1\xc9\xdd\x47\x70\x7b\x6f\ +\xf5\x72\x1b\x20\x11\xd0\x2f\x3c\xc1\x75\x89\x46\xee\x2e\x42\x67\ +\x49\x91\xa8\xe7\x07\x10\x57\x3a\x63\x82\xee\x99\xf4\xa2\xce\xca\ +\x55\x27\xa7\x01\x75\x71\xcc\x04\x30\xc3\x11\x4a\xa6\xad\x69\x2e\ +\x5e\x66\x69\x11\x3a\x86\xdf\x90\xd8\xef\x08\x9d\xfb\xb9\x8f\x70\ +\x5b\x2e\x7e\x4e\x03\x2c\xf4\x13\xe7\x31\xa5\xdf\xee\x59\xc0\xb7\ +\x7d\xd0\x58\x52\xf4\xf4\x4d\x74\x5d\x28\x41\x77\xe6\x1a\x1b\x64\ +\x35\xa0\x26\xaa\x2f\x00\xf8\x96\x23\x94\x54\xd0\xdc\xe7\x9f\xcc\ +\xd2\xa2\x2a\x89\x67\x01\xbc\xe5\x08\x5d\xf8\x9e\xc1\x37\xb2\x71\ +\xb3\x1a\x10\x08\xe2\x46\xf4\x4c\x55\xf5\x80\x78\x39\x51\xcf\x0f\ +\xfc\x14\x59\x4a\xac\x6f\x62\x9a\xd0\x7a\x67\x8c\xc6\xde\x9c\x8d\ +\x9b\xd5\x00\x41\xf3\x5c\x01\xcb\xe7\x7d\x53\x37\x50\x30\xc6\xa3\ +\x99\x73\xb2\xfd\x0d\x32\x0c\x38\xd3\x63\x4e\x77\xc6\x52\x69\xfc\ +\xd1\x67\x79\x25\xc7\xee\x57\xd1\x01\xc0\x79\xd7\x8e\x3a\x58\x86\ +\x29\x5e\x5e\x86\x01\x15\xff\x41\x2d\x80\x72\x47\xe8\xcf\x9d\x4d\ +\xdc\xef\xe5\x0d\x7a\xac\xa0\xa5\xe4\xba\x70\x52\xe6\x3c\x65\x86\ +\x01\x06\xf8\x8a\xab\x12\xb5\xdd\x7f\x75\x03\x03\x4b\xe3\xd2\x2e\ +\xda\x89\x5e\x4e\x66\x1f\x20\x7b\xa9\x8b\x60\xcd\x5b\x19\x9c\x21\ +\x82\x80\x81\x47\x3b\x2f\xf5\x72\x32\x0d\x20\xbf\xe4\x3c\xb4\xc0\ +\xa0\x7f\xf6\xe7\x42\xea\xb4\x47\xbb\x30\xce\xcb\xc9\x30\x40\x16\ +\x95\x1e\xc2\xbf\x7d\x57\x36\x40\x38\xeb\xa3\x0c\xed\x95\x5e\x4e\ +\x86\x01\xa4\x9b\x64\x89\x82\xe6\xd8\x06\x13\xda\x16\xe1\x14\x80\ +\x94\x23\x54\x5e\x1d\x95\xb3\x83\xcf\x62\x80\x67\x92\x84\x16\x83\ +\xe2\x9d\xbf\x54\xc8\xfc\x0b\x00\xc7\x9d\xc7\xde\x3b\x62\x28\x61\ +\xd6\xd3\xa8\x00\xe0\x9c\x0f\x38\xfd\x66\x13\x4f\x3b\x39\x59\x3a\ +\x41\xb8\x66\x54\x6d\xcf\x2a\xee\x90\xc4\xc9\xd1\x18\xe5\x09\x1d\ +\xf7\x72\x32\x0d\xb0\x7a\xcf\xc3\xc8\xe8\x39\x87\x0a\x94\xc6\xc5\ +\x9e\xd0\xbb\x5e\x4e\x96\x77\x01\xb3\xd7\x79\x44\xd9\x2f\xfb\x29\ +\x6a\x80\xe1\xd2\x2e\x68\x9f\x97\x90\xed\x2f\xe0\x59\x6c\xe4\x8c\ +\x0c\xce\x10\x01\x61\x67\xb8\x8f\xcd\xeb\x5e\x4e\x86\x01\xa1\x14\ +\x76\x01\x70\xae\xbf\x4f\x0e\xc7\x74\x91\xff\xf2\x4a\x8c\x66\x19\ +\x80\x73\x5d\x31\xa1\xcd\x4b\xcb\x30\xe0\xcc\xda\xda\x2e\x57\x3d\ +\x62\xae\x97\x37\xd8\x51\x33\x09\x53\xe0\x5e\x51\x3e\x16\x1a\x8d\ +\x3d\x5e\x5e\x8e\xf9\x00\xba\xde\xa2\x08\xcd\xf7\x57\x5e\xe9\x61\ +\x60\x5d\x9a\x05\xbd\xd0\x36\x9b\xa9\x4c\x5e\x16\x94\x05\xb0\x0e\ +\x3d\x9b\x1a\xce\x54\xc6\x55\x57\x44\x75\x9e\xef\x2a\x4b\x85\x66\ +\x19\x90\x0b\x9c\x21\x5a\xb3\x36\x1b\x35\xab\x01\x3b\xea\xd9\x25\ +\xe0\xa5\x4f\x2a\x03\x15\xc9\xa0\xf5\x2e\x87\x0f\x5a\xd4\x5e\x8e\ +\x1b\x00\x4c\x70\x84\xde\x0f\x8d\xf9\xb4\x3d\x4e\xe4\x9c\x15\x16\ +\xf9\x6b\xd7\x31\xf8\x83\xe9\x31\x8d\xf5\x47\x62\xe9\x50\x1d\x55\ +\xb9\xa4\x9f\x3b\x63\x22\x57\x67\xbb\xfd\x81\x5e\x0c\xe8\xb8\x16\ +\x2f\xc3\xdd\x19\x96\xa7\x61\x97\xfb\xa2\xb2\x84\x38\xbb\x0c\xdf\ +\x03\x5d\x83\xb7\xc3\x65\x06\x6b\x72\xf1\x73\xaf\x0c\x91\x22\x79\ +\xb7\x27\x76\x53\x38\xae\x8c\x79\xb5\xc1\x82\x29\xcf\xeb\x5c\x4a\ +\xae\x25\x7c\x88\xf7\xef\xa8\x67\xc6\x10\xf8\x63\xf4\xba\x36\xb8\ +\x3b\xc2\x36\x50\xcf\xba\xf8\x52\x3c\xbc\x51\x17\x14\x27\xd5\x7f\ +\x54\x47\x55\x1e\x48\x69\x03\xdc\x7b\x88\x5e\x4b\x1d\xc2\xa3\xbd\ +\xd5\xeb\x73\x75\x38\x20\x73\x17\xdc\xb3\xab\x55\x4a\xa9\xe5\x9a\ +\xcd\xf2\x6e\x8e\xfa\x4c\x31\x32\x68\x1f\x21\x70\xa5\x23\x94\x34\ +\xe4\xe2\xbe\x36\x55\xf6\x69\xc0\xce\x06\x7e\x08\xf1\x5a\x01\xa7\ +\x3e\x8e\x91\x98\x7e\xb8\xdb\x3e\xd6\xb3\x80\xfa\xd9\x23\x1c\xd3\ +\xed\x02\xbf\xef\x8c\x89\x5c\x92\xcf\xb6\x9d\xbc\x1b\x10\x8e\x69\ +\x21\x28\xf7\x8e\x0b\xe9\x77\xc7\xd3\xe6\x0e\xef\x3b\xf6\x80\x41\ +\x62\x6d\x1c\x77\x08\x5a\x0d\xe7\xc5\xa4\x1e\x4e\x44\x02\x3f\xce\ +\x27\x45\x41\x57\xb0\x36\x96\x7e\x40\xe4\x52\x97\x06\x60\x5b\x3a\ +\xc8\x05\x9d\xf3\x79\x28\x57\xbd\x52\xa0\x3a\xaa\xf2\x91\x01\xfb\ +\x98\xc8\x5b\x5d\x05\xc4\x8b\xa1\x73\x38\x37\xd7\x63\xcf\x8b\x82\ +\x76\x89\x55\xa5\xcd\xdd\x04\xe2\xee\xf3\xe1\xca\x60\x4a\x1d\x75\ +\xad\xba\xac\x90\x5c\xc5\x60\x7a\x8b\xce\xaf\x0c\xea\x4f\x19\x8d\ +\x07\xde\x38\x05\x5e\x9f\x6f\xe3\x81\x7e\x6c\x94\xbc\x2e\xaa\xc0\ +\x81\xa0\xfd\x95\x40\xef\x2d\x96\x04\xb4\x26\x00\xb3\x72\x67\x03\ +\x3f\x2c\x34\x6f\x3e\xa8\x8b\x2a\x94\x0e\xe2\x87\x84\x96\x01\xf8\ +\xbc\xa7\x78\x4b\x2a\xc5\x1b\x3a\x9b\x78\xb4\x90\x9c\xfd\xdf\x2a\ +\x1b\xd7\xad\x94\xd6\x00\x28\xf3\x14\x9d\xa0\xf4\x90\x42\x66\x55\ +\x21\x1b\x16\x7b\xc3\xac\xad\x0a\x76\x1f\xc6\x22\x51\xcb\xe1\xde\ +\xaf\x04\x00\x10\xb4\x6a\x6c\xca\x2c\x5d\xdf\xc4\x74\xa1\xb9\x8b\ +\xea\xc5\x6b\x62\x9a\x69\xa8\x16\x00\x63\xb2\x14\x1f\x01\xb4\x09\ +\x32\x9b\x10\xc2\x4b\x85\x9a\x51\x1d\x55\xf9\x48\x83\x99\x32\x76\ +\x1e\xc0\x7a\x00\xd9\x86\xe1\x49\x91\x4b\xda\x23\x7c\xb2\x3f\xfa\ +\x01\x1f\xb6\xcb\xd7\xb4\xaa\xca\x58\x3d\x0c\xa0\xa1\x17\x5a\x12\ +\xc4\x36\x59\x6e\xa5\xc1\x5f\x25\xfc\x4d\x06\x87\x2b\x82\x38\x91\ +\x34\x48\x9b\x13\xa8\xb4\xe5\x18\xa5\x34\xc6\x81\x18\x4f\xd8\x3a\ +\x80\x57\xa3\xe7\x93\x9a\x5c\xc2\x3b\x44\x2e\x49\x44\xd8\x59\x8c\ +\x7e\xdf\x9e\xe3\xb5\x71\x5d\x23\xe9\x01\x00\xa5\xee\x0c\xbb\x24\ +\xfe\x6c\x6c\x1a\x4f\xf4\xe7\x96\xf7\xc2\xdf\x81\x4c\xb3\xcc\xb4\ +\x49\xa8\x37\xd4\x32\x01\x35\xbe\xe6\x06\xde\x06\xb8\x2a\x74\x14\ +\x4f\xfa\xb9\x47\xb1\x64\x23\xb9\x9a\x0d\x9a\x68\x8c\x5d\x74\xe6\ +\x63\x87\xf1\xfd\x4c\xf3\x3e\xa0\xcd\x56\x66\x6d\xc7\x6b\x78\xa5\ +\x3f\xdf\x03\xf4\x85\x01\x19\xca\xd6\xb4\xaa\x8a\x16\xb3\x8d\xec\ +\x44\x91\x13\x00\x8c\x23\x31\x4a\xc2\x48\xf4\xac\xdc\x1c\x45\xcf\ +\x67\x73\x07\x00\xed\x23\xcd\x3e\x11\xdb\x12\xf5\xd8\x3b\x58\xb6\ +\xe3\x0e\x63\x18\xc3\xf8\xdf\xc4\x7f\x01\x16\x1d\xd4\x53\x92\x2f\ +\x1f\x88\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\xeb\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\x9d\x49\x44\x41\x54\x78\x9c\xed\ +\x9a\xbd\x6e\x13\x41\x14\x46\xcf\x75\x08\xa1\x09\x5d\xde\x80\x37\ +\xb0\x5d\xd1\xf0\x08\x34\x58\x36\x09\x08\x1a\x7b\x0b\x6c\x57\x74\ +\xb4\x3c\x80\x6d\x90\x6c\x37\xfc\xe6\x47\x50\x20\xde\x80\x1a\x70\ +\xc5\x73\x20\x21\xd1\x40\x24\x7c\x29\x22\x24\x33\x5e\xc7\xb1\x77\ +\x66\x76\x66\xe3\x5b\xee\xde\xfd\x34\xe7\x68\x76\x76\x35\x1a\xd8\ +\xd4\xa6\x36\x75\x99\x4b\xf2\x1e\x80\xeb\x2a\x37\x07\xb7\x11\x7d\ +\x2a\xc2\x0f\x9d\x4a\x32\x19\xb7\xbf\xcd\xde\xbf\x92\xd7\xc0\x7c\ +\x54\x25\xe9\xd5\x51\x3d\x04\x4a\x28\x48\x49\x87\xc0\xcd\xd9\x9e\ +\x52\x3e\x43\x73\x5f\x67\xf0\x72\x06\xff\xaf\x94\xeb\x66\x5f\x21\ +\x05\xa4\xc2\xc3\x1f\xd0\x27\x66\x6f\xe1\x5e\x81\x45\xf0\xaa\xd2\ +\x98\x8c\x3b\x1f\xcd\xfe\x42\x2d\x82\xe7\xc3\xb7\xdf\xa7\x3d\x53\ +\x18\x01\xeb\xc0\x43\x41\x04\xac\x0b\x0f\x05\x10\x90\x05\x1e\x22\ +\x17\x90\x15\x1e\x22\x16\x60\x03\x1e\x22\x15\x60\x0b\x1e\x22\x14\ +\x60\x13\x1e\x22\x13\x60\x1b\x1e\x22\x12\xe0\x02\x1e\x22\x11\xe0\ +\x0a\x1e\x22\x10\xe0\x12\x1e\x02\x17\xe0\x1a\x1e\x02\x16\xe0\x03\ +\x1e\x02\x15\xe0\x0b\x1e\x02\x14\x60\x1b\xbe\xdc\x1c\xdc\x91\x92\ +\x3e\x07\x28\xa1\xad\xcf\xc3\xee\x87\xd9\xfb\x41\xed\x08\xd9\x86\ +\xaf\x24\xbd\xba\x88\x9e\xa0\xec\xa1\xec\x4d\x91\x91\xd9\x13\x8c\ +\x00\x17\xf0\x29\x79\x73\x15\x84\x00\x4f\xf0\x53\x41\x1f\x99\xbd\ +\xb9\x0b\xf0\x06\x2f\xdc\xff\x32\xec\xbe\x33\xfb\x73\x5d\x04\xfd\ +\xc2\x77\x0e\xd3\x9e\xc9\x4d\x40\x08\xf0\x90\x93\x80\x50\xe0\x21\ +\x07\x01\x21\xc1\x83\x67\x01\xa1\xc1\x83\x47\x01\x21\xc2\x83\x27\ +\x01\xbe\xe0\x55\xe5\xde\x64\xdc\x3e\x5a\x25\xcb\xb9\x80\x90\xe1\ +\xc1\xb1\x80\xd0\xe1\xc1\xa1\x80\x18\xe0\xc1\x91\x80\x58\xe0\xc1\ +\x81\x80\x98\xe0\xc1\xb2\x80\xd8\xe0\xc1\xa2\x80\x18\xe1\xc1\x92\ +\x80\x58\xe1\xc1\xc2\x19\x21\x5f\xf0\xc0\xc1\x64\xdc\x3e\x5e\x35\ +\xaf\x9a\xf4\x6a\x8a\x3c\x03\x07\x7b\x82\x3e\xe1\xbf\x8e\x3a\xab\ +\xc3\xb7\x06\x07\xaa\x72\xec\x64\x4f\x30\x0a\x78\xf4\x15\x4b\x18\ +\xd7\x12\x10\x3c\x7c\xd2\xdf\x4f\x81\xb7\xb3\x27\x18\x05\xbc\xf2\ +\xda\xcc\xb3\xb2\x27\x18\x37\x7c\xc6\x3d\xc1\xd0\xe1\xcb\xcd\xc1\ +\x5d\x11\x7d\x63\xe6\x2d\xfb\x74\x5e\x48\x40\x51\xe1\xe1\x02\x6b\ +\x80\x37\x78\xd1\x7d\xdf\xf0\xb0\x64\x06\x78\x85\x1f\x76\x4f\x56\ +\xcd\xcb\x0a\x0f\xe7\xfc\x09\x86\x0e\x5f\x69\xf5\x1b\x30\x0f\xcf\ +\x8a\x7f\x8c\xa9\x33\x20\x0e\x78\xde\xce\xe5\xad\xb1\x86\x6c\x99\ +\x17\xaa\x49\xaf\x86\xca\x11\x96\xe0\x17\xe4\xad\x0d\x5f\x4d\x7a\ +\x35\x48\xc9\x5b\x73\x01\xfd\x6f\x06\x94\x9b\xa3\x6d\x91\xdf\xdf\ +\x81\xdd\x99\xcb\x19\x0e\x27\xa4\xe6\x65\x78\xe7\xed\xe6\x81\xf1\ +\x15\xd8\x3d\xbd\xba\x05\xec\xcc\x5c\xca\x74\x2c\x25\x25\x2f\xd3\ +\x60\x6d\xe7\x81\x21\xe0\xd3\xcb\x87\xbf\x54\x79\x0c\x9c\x02\x3f\ +\x81\x7a\x96\x33\x39\x66\x9e\x88\x36\xb2\x0c\xd6\x76\xde\xc2\xba\ +\xd1\xee\xef\x94\x9b\xa3\xed\x50\xf3\x6e\x3d\x78\x71\xcd\x66\xde\ +\xa6\x36\x75\x89\xeb\x2f\x57\x3e\x7f\x9e\x34\x61\xbc\xb4\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x87\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x39\x49\x44\x41\x54\x58\x85\xed\ +\xce\x31\x11\x00\x30\x08\x04\x41\x26\xde\x50\x80\x05\xfc\x5b\x20\ +\x22\xa0\xdc\xeb\xff\x67\x23\x16\x65\xf5\x64\xf5\x6c\x3e\xde\x66\ +\x7c\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ +\xc0\x07\xe4\xc6\x04\x35\x1a\x89\x95\x2e\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x86\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x38\x49\x44\x41\x54\x58\x85\xed\ +\xce\x41\x0d\x00\x40\x08\x03\x41\x72\xaa\x90\x87\x21\x24\x92\x9c\ +\x08\x78\xce\xfe\xdb\x4c\xc4\xa2\xec\xa9\xec\xa9\xcd\xc7\xdb\x8c\ +\x2f\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ +\xf8\xac\x79\x05\x03\xdf\x56\x31\xc9\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x03\xa2\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x54\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\xbd\x4f\x53\x51\x18\x87\x9f\xb7\x85\x58\x07\x8d\x9d\x18\x24\ +\x3a\xcb\xa0\x24\x92\x36\x6e\x98\x28\x0c\x1a\x91\x26\xc8\x20\x09\ +\xff\x81\x71\x53\x18\x24\x9a\xf8\x11\x27\x3f\xfe\x02\x12\x17\x31\ +\x82\x18\x1d\x44\x13\x9c\x34\x25\x98\xa0\x03\xce\x12\x1c\x70\xb0\ +\xc4\xc5\x1a\xa4\xaf\x83\x17\x73\xef\xed\xad\xd2\x9e\x7b\x7b\x40\ +\xce\xb3\x9d\xf7\x9e\x9e\xfe\xde\xdf\x3d\x5f\x69\xcf\x01\x87\xc3\ +\xb1\x93\x91\xcd\x54\xea\x9e\xd5\x96\x72\x89\x33\x15\x2a\x83\x82\ +\x74\x29\xec\x17\xd8\x95\xb4\xb8\x7a\x50\xf8\x21\xf0\x59\xd1\xf9\ +\x14\xa9\x87\x99\x2c\x4f\x5f\x1f\x97\x9f\xff\xfa\xdc\x3f\x0d\xc8\ +\x4f\xea\x49\xd0\xbb\xc0\xa1\x58\x94\x36\x8f\x45\x90\x8b\xc5\x82\ +\xbc\xfc\x5b\xa5\x54\xcd\x27\xaa\x92\x7b\xac\xa3\xa0\x33\x6c\xbf\ +\xe4\x01\x3a\x40\x67\xf2\x53\x3a\x82\x6a\xcd\x17\x5d\xd3\x80\xdc\ +\x24\x23\x22\x7a\x3d\x19\x6d\x4d\x44\xf5\x46\xfe\x09\x97\x6b\x3d\ +\x8e\x74\xc6\xeb\xf6\x33\xa1\x70\x49\x45\xae\x90\xe6\xf9\xc1\x32\ +\x4b\x8f\xce\xc9\x7a\xac\x42\x0d\x19\x98\xd0\xf4\xa7\x0c\x07\x58\ +\xe7\x94\xa8\x5e\x03\xb2\xc1\x1a\xd2\x13\x35\x1c\xaa\x0c\xe8\x9e\ +\xd5\x96\xef\x25\xfd\x80\xbf\xdb\x0b\xaf\x48\xc9\x50\xb1\x4f\x56\ +\x62\x57\x9e\x00\xf9\x69\x6d\xa3\xa2\x0f\x50\x4e\xf8\xc2\x8b\xbb\ +\xb3\x72\x24\x3c\x31\x56\x0d\x81\x72\x89\x33\x04\xc7\xfc\xd7\xb4\ +\xca\xf9\xed\x92\x3c\x40\xb1\x4f\x56\x48\xc9\x10\x50\xf2\x85\x3b\ +\xbc\xdc\x02\x54\x19\x50\xa1\x32\xe8\x2f\xab\xc8\xd8\x9b\x82\x7c\ +\x89\x5f\x66\xb2\x14\xfb\x64\x45\x54\xc6\xfc\xb1\x70\x6e\x10\x61\ +\x80\x20\x5d\x81\x40\x9a\xe7\xb1\xab\x6b\x12\x95\x56\x9e\x05\x23\ +\x72\x34\x5c\xa7\xca\x00\x85\xfd\xfe\xf2\xc1\x32\x4b\x71\x0b\x6b\ +\x16\x11\xda\xdb\xc3\x75\x22\x7a\x40\x70\x87\xb7\xd5\x66\xfb\x7a\ +\x08\x6b\x8f\xda\xbd\xd6\xde\x08\xed\x10\x9c\x01\xb6\x05\xd8\xc6\ +\x19\x60\x5b\x80\x6d\x9c\x01\xb6\x05\xd8\xc6\x19\x60\x5b\x80\x6d\ +\x9c\x01\xb6\x05\xd8\xc6\x19\x60\x5b\x80\x6d\x5a\xe2\x68\x24\x3f\ +\xa5\x3d\xa8\xde\x06\x0e\xb3\xc9\xff\x1a\x0c\x50\xe0\x3d\x22\x97\ +\x8a\xfd\x12\xfe\xdd\xb2\x6e\x8c\x7b\x40\x6e\x52\x87\x51\x7d\x01\ +\x1c\x21\xf9\xe4\xf1\xbe\xa3\x13\xd5\x17\xb9\x49\x1d\x36\x6d\xcc\ +\xc8\x80\xce\x29\xdd\x27\xe8\x7d\x53\x11\x8d\x22\xe8\xbd\xce\x29\ +\xdd\x67\xd2\x86\x91\x01\x19\x38\x06\xec\x31\x69\xc3\x90\xbd\x9e\ +\x86\x86\xd9\xf1\x93\xa0\x91\x01\x65\x78\x0b\x7c\x8b\x49\x4b\x23\ +\x7c\xf3\x34\x34\x8c\x91\x01\x0b\xfd\xb2\xaa\xc8\x05\x93\x36\x4c\ +\x50\xe4\xc2\x42\xbf\xac\x9a\xb4\x61\x3c\x04\xe6\x0a\x32\x8e\x48\ +\x2f\xb0\xc0\xef\x25\x2a\x69\x36\x96\xc1\xde\xb9\x82\x8c\x9b\x36\ +\x16\xcb\x3e\xc0\x5b\x8f\x8d\xd7\x64\x1b\xb8\x49\xd0\xb6\x00\xdb\ +\x38\x03\x6c\x0b\xb0\x8d\x33\xc0\xb6\x00\xdb\x38\x03\x6c\x0b\xb0\ +\x8d\x33\xc0\xb6\x00\xdb\x38\x03\x6c\x0b\xb0\x8d\x33\x20\x1c\x50\ +\xf8\xe1\x2f\x0f\x4c\x68\xba\x79\x72\xe2\x25\xac\x3d\x9c\x1b\x44\ +\x1f\x92\xfa\xec\x2f\x7f\xca\x70\x20\x7e\x69\xcd\x21\x42\xfb\x72\ +\xb8\x4e\x44\x0f\xd0\xf9\x40\x60\x9d\x53\xf1\xca\x6a\x1e\xa9\x35\ +\x4e\x07\x23\xfa\xae\xaa\x4e\x75\x20\xf5\xd0\x5f\x16\xd5\x6b\xf9\ +\x69\x6d\x8b\x5b\x5c\xd2\xe4\xa7\xb5\x4d\x45\xaf\xfa\x63\xe1\xdc\ +\x7e\xc7\x42\x64\xb2\x3c\x05\x3e\xfa\x42\x59\x2a\xfa\x60\x3b\x99\ +\xf0\xe7\xb0\x74\xf0\xc4\xf8\xa2\x97\x5b\x80\xba\x8e\xcb\x8b\xca\ +\x58\xa5\x95\x67\x5b\xf9\xb8\x7c\x6a\x8d\xd3\xde\x9b\x6f\xec\xb8\ +\xfc\x06\xb9\xc7\x3a\xfa\x5f\x5c\x98\x00\x10\x19\x2d\xf6\xcb\xcd\ +\xa8\x47\x35\xf7\x01\x73\x05\x6e\x22\x32\x9a\x9c\xaa\xa6\xa0\x20\ +\x23\xc5\xb3\xdc\xaa\x55\x61\xb3\x97\xa6\xee\x00\x1d\xb1\x4a\x4b\ +\x9e\x4d\x5d\x9a\xaa\xfb\xda\x9c\x77\xe4\xbc\x7d\x2b\x5e\x9b\x03\ +\x96\x41\xdf\xd5\x73\x6d\xce\xe1\x70\xec\x6c\x7e\x01\x43\x8d\x07\ +\x87\xbb\xe6\x3f\x9a\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ +\x82\ +\x00\x00\x08\xe5\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x08\x97\x49\x44\x41\x54\x78\x9c\xed\ +\x5b\x6d\x6c\x14\xc7\x19\x7e\xde\xb9\x0f\xdb\xa1\xfe\x68\x21\xa1\ +\xc8\xd0\x06\xac\x20\x28\xa6\x2a\x98\x56\x35\x45\x60\xc0\x9c\xeb\ +\xaa\x98\xf8\x60\xd5\x90\x0a\x62\xe3\x8f\x86\xa4\xad\x4a\x94\x46\ +\x02\x29\x39\xdc\x86\x7e\xa4\x0d\x09\x89\x14\x08\x9c\x8d\x21\xd0\ +\x48\x3d\x6c\x23\x93\xc6\xe1\x6c\xa7\x46\xa4\x80\x42\x20\x55\x02\ +\x36\x51\x52\x87\x50\x6a\x25\x51\xb1\x9d\x03\x81\xed\xbb\x9b\xb7\ +\x3f\xf8\xda\xdd\x5b\x9f\xef\x7c\xbb\xae\x69\xfd\xfc\x9b\x67\xde\ +\x7d\xf7\xd9\xe7\x66\x67\x66\x67\xe6\x80\x31\x8c\x61\x0c\xff\xcf\ +\xa0\x91\xb8\x49\xa1\x52\x7a\x77\x50\xda\x17\x0a\xe2\xd9\x92\x31\ +\x83\x80\x69\x00\x67\x80\x28\x0d\x12\x36\x10\x02\x00\x02\x20\xbe\ +\x00\x89\x0e\x16\xd4\x2e\x08\x47\xfd\x3e\xef\xc7\x56\x6b\xb3\xcc\ +\x80\x25\xf7\x57\x66\x09\x7b\xb8\x44\x30\x15\x31\xf0\xcd\x61\xa6\ +\xf9\x98\x99\x9b\x18\xa2\xb6\xb5\x7e\xd7\x3b\x00\xd8\x4c\x8d\x80\ +\xf9\x06\xd0\xd2\xe2\xb2\x02\x12\xe2\x09\x02\x2f\x36\x39\xf7\x19\ +\x26\x6c\xed\xf9\x8a\xd8\x77\x6a\xe7\xce\xa0\x59\x49\x4d\x33\xa0\ +\xc0\xbd\x6e\xb1\x24\xf1\x0c\x80\x79\x66\xe5\x34\x06\x9f\x27\x60\ +\xb3\xbf\xae\x7a\x2f\x4c\x68\x11\x09\x1b\xb0\xb4\xa8\x7c\x22\xd9\ +\xf1\x2c\x11\x7e\x1c\x25\x4c\x32\xf0\x37\x62\xb4\x31\xf8\x9c\x20\ +\xdb\x3f\x18\xd4\x1d\x14\xfd\x97\x53\x40\xe1\x81\x30\x52\x89\x44\ +\x3a\x88\xa6\x82\x31\x9d\x88\x73\xc1\xb4\x0c\x40\xca\x60\x09\x19\ +\x38\x6a\x03\xad\x3f\x5c\xb7\xeb\x6c\x22\xfa\x13\x32\xa0\x40\x29\ +\xfb\x8e\x94\x74\x10\xc0\x24\x7d\x1d\x03\x97\x01\xbc\x2e\x88\x0e\ +\x85\xc3\xfd\x6f\xb4\x36\xec\xbd\x14\x4f\xee\x5c\x65\x43\xca\xb8\ +\x70\x60\x09\x41\x2c\x07\x71\x91\xd1\x3d\x00\xf4\x01\x58\xd7\x5c\ +\xe7\x7d\x75\x58\x0f\x80\x04\x0c\xc8\x77\x97\x3d\x48\x44\x35\x00\ +\x92\x22\x44\x11\xbd\xe0\x74\xda\x7f\xf7\x97\x3f\x6d\xef\x19\x6e\ +\x7e\x35\x14\x45\x71\xf6\xca\xf4\x0a\x00\x4f\x01\xb8\x47\x5f\x4f\ +\xc0\x96\xdc\xec\xcc\xa7\xaa\xaa\xaa\x64\xbc\xb9\xe3\x36\xc0\xe3\ +\xf1\x88\x63\x67\xbb\x9e\x06\xf3\x46\x5d\x95\x04\xa3\xc6\x0e\x54\ +\x35\xd5\x7b\x2f\xc6\x9b\x37\x16\x14\x15\xad\x4b\xbd\x6a\x17\x8f\ +\x11\xe1\x71\x00\x5f\x52\xd7\x31\xe8\x60\x48\x38\xd6\xb4\xf9\x5e\ +\xba\x12\x4f\xce\xb8\x0c\xf0\x78\x3c\xe2\xd8\xfb\x17\xf7\x83\xe8\ +\x01\x5d\x96\x2e\x41\x5c\x7c\xd8\x57\xfd\x76\x3c\xf9\x86\x8b\x42\ +\x77\xf9\xe4\x10\xa1\x01\x91\x1d\xee\xbb\xf6\xe4\x6b\x79\x4d\xfb\ +\xf7\x07\x62\xcd\x65\x8b\xe7\xc6\xce\xf1\xf7\x55\x81\xe8\x51\x1d\ +\x7d\x42\xb0\x58\x7a\xb8\xce\xfb\x41\x3c\xb9\x12\xc1\x47\x1d\xa7\ +\x03\x13\xb3\x17\xed\x73\xc8\x81\x7b\x89\x34\x73\x8c\x49\xe1\x90\ +\x63\x76\x4e\x76\xd6\x9f\xdb\xdb\xdb\x63\x1a\x21\x62\x36\xc0\xe5\ +\x2e\xff\x11\x08\x2f\xea\xe8\x3d\xc1\xd4\x90\xd2\xfa\x6a\x75\x6f\ +\xac\x79\xcc\xc2\xc5\xf6\x13\xa1\xce\x8e\xd3\x0d\x59\x33\xe7\x5c\ +\x05\x51\x3e\x6e\xb4\x66\x02\xa6\xf7\x21\x25\xb9\xb3\xfd\x74\x4b\ +\x2c\x79\x62\x7a\x05\x96\xad\x5c\x37\x0f\x10\x47\x01\x24\xab\xe8\ +\x7d\xcd\x75\xde\xb5\xb0\x60\x76\x16\x2f\xf2\xdd\xe5\xbf\x20\xc2\ +\x73\x6a\x8e\x09\x0f\xb5\x1c\xf0\xee\x1d\xea\x5a\x31\x54\xc0\xd2\ +\xe2\xb5\xe3\x01\x71\x10\xea\x87\x67\xbc\x1d\x4c\x0d\x55\x60\x14\ +\x3c\x3c\x00\xb4\xd4\x7b\xb7\x81\xb1\x5b\xcd\x11\x63\x57\x81\xbb\ +\x72\xee\x50\xd7\x0e\x69\x00\x89\xa4\x67\x00\x64\xde\x26\xd0\x85\ +\x90\x2c\x6e\xab\xad\xed\x1b\x8e\x58\x8b\xc0\xf6\x6b\x29\xeb\x01\ +\x1c\x53\x71\xce\x30\xc9\x5d\x79\x79\x1e\x7b\xb4\x0b\xa3\x1a\x90\ +\xaf\x54\x2e\x20\xf0\x3a\xf5\x8d\x58\x62\x65\x73\x63\x4d\x57\x02\ +\x62\x2d\x41\x53\xd3\x8b\xfd\x32\x08\x37\x18\xff\xbe\xc9\x11\x30\ +\xd7\x39\xfe\x5f\x8f\x44\xbb\x2e\x9a\x01\x44\xe1\xf0\x6f\x75\xdc\ +\xfe\x96\x7a\xef\x89\x44\x84\x5a\x89\xd6\x46\xef\x67\x0c\x6c\x51\ +\x73\xcc\x78\xd2\xb5\x66\xcd\xb8\xc1\xae\x19\xd4\x80\x65\x4a\xc5\ +\x42\x10\x2d\x50\x51\x41\xc9\x61\x8f\x09\x3a\x2d\x45\x28\x2d\xb4\ +\x03\xc0\x85\x5b\x04\x61\x02\x5f\x4d\xfe\xc9\x60\xf1\x83\xb7\x00\ +\xc6\x2f\xb5\x04\xbd\xdc\x5a\xbf\xbb\x33\x61\x85\x16\xa3\xad\xb6\ +\xb6\x0f\x4c\xba\x1f\x8a\x1f\x53\x14\xc5\x70\xc8\x37\x34\x20\x4f\ +\x29\xf9\x2a\x98\xbf\xaf\xa2\x82\x32\xc8\x4f\x9b\xa6\xd2\x62\x64\ +\xd8\x7a\x5f\x01\xf8\x43\x15\x95\xd9\x23\x33\xf2\x8d\x62\x0d\x0d\ +\x70\x48\xc7\x83\xd0\x4e\x92\xde\x6c\x6d\xf4\x7e\x66\xa2\x46\x4b\ +\xe1\xf3\xf9\xc2\x60\xf2\xa9\x39\x02\x3f\x64\x14\x3b\xc8\x2b\xc0\ +\xcb\x35\x17\x13\x35\x9a\x25\x6e\xa4\x40\x24\xf4\x9a\x7f\x60\xf4\ +\x1a\x44\x18\x70\xa3\xc7\x9c\xaf\xe6\x24\xd1\x6b\xe6\xca\xb3\x1e\ +\xb9\xd9\x93\x4e\x82\xa0\x6e\xb5\xe9\x01\xa4\xe5\xe8\xe3\x22\x0c\ +\xe0\x6b\xce\xef\x02\x70\xaa\xa8\xbf\xb7\xf8\x76\x5e\xd0\xc7\x8d\ +\x76\x54\x55\x55\x49\x30\x34\x3f\x9c\x64\x11\xb1\x4e\x19\xf9\x0a\ +\xb0\xc8\x56\x17\x89\x70\xd4\x74\x75\x23\x04\x02\x6b\xb5\x33\x66\ +\xe9\x63\x0c\x0c\xc0\x4c\x75\x51\x4a\xfa\x30\x22\xe6\x4e\x01\x09\ +\x9d\x76\x9e\xa9\x0f\x89\x34\x80\xf8\x5e\x2d\x21\x47\xfd\xd8\x3f\ +\x18\x06\x28\xa8\xd7\x3e\x55\x1f\x63\x34\x0a\xa4\xaa\x0b\x04\x8c\ +\xf8\xb7\xbe\x69\x18\x17\xa1\x3d\x55\x1f\x32\xa4\x01\x82\x39\xae\ +\x35\xb6\xd1\x84\xb6\xda\xda\x7e\x00\x21\x15\xe5\x54\x14\x45\xdd\ +\xc1\x1b\x1a\xa0\x59\x24\x09\x09\x31\x2a\xbe\xf9\xad\x42\x84\x01\ +\xc4\xb8\xac\x09\x60\x8e\x68\x36\x77\x0a\xf2\x4a\x4a\x92\x00\xa8\ +\xd7\x03\x06\x7c\x3e\xdf\x80\x3a\x26\x72\x1e\x70\x7d\xa7\xf6\x76\ +\x19\xc8\xb0\x46\x9e\xf5\xb0\x75\xdb\xd3\x75\xd4\x65\x7d\x4c\xa4\ +\x01\xc0\x27\x1a\x82\x22\x7b\xce\x3b\x06\x49\x72\x9a\xa6\xcc\x38\ +\xaf\x0f\x31\x9a\x07\x74\xa8\x8b\x04\xba\xcf\x64\x59\x23\x06\x62\ +\xa1\xd1\xce\xc0\x39\x7d\x4c\x84\x01\x82\xa1\xd9\x6c\x64\x60\x81\ +\x3e\xe6\x4e\x81\x60\xd6\x6a\x27\x9c\x89\x88\xd1\x13\x03\x76\xe7\ +\x71\x00\xb7\xf6\xdf\x09\x98\x5b\xe8\x2e\x9f\x6c\x85\x40\x2b\xe1\ +\xf1\x78\x04\x83\x7e\xa8\x21\x19\x6d\xfa\xb8\x08\x03\x6e\xec\xad\ +\x1d\x57\x73\x21\xd2\x25\xba\x03\xf0\xd6\xfb\x5d\x39\xd0\xec\x28\ +\x53\x20\xd4\x9d\xf9\x8e\x3e\xce\x70\x3d\x80\x00\xdd\xe7\xaf\x2c\ +\x32\x55\xdd\x08\x80\x84\x5e\x33\xbf\xd1\xd6\x56\x15\xd2\xc7\x19\ +\x1a\xc0\x41\xb9\x1f\x80\x6a\xab\x99\x96\x14\x2a\xa5\x77\x9b\xaa\ +\xd0\x42\x78\x3c\x1e\x41\x4c\xab\x74\xf4\x1e\xa3\x58\x43\x03\x9a\ +\x1b\x6b\xba\x88\xe0\x57\x51\x49\x41\x69\xd7\x6f\x87\x8f\x5a\x1c\ +\x3f\xdb\xb5\x1a\xc0\x8c\x9b\x65\x02\x3e\x0d\x5e\xca\xf4\x1b\xc5\ +\x0e\xba\x2a\xcc\xe0\x3f\xaa\xcb\x04\x7e\x74\x89\xbb\xec\xeb\xa6\ +\xa9\xb4\x08\x8a\xa2\x38\x99\xf9\xd7\x6a\x8e\x99\x9f\x33\x6a\xfe\ +\x40\x14\x03\x9a\x0f\x54\xbf\x49\xac\xe9\x0c\x9d\x36\xc2\x66\x73\ +\x64\x5a\x87\x1e\x99\x56\x09\xed\x67\x6f\x77\x4a\x88\xb7\x0f\x16\ +\x1f\x6d\x67\x88\xa5\xc0\x26\x2d\x45\x6b\x5d\x4a\x79\xc4\xba\xda\ +\x68\x41\xde\xea\xca\x09\x04\x7a\x52\x43\x32\x7e\xd3\xd8\x58\x13\ +\x31\x05\xbe\x89\xa8\x7b\x83\x2d\x07\xbc\x6d\x00\xbd\xa2\x8e\x67\ +\x89\x86\xa5\x45\xe5\x13\x13\x52\x6a\x01\x14\x45\x71\x3a\xfa\xe5\ +\x01\xa8\xce\x10\x11\xf0\x5e\xf7\x04\xf1\x42\xb4\xeb\x86\xde\x1d\ +\x96\xb6\xc7\x75\xab\xab\x53\x84\x03\xf5\x85\x85\x3f\xd3\x1f\x8e\ +\xfa\xaf\xa2\x57\xa6\x6f\x03\x61\x91\x8a\x0a\x92\xe0\x8a\xa1\x0e\ +\x55\x0e\x69\x80\xbf\x61\xc7\xe7\x2c\x71\x3f\x80\x7e\x15\x3d\x3f\ +\x78\x57\xdf\x4b\x18\xa1\xb3\xc6\x43\xc1\xb5\xaa\xe2\x11\x00\x0f\ +\xab\x39\x62\xac\x8f\xe5\xcc\x52\x4c\x47\x64\x3a\x3b\x4e\x5f\xcc\ +\x9a\x39\xe7\x13\x10\x15\xdf\xba\x01\x30\x67\xda\x37\xe6\x4e\xca\ +\xc9\xce\xf2\xb7\xb7\xb7\x87\xe3\x56\x6d\x0e\xc8\xb5\xb2\xfc\xe7\ +\x0c\x6c\x83\xea\xc7\x20\xc2\xf3\xfe\x3a\xaf\x7e\x67\xdb\x10\x31\ +\x9f\x11\xea\xec\x78\xf7\xbd\xac\x59\x39\x77\x01\xf8\xde\xad\x1b\ +\x01\x39\x7d\x32\x79\xe1\xd7\xbe\x35\xef\xb5\xf3\x67\x4e\x5d\x8d\ +\x47\x79\xa2\x50\x14\xc5\x99\x39\x73\xfe\xcb\x00\x36\x41\xdb\x12\ +\x0f\x07\x2f\x65\x96\x9e\x3f\x7f\x24\xa6\x33\x83\x43\xbe\x02\x6a\ +\x64\x50\xef\x26\x5c\x3f\x9e\x76\x1b\x84\x45\x8e\x81\xf0\xc9\x7c\ +\xa5\x72\x76\x3c\xb9\x12\x81\xab\xf8\xe1\x7b\x7a\xc3\x69\xad\x00\ +\xca\x74\x55\x67\x83\xe1\xd0\x03\x83\x8d\xf9\x46\x88\xfb\x1d\x56\ +\x14\xc5\xd6\x23\x33\xfe\x40\xe0\x0d\xba\xaa\x20\x80\xed\x24\xed\ +\x5b\xfc\x0d\x3b\x3e\x8f\x37\x6f\x2c\xc8\x55\x36\xa4\xa4\xca\xcb\ +\x3f\x65\xc6\x46\x10\xbe\xac\xad\xe5\x26\x16\xb6\xd5\x2d\xbe\x9d\ +\x5f\xc4\x93\x73\xd8\x9d\x98\xcb\x5d\x5e\xc6\x84\xed\x00\x1c\xba\ +\xaa\x2b\x44\x78\xd6\x96\x74\x6d\x6b\x3c\x07\x16\xa3\x21\x2f\xcf\ +\x63\x77\x4c\xb8\x58\x02\xa6\xcd\x50\x9f\x57\xba\x05\xde\x9a\x21\ +\x02\x4f\xf8\x7c\xbe\xb8\xfb\xa2\x84\x7a\x71\x97\xbb\x6c\x21\x13\ +\xd5\x03\x18\x1f\xa9\x09\x3d\x04\x1c\x02\x70\xc8\x96\x72\xcd\x1f\ +\xaf\x19\x8a\xa2\x38\xbb\xc3\x19\x0b\x05\xf1\x72\x00\x2b\x00\x18\ +\x4d\xc3\x83\xc4\x58\xef\xaf\xf7\x56\x0f\x47\x3f\x60\xc2\x30\xe6\ +\x5a\x51\x3a\x85\xed\xb6\xe7\x01\xb8\xa3\x84\x05\x09\x38\xc2\x84\ +\xbf\x32\xd3\x07\x36\x19\xfe\x88\x25\x77\x3b\xc6\x25\x5f\x91\x14\ +\x08\xf7\x0f\xa4\xa6\x12\xfa\xd3\x29\x2c\xa6\x0a\xc2\x74\x66\xca\ +\x05\x51\x01\xc0\x69\x51\x72\x9e\x24\x81\xf5\x7e\x9f\xf7\x54\x22\ +\xfa\x4d\x1b\xc7\x5d\xab\x2a\x0a\x99\xf9\xf7\x00\xac\xed\x0c\x09\ +\x5d\x00\xff\x2a\x83\x02\xde\xe1\x34\xf9\xc8\x74\x26\xe2\xfa\x61\ +\xea\xae\x15\x20\xde\x08\xe0\xdb\x66\xe6\x06\xd0\x09\x60\x6b\x30\ +\x35\x54\x6d\xe6\x19\x45\xcb\x66\x72\x05\x2b\x2b\x66\x31\x50\xc2\ +\xe0\x22\x00\xd3\x87\x93\x83\x80\x4f\x25\xe8\x75\xc1\x72\x4f\xee\ +\xec\xc9\x6f\x0d\xe7\xff\x00\x31\xdc\xc3\x7a\xb8\x56\x94\x4e\x91\ +\x0e\xdb\x62\x02\xcd\x02\xe4\x0c\x30\x4d\x05\x90\x0e\x20\x0d\xd7\ +\x77\x6e\xbe\x00\x10\x00\xe8\x9f\x00\x9f\x63\xe0\x1c\x8b\xf0\x91\ +\x56\xdf\xee\x0e\x8c\x92\xe3\xb8\x63\x18\xc3\x18\xfe\x37\xf1\x1f\ +\x38\xf1\xe0\xe7\x81\x02\x5e\x62\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x00\xcd\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x7f\x49\x44\x41\x54\x78\x9c\xed\ +\xd9\x51\x0d\x80\x30\x10\x05\xc1\x03\xff\xca\x50\x41\x83\x10\x90\ +\xb1\x24\x9d\x31\x70\x2f\x9b\xfe\x75\x26\x74\xaf\xe7\xbd\xd7\xf3\ +\x96\x1b\xce\xf2\xf8\x1f\x08\x50\x0f\xa8\x09\x50\x0f\xa8\x09\x50\ +\x0f\xa8\x09\x50\x0f\xa8\x09\x50\x0f\xa8\x09\x50\x0f\xa8\x09\x50\ +\x0f\xa8\x09\x50\x0f\xa8\x09\x50\x0f\xa8\x09\x50\x0f\xa8\x09\x50\ +\x0f\xa8\x09\x50\x0f\xa8\x09\x50\x0f\xa8\x09\x50\x0f\xa8\x6d\x1f\ +\xe0\x28\x8f\xd7\x5f\xe3\x33\xf1\x0b\x38\x66\xae\xf2\x3e\x00\x00\ +\x00\x00\x00\x00\x00\x6c\xe2\x03\x9c\x6d\x0b\xf4\x94\x3b\x8d\x4b\ +\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x30\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xe2\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\xb1\x0d\xc2\x30\x18\x05\xe1\x67\x86\x48\x87\x94\x99\x58\x21\ +\x15\x13\xb1\x05\x33\x45\xa1\x61\x0b\x53\x80\xa8\xa0\xb2\x9d\x43\ +\xe2\xbe\x2a\xc5\x2f\x78\xbe\x44\xd2\x3f\x2b\xa3\xff\x60\x5d\x6f\ +\xa7\x94\x5c\x92\x24\x35\xe7\x79\x3e\x5e\x7b\xde\xb7\x3a\x8c\xfc\ +\xf1\x24\x79\x3d\x66\x4a\x32\xbd\x1f\xd6\xf3\xbe\xd1\xf8\x00\xcf\ +\xc7\x7c\xfa\xee\x75\xdf\x64\x8f\x00\x3f\xcd\x00\xf4\x00\x9a\x01\ +\xe8\x01\x34\x03\xd0\x03\x68\x06\xa0\x07\xd0\x0c\x40\x0f\xa0\x19\ +\x80\x1e\x40\x33\x00\x3d\x80\x66\x00\x7a\x00\xcd\x00\xf4\x00\x9a\ +\x01\xe8\x01\x34\x03\xd0\x03\x68\x06\xa0\x07\xd0\x0c\x40\x0f\xa0\ +\x19\x80\x1e\x40\x33\x00\x3d\x80\x66\x00\x7a\x00\xcd\x00\xf4\x00\ +\x9a\x01\xe8\x01\x34\x03\xd0\x03\x68\x06\xa0\x07\xd0\x0c\x40\x0f\ +\xa0\x19\x80\x1e\x40\x33\x00\x3d\x80\x66\x00\x7a\x00\xcd\x00\xf4\ +\x00\xda\x1e\x01\xee\x5f\xbe\x7b\xdd\x37\x19\x1f\xa0\x66\x49\xc9\ +\x96\x92\x2d\x35\x4b\xf7\x7b\x49\x6a\xf0\x00\xc5\x3d\x1c\x34\xe1\ +\xa3\xf7\x6f\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\x2c\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\xde\x49\x44\x41\x54\x78\x9c\xed\ +\x98\xcf\x6b\x5c\x55\x14\xc7\x3f\xe7\xbe\x34\x34\x91\x8a\x60\x71\ +\x93\xb6\x2e\xb2\xd0\x90\x22\xc6\x42\x17\xad\x59\xc4\xa6\x69\x0a\ +\x5a\x35\x31\x0b\x17\x22\x4d\x13\xf0\x1f\x10\x7f\x40\x91\xa0\x82\ +\xba\x50\x0a\x2e\x34\x9d\x69\x04\x89\x05\x33\x9d\x74\x84\x9a\x32\ +\x33\x29\x23\xe2\xaa\x36\xe9\xaa\x31\x5d\x04\x6d\x2b\x88\xa6\x0b\ +\x9b\xd2\x40\x66\xe6\x1d\x17\x49\x63\xdf\x9b\x37\xc9\x64\x66\xde\ +\x34\xda\xfb\x59\xbe\xf3\xee\x79\xdf\x73\xef\xb9\xe7\xbe\x7b\xc0\ +\x62\xb1\x58\x2c\x16\x8b\xc5\x62\xb1\x58\x2c\x16\x8b\xc5\xf2\x60\ +\x21\xfe\x07\x9d\x3d\xfd\xef\x89\x31\xc7\x51\x1c\xc0\x05\xb4\xf6\ +\xb2\xaa\x8a\x00\x06\x21\xaf\xae\xfb\x7e\x3a\x7e\x6a\xe8\x5e\x63\ +\x5d\xc1\xdb\xb2\x1a\x3c\x80\xa9\x85\xc2\x9a\xa0\x38\x22\xe6\x38\ +\xe0\x99\x80\xff\x4f\x80\x65\x52\x30\x01\xaa\xee\x07\xa0\xff\xf5\ +\xb4\x0f\x40\x75\x39\x36\x2f\x05\x35\x00\xe0\x50\x4f\x7f\x47\x5e\ +\x4c\x42\x60\x9b\xc7\x05\xa8\x2c\xd7\x85\xcd\x8b\xaa\x41\xc4\x13\ +\x97\xc2\x02\xc2\x91\x74\x2c\x92\xf1\xbf\x1e\x38\x01\x00\x5d\x7d\ +\x03\x7b\x34\xcf\x79\x84\xed\xfe\x2f\x80\x71\x37\x5f\x6d\x14\x40\ +\x0d\xfe\x98\x94\x79\x71\xe8\x4e\x8e\x45\x2e\x15\x1b\x55\x94\xee\ +\xbe\xfe\x27\xf2\xae\x49\x01\x3b\xbd\x4e\x55\x11\xd9\x6c\x99\x50\ +\x18\x3c\x5c\x73\x8c\xdb\x75\x7e\xec\xd4\x6c\xb1\x41\x6b\x4e\x00\ +\x40\xd7\x8b\x47\x77\x6a\x9d\x93\x04\x9e\xf4\x99\x94\xcd\xb3\x1d\ +\x82\x82\xff\x45\x72\xf9\xae\x64\x62\xe4\xfa\x7a\x03\xd7\x24\x99\ +\x18\xb9\x9e\xad\x37\xed\xc0\xcf\x3e\x93\x80\x3a\x41\x63\x6a\x87\ +\xb0\xa2\xc1\x1f\xfc\xc5\x6c\xbd\x69\x5f\x2f\x78\x28\xf1\x18\xcc\ +\x9c\x1e\x9e\x6f\xc8\xba\xcf\x21\x5c\x28\x22\xa0\xe6\x08\x08\xb8\ +\x4e\x40\x12\x4f\x36\x64\xdd\x03\x99\xd3\xc3\xf3\xa5\xf8\x29\x59\ +\xfc\xec\xec\xf4\xd2\xae\xbd\x4f\x7d\xeb\x64\x4d\x2b\xd0\xe2\x91\ +\x02\xa6\x84\xdd\x54\x45\x44\x8a\x7c\x33\x5e\x77\xa7\xa1\xf7\xdc\ +\xb9\x2f\xef\x94\xea\x69\x43\xab\xf7\xeb\xe5\xcb\xb9\x5d\x8f\xbd\ +\x70\xc6\x69\x5c\x68\x02\x9e\x09\x52\x15\x36\x72\xf7\xd7\xb6\x90\ +\xe8\x23\xe6\xef\xd7\x13\x89\x91\xec\x06\xfd\x95\xa7\xa3\xb3\x77\ +\xe0\x63\x81\x37\x03\x1c\xba\x1a\xd6\x19\x29\x08\x1a\x10\xbc\xc8\ +\x27\xa9\xd8\xc9\xb7\x29\xe3\xbb\x65\xef\xdf\xb9\x99\xa9\x54\x73\ +\x4b\xdb\x22\x22\x07\xfd\x72\xc2\xc8\x85\xa2\x2b\xaf\xfa\x56\xea\ +\x4c\x64\xa8\x70\x44\x69\x54\x54\xc0\xe6\x66\xa6\x7f\x6a\x6e\x6d\ +\xfb\x1d\xe4\x79\xbc\xd9\x54\xd5\x19\x10\x10\x2d\x0c\xde\x15\x65\ +\x30\x15\x8f\x7e\x5e\xa1\xef\xca\xe9\xec\x1d\xec\x15\xf4\x1b\xa0\ +\xde\x67\xaa\xf8\x5f\x41\x51\x13\x90\x52\x4b\x2a\xbc\x9a\x8e\x45\ +\xe2\x95\xf8\x86\x2a\xae\xd4\x81\x9e\xc1\x4e\x23\x7a\x16\x78\xc8\ +\x6b\x51\x85\xf2\xfe\x1a\x15\x8c\x14\x6a\xbc\x8d\xe8\x4b\xa9\x58\ +\x74\xb2\x3c\xa5\x5e\xaa\x9a\xaa\x87\xfa\x8e\xed\x75\x5d\xf9\x1e\ +\x78\xd4\x63\x50\x14\xd9\x60\x26\x28\x06\x29\xd0\x77\xd3\x55\x39\ +\x3c\x19\x3f\x79\xb1\x32\xa5\xff\x52\xf5\x6a\xd5\xf9\xf2\x40\x8b\ +\x18\x52\x40\x93\xcf\x54\xfa\x76\x08\xb8\xd1\x01\x37\xd4\xa5\x2b\ +\x3d\x1e\x99\xa9\x82\xcc\x55\xaa\xde\x10\x49\x8f\x47\x66\xf2\xaa\ +\xfb\x81\xab\x3e\x53\xf0\x11\xe6\x43\x09\x0c\xfe\xaa\x1a\xb3\xbf\ +\xda\xc1\x43\x48\x1d\xa1\x0b\xf1\xe8\x6f\xe2\xd6\xb5\x2b\x4c\x79\ +\x0c\xcb\x29\xbd\xd6\xc9\xe3\xf8\x0b\x9e\xc2\x54\x9d\xc9\x3f\x9b\ +\x1e\x1b\xbe\x16\x82\xd4\xf0\x5a\x62\xc9\xf1\x2f\xfe\xdc\xb2\x75\ +\xb1\x03\xe5\x07\xbf\x4d\x03\x27\x21\xf0\x4e\x91\xd9\xb2\x75\xb1\ +\x63\x62\x6c\xe4\xaf\x10\x24\x02\x21\xf7\x04\x27\x46\x47\x6f\x65\ +\x1f\xce\x75\x23\xfa\xdd\xbd\xcf\x57\x96\xd8\x11\x41\x64\x35\x2b\ +\xbc\x59\x2f\x90\xc8\x6e\xcb\x1d\x9e\x18\x1d\xbd\x15\xa6\xc6\xd0\ +\x6f\x72\xcb\xf7\x87\x23\x31\xa7\x71\xe1\x71\xe0\x69\x9f\x59\x08\ +\x2c\xc4\xfa\x55\xf6\xe6\x8e\xd7\x32\x67\x4f\x2c\x85\xad\xaf\x26\ +\x5d\xe1\x4c\x66\x28\xb7\x6f\x77\x53\xbf\x22\x9f\xad\xff\xb6\x7e\ +\xba\x6f\xf7\x8e\x63\x99\xcc\x50\x2e\x7c\x65\xb5\xbd\xc3\x02\xc8\ +\xc1\x57\x06\xde\x41\xf9\x30\xd0\xa8\xfa\x6e\x32\x1e\xfd\x88\x1a\ +\x36\x1c\x6b\xde\xcc\x98\xbb\x32\xf5\x63\x73\x6b\xdb\x1f\x2b\xf7\ +\x87\xbb\xa8\x28\x6f\x24\xe3\xd1\x13\xb5\xd6\x73\x5f\xba\x39\x73\ +\x57\xa6\x2f\x35\xb7\xee\x69\x64\xb9\xcf\x78\x5b\x94\xa3\xc9\x78\ +\xe4\xeb\xfb\xa1\xc5\x62\xb1\x58\x2c\x16\x8b\xc5\x62\xb1\x58\x2c\ +\x16\x8b\xc5\xf2\xa0\xf1\x0f\x64\x76\x37\x12\x6f\xd4\x61\x03\x00\ +\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xc8\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x7a\x49\x44\x41\x54\x58\x85\xed\ +\xd2\xb1\x0d\x83\x40\x10\x44\xd1\xbf\x4b\x0f\x96\x08\x08\xdc\x09\ +\x9d\x10\x90\xb8\x24\x02\xc7\xae\x81\x6e\x08\x1c\x20\xd1\x03\xb7\ +\x8e\x0e\x59\x42\x22\xe3\x2e\x99\x97\x8d\xb4\xd2\x4c\xb0\x20\x22\ +\x22\x52\x99\xfd\x87\x88\x30\xa0\xb9\xb9\x73\x37\xb3\x38\x0d\x58\ +\x96\x6f\x6f\xce\x07\x68\x6f\x1e\xb0\x85\x33\x3c\xbb\x6e\x06\xf0\ +\x63\x89\x33\x15\x28\x07\x78\x58\xe2\x9d\x83\x5f\x5d\x96\x70\x0c\ +\x88\xc4\x0b\x58\x0b\x74\x6e\x61\x31\xe6\x50\xfd\x09\x45\x44\x44\ +\xaa\xfb\x01\x02\x66\x1a\x07\xaf\xc1\xa8\xac\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x03\x63\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x15\x49\x44\x41\x54\x78\x9c\xed\ +\x99\x5f\x48\x53\x61\x18\xc6\x9f\xef\x9c\xcd\xe9\xa0\x14\x2b\x92\ +\xbc\x52\x8c\xae\xba\xda\x99\x56\x26\x44\x04\xa1\x37\x15\x61\xd1\ +\x55\x46\xe2\x51\x6b\xb3\x24\xe8\x22\x68\x17\x75\x17\x99\x6d\x91\ +\x73\x81\x7a\x11\x12\x49\x10\x05\x26\x04\xd9\x45\x65\xe5\x66\x94\ +\x41\x08\xf6\xe7\xa2\x34\x44\x4b\x34\x1c\xfb\xfb\x76\x63\x31\xb7\ +\x63\x43\xf0\xfb\x8e\xd0\xf7\xbb\xdb\xfb\xc2\x9e\xe7\x7b\xce\xbb\ +\x9d\x77\x67\x80\x44\x22\x91\x48\x24\x12\x89\x44\x22\x91\x48\x24\ +\x92\xff\x0d\xc6\x5b\x40\xd3\xbd\xbd\x00\x8e\x01\x00\x63\x38\x31\ +\xec\x77\xf7\xf0\xd6\x5c\x09\x5c\x03\xd8\x53\xd7\x9d\xfb\xcb\x36\ +\x1f\x4e\xad\x11\xd1\xde\x50\xa0\x65\x90\xa7\xee\x4a\x50\x78\xbe\ +\xf9\x94\x7d\xc1\x92\x5e\x63\x8c\x3d\xd1\x9a\xda\x4a\x79\xea\xae\ +\x04\x11\x1f\x01\x32\xaa\xdb\x62\xe1\xf5\xcf\xbb\xce\xcf\xf3\xd6\ +\xcf\x06\xd7\x09\x00\x80\x92\x1f\x45\x19\x53\x00\x00\x11\x6b\xde\ +\x1c\x3c\x1e\xee\xfa\xd9\xe0\x6e\xa0\xaf\xef\x48\x42\xcd\x41\xbe\ +\x51\x4f\xfb\xbe\x21\xc1\x5b\x3f\x1b\x42\xae\xc0\x2b\x9f\x7b\x2e\ +\xa9\xaa\x5b\x8d\x7a\x9a\xee\x7d\x26\xc2\xc3\x72\x08\x1b\xc1\x91\ +\x9b\xa7\xc6\x19\x68\x9f\x41\xab\xd2\xa1\xfb\xae\x88\xf2\x91\x8e\ +\x2a\x52\x6c\x22\x34\xf0\x79\x8b\xb3\x7a\x06\x40\x4d\x6a\x9d\x01\ +\xbb\x8a\x9d\xd5\xe3\x13\xc1\x47\xa3\x22\xfd\x2c\x6a\x8b\xc7\xd9\ +\xe8\xeb\x21\xa2\xe3\x19\x0d\x86\x8a\xa0\xdf\xfd\x5a\xa4\x17\x53\ +\x02\x00\x00\x4d\xf7\x7d\x04\x28\x63\x1f\x48\x58\x59\xf1\x9b\x1b\ +\xae\x09\x51\x3e\x4c\x0b\x00\x58\x7e\x47\xb0\xda\xe3\xf6\xa1\x6b\ +\xad\x61\xa3\xde\x6a\x63\xea\x7d\x98\xc8\x96\x63\x54\x8f\x2d\x58\ +\x16\x00\x12\x72\x71\x4c\x0d\x20\x14\xd0\x63\x44\xd1\x4d\x46\x3d\ +\x4d\xf7\xfd\x14\xe1\xc1\xf4\x4d\x2c\x14\x38\x37\x0d\x46\xdb\x0d\ +\x5a\xf9\x9a\xee\xbd\xc3\x5b\xdf\xf4\x00\x00\x20\xe8\x6f\x79\x0f\ +\xd0\x41\x83\xd6\x51\xde\xda\x6b\x22\x00\x00\x20\x52\xc6\xcc\xd0\ +\x5d\x13\x01\x54\xd4\xb7\x6f\x66\x8c\xfa\x33\x1a\x0c\x2f\x78\x6b\ +\x9b\x1e\x80\xa3\xa1\xd3\x9e\x50\x95\x07\x00\x4a\x52\xeb\x8c\xd1\ +\xa5\xa0\xdf\x5d\xc9\x5b\xdf\xd4\x00\x6a\x6b\xef\xaa\x8c\x45\x7a\ +\x01\x94\xa7\xd6\x09\xb8\x35\xec\x77\x7b\x44\x78\x30\x35\x80\x4f\ +\x85\x93\x57\x01\x1c\x48\x2b\x0f\xac\x2b\x9a\x69\x06\x98\xe1\x92\ +\xb4\xda\x98\xb6\x09\x3a\x75\x5f\x0b\x81\xda\x53\x6b\x04\xbc\xcd\ +\x8d\x85\xab\x44\x3e\x29\x32\x25\x80\xf2\xc6\xeb\x87\x92\xc4\xee\ +\xa5\xe9\x7f\xb5\xb2\xf8\x8e\x21\x7f\xeb\x37\x91\x5e\x84\x07\xe0\ +\x68\x68\xaf\x60\x4c\x19\x04\x90\x97\x52\x9e\x4f\x2a\xc9\xdd\x23\ +\x1d\x67\xde\x89\xf6\x63\xf8\xbc\x8e\x17\x5a\x53\x5b\x29\x48\x79\ +\x08\x5a\x72\xf8\x38\xa0\x1c\x1e\xe9\x70\x0b\x3f\x3c\x20\xf0\x4b\ +\x70\xe7\xc9\xb6\x42\x24\x2d\xfd\x20\x2c\xdd\xfd\x19\xf4\x60\xe7\ +\xe9\xc7\xa2\x7c\xa4\x23\x64\x02\xca\x5c\x5e\x5b\x3c\x8a\xfb\x00\ +\xb6\xa5\xd6\x19\x70\x79\xd8\xef\xee\x12\xe1\x61\x39\xf8\x4f\x80\ +\xc7\xa3\x14\x44\xd1\x4d\x40\xd5\xd2\x06\xdd\x1e\xee\x74\x5d\xe4\ +\xae\x9f\x05\xee\x01\x38\x26\x37\x5e\xc0\xe2\x7f\x83\x29\x3c\x9d\ +\xcd\x61\xf5\xa2\xee\xf5\xff\x82\xeb\x5d\xa0\xcc\xe5\xb5\x15\x44\ +\x31\x0b\x20\xf7\x6f\x91\xd8\x87\x88\xaa\x56\x8e\x76\x34\x0b\xf9\ +\xbd\x9f\x0d\xae\x13\x90\x1f\xb1\x25\x01\xc4\xfe\xbc\x66\xc0\x94\ +\x45\x89\xd7\xac\x95\xc3\x03\x9c\x03\x08\x05\xf4\x18\x03\xea\x00\ +\x4c\x03\x18\x43\x32\xb1\xff\xa5\xff\xec\x17\x9e\x9a\x12\x89\x44\ +\x22\x91\x48\x24\x12\x89\x44\x22\x91\x48\x24\xd9\xf8\x0d\x59\x9b\ +\xda\x0c\x1f\xf1\x22\x4f\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ +\x60\x82\ +\x00\x00\x01\x89\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x3b\x49\x44\x41\x54\x58\x85\xed\ +\x97\x31\x4e\x02\x41\x14\x86\xbf\xb7\x81\xa5\x74\x69\x56\x0a\x43\ +\x34\xd9\x66\x2f\xe0\x09\x4c\xe4\x0e\x9c\x02\x6b\xb5\x90\x1e\x4e\ +\xc1\x19\x8c\x89\x27\xe0\x02\xdb\x6c\xc0\x80\xc5\x86\x06\x2c\x59\ +\xc8\x3e\x0b\x67\x0d\x2c\x62\xa1\xbb\xb1\x70\xfe\x6a\x32\x33\xc9\ +\xf7\x65\xa6\x79\x3f\xfc\xf7\x48\x71\x63\x3a\x9b\x5d\x3b\x2a\x37\ +\x0a\x97\x80\x57\x12\x67\x25\x30\xce\x44\x07\x17\xed\xf6\xd3\x51\ +\x81\x97\xd9\x6b\x1f\xd5\x5b\x60\x0d\x44\x28\x6f\xa5\xe0\x85\x13\ +\x20\x04\x1a\x88\xf4\xcf\xdb\x67\xf7\x07\x02\xd3\xf9\xbc\x23\x19\ +\x8f\xa0\xcf\xdb\x8d\xdb\x0d\x82\xd6\xa2\x14\xb8\x49\x1c\x27\x7e\ +\xad\x9e\x8e\x40\xae\x54\xb4\x93\xbf\x84\x93\x5f\x70\x32\x7a\xc0\ +\xba\x0a\x38\x40\x10\xb4\x16\xdb\x8d\xdb\x05\x52\x47\xa5\xf7\xc9\ +\xcd\x17\xe6\xcf\xa3\x2a\xe0\xbb\x12\x08\x91\x61\xed\x0b\x00\x5e\ +\x69\x7f\xfe\x5d\x32\x56\x40\xf3\x2b\x81\x3f\x89\x15\xb0\x02\x56\ +\xc0\x0a\x58\x01\x2b\x60\x05\xac\xc0\xae\xc0\xca\x4c\xaf\x55\x13\ +\x3d\x60\x79\x20\x20\x30\x06\xc2\x38\x4e\xfc\xaa\xd8\x71\x9c\xf8\ +\x28\xa1\x61\xed\x0b\x64\xa2\x03\xa0\x51\xab\xa7\xa3\x2a\x24\x26\ +\x93\xc9\xe9\xc7\x58\x8e\x9b\x89\x0e\xf3\xfd\x62\x31\x79\x40\xf5\ +\x0e\x48\x11\x22\x33\x40\xfe\x3e\x0e\x1e\x4a\x08\xb8\x47\x8b\x49\ +\x1e\x53\xcd\x7a\x66\x74\x6e\x16\xcf\x7f\x98\xa5\xa9\x66\xc3\x62\ +\x35\xb3\x79\x07\x25\xbf\x6e\x2c\x3a\x0b\x42\xe7\x00\x00\x00\x00\ +\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xd3\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x85\x49\x44\x41\x54\x78\x9c\xed\ +\xd7\xb1\x0d\xc2\x40\x10\x04\xc0\x7d\xe8\x01\x51\x0a\x75\x20\x3a\ +\x20\x72\x45\xee\x82\x90\x1e\xe8\xc4\xa2\x07\x78\x52\xf4\x26\xb5\ +\x1e\xd9\x33\xe1\xea\x82\xbd\xcb\x2e\x01\x00\x00\x00\x00\x60\x3b\ +\x4a\x1b\x9c\x6e\xf5\x5c\x53\xc7\x24\x87\x0e\x7d\x96\x34\xe5\x5d\ +\xae\x8f\x4b\xb9\x7f\x87\xbb\x76\x6a\xa5\xcb\x27\xc9\xb1\xec\xeb\ +\xd8\x86\xb3\x03\x6c\xcd\xec\x00\x25\x65\x48\xf2\xec\xd0\x65\x69\ +\x53\x7d\x95\xa1\x77\x09\x00\xe0\x7f\xf8\x05\xda\xa9\x95\x2e\x9f\ +\xf8\x05\x7e\xf3\x0b\x00\x00\x00\x00\x00\x00\xb0\x11\x1f\x5d\xbc\ +\x24\x0f\x6c\x9f\x83\x41\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ +\x60\x82\ +\x00\x00\x01\x8c\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x3e\x49\x44\x41\x54\x58\x85\xed\ +\xd2\xbf\x2b\x85\x51\x00\xc6\xf1\xef\xf3\xca\x62\x90\x52\xac\xfc\ +\x05\x14\xbd\xf7\x96\xcd\x24\x3f\x8a\x9b\x98\x58\x29\x7f\x80\xcd\ +\x24\x93\xc9\x2c\x52\x06\x03\x2f\x29\x25\x8b\x22\xf1\x8a\xa2\xcc\ +\x16\x65\xb1\xd0\x1d\xa4\xee\xbd\x8f\x81\x01\xc5\xeb\xde\x4d\xce\ +\x67\x3c\x3d\x3d\x3d\xa7\x73\x20\x08\x82\x20\xf8\xef\x94\x15\xc8\ +\x6f\x95\x97\x2d\x75\x95\xd1\xc4\x45\x41\x37\xbf\x29\xcd\x6f\xbb\ +\xcd\xf6\x3a\xe2\x29\x1d\xd6\x20\x92\xbf\xcb\x46\x59\x65\x46\x4d\ +\x40\x67\x1d\x3e\x89\x13\xf7\x66\xe5\x73\xdb\xee\xb2\x7d\x06\xf4\ +\x50\xa1\x39\x2b\x9f\x39\x20\x2a\x6b\x02\xd8\x04\x1a\x85\xf7\xe3\ +\xc4\x93\xdf\x65\xe3\x2d\x0f\x60\x1f\x01\xad\xc0\xe1\x4b\xa4\xbe\ +\x9f\x6e\xff\xab\x01\xa7\x63\x7a\x4e\xaf\x35\x0e\x5e\x04\xea\x85\ +\xd7\x72\x89\xe7\xb0\x3f\x3d\x5f\x9c\x78\x5a\xf2\x2e\xd0\x00\x5e\ +\x2f\x96\xd4\x77\x35\xa2\xc7\xac\xfe\xcc\x3f\xf0\x51\x2e\xf1\x0c\ +\x78\xe9\x6d\xb8\x57\x4b\x0f\xd1\xd4\xe5\x3d\xe5\xb8\xa3\xb2\x20\ +\x34\x0b\x80\x3d\x9f\x16\xa2\xb9\xac\x9b\xd7\x34\x00\x20\xbf\xe3\ +\x21\x57\xbc\x01\x34\x00\xc7\x88\x22\xa6\x1f\x28\x81\xa6\xd2\x82\ +\x56\xaa\xe9\xab\x7a\x00\x40\xbc\xe9\x6e\x45\xde\x03\x5a\xde\x8f\ +\x8a\x48\xa3\xe9\x88\x0e\xaa\xed\xaa\x69\x00\x40\xbc\xeb\x76\x95\ +\x7c\x0b\xdc\x19\x0d\x9d\x17\x74\x5d\x6b\x57\xed\x6c\x7d\xfd\x8c\ +\x41\x10\x04\xc1\x9f\xf3\x0a\x0d\x2b\x72\x05\x90\xf4\xef\x82\x00\ +\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x21\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xd3\x49\x44\x41\x54\x58\x85\xed\ +\x97\xb1\x6b\x53\x51\x14\xc6\x7f\x5f\x5e\xe9\x22\x15\xb4\xc4\xfe\ +\x01\x1d\x4a\x47\x5d\x2c\x28\x2e\x79\xea\x10\x09\x54\x5e\xd7\x22\ +\xe4\xe9\x20\x98\xa9\x54\xff\x04\x33\x38\x18\xc1\xc5\x64\xd0\x0e\ +\x45\x94\x08\x85\x0c\x1a\xe2\x20\xa8\x75\xd1\x4d\xb7\xee\x6d\x51\ +\x90\xe0\x52\xc8\x3d\x0e\xbe\x17\x9f\x52\x5e\x89\x7d\x69\x45\xf3\ +\x4d\xf7\x9d\x7b\x38\xdf\xef\xde\x73\x79\xdc\x0b\xff\xbb\xf4\x7b\ +\xe0\xfc\xe5\xf2\x19\xa4\x9b\xc0\x1c\x90\xcf\xc8\x67\x1b\x58\xc7\ +\xac\xda\x6e\x36\x5e\x27\x27\xbc\xe4\x87\x1f\x94\x97\x84\x56\x81\ +\x19\xe0\x48\x46\xe6\x44\xb5\x66\x90\xae\x4c\xcf\x9e\xfa\xb6\xf1\ +\xe9\xfd\xdb\x78\xa2\xbf\x03\xfe\xc2\xb5\xb3\x72\xee\x15\xf0\x15\ +\xb3\x4a\xce\xa3\xf5\xfc\x49\xe3\x4b\x16\xee\x17\x17\xca\xc7\x5d\ +\x8f\x22\x52\x0d\x38\x8a\xd9\xb9\x78\x27\xc6\xfa\x24\xce\x2d\x03\ +\xc2\xac\xd2\x6e\x36\x56\xb2\x30\x8e\x15\x2d\x64\xc5\x0f\x42\xc9\ +\x78\x18\xb5\xb8\x04\x90\x4b\xe4\xcd\x01\xe4\x3c\x5a\x59\x9a\x27\ +\x65\xbd\x9d\xb8\xf6\xe9\x38\x96\x04\xc8\x27\x68\x87\xa2\xce\xb3\ +\x47\x9f\xa3\xe1\x89\xdd\x00\x0e\x45\x23\x80\x11\xc0\xa1\x03\x8c\ +\xed\x95\x70\x21\xb8\x7a\xdd\x99\xdd\x16\x4c\x0c\x52\xd8\xa0\x9b\ +\x93\x6e\xbd\x78\xfa\xe0\x7e\x5a\x5e\xea\x0e\x14\x4a\xe1\x94\x99\ +\xdd\x1b\xd4\x1c\x40\x30\x61\x66\xb5\x42\x29\x9c\xfa\x63\x80\x83\ +\x50\x2a\x40\x67\xad\xbe\x29\xe9\x86\x41\x77\xd0\xc2\x06\x5d\x49\ +\x95\xce\x5a\x7d\x33\x2d\x6f\xcf\x33\x10\xf5\x30\xb5\x8f\xfb\xd1\ +\xdf\xdd\x82\x11\xc0\x08\xe0\xa0\x01\xb6\xe1\xc7\x05\x72\x58\x66\ +\x85\xf9\xc5\xc9\x68\xb8\xb5\x1b\xc0\x3a\x80\xeb\x51\x1c\x16\x80\ +\xbc\xf1\xb8\xf6\xbb\x38\xf6\xf3\x47\x64\x56\x45\xba\x84\x54\xf3\ +\x83\x50\xd6\xdb\x69\x25\xee\x70\xfb\x52\x61\x7e\x71\x52\xde\x78\ +\x51\xc6\x5d\xc0\x61\x56\xed\x43\x25\x13\xfd\xa0\xbc\x24\x53\x95\ +\xe1\x9d\x0d\x87\xb1\xdc\x6e\xd6\xef\xc4\x81\x5f\x5e\x46\x1b\x1f\ +\x3f\xbc\x99\x9e\x3d\xd9\x41\xca\x03\xc7\xc8\xee\x75\xb4\x05\xbc\ +\xc4\x2c\x6c\x37\x1b\x8f\x33\xaa\xf9\x8f\xe8\x3b\xaa\x2b\x8c\x73\ +\x1f\xb4\x18\x18\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\ +\x00\x00\x01\xaa\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x5c\x49\x44\x41\x54\x58\x85\xed\ +\x94\x3f\x4b\x42\x51\x18\x87\x9f\x57\xad\x4d\xac\x21\x8a\x5a\x0c\ +\xb7\x6c\x72\x74\x70\x09\x6d\x68\x08\xba\xda\x16\x05\x1a\x41\xdf\ +\xa0\x49\xce\xd0\xd2\x27\xa8\x54\x70\x0a\x32\x8d\x86\x5a\x14\xa4\ +\xbe\x80\xd0\xe4\x94\xd4\x14\xd1\x90\x53\x43\xea\x3d\x4d\x5a\x8d\ +\xf7\x5c\xb8\x4b\xf7\xd9\x5e\x38\xe7\xf7\x3e\xbc\xe7\x0f\xf8\xf8\ +\xf8\xfc\x77\xc4\xe9\xfa\xb4\x55\xb0\x01\x06\xa3\xe1\xec\xfd\x4d\ +\xb5\xef\x56\x20\xe0\x64\x71\xb1\x58\x9c\x08\x4f\x05\x43\x1f\xb9\ +\x5c\x2e\xe8\xa9\x80\x52\xca\x46\xf4\xf6\xb8\xee\xdb\x91\xa1\xa7\ +\x02\x00\xad\x7a\xe5\x4a\xe0\x78\x5c\x67\xac\xc2\xa3\x1b\x01\xa3\ +\x11\x3e\x75\x3b\xed\x58\x3c\x91\x02\x96\x81\xf9\xd8\x4a\x62\xa1\ +\xd7\xed\xdc\x99\x64\x39\xbd\x84\x7f\x48\x5b\x05\x3d\x09\xd2\x1c\ +\x34\xaf\xcb\xe7\x4e\x33\x1c\x1f\xc1\x6f\x92\xab\x4b\x93\x09\x6a\ +\xe1\x2c\xb3\x95\x4f\x79\x2a\xa0\x94\xb2\x07\x81\xe9\xf0\x8f\x84\ +\x3c\x78\x2a\x00\x30\xc7\xfb\x17\xe8\x67\xd3\xfd\x6e\x05\xa4\x6f\ +\xcf\x94\x41\xa2\x08\x6f\x23\xad\xa3\x9e\x0a\x64\xb2\x85\x22\xe8\ +\x1d\xe0\x53\x84\x8d\xf6\x75\xe5\xc5\x69\x86\xf1\x2b\xc8\x58\xf9\ +\x5d\x8d\x54\x01\x5b\x44\x36\x9b\xf5\xd2\xad\x49\x8e\xd1\x3f\x90\ +\xce\xe6\xd7\x40\x6a\x40\x00\xe4\xb0\xd5\x28\x5d\x98\xe4\x80\xc1\ +\x11\xac\x5b\xfb\x71\xb4\x34\x80\x10\x22\x27\xad\x46\xe9\xd4\xb4\ +\xb9\x89\x80\xd8\x50\x03\x22\x1a\x2e\x93\xf1\xc5\x23\x37\xcd\x01\ +\x42\xce\xb7\xe8\x57\x0d\xbd\x61\x78\xb8\xa7\x94\xb2\xdd\x0a\xf8\ +\xf8\xf8\xf8\x7c\x03\xa5\xd7\x5e\xc1\x97\x2b\x14\xb6\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x31\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xe3\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\xb1\x11\x82\x40\x18\x05\xe1\xf7\x5b\x04\xb5\x58\x07\x2d\x18\ +\x59\x91\x5d\x50\x87\x75\x10\x59\x05\x18\xa0\x99\x46\x77\xb0\xce\ +\xb8\x5f\x74\xc1\x0d\xbc\xdb\x44\xd2\x3f\xab\xbd\x7f\x70\x9e\xd6\ +\x71\xcd\x7a\xdb\x7e\x56\xd7\xfb\x58\x53\xcf\xfb\xad\x4e\x7b\x7e\ +\x3c\x49\x5e\x8f\x19\x92\x0c\xef\x87\xf5\xbc\xdf\x6a\xf7\x00\xd9\ +\x1e\xf3\xe9\xdc\xeb\x7e\x93\x23\x02\xfc\x34\x03\xd0\x03\x68\x06\ +\xa0\x07\xd0\x0c\x40\x0f\xa0\x19\x80\x1e\x40\x33\x00\x3d\x80\x66\ +\x00\x7a\x00\xcd\x00\xf4\x00\x9a\x01\xe8\x01\x34\x03\xd0\x03\x68\ +\x06\xa0\x07\xd0\x0c\x40\x0f\xa0\x19\x80\x1e\x40\x33\x00\x3d\x80\ +\x66\x00\x7a\x00\xcd\x00\xf4\x00\x9a\x01\xe8\x01\x34\x03\xd0\x03\ +\x68\x06\xa0\x07\xd0\x0c\x40\x0f\xa0\x19\x80\x1e\x40\x33\x00\x3d\ +\x80\x66\x00\x7a\x00\xcd\x00\xf4\x00\x9a\x01\xe8\x01\x34\x03\xd0\ +\x03\x68\x47\x04\x78\x7c\x39\xf7\xba\xdf\x64\xff\x00\x4b\x5d\xaa\ +\x32\x57\x65\xce\x52\x97\xee\xf7\x25\xa9\xc1\x13\x85\x02\x26\x2c\ +\x67\x7d\xc5\x41\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\ +\x00\x00\x02\xda\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\x8c\x49\x44\x41\x54\x78\x9c\xed\ +\x9a\x3b\x6f\x13\x41\x14\x46\xcf\xb5\x13\x42\x13\xba\xfc\x92\x48\ +\xb6\x25\x1a\x5a\xba\x3c\x44\xe4\x90\x80\x44\x05\x05\x2d\x1d\x2d\ +\xff\x00\x24\x5c\x21\x1e\x79\x08\x84\x57\x34\xd4\x74\x80\x5b\x7e\ +\x07\x12\x12\x0d\x42\x72\x3e\x0a\x84\x64\x36\xeb\x38\xde\x9d\x99\ +\x9d\x59\xfb\x96\xb3\x77\x3f\xcd\x39\xda\x5d\x5b\x57\x03\xcb\x5a\ +\xd6\xb2\x16\xb9\xac\xee\x0d\xf8\xae\x4e\xa6\x2d\x93\x9e\x48\xfc\ +\x68\xb7\xed\xc1\xe7\x2d\xfb\x36\x79\x7d\xa5\xae\x8d\x85\xa8\xee\ +\x50\x7d\xa4\x23\xa0\x65\x06\xe3\xb1\x9e\x03\xd7\x27\x7b\x5a\xf5\ +\x6c\xcd\x7f\x75\x87\xea\xc3\x5f\xf8\x7f\x6b\x2d\xe3\x5a\xbe\xaf\ +\x91\x02\x8a\xe0\x81\xb1\xb0\xc7\xf9\xde\xc6\xbd\x02\x17\xc0\xef\ +\x8f\x76\xec\x43\xbe\xbf\x51\x1f\xc1\x19\xf0\xef\x8a\xee\x69\x8c\ +\x80\x32\xf0\xd0\x10\x01\x65\xe1\xa1\x01\x02\xaa\xc0\x43\xe2\x02\ +\xaa\xc2\x43\xc2\x02\x5c\xc0\x43\xa2\x02\x5c\xc1\x43\x82\x02\x5c\ +\xc2\x43\x62\x02\x5c\xc3\x43\x42\x02\x7c\xc0\x43\x22\x02\x7c\xc1\ +\x43\x02\x02\x7c\xc2\x43\xe4\x02\x7c\xc3\x43\xc4\x02\x42\xc0\x43\ +\xa4\x02\x42\xc1\x43\x84\x02\x5c\xc3\x77\x86\xba\x05\x7a\x06\x80\ +\xec\xfe\x68\xd7\xb2\xc9\xeb\x51\x4d\x84\x5c\xc3\x77\x87\xea\x1b\ +\x3a\x35\xd8\x30\xd8\xc0\x34\xc8\xf7\x44\x23\xc0\x07\x7c\x41\xde\ +\xb9\x8a\x42\x40\x20\xf8\xb3\x96\xd9\xc3\x7c\x6f\xed\x02\x42\xc1\ +\x1b\x76\xf7\xcb\xb6\xbd\xcd\xf7\xd7\xfa\x11\x0c\x0a\xbf\x63\x47\ +\x45\xf7\xd4\x26\x20\x06\x78\xa8\x49\x40\x2c\xf0\x50\x83\x80\x98\ +\xe0\x21\xb0\x80\xd8\xe0\x21\xa0\x80\x18\xe1\x21\x90\x80\x50\xf0\ +\x92\xdd\x19\xed\xda\xf1\x3c\x59\xde\x05\xc4\x0c\x0f\x9e\x05\xc4\ +\x0e\x0f\x1e\x05\xa4\x00\x0f\x9e\x04\xa4\x02\x0f\x1e\x04\xa4\x04\ +\x0f\x8e\x05\xa4\x06\x0f\x0e\x05\xa4\x08\x0f\x8e\x04\xa4\x0a\x0f\ +\x0e\x04\x04\x83\x37\x3b\x1c\x6d\xdb\xc9\xbc\x79\xbd\x4c\x7b\x67\ +\xd2\x53\xc0\xfd\x4c\x30\x76\xf8\x6e\xa6\x43\x49\x27\x5e\x66\x82\ +\x29\xc0\x23\xbd\x64\x06\x63\x29\x01\xb1\xc3\xf7\x86\x3a\x28\x80\ +\x77\x33\x13\x4c\x01\x5e\xe8\x55\x3e\xcf\xc9\x4c\x30\x69\xf8\xaa\ +\x33\xc1\xd8\xe1\x3b\xef\x75\xdb\x4c\xaf\xcf\xe5\xcd\xf8\xe9\xbc\ +\x94\x80\xa6\xc2\xc3\x25\xce\x0a\x87\x82\x07\x3b\x18\x6d\xdb\xe9\ +\xbc\x79\x55\xe0\x61\xc6\x13\x10\x12\xfe\xeb\x4e\x78\x78\xb8\x40\ +\x40\xf4\xf0\x99\xf6\x4d\x7a\x93\xcf\x9b\xf7\x35\x2a\x14\xb0\x28\ +\xf0\x00\xed\xfc\x42\x2f\xd3\x1e\xe8\x18\x47\xf0\x53\xf2\x4a\xc3\ +\xf7\x32\xed\xa1\xf3\x79\x65\x3f\xa0\xff\x3d\x01\x9b\x03\xad\xae\ +\x6c\xe8\x3b\xb0\x3e\xb1\x5c\x1a\x7e\x4a\x5e\x69\x78\xd7\x79\x90\ +\xfb\x27\xb8\x7e\x85\x36\xb0\x36\xb1\x54\xe9\x58\x4a\x41\x5e\xa5\ +\xcd\xba\xce\x83\x9c\x80\x4f\xf7\xec\x97\x61\x8f\x80\xdf\xc0\x4f\ +\x64\xfd\x2a\x67\x72\xf2\x79\x66\xb6\x5f\x65\xb3\xae\xf3\xa6\xd6\ +\xcd\x8f\x5a\xdb\x1c\x68\x35\xd6\xbc\x1b\x2f\x74\xd5\x65\xde\xb2\ +\x96\xb5\xc0\xf5\x07\xd6\x41\x4c\x2b\x6c\xde\x0f\x7f\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\xe8\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x9a\x49\x44\x41\x54\x58\x85\xc5\ +\x97\xd9\x76\xe2\x46\x10\x86\xbf\x66\x11\x12\x60\x50\x9c\xc4\x9e\ +\xf1\x24\x39\x59\xde\xff\x9d\x72\x31\x9e\x49\x1c\xcf\x18\x6c\x23\ +\x19\x24\xa8\x5c\xd4\xdf\xa8\x91\x71\x72\x97\xd4\x39\x1c\x89\x56\ +\xd7\xf6\xd7\xd6\x0d\x58\x09\x16\xf8\xcf\xc9\x02\x58\x19\xa4\x7c\ +\x09\xac\x21\x58\xf7\x91\x4b\x20\x1a\x96\x25\xef\x93\x44\x4a\x5c\ +\xb3\x64\x6d\x9b\xac\xed\xf4\x7e\x00\x1e\x7a\xf2\x97\xc0\x3a\xf4\ +\x16\x0e\xc0\x05\x30\x00\xaa\x44\x59\x90\x11\x13\xd8\x0d\x21\x8c\ +\x81\x71\xcf\xa5\x16\xac\x81\xac\x95\x11\x51\xb9\x01\x0d\x90\x4b\ +\xfe\x23\x30\x3c\x75\xd8\xf7\x2d\xc0\x7e\x11\x34\x63\xb0\x99\xd6\ +\x33\xb0\xf7\xf0\x50\x82\xe5\x60\x13\xb0\x82\x57\x64\x85\xbe\x4d\ +\xb5\xf7\xca\x79\xc1\xd7\x2c\x93\xec\x5f\xc1\x2e\xfa\x10\x02\xf6\ +\x01\xf8\x24\x24\x0c\x78\x01\x0a\xd8\xbd\x87\xec\xa3\xbc\x00\x58\ +\xc8\x8b\x73\x94\x7e\x9b\xc0\xee\x06\xb2\x5b\x21\x92\x4b\xdf\x1a\ +\xb8\x81\x70\x0b\x30\x92\xf2\x80\xc3\x3e\x96\xf2\x1b\xe0\xde\x19\ +\xb2\xfb\x44\xf9\x04\x0f\x91\x71\x1a\xf7\xe8\xcc\x4c\xca\xf4\xcb\ +\xbe\xc2\xa6\x80\xd9\x18\x78\x07\x7c\x94\x8e\x41\x0f\x01\xfb\x4e\ +\xff\x2b\x08\x15\xd8\xb5\xbe\xfd\x09\xcc\x1d\x8d\xd5\x0c\x4a\x5c\ +\x70\xa8\xcf\x03\x60\x73\xa0\xc5\xf3\xa5\xd2\xf3\x80\x27\xf4\x0e\ +\x78\xc2\xe3\xff\x0d\xb0\x82\xb0\x19\x25\xdc\x63\x29\xcf\xe5\xdd\ +\x1a\xb8\x92\xc5\x39\x94\x4f\x82\x71\x02\x66\x1d\x0f\x24\x08\xe5\ +\xc0\xb3\x94\x95\x42\x38\x03\xee\xf0\xf0\x64\x10\x9e\x12\x07\x3b\ +\x28\xdc\x52\x9b\xc0\xcb\xb5\x18\x83\xa0\x5c\x48\x68\xa4\x39\x1e\ +\x86\xb9\xf8\x07\xfa\x1f\xd7\x22\x6d\xc4\xbb\x93\xac\x00\xdb\xf7\ +\x4a\xcc\x63\xee\xc5\x10\xbc\x73\x41\x15\x30\xfd\x8c\xc7\xb2\x96\ +\xf5\x23\xc1\x56\x43\x75\x09\xd3\xb5\x23\x75\x8e\x6c\x21\x99\x35\ +\x30\x95\x03\x53\xba\xd2\x1b\x49\xf6\x1c\x0f\xc1\x97\x14\x81\x09\ +\xb4\x2f\x49\x6d\x16\x8a\xb5\xe1\x96\x5d\xc3\x74\xe5\x48\xbd\x49\ +\xb1\xce\xbf\x17\x8f\x09\x89\x58\xb6\x2d\x3c\x36\x78\xe8\xfa\x21\ +\x68\x4a\x58\x3c\x74\xc6\x30\x54\x3e\xe4\x78\xd2\xfc\x25\xc1\x85\ +\xfa\x41\xee\x49\x67\xb3\xee\x3f\x05\x9e\x37\x5f\x61\x73\x29\xde\ +\x3c\x91\x09\x2c\x9e\x49\x42\x15\x0d\xc8\xbc\x8b\x91\x0b\xc6\x52\ +\x1e\xb4\x62\x5c\xe1\x89\xf6\x20\x48\x73\x3d\x83\xa0\x9d\xba\x0c\ +\xa6\xae\x9c\x06\x66\x0f\xda\xd7\xe2\x3d\xe5\x12\xef\x31\x43\x68\ +\x4c\xfb\x63\x1f\x20\x40\x50\xd7\x0a\x8f\xde\xb9\x82\x32\xdb\x0c\ +\x82\xfa\xbb\x35\x12\x36\x06\xee\x7b\xbd\xfd\xca\x8d\x8e\x7c\xb4\ +\x60\x7b\x7f\x86\x1d\xd8\x33\x5e\x86\x03\xba\x24\x3f\xa9\x82\x61\ +\x52\xdf\x49\x93\xa9\xd3\x3d\xda\xc7\xbd\x7b\x63\xe9\x30\xbb\x4b\ +\x1c\x8a\x94\x4e\x59\xc9\x0c\x55\xe7\x6c\xc7\x30\x82\xf1\x21\xf1\ +\x86\xe4\xbd\x4d\x84\x8c\x80\xc6\x3d\xb7\x35\xea\x4c\x78\x46\x5b\ +\xd2\x1f\x52\x4a\x1d\x78\x35\x3d\x07\xc9\x73\x7f\x86\xb9\x4f\x87\ +\x9e\xc0\x3e\x9d\x6b\xcf\x96\xbc\xbf\xda\x17\x85\xed\xa0\x51\x57\ +\x0b\xd6\x6d\x0e\x06\xf5\xb0\x67\xc0\x30\x81\x7d\xa5\xdf\x32\x99\ +\x27\x7d\x83\x4f\x46\x6e\xdf\x98\x94\xa1\x55\x29\xf5\xac\x2d\xfa\ +\x75\xdf\xe2\x09\xa7\x79\x1e\x62\xdb\xbe\xa6\x3b\x03\x44\x0a\xaf\ +\xdf\xad\x00\x3b\xee\x8b\x39\x60\xca\x70\x53\x19\xce\x34\x58\xc0\ +\x4b\xb3\x94\xe2\x02\x6f\xb9\x6a\x36\x96\x42\xdc\x00\xdf\x4a\xb8\ +\x49\xb6\x0e\x21\x16\x3b\x20\x32\x76\x1f\xf9\xa2\x01\x3b\x08\x43\ +\x95\xdb\xd6\x0f\x24\x34\xfe\xdf\xc0\x33\x7f\x23\x21\x9f\xff\x61\ +\x1a\xee\x38\x9e\x76\xd6\x25\x2c\xef\x3a\x07\x79\xc0\x4b\x38\xee\ +\xd9\xc1\x49\x08\xc6\x75\xe2\xf5\x16\x35\x0a\x51\x05\x2f\x3f\xc9\ +\xf3\x73\x99\x7e\xb4\x40\x1e\x7e\x80\xe5\x53\xb7\xbc\x2a\xa4\x1c\ +\x37\x6c\xbc\x89\x5f\x06\x09\xe3\x06\xea\xb2\x63\xa2\xf6\x86\x14\ +\x0f\x1a\xf9\x2d\x3e\xdd\xfa\x67\xc1\x94\x22\xd4\x7f\xe0\xed\x36\ +\xf8\xb3\x4c\x86\x57\x36\x93\x31\x27\x21\xd8\xfb\xe6\xe2\x19\xec\ +\x86\x6e\xe0\x14\xf8\x49\xe6\x77\x3c\x9e\x7b\xa0\x74\xa4\xea\x41\ +\x97\xa0\xf5\x50\x02\xd5\x21\x8f\x7b\x7f\xc6\xbb\x9f\x8e\x77\x2c\ +\xa1\xb8\x95\xcc\x6d\x6a\x00\x6e\x40\x78\x06\x1b\xd0\xc5\x7c\x24\ +\x6f\x0e\x10\x36\x60\x2d\xf0\x0c\xe1\xe5\x3c\x00\x36\x77\x19\xa0\ +\x83\xeb\x67\x7c\x96\x6c\x24\x73\xe5\xf9\xd3\x45\x31\x0d\x41\xe3\ +\x93\x2d\x3c\x42\x7d\xe1\x9e\xb2\x96\xf5\x5b\xe5\xc7\x71\x8c\xbe\ +\x4d\x36\x56\xe8\x1a\x3c\xd1\xd6\xc0\x25\x54\x33\x47\xc3\x66\x5a\ +\x3f\x09\xc1\x57\xe0\x07\xdf\x6c\x4b\x60\x06\x2f\x41\x93\x74\x42\ +\x67\xb2\x0e\x97\x55\x05\x85\xd1\x75\xcf\xd8\xac\x0a\x3c\xdb\x77\ +\x38\xf3\xc2\x8d\xaf\xa7\x30\x9d\xe3\x13\x76\xe3\x8e\x87\x4d\x62\ +\x40\x30\xb0\x03\x5e\xeb\x01\xf8\x04\x45\x34\x86\x0e\x56\xf0\x30\ +\x4c\x75\xf4\x36\x21\x18\xe2\x1c\x59\x38\x82\xc7\xbd\x17\x6e\xcc\ +\xf4\x8b\x64\xc5\xd9\x72\xee\x50\x63\x17\xba\x34\xf4\x2f\x26\x0b\ +\xa8\x7e\xec\x2e\x23\xff\x76\x31\x01\xe7\xad\x3e\x74\x65\x7d\x72\ +\x31\xf9\xed\xcc\xc5\xe4\xd8\xdb\xf7\x82\x6d\x20\x2b\x33\x1c\xfe\ +\x81\x7f\x6f\x32\x79\x30\x84\x71\x7a\xf7\xcb\x75\x30\x6e\x7d\xd4\ +\x8e\x6a\xbc\x67\xec\xc5\xdb\xd0\x0d\xa6\x35\xc9\xd5\xec\x8d\xcb\ +\x69\xf4\xe2\x98\x70\xc3\xe4\x7d\xa2\xf7\x09\x6c\x35\x3b\x26\x95\ +\x94\x18\xdd\xe5\x54\x06\xb9\xb0\x18\xf3\x9e\xc3\x6b\xf8\x9f\xaf\ +\xe7\x7f\x03\x88\x7c\xd3\x3b\xed\x32\x4f\xdf\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xee\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xa0\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\x41\x0d\x00\x20\x00\x03\x31\x82\x7f\x91\x10\x84\x80\x8c\xf2\ +\xb8\x1a\xd8\x65\x63\x40\x6b\x9f\xbb\xf6\xb9\xb2\x61\xca\xf1\x1f\ +\x74\x80\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\ +\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\ +\x80\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\ +\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\ +\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\ +\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\ +\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\ +\xad\x03\x74\x80\xd6\x01\x3a\x40\x7b\xd6\x8f\x07\xc5\x02\xeb\xa3\ +\x1e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x0a\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xbc\x49\x44\x41\x54\x58\x85\xed\ +\x94\x3d\x6b\x14\x61\x14\x85\x9f\xf3\x6e\x84\x85\x80\x68\x23\x83\ +\x9b\x9d\x37\x0b\xfe\x00\x7f\x81\x9d\x28\x12\xb4\xd1\x52\x48\x2b\ +\x41\xf2\x1f\xf4\x0f\x88\x16\x96\x36\x16\x8a\x58\x69\xa1\x58\x5a\ +\x68\xa9\xbd\x98\xcc\xec\x46\xd6\x4a\x63\x12\x30\xc8\xce\xb1\xd8\ +\x0f\x96\x7c\xed\xce\xfa\x91\x66\x1e\x18\xb8\x33\x5c\xce\x39\xdc\ +\x79\xef\x0b\x15\x15\x15\x15\xc7\x8c\x86\xc5\x7a\x96\x7f\x03\x9d\ +\xfa\x3f\xb6\xfe\xbe\x18\xd3\xd3\x00\x61\xf4\x69\xac\xfe\xe7\xf6\ +\x63\x5e\xa3\x62\x2e\xa8\x85\x78\xdf\xef\x30\x98\x02\xe8\xfd\x95\ +\xc7\x14\xd8\x43\xab\x77\x73\x41\xad\xe1\xcb\xe8\x17\x00\x74\xbb\ +\xdd\xf9\xdd\xdd\x5f\xcf\x0d\x97\x06\x49\x0b\x81\xf9\x03\x0c\x12\ +\x0e\x20\x30\xaf\xea\xf5\x13\xd7\x93\x24\xd9\xd9\x37\x01\x80\x24\ +\x49\x76\xb6\xb6\x36\xaf\x0a\x3d\x1d\xa4\x0b\x7b\x43\x96\xb4\x57\ +\x5f\x43\x60\x3d\xd9\xde\xde\xbc\x36\x6e\xce\x61\xe2\xb6\x6b\x59\ +\xb6\xf1\x00\xf9\x96\x6d\x24\x15\x94\x9c\x84\x40\x85\x1d\x24\x81\ +\xf5\x30\xc6\xc6\x6d\x49\xbd\xbd\x7d\x07\x1e\x3c\x49\xbd\x18\x1b\ +\x2b\x48\x77\x25\x01\x04\x95\x98\x84\x40\x86\x20\x09\xc3\x9d\x18\ +\x1b\x2b\x07\x99\x0f\x7a\x8f\x26\xcb\xda\xab\x86\x7b\x00\x06\x0b\ +\x8a\xa3\xfa\x3d\x16\x56\xb0\x1a\x63\xf3\xfe\x84\xb0\x93\xc9\xb2\ +\xce\x4d\xe3\x47\x40\xad\xef\x71\x48\x08\x13\x10\x02\x7a\x82\xe5\ +\x18\x9b\x8f\x27\x69\x4f\x3d\xd6\x2c\xeb\x2c\x19\x3f\x03\xea\x18\ +\xa3\x7d\x21\x86\x07\xf6\xa7\xd0\x8d\x18\x17\x5e\x4e\xa3\x5b\xea\ +\x84\x7f\xce\xf3\x0b\xc1\x7a\x01\x9c\x44\x78\x70\x57\x80\x08\x18\ +\x01\x3f\x82\xbc\x94\xa6\xe9\xdb\x69\x35\x4b\xaf\xd8\xda\x5a\xe7\ +\xbc\x82\x5f\x03\x67\x40\x76\x7f\xd5\x00\x7d\x75\xc1\xe5\x56\x6b\ +\xe1\x43\x19\xbd\x99\x76\xbc\xdd\x6e\x9f\xeb\x15\x7a\x03\x5e\x1c\ +\xc8\xac\xd7\x82\x2f\x36\x9b\xcd\x4f\x65\xb5\x66\xbe\x64\xf2\x3c\ +\x3f\x5b\x58\x1b\x88\x8f\x01\x5f\x49\xd3\xf4\xcb\xac\x5a\x15\x15\ +\x15\x15\xc7\xca\x6f\xbc\xd7\xa4\x72\xc7\xdc\xd0\xf5\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x78\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x2a\x49\x44\x41\x54\x58\x85\xed\ +\xce\x41\x01\x00\x20\x0c\xc4\xb0\x0d\x4d\x78\x9a\x1f\x0c\x83\x8c\ +\xe3\x91\x18\x68\xab\x00\x80\xb0\xde\x73\x6e\x72\x60\x25\xe3\x00\ +\xc0\x17\x1e\xbe\x17\x02\x30\xed\xb9\x5b\x96\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x20\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xd2\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\xb1\x0d\xc2\x40\x14\x44\xc1\x35\x45\x38\x43\x72\x4d\xb4\xe0\ +\x88\x8a\xe8\x82\x9a\x2c\x93\xd0\x85\x09\x40\x44\x90\x7a\x90\xd8\ +\x89\x2e\xbb\xfd\x2f\xa9\xaa\x7f\x36\xa8\x8f\x97\xe5\x76\xca\x90\ +\x4b\x92\x64\xcb\x79\x9a\x8e\x57\xb1\xe3\x20\x3e\x4d\x92\xd7\xf1\ +\x63\x92\xf1\x1d\x02\x70\x01\x9e\xc7\x7f\x7a\xef\x4a\x06\xf8\x09\ +\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\ +\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\ +\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\ +\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\ +\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\ +\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\ +\x0d\xa0\x07\x68\x32\xc0\xfd\xcb\x7b\x57\x2e\xc0\x96\x39\x43\xd6\ +\x0c\x59\xb3\x65\x66\x3b\xaa\xea\xaf\x3d\x00\x08\x2d\x0e\x52\x29\ +\x6c\xf3\x60\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\x03\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\xb5\x49\x44\x41\x54\x58\x85\xe5\ +\x97\x5d\x68\x9b\x55\x18\xc7\x7f\xcf\x79\xfb\x81\x53\xe7\x6c\x07\ +\x8b\xd8\xb2\x59\xaa\x62\x41\x91\x35\xcd\xf4\xc2\xaf\x39\x36\x44\ +\xb6\x4e\xb0\x88\xc8\x9c\x0c\xd7\x74\xad\xe9\xaa\x20\x74\x78\x11\ +\x83\x43\x0b\x82\xc5\x34\xad\x26\x1b\x88\xa2\x57\x03\x8b\xed\x74\ +\x3a\x50\xba\x2b\xe9\xb2\x58\xbc\xb0\x14\x84\x0a\x9a\x36\x1d\xae\ +\x05\xc5\x6d\x36\xcb\x7b\x1e\x2f\x92\x7e\x66\xed\x5a\x9a\x7a\xb3\ +\xff\xe5\xf3\x3e\xe7\xfc\x7f\xcf\xe1\x3d\xe7\x3c\x07\x6e\x76\xc9\ +\x6a\x92\xeb\x9a\xbb\x2b\xad\x9b\xd9\x2f\x2a\xbb\x10\x2a\x11\x2a\ +\x50\x0c\xca\x18\x22\x49\x84\x73\x8e\xda\xde\xc1\xe8\xd1\x5f\x0b\ +\x0a\xe0\x6d\x0a\xfb\x50\x3a\x80\xa7\x56\x38\x6b\x5c\x54\x8f\xc5\ +\xa3\x47\xbf\x5f\x13\x40\x6d\x63\xf4\x0e\x91\xe9\x8f\x80\x17\x73\ +\xa1\x14\x48\xbf\x2a\x67\xd4\x71\x47\xf5\x5f\x93\x2a\xde\x60\xac\ +\xa6\xf1\x58\xb1\xdb\x8c\x61\xb7\x5a\xea\x11\xb6\xe6\xa6\xff\xc6\ +\x71\xdd\x43\x83\x27\xdb\x2e\xae\x1a\x60\x7b\x73\x77\xb5\xc9\xd8\ +\x3e\x44\x1f\x00\x52\x22\x04\x6f\xdd\x32\xf9\xc9\x40\x28\x94\x59\ +\xb6\xa4\x60\xd0\x78\x27\xca\x5f\x00\x39\x0e\x5a\x05\xfc\x6e\x60\ +\xdf\xf9\x68\xeb\xcf\x2b\x06\xf0\x1e\xf9\xa0\x0a\x5b\x34\x08\x6c\ +\x06\xbe\x72\x4a\x78\x79\xb0\xab\xf5\xef\x65\x8d\x17\xa9\x3a\x10\ +\x2e\xdd\x34\x4d\x0f\xc2\x21\xe0\x32\xc2\x63\x17\x3e\x6e\x1d\xba\ +\x21\xc0\x8e\x40\x78\x63\x26\xcd\x8f\x02\x35\x8a\x7e\x98\xf0\x4c\ +\xbd\x41\x28\x64\x57\x63\x3e\x27\x95\x3a\x7f\xb8\x5d\x91\x77\x81\ +\xa4\xaa\xeb\x4b\xc4\x5e\x4f\xcd\xcf\x30\x8b\x87\xb8\xd3\x44\x04\ +\x6a\x80\xfe\xb5\x99\x03\x88\xc6\xa3\xad\x1d\x22\x9c\x04\x2a\x8c\ +\x38\x9f\x83\x2e\x28\x7a\x01\x80\xcf\xdf\xe5\x45\x38\x80\xf0\xa7\ +\x6a\xe9\x81\xb5\x99\xcf\x41\x5c\x9e\x9c\x6c\x01\x46\x14\x76\x7a\ +\xfd\xe1\x67\x96\x04\xb0\xa2\xef\x01\xa8\xea\x3b\x89\x98\xff\xaf\ +\xb5\x9b\x67\x35\x7c\x2a\x94\x16\x78\x2b\x07\xd4\x31\x7f\x15\x66\ +\x01\x6a\x1b\x3b\xef\x42\x79\x1a\x98\xba\x3a\x35\x15\x2d\x94\xf9\ +\x8c\xe2\xd1\x40\x2f\x30\x02\x3c\xe8\xf3\x77\x3d\x94\x07\x20\x98\ +\xbd\x80\xa0\x7c\x3d\x7c\x2a\x94\x2e\x34\x00\x88\xa2\xda\x07\x60\ +\x45\x9f\xcb\x03\x40\xe4\x49\x00\x45\xbe\x2d\xbc\x79\x56\xd6\x98\ +\xef\xb2\x28\xb2\x33\x1f\x00\x2a\x01\x1c\x91\xdf\xd6\x0b\xa0\x84\ +\xcc\x28\x80\x42\x45\x1e\xc0\x4c\xd0\xc8\xb5\x54\xfe\xd0\xc2\xe8\ +\x52\xb1\x33\x33\xf7\xdd\x33\x3f\x62\xde\x39\xf0\xbf\x29\xf8\xf6\ +\x42\x00\x81\x31\x80\xb4\x38\x9e\xf5\xf2\xbc\xdd\x1a\x0f\x80\xc2\ +\xf8\xcc\x19\x33\xb7\x02\x2a\x7f\x00\x18\xcb\x3d\xeb\x05\x60\xae\ +\xb9\x55\x00\x02\xc9\xd9\xd8\xdc\x57\x1d\x00\x10\x91\x3d\xeb\x06\ +\x60\xd8\x0d\xa0\xf0\x43\x1e\x80\x5b\x24\xfd\x00\xaa\xfa\x6c\x6d\ +\x63\xb4\xb8\xf0\xf6\x2a\x56\x65\x1f\x80\xb1\x6e\x6f\x1e\xc0\x50\ +\x24\x30\x2e\x59\xb2\xcd\x30\xfd\x6a\xa1\xed\xbd\x47\x22\x7b\x73\ +\x97\xdc\x2f\xf1\x13\x6d\xb3\xbd\xc1\xc2\x5d\x60\x6d\x3b\x80\x08\ +\xc1\x1d\x81\xf0\xc6\x42\x99\xd7\x34\x04\x4b\xd4\x66\xef\x19\x81\ +\x63\x20\x7a\x5d\x80\xf8\x89\xb6\xb8\xc2\x17\xc0\x16\x37\xcd\x67\ +\x04\x83\x05\xd8\xa6\x2a\x1b\xee\x2c\x0f\xe7\xaa\x1f\x88\x47\x03\ +\xa7\xe7\x7f\xcd\x37\xd0\xd2\x16\xb2\x97\x46\xbd\x77\xa2\xfc\xfd\ +\xb5\x41\xa8\x78\x9b\x22\x6f\x22\xf8\x51\xc6\xdd\x62\x79\x69\x7e\ +\xf5\xb0\x44\x4b\xb6\xbd\xb9\xbb\xda\xb8\xee\x20\x50\x06\x7c\x79\ +\xc5\x71\x0e\x0e\xf7\xb4\xfc\xb3\x1a\xeb\x9a\x86\x60\xc9\x2d\x65\ +\xe5\x11\x81\xc3\xc0\x15\x83\x3c\x71\x3e\x1a\xb8\xb0\x38\x6f\xc9\ +\xa6\xd4\x77\x38\x72\x9f\x35\xb6\x0f\xb8\x5f\x91\x31\x81\xe0\x6d\ +\x9e\x4b\x9f\xae\xa4\x29\xad\xbb\x58\xf6\xbc\x55\x39\x2e\x70\x2f\ +\x90\x54\x35\xf5\x89\xd8\x6b\x3f\x5d\x2f\x7d\xd9\xb6\xfc\xe1\x57\ +\x3a\x37\x15\x95\x9a\x18\x48\x43\x2e\x94\x14\xa1\x1f\xe5\x0c\xd6\ +\x8c\x16\xd9\x74\xea\xaa\x2b\xd6\x29\x29\xf2\xa8\x61\xab\xb1\x76\ +\x0f\x62\xea\x73\xdd\x30\xc0\x59\x71\x9c\x83\xf1\x9e\x96\x89\xa5\ +\x3c\x56\xf4\x30\xf1\xf9\x23\x8f\x5a\xb4\x03\xf4\xf1\x95\xe4\x03\ +\x43\xaa\xb4\x27\x62\xad\x67\x6f\x94\xb8\xaa\xa7\xd9\x23\x4d\x9d\ +\xdb\x32\xd6\xd9\x8f\xb0\x0b\xcd\x3d\xcd\xc0\x01\x92\xd9\xe3\x55\ +\xcf\x59\x35\xbd\x89\x58\x60\x64\x35\xf3\xde\xdc\xfa\x0f\x80\xbd\ +\x5b\x45\x41\xb4\xc0\xa5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ +\x60\x82\ +\x00\x00\x04\xe8\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x9a\x49\x44\x41\x54\x58\x85\xc5\ +\x97\xd9\x76\xe2\x46\x10\x86\xbf\x66\x11\x12\x60\x50\x9c\xc4\x9e\ +\xf1\x24\x39\x59\xde\xff\x9d\x72\x31\x9e\x49\x1c\xcf\x18\x6c\x23\ +\x19\x24\xa8\x5c\xd4\xdf\xa8\x91\x71\x72\x97\xd4\x39\x1c\x89\x56\ +\xd7\xf6\xd7\xd6\x0d\x58\x09\x16\xf8\xcf\xc9\x02\x58\x19\xa4\x7c\ +\x09\xac\x21\x58\xf7\x91\x4b\x20\x1a\x96\x25\xef\x93\x44\x4a\x5c\ +\xb3\x64\x6d\x9b\xac\xed\xf4\x7e\x00\x1e\x7a\xf2\x97\xc0\x3a\xf4\ +\x16\x0e\xc0\x05\x30\x00\xaa\x44\x59\x90\x11\x13\xd8\x0d\x21\x8c\ +\x81\x71\xcf\xa5\x16\xac\x81\xac\x95\x11\x51\xb9\x01\x0d\x90\x4b\ +\xfe\x23\x30\x3c\x75\xd8\xf7\x2d\xc0\x7e\x11\x34\x63\xb0\x99\xd6\ +\x33\xb0\xf7\xf0\x50\x82\xe5\x60\x13\xb0\x82\x57\x64\x85\xbe\x4d\ +\xb5\xf7\xca\x79\xc1\xd7\x2c\x93\xec\x5f\xc1\x2e\xfa\x10\x02\xf6\ +\x01\xf8\x24\x24\x0c\x78\x01\x0a\xd8\xbd\x87\xec\xa3\xbc\x00\x58\ +\xc8\x8b\x73\x94\x7e\x9b\xc0\xee\x06\xb2\x5b\x21\x92\x4b\xdf\x1a\ +\xb8\x81\x70\x0b\x30\x92\xf2\x80\xc3\x3e\x96\xf2\x1b\xe0\xde\x19\ +\xb2\xfb\x44\xf9\x04\x0f\x91\x71\x1a\xf7\xe8\xcc\x4c\xca\xf4\xcb\ +\xbe\xc2\xa6\x80\xd9\x18\x78\x07\x7c\x94\x8e\x41\x0f\x01\xfb\x4e\ +\xff\x2b\x08\x15\xd8\xb5\xbe\xfd\x09\xcc\x1d\x8d\xd5\x0c\x4a\x5c\ +\x70\xa8\xcf\x03\x60\x73\xa0\xc5\xf3\xa5\xd2\xf3\x80\x27\xf4\x0e\ +\x78\xc2\xe3\xff\x0d\xb0\x82\xb0\x19\x25\xdc\x63\x29\xcf\xe5\xdd\ +\x1a\xb8\x92\xc5\x39\x94\x4f\x82\x71\x02\x66\x1d\x0f\x24\x08\xe5\ +\xc0\xb3\x94\x95\x42\x38\x03\xee\xf0\xf0\x64\x10\x9e\x12\x07\x3b\ +\x28\xdc\x52\x9b\xc0\xcb\xb5\x18\x83\xa0\x5c\x48\x68\xa4\x39\x1e\ +\x86\xb9\xf8\x07\xfa\x1f\xd7\x22\x6d\xc4\xbb\x93\xac\x00\xdb\xf7\ +\x4a\xcc\x63\xee\xc5\x10\xbc\x73\x41\x15\x30\xfd\x8c\xc7\xb2\x96\ +\xf5\x23\xc1\x56\x43\x75\x09\xd3\xb5\x23\x75\x8e\x6c\x21\x99\x35\ +\x30\x95\x03\x53\xba\xd2\x1b\x49\xf6\x1c\x0f\xc1\x97\x14\x81\x09\ +\xb4\x2f\x49\x6d\x16\x8a\xb5\xe1\x96\x5d\xc3\x74\xe5\x48\xbd\x49\ +\xb1\xce\xbf\x17\x8f\x09\x89\x58\xb6\x2d\x3c\x36\x78\xe8\xfa\x21\ +\x68\x4a\x58\x3c\x74\xc6\x30\x54\x3e\xe4\x78\xd2\xfc\x25\xc1\x85\ +\xfa\x41\xee\x49\x67\xb3\xee\x3f\x05\x9e\x37\x5f\x61\x73\x29\xde\ +\x3c\x91\x09\x2c\x9e\x49\x42\x15\x0d\xc8\xbc\x8b\x91\x0b\xc6\x52\ +\x1e\xb4\x62\x5c\xe1\x89\xf6\x20\x48\x73\x3d\x83\xa0\x9d\xba\x0c\ +\xa6\xae\x9c\x06\x66\x0f\xda\xd7\xe2\x3d\xe5\x12\xef\x31\x43\x68\ +\x4c\xfb\x63\x1f\x20\x40\x50\xd7\x0a\x8f\xde\xb9\x82\x32\xdb\x0c\ +\x82\xfa\xbb\x35\x12\x36\x06\xee\x7b\xbd\xfd\xca\x8d\x8e\x7c\xb4\ +\x60\x7b\x7f\x86\x1d\xd8\x33\x5e\x86\x03\xba\x24\x3f\xa9\x82\x61\ +\x52\xdf\x49\x93\xa9\xd3\x3d\xda\xc7\xbd\x7b\x63\xe9\x30\xbb\x4b\ +\x1c\x8a\x94\x4e\x59\xc9\x0c\x55\xe7\x6c\xc7\x30\x82\xf1\x21\xf1\ +\x86\xe4\xbd\x4d\x84\x8c\x80\xc6\x3d\xb7\x35\xea\x4c\x78\x46\x5b\ +\xd2\x1f\x52\x4a\x1d\x78\x35\x3d\x07\xc9\x73\x7f\x86\xb9\x4f\x87\ +\x9e\xc0\x3e\x9d\x6b\xcf\x96\xbc\xbf\xda\x17\x85\xed\xa0\x51\x57\ +\x0b\xd6\x6d\x0e\x06\xf5\xb0\x67\xc0\x30\x81\x7d\xa5\xdf\x32\x99\ +\x27\x7d\x83\x4f\x46\x6e\xdf\x98\x94\xa1\x55\x29\xf5\xac\x2d\xfa\ +\x75\xdf\xe2\x09\xa7\x79\x1e\x62\xdb\xbe\xa6\x3b\x03\x44\x0a\xaf\ +\xdf\xad\x00\x3b\xee\x8b\x39\x60\xca\x70\x53\x19\xce\x34\x58\xc0\ +\x4b\xb3\x94\xe2\x02\x6f\xb9\x6a\x36\x96\x42\xdc\x00\xdf\x4a\xb8\ +\x49\xb6\x0e\x21\x16\x3b\x20\x32\x76\x1f\xf9\xa2\x01\x3b\x08\x43\ +\x95\xdb\xd6\x0f\x24\x34\xfe\xdf\xc0\x33\x7f\x23\x21\x9f\xff\x61\ +\x1a\xee\x38\x9e\x76\xd6\x25\x2c\xef\x3a\x07\x79\xc0\x4b\x38\xee\ +\xd9\xc1\x49\x08\xc6\x75\xe2\xf5\x16\x35\x0a\x51\x05\x2f\x3f\xc9\ +\xf3\x73\x99\x7e\xb4\x40\x1e\x7e\x80\xe5\x53\xb7\xbc\x2a\xa4\x1c\ +\x37\x6c\xbc\x89\x5f\x06\x09\xe3\x06\xea\xb2\x63\xa2\xf6\x86\x14\ +\x0f\x1a\xf9\x2d\x3e\xdd\xfa\x67\xc1\x94\x22\xd4\x7f\xe0\xed\x36\ +\xf8\xb3\x4c\x86\x57\x36\x93\x31\x27\x21\xd8\xfb\xe6\xe2\x19\xec\ +\x86\x6e\xe0\x14\xf8\x49\xe6\x77\x3c\x9e\x7b\xa0\x74\xa4\xea\x41\ +\x97\xa0\xf5\x50\x02\xd5\x21\x8f\x7b\x7f\xc6\xbb\x9f\x8e\x77\x2c\ +\xa1\xb8\x95\xcc\x6d\x6a\x00\x6e\x40\x78\x06\x1b\xd0\xc5\x7c\x24\ +\x6f\x0e\x10\x36\x60\x2d\xf0\x0c\xe1\xe5\x3c\x00\x36\x77\x19\xa0\ +\x83\xeb\x67\x7c\x96\x6c\x24\x73\xe5\xf9\xd3\x45\x31\x0d\x41\xe3\ +\x93\x2d\x3c\x42\x7d\xe1\x9e\xb2\x96\xf5\x5b\xe5\xc7\x71\x8c\xbe\ +\x4d\x36\x56\xe8\x1a\x3c\xd1\xd6\xc0\x25\x54\x33\x47\xc3\x66\x5a\ +\x3f\x09\xc1\x57\xe0\x07\xdf\x6c\x4b\x60\x06\x2f\x41\x93\x74\x42\ +\x67\xb2\x0e\x97\x55\x05\x85\xd1\x75\xcf\xd8\xac\x0a\x3c\xdb\x77\ +\x38\xf3\xc2\x8d\xaf\xa7\x30\x9d\xe3\x13\x76\xe3\x8e\x87\x4d\x62\ +\x40\x30\xb0\x03\x5e\xeb\x01\xf8\x04\x45\x34\x86\x0e\x56\xf0\x30\ +\x4c\x75\xf4\x36\x21\x18\xe2\x1c\x59\x38\x82\xc7\xbd\x17\x6e\xcc\ +\xf4\x8b\x64\xc5\xd9\x72\xee\x50\x63\x17\xba\x34\xf4\x2f\x26\x0b\ +\xa8\x7e\xec\x2e\x23\xff\x76\x31\x01\xe7\xad\x3e\x74\x65\x7d\x72\ +\x31\xf9\xed\xcc\xc5\xe4\xd8\xdb\xf7\x82\x6d\x20\x2b\x33\x1c\xfe\ +\x81\x7f\x6f\x32\x79\x30\x84\x71\x7a\xf7\xcb\x75\x30\x6e\x7d\xd4\ +\x8e\x6a\xbc\x67\xec\xc5\xdb\xd0\x0d\xa6\x35\xc9\xd5\xec\x8d\xcb\ +\x69\xf4\xe2\x98\x70\xc3\xe4\x7d\xa2\xf7\x09\x6c\x35\x3b\x26\x95\ +\x94\x18\xdd\xe5\x54\x06\xb9\xb0\x18\xf3\x9e\xc3\x6b\xf8\x9f\xaf\ +\xe7\x7f\x03\x88\x7c\xd3\x3b\xed\x32\x4f\xdf\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x06\x7b\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x06\x2d\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\xc9\x73\x5c\x57\x15\xc6\x7f\xdf\xb5\x49\x39\x09\x91\x83\x33\ +\x40\x15\x2b\xb6\x78\x48\x9c\x48\x3d\x24\x14\xc4\x8a\x63\xc9\x93\ +\x2c\x75\xab\xf2\x87\xb0\x0a\x0b\x58\x50\x5e\xb0\xc9\x12\xfe\x88\ +\x54\xab\x25\x92\x38\x65\x6b\x34\x09\xa0\x1e\x0c\x45\x18\x56\x29\ +\x2a\x95\x62\x45\x26\xb0\x6c\x63\x29\x46\xf7\xb0\xe8\x6e\xe8\x74\ +\xb7\xf4\xee\xeb\x7e\x4f\xea\x14\xfa\x96\xf7\x9e\x3e\xf7\x7c\xbf\ +\x3a\xe7\xf5\xeb\xa7\x27\x38\xd0\x81\x0e\xf4\xff\x2c\xf5\x5a\x3c\ +\x75\xc3\x1e\x7d\xf8\x2e\x3f\x94\xec\xb2\xc1\x11\xcc\xd6\xed\x6b\ +\xee\x67\xb5\x29\x7d\xb8\xd7\x05\xf6\xa3\xcc\x9b\xf6\x1d\x3d\xf0\ +\xaf\x21\xe5\x05\x9b\x5e\xba\xf6\xc8\x03\x5e\xbf\xf9\xaa\xee\x76\ +\xc6\x76\x01\x78\xf1\x97\xf6\xd8\x03\x6f\xbf\x92\x71\xba\x63\xeb\ +\xb6\x9c\x26\x2a\xd3\xaa\xa6\x56\x79\x02\x1a\x9b\xb3\x31\x27\x5b\ +\x02\x8e\x76\x6c\xbd\xcf\x11\x7d\xbf\x7a\x41\x1b\xed\x8b\xae\x33\ +\xc1\xf6\xb6\x7f\xad\x87\x79\x80\xa3\xe6\x6d\x31\xb7\x60\xd9\x04\ +\xeb\x4d\x54\xbb\x98\x07\x78\x86\x4d\xff\xa3\xce\xc5\x2e\x00\xa0\ +\xa9\x5d\xce\x18\x19\x56\x08\x11\xe6\x9b\xd2\x95\xce\x95\x2e\x00\ +\x1e\x1e\x8e\x38\x6b\xc4\xbc\x2d\xe6\xe7\x2d\x13\xb7\xc8\xb4\x94\ +\x29\xd9\x68\xb4\x79\xc0\x38\xd2\xb9\xd4\x05\x40\xd8\x6f\x02\xce\ +\x1c\xf1\x66\x4b\xc3\x00\x21\x53\xb2\x51\x39\x5b\x26\xca\x3c\x80\ +\xba\xbd\x75\x8f\x80\x77\x57\x81\xdb\x01\x67\xef\x3b\x84\x58\xe6\ +\x61\x03\xef\x7e\xda\xb9\xd8\x05\xa0\x3a\xab\x0f\x9c\x74\x8e\x70\ +\x08\xfb\x32\x0e\x4d\xf3\xd1\x6d\xdf\xd0\x06\xa6\x89\xea\xac\x3e\ +\xe8\xdc\xe8\x79\x1f\x00\x90\x9f\xb7\x8c\x37\x5b\x02\x46\x02\x0e\ +\xb8\xed\x4d\xaf\xd4\x8b\xaa\x07\xc4\x0e\xac\xec\xbc\x3d\x8f\xd9\ +\x32\xf0\x78\x40\xf8\x1d\x4c\xe7\xaa\x45\x55\x7a\x6d\xee\x08\x00\ +\x86\x13\x42\x92\xe6\x21\x02\x00\x0c\x17\x84\xa4\xcd\x43\x00\x00\ +\x80\xdc\x82\x65\xcd\xdb\x22\x81\x10\xcc\xeb\x6c\x6d\x56\xb7\x42\ +\x72\x87\x2a\x37\x67\xcf\x99\x6c\x19\xf8\x46\x40\xf8\x1d\x43\x13\ +\xb5\x82\xd6\xa3\x02\x83\x00\xc0\xfe\x42\x48\xcb\x3c\xf4\xbc\x13\ +\xec\xad\xca\xb4\xaa\x98\x26\x80\x8d\xc8\x60\x38\x2a\x67\xcb\x99\ +\x92\x8d\x86\xe6\xdf\x49\x71\xcd\x3b\xa7\xc9\x50\xf3\x10\xa3\x03\ +\x5a\xca\xce\x59\x0e\xd9\x22\xf0\x58\x40\xf8\x3f\xcd\xeb\x95\x7e\ +\x3b\x21\xa6\xf9\xbb\xce\x69\x62\x7d\x5a\xbf\x8d\x73\x46\x6c\x00\ +\x10\x1f\x02\xd2\xd9\xea\x8c\x7e\x17\xe7\x8c\xbd\x30\x0f\x31\x46\ +\xa0\x5d\xd5\xa2\x2a\x98\xce\x01\x77\x02\xc2\x1f\xc7\x6c\x39\x3b\ +\x6f\xcf\x87\xe6\xcf\x97\xec\xf4\x5e\x98\x87\x3e\x01\x40\x03\x82\ +\xa1\x09\x12\x86\x90\x2f\xd9\x69\xef\x6c\x85\x40\xf3\x32\x4d\xf6\ +\x6b\x1e\xfa\x1c\x81\x76\x65\xca\x96\x17\x76\x83\x04\xc6\xa1\x1f\ +\xf3\x95\xa2\x42\x7e\xbc\xed\xa8\xbe\x3b\xa0\xa5\x5a\x41\xeb\xce\ +\x69\x92\xf0\x4e\x58\xca\xcd\xd9\x73\x9d\x1b\x4d\xf3\xc1\x6d\x0f\ +\x3a\x3f\xa8\x79\x48\xa0\x03\x5a\xca\x2f\xd8\x0b\xde\xdb\x0d\xe0\ +\xeb\x01\xe1\xff\x90\xe9\x6c\xa5\xa8\xdf\x03\x8c\xcd\xdb\xb3\xce\ +\x6c\x05\x38\x16\xf9\x49\xe3\x1e\xd2\x64\xb5\xa0\x5f\x0f\x56\x71\ +\x43\x89\x01\x80\xfe\x20\x6c\x3b\xfc\x7e\x99\x87\x84\x01\x40\x3c\ +\x08\x26\x36\x64\x40\xc8\xdd\x65\x0a\xe6\x21\x05\x00\x00\xb9\x39\ +\x7b\xd1\x64\xd7\x09\xeb\x84\x68\x19\xf7\xec\x90\xce\xd7\xa6\xf5\ +\x5e\x22\xf9\xda\x94\x0a\x00\x48\x10\x42\x8a\xe6\x21\x81\x6f\x81\ +\x9d\xd4\xb8\x42\xeb\x3c\xd0\xf5\xc7\x88\x60\x19\xf7\x3c\xba\x90\ +\x96\x79\x48\xb1\x03\x5a\xca\x96\xed\x7b\x98\x5d\x47\x3c\x1a\xeb\ +\x83\x4d\xf3\xf5\xa2\xde\x4d\xa9\x34\x60\x0f\x00\xc0\x7f\x21\x2c\ +\xa2\xc8\x47\xee\x0d\x19\x9b\x1e\x4d\xa4\x6d\x1e\x52\x1c\x81\x2f\ +\xc9\xb3\x81\xf8\x22\x38\xde\xe9\x0b\x5c\xd0\xcf\xee\x81\x95\x3a\ +\x80\x6c\xc9\x4e\xe1\x6c\x95\xb0\xa7\xb7\x0d\x99\x8d\x38\xb3\x95\ +\xb1\x79\x7b\x36\xbd\xca\x1a\x4a\x75\x04\xda\xcc\x3f\xd1\x67\x8a\ +\xcf\xbd\xf4\x72\x7d\x46\x7f\x48\xb2\xae\x76\xa5\x06\xa0\x69\x7e\ +\x05\x78\x72\xc0\x54\x9f\x1b\x1a\xaf\x15\xf4\x7e\x12\x75\x75\x2a\ +\x95\x11\xc8\x2f\xd8\xc9\x84\xcc\x03\x1c\x13\xb6\x9a\x29\xdb\x33\ +\x09\xe4\xea\x52\xe2\x00\xf2\x0b\x76\xd2\x7b\x5b\x25\xc0\xbc\xc1\ +\x96\x60\x2b\x20\xed\x31\x61\x2b\x69\x40\x48\x14\x40\x1c\xf3\xc0\ +\x7d\x27\x4d\x6e\x37\x9e\x2c\xfd\x2b\x20\xfe\x89\x34\x20\x24\x06\ +\x60\xb4\x6c\x27\xe2\x98\xc7\x74\xb1\x32\xa3\x9b\xf5\xa2\xde\x75\ +\xe8\x02\x31\x20\x64\x4b\x76\x6a\xb0\x6a\xff\xa7\x44\x2e\x82\xa3\ +\x65\x3b\x71\x08\x5b\x23\x86\xf9\x6a\x51\x6b\xed\x8b\xf9\xb2\xfd\ +\xc0\x63\xef\x00\x8f\x04\xe4\xf8\x0c\xaf\xf1\xea\xac\xfe\xd8\x4f\ +\xbd\xed\x1a\x18\x40\x5c\xf3\x86\x2e\xd5\x0a\x5a\xed\xb5\x99\x9b\ +\xb7\x97\xcc\xec\x1a\x7b\x08\x61\xa0\x11\x18\x2d\xdb\x09\x47\x78\ +\xdb\xef\x66\x1e\xa0\x32\xa3\x9b\x92\x2e\x12\x38\x0e\xb8\xc1\xc7\ +\xa1\xef\x0e\x68\x99\x17\x3c\x15\x10\x7e\xdf\x4b\x97\xeb\x33\x5a\ +\x09\xc9\xdd\xec\x84\x77\x88\x7e\x5d\x07\xe0\x53\xe7\x34\xbe\x3e\ +\xad\x3f\x85\xe4\xee\x54\x5f\x00\xc6\x4a\x76\x5c\xce\xd6\x02\xcd\ +\x6f\x7a\xe9\x52\xa8\xf9\x96\xf6\x0a\x42\xec\x11\xd8\x0b\xf3\xd0\ +\x18\x07\x4c\x17\x81\xfb\x01\xe1\x4f\x7a\x6f\xab\xf9\x05\x3b\x19\ +\xf7\x9c\x58\x1d\x30\x56\xb2\xe3\xae\x71\x6f\xff\x74\x40\x78\xdf\ +\xe6\xdb\x95\x9d\xb3\x33\xc8\xae\x11\xd8\x09\xdb\xe8\xcc\xad\x82\ +\xfe\x1c\x9a\x3f\xb8\x03\xe2\x9a\x97\x0f\x9f\xf9\xdd\x54\x2d\x6a\ +\xcd\xd0\x25\x02\x3b\xe1\x10\xb6\x36\x5a\xb6\x13\xa1\xf9\x83\x3a\ +\x20\xbb\x60\xdf\xc5\xdb\x1a\x31\xcc\x57\x66\xb5\x1c\x5a\x44\x88\ +\x32\x65\x1b\x17\xf6\x36\x09\x77\x42\x24\x80\xb8\xe6\x41\x53\xd5\ +\x82\x96\x02\x62\x63\x6b\x6c\xde\x5e\x76\x66\x6f\x11\x00\xc1\xe0\ +\x13\x8f\xc6\xa3\x20\xec\x0a\x60\x98\xcc\xb7\xd4\x84\xf0\x36\x74\ +\xbf\xf5\xd9\xa9\x10\x08\x3b\x5e\x03\x9a\xe6\x83\x67\x1e\xe9\x4a\ +\xda\xe6\x01\xea\x33\x5a\xf1\xd2\x25\x60\x33\x2a\x56\xf0\x94\xc3\ +\x56\xc7\x4a\x76\x7c\x97\x98\x6e\xb5\x99\xff\x66\xd4\x21\x06\x5b\ +\x92\xa6\xaa\x33\x5a\x8c\x8a\x4d\x52\x71\x3b\xc1\xbc\xce\xd4\x67\ +\xf5\x97\xce\xbd\x2e\x00\xf9\x37\xec\xdb\xfe\xb0\xdd\x02\xbe\x15\ +\x90\x78\x5f\xcc\xb7\x94\x2b\xd9\x59\x73\xf6\x16\x01\x10\x80\x8f\ +\xbd\xd3\x68\x7d\x5a\x7f\x6b\x5f\xec\x7e\x5b\xfc\xb0\xff\x31\x5f\ +\x01\xf3\x00\x95\x59\x2d\xcb\xeb\x32\x01\xe3\x00\x3c\x2d\xef\x7f\ +\xd2\xb9\xd8\xeb\xff\x05\x5e\x8a\xca\x64\xb0\x85\xd7\x95\xfd\x34\ +\xdf\x52\xe3\xeb\x56\x53\x04\x41\xd0\x99\xce\x95\x5e\x17\xc1\xed\ +\xdd\x52\xb4\xcc\xd7\x66\x75\x23\xb4\xc8\xb4\xd5\xb8\xf8\x46\x43\ +\x50\x0f\x6f\xdd\x00\x1a\x6f\x7f\xf5\x94\xc1\xd6\x21\x34\x3d\x4c\ +\xe6\x5b\xaa\x16\xb4\x84\x74\x85\x5d\x21\xd8\xf5\xce\x95\x2e\x00\ +\x66\xee\xaa\xc1\x5f\xbb\xd6\x9b\xe6\xd7\x0b\xea\x4a\x32\x2c\xaa\ +\xce\x68\x71\x47\x08\xc6\x87\x0f\xfd\xdb\x5d\xed\x5c\xee\x02\x50\ +\x2b\xe8\xb3\xed\xc3\xca\x81\xfd\x1c\xf8\x08\xf8\x18\x78\xd3\x99\ +\x5e\x18\x66\xf3\x2d\x55\x67\xb4\xe8\xa5\x3c\xc6\x02\xf0\x77\xe0\ +\x23\x64\xbf\x78\x68\x5b\xd9\xf7\x5e\xd5\x27\xfb\x5d\xdf\x81\x0e\ +\x74\xa0\xe1\xd2\x7f\x00\x72\xd2\x49\x30\x2e\xe9\xad\x3a\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\x58\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x0a\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4b\x88\x5c\x45\x18\x85\xcf\xa9\x19\x34\x41\xa2\xa0\x21\x1b\ +\x09\xee\x7c\xac\x04\x13\x7b\xda\xb8\x30\x06\x13\x99\x80\x26\xdd\ +\x1d\x06\x17\x82\xe0\x83\x08\xae\x14\x09\x24\x88\x1a\x4c\x40\x11\ +\x5c\x28\xf8\x42\xd1\x85\x28\x8a\xdd\xf3\x40\x26\x32\x41\x1c\x10\ +\x64\x7a\x9a\x11\xb2\x10\x41\x5c\x04\x11\x41\x83\x09\x11\x25\x0d\ +\xe9\x5b\xc7\x45\xcf\xa8\xdc\x2a\x35\x9d\x54\x55\x17\xd8\xdf\xf2\ +\x2e\xea\xfc\xff\xb9\x55\x7f\xd5\x7f\x1f\xc0\x88\x11\x23\xfe\xcf\ +\x30\xd4\x40\x95\xa6\x9e\x35\xb4\x4f\x89\x94\x2c\x8f\x2c\x37\x78\ +\x38\xd4\xd8\x31\x09\x66\xc0\x44\xb3\x28\x40\x9a\xd5\x51\x45\x70\ +\xc7\x52\x8d\x8b\xa1\xc6\x8f\x85\x09\x36\xd2\x5a\xf2\x00\x20\x50\ +\xd2\xdc\xc4\xb4\xb6\x04\x1b\x3f\x12\xc1\x0c\x10\x60\x4b\x97\x36\ +\x40\xfa\x74\xeb\xac\x6e\x08\xa5\x11\x83\x60\x06\x10\x90\xe7\xf2\ +\xc6\xb1\x42\xc7\x6f\x9d\xd1\xe6\x50\x3a\xa1\x09\xb7\x04\xfe\x99\ +\xcd\xc6\x6a\x61\xcb\x9c\x36\x26\xd0\x1a\x98\x14\x06\x00\xc0\x8d\ +\xe3\x85\x8e\xdd\x3e\xab\x0d\x89\xf4\x2e\x98\x68\x06\xa8\xbc\x24\ +\x84\xad\xbd\x42\x33\x93\xf3\xba\x3c\x96\xe6\xc5\x10\xcd\x00\x02\ +\x16\x74\xea\xc2\x8e\xd3\x5d\xbd\xbf\xfd\x73\x8d\xc7\xd2\x1d\x94\ +\xb8\x4b\x40\xb0\x70\x8b\x63\xbd\x7b\xda\xbe\x0e\x29\xd8\x19\xe4\ +\x52\x48\x51\x03\x9c\x99\x20\xf2\xa1\x6a\xcb\x3e\x9f\x40\xfb\x3f\ +\x49\x53\x04\x05\xab\x72\x49\x20\x0f\x54\xa6\x75\x20\x89\xfe\xbf\ +\x90\x6a\x17\x00\x69\x0a\xe7\x9a\xf4\x42\xb5\xa9\x87\x53\xc5\xe0\ +\x23\x99\x01\x90\x7c\xa7\x45\x88\x7a\xa3\xda\x52\x3d\x59\x1c\x25\ +\xd2\x19\x80\xfe\x69\xd1\x63\x82\x11\xf4\x41\xf5\x63\xdd\x95\x32\ +\x96\x3f\xc5\x53\x0b\x12\xd0\xea\xee\xf0\x77\x2e\x13\x35\x73\xdb\ +\xb4\x2a\xa9\xe3\x49\x6e\x00\x00\x80\x9e\x99\x40\x5c\x61\xa5\xf9\ +\x6a\x4b\x37\xa5\x0c\x65\x38\x06\x60\xad\x79\x62\x79\x26\x5c\x23\ +\xe8\xf8\xb6\xa6\xae\x4b\x15\xc7\xd0\x0c\xe8\x23\x9f\x09\xd7\x16\ +\xd4\xc2\xb6\x96\x36\xa5\x88\x60\xc8\x06\x00\x7d\x13\x54\x3e\x2d\ +\x5e\x5f\x40\xc7\x26\xe6\x75\x65\x6c\xf5\x0c\x0c\x00\x00\x5a\xa7\ +\x79\x02\x6e\x51\x57\x73\xdb\xdf\xd1\xba\x98\xca\x99\x18\xb0\xda\ +\x3c\x95\x4c\x20\x70\xc7\xb9\xab\xf4\x61\xcc\xe6\x29\x1b\x03\x56\ +\xf1\x35\x4f\xf7\x76\xcf\xd8\xb7\xf0\x8c\xa2\xc4\x9a\x9b\x01\x80\ +\xaf\x79\x02\x1f\xa8\xdc\x6c\x5f\x8c\xd1\x41\xe6\x68\x40\xbf\x8d\ +\x2e\xd5\x45\x82\x4f\x54\x5a\x38\x18\x5a\x2a\x4f\x03\x00\x80\x74\ +\x9b\x27\xea\x68\xa5\xa9\xfd\x21\x65\xf2\x35\x00\x80\x04\x5b\xae\ +\x08\xa4\x5e\x9b\x68\x6a\x5f\x28\x8d\xac\x0d\xa0\xef\xc8\x0c\x10\ +\xd4\x2b\xa1\x34\xb2\x36\x00\x00\xe8\x2f\x7b\xc1\xb6\xc5\xbc\x0d\ +\xe8\x67\xef\xc4\x28\xe8\xed\x50\x12\xd9\x3c\x9d\xf5\x22\x8d\xb9\ +\xd7\xf8\xd8\x72\xc3\xbc\x1a\x4a\x22\xe3\x19\xe0\x4d\xfe\xe9\x76\ +\x83\xc1\x92\x07\x72\x34\x80\x80\x08\xe3\xbe\xb9\xd7\xcb\xed\x3a\ +\x8e\x84\x96\xcb\xce\x00\x09\x86\x2a\x67\xaf\xf7\xda\x27\xcc\xe3\ +\x20\x7d\x2f\x60\x2f\x89\xbc\x0c\x20\x0c\x4b\xb7\x9e\xc0\x27\xbd\ +\x53\xe6\x41\x1c\x76\x9e\x1b\x04\x21\x27\x03\x0c\x9c\x3b\x8f\x2f\ +\xd8\xe3\xd4\xca\x7e\x9e\x8f\x25\x9a\xc9\x2e\x20\xe3\xd9\xf1\x4f\ +\xf4\x7a\xbc\x67\x65\x8a\xe7\x62\x2a\x0f\xdd\x00\x81\x2c\x4f\x7b\ +\x08\xdf\x61\x9c\x77\xaf\xd4\x79\x36\xb6\xfe\x50\x97\x40\x3f\x79\ +\xa7\xcf\xff\x91\x86\x3b\xdb\x7b\xf8\x53\x8a\x18\x86\x67\x80\xe0\ +\x4b\xfe\x8c\xb5\xdc\xb5\x54\xe3\xc9\x54\x61\x0c\xc5\x00\x09\x04\ +\x4b\xda\xc2\xef\x10\x77\x77\xf6\xf1\xeb\x94\xb1\x24\xaf\x01\x02\ +\xc8\x72\xf2\xc0\x79\x18\xd6\xdb\x35\x2e\xa5\x8e\x27\xe9\x0c\x90\ +\x40\xca\xd1\x14\xc9\xfb\xdb\x35\x2e\xa4\x8c\x65\x8d\x74\x33\x80\ +\x84\x67\xcd\x03\xe4\xa3\x4b\x35\x7e\x94\x2c\x8e\x12\xc9\x66\x80\ +\x64\xdd\xe6\x86\x3c\xd4\xae\xf1\xcd\x54\x31\xf8\x48\x63\x00\x61\ +\xe8\x6c\xf5\x7a\xa9\xbd\x17\x43\xff\x4c\x26\x85\x01\xee\x11\x57\ +\x7a\x77\xb9\x66\x9e\x8c\xd1\xdc\x0c\x4a\x5c\x03\xfa\xd5\xbe\x7c\ +\xc4\x9d\x5d\x7f\xb5\x79\x24\x87\xe4\x81\xb8\x1f\x4a\xfa\x9a\x9b\ +\xc5\xf5\x67\x79\xdf\xe2\x9d\xec\xc5\xd2\x1d\x94\x68\xbb\x80\x73\ +\xbe\x07\xbe\xc2\x3a\xee\x59\xac\xb3\x1b\x4b\xf3\x62\x48\xb5\x0b\ +\x7c\x3b\x06\x4e\xb6\x77\xf3\xd7\x44\x7a\x17\x4c\x0a\x03\x7e\xe8\ +\xf5\xb8\xf3\xcb\x3a\x7f\x4e\xa0\x35\x30\x21\x7f\x98\xf0\x3d\xc1\ +\xff\x85\xe0\xae\x95\x29\x7e\x1f\x4a\x27\x34\xc1\x6a\x00\x5d\x33\ +\x7f\xb3\xe2\x64\xa7\xc1\x6f\x42\x69\xc4\x20\xe4\x12\xf8\xeb\x99\ +\x1d\x21\x4b\xee\xed\x34\xd8\x09\x38\x7e\x14\x42\xfe\x34\x75\x14\ +\x40\x01\xa0\x80\xf8\x5c\xa7\xc6\xcf\x82\x8d\x3d\x62\xc4\x88\x11\ +\x91\xf8\x03\x6e\xfe\x4e\x7e\xe0\xc6\x25\x53\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xcd\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x7f\x49\x44\x41\x54\x78\x9c\xed\ +\xd9\x51\x0d\x80\x30\x10\x05\xc1\x03\x6f\x55\x80\x05\xd4\x62\xaa\ +\xc8\x58\x12\x66\x0c\xdc\xcb\xa6\x7f\x9d\x09\xad\xeb\xde\xeb\xba\ +\x77\xb9\xe1\x2c\x8f\x7f\x81\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\ +\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\ +\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\ +\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\xda\xef\ +\x03\x1c\xe5\xf1\xfa\x6b\x7c\xa6\x7e\x01\x7b\x9e\xf4\x3e\x00\x00\ +\x00\x00\x00\x00\x00\xfc\xc3\x0b\xb7\x26\x07\xfa\x17\x1e\x2a\x64\ +\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x8f\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\x41\x49\x44\x41\x54\x58\x85\xed\ +\x97\x31\x6b\x14\x51\x14\x85\xbf\x33\x59\xab\x80\x85\x62\x20\x76\ +\xf9\x03\x62\xb5\xbb\xa2\x88\x82\x5d\x42\x8a\x24\xf8\x07\x02\x6a\ +\x95\xca\x24\x65\x08\xa9\x56\xb0\x30\x60\x50\x41\x41\xd2\x04\xc1\ +\x2d\x82\x0b\x76\x01\x41\xb2\xbb\x95\xf8\x07\x92\x3a\x41\xc1\x22\ +\x95\xc9\x1c\x8b\x9d\xb7\xac\x9b\xd9\xec\x4e\x76\xb4\xd1\xaf\x7a\ +\xdc\x77\x67\xee\x99\x73\xdf\xcc\xbc\x07\xff\x3a\xea\x0e\x94\xdf\ +\xfb\x66\x8c\x97\x11\x65\xc1\x95\x3c\x8a\x18\x0e\x31\xf5\x08\x55\ +\xea\xb3\xfa\xdc\x53\x40\xa9\xea\xc7\xe0\x27\x69\xc2\x72\x22\xc6\ +\x5a\x6a\xcc\xea\xe9\x29\x01\xa5\xaa\x6f\x81\x3f\x01\x3f\xb0\x16\ +\xa2\x13\x6a\xbb\xf7\xf5\x3d\x8f\xaa\x37\xde\xf9\x52\x3c\xc2\x24\ +\xf2\x3a\x70\x51\xd6\xed\xe0\x44\x21\x24\xd9\x5e\x92\x10\xd6\x42\ +\x63\x56\x9b\x79\x14\x0e\x24\x0f\xb2\x59\xac\x5a\xc2\x6f\x63\xbc\ +\x0c\x4c\x03\x44\xed\x2c\x51\x06\x88\x4e\xa8\xe5\x59\xbc\x8b\x1a\ +\x80\x44\x29\x04\xda\x02\xc2\x82\xcb\xcb\xf6\x34\x9a\x33\xfa\x96\ +\x0c\xc7\x42\xac\xd0\x23\xf7\xdc\x14\xab\x9e\x12\x7e\x05\x60\xf4\ +\xa0\x39\xa3\x0f\x67\xe5\xe7\x2a\xa0\xb8\xed\x09\xfd\xf4\x16\x62\ +\x14\x20\x11\x72\xf5\xac\x6b\xa2\xb3\x26\x33\xb1\xe2\x48\xc7\x7e\ +\x13\x8a\x0f\x4a\x6e\x02\x4a\xd7\x78\x04\xdc\xe9\x8c\x49\x5a\xfb\ +\x2b\x02\x8a\xdb\x9e\x48\x3e\x60\x9d\xec\xd4\xbf\xf0\xf2\xcf\x0b\ +\x48\xb3\xde\x1c\xb9\xa0\x79\x56\x15\xf7\xbb\xbc\xef\x22\xec\xb7\ +\xaa\x53\xad\x8f\xb4\xd8\x98\xd6\xde\x20\xfa\xfb\x3a\x90\x14\x1f\ +\x07\xc6\x65\x6f\xb5\xec\x4e\xc4\x0d\x61\x7d\x20\xdb\x6b\x28\x46\ +\x75\xec\xd7\xac\xf8\x1e\x40\xaa\xf5\x17\x06\xb3\x7e\x60\x01\x92\ +\xd6\x6c\x6f\x74\x84\xee\x96\xaf\xf3\xd0\x31\x62\x08\xeb\x03\x7d\ +\x5b\x90\xd8\xb9\xd3\x19\xb3\xbd\x81\xfc\xbc\x2b\x35\x93\xf5\x03\ +\x0b\x60\x55\xb1\x0b\x9a\xc7\x1c\xf5\xcc\xc9\xb0\xea\xb3\x0b\x00\ +\x9a\xd3\xda\x03\x2d\xf5\x9a\x57\xa4\xc5\x66\x46\xeb\x33\x09\x00\ +\x68\x7c\xe5\x05\x5d\xad\x48\x38\x97\xf5\x99\x05\xa4\xb6\x62\x08\ +\xeb\xb3\x0b\xa0\xd5\x8a\x48\x9a\x03\xf6\x81\xfd\x48\x9a\x3b\xaf\ +\xf5\x81\xcc\xbf\xe3\xdd\x19\x7d\x04\x26\xfa\x26\x0e\x48\xdb\x01\ +\xc3\x21\xb4\x36\x90\x79\xdd\xbc\x9b\x62\xd5\x97\x93\xe1\xc1\x29\ +\x01\x98\x3a\x40\x3c\xc2\xe4\x9f\x12\x00\xad\x7b\xdb\x34\x42\xa0\ +\xdd\x82\x08\x55\x8c\xa7\x90\xd7\x8b\x55\x0b\xa8\x75\xec\xe1\x86\ +\x22\x79\xf2\x49\xe1\x67\x40\x1c\xa1\x4a\x98\x4b\x3b\x98\x54\xc8\ +\x73\xa7\xf4\x3b\xbd\x0f\x26\x81\x70\x34\x4b\xb6\xce\x63\xdd\xf3\ +\xe7\xe4\xc0\xa6\x91\x76\x34\xfb\xcf\x2f\xa6\x4e\xeb\xad\xb9\x6d\ +\xcb\x1e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x8b\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3d\x49\x44\x41\x54\x58\x85\xed\ +\xd3\x21\x12\x00\x10\x00\x05\xd1\xe5\x52\xaa\xe2\x00\x2e\xea\x04\ +\x66\x64\x97\x32\x92\x2a\x52\xf6\xa5\xdf\x36\x7d\x90\x24\x7d\x16\ +\xce\x48\x6d\x0d\x20\x3f\xaa\xf6\x59\x63\x01\x88\x4f\x82\xd2\x85\ +\x2f\x90\x24\xe9\xbb\x0d\xbb\x58\x0a\x07\x83\x32\x65\x0f\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x26\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xd8\x49\x44\x41\x54\x78\x9c\xed\ +\xd2\xb1\x4d\xc3\x50\x18\x46\xd1\x1f\x86\xf0\x26\x2c\x92\x15\x52\ +\x20\x1a\x86\xa1\x89\xb2\x44\x16\x61\x8b\x54\x6c\x61\x0a\x2c\xa5\ +\x88\x68\x7d\x22\xe5\x1e\xc9\xd2\x73\xf5\x3e\x5f\x79\x26\xc9\x33\ +\x7b\x51\x17\xbf\xbd\x7f\x1d\x66\xe6\xb4\xbd\x7e\x7c\x9f\x3f\x2f\ +\x62\xc7\xab\xb8\x74\x73\x5a\x67\x96\x75\x66\x99\x5b\x88\xdd\xb1\ +\x00\xdb\x87\xdf\x9d\xf7\x26\xff\x80\x87\x50\x00\x3d\x40\x2b\x80\ +\x1e\xa0\x15\x40\x0f\xd0\x0a\xa0\x07\x68\x05\xd0\x03\xb4\x02\xe8\ +\x01\x5a\x01\xf4\x00\xad\x00\x7a\x80\x56\x00\x3d\x40\x2b\x80\x1e\ +\xa0\x15\x40\x0f\xd0\x0a\xa0\x07\x68\x05\xd0\x03\xb4\x02\xe8\x01\ +\x5a\x01\xf4\x00\xad\x00\x7a\x80\x56\x00\x3d\x40\x2b\x80\x1e\xa0\ +\x15\x40\x0f\xd0\x0a\xa0\x07\x68\x05\xd0\x03\xb4\x02\xe8\x01\x5a\ +\x01\xf4\x00\xad\x00\x7a\x80\x56\x00\x3d\x40\x93\x01\x7e\xfe\x39\ +\xef\x0a\x06\x58\x8f\x33\x73\xfd\x7b\xd6\xa3\xdb\x91\xe4\x99\xfd\ +\x02\xc9\x6e\x11\x4a\x9d\x22\x1c\x0a\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x03\x5c\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x0e\x49\x44\x41\x54\x78\x9c\xed\ +\xd5\x4b\x6c\x54\x75\x14\xc7\xf1\xef\xb9\x53\xa6\xda\x81\xd0\xd0\ +\x98\x50\x4d\x4a\x64\x63\x52\x36\xc0\x4c\xc7\x47\xa2\xa9\xcf\xa4\ +\x16\x24\x2c\x70\x41\x04\x4b\x02\x33\x03\xed\x80\x62\xe2\xc2\xc4\ +\x4c\xba\x33\xf1\x51\x3b\x03\xa5\x0f\x89\x04\x16\x18\x0a\x29\x31\ +\x60\xdd\x98\x58\x92\x52\x18\xda\x59\xb2\x00\xa2\x1b\x83\x84\xd0\ +\x0a\x49\x83\x9d\xda\xce\x71\x51\xa3\xd3\x6b\x25\xd8\x7b\x67\xba\ +\xe0\x7c\x96\xff\x73\xef\x6f\x7e\xf7\xcc\x0b\x8c\x31\xc6\x18\x63\ +\x8c\x31\xc6\x18\x63\x8c\x31\xc6\x18\xf3\xa8\x10\xaf\x01\xcf\xc6\ +\xd3\xf5\xb3\xca\x71\x84\xa7\x50\xbe\x18\xed\x4d\x7e\x06\xa2\x7e\ +\x94\x5b\x48\x34\xd1\xb9\xb5\xa0\xf2\x29\x00\x05\x49\x8e\xf6\x25\ +\x07\xbd\xe4\x79\x5e\x40\x24\x9e\x19\x02\x7d\xe9\xef\x03\xe5\xc4\ +\xfd\xdf\xc6\x77\x5f\xed\x6f\x9f\xf6\x9a\x3d\x9f\x4a\x38\x9e\xf9\ +\x50\xe0\x93\xa2\xc3\x7b\xaa\x95\x4f\x8c\xf5\xc6\xff\x58\x6c\xaa\ +\xe3\x43\xb1\xf9\x19\xc2\x8e\xaa\x55\x35\xdf\xaf\x6f\xe9\xa8\xf6\ +\x9e\x3d\xa7\x31\x95\xaa\x88\xc4\xd3\x5d\xae\x87\x9f\x7b\x35\x8f\ +\xbc\x2f\x40\x74\xaf\xc0\x6d\xd7\xe9\xcb\x81\xca\xc0\xf0\x86\xd6\ +\x43\x6b\xbc\xc6\xd7\xef\x3b\xbc\x7c\xf2\x56\xcd\x59\x90\x84\x6b\ +\x94\x17\x78\xc7\xcb\xbb\x0f\x3e\x6c\x10\x20\xba\x3b\xf3\x74\x21\ +\xa0\x83\xc0\x33\xae\xd1\x2d\x55\xa7\x79\xac\xb7\x2d\xb7\x98\xdc\ +\x70\xac\xa3\x56\x24\x70\x0e\xd8\xe8\x1a\x4d\x20\xf2\xd6\x68\x77\ +\x72\x78\x31\xb9\xc5\x7c\xf8\x0a\x40\xf6\xab\xe4\xcf\xcb\x66\x66\ +\x5e\x00\xb9\xe0\x1a\xad\x16\x29\x5c\x08\xc7\xd2\xcd\xff\x37\xb3\ +\x61\xcf\xa1\x75\x22\x81\x4b\xfc\xeb\xe1\xe5\x27\xa7\xe0\x3c\xef\ +\xc7\xc3\x83\x4f\x0b\x00\x18\x39\x7a\x70\xe2\x6e\x50\xdf\x00\x4e\ +\xba\x46\x21\x11\xbe\x0d\xc7\xd2\x7b\x1f\x36\x6b\x63\x22\xf3\x8a\ +\x3a\x85\x61\xa0\x6e\xfe\x44\x2e\xcf\x4e\xeb\x73\xd9\xbe\xb6\x6b\ +\x9e\x0b\xff\x25\xe0\x57\x10\xc0\x44\x76\x70\xf6\xe6\xa6\xe8\x40\ +\xed\x64\x28\x28\xf0\x62\xd1\x48\x44\x68\x7e\x32\xd2\x14\xba\xb9\ +\x29\xfa\x03\x43\x43\xff\xf9\x37\x19\x89\xa7\x77\x0a\x9c\x02\xaa\ +\x8a\xcf\x15\x19\x40\x83\x5b\x72\x47\x5b\xef\xf9\xd9\xd9\x97\xdf\ +\x80\x85\x44\x62\x9d\x31\x44\xba\x70\x2d\x59\xe1\xd4\x8a\xfc\x8a\ +\x77\x7f\x3c\xb6\x6b\x6a\xfe\x1d\x2a\x0d\xf1\xcc\xc7\x0a\xed\xee\ +\x2c\x45\x3b\xd7\x4e\xd4\x7e\xd0\xdf\xff\xf6\xac\xdf\x3d\x4b\xb6\ +\x00\x80\xc8\x9e\x4c\x13\x8e\xf6\x03\x21\xd7\x68\xd8\xa9\x70\xb6\ +\x64\x0f\xb7\x8d\x03\xd4\x6f\x4b\x05\x1f\x5f\x55\xd3\x23\xd0\xe2\ +\xba\x4e\x05\x79\xff\x4a\x4f\xb2\xb3\x54\x1d\x4b\xba\x00\x80\x48\ +\x22\xbd\x01\xe5\x3c\x50\x5b\x7c\xae\x70\x1d\xa5\x09\x2a\xef\x88\ +\x93\x3f\x8d\xf2\x9a\xeb\xd6\x29\x47\x74\x7b\xb6\xfb\xc0\x40\x29\ +\xfb\x95\x7c\x01\x00\xe1\xd8\x97\x75\x22\xce\x77\xc0\xba\x87\xbc\ +\xe5\x4e\xc1\x61\x73\xee\xc8\xfe\x4b\xa5\xec\x05\x65\x5a\x00\x40\ +\x38\xd6\xb3\x52\x24\x7f\x06\x78\xf5\x41\xd7\x29\x5c\xd7\x40\xe0\ +\xcd\x5c\x57\xeb\x8d\x72\xf4\xf2\xf5\x5f\xe0\x41\x7e\x1d\x3b\x97\ +\xaf\x5e\x1b\xfd\x26\x58\x15\xaa\x03\xd6\x2f\x78\x91\x70\x11\x9d\ +\x7e\x3d\xd7\xfd\xde\x2f\xe5\xea\x55\xb6\x4f\xc0\x3f\x54\x22\x89\ +\x74\x0a\x95\x94\x6b\x70\x7a\x59\xd5\xcc\xce\x91\x8e\x83\xbf\x97\ +\xb3\xcd\x12\x2c\x60\x4e\x43\x22\xdd\xa7\xca\x2e\x40\x81\xcf\x47\ +\x57\x8f\x7f\x44\x7b\x7b\x61\xa9\xfa\x2c\x89\xc6\x54\xaa\xa2\xb1\ +\xe5\xeb\xc7\x96\xba\x87\x31\xc6\x18\x63\x8c\x31\xc6\x18\x63\x8c\ +\x31\xc6\x18\xf3\x88\xf8\x13\xba\x50\xdf\xc1\x6b\x55\xb9\xde\x00\ +\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xc4\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x76\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\xc1\x0d\x82\x40\x14\x04\xd0\x59\x8b\x30\x36\x62\x23\xb6\xc0\ +\xc1\x70\xb2\x17\x2f\x84\x46\xa8\x82\x42\x88\x4d\xac\x57\x43\xf6\ +\x0a\x24\xf2\xde\x71\xf2\x0f\xf3\x27\x01\x00\x00\x00\x00\x00\x00\ +\xce\xa0\xac\x83\xfb\xf3\xfd\x48\x32\xd4\xe4\x7a\x40\x9f\x2d\x2d\ +\x49\xed\xe6\xf1\x35\xfd\x86\x97\xc6\xe1\x3f\x3e\x9f\x24\xb7\xa4\ +\x0c\xeb\xb0\x35\xc0\xa9\xb4\x06\xe8\x4b\xf2\xd9\xbd\xc9\xf6\x96\ +\xa4\xf6\x47\x97\x00\x00\x00\x00\x00\x00\x00\x00\xf6\xf7\x05\x16\ +\xa6\x0e\x08\x70\x11\x84\x99\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ +\x42\x60\x82\ +\x00\x00\x00\xd6\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x88\x49\x44\x41\x54\x78\x9c\xed\ +\xd7\xb1\x0d\xc2\x40\x10\x04\xc0\x7d\x8a\x40\x14\x44\x05\x88\x0e\ +\x20\x71\x45\x4e\x68\x81\x94\xc4\x0d\x59\x34\xf1\xa4\xc8\x2f\x42\ +\xeb\x91\x3d\x13\xae\x2e\xd8\xbb\xec\x12\x00\x00\x00\x00\x00\xf6\ +\xa3\x2c\x83\xf3\xf5\x7e\x29\x35\x63\x92\x63\x87\x3e\xab\x29\xc9\ +\x5c\x93\xdb\xf4\x7c\xbc\xbe\xf3\x43\x33\xb8\xc1\xe5\x93\xa4\x26\ +\xa7\x24\xe3\x32\x6f\x0e\xb0\x37\xcd\x01\x6a\xc9\x90\xe4\xdd\xa1\ +\xcb\xaa\x4a\x32\x27\x19\x7a\xf7\x00\x00\xfe\x87\x5f\xa0\x19\xdc\ +\xe0\xf2\x89\x5f\xe0\x27\xbf\x00\x00\x00\x00\x00\x00\x00\x3b\xf1\ +\x01\xd7\x53\x1e\x0f\x14\xfc\xaf\x10\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x02\xc4\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\x76\x49\x44\x41\x54\x78\x9c\xed\ +\x9a\x3d\x6f\xd3\x40\x1c\x87\x9f\x4b\xa8\xca\x02\x4b\x78\x59\x6a\ +\xe7\xfc\x39\xf8\x12\x2c\x54\x0d\x2d\xac\x74\x60\x65\x63\xe5\x1b\ +\x80\xc4\xca\x4b\x0b\x82\x01\xf1\x3d\xbc\x31\x66\x70\xed\x66\x43\ +\x48\x48\x2c\xa8\x52\x7b\x2c\x11\x32\x87\x9d\x36\xf6\xdd\xf9\xce\ +\xf1\x6f\xb3\xfd\xcf\x4f\xf7\x3c\x8a\x9d\xe8\x64\x18\x32\x64\xc8\ +\x26\x47\x74\xbd\x00\xdb\xc9\x8a\xe2\xbe\x50\xe2\x05\xf0\x73\x3c\ +\xe2\x30\x8a\xa2\x6f\xe5\xeb\xd7\x3a\x5a\x97\x93\x64\x45\xb1\x27\ +\x94\x38\x02\x46\x00\xe7\x17\xbc\x06\xee\x95\x67\x46\x5d\x2c\xcc\ +\x45\x74\xf8\x65\x6e\xea\x73\xbd\x14\x50\x03\x7f\xae\x84\x7a\xae\ +\xcf\xf6\xee\x16\xa8\x83\x17\x88\x99\x8c\xa3\xaf\xfa\x7c\xaf\x1e\ +\x82\xab\xe0\xa7\xd3\x9d\xcf\x55\x9f\xe9\x8d\x80\x26\xf0\xd0\x13\ +\x01\x4d\xe1\xa1\x07\x02\xda\xc0\x43\xe0\x02\xda\xc2\x43\xc0\x02\ +\x4c\xc0\x43\xa0\x02\x4c\xc1\x43\x80\x02\x4c\xc2\x43\x60\x02\x4c\ +\xc3\x43\x40\x02\x6c\xc0\x43\x20\x02\x6c\xc1\x43\x00\x02\x6c\xc2\ +\x83\xe7\x02\x6c\xc3\x83\xc7\x02\x5c\xc0\x83\xa7\x02\x5c\xc1\x83\ +\x87\x02\x4c\xc3\xe7\xf9\xe2\x81\x52\xea\xd5\xf2\xf0\x89\x94\xd1\ +\x97\xf2\x75\xaf\x04\x98\x86\xff\xaf\x4f\xf1\x5d\xca\xe8\x4e\x79\ +\xc6\x9b\x2d\x31\xeb\xf0\x35\xf1\x42\x80\x23\xf8\x0b\x21\xc4\x53\ +\x7d\xb6\x73\x01\xae\xe0\x51\x3c\x9e\x4e\x77\x3e\xe9\xf3\x9d\x3e\ +\x03\x5c\xc2\x4b\x19\x1d\x55\x7d\xa6\x33\x01\x3e\xc0\x43\x47\x02\ +\x7c\x81\x87\x0e\x04\xf8\x04\x0f\x8e\x05\xf8\x06\x0f\x0e\x05\xf8\ +\x08\x0f\x8e\x04\x38\x84\x7f\x24\x65\x74\xbc\x4e\x97\x75\x01\x3e\ +\xc3\x83\x65\x01\xbe\xc3\x83\x45\x01\x21\xc0\x83\x25\x01\xa1\xc0\ +\x83\x05\x01\x21\xc1\x83\x61\x01\xa1\xc1\x83\x41\x01\x21\xc2\x83\ +\x21\x01\xa1\xc2\x83\x01\x01\xae\xe0\x95\x50\x07\x49\x1c\x7f\x58\ +\xb7\x2f\xcf\x17\xbb\x4a\xa9\x97\xcb\x43\xb3\x7b\x82\xfe\xc3\x9f\ +\x1e\x28\x78\xf3\xb7\xcf\xe4\x9e\x60\x70\xf0\x35\x69\x24\xc0\x77\ +\xf8\x93\x93\xd3\xfd\x0a\x78\x33\x7b\x82\x21\xc0\x23\x78\xab\xf7\ +\x19\xd9\x13\x0c\x19\xbe\xf5\x9e\x60\x00\xf0\x0f\x11\xbc\xd3\xfb\ +\x2e\xfb\xe9\xbc\x92\x80\xbe\xc2\xc3\x15\x04\x38\x84\xdf\x4f\xe2\ +\xf8\xe3\xba\x7d\x6d\xe0\xe1\x12\x01\x7d\x87\x87\x15\x02\x7c\x87\ +\xcf\x8a\x62\x26\x94\x78\x5f\xd1\xb7\xd6\x6d\x54\x29\x60\x53\xe0\ +\x01\xc6\xfa\x89\x3c\x5f\xec\x02\xc7\x18\x82\xaf\xe9\x6b\x0c\xbf\ +\xa2\xaf\xd1\x03\xf4\x9f\x6f\x40\x9a\xa6\x5b\xb7\x6e\xdf\xfd\x01\ +\xdc\x28\x9d\x6e\x0c\x5f\xd3\xd7\x18\xde\x74\x1f\x68\xff\x04\x27\ +\x93\xc9\x18\xd8\x2e\x9d\x6a\xf5\x5a\x4a\x45\x5f\xab\xc5\x9a\xee\ +\x03\x4d\x40\x92\x24\xbf\x05\x3c\x03\xce\x80\x5f\x02\xb1\xd7\xe6\ +\x9d\x9c\x8a\xbe\x59\x9b\xc5\x9a\xee\xab\xcd\x7c\x3e\xdf\x4e\xd3\ +\x74\xcb\xd7\xbe\x2c\xcb\xae\x9b\xec\x1b\x32\x64\x83\xf3\x07\x17\ +\xa8\x1d\x6f\x59\x60\x0c\x9b\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ +\x42\x60\x82\ +\x00\x00\x0a\xf4\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x0a\xa6\x49\x44\x41\x54\x78\x9c\xed\ +\x5b\x7b\x70\x54\xd5\x19\xff\x7d\xf7\xee\x6e\x60\x93\x08\x64\x11\ +\x83\xd2\x91\xd8\x96\xd1\x58\x98\x21\xbb\x0b\x52\x35\x22\xda\xd1\ +\x5a\xc5\x07\xae\xf5\x31\x28\x51\xd8\x4d\x80\x2c\xc2\x54\x5b\x9d\ +\xa9\x4b\xac\x76\xb4\x6a\x08\xbb\x60\xdc\x08\x18\x41\xa6\xad\x99\ +\x51\xa7\x3a\x8a\x4c\xb5\xa1\xd4\x22\x64\x03\x96\xfa\xc0\xf1\x11\ +\x1f\x34\x90\x4a\xc2\x23\x12\xb2\xd9\xdd\xf3\xf5\x8f\x20\xdc\x7b\ +\xf7\xee\xbd\x77\x93\x5d\xa6\xd3\xf2\xfb\x6f\xbf\xf3\x3b\xdf\xf9\ +\x9d\xef\x9e\x3d\xf7\x3c\xbe\x0b\x9c\xc6\x69\x9c\xc6\xff\x33\xe8\ +\x54\x34\x32\xb5\x2a\x7c\xa6\x5c\x40\x95\x80\x98\x0c\xa6\xf3\x41\ +\x38\x8f\x19\xa3\x09\x38\x03\x80\x0c\xd0\x11\x00\x47\xc0\xfc\x15\ +\x08\x1f\x01\xf8\x50\x4a\xd1\xd6\x1d\x6b\x6a\x3b\xf2\xad\x2d\x6f\ +\x01\x70\xfb\xc3\xdf\x97\x08\xf3\x98\x31\x1b\x84\x29\x43\x74\xd3\ +\xc1\xe0\x37\x24\xc1\xcd\x6d\xcf\x2e\x89\x01\xc4\x39\x15\x89\x9c\ +\x07\x80\xc9\x1b\x08\x5f\xc5\xa0\xfb\x01\x5c\x9e\x5b\xdf\x78\x9f\ +\x40\xf5\x82\x1d\x2f\xb4\x37\x05\x12\xb9\x72\x9a\xb3\x00\xb8\xfd\ +\x2b\x2f\x27\xa2\xdf\x01\xf0\xe4\xca\xa7\x1e\x18\xf8\x02\xcc\xcb\ +\xdb\x9b\x82\xeb\x73\x31\x22\x86\x1d\x80\xe9\xf3\x1b\xce\x4a\xca\ +\xd2\x53\x04\xdc\x61\x40\x13\x04\xbc\x03\xe2\x56\x21\xa4\x3d\x40\ +\xea\x33\x1b\x51\x8f\x90\x6d\xbd\xc9\x63\xa9\x94\x3c\x22\x59\x0c\ +\xb6\x8d\x22\x46\x99\x60\x9a\x44\xe0\x19\x20\xfc\x04\xc0\x48\x03\ +\xe1\x5b\x21\xa4\x9a\xb6\x67\x17\x7f\x30\x1c\xfd\xc3\x0a\x80\xa7\ +\x3a\x3c\x0d\x8c\x57\x00\x8c\xd7\x29\xee\x05\xf0\x3a\x11\x5e\x25\ +\x59\xda\xb4\x63\xf5\xe2\xee\x6c\x7c\xcf\x58\x5a\x3f\x72\xe0\xa8\ +\x6d\x16\x01\xd7\x81\x30\x3b\x43\x1b\xfd\x00\xee\x8e\x45\x83\xbf\ +\xcf\x5e\xfd\x20\x86\x1c\x00\xb7\x3f\x72\x3b\x11\xaf\x03\x50\x90\ +\x26\x8a\x39\x1c\x97\xed\x8f\xfd\xb3\x71\xe1\xc1\xa1\xfa\x57\xa2\ +\xdc\x17\x72\x38\xc7\x94\x2c\x20\xa2\x87\x18\x18\x97\x46\x60\x7a\ +\x34\x36\xfe\xc0\x43\xa8\xab\x13\xd9\xfa\xce\x3e\x00\xa1\x90\xe4\ +\xde\x3f\xf6\x11\x02\x3f\xa0\x29\x11\x44\x58\x27\x25\x51\xb7\x7d\ +\x4d\x70\x6f\xd6\x7e\x2d\xe0\xe2\xbb\x1f\x2f\x8e\xdb\x9c\xcb\x40\ +\xfc\x0b\x00\x45\x9a\xe2\x57\xfa\x64\x79\xee\x87\x4f\x2f\xfa\x36\ +\x1b\x9f\xd9\x05\x20\x14\x92\x3c\xfb\xc6\x6e\x04\xf1\xad\x2a\x3b\ +\xa3\x13\x12\x6e\x8c\x3d\x13\xdc\x91\x95\xbf\x21\x62\xfa\xfc\xf0\ +\x84\x94\x8c\x97\x91\x3e\xe1\xee\x92\x1d\x98\xb9\x3d\x12\x3c\x62\ +\xd5\x97\x94\x4d\xc3\xde\xae\x92\xe5\xda\xce\x13\xf0\x2e\x23\xe5\ +\x39\x55\x9d\x07\x80\xed\x6b\x82\x7b\xed\xce\x64\x25\x03\x1b\x35\ +\x45\x53\xc5\x00\x6f\xf4\xf9\x5e\x94\xad\xfa\xb2\x4c\xf4\x06\x22\ +\x3f\x67\x20\xa2\xb4\x11\xd1\xf3\x85\xf1\x62\xdf\xb6\xb5\x35\x87\ +\xac\xfa\xc9\x15\xf6\xbe\xfb\x66\x72\x5f\xfb\xeb\x2f\x9f\xed\x6d\ +\xeb\x03\x70\x25\x4e\x8c\x66\x9a\x74\x68\x44\xef\x88\xce\xf6\x4d\ +\x7f\xb6\xe2\xc7\xd2\x5f\x60\x5a\x20\xe2\x11\xe0\xad\x00\x46\x9c\ +\xb4\xf2\x0b\xb1\x68\xf0\xce\x7c\xac\xce\xb2\x85\xc7\x1f\xbe\x17\ +\x84\x15\x1a\xf3\x5d\xb1\x68\x70\xbd\x59\x5d\xd3\x00\x4c\x5b\xb4\ +\xca\x95\x4a\xf2\x3f\x08\x7c\x8e\xc2\xbc\xa3\x28\x5e\x7c\x59\x6b\ +\x73\x55\x7f\x36\x42\x2b\x16\xae\xb8\x40\x4a\xca\x37\x1e\x5f\x1a\ +\x4f\x00\x63\x02\x88\x52\x00\xf6\x12\x89\xbd\x42\xd0\x4e\x59\xd0\ +\x4b\xd9\xef\x01\x98\x3c\x81\xf0\x5a\x80\xaa\x14\xc6\x01\x66\x69\ +\x46\x7b\xd3\xe2\x9d\x46\x35\x4d\x03\xe0\xf1\x87\xd7\x82\x70\xf7\ +\xc9\xb6\xd0\x99\x72\x90\x77\xd7\xaa\xda\x4e\x2b\xd2\xca\x7d\x21\ +\x47\x61\xc9\xd8\x1a\x06\x57\x03\x38\xdf\x4a\x1d\x00\xbb\x88\x10\ +\x9e\xd8\x5d\xba\xa1\xa5\xe5\x96\x94\x95\x0a\x3f\xa8\x0d\x17\x8c\ +\x4e\xe0\x6d\x30\x7e\xac\x30\xef\x2c\x2a\xed\x9e\xde\x5a\x57\x97\ +\xcc\x54\xcf\x70\x12\x74\xfb\x1b\x2e\x51\x75\x1e\x60\x21\x63\x8e\ +\xd5\xce\xbb\xfd\x91\x1b\x9c\x63\x5c\x1f\x30\xb8\x01\xd6\x3b\x0f\ +\x00\x53\x99\xf1\x5c\x47\x49\x57\xac\xa2\x3a\x32\xcb\x4a\x85\x4f\ +\x23\xc1\xb8\x9c\x14\x37\x01\x38\xa0\x30\x57\xf4\xee\x73\x2d\x34\ +\xaa\x67\x30\x02\x98\x3c\x81\xc8\x5f\x01\x5c\xa2\xb0\xbd\x10\x8b\ +\x2e\x99\x6b\x26\xc6\xed\x8f\xda\x41\xfd\x0d\x04\x32\x6c\xdc\x32\ +\x88\xeb\x62\x67\xf5\x3c\x6c\x65\xa1\xa3\x33\x1f\x1c\x18\xe8\x8b\ +\x4f\xdc\xbd\xe1\xbe\xa3\x7a\xfc\x8c\x23\xc0\xbb\x20\x52\x09\x55\ +\xe7\x91\x80\x94\x0a\x99\x09\x98\x5c\xf3\xf4\x18\xa2\xf8\x1b\x39\ +\xeb\x3c\x00\x30\x85\x3c\xfb\x5d\x7f\x74\xfb\xa3\x4e\x33\x6a\xd1\ +\x40\xf1\x33\x00\xbe\x52\x98\xc6\xda\x9d\x8e\x40\x26\x7e\xc6\x00\ +\xb0\x84\xfb\xd4\x06\x44\x63\x8d\xcb\x3e\x37\x6a\xbc\xdc\x17\x72\ +\x14\x88\xd4\x2b\x00\xae\x30\x13\x3a\x04\xdc\x4c\xe8\x5f\x8f\x50\ +\xc8\xf0\x6f\xdb\xda\x5c\xd5\x4f\x04\xcd\x83\x92\x96\x65\x5a\x1b\ +\xe8\x3a\xf3\x2e\x5c\x5d\x0a\xe0\x6a\x85\x29\x21\x0b\xf1\x88\xb1\ +\x3e\xa6\x42\x97\x6b\x35\xc0\x95\xc6\xbc\x61\x80\x68\x8e\x7b\xbf\ +\xcb\x74\x14\x4e\xec\x2e\xdd\xc0\xc0\x27\x27\xaa\x81\xcf\xf9\xcc\ +\xd5\x75\xa5\x1e\x57\x37\x00\x22\x95\xbc\x1d\x8a\x45\x12\x01\x6f\ +\x6f\x5f\x73\x6f\x97\x51\xa3\xde\xc0\xaa\x3b\x98\x31\xdf\x4c\xdc\ +\x70\x41\xc0\x43\x9e\x05\x61\xdd\xce\x7c\x87\x96\x96\x5b\x52\x44\ +\x68\x51\xda\x24\xe6\xbb\xf4\xb8\xba\x01\x20\xd0\x75\x1a\xcb\x9f\ +\x8c\x1a\x74\xfb\xa3\x4e\x01\x3c\x66\xc4\xc9\x29\x24\xd4\x9b\x2d\ +\x77\x59\x08\xad\xe6\x6b\xf4\xea\xa4\x05\x60\xca\xdc\x27\x0a\x01\ +\xd5\xbb\x14\x82\x53\xaf\x19\x0a\xa2\xf8\x32\xcd\x42\x29\xdf\x98\ +\xdc\x51\xd2\x35\xcf\x88\xd0\x3e\xfe\x60\x1b\x00\xe5\xa8\x1d\xd5\ +\xe1\xda\xef\xd6\xf2\xd2\x02\x50\xe0\x74\x5c\x04\xc0\x71\xd2\x42\ +\xef\xb5\x37\xdd\xfb\x95\x96\xf7\x1d\x7c\xbe\x17\x65\x22\x04\xcd\ +\x35\xe7\x1a\xbc\xc4\xb0\xb8\xae\x4e\x00\xac\x7a\x70\xcc\xe9\xe7\ +\x94\x3a\x7f\x01\xe9\x47\x1a\xc3\x56\xa3\x76\x3a\x5c\x5d\x97\x82\ +\x71\xa6\xa1\x98\xfc\x60\xf2\xf4\xc0\xca\x1f\x1a\x11\x98\xd5\xda\ +\x89\x71\xa1\x96\x93\x16\x00\x66\xbe\x40\xf5\x1b\xe2\x13\x2d\x47\ +\x53\xe1\x66\xc3\xf2\x3c\x22\xc9\xd2\x1c\xa3\x72\x89\xa1\xd6\x4e\ +\xb8\x20\x8d\xa3\x35\x10\x61\xa2\xca\xc0\x64\xf8\xee\x07\x28\xaf\ +\xa7\xc0\x86\x2d\x13\xa7\xfd\xa7\x55\xb0\xdb\xb4\xda\xcb\xb4\x94\ +\xf4\x11\x40\x28\x56\x35\x22\x91\xc9\x5e\xff\x94\x4e\x7e\x2a\x10\ +\x30\xc1\xa8\xbc\xb0\xcf\xa9\xd5\x5e\xac\xe5\xa4\xcf\x01\xac\x26\ +\x49\xcc\x99\xcf\xd8\x06\x57\x65\x7a\xa7\xb5\xa7\x04\x6c\x12\x80\ +\xd6\xe6\x79\x71\x00\xca\x9d\xa0\xa3\xdc\x17\x72\x28\x39\x7a\xeb\ +\x00\xd5\x06\x29\x29\x89\x8c\x07\x1e\x33\x07\xeb\x67\x75\xac\x96\ +\x63\xd8\x87\xeb\x40\x4f\x7c\xaf\x8a\xc0\x72\xda\xb0\xf9\x0e\xc7\ +\xf7\xd9\x86\x2b\xc4\xbc\x82\x61\x78\xfa\x3c\x73\x5e\x73\x01\x00\ +\x9b\xc2\x34\xf0\x61\x4b\xdd\x80\x92\x93\x3e\x09\x02\xaa\x13\x55\ +\x16\x3c\xda\x44\xc4\xbf\x4c\x85\xe6\x0b\x64\x1c\x80\x63\xb6\xc3\ +\xa3\x34\xa6\x5e\x2d\x27\x7d\x12\x04\x7d\xa9\x6a\x43\x4a\x9f\x39\ +\xd5\xe5\xf4\xbe\x51\x79\x5e\xc1\xc6\x6d\xb3\x6c\x3b\x4f\x6d\xc0\ +\x17\x5a\x8e\xce\x24\xc8\x1f\x29\x7f\x12\x60\xbc\xd8\x20\xbc\x64\ +\x54\x9e\x4f\x30\xc8\xb0\x6d\x01\xa1\xd2\xce\x84\x3d\x5a\x4e\x7a\ +\x00\x48\x52\x5d\x36\x32\xab\x0e\x45\xd2\x50\x74\xac\x68\x33\x80\ +\xac\x6e\x63\x72\x02\xc6\x97\xed\x4d\x8b\x76\x19\x53\x34\xda\x75\ +\x46\x4c\x5a\x00\xfa\x64\xda\x06\x40\x79\xff\x5e\x31\x7d\x7e\x38\ +\xe3\xeb\xa6\xb5\xb9\xaa\x1f\x8c\x66\x33\xbd\x79\x40\x93\xe1\x91\ +\x7c\x28\x24\x11\x70\xad\xd2\xc4\x32\xb7\x6a\x69\x69\x01\x18\xbc\ +\x5b\xa3\x6d\x4a\x5b\x52\xa6\x6b\xb5\x3c\x25\x52\x09\x3c\x0c\xe0\ +\xb0\x89\xe0\x5c\xe2\x6b\x7b\x61\x52\x7b\x0f\xa0\x82\xb7\x73\x8c\ +\x1b\xea\x35\xca\x91\x33\xc6\x75\xc7\xb4\x3c\xfd\x77\x38\xab\x77\ +\x51\x44\x3c\xdb\xa8\xb1\x5d\xcf\x05\xbf\x21\xb0\xc9\x89\x51\xee\ +\x40\xa0\x07\xb7\xad\x58\x76\xcc\x90\x24\x49\x2a\xcd\x0c\x6c\xd2\ +\x3b\x1e\xd7\x0d\x40\xca\x41\x1b\x01\x9c\x3c\x81\x65\xcc\x9a\x5a\ +\x15\x36\xdc\xf1\x15\x96\xf6\x34\x10\xf0\xa6\xa1\xa8\x5c\x80\xb1\ +\xa1\x2d\xba\x58\x7b\x27\xa8\x46\x28\x24\x31\xa0\xda\xa4\x11\xf8\ +\x79\x3d\xaa\x6e\x00\x8e\x9f\xfb\x6f\x56\x98\x0a\x64\x7b\xda\x75\ +\xb8\x0a\xad\x75\x75\xc9\x44\x3c\x75\x2b\x80\x8f\x0d\xc5\x0d\x03\ +\x04\xbc\x5b\x34\x50\xec\x37\xbb\x8e\xf3\x76\xb9\x6e\x83\xfa\x1e\ +\x62\x7f\x51\x69\xcf\x66\x3d\x6e\xc6\x65\x2c\x81\x9f\x54\x1b\x68\ +\xd1\xd4\x45\xab\xce\x35\x6a\xf8\xbd\xe6\xa5\x87\x20\x25\xaf\x41\ +\x7e\x82\x10\x93\x52\xe2\x06\xb3\xeb\xb8\x72\x5f\xc8\xc1\x8c\xdf\ +\xa8\x8c\x44\x2b\x32\xdd\x0e\x65\x0c\x40\x5b\x34\xf8\x36\x00\xe5\ +\x64\xe8\x90\x92\x62\xb9\xa9\xca\xc6\x65\x9f\x27\xe3\xa9\x8b\xa0\ +\x1e\x41\xc3\x03\xd3\x1f\xec\xce\x64\xa5\xd9\xc1\x2c\x00\x38\x5d\ +\x2e\x3f\xd4\xdb\xde\x9e\x82\x81\xbe\xc6\x4c\x7c\x83\x8d\x0c\x31\ +\x88\x1e\x54\x59\x80\x3b\x2b\x6a\x56\x1a\xef\xc1\x31\x38\x12\x8a\ +\x4a\xbb\x7f\xc6\xc0\xaf\xa0\xb3\xfc\xcc\x02\x07\x18\x54\x13\x6b\ +\x5a\x7c\xbb\xe9\xa4\x07\xc0\xed\x7f\x72\x2c\x31\x7e\xad\xb4\x31\ +\xe3\xb7\xef\xac\xfb\x65\x46\x0d\x56\x2e\x47\xd7\x83\xa0\xbc\x0e\ +\xfb\x5a\x4e\x09\xaf\x95\xa7\x01\x00\x53\xaa\x1b\xc7\x15\x20\xb1\ +\x9c\x19\x77\x01\x30\xbd\xd9\x39\x8e\xc3\x44\xdc\x28\xc4\x88\xc7\ +\xda\x9b\x02\x96\x5e\xaf\xe5\xbe\x90\xc3\xe9\x72\x6d\x06\xe3\xb2\ +\x13\x46\xc6\x6e\x46\x81\xc7\x28\xaf\xd0\x34\x00\x53\xaa\x1b\xc7\ +\x39\x38\xb1\x1b\xc0\x59\x8a\x5a\x7f\x3f\x64\xc7\xac\x4f\x23\xc1\ +\xb8\x15\x71\xc0\xe0\xd1\xb9\x44\xf1\xab\x41\x3c\x87\x99\x26\x03\ +\x38\x07\x40\xc9\x71\x7f\xdf\x30\xa3\x93\xc0\x3b\x21\xa4\x96\xbe\ +\x43\x07\xde\xd2\xee\xda\xcc\xe0\x09\xac\x6c\x04\xa8\x5a\x61\x4a\ +\x80\x70\x89\x59\xe6\x8a\xa5\x04\x89\x8a\x9a\xf0\x45\x92\x40\x2b\ +\x94\x19\x61\x8c\x75\xb1\xa6\xda\xf9\xc3\x49\x90\x98\xb1\xb4\x7e\ +\xe4\x37\x49\x9b\xc8\x26\x90\x7a\xf0\x06\x22\x0b\x19\xbc\x5a\x6d\ +\xa5\xf9\xb1\x68\xed\x5a\xb3\xba\x96\x93\xa4\x3c\xd5\x2b\xe7\x82\ +\x49\x93\x71\x41\x4d\x7d\x3d\x07\x6a\xb3\x7d\x5a\xb9\x03\x93\xdb\ +\x1f\xa9\xa5\xc1\xdb\x60\xe5\x7c\xd6\x10\x8b\x06\x97\x5a\xf1\x60\ +\x39\x47\xa8\x33\xb6\x69\xf7\xd9\xee\xab\x9d\x20\xba\x58\x61\x76\ +\xdb\x9d\xce\xca\xf1\x15\x57\xbc\xb6\xaf\x7d\x73\x9f\x55\x5f\xb9\ +\x40\xb9\x2f\xe4\x38\xf7\xd2\xdd\x51\x1a\x9c\xa8\x4f\x3c\x48\x02\ +\xde\x2c\x2a\xed\xae\xfa\x62\xcb\x16\x4b\x39\x83\x59\x1d\x67\x95\ +\x1d\x1c\xff\x20\x83\x5e\x56\x19\x19\x97\x81\x1c\x6d\x6e\x7f\x64\ +\x72\x36\xbe\x86\x83\x29\xd5\x8d\xe3\x9c\x25\xae\xb7\x00\xba\x47\ +\x53\xf4\x41\x22\x9e\xba\xd5\x28\x23\x44\x8b\xac\x13\x25\x7d\xbe\ +\x17\xe5\x8e\x31\xfb\x9e\x00\x91\x76\x88\x25\x88\xd0\x18\x87\xfd\ +\xd1\xdd\xcf\xd4\xfc\x3b\x5b\xbf\x56\x30\x63\x69\xfd\xc8\xc4\x51\ +\xdb\x62\x10\x1e\x00\x30\x46\x55\x48\x78\x83\x45\xc1\x6d\x56\xdf\ +\x1a\x27\xab\x0d\x11\x9e\x40\xe4\x1e\x80\x1b\x91\x7e\x30\xf9\x2d\ +\x88\x9f\x92\xed\x54\x9f\x4d\xc2\xa2\x11\x66\x86\x42\xb6\xde\x7d\ +\x25\xf3\x40\xd2\xf2\x0c\x77\x90\xf5\x65\x3d\xa5\xf7\x5b\xcd\x27\ +\x52\x62\x58\xc9\xd2\xde\x40\x43\x25\x43\x7a\x09\x80\x4b\xa7\xf8\ +\x20\x80\x57\x01\xbc\x2a\x3b\xb0\x39\xdb\x60\x94\xfb\x42\x0e\xe7\ +\x68\x57\x25\xc9\xb8\x8e\x05\xae\x07\x41\x6f\x19\x9e\x00\xa8\xc6\ +\xca\x6c\x9f\x09\xc3\x4e\x97\xf7\x2e\x5c\xfd\x3d\x4e\xa5\x1a\x00\ +\xdc\x64\x40\x4b\x80\xb0\x05\x02\x7f\x81\x44\x1f\x4b\xcc\x9f\xb2\ +\x2c\xf7\xf4\x33\x7d\xeb\xb4\x25\x53\x52\x22\x59\x2c\xd8\x36\x2a\ +\xc9\x28\x23\x89\x26\x81\xc5\x0c\x80\xae\xc2\xe0\x27\x35\x99\x94\ +\xb7\x09\xe2\x9a\x9d\x8d\x4b\xda\x87\xa3\x3f\x67\x1f\x4c\x78\x16\ +\x44\x7e\x0a\x89\x1f\x07\x90\xdf\xc9\x70\x30\x2f\xf9\xe1\xb2\xee\ +\xd2\x35\x43\x19\xf2\x5a\xe4\xf6\x93\x99\x50\x48\x9a\xd6\x55\x72\ +\xbd\x00\x3d\x00\x86\x37\xa7\xbe\x41\x9f\x83\x45\x7d\xd1\xc0\x19\ +\x6b\xb3\x4d\xd0\x34\xf4\x9a\x2b\x47\x5a\x78\x17\xac\xba\x50\x48\ +\x3c\x8f\xc0\xb3\x01\x4c\x1a\xa2\x9b\xfd\x60\xbc\x4e\x24\x9e\x6f\ +\x2b\x3d\xf8\xb7\xa1\x7c\x0f\x60\x86\x53\xf2\xd9\xdc\xf1\x79\xe2\ +\x72\x30\x5f\x08\xd0\xf9\x20\x94\x01\x18\x85\xc1\xff\xb8\x8d\x41\ +\x87\x89\x71\x04\xc4\x5f\x13\x61\x8f\x10\xd8\x63\x23\x6c\xd9\x1e\ +\xad\xfd\xe8\xbf\x21\x17\xf9\x34\x4e\xe3\x34\xfe\x77\xf1\x1f\x1c\ +\x6b\xc6\x54\xc2\x9c\x88\xf8\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ +\x42\x60\x82\ +\x00\x00\x00\x9b\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x4d\x49\x44\x41\x54\x58\x85\xed\ +\xd7\xc1\x09\x00\x20\x08\x46\x61\x8b\x46\x72\x80\xb6\x71\x9f\xe6\ +\x09\x5c\xad\x0d\x32\xa5\xe3\x7b\xc7\x1f\x84\xef\xaa\x08\x25\x53\ +\x5b\xae\xb6\xfc\x75\x8f\x1a\x05\xc3\x4c\xee\xd7\x7a\xe5\xe8\x67\ +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x90\xff\x8c\ +\x9a\xec\xd4\x4e\x41\x07\x39\xb5\x09\xe5\x39\xad\x0d\x4e\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\xc7\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x79\x49\x44\x41\x54\x58\x85\xe5\ +\xd6\x31\x4e\xc3\x30\x14\xc6\xf1\xff\xb3\x9b\x72\x03\x3a\x70\x82\ +\x82\x84\xc4\xd4\xb9\xe5\x00\x48\x70\x85\x0e\xb0\x54\xdc\x20\x1c\ +\xa1\x1b\x54\xe2\x12\x88\x05\x09\xa9\x99\x91\x3a\x51\x28\x27\x60\ +\x80\x89\xb9\x21\x35\x43\x15\xa1\xb6\x69\x63\xa7\x4e\x18\xf0\x68\ +\x3f\xf9\xf7\xc9\xb6\x9e\x0c\xff\x7d\x48\x95\x58\xab\xdb\x6f\x24\ +\x5a\xdf\x81\x79\x1f\x0d\x7a\x67\x00\xaa\x52\x5c\xe9\x08\x4c\x0b\ +\x64\x2f\x9d\xaf\x55\x8a\x8b\x69\x62\xe4\x4d\xcf\x92\x93\x74\xad\ +\xf4\x2b\xc8\xc0\xdb\x4f\xb7\x97\x1f\x95\x04\xc8\xc3\x4b\x0d\x60\ +\x83\x97\x16\xc0\x16\x2f\x25\x80\x0b\xee\x3d\x80\x2b\xee\x35\x40\ +\x11\xdc\x5b\x00\x5b\xfc\xf0\xfc\x7a\xb7\x6e\xe2\x07\xe0\x6b\x34\ +\xe8\x75\xc0\x43\x27\x74\xc4\x87\xc0\x11\x50\x4f\xe7\xb7\x0a\x50\ +\x00\x3f\x00\x5e\xa6\x12\x9c\xa6\x6b\x85\xaf\x60\x0b\xfc\xf8\xf9\ +\xe6\xe2\x73\xab\x00\xbe\xf0\x42\x01\x5c\xf0\xc0\xc4\x91\xc0\x3e\ +\xf0\x3a\x95\xa0\xb3\x8c\x3b\x07\xf0\x8d\x3b\x05\x28\x03\x07\xd0\ +\x3e\xf1\x56\xb7\xdf\x10\x31\xd6\x38\x58\x9c\x80\x0b\xfe\xad\xd5\ +\xd0\x05\xcf\x0d\x50\x04\x37\x30\x89\x25\x68\x67\xe1\x4e\x9d\xb0\ +\x24\x7c\xa5\x13\x66\xfe\x09\xcb\xc0\x03\x13\x47\xcc\xaf\x67\xa1\ +\x13\xae\x3c\x42\x17\x3c\x51\x3a\x12\xd9\x8c\x67\x3c\xcc\x85\x66\ +\xa4\xb2\x36\xb5\xc5\x11\xd3\x34\x30\xa9\x25\xb3\xcc\x07\x67\xf3\ +\x30\x25\x6b\x53\x57\xdc\xa6\x6e\xdd\x09\xcd\x4f\x20\x0c\x55\xa2\ +\xd5\x63\xfe\x67\xc2\x48\x52\x53\xf7\x79\xf8\x72\xdd\x3a\xfc\x37\ +\xc0\x7c\xec\x00\xe3\x8d\x3f\x99\xf0\x4a\x8c\xa1\x0e\x8c\xd7\xe3\ +\xab\x75\x36\xfd\x00\xc2\x50\x81\xb1\x68\xcd\x46\xfc\xd6\xfd\xf1\ +\xf8\x01\x9a\x8b\x01\xab\xe8\x4a\xa0\x68\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x2a\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xdc\x49\x44\x41\x54\x58\x85\xed\ +\x95\xbf\x6b\x53\x51\x14\xc7\x3f\xdf\x9b\x68\x4a\x07\xab\x06\x2a\ +\xb5\xab\x2e\x82\x54\x92\x06\x51\xe9\x6c\x8b\x9d\x44\x07\x51\x70\ +\x32\x3f\x14\x2b\xfe\x05\x21\x9b\x93\xc5\x18\x85\x66\xea\xe6\xe2\ +\xa0\xa0\x54\xbb\x05\xec\x52\x1a\xd4\xbf\x40\xa7\xaa\x83\xe2\x24\ +\xb4\x4d\xee\x71\xc8\xb3\xa9\x69\xaa\xcd\x6b\xc4\xe5\x7d\xe0\x0d\ +\xef\xde\x7b\xce\xf9\x70\xee\xbb\xef\x42\x44\x44\x44\xc4\x7f\x46\ +\x61\x03\xcf\xe4\xef\x8f\xae\x5b\xfc\xa5\x60\xac\xb9\x4f\xa3\x6f\ +\x2b\xb7\x57\xc3\xe4\x71\x61\x82\x4e\xe7\x1e\x1c\x5f\xb7\xf8\x1b\ +\xc1\x18\x80\xdb\xb0\xa5\xd4\xcd\x47\xc7\xc2\xe4\xea\xb9\x03\x99\ +\x1b\xb3\xa7\x70\xb1\xd7\x06\xc3\x1d\x53\x5f\x1c\x9c\x5f\x9e\x9b\ +\x79\xdf\x4b\xbe\x9e\x3a\x90\x2a\x94\x27\xcc\xc5\x6a\x06\xc3\x18\ +\x06\x34\x5b\x8f\x0c\x38\xe2\xa1\x96\x2a\x94\x27\xfe\x89\x40\x2a\ +\x5f\x99\x76\x9e\x45\xe0\x80\x81\x21\x7c\x7b\xd6\xbc\x99\x0c\x18\ +\x72\x9e\xc5\x74\xb6\x7c\xa1\xaf\x02\x99\xdc\xc3\x6b\xce\xfc\x33\ +\x60\x00\x30\xb1\xb5\x78\x0b\xc9\x7c\xd0\x95\x01\x89\xe7\x99\x7c\ +\xf9\xea\x6e\x72\xc7\xfe\xb6\x20\x9d\x2d\xcf\x20\xaa\x81\xac\xd1\ +\xa5\x78\xdb\x02\xc3\x10\xc2\x01\x17\x47\xc6\x27\xbf\x7d\xaa\xbf\ +\x5a\x0e\x29\x60\x4a\xe7\x92\x25\x89\x7b\xc1\x80\x0f\x04\xfe\x8c\ +\x30\x13\x08\x24\x34\x75\x34\x33\xa9\xd5\x95\x85\x1a\x94\x76\x58\ +\xde\x8d\x62\xd1\x8d\x7f\x4e\x96\x81\x5b\xb4\xaa\x7a\xed\xa6\xf8\ +\x56\x7d\x4c\x42\x2e\x78\xa9\xac\x8c\x7c\xbd\x43\xa9\xb4\x7d\xeb\ +\x3a\x07\x4e\x5c\x2e\xee\x1f\x3c\x9c\x9c\x07\xae\x00\x98\xf0\xb2\ +\xde\x8a\x6f\x4a\x08\xc9\x36\xbf\xb3\x27\x66\x89\xeb\xf5\x6a\x6e\ +\x63\x47\x81\x74\x76\x6e\x50\x6e\xed\x29\xc6\x14\x06\x26\xf3\x6a\ +\x1d\xb1\xd0\xfc\xd6\x09\xb1\x60\x3e\x71\xa9\x5e\xcd\xfd\xd8\x26\ +\x70\xb2\xf0\xf8\x50\xc2\x1a\x2f\x30\xce\x06\x81\x7b\x2e\xde\x96\ +\x40\x6a\x9f\xb8\xa5\xc6\x5a\x73\xfa\xdd\xfc\xdd\xef\x00\xf1\x5f\ +\x8b\x12\xbe\xf1\x01\x18\x6a\x9b\x29\xd4\x6f\xba\x1b\x1d\xfb\x7c\ +\x2e\x9e\x88\x7f\x04\x0e\x42\xc8\xbb\x60\xef\xf4\xa5\xb1\x11\x11\ +\x11\x11\xfd\xe1\x27\x68\xea\x98\xa0\x5e\x6e\x43\xde\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x47\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xf9\x49\x44\x41\x54\x78\x9c\xed\ +\xd6\x21\x4e\xc4\x50\x14\x85\xe1\x73\x5b\xa6\x04\x04\x0a\x6c\x43\ +\x9a\x54\x92\x20\xd8\x03\x2c\x80\x75\x60\x58\x00\x61\x01\xb3\x09\ +\x3c\x92\x64\x58\x06\xba\x06\x53\x12\x32\x0e\x41\x86\x0e\xf3\x2e\ +\x96\xbc\x07\xb8\xbe\x49\xe8\xff\xc9\x73\x2b\x4e\x8f\x69\x25\x00\ +\x00\x00\x00\x00\x00\x00\x00\x00\x60\x12\xec\xaf\xa3\xbb\x9b\xa4\ +\x32\x53\x97\xb1\x04\x33\x0b\xbf\x1d\x7f\x1c\xa0\xef\xfb\xc3\xe1\ +\x73\x33\x37\xd9\xa5\xa4\xfd\xd1\xaa\xe5\xb1\x92\xf4\x50\x98\x5f\ +\xd5\x75\xfd\x12\x1f\x93\x01\xba\xae\x3b\x98\x55\x7b\x4f\x92\x1f\ +\xe7\x68\x97\x8d\x6b\x19\xc2\xfa\xa4\x69\x9a\xd7\xef\x71\x11\x3f\ +\x57\x55\xbb\xb7\xff\xee\xe5\x25\xc9\x74\x54\x94\xb3\x79\x1c\x27\ +\x03\xb8\x74\x9e\xa7\xd1\x56\x5c\xc4\x41\x32\xc0\xd4\x24\x03\x98\ +\xf4\xb8\x8d\x22\x99\x2c\xe2\x20\x19\x60\x18\x3e\x6e\x24\x7b\xce\ +\x52\x27\x27\xd7\x32\x6c\xd6\xd7\x71\x9c\x0c\xd0\xb6\xed\xdb\x4e\ +\xa9\x33\x97\xdf\x49\x7a\xcf\x52\x6e\x5c\x2b\x49\xf7\x45\xe1\xa7\ +\xf1\x17\x40\xe2\x47\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x98\ +\x8a\x2f\xe6\x4f\x38\x6a\x74\xad\x97\x2f\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xef\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xa1\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\x41\x11\x00\x20\x00\xc3\x30\x0e\x4d\x78\xc2\x0f\x86\x41\x46\ +\x78\x34\x06\xd6\xdb\x18\xd0\xda\xe7\xae\x7d\xae\x6c\x98\x72\xfc\ +\x07\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\ +\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\xd0\x3a\x40\x07\x68\ +\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\ +\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\xd0\x3a\x40\x07\x68\x1d\ +\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\ +\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\ +\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\ +\x40\xeb\x00\x1d\xa0\x75\x80\x0e\xd0\x1e\x06\x73\x04\xd7\x28\x98\ +\xcd\x67\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x03\x52\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x04\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\xbd\x4f\x14\x51\x14\xc5\xcf\x99\xac\x05\x6c\xa9\x1b\xbe\x7a\ +\x1b\x59\x1a\xe2\x62\x21\x35\x35\x9f\x46\x12\xb1\x93\x68\x02\x5a\ +\xc2\x5f\xa0\x35\x98\x08\xa5\x9a\x48\xc2\x67\x2c\xa9\xb1\x20\x24\ +\x34\x2c\x54\xd6\x2c\x12\xb4\xdc\xa5\x60\x9d\x63\xe1\xb2\x3b\xcc\ +\x0c\x1f\x22\xbb\x77\x37\xbc\x5f\xb5\xf7\xdd\x3b\xc9\x79\x27\xef\ +\xcd\x6c\x71\x2f\xe0\x70\x38\x6e\x33\xbc\x4a\x51\xd7\xba\x92\x4d\ +\x79\x8c\x80\x1a\x22\xd0\x29\xa1\x1d\x40\xa2\xca\xda\xfe\x95\x22\ +\x89\x9c\x80\x5d\x88\xcb\xc7\x49\x2c\xee\xf4\x31\x7f\xd9\x43\x17\ +\x1b\x20\x31\xb3\x86\x31\x42\x6f\x01\xb4\xdd\x94\xd2\x1a\x71\x20\ +\x70\x6a\xab\x1f\x9f\x41\xea\xbc\xa2\x73\x0d\xe8\x9e\xd7\x9d\x44\ +\xca\x9f\x05\x38\x5e\x1d\x7d\xb5\x42\xf3\xc5\x23\x6f\x62\x7b\x9c\ +\x27\x71\xd9\xf8\x63\x2c\x31\xb1\xea\xbf\x07\xf8\x22\x94\xc9\x4a\ +\xfa\x46\x7a\x3f\x48\xf8\x37\x2d\xf5\x7f\x90\xe0\x49\x7e\x2b\xc9\ +\xc7\x00\xd2\x95\x0c\xc7\x13\x29\x1f\x90\x5e\xc6\x9d\x84\xd8\x13\ +\x90\x59\xd5\x18\xa1\x8f\x81\xa5\x5f\x12\x27\xb7\x06\xb0\x70\xd1\ +\x71\xaa\x0b\x24\x66\x56\xf1\x94\xd4\x0c\x80\xbb\xe5\x65\xf0\xf9\ +\xd6\x00\x3f\x85\xcb\x23\x06\xfc\x7d\xe1\xe9\x3b\x2a\x77\xfe\x67\ +\x51\xec\xda\x1e\xe4\x41\xd5\x44\x57\x81\xee\x15\xb5\x25\xa8\x1d\ +\x00\xf7\x4a\x4b\xb9\xe3\x24\xef\x87\x5f\x8c\x5e\xf8\xc1\xa6\x3c\ +\x46\x10\x78\xe1\x49\x7c\xdd\x68\x9b\x07\x80\xed\x41\x1e\x10\x7c\ +\x13\x58\x6a\x6f\x2e\x60\x38\x5c\x17\x31\x00\xd4\x50\x20\xca\x6e\ +\x0d\x60\xa1\x0a\xfa\x6a\xc2\x66\x3f\xbe\x00\xc8\x9e\xc6\x82\x2e\ +\x37\x80\x40\x67\x25\xd0\x46\xdd\xdf\xf9\x8b\x20\x05\x6a\xa3\x1c\ +\x0b\x0f\xc2\x25\x11\x03\x4a\x7f\x72\x4a\x81\x77\x58\x2d\x6d\x35\ +\xe3\xec\x1e\x3a\xc2\xe9\xe8\x15\x08\x7c\x1a\xeb\xed\x53\x77\x1d\ +\x42\x7b\x88\x7c\xf6\xe3\x0c\xb8\x55\x38\x03\xac\x05\x58\xe3\x0c\ +\xb0\x16\x60\x8d\x33\xc0\x5a\x80\x35\xce\x00\x6b\x01\xd6\x38\x03\ +\xac\x05\x58\xe3\x0c\xb0\x16\x60\x8d\x33\xc0\x5a\x80\x35\xce\x00\ +\x6b\x01\xd6\x38\x03\xac\x05\x58\xe3\x0c\xb0\x16\x60\x8d\x33\xc0\ +\x5a\x80\x35\xce\x00\x6b\x01\xd6\x38\x03\xac\x05\x58\xe3\x0c\xb0\ +\x16\x60\x8d\x33\xc0\x5a\x80\x35\xce\x00\x6b\x01\xd6\x38\x03\xac\ +\x05\x58\x13\x67\x40\xf1\xf4\x87\xd4\xf8\x06\x85\xf6\x50\x0c\xe7\ +\xa3\x6d\x72\x44\xae\x12\xf8\x2d\xd5\x91\x55\x43\xce\xee\x61\x3f\ +\x9c\x8e\xb6\xc9\x01\xbb\x95\x80\xbd\x90\xae\x34\x53\x50\x97\x48\ +\x84\xd8\x5b\x8e\x89\xbd\x70\x49\xf4\x88\x8b\xcb\x81\x28\xfd\x68\ +\x15\x23\x55\x11\x57\x03\x7a\xd6\xf0\x04\x81\xce\x71\x82\x4b\xe1\ +\x9a\x88\x01\xc7\x49\x2c\x02\x28\xf7\x06\xfb\xd4\x6c\xcf\x57\x35\ +\xdc\x55\x78\xb8\xa8\x56\x41\x33\x81\xa5\x5c\xa1\x19\x97\x1b\xb0\ +\xd3\xc7\xbc\xc0\xa9\xd3\x98\x40\x4a\xbf\x95\xcd\xac\x68\xb4\x21\ +\xae\x83\xc4\xcc\x8a\x46\x99\xd0\x0e\x81\x54\x79\x19\x9c\x8e\x1b\ +\xa1\x89\xdf\x90\xc4\x9e\x35\xff\x43\xcc\xb4\x48\x16\xd4\x06\xe4\ +\x1d\xd6\x5b\x17\xa9\x04\x0f\xf4\x5b\x4a\x77\x3e\x1d\xcc\x11\x9a\ +\xdb\xec\xf7\x5e\xc5\xf5\x3d\xc7\x4f\x8c\x90\x2a\xce\x6b\x22\x91\ +\xf2\x11\x32\x21\x0d\x31\x0d\x08\xaa\xc7\x16\xea\x98\x03\x4a\x68\ +\xee\xe4\xc8\x9b\x3c\xaf\xe9\xfb\x2a\x43\x53\xcf\x08\xbd\x43\xe3\ +\x0d\x4d\xe5\x04\x4e\x5f\x7b\x68\x2a\x48\xd7\xba\x92\xcd\x05\x0c\ +\x0b\x1a\x2e\xb5\x9c\x77\xa0\x0e\xc7\xe6\x00\xec\x83\xd8\x23\xb8\ +\x54\x68\xc6\xd2\x55\xc6\xe6\x1c\x0e\xc7\xed\xe6\x0f\xfd\x5b\xf6\ +\x1a\x3c\xff\xda\x47\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ +\x82\ +\x00\x00\x00\xc5\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x77\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\xb1\x0d\xc2\x40\x10\x04\xc0\x3d\xe8\x01\x51\x0a\x75\x20\x3a\ +\x20\x72\x45\xee\x82\x90\x1e\xe8\xc4\xa2\x07\x78\x52\xf4\x8e\x8d\ +\x25\x3c\x13\xae\x2e\xd8\xdb\x04\x00\x00\x00\x00\x00\x00\xd8\x82\ +\xea\x83\xd3\xad\x9d\x5b\xda\x98\xe4\xb0\x42\x9f\x25\x4d\x79\xd7\ +\xf5\x71\xa9\xfb\x77\xb8\xeb\xaf\xfe\xf4\xf9\x24\x39\xd6\xbe\x8d\ +\x7d\x38\x1b\x60\x6b\x66\x03\x54\x6a\x48\xf2\x5c\xa1\xcb\xd2\xa6\ +\xf6\xaa\x61\xed\x12\x00\x00\x00\x00\x00\x00\x00\xc0\xef\x7d\x00\ +\x4e\xfe\x12\x08\x2a\x3f\xe7\x81\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x05\x27\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\xd9\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4f\x68\x14\x57\x1c\xc7\xbf\xbf\x99\xd1\x42\xd3\x22\x76\x85\ +\xdd\x90\xa2\x87\xc6\x43\x45\xb0\x24\x5b\xf6\xe0\x65\xa1\xb5\x17\ +\x6d\x2e\x6d\x6a\x4b\x55\x3c\x84\xac\x8d\x36\xe6\xd2\x82\x81\x66\ +\xb2\x81\x62\x6b\x2f\xd9\x60\xc4\xb5\x81\x16\x1a\x5a\x34\xf6\x12\ +\x22\x94\xb4\x87\xa0\xbd\x2c\xd9\x78\x90\xba\xbd\xd8\x83\x21\xd6\ +\xac\x10\x45\x30\x48\xc2\xce\xfc\x7a\x48\x5e\x3b\xbb\x3b\xbb\x3b\ +\x9b\xf9\x9b\x66\x3f\xb0\x87\x79\xf3\x9b\x79\xbf\xf9\xee\xf7\x37\ +\xf3\x66\x78\x0f\x68\xd0\xa0\xc1\x56\x86\xac\x04\xc5\x55\x55\x59\ +\x5e\x0c\x75\xe8\xc0\x51\x02\x45\x01\x6e\x01\xf0\x82\xcb\xb9\xd5\ +\xcb\x0a\x40\x0f\x18\x9c\x95\x80\xab\x4d\x91\xa5\xc9\x99\x64\xb2\ +\x50\xeb\xa0\x9a\x02\x44\x13\x17\x0f\x81\x39\x05\xe2\xd7\x9d\xc9\ +\xd3\x1b\x18\xc8\x11\xa4\xbe\x6c\xfa\xcc\xaf\xd5\xe2\xa4\x2a\xa7\ +\xa0\x68\xf7\x48\x3f\xa0\x4f\x6f\xb6\x8b\x07\x00\x02\xf6\x01\xfa\ +\xf4\x9b\x89\xd4\x39\x80\x2b\xfe\xd1\x72\xa5\x1d\xd1\xee\x50\x3f\ +\x08\x5f\xba\x93\x9e\x97\xd0\x5b\x2d\xd1\xcc\xca\xdf\x73\xbf\xfc\ +\x6e\xba\xd7\xac\x31\x9a\xb8\x78\x08\xd0\xa7\x4b\x9a\x9f\x80\x30\ +\x20\x15\xe8\xc6\x9e\xa7\xe1\xf9\x89\x89\x0f\x34\xc7\x73\xb5\x41\ +\x67\xe7\x35\xf9\xfe\x8e\xfc\x6e\x5d\xe1\xc3\x60\x0c\x01\xd8\x59\ +\x1c\x21\xbd\x63\x56\x0e\x65\x02\xc4\x55\x55\x79\xf6\x70\xd7\x9d\ +\x22\xdb\x13\x7e\x93\x0b\xfa\xb1\xcc\x58\x5f\xde\xf9\xd4\x9d\x27\ +\xd6\x35\x1c\xd6\x14\x69\x1c\x8c\xb7\x45\x1b\x03\xb9\x97\x23\x4b\ +\x07\x4a\x6f\x8c\x65\xf7\x80\xe5\xc5\x50\x47\x49\xcd\x3f\x5e\xc5\ +\xb6\x8f\x37\xcb\xc5\x03\x40\x66\xac\x2f\x2f\x17\xf4\x63\x00\x9e\ +\x88\x36\x02\xf6\x2d\x2f\x86\x3a\x4a\x63\xcb\x04\xd0\x81\xa3\x45\ +\x0d\x04\xf5\xce\xe5\x4f\x1e\xb9\x91\xa8\x9b\x64\xc6\xfa\xf2\x0c\ +\x56\x8d\x6d\x65\xd7\x06\x13\x01\xd6\x9e\xf3\x86\x80\x02\xdd\x70\ +\x3e\x3d\x6f\x90\x35\x69\xca\xb8\x4d\x40\x7b\x69\x8c\xc9\x63\x90\ +\x5b\x8c\x5b\x7b\x9e\x86\xe7\x9d\x4e\xcc\x2b\x4c\x72\x7f\xb5\x34\ +\xc6\x6c\x1c\x50\x34\xc2\x0b\xda\xdd\xbe\x1e\x4c\x72\x2f\x1b\xbd\ +\x56\x19\x08\x6d\x0d\x14\xbf\x13\xb0\x42\x5b\xcf\x68\xab\x54\xd0\ +\x06\x40\x78\x6f\xbd\xe9\x3a\x33\x86\xe6\xae\xf4\xfe\x65\xf7\xdc\ +\x81\x77\x40\x2c\x91\xda\x2b\x69\xda\x4d\x10\x8e\x03\x78\x71\xfd\ +\x77\x82\x08\xb7\xda\x7a\x46\x5b\xed\x9e\x3f\xd0\x02\xc4\x55\x55\ +\xd1\x98\x7e\x02\xd0\x6c\xb2\xbb\x59\xd2\xb4\x2f\xec\xf6\x11\x68\ +\x01\x9e\x3d\x0c\x7d\x0e\x2a\x7f\x74\x19\x78\xdf\x6e\x1f\x81\x15\ +\x20\x7a\x2a\xb5\x1f\x84\x41\xb7\xfb\x09\xa4\x00\x71\x55\x55\xa0\ +\xd3\xf7\x00\xb6\x55\x8b\x23\xa2\x09\xbb\x7d\x05\x52\x00\x0b\xd6\ +\x07\x80\x55\x89\xf9\x82\xdd\xbe\x02\x27\x80\x55\xeb\x13\x78\x30\ +\x93\xee\xcd\xd9\xed\x2f\x50\x02\x58\xb5\x3e\x80\x6c\x53\xe4\xf1\ +\x37\x4e\xf4\x19\x28\x01\xac\x5a\x9f\x74\xe9\xa4\x95\x0f\x9e\x56\ +\x08\x8c\x00\xf5\x58\x7f\xf6\xdb\x33\x77\x9d\xea\x37\x10\x02\xf8\ +\x61\x7d\x81\x23\xef\x02\xed\xdd\x23\xaf\x11\x61\x00\x62\x60\xc2\ +\xf8\x59\x57\xe4\xa1\xdb\x97\x4e\xdf\xb3\x72\xbc\x1f\xd6\x17\xd8\ +\x76\x40\x5b\xcf\x68\x2b\x11\x6e\x01\x38\x01\x31\x56\x27\x1c\x97\ +\x34\xed\x66\x2c\x91\xda\x5b\xeb\x78\xbf\xac\x2f\xb0\x2d\x80\x54\ +\xd0\x06\x50\x61\xac\xae\x81\x7e\x8c\xab\x6a\x45\x97\xf9\x69\x7d\ +\x81\xfd\x7b\xc0\x7f\xaf\xa8\x66\x44\x97\x17\x5f\xf9\xac\xd2\x4e\ +\x3f\xad\x2f\x70\xfd\x26\xc8\xa0\xc1\xe8\xa9\xd4\xfe\xd2\x76\xbf\ +\xad\x2f\x70\x42\x80\xeb\x35\xf6\x6f\x07\xd3\x77\xc6\x52\x08\x82\ +\xf5\x05\xb6\x05\x90\x81\xaf\x01\xac\xd6\x08\x2b\x2a\x85\x20\x58\ +\x5f\x60\x5b\x80\x4c\xba\x37\x07\x46\xb2\x56\x9c\x28\x85\xa0\x58\ +\x5f\xe0\xc8\x3d\xe0\xa5\xe6\xa5\x0b\x60\xcc\xd5\x08\xdb\x0e\x96\ +\x7e\x60\xa6\x71\x04\xc0\xfa\x02\x47\x04\x98\x49\x26\x0b\x90\xf8\ +\x24\x6a\x96\x02\xbf\x41\xc0\x81\x1a\xa7\xf3\xc4\xfa\x02\xc7\x9e\ +\x02\xd9\xcb\x67\xff\xb0\x52\x0a\xb5\xf0\xca\xfa\x02\x47\x1f\x83\ +\x16\x4b\xa1\x1a\x9e\x59\x5f\xe0\xa8\x00\xd6\x4b\xc1\x14\x4f\xad\ +\x2f\x70\x7c\x20\xb4\xd1\x52\xf0\xda\xfa\x02\x57\x46\x82\x1b\x28\ +\x05\xcf\xad\x2f\x70\x45\x80\x3a\x4b\xc1\x17\xeb\x0b\x5c\x7b\x17\ +\xb0\x5a\x0a\x7e\x59\x5f\xe0\xea\xcb\x90\x85\x52\xf0\xcd\xfa\x02\ +\x57\x05\x98\x49\x26\x0b\xba\x22\x7f\x08\xc0\x6c\x92\xc5\xbc\x2e\ +\xcb\x1f\xf9\x65\x7d\x81\xeb\xaf\xc3\xb7\x2f\x9d\xbe\x27\x6b\x38\ +\x48\xe0\x29\x00\xcf\x01\x3c\x27\xf0\x94\xac\xe1\xa0\xd5\x4f\x66\ +\x6e\xe2\xc9\xfc\x80\xcc\x58\xef\x02\x80\x77\xbd\xe8\xab\x5e\x02\ +\xf1\x55\xd8\x4f\xcc\x04\x58\x31\x6e\x74\x76\x5e\xab\x38\x9d\x36\ +\xe8\x98\xe4\xbe\x52\x1a\x63\x22\x00\x3d\x30\x6e\xdd\xdf\x91\xdf\ +\xed\x68\x56\x1e\x62\x92\xfb\x42\x69\x4c\x99\x00\x0c\xce\x1a\xb7\ +\x75\x85\x0f\x3b\x9c\x97\x67\x68\xb2\x7e\xc4\xb8\xcd\x28\x7f\x24\ +\x97\x09\x20\x01\x57\x8b\x1a\x18\x43\xb1\xae\xe1\xb0\xe3\xd9\xb9\ +\x4c\xac\x6b\x38\x4c\xa0\xa2\x81\x58\xd9\xb5\xc1\x44\x80\xa6\xc8\ +\xd2\x24\x98\xfe\x34\x34\xed\xd4\x14\x69\x7c\x33\x89\xf0\xef\x64\ +\x69\xc3\x8c\x71\x06\x72\x4d\x91\xa5\xc9\xd2\xd8\xba\xa6\xcb\x33\ +\x58\x95\x35\x69\x2a\xc8\xd3\xe5\x35\x59\x3f\xb2\xfe\xcf\x6f\x6c\ +\xba\xbc\x20\xda\x3d\xf2\x3f\x59\x30\x01\x10\xb8\x7f\x36\x7d\xf6\ +\xbc\xd9\xbe\x8a\xe3\x80\xec\x95\x4f\xcf\x13\xb8\xdf\xbd\xb4\x3c\ +\x81\x99\xe9\xdc\x6c\xba\xf7\xab\x4a\x01\x96\x16\x4d\x31\xf4\xe1\ +\xb5\x35\x38\x9b\x07\xab\x8b\xa6\x36\xb0\x6c\x0e\xed\x58\x9b\x75\ +\x1d\xc0\x65\x73\x58\x60\x60\xae\x9e\x65\x73\x0d\x1a\x34\xd8\xda\ +\xfc\x03\xf8\xad\xf2\xfb\x1a\x49\x36\xd6\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x87\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x39\x49\x44\x41\x54\x58\x85\xed\ +\xd7\xbf\x4e\xc2\x50\x14\xc7\xf1\xef\xb9\x21\x30\x5a\x17\x7c\x86\ +\xbe\x40\x5f\x80\x8a\x4c\x26\xa8\x1b\x23\x98\xb0\xd6\x59\x1d\x64\ +\x87\x95\x44\x57\x46\x65\x34\x22\x4f\xd0\x17\xe8\x3b\xb0\x50\x47\ +\x08\xe1\x38\x94\x2a\x7f\x5d\x6c\xe3\xe0\xfd\x8d\x37\x37\xfd\x7d\ +\xd2\xbb\x9c\x03\xff\x3d\xb2\x7d\xe0\x5f\x5e\x9f\x09\xdc\x80\x7a\ +\x80\x93\x51\x4f\x0c\x12\x2a\x74\xc7\xcf\x8f\x6f\x07\x01\xfe\x55\ +\xb3\x23\x2a\xb7\xc0\x0c\x88\x50\x3e\x32\xa9\x17\x8e\x00\x17\x28\ +\xa1\x74\xde\x5f\x9e\xee\x77\x00\x95\x7a\xb3\x66\x8c\xbc\x0a\x8c\ +\x59\x16\x1a\xa3\x61\x7f\x92\x49\xf9\x2a\xd5\x7a\xbb\x8c\x59\x0c\ +\x14\x7c\x45\x6a\xe9\x9f\x30\xe9\x05\x63\x4c\x00\xcc\xf2\x28\x07\ +\x18\x0d\xfb\x13\x96\x85\x06\x30\x17\x34\xf8\xea\xfd\xbe\xa2\x1e\ +\x10\xe5\x51\xbe\x81\x40\x22\x14\x6f\x0f\x00\x27\xb3\x37\xff\x29\ +\xaa\x31\xc2\xf1\x3e\xc0\x9f\xc4\x02\x2c\xc0\x02\x2c\xc0\x02\x2c\ +\xc0\x02\x2c\x60\x1d\x10\xaf\xa6\xd7\x7c\x23\xe2\xa0\x4c\xf7\x00\ +\x24\x04\xdc\x6a\xbd\x5d\xce\xab\x3b\xf9\xb6\xba\x08\xe1\x0e\x40\ +\xa1\x0b\x94\x30\x8b\x41\x1e\x88\xca\x79\xeb\x04\xb3\x18\x00\x45\ +\x45\x7a\xe9\xf9\xc6\x62\x72\x7a\xd1\x7a\x40\xb8\x03\xe6\xc9\xf4\ +\xaa\x71\x26\xed\x22\x0e\xa8\x0b\x14\x0f\x2e\x26\x69\x92\xd5\x4c\ +\x03\x14\x6f\x7d\x7a\xfd\x55\x94\x29\x42\xa8\x48\x6f\x7b\x35\xb3\ +\xf9\x04\xc3\x25\x66\x2f\xe5\x8f\x2b\x3d\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x03\x4e\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x00\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4f\x4f\x13\x51\x14\xc5\xcf\x41\x40\x09\x4b\xad\x94\x3f\xb6\ +\x0d\x0b\x37\x80\x2b\x96\xf2\x2d\x00\x23\x89\xb8\x93\x68\x22\xba\ +\x84\x4f\xa0\x6b\x35\x11\x97\x6a\x22\x89\xf0\x2d\x70\xc9\x8a\xc2\ +\xca\x05\x43\x0b\xa5\x50\x5d\x12\xb4\x20\xc7\x05\x2d\x0e\xd3\x81\ +\x56\xe2\xf4\xb6\xf2\x7e\xab\xd7\xfb\xde\x34\xe7\x9e\xbe\x37\xaf\ +\x8b\x7b\x01\x87\xc3\x71\x99\x61\x2d\x8b\xf2\xf9\x7c\xe7\x7e\xb1\ +\x38\x4e\x71\x14\xc4\x20\x84\x1e\x00\xad\x11\x6b\xfb\x5b\x0e\x41\ +\xe4\x20\xac\x8a\x5a\xec\x68\x6f\xff\x1c\x8f\xc7\xf7\xaa\x3d\x74\ +\xae\x01\x92\xe8\x65\xb6\x26\x09\xbd\x00\xd0\xfd\xcf\xa4\xd6\x87\ +\x6d\x82\x33\x89\x44\xef\x47\x92\x3a\x6b\xd1\x99\x06\x2c\x2f\x2f\ +\xb7\xc5\x62\x37\x5f\x0b\x9c\x8a\x46\x5f\x7d\x20\xf4\xae\x50\xd8\ +\x7d\x3a\x3c\x3c\x7c\x10\x36\x1f\xba\x8d\x8f\x7f\xf9\xcd\x37\x02\ +\x1e\x9d\x8a\x03\x69\x8a\x5f\x48\xe5\x25\x1d\x45\x21\xf8\xa2\x90\ +\x6c\x91\x18\x17\x75\x97\xc0\x50\x39\x2e\x70\x2a\x16\xbb\x09\x49\ +\x8f\xc3\x76\x42\xe8\x0e\xd8\xd8\xd8\x9c\x14\xf4\xde\x17\xfa\x0e\ +\x61\x3a\x99\xec\x9b\x3f\x6f\x3b\x35\x02\x92\xb8\xb1\xb1\x79\x1f\ +\xc4\x2b\x00\xd7\xcb\x71\x82\x0f\x93\xc9\xbe\x0f\xc1\xf5\x15\x06\ +\xe4\xf3\xf9\xce\x1f\x3f\x0f\xbe\xe2\xcf\x99\xff\x06\xfd\xba\x93\ +\x4a\xa5\xb6\x23\x53\x1d\x01\x9e\xe7\x75\x83\x57\x56\x00\xdc\x28\ +\x85\x72\xd7\xae\xb6\xdd\x0e\xbe\x18\x5b\x82\x0f\xee\x17\x8b\xe3\ +\xf0\xbf\xf0\x84\x67\xcd\x96\x3c\x00\xa4\x52\xa9\x6d\x08\xcf\x7d\ +\xa1\x9e\xfd\x62\x71\x2c\xb8\xae\xc2\x00\x8a\xa3\xe5\xb1\x80\x74\ +\x32\xd9\x37\x1f\x91\xc6\xc8\x49\x26\xfb\x3e\x09\x48\x97\x3f\x53\ +\xac\x6e\x00\x88\x41\xdf\x03\x4b\x8d\x7e\xe6\xcf\x83\xa4\x28\x2e\ +\xf9\x42\x03\xc1\x35\x95\x06\x1c\xff\xc9\x29\x7d\x81\x76\xa2\x91\ +\x56\x3f\x02\x39\xf4\x06\xe7\x2b\x0d\xf0\x5d\x8d\x8d\x76\xd5\x5d\ +\x84\x40\x0e\x15\xd7\x7e\x98\x01\x97\x0a\x67\x80\xb5\x00\x6b\x9c\ +\x01\xd6\x02\xac\x71\x06\x58\x0b\xb0\xc6\x19\x60\x2d\xc0\x1a\x67\ +\x80\xb5\x00\x6b\x9c\x01\xd6\x02\xac\x71\x06\x58\x0b\xb0\xc6\x19\ +\x60\x2d\xc0\x1a\x67\x80\xb5\x00\x6b\x9c\x01\xd6\x02\xac\x71\x06\ +\x58\x0b\xb0\xc6\x19\x60\x2d\xc0\x1a\x67\x80\xb5\x00\x6b\x9c\x01\ +\xd6\x02\xac\x71\x06\x58\x0b\xb0\xc6\x19\x60\x2d\xc0\x1a\x67\x80\ +\xb5\x00\x6b\xc2\x0c\x38\x2c\x0f\x48\x36\xbd\x41\x81\x1c\x0e\x83\ +\xf3\x61\x65\x72\xb9\xf2\x50\x62\x57\x34\xb2\xea\x47\x20\x87\xad\ +\xe0\x7c\x58\x99\xdc\xea\xc9\x90\x1a\x91\x54\x53\x4f\x41\x23\x22\ +\x89\xa2\x46\x7c\xa1\xb5\xe0\x9a\x0a\x03\x44\x2d\x96\xc7\x04\x86\ +\xbc\x6c\x76\x3c\x22\x7d\x91\xe3\x65\xb3\xf7\x4e\x55\x8e\x53\x0b\ +\xc1\x35\xd5\x8b\xa5\x85\xc2\xd1\xd1\xc1\x50\x7f\x7f\x7f\x53\x15\ +\x4d\xae\xaf\xaf\xc7\xc9\xd6\x15\x10\xb1\x52\xa8\xb6\x62\xe9\x78\ +\x3c\xbe\x47\x70\xe6\x24\x40\xc4\x5a\x5a\xda\xd2\x9e\x97\x9d\x68\ +\x86\xe3\x20\x89\x9e\x97\x9d\x08\x24\x0f\x82\xb3\x61\x2d\x34\xa1\ +\x09\x49\x62\x26\x93\x7d\x1b\xec\x16\x29\x35\x4c\x2c\x91\xda\x69\ +\xb4\x2a\xd2\x52\xc3\x44\x97\xa8\x11\xff\xb6\x07\x00\x42\x73\x89\ +\xc4\xad\x27\x35\x37\x4c\x00\xff\x55\xcb\xcc\x5c\xa1\xb0\x3b\x7d\ +\x56\xcb\x4c\xd5\xa6\xa9\x4c\x66\xeb\x81\xa0\x97\x68\xbe\xa6\xa9\ +\x1c\xc1\xd9\x0b\x37\x4d\xf9\x29\xb5\xcd\x8d\x95\xea\xed\x07\x70\ +\x5c\x75\xdd\x78\x6d\x73\xc7\xf7\xfc\x9a\xa8\x85\x8e\xf6\xf6\x85\ +\x5a\xda\xe6\x1c\x0e\xc7\xe5\xe6\x37\x49\x9a\x11\x82\x28\x6e\xc8\ +\x6e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x78\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x2a\x49\x44\x41\x54\x58\x85\xed\ +\xce\x41\x11\x00\x20\x0c\x04\xb1\x16\xff\x22\xe9\x20\x04\x64\x1c\ +\x8f\xc4\xc0\x6e\x15\x00\x10\xd6\x7b\xce\x4d\x0e\xac\x64\x1c\x00\ +\xf8\xc2\x03\x48\xae\x03\xa7\xd4\xed\xa0\x47\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x06\x65\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x06\x17\x49\x44\x41\x54\x78\x9c\xed\ +\x9a\xc9\x73\x5c\xd5\x15\x87\xbf\x73\x5b\x31\x32\x83\x4c\x6c\x50\ +\x00\xf5\x1b\x5a\x15\x6f\xb0\x31\x93\xc1\x98\xa4\x12\x2c\x1c\x24\ +\x83\x6d\xe5\x6f\x61\x05\x8b\x64\x91\xf2\x82\x0d\xcb\xe4\xef\xa0\ +\x98\xca\xd6\x18\x46\x43\x85\xa4\x42\x80\x2a\xaa\x28\xd4\x6f\x90\ +\x29\x07\xc7\x0e\x96\x71\x2c\x19\xeb\x1e\x16\x52\x3b\xe2\x75\xab\ +\xfb\xbe\xee\xf7\x24\x51\xe8\x5b\xde\x77\xfa\xbe\xf3\xfb\xfa\xdc\ +\x1e\xa4\x86\x6d\xb6\xd9\xe6\xa7\x8c\xb4\x5a\x3c\x7f\xfe\xfc\x6d\ +\x8b\x8b\xd7\x9f\x57\x91\x13\x40\x3f\x70\x56\x74\xf9\xa5\x30\x0c\ +\xeb\x1b\xdb\x5e\x77\x44\x51\x54\x53\xa9\xbc\x00\x1c\x06\x16\x0d\ +\xbc\xb1\x73\xe7\x2d\x2f\x0f\x0e\x0e\x7e\x9b\xad\x6d\x12\xf0\xf9\ +\xe7\x17\xee\xe8\xdf\xb9\xf8\x16\xf0\x70\xe6\xd2\x65\x35\x8c\xd6\ +\x3c\xef\xc3\x72\xda\x2e\x86\x24\x49\x1e\xb3\x2a\x93\xc0\xae\x1f\ +\x5c\x10\x3e\xfe\x6e\x69\xf1\x37\x7b\xf7\xee\x5d\x58\xbb\x6c\xb2\ +\x1b\xf4\xf7\x5f\x7b\x81\xe6\xf0\x00\xbb\xc4\x32\x51\x4f\xd3\x43\ +\x45\x36\x5c\x24\xeb\x86\x07\x50\x1e\xdc\xb1\xa3\xff\xc5\xec\x72\ +\x93\x00\x44\x4e\xb6\xb9\xc7\xc0\x56\x95\xd0\x36\xfc\x2a\x8a\x8e\ +\x67\xd7\x9a\x05\xc0\xce\x0e\xf7\x1a\x10\xcb\xc4\x5c\x9a\x3e\x9e\ +\xb3\xc7\xd2\x48\x92\xe4\x60\xa7\xf0\x2b\x48\x7f\x76\xa5\x49\x80\ +\xa2\xef\x39\xdc\x73\xc0\x58\x26\xb7\x82\x84\xd5\xf0\x53\x74\x0c\ +\x0f\x40\x53\xb6\x26\x01\x7d\x46\x4e\x01\x97\x1d\x36\xdb\x74\x09\ +\x39\xc3\x2f\x54\x0c\x7f\xca\x2e\x36\x09\xf0\x3c\xef\x0b\x6b\x78\ +\x06\x77\x09\x9b\x72\x1c\xdc\xc7\x1e\x80\x05\xb5\x32\xea\x79\xde\ +\x17\xd9\x0b\x2d\x3f\x07\x00\xcc\xa5\xe9\xe3\xc6\x32\x09\x0c\x38\ +\xdc\xe0\xb2\x11\xfd\x9d\xef\xfb\x7f\x73\xa8\xed\x99\x38\x8e\x1f\ +\x55\xcc\x14\x70\xa7\x43\xf9\x15\xb5\xf2\x4c\xad\x56\xfd\xa0\xd5\ +\xc5\x75\x05\xc0\xd6\x94\x50\x64\x78\xe8\x20\x00\xb6\x96\x84\xa2\ +\xc3\x83\x83\x00\x80\x7a\x9a\x1e\x12\xcb\x04\xee\x12\x8e\xfa\xbe\ +\xff\x91\xcb\xde\xae\x44\xd1\x57\x8f\x20\xcb\x53\xc0\xcf\x1d\xca\ +\xaf\xa0\x32\x1a\x86\xd5\xb3\x9d\x0a\x9d\x04\xc0\xe6\x4a\x28\x2b\ +\x3c\xb4\xfe\x20\xd4\x92\x9a\xe7\x7d\xa8\x56\x46\x81\x85\x8e\xc5\ +\xb0\xcb\xaa\x4c\x25\x49\x72\xd0\x75\xff\xf5\xc8\x1f\xde\x8c\xb9\ +\x86\x87\x1c\x13\xd0\xa0\x5e\x9f\x7f\x42\x8c\x4e\x00\x77\x38\x94\ +\x7f\xb3\xfa\x9a\xd0\xd5\x24\xe4\x0c\xff\x2d\x6a\x46\xc3\x70\xe8\ +\xfd\x3c\xf7\xc8\x2d\x00\xf2\x4b\x10\xec\xd1\x20\x08\xfe\x9e\xe7\ +\x1e\x1b\x11\x1e\xba\x14\x00\xe5\x4a\x88\xa2\x73\x0f\x23\x76\x9a\ +\x92\xc3\x43\x0f\x02\x00\xa2\x68\xfe\x30\xa2\x67\x28\x50\x42\xde\ +\xf0\x82\x19\x0b\x82\x21\x97\xef\x2f\x2d\xe9\x49\x00\x14\x2b\x61\ +\xa3\xc3\x43\x8e\x77\x81\xf5\x08\xc3\xea\x59\xd4\x8c\x01\x57\x1c\ +\xca\xef\x54\xcc\x64\x14\x7d\xf5\x48\xf6\xc2\x6a\x78\xe7\x33\x2f\ +\xd8\x63\xbd\x86\x87\x02\x26\xa0\x41\x14\x9d\x7b\x12\xb1\x67\x80\ +\xdb\x1d\xca\xff\x8b\x56\x8e\x86\xe1\x7d\xff\x00\xa8\xd7\xe7\x1f\ +\x12\xa3\xd3\xc0\x6e\x87\xc7\x5e\x15\xec\x58\x10\x04\xef\xf6\xd2\ +\x6f\x83\xc2\x04\x40\x77\x12\x54\xad\xdd\xac\xf0\x50\xb0\x00\xc8\ +\x29\x41\x59\x50\x14\x11\x71\xf9\x74\x59\x78\x78\x28\x41\x00\x40\ +\x1c\x9f\xfb\x95\x62\x4f\xe3\x36\x09\x2e\x5c\x35\xa2\xc7\x7c\xdf\ +\x7f\xa7\xa0\xfd\x6e\x52\x8a\x00\x28\x54\x42\x69\xe1\xa1\x80\x77\ +\x81\xf5\x08\x82\xa1\xf7\x04\x7b\x0c\x68\xfa\x67\x44\x0e\xae\x5a\ +\xd1\x67\xcb\x0a\x0f\x25\x4e\x40\x83\x38\x8e\x7f\xad\x98\xd3\xc0\ +\x6d\x39\x1f\x7a\xd5\x8a\x3e\x3b\xec\xfb\x6f\x97\xd1\x57\x83\xd2\ +\x05\xc0\xaa\x04\x35\x13\x48\xc7\x3f\xb9\x37\x58\xb4\xa2\xa3\x65\ +\x87\x87\x12\x8f\xc0\x5a\x96\x8d\x59\x40\xb8\xee\x5a\xaf\x70\x5d\ +\x96\x8d\xcb\xd7\xee\x9e\x29\x5d\xc0\x5c\x9a\x1e\x30\x96\x19\xdc\ +\xfe\x7a\x0b\x80\xc0\x80\x18\x9d\xae\xd7\xe7\x1f\x2a\xb1\xb5\xc6\ +\xbd\xca\x63\x4d\xf8\x3d\x5d\x6e\x71\x49\xad\x3c\x5d\xab\x55\xff\ +\x59\x64\x5f\x6b\x29\x6d\x02\x56\xc3\x4f\xd3\x7d\x78\x80\xdd\x62\ +\x74\x7a\x6e\x6e\xfe\xc1\xa2\xfa\xca\x52\xca\x04\xa4\x69\xfa\xc0\ +\xf2\xca\x33\x7f\x57\x41\x5b\x5e\xb2\xcb\x32\x32\x3c\x5c\xfd\xb8\ +\xa0\xfd\x6e\x52\xf8\x04\xe4\x0c\xbf\xa4\xaa\x4b\x0e\x75\xbb\x4d\ +\xa5\x9c\x49\x28\x54\x40\xce\xf0\xd7\xd4\x32\xa6\x2b\xff\x86\xfb\ +\x9f\x43\xfd\x9e\x32\x24\x14\x76\x04\x92\x24\xd9\x6f\x55\x66\x71\ +\x0c\x8f\xca\x73\x61\x58\x9d\x05\xa8\xa7\xe9\x6f\xc5\xf2\x26\x70\ +\xab\xc3\x63\x2f\x5a\xc3\xc8\xb0\xe7\xfd\xab\x97\x7e\x1b\x14\x22\ +\xa0\x97\xf0\x0d\x36\x4b\x42\xcf\x47\xa0\x8b\xf0\xc7\xb3\xe1\x01\ +\x6a\x9e\xf7\x96\x5a\x9e\xc3\xf5\x38\x58\x66\xe6\xd2\xf4\x40\xde\ +\x7e\xb3\xf4\x24\x20\x49\x92\xfd\xd6\x8a\xf3\x99\x5f\x0d\x3f\xb3\ +\x5e\x41\xad\xe6\xfd\x35\xa7\x84\xe9\x5e\x25\x74\x7d\x04\x6e\x86\ +\x17\xee\x76\x28\xbf\x26\xc8\x89\x20\xa8\x4e\xbb\xec\x5d\xaf\xa7\ +\x4f\x89\xe1\x4d\x3a\xff\x5c\x07\xe0\x3f\x15\xc3\x88\xe7\x79\x9f\ +\xb8\xec\x9d\xa5\x2b\x01\x71\x1c\xef\x53\x35\xb3\x8e\xe1\x17\x05\ +\x39\xee\x1a\xbe\xc1\x46\x49\xc8\x2d\x60\x23\xc2\x37\x88\xa2\xf9\ +\x23\x88\xbe\x41\x89\x12\x72\x09\x88\xe3\x78\x9f\x62\x66\x80\x41\ +\x87\xf2\x9e\xc2\x37\xc8\x2b\xc1\x88\x1e\xf1\x7d\xff\x53\xd7\xfd\ +\x9d\x5f\x04\xf3\x87\x37\xce\x67\xbe\x1d\x61\x58\x9d\x45\xe5\x38\ +\x70\xcd\xa1\xfc\x2e\xab\x32\x9b\x24\xc9\x7e\xd7\xfd\x9d\x26\x20\ +\x8e\xe3\xfb\x15\x33\x4b\xae\xf0\x43\x53\xae\x4d\xb8\x10\x45\xf3\ +\x23\x88\xbe\x4e\xc1\x93\xd0\x71\x02\xf2\x87\xb7\x27\x8b\x0e\x0f\ +\x10\x86\xd5\x19\x41\x4e\xe0\x3a\x09\x56\x66\x5c\x26\xa1\xed\x04\ +\x74\x17\x3e\x98\x74\xa8\xed\x9a\x38\x9e\x7f\x5a\xd1\xd7\x59\xf9\ +\x15\x7b\x7b\x94\x0b\xc6\xe8\x48\xbb\x49\x58\x77\x02\x56\xc2\x57\ +\x9c\xcf\xbc\x15\x1d\x2f\x3b\x3c\x40\x10\x54\xa7\x05\x39\x0e\x2c\ +\x76\x2c\x16\xee\xb6\x56\x66\xe2\x38\xde\xb7\x7e\x49\x0b\xfe\x1f\ +\x5e\x7f\xe1\xd0\xd3\x92\x15\x3d\x39\xec\xfb\x13\x0e\xb5\x85\x91\ +\x77\x12\x44\xec\x91\x20\x08\x3e\xcb\x5e\x6a\x12\x90\xa6\xe9\xd0\ +\xb2\xe5\x23\xe0\x1e\x87\x3e\x36\x25\x7c\x83\x38\x3e\x77\x54\xb1\ +\xaf\xe1\x22\x01\xbe\xbe\xd1\x67\x0e\xfe\x72\x68\x28\x5d\xbb\xd8\ +\x74\x04\xac\xd5\x3f\xf0\x23\x08\x0f\x10\x04\x43\x53\x82\x39\x81\ +\xcb\x71\x80\xc1\xbe\x1b\xf6\x8f\xd9\xc5\x16\xbf\x16\x97\xa7\x1c\ +\x36\x5b\x52\xd1\xf1\xcd\x0c\xdf\x60\x45\x82\x3d\x89\x9b\x84\x23\ +\xd9\x85\x56\x2f\x82\xcb\x1d\x36\x59\x52\xd1\xf1\x9a\xef\x9f\x71\ +\x69\x70\x23\x08\x82\x60\xd2\x49\x82\x36\x67\x6b\x12\x20\x68\xbb\ +\x67\x75\x49\x0d\xbf\xdf\x4a\xe1\x1b\x04\x41\x30\x69\x45\xc7\x69\ +\x23\x41\x85\xd3\xd9\xb5\x26\x01\x95\x8a\x39\x05\x7c\xd9\xe2\xf1\ +\x2b\xe1\x3d\xaf\x69\x93\xad\xc2\xb0\xef\x4f\xb4\x91\x50\xbf\xb1\ +\xa3\xef\x54\x76\xb1\x49\x40\xb5\x5a\xbd\xf8\xb3\x3e\xf3\x04\xc2\ +\x9f\x81\x18\xf8\x5a\x91\x57\xd1\xca\x93\x5b\x39\x7c\x83\x61\xdf\ +\x9f\x50\x2b\x87\x51\x5e\x01\xf9\x37\x10\xa3\xf2\x97\xef\x76\xf4\ +\x1d\xda\x7b\xef\xbd\x17\x36\xbb\xbf\x6d\xb6\xd9\x66\x6b\xf1\x3d\ +\x64\x29\x23\xc7\x02\xc7\xba\xcb\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x01\x06\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xb8\x49\x44\x41\x54\x78\x9c\xed\ +\xd9\xc1\x0d\x83\x50\x10\xc4\xd0\x0d\xa2\x24\x7a\xe2\x46\x31\xdc\ +\xe8\x29\x3d\x91\x32\x5e\xa4\x6f\x37\xb0\x96\x35\xb7\x9d\x81\x1c\ +\xe7\xfd\x1e\xe7\xfd\x4a\x87\x4d\x1e\xff\x07\x0a\xa0\x05\x34\x05\ +\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\ +\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\ +\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\ +\xa0\x59\x3e\xc0\x47\x1e\xd7\xaf\xf1\x99\x16\x30\xbb\x16\x98\x99\ +\xf9\x3e\x17\x5b\xe2\xf2\x0b\x28\x80\x16\xd0\x14\x40\x0b\x68\x0a\ +\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\ +\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\ +\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\x66\xf9\x00\ +\x3f\xfa\xaa\x08\xd8\xe7\x6a\x2c\xe4\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x04\x72\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x24\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4d\x88\x1c\x55\x14\x85\xbf\x5b\xdd\x09\x8a\x8a\x20\x2a\x62\ +\x4f\x57\x75\x0d\x19\x14\x77\xc2\xe0\x52\x50\x34\x1a\xc4\xe0\x0f\ +\xe8\x4a\x44\x51\xd0\x85\x18\x41\x11\x74\x11\x21\x8a\x11\x04\x17\ +\x22\x1a\x70\xe3\xc2\xa0\xae\xc2\x80\x46\x47\x5d\x08\x82\xe0\x42\ +\x10\x44\x82\x66\xa6\xe7\x75\xcd\x24\xd1\x88\x8a\x60\x18\xec\xee\ +\x77\x5d\xcc\x88\x55\x35\x43\x98\x21\xef\xbd\x7a\x9a\x3e\xcb\x73\ +\xa0\xee\x7d\xa7\xee\x7d\x3f\xf5\x03\x13\x4c\x30\xc1\x04\xff\x01\ +\x18\xb3\xb2\xdf\x0c\x8a\xe1\x92\x29\x46\xc6\x14\x2f\xb8\xba\xae\ +\xb8\xba\x90\x4f\x2c\x2d\x2d\xdf\x84\xe8\xe7\xfc\x9b\xaf\xed\x65\ +\xdd\x96\x8b\x6b\x27\x2e\x2e\xe2\x13\x83\xc1\x60\x16\xd1\x39\x4a\ +\x37\x4b\x55\x9d\xe5\x1d\xb5\x01\xfd\xfe\xca\xb5\x56\xe5\x28\x70\ +\x71\x99\x17\x11\xeb\x2a\x46\xb4\x06\x2c\x2c\xac\xa4\x49\x62\xe7\ +\x81\xcb\x37\x91\xd5\x55\x9c\x28\x0d\xf8\xf1\xe4\xc9\x2b\x5a\x6d\ +\x3b\xaf\xd0\xf5\x1d\x2b\x3a\x03\x8e\x1d\x3b\x7d\xc9\x8e\xbf\x46\ +\x1f\x01\xd7\x84\x88\xd7\x0e\x11\x64\xab\xe8\xf7\xfb\x17\x48\xb2\ +\x7a\x04\x98\xad\x49\x8a\xa7\x15\x2b\x9a\x0a\x50\xd5\xb6\xb4\xda\ +\x87\x81\x9b\xeb\x12\xe0\x6c\xd2\xab\x23\x0a\x03\x54\x55\x4c\xb1\ +\x7c\x08\xe5\xee\xaa\x22\x5e\x07\x0f\x91\x18\x60\x06\xcb\xaf\xa0\ +\x3c\x5c\xe6\x44\x50\x50\xaf\x83\x87\x08\xe6\x00\x63\x8a\x67\x15\ +\x9e\x29\x73\xba\xb6\xc8\x79\x1f\x3c\x34\x5c\x01\xc6\x14\x8f\x2a\ +\x1c\xac\xf3\x22\x8c\x43\xe5\xd0\x98\x01\x4b\x4b\xc5\xbd\x0a\x6f\ +\x6d\x54\xfc\x97\x7d\x19\x8d\x18\x60\xcc\xca\x2d\x08\x87\x37\xc4\ +\x57\xec\xfa\xc4\x17\x0c\xc1\x0d\x58\x2c\x8a\x1b\x14\x7b\x04\xd8\ +\x59\xe6\x15\x2c\xe2\x6e\x8b\xbb\x55\x04\x9d\x04\x8d\x31\xd7\xa9\ +\xe5\x28\x70\x51\x4d\xb2\xe2\x70\x7f\xbf\x1d\x04\xab\x80\xc5\xc5\ +\x13\x99\x92\xcc\x03\x97\x55\x04\xc1\xd2\xd0\xe0\x21\x90\x01\xc7\ +\x8f\x9f\xba\x52\x5a\xe3\x4f\x81\x4e\x99\x17\xb0\x68\x73\x83\x87\ +\x00\x2d\xb0\xb0\xb0\x70\x69\xab\x3d\xfc\x18\x98\xa9\x2a\xaa\x1a\ +\x78\xc2\xdb\x0c\x5e\x0d\x28\x8a\xe2\x42\x6b\x99\x53\xb8\xbe\x26\ +\x29\xb8\x7b\xa8\x71\x2e\xf0\xd6\x02\xaa\xda\x1e\x59\x79\x4f\xe1\ +\xc6\xba\x44\xa0\x5d\xde\x56\xe0\xc5\x00\x55\x4d\x06\x83\xe2\x6d\ +\x41\xf7\x96\x79\x89\x6c\xf0\xe0\xc1\x00\x55\x15\x63\x8a\x57\x15\ +\x79\xb0\xcc\x8b\xa0\x1a\xd9\xe0\xc1\xc3\x1c\x60\x8a\xe2\x39\x44\ +\x9e\x2a\x73\x21\x0f\x37\xdb\x85\xd3\x0a\xe8\x0f\x96\x1f\x43\xe5\ +\xc5\x3a\x1f\xf2\x70\xb3\x5d\x38\x33\xa0\x6f\x8a\x83\xa2\xfa\xe6\ +\x46\x25\xec\xe1\x66\xbb\x70\x66\x80\xd4\x1e\x68\xc0\xfa\xfe\x3e\ +\x82\xb5\xfe\x6c\x70\xd7\x02\x9b\x94\x79\x03\x67\x9b\x6d\xc3\x5d\ +\x05\x20\x4f\x52\xdb\xd3\x2b\x12\xc5\x23\xb7\xb3\xc1\x59\x82\x59\ +\x36\xf5\x01\xaa\x4f\x94\x39\x01\x14\x5a\x31\xbf\x83\x75\x7a\x87\ +\x7a\xbd\xf4\x0d\x81\xfd\x65\x4e\x00\xd4\x46\x6b\x82\xf3\x12\x4d\ +\xd3\xa9\x03\xc0\xeb\x15\x52\x04\xc4\xdd\x1b\x5d\x97\x70\x9e\x94\ +\x88\x68\x96\x4e\xed\x03\xde\xad\x08\x8a\x20\x71\x3c\x86\x2f\xc3\ +\x4b\x42\x22\x62\x7f\x39\xfd\xd3\x43\xc0\x87\x15\x41\x11\x90\x44\ +\x22\xea\x06\x6f\x77\x64\x76\x76\x76\xb8\xa3\x9d\xdc\x07\xf2\x65\ +\x55\x51\x71\xf9\x81\xc3\xb9\xc2\x6b\x22\x9d\x4e\xe7\x8c\xda\xe1\ +\x9d\x08\xdf\x56\x15\x11\x34\x8e\x76\xf0\x9e\x44\x9e\xe7\xbf\xeb\ +\x78\x74\x3b\xb0\x50\x11\x04\x41\x9a\x6f\x86\x20\x77\x21\xcf\xf3\ +\x53\xe8\xf8\x56\xe0\x44\x45\x50\x4d\xd6\x96\x88\xe6\x10\xac\x0c\ +\x7b\xbd\x5e\x3f\x11\xbd\x0d\xf8\xad\xaa\x68\x42\x83\x9b\x84\xa0\ +\x7d\x98\xa6\xe9\x77\xa8\xdc\x01\x9c\xa9\xe7\xa1\x0d\x99\x10\x7c\ +\x22\xea\xf5\xa6\xbe\x52\xd1\x7b\x80\x61\x99\x17\x48\x54\xc3\x9b\ +\xd0\xc8\x4c\x9c\xa7\xe9\x27\x2a\xfa\x00\xb5\xc3\x93\x08\x09\x68\ +\x50\x13\x1a\x5b\x8a\xf2\x34\x7d\x5f\x91\xc7\x37\x2a\x61\x4f\x90\ +\x8d\xae\xc5\x79\x36\x75\x08\x91\xe7\xeb\xbc\x2a\x4e\x3e\x83\xdd\ +\x0a\x1a\xdf\x8c\x64\xdd\xce\xcb\xa8\xbe\x56\xe6\x44\xfe\x69\x07\ +\xff\x68\xdc\x00\x11\xd1\x2c\xeb\x3e\x2d\xe8\x3b\x65\x5e\xd7\xcf\ +\x0d\xbe\xe3\x37\x6e\x00\xac\x1d\x9e\xd2\xb4\xfb\x88\x22\x73\x55\ +\x45\x05\xcf\x39\x46\x61\x00\x80\x88\x8c\xb0\xc3\xfb\x51\xbe\xa8\ +\x4b\x78\xcc\x33\x1a\x03\x00\xf2\x3c\x5f\x1d\x0e\x57\xf7\x82\x7e\ +\x53\x93\xbc\x2d\x8d\x51\x19\x00\x30\x33\x33\xf3\xc7\x68\xb8\x73\ +\x0f\xca\x0f\x21\xe2\x45\x67\x00\xc0\xae\x5d\x57\xfd\x6c\x6d\x6b\ +\x37\xb0\xe2\x3b\x56\x94\x06\x00\x4c\x4f\x5f\x6d\x04\xbb\x1b\xf8\ +\x75\x13\xd9\x59\x4b\x44\x6b\x00\x40\x96\x65\xdf\xdb\x84\x3d\xc0\ +\x9f\x65\xfe\xbc\xf9\x65\x06\x60\xba\xdb\xfd\x5a\x48\xee\x2a\xbf\ +\x62\x3b\x2f\x7e\x99\x29\x23\xcb\x3a\x9f\x09\x72\x00\x18\x83\x8c\ +\x13\x91\x97\x9a\xce\x69\x82\x09\x26\xf8\x7f\xe0\x6f\x3e\x50\x4e\ +\x18\x86\xf9\x70\xa3\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ +\x82\ +\x00\x00\x03\x61\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x13\x49\x44\x41\x54\x78\x9c\xed\ +\x9a\xbf\x6b\x14\x41\x14\xc7\xbf\x6f\x93\x70\x9e\x04\x1b\x31\x46\ +\x72\x9b\xdd\x8d\xb9\x42\x08\xd8\xda\xfb\x03\xb4\xb0\x93\x80\x5d\ +\x0e\x44\x25\x9d\x4d\xc8\x5f\x60\x2c\x85\x04\xd1\x22\xa5\x4d\x6c\ +\x44\x48\x04\xb5\xb3\xb0\x15\x52\x08\xd1\xec\xde\xde\x82\x78\x62\ +\xa1\xa8\xe7\x91\xdc\x8c\x4d\x08\x78\xbb\x77\x97\xdd\xb9\x97\xc9\ +\xb9\xf3\x29\xe7\xe6\xbe\xef\xbb\xdf\xdb\x9d\x7d\xcc\x0d\x60\x30\ +\x18\xf2\x0c\xa9\x0a\xd4\xeb\xf5\xd1\x46\xa3\x39\x2f\x81\x1b\x00\ +\x66\x00\x14\xd4\x6d\x29\xd1\x04\xb0\x49\xc0\x5a\xb1\x58\x58\x19\ +\x1b\x1b\xfb\xd9\x6d\xb2\x52\x00\xd5\x6a\xf5\xb2\x84\xb5\x0a\xa0\ +\xa4\xa2\xc3\x48\x44\x10\x15\xc7\x71\x5e\x75\x9a\x60\x65\x55\x0e\ +\x82\xb0\x22\x61\xbd\xc4\xd1\xbd\x78\x00\x28\x49\x58\x1b\x7e\x18\ +\xce\x75\x9a\x90\xe9\x0e\xd8\x0e\xc3\x2b\x96\xa4\x0d\x28\x04\x78\ +\xc8\xb4\x08\xe2\x6a\xd2\x9d\x90\x3a\x80\x7a\xbd\x3e\xfa\xbb\xd1\ +\xfc\x00\x60\xa2\x2f\xd6\x0e\x8f\xe8\x78\xb1\x70\xae\x7d\x4d\x48\ +\xfd\x0b\x36\x1a\xcd\x79\x0c\xde\xc5\x03\x40\x69\xcf\xfb\x3f\xa4\ +\x0e\x60\x6f\xb5\x1f\x48\x92\xbc\x67\x79\x86\x67\xfa\xe0\x45\x17\ +\x31\xef\xc3\x19\x44\xba\xbe\xe7\x5d\xc7\x56\xee\x2d\x54\x08\xaa\ +\x35\xd9\xe5\xe3\x98\xf7\x41\x59\xc5\xd9\x30\x01\xe8\x36\xa0\x1b\ +\x13\x80\x6e\x03\xba\x31\x01\xe8\x36\xa0\x9b\xdc\x07\xd0\xb3\x11\ +\x0a\x82\xe0\x0c\xac\xe1\xbb\x90\xf2\x22\x80\xd3\x3d\xe7\x57\x6b\ +\x1f\x15\xfc\x48\x10\x22\x08\xac\xef\xec\xfc\x79\x5c\x2e\x97\x7f\ +\x28\x68\x1d\x88\xae\x5d\x5b\x18\x86\xd7\x85\xa4\x55\x00\x27\xb9\ +\x8d\x24\xe0\x4b\x41\x37\x3d\xaf\xf4\x2e\xcd\x97\x7a\x74\x82\xb1\ +\x4e\xb5\xe3\x23\xe0\x57\x6b\x4b\x42\xd2\x73\xe8\xb9\x78\x00\xf0\ +\xc8\x92\x6f\xfd\x30\xba\xc3\x59\x24\x31\x00\x3f\x0c\x67\x09\x58\ +\xe0\x2c\x7c\x40\x86\x48\xca\x65\xdf\x8f\x2e\x70\x15\x88\x05\xe0\ +\xfb\xbe\x4b\x92\x9e\x70\x15\xcc\xc0\x10\x59\xf2\xe9\xd6\xd6\xd6\ +\x09\x0e\xf1\xf8\x1d\x60\x0d\x2f\x02\x60\x29\xa6\x80\x37\x32\x72\ +\xec\x36\x87\x70\x2c\x00\x02\xae\x71\x14\x52\xc6\xe2\xf1\x95\xb4\ +\x06\x1c\xcd\x5d\x5e\xc9\xe3\x2b\xf5\x86\xc8\x90\x85\x32\x87\x91\ +\x5d\x60\x9a\x04\x36\xba\x4c\x61\xd9\x68\x49\x1d\x80\x6d\xdb\x2a\ +\x8d\x4e\x47\x6a\xb5\x1a\x5a\x1c\xc2\x3d\xc8\x7d\x2b\x6c\x02\xd0\ +\x6d\x40\x37\x26\x00\xdd\x06\x74\x63\x02\xd0\x6d\x40\x37\x26\x00\ +\xdd\x06\x74\x63\x02\xd0\x6d\x40\x37\x26\x00\xdd\x06\x74\x93\xe5\ +\x7c\x80\x2e\xce\xf6\xda\xf1\x3d\x00\xcd\xf6\x81\xbc\xdd\x01\x9b\ +\xed\x03\xb9\x0a\x80\x80\xb5\xf6\xb1\x3c\x05\x10\x15\x8b\x85\x95\ +\xf6\xc1\xbc\x04\xd0\x22\x88\x4a\xd2\xb9\xe1\x3c\x04\xd0\x92\x24\ +\x6f\x75\x3a\x2f\x3c\x48\x6f\x81\x2c\x44\x04\x51\x71\x27\x3b\x1f\ +\x96\xfe\x1f\x03\xd8\x3f\x2e\x5f\x28\x8c\x2c\x8f\x8f\x8f\xff\xea\ +\x36\x39\xb6\xd5\xdc\x87\x77\x2d\x17\x9f\x5c\xc7\x9e\xee\xb7\x68\ +\x7c\x0d\x90\xf8\xda\xef\x22\x7d\xe2\x0b\x87\x68\xd2\x22\xf8\x9a\ +\xa3\x90\x32\x44\x6f\x38\x64\x63\x01\x08\x41\x0f\x00\xec\x70\x14\ +\x53\xe0\x1b\xc4\xee\x23\x0e\xe1\x58\x00\x53\x53\xa5\xf7\x92\xe8\ +\x28\x9c\x0d\xd8\x87\x60\xcd\xb9\xae\xfb\x99\x43\x3b\xb1\x0f\x70\ +\xed\x89\x87\x00\x9e\x71\x14\x4c\x0b\x01\x4b\x8e\x33\xf1\x82\x4b\ +\x3f\x31\x00\x22\x12\xce\x64\x69\x56\x12\xdd\x83\xbe\xc7\xe1\x3b\ +\x81\x66\x1d\xc7\x5e\xe4\x2c\xd2\xf3\x1f\xd7\xed\xed\xe8\xbc\x65\ +\xc9\x05\x00\x97\x40\x38\xc5\x69\x66\x8f\x48\x02\xeb\x10\xbb\xf7\ +\x3d\xcf\x0b\x0e\xa1\x9e\xc1\x60\xc8\x31\x7f\x01\x50\x46\xc4\x66\ +\xcc\x07\x14\xea\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\ +\x00\x00\x00\x97\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x49\x49\x44\x41\x54\x58\x85\xed\ +\xce\xc1\x09\xc0\x30\x0c\x04\x41\xc9\x49\xdf\x71\x4d\x6e\x48\x08\ +\xd5\x11\xec\x22\xce\xa0\xcf\xce\xff\x8e\x35\x13\x44\xd6\x8c\xac\ +\xa9\x7c\x0c\x65\x7c\x03\x01\x04\x10\x40\x00\x01\x04\xb4\x07\xbc\ +\xea\x81\x9b\x7d\x91\xd5\x13\xe0\xfb\x59\xdb\x7f\xe5\x02\x00\x00\ +\xf4\x3b\x2b\x9a\x0d\x40\x4d\xe0\x05\x89\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x85\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x37\x49\x44\x41\x54\x58\x85\xed\ +\xce\xc1\x0d\x00\x30\x08\x03\x31\xd4\xc9\xd9\x14\x21\x16\xe9\x10\ +\xf0\xf4\xfd\x13\x39\x62\x51\xf5\x64\xf5\xe4\xe6\xe3\x6d\xc6\x17\ +\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x7c\ +\x9f\x23\x06\x85\x22\x0f\x12\xcb\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x05\x38\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\xea\x49\x44\x41\x54\x58\x85\xe5\ +\x97\x5b\x6c\x54\x55\x14\x86\xbf\xb5\x67\x3a\x20\x24\xe5\x22\x46\ +\x04\x2a\xd0\x80\x29\x04\x4c\x04\x25\x01\x82\xa2\xd0\xd6\x8a\x40\ +\x29\x39\x1a\x52\x22\xf6\x02\x21\x26\xfa\x60\x82\x82\x10\x27\x0d\ +\x0a\xf5\xc5\x04\x45\x94\xda\x16\x8d\xf2\xc2\xf4\xa2\x6d\x28\xd0\ +\x01\xd2\xbe\x80\x04\x6b\x43\xc0\x42\x62\x2c\x17\x4b\xab\x31\x10\ +\x30\x8a\xb4\x9d\xd9\xcb\x87\x99\x29\x67\x7a\x6f\xf1\x8d\xf5\x74\ +\xf6\xda\xeb\xfc\xff\xbf\xd7\xd9\x6b\xaf\x7d\xe0\x41\x37\x19\x4a\ +\x70\xda\xea\x9c\x24\xeb\xf1\x66\x8a\xb1\xcb\x51\x49\x02\xa6\x00\ +\x46\xe0\xba\x42\x0b\xaa\xf5\x88\xb7\x32\x58\xbe\xff\x97\xff\x55\ +\x40\xba\x93\xb7\x20\x6c\x4d\xa1\xa0\xcf\x0f\x12\xf7\x2c\xa2\xdb\ +\x82\x65\x25\x27\xee\x4b\xc0\x72\x67\xd3\x18\xb1\xf6\x73\x60\x5d\ +\xd4\xd5\xa6\x50\x6d\xd0\x23\x61\xa4\xd9\x67\xc2\x6d\x1d\xa1\xb0\ +\xf5\x9a\x11\x13\xc3\x6a\xa7\x89\x48\x1a\xb0\x1a\x98\x1a\x8d\xaf\ +\xb1\x9d\xe4\x9e\xa8\x2a\xfe\x63\xc8\x02\xd2\x9d\xbc\x19\xd6\x4a\ +\x15\x30\x2b\x42\x2c\xfe\xd0\x8d\x49\x07\xea\xea\x0a\x42\xfd\x89\ +\xf6\xfb\xfd\xe6\xd4\x85\xeb\xaf\x02\x1f\x00\xc9\xc0\x35\x63\xed\ +\xaa\x63\x95\xa5\xe7\x06\x2d\x60\x59\x56\x4e\xb2\xc1\x73\x06\x61\ +\x82\xc0\xf7\x9e\x91\xff\xbe\x76\xe4\xe0\xc1\xbf\xfa\x23\xee\x6e\ +\x19\x19\x6f\x8e\xe8\x1c\x75\x77\x9f\xa0\xb9\xc0\x3f\x8a\x2e\x39\ +\x5e\x5e\xd2\x38\xa0\x80\x8c\xec\xec\xc4\xd0\xdd\x51\xa7\x41\x67\ +\x83\xee\x59\x34\x67\xca\xdb\x05\x05\x05\x76\x28\xe4\x6e\xfc\xb4\ +\xac\xbc\xad\x2a\xb2\x0b\x68\x31\x6a\x16\x1c\xab\x28\x6a\x73\x07\ +\x78\xbb\xbf\x11\xba\x3b\x6a\x6f\x84\x9c\xea\xde\xc8\xd3\x56\xe7\ +\x24\xa9\xd7\x9b\x0f\xfa\x12\xf0\xb8\x80\x55\xf4\x2a\x22\x87\x8d\ +\x35\xc5\xdd\x08\xb4\xb6\xa2\xa4\x30\x35\x2b\x3f\x19\x21\xdf\x1a\ +\xfb\x2d\xb0\x1c\xd0\x5e\x33\x90\xba\x36\xf7\x69\x30\x67\x81\x3f\ +\xd5\x98\x99\xc7\x03\x45\xb7\x63\x73\x7e\xbf\xdf\x9c\x3e\xdf\xf2\ +\xae\x8a\xbc\x0f\x8c\xec\x63\xc5\xff\x08\xbc\x57\x5b\x5e\xfc\xa9\ +\x9b\xc4\x71\x1c\xdf\x2d\x3b\xe6\x1c\x90\x02\xac\x08\x96\x17\xd7\ +\xc4\xe6\x4c\x5c\xbe\x30\xbb\x01\x54\x65\x67\x77\xf2\x53\x17\xae\ +\x7f\x1d\x4d\x65\x5f\xe4\x00\xa3\x15\xf6\xa4\xae\xcd\xdf\xe7\x5e\ +\x5c\x20\x10\xe8\x50\x61\x7b\x74\x58\xe8\x9e\xeb\x12\x90\x9e\xb5\ +\xe9\x31\x85\x65\xc0\xcd\x71\x9e\x5b\xfb\xdd\xa8\xa7\x2e\xb4\xec\ +\x00\xd6\xdf\x5b\x53\x3f\x16\x89\xd9\x9c\xba\x76\xe3\x5b\x6e\xf7\ +\xf1\xb2\xe2\x4a\xe0\x12\x30\x37\x7d\x4d\xee\x93\x3d\x04\x28\x76\ +\x65\x44\x99\x1c\x0e\x04\x02\x1d\x31\xff\xb2\xac\x9c\x64\x90\x1d\ +\xc0\xe0\x8e\xad\xae\x18\xfd\x30\x75\x55\xee\xa4\x38\x69\x22\x55\ +\x00\xea\x31\x6b\x7a\x0a\x10\x96\x02\xa8\xda\xa3\x6e\x3c\x63\x3c\ +\x6f\x00\x09\x83\xa0\xee\x6e\xa3\xd5\x6b\x36\xc6\x69\x0b\xeb\x31\ +\x00\xab\xbc\xd0\x43\x00\xaa\x49\x11\x75\x7a\x39\x0e\x46\x59\x31\ +\x0c\xf2\x08\xa1\xf0\xb2\x7b\x6c\xd4\xdb\x0c\x20\x91\x1e\xd2\x4d\ +\x80\x44\x9c\x09\x9d\x3e\x77\x19\x09\x91\xd3\x6c\xb8\x36\xd5\x3d\ +\x90\xf6\x84\x18\xf6\xe4\x28\x76\x7c\x15\x74\x37\xbf\xdf\x2f\x03\ +\xc5\x0c\x60\x9e\x01\xb0\xdd\xe0\x72\x1d\x20\x64\x42\x13\x63\x9e\ +\x82\x82\x02\x2b\x70\xf5\x3e\x04\x5c\x73\x0f\xda\x1f\xba\x13\xc5\ +\xd6\xd6\xd8\x01\xe7\xde\x03\xbf\x01\x88\x30\x3d\x0e\x42\xa8\x61\ +\xb8\xa6\xf1\xef\x26\xa0\xc9\x51\x7f\x4b\xcc\x77\x4f\x80\xa1\x2e\ +\xfa\x94\xee\x7e\x29\x2c\xe1\x2f\x80\xe1\xf4\x82\x0e\xf1\x50\x1c\ +\xa7\x47\x4c\x1a\x00\x62\x4e\xf6\x14\xd0\xa1\xd5\x51\x75\x2b\xe6\ +\x6f\xda\xd4\x55\x76\x27\x02\x07\x9a\x44\xf8\x24\x3a\x37\xa0\xc5\ +\x42\x54\xd9\x55\x1b\x28\x76\x57\x94\x28\xb2\x2a\xca\x5a\xd9\x43\ +\x40\xb0\xaa\xb4\x15\xe1\x24\xc2\x84\x71\x37\x6c\xbe\x1b\xf4\xc6\ +\x78\xf3\x0e\x50\x33\x98\x83\x48\x22\x2a\x02\x8b\xe7\x4e\xde\xe9\ +\xf6\xa7\x66\x6d\x5c\x19\x6d\x72\x3f\x07\x03\x5f\x76\xdd\x0d\xe2\ +\x76\xb8\xb5\xb2\x15\x40\x04\x7f\x46\x76\x76\x62\xcc\xdf\x50\x54\ +\xd4\x79\xf3\x61\x93\x09\xba\x87\xfe\x3f\x47\x08\x65\xd7\x58\xcf\ +\xed\x75\xee\x2e\xea\x38\x8e\x0f\x61\x77\x44\xa0\x6e\xc3\x95\xcb\ +\xb8\x32\xb9\x7c\xf1\xa7\xd6\xe4\x59\xf3\x66\x0a\x2c\xd4\x50\xc2\ +\xec\xf5\xaf\xac\x3c\x54\x5f\x5f\xaf\x00\x6d\x0d\x0d\xb6\xf9\x62\ +\xe3\xd1\x19\x29\x4f\x55\x20\xa2\xc0\x23\x40\x22\x60\x05\x2e\x83\ +\x7e\xe3\x31\x9a\x5b\x5b\x5e\x72\xa8\xa9\xa9\xc9\xfd\xb1\x64\x72\ +\xca\xe2\xcf\x10\xcd\x00\xea\x82\xe5\x25\xdb\xdd\x9c\x3d\x92\x1a\ +\xbd\x07\xfe\x00\xa4\x80\x7e\xbc\x68\xce\x94\x2d\x7d\x5d\x48\x1c\ +\xc7\xf1\x00\x04\x02\x81\x70\x1f\x19\x91\xd4\xac\xbc\x2d\x88\x7c\ +\x84\xd0\x4a\x87\x7d\x26\x58\x55\xda\xda\xaf\x00\xe8\xba\x0f\x9e\ +\x01\xc6\x03\x15\x9d\xc6\xb7\xa1\x2e\xb0\xef\xef\x3e\x48\x7a\x35\ +\xc7\x71\x7c\xb7\x6d\xe2\x5e\x45\x36\x02\x77\xc0\x3e\x17\x2c\x2f\ +\xfd\xb1\x7b\x5c\xaf\x27\xd5\xaf\x4d\x8d\x37\xa7\xa7\xcc\xff\x0e\ +\x21\x4d\x60\x89\x47\xc3\x1b\x66\xcc\x9a\x77\x3b\xe9\xd1\x95\xe7\ +\xaf\x5c\xa9\xef\xb7\x24\xfd\x7e\xbf\x49\x98\xf0\x84\xd3\xae\xbe\ +\x32\x90\x54\x22\x57\xb1\xb4\xda\x8a\xe2\x86\xde\xe2\xfb\xdd\xd7\ +\x4b\x33\x5f\x1f\x9b\x60\xbc\x45\x08\x4e\xd4\xd5\x22\x50\x0d\x7a\ +\x44\x30\xcd\x18\xdb\xd6\xde\x19\xb6\x3e\x8f\x6f\xa2\x45\xa7\x02\ +\xe9\x82\xae\xa6\xab\x7f\x48\x6d\xa7\xe9\xdc\x50\x17\xf8\xea\xf7\ +\xbe\x38\x06\xf5\x63\xb2\xcc\xc9\x5d\x68\xac\x29\x04\x9e\x1d\x4c\ +\x3c\xd0\x88\xd8\xad\xc1\xb2\xd2\xda\x81\x02\x87\xf4\x6b\xf6\x62\ +\xe6\xe6\x69\x21\x13\xca\x14\x23\xcb\x45\x35\x49\x23\x6d\xd5\x03\ +\xb4\x00\x2d\xa2\x5a\x8f\x78\x2a\x6b\xcb\x8b\x2e\x0d\x05\xf7\xc1\ +\xb6\xff\x00\xf7\x80\xda\xb0\x80\x19\xdd\x42\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xcc\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x7e\x49\x44\x41\x54\x78\x9c\xed\ +\xd9\x41\x0d\xc0\x20\x14\x05\x41\x5a\x4d\x78\xc2\x4f\x65\xd5\x14\ +\x95\xb1\x4d\x98\x31\xf0\x5f\x36\xdc\x18\x23\x34\xd7\xb3\xe7\x7a\ +\x76\xb9\xe1\x2e\x8f\xff\x81\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\ +\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\ +\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\ +\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\xda\xf1\ +\x01\xae\xf2\x78\xfd\x35\x3e\x46\xff\x02\xde\xf8\x3e\x00\x00\x00\ +\x00\x00\x00\x00\x9c\xe0\x03\xda\xaf\x07\x8e\xa0\xaf\x15\x04\x00\ +\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x68\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x1a\x49\x44\x41\x54\x58\x85\xed\ +\xc1\x01\x01\x00\x00\x00\x82\x20\xff\xaf\x6e\x48\x40\x01\x00\x00\ +\x00\xef\x06\x10\x20\x00\x01\x47\x01\xa0\x88\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\xf7\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xa9\x49\x44\x41\x54\x58\x85\xed\ +\x96\xb1\x4a\xc3\x50\x14\x86\xff\x93\x64\xb1\x05\x5f\x40\xd4\x37\ +\xa8\x60\xa1\x11\x41\x7c\x03\x29\x0d\x2a\x5d\x7c\x01\x5d\x04\x11\ +\x97\x4e\x1d\x1c\x44\x97\xe2\x13\x38\x59\x49\x3a\x17\x17\x41\x0a\ +\x86\x52\xb0\x8f\x50\x3b\xb8\xb8\x28\xd4\xa9\xb9\xc7\xa1\x26\x36\ +\xb5\xb7\x4d\x4c\x6b\x86\xf6\x9f\x6e\x92\x73\xcf\xff\xe5\xdc\x7b\ +\x0f\x17\x98\x75\xd1\xa8\x8f\xa9\x2a\x27\x13\x1d\x51\x64\x50\x0e\ +\xc0\x6a\x44\xaf\x16\x83\x4d\x47\x53\x0a\x8d\x1d\xfa\x1c\x0b\x90\ +\xaa\x72\x72\xa1\xc3\x35\x00\x6b\x11\x8d\x07\xd5\xec\x6a\xb4\xe9\ +\x42\x28\xb2\xa8\x44\x47\x14\xa7\x60\x0e\x00\x6b\x6a\x57\x14\xdd\ +\x07\x29\xc0\x77\xd9\xa7\x22\x02\x19\xee\x58\x1b\x11\xe7\x5b\x73\ +\x3b\xa7\x8c\xdc\x2f\xe3\xa4\x5b\x82\x87\xe5\x96\x56\xe0\xbf\x34\ +\x07\xf8\xb5\x07\xd2\x65\x5e\xd1\x54\x6c\x03\xec\x7b\x9f\xa9\xf0\ +\x91\x2c\x09\x09\x08\x02\x9a\xcb\x0e\x9e\xee\xf6\xc8\xf9\x33\x80\ +\x6e\xf1\x09\xc0\xe7\xc3\xc0\x88\xb9\x24\xcd\x42\x3d\xdc\x17\x0d\ +\x8f\x69\x93\xf7\x1b\x06\xbd\x06\x05\xf0\x96\x20\x53\xe1\x3c\xc0\ +\x17\xc3\xcc\x43\x68\x4b\x23\xbe\xdd\x2d\xb3\x1a\x1a\x80\x98\x4f\ +\x23\x18\xfb\x20\xda\x2a\x36\x82\x06\xf7\xff\xed\x40\xd7\xe3\xeb\ +\xe0\x9e\x94\x05\xb0\xe4\xcd\xec\xe5\xaa\x85\x05\xf0\x35\x1a\x3b\ +\xa7\x4a\x37\xdd\xa0\x74\xcb\x01\x40\x87\x1e\x80\x12\xfc\x74\xc5\ +\x7e\x0c\xe7\x00\x73\x80\xd8\x01\xa2\x74\x3d\xa9\x88\xb9\xa4\x5b\ +\x42\xde\xba\x81\x96\x3b\x88\xa5\x02\x0c\x36\xe3\x04\x68\x3a\x9a\ +\x52\x88\x03\xa0\xc5\xe0\xab\xfe\x1b\x31\xd0\xd7\x7e\x75\x4b\xbc\ +\x03\x58\x9c\x88\x15\xd3\x81\x6d\xd0\x4d\x90\xd0\x9f\x0a\x30\xee\ +\x27\x62\x0e\x74\x85\x8a\x87\xa0\xc1\x1e\x80\x50\xe9\x18\xc0\x5b\ +\x64\x7b\xa6\xb3\x7a\x96\xda\xa1\x01\xea\x59\x6a\x0b\x85\xd6\xc1\ +\x30\x01\x7c\x84\xb5\x05\xf0\x0c\x50\xde\x36\xe8\x32\xe4\xdc\x19\ +\xd7\x17\x91\x1d\x7b\x32\x62\xe5\x6b\x14\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x94\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x46\x49\x44\x41\x54\x58\x85\xed\ +\xd1\x21\x4b\x43\x51\x18\xc6\xf1\xff\x7b\xc7\x8a\x41\x04\x41\xcb\ +\x76\xdd\xf6\x09\x04\x6d\x36\x93\xa8\x6b\x82\x49\xab\x82\xdf\xc1\ +\x62\x31\xf8\x11\x64\x20\x18\x0c\x26\x41\x10\x8b\xa0\x08\x86\x15\ +\xc1\xec\x7d\xcf\x3d\xd7\xee\x98\x60\x71\x7b\x2d\x1a\x14\xb6\xbb\ +\xbb\x24\x78\x7e\xf1\xf0\xf0\xf0\x1c\x5e\x08\x82\x20\x08\xfe\x3b\ +\xc9\x0b\x68\xea\x8f\x31\x16\x22\xb1\xad\x38\x8e\x9f\x46\x29\x4d\ +\x92\xa4\x26\x51\xe9\x14\xa4\x33\x17\x57\xd6\x45\xc4\x06\x65\xa3\ +\xdc\x36\x63\x0a\x98\xef\x9b\xdc\xab\x66\xcb\x79\x71\xe7\xdc\x82\ +\x44\xe5\x07\x90\x25\x8c\xe9\xbc\x7c\xee\x80\x52\xc4\x16\x70\x0e\ +\x4c\x22\x76\xe5\x5c\xb6\x3d\x28\xab\x9a\xad\x19\xd1\x2d\xd8\x2c\ +\x70\x63\xf6\xb1\x32\xec\xf7\x23\x0d\xa8\x56\xab\xef\x73\x71\x65\ +\x13\xe1\x08\x28\x1b\x76\xe2\x9c\xdf\x37\xb3\x1f\xe7\x4b\xd2\x6c\ +\x17\xb1\x0b\x60\x02\x38\x7d\xeb\x76\x56\xea\xf5\xfa\x6b\x5e\x7f\ +\x21\xaa\xe9\x9e\x3a\xdf\x53\xe7\x4d\x35\x6b\xb5\xdb\xed\xb2\x99\ +\x45\x89\xf3\x87\xea\xbc\xa9\xf3\xa6\x69\x76\xf0\x7b\xdc\x30\x23\ +\x07\xbf\x39\xf7\xd2\x34\xfa\x67\xc0\x84\xc1\x9d\x40\x17\x58\x05\ +\x3e\x30\xdb\xa9\xd5\xe2\x56\x91\xbe\xc2\x03\x00\xd2\x34\x5d\xec\ +\x9b\x5c\x02\x33\x5f\x4f\xdd\xbe\xd8\x46\x23\x8e\xaf\x8b\x76\x8d\ +\x35\x00\x40\x55\xeb\x48\xe9\x59\xc0\xf7\x7a\xd2\x6c\x34\x2a\x8f\ +\xe3\x76\x8d\xcd\xcc\xa4\xc8\xbd\x83\x20\x08\x82\x3f\xe9\x13\xfa\ +\xca\x87\x49\xdf\x83\x3a\x35\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ +\x42\x60\x82\ +\x00\x00\x04\x83\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x35\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4b\x88\x1c\x55\x14\x86\xbf\x53\xdd\x93\x31\x24\x41\x88\xf1\ +\x85\xa8\x2b\x51\x5c\x08\x43\xb7\x11\x11\x64\x14\x8d\x06\x31\xf8\ +\x00\x5d\x89\x4e\x30\xd3\x1d\x92\x9e\x76\x40\x11\x7c\xd0\x36\x89\ +\x98\x80\xf8\xe8\x36\xa6\x7b\x0c\x18\x17\x06\x75\x15\x06\x34\x3a\ +\xba\x48\x40\x90\xcc\x74\xe2\x03\x71\x21\x88\xb8\xd0\xa8\x84\x28\ +\x9a\x09\x66\x66\xba\x7e\x17\x6d\xa0\xaa\x18\x83\xd1\x7a\x5c\x4c\ +\xff\xcb\xff\x40\xdd\x73\xbf\x3a\x7d\xef\x3d\x55\xd5\xd0\x57\x5f\ +\x7d\x9d\xcd\xb2\xac\x13\xf8\xa7\x2a\x8e\x36\x6b\x66\x7a\x4a\x60\ +\x48\x5b\x3b\x13\xd5\x67\xe2\xb8\xae\x17\xc7\x45\x92\x56\x61\xf4\ +\xe5\x9b\x30\x6a\x82\x3c\x90\xc3\xec\xe9\xb8\xae\xed\x3c\x80\xd5\ +\xa5\x66\xd1\xcc\x26\x41\xc1\x6a\x8d\x2d\x6f\xa7\x01\x14\x46\x9b\ +\x57\xf9\x68\x1f\xb0\x3c\xe8\x0b\xfc\xb8\xc6\x70\x16\x40\x61\xf4\ +\xa5\xcb\xcc\x34\x05\xac\x8a\xc6\x0c\x14\xd7\x38\xf9\xb8\x2e\x14\ +\xa7\x86\x46\x1a\xe7\x9b\x31\x05\x5c\x9a\xf4\x58\xce\x55\xc0\x0d\ +\xeb\xb7\xaf\xc8\x2d\xe1\x3d\xe0\xca\x34\xc6\x73\x0a\xc0\xf0\x43\ +\xaf\x9f\x33\x37\xb0\x74\x2f\x50\x0c\xfa\x8a\xb1\xe4\xa3\x72\x06\ +\xc0\x70\xad\x96\xff\x7d\xf0\xf8\x1e\xc1\xcd\x91\x90\x2c\xc6\x45\ +\x2f\x2a\x47\x00\xc8\x8e\x1f\x39\xaf\x6d\xe8\xee\xb0\x6f\x22\xc1\ +\xc9\x83\x23\x00\x8a\xa5\xe6\x76\x8c\xf5\x41\x4f\x98\x40\x89\x4e\ +\x1e\x1c\x00\x50\x28\x35\x1e\x07\x1e\x8b\xfa\x96\xc2\xe4\x21\x63\ +\x00\xd7\x96\x1b\x1b\x0c\xb6\x2d\x12\xea\xa6\x95\x43\x66\x00\x8a\ +\xe5\xe6\xbd\x12\xad\xa8\xaf\x94\xee\xfc\x29\x65\x02\xa0\xb8\xa1\ +\x71\x0b\xd2\x9e\x45\xc6\xf7\xad\xb7\xf0\xa5\xa6\xd4\x01\x14\xcb\ +\x8d\xd5\x78\xec\x05\x96\x04\x7d\x19\x3e\x09\xee\xf7\x7f\xa7\x54\ +\x01\x5c\x57\x6a\x5c\x8d\xd8\x07\x2c\x8b\x84\x7c\x53\xfa\x93\x87\ +\x14\x01\x0c\x6d\x7a\xe5\xf2\x05\x6c\x0a\x58\x19\xf4\xff\xea\xec\ +\x32\x99\x3c\xa4\x04\xe0\x9a\xf2\xce\x0b\xbc\x05\xff\x43\x43\x97\ +\x04\x7d\x81\x1f\x67\x67\xf7\x6f\x94\x78\x37\x58\x18\x6d\x9f\x6b\ +\x3a\xf9\x3e\x70\x45\xd0\x57\xef\x88\x9b\xe9\xe4\x21\xe1\x0a\xb8\ +\x7e\xfc\x85\xa5\x66\x73\x93\xc0\x50\x28\x20\x4b\xf4\x7c\x7f\x26\ +\x4a\x0c\xc0\x70\xad\x96\x9f\x9f\xcd\xbf\x05\xba\x31\xe8\xab\x77\ +\xca\x75\x62\xf2\x90\x14\x80\x5a\xcd\x9b\xfd\x69\xd5\x2e\x8c\x75\ +\x41\x5b\xb8\x73\xe7\x4f\x29\x01\x00\xb2\xe2\x91\x95\xcf\x4b\x7a\ +\x30\xec\xbb\x37\x79\x48\x60\x11\x2c\x96\x1b\x4f\x20\x1b\x0f\x99\ +\x12\x98\x7b\x93\x87\x98\x2b\xa0\x50\x6a\x96\x91\x6d\x0d\x99\x02\ +\x33\x4b\xad\xb9\x39\x53\xc5\x06\xa0\x58\x6a\x6c\x33\xb4\x33\xea\ +\xcb\xf0\x33\xdf\xeb\x4e\xa3\xf8\x2a\x20\xf2\x40\x03\x7a\x9d\x9d\ +\x0b\x7b\xfd\xe9\x14\x1f\x00\xa5\xd7\xc3\xc7\xa9\xd8\x00\x98\xa9\ +\x4a\xe4\x6e\x1b\xe6\xb9\xfe\xfa\x35\x36\x00\x33\xad\xea\x3b\x48\ +\x95\xa8\x2f\x91\x73\x19\x42\xac\xbb\x40\x67\xa2\xba\xc3\xa0\x16\ +\xf4\x0c\x40\xca\xb9\xfa\x26\x3e\xf6\x83\xd0\x4c\xbb\xb2\x05\xac\ +\x19\x76\x0d\x50\xe6\x0f\x60\x17\x53\x02\x49\x99\x3a\x17\x1d\x7d\ +\x44\xf0\x66\x34\x90\xcc\x78\xff\x4d\xc9\x24\x54\xaf\xfb\x68\x70\ +\x04\x78\x37\x12\x31\xe4\x16\x84\xc4\x92\x39\x34\x51\x9a\x97\x06\ +\xef\x03\x3e\x0e\x05\x0c\x03\x73\x06\x42\xa2\x89\x1c\x9a\x28\x9d\ +\x58\x38\xd9\xbd\x53\xf0\x79\x38\x22\x67\x7e\x0e\x89\x27\xf1\xd9\ +\xee\xf1\x5f\xbd\x5c\xee\x76\xe0\x9b\x48\xc8\x7a\xd5\x90\xad\x52\ +\xb9\x0b\x33\xaf\x6e\xfa\xd1\xeb\xda\xad\x88\x1f\x42\x01\xe1\x29\ +\x63\x08\xa9\x95\xe1\xf4\xae\xca\xb7\x78\xba\x0d\xf8\x25\xe8\x9b\ +\xf0\x7a\x8f\x0a\xb2\x51\xaa\xbf\xc3\x4e\xab\xfa\xa5\x87\x77\x07\ +\x70\x22\x14\x90\x79\x22\x1b\x08\xa9\x2f\x44\xd3\xed\xcd\x9f\xf8\ +\x66\xf7\x00\xf3\x41\xdf\x30\x4f\x19\x54\x42\x26\x2b\xf1\xe1\x56\ +\xe5\x03\xc3\x1e\x20\xda\x3c\xc9\x3c\xa5\x7c\x66\xce\x6c\x2b\x9a\ +\x69\x57\xde\xc6\xd8\x18\xf5\x4d\x78\x69\x12\xc8\x74\x2f\xee\xb4\ +\xc6\xda\x88\x27\x43\xa6\x81\xa4\x5c\x5a\x39\x64\x7e\x18\xe9\x4c\ +\x54\x9e\x43\x7a\x31\x64\x9a\xa1\x94\x4e\x8b\x99\x03\x00\x53\xe7\ +\xe2\x63\x8f\x9a\xd9\x1b\x21\x17\xa5\xd2\x37\x38\x00\x00\xa8\xd7\ +\xfd\x65\x17\x1e\x7d\x18\x31\x19\xf2\x2d\xf9\x0e\xd2\x0d\x00\xc0\ +\xfe\x7a\x7d\x61\xf9\xdc\x8a\xfb\x31\x0e\x44\x42\xa6\x04\xf3\x74\ +\x06\x00\xc0\xfe\xdd\x23\x7f\xe4\x06\x58\x07\x1c\x0e\xfa\x96\xe0\ +\xd6\xe8\x14\x00\x80\x83\xcd\xb1\xdf\xe6\x6c\x60\x2d\xf0\x75\x1a\ +\xe3\x39\x07\x00\xe0\x8b\xd6\xc6\x9f\xbb\x79\x6f\x8d\xb0\xef\x93\ +\x1e\xcb\x49\x00\x00\x9f\xee\xd8\xfc\x5d\x1e\xad\x01\x8e\x45\x63\ +\x71\x9e\x16\x9d\x05\x00\x70\xb0\x3d\xf6\x15\xc6\x5a\x60\x36\xe8\ +\xdb\xd9\xf2\x97\x19\x80\x4e\x6b\x6c\x1a\x9f\xbb\x14\xf8\x7e\x30\ +\xce\x8f\x29\x9d\x07\x00\xd0\x79\x6d\xec\x23\xd0\x16\xb0\xae\x89\ +\x2e\xe6\x3d\x9b\x75\x4e\x7d\xf5\xd5\xd7\xff\x43\x7f\x02\x97\x76\ +\x3e\x83\x62\x89\x8e\x83\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ +\x60\x82\ +\x00\x00\x00\x89\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3b\x49\x44\x41\x54\x58\x85\xed\ +\xcd\xb1\x11\x00\x10\x10\x05\xd1\x4f\x21\x28\x45\xa2\x6b\x33\x5a\ +\x31\x14\x72\x22\xa1\xf4\x12\xfb\xa2\xcd\x56\x02\x00\xe0\x77\xe1\ +\xc6\x5c\x7b\xc8\x54\x7d\xb6\xd6\x4b\x4e\x4d\x92\xa2\xcf\x10\x00\ +\x00\xe0\xed\x00\x5a\x36\x07\x04\x97\xc1\x22\x16\x00\x00\x00\x00\ +\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\xca\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\x7c\x49\x44\x41\x54\x58\x85\xed\ +\x97\x4b\x72\xd3\x40\x14\x45\xcf\x73\x32\x00\xb6\x10\x59\x2d\xcd\ +\x60\x0b\x6c\x81\x01\x90\x00\x81\x90\x8a\xf3\x71\x15\x2c\x20\x55\ +\xac\x81\x61\x66\x0c\x20\xc4\xf9\x3b\x21\x14\x55\xac\x81\x35\xc0\ +\x08\xb7\x24\x03\x3b\x00\x06\xc4\x8f\x41\xe4\x20\xeb\x63\x49\x2e\ +\x33\x82\x1e\x59\xaf\xba\xef\x39\x7e\x6a\x5b\x2d\xf8\xd7\x87\x0c\ +\x3f\x58\xfb\xe5\xa6\xca\xe0\x85\xc0\x55\x94\x67\x9e\xd7\x7c\x3b\ +\x4d\x90\xb5\xd1\x3c\xc2\x73\xe0\xa7\xd0\x78\x6a\xcc\xdc\x87\x51\ +\x81\x20\xfa\x08\x5c\x8f\x2f\x07\x2a\xba\xe4\xbb\x6e\x77\x1a\xf0\ +\x5e\x18\x3e\x14\x95\x03\xa0\x11\x97\x3e\x79\xa6\x79\x83\x44\x01\ +\x90\x2b\x89\x35\x0d\x51\x39\xec\x85\xe1\xe2\x5f\x80\x83\x70\xed\ +\x12\x74\x59\x54\xdd\x04\x06\xd3\x94\xe8\x85\xe1\x62\x06\x0e\x03\ +\x51\xd9\xcc\x08\x78\x5e\xf3\x4c\x45\x97\x73\x24\x0e\x26\x91\x88\ +\xe1\x87\x19\x38\xb4\x8c\x71\x4e\x33\x02\x00\xbe\xeb\x1e\xe5\x48\ +\xcc\xd4\x95\x28\xfc\xe6\xd0\x32\xa6\xb9\x9f\x9c\x2b\xe4\x0c\x6b\ +\xa3\x25\x84\xbd\x54\xc0\xb9\x20\x4b\xc6\x38\x27\xe3\xe0\x41\xd0\ +\x7f\xa0\xe8\x21\x30\x53\x06\x2f\x14\x98\x54\xa2\x00\xae\x02\x2b\ +\x79\xf0\xb1\x02\xb1\xc4\x63\x84\xdd\x2a\x12\x41\xd0\xbf\xaf\xe8\ +\x51\x1d\x78\xa9\x40\x89\xc4\xa3\xe1\x66\x9a\x14\x5e\x49\xe0\x02\ +\x10\x2d\x2b\x74\xf2\x24\x00\xf2\xe1\xd2\x32\xc6\xd9\x2b\xcb\xae\ +\x24\x30\x46\x62\xf8\x6b\x49\xd6\x2a\xc3\x6b\x09\x24\x24\x76\xc7\ +\xac\xab\x05\x87\xd4\xff\x40\xd9\x30\xa6\xb9\x2f\xb0\x02\x68\x01\ +\x7c\xb5\x0e\xbc\xb6\x00\x80\x2a\x3f\xf2\x04\xe4\xa2\xf6\xbd\x6e\ +\x5e\x2d\x01\x6b\xa3\x05\x84\xe3\xbc\x75\x0a\x0d\x45\x8f\x83\xa0\ +\x7f\xaf\x4e\x66\xe5\x3d\x10\x3f\xcf\xbb\xc0\xec\x08\x57\x04\x54\ +\x93\x39\xe7\x28\x8b\x9e\xd7\x3c\xab\x92\x5b\xa9\x03\x45\x70\x45\ +\xd6\x44\x59\x65\xf4\x96\xcc\x20\x74\xad\x8d\x16\xa6\x22\x60\x6d\ +\x74\xb7\x08\xee\x1b\xa7\x63\x8c\xb3\xab\xc8\xda\xa4\x12\x63\x05\ +\x62\xf8\x49\x06\x2e\xba\xee\x1b\xa7\x33\x2c\xf8\xc6\xe9\x14\x48\ +\x1c\x97\x49\x14\x0a\x8c\x85\xbb\xee\x4e\x7a\xbe\x6f\x9c\x8e\x8a\ +\xae\xa7\x24\x66\xcb\x24\x72\x37\x61\x2f\x0c\xef\x88\xca\x69\x55\ +\x78\x6a\xed\xaa\xa8\x6c\xa7\xb2\x7f\xc5\x1b\x33\x73\xd0\xcd\x74\ +\x60\x0c\x7c\xa3\x0c\x0e\xe0\xbb\xee\x8e\x8a\x6e\x90\xed\x44\xd7\ +\xda\x68\x3e\x3d\x7f\xa4\x03\xbd\x30\xbc\x2d\x2a\x6f\x0a\xe0\xaf\ +\xcb\xe0\xa9\xac\x35\x51\x79\x45\x49\x27\x12\xef\x05\xfd\x5b\x88\ +\xbe\x9b\x06\xfc\x4f\x66\xb8\x8e\xc8\xcb\xb4\x84\xd0\x98\x37\x66\ +\xee\x3d\x8c\x1c\x95\x75\x2b\x0d\x47\xb5\x3d\x29\x1c\xc0\xf3\xdc\ +\x6d\x54\xdb\xa4\x6e\x87\x32\xd8\x1a\x5e\x5c\x0a\xe8\xe8\x41\x54\ +\x51\x6d\x7b\x9e\xbb\x3d\x29\xbc\x44\xe2\x3c\x23\x20\x2a\x4f\x80\ +\xcf\xc0\x37\x41\x5a\xd3\x80\x27\x25\xe2\xa7\xe8\x57\xa0\xc7\x05\ +\xeb\xff\x00\xe0\x37\x93\x02\x62\x58\xa2\x39\x4a\x39\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xce\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x80\x49\x44\x41\x54\x58\x85\xed\ +\xd2\x21\x0e\xc2\x40\x14\x84\xe1\x7f\x96\x3b\x90\x70\x13\xe4\x9e\ +\x81\x0b\x20\x30\x1c\x09\x81\xc6\xd6\x22\xeb\x38\x0a\x49\xef\x40\ +\x07\xd5\x26\x0d\x09\xae\x5b\x33\x9f\x7b\x6f\x37\x99\x11\x0f\x22\ +\x22\x22\x36\xa6\xc5\x64\xab\xf6\xec\xd6\x0c\xec\x2b\x1f\x24\xff\ +\x14\x38\x76\xae\xb6\x1f\xc0\x61\xcd\x02\xc0\x50\xd0\xf9\x75\xd2\ +\x13\xa0\x4c\x5b\xdb\xb7\x06\xe1\x00\xfb\x11\xdf\xa7\xa1\xfc\xfb\ +\xd9\xc2\x5c\x40\xd2\x15\x78\x37\xc8\x1c\x3c\xea\x32\xe7\x2e\x9e\ +\x36\x38\xc2\x88\x88\x88\xcd\x7d\x01\x5e\x93\x20\x04\x37\xe4\x99\ +\xec\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x0b\x37\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x0a\xe9\x49\x44\x41\x54\x78\x9c\xed\ +\x5b\x7d\x70\x54\xd5\x15\xff\x9d\xbb\x9b\x4d\x22\xe6\x43\xc1\xaf\ +\x06\x3f\x30\xc8\x40\x43\xac\x12\xb4\xc6\xd2\xc8\x47\xb2\x18\x85\ +\x60\x36\xbc\x56\xb1\x68\x20\x9b\x08\x5a\xdb\xe2\xb4\x4e\x65\xa6\ +\xae\xb1\xda\xb1\x1f\x02\x23\xa3\x68\xd8\x40\x44\xa3\x6d\x97\x04\ +\x06\xac\x31\x5f\x76\x53\x14\x1c\x85\xd0\x22\x04\x18\x35\x44\xc5\ +\xd4\x56\x49\x42\x40\x20\xfb\x76\xdf\xe9\x1f\x21\xf0\xf6\xed\xdb\ +\xb7\x6f\x93\x5d\xa6\xd3\xf2\x9b\xd9\x3f\xde\xb9\xbf\x7b\xce\x79\ +\xe7\xdd\x77\xdf\xbd\xe7\x9e\x05\xce\xe3\x3c\xce\xe3\xff\x19\x74\ +\x2e\x8c\x14\x4a\x8b\x2e\x91\x15\x6b\x9e\x20\xce\x56\x18\x13\x09\ +\xb8\x16\xe0\x74\x10\xa5\x42\x81\x05\x84\x7e\x00\xfd\x20\xfe\x0c\ +\x0a\xf6\xb3\xa0\x0e\x41\xd8\xd6\xe4\x71\x1f\x8a\xb7\x6f\x71\x0b\ +\xc0\xcc\xbb\x2a\x32\x85\x35\x50\x2a\x98\x8a\x18\xb8\x7e\x98\x6a\ +\x0e\x31\x73\x03\x43\xd4\xb4\xd6\xaf\xdd\x09\x80\x63\xe9\x23\x10\ +\xfb\x00\xd0\xac\xe2\xb2\xd9\x24\xc4\xa3\x04\x9e\x11\x63\xdd\x7b\ +\x99\xb0\xa2\xf7\x62\xf1\xea\xae\xaa\x2a\x39\x56\x4a\x63\x16\x80\ +\xd9\x8e\xc5\x33\x14\x12\xbf\x03\x30\x35\x56\x3a\xf5\xc1\x5d\x04\ +\x3c\xd1\x54\x57\xbd\x01\x31\x18\x11\x23\x0e\xc0\xac\x22\xe7\x65\ +\x64\xc5\xb3\x44\xb8\xd7\x80\xa6\x30\xf0\x2e\x31\xbc\x0c\x3e\x20\ +\xc8\xf2\x09\x83\x7a\x64\x31\x70\x2c\x19\x14\xf0\x05\x90\x42\x24\ +\xd2\x40\x34\x0e\x8c\x09\x44\x9c\x0b\xa6\x02\x00\xc9\xe1\x14\x32\ +\xb0\xcd\x02\x5a\xda\x58\xb7\x76\xdf\x48\xfc\x1f\x51\x00\x66\x4b\ +\x65\x37\x2b\x0a\x6d\x06\x70\x85\xb6\x8d\x81\x63\x00\xde\x14\x44\ +\x5b\x03\x81\x81\xb7\x5a\x37\x6d\x38\x12\x8d\xee\x5c\x69\x59\xf2\ +\xa8\x40\xff\x4c\x82\x98\x0b\xe2\x22\x3d\x1b\x00\x4e\x01\x58\xdc\ +\x5c\xe7\x7e\x7d\x58\x37\x80\x11\x04\x20\xdf\x51\xb6\x80\x88\xd6\ +\x01\x48\x0c\x71\x8a\xe8\x39\x9b\xcd\xfa\xcc\x5f\x5e\x5b\xd3\x3b\ +\x5c\xfd\x6a\x48\x92\x64\xeb\x53\xd2\xca\x01\x3c\x0e\xe0\x52\x6d\ +\x3b\x01\x4f\xe7\x4e\xce\x78\xbc\xb2\xb2\x52\x89\x56\x77\xd4\x01\ +\x70\xb9\x5c\x62\xfb\xbe\xee\xa7\xc0\xfc\x98\xa6\x49\x01\x63\x9d\ +\x15\xa8\x6c\xa8\x77\x1f\x8e\x56\xaf\x19\x14\x15\x2d\x4e\x39\x61\ +\x15\x8f\x10\xe1\xe7\x00\x2e\x54\xb7\x31\x68\xb3\x5f\x24\x2c\xf4\ +\x7a\x5e\x38\x1e\x8d\xce\xa8\x02\xe0\x72\xb9\xc4\xf6\x0f\x0f\xd7\ +\x82\xe8\x6e\x8d\x96\x6e\x41\x5c\xdc\xe8\xa9\x7e\x3f\x1a\x7d\xc3\ +\x45\xa1\xc3\x39\xd6\x4f\xd8\x84\xd0\x09\x77\xb7\x35\xe9\xe4\xf4\ +\x86\xda\xda\x7e\xb3\xba\x2c\xd1\x18\xb6\x8d\xbe\xae\x12\x44\x0f\ +\x69\xc4\xef\x09\x16\xb3\x1a\xeb\xdc\x07\xa3\xd1\x35\x12\x7c\xbc\ +\xbf\xbd\xff\xb2\xc9\xb7\xbd\x9a\xa0\xf8\xae\x21\x0a\x5a\x63\x5c\ +\x11\xf0\x27\x64\xe7\x4c\xce\xfc\x73\x47\x47\x87\xa9\x2f\x84\xe9\ +\x00\xd8\x1d\xce\x1f\x82\xb0\x5a\x23\x7e\x59\x4e\xf1\x4b\xad\xaf\ +\x57\xf7\x99\xd5\x13\x2b\x1c\xee\x78\xcf\xdf\xb9\xbf\x7d\x53\xe6\ +\xa4\x1b\x4f\x80\x28\x1f\xa7\x47\x33\x01\x13\x4e\x21\x39\xa9\xb3\ +\xa3\xbd\xc5\x8c\x1e\x53\xaf\x40\x41\xc9\xe2\xa9\x80\xd8\x06\x20\ +\x49\x25\x7e\xb5\xb9\xce\x7d\x1f\xe2\xb0\x3a\x8b\x16\xf9\x0e\xe7\ +\xcf\x88\xb0\x52\x2d\x63\xc2\xfd\x2d\x1b\xdd\x1b\x22\xf5\x8d\x18\ +\x80\x59\xc5\xf7\x8d\x16\xc2\xf6\x0f\x00\x19\x67\xb5\xe3\x7d\x39\ +\xd5\x7f\x9b\xb7\xa6\xe6\x54\x54\x8e\x16\x3b\x27\x91\x05\xc5\xcc\ +\xb8\x9e\x80\xb1\x18\xfc\x05\x00\x1c\x26\xe0\x30\x33\xda\xc9\x82\ +\xfa\x61\xec\x01\xa8\xc0\xe1\xac\x06\x61\x91\x4a\xe6\x13\x2c\x72\ +\x1b\xeb\xab\xda\x0d\x3b\x46\x74\xba\xa4\xbc\x9a\xc0\x8b\x55\x3d\ +\xba\xe1\x53\x6e\x6a\xde\xb2\xae\xdb\x8c\x67\x83\x9f\xb0\xf4\xa5\ +\x00\x2f\x01\x30\xd1\x4c\x1f\x00\xbb\xc1\xf4\x5c\xba\xa5\xef\x15\ +\x8f\xc7\x13\x30\xd3\xa1\xb0\xf0\xe1\x44\xff\x05\x27\xdf\x06\x70\ +\xeb\x90\x8c\x81\x76\xff\x91\x8c\xef\x7a\xbd\x95\xfe\x70\xfd\x84\ +\x91\xd2\x7c\xa9\x62\x5a\xd0\xcd\x03\xcc\x0a\x4a\xcc\xde\xbc\xbd\ +\xa4\xec\xae\x3e\x25\x6d\x1f\xc0\xab\x60\xfe\xe6\x01\xe0\x46\x10\ +\xaf\xef\x53\xd2\x76\xda\x8b\x9d\x33\xcd\x74\x68\x68\x58\x3d\xa0\ +\xc8\x70\x80\xf1\xf5\x90\x8c\x80\x29\xb6\xd1\x5f\x3c\x68\xd4\xcf\ +\x68\x12\xa4\xcc\x89\x37\xd4\x82\xe8\x2a\x95\xac\xb6\xa5\xde\xad\ +\x9d\x08\x43\x90\x53\x51\x91\x90\x75\xf5\x0d\xab\x41\xf4\x2c\x80\ +\x8b\x23\x7a\x1f\x1e\x97\x83\x70\xff\xf8\xac\x29\xf4\x23\x69\xee\ +\xdf\xda\xda\xda\x0c\xe7\x9b\x43\x07\xdb\xbf\xb9\x76\xd2\x14\x99\ +\x08\xb7\x9f\x11\x32\x6e\x1a\x3f\x35\xeb\x85\x4f\xf6\xec\xd1\xdd\ +\x40\x85\x1d\x01\x05\x52\x79\x1e\x88\xa6\xa9\x44\xb2\xc2\x01\x57\ +\x24\x8f\xef\x5c\xb0\xf4\xa2\x8b\x8f\x28\x0d\x44\x64\x18\xf9\x68\ +\xc0\x0c\xd7\xf6\x7d\x5f\xfc\x69\xce\x9c\x8a\x0b\x22\x71\xfd\xa9\ +\xfe\x17\x01\x7c\x76\x46\x40\x18\xc3\x27\x92\x1e\x08\xc7\x0f\xff\ +\x0a\x30\x7e\x11\x2c\xa0\x97\x5a\xeb\xd7\x77\x1a\x19\x97\x24\xc9\ +\xe6\x1b\x90\x37\x03\x98\x15\xc9\xd1\xa8\xc1\x98\xef\x4b\x0c\x6c\ +\x70\xb9\x5c\x86\xaf\xad\xb7\xa6\xe6\x14\x98\x34\x0f\x8a\x1f\x91\ +\x24\x49\x77\xb4\xeb\x2a\x9b\x2e\x95\x5e\x0e\xe6\xdb\x55\x22\x59\ +\x91\xf9\xa9\x08\x2e\x52\x5f\x20\xed\x79\x00\x79\x11\x78\xc3\x06\ +\x83\x4a\xb6\xef\xed\x8e\x38\x0a\xd3\x2d\x7d\xaf\x00\xfc\x91\x4a\ +\x94\xd1\xab\xa4\xe7\xeb\x71\x75\x03\x90\xa0\x24\x2c\x40\xf0\xfc\ +\xf0\x76\xeb\x16\xf7\xbf\x8c\x8c\x16\x94\x38\xef\x05\xc1\x19\xc9\ +\xb9\x91\x83\x1f\x9f\xe5\x28\xd7\xbd\x99\x21\x78\x3c\x9e\x00\x98\ +\x3c\x6a\x19\x81\xef\xd7\xe3\x86\x19\x4e\x3c\x37\xa8\x33\xd1\x16\ +\x23\x83\xa7\xdf\xcd\x67\x8c\x38\xb1\x84\x20\x5e\x11\x6e\x48\x0f\ +\x81\x48\x68\x7d\xbe\x43\xaf\x4f\x48\x00\xec\x0b\x17\x8e\x82\xea\ +\x5b\x0a\x00\x0a\xd1\x1b\x46\xc6\x7c\x36\x7e\x04\xea\x85\x52\xfc\ +\x91\x7d\x34\x90\x56\x6a\x44\xc8\x9d\x7c\xc5\x07\x20\xa8\x47\x6d\ +\x5a\x3f\x52\x73\xb4\xbc\x90\x00\xf0\x49\xdb\x2d\x00\x6c\x2a\xd1\ +\xdf\x5b\x3c\x55\x9f\x69\x79\x43\x90\x24\xc9\xc2\xc4\x3f\x89\xec\ +\x73\x6c\xc1\x84\x9f\x1a\xb5\x57\x56\x56\x2a\x60\x04\x3d\x38\x85\ +\x45\x48\x9e\x32\xf4\x15\x60\x31\x59\x7d\x49\x84\x6d\x46\x86\x7a\ +\x39\xed\xfb\x00\x2e\x31\xe2\xc4\x09\xd9\x05\x25\x0f\x5c\x67\x44\ +\x20\x70\xb0\xef\x8c\x2c\x2d\x47\x27\x00\x98\xa4\xbe\x54\x14\xfa\ +\x28\x84\xa3\x36\xc2\x98\x6f\xd4\x1e\x4f\x30\x02\x25\x86\x04\x12\ +\x1a\xdf\x79\x92\x96\x12\x1a\x00\xe2\x6b\x82\x05\x8a\xe1\xb7\x1f\ +\xe0\x38\x67\x81\xc3\x83\x08\x21\xef\xb4\x1a\x3e\x92\xb5\xbe\x8f\ +\xd3\x72\xf4\xbe\x02\x29\x41\x46\x80\x08\x7b\x7d\x3a\x97\x93\x5f\ +\x30\x18\x63\x0d\xdb\x47\x85\xf8\x9e\xa2\xa5\x44\x0c\x80\x60\x0e\ +\x9b\x63\x3b\xbd\x2a\xd3\xcb\xd6\x9e\x2b\x18\x06\xc0\x5b\x53\x33\ +\x00\x40\xbd\x13\xb4\x49\x92\xa4\x9e\xe0\x75\x03\x10\xb4\x45\xf6\ +\x0b\x11\x76\x03\xd2\xd6\x06\x11\x46\xc7\xb9\x01\x21\x61\xa4\x2a\ +\x42\x9c\x27\xc6\xb1\x20\x02\x73\xc8\xb0\x19\x82\xd7\x5b\xe9\x27\ +\xc0\x70\x85\x18\x57\x28\x30\xcc\x3e\x4f\x2f\x2d\x4d\x04\x60\x55\ +\x89\x7c\x1e\x8f\xc7\xa7\xe6\x84\xae\x03\x06\x4f\x6a\xcf\x5e\x03\ +\xe9\x46\x46\x98\xf1\x45\x64\x4f\xe3\x03\x22\xe3\x00\x58\x7a\xac\ +\x69\x1a\xd1\x31\x2d\x27\x34\x00\xc0\xa7\xc1\x56\x42\x67\x4e\x4d\ +\xfb\x5e\xc3\xf6\xf8\xc2\xd8\x76\xa2\x72\x6d\xd0\x35\xa3\x4b\x4b\ +\xd1\x5b\x07\xec\x57\x5f\x12\xc8\x70\xb1\x01\xa6\x7a\xc3\xf6\x38\ +\x82\x58\x18\xda\x26\x16\x41\xbe\x33\x70\x40\xcb\x09\x09\x80\x60\ +\x04\x1d\x36\x32\x30\x4d\xcb\x51\x43\x4e\x95\x9b\x00\x44\x75\x1a\ +\x13\x23\x7c\xda\x58\x5f\xb5\xdb\x88\x20\x98\x83\x7d\xd7\x19\xad\ +\x21\x01\xf0\x59\x6d\x3b\x00\x9c\x49\x1f\x11\x30\xa5\xd0\xe1\x0c\ +\xfb\xb9\x19\xcc\x0c\x53\x8d\x09\x87\x63\x0b\x42\x15\x0c\x52\xf2\ +\x2e\x97\x4b\x30\x68\x4e\x90\x90\xe1\xd5\xf2\x42\x02\x70\xfa\x6c\ +\x6d\x87\x5a\xe6\x27\x8d\x22\x0d\xac\xc2\xff\x24\x80\xa3\x86\x0e\ +\xc7\x16\x9f\x1f\xa7\x94\x95\x46\x84\x77\x3e\xec\xce\x41\xd0\x1a\ +\x85\xfa\xfd\x3d\x19\x3b\xb5\x3c\xdd\x6f\x38\x01\x9a\xed\xaf\x52\ +\x64\x64\xac\xc1\xb3\xfe\x2b\xa6\x88\x19\xa3\x58\x62\xf9\x0e\xcf\ +\xca\x93\x46\x04\x12\x5a\x9f\xf9\x2d\xbd\xf4\xb8\x6e\x00\x58\x56\ +\x6a\x01\xa8\x8e\x9a\x69\x66\xa1\xb4\xc8\x70\xc7\xe7\xff\x7a\xec\ +\x2a\x00\x8d\x46\x9c\xd8\x80\x5e\x69\xae\x73\xd7\x1a\x31\x5c\x2e\ +\x97\x20\x26\xed\x26\xed\x65\x3d\xae\x6e\x00\x9a\xb7\xac\xeb\x26\ +\x42\x93\x4a\x94\x28\x2b\x56\xed\x71\x78\x10\xbc\xde\x4a\xbf\x1c\ +\xf0\xdf\xcd\x40\x3c\x0f\x49\xdf\x93\x53\xe4\x0a\x44\x38\x8e\xdb\ +\xb1\xaf\xfb\x1e\xa8\xce\x21\x08\xf8\x52\x3e\x92\xd1\xa4\xc7\x0d\ +\xbb\x8c\x65\xf0\x1f\xd4\xd7\x04\x7e\x68\xa6\xa3\xec\x6a\x23\xc3\ +\xde\xcd\x35\x7d\xcc\x81\x3b\xe2\x14\x84\x9d\x8a\x8c\xbb\x22\x1d\ +\xc7\x49\x92\x64\x63\xe6\x5f\xab\x65\xcc\xbc\x32\xdc\xe9\x50\xd8\ +\x00\x34\x6f\xac\x7e\x9b\x38\x68\x32\xb4\x59\x08\x4f\x44\xf2\xb2\ +\xb5\x7e\x7d\xa7\x3f\xe0\xbf\x05\x20\xdd\x88\x0f\x0b\xcc\x7f\x3c\ +\x2e\x52\xf2\x22\x25\x66\x01\xa0\x57\x49\xad\x40\xf0\xb6\xb7\x27\ +\xd9\xcf\x6b\xc2\xf1\x8d\x36\x32\xac\x08\x2c\x0f\x16\xd1\x7d\x76\ +\xc9\x69\xb8\x07\x07\x06\x47\x82\x7c\xe4\x5b\x77\x82\xe8\x97\xac\ +\xb3\xfc\x34\x0d\xc6\xd7\x00\x2d\x6d\xae\xaf\x5e\x10\x69\xd2\x03\ +\x80\xe9\xf7\x54\x8c\x21\xd0\xaf\x34\x3a\x7e\xb3\x65\xcb\xba\xb0\ +\x3e\x18\x66\x56\x3b\x3b\xda\xbb\x32\xbf\x9d\x93\x09\xe0\x3b\xa7\ +\x45\x04\x46\xe1\xb8\xeb\xa6\xbc\x76\xe8\x60\xfb\x37\x46\x7d\xbb\ +\xba\xda\x94\xce\x8e\xf6\x77\xc7\x4f\xbc\xb9\x9a\x48\xb9\x10\x40\ +\x16\x60\x7a\xf7\x76\x94\x80\x55\x6c\x11\x3f\x68\xd9\xb8\xf6\x5d\ +\x33\x1d\x24\x49\xb2\xc9\x72\xe2\x56\xd0\xd9\xb4\x17\x01\x7b\x7a\ +\xc6\x88\xb2\x7f\xee\xda\x15\xb6\x76\x28\xe2\xe9\xb0\xbd\x78\xc9\ +\xa5\x6c\xf1\xef\x01\xe3\x32\x95\x78\xbb\xf5\x44\xf2\xcc\x86\x86\ +\xd5\x03\x66\x9c\x03\x06\x53\xe7\xa7\x92\x94\xdb\x05\xa3\x84\x81\ +\x6c\x0c\x66\x91\x87\xce\x0d\xbf\x02\xa8\x1b\xcc\xed\x24\xc8\x93\ +\x46\x7d\xad\xda\x5d\x5b\x24\x14\x94\x38\xd7\x00\x58\xa2\x12\xc9\ +\x42\xf0\xb4\x48\x65\x3b\xa6\x0a\x24\xf2\x1d\xce\x5b\x88\xe0\x85\ +\xaa\x22\x8c\x41\xeb\x5a\xea\xd6\x3a\x31\x82\x02\x89\x5c\x69\x59\ +\x72\xfa\x71\xbf\x12\x4d\x20\xf5\x60\x9f\x5f\xfe\x20\x33\x3f\xaf\ +\x96\x11\xc3\xd9\x54\xef\xae\x8e\xd4\xd7\x74\x91\x54\x81\xa3\x6c\ +\x21\x88\x82\x2a\x2e\x18\xa8\xba\x48\x1c\x7d\x38\xda\xa7\x15\x43\ +\x90\xbd\xc4\xf9\x30\x03\x2b\xa1\x9a\xcf\x88\xb0\xaa\x69\xa3\x7b\ +\x99\x19\x05\xa6\x6b\x84\x3a\xf7\xef\xde\x93\x99\x95\x73\x01\x80\ +\xef\x9d\x31\x04\xe4\x9c\x52\x92\xf2\xae\xba\x61\xea\x1b\x5d\x7b\ +\x77\x9d\x88\xc6\xf3\x91\x42\x92\x24\x5b\xc6\xa4\x5b\x5f\x02\xb0\ +\x1c\xc1\x0f\xb2\x51\x3e\x92\xb1\xa8\xab\xab\xcd\x54\xcd\x60\x54\ +\xe9\xac\x74\xea\x5b\x8e\xc1\xf2\xb4\xb3\x20\xdc\x96\xe0\x0b\x7c\ +\x90\x2f\x55\x64\x47\xa3\x6b\x24\xb0\x17\x2f\xb9\xb4\x2f\x90\xda\ +\x0a\xa0\x4c\xd3\xb4\x4f\x0e\xf8\xef\x36\xaa\x08\xd1\x22\xea\x42\ +\x49\x49\x92\x2c\xbd\x4a\xfa\xef\x09\xac\x1d\x62\x32\x80\x35\xa4\ +\x58\x9f\x6e\xda\xf4\xe2\xbf\xa3\xd5\x6b\x06\xb9\xd2\xb2\xe4\x14\ +\xe5\xd8\x8f\x99\xf1\x18\x08\x17\x05\xb7\x72\x03\x0b\xcb\x3d\x2d\ +\x9e\xaa\xa8\x36\x65\xc3\x2e\x95\xb5\x3b\x9c\x65\x4c\x58\x83\xd0\ +\x4f\xdb\x71\x22\x3c\x6b\x49\x3c\xb9\x22\x9a\x82\x45\x23\x4c\x9f\ +\xee\xb2\x26\x8c\x39\x5c\x0a\xa6\x27\xa0\x7b\x06\xc9\x2b\xd2\x45\ +\xff\xa3\x66\xeb\x89\xd4\x18\x51\xb1\xb4\xdd\x51\x96\xc7\x44\xf5\ +\x00\x46\x87\xfa\x84\x5e\x02\xb6\x02\xd8\x6a\x49\x3e\xd9\x14\x6d\ +\x30\x24\x49\xb2\xf5\x04\xd2\xf3\x04\xf1\x5c\x00\xf3\x00\xe8\x2d\ +\xc3\x65\x62\x2c\x35\x33\xdb\x87\xc3\x88\xcb\xe5\xed\xf3\x16\x5d\ +\xc9\x56\xcb\x2a\x00\x0e\x03\x9a\x4c\x40\x1b\x13\xfe\xca\x4c\x07\ +\x2d\x4a\xe0\x63\x56\xb8\x27\x61\x54\xd2\x71\x85\xfa\x03\x03\xbe\ +\x94\x14\xc2\x40\x1a\x05\xc4\x38\x41\x98\xc0\x4c\xb9\x20\x9a\x0d\ +\x70\xaa\x81\xce\x0f\x48\x60\x69\x93\xc7\xbd\x6b\x24\xfe\xc7\xec\ +\x0f\x13\xf6\xf9\xe5\x85\xcc\xfc\x5b\x0c\x2e\x72\xe2\x07\x42\x37\ +\xc0\x4f\xa6\x53\xbf\x7b\x38\x43\x3e\x54\x5d\x0c\x31\x58\x4c\xdd\ +\x3d\x0f\xc4\x8f\x01\xb8\x29\x96\xba\x01\x74\x02\x58\x21\xa7\xf8\ +\xab\xa3\x2d\xd0\x34\x42\xdc\xfe\x34\x35\xbb\xa4\x3c\x8b\x81\x52\ +\x06\x17\x01\x98\x30\x1c\x1d\x04\x7c\xa9\x80\xde\x14\xac\xbc\x9c\ +\x9b\x3d\xf6\x9d\xe1\xfc\x1f\xc0\x84\x8d\xf8\xc3\x3e\x6f\xd1\x95\ +\x4a\x82\x65\x06\x81\xb2\x00\x65\x22\x98\xc6\x01\x48\x03\x90\x8a\ +\xc1\x93\x9b\xa3\x00\xfa\x01\xfa\x1c\xe0\x03\x0c\x1c\x60\x11\x68\ +\x6b\xf5\xac\xdf\x8f\xff\x82\x5a\xe4\xf3\x38\x8f\xf3\xf8\xdf\xc5\ +\x7f\x00\x80\x02\xea\x80\xb2\xb7\x05\xfa\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\xb2\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x64\x49\x44\x41\x54\x58\x85\xe5\ +\xd6\xb1\x4a\x03\x31\x1c\xc7\xf1\x6f\x72\x97\xfa\x06\x56\x90\x6a\ +\x29\x5d\xaa\x93\x93\x73\xeb\x03\x08\xfa\xa4\xe2\x52\x10\xda\x87\ +\x50\xeb\x52\x6e\x13\xd4\xc9\xfd\xae\xf7\x77\x90\x13\xda\x5e\xbd\ +\x24\x4d\xce\xc1\x8c\xc9\x1f\x3e\x3f\x92\x3f\x7f\x02\xff\x7d\xa9\ +\x36\xb1\x2c\xcb\xba\x5a\x9b\x3b\x34\xaf\xfd\x93\xde\x2d\x80\x6e\ +\x15\x4f\xd2\x39\x8a\x4b\x4a\x8e\xab\xfd\xb4\x55\x1c\x35\x02\x79\ +\x29\xcb\xe2\xba\x3a\x8b\xfe\x04\x5b\xf8\xaa\x18\x0f\x06\x83\xf7\ +\x56\x02\x34\xe1\x51\x03\xd8\xe0\xd1\x02\xd8\xe2\x51\x02\xb8\xe0\ +\xc1\x03\xb8\xe2\x41\x03\xf8\xe0\xc1\x02\xd8\xe2\xcb\xe5\xdb\x61\ +\x6a\xf2\x29\xf0\xd9\x3f\xed\x4d\x20\xc0\x24\x74\xc4\x67\xc0\x05\ +\x48\xa7\xda\xdf\x2b\x80\x07\x7e\x0e\x3c\x15\x79\xe7\xa6\x3a\xf3\ +\x7e\x02\x7f\xdc\x5c\x0d\x87\x47\x1f\x7b\x05\x08\x85\x7b\x05\x70\ +\xc4\xe7\xc0\x19\xf0\x5c\xe4\x66\xb2\x89\x3b\x07\x08\x8d\x3b\x05\ +\x88\x81\x03\x24\x21\xf1\x2c\xcb\xba\x49\x8a\x35\x0e\x16\x37\xe0\ +\x82\xeb\xc4\xcc\x5c\xf0\xc6\x00\x9e\xf8\xa2\xc8\xcd\xb8\x0e\x77\ +\x9a\x84\x91\xf0\xad\x49\x58\xfb\x27\x8c\x84\x57\xbd\xb1\x36\x09\ +\xb7\x9a\xd0\x0d\x4f\xe7\xa0\x7e\xc5\x6b\x1a\x73\x6d\x18\xe9\xcd\ +\x62\x47\x7c\x04\x2c\xca\x55\x5e\xdb\x70\x36\x8d\xa9\xd6\x8b\xfd\ +\x70\x9b\xba\x5d\x37\xa4\x01\x44\x44\xab\xc4\x3c\x34\xe1\x22\xa2\ +\x54\x62\xee\x9b\xf0\xcd\xba\x5d\xf8\x4f\x00\x00\x25\x1c\x08\x3c\ +\x36\xfc\x64\x94\x52\x74\xbe\xeb\xea\xf1\xba\x3a\x9b\x79\x80\x88\ +\x68\x11\x69\x1c\x4c\x22\xa2\x42\xd6\xfd\xf9\xfa\x02\x53\x42\xe8\ +\x88\x61\x1a\x4e\x81\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ +\x82\ +\x00\x00\x03\x5e\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x10\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4d\x4f\x13\x51\x14\x86\xdf\x53\xd1\x21\x74\xa9\x84\x0f\xf7\ +\x6e\xb0\xdd\xb4\xc4\x8d\xfe\x0b\xc1\x48\x52\xdc\x98\x56\x89\xad\ +\xb2\x30\x81\x5f\xa0\x09\x0b\x4d\x5b\x23\xed\x4e\x49\x34\x01\xfe\ +\x05\xee\xa4\x1b\x0a\x2b\xd7\x14\x49\x74\x09\x32\x0a\x7d\x5d\xb4\ +\x94\x61\x66\x4a\x2b\x32\x3d\x6d\xb8\xcf\x6a\x3a\xe7\x4e\xf2\xde\ +\x27\xf7\xf6\x6e\xee\x01\x0c\x06\xc3\x65\x46\xda\x19\x14\x4d\x2c\ +\x84\xad\x81\xfe\x49\x02\xf7\x01\xde\x06\x30\x0a\xa0\x2f\xd8\x68\ +\xff\xcc\x21\x80\x0a\x20\x9b\x02\xac\xda\xfb\x07\xcb\x1b\x4b\x2f\ +\xf7\x5a\x7d\xd4\x42\x00\x25\x96\xcc\x4e\x8b\xc8\x2b\x00\x23\x17\ +\x93\xb3\x63\xec\x00\x98\x5b\x2f\xa4\x97\x00\x61\xb3\x41\x4d\x05\ +\xc4\x92\x85\xab\x02\x3b\x07\x41\x2a\x90\x78\x9d\x82\x28\x10\x56\ +\xba\x54\x4c\xfd\xf1\x2b\x37\x59\xc6\x14\x91\x7c\x1e\x40\xd2\x55\ +\x28\x8b\xe0\x0b\x88\xef\x55\xa0\x7a\xb1\x49\xff\x8f\x10\x10\x82\ +\x60\x98\xc4\x5d\x00\x91\x46\x41\x90\x12\xda\x00\xf8\xd4\x6f\x25\ +\xf8\xae\x80\x78\x2a\x3b\x0d\xe0\x83\xe3\xd5\x4f\x52\x32\xa5\xe2\ +\xb3\xcf\x67\x2d\xa7\xee\x80\x12\x4b\xe6\x1f\x8a\x30\x0b\xe0\xba\ +\xa3\xf0\x68\xbd\x90\xf9\xe8\x1e\xed\x11\x10\x4d\x2c\x84\xaf\x0d\ +\x58\xdf\x70\xb2\xe7\x7f\x90\x47\xd1\x52\x71\x76\x27\x98\xc0\xc1\ +\x10\x4b\xbe\x19\x11\xb9\xb2\x01\xe0\x06\x00\x80\xa8\xfc\xfe\x65\ +\xdf\x72\xff\x31\x86\xdc\x1f\x5a\x03\xfd\x93\x70\xfc\xe1\x91\xf2\ +\xbc\xd7\x26\x0f\x00\xa5\xe2\xec\x8e\x08\x5e\x34\x5e\x08\x46\xad\ +\xb0\x35\xe1\x1e\xe7\x11\x50\x3b\xea\x1a\x94\x6b\xcb\xbe\x37\xf9\ +\xba\x98\xfe\x04\xa0\x7c\xfc\x9b\x94\xd6\x02\xea\xe7\x7c\xed\x09\ +\x5c\xeb\xfe\x3d\x7f\x16\xc2\xda\x1c\xea\x90\x63\xee\x11\x3e\x02\ +\x30\x7a\x52\x94\xdd\x60\x82\x75\x8e\x53\x73\x10\xdc\xf4\xd6\xbd\ +\x34\x8e\xc6\x6e\x3b\xea\xce\x83\x6b\x0e\x9e\x63\xdf\x4f\xc0\xa5\ +\xc2\x08\xd0\x0e\xa0\x8d\x11\xa0\x1d\x40\x1b\x23\x40\x3b\x80\x36\ +\x46\x80\x76\x00\x6d\x8c\x00\xed\x00\xda\x18\x01\xda\x01\xb4\x31\ +\x02\xb4\x03\x68\x63\x04\x68\x07\xd0\xc6\x08\xd0\x0e\xa0\x8d\x11\ +\xa0\x1d\x40\x1b\x23\x40\x3b\x80\x36\x46\x80\x76\x00\x6d\x8c\x00\ +\xed\x00\xda\x18\x01\xda\x01\xb4\x31\x02\xb4\x03\x68\x63\x04\x68\ +\x07\xd0\xc6\x08\xd0\x0e\xa0\x8d\x9f\x80\x43\x47\xb1\xe7\x05\xb9\ +\xe6\x70\xe8\x53\xf7\x50\x39\x7e\xa8\x82\x43\x41\x84\xea\x24\xa7\ +\xe6\x40\x6c\xbb\xeb\x3e\x02\x64\xb3\xf1\x04\xb9\x07\xb0\xad\x9e\ +\x82\xee\x84\x52\x9b\x43\x1d\x91\x2d\xf7\x08\x8f\x00\x01\x56\x1d\ +\x3f\x23\xe3\xa9\xfc\x64\x30\xe1\x82\x27\xfe\x24\xfb\x00\x8e\x9b\ +\xe3\x22\x5c\x71\x8f\xf1\x08\xb0\xf7\x0f\x96\x51\x6b\x36\x00\x00\ +\x50\x98\xbb\xf3\xf8\x6d\xcf\x6d\x85\xf1\x99\x77\xc3\x80\x64\x1b\ +\x2f\x88\x8a\xbd\x67\xb7\x16\x50\xbf\x4d\x3d\xe7\xf8\x70\xf0\xa8\ +\x2f\x54\x8e\x25\x73\x53\xbd\xb1\x1d\x28\xb1\x64\x6e\x8a\xd5\xa3\ +\x0d\x10\x83\x8d\xd7\x82\x79\xbf\x16\x9a\x26\x13\xa2\xc4\x93\xb9\ +\xf7\x3e\xdd\x22\x65\x82\x6b\x21\xc8\x6e\xb7\xdd\x22\x0d\x01\xa1\ +\x2a\x38\x54\xdf\xf3\x91\xd3\x55\x2e\xae\x17\x32\x33\x7e\xf7\x9e\ +\x9b\x74\x8c\x08\x89\x42\x5a\x68\xc3\x25\x21\x22\x90\x08\xd1\x66\ +\xb7\x55\x07\xa9\x65\xf2\x4b\xc5\x45\xb2\x3f\xd3\xec\xd2\x77\xcb\ +\xa6\xa9\x78\x2a\x97\x00\xf0\x1a\xbd\xd6\x34\x45\x54\x20\x98\x3f\ +\x77\xd3\x94\x93\x68\x62\x21\x6c\x85\xad\x09\x52\x26\x40\x8e\xd5\ +\x6f\x5d\x77\x5f\xdb\x1c\xb1\x0d\x91\x2d\x11\xae\xd8\x7b\xf6\x4a\ +\x3b\x6d\x73\x06\x83\xe1\x72\xf3\x17\xf4\xb0\xe5\x26\x61\x1e\x11\ +\x45\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x8d\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x3f\x49\x44\x41\x54\x58\x85\xed\ +\x92\xb1\x4a\x03\x51\x10\x45\xcf\x4d\x02\xa2\x18\x82\xad\xac\xd9\ +\x4d\x5a\xc1\x5f\xb0\xb0\xb4\xb0\xb3\x13\xed\x2c\xfc\x02\x41\xb0\ +\xb2\xf1\x07\x14\x49\x61\xab\x62\x67\x2d\xe8\x1f\xf8\x03\xba\x6f\ +\xb3\x20\xa6\xd1\xca\x42\x93\x37\x56\x09\x62\xb7\x6f\x61\x1b\xf7\ +\x74\x03\x33\x77\x0e\xef\x0d\xd4\xd4\xd4\xfc\x77\x54\xa4\xd9\xcc\ +\xe4\xb2\xdc\x03\x98\x1f\x2f\xf5\x7a\xbd\x8f\xb2\x02\x8d\x82\xfd\ +\x33\x61\x35\x5a\xef\x66\xd6\xac\x54\x40\x92\x17\xda\x9e\xd6\x2e\ +\xcb\xc7\x95\x0a\x00\xc4\x71\x74\x83\xe9\x64\x5a\xa7\xe9\xf0\xa9\ +\x52\x01\x80\x24\x89\x8e\x80\x7b\x00\xc4\x9a\x73\xd9\x59\xa8\x40\ +\xa1\x23\xfc\x4b\xea\x86\xf6\x2b\x68\x3f\x8e\x57\x2e\x2a\x15\x30\ +\xb3\x86\xcb\xf2\xc9\xb4\xf6\xb2\xf5\x7e\xb7\xfb\x58\x24\x23\xe8\ +\x0b\xa6\x48\xf2\x0b\xf3\x73\xed\x59\x98\xe9\xa1\x68\x46\x29\x01\ +\x80\xd1\x68\xf4\x05\x4a\x43\xe7\x4b\x09\x98\x99\x16\xdb\x9d\x01\ +\x58\x02\x7a\xf3\x93\x66\x52\xa9\x40\x9a\xe5\xc7\xc0\x0e\xf0\x29\ +\x26\x9b\xfd\xfe\xb2\x2b\x9a\x11\x7c\x84\x2f\x2e\xdf\x15\x76\x09\ +\x78\xa1\xad\x38\x8e\xee\x42\x72\x82\x5e\xc0\xb9\x7c\x43\xd8\x00\ +\xc0\xa4\x83\xd0\xe5\x41\x02\xce\xb9\x55\xc3\x6e\x81\x96\xc1\x69\ +\xaf\x1b\x9d\x87\x2e\x2f\x2c\x60\x66\x32\x1a\xd7\x40\x47\xe8\x2a\ +\xe9\x46\x87\x65\x96\x03\xb4\x02\x66\x5e\x81\x67\xef\xbf\xf7\x24\ +\xf9\xb2\x02\x35\x35\x35\x35\x3f\x6e\x39\x66\xc8\x1a\xa6\xbc\x56\ +\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x83\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x35\x49\x44\x41\x54\x58\x85\xed\ +\x97\x31\x4e\x02\x51\x14\x45\xcf\x65\x12\x28\x91\x06\xd7\x30\x1b\ +\x18\x22\xb5\x09\xb4\x1a\x3b\x56\x81\xb5\x5a\x48\x2f\xab\xa0\x53\ +\x8c\x95\x31\xb1\x36\x71\x36\xc0\x1e\x68\xc0\x52\x93\x99\x6b\x01\ +\x93\x20\x82\x85\x99\x89\x85\xff\x96\xef\xbf\xfc\x7b\xf2\xfe\x2f\ +\xde\x85\xff\x2e\x6d\x17\x92\x5b\xf7\x54\xf3\x39\x90\x00\x07\x25\ +\xf9\x2c\x81\xd4\xb9\x6e\xd2\x33\x3d\xed\x05\xe8\xdc\x65\x23\xa4\ +\x0b\xc3\xbb\x60\x66\x78\x2b\xc3\x5d\xd0\x34\xc4\x82\x06\xf2\xe8\ +\xf5\x24\xba\xfa\x06\x70\x34\x75\x3f\xc7\x8f\x88\xe7\xc8\x1a\xbc\ +\x9c\x6a\x5e\x86\x79\xa1\xee\xd4\xed\x4c\x9e\x60\x8e\x9d\xab\x5f\ +\x4c\xa2\x56\x34\xe4\x78\x68\x78\xaf\xc2\x1c\xe0\xe5\x54\xf3\xc8\ +\x1a\x00\x1f\x8a\x3c\x2c\xea\xb5\x8d\x9e\x44\x30\xab\xc2\x7c\x13\ +\x02\x98\x61\x92\x5d\x00\x07\x65\xbd\xf9\x4f\xf2\xea\x43\xb6\x76\ +\x01\xfc\x89\x02\x40\x00\x08\x00\x01\x20\x00\x04\x80\x00\x10\x00\ +\x36\x01\x96\x82\x66\xd5\x86\x5a\xad\xfa\x8b\x5d\x00\xa9\x21\xee\ +\x4e\xdd\xae\xca\x7c\x7d\x77\x8c\x48\xbf\x01\x38\xd7\x8d\xa0\x91\ +\xc9\x93\x2a\x20\x3a\x0f\x3e\xcc\xe4\x09\x50\x77\xa6\x71\x51\xff\ +\x1a\x4c\xee\xb3\x6b\xac\x4b\xe0\x83\x55\x30\x59\x96\x61\xbe\x1e\ +\x7b\x0c\xd4\xf7\x06\x93\x42\xc9\xad\x7b\x8a\x3c\x5c\xaf\xce\xad\ +\xed\xf3\x5f\x6a\x81\x48\x9d\x69\xbc\x1d\xcd\x82\x3e\x01\x68\xb1\ +\x6f\x2f\x7c\x41\x27\x3e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ +\x60\x82\ +\x00\x00\x03\xeb\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x9d\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x3f\x6c\x52\x51\x14\xc6\xbf\xf3\x78\xe8\xa4\xd8\xa8\x69\x22\ +\xc6\xa9\x83\x75\x50\x6b\x5d\xdc\x48\x10\x1c\x34\xa4\xa6\x25\x0e\ +\xd6\xd8\x28\xb3\x71\x33\x61\x90\xd4\xc4\x18\xdd\xd4\xc5\x01\x4c\ +\x35\x2e\xa6\xf6\x4f\x88\x0e\x52\x9b\x30\x54\x5d\xaa\x55\x07\x98\ +\xea\x60\x64\xa8\xf1\x1f\x6e\xd8\xf2\x8e\x43\xd1\x3e\x1e\x0f\x5a\ +\x7a\xdf\xe3\xb6\x72\x7f\xdb\x3d\xef\xdc\xc3\x77\xbf\xbc\x77\xef\ +\x4d\xb8\x17\x50\x28\x14\xed\x0c\xad\x25\x29\x10\x48\xe8\xfa\xae\ +\x42\x84\x18\x67\x00\x1c\x05\xe0\x07\xb0\xd5\x55\x65\xcd\x53\x02\ +\x50\x00\x30\xcb\x84\xc7\x4b\x5f\xfd\xe9\x6c\x76\x78\x69\xb5\x4e\ +\xab\x1a\x10\x3e\x1d\x0b\xb1\x86\xdb\x00\xba\x1d\x10\xd9\x42\x28\ +\x47\x06\x5f\xce\x4c\x24\xa7\x1a\x65\x79\x1a\x55\x08\x0d\xc4\xe2\ +\x20\x8c\x00\xd8\xed\xa8\xb6\xd6\xb0\x1b\x84\x73\x5d\xdd\x3d\xbf\ +\xe7\xf3\x73\x2f\xeb\x25\xd5\x35\x20\x34\x10\x8b\x83\x71\xdd\x1d\ +\x6d\x2d\x84\x28\xd8\xd5\xdd\x53\x9a\xcf\xcf\xcd\xd8\x3e\xb6\x0b\ +\x56\x5e\xfb\x4c\x55\x90\xf1\x83\x89\xaf\x6a\x1a\x3d\xf3\xa1\xf8\ +\x69\x74\x74\xb4\xec\x82\xdc\x75\x13\x8d\x46\x3d\x45\xf8\xf6\x19\ +\x06\x9f\x24\xa6\x6b\x20\x74\x98\x9f\x93\x81\xb0\xdd\xe7\x50\x63\ +\x40\x20\x90\xd0\xbd\x3b\x0b\x1f\x60\xfa\xe6\x09\x78\x51\x5e\xc4\ +\xe0\x74\x3a\xb9\xe0\x8a\x7a\x87\x09\x46\x62\x9d\x1e\x2f\x1e\x31\ +\x70\x7c\x25\x4a\xb9\xc5\x6f\x7b\x0e\x59\x27\x46\xcd\xda\x59\xdf\ +\x55\x88\xa0\x7a\xc2\xfb\x0e\x43\x3f\xbb\x59\x06\x0f\x00\xd3\xe9\ +\xe4\x42\x79\x11\x83\x60\xfc\x58\x89\xf2\x81\xca\xd8\xaa\xa8\x31\ +\xa0\xb2\xd4\xad\x74\x03\x27\x32\x13\xf7\xbe\xb8\x21\xd4\x4d\xa6\ +\xd3\xc9\x05\x06\x25\xcc\x31\xeb\xd8\x00\x1b\x03\xb0\xbc\xce\xaf\ +\x24\x68\xf4\xcc\x61\x6d\x2d\x43\xf3\xf0\x53\x73\x9b\x80\xde\x9a\ +\x1c\x9b\x7e\x7e\x73\xc3\x87\xe2\x27\x87\x75\xb5\x0c\xab\x76\x06\ +\xf6\x5a\x73\xec\x0c\xa8\xda\xe1\x6d\xb4\xd9\xbe\x19\x6c\xb4\xd7\ +\xec\x5e\xed\x0c\x68\x2b\x94\x01\xb2\x05\xc8\x46\x19\x20\x5b\x80\ +\x6c\x94\x01\xb2\x05\xc8\x46\x19\x20\x5b\x80\x6c\x94\x01\xb2\x05\ +\xc8\x46\x19\x20\x5b\x80\x6c\x74\x27\x8a\x84\x06\x2e\x84\xc1\x9e\ +\x5b\x00\x1f\xc4\x1a\xff\x6b\x10\x80\x01\xbc\x07\x19\x57\xa6\x9e\ +\xdc\xcf\xac\x9a\xbd\x0a\xc2\x6f\x40\xb8\xff\xe2\x79\xb0\xf6\x1c\ +\xe0\x43\x70\x7f\xf0\xa8\xfc\xc6\x61\xb0\xf6\x3c\xdc\x7f\xf1\xbc\ +\x68\x31\x21\x03\x02\x7d\x43\x3b\x0c\xd0\x5d\x51\x11\xeb\x85\xa1\ +\xdd\x09\xf4\x0d\xed\x10\xa9\x21\x64\xc0\x16\xdd\x7b\x8c\x80\x6d\ +\x22\x35\xc4\xe0\xed\x5b\x74\xef\x31\x91\x0a\x6d\x3f\x09\x0a\x19\ +\xf0\x7b\x69\xf1\x35\x40\xbf\x9c\x12\xd3\x3c\xf4\x6b\x59\xc3\xfa\ +\x11\x32\x20\x3b\x39\xf2\x93\x60\x5c\x12\xa9\x21\x02\xc1\xb8\x94\ +\x9d\x1c\xf9\x29\x52\x43\xf8\x13\xc8\x8c\xa5\x1e\x80\x8c\x13\x00\ +\xde\x61\x79\x89\x72\x1b\x06\xe8\x3d\xc8\x38\x91\x19\x4b\x3d\x10\ +\x2d\xe6\xc8\x3e\xa0\xb2\x1e\x0b\xaf\xc9\x32\x50\x93\xa0\x6c\x01\ +\xb2\x51\x06\xc8\x16\x20\x1b\x65\x80\x6c\x01\xb2\x51\x06\xc8\x16\ +\x20\x1b\x65\x80\x6c\x01\xb2\x51\x06\xc8\x16\x20\x1b\x65\x80\x4d\ +\xac\x64\x6e\x44\xa3\xd1\x46\xe7\x89\x37\x34\x36\xda\x4b\xd6\x1c\ +\x3b\x03\x0a\xe6\x46\x11\xbe\x7d\x4e\x8a\x6a\x25\x56\xed\x04\x7c\ +\xb6\xe6\xd8\x19\x30\x6b\x6e\x18\x06\x9f\x74\x58\x57\xcb\x30\xca\ +\x74\xca\xdc\x66\xe0\x8d\x35\xa7\xc6\x00\x26\x3c\x36\xb7\x89\xe9\ +\x5a\x30\x12\xeb\x74\x5e\x9e\xbb\x04\x23\xb1\x4e\x02\x0f\x9b\x63\ +\xd6\xb1\x01\x36\x06\x2c\x7d\xf5\xa7\x01\xe4\xff\x05\x08\x1d\x1e\ +\x2f\x1e\x6d\x26\x13\xfe\x1e\x96\xae\x3e\x31\x4e\xb9\xca\xd8\xaa\ +\x68\xee\xb8\x3c\x28\xa1\x79\xf8\xe9\x86\x3e\x2e\x5f\xa6\x53\x04\ +\x1e\x5e\xf7\x71\xf9\xbf\xfc\x37\x17\x26\x00\x10\x73\x3c\x33\x9e\ +\xba\x61\xf7\xac\xee\x12\xf7\x31\xf7\x76\xa6\xab\xbb\xa7\x04\xa2\ +\xa0\x7b\xd2\x5c\x87\x19\x88\x4f\x8d\xa7\x6e\xd6\x4b\x68\xb8\xc6\ +\xcf\xe7\xe7\x66\xba\xf6\x1f\x79\x05\xa2\x5e\x6c\xba\x7b\x43\x94\ +\x23\x03\x83\x53\xe3\xc9\x87\x0d\xb3\xd6\x52\xca\x7c\x6d\x8e\x80\ +\xde\xca\xa9\xeb\x0d\x77\x6d\x8e\x80\xcf\x0c\xbc\x69\xe6\xda\x9c\ +\x42\xa1\x68\x6f\xfe\x00\x06\x14\x1b\x10\x41\x9d\x58\x08\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\x15\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\xc7\x49\x44\x41\x54\x58\x85\xe5\ +\x97\x51\x48\x5d\x65\x1c\xc0\x7f\xff\xef\xea\x5d\xf3\xc1\x6d\x21\ +\xcc\x4a\xd9\x26\x2b\xb6\xa8\x1e\x5a\x0c\x0a\x56\x2b\xf5\x9a\x0c\ +\xa7\x33\x0e\x11\x42\x36\x6d\x16\x44\x2f\x41\xe0\xe8\xe1\x20\x45\ +\x13\x7a\x2a\xc6\x62\x4e\x2d\x22\x9f\xae\x57\x4b\x6b\xb6\x7b\x75\ +\x5c\x5f\x16\xc3\x42\x46\x2b\x84\xc8\x46\x5d\xb5\x88\x0d\x8d\x5a\ +\xea\xbd\xf7\xfb\xf7\x70\xaf\x76\xbd\xd7\x39\x2f\x5e\x7b\xd9\xff\ +\xe9\x9c\xef\xfc\xbf\xff\xef\xf7\x1d\xce\x39\xdf\xff\xc0\x9d\x1e\ +\x92\x4d\xb2\xaf\xf6\x78\xa9\xf5\xe4\xd5\x89\xb1\x15\xa8\x94\x02\ +\x25\x80\x11\x98\x52\x88\xa0\x3a\x8a\xe4\xf5\x87\x02\x67\x7f\xcc\ +\xa9\x40\x95\xd3\x7c\x30\x6e\x4d\xbb\xa0\x4f\xaf\xb3\xee\x18\xa2\ +\x27\x43\xbd\x5d\x23\x1b\x12\xa8\x70\x5a\xb6\x89\xb5\x1f\x02\x2f\ +\x24\x87\x66\x14\x06\x0d\x3a\x14\x47\x26\xbd\x26\x3e\xb3\x18\x8b\ +\xdb\x3c\xb3\xa5\x38\xae\x76\xb7\x88\xf8\x80\x5a\x60\x57\x32\xff\ +\xbc\x8d\xd2\x34\x32\xd0\xf9\x7b\xd6\x02\x55\x4e\xf3\x5e\x6b\x65\ +\x00\xd8\x9f\x00\x8b\x1b\xbb\x7e\xef\x47\xe1\x70\x5b\x6c\x2d\x69\ +\xd7\x75\xcd\xa5\xab\x53\xcf\x03\xef\x00\x65\xc0\x2f\xc6\xda\xa3\ +\x17\xfa\xbb\xaf\xac\x5b\xa0\xbc\xfe\x78\x99\xc1\x73\x19\xa1\x48\ +\xe0\x73\xcf\x5d\xff\xbc\x38\xd4\xd3\xf3\xe7\x5a\xe0\xf4\xa8\xae\ +\x7e\x7d\x4b\xb4\x60\xfe\x8c\xa0\x4d\xc0\xdf\x8a\x1e\x1a\x0e\x74\ +\x8d\xdf\x56\xa0\xba\xa1\xa1\x30\x36\x5f\xf0\x35\xe8\x83\xa0\xef\ +\x3f\xf1\x50\xc9\x1b\x6d\x6d\x6d\x36\x1b\x78\x6a\x7d\x5f\x7d\x73\ +\xab\x8a\xbc\x0b\x44\x8c\x9a\x83\x17\xfa\x3a\x66\x52\x13\x4c\xfa\ +\x8c\xd8\x7c\xc1\xe9\x04\x9c\xc1\x0d\xc2\x01\x34\xd8\xd7\xd5\x8e\ +\xd2\x09\x94\x58\x63\x3f\x25\x6d\xd1\x2b\x4e\x2a\x9f\x6b\x7a\x0c\ +\xcc\x18\xf0\x87\x1a\x73\xff\xb0\xbf\x63\x6e\x03\xf0\xe5\x70\x1c\ +\xc7\x3b\x6b\xb7\x5d\x01\xf6\x01\x47\x42\x81\xce\xf3\x4b\xd7\x56\ +\xdc\x01\xc1\x9c\x02\x50\x95\xb7\x73\x05\x07\xf0\xfb\xfd\x8b\x2a\ +\xbc\x95\x3c\x6d\x27\x65\xe1\xcb\x02\x55\xf5\x2d\xf7\x28\x94\x03\ +\x37\x76\x78\x66\xcf\xe6\x0a\xbe\x14\xc3\xbd\x9d\xfd\xc0\x04\xf0\ +\x70\xd5\xb1\xa6\x47\x32\x04\x14\x5b\x93\x30\x93\x2f\xfd\x7e\xff\ +\x62\xae\x05\x00\x45\x64\x00\x40\x3d\xe6\x58\xa6\x80\x70\x18\x40\ +\xd5\x7e\xb5\x09\x70\x00\x24\xae\x17\x00\xac\xf2\x4c\x86\x00\xaa\ +\xa5\x09\x3b\xfd\x79\xb3\x04\x8c\xe6\x4d\x02\x48\x62\x0f\x49\x13\ +\x90\xc4\x60\x7e\xd4\x3b\x93\x31\x33\x47\x21\x0b\xf9\x4b\xb5\xef\ +\x23\xf9\x20\x66\x7c\x07\xfe\xaf\x70\x5d\x37\x5d\x40\xa6\x00\x62\ +\x26\x56\xbc\x59\xd0\x85\xad\x37\x93\xb5\x75\x7a\xe9\x03\x97\xfa\ +\x0c\xfc\x0a\x20\xc2\x9e\xcd\x12\xc8\x47\xcb\x12\x2c\x22\x4b\x63\ +\xff\x09\x18\xc2\xc9\xa3\xaa\xcd\x12\x50\x31\x3e\x00\xc4\x5c\xcc\ +\x14\x58\xd4\xc1\xa4\xdd\x91\x03\x2d\x2d\xf9\x9b\xc0\x17\x45\x8e\ +\x26\xa9\xfd\x19\x02\xa1\x81\xee\x69\x84\x8b\x08\x45\x3b\xae\xdb\ +\x97\x73\x4d\xaf\xac\x3f\x51\x93\xdc\xe4\xbe\x0f\xf9\xcf\x2d\xf7\ +\x06\x2b\xde\x02\x6b\xa5\x15\x40\x04\xb7\xba\xa1\xa1\x30\x57\x70\ +\xc7\x71\xbc\x08\xa7\x00\x04\x3d\x09\xe8\xaa\x02\x23\x7d\xe7\xc6\ +\x54\xe9\x41\xd9\x19\x9f\xdf\xfa\x89\xeb\xba\xb9\x78\x4d\x65\x36\ +\xbe\xfd\x83\xe4\xea\xc3\xc1\x40\xd7\x17\xa9\x17\x33\x01\x1e\xf3\ +\x1a\x30\xa1\x50\x7b\xe9\x6a\xe4\xbd\x0d\x4a\x48\x65\x7d\xf3\x9b\ +\x88\xbe\x82\x30\x4d\xd4\x36\x90\xb2\x7a\xb8\x45\x4b\x96\xec\x07\ +\x2f\x03\x77\x03\x7d\x51\xe3\x6d\x0c\xfb\xcf\xfc\x95\x0d\xd9\x71\ +\x1c\xef\x9c\x2d\x3c\xad\xc8\x09\xe0\x26\xd8\xa7\x42\x81\xee\x6f\ +\xd2\xf3\x3c\xab\x4d\xfe\xe9\x87\xf1\x1b\x7b\xf6\x1d\xf8\x0c\xc1\ +\x27\x70\xc8\xa3\xf1\xc6\xbd\xfb\x1f\x9d\x2b\xdd\x59\xf3\xdd\xb5\ +\x6b\xa3\x6b\x76\x48\xae\xeb\x9a\xfc\xa2\x07\x9c\x05\xf5\xf6\x82\ +\x54\x92\x68\xc5\x7c\xc1\xbe\xce\x6f\x57\xcb\x5f\xb3\x2d\x3f\x5c\ +\xf7\xd2\xf6\x7c\x93\xd7\x81\xe0\x24\x87\x22\x02\x83\xa0\x43\x82\ +\x99\xc4\xd8\x99\x85\x68\xdc\x7a\x3d\xde\x62\x8b\xee\x02\xaa\x04\ +\xad\x25\xd1\x0d\x03\x12\x8c\x9a\x68\x63\xd8\xff\xf1\x6f\xb7\x62\ +\xac\xeb\xc7\xa4\xdc\x69\x7a\xdc\x58\xd3\x0e\x3c\xb9\x9e\x7c\x60\ +\x1c\xb1\xad\xa1\xde\xee\xe0\xed\x12\xb3\xfa\x35\x7b\xb6\xee\xd5\ +\xdd\x31\x13\xab\x13\x23\x15\xa2\x5a\xaa\x89\x6d\xd5\x03\x44\x80\ +\x88\xa8\x8e\x22\x9e\xfe\x60\xa0\x63\x22\x9b\xba\x77\x76\xfc\x0b\ +\xeb\x32\x64\xd4\x54\xc2\x43\x07\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x03\x64\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x16\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\xbf\x4f\x53\x51\x14\xc7\xbf\xdf\x17\x08\x90\x4e\xf2\x23\x02\ +\xee\x2e\x58\x17\x57\x4d\x4c\xac\x75\x73\xa8\x05\x23\x49\xd1\xa4\ +\xa5\x44\x13\xd0\x11\xfe\x02\x9d\xc1\x44\xac\x38\x68\x13\x4d\xa0\ +\xb2\x83\x6c\xb8\xba\x50\x98\x9c\x29\x92\x14\xb6\x0a\x44\xf2\x8e\ +\x03\x7d\x4d\x73\xfb\x6a\x11\x69\x4f\x1b\xee\x67\xba\x3d\xf7\xbe\ +\xf6\x7b\xbe\xbd\xf7\xdd\xe5\x1c\xc0\x62\xb1\x5c\x64\x78\x9a\x45\ +\xe1\x58\x2c\xe0\x1e\x74\x8c\x50\x10\x05\x70\x0d\xc0\x20\x80\xb6\ +\xba\x2a\xfb\x77\x8e\x01\xe4\x00\x6c\x0a\x91\x71\xba\x8e\x16\x57\ +\xd3\xe9\x42\xad\x87\x6a\x19\xc0\xf0\x83\xf8\x98\x80\x2f\x01\x0c\ +\x9c\x87\xca\x06\xb2\x23\xc4\xf4\x5a\x66\x21\x0d\x40\xaa\x2d\xaa\ +\x6a\xc0\x8d\x64\xb2\xbd\x3b\x2f\x73\xa0\x4c\xd4\x45\x5e\xa3\x10\ +\xbe\xdd\xef\xe5\xe4\xf7\x54\xea\xb7\xdf\x74\xb5\x6d\xcc\x4b\x7b\ +\xee\x6b\x10\x49\x23\x9e\x25\xf0\x4d\x20\x3f\x29\x8e\x7b\xbe\x4a\ +\xff\x0f\xa1\xeb\x10\xec\x17\xe0\x26\x80\x60\x69\x82\x32\xd1\x9d\ +\x07\x00\x3c\x85\xcf\x4e\xf0\xdd\x01\xa1\x68\x62\x8c\x82\x0f\x65\ +\xa1\x3d\x11\x99\x5a\x5b\x7e\xff\xd9\xef\x4b\x9a\x0c\x86\x22\xf1\ +\x47\x24\x67\x01\xf4\x78\x41\x21\x1e\xaf\x65\x16\x3e\x56\x2c\x36\ +\x03\xe1\x58\x2c\x20\xbf\x3a\x7e\xc0\x3b\xf3\x82\xbc\x03\xe7\xfa\ +\xca\x72\x6a\xa7\x8e\xa2\xcf\x9d\x7b\x91\xe4\x80\x0b\x77\x03\x44\ +\x2f\x00\x80\xc8\xb1\xeb\xe8\xaa\xf9\x62\x74\xcc\x07\xdd\x83\x8e\ +\x11\x94\xbd\xf0\x04\xf2\xbc\xd5\x92\x07\x80\x95\xe5\xd4\x0e\x1d\ +\xbe\x28\x05\x04\x83\x52\xe8\x1c\x36\xd7\x55\x18\x50\xbc\xea\x3c\ +\xb2\xc5\x6d\xdf\x92\xac\x66\xde\x7d\x02\x90\x2d\x05\x28\xb5\x0d\ +\xc0\xc9\x3d\x0f\x00\x10\x91\x75\x34\xff\x99\xff\x1b\x52\xcc\xc1\ +\x63\xc8\x5c\xe0\x67\xc0\xa0\x37\x20\xb1\x5b\x0f\x55\x8d\xc4\xc8\ +\xe1\x8a\x39\xef\x67\x40\xe9\x6a\x6c\xb6\xab\xee\x2c\x18\x39\x54\ +\x5c\xfb\x7e\x06\x5c\x28\xac\x01\xda\x02\xb4\xb1\x06\x68\x0b\xd0\ +\xc6\x1a\xa0\x2d\x40\x1b\x6b\x80\xb6\x00\x6d\xac\x01\xda\x02\xb4\ +\xb1\x06\x68\x0b\xd0\xc6\x1a\xa0\x2d\x40\x1b\x6b\x80\xb6\x00\x6d\ +\xac\x01\xda\x02\xb4\xb1\x06\x68\x0b\xd0\xc6\x1a\xa0\x2d\x40\x1b\ +\x6b\x80\xb6\x00\x6d\xac\x01\xda\x02\xb4\xb1\x06\x68\x0b\xd0\xc6\ +\x1a\xa0\x2d\x40\x1b\x6b\x80\xb6\x00\x6d\xac\x01\xda\x02\xb4\xf1\ +\x33\xe0\xd8\x1b\x08\xdd\x96\x37\xc8\xc8\xe1\xd8\x9c\xf7\x4b\x30\ +\x57\x7a\x58\x70\xb9\x1e\xa2\x1a\x89\x91\xc3\xb6\x39\xef\x67\xc0\ +\xa6\x37\x20\x79\x0b\xa7\xec\x29\x68\x52\x58\xcc\xc1\x63\xcb\x5c\ +\x50\x61\x80\x10\x99\xb2\x8f\xc1\x70\x24\x31\x52\x0f\x65\x8d\x20\ +\x1c\x1d\x7f\x88\xf2\xca\x71\xe1\x92\xb9\xa6\xc2\x00\xa7\xeb\x68\ +\x11\x40\xa9\x36\x58\x88\xb9\x3b\xf7\x13\x2d\x77\x14\x6e\x0f\x3f\ +\xe9\x17\x91\xd9\x52\x80\xc8\x31\x70\x58\xdb\x80\xd5\x74\xba\x20\ +\xc4\x74\x59\xa8\xcf\x69\x47\x36\x14\x89\x8f\xa2\x35\x8e\x03\x43\ +\x91\xf8\x68\xbb\xdb\xb6\x01\xa0\xcf\x0b\x0a\x30\xe3\xd7\x42\x53\ +\x2d\x21\xde\x8d\x8c\xbf\xf1\xe9\x16\xc9\x8a\xc8\x3a\x89\xdd\x66\ +\xab\x22\x15\xba\x8e\x08\x2e\x17\xcf\x7c\xd0\x98\x9e\xff\xfa\x65\ +\xe1\x19\x7c\xea\x9e\xab\x75\x8c\xc8\x7e\x2f\x27\xbb\xf3\x80\x61\ +\x42\x90\x64\xf0\xe4\x07\x9b\xad\x86\x9a\xa0\xff\xdf\x39\xbf\xdf\ +\xe3\x4c\xa1\x4a\xd1\x77\xcd\xa6\xa9\x50\x34\x11\xa3\xe0\x15\x5a\ +\xad\x69\x8a\xc8\x09\x30\x73\xe6\xa6\xa9\x72\xc2\xb1\x58\x40\x0a\ +\x9d\xc3\xc5\x7a\xfb\x21\x9c\x54\x5d\x37\x63\xdb\xdc\x36\x80\x2d\ +\x08\x97\x18\x38\x5c\x3a\x4d\xdb\x9c\xc5\x62\xb9\xd8\xfc\x01\xdf\ +\x73\xe1\xb5\xcf\x33\xa6\xd1\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ +\x42\x60\x82\ +\x00\x00\x00\xc8\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x7a\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\xb1\x6d\xc2\x60\x14\x85\xd1\xef\x67\x88\x88\x81\x32\x01\x62\ +\x83\xd0\x78\x22\x9a\xac\x90\x36\x0d\x0b\x59\x2c\xe1\xb4\x91\x5d\ +\x83\x25\x38\xa7\xbc\x7a\xc5\x7d\xb7\x00\x00\x00\x00\x00\x00\x80\ +\x77\x30\xd6\xc1\xe7\xf9\x72\x1a\x4b\xd7\xea\x63\x87\x3e\x0f\x33\ +\x6a\x5e\xea\xeb\xf6\xf3\xfd\xfb\x3f\x3f\x6c\x0e\x5f\xf0\xf9\xaa\ +\xa5\x8e\xd5\x75\x9d\x6f\x06\x78\x37\x9b\x01\x96\xd1\x54\xdd\x77\ +\xe8\xf2\x50\xa3\xe6\x6a\xda\xbb\x07\x00\x00\x00\x00\x00\x00\x00\ +\xf0\x7c\x7f\x0b\xd1\x0f\x08\x20\x9f\x5b\xc7\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x04\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xb6\x49\x44\x41\x54\x78\x9c\xed\ +\xd9\x41\x0d\xc3\x40\x10\xc5\xd0\x69\x14\x4e\xe1\x51\xa0\xe1\x11\ +\x52\x9b\xc2\x78\x95\xd6\x26\x30\x96\xf5\x6f\x33\x03\xb9\xee\xf5\ +\x5e\xf7\x7a\xa5\xc3\x21\x8f\xff\x03\x05\xd0\x02\x9a\x02\x68\x01\ +\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\ +\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\ +\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x6c\ +\x1f\xe0\x23\x8f\xeb\xd7\xf8\x4c\x0b\x98\x53\x0b\xcc\xcc\x3c\xdf\ +\x83\x2d\x71\xfb\x05\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\ +\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\ +\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\ +\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\xb3\x7d\x80\x1f\x17\ +\x67\x0a\x44\xf8\xee\xeb\x4c\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ +\x42\x60\x82\ +\x00\x00\x02\x1d\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xcf\x49\x44\x41\x54\x58\x85\xed\ +\xd6\x3d\x8b\x53\x41\x18\xc5\xf1\xff\x99\x44\xf1\x05\x5f\x3a\x41\ +\x1b\x11\x2b\x0b\xb5\x31\x61\x11\x4b\x49\xb3\xb2\x59\x65\xd7\x46\ +\xd0\xd6\x42\xf6\x13\x88\x2c\x7e\x01\x51\xb0\x16\xb1\x90\x15\xcd\ +\x2e\x04\x71\xb1\x14\x89\x49\xa5\x16\x56\x16\x6b\x23\xd8\x28\x8b\ +\xf8\x82\x26\x73\x2c\xe6\x46\x2c\x73\x93\x30\x16\xfa\x14\x97\x5b\ +\xcc\xcc\xf9\xcd\xdc\x67\xe0\xc2\xbf\x5e\x1a\x65\x50\xad\x15\x3f\ +\xc9\x28\xf4\x75\xa8\xb3\xa8\x8f\xd3\x04\x84\x51\x06\xc9\xec\x05\ +\xf6\xc4\xaa\xdb\x47\xd7\xbd\x33\x3b\xe0\x8f\x9a\xd9\xfe\xd5\x0f\ +\x8f\xac\x78\xeb\x5f\x01\x38\x3d\x1a\xbb\xb6\xc4\xbb\x0b\x2b\xae\ +\x64\x07\x60\x22\xc2\x58\xe7\xdf\x55\xe2\x2d\xec\x91\x7a\x68\x6a\ +\x00\x09\x63\x6c\x83\xa4\xcb\xf5\xd5\xb8\x9c\x15\x50\x94\x81\x98\ +\xde\x74\xb5\xde\xf2\x52\x6e\x00\x12\xf6\x6f\x84\x6f\xd4\x5b\xbe\ +\x90\x15\x00\x20\xb0\xd1\x10\x71\xa7\xf6\xc8\xb3\x59\x01\x09\x61\ +\x1b\x1b\xa8\x08\x3f\xa8\xad\xfa\x54\x56\x40\x42\x28\x92\x10\xdb\ +\x14\xdd\x3e\xd1\xf2\xf1\xac\x80\x82\x11\x9d\x9a\x73\x77\xb0\x9f\ +\xcc\xac\xf9\x70\x66\x00\x28\x35\xa5\x81\x7d\x71\xe0\xa7\x27\xd7\ +\xbc\x3f\x2b\xa0\x50\xc4\xf4\x35\x38\xd8\x1f\xf8\x71\x7e\x40\x42\ +\x0c\xeb\x58\x7e\x80\x09\x85\x60\xa3\x5a\xd1\x81\xac\x00\x8b\x40\ +\x4a\xff\x10\x2a\x3a\xfd\x7c\x4e\xef\x33\x02\x1c\x64\x04\x6c\x1a\ +\x35\x3a\x73\x7a\x3b\xea\xcc\xea\xc4\xd1\x38\x08\x09\xf8\xee\xa0\ +\x33\xbd\xa6\x5e\x95\x99\x3f\xd1\x09\xd8\x52\x11\x3e\x30\x5a\xe8\ +\x35\xf5\xac\xec\x1a\x63\x9f\x80\x8d\x24\xa7\x0d\x48\x97\x7a\xf3\ +\x6a\x8f\xb3\xce\xb8\x27\x20\xa5\xa6\x43\x68\xa9\x3b\xaf\x7b\x63\ +\xae\x53\x1e\x60\x23\x18\xee\xdc\xd7\x5f\x9c\xd5\xcd\x71\xc3\x4b\ +\x03\x9c\x7e\x05\xd2\x5d\x97\x6f\x77\x9b\xe1\xda\x24\xe1\xa5\x01\ +\xc2\x21\xf5\x9c\xef\x77\x5f\x86\x2b\x48\xce\x0a\x48\x3b\x67\xfd\ +\x73\x3f\x5c\x64\xb9\xf8\x19\x99\xb0\xca\xde\x82\xce\xb7\x1d\x3a\ +\xf7\xa6\xa1\x1f\xd3\x08\x2f\x03\xd8\x44\x56\xf8\x19\x66\x5f\x37\ +\xf4\x65\x5a\xe1\xff\x0b\xe0\x17\x0f\x9e\xa4\x40\x97\xf1\x9c\xea\ +\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xf8\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xaa\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\x31\x15\x80\x30\x00\xc4\x50\x8a\xa6\x7a\x62\x43\x0c\x1b\x9e\ +\xf0\x54\x56\x1c\x7c\x86\x64\xbb\xe9\xf2\x32\x36\xc4\x3c\xae\xf5\ +\xdd\xcf\x7d\x0e\xe1\xb1\x8b\xd3\x3f\x51\x00\x2d\xa0\x29\x80\x16\ +\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\ +\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\ +\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\ +\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\ +\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\ +\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\ +\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\ +\x80\xe6\x05\x58\xe1\x04\x80\x5c\x86\x43\xbc\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x4d\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xff\x49\x44\x41\x54\x78\x9c\xed\ +\xd6\xa1\x4a\x04\x51\x14\xc6\xf1\xef\xcc\x8c\x08\x06\xd3\xda\x7d\ +\x01\x41\x50\xb0\xda\x5c\xb6\x6c\xf1\x39\x2c\x3e\x80\xec\x03\xec\ +\x4b\xd8\x2d\xc2\x8a\xb6\x29\x86\x8d\xbe\x81\x69\x41\x6c\x06\x19\ +\x41\xef\x31\x58\xe4\x5e\xb5\xcd\x59\x70\xfe\xbf\x78\xce\x84\xef\ +\x7e\xe1\xce\x95\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x41\xb0\ +\x3f\xb7\xee\x76\xdc\xaa\x0e\xca\xd2\x8b\xb6\x55\xd2\xcc\xd2\x6f\ +\xfb\x1f\x0b\x38\xb8\xf6\x51\xf3\x9e\xe6\x92\x9d\x4a\xda\xea\x2d\ +\x5d\x8c\x4e\xae\x45\xd3\xd8\xd9\xfd\xd4\x56\xf9\xb2\x28\xe0\xe8\ +\xc6\xb7\xd5\xf9\x83\xa4\xdd\x88\x74\x51\x5c\x7a\xb6\xda\xf6\x96\ +\x53\x7b\xfa\x3e\xaf\x8a\x2f\xdf\xd2\x4c\xff\xec\xf0\x92\x64\xd2\ +\x8e\x7f\xa4\x79\x3e\x2f\x0b\x70\x3b\x09\x49\xb4\x06\x26\x1b\xe7\ +\xb3\xb2\x80\x81\x29\x0b\x30\xbf\x5b\x43\x8e\x10\x2e\xbf\xcd\x67\ +\x65\x01\x9b\xd5\x85\xa4\xc7\x80\x3c\xa1\xbe\x2e\xc1\xea\x3c\x9f\ +\x17\x05\x2c\x27\xf6\xe2\xb2\x43\xc9\x2f\x25\xbd\x86\xa4\xeb\x57\ +\x27\xd7\xd5\x46\x6d\xfb\xf9\x1f\x40\xe2\x21\x04\x00\x00\x00\x00\ +\x00\x00\x00\x00\x00\x0c\xc5\x27\x17\xb6\x3b\xc1\x0d\x7c\x50\x9f\ +\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x22\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xd4\x49\x44\x41\x54\x58\x85\xed\ +\xd6\x31\x6b\x14\x41\x18\xc6\xf1\xff\x33\x17\x8d\x20\xd1\x74\x1e\ +\xde\xed\xad\x1c\x96\x82\xb6\x16\x96\x92\x26\x56\x22\x36\x82\xb6\ +\x16\x92\x4f\x20\x22\x7e\x01\x51\xb0\x16\xb1\x10\xc4\xee\x10\xc5\ +\xd2\xc2\x5a\xb8\x52\x48\x76\x37\x91\xb3\x51\x03\x11\x8c\x72\xf3\ +\x58\xec\x5d\x5a\x6f\xef\x96\x4d\xa1\xd3\xec\x2e\xcc\x3b\xcf\x6f\ +\xdf\x9d\x81\x85\x7f\x7d\x68\x96\x49\x5b\x59\xfe\x0d\xa4\x56\xa0\ +\x9f\x24\xc9\xd7\x3a\x01\x61\xb6\x69\x5a\x05\x4e\x8e\x23\x83\xd1\ +\x68\x74\xfc\x10\x00\x07\xe3\xe2\xfe\xfe\xef\x57\xc3\xe1\xf0\xe8\ +\xe1\x00\x6c\x0c\x6b\x2b\x2b\xab\xcf\x6c\xb7\x9a\x07\xa0\x28\x61\ +\xe3\xeb\x59\xb6\xf3\xd8\xf6\x4c\x7b\xa8\x3e\x80\x70\x34\x2e\xef\ +\x7d\x3b\x2b\x76\xee\x37\x0b\x00\x04\x06\x47\xdb\x60\xdf\xcd\xb2\ +\x62\xa3\x51\xc0\x84\x61\x29\x44\x00\xc3\xc3\x2c\x2b\x6e\x34\x0c\ +\x00\xb0\x91\xa6\x88\xa7\x59\xb6\xbd\xde\x30\x00\xb0\x4d\xb9\x27\ +\x5a\xc6\x2f\xf3\x3c\xbf\xd4\x2c\x00\x40\x44\xb0\x81\x63\xd1\x1a\ +\x6c\x6e\x6e\x5f\x68\x16\x50\x2a\x22\x60\xe0\x84\x02\x6f\x8a\xa2\ +\x38\xdb\x30\x00\x80\x38\x39\x21\xa7\xc6\x51\xef\xf2\x3c\x3f\xdd\ +\x34\x00\x43\x2c\x1b\xe1\x33\x11\xbd\x6e\x1c\x30\x55\x4c\xae\xe7\ +\x1b\x07\x08\x02\x12\xa0\xad\x20\x77\x66\xa9\x59\xaa\x31\x3f\x18\ +\x04\xfa\xd2\x0a\xbe\x9c\x24\xbd\xcf\x33\x15\xd5\x93\xed\x40\xf9\ +\x73\xb3\x1b\xc7\xac\x25\x49\xf2\x69\xd6\xca\x85\x01\x86\x40\xd9\ +\xf7\x9f\x41\xbe\xd2\xef\x77\x3f\x56\xa9\x5f\x10\x20\xa9\x7c\xf3\ +\xb1\xd0\xb5\x5e\xaf\xf7\xbe\xea\x0a\x8b\x00\x34\x69\x3d\x82\x5b\ +\x69\xda\x1d\xcc\xb3\xc8\xbc\x00\xd9\x07\xe1\x1b\x69\x9a\x3c\x9f\ +\x73\x9d\xea\xa7\xc0\xe5\x07\x0f\x65\xf3\xf5\x20\xed\x75\x1f\xcd\ +\x1b\x0e\x15\x3b\x60\x97\xe1\xe5\x83\x9e\xa4\x49\xe7\xde\x22\xe1\ +\x95\x01\x92\xa7\xe1\x2f\xd2\xb4\x73\x47\x92\xff\x52\x52\x2f\x00\ +\x84\xe0\xed\xde\xde\xf7\x9b\x9a\xfc\x8c\x2c\x3a\xaa\xee\x81\x0f\ +\xcb\xcb\x47\xae\xa6\xe9\xb9\x5f\x75\x84\x57\x00\x78\xd7\x46\x4b\ +\x2d\xad\xb7\xdb\xed\x1f\x75\x85\xff\x1f\x00\x7f\x00\x61\x3f\xa0\ +\x35\x7d\x81\xed\xd8\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ +\x82\ +\x00\x00\x04\xe7\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x99\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\xbd\x6f\x1c\x45\x18\xc6\x9f\x77\xf7\x1c\xa4\x74\xa9\x4c\x74\ +\x1f\x63\x1f\x4e\x91\x28\x52\x90\x92\x2e\x6d\xa0\x09\x50\x60\xa4\ +\x80\x44\xa2\xfc\x03\x11\x69\x40\xd8\x12\x4e\xb0\x14\x02\xa1\x81\ +\xbf\x00\x24\x2c\x50\x44\x42\x11\x39\x8d\xa1\x4a\x5a\xa7\x41\x60\ +\x37\xe1\xd8\x8f\xbb\x22\x14\x50\x22\x87\xdb\x7d\x28\xce\x23\xf6\ +\x6e\xf7\xbc\x7b\xde\x4f\xe3\xfb\x49\x2e\x76\xe6\xbd\x9b\x77\x1f\ +\x3f\xef\xec\xec\x69\x06\x98\x32\x65\xca\x61\x46\x92\x04\x91\xac\ +\xd9\x76\xf7\x0d\x0a\x2f\x09\xe4\x1c\x80\x3a\x80\x17\xf2\x4d\x6d\ +\x62\x76\x00\xf4\x08\x6e\x0a\xe5\xae\x52\x8d\x07\x22\xd2\x8f\xfb\ +\x50\xac\x00\xb6\x6d\xbf\x42\xc8\x97\x80\x9c\xcc\x24\xcd\xe2\xd8\ +\x12\xf8\xd7\x95\x52\x3f\xee\x15\x64\x8c\xeb\x20\x29\x96\xd3\x5d\ +\x26\x8c\x8d\x03\x78\xf3\x00\x70\x8a\x30\x36\x7e\xb7\xbb\x4b\x24\ +\xc7\xfe\xa3\xc7\x0a\x60\xbb\xbd\x25\x90\xb7\xf2\xc9\xad\x38\x04\ +\xfc\xc4\x72\x7a\x1f\x8e\xef\x8f\x60\x60\x7b\x63\x63\xa4\xf9\x2f\ +\x10\x2b\x80\xf7\x50\x29\xe5\x88\x88\x97\x69\xa6\x29\x21\x69\xda\ +\xb6\xdd\x02\xcc\x8b\x10\xac\x02\x38\x16\xec\x17\xf8\xaf\x46\x95\ +\x43\x48\x00\x92\x35\xdb\x71\x7f\x1e\xb6\x3d\x7f\xf2\xbd\xfe\xbb\ +\xed\x76\xfb\x59\x0e\xb9\x67\x4e\xa7\xd3\x99\x35\xcc\xda\x1a\x20\ +\x17\x02\xcd\x5b\xaa\xd5\x38\x33\x3a\x31\x86\x04\xb0\x2c\xf7\x4d\ +\x08\xee\x07\x9a\xfe\xec\xff\x33\x73\x72\x61\xe1\xc5\x3f\xf2\x4a\ +\x38\x0f\x06\x22\xcc\x6c\x23\xe8\x04\x62\x71\x6e\xae\xf9\x43\x30\ +\x2e\x34\x07\x50\x78\x69\xb8\x01\x37\x0e\xda\xcd\x03\x40\xbb\xdd\ +\x7e\x26\xc0\x8d\x60\x5b\xe8\xde\x10\x21\xc0\xee\x73\x3e\x80\xf7\ +\x30\xeb\xe4\x8a\x82\xf4\xd6\x83\xd7\x02\x39\x3b\x1a\x13\xf5\x14\ +\xa8\x07\x2f\x94\x52\x4e\xc6\x79\x15\x46\x44\xee\x8d\xd1\x98\x28\ +\x01\x86\x56\x78\x55\x9b\xed\x27\x21\x22\xf7\xd0\xea\x75\xec\x3a\ +\xe0\xb0\x50\x2b\x3b\x81\x24\xb8\xae\xbb\xe0\xf9\x58\x01\xb0\x08\ +\x00\x04\xef\x99\x82\xd5\x56\xab\xf5\x5b\xda\xef\xae\xbc\x03\x5c\ +\xd7\x3d\xe1\xf9\x78\x04\xe0\x32\x80\xa3\x00\x8e\x0a\xe4\x8a\x4f\ +\x79\xec\xba\xee\x42\xda\xef\xaf\xb4\x00\x24\x6b\x9e\x8f\xef\x00\ +\x1c\x8f\xe8\x3e\xde\xf7\xf9\x51\xda\x31\x2a\x2d\x80\xed\xf6\x3e\ +\x00\x10\x7a\x74\x69\x04\xf2\x56\xda\x31\x2a\x2b\x80\xe3\x38\xa7\ +\x41\xde\xcc\x7b\x9c\x4a\x0a\x40\xb2\xe6\x53\xbe\x06\x30\xb3\x57\ +\x9c\x80\xdf\xa7\x1d\xab\x92\x02\xc4\x59\x7f\x97\xe7\x00\xef\xa4\ +\x1d\xab\x72\x02\x24\xb5\x3e\x21\x37\x95\x52\x5b\x69\xc7\xab\x94\ +\x00\x49\xad\x0f\x60\x73\xae\x55\xff\x3c\x8b\x31\x2b\x25\x40\x52\ +\xeb\x0b\xfc\xab\x49\x7e\xf0\x4c\x42\x65\x04\x98\xd0\xfa\xbf\x66\ +\x35\x6e\x25\x04\x28\xc3\xfa\x9a\x4c\xde\x05\x1c\xc7\x79\xc9\x23\ +\x56\x02\x0b\x93\xfb\xa6\x81\xd5\x66\xb3\xf9\x34\xc9\xe7\xcb\xb0\ +\xbe\x26\xb5\x03\x5c\xd7\x5d\xf0\x29\x8f\x05\x72\x05\xbb\x6b\x75\ +\x00\x97\x3d\x1f\x8f\x5c\xd7\x3d\x11\xf7\xf9\xb2\xac\xaf\x49\x2d\ +\xc0\xee\x5b\x5a\xe4\x5a\xdd\xf3\xf1\x2d\xc9\xb1\x2e\x2b\xd3\xfa\ +\x9a\x2c\xe6\x80\xc5\x3d\xfa\xce\x59\x4e\xef\xfd\x71\x9d\x65\x5a\ +\x5f\x93\xfb\x24\x28\xe0\x4d\xc7\x71\x4e\x8f\xb6\x97\x6d\x7d\x4d\ +\x6a\x01\x08\xde\x8b\x09\x39\xe2\x53\xbe\x0a\x96\x42\x15\xac\xaf\ +\x49\x2d\x80\x01\x7e\x06\xe0\x79\x4c\xd8\x50\x29\x54\xc1\xfa\x9a\ +\xd4\x02\x28\xa5\xb6\x20\xf2\x71\x5c\x9c\x2e\x85\xaa\x58\x5f\x93\ +\xc9\x1c\xa0\x9a\xf5\x3b\x00\x9e\xc4\x84\x1d\xf1\x29\xdf\xf8\x90\ +\x35\x54\xc0\xfa\x9a\x4c\x04\x10\x91\xbe\x21\xbc\x8a\xf8\x52\x78\ +\x19\xc4\x99\x98\x98\x42\xac\xaf\xc9\xec\x29\xd0\x6a\xb5\x7e\x49\ +\x52\x0a\x71\x14\x65\x7d\x4d\xa6\x8f\xc1\x84\xa5\xb0\x17\x85\x59\ +\x5f\x93\xa9\x00\x13\x94\x42\x14\x85\x5a\x5f\x93\xf9\x42\x68\xbf\ +\xa5\x50\xb4\xf5\x35\xb9\xac\x04\xf7\x51\x0a\x85\x5b\x5f\x93\x8b\ +\x00\x13\x96\x42\x29\xd6\xd7\xe4\xf6\x2e\x90\xb4\x14\xca\xb2\xbe\ +\x26\xd7\x97\xa1\x04\xa5\x50\x9a\xf5\x35\xb9\x0a\x20\x22\x7d\xd3\ +\xc0\xdb\x10\x84\x37\x59\x08\x1c\xd3\xc0\x3b\x65\x59\x5f\x93\xfb\ +\xeb\x70\xb3\xd9\x7c\x5a\x33\xe4\x3c\x80\x75\x00\x7f\xef\xfe\xad\ +\xd7\x0c\x39\x9f\xf4\x27\xb3\x3c\x29\x64\x7f\x40\xa3\xd1\xe8\x02\ +\x78\xbd\x88\xb1\x26\xa5\x12\xbf\x0a\x97\x49\x94\x00\x3b\xc1\x0b\ +\x92\x66\x41\xb9\x64\x4e\x44\xee\x3b\xa3\x31\x51\x02\xf4\x82\x17\ +\x83\xed\xa7\x07\x93\x88\xdc\xbb\xa3\x31\xe1\x8d\x92\xe0\xe6\x70\ +\x8b\x79\x31\xd3\xac\x0a\x44\xc4\x7c\x2d\x78\x4d\x30\xf4\x48\x0e\ +\x6f\x94\xa4\xdc\x1d\x6e\xc0\x6a\xa7\xd3\x99\xcd\x3c\xbb\x9c\xe9\ +\x74\x3a\xb3\x04\x86\x16\x62\xa1\x7b\x43\x84\x00\x4a\x35\x1e\x00\ +\xdc\x0e\x34\x1d\x33\xcc\xda\xda\x41\x12\xe1\xbf\xcd\xd2\x43\x3b\ +\xc6\xb7\x06\xf7\x36\x4c\xd8\x01\x22\x7d\x01\xdf\x1b\x69\xbd\x60\ +\x98\x33\xdb\xb6\xed\x5e\xb3\x2c\x6b\xbe\x8a\x13\x23\x49\xd3\xb2\ +\xac\x79\xdb\x76\xaf\x0d\x36\x49\x0f\xed\x14\x87\xc0\xbf\x1e\xb5\ +\xe8\x1a\x7b\x92\xc2\x72\xba\xcb\xff\x87\x03\x13\x00\x40\xc8\xf2\ +\xbc\x6a\xdc\x8e\xea\x1b\xbb\x0e\x50\xcd\xfa\x6d\x42\x96\xf3\x4b\ +\xab\x10\x48\x60\x69\xae\x55\xff\x74\x5c\x40\xc2\x43\x53\xc6\x17\ +\x00\x4e\x65\x9a\x5a\xfe\x24\x3a\x34\xb5\x9f\x63\x73\x67\x31\xd8\ +\x75\x5d\xc5\x63\x73\x5d\x82\x4f\x26\x39\x36\x37\x65\xca\x94\xc3\ +\xcd\xbf\x5b\x3f\xf6\x3c\xa0\xff\x9c\x5c\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\xf5\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\xa7\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\xcf\x6f\x15\x55\x14\xc7\xbf\x67\xa6\x85\xc2\xca\xe7\xa6\x21\ +\x10\x58\x58\x16\x36\x4d\x30\xf1\xa5\x2f\x95\x4d\x9b\xa8\x1b\x90\ +\x96\x02\xa2\x11\x08\x7f\x82\x1b\x89\x6d\x62\x5b\x9b\x28\x8a\x1b\ +\xfd\x0b\x34\xb1\xd1\x00\x6d\xf1\x91\xb2\xa9\x26\x6d\x20\x81\x3c\ +\x2d\x1b\xa3\x75\x83\x0b\x9a\xb2\xa8\x8b\xd6\x15\x2d\xd0\xb9\x5f\ +\x17\x7d\x53\x66\xe6\xcd\x74\xe6\x31\x77\x7e\xd4\xbe\x4f\xf2\x16\ +\x73\xee\x79\xef\x9e\x7b\xde\xf7\xdc\xb9\x33\xb9\x17\x68\xd0\xa0\ +\xc1\x4e\x46\xa2\x38\x75\xcf\xb0\x69\x6d\x05\x27\x14\xd4\x59\x81\ +\x14\x09\xec\x17\x60\x77\xd2\xc1\xd5\x03\x81\x27\x02\x3c\x22\x38\ +\x67\xc0\xb8\xda\x52\xc0\xcd\xd9\x1e\x59\x0f\xfb\x5e\x68\x02\x4a\ +\x93\x7c\x0b\xe0\x37\x00\x5e\xd5\x12\x69\x7a\xcc\x03\xf2\x61\xa5\ +\x5f\x7e\xde\xca\xc9\x08\x6c\x21\xa5\x73\x82\x83\x00\xa7\xb1\xfd\ +\x06\x0f\x00\xed\x00\xa7\x4b\x37\x38\x00\x32\xf0\x8f\x0e\x4c\x40\ +\xe7\x24\x06\x44\xf8\x59\x32\xb1\xa5\x08\xf9\x79\xe9\x27\x7c\x1c\ +\xd4\xec\x9b\x99\xaa\xec\xa7\x3d\xe6\x15\x8a\x0c\xc1\xc4\xad\x43\ +\x6b\x58\xb8\xfe\xae\x58\x5a\x03\x8d\xc9\x99\x6b\x34\x1f\xb6\xe0\ +\x20\x2c\x1c\x13\x72\x14\x40\xc1\xed\x21\x6f\xfb\x95\x43\x4d\x02\ +\xba\x67\xd8\xb4\xba\xc2\xdf\xe1\x94\xbd\xe0\x17\x18\x72\xae\xd2\ +\x2b\x4b\xda\x23\x4f\x80\x52\x99\xad\x50\x1c\x03\xf1\xa6\xc3\x3c\ +\xbf\xa7\x20\x47\xbc\x13\x63\x4d\x09\xac\xad\xe0\x04\xdc\x35\xbf\ +\x6c\x52\x3e\xd8\x2e\x83\x07\x80\x4a\xaf\x2c\xc1\x90\x73\x00\x56\ +\x1c\xe6\xf6\xea\xd8\x5c\xd4\x24\x40\x41\x9d\x75\x5e\x53\x64\xf8\ +\x6e\xbf\xfc\xa3\x3f\xcc\x64\xa9\xf4\xca\x92\x50\x86\x9d\x36\xef\ +\xd8\x00\x9f\x04\x08\xa4\xe8\x32\x98\xb8\xa5\x3d\xba\x94\x50\xcd\ +\x98\x72\x5b\xe4\x75\xaf\x4f\x4d\x02\x08\xec\x77\x5e\x1f\x5a\xc3\ +\x82\xee\xc0\xd2\xc2\x27\xf6\x03\x5e\x1f\x1f\x05\xb8\x57\x78\x79\ +\x9b\xed\xeb\xc1\x1b\xbb\xdf\xea\x35\x78\x21\xb4\x43\x68\xca\x3a\ +\x80\x28\x74\x95\xd9\xa6\x94\x1a\x02\xe5\xd4\x86\x85\xe3\xa6\x18\ +\xa3\x77\x4f\xca\xdf\x71\x7f\x3b\xf7\x0a\x28\x8d\xf3\xb0\xb2\x78\ +\x1b\x94\xf3\x00\xf6\x6e\x7c\xe4\x82\x45\xde\xe9\x2a\xb3\x2d\xee\ +\xef\xe7\x3a\x01\xdd\x33\x6c\x82\xc1\x1f\x01\xec\xf3\x69\xde\xa7\ +\x2c\xf5\x49\xdc\x3e\x72\x9d\x80\xc7\xcb\xb8\x04\xa0\xe6\xd6\xf5\ +\x1c\x39\x1d\xb7\x8f\xdc\xce\x01\xc5\x49\x76\x08\x38\x92\x74\x3f\ +\xb9\x54\x40\xf7\x0c\x9b\x4c\xf0\x3b\x00\xcd\x5b\xf9\x09\x78\x3d\ +\x6e\x5f\xb9\x4c\x40\xb8\xf4\x01\x00\x4f\x69\x18\x57\xe2\xf6\x95\ +\xbb\x12\x88\x2c\x7d\x91\x91\x4a\x9f\xcc\xc7\xed\x2f\x57\x0a\x88\ +\x2a\x7d\x08\xe6\xf6\xbc\x84\xaf\x74\xf4\x99\xab\x04\x44\x95\xbe\ +\xb2\xe4\x62\x94\x17\x9e\x51\xc8\x4d\x09\xd4\x23\xfd\xdf\x4e\xcb\ +\x9f\xba\xfa\xcd\x85\x02\xb2\x90\xbe\x8d\x16\x05\xbc\x71\x83\xaf\ +\x58\x54\x43\x9b\x0b\x13\xe1\x84\x61\x18\xa3\xf7\x7a\xe5\x41\x94\ +\xef\x3f\x5e\xc6\x25\x91\x74\xa5\x6f\x13\x5b\x01\x5d\x65\xb6\x59\ +\xe4\x1d\x40\x2e\xc0\x5e\xab\x53\xce\x2b\x8b\xb7\x4b\xe3\x3c\x1c\ +\xf6\xfd\xe2\x24\x3b\x44\xd2\x97\xbe\x4d\xec\x04\x28\xa5\x86\x10\ +\xb0\x56\x87\xc9\x1f\xba\x67\x18\xa8\xb2\x2c\xa5\x6f\x13\x7f\x0e\ +\xd8\x7c\x44\xf5\x6b\x43\x71\xf5\x5f\x7c\x14\xd4\x9c\xc5\xac\xef\ +\x25\xf9\x49\x90\x1c\x29\x4e\xb2\xc3\x6b\xce\x5a\xfa\x36\x1a\x12\ +\xc0\xf1\x10\x87\x5d\xa6\xf0\x5b\x67\x29\xe4\x41\xfa\x36\xf1\x13\ +\x60\x18\x5f\x02\x78\xba\xa5\x8f\xa7\x14\xf2\x20\x7d\x9b\xd8\x09\ +\xa8\xf4\xc9\x3c\x29\x9f\x86\x3a\x56\x4b\x21\x2f\xd2\xb7\xd1\x32\ +\x07\xec\x7d\x19\x57\x00\xdc\x0f\x71\xdb\x65\x82\xdf\x9b\xe0\x18\ +\x72\x20\x7d\x1b\x2d\x09\x98\xed\x91\x75\x0b\x72\x11\x61\xa5\x00\ +\xbc\x06\xe0\x48\x88\x4f\x2a\xd2\xb7\xd1\x76\x17\x98\xeb\x97\x3f\ +\x22\x95\x42\x18\x29\x49\xdf\x46\xeb\x6d\x30\x62\x29\x04\x93\xa2\ +\xf4\x6d\xb4\x26\xa0\x8e\x52\xf0\x23\x55\xe9\xdb\x68\x5f\x08\xbd\ +\x70\x29\xa4\x2c\x7d\x9b\x44\x56\x82\x75\x97\x42\x06\xd2\xb7\x49\ +\x24\x01\x75\x96\x42\x26\xd2\xb7\x49\xec\x59\x20\x72\x29\x64\x24\ +\x7d\x9b\x44\x1f\x86\x42\x4b\x21\x43\xe9\xdb\x24\x9a\x80\xd9\x1e\ +\x59\x37\x4c\x79\x4f\xa4\x76\x93\x85\x08\x16\x0c\x43\xde\xcf\x4a\ +\xfa\x36\x89\x3f\x0e\xdf\xeb\x95\x07\x54\x72\x54\x80\x29\x00\xab\ +\x00\x56\x05\x98\xa2\x92\xa3\x51\x5f\x99\x25\x49\x2a\x6f\x85\x2b\ +\xa7\x64\x11\xc0\x3b\x69\xf4\x55\x2f\xb9\x78\x2b\x9c\x25\x7e\x9b\ +\xa4\x9e\x38\xaf\xcf\x5c\xa3\x99\x5e\x38\x7a\xf1\xc6\xee\x1d\x1b\ +\xe0\xbf\x49\xea\x91\xf3\xfa\x61\x0b\x0e\xea\x0f\x2d\x1d\x7c\x62\ +\x5f\xf4\xfa\xf8\x28\x80\x73\x2e\x83\x85\x63\x7a\xc3\x4a\x0f\xe3\ +\x19\x8e\xbb\x2d\xac\xb9\x25\xd7\x24\xc0\x80\x71\xd5\x79\x2d\xe4\ +\x68\xa9\xcc\x56\xdd\xc1\x25\x4d\xa9\xcc\x56\x0a\x5d\x0b\x31\xef\ +\xd8\x36\x6c\x1e\x5a\x0a\xb8\x09\xe0\x2f\x87\xa9\x00\xc5\xb1\xed\ +\x94\x84\xcd\xcd\xd2\xee\x1d\xe3\xf3\xd5\xb1\xb9\xa8\x6b\xbb\xbc\ +\x50\x86\x55\x33\xa6\xf2\xbc\x5d\xde\x78\x86\xe3\xd5\x7f\xfe\xc5\ +\xb6\xcb\xdb\x74\x4e\x70\xf0\x7f\x71\x60\x02\x00\x44\x06\x2b\x27\ +\xe5\xb2\x5f\x53\xe0\x3a\xe0\xd7\x7e\x5c\x86\xc8\x60\x72\x51\xa5\ +\x02\x01\x19\xa8\xf4\xe1\x8b\x20\x87\xa8\x87\xa6\xbe\x06\xd0\xae\ +\x35\xb4\xe4\x89\x74\x68\xaa\xee\x63\x73\xd5\x2d\xe7\x07\xf2\x78\ +\x6c\x0e\xc0\x22\xc0\xfb\xf5\x1c\x9b\x6b\xd0\xa0\xc1\xce\xe6\x3f\ +\xb7\x37\xe9\x8b\xf9\x5d\x56\x0e\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x00\x97\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x49\x49\x44\x41\x54\x58\x85\xed\ +\xd7\x41\x0d\x00\x20\x0c\x04\xc1\x83\x20\xa9\x02\x70\x53\x3f\xd5\ +\x43\x52\x6b\x88\x38\x7e\xec\xfe\x7b\x99\x6f\x25\x32\x8a\xac\x8e\ +\xac\x76\x36\x96\x69\xd8\xe6\xbd\xa6\x3b\x00\x00\x00\x00\x00\x00\ +\x00\x00\x00\x00\x00\x00\x00\x00\x6e\xde\x67\x34\x74\x1e\x39\x3e\ +\xee\x02\x8e\xc2\x05\x10\x61\x1a\xbe\x91\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x03\xde\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x90\x49\x44\x41\x54\x78\x9c\xed\ +\x98\xcf\x6f\x54\x55\x1c\xc5\xcf\xb9\xf3\xd2\xd4\x04\x31\x4a\xdd\ +\x89\x2e\x81\x75\xdb\x99\x31\xc6\x64\xaa\x81\x98\x2e\xb4\xd3\x1a\ +\x16\xec\x90\x10\xfd\x03\x54\xe2\x82\x18\x62\x42\xfc\xb1\x36\x21\ +\x50\x60\x45\x4c\xa0\xf3\xa6\xb8\x60\x92\x26\x32\x24\xd8\xc8\x88\ +\xac\xd5\x35\xee\x24\x1a\xe3\xa2\x55\xda\x7b\x5c\xcc\x80\xd3\x77\ +\x6f\x3b\xbf\xde\x9b\xa9\x78\x3f\xcb\xfb\xee\xfd\x7e\xcf\xf7\xbc\ +\xef\xdc\x77\xef\x00\x81\x40\x20\x10\x08\x04\x02\x81\x40\x20\x10\ +\x08\x04\x02\x81\xff\x17\x1c\x55\xe2\x7c\x45\x65\x52\x5f\x02\x30\ +\x90\x2e\x34\x16\x72\xa7\x47\xa1\x63\x24\x06\x14\x63\x9d\x14\x74\ +\x0e\x80\x79\x2c\x44\x3c\x79\x67\x81\x8b\xc3\xd6\x62\x3a\x4f\x49\ +\x97\x62\xac\x53\x82\xce\x27\x73\x8b\xba\x90\xaf\xea\xc3\x61\xeb\ +\x19\x5e\x07\x48\x2c\x54\xed\xe7\x00\xdf\xef\x30\xf1\x8b\x46\xd9\ +\x9c\x02\xa9\x61\xc8\x1a\x8a\x01\xa5\xba\xa2\xb5\xdf\xed\x79\x80\ +\xc7\xbb\x5b\xa1\x4b\x4f\x3d\x6b\xde\xbd\x35\xc3\x8d\x6c\x95\x0d\ +\xc1\x80\xd2\x65\x8d\xaf\xed\xd5\x57\x20\xe6\x92\xcf\x24\x58\x36\ +\x15\x38\x3f\x45\x02\xd5\xf1\x3f\x78\xec\xd6\x71\xae\x67\xa9\x2f\ +\x53\x03\x0a\x37\xb4\x17\xeb\x5a\x06\x30\xe3\x49\xbd\x09\x3c\xea\ +\x72\x02\x50\xce\x13\xe2\x66\x94\xe3\xdc\xea\x5b\xfc\x33\x2b\x8d\ +\x99\x19\xf0\xea\x55\x3d\xff\x77\xa4\x1a\x80\xc9\xad\x4f\x84\x66\ +\xf1\x3e\x94\x73\x24\x11\x3f\x8c\x3d\xe4\xec\xed\xa3\xfc\x35\x0b\ +\x9d\x99\x18\x30\x79\x55\x2f\x46\x91\x56\x00\x1c\x48\x64\x13\x05\ +\xbb\xe3\xee\x46\x18\xc8\xd1\xf5\xb3\x35\x3c\x7c\x77\x8e\xf7\x53\ +\x96\x9a\xbe\x01\xc5\x58\x87\x04\xad\x00\x78\x21\xf1\x48\x20\x2c\ +\x3a\xed\xed\x04\x24\x18\xba\xda\xee\x1b\xcb\x23\xdf\xbd\xcd\x9f\ +\xd2\x53\x9b\xf2\x39\x60\xba\xa2\x69\x41\xb7\xe1\x2b\x1e\x5d\x14\ +\xdf\x9a\x49\xc0\x82\xce\xec\xfd\xd6\xe8\xdb\xfc\x92\xa6\x52\x11\ +\xdb\x22\x35\x03\xa6\xab\x7a\xdd\x50\x37\x01\xec\x6b\x1f\x17\xd4\ +\x2c\xbe\x57\x04\x0b\x38\x26\xec\xa3\x51\x3d\x1f\xeb\xb5\xbe\x85\ +\x26\x48\xc5\x80\x62\xac\x79\x23\xdd\x00\xb0\xa7\x7d\x5c\x90\x08\ +\xf6\x5e\xfc\xbf\x58\x34\x0d\x6c\x67\x0f\xa1\x5a\xbe\xa2\xf2\x00\ +\x71\x1f\x33\xb0\x01\xf9\xaa\x4e\x08\xba\x06\x60\xac\x7d\x5c\xa0\ +\x1d\xb0\xf8\x16\xb4\x72\xe3\x8c\x91\x5a\x2a\xc4\x7a\x67\xd0\xe8\ +\x03\x19\x90\x8f\xf5\x01\xa5\xc5\x64\x9c\x66\xf1\xce\x9b\xeb\x1b\ +\x42\xf2\x98\x60\x00\x5d\x2c\xc4\xea\x70\xb4\xee\x14\xbb\x1f\x24\ +\x16\x63\xfb\xa9\x48\xe7\xf2\x22\xc0\xd2\xfd\xed\xa6\x05\xe1\x79\ +\x69\x82\x3e\xfb\xbe\x6c\x3e\xea\xe7\xfe\xd0\xb3\x01\xa5\xba\xa2\ +\xf5\xdf\xec\x39\x91\x27\x5c\x21\x99\x16\xdf\xcc\x21\x90\xf4\x9a\ +\xb0\xf8\xd2\x86\x79\xef\xda\xd1\xed\x0e\x59\x7e\x7a\x32\xa0\x74\ +\x59\xe3\x6b\xcf\xe8\x0a\x80\xf9\x44\xf6\x66\xf1\xee\xa7\x2b\x13\ +\x24\x90\x80\xf1\xa8\x8f\x9f\x1b\xe7\xb1\xda\x2c\xff\xea\x36\x56\ +\xd7\x06\xbc\x72\x5d\x4f\x6f\x6c\x6a\x19\x80\xf3\x09\x6a\x5d\x6a\ +\x86\x52\x7c\x5b\x4e\x6f\x27\x10\xf8\x26\x97\x63\xb9\xdb\xfb\x43\ +\x57\x06\x4c\x7e\xad\x89\x68\x53\x35\x08\x5b\x0f\x21\x12\xc0\xde\ +\x5a\x2e\x55\x48\xc0\xda\x1c\xb8\xb5\x0c\x02\x77\x1f\x46\x9c\xbd\ +\xf7\x26\x1f\x74\x0c\xd1\x69\xc2\xf4\xb2\xf6\x1b\xab\x15\x00\x07\ +\x13\x8f\xfa\x3b\xe0\x64\x81\xff\xfe\xf0\x23\xc4\x23\x8d\x05\xfe\ +\xb2\xd3\xd2\x1d\x3f\x83\x2f\x2f\xe9\xa0\xb1\x5a\xc5\x6e\x2e\x1e\ +\xd8\xee\xd4\x78\x88\x46\xab\x53\xd7\x75\xc0\xb7\xe4\x11\xdb\x76\ +\x40\x7e\x49\x53\x34\xaa\x01\x98\x70\xd2\xed\xa6\xe2\xdb\xf1\x77\ +\xc2\x03\x90\x6f\x34\xca\xbc\xe7\x5b\xe2\xed\x80\x42\x45\x33\x34\ +\xaa\x23\x51\xbc\x76\x73\xf1\x00\xd0\xbc\x6a\x27\x3b\x61\x02\x52\ +\xbd\x58\x55\xc9\xb7\xc4\xe9\x80\x42\x45\xa7\x61\x74\xc6\xe3\xe4\ +\x70\xb7\xf9\x01\x71\xc4\x13\x82\xe5\xc7\x8d\x05\x7e\xb2\xe3\xbc\ +\x62\x6c\x37\x04\xf8\xfe\x9e\xfa\xcf\x43\x60\xf3\xce\xbc\x89\xda\ +\xc7\x3c\x27\xaa\x27\x17\x5f\x6d\xee\x1e\x40\x9e\x6d\xed\xaa\x4f\ +\x16\x82\x05\x79\x76\xd4\x32\x02\x81\x40\x20\x10\x08\x04\x02\x81\ +\x40\x20\x10\x08\x04\x02\xa3\xe6\x1f\x3c\x8f\x50\x7d\x3b\xd7\xa3\ +\xf5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\xfc\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\xae\x49\x44\x41\x54\x78\x9c\xed\ +\x9a\x3f\x6e\x13\x41\x14\x87\xbf\xd9\x10\x85\x26\x48\x14\xb9\x01\ +\x15\x25\x29\x69\x90\x88\x2d\xa5\x43\xd8\xa0\x84\x24\x10\xc9\xb1\ +\xa1\x80\x1b\xd0\x72\x03\x90\x00\xc7\x05\x7f\x82\x03\xb1\x8d\x68\ +\xb3\x3e\x44\x24\x2e\xc0\x05\x22\x21\x0a\x8a\x08\xfc\x68\x90\x70\ +\xc6\xde\x18\xef\xce\xcc\xce\x6c\xfc\xca\xf5\xdb\x9f\xe6\xfb\xb4\ +\x9e\x1d\x3d\x2d\xcc\x6a\x56\xb3\x3a\xcf\xa5\xf2\x5e\x80\xed\x2a\ +\x57\x6a\xb7\x84\xe8\x19\xc8\x77\x89\xa2\x47\xfd\x83\xd7\x5f\x87\ +\x7f\xbf\x90\xd7\xc2\x5c\x54\xb9\x5a\x5f\x13\x91\x3d\x90\x08\x40\ +\x0d\x06\x2f\x81\xeb\xc3\x3d\x51\x2e\x2b\x73\x50\xff\xe0\x4f\x31\ +\x5e\xd2\xfb\x0a\x29\x20\x01\xfe\xb7\x28\x9e\xea\xbd\x85\xfb\x0b\ +\x24\xc1\xa3\x64\xbd\xdf\x69\x7d\xd1\xfb\x0b\xb5\x09\x9e\x05\x1f\ +\x77\x5a\x07\xe3\xee\x29\x8c\x80\x34\xf0\x50\x10\x01\x69\xe1\xa1\ +\x00\x02\xb2\xc0\x43\xe0\x02\xb2\xc2\x43\xc0\x02\x4c\xc0\x43\xa0\ +\x02\x4c\xc1\x43\x80\x02\x4c\xc2\x43\x60\x02\x4c\xc3\x43\x40\x02\ +\x6c\xc0\x43\x20\x02\x6c\xc1\x43\x00\x02\x6c\xc2\x83\xe7\x02\x6c\ +\xc3\x83\xc7\x02\x5c\xc0\x83\xa7\x02\x5c\xc1\x83\x87\x02\x4c\xc3\ +\x97\xaa\xb5\x3b\x88\x7a\x01\x80\xa8\x87\x71\xaf\xf9\x79\xf8\x77\ +\xaf\x26\x42\xa6\xe1\xcb\xd5\xfa\x1a\xa2\xf6\x81\x25\x60\x09\x25\ +\xaf\xf4\x1e\x6f\x04\xd8\x80\x1f\x93\x37\x52\x5e\x08\x70\x04\x3f\ +\x10\xd4\x63\xbd\x37\x77\x01\xae\xe0\x95\x52\xf7\xfb\xdd\xe6\x27\ +\xbd\x3f\xd7\x4d\xd0\x25\xfc\x61\xa7\xb9\x37\xee\x9e\xdc\x04\xf8\ +\x00\x0f\x39\x09\xf0\x05\x1e\x72\x10\xe0\x13\x3c\x38\x16\xe0\x1b\ +\x3c\x38\x14\xe0\x23\x3c\x38\x12\xe0\xec\x3d\x2f\xb2\xd5\xef\xb5\ +\x3e\x4c\x93\x65\x5d\x80\xcf\xf0\x60\x59\x80\xef\xf0\x60\x51\x40\ +\x08\xf0\x60\x49\x40\x28\xf0\x60\x41\x40\x48\xf0\x60\x58\x40\x68\ +\xf0\x60\x50\x40\x88\xf0\x60\x48\x40\xa8\xf0\x60\xe0\x1b\x21\x57\ +\xf0\xc0\x66\xbf\xd7\x6a\x4f\x9b\xb7\x52\xa9\xdf\x55\xc8\x73\xc0\ +\xfc\x4c\xd0\x25\x7c\xdc\xdd\x9d\x1a\xbe\x54\xd9\xd9\x54\x48\x1b\ +\x1b\x33\xc1\x10\xe0\x81\x37\x4c\x60\x4c\x25\xc0\x77\xf8\x72\xb5\ +\xbe\xc1\x28\xbc\x99\x99\x60\x08\xf0\x22\xf2\x56\xcf\x33\x32\x13\ +\x0c\x19\x3e\xf3\x4c\xd0\x77\xf8\x95\xdb\xb5\x7b\x4a\xa9\x77\x7a\ +\xde\xa4\x57\xe7\x7f\x09\x28\x2a\x3c\xc0\x5c\xca\xc5\xda\x98\xe4\ +\x6c\xc4\xdd\xdd\xfd\x69\xf3\xb2\xc0\xc3\x84\x27\xc0\x25\xfc\x61\ +\xa7\xe9\x1c\x1e\xce\x38\x09\xfa\x0e\x5f\xaa\xec\xac\x03\x23\xf0\ +\x4c\x79\x62\x1c\xfb\x04\x04\x02\xff\x5e\xcf\x23\xc5\x1e\x32\x22\ +\xe0\xef\xd9\xb9\x8d\x21\xf8\x84\xbc\xf4\x8f\x7d\x42\x1e\x29\x37\ +\xd0\x53\x02\x96\x1b\x8d\xf9\xcb\xc7\x83\x63\x05\x8b\x43\x97\x53\ +\xc3\x27\xe4\xa5\x86\x37\x9d\x07\xda\x49\x70\xf1\xe4\x64\x4e\xc1\ +\xc2\xd0\xa5\x4c\x9f\xa5\x8c\xc9\xcb\xb4\x58\xd3\x79\xa0\xbd\x06\ +\xbf\x1d\x1d\xfd\xba\x72\xf5\xda\x0f\xe0\xa6\xc0\xcf\x48\xd8\x8a\ +\xbb\xad\x4e\xda\x70\x3d\x0f\xd4\x83\xb8\xdb\xfc\xe8\x4b\x5e\x62\ +\xad\xae\x3e\x59\x58\x6e\x34\xe6\x7d\xcd\xbb\xb1\xbd\x7d\xd1\x64\ +\xde\xac\x66\x75\x8e\xeb\x0f\x00\x7d\xea\x19\xbf\xa0\x8f\x59\x00\ +\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x14\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xc6\x49\x44\x41\x54\x58\x85\xed\ +\x94\xb1\x6a\x14\x51\x14\x86\xbf\xff\xee\xa0\x41\xd0\x68\x13\x8b\ +\xb4\xda\xd8\xac\x20\xee\x6e\xd4\xd4\x22\x06\x45\xb1\x11\x05\x4b\ +\x0b\x51\x1f\x41\xf3\x08\x06\x1f\x40\x50\x10\x42\x76\xb3\x91\x88\ +\x98\x2e\xe0\x82\x08\x01\xf5\x05\xb4\x12\xc4\xc6\x4a\x58\xb3\x73\ +\x7f\x8b\x99\x84\x24\xbb\xd1\xec\xb0\x6a\x33\x5f\x75\x87\x7b\xee\ +\xf9\xff\x73\xce\xbd\x03\x25\x25\x25\x25\xff\x19\x15\x3d\x38\x35\ +\xef\xc9\x98\xf8\x25\x50\x4d\x2a\x9a\xec\x5c\xd6\x97\x22\x79\x42\ +\x91\x43\xf5\x05\x1f\x8f\x89\xdf\x00\x55\x80\x5e\xea\xce\xd4\x92\ +\x8f\x15\xc9\x35\x74\x07\x4e\x2f\xfa\x64\xb0\x5f\x03\x13\xd8\x79\ +\x16\x01\x7c\x35\x3a\xff\xee\xaa\x3e\x0c\x93\x6f\xa8\x0e\xd4\xda\ +\x9e\x0e\xf6\x2a\x30\x81\x30\x41\x29\x41\x29\x60\xe0\xa8\xf0\x6a\ +\xad\xed\xe9\xbf\x62\xa0\xd6\xf2\x8c\xa2\x57\x80\x43\x16\xc6\x44\ +\x9c\x4b\x43\x74\xb6\x1a\x57\xf4\x4a\xad\xe9\x8b\x23\x35\x50\x5f\ +\xf4\x4d\xe1\x36\x30\x06\xb6\x4c\xdc\x19\x23\x88\x64\x33\x19\x93\ +\xbc\xd4\x68\xf9\xc6\x48\x0c\x34\x5a\xbe\x87\xfd\x14\xa8\x18\x1b\ +\xd4\x27\xbe\xc5\x46\xcc\x62\xa8\x18\x3f\x6b\x34\x7d\xb7\xb8\x01\ +\x5b\xf5\x56\x3a\x6b\xfc\x28\xff\x8c\xfa\xad\x78\x6e\x01\x45\xe7\ +\x71\x96\xe7\x1a\xcd\xf4\x21\xf6\xae\x97\x7d\xf0\xc6\x03\x87\x7a\ +\x35\xce\x81\xee\x00\x18\xa2\x36\xa6\xbd\x47\x9c\xbd\x8d\x00\x20\ +\xfb\xf1\xdb\x8f\xe1\x3e\xb3\xfd\x05\xf4\x19\x38\x31\xef\x7d\x07\ +\x93\xf8\x04\x74\xdd\x59\xa6\x28\x0d\x27\xbe\x69\xc2\x08\x11\x32\ +\x11\x3f\xef\x7d\x0b\xb7\xd6\x6e\x6b\x7d\x57\x03\xa7\x5e\xf8\x40\ +\xd2\xf3\x02\x70\x21\x1b\xb7\x22\x43\x56\x3e\x00\x81\x43\x2e\xf5\ +\xaa\x97\xe8\xda\xda\x25\xfd\xe8\x33\x70\x6e\xd9\x47\x7e\x76\xbd\ +\x2c\x71\xc6\x80\x4c\xa4\x60\xe5\x3b\xd9\xde\x09\x3a\x5d\x69\xe6\ +\xfd\x15\x7d\x07\x48\x36\x82\xd6\xbb\xfe\x24\x31\xbe\xe9\x4a\xc5\ +\x7e\xd3\x83\xd0\xf6\x41\x9f\xdd\x6f\x7f\x06\x0e\xc3\x96\x57\xe0\ +\xd1\x14\xbb\x27\xec\x7f\xa7\x55\x52\x52\x52\xf2\x47\x7e\x01\x51\ +\xe3\xba\x72\x94\x2f\x72\xc5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ +\x42\x60\x82\ +\x00\x00\x00\xd1\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x83\x49\x44\x41\x54\x78\x9c\xed\ +\xd7\xb1\x0d\xc2\x40\x10\x04\xc0\x7d\x8a\x40\x34\x42\x23\xb4\x40\ +\x80\x1c\xd1\x0b\x89\x45\x23\x54\xe1\x42\x2c\x9a\x78\x52\x64\x7d\ +\x6a\x8c\xfc\x33\xe1\xea\x82\xbd\xcb\x2e\x01\x00\x00\x00\x00\xa0\ +\x1f\x65\x19\x9c\x6f\x8f\x4b\x92\xb1\x26\xc7\x0d\xfa\xac\x69\x4e\ +\xea\x75\x7a\xde\x5f\xdf\xe1\xa1\x31\xb8\xc7\xe5\x93\xe4\x94\x94\ +\x71\x19\xb6\x0e\xd0\x95\xd6\x01\x86\x92\xbc\x7f\xde\x64\x7d\x73\ +\x52\x87\xad\x4b\x00\x00\xff\xc3\x2f\xd0\x18\xdc\xe3\xf2\x89\x5f\ +\xa0\xcd\x2f\x00\x00\x00\x00\x00\x00\x40\x27\x3e\xec\xfd\x1c\x0f\ +\x3a\x57\x98\xc9\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\ +\x00\x00\x01\x34\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xe6\x49\x44\x41\x54\x78\x9c\xed\ +\xd2\xb1\x09\xc2\x40\x00\x46\xe1\x5f\x87\xc8\x26\x2e\xe2\x0a\x29\ +\xc4\xc6\x61\x6c\x82\x4b\xb8\x88\x5b\xa4\x72\x8b\xb3\x30\x60\x21\ +\x36\xde\x5d\x9e\xe0\xfb\x20\x90\xc0\xa1\x7f\x1e\x49\x24\xfd\xb3\ +\x4d\xef\x3f\xd8\x1d\xce\xfb\x24\xd3\xf2\x78\xbc\x5d\x4e\xd7\x96\ +\xe7\x6b\x6d\x7b\xfe\xf8\x62\x2a\xc9\x50\x92\x21\xaf\x17\x6b\x79\ +\xbe\x4a\xf7\x00\xcb\x8b\xbc\xdd\xb7\x3a\x5f\x6b\x8d\x2f\xe0\xa7\ +\x19\x80\x1e\x40\x33\x00\x3d\x80\x66\x00\x7a\x00\xcd\x00\xf4\x00\ +\x9a\x01\xe8\x01\x34\x03\xd0\x03\x68\x06\xa0\x07\xd0\x0c\x40\x0f\ +\xa0\x19\x80\x1e\x40\x33\x00\x3d\x80\x66\x00\x7a\x00\xcd\x00\xf4\ +\x00\x9a\x01\xe8\x01\x34\x03\xd0\x03\x68\x06\xa0\x07\xd0\x0c\x40\ +\x0f\xa0\x19\x80\x1e\x40\x33\x00\x3d\x80\x66\x00\x7a\x00\xcd\x00\ +\xf4\x00\x9a\x01\xe8\x01\x34\x03\xd0\x03\x68\x06\xa0\x07\xd0\x0c\ +\x40\x0f\xa0\x19\x80\x1e\x40\x5b\x23\xc0\xfd\xc3\x7d\xab\xf3\x55\ +\x56\x08\x50\xc6\x24\xf3\xf3\x2a\x63\xfb\xf3\x92\xf4\xbd\x07\x47\ +\xdd\x22\x24\x17\x57\x09\xda\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ +\x42\x60\x82\ +\x00\x00\x04\x2e\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\xe0\x49\x44\x41\x54\x78\x9c\xed\ +\x98\x4d\x68\x5c\x55\x14\xc7\x7f\xe7\xbd\x32\xa9\x9a\xb8\xb1\x94\ +\xb4\x52\xc4\x8d\xd6\x8d\x60\x32\x16\xba\x28\x34\x7e\x84\x88\x52\ +\x94\x4a\x51\x57\xcd\xa2\xe9\xa4\x69\x26\x11\xea\x27\x04\x09\x56\ +\xb0\x5d\xa8\xcd\xd4\x7c\x8c\x94\x44\x84\x82\x9b\x62\x5d\x18\x69\ +\xa9\x4c\x16\xae\xe6\x4d\x0a\x6e\xfc\xc0\x45\x69\x35\x0b\x9b\x48\ +\x21\x81\xa6\x53\xe7\x1d\x17\xc9\x68\xe6\xbd\x97\x4e\x66\xe6\xbd\ +\x49\x4a\xef\x6f\x79\xcf\xbb\xe7\xfe\xcf\xb9\xef\xde\x7b\xee\x05\ +\x83\xc1\x60\x30\x18\x0c\x06\x83\xc1\x60\x30\x18\x0c\x06\xc3\xbd\ +\x85\x78\x1b\xe2\x5d\xa9\x0f\x04\x1d\x50\xc1\x56\x70\x05\x74\x3d\ +\x84\x85\x85\x82\x08\x58\xa2\x14\x14\xf9\xd0\x49\xf7\x0e\xae\xb4\ +\x6f\xf2\xf5\x10\x1d\x50\xb0\x01\x04\xac\x3a\xe9\x8c\x8c\xe2\x0c\ +\xab\x60\x83\x0e\x00\x25\x09\xb8\xeb\x03\xac\x15\x7f\x02\x54\x8f\ +\x2b\x72\x57\xff\xf6\x41\x28\xa2\xa8\x1e\xf7\xb6\xfb\xf6\x00\x80\ +\xd6\xae\x53\x6d\x22\x72\x1e\x68\xf2\x7c\xae\xa0\x6e\x24\x0a\xc3\ +\xc3\xc2\x1f\xd7\x3c\x22\xfb\x9c\xd1\xde\x8c\xf7\xe3\xc0\x04\x00\ +\xb4\x74\x9f\x6a\xb5\x5c\xf9\x1e\xd8\x52\x62\x50\x14\x61\x43\x26\ +\x41\xc1\x12\x7f\x4c\xb3\xae\xa5\x1d\xd3\x23\x7d\xb9\xa0\x3e\xab\ +\x26\x00\x20\xde\xfd\xd9\xe3\xb8\xd6\x45\x60\x87\xa7\x9b\x02\xee\ +\xc6\x39\x20\x64\x39\x78\xf5\xc6\x73\x15\xcb\x6d\x77\x46\xfa\x7f\ +\x5d\xbd\x67\x19\x9e\x3e\xf2\xf9\x0e\x2d\x14\x2e\x00\x3b\x3d\x5d\ +\x37\x48\x12\x04\xc0\xc2\x1f\xfc\x2f\x62\xdb\xed\xd9\xe1\x9e\x6b\ +\x77\xea\x5d\xf6\x14\xc8\x0e\xf7\x5c\x53\xcd\xef\x01\x9c\x52\x8b\ +\x8a\xa2\x76\xf9\x14\x46\x87\x00\x8a\xda\xbe\xe0\x85\xac\x6a\x7e\ +\x4f\xb9\xe0\x61\x8d\xc7\x60\x2e\x7d\x6c\xb6\xe1\xf6\xcd\x67\x04\ +\x7e\xf0\x09\x50\xec\xf5\xc8\x81\x82\xb8\x04\x8e\x7d\xa9\x21\x7f\ +\xf3\xd9\x5c\xfa\xd8\xec\x5a\xfc\x54\xa4\x7d\xef\xc1\xf1\xcd\xf3\ +\x0d\x0b\x67\x05\x7d\xc5\x2f\x48\x5d\xa9\xd3\xf1\xa9\xa8\x08\x12\ +\x34\x79\xe7\x6e\xc4\x78\xe3\xf7\x54\xf2\xd6\x5a\x7d\x55\x54\x08\ +\x65\x26\x3a\x17\x9b\x9a\x67\x0f\x80\x9e\xf1\xda\x04\xb1\xb4\xc2\ +\x84\x56\xc3\x52\x69\x1b\x14\xbc\x9e\x79\xf4\xef\xe6\x03\x95\x04\ +\x0f\x55\x0b\x56\x89\x1f\x4e\x9d\x00\xde\x0a\x10\x18\xd9\xfd\xa1\ +\x58\xd7\xfb\x0d\x7a\xd2\x49\x27\xdf\xa5\x8a\x3f\xb0\xa6\x19\x8b\ +\x27\x52\x6f\xa3\x7a\x22\xc0\xab\x8b\x86\x9d\x04\x15\x82\x66\x5e\ +\xe4\x1d\x67\xb4\xf7\x64\xb5\x5e\xed\x5a\x24\xcd\x38\x93\x3f\x6e\ +\x6b\xed\xf8\x53\x44\x5e\xa2\x34\x99\xa2\x84\xb8\x1e\x84\xa0\xe0\ +\x5d\x90\x43\xce\x58\xef\xe9\xda\x5c\x87\x40\x3c\x91\xda\x8f\xea\ +\x59\x20\xe6\x31\x2d\xd7\x0a\x35\x11\x54\xda\xe6\x05\x5e\xcf\x8e\ +\x25\xcf\xd5\xe8\x3b\xbc\x49\x8a\x1f\x1a\x7a\x0e\x8b\x6f\x80\x07\ +\x56\xb6\xeb\xd2\x96\x5d\x65\x12\x24\xa8\xc0\x59\x10\xf4\xe5\xec\ +\x58\xdf\xa5\xea\x7c\x7a\x46\x08\xc3\x49\x91\x78\x62\x68\x17\xca\ +\x77\xc0\x43\x9e\x61\xaa\xb8\x44\x05\x06\x3f\x27\xae\xfb\x42\xf6\ +\x8b\xfe\x6c\x2d\x3a\x4b\x46\x09\xcb\x51\x91\x96\x23\x9f\x3e\x21\ +\x85\x4d\x17\x05\x7d\xd8\x63\xaa\x60\x39\x04\x06\xff\x87\x6b\x17\ +\xda\xa7\x87\xdf\xfc\x39\x04\x99\xff\x8f\x14\xa6\xb3\x22\x4f\xf5\ +\x9c\x7e\xc4\xfe\xc7\xbd\x00\x3c\x56\x62\x50\x51\xe4\x4e\x7f\x82\ +\x00\x1a\xb4\xe6\x7f\x53\x75\x9f\xcf\xa5\xfb\xaf\x86\x2c\x35\xba\ +\xc2\xe5\xc9\xc4\xc8\xd6\x98\xde\x9e\x04\x5a\x4a\x2d\x0a\x48\x21\ +\x50\x89\xaa\x1d\x20\x69\xba\x90\xa7\xe3\xf2\x78\xf2\x7a\x14\x3a\ +\x23\x7b\x12\xfb\x69\xb4\xfb\x2f\x3b\x46\x1b\xc2\x54\xa9\x45\x00\ +\x4a\x2e\x51\xc5\x3b\x45\x40\xf0\x19\x3b\x46\x5b\x54\xc1\xff\xa7\ +\x26\x4a\xf6\x1e\x1c\xdf\xbc\x10\x9b\xff\x1a\x61\x9f\xd7\xa6\xcb\ +\x7b\xc2\x2a\x8f\xaf\xe7\x1b\x6f\x35\xbd\x96\x99\xe8\x5c\x8c\x52\ +\x5f\xe4\x8f\xa2\x99\x89\xce\xc5\xc6\x6d\x73\xfb\x45\xe4\x4b\xaf\ +\x4d\x96\x5e\x70\x7c\x1a\x14\x26\x1a\x9b\xe7\x5e\x8d\x3a\x78\xa8\ +\xb1\x12\x5c\x2b\x57\xa6\xa6\xdc\x99\x17\x77\x7d\xbb\x7d\xfe\xbe\ +\x07\x11\xd9\x5d\xe6\xf3\x4f\x72\xcd\x73\x47\xaf\x0c\x0e\xfa\xf7\ +\x89\x08\xa8\xf3\x55\x5e\x25\xde\x95\x7a\x0f\xe1\xa3\x60\x31\xfa\ +\x7e\x76\x2c\xf9\x71\x35\x97\x9a\x6a\x59\x97\xf7\x9c\x78\x62\xe8\ +\x30\xca\xe8\x8a\x26\x45\x35\xe1\xa4\xfb\xd2\xf5\xd6\x52\x97\x25\ +\xe0\x65\xc6\x99\xcc\x6d\x6f\xed\xb8\x1f\x91\x9d\x02\x0b\x40\xa7\ +\x93\xee\xfb\x6a\x3d\xb4\x18\x0c\x06\x83\xc1\x60\x30\x18\x0c\x06\ +\x83\xc1\x60\x30\x18\xee\x35\xfe\x05\x2f\xee\x41\x9b\x3f\x6f\x48\ +\xfe\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x22\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xd4\x49\x44\x41\x54\x58\x85\xed\ +\x94\xb1\x6b\x13\x51\x1c\xc7\x3f\xdf\x17\x84\xa0\x20\x71\xd0\xc1\ +\x49\x89\x08\x4a\x06\x25\xb8\x3a\x79\xb5\x48\xe9\x50\x0d\x8e\x82\ +\x6d\x66\xff\x02\x41\xdd\xfc\x0b\x1c\x92\xb8\x56\xbc\x06\xa1\x75\ +\xf0\x7a\x43\x07\x07\x75\x11\xed\x10\x17\x2d\x2e\x0a\x2e\xb5\x64\ +\xb1\xa1\xe6\x7e\x0e\x97\x33\xa7\x6d\x63\x92\x16\xbb\xdc\x17\x0e\ +\xde\xdd\xfb\xbe\xef\xf7\xfb\x7e\xef\xf7\x0e\x32\x64\xc8\x90\xe1\ +\x80\xa1\x64\xe0\x5d\x9f\xfb\x0e\x14\xfe\x93\xef\x46\xd8\xac\x1f\ +\x03\x70\xfd\x28\x72\xbb\xd2\xf7\x1b\x29\xaf\xfe\x40\xd1\x69\xe0\ +\x75\x8a\x16\x01\xdd\xfd\x78\x84\xa2\xdf\xde\xc6\xab\x9e\xd7\x9f\ +\x01\x02\xbf\xb1\xae\xc3\x9d\x2b\x40\x00\x80\xe1\x48\x1d\xd1\x1e\ +\x76\xab\x08\x73\xf1\x90\x17\x1c\xe9\x78\x81\xdf\x58\x4f\xa6\x73\ +\x69\xee\xa7\xd5\xd5\xad\x72\xa9\xf8\xf4\x87\xe5\xcf\x4a\x94\x30\ +\xb4\xb7\x08\x12\x98\x13\x80\xd9\x93\x82\x6b\xdf\x5c\x9a\x9f\xdf\ +\x4c\x33\x72\x7f\x2f\x69\xb5\x5a\xdd\x72\xa9\xf8\xac\x63\xf9\xe3\ +\x88\x4b\x8c\x5b\x05\xc5\xe6\xc4\x02\x8f\x0a\xb9\x76\xd5\xf7\xfd\ +\x9f\xdb\x68\x83\x24\xbc\x99\xb9\xfb\x88\xbb\xbd\xd7\x08\xcc\x86\ +\x75\x4f\xcc\x41\x0f\xc2\x66\xed\x1e\xb0\xe3\xda\x6d\x15\x48\x63\ +\xed\xc3\xdb\x95\xe2\xf9\xf2\x06\x30\xd9\x0b\xab\xdd\x84\x12\x98\ +\xe1\x24\x92\x9d\xdf\x09\x9b\xf5\x87\x83\xf8\x03\x03\xf4\x42\xbc\ +\x29\x9e\xbb\xb8\x86\x34\x0d\xb8\x5e\x5f\xec\x18\xc2\xcc\x9c\x24\ +\x11\x77\xff\xad\xb0\x59\xaf\xfd\x4b\x7f\xe8\xf3\x9d\xb8\x51\x9d\ +\x32\x33\x1f\xc8\x13\x57\x21\x4a\xcf\xa7\xcc\x37\x25\x55\x96\x17\ +\x6a\xcf\x87\xd1\x1d\xa9\xc1\x26\x66\x66\x2f\x9b\xdc\x12\xd8\x51\ +\x33\x33\x29\xbe\xdf\x7d\x73\xb5\x9d\x6c\x2a\x58\xa8\xbf\x1c\x56\ +\x73\xe4\x0e\xf7\x2a\xd5\x0b\x44\x16\x00\x27\x0c\x4c\x89\x86\xf8\ +\x86\x34\x19\xfa\xb5\x77\xa3\xe8\x8d\x75\xc5\xae\x56\x66\xcf\x44\ +\x11\x21\xe8\x54\xfc\xc5\x3e\x3b\x87\x17\xf8\x8d\x8f\xa3\x6a\x8d\ +\xfd\x9b\xf1\xa6\x6f\x9f\xe4\x90\xfb\x02\x7a\xcf\x56\xf7\x5a\xb8\ +\xf8\xf8\xeb\xb8\x5a\x19\x32\x64\xc8\x70\xa0\xf8\x05\xa4\xf1\xa4\ +\x8e\x44\xc6\x51\x5e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ +\x82\ +\x00\x00\x00\x8a\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3c\x49\x44\x41\x54\x58\x85\xed\ +\xcd\x21\x15\x00\x21\x00\xc0\xd0\x41\x26\x02\x60\xc8\x82\xbb\x30\ +\xa7\x08\xc3\x7b\x14\x20\x14\x0a\x8b\xc4\xb0\xaf\xe6\x06\x92\x24\ +\xbd\x2e\xec\x48\xf5\x1f\x40\xbe\x74\xed\xb3\x7d\x05\x20\x5e\x19\ +\x4a\x92\x24\x1d\x2c\x16\x1c\x05\x04\xcb\x08\x93\xc5\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x93\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x45\x49\x44\x41\x54\x58\x85\xed\ +\xd7\xb1\x4e\xc2\x50\x14\xc6\xf1\xff\x29\xa1\x8c\x96\x05\x9f\xa1\ +\x0b\x03\x09\xf8\x02\x26\xf0\x0e\xac\x26\x94\xc1\x18\x9c\xd5\x41\ +\x76\x10\x19\xe8\x0b\xf0\x0c\xc6\xc4\x27\xa8\x89\x03\x4b\xdf\x81\ +\x05\x1c\x29\x81\xe3\x00\x35\x58\xc0\x41\xdb\x38\x78\xbf\xf1\xb4\ +\xc9\xf7\x4b\x6f\x87\x7b\xe0\xbf\x47\x92\x83\x8a\x37\xac\x5b\xaa\ +\xd7\x40\x0d\x70\x52\xea\x99\x03\xc1\x5a\xa4\xf7\xe6\x5f\x3e\x1f\ +\x05\x54\x5b\x8f\x5d\x85\x1b\x60\x01\x12\x22\xfa\x9e\x4a\xbd\xca\ +\x09\xa8\x0b\x14\x44\xb4\xfb\xea\x5f\xdd\xed\x01\xaa\xad\x41\x43\ +\x91\x27\x84\x97\x88\x7c\x73\xe2\xb7\xa7\xa9\x94\x6f\x53\xf6\x46\ +\x25\x9b\xe5\x18\xe5\x7c\x2d\xd2\x88\xbf\x84\xf5\x89\x44\x3a\xc0\ +\x22\x8b\x72\x80\x89\xdf\x9e\x46\xe4\x9b\x40\x94\x53\xed\xc4\x73\ +\x6b\xe7\x9d\x1a\x48\x98\x45\xf9\x2e\x42\x21\xd4\xcd\xff\xb5\x07\ +\x70\x52\x3b\xf3\x6f\x22\xc2\x1c\x28\x1e\x02\xfc\x49\x0c\xc0\x00\ +\x0c\xc0\x00\x0c\xc0\x00\x0c\xc0\x00\x76\x01\xf3\xcd\xed\x35\xdb\ +\xa8\xe2\x00\xb3\x43\x80\x00\xd4\x2d\x7b\xa3\x52\x56\xe5\x65\x6f\ +\x54\x12\x70\x05\x82\x3d\xc0\x5a\xa4\x07\x14\x6c\x96\xe3\x2c\x10\ +\x67\x17\x0f\xa7\x36\xcb\x31\x60\xaf\x44\xfa\xf1\xfc\xeb\x62\xe2\ +\x0d\xee\x55\xe5\x16\x88\x14\xc2\xed\x05\xf2\xd7\x51\xc5\x11\x70\ +\x01\xfb\xe8\x62\x12\xa7\xe2\x0d\xeb\x39\xd5\xce\xf6\xea\x5c\x4c\ +\x3e\xff\x61\x66\x02\xc1\x4a\xa4\x9f\x5c\xcd\x4c\x3e\x00\xa7\x7c\ +\x6e\x32\xdb\xbd\x64\x45\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ +\x60\x82\ +\x00\x00\x00\xa1\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x53\x49\x44\x41\x54\x58\x85\x63\ +\x60\xa0\x00\x98\x64\x4c\x6c\x30\xc9\x98\xd8\x40\x89\x19\x4c\x94\ +\x68\xa6\x06\x18\x75\xc0\xa8\x03\x46\x1d\x30\xea\x80\x51\x07\x8c\ +\x3a\x60\xc0\x1d\xc0\x42\x05\x33\x1c\x28\xa9\x92\x87\x45\x08\x1c\ +\x38\x33\x23\xbf\x81\x5c\xcd\x03\x1e\x02\xa3\x0e\x18\x75\xc0\xa8\ +\x03\x46\x1d\x30\xea\x80\x51\x07\x0c\xb8\x03\x00\xb9\x93\x08\x9d\ +\x47\x2d\xcd\xca\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\ +\x00\x00\x03\x9c\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x4e\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\xcd\x6b\x13\x41\x18\xc6\x9f\x77\xd3\xa8\x85\x52\x0f\x22\x22\ +\xf6\x60\x6d\x3c\xa8\x05\xd1\x93\xde\x8a\x36\x89\x15\x14\x9b\x18\ +\x94\x16\x11\xd2\x54\xfb\xf1\x07\x14\xff\x02\xeb\x51\x69\xfd\x22\ +\xed\xa5\xd4\x83\x31\x55\x11\x5a\x4d\x2a\xb4\xe0\xc1\x8b\x1f\x87\ +\x22\x3d\x58\x11\xcc\xa5\x8a\x87\x96\x8a\xa9\x49\x66\x3c\x18\x04\ +\xb3\x9b\x4d\xb3\xbb\x93\x31\xcd\xfc\x8e\xb3\xc3\xf3\x3e\xfb\x64\ +\x32\x33\xec\xce\x02\x0a\x85\xa2\x96\x21\xbb\x02\x6d\xa1\x81\x06\ +\x37\xcf\x0c\x82\xf1\x10\x08\xad\x00\xb6\x3a\xe0\xcb\x0e\xeb\xe0\ +\x58\x80\x46\xb1\x0c\xb9\x47\xe7\x62\xb7\xd7\xcc\x3a\xdb\x0a\xc0\ +\xd7\x19\xf1\x72\x0d\xe3\x00\x9a\xec\xe8\x08\x24\x45\x0c\xe1\xc4\ +\xe3\x68\xb2\x58\x07\x97\x55\x65\x5f\xb0\x27\xcc\x89\x1e\x02\xd8\ +\x6e\x55\xa3\x02\x34\x82\xd0\xb5\xef\xd0\xd1\x2f\x9f\x3e\xbc\x7d\ +\x6f\xd4\xc1\xd2\x08\xf0\x9e\x0f\xfb\xc0\xb5\x19\x00\x9a\x2d\x7b\ +\x95\x23\x47\x0c\x1d\x46\x23\xa1\xec\x00\xda\x42\x03\x0d\x6e\xf6\ +\x6b\x11\xc0\x1e\x47\xac\x55\x8e\x54\x46\xdb\x72\xa0\x70\x4e\x28\ +\xfb\x17\x74\xf3\xcc\x20\xaa\xef\xe6\x01\xa0\x29\xef\xfd\x1f\xca\ +\x1f\xc2\x8c\x87\x1c\xb1\x23\x03\x03\xef\xe5\x07\xf0\x67\xa9\xab\ +\x4e\x0c\xbc\xd7\x59\x90\x31\x5d\xe7\x93\xf1\xa8\xed\xbd\x85\x1d\ +\xbc\xc1\x08\x37\xb9\xac\xf3\x5e\x2d\xb3\xb8\x30\x54\x00\xb2\x0d\ +\xc8\x46\x05\x20\xdb\x80\x6c\x54\x00\xb2\x0d\xc8\xa6\xe6\x03\x28\ +\xb9\x11\xf2\x07\xae\xec\x66\x60\xfd\x20\x9c\x24\x60\x97\xd9\x2e\ +\x03\x00\x7c\xc1\xc8\x47\xab\x66\x38\xc0\x01\xa4\x08\x98\x76\x6d\ +\xfb\x79\x6f\x66\x72\x72\xd5\xaa\xd6\x46\x31\x0d\xc0\x1b\xe8\x3d\ +\xcb\x88\x8d\x03\xd8\x91\x37\x58\x12\x0e\xb4\xd8\xf4\xe4\xe1\x40\ +\x5b\x36\x5d\xdf\xdf\x1e\x88\x74\xcd\x4e\x45\x5f\xdb\xd4\x33\xa5\ +\xe8\x5f\xc0\x1b\xe8\x19\x06\xf1\xa7\xc8\xdf\xbc\x04\x9a\x89\xf0\ +\xca\x1b\xec\xed\x13\x59\xc4\x30\x00\x5f\x20\x72\x01\x44\x43\x22\ +\x0b\x6f\x10\x17\xc0\x47\xda\x03\x91\x63\xa2\x0a\xe8\x02\x38\x75\ +\xae\x6f\x2f\x27\xba\x2f\xaa\xa0\x05\x5c\x44\x78\xd0\xd1\xdd\xdd\ +\x28\x42\x5c\x17\x40\xd6\x95\xbd\x06\x70\x21\xc5\x6c\xd0\x9c\x4b\ +\xd7\x5f\x15\x21\xac\x0b\x80\x80\xd3\x22\x0a\xd9\x85\x0b\xf2\x65\ +\x34\x07\xfc\xaf\x8f\xb8\x85\xf8\x2a\xfb\x81\x88\xa6\xf1\xfd\x22\ +\x8c\x64\xb3\xf0\x68\x1a\xcd\x14\xbb\x4e\x0e\xbc\xc4\x31\xa2\xec\ +\x00\x5e\xc4\xc6\x2c\x6f\x74\xcc\xf0\x87\x7a\xc0\x98\x08\x65\x73\ +\x6a\x7e\x2b\xac\x02\x90\x6d\x40\x36\x2a\x00\xd9\x06\x64\xa3\x02\ +\x90\x6d\x40\x36\x2a\x00\xd9\x06\x64\xa3\x02\x90\x6d\x40\x36\x2a\ +\x00\xd9\x06\x64\x63\xe5\x7c\x80\x14\x38\xd0\x52\xe2\xdd\xff\x46\ +\x58\x2f\x6c\xa8\xad\x11\xc0\xb1\x50\xd8\x54\x5b\x01\x68\x14\xd3\ +\x35\xc9\xf0\x21\x89\x54\x86\xdc\xa3\x85\x8d\x55\x33\x07\xd8\x24\ +\x47\x0c\xe1\xb9\xb8\xfe\xdc\x70\x2d\x04\x90\xe3\x84\xde\x64\x91\ +\xf3\xc2\x9b\x3d\x80\x14\x31\x84\x8b\xdd\x3c\xb0\x39\x03\xf8\x7b\ +\x5c\x9e\xea\xd3\x23\x89\x89\x89\x1f\x66\x9d\x75\x8f\x9a\x1d\x58\ +\x6b\x85\x40\xc0\x52\x22\x1e\xf5\x38\xad\x6b\xb4\x0a\x7c\x73\xba\ +\x88\x13\x70\x60\x59\x84\xae\x51\x00\xb3\x22\x0a\xd9\x86\xe3\xa5\ +\x08\x59\x5d\x00\x1a\x63\x37\x00\x64\x44\x14\xb3\xc1\x77\x0d\xda\ +\x1d\x11\xc2\xba\x2f\x46\x96\x16\xdf\x2d\x7b\x0e\x1e\x59\x03\xc8\ +\x2f\xa2\xa0\x15\x08\xfc\x62\x62\x2a\xfa\x46\x84\xb6\xe1\x4e\xf0\ +\x78\x6b\xd3\x4d\x10\x1e\x89\x28\x58\x2e\x04\x0c\x27\xe2\x63\xcf\ +\x44\xe9\x1b\x7e\x33\x34\x3f\x3f\xcf\x2f\x85\xce\xc4\x53\x5f\x57\ +\x57\x00\x3a\x51\xac\x9f\x60\x56\x38\xe8\x72\x32\x1e\xbd\x25\xb2\ +\x48\xc9\x37\xae\xfe\xce\xf0\x61\xa6\x69\x43\x00\xda\x01\xec\x14\ +\x69\x26\x4f\x8a\x03\xd3\x75\xb9\xba\xeb\xcf\x9f\xdc\xfd\x5c\x81\ +\x7a\x0a\x85\xa2\x86\xf9\x0d\x29\x0e\xd0\xf4\xc6\x6c\xeb\x8f\x00\ +\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x9f\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x51\x49\x44\x41\x54\x58\x85\xed\ +\x94\x2d\x48\x43\x51\x14\x80\xbf\xf3\x36\x10\x14\x15\x67\xd1\x66\ +\x17\x2c\xbe\x55\x8b\x98\x4d\xb3\x6a\x71\x4f\xd0\x4d\x8c\x82\xe0\ +\x5e\xb0\x98\xdc\x14\xdd\xc6\xc2\xaa\x13\x9b\x59\xb0\xcf\xbf\x64\ +\x53\x9b\x7f\xf8\x93\x06\x8a\xbb\xc7\xb4\x89\xf1\xdd\x07\xaf\xf8\ +\xbe\x76\xe0\xfc\x7c\xdc\x7b\xee\x85\x98\x98\x98\xff\x8e\x04\x4b\ +\x57\x71\xbd\x5d\x03\xf0\xfd\xd9\x1e\xba\xaa\xaf\x7d\x84\x15\x70\ +\x02\x65\x6f\x16\xba\xc2\xc9\x9e\xc4\x7b\x26\xd3\x48\x44\x2b\xe0\ +\xfb\x46\x55\xe6\x3a\xe1\x5d\xea\xf1\x3b\x5a\x01\xe0\xbc\x9a\x3b\ +\x42\x65\xab\x13\xbb\xd9\xd2\x75\xa4\x02\x00\xcd\x6a\x6e\x43\xe0\ +\x14\x00\x61\xc2\xf5\x8a\x07\xb6\x02\x01\x97\xf0\x2f\xae\x57\xd2\ +\x6e\xa0\xea\x35\xab\xab\xd5\xa0\x3d\xac\x4e\xa0\x43\x73\xe4\xf5\ +\x77\x09\x45\x2a\x69\x6f\x67\x2a\x52\x01\x7c\xdf\xb4\x12\x89\xfe\ +\x4e\xa8\x38\x67\xd1\x0a\x00\xbc\x3c\x7f\x29\xdc\xdb\x96\x87\x14\ +\x50\xe9\x1d\x1a\xae\x09\x8c\x01\x4f\xed\xa4\x33\x16\xb4\x43\xa8\ +\x8f\xc4\x5d\x4a\x15\x40\xf2\x40\xcb\x38\x3a\x73\xb9\x9f\xbf\x09\ +\xda\xc3\xfa\x15\x4c\x66\x8b\xf3\x22\x52\x07\x8c\x11\x67\xf6\xa2\ +\xbc\x72\x62\xd3\x27\x69\x53\x94\xf6\x8a\xd3\x8a\xd4\x00\x14\x59\ +\xb6\x1d\x0e\x16\x3b\x90\x5e\xdc\x1b\x57\xe4\x18\x48\xa2\xba\x7d\ +\x5e\xc9\x95\x6d\x87\x5b\x08\xa8\x18\xc7\x34\x80\x41\xe0\xb0\x39\ +\xfa\xb6\x1e\x66\x38\x58\x5c\x81\xc0\x83\xa0\xb7\x7d\x9f\x03\x0b\ +\xf8\x79\x13\x56\x20\x26\x26\x26\xe6\x07\x9e\x35\x61\x37\x0a\x6d\ +\x65\xe5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x97\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x49\x49\x44\x41\x54\x58\x85\xed\ +\xd7\xb1\x0d\x00\x20\x0c\x03\x41\x0b\x31\x18\x83\x23\x65\x15\x94\ +\x0c\x12\x86\x30\x1d\xff\x7d\xac\x6b\x23\x91\xd1\xc9\x8a\x93\x15\ +\xce\xc6\xb4\x04\xad\x65\xdd\x4b\x1a\xee\x00\x00\x00\x00\x00\x00\ +\x00\x00\x00\x00\x00\x00\x00\x00\xb8\x79\x9f\x91\x7a\xbf\x61\xfc\ +\xdc\x05\xd1\x25\x09\xfd\x18\x55\xe2\x51\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x87\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x39\x49\x44\x41\x54\x58\x85\xed\ +\xce\x31\x11\x00\x30\x08\x04\x41\x26\x9a\x10\x85\x0c\x2c\xe0\x38\ +\x22\xa0\xdc\xeb\xff\x67\x23\x16\x65\x4d\x67\x4d\x6f\x3e\xde\x66\ +\x7c\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ +\xc0\x07\x39\x3f\x03\x99\x39\x3b\x26\x1f\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x0d\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xbf\x49\x44\x41\x54\x58\x85\xed\ +\x94\xb1\x6a\x54\x41\x14\x86\xbf\x7f\x36\x4a\x90\xe0\x6a\x13\x8b\ +\x8d\x91\x04\xad\x63\x91\x4a\x49\x2d\x62\x4a\x1b\x51\xf0\x01\x44\ +\x7d\x05\x7d\x04\x83\x0f\x20\x28\xd8\x58\x28\x28\x62\xba\x80\x79\ +\x00\x61\xfb\xdd\xd9\xd9\x15\x02\x29\xac\x6c\xc2\x9d\xdf\xe2\xee\ +\x26\x31\xbb\x01\xf7\xba\x62\x73\xbf\xe2\x32\x70\xee\x9c\xff\x9b\ +\x73\x87\x0b\x35\x35\x35\x35\xff\x19\x55\xdd\x98\x52\x6a\x15\xe6\ +\x13\x66\x2d\xc8\xad\xe5\xe5\xe5\xef\x55\xfa\x84\x8a\xe1\xd7\x8a\ +\xac\xaf\x98\x35\x80\xec\xb0\x9b\x52\xba\x5a\xa5\xd7\xd4\x13\xe8\ +\x74\xfa\xd7\x15\xfc\x05\x58\x04\x1f\x6b\xa3\xbd\x5c\x70\x6b\x75\ +\x75\xe9\xdb\x34\xfd\xa6\x9a\x40\xaf\xd7\xdb\x50\xf0\x0e\xb0\x28\ +\x30\xa8\x00\x15\xe5\xda\x97\x42\xc3\x3b\xbd\x5e\x6f\xe3\x9f\x08\ +\xc4\xd8\xdf\xcc\xd6\x36\x70\x1e\xb0\x21\x8f\x6a\xc3\xb5\x81\x66\ +\xb6\xb6\xbb\xdd\xfe\x9d\x99\x0a\xc4\x98\x1e\x18\xbf\x07\xe6\xcb\ +\xec\xa3\xf0\x63\xe4\x61\x6d\x1e\xf9\x43\xb7\x9b\xee\xcf\x44\x20\ +\xc6\xf4\xc4\xf0\x1a\x68\xb8\x1c\xfb\xa4\xf0\x21\xca\x18\x03\x0d\ +\xc4\x9b\x18\xd3\xe3\xca\x02\xb6\xd5\x89\xe9\xb9\xe1\xc5\xa8\xb9\ +\x26\x9f\xfc\x84\x03\x19\x95\x92\x86\xad\x4e\x4c\xcf\x6c\x9f\x7a\ +\xd9\x27\x16\x6c\x87\x98\xfa\x5b\x98\x47\xb6\x09\x52\xf6\xd1\x95\ +\xff\x43\x24\x3b\x07\x49\x20\x5e\x5e\xb9\xbc\xf4\x54\x1a\x9f\xde\ +\x98\x40\xbb\xdd\x3e\xbb\xb0\xd0\x7c\x85\xb8\x37\xd4\xc9\xa0\x29\ +\xc3\x0f\x8f\x22\x50\x39\x65\xf3\x76\x7f\x7f\xef\xe1\xfa\xfa\xfa\ +\xc1\xa9\x02\x83\xc1\xe0\xdc\x41\x91\xdf\x61\x6e\x97\x7b\xc8\x9a\ +\xfa\xe4\x27\x14\x40\xc2\x01\x04\xe2\xf3\x99\x46\xb8\xdb\x6a\xb5\ +\x7e\x8e\x09\xc4\x18\x2f\x9a\xf0\x11\xb8\x51\x5e\x66\x65\xf4\x77\ +\xe1\xc7\x2c\x04\x0e\x48\x80\x77\x9d\x8b\xcd\x95\x95\x95\x1f\x00\ +\x73\xa3\x77\xb2\x43\x47\xa2\x59\x6a\x09\x2a\xfe\xa6\x27\xa2\xc3\ +\x07\xa0\x9b\x0a\x73\x5d\xe0\xc2\xef\x21\x55\x3f\x73\x05\x3c\xa3\ +\xc1\xd6\xd4\xd4\xd4\xcc\x84\x5f\x30\x7d\xb9\x9b\x4b\x8f\xb2\x18\ +\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x75\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x27\x49\x44\x41\x54\x78\x9c\xed\ +\xc1\x01\x0d\x00\x00\x00\xc2\xa0\xf7\x4f\x6d\x0e\x37\xa0\x00\x00\ +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x77\x03\ +\x40\x40\x00\x01\x8f\xf2\xc9\x51\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x04\x67\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x19\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4d\x88\x1c\x45\x18\x86\xdf\xb7\x67\x27\x59\x91\x78\x31\x88\ +\x30\x3b\xdd\xd3\x3b\x89\x3f\x57\x5d\xbc\x0a\xc1\x44\x22\xf8\xc3\ +\x22\xe2\x41\x10\xfc\x41\xc1\x93\x22\x01\x3d\xa8\xa0\x01\x45\xf0\ +\xa0\xe0\x1f\x0a\x1e\x44\xd1\x53\x0c\x62\x64\x83\x10\xf0\x22\x08\ +\x82\x07\x31\x38\xcb\x6c\xd7\xf4\x74\x30\x46\x11\x45\x71\xcd\xf4\ +\xd4\xe7\x61\x26\xc6\xed\x6a\xcd\x8e\xa9\xaa\xee\xc3\x3c\xb7\x6d\ +\x96\x7a\xbf\x7a\xa6\xba\xbb\xbe\xee\x19\x60\xce\x9c\x39\x73\x2c\ +\xa0\x54\xfa\x4c\xa2\xd2\x5c\x0d\xd2\x91\x52\xd9\xd3\x55\xd7\xb3\ +\x5d\x68\x6b\xa0\x44\xa5\x63\x00\xc1\xf4\x4f\x11\x8d\x7d\x71\xdc\ +\x3e\x61\x6b\x7c\x57\x04\x17\xfe\x97\xed\x21\x22\xff\x1c\x8b\x0c\ +\x70\x54\x29\x75\xbd\xad\xf1\x5d\x61\x4d\x00\x49\x5d\x38\xb4\x4b\ +\x10\x7c\xda\xef\x67\x57\xdb\xca\x70\x81\x35\x01\x00\xa4\xe4\xd8\ +\xee\x46\x43\x1f\x5f\xcf\xb2\xb6\xc5\x1c\xab\xd8\x14\x50\x8a\x00\ +\xed\x85\x5c\xaf\x65\x59\xb6\xdb\x75\xd6\xff\xc1\xb9\x80\x29\xd7\ +\x8c\x72\x7d\xec\xe4\xc9\x33\xbb\x3c\xe5\x6d\x1b\x97\x02\x8a\xa7\ +\xc4\xca\xe2\x25\x9b\x47\x7a\xbd\xde\x4e\x87\x99\x33\xe3\x52\x80\ +\x86\x29\x61\x5f\x73\xe7\xe2\x7b\x22\xb2\xe0\x30\x77\x26\x5c\x9f\ +\x02\x1a\xe0\x56\x09\x82\x55\x95\x0e\x5f\x17\x11\x6b\x7b\x90\x8b\ +\xc1\xc3\x35\x40\x34\x8b\x2b\x41\x70\x7f\x32\x18\x3e\xef\x3e\xfb\ +\xc2\x78\xb9\x08\x0a\xa0\xa5\x70\x32\x10\x38\xa4\x54\x7a\xc8\x47\ +\xfe\x7f\xe1\xeb\x2e\x00\x12\xe3\xe2\x31\x01\x5e\x48\x92\xf4\x01\ +\x5f\x35\x94\xe1\x4d\xc0\x04\x29\xee\x16\x01\xe2\x8d\x24\x49\x57\ +\xfd\xd6\x71\x1e\xcf\x02\x28\x10\x14\x25\x04\x20\xde\x57\x2a\xbb\ +\xc9\x6f\x2d\xe7\xc2\x7d\x43\x08\x60\x48\xd8\x21\xd0\x47\xfa\x69\ +\x7a\x83\xef\x72\xfc\x0b\x98\x50\x26\xe1\xd2\x40\xe3\x93\x24\x49\ +\xae\xf5\x59\x48\x55\x02\x00\x40\x40\x43\xc2\xe5\x60\xe3\x78\xbf\ +\x7f\x2a\xf2\x55\x44\x95\x02\x00\x81\xd0\x5c\x09\xad\x20\x18\xaf\ +\xad\xaf\x7f\x7f\x85\x8f\x12\xaa\x15\x00\x40\x00\x91\xe2\x46\x89\ +\xb8\x6a\xa1\x79\xf6\x58\xaf\xd7\xbb\xcc\x75\x7e\xe5\x02\x00\x80\ +\xa5\x7d\x03\xaf\x6b\x36\x17\x8f\x6e\x6c\x6c\x2c\xba\xcc\xae\x85\ +\x80\x29\xa6\x04\xe2\x46\x04\xcd\x0f\x5c\x36\x4f\x75\x12\x00\x94\ +\x34\x4f\x84\xdc\x36\x18\xa4\x6f\x15\x9e\x39\x5a\xa3\x6e\x02\x00\ +\x88\x26\xb7\xae\x04\x01\xef\x55\x2a\x7b\xd1\x45\x07\x59\x43\x01\ +\x80\x88\xd9\x3c\x81\xf2\x98\x4a\xb3\x27\x6c\x67\xd5\x52\x00\x50\ +\xde\x3c\x41\xe4\xf0\x86\x1a\x3e\x64\x33\xa7\xb6\x02\x26\x98\xcd\ +\x13\x21\xaf\x29\x35\xbc\xd3\x56\x42\xcd\x05\x50\xc4\x6c\x9e\x28\ +\x90\x57\x6c\x25\xd4\x5c\x00\xfe\xed\xe5\x9d\xb5\xdb\x62\x6d\x1e\ +\x4e\x96\x31\x9d\xbb\xf1\x21\x09\xf0\xb6\xad\x8c\x1a\x0b\x20\x34\ +\xa4\x61\x2c\x00\xca\x23\x71\x18\xbe\x6a\x2b\xa5\xa6\xa7\x00\x21\ +\x52\x32\x79\x91\xa7\x3a\x16\x27\x0f\xd4\x55\x00\x25\x60\x61\xf6\ +\x02\xbc\x1c\x45\xed\xe7\x6c\x47\xd5\x4e\x00\x81\x00\x62\x5c\xfa\ +\xde\xed\x84\x4b\x8f\x92\x2c\x7b\x01\x7b\x51\xd4\x46\xc0\xe4\x13\ +\x67\x20\xe6\x75\xff\xe3\x1f\xcf\x9c\xbe\xaf\xe4\xf5\xbb\x15\x6a\ +\x23\x60\xd2\xec\x6c\xdd\xeb\x0b\xf0\x79\x23\xc0\x5d\x2b\x2b\x2b\ +\x23\x57\xb9\xf5\x10\x20\x12\x9c\x5b\x03\x7f\x43\x7c\xad\xf3\xb3\ +\xb7\xb6\xdb\xed\x3f\x5c\x46\x57\x7f\x1b\x24\x09\x73\xd9\xaf\xeb\ +\x7c\x74\x73\xb7\xdb\xfd\xc5\x75\x7c\xc5\x2b\x80\x84\xd9\xe7\x9f\ +\x12\x9d\xef\x5f\x5e\x5e\x3e\xed\xa3\x82\x2a\x57\x00\x01\x63\xf2\ +\x3f\x13\xfa\x40\x27\x8e\x13\x5f\x45\x54\xb2\x02\xa6\x57\xfa\x62\ +\xf6\xef\xa2\x79\x4b\x14\x45\xdf\xf8\xac\xc5\xbf\x00\x01\x69\xe6\ +\x8e\x34\x65\x35\x8e\x97\xbe\xf0\x5d\x8e\xef\x97\xa3\x04\x8d\x4c\ +\x21\x78\xcf\x72\x18\xae\xf9\xad\x65\x82\xef\x97\xa3\x46\x1e\x81\ +\x87\xa3\x68\xe9\x43\xbf\x75\x9c\xc7\x9b\x00\x11\x34\x8c\x63\xe0\ +\x93\x51\xd4\x7e\xd3\x57\x0d\x65\x78\xb9\x0b\xd0\x5c\xf6\x80\xf0\ +\xa5\x4e\xd4\xaa\xfc\x6b\x32\x1e\x56\x00\x03\x29\x34\x37\x04\xdf\ +\x89\xa2\xd6\xe3\x2e\x9a\x9b\x59\x71\x2d\xc0\xd8\xdf\x13\xf8\x28\ +\x0c\x5b\x0f\xd6\x61\xf2\x80\x5b\x01\x01\x8a\x5b\x5c\xe2\x84\xd6\ +\xf9\xdd\x24\x73\x87\xb9\x33\xe1\x52\x40\xf1\x91\xc6\x57\xa3\x3f\ +\x37\x6f\x8f\xe3\x78\xd3\x61\xe6\xcc\xf8\xd9\x0a\x0b\xbe\xcb\xf3\ +\x1d\x07\xf7\xee\x0d\x7f\xf5\x92\x37\x03\x3e\x6e\x83\xc3\xf1\x38\ +\xd8\xbf\x67\xcf\x95\x3f\x78\xc8\x9a\x19\x9b\x02\xca\x9e\xe0\xff\ +\x04\x19\x1f\xe8\x76\x5b\x03\x8b\x39\x56\x71\xf5\x93\x19\x00\xf8\ +\x2d\xa0\x1c\xec\x74\x3a\xdf\xda\xca\x70\x81\xa3\x9f\xcc\x50\x08\ +\xde\x11\x86\xe1\x97\xb6\xc6\x77\x85\x35\x01\x01\x79\x18\xe0\x18\ +\xc0\x98\xe0\xb3\x51\xb4\xf4\x99\xad\xb1\xe7\xcc\x99\x33\xc7\x15\ +\x7f\x01\x49\x16\x4b\x51\x69\x18\xd5\x52\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x97\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x49\x49\x44\x41\x54\x58\x85\xed\ +\xd7\xb1\x0d\x00\x20\x0c\x03\x41\x83\x18\x8c\x26\x13\x64\x85\x8c\ +\x89\x94\xd5\x18\xc2\x74\xfc\xf7\xb1\xae\x8d\x44\x46\x91\xd5\x91\ +\xd5\xce\xc6\x32\x0d\xdb\xbc\xd7\x74\x07\x00\x00\x00\x00\x00\x00\ +\x00\x00\x00\x00\x00\x00\x00\xc0\xcd\xfa\x8c\x86\x74\x5e\x41\xfe\ +\xed\x02\xdd\xeb\x04\xae\xa2\x49\x76\xdf\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x0c\xd6\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x0c\x88\x49\x44\x41\x54\x78\x9c\xe5\ +\x9b\x5b\x6f\x5b\xc7\x11\x80\xbf\x25\x45\x8a\x94\x28\x89\x92\xad\ +\xbb\x64\xc9\x4e\x9a\xc2\x41\xe0\x26\x45\xd1\xa0\x48\x0a\xf4\xa9\ +\x7d\xe9\x7b\x81\x16\xfd\xa3\x7d\x2a\x50\xb4\x0f\x41\x90\x36\x4e\ +\x52\x20\x69\x92\xc6\x96\x6c\xc9\x37\x5d\x48\x49\xa4\x2e\xe4\xf4\ +\x61\xf6\x1c\xee\xd9\x33\x87\xa4\xe4\xf4\xc9\x03\x10\x24\x77\xf7\ +\xcc\xce\xcc\xee\xce\x6d\xe7\x00\xb2\x05\xe2\x78\xe3\x40\x9c\xf2\ +\x9e\xfe\x78\x93\x84\x90\xe3\xf9\x4d\x12\x42\x96\x57\x97\xed\xe0\ +\x0e\xf0\x18\x9c\x14\x3c\xdc\x00\x6e\x19\x1d\x25\x60\x32\x8b\x2f\ +\x6d\xaf\x0d\xa1\x66\x12\x10\xe0\x62\xc8\x98\x73\xa0\x67\xb4\x77\ +\x81\xbe\xd1\xfe\x12\xdc\xa9\x8d\x2a\xcf\xa3\x1b\x35\x00\x64\x1b\ +\xb8\xed\x09\x3d\x01\x5e\xf8\x89\xa7\x80\x39\xdf\x2e\xc0\x59\xd0\ +\x3e\xeb\xdb\xfa\xbe\x1d\x8f\xa3\x0a\x34\x81\x8a\xef\x3f\xf7\x34\ +\x54\xfd\xf7\x25\x70\x04\x97\xa7\x50\x39\xf2\x6d\x53\xa8\x20\x9d\ +\x9f\xff\xc4\xff\x9f\xf2\x6d\x0e\x68\x01\xa7\xbe\x7d\x29\xe8\x7b\ +\x01\xee\x71\x31\x6f\x85\x52\x92\x2d\x90\x09\x90\x8f\x40\x56\x8d\ +\x31\x6b\x20\x0b\x46\xfb\x06\xc8\xbc\xff\x3d\x05\x72\x0f\xe4\xae\ +\xff\xcc\x80\xdc\x01\x19\xb2\x23\xa4\xee\xc7\x2c\xa8\xe0\xe5\xae\ +\xc7\x31\xe1\xfb\xe7\x40\x36\xf3\x47\x55\x9a\x05\xed\x1b\x20\xbf\ +\x06\x29\x5f\xf3\x88\xcb\x04\xc8\x9f\xf5\xc1\x5c\xdf\x36\x48\xc5\ +\x68\x7f\xdb\x3f\xb7\xe2\x27\x5b\x8e\xf0\xdd\x1b\x73\x72\x3c\xe3\ +\x25\xff\xdb\x79\x46\xb6\xa0\x75\x4b\xdb\xe5\x2d\x83\xd9\x32\xc8\ +\x4f\x8c\xf6\x09\x90\x3f\xda\xbc\x14\x13\xf0\x91\x7f\x30\x92\x9a\ +\xac\x17\x30\x7f\xc7\x7f\xb6\xed\x15\x96\xed\x6b\x4c\x4e\x60\xa2\ +\xe2\xf6\x59\x15\x4e\x7b\x49\xe7\xcb\xf5\x97\xb3\xcf\xa5\xbb\xb9\ +\x02\xf2\xab\x71\x27\xdf\x1e\x6c\xfb\x50\x63\xca\x14\xc8\x6d\x63\ +\xfc\x2a\xc8\x07\xba\x7d\x4d\x7c\xf3\x5e\x79\x5e\x13\x64\x56\xb7\ +\xbc\xd9\x37\x07\xf2\x00\x64\xd1\xe8\x6b\xfa\x67\x23\xcb\x26\x9b\ +\xfa\xc9\x82\x71\x26\xe4\x17\xe0\x3e\x0d\xfe\x27\xca\xa3\x07\xec\ +\x01\x21\xa3\xab\x70\x79\x0b\x2a\x5f\x0e\xe1\x64\x0d\x78\x5a\xd0\ +\x97\xda\xe1\x1b\x3c\x0b\xf0\x00\xba\x4f\xa0\xf6\x2a\x68\xeb\x28\ +\x5d\x94\xc9\x29\xbc\x98\x37\x98\x30\x90\xc6\xc4\x34\x50\xe6\x1f\ +\xa0\x5a\xbd\xed\xc7\x6c\x01\x2f\x54\xa1\x0f\x05\xf1\xc4\x2c\xf9\ +\xff\x89\xe9\x4a\x34\x78\xd8\x46\xd0\xf6\xc2\xa0\x25\x86\x17\x20\ +\x82\x32\xbc\xe7\x9f\x5d\x02\x7e\x06\x7c\x0e\xcc\xa0\x16\x22\x81\ +\x9c\xd9\x8c\x04\x20\x0d\xd4\xcc\x24\xff\x37\x80\x36\xb8\x5d\x3f\ +\x51\x05\x35\x5d\x9b\xc0\xd7\xe0\xae\xf4\x7c\xb9\x13\x72\x20\xce\ +\x8f\x9b\x42\x7d\x81\x6f\x47\x98\x9f\xf8\xd9\x45\x60\x1a\x35\xa9\ +\x7b\xf6\xb3\xd2\x86\xfa\x0b\xd4\x9f\x58\x01\x7e\x00\x16\x80\xcf\ +\x80\xe7\x80\xb7\x3c\xec\xf8\xe7\x7b\xaa\xdb\xdc\x55\xd1\xc4\x5b\ +\x03\xf3\x26\x5b\x59\xcd\x29\x1b\x5e\x0f\x7c\x1c\x29\x46\xcb\x4c\ +\x2e\xa1\xa6\x72\x46\x3f\x37\x05\x59\xf5\xca\x78\x3d\x6b\x55\xd2\ +\xfe\x99\x81\x7e\x91\x09\x90\xdf\x78\x2b\x11\xb6\x07\x8a\x51\xee\ +\xaa\x8e\x18\x40\xc9\x98\xb5\xaf\x13\xb2\x0b\xae\x17\x8d\x5d\x03\ +\xfe\x0e\xdc\x09\x84\x10\xac\xcc\x61\x53\x19\xe7\x10\xdc\x53\xdf\ +\x37\xe6\xaa\x9b\xe0\x9f\x75\x4f\x80\x03\xc5\x7d\xd8\xcc\xf7\x8b\ +\x03\xd6\x81\xbf\x01\xf7\xb2\x73\xba\x9e\xf2\x22\xeb\x18\x47\xc0\ +\x12\xc0\x14\x70\x16\x31\x0f\x7a\xe6\xbf\xf3\x5b\xe9\x31\x59\x21\ +\xa0\x1a\xb9\xd9\x57\xc6\xdd\xe5\xf8\x3c\x8e\x0b\xee\x52\x71\x37\ +\xfb\xd1\x6e\x08\x3d\xbc\x1e\xf0\x04\x3d\x7a\xe1\x90\x1e\xea\x29\ +\x4e\xc7\x58\x2d\x25\x38\xe7\x57\x2f\x00\xd9\x46\x95\x4c\x29\x30\ +\x77\x07\xc0\x7d\xe0\xd2\x9b\xab\x57\xe8\xee\x09\x4d\x9e\x9f\xd0\ +\xdc\x04\x25\xe8\xfa\xe3\x56\x3b\xc4\xf6\xf7\xa7\x81\x2e\x48\x78\ +\x66\xfb\x3a\x56\xee\x03\x47\xe8\xca\x7f\xad\x63\x05\xa0\x03\x9d\ +\x13\xa8\x2f\x92\xd1\x67\xee\x08\xe4\xa7\xf1\x04\x63\x58\x01\x79\ +\x0b\x2e\x2a\x50\x9d\x46\x15\xd3\x29\x83\xad\xbd\x0b\xfc\x0e\xf8\ +\x4b\x01\x03\x01\x74\xe6\xa1\x9e\x04\x3f\x3e\x4e\xa8\x1d\xf9\xce\ +\x79\xd4\x52\xf8\x1d\xd5\x39\x87\xfa\xe1\x10\x64\x5d\xd4\x3c\xfe\ +\x06\xf8\x24\xa0\xd9\x2b\xcf\x7a\x0d\xb8\x0d\x72\x1e\x2d\x66\x6e\ +\x25\x62\x01\xc4\xd1\xe1\x5d\x60\x1a\x26\x1f\xaa\x12\x74\xfb\xd9\ +\xe1\xb2\x0e\xfc\x03\x0d\x70\x8c\x20\x43\x80\xee\x6d\xa8\x4d\x40\ +\xfd\x25\xb8\x4e\x01\x43\x47\xd9\xbf\x52\x07\x16\xe0\xa2\x06\xd5\ +\x93\xbc\xd6\x4e\x7d\x93\xbf\x02\x6b\xe0\xf6\x82\xce\x36\xc8\x09\ +\xba\x63\xdf\xf6\x9e\x6b\x42\x5b\x9f\xe8\xd8\xc7\x3a\xa0\x0a\x9c\ +\xfb\x09\xee\xa1\xab\xf2\x85\x4d\xb3\x2c\xa1\xdb\xbe\x87\xad\x13\ +\xa6\x81\x55\xa8\xb5\x55\x89\x15\x32\x6f\x80\xeb\xe8\x33\xd5\xb6\ +\x32\x18\x1e\xab\x30\xaa\xa3\x87\xfa\x02\x2b\x05\x88\xbe\xf1\x63\ +\xee\xf9\xe7\x3a\x64\x1d\xb9\x22\x2b\xc0\x06\xf0\x0c\xf5\x01\x8c\ +\x03\x7c\xd8\x04\xba\xe0\xba\x9e\xe0\x48\x31\x1e\xcd\x43\xbb\x86\ +\xae\xc2\xf9\x58\x3c\xdb\x70\x01\x3c\x85\xf6\x24\x1c\x2f\x60\x87\ +\xb4\x5d\xe0\x4c\xe7\x8c\xc1\x9d\xa1\x8b\xfa\x83\xe7\x29\xc7\x8b\ +\x25\x80\x06\xea\x3d\x2d\xe6\xb7\x7c\x02\xcd\x29\x70\xad\x6c\x5b\ +\x22\x84\xcb\xf7\x61\xae\x07\xb3\xaf\xcc\x47\x6f\x04\xb3\xaf\x60\ +\xf6\x52\x71\x5b\x47\xcd\xb5\x60\xae\x20\x16\x61\x07\x35\xdf\x2d\ +\xd4\xc2\x65\xc0\x12\xc0\x34\xaa\x3d\x0b\x94\x9a\x2c\xa3\x6e\xaa\ +\x01\xc7\x4d\xa8\x7c\x0f\xcc\x33\x7e\xec\x3d\x06\x88\x03\x16\xa0\ +\xf2\x9d\xce\x61\xc2\x73\xdb\x59\x72\x97\x40\x19\xdc\x31\xba\xb8\ +\x19\xb0\x04\x20\xa8\x69\xd9\x29\x20\x64\xc2\xb6\xf3\x32\x05\xa5\ +\x64\x22\x7f\x1c\xac\x60\xeb\xda\x10\x6e\xfb\x16\x94\x4a\x5e\xbf\ +\xc4\xc3\xae\x94\x36\xb1\x78\x3a\xd4\x23\x34\xda\x0a\x94\x07\x83\ +\x4c\xbf\x7d\x13\xd5\xb2\xe1\x2a\xcc\x82\x74\x81\x15\x98\xd9\x0f\ +\xfa\x5a\xc0\xbb\xc0\x13\xd2\x8c\x4e\x06\x92\xd4\x19\xa8\x4f\x61\ +\xe5\x05\xe7\xd0\x40\xe7\x07\xfd\x2d\xa0\x3b\x73\x03\xe4\x19\x03\ +\x3f\x23\xc1\x7f\xa6\x7d\x1c\x64\xd1\xb8\x63\xef\x0e\x27\x81\x59\ +\x0a\x31\x61\x35\x72\x49\x48\x99\x47\x83\x8d\x65\x4f\x64\x84\x9c\ +\x1e\x74\x66\xa1\x7e\x00\xc4\x41\xc6\x23\x4f\xd0\xd7\xc1\xe4\x2b\ +\x40\x1f\x3a\x67\x50\xdf\x05\x1c\x74\x6f\x41\x2d\xc9\x2f\x3e\xf3\ +\xdf\xce\xcf\xf9\x05\x9a\x2b\x0c\xe1\x15\x74\x66\xa0\x9e\x08\x2d\ +\x9c\xb7\x89\x2a\xbe\xbe\xee\x86\x54\x57\x25\x79\xcb\x4c\xc2\xc6\ +\x5a\x99\x45\xe0\x4b\x90\xaa\x27\xe0\x25\xb8\x43\x34\xd3\x73\x96\ +\x8f\xfc\xa4\x01\xf5\x32\xb8\xe7\x79\x54\x82\x67\x7e\x01\x38\x46\ +\x57\xec\x1b\x63\x77\xb5\xfd\xf8\x32\xba\xe2\x07\x9e\x8e\xff\x68\ +\x5f\x2e\x7a\x3b\xf1\xa6\xcf\x67\x7f\x43\x9a\x64\x1f\x15\x98\x17\ +\x9a\x6c\x02\x4f\xe0\xa4\x03\x8d\x29\xb2\xe1\xb1\xa9\x03\x4a\xa8\ +\x04\x6f\x83\xdb\x09\xec\xf7\x2d\x6c\xe5\x37\x0d\x47\x05\x69\x68\ +\xa5\x00\xcd\xf4\x6e\x01\x4f\x87\x87\xc4\xa9\x2f\x7f\x1f\x0d\x67\ +\x87\x05\x52\x27\x18\xbe\xbd\x5f\x08\x9f\xb9\x72\x27\xa8\xb7\xba\ +\x01\x8d\x03\xf4\x48\x65\xa0\x48\x09\x2e\xe5\xe3\x01\x28\x20\xbe\ +\x01\xf3\x47\x46\x7b\x02\x65\x25\xb4\xf2\x90\x9c\xb3\x94\x9b\x3a\ +\x51\x78\x9f\x61\xdf\x3f\x84\xb4\x14\x08\x20\x37\x4e\x7c\x6a\x7c\ +\xcd\xea\xb5\x04\xb0\x00\x58\xf6\xdf\xba\x84\x18\x07\x56\x18\x24\ +\x34\x0c\x8f\x31\x81\x9c\x93\xf3\x12\x2e\x8c\xd4\x7b\x06\x8a\x84\ +\x69\xd1\xfa\x0a\x43\x60\x05\x47\xe0\x5a\xe1\xec\x28\xc1\xf4\x07\ +\x3b\xa7\x30\x94\x36\x3c\x3c\xd7\x85\xea\xa8\x7c\xdb\x35\x72\x0d\ +\xee\x0c\x55\xe6\x19\x88\x05\x30\x41\x71\x54\x77\x13\x9b\x5e\x83\ +\x6e\x64\xde\x62\x21\x0c\xbd\xb1\xb9\xa9\x1f\x51\xf4\x5c\xae\x3d\ +\xb6\x02\xcb\x70\x65\x69\xf3\xc0\x3f\xc8\xb4\x97\xec\xf6\x14\x9a\ +\x50\x7b\x66\xd0\x21\x20\x8f\xd1\x24\x0b\xc0\xa3\x02\xfd\x32\x62\ +\x85\xbb\x7d\x8d\x34\x73\xd0\xc3\xce\xd6\x8e\x8a\x05\x7a\x15\x98\ +\xb8\xce\xf6\x4f\xec\x75\x11\xf4\x47\xf4\xbf\x26\xd4\x1c\xc5\x47\ +\x70\xac\x79\x23\x01\x94\x9f\xa1\xf6\x37\xc6\xd5\xb3\x11\x8e\xcc\ +\xf2\x1e\x90\x9a\xa4\x10\xd2\x6d\xff\xc8\x7f\x46\x58\x87\x42\x28\ +\x12\x40\x19\xdb\xb3\xcc\xcd\x11\xeb\x80\x2e\x51\xbc\x1c\x40\x11\ +\xb3\xc3\x08\xbf\xca\xcf\x11\x9f\xf9\x51\xd6\x61\x28\x14\x8d\x1f\ +\x5b\x39\xc6\x02\x48\x72\xe7\x39\x6d\x79\x03\x22\x12\xe8\x93\xde\ +\x27\x16\x29\x3c\x4b\x08\x32\x43\xea\xe9\xdd\x78\xee\x00\xc4\xe7\ +\x17\xb3\x60\x99\xc1\x23\x06\xb7\x38\x3f\x06\x3c\x07\x56\x46\x68\ +\x7b\x22\x21\x94\x50\xaf\xcd\xb8\x70\xc9\xc0\x98\xbe\x49\x12\x4e\ +\xe7\x05\x6a\x09\xc0\x01\xfb\xe4\x2f\x12\x8b\xa4\x7d\x00\x6d\x43\ +\x6f\x64\xe0\x25\xf0\x21\x23\x8b\x13\x9c\xa0\x61\xf8\x47\x0c\xbf\ +\x13\xc4\x67\x80\x8e\x8b\x10\x0d\x7e\x8a\x43\xad\xcd\x2e\x63\xe8\ +\x00\x00\xf1\x8e\xd0\x53\x15\x42\x7a\xb3\x73\x80\x79\x1b\xcb\x25\ +\x34\xaa\x43\x28\x4d\xee\xeb\xfe\x05\x6c\x6a\xde\xa0\x08\x64\x8e\ +\xc1\xe5\xcb\xa6\x45\xf0\x00\xe6\x26\x31\xd3\x6d\xed\x45\xd2\x88\ +\x55\x9a\x68\x6e\xe3\x91\xc7\x35\x32\x1f\x00\x9a\xe7\x9f\x04\x77\ +\x0e\xec\x28\x12\xd9\x40\xad\xc3\xbc\x8f\xbd\x43\x44\x4b\xc0\x19\ +\xc8\x3b\x44\x91\x16\x9a\x81\x59\x43\xa3\xba\x26\x70\x01\x17\x5b\ +\x5e\xc7\x58\x4e\xcf\x29\x1a\x19\x2e\xe9\x58\x1e\x00\xff\x06\x89\ +\x4d\x73\x92\xd9\x49\xf2\x01\xc9\xff\x24\x84\xee\x78\xfc\x7b\x7a\ +\xaf\x09\x3e\x83\x9d\xf3\x49\x62\x01\x74\x7c\xdb\x32\x7a\x1e\xd1\ +\x0b\x05\x8e\x3c\xbd\x02\xec\x67\xb7\xb1\xa0\xb9\x43\x59\xcf\xe6\ +\x10\xd3\x73\xf7\x4f\x70\xed\x60\x8e\x82\x3c\xa3\x05\x02\x9a\x38\ +\xd9\x8d\xe6\x5c\xd3\x60\x2d\x61\x3c\x09\x87\xc5\xa1\xbb\xfa\x38\ +\xdb\x0e\x0c\x0a\xb6\x32\xd9\xe9\xf8\x08\x84\x57\xd7\x16\xec\xa1\ +\xc1\x8d\x05\xcf\xc8\x14\x56\xe0\x6f\x65\x5f\xfb\x6e\x30\xb6\x0e\ +\x2b\x14\xe6\x24\x93\xc0\xcb\x84\xe4\x3a\x3e\xa3\x38\x8b\x94\xe0\ +\x85\x6d\x0a\x5d\x5f\x89\xb2\xea\x6d\xdc\x15\xd0\xf2\x67\x30\xc9\ +\xdb\xbf\x0e\xf3\x09\x04\x42\x68\xdd\x46\x13\x24\x56\x4e\xb2\x1c\ +\xd0\x18\xf7\x2d\xa3\xd6\x68\x2c\x25\xd8\x46\xed\xa5\x19\x3f\xfb\ +\x6d\x6e\x64\x5f\x01\x38\x83\xc6\x32\x9c\x9c\x8d\xe1\x25\x5e\x03\ +\x9c\x28\xce\x99\x15\x06\x65\x77\x31\x2c\x53\x7c\xbc\x92\x1a\x85\ +\x9c\x59\xb5\x04\x70\x86\x2a\x97\x72\x41\x86\x15\x38\xee\x90\xbb\ +\xf7\x4f\xb7\xfd\x57\xd0\x38\xd3\x73\xfa\x63\x81\xac\x2a\x4e\xbe\ +\xc2\xf4\x18\xa5\x01\xad\xae\x2d\x74\x99\x83\xb3\x2e\xca\x53\x4e\ +\x78\x45\xf9\x80\xc4\x66\xbe\x6d\x13\xd4\x3c\x54\x84\xc9\x31\xc9\ +\xb9\xb7\xa7\xe8\x96\x5b\x85\x4e\x41\xa1\xd3\x38\x70\x3e\xab\x38\ +\x92\xea\x4f\xd3\x6d\x9e\x04\x66\x61\x2e\x4e\xd6\x26\xb0\x02\x53\ +\xd3\x01\x4f\x19\x88\x05\x70\x41\x9a\x34\x70\xde\x74\xc9\xba\x8d\ +\xd7\xed\x2b\x72\x4a\xd8\xee\xed\x15\xb0\x07\xf5\x4b\x55\x5c\xb2\ +\x38\x9e\xaf\x2f\xce\x8f\x5d\x81\x49\x8f\x23\x3c\xf3\xa1\x10\x28\ +\x01\xab\x76\xfa\x0e\xd4\x34\x5f\x54\xc0\x7d\xeb\x1b\xea\x44\x56\ +\x20\x36\x83\xf1\x95\xd3\x27\x68\x39\x1a\xc0\x32\x5a\x27\xd4\x0f\ +\xc6\x5d\x02\xbf\x45\xaf\xc7\x97\x0d\x9d\x97\xa4\xa0\x4e\xd1\xf8\ +\xfc\x3d\x2f\x84\x61\x89\x0f\x21\xad\x35\xa0\x81\xba\xd1\x56\x4d\ +\xcf\x25\xf0\x7b\xe0\x53\x06\x97\xa3\x89\x19\x4c\xca\x6b\x27\xf5\ +\x66\x3b\x85\x12\xc3\xdd\x67\xd9\x42\x0b\x0f\xc2\xb6\x86\xf7\x08\ +\x37\xa2\xf6\xa4\x0e\x6f\xcd\x7f\x1b\x56\x43\x1a\xdc\xa8\x46\x30\ +\x7d\x7e\x05\xf3\x52\x45\xaa\x68\x09\xed\x1c\xc8\xbb\xb6\x4e\x90\ +\xf7\xf3\xd6\x4a\x3e\x64\x8c\x1a\xa1\x43\x90\x20\x23\xeb\x4e\xe0\ +\xa4\xab\xf5\x80\x29\xa2\xf0\x8a\xba\x0f\xee\x11\xea\x25\xbe\x06\ +\xb3\xe3\x82\xcc\xa0\x29\xfb\xef\xd1\xcc\xcf\x0e\x79\xc5\xb8\x81\ +\xa6\xe0\xc3\x0b\x9e\xe4\x6e\x22\x03\x96\x00\xba\x40\x95\x4c\x49\ +\xec\xcc\x0b\xa8\x4c\x7a\xc9\x16\x85\xb4\xfb\xd0\xaa\xaa\xce\xb8\ +\x56\x5d\xee\x98\x20\x65\xc5\xdd\xaa\x90\xaf\xfa\x08\x14\x63\x7b\ +\x11\xba\x1d\x32\x1a\x5f\x2a\xa8\x6e\xcb\xd5\x28\x58\xb1\x40\x09\ +\xdc\x9e\x6e\x79\x79\x16\x28\xa0\xa7\xa8\x46\xee\x01\xff\x0d\x98\ +\x0f\x24\x3f\x77\xe0\x05\x94\x84\xbf\xa1\x0b\x7c\x13\x48\xbc\xbf\ +\x55\x94\xd1\xa7\x30\x27\x51\xbf\x04\x39\xc6\xfb\xd0\x68\x91\xb9\ +\xbe\x93\x8a\xd2\xe3\x76\x40\xee\x1a\xcc\x66\xe0\x25\x69\x2e\xc0\ +\xed\xa2\x75\x36\xc9\xd6\x17\x54\xf1\x54\xc8\x66\x8d\x22\x1c\x4e\ +\x54\x80\xec\xa3\xb5\x3f\xf7\xc6\x08\x97\x0d\x68\xdd\x46\x9d\x9b\ +\x25\xe0\xb9\xee\xb0\x9c\x9d\x9f\x26\x5d\xd5\xe3\x26\xba\xea\x65\ +\x54\x79\x76\xd0\xda\xe6\x25\x65\x1e\xd0\xcb\xd8\x8c\x33\x14\xed\ +\x00\x77\x9a\x0d\x57\xdd\x1e\x5a\xc3\xbf\x81\x46\x66\x9f\xa3\x42\ +\x78\x00\xe7\x27\x50\x3d\x52\x22\x0b\xcd\x5b\x5f\xe7\x68\x24\x15\ +\x9b\x49\x1b\x80\x83\x0b\xbf\xbb\xaa\xc9\x0b\x14\x21\x1c\x7b\x66\ +\xbc\xa9\x33\x1d\xcb\x65\xc5\x2f\x4b\x1e\x6f\x12\x23\x7c\x00\x3c\ +\x04\x0e\xc0\xbd\x0c\xc6\x97\xe3\x7b\x46\xeb\x08\xc4\xcc\x74\x3d\ +\x21\x0f\xd1\x82\x45\xd0\x2b\xef\x65\xdf\xbe\x1f\xb4\x1b\x20\x62\ +\xf7\x8b\x83\xea\xa4\x67\xb0\x53\xe0\xc5\xad\x8f\xc0\x7d\x05\x4c\ +\xc1\xd1\xf7\xd9\xeb\x39\x71\x9e\xb6\xf8\xcc\x8f\x93\x42\x93\x3b\ +\x03\xe7\x27\x53\x2e\x5f\xcf\x5a\x07\xf0\x66\xe8\x7d\xec\x44\x49\ +\x32\xe6\xff\x50\x2e\x0f\xba\x00\xf2\xf3\xbc\xf9\x95\xa6\x5a\x8a\ +\x5c\xb9\xfc\x1d\xcc\xb2\x5e\x1b\xf9\xc7\xd8\x2f\x4c\xac\x92\x7b\ +\x61\x42\x1c\xfa\x82\x85\xf1\x02\x43\x3a\x66\x7b\xcc\x89\x43\x9c\ +\x05\xcf\x88\x43\xdf\x18\xf9\xa5\xd1\x57\xce\xfa\x2b\xa9\x10\xaa\ +\x8c\xff\xc2\x44\x8a\xe8\x4f\x05\x4e\xc8\x46\x5e\x08\x00\xf2\x1e\ +\xfa\xca\x4a\xee\xa5\x04\x5e\xeb\x95\x99\xb4\xad\xe4\x9d\x9f\xb7\ +\x40\xde\x31\x9c\x9f\xb2\xa5\xe5\x3d\xf3\x7f\xc8\xe3\x2b\x9e\x3c\ +\x91\x5a\x59\xa5\x16\x7b\x80\xe0\x77\x82\x71\x7d\x2d\x1b\x7e\x6b\ +\xde\xd3\x4f\x2b\x74\x9e\x2a\x8c\x7e\x69\x6a\xca\x8f\x09\x04\x2f\ +\x2b\x0c\x5e\xbe\x2a\x7a\x39\x6a\x1e\x33\x66\x91\x2d\xcf\x43\x29\ +\xbf\x9b\x15\x62\x44\x86\x93\x23\x9b\xa8\xb6\xf5\x35\xba\xb4\xfc\ +\xef\x1a\x6a\xe6\x1c\x7a\x01\x72\xc1\xe0\xb5\xb9\x19\x40\xa0\x37\ +\x0d\xe5\xc4\x29\x4a\x4a\x64\x7b\xc1\xff\xe4\xf6\x26\x79\x6d\x2e\ +\x28\x97\x4d\xe9\xeb\xfa\x71\x0e\x35\x61\xa7\xfe\xf7\x24\xaa\xc4\ +\x7d\x01\x06\x1d\x54\xa1\xce\x06\x78\xf6\x06\x4e\x93\xed\xc0\x8d\ +\xb8\xa2\x8e\x41\x26\x30\x4a\xcd\x3c\x9e\x3a\x79\x2d\x1b\xbf\x38\ +\x59\x42\xaf\xca\x92\x23\x54\x65\xe0\x5f\xe0\x99\x38\x24\x6b\xf3\ +\xac\x17\x27\x85\x41\xe2\x33\x06\xa3\xb4\x36\x7d\xac\x88\xc7\x37\ +\xf7\xd5\x59\xab\xe1\x0d\x80\x0c\xcf\x6f\x1a\xf3\x09\xa8\x10\xfe\ +\x07\xb4\x0a\xfd\x7e\xcf\x22\x5b\xc2\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x02\x0b\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xbd\x49\x44\x41\x54\x58\x85\xed\ +\x94\x3d\x6b\x14\x51\x18\x85\x9f\x73\xd7\x42\x09\x88\x36\x16\x16\ +\x41\xc1\x5a\x6c\x92\x45\x04\x3b\x59\x91\xe0\xba\x8b\xa6\x51\xc1\ +\x7f\x90\x5f\x20\xa8\xbf\x40\x6c\x52\xda\x58\x28\xb2\x89\x41\x0b\ +\x43\x4a\x91\x24\x6b\xa3\x29\x52\x59\xd8\x28\x58\x25\xa8\x91\x90\ +\xdd\xbd\xc7\x62\x66\xdd\x65\xa3\x9b\x99\xf5\x23\xcd\x3c\x30\xf0\ +\x32\xdc\x39\xe7\xdc\xfb\xbe\x77\xa0\xa0\xa0\xa0\x60\x9f\x51\xb7\ +\x98\x9c\x8b\x1b\x82\x23\xff\xc3\xd4\xb0\xd9\xac\x87\xa3\x00\xe1\ +\x67\x12\xf5\xea\x7f\x4d\xbf\x57\xaf\x68\xe9\x24\xb0\x92\x26\x04\ +\x13\x81\xce\xdf\x78\x6c\xa2\x7b\xfe\xcb\xa9\x57\x12\xa6\x3f\xd9\ +\xe9\x45\x8f\x1d\xfa\xee\x06\xa6\x82\x8d\x51\x94\x30\x7f\x86\xc0\ +\x01\x84\xe1\xe5\xf6\x98\xae\xae\x55\xb4\xb5\xeb\x04\x00\xd6\x2a\ +\xda\xfa\xda\xd2\x65\xe4\x27\x48\x48\x0e\x83\x21\xf3\x60\x23\x43\ +\x48\x24\xfc\xf8\x5b\x5b\xd5\x7e\xf3\x5d\x01\x00\xd6\xa7\xb5\x33\ +\xde\x0a\xd7\x6d\xcf\xa6\xde\xc1\xce\x1f\xc2\x20\x89\x20\xc0\xf6\ +\xec\x78\x3b\xdc\x58\x9f\xd6\xce\xe0\xba\xdf\x0b\xdb\x2a\x3f\x8b\ +\x77\xb1\x6e\x27\x82\x8a\xc2\x99\xda\x61\x24\xe1\x74\x73\xbe\xb7\ +\x5a\x0b\x77\x90\x7e\xf9\xed\x9e\x3b\x2b\xcf\x7b\x06\xfb\x7e\x37\ +\x15\x28\x0e\x37\x77\x10\x52\x22\xae\x99\x95\xba\x1e\x0c\x5b\x9f\ +\xe9\x68\xcb\x0d\xdf\x44\x7e\x08\x94\x86\x85\xe8\x33\xef\x20\xdd\ +\x5a\xad\xe9\xd1\x5e\xda\x99\x7b\x3b\x39\xe7\x29\xe1\xa7\xc0\x41\ +\x92\x9b\x3a\x18\xa2\x3b\xb0\xdb\x46\xd7\x9a\x75\xbd\xc8\xa2\x9b\ +\x6b\xb8\x26\x1a\x3e\x1f\xe4\xe7\xc0\x61\x83\x95\x86\x30\x04\x25\ +\x5a\x5f\x1c\x34\xd5\xbc\xa2\x57\x59\x35\x73\x4f\xf7\xc4\xbc\xcf\ +\x04\x7b\x11\x38\x86\x30\xd1\xdd\x96\x7f\x8e\xd2\xc5\x37\x35\xbd\ +\xcd\xa3\x37\xd2\x1d\x3f\xbb\xe0\x53\xb1\xe3\x25\xe0\x44\xfa\xea\ +\x43\x28\xe9\xc2\x72\x55\xef\xf3\x6a\x8d\xfc\x93\x39\xb7\xe0\xe3\ +\xed\x8e\x3f\x02\xef\x0e\x94\x74\xe9\x75\x55\x9f\x46\xd5\x2a\x28\ +\x28\x28\xd8\x57\x7e\x00\xa4\xf8\xb1\x06\x78\x8b\xc7\xb8\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xcf\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x81\x49\x44\x41\x54\x58\x85\xed\ +\xd2\x31\x0e\x82\x50\x10\x84\xe1\x7f\x9f\x77\x20\xe1\x36\xaf\xe0\ +\x08\xf6\x16\x5a\x70\x0b\xc2\x2d\x28\xb0\xb5\xb5\xb5\x31\xe1\x36\ +\x26\xdc\x01\x96\x0a\x88\x98\xd8\xf1\x68\xe6\xeb\x76\xb3\xc9\x4c\ +\xb1\x20\x22\x22\x72\x30\xdb\xce\x31\x56\xa7\x3d\x03\xbb\xae\x1e\ +\x00\xff\x29\x50\x9c\x6f\xd1\x9c\x07\x90\xef\x59\x00\xe8\xc7\xd1\ +\x2f\xef\xe7\xfd\x05\x10\x96\xb5\xd3\x24\x08\x07\xc8\x42\xb0\x76\ +\x1e\xc2\xbf\xcb\x14\xd6\x02\x46\x09\x7c\x12\x64\xf6\x8e\x5d\xd7\ +\xd8\x6f\xc9\x9f\x50\x44\x44\xe4\x70\x13\x6a\x59\x1a\x0e\xce\xfb\ +\x3e\xfc\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +" + +qt_resource_name = b"\ +\x00\x09\ +\x09\x5f\x97\x13\ +\x00\x71\ +\x00\x73\x00\x73\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x73\ +\x00\x0a\ +\x09\x24\x4d\x25\ +\x00\x71\ +\x00\x64\x00\x61\x00\x72\x00\x6b\x00\x73\x00\x74\x00\x79\x00\x6c\x00\x65\ +\x00\x04\ +\x00\x06\xa8\x8b\ +\x00\x64\ +\x00\x61\x00\x72\x00\x6b\ +\x00\x0d\ +\x0d\x36\x0c\x63\ +\x00\x64\ +\x00\x61\x00\x72\x00\x6b\x00\x73\x00\x74\x00\x79\x00\x6c\x00\x65\x00\x2e\x00\x71\x00\x73\x00\x73\ +\x00\x02\ +\x00\x00\x07\x83\ +\x00\x72\ +\x00\x63\ +\x00\x17\ +\x0e\xfe\x32\x47\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\ +\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x27\ +\x0d\x0d\x92\xa7\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ +\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1d\ +\x0c\x09\x66\x07\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ +\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x01\x87\xae\x67\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ +\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x20\ +\x0e\xfe\x76\x47\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\ +\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x11\ +\x09\xcb\xcc\xe7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\ +\x00\x18\ +\x07\x8b\xec\xe7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ +\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x0d\x9d\x97\x47\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ +\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1d\ +\x09\x07\x81\x07\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\ +\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1b\ +\x09\x0d\xa6\xc7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ +\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x07\x36\x1b\x47\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\ +\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x0c\xeb\x5f\x67\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\ +\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x10\ +\x05\x3e\x39\x67\ +\x00\x62\ +\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x00\x4f\x29\xc7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x5f\x00\x70\x00\x72\x00\x65\ +\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x26\ +\x04\x24\xf6\xe7\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\ +\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x27\ +\x0e\x3d\xd7\xc7\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ +\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\ +\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1e\ +\x07\x50\x2b\xe7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x5f\x00\x70\ +\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x0d\x6c\x22\x07\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\ +\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x18\ +\x03\xae\x62\xe7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ +\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x0e\x19\x8b\xc7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\ +\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x04\xf8\x32\xc7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\ +\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1c\ +\x02\x75\x51\x87\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\ +\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x21\ +\x01\xf6\xa2\x67\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\ +\x00\x18\ +\x07\x83\xfe\x27\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ +\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x14\ +\x01\xe9\xfd\xe7\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x40\x00\x32\x00\x78\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x13\ +\x08\xc8\x96\xe7\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x2e\x00\x70\ +\x00\x6e\x00\x67\ +\x00\x14\ +\x07\xec\xd1\xc7\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x16\ +\x03\x94\x39\x67\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x40\x00\x32\ +\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x29\ +\x09\x81\xd3\x67\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\ +\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x11\ +\x08\x8f\x96\xa7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\ +\x00\x17\ +\x07\x06\x3d\xa7\ +\x00\x74\ +\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ +\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1d\ +\x0e\x35\xf3\xa7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\ +\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x05\x35\xb6\x67\ +\x00\x74\ +\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ +\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1c\ +\x00\x10\xb9\x67\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\ +\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x0b\x46\x72\x87\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x5f\x00\x66\x00\x6f\x00\x63\ +\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1c\ +\x09\xc8\xa4\xa7\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x64\ +\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x0c\xa5\xc5\x27\ +\x00\x62\ +\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\ +\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x15\ +\x0a\x12\x4a\x67\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ +\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x0f\ +\x06\x16\x25\xe7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1f\ +\x04\x8d\x48\xc7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x5f\x00\x64\ +\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x02\xb6\xb5\xa7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ +\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1f\ +\x0c\xa4\x6f\xa7\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x64\ +\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x00\x6c\xa3\xa7\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\ +\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x18\ +\x0e\x0c\xda\xa7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\ +\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x25\ +\x06\x6c\x47\xe7\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ +\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\ +\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x01\x0e\xe5\xa7\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\ +\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x0c\xd5\x5a\x67\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\ +\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x18\ +\x07\x86\x4e\x27\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ +\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x12\ +\x00\x68\xca\xe7\ +\x00\x74\ +\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ +\x00\x67\ +\x00\x1a\ +\x0f\x5a\xb4\xa7\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\ +\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x16\ +\x05\x7a\xd3\x67\ +\x00\x62\ +\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\ +\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x2c\ +\x0c\xa4\x5a\x47\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\ +\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x24\ +\x05\x94\xa0\x47\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x0f\x1e\x9b\x47\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\ +\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x22\ +\x01\x41\xee\x87\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ +\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\ +\x00\x67\ +\x00\x14\ +\x00\x2e\x0a\x07\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x03\x9f\x72\x87\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ +\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x16\ +\x0f\x35\xfb\x07\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ +\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1c\ +\x0f\xd0\x9c\x67\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ +\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x0e\ +\x08\xfa\xe1\x27\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x0d\x0d\x28\xa7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ +\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x18\ +\x0f\xd7\x34\x67\ +\x00\x74\ +\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ +\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x0c\x24\xec\x07\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x66\ +\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x21\ +\x05\x70\x30\x27\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ +\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\ +\x00\x18\ +\x06\x60\x39\xe7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ +\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x11\ +\x0a\xe5\x6c\x07\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\ +\x00\x1a\ +\x0a\xa0\x05\x47\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x5f\x00\x64\x00\x69\x00\x73\ +\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x0f\x7e\x6f\xe7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\ +\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x15\ +\x0c\x60\x8e\x27\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\ +\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x0b\x59\x6e\x87\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x66\ +\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1b\ +\x02\x0d\xa6\x67\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ +\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x18\ +\x0e\x31\x43\xa7\ +\x00\x74\ +\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ +\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x13\ +\x0c\x24\x39\x47\ +\x00\x62\ +\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\ +\x00\x6e\x00\x67\ +\x00\x21\ +\x0e\xf1\x37\x67\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ +\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\ +\x00\x1b\ +\x0b\xea\x1b\xe7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x5f\x00\x70\ +\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x11\ +\x05\x2a\x70\x67\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\ +\x00\x20\ +\x09\xd7\x1f\xa7\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ +\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x01\xc7\x25\x47\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ +\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1e\ +\x04\x3c\x09\xc7\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x70\ +\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1b\ +\x0d\xfd\xa2\x07\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ +\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x0f\ +\x0c\xe2\x68\x67\ +\x00\x74\ +\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x18\ +\x06\x6d\x9b\x27\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ +\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x16\ +\x0f\x80\x4f\xa7\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x40\x00\x32\ +\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x0e\x26\x93\xe7\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ +\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x16\ +\x06\x14\xad\xc7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ +\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x14\ +\x00\x44\xa0\x47\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x18\ +\x07\xa5\xb1\x27\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ +\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x04\xce\xfa\x67\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\ +\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x24\ +\x04\x0b\x8d\x27\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ +\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x1d\ +\x04\x34\xf0\xc7\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\ +\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x15\ +\x0f\xac\xe3\xc7\ +\x00\x62\ +\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\ +\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x14\ +\x0b\x2d\x81\x07\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x16\ +\x0a\x7a\x87\x67\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\ +\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x15\ +\x06\xf8\x08\xa7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ +\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x0f\ +\x01\x40\x2d\xa7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x12\ +\x04\xb5\x9d\x47\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ +\x00\x67\ +\x00\x17\ +\x0f\x18\x45\x87\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ +\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x14\ +\x05\xe4\x2d\xe7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x1b\ +\x07\xac\x39\xa7\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ +\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1b\ +\x0a\x19\xf4\xe7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\ +\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x22\ +\x08\x8a\x08\x27\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ +\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\ +\x00\x67\ +\x00\x16\ +\x0a\x1a\xd6\x47\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ +\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x12\ +\x04\xb1\x94\x27\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ +\x00\x67\ +\x00\x1e\ +\x0c\xd2\xb9\x87\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x70\ +\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1b\ +\x08\x21\xa7\xc7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ +\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x18\ +\x05\x12\xcf\x67\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\ +\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1c\ +\x04\x73\x5f\x47\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x5f\x00\x70\x00\x72\x00\x65\ +\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1c\ +\x08\x2e\xd3\x67\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x66\ +\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1c\ +\x00\x06\x3d\xc7\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x66\ +\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x0a\x14\xed\x47\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ +\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x0d\x33\x2d\xa7\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\ +\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x15\ +\x0b\x78\x08\xe7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ +\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x23\ +\x07\x14\x6d\x87\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ +\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\ +\x00\x6e\x00\x67\ +\x00\x1f\ +\x02\x4f\x6a\xa7\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x64\ +\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x11\ +\x01\xf6\xff\x67\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\ +\x00\x1e\ +\x05\x75\xad\x27\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ +\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x09\x2e\xa9\x47\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ +\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x13\ +\x05\x76\x1e\x67\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x2e\x00\x70\ +\x00\x6e\x00\x67\ +\x00\x1c\ +\x0c\xfb\xa0\x47\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\ +\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x16\ +\x01\x75\xcc\x87\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ +\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x22\ +\x00\xa7\x99\x47\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ +\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ +\x00\x67\ +\x00\x15\ +\x06\x62\x08\x27\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ +\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x23\ +\x06\xf2\x1a\x47\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ +\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\ +\x00\x6e\x00\x67\ +\x00\x1a\ +\x05\x28\x8d\xa7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\ +\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x24\ +\x05\xed\xfa\xe7\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ +\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x18\ +\x02\x48\x15\x27\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ +\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x0d\ +\x0b\x72\x3d\x07\ +\x00\x62\ +\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x12\ +\x04\xb3\x4c\x27\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ +\x00\x67\ +\x00\x0e\ +\x06\x0c\xe6\x07\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1b\ +\x0f\x79\xa3\xc7\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x70\ +\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x23\ +\x03\x43\xb9\x67\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\ +\x00\x6e\x00\x67\ +\x00\x1b\ +\x0a\xfb\x2d\x27\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x70\ +\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x16\ +\x04\x9c\xa4\xa7\ +\x00\x62\ +\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\ +\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x0e\x98\x18\x27\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\ +\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x18\ +\x06\x43\xc6\xe7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ +\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x04\x64\xf7\x07\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ +\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x05\x11\xe0\xe7\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\ +\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1f\ +\x06\x75\x64\x87\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ +\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x2b\ +\x03\xd2\xba\xc7\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\ +\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x0f\x9a\xe5\x07\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ +\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x29\ +\x09\xe4\xb0\x07\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ +\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x25\ +\x08\x07\x7e\x87\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ +\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\ +\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x12\ +\x06\xa7\x5a\x47\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ +\x00\x67\ +\x00\x1c\ +\x08\xb5\x77\x67\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\ +\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x23\ +\x03\xa5\x91\x47\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ +\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\ +\x00\x6e\x00\x67\ +\x00\x17\ +\x0d\xdf\xcf\xa7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ +\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x14\ +\x0b\x23\x21\x67\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x16\ +\x07\x09\xf8\x27\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x40\x00\x32\ +\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x02\x38\x25\x07\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ +\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1f\ +\x0b\x48\x50\x87\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ +\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x27\ +\x0c\xeb\xe5\x67\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\ +\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1f\ +\x03\xf7\x18\x07\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\ +\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1f\ +\x0a\xae\x27\x47\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ +\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x0a\x27\x78\x07\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ +\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x13\ +\x0b\x4e\x57\xa7\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x2e\x00\x70\ +\x00\x6e\x00\x67\ +\x00\x13\ +\x00\xcf\x5c\xc7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\ +\x00\x6e\x00\x67\ +\x00\x1a\ +\x07\x88\x25\x07\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ +\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x11\ +\x08\xfc\x49\xe7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\ +\x00\x14\ +\x0a\x20\x6e\x07\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x40\x00\x32\x00\x78\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x0e\ +\x0d\x4e\x71\x87\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x0f\ +\x00\xd6\x25\xc7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x0e\xbc\xc3\x67\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\ +\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x09\x5e\xb0\x07\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ +\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x15\ +\x03\x1c\x93\x87\ +\x00\x74\ +\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ +\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x09\x2f\xda\x87\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x5f\x00\x66\x00\x6f\x00\x63\ +\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x0f\ +\x06\x53\x25\xa7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x0c\x33\x94\x27\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ +\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1e\ +\x0f\x96\x71\x87\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x10\ +\x00\x55\x62\x07\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x00\x38\x7f\xa7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x5f\x00\x66\ +\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1d\ +\x0a\xd8\x81\x27\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\ +\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x0f\ +\x00\x6f\x04\x87\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x21\ +\x0a\x51\x5f\x47\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ +\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\ +\x00\x11\ +\x0b\xda\x30\xa7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\ +\x00\x1c\ +\x08\x3f\xda\x67\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ +\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x26\ +\x07\x4b\x88\xe7\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ +\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\ +\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1c\ +\x01\xe0\x4a\x07\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x64\ +\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x22\ +\x04\x9a\x03\x67\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ +\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ +\x00\x67\ +\x00\x2a\ +\x0f\xc4\xf7\x07\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ +\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x18\ +\x06\x65\x89\xe7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ +\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x15\ +\x04\x90\x0a\xc7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ +\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1c\ +\x07\x5b\xb0\x67\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\ +\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1c\ +\x01\x15\x51\xe7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x5f\x00\x66\ +\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x0f\ +\x0f\x2c\x24\xc7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x0b\xf3\xab\x27\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x40\ +\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1d\ +\x08\xe1\xf6\xc7\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\ +\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x28\ +\x0f\x63\x53\xc7\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\ +\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x15\ +\x0d\x86\xf9\xe7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\ +\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1b\ +\x00\xc1\x23\x67\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ +\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x12\ +\x0d\x78\xb6\x87\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\ +\x00\x67\ +\x00\x24\ +\x05\x98\x88\x87\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ +\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x26\ +\x0f\xfb\x22\x07\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ +\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\ +\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x0b\x8a\x15\xe7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ +\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x0f\xff\xfc\x07\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ +\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x26\ +\x0f\x35\xf0\xa7\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ +\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1e\ +\x00\x4f\xcb\xe7\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ +\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x0b\x9d\x16\x67\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ +\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1d\ +\x06\xba\x02\xa7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x5f\x00\x64\x00\x69\x00\x73\ +\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x07\xb7\xa1\x47\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\ +\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x20\ +\x07\x4e\x5a\xc7\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x0b\x9d\x4d\x67\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ +\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x0c\ +\x0b\xd0\x7a\xe7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1b\ +\x02\xd4\x90\x87\ +\x00\x74\ +\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ +\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x12\ +\x04\xa2\xb3\x27\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ +\x00\x67\ +\x00\x29\ +\x08\x67\xa4\xa7\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\ +\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x18\ +\x08\xd2\xa3\x27\ +\x00\x62\ +\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\ +\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x14\ +\x06\xe9\x8f\x67\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x1c\ +\x00\xf3\x26\x27\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x5f\x00\x64\ +\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +" + +qt_resource_struct_v1 = b"\ +\x00\x00\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x01\ +\x00\x00\x00\x18\x00\x02\x00\x00\x00\x01\x00\x00\x00\xd5\ +\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\ +\x00\x00\x00\x32\x00\x02\x00\x00\x00\x01\x00\x00\x00\x04\ +\x00\x00\x00\x60\x00\x02\x00\x00\x00\xd0\x00\x00\x00\x05\ +\x00\x00\x18\x4c\x00\x00\x00\x00\x00\x01\x00\x01\x3b\x76\ +\x00\x00\x07\xe8\x00\x00\x00\x00\x00\x01\x00\x00\x68\x2b\ +\x00\x00\x0d\x0e\x00\x00\x00\x00\x00\x01\x00\x00\xb6\x47\ +\x00\x00\x25\xea\x00\x00\x00\x00\x00\x01\x00\x01\xd7\xaf\ +\x00\x00\x13\x62\x00\x00\x00\x00\x00\x01\x00\x01\x04\xe1\ +\x00\x00\x03\x52\x00\x00\x00\x00\x00\x01\x00\x00\x41\xeb\ +\x00\x00\x2c\x2c\x00\x00\x00\x00\x00\x01\x00\x02\x1c\x30\ +\x00\x00\x25\xc4\x00\x00\x00\x00\x00\x01\x00\x01\xd4\xe1\ +\x00\x00\x0b\x4e\x00\x00\x00\x00\x00\x01\x00\x00\x97\x7a\ +\x00\x00\x09\xec\x00\x00\x00\x00\x00\x01\x00\x00\x88\x43\ +\x00\x00\x26\x62\x00\x00\x00\x00\x00\x01\x00\x01\xe3\xbc\ +\x00\x00\x1a\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x60\x51\ +\x00\x00\x2a\x68\x00\x00\x00\x00\x00\x01\x00\x02\x0e\x25\ +\x00\x00\x23\x4e\x00\x00\x00\x00\x00\x01\x00\x01\xb5\x50\ +\x00\x00\x24\x2c\x00\x00\x00\x00\x00\x01\x00\x01\xc5\x39\ +\x00\x00\x2e\xd4\x00\x00\x00\x00\x00\x01\x00\x02\x3b\x4e\ +\x00\x00\x0a\xa6\x00\x00\x00\x00\x00\x01\x00\x00\x90\xe9\ +\x00\x00\x29\x0c\x00\x00\x00\x00\x00\x01\x00\x01\xfc\x4d\ +\x00\x00\x15\x4e\x00\x00\x00\x00\x00\x01\x00\x01\x17\x04\ +\x00\x00\x0c\xc4\x00\x00\x00\x00\x00\x01\x00\x00\xb5\xb7\ +\x00\x00\x1a\xcc\x00\x00\x00\x00\x00\x01\x00\x01\x5e\xc4\ +\x00\x00\x01\x32\x00\x00\x00\x00\x00\x01\x00\x00\x23\x58\ +\x00\x00\x11\xb4\x00\x00\x00\x00\x00\x01\x00\x00\xe4\x33\ +\x00\x00\x27\x86\x00\x00\x00\x00\x00\x01\x00\x01\xef\xdb\ +\x00\x00\x06\x00\x00\x00\x00\x00\x00\x01\x00\x00\x56\xae\ +\x00\x00\x05\x82\x00\x00\x00\x00\x00\x01\x00\x00\x55\x3f\ +\x00\x00\x19\xbe\x00\x00\x00\x00\x00\x01\x00\x01\x54\x5c\ +\x00\x00\x10\x24\x00\x00\x00\x00\x00\x01\x00\x00\xda\x1f\ +\x00\x00\x21\x90\x00\x00\x00\x00\x00\x01\x00\x01\xa5\xba\ +\x00\x00\x1c\x4c\x00\x00\x00\x00\x00\x01\x00\x01\x67\xc0\ +\x00\x00\x19\x7a\x00\x00\x00\x00\x00\x01\x00\x01\x4b\x73\ +\x00\x00\x05\x44\x00\x00\x00\x00\x00\x01\x00\x00\x52\x7b\ +\x00\x00\x09\x6e\x00\x00\x00\x00\x00\x01\x00\x00\x83\x3b\ +\x00\x00\x2d\xb2\x00\x00\x00\x00\x00\x01\x00\x02\x26\xe6\ +\x00\x00\x24\xc2\x00\x00\x00\x00\x00\x01\x00\x01\xcb\xce\ +\x00\x00\x1d\x2a\x00\x00\x00\x00\x00\x01\x00\x01\x73\x06\ +\x00\x00\x06\x88\x00\x00\x00\x00\x00\x01\x00\x00\x5e\x2e\ +\x00\x00\x0d\x3c\x00\x00\x00\x00\x00\x01\x00\x00\xc0\xd9\ +\x00\x00\x20\xb0\x00\x00\x00\x00\x00\x01\x00\x01\x9f\xd7\ +\x00\x00\x04\xa6\x00\x00\x00\x00\x00\x01\x00\x00\x48\xc0\ +\x00\x00\x1f\x0a\x00\x00\x00\x00\x00\x01\x00\x01\x8b\xeb\ +\x00\x00\x22\x62\x00\x00\x00\x00\x00\x01\x00\x01\xaa\xcc\ +\x00\x00\x14\x00\x00\x00\x00\x00\x00\x01\x00\x01\x0a\xcd\ +\x00\x00\x03\x8a\x00\x00\x00\x00\x00\x01\x00\x00\x44\x0a\ +\x00\x00\x14\x4e\x00\x00\x00\x00\x00\x01\x00\x01\x0b\x6c\ +\x00\x00\x11\xee\x00\x00\x00\x00\x00\x01\x00\x00\xe8\xc1\ +\x00\x00\x1e\x52\x00\x00\x00\x00\x00\x01\x00\x01\x87\xf8\ +\x00\x00\x17\xd0\x00\x00\x00\x00\x00\x01\x00\x01\x37\x5c\ +\x00\x00\x09\x2a\x00\x00\x00\x00\x00\x01\x00\x00\x81\xe7\ +\x00\x00\x28\x9e\x00\x00\x00\x00\x00\x01\x00\x01\xf9\x30\ +\x00\x00\x27\xc4\x00\x00\x00\x00\x00\x01\x00\x01\xf3\xf4\ +\x00\x00\x1d\xb2\x00\x00\x00\x00\x00\x01\x00\x01\x78\x31\ +\x00\x00\x2d\xee\x00\x00\x00\x00\x00\x01\x00\x02\x27\x5f\ +\x00\x00\x16\xf2\x00\x00\x00\x00\x00\x01\x00\x01\x2f\x6e\ +\x00\x00\x1c\xa2\x00\x00\x00\x00\x00\x01\x00\x01\x6f\x8a\ +\x00\x00\x15\x72\x00\x00\x00\x00\x00\x01\x00\x01\x1a\xf8\ +\x00\x00\x13\xc6\x00\x00\x00\x00\x00\x01\x00\x01\x07\x9f\ +\x00\x00\x05\x10\x00\x00\x00\x00\x00\x01\x00\x00\x4e\x5a\ +\x00\x00\x1e\x8c\x00\x00\x00\x00\x00\x01\x00\x01\x88\xc9\ +\x00\x00\x17\x9a\x00\x00\x00\x00\x00\x01\x00\x01\x34\x70\ +\x00\x00\x1b\xc4\x00\x00\x00\x00\x00\x01\x00\x01\x64\xdd\ +\x00\x00\x11\x46\x00\x00\x00\x00\x00\x01\x00\x00\xe1\xd4\ +\x00\x00\x07\xae\x00\x00\x00\x00\x00\x01\x00\x00\x67\xb2\ +\x00\x00\x03\x2c\x00\x00\x00\x00\x00\x01\x00\x00\x35\x11\ +\x00\x00\x0e\xa4\x00\x00\x00\x00\x00\x01\x00\x00\xc8\x4d\ +\x00\x00\x19\xe6\x00\x00\x00\x00\x00\x01\x00\x01\x55\x2d\ +\x00\x00\x1a\x62\x00\x00\x00\x00\x00\x01\x00\x01\x5a\x91\ +\x00\x00\x0b\xb2\x00\x00\x00\x00\x00\x01\x00\x00\xa2\x57\ +\x00\x00\x0c\x42\x00\x00\x00\x00\x00\x01\x00\x00\xb0\x58\ +\x00\x00\x2a\xce\x00\x00\x00\x00\x00\x01\x00\x02\x13\x3d\ +\x00\x00\x15\xd0\x00\x00\x00\x00\x00\x01\x00\x01\x20\x5a\ +\x00\x00\x1b\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x66\x8b\ +\x00\x00\x1c\xcc\x00\x00\x00\x00\x00\x01\x00\x01\x70\x7c\ +\x00\x00\x13\x30\x00\x00\x00\x00\x00\x01\x00\x01\x02\x9f\ +\x00\x00\x09\x06\x00\x00\x00\x00\x00\x01\x00\x00\x81\x3d\ +\x00\x00\x1e\x1c\x00\x00\x00\x00\x00\x01\x00\x01\x83\x9c\ +\x00\x00\x25\x26\x00\x00\x00\x00\x00\x01\x00\x01\xce\x35\ +\x00\x00\x0e\xec\x00\x00\x00\x00\x00\x01\x00\x00\xc8\xeb\ +\x00\x00\x1b\x48\x00\x00\x00\x00\x00\x01\x00\x01\x61\x28\ +\x00\x00\x28\x68\x00\x00\x00\x00\x00\x01\x00\x01\xf8\x28\ +\x00\x00\x0a\x56\x00\x00\x00\x00\x00\x01\x00\x00\x8d\x02\ +\x00\x00\x12\x90\x00\x00\x00\x00\x00\x01\x00\x00\xf6\x83\ +\x00\x00\x1e\xc6\x00\x00\x00\x00\x00\x01\x00\x01\x8b\x5c\ +\x00\x00\x20\x48\x00\x00\x00\x00\x00\x01\x00\x01\x92\x17\ +\x00\x00\x2c\xa2\x00\x00\x00\x00\x00\x01\x00\x02\x1e\x6c\ +\x00\x00\x2e\xa6\x00\x00\x00\x00\x00\x01\x00\x02\x39\x3f\ +\x00\x00\x1b\x78\x00\x00\x00\x00\x00\x01\x00\x01\x62\xb8\ +\x00\x00\x15\x1e\x00\x00\x00\x00\x00\x01\x00\x01\x16\x5c\ +\x00\x00\x07\x3a\x00\x00\x00\x00\x00\x01\x00\x00\x63\xe4\ +\x00\x00\x21\x5e\x00\x00\x00\x00\x00\x01\x00\x01\xa4\x6f\ +\x00\x00\x19\x2e\x00\x00\x00\x00\x00\x01\x00\x01\x47\xcd\ +\x00\x00\x02\xc0\x00\x00\x00\x00\x00\x01\x00\x00\x33\xb8\ +\x00\x00\x27\x34\x00\x00\x00\x00\x00\x01\x00\x01\xeb\xec\ +\x00\x00\x2d\x1a\x00\x00\x00\x00\x00\x01\x00\x02\x23\xaf\ +\x00\x00\x04\x30\x00\x00\x00\x00\x00\x01\x00\x00\x45\xdc\ +\x00\x00\x28\xce\x00\x00\x00\x00\x00\x01\x00\x01\xfb\x51\ +\x00\x00\x05\xca\x00\x00\x00\x00\x00\x01\x00\x00\x56\x03\ +\x00\x00\x0b\x18\x00\x00\x00\x00\x00\x01\x00\x00\x96\xef\ +\x00\x00\x23\x7a\x00\x00\x00\x00\x00\x01\x00\x01\xbb\xb9\ +\x00\x00\x01\xda\x00\x00\x00\x00\x00\x01\x00\x00\x2c\x7b\ +\x00\x00\x13\x90\x00\x00\x00\x00\x00\x01\x00\x01\x05\x7a\ +\x00\x00\x15\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x23\x96\ +\x00\x00\x2c\xe2\x00\x00\x00\x00\x00\x01\x00\x02\x22\x0c\ +\x00\x00\x06\x5a\x00\x00\x00\x00\x00\x01\x00\x00\x5b\xa0\ +\x00\x00\x1f\xf8\x00\x00\x00\x00\x00\x01\x00\x01\x91\x3d\ +\x00\x00\x17\x5e\x00\x00\x00\x00\x00\x01\x00\x01\x31\x04\ +\x00\x00\x18\x0e\x00\x00\x00\x00\x00\x01\x00\x01\x3a\xe9\ +\x00\x00\x26\xf6\x00\x00\x00\x00\x00\x01\x00\x01\xea\x65\ +\x00\x00\x2e\x18\x00\x00\x00\x00\x00\x01\x00\x02\x2b\xca\ +\x00\x00\x16\x76\x00\x00\x00\x00\x00\x01\x00\x01\x2b\x29\ +\x00\x00\x07\x12\x00\x00\x00\x00\x00\x01\x00\x00\x5f\xdf\ +\x00\x00\x20\x72\x00\x00\x00\x00\x00\x01\x00\x01\x94\xdf\ +\x00\x00\x06\x2e\x00\x00\x00\x00\x00\x01\x00\x00\x57\xa8\ +\x00\x00\x2e\x70\x00\x00\x00\x00\x00\x01\x00\x02\x2c\x65\ +\x00\x00\x29\xa2\x00\x00\x00\x00\x00\x01\x00\x02\x04\xaf\ +\x00\x00\x0d\xe0\x00\x00\x00\x00\x00\x01\x00\x00\xc4\x8b\ +\x00\x00\x23\xb4\x00\x00\x00\x00\x00\x01\x00\x01\xbc\xc3\ +\x00\x00\x02\x44\x00\x00\x00\x00\x00\x01\x00\x00\x2f\xce\ +\x00\x00\x02\x84\x00\x00\x00\x00\x00\x01\x00\x00\x32\xad\ +\x00\x00\x1a\x28\x00\x00\x00\x00\x00\x01\x00\x01\x56\x61\ +\x00\x00\x24\xf2\x00\x00\x00\x00\x00\x01\x00\x01\xcc\x3a\ +\x00\x00\x24\x8a\x00\x00\x00\x00\x00\x01\x00\x01\xca\xfe\ +\x00\x00\x06\xba\x00\x00\x00\x00\x00\x01\x00\x00\x5e\xbb\ +\x00\x00\x08\x60\x00\x00\x00\x00\x00\x01\x00\x00\x72\x4a\ +\x00\x00\x01\xb2\x00\x00\x00\x00\x00\x01\x00\x00\x2a\x72\ +\x00\x00\x11\x6e\x00\x00\x00\x00\x00\x01\x00\x00\xe2\x5d\ +\x00\x00\x1f\xa0\x00\x00\x00\x00\x00\x01\x00\x01\x90\x75\ +\x00\x00\x08\xd6\x00\x00\x00\x00\x00\x01\x00\x00\x7f\xa1\ +\x00\x00\x18\x8a\x00\x00\x00\x00\x00\x01\x00\x01\x43\xc9\ +\x00\x00\x16\x3a\x00\x00\x00\x00\x00\x01\x00\x01\x24\x34\ +\x00\x00\x16\xc0\x00\x00\x00\x00\x00\x01\x00\x01\x2d\x33\ +\x00\x00\x23\xdc\x00\x00\x00\x00\x00\x01\x00\x01\xc1\x39\ +\x00\x00\x22\xea\x00\x00\x00\x00\x00\x01\x00\x01\xb1\x82\ +\x00\x00\x26\x86\x00\x00\x00\x00\x00\x01\x00\x01\xe5\x72\ +\x00\x00\x14\xec\x00\x00\x00\x00\x00\x01\x00\x01\x13\x80\ +\x00\x00\x0f\x4a\x00\x00\x00\x00\x00\x01\x00\x00\xce\xcb\ +\x00\x00\x22\xa6\x00\x00\x00\x00\x00\x01\x00\x01\xaf\xf7\ +\x00\x00\x26\x22\x00\x00\x00\x00\x00\x01\x00\x01\xd8\x81\ +\x00\x00\x0f\x22\x00\x00\x00\x00\x00\x01\x00\x00\xc9\xdd\ +\x00\x00\x1d\x76\x00\x00\x00\x00\x00\x01\x00\x01\x74\x2a\ +\x00\x00\x21\x30\x00\x00\x00\x00\x00\x01\x00\x01\xa2\x41\ +\x00\x00\x14\xbe\x00\x00\x00\x00\x00\x01\x00\x01\x11\x55\ +\x00\x00\x08\x26\x00\x00\x00\x00\x00\x01\x00\x00\x6e\xe4\ +\x00\x00\x21\xca\x00\x00\x00\x00\x00\x01\x00\x01\xa6\xad\ +\x00\x00\x23\x22\x00\x00\x00\x00\x00\x01\x00\x01\xb4\xd4\ +\x00\x00\x0f\xec\x00\x00\x00\x00\x00\x01\x00\x00\xd6\x48\ +\x00\x00\x1c\x82\x00\x00\x00\x00\x00\x01\x00\x01\x6a\x9e\ +\x00\x00\x18\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x47\x43\ +\x00\x00\x2b\x6e\x00\x00\x00\x00\x00\x01\x00\x02\x15\x4a\ +\x00\x00\x2c\x6e\x00\x00\x00\x00\x00\x01\x00\x02\x1d\xc7\ +\x00\x00\x2d\x60\x00\x00\x00\x00\x00\x01\x00\x02\x24\x4a\ +\x00\x00\x2d\x94\x00\x00\x00\x00\x00\x01\x00\x02\x24\xd5\ +\x00\x00\x26\xce\x00\x00\x00\x00\x00\x01\x00\x01\xe8\xd4\ +\x00\x00\x11\x0a\x00\x00\x00\x00\x00\x01\x00\x00\xe0\xfe\ +\x00\x00\x29\x6e\x00\x00\x00\x00\x00\x01\x00\x01\xff\xc4\ +\x00\x00\x00\xf2\x00\x00\x00\x00\x00\x01\x00\x00\x1f\x99\ +\x00\x00\x10\x96\x00\x00\x00\x00\x00\x01\x00\x00\xdb\x7f\ +\x00\x00\x0e\x6c\x00\x00\x00\x00\x00\x01\x00\x00\xc7\xd2\ +\x00\x00\x25\x4a\x00\x00\x00\x00\x00\x01\x00\x01\xcf\xcd\ +\x00\x00\x0f\xbc\x00\x00\x00\x00\x00\x01\x00\x00\xd4\x1f\ +\x00\x00\x0b\xe4\x00\x00\x00\x00\x00\x01\x00\x00\xaf\x31\ +\x00\x00\x09\xa8\x00\x00\x00\x00\x00\x01\x00\x00\x87\xb4\ +\x00\x00\x08\x9e\x00\x00\x00\x00\x00\x01\x00\x00\x72\xc7\ +\x00\x00\x17\x1c\x00\x00\x00\x00\x00\x01\x00\x01\x30\x76\ +\x00\x00\x0a\xde\x00\x00\x00\x00\x00\x01\x00\x00\x95\xf5\ +\x00\x00\x12\x6c\x00\x00\x00\x00\x00\x01\x00\x00\xf6\x17\ +\x00\x00\x02\xf8\x00\x00\x00\x00\x00\x01\x00\x00\x34\x42\ +\x00\x00\x22\x0e\x00\x00\x00\x00\x00\x01\x00\x01\xaa\x03\ +\x00\x00\x1a\x8e\x00\x00\x00\x00\x00\x01\x00\x01\x5b\x5d\ +\x00\x00\x0e\x02\x00\x00\x00\x00\x00\x01\x00\x00\xc6\xbd\ +\x00\x00\x00\x9e\x00\x00\x00\x00\x00\x01\x00\x00\x1f\x0d\ +\x00\x00\x18\xc4\x00\x00\x00\x00\x00\x01\x00\x01\x46\xb8\ +\x00\x00\x24\x0a\x00\x00\x00\x00\x00\x01\x00\x01\xc4\x9e\ +\x00\x00\x04\x72\x00\x00\x00\x00\x00\x01\x00\x00\x47\x31\ +\x00\x00\x2a\xa4\x00\x00\x00\x00\x00\x01\x00\x02\x11\x25\ +\x00\x00\x2a\x38\x00\x00\x00\x00\x00\x01\x00\x02\x0a\x43\ +\x00\x00\x02\x10\x00\x00\x00\x00\x00\x01\x00\x00\x2e\x25\ +\x00\x00\x20\xfc\x00\x00\x00\x00\x00\x01\x00\x01\xa0\x76\ +\x00\x00\x12\x30\x00\x00\x00\x00\x00\x01\x00\x00\xf1\x9c\ +\x00\x00\x0a\x20\x00\x00\x00\x00\x00\x01\x00\x00\x88\xcc\ +\x00\x00\x04\xdc\x00\x00\x00\x00\x00\x01\x00\x00\x4a\x76\ +\x00\x00\x12\xf8\x00\x00\x00\x00\x00\x01\x00\x01\x02\x0e\ +\x00\x00\x10\x60\x00\x00\x00\x00\x00\x01\x00\x00\xdb\x13\ +\x00\x00\x07\x6e\x00\x00\x00\x00\x00\x01\x00\x00\x64\x50\ +\x00\x00\x03\xdc\x00\x00\x00\x00\x00\x01\x00\x00\x44\xa3\ +\x00\x00\x1d\xe4\x00\x00\x00\x00\x00\x01\x00\x01\x7d\x1d\ +\x00\x00\x24\x50\x00\x00\x00\x00\x00\x01\x00\x01\xc5\xc2\ +\x00\x00\x10\xc2\x00\x00\x00\x00\x00\x01\x00\x00\xe0\x6b\ +\x00\x00\x00\x6a\x00\x00\x00\x00\x00\x01\x00\x00\x1a\xaa\ +\x00\x00\x01\x6c\x00\x00\x00\x00\x00\x01\x00\x00\x25\x38\ +\x00\x00\x15\x9c\x00\x00\x00\x00\x00\x01\x00\x01\x1e\x29\ +\x00\x00\x0c\x90\x00\x00\x00\x00\x00\x01\x00\x00\xb0\xe3\ +\x00\x00\x29\x4a\x00\x00\x00\x00\x00\x01\x00\x01\xfd\x9e\ +\x00\x00\x2b\xda\x00\x00\x00\x00\x00\x01\x00\x02\x1b\xa2\ +\x00\x00\x0d\x70\x00\x00\x00\x00\x00\x01\x00\x00\xc3\x1b\ +\x00\x00\x0b\x78\x00\x00\x00\x00\x00\x01\x00\x00\x97\xf3\ +\x00\x00\x29\xe2\x00\x00\x00\x00\x00\x01\x00\x02\x09\xa8\ +\x00\x00\x1c\xee\x00\x00\x00\x00\x00\x01\x00\x01\x72\x8a\ +\x00\x00\x0f\x84\x00\x00\x00\x00\x00\x01\x00\x00\xd0\xe7\ +\x00\x00\x12\xc6\x00\x00\x00\x00\x00\x01\x00\x00\xf9\x9e\ +\x00\x00\x25\x82\x00\x00\x00\x00\x00\x01\x00\x01\xd4\x54\ +\x00\x00\x1f\x66\x00\x00\x00\x00\x00\x01\x00\x01\x8d\x15\ +\x00\x00\x14\x8e\x00\x00\x00\x00\x00\x01\x00\x01\x0c\x69\ +\x00\x00\x28\x0e\x00\x00\x00\x00\x00\x01\x00\x01\xf7\x5c\ +\x00\x00\x0d\xa2\x00\x00\x00\x00\x00\x01\x00\x00\xc3\xb7\ +\x00\x00\x0e\x36\x00\x00\x00\x00\x00\x01\x00\x00\xc7\x59\ +\x00\x00\x2b\x1c\x00\x00\x00\x00\x00\x01\x00\x02\x14\x12\ +\x00\x00\x2b\xa6\x00\x00\x00\x00\x00\x01\x00\x02\x19\x7c\ +\x00\x00\x00\x32\x00\x02\x00\x00\x00\x01\x00\x00\x00\xd6\ +\x00\x00\x00\x40\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\ +" + +qt_resource_struct_v2 = b"\ +\x00\x00\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x01\ +\x00\x00\x00\x00\x00\x00\x00\x00\ +\x00\x00\x00\x18\x00\x02\x00\x00\x00\x01\x00\x00\x00\xd5\ +\x00\x00\x00\x00\x00\x00\x00\x00\ +\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\ +\x00\x00\x00\x00\x00\x00\x00\x00\ +\x00\x00\x00\x32\x00\x02\x00\x00\x00\x01\x00\x00\x00\x04\ +\x00\x00\x00\x00\x00\x00\x00\x00\ +\x00\x00\x00\x60\x00\x02\x00\x00\x00\xd0\x00\x00\x00\x05\ +\x00\x00\x00\x00\x00\x00\x00\x00\ +\x00\x00\x18\x4c\x00\x00\x00\x00\x00\x01\x00\x01\x3b\x76\ +\x00\x00\x01\x81\x15\x91\x87\xb0\ +\x00\x00\x07\xe8\x00\x00\x00\x00\x00\x01\x00\x00\x68\x2b\ +\x00\x00\x01\x81\x15\x91\x88\x41\ +\x00\x00\x0d\x0e\x00\x00\x00\x00\x00\x01\x00\x00\xb6\x47\ +\x00\x00\x01\x81\x15\x91\x87\x94\ +\x00\x00\x25\xea\x00\x00\x00\x00\x00\x01\x00\x01\xd7\xaf\ +\x00\x00\x01\x81\x15\x91\x86\x7f\ +\x00\x00\x13\x62\x00\x00\x00\x00\x00\x01\x00\x01\x04\xe1\ +\x00\x00\x01\x81\x15\x91\x84\xf5\ +\x00\x00\x03\x52\x00\x00\x00\x00\x00\x01\x00\x00\x41\xeb\ +\x00\x00\x01\x81\x15\x91\x86\x9e\ +\x00\x00\x2c\x2c\x00\x00\x00\x00\x00\x01\x00\x02\x1c\x30\ +\x00\x00\x01\x81\x15\x91\x85\x87\ +\x00\x00\x25\xc4\x00\x00\x00\x00\x00\x01\x00\x01\xd4\xe1\ +\x00\x00\x01\x81\x15\x91\x86\x4c\ +\x00\x00\x0b\x4e\x00\x00\x00\x00\x00\x01\x00\x00\x97\x7a\ +\x00\x00\x01\x81\x15\x91\x88\x2e\ +\x00\x00\x09\xec\x00\x00\x00\x00\x00\x01\x00\x00\x88\x43\ +\x00\x00\x01\x81\x15\x91\x85\xba\ +\x00\x00\x26\x62\x00\x00\x00\x00\x00\x01\x00\x01\xe3\xbc\ +\x00\x00\x01\x81\x15\x91\x86\x5c\ +\x00\x00\x1a\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x60\x51\ +\x00\x00\x01\x81\x15\x91\x87\xe7\ +\x00\x00\x2a\x68\x00\x00\x00\x00\x00\x01\x00\x02\x0e\x25\ +\x00\x00\x01\x81\x15\x91\x88\x51\ +\x00\x00\x23\x4e\x00\x00\x00\x00\x00\x01\x00\x01\xb5\x50\ +\x00\x00\x01\x81\x15\x91\x88\x3d\ +\x00\x00\x24\x2c\x00\x00\x00\x00\x00\x01\x00\x01\xc5\x39\ +\x00\x00\x01\x81\x15\x91\x85\x07\ +\x00\x00\x2e\xd4\x00\x00\x00\x00\x00\x01\x00\x02\x3b\x4e\ +\x00\x00\x01\x81\x15\x91\x86\x7c\ +\x00\x00\x0a\xa6\x00\x00\x00\x00\x00\x01\x00\x00\x90\xe9\ +\x00\x00\x01\x81\x15\x91\x85\xd5\ +\x00\x00\x29\x0c\x00\x00\x00\x00\x00\x01\x00\x01\xfc\x4d\ +\x00\x00\x01\x81\x15\x91\x88\x67\ +\x00\x00\x15\x4e\x00\x00\x00\x00\x00\x01\x00\x01\x17\x04\ +\x00\x00\x01\x81\x15\x91\x86\xbe\ +\x00\x00\x0c\xc4\x00\x00\x00\x00\x00\x01\x00\x00\xb5\xb7\ +\x00\x00\x01\x81\x15\x91\x86\x10\ +\x00\x00\x1a\xcc\x00\x00\x00\x00\x00\x01\x00\x01\x5e\xc4\ +\x00\x00\x01\x81\x15\x91\x85\x6a\ +\x00\x00\x01\x32\x00\x00\x00\x00\x00\x01\x00\x00\x23\x58\ +\x00\x00\x01\x81\x15\x91\x85\x54\ +\x00\x00\x11\xb4\x00\x00\x00\x00\x00\x01\x00\x00\xe4\x33\ +\x00\x00\x01\x81\x15\x91\x86\xbe\ +\x00\x00\x27\x86\x00\x00\x00\x00\x00\x01\x00\x01\xef\xdb\ +\x00\x00\x01\x81\x15\x91\x85\xda\ +\x00\x00\x06\x00\x00\x00\x00\x00\x00\x01\x00\x00\x56\xae\ +\x00\x00\x01\x81\x15\x91\x87\x84\ +\x00\x00\x05\x82\x00\x00\x00\x00\x00\x01\x00\x00\x55\x3f\ +\x00\x00\x01\x81\x15\x91\x88\x17\ +\x00\x00\x19\xbe\x00\x00\x00\x00\x00\x01\x00\x01\x54\x5c\ +\x00\x00\x01\x81\x15\x91\x86\xec\ +\x00\x00\x10\x24\x00\x00\x00\x00\x00\x01\x00\x00\xda\x1f\ +\x00\x00\x01\x81\x15\x91\x86\xfc\ +\x00\x00\x21\x90\x00\x00\x00\x00\x00\x01\x00\x01\xa5\xba\ +\x00\x00\x01\x81\x15\x91\x87\x0c\ +\x00\x00\x1c\x4c\x00\x00\x00\x00\x00\x01\x00\x01\x67\xc0\ +\x00\x00\x01\x81\x15\x91\x88\x57\ +\x00\x00\x19\x7a\x00\x00\x00\x00\x00\x01\x00\x01\x4b\x73\ +\x00\x00\x01\x81\x15\x91\x87\xaa\ +\x00\x00\x05\x44\x00\x00\x00\x00\x00\x01\x00\x00\x52\x7b\ +\x00\x00\x01\x81\x15\x91\x85\x54\ +\x00\x00\x09\x6e\x00\x00\x00\x00\x00\x01\x00\x00\x83\x3b\ +\x00\x00\x01\x81\x15\x91\x86\xae\ +\x00\x00\x2d\xb2\x00\x00\x00\x00\x00\x01\x00\x02\x26\xe6\ +\x00\x00\x01\x81\x15\x91\x88\x33\ +\x00\x00\x24\xc2\x00\x00\x00\x00\x00\x01\x00\x01\xcb\xce\ +\x00\x00\x01\x81\x15\x91\x86\x4c\ +\x00\x00\x1d\x2a\x00\x00\x00\x00\x00\x01\x00\x01\x73\x06\ +\x00\x00\x01\x81\x15\x91\x87\xfb\ +\x00\x00\x06\x88\x00\x00\x00\x00\x00\x01\x00\x00\x5e\x2e\ +\x00\x00\x01\x81\x15\x91\x87\x75\ +\x00\x00\x0d\x3c\x00\x00\x00\x00\x00\x01\x00\x00\xc0\xd9\ +\x00\x00\x01\x81\x15\x91\x84\x9c\ +\x00\x00\x20\xb0\x00\x00\x00\x00\x00\x01\x00\x01\x9f\xd7\ +\x00\x00\x01\x81\x15\x91\x85\xf9\ +\x00\x00\x04\xa6\x00\x00\x00\x00\x00\x01\x00\x00\x48\xc0\ +\x00\x00\x01\x81\x15\x91\x86\x5c\ +\x00\x00\x1f\x0a\x00\x00\x00\x00\x00\x01\x00\x01\x8b\xeb\ +\x00\x00\x01\x81\x15\x91\x88\x13\ +\x00\x00\x22\x62\x00\x00\x00\x00\x00\x01\x00\x01\xaa\xcc\ +\x00\x00\x01\x81\x15\x91\x87\x4e\ +\x00\x00\x14\x00\x00\x00\x00\x00\x00\x01\x00\x01\x0a\xcd\ +\x00\x00\x01\x81\x15\x91\x85\xf9\ +\x00\x00\x03\x8a\x00\x00\x00\x00\x00\x01\x00\x00\x44\x0a\ +\x00\x00\x01\x81\x15\x91\x86\x2b\ +\x00\x00\x14\x4e\x00\x00\x00\x00\x00\x01\x00\x01\x0b\x6c\ +\x00\x00\x01\x81\x15\x91\x87\x88\ +\x00\x00\x11\xee\x00\x00\x00\x00\x00\x01\x00\x00\xe8\xc1\ +\x00\x00\x01\x81\x15\x91\x87\xb5\ +\x00\x00\x1e\x52\x00\x00\x00\x00\x00\x01\x00\x01\x87\xf8\ +\x00\x00\x01\x81\x15\x91\x86\xec\ +\x00\x00\x17\xd0\x00\x00\x00\x00\x00\x01\x00\x01\x37\x5c\ +\x00\x00\x01\x81\x15\x91\x88\x7c\ +\x00\x00\x09\x2a\x00\x00\x00\x00\x00\x01\x00\x00\x81\xe7\ +\x00\x00\x01\x81\x15\x91\x88\x62\ +\x00\x00\x28\x9e\x00\x00\x00\x00\x00\x01\x00\x01\xf9\x30\ +\x00\x00\x01\x81\x15\x91\x84\x9c\ +\x00\x00\x27\xc4\x00\x00\x00\x00\x00\x01\x00\x01\xf3\xf4\ +\x00\x00\x01\x81\x15\x91\x87\x69\ +\x00\x00\x1d\xb2\x00\x00\x00\x00\x00\x01\x00\x01\x78\x31\ +\x00\x00\x01\x81\x15\x91\x84\xbb\ +\x00\x00\x2d\xee\x00\x00\x00\x00\x00\x01\x00\x02\x27\x5f\ +\x00\x00\x01\x81\x15\x91\x86\xae\ +\x00\x00\x16\xf2\x00\x00\x00\x00\x00\x01\x00\x01\x2f\x6e\ +\x00\x00\x01\x81\x15\x91\x87\x0c\ +\x00\x00\x1c\xa2\x00\x00\x00\x00\x00\x01\x00\x01\x6f\x8a\ +\x00\x00\x01\x81\x15\x91\x86\xfc\ +\x00\x00\x15\x72\x00\x00\x00\x00\x00\x01\x00\x01\x1a\xf8\ +\x00\x00\x01\x81\x15\x91\x87\x0c\ +\x00\x00\x13\xc6\x00\x00\x00\x00\x00\x01\x00\x01\x07\x9f\ +\x00\x00\x01\x81\x15\x91\x86\xec\ +\x00\x00\x05\x10\x00\x00\x00\x00\x00\x01\x00\x00\x4e\x5a\ +\x00\x00\x01\x81\x15\x91\x86\xcd\ +\x00\x00\x1e\x8c\x00\x00\x00\x00\x00\x01\x00\x01\x88\xc9\ +\x00\x00\x01\x81\x15\x91\x85\x52\ +\x00\x00\x17\x9a\x00\x00\x00\x00\x00\x01\x00\x01\x34\x70\ +\x00\x00\x01\x81\x15\x91\x86\x5c\ +\x00\x00\x1b\xc4\x00\x00\x00\x00\x00\x01\x00\x01\x64\xdd\ +\x00\x00\x01\x81\x15\x91\x84\xcb\ +\x00\x00\x11\x46\x00\x00\x00\x00\x00\x01\x00\x00\xe1\xd4\ +\x00\x00\x01\x81\x15\x91\x85\xa9\ +\x00\x00\x07\xae\x00\x00\x00\x00\x00\x01\x00\x00\x67\xb2\ +\x00\x00\x01\x81\x15\x91\x88\x39\ +\x00\x00\x03\x2c\x00\x00\x00\x00\x00\x01\x00\x00\x35\x11\ +\x00\x00\x01\x81\x15\x91\x86\xcd\ +\x00\x00\x0e\xa4\x00\x00\x00\x00\x00\x01\x00\x00\xc8\x4d\ +\x00\x00\x01\x81\x15\x91\x85\xf9\ +\x00\x00\x19\xe6\x00\x00\x00\x00\x00\x01\x00\x01\x55\x2d\ +\x00\x00\x01\x81\x15\x91\x87\xc3\ +\x00\x00\x1a\x62\x00\x00\x00\x00\x00\x01\x00\x01\x5a\x91\ +\x00\x00\x01\x81\x15\x91\x86\x6b\ +\x00\x00\x0b\xb2\x00\x00\x00\x00\x00\x01\x00\x00\xa2\x57\ +\x00\x00\x01\x81\x15\x91\x86\xdd\ +\x00\x00\x0c\x42\x00\x00\x00\x00\x00\x01\x00\x00\xb0\x58\ +\x00\x00\x01\x81\x15\x91\x86\x3d\ +\x00\x00\x2a\xce\x00\x00\x00\x00\x00\x01\x00\x02\x13\x3d\ +\x00\x00\x01\x81\x15\x91\x87\xec\ +\x00\x00\x15\xd0\x00\x00\x00\x00\x00\x01\x00\x01\x20\x5a\ +\x00\x00\x01\x81\x15\x91\x86\xdd\ +\x00\x00\x1b\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x66\x8b\ +\x00\x00\x01\x81\x15\x91\x87\xd5\ +\x00\x00\x1c\xcc\x00\x00\x00\x00\x00\x01\x00\x01\x70\x7c\ +\x00\x00\x01\x81\x15\x91\x84\x48\ +\x00\x00\x13\x30\x00\x00\x00\x00\x00\x01\x00\x01\x02\x9f\ +\x00\x00\x01\x81\x15\x91\x84\x87\ +\x00\x00\x09\x06\x00\x00\x00\x00\x00\x01\x00\x00\x81\x3d\ +\x00\x00\x01\x81\x15\x91\x85\x1a\ +\x00\x00\x1e\x1c\x00\x00\x00\x00\x00\x01\x00\x01\x83\x9c\ +\x00\x00\x01\x81\x15\x91\x86\xbe\ +\x00\x00\x25\x26\x00\x00\x00\x00\x00\x01\x00\x01\xce\x35\ +\x00\x00\x01\x81\x15\x91\x85\x2e\ +\x00\x00\x0e\xec\x00\x00\x00\x00\x00\x01\x00\x00\xc8\xeb\ +\x00\x00\x01\x81\x15\x91\x86\xfc\ +\x00\x00\x1b\x48\x00\x00\x00\x00\x00\x01\x00\x01\x61\x28\ +\x00\x00\x01\x81\x15\x91\x85\x34\ +\x00\x00\x28\x68\x00\x00\x00\x00\x00\x01\x00\x01\xf8\x28\ +\x00\x00\x01\x81\x15\x91\x87\x0c\ +\x00\x00\x0a\x56\x00\x00\x00\x00\x00\x01\x00\x00\x8d\x02\ +\x00\x00\x01\x81\x15\x91\x87\x61\ +\x00\x00\x12\x90\x00\x00\x00\x00\x00\x01\x00\x00\xf6\x83\ +\x00\x00\x01\x81\x15\x91\x87\x23\ +\x00\x00\x1e\xc6\x00\x00\x00\x00\x00\x01\x00\x01\x8b\x5c\ +\x00\x00\x01\x81\x15\x91\x86\x13\ +\x00\x00\x20\x48\x00\x00\x00\x00\x00\x01\x00\x01\x92\x17\ +\x00\x00\x01\x81\x15\x91\x88\x4e\ +\x00\x00\x2c\xa2\x00\x00\x00\x00\x00\x01\x00\x02\x1e\x6c\ +\x00\x00\x01\x81\x15\x91\x88\x75\ +\x00\x00\x2e\xa6\x00\x00\x00\x00\x00\x01\x00\x02\x39\x3f\ +\x00\x00\x01\x81\x15\x91\x84\x65\ +\x00\x00\x1b\x78\x00\x00\x00\x00\x00\x01\x00\x01\x62\xb8\ +\x00\x00\x01\x81\x15\x91\x85\x54\ +\x00\x00\x15\x1e\x00\x00\x00\x00\x00\x01\x00\x01\x16\x5c\ +\x00\x00\x01\x81\x15\x91\x85\x27\ +\x00\x00\x07\x3a\x00\x00\x00\x00\x00\x01\x00\x00\x63\xe4\ +\x00\x00\x01\x81\x15\x91\x86\x4c\ +\x00\x00\x21\x5e\x00\x00\x00\x00\x00\x01\x00\x01\xa4\x6f\ +\x00\x00\x01\x81\x15\x91\x88\x5e\ +\x00\x00\x19\x2e\x00\x00\x00\x00\x00\x01\x00\x01\x47\xcd\ +\x00\x00\x01\x81\x15\x91\x87\x5d\ +\x00\x00\x02\xc0\x00\x00\x00\x00\x00\x01\x00\x00\x33\xb8\ +\x00\x00\x01\x81\x15\x91\x85\xbd\ +\x00\x00\x27\x34\x00\x00\x00\x00\x00\x01\x00\x01\xeb\xec\ +\x00\x00\x01\x81\x15\x91\x87\x58\ +\x00\x00\x2d\x1a\x00\x00\x00\x00\x00\x01\x00\x02\x23\xaf\ +\x00\x00\x01\x81\x15\x91\x86\x1f\ +\x00\x00\x04\x30\x00\x00\x00\x00\x00\x01\x00\x00\x45\xdc\ +\x00\x00\x01\x81\x15\x91\x88\x6b\ +\x00\x00\x28\xce\x00\x00\x00\x00\x00\x01\x00\x01\xfb\x51\ +\x00\x00\x01\x81\x15\x91\x87\x90\ +\x00\x00\x05\xca\x00\x00\x00\x00\x00\x01\x00\x00\x56\x03\ +\x00\x00\x01\x81\x15\x91\x85\x1d\ +\x00\x00\x0b\x18\x00\x00\x00\x00\x00\x01\x00\x00\x96\xef\ +\x00\x00\x01\x81\x15\x91\x85\x0a\ +\x00\x00\x23\x7a\x00\x00\x00\x00\x00\x01\x00\x01\xbb\xb9\ +\x00\x00\x01\x81\x15\x91\x87\x0c\ +\x00\x00\x01\xda\x00\x00\x00\x00\x00\x01\x00\x00\x2c\x7b\ +\x00\x00\x01\x81\x15\x91\x85\x31\ +\x00\x00\x13\x90\x00\x00\x00\x00\x00\x01\x00\x01\x05\x7a\ +\x00\x00\x01\x81\x15\x91\x84\x8c\ +\x00\x00\x15\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x23\x96\ +\x00\x00\x01\x81\x15\x91\x85\xe9\ +\x00\x00\x2c\xe2\x00\x00\x00\x00\x00\x01\x00\x02\x22\x0c\ +\x00\x00\x01\x81\x15\x91\x84\xdb\ +\x00\x00\x06\x5a\x00\x00\x00\x00\x00\x01\x00\x00\x5b\xa0\ +\x00\x00\x01\x81\x15\x91\x85\x46\ +\x00\x00\x1f\xf8\x00\x00\x00\x00\x00\x01\x00\x01\x91\x3d\ +\x00\x00\x01\x81\x15\x91\x87\xe3\ +\x00\x00\x17\x5e\x00\x00\x00\x00\x00\x01\x00\x01\x31\x04\ +\x00\x00\x01\x81\x15\x91\x87\x1b\ +\x00\x00\x18\x0e\x00\x00\x00\x00\x00\x01\x00\x01\x3a\xe9\ +\x00\x00\x01\x81\x15\x91\x87\x7d\ +\x00\x00\x26\xf6\x00\x00\x00\x00\x00\x01\x00\x01\xea\x65\ +\x00\x00\x01\x81\x15\x91\x85\x7d\ +\x00\x00\x2e\x18\x00\x00\x00\x00\x00\x01\x00\x02\x2b\xca\ +\x00\x00\x01\x81\x15\x91\x86\x28\ +\x00\x00\x16\x76\x00\x00\x00\x00\x00\x01\x00\x01\x2b\x29\ +\x00\x00\x01\x81\x15\x91\x85\x54\ +\x00\x00\x07\x12\x00\x00\x00\x00\x00\x01\x00\x00\x5f\xdf\ +\x00\x00\x01\x81\x15\x91\x86\x9e\ +\x00\x00\x20\x72\x00\x00\x00\x00\x00\x01\x00\x01\x94\xdf\ +\x00\x00\x01\x81\x15\x91\x87\xa3\ +\x00\x00\x06\x2e\x00\x00\x00\x00\x00\x01\x00\x00\x57\xa8\ +\x00\x00\x01\x81\x15\x91\x85\xda\ +\x00\x00\x2e\x70\x00\x00\x00\x00\x00\x01\x00\x02\x2c\x65\ +\x00\x00\x01\x81\x15\x91\x86\xdd\ +\x00\x00\x29\xa2\x00\x00\x00\x00\x00\x01\x00\x02\x04\xaf\ +\x00\x00\x01\x81\x15\x91\x87\x48\ +\x00\x00\x0d\xe0\x00\x00\x00\x00\x00\x01\x00\x00\xc4\x8b\ +\x00\x00\x01\x81\x15\x91\x84\x7c\ +\x00\x00\x23\xb4\x00\x00\x00\x00\x00\x01\x00\x01\xbc\xc3\ +\x00\x00\x01\x81\x15\x91\x86\xae\ +\x00\x00\x02\x44\x00\x00\x00\x00\x00\x01\x00\x00\x2f\xce\ +\x00\x00\x01\x81\x15\x91\x85\x4f\ +\x00\x00\x02\x84\x00\x00\x00\x00\x00\x01\x00\x00\x32\xad\ +\x00\x00\x01\x81\x15\x91\x87\x0c\ +\x00\x00\x1a\x28\x00\x00\x00\x00\x00\x01\x00\x01\x56\x61\ +\x00\x00\x01\x81\x15\x91\x86\x9e\ +\x00\x00\x24\xf2\x00\x00\x00\x00\x00\x01\x00\x01\xcc\x3a\ +\x00\x00\x01\x81\x15\x91\x86\x8f\ +\x00\x00\x24\x8a\x00\x00\x00\x00\x00\x01\x00\x01\xca\xfe\ +\x00\x00\x01\x81\x15\x91\x86\xfc\ +\x00\x00\x06\xba\x00\x00\x00\x00\x00\x01\x00\x00\x5e\xbb\ +\x00\x00\x01\x81\x15\x91\x88\x0d\ +\x00\x00\x08\x60\x00\x00\x00\x00\x00\x01\x00\x00\x72\x4a\ +\x00\x00\x01\x81\x15\x91\x85\x93\ +\x00\x00\x01\xb2\x00\x00\x00\x00\x00\x01\x00\x00\x2a\x72\ +\x00\x00\x01\x81\x15\x91\x86\x7f\ +\x00\x00\x11\x6e\x00\x00\x00\x00\x00\x01\x00\x00\xe2\x5d\ +\x00\x00\x01\x81\x15\x91\x85\x54\ +\x00\x00\x1f\xa0\x00\x00\x00\x00\x00\x01\x00\x01\x90\x75\ +\x00\x00\x01\x81\x15\x91\x88\x2b\ +\x00\x00\x08\xd6\x00\x00\x00\x00\x00\x01\x00\x00\x7f\xa1\ +\x00\x00\x01\x81\x15\x91\x86\x6b\ +\x00\x00\x18\x8a\x00\x00\x00\x00\x00\x01\x00\x01\x43\xc9\ +\x00\x00\x01\x81\x15\x91\x88\x5b\ +\x00\x00\x16\x3a\x00\x00\x00\x00\x00\x01\x00\x01\x24\x34\ +\x00\x00\x01\x81\x15\x91\x88\x4a\ +\x00\x00\x16\xc0\x00\x00\x00\x00\x00\x01\x00\x01\x2d\x33\ +\x00\x00\x01\x81\x15\x91\x84\x72\ +\x00\x00\x23\xdc\x00\x00\x00\x00\x00\x01\x00\x01\xc1\x39\ +\x00\x00\x01\x81\x15\x91\x88\x70\ +\x00\x00\x22\xea\x00\x00\x00\x00\x00\x01\x00\x01\xb1\x82\ +\x00\x00\x01\x81\x15\x91\x87\x66\ +\x00\x00\x26\x86\x00\x00\x00\x00\x00\x01\x00\x01\xe5\x72\ +\x00\x00\x01\x81\x15\x91\x87\x72\ +\x00\x00\x14\xec\x00\x00\x00\x00\x00\x01\x00\x01\x13\x80\ +\x00\x00\x01\x81\x15\x91\x86\x5c\ +\x00\x00\x0f\x4a\x00\x00\x00\x00\x00\x01\x00\x00\xce\xcb\ +\x00\x00\x01\x81\x15\x91\x86\x8f\ +\x00\x00\x22\xa6\x00\x00\x00\x00\x00\x01\x00\x01\xaf\xf7\ +\x00\x00\x01\x81\x15\x91\x85\x74\ +\x00\x00\x26\x22\x00\x00\x00\x00\x00\x01\x00\x01\xd8\x81\ +\x00\x00\x01\x81\x15\x91\x87\x99\ +\x00\x00\x0f\x22\x00\x00\x00\x00\x00\x01\x00\x00\xc9\xdd\ +\x00\x00\x01\x81\x15\x91\x85\xc6\ +\x00\x00\x1d\x76\x00\x00\x00\x00\x00\x01\x00\x01\x74\x2a\ +\x00\x00\x01\x81\x15\x91\x85\xe9\ +\x00\x00\x21\x30\x00\x00\x00\x00\x00\x01\x00\x01\xa2\x41\ +\x00\x00\x01\x81\x15\x91\x84\xac\ +\x00\x00\x14\xbe\x00\x00\x00\x00\x00\x01\x00\x01\x11\x55\ +\x00\x00\x01\x81\x15\x91\x84\x84\ +\x00\x00\x08\x26\x00\x00\x00\x00\x00\x01\x00\x00\x6e\xe4\ +\x00\x00\x01\x81\x15\x91\x88\x79\ +\x00\x00\x21\xca\x00\x00\x00\x00\x00\x01\x00\x01\xa6\xad\ +\x00\x00\x01\x81\x15\x91\x87\x6e\ +\x00\x00\x23\x22\x00\x00\x00\x00\x00\x01\x00\x01\xb4\xd4\ +\x00\x00\x01\x81\x15\x91\x85\x8b\ +\x00\x00\x0f\xec\x00\x00\x00\x00\x00\x01\x00\x00\xd6\x48\ +\x00\x00\x01\x81\x15\x91\x85\xda\ +\x00\x00\x1c\x82\x00\x00\x00\x00\x00\x01\x00\x01\x6a\x9e\ +\x00\x00\x01\x81\x15\x91\x84\xac\ +\x00\x00\x18\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x47\x43\ +\x00\x00\x01\x81\x15\x91\x85\x0d\ +\x00\x00\x2b\x6e\x00\x00\x00\x00\x00\x01\x00\x02\x15\x4a\ +\x00\x00\x01\x81\x15\x91\x86\x9e\ +\x00\x00\x2c\x6e\x00\x00\x00\x00\x00\x01\x00\x02\x1d\xc7\ +\x00\x00\x01\x81\x15\x91\x85\x2a\ +\x00\x00\x2d\x60\x00\x00\x00\x00\x00\x01\x00\x02\x24\x4a\ +\x00\x00\x01\x81\x15\x91\x85\x17\ +\x00\x00\x2d\x94\x00\x00\x00\x00\x00\x01\x00\x02\x24\xd5\ +\x00\x00\x01\x81\x15\x91\x84\x9c\ +\x00\x00\x26\xce\x00\x00\x00\x00\x00\x01\x00\x01\xe8\xd4\ +\x00\x00\x01\x81\x15\x91\x84\xcb\ +\x00\x00\x11\x0a\x00\x00\x00\x00\x00\x01\x00\x00\xe0\xfe\ +\x00\x00\x01\x81\x15\x91\x86\x7f\ +\x00\x00\x29\x6e\x00\x00\x00\x00\x00\x01\x00\x01\xff\xc4\ +\x00\x00\x01\x81\x15\x91\x87\x3e\ +\x00\x00\x00\xf2\x00\x00\x00\x00\x00\x01\x00\x00\x1f\x99\ +\x00\x00\x01\x81\x15\x91\x87\x53\ +\x00\x00\x10\x96\x00\x00\x00\x00\x00\x01\x00\x00\xdb\x7f\ +\x00\x00\x01\x81\x15\x91\x84\xbb\ +\x00\x00\x0e\x6c\x00\x00\x00\x00\x00\x01\x00\x00\xc7\xd2\ +\x00\x00\x01\x81\x15\x91\x85\x9c\ +\x00\x00\x25\x4a\x00\x00\x00\x00\x00\x01\x00\x01\xcf\xcd\ +\x00\x00\x01\x81\x15\x91\x86\xae\ +\x00\x00\x0f\xbc\x00\x00\x00\x00\x00\x01\x00\x00\xd4\x1f\ +\x00\x00\x01\x81\x15\x91\x84\x9c\ +\x00\x00\x0b\xe4\x00\x00\x00\x00\x00\x01\x00\x00\xaf\x31\ +\x00\x00\x01\x81\x15\x91\x88\x09\ +\x00\x00\x09\xa8\x00\x00\x00\x00\x00\x01\x00\x00\x87\xb4\ +\x00\x00\x01\x81\x15\x91\x87\x79\ +\x00\x00\x08\x9e\x00\x00\x00\x00\x00\x01\x00\x00\x72\xc7\ +\x00\x00\x01\x81\x15\x91\x86\xcd\ +\x00\x00\x17\x1c\x00\x00\x00\x00\x00\x01\x00\x01\x30\x76\ +\x00\x00\x01\x81\x15\x91\x87\x80\ +\x00\x00\x0a\xde\x00\x00\x00\x00\x00\x01\x00\x00\x95\xf5\ +\x00\x00\x01\x81\x15\x91\x87\x8c\ +\x00\x00\x12\x6c\x00\x00\x00\x00\x00\x01\x00\x00\xf6\x17\ +\x00\x00\x01\x81\x15\x91\x86\x3d\ +\x00\x00\x02\xf8\x00\x00\x00\x00\x00\x01\x00\x00\x34\x42\ +\x00\x00\x01\x81\x15\x91\x86\xfc\ +\x00\x00\x22\x0e\x00\x00\x00\x00\x00\x01\x00\x01\xaa\x03\ +\x00\x00\x01\x81\x15\x91\x88\x1f\ +\x00\x00\x1a\x8e\x00\x00\x00\x00\x00\x01\x00\x01\x5b\x5d\ +\x00\x00\x01\x81\x15\x91\x86\xec\ +\x00\x00\x0e\x02\x00\x00\x00\x00\x00\x01\x00\x00\xc6\xbd\ +\x00\x00\x01\x81\x15\x91\x84\xea\ +\x00\x00\x00\x9e\x00\x00\x00\x00\x00\x01\x00\x00\x1f\x0d\ +\x00\x00\x01\x81\x15\x91\x86\x2d\ +\x00\x00\x18\xc4\x00\x00\x00\x00\x00\x01\x00\x01\x46\xb8\ +\x00\x00\x01\x81\x15\x91\x85\xb1\ +\x00\x00\x24\x0a\x00\x00\x00\x00\x00\x01\x00\x01\xc4\x9e\ +\x00\x00\x01\x81\x15\x91\x84\xdb\ +\x00\x00\x04\x72\x00\x00\x00\x00\x00\x01\x00\x00\x47\x31\ +\x00\x00\x01\x81\x15\x91\x84\xdb\ +\x00\x00\x2a\xa4\x00\x00\x00\x00\x00\x01\x00\x02\x11\x25\ +\x00\x00\x01\x81\x15\x91\x84\xac\ +\x00\x00\x2a\x38\x00\x00\x00\x00\x00\x01\x00\x02\x0a\x43\ +\x00\x00\x01\x81\x15\x91\x86\xcd\ +\x00\x00\x02\x10\x00\x00\x00\x00\x00\x01\x00\x00\x2e\x25\ +\x00\x00\x01\x81\x15\x91\x85\x3e\ +\x00\x00\x20\xfc\x00\x00\x00\x00\x00\x01\x00\x01\xa0\x76\ +\x00\x00\x01\x81\x15\x91\x86\x6b\ +\x00\x00\x12\x30\x00\x00\x00\x00\x00\x01\x00\x00\xf1\x9c\ +\x00\x00\x01\x81\x15\x91\x86\xbe\ +\x00\x00\x0a\x20\x00\x00\x00\x00\x00\x01\x00\x00\x88\xcc\ +\x00\x00\x01\x81\x15\x91\x86\xbe\ +\x00\x00\x04\xdc\x00\x00\x00\x00\x00\x01\x00\x00\x4a\x76\ +\x00\x00\x01\x81\x15\x91\x86\x9e\ +\x00\x00\x12\xf8\x00\x00\x00\x00\x00\x01\x00\x01\x02\x0e\ +\x00\x00\x01\x81\x15\x91\x86\x0d\ +\x00\x00\x10\x60\x00\x00\x00\x00\x00\x01\x00\x00\xdb\x13\ +\x00\x00\x01\x81\x15\x91\x86\x3d\ +\x00\x00\x07\x6e\x00\x00\x00\x00\x00\x01\x00\x00\x64\x50\ +\x00\x00\x01\x81\x15\x91\x86\xec\ +\x00\x00\x03\xdc\x00\x00\x00\x00\x00\x01\x00\x00\x44\xa3\ +\x00\x00\x01\x81\x15\x91\x87\xd0\ +\x00\x00\x1d\xe4\x00\x00\x00\x00\x00\x01\x00\x01\x7d\x1d\ +\x00\x00\x01\x81\x15\x91\x88\x46\ +\x00\x00\x24\x50\x00\x00\x00\x00\x00\x01\x00\x01\xc5\xc2\ +\x00\x00\x01\x81\x15\x91\x85\xc9\ +\x00\x00\x10\xc2\x00\x00\x00\x00\x00\x01\x00\x00\xe0\x6b\ +\x00\x00\x01\x81\x15\x91\x86\x16\ +\x00\x00\x00\x6a\x00\x00\x00\x00\x00\x01\x00\x00\x1a\xaa\ +\x00\x00\x01\x81\x15\x91\x86\xae\ +\x00\x00\x01\x6c\x00\x00\x00\x00\x00\x01\x00\x00\x25\x38\ +\x00\x00\x01\x81\x15\x91\x87\x43\ +\x00\x00\x15\x9c\x00\x00\x00\x00\x00\x01\x00\x01\x1e\x29\ +\x00\x00\x01\x81\x15\x91\x84\x81\ +\x00\x00\x0c\x90\x00\x00\x00\x00\x00\x01\x00\x00\xb0\xe3\ +\x00\x00\x01\x81\x15\x91\x85\xcd\ +\x00\x00\x29\x4a\x00\x00\x00\x00\x00\x01\x00\x01\xfd\x9e\ +\x00\x00\x01\x81\x15\x91\x84\x8c\ +\x00\x00\x2b\xda\x00\x00\x00\x00\x00\x01\x00\x02\x1b\xa2\ +\x00\x00\x01\x81\x15\x91\x86\x3d\ +\x00\x00\x0d\x70\x00\x00\x00\x00\x00\x01\x00\x00\xc3\x1b\ +\x00\x00\x01\x81\x15\x91\x84\xfd\ +\x00\x00\x0b\x78\x00\x00\x00\x00\x00\x01\x00\x00\x97\xf3\ +\x00\x00\x01\x81\x15\x91\x87\x9f\ +\x00\x00\x29\xe2\x00\x00\x00\x00\x00\x01\x00\x02\x09\xa8\ +\x00\x00\x01\x81\x15\x91\x86\x2d\ +\x00\x00\x1c\xee\x00\x00\x00\x00\x00\x01\x00\x01\x72\x8a\ +\x00\x00\x01\x81\x15\x91\x85\x9f\ +\x00\x00\x0f\x84\x00\x00\x00\x00\x00\x01\x00\x00\xd0\xe7\ +\x00\x00\x01\x81\x15\x91\x86\x5c\ +\x00\x00\x12\xc6\x00\x00\x00\x00\x00\x01\x00\x00\xf9\x9e\ +\x00\x00\x01\x81\x15\x91\x87\xa7\ +\x00\x00\x25\x82\x00\x00\x00\x00\x00\x01\x00\x01\xd4\x54\ +\x00\x00\x01\x81\x15\x91\x86\x2d\ +\x00\x00\x1f\x66\x00\x00\x00\x00\x00\x01\x00\x01\x8d\x15\ +\x00\x00\x01\x81\x15\x91\x87\x32\ +\x00\x00\x14\x8e\x00\x00\x00\x00\x00\x01\x00\x01\x0c\x69\ +\x00\x00\x01\x81\x15\x91\x84\xbb\ +\x00\x00\x28\x0e\x00\x00\x00\x00\x00\x01\x00\x01\xf7\x5c\ +\x00\x00\x01\x81\x15\x91\x88\x1b\ +\x00\x00\x0d\xa2\x00\x00\x00\x00\x00\x01\x00\x00\xc3\xb7\ +\x00\x00\x01\x81\x15\x91\x87\xdd\ +\x00\x00\x0e\x36\x00\x00\x00\x00\x00\x01\x00\x00\xc7\x59\ +\x00\x00\x01\x81\x15\x91\x88\x36\ +\x00\x00\x2b\x1c\x00\x00\x00\x00\x00\x01\x00\x02\x14\x12\ +\x00\x00\x01\x81\x15\x91\x87\xd9\ +\x00\x00\x2b\xa6\x00\x00\x00\x00\x00\x01\x00\x02\x19\x7c\ +\x00\x00\x01\x81\x15\x91\x84\x53\ +\x00\x00\x00\x32\x00\x02\x00\x00\x00\x01\x00\x00\x00\xd6\ +\x00\x00\x00\x00\x00\x00\x00\x00\ +\x00\x00\x00\x40\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\ +\x00\x00\x01\x81\x15\x91\x89\x29\ +" + +qt_version = [int(v) for v in QtCore.qVersion().split('.')] +if qt_version < [5, 8, 0]: + rcc_version = 1 + qt_resource_struct = qt_resource_struct_v1 +else: + rcc_version = 2 + qt_resource_struct = qt_resource_struct_v2 + +def qInitResources(): + QtCore.qRegisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data) + +def qCleanupResources(): + QtCore.qUnregisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data) + +qInitResources() diff --git a/3rdParty/qdarkstyle/dark/main.scss b/3rdParty/qdarkstyle/dark/main.scss index dc40bc521c..44409319fb 100644 --- a/3rdParty/qdarkstyle/dark/main.scss +++ b/3rdParty/qdarkstyle/dark/main.scss @@ -1,4 +1,4 @@ -/* Light Style - QDarkStyleSheet ------------------------------------------ */ - -@import '_variables'; -@import '../qss/_styles'; +/* Light Style - QDarkStyleSheet ------------------------------------------ */ + +@import '_variables'; +@import '../qss/_styles'; diff --git a/3rdParty/qdarkstyle/dark/palette.py b/3rdParty/qdarkstyle/dark/palette.py index 23a1d1f837..791e1a759e 100644 --- a/3rdParty/qdarkstyle/dark/palette.py +++ b/3rdParty/qdarkstyle/dark/palette.py @@ -1,36 +1,36 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -"""QDarkStyle default dark palette.""" - -# Local imports -from qdarkstyle.colorsystem import Blue, Gray -from qdarkstyle.palette import Palette - - -class DarkPalette(Palette): - """Dark palette variables.""" - - # Identifier - ID = 'dark' - - # Color - COLOR_BACKGROUND_1 = Gray.B10 - COLOR_BACKGROUND_2 = Gray.B20 - COLOR_BACKGROUND_3 = Gray.B30 - COLOR_BACKGROUND_4 = Gray.B40 - COLOR_BACKGROUND_5 = Gray.B50 - COLOR_BACKGROUND_6 = Gray.B60 - - COLOR_TEXT_1 = Gray.B130 - COLOR_TEXT_2 = Gray.B110 - COLOR_TEXT_3 = Gray.B90 - COLOR_TEXT_4 = Gray.B80 - - COLOR_ACCENT_1 = Blue.B20 - COLOR_ACCENT_2 = Blue.B40 - COLOR_ACCENT_3 = Blue.B50 - COLOR_ACCENT_4 = Blue.B70 - COLOR_ACCENT_5 = Blue.B80 - - OPACITY_TOOLTIP = 230 +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +"""QDarkStyle default dark palette.""" + +# Local imports +from qdarkstyle.colorsystem import Blue, Gray +from qdarkstyle.palette import Palette + + +class DarkPalette(Palette): + """Dark palette variables.""" + + # Identifier + ID = 'dark' + + # Color + COLOR_BACKGROUND_1 = Gray.B10 + COLOR_BACKGROUND_2 = Gray.B20 + COLOR_BACKGROUND_3 = Gray.B30 + COLOR_BACKGROUND_4 = Gray.B40 + COLOR_BACKGROUND_5 = Gray.B50 + COLOR_BACKGROUND_6 = Gray.B60 + + COLOR_TEXT_1 = Gray.B130 + COLOR_TEXT_2 = Gray.B110 + COLOR_TEXT_3 = Gray.B90 + COLOR_TEXT_4 = Gray.B80 + + COLOR_ACCENT_1 = Blue.B20 + COLOR_ACCENT_2 = Blue.B40 + COLOR_ACCENT_3 = Blue.B50 + COLOR_ACCENT_4 = Blue.B70 + COLOR_ACCENT_5 = Blue.B80 + + OPACITY_TOOLTIP = 230 diff --git a/3rdParty/qdarkstyle/dark/rc/.keep b/3rdParty/qdarkstyle/dark/rc/.keep index 8d1c8b69c3..56f3b36e27 100644 --- a/3rdParty/qdarkstyle/dark/rc/.keep +++ b/3rdParty/qdarkstyle/dark/rc/.keep @@ -1 +1 @@ - + diff --git a/3rdPartyBinaries/Sleepy.dll b/3rdPartyBinaries/Sleepy.dll deleted file mode 100644 index 3d7b601fed..0000000000 Binary files a/3rdPartyBinaries/Sleepy.dll and /dev/null differ diff --git a/3rdPartyBinaries/Sleepy.lib b/3rdPartyBinaries/Sleepy.lib deleted file mode 100644 index 8943da6e92..0000000000 Binary files a/3rdPartyBinaries/Sleepy.lib and /dev/null differ diff --git a/ClientSource/Connection/BotBaseMessage.h b/ClientSource/Connection/BotBaseMessage.h index b05cc23691..cd616ede75 100644 --- a/ClientSource/Connection/BotBaseMessage.h +++ b/ClientSource/Connection/BotBaseMessage.h @@ -40,13 +40,13 @@ struct BotBaseMessage{ if (type != MessageType){ throw SerialProtocolException( logger, PA_CURRENT_FUNCTION, - "Received incorrect response type: " + std::to_string(type) + "Received Incorrect Response Type: Expected = " + std::to_string(MessageType) + ", Actual = " + std::to_string(type) ); } if (body.size() != sizeof(MessageBody)){ throw SerialProtocolException( logger, PA_CURRENT_FUNCTION, - "Received incorrect response size: " + std::to_string(body.size()) + "Received Incorrect Response Size: Expected = " + std::to_string(sizeof(MessageBody)) + ", Actual = " + std::to_string(body.size()) ); } memcpy(¶ms, body.c_str(), body.size()); diff --git a/ClientSource/Connection/PABotBase.cpp b/ClientSource/Connection/PABotBase.cpp index 3f8403596b..85cc847e25 100644 --- a/ClientSource/Connection/PABotBase.cpp +++ b/ClientSource/Connection/PABotBase.cpp @@ -157,6 +157,10 @@ void PABotBase::wait_for_all_requests(const Cancellable* cancelled){ ReadSpinLock lg0(m_state_lock); throw InvalidConnectionStateException(m_error_message); } + if (m_error.load(std::memory_order_acquire)){ + ReadSpinLock lg0(m_state_lock); + throw ConnectionException(&m_logger, m_error_message); + } { ReadSpinLock lg1(m_state_lock, "PABotBase::wait_for_all_requests()"); #if 0 @@ -634,7 +638,7 @@ uint64_t PABotBase::try_issue_request( if (message.body.size() < sizeof(uint32_t)){ throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Message is too short."); } - if (message.body.size() > MAX_MESSAGE_SIZE){ + if (message.body.size() > PABB_PROTOCOL_MAX_PACKET_SIZE){ throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Message is too long."); } @@ -714,7 +718,7 @@ uint64_t PABotBase::try_issue_command( if (message.body.size() < sizeof(uint32_t)){ throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Message is too short."); } - if (message.body.size() > MAX_MESSAGE_SIZE){ + if (message.body.size() > PABB_PROTOCOL_MAX_PACKET_SIZE){ throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Message is too long."); } diff --git a/ClientSource/Connection/PABotBaseConnection.cpp b/ClientSource/Connection/PABotBaseConnection.cpp index 3863765e31..dbd941d7c0 100644 --- a/ClientSource/Connection/PABotBaseConnection.cpp +++ b/ClientSource/Connection/PABotBaseConnection.cpp @@ -67,7 +67,7 @@ void PABotBaseConnection::send_message(const BotBaseMessage& message, bool is_re m_sniffer->on_send(message, is_retransmit); size_t total_bytes = PABB_PROTOCOL_OVERHEAD + message.body.size(); - if (total_bytes > MAX_MESSAGE_SIZE){ + if (total_bytes > PABB_PROTOCOL_MAX_PACKET_SIZE){ throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Message is too long."); } @@ -82,6 +82,33 @@ void PABotBaseConnection::send_message(const BotBaseMessage& message, bool is_re } +void PABotBaseConnection::push_error_byte(ErrorBatchType type, char byte){ + if (m_current_error_type == type){ + m_current_error_batch.push_back(byte); + return; + } + + switch (m_current_error_type){ + case ErrorBatchType::NO_ERROR_: + break; + case ErrorBatchType::ZERO_BYTES: + m_sniffer->log("Skipped " + std::to_string(m_current_error_batch.size()) + " zero byte(s)."); + break; + case ErrorBatchType::FF_BYTES: + m_sniffer->log("Skipped " + std::to_string(m_current_error_batch.size()) + " 0xff byte(s)."); + break; + case ErrorBatchType::ASCII_BYTES: + m_sniffer->log("Received possible ASCII: " + m_current_error_batch); + break; + case ErrorBatchType::OTHER: +// m_sniffer->log("Skipped " + std::to_string(m_current_error_batch.size()) + " invalid length byte(s)."); + break; + } + + m_current_error_batch.clear(); + m_current_error_batch.push_back(byte); + m_current_error_type = type; +} void PABotBaseConnection::on_recv(const void* data, size_t bytes){ // Push into receive buffer. for (size_t c = 0; c < bytes; c++){ @@ -92,25 +119,32 @@ void PABotBaseConnection::on_recv(const void* data, size_t bytes){ uint8_t length = ~m_recv_buffer[0]; if (m_recv_buffer[0] == 0){ - m_sniffer->log("Skipping zero byte."); +// m_sniffer->log("Skipping zero byte."); + push_error_byte(ErrorBatchType::ZERO_BYTES, 0); m_recv_buffer.pop_front(); continue; } // Message is too short. if (length < PABB_PROTOCOL_OVERHEAD){ - m_sniffer->log("Message is too short: bytes = " + std::to_string(length)); + if (length == 0){ + push_error_byte(ErrorBatchType::FF_BYTES, ~length); + }else{ + m_sniffer->log("Message is too short: bytes = " + std::to_string(length)); + push_error_byte(ErrorBatchType::OTHER, ~length); + } m_recv_buffer.pop_front(); continue; } // Message is too long. - if (length > MAX_MESSAGE_SIZE){ - char ascii = ~length; - std::string text = ascii < 32 - ? ", ascii = " + std::to_string(ascii) - : std::string(", char = ") + ascii; - m_sniffer->log("Message is too long: bytes = " + std::to_string(length) + text); + if (length > PABB_PROTOCOL_MAX_PACKET_SIZE){ +// char ascii = ~length; +// std::string text = ascii < 32 +// ? ", ascii = " + std::to_string(ascii) +// : std::string(", char = ") + ascii; +// m_sniffer->log("Message is too long: bytes = " + std::to_string(length) + text); + push_error_byte(ErrorBatchType::ASCII_BYTES, ~length); m_recv_buffer.pop_front(); continue; } @@ -120,6 +154,9 @@ void PABotBaseConnection::on_recv(const void* data, size_t bytes){ return; } + m_current_error_type = ErrorBatchType::NO_ERROR_; + m_current_error_batch.clear(); + std::string message(m_recv_buffer.begin(), m_recv_buffer.begin() + length); // Verify checksum diff --git a/ClientSource/Connection/PABotBaseConnection.h b/ClientSource/Connection/PABotBaseConnection.h index 758dc94dce..0a2c40181a 100644 --- a/ClientSource/Connection/PABotBaseConnection.h +++ b/ClientSource/Connection/PABotBaseConnection.h @@ -16,7 +16,7 @@ #include #include -//#include "Common/SerialPABotBase/SerialPABotBase_Protocol.h" +#include "Common/SerialPABotBase/SerialPABotBase_Protocol.h" #include "BotBase.h" #include "MessageSniffer.h" #include "StreamInterface.h" @@ -27,9 +27,6 @@ namespace PokemonAutomation{ // None the functions in this class are thread-safe. It is up to // the child class to wrap and make them thread-safe. class PABotBaseConnection : public StreamListener{ -public: - static const size_t MAX_MESSAGE_SIZE = 64; - public: PABotBaseConnection(Logger& logger, std::unique_ptr connection); virtual ~PABotBaseConnection(); @@ -37,7 +34,7 @@ class PABotBaseConnection : public StreamListener{ void set_sniffer(MessageSniffer* sniffer); public: - void send_zeros(uint8_t bytes = MAX_MESSAGE_SIZE); + void send_zeros(uint8_t bytes = PABB_PROTOCOL_MAX_PACKET_SIZE); void send_message(const BotBaseMessage& message, bool is_retransmit); protected: @@ -48,10 +45,22 @@ class PABotBaseConnection : public StreamListener{ virtual void on_recv(const void* data, size_t bytes) override; virtual void on_recv_message(BotBaseMessage message) = 0; + enum class ErrorBatchType{ + NO_ERROR_, + ZERO_BYTES, + FF_BYTES, + ASCII_BYTES, + OTHER, + }; + void push_error_byte(ErrorBatchType type, char byte); + private: std::unique_ptr m_connection; std::deque m_recv_buffer; + ErrorBatchType m_current_error_type; + std::string m_current_error_batch; + protected: Logger& m_logger; MessageSniffer* m_sniffer; diff --git a/ClientSource/Libraries/MessageConverter.cpp b/ClientSource/Libraries/MessageConverter.cpp index a4d80616f6..63027b7f1b 100644 --- a/ClientSource/Libraries/MessageConverter.cpp +++ b/ClientSource/Libraries/MessageConverter.cpp @@ -420,7 +420,7 @@ int register_message_converters_custom_info(){ PABB_MSG_INFO_H32_LABEL, [](const std::string& body){ std::ostringstream ss; - ss << "PABB_MSG_INFO_I32_LABEL - "; + ss << "PABB_MSG_INFO_H32_LABEL - "; if (body.size() < sizeof(uint32_t)){ ss << "(invalid size)" << std::endl; return ss.str(); diff --git a/Common/Cpp/BitmapConversion.cpp b/Common/Cpp/BitmapConversion.cpp new file mode 100644 index 0000000000..f8289b0957 --- /dev/null +++ b/Common/Cpp/BitmapConversion.cpp @@ -0,0 +1,151 @@ +// Base64 Originally from René Nyffenegger's public domain base64 code +// (https://renenyffenegger.ch/notes/development/Base64/Encoding-and-decoding-base-64-with-cpp/) +// +// These changes were made: +// 1. String input/output interface +// 2. Proper padding handling +// 3. Explicit character validation + +#include "BitmapConversion.h" + +static const std::string BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; + +bool is_base64(unsigned char c) { + return (isalnum(c) || (c == '+') || (c == '/')); +} + +bool base64_encode(std::string &out, const std::string &in) { + int i = 0, j = 0; + unsigned char char_array_3[3]; + unsigned char char_array_4[4]; + out.clear(); + + for (auto c : in) { + char_array_3[i++] = c; + if (i == 3) { + char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; + char_array_4[1] = + ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); + char_array_4[2] = + ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); + char_array_4[3] = char_array_3[2] & 0x3f; + + for (i = 0; i < 4; i++) + out += BASE64_CHARS[char_array_4[i]]; + i = 0; + } + } + + if (i) { + for (j = i; j < 3; j++) + char_array_3[j] = '\0'; + + char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; + char_array_4[1] = + ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); + char_array_4[2] = + ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); + + for (j = 0; j < i + 1; j++) + out += BASE64_CHARS[char_array_4[j]]; + + while (i++ < 3) + out += '='; + } + + return true; +} + +bool base64_decode(std::string &out, const std::string &in) { + int i = 0, j = 0; + unsigned char char_array_4[4], char_array_3[3]; + out.clear(); + + for (auto c : in) { + if (c == '=') + break; + + if (!is_base64(c)) + return false; + + char_array_4[i++] = c; + if (i == 4) { + for (i = 0; i < 4; i++) + char_array_4[i] = (unsigned char)BASE64_CHARS.find(char_array_4[i]); + + char_array_3[0] = + (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = + ((char_array_4[1] & 0x0f) << 4) + ((char_array_4[2] & 0x3c) >> 2); + char_array_3[2] = ((char_array_4[2] & 0x03) << 6) + char_array_4[3]; + + for (i = 0; i < 3; i++) + out += char_array_3[i]; + i = 0; + } + } + + if (i) { + for (j = i; j < 4; j++) + char_array_4[j] = 0; + + for (j = 0; j < 4; j++) + char_array_4[j] = (unsigned char)BASE64_CHARS.find(char_array_4[j]); + + char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = + ((char_array_4[1] & 0x0f) << 4) + ((char_array_4[2] & 0x3c) >> 2); + + for (j = 0; j < i - 1; j++) + out += char_array_3[j]; + } + + return true; +} + +std::string pack_bits_to_string(const std::vector &vec) { + std::string packed; + if (vec.empty()) + return packed; + + packed.reserve((vec.size() + 7) / 8); + for (size_t i = 0; i < vec.size(); i += 8) { + unsigned char byte = 0; + for (size_t j = 0; j < 8 && (i + j) < vec.size(); ++j) { + if (vec[i + j]) { + byte |= (1 << (7 - j)); + } + } + packed.push_back(byte); + } + return packed; +} + +std::vector unpack_bits_from_string(const std::string &packed, + size_t original_size) { + std::vector vec; + vec.reserve(original_size); + for (size_t i = 0; i < packed.size(); ++i) { + unsigned char byte = packed[i]; + for (int j = 7; j >= 0 && vec.size() < original_size; --j) { + vec.push_back((byte >> j) & 1); + } + } + return vec; +} + +std::string pack_bit_vector_to_base64(const std::vector &vec) { + std::string packed = pack_bits_to_string(vec); + std::string b64; + base64_encode(b64, packed); + return b64; +} + +std::vector unpack_bit_vector_from_base64(const std::string &b64, + size_t original_size) { + std::string packed; + base64_decode(packed, b64); + return unpack_bits_from_string(packed, original_size); +} diff --git a/Common/Cpp/BitmapConversion.h b/Common/Cpp/BitmapConversion.h new file mode 100644 index 0000000000..4d390de75a --- /dev/null +++ b/Common/Cpp/BitmapConversion.h @@ -0,0 +1,32 @@ +/* Bitmap Conversion + * + * From: https://github.com/PokemonAutomation/ + * + * Functions to: + * - convert vector to string and back + * - convert vector to base64 string and back. + * + * The Base64 algorithm is originally from René Nyffenegger's public domain base64 code + * (https://renenyffenegger.ch/notes/development/Base64/Encoding-and-decoding-base-64-with-cpp/) + * + * These changes were made: + * 1. String input/output interface + * 2. Proper padding handling + * 3. Explicit character validation + */ + +#ifndef PokemonAutomation_BitmapCompression_H +#define PokemonAutomation_BitmapCompression_H + +#include +#include + +std::string pack_bits_to_string(const std::vector &vec); + +std::vector unpack_bits_from_string(const std::string &packed, size_t original_size); + +std::string pack_bit_vector_to_base64(const std::vector &vec); + +std::vector unpack_bit_vector_from_base64(const std::string &b64, size_t original_size); + +#endif diff --git a/Common/Cpp/Concurrency/AsyncDispatcher.cpp b/Common/Cpp/Concurrency/AsyncDispatcher.cpp index 2fa60c52b0..4056193cd4 100644 --- a/Common/Cpp/Concurrency/AsyncDispatcher.cpp +++ b/Common/Cpp/Concurrency/AsyncDispatcher.cpp @@ -15,31 +15,6 @@ namespace PokemonAutomation{ -AsyncTask::~AsyncTask(){ - std::unique_lock lg(m_lock); - m_cv.wait(lg, [this]{ return m_finished; }); -} -void AsyncTask::rethrow_exceptions(){ - if (!m_stopped_with_error.load(std::memory_order_acquire)){ - return; - } - std::unique_lock lg(m_lock); - if (m_exception){ - std::rethrow_exception(m_exception); - } -} -void AsyncTask::wait_and_rethrow_exceptions(){ - std::unique_lock lg(m_lock); - m_cv.wait(lg, [this]{ return m_finished; }); - if (m_exception){ - std::rethrow_exception(m_exception); - } -} -void AsyncTask::signal(){ - std::lock_guard lg(m_lock); - m_finished = true; - m_cv.notify_all(); -} #if 0 @@ -67,7 +42,8 @@ AsyncDispatcher::~AsyncDispatcher(){ thread.join(); } for (AsyncTask* task : m_queue){ - task->signal(); + task->report_cancelled(); +// task->signal(); } } @@ -83,7 +59,7 @@ void AsyncDispatcher::dispatch_task(AsyncTask& task){ std::lock_guard lg(m_lock); // Enqueue task. - m_queue.emplace_back(&task); + m_queue.emplace_back(&task)->report_started(); // Make sure a thread is ready for it. if (m_queue.size() > m_threads.size() - m_busy_count){ @@ -122,7 +98,7 @@ void AsyncDispatcher::run_in_parallel( // Enqueue tasks. for (std::unique_ptr& task : tasks){ - m_queue.emplace_back(task.get()); + m_queue.emplace_back(task.get())->report_started(); } // Make sure there are enough threads. @@ -178,18 +154,7 @@ void AsyncDispatcher::thread_loop(){ m_busy_count++; } - try{ - task->m_task(); - }catch (...){ - task->m_exception = std::current_exception(); - task->m_stopped_with_error.store(true, std::memory_order_release); -// cout << "Task threw an exception." << endl; -// std::lock_guard lg(m_lock); -// for (AsyncTask* t : m_queue){ -// t->signal(); -// } - } - task->signal(); + task->run(); } // cout << "AsyncDispatcher::thread_loop() End (outside) = " << GetCurrentThreadId() << endl; } diff --git a/Common/Cpp/Concurrency/AsyncDispatcher.h b/Common/Cpp/Concurrency/AsyncDispatcher.h index 3f0327d4d5..7955b2f4ca 100644 --- a/Common/Cpp/Concurrency/AsyncDispatcher.h +++ b/Common/Cpp/Concurrency/AsyncDispatcher.h @@ -3,9 +3,9 @@ * From: https://github.com/PokemonAutomation/ * * This class is meant for asynchronous tasks, not for parallel computation. - * This class will always spawn enough threads run all tasks in parallel. + * This class will always spawn enough threads run all tasks in parallel. * - * If you need to spam a bunch of compute tasks in parallel, use ParallelTaskRunner. + * If you need to spam a bunch of compute tasks in parallel, use ComputationThreadPool. * */ @@ -15,51 +15,14 @@ #include #include #include -#include #include #include #include -#include +#include "AsyncTask.h" namespace PokemonAutomation{ -class AsyncTask{ -public: - // Wait for the task to finish before destructing. Doesn't rethrow exceptions. - ~AsyncTask(); - - // If the task ended with an exception, rethrow it here. - // This does not clear the exception. - void rethrow_exceptions(); - - // Wait for the task to finish. Will rethrow any exceptions. - void wait_and_rethrow_exceptions(); - - -private: - template - AsyncTask(Args&&... args) - : m_task(std::forward(args)...) - , m_finished(false) - , m_stopped_with_error(false) - {} - void signal(); - -private: - friend class FireForgetDispatcher; - friend class AsyncDispatcher; - friend class ParallelTaskRunner; - - std::function m_task; - bool m_finished; - std::atomic m_stopped_with_error; - std::exception_ptr m_exception; - std::mutex m_lock; - std::condition_variable m_cv; -}; - - class AsyncDispatcher{ public: diff --git a/Common/Cpp/Concurrency/AsyncTask.cpp b/Common/Cpp/Concurrency/AsyncTask.cpp new file mode 100644 index 0000000000..b748f998dd --- /dev/null +++ b/Common/Cpp/Concurrency/AsyncTask.cpp @@ -0,0 +1,72 @@ +/* Async Task + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "SpinPause.h" +#include "AsyncTask.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +AsyncTask::~AsyncTask(){ + State state = m_state.load(std::memory_order_acquire); + if (state == State::NOT_STARTED || state == State::SAFE_TO_DESTRUCT){ +// cout << "Already Done: " << (int)state << endl; + return; + } + + { + std::unique_lock lg(m_lock); + m_cv.wait(lg, [this]{ + return m_state.load(std::memory_order_relaxed) != State::RUNNING; + }); + } + + while (m_state.load(std::memory_order_acquire) != State::SAFE_TO_DESTRUCT){ + pause(); + } + +// cout << "Late Finish" << endl; +} + + +void AsyncTask::report_cancelled() noexcept{ + { +#ifdef PA_SANITIZE_AsyncTask + auto scope = m_sanitizer.check_scope(); +#endif + m_state.store(State::FINISHED, std::memory_order_release); + { + std::lock_guard lg(m_lock); + } + m_cv.notify_all(); + } + m_state.store(State::SAFE_TO_DESTRUCT, std::memory_order_release); +} +void AsyncTask::run() noexcept{ + { +#ifdef PA_SANITIZE_AsyncTask + auto scope = m_sanitizer.check_scope(); +#endif + try{ + m_task(); + }catch (...){ + std::lock_guard lg(m_lock); + m_exception = std::current_exception(); + } + } + report_cancelled(); +} + + + + + +} diff --git a/Common/Cpp/Concurrency/AsyncTask.h b/Common/Cpp/Concurrency/AsyncTask.h new file mode 100644 index 0000000000..ba65845ed5 --- /dev/null +++ b/Common/Cpp/Concurrency/AsyncTask.h @@ -0,0 +1,99 @@ +/* Async Task + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_AsyncTask_H +#define PokemonAutomation_AsyncTask_H + +#include +#include +#include +#include +#include + +#define PA_SANITIZE_AsyncTask + +#ifdef PA_SANITIZE_AsyncTask +#include "Common/Cpp/LifetimeSanitizer.h" +#endif + +namespace PokemonAutomation{ + + +class AsyncTask{ +public: + enum class State{ + NOT_STARTED, + RUNNING, + FINISHED, + SAFE_TO_DESTRUCT, + }; + + +public: + // If the task has already started, this will wait for it to finish. + // This will not rethrow exceptions. + ~AsyncTask(); + + +public: + template + AsyncTask(Args&&... args) + : m_task(std::forward(args)...) + , m_state(State::NOT_STARTED) + {} + + bool is_finished() const noexcept{ +#ifdef PA_SANITIZE_AsyncTask + auto scope = m_sanitizer.check_scope(); +#endif + State state = m_state.load(std::memory_order_acquire); + return state == State::FINISHED || state == State::SAFE_TO_DESTRUCT; + } + + // Wait for the task to finish. Will rethrow any exceptions. + void wait_and_rethrow_exceptions(){ +#ifdef PA_SANITIZE_AsyncTask + auto scope = m_sanitizer.check_scope(); +#endif + if (!is_finished()){ + std::unique_lock lg(m_lock); + m_cv.wait(lg, [this]{ return is_finished(); }); + } + if (m_exception){ + std::rethrow_exception(m_exception); + } + } + + +public: + // These should only be called inside a parallel framework. + // These are not thread-safe with each other. + void report_started(){ +#ifdef PA_SANITIZE_AsyncTask + auto scope = m_sanitizer.check_scope(); +#endif + m_state.store(State::RUNNING, std::memory_order_release); + } + void report_cancelled() noexcept; + void run() noexcept; + + +private: + std::function m_task; + std::atomic m_state; + std::exception_ptr m_exception; + mutable std::mutex m_lock; + std::condition_variable m_cv; + +#ifdef PA_SANITIZE_AsyncTask + LifetimeSanitizer m_sanitizer; +#endif +}; + + + +} +#endif diff --git a/Common/Cpp/Concurrency/ComputationThreadPool.cpp b/Common/Cpp/Concurrency/ComputationThreadPool.cpp new file mode 100644 index 0000000000..70b0774dc0 --- /dev/null +++ b/Common/Cpp/Concurrency/ComputationThreadPool.cpp @@ -0,0 +1,83 @@ +/* Computation Thread Pool + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "AsyncTask.h" +#include "ComputationThreadPoolCore.h" +#include "ComputationThreadPool.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + + + + + + + +ComputationThreadPool::ComputationThreadPool( + std::function&& new_thread_callback, + size_t starting_threads, + size_t max_threads +) + : m_core( + CONSTRUCT_TOKEN, + std::move(new_thread_callback), + starting_threads, + max_threads + ) +{} +ComputationThreadPool::~ComputationThreadPool() = default; +size_t ComputationThreadPool::current_threads() const{ + return m_core->current_threads(); +} +size_t ComputationThreadPool::max_threads() const{ + return m_core->max_threads(); +} +WallDuration ComputationThreadPool::cpu_time() const{ + return m_core->cpu_time(); +} +void ComputationThreadPool::ensure_threads(size_t threads){ + m_core->ensure_threads(threads); +} +//void ParallelTaskRunner::wait_for_everything(){ +// m_core->wait_for_everything(); +//} +std::unique_ptr ComputationThreadPool::blocking_dispatch(std::function&& func){ + return m_core->blocking_dispatch(std::move(func)); +} +std::unique_ptr ComputationThreadPool::try_dispatch(std::function& func){ + return m_core->try_dispatch(func); +} +void ComputationThreadPool::run_in_parallel( + const std::function& func, + size_t start, size_t end, + size_t block_size +){ + m_core->run_in_parallel(func, start, end, block_size); +} + + + + + + + + + + + + + + + + +} diff --git a/Common/Cpp/Concurrency/ComputationThreadPool.h b/Common/Cpp/Concurrency/ComputationThreadPool.h new file mode 100644 index 0000000000..b71194dbd0 --- /dev/null +++ b/Common/Cpp/Concurrency/ComputationThreadPool.h @@ -0,0 +1,81 @@ +/* Computation Thread Pool + * + * From: https://github.com/PokemonAutomation/ + * + * This is a thread pool for compute-heavy tasks. + * + * This thread pool has a limited number of threads and should only be used for + * compute-heavy tasks that do not block or yield. A blocked thread will still + * count towards the thread limit. + * + * Because the # of threads is capped, it is safe to spam this thread pool with + * lots of smaller tasks. + * + */ + +#ifndef PokemonAutomation_ComputationThreadPool_H +#define PokemonAutomation_ComputationThreadPool_H + +#include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/Containers/Pimpl.h" + +namespace PokemonAutomation{ + +class AsyncTask; +class ComputationThreadPoolCore; + + +class ComputationThreadPool final{ +public: + ComputationThreadPool( + std::function&& new_thread_callback, + size_t starting_threads, + size_t max_threads + ); + ~ComputationThreadPool(); + + size_t current_threads() const; + size_t max_threads() const; + WallDuration cpu_time() const; + + void ensure_threads(size_t threads); + +// void wait_for_everything(); + + +public: + // As of this writing, tasks dispatched earlier are not allowed to block + // on tasks that are dispatched later as it may cause a deadlock. + + // Dispatch the function. If there are no threads available, it waits until + // there are. + [[nodiscard]] std::unique_ptr blocking_dispatch(std::function&& func); + + // Dispatch the function. Returns null if no threads are available. + // "func" will be moved-from only on success. + [[nodiscard]] std::unique_ptr try_dispatch(std::function& func); + + // Run function for all the indices [start, end). + // Lower indices are not allowed to block on higher indices. + void run_in_parallel( + const std::function& func, + size_t start, size_t end, + size_t block_size = 0 + ); + + +private: + Pimpl m_core; +}; + + + + + + + + + +} +#endif diff --git a/Common/Cpp/Concurrency/ComputationThreadPoolCore.cpp b/Common/Cpp/Concurrency/ComputationThreadPoolCore.cpp new file mode 100644 index 0000000000..f1d1f637d5 --- /dev/null +++ b/Common/Cpp/Concurrency/ComputationThreadPoolCore.cpp @@ -0,0 +1,243 @@ +/* Computation Thread Pool + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PanicDump.h" +#include "ReverseLockGuard.h" +#include "ComputationThreadPoolCore.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +ComputationThreadPoolCore::ComputationThreadPoolCore( + std::function&& new_thread_callback, + size_t starting_threads, + size_t max_threads +) + : m_new_thread_callback(std::move(new_thread_callback)) + , m_max_threads(max_threads == 0 ? std::thread::hardware_concurrency() : max_threads) + , m_stopping(false) + , m_busy_count(0) +{ + for (size_t c = 0; c < starting_threads; c++){ + spawn_thread(); + } +} +ComputationThreadPoolCore::~ComputationThreadPoolCore(){ + { + std::lock_guard lg(m_lock); + m_stopping = true; + m_thread_cv.notify_all(); +// m_dispatch_cv.notify_all(); + } + for (ThreadData& thread : m_threads){ + thread.thread.join(); + } + for (auto& task : m_queue){ + task->report_cancelled(); + } +} + +WallDuration ComputationThreadPoolCore::cpu_time() const{ + // TODO: Don't lock the entire queue. + WallDuration ret = WallDuration::zero(); + std::lock_guard lg(m_lock); + for (const ThreadData& thread : m_threads){ +// ret += thread_cpu_time(thread.handle); + ret += thread.runtime.total(); + } + return ret; +} + + +void ComputationThreadPoolCore::ensure_threads(size_t threads){ + std::lock_guard lg(m_lock); + while (m_threads.size() < threads){ + spawn_thread(); + } +} +#if 0 +void ComputationThreadPoolCore::wait_for_everything(){ + std::unique_lock lg(m_lock); + m_dispatch_cv.wait(lg, [this]{ + return m_queue.size() + m_busy_count == 0; + }); +} +#endif + +std::unique_ptr ComputationThreadPoolCore::blocking_dispatch(std::function&& func){ + std::unique_ptr task(new AsyncTask(std::move(func))); + + { + std::unique_lock lg(m_lock); + + m_dispatch_cv.wait(lg, [this]{ + return m_queue.size() + m_busy_count < m_max_threads; + }); + + // Enqueue task. + m_queue.emplace_back(task.get())->report_started(); + spawn_threads(); + +#if 0 + // Use this thread to process the queue until our task is + while (!m_queue.empty() && !task->is_finished()){ + AsyncTask* current = m_queue.front(); + m_queue.pop_front(); + + ReverseLockGuard lg0(m_lock); + current->run(); + } +#endif + } + +// cout << "notify... " << endl; + m_thread_cv.notify_one(); + + return task; +} +std::unique_ptr ComputationThreadPoolCore::try_dispatch(std::function& func){ + std::unique_ptr task; + { + std::lock_guard lg(m_lock); + + if (m_queue.size() + m_busy_count >= m_max_threads){ + return nullptr; + } + + task.reset(new AsyncTask(std::move(func))); + + // Enqueue task. + m_queue.emplace_back(task.get())->report_started(); + + spawn_threads(); + } + + m_thread_cv.notify_one(); + + return task; +} + + +void ComputationThreadPoolCore::run_in_parallel( + const std::function& func, + size_t start, size_t end, + size_t block_size +){ + if (start >= end){ + return; + } + size_t total = end - start; + + if (block_size == 0){ + block_size = total / m_max_threads / 16; + if (block_size == 0){ + block_size = 1; + } + } + + size_t blocks = (total + block_size - 1) / block_size; + + // Prepare all the tasks. + std::vector> tasks(blocks); + for (size_t c = 0; c < blocks; c++){ + tasks[c].reset(new AsyncTask([=, &func]{ + size_t s = start + c * block_size; + size_t e = std::min(s + block_size, end); +// cout << "Running: [" << s << "," << e << ")" << endl; + for (; s < e; s++){ + func(s); + } + })); + } + + { + // Enqueue all the tasks. + std::unique_lock lg(m_lock); + for (std::unique_ptr& task : tasks){ + m_queue.emplace_back(task.get())->report_started(); + m_thread_cv.notify_one(); + } + spawn_threads(); + + // Use this thread to process the queue until our tasks are done. + while (!m_queue.empty() && !tasks.back()->is_finished()){ + AsyncTask* task = m_queue.front(); + m_queue.pop_front(); + + ReverseLockGuard lg0(m_lock); + task->run(); + } + } + + // Wait for everything to finish. + for (std::unique_ptr& task : tasks){ + task->wait_and_rethrow_exceptions(); + } +} + + + +void ComputationThreadPoolCore::spawn_thread(){ + // Must call under lock. + ThreadData& handle = m_threads.emplace_back(); + try{ + handle.thread = std::thread( + run_with_catch, + "ParallelTaskRunner::thread_loop()", + [&, this]{ thread_loop(handle); } + ); + }catch (...){ + m_threads.pop_back(); + throw; + } +} +void ComputationThreadPoolCore::spawn_threads(){ + while (m_threads.size() < std::min(m_queue.size() + m_busy_count, m_max_threads)){ + spawn_thread(); + } +} +void ComputationThreadPoolCore::thread_loop(ThreadData& data){ + data.handle = current_thread_handle(); + + if (m_new_thread_callback){ + m_new_thread_callback(); + } + + data.runtime.start(); + + std::unique_lock lg(m_lock); + m_busy_count++; + while (!m_stopping){ +// cout << "m_queue... " << m_queue.size() << endl; + if (m_queue.empty()){ + data.runtime.stop(); + m_busy_count--; + m_dispatch_cv.notify_all(); +// cout << "waiting... " << m_busy_count << endl; + m_thread_cv.wait(lg); +// cout << "waking... " << m_busy_count << endl; + m_busy_count++; + data.runtime.start(); + continue; + } + + AsyncTask* task = m_queue.front(); + m_queue.pop_front(); + + ReverseLockGuard lg0(m_lock); + task->run(); + } +} + + + + +} diff --git a/Common/Cpp/Concurrency/ComputationThreadPoolCore.h b/Common/Cpp/Concurrency/ComputationThreadPoolCore.h new file mode 100644 index 0000000000..a262b83c36 --- /dev/null +++ b/Common/Cpp/Concurrency/ComputationThreadPoolCore.h @@ -0,0 +1,107 @@ +/* Computation Thread Pool + * + * From: https://github.com/PokemonAutomation/ + * + * This is a thread pool for compute-heavy tasks. + * + * This thread pool has a limited number of threads and should only be used for + * compute-heavy tasks that do not block or yield. A blocked thread will still + * count towards the thread limit. + * + * Because the # of threads is capped, it is safe to spam this thread pool with + * lots of smaller tasks. + * + */ + +#ifndef PokemonAutomation_ComputationThreadPoolCore_H +#define PokemonAutomation_ComputationThreadPoolCore_H + +#include +#include +#include +#include +#include "Common/Cpp/CpuUtilization/CpuUtilization.h" +#include "Common/Cpp/Stopwatch.h" +#include "AsyncTask.h" + +namespace PokemonAutomation{ + + + + +class ComputationThreadPoolCore final{ +public: + ComputationThreadPoolCore( + std::function&& new_thread_callback, + size_t starting_threads, + size_t max_threads + ); + ~ComputationThreadPoolCore(); + + size_t current_threads() const{ + std::lock_guard lg(m_lock); + return m_threads.size(); + } + size_t max_threads() const{ + return m_max_threads; + } + WallDuration cpu_time() const; + + void ensure_threads(size_t threads); +// void wait_for_everything(); + + +public: + // As of this writing, tasks dispatched earlier are not allowed to block + // on tasks that are dispatched later as it may cause a deadlock. + + // Dispatch the function. If there are no threads available, it waits until + // there are. + [[nodiscard]] std::unique_ptr blocking_dispatch(std::function&& func); + + // Dispatch the function. Returns null if no threads are available. + // "func" will be moved-from only on success. + [[nodiscard]] std::unique_ptr try_dispatch(std::function& func); + + // Run function for all the indices [start, end). + // Lower indices are not allowed to block on higher indices. + void run_in_parallel( + const std::function& func, + size_t start, size_t end, + size_t block_size = 0 + ); + + +private: + struct ThreadData{ + std::thread thread; + ThreadHandle handle; + Stopwatch runtime; + }; + + void spawn_thread(); + void spawn_threads(); + void thread_loop(ThreadData& data); + + +private: + struct Data; + + std::function m_new_thread_callback; + size_t m_max_threads; + std::deque m_queue; + + std::deque m_threads; + + bool m_stopping; + size_t m_busy_count; + mutable std::mutex m_lock; + std::condition_variable m_thread_cv; + std::condition_variable m_dispatch_cv; +}; + + + + +} +#endif diff --git a/Common/Cpp/Concurrency/ParallelTaskRunner.cpp b/Common/Cpp/Concurrency/ParallelTaskRunner.cpp deleted file mode 100644 index ade11dd5fa..0000000000 --- a/Common/Cpp/Concurrency/ParallelTaskRunner.cpp +++ /dev/null @@ -1,159 +0,0 @@ -/* Parallel Task Runner - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#if _WIN32 -#include -#endif -#include "Common/Cpp/PanicDump.h" -#include "ParallelTaskRunner.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -ParallelTaskRunner::ParallelTaskRunner( - std::function&& new_thread_callback, - size_t starting_threads, - size_t max_threads -) - : m_new_thread_callback(std::move(new_thread_callback)) - , m_max_threads(max_threads == 0 ? std::thread::hardware_concurrency() : max_threads) - , m_stopping(false) - , m_busy_count(0) -{ - for (size_t c = 0; c < starting_threads; c++){ - m_threads.emplace_back(run_with_catch, "ParallelTaskRunner::thread_loop()", [this]{ thread_loop(); }); - } -} -ParallelTaskRunner::~ParallelTaskRunner(){ - { - std::lock_guard lg(m_lock); - m_stopping = true; - m_thread_cv.notify_all(); -// m_dispatch_cv.notify_all(); - } - for (std::thread& thread : m_threads){ - thread.join(); - } - for (auto& task : m_queue){ - task->signal(); - } -} - -void ParallelTaskRunner::wait_for_everything(){ - std::unique_lock lg(m_lock); - m_dispatch_cv.wait(lg, [this]{ - return m_queue.size() + m_busy_count == 0; - }); -} - -std::shared_ptr ParallelTaskRunner::dispatch(std::function&& func){ - std::shared_ptr task(new AsyncTask(std::move(func))); - - std::unique_lock lg(m_lock); - - m_dispatch_cv.wait(lg, [this]{ - return m_queue.size() + m_busy_count < m_max_threads; - }); - - // Enqueue task. - m_queue.emplace_back(task); - - if (m_queue.size() + m_busy_count > m_threads.size()){ - m_threads.emplace_back(run_with_catch, "ParallelTaskRunner::thread_loop()", [this]{ thread_loop(); }); - } - - m_thread_cv.notify_one(); - - return task; -} - - -void ParallelTaskRunner::run_in_parallel( - const std::function& func, - size_t start, size_t end, - size_t block_size -){ - if (start >= end){ - return; - } - size_t total = end - start; - size_t blocks = (total + block_size - 1) / block_size; - - std::vector> tasks; - for (size_t c = 0; c < blocks; c++){ - tasks.emplace_back(dispatch([=, &func]{ - size_t s = start + c * block_size; - size_t e = std::min(s + block_size, end); -// cout << "Running: [" << s << "," << e << ")" << endl; - for (; s < e; s++){ - func(s); - } - })); - } - - for (std::shared_ptr& task : tasks){ - task->wait_and_rethrow_exceptions(); - } -} - - - - -void ParallelTaskRunner::thread_loop(){ -//#if _WIN32 -// SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_IDLE); -//#endif - if (m_new_thread_callback){ - m_new_thread_callback(); - } - - bool busy = false; - while (true){ - std::shared_ptr task; - { - std::unique_lock lg(m_lock); - if (busy){ - m_busy_count--; - busy = false; - m_dispatch_cv.notify_all(); - } - - if (m_stopping){ - return; - } - if (m_queue.empty()){ - m_thread_cv.wait(lg); - continue; - } - - task = m_queue.front(); - m_queue.pop_front(); - - busy = true; - m_busy_count++; - } - - try{ - task->m_task(); - }catch (...){ - task->m_exception = std::current_exception(); -// std::lock_guard lg(m_lock); -// for (std::shared_ptr& t : m_queue){ -// t->signal(); -// } - } - task->signal(); - } -} - - - -} diff --git a/Common/Cpp/Concurrency/ParallelTaskRunner.h b/Common/Cpp/Concurrency/ParallelTaskRunner.h deleted file mode 100644 index b682d41398..0000000000 --- a/Common/Cpp/Concurrency/ParallelTaskRunner.h +++ /dev/null @@ -1,57 +0,0 @@ -/* Parallel Task Runner - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ParallelTaskRunner_H -#define PokemonAutomation_ParallelTaskRunner_H - -#include "AsyncDispatcher.h" - -namespace PokemonAutomation{ - - -class ParallelTaskRunner{ -public: - ParallelTaskRunner( - std::function&& new_thread_callback, - size_t starting_threads, - size_t max_threads - ); - ~ParallelTaskRunner(); - - void wait_for_everything(); - - std::shared_ptr dispatch(std::function&& func); - - void run_in_parallel( - const std::function& func, - size_t start, size_t end, - size_t block_size = 0 - ); - - -private: -// void dispatch_task(AsyncTask& task); - void thread_loop(); - - -private: - std::function m_new_thread_callback; - size_t m_max_threads; - std::deque> m_queue; - std::vector m_threads; - bool m_stopping; - size_t m_busy_count; - std::mutex m_lock; - std::condition_variable m_thread_cv; - std::condition_variable m_dispatch_cv; -}; - - - - - -} -#endif diff --git a/Common/Cpp/Concurrency/PeriodicScheduler.cpp b/Common/Cpp/Concurrency/PeriodicScheduler.cpp index 61e60745b4..37207aac08 100644 --- a/Common/Cpp/Concurrency/PeriodicScheduler.cpp +++ b/Common/Cpp/Concurrency/PeriodicScheduler.cpp @@ -148,7 +148,7 @@ void PeriodicRunner::thread_loop(){ bool is_back_to_back = false; std::unique_lock lg(m_lock); WallClock last_check_timestamp = current_time(); - WallClock::duration idle_since_last_check = WallClock::duration(0); + WallDuration idle_since_last_check = WallDuration(0); while (true){ if (cancelled()){ return; @@ -166,7 +166,7 @@ void PeriodicRunner::thread_loop(){ m_utilization.push_event(now - last_check_timestamp - idle_since_last_check, now); } last_check_timestamp = now; - idle_since_last_check = WallClock::duration(0); + idle_since_last_check = WallDuration(0); // cout << m_utilization.utilization() << endl; void* event = m_scheduler.request_next_event(now); diff --git a/Common/Cpp/Concurrency/ReverseLockGuard.h b/Common/Cpp/Concurrency/ReverseLockGuard.h index 69de98cad8..312a3a7312 100644 --- a/Common/Cpp/Concurrency/ReverseLockGuard.h +++ b/Common/Cpp/Concurrency/ReverseLockGuard.h @@ -1,40 +1,40 @@ -/* Reverse Lock Guard - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ReverseLockGuard_H -#define PokemonAutomation_ReverseLockGuard_H - -#include "Common/Cpp/Exceptions.h" - -namespace PokemonAutomation{ - - -template -class ReverseLockGuard{ -public: - ReverseLockGuard(Mutex& lock) - : m_lock(lock) - { - if (lock.try_lock()){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Attempted to unlock an already unlocked lock." - ); - } - lock.unlock(); - } - ~ReverseLockGuard(){ - m_lock.lock(); - } - - -private: - Mutex& m_lock; -}; - - -} -#endif +/* Reverse Lock Guard + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ReverseLockGuard_H +#define PokemonAutomation_ReverseLockGuard_H + +#include "Common/Cpp/Exceptions.h" + +namespace PokemonAutomation{ + + +template +class ReverseLockGuard{ +public: + ReverseLockGuard(Mutex& lock) + : m_lock(lock) + { + if (lock.try_lock()){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Attempted to unlock an already unlocked lock." + ); + } + lock.unlock(); + } + ~ReverseLockGuard(){ + m_lock.lock(); + } + + +private: + Mutex& m_lock; +}; + + +} +#endif diff --git a/Common/Cpp/Containers/CircularBuffer.h b/Common/Cpp/Containers/CircularBuffer.h index 58a18f6fb3..488dac8392 100644 --- a/Common/Cpp/Containers/CircularBuffer.h +++ b/Common/Cpp/Containers/CircularBuffer.h @@ -1,215 +1,215 @@ -/* Circular Buffer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CircularBuffer_H -#define PokemonAutomation_CircularBuffer_H - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/AlignedMalloc.h" - -namespace PokemonAutomation{ - - - -template -class CircularBuffer{ -public: - ~CircularBuffer(); - CircularBuffer(CircularBuffer&& x) noexcept; - void operator=(CircularBuffer&& x) noexcept; - CircularBuffer(const CircularBuffer& x); - void operator=(const CircularBuffer& x); - -public: - CircularBuffer(); - CircularBuffer(size_t capacity); - - void clear() noexcept; - - size_t empty() const{ return m_front == m_back; } - size_t full() const{ return m_back - m_front >= m_capacity; } - size_t size() const{ return m_back - m_front; } - - const Object& front() const; - Object& front(); - const Object& operator[](size_t index) const; - Object& operator[](size_t index); - - - template - Object& push_back(Args&&... args); - template - Object* try_push_back(Args&&... args); - void pop_front(); - -private: - size_t m_capacity; - size_t m_front; - size_t m_back; - Object* m_ptr; -}; - - - -template -CircularBuffer::~CircularBuffer(){ - clear(); - aligned_free(m_ptr); -} -template -CircularBuffer::CircularBuffer(CircularBuffer&& x) noexcept - : m_capacity(x.m_capacity) - , m_front(x.m_front) - , m_back(x.m_back) - , m_ptr(x.m_ptr) -{ - x.m_capacity = 0; - x.m_front = 0; - x.m_back = 0; - x.m_ptr = nullptr; -} -template -void CircularBuffer::operator=(CircularBuffer&& x) noexcept{ - if (this == &x){ - return; - } - clear(); - aligned_free(m_ptr); - m_capacity = x.m_capacity; - m_front = x.m_front; - m_back = x.m_back; - m_ptr = x.m_ptr; - x.m_capacity = 0; - x.m_front = 0; - x.m_back = 0; - x.m_ptr = nullptr; -} -template -CircularBuffer::CircularBuffer(const CircularBuffer& x) - : CircularBuffer(x.m_capacity) -{ - size_t size = x.size(); - for (size_t c = 0; c < size; c++){ - push_back(x[c]); - } -} -template -void CircularBuffer::operator=(const CircularBuffer& x){ - if (this == &x){ - return; - } - CircularBuffer tmp(x); - *this = std::move(tmp); -} - -template -CircularBuffer::CircularBuffer() - : m_capacity(0) - , m_front(0) - , m_back(0) - , m_ptr(nullptr) -{} -template -CircularBuffer::CircularBuffer(size_t capacity) - : m_capacity(capacity) - , m_front(0) - , m_back(0) - , m_ptr(nullptr) -{ - if (capacity == 0){ - return; - } - m_ptr = (Object*)aligned_malloc(capacity * sizeof(Object), alignof(Object)); - if (m_ptr == nullptr){ - throw std::bad_alloc(); - } -} - -template -void CircularBuffer::clear() noexcept{ - while (m_back > m_front){ - pop_front(); - } -} - - -template -const Object& CircularBuffer::front() const{ - return m_ptr[m_front]; -} -template -Object& CircularBuffer::front(){ - return m_ptr[m_front]; -} -template -const Object& CircularBuffer::operator[](size_t index) const{ - index += m_front; - if (index >= m_capacity){ - index -= m_capacity; - } - return m_ptr[index]; -} -template -Object& CircularBuffer::operator[](size_t index){ - index += m_front; - if (index >= m_capacity){ - index -= m_capacity; - } - return m_ptr[index]; -} - -template -template -Object& CircularBuffer::push_back(Args&&... args){ - if (m_back - m_front >= m_capacity){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "CircularBuffer: Attempted to push while full."); - } - size_t back = m_back; - if (back >= m_capacity){ - back -= m_capacity; - } - new (m_ptr + back) Object(std::forward(args)...); - m_back++; - return m_ptr[back]; -} -template -template -Object* CircularBuffer::try_push_back(Args&&... args){ - if (m_back - m_front >= m_capacity){ - return nullptr; - } - size_t back = m_back; - if (back >= m_capacity){ - back -= m_capacity; - } - new (m_ptr + back) Object(std::forward(args)...); - m_back++; - return &m_ptr[back]; -} - -template -void CircularBuffer::pop_front(){ - if (m_front == m_back){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "CircularBuffer: Attempted to pop while empty."); - } - size_t front = m_front; - m_ptr[front].~Object(); - front++; - size_t diff = front >= m_capacity ? m_capacity : 0; - m_front = front - diff; - m_back -= diff; -} - - - - - - - -} -#endif +/* Circular Buffer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CircularBuffer_H +#define PokemonAutomation_CircularBuffer_H + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/AlignedMalloc.h" + +namespace PokemonAutomation{ + + + +template +class CircularBuffer{ +public: + ~CircularBuffer(); + CircularBuffer(CircularBuffer&& x) noexcept; + void operator=(CircularBuffer&& x) noexcept; + CircularBuffer(const CircularBuffer& x); + void operator=(const CircularBuffer& x); + +public: + CircularBuffer(); + CircularBuffer(size_t capacity); + + void clear() noexcept; + + size_t empty() const{ return m_front == m_back; } + size_t full() const{ return m_back - m_front >= m_capacity; } + size_t size() const{ return m_back - m_front; } + + const Object& front() const; + Object& front(); + const Object& operator[](size_t index) const; + Object& operator[](size_t index); + + + template + Object& push_back(Args&&... args); + template + Object* try_push_back(Args&&... args); + void pop_front(); + +private: + size_t m_capacity; + size_t m_front; + size_t m_back; + Object* m_ptr; +}; + + + +template +CircularBuffer::~CircularBuffer(){ + clear(); + aligned_free(m_ptr); +} +template +CircularBuffer::CircularBuffer(CircularBuffer&& x) noexcept + : m_capacity(x.m_capacity) + , m_front(x.m_front) + , m_back(x.m_back) + , m_ptr(x.m_ptr) +{ + x.m_capacity = 0; + x.m_front = 0; + x.m_back = 0; + x.m_ptr = nullptr; +} +template +void CircularBuffer::operator=(CircularBuffer&& x) noexcept{ + if (this == &x){ + return; + } + clear(); + aligned_free(m_ptr); + m_capacity = x.m_capacity; + m_front = x.m_front; + m_back = x.m_back; + m_ptr = x.m_ptr; + x.m_capacity = 0; + x.m_front = 0; + x.m_back = 0; + x.m_ptr = nullptr; +} +template +CircularBuffer::CircularBuffer(const CircularBuffer& x) + : CircularBuffer(x.m_capacity) +{ + size_t size = x.size(); + for (size_t c = 0; c < size; c++){ + push_back(x[c]); + } +} +template +void CircularBuffer::operator=(const CircularBuffer& x){ + if (this == &x){ + return; + } + CircularBuffer tmp(x); + *this = std::move(tmp); +} + +template +CircularBuffer::CircularBuffer() + : m_capacity(0) + , m_front(0) + , m_back(0) + , m_ptr(nullptr) +{} +template +CircularBuffer::CircularBuffer(size_t capacity) + : m_capacity(capacity) + , m_front(0) + , m_back(0) + , m_ptr(nullptr) +{ + if (capacity == 0){ + return; + } + m_ptr = (Object*)aligned_malloc(capacity * sizeof(Object), alignof(Object)); + if (m_ptr == nullptr){ + throw std::bad_alloc(); + } +} + +template +void CircularBuffer::clear() noexcept{ + while (m_back > m_front){ + pop_front(); + } +} + + +template +const Object& CircularBuffer::front() const{ + return m_ptr[m_front]; +} +template +Object& CircularBuffer::front(){ + return m_ptr[m_front]; +} +template +const Object& CircularBuffer::operator[](size_t index) const{ + index += m_front; + if (index >= m_capacity){ + index -= m_capacity; + } + return m_ptr[index]; +} +template +Object& CircularBuffer::operator[](size_t index){ + index += m_front; + if (index >= m_capacity){ + index -= m_capacity; + } + return m_ptr[index]; +} + +template +template +Object& CircularBuffer::push_back(Args&&... args){ + if (m_back - m_front >= m_capacity){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "CircularBuffer: Attempted to push while full."); + } + size_t back = m_back; + if (back >= m_capacity){ + back -= m_capacity; + } + new (m_ptr + back) Object(std::forward(args)...); + m_back++; + return m_ptr[back]; +} +template +template +Object* CircularBuffer::try_push_back(Args&&... args){ + if (m_back - m_front >= m_capacity){ + return nullptr; + } + size_t back = m_back; + if (back >= m_capacity){ + back -= m_capacity; + } + new (m_ptr + back) Object(std::forward(args)...); + m_back++; + return &m_ptr[back]; +} + +template +void CircularBuffer::pop_front(){ + if (m_front == m_back){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "CircularBuffer: Attempted to pop while empty."); + } + size_t front = m_front; + m_ptr[front].~Object(); + front++; + size_t diff = front >= m_capacity ? m_capacity : 0; + m_front = front - diff; + m_back -= diff; +} + + + + + + + +} +#endif diff --git a/Common/Cpp/Containers/SparseArray.cpp b/Common/Cpp/Containers/SparseArray.cpp index 454a5db61f..317a4cbfa7 100644 --- a/Common/Cpp/Containers/SparseArray.cpp +++ b/Common/Cpp/Containers/SparseArray.cpp @@ -1,199 +1,199 @@ -/* Sparse Array - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "SparseArray.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -void SparseArray::write(size_t address, size_t bytes, const void* data){ - if (m_data.empty()){ - m_data.emplace( - std::piecewise_construct, - std::forward_as_tuple(address), - std::forward_as_tuple((char*)data, (char*)data + bytes) - ); - return; - } - - // Below bottom. - size_t top = address + bytes; - size_t lowest = m_data.begin()->first; - if (top < lowest){ - m_data.emplace( - std::piecewise_construct, - std::forward_as_tuple(address), - std::forward_as_tuple((char*)data, (char*)data + bytes) - ); - return; - } - - // Above top. - size_t highest = m_data.rbegin()->first + m_data.rbegin()->second.size(); - if (highest < address){ - m_data.emplace( - std::piecewise_construct, - std::forward_as_tuple(address), - std::forward_as_tuple((char*)data, (char*)data + bytes) - ); - return; - } - - // Get the first and last blocks that will be affected. - auto lower = m_data.upper_bound(address); - if (lower != m_data.begin()){ - --lower; - } - if (lower->first + lower->second.size() < address){ - ++lower; - } - auto upper = m_data.lower_bound(top); - if (upper != m_data.begin()){ - --upper; - } - - lowest = lower->first; - highest = upper->first + upper->second.size(); - if (lower == upper && lowest <= address && top <= highest){ - // Completely inside. - memcpy(lower->second.data() + address - lowest, data, bytes); - return; - } - - lowest = std::min(lowest, address); - highest = std::max(highest, top); - - std::string block(highest - lowest, 0); - - // Copy in the partial blocks. - bool one_block = lower == upper; - { - size_t shift = lower->first - lowest; - memcpy( - block.data() + shift, - lower->second.data(), - lower->second.size() - ); - } - if (!one_block){ - size_t shift = highest - upper->first - upper->second.size(); - memcpy( - block.data() + block.size() - upper->second.size() - shift, - upper->second.data(), - upper->second.size() - ); - } - -// cout << "lower = " << lower->first << endl; -// cout << "upper = " << upper->first << endl; -// cout << "lowest = " << lowest << endl; -// cout << "highest = " << highest << endl; - - // Copy the newly written block. - memcpy(block.data() + address - lowest, data, bytes); - -// cout << std::string((char*)block.data(), block.size()) << endl; - - // Insert into table. - if (lower->first == lowest){ -// cout << "replace" << endl; - lower->second = std::move(block); - ++lower; - }else{ -// cout << "add" << endl; - auto iter = m_data.emplace( - std::piecewise_construct, - std::forward_as_tuple(lowest), - std::forward_as_tuple(std::move(block)) - ).first; - m_data.erase(lower); - ++iter; - lower = iter; - } - - // Remove all the blocks that it touched. - if (!one_block){ - while (lower != upper){ - lower = m_data.erase(lower); - } - m_data.erase(lower); - } -} -void SparseArray::read(size_t address, size_t bytes, void* data) const{ - if (m_data.empty()){ - return; - } - - // Below bottom. - size_t top = address + bytes; - size_t lowest = m_data.begin()->first; - if (top < lowest){ - return; - } - - // Above top. - size_t highest = m_data.rbegin()->first + m_data.rbegin()->second.size(); - if (highest < address){ - return; - } - - auto lower = m_data.upper_bound(address); - if (lower != m_data.begin()){ - --lower; - } - - while (lower != m_data.end() && bytes > 0){ - size_t block = lower->first; - if (block >= top){ - break; - } - -// cout << "bytes = " << bytes << endl; -// cout << "address = " << address << endl; -// cout << "block = " << block << endl; - - const char* ptr = lower->second.data(); - size_t len = lower->second.size(); - - if (block < address){ -// cout << "block is before" << endl; - size_t shift = address - block; - block = address; - ptr += shift; - len -= shift; // Cannot go negative since it's guaranteed to overlap with region. - } - if (block > address){ -// cout << "block is later" << endl; - size_t shift = block - address; -// cout << "shift = " << shift << endl; - address = block; - data = (char*)data + shift; - bytes -= shift; // Cannot go negative since it's guaranteed to overlap with block. - } - - len = std::min(len, bytes); - -// cout << "len = " << len << endl; - - memcpy(data, ptr, len); - data = (char*)data + len; - address += len; - bytes -= len; - ++lower; - } - -} - - - - -} +/* Sparse Array + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "SparseArray.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +void SparseArray::write(size_t address, size_t bytes, const void* data){ + if (m_data.empty()){ + m_data.emplace( + std::piecewise_construct, + std::forward_as_tuple(address), + std::forward_as_tuple((char*)data, (char*)data + bytes) + ); + return; + } + + // Below bottom. + size_t top = address + bytes; + size_t lowest = m_data.begin()->first; + if (top < lowest){ + m_data.emplace( + std::piecewise_construct, + std::forward_as_tuple(address), + std::forward_as_tuple((char*)data, (char*)data + bytes) + ); + return; + } + + // Above top. + size_t highest = m_data.rbegin()->first + m_data.rbegin()->second.size(); + if (highest < address){ + m_data.emplace( + std::piecewise_construct, + std::forward_as_tuple(address), + std::forward_as_tuple((char*)data, (char*)data + bytes) + ); + return; + } + + // Get the first and last blocks that will be affected. + auto lower = m_data.upper_bound(address); + if (lower != m_data.begin()){ + --lower; + } + if (lower->first + lower->second.size() < address){ + ++lower; + } + auto upper = m_data.lower_bound(top); + if (upper != m_data.begin()){ + --upper; + } + + lowest = lower->first; + highest = upper->first + upper->second.size(); + if (lower == upper && lowest <= address && top <= highest){ + // Completely inside. + memcpy(lower->second.data() + address - lowest, data, bytes); + return; + } + + lowest = std::min(lowest, address); + highest = std::max(highest, top); + + std::string block(highest - lowest, 0); + + // Copy in the partial blocks. + bool one_block = lower == upper; + { + size_t shift = lower->first - lowest; + memcpy( + block.data() + shift, + lower->second.data(), + lower->second.size() + ); + } + if (!one_block){ + size_t shift = highest - upper->first - upper->second.size(); + memcpy( + block.data() + block.size() - upper->second.size() - shift, + upper->second.data(), + upper->second.size() + ); + } + +// cout << "lower = " << lower->first << endl; +// cout << "upper = " << upper->first << endl; +// cout << "lowest = " << lowest << endl; +// cout << "highest = " << highest << endl; + + // Copy the newly written block. + memcpy(block.data() + address - lowest, data, bytes); + +// cout << std::string((char*)block.data(), block.size()) << endl; + + // Insert into table. + if (lower->first == lowest){ +// cout << "replace" << endl; + lower->second = std::move(block); + ++lower; + }else{ +// cout << "add" << endl; + auto iter = m_data.emplace( + std::piecewise_construct, + std::forward_as_tuple(lowest), + std::forward_as_tuple(std::move(block)) + ).first; + m_data.erase(lower); + ++iter; + lower = iter; + } + + // Remove all the blocks that it touched. + if (!one_block){ + while (lower != upper){ + lower = m_data.erase(lower); + } + m_data.erase(lower); + } +} +void SparseArray::read(size_t address, size_t bytes, void* data) const{ + if (m_data.empty()){ + return; + } + + // Below bottom. + size_t top = address + bytes; + size_t lowest = m_data.begin()->first; + if (top < lowest){ + return; + } + + // Above top. + size_t highest = m_data.rbegin()->first + m_data.rbegin()->second.size(); + if (highest < address){ + return; + } + + auto lower = m_data.upper_bound(address); + if (lower != m_data.begin()){ + --lower; + } + + while (lower != m_data.end() && bytes > 0){ + size_t block = lower->first; + if (block >= top){ + break; + } + +// cout << "bytes = " << bytes << endl; +// cout << "address = " << address << endl; +// cout << "block = " << block << endl; + + const char* ptr = lower->second.data(); + size_t len = lower->second.size(); + + if (block < address){ +// cout << "block is before" << endl; + size_t shift = address - block; + block = address; + ptr += shift; + len -= shift; // Cannot go negative since it's guaranteed to overlap with region. + } + if (block > address){ +// cout << "block is later" << endl; + size_t shift = block - address; +// cout << "shift = " << shift << endl; + address = block; + data = (char*)data + shift; + bytes -= shift; // Cannot go negative since it's guaranteed to overlap with block. + } + + len = std::min(len, bytes); + +// cout << "len = " << len << endl; + + memcpy(data, ptr, len); + data = (char*)data + len; + address += len; + bytes -= len; + ++lower; + } + +} + + + + +} diff --git a/Common/Cpp/Containers/SparseArray.h b/Common/Cpp/Containers/SparseArray.h index 26cec21912..045f453f04 100644 --- a/Common/Cpp/Containers/SparseArray.h +++ b/Common/Cpp/Containers/SparseArray.h @@ -1,68 +1,68 @@ -/* Sparse Array - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SparseArray_H -#define PokemonAutomation_SparseArray_H - -#include -#include -#include - -namespace PokemonAutomation{ - - -struct SparseArrayBlock{ - size_t address; - std::string data; - - SparseArrayBlock(size_t p_address, const char* str) - : address(p_address) - , data(str, str + strlen(str)) - {} - SparseArrayBlock(size_t p_address, std::initializer_list p_data) - : address(p_address) - , data(p_data) - {} -}; - - -class SparseArray{ -public: - SparseArray() = default; - SparseArray(std::initializer_list list){ - for (auto& item : list){ - write(item.address, item.data.size(), item.data.data()); - } - } - - void write(size_t address, size_t bytes, const void* data); - void read(size_t address, size_t bytes, void* data) const; - -#if 1 - std::string dump() const{ - std::string ret; - for (const auto& item : m_data){ - ret += "{"; - ret += std::to_string(item.first); - ret += " : "; - ret += std::to_string(item.first + item.second.size()); - ret += "} = "; - ret += item.second; - ret += "\n"; - } - return ret; - } -#endif - -private: - std::map m_data; -}; - - - - -} -#endif +/* Sparse Array + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SparseArray_H +#define PokemonAutomation_SparseArray_H + +#include +#include +#include + +namespace PokemonAutomation{ + + +struct SparseArrayBlock{ + size_t address; + std::string data; + + SparseArrayBlock(size_t p_address, const char* str) + : address(p_address) + , data(str, str + strlen(str)) + {} + SparseArrayBlock(size_t p_address, std::initializer_list p_data) + : address(p_address) + , data(p_data) + {} +}; + + +class SparseArray{ +public: + SparseArray() = default; + SparseArray(std::initializer_list list){ + for (auto& item : list){ + write(item.address, item.data.size(), item.data.data()); + } + } + + void write(size_t address, size_t bytes, const void* data); + void read(size_t address, size_t bytes, void* data) const; + +#if 1 + std::string dump() const{ + std::string ret; + for (const auto& item : m_data){ + ret += "{"; + ret += std::to_string(item.first); + ret += " : "; + ret += std::to_string(item.first + item.second.size()); + ret += "} = "; + ret += item.second; + ret += "\n"; + } + return ret; + } +#endif + +private: + std::map m_data; +}; + + + + +} +#endif diff --git a/Common/Cpp/CpuUtilization/CpuUtilization.cpp b/Common/Cpp/CpuUtilization/CpuUtilization.cpp new file mode 100644 index 0000000000..d47db026e0 --- /dev/null +++ b/Common/Cpp/CpuUtilization/CpuUtilization.cpp @@ -0,0 +1,16 @@ +/* CPU Utilization + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CpuUtilization.h" + + +#if _WIN32 +#include "CpuUtilization_Windows.tpp" +#endif + +#if defined(__linux) || defined(__APPLE__) +#include "CpuUtilization_Linux.tpp" +#endif diff --git a/Common/Cpp/CpuUtilization/CpuUtilization.h b/Common/Cpp/CpuUtilization/CpuUtilization.h new file mode 100644 index 0000000000..5c63594e87 --- /dev/null +++ b/Common/Cpp/CpuUtilization/CpuUtilization.h @@ -0,0 +1,21 @@ +/* CPU Utilization + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CpuUtilization_H +#define PokemonAutomation_CpuUtilization_H + + +#if _WIN32 +#include "CpuUtilization_Windows.h" +#elif defined(__linux) || defined(__APPLE__) +#include "CpuUtilization_Linux.h" +#else +#error "Unsupported platform." +#endif + + + +#endif diff --git a/Common/Cpp/CpuUtilization/CpuUtilization_Linux.h b/Common/Cpp/CpuUtilization/CpuUtilization_Linux.h new file mode 100644 index 0000000000..5fd22b923b --- /dev/null +++ b/Common/Cpp/CpuUtilization/CpuUtilization_Linux.h @@ -0,0 +1,54 @@ +/* CPU Utilization (Linux) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CpuUtilization_Linux_H +#define PokemonAutomation_CpuUtilization_Linux_H + +#include +#include +#include "Common/Cpp/Time.h" +//#include "CpuUtilization.h" + +namespace PokemonAutomation{ + + + +class ThreadHandle{ +public: + pthread_t handle; +}; +ThreadHandle current_thread_handle(); +// Get the cpu time of the thread. +// This function must be called in the same process the thread belongs to. +WallDuration thread_cpu_time(const ThreadHandle& handle); + + + +class SystemCpuTime{ +public: + static SystemCpuTime now(); + static size_t vcores(); + + bool is_valid() const{ + return m_usec != 0 || m_sec != 0; + } + + std::chrono::microseconds operator-(const SystemCpuTime& x) const; + +private: + void set_to_now(); + static size_t read_cores(); + +private: + time_t m_sec = 0; + suseconds_t m_usec = 0; +}; + + + + +} +#endif diff --git a/Common/Cpp/CpuUtilization/CpuUtilization_Linux.tpp b/Common/Cpp/CpuUtilization/CpuUtilization_Linux.tpp new file mode 100644 index 0000000000..d1429729f4 --- /dev/null +++ b/Common/Cpp/CpuUtilization/CpuUtilization_Linux.tpp @@ -0,0 +1,94 @@ +/* CPU Utilization (Linux) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "CpuUtilization_Linux.h" + +#if defined(__APPLE__) +#include +#endif + +namespace PokemonAutomation{ + + + +ThreadHandle current_thread_handle(){ + return ThreadHandle{pthread_self()}; +} +WallDuration thread_cpu_time(const ThreadHandle& handle){ + uint64_t nanos = 0; + +#if defined(__APPLE__) + uint64_t tid = 0; + pthread_threadid_np(handle.handle, &tid); + struct proc_threadinfo pth; + if (PROC_PIDTHREADINFO_SIZE == + proc_pidinfo(getpid(), PROC_PIDTHREADID64INFO, tid, &pth, + PROC_PIDTHREADINFO_SIZE)) { + nanos = pth.pth_user_time + pth.pth_system_time; // user time + system time in ns + } + else{ + return WallDuration::min(); + } + +#else + clockid_t clockid; + int error = pthread_getcpuclockid(handle.handle, &clockid); + if (error){ + return WallDuration::min(); + } + + struct timespec ts; + if (clock_gettime(clockid, &ts) == -1){ + return WallDuration::min(); + } + + nanos = (uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec; +#endif + + return std::chrono::duration_cast(std::chrono::nanoseconds(nanos)); +} + + + + + + +std::chrono::microseconds SystemCpuTime::operator-(const SystemCpuTime& x) const{ + return std::chrono::microseconds((m_sec - x.m_sec) * 1000000ull + (m_usec - x.m_usec)); +} +SystemCpuTime SystemCpuTime::now(){ + SystemCpuTime ret; + ret.set_to_now(); + return ret; +} +size_t SystemCpuTime::vcores(){ + static size_t cores = read_cores(); + return cores; +} +void SystemCpuTime::set_to_now(){ + struct rusage ru; + if (getrusage(RUSAGE_SELF, &ru) == -1){ + m_sec = 0; + m_usec = 0; + }else{ + m_sec = ru.ru_utime.tv_sec + ru.ru_stime.tv_sec; + m_usec = ru.ru_utime.tv_usec + ru.ru_stime.tv_usec; + } +} +size_t SystemCpuTime::read_cores(){ + return std::thread::hardware_concurrency(); +} + + + + + +} diff --git a/Common/Cpp/CpuUtilization/CpuUtilization_Windows.h b/Common/Cpp/CpuUtilization/CpuUtilization_Windows.h new file mode 100644 index 0000000000..933d3f26a5 --- /dev/null +++ b/Common/Cpp/CpuUtilization/CpuUtilization_Windows.h @@ -0,0 +1,70 @@ +/* CPU Utilization (Windows) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CpuUtilization_Windows_H +#define PokemonAutomation_CpuUtilization_Windows_H + +#include +#include "Common/Cpp/Time.h" +//#include "CpuUtilization.h" + +namespace PokemonAutomation{ + + + +class WinApiHandleHolder; + +class ThreadHandle{ +public: + ThreadHandle(ThreadHandle&& x); + ThreadHandle& operator=(ThreadHandle&& x); + ThreadHandle(const ThreadHandle& x); + ThreadHandle& operator=(const ThreadHandle& x); + ~ThreadHandle(); + + ThreadHandle(std::shared_ptr ptr = nullptr); + + std::shared_ptr m_ptr; +}; +ThreadHandle current_thread_handle(); +WallDuration thread_cpu_time(const ThreadHandle& handle); + + + + + +class SystemCpuTime{ +public: + static SystemCpuTime now(); + static size_t vcores(); + + bool is_valid() const{ + return m_kernel != 0; + } + + std::chrono::microseconds operator-(const SystemCpuTime& x) const{ + uint64_t idle = m_idle - x.m_idle; + uint64_t kernel = m_kernel - x.m_kernel; + uint64_t user = m_user - x.m_user; + uint64_t total_utilization = kernel + user - idle; + return std::chrono::microseconds(total_utilization / 10); + } + +private: + void set_to_now(); + static size_t read_cores(); + +private: + uint64_t m_idle = 0; + uint64_t m_kernel = 0; + uint64_t m_user = 0; +}; + + + + +} +#endif diff --git a/Common/Cpp/CpuUtilization/CpuUtilization_Windows.tpp b/Common/Cpp/CpuUtilization/CpuUtilization_Windows.tpp new file mode 100644 index 0000000000..942e81ba49 --- /dev/null +++ b/Common/Cpp/CpuUtilization/CpuUtilization_Windows.tpp @@ -0,0 +1,121 @@ +/* CPU Utilization (Windows) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CpuUtilization_Windows.h" + +namespace PokemonAutomation{ + + + +class WinApiHandleHolder{ +public: + WinApiHandleHolder(const WinApiHandleHolder& x) = delete; + void operator=(const WinApiHandleHolder& x) = delete; + ~WinApiHandleHolder(){ + CloseHandle(m_handle); + } + WinApiHandleHolder(HANDLE handle) + : m_handle(handle) + {} + operator HANDLE() const{ + return m_handle; + } + +private: + HANDLE m_handle; +}; + + + + + +ThreadHandle::ThreadHandle(ThreadHandle&& x) = default; +ThreadHandle& ThreadHandle::operator=(ThreadHandle&& x) = default; +ThreadHandle::ThreadHandle(const ThreadHandle& x) = default; +ThreadHandle& ThreadHandle::operator=(const ThreadHandle& x) = default; +ThreadHandle::~ThreadHandle() = default; +ThreadHandle::ThreadHandle(std::shared_ptr ptr) + : m_ptr(std::move(ptr)) +{} + + + +ThreadHandle current_thread_handle(){ + DWORD id = GetCurrentThreadId(); + HANDLE handle = OpenThread(THREAD_QUERY_LIMITED_INFORMATION, false, id); +// cout << handle << endl; + if (handle == NULL){ + return ThreadHandle(); + } + return ThreadHandle{std::make_shared(handle)}; +} +WallDuration thread_cpu_time(const ThreadHandle& handle){ + FILETIME creation_time; + FILETIME exit_time; + FILETIME kernel_time; + FILETIME user_time; + + if (!handle.m_ptr){ + return WallDuration::min(); + } + + if (!GetThreadTimes(*handle.m_ptr, &creation_time, &exit_time, &kernel_time, &user_time)){ + return WallDuration::min(); + } + + uint64_t nanos = user_time.dwLowDateTime + ((uint64_t)user_time.dwHighDateTime << 32); + nanos *= 100; + return std::chrono::duration_cast(std::chrono::nanoseconds(nanos)); +} + + + + + + + + +SystemCpuTime SystemCpuTime::now(){ + SystemCpuTime ret; + ret.set_to_now(); + return ret; +} +size_t SystemCpuTime::vcores(){ + static size_t cores = read_cores(); + return cores; +} +void SystemCpuTime::set_to_now(){ + FILETIME idle_time, kernel_time, user_time; + if (GetSystemTimes(&idle_time, &kernel_time, &user_time)){ + m_idle = idle_time.dwLowDateTime + ((uint64_t)idle_time.dwHighDateTime << 32); + m_kernel = kernel_time.dwLowDateTime + ((uint64_t)kernel_time.dwHighDateTime << 32); + m_user = user_time.dwLowDateTime + ((uint64_t)user_time.dwHighDateTime << 32); + }else{ + m_idle = 0; + m_kernel = 0; + m_user = 0; + } +} +size_t SystemCpuTime::read_cores(){ + size_t cores = 0; + WORD total_groups = GetActiveProcessorGroupCount(); + for (WORD group = 0; group < total_groups; group++){ + DWORD processors_within_group = GetActiveProcessorCount(group); + cores += processors_within_group; + } + return cores; +} + + + + + + + + + +} diff --git a/Common/Cpp/EnumStringMap.h b/Common/Cpp/EnumStringMap.h index 72b110f324..9e24edc861 100644 --- a/Common/Cpp/EnumStringMap.h +++ b/Common/Cpp/EnumStringMap.h @@ -1,70 +1,70 @@ -/* Enum Database - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_EnumStringMap_H -#define PokemonAutomation_EnumStringMap_H - -#include -#include -#include -#include "Common/Cpp/Exceptions.h" - -namespace PokemonAutomation{ - - - -template -class EnumStringMap{ -public: - EnumStringMap(std::initializer_list> x) - : m_enum_to_string(std::move(x)) - { - for (const auto& item : m_enum_to_string){ - auto ret = m_string_to_enum.emplace(item.second, item.first); - if (!ret.second){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Duplicate Enum String: " + item.second - ); - } - } - } - - const std::string& get_string(EnumType type) const{ - auto iter = m_enum_to_string.find(type); - if (iter == m_enum_to_string.end()){ - throw ParseException("Invalid Enum: " + std::to_string((uint64_t)type)); - } - return iter->second; - } - EnumType get_enum(const std::string& str) const{ - auto iter = m_string_to_enum.find(str); - if (iter == m_string_to_enum.end()){ - throw ParseException("Invalid Enum String: " + str); - } - return iter->second; - } - EnumType get_enum(const std::string& str, EnumType default_value) const{ - auto iter = m_string_to_enum.find(str); - return iter == m_string_to_enum.end() ? default_value : iter->second; - } - - auto begin() const{ - return m_enum_to_string.begin(); - } - auto end() const{ - return m_enum_to_string.end(); - } - -private: - std::map m_enum_to_string; - std::map m_string_to_enum; -}; - - - -} -#endif +/* Enum Database + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_EnumStringMap_H +#define PokemonAutomation_EnumStringMap_H + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" + +namespace PokemonAutomation{ + + + +template +class EnumStringMap{ +public: + EnumStringMap(std::initializer_list> x) + : m_enum_to_string(std::move(x)) + { + for (const auto& item : m_enum_to_string){ + auto ret = m_string_to_enum.emplace(item.second, item.first); + if (!ret.second){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Duplicate Enum String: " + item.second + ); + } + } + } + + const std::string& get_string(EnumType type) const{ + auto iter = m_enum_to_string.find(type); + if (iter == m_enum_to_string.end()){ + throw ParseException("Invalid Enum: " + std::to_string((uint64_t)type)); + } + return iter->second; + } + EnumType get_enum(const std::string& str) const{ + auto iter = m_string_to_enum.find(str); + if (iter == m_string_to_enum.end()){ + throw ParseException("Invalid Enum String: " + str); + } + return iter->second; + } + EnumType get_enum(const std::string& str, EnumType default_value) const{ + auto iter = m_string_to_enum.find(str); + return iter == m_string_to_enum.end() ? default_value : iter->second; + } + + auto begin() const{ + return m_enum_to_string.begin(); + } + auto end() const{ + return m_enum_to_string.end(); + } + +private: + std::map m_enum_to_string; + std::map m_string_to_enum; +}; + + + +} +#endif diff --git a/Common/Cpp/EventRateTracker.h b/Common/Cpp/EventRateTracker.h index 3fa284cff1..ba43d0aa53 100644 --- a/Common/Cpp/EventRateTracker.h +++ b/Common/Cpp/EventRateTracker.h @@ -58,13 +58,13 @@ class EventRateTracker{ class UtilizationTracker{ public: - UtilizationTracker(WallClock::duration window = std::chrono::milliseconds(1000)) + UtilizationTracker(WallDuration window = std::chrono::milliseconds(1000)) : m_window(window) , m_min_window(window / 2) , m_running_usage(0) {} - void push_event(WallClock::duration usage_since_last, WallClock timestamp = current_time()){ + void push_event(WallDuration usage_since_last, WallClock timestamp = current_time()){ WallClock threshold = timestamp - m_window; while (m_history.size() > 1){ if (m_history.front().timestamp >= threshold){ @@ -78,13 +78,13 @@ class UtilizationTracker{ } void push_idle(){ m_history.clear(); - m_running_usage = WallClock::duration(0); + m_running_usage = WallDuration(0); } size_t events_in_window() const{ return m_history.size(); } - WallClock::duration usage_in_window() const{ + WallDuration usage_in_window() const{ return m_running_usage; } double utilization() const{ @@ -107,14 +107,14 @@ class UtilizationTracker{ private: struct Entry{ WallClock timestamp; - WallClock::duration usage; + WallDuration usage; }; - WallClock::duration m_window; - WallClock::duration m_min_window; + WallDuration m_window; + WallDuration m_min_window; std::deque m_history; - WallClock::duration m_running_usage; + WallDuration m_running_usage; }; diff --git a/Common/Cpp/ExpressionEvaluator.cpp b/Common/Cpp/ExpressionEvaluator.cpp index 9ec2d3afa4..a40879ab4e 100644 --- a/Common/Cpp/ExpressionEvaluator.cpp +++ b/Common/Cpp/ExpressionEvaluator.cpp @@ -1,373 +1,373 @@ -/* Simple (and incomplete) Expression Evaluator - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "ExpressionEvaluator.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -bool is_whitespace(char ch){ - switch (ch){ - case ' ': return true; - case '\t': return true; - case '\r': return true; - case '\n': return true; - case '\0': return true; - } - return false; -} -bool is_digit(char ch){ - return '0' <= ch && ch <= '9'; -} -bool is_symbol(char ch){ - if ('a' <= ch && ch <= 'z'){ - return true; - } - if ('A' <= ch && ch <= 'Z'){ - return true; - } - if (ch == '_'){ - return true; - } - return false; -} -bool skip_whitespace(const char*& str){ - while (true){ - char ch = *str; - if (ch == '\0'){ - return true; - } - if (!is_whitespace(ch)){ - return false; - } - str++; - } -} - -template -T checked_multiply(T x, T y){ - if (x == 0 || y == 0){ - return 0; - } - T ret = x * y; - if (ret / x != y){ - throw ParseException("Overflow"); - } - return ret; -} -template -T checked_add(T x, T y){ - if constexpr (std::is_unsigned_v){ - T ret = x + y; - if (ret < x){ - throw ParseException("Overflow"); - } - return ret; - }else{ - if (x >= 0 && std::numeric_limits::max() - x < y){ - throw ParseException("Overflow"); - } - if (x < 0 && y < std::numeric_limits::min() - x){ - throw ParseException("Overflow"); - } - return x + y; - } -} -template -T checked_sub(T x, T y){ - if (x >= 0 && x - std::numeric_limits::max() > y){ - throw ParseException("Overflow"); - } - if (x < 0 && y > x - std::numeric_limits::min()){ - throw ParseException("Overflow"); - } - return x - y; -} - -template -T parse_integer(const char*& str){ - const char* ptr = str; - - T x = 0; - while (true){ - char ch = *str; - if (is_whitespace(ch)){ - return x; - } - if (is_digit(ch)){ - x = checked_multiply(x, 10); - x = checked_add(x, ch - '0'); - str++; - continue; - } - switch (ch){ - case '+': - case '-': - case '*': - case ')': - return x; - } - if (is_symbol(ch)){ - return x; - } - throw ParseException(std::string("Invalid integer: ") + ptr); - } -} -std::string parse_symbol(const char*& str){ - const char* ptr = str; - - std::string ret; - ret += *str++; - while (true){ - char ch = *str; - if (is_whitespace(ch)){ - return ret; - } - if (is_symbol(ch)){ - ret += ch; - str++; - continue; - } - if (is_digit(ch)){ - ret += ch; - str++; - continue; - } - switch (ch){ - case '+': - case '-': - case '*': - case ')': - return ret; - } - throw ParseException(std::string("Invalid symbol: ") + ptr); - } -} - -uint8_t precedence(char ch){ - switch (ch){ - case '+': - case '-': - return 0; - case '*': - return 1; - } - throw ParseException(std::string("Invalid operator: ") + ch); -} - -int64_t parse_expression( - const std::map& variables, - const std::string& expression -){ - const char* str = expression.c_str(); - - std::vector> num; - std::vector op; - - size_t consecutive_values = 0; - while (true){ - // Consecutive values is an implied multiply. - if (consecutive_values > 1){ - consecutive_values = 0; - op.push_back('*'); - while (op.size() >= 2){ - char top = op.back(); - char next = op[op.size() - 2]; - uint8_t p_top = precedence(top); - uint8_t p_next = precedence(next); - if (p_top > p_next){ - break; - } - op.pop_back(); - op.pop_back(); - num.emplace_back(next, 0); - op.push_back(top); - if (p_top == p_next){ - break; - } - } - continue; - } - - if (skip_whitespace(str)){ - break; - } - char ch = *str; -// cout << "ch = " << ch << endl; - - - if (is_digit(ch)){ - consecutive_values++; - num.emplace_back('\0', parse_integer(str)); - continue; - } - if (is_symbol(ch)){ - consecutive_values++; - std::string symbol = parse_symbol(str); - auto iter = variables.find(symbol); - if (iter == variables.end()){ - throw ParseException("Undefined Symbol: " + symbol); - } - num.emplace_back('\0', iter->second); - continue; - } - if (ch == '+' || ch == '-' || ch == '*'){ - consecutive_values = 0; - op.push_back(ch); - str++; - while (op.size() >= 2){ - char top = op.back(); - char next = op[op.size() - 2]; - uint8_t p_top = precedence(top); - uint8_t p_next = precedence(next); - if (p_top > p_next){ - break; - } - op.pop_back(); - op.pop_back(); - num.emplace_back(next, 0); - op.push_back(top); - if (p_top == p_next){ - break; - } - } - continue; - } - // if (ch == '('){ - // - // } - // if (ch == ')'){ - // - // } - throw ParseException("Invalid expression: " + expression); - } - - while (!op.empty()){ - num.emplace_back(op.back(), 0); - op.pop_back(); - } - -#if 0 - cout << "operands: "; - for (const auto& item : num){ - if (item.first == 0){ - cout << item.second << " "; - }else{ - cout << item.first << " "; - } - } - cout << endl; - //cout << "operators: "; - //for (const auto& item : op){ - // cout << item << " "; - //} - //cout << endl; -#endif - - std::vector stack; - for (const auto& item : num){ - if (item.first == 0){ - stack.push_back(item.second); - num.pop_back(); - continue; - } - switch (item.first){ - case '+':{ - if (stack.size() < 2){ - throw ParseException("Invalid expression: unexpected +"); - } - int64_t x = stack[stack.size() - 2]; - int64_t y = stack[stack.size() - 1]; - stack.pop_back(); - stack.pop_back(); - - x = checked_add(x, y); - stack.push_back(x); - continue; - } - case '-':{ - if (stack.size() == 0){ - throw ParseException("Invalid expression: unexpected -"); - } - - // If we have at least two integers (x, y) in the stack, perform x - y - // If we have only one integer y in the stack, perform - y (by leaving x = 0) - - int64_t y = stack[stack.size() - 1]; - stack.pop_back(); - - int64_t x = 0; - if (stack.size() > 0){ - x = stack[stack.size() - 1]; - stack.pop_back(); - } - x = checked_sub(x, y); - stack.push_back(x); - continue; - } - case '*':{ - if (stack.size() < 2){ - throw ParseException("Invalid expression: unexpected *"); - } - int64_t x = stack[stack.size() - 2]; - int64_t y = stack[stack.size() - 1]; - stack.pop_back(); - stack.pop_back(); - x = checked_multiply(x, y); - stack.push_back(x); - continue; - } - } - throw ParseException("Invalid operator."); - } - if (stack.size() != 1){ - throw ParseException("Invalid expression."); - } - - return stack[0]; -} - -const std::map& SYMBOLS(){ - static const std::map SYMBOLS{ - {"TICKS_PER_SECOND", 125}, - }; - return SYMBOLS; -} - - -uint32_t parse_ticks_ui32(const std::string& expression){ - int64_t x = parse_expression(SYMBOLS(), expression); - if (x < 0){ - throw ParseException("Value cannot be negative."); - } - if ((int32_t)x != x){ - throw ParseException("Overflow"); - } - return (int32_t)x; -} - - -int32_t parse_ticks_i32(const std::string& expression){ - int64_t x = parse_expression(SYMBOLS(), expression); - if ((int32_t)x != x){ - throw ParseException("Overflow"); - } - return (int32_t)x; -} - - -} - - +/* Simple (and incomplete) Expression Evaluator + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "ExpressionEvaluator.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +bool is_whitespace(char ch){ + switch (ch){ + case ' ': return true; + case '\t': return true; + case '\r': return true; + case '\n': return true; + case '\0': return true; + } + return false; +} +bool is_digit(char ch){ + return '0' <= ch && ch <= '9'; +} +bool is_symbol(char ch){ + if ('a' <= ch && ch <= 'z'){ + return true; + } + if ('A' <= ch && ch <= 'Z'){ + return true; + } + if (ch == '_'){ + return true; + } + return false; +} +bool skip_whitespace(const char*& str){ + while (true){ + char ch = *str; + if (ch == '\0'){ + return true; + } + if (!is_whitespace(ch)){ + return false; + } + str++; + } +} + +template +T checked_multiply(T x, T y){ + if (x == 0 || y == 0){ + return 0; + } + T ret = x * y; + if (ret / x != y){ + throw ParseException("Overflow"); + } + return ret; +} +template +T checked_add(T x, T y){ + if constexpr (std::is_unsigned_v){ + T ret = x + y; + if (ret < x){ + throw ParseException("Overflow"); + } + return ret; + }else{ + if (x >= 0 && std::numeric_limits::max() - x < y){ + throw ParseException("Overflow"); + } + if (x < 0 && y < std::numeric_limits::min() - x){ + throw ParseException("Overflow"); + } + return x + y; + } +} +template +T checked_sub(T x, T y){ + if (x >= 0 && x - std::numeric_limits::max() > y){ + throw ParseException("Overflow"); + } + if (x < 0 && y > x - std::numeric_limits::min()){ + throw ParseException("Overflow"); + } + return x - y; +} + +template +T parse_integer(const char*& str){ + const char* ptr = str; + + T x = 0; + while (true){ + char ch = *str; + if (is_whitespace(ch)){ + return x; + } + if (is_digit(ch)){ + x = checked_multiply(x, 10); + x = checked_add(x, ch - '0'); + str++; + continue; + } + switch (ch){ + case '+': + case '-': + case '*': + case ')': + return x; + } + if (is_symbol(ch)){ + return x; + } + throw ParseException(std::string("Invalid integer: ") + ptr); + } +} +std::string parse_symbol(const char*& str){ + const char* ptr = str; + + std::string ret; + ret += *str++; + while (true){ + char ch = *str; + if (is_whitespace(ch)){ + return ret; + } + if (is_symbol(ch)){ + ret += ch; + str++; + continue; + } + if (is_digit(ch)){ + ret += ch; + str++; + continue; + } + switch (ch){ + case '+': + case '-': + case '*': + case ')': + return ret; + } + throw ParseException(std::string("Invalid symbol: ") + ptr); + } +} + +uint8_t precedence(char ch){ + switch (ch){ + case '+': + case '-': + return 0; + case '*': + return 1; + } + throw ParseException(std::string("Invalid operator: ") + ch); +} + +int64_t parse_expression( + const std::map& variables, + const std::string& expression +){ + const char* str = expression.c_str(); + + std::vector> num; + std::vector op; + + size_t consecutive_values = 0; + while (true){ + // Consecutive values is an implied multiply. + if (consecutive_values > 1){ + consecutive_values = 0; + op.push_back('*'); + while (op.size() >= 2){ + char top = op.back(); + char next = op[op.size() - 2]; + uint8_t p_top = precedence(top); + uint8_t p_next = precedence(next); + if (p_top > p_next){ + break; + } + op.pop_back(); + op.pop_back(); + num.emplace_back(next, 0); + op.push_back(top); + if (p_top == p_next){ + break; + } + } + continue; + } + + if (skip_whitespace(str)){ + break; + } + char ch = *str; +// cout << "ch = " << ch << endl; + + + if (is_digit(ch)){ + consecutive_values++; + num.emplace_back('\0', parse_integer(str)); + continue; + } + if (is_symbol(ch)){ + consecutive_values++; + std::string symbol = parse_symbol(str); + auto iter = variables.find(symbol); + if (iter == variables.end()){ + throw ParseException("Undefined Symbol: " + symbol); + } + num.emplace_back('\0', iter->second); + continue; + } + if (ch == '+' || ch == '-' || ch == '*'){ + consecutive_values = 0; + op.push_back(ch); + str++; + while (op.size() >= 2){ + char top = op.back(); + char next = op[op.size() - 2]; + uint8_t p_top = precedence(top); + uint8_t p_next = precedence(next); + if (p_top > p_next){ + break; + } + op.pop_back(); + op.pop_back(); + num.emplace_back(next, 0); + op.push_back(top); + if (p_top == p_next){ + break; + } + } + continue; + } + // if (ch == '('){ + // + // } + // if (ch == ')'){ + // + // } + throw ParseException("Invalid expression: " + expression); + } + + while (!op.empty()){ + num.emplace_back(op.back(), 0); + op.pop_back(); + } + +#if 0 + cout << "operands: "; + for (const auto& item : num){ + if (item.first == 0){ + cout << item.second << " "; + }else{ + cout << item.first << " "; + } + } + cout << endl; + //cout << "operators: "; + //for (const auto& item : op){ + // cout << item << " "; + //} + //cout << endl; +#endif + + std::vector stack; + for (const auto& item : num){ + if (item.first == 0){ + stack.push_back(item.second); + num.pop_back(); + continue; + } + switch (item.first){ + case '+':{ + if (stack.size() < 2){ + throw ParseException("Invalid expression: unexpected +"); + } + int64_t x = stack[stack.size() - 2]; + int64_t y = stack[stack.size() - 1]; + stack.pop_back(); + stack.pop_back(); + + x = checked_add(x, y); + stack.push_back(x); + continue; + } + case '-':{ + if (stack.size() == 0){ + throw ParseException("Invalid expression: unexpected -"); + } + + // If we have at least two integers (x, y) in the stack, perform x - y + // If we have only one integer y in the stack, perform - y (by leaving x = 0) + + int64_t y = stack[stack.size() - 1]; + stack.pop_back(); + + int64_t x = 0; + if (stack.size() > 0){ + x = stack[stack.size() - 1]; + stack.pop_back(); + } + x = checked_sub(x, y); + stack.push_back(x); + continue; + } + case '*':{ + if (stack.size() < 2){ + throw ParseException("Invalid expression: unexpected *"); + } + int64_t x = stack[stack.size() - 2]; + int64_t y = stack[stack.size() - 1]; + stack.pop_back(); + stack.pop_back(); + x = checked_multiply(x, y); + stack.push_back(x); + continue; + } + } + throw ParseException("Invalid operator."); + } + if (stack.size() != 1){ + throw ParseException("Invalid expression."); + } + + return stack[0]; +} + +const std::map& SYMBOLS(){ + static const std::map SYMBOLS{ + {"TICKS_PER_SECOND", 125}, + }; + return SYMBOLS; +} + + +uint32_t parse_ticks_ui32(const std::string& expression){ + int64_t x = parse_expression(SYMBOLS(), expression); + if (x < 0){ + throw ParseException("Value cannot be negative."); + } + if ((int32_t)x != x){ + throw ParseException("Overflow"); + } + return (int32_t)x; +} + + +int32_t parse_ticks_i32(const std::string& expression){ + int64_t x = parse_expression(SYMBOLS(), expression); + if ((int32_t)x != x){ + throw ParseException("Overflow"); + } + return (int32_t)x; +} + + +} + + diff --git a/Common/Cpp/ExpressionEvaluator.h b/Common/Cpp/ExpressionEvaluator.h index 0185915e6c..01061f9886 100644 --- a/Common/Cpp/ExpressionEvaluator.h +++ b/Common/Cpp/ExpressionEvaluator.h @@ -1,24 +1,24 @@ -/* Simple (and incomplete) Expression Evaluator - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include - -namespace PokemonAutomation{ - - - -int64_t parse_expression( - const std::map& variables, - const std::string& expression -); - -uint32_t parse_ticks_ui32(const std::string& expression); -int32_t parse_ticks_i32(const std::string& expression); - - -} +/* Simple (and incomplete) Expression Evaluator + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include + +namespace PokemonAutomation{ + + + +int64_t parse_expression( + const std::map& variables, + const std::string& expression +); + +uint32_t parse_ticks_ui32(const std::string& expression); +int32_t parse_ticks_i32(const std::string& expression); + + +} diff --git a/Common/Cpp/LifetimeSanitizer.cpp b/Common/Cpp/LifetimeSanitizer.cpp index d49357476a..6de5789d30 100644 --- a/Common/Cpp/LifetimeSanitizer.cpp +++ b/Common/Cpp/LifetimeSanitizer.cpp @@ -105,14 +105,14 @@ void LifetimeSanitizer::check_usage() const{ return; } ReadSpinLock lg(sanitizer_lock); - if (SANITIZER_FILTER.contains(m_name)){ - std::cout << "LifetimeSanitizer - Using: " << this << " : " << m_name << std::endl; - } auto iter = sanitizer_map.find(this); if (iter == sanitizer_map.end()){ - std::cerr << "Use non-existent: " << this << " : " << m_name << std::endl; + std::cerr << "Use non-existent: " << this << std::endl; terminate_with_dump(); } + if (SANITIZER_FILTER.contains(m_name)){ + std::cout << "LifetimeSanitizer - Using: " << this << " : " << m_name << std::endl; + } if (m_token != SANITIZER_TOKEN || m_self != this){ std::cerr << "Use corrupted: " << this << " : " << m_name << std::endl; terminate_with_dump(); @@ -123,14 +123,14 @@ void LifetimeSanitizer::start_using() const{ return; } ReadSpinLock lg(sanitizer_lock); - if (SANITIZER_FILTER.contains(m_name)){ - std::cout << "LifetimeSanitizer - Start using: " << this << " : " << m_name << std::endl; - } auto iter = sanitizer_map.find(this); if (iter == sanitizer_map.end()){ - std::cerr << "Start using non-existent: " << this << " : " << m_name << std::endl; + std::cerr << "Start using non-existent: " << this << std::endl; terminate_with_dump(); } + if (SANITIZER_FILTER.contains(m_name)){ + std::cout << "LifetimeSanitizer - Start using: " << this << " : " << m_name << std::endl; + } if (m_token != SANITIZER_TOKEN || m_self != this){ std::cerr << "Start using corrupted: " << this << " : " << m_name << std::endl; terminate_with_dump(); @@ -142,14 +142,14 @@ void LifetimeSanitizer::done_using() const{ return; } ReadSpinLock lg(sanitizer_lock); - if (SANITIZER_FILTER.contains(m_name)){ - std::cout << "LifetimeSanitizer - Done using: " << this << " : " << m_name << std::endl; - } auto iter = sanitizer_map.find(this); if (iter == sanitizer_map.end()){ - std::cerr << "Done using non-existent: " << this << " : " << m_name << std::endl; + std::cerr << "Done using non-existent: " << this << std::endl; terminate_with_dump(); } + if (SANITIZER_FILTER.contains(m_name)){ + std::cout << "LifetimeSanitizer - Done using: " << this << " : " << m_name << std::endl; + } if (m_token != SANITIZER_TOKEN || m_self != this){ std::cerr << "Done using corrupted: " << this << " : " << m_name << std::endl; terminate_with_dump(); diff --git a/Common/Cpp/ListenerSet.h b/Common/Cpp/ListenerSet.h index 8e39c1a9fe..c3922fd7fe 100644 --- a/Common/Cpp/ListenerSet.h +++ b/Common/Cpp/ListenerSet.h @@ -1,119 +1,145 @@ -/* Listener Set - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ListenerSet_H -#define PokemonAutomation_ListenerSet_H - -#include -#include -#include "Common/Cpp/Concurrency/SpinLock.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -template -class ListenerSet{ -public: - bool empty() const{ - return m_count.load(std::memory_order_relaxed) == 0; - } - size_t count_unique() const{ - return m_count.load(std::memory_order_relaxed); - } - - void add(ListenerType& listener){ - WriteSpinLock lg(m_lock); -// std::lock_guard lg(m_lock); - m_listeners[&listener]++; - m_count.store(m_listeners.size(), std::memory_order_relaxed); - } - void remove(ListenerType& listener){ - WriteSpinLock lg(m_lock); -// std::lock_guard lg(m_lock); - auto iter = m_listeners.find(&listener); - if (iter == m_listeners.end()){ - return; - } - if (--iter->second == 0){ - m_listeners.erase(iter); - } - m_count.store(m_listeners.size(), std::memory_order_relaxed); - } - - template - void run_lambda_unique(Lambda&& lambda){ - if (empty()){ - return; - } - ReadSpinLock lg(m_lock); -// std::lock_guard lg(m_lock); - for (auto& item : m_listeners){ - lambda(*item.first); - } - } - template - void run_lambda_with_duplicates(Lambda&& lambda){ - if (empty()){ - return; - } - ReadSpinLock lg(m_lock); -// std::lock_guard lg(m_lock); - for (auto& item : m_listeners){ - ListenerType& listener = *item.first; - size_t count = item.second; - do{ - lambda(listener); - }while (--count); - } - } - - template - void run_method_unique(Function function, Args&&... args){ - if (empty()){ - return; - } - ReadSpinLock lg(m_lock); -// std::lock_guard lg(m_lock); - for (auto& item : m_listeners){ - (item.first->*function)(std::forward(args)...); - } - } - template - void run_method_with_duplicates(Function function, Args&&... args){ - if (empty()){ - return; - } - ReadSpinLock lg(m_lock); -// std::lock_guard lg(m_lock); - for (auto& item : m_listeners){ - ListenerType& listener = *item.first; - size_t count = item.second; - do{ - (listener->*function)(std::forward(args)...); - }while (--count); - } - } - -private: - // Optimization. Keep an atomic version of the count. This will let us - // skip the lock when there are no listeners. - std::atomic m_count; - - mutable SpinLock m_lock; -// mutable std::mutex m_lock; - std::map m_listeners; -}; - - - - -} -#endif +/* Listener Set + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ListenerSet_H +#define PokemonAutomation_ListenerSet_H + +#include +#include +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Cpp/LifetimeSanitizer.h" + +//#include +//using std::cout; +//using std::endl; + +//#define PA_DEBUG_ListenerSet + + +namespace PokemonAutomation{ + + + +template +class ListenerSet{ +public: + bool empty() const{ + return m_count.load(std::memory_order_relaxed) == 0; + } + size_t count_unique() const{ + return m_count.load(std::memory_order_relaxed); + } + + void add(ListenerType& listener){ +#ifdef PA_DEBUG_ListenerSet + auto scope = m_sanitizer.check_scope(); +#endif + WriteSpinLock lg(m_lock); +// std::lock_guard lg(m_lock); + m_listeners[&listener]++; + m_count.store(m_listeners.size(), std::memory_order_relaxed); + } + void remove(ListenerType& listener){ +#ifdef PA_DEBUG_ListenerSet + auto scope = m_sanitizer.check_scope(); +#endif + WriteSpinLock lg(m_lock); +// std::lock_guard lg(m_lock); + auto iter = m_listeners.find(&listener); + if (iter == m_listeners.end()){ + return; + } + if (--iter->second == 0){ + m_listeners.erase(iter); + } + m_count.store(m_listeners.size(), std::memory_order_relaxed); + } + + template + void run_lambda_unique(Lambda&& lambda){ +#ifdef PA_DEBUG_ListenerSet + auto scope = m_sanitizer.check_scope(); +#endif + if (empty()){ + return; + } + ReadSpinLock lg(m_lock); +// std::lock_guard lg(m_lock); + for (auto& item : m_listeners){ + lambda(*item.first); + } + } + template + void run_lambda_with_duplicates(Lambda&& lambda){ +#ifdef PA_DEBUG_ListenerSet + auto scope = m_sanitizer.check_scope(); +#endif + if (empty()){ + return; + } + ReadSpinLock lg(m_lock); +// std::lock_guard lg(m_lock); + for (auto& item : m_listeners){ + ListenerType& listener = *item.first; + size_t count = item.second; + do{ + lambda(listener); + }while (--count); + } + } + + template + void run_method_unique(Function function, Args&&... args){ +#ifdef PA_DEBUG_ListenerSet + auto scope = m_sanitizer.check_scope(); +#endif + if (empty()){ + return; + } + ReadSpinLock lg(m_lock); +// std::lock_guard lg(m_lock); + for (auto& item : m_listeners){ + (item.first->*function)(std::forward(args)...); + } + } + template + void run_method_with_duplicates(Function function, Args&&... args){ +#ifdef PA_DEBUG_ListenerSet + auto scope = m_sanitizer.check_scope(); +#endif + if (empty()){ + return; + } + ReadSpinLock lg(m_lock); +// std::lock_guard lg(m_lock); + for (auto& item : m_listeners){ + ListenerType& listener = *item.first; + size_t count = item.second; + do{ + (listener->*function)(std::forward(args)...); + }while (--count); + } + } + +private: + // Optimization. Keep an atomic version of the count. This will let us + // skip the lock when there are no listeners. + std::atomic m_count; + + mutable SpinLock m_lock; +// mutable std::mutex m_lock; + std::map m_listeners; + +#ifdef PA_DEBUG_ListenerSet + LifetimeSanitizer m_sanitizer; +#endif +}; + + + + +} +#endif diff --git a/Common/Cpp/Options/ColorOption.cpp b/Common/Cpp/Options/ColorOption.cpp index a4cdbb5f32..8d6a61dce9 100644 --- a/Common/Cpp/Options/ColorOption.cpp +++ b/Common/Cpp/Options/ColorOption.cpp @@ -1,126 +1,126 @@ -/* Color Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" - #include "ColorOption.h" - -namespace PokemonAutomation{ - - -ColorCell::ColorCell(const ColorCell& x) - : ConfigOption(x) - , m_default_value(x.m_default_value) - , m_current_value(x) -{} -ColorCell::ColorCell( - LockMode lock_while_running, - bool has_alpha, - uint32_t default_value, uint32_t current_value -) - : ConfigOption(lock_while_running) - , m_has_alpha(has_alpha) - , m_default_value(default_value) - , m_current_value(current_value) -{ - if (!m_has_alpha){ - m_default_value &= 0x00ffffff; - m_current_value &= 0x00ffffff; - } -} -uint32_t ColorCell::default_value() const{ - return m_default_value; -} -std::string ColorCell::to_str() const{ - return color_to_str(*this, m_has_alpha); -} -std::string ColorCell::color_to_str(uint32_t color, bool has_alpha){ - static const char HEX_DIGITS[] = "0123456789ABCDEF"; - std::string str; - if (has_alpha){ - str += HEX_DIGITS[(color >> 28) & 0xf]; - str += HEX_DIGITS[(color >> 24) & 0xf]; - } - str += HEX_DIGITS[(color >> 20) & 0xf]; - str += HEX_DIGITS[(color >> 16) & 0xf]; - str += HEX_DIGITS[(color >> 12) & 0xf]; - str += HEX_DIGITS[(color >> 8) & 0xf]; - str += HEX_DIGITS[(color >> 4) & 0xf]; - str += HEX_DIGITS[(color >> 0) & 0xf]; - return str; -} -ColorCell::operator uint32_t() const{ - return m_current_value.load(std::memory_order_relaxed); -} -void ColorCell::set(uint32_t x){ - if (!m_has_alpha){ - x &= 0x00ffffff; - } - if (x != m_current_value.exchange(x, std::memory_order_relaxed)){ - report_value_changed(this); - } -} -void ColorCell::set(const std::string& str){ - size_t max_digits = m_has_alpha ? 8 : 6; - - uint32_t x = 0; - size_t count = 0; - for (char ch : str){ - if (count >= max_digits){ - break; - } - switch (ch){ - case '\0': - break; - case '-': - case ':': - case ' ': - continue; - } - - if ('0' <= ch && ch <= '9'){ - x <<= 4; - x |= ch - '0'; - count++; - continue; - } - if ('a' <= ch && ch <= 'f'){ - x <<= 4; - x |= ch - 'a' + 10; - count++; - continue; - } - if ('A' <= ch && ch <= 'F'){ - x <<= 4; - x |= ch - 'A' + 10; - count++; - continue; - } - - break; - } - if (!m_has_alpha){ - x &= 0x00ffffff; - } - set(x); -} - -void ColorCell::load_json(const JsonValue& json){ - uint32_t value; - if (!json.read_integer(value)){ - return; - } - set(value); -} -JsonValue ColorCell::to_json() const{ - return (uint32_t)*this; -} -void ColorCell::restore_defaults(){ - set(m_default_value); -} - - - -} +/* Color Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" + #include "ColorOption.h" + +namespace PokemonAutomation{ + + +ColorCell::ColorCell(const ColorCell& x) + : ConfigOption(x) + , m_default_value(x.m_default_value) + , m_current_value(x) +{} +ColorCell::ColorCell( + LockMode lock_while_running, + bool has_alpha, + uint32_t default_value, uint32_t current_value +) + : ConfigOption(lock_while_running) + , m_has_alpha(has_alpha) + , m_default_value(default_value) + , m_current_value(current_value) +{ + if (!m_has_alpha){ + m_default_value &= 0x00ffffff; + m_current_value &= 0x00ffffff; + } +} +uint32_t ColorCell::default_value() const{ + return m_default_value; +} +std::string ColorCell::to_str() const{ + return color_to_str(*this, m_has_alpha); +} +std::string ColorCell::color_to_str(uint32_t color, bool has_alpha){ + static const char HEX_DIGITS[] = "0123456789ABCDEF"; + std::string str; + if (has_alpha){ + str += HEX_DIGITS[(color >> 28) & 0xf]; + str += HEX_DIGITS[(color >> 24) & 0xf]; + } + str += HEX_DIGITS[(color >> 20) & 0xf]; + str += HEX_DIGITS[(color >> 16) & 0xf]; + str += HEX_DIGITS[(color >> 12) & 0xf]; + str += HEX_DIGITS[(color >> 8) & 0xf]; + str += HEX_DIGITS[(color >> 4) & 0xf]; + str += HEX_DIGITS[(color >> 0) & 0xf]; + return str; +} +ColorCell::operator uint32_t() const{ + return m_current_value.load(std::memory_order_relaxed); +} +void ColorCell::set(uint32_t x){ + if (!m_has_alpha){ + x &= 0x00ffffff; + } + if (x != m_current_value.exchange(x, std::memory_order_relaxed)){ + report_value_changed(this); + } +} +void ColorCell::set(const std::string& str){ + size_t max_digits = m_has_alpha ? 8 : 6; + + uint32_t x = 0; + size_t count = 0; + for (char ch : str){ + if (count >= max_digits){ + break; + } + switch (ch){ + case '\0': + break; + case '-': + case ':': + case ' ': + continue; + } + + if ('0' <= ch && ch <= '9'){ + x <<= 4; + x |= ch - '0'; + count++; + continue; + } + if ('a' <= ch && ch <= 'f'){ + x <<= 4; + x |= ch - 'a' + 10; + count++; + continue; + } + if ('A' <= ch && ch <= 'F'){ + x <<= 4; + x |= ch - 'A' + 10; + count++; + continue; + } + + break; + } + if (!m_has_alpha){ + x &= 0x00ffffff; + } + set(x); +} + +void ColorCell::load_json(const JsonValue& json){ + uint32_t value; + if (!json.read_integer(value)){ + return; + } + set(value); +} +JsonValue ColorCell::to_json() const{ + return (uint32_t)*this; +} +void ColorCell::restore_defaults(){ + set(m_default_value); +} + + + +} diff --git a/Common/Cpp/Options/ColorOption.h b/Common/Cpp/Options/ColorOption.h index ec74c83c0b..905063cd33 100644 --- a/Common/Cpp/Options/ColorOption.h +++ b/Common/Cpp/Options/ColorOption.h @@ -1,50 +1,50 @@ -/* Color Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ColorOption_H -#define PokemonAutomation_ColorOption_H - -#include -#include "Common/Cpp/Options/ConfigOption.h" - -namespace PokemonAutomation{ - - - -class ColorCell : public ConfigOption{ -public: - ColorCell(const ColorCell& x); - ColorCell( - LockMode lock_while_running, - bool has_alpha, - uint32_t default_value, uint32_t current_value - ); - - uint32_t default_value() const; - std::string to_str() const; - static std::string color_to_str(uint32_t color, bool has_alpha); - - operator uint32_t() const; - void set(uint32_t x); - void set(const std::string& str); - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - virtual void restore_defaults() override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - - -private: - bool m_has_alpha; - uint32_t m_default_value; - std::atomic m_current_value; -}; - - - -} -#endif +/* Color Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ColorOption_H +#define PokemonAutomation_ColorOption_H + +#include +#include "Common/Cpp/Options/ConfigOption.h" + +namespace PokemonAutomation{ + + + +class ColorCell : public ConfigOption{ +public: + ColorCell(const ColorCell& x); + ColorCell( + LockMode lock_while_running, + bool has_alpha, + uint32_t default_value, uint32_t current_value + ); + + uint32_t default_value() const; + std::string to_str() const; + static std::string color_to_str(uint32_t color, bool has_alpha); + + operator uint32_t() const; + void set(uint32_t x); + void set(const std::string& str); + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + virtual void restore_defaults() override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + + +private: + bool m_has_alpha; + uint32_t m_default_value; + std::atomic m_current_value; +}; + + + +} +#endif diff --git a/Common/Cpp/Options/EnumDropdownDatabase.cpp b/Common/Cpp/Options/EnumDropdownDatabase.cpp index 1bb1834a5e..eaaf066bec 100644 --- a/Common/Cpp/Options/EnumDropdownDatabase.cpp +++ b/Common/Cpp/Options/EnumDropdownDatabase.cpp @@ -1,129 +1,129 @@ -/* Named Enum - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/LifetimeSanitizer.h" -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "EnumDropdownDatabase.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -class IntegerEnumDropdownDatabaseImpl{ -public: - void add(EnumEntry entry){ - auto scope_check = m_sanitizer.check_scope(); - size_t enum_value = entry.enum_value; - m_list.emplace_back(enum_value); - - auto ret = m_map.emplace(enum_value, std::move(entry)); - if (!ret.second){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum: " + std::to_string(enum_value)); - } - - auto ret1 = m_slug_to_enum.emplace(ret.first->second.slug, &ret.first->second); - if (!ret1.second){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum Slug: " + ret.first->second.slug); - } - - auto ret2 = m_display_to_enum.emplace(ret.first->second.display, &ret.first->second); - if (!ret2.second){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum Display: " + ret.first->second.display); - } - } - - const EnumEntry* find(size_t value) const{ - auto scope_check = m_sanitizer.check_scope(); - auto iter = m_map.find(value); - if (iter == m_map.end()){ - return nullptr; - } - return &iter->second; - } - const EnumEntry* find_slug(const std::string& slug) const{ - auto scope_check = m_sanitizer.check_scope(); - auto iter = m_slug_to_enum.find(slug); - if (iter == m_slug_to_enum.end()){ - return nullptr; - } - return iter->second; - } - const EnumEntry* find_display(const std::string& display) const{ - auto scope_check = m_sanitizer.check_scope(); - auto iter = m_display_to_enum.find(display); - if (iter == m_display_to_enum.end()){ - return nullptr; - } - return iter->second; - } - - FixedLimitVector all_values() const{ - auto scope_check = m_sanitizer.check_scope(); - FixedLimitVector ret(m_map.size()); - for (const auto& item : m_map){ - ret.emplace_back(item.first); - } - return ret; - } - -private: - using Node = typename std::map::const_iterator; - std::vector m_list; - std::map m_map; - std::map m_slug_to_enum; - std::map m_display_to_enum; - - LifetimeSanitizer m_sanitizer; -}; - - - -IntegerEnumDropdownDatabase::IntegerEnumDropdownDatabase(IntegerEnumDropdownDatabase&& x) = default; -IntegerEnumDropdownDatabase& IntegerEnumDropdownDatabase::operator=(IntegerEnumDropdownDatabase&& x) = default; -IntegerEnumDropdownDatabase::~IntegerEnumDropdownDatabase() = default; - -IntegerEnumDropdownDatabase::IntegerEnumDropdownDatabase(void*){} -IntegerEnumDropdownDatabase::IntegerEnumDropdownDatabase() - : m_core(CONSTRUCT_TOKEN) -{} -IntegerEnumDropdownDatabase::IntegerEnumDropdownDatabase(std::initializer_list list) - : m_core(CONSTRUCT_TOKEN) -{ - size_t index = 0; - for (auto iter = list.begin(); iter != list.end(); ++iter, index++){ - add(iter->enum_value, std::move(iter->slug), std::move(iter->display), iter->enabled); - } -} -void IntegerEnumDropdownDatabase::add(EnumEntry entry){ - m_core->add(entry); -} -const EnumEntry* IntegerEnumDropdownDatabase::find(size_t value) const{ - return m_core->find(value); -} -const EnumEntry* IntegerEnumDropdownDatabase::find_slug(const std::string& slug) const{ - return m_core->find_slug(slug); -} -const EnumEntry* IntegerEnumDropdownDatabase::find_display(const std::string& display) const{ - return m_core->find_display(display); -} -FixedLimitVector IntegerEnumDropdownDatabase::all_values() const{ - return m_core->all_values(); -} - - -template class FixedLimitVector; - - - -} +/* Named Enum + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/LifetimeSanitizer.h" +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "EnumDropdownDatabase.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +class IntegerEnumDropdownDatabaseImpl{ +public: + void add(EnumEntry entry){ + auto scope_check = m_sanitizer.check_scope(); + size_t enum_value = entry.enum_value; + m_list.emplace_back(enum_value); + + auto ret = m_map.emplace(enum_value, std::move(entry)); + if (!ret.second){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum: " + std::to_string(enum_value)); + } + + auto ret1 = m_slug_to_enum.emplace(ret.first->second.slug, &ret.first->second); + if (!ret1.second){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum Slug: " + ret.first->second.slug); + } + + auto ret2 = m_display_to_enum.emplace(ret.first->second.display, &ret.first->second); + if (!ret2.second){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum Display: " + ret.first->second.display); + } + } + + const EnumEntry* find(size_t value) const{ + auto scope_check = m_sanitizer.check_scope(); + auto iter = m_map.find(value); + if (iter == m_map.end()){ + return nullptr; + } + return &iter->second; + } + const EnumEntry* find_slug(const std::string& slug) const{ + auto scope_check = m_sanitizer.check_scope(); + auto iter = m_slug_to_enum.find(slug); + if (iter == m_slug_to_enum.end()){ + return nullptr; + } + return iter->second; + } + const EnumEntry* find_display(const std::string& display) const{ + auto scope_check = m_sanitizer.check_scope(); + auto iter = m_display_to_enum.find(display); + if (iter == m_display_to_enum.end()){ + return nullptr; + } + return iter->second; + } + + FixedLimitVector all_values() const{ + auto scope_check = m_sanitizer.check_scope(); + FixedLimitVector ret(m_map.size()); + for (const auto& item : m_map){ + ret.emplace_back(item.first); + } + return ret; + } + +private: + using Node = typename std::map::const_iterator; + std::vector m_list; + std::map m_map; + std::map m_slug_to_enum; + std::map m_display_to_enum; + + LifetimeSanitizer m_sanitizer; +}; + + + +IntegerEnumDropdownDatabase::IntegerEnumDropdownDatabase(IntegerEnumDropdownDatabase&& x) = default; +IntegerEnumDropdownDatabase& IntegerEnumDropdownDatabase::operator=(IntegerEnumDropdownDatabase&& x) = default; +IntegerEnumDropdownDatabase::~IntegerEnumDropdownDatabase() = default; + +IntegerEnumDropdownDatabase::IntegerEnumDropdownDatabase(void*){} +IntegerEnumDropdownDatabase::IntegerEnumDropdownDatabase() + : m_core(CONSTRUCT_TOKEN) +{} +IntegerEnumDropdownDatabase::IntegerEnumDropdownDatabase(std::initializer_list list) + : m_core(CONSTRUCT_TOKEN) +{ + size_t index = 0; + for (auto iter = list.begin(); iter != list.end(); ++iter, index++){ + add(iter->enum_value, std::move(iter->slug), std::move(iter->display), iter->enabled); + } +} +void IntegerEnumDropdownDatabase::add(EnumEntry entry){ + m_core->add(entry); +} +const EnumEntry* IntegerEnumDropdownDatabase::find(size_t value) const{ + return m_core->find(value); +} +const EnumEntry* IntegerEnumDropdownDatabase::find_slug(const std::string& slug) const{ + return m_core->find_slug(slug); +} +const EnumEntry* IntegerEnumDropdownDatabase::find_display(const std::string& display) const{ + return m_core->find_display(display); +} +FixedLimitVector IntegerEnumDropdownDatabase::all_values() const{ + return m_core->all_values(); +} + + +template class FixedLimitVector; + + + +} diff --git a/Common/Cpp/Options/EnumDropdownDatabase.h b/Common/Cpp/Options/EnumDropdownDatabase.h index 2e3494d18d..132e29aa21 100644 --- a/Common/Cpp/Options/EnumDropdownDatabase.h +++ b/Common/Cpp/Options/EnumDropdownDatabase.h @@ -1,118 +1,118 @@ -/* Enum Database - * - * From: https://github.com/PokemonAutomation/ - * - * A database that goes with an enum. - * - * This database contains information about the enum such as the display names - * and serialization slugs. - * - * This database is used to initialize an EnumDropdownCell/Option. - * - */ - -#ifndef PokemonAutomation_Options_EnumDropdownDatabase_H -#define PokemonAutomation_Options_EnumDropdownDatabase_H - -#include -#include "Common/Cpp/Containers/Pimpl.h" -#include "Common/Cpp/Containers/FixedLimitVector.h" - -namespace PokemonAutomation{ - -class IntegerEnumDropdownDatabaseImpl; - - - - -struct EnumEntry{ - size_t enum_value; // Integer value of the enum. - std::string slug; - std::string display; - bool enabled = true; -}; - - -// This is the typeless database that uses an integer for the enum value. -class IntegerEnumDropdownDatabase{ -public: - IntegerEnumDropdownDatabase(IntegerEnumDropdownDatabase&& x); - IntegerEnumDropdownDatabase& operator=(IntegerEnumDropdownDatabase&& x); - IntegerEnumDropdownDatabase(const IntegerEnumDropdownDatabase& x) = delete; - IntegerEnumDropdownDatabase& operator=(const IntegerEnumDropdownDatabase& x) = delete; - ~IntegerEnumDropdownDatabase(); - -public: - IntegerEnumDropdownDatabase(); // Constructs empty database. - IntegerEnumDropdownDatabase(std::initializer_list list); - - void add(EnumEntry entry); - void add(size_t value, std::string slug, std::string display, bool enabled){ - add(EnumEntry{value, std::move(slug), std::move(display), enabled}); - } - - // Find an enum. Returns null if not in the database. - const EnumEntry* find(size_t value) const; - const EnumEntry* find_slug(const std::string& slug) const; - const EnumEntry* find_display(const std::string& display) const; - - // Returns the integer enum values of everything in the database. - FixedLimitVector all_values() const; - -protected: - IntegerEnumDropdownDatabase(void*); // Constructs null database. -private: - Pimpl m_core; -}; - - - -// This is the type-safe database for your specific enum. -template -class EnumDropdownDatabase : public IntegerEnumDropdownDatabase{ -public: - struct Entry{ - EnumType value; - std::string slug; - std::string display; - bool enabled = true; - }; - -//public: -// EnumDropdownDatabase(EnumDropdownDatabase&& x) = default; -// EnumDropdownDatabase& operator=(EnumDropdownDatabase&& x) = default; - -public: - EnumDropdownDatabase() : IntegerEnumDropdownDatabase() {} - EnumDropdownDatabase(std::initializer_list list){ - size_t index = 0; - for (auto iter = list.begin(); iter != list.end(); ++iter, index++){ - add(iter->value, std::move(iter->slug), std::move(iter->display), iter->enabled); - } - } - - void add(EnumType value, std::string slug, std::string display, bool enabled){ - IntegerEnumDropdownDatabase::add(EnumEntry{(size_t)value, std::move(slug), std::move(display), enabled}); - } - - // Find an enum. Returns null if not in the database. - const EnumEntry* find(EnumType value) const{ - return IntegerEnumDropdownDatabase::find((size_t)value); - } - EnumType find_slug(const std::string& slug) const{ - return (EnumType)IntegerEnumDropdownDatabase::find_slug(slug); - } - EnumType find_display(const std::string& display) const{ - return (EnumType)IntegerEnumDropdownDatabase::find_display(display); - } - -protected: - EnumDropdownDatabase(void*) : IntegerEnumDropdownDatabase(nullptr) {} -}; - - - - - -} -#endif +/* Enum Database + * + * From: https://github.com/PokemonAutomation/ + * + * A database that goes with an enum. + * + * This database contains information about the enum such as the display names + * and serialization slugs. + * + * This database is used to initialize an EnumDropdownCell/Option. + * + */ + +#ifndef PokemonAutomation_Options_EnumDropdownDatabase_H +#define PokemonAutomation_Options_EnumDropdownDatabase_H + +#include +#include "Common/Cpp/Containers/Pimpl.h" +#include "Common/Cpp/Containers/FixedLimitVector.h" + +namespace PokemonAutomation{ + +class IntegerEnumDropdownDatabaseImpl; + + + + +struct EnumEntry{ + size_t enum_value; // Integer value of the enum. + std::string slug; + std::string display; + bool enabled = true; +}; + + +// This is the typeless database that uses an integer for the enum value. +class IntegerEnumDropdownDatabase{ +public: + IntegerEnumDropdownDatabase(IntegerEnumDropdownDatabase&& x); + IntegerEnumDropdownDatabase& operator=(IntegerEnumDropdownDatabase&& x); + IntegerEnumDropdownDatabase(const IntegerEnumDropdownDatabase& x) = delete; + IntegerEnumDropdownDatabase& operator=(const IntegerEnumDropdownDatabase& x) = delete; + ~IntegerEnumDropdownDatabase(); + +public: + IntegerEnumDropdownDatabase(); // Constructs empty database. + IntegerEnumDropdownDatabase(std::initializer_list list); + + void add(EnumEntry entry); + void add(size_t value, std::string slug, std::string display, bool enabled){ + add(EnumEntry{value, std::move(slug), std::move(display), enabled}); + } + + // Find an enum. Returns null if not in the database. + const EnumEntry* find(size_t value) const; + const EnumEntry* find_slug(const std::string& slug) const; + const EnumEntry* find_display(const std::string& display) const; + + // Returns the integer enum values of everything in the database. + FixedLimitVector all_values() const; + +protected: + IntegerEnumDropdownDatabase(void*); // Constructs null database. +private: + Pimpl m_core; +}; + + + +// This is the type-safe database for your specific enum. +template +class EnumDropdownDatabase : public IntegerEnumDropdownDatabase{ +public: + struct Entry{ + EnumType value; + std::string slug; + std::string display; + bool enabled = true; + }; + +//public: +// EnumDropdownDatabase(EnumDropdownDatabase&& x) = default; +// EnumDropdownDatabase& operator=(EnumDropdownDatabase&& x) = default; + +public: + EnumDropdownDatabase() : IntegerEnumDropdownDatabase() {} + EnumDropdownDatabase(std::initializer_list list){ + size_t index = 0; + for (auto iter = list.begin(); iter != list.end(); ++iter, index++){ + add(iter->value, std::move(iter->slug), std::move(iter->display), iter->enabled); + } + } + + void add(EnumType value, std::string slug, std::string display, bool enabled){ + IntegerEnumDropdownDatabase::add(EnumEntry{(size_t)value, std::move(slug), std::move(display), enabled}); + } + + // Find an enum. Returns null if not in the database. + const EnumEntry* find(EnumType value) const{ + return IntegerEnumDropdownDatabase::find((size_t)value); + } + EnumType find_slug(const std::string& slug) const{ + return (EnumType)IntegerEnumDropdownDatabase::find_slug(slug); + } + EnumType find_display(const std::string& display) const{ + return (EnumType)IntegerEnumDropdownDatabase::find_display(display); + } + +protected: + EnumDropdownDatabase(void*) : IntegerEnumDropdownDatabase(nullptr) {} +}; + + + + + +} +#endif diff --git a/Common/Cpp/Options/KeyBindingOption.cpp b/Common/Cpp/Options/KeyBindingOption.cpp index 664774e087..a24074e0ff 100644 --- a/Common/Cpp/Options/KeyBindingOption.cpp +++ b/Common/Cpp/Options/KeyBindingOption.cpp @@ -1,82 +1,82 @@ -/* Key Binding Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "KeyBindingOption.h" - -namespace PokemonAutomation{ - - - -struct KeyBindingCell::Data{ - const uint32_t m_default; - - mutable SpinLock m_lock; - uint32_t m_current; - std::string m_current_text; - - Data(uint32_t default_value) - : m_default(default_value) - , m_current(default_value) - {} -}; - - - -KeyBindingCell::~KeyBindingCell(){ - -} -KeyBindingCell::KeyBindingCell(LockMode lock_while_program_is_running) - : ConfigOption(lock_while_program_is_running) - , m_data(CONSTRUCT_TOKEN, 0) -{} - - -KeyBindingCell::operator uint32_t() const{ - ReadSpinLock lg(m_data->m_lock); - return m_data->m_current; -} -KeyBindingCell::operator std::string() const{ - ReadSpinLock lg(m_data->m_lock); - return m_data->m_current_text; -} -void KeyBindingCell::set(uint32_t key){ - { - ReadSpinLock lg(m_data->m_lock); - m_data->m_current = key; - } - report_value_changed(this); -} -void KeyBindingCell::set(std::string text){ - ReadSpinLock lg(m_data->m_lock); - m_data->m_current_text = std::move(text); -} - - - -void KeyBindingCell::load_json(const JsonValue& json){ - set((uint32_t)json.to_integer_default(0)); -} -JsonValue KeyBindingCell::to_json() const{ - ReadSpinLock lg(m_data->m_lock); - return m_data->m_current; -} - -void KeyBindingCell::restore_defaults(){ - set(m_data->m_default); -} - - - - - - - - - -} +/* Key Binding Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "KeyBindingOption.h" + +namespace PokemonAutomation{ + + + +struct KeyBindingCell::Data{ + const uint32_t m_default; + + mutable SpinLock m_lock; + uint32_t m_current; + std::string m_current_text; + + Data(uint32_t default_value) + : m_default(default_value) + , m_current(default_value) + {} +}; + + + +KeyBindingCell::~KeyBindingCell(){ + +} +KeyBindingCell::KeyBindingCell(LockMode lock_while_program_is_running) + : ConfigOption(lock_while_program_is_running) + , m_data(CONSTRUCT_TOKEN, 0) +{} + + +KeyBindingCell::operator uint32_t() const{ + ReadSpinLock lg(m_data->m_lock); + return m_data->m_current; +} +KeyBindingCell::operator std::string() const{ + ReadSpinLock lg(m_data->m_lock); + return m_data->m_current_text; +} +void KeyBindingCell::set(uint32_t key){ + { + ReadSpinLock lg(m_data->m_lock); + m_data->m_current = key; + } + report_value_changed(this); +} +void KeyBindingCell::set(std::string text){ + ReadSpinLock lg(m_data->m_lock); + m_data->m_current_text = std::move(text); +} + + + +void KeyBindingCell::load_json(const JsonValue& json){ + set((uint32_t)json.to_integer_default(0)); +} +JsonValue KeyBindingCell::to_json() const{ + ReadSpinLock lg(m_data->m_lock); + return m_data->m_current; +} + +void KeyBindingCell::restore_defaults(){ + set(m_data->m_default); +} + + + + + + + + + +} diff --git a/Common/Cpp/Options/KeyBindingOption.h b/Common/Cpp/Options/KeyBindingOption.h index 305da9a915..f5c5489e9b 100644 --- a/Common/Cpp/Options/KeyBindingOption.h +++ b/Common/Cpp/Options/KeyBindingOption.h @@ -1,48 +1,48 @@ -/* Key Binding Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_KeyBindingOption_H -#define PokemonAutomation_Options_KeyBindingOption_H - -#include "Common/Cpp/Containers/Pimpl.h" -#include "Common/Cpp/Options/ConfigOption.h" - -namespace PokemonAutomation{ - - - -class KeyBindingCell : public ConfigOption{ -public: - ~KeyBindingCell(); - KeyBindingCell(LockMode lock_while_program_is_running); - - operator uint32_t() const; - operator std::string() const; - void set(uint32_t key); - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual void restore_defaults() override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - - -public: - // UI Functions - void set(std::string text); - - -private: - struct Data; - Pimpl m_data; -}; - - - - -} -#endif +/* Key Binding Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_KeyBindingOption_H +#define PokemonAutomation_Options_KeyBindingOption_H + +#include "Common/Cpp/Containers/Pimpl.h" +#include "Common/Cpp/Options/ConfigOption.h" + +namespace PokemonAutomation{ + + + +class KeyBindingCell : public ConfigOption{ +public: + ~KeyBindingCell(); + KeyBindingCell(LockMode lock_while_program_is_running); + + operator uint32_t() const; + operator std::string() const; + void set(uint32_t key); + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual void restore_defaults() override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + + +public: + // UI Functions + void set(std::string text); + + +private: + struct Data; + Pimpl m_data; +}; + + + + +} +#endif diff --git a/Common/Cpp/Options/MacAddressOption.cpp b/Common/Cpp/Options/MacAddressOption.cpp index 17c40e6e70..8ecdb98868 100644 --- a/Common/Cpp/Options/MacAddressOption.cpp +++ b/Common/Cpp/Options/MacAddressOption.cpp @@ -1,151 +1,151 @@ -/* MAC Address Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Json/JsonValue.h" -#include "MacAddressOption.h" - -#include "Common/Qt/Options/MacAddressWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -ConfigWidget* MacAddressCell::make_QtWidget(QWidget& parent){ - return new MacAddressCellWidget(parent, *this); -} - - - -std::string write_MAC_address(size_t length, const uint8_t* address){ - static const char HEX_DIGITS[] = "0123456789ABCDEF"; - std::string ret; - for (size_t c = 0; c < length; c++){ - if (!ret.empty()){ - ret += "-"; - } - ret += HEX_DIGITS[address[c] >> 4]; - ret += HEX_DIGITS[address[c] & 0xf]; - } - return ret; -} -void parse_MAC_address(size_t length, uint8_t* address, const std::string& str){ - memset(address, 0, length); - size_t current_index = 0; - for (char ch : str){ - if (current_index >= 2*length){ - return; - } - if ('0' <= ch && ch <= '9'){ - ch -= '0'; - }else if ('a' <= ch && ch <= 'f'){ - ch += 10 - 'a'; - }else if ('A' <= ch && ch <= 'F'){ - ch += 10 - 'A'; - }else{ - continue; - } - address[current_index / 2] |= ch << 4*(1 - current_index % 2); - current_index++; - } -} - - - -struct MacAddressCell::Data{ - mutable std::mutex m_lock; - std::vector m_current; - - Data(size_t bytes, const uint8_t* current) - : m_current(bytes) - { - if (current != nullptr){ - memcpy(m_current.data(), current, bytes); - } - } -}; - - - -MacAddressCell::~MacAddressCell() = default; -MacAddressCell::MacAddressCell(const MacAddressCell& x) - : ConfigOption(x) - , m_data(CONSTRUCT_TOKEN, x.m_data->m_current.size(), x.m_data->m_current.data()) -{} -void MacAddressCell::operator=(const MacAddressCell& x){ - if (bytes() != x.bytes()){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Attempt to assign a MAC address is mismatching size." - ); - } - { - std::scoped_lock lg(m_data->m_lock, x.m_data->m_lock); - memcpy(m_data->m_current.data(), x.m_data->m_current.data(), bytes()); - } - report_value_changed(this); -} -MacAddressCell::MacAddressCell( - LockMode lock_while_running, - size_t bytes, - uint8_t* current_value -) - : ConfigOption(lock_while_running) - , m_data(CONSTRUCT_TOKEN, bytes, current_value) -{} - - -size_t MacAddressCell::bytes() const{ - return m_data->m_current.size(); -} -std::string MacAddressCell::to_string() const{ - std::lock_guard lg(m_data->m_lock); - return write_MAC_address(m_data->m_current.size(), m_data->m_current.data()); -} -void MacAddressCell::current_value(uint8_t* address) const{ - std::lock_guard lg(m_data->m_lock); - memcpy(address, m_data->m_current.data(), m_data->m_current.size()); -} -void MacAddressCell::set(const uint8_t* address){ - { - std::lock_guard lg(m_data->m_lock); - if (memcmp(m_data->m_current.data(), address, m_data->m_current.size()) == 0){ - return; - } - memcpy(m_data->m_current.data(), address, m_data->m_current.size()); - } - report_value_changed(this); -} -void MacAddressCell::set(const std::string& address){ - std::vector new_value(m_data->m_current.size()); - parse_MAC_address(new_value.size(), new_value.data(), address); - set(new_value.data()); -} - - -bool MacAddressCell::operator==(const uint8_t* address) const{ - std::lock_guard lg(m_data->m_lock); - return memcmp(m_data->m_current.data(), address, m_data->m_current.size()) == 0; -} - - -void MacAddressCell::load_json(const JsonValue& json){ - set(json.to_string_default()); -} -JsonValue MacAddressCell::to_json() const{ - return to_string(); -} - - - - - -} +/* MAC Address Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Json/JsonValue.h" +#include "MacAddressOption.h" + +#include "Common/Qt/Options/MacAddressWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +ConfigWidget* MacAddressCell::make_QtWidget(QWidget& parent){ + return new MacAddressCellWidget(parent, *this); +} + + + +std::string write_MAC_address(size_t length, const uint8_t* address){ + static const char HEX_DIGITS[] = "0123456789ABCDEF"; + std::string ret; + for (size_t c = 0; c < length; c++){ + if (!ret.empty()){ + ret += "-"; + } + ret += HEX_DIGITS[address[c] >> 4]; + ret += HEX_DIGITS[address[c] & 0xf]; + } + return ret; +} +void parse_MAC_address(size_t length, uint8_t* address, const std::string& str){ + memset(address, 0, length); + size_t current_index = 0; + for (char ch : str){ + if (current_index >= 2*length){ + return; + } + if ('0' <= ch && ch <= '9'){ + ch -= '0'; + }else if ('a' <= ch && ch <= 'f'){ + ch += 10 - 'a'; + }else if ('A' <= ch && ch <= 'F'){ + ch += 10 - 'A'; + }else{ + continue; + } + address[current_index / 2] |= ch << 4*(1 - current_index % 2); + current_index++; + } +} + + + +struct MacAddressCell::Data{ + mutable std::mutex m_lock; + std::vector m_current; + + Data(size_t bytes, const uint8_t* current) + : m_current(bytes) + { + if (current != nullptr){ + memcpy(m_current.data(), current, bytes); + } + } +}; + + + +MacAddressCell::~MacAddressCell() = default; +MacAddressCell::MacAddressCell(const MacAddressCell& x) + : ConfigOption(x) + , m_data(CONSTRUCT_TOKEN, x.m_data->m_current.size(), x.m_data->m_current.data()) +{} +void MacAddressCell::operator=(const MacAddressCell& x){ + if (bytes() != x.bytes()){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Attempt to assign a MAC address is mismatching size." + ); + } + { + std::scoped_lock lg(m_data->m_lock, x.m_data->m_lock); + memcpy(m_data->m_current.data(), x.m_data->m_current.data(), bytes()); + } + report_value_changed(this); +} +MacAddressCell::MacAddressCell( + LockMode lock_while_running, + size_t bytes, + uint8_t* current_value +) + : ConfigOption(lock_while_running) + , m_data(CONSTRUCT_TOKEN, bytes, current_value) +{} + + +size_t MacAddressCell::bytes() const{ + return m_data->m_current.size(); +} +std::string MacAddressCell::to_string() const{ + std::lock_guard lg(m_data->m_lock); + return write_MAC_address(m_data->m_current.size(), m_data->m_current.data()); +} +void MacAddressCell::current_value(uint8_t* address) const{ + std::lock_guard lg(m_data->m_lock); + memcpy(address, m_data->m_current.data(), m_data->m_current.size()); +} +void MacAddressCell::set(const uint8_t* address){ + { + std::lock_guard lg(m_data->m_lock); + if (memcmp(m_data->m_current.data(), address, m_data->m_current.size()) == 0){ + return; + } + memcpy(m_data->m_current.data(), address, m_data->m_current.size()); + } + report_value_changed(this); +} +void MacAddressCell::set(const std::string& address){ + std::vector new_value(m_data->m_current.size()); + parse_MAC_address(new_value.size(), new_value.data(), address); + set(new_value.data()); +} + + +bool MacAddressCell::operator==(const uint8_t* address) const{ + std::lock_guard lg(m_data->m_lock); + return memcmp(m_data->m_current.data(), address, m_data->m_current.size()) == 0; +} + + +void MacAddressCell::load_json(const JsonValue& json){ + set(json.to_string_default()); +} +JsonValue MacAddressCell::to_json() const{ + return to_string(); +} + + + + + +} diff --git a/Common/Cpp/Options/MacAddressOption.h b/Common/Cpp/Options/MacAddressOption.h index 0fcb901d56..f24e545a1e 100644 --- a/Common/Cpp/Options/MacAddressOption.h +++ b/Common/Cpp/Options/MacAddressOption.h @@ -1,63 +1,63 @@ -/* MAC Address Option - * - * From: https://github.com/PokemonAutomation/ - * - * This option is thread-safe. - * - */ - -#ifndef PokemonAutomation_Options_MacAddressOption_H -#define PokemonAutomation_Options_MacAddressOption_H - -#include "Common/Cpp/Containers/Pimpl.h" -#include "ConfigOption.h" - -namespace PokemonAutomation{ - - -std::string write_MAC_address(size_t length, const uint8_t* address); -void parse_MAC_address(size_t length, uint8_t* address, const std::string& str); - - -class MacAddressCell : public ConfigOption{ -public: - ~MacAddressCell(); - MacAddressCell(const MacAddressCell& x); - void operator=(const MacAddressCell& x); - MacAddressCell( - LockMode lock_while_running, - size_t bytes, - uint8_t* current_value - ); - -public: - size_t bytes() const; - std::string to_string() const; - - // Buffer must be long enough. - - void current_value(uint8_t* address) const; - void set(const uint8_t* address); - void set(const std::string& address); - - bool operator==(const uint8_t* address) const; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - -public: - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -protected: - struct Data; - Pimpl m_data; -}; - - - - - - -} -#endif - +/* MAC Address Option + * + * From: https://github.com/PokemonAutomation/ + * + * This option is thread-safe. + * + */ + +#ifndef PokemonAutomation_Options_MacAddressOption_H +#define PokemonAutomation_Options_MacAddressOption_H + +#include "Common/Cpp/Containers/Pimpl.h" +#include "ConfigOption.h" + +namespace PokemonAutomation{ + + +std::string write_MAC_address(size_t length, const uint8_t* address); +void parse_MAC_address(size_t length, uint8_t* address, const std::string& str); + + +class MacAddressCell : public ConfigOption{ +public: + ~MacAddressCell(); + MacAddressCell(const MacAddressCell& x); + void operator=(const MacAddressCell& x); + MacAddressCell( + LockMode lock_while_running, + size_t bytes, + uint8_t* current_value + ); + +public: + size_t bytes() const; + std::string to_string() const; + + // Buffer must be long enough. + + void current_value(uint8_t* address) const; + void set(const uint8_t* address); + void set(const std::string& address); + + bool operator==(const uint8_t* address) const; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + +public: + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +protected: + struct Data; + Pimpl m_data; +}; + + + + + + +} +#endif + diff --git a/Common/Cpp/Options/SimpleIntegerOption.cpp b/Common/Cpp/Options/SimpleIntegerOption.cpp index 3f899e7d0b..d85cbf0e95 100644 --- a/Common/Cpp/Options/SimpleIntegerOption.cpp +++ b/Common/Cpp/Options/SimpleIntegerOption.cpp @@ -200,7 +200,6 @@ SimpleIntegerOption::SimpleIntegerOption( - template class SimpleIntegerCell; template class SimpleIntegerCell; template class SimpleIntegerCell; @@ -220,5 +219,11 @@ template class SimpleIntegerOption; template class SimpleIntegerOption; +// This is stupid. +#ifdef __APPLE__ +template class SimpleIntegerCell; +template class SimpleIntegerOption; +#endif + } diff --git a/Common/Cpp/Options/TimeDurationOption.cpp b/Common/Cpp/Options/TimeDurationOption.cpp index e9c53a8465..53d34007e3 100644 --- a/Common/Cpp/Options/TimeDurationOption.cpp +++ b/Common/Cpp/Options/TimeDurationOption.cpp @@ -1,337 +1,337 @@ -/* Time Duration Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/ExpressionEvaluator.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Qt/Options/TimeDurationWidget.h" -#include "TimeDurationOption.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -template -struct TimeDurationCell::Data{ - const std::string m_units; - const bool m_show_summary; - const Type m_min_value; - const Type m_max_value; - const std::string m_default; - - mutable SpinLock m_lock; - std::string m_current; - Type m_value; - std::string m_error; - - Data( - std::string units, bool show_summary, - Type min_value, Type max_value, - std::string default_value - ) - : m_units(units) - , m_show_summary(show_summary) - , m_min_value(min_value) - , m_max_value(max_value) - , m_default(std::move(default_value)) - , m_current(m_default) - , m_value(0) - { - m_error = process(m_current, m_value); - } - - static std::map make_symbol_map(){ - std::map map; - - auto self = std::chrono::duration_cast(Type(1)).count(); - auto microseconds = std::chrono::duration_cast(std::chrono::microseconds(1)).count(); - auto milliseconds = std::chrono::duration_cast(std::chrono::milliseconds(1)).count(); - auto seconds = std::chrono::duration_cast(std::chrono::seconds(1)).count(); - auto minutes = std::chrono::duration_cast(std::chrono::minutes(1)).count(); - auto hours = std::chrono::duration_cast(std::chrono::hours(1)).count(); - auto days = std::chrono::duration_cast(std::chrono::days(1)).count(); - auto weeks = days * 7; - auto years = std::chrono::duration_cast(std::chrono::years(1)).count(); - - if (self <= microseconds){ - map["us"] = map["microsecond"] = map["microseconds"] = microseconds / self; - } - if (self <= milliseconds){ - map["ms"] = map["millisecond"] = map["milliseconds"] = milliseconds / self; - } - if (self <= seconds){ - map["s"] = map["secs"] = map["second"] = map["seconds"] = seconds / self; - } - if (self <= minutes){ - map["min"] = map["minute"] = map["minutes"] = minutes / self; - } - if (self <= hours){ - map["h"] = map["hour"] = map["hours"] = hours / self; - } - if (self <= days){ - map["d"] = map["day"] = map["days"] = days / self; - } - if (self <= weeks){ - map["w"] = map["week"] = map["weeks"] = weeks / self; - } - if (self <= years){ - map["y"] = map["year"] = map["years"] = years / self; - } - - return map; - } - - std::string process(const std::string& text, Type& value) const{ - if (text.empty()){ - return "Expression is empty."; - } - - static const std::map SYMBOLS = make_symbol_map(); - - using Rep = typename Type::rep; - Rep parsed; - try{ - parsed = parse_expression(SYMBOLS, text); - }catch (const ParseException& str){ - return str.message(); - } - // std::cout << "value = " << parsed << " " << m_min_value << " " << m_max_value << std::endl; - - if (Type(parsed) < m_min_value){ - return "Overflow: Number is too small."; - } - if (Type(parsed) > m_max_value){ - return "Overflow: Number is too large."; - } - value = (Type)parsed; - return std::string(); - } -}; - - - - - -template -TimeDurationCell::~TimeDurationCell() = default; -template -TimeDurationCell::TimeDurationCell( - std::string units, bool show_summary, - LockMode lock_while_running, - Type min_value, Type max_value, - std::string default_value -) - : ConfigOption(lock_while_running) - , m_data( - CONSTRUCT_TOKEN, - std::move(units), show_summary, - min_value, max_value, - std::move(default_value) - ) -{} - -template -TimeDurationCell::TimeDurationCell( - std::string units, - LockMode lock_while_running, - std::string default_value -) - : ConfigOption(lock_while_running) - , m_data( - CONSTRUCT_TOKEN, - std::move(units), true, - Type(0), Type::max(), - std::move(default_value) - ) -{} -template -TimeDurationCell::TimeDurationCell( - std::string units, - LockMode lock_while_running, - Type min_value, - std::string default_value -) - : ConfigOption(lock_while_running) - , m_data( - CONSTRUCT_TOKEN, - std::move(units), true, - min_value, Type::max(), - std::move(default_value) - ) -{} - -template -TimeDurationCell::TimeDurationCell( - std::string units, - LockMode lock_while_running, - Type min_value, Type max_value, - std::string default_value -) - : ConfigOption(lock_while_running) - , m_data( - CONSTRUCT_TOKEN, - std::move(units), true, - min_value, max_value, - std::move(default_value) - ) -{} - - -template -const std::string& TimeDurationCell::units() const{ - return m_data->m_units; -} -template -bool TimeDurationCell::show_summary() const{ - return m_data->m_show_summary; -} -template -Type TimeDurationCell::min_value() const{ - return m_data->m_min_value; -} -template -Type TimeDurationCell::max_value() const{ - return m_data->m_max_value; -} -template -const std::string& TimeDurationCell::default_value() const{ - return m_data->m_default; -} -template -std::string TimeDurationCell::current_text() const{ - const Data& data = *m_data; - ReadSpinLock lg(data.m_lock); - return data.m_current; -} -template -Type TimeDurationCell::get() const{ - const Data& data = *m_data; - ReadSpinLock lg(data.m_lock); - return data.m_value; -} -template -std::string TimeDurationCell::set(std::string text){ - Data& data = *m_data; - Type value(0); - std::string error; - { - WriteSpinLock lg(data.m_lock); - if (data.m_current == text){ - return std::string(); - } - error = data.process(text, value); - data.m_current = std::move(text); - data.m_value = value; - data.m_error.clear(); - } - report_value_changed(this); - return error; -} - -template -std::string TimeDurationCell::time_string() const{ - const Data& data = *m_data; - ReadSpinLock lg(data.m_lock); - if (!data.m_error.empty()){ - return "" + data.m_error + ""; - } - return time_string(data.m_current); -} -template -std::string TimeDurationCell::time_string(const std::string& text) const{ - const Data& data = *m_data; - Type value; - std::string error = data.process(text, value); - if (!error.empty()){ - return "" + error + ""; - } - - constexpr auto self = std::chrono::duration_cast(Type(1)).count(); - constexpr auto milliseconds = std::chrono::duration_cast(std::chrono::milliseconds(1)).count(); - if constexpr (self >= milliseconds){ - return duration_to_string(std::chrono::duration_cast(value)); - }else{ - return tostr_u_commas(value.count()) + " " + m_data->m_units; - } -} - -template -void TimeDurationCell::load_json(const JsonValue& json){ - Data& data = *m_data; - const std::string* str = json.to_string(); - if (str == nullptr){ - return; - } - { - WriteSpinLock lg(data.m_lock); - data.m_current = *str; - data.m_error = data.process(data.m_current, data.m_value); - } - report_value_changed(this); -} -template -JsonValue TimeDurationCell::to_json() const{ - const Data& data = *m_data; - ReadSpinLock lg(data.m_lock); - return data.m_current; -} - -template -std::string TimeDurationCell::check_validity() const{ - const Data& data = *m_data; - ReadSpinLock lg(data.m_lock); - return data.m_error; -} -template -void TimeDurationCell::restore_defaults(){ - Data& data = *m_data; - { - WriteSpinLock lg(data.m_lock); - data.m_current = data.m_default; - data.m_error = data.process(data.m_current, data.m_value); - } - report_value_changed(this); -} - - - - - - - - - -template -ConfigWidget* TimeDurationCell::make_QtWidget(QWidget& parent){ - return new TimeDurationCellWidget(parent, *this); -} - -template -ConfigWidget* TimeDurationOption::make_QtWidget(QWidget& parent){ - return new TimeDurationOptionWidget(parent, *this); -} - - - - - -template class TimeDurationCell; -template class TimeDurationCell; -template class TimeDurationOption; -template class TimeDurationOption; - - - - - - - -} +/* Time Duration Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/ExpressionEvaluator.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Qt/Options/TimeDurationWidget.h" +#include "TimeDurationOption.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +template +struct TimeDurationCell::Data{ + const std::string m_units; + const bool m_show_summary; + const Type m_min_value; + const Type m_max_value; + const std::string m_default; + + mutable SpinLock m_lock; + std::string m_current; + Type m_value; + std::string m_error; + + Data( + std::string units, bool show_summary, + Type min_value, Type max_value, + std::string default_value + ) + : m_units(units) + , m_show_summary(show_summary) + , m_min_value(min_value) + , m_max_value(max_value) + , m_default(std::move(default_value)) + , m_current(m_default) + , m_value(0) + { + m_error = process(m_current, m_value); + } + + static std::map make_symbol_map(){ + std::map map; + + auto self = std::chrono::duration_cast(Type(1)).count(); + auto microseconds = std::chrono::duration_cast(std::chrono::microseconds(1)).count(); + auto milliseconds = std::chrono::duration_cast(std::chrono::milliseconds(1)).count(); + auto seconds = std::chrono::duration_cast(std::chrono::seconds(1)).count(); + auto minutes = std::chrono::duration_cast(std::chrono::minutes(1)).count(); + auto hours = std::chrono::duration_cast(std::chrono::hours(1)).count(); + auto days = std::chrono::duration_cast(std::chrono::days(1)).count(); + auto weeks = days * 7; + auto years = std::chrono::duration_cast(std::chrono::years(1)).count(); + + if (self <= microseconds){ + map["us"] = map["microsecond"] = map["microseconds"] = microseconds / self; + } + if (self <= milliseconds){ + map["ms"] = map["millisecond"] = map["milliseconds"] = milliseconds / self; + } + if (self <= seconds){ + map["s"] = map["secs"] = map["second"] = map["seconds"] = seconds / self; + } + if (self <= minutes){ + map["min"] = map["minute"] = map["minutes"] = minutes / self; + } + if (self <= hours){ + map["h"] = map["hour"] = map["hours"] = hours / self; + } + if (self <= days){ + map["d"] = map["day"] = map["days"] = days / self; + } + if (self <= weeks){ + map["w"] = map["week"] = map["weeks"] = weeks / self; + } + if (self <= years){ + map["y"] = map["year"] = map["years"] = years / self; + } + + return map; + } + + std::string process(const std::string& text, Type& value) const{ + if (text.empty()){ + return "Expression is empty."; + } + + static const std::map SYMBOLS = make_symbol_map(); + + using Rep = typename Type::rep; + Rep parsed; + try{ + parsed = parse_expression(SYMBOLS, text); + }catch (const ParseException& str){ + return str.message(); + } + // std::cout << "value = " << parsed << " " << m_min_value << " " << m_max_value << std::endl; + + if (Type(parsed) < m_min_value){ + return "Overflow: Number is too small."; + } + if (Type(parsed) > m_max_value){ + return "Overflow: Number is too large."; + } + value = (Type)parsed; + return std::string(); + } +}; + + + + + +template +TimeDurationCell::~TimeDurationCell() = default; +template +TimeDurationCell::TimeDurationCell( + std::string units, bool show_summary, + LockMode lock_while_running, + Type min_value, Type max_value, + std::string default_value +) + : ConfigOption(lock_while_running) + , m_data( + CONSTRUCT_TOKEN, + std::move(units), show_summary, + min_value, max_value, + std::move(default_value) + ) +{} + +template +TimeDurationCell::TimeDurationCell( + std::string units, + LockMode lock_while_running, + std::string default_value +) + : ConfigOption(lock_while_running) + , m_data( + CONSTRUCT_TOKEN, + std::move(units), true, + Type(0), Type::max(), + std::move(default_value) + ) +{} +template +TimeDurationCell::TimeDurationCell( + std::string units, + LockMode lock_while_running, + Type min_value, + std::string default_value +) + : ConfigOption(lock_while_running) + , m_data( + CONSTRUCT_TOKEN, + std::move(units), true, + min_value, Type::max(), + std::move(default_value) + ) +{} + +template +TimeDurationCell::TimeDurationCell( + std::string units, + LockMode lock_while_running, + Type min_value, Type max_value, + std::string default_value +) + : ConfigOption(lock_while_running) + , m_data( + CONSTRUCT_TOKEN, + std::move(units), true, + min_value, max_value, + std::move(default_value) + ) +{} + + +template +const std::string& TimeDurationCell::units() const{ + return m_data->m_units; +} +template +bool TimeDurationCell::show_summary() const{ + return m_data->m_show_summary; +} +template +Type TimeDurationCell::min_value() const{ + return m_data->m_min_value; +} +template +Type TimeDurationCell::max_value() const{ + return m_data->m_max_value; +} +template +const std::string& TimeDurationCell::default_value() const{ + return m_data->m_default; +} +template +std::string TimeDurationCell::current_text() const{ + const Data& data = *m_data; + ReadSpinLock lg(data.m_lock); + return data.m_current; +} +template +Type TimeDurationCell::get() const{ + const Data& data = *m_data; + ReadSpinLock lg(data.m_lock); + return data.m_value; +} +template +std::string TimeDurationCell::set(std::string text){ + Data& data = *m_data; + Type value(0); + std::string error; + { + WriteSpinLock lg(data.m_lock); + if (data.m_current == text){ + return std::string(); + } + error = data.process(text, value); + data.m_current = std::move(text); + data.m_value = value; + data.m_error.clear(); + } + report_value_changed(this); + return error; +} + +template +std::string TimeDurationCell::time_string() const{ + const Data& data = *m_data; + ReadSpinLock lg(data.m_lock); + if (!data.m_error.empty()){ + return "" + data.m_error + ""; + } + return time_string(data.m_current); +} +template +std::string TimeDurationCell::time_string(const std::string& text) const{ + const Data& data = *m_data; + Type value; + std::string error = data.process(text, value); + if (!error.empty()){ + return "" + error + ""; + } + + constexpr auto self = std::chrono::duration_cast(Type(1)).count(); + constexpr auto milliseconds = std::chrono::duration_cast(std::chrono::milliseconds(1)).count(); + if constexpr (self >= milliseconds){ + return duration_to_string(std::chrono::duration_cast(value)); + }else{ + return tostr_u_commas(value.count()) + " " + m_data->m_units; + } +} + +template +void TimeDurationCell::load_json(const JsonValue& json){ + Data& data = *m_data; + const std::string* str = json.to_string(); + if (str == nullptr){ + return; + } + { + WriteSpinLock lg(data.m_lock); + data.m_current = *str; + data.m_error = data.process(data.m_current, data.m_value); + } + report_value_changed(this); +} +template +JsonValue TimeDurationCell::to_json() const{ + const Data& data = *m_data; + ReadSpinLock lg(data.m_lock); + return data.m_current; +} + +template +std::string TimeDurationCell::check_validity() const{ + const Data& data = *m_data; + ReadSpinLock lg(data.m_lock); + return data.m_error; +} +template +void TimeDurationCell::restore_defaults(){ + Data& data = *m_data; + { + WriteSpinLock lg(data.m_lock); + data.m_current = data.m_default; + data.m_error = data.process(data.m_current, data.m_value); + } + report_value_changed(this); +} + + + + + + + + + +template +ConfigWidget* TimeDurationCell::make_QtWidget(QWidget& parent){ + return new TimeDurationCellWidget(parent, *this); +} + +template +ConfigWidget* TimeDurationOption::make_QtWidget(QWidget& parent){ + return new TimeDurationOptionWidget(parent, *this); +} + + + + + +template class TimeDurationCell; +template class TimeDurationCell; +template class TimeDurationOption; +template class TimeDurationOption; + + + + + + + +} diff --git a/Common/Cpp/Options/TimeDurationOption.h b/Common/Cpp/Options/TimeDurationOption.h index 5207fa485e..0db97e386e 100644 --- a/Common/Cpp/Options/TimeDurationOption.h +++ b/Common/Cpp/Options/TimeDurationOption.h @@ -1,149 +1,149 @@ -/* Time Duration Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_TimeDurationOption_H -#define PokemonAutomation_Options_TimeDurationOption_H - -#include "Common/Cpp/Time.h" -#include "Common/Cpp/Containers/Pimpl.h" -#include "Common/Cpp/Options/ConfigOption.h" - -namespace PokemonAutomation{ - - -template -class TimeDurationCell : public ConfigOption{ -public: - ~TimeDurationCell(); - TimeDurationCell(const TimeDurationCell& x) = delete; - TimeDurationCell( - std::string units, bool show_summary, - LockMode lock_while_running, - Type min_value, Type max_value, - std::string default_value - ); - -public: - TimeDurationCell( - std::string units, - LockMode lock_while_running, - std::string default_value - ); - TimeDurationCell( - std::string units, - LockMode lock_while_running, - Type min_value, - std::string default_value - ); - TimeDurationCell( - std::string units, - LockMode lock_while_running, - Type min_value, Type max_value, - std::string default_value - ); - - -public: - const std::string& units() const; - bool show_summary() const; - Type min_value() const; - Type max_value() const; - const std::string& default_value() const; - std::string current_text() const; - - template - operator std::chrono::duration() const{ - return std::chrono::duration_cast>(get()); - } - - Type get() const; - std::string set(std::string text); - - -public: - // Get the description text using the current value. - std::string time_string() const; - - // Get the description text if you were to set the box to this value. - std::string time_string(const std::string& text) const; - - -public: - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual std::string check_validity() const override; - virtual void restore_defaults() override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - - -protected: - struct Data; - Pimpl m_data; -}; - - - -template -class TimeDurationOption : public TimeDurationCell{ -public: - template - TimeDurationOption(std::string label, Args&&... args) - : TimeDurationCell(std::forward(args)...) - , m_label(std::move(label)) - {} - - const std::string& label() const{ return m_label; } - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - const std::string m_label; -}; - - - - - -class MillisecondsCell : public TimeDurationCell{ -public: - template - MillisecondsCell(Args&&... args) - : TimeDurationCell("milliseconds", std::forward(args)...) - {} -}; -class MillisecondsOption : public TimeDurationOption{ -public: - template - MillisecondsOption(std::string label, Args&&... args) - : TimeDurationOption( - std::move(label), - "milliseconds", - std::forward(args)... - ) - {} -}; - - - -class MicrosecondsOption : public TimeDurationOption{ -public: - template - MicrosecondsOption(std::string label, Args&&... args) - : TimeDurationOption( - std::move(label), - "microseconds", - std::forward(args)... - ) - {} -}; - - - - -} -#endif +/* Time Duration Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_TimeDurationOption_H +#define PokemonAutomation_Options_TimeDurationOption_H + +#include "Common/Cpp/Time.h" +#include "Common/Cpp/Containers/Pimpl.h" +#include "Common/Cpp/Options/ConfigOption.h" + +namespace PokemonAutomation{ + + +template +class TimeDurationCell : public ConfigOption{ +public: + ~TimeDurationCell(); + TimeDurationCell(const TimeDurationCell& x) = delete; + TimeDurationCell( + std::string units, bool show_summary, + LockMode lock_while_running, + Type min_value, Type max_value, + std::string default_value + ); + +public: + TimeDurationCell( + std::string units, + LockMode lock_while_running, + std::string default_value + ); + TimeDurationCell( + std::string units, + LockMode lock_while_running, + Type min_value, + std::string default_value + ); + TimeDurationCell( + std::string units, + LockMode lock_while_running, + Type min_value, Type max_value, + std::string default_value + ); + + +public: + const std::string& units() const; + bool show_summary() const; + Type min_value() const; + Type max_value() const; + const std::string& default_value() const; + std::string current_text() const; + + template + operator std::chrono::duration() const{ + return std::chrono::duration_cast>(get()); + } + + Type get() const; + std::string set(std::string text); + + +public: + // Get the description text using the current value. + std::string time_string() const; + + // Get the description text if you were to set the box to this value. + std::string time_string(const std::string& text) const; + + +public: + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual std::string check_validity() const override; + virtual void restore_defaults() override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + + +protected: + struct Data; + Pimpl m_data; +}; + + + +template +class TimeDurationOption : public TimeDurationCell{ +public: + template + TimeDurationOption(std::string label, Args&&... args) + : TimeDurationCell(std::forward(args)...) + , m_label(std::move(label)) + {} + + const std::string& label() const{ return m_label; } + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + const std::string m_label; +}; + + + + + +class MillisecondsCell : public TimeDurationCell{ +public: + template + MillisecondsCell(Args&&... args) + : TimeDurationCell("milliseconds", std::forward(args)...) + {} +}; +class MillisecondsOption : public TimeDurationOption{ +public: + template + MillisecondsOption(std::string label, Args&&... args) + : TimeDurationOption( + std::move(label), + "milliseconds", + std::forward(args)... + ) + {} +}; + + + +class MicrosecondsOption : public TimeDurationOption{ +public: + template + MicrosecondsOption(std::string label, Args&&... args) + : TimeDurationOption( + std::move(label), + "microseconds", + std::forward(args)... + ) + {} +}; + + + + +} +#endif diff --git a/Common/Cpp/PixelRGB32.h b/Common/Cpp/PixelRGB32.h index fb428c2a25..3a51449895 100644 --- a/Common/Cpp/PixelRGB32.h +++ b/Common/Cpp/PixelRGB32.h @@ -1,51 +1,51 @@ -/* Pixel: RGB32 - * - * From: https://github.com/PokemonAutomation/ - * - * Perform a filter over an image and replace pixels that match the filter. - * - */ - -#ifndef PokemonAutomation_Pixel_RGB32_H -#define PokemonAutomation_Pixel_RGB32_H - -#include - -namespace PokemonAutomation{ - - - - - -union PixelRGB32{ - struct{ - uint8_t blue; - uint8_t green; - uint8_t red; - uint8_t alpha; - } parts; - uint32_t u32; - - PixelRGB32(uint32_t value) - : u32(value) - {} - PixelRGB32(uint8_t red, uint8_t green, uint8_t blue){ - parts.alpha = 0xff; - parts.red = red; - parts.green = green; - parts.blue = blue; - } - PixelRGB32(uint8_t alpha, uint8_t red, uint8_t green, uint8_t blue){ - parts.alpha = alpha; - parts.red = red; - parts.green = green; - parts.blue = blue; - } -}; - - - - - -} -#endif +/* Pixel: RGB32 + * + * From: https://github.com/PokemonAutomation/ + * + * Perform a filter over an image and replace pixels that match the filter. + * + */ + +#ifndef PokemonAutomation_Pixel_RGB32_H +#define PokemonAutomation_Pixel_RGB32_H + +#include + +namespace PokemonAutomation{ + + + + + +union PixelRGB32{ + struct{ + uint8_t blue; + uint8_t green; + uint8_t red; + uint8_t alpha; + } parts; + uint32_t u32; + + PixelRGB32(uint32_t value) + : u32(value) + {} + PixelRGB32(uint8_t red, uint8_t green, uint8_t blue){ + parts.alpha = 0xff; + parts.red = red; + parts.green = green; + parts.blue = blue; + } + PixelRGB32(uint8_t alpha, uint8_t red, uint8_t green, uint8_t blue){ + parts.alpha = alpha; + parts.red = red; + parts.green = green; + parts.blue = blue; + } +}; + + + + + +} +#endif diff --git a/Common/Cpp/RecursiveThrottler.h b/Common/Cpp/RecursiveThrottler.h index 2b833ef8fd..4fb4aec6bf 100644 --- a/Common/Cpp/RecursiveThrottler.h +++ b/Common/Cpp/RecursiveThrottler.h @@ -1,56 +1,56 @@ -/* Recursive Throttler - * - * From: https://github.com/PokemonAutomation/ - * - * Used to suppress recursive logging. - * Log only at the top level. And limit to 1 thread at a time. - * - */ - -#ifndef PokemonAutomation_RecursiveThrottler_H -#define PokemonAutomation_RecursiveThrottler_H - -#include - -namespace PokemonAutomation{ - -class RecursiveThrottler{ -public: - // Returns true if ok to run. (not throttled) - operator bool() const{ - std::lock_guard lg(m_lock); - return m_depth == 0; - } - -private: - friend class ThrottleScope; - mutable std::recursive_mutex m_lock; - size_t m_depth = 0; -}; - -class ThrottleScope{ - ThrottleScope(const ThrottleScope&) = delete; - void operator=(const ThrottleScope&) = delete; -public: - ThrottleScope(RecursiveThrottler& throttler) - : m_throttler(throttler) - , m_guard(throttler.m_lock) - { - throttler.m_depth++; - } - ~ThrottleScope(){ - m_throttler.m_depth--; - } - - // Returns true if ok to run. (not throttled) - operator bool() const{ - return m_throttler.m_depth == 1; - } - -private: - RecursiveThrottler& m_throttler; - std::lock_guard m_guard; -}; - -} -#endif +/* Recursive Throttler + * + * From: https://github.com/PokemonAutomation/ + * + * Used to suppress recursive logging. + * Log only at the top level. And limit to 1 thread at a time. + * + */ + +#ifndef PokemonAutomation_RecursiveThrottler_H +#define PokemonAutomation_RecursiveThrottler_H + +#include + +namespace PokemonAutomation{ + +class RecursiveThrottler{ +public: + // Returns true if ok to run. (not throttled) + operator bool() const{ + std::lock_guard lg(m_lock); + return m_depth == 0; + } + +private: + friend class ThrottleScope; + mutable std::recursive_mutex m_lock; + size_t m_depth = 0; +}; + +class ThrottleScope{ + ThrottleScope(const ThrottleScope&) = delete; + void operator=(const ThrottleScope&) = delete; +public: + ThrottleScope(RecursiveThrottler& throttler) + : m_throttler(throttler) + , m_guard(throttler.m_lock) + { + throttler.m_depth++; + } + ~ThrottleScope(){ + m_throttler.m_depth--; + } + + // Returns true if ok to run. (not throttled) + operator bool() const{ + return m_throttler.m_depth == 1; + } + +private: + RecursiveThrottler& m_throttler; + std::lock_guard m_guard; +}; + +} +#endif diff --git a/Common/Cpp/Sockets/AbstractClientSocket.h b/Common/Cpp/Sockets/AbstractClientSocket.h index d0bce4b086..078c3e85aa 100644 --- a/Common/Cpp/Sockets/AbstractClientSocket.h +++ b/Common/Cpp/Sockets/AbstractClientSocket.h @@ -1,75 +1,75 @@ -/* Abstract Client Socket - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Sockets_AbstractClientSocket_H -#define PokemonAutomation_Sockets_AbstractClientSocket_H - -#include -#include "Common/Compiler.h" -#include "Common/Cpp/ListenerSet.h" - -namespace PokemonAutomation{ - - - -class AbstractClientSocket{ -public: - enum class State{ - NOT_RUNNING, - CONNECTING, - CONNECTED, - DESTRUCTING, - }; - - struct Listener{ - // Called at the start of the receiver thread. This can be used to set - // the thread priority of the thread. - virtual void on_thread_start(){} - - // Called when a connection attempt finishes. - // If successful, "error_message" is empty. - // Otherwise, it contains the error message. - virtual void on_connect_finished(const std::string& error_message){} - - // Called when the socket receives data from the server. - virtual void on_receive_data(const void* data, size_t bytes){} - }; - - void add_listener(Listener& listener){ - m_listeners.add(listener); - } - void remove_listener(Listener& listener){ - m_listeners.add(listener); - } - - -public: - AbstractClientSocket() - : m_state(State::NOT_RUNNING) - {} - virtual ~AbstractClientSocket() = default; - - State state() const{ - return m_state.load(std::memory_order_relaxed); - } - - virtual void close() noexcept = 0; - virtual void connect(const std::string& address, uint16_t port) = 0; - - virtual size_t blocking_send(const void* data, size_t bytes) = 0; - - -protected: - std::atomic m_state; - ListenerSet m_listeners; -}; - - - - - -} -#endif +/* Abstract Client Socket + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Sockets_AbstractClientSocket_H +#define PokemonAutomation_Sockets_AbstractClientSocket_H + +#include +#include "Common/Compiler.h" +#include "Common/Cpp/ListenerSet.h" + +namespace PokemonAutomation{ + + + +class AbstractClientSocket{ +public: + enum class State{ + NOT_RUNNING, + CONNECTING, + CONNECTED, + DESTRUCTING, + }; + + struct Listener{ + // Called at the start of the receiver thread. This can be used to set + // the thread priority of the thread. + virtual void on_thread_start(){} + + // Called when a connection attempt finishes. + // If successful, "error_message" is empty. + // Otherwise, it contains the error message. + virtual void on_connect_finished(const std::string& error_message){} + + // Called when the socket receives data from the server. + virtual void on_receive_data(const void* data, size_t bytes){} + }; + + void add_listener(Listener& listener){ + m_listeners.add(listener); + } + void remove_listener(Listener& listener){ + m_listeners.add(listener); + } + + +public: + AbstractClientSocket() + : m_state(State::NOT_RUNNING) + {} + virtual ~AbstractClientSocket() = default; + + State state() const{ + return m_state.load(std::memory_order_relaxed); + } + + virtual void close() noexcept = 0; + virtual void connect(const std::string& address, uint16_t port) = 0; + + virtual size_t send(const void* data, size_t bytes) = 0; + + +protected: + std::atomic m_state; + ListenerSet m_listeners; +}; + + + + + +} +#endif diff --git a/Common/Cpp/Sockets/ClientSocket.cpp b/Common/Cpp/Sockets/ClientSocket.cpp index 10183d77b9..66d38393e0 100644 --- a/Common/Cpp/Sockets/ClientSocket.cpp +++ b/Common/Cpp/Sockets/ClientSocket.cpp @@ -1,14 +1,14 @@ -/* Client Socket - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "ClientSocket.h" - -namespace PokemonAutomation{ - - - - -} +/* Client Socket + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "ClientSocket.h" + +namespace PokemonAutomation{ + + + + +} diff --git a/Common/Cpp/Sockets/ClientSocket.h b/Common/Cpp/Sockets/ClientSocket.h index 61d38b7784..011ebc6a00 100644 --- a/Common/Cpp/Sockets/ClientSocket.h +++ b/Common/Cpp/Sockets/ClientSocket.h @@ -1,26 +1,28 @@ -/* Client Socket - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ClientSocket_H -#define PokemonAutomation_ClientSocket_H - - - -#ifdef _WIN32 -#include "ClientSocket_WinSocket.h" -namespace PokemonAutomation{ - using ClientSocket = ClientSocket_WinSocket; -} -#else -#include "ClientSocket_POSIX.h" -namespace PokemonAutomation{ - using ClientSocket = ClientSocket_POSIX; -} -#endif - - - -#endif +/* Client Socket + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ClientSocket_H +#define PokemonAutomation_ClientSocket_H + + + +#ifdef _WIN32 +//#include "ClientSocket_WinSocket.h" +#include "ClientSocket_Qt.h" +namespace PokemonAutomation{ +// using ClientSocket = ClientSocket_WinSocket; + using ClientSocket = ClientSocket_Qt; +} +#else +#include "ClientSocket_POSIX.h" +namespace PokemonAutomation{ + using ClientSocket = ClientSocket_POSIX; +} +#endif + + + +#endif diff --git a/Common/Cpp/Sockets/ClientSocket_POSIX.h b/Common/Cpp/Sockets/ClientSocket_POSIX.h index 135082ab1f..a63ce4225d 100644 --- a/Common/Cpp/Sockets/ClientSocket_POSIX.h +++ b/Common/Cpp/Sockets/ClientSocket_POSIX.h @@ -1,241 +1,241 @@ -/* Client Socket (POSIX) - * - * From: https://github.com/PokemonAutomation/ - * - * This file is completely untested! - * - */ - -#ifndef PokemonAutomation_ClientSocket_POSIX_H -#define PokemonAutomation_ClientSocket_POSIX_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "AbstractClientSocket.h" - -namespace PokemonAutomation{ - - - -class ClientSocket_POSIX final : public AbstractClientSocket{ -public: - ClientSocket_POSIX() - : m_socket(socket(AF_INET, SOCK_STREAM, 0)) - { - fcntl(m_socket, F_SETFL, O_NONBLOCK); - } - - virtual ~ClientSocket_POSIX(){ - close(); - if (m_thread.joinable()){ - m_thread.join(); - } - if (m_socket != -1){ - ::close(m_socket); - } - } - virtual void close() noexcept override{ - { - std::lock_guard lg1(m_lock); - m_state.store(State::DESTRUCTING, std::memory_order_relaxed); - m_cv.notify_all(); - } - } - - virtual void connect(const std::string& address, uint16_t port) override{ - std::lock_guard lg1(m_lock); - if (m_state.load(std::memory_order_relaxed) != State::NOT_RUNNING){ - return; - } - try{ - m_state.store(State::CONNECTING, std::memory_order_relaxed); - m_thread = std::thread( - &ClientSocket_POSIX::thread_loop, - this, address, port - ); - }catch (...){ - m_state.store(State::NOT_RUNNING, std::memory_order_relaxed); - throw; - } - } - - - virtual size_t blocking_send(const void* data, size_t bytes) override{ - if (m_socket == -1){ - return 0; - } - - constexpr int BLOCK_SIZE = (int)1 << 30; - const char* ptr = (const char*)data; - size_t sent = 0; - - while (bytes > 0){ - size_t current = std::min(bytes, BLOCK_SIZE); - ssize_t current_sent = ::send(m_socket, ptr, (int)current, MSG_DONTWAIT); - if (current_sent != -1){ - sent += current; - if ((size_t)current_sent < current){ - return sent; - } - ptr += current; - bytes -= current; - continue; - } - - std::unique_lock lg(m_lock); - if (state() == State::DESTRUCTING){ - break; - } - - int error = errno; -// cout << "error = " << error << endl; - switch (error){ - case EAGAIN: -// case EWOULDBLOCK: - break; - default: - m_error = "POSIX Error Code: " + std::to_string(error); - return sent; - } - - m_cv.wait_for(lg, std::chrono::milliseconds(1)); - } - return sent; - } - - -private: - void thread_loop(const std::string& address, uint16_t port){ - try{ - thread_loop_internal(address, port); - }catch (...){ - try{ - std::cout << "ClientSocket_POSIX(): An exception was thrown from the receive thread." << std::endl; - }catch (...){} - } - } - - void thread_loop_internal(const std::string& address, uint16_t port){ - m_listeners.run_method_unique(&Listener::on_thread_start); - - { - std::unique_lock lg(m_lock); - - sockaddr_in server; - server.sin_family = AF_INET; - server.sin_port = htons(port); - server.sin_addr.s_addr = inet_addr(address.c_str()); - - // Connect - while (true){ - State state = m_state.load(std::memory_order_relaxed); - if (state == State::DESTRUCTING){ - return; - } - - if (::connect(m_socket, (struct sockaddr*)&server, sizeof(server)) != -1){ - break; - } - - int error = errno; -// cout << "error = " << error << endl; - - switch (error){ - case EISCONN: - goto Connected; - case EAGAIN: - case EALREADY: - case EINPROGRESS: - break; - case ETIMEDOUT: - m_state.store(State::NOT_RUNNING, std::memory_order_relaxed); - m_error = "Connection timed out."; - m_lock.unlock(); - m_listeners.run_method_unique(&Listener::on_connect_finished, m_error); - return; - default: - m_state.store(State::NOT_RUNNING, std::memory_order_relaxed); - m_error = "WSA Error Code: " + std::to_string(error); - m_lock.unlock(); - m_listeners.run_method_unique(&Listener::on_connect_finished, m_error); - return; - } - - m_cv.wait_for(lg, std::chrono::milliseconds(10)); - - } - -Connected: - m_state.store(State::CONNECTED, std::memory_order_relaxed); - } - - m_listeners.run_method_unique(&Listener::on_connect_finished, ""); - - - constexpr size_t BUFFER_SIZE = 4096; - char buffer[BUFFER_SIZE]; - - while (true){ - ssize_t bytes; - int error = 0; - { - std::unique_lock lg(m_lock); - State state = m_state.load(std::memory_order_relaxed); - if (state == State::DESTRUCTING){ - return; - } - bytes = ::recv(m_socket, buffer, BUFFER_SIZE, 0); - if (bytes < 0){ - error = errno; - } - } - - if (bytes > 0){ - m_listeners.run_method_unique(&Listener::on_receive_data, buffer, bytes); - continue; - } - - std::unique_lock lg(m_lock); - if (state() == State::DESTRUCTING){ - return; - } - - if (bytes < 0){ -// cout << "error = " << error << endl; - switch (error){ - case EAGAIN: -// case EWOULDBLOCK: - break; - default: - std::unique_lock lg(m_lock); - m_error = "POSIX Error Code: " + std::to_string(error); - return; - } - } - - m_cv.wait_for(lg, std::chrono::milliseconds(1)); - } - - } - - -private: - const int m_socket; - - std::string m_error; - - mutable std::mutex m_lock; - std::condition_variable m_cv; - std::thread m_thread; -}; - - -} -#endif +/* Client Socket (POSIX) + * + * From: https://github.com/PokemonAutomation/ + * + * This file is completely untested! + * + */ + +#ifndef PokemonAutomation_ClientSocket_POSIX_H +#define PokemonAutomation_ClientSocket_POSIX_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "AbstractClientSocket.h" + +namespace PokemonAutomation{ + + + +class ClientSocket_POSIX final : public AbstractClientSocket{ +public: + ClientSocket_POSIX() + : m_socket(socket(AF_INET, SOCK_STREAM, 0)) + { + fcntl(m_socket, F_SETFL, O_NONBLOCK); + } + + virtual ~ClientSocket_POSIX(){ + close(); + if (m_thread.joinable()){ + m_thread.join(); + } + if (m_socket != -1){ + ::close(m_socket); + } + } + virtual void close() noexcept override{ + { + std::lock_guard lg1(m_lock); + m_state.store(State::DESTRUCTING, std::memory_order_relaxed); + m_cv.notify_all(); + } + } + + virtual void connect(const std::string& address, uint16_t port) override{ + std::lock_guard lg1(m_lock); + if (m_state.load(std::memory_order_relaxed) != State::NOT_RUNNING){ + return; + } + try{ + m_state.store(State::CONNECTING, std::memory_order_relaxed); + m_thread = std::thread( + &ClientSocket_POSIX::thread_loop, + this, address, port + ); + }catch (...){ + m_state.store(State::NOT_RUNNING, std::memory_order_relaxed); + throw; + } + } + + + virtual size_t send(const void* data, size_t bytes) override{ + if (m_socket == -1){ + return 0; + } + + constexpr int BLOCK_SIZE = (int)1 << 30; + const char* ptr = (const char*)data; + size_t sent = 0; + + while (bytes > 0){ + size_t current = std::min(bytes, BLOCK_SIZE); + ssize_t current_sent = ::send(m_socket, ptr, (int)current, MSG_DONTWAIT); + if (current_sent != -1){ + sent += current; + if ((size_t)current_sent < current){ + return sent; + } + ptr += current; + bytes -= current; + continue; + } + + std::unique_lock lg(m_lock); + if (state() == State::DESTRUCTING){ + break; + } + + int error = errno; +// cout << "error = " << error << endl; + switch (error){ + case EAGAIN: +// case EWOULDBLOCK: + break; + default: + m_error = "POSIX Error Code: " + std::to_string(error); + return sent; + } + + m_cv.wait_for(lg, std::chrono::milliseconds(1)); + } + return sent; + } + + +private: + void thread_loop(const std::string& address, uint16_t port){ + try{ + thread_loop_internal(address, port); + }catch (...){ + try{ + std::cout << "ClientSocket_POSIX(): An exception was thrown from the receive thread." << std::endl; + }catch (...){} + } + } + + void thread_loop_internal(const std::string& address, uint16_t port){ + m_listeners.run_method_unique(&Listener::on_thread_start); + + { + std::unique_lock lg(m_lock); + + sockaddr_in server; + server.sin_family = AF_INET; + server.sin_port = htons(port); + server.sin_addr.s_addr = inet_addr(address.c_str()); + + // Connect + while (true){ + State state = m_state.load(std::memory_order_relaxed); + if (state == State::DESTRUCTING){ + return; + } + + if (::connect(m_socket, (struct sockaddr*)&server, sizeof(server)) != -1){ + break; + } + + int error = errno; +// cout << "error = " << error << endl; + + switch (error){ + case EISCONN: + goto Connected; + case EAGAIN: + case EALREADY: + case EINPROGRESS: + break; + case ETIMEDOUT: + m_state.store(State::NOT_RUNNING, std::memory_order_relaxed); + m_error = "Connection timed out."; + m_lock.unlock(); + m_listeners.run_method_unique(&Listener::on_connect_finished, m_error); + return; + default: + m_state.store(State::NOT_RUNNING, std::memory_order_relaxed); + m_error = "WSA Error Code: " + std::to_string(error); + m_lock.unlock(); + m_listeners.run_method_unique(&Listener::on_connect_finished, m_error); + return; + } + + m_cv.wait_for(lg, std::chrono::milliseconds(10)); + + } + +Connected: + m_state.store(State::CONNECTED, std::memory_order_relaxed); + } + + m_listeners.run_method_unique(&Listener::on_connect_finished, ""); + + + constexpr size_t BUFFER_SIZE = 4096; + char buffer[BUFFER_SIZE]; + + while (true){ + ssize_t bytes; + int error = 0; + { + std::unique_lock lg(m_lock); + State state = m_state.load(std::memory_order_relaxed); + if (state == State::DESTRUCTING){ + return; + } + bytes = ::recv(m_socket, buffer, BUFFER_SIZE, 0); + if (bytes < 0){ + error = errno; + } + } + + if (bytes > 0){ + m_listeners.run_method_unique(&Listener::on_receive_data, buffer, bytes); + continue; + } + + std::unique_lock lg(m_lock); + if (state() == State::DESTRUCTING){ + return; + } + + if (bytes < 0){ +// cout << "error = " << error << endl; + switch (error){ + case EAGAIN: +// case EWOULDBLOCK: + break; + default: + std::unique_lock lg(m_lock); + m_error = "POSIX Error Code: " + std::to_string(error); + return; + } + } + + m_cv.wait_for(lg, std::chrono::milliseconds(1)); + } + + } + + +private: + const int m_socket; + + std::string m_error; + + mutable std::mutex m_lock; + std::condition_variable m_cv; + std::thread m_thread; +}; + + +} +#endif diff --git a/Common/Cpp/Sockets/ClientSocket_Qt.h b/Common/Cpp/Sockets/ClientSocket_Qt.h new file mode 100644 index 0000000000..415d01e33a --- /dev/null +++ b/Common/Cpp/Sockets/ClientSocket_Qt.h @@ -0,0 +1,227 @@ +/* Client Socket (Qt) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ClientSocket_Qt_H +#define PokemonAutomation_ClientSocket_Qt_H + +#include +#include +#include +#include +#include +//#include "Common/Cpp/Concurrency/SpinPause.h" +#include "AbstractClientSocket.h" + +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +class ClientSocket_Qt final : public QThread, public AbstractClientSocket{ + Q_OBJECT + + struct SendData{ + const void* data; + size_t total_bytes; + size_t bytes_sent; + std::mutex lock; + std::condition_variable cv; + }; + + +public: + ClientSocket_Qt() + : m_socket(nullptr) + { +// cout << "ClientSocket_Qt()" << endl; + start(); + +// cout << "ClientSocket_Qt() - waiting" << endl; + std::unique_lock lg(m_lock); + m_cv.wait(lg, [this]{ return m_socket != nullptr; }); + } + + virtual ~ClientSocket_Qt(){ +// cout << "~ClientSocket_Qt()" << endl; + close(); + } + virtual void close() noexcept override{ +// cout << "close()" << endl; + m_state.store(State::DESTRUCTING, std::memory_order_release); + quit(); + wait(); + } + + virtual void connect(const std::string& address, uint16_t port) override{ +// cout << "connect()" << endl; + emit internal_connect(address, port); + } + + virtual size_t send(const void* data, size_t bytes) override{ +// cout << "send() - start: " << std::string((const char*)data, bytes) << endl; + emit internal_send(std::string((const char*)data, bytes)); + return bytes; + +#if 0 + SendData send_data; + send_data.data = data; + send_data.total_bytes = bytes; + send_data.bytes_sent = 0; + + emit send(&send_data); + + std::unique_lock lg(send_data.lock); + send_data.cv.wait(lg, [&]{ + return send_data.data == nullptr || m_socket == nullptr; + }); + +// cout << "send() - end: " << std::string((const char*)data, bytes) << endl; + return send_data.bytes_sent; +#endif + } + + +signals: + void internal_connect(const std::string& address, uint16_t port); + void internal_send(std::string packet); + +private: + virtual void run() override{ + QTcpSocket socket; + + QThread::connect( + &socket, &QTcpSocket::connected, + &socket, [this]{ +// cout << "connected()" << endl; + m_state.store(State::CONNECTED, std::memory_order_release); + m_listeners.run_method_unique(&Listener::on_connect_finished, ""); + } + ); + QThread::connect( + &socket, &QTcpSocket::disconnected, + &socket, [this]{ + std::cout << "QTcpSocket::disconnected()" << std::endl; + m_state.store(State::DESTRUCTING, std::memory_order_release); + quit(); + } + ); + QThread::connect( + &socket, &QTcpSocket::errorOccurred, + &socket, [this](QAbstractSocket::SocketError error){ + std::cout << "QTcpSocket::errorOccurred(): error = " << (int)error << std::endl; + m_state.store(State::DESTRUCTING, std::memory_order_release); + quit(); + } + ); + QThread::connect( + &socket, &QTcpSocket::readyRead, + &socket, [this]{ +// cout << "readyRead()" << endl; + constexpr size_t BUFFER_SIZE = 4096; + char buffer[BUFFER_SIZE]; + qint64 bytes = m_socket->read(buffer, BUFFER_SIZE); + if (bytes > 0){ +// cout << "Received: " << std::string(buffer, bytes) << endl; + m_listeners.run_method_unique(&Listener::on_receive_data, buffer, bytes); + } + } + ); + QThread::connect( + this, &ClientSocket_Qt::internal_connect, + &socket, [this](const std::string& address, uint16_t port){ + m_state.store(State::CONNECTING, std::memory_order_release); + m_socket->connectToHost(QHostAddress(QString::fromStdString(address)), port); + } + ); + QThread::connect( + this, &ClientSocket_Qt::internal_send, + &socket, [this](std::string packet){ +// cout << "internal_send() - enter: " << packet.data() << endl; + + size_t bytes = packet.size(); + + const char* ptr = (const char*)packet.data(); + while (bytes > 0 && m_socket->state() == QAbstractSocket::ConnectedState){ + qint64 current_sent = m_socket->write(ptr, bytes); + if (current_sent <= 0){ + break; + } + ptr += current_sent; + bytes -= current_sent; + } + +// m_socket->flush(); + +// cout << "internal_send() - exit " << endl; + } + ); +#if 0 + QThread::connect( + this, &ClientSocket_Qt::send, + &socket, [this](void* params){ +// cout << "internal_send() - enter " << endl; + + SendData& data = *(SendData*)params; + size_t sent = 0; + + size_t bytes = data.total_bytes; + + const char* ptr = (const char*)data.data; + while (bytes > 0 && m_socket->state() == QAbstractSocket::ConnectedState){ + qint64 current_sent = m_socket->write((const char*)ptr, bytes); + if (current_sent <= 0){ + break; + } + sent += current_sent; + ptr += current_sent; + bytes -= current_sent; + } + + m_socket->flush(); + + std::lock_guard lg(data.lock); + data.data = nullptr; + data.bytes_sent = sent; + data.cv.notify_all(); + +// cout << "internal_send() - exit " << endl; + } + ); +#endif + + + { + std::lock_guard lg(m_lock); + if (this->state() == State::DESTRUCTING){ + return; + } + m_socket = &socket; + } + m_cv.notify_all(); + + exec(); + + { + std::lock_guard lg(m_lock); + m_socket = nullptr; + } + m_cv.notify_all(); + } + +private: + std::mutex m_lock; + std::condition_variable m_cv; + QTcpSocket* m_socket; +}; + + + + + +} +#endif diff --git a/Common/Cpp/Sockets/ClientSocket_WinSocket.h b/Common/Cpp/Sockets/ClientSocket_WinSocket.h index 026e6795f3..80d0dc3863 100644 --- a/Common/Cpp/Sockets/ClientSocket_WinSocket.h +++ b/Common/Cpp/Sockets/ClientSocket_WinSocket.h @@ -1,250 +1,250 @@ -/* Client Socket (Windows) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ClientSocket_WinSocket_H -#define PokemonAutomation_ClientSocket_WinSocket_H - -#include -#include -#include -#include -#include -#include "AbstractClientSocket.h" - -#pragma comment(lib, "Ws2_32.lib") - -namespace PokemonAutomation{ - - - -class ClientSocket_WinSocket final : public AbstractClientSocket{ -public: - ClientSocket_WinSocket() - : m_socket(::socket(AF_INET, SOCK_STREAM, 0)) - { - u_long non_blocking = 1; - if (ioctlsocket(m_socket, FIONBIO, &non_blocking)){ -// cout << "ioctlsocket() Failed" << endl; - close_socket(); - return; - } - } - - virtual ~ClientSocket_WinSocket(){ - close(); - if (m_thread.joinable()){ - m_thread.join(); - } - close_socket(); - } - virtual void close() noexcept override{ - { - std::lock_guard lg1(m_lock); - m_state.store(State::DESTRUCTING, std::memory_order_relaxed); - m_cv.notify_all(); - } - } - - virtual void connect(const std::string& address, uint16_t port) override{ - std::lock_guard lg1(m_lock); - if (m_state.load(std::memory_order_relaxed) != State::NOT_RUNNING){ - return; - } - try{ - m_state.store(State::CONNECTING, std::memory_order_relaxed); - m_thread = std::thread( - &ClientSocket_WinSocket::thread_loop, - this, address, port - ); - }catch (...){ - m_state.store(State::NOT_RUNNING, std::memory_order_relaxed); - throw; - } - } - - - virtual size_t blocking_send(const void* data, size_t bytes) override{ - if (m_socket == INVALID_SOCKET){ - return 0; - } - - constexpr int BLOCK_SIZE = (int)1 << 30; - const char* ptr = (const char*)data; - size_t sent = 0; - - while (bytes > 0 && state() == State::CONNECTED){ - size_t current = std::min(bytes, BLOCK_SIZE); - int current_sent = ::send(m_socket, ptr, (int)current, 0); - if (current_sent != SOCKET_ERROR){ - sent += current; - if ((size_t)current_sent < current){ - return sent; - } - ptr += current; - bytes -= current; - continue; - } - - int error = WSAGetLastError(); -// cout << "error = " << error << endl; - - std::unique_lock lg(m_lock); - if (state() == State::DESTRUCTING){ - break; - } - - switch (error){ - case WSAEWOULDBLOCK: - break; - default: - m_error = "WSA Error Code: " + std::to_string(error); - return sent; - } - - m_cv.wait_for(lg, std::chrono::milliseconds(1)); - } - return sent; - } - - -private: - void close_socket(){ - if (m_socket == INVALID_SOCKET){ - return; - } - int ret = closesocket(m_socket); - if (ret == 0){ - return; - } - try{ - std::cout << "Failed closesocket(): WSA Error Code = " + std::to_string(ret) << std::endl; - }catch (...){} - } - - void thread_loop(const std::string& address, uint16_t port){ - try{ - thread_loop_internal(address, port); - }catch (...){ - try{ - std::cout << "ClientSocket_WinSocket(): An exception was thrown from the receive thread." << std::endl; - }catch (...){} - } - } - - void thread_loop_internal(const std::string& address, uint16_t port){ - m_listeners.run_method_unique(&Listener::on_thread_start); - - { - std::unique_lock lg(m_lock); - - sockaddr_in server; - server.sin_family = AF_INET; - server.sin_port = htons(port); - server.sin_addr.s_addr = inet_addr(address.c_str()); - - // Connect - while (true){ - State state = m_state.load(std::memory_order_relaxed); - if (state == State::DESTRUCTING){ - return; - } - - if (::connect(m_socket, (struct sockaddr*)&server, sizeof(server)) != SOCKET_ERROR){ - break; - } - - int error = WSAGetLastError(); -// cout << "error = " << error << endl; - - switch (error){ - case WSAEISCONN: - goto Connected; - case WSAEWOULDBLOCK: - case WSAEINVAL: - break; - case WSAETIMEDOUT: - m_state.store(State::NOT_RUNNING, std::memory_order_relaxed); - m_error = "Connection timed out."; - m_lock.unlock(); - m_listeners.run_method_unique(&Listener::on_connect_finished, m_error); - return; - default: - m_state.store(State::NOT_RUNNING, std::memory_order_relaxed); - m_error = "WSA Error Code: " + std::to_string(error); - m_lock.unlock(); - m_listeners.run_method_unique(&Listener::on_connect_finished, m_error); - return; - } - - m_cv.wait_for(lg, std::chrono::milliseconds(10)); - - } - -Connected: - m_state.store(State::CONNECTED, std::memory_order_relaxed); - } - - m_listeners.run_method_unique(&Listener::on_connect_finished, ""); - - - constexpr size_t BUFFER_SIZE = 4096; - char buffer[BUFFER_SIZE]; - - while (true){ - int bytes; - int error = 0; - { - State state = m_state.load(std::memory_order_relaxed); - if (state == State::DESTRUCTING){ - return; - } - bytes = ::recv(m_socket, buffer, BUFFER_SIZE, 0); - if (bytes == SOCKET_ERROR){ - error = WSAGetLastError(); - } - } - - if (bytes > 0){ - m_listeners.run_method_unique(&Listener::on_receive_data, buffer, bytes); - continue; - } - - std::unique_lock lg(m_lock); - if (state() == State::DESTRUCTING){ - return; - } - - if (bytes == SOCKET_ERROR){ -// cout << "error = " << error << endl; - switch (error){ - case WSAEWOULDBLOCK: - break; - default: - m_error = "WSA Error Code: " + std::to_string(error); - return; - } - } - - m_cv.wait_for(lg, std::chrono::milliseconds(1)); - } - - } - - -private: - const SOCKET m_socket; - - std::string m_error; - - mutable std::mutex m_lock; - std::condition_variable m_cv; - std::thread m_thread; -}; - - - -} -#endif +/* Client Socket (Windows) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ClientSocket_WinSocket_H +#define PokemonAutomation_ClientSocket_WinSocket_H + +#include +#include +#include +#include +#include +#include "AbstractClientSocket.h" + +#pragma comment(lib, "Ws2_32.lib") + +namespace PokemonAutomation{ + + + +class ClientSocket_WinSocket final : public AbstractClientSocket{ +public: + ClientSocket_WinSocket() + : m_socket(::socket(AF_INET, SOCK_STREAM, 0)) + { + u_long non_blocking = 1; + if (ioctlsocket(m_socket, FIONBIO, &non_blocking)){ +// cout << "ioctlsocket() Failed" << endl; + close_socket(); + return; + } + } + + virtual ~ClientSocket_WinSocket(){ + close(); + if (m_thread.joinable()){ + m_thread.join(); + } + close_socket(); + } + virtual void close() noexcept override{ + { + std::lock_guard lg1(m_lock); + m_state.store(State::DESTRUCTING, std::memory_order_relaxed); + m_cv.notify_all(); + } + } + + virtual void connect(const std::string& address, uint16_t port) override{ + std::lock_guard lg1(m_lock); + if (m_state.load(std::memory_order_relaxed) != State::NOT_RUNNING){ + return; + } + try{ + m_state.store(State::CONNECTING, std::memory_order_relaxed); + m_thread = std::thread( + &ClientSocket_WinSocket::thread_loop, + this, address, port + ); + }catch (...){ + m_state.store(State::NOT_RUNNING, std::memory_order_relaxed); + throw; + } + } + + + virtual size_t send(const void* data, size_t bytes) override{ + if (m_socket == INVALID_SOCKET){ + return 0; + } + + constexpr int BLOCK_SIZE = (int)1 << 30; + const char* ptr = (const char*)data; + size_t sent = 0; + + while (bytes > 0 && state() == State::CONNECTED){ + size_t current = std::min(bytes, BLOCK_SIZE); + int current_sent = ::send(m_socket, ptr, (int)current, 0); + if (current_sent != SOCKET_ERROR){ + sent += current; + if ((size_t)current_sent < current){ + return sent; + } + ptr += current; + bytes -= current; + continue; + } + + int error = WSAGetLastError(); +// cout << "error = " << error << endl; + + std::unique_lock lg(m_lock); + if (state() == State::DESTRUCTING){ + break; + } + + switch (error){ + case WSAEWOULDBLOCK: + break; + default: + m_error = "WSA Error Code: " + std::to_string(error); + return sent; + } + + m_cv.wait_for(lg, std::chrono::milliseconds(1)); + } + return sent; + } + + +private: + void close_socket(){ + if (m_socket == INVALID_SOCKET){ + return; + } + int ret = closesocket(m_socket); + if (ret == 0){ + return; + } + try{ + std::cout << "Failed closesocket(): WSA Error Code = " + std::to_string(ret) << std::endl; + }catch (...){} + } + + void thread_loop(const std::string& address, uint16_t port){ + try{ + thread_loop_internal(address, port); + }catch (...){ + try{ + std::cout << "ClientSocket_WinSocket(): An exception was thrown from the receive thread." << std::endl; + }catch (...){} + } + } + + void thread_loop_internal(const std::string& address, uint16_t port){ + m_listeners.run_method_unique(&Listener::on_thread_start); + + { + std::unique_lock lg(m_lock); + + sockaddr_in server; + server.sin_family = AF_INET; + server.sin_port = htons(port); + server.sin_addr.s_addr = inet_addr(address.c_str()); + + // Connect + while (true){ + State state = m_state.load(std::memory_order_relaxed); + if (state == State::DESTRUCTING){ + return; + } + + if (::connect(m_socket, (struct sockaddr*)&server, sizeof(server)) != SOCKET_ERROR){ + break; + } + + int error = WSAGetLastError(); +// cout << "error = " << error << endl; + + switch (error){ + case WSAEISCONN: + goto Connected; + case WSAEWOULDBLOCK: + case WSAEINVAL: + break; + case WSAETIMEDOUT: + m_state.store(State::NOT_RUNNING, std::memory_order_relaxed); + m_error = "Connection timed out."; + m_lock.unlock(); + m_listeners.run_method_unique(&Listener::on_connect_finished, m_error); + return; + default: + m_state.store(State::NOT_RUNNING, std::memory_order_relaxed); + m_error = "WSA Error Code: " + std::to_string(error); + m_lock.unlock(); + m_listeners.run_method_unique(&Listener::on_connect_finished, m_error); + return; + } + + m_cv.wait_for(lg, std::chrono::milliseconds(10)); + + } + +Connected: + m_state.store(State::CONNECTED, std::memory_order_relaxed); + } + + m_listeners.run_method_unique(&Listener::on_connect_finished, ""); + + + constexpr size_t BUFFER_SIZE = 4096; + char buffer[BUFFER_SIZE]; + + while (true){ + int bytes; + int error = 0; + { + State state = m_state.load(std::memory_order_relaxed); + if (state == State::DESTRUCTING){ + return; + } + bytes = ::recv(m_socket, buffer, BUFFER_SIZE, 0); + if (bytes == SOCKET_ERROR){ + error = WSAGetLastError(); + } + } + + if (bytes > 0){ + m_listeners.run_method_unique(&Listener::on_receive_data, buffer, bytes); + continue; + } + + std::unique_lock lg(m_lock); + if (state() == State::DESTRUCTING){ + return; + } + + if (bytes == SOCKET_ERROR){ +// cout << "error = " << error << endl; + switch (error){ + case WSAEWOULDBLOCK: + break; + default: + m_error = "WSA Error Code: " + std::to_string(error); + return; + } + } + + m_cv.wait_for(lg, std::chrono::milliseconds(1)); + } + + } + + +private: + const SOCKET m_socket; + + std::string m_error; + + mutable std::mutex m_lock; + std::condition_variable m_cv; + std::thread m_thread; +}; + + + +} +#endif diff --git a/Common/Cpp/Stopwatch.h b/Common/Cpp/Stopwatch.h new file mode 100644 index 0000000000..b9595e0269 --- /dev/null +++ b/Common/Cpp/Stopwatch.h @@ -0,0 +1,54 @@ +/* Stop Watch + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_SnapshotManager_H +#define PokemonAutomation_VideoPipeline_SnapshotManager_H + +#include "Time.h" + +namespace PokemonAutomation{ + + +class Stopwatch{ +public: + Stopwatch() + : m_total(WallDuration::zero()) + , m_last_start(WallClock::max()) + {} + + void start(){ +// cout << "start" << endl; + if (m_last_start != WallClock::max()){ + return; + } + m_last_start = current_time(); + } + void stop(){ +// cout << "stop" << endl; + if (m_last_start == WallClock::max()){ + return; + } + m_total += current_time() - m_last_start; + m_last_start = WallClock::max(); + } + WallDuration total() const{ + WallDuration ret = m_total; + if (m_last_start != WallClock::max()){ + ret += current_time() - m_last_start; + } +// cout << "total: " << std::chrono::duration_cast(ret).count() << endl; + return ret; + } + +private: + WallDuration m_total; + WallClock m_last_start; +}; + + + +} +#endif diff --git a/Common/Qt/Options/ColorWidget.cpp b/Common/Qt/Options/ColorWidget.cpp index 6bd88f5900..d86918c5de 100644 --- a/Common/Qt/Options/ColorWidget.cpp +++ b/Common/Qt/Options/ColorWidget.cpp @@ -1,67 +1,67 @@ -/* Color Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "QHBoxLayout" -#include "ColorWidget.h" - -namespace PokemonAutomation{ - - -ConfigWidget* ColorCell::make_QtWidget(QWidget& parent){ - return new ColorCellWidget(parent, *this); -} - - -ColorCellWidget::~ColorCellWidget(){ - m_value.remove_listener(*this); -} -ColorCellWidget::ColorCellWidget(QWidget& parent, ColorCell& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - QHBoxLayout* layout = new QHBoxLayout(this); - layout->setContentsMargins(0, 0, 5, 0); - - QString str = QString::fromStdString(value.to_str()); - - m_line_edit = new QLineEdit(str, this); - m_line_edit->setFixedWidth(60); - layout->addWidget(m_line_edit); - - m_box = new QLabel(this); - m_box->setTextFormat(Qt::RichText); - layout->addWidget(m_box); - - ColorCellWidget::update_value(); - - connect( - m_line_edit, &QLineEdit::editingFinished, - this, [this](){ - m_value.set(m_line_edit->text().toStdString()); - update_value(); - } - ); - - m_value.add_listener(*this); -} -void ColorCellWidget::update_value(){ - QString str = QString::fromStdString(m_value.to_str()); - m_line_edit->setText(str); - m_box->setText(""); -} -void ColorCellWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(this, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - - -} +/* Color Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "QHBoxLayout" +#include "ColorWidget.h" + +namespace PokemonAutomation{ + + +ConfigWidget* ColorCell::make_QtWidget(QWidget& parent){ + return new ColorCellWidget(parent, *this); +} + + +ColorCellWidget::~ColorCellWidget(){ + m_value.remove_listener(*this); +} +ColorCellWidget::ColorCellWidget(QWidget& parent, ColorCell& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(0, 0, 5, 0); + + QString str = QString::fromStdString(value.to_str()); + + m_line_edit = new QLineEdit(str, this); + m_line_edit->setFixedWidth(60); + layout->addWidget(m_line_edit); + + m_box = new QLabel(this); + m_box->setTextFormat(Qt::RichText); + layout->addWidget(m_box); + + ColorCellWidget::update_value(); + + connect( + m_line_edit, &QLineEdit::editingFinished, + this, [this](){ + m_value.set(m_line_edit->text().toStdString()); + update_value(); + } + ); + + m_value.add_listener(*this); +} +void ColorCellWidget::update_value(){ + QString str = QString::fromStdString(m_value.to_str()); + m_line_edit->setText(str); + m_box->setText(""); +} +void ColorCellWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(this, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + + +} diff --git a/Common/Qt/Options/ColorWidget.h b/Common/Qt/Options/ColorWidget.h index 0ed7343359..d800804faa 100644 --- a/Common/Qt/Options/ColorWidget.h +++ b/Common/Qt/Options/ColorWidget.h @@ -1,40 +1,40 @@ -/* Color Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ColorWidget_H -#define PokemonAutomation_ColorWidget_H - -#include -#include "Common/Cpp/Options/ColorOption.h" -#include "ConfigWidget.h" - -class QLabel; -class QLineEdit; - -namespace PokemonAutomation{ - - - -class ColorCellWidget : public QWidget, public ConfigWidget{ -public: - ~ColorCellWidget(); - ColorCellWidget(QWidget& parent, ColorCell& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - - -private: - ColorCell& m_value; - QLineEdit* m_line_edit; - QLabel* m_box; -}; - - - - -} -#endif +/* Color Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ColorWidget_H +#define PokemonAutomation_ColorWidget_H + +#include +#include "Common/Cpp/Options/ColorOption.h" +#include "ConfigWidget.h" + +class QLabel; +class QLineEdit; + +namespace PokemonAutomation{ + + + +class ColorCellWidget : public QWidget, public ConfigWidget{ +public: + ~ColorCellWidget(); + ColorCellWidget(QWidget& parent, ColorCell& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + + +private: + ColorCell& m_value; + QLineEdit* m_line_edit; + QLabel* m_box; +}; + + + + +} +#endif diff --git a/Common/Qt/Options/KeyBindingWidget.cpp b/Common/Qt/Options/KeyBindingWidget.cpp index 6a26618a69..3fe755c19f 100644 --- a/Common/Qt/Options/KeyBindingWidget.cpp +++ b/Common/Qt/Options/KeyBindingWidget.cpp @@ -1,60 +1,60 @@ -/* Key Binding Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "KeyBindingWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -ConfigWidget* KeyBindingCell::make_QtWidget(QWidget& parent){ - return new KeyBindingCellWidget(parent, *this); -} - - - -KeyBindingCellWidget::~KeyBindingCellWidget(){ - m_value.remove_listener(*this); -} -KeyBindingCellWidget::KeyBindingCellWidget(QWidget& parent, KeyBindingCell& value) - : QLineEdit(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - KeyBindingCellWidget::update_value(); - m_value.add_listener(*this); -} - - -void KeyBindingCellWidget::keyPressEvent(QKeyEvent* event){ - m_value.set(event->key()); -} - - -void KeyBindingCellWidget::update_value(){ - QKeySequence seq((Qt::Key)(uint32_t)m_value); -// cout << (uint32_t)m_value << endl; - this->setText(seq.toString()); -} -void KeyBindingCellWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(this, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - - - - - - -} +/* Key Binding Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "KeyBindingWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +ConfigWidget* KeyBindingCell::make_QtWidget(QWidget& parent){ + return new KeyBindingCellWidget(parent, *this); +} + + + +KeyBindingCellWidget::~KeyBindingCellWidget(){ + m_value.remove_listener(*this); +} +KeyBindingCellWidget::KeyBindingCellWidget(QWidget& parent, KeyBindingCell& value) + : QLineEdit(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + KeyBindingCellWidget::update_value(); + m_value.add_listener(*this); +} + + +void KeyBindingCellWidget::keyPressEvent(QKeyEvent* event){ + m_value.set(event->key()); +} + + +void KeyBindingCellWidget::update_value(){ + QKeySequence seq((Qt::Key)(uint32_t)m_value); +// cout << (uint32_t)m_value << endl; + this->setText(seq.toString()); +} +void KeyBindingCellWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(this, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + + + + + + +} diff --git a/Common/Qt/Options/KeyBindingWidget.h b/Common/Qt/Options/KeyBindingWidget.h index 21877003ac..b492102077 100644 --- a/Common/Qt/Options/KeyBindingWidget.h +++ b/Common/Qt/Options/KeyBindingWidget.h @@ -1,36 +1,36 @@ -/* Key Binding Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_KeyBindingWidget_H -#define PokemonAutomation_Options_KeyBindingWidget_H - -#include -#include "Common/Cpp/Options/KeyBindingOption.h" -#include "ConfigWidget.h" - -namespace PokemonAutomation{ - - - -class KeyBindingCellWidget : public QLineEdit, public ConfigWidget{ -public: - ~KeyBindingCellWidget(); - KeyBindingCellWidget(QWidget& parent, KeyBindingCell& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - - virtual void keyPressEvent(QKeyEvent* event) override; - -private: - KeyBindingCell& m_value; -}; - - - - -} -#endif +/* Key Binding Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_KeyBindingWidget_H +#define PokemonAutomation_Options_KeyBindingWidget_H + +#include +#include "Common/Cpp/Options/KeyBindingOption.h" +#include "ConfigWidget.h" + +namespace PokemonAutomation{ + + + +class KeyBindingCellWidget : public QLineEdit, public ConfigWidget{ +public: + ~KeyBindingCellWidget(); + KeyBindingCellWidget(QWidget& parent, KeyBindingCell& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + + virtual void keyPressEvent(QKeyEvent* event) override; + +private: + KeyBindingCell& m_value; +}; + + + + +} +#endif diff --git a/Common/Qt/Options/MacAddressWidget.cpp b/Common/Qt/Options/MacAddressWidget.cpp index ee897ade12..1085de25e8 100644 --- a/Common/Qt/Options/MacAddressWidget.cpp +++ b/Common/Qt/Options/MacAddressWidget.cpp @@ -1,50 +1,50 @@ -/* MAC Address Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "ConfigWidget.h" -#include "MacAddressWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -MacAddressCellWidget::~MacAddressCellWidget(){ - m_value.remove_listener(*this); -} - -MacAddressCellWidget::MacAddressCellWidget(QWidget& parent, MacAddressCell& value) - : QLineEdit(QString::fromStdString(value.to_string()), &parent) - , ConfigWidget(value, *this) - , m_value(value) -{ -// cout << "sizeHint() = " << this->sizeHint().width() << endl; - - this->setReadOnly(value.lock_mode() == LockMode::READ_ONLY); - - connect( - this, &QLineEdit::editingFinished, - this, [this](){ - m_value.set(this->text().toStdString()); - } - ); - value.add_listener(*this); -} -void MacAddressCellWidget::update_value(){ - this->setText(QString::fromStdString(m_value.to_string())); -} -void MacAddressCellWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(this, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - -} +/* MAC Address Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "ConfigWidget.h" +#include "MacAddressWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +MacAddressCellWidget::~MacAddressCellWidget(){ + m_value.remove_listener(*this); +} + +MacAddressCellWidget::MacAddressCellWidget(QWidget& parent, MacAddressCell& value) + : QLineEdit(QString::fromStdString(value.to_string()), &parent) + , ConfigWidget(value, *this) + , m_value(value) +{ +// cout << "sizeHint() = " << this->sizeHint().width() << endl; + + this->setReadOnly(value.lock_mode() == LockMode::READ_ONLY); + + connect( + this, &QLineEdit::editingFinished, + this, [this](){ + m_value.set(this->text().toStdString()); + } + ); + value.add_listener(*this); +} +void MacAddressCellWidget::update_value(){ + this->setText(QString::fromStdString(m_value.to_string())); +} +void MacAddressCellWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(this, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + +} diff --git a/Common/Qt/Options/MacAddressWidget.h b/Common/Qt/Options/MacAddressWidget.h index a5290aaf17..c5039448ca 100644 --- a/Common/Qt/Options/MacAddressWidget.h +++ b/Common/Qt/Options/MacAddressWidget.h @@ -1,35 +1,35 @@ -/* MAC Address option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_MacAddressWidget_H -#define PokemonAutomation_MacAddressWidget_H - -#include -#include "ConfigWidget.h" -#include "Common/Cpp/Options/MacAddressOption.h" - -namespace PokemonAutomation{ - - - - -class MacAddressCellWidget : public QLineEdit, public ConfigWidget{ -public: - ~MacAddressCellWidget(); - MacAddressCellWidget(QWidget& parent, MacAddressCell& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - MacAddressCell& m_value; -}; - - - - -} -#endif +/* MAC Address option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_MacAddressWidget_H +#define PokemonAutomation_MacAddressWidget_H + +#include +#include "ConfigWidget.h" +#include "Common/Cpp/Options/MacAddressOption.h" + +namespace PokemonAutomation{ + + + + +class MacAddressCellWidget : public QLineEdit, public ConfigWidget{ +public: + ~MacAddressCellWidget(); + MacAddressCellWidget(QWidget& parent, MacAddressCell& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + MacAddressCell& m_value; +}; + + + + +} +#endif diff --git a/Common/Qt/Options/SimpleIntegerWidget.cpp b/Common/Qt/Options/SimpleIntegerWidget.cpp index 1ec19b6601..7d28b68169 100644 --- a/Common/Qt/Options/SimpleIntegerWidget.cpp +++ b/Common/Qt/Options/SimpleIntegerWidget.cpp @@ -136,4 +136,11 @@ template class SimpleIntegerOptionWidget; template class SimpleIntegerOptionWidget; +// This is stupid. +#ifdef __APPLE__ +template class SimpleIntegerCellWidget; +template class SimpleIntegerOptionWidget; +#endif + + } diff --git a/Common/Qt/Options/TimeDurationWidget.cpp b/Common/Qt/Options/TimeDurationWidget.cpp index 8ff3ca8556..2fb0f7db52 100644 --- a/Common/Qt/Options/TimeDurationWidget.cpp +++ b/Common/Qt/Options/TimeDurationWidget.cpp @@ -1,165 +1,165 @@ -/* Time Duration Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "TimeDurationWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -template -TimeDurationCellWidget::~TimeDurationCellWidget(){ - m_value.remove_listener(*this); -} -template -TimeDurationCellWidget::TimeDurationCellWidget(QWidget& parent, TimeDurationCell& value) - : QLineEdit(QString::fromStdString(value.current_text()), &parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - this->setToolTip(QString::fromStdString( - "Time duration in " + value.units() + - "

" - "For controller timings, this will be rounded " - "up to the tick size of the controller." - "

" - "The tick size for wired controllers is usually 8ms and are very precise." - "

" - "Wireless controllers have larger tick sizes and are imprecise due to wireless communication latency." - )); - - connect( - this, &QLineEdit::textChanged, - this, [this](const QString& text){ - std::string error = m_value.set(text.toStdString()); - } - ); - - value.add_listener(*this); -} -template -void TimeDurationCellWidget::update_value(){ - this->setText(QString::fromStdString(m_value.current_text())); -} -template -void TimeDurationCellWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(this, [this]{ - this->update_value(); - }, Qt::QueuedConnection); -} - - - - - -template -TimeDurationOptionWidget::~TimeDurationOptionWidget(){ - m_value.remove_listener(*this); -} -template -TimeDurationOptionWidget::TimeDurationOptionWidget(QWidget& parent, TimeDurationOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - - QHBoxLayout* layout = new QHBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - QLabel* text = new QLabel(QString::fromStdString(m_value.label()), this); - text->setWordWrap(true); - text->setTextFormat(Qt::RichText); - text->setTextInteractionFlags(Qt::TextBrowserInteraction); - text->setOpenExternalLinks(true); - layout->addWidget(text, 1); - QVBoxLayout* rows = new QVBoxLayout(); - layout->addLayout(rows, 1); - - QHBoxLayout* row0 = new QHBoxLayout(); - rows->addLayout(row0); - QHBoxLayout* row1 = new QHBoxLayout(); - rows->addLayout(row1); - - m_box = new QLineEdit(QString::fromStdString(m_value.current_text()), this); - row0->addWidget(m_box); - if (value.show_summary()){ - row0->addWidget(new QLabel(QString::fromStdString(value.units()), this)); - } - m_box->setToolTip(QString::fromStdString( - "Time duration in " + value.units() + - "

" - "For controller timings, this will be rounded " - "up to the tick size of the controller." - "

" - "The tick size for wired controllers is usually 8ms and are very precise." - "

" - "Wireless controllers have larger tick sizes and are imprecise due to wireless communication latency." - )); - - QLabel* description = nullptr; - if (value.show_summary()){ - description = new QLabel(QString::fromStdString(m_value.time_string()), this); - description->setAlignment(Qt::AlignHCenter); - row1->addWidget(description); - } - - connect( - m_box, &QLineEdit::editingFinished, - this, [this, description](){ - std::string error = m_value.set(m_box->text().toStdString()); - if (description == nullptr){ - return; - } - if (error.empty()){ - description->setText(QString::fromStdString(m_value.time_string())); - }else{ - description->setText(QString::fromStdString("" + error + "")); - } - } - ); - connect( - m_box, &QLineEdit::textChanged, - this, [this, description](){ - if (description == nullptr){ - return; - } - std::string text = m_value.time_string(m_box->text().toStdString()); - description->setText(QString::fromStdString(text)); - } - ); - - value.add_listener(*this); -} -template -void TimeDurationOptionWidget::update_value(){ - m_box->setText(QString::fromStdString(m_value.current_text())); -} -template -void TimeDurationOptionWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(m_box, [this]{ - this->update_value(); - }, Qt::QueuedConnection); -} - - - - - -template class TimeDurationCellWidget; -template class TimeDurationCellWidget; -template class TimeDurationOptionWidget; -template class TimeDurationOptionWidget; - - - - -} +/* Time Duration Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "TimeDurationWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +template +TimeDurationCellWidget::~TimeDurationCellWidget(){ + m_value.remove_listener(*this); +} +template +TimeDurationCellWidget::TimeDurationCellWidget(QWidget& parent, TimeDurationCell& value) + : QLineEdit(QString::fromStdString(value.current_text()), &parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + this->setToolTip(QString::fromStdString( + "Time duration in " + value.units() + + "

" + "For controller timings, this will be rounded " + "up to the tick size of the controller." + "

" + "The tick size for wired controllers is usually 8ms and are very precise." + "

" + "Wireless controllers have larger tick sizes and are imprecise due to wireless communication latency." + )); + + connect( + this, &QLineEdit::textChanged, + this, [this](const QString& text){ + std::string error = m_value.set(text.toStdString()); + } + ); + + value.add_listener(*this); +} +template +void TimeDurationCellWidget::update_value(){ + this->setText(QString::fromStdString(m_value.current_text())); +} +template +void TimeDurationCellWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(this, [this]{ + this->update_value(); + }, Qt::QueuedConnection); +} + + + + + +template +TimeDurationOptionWidget::~TimeDurationOptionWidget(){ + m_value.remove_listener(*this); +} +template +TimeDurationOptionWidget::TimeDurationOptionWidget(QWidget& parent, TimeDurationOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + QLabel* text = new QLabel(QString::fromStdString(m_value.label()), this); + text->setWordWrap(true); + text->setTextFormat(Qt::RichText); + text->setTextInteractionFlags(Qt::TextBrowserInteraction); + text->setOpenExternalLinks(true); + layout->addWidget(text, 1); + QVBoxLayout* rows = new QVBoxLayout(); + layout->addLayout(rows, 1); + + QHBoxLayout* row0 = new QHBoxLayout(); + rows->addLayout(row0); + QHBoxLayout* row1 = new QHBoxLayout(); + rows->addLayout(row1); + + m_box = new QLineEdit(QString::fromStdString(m_value.current_text()), this); + row0->addWidget(m_box); + if (value.show_summary()){ + row0->addWidget(new QLabel(QString::fromStdString(value.units()), this)); + } + m_box->setToolTip(QString::fromStdString( + "Time duration in " + value.units() + + "

" + "For controller timings, this will be rounded " + "up to the tick size of the controller." + "

" + "The tick size for wired controllers is usually 8ms and are very precise." + "

" + "Wireless controllers have larger tick sizes and are imprecise due to wireless communication latency." + )); + + QLabel* description = nullptr; + if (value.show_summary()){ + description = new QLabel(QString::fromStdString(m_value.time_string()), this); + description->setAlignment(Qt::AlignHCenter); + row1->addWidget(description); + } + + connect( + m_box, &QLineEdit::editingFinished, + this, [this, description](){ + std::string error = m_value.set(m_box->text().toStdString()); + if (description == nullptr){ + return; + } + if (error.empty()){ + description->setText(QString::fromStdString(m_value.time_string())); + }else{ + description->setText(QString::fromStdString("" + error + "")); + } + } + ); + connect( + m_box, &QLineEdit::textChanged, + this, [this, description](){ + if (description == nullptr){ + return; + } + std::string text = m_value.time_string(m_box->text().toStdString()); + description->setText(QString::fromStdString(text)); + } + ); + + value.add_listener(*this); +} +template +void TimeDurationOptionWidget::update_value(){ + m_box->setText(QString::fromStdString(m_value.current_text())); +} +template +void TimeDurationOptionWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(m_box, [this]{ + this->update_value(); + }, Qt::QueuedConnection); +} + + + + + +template class TimeDurationCellWidget; +template class TimeDurationCellWidget; +template class TimeDurationOptionWidget; +template class TimeDurationOptionWidget; + + + + +} diff --git a/Common/Qt/Options/TimeDurationWidget.h b/Common/Qt/Options/TimeDurationWidget.h index d41c7ae43c..c4f7d9290c 100644 --- a/Common/Qt/Options/TimeDurationWidget.h +++ b/Common/Qt/Options/TimeDurationWidget.h @@ -1,49 +1,49 @@ -/* Time Duration Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_TimeDurationWidget_H -#define PokemonAutomation_Options_TimeDurationWidget_H - -#include -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "ConfigWidget.h" - -namespace PokemonAutomation{ - - - -template -class TimeDurationCellWidget : public QLineEdit, public ConfigWidget{ -public: - ~TimeDurationCellWidget(); - TimeDurationCellWidget(QWidget& parent, TimeDurationCell& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - TimeDurationCell& m_value; -}; - - - -template -class TimeDurationOptionWidget : public QWidget, public ConfigWidget{ -public: - ~TimeDurationOptionWidget(); - TimeDurationOptionWidget(QWidget& parent, TimeDurationOption& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - TimeDurationOption& m_value; - QLineEdit* m_box; -}; - - -} -#endif +/* Time Duration Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_TimeDurationWidget_H +#define PokemonAutomation_Options_TimeDurationWidget_H + +#include +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "ConfigWidget.h" + +namespace PokemonAutomation{ + + + +template +class TimeDurationCellWidget : public QLineEdit, public ConfigWidget{ +public: + ~TimeDurationCellWidget(); + TimeDurationCellWidget(QWidget& parent, TimeDurationCell& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + TimeDurationCell& m_value; +}; + + + +template +class TimeDurationOptionWidget : public QWidget, public ConfigWidget{ +public: + ~TimeDurationOptionWidget(); + TimeDurationOptionWidget(QWidget& parent, TimeDurationOption& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + TimeDurationOption& m_value; + QLineEdit* m_box; +}; + + +} +#endif diff --git a/Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h b/Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h index 7d9c9f2881..7fe3b30e8a 100644 --- a/Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h +++ b/Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h @@ -1,111 +1,111 @@ -/* SerialPABotBase Messages (ESP32) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SerialPABotBase_Messages_ESP32_H -#define PokemonAutomation_SerialPABotBase_Messages_ESP32_H - -#include "SerialPABotBase_Protocol.h" - -#if _WIN32 -#pragma pack(push, 1) -#define PABB_PACK -#elif __GNUC__ -#define PABB_PACK __attribute__((packed)) -#else -#define PABB_PACK -#endif - - -#ifdef __cplusplus -extern "C" { -#endif - - - -typedef struct{ - uint8_t body[3]; - uint8_t buttons[3]; - uint8_t left_grip[3]; - uint8_t right_grip[3]; -} PABB_NintendoSwitch_ControllerColors; - -typedef struct{ - uint8_t button3; - uint8_t button4; - uint8_t button5; - uint8_t left_joystick[3]; - uint8_t right_joystick[3]; - uint8_t vibrator; -} PABB_NintendoSwitch_ButtonState; - -typedef struct{ - int16_t accel_x; - int16_t accel_y; - int16_t accel_z; - int16_t rotation_x; - int16_t rotation_y; - int16_t rotation_z; -} PABB_NintendoSwitch_GyroState; - -typedef struct{ - PABB_NintendoSwitch_GyroState time0; - PABB_NintendoSwitch_GyroState time1; - PABB_NintendoSwitch_GyroState time2; -} PABB_NintendoSwitch_GyroStateX3; - - - - - -#define PABB_MSG_ESP32_REQUEST_READ_SPI 0x60 -typedef struct{ - seqnum_t seqnum; - uint32_t controller_type; - uint32_t address; - uint8_t bytes; -} PABB_PACK pabb_Message_ESP32_ReadSpi; - -#define PABB_MSG_ESP32_REQUEST_WRITE_SPI 0x61 -typedef struct{ - seqnum_t seqnum; - uint32_t controller_type; - uint32_t address; - uint8_t bytes; -} PABB_PACK pabb_Message_ESP32_WriteSpi; - - - -#define PABB_MSG_ESP32_CONTROLLER_STATE_BUTTONS 0xa0 -typedef struct{ - seqnum_t seqnum; - uint16_t milliseconds; - PABB_NintendoSwitch_ButtonState buttons; -} PABB_PACK pabb_Message_ESP32_CommandButtonState; - - -#define PABB_MSG_ESP32_CONTROLLER_STATE_FULL 0xa1 -typedef struct{ - seqnum_t seqnum; - uint16_t milliseconds; - PABB_NintendoSwitch_ButtonState buttons; - PABB_NintendoSwitch_GyroStateX3 gyro; -} PABB_PACK pabb_Message_ESP32_CommandFullState; - - - - -#ifdef __cplusplus -} -#endif - - - -#if _WIN32 -#pragma pack(pop) -#endif - - -#endif +/* SerialPABotBase Messages (ESP32) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SerialPABotBase_Messages_ESP32_H +#define PokemonAutomation_SerialPABotBase_Messages_ESP32_H + +#include "SerialPABotBase_Protocol.h" + +#if _WIN32 +#pragma pack(push, 1) +#define PABB_PACK +#elif __GNUC__ +#define PABB_PACK __attribute__((packed)) +#else +#define PABB_PACK +#endif + + +#ifdef __cplusplus +extern "C" { +#endif + + + +typedef struct{ + uint8_t body[3]; + uint8_t buttons[3]; + uint8_t left_grip[3]; + uint8_t right_grip[3]; +} PABB_NintendoSwitch_ControllerColors; + +typedef struct{ + uint8_t button3; + uint8_t button4; + uint8_t button5; + uint8_t left_joystick[3]; + uint8_t right_joystick[3]; + uint8_t vibrator; +} PABB_NintendoSwitch_ButtonState; + +typedef struct{ + int16_t accel_x; + int16_t accel_y; + int16_t accel_z; + int16_t rotation_x; + int16_t rotation_y; + int16_t rotation_z; +} PABB_NintendoSwitch_GyroState; + +typedef struct{ + PABB_NintendoSwitch_GyroState time0; + PABB_NintendoSwitch_GyroState time1; + PABB_NintendoSwitch_GyroState time2; +} PABB_NintendoSwitch_GyroStateX3; + + + + + +#define PABB_MSG_ESP32_REQUEST_READ_SPI 0x60 +typedef struct{ + seqnum_t seqnum; + uint32_t controller_type; + uint32_t address; + uint8_t bytes; +} PABB_PACK pabb_Message_ESP32_ReadSpi; + +#define PABB_MSG_ESP32_REQUEST_WRITE_SPI 0x61 +typedef struct{ + seqnum_t seqnum; + uint32_t controller_type; + uint32_t address; + uint8_t bytes; +} PABB_PACK pabb_Message_ESP32_WriteSpi; + + + +#define PABB_MSG_ESP32_CONTROLLER_STATE_BUTTONS 0xa0 +typedef struct{ + seqnum_t seqnum; + uint16_t milliseconds; + PABB_NintendoSwitch_ButtonState buttons; +} PABB_PACK pabb_Message_ESP32_CommandButtonState; + + +#define PABB_MSG_ESP32_CONTROLLER_STATE_FULL 0xa1 +typedef struct{ + seqnum_t seqnum; + uint16_t milliseconds; + PABB_NintendoSwitch_ButtonState buttons; + PABB_NintendoSwitch_GyroStateX3 gyro; +} PABB_PACK pabb_Message_ESP32_CommandFullState; + + + + +#ifdef __cplusplus +} +#endif + + + +#if _WIN32 +#pragma pack(pop) +#endif + + +#endif diff --git a/Common/SerialPABotBase/SerialPABotBase_Messages_NS_Generic.h b/Common/SerialPABotBase/SerialPABotBase_Messages_NS_Generic.h index 1a267eee6c..9b4eefee4f 100644 --- a/Common/SerialPABotBase/SerialPABotBase_Messages_NS_Generic.h +++ b/Common/SerialPABotBase/SerialPABotBase_Messages_NS_Generic.h @@ -1,67 +1,58 @@ -/* SerialPABotBase Messages (Nintendo Switch Generic Wired Controller) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SerialPABotBase_Messages_NS_Generic_H -#define PokemonAutomation_SerialPABotBase_Messages_NS_Generic_H - -#include "SerialPABotBase_Protocol.h" - -#if _WIN32 -#pragma pack(push, 1) -#define PABB_PACK -#elif __GNUC__ -#define PABB_PACK __attribute__((packed)) -#else -#define PABB_PACK -#endif - - -#ifdef __cplusplus -namespace PokemonAutomation{ -namespace SerialPABotBase{ -#endif - - - -#define PABB_MSG_NS_GENERIC_CONTROLLER_STATE_TICKS 0x9f -typedef struct{ - seqnum_t seqnum; - uint16_t buttons; - uint8_t dpad; - uint8_t left_joystick_x; - uint8_t left_joystick_y; - uint8_t right_joystick_x; - uint8_t right_joystick_y; - uint8_t ticks; -} PABB_PACK pabb_Message_NS_Generic_ControllerStateTicks; - - - -#define PABB_MSG_NS_GENERIC_CONTROLLER_STATE_MS 0x90 -typedef struct{ - seqnum_t seqnum; - uint16_t milliseconds; - uint16_t buttons; - uint8_t dpad; - uint8_t left_joystick_x; - uint8_t left_joystick_y; - uint8_t right_joystick_x; - uint8_t right_joystick_y; -} PABB_PACK pabb_Message_NS_Generic_ControllerStateMs; - - - -#ifdef __cplusplus -} -} -#endif - - -#if _WIN32 -#pragma pack(pop) -#endif - -#endif +/* SerialPABotBase Messages (Nintendo Switch Generic Wired Controller) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SerialPABotBase_Messages_NS_Generic_H +#define PokemonAutomation_SerialPABotBase_Messages_NS_Generic_H + +#include "SerialPABotBase_Protocol.h" + +#if _WIN32 +#pragma pack(push, 1) +#define PABB_PACK +#elif __GNUC__ +#define PABB_PACK __attribute__((packed)) +#else +#define PABB_PACK +#endif + + +#ifdef __cplusplus +namespace PokemonAutomation{ +namespace SerialPABotBase{ +#endif + + +#define PABB_MSG_NS_GENERIC_CONTROLLER_STATE_MS 0x90 +typedef struct{ + uint8_t buttons0; + uint8_t buttons1; +// uint8_t buttons2; +// uint8_t buttons3; + uint8_t dpad; + uint8_t left_joystick_x; + uint8_t left_joystick_y; + uint8_t right_joystick_x; + uint8_t right_joystick_y; +} pabb_ControllerReport_NS_Generic_Controller; +typedef struct{ + seqnum_t seqnum; + uint16_t milliseconds; + pabb_ControllerReport_NS_Generic_Controller report; +} PABB_PACK pabb_Message_NS_Generic_ControllerStateMs; + + + +#ifdef __cplusplus +} +} +#endif + + +#if _WIN32 +#pragma pack(pop) +#endif + +#endif diff --git a/Common/SerialPABotBase/SerialPABotBase_Protocol.h b/Common/SerialPABotBase/SerialPABotBase_Protocol.h index 7258c7924e..0b9539ab84 100644 --- a/Common/SerialPABotBase/SerialPABotBase_Protocol.h +++ b/Common/SerialPABotBase/SerialPABotBase_Protocol.h @@ -1,362 +1,363 @@ -/* Serial PABotBase Message Protocol - * - * From: https://github.com/PokemonAutomation/ - * - * - * Pokemon Automation Bot-Base implements reliable data transmissions over - * serial communication. This is done by checksumming messages along with a - * protocol that is tolerant to data drops. - * - * This file describes the message protocol. The data being transmitted is raw - * binary and not is readable text. - * - * - * Message Format: - * byte 0: Length of the entire message. (bits are inverted) - * byte 1: Message Type - * byte X: Optional data of variable length. - * Last 4 bytes: CRC32C of the entire message except these last 4 bytes. - * - * Thus there are 6 bytes of overhead for each message. - * - * - * There are currently 4 categories of message types: - * - * 1. Info: These are simple one-way messages. They do not need to be - * acked and may be dropped without adversely affecting anything. - * - * 2. Ack/Response: These are messages sent in response to an earlier - * message that was received. - * - * 3. Request: The sender requests the receiver to do something simple. - * The receiver must respond with an ack. - * - * This is used for things that take no clock time. For example, querying - * for program identifiers, turning on/off LEDs, or setting flags in the - * program to change its behavior in the future. - * - * 4. Command: The sender requests the receiver to do a large asynchronous - * operation. The receiver must ack this message. Once the command is - * finished, the receiver must send a request message back to the sender - * to indicate that the command is finished. - * - * This is used for issuing button presses or other subroutines that - * consume time. - * - * - * General Protocol: - * - * 1. Every time you send a new request/command message, you increment - * your sequence number (seqnum) by 1. - * - * 2. If you receive an invalid message (bad length or bad checksum), ignore - * the first byte and attempt to parse the next byte as the start of a - * new message. - * - * 3. If you receive a zero for the 1st byte of a message, ignore it and - * attempt to parse the next byte as the start of a new message. - * - * 4. At any point, you can send a bunch of zero bytes. This will cause - * the receiver to re-synchronize. - * - * 5. If you receive a request/command message, you must send the appropriate - * ack/response message using the same seqnum. - * - * 6. If you receive a command message, you must first ack the message itself. - * Once the command is finished, you must send a request referencing the - * command to indicate that it is finished. You will receive an ack for - * this short (finishing) command, and if you don't, send it again until - * you do. If the command finishes immediately, you can skip the ack and - * just send the finish request. - * - * 7. If you send a request/command message and don't get a response after - * a time limit, you should resend the message with the same seqnum. - * - * 8. If you receive a request/command that has a seqnum ahead of what you - * are expecting, it means an earlier request/command was dropped. - * Do not process the request/command since you will lose ordering. - * - * 9. If you receive a request/command that has an old seqnum, it is a - * retransmit. Send an ack for it, but don't process it again. (idempotency) - * - * - * Failure Analysis: - * - * - Corrupted messages will either fail checksum or will have an invalid - * length/type. These are simply ignored and dropped. - * - * - If either sender or receiver gets out-of-sync and loses track of - * message boundaries, it will eventually find the boundary again by - * simply trying to parse every byte as the start of a new message and - * verifying the length and CRC. - * - * - If a request/command is dropped, no ack will be received. The sender - * will eventually send the command again. (#7) - * - * - If an ack is dropped, the sender will eventually resend the - * request/command again. The receiver will see the duplicate - * request/command and ack it. But the receiver will not process it - * again to preserve idempotency. (#9) - * - * The current protocol guarantees that all commands are processed in order - * exactly once. Requests are not guaranteed to process in order and may execute - * more than once so they should be idempotent. - * - * The protocol also allows both sides to queue up requests and commands. - * In other words, it is possible to send multiple requests/commands at once - * without waiting for the individual acks. - * - * - * PABotBase Specifics: - * - * - PABotBase can queue up to 4 commands. If it receives any commands - * while the queue is full, it drops it and responds with - * "PABB_MSG_ERROR_COMMAND_DROPPED". (Any command that results in a - * button press or a wait is a long command.) - * - * - PABotBase can still handle other messages while it is running a long - * command. - * - */ - -#ifndef PokemonAutomation_SerialPABotBase_Protocol_H -#define PokemonAutomation_SerialPABotBase_Protocol_H - -#include -#include - -#if _WIN32 -#pragma pack(push, 1) -#define PABB_PACK -#elif __GNUC__ -#define PABB_PACK __attribute__((packed)) -#else -#define PABB_PACK -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -#define PABB_BAUD_RATE 115200 -#define PABB_PROTOCOL_OVERHEAD (2 + sizeof(uint32_t)) - -// Must be a power-of-two. -#define PABB_DEVICE_MINIMUM_QUEUE_SIZE 4 - -typedef uint32_t seqnum_t; - -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -// Basic Message Types - -#define PABB_MSG_IS_ERROR(x) (((x) & 0xf0) == 0x00) // Framework errors between 0x00 - 0x0f. -#define PABB_MSG_IS_ACK(x) (((x) & 0xf0) == 0x10) // Acks between 0x10 - 0x1f. -#define PABB_MSG_IS_INFO(x) (((x) & 0xe0) == 0x20) // Custom info between 0x20 - 0x3f. -#define PABB_MSG_IS_REQUEST(x) (((x) & 0xc0) == 0x40) // Requests between 0x40 - 0x7f. -#define PABB_MSG_IS_COMMAND(x) ((x) >= 0x80) // Commands between 0x80 - 0xff. - -#define PABB_MSG_IS_REQUEST_OR_COMMAND(x) ((x) >= 0x40) - -//////////////////////////////////////////////////////////////////////////////// -// Framework Errors -#define PABB_MSG_ERROR_READY 0x00 -// No Parameters - -#define PABB_MSG_ERROR_INVALID_MESSAGE 0x01 -typedef struct{ - uint8_t message_length; -} PABB_PACK pabb_MsgInfoInvalidMessage; - -#define PABB_MSG_ERROR_CHECKSUM_MISMATCH 0x02 -typedef struct{ - uint8_t message_length; -} PABB_PACK pabb_MsgInfoChecksumMismatch; - -#define PABB_MSG_ERROR_INVALID_TYPE 0x03 -typedef struct{ - uint8_t type; -} PABB_PACK pabb_MsgInfoInvalidType; - -#define PABB_MSG_ERROR_INVALID_REQUEST 0x04 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgInfoInvalidRequest; - -#define PABB_MSG_ERROR_MISSED_REQUEST 0x05 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgInfoMissedRequest; - -#define PABB_MSG_ERROR_COMMAND_DROPPED 0x06 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgInfoCommandDropped; - -#define PABB_MSG_ERROR_WARNING 0x07 -typedef struct{ - uint16_t error_code; -} PABB_PACK pabb_MsgInfoWARNING; - -#define PABB_MSG_ERROR_DISCONNECTED 0x08 -typedef struct{ - uint16_t error_code; -} PABB_PACK pabb_MsgInfoDisconnected; - -//////////////////////////////////////////////////////////////////////////////// -// Ack - -#define PABB_MSG_ACK_COMMAND 0x10 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgAckCommand; - -#define PABB_MSG_ACK_REQUEST 0x11 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgAckRequest; - -#define PABB_MSG_ACK_REQUEST_I8 0x12 -typedef struct{ - seqnum_t seqnum; - uint8_t data; -} PABB_PACK pabb_MsgAckRequestI8; - -#define PABB_MSG_ACK_REQUEST_I16 0x13 -typedef struct{ - seqnum_t seqnum; - uint16_t data; -} PABB_PACK pabb_MsgAckRequestI16; - -#define PABB_MSG_ACK_REQUEST_I32 0x14 -typedef struct{ - seqnum_t seqnum; - uint32_t data; -} PABB_PACK pabb_MsgAckRequestI32; - -#define PABB_MSG_ACK_REQUEST_DATA 0x1f -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgAckRequestData; - -//////////////////////////////////////////////////////////////////////////////// -// Custom Info - -#define PABB_MSG_INFO_I32 0x20 -typedef struct{ - uint8_t tag; - uint32_t data; -} PABB_PACK pabb_MsgInfoI32; - -#define PABB_MSG_INFO_DATA 0x21 -typedef struct{ - uint32_t tag; -} PABB_PACK pabb_MsgInfoData; - -#define PABB_MSG_INFO_STRING 0x23 - -#define PABB_MSG_INFO_I32_LABEL 0x24 -#define PABB_MSG_INFO_H32_LABEL 0x25 -typedef struct{ - uint32_t value; -} PABB_PACK pabb_MsgInfoI32Label; - -//////////////////////////////////////////////////////////////////////////////// -// Requests - -#define PABB_MSG_SEQNUM_RESET 0x40 -// After you send this message, the next seqnum you should use is (seqnum + 1). -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgInfoSeqnumReset; - -#define PABB_MSG_REQUEST_PROTOCOL_VERSION 0x41 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgRequestProtocolVersion; - -#define PABB_MSG_REQUEST_PROGRAM_VERSION 0x42 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgRequestProgramVersion; - -#define PABB_MSG_REQUEST_PROGRAM_ID 0x43 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgRequestProgramID; - -#define PABB_MSG_REQUEST_CLOCK 0x44 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_system_clock; - -#define PABB_MSG_REQUEST_COMMAND_FINISHED 0x45 -// When you receive this message, you must ack it with PABB_MSG_ACK_REQUEST. -typedef struct{ - seqnum_t seqnum; - seqnum_t seq_of_original_command; - uint32_t finish_time; -} PABB_PACK pabb_MsgRequestCommandFinished; - -#define PABB_MSG_REQUEST_STOP 0x46 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgRequestStop; - -#define PABB_MSG_REQUEST_NEXT_CMD_INTERRUPT 0x47 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgRequestNextCmdInterrupt; - -#define PABB_MSG_REQUEST_QUEUE_SIZE 0x48 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgRequestQueueSize; - -#define PABB_MSG_REQUEST_READ_CONTROLLER_MODE 0x49 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgRequestReadControllerMode; - -#define PABB_MSG_REQUEST_CHANGE_CONTROLLER_MODE 0x4a -typedef struct{ - seqnum_t seqnum; - uint32_t mode; -} PABB_PACK pabb_MsgRequestChangeControllerMode; - -//////////////////////////////////////////////////////////////////////////////// -// Common Requests - -#define PABB_MSG_REQUEST_STATUS 0x50 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_Message_RequestStatus; - -//////////////////////////////////////////////////////////////////////////////// -// Commands - -// These are no longer supported by anything. - -#if 0 -#define PABB_MSG_COMMAND_SET_LED_STATE 0x81 -typedef struct{ - seqnum_t seqnum; - bool on; -} PABB_PACK pabb_MsgCommandSetLeds; -#endif - -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -#ifdef __cplusplus -} -#endif - -#if _WIN32 -#pragma pack(pop) -#endif - -#endif +/* Serial PABotBase Message Protocol + * + * From: https://github.com/PokemonAutomation/ + * + * + * Pokemon Automation Bot-Base implements reliable data transmissions over + * serial communication. This is done by checksumming messages along with a + * protocol that is tolerant to data drops. + * + * This file describes the message protocol. The data being transmitted is raw + * binary and not is readable text. + * + * + * Message Format: + * byte 0: Length of the entire message. (bits are inverted) + * byte 1: Message Type + * byte X: Optional data of variable length. + * Last 4 bytes: CRC32C of the entire message except these last 4 bytes. + * + * Thus there are 6 bytes of overhead for each message. + * + * + * There are currently 4 categories of message types: + * + * 1. Info: These are simple one-way messages. They do not need to be + * acked and may be dropped without adversely affecting anything. + * + * 2. Ack/Response: These are messages sent in response to an earlier + * message that was received. + * + * 3. Request: The sender requests the receiver to do something simple. + * The receiver must respond with an ack. + * + * This is used for things that take no clock time. For example, querying + * for program identifiers, turning on/off LEDs, or setting flags in the + * program to change its behavior in the future. + * + * 4. Command: The sender requests the receiver to do a large asynchronous + * operation. The receiver must ack this message. Once the command is + * finished, the receiver must send a request message back to the sender + * to indicate that the command is finished. + * + * This is used for issuing button presses or other subroutines that + * consume time. + * + * + * General Protocol: + * + * 1. Every time you send a new request/command message, you increment + * your sequence number (seqnum) by 1. + * + * 2. If you receive an invalid message (bad length or bad checksum), ignore + * the first byte and attempt to parse the next byte as the start of a + * new message. + * + * 3. If you receive a zero for the 1st byte of a message, ignore it and + * attempt to parse the next byte as the start of a new message. + * + * 4. At any point, you can send a bunch of zero bytes. This will cause + * the receiver to re-synchronize. + * + * 5. If you receive a request/command message, you must send the appropriate + * ack/response message using the same seqnum. + * + * 6. If you receive a command message, you must first ack the message itself. + * Once the command is finished, you must send a request referencing the + * command to indicate that it is finished. You will receive an ack for + * this short (finishing) command, and if you don't, send it again until + * you do. If the command finishes immediately, you can skip the ack and + * just send the finish request. + * + * 7. If you send a request/command message and don't get a response after + * a time limit, you should resend the message with the same seqnum. + * + * 8. If you receive a request/command that has a seqnum ahead of what you + * are expecting, it means an earlier request/command was dropped. + * Do not process the request/command since you will lose ordering. + * + * 9. If you receive a request/command that has an old seqnum, it is a + * retransmit. Send an ack for it, but don't process it again. (idempotency) + * + * + * Failure Analysis: + * + * - Corrupted messages will either fail checksum or will have an invalid + * length/type. These are simply ignored and dropped. + * + * - If either sender or receiver gets out-of-sync and loses track of + * message boundaries, it will eventually find the boundary again by + * simply trying to parse every byte as the start of a new message and + * verifying the length and CRC. + * + * - If a request/command is dropped, no ack will be received. The sender + * will eventually send the command again. (#7) + * + * - If an ack is dropped, the sender will eventually resend the + * request/command again. The receiver will see the duplicate + * request/command and ack it. But the receiver will not process it + * again to preserve idempotency. (#9) + * + * The current protocol guarantees that all commands are processed in order + * exactly once. Requests are not guaranteed to process in order and may execute + * more than once so they should be idempotent. + * + * The protocol also allows both sides to queue up requests and commands. + * In other words, it is possible to send multiple requests/commands at once + * without waiting for the individual acks. + * + * + * PABotBase Specifics: + * + * - PABotBase can queue up to 4 commands. If it receives any commands + * while the queue is full, it drops it and responds with + * "PABB_MSG_ERROR_COMMAND_DROPPED". (Any command that results in a + * button press or a wait is a long command.) + * + * - PABotBase can still handle other messages while it is running a long + * command. + * + */ + +#ifndef PokemonAutomation_SerialPABotBase_Protocol_H +#define PokemonAutomation_SerialPABotBase_Protocol_H + +#include +#include + +#if _WIN32 +#pragma pack(push, 1) +#define PABB_PACK +#elif __GNUC__ +#define PABB_PACK __attribute__((packed)) +#else +#define PABB_PACK +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// + +#define PABB_BAUD_RATE 115200 +#define PABB_PROTOCOL_OVERHEAD (2 + sizeof(uint32_t)) +#define PABB_PROTOCOL_MAX_PACKET_SIZE 64 + +// Must be a power-of-two. +#define PABB_DEVICE_MINIMUM_QUEUE_SIZE 4 + +typedef uint32_t seqnum_t; + +//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// +// Basic Message Types + +#define PABB_MSG_IS_ERROR(x) (((x) & 0xf0) == 0x00) // Framework errors between 0x00 - 0x0f. +#define PABB_MSG_IS_ACK(x) (((x) & 0xf0) == 0x10) // Acks between 0x10 - 0x1f. +#define PABB_MSG_IS_INFO(x) (((x) & 0xe0) == 0x20) // Custom info between 0x20 - 0x3f. +#define PABB_MSG_IS_REQUEST(x) (((x) & 0xc0) == 0x40) // Requests between 0x40 - 0x7f. +#define PABB_MSG_IS_COMMAND(x) ((x) >= 0x80) // Commands between 0x80 - 0xff. + +#define PABB_MSG_IS_REQUEST_OR_COMMAND(x) ((x) >= 0x40) + +//////////////////////////////////////////////////////////////////////////////// +// Framework Errors +#define PABB_MSG_ERROR_READY 0x00 +// No Parameters + +#define PABB_MSG_ERROR_INVALID_MESSAGE 0x01 +typedef struct{ + uint8_t message_length; +} PABB_PACK pabb_MsgInfoInvalidMessage; + +#define PABB_MSG_ERROR_CHECKSUM_MISMATCH 0x02 +typedef struct{ + uint8_t message_length; +} PABB_PACK pabb_MsgInfoChecksumMismatch; + +#define PABB_MSG_ERROR_INVALID_TYPE 0x03 +typedef struct{ + uint8_t type; +} PABB_PACK pabb_MsgInfoInvalidType; + +#define PABB_MSG_ERROR_INVALID_REQUEST 0x04 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgInfoInvalidRequest; + +#define PABB_MSG_ERROR_MISSED_REQUEST 0x05 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgInfoMissedRequest; + +#define PABB_MSG_ERROR_COMMAND_DROPPED 0x06 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgInfoCommandDropped; + +#define PABB_MSG_ERROR_WARNING 0x07 +typedef struct{ + uint16_t error_code; +} PABB_PACK pabb_MsgInfoWARNING; + +#define PABB_MSG_ERROR_DISCONNECTED 0x08 +typedef struct{ + uint16_t error_code; +} PABB_PACK pabb_MsgInfoDisconnected; + +//////////////////////////////////////////////////////////////////////////////// +// Ack + +#define PABB_MSG_ACK_COMMAND 0x10 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgAckCommand; + +#define PABB_MSG_ACK_REQUEST 0x11 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgAckRequest; + +#define PABB_MSG_ACK_REQUEST_I8 0x12 +typedef struct{ + seqnum_t seqnum; + uint8_t data; +} PABB_PACK pabb_MsgAckRequestI8; + +#define PABB_MSG_ACK_REQUEST_I16 0x13 +typedef struct{ + seqnum_t seqnum; + uint16_t data; +} PABB_PACK pabb_MsgAckRequestI16; + +#define PABB_MSG_ACK_REQUEST_I32 0x14 +typedef struct{ + seqnum_t seqnum; + uint32_t data; +} PABB_PACK pabb_MsgAckRequestI32; + +#define PABB_MSG_ACK_REQUEST_DATA 0x1f +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgAckRequestData; + +//////////////////////////////////////////////////////////////////////////////// +// Custom Info + +#define PABB_MSG_INFO_I32 0x20 +typedef struct{ + uint8_t tag; + uint32_t data; +} PABB_PACK pabb_MsgInfoI32; + +#define PABB_MSG_INFO_DATA 0x21 +typedef struct{ + uint32_t tag; +} PABB_PACK pabb_MsgInfoData; + +#define PABB_MSG_INFO_STRING 0x23 + +#define PABB_MSG_INFO_I32_LABEL 0x24 +#define PABB_MSG_INFO_H32_LABEL 0x25 +typedef struct{ + uint32_t value; +} PABB_PACK pabb_MsgInfoI32Label; + +//////////////////////////////////////////////////////////////////////////////// +// Requests + +#define PABB_MSG_SEQNUM_RESET 0x40 +// After you send this message, the next seqnum you should use is (seqnum + 1). +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgInfoSeqnumReset; + +#define PABB_MSG_REQUEST_PROTOCOL_VERSION 0x41 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgRequestProtocolVersion; + +#define PABB_MSG_REQUEST_PROGRAM_VERSION 0x42 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgRequestProgramVersion; + +#define PABB_MSG_REQUEST_PROGRAM_ID 0x43 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgRequestProgramID; + +#define PABB_MSG_REQUEST_CLOCK 0x44 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_system_clock; + +#define PABB_MSG_REQUEST_COMMAND_FINISHED 0x45 +// When you receive this message, you must ack it with PABB_MSG_ACK_REQUEST. +typedef struct{ + seqnum_t seqnum; + seqnum_t seq_of_original_command; + uint32_t finish_time; +} PABB_PACK pabb_MsgRequestCommandFinished; + +#define PABB_MSG_REQUEST_STOP 0x46 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgRequestStop; + +#define PABB_MSG_REQUEST_NEXT_CMD_INTERRUPT 0x47 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgRequestNextCmdInterrupt; + +#define PABB_MSG_REQUEST_QUEUE_SIZE 0x48 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgRequestQueueSize; + +#define PABB_MSG_REQUEST_READ_CONTROLLER_MODE 0x49 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgRequestReadControllerMode; + +#define PABB_MSG_REQUEST_CHANGE_CONTROLLER_MODE 0x4a +typedef struct{ + seqnum_t seqnum; + uint32_t mode; +} PABB_PACK pabb_MsgRequestChangeControllerMode; + +//////////////////////////////////////////////////////////////////////////////// +// Common Requests + +#define PABB_MSG_REQUEST_STATUS 0x50 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_Message_RequestStatus; + +//////////////////////////////////////////////////////////////////////////////// +// Commands + +// These are no longer supported by anything. + +#if 0 +#define PABB_MSG_COMMAND_SET_LED_STATE 0x81 +typedef struct{ + seqnum_t seqnum; + bool on; +} PABB_PACK pabb_MsgCommandSetLeds; +#endif + +//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// + +#ifdef __cplusplus +} +#endif + +#if _WIN32 +#pragma pack(pop) +#endif + +#endif diff --git a/Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h b/Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h index e3689040e1..bf78950ce7 100644 --- a/Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h +++ b/Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h @@ -1,41 +1,41 @@ -/* SerialPABotBase Protocol IDs - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SerialPABotBase_Protocol_IDs_H -#define PokemonAutomation_SerialPABotBase_Protocol_IDs_H - - -// Program IDs -#define PABB_PID_UNSPECIFIED 0x00 - -// Old AVR8 -#define PABB_PID_PABOTBASE_12KB 0x08 -#define PABB_PID_PABOTBASE_31KB 0x09 - -// New AVR8 -#define PABB_PID_PABOTBASE_ArduinoUnoR3 0x01 -#define PABB_PID_PABOTBASE_ArduinoLeonardo 0x02 -#define PABB_PID_PABOTBASE_ProMicro 0x03 -#define PABB_PID_PABOTBASE_Teensy2 0x04 -#define PABB_PID_PABOTBASE_TeensyPP2 0x05 - -// Misc. -#define PABB_PID_PABOTBASE_CH552 0x0a - -// ESP32 -#define PABB_PID_PABOTBASE_ESP32 0x10 -#define PABB_PID_PABOTBASE_ESP32S3 0x12 - - -// Controller IDs -#define PABB_CID_NONE 0 -#define PABB_CID_NINTENDO_SWITCH_WIRED_PRO_CONTROLLER 1 -#define PABB_CID_NINTENDO_SWITCH_WIRELESS_PRO_CONTROLLER 2 -#define PABB_CID_NINTENDO_SWITCH_LEFT_JOYCON 3 -#define PABB_CID_NINTENDO_SWITCH_RIGHT_JOYCON 4 - - -#endif +/* SerialPABotBase Protocol IDs + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SerialPABotBase_Protocol_IDs_H +#define PokemonAutomation_SerialPABotBase_Protocol_IDs_H + + +// Program IDs +#define PABB_PID_UNSPECIFIED 0x00 + +// Old AVR8 +#define PABB_PID_PABOTBASE_12KB 0x08 +#define PABB_PID_PABOTBASE_31KB 0x09 + +// New AVR8 +#define PABB_PID_PABOTBASE_ArduinoUnoR3 0x01 +#define PABB_PID_PABOTBASE_ArduinoLeonardo 0x02 +#define PABB_PID_PABOTBASE_ProMicro 0x03 +#define PABB_PID_PABOTBASE_Teensy2 0x04 +#define PABB_PID_PABOTBASE_TeensyPP2 0x05 + +// Misc. +#define PABB_PID_PABOTBASE_CH552 0x0a + +// ESP32 +#define PABB_PID_PABOTBASE_ESP32 0x10 +#define PABB_PID_PABOTBASE_ESP32S3 0x12 + + +// Controller IDs +#define PABB_CID_NONE 0 +#define PABB_CID_NINTENDO_SWITCH_WIRED_PRO_CONTROLLER 1 +#define PABB_CID_NINTENDO_SWITCH_WIRELESS_PRO_CONTROLLER 2 +#define PABB_CID_NINTENDO_SWITCH_LEFT_JOYCON 3 +#define PABB_CID_NINTENDO_SWITCH_RIGHT_JOYCON 4 + + +#endif diff --git a/IconResource/IconResource.rc b/IconResource/IconResource.rc index a841e99b45..e16ba4098e 100644 --- a/IconResource/IconResource.rc +++ b/IconResource/IconResource.rc @@ -1 +1 @@ -IDI_ICON1 ICON "icon.ico" +IDI_ICON1 ICON "icon.ico" diff --git a/LICENSE b/LICENSE index 495378a644..0b44e57762 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,21 @@ -MIT License - -Copyright (c) 2021 Alexander J. Yee - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +MIT License + +Copyright (c) 2021 Alexander J. Yee + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 0af400e96a..3eb2aec8ef 100644 --- a/README.md +++ b/README.md @@ -1,31 +1,30 @@ -# Arduino-Source - -This is the source code for all the main Arduino programs. - -[](https://discord.gg/cQ4gWxN) - - -# Licensing: -- Unless otherwise specified, all source code in this repository is under the MIT license. -- Some files may be under other (compatible) licenses. -- All precompiled binaries and object files are free for non-commercial use only. For all other uses, please contact the Pokémon Automation server admins. - -# Dependencies: - -| **Dependency** | **License** | -| --- | --- | -| Qt5 and Qt6 | LGPLv3 | -| [QDarkStyleSheet](https://github.com/ColinDuquesnoy/QDarkStyleSheet) | MIT | -| [Qt Wav Reader](https://code.qt.io/cgit/qt/qtmultimedia.git/tree/examples/multimedia/spectrum/app/wavfile.cpp?h=5.15) | BSD | -| [nlohmann json](https://github.com/nlohmann/json) | MIT | -| [Sleepy Discord](https://github.com/yourWaifu/sleepy-discord) | MIT | -| [D++](https://github.com/brainboxdotcc/DPP) | Apache 2.0 | -| [LUFA](https://github.com/abcminiuser/lufa) | MIT | -| [Tesseract](https://github.com/tesseract-ocr/tesseract) | Apache 2.0 | -| [Tesseract for Windows](https://github.com/peirick/Tesseract-OCR_for_Windows) | Apache 2.0 | -| [OpenCV](https://github.com/opencv/opencv) | Apache 2.0 | -| [ONNX](https://github.com/microsoft/onnxruntime) | MIT | - -Vanilla GPL is disallowed, though LGPL is allowed. This is for the following reasons: -1. A tiny portion of the project is not open-sourced. (mostly related to telemetry and internal research experiments) -2. We reserve right to re-license the project in ways that do not abide by the copy-left requirement of GPL. +# Arduino-Source + +This is the source code for all the main Arduino programs. + +[](https://discord.gg/cQ4gWxN) + + +# Licensing: +- Unless otherwise specified, all source code in this repository is under the MIT license. +- Some files may be under other (compatible) licenses. +- All precompiled binaries and object files are free for non-commercial use only. For all other uses, please contact the Pokémon Automation server admins. + +# Dependencies: + +| **Dependency** | **License** | +| --- | --- | +| Qt5 and Qt6 | LGPLv3 | +| [QDarkStyleSheet](https://github.com/ColinDuquesnoy/QDarkStyleSheet) | MIT | +| [Qt Wav Reader](https://code.qt.io/cgit/qt/qtmultimedia.git/tree/examples/multimedia/spectrum/app/wavfile.cpp?h=5.15) | BSD | +| [nlohmann json](https://github.com/nlohmann/json) | MIT | +| [D++](https://github.com/brainboxdotcc/DPP) | Apache 2.0 | +| [LUFA](https://github.com/abcminiuser/lufa) | MIT | +| [Tesseract](https://github.com/tesseract-ocr/tesseract) | Apache 2.0 | +| [Tesseract for Windows](https://github.com/peirick/Tesseract-OCR_for_Windows) | Apache 2.0 | +| [OpenCV](https://github.com/opencv/opencv) | Apache 2.0 | +| [ONNX](https://github.com/microsoft/onnxruntime) | MIT | + +Vanilla GPL is disallowed, though LGPL is allowed. This is for the following reasons: +1. A tiny portion of the project is not open-sourced. (mostly related to telemetry and internal research experiments) +2. We reserve right to re-license the project in ways that do not abide by the copy-left requirement of GPL. diff --git a/SerialPrograms/BuildInstructions/Build-Ubuntu-Qt6.8.2.md b/SerialPrograms/BuildInstructions/Build-Ubuntu-Qt6.8.2.md index ce0129337a..ad65c8191a 100644 --- a/SerialPrograms/BuildInstructions/Build-Ubuntu-Qt6.8.2.md +++ b/SerialPrograms/BuildInstructions/Build-Ubuntu-Qt6.8.2.md @@ -1,54 +1,54 @@ -# How to Build (Qt 6.8.2) - Ubuntu 24.04 - -Note that our Ubuntu setup does not work. The video display flickers to the point of being unusable. - -## Build Tools: - -Install the following packages: - -``` -sudo apt install cmake -sudo apt install libglx-dev libgl1-mesa-dev -sudo apt install libopencv-dev -``` - - -## Install Qt 6.8.2: - -1. Download the online installer from here: https://www.qt.io/download-qt-installer -2. Select custom install settings. -3. Select the following options: - - Qt 6.8.2 - - MSVC 2022 64-bit - - Sources - - Additional Libraries - - Qt Image Formats - - Qt Multimedia - - Qt Serial Port - - Qt Debug Information Files - -![](Images/Windows-Install-Qt6.7.3-Custom.png) -![](Images/Windows-Install-Qt6.8.2-Components.png) - -## Setup: - -1. Clone this repo. -2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). -3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. - -![](Images/Directory.png) - -4. Open Qt Creator. -5. Click on `File` -> `Open File or Project`. -6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. -7. Enable parallel build: Build & Run -> Build Steps -> Build -> Details -> CMake arguments: `-j16` (the # of cores you have) -8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. -9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. - -
- -**Discord Server:** - - -[](https://discord.gg/cQ4gWxN) - +# How to Build (Qt 6.8.2) - Ubuntu 24.04 + +Note that our Ubuntu setup does not work. The video display flickers to the point of being unusable. + +## Build Tools: + +Install the following packages: + +``` +sudo apt install cmake +sudo apt install libglx-dev libgl1-mesa-dev +sudo apt install libopencv-dev +``` + + +## Install Qt 6.8.2: + +1. Download the online installer from here: https://www.qt.io/download-qt-installer +2. Select custom install settings. +3. Select the following options: + - Qt 6.8.2 + - MSVC 2022 64-bit + - Sources + - Additional Libraries + - Qt Image Formats + - Qt Multimedia + - Qt Serial Port + - Qt Debug Information Files + +![](Images/Windows-Install-Qt6.7.3-Custom.png) +![](Images/Windows-Install-Qt6.8.2-Components.png) + +## Setup: + +1. Clone this repo. +2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). +3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. + +![](Images/Directory.png) + +4. Open Qt Creator. +5. Click on `File` -> `Open File or Project`. +6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. +7. Enable parallel build: Build & Run -> Build Steps -> Build -> Details -> CMake arguments: `-j16` (the # of cores you have) +8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. +9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. + +
+ +**Discord Server:** + + +[](https://discord.gg/cQ4gWxN) + diff --git a/SerialPrograms/BuildInstructions/Build-Windows-Qt5.12.md b/SerialPrograms/BuildInstructions/Build-Windows-Qt5.12.md index 050a4f4773..bde70b48ac 100644 --- a/SerialPrograms/BuildInstructions/Build-Windows-Qt5.12.md +++ b/SerialPrograms/BuildInstructions/Build-Windows-Qt5.12.md @@ -1,60 +1,60 @@ -# How to Build (Qt 5.12) - Windows - -## Build Tools: - -1. Install Visual Studio 2019: - 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes) - 2. Make sure you select the C++ development tools. -2. Install Windows Development SDK: - 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) -3. Install CMake: - 1. [Download Page](https://cmake.org/download/) - 2. When prompted select, "Add CMake to the system PATH for all users". -4. Install Qt 5.12.12: - 1. [Download the offline installer.](https://www.qt.io/offline-installers) [Direct Download Link](https://download.qt.io/official_releases/qt/5.12/5.12.12/qt-opensource-windows-x86-5.12.12.exe) - 2. Disconnect from the internet. This is needed to keep it from forcing you to create an account. - 3. Run the installer. - 4. When prompted for components, select all of the following: - - Qt 5.12.12 - - MSVC 2017 32-bit - - MSVC 2017 64-bit - - MinGW 7.3.0 32-bit - - MinGW 7.3.0 64-bit - - Developer and Designer Tools - - Qt Creator 5.0.2 CDB Debugger Support - - MinGW 7.3.0 32-bit - - MinGW 7.3.0 64-bit - -![](Images/Windows-Install-Qt.png) - -## Setup: - -1. Clone this repo. -2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). -3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. - -![](Images/Directory.png) - -4. Open Qt Creator. -5. Click on `Projects` -> `Open`. -6. Navigate to [`SerialPrograms`](./) and select `CMakeLists.txt`. -7. It will then ask you to configure the project. Select `Desktop Qt 5.12.12 MSVC2017 64bit`*. -8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. -9. Open up the file `CMakeLists.txt`. Change `QT_MAJOR` to `5`.![](Images/QT_MAJOR-6.png) -10. Click the upper green arrow** to compile and launch the program. - -![](Images/Windows-Configuration.png) - - -*Even though it says "MSVC2017", it will be using your MSVC 2019 installation instead. - -**Note that you will not be able to feasibly run with a debugger attached. This is because Qt Creator places a breakpoint on every single thrown exception and this application heavily uses exceptions even for non-error situations. So the debugger will break on literally everything. If you know how to disable break on exceptions, please let us know. - - -
- -**Discord Server:** - - -[](https://discord.gg/cQ4gWxN) - +# How to Build (Qt 5.12) - Windows + +## Build Tools: + +1. Install Visual Studio 2019: + 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes) + 2. Make sure you select the C++ development tools. +2. Install Windows Development SDK: + 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) +3. Install CMake: + 1. [Download Page](https://cmake.org/download/) + 2. When prompted select, "Add CMake to the system PATH for all users". +4. Install Qt 5.12.12: + 1. [Download the offline installer.](https://www.qt.io/offline-installers) [Direct Download Link](https://download.qt.io/official_releases/qt/5.12/5.12.12/qt-opensource-windows-x86-5.12.12.exe) + 2. Disconnect from the internet. This is needed to keep it from forcing you to create an account. + 3. Run the installer. + 4. When prompted for components, select all of the following: + - Qt 5.12.12 + - MSVC 2017 32-bit + - MSVC 2017 64-bit + - MinGW 7.3.0 32-bit + - MinGW 7.3.0 64-bit + - Developer and Designer Tools + - Qt Creator 5.0.2 CDB Debugger Support + - MinGW 7.3.0 32-bit + - MinGW 7.3.0 64-bit + +![](Images/Windows-Install-Qt.png) + +## Setup: + +1. Clone this repo. +2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). +3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. + +![](Images/Directory.png) + +4. Open Qt Creator. +5. Click on `Projects` -> `Open`. +6. Navigate to [`SerialPrograms`](./) and select `CMakeLists.txt`. +7. It will then ask you to configure the project. Select `Desktop Qt 5.12.12 MSVC2017 64bit`*. +8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. +9. Open up the file `CMakeLists.txt`. Change `QT_MAJOR` to `5`.![](Images/QT_MAJOR-6.png) +10. Click the upper green arrow** to compile and launch the program. + +![](Images/Windows-Configuration.png) + + +*Even though it says "MSVC2017", it will be using your MSVC 2019 installation instead. + +**Note that you will not be able to feasibly run with a debugger attached. This is because Qt Creator places a breakpoint on every single thrown exception and this application heavily uses exceptions even for non-error situations. So the debugger will break on literally everything. If you know how to disable break on exceptions, please let us know. + + +
+ +**Discord Server:** + + +[](https://discord.gg/cQ4gWxN) + diff --git a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.3.2.md b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.3.2.md index ae21e17237..0109817209 100644 --- a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.3.2.md +++ b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.3.2.md @@ -1,81 +1,81 @@ -# How to Build (Qt 6.3.2) - Windows - -We recommend that you install everything here in the exact order listed and the exact versions mentioned. Failing either will likely result in a broken Qt Creator installation that must be fixed by manually configuring it (which is not fun if you don't know what you're doing). - -Required Versions: -- **Visual Studio 2019** - You must install VS2019. If you install VS2022 instead, your Qt Creator installation will be broken. It is ok to have both VS2019 and VS2022 installed. But you must have VS2019 as that is the version that Qt Creator will look for. -- **Qt 6.3.2** - Do not install a later version of Qt. All Qt versions 6.4.x - 6.5.2 are broken for this project. - -## Build Tools: - -The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. - -1. Install Visual Studio 2019: - 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes) - 2. Make sure you select the C++ development tools. -2. Install Windows Development SDK: - 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) -3. Install CMake: - 1. [Download Page](https://cmake.org/download/) - 2. When prompted select, "Add CMake to the system PATH for all users". - -## Install Qt 6.3.2: - -Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. - -### Official Online Installer: - -If you are ok with creating an account with Qt and using their online installer, then use this method. - -1. Download the online installer from here: https://www.qt.io/download-qt-installer -2. When prompted to select components, check `Archive` on the right side bar, then click `Filter`. Then select the following options: - - - Qt 6.3.2 - - MSVC 2019 64-bit - - Sources - - Additional Libraries - - Qt Image Formats - - Qt Multimedia - - Qt Serial Port - - Qt Debug Information Files - -![](Images/Windows-Install-Qt6.3.1.png) - -If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. - -### Unofficial Installation Copy: - -If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. - -1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. -2. Download `Qt6.3.2.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. -3. Move this folder to `C:\`. It will probably ask you for permissions to do it. -4. Navigate to: `C:\Qt6.3.2\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 8.0.1 (Community)`) - -*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. - -## Setup: - -1. Clone this repo. -2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). -3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. - -![](Images/Directory.png) - -4. Open Qt Creator. -5. Click on `File` -> `Open File or Project`. -6. Navigate to [`SerialPrograms`](./) and select `CMakeLists.txt`. -7. It will then ask you to configure the project. Select `Desktop Qt 6.3.2 MSVC2019 64bit`. Click `Configure Project`. -![](Images/Windows-configure-project.png) -8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. -![](Images/Windows-Configuration-Qt6.png) -9. At the bottom left corner, click the upper green arrow to compile and launch the program. - - -
- -**Discord Server:** - - -[](https://discord.gg/cQ4gWxN) - +# How to Build (Qt 6.3.2) - Windows + +We recommend that you install everything here in the exact order listed and the exact versions mentioned. Failing either will likely result in a broken Qt Creator installation that must be fixed by manually configuring it (which is not fun if you don't know what you're doing). + +Required Versions: +- **Visual Studio 2019** - You must install VS2019. If you install VS2022 instead, your Qt Creator installation will be broken. It is ok to have both VS2019 and VS2022 installed. But you must have VS2019 as that is the version that Qt Creator will look for. +- **Qt 6.3.2** - Do not install a later version of Qt. All Qt versions 6.4.x - 6.5.2 are broken for this project. + +## Build Tools: + +The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. + +1. Install Visual Studio 2019: + 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes) + 2. Make sure you select the C++ development tools. +2. Install Windows Development SDK: + 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) +3. Install CMake: + 1. [Download Page](https://cmake.org/download/) + 2. When prompted select, "Add CMake to the system PATH for all users". + +## Install Qt 6.3.2: + +Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. + +### Official Online Installer: + +If you are ok with creating an account with Qt and using their online installer, then use this method. + +1. Download the online installer from here: https://www.qt.io/download-qt-installer +2. When prompted to select components, check `Archive` on the right side bar, then click `Filter`. Then select the following options: + + - Qt 6.3.2 + - MSVC 2019 64-bit + - Sources + - Additional Libraries + - Qt Image Formats + - Qt Multimedia + - Qt Serial Port + - Qt Debug Information Files + +![](Images/Windows-Install-Qt6.3.1.png) + +If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. + +### Unofficial Installation Copy: + +If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. + +1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. +2. Download `Qt6.3.2.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. +3. Move this folder to `C:\`. It will probably ask you for permissions to do it. +4. Navigate to: `C:\Qt6.3.2\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 8.0.1 (Community)`) + +*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. + +## Setup: + +1. Clone this repo. +2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). +3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. + +![](Images/Directory.png) + +4. Open Qt Creator. +5. Click on `File` -> `Open File or Project`. +6. Navigate to [`SerialPrograms`](./) and select `CMakeLists.txt`. +7. It will then ask you to configure the project. Select `Desktop Qt 6.3.2 MSVC2019 64bit`. Click `Configure Project`. +![](Images/Windows-configure-project.png) +8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. +![](Images/Windows-Configuration-Qt6.png) +9. At the bottom left corner, click the upper green arrow to compile and launch the program. + + +
+ +**Discord Server:** + + +[](https://discord.gg/cQ4gWxN) + diff --git a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.4.md b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.4.md index 67c560b804..e5d464243c 100644 --- a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.4.md +++ b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.4.md @@ -1,67 +1,67 @@ -# How to Build (Qt 6.4) - Windows - -***Note: Qt 6.4 is not recommended at this time due to a bug in their video pipeline that distorts colors.*** - -## Build Tools: - -1. Install Visual Studio 2019: - 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes) - 2. Make sure you select the C++ development tools. -2. Install Windows Development SDK: - 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) -3. Install CMake: - 1. [Download Page](https://cmake.org/download/) - 2. When prompted select, "Add CMake to the system PATH for all users". - -## Install Qt 6.4: - -Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. - -### Official Online Installer: - -If you are ok with creating an account with Qt and using their online installer, then use this method. - -1. Download the online installer from here: https://www.qt.io/download-qt-installer -2. Select the following options: ![](Images/Windows-Install-Qt6.4.0.png) - -If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. - -### Unofficial Installation Copy: - -If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. - -1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. -2. Download `Qt6.4.0.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. -3. Move this folder to `C:\`. It will probably ask you for permissions to do it. -4. Navigate to: `C:\Qt6.4.0\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 8.0.1 (Community)`) - -*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. - -## Setup: - -1. Clone this repo. -2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). -3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. - -![](Images/Directory.png) - -4. Open Qt Creator. -5. Click on `Projects` -> `Open`. -6. Navigate to [`SerialPrograms`](./) and select `CMakeLists.txt`. -7. It will then ask you to configure the project. Select `Desktop Qt 6.4.0 MSVC2019 64bit`. -8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. -9. Open up the file `CMakeLists.txt`. Change `QT_MAJOR` to `6`.![](Images/QT_MAJOR-6.png) -10. Click the upper green arrow to compile and launch the program. - -![](Images/Windows-Configuration-Qt6.png) - - - - -
- -**Discord Server:** - - -[](https://discord.gg/cQ4gWxN) - +# How to Build (Qt 6.4) - Windows + +***Note: Qt 6.4 is not recommended at this time due to a bug in their video pipeline that distorts colors.*** + +## Build Tools: + +1. Install Visual Studio 2019: + 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes) + 2. Make sure you select the C++ development tools. +2. Install Windows Development SDK: + 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) +3. Install CMake: + 1. [Download Page](https://cmake.org/download/) + 2. When prompted select, "Add CMake to the system PATH for all users". + +## Install Qt 6.4: + +Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. + +### Official Online Installer: + +If you are ok with creating an account with Qt and using their online installer, then use this method. + +1. Download the online installer from here: https://www.qt.io/download-qt-installer +2. Select the following options: ![](Images/Windows-Install-Qt6.4.0.png) + +If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. + +### Unofficial Installation Copy: + +If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. + +1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. +2. Download `Qt6.4.0.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. +3. Move this folder to `C:\`. It will probably ask you for permissions to do it. +4. Navigate to: `C:\Qt6.4.0\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 8.0.1 (Community)`) + +*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. + +## Setup: + +1. Clone this repo. +2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). +3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. + +![](Images/Directory.png) + +4. Open Qt Creator. +5. Click on `Projects` -> `Open`. +6. Navigate to [`SerialPrograms`](./) and select `CMakeLists.txt`. +7. It will then ask you to configure the project. Select `Desktop Qt 6.4.0 MSVC2019 64bit`. +8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. +9. Open up the file `CMakeLists.txt`. Change `QT_MAJOR` to `6`.![](Images/QT_MAJOR-6.png) +10. Click the upper green arrow to compile and launch the program. + +![](Images/Windows-Configuration-Qt6.png) + + + + +
+ +**Discord Server:** + + +[](https://discord.gg/cQ4gWxN) + diff --git a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.5.2.md b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.5.2.md index 4c35a3baed..a6b479b310 100644 --- a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.5.2.md +++ b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.5.2.md @@ -1,73 +1,73 @@ -# How to Build (Qt 6.5.2) - Windows - -***Qt 6.5.2 is broken for this project. Please use [Qt 6.3.2](Build-Qt6.3.2.md) instead.*** - -Required Versions: -- **Visual Studio 2019** - You must install VS2019. If you install VS2022 instead, your Qt Creator installation will be broken. It is ok to have both VS2019 and VS2022 installed. But you must have VS2019 as that is the version that Qt Creator will look for. -- **Qt 6.5.2** - N/A. This version is broken. - -## Build Tools: - -The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. - -1. Install Visual Studio 2019: - 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes) - 2. Make sure you select the C++ development tools. -2. Install Windows Development SDK: - 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) -3. Install CMake: - 1. [Download Page](https://cmake.org/download/) - 2. When prompted select, "Add CMake to the system PATH for all users". - -## Install Qt 6.5.2: - -Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. - -### Official Online Installer: - -If you are ok with creating an account with Qt and using their online installer, then use this method. - -1. Download the online installer from here: https://www.qt.io/download-qt-installer -2. Select the following options: ![](Images/Windows-Install-Qt6.4.0.png) - -If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. - -### Unofficial Installation Copy: - -If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. - -1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. -2. Download `Qt6.5.2.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. -3. Move this folder to `C:\`. It will probably ask you for permissions to do it. -4. Navigate to: `C:\Qt6.5.2\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 11.0.2 (Community)`) - -*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. - -## Setup: - -1. Clone this repo. -2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). -3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. - -![](Images/Directory.png) - -4. Open Qt Creator. -5. Click on `Projects` -> `Open`. -6. Navigate to [`SerialPrograms`](./) and select `CMakeLists.txt`. -7. It will then ask you to configure the project. Select `Desktop Qt 6.5.2 MSVC2019 64bit`. -8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. -9. Open up the file `CMakeLists.txt`. Change `QT_MAJOR` to `6`.![](Images/QT_MAJOR-6.png) -10. Click the upper green arrow to compile and launch the program. - -![](Images/Windows-Configuration-Qt6.png) - - - - -
- -**Discord Server:** - - -[](https://discord.gg/cQ4gWxN) - +# How to Build (Qt 6.5.2) - Windows + +***Qt 6.5.2 is broken for this project. Please use [Qt 6.3.2](Build-Qt6.3.2.md) instead.*** + +Required Versions: +- **Visual Studio 2019** - You must install VS2019. If you install VS2022 instead, your Qt Creator installation will be broken. It is ok to have both VS2019 and VS2022 installed. But you must have VS2019 as that is the version that Qt Creator will look for. +- **Qt 6.5.2** - N/A. This version is broken. + +## Build Tools: + +The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. + +1. Install Visual Studio 2019: + 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes) + 2. Make sure you select the C++ development tools. +2. Install Windows Development SDK: + 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) +3. Install CMake: + 1. [Download Page](https://cmake.org/download/) + 2. When prompted select, "Add CMake to the system PATH for all users". + +## Install Qt 6.5.2: + +Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. + +### Official Online Installer: + +If you are ok with creating an account with Qt and using their online installer, then use this method. + +1. Download the online installer from here: https://www.qt.io/download-qt-installer +2. Select the following options: ![](Images/Windows-Install-Qt6.4.0.png) + +If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. + +### Unofficial Installation Copy: + +If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. + +1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. +2. Download `Qt6.5.2.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. +3. Move this folder to `C:\`. It will probably ask you for permissions to do it. +4. Navigate to: `C:\Qt6.5.2\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 11.0.2 (Community)`) + +*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. + +## Setup: + +1. Clone this repo. +2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). +3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. + +![](Images/Directory.png) + +4. Open Qt Creator. +5. Click on `Projects` -> `Open`. +6. Navigate to [`SerialPrograms`](./) and select `CMakeLists.txt`. +7. It will then ask you to configure the project. Select `Desktop Qt 6.5.2 MSVC2019 64bit`. +8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. +9. Open up the file `CMakeLists.txt`. Change `QT_MAJOR` to `6`.![](Images/QT_MAJOR-6.png) +10. Click the upper green arrow to compile and launch the program. + +![](Images/Windows-Configuration-Qt6.png) + + + + +
+ +**Discord Server:** + + +[](https://discord.gg/cQ4gWxN) + diff --git a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.5.3.md b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.5.3.md index 14f80303d4..22ccb2c376 100644 --- a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.5.3.md +++ b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.5.3.md @@ -1,92 +1,92 @@ -# How to Build (Qt 6.5.3) - Windows - -Required Versions: -- **Visual Studio 2019** - You must install VS2019. If you install VS2022 instead, your Qt Creator installation will be broken. It is ok to have both VS2019 and VS2022 installed. But you must have VS2019 as that is the version that Qt Creator will look for. - -## Build Tools: - -The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. - -1. Install Visual Studio 2019: - 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes) - 2. Make sure you select the C++ development tools. -2. Install Windows Development SDK: - 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) -3. Install CMake: - 1. [Download Page](https://cmake.org/download/) - 2. When prompted select, "Add CMake to the system PATH for all users". - -## Install Qt 6.5.3: - -Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. - -### Official Online Installer: - -If you are ok with creating an account with Qt and using their online installer, then use this method. - -1. Download the online installer from here: https://www.qt.io/download-qt-installer -2. Select the following options: - - Qt 6.5.3 - - MSVC 2019 64-bit - - Sources - - Additional Libraries - - Qt Image Formats - - Qt Multimedia - - Qt Serial Port - - Qt Debug Information Files - -![](Images/Windows-Install-Qt6.5.3.png) - -If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. - -### Unofficial Installation Copy: - -If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. - -1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. -2. Download `Qt6.5.3.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. -3. Move this folder to `C:\`. It will probably ask you for permissions to do it. -4. Navigate to: `C:\Qt6.5.3\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 11.0.3 (Community)`) - -*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. - -## Setup: - -1. Clone this repo. -2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). -3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. - -![](Images/Directory.png) - -4. Open Qt Creator. -5. Click on `File` -> `Open File or Project`. -6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. -7. It will then ask you to configure the project. Ensure `Desktop Qt 6.5.3 MSVC2019 64bit` and `Release with Debug Information` are selected. - - Ensure the build directory for `Desktop_Qt_6_5_3_MSVC2019_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - Click `Configure Project`. - -![](Images/Windows-configure-project-qt-creator-13.png) - -8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. - -![](Images/Windows-Configuration-Qt6.png) - -9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. - -## Troubleshooting - -### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing - -- Click `Projects` on the left sidebar. -- In `Build directory`, ensure the build directory for `Desktop_Qt_6_5_3_MSVC2019_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_5_3_MSVC2019_64bit-RelWithDebInfo` - - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_5_3_MSVC2019_64bit-RelWithDebInfo` - - -
- -**Discord Server:** - - -[](https://discord.gg/cQ4gWxN) - +# How to Build (Qt 6.5.3) - Windows + +Required Versions: +- **Visual Studio 2019** - You must install VS2019. If you install VS2022 instead, your Qt Creator installation will be broken. It is ok to have both VS2019 and VS2022 installed. But you must have VS2019 as that is the version that Qt Creator will look for. + +## Build Tools: + +The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. + +1. Install Visual Studio 2019: + 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes) + 2. Make sure you select the C++ development tools. +2. Install Windows Development SDK: + 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) +3. Install CMake: + 1. [Download Page](https://cmake.org/download/) + 2. When prompted select, "Add CMake to the system PATH for all users". + +## Install Qt 6.5.3: + +Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. + +### Official Online Installer: + +If you are ok with creating an account with Qt and using their online installer, then use this method. + +1. Download the online installer from here: https://www.qt.io/download-qt-installer +2. Select the following options: + - Qt 6.5.3 + - MSVC 2019 64-bit + - Sources + - Additional Libraries + - Qt Image Formats + - Qt Multimedia + - Qt Serial Port + - Qt Debug Information Files + +![](Images/Windows-Install-Qt6.5.3.png) + +If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. + +### Unofficial Installation Copy: + +If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. + +1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. +2. Download `Qt6.5.3.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. +3. Move this folder to `C:\`. It will probably ask you for permissions to do it. +4. Navigate to: `C:\Qt6.5.3\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 11.0.3 (Community)`) + +*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. + +## Setup: + +1. Clone this repo. +2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). +3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. + +![](Images/Directory.png) + +4. Open Qt Creator. +5. Click on `File` -> `Open File or Project`. +6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. +7. It will then ask you to configure the project. Ensure `Desktop Qt 6.5.3 MSVC2019 64bit` and `Release with Debug Information` are selected. + - Ensure the build directory for `Desktop_Qt_6_5_3_MSVC2019_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - Click `Configure Project`. + +![](Images/Windows-configure-project-qt-creator-13.png) + +8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. + +![](Images/Windows-Configuration-Qt6.png) + +9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. + +## Troubleshooting + +### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing + +- Click `Projects` on the left sidebar. +- In `Build directory`, ensure the build directory for `Desktop_Qt_6_5_3_MSVC2019_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_5_3_MSVC2019_64bit-RelWithDebInfo` + - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_5_3_MSVC2019_64bit-RelWithDebInfo` + + +
+ +**Discord Server:** + + +[](https://discord.gg/cQ4gWxN) + diff --git a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.7.3.md b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.7.3.md index c8f0c6572a..97a9401ca1 100644 --- a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.7.3.md +++ b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.7.3.md @@ -1,93 +1,93 @@ -# How to Build (Qt 6.7.3) - Windows - -**(Note: These instructions have not been fully tested for 6.7.3. Let us know if you encounter any issues.)** - -## Build Tools: - -The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. - -1. Install Visual Studio 2022: - 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes) - 2. Make sure you select the C++ development tools. -2. Install Windows Development SDK: - 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) -3. Install CMake: - 1. [Download Page](https://cmake.org/download/) - 2. When prompted select, "Add CMake to the system PATH for all users". - -## Install Qt 6.7.3: - -Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. - -### Official Online Installer: - -If you are ok with creating an account with Qt and using their online installer, then use this method. - -1. Download the online installer from here: https://www.qt.io/download-qt-installer -2. Select custom install settings. -3. Select the following options: - - Qt 6.7.3 - - MSVC 2022 64-bit - - Sources - - Additional Libraries - - Qt Image Formats - - Qt Multimedia - - Qt Serial Port - - Qt Debug Information Files - -![](Images/Windows-Install-Qt6.7.3-Custom.png) -![](Images/Windows-Install-Qt6.7.3-Components.png) - -If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. - -### Unofficial Installation Copy: - -If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. - -1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. -2. Download `Qt6.7.3.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. -3. Move this folder to `C:\`. It will probably ask you for permissions to do it. -4. Navigate to: `C:\Qt6.7.3\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 14.0.2 (Community)`) - -*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. - -## Setup: - -1. Clone this repo. -2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). -3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. - -![](Images/Directory.png) - -4. Open Qt Creator. -5. Click on `File` -> `Open File or Project`. -6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. -7. It will then ask you to configure the project. Ensure `Desktop Qt 6.7.3 MSVC2022 64bit` and `Release with Debug Information` are selected. - - Ensure the build directory for `Desktop_Qt_6_7_3_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - Click `Configure Project`. - -![](Images/Windows-configure-project-qt-creator-13.png) - -8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. - -![](Images/Windows-Configuration-Qt6.png) - -9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. - -## Troubleshooting - -### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing - -- Click `Projects` on the left sidebar. -- In `Build directory`, ensure the build directory for `Desktop_Qt_6_7_3_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_7_3_MSVC2022_64bit-RelWithDebInfo` - - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_7_3_MSVC2022_64bit-RelWithDebInfo` - - -
- -**Discord Server:** - - -[](https://discord.gg/cQ4gWxN) - +# How to Build (Qt 6.7.3) - Windows + +**(Note: These instructions have not been fully tested for 6.7.3. Let us know if you encounter any issues.)** + +## Build Tools: + +The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. + +1. Install Visual Studio 2022: + 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes) + 2. Make sure you select the C++ development tools. +2. Install Windows Development SDK: + 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) +3. Install CMake: + 1. [Download Page](https://cmake.org/download/) + 2. When prompted select, "Add CMake to the system PATH for all users". + +## Install Qt 6.7.3: + +Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. + +### Official Online Installer: + +If you are ok with creating an account with Qt and using their online installer, then use this method. + +1. Download the online installer from here: https://www.qt.io/download-qt-installer +2. Select custom install settings. +3. Select the following options: + - Qt 6.7.3 + - MSVC 2022 64-bit + - Sources + - Additional Libraries + - Qt Image Formats + - Qt Multimedia + - Qt Serial Port + - Qt Debug Information Files + +![](Images/Windows-Install-Qt6.7.3-Custom.png) +![](Images/Windows-Install-Qt6.7.3-Components.png) + +If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. + +### Unofficial Installation Copy: + +If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. + +1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. +2. Download `Qt6.7.3.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. +3. Move this folder to `C:\`. It will probably ask you for permissions to do it. +4. Navigate to: `C:\Qt6.7.3\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 14.0.2 (Community)`) + +*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. + +## Setup: + +1. Clone this repo. +2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). +3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. + +![](Images/Directory.png) + +4. Open Qt Creator. +5. Click on `File` -> `Open File or Project`. +6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. +7. It will then ask you to configure the project. Ensure `Desktop Qt 6.7.3 MSVC2022 64bit` and `Release with Debug Information` are selected. + - Ensure the build directory for `Desktop_Qt_6_7_3_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - Click `Configure Project`. + +![](Images/Windows-configure-project-qt-creator-13.png) + +8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. + +![](Images/Windows-Configuration-Qt6.png) + +9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. + +## Troubleshooting + +### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing + +- Click `Projects` on the left sidebar. +- In `Build directory`, ensure the build directory for `Desktop_Qt_6_7_3_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_7_3_MSVC2022_64bit-RelWithDebInfo` + - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_7_3_MSVC2022_64bit-RelWithDebInfo` + + +
+ +**Discord Server:** + + +[](https://discord.gg/cQ4gWxN) + diff --git a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.0.md b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.0.md index bc0c2ee0df..c8b5c12c58 100644 --- a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.0.md +++ b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.0.md @@ -1,93 +1,93 @@ -# How to Build (Qt 6.8.0) - Windows - -**(Note: These instructions have not been fully tested for 6.8.0. Let us know if you encounter any issues.)** - -## Build Tools: - -The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. - -1. Install Visual Studio 2022: - 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes) - 2. Make sure you select the C++ development tools. -2. Install Windows Development SDK: - 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) -3. Install CMake: - 1. [Download Page](https://cmake.org/download/) - 2. When prompted select, "Add CMake to the system PATH for all users". - -## Install Qt 6.8.0: - -Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. - -### Official Online Installer: - -If you are ok with creating an account with Qt and using their online installer, then use this method. - -1. Download the online installer from here: https://www.qt.io/download-qt-installer -2. Select custom install settings. -3. Select the following options: - - Qt 6.8.0 - - MSVC 2022 64-bit - - Sources - - Additional Libraries - - Qt Image Formats - - Qt Multimedia - - Qt Serial Port - - Qt Debug Information Files - -![](Images/Windows-Install-Qt6.7.3-Custom.png) -![](Images/Windows-Install-Qt6.8.0-Components.png) - -If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. - -### Unofficial Installation Copy: - -If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. - -1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. -2. Download `Qt6.8.0.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. -3. Move this folder to `C:\`. It will probably ask you for permissions to do it. -4. Navigate to: `C:\Qt6.8.0\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 14.0.2 (Community)`) - -*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. - -## Setup: - -1. Clone this repo. -2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). -3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. - -![](Images/Directory.png) - -4. Open Qt Creator. -5. Click on `File` -> `Open File or Project`. -6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. -7. It will then ask you to configure the project. Ensure `Desktop Qt 6.8.0 MSVC2022 64bit` and `Release with Debug Information` are selected. - - Ensure the build directory for `Desktop_Qt_6_8_0_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - Click `Configure Project`. - -![](Images/Windows-configure-project-qt-creator-13.png) - -8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. - -![](Images/Windows-Configuration-Qt6.png) - -9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. - -## Troubleshooting - -### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing - -- Click `Projects` on the left sidebar. -- In `Build directory`, ensure the build directory for `Desktop_Qt_6_8_0_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_8_0_MSVC2022_64bit-RelWithDebInfo` - - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_8_0_MSVC2022_64bit-RelWithDebInfo` - - -
- -**Discord Server:** - - -[](https://discord.gg/cQ4gWxN) - +# How to Build (Qt 6.8.0) - Windows + +**(Note: These instructions have not been fully tested for 6.8.0. Let us know if you encounter any issues.)** + +## Build Tools: + +The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. + +1. Install Visual Studio 2022: + 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes) + 2. Make sure you select the C++ development tools. +2. Install Windows Development SDK: + 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) +3. Install CMake: + 1. [Download Page](https://cmake.org/download/) + 2. When prompted select, "Add CMake to the system PATH for all users". + +## Install Qt 6.8.0: + +Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. + +### Official Online Installer: + +If you are ok with creating an account with Qt and using their online installer, then use this method. + +1. Download the online installer from here: https://www.qt.io/download-qt-installer +2. Select custom install settings. +3. Select the following options: + - Qt 6.8.0 + - MSVC 2022 64-bit + - Sources + - Additional Libraries + - Qt Image Formats + - Qt Multimedia + - Qt Serial Port + - Qt Debug Information Files + +![](Images/Windows-Install-Qt6.7.3-Custom.png) +![](Images/Windows-Install-Qt6.8.0-Components.png) + +If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. + +### Unofficial Installation Copy: + +If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. + +1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. +2. Download `Qt6.8.0.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. +3. Move this folder to `C:\`. It will probably ask you for permissions to do it. +4. Navigate to: `C:\Qt6.8.0\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 14.0.2 (Community)`) + +*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. + +## Setup: + +1. Clone this repo. +2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). +3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. + +![](Images/Directory.png) + +4. Open Qt Creator. +5. Click on `File` -> `Open File or Project`. +6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. +7. It will then ask you to configure the project. Ensure `Desktop Qt 6.8.0 MSVC2022 64bit` and `Release with Debug Information` are selected. + - Ensure the build directory for `Desktop_Qt_6_8_0_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - Click `Configure Project`. + +![](Images/Windows-configure-project-qt-creator-13.png) + +8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. + +![](Images/Windows-Configuration-Qt6.png) + +9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. + +## Troubleshooting + +### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing + +- Click `Projects` on the left sidebar. +- In `Build directory`, ensure the build directory for `Desktop_Qt_6_8_0_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_8_0_MSVC2022_64bit-RelWithDebInfo` + - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_8_0_MSVC2022_64bit-RelWithDebInfo` + + +
+ +**Discord Server:** + + +[](https://discord.gg/cQ4gWxN) + diff --git a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.1.md b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.1.md index 7edd88177d..ef5a42af85 100644 --- a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.1.md +++ b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.1.md @@ -1,90 +1,90 @@ -# How to Build (Qt 6.8.1) - Windows - -## Build Tools: - -The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. - -1. Install Visual Studio 2022: - 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes) - 2. Make sure you select the C++ development tools. -2. Install Windows Development SDK: - 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) -3. Install CMake: - 1. [Download Page](https://cmake.org/download/) - 2. When prompted select, "Add CMake to the system PATH for all users". - -## Install Qt 6.8.1: - -Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. - -### Official Online Installer: - -If you are ok with creating an account with Qt and using their online installer, then use this method. - -1. Download the online installer from here: https://www.qt.io/download-qt-Images/ -3. Select the following options: - - Qt 6.8.1 - - MSVC 2022 64-bit - - Sources - - Additional Libraries - - Qt Image Formats - - Qt Multimedia - - Qt Serial Port - - Qt Debug Information Files - -![](Images/Windows-Install-Qt6.7.3-Custom.png) -![](Images/Windows-Install-Qt6.8.1-Components.png) - -If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. - -### Unofficial Installation Copy: - -If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. - -1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. -2. Download `Qt6.8.1.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. -3. Move this folder to `C:\`. It will probably ask you for permissions to do it. -4. Navigate to: `C:\Qt6.8.1\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 15.0.0 (Community)`) - -*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. - -## Setup: - -1. Clone this repo. -2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). -3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. - -![](Images/Directory.png) - -4. Open Qt Creator. -5. Click on `File` -> `Open File or Project`. -6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. -7. It will then ask you to configure the project. Ensure `Desktop Qt 6.8.1 MSVC2022 64bit` and `Release with Debug Information` are selected. - - Ensure the build directory for `Desktop_Qt_6_8_1_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - Click `Configure Project`. - -![](Images/Windows-configure-project-qt-creator-13.png) - -8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. - -![](Images/Windows-Configuration-Qt6.png) - -9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. - -## Troubleshooting - -### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing - -- Click `Projects` on the left sidebar. -- In `Build directory`, ensure the build directory for `Desktop_Qt_6_8_1_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_8_1_MSVC2022_64bit-RelWithDebInfo` - - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_8_1_MSVC2022_64bit-RelWithDebInfo` - - -
- -**Discord Server:** - - -[](https://discord.gg/cQ4gWxN) - +# How to Build (Qt 6.8.1) - Windows + +## Build Tools: + +The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. + +1. Install Visual Studio 2022: + 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes) + 2. Make sure you select the C++ development tools. +2. Install Windows Development SDK: + 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) +3. Install CMake: + 1. [Download Page](https://cmake.org/download/) + 2. When prompted select, "Add CMake to the system PATH for all users". + +## Install Qt 6.8.1: + +Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. + +### Official Online Installer: + +If you are ok with creating an account with Qt and using their online installer, then use this method. + +1. Download the online installer from here: https://www.qt.io/download-qt-Images/ +3. Select the following options: + - Qt 6.8.1 + - MSVC 2022 64-bit + - Sources + - Additional Libraries + - Qt Image Formats + - Qt Multimedia + - Qt Serial Port + - Qt Debug Information Files + +![](Images/Windows-Install-Qt6.7.3-Custom.png) +![](Images/Windows-Install-Qt6.8.1-Components.png) + +If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. + +### Unofficial Installation Copy: + +If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. + +1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. +2. Download `Qt6.8.1.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. +3. Move this folder to `C:\`. It will probably ask you for permissions to do it. +4. Navigate to: `C:\Qt6.8.1\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 15.0.0 (Community)`) + +*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. + +## Setup: + +1. Clone this repo. +2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). +3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. + +![](Images/Directory.png) + +4. Open Qt Creator. +5. Click on `File` -> `Open File or Project`. +6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. +7. It will then ask you to configure the project. Ensure `Desktop Qt 6.8.1 MSVC2022 64bit` and `Release with Debug Information` are selected. + - Ensure the build directory for `Desktop_Qt_6_8_1_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - Click `Configure Project`. + +![](Images/Windows-configure-project-qt-creator-13.png) + +8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. + +![](Images/Windows-Configuration-Qt6.png) + +9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. + +## Troubleshooting + +### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing + +- Click `Projects` on the left sidebar. +- In `Build directory`, ensure the build directory for `Desktop_Qt_6_8_1_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_8_1_MSVC2022_64bit-RelWithDebInfo` + - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_8_1_MSVC2022_64bit-RelWithDebInfo` + + +
+ +**Discord Server:** + + +[](https://discord.gg/cQ4gWxN) + diff --git a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.2.md b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.2.md index 6081212503..3029c96f52 100644 --- a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.2.md +++ b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.2.md @@ -1,90 +1,90 @@ -# How to Build (Qt 6.8.2) - Windows - -## Build Tools: - -The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. - -1. Install Visual Studio 2022: - 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes) - 2. Make sure you select the C++ development tools. -2. Install Windows Development SDK: - 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) -3. Install CMake: - 1. [Download Page](https://cmake.org/download/) - 2. When prompted select, "Add CMake to the system PATH for all users". - -## Install Qt 6.8.2: - -Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. - -### Official Online Installer: - -If you are ok with creating an account with Qt and using their online installer, then use this method. - -1. Download the online installer from here: https://www.qt.io/download-qt-Images/ -3. Select the following options: - - Qt 6.8.2 - - MSVC 2022 64-bit - - Sources - - Additional Libraries - - Qt Image Formats - - Qt Multimedia - - Qt Serial Port - - Qt Debug Information Files - -![](Images/Windows-Install-Qt6.7.3-Custom.png) -![](Images/Windows-Install-Qt6.8.2-Components.png) - -If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. - -### Unofficial Installation Copy: - -If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. - -1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. -2. Download `Qt6.8.2.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. -3. Move this folder to `C:\`. It will probably ask you for permissions to do it. -4. Navigate to: `C:\Qt6.8.2\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 15.0.1 (Community)`) - -*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. - -## Setup: - -1. Clone this repo. -2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). -3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. - -![](Images/Directory.png) - -4. Open Qt Creator. -5. Click on `File` -> `Open File or Project`. -6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. -7. It will then ask you to configure the project. Ensure `Desktop Qt 6.8.2 MSVC2022 64bit` and `Release with Debug Information` are selected. - - Ensure the build directory for `Desktop_Qt_6_8_2_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - Click `Configure Project`. - -![](Images/Windows-configure-project-qt-creator-13.png) - -8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. - -![](Images/Windows-Configuration-Qt6.png) - -9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. - -## Troubleshooting - -### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing - -- Click `Projects` on the left sidebar. -- In `Build directory`, ensure the build directory for `Desktop_Qt_6_8_2_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_8_1_MSVC2022_64bit-RelWithDebInfo` - - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_8_2_MSVC2022_64bit-RelWithDebInfo` - - -
- -**Discord Server:** - - -[](https://discord.gg/cQ4gWxN) - +# How to Build (Qt 6.8.2) - Windows + +## Build Tools: + +The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. + +1. Install Visual Studio 2022: + 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes) + 2. Make sure you select the C++ development tools. +2. Install Windows Development SDK: + 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) +3. Install CMake: + 1. [Download Page](https://cmake.org/download/) + 2. When prompted select, "Add CMake to the system PATH for all users". + +## Install Qt 6.8.2: + +Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. + +### Official Online Installer: + +If you are ok with creating an account with Qt and using their online installer, then use this method. + +1. Download the online installer from here: https://www.qt.io/download-qt-Images/ +3. Select the following options: + - Qt 6.8.2 + - MSVC 2022 64-bit + - Sources + - Additional Libraries + - Qt Image Formats + - Qt Multimedia + - Qt Serial Port + - Qt Debug Information Files + +![](Images/Windows-Install-Qt6.7.3-Custom.png) +![](Images/Windows-Install-Qt6.8.2-Components.png) + +If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. + +### Unofficial Installation Copy: + +If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. + +1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. +2. Download `Qt6.8.2.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. +3. Move this folder to `C:\`. It will probably ask you for permissions to do it. +4. Navigate to: `C:\Qt6.8.2\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 15.0.1 (Community)`) + +*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. + +## Setup: + +1. Clone this repo. +2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). +3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. + +![](Images/Directory.png) + +4. Open Qt Creator. +5. Click on `File` -> `Open File or Project`. +6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. +7. It will then ask you to configure the project. Ensure `Desktop Qt 6.8.2 MSVC2022 64bit` and `Release with Debug Information` are selected. + - Ensure the build directory for `Desktop_Qt_6_8_2_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - Click `Configure Project`. + +![](Images/Windows-configure-project-qt-creator-13.png) + +8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. + +![](Images/Windows-Configuration-Qt6.png) + +9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. + +## Troubleshooting + +### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing + +- Click `Projects` on the left sidebar. +- In `Build directory`, ensure the build directory for `Desktop_Qt_6_8_2_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_8_1_MSVC2022_64bit-RelWithDebInfo` + - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_8_2_MSVC2022_64bit-RelWithDebInfo` + + +
+ +**Discord Server:** + + +[](https://discord.gg/cQ4gWxN) + diff --git a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.3.md b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.3.md index 6f007a31c6..21165e9ff4 100644 --- a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.3.md +++ b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.3.md @@ -1,126 +1,126 @@ -# How to Build (Qt 6.8.3) - Windows - -**(Note: These instructions have not been fully tested for 6.8.3. Let us know if you encounter any issues.)** - -## Build Tools: - -The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. - -1. Install Visual Studio 2022: - 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes) - 2. Make sure you select the C++ development tools. -2. Install Windows Development SDK: - 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) -3. Install CMake: - 1. [Download Page](https://cmake.org/download/) - 2. When prompted select, "Add CMake to the system PATH for all users". - -## Install Qt 6.8.3: - -Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. - -### Official Online Installer: - -If you are ok with creating an account with Qt and using their online installer, then use this method. - -1. Download the online installer from here: https://www.qt.io/download-qt-Images/ -3. Select the following options: - - Qt 6.8.3 - - MSVC 2022 64-bit - - Sources - - Additional Libraries - - Qt Image Formats - - Qt Multimedia - - Qt Serial Port - - Qt Debug Information Files - -![](Images/Windows-Install-Qt6.8.3-Custom.png) -![](Images/Windows-Install-Qt6.8.3-Components.png) - -If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. - -### Unofficial Installation Copy: - -If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. - -1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. -2. Download `Qt6.8.3.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. -3. Move this folder to `C:\`. It will probably ask you for permissions to do it. -4. Navigate to: `C:\Qt6.8.3\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 16.0.0 (Community)`) - -*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. - -## Setup: - -1. Clone this repo. -2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). -3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. - -![](Images/Directory.png) - -4. Open Qt Creator. -5. Click on `File` -> `Open File or Project`. -6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. -7. It will then ask you to configure the project. Ensure `Desktop Qt 6.8.3 MSVC2022 64bit` and `Release with Debug Information` are selected. - - Ensure the build directory for `Desktop_Qt_6_8_2_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - Click `Configure Project`. - -![](Images/Windows-configure-project-qt-creator-13.png) - -8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. - -![](Images/Windows-Configuration-Qt6.png) - -9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. - -## Troubleshooting - -### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing - -- Click `Projects` on the left sidebar. -- In `Build directory`, ensure the build directory for `Desktop_Qt_6_8_3_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_8_3_MSVC2022_64bit-RelWithDebInfo` - - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_8_3_MSVC2022_64bit-RelWithDebInfo` - - -## Upgrading Qt components - -### Installing newer Qt version -If you have already have older versions of Qt installed, but need to upgrade Qt components, you can use the Maintenance tool, which comes pre-instaled with Qt (C:\Qt\MaintenanceTool.exe). - -- When prompted, in `Maintenance Actions`, choose `Add or remove components`. -- You may select the components needed, as per the instructions above, for the newer version. And de-select old versions to remove them, if you wish. -- Optional: In `Maintenance Actions`, you may also choose `Update components` as well. To update Qt Creator, and other components. - -### Building with the newer Qt version -- Open the `SerialPrograms` project in Qt, as outlined in the "Setup" section above. -- In the toolbar, click `Edit` -> `Preferences` -- Under `Kits` tab, choose the newer Qt version (e.g. Desktop Qt 6.8.3) - - -- Under `Compiler`, set it to Microsoft Visual C++ Compiler or Visual Studio, if not already set. -- Click `Ok`, to save Kits preferences. -- Click the Monitor symbol at the bottom left - - -- Under `Kit`: choose the desired Qt version. -- Under `Build`: choose `Release with Debug Information` -- Click the green arrow to compile and launch the program. -- Optional: Move the `UserSettings` folder from the old build folder to the new build folder, to keep your old settings, such as the dev key. - -### Upgrade compiler -- Upgrade the compiler by installing a new version of Visual Studio. Ensure `Desktop development with C++` is checked, so the latest MSVC compiler is also installed. -- Open the `SerialPrograms` project in Qt, as outlined in the "Setup" section above. -- In the toolbar, click `Edit` -> `Preferences` -- Click the `Kits` tab on the left. Then click the `Compilers` tab, click `Re-detect` to refresh the list of compilers. Then click `Apply` in the bottom right. -- Back in the `Kits` tab, your newly installed compilers should now show up in the list of compilers. - -When building, if you get the error `yvals_core.h:931: error: STL1001: Unexpected compiler version, expected MSVC 19.42 or newer` (or something similar), consider deleting the old build folder, and rebuilding from scratch. - -
- -**Discord Server:** - - -[](https://discord.gg/cQ4gWxN) - +# How to Build (Qt 6.8.3) - Windows + +**(Note: These instructions have not been fully tested for 6.8.3. Let us know if you encounter any issues.)** + +## Build Tools: + +The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. + +1. Install Visual Studio 2022: + 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes) + 2. Make sure you select the C++ development tools. +2. Install Windows Development SDK: + 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) +3. Install CMake: + 1. [Download Page](https://cmake.org/download/) + 2. When prompted select, "Add CMake to the system PATH for all users". + +## Install Qt 6.8.3: + +Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. + +### Official Online Installer: + +If you are ok with creating an account with Qt and using their online installer, then use this method. + +1. Download the online installer from here: https://www.qt.io/download-qt-Images/ +3. Select the following options: + - Qt 6.8.3 + - MSVC 2022 64-bit + - Sources + - Additional Libraries + - Qt Image Formats + - Qt Multimedia + - Qt Serial Port + - Qt Debug Information Files + +![](Images/Windows-Install-Qt6.8.3-Custom.png) +![](Images/Windows-Install-Qt6.8.3-Components.png) + +If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. + +### Unofficial Installation Copy: + +If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. + +1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. +2. Download `Qt6.8.3.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. +3. Move this folder to `C:\`. It will probably ask you for permissions to do it. +4. Navigate to: `C:\Qt6.8.3\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 16.0.0 (Community)`) + +*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. + +## Setup: + +1. Clone this repo. +2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). +3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. + +![](Images/Directory.png) + +4. Open Qt Creator. +5. Click on `File` -> `Open File or Project`. +6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. +7. It will then ask you to configure the project. Ensure `Desktop Qt 6.8.3 MSVC2022 64bit` and `Release with Debug Information` are selected. + - Ensure the build directory for `Desktop_Qt_6_8_2_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - Click `Configure Project`. + +![](Images/Windows-configure-project-qt-creator-13.png) + +8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. + +![](Images/Windows-Configuration-Qt6.png) + +9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. + +## Troubleshooting + +### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing + +- Click `Projects` on the left sidebar. +- In `Build directory`, ensure the build directory for `Desktop_Qt_6_8_3_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_8_3_MSVC2022_64bit-RelWithDebInfo` + - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_8_3_MSVC2022_64bit-RelWithDebInfo` + + +## Upgrading Qt components + +### Installing newer Qt version +If you have already have older versions of Qt installed, but need to upgrade Qt components, you can use the Maintenance tool, which comes pre-instaled with Qt (C:\Qt\MaintenanceTool.exe). + +- When prompted, in `Maintenance Actions`, choose `Add or remove components`. +- You may select the components needed, as per the instructions above, for the newer version. And de-select old versions to remove them, if you wish. +- Optional: In `Maintenance Actions`, you may also choose `Update components` as well. To update Qt Creator, and other components. + +### Building with the newer Qt version +- Open the `SerialPrograms` project in Qt, as outlined in the "Setup" section above. +- In the toolbar, click `Edit` -> `Preferences` +- Under `Kits` tab, choose the newer Qt version (e.g. Desktop Qt 6.8.3) + + +- Under `Compiler`, set it to Microsoft Visual C++ Compiler or Visual Studio, if not already set. +- Click `Ok`, to save Kits preferences. +- Click the Monitor symbol at the bottom left + + +- Under `Kit`: choose the desired Qt version. +- Under `Build`: choose `Release with Debug Information` +- Click the green arrow to compile and launch the program. +- Optional: Move the `UserSettings` folder from the old build folder to the new build folder, to keep your old settings, such as the dev key. + +### Upgrade compiler +- Upgrade the compiler by installing a new version of Visual Studio. Ensure `Desktop development with C++` is checked, so the latest MSVC compiler is also installed. +- Open the `SerialPrograms` project in Qt, as outlined in the "Setup" section above. +- In the toolbar, click `Edit` -> `Preferences` +- Click the `Kits` tab on the left. Then click the `Compilers` tab, click `Re-detect` to refresh the list of compilers. Then click `Apply` in the bottom right. +- Back in the `Kits` tab, your newly installed compilers should now show up in the list of compilers. + +When building, if you get the error `yvals_core.h:931: error: STL1001: Unexpected compiler version, expected MSVC 19.42 or newer` (or something similar), consider deleting the old build folder, and rebuilding from scratch. + +
+ +**Discord Server:** + + +[](https://discord.gg/cQ4gWxN) + diff --git a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.9.0.md b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.9.0.md index e992af6ddd..7011973486 100644 --- a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.9.0.md +++ b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.9.0.md @@ -1,126 +1,126 @@ -# How to Build (Qt 6.9.0) - Windows - -**(Note: These instructions have not been fully tested for 6.9.0. Let us know if you encounter any issues.)** - -## Build Tools: - -The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. - -1. Install Visual Studio 2022: - 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes) - 2. Make sure you select the C++ development tools. -2. Install Windows Development SDK: - 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) -3. Install CMake: - 1. [Download Page](https://cmake.org/download/) - 2. When prompted select, "Add CMake to the system PATH for all users". - -## Install Qt 6.9.0: - -Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. - -### Official Online Installer: - -If you are ok with creating an account with Qt and using their online installer, then use this method. - -1. Download the online installer from here: https://www.qt.io/download-qt-Images/ -3. Select the following options: - - Qt 6.9.0 - - MSVC 2022 64-bit - - Sources - - Additional Libraries - - Qt Image Formats - - Qt Multimedia - - Qt Serial Port - - Qt Debug Information Files - -![](Images/Windows-Install-Qt6.9.0-Custom.png) -![](Images/Windows-Install-Qt6.9.0-Components.png) - -If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. - -### Unofficial Installation Copy: - -If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. - -1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. -2. Download `Qt6.9.0.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. -3. Move this folder to `C:\`. It will probably ask you for permissions to do it. -4. Navigate to: `C:\Qt6.9.0\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 16.0.0 (Community)`) - -*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. - -## Setup: - -1. Clone this repo. -2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). -3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. - -![](Images/Directory.png) - -4. Open Qt Creator. -5. Click on `File` -> `Open File or Project`. -6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. -7. It will then ask you to configure the project. Ensure `Desktop Qt 6.9.0 MSVC2022 64bit` and `Release with Debug Information` are selected. - - Ensure the build directory for `Desktop_Qt_6_9_0_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - Click `Configure Project`. - -![](Images/Windows-configure-project-qt-creator-13.png) - -8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. - -![](Images/Windows-Configuration-Qt6.png) - -9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. - -## Troubleshooting - -### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing - -- Click `Projects` on the left sidebar. -- In `Build directory`, ensure the build directory for `Desktop_Qt_6_9_0_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_9_0_MSVC2022_64bit-RelWithDebInfo` - - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_9_0_MSVC2022_64bit-RelWithDebInfo` - - -## Upgrading Qt components - -### Installing newer Qt version -If you have already have older versions of Qt installed, but need to upgrade Qt components, you can use the Maintenance tool, which comes pre-instaled with Qt (C:\Qt\MaintenanceTool.exe). - -- When prompted, in `Maintenance Actions`, choose `Add or remove components`. -- You may select the components needed, as per the instructions above, for the newer version. And de-select old versions to remove them, if you wish. -- Optional: In `Maintenance Actions`, you may also choose `Update components` as well. To update Qt Creator, and other components. - -### Building with the newer Qt version -- Open the `SerialPrograms` project in Qt, as outlined in the "Setup" section above. -- In the toolbar, click `Edit` -> `Preferences` -- Under `Kits` tab, choose the newer Qt version (e.g. Desktop Qt 6.8.3) - - -- Under `Compiler`, set it to Microsoft Visual C++ Compiler or Visual Studio, if not already set. -- Click `Ok`, to save Kits preferences. -- Click the Monitor symbol at the bottom left - - -- Under `Kit`: choose the desired Qt version. -- Under `Build`: choose `Release with Debug Information` -- Click the green arrow to compile and launch the program. -- Optional: Move the `UserSettings` folder from the old build folder to the new build folder, to keep your old settings, such as the dev key. - -### Upgrade compiler -- Upgrade the compiler by installing a new version of Visual Studio. Ensure `Desktop development with C++` is checked, so the latest MSVC compiler is also installed. -- Open the `SerialPrograms` project in Qt, as outlined in the "Setup" section above. -- In the toolbar, click `Edit` -> `Preferences` -- Click the `Kits` tab on the left. Then click the `Compilers` tab, click `Re-detect` to refresh the list of compilers. Then click `Apply` in the bottom right. -- Back in the `Kits` tab, your newly installed compilers should now show up in the list of compilers. - -When building, if you get the error `yvals_core.h:931: error: STL1001: Unexpected compiler version, expected MSVC 19.42 or newer` (or something similar), consider deleting the old build folder, and rebuilding from scratch. - -
- -**Discord Server:** - - -[](https://discord.gg/cQ4gWxN) - +# How to Build (Qt 6.9.0) - Windows + +**(Note: These instructions have not been fully tested for 6.9.0. Let us know if you encounter any issues.)** + +## Build Tools: + +The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. + +1. Install Visual Studio 2022: + 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes) + 2. Make sure you select the C++ development tools. +2. Install Windows Development SDK: + 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) +3. Install CMake: + 1. [Download Page](https://cmake.org/download/) + 2. When prompted select, "Add CMake to the system PATH for all users". + +## Install Qt 6.9.0: + +Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. + +### Official Online Installer: + +If you are ok with creating an account with Qt and using their online installer, then use this method. + +1. Download the online installer from here: https://www.qt.io/download-qt-Images/ +3. Select the following options: + - Qt 6.9.0 + - MSVC 2022 64-bit + - Sources + - Additional Libraries + - Qt Image Formats + - Qt Multimedia + - Qt Serial Port + - Qt Debug Information Files + +![](Images/Windows-Install-Qt6.9.0-Custom.png) +![](Images/Windows-Install-Qt6.9.0-Components.png) + +If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. + +### Unofficial Installation Copy: + +If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. + +1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. +2. Download `Qt6.9.0.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. +3. Move this folder to `C:\`. It will probably ask you for permissions to do it. +4. Navigate to: `C:\Qt6.9.0\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 16.0.0 (Community)`) + +*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. + +## Setup: + +1. Clone this repo. +2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). +3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. + +![](Images/Directory.png) + +4. Open Qt Creator. +5. Click on `File` -> `Open File or Project`. +6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. +7. It will then ask you to configure the project. Ensure `Desktop Qt 6.9.0 MSVC2022 64bit` and `Release with Debug Information` are selected. + - Ensure the build directory for `Desktop_Qt_6_9_0_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - Click `Configure Project`. + +![](Images/Windows-configure-project-qt-creator-13.png) + +8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. + +![](Images/Windows-Configuration-Qt6.png) + +9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. + +## Troubleshooting + +### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing + +- Click `Projects` on the left sidebar. +- In `Build directory`, ensure the build directory for `Desktop_Qt_6_9_0_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_9_0_MSVC2022_64bit-RelWithDebInfo` + - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_9_0_MSVC2022_64bit-RelWithDebInfo` + + +## Upgrading Qt components + +### Installing newer Qt version +If you have already have older versions of Qt installed, but need to upgrade Qt components, you can use the Maintenance tool, which comes pre-instaled with Qt (C:\Qt\MaintenanceTool.exe). + +- When prompted, in `Maintenance Actions`, choose `Add or remove components`. +- You may select the components needed, as per the instructions above, for the newer version. And de-select old versions to remove them, if you wish. +- Optional: In `Maintenance Actions`, you may also choose `Update components` as well. To update Qt Creator, and other components. + +### Building with the newer Qt version +- Open the `SerialPrograms` project in Qt, as outlined in the "Setup" section above. +- In the toolbar, click `Edit` -> `Preferences` +- Under `Kits` tab, choose the newer Qt version (e.g. Desktop Qt 6.8.3) + + +- Under `Compiler`, set it to Microsoft Visual C++ Compiler or Visual Studio, if not already set. +- Click `Ok`, to save Kits preferences. +- Click the Monitor symbol at the bottom left + + +- Under `Kit`: choose the desired Qt version. +- Under `Build`: choose `Release with Debug Information` +- Click the green arrow to compile and launch the program. +- Optional: Move the `UserSettings` folder from the old build folder to the new build folder, to keep your old settings, such as the dev key. + +### Upgrade compiler +- Upgrade the compiler by installing a new version of Visual Studio. Ensure `Desktop development with C++` is checked, so the latest MSVC compiler is also installed. +- Open the `SerialPrograms` project in Qt, as outlined in the "Setup" section above. +- In the toolbar, click `Edit` -> `Preferences` +- Click the `Kits` tab on the left. Then click the `Compilers` tab, click `Re-detect` to refresh the list of compilers. Then click `Apply` in the bottom right. +- Back in the `Kits` tab, your newly installed compilers should now show up in the list of compilers. + +When building, if you get the error `yvals_core.h:931: error: STL1001: Unexpected compiler version, expected MSVC 19.42 or newer` (or something similar), consider deleting the old build folder, and rebuilding from scratch. + +
+ +**Discord Server:** + + +[](https://discord.gg/cQ4gWxN) + diff --git a/SerialPrograms/CMakeLists.txt b/SerialPrograms/CMakeLists.txt index eee2e93fdd..d5d5abd040 100644 --- a/SerialPrograms/CMakeLists.txt +++ b/SerialPrograms/CMakeLists.txt @@ -63,16 +63,22 @@ file(GLOB MAIN_SOURCES ../Common/CRC32.h ../Common/Compiler.h ../Common/Cpp/AbstractLogger.h + ../Common/Cpp/BitmapConversion.cpp + ../Common/Cpp/BitmapConversion.h ../Common/Cpp/CancellableScope.cpp ../Common/Cpp/CancellableScope.h ../Common/Cpp/Color.cpp ../Common/Cpp/Color.h ../Common/Cpp/Concurrency/AsyncDispatcher.cpp ../Common/Cpp/Concurrency/AsyncDispatcher.h + ../Common/Cpp/Concurrency/AsyncTask.cpp + ../Common/Cpp/Concurrency/AsyncTask.h + ../Common/Cpp/Concurrency/ComputationThreadPool.cpp + ../Common/Cpp/Concurrency/ComputationThreadPool.h + ../Common/Cpp/Concurrency/ComputationThreadPoolCore.cpp + ../Common/Cpp/Concurrency/ComputationThreadPoolCore.h ../Common/Cpp/Concurrency/FireForgetDispatcher.cpp ../Common/Cpp/Concurrency/FireForgetDispatcher.h - ../Common/Cpp/Concurrency/ParallelTaskRunner.cpp - ../Common/Cpp/Concurrency/ParallelTaskRunner.h ../Common/Cpp/Concurrency/PeriodicScheduler.cpp ../Common/Cpp/Concurrency/PeriodicScheduler.h ../Common/Cpp/Concurrency/ReverseLockGuard.h @@ -102,6 +108,12 @@ file(GLOB MAIN_SOURCES ../Common/Cpp/CpuId/CpuId_arm64.tpp ../Common/Cpp/CpuId/CpuId_x86.h ../Common/Cpp/CpuId/CpuId_x86.tpp + ../Common/Cpp/CpuUtilization/CpuUtilization.cpp + ../Common/Cpp/CpuUtilization/CpuUtilization.h + ../Common/Cpp/CpuUtilization/CpuUtilization_Linux.h + ../Common/Cpp/CpuUtilization/CpuUtilization_Linux.tpp + ../Common/Cpp/CpuUtilization/CpuUtilization_Windows.h + ../Common/Cpp/CpuUtilization/CpuUtilization_Windows.tpp ../Common/Cpp/DateTime.h ../Common/Cpp/EnumStringMap.h ../Common/Cpp/EventRateTracker.h @@ -182,7 +194,9 @@ file(GLOB MAIN_SOURCES ../Common/Cpp/Sockets/ClientSocket.cpp ../Common/Cpp/Sockets/ClientSocket.h ../Common/Cpp/Sockets/ClientSocket_POSIX.h + ../Common/Cpp/Sockets/ClientSocket_Qt.h ../Common/Cpp/Sockets/ClientSocket_WinSocket.h + ../Common/Cpp/Stopwatch.h ../Common/Cpp/StreamConverters.cpp ../Common/Cpp/StreamConverters.h ../Common/Cpp/StringTools.cpp @@ -402,6 +416,8 @@ file(GLOB MAIN_SOURCES Source/CommonFramework/Options/ResolutionOption.cpp Source/CommonFramework/Options/ResolutionOption.h Source/CommonFramework/Options/ScreenshotFormatOption.h + Source/CommonFramework/Options/ThreadPoolOption.cpp + Source/CommonFramework/Options/ThreadPoolOption.h Source/CommonFramework/Panels/PanelDescriptor.cpp Source/CommonFramework/Panels/PanelDescriptor.h Source/CommonFramework/Panels/PanelInstance.cpp @@ -449,6 +465,8 @@ file(GLOB MAIN_SOURCES Source/CommonFramework/Tools/ErrorDumper.h Source/CommonFramework/Tools/FileDownloader.cpp Source/CommonFramework/Tools/FileDownloader.h + Source/CommonFramework/Tools/GlobalThreadPools.cpp + Source/CommonFramework/Tools/GlobalThreadPools.h Source/CommonFramework/Tools/ProgramEnvironment.cpp Source/CommonFramework/Tools/ProgramEnvironment.h Source/CommonFramework/Tools/StatAccumulator.cpp @@ -463,6 +481,9 @@ file(GLOB MAIN_SOURCES Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.h Source/CommonFramework/VideoPipeline/Backends/MediaServicesQt6.cpp Source/CommonFramework/VideoPipeline/Backends/MediaServicesQt6.h + Source/CommonFramework/VideoPipeline/Backends/QVideoFrameCache.h + Source/CommonFramework/VideoPipeline/Backends/SnapshotManager.cpp + Source/CommonFramework/VideoPipeline/Backends/SnapshotManager.h Source/CommonFramework/VideoPipeline/Backends/VideoFrameQt.h Source/CommonFramework/VideoPipeline/CameraInfo.h Source/CommonFramework/VideoPipeline/Stats/CpuUtilizationStats.h @@ -523,8 +544,6 @@ file(GLOB MAIN_SOURCES Source/CommonTools/Audio/SpectrogramMatcher.h Source/CommonTools/DetectionDebouncer.h Source/CommonTools/FailureWatchdog.h - Source/CommonTools/GlobalInferenceRunner.cpp - Source/CommonTools/GlobalInferenceRunner.h Source/CommonTools/ImageMatch/CroppedImageDictionaryMatcher.cpp Source/CommonTools/ImageMatch/CroppedImageDictionaryMatcher.h Source/CommonTools/ImageMatch/ExactImageDictionaryMatcher.cpp @@ -695,8 +714,6 @@ file(GLOB MAIN_SOURCES Source/Integrations/IntegrationsAPI.h Source/Integrations/ProgramTracker.cpp Source/Integrations/ProgramTracker.h - Source/Integrations/SleepyDiscordRunner.cpp - Source/Integrations/SleepyDiscordRunner.h Source/Kernels/AbsFFT/Kernels_AbsFFT.cpp Source/Kernels/AbsFFT/Kernels_AbsFFT.h Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch.h @@ -871,12 +888,25 @@ file(GLOB MAIN_SOURCES Source/Kernels/Waterfill/Kernels_Waterfill_Session.h Source/Kernels/Waterfill/Kernels_Waterfill_Session.tpp Source/Kernels/Waterfill/Kernels_Waterfill_Types.h - Source/ML/DataLabeling/SegmentAnythingModel.cpp - Source/ML/DataLabeling/SegmentAnythingModel.h + Source/ML/DataLabeling/ML_AnnotationIO.cpp + Source/ML/DataLabeling/ML_AnnotationIO.h + Source/ML/DataLabeling/ML_SegmentAnythingModel.cpp + Source/ML/DataLabeling/ML_SegmentAnythingModel.h + Source/ML/DataLabeling/ML_SegmentAnythingModelConstants.h Source/ML/ML_Panels.cpp Source/ML/ML_Panels.h Source/ML/Programs/ML_LabelImages.cpp Source/ML/Programs/ML_LabelImages.h + Source/ML/UI/ML_ImageAnnotationCommandRow.cpp + Source/ML/UI/ML_ImageAnnotationCommandRow.h + Source/ML/UI/ML_ImageAnnotationDisplayOption.cpp + Source/ML/UI/ML_ImageAnnotationDisplayOption.h + Source/ML/UI/ML_ImageAnnotationDisplaySession.cpp + Source/ML/UI/ML_ImageAnnotationDisplaySession.h + Source/ML/UI/ML_ImageAnnotationDisplayWidget.cpp + Source/ML/UI/ML_ImageAnnotationDisplayWidget.h + Source/ML/UI/ML_ImageAnnotationSourceSelectorWidget.cpp + Source/ML/UI/ML_ImageAnnotationSourceSelectorWidget.h Source/NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.cpp Source/NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.cpp @@ -953,6 +983,8 @@ file(GLOB MAIN_SOURCES Source/NintendoSwitch/Framework/UI/NintendoSwitch_SingleSwitchProgramWidget.h Source/NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget.cpp Source/NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget.h + Source/NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.cpp + Source/NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.h Source/NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.cpp Source/NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.h Source/NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.cpp @@ -967,8 +999,6 @@ file(GLOB MAIN_SOURCES Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.h Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.cpp Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.h - Source/NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.cpp - Source/NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.h Source/NintendoSwitch/NintendoSwitch_ConsoleHandle.cpp Source/NintendoSwitch/NintendoSwitch_ConsoleHandle.h Source/NintendoSwitch/NintendoSwitch_ConsoleState.cpp @@ -1002,6 +1032,8 @@ file(GLOB MAIN_SOURCES Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.h Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.cpp Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.h + Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch1_HomeToDateTime.cpp + Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch2_HomeToDateTime.cpp Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.cpp Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_NeutralDateSkip.cpp @@ -1010,8 +1042,6 @@ file(GLOB MAIN_SOURCES Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.h Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.cpp Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.h - Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch1_HomeToDateTime.cpp - Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch2_HomeToDateTime.cpp Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_CodeEntryTools.cpp Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_CodeEntryTools.h Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.cpp @@ -1264,6 +1294,8 @@ file(GLOB MAIN_SOURCES Source/PokemonHome/Programs/PokemonHome_GenerateNameOCR.h Source/PokemonHome/Programs/PokemonHome_PageSwap.cpp Source/PokemonHome/Programs/PokemonHome_PageSwap.h + Source/PokemonHome/Resources/PokemonHome_PokeballSprites.cpp + Source/PokemonHome/Resources/PokemonHome_PokeballSprites.h Source/PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.cpp Source/PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h Source/PokemonLA/Inference/Battles/PokemonLA_BattleMoveSelectionDetector.cpp @@ -1529,6 +1561,8 @@ file(GLOB MAIN_SOURCES Source/PokemonSV/Inference/Battles/PokemonSV_PostCatchDetector.h Source/PokemonSV/Inference/Battles/PokemonSV_ShinySoundDetector.cpp Source/PokemonSV/Inference/Battles/PokemonSV_ShinySoundDetector.h + Source/PokemonSV/Inference/Battles/PokemonSV_StartBattleYellowBar.cpp + Source/PokemonSV/Inference/Battles/PokemonSV_StartBattleYellowBar.h Source/PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.cpp Source/PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.h Source/PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.cpp @@ -1583,6 +1617,8 @@ file(GLOB MAIN_SOURCES Source/PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.h Source/PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.cpp Source/PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h + Source/PokemonSV/Inference/Overworld/PokemonSV_OverworldSensors.cpp + Source/PokemonSV/Inference/Overworld/PokemonSV_OverworldSensors.h Source/PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.cpp Source/PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.h Source/PokemonSV/Inference/Picnics/PokemonSV_PicnicDetector.cpp @@ -2446,7 +2482,6 @@ if (MSVC) OpenCV_lib ONNX_lib ONNX_Providers_lib - Sleepy.lib dpp_lib ) target_compile_definitions( @@ -2454,7 +2489,6 @@ if (MSVC) _CRT_SECURE_NO_WARNINGS _DISABLE_CONSTEXPR_MUTEX_CONSTRUCTOR PA_TESSERACT - PA_SLEEPY PA_DPP ) diff --git a/SerialPrograms/Scripts/CodeTemplates/Program/GameName_ProgramName.cpp b/SerialPrograms/Scripts/CodeTemplates/Program/GameName_ProgramName.cpp index 2bdd30e3d7..38a68fd358 100644 --- a/SerialPrograms/Scripts/CodeTemplates/Program/GameName_ProgramName.cpp +++ b/SerialPrograms/Scripts/CodeTemplates/Program/GameName_ProgramName.cpp @@ -1,91 +1,91 @@ -/* Program Name - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "GameName_ProgramName.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace GameName{ - - -ProgramName_Descriptor::ProgramName_Descriptor() - : SingleSwitchProgramDescriptor( - "GameName:ProgramName", - "Game Name", "Program Name", - "ComputerControl/blob/master/Wiki/Programs/GameName/ProgramName.md", - ".", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct ProgramName_Descriptor::Stats : public StatsTracker{ - Stats() - : m_attempts(m_stats["Attempts"]) - , m_errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Attempts"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& m_attempts; - std::atomic& m_errors; -}; -std::unique_ptr ProgramName_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -ProgramName::ProgramName() - : GO_HOME_WHEN_DONE(false) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(NOTIFICATIONS); -} - - -void ProgramName::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - - ProgramName_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_L, 10, 100); - - try{ - - } catch(OperationFailedException&){ - stats.m_errors++; - env.update_stats(); - throw; - } - - env.update_stats(); - GO_HOME_WHEN_DONE.run_end_of_program(context); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - - - -} -} -} +/* Program Name + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "GameName_ProgramName.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace GameName{ + + +ProgramName_Descriptor::ProgramName_Descriptor() + : SingleSwitchProgramDescriptor( + "GameName:ProgramName", + "Game Name", "Program Name", + "ComputerControl/blob/master/Wiki/Programs/GameName/ProgramName.md", + ".", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct ProgramName_Descriptor::Stats : public StatsTracker{ + Stats() + : m_attempts(m_stats["Attempts"]) + , m_errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Attempts"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& m_attempts; + std::atomic& m_errors; +}; +std::unique_ptr ProgramName_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +ProgramName::ProgramName() + : GO_HOME_WHEN_DONE(false) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); +} + + +void ProgramName::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + + ProgramName_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_L, 10, 100); + + try{ + + } catch(OperationFailedException&){ + stats.m_errors++; + env.update_stats(); + throw; + } + + env.update_stats(); + GO_HOME_WHEN_DONE.run_end_of_program(context); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + + + +} +} +} diff --git a/SerialPrograms/Scripts/CodeTemplates/Program/GameName_ProgramName.h b/SerialPrograms/Scripts/CodeTemplates/Program/GameName_ProgramName.h index 251c8de7a3..c3fadc92de 100644 --- a/SerialPrograms/Scripts/CodeTemplates/Program/GameName_ProgramName.h +++ b/SerialPrograms/Scripts/CodeTemplates/Program/GameName_ProgramName.h @@ -1,51 +1,51 @@ -/* Program Name - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_GameName_ProgramName_H -#define PokemonAutomation_GameName_ProgramName_H - -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace GameName{ - - -class ProgramName_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ProgramName_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class ProgramName : public SingleSwitchProgramInstance{ -public: - ProgramName(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - -private: - - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif +/* Program Name + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_GameName_ProgramName_H +#define PokemonAutomation_GameName_ProgramName_H + +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace GameName{ + + +class ProgramName_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ProgramName_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class ProgramName : public SingleSwitchProgramInstance{ +public: + ProgramName(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + +private: + + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Scripts/check_detector_regions.py b/SerialPrograms/Scripts/check_detector_regions.py index 2d535d6b33..34f6eeb071 100755 --- a/SerialPrograms/Scripts/check_detector_regions.py +++ b/SerialPrograms/Scripts/check_detector_regions.py @@ -1,253 +1,253 @@ -#!/usr/local/bin/python3 - -""" -A script used to fine-tune detection box placements and check the color stats from those boxes. -After using image_viewer.py to get an initial box placement, you can place the box values -(x, y, width, height) into this script, repeating the line -add_infer_box_to_image(raw_image, , , , , image) -to add a box onto the image. - -In the end of the script, it will call ImageViewer to render the image, with boxes added. -You can inspect the boxes to fine tune their positions. -""" - -import cv2 -import sys -import numpy as np -from typing import Tuple -from dataclasses import dataclass - -from image_viewer import ImageViewer -from image_region_check import RegionCheck, add_rect, add_infer_box_to_image - - -assert len(sys.argv) == 2 - -filename = sys.argv[1] - -image = cv2.imread(filename) -height = image.shape[0] -width = image.shape[1] -print(f"Size: {width} x {height}") - -raw_image = image.copy() - -# ================================================================== -# LA map weather symbol -# add_infer_box_to_image(raw_image, 0.028, 0.069, 0.025, 0.044, image) - -# ================================================================== -# LA mult-pokemon battle sprite arrow -# for i in range(8): -# loc = (0.936 - 0.035*i, 0.018, 0.015, 0.027) -# add_infer_box_to_image(raw_image, *loc, image) - -# ================================================================== -# LA battle sprite locations -# for i in range(8): -# loc = (0.957 - 0.035*i, 0.044, 0.021, 0.035) -# add_infer_box_to_image(raw_image, *loc, image) - -# ================================================================== -# LA battle + details pokemon info -# add_infer_box_to_image(raw_image, 0.726, 0.133, 0.015, 0.023, image) -# add_infer_box_to_image(raw_image, 0.750, 0.133, 0.015, 0.023, image) -# add_infer_box_to_image(raw_image, 0.777, 0.138, 0.001, 0.015, image) -# add_infer_box_to_image(raw_image, 0.525, 0.130, 0.100, 0.038, image) - -# ================================================================== -# LA wild pokemon focus reading pokemon info -# add_infer_box_to_image(raw_image, 0.108, 0.868, 0.135, 0.037, image) -# add_infer_box_to_image(raw_image, 0.307, 0.873, 0.016, 0.030, image) -# add_infer_box_to_image(raw_image, 0.307, 0.920, 0.016, 0.029, image) -# add_infer_box_to_image(raw_image, 0.324, 0.868, 0.023, 0.04, image) -# add_infer_box_to_image(raw_image, 0.244, 0.815, 0.026, 0.047, image) - - -# ================================================================== -# LA wild pokemon focus -# add_infer_box_to_image(raw_image, 0.109, 0.857, 0.24, 0.012, image) -# add_infer_box_to_image(raw_image, 0.109, 0.949, 0.24, 0.012, image) -# add_infer_box_to_image(raw_image, 0.102, 0.875, 0.007, 0.073, image) -# add_infer_box_to_image(raw_image, 0.348, 0.873, 0.007, 0.073, image) - -# ================================================================== -# LA battle start boundary lines -# add_infer_box_to_image(raw_image, 0.0, 0.113, 1.0, 0.015, image) -# add_infer_box_to_image(raw_image, 0.2, 0.871, 0.63, 0.015, image) - - -# ================================================================== -# LA map mission tab raised detection -# add_infer_box_to_image(raw_image, 0.9235, 0.617, 0.003, 0.019, image) -# add_infer_box_to_image(raw_image, 0.937, 0.62, 0.0035, 0.012, image) - -# ================================================================== -# LA map zoom -# add_infer_box_to_image(raw_image, 0.780, 0.085, 0.008, 0.014, image) -# add_infer_box_to_image(raw_image, 0.795, 0.082, 0.010, 0.019, image) -# add_infer_box_to_image(raw_image, 0.807, 0.081, 0.014, 0.022, image) - -# ================================================================== -# LA MMO Map question mark locations -# add_infer_box_to_image(raw_image, 0.362, 0.670, 0.045, 0.075, image) -# add_infer_box_to_image(raw_image, 0.683, 0.555, 0.039, 0.076, image) -# add_infer_box_to_image(raw_image, 0.828, 0.372, 0.042, 0.082, image) -# add_infer_box_to_image(raw_image, 0.485, 0.440, 0.044, 0.080, image) -# add_infer_box_to_image(raw_image, 0.393, 0.144, 0.050, 0.084, image) - -# ================================================================== -# LA Map location detector -# add_infer_box_to_image(raw_image, 0.252, 0.400, 0.025, 0.150, image) -# add_infer_box_to_image(raw_image, 0.415, 0.550, 0.025, 0.150, image) -# add_infer_box_to_image(raw_image, 0.750, 0.570, 0.025, 0.150, image) -# add_infer_box_to_image(raw_image, 0.865, 0.240, 0.025, 0.150, image) -# add_infer_box_to_image(raw_image, 0.508, 0.320, 0.025, 0.150, image) -# add_infer_box_to_image(raw_image, 0.457, 0.060, 0.025, 0.150, image) -# add_infer_box_to_image(raw_image, 0.635, 0.285, 0.025, 0.150, image) - - -# ================================================================== -# LA dropped items detection -# add_infer_box_to_image(raw_image, 0.030, 0.177, 0.020, 0.038, image) -# add_infer_box_to_image(raw_image, 0.030, 0.225, 0.020, 0.038, image) -# add_infer_box_to_image(raw_image, 0.050, 0.177, 0.200, 0.038, image) -# add_infer_box_to_image(raw_image, 0.050, 0.177, 0.055, 0.038, image) # MMO ?????? - -# ================================================================== -# LA dropped items detection -# add_infer_box_to_image(raw_image, 0.439, 0.819, 0.029, 0.059, image) - -# add_infer_box_to_image(raw_image, 0.031, 0.900, 0.024, 0.017, image) -# add_infer_box_to_image(raw_image, 0.026, 0.743, 0.021, 0.038, image) -# add_infer_box_to_image(raw_image, 0.022, 0.581, 0.020, 0.018, image) -# add_infer_box_to_image(raw_image, 0.152, 0.482, 0.017, 0.040, image) -# add_infer_box_to_image(raw_image, 0.016, 0.218, 0.018, 0.021, image) -# add_infer_box_to_image(raw_image, 0.169, 0.103, 0.024, 0.036, image) -# add_infer_box_to_image(raw_image, 0.815, 0.244, 0.026, 0.026, image) -# add_infer_box_to_image(raw_image, 0.737, 0.126, 0.045, 0.056, image) -# add_infer_box_to_image(raw_image, 0.806, 0.431, 0.043, 0.026, image) -# add_infer_box_to_image(raw_image, 0.827, 0.507, 0.023, 0.028, image) -# add_infer_box_to_image(raw_image, 0.747, 0.603, 0.087, 0.086, image) -# add_infer_box_to_image(raw_image, 0.885, 0.653, 0.041, 0.093, image) -# add_infer_box_to_image(raw_image, 0.934, 0.556, 0.039, 0.038, image) -# add_infer_box_to_image(raw_image, 0.761, 0.913, 0.071, 0.051, image) -# add_infer_box_to_image(raw_image, 0.865, 0.098, 0.022, 0.030, image) -# add_infer_box_to_image(raw_image, 0.202, 0.631, 0.057, 0.075, image) -# add_infer_box_to_image(raw_image, 0.099, 0.265, 0.072, 0.070, image) -# add_infer_box_to_image(raw_image, 0.908, 0.313, 0.020, 0.017, image) - -# ================================================================== -# LA black out detection -# add_infer_box_to_image(raw_image, 0.068, 0.088, 0.864, 0.581, image) -# add_infer_box_to_image(raw_image, 0.720, 0.842, 0.028, 0.051, image) - - -# ================================================================== -# LA Transparent Dialogue Yellow arrow detection -# add_infer_box_to_image(raw_image, 0.720, 0.759, 0.049, 0.128, image) - -# ================================================================== -# LA Dialogue Ellipse detection -# add_infer_box_to_image(raw_image, 0.741, 0.811, 0.028, 0.023, image) - -# ================================================================== -# LA Tenacity path menu -# add_infer_box_to_image(raw_image, 0.56, 0.46, 0.33, 0.27, image) - -# ================================================================== -# LA wild pokemon name in focus -# add_infer_box_to_image(raw_image, 0.11, 0.868, 0.135, 0.043, image) - -# ================================================================== -# LA camp dialogue box -# add_infer_box_to_image(raw_image, 0.741, 0.811, 0.028, 0.023, image) - -# ================================================================== -# LA item compatibility -# add_infer_box_to_image(raw_image, 0.838, 0.1815, 0.090, 0.024, image) - -# ================================================================== -# LA battle move image match -# for i in range(4): - # add_infer_box_to_image(raw_image, 0.66 - i * 0.0205, 0.622 + i * 0.0655, 0.25, 0.032, image) - -# ================================================================== -# LA Ingo battle initial dialogue selection -# add_infer_box_to_image(raw_image, 0.50, 0.350, 0.40, 0.400, image) -# add_infer_box_to_image(raw_image, 0.50, 0.350, 0.40, 0.400, image) - - -# ================================================================== -# LA battle pokemon switch -# add_infer_box_to_image(raw_image, 0.641, 0.178, 0.050, 0.023, image) -# add_infer_box_to_image(raw_image, 0.641, 0.248, 0.050, 0.023, image) -# add_infer_box_to_image(raw_image, 0.517, 0.195, 0.011, 0.061, image) -# add_infer_box_to_image(raw_image, 0.924, 0.185, 0.019, 0.076, image) - -# add_infer_box_to_image(raw_image, 0.540, 0.216, 0.016, 0.018, image) -# add_infer_box_to_image(raw_image, 0.676, 0.216, 0.016, 0.018, image) - -# add_infer_box_to_image(raw_image, 0.044, 0.091, 0.043, 0.077, image) - - -# ================================================================== -# LA battle move selection -# for i in range(4): - # add_infer_box_to_image(raw_image, 0.8 - i * 0.021, 0.622 + i * 0.0655, 0.02, 0.032, image) - -# ================================================================== -# LA battle menu -# add_infer_box_to_image(raw_image, 0.056, 0.948, 0.013, 0.020, image) -# add_infer_box_to_image(raw_image, 0.174, 0.948, 0.032, 0.046, image) - -# ================================================================== -# LA normal opaque dialogue -# add_infer_box_to_image(raw_image, 0.278, 0.712, 0.100, 0.005, image) -# add_infer_box_to_image(raw_image, 0.278, 0.755, 0.100, 0.005, image) -# add_infer_box_to_image(raw_image, 0.259, 0.715, 0.003, 0.043, image) -# add_infer_box_to_image(raw_image, 0.390, 0.715, 0.003, 0.043, image) - -# add_infer_box_to_image(raw_image, 0.500, 0.750, 0.200, 0.020, image) -# add_infer_box_to_image(raw_image, 0.400, 0.895, 0.200, 0.020, image) -# add_infer_box_to_image(raw_image, 0.230, 0.805, 0.016, 0.057, image) -# add_infer_box_to_image(raw_image, 0.755, 0.805, 0.016, 0.057, image) - -# ================================================================== -# LA normal surprise dialogue -# add_infer_box_to_image(raw_image, 0.295, 0.722, 0.100, 0.005, image) -# add_infer_box_to_image(raw_image, 0.295, 0.765, 0.100, 0.005, image) - -# add_infer_box_to_image(raw_image, 0.500, 0.760, 0.200, 0.020, image) -# add_infer_box_to_image(raw_image, 0.400, 0.900, 0.200, 0.020, image) -# add_infer_box_to_image(raw_image, 0.720, 0.855, 0.030, 0.060, image) - -# ================================================================== -# Pokemon Home Box Sorting - -# , m_box_sprite(console, {0.228, 0.095, 0.030, 0.049}) // ball -# ImageFloatBox GENDER_BOX{0.417, 0.097, 0.031, 0.046}; // gender - -# add_infer_box_to_image(raw_image, 0.495, 0.0045, 0.01, 0.005, image) # square color to check which mode is active -# add_infer_box_to_image(raw_image, 0.447, 0.250, 0.037, 0.034, image) # pokemon national dex number pos -# add_infer_box_to_image(raw_image, 0.702, 0.09, 0.04, 0.06, image) # shiny symbol pos -# add_infer_box_to_image(raw_image, 0.463, 0.09, 0.04, 0.06, image) # gmax symbol pos -# add_infer_box_to_image(raw_image, 0.623, 0.095, 0.033, 0.05, image) # origin symbol pos -# add_infer_box_to_image(raw_image, 0.69, 0.18, 0.28, 0.46, image) # pokemon render pos -# add_infer_box_to_image(raw_image, 0.228, 0.095, 0.030, 0.049, image) # ball type pos -# add_infer_box_to_image(raw_image, 0.417, 0.097, 0.031, 0.046, image) # gender pos -# add_infer_box_to_image(raw_image, 0.546, 0.099, 0.044, 0.041, image) # Level box -# add_infer_box_to_image(raw_image, 0.782, 0.719, 0.193, 0.046, image) # OT ID box -# add_infer_box_to_image(raw_image, 0.492, 0.719, 0.165, 0.049, image) # OT box -# add_infer_box_to_image(raw_image, 0.157, 0.783, 0.212, 0.042, image) # Nature box -# add_infer_box_to_image(raw_image, 0.158, 0.838, 0.213, 0.042, image) # Ability box - -# ================================================================== -# Pokemon BDSP Poffin Cooking - -# add_infer_box_to_image(raw_image, 0.56, 0.724, 0.012, 0.024, image) # green & blue arrow pos - - -viewer = ImageViewer(image) -viewer.run() - +#!/usr/local/bin/python3 + +""" +A script used to fine-tune detection box placements and check the color stats from those boxes. +After using image_viewer.py to get an initial box placement, you can place the box values +(x, y, width, height) into this script, repeating the line +add_infer_box_to_image(raw_image, , , , , image) +to add a box onto the image. + +In the end of the script, it will call ImageViewer to render the image, with boxes added. +You can inspect the boxes to fine tune their positions. +""" + +import cv2 +import sys +import numpy as np +from typing import Tuple +from dataclasses import dataclass + +from image_viewer import ImageViewer +from image_region_check import RegionCheck, add_rect, add_infer_box_to_image + + +assert len(sys.argv) == 2 + +filename = sys.argv[1] + +image = cv2.imread(filename) +height = image.shape[0] +width = image.shape[1] +print(f"Size: {width} x {height}") + +raw_image = image.copy() + +# ================================================================== +# LA map weather symbol +# add_infer_box_to_image(raw_image, 0.028, 0.069, 0.025, 0.044, image) + +# ================================================================== +# LA mult-pokemon battle sprite arrow +# for i in range(8): +# loc = (0.936 - 0.035*i, 0.018, 0.015, 0.027) +# add_infer_box_to_image(raw_image, *loc, image) + +# ================================================================== +# LA battle sprite locations +# for i in range(8): +# loc = (0.957 - 0.035*i, 0.044, 0.021, 0.035) +# add_infer_box_to_image(raw_image, *loc, image) + +# ================================================================== +# LA battle + details pokemon info +# add_infer_box_to_image(raw_image, 0.726, 0.133, 0.015, 0.023, image) +# add_infer_box_to_image(raw_image, 0.750, 0.133, 0.015, 0.023, image) +# add_infer_box_to_image(raw_image, 0.777, 0.138, 0.001, 0.015, image) +# add_infer_box_to_image(raw_image, 0.525, 0.130, 0.100, 0.038, image) + +# ================================================================== +# LA wild pokemon focus reading pokemon info +# add_infer_box_to_image(raw_image, 0.108, 0.868, 0.135, 0.037, image) +# add_infer_box_to_image(raw_image, 0.307, 0.873, 0.016, 0.030, image) +# add_infer_box_to_image(raw_image, 0.307, 0.920, 0.016, 0.029, image) +# add_infer_box_to_image(raw_image, 0.324, 0.868, 0.023, 0.04, image) +# add_infer_box_to_image(raw_image, 0.244, 0.815, 0.026, 0.047, image) + + +# ================================================================== +# LA wild pokemon focus +# add_infer_box_to_image(raw_image, 0.109, 0.857, 0.24, 0.012, image) +# add_infer_box_to_image(raw_image, 0.109, 0.949, 0.24, 0.012, image) +# add_infer_box_to_image(raw_image, 0.102, 0.875, 0.007, 0.073, image) +# add_infer_box_to_image(raw_image, 0.348, 0.873, 0.007, 0.073, image) + +# ================================================================== +# LA battle start boundary lines +# add_infer_box_to_image(raw_image, 0.0, 0.113, 1.0, 0.015, image) +# add_infer_box_to_image(raw_image, 0.2, 0.871, 0.63, 0.015, image) + + +# ================================================================== +# LA map mission tab raised detection +# add_infer_box_to_image(raw_image, 0.9235, 0.617, 0.003, 0.019, image) +# add_infer_box_to_image(raw_image, 0.937, 0.62, 0.0035, 0.012, image) + +# ================================================================== +# LA map zoom +# add_infer_box_to_image(raw_image, 0.780, 0.085, 0.008, 0.014, image) +# add_infer_box_to_image(raw_image, 0.795, 0.082, 0.010, 0.019, image) +# add_infer_box_to_image(raw_image, 0.807, 0.081, 0.014, 0.022, image) + +# ================================================================== +# LA MMO Map question mark locations +# add_infer_box_to_image(raw_image, 0.362, 0.670, 0.045, 0.075, image) +# add_infer_box_to_image(raw_image, 0.683, 0.555, 0.039, 0.076, image) +# add_infer_box_to_image(raw_image, 0.828, 0.372, 0.042, 0.082, image) +# add_infer_box_to_image(raw_image, 0.485, 0.440, 0.044, 0.080, image) +# add_infer_box_to_image(raw_image, 0.393, 0.144, 0.050, 0.084, image) + +# ================================================================== +# LA Map location detector +# add_infer_box_to_image(raw_image, 0.252, 0.400, 0.025, 0.150, image) +# add_infer_box_to_image(raw_image, 0.415, 0.550, 0.025, 0.150, image) +# add_infer_box_to_image(raw_image, 0.750, 0.570, 0.025, 0.150, image) +# add_infer_box_to_image(raw_image, 0.865, 0.240, 0.025, 0.150, image) +# add_infer_box_to_image(raw_image, 0.508, 0.320, 0.025, 0.150, image) +# add_infer_box_to_image(raw_image, 0.457, 0.060, 0.025, 0.150, image) +# add_infer_box_to_image(raw_image, 0.635, 0.285, 0.025, 0.150, image) + + +# ================================================================== +# LA dropped items detection +# add_infer_box_to_image(raw_image, 0.030, 0.177, 0.020, 0.038, image) +# add_infer_box_to_image(raw_image, 0.030, 0.225, 0.020, 0.038, image) +# add_infer_box_to_image(raw_image, 0.050, 0.177, 0.200, 0.038, image) +# add_infer_box_to_image(raw_image, 0.050, 0.177, 0.055, 0.038, image) # MMO ?????? + +# ================================================================== +# LA dropped items detection +# add_infer_box_to_image(raw_image, 0.439, 0.819, 0.029, 0.059, image) + +# add_infer_box_to_image(raw_image, 0.031, 0.900, 0.024, 0.017, image) +# add_infer_box_to_image(raw_image, 0.026, 0.743, 0.021, 0.038, image) +# add_infer_box_to_image(raw_image, 0.022, 0.581, 0.020, 0.018, image) +# add_infer_box_to_image(raw_image, 0.152, 0.482, 0.017, 0.040, image) +# add_infer_box_to_image(raw_image, 0.016, 0.218, 0.018, 0.021, image) +# add_infer_box_to_image(raw_image, 0.169, 0.103, 0.024, 0.036, image) +# add_infer_box_to_image(raw_image, 0.815, 0.244, 0.026, 0.026, image) +# add_infer_box_to_image(raw_image, 0.737, 0.126, 0.045, 0.056, image) +# add_infer_box_to_image(raw_image, 0.806, 0.431, 0.043, 0.026, image) +# add_infer_box_to_image(raw_image, 0.827, 0.507, 0.023, 0.028, image) +# add_infer_box_to_image(raw_image, 0.747, 0.603, 0.087, 0.086, image) +# add_infer_box_to_image(raw_image, 0.885, 0.653, 0.041, 0.093, image) +# add_infer_box_to_image(raw_image, 0.934, 0.556, 0.039, 0.038, image) +# add_infer_box_to_image(raw_image, 0.761, 0.913, 0.071, 0.051, image) +# add_infer_box_to_image(raw_image, 0.865, 0.098, 0.022, 0.030, image) +# add_infer_box_to_image(raw_image, 0.202, 0.631, 0.057, 0.075, image) +# add_infer_box_to_image(raw_image, 0.099, 0.265, 0.072, 0.070, image) +# add_infer_box_to_image(raw_image, 0.908, 0.313, 0.020, 0.017, image) + +# ================================================================== +# LA black out detection +# add_infer_box_to_image(raw_image, 0.068, 0.088, 0.864, 0.581, image) +# add_infer_box_to_image(raw_image, 0.720, 0.842, 0.028, 0.051, image) + + +# ================================================================== +# LA Transparent Dialogue Yellow arrow detection +# add_infer_box_to_image(raw_image, 0.720, 0.759, 0.049, 0.128, image) + +# ================================================================== +# LA Dialogue Ellipse detection +# add_infer_box_to_image(raw_image, 0.741, 0.811, 0.028, 0.023, image) + +# ================================================================== +# LA Tenacity path menu +# add_infer_box_to_image(raw_image, 0.56, 0.46, 0.33, 0.27, image) + +# ================================================================== +# LA wild pokemon name in focus +# add_infer_box_to_image(raw_image, 0.11, 0.868, 0.135, 0.043, image) + +# ================================================================== +# LA camp dialogue box +# add_infer_box_to_image(raw_image, 0.741, 0.811, 0.028, 0.023, image) + +# ================================================================== +# LA item compatibility +# add_infer_box_to_image(raw_image, 0.838, 0.1815, 0.090, 0.024, image) + +# ================================================================== +# LA battle move image match +# for i in range(4): + # add_infer_box_to_image(raw_image, 0.66 - i * 0.0205, 0.622 + i * 0.0655, 0.25, 0.032, image) + +# ================================================================== +# LA Ingo battle initial dialogue selection +# add_infer_box_to_image(raw_image, 0.50, 0.350, 0.40, 0.400, image) +# add_infer_box_to_image(raw_image, 0.50, 0.350, 0.40, 0.400, image) + + +# ================================================================== +# LA battle pokemon switch +# add_infer_box_to_image(raw_image, 0.641, 0.178, 0.050, 0.023, image) +# add_infer_box_to_image(raw_image, 0.641, 0.248, 0.050, 0.023, image) +# add_infer_box_to_image(raw_image, 0.517, 0.195, 0.011, 0.061, image) +# add_infer_box_to_image(raw_image, 0.924, 0.185, 0.019, 0.076, image) + +# add_infer_box_to_image(raw_image, 0.540, 0.216, 0.016, 0.018, image) +# add_infer_box_to_image(raw_image, 0.676, 0.216, 0.016, 0.018, image) + +# add_infer_box_to_image(raw_image, 0.044, 0.091, 0.043, 0.077, image) + + +# ================================================================== +# LA battle move selection +# for i in range(4): + # add_infer_box_to_image(raw_image, 0.8 - i * 0.021, 0.622 + i * 0.0655, 0.02, 0.032, image) + +# ================================================================== +# LA battle menu +# add_infer_box_to_image(raw_image, 0.056, 0.948, 0.013, 0.020, image) +# add_infer_box_to_image(raw_image, 0.174, 0.948, 0.032, 0.046, image) + +# ================================================================== +# LA normal opaque dialogue +# add_infer_box_to_image(raw_image, 0.278, 0.712, 0.100, 0.005, image) +# add_infer_box_to_image(raw_image, 0.278, 0.755, 0.100, 0.005, image) +# add_infer_box_to_image(raw_image, 0.259, 0.715, 0.003, 0.043, image) +# add_infer_box_to_image(raw_image, 0.390, 0.715, 0.003, 0.043, image) + +# add_infer_box_to_image(raw_image, 0.500, 0.750, 0.200, 0.020, image) +# add_infer_box_to_image(raw_image, 0.400, 0.895, 0.200, 0.020, image) +# add_infer_box_to_image(raw_image, 0.230, 0.805, 0.016, 0.057, image) +# add_infer_box_to_image(raw_image, 0.755, 0.805, 0.016, 0.057, image) + +# ================================================================== +# LA normal surprise dialogue +# add_infer_box_to_image(raw_image, 0.295, 0.722, 0.100, 0.005, image) +# add_infer_box_to_image(raw_image, 0.295, 0.765, 0.100, 0.005, image) + +# add_infer_box_to_image(raw_image, 0.500, 0.760, 0.200, 0.020, image) +# add_infer_box_to_image(raw_image, 0.400, 0.900, 0.200, 0.020, image) +# add_infer_box_to_image(raw_image, 0.720, 0.855, 0.030, 0.060, image) + +# ================================================================== +# Pokemon Home Box Sorting + +# , m_box_sprite(console, {0.228, 0.095, 0.030, 0.049}) // ball +# ImageFloatBox GENDER_BOX{0.417, 0.097, 0.031, 0.046}; // gender + +# add_infer_box_to_image(raw_image, 0.495, 0.0045, 0.01, 0.005, image) # square color to check which mode is active +# add_infer_box_to_image(raw_image, 0.447, 0.250, 0.037, 0.034, image) # pokemon national dex number pos +# add_infer_box_to_image(raw_image, 0.702, 0.09, 0.04, 0.06, image) # shiny symbol pos +# add_infer_box_to_image(raw_image, 0.463, 0.09, 0.04, 0.06, image) # gmax symbol pos +# add_infer_box_to_image(raw_image, 0.623, 0.095, 0.033, 0.05, image) # origin symbol pos +# add_infer_box_to_image(raw_image, 0.69, 0.18, 0.28, 0.46, image) # pokemon render pos +# add_infer_box_to_image(raw_image, 0.228, 0.095, 0.030, 0.049, image) # ball type pos +# add_infer_box_to_image(raw_image, 0.417, 0.097, 0.031, 0.046, image) # gender pos +# add_infer_box_to_image(raw_image, 0.546, 0.099, 0.044, 0.041, image) # Level box +# add_infer_box_to_image(raw_image, 0.782, 0.719, 0.193, 0.046, image) # OT ID box +# add_infer_box_to_image(raw_image, 0.492, 0.719, 0.165, 0.049, image) # OT box +# add_infer_box_to_image(raw_image, 0.157, 0.783, 0.212, 0.042, image) # Nature box +# add_infer_box_to_image(raw_image, 0.158, 0.838, 0.213, 0.042, image) # Ability box + +# ================================================================== +# Pokemon BDSP Poffin Cooking + +# add_infer_box_to_image(raw_image, 0.56, 0.724, 0.012, 0.024, image) # green & blue arrow pos + + +viewer = ImageViewer(image) +viewer.run() + diff --git a/SerialPrograms/Scripts/image_region_check.py b/SerialPrograms/Scripts/image_region_check.py index 180d16a2fa..9f96b5d300 100644 --- a/SerialPrograms/Scripts/image_region_check.py +++ b/SerialPrograms/Scripts/image_region_check.py @@ -1,175 +1,175 @@ -""" -Functions to check stats on image regions: what's the average color of this region and the std dev of the color of this region. -These stats is useful for image inferences like whether the current screen shows a pokemon battle menu. -The code here matches the implementation in C++, so that we can quickly prototype and debug image inference code in Python. -""" -import cv2 -import sys -import numpy as np -from typing import Tuple, Union, List, NamedTuple -from dataclasses import dataclass - -class Stats(NamedTuple): - # RGB order in this class - - avg: np.ndarray - - avg_sum: float - - stddev: np.ndarray - - stddev_sum: float - - color_ratio: np.ndarray - - # Crop size: width, height - crop_size: Tuple[int, int] - - def to_str(self) -> str: - avg = self.avg - ratio = self.color_ratio - stdev = self.stddev - return ( - f"RGB avg [{int(avg[0]+0.5)}, {int(avg[1]+0.5)}, {int(avg[2]+0.5)}]" - + f" avg sum {int(self.avg_sum+0.5)} ratio [{ratio[0]:.3f}, {ratio[1]:.3f}, {ratio[2]:.3f}]" - + f" stddev [{stdev[0]:.3f}, {stdev[1]:.3f}, {stdev[2]:.3f}] sum {self.stddev_sum:.3f}" - + f" crop size {self.crop_size}" - ) - - - -def _get_region(image: np.ndarray, x: float, y: float, w: float, h: float) -> Tuple[int, int, int, int]: - """ - Given an image and (x, y, w, h) denoting a resolution-independent region, return - the actual region in pixel counts. - """ - height = image.shape[0] - width = image.shape[1] - start_x = int(x * width + 0.5) - start_y = int(y * height + 0.5) - rect_width = int(w * width + 0.5) - rect_height = int(h * height + 0.5) - end_x = start_x + rect_width - end_y = start_y + rect_height - return start_x, start_y, end_x, end_y - - -def add_rect(image: np.ndarray, x: float, y: float, w: float, h: float, color=(0, 0, 255)) -> np.ndarray: - """ - Add a red rectangle around a region, where (x, y, w, h) denoting a resolution-independent region. - """ - start_x, start_y, end_x, end_y = _get_region(image, x, y, w, h) - # print(start_x, start_y, end_x, end_y) - image = cv2.rectangle(image, (start_x, start_y), (end_x, end_y), color, 2) - return image - -def _get_stats(image: np.ndarray, x: float, y: float, w: float, h: float) -> Stats: - """ - Given (x, y, w, h) denoting a resolution-independent region, return the color stats of the region. - - Return the average color of the region and the std dev of the region. - """ - start_x, start_y, end_x, end_y = _get_region(image, x, y, w, h) - crop = image[start_y:end_y, start_x:end_x].astype(float) - num_pixels = crop.shape[0] * crop.shape[1] - crop_sum = np.sum(crop, (0, 1)) - crop_avg = crop_sum / num_pixels - avg_sum = np.sum(crop_avg) - crop_color_ratio = [1/3., 1/3., 1/3.] if avg_sum <= 1e-6 else crop_avg / avg_sum - crop_color_ratio = np.array([crop_color_ratio[2], crop_color_ratio[1], crop_color_ratio[0]]) - - crop_sqr_sum = np.sum(np.square(crop), (0, 1)) - crop_stddev = np.sqrt((crop_sqr_sum - (np.square(crop_sum) / num_pixels)) / (num_pixels-1)) - crop_stddev_sum = np.sum(crop_stddev) - return Stats( - avg = np.flip(crop_avg), # from BGR to RGB - avg_sum = avg_sum, - stddev = np.flip(crop_stddev), # from BGR to RGB - stddev_sum = crop_stddev_sum, - color_ratio = crop_color_ratio, - crop_size=(end_x - start_x, end_y - start_y), - ) - -def add_infer_box_to_image( - image: np.ndarray, - x: float, y: float, w: float, h: float, - rendered_image: np.ndarray, - color=(0,0,255) -) -> np.ndarray: - stats = _get_stats(image, x, y, w, h) - ratio = stats.color_ratio - print(f"Add infer box: ({x:0.4f}, {y:0.4f}, {w:0.4f}, {h:0.4f}), {stats.to_str()}") - return add_rect(rendered_image, x, y, w, h, color) - -def _color_matched( - crop_color_ratio: np.ndarray, - crop_stddev_sum: float, - expected_color_ratio: Union[np.ndarray, Tuple[float, float, float]], - max_euclidean_distance: float, - max_stddev_sum: float -) -> bool: - """Check whether an inference box check is matched""" - dist = crop_color_ratio - np.array(expected_color_ratio) - dist = np.square(dist) - euclidean_distance = np.sqrt(np.sum(dist)) - - # print(f"stddev_sum: {stddev_sum} vs max {max_stddev_sum}, rgb actual: {actual}, eu_dist: {euclidean_distance} vs max {max_euclidean_distance}") - if crop_stddev_sum > max_stddev_sum: - return False - return euclidean_distance <= max_euclidean_distance - - -@dataclass -class RegionCheck: - # Name of the region - name: str - # (x, y, w, h) denoting a resolution-independent region - region: Tuple[float, float, float, float] - # extpected the color ratio, all three values sum to one - expected_color_ratio: Tuple[float, float, float] - # threshold for euclidendistance between the color aspect ratio (size-3 vecctor) of - # the current image and the expected ratio. - max_euclidean_distance: float - # threshold for sum of stddev from the three color channels. - max_stddev_sum: float - - def check(self, image: np.ndarray) -> bool: - """Check whether this image passes inference check.""" - stats = _get_stats(image, *self.region) - crop_ratio = stats.color_ratio - crop_stddev_sum = stats.stddev_sum - print(f"Checking {self.name}") - print(stats.to_str()) - solid = _color_matched(crop_ratio, crop_stddev_sum, self.expected_color_ratio, self.max_euclidean_distance, self.max_stddev_sum) - print(f"_color_matched? {solid}") - return solid - - -def check_image(filename: str, regions: List[RegionCheck]) -> None: - """Print whether an image saved in filename passes all region checks.""" - image = cv2.imread(filename, cv2.IMREAD_UNCHANGED) - height = image.shape[0] - width = image.shape[1] - print(f"Load image {filename}, size: {width} x {height}") - - for region in regions: - if region.check(image) == False: - print("====== Failed ======") - return - print("====== Passed ======") - - -def set_black_out_of_rect(image: np.ndarray, x: float, y: float, w: float, h: float): - """Set regions outside of the rect on `image` to be black.""" - height = image.shape[0] - width = image.shape[1] - start_x = int(x * width + 0.5) - start_y = int(y * height + 0.5) - rect_width = int(w * width + 0.5) - rect_height = int(h * height + 0.5) - end_x = start_x + rect_width - end_y = start_y + rect_height - - new_image = np.zeros(image.shape, dtype=image.dtype) - new_image[start_y:end_y, start_x:end_x] = image[start_y:end_y, start_x:end_x] +""" +Functions to check stats on image regions: what's the average color of this region and the std dev of the color of this region. +These stats is useful for image inferences like whether the current screen shows a pokemon battle menu. +The code here matches the implementation in C++, so that we can quickly prototype and debug image inference code in Python. +""" +import cv2 +import sys +import numpy as np +from typing import Tuple, Union, List, NamedTuple +from dataclasses import dataclass + +class Stats(NamedTuple): + # RGB order in this class + + avg: np.ndarray + + avg_sum: float + + stddev: np.ndarray + + stddev_sum: float + + color_ratio: np.ndarray + + # Crop size: width, height + crop_size: Tuple[int, int] + + def to_str(self) -> str: + avg = self.avg + ratio = self.color_ratio + stdev = self.stddev + return ( + f"RGB avg [{int(avg[0]+0.5)}, {int(avg[1]+0.5)}, {int(avg[2]+0.5)}]" + + f" avg sum {int(self.avg_sum+0.5)} ratio [{ratio[0]:.3f}, {ratio[1]:.3f}, {ratio[2]:.3f}]" + + f" stddev [{stdev[0]:.3f}, {stdev[1]:.3f}, {stdev[2]:.3f}] sum {self.stddev_sum:.3f}" + + f" crop size {self.crop_size}" + ) + + + +def _get_region(image: np.ndarray, x: float, y: float, w: float, h: float) -> Tuple[int, int, int, int]: + """ + Given an image and (x, y, w, h) denoting a resolution-independent region, return + the actual region in pixel counts. + """ + height = image.shape[0] + width = image.shape[1] + start_x = int(x * width + 0.5) + start_y = int(y * height + 0.5) + rect_width = int(w * width + 0.5) + rect_height = int(h * height + 0.5) + end_x = start_x + rect_width + end_y = start_y + rect_height + return start_x, start_y, end_x, end_y + + +def add_rect(image: np.ndarray, x: float, y: float, w: float, h: float, color=(0, 0, 255)) -> np.ndarray: + """ + Add a red rectangle around a region, where (x, y, w, h) denoting a resolution-independent region. + """ + start_x, start_y, end_x, end_y = _get_region(image, x, y, w, h) + # print(start_x, start_y, end_x, end_y) + image = cv2.rectangle(image, (start_x, start_y), (end_x, end_y), color, 2) + return image + +def _get_stats(image: np.ndarray, x: float, y: float, w: float, h: float) -> Stats: + """ + Given (x, y, w, h) denoting a resolution-independent region, return the color stats of the region. + + Return the average color of the region and the std dev of the region. + """ + start_x, start_y, end_x, end_y = _get_region(image, x, y, w, h) + crop = image[start_y:end_y, start_x:end_x].astype(float) + num_pixels = crop.shape[0] * crop.shape[1] + crop_sum = np.sum(crop, (0, 1)) + crop_avg = crop_sum / num_pixels + avg_sum = np.sum(crop_avg) + crop_color_ratio = [1/3., 1/3., 1/3.] if avg_sum <= 1e-6 else crop_avg / avg_sum + crop_color_ratio = np.array([crop_color_ratio[2], crop_color_ratio[1], crop_color_ratio[0]]) + + crop_sqr_sum = np.sum(np.square(crop), (0, 1)) + crop_stddev = np.sqrt((crop_sqr_sum - (np.square(crop_sum) / num_pixels)) / (num_pixels-1)) + crop_stddev_sum = np.sum(crop_stddev) + return Stats( + avg = np.flip(crop_avg), # from BGR to RGB + avg_sum = avg_sum, + stddev = np.flip(crop_stddev), # from BGR to RGB + stddev_sum = crop_stddev_sum, + color_ratio = crop_color_ratio, + crop_size=(end_x - start_x, end_y - start_y), + ) + +def add_infer_box_to_image( + image: np.ndarray, + x: float, y: float, w: float, h: float, + rendered_image: np.ndarray, + color=(0,0,255) +) -> np.ndarray: + stats = _get_stats(image, x, y, w, h) + ratio = stats.color_ratio + print(f"Add infer box: ({x:0.4f}, {y:0.4f}, {w:0.4f}, {h:0.4f}), {stats.to_str()}") + return add_rect(rendered_image, x, y, w, h, color) + +def _color_matched( + crop_color_ratio: np.ndarray, + crop_stddev_sum: float, + expected_color_ratio: Union[np.ndarray, Tuple[float, float, float]], + max_euclidean_distance: float, + max_stddev_sum: float +) -> bool: + """Check whether an inference box check is matched""" + dist = crop_color_ratio - np.array(expected_color_ratio) + dist = np.square(dist) + euclidean_distance = np.sqrt(np.sum(dist)) + + # print(f"stddev_sum: {stddev_sum} vs max {max_stddev_sum}, rgb actual: {actual}, eu_dist: {euclidean_distance} vs max {max_euclidean_distance}") + if crop_stddev_sum > max_stddev_sum: + return False + return euclidean_distance <= max_euclidean_distance + + +@dataclass +class RegionCheck: + # Name of the region + name: str + # (x, y, w, h) denoting a resolution-independent region + region: Tuple[float, float, float, float] + # extpected the color ratio, all three values sum to one + expected_color_ratio: Tuple[float, float, float] + # threshold for euclidendistance between the color aspect ratio (size-3 vecctor) of + # the current image and the expected ratio. + max_euclidean_distance: float + # threshold for sum of stddev from the three color channels. + max_stddev_sum: float + + def check(self, image: np.ndarray) -> bool: + """Check whether this image passes inference check.""" + stats = _get_stats(image, *self.region) + crop_ratio = stats.color_ratio + crop_stddev_sum = stats.stddev_sum + print(f"Checking {self.name}") + print(stats.to_str()) + solid = _color_matched(crop_ratio, crop_stddev_sum, self.expected_color_ratio, self.max_euclidean_distance, self.max_stddev_sum) + print(f"_color_matched? {solid}") + return solid + + +def check_image(filename: str, regions: List[RegionCheck]) -> None: + """Print whether an image saved in filename passes all region checks.""" + image = cv2.imread(filename, cv2.IMREAD_UNCHANGED) + height = image.shape[0] + width = image.shape[1] + print(f"Load image {filename}, size: {width} x {height}") + + for region in regions: + if region.check(image) == False: + print("====== Failed ======") + return + print("====== Passed ======") + + +def set_black_out_of_rect(image: np.ndarray, x: float, y: float, w: float, h: float): + """Set regions outside of the rect on `image` to be black.""" + height = image.shape[0] + width = image.shape[1] + start_x = int(x * width + 0.5) + start_y = int(y * height + 0.5) + rect_width = int(w * width + 0.5) + rect_height = int(h * height + 0.5) + end_x = start_x + rect_width + end_y = start_y + rect_height + + new_image = np.zeros(image.shape, dtype=image.dtype) + new_image[start_y:end_y, start_x:end_x] = image[start_y:end_y, start_x:end_x] image[...] = new_image[...] \ No newline at end of file diff --git a/SerialPrograms/Scripts/image_viewer.py b/SerialPrograms/Scripts/image_viewer.py index ea2a2b2ba6..29c00bec6d 100755 --- a/SerialPrograms/Scripts/image_viewer.py +++ b/SerialPrograms/Scripts/image_viewer.py @@ -1,253 +1,253 @@ -#!python3 - -""" -A simple image viewer (using OpenCV) with basic ability to check pixel location and color. -It can also draw boxes on the image and print their locations. Useful for writing -PokemonAutomation visual inference methods. - -Single left clicking on a pixel shows you the info of that pixel. Note it may also print the -alpha channel value. - -- Press 'w', 's', 'a', 'd' to move the selected pixels around. - -To draw a box: left click and drag the rectangle. -You can draw multiple boxes on the screen. - -- Press 'i' to dump the information of those boxes so you can copy them into the code, - or into check_detector_regions.py to fine tune the boxes. - -- Press 'backspace/delete' to delete the current selected box. If no box is selected, - delete the last added box. Select an existing box by right clicking. - -- Press 'ESC' to exit the program. -""" - - -import cv2 -import numpy as np - -class ImageViewer: - def __init__(self, image, highlight_list = []): - self.image = image - self.hsv_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) - self.selected_pixel = (-1, -1) - self.buffer = image.copy() - self.window_name = 'image' - self.height = image.shape[0] - self.width = image.shape[1] - self.highlight_list = highlight_list - self.cur_highlight_index = -1 - self.rects = [] # List of Tuple[int,int,int,int]: each tuple: start_x, start_y, end_x, end_y - self.cur_rect_index = -1 - self.mouse_down = False - self.mouse_move_counter = 0 - self.nc = image.shape[2] # num_channel - # The size of the cross used to highlight a selected pixel - self.cross_size = max(1, min(self.width, self.height) // 200) - - def _solid_color(self, color): - return color if self.image.shape[2] == 3 else color + [255] - - def _set_color_to_buffer(self, coord, color): - x, y = coord - if x >= 0 and x < self.width and y >= 0 and y < self.height: - self.buffer[y, x] = self._solid_color(color) - - def _render(self): - self.buffer = self.image.copy() - if self.selected_pixel[0] >= 0 and self.selected_pixel[1] >= 0: - p = self.selected_pixel - # Draw a red cross - self._set_color_to_buffer(p, color=[0, 0, 255]) - for i in range(1, self.cross_size): - self._set_color_to_buffer((p[0]-i, p[1]), color=[0, 0, 255]) - self._set_color_to_buffer((p[0]+i, p[1]), color=[0, 0, 255]) - self._set_color_to_buffer((p[0], p[1]-i), color=[0, 0, 255]) - self._set_color_to_buffer((p[0], p[1]+i), color=[0, 0, 255]) - - if self.cur_highlight_index >= 0 and len(self.highlight_list) > 0: - for pixel in self.highlight_list[self.cur_highlight_index]: - self.buffer[pixel[1], pixel[0]] = self._solid_color([255, 0, 0]) - - for i, rect in enumerate(self.rects): - # print(f"In render(): {rect}") - # rect: [start_x start_y end_x end_y] - width = 2 - color = (0, 0, 255) if i == self.cur_rect_index else (255, 0, 0) - self.buffer = cv2.rectangle(self.buffer, (rect[0], rect[1]), (rect[2], rect[3]), color, width) - - cv2.imshow(self.window_name, self.buffer) - # self.fullscreen = False - - def _change_selected_rect(self, x, y): - if len(self.rects) == 0: - return - - min_dist = 0 - for i, rect in enumerate(self.rects): - min_x = min(rect[0], rect[2]) - max_x = max(rect[0], rect[2]) - min_y = min(rect[1], rect[3]) - max_y = max(rect[1], rect[3]) - dist_x = min_x - x if x <= min_x else (x - max_x if x >= max_x else 0) - dist_y = min_y - y if y <= min_y else (y - max_y if y >= max_y else 0) - dist = dist_x ** 2 + dist_y ** 2 - if i == 0 or dist < min_dist: - min_dist = dist - self.cur_rect_index = i - print(f"Selected rect No.{self.cur_rect_index}/{len(self.rects)}: {rect}.") - - def _print_pixel(self, coord): - p = self.image[coord[1], coord[0]] - print(f"Pixel (x,y) = ({coord[0]}, {coord[1]}), ({coord[0]/self.width:0.3}, {coord[1]/self.height:0.3}), " - + f"rgb=[{str(p[3]) + ',' if self.nc == 4 else ''}{p[2]},{p[1]},{p[0]}] hsv={self.hsv_image[coord[1], coord[0]]}") - - def _print_rect(self, i, rect): - crop = self.image[rect[1]:rect[3], rect[0]:rect[2]].astype(float) / 255.0 - num_pixels = crop.shape[0] * crop.shape[1] - # crop_sum shape: (4), 4 is channel count - crop_sum = np.sum(crop, (0, 1)) - # crop_avg shape: (4), 4 is channel count - crop_avg = crop_sum / num_pixels - # crop_sqr_sum shape: (4), 4 is channel count - crop_sqr_sum = np.sum(np.square(crop), (0, 1)) - - crop_stddev = np.sqrt( np.clip(crop_sqr_sum - (np.square(crop_sum) / num_pixels), 0, None) / (num_pixels-1)) - - avg_sum = np.sum(crop_avg) - avg_ratio = [1/3., 1/3., 1/3.] if avg_sum == 0. else crop_avg / avg_sum - avg_ratio = np.array([avg_ratio[2], avg_ratio[1], avg_ratio[0]]) - x = rect[0] / self.width - y = rect[1] / self.height - w = (rect[2] - rect[0]) / self.width - h = (rect[3] - rect[1]) / self.height - - stddev_sum = np.sum(crop_stddev) - print(f"Rect No.{i}, ({x:.3f}, {y:.3f}, {w:.3f}, {h:.3f}) rgb ratio: {avg_ratio[0]:.3f}:{avg_ratio[1]:.3f}:{avg_ratio[2]:.3f}, stddev sum: {stddev_sum:.3g}") - - def _move_crop(self, o0, o1, o2, o3): - if self.cur_crop_index >= 0 and self.cur_crop_index < len(self.crops): - self.crops[self.cur_crop_index][0] += o0 - self.crops[self.cur_crop_index][1] += o1 - self.crops[self.cur_crop_index][2] += o2 - self.crops[self.cur_crop_index][3] += o3 - self._render() - - def _mouse_callback(self, event, x, y, flags, param): - redraw = False - - # Dragging selected_pixel rectangle - if event == cv2.EVENT_LBUTTONDOWN: - self.mouse_down = True - self.cur_rect_index = len(self.rects) - self.rects.append([x, y, x, y]) - self.mouse_move_counter = 0 - elif event == cv2.EVENT_LBUTTONUP: - self.mouse_down = False - assert len(self.rects) > 0 - if self.rects[-1][0] == self.rects[-1][2] and self.rects[-1][1] == self.rects[-1][3]: - self.cur_rect_index -= 1 - self.rects.pop() - self._change_selected_rect(x, y) - self._print_pixel((x, y)) - if self.selected_pixel != (x, y): - self.selected_pixel = (x, y) - redraw = True - else: - # sanitize the rect: - if self.cur_rect_index >= 0 and self.cur_rect_index < len(self.rects): - rect = self.rects[self.cur_rect_index] - min_x = min(rect[0], rect[2]) - max_x = max(rect[0], rect[2]) - min_y = min(rect[1], rect[3]) - max_y = max(rect[1], rect[3]) - rect[0] = min_x - rect[1] = min_y - rect[2] = max_x - rect[3] = max_y - redraw = True - mouse_move_counter = 0 - elif event == cv2.EVENT_RBUTTONUP: # right click to select existing rect to edit - if len(self.rects) > 0: - self._change_selected_rect(x, y) - redraw = True - elif event == cv2.EVENT_MOUSEMOVE and self.mouse_down: - if self.cur_rect_index >= 0 and self.cur_rect_index < len(self.rects): - old_loc = (self.rects[self.cur_rect_index][2], self.rects[self.cur_rect_index][3]) - if old_loc != (x, y): - self.rects[self.cur_rect_index][2] = x - self.rects[self.cur_rect_index][3] = y - # if mouse_move_counter % 2 == 0: - redraw = True - self.mouse_move_counter += 1 - - if redraw: - self._render() - - def run(self): - - cv2.imshow(self.window_name, self.buffer) - cv2.setWindowProperty(self.window_name, cv2.WND_PROP_TOPMOST, 1) - cv2.setMouseCallback(self.window_name, self._mouse_callback) - - while True: - key = cv2.waitKey(0) - - if key == 27: # esc - cv2.destroyAllWindows() - break - elif key == 119: # w - if self.selected_pixel[0] >= 0 and self.selected_pixel[1] >= 1: - self.selected_pixel = (self.selected_pixel[0], self.selected_pixel[1]-1) - self._print_pixel(self.selected_pixel) - elif key == 115: # s - if self.selected_pixel[0] >= 0 and self.selected_pixel[1] >= 0 and self.selected_pixel[1] + 1 < self.height: - self.selected_pixel = (self.selected_pixel[0], self.selected_pixel[1]+1) - self._print_pixel(self.selected_pixel) - elif key == 97: # a - if self.selected_pixel[0] >= 1 and self.selected_pixel[1] >= 0: - self.selected_pixel = (self.selected_pixel[0]-1, self.selected_pixel[1]) - self._print_pixel(self.selected_pixel) - elif key == 100: # d - if self.selected_pixel[0] >= 0 and self.selected_pixel[1] >= 0 and self.selected_pixel[0] + 1 < self.width: - self.selected_pixel = (self.selected_pixel[0]+1, self.selected_pixel[1]) - self._print_pixel(self.selected_pixel) - elif key == 44: # , - if len(self.highlight_list) > 0: - self.cur_highlight_index = len(self.highlight_list) - 1 if self.cur_highlight_index < 0 else self.cur_highlight_index-1 - print(f"Change highlight index to {self.cur_highlight_index}/{len(self.highlight_list)}") - elif key == 46: # . - if len(self.highlight_list) > 0: - self.cur_highlight_index = -1 if self.cur_highlight_index == len(self.highlight_list)-1 else self.cur_highlight_index+1 - print(f"Change highlight index to {self.cur_highlight_index}/{len(self.highlight_list)}") - elif key == 127 or key == 8: # DEL or backspace (BS), remove selected rectangle - mouse_down = False - mouse_move_counter = 0 - if len(self.rects) > 0: - if self.cur_rect_index < 0: - self.cur_rect_index = len(self.crops) - 1 - del self.rects[self.cur_rect_index] - if len(self.rects) == 0: - self.cur_rect_index = -1 - elif self.cur_rect_index >= len(self.rects): - self.cur_rect_index = len(self.rects) - 1 - elif key == 105: # i - for i, rect in enumerate(self.rects): - self._print_rect(i, rect) - else: - print(f"Pressed key {key}") - self._render() - -if __name__ == '__main__': - import sys - assert len(sys.argv) == 2 - - filename = sys.argv[1] - - image = cv2.imread(filename, cv2.IMREAD_UNCHANGED) - - height = image.shape[0] - width = image.shape[1] - print(f"Load image from {filename}, size: {width} x {height}") - viewer = ImageViewer(image) - viewer.run() +#!python3 + +""" +A simple image viewer (using OpenCV) with basic ability to check pixel location and color. +It can also draw boxes on the image and print their locations. Useful for writing +PokemonAutomation visual inference methods. + +Single left clicking on a pixel shows you the info of that pixel. Note it may also print the +alpha channel value. + +- Press 'w', 's', 'a', 'd' to move the selected pixels around. + +To draw a box: left click and drag the rectangle. +You can draw multiple boxes on the screen. + +- Press 'i' to dump the information of those boxes so you can copy them into the code, + or into check_detector_regions.py to fine tune the boxes. + +- Press 'backspace/delete' to delete the current selected box. If no box is selected, + delete the last added box. Select an existing box by right clicking. + +- Press 'ESC' to exit the program. +""" + + +import cv2 +import numpy as np + +class ImageViewer: + def __init__(self, image, highlight_list = []): + self.image = image + self.hsv_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) + self.selected_pixel = (-1, -1) + self.buffer = image.copy() + self.window_name = 'image' + self.height = image.shape[0] + self.width = image.shape[1] + self.highlight_list = highlight_list + self.cur_highlight_index = -1 + self.rects = [] # List of Tuple[int,int,int,int]: each tuple: start_x, start_y, end_x, end_y + self.cur_rect_index = -1 + self.mouse_down = False + self.mouse_move_counter = 0 + self.nc = image.shape[2] # num_channel + # The size of the cross used to highlight a selected pixel + self.cross_size = max(1, min(self.width, self.height) // 200) + + def _solid_color(self, color): + return color if self.image.shape[2] == 3 else color + [255] + + def _set_color_to_buffer(self, coord, color): + x, y = coord + if x >= 0 and x < self.width and y >= 0 and y < self.height: + self.buffer[y, x] = self._solid_color(color) + + def _render(self): + self.buffer = self.image.copy() + if self.selected_pixel[0] >= 0 and self.selected_pixel[1] >= 0: + p = self.selected_pixel + # Draw a red cross + self._set_color_to_buffer(p, color=[0, 0, 255]) + for i in range(1, self.cross_size): + self._set_color_to_buffer((p[0]-i, p[1]), color=[0, 0, 255]) + self._set_color_to_buffer((p[0]+i, p[1]), color=[0, 0, 255]) + self._set_color_to_buffer((p[0], p[1]-i), color=[0, 0, 255]) + self._set_color_to_buffer((p[0], p[1]+i), color=[0, 0, 255]) + + if self.cur_highlight_index >= 0 and len(self.highlight_list) > 0: + for pixel in self.highlight_list[self.cur_highlight_index]: + self.buffer[pixel[1], pixel[0]] = self._solid_color([255, 0, 0]) + + for i, rect in enumerate(self.rects): + # print(f"In render(): {rect}") + # rect: [start_x start_y end_x end_y] + width = 2 + color = (0, 0, 255) if i == self.cur_rect_index else (255, 0, 0) + self.buffer = cv2.rectangle(self.buffer, (rect[0], rect[1]), (rect[2], rect[3]), color, width) + + cv2.imshow(self.window_name, self.buffer) + # self.fullscreen = False + + def _change_selected_rect(self, x, y): + if len(self.rects) == 0: + return + + min_dist = 0 + for i, rect in enumerate(self.rects): + min_x = min(rect[0], rect[2]) + max_x = max(rect[0], rect[2]) + min_y = min(rect[1], rect[3]) + max_y = max(rect[1], rect[3]) + dist_x = min_x - x if x <= min_x else (x - max_x if x >= max_x else 0) + dist_y = min_y - y if y <= min_y else (y - max_y if y >= max_y else 0) + dist = dist_x ** 2 + dist_y ** 2 + if i == 0 or dist < min_dist: + min_dist = dist + self.cur_rect_index = i + print(f"Selected rect No.{self.cur_rect_index}/{len(self.rects)}: {rect}.") + + def _print_pixel(self, coord): + p = self.image[coord[1], coord[0]] + print(f"Pixel (x,y) = ({coord[0]}, {coord[1]}), ({coord[0]/self.width:0.3}, {coord[1]/self.height:0.3}), " + + f"rgb=[{str(p[3]) + ',' if self.nc == 4 else ''}{p[2]},{p[1]},{p[0]}] hsv={self.hsv_image[coord[1], coord[0]]}") + + def _print_rect(self, i, rect): + crop = self.image[rect[1]:rect[3], rect[0]:rect[2]].astype(float) / 255.0 + num_pixels = crop.shape[0] * crop.shape[1] + # crop_sum shape: (4), 4 is channel count + crop_sum = np.sum(crop, (0, 1)) + # crop_avg shape: (4), 4 is channel count + crop_avg = crop_sum / num_pixels + # crop_sqr_sum shape: (4), 4 is channel count + crop_sqr_sum = np.sum(np.square(crop), (0, 1)) + + crop_stddev = np.sqrt( np.clip(crop_sqr_sum - (np.square(crop_sum) / num_pixels), 0, None) / (num_pixels-1)) + + avg_sum = np.sum(crop_avg) + avg_ratio = [1/3., 1/3., 1/3.] if avg_sum == 0. else crop_avg / avg_sum + avg_ratio = np.array([avg_ratio[2], avg_ratio[1], avg_ratio[0]]) + x = rect[0] / self.width + y = rect[1] / self.height + w = (rect[2] - rect[0]) / self.width + h = (rect[3] - rect[1]) / self.height + + stddev_sum = np.sum(crop_stddev) + print(f"Rect No.{i}, ({x:.3f}, {y:.3f}, {w:.3f}, {h:.3f}) rgb ratio: {avg_ratio[0]:.3f}:{avg_ratio[1]:.3f}:{avg_ratio[2]:.3f}, stddev sum: {stddev_sum:.3g}") + + def _move_crop(self, o0, o1, o2, o3): + if self.cur_crop_index >= 0 and self.cur_crop_index < len(self.crops): + self.crops[self.cur_crop_index][0] += o0 + self.crops[self.cur_crop_index][1] += o1 + self.crops[self.cur_crop_index][2] += o2 + self.crops[self.cur_crop_index][3] += o3 + self._render() + + def _mouse_callback(self, event, x, y, flags, param): + redraw = False + + # Dragging selected_pixel rectangle + if event == cv2.EVENT_LBUTTONDOWN: + self.mouse_down = True + self.cur_rect_index = len(self.rects) + self.rects.append([x, y, x, y]) + self.mouse_move_counter = 0 + elif event == cv2.EVENT_LBUTTONUP: + self.mouse_down = False + assert len(self.rects) > 0 + if self.rects[-1][0] == self.rects[-1][2] and self.rects[-1][1] == self.rects[-1][3]: + self.cur_rect_index -= 1 + self.rects.pop() + self._change_selected_rect(x, y) + self._print_pixel((x, y)) + if self.selected_pixel != (x, y): + self.selected_pixel = (x, y) + redraw = True + else: + # sanitize the rect: + if self.cur_rect_index >= 0 and self.cur_rect_index < len(self.rects): + rect = self.rects[self.cur_rect_index] + min_x = min(rect[0], rect[2]) + max_x = max(rect[0], rect[2]) + min_y = min(rect[1], rect[3]) + max_y = max(rect[1], rect[3]) + rect[0] = min_x + rect[1] = min_y + rect[2] = max_x + rect[3] = max_y + redraw = True + mouse_move_counter = 0 + elif event == cv2.EVENT_RBUTTONUP: # right click to select existing rect to edit + if len(self.rects) > 0: + self._change_selected_rect(x, y) + redraw = True + elif event == cv2.EVENT_MOUSEMOVE and self.mouse_down: + if self.cur_rect_index >= 0 and self.cur_rect_index < len(self.rects): + old_loc = (self.rects[self.cur_rect_index][2], self.rects[self.cur_rect_index][3]) + if old_loc != (x, y): + self.rects[self.cur_rect_index][2] = x + self.rects[self.cur_rect_index][3] = y + # if mouse_move_counter % 2 == 0: + redraw = True + self.mouse_move_counter += 1 + + if redraw: + self._render() + + def run(self): + + cv2.imshow(self.window_name, self.buffer) + cv2.setWindowProperty(self.window_name, cv2.WND_PROP_TOPMOST, 1) + cv2.setMouseCallback(self.window_name, self._mouse_callback) + + while True: + key = cv2.waitKey(0) + + if key == 27: # esc + cv2.destroyAllWindows() + break + elif key == 119: # w + if self.selected_pixel[0] >= 0 and self.selected_pixel[1] >= 1: + self.selected_pixel = (self.selected_pixel[0], self.selected_pixel[1]-1) + self._print_pixel(self.selected_pixel) + elif key == 115: # s + if self.selected_pixel[0] >= 0 and self.selected_pixel[1] >= 0 and self.selected_pixel[1] + 1 < self.height: + self.selected_pixel = (self.selected_pixel[0], self.selected_pixel[1]+1) + self._print_pixel(self.selected_pixel) + elif key == 97: # a + if self.selected_pixel[0] >= 1 and self.selected_pixel[1] >= 0: + self.selected_pixel = (self.selected_pixel[0]-1, self.selected_pixel[1]) + self._print_pixel(self.selected_pixel) + elif key == 100: # d + if self.selected_pixel[0] >= 0 and self.selected_pixel[1] >= 0 and self.selected_pixel[0] + 1 < self.width: + self.selected_pixel = (self.selected_pixel[0]+1, self.selected_pixel[1]) + self._print_pixel(self.selected_pixel) + elif key == 44: # , + if len(self.highlight_list) > 0: + self.cur_highlight_index = len(self.highlight_list) - 1 if self.cur_highlight_index < 0 else self.cur_highlight_index-1 + print(f"Change highlight index to {self.cur_highlight_index}/{len(self.highlight_list)}") + elif key == 46: # . + if len(self.highlight_list) > 0: + self.cur_highlight_index = -1 if self.cur_highlight_index == len(self.highlight_list)-1 else self.cur_highlight_index+1 + print(f"Change highlight index to {self.cur_highlight_index}/{len(self.highlight_list)}") + elif key == 127 or key == 8: # DEL or backspace (BS), remove selected rectangle + mouse_down = False + mouse_move_counter = 0 + if len(self.rects) > 0: + if self.cur_rect_index < 0: + self.cur_rect_index = len(self.crops) - 1 + del self.rects[self.cur_rect_index] + if len(self.rects) == 0: + self.cur_rect_index = -1 + elif self.cur_rect_index >= len(self.rects): + self.cur_rect_index = len(self.rects) - 1 + elif key == 105: # i + for i, rect in enumerate(self.rects): + self._print_rect(i, rect) + else: + print(f"Pressed key {key}") + self._render() + +if __name__ == '__main__': + import sys + assert len(sys.argv) == 2 + + filename = sys.argv[1] + + image = cv2.imread(filename, cv2.IMREAD_UNCHANGED) + + height = image.shape[0] + width = image.shape[1] + print(f"Load image from {filename}, size: {width} x {height}") + viewer = ImageViewer(image) + viewer.run() diff --git a/SerialPrograms/Scripts/invert_json.py b/SerialPrograms/Scripts/invert_json.py index 3308959ec6..ce89f6b425 100644 --- a/SerialPrograms/Scripts/invert_json.py +++ b/SerialPrograms/Scripts/invert_json.py @@ -1,25 +1,25 @@ -import json -import sys - - -def main(): - if len(sys.argv) != 3: - print("usage: {} ".format(sys.argv[0])) - sys.exit(1) - - with open(sys.argv[1], "r", encoding="utf-8") as f: - data = json.load(f) - - inverted = {} - for key, value in data.items(): - for lang, word in value.items(): - if lang not in inverted: - inverted[lang] = {} - inverted[lang][key] = word - - with open(sys.argv[2], "w", encoding="utf-8") as f: - json.dump(inverted, f, indent=4, ensure_ascii=False) - - -if __name__ == "__main__": +import json +import sys + + +def main(): + if len(sys.argv) != 3: + print("usage: {} ".format(sys.argv[0])) + sys.exit(1) + + with open(sys.argv[1], "r", encoding="utf-8") as f: + data = json.load(f) + + inverted = {} + for key, value in data.items(): + for lang, word in value.items(): + if lang not in inverted: + inverted[lang] = {} + inverted[lang][key] = word + + with open(sys.argv[2], "w", encoding="utf-8") as f: + json.dump(inverted, f, indent=4, ensure_ascii=False) + + +if __name__ == "__main__": main() \ No newline at end of file diff --git a/SerialPrograms/Scripts/make_ocr_json.py b/SerialPrograms/Scripts/make_ocr_json.py index 1a35905fca..988d23ce30 100644 --- a/SerialPrograms/Scripts/make_ocr_json.py +++ b/SerialPrograms/Scripts/make_ocr_json.py @@ -1,154 +1,154 @@ -""" -Generates an OCR json file for dictionary matching - -Set-up: -- Create a file named "target_words.txt". Put all your target dictionary words in this file, -with a new line between each phrase. Put this file in the same folder as this script. -- Adjust the start_line and end_line variables, which are hard-coded. -This helps to limit the script's search of the text dump files. -This helps with dealing with cases where the same English word is used by different parts of the game, but in a different -language, different words may be used. e.g. "Close" in English can be "Nah" or "Schließen" in German. -- Put all the text dump files for all languages in the same folder as this script. You can get the text dump files -from data miners such as https://x.com/mattyoukhana_ - - Ensure the names of the text dump files match the file names in the function `get_text_dump_filename_from_language()` - -How it works: -- each target word from "target_words.txt" is converted to a slug. -i.e. spaces are converted to dashes and converted to lowercase -- for each target word, "English.txt" is searched to find the location (line number and column) of the word. All the -text dump files for the various languages are formatted similarly. So, the above location will also point us to -the corresponding target word in other languages. -- the json OCR file is then created based on the slugs and the location of each target word for each of the languages -""" - -from typing import TextIO - - -start_line, end_line = 39560, 39665 # for menu option items -# start_line, end_line = 50255, 51178 # for all moves - -def find_location_from_target_word(text_dump_filename: str, target_word: str, start: int, end: int) -> tuple[int, int]: - with open(text_dump_filename, 'r', encoding='utf-8', errors='ignore') as file: - for row, line in enumerate(file): - if row < start: - continue - if row > end: - break - split_line = line.split("\t") - for column, cell in enumerate(split_line): - if cell.strip() == target_word: - return row, column - raise Exception("unable to find target word: " + target_word) - -def find_target_word_from_location(text_dump_filename: str, location: tuple[int, int]) -> str: - target_row = location[0] - target_column = location[1] - if target_row < 0: - raise IndexError("target_row index out of range") - with open(text_dump_filename, 'r', encoding='utf-8', errors='ignore') as file: - for row, line in enumerate(file): - if row == target_row: - split_line = line.split("\t") - if target_column < 0 or target_column >= len(split_line): - raise IndexError("target_column index out of range") - for column, cell in enumerate(split_line): - if column == target_column: - return cell.strip() - raise IndexError("target_row index out of range") - - - -def get_slug_from_target_word(target_word: str) -> str: - slug = (target_word.replace(" ", "-") - .replace("'", "") - .replace("’", "") - .replace("é","e") - .casefold()) - return slug - -def generate_ocr_json_file(target_words_filename: str, start: int, end: int): - list_of_slug_location_pair = get_list_of_slug_location_pair(target_words_filename, "English.txt", start, end) - json_output_filename = "OCR.json" - with open(json_output_filename, 'a', encoding='utf-8') as file: - file.truncate(0) # clear file contents first - file.write("{\n") - generate_ocr_json_file_one_language(file, "deu", list_of_slug_location_pair) - file.write(",\n") - generate_ocr_json_file_one_language(file, "eng", list_of_slug_location_pair) - file.write(",\n") - generate_ocr_json_file_one_language(file, "spa", list_of_slug_location_pair) - file.write(",\n") - generate_ocr_json_file_one_language(file, "fra", list_of_slug_location_pair) - file.write(",\n") - generate_ocr_json_file_one_language(file, "ita", list_of_slug_location_pair) - file.write(",\n") - generate_ocr_json_file_one_language(file, "kor", list_of_slug_location_pair) - file.write(",\n") - generate_ocr_json_file_one_language(file, "jpn", list_of_slug_location_pair) - file.write(",\n") - generate_ocr_json_file_one_language(file, "chi_sim", list_of_slug_location_pair) - file.write(",\n") - generate_ocr_json_file_one_language(file, "chi_tra", list_of_slug_location_pair) - file.write("\n}") - - -# start and end parameter so we only search certain portions of file. -# This helps with dealing with cases where the same English word is used by different parts of the game, -# but in a different language, different words may be used. -# e.g. "Close" in English can be "Nah" or "Schließen" in German. -def get_list_of_slug_location_pair(target_words_filename: str, text_dump_filename: str, start: int, end: int) -> list[tuple[str, tuple[int, int]]]: - with open(target_words_filename, 'r', encoding='utf-8', errors='ignore') as file: - list_of_slug_location_pair = [] - for line in file: - target_word = line.strip() - slug = get_slug_from_target_word(target_word) - location = find_location_from_target_word(text_dump_filename, target_word, start, end) - slug_location_pair = (slug, location) - list_of_slug_location_pair.append(slug_location_pair) - print("Done finding list_of_slug_location_pair") - return list_of_slug_location_pair - - -def generate_ocr_json_file_one_language(file: TextIO, language: str, list_of_slug_location_pair: list[tuple[str, tuple[int, int]]]): - text_dump_filename = get_text_dump_filename_from_language(language) - file.write("\t" + "\"" + language + "\"" + ": " + "{" + "\n") - for i, slug_location_pair in enumerate(list_of_slug_location_pair): - slug = slug_location_pair[0] - location = slug_location_pair[1] - target_word = find_target_word_from_location(text_dump_filename, location) - if i != 0: - file.write(",\n") - file.write("\t\t" + "\"" + slug + "\"" + ": " + "[ " + "\"" + target_word + "\"" + " ]") - file.write("\n\t}") - print("Done language: " + language) - -def get_text_dump_filename_from_language(language: str) -> str: - text_dump_filename = "" - match language: - case "deu": - text_dump_filename = "Deutsch.txt" - case "eng": - text_dump_filename = "English.txt" - case "spa": - text_dump_filename = "Español (España).txt" - case "fra": - text_dump_filename = "Français.txt" - case "ita": - text_dump_filename = "Italiano.txt" - case "kor": - text_dump_filename = "한국어.txt" - case "jpn": - text_dump_filename = "日本語 (カタカナ).txt" - case "chi_sim": - text_dump_filename = "简体中文.txt" - case "chi_tra": - text_dump_filename = "繁體中文.txt" - - if text_dump_filename == "": - raise Exception("Language not recognized") - return text_dump_filename - - -generate_ocr_json_file("target_words.txt", start_line, end_line) - - +""" +Generates an OCR json file for dictionary matching + +Set-up: +- Create a file named "target_words.txt". Put all your target dictionary words in this file, +with a new line between each phrase. Put this file in the same folder as this script. +- Adjust the start_line and end_line variables, which are hard-coded. +This helps to limit the script's search of the text dump files. +This helps with dealing with cases where the same English word is used by different parts of the game, but in a different +language, different words may be used. e.g. "Close" in English can be "Nah" or "Schließen" in German. +- Put all the text dump files for all languages in the same folder as this script. You can get the text dump files +from data miners such as https://x.com/mattyoukhana_ + - Ensure the names of the text dump files match the file names in the function `get_text_dump_filename_from_language()` + +How it works: +- each target word from "target_words.txt" is converted to a slug. +i.e. spaces are converted to dashes and converted to lowercase +- for each target word, "English.txt" is searched to find the location (line number and column) of the word. All the +text dump files for the various languages are formatted similarly. So, the above location will also point us to +the corresponding target word in other languages. +- the json OCR file is then created based on the slugs and the location of each target word for each of the languages +""" + +from typing import TextIO + + +start_line, end_line = 39560, 39665 # for menu option items +# start_line, end_line = 50255, 51178 # for all moves + +def find_location_from_target_word(text_dump_filename: str, target_word: str, start: int, end: int) -> tuple[int, int]: + with open(text_dump_filename, 'r', encoding='utf-8', errors='ignore') as file: + for row, line in enumerate(file): + if row < start: + continue + if row > end: + break + split_line = line.split("\t") + for column, cell in enumerate(split_line): + if cell.strip() == target_word: + return row, column + raise Exception("unable to find target word: " + target_word) + +def find_target_word_from_location(text_dump_filename: str, location: tuple[int, int]) -> str: + target_row = location[0] + target_column = location[1] + if target_row < 0: + raise IndexError("target_row index out of range") + with open(text_dump_filename, 'r', encoding='utf-8', errors='ignore') as file: + for row, line in enumerate(file): + if row == target_row: + split_line = line.split("\t") + if target_column < 0 or target_column >= len(split_line): + raise IndexError("target_column index out of range") + for column, cell in enumerate(split_line): + if column == target_column: + return cell.strip() + raise IndexError("target_row index out of range") + + + +def get_slug_from_target_word(target_word: str) -> str: + slug = (target_word.replace(" ", "-") + .replace("'", "") + .replace("’", "") + .replace("é","e") + .casefold()) + return slug + +def generate_ocr_json_file(target_words_filename: str, start: int, end: int): + list_of_slug_location_pair = get_list_of_slug_location_pair(target_words_filename, "English.txt", start, end) + json_output_filename = "OCR.json" + with open(json_output_filename, 'a', encoding='utf-8') as file: + file.truncate(0) # clear file contents first + file.write("{\n") + generate_ocr_json_file_one_language(file, "deu", list_of_slug_location_pair) + file.write(",\n") + generate_ocr_json_file_one_language(file, "eng", list_of_slug_location_pair) + file.write(",\n") + generate_ocr_json_file_one_language(file, "spa", list_of_slug_location_pair) + file.write(",\n") + generate_ocr_json_file_one_language(file, "fra", list_of_slug_location_pair) + file.write(",\n") + generate_ocr_json_file_one_language(file, "ita", list_of_slug_location_pair) + file.write(",\n") + generate_ocr_json_file_one_language(file, "kor", list_of_slug_location_pair) + file.write(",\n") + generate_ocr_json_file_one_language(file, "jpn", list_of_slug_location_pair) + file.write(",\n") + generate_ocr_json_file_one_language(file, "chi_sim", list_of_slug_location_pair) + file.write(",\n") + generate_ocr_json_file_one_language(file, "chi_tra", list_of_slug_location_pair) + file.write("\n}") + + +# start and end parameter so we only search certain portions of file. +# This helps with dealing with cases where the same English word is used by different parts of the game, +# but in a different language, different words may be used. +# e.g. "Close" in English can be "Nah" or "Schließen" in German. +def get_list_of_slug_location_pair(target_words_filename: str, text_dump_filename: str, start: int, end: int) -> list[tuple[str, tuple[int, int]]]: + with open(target_words_filename, 'r', encoding='utf-8', errors='ignore') as file: + list_of_slug_location_pair = [] + for line in file: + target_word = line.strip() + slug = get_slug_from_target_word(target_word) + location = find_location_from_target_word(text_dump_filename, target_word, start, end) + slug_location_pair = (slug, location) + list_of_slug_location_pair.append(slug_location_pair) + print("Done finding list_of_slug_location_pair") + return list_of_slug_location_pair + + +def generate_ocr_json_file_one_language(file: TextIO, language: str, list_of_slug_location_pair: list[tuple[str, tuple[int, int]]]): + text_dump_filename = get_text_dump_filename_from_language(language) + file.write("\t" + "\"" + language + "\"" + ": " + "{" + "\n") + for i, slug_location_pair in enumerate(list_of_slug_location_pair): + slug = slug_location_pair[0] + location = slug_location_pair[1] + target_word = find_target_word_from_location(text_dump_filename, location) + if i != 0: + file.write(",\n") + file.write("\t\t" + "\"" + slug + "\"" + ": " + "[ " + "\"" + target_word + "\"" + " ]") + file.write("\n\t}") + print("Done language: " + language) + +def get_text_dump_filename_from_language(language: str) -> str: + text_dump_filename = "" + match language: + case "deu": + text_dump_filename = "Deutsch.txt" + case "eng": + text_dump_filename = "English.txt" + case "spa": + text_dump_filename = "Español (España).txt" + case "fra": + text_dump_filename = "Français.txt" + case "ita": + text_dump_filename = "Italiano.txt" + case "kor": + text_dump_filename = "한국어.txt" + case "jpn": + text_dump_filename = "日本語 (カタカナ).txt" + case "chi_sim": + text_dump_filename = "简体中文.txt" + case "chi_tra": + text_dump_filename = "繁體中文.txt" + + if text_dump_filename == "": + raise Exception("Language not recognized") + return text_dump_filename + + +generate_ocr_json_file("target_words.txt", start_line, end_line) + + diff --git a/SerialPrograms/Scripts/prune_json.py b/SerialPrograms/Scripts/prune_json.py index ec51a7656a..c6932f71ce 100644 --- a/SerialPrograms/Scripts/prune_json.py +++ b/SerialPrograms/Scripts/prune_json.py @@ -1,125 +1,125 @@ -import json - -filling_slugs = [ - "apple", - "avocado", - "bacon", - "baguette", - "banana", - "basil", - "cheese", - "cherry-tomatoes", - "chorizo", - "cucumber", - "egg", - "fried-fillet", - "green-bell-pepper", - "ham", - "hamburger", - "herbed-sausage", - "jalapeño", - "kiwi", - "klawf-stick", - "lettuce", - "noodles", - "onion", - "pickle", - "pineapple", - "potato-salad", - "potato-tortilla", - "prosciutto", - "red-bell-pepper", - "red-onion", - "rice", - "smoked-fillet", - "strawberry", - "tofu", - "tomato", - "watercress", - "yellow-bell-pepper"] - -condiment_slugs = [ - "butter", - "chili-sauce", - "cream-cheese", - "curry-powder", - "horseradish", - "jam", - "ketchup", - "marmalade", - "mayonnaise", - "mustard", - "olive-oil", - "peanut-butter", - "pepper", - "salt", - "vinegar", - "wasabi", - "whipped-cream", - "yogurt", - "bitter-herba-mystica", - "spicy-herba-mystica", - "salty-herba-mystica", - "sour-herba-mystica", - "sweet-herba-mystica"] - -pick_slugs = [ - "blue-flag-pick", - "blue-poke-ball-pick", - "blue-sky-flower-pick", - "gold-pick", - "green-poke-ball-pick", - "heroic-sword-pick", - "magical-heart-pick", - "magical-star-pick", - "parasol-pick", - "party-sparkler-pick", - "pika-pika-pick", - "red-flag-pick", - "red-poke-ball-pick", - "silver-pick", - "smiling-vee-pick", - "sunrise-flower-pick", - "sunset-flower-pick", - "vee-vee-pick", - "winking-pika-pick"] - -def filter_keys(obj, keys): - if isinstance(obj, dict): - return {k: filter_keys(v, keys) for k, v in obj.items() if k not in keys} - elif isinstance(obj, list): - return [filter_keys(elem, keys) for elem in obj] - else: - return obj - -with open("OCR.json", "r", encoding="utf-8") as f: - input_ocr = json.load(f) - -output_ocr_condiments = filter_keys(input_ocr, filling_slugs + pick_slugs) -with open('SandwichCondimentOCR.json', 'w', encoding="utf-8") as f: - json.dump(output_ocr_condiments, f, indent=4, ensure_ascii=False) - -output_ocr_fillings = filter_keys(input_ocr, condiment_slugs + pick_slugs) -with open('SandwichFillingOCR.json', 'w', encoding="utf-8") as f: - json.dump(output_ocr_fillings, f, indent=4, ensure_ascii=False) - -output_ocr_picks = filter_keys(input_ocr, condiment_slugs + filling_slugs) -with open('SandwichPickOCR.json', 'w', encoding="utf-8") as f: - json.dump(output_ocr_picks, f, indent=4, ensure_ascii=False) - - - -with open("Sprites.json", "r", encoding="utf-8") as f: - input_sprite = json.load(f) - -output_sprite_condiments = filter_keys(input_sprite, filling_slugs + pick_slugs) -with open('SandwichCondimentSprites.json', 'w', encoding="utf-8") as f: - json.dump(output_sprite_condiments, f, indent=4, ensure_ascii=False) - -output_sprite_fillings = filter_keys(input_sprite, condiment_slugs + pick_slugs) -with open('SandwichFillingSprites.json', 'w', encoding="utf-8") as f: - json.dump(output_sprite_fillings, f, indent=4, ensure_ascii=False) - -output_sprite_picks = filter_keys(input_sprite, condiment_slugs + filling_slugs) -with open('SandwichPickSprites.json', 'w', encoding="utf-8") as f: +import json + +filling_slugs = [ + "apple", + "avocado", + "bacon", + "baguette", + "banana", + "basil", + "cheese", + "cherry-tomatoes", + "chorizo", + "cucumber", + "egg", + "fried-fillet", + "green-bell-pepper", + "ham", + "hamburger", + "herbed-sausage", + "jalapeño", + "kiwi", + "klawf-stick", + "lettuce", + "noodles", + "onion", + "pickle", + "pineapple", + "potato-salad", + "potato-tortilla", + "prosciutto", + "red-bell-pepper", + "red-onion", + "rice", + "smoked-fillet", + "strawberry", + "tofu", + "tomato", + "watercress", + "yellow-bell-pepper"] + +condiment_slugs = [ + "butter", + "chili-sauce", + "cream-cheese", + "curry-powder", + "horseradish", + "jam", + "ketchup", + "marmalade", + "mayonnaise", + "mustard", + "olive-oil", + "peanut-butter", + "pepper", + "salt", + "vinegar", + "wasabi", + "whipped-cream", + "yogurt", + "bitter-herba-mystica", + "spicy-herba-mystica", + "salty-herba-mystica", + "sour-herba-mystica", + "sweet-herba-mystica"] + +pick_slugs = [ + "blue-flag-pick", + "blue-poke-ball-pick", + "blue-sky-flower-pick", + "gold-pick", + "green-poke-ball-pick", + "heroic-sword-pick", + "magical-heart-pick", + "magical-star-pick", + "parasol-pick", + "party-sparkler-pick", + "pika-pika-pick", + "red-flag-pick", + "red-poke-ball-pick", + "silver-pick", + "smiling-vee-pick", + "sunrise-flower-pick", + "sunset-flower-pick", + "vee-vee-pick", + "winking-pika-pick"] + +def filter_keys(obj, keys): + if isinstance(obj, dict): + return {k: filter_keys(v, keys) for k, v in obj.items() if k not in keys} + elif isinstance(obj, list): + return [filter_keys(elem, keys) for elem in obj] + else: + return obj + +with open("OCR.json", "r", encoding="utf-8") as f: + input_ocr = json.load(f) + +output_ocr_condiments = filter_keys(input_ocr, filling_slugs + pick_slugs) +with open('SandwichCondimentOCR.json', 'w', encoding="utf-8") as f: + json.dump(output_ocr_condiments, f, indent=4, ensure_ascii=False) + +output_ocr_fillings = filter_keys(input_ocr, condiment_slugs + pick_slugs) +with open('SandwichFillingOCR.json', 'w', encoding="utf-8") as f: + json.dump(output_ocr_fillings, f, indent=4, ensure_ascii=False) + +output_ocr_picks = filter_keys(input_ocr, condiment_slugs + filling_slugs) +with open('SandwichPickOCR.json', 'w', encoding="utf-8") as f: + json.dump(output_ocr_picks, f, indent=4, ensure_ascii=False) + + + +with open("Sprites.json", "r", encoding="utf-8") as f: + input_sprite = json.load(f) + +output_sprite_condiments = filter_keys(input_sprite, filling_slugs + pick_slugs) +with open('SandwichCondimentSprites.json', 'w', encoding="utf-8") as f: + json.dump(output_sprite_condiments, f, indent=4, ensure_ascii=False) + +output_sprite_fillings = filter_keys(input_sprite, condiment_slugs + pick_slugs) +with open('SandwichFillingSprites.json', 'w', encoding="utf-8") as f: + json.dump(output_sprite_fillings, f, indent=4, ensure_ascii=False) + +output_sprite_picks = filter_keys(input_sprite, condiment_slugs + filling_slugs) +with open('SandwichPickSprites.json', 'w', encoding="utf-8") as f: json.dump(output_sprite_picks, f, indent=4, ensure_ascii=False) \ No newline at end of file diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioPipelineOptions.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioPipelineOptions.h index 353c28f031..282562bb47 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioPipelineOptions.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioPipelineOptions.h @@ -1,79 +1,79 @@ -/* Audio Pipeline Options - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_AudioPipeline_AudioPipelineOptions_H -#define PokemonAutomation_AudioPipeline_AudioPipelineOptions_H - -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "CommonFramework/GlobalSettingsPanel.h" - -namespace PokemonAutomation{ - - -class AudioPipelineOptions : public GroupOption{ -public: - AudioPipelineOptions() - : GroupOption( - "Audio Pipeline", - LockMode::LOCK_WHILE_RUNNING, - GroupOption::EnableMode::ALWAYS_ENABLED, true - ) - , FILE_VOLUME_SCALE( - "Audio File Input Volume Scale:
" - "Multiply audio file playback by this factor. (This is linear scale. So each factor of 10 is 20dB.)", - LockMode::UNLOCK_WHILE_RUNNING, - 0.31622776601683793320, // -10dB - -10000, 10000 - ) - , DEVICE_VOLUME_SCALE( - "Audio Device Input Volume Scale:
" - "Multiply audio device input by this factor. (This is linear scale. So each factor of 10 is 20dB.)", - LockMode::UNLOCK_WHILE_RUNNING, - 1.0, -10000, 10000 - ) - , SHOW_ALL_DEVICES( - "Show all Audio Devices:
" - "Show all audio devices - including duplicates.", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , SHOW_RECORD_FREQUENCIES( - "Show Record Frequencies:
" - "Show option to record audio frequencies.", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , AUTO_RESET_SECONDS( - "Audio Auto-Reset:
" - "Attempt to reset the audio if this many seconds has elapsed since the last audio frame (in order to fix issues with RDP disconnection, etc).", - LockMode::UNLOCK_WHILE_RUNNING, - 5 - ) - { - PA_ADD_OPTION(FILE_VOLUME_SCALE); - PA_ADD_OPTION(DEVICE_VOLUME_SCALE); - PA_ADD_OPTION(SHOW_ALL_DEVICES); - if (PreloadSettings::instance().DEVELOPER_MODE){ - PA_ADD_OPTION(SHOW_RECORD_FREQUENCIES); - } - PA_ADD_OPTION(AUTO_RESET_SECONDS); - } - -public: - FloatingPointOption FILE_VOLUME_SCALE; - FloatingPointOption DEVICE_VOLUME_SCALE; - BooleanCheckBoxOption SHOW_ALL_DEVICES; - BooleanCheckBoxOption SHOW_RECORD_FREQUENCIES; - SimpleIntegerOption AUTO_RESET_SECONDS; -}; - - - -} -#endif +/* Audio Pipeline Options + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_AudioPipeline_AudioPipelineOptions_H +#define PokemonAutomation_AudioPipeline_AudioPipelineOptions_H + +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "CommonFramework/GlobalSettingsPanel.h" + +namespace PokemonAutomation{ + + +class AudioPipelineOptions : public GroupOption{ +public: + AudioPipelineOptions() + : GroupOption( + "Audio Pipeline", + LockMode::LOCK_WHILE_RUNNING, + GroupOption::EnableMode::ALWAYS_ENABLED, true + ) + , FILE_VOLUME_SCALE( + "Audio File Input Volume Scale:
" + "Multiply audio file playback by this factor. (This is linear scale. So each factor of 10 is 20dB.)", + LockMode::UNLOCK_WHILE_RUNNING, + 0.31622776601683793320, // -10dB + -10000, 10000 + ) + , DEVICE_VOLUME_SCALE( + "Audio Device Input Volume Scale:
" + "Multiply audio device input by this factor. (This is linear scale. So each factor of 10 is 20dB.)", + LockMode::UNLOCK_WHILE_RUNNING, + 1.0, -10000, 10000 + ) + , SHOW_ALL_DEVICES( + "Show all Audio Devices:
" + "Show all audio devices - including duplicates.", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , SHOW_RECORD_FREQUENCIES( + "Show Record Frequencies:
" + "Show option to record audio frequencies.", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , AUTO_RESET_SECONDS( + "Audio Auto-Reset:
" + "Attempt to reset the audio if this many seconds has elapsed since the last audio frame (in order to fix issues with RDP disconnection, etc).", + LockMode::UNLOCK_WHILE_RUNNING, + 5 + ) + { + PA_ADD_OPTION(FILE_VOLUME_SCALE); + PA_ADD_OPTION(DEVICE_VOLUME_SCALE); + PA_ADD_OPTION(SHOW_ALL_DEVICES); + if (PreloadSettings::instance().DEVELOPER_MODE){ + PA_ADD_OPTION(SHOW_RECORD_FREQUENCIES); + } + PA_ADD_OPTION(AUTO_RESET_SECONDS); + } + +public: + FloatingPointOption FILE_VOLUME_SCALE; + FloatingPointOption DEVICE_VOLUME_SCALE; + BooleanCheckBoxOption SHOW_ALL_DEVICES; + BooleanCheckBoxOption SHOW_RECORD_FREQUENCIES; + SimpleIntegerOption AUTO_RESET_SECONDS; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQtThread.cpp b/SerialPrograms/Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQtThread.cpp index 69098a9f03..6578ee1abb 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQtThread.cpp +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQtThread.cpp @@ -57,7 +57,7 @@ AudioPassthroughPairQtThread::~AudioPassthroughPairQtThread(){ } void AudioPassthroughPairQtThread::run(){ auto scope_check = m_sanitizer.check_scope(); - GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(); + GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(m_logger); AudioPassthroughPairQt body(m_logger); m_body.store(&body, std::memory_order_relaxed); diff --git a/SerialPrograms/Source/CommonFramework/Environment/Environment.h b/SerialPrograms/Source/CommonFramework/Environment/Environment.h index 3501a065a0..dc18fbea44 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/Environment.h +++ b/SerialPrograms/Source/CommonFramework/Environment/Environment.h @@ -8,7 +8,7 @@ #define PokemonAutomation_Environment_H #include -#include +#include "Common/Cpp/AbstractLogger.h" #include "Common/Cpp/Options/EnumDropdownDatabase.h" #if _WIN32 @@ -24,7 +24,7 @@ namespace PokemonAutomation{ const EnumDropdownDatabase& PRIORITY_DATABASE(); -bool set_thread_priority(ThreadPriority priority); +bool set_thread_priority(Logger& logger, ThreadPriority priority); class ThreadHandle; diff --git a/SerialPrograms/Source/CommonFramework/Environment/Environment_Linux.h b/SerialPrograms/Source/CommonFramework/Environment/Environment_Linux.h index 36aeddf937..16c9ad1590 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/Environment_Linux.h +++ b/SerialPrograms/Source/CommonFramework/Environment/Environment_Linux.h @@ -7,11 +7,6 @@ #ifndef PokemonAutomation_Environment_Linux_H #define PokemonAutomation_Environment_Linux_H -#include -#include -#include -#include "Common/Cpp/Time.h" - namespace PokemonAutomation{ @@ -27,37 +22,6 @@ constexpr ThreadPriority DEFAULT_PRIORITY_COMPUTE = ThreadPriority -class ThreadHandle{ -public: - pthread_t handle; -}; -ThreadHandle current_thread_handle(); -// Get the cpu time of the thread. -// This function must be called in the same process the thread belongs to. -WallClock::duration thread_cpu_time(const ThreadHandle& handle); - - - -class SystemCpuTime{ -public: - static SystemCpuTime now(); - static size_t vcores(); - - bool is_valid() const{ - return m_usec != 0 || m_sec != 0; - } - - std::chrono::microseconds operator-(const SystemCpuTime& x) const; - -private: - void set_to_now(); - static size_t read_cores(); - -private: - time_t m_sec = 0; - suseconds_t m_usec = 0; -}; - diff --git a/SerialPrograms/Source/CommonFramework/Environment/Environment_Linux.tpp b/SerialPrograms/Source/CommonFramework/Environment/Environment_Linux.tpp index 0cab243343..36f34daab3 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/Environment_Linux.tpp +++ b/SerialPrograms/Source/CommonFramework/Environment/Environment_Linux.tpp @@ -38,7 +38,7 @@ const EnumDropdownDatabase& PRIORITY_DATABASE(){ return database; } -bool set_thread_priority(ThreadPriority priority){ +bool set_thread_priority(Logger& logger, ThreadPriority priority){ int native_priority = sched_get_priority_min(SCHED_RR); switch (priority){ case ThreadPriority::Max: @@ -54,11 +54,12 @@ bool set_thread_priority(ThreadPriority priority){ struct sched_param param; param.sched_priority = native_priority; if (pthread_setschedparam(pthread_self(), SCHED_RR, ¶m) == 0){ + logger.log("Thread priority set to: " + PRIORITY_DATABASE().find(priority)->display, COLOR_BLUE); return true; } int errorcode = errno; - global_logger_tagged().log("Unable to set process priority. Error Code = " + std::to_string(errorcode), COLOR_RED); + logger.log("Unable to set process priority. Error Code = " + std::to_string(errorcode), COLOR_RED); return false; } @@ -66,74 +67,6 @@ bool set_thread_priority(ThreadPriority priority){ -ThreadHandle current_thread_handle(){ - return ThreadHandle{pthread_self()}; -} -WallClock::duration thread_cpu_time(const ThreadHandle& handle){ - uint64_t nanos = 0; - -#if defined(__APPLE__) - uint64_t tid = 0; - pthread_threadid_np(handle.handle, &tid); - struct proc_threadinfo pth; - if (PROC_PIDTHREADINFO_SIZE == - proc_pidinfo(getpid(), PROC_PIDTHREADID64INFO, tid, &pth, - PROC_PIDTHREADINFO_SIZE)) { - nanos = pth.pth_user_time + pth.pth_system_time; // user time + system time in ns - } - else{ - return WallClock::duration::min(); - } - -#else - clockid_t clockid; - int error = pthread_getcpuclockid(handle.handle, &clockid); - if (error){ - return WallClock::duration::min(); - } - - struct timespec ts; - if (clock_gettime(clockid, &ts) == -1){ - return WallClock::duration::min(); - } - - nanos = (uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec; -#endif - - return std::chrono::duration_cast(std::chrono::nanoseconds(nanos)); -} - - - - - - -std::chrono::microseconds SystemCpuTime::operator-(const SystemCpuTime& x) const{ - return std::chrono::microseconds((m_sec - x.m_sec) * 1000000ull + (m_usec - x.m_usec)); -} -SystemCpuTime SystemCpuTime::now(){ - SystemCpuTime ret; - ret.set_to_now(); - return ret; -} -size_t SystemCpuTime::vcores(){ - static size_t cores = read_cores(); - return cores; -} -void SystemCpuTime::set_to_now(){ - struct rusage ru; - if (getrusage(RUSAGE_SELF, &ru) == -1){ - m_sec = 0; - m_usec = 0; - }else{ - m_sec = ru.ru_utime.tv_sec + ru.ru_stime.tv_sec; - m_usec = ru.ru_utime.tv_usec + ru.ru_stime.tv_usec; - } -} -size_t SystemCpuTime::read_cores(){ - return std::thread::hardware_concurrency(); -} - diff --git a/SerialPrograms/Source/CommonFramework/Environment/Environment_Windows.h b/SerialPrograms/Source/CommonFramework/Environment/Environment_Windows.h index 2be6b3cce3..f27072df68 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/Environment_Windows.h +++ b/SerialPrograms/Source/CommonFramework/Environment/Environment_Windows.h @@ -7,9 +7,6 @@ #ifndef PokemonAutomation_Environment_Windows_H #define PokemonAutomation_Environment_Windows_H -#include -#include "Common/Cpp/Time.h" - namespace PokemonAutomation{ @@ -31,53 +28,6 @@ constexpr ThreadPriority DEFAULT_PRIORITY_COMPUTE = ThreadPriority -class WinApiHandleHolder; - -class ThreadHandle{ -public: - ThreadHandle(ThreadHandle&& x); - ThreadHandle& operator=(ThreadHandle&& x); - ThreadHandle(const ThreadHandle& x); - ThreadHandle& operator=(const ThreadHandle& x); - ~ThreadHandle(); - - ThreadHandle(std::shared_ptr ptr = nullptr); - - std::shared_ptr m_ptr; -}; -ThreadHandle current_thread_handle(); -WallClock::duration thread_cpu_time(const ThreadHandle& handle); - - - - - -class SystemCpuTime{ -public: - static SystemCpuTime now(); - static size_t vcores(); - - bool is_valid() const{ - return m_kernel != 0; - } - - std::chrono::microseconds operator-(const SystemCpuTime& x) const{ - uint64_t idle = m_idle - x.m_idle; - uint64_t kernel = m_kernel - x.m_kernel; - uint64_t user = m_user - x.m_user; - uint64_t total_utilization = kernel + user - idle; - return std::chrono::microseconds(total_utilization / 10); - } - -private: - void set_to_now(); - static size_t read_cores(); - -private: - uint64_t m_idle = 0; - uint64_t m_kernel = 0; - uint64_t m_user = 0; -}; diff --git a/SerialPrograms/Source/CommonFramework/Environment/Environment_Windows.tpp b/SerialPrograms/Source/CommonFramework/Environment/Environment_Windows.tpp index 6da3b651cc..38e68af824 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/Environment_Windows.tpp +++ b/SerialPrograms/Source/CommonFramework/Environment/Environment_Windows.tpp @@ -30,26 +30,6 @@ namespace PokemonAutomation{ -class WinApiHandleHolder{ -public: - WinApiHandleHolder(const WinApiHandleHolder& x) = delete; - void operator=(const WinApiHandleHolder& x) = delete; - ~WinApiHandleHolder(){ - CloseHandle(m_handle); - } - WinApiHandleHolder(HANDLE handle) - : m_handle(handle) - {} - operator HANDLE() const{ - return m_handle; - } - -private: - HANDLE m_handle; -}; - - - const EnumDropdownDatabase& PRIORITY_DATABASE(){ static EnumDropdownDatabase database({ @@ -63,119 +43,43 @@ const EnumDropdownDatabase& PRIORITY_DATABASE(){ return database; } -bool set_thread_priority(ThreadPriority priority){ - DWORD native_priority; +bool set_thread_priority(Logger& logger, ThreadPriority priority){ + int native_priority; switch (priority){ case ThreadPriority::Realtime: - native_priority = REALTIME_PRIORITY_CLASS; + native_priority = THREAD_PRIORITY_TIME_CRITICAL; break; case ThreadPriority::High: - native_priority = HIGH_PRIORITY_CLASS; + native_priority = THREAD_PRIORITY_HIGHEST; break; case ThreadPriority::AboveNormal: - native_priority = ABOVE_NORMAL_PRIORITY_CLASS; + native_priority = THREAD_PRIORITY_ABOVE_NORMAL; break; case ThreadPriority::Normal: - native_priority = NORMAL_PRIORITY_CLASS; + native_priority = THREAD_PRIORITY_NORMAL; break; case ThreadPriority::BelowNormal: - native_priority = BELOW_NORMAL_PRIORITY_CLASS; + native_priority = THREAD_PRIORITY_BELOW_NORMAL; break; case ThreadPriority::Low: - native_priority = IDLE_PRIORITY_CLASS; + native_priority = THREAD_PRIORITY_IDLE; break; default: throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Priority: " + std::to_string((int)priority)); } - if (SetPriorityClass(GetCurrentProcess(), native_priority)){ + if (SetThreadPriority(GetCurrentThread(), native_priority)){ // cout << "Thread priority set to: " + PRIORITY_DATABASE().find(priority)->display << endl; - global_logger_tagged().log("Thread priority set to: " + PRIORITY_DATABASE().find(priority)->display, COLOR_BLUE); + logger.log("Thread priority set to: " + PRIORITY_DATABASE().find(priority)->display, COLOR_BLUE); return true; } DWORD error = GetLastError(); - global_logger_tagged().log("Unable to set process priority. Error Code = " + std::to_string(error), COLOR_RED); + logger.log("Unable to set thread priority. Error Code = " + std::to_string(error), COLOR_RED); return false; } -ThreadHandle::ThreadHandle(ThreadHandle&& x) = default; -ThreadHandle& ThreadHandle::operator=(ThreadHandle&& x) = default; -ThreadHandle::ThreadHandle(const ThreadHandle& x) = default; -ThreadHandle& ThreadHandle::operator=(const ThreadHandle& x) = default; -ThreadHandle::~ThreadHandle() = default; -ThreadHandle::ThreadHandle(std::shared_ptr ptr) - : m_ptr(std::move(ptr)) -{} - - - -ThreadHandle current_thread_handle(){ - DWORD id = GetCurrentThreadId(); - HANDLE handle = OpenThread(THREAD_QUERY_LIMITED_INFORMATION, false, id); -// cout << handle << endl; - if (handle == NULL){ - return ThreadHandle(); - } - return ThreadHandle{std::make_shared(handle)}; -} -WallClock::duration thread_cpu_time(const ThreadHandle& handle){ - FILETIME creation_time; - FILETIME exit_time; - FILETIME kernel_time; - FILETIME user_time; - - if (!handle.m_ptr){ - return WallClock::duration::min(); - } - - if (!GetThreadTimes(*handle.m_ptr, &creation_time, &exit_time, &kernel_time, &user_time)){ - return WallClock::duration::min(); - } - - uint64_t nanos = user_time.dwLowDateTime + ((uint64_t)user_time.dwHighDateTime << 32); - nanos *= 100; - return std::chrono::duration_cast(std::chrono::nanoseconds(nanos)); -} - - - - - - - - -SystemCpuTime SystemCpuTime::now(){ - SystemCpuTime ret; - ret.set_to_now(); - return ret; -} -size_t SystemCpuTime::vcores(){ - static size_t cores = read_cores(); - return cores; -} -void SystemCpuTime::set_to_now(){ - FILETIME idle_time, kernel_time, user_time; - if (GetSystemTimes(&idle_time, &kernel_time, &user_time)){ - m_idle = idle_time.dwLowDateTime + ((uint64_t)idle_time.dwHighDateTime << 32); - m_kernel = kernel_time.dwLowDateTime + ((uint64_t)kernel_time.dwHighDateTime << 32); - m_user = user_time.dwLowDateTime + ((uint64_t)user_time.dwHighDateTime << 32); - }else{ - m_idle = 0; - m_kernel = 0; - m_user = 0; - } -} -size_t SystemCpuTime::read_cores(){ - size_t cores = 0; - WORD total_groups = GetActiveProcessorGroupCount(); - for (WORD group = 0; group < total_groups; group++){ - DWORD processors_within_group = GetActiveProcessorCount(group); - cores += processors_within_group; - } - return cores; -} diff --git a/SerialPrograms/Source/CommonFramework/Environment/Environment_x86_Windows.tpp b/SerialPrograms/Source/CommonFramework/Environment/Environment_x86_Windows.tpp index d4e44f343d..68018ed200 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/Environment_x86_Windows.tpp +++ b/SerialPrograms/Source/CommonFramework/Environment/Environment_x86_Windows.tpp @@ -13,6 +13,9 @@ #endif #endif +#include +#include +#include #include "Common/Cpp/Exceptions.h" #include "Environment.h" diff --git a/SerialPrograms/Source/CommonFramework/Environment/SystemSleep_Apple.tpp b/SerialPrograms/Source/CommonFramework/Environment/SystemSleep_Apple.tpp index 24cfe348d9..b0b645b61a 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/SystemSleep_Apple.tpp +++ b/SerialPrograms/Source/CommonFramework/Environment/SystemSleep_Apple.tpp @@ -1,144 +1,144 @@ -/* OS Sleep (Apple) - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#include -#include -#include -#include "CommonFramework/Logging/Logger.h" -#include "SystemSleep.h" - -namespace PokemonAutomation{ - - - -class AppleSleepController : public SystemSleepController{ -public: - virtual ~AppleSleepController(){ - std::lock_guard lg(m_lock); - m_screen_on_requests = 0; - m_no_sleep_requests = 0; - update_state(); - } - virtual void push_screen_on() override{ - std::lock_guard lg(m_lock); - m_screen_on_requests++; - update_state(); - } - virtual void pop_screen_on() override{ - std::lock_guard lg(m_lock); - m_screen_on_requests--; - update_state(); - } - virtual void push_no_sleep() override{ - std::lock_guard lg(m_lock); - m_no_sleep_requests++; - update_state(); - } - virtual void pop_no_sleep() override{ - std::lock_guard lg(m_lock); - m_no_sleep_requests--; - update_state(); - } - - -private: - // Disable/Enable screen saver and OS sleep. - // Return whether the setting is successful. - bool prevent_sleep(bool prevent); - void update_state(); - - bool disable_sleep(); - bool enable_sleep(); - - IOReturn m_prevention_succeeded = kIOReturnError; - IOPMAssertionID m_session_id = 0; - - size_t m_screen_on_requests = 0; - size_t m_no_sleep_requests = 0; -}; - - -// Code from https://stackoverflow.com/questions/5596319/how-to-programmatically-prevent-a-mac-from-going-to-sleep/8461182#8461182 - - -bool AppleSleepController::prevent_sleep(bool prevent){ - if (prevent){ - return disable_sleep(); - }else{ - return enable_sleep(); - } -} - -bool AppleSleepController::disable_sleep(){ - if (m_prevention_succeeded == kIOReturnSuccess){ - return true; - } - std::cout << "Disabling display sleep and OS sleep" << std::endl; - // kIOPMAssertionTypeNoDisplaySleep prevents display sleep, - // kIOPMAssertionTypeNoIdleSleep prevents idle sleep - - // NOTE: IOPMAssertionCreateWithName limits the string to 128 characters. - CFStringRef reasonForActivity = (CFStringRef) __builtin___CFStringMakeConstantString("SerialPrograms is running"); - - m_prevention_succeeded = kIOReturnError; - m_session_id = 0; - m_prevention_succeeded = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, - kIOPMAssertionLevelOn, reasonForActivity, &m_session_id); - if (m_prevention_succeeded != kIOReturnSuccess){ - m_session_id = 0; - std::cerr << "Cannot disable sleep. Error code " << m_prevention_succeeded << std::endl; - return false; - } - - std::cout << "Disabled display sleep and OS sleep" << std::endl; - return true; -} - -bool AppleSleepController::enable_sleep(){ - if (m_prevention_succeeded == kIOReturnSuccess){ - IOPMAssertionRelease(m_session_id); - m_session_id = 0; - m_prevention_succeeded = kIOReturnError; - std::cout << "Enabled display sleep and OS sleep." << std::endl; - } - return true; -} - - - -void AppleSleepController::update_state(){ - // Must call under lock. - - SleepSuppress before_state = m_state.load(std::memory_order_relaxed); - SleepSuppress after_state = SleepSuppress::NONE; - - // TODO: Distiguish these two. - bool enabled = m_screen_on_requests > 0 || m_no_sleep_requests > 0; - prevent_sleep(enabled); - - after_state = enabled - ? SleepSuppress::SCREEN_ON - : SleepSuppress::NONE, - - m_state.store(after_state, std::memory_order_release); - - if (before_state != after_state){ - notify_listeners(after_state); - } -} - - -SystemSleepController& SystemSleepController::instance(){ - static AppleSleepController controller; - return controller; -} - - - - - - -} +/* OS Sleep (Apple) + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#include +#include +#include +#include "CommonFramework/Logging/Logger.h" +#include "SystemSleep.h" + +namespace PokemonAutomation{ + + + +class AppleSleepController : public SystemSleepController{ +public: + virtual ~AppleSleepController(){ + std::lock_guard lg(m_lock); + m_screen_on_requests = 0; + m_no_sleep_requests = 0; + update_state(); + } + virtual void push_screen_on() override{ + std::lock_guard lg(m_lock); + m_screen_on_requests++; + update_state(); + } + virtual void pop_screen_on() override{ + std::lock_guard lg(m_lock); + m_screen_on_requests--; + update_state(); + } + virtual void push_no_sleep() override{ + std::lock_guard lg(m_lock); + m_no_sleep_requests++; + update_state(); + } + virtual void pop_no_sleep() override{ + std::lock_guard lg(m_lock); + m_no_sleep_requests--; + update_state(); + } + + +private: + // Disable/Enable screen saver and OS sleep. + // Return whether the setting is successful. + bool prevent_sleep(bool prevent); + void update_state(); + + bool disable_sleep(); + bool enable_sleep(); + + IOReturn m_prevention_succeeded = kIOReturnError; + IOPMAssertionID m_session_id = 0; + + size_t m_screen_on_requests = 0; + size_t m_no_sleep_requests = 0; +}; + + +// Code from https://stackoverflow.com/questions/5596319/how-to-programmatically-prevent-a-mac-from-going-to-sleep/8461182#8461182 + + +bool AppleSleepController::prevent_sleep(bool prevent){ + if (prevent){ + return disable_sleep(); + }else{ + return enable_sleep(); + } +} + +bool AppleSleepController::disable_sleep(){ + if (m_prevention_succeeded == kIOReturnSuccess){ + return true; + } + std::cout << "Disabling display sleep and OS sleep" << std::endl; + // kIOPMAssertionTypeNoDisplaySleep prevents display sleep, + // kIOPMAssertionTypeNoIdleSleep prevents idle sleep + + // NOTE: IOPMAssertionCreateWithName limits the string to 128 characters. + CFStringRef reasonForActivity = (CFStringRef) __builtin___CFStringMakeConstantString("SerialPrograms is running"); + + m_prevention_succeeded = kIOReturnError; + m_session_id = 0; + m_prevention_succeeded = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, + kIOPMAssertionLevelOn, reasonForActivity, &m_session_id); + if (m_prevention_succeeded != kIOReturnSuccess){ + m_session_id = 0; + std::cerr << "Cannot disable sleep. Error code " << m_prevention_succeeded << std::endl; + return false; + } + + std::cout << "Disabled display sleep and OS sleep" << std::endl; + return true; +} + +bool AppleSleepController::enable_sleep(){ + if (m_prevention_succeeded == kIOReturnSuccess){ + IOPMAssertionRelease(m_session_id); + m_session_id = 0; + m_prevention_succeeded = kIOReturnError; + std::cout << "Enabled display sleep and OS sleep." << std::endl; + } + return true; +} + + + +void AppleSleepController::update_state(){ + // Must call under lock. + + SleepSuppress before_state = m_state.load(std::memory_order_relaxed); + SleepSuppress after_state = SleepSuppress::NONE; + + // TODO: Distiguish these two. + bool enabled = m_screen_on_requests > 0 || m_no_sleep_requests > 0; + prevent_sleep(enabled); + + after_state = enabled + ? SleepSuppress::SCREEN_ON + : SleepSuppress::NONE, + + m_state.store(after_state, std::memory_order_release); + + if (before_state != after_state){ + notify_listeners(after_state); + } +} + + +SystemSleepController& SystemSleepController::instance(){ + static AppleSleepController controller; + return controller; +} + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Environment/SystemSleep_Windows.tpp b/SerialPrograms/Source/CommonFramework/Environment/SystemSleep_Windows.tpp index 6325b58dd2..2f71cd8223 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/SystemSleep_Windows.tpp +++ b/SerialPrograms/Source/CommonFramework/Environment/SystemSleep_Windows.tpp @@ -1,127 +1,127 @@ -/* OS Sleep (Windows) - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#include -#include -#include -#include "Common/Qt/Redispatch.h" -#include "CommonFramework/Logging/Logger.h" -#include "SystemSleep.h" - -namespace PokemonAutomation{ - - -class WindowsSleepController : public SystemSleepController{ -public: - virtual ~WindowsSleepController(){ - { - std::lock_guard lg(m_lock); - m_stopping = true; - m_cv.notify_all(); - } - m_thread.join(); - if (m_state.load(std::memory_order_relaxed) != SleepSuppress::NONE){ - global_logger_tagged().log("Destroying WindowsSleepController with active requests...", COLOR_RED); - } - } - WindowsSleepController() - : m_screen_on_requests(0) - , m_no_sleep_requests(0) - , m_stopping(false) - , m_thread(&WindowsSleepController::thread_loop, this) - {} - - virtual void push_screen_on() override{ - std::lock_guard lg(m_lock); - m_screen_on_requests++; - m_cv.notify_all(); - } - virtual void pop_screen_on() override{ - std::lock_guard lg(m_lock); - m_screen_on_requests--; - m_cv.notify_all(); - } - virtual void push_no_sleep() override{ - std::lock_guard lg(m_lock); - m_no_sleep_requests++; - m_cv.notify_all(); - } - virtual void pop_no_sleep() override{ - std::lock_guard lg(m_lock); - m_no_sleep_requests--; - m_cv.notify_all(); - } - -private: - void thread_loop(){ - // SetThreadExecutionState(ES_CONTINUOUS) only lasts as long as the - // thread is alive. So we use our own thread. - while (true){ - std::unique_lock lg(m_lock); - if (m_stopping){ - return; - } - - SleepSuppress before_state = m_state.load(std::memory_order_relaxed); - SleepSuppress after_state = SleepSuppress::NONE; - - EXECUTION_STATE flags = ES_CONTINUOUS; - if (m_no_sleep_requests > 0){ - flags |= ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED; - after_state = SleepSuppress::NO_SLEEP; - } - if (m_screen_on_requests > 0){ - flags |= ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED; - after_state = SleepSuppress::SCREEN_ON; - } - EXECUTION_STATE ret = SetThreadExecutionState(flags); - if (ret == 0){ - global_logger_tagged().log("Unable to set system sleep state.", COLOR_RED); - }else{ - switch (after_state){ - case SleepSuppress::NONE: - global_logger_tagged().log("Setting sleep state to: None", COLOR_BLUE); - break; - case SleepSuppress::NO_SLEEP: - global_logger_tagged().log("Setting sleep state to: No Sleep", COLOR_BLUE); - break; - case SleepSuppress::SCREEN_ON: - global_logger_tagged().log("Setting sleep state to: Screen On", COLOR_BLUE); - break; - } - - m_state.store(after_state, std::memory_order_release); - - if (before_state != after_state){ - notify_listeners(after_state); - } - } - - m_cv.wait(lg); - } - } - -private: - size_t m_screen_on_requests = 0; - size_t m_no_sleep_requests = 0; - - bool m_stopping; - std::condition_variable m_cv; - std::thread m_thread; -}; - - -SystemSleepController& SystemSleepController::instance(){ - static WindowsSleepController controller; - return controller; -} - - - - - - -} +/* OS Sleep (Windows) + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#include +#include +#include +#include "Common/Qt/Redispatch.h" +#include "CommonFramework/Logging/Logger.h" +#include "SystemSleep.h" + +namespace PokemonAutomation{ + + +class WindowsSleepController : public SystemSleepController{ +public: + virtual ~WindowsSleepController(){ + { + std::lock_guard lg(m_lock); + m_stopping = true; + m_cv.notify_all(); + } + m_thread.join(); + if (m_state.load(std::memory_order_relaxed) != SleepSuppress::NONE){ + global_logger_tagged().log("Destroying WindowsSleepController with active requests...", COLOR_RED); + } + } + WindowsSleepController() + : m_screen_on_requests(0) + , m_no_sleep_requests(0) + , m_stopping(false) + , m_thread(&WindowsSleepController::thread_loop, this) + {} + + virtual void push_screen_on() override{ + std::lock_guard lg(m_lock); + m_screen_on_requests++; + m_cv.notify_all(); + } + virtual void pop_screen_on() override{ + std::lock_guard lg(m_lock); + m_screen_on_requests--; + m_cv.notify_all(); + } + virtual void push_no_sleep() override{ + std::lock_guard lg(m_lock); + m_no_sleep_requests++; + m_cv.notify_all(); + } + virtual void pop_no_sleep() override{ + std::lock_guard lg(m_lock); + m_no_sleep_requests--; + m_cv.notify_all(); + } + +private: + void thread_loop(){ + // SetThreadExecutionState(ES_CONTINUOUS) only lasts as long as the + // thread is alive. So we use our own thread. + while (true){ + std::unique_lock lg(m_lock); + if (m_stopping){ + return; + } + + SleepSuppress before_state = m_state.load(std::memory_order_relaxed); + SleepSuppress after_state = SleepSuppress::NONE; + + EXECUTION_STATE flags = ES_CONTINUOUS; + if (m_no_sleep_requests > 0){ + flags |= ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED; + after_state = SleepSuppress::NO_SLEEP; + } + if (m_screen_on_requests > 0){ + flags |= ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED; + after_state = SleepSuppress::SCREEN_ON; + } + EXECUTION_STATE ret = SetThreadExecutionState(flags); + if (ret == 0){ + global_logger_tagged().log("Unable to set system sleep state.", COLOR_RED); + }else{ + switch (after_state){ + case SleepSuppress::NONE: + global_logger_tagged().log("Setting sleep state to: None", COLOR_BLUE); + break; + case SleepSuppress::NO_SLEEP: + global_logger_tagged().log("Setting sleep state to: No Sleep", COLOR_BLUE); + break; + case SleepSuppress::SCREEN_ON: + global_logger_tagged().log("Setting sleep state to: Screen On", COLOR_BLUE); + break; + } + + m_state.store(after_state, std::memory_order_release); + + if (before_state != after_state){ + notify_listeners(after_state); + } + } + + m_cv.wait(lg); + } + } + +private: + size_t m_screen_on_requests = 0; + size_t m_no_sleep_requests = 0; + + bool m_stopping; + std::condition_variable m_cv; + std::thread m_thread; +}; + + +SystemSleepController& SystemSleepController::instance(){ + static WindowsSleepController controller; + return controller; +} + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/ErrorReports/ErrorReports.cpp b/SerialPrograms/Source/CommonFramework/ErrorReports/ErrorReports.cpp index a91188b960..f386cec5f1 100644 --- a/SerialPrograms/Source/CommonFramework/ErrorReports/ErrorReports.cpp +++ b/SerialPrograms/Source/CommonFramework/ErrorReports/ErrorReports.cpp @@ -1,428 +1,432 @@ -/* Error Reports - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/GlobalServices.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/Environment/Environment.h" -#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" -#include "CommonFramework/Recording/StreamHistorySession.h" -#include "ProgramDumper.h" -#include "ErrorReports.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -const std::string& ERROR_LOGS_NAME = "Logs.log"; -const std::string& ERROR_DUMP_NAME = "Minidump.dmp"; -const std::string& ERROR_PATH_UNSENT = "ErrorReportsLocal"; -const std::string& ERROR_PATH_SENT = "ErrorReportsSent"; - - - -ErrorReportOption::ErrorReportOption() - : GroupOption( - "Error Reports", - LockMode::UNLOCK_WHILE_RUNNING, - GroupOption::EnableMode::ALWAYS_ENABLED, true - ) - , DESCRIPTION( - "Send error reports to the " + PROGRAM_NAME + " server to help them resolve issues and improve the program." - ) - , SEND_MODE( - "When to Send Error Reports:", - { - {ErrorReportSendMode::SEND_AUTOMATICALLY, "automatic", "Send automatically."}, - {ErrorReportSendMode::PROMPT_WHEN_CONVENIENT, "prompt", "Prompt when convenient."}, - {ErrorReportSendMode::NEVER_SEND_ANYTHING, "never", "Never send error reports."}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - IS_BETA_VERSION - ? ErrorReportSendMode::SEND_AUTOMATICALLY - : ErrorReportSendMode::PROMPT_WHEN_CONVENIENT - ) - , SCREENSHOT( - "Include Screenshots:", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , VIDEO( - "Include Video:
Include a video leading up to the error. (if available)", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , LOGS( - "Include Logs:
Include the recent log leading up to the error.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , DUMPS( - "Include Dumps:
Include stack-trace and related information.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , FILES( - "Include Other Files:
Include other files that may be helpful for the developers.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) -{ - PA_ADD_STATIC(DESCRIPTION); - PA_ADD_OPTION(SEND_MODE); - PA_ADD_OPTION(SCREENSHOT); - PA_ADD_OPTION(VIDEO); - PA_ADD_OPTION(LOGS); - PA_ADD_OPTION(DUMPS); - if (PreloadSettings::instance().DEVELOPER_MODE){ - PA_ADD_OPTION(FILES); - } -} - - -SendableErrorReport::SendableErrorReport() - : m_timestamp(now_to_filestring()) - , m_directory(ERROR_PATH_UNSENT + "/" + m_timestamp + "/") - , m_processor(get_processor_name()) - , m_program(PreloadSettings::instance().DEVELOPER_MODE - ? PROGRAM_NAME + " (" + PROGRAM_VERSION + "-dev)" - : PROGRAM_NAME + " (" + PROGRAM_VERSION + ")" - ) - , m_program_runtime_millis(0) - , m_dump_name(ERROR_DUMP_NAME) -{ - QDir().mkpath(QString::fromStdString(m_directory)); -} -SendableErrorReport::SendableErrorReport( - Logger* logger, - const ProgramInfo& info, - std::string title, - std::vector> messages, - const ImageViewRGB32& image, - const StreamHistorySession* stream_history -) - : SendableErrorReport() -{ - if (logger){ - logger->log("Compiling Error Report..."); - }else{ - std::cout << "Compiling Error Report..." << std::endl; - } - m_program_id = info.program_id; - if (info.start_time != WallClock::min()){ - m_program_runtime_millis = std::chrono::duration_cast(current_time() - info.start_time).count(); - } - m_title = std::move(title); - m_messages = std::move(messages); - m_image = image; - { - std::string log; - for (const std::string& line : global_logger_raw().get_last()){ - log += line; - log += "\r\n"; - } - QFile file(QString::fromStdString(m_directory + ERROR_LOGS_NAME)); - bool exists = file.exists(); - file.open(QIODevice::WriteOnly); - if (!exists){ - std::string bom = "\xef\xbb\xbf"; - file.write(bom.c_str(), bom.size()); - } - file.write(log.c_str()); - file.flush(); - m_logs_name = ERROR_LOGS_NAME; - } - if (stream_history){ - if (stream_history->save(m_directory + "Video.mp4")){ - m_video_name = "Video.mp4"; - } - } - if (program_dump(logger, m_directory + ERROR_DUMP_NAME)){ - m_dump_name = ERROR_DUMP_NAME; - } -} - -SendableErrorReport::SendableErrorReport(std::string directory) - : m_directory(std::move(directory)) -{ - if (m_directory.back() != '/'){ - m_directory += '/'; - } - - JsonValue json = load_json_file(m_directory + "Report.json"); - const JsonObject& obj = json.to_object_throw(); - m_timestamp = obj.get_string_throw("Timestamp"); - - // If we error from this point on, we'll just move it to the sent folder. - try{ - m_processor = obj.get_string_throw("Processor"); - m_program = obj.get_string_throw("Program"); - m_program_id = obj.get_string_throw("ProgramID"); - m_program_runtime_millis = obj.get_integer_throw("ElapsedTimeMillis"); - m_title = obj.get_string_throw("Title"); - { - const JsonArray& messages = obj.get_array_throw("Messages"); - for (const JsonValue& message : messages){ - const JsonArray& item = message.to_array_throw(); - if (item.size() != 2){ - throw ParseException("Expected 2 values for message."); - } - m_messages.emplace_back( - item[0].to_string_throw(), - item[1].to_string_throw() - ); - } - } - { - const std::string* image_name = obj.get_string("Screenshot"); - if (image_name){ - try{ - m_image_owner = ImageRGB32(m_directory + *image_name); - m_image = m_image_owner; - }catch (FileException&){} - } - } - { - const std::string* video_name = obj.get_string("Video"); - if (video_name){ - m_video_name = *video_name; - } - } - { - const std::string* dump_name = obj.get_string("Dump"); - if (dump_name){ - m_dump_name = *dump_name; - } - } - { - const std::string* logs_name = obj.get_string("Logs"); - if (logs_name){ - m_logs_name = *logs_name; - } - } - { - const JsonArray& files = obj.get_array_throw("Files"); - for (const JsonValue& file : files){ - m_files.emplace_back(file.to_string_throw()); - } - } - }catch (...){ - move_to_sent(); - throw; - } -} -void SendableErrorReport::add_file(std::string filename){ - m_files.emplace_back(std::move(filename)); -} - -void SendableErrorReport::save(Logger* logger) const{ - if (logger){ - logger->log("Saving Error Report..."); - }else{ - std::cout << "Saving Error Report..." << std::endl; - } - - JsonObject report; - - report["Timestamp"] = m_timestamp; - report["Processor"] = m_processor; - report["Program"] = m_program; - report["ProgramID"] = m_program_id; - report["ElapsedTimeMillis"] = m_program_runtime_millis; - report["Title"] = m_title; - { - JsonArray messages; - for (const std::pair& item : m_messages){ - JsonArray array; - array.push_back(item.first); - array.push_back(item.second); - messages.push_back(std::move(array)); - } - report["Messages"] = std::move(messages); - } - if (m_image){ - if (m_image.save(m_directory + "Screenshot.png")){ - report["Screenshot"] = "Screenshot.png"; - } - } - if (!m_video_name.empty()){ - report["Video"] = m_video_name; - } - if (!m_dump_name.empty()){ - report["Dump"] = m_dump_name; - } - if (!m_logs_name.empty()){ - report["Logs"] = m_logs_name; - } - - JsonArray array; - for (const std::string& file : m_files){ - array.push_back(file); - } - report["Files"] = std::move(array); - - report.dump(m_directory + "Report.json"); -} - -void SendableErrorReport::move_to_sent(){ -// cout << "move_to_sent()" << endl; - QDir().mkdir(QString::fromStdString(ERROR_PATH_SENT)); - - std::string new_directory = ERROR_PATH_SENT + "/" + m_timestamp + "/"; -// cout << "old: " << m_directory << endl; -// cout << "new: " << new_directory << endl; - bool success = QDir().rename( - QString::fromStdString(m_directory), - QString::fromStdString(new_directory) - ); - if (success){ - global_logger_tagged().log("Moved error report " + m_timestamp + "."); - }else{ - global_logger_tagged().log("Unable to move error report " + m_timestamp + ".", COLOR_RED); - } - m_directory = std::move(new_directory); -} - - -std::vector SendableErrorReport::get_pending_reports(){ - std::vector ret; - QDir dir(QString::fromStdString(ERROR_PATH_UNSENT)); - dir.setFilter(QDir::Filter::AllDirs); - QFileInfoList list = dir.entryInfoList(); - for (const auto& item : list){ - std::string path = item.filePath().toStdString(); - if (path.back() == '.'){ - continue; - } - ret.emplace_back(std::move(path)); - } - return ret; -} - -#ifndef PA_OFFICIAL -void SendableErrorReport::send(Logger& logger, std::shared_ptr report){} -#endif - - - -// Send all the reports. This function will return early and all the reports -// will be sent asynchronously in the background. -void send_reports(Logger& logger, const std::vector& reports){ - for (const std::string& path : reports){ - try{ -// static int c = 0; -// cout << "Sending... " << c++ << endl; - // std:::shared_ptr because it needs to take ownership for - // destruction at a later time. - SendableErrorReport::send(logger, std::make_shared(path)); - }catch (Exception& e){ - logger.log("Unable to send report: " + path + ", Message: " + e.to_str(), COLOR_RED); - }catch (...){ - logger.log("Unable to send report: " + path, COLOR_RED); - } - } -} -std::unique_ptr send_all_unsent_reports(Logger& logger, bool allow_prompt){ -#ifdef PA_OFFICIAL - ErrorReportSendMode mode = GlobalSettings::instance().ERROR_REPORTS->SEND_MODE; - if (mode == ErrorReportSendMode::NEVER_SEND_ANYTHING){ - return nullptr; - } - - std::vector reports = SendableErrorReport::get_pending_reports(); - global_logger_tagged().log("Found " + std::to_string(reports.size()) + " unsent error reports.", COLOR_PURPLE); - - if (reports.empty()){ - return nullptr; - } - - if (mode == ErrorReportSendMode::PROMPT_WHEN_CONVENIENT){ - if (!allow_prompt){ - return nullptr; - } - QMessageBox box; - QMessageBox::StandardButton button = box.information( - nullptr, - "Error Reporting", - QString::fromStdString( - (reports.size() == 1 - ? "There is " + tostr_u_commas(reports.size()) + " error report.

" - "Would you like to help make this program better by sending it to the developers?

" - : "There are " + tostr_u_commas(reports.size()) + " error reports.

" - "Would you like to help make this program better by sending them to the developers?

" - ) + - make_text_url(ERROR_PATH_UNSENT, "View unsent error reports.")// + "

" -// "(You can change )" - ), - QMessageBox::Yes | QMessageBox::No, - QMessageBox::StandardButton::Yes - ); - if (button != QMessageBox::StandardButton::Yes){ - return nullptr; - } - } - - global_logger_tagged().log("Attempting to send " + std::to_string(reports.size()) + " error reports.", COLOR_PURPLE); - - return global_async_dispatcher().dispatch([reports = std::move(reports)]{ - send_reports(global_logger_tagged(), reports); - }); -#else - return nullptr; -#endif -} - -void report_error( - Logger* logger, - const ProgramInfo& info, - std::string title, - std::vector> messages, - const ImageViewRGB32& image, - const StreamHistorySession* stream_history, - const std::vector& files -){ - if (logger == nullptr){ - logger = &global_logger_tagged(); - } - - { - SendableErrorReport report( - logger, - info, - std::move(title), - std::move(messages), - image, - stream_history - ); - - std::vector full_file_paths; - for (const std::string& file: files){ - full_file_paths.emplace_back(report.directory() + file); - } - - report.save(logger); - } - - send_all_unsent_reports(*logger, false); -} - - - - -} +/* Error Reports + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Common/Cpp/Concurrency/AsyncDispatcher.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/GlobalServices.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/Environment/Environment.h" +#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" +#include "CommonFramework/Recording/StreamHistorySession.h" +#include "ProgramDumper.h" +#include "ErrorReports.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +const std::string& ERROR_LOGS_NAME = "Logs.log"; +const std::string& ERROR_DUMP_NAME = "Minidump.dmp"; +const std::string& ERROR_PATH_UNSENT = "ErrorReportsLocal"; +const std::string& ERROR_PATH_SENT = "ErrorReportsSent"; + + + +ErrorReportOption::ErrorReportOption() + : GroupOption( + "Error Reports", + LockMode::UNLOCK_WHILE_RUNNING, + GroupOption::EnableMode::ALWAYS_ENABLED, true + ) + , DESCRIPTION( + "Send error reports to the " + PROGRAM_NAME + " server to help them resolve issues and improve the program." + ) + , SEND_MODE( + "When to Send Error Reports:", + { + {ErrorReportSendMode::SEND_AUTOMATICALLY, "automatic", "Send automatically."}, + {ErrorReportSendMode::PROMPT_WHEN_CONVENIENT, "prompt", "Prompt when convenient."}, + {ErrorReportSendMode::NEVER_SEND_ANYTHING, "never", "Never send error reports."}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + IS_BETA_VERSION + ? ErrorReportSendMode::SEND_AUTOMATICALLY + : ErrorReportSendMode::PROMPT_WHEN_CONVENIENT + ) + , SCREENSHOT( + "Include Screenshots:", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , VIDEO( + "Include Video:
Include a video leading up to the error. (if available)", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , LOGS( + "Include Logs:
Include the recent log leading up to the error.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , DUMPS( + "Include Dumps:
Include stack-trace and related information.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , FILES( + "Include Other Files:
Include other files that may be helpful for the developers.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) +{ + PA_ADD_STATIC(DESCRIPTION); + PA_ADD_OPTION(SEND_MODE); + PA_ADD_OPTION(SCREENSHOT); + PA_ADD_OPTION(VIDEO); + PA_ADD_OPTION(LOGS); + PA_ADD_OPTION(DUMPS); + if (PreloadSettings::instance().DEVELOPER_MODE){ + PA_ADD_OPTION(FILES); + } +} + + +SendableErrorReport::SendableErrorReport() + : m_timestamp(now_to_filestring()) + , m_directory(ERROR_PATH_UNSENT + "/" + m_timestamp + "/") + , m_processor(get_processor_name()) + , m_program(PreloadSettings::instance().DEVELOPER_MODE + ? PROGRAM_NAME + " (" + PROGRAM_VERSION + "-dev)" + : PROGRAM_NAME + " (" + PROGRAM_VERSION + ")" + ) + , m_program_runtime_millis(0) + , m_dump_name(ERROR_DUMP_NAME) +{ + QDir().mkpath(QString::fromStdString(m_directory)); +} +SendableErrorReport::SendableErrorReport( + Logger* logger, + const ProgramInfo& info, + std::string title, + std::vector> messages, + const ImageViewRGB32& image, + const StreamHistorySession* stream_history +) + : SendableErrorReport() +{ + if (logger){ + logger->log("Compiling Error Report..."); + }else{ + std::cout << "Compiling Error Report..." << std::endl; + } + m_program_id = info.program_id; + if (info.start_time != WallClock::min()){ + m_program_runtime_millis = std::chrono::duration_cast(current_time() - info.start_time).count(); + } + m_title = std::move(title); + m_messages = std::move(messages); + m_image = image; + { + std::string log; + for (const std::string& line : global_logger_raw().get_last()){ + log += line; + log += "\r\n"; + } + QFile file(QString::fromStdString(m_directory + ERROR_LOGS_NAME)); + bool exists = file.exists(); + file.open(QIODevice::WriteOnly); + if (!exists){ + std::string bom = "\xef\xbb\xbf"; + file.write(bom.c_str(), bom.size()); + } + file.write(log.c_str()); + file.flush(); + m_logs_name = ERROR_LOGS_NAME; + } + if (stream_history){ + if (stream_history->save(m_directory + "Video.mp4")){ + m_video_name = "Video.mp4"; + } + } + if (program_dump(logger, m_directory + ERROR_DUMP_NAME)){ + m_dump_name = ERROR_DUMP_NAME; + } +} + +SendableErrorReport::SendableErrorReport(std::string directory) + : m_directory(std::move(directory)) +{ + if (m_directory.back() != '/'){ + m_directory += '/'; + } + + JsonValue json = load_json_file(m_directory + "Report.json"); + const JsonObject& obj = json.to_object_throw(); + m_timestamp = obj.get_string_throw("Timestamp"); + + // If we error from this point on, we'll just move it to the sent folder. + try{ + m_processor = obj.get_string_throw("Processor"); + m_program = obj.get_string_throw("Program"); + m_program_id = obj.get_string_throw("ProgramID"); + m_program_runtime_millis = obj.get_integer_throw("ElapsedTimeMillis"); + m_title = obj.get_string_throw("Title"); + { + const JsonArray& messages = obj.get_array_throw("Messages"); + for (const JsonValue& message : messages){ + const JsonArray& item = message.to_array_throw(); + if (item.size() != 2){ + throw ParseException("Expected 2 values for message."); + } + m_messages.emplace_back( + item[0].to_string_throw(), + item[1].to_string_throw() + ); + } + } + { + const std::string* image_name = obj.get_string("Screenshot"); + if (image_name){ + try{ + m_image_owner = ImageRGB32(m_directory + *image_name); + m_image = m_image_owner; + }catch (FileException&){} + } + } + { + const std::string* video_name = obj.get_string("Video"); + if (video_name){ + m_video_name = *video_name; + } + } + { + const std::string* dump_name = obj.get_string("Dump"); + if (dump_name){ + m_dump_name = *dump_name; + } + } + { + const std::string* logs_name = obj.get_string("Logs"); + if (logs_name){ + m_logs_name = *logs_name; + } + } + { + const JsonArray& files = obj.get_array_throw("Files"); + for (const JsonValue& file : files){ + m_files.emplace_back(file.to_string_throw()); + } + } + }catch (...){ + move_to_sent(); + throw; + } +} +void SendableErrorReport::add_file(std::string filename){ + m_files.emplace_back(std::move(filename)); +} + +void SendableErrorReport::save(Logger* logger) const{ + if (logger){ + logger->log("Saving Error Report..."); + }else{ + std::cout << "Saving Error Report..." << std::endl; + } + + JsonObject report; + + report["Timestamp"] = m_timestamp; + report["Processor"] = m_processor; + report["Program"] = m_program; + report["ProgramID"] = m_program_id; + report["ElapsedTimeMillis"] = m_program_runtime_millis; + report["Title"] = m_title; + { + JsonArray messages; + for (const std::pair& item : m_messages){ + JsonArray array; + array.push_back(item.first); + array.push_back(item.second); + messages.push_back(std::move(array)); + } + report["Messages"] = std::move(messages); + } + if (m_image){ + // 4k .png images are too big for current Discord limits. + std::string extension = m_image.width() > 1920 + ? ".jpg" + : ".png"; + if (m_image.save(m_directory + "Screenshot" + extension)){ + report["Screenshot"] = "Screenshot" + extension; + } + } + if (!m_video_name.empty()){ + report["Video"] = m_video_name; + } + if (!m_dump_name.empty()){ + report["Dump"] = m_dump_name; + } + if (!m_logs_name.empty()){ + report["Logs"] = m_logs_name; + } + + JsonArray array; + for (const std::string& file : m_files){ + array.push_back(file); + } + report["Files"] = std::move(array); + + report.dump(m_directory + "Report.json"); +} + +void SendableErrorReport::move_to_sent(){ +// cout << "move_to_sent()" << endl; + QDir().mkdir(QString::fromStdString(ERROR_PATH_SENT)); + + std::string new_directory = ERROR_PATH_SENT + "/" + m_timestamp + "/"; +// cout << "old: " << m_directory << endl; +// cout << "new: " << new_directory << endl; + bool success = QDir().rename( + QString::fromStdString(m_directory), + QString::fromStdString(new_directory) + ); + if (success){ + global_logger_tagged().log("Moved error report " + m_timestamp + "."); + }else{ + global_logger_tagged().log("Unable to move error report " + m_timestamp + ".", COLOR_RED); + } + m_directory = std::move(new_directory); +} + + +std::vector SendableErrorReport::get_pending_reports(){ + std::vector ret; + QDir dir(QString::fromStdString(ERROR_PATH_UNSENT)); + dir.setFilter(QDir::Filter::AllDirs); + QFileInfoList list = dir.entryInfoList(); + for (const auto& item : list){ + std::string path = item.filePath().toStdString(); + if (path.back() == '.'){ + continue; + } + ret.emplace_back(std::move(path)); + } + return ret; +} + +#ifndef PA_OFFICIAL +void SendableErrorReport::send(Logger& logger, std::shared_ptr report){} +#endif + + + +// Send all the reports. This function will return early and all the reports +// will be sent asynchronously in the background. +void send_reports(Logger& logger, const std::vector& reports){ + for (const std::string& path : reports){ + try{ +// static int c = 0; +// cout << "Sending... " << c++ << endl; + // std:::shared_ptr because it needs to take ownership for + // destruction at a later time. + SendableErrorReport::send(logger, std::make_shared(path)); + }catch (Exception& e){ + logger.log("Unable to send report: " + path + ", Message: " + e.to_str(), COLOR_RED); + }catch (...){ + logger.log("Unable to send report: " + path, COLOR_RED); + } + } +} +std::unique_ptr send_all_unsent_reports(Logger& logger, bool allow_prompt){ +#ifdef PA_OFFICIAL + ErrorReportSendMode mode = GlobalSettings::instance().ERROR_REPORTS->SEND_MODE; + if (mode == ErrorReportSendMode::NEVER_SEND_ANYTHING){ + return nullptr; + } + + std::vector reports = SendableErrorReport::get_pending_reports(); + global_logger_tagged().log("Found " + std::to_string(reports.size()) + " unsent error reports.", COLOR_PURPLE); + + if (reports.empty()){ + return nullptr; + } + + if (mode == ErrorReportSendMode::PROMPT_WHEN_CONVENIENT){ + if (!allow_prompt){ + return nullptr; + } + QMessageBox box; + QMessageBox::StandardButton button = box.information( + nullptr, + "Error Reporting", + QString::fromStdString( + (reports.size() == 1 + ? "There is " + tostr_u_commas(reports.size()) + " error report.

" + "Would you like to help make this program better by sending it to the developers?

" + : "There are " + tostr_u_commas(reports.size()) + " error reports.

" + "Would you like to help make this program better by sending them to the developers?

" + ) + + make_text_url(ERROR_PATH_UNSENT, "View unsent error reports.")// + "

" +// "(You can change )" + ), + QMessageBox::Yes | QMessageBox::No, + QMessageBox::StandardButton::Yes + ); + if (button != QMessageBox::StandardButton::Yes){ + return nullptr; + } + } + + global_logger_tagged().log("Attempting to send " + std::to_string(reports.size()) + " error reports.", COLOR_PURPLE); + + return global_async_dispatcher().dispatch([reports = std::move(reports)]{ + send_reports(global_logger_tagged(), reports); + }); +#else + return nullptr; +#endif +} + +void report_error( + Logger* logger, + const ProgramInfo& info, + std::string title, + std::vector> messages, + const ImageViewRGB32& image, + const StreamHistorySession* stream_history, + const std::vector& files +){ + if (logger == nullptr){ + logger = &global_logger_tagged(); + } + + { + SendableErrorReport report( + logger, + info, + std::move(title), + std::move(messages), + image, + stream_history + ); + + std::vector full_file_paths; + for (const std::string& file: files){ + full_file_paths.emplace_back(report.directory() + file); + } + + report.save(logger); + } + + send_all_unsent_reports(*logger, false); +} + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/ErrorReports/ErrorReports.h b/SerialPrograms/Source/CommonFramework/ErrorReports/ErrorReports.h index 4814ff00fd..0988eb80e1 100644 --- a/SerialPrograms/Source/CommonFramework/ErrorReports/ErrorReports.h +++ b/SerialPrograms/Source/CommonFramework/ErrorReports/ErrorReports.h @@ -1,126 +1,126 @@ -/* Error Reports - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ErrorReports_H -#define PokemonAutomation_ErrorReports_H - -#include -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/Notifications/ProgramInfo.h" - -namespace PokemonAutomation{ - - -class AsyncTask; -class StreamHistorySession; - - -extern const std::string& ERROR_LOGS_NAME; -extern const std::string& ERROR_DUMP_NAME; -extern const std::string& ERROR_PATH_UNSENT; -extern const std::string& ERROR_PATH_SENT; - - - -enum class ErrorReportSendMode{ - SEND_AUTOMATICALLY, - PROMPT_WHEN_CONVENIENT, - NEVER_SEND_ANYTHING, -}; - -class ErrorReportOption : public GroupOption{ -public: - ErrorReportOption(); - - StaticTextOption DESCRIPTION; - - EnumDropdownOption SEND_MODE; - - BooleanCheckBoxOption SCREENSHOT; - BooleanCheckBoxOption VIDEO; - BooleanCheckBoxOption LOGS; - BooleanCheckBoxOption DUMPS; - BooleanCheckBoxOption FILES; -}; - - - -class SendableErrorReport{ -public: - SendableErrorReport(); - - // Create new report from current stack. - SendableErrorReport( - Logger* logger, - const ProgramInfo& info = ProgramInfo(), - std::string title = "", - std::vector> messages = {}, - const ImageViewRGB32& image = ImageViewRGB32(), - const StreamHistorySession* stream_history = nullptr - ); - - // Deserialize from existing report. - SendableErrorReport(std::string directory); - - const std::string& directory() const{ - return m_directory; - } - - void add_file(std::string filename); - - void save(Logger* logger) const; - void move_to_sent(); - - static std::vector get_pending_reports(); - static void send(Logger& logger, std::shared_ptr report); - -private: - std::string m_timestamp; - std::string m_directory; - std::string m_processor; - std::string m_program; - std::string m_program_id; - uint64_t m_program_runtime_millis = 0; - std::string m_title; - std::vector> m_messages; - ImageRGB32 m_image_owner; - ImageViewRGB32 m_image; - std::string m_logs_name; - std::string m_video_name; - std::string m_dump_name; - std::vector m_files; -}; - - -void send_reports(Logger& logger, const std::vector& reports); -std::unique_ptr send_all_unsent_reports(Logger& logger, bool allow_prompt); - - -void report_error( - Logger* logger = nullptr, - const ProgramInfo& info = ProgramInfo(), - std::string title = "", - std::vector> messages = {}, - const ImageViewRGB32& image = ImageViewRGB32(), - const StreamHistorySession* stream_history = nullptr, - const std::vector& files = {} -); - - - - - - - -} - -#endif +/* Error Reports + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ErrorReports_H +#define PokemonAutomation_ErrorReports_H + +#include +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/Notifications/ProgramInfo.h" + +namespace PokemonAutomation{ + + +class AsyncTask; +class StreamHistorySession; + + +extern const std::string& ERROR_LOGS_NAME; +extern const std::string& ERROR_DUMP_NAME; +extern const std::string& ERROR_PATH_UNSENT; +extern const std::string& ERROR_PATH_SENT; + + + +enum class ErrorReportSendMode{ + SEND_AUTOMATICALLY, + PROMPT_WHEN_CONVENIENT, + NEVER_SEND_ANYTHING, +}; + +class ErrorReportOption : public GroupOption{ +public: + ErrorReportOption(); + + StaticTextOption DESCRIPTION; + + EnumDropdownOption SEND_MODE; + + BooleanCheckBoxOption SCREENSHOT; + BooleanCheckBoxOption VIDEO; + BooleanCheckBoxOption LOGS; + BooleanCheckBoxOption DUMPS; + BooleanCheckBoxOption FILES; +}; + + + +class SendableErrorReport{ +public: + SendableErrorReport(); + + // Create new report from current stack. + SendableErrorReport( + Logger* logger, + const ProgramInfo& info = ProgramInfo(), + std::string title = "", + std::vector> messages = {}, + const ImageViewRGB32& image = ImageViewRGB32(), + const StreamHistorySession* stream_history = nullptr + ); + + // Deserialize from existing report. + SendableErrorReport(std::string directory); + + const std::string& directory() const{ + return m_directory; + } + + void add_file(std::string filename); + + void save(Logger* logger) const; + void move_to_sent(); + + static std::vector get_pending_reports(); + static void send(Logger& logger, std::shared_ptr report); + +private: + std::string m_timestamp; + std::string m_directory; + std::string m_processor; + std::string m_program; + std::string m_program_id; + uint64_t m_program_runtime_millis = 0; + std::string m_title; + std::vector> m_messages; + ImageRGB32 m_image_owner; + ImageViewRGB32 m_image; + std::string m_logs_name; + std::string m_video_name; + std::string m_dump_name; + std::vector m_files; +}; + + +void send_reports(Logger& logger, const std::vector& reports); +std::unique_ptr send_all_unsent_reports(Logger& logger, bool allow_prompt); + + +void report_error( + Logger* logger = nullptr, + const ProgramInfo& info = ProgramInfo(), + std::string title = "", + std::vector> messages = {}, + const ImageViewRGB32& image = ImageViewRGB32(), + const StreamHistorySession* stream_history = nullptr, + const std::vector& files = {} +); + + + + + + + +} + +#endif diff --git a/SerialPrograms/Source/CommonFramework/ErrorReports/ProgramDumper.cpp b/SerialPrograms/Source/CommonFramework/ErrorReports/ProgramDumper.cpp index fcfab9910f..ccafa57691 100644 --- a/SerialPrograms/Source/CommonFramework/ErrorReports/ProgramDumper.cpp +++ b/SerialPrograms/Source/CommonFramework/ErrorReports/ProgramDumper.cpp @@ -1,23 +1,23 @@ -/* Program Dumper - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Compiler.h" -#include "ProgramDumper.h" - - -#if _WIN32 && _MSC_VER -#include "ProgramDumper_Windows.tpp" - -#else -namespace PokemonAutomation{ - void setup_crash_handler(){ - // Not supported - } - bool program_dump(Logger* logger, const std::string& filename){ - return false; - } -} -#endif +/* Program Dumper + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Compiler.h" +#include "ProgramDumper.h" + + +#if _WIN32 && _MSC_VER +#include "ProgramDumper_Windows.tpp" + +#else +namespace PokemonAutomation{ + void setup_crash_handler(){ + // Not supported + } + bool program_dump(Logger* logger, const std::string& filename){ + return false; + } +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/ErrorReports/ProgramDumper.h b/SerialPrograms/Source/CommonFramework/ErrorReports/ProgramDumper.h index 8d2604b3c1..a1e5a595d8 100644 --- a/SerialPrograms/Source/CommonFramework/ErrorReports/ProgramDumper.h +++ b/SerialPrograms/Source/CommonFramework/ErrorReports/ProgramDumper.h @@ -1,21 +1,21 @@ -/* Program Dumper - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ProgramDumper_H -#define PokemonAutomation_ProgramDumper_H - -#include -#include "Common/Cpp/AbstractLogger.h" - -namespace PokemonAutomation{ - - -void setup_crash_handler(); -bool program_dump(Logger* logger, const std::string& filename); - - -} -#endif +/* Program Dumper + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ProgramDumper_H +#define PokemonAutomation_ProgramDumper_H + +#include +#include "Common/Cpp/AbstractLogger.h" + +namespace PokemonAutomation{ + + +void setup_crash_handler(); +bool program_dump(Logger* logger, const std::string& filename); + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/ErrorReports/ProgramDumper_Windows.tpp b/SerialPrograms/Source/CommonFramework/ErrorReports/ProgramDumper_Windows.tpp index 8a668a520a..211c9de148 100644 --- a/SerialPrograms/Source/CommonFramework/ErrorReports/ProgramDumper_Windows.tpp +++ b/SerialPrograms/Source/CommonFramework/ErrorReports/ProgramDumper_Windows.tpp @@ -1,132 +1,132 @@ -/* Program Dumper (Windows) - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#pragma comment (lib, "Dbghelp.lib") -#include -#include -#include -#include -#include "Common/Cpp/Unicode.h" -#include "Common/Cpp/PrettyPrint.h" -#include "ErrorReports.h" -#include "ProgramDumper.h" - -namespace PokemonAutomation{ - - -class HandleHolder{ -public: - HandleHolder(const HandleHolder&) = delete; - void operator=(const HandleHolder&) = delete; - ~HandleHolder(){ - CloseHandle(m_handle); - } - HandleHolder(HANDLE handle) - : m_handle(handle) - {} - operator bool() const{ - return m_handle != INVALID_HANDLE_VALUE; - } - operator HANDLE() const{ - return m_handle; - } - -private: - HANDLE m_handle; -}; - - -bool program_dump(Logger* logger, const std::string& filename, EXCEPTION_POINTERS* e){ - HandleHolder handle = CreateFileW( - utf8_to_wstr(filename).c_str(), - FILE_WRITE_ACCESS, - FILE_SHARE_READ, - nullptr, - OPEN_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - 0 - ); - if (!handle){ - DWORD error = GetLastError(); - if (logger){ - logger->log("Unable to create dump file: " + std::to_string(error), COLOR_RED); - }else{ - std::cout << "Unable to create dump file: " << error << std::endl; - } - return false; - } - - int ret; - if (e != nullptr){ - MINIDUMP_EXCEPTION_INFORMATION exceptionInfo; - exceptionInfo.ThreadId = GetCurrentThreadId(); - exceptionInfo.ExceptionPointers = e; - exceptionInfo.ClientPointers = FALSE; - ret = MiniDumpWriteDump( - GetCurrentProcess(), - GetCurrentProcessId(), - handle, - MiniDumpNormal, - &exceptionInfo, - nullptr, - nullptr - ); - }else{ - ret = MiniDumpWriteDump( - GetCurrentProcess(), - GetCurrentProcessId(), - handle, - MiniDumpNormal, - nullptr, - nullptr, - nullptr - ); - } - if (!ret){ - DWORD error = GetLastError(); - if (logger){ - logger->log("Unable to create dump file: " + std::to_string(error), COLOR_RED); - }else{ - std::cout << "Unable to create dump file: " << error << std::endl; - } - return false; - } - - return true; -} -bool program_dump(Logger* logger, const std::string& filename){ - return program_dump(logger, filename, nullptr); -} - - - -long WINAPI crash_handler(EXCEPTION_POINTERS* e){ - static bool handled = false; - if (handled){ - return EXCEPTION_CONTINUE_SEARCH; - } - handled = true; - - SendableErrorReport report; - -// _wmkdir(utf8_to_wstr(ERROR_PATH_UNSENT).c_str()); - program_dump(nullptr, report.directory() + ERROR_DUMP_NAME, e); - report.save(nullptr); - - Sleep(1000); - - return EXCEPTION_CONTINUE_SEARCH; -} - - -void setup_crash_handler(){ -// AddVectoredExceptionHandler(0, crash_handler); - SetUnhandledExceptionFilter(crash_handler); -} - - - -} +/* Program Dumper (Windows) + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#pragma comment (lib, "Dbghelp.lib") +#include +#include +#include +#include +#include "Common/Cpp/Unicode.h" +#include "Common/Cpp/PrettyPrint.h" +#include "ErrorReports.h" +#include "ProgramDumper.h" + +namespace PokemonAutomation{ + + +class HandleHolder{ +public: + HandleHolder(const HandleHolder&) = delete; + void operator=(const HandleHolder&) = delete; + ~HandleHolder(){ + CloseHandle(m_handle); + } + HandleHolder(HANDLE handle) + : m_handle(handle) + {} + operator bool() const{ + return m_handle != INVALID_HANDLE_VALUE; + } + operator HANDLE() const{ + return m_handle; + } + +private: + HANDLE m_handle; +}; + + +bool program_dump(Logger* logger, const std::string& filename, EXCEPTION_POINTERS* e){ + HandleHolder handle = CreateFileW( + utf8_to_wstr(filename).c_str(), + FILE_WRITE_ACCESS, + FILE_SHARE_READ, + nullptr, + OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, + 0 + ); + if (!handle){ + DWORD error = GetLastError(); + if (logger){ + logger->log("Unable to create dump file: " + std::to_string(error), COLOR_RED); + }else{ + std::cout << "Unable to create dump file: " << error << std::endl; + } + return false; + } + + int ret; + if (e != nullptr){ + MINIDUMP_EXCEPTION_INFORMATION exceptionInfo; + exceptionInfo.ThreadId = GetCurrentThreadId(); + exceptionInfo.ExceptionPointers = e; + exceptionInfo.ClientPointers = FALSE; + ret = MiniDumpWriteDump( + GetCurrentProcess(), + GetCurrentProcessId(), + handle, + MiniDumpNormal, + &exceptionInfo, + nullptr, + nullptr + ); + }else{ + ret = MiniDumpWriteDump( + GetCurrentProcess(), + GetCurrentProcessId(), + handle, + MiniDumpNormal, + nullptr, + nullptr, + nullptr + ); + } + if (!ret){ + DWORD error = GetLastError(); + if (logger){ + logger->log("Unable to create dump file: " + std::to_string(error), COLOR_RED); + }else{ + std::cout << "Unable to create dump file: " << error << std::endl; + } + return false; + } + + return true; +} +bool program_dump(Logger* logger, const std::string& filename){ + return program_dump(logger, filename, nullptr); +} + + + +long WINAPI crash_handler(EXCEPTION_POINTERS* e){ + static bool handled = false; + if (handled){ + return EXCEPTION_CONTINUE_SEARCH; + } + handled = true; + + SendableErrorReport report; + +// _wmkdir(utf8_to_wstr(ERROR_PATH_UNSENT).c_str()); + program_dump(nullptr, report.directory() + ERROR_DUMP_NAME, e); + report.save(nullptr); + + Sleep(1000); + + return EXCEPTION_CONTINUE_SEARCH; +} + + +void setup_crash_handler(){ +// AddVectoredExceptionHandler(0, crash_handler); + SetUnhandledExceptionFilter(crash_handler); +} + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Exceptions/ScreenshotException.cpp b/SerialPrograms/Source/CommonFramework/Exceptions/ScreenshotException.cpp index 29c629b014..eb85bfe12b 100644 --- a/SerialPrograms/Source/CommonFramework/Exceptions/ScreenshotException.cpp +++ b/SerialPrograms/Source/CommonFramework/Exceptions/ScreenshotException.cpp @@ -73,13 +73,16 @@ void ScreenshotException::add_stream_if_needed(VideoStream& stream){ } } -ImageViewRGB32 ScreenshotException::screenshot() const{ +ImageViewRGB32 ScreenshotException::screenshot_view() const{ if (m_screenshot){ return *m_screenshot; }else{ return ImageViewRGB32(); } } +std::shared_ptr ScreenshotException::screenshot() const{ + return m_screenshot; +} void ScreenshotException::send_notification(ProgramEnvironment& env, EventNotificationOption& notification) const{ @@ -94,7 +97,7 @@ void ScreenshotException::send_notification(ProgramEnvironment& env, EventNotifi env.program_info(), name(), embeds, - screenshot(), + screenshot_view(), m_stream ? &m_stream->history() : nullptr ); } @@ -104,7 +107,7 @@ void ScreenshotException::send_notification(ProgramEnvironment& env, EventNotifi color(), name(), std::move(embeds), "", - screenshot() + screenshot_view() ); } diff --git a/SerialPrograms/Source/CommonFramework/Exceptions/ScreenshotException.h b/SerialPrograms/Source/CommonFramework/Exceptions/ScreenshotException.h index 0a654cff67..e10a8c313f 100644 --- a/SerialPrograms/Source/CommonFramework/Exceptions/ScreenshotException.h +++ b/SerialPrograms/Source/CommonFramework/Exceptions/ScreenshotException.h @@ -67,7 +67,8 @@ class ScreenshotException : public Exception{ public: // virtual const char* name() const override{ return "ScreenshotException"; } virtual std::string message() const override{ return m_message; } - ImageViewRGB32 screenshot() const; + ImageViewRGB32 screenshot_view() const; + std::shared_ptr screenshot() const; virtual Color color() const{ return COLOR_RED; } virtual void send_notification(ProgramEnvironment& env, EventNotificationOption& notification) const; diff --git a/SerialPrograms/Source/CommonFramework/Exceptions/UnexpectedBattleException.h b/SerialPrograms/Source/CommonFramework/Exceptions/UnexpectedBattleException.h index 7d0e9757b1..30e609c5c1 100644 --- a/SerialPrograms/Source/CommonFramework/Exceptions/UnexpectedBattleException.h +++ b/SerialPrograms/Source/CommonFramework/Exceptions/UnexpectedBattleException.h @@ -1,31 +1,31 @@ -/* Unexpected Battle Exception - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_UnexpectedBattleException_H -#define PokemonAutomation_UnexpectedBattleException_H - -#include "ScreenshotException.h" - -namespace PokemonAutomation{ - -class FatalProgramException; - - -// Thrown by subroutines if caught in an wild battle in-game unexpectedly. -// These include recoverable errors which can be consumed by the program. -class UnexpectedBattleException : public ScreenshotException{ -public: - using ScreenshotException::ScreenshotException; - - virtual const char* name() const override{ return "UnexpectedBattleException"; } -}; - - - - - -} -#endif +/* Unexpected Battle Exception + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_UnexpectedBattleException_H +#define PokemonAutomation_UnexpectedBattleException_H + +#include "ScreenshotException.h" + +namespace PokemonAutomation{ + +class FatalProgramException; + + +// Thrown by subroutines if caught in an wild battle in-game unexpectedly. +// These include recoverable errors which can be consumed by the program. +class UnexpectedBattleException : public ScreenshotException{ +public: + using ScreenshotException::ScreenshotException; + + virtual const char* name() const override{ return "UnexpectedBattleException"; } +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/GlobalSettingsPanel.cpp b/SerialPrograms/Source/CommonFramework/GlobalSettingsPanel.cpp index 1a26fe6cfd..2aeed75bcc 100644 --- a/SerialPrograms/Source/CommonFramework/GlobalSettingsPanel.cpp +++ b/SerialPrograms/Source/CommonFramework/GlobalSettingsPanel.cpp @@ -130,10 +130,23 @@ GlobalSettings::GlobalSettings() , THEME(CONSTRUCT_TOKEN) , WINDOW_SIZE( CONSTRUCT_TOKEN, - "Window Size:", - "Set the size of the window. Takes effect immediately.
" + "Window Size/Position:", + "Set the size/position of the window. Takes effect immediately.
" "Use this to easily set the window to a specific resolution for streaming alignment.", - 1280, 1000 + 1280, 1000, + 0, 0 + ) + , LOG_WINDOW_SIZE( + CONSTRUCT_TOKEN, + "Output Window Size/Position:", + "Set the size/position of the output window. Takes effect immediately.
", + 600, 1200, + 0, 0 + ) + , LOG_WINDOW_STARTUP( + "Open Output Window at startup:", + LockMode::UNLOCK_WHILE_RUNNING, + false ) , STREAM_HISTORY(CONSTRUCT_TOKEN) , SLEEP_SUPPRESS(CONSTRUCT_TOKEN) @@ -196,6 +209,8 @@ GlobalSettings::GlobalSettings() PA_ADD_OPTION(TEMP_FOLDER); PA_ADD_OPTION(THEME); PA_ADD_OPTION(WINDOW_SIZE); + PA_ADD_OPTION(LOG_WINDOW_SIZE); + PA_ADD_OPTION(LOG_WINDOW_STARTUP); #if (QT_VERSION_MAJOR == 6) && (QT_VERSION_MINOR >= 8) if (IS_BETA_VERSION || PreloadSettings::instance().DEVELOPER_MODE){ PA_ADD_OPTION(STREAM_HISTORY); diff --git a/SerialPrograms/Source/CommonFramework/GlobalSettingsPanel.h b/SerialPrograms/Source/CommonFramework/GlobalSettingsPanel.h index 28330ff3c8..fcec0f2a9d 100644 --- a/SerialPrograms/Source/CommonFramework/GlobalSettingsPanel.h +++ b/SerialPrograms/Source/CommonFramework/GlobalSettingsPanel.h @@ -96,6 +96,8 @@ class GlobalSettings : public BatchOption, private ConfigOption::Listener{ Pimpl THEME; Pimpl WINDOW_SIZE; + Pimpl LOG_WINDOW_SIZE; + BooleanCheckBoxOption LOG_WINDOW_STARTUP; Pimpl STREAM_HISTORY; Pimpl SLEEP_SUPPRESS; diff --git a/SerialPrograms/Source/CommonFramework/Globals.cpp b/SerialPrograms/Source/CommonFramework/Globals.cpp index 70309a3ab4..b281d3db39 100644 --- a/SerialPrograms/Source/CommonFramework/Globals.cpp +++ b/SerialPrograms/Source/CommonFramework/Globals.cpp @@ -26,7 +26,7 @@ namespace PokemonAutomation{ const bool IS_BETA_VERSION = true; const int PROGRAM_VERSION_MAJOR = 0; const int PROGRAM_VERSION_MINOR = 54; -const int PROGRAM_VERSION_PATCH = 8; +const int PROGRAM_VERSION_PATCH = 26; const std::string PROGRAM_VERSION_BASE = "v" + std::to_string(PROGRAM_VERSION_MAJOR) + diff --git a/SerialPrograms/Source/CommonFramework/ImageTools/ImageDiff.cpp b/SerialPrograms/Source/CommonFramework/ImageTools/ImageDiff.cpp index 2a4079b9a2..9f3674761f 100644 --- a/SerialPrograms/Source/CommonFramework/ImageTools/ImageDiff.cpp +++ b/SerialPrograms/Source/CommonFramework/ImageTools/ImageDiff.cpp @@ -1,115 +1,115 @@ -/* Image Diff - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Compiler.h" -#include "Common/Cpp/Exceptions.h" -#include "Kernels/ImageStats/Kernels_ImagePixelSumSqr.h" -#include "Kernels/ImageStats/Kernels_ImagePixelSumSqrDev.h" -#include "Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "ImageDiff.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace ImageMatch{ - - -FloatPixel pixel_average(const ImageViewRGB32& image, const ImageViewRGB32& alpha_mask){ - if (!image){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Dimensions"); - } - if (image.width() != alpha_mask.width() || image.height() != alpha_mask.height()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching Dimensions"); - } - Kernels::PixelSums sums; - Kernels::pixel_sum_sqr( - sums, image.width(), image.height(), - image.data(), image.bytes_per_row(), - alpha_mask.data(), alpha_mask.bytes_per_row() - ); - - FloatPixel sum((double)sums.sumR, (double)sums.sumG, (double)sums.sumB); - sum /= (double)sums.count; - return sum; -} - - - -void scale_brightness(ImageRGB32& image, const FloatPixel& multiplier){ - Kernels::scale_brightness( - image.width(), image.height(), - image.data(), image.bytes_per_row(), - (float)multiplier.r, (float)multiplier.g, (float)multiplier.b - ); -} - - - -double pixel_RMSD(const ImageViewRGB32& reference, const ImageViewRGB32& image){ - if (!image){ -// throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Dimensions"); - return 765; // Max possible deviation. - } - if (reference.width() != image.width() || reference.height() != image.height()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching Dimensions"); - } - uint64_t count = 0; - uint64_t sumsqrs = 0; - Kernels::sum_sqr_deviation( - count, sumsqrs, - reference.width(), reference.height(), - reference.data(), reference.bytes_per_row(), - image.data(), image.bytes_per_row() - ); - return std::sqrt((double)sumsqrs / (double)count); -} -double pixel_RMSD(const ImageViewRGB32& reference, const ImageViewRGB32& image, Color background){ - if (!image){ -// throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Dimensions"); - return 765; // Max possible deviation. - } - if (reference.width() != image.width() || reference.height() != image.height()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching Dimensions"); - } - uint64_t count = 0; - uint64_t sumsqrs = 0; - Kernels::sum_sqr_deviation( - count, sumsqrs, - reference.width(), reference.height(), - reference.data(), reference.bytes_per_row(), - image.data(), image.bytes_per_row(), - (uint32_t)background - ); - return std::sqrt((double)sumsqrs / (double)count); -} -double pixel_RMSD_masked(const ImageViewRGB32& reference, const ImageViewRGB32& image){ - if (!image){ -// throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Dimensions"); - return 765; // Max possible deviation. - } - if (reference.width() != image.width() || reference.height() != image.height()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching Dimensions"); - } - uint64_t count = 0; - uint64_t sumsqrs = 0; - Kernels::sum_sqr_deviation_masked( - count, sumsqrs, - reference.width(), reference.height(), - reference.data(), reference.bytes_per_row(), - image.data(), image.bytes_per_row() - ); - return std::sqrt((double)sumsqrs / (double)count); -} - - - -} -} +/* Image Diff + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Compiler.h" +#include "Common/Cpp/Exceptions.h" +#include "Kernels/ImageStats/Kernels_ImagePixelSumSqr.h" +#include "Kernels/ImageStats/Kernels_ImagePixelSumSqrDev.h" +#include "Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "ImageDiff.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace ImageMatch{ + + +FloatPixel pixel_average(const ImageViewRGB32& image, const ImageViewRGB32& alpha_mask){ + if (!image){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Dimensions"); + } + if (image.width() != alpha_mask.width() || image.height() != alpha_mask.height()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching Dimensions"); + } + Kernels::PixelSums sums; + Kernels::pixel_sum_sqr( + sums, image.width(), image.height(), + image.data(), image.bytes_per_row(), + alpha_mask.data(), alpha_mask.bytes_per_row() + ); + + FloatPixel sum((double)sums.sumR, (double)sums.sumG, (double)sums.sumB); + sum /= (double)sums.count; + return sum; +} + + + +void scale_brightness(ImageRGB32& image, const FloatPixel& multiplier){ + Kernels::scale_brightness( + image.width(), image.height(), + image.data(), image.bytes_per_row(), + (float)multiplier.r, (float)multiplier.g, (float)multiplier.b + ); +} + + + +double pixel_RMSD(const ImageViewRGB32& reference, const ImageViewRGB32& image){ + if (!image){ +// throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Dimensions"); + return 765; // Max possible deviation. + } + if (reference.width() != image.width() || reference.height() != image.height()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching Dimensions"); + } + uint64_t count = 0; + uint64_t sumsqrs = 0; + Kernels::sum_sqr_deviation( + count, sumsqrs, + reference.width(), reference.height(), + reference.data(), reference.bytes_per_row(), + image.data(), image.bytes_per_row() + ); + return std::sqrt((double)sumsqrs / (double)count); +} +double pixel_RMSD(const ImageViewRGB32& reference, const ImageViewRGB32& image, Color background){ + if (!image){ +// throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Dimensions"); + return 765; // Max possible deviation. + } + if (reference.width() != image.width() || reference.height() != image.height()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching Dimensions"); + } + uint64_t count = 0; + uint64_t sumsqrs = 0; + Kernels::sum_sqr_deviation( + count, sumsqrs, + reference.width(), reference.height(), + reference.data(), reference.bytes_per_row(), + image.data(), image.bytes_per_row(), + (uint32_t)background + ); + return std::sqrt((double)sumsqrs / (double)count); +} +double pixel_RMSD_masked(const ImageViewRGB32& reference, const ImageViewRGB32& image){ + if (!image){ +// throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Dimensions"); + return 765; // Max possible deviation. + } + if (reference.width() != image.width() || reference.height() != image.height()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching Dimensions"); + } + uint64_t count = 0; + uint64_t sumsqrs = 0; + Kernels::sum_sqr_deviation_masked( + count, sumsqrs, + reference.width(), reference.height(), + reference.data(), reference.bytes_per_row(), + image.data(), image.bytes_per_row() + ); + return std::sqrt((double)sumsqrs / (double)count); +} + + + +} +} diff --git a/SerialPrograms/Source/CommonFramework/ImageTools/ImageDiff.h b/SerialPrograms/Source/CommonFramework/ImageTools/ImageDiff.h index 299c1204f9..1bc8ad9f99 100644 --- a/SerialPrograms/Source/CommonFramework/ImageTools/ImageDiff.h +++ b/SerialPrograms/Source/CommonFramework/ImageTools/ImageDiff.h @@ -1,64 +1,64 @@ -/* Image Diff - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonFramework_ImageDiff_H -#define PokemonAutomation_CommonFramework_ImageDiff_H - -#include "CommonFramework/ImageTools/FloatPixel.h" - -namespace PokemonAutomation{ - class ImageViewRGB32; - class ImageRGB32; -namespace ImageMatch{ - - -// Compute average of all 4 components. -// - The two images must be the same dimensions. -// - The alpha channels of "reference" is used to indicate which parts to ignore. -// 0 means background. 255 means object. No other values are valid. -FloatPixel pixel_average(const ImageViewRGB32& image, const ImageViewRGB32& alpha_mask); - - -// Multiply every pixel by "multiplier". Alpha channels are ignored. -void scale_brightness(ImageRGB32& image, const FloatPixel& multiplier); - - -// Compute root-mean-square deviation of the two images. -// - The two images must be the same dimensions. -// - The alpha channels of "reference" must be 0 or 255. No other values are valid. -// -// If (reference.alpha == 255) Count the pixel. -// If (reference.alpha == 0) Ignore the pixel and exclude from pixel count. -// -double pixel_RMSD(const ImageViewRGB32& reference, const ImageViewRGB32& image); - - -// Compute root-mean-square deviation of the two images. -// - The two images must be the same dimensions. -// - The alpha channels of "reference" must be 0 or 255. No other values are valid. -// -// If (reference.alpha == 255) Count the pixel. -// If (reference.alpha == 0) Replace reference pixel with "background". -// -double pixel_RMSD(const ImageViewRGB32& reference, const ImageViewRGB32& image, Color background); - - -// Compute root-mean-square deviation of the two images. -// - The two images must be the same dimensions. -// - The alpha channels of both images must be 0 or 255. No other values are valid. -// -// If (reference.alpha == 255 && image.alpha == 255) Count the pixel. -// If (reference.alpha == 255 && image.alpha == 0) Count the pixel as maximum possible distance. (255 for all RGB) -// If (reference.alpha == 0 && image.alpha == 255) Count the pixel as maximum possible distance. (255 for all RGB) -// If (reference.alpha == 0 && image.alpha == 0) Ignore the pixel and exclude from pixel count. -// -double pixel_RMSD_masked(const ImageViewRGB32& reference, const ImageViewRGB32& image); - - - -} -} -#endif +/* Image Diff + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonFramework_ImageDiff_H +#define PokemonAutomation_CommonFramework_ImageDiff_H + +#include "CommonFramework/ImageTools/FloatPixel.h" + +namespace PokemonAutomation{ + class ImageViewRGB32; + class ImageRGB32; +namespace ImageMatch{ + + +// Compute average of all 4 components. +// - The two images must be the same dimensions. +// - The alpha channels of "reference" is used to indicate which parts to ignore. +// 0 means background. 255 means object. No other values are valid. +FloatPixel pixel_average(const ImageViewRGB32& image, const ImageViewRGB32& alpha_mask); + + +// Multiply every pixel by "multiplier". Alpha channels are ignored. +void scale_brightness(ImageRGB32& image, const FloatPixel& multiplier); + + +// Compute root-mean-square deviation of the two images. +// - The two images must be the same dimensions. +// - The alpha channels of "reference" must be 0 or 255. No other values are valid. +// +// If (reference.alpha == 255) Count the pixel. +// If (reference.alpha == 0) Ignore the pixel and exclude from pixel count. +// +double pixel_RMSD(const ImageViewRGB32& reference, const ImageViewRGB32& image); + + +// Compute root-mean-square deviation of the two images. +// - The two images must be the same dimensions. +// - The alpha channels of "reference" must be 0 or 255. No other values are valid. +// +// If (reference.alpha == 255) Count the pixel. +// If (reference.alpha == 0) Replace reference pixel with "background". +// +double pixel_RMSD(const ImageViewRGB32& reference, const ImageViewRGB32& image, Color background); + + +// Compute root-mean-square deviation of the two images. +// - The two images must be the same dimensions. +// - The alpha channels of both images must be 0 or 255. No other values are valid. +// +// If (reference.alpha == 255 && image.alpha == 255) Count the pixel. +// If (reference.alpha == 255 && image.alpha == 0) Count the pixel as maximum possible distance. (255 for all RGB) +// If (reference.alpha == 0 && image.alpha == 255) Count the pixel as maximum possible distance. (255 for all RGB) +// If (reference.alpha == 0 && image.alpha == 0) Ignore the pixel and exclude from pixel count. +// +double pixel_RMSD_masked(const ImageViewRGB32& reference, const ImageViewRGB32& image); + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Logging/FileWindowLogger.cpp b/SerialPrograms/Source/CommonFramework/Logging/FileWindowLogger.cpp index 47600c9b46..e06b05e919 100644 --- a/SerialPrograms/Source/CommonFramework/Logging/FileWindowLogger.cpp +++ b/SerialPrograms/Source/CommonFramework/Logging/FileWindowLogger.cpp @@ -8,8 +8,11 @@ #include #include #include "CommonFramework/Globals.h" +#include "CommonFramework/GlobalSettingsPanel.h" #include "CommonFramework/Windows/DpiScaler.h" #include "CommonFramework/Windows/WindowTracker.h" +#include "CommonFramework/Windows/MainWindow.h" +#include "CommonFramework/Options/ResolutionOption.h" #include "FileWindowLogger.h" //#include @@ -212,7 +215,9 @@ FileWindowLoggerWindow::FileWindowLoggerWindow(FileWindowLogger& logger, QWidget if (objectName().isEmpty()){ setObjectName(QString::fromUtf8("TextWindow")); } - resize(scale_dpi_width(1200), scale_dpi_height(600)); + uint32_t width = GlobalSettings::instance().LOG_WINDOW_SIZE->WIDTH; + uint32_t height = GlobalSettings::instance().LOG_WINDOW_SIZE->HEIGHT; + resize(scale_dpi_width(width), scale_dpi_height(height)); m_text = new QTextEdit(this); m_text->setObjectName(QString::fromUtf8("centralwidget")); setCentralWidget(m_text); @@ -236,6 +241,11 @@ FileWindowLoggerWindow::FileWindowLoggerWindow(FileWindowLogger& logger, QWidget } ); + GlobalSettings::instance().LOG_WINDOW_SIZE->WIDTH.add_listener(*this); + GlobalSettings::instance().LOG_WINDOW_SIZE->HEIGHT.add_listener(*this); + GlobalSettings::instance().LOG_WINDOW_SIZE->X_POS.add_listener(*this); + GlobalSettings::instance().LOG_WINDOW_SIZE->Y_POS.add_listener(*this); + m_logger += *this; log("================================================================================"); log("Window Startup..."); @@ -248,6 +258,10 @@ FileWindowLoggerWindow::FileWindowLoggerWindow(FileWindowLogger& logger, QWidget FileWindowLoggerWindow::~FileWindowLoggerWindow(){ remove_window(*this); m_logger -= *this; + GlobalSettings::instance().LOG_WINDOW_SIZE->WIDTH.remove_listener(*this); + GlobalSettings::instance().LOG_WINDOW_SIZE->HEIGHT.remove_listener(*this); + GlobalSettings::instance().LOG_WINDOW_SIZE->X_POS.remove_listener(*this); + GlobalSettings::instance().LOG_WINDOW_SIZE->Y_POS.remove_listener(*this); } void FileWindowLoggerWindow::log(QString msg){ @@ -255,6 +269,42 @@ void FileWindowLoggerWindow::log(QString msg){ emit signal_log(msg); } +void FileWindowLoggerWindow::resizeEvent(QResizeEvent* event){ + m_pending_resize = true; + GlobalSettings::instance().LOG_WINDOW_SIZE->WIDTH.set(width()); + GlobalSettings::instance().LOG_WINDOW_SIZE->HEIGHT.set(height()); + m_pending_resize = false; +} + +void FileWindowLoggerWindow::moveEvent(QMoveEvent* event){ + m_pending_move = true; + GlobalSettings::instance().LOG_WINDOW_SIZE->X_POS.set(x()); + GlobalSettings::instance().LOG_WINDOW_SIZE->Y_POS.set(y()); + m_pending_move = false; +} + +void FileWindowLoggerWindow::on_config_value_changed(void* object){ + if (object == &GlobalSettings::instance().LOG_WINDOW_SIZE->WIDTH || object == &GlobalSettings::instance().LOG_WINDOW_SIZE->HEIGHT){ + QMetaObject::invokeMethod(this, [this]{ + if (!m_pending_resize){ + resize( + GlobalSettings::instance().LOG_WINDOW_SIZE->WIDTH, + GlobalSettings::instance().LOG_WINDOW_SIZE->HEIGHT + ); + } + }); + }else if (object == &GlobalSettings::instance().LOG_WINDOW_SIZE->X_POS || object == &GlobalSettings::instance().LOG_WINDOW_SIZE->Y_POS){ + QMetaObject::invokeMethod(this, [this]{ + if (!m_pending_move){ + move( + move_x_within_screen_bounds(GlobalSettings::instance().LOG_WINDOW_SIZE->X_POS), + move_y_within_screen_bounds(GlobalSettings::instance().LOG_WINDOW_SIZE->Y_POS) + ); + } + }); + } +} + diff --git a/SerialPrograms/Source/CommonFramework/Logging/FileWindowLogger.h b/SerialPrograms/Source/CommonFramework/Logging/FileWindowLogger.h index cc9e38ba6d..a24bc4002d 100644 --- a/SerialPrograms/Source/CommonFramework/Logging/FileWindowLogger.h +++ b/SerialPrograms/Source/CommonFramework/Logging/FileWindowLogger.h @@ -16,6 +16,7 @@ #include #include #include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Options/ConfigOption.h" //#include "Common/Cpp/LifetimeSanitizer.h" namespace PokemonAutomation{ @@ -72,7 +73,7 @@ class FileWindowLogger : public Logger{ }; -class FileWindowLoggerWindow : public QMainWindow{ +class FileWindowLoggerWindow : public QMainWindow, public ConfigOption::Listener{ Q_OBJECT public: @@ -80,14 +81,19 @@ class FileWindowLoggerWindow : public QMainWindow{ virtual ~FileWindowLoggerWindow(); void log(QString msg); + virtual void resizeEvent(QResizeEvent* event) override; + virtual void moveEvent(QMoveEvent* event) override; signals: void signal_log(QString msg); private: + virtual void on_config_value_changed(void* object) override; FileWindowLogger& m_logger; QMenuBar* m_menubar; QTextEdit* m_text; + bool m_pending_resize = false; + bool m_pending_move = false; }; diff --git a/SerialPrograms/Source/CommonFramework/Main.cpp b/SerialPrograms/Source/CommonFramework/Main.cpp index 6765e5177b..f43b58048f 100644 --- a/SerialPrograms/Source/CommonFramework/Main.cpp +++ b/SerialPrograms/Source/CommonFramework/Main.cpp @@ -15,7 +15,6 @@ #include "Logging/Logger.h" #include "Logging/OutputRedirector.h" //#include "Tools/StatsDatabase.h" -#include "Integrations/SleepyDiscordRunner.h" #include "Globals.h" #include "GlobalSettingsPanel.h" //#include "Windows/DpiScaler.h" @@ -111,15 +110,8 @@ int main(int argc, char *argv[]){ Integration::DiscordIntegrationSettingsOption& discord_settings = GlobalSettings::instance().DISCORD->integration; if (discord_settings.run_on_start){ -#ifdef PA_SLEEPY - if (discord_settings.library0 == Integration::DiscordIntegrationSettingsOption::Library::SleepyDiscord){ - Integration::SleepyDiscordRunner::sleepy_connect(); - } -#endif #ifdef PA_DPP - if (discord_settings.library0 == Integration::DiscordIntegrationSettingsOption::Library::DPP){ - Integration::DppClient::Client::instance().connect(); - } + Integration::DppClient::Client::instance().connect(); #endif discord_settings.on_config_value_changed(nullptr); } @@ -144,9 +136,6 @@ int main(int argc, char *argv[]){ #ifdef PA_DPP Integration::DppClient::Client::instance().disconnect(); #endif -#ifdef PA_SLEEPY - Integration::SleepyDiscordRunner::sleepy_terminate(); -#endif return ret; } diff --git a/SerialPrograms/Source/CommonFramework/Notifications/EventNotificationOption.cpp b/SerialPrograms/Source/CommonFramework/Notifications/EventNotificationOption.cpp index cb0917bc0a..b6cd62a261 100644 --- a/SerialPrograms/Source/CommonFramework/Notifications/EventNotificationOption.cpp +++ b/SerialPrograms/Source/CommonFramework/Notifications/EventNotificationOption.cpp @@ -226,7 +226,7 @@ EventNotificationOption::EventNotificationOption( add_option(m_data->m_enabled, "Enabled"); add_option(m_data->m_label, ""); add_option(m_data->m_ping, "Ping"); - add_option(m_data->m_screenshot, "Screenshot"); + add_option(m_data->m_screenshot, "Screenshot0"); add_option(m_data->m_tags, "Tags"); add_option(m_data->m_rate_limit_seconds, "RateLimitSeconds"); add_option(m_test_button, ""); diff --git a/SerialPrograms/Source/CommonFramework/Notifications/ProgramNotifications.cpp b/SerialPrograms/Source/CommonFramework/Notifications/ProgramNotifications.cpp index 76aecde236..dc73cf51d2 100644 --- a/SerialPrograms/Source/CommonFramework/Notifications/ProgramNotifications.cpp +++ b/SerialPrograms/Source/CommonFramework/Notifications/ProgramNotifications.cpp @@ -15,7 +15,6 @@ #include "CommonFramework/Tools/ProgramEnvironment.h" #include "CommonFramework/ProgramStats/StatsTracking.h" #include "Integrations/DiscordWebhook.h" -#include "Integrations/SleepyDiscordRunner.h" #include "ProgramNotifications.h" //#include @@ -120,22 +119,11 @@ void send_raw_notification( hasFile ? file : nullptr ); -#ifdef PA_SLEEPY - if (GlobalSettings::instance().DISCORD->integration.library0 == Integration::DiscordIntegrationSettingsOption::Library::SleepyDiscord){ - Integration::SleepyDiscordRunner::send_embed_sleepy( - should_ping, tags, std::move(embed), - hasFile ? file : nullptr - ); - } -#endif - #ifdef PA_DPP - if (GlobalSettings::instance().DISCORD->integration.library0 == Integration::DiscordIntegrationSettingsOption::Library::DPP){ - Integration::DppClient::Client::instance().send_embed_dpp( - should_ping, color, tags, std::move(embed), - hasFile ? file : nullptr - ); - } + Integration::DppClient::Client::instance().send_embed_dpp( + should_ping, color, tags, std::move(embed), + hasFile ? file : nullptr + ); #endif } void send_raw_notification( @@ -173,22 +161,11 @@ void send_raw_notification( hasFile ? file : nullptr ); -#ifdef PA_SLEEPY - if (GlobalSettings::instance().DISCORD->integration.library0 == Integration::DiscordIntegrationSettingsOption::Library::SleepyDiscord){ - Integration::SleepyDiscordRunner::send_embed_sleepy( - should_ping, tags, std::move(embed), - hasFile ? file : nullptr - ); - } -#endif - #ifdef PA_DPP - if (GlobalSettings::instance().DISCORD->integration.library0 == Integration::DiscordIntegrationSettingsOption::Library::DPP){ - Integration::DppClient::Client::instance().send_embed_dpp( - should_ping, color, tags, std::move(embed), - hasFile ? file : nullptr - ); - } + Integration::DppClient::Client::instance().send_embed_dpp( + should_ping, color, tags, std::move(embed), + hasFile ? file : nullptr + ); #endif } diff --git a/SerialPrograms/Source/CommonFramework/Options/CheckForUpdatesOption.h b/SerialPrograms/Source/CommonFramework/Options/CheckForUpdatesOption.h index 2da321bbf1..b18ee97e99 100644 --- a/SerialPrograms/Source/CommonFramework/Options/CheckForUpdatesOption.h +++ b/SerialPrograms/Source/CommonFramework/Options/CheckForUpdatesOption.h @@ -1,67 +1,67 @@ -/* Check for Updates Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_CheckForUpdatesOption_H -#define PokemonAutomation_Options_CheckForUpdatesOption_H - -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/StringOption.h" -#include "CommonFramework/Globals.h" - -namespace PokemonAutomation{ - - -class CheckForUpdatesOption : public GroupOption{ -public: - CheckForUpdatesOption() - : GroupOption( - "Check for Updates", - LockMode::UNLOCK_WHILE_RUNNING, - EnableMode::ALWAYS_ENABLED, - true - ) - , RELEASE0( - "New Releases:
Automatically check for new stable releases.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , PUBLIC_BETA0( - "Public Betas:
Automatically check for new public betas.", - LockMode::UNLOCK_WHILE_RUNNING, - IS_BETA_VERSION - ) - , PRIVATE_BETA0( - "Private Betas:
Automatically check for new private betas.", - LockMode::UNLOCK_WHILE_RUNNING, - IS_BETA_VERSION - ) - ,SKIP_VERSION( - false, - "Skip this Version:
Skip this version and don't notify until the next update.", - LockMode::UNLOCK_WHILE_RUNNING, - "", - "0.50.0" - ) - { - PA_ADD_OPTION(RELEASE0); - PA_ADD_OPTION(PUBLIC_BETA0); - if (IS_BETA_VERSION){ - PA_ADD_OPTION(PRIVATE_BETA0); - } - PA_ADD_OPTION(SKIP_VERSION); - } - -public: - BooleanCheckBoxOption RELEASE0; - BooleanCheckBoxOption PUBLIC_BETA0; - BooleanCheckBoxOption PRIVATE_BETA0; - StringOption SKIP_VERSION; -}; - - -} -#endif +/* Check for Updates Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_CheckForUpdatesOption_H +#define PokemonAutomation_Options_CheckForUpdatesOption_H + +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/StringOption.h" +#include "CommonFramework/Globals.h" + +namespace PokemonAutomation{ + + +class CheckForUpdatesOption : public GroupOption{ +public: + CheckForUpdatesOption() + : GroupOption( + "Check for Updates", + LockMode::UNLOCK_WHILE_RUNNING, + EnableMode::ALWAYS_ENABLED, + true + ) + , RELEASE0( + "New Releases:
Automatically check for new stable releases.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , PUBLIC_BETA0( + "Public Betas:
Automatically check for new public betas.", + LockMode::UNLOCK_WHILE_RUNNING, + IS_BETA_VERSION + ) + , PRIVATE_BETA0( + "Private Betas:
Automatically check for new private betas.", + LockMode::UNLOCK_WHILE_RUNNING, + IS_BETA_VERSION + ) + ,SKIP_VERSION( + false, + "Skip this Version:
Skip this version and don't notify until the next update.", + LockMode::UNLOCK_WHILE_RUNNING, + "", + "0.50.0" + ) + { + PA_ADD_OPTION(RELEASE0); + PA_ADD_OPTION(PUBLIC_BETA0); + if (IS_BETA_VERSION){ + PA_ADD_OPTION(PRIVATE_BETA0); + } + PA_ADD_OPTION(SKIP_VERSION); + } + +public: + BooleanCheckBoxOption RELEASE0; + BooleanCheckBoxOption PUBLIC_BETA0; + BooleanCheckBoxOption PRIVATE_BETA0; + StringOption SKIP_VERSION; +}; + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Options/Environment/PerformanceOptions.h b/SerialPrograms/Source/CommonFramework/Options/Environment/PerformanceOptions.h index 87ae4043e3..f1a0c6c75e 100644 --- a/SerialPrograms/Source/CommonFramework/Options/Environment/PerformanceOptions.h +++ b/SerialPrograms/Source/CommonFramework/Options/Environment/PerformanceOptions.h @@ -1,85 +1,101 @@ -/* Performance Options - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PerformanceOptions_H -#define PokemonAutomation_PerformanceOptions_H - -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "ProcessPriorityOption.h" -#include "ProcessorLevelOption.h" - -namespace PokemonAutomation{ - - -class PerformanceOptions : public GroupOption{ -public: - PerformanceOptions() - : GroupOption( - "Performance", - LockMode::LOCK_WHILE_RUNNING, - GroupOption::EnableMode::ALWAYS_ENABLED, true - ) - , PRECISE_WAKE_MARGIN( - "Precise Wake Time Margin:
" - "Some operations require a thread to wake up at a very precise time - " - "more precise than what the operating system's scheduler can provide. " - "This option will force such operations to wake up this many " - "microseconds earlier, then busy wait until the time is reached. " - "The sys-botbase controller is an example of something that requires " - "extremely precise wake times.", - LockMode::UNLOCK_WHILE_RUNNING, - "2000 us" - ) - , REALTIME_THREAD_PRIORITY( - "Realtime Thread Priority:
" - "Thread priority of real-time threads. (UI thread, audio threads)
" - "Restart the program for this to fully take effect.", - DEFAULT_PRIORITY_REALTIME - ) - , REALTIME_INFERENCE_PRIORITY( - "Inference Priority:
" - "Thread priority of realtime inference threads that must run fast " - "enough to keep a program working properly.", - DEFAULT_PRIORITY_REALTIME_INFERENCE - ) - , NORMAL_INFERENCE_PRIORITY( - "normal Inference Priority:
" - "Thread priority of non-realtime inference threads that can be slow " - "without negatively affecting a program.", - DEFAULT_PRIORITY_NORMAL_INFERENCE - ) - , COMPUTE_PRIORITY( - "Compute Priority:
" - "Thread priority of computation threads.", - DEFAULT_PRIORITY_COMPUTE - ) - { - PA_ADD_OPTION(PRECISE_WAKE_MARGIN); - PA_ADD_OPTION(REALTIME_THREAD_PRIORITY); - PA_ADD_OPTION(REALTIME_INFERENCE_PRIORITY); - PA_ADD_OPTION(NORMAL_INFERENCE_PRIORITY); - PA_ADD_OPTION(COMPUTE_PRIORITY); - PA_ADD_OPTION(PROCESSOR_LEVEL); - } - -public: - MicrosecondsOption PRECISE_WAKE_MARGIN; - - ThreadPriorityOption REALTIME_THREAD_PRIORITY; - ThreadPriorityOption REALTIME_INFERENCE_PRIORITY; - ThreadPriorityOption NORMAL_INFERENCE_PRIORITY; - ThreadPriorityOption COMPUTE_PRIORITY; - - ProcessorLevelOption PROCESSOR_LEVEL; -}; - - - - - -} -#endif +/* Performance Options + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PerformanceOptions_H +#define PokemonAutomation_PerformanceOptions_H + +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Options/ThreadPoolOption.h" +#include "ProcessPriorityOption.h" +#include "ProcessorLevelOption.h" + +namespace PokemonAutomation{ + + +class PerformanceOptions : public GroupOption{ +public: + PerformanceOptions() + : GroupOption( + "Performance", + LockMode::LOCK_WHILE_RUNNING, + GroupOption::EnableMode::ALWAYS_ENABLED, true + ) + , REALTIME_THREAD_PRIORITY( + "Realtime Thread Priority:
" + "Thread priority of real-time threads. (UI thread, audio threads)
" + "Restart the program for this to fully take effect.", + DEFAULT_PRIORITY_REALTIME + ) + , INFERENCE_PIVOT_PRIORITY( + "Inference Pivot Priority:
" + "Thread priority of inference dispatcher threads.", + DEFAULT_PRIORITY_REALTIME_INFERENCE + ) + , COMPUTE_PRIORITY( + "Compute Priority:
" + "Thread priority of computation threads.", + DEFAULT_PRIORITY_COMPUTE + ) + , REALTIME_THREAD_POOL( + "Real-time Thread Pool", + "Thread pool for tasks that must run fast enough to keep a " + "program running properly.
" + "Restart program for changes to take full effect.", + DEFAULT_PRIORITY_REALTIME_INFERENCE, + 0.5 + ) + , NORMAL_THREAD_POOL( + "Normal Thread Pool", + "Thread pool for tasks that can be slow without negatively " + "affecting a program.
" + "Restart program for changes to take full effect.", + DEFAULT_PRIORITY_NORMAL_INFERENCE, + 1.0 + ) + , PRECISE_WAKE_MARGIN( + "Precise Wake Time Margin:
" + "Some operations require a thread to wake up at a very precise time - " + "more precise than what the operating system's scheduler can provide. " + "This option will force such operations to wake up this many " + "microseconds earlier, then busy wait until the time is reached. " + "The sys-botbase controller is an example of something that requires " + "extremely precise wake times.", + LockMode::UNLOCK_WHILE_RUNNING, + "2000 us" + ) + { + PA_ADD_OPTION(PROCESSOR_LEVEL); + + PA_ADD_OPTION(REALTIME_THREAD_PRIORITY); + PA_ADD_OPTION(INFERENCE_PIVOT_PRIORITY); + PA_ADD_OPTION(COMPUTE_PRIORITY); + + PA_ADD_OPTION(REALTIME_THREAD_POOL); + PA_ADD_OPTION(NORMAL_THREAD_POOL); + + PA_ADD_OPTION(PRECISE_WAKE_MARGIN); + } + +public: + ProcessorLevelOption PROCESSOR_LEVEL; + + ThreadPriorityOption REALTIME_THREAD_PRIORITY; + ThreadPriorityOption INFERENCE_PIVOT_PRIORITY; + ThreadPriorityOption COMPUTE_PRIORITY; + + ThreadPoolOption REALTIME_THREAD_POOL; + ThreadPoolOption NORMAL_THREAD_POOL; + + MicrosecondsOption PRECISE_WAKE_MARGIN; +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Options/Environment/ProcessPriorityOption.h b/SerialPrograms/Source/CommonFramework/Options/Environment/ProcessPriorityOption.h index a66e0f0749..4641181f8f 100644 --- a/SerialPrograms/Source/CommonFramework/Options/Environment/ProcessPriorityOption.h +++ b/SerialPrograms/Source/CommonFramework/Options/Environment/ProcessPriorityOption.h @@ -8,7 +8,7 @@ #define PokemonAutomation_ProcessPriorityOption_H #include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/GroupOption.h" +//#include "Common/Cpp/Options/GroupOption.h" #include "CommonFramework/Environment/Environment.h" namespace PokemonAutomation{ @@ -26,8 +26,8 @@ class ThreadPriorityOption : public EnumDropdownOption{ default_priority ) {} - void set_on_this_thread() const{ - set_thread_priority(*this); + void set_on_this_thread(Logger& logger) const{ + set_thread_priority(logger, *this); } }; diff --git a/SerialPrograms/Source/CommonFramework/Options/Environment/SleepSuppressOption.cpp b/SerialPrograms/Source/CommonFramework/Options/Environment/SleepSuppressOption.cpp index c4cd6cb21b..bd7bb40f3c 100644 --- a/SerialPrograms/Source/CommonFramework/Options/Environment/SleepSuppressOption.cpp +++ b/SerialPrograms/Source/CommonFramework/Options/Environment/SleepSuppressOption.cpp @@ -1,80 +1,80 @@ -/* Sleep Suppress Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "SleepSuppressOption.h" - -namespace PokemonAutomation{ - - -SleepSuppressOption::SleepSuppressOption(std::string label, SleepSuppress default_value) - : EnumDropdownOption( - std::move(label), - { - {SleepSuppress::NONE, "none", "Do not suppress sleep or screensaver."}, -#ifdef PA_ENABLE_SLEEP_SUPPRESS_NO_SLEEP - {SleepSuppress::NO_SLEEP, "no-sleep", "Prevent computer from sleeping, but allow screen to turn off."}, -#endif - {SleepSuppress::SCREEN_ON, "screen-on", "Keep the screen on."}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - default_value - ) -{} - - -SleepSuppressOptions::~SleepSuppressOptions(){ - PROGRAM_RUNNING.remove_listener(*this); - IDLE.remove_listener(*this); -} -SleepSuppressOptions::SleepSuppressOptions() - : GroupOption( - "Suppress Screensaver/Sleep:", - LockMode::UNLOCK_WHILE_RUNNING, - GroupOption::EnableMode::ALWAYS_ENABLED, true - ) - , IDLE("No Program Running:", SleepSuppress::NONE) -#ifdef PA_ENABLE_SLEEP_SUPPRESS_NO_SLEEP - , PROGRAM_RUNNING("Program is Running:", SleepSuppress::NO_SLEEP) -#else - , PROGRAM_RUNNING("Program is Running:", SleepSuppress::NONE) -#endif - , m_idle_scope(IDLE) -{ - PA_ADD_OPTION(IDLE); - PA_ADD_OPTION(PROGRAM_RUNNING); - - IDLE.add_listener(*this); - PROGRAM_RUNNING.add_listener(*this); -} - -void SleepSuppressOptions::on_config_value_changed(void* object){ - if (object == &IDLE){ - m_idle_scope = IDLE; - PROGRAM_RUNNING.set_value(std::max(IDLE.current_value(), PROGRAM_RUNNING.current_value())); - }else{ - IDLE.set_value(std::min(IDLE.current_value(), PROGRAM_RUNNING.current_value())); - } -} - - -} - - - - - - - - - - - - - - - - - +/* Sleep Suppress Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "SleepSuppressOption.h" + +namespace PokemonAutomation{ + + +SleepSuppressOption::SleepSuppressOption(std::string label, SleepSuppress default_value) + : EnumDropdownOption( + std::move(label), + { + {SleepSuppress::NONE, "none", "Do not suppress sleep or screensaver."}, +#ifdef PA_ENABLE_SLEEP_SUPPRESS_NO_SLEEP + {SleepSuppress::NO_SLEEP, "no-sleep", "Prevent computer from sleeping, but allow screen to turn off."}, +#endif + {SleepSuppress::SCREEN_ON, "screen-on", "Keep the screen on."}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + default_value + ) +{} + + +SleepSuppressOptions::~SleepSuppressOptions(){ + PROGRAM_RUNNING.remove_listener(*this); + IDLE.remove_listener(*this); +} +SleepSuppressOptions::SleepSuppressOptions() + : GroupOption( + "Suppress Screensaver/Sleep:", + LockMode::UNLOCK_WHILE_RUNNING, + GroupOption::EnableMode::ALWAYS_ENABLED, true + ) + , IDLE("No Program Running:", SleepSuppress::NONE) +#ifdef PA_ENABLE_SLEEP_SUPPRESS_NO_SLEEP + , PROGRAM_RUNNING("Program is Running:", SleepSuppress::NO_SLEEP) +#else + , PROGRAM_RUNNING("Program is Running:", SleepSuppress::NONE) +#endif + , m_idle_scope(IDLE) +{ + PA_ADD_OPTION(IDLE); + PA_ADD_OPTION(PROGRAM_RUNNING); + + IDLE.add_listener(*this); + PROGRAM_RUNNING.add_listener(*this); +} + +void SleepSuppressOptions::on_config_value_changed(void* object){ + if (object == &IDLE){ + m_idle_scope = IDLE; + PROGRAM_RUNNING.set_value(std::max(IDLE.current_value(), PROGRAM_RUNNING.current_value())); + }else{ + IDLE.set_value(std::min(IDLE.current_value(), PROGRAM_RUNNING.current_value())); + } +} + + +} + + + + + + + + + + + + + + + + + diff --git a/SerialPrograms/Source/CommonFramework/Options/Environment/SleepSuppressOption.h b/SerialPrograms/Source/CommonFramework/Options/Environment/SleepSuppressOption.h index 338dc53ed5..a4422d5a65 100644 --- a/SerialPrograms/Source/CommonFramework/Options/Environment/SleepSuppressOption.h +++ b/SerialPrograms/Source/CommonFramework/Options/Environment/SleepSuppressOption.h @@ -1,41 +1,41 @@ -/* Sleep Suppress Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SleepSuppressOption_H -#define PokemonAutomation_SleepSuppressOption_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/GroupOption.h" -#include "CommonFramework/Environment/SystemSleep.h" - -namespace PokemonAutomation{ - - - -class SleepSuppressOption : public EnumDropdownOption{ -public: - SleepSuppressOption(std::string label, SleepSuppress default_value); -}; - - -class SleepSuppressOptions : public GroupOption, public ConfigOption::Listener{ -public: - ~SleepSuppressOptions(); - SleepSuppressOptions(); - - virtual void on_config_value_changed(void* object) override; - -public: - SleepSuppressOption IDLE; - SleepSuppressOption PROGRAM_RUNNING; - -private: - SleepSuppressScope m_idle_scope; -}; - - -} -#endif +/* Sleep Suppress Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SleepSuppressOption_H +#define PokemonAutomation_SleepSuppressOption_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/GroupOption.h" +#include "CommonFramework/Environment/SystemSleep.h" + +namespace PokemonAutomation{ + + + +class SleepSuppressOption : public EnumDropdownOption{ +public: + SleepSuppressOption(std::string label, SleepSuppress default_value); +}; + + +class SleepSuppressOptions : public GroupOption, public ConfigOption::Listener{ +public: + ~SleepSuppressOptions(); + SleepSuppressOptions(); + + virtual void on_config_value_changed(void* object) override; + +public: + SleepSuppressOption IDLE; + SleepSuppressOption PROGRAM_RUNNING; + +private: + SleepSuppressScope m_idle_scope; +}; + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Options/QtWidget/LabelCellWidget.cpp b/SerialPrograms/Source/CommonFramework/Options/QtWidget/LabelCellWidget.cpp index a2c25a3744..4786d1dab9 100644 --- a/SerialPrograms/Source/CommonFramework/Options/QtWidget/LabelCellWidget.cpp +++ b/SerialPrograms/Source/CommonFramework/Options/QtWidget/LabelCellWidget.cpp @@ -1,60 +1,60 @@ -/* Label Cell - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "LabelCellWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -ConfigWidget* LabelCellOption::make_QtWidget(QWidget& parent){ - return new LabelCellWidget(parent, *this); -} - - -LabelCellWidget::~LabelCellWidget(){ -} -LabelCellWidget::LabelCellWidget(QWidget& parent, LabelCellOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) -// , m_value(value) -{ - QHBoxLayout* layout = new QHBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); -// layout->setAlignment(Qt::AlignLeft); - - if (value.icon()){ - m_icon = new QLabel(this); - Resolution resolution = value.resolution(); -// cout << resolution.width << " x " << resolution.height << endl; - QPixmap pixmap; - if (resolution.width == 0 || resolution.height == 0){ - pixmap = QPixmap::fromImage(value.icon().to_QImage_ref()); - }else{ - pixmap = QPixmap::fromImage(value.icon().scaled_to_QImage(resolution.width, resolution.height)); - } - m_icon->setPixmap(pixmap); - m_icon->setAlignment(Qt::AlignCenter); - layout->addWidget(m_icon); - } - - m_text = new QLabel(QString::fromStdString(value.text()), this); - layout->addWidget(m_text, 1); -// text->setTextInteractionFlags(Qt::TextBrowserInteraction); -// m_text->setOpenExternalLinks(true); -} - - - - -} +/* Label Cell + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "LabelCellWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +ConfigWidget* LabelCellOption::make_QtWidget(QWidget& parent){ + return new LabelCellWidget(parent, *this); +} + + +LabelCellWidget::~LabelCellWidget(){ +} +LabelCellWidget::LabelCellWidget(QWidget& parent, LabelCellOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) +// , m_value(value) +{ + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); +// layout->setAlignment(Qt::AlignLeft); + + if (value.icon()){ + m_icon = new QLabel(this); + Resolution resolution = value.resolution(); +// cout << resolution.width << " x " << resolution.height << endl; + QPixmap pixmap; + if (resolution.width == 0 || resolution.height == 0){ + pixmap = QPixmap::fromImage(value.icon().to_QImage_ref()); + }else{ + pixmap = QPixmap::fromImage(value.icon().scaled_to_QImage(resolution.width, resolution.height)); + } + m_icon->setPixmap(pixmap); + m_icon->setAlignment(Qt::AlignCenter); + layout->addWidget(m_icon); + } + + m_text = new QLabel(QString::fromStdString(value.text()), this); + layout->addWidget(m_text, 1); +// text->setTextInteractionFlags(Qt::TextBrowserInteraction); +// m_text->setOpenExternalLinks(true); +} + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Options/QtWidget/LabelCellWidget.h b/SerialPrograms/Source/CommonFramework/Options/QtWidget/LabelCellWidget.h index f9fa4c8677..07982208b1 100644 --- a/SerialPrograms/Source/CommonFramework/Options/QtWidget/LabelCellWidget.h +++ b/SerialPrograms/Source/CommonFramework/Options/QtWidget/LabelCellWidget.h @@ -1,35 +1,35 @@ -/* Label Cell - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_LabelCellWidget_H -#define PokemonAutomation_Options_LabelCellWidget_H - -#include -#include "Common/Qt/Options/ConfigWidget.h" -#include "CommonFramework/Options/LabelCellOption.h" - -class QLabel; - -namespace PokemonAutomation{ - - - -class LabelCellWidget : public QWidget, public ConfigWidget{ -public: - ~LabelCellWidget(); - LabelCellWidget(QWidget& parent, LabelCellOption& value); - -private: -// LabelCellOption& m_value; - QLabel* m_icon = nullptr; - QLabel* m_text; -}; - - - - -} -#endif +/* Label Cell + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_LabelCellWidget_H +#define PokemonAutomation_Options_LabelCellWidget_H + +#include +#include "Common/Qt/Options/ConfigWidget.h" +#include "CommonFramework/Options/LabelCellOption.h" + +class QLabel; + +namespace PokemonAutomation{ + + + +class LabelCellWidget : public QWidget, public ConfigWidget{ +public: + ~LabelCellWidget(); + LabelCellWidget(QWidget& parent, LabelCellOption& value); + +private: +// LabelCellOption& m_value; + QLabel* m_icon = nullptr; + QLabel* m_text; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Options/ResolutionOption.cpp b/SerialPrograms/Source/CommonFramework/Options/ResolutionOption.cpp index f0c94428fa..af8070551e 100644 --- a/SerialPrograms/Source/CommonFramework/Options/ResolutionOption.cpp +++ b/SerialPrograms/Source/CommonFramework/Options/ResolutionOption.cpp @@ -1,28 +1,34 @@ -/* Resolution Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Windows/DpiScaler.h" -#include "ResolutionOption.h" - -namespace PokemonAutomation{ - - -ResolutionOption::ResolutionOption( - std::string label, std::string description, - int default_width, int default_height -) - : GroupOption(std::move(label), LockMode::LOCK_WHILE_RUNNING) - , DESCRIPTION(std::move(description)) - , WIDTH("Width:", LockMode::LOCK_WHILE_RUNNING, scale_dpi_width(default_width)) - , HEIGHT("Height:", LockMode::LOCK_WHILE_RUNNING, scale_dpi_height(default_height)) -{ - PA_ADD_STATIC(DESCRIPTION); - PA_ADD_OPTION(WIDTH); - PA_ADD_OPTION(HEIGHT); -} - - -} +/* Resolution Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Windows/DpiScaler.h" +#include "ResolutionOption.h" + +namespace PokemonAutomation{ + + +ResolutionOption::ResolutionOption( + std::string label, std::string description, + int default_width, int default_height, + int initial_x_pos, int initial_y_pos +) + : GroupOption(std::move(label), LockMode::LOCK_WHILE_RUNNING) + , DESCRIPTION(std::move(description)) + , WIDTH("Width:", LockMode::LOCK_WHILE_RUNNING, scale_dpi_width(default_width)) + , HEIGHT("Height:", LockMode::LOCK_WHILE_RUNNING, scale_dpi_height(default_height)) + , X_POS("X-position:", LockMode::LOCK_WHILE_RUNNING, scale_dpi_width(initial_x_pos)) + , Y_POS("Y-position:", LockMode::LOCK_WHILE_RUNNING, scale_dpi_height(initial_y_pos)) +{ + PA_ADD_STATIC(DESCRIPTION); + PA_ADD_OPTION(WIDTH); + PA_ADD_OPTION(HEIGHT); + PA_ADD_OPTION(X_POS); + PA_ADD_OPTION(Y_POS); +} + + +} diff --git a/SerialPrograms/Source/CommonFramework/Options/ResolutionOption.h b/SerialPrograms/Source/CommonFramework/Options/ResolutionOption.h index 4de2ee091a..a4ecfeb2e1 100644 --- a/SerialPrograms/Source/CommonFramework/Options/ResolutionOption.h +++ b/SerialPrograms/Source/CommonFramework/Options/ResolutionOption.h @@ -1,31 +1,34 @@ -/* Resolution Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_ResolutionOption_H -#define PokemonAutomation_Options_ResolutionOption_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/GroupOption.h" - -namespace PokemonAutomation{ - - -class ResolutionOption : public GroupOption{ -public: - ResolutionOption( - std::string label, std::string description, - int default_width, int default_height - ); - - StaticTextOption DESCRIPTION; - SimpleIntegerOption WIDTH; - SimpleIntegerOption HEIGHT; -}; - - -} -#endif +/* Resolution Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_ResolutionOption_H +#define PokemonAutomation_Options_ResolutionOption_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/GroupOption.h" + +namespace PokemonAutomation{ + + +class ResolutionOption : public GroupOption{ +public: + ResolutionOption( + std::string label, std::string description, + int default_width, int default_height, + int initial_x_pos, int initial_y_pos + ); + + StaticTextOption DESCRIPTION; + SimpleIntegerOption WIDTH; + SimpleIntegerOption HEIGHT; + SimpleIntegerOption X_POS; + SimpleIntegerOption Y_POS; +}; + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Options/ThreadPoolOption.cpp b/SerialPrograms/Source/CommonFramework/Options/ThreadPoolOption.cpp new file mode 100644 index 0000000000..d8c62e920e --- /dev/null +++ b/SerialPrograms/Source/CommonFramework/Options/ThreadPoolOption.cpp @@ -0,0 +1,62 @@ +/* Thread Pool Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "ThreadPoolOption.h" + +namespace PokemonAutomation{ + + +ThreadPoolOption::ThreadPoolOption( + std::string label, + std::string description, + ThreadPriority default_priority, + double default_max_thread_ratio +) + : GroupOption( + std::move(label), + LockMode::UNLOCK_WHILE_RUNNING, + EnableMode::ALWAYS_ENABLED, + true + ) + , m_default_max_threads( + std::max( + (size_t)(std::thread::hardware_concurrency() * default_max_thread_ratio), + (size_t)1 + ) + ) + , HARDWARE_THREADS( + "Hardware Threads:", + LockMode::UNLOCK_WHILE_RUNNING, + std::thread::hardware_concurrency() + ) + , m_description(std::move(description)) + , PRIORITY("Thread Priority:", default_priority) + , MAX_THREADS( + "Maximum Threads:", + LockMode::UNLOCK_WHILE_RUNNING, + m_default_max_threads, 1 + ) +{ + PA_ADD_OPTION(HARDWARE_THREADS); + PA_ADD_STATIC(m_description); + PA_ADD_OPTION(PRIORITY); + PA_ADD_OPTION(MAX_THREADS); + HARDWARE_THREADS.set_visibility(ConfigOptionState::HIDDEN); +} + +void ThreadPoolOption::load_json(const JsonValue& json){ + GroupOption::load_json(json); + + // Reset the max threads if the hardware threads has changed. + if (HARDWARE_THREADS != std::thread::hardware_concurrency()){ + MAX_THREADS.set(m_default_max_threads); + } +} + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Options/ThreadPoolOption.h b/SerialPrograms/Source/CommonFramework/Options/ThreadPoolOption.h new file mode 100644 index 0000000000..3c32908bc4 --- /dev/null +++ b/SerialPrograms/Source/CommonFramework/Options/ThreadPoolOption.h @@ -0,0 +1,42 @@ +/* Thread Pool Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_ThreadPoolOption_H +#define PokemonAutomation_Options_ThreadPoolOption_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/GroupOption.h" +#include "Environment/ProcessPriorityOption.h" + +namespace PokemonAutomation{ + + +class ThreadPoolOption : public GroupOption{ +public: + ThreadPoolOption( + std::string label, + std::string description, + ThreadPriority default_priority, + double default_max_thread_ratio = 1.0 + ); + + virtual void load_json(const JsonValue& json) override; + +private: + const size_t m_default_max_threads; + SimpleIntegerOption HARDWARE_THREADS; + +public: + StaticTextOption m_description; + ThreadPriorityOption PRIORITY; + SimpleIntegerOption MAX_THREADS; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Panels/UI/PanelWidget.h b/SerialPrograms/Source/CommonFramework/Panels/UI/PanelWidget.h index b9ead315a9..88f1bb8fbc 100644 --- a/SerialPrograms/Source/CommonFramework/Panels/UI/PanelWidget.h +++ b/SerialPrograms/Source/CommonFramework/Panels/UI/PanelWidget.h @@ -31,6 +31,8 @@ class PanelWidget : public QWidget{ PanelInstance& instance(){ return m_instance; } protected: + // Generate a collapsible UI element that shows the program panel header. + // It contains the name of the program and its description. virtual CollapsibleGroupBox* make_header(QWidget& parent); protected: diff --git a/SerialPrograms/Source/CommonFramework/PersistentSettings.cpp b/SerialPrograms/Source/CommonFramework/PersistentSettings.cpp index b568d8d435..81c944073f 100644 --- a/SerialPrograms/Source/CommonFramework/PersistentSettings.cpp +++ b/SerialPrograms/Source/CommonFramework/PersistentSettings.cpp @@ -7,10 +7,11 @@ #include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" +//#include "Common/Cpp/Json/JsonArray.h" #include "Common/Cpp/Json/JsonObject.h" #include "CommonFramework/Globals.h" #include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Logging/Logger.h" #include "CommonFramework/Options/Environment/PerformanceOptions.h" #include "PersistentSettings.h" @@ -62,7 +63,7 @@ void PersistentSettings::read(){ } // GlobalSettings::instance().PROCESS_PRIORITY0.update_priority_to_option(); - GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(); + GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(global_logger_tagged()); #if 0 { diff --git a/SerialPrograms/Source/CommonFramework/ProgramStats/StatsDatabase.cpp b/SerialPrograms/Source/CommonFramework/ProgramStats/StatsDatabase.cpp index ab4eb16ac9..b6465c4239 100644 --- a/SerialPrograms/Source/CommonFramework/ProgramStats/StatsDatabase.cpp +++ b/SerialPrograms/Source/CommonFramework/ProgramStats/StatsDatabase.cpp @@ -1,248 +1,248 @@ -/* Stats Database - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "ClientSource/Libraries/Logging.h" -#include "StatsDatabase.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - -const std::map STATS_DATABASE_ALIASES{ - {"Dex Rec Finder", "PokemonSwSh:DexRecFinder"}, - {"Day Skipper (JPN)", "PokemonSwSh:DaySkipperJPN"}, - {"Day Skipper (EU)", "PokemonSwSh:DaySkipperEU"}, - {"Day Skipper (US)", "PokemonSwSh:DaySkipperUS"}, - {"Day Skipper (JPN) - 7.8k", "PokemonSwSh:DaySkipperJPN7p8k"}, - {"Purple Beam Finder", "PokemonSwSh:PurpleBeamFinder"}, - {"Auto-Host Multi-Game", "PokemonSwSh:AutoHostMultiGame"}, - {"Auto-Host Rolling", "PokemonSwSh:AutoHostRolling"}, - {"Stats Reset", "PokemonSwSh:StatsReset"}, - {"Shiny Hunt Autonomous - Regi", "PokemonSwSh:ShinyHuntAutonomousRegi"}, - {"Shiny Hunt Autonomous - Swords Of Justice", "PokemonSwSh:ShinyHuntAutonomousSwordsOfJustice"}, - {"Shiny Hunt Autonomous - Strong Spawn", "PokemonSwSh:ShinyHuntAutonomousStrongSpawn"}, - {"Shiny Hunt Autonomous - Regigigas2", "PokemonSwSh:ShinyHuntAutonomousRegigigas2"}, - {"Shiny Hunt Autonomous - IoA Trade", "PokemonSwSh:ShinyHuntAutonomousIoATrade"}, - {"Shiny Hunt Autonomous - Berry Tree", "PokemonSwSh:ShinyHuntAutonomousBerryTree"}, - {"Shiny Hunt Autonomous - Whistling", "PokemonSwSh:ShinyHuntAutonomousWhistling"}, - {"Shiny Hunt Autonomous - Fishing", "PokemonSwSh:ShinyHuntAutonomousFishing"}, - {"Shiny Hunt Autonomous - Overworld", "PokemonSwSh:ShinyHuntAutonomousOverworld"}, - {"PokemonSV:StatsResetBloodmoon", "PokemonSV:StatsResetEventBattle"}, -}; - - - -StatLine::StatLine(StatsTracker& tracker) - : m_time(current_time_to_str()) - , m_stats(tracker.to_str(StatsTracker::SAVE_TO_STATS_FILE)) -{} -StatLine::StatLine(const std::string& line){ - size_t pos = line.find(" - "); - if (pos == std::string::npos){ - m_time = line; - return; - } - m_time = line.substr(0, pos); - - const char* ptr = line.c_str() + pos + 3; - - // Skip to stats. - while (true){ - char ch = *ptr; - if (ch < 32) return; - if (('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z')) break; - ptr++; - } - - m_stats = ptr; -} -std::string StatLine::to_str() const{ - return m_time + " - " + m_stats; -#if 0 - std::string str = m_time + " - "; - str += m_tracker - ? m_tracker->to_str() - : m_stats; - return m_time + " - " + - (m_tracker ? m_tracker->to_str() : m_stats); -#endif -} - - - - -void StatList::operator+=(StatsTracker& tracker){ - m_list.emplace_back(tracker); -} -void StatList::operator+=(const std::string& line){ - m_list.emplace_back(line); -} -std::string StatList::to_str() const{ - std::string str; - for (const StatLine& line : m_list){ - str += line.to_str(); - str += "\r\n"; - } - return str; -} - -void StatList::aggregate(StatsTracker& tracker) const{ - for (const StatLine& line : m_list){ - tracker.parse_and_append_line(line.stats()); -// cout << tracker.to_str() << endl; - } -} - - - - -#if 0 -StatList* StatSet::find(const std::string& label){ - auto iter = m_data.find(label); - return iter == m_data.end() - ? nullptr - : &iter->second; -} -#endif -StatList& StatSet::operator[](const std::string& identifier){ - return m_data[identifier]; -} - -std::string StatSet::to_str() const{ - std::string str; - for (const auto& item : m_data){ - if (item.second.size() == 0){ - continue; - } - str += "================================================================================\r\n"; - str += item.first; - str += "\r\n"; - str += "\r\n"; - str += item.second.to_str(); - str += "\r\n"; - } - return str; -} - -void StatSet::save_to_file(const std::string& filepath){ - QFile file(QString::fromStdString(filepath)); - file.open(QIODevice::WriteOnly); - std::string data = to_str(); - file.write(data.c_str(), data.size()); -} -void StatSet::open_from_file(const std::string& filepath){ - QFile file(QString::fromStdString(filepath)); - if (!file.open(QIODevice::ReadOnly)){ - return; - } - - std::string str = file.readAll().data(); - load_from_string(str.c_str()); -} - -bool StatSet::update_file( - const std::string& filepath, - const std::string& identifier, - StatsTracker& tracker -){ - QFile file(QString::fromStdString(filepath)); - while (!file.open(QIODevice::ReadWrite)){ - return false; - } - std::string data = file.readAll().data(); - - StatSet set; - set.load_from_string(data.c_str()); - - set[identifier] += tracker; - - data = set.to_str(); - file.seek(0); - file.write(data.c_str(), data.size()); - file.resize(data.size()); - - return true; -} - - -bool StatSet::get_line(std::string& line, const char*& ptr){ - line.clear(); - for (;; ptr++){ - char ch = *ptr; - if (ch == '\0'){ -// cout << line << endl; - ptr++; - return false; - } - if (ch == '\r'){ - continue; - } - if (ch == '\n'){ -// cout << line << endl; - ptr++; - return true; - } - line += ch; - } -} -void StatSet::load_from_string(const char* ptr){ - m_data.clear(); - - // Find first section. - while (true){ - std::string line; - if (!get_line(line, ptr)){ - return; - } - if (line[0] == '='){ - break; - } - } - - while (true){ - std::string line; - if (!get_line(line, ptr)){ - return; - } - if (line.empty()){ - continue; - } - - auto iter = STATS_DATABASE_ALIASES.find(line); - if (iter != STATS_DATABASE_ALIASES.end()){ - line = iter->second; - } - - StatList& program = m_data[line]; - while (true){ - if (!get_line(line, ptr)){ - return; - } - if (line.empty()){ - continue; - } - if (line[0] == '='){ - break; - } - program += line; - } - } -} - - - - - - - - - -} - +/* Stats Database + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "ClientSource/Libraries/Logging.h" +#include "StatsDatabase.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + +const std::map STATS_DATABASE_ALIASES{ + {"Dex Rec Finder", "PokemonSwSh:DexRecFinder"}, + {"Day Skipper (JPN)", "PokemonSwSh:DaySkipperJPN"}, + {"Day Skipper (EU)", "PokemonSwSh:DaySkipperEU"}, + {"Day Skipper (US)", "PokemonSwSh:DaySkipperUS"}, + {"Day Skipper (JPN) - 7.8k", "PokemonSwSh:DaySkipperJPN7p8k"}, + {"Purple Beam Finder", "PokemonSwSh:PurpleBeamFinder"}, + {"Auto-Host Multi-Game", "PokemonSwSh:AutoHostMultiGame"}, + {"Auto-Host Rolling", "PokemonSwSh:AutoHostRolling"}, + {"Stats Reset", "PokemonSwSh:StatsReset"}, + {"Shiny Hunt Autonomous - Regi", "PokemonSwSh:ShinyHuntAutonomousRegi"}, + {"Shiny Hunt Autonomous - Swords Of Justice", "PokemonSwSh:ShinyHuntAutonomousSwordsOfJustice"}, + {"Shiny Hunt Autonomous - Strong Spawn", "PokemonSwSh:ShinyHuntAutonomousStrongSpawn"}, + {"Shiny Hunt Autonomous - Regigigas2", "PokemonSwSh:ShinyHuntAutonomousRegigigas2"}, + {"Shiny Hunt Autonomous - IoA Trade", "PokemonSwSh:ShinyHuntAutonomousIoATrade"}, + {"Shiny Hunt Autonomous - Berry Tree", "PokemonSwSh:ShinyHuntAutonomousBerryTree"}, + {"Shiny Hunt Autonomous - Whistling", "PokemonSwSh:ShinyHuntAutonomousWhistling"}, + {"Shiny Hunt Autonomous - Fishing", "PokemonSwSh:ShinyHuntAutonomousFishing"}, + {"Shiny Hunt Autonomous - Overworld", "PokemonSwSh:ShinyHuntAutonomousOverworld"}, + {"PokemonSV:StatsResetBloodmoon", "PokemonSV:StatsResetEventBattle"}, +}; + + + +StatLine::StatLine(StatsTracker& tracker) + : m_time(current_time_to_str()) + , m_stats(tracker.to_str(StatsTracker::SAVE_TO_STATS_FILE)) +{} +StatLine::StatLine(const std::string& line){ + size_t pos = line.find(" - "); + if (pos == std::string::npos){ + m_time = line; + return; + } + m_time = line.substr(0, pos); + + const char* ptr = line.c_str() + pos + 3; + + // Skip to stats. + while (true){ + char ch = *ptr; + if (ch < 32) return; + if (('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z')) break; + ptr++; + } + + m_stats = ptr; +} +std::string StatLine::to_str() const{ + return m_time + " - " + m_stats; +#if 0 + std::string str = m_time + " - "; + str += m_tracker + ? m_tracker->to_str() + : m_stats; + return m_time + " - " + + (m_tracker ? m_tracker->to_str() : m_stats); +#endif +} + + + + +void StatList::operator+=(StatsTracker& tracker){ + m_list.emplace_back(tracker); +} +void StatList::operator+=(const std::string& line){ + m_list.emplace_back(line); +} +std::string StatList::to_str() const{ + std::string str; + for (const StatLine& line : m_list){ + str += line.to_str(); + str += "\r\n"; + } + return str; +} + +void StatList::aggregate(StatsTracker& tracker) const{ + for (const StatLine& line : m_list){ + tracker.parse_and_append_line(line.stats()); +// cout << tracker.to_str() << endl; + } +} + + + + +#if 0 +StatList* StatSet::find(const std::string& label){ + auto iter = m_data.find(label); + return iter == m_data.end() + ? nullptr + : &iter->second; +} +#endif +StatList& StatSet::operator[](const std::string& identifier){ + return m_data[identifier]; +} + +std::string StatSet::to_str() const{ + std::string str; + for (const auto& item : m_data){ + if (item.second.size() == 0){ + continue; + } + str += "================================================================================\r\n"; + str += item.first; + str += "\r\n"; + str += "\r\n"; + str += item.second.to_str(); + str += "\r\n"; + } + return str; +} + +void StatSet::save_to_file(const std::string& filepath){ + QFile file(QString::fromStdString(filepath)); + file.open(QIODevice::WriteOnly); + std::string data = to_str(); + file.write(data.c_str(), data.size()); +} +void StatSet::open_from_file(const std::string& filepath){ + QFile file(QString::fromStdString(filepath)); + if (!file.open(QIODevice::ReadOnly)){ + return; + } + + std::string str = file.readAll().data(); + load_from_string(str.c_str()); +} + +bool StatSet::update_file( + const std::string& filepath, + const std::string& identifier, + StatsTracker& tracker +){ + QFile file(QString::fromStdString(filepath)); + while (!file.open(QIODevice::ReadWrite)){ + return false; + } + std::string data = file.readAll().data(); + + StatSet set; + set.load_from_string(data.c_str()); + + set[identifier] += tracker; + + data = set.to_str(); + file.seek(0); + file.write(data.c_str(), data.size()); + file.resize(data.size()); + + return true; +} + + +bool StatSet::get_line(std::string& line, const char*& ptr){ + line.clear(); + for (;; ptr++){ + char ch = *ptr; + if (ch == '\0'){ +// cout << line << endl; + ptr++; + return false; + } + if (ch == '\r'){ + continue; + } + if (ch == '\n'){ +// cout << line << endl; + ptr++; + return true; + } + line += ch; + } +} +void StatSet::load_from_string(const char* ptr){ + m_data.clear(); + + // Find first section. + while (true){ + std::string line; + if (!get_line(line, ptr)){ + return; + } + if (line[0] == '='){ + break; + } + } + + while (true){ + std::string line; + if (!get_line(line, ptr)){ + return; + } + if (line.empty()){ + continue; + } + + auto iter = STATS_DATABASE_ALIASES.find(line); + if (iter != STATS_DATABASE_ALIASES.end()){ + line = iter->second; + } + + StatList& program = m_data[line]; + while (true){ + if (!get_line(line, ptr)){ + return; + } + if (line.empty()){ + continue; + } + if (line[0] == '='){ + break; + } + program += line; + } + } +} + + + + + + + + + +} + diff --git a/SerialPrograms/Source/CommonFramework/ProgramStats/StatsDatabase.h b/SerialPrograms/Source/CommonFramework/ProgramStats/StatsDatabase.h index 196c5fc025..18aa914f91 100644 --- a/SerialPrograms/Source/CommonFramework/ProgramStats/StatsDatabase.h +++ b/SerialPrograms/Source/CommonFramework/ProgramStats/StatsDatabase.h @@ -1,76 +1,76 @@ -/* Stats Database - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_StatsDatabase_H -#define PokemonAutomation_StatsDatabase_H - -#include "StatsTracking.h" - -namespace PokemonAutomation{ - - -class StatLine{ -public: - StatLine(StatsTracker& tracker); - StatLine(const std::string& line); - - const std::string& stats() const{ return m_stats; } - std::string to_str() const; - -private: - std::string m_time; - std::string m_stats; -}; - - - -class StatList{ -public: - void operator+=(StatsTracker& tracker); - void operator+=(const std::string& line); - - size_t size() const{ return m_list.size(); } - std::string to_str() const; - - const std::vector& list() const{ return m_list; } - - void aggregate(StatsTracker& tracker) const; - -private: - std::vector m_list; -}; - - - - -class StatSet{ -public: -// StatList* find(const std::string& label); - StatList& operator[](const std::string& identifier); - - std::string to_str() const; - - void save_to_file(const std::string& filepath); - void open_from_file(const std::string& filepath); - - static bool update_file( - const std::string& filepath, - const std::string& identifier, - StatsTracker& tracker - ); - -private: - bool get_line(std::string& line, const char*& ptr); - void load_from_string(const char* ptr); - -private: - std::map m_data; -}; - - - -} -#endif +/* Stats Database + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_StatsDatabase_H +#define PokemonAutomation_StatsDatabase_H + +#include "StatsTracking.h" + +namespace PokemonAutomation{ + + +class StatLine{ +public: + StatLine(StatsTracker& tracker); + StatLine(const std::string& line); + + const std::string& stats() const{ return m_stats; } + std::string to_str() const; + +private: + std::string m_time; + std::string m_stats; +}; + + + +class StatList{ +public: + void operator+=(StatsTracker& tracker); + void operator+=(const std::string& line); + + size_t size() const{ return m_list.size(); } + std::string to_str() const; + + const std::vector& list() const{ return m_list; } + + void aggregate(StatsTracker& tracker) const; + +private: + std::vector m_list; +}; + + + + +class StatSet{ +public: +// StatList* find(const std::string& label); + StatList& operator[](const std::string& identifier); + + std::string to_str() const; + + void save_to_file(const std::string& filepath); + void open_from_file(const std::string& filepath); + + static bool update_file( + const std::string& filepath, + const std::string& identifier, + StatsTracker& tracker + ); + +private: + bool get_line(std::string& line, const char*& ptr); + void load_from_string(const char* ptr); + +private: + std::map m_data; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/ProgramStats/StatsTracking.cpp b/SerialPrograms/Source/CommonFramework/ProgramStats/StatsTracking.cpp index 54dfdf193c..b8f916bcce 100644 --- a/SerialPrograms/Source/CommonFramework/ProgramStats/StatsTracking.cpp +++ b/SerialPrograms/Source/CommonFramework/ProgramStats/StatsTracking.cpp @@ -1,192 +1,192 @@ -/* Stats Tracking - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/PrettyPrint.h" -#include "StatsTracking.h" - -namespace PokemonAutomation{ - - - -StatsTracker::Stat::Stat(std::string&& p_label, DisplayMode p_display_node) - : label(p_label) - , display_mode(p_display_node) -{} -std::string StatsTracker::to_str(PrintMode mode) const{ - std::map stats; - for (const auto& item : m_stats){ - auto alias = m_aliases.find(item.first); - - // Not an alias. - if (alias == m_aliases.end()){ - stats[item.first] += item.second.load(std::memory_order_relaxed); - continue; - } - - // Find alias target. - auto iter = m_stats.find(alias->second); - if (iter != m_stats.end()){ - stats[alias->second] += item.second.load(std::memory_order_relaxed); - } - } - - std::string str; - for (const Stat& stat : m_display_order){ - auto iter = stats.find(stat.label); - uint64_t count = 0; - if (iter != stats.end()){ - count += iter->second; - } - - switch (stat.display_mode){ - case ALWAYS_VISIBLE: - break; - case HIDDEN_IF_ZERO: - if (count == 0){ - continue; - }else{ - break; - } - case ALWAYS_HIDDEN: - switch (mode){ - case DISPLAY_ON_SCREEN: - continue; - case SAVE_TO_STATS_FILE: - if (count == 0){ - continue; - }else{ - break; - } - } - } - - if (!str.empty()){ - str += " - "; - } - str += stat.label; - str += ": "; - str += tostr_u_commas(count); - } - return str; -} - - - -void StatsTracker::parse_and_append_line(const std::string& line){ - const char* ptr = line.c_str(); - while (true){ - // Parse label. - std::string label; - while (true){ - char ch = *ptr++; - if (ch < 32) return; - if (ch == ':') break; - label += ch; - } - - // Skip to number. - while (true){ - char ch = *ptr; - if (ch < 32) return; - if ('0' <= ch && ch <= '9') break; - ptr++; - } - - // Parse number. - uint64_t count = 0; - while (true){ - char ch = *ptr++; - if (ch < 32){ - m_stats[label] += count; - return; - } - if (ch == ',') continue; - if (!('0' <= ch && ch <= '9')) break; - count *= 10; - count += ch - '0'; - } - -// cout << label << " = " << count << endl; - m_stats[label] += count; - - // Skip to next; - while (true){ - char ch = *ptr; - if (ch < 32) return; - if (('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z')) break; - ptr++; - } - } -} - - - -std::string stats_to_bar( - Logger& logger, - const StatsTracker* historical, - const StatsTracker* current, - const std::string& override_current -){ - std::string current_str; - if (!override_current.empty()){ - current_str = override_current; - }else if (current){ - current_str = current->to_str(StatsTracker::DISPLAY_ON_SCREEN); - } - - std::string historical_str; - if (historical){ - historical_str = historical->to_str(StatsTracker::DISPLAY_ON_SCREEN); - } - - if (current_str.empty() && historical_str.empty()){ - return ""; - } - - if (!current_str.empty() && historical_str.empty()){ - logger.log(current_str); - return current_str; - } - if (current_str.empty() && !historical_str.empty()){ - return "Past Runs - " + historical_str; - } - - logger.log(current_str); - - std::string str; - str += "Current Run - " + current_str; - str += "
"; - str += "Past Totals - " + historical_str; - - return str; -} - - - - - - - - - - - - - - - - - - - - - - - - - -} +/* Stats Tracking + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/PrettyPrint.h" +#include "StatsTracking.h" + +namespace PokemonAutomation{ + + + +StatsTracker::Stat::Stat(std::string&& p_label, DisplayMode p_display_node) + : label(p_label) + , display_mode(p_display_node) +{} +std::string StatsTracker::to_str(PrintMode mode) const{ + std::map stats; + for (const auto& item : m_stats){ + auto alias = m_aliases.find(item.first); + + // Not an alias. + if (alias == m_aliases.end()){ + stats[item.first] += item.second.load(std::memory_order_relaxed); + continue; + } + + // Find alias target. + auto iter = m_stats.find(alias->second); + if (iter != m_stats.end()){ + stats[alias->second] += item.second.load(std::memory_order_relaxed); + } + } + + std::string str; + for (const Stat& stat : m_display_order){ + auto iter = stats.find(stat.label); + uint64_t count = 0; + if (iter != stats.end()){ + count += iter->second; + } + + switch (stat.display_mode){ + case ALWAYS_VISIBLE: + break; + case HIDDEN_IF_ZERO: + if (count == 0){ + continue; + }else{ + break; + } + case ALWAYS_HIDDEN: + switch (mode){ + case DISPLAY_ON_SCREEN: + continue; + case SAVE_TO_STATS_FILE: + if (count == 0){ + continue; + }else{ + break; + } + } + } + + if (!str.empty()){ + str += " - "; + } + str += stat.label; + str += ": "; + str += tostr_u_commas(count); + } + return str; +} + + + +void StatsTracker::parse_and_append_line(const std::string& line){ + const char* ptr = line.c_str(); + while (true){ + // Parse label. + std::string label; + while (true){ + char ch = *ptr++; + if (ch < 32) return; + if (ch == ':') break; + label += ch; + } + + // Skip to number. + while (true){ + char ch = *ptr; + if (ch < 32) return; + if ('0' <= ch && ch <= '9') break; + ptr++; + } + + // Parse number. + uint64_t count = 0; + while (true){ + char ch = *ptr++; + if (ch < 32){ + m_stats[label] += count; + return; + } + if (ch == ',') continue; + if (!('0' <= ch && ch <= '9')) break; + count *= 10; + count += ch - '0'; + } + +// cout << label << " = " << count << endl; + m_stats[label] += count; + + // Skip to next; + while (true){ + char ch = *ptr; + if (ch < 32) return; + if (('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z')) break; + ptr++; + } + } +} + + + +std::string stats_to_bar( + Logger& logger, + const StatsTracker* historical, + const StatsTracker* current, + const std::string& override_current +){ + std::string current_str; + if (!override_current.empty()){ + current_str = override_current; + }else if (current){ + current_str = current->to_str(StatsTracker::DISPLAY_ON_SCREEN); + } + + std::string historical_str; + if (historical){ + historical_str = historical->to_str(StatsTracker::DISPLAY_ON_SCREEN); + } + + if (current_str.empty() && historical_str.empty()){ + return ""; + } + + if (!current_str.empty() && historical_str.empty()){ + logger.log(current_str); + return current_str; + } + if (current_str.empty() && !historical_str.empty()){ + return "Past Runs - " + historical_str; + } + + logger.log(current_str); + + std::string str; + str += "Current Run - " + current_str; + str += "
"; + str += "Past Totals - " + historical_str; + + return str; +} + + + + + + + + + + + + + + + + + + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/ProgramStats/StatsTracking.h b/SerialPrograms/Source/CommonFramework/ProgramStats/StatsTracking.h index 4e12117e9f..f50f1323a8 100644 --- a/SerialPrograms/Source/CommonFramework/ProgramStats/StatsTracking.h +++ b/SerialPrograms/Source/CommonFramework/ProgramStats/StatsTracking.h @@ -1,67 +1,67 @@ -/* Stats Tracking - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_StatsTracking_H -#define PokemonAutomation_StatsTracking_H - -#include -#include -#include -#include - -namespace PokemonAutomation{ - -class Logger; - -class StatsTracker{ - StatsTracker(const StatsTracker&) = delete; - -public: - StatsTracker() = default; - virtual ~StatsTracker() = default; - - enum PrintMode{ - DISPLAY_ON_SCREEN, - SAVE_TO_STATS_FILE, - }; - virtual std::string to_str(PrintMode mode) const; - - void parse_and_append_line(const std::string& line); - - -protected: -// static constexpr bool HIDDEN_IF_ZERO = true; -// static constexpr bool ALWAYS_VISIBLE = false; - enum DisplayMode{ - ALWAYS_VISIBLE, - HIDDEN_IF_ZERO, - ALWAYS_HIDDEN, - }; - - struct Stat{ - std::string label; - DisplayMode display_mode; - Stat(std::string&& p_label, DisplayMode p_display_node = ALWAYS_VISIBLE); - }; - - std::vector m_display_order; - std::map> m_stats; - std::map m_aliases; -}; - - -std::string stats_to_bar( - Logger& logger, - const StatsTracker* historical, - const StatsTracker* current, - const std::string& override_current = "" -); - - - - -} -#endif +/* Stats Tracking + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_StatsTracking_H +#define PokemonAutomation_StatsTracking_H + +#include +#include +#include +#include + +namespace PokemonAutomation{ + +class Logger; + +class StatsTracker{ + StatsTracker(const StatsTracker&) = delete; + +public: + StatsTracker() = default; + virtual ~StatsTracker() = default; + + enum PrintMode{ + DISPLAY_ON_SCREEN, + SAVE_TO_STATS_FILE, + }; + virtual std::string to_str(PrintMode mode) const; + + void parse_and_append_line(const std::string& line); + + +protected: +// static constexpr bool HIDDEN_IF_ZERO = true; +// static constexpr bool ALWAYS_VISIBLE = false; + enum DisplayMode{ + ALWAYS_VISIBLE, + HIDDEN_IF_ZERO, + ALWAYS_HIDDEN, + }; + + struct Stat{ + std::string label; + DisplayMode display_mode; + Stat(std::string&& p_label, DisplayMode p_display_node = ALWAYS_VISIBLE); + }; + + std::vector m_display_order; + std::map> m_stats; + std::map m_aliases; +}; + + +std::string stats_to_bar( + Logger& logger, + const StatsTracker* historical, + const StatsTracker* current, + const std::string& override_current = "" +); + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryOption.cpp b/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryOption.cpp index d8d6d96518..448a3e7566 100644 --- a/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryOption.cpp +++ b/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryOption.cpp @@ -1,117 +1,117 @@ -/* Stream History Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Globals.h" -#include "StreamHistoryOption.h" - -namespace PokemonAutomation{ - -StreamHistoryOption::StreamHistoryOption() - : GroupOption( - "Stream History", - LockMode::LOCK_WHILE_RUNNING, - GroupOption::EnableMode::DEFAULT_DISABLED, - true - ) - , DESCRIPTION( - "Keep a record of the recent video+audio streams. This will allow video capture " - "for unexpected events.

" - "Warning: This feature has a known memory leak. It will leak ~3GB per day per " - "video stream. You have been warned!" - "

" - "Warning: This feature is computationally expensive and " - "will require a more powerful computer to run (especially for multi-Switch programs).
" - "Furthermore, the current implementation is inefficient as it will write a lot " - "of data to disk. This feature is still a work-in-progress." - "
" - ) - , HISTORY_SECONDS( - "History (seconds):
" - "Keep this many seconds of video and audio feed for video capture and debugging purposes.

" - "Do not set this too large as it will consume a lot of memory and may exceed the " - "attachment size limit for Discord notifications." - "", - LockMode::UNLOCK_WHILE_RUNNING, - 30 - ) - , RESOLUTION( - "Resolution:", - { - {Resolution::MATCH_INPUT, "match", "Match Input Resolution"}, - {Resolution::FORCE_720p, "720p", "1280 x 720"}, - {Resolution::FORCE_1080p, "1080p", "1920 x 1080"}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - Resolution::FORCE_720p - ) - , ENCODING_MODE( - "Encoding Mode:", - { - {EncodingMode::FIXED_QUALITY, "fixed-quality", "Fixed Quality"}, - {EncodingMode::FIXED_BITRATE, "fixed-bitrate", "Fixed Bit Rate"}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - EncodingMode::FIXED_QUALITY - ) - , VIDEO_QUALITY( - "Video Quality:
" - "High quality videos will take more disk space " - "and may exceed the attachment size limit for Discord notifications." - "", - { - {VideoQuality::VERY_LOW, "very-low", "Very Low"}, - {VideoQuality::LOW, "low", "Low"}, - {VideoQuality::NORMAL, "normal", "Normal"}, - {VideoQuality::HIGH, "high", "High"}, - {VideoQuality::VERY_HIGH, "very-high", "Very High"}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - VideoQuality::LOW - ) - , VIDEO_BITRATE( - "Video Bit-Rate (kbps):
" - "Lower = lower quality, smaller file size.
" - "Higher = high quality, larger file size.
" - "Large values can exceed the attachment size limit for Discord notifications." - "", - LockMode::UNLOCK_WHILE_RUNNING, - 5000 - ) -{ - PA_ADD_STATIC(DESCRIPTION); - PA_ADD_OPTION(HISTORY_SECONDS); - PA_ADD_OPTION(RESOLUTION); - PA_ADD_OPTION(ENCODING_MODE); - PA_ADD_OPTION(VIDEO_QUALITY); - PA_ADD_OPTION(VIDEO_BITRATE); - - StreamHistoryOption::on_config_value_changed(this); - - ENCODING_MODE.add_listener(*this); -} -StreamHistoryOption::~StreamHistoryOption(){ - ENCODING_MODE.remove_listener(*this); -} - -void StreamHistoryOption::on_config_value_changed(void* object){ - switch (ENCODING_MODE){ - case EncodingMode::FIXED_QUALITY: - VIDEO_QUALITY.set_visibility(ConfigOptionState::ENABLED); - VIDEO_BITRATE.set_visibility(ConfigOptionState::HIDDEN); - break; - case EncodingMode::FIXED_BITRATE: - VIDEO_QUALITY.set_visibility(ConfigOptionState::HIDDEN); - VIDEO_BITRATE.set_visibility(ConfigOptionState::ENABLED); - break; - } -} - - - - - - -} +/* Stream History Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Globals.h" +#include "StreamHistoryOption.h" + +namespace PokemonAutomation{ + +StreamHistoryOption::StreamHistoryOption() + : GroupOption( + "Stream History", + LockMode::LOCK_WHILE_RUNNING, + GroupOption::EnableMode::DEFAULT_DISABLED, + true + ) + , DESCRIPTION( + "Keep a record of the recent video+audio streams. This will allow video capture " + "for unexpected events.

" + "Warning: This feature has a known memory leak. It will leak ~3GB per day per " + "video stream. You have been warned!" + "

" + "Warning: This feature is computationally expensive and " + "will require a more powerful computer to run (especially for multi-Switch programs).
" + "Furthermore, the current implementation is inefficient as it will write a lot " + "of data to disk. This feature is still a work-in-progress." + "
" + ) + , HISTORY_SECONDS( + "History (seconds):
" + "Keep this many seconds of video and audio feed for video capture and debugging purposes.

" + "Do not set this too large as it will consume a lot of memory and may exceed the " + "attachment size limit for Discord notifications." + "", + LockMode::UNLOCK_WHILE_RUNNING, + 30 + ) + , RESOLUTION( + "Resolution:", + { + {Resolution::MATCH_INPUT, "match", "Match Input Resolution"}, + {Resolution::FORCE_720p, "720p", "1280 x 720"}, + {Resolution::FORCE_1080p, "1080p", "1920 x 1080"}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + Resolution::FORCE_720p + ) + , ENCODING_MODE( + "Encoding Mode:", + { + {EncodingMode::FIXED_QUALITY, "fixed-quality", "Fixed Quality"}, + {EncodingMode::FIXED_BITRATE, "fixed-bitrate", "Fixed Bit Rate"}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + EncodingMode::FIXED_QUALITY + ) + , VIDEO_QUALITY( + "Video Quality:
" + "High quality videos will take more disk space " + "and may exceed the attachment size limit for Discord notifications." + "", + { + {VideoQuality::VERY_LOW, "very-low", "Very Low"}, + {VideoQuality::LOW, "low", "Low"}, + {VideoQuality::NORMAL, "normal", "Normal"}, + {VideoQuality::HIGH, "high", "High"}, + {VideoQuality::VERY_HIGH, "very-high", "Very High"}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + VideoQuality::LOW + ) + , VIDEO_BITRATE( + "Video Bit-Rate (kbps):
" + "Lower = lower quality, smaller file size.
" + "Higher = high quality, larger file size.
" + "Large values can exceed the attachment size limit for Discord notifications." + "", + LockMode::UNLOCK_WHILE_RUNNING, + 5000 + ) +{ + PA_ADD_STATIC(DESCRIPTION); + PA_ADD_OPTION(HISTORY_SECONDS); + PA_ADD_OPTION(RESOLUTION); + PA_ADD_OPTION(ENCODING_MODE); + PA_ADD_OPTION(VIDEO_QUALITY); + PA_ADD_OPTION(VIDEO_BITRATE); + + StreamHistoryOption::on_config_value_changed(this); + + ENCODING_MODE.add_listener(*this); +} +StreamHistoryOption::~StreamHistoryOption(){ + ENCODING_MODE.remove_listener(*this); +} + +void StreamHistoryOption::on_config_value_changed(void* object){ + switch (ENCODING_MODE){ + case EncodingMode::FIXED_QUALITY: + VIDEO_QUALITY.set_visibility(ConfigOptionState::ENABLED); + VIDEO_BITRATE.set_visibility(ConfigOptionState::HIDDEN); + break; + case EncodingMode::FIXED_BITRATE: + VIDEO_QUALITY.set_visibility(ConfigOptionState::HIDDEN); + VIDEO_BITRATE.set_visibility(ConfigOptionState::ENABLED); + break; + } +} + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryOption.h b/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryOption.h index 8db78e0e9c..11781c302f 100644 --- a/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryOption.h +++ b/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryOption.h @@ -1,56 +1,56 @@ -/* Stream History Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_StreamHistoryOption_H -#define PokemonAutomation_StreamHistoryOption_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/GroupOption.h" - -namespace PokemonAutomation{ - - - -class StreamHistoryOption : public GroupOption, public ConfigOption::Listener{ -public: - StreamHistoryOption(); - ~StreamHistoryOption(); - - virtual void on_config_value_changed(void* object) override; - - StaticTextOption DESCRIPTION; - SimpleIntegerOption HISTORY_SECONDS; - - enum class Resolution{ - MATCH_INPUT, - FORCE_720p, - FORCE_1080p, - }; - EnumDropdownOption RESOLUTION; - - enum class EncodingMode{ - FIXED_QUALITY, - FIXED_BITRATE, - }; - EnumDropdownOption ENCODING_MODE; - - - enum class VideoQuality{ - VERY_LOW, - LOW, - NORMAL, - HIGH, - VERY_HIGH, - }; - EnumDropdownOption VIDEO_QUALITY; - SimpleIntegerOption VIDEO_BITRATE; -}; - - -} -#endif +/* Stream History Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_StreamHistoryOption_H +#define PokemonAutomation_StreamHistoryOption_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/GroupOption.h" + +namespace PokemonAutomation{ + + + +class StreamHistoryOption : public GroupOption, public ConfigOption::Listener{ +public: + StreamHistoryOption(); + ~StreamHistoryOption(); + + virtual void on_config_value_changed(void* object) override; + + StaticTextOption DESCRIPTION; + SimpleIntegerOption HISTORY_SECONDS; + + enum class Resolution{ + MATCH_INPUT, + FORCE_720p, + FORCE_1080p, + }; + EnumDropdownOption RESOLUTION; + + enum class EncodingMode{ + FIXED_QUALITY, + FIXED_BITRATE, + }; + EnumDropdownOption ENCODING_MODE; + + + enum class VideoQuality{ + VERY_LOW, + LOW, + NORMAL, + HIGH, + VERY_HIGH, + }; + EnumDropdownOption VIDEO_QUALITY; + SimpleIntegerOption VIDEO_BITRATE; +}; + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Recording/StreamHistorySession.cpp b/SerialPrograms/Source/CommonFramework/Recording/StreamHistorySession.cpp index e9b8c669b0..f7dc856aa0 100644 --- a/SerialPrograms/Source/CommonFramework/Recording/StreamHistorySession.cpp +++ b/SerialPrograms/Source/CommonFramework/Recording/StreamHistorySession.cpp @@ -1,244 +1,244 @@ -/* Stream History Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" -#include "CommonFramework/Recording/StreamHistoryOption.h" - -#if (QT_VERSION_MAJOR == 6) && (QT_VERSION_MINOR >= 8) -//#include "StreamHistoryTracker_SaveFrames.h" -//#include "StreamHistoryTracker_RecordOnTheFly.h" -#include "StreamHistoryTracker_ParallelStreams.h" -#else -#include "StreamHistoryTracker_Null.h" -#endif - - -#include "StreamHistorySession.h" - - - -namespace PokemonAutomation{ - - - - - -struct StreamHistorySession::Data{ - Logger& m_logger; - mutable SpinLock m_lock; - std::chrono::seconds m_window; - AudioChannelFormat m_audio_format; - bool m_has_video; - std::shared_ptr m_current; - - Data(Logger& logger) - : m_logger(logger) - , m_window(GlobalSettings::instance().STREAM_HISTORY->HISTORY_SECONDS) - , m_audio_format(AudioChannelFormat::NONE) - , m_has_video(false) - {} -}; - - - - -StreamHistorySession::~StreamHistorySession() = default; -StreamHistorySession::StreamHistorySession(Logger& logger) - : AudioFloatStreamListener(1) - , m_data(CONSTRUCT_TOKEN, logger) -{} -void StreamHistorySession::start(AudioChannelFormat format, bool has_video){ - Data& data = *m_data; - WriteSpinLock lg(data.m_lock); - if (!data.m_current){ - data.m_audio_format = format; - data.m_has_video = has_video; - initialize(); - } -} - - -#if 0 -class HistorySaverThread : public QThread{ -public: - HistorySaverThread(StreamHistoryTracker& tracker, const std::string& filename) - : m_tracker(tracker) - , m_filename(filename) - {} - ~HistorySaverThread(){ - quit(); - wait(); - } - bool save(){ - start(); - quit(); - wait(); - return m_success; - } - virtual void run() override{ -// m_success = m_tracker.save(m_logger, m_filename); - m_success = m_tracker.save(m_filename); - exec(); - } - -private: - StreamHistoryTracker& m_tracker; - const std::string& m_filename; - bool m_success = false; -}; -#endif - -bool StreamHistorySession::save(const std::string& filename) const{ - // This will be coming in from random threads. It will block until the save - // is finished or failed. - - const Data& data = *m_data; - - // Get an owning reference to the current tracker. - // This will allow us to promptly release the lock and unblock the UI from - // changing the streams (which will wipe the history). - std::shared_ptr tracker; - { - WriteSpinLock lg(data.m_lock); - if (!data.m_current){ - data.m_logger.log("Cannot save stream history: Stream history is not enabled.", COLOR_RED); - return false; - } - tracker = data.m_current; - } - -// tracker->save(m_logger, filename); -// HistorySaverThread saver(*tracker, filename); -// return saver.save(); - - return tracker->save(filename); -} -void StreamHistorySession::on_samples(const float* samples, size_t frames){ - Data& data = *m_data; - WriteSpinLock lg(data.m_lock); - if (data.m_current){ - data.m_current->on_samples(samples, frames); - } -} -void StreamHistorySession::on_frame(std::shared_ptr frame){ - Data& data = *m_data; - WriteSpinLock lg(data.m_lock); - if (data.m_current){ - data.m_current->on_frame(std::move(frame)); - } -} - - -void StreamHistorySession::clear(){ -// cout << "clear()" << endl; - - // Must call under lock. - Data& data = *m_data; - data.m_logger.log("Clearing stream history...", COLOR_ORANGE); - data.m_current.reset(); -// expected_samples_per_frame = 0; -// data.m_audio_format = AudioChannelFormat::NONE; -// data.m_has_video = false; -} -void StreamHistorySession::initialize(){ - if (!GlobalSettings::instance().STREAM_HISTORY->enabled()){ - return; - } - - // Must call under lock. - Data& data = *m_data; - data.m_logger.log("Starting stream history...", COLOR_ORANGE); - -// cout << "video = " << data.m_has_video << endl; - - switch (data.m_audio_format){ - case AudioChannelFormat::NONE: - expected_samples_per_frame = 0; - data.m_current.reset(new StreamHistoryTracker(data.m_logger, data.m_window, 0, 0, data.m_has_video)); - return; - case AudioChannelFormat::MONO_48000: - expected_samples_per_frame = 1; - data.m_current.reset(new StreamHistoryTracker(data.m_logger, data.m_window, 1, 48000, data.m_has_video)); - return; - case AudioChannelFormat::DUAL_44100: - expected_samples_per_frame = 2; - data.m_current.reset(new StreamHistoryTracker(data.m_logger, data.m_window, 1, 44100, data.m_has_video)); - return; - case AudioChannelFormat::DUAL_48000: - case AudioChannelFormat::MONO_96000: - case AudioChannelFormat::INTERLEAVE_LR_96000: - case AudioChannelFormat::INTERLEAVE_RL_96000: - expected_samples_per_frame = 2; - data.m_current.reset(new StreamHistoryTracker(data.m_logger, data.m_window, 2, 48000, data.m_has_video)); - return; - default: - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Invalid AudioFormat: " + std::to_string((size_t)data.m_audio_format) - ); - } -} -void StreamHistorySession::pre_input_change(){ -// cout << "pre_input_change()" << endl; - Data& data = *m_data; - WriteSpinLock lg(data.m_lock); - clear(); -} -void StreamHistorySession::post_input_change(const std::string& file, const AudioDeviceInfo& device, AudioChannelFormat format){ -// cout << "post_input_change()" << endl; - Data& data = *m_data; - WriteSpinLock lg(data.m_lock); - if (device){ - data.m_audio_format = format; - }else{ - data.m_audio_format = AudioChannelFormat::NONE; - } - initialize(); -} -void StreamHistorySession::pre_shutdown(){ -// cout << "pre_shutdown()" << endl; - Data& data = *m_data; - WriteSpinLock lg(data.m_lock); - clear(); -} -void StreamHistorySession::post_shutdown(){ -// cout << "post_shutdown()" << endl; - Data& data = *m_data; - WriteSpinLock lg(data.m_lock); - data.m_has_video = false; - initialize(); -} -void StreamHistorySession::post_startup(VideoSource* source){ - Data& data = *m_data; - WriteSpinLock lg(data.m_lock); - data.m_has_video = source != nullptr; - initialize(); -} -void StreamHistorySession::pre_resolution_change(Resolution resolution){ -// cout << "pre_resolution_change()" << endl; - Data& data = *m_data; - WriteSpinLock lg(data.m_lock); - clear(); -} -void StreamHistorySession::post_resolution_change(Resolution resolution){ -// cout << "post_resolution_change()" << endl; - Data& data = *m_data; - WriteSpinLock lg(data.m_lock); - initialize(); -} - - - - - - - -} +/* Stream History Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" +#include "CommonFramework/Recording/StreamHistoryOption.h" + +#if (QT_VERSION_MAJOR == 6) && (QT_VERSION_MINOR >= 8) +//#include "StreamHistoryTracker_SaveFrames.h" +//#include "StreamHistoryTracker_RecordOnTheFly.h" +#include "StreamHistoryTracker_ParallelStreams.h" +#else +#include "StreamHistoryTracker_Null.h" +#endif + + +#include "StreamHistorySession.h" + + + +namespace PokemonAutomation{ + + + + + +struct StreamHistorySession::Data{ + Logger& m_logger; + mutable SpinLock m_lock; + std::chrono::seconds m_window; + AudioChannelFormat m_audio_format; + bool m_has_video; + std::shared_ptr m_current; + + Data(Logger& logger) + : m_logger(logger) + , m_window(GlobalSettings::instance().STREAM_HISTORY->HISTORY_SECONDS) + , m_audio_format(AudioChannelFormat::NONE) + , m_has_video(false) + {} +}; + + + + +StreamHistorySession::~StreamHistorySession() = default; +StreamHistorySession::StreamHistorySession(Logger& logger) + : AudioFloatStreamListener(1) + , m_data(CONSTRUCT_TOKEN, logger) +{} +void StreamHistorySession::start(AudioChannelFormat format, bool has_video){ + Data& data = *m_data; + WriteSpinLock lg(data.m_lock); + if (!data.m_current){ + data.m_audio_format = format; + data.m_has_video = has_video; + initialize(); + } +} + + +#if 0 +class HistorySaverThread : public QThread{ +public: + HistorySaverThread(StreamHistoryTracker& tracker, const std::string& filename) + : m_tracker(tracker) + , m_filename(filename) + {} + ~HistorySaverThread(){ + quit(); + wait(); + } + bool save(){ + start(); + quit(); + wait(); + return m_success; + } + virtual void run() override{ +// m_success = m_tracker.save(m_logger, m_filename); + m_success = m_tracker.save(m_filename); + exec(); + } + +private: + StreamHistoryTracker& m_tracker; + const std::string& m_filename; + bool m_success = false; +}; +#endif + +bool StreamHistorySession::save(const std::string& filename) const{ + // This will be coming in from random threads. It will block until the save + // is finished or failed. + + const Data& data = *m_data; + + // Get an owning reference to the current tracker. + // This will allow us to promptly release the lock and unblock the UI from + // changing the streams (which will wipe the history). + std::shared_ptr tracker; + { + WriteSpinLock lg(data.m_lock); + if (!data.m_current){ + data.m_logger.log("Cannot save stream history: Stream history is not enabled.", COLOR_RED); + return false; + } + tracker = data.m_current; + } + +// tracker->save(m_logger, filename); +// HistorySaverThread saver(*tracker, filename); +// return saver.save(); + + return tracker->save(filename); +} +void StreamHistorySession::on_samples(const float* samples, size_t frames){ + Data& data = *m_data; + WriteSpinLock lg(data.m_lock); + if (data.m_current){ + data.m_current->on_samples(samples, frames); + } +} +void StreamHistorySession::on_frame(std::shared_ptr frame){ + Data& data = *m_data; + WriteSpinLock lg(data.m_lock); + if (data.m_current){ + data.m_current->on_frame(std::move(frame)); + } +} + + +void StreamHistorySession::clear(){ +// cout << "clear()" << endl; + + // Must call under lock. + Data& data = *m_data; + data.m_logger.log("Clearing stream history...", COLOR_ORANGE); + data.m_current.reset(); +// expected_samples_per_frame = 0; +// data.m_audio_format = AudioChannelFormat::NONE; +// data.m_has_video = false; +} +void StreamHistorySession::initialize(){ + if (!GlobalSettings::instance().STREAM_HISTORY->enabled()){ + return; + } + + // Must call under lock. + Data& data = *m_data; + data.m_logger.log("Starting stream history...", COLOR_ORANGE); + +// cout << "video = " << data.m_has_video << endl; + + switch (data.m_audio_format){ + case AudioChannelFormat::NONE: + expected_samples_per_frame = 0; + data.m_current.reset(new StreamHistoryTracker(data.m_logger, data.m_window, 0, 0, data.m_has_video)); + return; + case AudioChannelFormat::MONO_48000: + expected_samples_per_frame = 1; + data.m_current.reset(new StreamHistoryTracker(data.m_logger, data.m_window, 1, 48000, data.m_has_video)); + return; + case AudioChannelFormat::DUAL_44100: + expected_samples_per_frame = 2; + data.m_current.reset(new StreamHistoryTracker(data.m_logger, data.m_window, 1, 44100, data.m_has_video)); + return; + case AudioChannelFormat::DUAL_48000: + case AudioChannelFormat::MONO_96000: + case AudioChannelFormat::INTERLEAVE_LR_96000: + case AudioChannelFormat::INTERLEAVE_RL_96000: + expected_samples_per_frame = 2; + data.m_current.reset(new StreamHistoryTracker(data.m_logger, data.m_window, 2, 48000, data.m_has_video)); + return; + default: + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Invalid AudioFormat: " + std::to_string((size_t)data.m_audio_format) + ); + } +} +void StreamHistorySession::pre_input_change(){ +// cout << "pre_input_change()" << endl; + Data& data = *m_data; + WriteSpinLock lg(data.m_lock); + clear(); +} +void StreamHistorySession::post_input_change(const std::string& file, const AudioDeviceInfo& device, AudioChannelFormat format){ +// cout << "post_input_change()" << endl; + Data& data = *m_data; + WriteSpinLock lg(data.m_lock); + if (device){ + data.m_audio_format = format; + }else{ + data.m_audio_format = AudioChannelFormat::NONE; + } + initialize(); +} +void StreamHistorySession::pre_shutdown(){ +// cout << "pre_shutdown()" << endl; + Data& data = *m_data; + WriteSpinLock lg(data.m_lock); + clear(); +} +void StreamHistorySession::post_shutdown(){ +// cout << "post_shutdown()" << endl; + Data& data = *m_data; + WriteSpinLock lg(data.m_lock); + data.m_has_video = false; + initialize(); +} +void StreamHistorySession::post_startup(VideoSource* source){ + Data& data = *m_data; + WriteSpinLock lg(data.m_lock); + data.m_has_video = source != nullptr; + initialize(); +} +void StreamHistorySession::pre_resolution_change(Resolution resolution){ +// cout << "pre_resolution_change()" << endl; + Data& data = *m_data; + WriteSpinLock lg(data.m_lock); + clear(); +} +void StreamHistorySession::post_resolution_change(Resolution resolution){ +// cout << "post_resolution_change()" << endl; + Data& data = *m_data; + WriteSpinLock lg(data.m_lock); + initialize(); +} + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Recording/StreamHistorySession.h b/SerialPrograms/Source/CommonFramework/Recording/StreamHistorySession.h index 91df2eb15a..7e01968428 100644 --- a/SerialPrograms/Source/CommonFramework/Recording/StreamHistorySession.h +++ b/SerialPrograms/Source/CommonFramework/Recording/StreamHistorySession.h @@ -1,58 +1,58 @@ -/* Stream History Session - * - * From: https://github.com/PokemonAutomation/ - * - * Capture the last X seconds of audio and video. - * - */ - -#ifndef PokemonAutomation_StreamHistorySession_H -#define PokemonAutomation_StreamHistorySession_H - -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Containers/Pimpl.h" -#include "CommonFramework/AudioPipeline/AudioSession.h" -#include "CommonFramework/VideoPipeline/VideoSession.h" - -namespace PokemonAutomation{ - - -class StreamHistorySession - : public AudioFloatStreamListener - , public VideoFrameListener - , public AudioSession::StateListener - , public VideoSession::StateListener -{ -public: - ~StreamHistorySession(); - StreamHistorySession(Logger& logger); - void start(AudioChannelFormat format, bool has_video); - bool save(const std::string& filename) const; - -public: - virtual void on_samples(const float* data, size_t frames) override; - virtual void on_frame(std::shared_ptr frame) override; - -public: - virtual void pre_input_change() override; - virtual void post_input_change(const std::string& file, const AudioDeviceInfo& device, AudioChannelFormat format) override; - - virtual void pre_shutdown() override; - virtual void post_shutdown() override; - virtual void post_startup(VideoSource* source) override; - virtual void pre_resolution_change(Resolution resolution) override; - virtual void post_resolution_change(Resolution resolution) override; - -private: - void clear(); - void initialize(); - -private: - struct Data; - Pimpl m_data; -}; - - - -} -#endif +/* Stream History Session + * + * From: https://github.com/PokemonAutomation/ + * + * Capture the last X seconds of audio and video. + * + */ + +#ifndef PokemonAutomation_StreamHistorySession_H +#define PokemonAutomation_StreamHistorySession_H + +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Containers/Pimpl.h" +#include "CommonFramework/AudioPipeline/AudioSession.h" +#include "CommonFramework/VideoPipeline/VideoSession.h" + +namespace PokemonAutomation{ + + +class StreamHistorySession + : public AudioFloatStreamListener + , public VideoFrameListener + , public AudioSession::StateListener + , public VideoSession::StateListener +{ +public: + ~StreamHistorySession(); + StreamHistorySession(Logger& logger); + void start(AudioChannelFormat format, bool has_video); + bool save(const std::string& filename) const; + +public: + virtual void on_samples(const float* data, size_t frames) override; + virtual void on_frame(std::shared_ptr frame) override; + +public: + virtual void pre_input_change() override; + virtual void post_input_change(const std::string& file, const AudioDeviceInfo& device, AudioChannelFormat format) override; + + virtual void pre_shutdown() override; + virtual void post_shutdown() override; + virtual void post_startup(VideoSource* source) override; + virtual void pre_resolution_change(Resolution resolution) override; + virtual void post_resolution_change(Resolution resolution) override; + +private: + void clear(); + void initialize(); + +private: + struct Data; + Pimpl m_data; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_Null.h b/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_Null.h index 55b1748ff6..cf0012c387 100644 --- a/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_Null.h +++ b/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_Null.h @@ -1,47 +1,47 @@ -/* Stream History Tracker - * - * From: https://github.com/PokemonAutomation/ - * - * A null implementation that will compile before Qt 6.8. - * - */ - -#ifndef PokemonAutomation_StreamHistoryTracker_Null_H -#define PokemonAutomation_StreamHistoryTracker_Null_H - -#include "Common/Compiler.h" -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" - -namespace PokemonAutomation{ - - -class StreamHistoryTracker{ -public: - StreamHistoryTracker( - Logger& logger, - std::chrono::seconds window, - size_t audio_samples_per_frame, - size_t audio_frames_per_second, - bool has_video - ) - : m_logger(logger) - {} - void set_window(std::chrono::seconds window){} - - bool save(const std::string& filename) const{ - m_logger.log("Cannot save stream history: Not implemented.", COLOR_RED); - return false; - } - -public: - void on_samples(const float* data, size_t frames){} - void on_frame(std::shared_ptr frame){} - -private: - Logger& m_logger; -}; - - -} -#endif +/* Stream History Tracker + * + * From: https://github.com/PokemonAutomation/ + * + * A null implementation that will compile before Qt 6.8. + * + */ + +#ifndef PokemonAutomation_StreamHistoryTracker_Null_H +#define PokemonAutomation_StreamHistoryTracker_Null_H + +#include "Common/Compiler.h" +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" + +namespace PokemonAutomation{ + + +class StreamHistoryTracker{ +public: + StreamHistoryTracker( + Logger& logger, + std::chrono::seconds window, + size_t audio_samples_per_frame, + size_t audio_frames_per_second, + bool has_video + ) + : m_logger(logger) + {} + void set_window(std::chrono::seconds window){} + + bool save(const std::string& filename) const{ + m_logger.log("Cannot save stream history: Not implemented.", COLOR_RED); + return false; + } + +public: + void on_samples(const float* data, size_t frames){} + void on_frame(std::shared_ptr frame){} + +private: + Logger& m_logger; +}; + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_ParallelStreams.h b/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_ParallelStreams.h index 12c14610ed..42c2a75620 100644 --- a/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_ParallelStreams.h +++ b/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_ParallelStreams.h @@ -1,181 +1,181 @@ -/* Stream History Tracker - * - * From: https://github.com/PokemonAutomation/ - * - * Implement by running two recordings in parallel. - * When each reaches 2X seconds, delete it start over. - * Both recordings are offset by X seconds - thus guaranteeing - * that the last X seconds are available. - * - */ - -#ifndef PokemonAutomation_StreamHistoryTracker_ParallelStreams_H -#define PokemonAutomation_StreamHistoryTracker_ParallelStreams_H - -#include -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Qt/Redispatch.h" -#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" -#include "StreamRecorder.h" - -// REMOVE -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - - - - - - - - -class StreamHistoryTracker{ - static constexpr size_t PARALLEL_RECORDINGS = 2; - -public: - StreamHistoryTracker( - Logger& logger, - std::chrono::seconds window, - size_t audio_samples_per_frame, - size_t audio_frames_per_second, - bool has_video - ) - : m_logger(logger) - , m_window(window) // REMOVE -// , m_window(100) - , m_audio_samples_per_frame(audio_samples_per_frame) - , m_audio_frames_per_second(audio_frames_per_second) - , m_has_video(has_video) - { - update_streams(current_time()); - } - void set_window(std::chrono::seconds window){ - SpinLockGuard lg(m_lock); - m_window = window; - update_streams(current_time()); - } - - bool save(const std::string& filename){ - std::unique_ptr recording; - { - SpinLockGuard lg(m_lock); - if (m_recordings.empty()){ - m_logger.log("Cannot save stream history. Recording is not enabled.", COLOR_RED); - return false; - } - - m_logger.log("Saving stream history...", COLOR_BLUE); - - auto iter = m_recordings.begin(); - recording = std::move(iter->second); - m_recordings.erase(iter); - update_streams(current_time()); - } - return recording->stop_and_save(filename); - } - - - void on_samples(const float* samples, size_t frames){ - WallClock now = current_time(); - SpinLockGuard lg(m_lock); - for (auto& item : m_recordings){ - item.second->push_samples(now, samples, frames); - } - update_streams(now); - } - void on_frame(std::shared_ptr frame){ - WallClock now = current_time(); - SpinLockGuard lg(m_lock); - for (auto& item : m_recordings){ - item.second->push_frame(frame); - } - update_streams(now); - } - - -private: - void update_streams(WallClock current_time){ -// dispatch_to_main_thread([this, current_time]{ - internal_update_streams(current_time); -// }); - } - void internal_update_streams(WallClock current_time){ -// cout << "streams = " << m_recordings.size() << endl; - - // Must call under the lock. - WallClock threshold = current_time - m_window; - - // Clear any streams that are not needed any more. - // A stream is not needed anymore when there is a newer stream that - // is at least "m_window" long. - if (PARALLEL_RECORDINGS >= 2){ - while (m_recordings.size() >= PARALLEL_RECORDINGS){ - auto first = m_recordings.begin(); - auto second = first; - ++second; - if (second->first < threshold){ -// cout << "removing recording..." << endl; - m_recordings.erase(first); - }else{ - break; - } - } - } - - // If all recordings start in the future, reset everything. - if (!m_recordings.empty() && m_recordings.begin()->first > current_time){ - m_recordings.clear(); - } - - // Add recordings until we've reached the desired amount. - while (m_recordings.size() < PARALLEL_RECORDINGS){ -// cout << "adding recording = " << m_recordings.size() << endl; - // If no recordings are live, start it now. - // Otherwise, schedule to start "m_interval" after the start - // of the newest recording. - WallClock start_time = m_recordings.empty() - ? current_time - : m_recordings.rbegin()->first + m_window; - -// cout << std::chrono::duration_cast(start_time - current_time).count() / 1000. << endl; - - m_recordings.emplace( - std::piecewise_construct, - std::forward_as_tuple(start_time), - std::forward_as_tuple(new StreamRecording( - m_logger, std::chrono::milliseconds(500), - start_time, - m_audio_samples_per_frame, - m_audio_frames_per_second, - m_has_video - )) - ); - } - } - - -private: - Logger& m_logger; - mutable SpinLock m_lock; - std::chrono::milliseconds m_window; - const size_t m_audio_samples_per_frame; - const size_t m_audio_frames_per_second; - const bool m_has_video; - std::map> m_recordings; -}; - - - - - - - - - -} -#endif +/* Stream History Tracker + * + * From: https://github.com/PokemonAutomation/ + * + * Implement by running two recordings in parallel. + * When each reaches 2X seconds, delete it start over. + * Both recordings are offset by X seconds - thus guaranteeing + * that the last X seconds are available. + * + */ + +#ifndef PokemonAutomation_StreamHistoryTracker_ParallelStreams_H +#define PokemonAutomation_StreamHistoryTracker_ParallelStreams_H + +#include +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Qt/Redispatch.h" +#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" +#include "StreamRecorder.h" + +// REMOVE +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + + + + + + + + +class StreamHistoryTracker{ + static constexpr size_t PARALLEL_RECORDINGS = 2; + +public: + StreamHistoryTracker( + Logger& logger, + std::chrono::seconds window, + size_t audio_samples_per_frame, + size_t audio_frames_per_second, + bool has_video + ) + : m_logger(logger) + , m_window(window) // REMOVE +// , m_window(100) + , m_audio_samples_per_frame(audio_samples_per_frame) + , m_audio_frames_per_second(audio_frames_per_second) + , m_has_video(has_video) + { + update_streams(current_time()); + } + void set_window(std::chrono::seconds window){ + SpinLockGuard lg(m_lock); + m_window = window; + update_streams(current_time()); + } + + bool save(const std::string& filename){ + std::unique_ptr recording; + { + SpinLockGuard lg(m_lock); + if (m_recordings.empty()){ + m_logger.log("Cannot save stream history. Recording is not enabled.", COLOR_RED); + return false; + } + + m_logger.log("Saving stream history...", COLOR_BLUE); + + auto iter = m_recordings.begin(); + recording = std::move(iter->second); + m_recordings.erase(iter); + update_streams(current_time()); + } + return recording->stop_and_save(filename); + } + + + void on_samples(const float* samples, size_t frames){ + WallClock now = current_time(); + SpinLockGuard lg(m_lock); + for (auto& item : m_recordings){ + item.second->push_samples(now, samples, frames); + } + update_streams(now); + } + void on_frame(std::shared_ptr frame){ + WallClock now = current_time(); + SpinLockGuard lg(m_lock); + for (auto& item : m_recordings){ + item.second->push_frame(frame); + } + update_streams(now); + } + + +private: + void update_streams(WallClock current_time){ +// dispatch_to_main_thread([this, current_time]{ + internal_update_streams(current_time); +// }); + } + void internal_update_streams(WallClock current_time){ +// cout << "streams = " << m_recordings.size() << endl; + + // Must call under the lock. + WallClock threshold = current_time - m_window; + + // Clear any streams that are not needed any more. + // A stream is not needed anymore when there is a newer stream that + // is at least "m_window" long. + if (PARALLEL_RECORDINGS >= 2){ + while (m_recordings.size() >= PARALLEL_RECORDINGS){ + auto first = m_recordings.begin(); + auto second = first; + ++second; + if (second->first < threshold){ +// cout << "removing recording..." << endl; + m_recordings.erase(first); + }else{ + break; + } + } + } + + // If all recordings start in the future, reset everything. + if (!m_recordings.empty() && m_recordings.begin()->first > current_time){ + m_recordings.clear(); + } + + // Add recordings until we've reached the desired amount. + while (m_recordings.size() < PARALLEL_RECORDINGS){ +// cout << "adding recording = " << m_recordings.size() << endl; + // If no recordings are live, start it now. + // Otherwise, schedule to start "m_interval" after the start + // of the newest recording. + WallClock start_time = m_recordings.empty() + ? current_time + : m_recordings.rbegin()->first + m_window; + +// cout << std::chrono::duration_cast(start_time - current_time).count() / 1000. << endl; + + m_recordings.emplace( + std::piecewise_construct, + std::forward_as_tuple(start_time), + std::forward_as_tuple(new StreamRecording( + m_logger, std::chrono::milliseconds(500), + start_time, + m_audio_samples_per_frame, + m_audio_frames_per_second, + m_has_video + )) + ); + } + } + + +private: + Logger& m_logger; + mutable SpinLock m_lock; + std::chrono::milliseconds m_window; + const size_t m_audio_samples_per_frame; + const size_t m_audio_frames_per_second; + const bool m_has_video; + std::map> m_recordings; +}; + + + + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_RecordOnTheFly.h b/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_RecordOnTheFly.h index c6fdca0f6a..1ad030c774 100644 --- a/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_RecordOnTheFly.h +++ b/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_RecordOnTheFly.h @@ -1,192 +1,192 @@ -/* Stream History Tracker - * - * From: https://github.com/PokemonAutomation/ - * - * Implement by recording in real-time. - * - */ - -#ifndef PokemonAutomation_StreamHistoryTracker_RecordOnTheFly_H -#define PokemonAutomation_StreamHistoryTracker_RecordOnTheFly_H - -#include -#include -#include -#include -//#include -#include -#include -#include -#include -#include -#include "Common/Cpp/LifetimeSanitizer.h" -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Concurrency/SpinPause.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - -class RollingStream : public QIODevice{ -public: - ~RollingStream(){ - waitForBytesWritten(-1); -// cout << "~RollingStream()" << endl; - } - RollingStream(){ - setOpenMode(QIODeviceBase::WriteOnly); - } - virtual qint64 readData(char* data, qint64 maxlen){ return 0; } - virtual qint64 writeData(const char* data, qint64 len){ - auto scope_check = m_sanitizer.check_scope(); - m_bytes += len; - cout << "total = " << m_bytes << ", current = " << len << endl; - return len; - } - -private: - uint64_t m_bytes = 0; - - LifetimeSanitizer m_sanitizer; -}; - - - -class StreamHistoryTracker{ -public: - ~StreamHistoryTracker(); - StreamHistoryTracker( - size_t audio_samples_per_frame, - size_t audio_frames_per_second, - std::chrono::seconds window - ); - void set_window(std::chrono::seconds window); - - bool save(Logger& logger, const std::string& filename) const; - -public: -// void push_frame(QVideoFrame frame); - - void on_samples(const float* data, size_t frames); - void on_frame(std::shared_ptr frame); - -private: -// void clear_old(); - -private: - mutable SpinLock m_lock; - std::chrono::seconds m_window; - - const size_t m_audio_samples_per_frame; -// const size_t m_audio_frames_per_second; -// const size_t m_audio_samples_per_second; -// const double m_microseconds_per_sample; - -// mutable std::mutex m_lock; -// std::condition_variable m_cv; - - RollingStream m_stream; - - QAudioFormat m_audio_format; - QAudioBufferInput m_audio_input; - QVideoFrameInput m_video_input; - QMediaCaptureSession m_session; - - QMediaRecorder m_recorder; -}; - - -StreamHistoryTracker::~StreamHistoryTracker(){ - m_recorder.stop(); - while (m_recorder.recorderState() != QMediaRecorder::StoppedState){ -// cout << "StreamHistoryTracker: process" << endl; - try{ - QCoreApplication::processEvents(); - pause(); - }catch (...){} - } -// cout << "~StreamHistoryTracker()" << endl; -} -StreamHistoryTracker::StreamHistoryTracker( - size_t audio_samples_per_frame, - size_t audio_frames_per_second, - std::chrono::seconds window -) - : m_window(window) - , m_audio_samples_per_frame(audio_samples_per_frame) -// , m_audio_frames_per_second(audio_frames_per_second) -// , m_audio_samples_per_second(audio_samples_per_frame * audio_frames_per_second) -// , m_microseconds_per_sample(1. / (m_audio_samples_per_second * 1000000.)) -{ - m_audio_format.setChannelCount((int)audio_samples_per_frame); - m_audio_format.setChannelConfig(audio_samples_per_frame == 1 ? QAudioFormat::ChannelConfigMono : QAudioFormat::ChannelConfigStereo); - m_audio_format.setSampleRate((int)audio_frames_per_second); - m_audio_format.setSampleFormat(QAudioFormat::Float); - - m_session.setAudioBufferInput(&m_audio_input); - m_session.setVideoFrameInput(&m_video_input); - m_session.setRecorder(&m_recorder); - m_recorder.setMediaFormat(QMediaFormat::MPEG4); - m_recorder.setQuality(QMediaRecorder::HighQuality); - -#if 0 - m_recorder.connect( - &m_recorder, &QMediaRecorder::recorderStateChanged, - &m_recorder, [](QMediaRecorder::RecorderState state){ - - } - ); -#endif - - QFileInfo file(QString::fromStdString("capture-" + now_to_filestring() + ".mp4")); -#if 1 - m_recorder.setOutputLocation( - QUrl::fromLocalFile(file.absoluteFilePath()) - ); -#else - m_recorder.setOutputDevice(&m_stream); -#endif - - m_recorder.record(); -} - -void StreamHistoryTracker::set_window(std::chrono::seconds window){ - WriteSpinLock lg(m_lock); - m_window = window; -} - - -void StreamHistoryTracker::on_samples(const float* samples, size_t frames){ - if (frames == 0){ - return; - } - QByteArray buffer((const char*)samples, m_audio_samples_per_frame * frames * sizeof(float)); - QAudioBuffer audio_buffer(buffer, m_audio_format); - m_audio_input.sendAudioBuffer(audio_buffer); -} -void StreamHistoryTracker::on_frame(std::shared_ptr frame){ - m_video_input.sendVideoFrame(frame->frame); -} - -bool StreamHistoryTracker::save(Logger& logger, const std::string& filename) const{ - logger.log("Cannot save stream history: Not implemented.", COLOR_RED); - - // TODO - - return false; -} - - - - - - - -} -#endif +/* Stream History Tracker + * + * From: https://github.com/PokemonAutomation/ + * + * Implement by recording in real-time. + * + */ + +#ifndef PokemonAutomation_StreamHistoryTracker_RecordOnTheFly_H +#define PokemonAutomation_StreamHistoryTracker_RecordOnTheFly_H + +#include +#include +#include +#include +//#include +#include +#include +#include +#include +#include +#include "Common/Cpp/LifetimeSanitizer.h" +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Concurrency/SpinPause.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + +class RollingStream : public QIODevice{ +public: + ~RollingStream(){ + waitForBytesWritten(-1); +// cout << "~RollingStream()" << endl; + } + RollingStream(){ + setOpenMode(QIODeviceBase::WriteOnly); + } + virtual qint64 readData(char* data, qint64 maxlen){ return 0; } + virtual qint64 writeData(const char* data, qint64 len){ + auto scope_check = m_sanitizer.check_scope(); + m_bytes += len; + cout << "total = " << m_bytes << ", current = " << len << endl; + return len; + } + +private: + uint64_t m_bytes = 0; + + LifetimeSanitizer m_sanitizer; +}; + + + +class StreamHistoryTracker{ +public: + ~StreamHistoryTracker(); + StreamHistoryTracker( + size_t audio_samples_per_frame, + size_t audio_frames_per_second, + std::chrono::seconds window + ); + void set_window(std::chrono::seconds window); + + bool save(Logger& logger, const std::string& filename) const; + +public: +// void push_frame(QVideoFrame frame); + + void on_samples(const float* data, size_t frames); + void on_frame(std::shared_ptr frame); + +private: +// void clear_old(); + +private: + mutable SpinLock m_lock; + std::chrono::seconds m_window; + + const size_t m_audio_samples_per_frame; +// const size_t m_audio_frames_per_second; +// const size_t m_audio_samples_per_second; +// const double m_microseconds_per_sample; + +// mutable std::mutex m_lock; +// std::condition_variable m_cv; + + RollingStream m_stream; + + QAudioFormat m_audio_format; + QAudioBufferInput m_audio_input; + QVideoFrameInput m_video_input; + QMediaCaptureSession m_session; + + QMediaRecorder m_recorder; +}; + + +StreamHistoryTracker::~StreamHistoryTracker(){ + m_recorder.stop(); + while (m_recorder.recorderState() != QMediaRecorder::StoppedState){ +// cout << "StreamHistoryTracker: process" << endl; + try{ + QCoreApplication::processEvents(); + pause(); + }catch (...){} + } +// cout << "~StreamHistoryTracker()" << endl; +} +StreamHistoryTracker::StreamHistoryTracker( + size_t audio_samples_per_frame, + size_t audio_frames_per_second, + std::chrono::seconds window +) + : m_window(window) + , m_audio_samples_per_frame(audio_samples_per_frame) +// , m_audio_frames_per_second(audio_frames_per_second) +// , m_audio_samples_per_second(audio_samples_per_frame * audio_frames_per_second) +// , m_microseconds_per_sample(1. / (m_audio_samples_per_second * 1000000.)) +{ + m_audio_format.setChannelCount((int)audio_samples_per_frame); + m_audio_format.setChannelConfig(audio_samples_per_frame == 1 ? QAudioFormat::ChannelConfigMono : QAudioFormat::ChannelConfigStereo); + m_audio_format.setSampleRate((int)audio_frames_per_second); + m_audio_format.setSampleFormat(QAudioFormat::Float); + + m_session.setAudioBufferInput(&m_audio_input); + m_session.setVideoFrameInput(&m_video_input); + m_session.setRecorder(&m_recorder); + m_recorder.setMediaFormat(QMediaFormat::MPEG4); + m_recorder.setQuality(QMediaRecorder::HighQuality); + +#if 0 + m_recorder.connect( + &m_recorder, &QMediaRecorder::recorderStateChanged, + &m_recorder, [](QMediaRecorder::RecorderState state){ + + } + ); +#endif + + QFileInfo file(QString::fromStdString("capture-" + now_to_filestring() + ".mp4")); +#if 1 + m_recorder.setOutputLocation( + QUrl::fromLocalFile(file.absoluteFilePath()) + ); +#else + m_recorder.setOutputDevice(&m_stream); +#endif + + m_recorder.record(); +} + +void StreamHistoryTracker::set_window(std::chrono::seconds window){ + WriteSpinLock lg(m_lock); + m_window = window; +} + + +void StreamHistoryTracker::on_samples(const float* samples, size_t frames){ + if (frames == 0){ + return; + } + QByteArray buffer((const char*)samples, m_audio_samples_per_frame * frames * sizeof(float)); + QAudioBuffer audio_buffer(buffer, m_audio_format); + m_audio_input.sendAudioBuffer(audio_buffer); +} +void StreamHistoryTracker::on_frame(std::shared_ptr frame){ + m_video_input.sendVideoFrame(frame->frame); +} + +bool StreamHistoryTracker::save(Logger& logger, const std::string& filename) const{ + logger.log("Cannot save stream history: Not implemented.", COLOR_RED); + + // TODO + + return false; +} + + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_SaveFrames.h b/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_SaveFrames.h index 5fb326c9e2..df8334818a 100644 --- a/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_SaveFrames.h +++ b/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_SaveFrames.h @@ -1,312 +1,312 @@ -/* Stream History Tracker - * - * From: https://github.com/PokemonAutomation/ - * - * Implement by saving the last X seconds of frames. This is currently not - * viable because the QVideoFrames are uncompressed. - * - */ - -#ifndef PokemonAutomation_StreamHistoryTracker_SaveFrames_H -#define PokemonAutomation_StreamHistoryTracker_SaveFrames_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" - - -//#include -//using std::cout; -//using std::endl; - - -namespace PokemonAutomation{ - - -struct AudioBlock{ - WallClock timestamp; - std::vector samples; - - AudioBlock(const AudioBlock&) = delete; - void operator=(const AudioBlock&) = delete; - - AudioBlock(WallClock p_timestamp, const float* p_samples, size_t p_count) - : timestamp(p_timestamp) - , samples(p_samples, p_samples + p_count) - {} -}; - - -class StreamHistoryTracker{ -public: - StreamHistoryTracker( - size_t audio_samples_per_frame, - size_t audio_frames_per_second, - std::chrono::seconds window - ); - void set_window(std::chrono::seconds window); - - bool save(Logger& logger, const std::string& filename) const; - -public: - void on_samples(const float* data, size_t frames); - void on_frame(std::shared_ptr frame); - -private: - void clear_old(); - -private: - mutable SpinLock m_lock; - std::chrono::seconds m_window; - - const size_t m_audio_samples_per_frame; - const size_t m_audio_frames_per_second; - const size_t m_audio_samples_per_second; - const double m_microseconds_per_sample; - - // We use shared_ptr here so it's fast to snapshot when we need to copy - // everything asynchronously. - std::deque> m_audio; - std::deque> m_frames; -}; - - - - -StreamHistoryTracker::StreamHistoryTracker( - size_t audio_samples_per_frame, - size_t audio_frames_per_second, - std::chrono::seconds window -) - : m_window(window) - , m_audio_samples_per_frame(audio_samples_per_frame) - , m_audio_frames_per_second(audio_frames_per_second) - , m_audio_samples_per_second(audio_samples_per_frame * audio_frames_per_second) - , m_microseconds_per_sample(1. / (m_audio_samples_per_second * 1000000.)) -{} - -void StreamHistoryTracker::set_window(std::chrono::seconds window){ - WriteSpinLock lg(m_lock); - m_window = window; - clear_old(); -} -void StreamHistoryTracker::on_samples(const float* samples, size_t frames){ - if (frames == 0){ - return; - } - WallClock now = current_time(); - WriteSpinLock lg(m_lock); -// cout << "on_samples() = " << m_audio.size() << endl; - m_audio.emplace_back(std::make_shared( - now, samples, frames * m_audio_samples_per_frame - )); - clear_old(); -} -void StreamHistoryTracker::on_frame(std::shared_ptr frame){ - // TODO: Find a more efficient way to buffer the frames. - // It takes almost 10GB of memory to store 30 seconds of QVideoFrames - // due to them caching uncompressed bitmaps. -// return; // TODO - - WriteSpinLock lg(m_lock); -// cout << "on_frame() = " << m_frames.size() << endl; - m_frames.emplace_back(std::move(frame)); - clear_old(); -} - - - -void StreamHistoryTracker::clear_old(){ - // Must call under lock. - WallClock now = current_time(); - WallClock threshold = now - m_window; - -// WriteSpinLock lg(m_lock); -// cout << "enter" << endl; - while (!m_audio.empty()){ -// cout << "audio.size() = " << m_audio.size() << endl; - AudioBlock& block = *m_audio.front(); - - WallClock end_block = block.timestamp; - end_block += std::chrono::microseconds( - static_cast((double)block.samples.size() * m_microseconds_per_sample) - ); - - if (end_block < threshold){ - m_audio.pop_front(); - }else{ - break; - } - } -// cout << "exit" << endl; - - while (!m_frames.empty()){ - if (m_frames.front()->timestamp < threshold){ - m_frames.pop_front(); - }else{ - break; - } - } -} - - - - - -bool StreamHistoryTracker::save(Logger& logger, const std::string& filename) const{ - logger.log("Saving stream history...", COLOR_BLUE); - - std::deque> audio; - std::deque> frames; - { - // Fast copy the current state of the stream. - WriteSpinLock lg(m_lock); - if (m_audio.empty() && m_frames.empty()){ - return false; - } - audio = m_audio; - frames = m_frames; - } - - // Now that the lock is released, we can take our time encoding it. - - // TODO - -#if 0 - WallClock start = WallClock::max(); - if (!audio.empty()){ - start = std::min(start, audio.front()->timestamp); - } - if (!frames.empty()){ - start = std::min(start, frames.front()->timestamp); - } - -#endif - - -// run_on_main_thread_and_wait([&]{ - - QAudioFormat audio_format; - audio_format.setChannelCount((int)m_audio_samples_per_frame); - audio_format.setChannelConfig(m_audio_samples_per_frame == 1 ? QAudioFormat::ChannelConfigMono : QAudioFormat::ChannelConfigStereo); - audio_format.setSampleRate((int)m_audio_frames_per_second); - audio_format.setSampleFormat(QAudioFormat::Float); - -// cout << "audio_format = " << audio_format.isValid() << endl; - - QAudioBufferInput audio_input; - QVideoFrameInput video_input; - -// cout << "audio = " << audio.size() << endl; -// cout << "frames = " << frames.size() << endl; - - QMediaCaptureSession session; - QMediaRecorder recorder; - session.setAudioBufferInput(&audio_input); - session.setVideoFrameInput(&video_input); - session.setRecorder(&recorder); -#if 1 - recorder.setMediaFormat(QMediaFormat::MPEG4); -#else - QMediaFormat video_format; - video_format.setAudioCodec(QMediaFormat::AudioCodec::AAC); -// video_format.setVideoCodec(QMediaFormat::VideoCodec::H264); - video_format.setFileFormat(QMediaFormat::MPEG4); - recorder.setMediaFormat(video_format); -#endif - recorder.setQuality(QMediaRecorder::NormalQuality); - - QFileInfo file(QString::fromStdString(filename)); - recorder.setOutputLocation( - QUrl::fromLocalFile(file.absoluteFilePath()) - ); - - recorder.record(); - - WallClock last_change = current_time(); - QAudioBuffer audio_buffer; - bool success = true; - while (audio_buffer.isValid() || !frames.empty()){ -#if 1 - while (true){ - if (frames.empty()){ -// video_input.sendVideoFrame(QVideoFrame()); -// session.setVideoFrameInput(nullptr); - break; - } - if (!video_input.sendVideoFrame((*frames.begin())->frame)){ -// cout << "Failed Video: " << frames.size() << endl; - break; - } - frames.pop_front(); - last_change = current_time(); -// cout << "Pushed Video: " << frames.size() << endl; - } -#endif -#if 1 - while (true){ - if (!audio_buffer.isValid()){ - if (audio.empty()){ -// audio_input.sendAudioBuffer(QAudioBuffer()); -// session.setAudioBufferInput(nullptr); - break; - } -// cout << "constructing audio buffer: " << audio.size() << endl; - const std::vector& samples = audio.front()->samples; - QByteArray bytes((const char*)samples.data(), samples.size() * sizeof(float)); - audio_buffer = QAudioBuffer( - bytes, audio_format//, -// std::chrono::duration_cast(audio.front()->timestamp - start).count() - ); -// cout << "audio_buffer = " << audio_buffer.isValid() << endl; - audio.pop_front(); - } - if (!audio_buffer.isValid()){ - break; - } - if (!audio_input.sendAudioBuffer(audio_buffer)){ -// cout << "Failed Audio: " << audio.size() << endl; -// cout << audio_input.captureSession() << endl; - break; - } - audio_buffer = QAudioBuffer(); - last_change = current_time(); -// cout << "Pushed audio: " << audio.size() << endl; - } -#endif - - if (current_time() - last_change > std::chrono::seconds(10)){ - logger.log("Failed to record stream history: No progress made after 10 seconds.", COLOR_RED); - success = false; - break; - } - - QCoreApplication::processEvents(); - } - - recorder.stop(); - logger.log("Done saving stream history...", COLOR_BLUE); -// cout << recorder.duration() << endl; - - -// }); - return success; -} - - - - - - - -} -#endif +/* Stream History Tracker + * + * From: https://github.com/PokemonAutomation/ + * + * Implement by saving the last X seconds of frames. This is currently not + * viable because the QVideoFrames are uncompressed. + * + */ + +#ifndef PokemonAutomation_StreamHistoryTracker_SaveFrames_H +#define PokemonAutomation_StreamHistoryTracker_SaveFrames_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" + + +//#include +//using std::cout; +//using std::endl; + + +namespace PokemonAutomation{ + + +struct AudioBlock{ + WallClock timestamp; + std::vector samples; + + AudioBlock(const AudioBlock&) = delete; + void operator=(const AudioBlock&) = delete; + + AudioBlock(WallClock p_timestamp, const float* p_samples, size_t p_count) + : timestamp(p_timestamp) + , samples(p_samples, p_samples + p_count) + {} +}; + + +class StreamHistoryTracker{ +public: + StreamHistoryTracker( + size_t audio_samples_per_frame, + size_t audio_frames_per_second, + std::chrono::seconds window + ); + void set_window(std::chrono::seconds window); + + bool save(Logger& logger, const std::string& filename) const; + +public: + void on_samples(const float* data, size_t frames); + void on_frame(std::shared_ptr frame); + +private: + void clear_old(); + +private: + mutable SpinLock m_lock; + std::chrono::seconds m_window; + + const size_t m_audio_samples_per_frame; + const size_t m_audio_frames_per_second; + const size_t m_audio_samples_per_second; + const double m_microseconds_per_sample; + + // We use shared_ptr here so it's fast to snapshot when we need to copy + // everything asynchronously. + std::deque> m_audio; + std::deque> m_frames; +}; + + + + +StreamHistoryTracker::StreamHistoryTracker( + size_t audio_samples_per_frame, + size_t audio_frames_per_second, + std::chrono::seconds window +) + : m_window(window) + , m_audio_samples_per_frame(audio_samples_per_frame) + , m_audio_frames_per_second(audio_frames_per_second) + , m_audio_samples_per_second(audio_samples_per_frame * audio_frames_per_second) + , m_microseconds_per_sample(1. / (m_audio_samples_per_second * 1000000.)) +{} + +void StreamHistoryTracker::set_window(std::chrono::seconds window){ + WriteSpinLock lg(m_lock); + m_window = window; + clear_old(); +} +void StreamHistoryTracker::on_samples(const float* samples, size_t frames){ + if (frames == 0){ + return; + } + WallClock now = current_time(); + WriteSpinLock lg(m_lock); +// cout << "on_samples() = " << m_audio.size() << endl; + m_audio.emplace_back(std::make_shared( + now, samples, frames * m_audio_samples_per_frame + )); + clear_old(); +} +void StreamHistoryTracker::on_frame(std::shared_ptr frame){ + // TODO: Find a more efficient way to buffer the frames. + // It takes almost 10GB of memory to store 30 seconds of QVideoFrames + // due to them caching uncompressed bitmaps. +// return; // TODO + + WriteSpinLock lg(m_lock); +// cout << "on_frame() = " << m_frames.size() << endl; + m_frames.emplace_back(std::move(frame)); + clear_old(); +} + + + +void StreamHistoryTracker::clear_old(){ + // Must call under lock. + WallClock now = current_time(); + WallClock threshold = now - m_window; + +// WriteSpinLock lg(m_lock); +// cout << "enter" << endl; + while (!m_audio.empty()){ +// cout << "audio.size() = " << m_audio.size() << endl; + AudioBlock& block = *m_audio.front(); + + WallClock end_block = block.timestamp; + end_block += std::chrono::microseconds( + static_cast((double)block.samples.size() * m_microseconds_per_sample) + ); + + if (end_block < threshold){ + m_audio.pop_front(); + }else{ + break; + } + } +// cout << "exit" << endl; + + while (!m_frames.empty()){ + if (m_frames.front()->timestamp < threshold){ + m_frames.pop_front(); + }else{ + break; + } + } +} + + + + + +bool StreamHistoryTracker::save(Logger& logger, const std::string& filename) const{ + logger.log("Saving stream history...", COLOR_BLUE); + + std::deque> audio; + std::deque> frames; + { + // Fast copy the current state of the stream. + WriteSpinLock lg(m_lock); + if (m_audio.empty() && m_frames.empty()){ + return false; + } + audio = m_audio; + frames = m_frames; + } + + // Now that the lock is released, we can take our time encoding it. + + // TODO + +#if 0 + WallClock start = WallClock::max(); + if (!audio.empty()){ + start = std::min(start, audio.front()->timestamp); + } + if (!frames.empty()){ + start = std::min(start, frames.front()->timestamp); + } + +#endif + + +// run_on_main_thread_and_wait([&]{ + + QAudioFormat audio_format; + audio_format.setChannelCount((int)m_audio_samples_per_frame); + audio_format.setChannelConfig(m_audio_samples_per_frame == 1 ? QAudioFormat::ChannelConfigMono : QAudioFormat::ChannelConfigStereo); + audio_format.setSampleRate((int)m_audio_frames_per_second); + audio_format.setSampleFormat(QAudioFormat::Float); + +// cout << "audio_format = " << audio_format.isValid() << endl; + + QAudioBufferInput audio_input; + QVideoFrameInput video_input; + +// cout << "audio = " << audio.size() << endl; +// cout << "frames = " << frames.size() << endl; + + QMediaCaptureSession session; + QMediaRecorder recorder; + session.setAudioBufferInput(&audio_input); + session.setVideoFrameInput(&video_input); + session.setRecorder(&recorder); +#if 1 + recorder.setMediaFormat(QMediaFormat::MPEG4); +#else + QMediaFormat video_format; + video_format.setAudioCodec(QMediaFormat::AudioCodec::AAC); +// video_format.setVideoCodec(QMediaFormat::VideoCodec::H264); + video_format.setFileFormat(QMediaFormat::MPEG4); + recorder.setMediaFormat(video_format); +#endif + recorder.setQuality(QMediaRecorder::NormalQuality); + + QFileInfo file(QString::fromStdString(filename)); + recorder.setOutputLocation( + QUrl::fromLocalFile(file.absoluteFilePath()) + ); + + recorder.record(); + + WallClock last_change = current_time(); + QAudioBuffer audio_buffer; + bool success = true; + while (audio_buffer.isValid() || !frames.empty()){ +#if 1 + while (true){ + if (frames.empty()){ +// video_input.sendVideoFrame(QVideoFrame()); +// session.setVideoFrameInput(nullptr); + break; + } + if (!video_input.sendVideoFrame((*frames.begin())->frame)){ +// cout << "Failed Video: " << frames.size() << endl; + break; + } + frames.pop_front(); + last_change = current_time(); +// cout << "Pushed Video: " << frames.size() << endl; + } +#endif +#if 1 + while (true){ + if (!audio_buffer.isValid()){ + if (audio.empty()){ +// audio_input.sendAudioBuffer(QAudioBuffer()); +// session.setAudioBufferInput(nullptr); + break; + } +// cout << "constructing audio buffer: " << audio.size() << endl; + const std::vector& samples = audio.front()->samples; + QByteArray bytes((const char*)samples.data(), samples.size() * sizeof(float)); + audio_buffer = QAudioBuffer( + bytes, audio_format//, +// std::chrono::duration_cast(audio.front()->timestamp - start).count() + ); +// cout << "audio_buffer = " << audio_buffer.isValid() << endl; + audio.pop_front(); + } + if (!audio_buffer.isValid()){ + break; + } + if (!audio_input.sendAudioBuffer(audio_buffer)){ +// cout << "Failed Audio: " << audio.size() << endl; +// cout << audio_input.captureSession() << endl; + break; + } + audio_buffer = QAudioBuffer(); + last_change = current_time(); +// cout << "Pushed audio: " << audio.size() << endl; + } +#endif + + if (current_time() - last_change > std::chrono::seconds(10)){ + logger.log("Failed to record stream history: No progress made after 10 seconds.", COLOR_RED); + success = false; + break; + } + + QCoreApplication::processEvents(); + } + + recorder.stop(); + logger.log("Done saving stream history...", COLOR_BLUE); +// cout << recorder.duration() << endl; + + +// }); + return success; +} + + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Recording/StreamRecorder.cpp b/SerialPrograms/Source/CommonFramework/Recording/StreamRecorder.cpp index 0d3e970b63..28d5e54502 100644 --- a/SerialPrograms/Source/CommonFramework/Recording/StreamRecorder.cpp +++ b/SerialPrograms/Source/CommonFramework/Recording/StreamRecorder.cpp @@ -1,792 +1,792 @@ -/* Stream Recorder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#if (QT_VERSION_MAJOR == 6) && (QT_VERSION_MINOR >= 8) -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Concurrency/SpinPause.h" -//#include "Common/Qt/Redispatch.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" -#include "CommonFramework/Recording/StreamHistoryOption.h" -#include "StreamRecorder.h" - - -// This doesn't work yet. QMediaRecorder writes different bytes with -// setOutputDevice() vs. setOutputLocation(). -// So far I can't get setOutputDevice() to work. The bytes that it -// spits out is not a valid .mp4 file. - -//#define PA_STREAM_HISTORY_LOCAL_BUFFER - - -// REMOVE -#include -using std::cout; -using std::endl; - - -namespace PokemonAutomation{ - - -StreamRecording::StreamRecording( - Logger& logger, - std::chrono::milliseconds buffer_limit, - WallClock start_time, - size_t audio_samples_per_frame, - size_t audio_frames_per_second, - bool has_video -) - : m_logger(logger) - , m_buffer_limit(buffer_limit) - , m_start_time(start_time) - , m_audio_samples_per_frame(audio_samples_per_frame) - , m_has_video(has_video) - , m_filename(GlobalSettings::instance().TEMP_FOLDER) - , m_stopping(false) - , m_last_drop(current_time()) - , m_last_frame_time(std::numeric_limits::min()) -{ - logger.log( - "StreamRecording: Audio = " + std::to_string(audio_samples_per_frame) + - ", Video = " + std::to_string(has_video) - ); -// cout << "audio = " << audio_samples_per_frame << ", video = " << has_video << endl; - - if (audio_samples_per_frame == 0 && !has_video){ - return; - } - - if (audio_samples_per_frame > 0){ - m_audio_format.setChannelCount((int)audio_samples_per_frame); - m_audio_format.setChannelConfig(audio_samples_per_frame == 1 ? QAudioFormat::ChannelConfigMono : QAudioFormat::ChannelConfigStereo); - m_audio_format.setSampleRate((int)audio_frames_per_second); - m_audio_format.setSampleFormat(QAudioFormat::Float); - } - -#ifndef PA_STREAM_HISTORY_LOCAL_BUFFER - QDir().mkdir(QString::fromStdString(m_filename)); -#endif - if (has_video){ - m_filename += now_to_filestring() + ".mp4"; - }else{ - m_filename += now_to_filestring() + ".m4a"; - } - - start(); -} -StreamRecording::~StreamRecording(){ - { - std::lock_guard lg(m_lock); - m_stopping = true; -// cout << "signalling: ~StreamRecording()" << endl; - m_cv.notify_all(); - } - quit(); - wait(); -#ifndef PA_STREAM_HISTORY_LOCAL_BUFFER - if (!m_filename.empty()){ - QDir().remove(QString::fromStdString(m_filename)); - } -#endif -} - -bool StreamRecording::stop_and_save(const std::string& filename){ - auto scope_check = m_santizer.check_scope(); - { - std::lock_guard lg(m_lock); - m_stopping = true; -// cout << "signalling: stop_and_save()" << endl; - m_cv.notify_all(); - } - quit(); - wait(); - -#ifdef PA_STREAM_HISTORY_LOCAL_BUFFER - return m_write_buffer.write(m_logger, filename); -#else - bool ret = QDir().rename(QString::fromStdString(m_filename), QString::fromStdString(filename)); - m_filename.clear(); - return ret; -#endif -} - - -void StreamRecording::push_samples(WallClock timestamp, const float* data, size_t frames){ - auto scope_check = m_santizer.check_scope(); -#if 1 - WallClock now = current_time(); - if (m_audio_samples_per_frame == 0 || now < m_start_time){ - return; - } - WallClock threshold = timestamp - m_buffer_limit; - - std::lock_guard lg(m_lock); - if (m_stopping){ - return; - } - - do{ - if (m_buffered_audio.empty()){ - break; - } - - // Too much has been buffered. Drop the block. - if (m_buffered_audio.front().timestamp < threshold){ - // Throttle the prints. - if (now - m_last_drop > std::chrono::seconds(5)){ - m_last_drop = now; - m_logger.log("Unable to keep up with audio recording. Dropping samples.", COLOR_RED); - } - return; - } - - }while (false); - - // Enqueue the sample block. - m_buffered_audio.emplace_back( - timestamp, - data, frames * m_audio_samples_per_frame - ); - m_cv.notify_all(); -#endif -} -void StreamRecording::push_frame(std::shared_ptr frame){ - auto scope_check = m_santizer.check_scope(); -#if 1 - WallClock now = current_time(); - if (!m_has_video || now < m_start_time){ - return; - } -// cout << "push_frame(): " << frame->frame.startTime() << " - " << frame->frame.endTime() << endl; - WallClock threshold = frame->timestamp - m_buffer_limit; - - std::lock_guard lg(m_lock); - if (m_stopping){ - return; - } - - qint64 frame_time = frame->frame.startTime(); - do{ - if (m_buffered_frames.empty()){ - break; - } - - // Too much has been buffered. Drop the frame. - if (m_buffered_frames.front()->timestamp < threshold){ - // Throttle the prints. - if (now - m_last_drop > std::chrono::seconds(5)){ - m_last_drop = now; - m_logger.log("Unable to keep up with video recording. Dropping samples.", COLOR_RED); - } - return; - } - - // Non-increasing timestamp. Drop possible duplicate frame. - if (frame_time <= m_last_frame_time){ - return; - } - }while (false); - - // Enqueue the frame. - m_buffered_frames.emplace_back(std::move(frame)); - m_last_frame_time = frame_time; - m_cv.notify_all(); -#endif -} - - - -std::unique_ptr StreamRecording::initialize_audio(){ - std::unique_ptr ret(new QAudioBufferInput()); - m_audio_input = ret.get(); - m_session->setAudioBufferInput(m_audio_input); - - connect( - m_audio_input, &QAudioBufferInput::readyToSendAudioBuffer, - m_recorder, [this](){ - std::lock_guard lg(m_lock); - m_cv.notify_all(); - }, - Qt::DirectConnection - ); - - return ret; -} -std::unique_ptr StreamRecording::initialize_video(){ - std::unique_ptr ret(new QVideoFrameInput()); - m_video_input = ret.get(); - m_session->setVideoFrameInput(m_video_input); - - const StreamHistoryOption& settings = GlobalSettings::instance().STREAM_HISTORY; - - switch (settings.RESOLUTION){ - case StreamHistoryOption::Resolution::MATCH_INPUT: - break; - case StreamHistoryOption::Resolution::FORCE_720p: - m_recorder->setVideoResolution(1280, 720); - break; - case StreamHistoryOption::Resolution::FORCE_1080p: - m_recorder->setVideoResolution(1920, 1080); - break; - } - - switch (settings.ENCODING_MODE){ - case StreamHistoryOption::EncodingMode::FIXED_QUALITY: - switch (settings.VIDEO_QUALITY){ - case StreamHistoryOption::VideoQuality::VERY_LOW: - m_recorder->setQuality(QMediaRecorder::VeryLowQuality); - break; - case StreamHistoryOption::VideoQuality::LOW: - m_recorder->setQuality(QMediaRecorder::LowQuality); - break; - case StreamHistoryOption::VideoQuality::NORMAL: - m_recorder->setQuality(QMediaRecorder::NormalQuality); - break; - case StreamHistoryOption::VideoQuality::HIGH: - m_recorder->setQuality(QMediaRecorder::HighQuality); - break; - case StreamHistoryOption::VideoQuality::VERY_HIGH: - m_recorder->setQuality(QMediaRecorder::VeryHighQuality); - break; - } - break; - case StreamHistoryOption::EncodingMode::FIXED_BITRATE: - m_recorder->setVideoBitRate(settings.VIDEO_BITRATE * 1000); - m_recorder->setEncodingMode(QMediaRecorder::AverageBitRateEncoding); - break; - } - - connect( - m_video_input, &QVideoFrameInput::readyToSendVideoFrame, - m_recorder, [this](){ - std::lock_guard lg(m_lock); - m_cv.notify_all(); - }, - Qt::DirectConnection - ); - - return ret; -} - -void StreamRecording::internal_run(){ - QMediaCaptureSession session; - QMediaRecorder recorder; - m_session = &session; - m_recorder = &recorder; - m_session->setRecorder(m_recorder); - - std::unique_ptr audio; - std::unique_ptr video; - - // Only initialize the streams we intend to use. - if (m_audio_samples_per_frame > 0){ - audio = initialize_audio(); - } - if (m_has_video){ - video = initialize_video(); - } - - m_recorder->setMediaFormat(QMediaFormat::MPEG4); - - connect( - m_recorder, &QMediaRecorder::recorderStateChanged, - m_recorder, [this](QMediaRecorder::RecorderState state){ - if (state == QMediaRecorder::StoppedState){ - std::lock_guard lg(m_lock); -// cout << "signalling: StoppedState" << endl; - m_stopping = true; - m_cv.notify_all(); - } - }, - Qt::DirectConnection - ); - - -#ifdef PA_STREAM_HISTORY_LOCAL_BUFFER - m_recorder->setOutputDevice(&m_write_buffer); -#else - QFileInfo file(QString::fromStdString(m_filename)); - m_recorder->setOutputLocation( - QUrl::fromLocalFile(file.absoluteFilePath()) - ); -#endif - -// cout << "Encoding Mode = " << (int)recorder.encodingMode() << endl; -// cout << "Bit Rate = " << (int)recorder.videoBitRate() << endl; - - -#if 1 -// cout << "starting recording" << endl; - m_recorder->record(); - - AudioBlock current_audio; - std::shared_ptr current_frame; - QAudioBuffer audio_buffer; - - while (true){ - QCoreApplication::processEvents(); - - { - std::unique_lock lg(m_lock); - if (m_stopping){ - break; - } - - if (!current_audio.is_valid() && !m_buffered_audio.empty()){ - current_audio = std::move(m_buffered_audio.front()); - m_buffered_audio.pop_front(); - } - if (!current_frame && !m_buffered_frames.empty()){ - current_frame = std::move(m_buffered_frames.front()); - m_buffered_frames.pop_front(); - } - - if (!current_audio.is_valid() && !current_frame){ -// cout << "sleeping 0..." << endl; - m_cv.wait(lg); -// cout << "waking 0..." << endl; - } - } - - bool progress_made = false; - - if (current_audio.is_valid()){ - if (!audio_buffer.isValid()){ - const std::vector& samples = current_audio.samples; - QByteArray bytes((const char*)samples.data(), samples.size() * sizeof(float)); - audio_buffer = QAudioBuffer(bytes, m_audio_format); - } - if (audio_buffer.isValid() && m_audio_input->sendAudioBuffer(audio_buffer)){ - current_audio.clear(); - audio_buffer = QAudioBuffer(); - progress_made = true; - } - } -// cout << "Before: " << m_video_input << endl; - if (current_frame && m_video_input->sendVideoFrame(current_frame->frame)){ -// cout << "push frame: " << current_frame->frame.startTime() << endl; - current_frame.reset(); - progress_made = true; - } -// cout << "After: " << m_video_input << endl; - - if (!progress_made){ - std::unique_lock lg(m_lock); - if (m_stopping){ - break; - } -// cout << "sleeping 1..." << endl; - m_cv.wait(lg); -// cout << "waking 1..." << endl; - } - } - - m_recorder->stop(); -// cout << "recorder.stop()" << endl; -#endif - - - while (m_recorder->recorderState() != QMediaRecorder::StoppedState){ -// cout << "StreamHistoryTracker: process" << endl; - QCoreApplication::processEvents(); - pause(); - } - - exec(); - -} -void StreamRecording::run(){ - auto scope_check = m_santizer.check_scope(); - try{ - internal_run(); - }catch (...){ - m_logger.log("Exception thrown out of stream recorder...", COLOR_RED); - std::lock_guard lg(m_lock); - m_stopping = true; - } -} - - - - - -StreamRecording2::StreamRecording2( - Logger& logger, - std::chrono::milliseconds buffer_limit, - WallClock start_time, - size_t audio_samples_per_frame, - size_t audio_frames_per_second, - bool has_video -) - : m_logger(logger) - , m_buffer_limit(buffer_limit) - , m_start_time(start_time) - , m_audio_samples_per_frame(audio_samples_per_frame) - , m_has_video(has_video) - , m_filename(GlobalSettings::instance().TEMP_FOLDER) - , m_stopping(false) - , m_last_drop(current_time()) - , m_last_frame_time(std::numeric_limits::min()) -{ - logger.log( - "StreamRecording: Audio = " + std::to_string(audio_samples_per_frame) + - ", Video = " + std::to_string(has_video) - ); -// cout << "audio = " << audio_samples_per_frame << ", video = " << has_video << endl; - - if (audio_samples_per_frame == 0 && !has_video){ - return; - } - - if (audio_samples_per_frame > 0){ - m_audio_format.setChannelCount((int)audio_samples_per_frame); - m_audio_format.setChannelConfig(audio_samples_per_frame == 1 ? QAudioFormat::ChannelConfigMono : QAudioFormat::ChannelConfigStereo); - m_audio_format.setSampleRate((int)audio_frames_per_second); - m_audio_format.setSampleFormat(QAudioFormat::Float); - } - -#ifndef PA_STREAM_HISTORY_LOCAL_BUFFER - QDir().mkdir(QString::fromStdString(m_filename)); -#endif - if (has_video){ - m_filename += now_to_filestring() + ".mp4"; - }else{ - m_filename += now_to_filestring() + ".m4a"; - } - - m_recorder.reset(new QMediaRecorder()); - m_session.setRecorder(m_recorder.get()); - - // Only initialize the streams we intend to use. - if (m_audio_samples_per_frame > 0){ - initialize_audio(); - } - if (m_has_video){ - initialize_video(); - } - - m_recorder->setMediaFormat(QMediaFormat::MPEG4); - - - -#ifdef PA_STREAM_HISTORY_LOCAL_BUFFER - m_recorder->setOutputDevice(&m_write_buffer); -#else - QFileInfo file(QString::fromStdString(m_filename)); - m_recorder->setOutputLocation( - QUrl::fromLocalFile(file.absoluteFilePath()) - ); -#endif - - m_recorder->record(); -} -StreamRecording2::~StreamRecording2(){ -#if 1 - stop(); -#else - { - std::unique_lock lg(m_lock); - if (m_stopping){ - return; - } - m_stopping = true; - } - - m_recorder->stop(); - m_recorder.reset(); -#endif - -#ifndef PA_STREAM_HISTORY_LOCAL_BUFFER - cout << QDir().remove(QString::fromStdString(m_filename)) << endl; // REMOVE -#endif -} - -void StreamRecording2::stop(){ - auto scope_check = m_santizer.check_scope(); - - { - std::unique_lock lg(m_lock); - if (m_stopping){ - return; - } - m_stopping = true; - } - -#if 0 - run_on_main_thread_and_wait([this]{ - QEventLoop loop; - m_recorder.connect( - &m_recorder, &QMediaRecorder::recorderStateChanged, - &m_recorder, [&](QMediaRecorder::RecorderState state){ - if (state == QMediaRecorder::StoppedState){ - loop.quit(); - } - } - ); - - emit m_recorder.stop(); - - if (m_recorder.recorderState() != QMediaRecorder::StoppedState){ - loop.exec(); - } - }); -#endif - - m_recorder->stop(); - - while (m_recorder->recorderState() != QMediaRecorder::StoppedState){ - cout << "Spin waiting..." << endl; // REMOVE - pause(); - } -} - - -void StreamRecording2::initialize_audio(){ - m_audio_input.reset(new QAudioBufferInput()); - m_session.setAudioBufferInput(m_audio_input.get()); - - m_recorder->connect( - m_audio_input.get(), &QAudioBufferInput::readyToSendAudioBuffer, - m_recorder.get(), [this](){ -// cout << "readyToSendAudioBuffer()" << endl; -// std::lock_guard lg(m_lock); -// m_cv.notify_all(); - process(); - }, - Qt::DirectConnection - ); -} -void StreamRecording2::initialize_video(){ - m_video_input.reset(new QVideoFrameInput()); - m_session.setVideoFrameInput(m_video_input.get()); - - const StreamHistoryOption& settings = GlobalSettings::instance().STREAM_HISTORY; - - switch (settings.RESOLUTION){ - case StreamHistoryOption::Resolution::MATCH_INPUT: - break; - case StreamHistoryOption::Resolution::FORCE_720p: - m_recorder->setVideoResolution(1280, 720); - break; - case StreamHistoryOption::Resolution::FORCE_1080p: - m_recorder->setVideoResolution(1920, 1080); - break; - } - - switch (settings.ENCODING_MODE){ - case StreamHistoryOption::EncodingMode::FIXED_QUALITY: - switch (settings.VIDEO_QUALITY){ - case StreamHistoryOption::VideoQuality::VERY_LOW: - m_recorder->setQuality(QMediaRecorder::VeryLowQuality); - break; - case StreamHistoryOption::VideoQuality::LOW: - m_recorder->setQuality(QMediaRecorder::LowQuality); - break; - case StreamHistoryOption::VideoQuality::NORMAL: - m_recorder->setQuality(QMediaRecorder::NormalQuality); - break; - case StreamHistoryOption::VideoQuality::HIGH: - m_recorder->setQuality(QMediaRecorder::HighQuality); - break; - case StreamHistoryOption::VideoQuality::VERY_HIGH: - m_recorder->setQuality(QMediaRecorder::VeryHighQuality); - break; - } - break; - case StreamHistoryOption::EncodingMode::FIXED_BITRATE: - m_recorder->setVideoBitRate(settings.VIDEO_BITRATE * 1000); - m_recorder->setEncodingMode(QMediaRecorder::AverageBitRateEncoding); - break; - } - - m_recorder->connect( - m_video_input.get(), &QVideoFrameInput::readyToSendVideoFrame, - m_recorder.get(), [this](){ -// cout << "readyToSendVideoFrame()" << endl; -// std::lock_guard lg(m_lock); -// m_cv.notify_all(); - process(); - }, - Qt::DirectConnection - ); -} - - - - -void StreamRecording2::push_samples(WallClock timestamp, const float* data, size_t frames){ - auto scope_check = m_santizer.check_scope(); -#if 1 - WallClock now = current_time(); - if (m_audio_samples_per_frame == 0 || now < m_start_time){ - return; - } - WallClock threshold = timestamp - m_buffer_limit; - - { - std::lock_guard lg(m_lock); - if (m_stopping){ - return; - } - - do{ - if (m_buffered_audio.empty()){ - break; - } - - // Too much has been buffered. Drop the block. - if (m_buffered_audio.front().timestamp < threshold){ - // Throttle the prints. - if (now - m_last_drop > std::chrono::seconds(5)){ - m_last_drop = now; - m_logger.log("Unable to keep up with audio recording. Dropping samples.", COLOR_RED); - } - return; - } - - }while (false); - - // Enqueue the sample block. - m_buffered_audio.emplace_back( - timestamp, - data, frames * m_audio_samples_per_frame - ); - } - - emit m_audio_input->readyToSendAudioBuffer(); -#endif -} -void StreamRecording2::push_frame(std::shared_ptr frame){ - auto scope_check = m_santizer.check_scope(); -#if 1 - WallClock now = current_time(); - if (!m_has_video || now < m_start_time){ - return; - } -// cout << "push_frame(): " << frame->frame.startTime() << " - " << frame->frame.endTime() << endl; - WallClock threshold = frame->timestamp - m_buffer_limit; - - { - std::lock_guard lg(m_lock); - if (m_stopping){ - return; - } - - qint64 frame_time = frame->frame.startTime(); - do{ - if (m_buffered_frames.empty()){ - break; - } - - // Too much has been buffered. Drop the frame. - if (m_buffered_frames.front()->timestamp < threshold){ - // Throttle the prints. - if (now - m_last_drop > std::chrono::seconds(5)){ - m_last_drop = now; - m_logger.log("Unable to keep up with video recording. Dropping samples.", COLOR_RED); - } - return; - } - - // Non-increasing timestamp. Drop possible duplicate frame. - if (frame_time <= m_last_frame_time){ - return; - } - }while (false); - - // Enqueue the frame. - m_buffered_frames.emplace_back(std::move(frame)); - m_last_frame_time = frame_time; - } - - emit m_video_input->readyToSendVideoFrame(); -#endif -} - - -bool StreamRecording2::stop_and_save(const std::string& filename){ - stop(); - -#ifdef PA_STREAM_HISTORY_LOCAL_BUFFER - return m_write_buffer.write(m_logger, filename); -#else - bool ret = QDir().rename(QString::fromStdString(m_filename), QString::fromStdString(filename)); - m_filename.clear(); - return ret; -#endif -} - -void StreamRecording2::process(){ - auto scope_check = m_santizer.check_scope(); - -// cout << "StreamRecording2::process()" << endl; - - bool progress_made; - do{ - { - std::unique_lock lg(m_lock); - if (m_stopping){ - cout << "exit" << endl; // REMOVE - break; - } - - if (!m_current_audio.is_valid() && !m_buffered_audio.empty()){ - m_current_audio = std::move(m_buffered_audio.front()); - m_buffered_audio.pop_front(); - } - if (!m_current_frame && !m_buffered_frames.empty()){ - m_current_frame = std::move(m_buffered_frames.front()); - m_buffered_frames.pop_front(); - } - - if (!m_current_audio.is_valid() && !m_current_frame){ - return; - } - } - - progress_made = false; - - if (m_current_audio.is_valid()){ - if (!m_audio_buffer.isValid()){ - const std::vector& samples = m_current_audio.samples; - QByteArray bytes((const char*)samples.data(), samples.size() * sizeof(float)); - m_audio_buffer = QAudioBuffer(bytes, m_audio_format); - } - if (m_audio_buffer.isValid() && m_audio_input->sendAudioBuffer(m_audio_buffer)){ - m_current_audio.clear(); - m_audio_buffer = QAudioBuffer(); - progress_made = true; - } - } -// cout << "Before: " << m_video_input << endl; - if (m_current_frame && m_video_input->sendVideoFrame(m_current_frame->frame)){ -// cout << "push frame: " << current_frame->frame.startTime() << endl; - m_current_frame.reset(); - progress_made = true; - } - - }while (progress_made); -} - - - - - - - -} -#endif +/* Stream Recorder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#if (QT_VERSION_MAJOR == 6) && (QT_VERSION_MINOR >= 8) +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Concurrency/SpinPause.h" +//#include "Common/Qt/Redispatch.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" +#include "CommonFramework/Recording/StreamHistoryOption.h" +#include "StreamRecorder.h" + + +// This doesn't work yet. QMediaRecorder writes different bytes with +// setOutputDevice() vs. setOutputLocation(). +// So far I can't get setOutputDevice() to work. The bytes that it +// spits out is not a valid .mp4 file. + +//#define PA_STREAM_HISTORY_LOCAL_BUFFER + + +// REMOVE +#include +using std::cout; +using std::endl; + + +namespace PokemonAutomation{ + + +StreamRecording::StreamRecording( + Logger& logger, + std::chrono::milliseconds buffer_limit, + WallClock start_time, + size_t audio_samples_per_frame, + size_t audio_frames_per_second, + bool has_video +) + : m_logger(logger) + , m_buffer_limit(buffer_limit) + , m_start_time(start_time) + , m_audio_samples_per_frame(audio_samples_per_frame) + , m_has_video(has_video) + , m_filename(GlobalSettings::instance().TEMP_FOLDER) + , m_stopping(false) + , m_last_drop(current_time()) + , m_last_frame_time(std::numeric_limits::min()) +{ + logger.log( + "StreamRecording: Audio = " + std::to_string(audio_samples_per_frame) + + ", Video = " + std::to_string(has_video) + ); +// cout << "audio = " << audio_samples_per_frame << ", video = " << has_video << endl; + + if (audio_samples_per_frame == 0 && !has_video){ + return; + } + + if (audio_samples_per_frame > 0){ + m_audio_format.setChannelCount((int)audio_samples_per_frame); + m_audio_format.setChannelConfig(audio_samples_per_frame == 1 ? QAudioFormat::ChannelConfigMono : QAudioFormat::ChannelConfigStereo); + m_audio_format.setSampleRate((int)audio_frames_per_second); + m_audio_format.setSampleFormat(QAudioFormat::Float); + } + +#ifndef PA_STREAM_HISTORY_LOCAL_BUFFER + QDir().mkdir(QString::fromStdString(m_filename)); +#endif + if (has_video){ + m_filename += now_to_filestring() + ".mp4"; + }else{ + m_filename += now_to_filestring() + ".m4a"; + } + + start(); +} +StreamRecording::~StreamRecording(){ + { + std::lock_guard lg(m_lock); + m_stopping = true; +// cout << "signalling: ~StreamRecording()" << endl; + m_cv.notify_all(); + } + quit(); + wait(); +#ifndef PA_STREAM_HISTORY_LOCAL_BUFFER + if (!m_filename.empty()){ + QDir().remove(QString::fromStdString(m_filename)); + } +#endif +} + +bool StreamRecording::stop_and_save(const std::string& filename){ + auto scope_check = m_santizer.check_scope(); + { + std::lock_guard lg(m_lock); + m_stopping = true; +// cout << "signalling: stop_and_save()" << endl; + m_cv.notify_all(); + } + quit(); + wait(); + +#ifdef PA_STREAM_HISTORY_LOCAL_BUFFER + return m_write_buffer.write(m_logger, filename); +#else + bool ret = QDir().rename(QString::fromStdString(m_filename), QString::fromStdString(filename)); + m_filename.clear(); + return ret; +#endif +} + + +void StreamRecording::push_samples(WallClock timestamp, const float* data, size_t frames){ + auto scope_check = m_santizer.check_scope(); +#if 1 + WallClock now = current_time(); + if (m_audio_samples_per_frame == 0 || now < m_start_time){ + return; + } + WallClock threshold = timestamp - m_buffer_limit; + + std::lock_guard lg(m_lock); + if (m_stopping){ + return; + } + + do{ + if (m_buffered_audio.empty()){ + break; + } + + // Too much has been buffered. Drop the block. + if (m_buffered_audio.front().timestamp < threshold){ + // Throttle the prints. + if (now - m_last_drop > std::chrono::seconds(5)){ + m_last_drop = now; + m_logger.log("Unable to keep up with audio recording. Dropping samples.", COLOR_RED); + } + return; + } + + }while (false); + + // Enqueue the sample block. + m_buffered_audio.emplace_back( + timestamp, + data, frames * m_audio_samples_per_frame + ); + m_cv.notify_all(); +#endif +} +void StreamRecording::push_frame(std::shared_ptr frame){ + auto scope_check = m_santizer.check_scope(); +#if 1 + WallClock now = current_time(); + if (!m_has_video || now < m_start_time){ + return; + } +// cout << "push_frame(): " << frame->frame.startTime() << " - " << frame->frame.endTime() << endl; + WallClock threshold = frame->timestamp - m_buffer_limit; + + std::lock_guard lg(m_lock); + if (m_stopping){ + return; + } + + qint64 frame_time = frame->frame.startTime(); + do{ + if (m_buffered_frames.empty()){ + break; + } + + // Too much has been buffered. Drop the frame. + if (m_buffered_frames.front()->timestamp < threshold){ + // Throttle the prints. + if (now - m_last_drop > std::chrono::seconds(5)){ + m_last_drop = now; + m_logger.log("Unable to keep up with video recording. Dropping samples.", COLOR_RED); + } + return; + } + + // Non-increasing timestamp. Drop possible duplicate frame. + if (frame_time <= m_last_frame_time){ + return; + } + }while (false); + + // Enqueue the frame. + m_buffered_frames.emplace_back(std::move(frame)); + m_last_frame_time = frame_time; + m_cv.notify_all(); +#endif +} + + + +std::unique_ptr StreamRecording::initialize_audio(){ + std::unique_ptr ret(new QAudioBufferInput()); + m_audio_input = ret.get(); + m_session->setAudioBufferInput(m_audio_input); + + connect( + m_audio_input, &QAudioBufferInput::readyToSendAudioBuffer, + m_recorder, [this](){ + std::lock_guard lg(m_lock); + m_cv.notify_all(); + }, + Qt::DirectConnection + ); + + return ret; +} +std::unique_ptr StreamRecording::initialize_video(){ + std::unique_ptr ret(new QVideoFrameInput()); + m_video_input = ret.get(); + m_session->setVideoFrameInput(m_video_input); + + const StreamHistoryOption& settings = GlobalSettings::instance().STREAM_HISTORY; + + switch (settings.RESOLUTION){ + case StreamHistoryOption::Resolution::MATCH_INPUT: + break; + case StreamHistoryOption::Resolution::FORCE_720p: + m_recorder->setVideoResolution(1280, 720); + break; + case StreamHistoryOption::Resolution::FORCE_1080p: + m_recorder->setVideoResolution(1920, 1080); + break; + } + + switch (settings.ENCODING_MODE){ + case StreamHistoryOption::EncodingMode::FIXED_QUALITY: + switch (settings.VIDEO_QUALITY){ + case StreamHistoryOption::VideoQuality::VERY_LOW: + m_recorder->setQuality(QMediaRecorder::VeryLowQuality); + break; + case StreamHistoryOption::VideoQuality::LOW: + m_recorder->setQuality(QMediaRecorder::LowQuality); + break; + case StreamHistoryOption::VideoQuality::NORMAL: + m_recorder->setQuality(QMediaRecorder::NormalQuality); + break; + case StreamHistoryOption::VideoQuality::HIGH: + m_recorder->setQuality(QMediaRecorder::HighQuality); + break; + case StreamHistoryOption::VideoQuality::VERY_HIGH: + m_recorder->setQuality(QMediaRecorder::VeryHighQuality); + break; + } + break; + case StreamHistoryOption::EncodingMode::FIXED_BITRATE: + m_recorder->setVideoBitRate(settings.VIDEO_BITRATE * 1000); + m_recorder->setEncodingMode(QMediaRecorder::AverageBitRateEncoding); + break; + } + + connect( + m_video_input, &QVideoFrameInput::readyToSendVideoFrame, + m_recorder, [this](){ + std::lock_guard lg(m_lock); + m_cv.notify_all(); + }, + Qt::DirectConnection + ); + + return ret; +} + +void StreamRecording::internal_run(){ + QMediaCaptureSession session; + QMediaRecorder recorder; + m_session = &session; + m_recorder = &recorder; + m_session->setRecorder(m_recorder); + + std::unique_ptr audio; + std::unique_ptr video; + + // Only initialize the streams we intend to use. + if (m_audio_samples_per_frame > 0){ + audio = initialize_audio(); + } + if (m_has_video){ + video = initialize_video(); + } + + m_recorder->setMediaFormat(QMediaFormat::MPEG4); + + connect( + m_recorder, &QMediaRecorder::recorderStateChanged, + m_recorder, [this](QMediaRecorder::RecorderState state){ + if (state == QMediaRecorder::StoppedState){ + std::lock_guard lg(m_lock); +// cout << "signalling: StoppedState" << endl; + m_stopping = true; + m_cv.notify_all(); + } + }, + Qt::DirectConnection + ); + + +#ifdef PA_STREAM_HISTORY_LOCAL_BUFFER + m_recorder->setOutputDevice(&m_write_buffer); +#else + QFileInfo file(QString::fromStdString(m_filename)); + m_recorder->setOutputLocation( + QUrl::fromLocalFile(file.absoluteFilePath()) + ); +#endif + +// cout << "Encoding Mode = " << (int)recorder.encodingMode() << endl; +// cout << "Bit Rate = " << (int)recorder.videoBitRate() << endl; + + +#if 1 +// cout << "starting recording" << endl; + m_recorder->record(); + + AudioBlock current_audio; + std::shared_ptr current_frame; + QAudioBuffer audio_buffer; + + while (true){ + QCoreApplication::processEvents(); + + { + std::unique_lock lg(m_lock); + if (m_stopping){ + break; + } + + if (!current_audio.is_valid() && !m_buffered_audio.empty()){ + current_audio = std::move(m_buffered_audio.front()); + m_buffered_audio.pop_front(); + } + if (!current_frame && !m_buffered_frames.empty()){ + current_frame = std::move(m_buffered_frames.front()); + m_buffered_frames.pop_front(); + } + + if (!current_audio.is_valid() && !current_frame){ +// cout << "sleeping 0..." << endl; + m_cv.wait(lg); +// cout << "waking 0..." << endl; + } + } + + bool progress_made = false; + + if (current_audio.is_valid()){ + if (!audio_buffer.isValid()){ + const std::vector& samples = current_audio.samples; + QByteArray bytes((const char*)samples.data(), samples.size() * sizeof(float)); + audio_buffer = QAudioBuffer(bytes, m_audio_format); + } + if (audio_buffer.isValid() && m_audio_input->sendAudioBuffer(audio_buffer)){ + current_audio.clear(); + audio_buffer = QAudioBuffer(); + progress_made = true; + } + } +// cout << "Before: " << m_video_input << endl; + if (current_frame && m_video_input->sendVideoFrame(current_frame->frame)){ +// cout << "push frame: " << current_frame->frame.startTime() << endl; + current_frame.reset(); + progress_made = true; + } +// cout << "After: " << m_video_input << endl; + + if (!progress_made){ + std::unique_lock lg(m_lock); + if (m_stopping){ + break; + } +// cout << "sleeping 1..." << endl; + m_cv.wait(lg); +// cout << "waking 1..." << endl; + } + } + + m_recorder->stop(); +// cout << "recorder.stop()" << endl; +#endif + + + while (m_recorder->recorderState() != QMediaRecorder::StoppedState){ +// cout << "StreamHistoryTracker: process" << endl; + QCoreApplication::processEvents(); + pause(); + } + + exec(); + +} +void StreamRecording::run(){ + auto scope_check = m_santizer.check_scope(); + try{ + internal_run(); + }catch (...){ + m_logger.log("Exception thrown out of stream recorder...", COLOR_RED); + std::lock_guard lg(m_lock); + m_stopping = true; + } +} + + + + + +StreamRecording2::StreamRecording2( + Logger& logger, + std::chrono::milliseconds buffer_limit, + WallClock start_time, + size_t audio_samples_per_frame, + size_t audio_frames_per_second, + bool has_video +) + : m_logger(logger) + , m_buffer_limit(buffer_limit) + , m_start_time(start_time) + , m_audio_samples_per_frame(audio_samples_per_frame) + , m_has_video(has_video) + , m_filename(GlobalSettings::instance().TEMP_FOLDER) + , m_stopping(false) + , m_last_drop(current_time()) + , m_last_frame_time(std::numeric_limits::min()) +{ + logger.log( + "StreamRecording: Audio = " + std::to_string(audio_samples_per_frame) + + ", Video = " + std::to_string(has_video) + ); +// cout << "audio = " << audio_samples_per_frame << ", video = " << has_video << endl; + + if (audio_samples_per_frame == 0 && !has_video){ + return; + } + + if (audio_samples_per_frame > 0){ + m_audio_format.setChannelCount((int)audio_samples_per_frame); + m_audio_format.setChannelConfig(audio_samples_per_frame == 1 ? QAudioFormat::ChannelConfigMono : QAudioFormat::ChannelConfigStereo); + m_audio_format.setSampleRate((int)audio_frames_per_second); + m_audio_format.setSampleFormat(QAudioFormat::Float); + } + +#ifndef PA_STREAM_HISTORY_LOCAL_BUFFER + QDir().mkdir(QString::fromStdString(m_filename)); +#endif + if (has_video){ + m_filename += now_to_filestring() + ".mp4"; + }else{ + m_filename += now_to_filestring() + ".m4a"; + } + + m_recorder.reset(new QMediaRecorder()); + m_session.setRecorder(m_recorder.get()); + + // Only initialize the streams we intend to use. + if (m_audio_samples_per_frame > 0){ + initialize_audio(); + } + if (m_has_video){ + initialize_video(); + } + + m_recorder->setMediaFormat(QMediaFormat::MPEG4); + + + +#ifdef PA_STREAM_HISTORY_LOCAL_BUFFER + m_recorder->setOutputDevice(&m_write_buffer); +#else + QFileInfo file(QString::fromStdString(m_filename)); + m_recorder->setOutputLocation( + QUrl::fromLocalFile(file.absoluteFilePath()) + ); +#endif + + m_recorder->record(); +} +StreamRecording2::~StreamRecording2(){ +#if 1 + stop(); +#else + { + std::unique_lock lg(m_lock); + if (m_stopping){ + return; + } + m_stopping = true; + } + + m_recorder->stop(); + m_recorder.reset(); +#endif + +#ifndef PA_STREAM_HISTORY_LOCAL_BUFFER + cout << QDir().remove(QString::fromStdString(m_filename)) << endl; // REMOVE +#endif +} + +void StreamRecording2::stop(){ + auto scope_check = m_santizer.check_scope(); + + { + std::unique_lock lg(m_lock); + if (m_stopping){ + return; + } + m_stopping = true; + } + +#if 0 + run_on_main_thread_and_wait([this]{ + QEventLoop loop; + m_recorder.connect( + &m_recorder, &QMediaRecorder::recorderStateChanged, + &m_recorder, [&](QMediaRecorder::RecorderState state){ + if (state == QMediaRecorder::StoppedState){ + loop.quit(); + } + } + ); + + emit m_recorder.stop(); + + if (m_recorder.recorderState() != QMediaRecorder::StoppedState){ + loop.exec(); + } + }); +#endif + + m_recorder->stop(); + + while (m_recorder->recorderState() != QMediaRecorder::StoppedState){ + cout << "Spin waiting..." << endl; // REMOVE + pause(); + } +} + + +void StreamRecording2::initialize_audio(){ + m_audio_input.reset(new QAudioBufferInput()); + m_session.setAudioBufferInput(m_audio_input.get()); + + m_recorder->connect( + m_audio_input.get(), &QAudioBufferInput::readyToSendAudioBuffer, + m_recorder.get(), [this](){ +// cout << "readyToSendAudioBuffer()" << endl; +// std::lock_guard lg(m_lock); +// m_cv.notify_all(); + process(); + }, + Qt::DirectConnection + ); +} +void StreamRecording2::initialize_video(){ + m_video_input.reset(new QVideoFrameInput()); + m_session.setVideoFrameInput(m_video_input.get()); + + const StreamHistoryOption& settings = GlobalSettings::instance().STREAM_HISTORY; + + switch (settings.RESOLUTION){ + case StreamHistoryOption::Resolution::MATCH_INPUT: + break; + case StreamHistoryOption::Resolution::FORCE_720p: + m_recorder->setVideoResolution(1280, 720); + break; + case StreamHistoryOption::Resolution::FORCE_1080p: + m_recorder->setVideoResolution(1920, 1080); + break; + } + + switch (settings.ENCODING_MODE){ + case StreamHistoryOption::EncodingMode::FIXED_QUALITY: + switch (settings.VIDEO_QUALITY){ + case StreamHistoryOption::VideoQuality::VERY_LOW: + m_recorder->setQuality(QMediaRecorder::VeryLowQuality); + break; + case StreamHistoryOption::VideoQuality::LOW: + m_recorder->setQuality(QMediaRecorder::LowQuality); + break; + case StreamHistoryOption::VideoQuality::NORMAL: + m_recorder->setQuality(QMediaRecorder::NormalQuality); + break; + case StreamHistoryOption::VideoQuality::HIGH: + m_recorder->setQuality(QMediaRecorder::HighQuality); + break; + case StreamHistoryOption::VideoQuality::VERY_HIGH: + m_recorder->setQuality(QMediaRecorder::VeryHighQuality); + break; + } + break; + case StreamHistoryOption::EncodingMode::FIXED_BITRATE: + m_recorder->setVideoBitRate(settings.VIDEO_BITRATE * 1000); + m_recorder->setEncodingMode(QMediaRecorder::AverageBitRateEncoding); + break; + } + + m_recorder->connect( + m_video_input.get(), &QVideoFrameInput::readyToSendVideoFrame, + m_recorder.get(), [this](){ +// cout << "readyToSendVideoFrame()" << endl; +// std::lock_guard lg(m_lock); +// m_cv.notify_all(); + process(); + }, + Qt::DirectConnection + ); +} + + + + +void StreamRecording2::push_samples(WallClock timestamp, const float* data, size_t frames){ + auto scope_check = m_santizer.check_scope(); +#if 1 + WallClock now = current_time(); + if (m_audio_samples_per_frame == 0 || now < m_start_time){ + return; + } + WallClock threshold = timestamp - m_buffer_limit; + + { + std::lock_guard lg(m_lock); + if (m_stopping){ + return; + } + + do{ + if (m_buffered_audio.empty()){ + break; + } + + // Too much has been buffered. Drop the block. + if (m_buffered_audio.front().timestamp < threshold){ + // Throttle the prints. + if (now - m_last_drop > std::chrono::seconds(5)){ + m_last_drop = now; + m_logger.log("Unable to keep up with audio recording. Dropping samples.", COLOR_RED); + } + return; + } + + }while (false); + + // Enqueue the sample block. + m_buffered_audio.emplace_back( + timestamp, + data, frames * m_audio_samples_per_frame + ); + } + + emit m_audio_input->readyToSendAudioBuffer(); +#endif +} +void StreamRecording2::push_frame(std::shared_ptr frame){ + auto scope_check = m_santizer.check_scope(); +#if 1 + WallClock now = current_time(); + if (!m_has_video || now < m_start_time){ + return; + } +// cout << "push_frame(): " << frame->frame.startTime() << " - " << frame->frame.endTime() << endl; + WallClock threshold = frame->timestamp - m_buffer_limit; + + { + std::lock_guard lg(m_lock); + if (m_stopping){ + return; + } + + qint64 frame_time = frame->frame.startTime(); + do{ + if (m_buffered_frames.empty()){ + break; + } + + // Too much has been buffered. Drop the frame. + if (m_buffered_frames.front()->timestamp < threshold){ + // Throttle the prints. + if (now - m_last_drop > std::chrono::seconds(5)){ + m_last_drop = now; + m_logger.log("Unable to keep up with video recording. Dropping samples.", COLOR_RED); + } + return; + } + + // Non-increasing timestamp. Drop possible duplicate frame. + if (frame_time <= m_last_frame_time){ + return; + } + }while (false); + + // Enqueue the frame. + m_buffered_frames.emplace_back(std::move(frame)); + m_last_frame_time = frame_time; + } + + emit m_video_input->readyToSendVideoFrame(); +#endif +} + + +bool StreamRecording2::stop_and_save(const std::string& filename){ + stop(); + +#ifdef PA_STREAM_HISTORY_LOCAL_BUFFER + return m_write_buffer.write(m_logger, filename); +#else + bool ret = QDir().rename(QString::fromStdString(m_filename), QString::fromStdString(filename)); + m_filename.clear(); + return ret; +#endif +} + +void StreamRecording2::process(){ + auto scope_check = m_santizer.check_scope(); + +// cout << "StreamRecording2::process()" << endl; + + bool progress_made; + do{ + { + std::unique_lock lg(m_lock); + if (m_stopping){ + cout << "exit" << endl; // REMOVE + break; + } + + if (!m_current_audio.is_valid() && !m_buffered_audio.empty()){ + m_current_audio = std::move(m_buffered_audio.front()); + m_buffered_audio.pop_front(); + } + if (!m_current_frame && !m_buffered_frames.empty()){ + m_current_frame = std::move(m_buffered_frames.front()); + m_buffered_frames.pop_front(); + } + + if (!m_current_audio.is_valid() && !m_current_frame){ + return; + } + } + + progress_made = false; + + if (m_current_audio.is_valid()){ + if (!m_audio_buffer.isValid()){ + const std::vector& samples = m_current_audio.samples; + QByteArray bytes((const char*)samples.data(), samples.size() * sizeof(float)); + m_audio_buffer = QAudioBuffer(bytes, m_audio_format); + } + if (m_audio_buffer.isValid() && m_audio_input->sendAudioBuffer(m_audio_buffer)){ + m_current_audio.clear(); + m_audio_buffer = QAudioBuffer(); + progress_made = true; + } + } +// cout << "Before: " << m_video_input << endl; + if (m_current_frame && m_video_input->sendVideoFrame(m_current_frame->frame)){ +// cout << "push frame: " << current_frame->frame.startTime() << endl; + m_current_frame.reset(); + progress_made = true; + } + + }while (progress_made); +} + + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Recording/StreamRecorder.h b/SerialPrograms/Source/CommonFramework/Recording/StreamRecorder.h index 63455615b6..a434f2c3a2 100644 --- a/SerialPrograms/Source/CommonFramework/Recording/StreamRecorder.h +++ b/SerialPrograms/Source/CommonFramework/Recording/StreamRecorder.h @@ -1,234 +1,234 @@ -/* Stream Recorder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_StreamRecorder_H -#define PokemonAutomation_StreamRecorder_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/LifetimeSanitizer.h" -#include "Common/Cpp/Time.h" -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" - -//#include -//using std::cout; -//using std::endl; - - -class QAudioBufferInput; -class QVideoFrameInput; -class QMediaCaptureSession; -class QMediaRecorder; - -namespace PokemonAutomation{ - - -struct AudioBlock{ - WallClock timestamp; - std::vector samples; - - AudioBlock(AudioBlock&&) = default; - AudioBlock& operator=(AudioBlock&&) = default; - AudioBlock(const AudioBlock&) = delete; - void operator=(const AudioBlock&) = delete; - - AudioBlock() - : timestamp(WallClock::min()) - {} - AudioBlock(WallClock p_timestamp, const float* p_samples, size_t p_count) - : timestamp(p_timestamp) - , samples(p_samples, p_samples + p_count) - {} - - void clear(){ - samples.clear(); - } - bool is_valid() const{ - return !samples.empty(); - } -}; - - - -class WriteBuffer : public QIODevice{ -public: - ~WriteBuffer(){ - waitForBytesWritten(-1); - } - WriteBuffer(){ - setOpenMode(QIODeviceBase::WriteOnly); - } - - virtual qint64 readData(char* data, qint64 maxlen){ return 0; } - virtual qint64 writeData(const char* data, qint64 len){ - m_bytes += len; -// cout << "total = " << m_bytes << ", current = " << len << endl; - m_blocks.emplace_back(data, data + len); -// cout << "data = " << (unsigned)data[0] << endl; - return len; - } - - bool write(Logger& logger, const std::string& filename) const{ -// cout << "write()" << endl; - QFile file(QString::fromStdString(filename)); - if (!file.open(QFile::WriteOnly)){ - logger.log("Failed to write file: " + filename, COLOR_RED); - return false; - } - for (const std::vector& block : m_blocks){ - if ((size_t)file.write(block.data(), block.size()) != block.size()){ - logger.log("Failed to write file: " + filename, COLOR_RED); - return false; - } - } - file.close(); - return true; - } - -private: - uint64_t m_bytes = 0; - std::deque> m_blocks; -}; - - - - -// -// This one works, but it leaks a tiny bit of memory each time QMediaRecorder -// is started and stopped. -// -class StreamRecording : public QThread{ -public: - StreamRecording( - Logger& logger, - std::chrono::milliseconds buffer_limit, - WallClock start_time, - size_t audio_samples_per_frame, - size_t audio_frames_per_second, - bool has_video - ); - ~StreamRecording(); - - void push_samples(WallClock timestamp, const float* data, size_t frames); - void push_frame(std::shared_ptr frame); - - bool stop_and_save(const std::string& filename); - -private: - std::unique_ptr initialize_audio(); - std::unique_ptr initialize_video(); - void internal_run(); - virtual void run() override; - -private: - Logger& m_logger; - const std::chrono::milliseconds m_buffer_limit; - const WallClock m_start_time; - const size_t m_audio_samples_per_frame; - const bool m_has_video; - - QAudioFormat m_audio_format; - std::string m_filename; - - std::mutex m_lock; - std::condition_variable m_cv; - - bool m_stopping = false; - WallClock m_last_drop; - - std::deque m_buffered_audio; - - qint64 m_last_frame_time; - std::deque> m_buffered_frames; - - WriteBuffer m_write_buffer; - - QAudioBufferInput* m_audio_input = nullptr; - QVideoFrameInput* m_video_input = nullptr; - QMediaCaptureSession* m_session = nullptr; - QMediaRecorder* m_recorder = nullptr; - - LifetimeSanitizer m_santizer; -}; - - -// -// This one doesn't work. QMediaRecorder::stop() is an asynchronous operation -// that you must execute event loop to finish it. But we cannot call event -// loop because it leads to reentrancy issues with the destruction path. -// -class StreamRecording2{ -public: - StreamRecording2( - Logger& logger, - std::chrono::milliseconds buffer_limit, - WallClock start_time, - size_t audio_samples_per_frame, - size_t audio_frames_per_second, - bool has_video - ); - ~StreamRecording2(); - - void push_samples(WallClock timestamp, const float* data, size_t frames); - void push_frame(std::shared_ptr frame); - - void stop(); - bool stop_and_save(const std::string& filename); - -private: - void initialize_audio(); - void initialize_video(); - void process(); - - -private: - Logger& m_logger; - const std::chrono::milliseconds m_buffer_limit; - const WallClock m_start_time; - const size_t m_audio_samples_per_frame; - const bool m_has_video; - - QAudioFormat m_audio_format; - std::string m_filename; - - std::mutex m_lock; -// std::condition_variable m_cv; - - bool m_stopping = false; - WallClock m_last_drop; - - std::deque m_buffered_audio; - - qint64 m_last_frame_time; - std::deque> m_buffered_frames; - - WriteBuffer m_write_buffer; - - std::unique_ptr m_audio_input; - std::unique_ptr m_video_input; - QMediaCaptureSession m_session; - std::unique_ptr m_recorder; - - AudioBlock m_current_audio; - std::shared_ptr m_current_frame; - QAudioBuffer m_audio_buffer; - - LifetimeSanitizer m_santizer; -}; - - - - -} -#endif +/* Stream Recorder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_StreamRecorder_H +#define PokemonAutomation_StreamRecorder_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/LifetimeSanitizer.h" +#include "Common/Cpp/Time.h" +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" + +//#include +//using std::cout; +//using std::endl; + + +class QAudioBufferInput; +class QVideoFrameInput; +class QMediaCaptureSession; +class QMediaRecorder; + +namespace PokemonAutomation{ + + +struct AudioBlock{ + WallClock timestamp; + std::vector samples; + + AudioBlock(AudioBlock&&) = default; + AudioBlock& operator=(AudioBlock&&) = default; + AudioBlock(const AudioBlock&) = delete; + void operator=(const AudioBlock&) = delete; + + AudioBlock() + : timestamp(WallClock::min()) + {} + AudioBlock(WallClock p_timestamp, const float* p_samples, size_t p_count) + : timestamp(p_timestamp) + , samples(p_samples, p_samples + p_count) + {} + + void clear(){ + samples.clear(); + } + bool is_valid() const{ + return !samples.empty(); + } +}; + + + +class WriteBuffer : public QIODevice{ +public: + ~WriteBuffer(){ + waitForBytesWritten(-1); + } + WriteBuffer(){ + setOpenMode(QIODeviceBase::WriteOnly); + } + + virtual qint64 readData(char* data, qint64 maxlen){ return 0; } + virtual qint64 writeData(const char* data, qint64 len){ + m_bytes += len; +// cout << "total = " << m_bytes << ", current = " << len << endl; + m_blocks.emplace_back(data, data + len); +// cout << "data = " << (unsigned)data[0] << endl; + return len; + } + + bool write(Logger& logger, const std::string& filename) const{ +// cout << "write()" << endl; + QFile file(QString::fromStdString(filename)); + if (!file.open(QFile::WriteOnly)){ + logger.log("Failed to write file: " + filename, COLOR_RED); + return false; + } + for (const std::vector& block : m_blocks){ + if ((size_t)file.write(block.data(), block.size()) != block.size()){ + logger.log("Failed to write file: " + filename, COLOR_RED); + return false; + } + } + file.close(); + return true; + } + +private: + uint64_t m_bytes = 0; + std::deque> m_blocks; +}; + + + + +// +// This one works, but it leaks a tiny bit of memory each time QMediaRecorder +// is started and stopped. +// +class StreamRecording : public QThread{ +public: + StreamRecording( + Logger& logger, + std::chrono::milliseconds buffer_limit, + WallClock start_time, + size_t audio_samples_per_frame, + size_t audio_frames_per_second, + bool has_video + ); + ~StreamRecording(); + + void push_samples(WallClock timestamp, const float* data, size_t frames); + void push_frame(std::shared_ptr frame); + + bool stop_and_save(const std::string& filename); + +private: + std::unique_ptr initialize_audio(); + std::unique_ptr initialize_video(); + void internal_run(); + virtual void run() override; + +private: + Logger& m_logger; + const std::chrono::milliseconds m_buffer_limit; + const WallClock m_start_time; + const size_t m_audio_samples_per_frame; + const bool m_has_video; + + QAudioFormat m_audio_format; + std::string m_filename; + + std::mutex m_lock; + std::condition_variable m_cv; + + bool m_stopping = false; + WallClock m_last_drop; + + std::deque m_buffered_audio; + + qint64 m_last_frame_time; + std::deque> m_buffered_frames; + + WriteBuffer m_write_buffer; + + QAudioBufferInput* m_audio_input = nullptr; + QVideoFrameInput* m_video_input = nullptr; + QMediaCaptureSession* m_session = nullptr; + QMediaRecorder* m_recorder = nullptr; + + LifetimeSanitizer m_santizer; +}; + + +// +// This one doesn't work. QMediaRecorder::stop() is an asynchronous operation +// that you must execute event loop to finish it. But we cannot call event +// loop because it leads to reentrancy issues with the destruction path. +// +class StreamRecording2{ +public: + StreamRecording2( + Logger& logger, + std::chrono::milliseconds buffer_limit, + WallClock start_time, + size_t audio_samples_per_frame, + size_t audio_frames_per_second, + bool has_video + ); + ~StreamRecording2(); + + void push_samples(WallClock timestamp, const float* data, size_t frames); + void push_frame(std::shared_ptr frame); + + void stop(); + bool stop_and_save(const std::string& filename); + +private: + void initialize_audio(); + void initialize_video(); + void process(); + + +private: + Logger& m_logger; + const std::chrono::milliseconds m_buffer_limit; + const WallClock m_start_time; + const size_t m_audio_samples_per_frame; + const bool m_has_video; + + QAudioFormat m_audio_format; + std::string m_filename; + + std::mutex m_lock; +// std::condition_variable m_cv; + + bool m_stopping = false; + WallClock m_last_drop; + + std::deque m_buffered_audio; + + qint64 m_last_frame_time; + std::deque> m_buffered_frames; + + WriteBuffer m_write_buffer; + + std::unique_ptr m_audio_input; + std::unique_ptr m_video_input; + QMediaCaptureSession m_session; + std::unique_ptr m_recorder; + + AudioBlock m_current_audio; + std::shared_ptr m_current_frame; + QAudioBuffer m_audio_buffer; + + LifetimeSanitizer m_santizer; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Startup/NewVersionCheck.cpp b/SerialPrograms/Source/CommonFramework/Startup/NewVersionCheck.cpp index 2afb5a3976..66a847da50 100644 --- a/SerialPrograms/Source/CommonFramework/Startup/NewVersionCheck.cpp +++ b/SerialPrograms/Source/CommonFramework/Startup/NewVersionCheck.cpp @@ -1,268 +1,268 @@ -/* New Version Check - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Time.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Options/CheckForUpdatesOption.h" -#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" -#include "CommonFramework/Tools/FileDownloader.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "NewVersionCheck.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -static auto CHECK_FOR_UPDATES_PERIOD = std::chrono::days(1); - - -struct ProgramVersion{ - int major; - int minor; - int patch; - std::string version_text; - - ProgramVersion(Logger& logger, const JsonObject* json){ - if (!json->read_integer(major, "VersionMajor")){ - throw_and_log(logger, "Invalid version JSON: Missing major version."); - } - if (!json->read_integer(minor, "VersionMinor")){ - throw_and_log(logger, "Invalid version JSON: Missing minor version."); - } - if (!json->read_integer(patch, "VersionPatch")){ - throw_and_log(logger, "Invalid version JSON: Missing patch #."); - } - version_text = std::to_string(major) - + "." + std::to_string(minor) - + "." + std::to_string(patch); - } - - bool is_newer() const{ - if (major > PROGRAM_VERSION_MAJOR){ - return true; - } - if (major < PROGRAM_VERSION_MAJOR){ - return false; - } - - if (minor > PROGRAM_VERSION_MINOR){ - return true; - } - if (minor < PROGRAM_VERSION_MINOR){ - return false; - } - - if (patch > PROGRAM_VERSION_PATCH){ - return true; - } - - return false; - } - - bool show_update_nag() const{ - if (!is_newer()){ - return false; - } - std::string skip_version = GlobalSettings::instance().CHECK_FOR_UPDATES->SKIP_VERSION; - return version_text != skip_version; - } -}; - -bool compare_version(Logger& logger, const JsonObject* json){ - if (json == nullptr){ - logger.log("Invalid version JSON.", COLOR_RED); - return false; - } - - int major; - int minor; - int patch; - if (!json->read_integer(major, "VersionMajor")){ - logger.log("Invalid version JSON: Missing major version.", COLOR_RED); - return false; - } - if (!json->read_integer(minor, "VersionMinor")){ - logger.log("Invalid version JSON: Missing minor version.", COLOR_RED); - return false; - } - if (!json->read_integer(patch, "VersionPatch")){ - logger.log("Invalid version JSON: Missing patch #.", COLOR_RED); - return false; - } - std::string full_version = std::to_string(major) - + "." + std::to_string(minor) - + "." + std::to_string(patch); - std::string skip_version = GlobalSettings::instance().CHECK_FOR_UPDATES->SKIP_VERSION; - if (full_version == skip_version){ - return false; - } - - if (major > PROGRAM_VERSION_MAJOR){ - return true; - } - if (major < PROGRAM_VERSION_MAJOR){ - return false; - } - - if (minor > PROGRAM_VERSION_MINOR){ - return true; - } - if (minor < PROGRAM_VERSION_MINOR){ - return false; - } - - if (patch > PROGRAM_VERSION_PATCH){ - return true; - } - - return false; -} -std::string get_changes(const JsonObject& json){ - const std::string* changes = json.get_string("Changes"); - if (changes == nullptr){ - return ""; - } - return "

" + *changes; -} -void show_update_box( - const std::string& title, - const std::string& link_text, - const std::string& link_url, - const std::string& header, - const ProgramVersion& version, - const JsonObject& node -){ - QMessageBox box; - QPushButton* ok = box.addButton(QMessageBox::Ok); - QPushButton* skip = box.addButton("Skip this Version", QMessageBox::NoRole); - - box.setTextFormat(Qt::RichText); - std::string text = header + "
"; - text += make_text_url(link_url, link_text); - text += get_changes(node); - - - box.setWindowTitle(QString::fromStdString(title)); - box.setText(QString::fromStdString(text)); - -// box.open(); - - box.exec(); - - QAbstractButton* clicked = box.clickedButton(); - if (clicked == ok){ - return; - } - if (clicked == skip){ - GlobalSettings::instance().CHECK_FOR_UPDATES->SKIP_VERSION.set(version.version_text); - return; - } - - -// box.information( -// nullptr, -// QString::fromStdString(title), -// QString::fromStdString(text) -// ); -} - - -void check_new_version(Logger& logger){ - bool check_release = GlobalSettings::instance().CHECK_FOR_UPDATES->RELEASE0; - bool check_beta = GlobalSettings::instance().CHECK_FOR_UPDATES->PUBLIC_BETA0; - bool check_private_beta = GlobalSettings::instance().CHECK_FOR_UPDATES->PRIVATE_BETA0; - bool updates_enabled = false; - updates_enabled |= check_release; - updates_enabled |= check_beta; - updates_enabled |= check_private_beta; - - if (!updates_enabled){ - return; - } - - static WallClock last_version_check = WallClock::min(); - WallClock now = current_time(); - if (last_version_check != WallClock::min() && now - last_version_check < CHECK_FOR_UPDATES_PERIOD){ - return; - } - last_version_check = now; - - logger.log("Checking for new version..."); - JsonValue json; - try{ - json = FileDownloader::download_json_file( - logger, - "https://raw.githubusercontent.com/PokemonAutomation/ComputerControl/master/LatestVersion.json" - ); - }catch (OperationFailedException&){ - return; - } - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - logger.log("Invalid version JSON.", COLOR_RED); - return; - } - - -// cout << json.dump() << endl; - - if (check_private_beta){ - const JsonObject* node = obj->get_object("PrivateBeta"); - ProgramVersion latest(logger, node); - if (latest.show_update_nag()){ - show_update_box( - "New Private Beta Available!", - "Download from our Discord!", - "https://discord.com/channels/695809740428673034/732736538965704726", - "A new private beta is available!", - latest, *node - ); - return; - } - } - if (check_beta){ - const JsonObject* node = obj->get_object("Beta"); - ProgramVersion latest(logger, node); - if (latest.show_update_nag()){ - show_update_box( - "New Beta Available!", - "Download here.", - "https://github.com/PokemonAutomation/ComputerControl/releases", - "A new beta is available!", - latest, *node - ); - return; - } - } - if (check_release){ - const JsonObject* node = obj->get_object("Release"); - ProgramVersion latest(logger, node); - if (latest.show_update_nag()){ - show_update_box( - "New Version Available!", - "Download here.", - "https://github.com/PokemonAutomation/ComputerControl/releases", - "A new version is available!", - latest, *node - ); - return; - } - } - -} - - - - - -} +/* New Version Check + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Options/CheckForUpdatesOption.h" +#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" +#include "CommonFramework/Tools/FileDownloader.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "NewVersionCheck.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +static auto CHECK_FOR_UPDATES_PERIOD = std::chrono::days(1); + + +struct ProgramVersion{ + int major; + int minor; + int patch; + std::string version_text; + + ProgramVersion(Logger& logger, const JsonObject* json){ + if (!json->read_integer(major, "VersionMajor")){ + throw_and_log(logger, "Invalid version JSON: Missing major version."); + } + if (!json->read_integer(minor, "VersionMinor")){ + throw_and_log(logger, "Invalid version JSON: Missing minor version."); + } + if (!json->read_integer(patch, "VersionPatch")){ + throw_and_log(logger, "Invalid version JSON: Missing patch #."); + } + version_text = std::to_string(major) + + "." + std::to_string(minor) + + "." + std::to_string(patch); + } + + bool is_newer() const{ + if (major > PROGRAM_VERSION_MAJOR){ + return true; + } + if (major < PROGRAM_VERSION_MAJOR){ + return false; + } + + if (minor > PROGRAM_VERSION_MINOR){ + return true; + } + if (minor < PROGRAM_VERSION_MINOR){ + return false; + } + + if (patch > PROGRAM_VERSION_PATCH){ + return true; + } + + return false; + } + + bool show_update_nag() const{ + if (!is_newer()){ + return false; + } + std::string skip_version = GlobalSettings::instance().CHECK_FOR_UPDATES->SKIP_VERSION; + return version_text != skip_version; + } +}; + +bool compare_version(Logger& logger, const JsonObject* json){ + if (json == nullptr){ + logger.log("Invalid version JSON.", COLOR_RED); + return false; + } + + int major; + int minor; + int patch; + if (!json->read_integer(major, "VersionMajor")){ + logger.log("Invalid version JSON: Missing major version.", COLOR_RED); + return false; + } + if (!json->read_integer(minor, "VersionMinor")){ + logger.log("Invalid version JSON: Missing minor version.", COLOR_RED); + return false; + } + if (!json->read_integer(patch, "VersionPatch")){ + logger.log("Invalid version JSON: Missing patch #.", COLOR_RED); + return false; + } + std::string full_version = std::to_string(major) + + "." + std::to_string(minor) + + "." + std::to_string(patch); + std::string skip_version = GlobalSettings::instance().CHECK_FOR_UPDATES->SKIP_VERSION; + if (full_version == skip_version){ + return false; + } + + if (major > PROGRAM_VERSION_MAJOR){ + return true; + } + if (major < PROGRAM_VERSION_MAJOR){ + return false; + } + + if (minor > PROGRAM_VERSION_MINOR){ + return true; + } + if (minor < PROGRAM_VERSION_MINOR){ + return false; + } + + if (patch > PROGRAM_VERSION_PATCH){ + return true; + } + + return false; +} +std::string get_changes(const JsonObject& json){ + const std::string* changes = json.get_string("Changes"); + if (changes == nullptr){ + return ""; + } + return "

" + *changes; +} +void show_update_box( + const std::string& title, + const std::string& link_text, + const std::string& link_url, + const std::string& header, + const ProgramVersion& version, + const JsonObject& node +){ + QMessageBox box; + QPushButton* ok = box.addButton(QMessageBox::Ok); + QPushButton* skip = box.addButton("Skip this Version", QMessageBox::NoRole); + + box.setTextFormat(Qt::RichText); + std::string text = header + "
"; + text += make_text_url(link_url, link_text); + text += get_changes(node); + + + box.setWindowTitle(QString::fromStdString(title)); + box.setText(QString::fromStdString(text)); + +// box.open(); + + box.exec(); + + QAbstractButton* clicked = box.clickedButton(); + if (clicked == ok){ + return; + } + if (clicked == skip){ + GlobalSettings::instance().CHECK_FOR_UPDATES->SKIP_VERSION.set(version.version_text); + return; + } + + +// box.information( +// nullptr, +// QString::fromStdString(title), +// QString::fromStdString(text) +// ); +} + + +void check_new_version(Logger& logger){ + bool check_release = GlobalSettings::instance().CHECK_FOR_UPDATES->RELEASE0; + bool check_beta = GlobalSettings::instance().CHECK_FOR_UPDATES->PUBLIC_BETA0; + bool check_private_beta = GlobalSettings::instance().CHECK_FOR_UPDATES->PRIVATE_BETA0; + bool updates_enabled = false; + updates_enabled |= check_release; + updates_enabled |= check_beta; + updates_enabled |= check_private_beta; + + if (!updates_enabled){ + return; + } + + static WallClock last_version_check = WallClock::min(); + WallClock now = current_time(); + if (last_version_check != WallClock::min() && now - last_version_check < CHECK_FOR_UPDATES_PERIOD){ + return; + } + last_version_check = now; + + logger.log("Checking for new version..."); + JsonValue json; + try{ + json = FileDownloader::download_json_file( + logger, + "https://raw.githubusercontent.com/PokemonAutomation/ComputerControl/master/LatestVersion.json" + ); + }catch (OperationFailedException&){ + return; + } + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + logger.log("Invalid version JSON.", COLOR_RED); + return; + } + + +// cout << json.dump() << endl; + + if (check_private_beta){ + const JsonObject* node = obj->get_object("PrivateBeta"); + ProgramVersion latest(logger, node); + if (latest.show_update_nag()){ + show_update_box( + "New Private Beta Available!", + "Download from our Discord!", + "https://discord.com/channels/695809740428673034/732736538965704726", + "A new private beta is available!", + latest, *node + ); + return; + } + } + if (check_beta){ + const JsonObject* node = obj->get_object("Beta"); + ProgramVersion latest(logger, node); + if (latest.show_update_nag()){ + show_update_box( + "New Beta Available!", + "Download here.", + "https://github.com/PokemonAutomation/ComputerControl/releases", + "A new beta is available!", + latest, *node + ); + return; + } + } + if (check_release){ + const JsonObject* node = obj->get_object("Release"); + ProgramVersion latest(logger, node); + if (latest.show_update_nag()){ + show_update_box( + "New Version Available!", + "Download here.", + "https://github.com/PokemonAutomation/ComputerControl/releases", + "A new version is available!", + latest, *node + ); + return; + } + } + +} + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Startup/NewVersionCheck.h b/SerialPrograms/Source/CommonFramework/Startup/NewVersionCheck.h index 792e587f13..174a609949 100644 --- a/SerialPrograms/Source/CommonFramework/Startup/NewVersionCheck.h +++ b/SerialPrograms/Source/CommonFramework/Startup/NewVersionCheck.h @@ -1,19 +1,19 @@ -/* New Version Check - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NewVersionCheck_H -#define PokemonAutomation_NewVersionCheck_H - -#include "CommonFramework/Logging/Logger.h" - -namespace PokemonAutomation{ - -void check_new_version(Logger& logger = global_logger_tagged()); - - - -} -#endif +/* New Version Check + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NewVersionCheck_H +#define PokemonAutomation_NewVersionCheck_H + +#include "CommonFramework/Logging/Logger.h" + +namespace PokemonAutomation{ + +void check_new_version(Logger& logger = global_logger_tagged()); + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Startup/SetupSettings.cpp b/SerialPrograms/Source/CommonFramework/Startup/SetupSettings.cpp index 0cf78e8c06..f189977e43 100644 --- a/SerialPrograms/Source/CommonFramework/Startup/SetupSettings.cpp +++ b/SerialPrograms/Source/CommonFramework/Startup/SetupSettings.cpp @@ -1,223 +1,223 @@ -/* Setup Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0) -#if QT_CONFIG(permissions) -#include -#endif -#endif -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "SetupSettings.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - -bool migrate_settings(Logger& logger, const std::string& file_name){ - QFile cur_dir_file(QString::fromStdString(file_name)); - QFile folder_file(QString::fromStdString(SETTINGS_PATH() + file_name)); - - logger.log("Checking if user setting JSON file need to be migrated..."); - - if (!cur_dir_file.exists() && !folder_file.exists()){ - logger.log("Clean install, nothing to migrate."); - return true; - } - - if (!cur_dir_file.exists() && folder_file.exists()){ - logger.log("Migrated, nothing to do."); - return true; - } - - if (cur_dir_file.exists() && !folder_file.exists()){ - logger.log("Migrating old setting file to the new folder..."); - cur_dir_file.copy(folder_file.fileName()); - logger.log("Renaming old setting file as backup..."); - cur_dir_file.rename(cur_dir_file.fileName() + ".bak"); - logger.log("Migrated."); - QMessageBox box; - box.setTextFormat(Qt::RichText); - box.information( - nullptr, - "Settings Migrated!", - QString::fromStdString( - "Detected a settings file at the old location used by version 0.29 and earlier.
" - "It has been automatically moved into the \"" + SETTINGS_PATH() + "\" folder." - ) - ); - return true; - } - - // last case: cur_dir_file.exists() && folder_file.exists() - logger.log("Two configs detected, showing prompt..."); - QMessageBox box; - box.setTextFormat(Qt::RichText); - box.critical( - nullptr, - "Two settings files detected!", - QString::fromStdString( - "Detected two settings files at these locations:

" + - cur_dir_file.fileName().toStdString() + " (versions 0.29 and older)
" + - folder_file.fileName().toStdString() + " (version 0.30)" + - "

This probably happened because you used an early beta of v0.30.x which created a new " - "settings file at the new location. Please either delete or rename the file you do not want to use." - ) - ); - return false; -} - -bool migrate_stats(Logger& logger){ - logger.log("Checking if stats file should be migrated..."); - - std::string path = GlobalSettings::instance().STATS_FILE; - if (path != "PA-Stats.txt"){ - logger.log("Stats file not at old default location. Will not attempt to migrate..."); - return true; - } - - const std::string new_path = GlobalSettings::instance().STATS_FILE.default_value(); - - // old location: current working directory - QFile cur_dir_file(QString::fromStdString(path)); - // new location: - QFile folder_file(QString::fromStdString(new_path)); - - if (!cur_dir_file.exists() && !folder_file.exists()){ - logger.log("Clean install, nothing to migrate."); - return true; - } - - if (!cur_dir_file.exists() && folder_file.exists()){ - logger.log("File migrated. Stats path in settings not updated. Updating..."); - GlobalSettings::instance().STATS_FILE.restore_defaults(); - return true; - } - - if (cur_dir_file.exists() && !folder_file.exists()){ - logger.log("Migrating old stats file to the folder..."); - cur_dir_file.copy(folder_file.fileName()); - logger.log("Renaming old stats file as backup..."); - cur_dir_file.rename(cur_dir_file.fileName() + ".bak"); - GlobalSettings::instance().STATS_FILE.restore_defaults(); - logger.log("Migrated."); - QMessageBox box; - box.setTextFormat(Qt::RichText); - box.information( - nullptr, - "Settings Migrated!", - QString::fromStdString( - "Detected a stats file at the old location used by version 0.29 and earlier.
" - "It has been automatically moved into the \"" + SETTINGS_PATH() + "\" folder." - ) - ); - return true; - } - - // last case: cur_dir_file.exists() && folder_file.exists() - logger.log("Two stats files detected, showing prompt..."); - QMessageBox box; - box.setTextFormat(Qt::RichText); - box.critical( - nullptr, - "Two settings files detected!", - QString::fromStdString( - "Detected two stats files at these locations:

" + - cur_dir_file.fileName().toStdString() + " (versions 0.29 and older)
" + - folder_file.fileName().toStdString() + " (version 0.30)" + - "

This probably happened because you used an early beta of v0.30.x which created a new stats file at the new location. " - "Please either delete or rename the file you do not want to use." - ) - ); - return false; -} - - -void set_permissions(QObject& object){ -#if defined(__APPLE__) -#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0) -#if QT_CONFIG(permissions) - cout << "Checking MacOS Permissions..." << endl; - QCameraPermission camera_permission; - switch(qApp->checkPermission(camera_permission)){ - case Qt::PermissionStatus::Undetermined: - cout << "Camera permission undetermined" << endl; - qApp->requestPermission(camera_permission, &object, [](const QPermission &permission){ - cout << "camera request is ready!" << endl; - }); - cout << "Requested Camera permission" << endl; - break; - case Qt::PermissionStatus::Denied: - cout << "No camera permission found" << endl; - qApp->requestPermission(camera_permission, &object, [](const QPermission &permission){ - cout << "camera request is ready!" << endl; - }); - cout << "Requested Camera permission" << endl; - break; - case Qt::PermissionStatus::Granted: - cout << "Camera permission granted" << endl; - break; - } - - QMicrophonePermission microphone_permission; - switch(qApp->checkPermission(microphone_permission)){ - case Qt::PermissionStatus::Undetermined: - cout << "Microphone permission undetermined" << endl; - qApp->requestPermission(microphone_permission, &object, [](const QPermission &permission){ - cout << "Microphone request is ready!" << endl; - }); - cout << "Requested microphone permission" << endl; - break; - case Qt::PermissionStatus::Denied: - cout << "No microphone permission found" << endl; - qApp->requestPermission(microphone_permission, &object, [](const QPermission &permission){ - cout << "Microphone request is ready!" << endl; - }); - cout << "Requested microphone permission" << endl; - break; - case Qt::PermissionStatus::Granted: - cout << "Microphone permission granted" << endl; - break; - } -#endif -#endif -#endif -} - - -bool check_resource_folder(Logger& logger){ - QDir resources_folder(QString::fromStdString(RESOURCE_PATH())); - if (resources_folder.exists()){ - logger.log("Found Resource folder at " + RESOURCE_PATH()); - return true; - } - logger.log("No Resources/ folder at " + RESOURCE_PATH()); - QMessageBox box; - box.setTextFormat(Qt::RichText); - box.critical( - nullptr, - "No Resources Folder!", - QString::fromStdString( - "No Resources Folder:

" - "Make sure you download Resources folder from latest release at
" - "https://github.com/PokemonAutomation/ComputerControl/releases/

" - "The Resources folder is part of PA-SerialPrograms-[VERSION]-[DATE].zip

" - "Extract the Resources folder from the zip file and place it at following path:

" + RESOURCE_PATH() - ) - ); - return false; -} - - - -} +/* Setup Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0) +#if QT_CONFIG(permissions) +#include +#endif +#endif +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "SetupSettings.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + +bool migrate_settings(Logger& logger, const std::string& file_name){ + QFile cur_dir_file(QString::fromStdString(file_name)); + QFile folder_file(QString::fromStdString(SETTINGS_PATH() + file_name)); + + logger.log("Checking if user setting JSON file need to be migrated..."); + + if (!cur_dir_file.exists() && !folder_file.exists()){ + logger.log("Clean install, nothing to migrate."); + return true; + } + + if (!cur_dir_file.exists() && folder_file.exists()){ + logger.log("Migrated, nothing to do."); + return true; + } + + if (cur_dir_file.exists() && !folder_file.exists()){ + logger.log("Migrating old setting file to the new folder..."); + cur_dir_file.copy(folder_file.fileName()); + logger.log("Renaming old setting file as backup..."); + cur_dir_file.rename(cur_dir_file.fileName() + ".bak"); + logger.log("Migrated."); + QMessageBox box; + box.setTextFormat(Qt::RichText); + box.information( + nullptr, + "Settings Migrated!", + QString::fromStdString( + "Detected a settings file at the old location used by version 0.29 and earlier.
" + "It has been automatically moved into the \"" + SETTINGS_PATH() + "\" folder." + ) + ); + return true; + } + + // last case: cur_dir_file.exists() && folder_file.exists() + logger.log("Two configs detected, showing prompt..."); + QMessageBox box; + box.setTextFormat(Qt::RichText); + box.critical( + nullptr, + "Two settings files detected!", + QString::fromStdString( + "Detected two settings files at these locations:

" + + cur_dir_file.fileName().toStdString() + " (versions 0.29 and older)
" + + folder_file.fileName().toStdString() + " (version 0.30)" + + "

This probably happened because you used an early beta of v0.30.x which created a new " + "settings file at the new location. Please either delete or rename the file you do not want to use." + ) + ); + return false; +} + +bool migrate_stats(Logger& logger){ + logger.log("Checking if stats file should be migrated..."); + + std::string path = GlobalSettings::instance().STATS_FILE; + if (path != "PA-Stats.txt"){ + logger.log("Stats file not at old default location. Will not attempt to migrate..."); + return true; + } + + const std::string new_path = GlobalSettings::instance().STATS_FILE.default_value(); + + // old location: current working directory + QFile cur_dir_file(QString::fromStdString(path)); + // new location: + QFile folder_file(QString::fromStdString(new_path)); + + if (!cur_dir_file.exists() && !folder_file.exists()){ + logger.log("Clean install, nothing to migrate."); + return true; + } + + if (!cur_dir_file.exists() && folder_file.exists()){ + logger.log("File migrated. Stats path in settings not updated. Updating..."); + GlobalSettings::instance().STATS_FILE.restore_defaults(); + return true; + } + + if (cur_dir_file.exists() && !folder_file.exists()){ + logger.log("Migrating old stats file to the folder..."); + cur_dir_file.copy(folder_file.fileName()); + logger.log("Renaming old stats file as backup..."); + cur_dir_file.rename(cur_dir_file.fileName() + ".bak"); + GlobalSettings::instance().STATS_FILE.restore_defaults(); + logger.log("Migrated."); + QMessageBox box; + box.setTextFormat(Qt::RichText); + box.information( + nullptr, + "Settings Migrated!", + QString::fromStdString( + "Detected a stats file at the old location used by version 0.29 and earlier.
" + "It has been automatically moved into the \"" + SETTINGS_PATH() + "\" folder." + ) + ); + return true; + } + + // last case: cur_dir_file.exists() && folder_file.exists() + logger.log("Two stats files detected, showing prompt..."); + QMessageBox box; + box.setTextFormat(Qt::RichText); + box.critical( + nullptr, + "Two settings files detected!", + QString::fromStdString( + "Detected two stats files at these locations:

" + + cur_dir_file.fileName().toStdString() + " (versions 0.29 and older)
" + + folder_file.fileName().toStdString() + " (version 0.30)" + + "

This probably happened because you used an early beta of v0.30.x which created a new stats file at the new location. " + "Please either delete or rename the file you do not want to use." + ) + ); + return false; +} + + +void set_permissions(QObject& object){ +#if defined(__APPLE__) +#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0) +#if QT_CONFIG(permissions) + cout << "Checking MacOS Permissions..." << endl; + QCameraPermission camera_permission; + switch(qApp->checkPermission(camera_permission)){ + case Qt::PermissionStatus::Undetermined: + cout << "Camera permission undetermined" << endl; + qApp->requestPermission(camera_permission, &object, [](const QPermission &permission){ + cout << "camera request is ready!" << endl; + }); + cout << "Requested Camera permission" << endl; + break; + case Qt::PermissionStatus::Denied: + cout << "No camera permission found" << endl; + qApp->requestPermission(camera_permission, &object, [](const QPermission &permission){ + cout << "camera request is ready!" << endl; + }); + cout << "Requested Camera permission" << endl; + break; + case Qt::PermissionStatus::Granted: + cout << "Camera permission granted" << endl; + break; + } + + QMicrophonePermission microphone_permission; + switch(qApp->checkPermission(microphone_permission)){ + case Qt::PermissionStatus::Undetermined: + cout << "Microphone permission undetermined" << endl; + qApp->requestPermission(microphone_permission, &object, [](const QPermission &permission){ + cout << "Microphone request is ready!" << endl; + }); + cout << "Requested microphone permission" << endl; + break; + case Qt::PermissionStatus::Denied: + cout << "No microphone permission found" << endl; + qApp->requestPermission(microphone_permission, &object, [](const QPermission &permission){ + cout << "Microphone request is ready!" << endl; + }); + cout << "Requested microphone permission" << endl; + break; + case Qt::PermissionStatus::Granted: + cout << "Microphone permission granted" << endl; + break; + } +#endif +#endif +#endif +} + + +bool check_resource_folder(Logger& logger){ + QDir resources_folder(QString::fromStdString(RESOURCE_PATH())); + if (resources_folder.exists()){ + logger.log("Found Resource folder at " + RESOURCE_PATH()); + return true; + } + logger.log("No Resources/ folder at " + RESOURCE_PATH()); + QMessageBox box; + box.setTextFormat(Qt::RichText); + box.critical( + nullptr, + "No Resources Folder!", + QString::fromStdString( + "No Resources Folder:

" + "Make sure you download Resources folder from latest release at
" + "https://github.com/PokemonAutomation/ComputerControl/releases/

" + "The Resources folder is part of PA-SerialPrograms-[VERSION]-[DATE].zip

" + "Extract the Resources folder from the zip file and place it at following path:

" + RESOURCE_PATH() + ) + ); + return false; +} + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Startup/SetupSettings.h b/SerialPrograms/Source/CommonFramework/Startup/SetupSettings.h index 63d230c79b..baf5d83f9f 100644 --- a/SerialPrograms/Source/CommonFramework/Startup/SetupSettings.h +++ b/SerialPrograms/Source/CommonFramework/Startup/SetupSettings.h @@ -1,37 +1,37 @@ -/* Setup Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SetupSettings_H -#define PokemonAutomation_SetupSettings_H - -#include - -class QObject; - -namespace PokemonAutomation{ - -class Logger; - -// Move user setting JSON file from old location to the new one -// return true if there is no need for migration or the migration is successful -// return false if migration fails. In this case it will also pop a critical error message box -bool migrate_settings(Logger& logger, const std::string& file_name); - -// Move stats file from old location to the new one -// return true if there is no need for migration or the migration is successful -// return false if migration fails. In this case it will also pop a critical error message box -bool migrate_stats(Logger& logger); - -// Use Qt to setup permissions of cameras and microphones on macOS. -// See https://www.qt.io/blog/permission-apis-in-qt-6.5 -void set_permissions(QObject& object); - -// Return true if there is the required Resources/ folder. -// When the folder is missing, it will also pop a critical error message box -bool check_resource_folder(Logger& logger); - -} -#endif +/* Setup Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SetupSettings_H +#define PokemonAutomation_SetupSettings_H + +#include + +class QObject; + +namespace PokemonAutomation{ + +class Logger; + +// Move user setting JSON file from old location to the new one +// return true if there is no need for migration or the migration is successful +// return false if migration fails. In this case it will also pop a critical error message box +bool migrate_settings(Logger& logger, const std::string& file_name); + +// Move stats file from old location to the new one +// return true if there is no need for migration or the migration is successful +// return false if migration fails. In this case it will also pop a critical error message box +bool migrate_stats(Logger& logger); + +// Use Qt to setup permissions of cameras and microphones on macOS. +// See https://www.qt.io/blog/permission-apis-in-qt-6.5 +void set_permissions(QObject& object); + +// Return true if there is the required Resources/ folder. +// When the folder is missing, it will also pop a critical error message box +bool check_resource_folder(Logger& logger); + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Tools/GlobalThreadPools.cpp b/SerialPrograms/Source/CommonFramework/Tools/GlobalThreadPools.cpp new file mode 100644 index 0000000000..22c8ba4336 --- /dev/null +++ b/SerialPrograms/Source/CommonFramework/Tools/GlobalThreadPools.cpp @@ -0,0 +1,40 @@ +/* Global Thread Pools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/Options/Environment/PerformanceOptions.h" +#include "GlobalThreadPools.h" + +namespace PokemonAutomation{ +namespace GlobalThreadPools{ + + + +ComputationThreadPool& realtime_inference(){ + static ComputationThreadPool runner( + [](){ + GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_POOL.PRIORITY.set_on_this_thread(global_logger_tagged()); + }, + 0, GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_POOL.MAX_THREADS + ); + return runner; +} +ComputationThreadPool& normal_inference(){ + static ComputationThreadPool runner( + [](){ + GlobalSettings::instance().PERFORMANCE->NORMAL_THREAD_POOL.PRIORITY.set_on_this_thread(global_logger_tagged()); + }, + 0, GlobalSettings::instance().PERFORMANCE->NORMAL_THREAD_POOL.MAX_THREADS + ); + return runner; +} + + + + +} +} diff --git a/SerialPrograms/Source/CommonFramework/Tools/GlobalThreadPools.h b/SerialPrograms/Source/CommonFramework/Tools/GlobalThreadPools.h new file mode 100644 index 0000000000..ca95ea5bc6 --- /dev/null +++ b/SerialPrograms/Source/CommonFramework/Tools/GlobalThreadPools.h @@ -0,0 +1,24 @@ +/* Global Thread Pools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_GlobalThreadPools_H +#define PokemonAutomation_CommonTools_GlobalThreadPools_H + +#include "Common/Cpp/Concurrency/ComputationThreadPool.h" + +namespace PokemonAutomation{ +namespace GlobalThreadPools{ + + + +ComputationThreadPool& realtime_inference(); +ComputationThreadPool& normal_inference(); + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Tools/ProgramEnvironment.cpp b/SerialPrograms/Source/CommonFramework/Tools/ProgramEnvironment.cpp index 83e9546d77..9b2b7532fb 100644 --- a/SerialPrograms/Source/CommonFramework/Tools/ProgramEnvironment.cpp +++ b/SerialPrograms/Source/CommonFramework/Tools/ProgramEnvironment.cpp @@ -22,7 +22,6 @@ struct ProgramEnvironmentData{ AsyncDispatcher m_realtime_dispatcher; AsyncDispatcher m_realtime_inference_dispatcher; - AsyncDispatcher m_normal_inference_dispatcher; ProgramEnvironmentData( const ProgramInfo& program_info @@ -30,19 +29,13 @@ struct ProgramEnvironmentData{ : m_program_info(program_info) , m_realtime_dispatcher( [](){ - GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(); + GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(global_logger_tagged()); }, 0 ) , m_realtime_inference_dispatcher( [](){ - GlobalSettings::instance().PERFORMANCE->REALTIME_INFERENCE_PRIORITY.set_on_this_thread(); - }, - 0 - ) - , m_normal_inference_dispatcher( - [](){ - GlobalSettings::instance().PERFORMANCE->NORMAL_INFERENCE_PRIORITY.set_on_this_thread(); + GlobalSettings::instance().PERFORMANCE->INFERENCE_PIVOT_PRIORITY.set_on_this_thread(global_logger_tagged()); }, 0 ) @@ -76,9 +69,6 @@ AsyncDispatcher& ProgramEnvironment::realtime_dispatcher(){ AsyncDispatcher& ProgramEnvironment::realtime_inference_dispatcher(){ return m_data->m_realtime_inference_dispatcher; } -AsyncDispatcher& ProgramEnvironment::normal_inference_dispatcher(){ - return m_data->m_normal_inference_dispatcher; -} void ProgramEnvironment::update_stats(){ diff --git a/SerialPrograms/Source/CommonFramework/Tools/ProgramEnvironment.h b/SerialPrograms/Source/CommonFramework/Tools/ProgramEnvironment.h index 6915f42652..620ac5bb09 100644 --- a/SerialPrograms/Source/CommonFramework/Tools/ProgramEnvironment.h +++ b/SerialPrograms/Source/CommonFramework/Tools/ProgramEnvironment.h @@ -50,10 +50,6 @@ class ProgramEnvironment{ // program to encounter issues. AsyncDispatcher& realtime_inference_dispatcher(); - // A low-priority dispatcher for inference where starvation will not affect - // the functionality of the program. - AsyncDispatcher& normal_inference_dispatcher(); - public: // Stats Management diff --git a/SerialPrograms/Source/CommonFramework/Tools/StatAccumulator.cpp b/SerialPrograms/Source/CommonFramework/Tools/StatAccumulator.cpp index 41a1e54155..90e1c5d0c2 100644 --- a/SerialPrograms/Source/CommonFramework/Tools/StatAccumulator.cpp +++ b/SerialPrograms/Source/CommonFramework/Tools/StatAccumulator.cpp @@ -1,113 +1,113 @@ -/* Stat Accumulator - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Logging/Logger.h" -#include "StatAccumulator.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - - -void StatAccumulatorI32::clear(){ - *this = StatAccumulatorI32(); -} -void StatAccumulatorI32::operator+=(uint32_t x){ - m_count++; - m_sum += x; - m_sqr += (uint64_t)x*x; - m_min = std::min(m_min, x); - m_max = std::max(m_max, x); -} - -double StatAccumulatorI32::mean() const{ - return (double)m_sum / m_count; -} -double StatAccumulatorI32::stddev() const{ - double diff = m_sqr - (double)m_sum*m_sum / m_count; - return std::sqrt(diff / (m_count - 1)); -} - - -std::string StatAccumulatorI32::dump(const char* units, double divider) const{ - divider = 1. / divider; - std::string str; - str += "Count = " + tostr_u_commas(m_count); - str += ", Mean = " + tostr_default(mean() * divider) + units; - str += ", Stddev = " + tostr_default(stddev() * divider) + units; - str += ", Min = " + tostr_default(min() * divider) + units; - str += ", Max = " + tostr_default(max() * divider) + units; - return str; -} -void StatAccumulatorI32::log(Logger& logger, const std::string& label, const char* units, double divider) const{ - logger.log(label + ": " + dump(units, divider), COLOR_MAGENTA); -} - - - -PeriodicStatsReporterI32::PeriodicStatsReporterI32( - const char* label, - const char* units, double divider, - std::chrono::milliseconds period -) - : m_label(label) - , m_units(units) - , m_divider(divider) - , m_period(period) - , m_last_report(current_time()) -{} -void PeriodicStatsReporterI32::report_data(Logger& logger, uint32_t x){ - StatAccumulatorI32::operator+=(x); - WallClock now = current_time(); - if (m_last_report + m_period <= now){ - log(logger, m_label, m_units, m_divider); - clear(); - m_last_report = now; - } - -} - - - - - - -FloatStatAccumulator::FloatStatAccumulator() - : m_count(0) - , m_sum(0) - , m_sqr(0) - , m_min(INFINITY) - , m_max(-INFINITY) -{} - -void FloatStatAccumulator::operator+=(double x){ - m_count++; - m_sum += x; - m_sqr += x*x; - m_min = std::min(m_min, x); - m_max = std::max(m_max, x); -} - -double FloatStatAccumulator::mean() const{ - return m_sum / m_count; -} -double FloatStatAccumulator::stddev() const{ - return std::sqrt((m_sqr - m_sum*m_sum / m_count) / (m_count - 1)); -} -double FloatStatAccumulator::diff_metric(double reference) const{ - return std::sqrt((m_sqr + reference*(reference * m_count - 2 * m_sum)) / m_count); -} - - - - -} +/* Stat Accumulator + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Logging/Logger.h" +#include "StatAccumulator.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + + +void StatAccumulatorI32::clear(){ + *this = StatAccumulatorI32(); +} +void StatAccumulatorI32::operator+=(uint32_t x){ + m_count++; + m_sum += x; + m_sqr += (uint64_t)x*x; + m_min = std::min(m_min, x); + m_max = std::max(m_max, x); +} + +double StatAccumulatorI32::mean() const{ + return (double)m_sum / m_count; +} +double StatAccumulatorI32::stddev() const{ + double diff = m_sqr - (double)m_sum*m_sum / m_count; + return std::sqrt(diff / (m_count - 1)); +} + + +std::string StatAccumulatorI32::dump(const char* units, double divider) const{ + divider = 1. / divider; + std::string str; + str += "Count = " + tostr_u_commas(m_count); + str += ", Mean = " + tostr_default(mean() * divider) + units; + str += ", Stddev = " + tostr_default(stddev() * divider) + units; + str += ", Min = " + tostr_default(min() * divider) + units; + str += ", Max = " + tostr_default(max() * divider) + units; + return str; +} +void StatAccumulatorI32::log(Logger& logger, const std::string& label, const char* units, double divider) const{ + logger.log(label + ": " + dump(units, divider), COLOR_MAGENTA); +} + + + +PeriodicStatsReporterI32::PeriodicStatsReporterI32( + const char* label, + const char* units, double divider, + std::chrono::milliseconds period +) + : m_label(label) + , m_units(units) + , m_divider(divider) + , m_period(period) + , m_last_report(current_time()) +{} +void PeriodicStatsReporterI32::report_data(Logger& logger, uint32_t x){ + StatAccumulatorI32::operator+=(x); + WallClock now = current_time(); + if (m_last_report + m_period <= now){ + log(logger, m_label, m_units, m_divider); + clear(); + m_last_report = now; + } + +} + + + + + + +FloatStatAccumulator::FloatStatAccumulator() + : m_count(0) + , m_sum(0) + , m_sqr(0) + , m_min(INFINITY) + , m_max(-INFINITY) +{} + +void FloatStatAccumulator::operator+=(double x){ + m_count++; + m_sum += x; + m_sqr += x*x; + m_min = std::min(m_min, x); + m_max = std::max(m_max, x); +} + +double FloatStatAccumulator::mean() const{ + return m_sum / m_count; +} +double FloatStatAccumulator::stddev() const{ + return std::sqrt((m_sqr - m_sum*m_sum / m_count) / (m_count - 1)); +} +double FloatStatAccumulator::diff_metric(double reference) const{ + return std::sqrt((m_sqr + reference*(reference * m_count - 2 * m_sum)) / m_count); +} + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Tools/StatAccumulator.h b/SerialPrograms/Source/CommonFramework/Tools/StatAccumulator.h index e9ff8f0021..b3a73b5a4c 100644 --- a/SerialPrograms/Source/CommonFramework/Tools/StatAccumulator.h +++ b/SerialPrograms/Source/CommonFramework/Tools/StatAccumulator.h @@ -1,89 +1,89 @@ -/* Stat Accumulator - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonFramework_StatAccumulator_H -#define PokemonAutomation_CommonFramework_StatAccumulator_H - -#include -#include -#include "Common/Cpp/Time.h" - -namespace PokemonAutomation{ - -class Logger; - - -class StatAccumulatorI32{ -public: - using StatObject = uint32_t; - -public: - void clear(); - void operator+=(uint32_t x); - - uint64_t count() const{ return m_count; }; - uint32_t min() const{ return m_min; } - uint32_t max() const{ return m_max; } - double mean() const; - double stddev() const; - - std::string dump(const char* units, double divider) const; - void log(Logger& logger, const std::string& label, const char* units, double divider) const; - -private: - uint64_t m_count = 0; - uint64_t m_sum = 0; - uint64_t m_sqr = 0; - uint32_t m_min = (uint32_t)-1; - uint32_t m_max = 0; -}; - -class PeriodicStatsReporterI32 : public StatAccumulatorI32{ -public: - PeriodicStatsReporterI32( - const char* label, - const char* units, double divider, - std::chrono::milliseconds period - ); - void report_data(Logger& logger, uint32_t x); - -private: - const char* m_label; - const char* m_units; - double m_divider; - std::chrono::milliseconds m_period; - WallClock m_last_report; -}; - - - -class FloatStatAccumulator{ -public: - using StatObject = double; - -public: - FloatStatAccumulator(); - - void operator+=(double x); - - uint64_t count() const{ return m_count; }; - double min() const{ return m_min; } - double max() const{ return m_max; } - double mean() const; - double stddev() const; - double diff_metric(double reference) const; - -private: - uint64_t m_count; - double m_sum; - double m_sqr; - double m_min; - double m_max; -}; - - -} -#endif +/* Stat Accumulator + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonFramework_StatAccumulator_H +#define PokemonAutomation_CommonFramework_StatAccumulator_H + +#include +#include +#include "Common/Cpp/Time.h" + +namespace PokemonAutomation{ + +class Logger; + + +class StatAccumulatorI32{ +public: + using StatObject = uint32_t; + +public: + void clear(); + void operator+=(uint32_t x); + + uint64_t count() const{ return m_count; }; + uint32_t min() const{ return m_min; } + uint32_t max() const{ return m_max; } + double mean() const; + double stddev() const; + + std::string dump(const char* units, double divider) const; + void log(Logger& logger, const std::string& label, const char* units, double divider) const; + +private: + uint64_t m_count = 0; + uint64_t m_sum = 0; + uint64_t m_sqr = 0; + uint32_t m_min = (uint32_t)-1; + uint32_t m_max = 0; +}; + +class PeriodicStatsReporterI32 : public StatAccumulatorI32{ +public: + PeriodicStatsReporterI32( + const char* label, + const char* units, double divider, + std::chrono::milliseconds period + ); + void report_data(Logger& logger, uint32_t x); + +private: + const char* m_label; + const char* m_units; + double m_divider; + std::chrono::milliseconds m_period; + WallClock m_last_report; +}; + + + +class FloatStatAccumulator{ +public: + using StatObject = double; + +public: + FloatStatAccumulator(); + + void operator+=(double x); + + uint64_t count() const{ return m_count; }; + double min() const{ return m_min; } + double max() const{ return m_max; } + double mean() const; + double stddev() const; + double diff_metric(double reference) const; + +private: + uint64_t m_count; + double m_sum; + double m_sqr; + double m_min; + double m_max; +}; + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Tools/VideoStream.cpp b/SerialPrograms/Source/CommonFramework/Tools/VideoStream.cpp index 8ec518cd97..2c3f395f7a 100644 --- a/SerialPrograms/Source/CommonFramework/Tools/VideoStream.cpp +++ b/SerialPrograms/Source/CommonFramework/Tools/VideoStream.cpp @@ -1,52 +1,52 @@ -/* Video Stream - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonFramework/Recording/StreamHistorySession.h" -#include "CommonTools/InferencePivots/VisualInferencePivot.h" -#include "CommonTools/InferencePivots/AudioInferencePivot.h" -#include "VideoStream.h" - -namespace PokemonAutomation{ - - - -VideoStream::VideoStream(VideoStream&& x) = default; -VideoStream::~VideoStream(){ - m_overlay.remove_stat(*m_audio_pivot); - m_overlay.remove_stat(*m_video_pivot); -} -VideoStream::VideoStream( - Logger& logger, - AudioFeed& audio, - VideoFeed& video, - const StreamHistorySession& history, - VideoOverlay& overlay -) - : m_logger(logger) - , m_audio(audio) - , m_video(video) - , m_history(history) - , m_overlay(overlay) -{} - - -bool VideoStream::save_stream_history(const std::string& filename){ - return history().save(filename); -} - - -void VideoStream::initialize_inference_threads(CancellableScope& scope, AsyncDispatcher& dispatcher){ - m_video_pivot.reset(scope, m_video, dispatcher); - m_audio_pivot.reset(scope, m_audio, dispatcher); - m_overlay.add_stat(*m_video_pivot); - m_overlay.add_stat(*m_audio_pivot); -} - - - -} +/* Video Stream + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonFramework/Recording/StreamHistorySession.h" +#include "CommonTools/InferencePivots/VisualInferencePivot.h" +#include "CommonTools/InferencePivots/AudioInferencePivot.h" +#include "VideoStream.h" + +namespace PokemonAutomation{ + + + +VideoStream::VideoStream(VideoStream&& x) = default; +VideoStream::~VideoStream(){ + m_overlay.remove_stat(*m_audio_pivot); + m_overlay.remove_stat(*m_video_pivot); +} +VideoStream::VideoStream( + Logger& logger, + AudioFeed& audio, + VideoFeed& video, + const StreamHistorySession& history, + VideoOverlay& overlay +) + : m_logger(logger) + , m_audio(audio) + , m_video(video) + , m_history(history) + , m_overlay(overlay) +{} + + +bool VideoStream::save_stream_history(const std::string& filename){ + return history().save(filename); +} + + +void VideoStream::initialize_inference_threads(CancellableScope& scope, AsyncDispatcher& dispatcher){ + m_video_pivot.reset(scope, m_video, dispatcher); + m_audio_pivot.reset(scope, m_audio, dispatcher); + m_overlay.add_stat(*m_video_pivot); + m_overlay.add_stat(*m_audio_pivot); +} + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Tools/VideoStream.h b/SerialPrograms/Source/CommonFramework/Tools/VideoStream.h index 4f599d649a..c180115378 100644 --- a/SerialPrograms/Source/CommonFramework/Tools/VideoStream.h +++ b/SerialPrograms/Source/CommonFramework/Tools/VideoStream.h @@ -1,95 +1,95 @@ -/* Video Stream - * - * From: https://github.com/PokemonAutomation/ - * - * Represents a single video stream. Includes video, audio, as well - * as their inference pivots. Also includes a logger and the video overlay. - * - * This is the class that should be passed into inference modules as it - * provides all the information needed for inference. - * - * This class has been separated from ConsoleHandle which used to take this - * role. But 95% of the uses don't require the controller. And the controller - * is messy due to being heterogeneous. - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoStream_H -#define PokemonAutomation_VideoPipeline_VideoStream_H - -#include -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Containers/Pimpl.h" - -namespace PokemonAutomation{ - -class CancellableScope; -class AsyncDispatcher; -class Logger; -class AudioFeed; -class VideoFeed; -class StreamHistorySession; -class VideoOverlay; -class VisualInferencePivot; -class AudioInferencePivot; - - -class VideoStream{ -public: - VideoStream(VideoStream&& x); - void operator=(VideoStream&& x) = delete; - VideoStream(const VideoStream& x) = delete; - void operator=(const VideoStream& x) = delete; - ~VideoStream(); - -public: - VideoStream( - Logger& logger, - AudioFeed& audio, - VideoFeed& video, - const StreamHistorySession& history, - VideoOverlay& overlay - ); - - // log(string-like msg, Color color = Color()) - // string-like can be const char* or std::string - template - void log(Args&&... args){ - m_logger.log(std::forward(args)...); - } - - Logger& logger(){ return m_logger; } - - AudioFeed& audio(){ return m_audio; } - VideoFeed& video(){ return m_video; } - - const StreamHistorySession& history() const{ return m_history; } - bool save_stream_history(const std::string& filename); - - VideoOverlay& overlay(){ return m_overlay; } - - VisualInferencePivot& video_inference_pivot(){ return *m_video_pivot; } - AudioInferencePivot& audio_inference_pivot(){ return *m_audio_pivot; } - - -public: - void initialize_inference_threads(CancellableScope& scope, AsyncDispatcher& dispatcher); - - -private: - Logger& m_logger; - - AudioFeed& m_audio; - VideoFeed& m_video; - const StreamHistorySession& m_history; - - VideoOverlay& m_overlay; - - Pimpl m_video_pivot; - Pimpl m_audio_pivot; -}; - - - -} -#endif +/* Video Stream + * + * From: https://github.com/PokemonAutomation/ + * + * Represents a single video stream. Includes video, audio, as well + * as their inference pivots. Also includes a logger and the video overlay. + * + * This is the class that should be passed into inference modules as it + * provides all the information needed for inference. + * + * This class has been separated from ConsoleHandle which used to take this + * role. But 95% of the uses don't require the controller. And the controller + * is messy due to being heterogeneous. + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoStream_H +#define PokemonAutomation_VideoPipeline_VideoStream_H + +#include +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Containers/Pimpl.h" + +namespace PokemonAutomation{ + +class CancellableScope; +class AsyncDispatcher; +class Logger; +class AudioFeed; +class VideoFeed; +class StreamHistorySession; +class VideoOverlay; +class VisualInferencePivot; +class AudioInferencePivot; + + +class VideoStream{ +public: + VideoStream(VideoStream&& x); + void operator=(VideoStream&& x) = delete; + VideoStream(const VideoStream& x) = delete; + void operator=(const VideoStream& x) = delete; + ~VideoStream(); + +public: + VideoStream( + Logger& logger, + AudioFeed& audio, + VideoFeed& video, + const StreamHistorySession& history, + VideoOverlay& overlay + ); + + // log(string-like msg, Color color = Color()) + // string-like can be const char* or std::string + template + void log(Args&&... args){ + m_logger.log(std::forward(args)...); + } + + Logger& logger(){ return m_logger; } + + AudioFeed& audio(){ return m_audio; } + VideoFeed& video(){ return m_video; } + + const StreamHistorySession& history() const{ return m_history; } + bool save_stream_history(const std::string& filename); + + VideoOverlay& overlay(){ return m_overlay; } + + VisualInferencePivot& video_inference_pivot(){ return *m_video_pivot; } + AudioInferencePivot& audio_inference_pivot(){ return *m_audio_pivot; } + + +public: + void initialize_inference_threads(CancellableScope& scope, AsyncDispatcher& dispatcher); + + +private: + Logger& m_logger; + + AudioFeed& m_audio; + VideoFeed& m_video; + const StreamHistorySession& m_history; + + VideoOverlay& m_overlay; + + Pimpl m_video_pivot; + Pimpl m_audio_pivot; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.5.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.5.cpp index 7a49e6d485..992a51daa9 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.5.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.5.cpp @@ -93,9 +93,7 @@ CameraVideoSource::CameraVideoSource( ) : VideoSource(true) , m_logger(logger) - , m_last_image_timestamp(WallClock::min()) - , m_stats_conversion("ConvertFrame", "ms", 1000, std::chrono::seconds(10)) - , m_last_frame_seqnum(0) + , m_snapshot_manager(logger, m_last_frame) { if (!info){ return; @@ -182,19 +180,8 @@ void CameraVideoSource::set_video_output(QGraphicsVideoItem& item){ // return immediately to unblock the main thread. WallClock now = current_time(); - { - WriteSpinLock lg(m_frame_lock); - - // Skip duplicate frames. - if (frame.startTime() != -1 && frame.startTime() <= m_last_frame.startTime()){ - return; - } - - m_last_frame = frame; - m_last_frame_timestamp = now; - uint64_t seqnum = m_last_frame_seqnum.load(std::memory_order_relaxed); - seqnum++; - m_last_frame_seqnum.store(seqnum, std::memory_order_relaxed); + if (!m_last_frame.push_frame(frame, now)){ + return; } report_source_frame(std::make_shared(now, frame)); }, @@ -206,55 +193,6 @@ void CameraVideoSource::set_video_output(QGraphicsVideoItem& item){ -VideoSnapshot CameraVideoSource::snapshot(){ - // This will be coming in from random threads. (not the main thread) - // So we efficiently grab the last frame to unblock the main thread. - // Then we can do any expensive post-processing as needed. - - std::lock_guard lg(m_cache_lock); - - // Check the cached image frame. If it's not stale, return it immediately. - uint64_t frame_seqnum = m_last_frame_seqnum.load(std::memory_order_relaxed); - if (!m_last_image.isNull() && m_last_image_seqnum == frame_seqnum){ - return VideoSnapshot(m_last_image, m_last_image_timestamp); - } - - // Cached image is stale. Grab the latest frame. - QVideoFrame frame; - WallClock frame_timestamp; - { - ReadSpinLock lg0(m_frame_lock); - frame_seqnum = m_last_frame_seqnum.load(std::memory_order_relaxed); - frame = m_last_frame; - frame_timestamp = m_last_frame_timestamp; - } - - if (!frame.isValid()){ - m_logger.log("QVideoFrame is null.", COLOR_RED); - return VideoSnapshot(); - } - - // Converting the QVideoFrame to QImage is expensive. Time it and - // report performance. - WallClock time0 = current_time(); - - QImage image = frame.toImage(); - QImage::Format format = image.format(); - if (format != QImage::Format_ARGB32 && format != QImage::Format_RGB32){ - image = image.convertToFormat(QImage::Format_ARGB32); - } - - WallClock time1 = current_time(); - const int64_t duration = std::chrono::duration_cast(time1 - time0).count(); - m_stats_conversion.report_data(m_logger, uint32_t(duration)); - - // Update the cached image. - m_last_image = std::move(image); - m_last_image_timestamp = frame_timestamp; - m_last_image_seqnum = frame_seqnum; - - return VideoSnapshot(m_last_image, m_last_image_timestamp); -} QWidget* CameraVideoSource::make_display_QtWidget(QWidget* parent){ return new CameraVideoDisplay(parent, *this); diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.5.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.5.h index 2df4180a0a..bb9071682a 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.5.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.5.h @@ -10,7 +10,7 @@ #include #if QT_VERSION_MAJOR == 6 -#include +//#include #include #include #include @@ -20,10 +20,11 @@ #include #include #include -#include "Common/Cpp/Concurrency/SpinLock.h" #include "CommonFramework/Tools/StatAccumulator.h" #include "CommonFramework/VideoPipeline/VideoSource.h" #include "CommonFramework/VideoPipeline/CameraInfo.h" +#include "QVideoFrameCache.h" +#include "SnapshotManager.h" #include "CameraImplementations.h" //#include @@ -87,6 +88,9 @@ class StaticQGraphicsView : public QGraphicsView{ }; + + + class CameraVideoSource : public QObject, public VideoSource{ public: virtual ~CameraVideoSource(); @@ -103,7 +107,12 @@ class CameraVideoSource : public QObject, public VideoSource{ return m_resolutions; } - virtual VideoSnapshot snapshot() override; + virtual VideoSnapshot snapshot_latest_blocking() override{ + return m_snapshot_manager.snapshot_latest_blocking(); + } + virtual VideoSnapshot snapshot_recent_nonblocking(WallClock min_time) override{ + return m_snapshot_manager.snapshot_recent_nonblocking(min_time); + } virtual QWidget* make_display_QtWidget(QWidget* parent) override; @@ -123,29 +132,10 @@ class CameraVideoSource : public QObject, public VideoSource{ std::vector m_resolutions; -private: - // Last Cached Image: All accesses must be under this lock. - - mutable std::mutex m_cache_lock; - - QImage m_last_image; - WallClock m_last_image_timestamp; - uint64_t m_last_image_seqnum = 0; - - PeriodicStatsReporterI32 m_stats_conversion; private: - // Last Frame: All accesses must be under this lock. - // These will be updated very rapidly by the main thread. - // Holding the frame lock will block the main thread. - // So accessors should minimize the time they hold the frame lock. - - mutable SpinLock m_frame_lock; - - QVideoFrame m_last_frame; - WallClock m_last_frame_timestamp; - std::atomic m_last_frame_seqnum; - + QVideoFrameCache m_last_frame; + SnapshotManager m_snapshot_manager; }; diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.cpp index 1bb3632df2..b275c2c17b 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.cpp @@ -86,9 +86,7 @@ CameraVideoSource::CameraVideoSource( ) : VideoSource(true) , m_logger(logger) - , m_last_image_timestamp(WallClock::min()) - , m_stats_conversion("ConvertFrame", "ms", 1000, std::chrono::seconds(10)) - , m_last_frame_seqnum(0) + , m_snapshot_manager(logger, m_last_frame) { if (!info){ return; @@ -160,14 +158,8 @@ CameraVideoSource::CameraVideoSource( // return immediately to unblock the main thread. WallClock now = current_time(); - { - WriteSpinLock lg(m_frame_lock); -// cout << now << endl; - m_last_frame = frame; - m_last_frame_timestamp = now; - uint64_t seqnum = m_last_frame_seqnum.load(std::memory_order_relaxed); - seqnum++; - m_last_frame_seqnum.store(seqnum, std::memory_order_relaxed); + if (!m_last_frame.push_frame(frame, now)){ + return; } report_source_frame(std::make_shared(now, frame)); } @@ -176,52 +168,6 @@ CameraVideoSource::CameraVideoSource( m_camera->start(); } -VideoSnapshot CameraVideoSource::snapshot(){ - // Prevent multiple concurrent screenshots from entering here. - std::lock_guard lg(m_snapshot_lock); - - if (m_camera == nullptr){ - return VideoSnapshot(); - } - - // Frame is already cached and is not stale. - QVideoFrame frame; - WallClock frame_timestamp; - uint64_t frame_seqnum; - { - SpinLockGuard lg0(m_frame_lock); - frame_seqnum = m_last_frame_seqnum; - if (!m_last_image.isNull() && m_last_image_seqnum == frame_seqnum){ - return VideoSnapshot(m_last_image, m_last_image_timestamp); - } - frame = m_last_frame; - frame_timestamp = m_last_frame_timestamp; - } - - if (!frame.isValid()){ - global_logger_tagged().log("QVideoFrame is null.", COLOR_RED); - return VideoSnapshot(); - } - - WallClock time0 = current_time(); - - QImage image = frame.toImage(); - QImage::Format format = image.format(); - if (format != QImage::Format_ARGB32 && format != QImage::Format_RGB32){ - image = image.convertToFormat(QImage::Format_ARGB32); - } - - // No lock needed here since this the only place that touches it. - m_last_image = std::move(image); - m_last_image_timestamp = frame_timestamp; - m_last_image_seqnum = frame_seqnum; - - WallClock time1 = current_time(); - const int64_t duration = std::chrono::duration_cast(time1 - time0).count(); - m_stats_conversion.report_data(m_logger, uint32_t(duration)); - - return VideoSnapshot(m_last_image, m_last_image_timestamp); -} QWidget* CameraVideoSource::make_display_QtWidget(QWidget* parent){ return new CameraVideoDisplay(parent, *this); diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.h index f48a6e3e12..cde88e30c8 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.h @@ -15,10 +15,11 @@ #include #include #include -#include "Common/Cpp/Concurrency/SpinLock.h" #include "CommonFramework/Tools/StatAccumulator.h" #include "CommonFramework/VideoPipeline/VideoSource.h" #include "CommonFramework/VideoPipeline/CameraInfo.h" +#include "QVideoFrameCache.h" +#include "SnapshotManager.h" #include "CameraImplementations.h" class QCamera; @@ -63,7 +64,12 @@ class CameraVideoSource : public QObject, public VideoSource{ return m_resolutions; } - virtual VideoSnapshot snapshot() override; + virtual VideoSnapshot snapshot_latest_blocking() override{ + return m_snapshot_manager.snapshot_latest_blocking(); + } + virtual VideoSnapshot snapshot_recent_nonblocking(WallClock min_time) override{ + return m_snapshot_manager.snapshot_recent_nonblocking(min_time); + } virtual QWidget* make_display_QtWidget(QWidget* parent) override; @@ -85,28 +91,10 @@ class CameraVideoSource : public QObject, public VideoSource{ std::vector m_resolutions; -private: - // Last Cached Image: All accesses must be under this lock. - - QImage m_last_image; - WallClock m_last_image_timestamp; - uint64_t m_last_image_seqnum = 0; - - PeriodicStatsReporterI32 m_stats_conversion; - private: - // Last Frame: All accesses must be under this lock. - // These will be updated very rapidly by the main thread. - // Holding the frame lock will block the main thread. - // So accessors should minimize the time they hold the frame lock. - - mutable SpinLock m_frame_lock; - - QVideoFrame m_last_frame; - WallClock m_last_frame_timestamp; - std::atomic m_last_frame_seqnum; - + QVideoFrameCache m_last_frame; + SnapshotManager m_snapshot_manager; }; diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/QVideoFrameCache.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/QVideoFrameCache.h new file mode 100644 index 0000000000..c167fc6bc9 --- /dev/null +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/QVideoFrameCache.h @@ -0,0 +1,70 @@ +/* QVideoFrameCache + * + * From: https://github.com/PokemonAutomation/ + * + * A simple cache that stores the last QVideoFrame from a stream. + * + */ + +#ifndef PokemonAutomation_VideoPipeline_QVideoFrameCache_H +#define PokemonAutomation_VideoPipeline_QVideoFrameCache_H + +#include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/Concurrency/SpinLock.h" + +namespace PokemonAutomation{ + + + +class QVideoFrameCache{ +public: + QVideoFrameCache() + : m_last_frame_timestamp(WallClock::min()) + , m_last_frame_seqnum(0) + {} + + uint64_t seqnum() const{ + return m_last_frame_seqnum.load(std::memory_order_relaxed); + } + uint64_t get_latest(QVideoFrame& frame, WallClock& timestamp) const{ + WriteSpinLock lg(m_frame_lock); + frame = m_last_frame; + timestamp = m_last_frame_timestamp; + return seqnum(); + } + + bool push_frame(QVideoFrame frame, WallClock timestamp){ + WriteSpinLock lg(m_frame_lock); + + // Skip duplicate frames. + if (frame.startTime() != -1 && frame.startTime() <= m_last_frame.startTime()){ + return false; + } + + m_last_frame = frame; + m_last_frame_timestamp = timestamp; + uint64_t seqnum = m_last_frame_seqnum.load(std::memory_order_relaxed); + seqnum++; + m_last_frame_seqnum.store(seqnum, std::memory_order_relaxed); + + return true; + } + + +private: + mutable SpinLock m_frame_lock; + + QVideoFrame m_last_frame; + WallClock m_last_frame_timestamp; + std::atomic m_last_frame_seqnum; +}; + + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/SnapshotManager.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/SnapshotManager.cpp new file mode 100644 index 0000000000..746c3404b8 --- /dev/null +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/SnapshotManager.cpp @@ -0,0 +1,268 @@ +/* Snapshot Manager + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Concurrency/ReverseLockGuard.h" +#include "Common/Cpp/Concurrency/AsyncTask.h" +#include "CommonFramework/Tools/GlobalThreadPools.h" +#include "SnapshotManager.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + + +SnapshotManager::~SnapshotManager(){ + std::unique_lock lg(m_lock); + m_cv.wait(lg, [this]{ return m_active_conversions == 0; }); +} +SnapshotManager::SnapshotManager(Logger& logger, QVideoFrameCache& cache) + : m_logger(logger) + , m_cache(cache) + , m_active_conversions(0) + , m_converting_seqnum(0) + , m_converted_seqnum(0) + , m_stats_conversion("ConvertFrame", "ms", 1000, std::chrono::seconds(10)) +{} + + +QImage SnapshotManager::frame_to_image(const QVideoFrame& frame){ + QImage image = frame.toImage(); + QImage::Format format = image.format(); + if (format != QImage::Format_ARGB32 && format != QImage::Format_RGB32){ + image = image.convertToFormat(QImage::Format_ARGB32); + } + return image; +} +void SnapshotManager::convert(uint64_t seqnum, QVideoFrame frame, WallClock timestamp) noexcept{ + VideoSnapshot snapshot; + snapshot.timestamp = timestamp; + try{ + WallClock time0 = current_time(); + snapshot.frame = std::make_shared(frame_to_image(frame)); + WallClock time1 = current_time(); + uint32_t microseconds = (uint32_t)std::chrono::duration_cast(time1 - time0).count(); + m_stats_conversion.report_data(m_logger, microseconds); + }catch (...){ + try{ + m_logger.log("Exception thrown while converting QVideoFrame -> QImage.", COLOR_RED); + }catch (...){} + } + + std::lock_guard lg(m_lock); +// cout << "SnapshotManager::convert() - post convert: " << seqnum << endl; + + if (m_converted_seqnum < seqnum){ + m_converted_seqnum = seqnum; + m_converted_snapshot = std::move(snapshot); + } + + m_active_conversions--; + + if (m_queued_convert){ + m_queued_convert = false; + seqnum = m_cache.get_latest(frame, timestamp); + if (m_converting_seqnum < seqnum){ + dispatch_conversion(seqnum, std::move(frame), timestamp); + } + } + + // Warning: The moment we release the lock with (m_active_conversions == 0), + // this class can be immediately destructed. + + // Therefore it is not safe to notify after releasing the lock. + m_cv.notify_all(); + + // Lock is implicitly released here. +} +bool SnapshotManager::try_dispatch_conversion(uint64_t seqnum, QVideoFrame frame, WallClock timestamp) noexcept{ + // Must call under the lock. + + std::unique_ptr* task; + try{ + task = &m_pending_conversions[seqnum]; + + // This frame is already being converted. + if (*task){ + return false; + } + }catch (...){ + return false; + } + + try{ + std::function lambda = [=, this, frame = std::move(frame)](){ + convert(seqnum, std::move(frame), timestamp); + }; + + *task = GlobalThreadPools::realtime_inference().try_dispatch(lambda); + + // Dispatch was successful. We're done. + if (*task){ + return true; + } + + // Dispatch failed. Queue it for later. + m_queued_convert = true; + }catch (...){} + + m_pending_conversions.erase(seqnum); + + return false; +} +void SnapshotManager::dispatch_conversion(uint64_t seqnum, QVideoFrame frame, WallClock timestamp) noexcept{ + // Must call under the lock. + m_active_conversions++; + + if (!try_dispatch_conversion(seqnum, std::move(frame), timestamp)){ + m_active_conversions--; + } + + // Cleanup finished tasks. + while (!m_pending_conversions.empty()){ + auto iter = m_pending_conversions.begin(); + if (iter->second->is_finished()){ + m_pending_conversions.erase(iter); + }else{ + break; + } + } +} + + + +VideoSnapshot SnapshotManager::snapshot_latest_blocking(){ + std::unique_lock lg(m_lock); + +// cout << "snapshot_latest_blocking()" << endl; + + // Already up-to-date. Return it. + uint64_t seqnum = m_cache.seqnum(); + if (seqnum <= m_converted_seqnum){ +// cout << "snapshot_latest_blocking(): Cached" << endl; + return m_converted_snapshot; + } + + // Check if we're already converting it. + if (m_converting_seqnum >= seqnum){ +// cout << "snapshot_latest_blocking(): Already Converting" << endl; + m_cv.wait(lg, [=, this]{ return m_converted_seqnum >= seqnum; }); +// cout << "snapshot_latest_blocking(): Already Converting - Done" << endl; + return m_converted_snapshot; + } + + + // Otherwise, we use this thread to convert the latest frame. +// cout << "snapshot_latest_blocking(): Convert Now" << endl; + + QVideoFrame frame; + WallClock timestamp; + seqnum = m_cache.get_latest(frame, timestamp); + +// m_active_conversions++; + m_converting_seqnum = seqnum; + + VideoSnapshot snapshot; + try{ + uint32_t microseconds; + { + ReverseLockGuard lg0(m_lock); + WallClock time0 = current_time(); + snapshot = VideoSnapshot(frame_to_image(frame), timestamp); + WallClock time1 = current_time(); + microseconds = (uint32_t)std::chrono::duration_cast(time1 - time0).count(); + } + m_stats_conversion.report_data(m_logger, microseconds); +// m_active_conversions--; + }catch (...){ +// m_active_conversions--; + m_logger.log("Exception thrown while converting QVideoFrame -> QImage.", COLOR_RED); + throw; + } + + m_converted_seqnum = seqnum; + + if (timestamp > m_converted_snapshot.timestamp){ + m_converted_snapshot = std::move(snapshot); + m_cv.notify_all(); + } + +// cout << "snapshot_latest_blocking(): Convert Now - Done" << endl; + return m_converted_snapshot; +} + +VideoSnapshot SnapshotManager::snapshot_recent_nonblocking(WallClock min_time){ +// WallClock now = current_time(); + + std::lock_guard lg(m_lock); + +// cout << "snapshot_recent_nonblocking()" << endl; + + // Already up-to-date. Return it. + uint64_t seqnum = m_cache.seqnum(); + if (seqnum <= m_converted_seqnum){ +// cout << "snapshot_recent_nonblocking(): Up-to-date" << endl; + return m_converted_snapshot; + } + + QVideoFrame frame; + WallClock timestamp; + seqnum = m_cache.get_latest(frame, timestamp); + + // Dispatch this frame for conversion. + if (m_converting_seqnum < seqnum){ +// cout << "snapshot_recent_nonblocking(): Dispatching..." << endl; + dispatch_conversion(seqnum, std::move(frame), timestamp); + } + + // Cached snapshot isn't too old. Return it. + + if (min_time <= m_converted_snapshot.timestamp){ +// cout << "snapshot_recent_nonblocking(): Good..." << endl; + return m_converted_snapshot; + }else{ +// cout << "snapshot_recent_nonblocking(): Too old..." << endl; + return VideoSnapshot(); + } + +#if 0 + std::chrono::microseconds window(m_stats_conversion.max()); +// cout << "window = " << window.count() << endl; + + WallClock oldest_allowed = now - 2 * window; +// cout << "snapshot_recent_nonblocking(): " << m_converted_seqnum << endl; + + if (m_converted_snapshot.timestamp >= oldest_allowed){ +// cout << "snapshot_recent_nonblocking(): Good..." << endl; + return m_converted_snapshot; + } + +// cout << "snapshot_recent_nonblocking(): Too old..." << endl; + return VideoSnapshot(); +#endif +} + + + + + + + + + + + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/SnapshotManager.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/SnapshotManager.h new file mode 100644 index 0000000000..6b541a23d9 --- /dev/null +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/SnapshotManager.h @@ -0,0 +1,60 @@ +/* Snapshot Manager + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_SnapshotManager_H +#define PokemonAutomation_VideoPipeline_SnapshotManager_H + +#include +#include +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/Tools/StatAccumulator.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "QVideoFrameCache.h" + +namespace PokemonAutomation{ + +class AsyncTask; + +class SnapshotManager{ +public: + ~SnapshotManager(); + SnapshotManager(Logger& logger, QVideoFrameCache& cache); + +public: + VideoSnapshot snapshot_latest_blocking(); + VideoSnapshot snapshot_recent_nonblocking(WallClock min_time); + +private: + static QImage frame_to_image(const QVideoFrame& frame); + void convert(uint64_t seqnum, QVideoFrame frame, WallClock timestamp) noexcept; + bool try_dispatch_conversion(uint64_t seqnum, QVideoFrame frame, WallClock timestamp) noexcept; + void dispatch_conversion(uint64_t seqnum, QVideoFrame frame, WallClock timestamp) noexcept; + +private: + Logger& m_logger; + QVideoFrameCache& m_cache; + + std::mutex m_lock; + std::condition_variable m_cv; + + size_t m_active_conversions; + std::map> m_pending_conversions; + bool m_queued_convert = false; + + uint64_t m_converting_seqnum; + + uint64_t m_converted_seqnum; + VideoSnapshot m_converted_snapshot; + + PeriodicStatsReporterI32 m_stats_conversion; +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/VideoFrameQt.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/VideoFrameQt.h index 4f798c0b6c..f9bb51d896 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/VideoFrameQt.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/VideoFrameQt.h @@ -1,44 +1,44 @@ -/* Video Frame - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoFrame_H -#define PokemonAutomation_VideoFrame_H - -#include -#include "Common/Cpp/Time.h" - -namespace PokemonAutomation{ - - -class VideoFrame{ -public: - WallClock timestamp; - QVideoFrame frame; - - VideoFrame(VideoFrame&&) = default; - VideoFrame& operator=(VideoFrame&&) = default; - VideoFrame(const VideoFrame&) = delete; - void operator=(const VideoFrame&) = delete; - - VideoFrame() - : timestamp(WallClock::min()) - {} - VideoFrame(WallClock p_timestamp, QVideoFrame p_frame) - : timestamp(p_timestamp) - , frame(std::move(p_frame)) - {} - - void clear(){ - frame = QVideoFrame(); - } - bool is_valid() const{ - return frame.isValid(); - } -}; - - -} -#endif +/* Video Frame + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoFrame_H +#define PokemonAutomation_VideoFrame_H + +#include +#include "Common/Cpp/Time.h" + +namespace PokemonAutomation{ + + +class VideoFrame{ +public: + WallClock timestamp; + QVideoFrame frame; + + VideoFrame(VideoFrame&&) = default; + VideoFrame& operator=(VideoFrame&&) = default; + VideoFrame(const VideoFrame&) = delete; + void operator=(const VideoFrame&) = delete; + + VideoFrame() + : timestamp(WallClock::min()) + {} + VideoFrame(WallClock p_timestamp, QVideoFrame p_frame) + : timestamp(p_timestamp) + , frame(std::move(p_frame)) + {} + + void clear(){ + frame = QVideoFrame(); + } + bool is_valid() const{ + return frame.isValid(); + } +}; + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Stats/CpuUtilizationStats.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/Stats/CpuUtilizationStats.h index 6f564ef27c..33ffc50838 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/Stats/CpuUtilizationStats.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Stats/CpuUtilizationStats.h @@ -7,9 +7,10 @@ #ifndef PokemonAutomation_CpuUtilizationStats_H #define PokemonAutomation_CpuUtilizationStats_H +#include #include "Common/Cpp/Time.h" #include "Common/Cpp/EventRateTracker.h" -#include "CommonFramework/Environment/Environment.h" +#include "Common/Cpp/CpuUtilization/CpuUtilization.h" #include "CommonFramework/VideoPipeline/VideoOverlayTypes.h" //#include @@ -51,7 +52,7 @@ inline OverlayStatSnapshot CpuUtilizationStat::get_current(){ if (m_last_clock.is_valid()){ auto duration = current - m_last_clock; duration /= vcores; - m_tracker.push_event(std::chrono::duration_cast(duration), now); + m_tracker.push_event(std::chrono::duration_cast(duration), now); } m_last_clock = current; diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.cpp index 13bf961aa1..7f500b6a53 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.cpp @@ -4,7 +4,8 @@ * */ -#include "Common/Cpp/PrettyPrint.h" +//#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Concurrency/ComputationThreadPool.h" #include "ThreadUtilizationStats.h" //#include @@ -24,12 +25,12 @@ OverlayStatSnapshot ThreadUtilizationStat::get_current(){ std::lock_guard lg(m_lock); WallClock now = current_time(); - WallClock::duration clock = thread_cpu_time(m_handle); - if (clock == WallClock::duration::min()){ + WallDuration clock = thread_cpu_time(m_handle); + if (clock == WallDuration::min()){ return OverlayStatSnapshot{m_label + " ---"}; } - if (m_last_clock != WallClock::duration::min()){ + if (m_last_clock != WallDuration::min()){ m_tracker.push_event(clock - m_last_clock, now); } m_last_clock = clock; @@ -39,4 +40,36 @@ OverlayStatSnapshot ThreadUtilizationStat::get_current(){ + +ThreadPoolUtilizationStat::ThreadPoolUtilizationStat(const ComputationThreadPool& thread_pool, std::string label) + : m_thread_pool(thread_pool) + , m_label(std::move(label)) + , m_last_clock(thread_pool.cpu_time()) + , m_printer((double)thread_pool.max_threads()) +{} + +OverlayStatSnapshot ThreadPoolUtilizationStat::get_current(){ + std::lock_guard lg(m_lock); + + WallClock now = current_time(); + WallDuration clock = m_thread_pool.cpu_time(); + if (clock <= WallDuration::zero()){ + return OverlayStatSnapshot(); + } + + if (m_last_clock != WallDuration::min()){ + m_tracker.push_event(clock - m_last_clock, now); + } + m_last_clock = clock; + + return m_printer.get_snapshot( + m_label + " (x" + std::to_string(m_thread_pool.current_threads()) + "):", + m_tracker.utilization() + ); +} + + + + + } diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.h index 417f63b20d..5a826ca7b2 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.h @@ -7,14 +7,19 @@ #ifndef PokemonAutomation_ThreadUtilizationStats_H #define PokemonAutomation_ThreadUtilizationStats_H +#include #include "Common/Cpp/Time.h" #include "Common/Cpp/EventRateTracker.h" -#include "CommonFramework/Environment/Environment.h" +#include "Common/Cpp/CpuUtilization/CpuUtilization.h" #include "CommonFramework/VideoPipeline/VideoOverlayTypes.h" namespace PokemonAutomation{ +class ComputationThreadPool; + + + class ThreadUtilizationStat : public OverlayStat{ public: ThreadUtilizationStat(ThreadHandle handle, std::string label); @@ -26,7 +31,25 @@ class ThreadUtilizationStat : public OverlayStat{ std::string m_label; std::mutex m_lock; - WallClock::duration m_last_clock; + WallDuration m_last_clock; + UtilizationTracker m_tracker; + + OverlayStatUtilizationPrinter m_printer; +}; + + +class ThreadPoolUtilizationStat : public OverlayStat{ +public: + ThreadPoolUtilizationStat(const ComputationThreadPool& thread_pool, std::string label); + + virtual OverlayStatSnapshot get_current() override; + +private: + const ComputationThreadPool& m_thread_pool; + std::string m_label; + + std::mutex m_lock; + WallDuration m_last_clock; UtilizationTracker m_tracker; OverlayStatUtilizationPrinter m_printer; @@ -34,5 +57,6 @@ class ThreadUtilizationStat : public OverlayStat{ + } #endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoDisplayWidget.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoDisplayWidget.h index f64a16efba..fa6c3a0c82 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoDisplayWidget.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoDisplayWidget.h @@ -1,7 +1,17 @@ -/* Video Display +/* Video Display Widget * * From: https://github.com/PokemonAutomation/ * + * VideoDisplayWidget renders a window for video stream from a Switch console or + * other sources. Stream control UI is not part of this class. + * + * The actual QWidget that displays the video content is not created by this class. + * But rather, this class receives the content widget from + * VideoSession.current_source()->make_display_QtWidget(). + * + * VideoDisplayWidget is repsonsible for handling aspect ratio and passing key events + * around. It also uses VideoDisplayWindow to pop up the stream view into a standalone + * QMainWindow. */ #ifndef PokemonAutomation_VideoPipeline_VideoDisplayWidget_H @@ -19,8 +29,8 @@ namespace PokemonAutomation{ class VideoDisplayWindow; -// Interface for forwarding keyboard commands from the VideoDisplayWidget to -// whatever thing under it handles it. +// Interface for forwarding keyboard and focus events from the VideoDisplayWidget to +// whatever thing inheriting CommandReceiver. struct CommandReceiver{ virtual void key_press(QKeyEvent* event) = 0; virtual void key_release(QKeyEvent* event) = 0; @@ -35,6 +45,7 @@ struct CommandReceiver{ class VideoDisplayWidget; +// Render the FPS of the incoming video stream as a text overlay on the video window class VideoSourceFPS : public OverlayStat{ public: VideoSourceFPS(VideoDisplayWidget& parent) @@ -46,6 +57,7 @@ class VideoSourceFPS : public OverlayStat{ VideoDisplayWidget& m_parent; }; +// Render the FPS of the rendering thread of the video window as a text overlay on the window class VideoDisplayFPS : public OverlayStat{ public: VideoDisplayFPS(VideoDisplayWidget& parent) @@ -59,12 +71,17 @@ class VideoDisplayFPS : public OverlayStat{ -// The widget that owns the video window. -// It consists of a VideoWidget that loads the video content from Switch and a -// VideoOverlayWidget that renders inference boxes and other visualizations on -// top of the video content. +// The widget that owns the video stream window. +// It consists of a VideoWidget that loads the video content from Switch or other sources +// and a VideoOverlayWidget that renders text overlays, inference boxes and other visualizations +// on top of the video content. class VideoDisplayWidget : public WidgetStackFixedAspectRatio, private VideoSession::StateListener{ public: + // holder: parent's layout that holds this VideoDisplayWidget + // id: the ID to differentiate multiple video views. For multi-Switch automation programs, this id + // is the console ID. + // command_receiver: whenever there is a keyboard or focus event, forward the event to this + // command_receiver object. VideoDisplayWidget( QWidget& parent, QLayout& holder, size_t id, diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoDisplayWindow.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoDisplayWindow.cpp index 2ac269a2cd..81d9fe3075 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoDisplayWindow.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoDisplayWindow.cpp @@ -22,19 +22,20 @@ namespace PokemonAutomation{ VideoDisplayWindow::VideoDisplayWindow(VideoDisplayWidget* display_widget) : m_display_widget(display_widget) { -// m_display_widget->setParent(this); setWindowTitle("Console: " + QString::number(m_display_widget->id())); this->setWindowIcon(QIcon(QString::fromStdString(RESOURCE_PATH() + "icon.png"))); -// this->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); + // Sets m_display_widget to be the VideoDisplayWindow's central widget. + // VideoDisplayWindow now takes ownership of m_display_widget as a QWidget this->setCentralWidget(m_display_widget); -// m_display_widget->setAlignment(Qt::AlignCenter); - -// cout << "Display Widget: " << m_display_widget->width() << " x " << m_display_widget->height() << endl; + + // this->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); + // m_display_widget->setAlignment(Qt::AlignCenter); + // cout << "Display Widget: " << m_display_widget->width() << " x " << m_display_widget->height() << endl; m_normal_size = m_display_widget->size(); this->resize(m_normal_size); -// cout << this->width() << " x " << this->height() << endl; + // cout << this->width() << " x " << this->height() << endl; this->show(); this->raise(); // bring the window to front on macOS diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoOverlayWidget.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoOverlayWidget.cpp index 4ca829ff08..45df772ca1 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoOverlayWidget.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoOverlayWidget.cpp @@ -281,15 +281,15 @@ void VideoOverlayWidget::render_log(QPainter& painter){ } } void VideoOverlayWidget::render_stats(QPainter& painter){ - const double TEXT_SIZE = 0.02; - const double ROW_HEIGHT = 0.03; + const double TEXT_SIZE = 0.018; + const double ROW_HEIGHT = 0.025; QColor box_color(10, 10, 10, 200); painter.setPen(box_color); int width = this->width(); int height = this->height(); - int start_x = (int)(width * 0.75); + int start_x = (int)(width * 0.78); std::vector lines; for (const auto& stat : *m_stats){ diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoSourceSelectorWidget.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoSourceSelectorWidget.cpp index 28e924ace6..c4370d9246 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoSourceSelectorWidget.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoSourceSelectorWidget.cpp @@ -1,164 +1,169 @@ -/* Video Source Selector Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "Common/Qt/NoWheelComboBox.h" -#include "CommonFramework/VideoPipeline/Backends/CameraImplementations.h" -#include "VideoSourceSelectorWidget.h" - -#include "CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.h" -#include "CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -VideoSourceSelectorWidget::~VideoSourceSelectorWidget(){ - m_session.remove_state_listener(*this); -} -VideoSourceSelectorWidget::VideoSourceSelectorWidget(Logger& logger, VideoSession& session) - : m_logger(logger) - , m_session(session) -{ - QHBoxLayout* camera_row = new QHBoxLayout(this); - camera_row->setContentsMargins(0, 0, 0, 0); - - camera_row->addWidget(new QLabel("Video Input:", this), 1); - camera_row->addSpacing(5); - - m_sources_box = new NoWheelComboBox(this); - m_sources_box->setMaxVisibleItems(20); - camera_row->addWidget(m_sources_box, 5); - camera_row->addSpacing(5); - - m_resolution_box = new NoWheelComboBox(this); - m_resolution_box->setMaxVisibleItems(20); - camera_row->addWidget(m_resolution_box, 3); - camera_row->addSpacing(5); - - m_reset_button = new QPushButton("Reset Video", this); - camera_row->addWidget(m_reset_button, 1); - - update_source_list(); - update_resolution_list(); - - connect( - m_sources_box, static_cast(&QComboBox::activated), - this, [this](int index){ - if (0 <= index && index < (int)m_sources.size()){ - m_sources[index]->run_post_select(); - m_session.set_source(m_sources[index]); - }else{ - m_session.set_source(std::make_unique()); - } - } - ); - connect( - m_resolution_box, static_cast(&QComboBox::activated), - this, [this](int index){ - if (index < 0 || index >= (int)m_resolutions.size()){ - return; - } - Resolution resolution = m_resolutions[index]; - m_session.set_resolution(resolution); - } - ); - connect( - m_reset_button, &QPushButton::clicked, - this, [this](bool){ - update_source_list(); - m_session.reset(); - } - ); - - m_session.add_state_listener(*this); -} - - - - -void VideoSourceSelectorWidget::update_source_list(){ - m_sources_box->clear(); - m_sources.clear(); - - std::shared_ptr current_descriptor = m_session.descriptor(); - - // Add all the static options. - { - VideoSourceOption option; - m_session.get(option); - m_sources.emplace_back(option.get_descriptor_from_cache(VideoSourceType::None)); - m_sources.emplace_back(option.get_descriptor_from_cache(VideoSourceType::StillImage)); - } - - // Now add all the cameras. - for (const CameraInfo& info : get_all_cameras()){ - m_sources.emplace_back(std::make_unique(info)); - } - - int index = -1; - for (int c = 0; c < (int)m_sources.size(); c++){ - const VideoSourceDescriptor& descriptor = *m_sources[c]; - m_sources_box->addItem(QString::fromStdString(descriptor.display_name())); - if (*current_descriptor == descriptor){ - index = c; - } - } - if (index >= 0){ - m_sources_box->setCurrentIndex((int)index); - }else{ - m_logger.log("Unable to find entry for this source.", COLOR_RED); - } -} -void VideoSourceSelectorWidget::update_resolution_list(){ - m_resolution_box->clear(); - - Resolution camera_resolution = m_session.current_resolution(); - m_resolutions = m_session.supported_resolutions(); - - int index = -1; - for (int c = 0; c < (int)m_resolutions.size(); c++){ - const Resolution& size = m_resolutions[c]; - m_resolution_box->addItem( - QString::fromStdString( - std::to_string(size.width) + " x " + - std::to_string(size.height) + " " + - aspect_ratio_as_string(size) - ) - ); - if (size == camera_resolution){ - index = c; - } - } - if (index >= 0){ - m_resolution_box->setCurrentIndex(index); - }else{ - m_logger.log("Unable to find entry for this resolution.", COLOR_RED); - } -} - - - - -void VideoSourceSelectorWidget::post_startup(VideoSource* source){ - update_source_list(); - update_resolution_list(); -} - - - - - - - - -} +/* Video Source Selector Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Qt/NoWheelComboBox.h" +#include "CommonFramework/VideoPipeline/Backends/CameraImplementations.h" +#include "VideoSourceSelectorWidget.h" + +#include "CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.h" +#include "CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +VideoSourceSelectorWidget::~VideoSourceSelectorWidget(){ + m_session.remove_state_listener(*this); +} +VideoSourceSelectorWidget::VideoSourceSelectorWidget(Logger& logger, VideoSession& session) + : m_logger(logger) + , m_session(session) +{ + QHBoxLayout* camera_row = new QHBoxLayout(this); + camera_row->setContentsMargins(0, 0, 0, 0); + + camera_row->addWidget(new QLabel("Video Input:", this), 1); + camera_row->addSpacing(5); + + m_sources_box = new NoWheelComboBox(this); + m_sources_box->setMaxVisibleItems(20); + camera_row->addWidget(m_sources_box, 5); + camera_row->addSpacing(5); + + m_resolution_box = new NoWheelComboBox(this); + m_resolution_box->setMaxVisibleItems(20); + camera_row->addWidget(m_resolution_box, 3); + camera_row->addSpacing(5); + + m_reset_button = new QPushButton("Reset Video", this); + camera_row->addWidget(m_reset_button, 1); + + update_source_list(); + update_resolution_list(); + + // Set the action for the video source selection box + connect( + m_sources_box, static_cast(&QComboBox::activated), + this, [this](int index){ + if (0 <= index && index < (int)m_sources.size()){ + m_sources[index]->run_post_select(); + m_session.set_source(m_sources[index]); + }else{ + m_session.set_source(std::make_unique()); + } + } + ); + + // Set the action for the video resolution selection box + connect( + m_resolution_box, static_cast(&QComboBox::activated), + this, [this](int index){ + if (index < 0 || index >= (int)m_resolutions.size()){ + return; + } + Resolution resolution = m_resolutions[index]; + m_session.set_resolution(resolution); + } + ); + + // Set the action for the video reset button + connect( + m_reset_button, &QPushButton::clicked, + this, [this](bool){ + update_source_list(); + m_session.reset(); + } + ); + + m_session.add_state_listener(*this); +} + + + + +void VideoSourceSelectorWidget::update_source_list(){ + m_sources_box->clear(); + m_sources.clear(); + + std::shared_ptr current_descriptor = m_session.descriptor(); + + // Add all the static options. + { + VideoSourceOption option; + m_session.get(option); + m_sources.emplace_back(option.get_descriptor_from_cache(VideoSourceType::None)); + m_sources.emplace_back(option.get_descriptor_from_cache(VideoSourceType::StillImage)); + } + + // Now add all the cameras. + for (const CameraInfo& info : get_all_cameras()){ + m_sources.emplace_back(std::make_unique(info)); + } + + int index = -1; + for (int c = 0; c < (int)m_sources.size(); c++){ + const VideoSourceDescriptor& descriptor = *m_sources[c]; + m_sources_box->addItem(QString::fromStdString(descriptor.display_name())); + if (*current_descriptor == descriptor){ + index = c; + } + } + if (index >= 0){ + m_sources_box->setCurrentIndex((int)index); + }else{ + m_logger.log("Unable to find entry for this source.", COLOR_RED); + } +} +void VideoSourceSelectorWidget::update_resolution_list(){ + m_resolution_box->clear(); + + Resolution camera_resolution = m_session.current_resolution(); + m_resolutions = m_session.supported_resolutions(); + + int index = -1; + for (int c = 0; c < (int)m_resolutions.size(); c++){ + const Resolution& size = m_resolutions[c]; + m_resolution_box->addItem( + QString::fromStdString( + std::to_string(size.width) + " x " + + std::to_string(size.height) + " " + + aspect_ratio_as_string(size) + ) + ); + if (size == camera_resolution){ + index = c; + } + } + if (index >= 0){ + m_resolution_box->setCurrentIndex(index); + }else{ + m_logger.log("Unable to find entry for this resolution.", COLOR_RED); + } +} + + + + +void VideoSourceSelectorWidget::post_startup(VideoSource* source){ + update_source_list(); + update_resolution_list(); +} + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoSourceSelectorWidget.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoSourceSelectorWidget.h index 74c79c4a3e..193f5c672c 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoSourceSelectorWidget.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoSourceSelectorWidget.h @@ -1,50 +1,59 @@ -/* Video Source Selector Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoSourceSelectorWidget_H -#define PokemonAutomation_VideoPipeline_VideoSourceSelectorWidget_H - -#include -#include -#include "CommonFramework/VideoPipeline/VideoSession.h" - -class QComboBox; -class QPushButton; - -namespace PokemonAutomation{ - - - -class VideoSourceSelectorWidget : public QWidget, public VideoSession::StateListener{ -public: - ~VideoSourceSelectorWidget(); - VideoSourceSelectorWidget(Logger& logger, VideoSession& session); - - -private: - void update_source_list(); - void update_resolution_list(); - - virtual void post_startup(VideoSource* source) override; - - -private: - Logger& m_logger; - VideoSession& m_session; - - QComboBox* m_sources_box; - QComboBox* m_resolution_box; - QPushButton* m_reset_button; - - std::vector> m_sources; - std::vector m_resolutions; - -}; - - - -} -#endif +/* Video Source Selector Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoSourceSelectorWidget_H +#define PokemonAutomation_VideoPipeline_VideoSourceSelectorWidget_H + +#include +#include +#include "CommonFramework/VideoPipeline/VideoSession.h" + +class QComboBox; +class QPushButton; + +namespace PokemonAutomation{ + + +// UI to select what video source to use for an Switch automation program +// This class inherits VideoSession::StateListener so it has callbacks for state change +// in the video session. +class VideoSourceSelectorWidget : public QWidget, public VideoSession::StateListener{ +public: + ~VideoSourceSelectorWidget(); + VideoSourceSelectorWidget(Logger& logger, VideoSession& session); + + +private: + // Query the OS to get all the possible video sources and update the UI to show them. + void update_source_list(); + // Load all possible video resolutions from the current video source. + void update_resolution_list(); + + // Overwrites VideoSession::StateListener::post_startup(). + // This function is called after setting a new video source or resetting the + // existing video source. + // This also includes after the video resolution is changed as we need to rebuild the video + // source with the new resolution. + virtual void post_startup(VideoSource* source) override; + + +private: + Logger& m_logger; + VideoSession& m_session; + + QComboBox* m_sources_box; + QComboBox* m_resolution_box; + QPushButton* m_reset_button; + + std::vector> m_sources; + std::vector m_resolutions; + +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoFeed.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoFeed.h index fc20b9c8dc..9770fd1efd 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoFeed.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoFeed.h @@ -64,12 +64,48 @@ class VideoFeed{ // Reset the video. Note that this may return early. virtual void reset() = 0; - // Do not call this on the main thread or it may deadlock. - virtual VideoSnapshot snapshot() = 0; - // Returns the currently measured frames/second for the video source + display. +public: + // + // Returns a snapshot of the latest available frame. + // + // If the latest frame is not yet ready (not converted to ImageRGB32), + // this function will block until it is ready. + // + // If this returns a null snapshot, it means the video isn't available. + // + // Implementations must be able to handle calls to this at high rate from + // many different threads simultaneously. So it should perform caching. + // + VideoSnapshot snapshot(){ + return snapshot_latest_blocking(); + } + virtual VideoSnapshot snapshot_latest_blocking() = 0; + + // + // This is a non-blocking snapshot function. It will never block, but it + // is not guaranteed to return the absolute latest snapshot. + // + // If this returns a null snapshot, it can mean either that the video + // isn't available or that no snapshot (>= min_time) is ready. + // + // Implementations must be able to handle calls to this at high rate from + // many different threads simultaneously. So it should perform caching. + // + // This function is intended to be called many times in a series. So calls + // will be taken as a hint for future calls. Thus the first call to this + // function will begin prefetch conversions of frames so they are ready + // on future calls. + // + virtual VideoSnapshot snapshot_recent_nonblocking(WallClock min_time) = 0; + + +public: + // Returns the currently measured frames/second for the video source. // Use this for diagnostic purposes. virtual double fps_source() const = 0; + // Returns the currently measured frames/second for the video display thread. + // Use this for diagnostic purposes. virtual double fps_display() const = 0; }; diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlay.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlay.cpp index 3f64ddfe28..73adafd9f2 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlay.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlay.cpp @@ -1,47 +1,47 @@ -/* Video Overlay - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/ListenerSet.h" -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "VideoOverlay.h" - -namespace PokemonAutomation{ - - - -struct VideoOverlay::Data{ - ListenerSet m_listeners; -}; - - -VideoOverlay::VideoOverlay() - : m_data(CONSTRUCT_TOKEN) -{} -VideoOverlay::~VideoOverlay() = default; - - - -void VideoOverlay::add_listener(MouseListener& listener){ - m_data->m_listeners.add(listener); -} -void VideoOverlay::remove_listener(MouseListener& listener){ - m_data->m_listeners.remove(listener); -} -void VideoOverlay::issue_mouse_press(double x, double y){ - m_data->m_listeners.run_method_unique(&MouseListener::on_mouse_press, x, y); -} -void VideoOverlay::issue_mouse_release(double x, double y){ - m_data->m_listeners.run_method_unique(&MouseListener::on_mouse_release, x, y); -} -void VideoOverlay::issue_mouse_move(double x, double y){ - m_data->m_listeners.run_method_unique(&MouseListener::on_mouse_move, x, y); -} - - - - - -} +/* Video Overlay + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/ListenerSet.h" +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "VideoOverlay.h" + +namespace PokemonAutomation{ + + + +struct VideoOverlay::Data{ + ListenerSet m_listeners; +}; + + +VideoOverlay::VideoOverlay() + : m_data(CONSTRUCT_TOKEN) +{} +VideoOverlay::~VideoOverlay() = default; + + + +void VideoOverlay::add_listener(MouseListener& listener){ + m_data->m_listeners.add(listener); +} +void VideoOverlay::remove_listener(MouseListener& listener){ + m_data->m_listeners.remove(listener); +} +void VideoOverlay::issue_mouse_press(double x, double y){ + m_data->m_listeners.run_method_unique(&MouseListener::on_mouse_press, x, y); +} +void VideoOverlay::issue_mouse_release(double x, double y){ + m_data->m_listeners.run_method_unique(&MouseListener::on_mouse_release, x, y); +} +void VideoOverlay::issue_mouse_move(double x, double y){ + m_data->m_listeners.run_method_unique(&MouseListener::on_mouse_move, x, y); +} + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayTypes.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayTypes.cpp index d7fd15743b..94efba1d53 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayTypes.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayTypes.cpp @@ -38,8 +38,9 @@ void OverlayStat::set_text(std::string text, Color color){ #endif -OverlayStatUtilizationPrinter::OverlayStatUtilizationPrinter() - : m_last_active(WallClock::min()) +OverlayStatUtilizationPrinter::OverlayStatUtilizationPrinter(double max_utilization) + : m_max_utilization(max_utilization) + , m_last_active(WallClock::min()) {} OverlayStatSnapshot OverlayStatUtilizationPrinter::get_snapshot(const std::string& label, double utilization){ WallClock now = current_time(); @@ -56,11 +57,11 @@ OverlayStatSnapshot OverlayStatUtilizationPrinter::get_snapshot(const std::strin } Color color = COLOR_WHITE; - if (utilization > 0.90){ + if (utilization > 0.90 * m_max_utilization){ color = COLOR_RED; - }else if (utilization > 0.80){ + }else if (utilization > 0.80 * m_max_utilization){ color = COLOR_ORANGE; - }else if (utilization > 0.50){ + }else if (utilization > 0.50 * m_max_utilization){ color = COLOR_YELLOW; } return OverlayStatSnapshot{ diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayTypes.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayTypes.h index b3f36ac029..fe972636dc 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayTypes.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayTypes.h @@ -126,10 +126,11 @@ class OverlayStat{ class OverlayStatUtilizationPrinter{ public: - OverlayStatUtilizationPrinter(); + OverlayStatUtilizationPrinter(double max_utilization = 1.0); OverlayStatSnapshot get_snapshot(const std::string& label, double utilization); private: + double m_max_utilization; WallClock m_last_active; }; diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoPipelineOptions.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoPipelineOptions.h index 6a861ce584..e7a4d19133 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoPipelineOptions.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoPipelineOptions.h @@ -1,62 +1,62 @@ -/* Video Pipeline Options - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoPipelineOptions_H -#define PokemonAutomation_VideoPipeline_VideoPipelineOptions_H - -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Backends/CameraImplementations.h" - -namespace PokemonAutomation{ - - -class VideoPipelineOptions : public GroupOption{ -public: - VideoPipelineOptions() - : GroupOption( - "Video Pipeline", - LockMode::LOCK_WHILE_RUNNING, - GroupOption::EnableMode::ALWAYS_ENABLED, true - ) -#if QT_VERSION_MAJOR == 5 - , ENABLE_FRAME_SCREENSHOTS( - "Enable Frame Screenshots:
" - "Attempt to use QVideoProbe and QVideoFrame for screenshots.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) -#endif - , AUTO_RESET_SECONDS( - "Video Auto-Reset:
" - "Attempt to reset the video if this many seconds has elapsed since the last video frame (in order to fix issues with RDP disconnection, etc).
" - "This option is not supported by all video frameworks.", - LockMode::UNLOCK_WHILE_RUNNING, - 5 - ) - { - PA_ADD_OPTION(VIDEO_BACKEND); -#if QT_VERSION_MAJOR == 5 - PA_ADD_OPTION(ENABLE_FRAME_SCREENSHOTS); -#endif - - PA_ADD_OPTION(AUTO_RESET_SECONDS); - } - -public: - VideoBackendOption VIDEO_BACKEND; -#if QT_VERSION_MAJOR == 5 - BooleanCheckBoxOption ENABLE_FRAME_SCREENSHOTS; -#endif - - SimpleIntegerOption AUTO_RESET_SECONDS; -}; - - - -} -#endif +/* Video Pipeline Options + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoPipelineOptions_H +#define PokemonAutomation_VideoPipeline_VideoPipelineOptions_H + +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Backends/CameraImplementations.h" + +namespace PokemonAutomation{ + + +class VideoPipelineOptions : public GroupOption{ +public: + VideoPipelineOptions() + : GroupOption( + "Video Pipeline", + LockMode::LOCK_WHILE_RUNNING, + GroupOption::EnableMode::ALWAYS_ENABLED, true + ) +#if QT_VERSION_MAJOR == 5 + , ENABLE_FRAME_SCREENSHOTS( + "Enable Frame Screenshots:
" + "Attempt to use QVideoProbe and QVideoFrame for screenshots.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) +#endif + , AUTO_RESET_SECONDS( + "Video Auto-Reset:
" + "Attempt to reset the video if this many seconds has elapsed since the last video frame (in order to fix issues with RDP disconnection, etc).
" + "This option is not supported by all video frameworks.", + LockMode::UNLOCK_WHILE_RUNNING, + 5 + ) + { + PA_ADD_OPTION(VIDEO_BACKEND); +#if QT_VERSION_MAJOR == 5 + PA_ADD_OPTION(ENABLE_FRAME_SCREENSHOTS); +#endif + + PA_ADD_OPTION(AUTO_RESET_SECONDS); + } + +public: + VideoBackendOption VIDEO_BACKEND; +#if QT_VERSION_MAJOR == 5 + BooleanCheckBoxOption ENABLE_FRAME_SCREENSHOTS; +#endif + + SimpleIntegerOption AUTO_RESET_SECONDS; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSession.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSession.cpp index 03a0fac482..89108ca2ca 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSession.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSession.cpp @@ -1,259 +1,267 @@ -/* Video Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Qt/Redispatch.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/GlobalServices.h" -#include "CommonFramework/VideoPipeline/VideoPipelineOptions.h" -#include "Backends/VideoFrameQt.h" -#include "VideoSources/VideoSource_Null.h" -#include "VideoSession.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -void VideoSession::add_state_listener(StateListener& listener){ - m_state_listeners.add(listener); -} -void VideoSession::remove_state_listener(StateListener& listener){ - m_state_listeners.remove(listener); -} -void VideoSession::add_frame_listener(VideoFrameListener& listener){ - m_frame_listeners.add(listener); -} -void VideoSession::remove_frame_listener(VideoFrameListener& listener){ - m_frame_listeners.remove(listener); -} - - - - -VideoSession::~VideoSession(){ - if (m_video_source){ - m_video_source->remove_source_frame_listener(*this); - m_video_source->remove_rendered_frame_listener(*this); - } - global_watchdog().remove(*this); -} -VideoSession::VideoSession(Logger& logger, VideoSourceOption& option) - : m_logger(logger) - , m_option(option) - , m_descriptor(std::make_unique()) -{ - uint8_t watchdog_timeout = GlobalSettings::instance().VIDEO_PIPELINE->AUTO_RESET_SECONDS; - if (watchdog_timeout != 0){ - global_watchdog().add(*this, std::chrono::seconds(watchdog_timeout)); - } - set_source(option.descriptor()); -} - - - - -std::shared_ptr VideoSession::descriptor() const{ - ReadSpinLock lg(m_state_lock); - return m_descriptor; -} -Resolution VideoSession::current_resolution(){ - ReadSpinLock lg(m_state_lock); - if (m_video_source){ - return m_video_source->current_resolution(); - }else{ - return Resolution(); - } -} -std::vector VideoSession::supported_resolutions() const{ - ReadSpinLock lg(m_state_lock); - if (m_video_source){ - return m_video_source->supported_resolutions(); - }else{ - return {}; - } -} - - - -void VideoSession::get(VideoSourceOption& option){ - ReadSpinLock lg(m_state_lock); - option = m_option; -} -void VideoSession::set(const VideoSourceOption& option){ - set_source(option.descriptor()); -} - -void VideoSession::reset(){ - m_logger.log("Resetting the video...", COLOR_GREEN); - dispatch_to_main_thread([this]{ - std::lock_guard lg0(m_reset_lock); - - m_state_listeners.run_method_unique(&StateListener::pre_shutdown); - - { - WriteSpinLock lg(m_state_lock); - if (m_video_source){ - m_video_source->remove_source_frame_listener(*this); - m_video_source->remove_rendered_frame_listener(*this); - m_video_source.reset(); - } - - m_video_source = m_descriptor->make_VideoSource(m_logger, m_option.m_resolution); - - if (m_video_source){ - m_option.m_resolution = m_video_source->current_resolution(); - m_video_source->add_source_frame_listener(*this); - m_video_source->add_rendered_frame_listener(*this); - } - } - - m_state_listeners.run_method_unique( - &StateListener::post_startup, - m_video_source.get() - ); - }); -} -void VideoSession::set_source(const std::shared_ptr& device){ - m_logger.log("Changing video...", COLOR_GREEN); - dispatch_to_main_thread([this, device]{ - std::lock_guard lg0(m_reset_lock); - if (*m_descriptor == *device && !m_descriptor->should_reload()){ - return; - } - - m_state_listeners.run_method_unique(&StateListener::pre_shutdown); - - { - WriteSpinLock lg(m_state_lock); - if (m_video_source){ - m_video_source->remove_source_frame_listener(*this); - m_video_source->remove_rendered_frame_listener(*this); - m_video_source.reset(); - } - - m_option.set_descriptor(device); - m_descriptor = device; - - Resolution desired_resolution = m_option.m_resolution; - m_video_source = device->make_VideoSource(m_logger, desired_resolution); - - if (m_video_source){ - m_option.m_resolution = m_video_source->current_resolution(); - m_video_source->add_source_frame_listener(*this); - m_video_source->add_rendered_frame_listener(*this); - } - } - - m_state_listeners.run_method_unique( - &StateListener::post_startup, - m_video_source.get() - ); - }); -} -void VideoSession::set_resolution(Resolution resolution){ - m_logger.log("Changing resolution...", COLOR_GREEN); - dispatch_to_main_thread([this, resolution]{ - std::lock_guard lg0(m_reset_lock); - if (m_option.m_resolution == resolution){ - return; - } - - { - WriteSpinLock lg(m_state_lock); - m_state_listeners.run_method_unique(&StateListener::pre_shutdown); - - if (m_video_source){ - m_video_source->remove_source_frame_listener(*this); - m_video_source->remove_rendered_frame_listener(*this); - m_video_source.reset(); - } - - m_video_source = m_descriptor->make_VideoSource(m_logger, resolution); - - if (m_video_source){ - m_option.m_resolution = m_video_source->current_resolution(); - m_video_source->add_source_frame_listener(*this); - m_video_source->add_rendered_frame_listener(*this); - } - } - - m_state_listeners.run_method_unique( - &StateListener::post_startup, - m_video_source.get() - ); - }); -} - - -VideoSnapshot VideoSession::snapshot(){ - ReadSpinLock lg(m_state_lock); - if (m_video_source){ - return m_video_source->snapshot(); - }else{ - return VideoSnapshot(); - } -} - -double VideoSession::fps_source() const{ - ReadSpinLock lg(m_fps_lock); - return m_fps_tracker_source.events_per_second(); -} -double VideoSession::fps_display() const{ - ReadSpinLock lg(m_fps_lock); - return m_fps_tracker_rendered.events_per_second(); -} -void VideoSession::on_frame(std::shared_ptr frame){ - m_frame_listeners.run_method_unique(&VideoFrameListener::on_frame, frame); - { - WriteSpinLock lg(m_fps_lock); - m_fps_tracker_source.push_event(frame->timestamp); - } - global_watchdog().delay(*this); -} -void VideoSession::on_rendered_frame(WallClock timestamp){ - WriteSpinLock lg(m_fps_lock); - m_fps_tracker_rendered.push_event(timestamp); -} - - -void VideoSession::on_watchdog_timeout(){ - { - ReadSpinLock lg(m_state_lock); - if (!m_video_source || !m_video_source->allow_watchdog_reset()){ - return; - } - } - - uint8_t watchdog_timeout = GlobalSettings::instance().VIDEO_PIPELINE->AUTO_RESET_SECONDS; - m_logger.log("No video detected for " + std::to_string(watchdog_timeout) + " seconds...", COLOR_RED); - - if (watchdog_timeout == 0){ - return; - } - - reset(); -} - - - - - - - - - - - - - - - - - -} +/* Video Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Qt/Redispatch.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/GlobalServices.h" +#include "CommonFramework/VideoPipeline/VideoPipelineOptions.h" +#include "Backends/VideoFrameQt.h" +#include "VideoSources/VideoSource_Null.h" +#include "VideoSession.h" + +// #include +// using std::cout; +// using std::endl; + +namespace PokemonAutomation{ + + + +void VideoSession::add_state_listener(StateListener& listener){ + m_state_listeners.add(listener); +} +void VideoSession::remove_state_listener(StateListener& listener){ + m_state_listeners.remove(listener); +} +void VideoSession::add_frame_listener(VideoFrameListener& listener){ + m_frame_listeners.add(listener); +} +void VideoSession::remove_frame_listener(VideoFrameListener& listener){ + m_frame_listeners.remove(listener); +} + + + + +VideoSession::~VideoSession(){ + if (m_video_source){ + m_video_source->remove_source_frame_listener(*this); + m_video_source->remove_rendered_frame_listener(*this); + } + global_watchdog().remove(*this); +} +VideoSession::VideoSession(Logger& logger, VideoSourceOption& option) + : m_logger(logger) + , m_option(option) + , m_descriptor(std::make_unique()) +{ + uint8_t watchdog_timeout = GlobalSettings::instance().VIDEO_PIPELINE->AUTO_RESET_SECONDS; + if (watchdog_timeout != 0){ + global_watchdog().add(*this, std::chrono::seconds(watchdog_timeout)); + } + set_source(option.descriptor()); +} + + + + +std::shared_ptr VideoSession::descriptor() const{ + ReadSpinLock lg(m_state_lock); + return m_descriptor; +} +Resolution VideoSession::current_resolution(){ + ReadSpinLock lg(m_state_lock); + if (m_video_source){ + return m_video_source->current_resolution(); + }else{ + return Resolution(); + } +} +std::vector VideoSession::supported_resolutions() const{ + ReadSpinLock lg(m_state_lock); + if (m_video_source){ + return m_video_source->supported_resolutions(); + }else{ + return {}; + } +} + + + +void VideoSession::get(VideoSourceOption& option){ + ReadSpinLock lg(m_state_lock); + option = m_option; +} +void VideoSession::set(const VideoSourceOption& option){ + set_source(option.descriptor()); +} + +void VideoSession::reset(){ + m_logger.log("Resetting the video...", COLOR_GREEN); + dispatch_to_main_thread([this]{ + std::lock_guard lg0(m_reset_lock); + + m_state_listeners.run_method_unique(&StateListener::pre_shutdown); + + { + WriteSpinLock lg(m_state_lock); + if (m_video_source){ + m_video_source->remove_source_frame_listener(*this); + m_video_source->remove_rendered_frame_listener(*this); + m_video_source.reset(); + } + + m_video_source = m_descriptor->make_VideoSource(m_logger, m_option.m_resolution); + + if (m_video_source){ + m_option.m_resolution = m_video_source->current_resolution(); + m_video_source->add_source_frame_listener(*this); + m_video_source->add_rendered_frame_listener(*this); + } + } + + m_state_listeners.run_method_unique( + &StateListener::post_startup, + m_video_source.get() + ); + }); +} +void VideoSession::set_source(const std::shared_ptr& device){ + m_logger.log("Changing video...", COLOR_GREEN); + dispatch_to_main_thread([this, device]{ + std::lock_guard lg0(m_reset_lock); + if (*m_descriptor == *device && !m_descriptor->should_reload()){ + return; + } + + m_state_listeners.run_method_unique(&StateListener::pre_shutdown); + + { + WriteSpinLock lg(m_state_lock); + if (m_video_source){ + m_video_source->remove_source_frame_listener(*this); + m_video_source->remove_rendered_frame_listener(*this); + m_video_source.reset(); + } + + m_option.set_descriptor(device); + m_descriptor = device; + + Resolution desired_resolution = m_option.m_resolution; + m_video_source = device->make_VideoSource(m_logger, desired_resolution); + + if (m_video_source){ + m_option.m_resolution = m_video_source->current_resolution(); + m_video_source->add_source_frame_listener(*this); + m_video_source->add_rendered_frame_listener(*this); + } + } + + m_state_listeners.run_method_unique( + &StateListener::post_startup, + m_video_source.get() + ); + }); +} +void VideoSession::set_resolution(Resolution resolution){ + m_logger.log("Changing resolution...", COLOR_GREEN); + dispatch_to_main_thread([this, resolution]{ + std::lock_guard lg0(m_reset_lock); + if (m_option.m_resolution == resolution){ + return; + } + + { + WriteSpinLock lg(m_state_lock); + m_state_listeners.run_method_unique(&StateListener::pre_shutdown); + + if (m_video_source){ + m_video_source->remove_source_frame_listener(*this); + m_video_source->remove_rendered_frame_listener(*this); + m_video_source.reset(); + } + + m_video_source = m_descriptor->make_VideoSource(m_logger, resolution); + + if (m_video_source){ + m_option.m_resolution = m_video_source->current_resolution(); + m_video_source->add_source_frame_listener(*this); + m_video_source->add_rendered_frame_listener(*this); + } + } + + m_state_listeners.run_method_unique( + &StateListener::post_startup, + m_video_source.get() + ); + }); +} + + +VideoSnapshot VideoSession::snapshot_latest_blocking(){ + ReadSpinLock lg(m_state_lock); + if (m_video_source){ + return m_video_source->snapshot_latest_blocking(); + }else{ + return VideoSnapshot(); + } +} +VideoSnapshot VideoSession::snapshot_recent_nonblocking(WallClock min_time){ + ReadSpinLock lg(m_state_lock); + if (m_video_source){ + return m_video_source->snapshot_recent_nonblocking(min_time); + }else{ + return VideoSnapshot(); + } +} + +double VideoSession::fps_source() const{ + ReadSpinLock lg(m_fps_lock); + return m_fps_tracker_source.events_per_second(); +} +double VideoSession::fps_display() const{ + ReadSpinLock lg(m_fps_lock); + return m_fps_tracker_rendered.events_per_second(); +} +void VideoSession::on_frame(std::shared_ptr frame){ + m_frame_listeners.run_method_unique(&VideoFrameListener::on_frame, frame); + { + WriteSpinLock lg(m_fps_lock); + m_fps_tracker_source.push_event(frame->timestamp); + } + global_watchdog().delay(*this); +} +void VideoSession::on_rendered_frame(WallClock timestamp){ + WriteSpinLock lg(m_fps_lock); + m_fps_tracker_rendered.push_event(timestamp); +} + + +void VideoSession::on_watchdog_timeout(){ + { + ReadSpinLock lg(m_state_lock); + if (!m_video_source || !m_video_source->allow_watchdog_reset()){ + return; + } + } + + uint8_t watchdog_timeout = GlobalSettings::instance().VIDEO_PIPELINE->AUTO_RESET_SECONDS; + m_logger.log("No video detected for " + std::to_string(watchdog_timeout) + " seconds...", COLOR_RED); + + if (watchdog_timeout == 0){ + return; + } + + reset(); +} + + + + + + + + + + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSession.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSession.h index d08889a506..6eaf48771b 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSession.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSession.h @@ -1,109 +1,197 @@ -/* Video Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoSession_H -#define PokemonAutomation_VideoPipeline_VideoSession_H - -#include -#include -#include "Common/Cpp/EventRateTracker.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Cpp/Concurrency/Watchdog.h" -#include "VideoSourceDescriptor.h" -#include "VideoSource.h" - -namespace PokemonAutomation{ - - -class VideoSession - : public VideoFeed - , private VideoFrameListener - , private VideoSource::RenderedFrameListener - , private WatchdogCallback -{ -public: - struct StateListener{ - virtual void post_startup(VideoSource* source){} - - // Sent before the video source shuts down. Listeners should drop their - // references to the internal video source before returning. - virtual void pre_shutdown(){} - virtual void post_shutdown(){} - - virtual void pre_resolution_change(Resolution resolution){} - virtual void post_resolution_change(Resolution resolution){} - }; - - void add_state_listener(StateListener& listener); - void remove_state_listener(StateListener& listener); - - virtual void add_frame_listener(VideoFrameListener& listener) override; - virtual void remove_frame_listener(VideoFrameListener& listener) override; - - -public: - ~VideoSession(); - VideoSession(Logger& logger, VideoSourceOption& option); - - Logger& logger(){ - return m_logger; - } - - std::shared_ptr descriptor() const; - - // Warning, not thread-safe with any source changes. - VideoSource* current_source(){ - return m_video_source.get(); - } - - Resolution current_resolution(); - std::vector supported_resolutions() const; - - virtual VideoSnapshot snapshot() override; - - virtual double fps_source() const override; - virtual double fps_display() const override; - - -public: - void get(VideoSourceOption& option); - void set(const VideoSourceOption& option); - - virtual void reset() override; - void set_source(const std::shared_ptr& device); - void set_resolution(Resolution resolution); - - -private: - virtual void on_frame(std::shared_ptr frame) override; - virtual void on_rendered_frame(WallClock timestamp) override; - - virtual void on_watchdog_timeout() override; - - -private: - mutable std::mutex m_reset_lock; - mutable SpinLock m_state_lock; - - Logger& m_logger; - VideoSourceOption& m_option; - - mutable SpinLock m_fps_lock; - EventRateTracker m_fps_tracker_source; - EventRateTracker m_fps_tracker_rendered; - - std::shared_ptr m_descriptor; - std::unique_ptr m_video_source; - - ListenerSet m_state_listeners; - ListenerSet m_frame_listeners; -}; - - - - -} -#endif +/* Video Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoSession_H +#define PokemonAutomation_VideoPipeline_VideoSession_H + +#include +#include +#include "Common/Cpp/EventRateTracker.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Cpp/Concurrency/Watchdog.h" +#include "VideoSourceDescriptor.h" +#include "VideoSource.h" + +namespace PokemonAutomation{ + + +class VideoSession + : public VideoFeed // interface class the automation programs have access to to query video snapshots + // and reset the video source + , private VideoFrameListener // listens to incoming frames from video source + , private VideoSource::RenderedFrameListener // listens to newly rendered frame from video source + , private WatchdogCallback +{ +public: + // other classes can inherit this struct to react to state changes in the VideoSession. + // You need to call VideoSession::add_state_listener() to add other classes as listeners + // and remove them by VideoSession::remove_state_listener() when they are no longer needed. + // When a state change happens, VideoSession will call the corresponding callback functions + // in the StateListener. + struct StateListener{ + // Called whenever the video source is initialized or reset. + // This also includes when the video resolution is changed as we need to rebuild the video + // source with the new resolution. + virtual void post_startup(VideoSource* source){} + + // Sent before the video source resets or shuts down. Listeners should drop their + // references to the internal video source before returning. + // This also includes when the video resolution is changed as we need to rebuild the video + // source with the new resolution. + virtual void pre_shutdown(){} + // Currently not called by VideoSession yet. + virtual void post_shutdown(){} + // Currently not called by VideoSession yet. + virtual void pre_resolution_change(Resolution resolution){} + // Currently not called by VideoSession yet. + virtual void post_resolution_change(Resolution resolution){} + }; + + // Add a state listener for it to react to state changes in the VideoSession. + // When a state change happens, VideoSession will call the corresponding callback functions + // in the StateListener. + void add_state_listener(StateListener& listener); + // Remove the state listener. + void remove_state_listener(StateListener& listener); + + // Implements VideoFeed::add_frame_listener(). + // Add a VideoFrameListener for it to react to incoming frames in the video source. + // Whenever the video source sends a frame, VideoSession will call the callback functions + // in added listeners. + virtual void add_frame_listener(VideoFrameListener& listener) override; + // Implements VideoFeed::remove_frame_listener(). + // Remove the frame listener. + virtual void remove_frame_listener(VideoFrameListener& listener) override; + + +public: + ~VideoSession(); + // Built from a VideoSourceOption. + // VideoSourceOption manages the current VideoSourceDescriptor, which are the descriptors + // to build a VideoSource. + // VideoSession stores a reference of the passed in VideoSourceOption to manipulate the + // option according to user selection. + VideoSession(Logger& logger, VideoSourceOption& option); + + Logger& logger(){ + return m_logger; + } + + // Current video source descriptor. + // This function is thread-safe. It has a lock to prevent concurrent calls + // of other VideoSession functions. + std::shared_ptr descriptor() const; + + // Warning, not thread-safe with any source changes. + VideoSource* current_source(){ + return m_video_source.get(); + } + + // Return current resolution. + // This function is thread-safe. It has a lock to prevent concurrent calls + // of other VideoSession functions. + Resolution current_resolution(); + // Return supported resolutions. + // This function is thread-safe. It has a lock to prevent concurrent calls + // of other VideoSession functions. + std::vector supported_resolutions() const; + + // Implements VideoFeed::snapshot() to provide a snapshot from the current video stream. + // It will wait for a latest snapshot, blocking the current thread to wait for it. + // This function is thread-safe. It has a lock to prevent concurrent calls + // of other VideoSession functions. + virtual VideoSnapshot snapshot_latest_blocking() override; + // Implements VideoFeed::snapshot_recent_nonblocking() to provide a snapshot from the + // current video stream. + // It will use the most recent available frame, therefore non-blocking. + // This function is thread-safe. It has a lock to prevent concurrent calls + // of other VideoSession functions. + virtual VideoSnapshot snapshot_recent_nonblocking(WallClock min_time) override; + + // Implements VideoFeed::fps_source(). + // Returns the currently measured frames/second for the video source. + // Use this for diagnostic purposes. + // This function is thread-safe. It has a lock to prevent concurrent fps calls. + virtual double fps_source() const override; + // Implements VideoFeed::fps_display(). + // Returns the currently measured frames/second for the video display thread. + // Use this for diagnostic purposes. + // This function is thread-safe. It has a lock to prevent concurrent fps calls. + virtual double fps_display() const override; + + +public: + // Get current video source option + void get(VideoSourceOption& option); + // Set a new video source. This will close the old video source. + // This equals to calling VideoSession::set_source(option.descriptor()). + // Change of video source and resolution will be reflected on the internal + // referenced video source option (aka the VideoSourceOption passed to the + // VideoSession constructor). + // The change is dispatched to the Qt main thread to execute. + void set(const VideoSourceOption& option); + // Implements VideoFeed::reset(). + // Reset the current video source. This equals to close the old video source + // and reopen it. + // This may also change the internal referenced video source option (aka the + // VideoSourceOption passed to the VideoSession constructor). + // The change is dispatched to the Qt main thread to execute. + virtual void reset() override; + // Set a new video source. This will close the old video source. + // Change of video source and resolution will be reflected on the internal + // referenced video source option (aka the VideoSourceOption passed to the + // VideoSession constructor). + // The change is dispatched to the Qt main thread to execute. + void set_source(const std::shared_ptr& device); + // Change video resolution. + // This will trigger a video source reset. + // Change of resolution will be reflected on the internal referenced video + // source option (aka the VideoSourceOption passed to the VideoSession + // constructor). + // The change is dispatched to the Qt main thread to execute. + void set_resolution(Resolution resolution); + + +private: + // Overwrites VideoFrameListener::on_frame() + // When this function is called, the VideoSession will update its internal fps record + // and call frame listeners added by VideoSession::add_frame_listener(). + // This function is thread-safe as it has a lock to prevent concurrent fps calls. + // Note the lock does not protect the other frame listeners added by + // VideoSession::add_frame_listener(). + virtual void on_frame(std::shared_ptr frame) override; + // Overwrites VideoSource::RenderedFrameListener::on_rendered_frame() + // This function is called when the video source finds a new rendered frame so + // VideoSession can update its internal fps record. + // This function is thread-safe as it has a lock to prevent concurrent fps calls. + virtual void on_rendered_frame(WallClock timestamp) override; + + virtual void on_watchdog_timeout() override; + + +private: + mutable std::mutex m_reset_lock; + mutable SpinLock m_state_lock; + + Logger& m_logger; + VideoSourceOption& m_option; + + mutable SpinLock m_fps_lock; + EventRateTracker m_fps_tracker_source; + EventRateTracker m_fps_tracker_rendered; + + std::shared_ptr m_descriptor; + std::unique_ptr m_video_source; + + ListenerSet m_state_listeners; + ListenerSet m_frame_listeners; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource.cpp index 9d61d0c2e9..e3ba271115 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource.cpp @@ -1,12 +1,12 @@ -/* Video Source - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "VideoSource.h" - -namespace PokemonAutomation{ - - -} +/* Video Source + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "VideoSource.h" + +namespace PokemonAutomation{ + + +} diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource.h index dd153d3629..5e94e66aa6 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource.h @@ -1,89 +1,96 @@ -/* Video Source - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoSource_H -#define PokemonAutomation_VideoPipeline_VideoSource_H - -#include "Common/Cpp/LifetimeSanitizer.h" -#include "Common/Cpp/ImageResolution.h" -#include "Common/Cpp/ListenerSet.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" - -class QWidget; - -namespace PokemonAutomation{ - - - - -class VideoSource{ -public: - struct RenderedFrameListener{ - virtual void on_rendered_frame(WallClock timestamp) = 0; - }; - - void add_source_frame_listener(VideoFrameListener& listener){ - m_source_frame_listeners.add(listener); - } - void remove_source_frame_listener(VideoFrameListener& listener){ - m_source_frame_listeners.remove(listener); - } - void add_rendered_frame_listener(RenderedFrameListener& listener){ - m_rendered_frame_listeners.add(listener); - } - void remove_rendered_frame_listener(RenderedFrameListener& listener){ - m_rendered_frame_listeners.remove(listener); - } - - -public: - VideoSource(bool allow_watchdog_reset) - : m_allow_watchdog_reset(allow_watchdog_reset) - , m_sanitizer("VideoSource") - {} - virtual ~VideoSource() = default; - - -public: - bool allow_watchdog_reset() const{ - return m_allow_watchdog_reset; - } - - virtual Resolution current_resolution() const = 0; - virtual const std::vector& supported_resolutions() const = 0; - - virtual VideoSnapshot snapshot() = 0; - - -protected: - void report_source_frame(std::shared_ptr frame){ - auto scope_check = m_sanitizer.check_scope(); - m_source_frame_listeners.run_method_unique(&VideoFrameListener::on_frame, frame); - } - void report_rendered_frame(WallClock timestamp){ - auto scope_check = m_sanitizer.check_scope(); - m_rendered_frame_listeners.run_method_unique(&RenderedFrameListener::on_rendered_frame, timestamp); - } - - -public: - virtual QWidget* make_display_QtWidget(QWidget* parent) = 0; - - -private: - ListenerSet m_source_frame_listeners; - ListenerSet m_rendered_frame_listeners; - - const bool m_allow_watchdog_reset; - - LifetimeSanitizer m_sanitizer; -}; - - - - -} -#endif +/* Video Source + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoSource_H +#define PokemonAutomation_VideoPipeline_VideoSource_H + +#include +#include "Common/Cpp/LifetimeSanitizer.h" +#include "Common/Cpp/ImageResolution.h" +#include "Common/Cpp/ListenerSet.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" + +class QWidget; + +namespace PokemonAutomation{ + + + + +class VideoSource{ +public: + struct RenderedFrameListener{ + virtual void on_rendered_frame(WallClock timestamp) = 0; + }; + + void add_source_frame_listener(VideoFrameListener& listener){ + auto scope_check = m_sanitizer.check_scope(); + m_source_frame_listeners.add(listener); + } + void remove_source_frame_listener(VideoFrameListener& listener){ + auto scope_check = m_sanitizer.check_scope(); + m_source_frame_listeners.remove(listener); + } + void add_rendered_frame_listener(RenderedFrameListener& listener){ + auto scope_check = m_sanitizer.check_scope(); + m_rendered_frame_listeners.add(listener); + } + void remove_rendered_frame_listener(RenderedFrameListener& listener){ + auto scope_check = m_sanitizer.check_scope(); + m_rendered_frame_listeners.remove(listener); + } + + +public: + VideoSource(bool allow_watchdog_reset) + : m_allow_watchdog_reset(allow_watchdog_reset) + , m_sanitizer("VideoSource") + {} + virtual ~VideoSource() = default; + + +public: + bool allow_watchdog_reset() const{ + return m_allow_watchdog_reset; + } + + virtual Resolution current_resolution() const = 0; + virtual const std::vector& supported_resolutions() const = 0; + + virtual VideoSnapshot snapshot_latest_blocking() = 0; + virtual VideoSnapshot snapshot_recent_nonblocking(WallClock min_time) = 0; + + +protected: + void report_source_frame(std::shared_ptr frame){ + auto scope_check = m_sanitizer.check_scope(); + m_source_frame_listeners.run_method_unique(&VideoFrameListener::on_frame, frame); + } + // Called by UI to report a frame is rendered + void report_rendered_frame(WallClock timestamp){ + auto scope_check = m_sanitizer.check_scope(); + m_rendered_frame_listeners.run_method_unique(&RenderedFrameListener::on_rendered_frame, timestamp); + } + + +public: + virtual QWidget* make_display_QtWidget(QWidget* parent) = 0; + + +private: + ListenerSet m_source_frame_listeners; + ListenerSet m_rendered_frame_listeners; + + const bool m_allow_watchdog_reset; + + LifetimeSanitizer m_sanitizer; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSourceDescriptor.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSourceDescriptor.cpp index f98a9122d4..7d9cab1290 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSourceDescriptor.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSourceDescriptor.cpp @@ -1,161 +1,161 @@ -/* Video Source Descriptor - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/EnumStringMap.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "VideoSourceDescriptor.h" - -#include "VideoSources/VideoSource_Null.h" -#include "VideoSources/VideoSource_StillImage.h" -#include "VideoSources/VideoSource_Camera.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -const EnumStringMap VIDEO_TYPE_STRINGS{ - {VideoSourceType::None, "None"}, - {VideoSourceType::StillImage, "Still Image"}, - {VideoSourceType::VideoPlayback, "Video Playback"}, - {VideoSourceType::Camera, "Camera"}, -}; - - -VideoSourceOption::VideoSourceOption() - : m_descriptor(new VideoSourceDescriptor_Null()) - , m_resolution(1920, 1080) -{} - -void VideoSourceOption::set_descriptor(std::shared_ptr descriptor){ - m_descriptor_cache[descriptor->type] = descriptor; - m_descriptor = std::move(descriptor); -} - -std::shared_ptr VideoSourceOption::get_descriptor_from_cache(VideoSourceType type){ - auto iter = m_descriptor_cache.find(type); - if (iter != m_descriptor_cache.end()){ - return iter->second; - } - std::shared_ptr descriptor; - switch (type){ - case VideoSourceType::None: - descriptor.reset(new VideoSourceDescriptor_Null()); - break; - case VideoSourceType::StillImage: - descriptor.reset(new VideoSourceDescriptor_StillImage()); - break; - case VideoSourceType::Camera: - descriptor.reset(new VideoSourceDescriptor_Camera()); - break; - default:; - descriptor.reset(new VideoSourceDescriptor_Null()); - } - m_descriptor_cache[descriptor->type] = descriptor; - return descriptor; -} - - - -void VideoSourceOption::load_json(const JsonValue& json){ - std::shared_ptr descriptor; - do{ - if (json.is_null()){ - break; - } - - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - break; - } - - const JsonArray* res = obj->get_array("Resolution"); - if (res != nullptr && res->size() == 2){ - do{ - size_t width, height; - if (!(*res)[0].read_integer(width)){ - break; - } - if (!(*res)[1].read_integer(height)){ - break; - } - m_resolution = Resolution(width, height); - }while (false); - } - - const std::string* type = obj->get_string("SourceType"); - if (type == nullptr){ - break; - } - -#if 0 - for (const auto& item : VIDEO_TYPE_STRINGS){ - const JsonValue* params = obj->get_value(VIDEO_TYPE_STRINGS.get_string(item.first)); - if (params == nullptr){ - continue; - } - m_descriptor_cache[item.first] = item.second->make(*params); - } -#endif - - const JsonValue* params; - params = obj->get_value(VIDEO_TYPE_STRINGS.get_string(VideoSourceType::StillImage)); - if (params != nullptr){ - auto x = std::make_unique(); - x->load_json(*params); - m_descriptor_cache[VideoSourceType::StillImage] = std::move(x); - } - params = obj->get_value(VIDEO_TYPE_STRINGS.get_string(VideoSourceType::VideoPlayback)); - if (params != nullptr){ -// m_descriptor_cache[VideoSourceType::VideoPlayback] = - } - params = obj->get_value(VIDEO_TYPE_STRINGS.get_string(VideoSourceType::Camera)); - if (params != nullptr){ - auto x = std::make_unique(); - x->load_json(*params); - m_descriptor_cache[VideoSourceType::Camera] = std::move(x); - } - - auto iter = m_descriptor_cache.find(VIDEO_TYPE_STRINGS.get_enum(*type, VideoSourceType::None)); - if (iter == m_descriptor_cache.end()){ - break; - } - - descriptor = iter->second; - }while (false); - - if (descriptor == nullptr){ - descriptor.reset(new VideoSourceDescriptor_Null()); - } - - m_descriptor = std::move(descriptor); -} -JsonValue VideoSourceOption::to_json() const{ - if (!m_descriptor){ - return JsonValue(); - } - JsonObject obj; - { - JsonArray res; - res.push_back(m_resolution.width); - res.push_back(m_resolution.height); - obj["Resolution"] = std::move(res); - } - obj["SourceType"] = VIDEO_TYPE_STRINGS.get_string(m_descriptor->type); - - for (const auto& item : m_descriptor_cache){ - obj[VIDEO_TYPE_STRINGS.get_string(item.first)] = item.second->to_json(); - } - - return obj; -} - - -} +/* Video Source Descriptor + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/EnumStringMap.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "VideoSourceDescriptor.h" + +#include "VideoSources/VideoSource_Null.h" +#include "VideoSources/VideoSource_StillImage.h" +#include "VideoSources/VideoSource_Camera.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +const EnumStringMap VIDEO_TYPE_STRINGS{ + {VideoSourceType::None, "None"}, + {VideoSourceType::StillImage, "Still Image"}, + {VideoSourceType::VideoPlayback, "Video Playback"}, + {VideoSourceType::Camera, "Camera"}, +}; + + +VideoSourceOption::VideoSourceOption() + : m_resolution(1920, 1080) + , m_descriptor(new VideoSourceDescriptor_Null()) +{} + +void VideoSourceOption::set_descriptor(std::shared_ptr descriptor){ + m_descriptor_cache[descriptor->type] = descriptor; + m_descriptor = std::move(descriptor); +} + +std::shared_ptr VideoSourceOption::get_descriptor_from_cache(VideoSourceType type){ + auto iter = m_descriptor_cache.find(type); + if (iter != m_descriptor_cache.end()){ + return iter->second; + } + std::shared_ptr descriptor; + switch (type){ + case VideoSourceType::None: + descriptor.reset(new VideoSourceDescriptor_Null()); + break; + case VideoSourceType::StillImage: + descriptor.reset(new VideoSourceDescriptor_StillImage()); + break; + case VideoSourceType::Camera: + descriptor.reset(new VideoSourceDescriptor_Camera()); + break; + default:; + descriptor.reset(new VideoSourceDescriptor_Null()); + } + m_descriptor_cache[descriptor->type] = descriptor; + return descriptor; +} + + + +void VideoSourceOption::load_json(const JsonValue& json){ + std::shared_ptr descriptor; + do{ + if (json.is_null()){ + break; + } + + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + break; + } + + const JsonArray* res = obj->get_array("Resolution"); + if (res != nullptr && res->size() == 2){ + do{ + size_t width, height; + if (!(*res)[0].read_integer(width)){ + break; + } + if (!(*res)[1].read_integer(height)){ + break; + } + m_resolution = Resolution(width, height); + }while (false); + } + + const std::string* type = obj->get_string("SourceType"); + if (type == nullptr){ + break; + } + +#if 0 + for (const auto& item : VIDEO_TYPE_STRINGS){ + const JsonValue* params = obj->get_value(VIDEO_TYPE_STRINGS.get_string(item.first)); + if (params == nullptr){ + continue; + } + m_descriptor_cache[item.first] = item.second->make(*params); + } +#endif + + const JsonValue* params; + params = obj->get_value(VIDEO_TYPE_STRINGS.get_string(VideoSourceType::StillImage)); + if (params != nullptr){ + auto x = std::make_unique(); + x->load_json(*params); + m_descriptor_cache[VideoSourceType::StillImage] = std::move(x); + } + params = obj->get_value(VIDEO_TYPE_STRINGS.get_string(VideoSourceType::VideoPlayback)); + if (params != nullptr){ +// m_descriptor_cache[VideoSourceType::VideoPlayback] = + } + params = obj->get_value(VIDEO_TYPE_STRINGS.get_string(VideoSourceType::Camera)); + if (params != nullptr){ + auto x = std::make_unique(); + x->load_json(*params); + m_descriptor_cache[VideoSourceType::Camera] = std::move(x); + } + + auto iter = m_descriptor_cache.find(VIDEO_TYPE_STRINGS.get_enum(*type, VideoSourceType::None)); + if (iter == m_descriptor_cache.end()){ + break; + } + + descriptor = iter->second; + }while (false); + + if (descriptor == nullptr){ + descriptor.reset(new VideoSourceDescriptor_Null()); + } + + m_descriptor = std::move(descriptor); +} +JsonValue VideoSourceOption::to_json() const{ + if (!m_descriptor){ + return JsonValue(); + } + JsonObject obj; + { + JsonArray res; + res.push_back(m_resolution.width); + res.push_back(m_resolution.height); + obj["Resolution"] = std::move(res); + } + obj["SourceType"] = VIDEO_TYPE_STRINGS.get_string(m_descriptor->type); + + for (const auto& item : m_descriptor_cache){ + obj[VIDEO_TYPE_STRINGS.get_string(item.first)] = item.second->to_json(); + } + + return obj; +} + + +} diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSourceDescriptor.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSourceDescriptor.h index 387c15c5c6..6afc93bc2f 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSourceDescriptor.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSourceDescriptor.h @@ -1,93 +1,107 @@ -/* Video Source Descriptor - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoSourceDescriptor_H -#define PokemonAutomation_VideoPipeline_VideoSourceDescriptor_H - -#include -#include -#include "Common/Cpp/ImageResolution.h" -#include "Common/Cpp/Json/JsonValue.h" - -namespace PokemonAutomation{ - -class VideoSource; - - - -enum class VideoSourceType{ - None, - StillImage, - VideoPlayback, - Camera, -}; - - - -class VideoSourceDescriptor{ -public: - const VideoSourceType type; - -public: - VideoSourceDescriptor(VideoSourceType p_type) - : type(p_type) - {} - virtual ~VideoSourceDescriptor() = default; - -public: - virtual bool should_reload() const{ return false; } - virtual bool operator==(const VideoSourceDescriptor& x) const = 0; - virtual std::string display_name() const = 0; - -public: - virtual void run_post_select(){}; - virtual void load_json(const JsonValue& json) = 0; - virtual JsonValue to_json() const = 0; - -public: - virtual std::unique_ptr make_VideoSource( - Logger& logger, - Resolution resolution - ) const = 0; -}; - - - - -class VideoSourceOption{ -public: - VideoSourceOption(); - - std::shared_ptr descriptor() const{ - return m_descriptor; - } - void set_descriptor(std::shared_ptr descriptor); - - // Remember the last used descriptor for each interface type. That way when - // the user switches back-and-forth between two interfaces, it will reload - // the previous one. - std::shared_ptr get_descriptor_from_cache(VideoSourceType type); - - -public: - void load_json(const JsonValue& json); - JsonValue to_json() const; - - -private: - std::shared_ptr m_descriptor; -public: - Resolution m_resolution; - -private: - std::map> m_descriptor_cache; -}; - - - - -} -#endif +/* Video Source Descriptor + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoSourceDescriptor_H +#define PokemonAutomation_VideoPipeline_VideoSourceDescriptor_H + +#include +#include +#include "Common/Cpp/ImageResolution.h" +#include "Common/Cpp/Json/JsonValue.h" + +namespace PokemonAutomation{ + +class VideoSource; + + + +enum class VideoSourceType{ + None, + StillImage, + VideoPlayback, + Camera, +}; + + + +// - Describe basic attributes of a video source. The source can be webcam or +// the capture card that streams a Switch console. +// - Can load and save the attributes to JSON. +// - Can call make_VideoSource() to create a VideoSource object that manages +// the video source and can create UI widget to display it. +// - After user selects a new video source on the UI, call run_post_select() +// to do some optional additional stuff after the user's selection, e.g. +// open a file selection dialog box to continue user interaction. +class VideoSourceDescriptor{ +public: + const VideoSourceType type; + +public: + VideoSourceDescriptor(VideoSourceType p_type) + : type(p_type) + {} + virtual ~VideoSourceDescriptor() = default; + +public: + virtual bool should_reload() const{ return false; } + virtual bool operator==(const VideoSourceDescriptor& x) const = 0; + virtual std::string display_name() const = 0; + +public: + // After user selects a new video source on the UI, call this function to + // do some optional additional stuff, e.g. open a file selection dialog + // box to continue user interaction. + virtual void run_post_select(){}; + virtual void load_json(const JsonValue& json) = 0; + virtual JsonValue to_json() const = 0; + +public: + virtual std::unique_ptr make_VideoSource( + Logger& logger, + Resolution resolution + ) const = 0; +}; + + + +// VideoSourceOption manages VideoSourceDescriptor so user can switch between different +// video sources. User can set new VideoSourceDescriptor to it. It also stores the current +// video resolution. +// It has a cache to store last used VideoSourceDescriptor for faster video source switch. +// It is used as the input to build a VideoSession. +class VideoSourceOption{ +public: + VideoSourceOption(); + + std::shared_ptr descriptor() const{ + return m_descriptor; + } + void set_descriptor(std::shared_ptr descriptor); + + // Use a cache to help create a VideoSoruceDescriptor. + // The cache remembers the last used descriptor for each interface type. That way when + // the user switches back-and-forth between two interfaces, it will reload the previous + // one and return faster. + // If not found in cache, it will create a new one according to the type. + std::shared_ptr get_descriptor_from_cache(VideoSourceType type); + +public: + void load_json(const JsonValue& json); + JsonValue to_json() const; + +public: + Resolution m_resolution; + +private: + std::shared_ptr m_descriptor; + std::map> m_descriptor_cache; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Camera.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Camera.cpp index e028436c80..78bd958a17 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Camera.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Camera.cpp @@ -1,48 +1,48 @@ -/* Camera Video Source - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Backends/CameraImplementations.h" -#include "VideoSource.h" -#include "VideoSource_Camera.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -bool VideoSourceDescriptor_Camera::operator==(const VideoSourceDescriptor& x) const{ - if (typeid(*this) != typeid(x)){ - return false; - } - return m_info == static_cast(x).m_info; -} -std::string VideoSourceDescriptor_Camera::display_name() const{ - return get_camera_name(m_info); -} - -void VideoSourceDescriptor_Camera::load_json(const JsonValue& json){ - const std::string* name = json.to_string(); - if (name != nullptr){ - m_info = CameraInfo(*name); - } -} -JsonValue VideoSourceDescriptor_Camera::to_json() const{ - return m_info.device_name(); -} - -std::unique_ptr VideoSourceDescriptor_Camera::make_VideoSource(Logger& logger, Resolution resolution) const{ - return get_camera_backend().make_video_source(logger, m_info, resolution); -} - - - - -} - - +/* Camera Video Source + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Backends/CameraImplementations.h" +#include "VideoSource.h" +#include "VideoSource_Camera.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +bool VideoSourceDescriptor_Camera::operator==(const VideoSourceDescriptor& x) const{ + if (typeid(*this) != typeid(x)){ + return false; + } + return m_info == static_cast(x).m_info; +} +std::string VideoSourceDescriptor_Camera::display_name() const{ + return get_camera_name(m_info); +} + +void VideoSourceDescriptor_Camera::load_json(const JsonValue& json){ + const std::string* name = json.to_string(); + if (name != nullptr){ + m_info = CameraInfo(*name); + } +} +JsonValue VideoSourceDescriptor_Camera::to_json() const{ + return m_info.device_name(); +} + +std::unique_ptr VideoSourceDescriptor_Camera::make_VideoSource(Logger& logger, Resolution resolution) const{ + return get_camera_backend().make_video_source(logger, m_info, resolution); +} + + + + +} + + diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Camera.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Camera.h index 93ce2488e1..3e4213a51b 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Camera.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Camera.h @@ -1,41 +1,41 @@ -/* Camera Video Source - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoSource_Camera_H -#define PokemonAutomation_VideoPipeline_VideoSource_Camera_H - -#include "CameraInfo.h" -#include "VideoSourceDescriptor.h" - -namespace PokemonAutomation{ - - -class VideoSourceDescriptor_Camera : public VideoSourceDescriptor{ -public: - VideoSourceDescriptor_Camera() - : VideoSourceDescriptor(VideoSourceType::Camera) - {} - VideoSourceDescriptor_Camera(CameraInfo info) - : VideoSourceDescriptor(VideoSourceType::Camera) - , m_info(std::move(info)) - {} - - virtual bool operator==(const VideoSourceDescriptor& x) const override; - virtual std::string display_name() const override; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual std::unique_ptr make_VideoSource(Logger& logger, Resolution resolution) const override; - -private: - CameraInfo m_info; -}; - - - -} -#endif +/* Camera Video Source + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoSource_Camera_H +#define PokemonAutomation_VideoPipeline_VideoSource_Camera_H + +#include "CameraInfo.h" +#include "VideoSourceDescriptor.h" + +namespace PokemonAutomation{ + + +class VideoSourceDescriptor_Camera : public VideoSourceDescriptor{ +public: + VideoSourceDescriptor_Camera() + : VideoSourceDescriptor(VideoSourceType::Camera) + {} + VideoSourceDescriptor_Camera(CameraInfo info) + : VideoSourceDescriptor(VideoSourceType::Camera) + , m_info(std::move(info)) + {} + + virtual bool operator==(const VideoSourceDescriptor& x) const override; + virtual std::string display_name() const override; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual std::unique_ptr make_VideoSource(Logger& logger, Resolution resolution) const override; + +private: + CameraInfo m_info; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Null.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Null.cpp index e0c8ee6dbb..84ee7e5433 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Null.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Null.cpp @@ -1,32 +1,32 @@ -/* Null Video Source - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "VideoSource.h" -#include "VideoSource_Null.h" - -namespace PokemonAutomation{ - - -bool VideoSourceDescriptor_Null::operator==(const VideoSourceDescriptor& x) const{ - return typeid(*this) == typeid(x); -} -std::string VideoSourceDescriptor_Null::display_name() const{ - return "(none)"; -} - -void VideoSourceDescriptor_Null::load_json(const JsonValue& json){ - -} -JsonValue VideoSourceDescriptor_Null::to_json() const{ - return JsonValue(); -} - -std::unique_ptr VideoSourceDescriptor_Null::make_VideoSource(Logger& logger, Resolution resolution) const{ - return nullptr; -} - - -} +/* Null Video Source + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "VideoSource.h" +#include "VideoSource_Null.h" + +namespace PokemonAutomation{ + + +bool VideoSourceDescriptor_Null::operator==(const VideoSourceDescriptor& x) const{ + return typeid(*this) == typeid(x); +} +std::string VideoSourceDescriptor_Null::display_name() const{ + return "(none)"; +} + +void VideoSourceDescriptor_Null::load_json(const JsonValue& json){ + +} +JsonValue VideoSourceDescriptor_Null::to_json() const{ + return JsonValue(); +} + +std::unique_ptr VideoSourceDescriptor_Null::make_VideoSource(Logger& logger, Resolution resolution) const{ + return nullptr; +} + + +} diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Null.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Null.h index 2faee8c114..36942aff46 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Null.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Null.h @@ -1,33 +1,33 @@ -/* Null Video Source - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoSource_Null_H -#define PokemonAutomation_VideoPipeline_VideoSource_Null_H - -#include "VideoSourceDescriptor.h" - -namespace PokemonAutomation{ - - -class VideoSourceDescriptor_Null : public VideoSourceDescriptor{ -public: - VideoSourceDescriptor_Null() - : VideoSourceDescriptor(VideoSourceType::None) - {} - - virtual bool operator==(const VideoSourceDescriptor& x) const override; - virtual std::string display_name() const override; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual std::unique_ptr make_VideoSource(Logger& logger, Resolution resolution) const override; -}; - - - -} -#endif +/* Null Video Source + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoSource_Null_H +#define PokemonAutomation_VideoPipeline_VideoSource_Null_H + +#include "VideoSourceDescriptor.h" + +namespace PokemonAutomation{ + + +class VideoSourceDescriptor_Null : public VideoSourceDescriptor{ +public: + VideoSourceDescriptor_Null() + : VideoSourceDescriptor(VideoSourceType::None) + {} + + virtual bool operator==(const VideoSourceDescriptor& x) const override; + virtual std::string display_name() const override; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual std::unique_ptr make_VideoSource(Logger& logger, Resolution resolution) const override; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.cpp index 28041cfdd6..49c90ff985 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.cpp @@ -1,51 +1,51 @@ -/* Video Source (Camera) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/Backends/CameraImplementations.h" -#include "CommonFramework/VideoPipeline/VideoSource.h" -#include "VideoSource_Camera.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -bool VideoSourceDescriptor_Camera::operator==(const VideoSourceDescriptor& x) const{ - if (typeid(*this) != typeid(x)){ - return false; - } - return m_info == static_cast(x).m_info; -} -std::string VideoSourceDescriptor_Camera::display_name() const{ - return get_camera_name(m_info); -} - -void VideoSourceDescriptor_Camera::load_json(const JsonValue& json){ - const std::string* name = json.to_string(); - if (name != nullptr){ - m_info = CameraInfo(*name); - } -} -JsonValue VideoSourceDescriptor_Camera::to_json() const{ - return m_info.device_name(); -} - -std::unique_ptr VideoSourceDescriptor_Camera::make_VideoSource( - Logger& logger, - Resolution resolution -) const{ - return get_camera_backend().make_video_source(logger, m_info, resolution); -} - - - - -} - - +/* Video Source (Camera) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/Backends/CameraImplementations.h" +#include "CommonFramework/VideoPipeline/VideoSource.h" +#include "VideoSource_Camera.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +bool VideoSourceDescriptor_Camera::operator==(const VideoSourceDescriptor& x) const{ + if (typeid(*this) != typeid(x)){ + return false; + } + return m_info == static_cast(x).m_info; +} +std::string VideoSourceDescriptor_Camera::display_name() const{ + return get_camera_name(m_info); +} + +void VideoSourceDescriptor_Camera::load_json(const JsonValue& json){ + const std::string* name = json.to_string(); + if (name != nullptr){ + m_info = CameraInfo(*name); + } +} +JsonValue VideoSourceDescriptor_Camera::to_json() const{ + return m_info.device_name(); +} + +std::unique_ptr VideoSourceDescriptor_Camera::make_VideoSource( + Logger& logger, + Resolution resolution +) const{ + return get_camera_backend().make_video_source(logger, m_info, resolution); +} + + + + +} + + diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.h index 5fb93e2dad..5553f82e01 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.h @@ -1,47 +1,47 @@ -/* Video Source (Camera) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoSource_Camera_H -#define PokemonAutomation_VideoPipeline_VideoSource_Camera_H - -#include "CommonFramework/VideoPipeline/CameraInfo.h" -#include "CommonFramework/VideoPipeline/VideoSourceDescriptor.h" - -namespace PokemonAutomation{ - - -class VideoSourceDescriptor_Camera : public VideoSourceDescriptor{ -public: - VideoSourceDescriptor_Camera() - : VideoSourceDescriptor(VideoSourceType::Camera) - {} - VideoSourceDescriptor_Camera(CameraInfo info) - : VideoSourceDescriptor(VideoSourceType::Camera) - , m_info(std::move(info)) - {} - - -public: - virtual bool operator==(const VideoSourceDescriptor& x) const override; - virtual std::string display_name() const override; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual std::unique_ptr make_VideoSource( - Logger& logger, - Resolution resolution - ) const override; - - -private: - CameraInfo m_info; -}; - - - -} -#endif +/* Video Source (Camera) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoSource_Camera_H +#define PokemonAutomation_VideoPipeline_VideoSource_Camera_H + +#include "CommonFramework/VideoPipeline/CameraInfo.h" +#include "CommonFramework/VideoPipeline/VideoSourceDescriptor.h" + +namespace PokemonAutomation{ + + +class VideoSourceDescriptor_Camera : public VideoSourceDescriptor{ +public: + VideoSourceDescriptor_Camera() + : VideoSourceDescriptor(VideoSourceType::Camera) + {} + VideoSourceDescriptor_Camera(CameraInfo info) + : VideoSourceDescriptor(VideoSourceType::Camera) + , m_info(std::move(info)) + {} + + +public: + virtual bool operator==(const VideoSourceDescriptor& x) const override; + virtual std::string display_name() const override; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual std::unique_ptr make_VideoSource( + Logger& logger, + Resolution resolution + ) const override; + + +private: + CameraInfo m_info; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.cpp index c4a31b01b1..f3fcdf22f4 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.cpp @@ -1,35 +1,35 @@ -/* Video Source (Null) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoSource.h" -#include "VideoSource_Null.h" - -namespace PokemonAutomation{ - - -bool VideoSourceDescriptor_Null::operator==(const VideoSourceDescriptor& x) const{ - return typeid(*this) == typeid(x); -} -std::string VideoSourceDescriptor_Null::display_name() const{ - return "(none)"; -} - -void VideoSourceDescriptor_Null::load_json(const JsonValue& json){ - -} -JsonValue VideoSourceDescriptor_Null::to_json() const{ - return JsonValue(); -} - -std::unique_ptr VideoSourceDescriptor_Null::make_VideoSource( - Logger& logger, - Resolution resolution -) const{ - return nullptr; -} - - -} +/* Video Source (Null) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoSource.h" +#include "VideoSource_Null.h" + +namespace PokemonAutomation{ + + +bool VideoSourceDescriptor_Null::operator==(const VideoSourceDescriptor& x) const{ + return typeid(*this) == typeid(x); +} +std::string VideoSourceDescriptor_Null::display_name() const{ + return "(none)"; +} + +void VideoSourceDescriptor_Null::load_json(const JsonValue& json){ + +} +JsonValue VideoSourceDescriptor_Null::to_json() const{ + return JsonValue(); +} + +std::unique_ptr VideoSourceDescriptor_Null::make_VideoSource( + Logger& logger, + Resolution resolution +) const{ + return nullptr; +} + + +} diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.h index b8fadc4631..f59052a976 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.h @@ -1,36 +1,36 @@ -/* Video Source (Null) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoSource_Null_H -#define PokemonAutomation_VideoPipeline_VideoSource_Null_H - -#include "CommonFramework/VideoPipeline/VideoSourceDescriptor.h" - -namespace PokemonAutomation{ - - -class VideoSourceDescriptor_Null : public VideoSourceDescriptor{ -public: - VideoSourceDescriptor_Null() - : VideoSourceDescriptor(VideoSourceType::None) - {} - - virtual bool operator==(const VideoSourceDescriptor& x) const override; - virtual std::string display_name() const override; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual std::unique_ptr make_VideoSource( - Logger& logger, - Resolution resolution - ) const override; -}; - - - -} -#endif +/* Video Source (Null) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoSource_Null_H +#define PokemonAutomation_VideoPipeline_VideoSource_Null_H + +#include "CommonFramework/VideoPipeline/VideoSourceDescriptor.h" + +namespace PokemonAutomation{ + + +class VideoSourceDescriptor_Null : public VideoSourceDescriptor{ +public: + VideoSourceDescriptor_Null() + : VideoSourceDescriptor(VideoSourceType::None) + {} + + virtual bool operator==(const VideoSourceDescriptor& x) const override; + virtual std::string display_name() const override; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual std::unique_ptr make_VideoSource( + Logger& logger, + Resolution resolution + ) const override; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_StillImage.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_StillImage.cpp index 51fc8e72b0..a2b9c1bd9b 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_StillImage.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_StillImage.cpp @@ -1,129 +1,122 @@ -/* Video Source (Still Image) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "VideoSource_StillImage.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -bool VideoSourceDescriptor_StillImage::operator==(const VideoSourceDescriptor& x) const{ - if (typeid(*this) != typeid(x)){ - return false; - } - - std::string other_path = static_cast(x).m_path; - - ReadSpinLock lg(m_lock); - return m_path == other_path; -} - -std::string VideoSourceDescriptor_StillImage::path() const{ - ReadSpinLock lg(m_lock); - return m_path; -} -void VideoSourceDescriptor_StillImage::set_path(std::string path){ - WriteSpinLock lg(m_lock); - m_path = std::move(path); - m_source_image_height = m_source_image_width = 0; -} - -void VideoSourceDescriptor_StillImage::run_post_select(){ -// if (!m_path.empty()){ -// return; -// } - std::string path = QFileDialog::getOpenFileName( - nullptr, "Open image file", ".", "*.png *.jpg" - ).toStdString(); - set_path(std::move(path)); -} -void VideoSourceDescriptor_StillImage::load_json(const JsonValue& json){ -// cout << "load_json: " << m_path << endl; - const std::string* name = json.to_string(); - if (name != nullptr){ - WriteSpinLock lg(m_lock); - m_path = *name; - m_source_image_height = m_source_image_width = 0; - } -} -JsonValue VideoSourceDescriptor_StillImage::to_json() const{ - ReadSpinLock lg(m_lock); - return m_path; -} - -std::unique_ptr VideoSourceDescriptor_StillImage::make_VideoSource(Logger& logger, Resolution resolution) const{ -// cout << "make_VideoSource: " << m_path << endl; - auto video_source = std::make_unique(path(), resolution); - - ReadSpinLock lg(m_lock); - m_source_image_width = video_source->original_image().width(); - m_source_image_height = video_source->original_image().height(); - return video_source; -} - - - - - -VideoSource_StillImage::VideoSource_StillImage(const std::string& path, Resolution resolution) - : VideoSource(false) - , m_original_image(QString::fromStdString(path)) -{ - m_snapshot = VideoSnapshot( - ImageRGB32(m_original_image).scale_to(resolution.width, resolution.height), - current_time() - ); - m_resolution = resolution; - m_resolutions = { - {1280, 720}, - {1920, 1080}, - {3840, 2160}, - {(size_t)m_original_image.width(), (size_t)m_original_image.height()} - }; -} - - - -class VideoWidget_StillImage : public QWidget{ -public: - VideoWidget_StillImage(QWidget* parent, VideoSource_StillImage& source) - : QWidget(parent) - , m_source(source) - {} - -private: - virtual void paintEvent(QPaintEvent* event) override{ - QWidget::paintEvent(event); - - QRect rect(0, 0, this->width(), this->height()); - QPainter painter(this); - painter.drawImage(rect, m_source.m_original_image); - } - -private: - VideoSource_StillImage& m_source; -}; - - - - - -QWidget* VideoSource_StillImage::make_display_QtWidget(QWidget* parent){ - return new VideoWidget_StillImage(parent, *this); -} - - - - -} - +/* Video Source (Still Image) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "VideoSource_StillImage.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +bool VideoSourceDescriptor_StillImage::operator==(const VideoSourceDescriptor& x) const{ + if (typeid(*this) != typeid(x)){ + return false; + } + + std::string other_path = static_cast(x).m_path; + + ReadSpinLock lg(m_lock); + return m_path == other_path; +} + +std::string VideoSourceDescriptor_StillImage::path() const{ + ReadSpinLock lg(m_lock); + return m_path; +} +void VideoSourceDescriptor_StillImage::set_path(std::string path){ + WriteSpinLock lg(m_lock); + m_path = std::move(path); +} + +void VideoSourceDescriptor_StillImage::run_post_select(){ +// if (!m_path.empty()){ +// return; +// } + std::string path = QFileDialog::getOpenFileName( + nullptr, "Open image file", ".", "*.png *.jpg" + ).toStdString(); + set_path(std::move(path)); +} +void VideoSourceDescriptor_StillImage::load_json(const JsonValue& json){ +// cout << "load_json: " << m_path << endl; + const std::string* name = json.to_string(); + if (name != nullptr){ + WriteSpinLock lg(m_lock); + m_path = *name; + } +} +JsonValue VideoSourceDescriptor_StillImage::to_json() const{ + ReadSpinLock lg(m_lock); + return m_path; +} + +std::unique_ptr VideoSourceDescriptor_StillImage::make_VideoSource(Logger& logger, Resolution resolution) const{ +// cout << "make_VideoSource: " << m_path << endl; + return std::make_unique(path(), resolution); +} + + + + + +VideoSource_StillImage::VideoSource_StillImage(const std::string& path, Resolution resolution) + : VideoSource(false) + , m_original_image(QString::fromStdString(path)) +{ + m_snapshot = VideoSnapshot( + ImageRGB32(m_original_image).scale_to(resolution.width, resolution.height), + current_time() + ); + m_resolution = resolution; + m_resolutions = { + {1280, 720}, + {1920, 1080}, + {3840, 2160}, + {(size_t)m_original_image.width(), (size_t)m_original_image.height()} + }; +} + + + +class VideoWidget_StillImage : public QWidget{ +public: + VideoWidget_StillImage(QWidget* parent, VideoSource_StillImage& source) + : QWidget(parent) + , m_source(source) + {} + +private: + virtual void paintEvent(QPaintEvent* event) override{ + QWidget::paintEvent(event); + + QRect rect(0, 0, this->width(), this->height()); + QPainter painter(this); + painter.drawImage(rect, m_source.m_original_image); + } + +private: + VideoSource_StillImage& m_source; +}; + + + + + +QWidget* VideoSource_StillImage::make_display_QtWidget(QWidget* parent){ + return new VideoWidget_StillImage(parent, *this); +} + + + + +} + diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_StillImage.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_StillImage.h index 65e27dbca9..1461db5e1d 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_StillImage.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_StillImage.h @@ -1,98 +1,93 @@ -/* Video Source (Still Image) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoSource_StillImage_H -#define PokemonAutomation_VideoPipeline_VideoSource_StillImage_H - -#include -#include "CommonFramework/VideoPipeline/VideoSourceDescriptor.h" -#include "CommonFramework/VideoPipeline/VideoSource.h" - -namespace PokemonAutomation{ - - -class VideoSourceDescriptor_StillImage : public VideoSourceDescriptor{ -public: - VideoSourceDescriptor_StillImage() - : VideoSourceDescriptor(VideoSourceType::StillImage) - {} - VideoSourceDescriptor_StillImage(std::string path) - : VideoSourceDescriptor(VideoSourceType::StillImage) - , m_path(std::move(path)) - {} - -public: - // get the image source path - std::string path() const; - // set the image source path - void set_path(std::string path); - // Get the source image width. Its value is only loaded after `make_VideoSource()` is called. - // Otherwise, return 0. - size_t source_image_width() const{return m_source_image_width;} - // Get the source image height. Its value is only loaded after `make_VideoSource()` is called. - // Otherwise, return 0. - size_t source_image_height() const{return m_source_image_height;} - - virtual bool should_reload() const override{ return true; } - virtual bool operator==(const VideoSourceDescriptor& x) const override; - virtual std::string display_name() const override{ - return "Display Image"; - } - - virtual void run_post_select() override; - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual std::unique_ptr make_VideoSource(Logger& logger, Resolution resolution) const override; - - -private: - mutable SpinLock m_lock; - std::string m_path; - mutable size_t m_source_image_width = 0; - mutable size_t m_source_image_height = 0; -}; - - - -class VideoSource_StillImage : public VideoSource{ -public: - VideoSource_StillImage(const std::string& path, Resolution resolution); - - const std::string path() const{ - return m_path; - } - - virtual Resolution current_resolution() const override{ - return m_resolution; - } - virtual const std::vector& supported_resolutions() const override{ - return m_resolutions; - } - - virtual VideoSnapshot snapshot() override{ - return m_snapshot; - } - - virtual QWidget* make_display_QtWidget(QWidget* parent) override; - - const QImage& original_image() const { return m_original_image;} -private: - friend class VideoWidget_StillImage; - - std::string m_path; - QImage m_original_image; - VideoSnapshot m_snapshot; - Resolution m_resolution; - std::vector m_resolutions; -}; - - - - - -} -#endif +/* Video Source (Still Image) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoSource_StillImage_H +#define PokemonAutomation_VideoPipeline_VideoSource_StillImage_H + +#include +#include "CommonFramework/VideoPipeline/VideoSourceDescriptor.h" +#include "CommonFramework/VideoPipeline/VideoSource.h" + +namespace PokemonAutomation{ + + +class VideoSourceDescriptor_StillImage : public VideoSourceDescriptor{ +public: + VideoSourceDescriptor_StillImage() + : VideoSourceDescriptor(VideoSourceType::StillImage) + {} + VideoSourceDescriptor_StillImage(std::string path) + : VideoSourceDescriptor(VideoSourceType::StillImage) + , m_path(std::move(path)) + {} + +public: + // get the image source path + std::string path() const; + // set the image source path + void set_path(std::string path); + + virtual bool should_reload() const override{ return true; } + virtual bool operator==(const VideoSourceDescriptor& x) const override; + virtual std::string display_name() const override{ + return "Display Image"; + } + + virtual void run_post_select() override; + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual std::unique_ptr make_VideoSource(Logger& logger, Resolution resolution) const override; + + +private: + mutable SpinLock m_lock; + std::string m_path; +}; + + + +class VideoSource_StillImage : public VideoSource{ +public: + VideoSource_StillImage(const std::string& path, Resolution resolution); + + const std::string path() const{ + return m_path; + } + + virtual Resolution current_resolution() const override{ + return m_resolution; + } + virtual const std::vector& supported_resolutions() const override{ + return m_resolutions; + } + + virtual VideoSnapshot snapshot_latest_blocking() override{ + return m_snapshot; + } + virtual VideoSnapshot snapshot_recent_nonblocking(WallClock min_time) override{ + return m_snapshot; + } + + virtual QWidget* make_display_QtWidget(QWidget* parent) override; + + const QImage& original_image() const { return m_original_image;} +private: + friend class VideoWidget_StillImage; + + std::string m_path; + QImage m_original_image; + VideoSnapshot m_snapshot; + Resolution m_resolution; + std::vector m_resolutions; +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Windows/MainWindow.cpp b/SerialPrograms/Source/CommonFramework/Windows/MainWindow.cpp index fd61620534..9fcf1027df 100644 --- a/SerialPrograms/Source/CommonFramework/Windows/MainWindow.cpp +++ b/SerialPrograms/Source/CommonFramework/Windows/MainWindow.cpp @@ -20,15 +20,16 @@ #include "CommonFramework/Startup/NewVersionCheck.h" #include "CommonFramework/Options/ResolutionOption.h" #include "CommonFramework/Options/Environment/ThemeSelectorOption.h" +#include "CommonFramework/Windows/DpiScaler.h" #include "PanelLists.h" #include "WindowTracker.h" #include "ButtonDiagram.h" #include "MainWindow.h" -//#include -//using std::cout; -//using std::endl; +#include +using std::cout; +using std::endl; namespace PokemonAutomation{ @@ -46,6 +47,16 @@ MainWindow::MainWindow(QWidget* parent) GlobalSettings::instance().WINDOW_SIZE->WIDTH, GlobalSettings::instance().WINDOW_SIZE->HEIGHT ); + // move main window to desired position on startup + // auto const screen_geometry = QGuiApplication::primaryScreen()->availableGeometry(); + // uint32_t const screen_width = (uint32_t)screen_geometry.width(); + // uint32_t const screen_height = (uint32_t)screen_geometry.height(); + int32_t x_pos_main = GlobalSettings::instance().WINDOW_SIZE->X_POS; + int32_t y_pos_main = GlobalSettings::instance().WINDOW_SIZE->Y_POS; + int32_t move_x_main = move_x_within_screen_bounds(x_pos_main); + int32_t move_y_main = move_y_within_screen_bounds(y_pos_main); + move(move_x_main, move_y_main); + centralwidget = new QWidget(this); centralwidget->setObjectName(QString::fromUtf8("centralwidget")); setCentralWidget(centralwidget); @@ -203,12 +214,27 @@ MainWindow::MainWindow(QWidget* parent) buttons->addWidget(output); connect( output, &QPushButton::clicked, - this, [this](bool){ + this, [&](bool){ m_output_window->show(); m_output_window->raise(); // bring the window to front on macOS m_output_window->activateWindow(); // bring the window to front on Windows } ); + // get snapshot of the saved initial x/y position, since activating the window seems to change the window coordinates, + // which then causes initial x/y position to change, due to triggering moveEvent(). + int32_t x_pos_log = GlobalSettings::instance().LOG_WINDOW_SIZE->X_POS; + int32_t y_pos_log = GlobalSettings::instance().LOG_WINDOW_SIZE->Y_POS; + + if (GlobalSettings::instance().LOG_WINDOW_STARTUP){ // show the Output Window on startup + m_output_window->show(); + m_output_window->raise(); // bring the window to front on macOS + m_output_window->activateWindow(); // bring the window to front on Windows + } + + // move the output window to desired position on startup + int32_t move_x_log = move_x_within_screen_bounds(x_pos_log); + int32_t move_y_log = move_y_within_screen_bounds(y_pos_log); + m_output_window->move(move_x_log, move_y_log); } { QPushButton* settings = new QPushButton("Settings", support_box); @@ -234,6 +260,8 @@ MainWindow::MainWindow(QWidget* parent) GlobalSettings::instance().WINDOW_SIZE->WIDTH.add_listener(*this); GlobalSettings::instance().WINDOW_SIZE->HEIGHT.add_listener(*this); + GlobalSettings::instance().WINDOW_SIZE->X_POS.add_listener(*this); + GlobalSettings::instance().WINDOW_SIZE->Y_POS.add_listener(*this); SystemSleepController::instance().add_listener(*this); // cout << "Done constructing" << endl; } @@ -242,6 +270,24 @@ MainWindow::~MainWindow(){ SystemSleepController::instance().remove_listener(*this); GlobalSettings::instance().WINDOW_SIZE->WIDTH.remove_listener(*this); GlobalSettings::instance().WINDOW_SIZE->HEIGHT.remove_listener(*this); + GlobalSettings::instance().WINDOW_SIZE->X_POS.remove_listener(*this); + GlobalSettings::instance().WINDOW_SIZE->Y_POS.remove_listener(*this); +} + +int32_t move_x_within_screen_bounds(int32_t x_pos){ + auto static const screen_geometry = QGuiApplication::primaryScreen()->availableGeometry(); + uint32_t static const screen_width = (uint32_t)screen_geometry.width(); + // ensure move_x is greater than 0, but less than screen_width + return scale_dpi_width(std::max(0, std::min(x_pos, (int32_t)(screen_width*0.97)))); + +} + +int32_t move_y_within_screen_bounds(int32_t y_pos){ + auto static const screen_geometry = QGuiApplication::primaryScreen()->availableGeometry(); + uint32_t const screen_height = (uint32_t)screen_geometry.height(); + // ensure move_y is greater than 0, but less than screen_height + return scale_dpi_width(std::max(0, std::min(y_pos, (int32_t)(screen_height*0.97)))); + } @@ -256,6 +302,13 @@ void MainWindow::resizeEvent(QResizeEvent* event){ m_pending_resize = false; } +void MainWindow::moveEvent(QMoveEvent* event){ + m_pending_move = true; + GlobalSettings::instance().WINDOW_SIZE->X_POS.set(x()); + GlobalSettings::instance().WINDOW_SIZE->Y_POS.set(y()); + m_pending_move = false; +} + void MainWindow::close_panel() noexcept{ // cout << "close_panel(): enter: " << m_current_panel_widget << endl; // Must destroy the widget first since it references the instance. @@ -342,14 +395,25 @@ void MainWindow::on_idle(){ void MainWindow::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(this, [this]{ - if (!m_pending_resize){ - resize( - GlobalSettings::instance().WINDOW_SIZE->WIDTH, - GlobalSettings::instance().WINDOW_SIZE->HEIGHT - ); - } - }); + if (object == &GlobalSettings::instance().WINDOW_SIZE->WIDTH || object == &GlobalSettings::instance().WINDOW_SIZE->HEIGHT){ + QMetaObject::invokeMethod(this, [this]{ + if (!m_pending_resize){ + resize( + GlobalSettings::instance().WINDOW_SIZE->WIDTH, + GlobalSettings::instance().WINDOW_SIZE->HEIGHT + ); + } + }); + }else if (object == &GlobalSettings::instance().WINDOW_SIZE->X_POS || object == &GlobalSettings::instance().WINDOW_SIZE->Y_POS){ + QMetaObject::invokeMethod(this, [this]{ + if (!m_pending_move){ + move( + move_x_within_screen_bounds(GlobalSettings::instance().WINDOW_SIZE->X_POS), + move_y_within_screen_bounds(GlobalSettings::instance().WINDOW_SIZE->Y_POS) + ); + } + }); + } } void MainWindow::sleep_suppress_state_changed(SleepSuppress new_state){ QMetaObject::invokeMethod(this, [=, this]{ diff --git a/SerialPrograms/Source/CommonFramework/Windows/MainWindow.h b/SerialPrograms/Source/CommonFramework/Windows/MainWindow.h index 71f67cd466..cb08eea269 100644 --- a/SerialPrograms/Source/CommonFramework/Windows/MainWindow.h +++ b/SerialPrograms/Source/CommonFramework/Windows/MainWindow.h @@ -34,9 +34,11 @@ class MainWindow : MainWindow(QWidget* parent = nullptr); ~MainWindow(); + private: virtual void closeEvent(QCloseEvent* event) override; virtual void resizeEvent(QResizeEvent* event) override; + virtual void moveEvent(QMoveEvent* event) override; void close_panel() noexcept; @@ -85,10 +87,14 @@ class MainWindow : std::unique_ptr m_sleep_scope; bool m_pending_resize = false; + bool m_pending_move = false; bool m_panel_transition = false; }; - +// returns given X value, but bounded by 0 and screen_width +int32_t move_x_within_screen_bounds(int32_t x_pos); +// returns given y value, but bounded by 0 and screen_height +int32_t move_y_within_screen_bounds(int32_t y_pos); } diff --git a/SerialPrograms/Source/CommonTools/Async/InferenceRoutines.cpp b/SerialPrograms/Source/CommonTools/Async/InferenceRoutines.cpp index 5a4c579496..2c9d9a0a11 100644 --- a/SerialPrograms/Source/CommonTools/Async/InferenceRoutines.cpp +++ b/SerialPrograms/Source/CommonTools/Async/InferenceRoutines.cpp @@ -1,121 +1,121 @@ -/* Visual Inference Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/CancellableScope.h" -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "InferenceSession.h" -#include "InferenceRoutines.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -int wait_until( - VideoStream& stream, CancellableScope& scope, - WallClock deadline, - const std::vector& callbacks, - std::chrono::milliseconds default_video_period, - std::chrono::milliseconds default_audio_period -){ - CancellableHolder subscope(scope); - InferenceSession session( - subscope, stream, - callbacks, - default_video_period, default_audio_period - ); - - try{ - subscope.wait_until(deadline); - }catch (OperationCancelledException&){} - - subscope.throw_if_cancelled_with_exception(); - scope.throw_if_cancelled(); - - return session.triggered_index(); -} - - - - -int run_until( - VideoStream& stream, CancellableScope& scope, - std::function&& command, - const std::vector& callbacks, - std::chrono::milliseconds default_video_period, - std::chrono::milliseconds default_audio_period -){ - CancellableHolder subscope(scope); - InferenceSession session( - subscope, stream, - callbacks, - default_video_period, default_audio_period - ); - - try{ - command(subscope); - }catch (OperationCancelledException&){} - - subscope.throw_if_cancelled_with_exception(); - scope.throw_if_cancelled(); - - return session.triggered_index(); -} - - - -#if 1 -int run_until_with_time_limit( - ProgramEnvironment& env, VideoStream& stream, CancellableScope& scope, - WallClock deadline, - std::function&& command, - const std::vector& callbacks, - std::chrono::milliseconds default_video_period, - std::chrono::milliseconds default_audio_period -){ - CancellableHolder subscope(scope); - InferenceSession session( - subscope, stream, - callbacks, - default_video_period, default_audio_period - ); - - bool timed_out = false; - std::unique_ptr timer = env.realtime_dispatcher().dispatch([&]{ - subscope.wait_until(deadline); - timed_out = true; - subscope.cancel(nullptr); - }); - - try{ - if (command){ - command(subscope); - } -// subscope.wait_for_all_requests(); - }catch (OperationCancelledException&){} - - timer->wait_and_rethrow_exceptions(); - subscope.throw_if_cancelled_with_exception(); - scope.throw_if_cancelled(); - - return timed_out ? -2 : session.triggered_index(); -} -#endif - - - - - - -} - - - +/* Visual Inference Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/CancellableScope.h" +#include "Common/Cpp/Concurrency/AsyncDispatcher.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "InferenceSession.h" +#include "InferenceRoutines.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +int wait_until( + VideoStream& stream, CancellableScope& scope, + WallClock deadline, + const std::vector& callbacks, + std::chrono::milliseconds default_video_period, + std::chrono::milliseconds default_audio_period +){ + CancellableHolder subscope(scope); + InferenceSession session( + subscope, stream, + callbacks, + default_video_period, default_audio_period + ); + + try{ + subscope.wait_until(deadline); + }catch (OperationCancelledException&){} + + subscope.throw_if_cancelled_with_exception(); + scope.throw_if_cancelled(); + + return session.triggered_index(); +} + + + + +int run_until( + VideoStream& stream, CancellableScope& scope, + std::function&& command, + const std::vector& callbacks, + std::chrono::milliseconds default_video_period, + std::chrono::milliseconds default_audio_period +){ + CancellableHolder subscope(scope); + InferenceSession session( + subscope, stream, + callbacks, + default_video_period, default_audio_period + ); + + try{ + command(subscope); + }catch (OperationCancelledException&){} + + subscope.throw_if_cancelled_with_exception(); + scope.throw_if_cancelled(); + + return session.triggered_index(); +} + + + +#if 1 +int run_until_with_time_limit( + ProgramEnvironment& env, VideoStream& stream, CancellableScope& scope, + WallClock deadline, + std::function&& command, + const std::vector& callbacks, + std::chrono::milliseconds default_video_period, + std::chrono::milliseconds default_audio_period +){ + CancellableHolder subscope(scope); + InferenceSession session( + subscope, stream, + callbacks, + default_video_period, default_audio_period + ); + + bool timed_out = false; + std::unique_ptr timer = env.realtime_dispatcher().dispatch([&]{ + subscope.wait_until(deadline); + timed_out = true; + subscope.cancel(nullptr); + }); + + try{ + if (command){ + command(subscope); + } +// subscope.wait_for_all_requests(); + }catch (OperationCancelledException&){} + + timer->wait_and_rethrow_exceptions(); + subscope.throw_if_cancelled_with_exception(); + scope.throw_if_cancelled(); + + return timed_out ? -2 : session.triggered_index(); +} +#endif + + + + + + +} + + + diff --git a/SerialPrograms/Source/CommonTools/Async/InferenceRoutines.h b/SerialPrograms/Source/CommonTools/Async/InferenceRoutines.h index 07be1d9c62..d13cbfcb27 100644 --- a/SerialPrograms/Source/CommonTools/Async/InferenceRoutines.h +++ b/SerialPrograms/Source/CommonTools/Async/InferenceRoutines.h @@ -1,119 +1,119 @@ -/* Inference Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_InferenceRoutines_H -#define PokemonAutomation_CommonTools_InferenceRoutines_H - -#include -#include -#include -#include "Common/Cpp/Time.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/InferenceCallbacks/InferenceCallback.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - -class ProgramEnvironment; - - -// Wait until one of the "callbacks" are triggered or it times out. -// -// Returns: -// - The index of the trigger if that's what stopped it. -// - -1 if nothing triggered before timeout. -// -// Exceptions thrown in either the commands or the callbacks will stop -// everything and will be propagated out of this function. -int wait_until( - VideoStream& stream, CancellableScope& scope, - WallClock deadline, - const std::vector& callbacks, - std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), - std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) -); -inline int wait_until( - VideoStream& stream, CancellableScope& scope, - std::chrono::milliseconds timeout, - const std::vector& callbacks, - std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), - std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) -){ - return wait_until( - stream, scope, - current_time() + timeout, - callbacks, - default_video_period, default_audio_period - ); -} - - -// Run the specified "command" until either it finishes or one of the -// "callbacks" are triggered. -// -// Returns: -// - The index of the trigger if that's what stopped it. -// - -1 if nothing triggered before command finished. -// -// Exceptions thrown in either the commands or the callbacks will stop -// everything and will be propagated out of this function. -int run_until( - VideoStream& stream, CancellableScope& scope, - std::function&& command, - const std::vector& callbacks, - std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), - std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) -); -template -int run_until( - VideoStream& stream, ControllerContext& context, - std::function&& command, - const std::vector& callbacks, - std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), - std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) -){ - return run_until( - stream, context, - [&](CancellableScope& scope){ - ControllerContext subcontext(scope, context); - command(subcontext); - subcontext.wait_for_all_requests(); - }, - callbacks, - default_video_period, - default_audio_period - ); -} - - -#if 1 -// Same as "run_until()", but will cancel the commands and return if a timeout -// is reached. -// -// Returns: -// - The index of the trigger if that's what stopped it. -// - -1 if nothing triggered before command finished. -// - -2 if timed out. Nothing triggered, and command did not finish. -// -int run_until_with_time_limit( - ProgramEnvironment& env, VideoStream& stream, CancellableScope& scope, - WallClock deadline, - std::function&& command, - const std::vector& callbacks, - std::chrono::milliseconds default_video_period, - std::chrono::milliseconds default_audio_period -); -#endif - - - - - -} -#endif +/* Inference Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_InferenceRoutines_H +#define PokemonAutomation_CommonTools_InferenceRoutines_H + +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/InferenceCallbacks/InferenceCallback.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + +class ProgramEnvironment; + + +// Wait until one of the "callbacks" are triggered or it times out. +// +// Returns: +// - The index of the trigger if that's what stopped it. +// - -1 if nothing triggered before timeout. +// +// Exceptions thrown in either the commands or the callbacks will stop +// everything and will be propagated out of this function. +int wait_until( + VideoStream& stream, CancellableScope& scope, + WallClock deadline, + const std::vector& callbacks, + std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), + std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) +); +inline int wait_until( + VideoStream& stream, CancellableScope& scope, + std::chrono::milliseconds timeout, + const std::vector& callbacks, + std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), + std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) +){ + return wait_until( + stream, scope, + current_time() + timeout, + callbacks, + default_video_period, default_audio_period + ); +} + + +// Run the specified "command" until either it finishes or one of the +// "callbacks" are triggered. +// +// Returns: +// - The index of the trigger if that's what stopped it. +// - -1 if nothing triggered before command finished. +// +// Exceptions thrown in either the commands or the callbacks will stop +// everything and will be propagated out of this function. +int run_until( + VideoStream& stream, CancellableScope& scope, + std::function&& command, + const std::vector& callbacks, + std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), + std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) +); +template +int run_until( + VideoStream& stream, ControllerContext& context, + std::function&& command, + const std::vector& callbacks, + std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), + std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) +){ + return run_until( + stream, context, + [&](CancellableScope& scope){ + ControllerContext subcontext(scope, context); + command(subcontext); + subcontext.wait_for_all_requests(); + }, + callbacks, + default_video_period, + default_audio_period + ); +} + + +#if 1 +// Same as "run_until()", but will cancel the commands and return if a timeout +// is reached. +// +// Returns: +// - The index of the trigger if that's what stopped it. +// - -1 if nothing triggered before command finished. +// - -2 if timed out. Nothing triggered, and command did not finish. +// +int run_until_with_time_limit( + ProgramEnvironment& env, VideoStream& stream, CancellableScope& scope, + WallClock deadline, + std::function&& command, + const std::vector& callbacks, + std::chrono::milliseconds default_video_period, + std::chrono::milliseconds default_audio_period +); +#endif + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Async/InferenceSession.cpp b/SerialPrograms/Source/CommonTools/Async/InferenceSession.cpp index 08bd9cc774..d71afe517b 100644 --- a/SerialPrograms/Source/CommonTools/Async/InferenceSession.cpp +++ b/SerialPrograms/Source/CommonTools/Async/InferenceSession.cpp @@ -1,105 +1,105 @@ -/* Inference Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/InferenceCallbacks/AudioInferenceCallback.h" -#include "CommonTools/InferencePivots/VisualInferencePivot.h" -#include "CommonTools/InferencePivots/AudioInferencePivot.h" -#include "InferenceSession.h" - -namespace PokemonAutomation{ - - -InferenceSession::InferenceSession( - Cancellable& scope, VideoStream& stream, - const std::vector& callbacks, - std::chrono::milliseconds default_video_period, - std::chrono::milliseconds default_audio_period -) - : m_stream(stream) - , m_overlays(stream.overlay()) - , m_triggered(nullptr) -{ - try{ - for (size_t c = 0; c < callbacks.size(); c++){ - const PeriodicInferenceCallback& callback = callbacks[c]; - if (callback.callback == nullptr){ - continue; - } - if (!m_map.emplace(callback.callback, c).second){ - throw InternalProgramError(&stream.logger(), PA_CURRENT_FUNCTION, "Attempted to add the same callback twice."); - } - switch (callback.callback->type()){ - case InferenceType::VISUAL:{ - VisualInferenceCallback& visual_callback = static_cast(*callback.callback); - stream.video_inference_pivot().add_callback( - scope, &m_triggered, - visual_callback, - callback.period > std::chrono::milliseconds(0) ? callback.period : default_video_period - ); - visual_callback.make_overlays(m_overlays); - break; - } - case InferenceType::AUDIO: - stream.audio_inference_pivot().add_callback( - scope, &m_triggered, - static_cast(*callback.callback), - callback.period > std::chrono::milliseconds(0) ? callback.period : default_audio_period - ); - break; - } - } - }catch (...){ - clear(); - throw; - } -} -InferenceSession::~InferenceSession(){ - clear(); -} - - -InferenceCallback* InferenceSession::triggered_ptr() const{ - return m_triggered.load(std::memory_order_acquire); -} -int InferenceSession::triggered_index() const{ - auto iter = m_map.find(m_triggered.load(std::memory_order_acquire)); - if (iter != m_map.end()){ - return (int)iter->second; - } - return -1; -} - - -void InferenceSession::clear() noexcept{ - const double DIVIDER = (double)(std::chrono::milliseconds(1) / std::chrono::microseconds(1)); - const char* UNITS = " ms"; - for (auto& item : m_map){ - switch (item.first->type()){ - case InferenceType::VISUAL:{ - StatAccumulatorI32 stats = m_stream.video_inference_pivot().remove_callback(static_cast(*item.first)); - try{ - stats.log(m_stream.logger(), item.first->label(), UNITS, DIVIDER); - }catch (...){} - break; - } - case InferenceType::AUDIO:{ - StatAccumulatorI32 stats = m_stream.audio_inference_pivot().remove_callback(static_cast(*item.first)); - try{ - stats.log(m_stream.logger(), item.first->label(), UNITS, DIVIDER); - }catch (...){} - break; - } - } - } -} - - - - -} +/* Inference Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/InferenceCallbacks/AudioInferenceCallback.h" +#include "CommonTools/InferencePivots/VisualInferencePivot.h" +#include "CommonTools/InferencePivots/AudioInferencePivot.h" +#include "InferenceSession.h" + +namespace PokemonAutomation{ + + +InferenceSession::InferenceSession( + Cancellable& scope, VideoStream& stream, + const std::vector& callbacks, + std::chrono::milliseconds default_video_period, + std::chrono::milliseconds default_audio_period +) + : m_stream(stream) + , m_overlays(stream.overlay()) + , m_triggered(nullptr) +{ + try{ + for (size_t c = 0; c < callbacks.size(); c++){ + const PeriodicInferenceCallback& callback = callbacks[c]; + if (callback.callback == nullptr){ + continue; + } + if (!m_map.emplace(callback.callback, c).second){ + throw InternalProgramError(&stream.logger(), PA_CURRENT_FUNCTION, "Attempted to add the same callback twice."); + } + switch (callback.callback->type()){ + case InferenceType::VISUAL:{ + VisualInferenceCallback& visual_callback = static_cast(*callback.callback); + stream.video_inference_pivot().add_callback( + scope, &m_triggered, + visual_callback, + callback.period > std::chrono::milliseconds(0) ? callback.period : default_video_period + ); + visual_callback.make_overlays(m_overlays); + break; + } + case InferenceType::AUDIO: + stream.audio_inference_pivot().add_callback( + scope, &m_triggered, + static_cast(*callback.callback), + callback.period > std::chrono::milliseconds(0) ? callback.period : default_audio_period + ); + break; + } + } + }catch (...){ + clear(); + throw; + } +} +InferenceSession::~InferenceSession(){ + clear(); +} + + +InferenceCallback* InferenceSession::triggered_ptr() const{ + return m_triggered.load(std::memory_order_acquire); +} +int InferenceSession::triggered_index() const{ + auto iter = m_map.find(m_triggered.load(std::memory_order_acquire)); + if (iter != m_map.end()){ + return (int)iter->second; + } + return -1; +} + + +void InferenceSession::clear() noexcept{ + const double DIVIDER = (double)(std::chrono::milliseconds(1) / std::chrono::microseconds(1)); + const char* UNITS = " ms"; + for (auto& item : m_map){ + switch (item.first->type()){ + case InferenceType::VISUAL:{ + StatAccumulatorI32 stats = m_stream.video_inference_pivot().remove_callback(static_cast(*item.first)); + try{ + stats.log(m_stream.logger(), item.first->label(), UNITS, DIVIDER); + }catch (...){} + break; + } + case InferenceType::AUDIO:{ + StatAccumulatorI32 stats = m_stream.audio_inference_pivot().remove_callback(static_cast(*item.first)); + try{ + stats.log(m_stream.logger(), item.first->label(), UNITS, DIVIDER); + }catch (...){} + break; + } + } + } +} + + + + +} diff --git a/SerialPrograms/Source/CommonTools/Async/InferenceSession.h b/SerialPrograms/Source/CommonTools/Async/InferenceSession.h index 13946d9fef..5b512953b3 100644 --- a/SerialPrograms/Source/CommonTools/Async/InferenceSession.h +++ b/SerialPrograms/Source/CommonTools/Async/InferenceSession.h @@ -1,71 +1,71 @@ -/* Inference Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_InferenceSession_H -#define PokemonAutomation_CommonTools_InferenceSession_H - -#include -#include -#include -#include -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/InferenceCallbacks/InferenceCallback.h" - -namespace PokemonAutomation{ - -class Cancellable; -class VideoStream; - - - -// -// On construction, all the callbacks are attached to inference threads and -// begin running at their specified period. -// -// Upon destruction, all callbacks are removed from the inference threads and -// stop running. -// -// When a callback returns true or throws an exception, "scope.cancel()" will -// be called. -// -// "triggered_ptr()/triggered_index()" gives the first callback that -// returned true. If nothing has returned true, it is null or -1 respectively. -// -// Note that the callbacks will continue running even if one of them has -// returned true. So it is expected that the object will be destructed soon -// after "scope.cancel()" is called. -// -class InferenceSession{ -public: - InferenceSession( - Cancellable& scope, VideoStream& stream, - const std::vector& callbacks, - std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), - std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) - ); - ~InferenceSession(); - - InferenceCallback* triggered_ptr() const; - int triggered_index() const; - - -private: - void clear() noexcept; - - -private: - VideoStream& m_stream; - VideoOverlaySet m_overlays; - std::map m_map; - std::atomic m_triggered; -}; - - - - - -} -#endif +/* Inference Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_InferenceSession_H +#define PokemonAutomation_CommonTools_InferenceSession_H + +#include +#include +#include +#include +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/InferenceCallbacks/InferenceCallback.h" + +namespace PokemonAutomation{ + +class Cancellable; +class VideoStream; + + + +// +// On construction, all the callbacks are attached to inference threads and +// begin running at their specified period. +// +// Upon destruction, all callbacks are removed from the inference threads and +// stop running. +// +// When a callback returns true or throws an exception, "scope.cancel()" will +// be called. +// +// "triggered_ptr()/triggered_index()" gives the first callback that +// returned true. If nothing has returned true, it is null or -1 respectively. +// +// Note that the callbacks will continue running even if one of them has +// returned true. So it is expected that the object will be destructed soon +// after "scope.cancel()" is called. +// +class InferenceSession{ +public: + InferenceSession( + Cancellable& scope, VideoStream& stream, + const std::vector& callbacks, + std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), + std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) + ); + ~InferenceSession(); + + InferenceCallback* triggered_ptr() const; + int triggered_index() const; + + +private: + void clear() noexcept; + + +private: + VideoStream& m_stream; + VideoOverlaySet m_overlays; + std::map m_map; + std::atomic m_triggered; +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Async/InterruptableCommands.h b/SerialPrograms/Source/CommonTools/Async/InterruptableCommands.h index be6e6cd9cf..892be246af 100644 --- a/SerialPrograms/Source/CommonTools/Async/InterruptableCommands.h +++ b/SerialPrograms/Source/CommonTools/Async/InterruptableCommands.h @@ -1,87 +1,87 @@ -/* Interruptable Commands - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_InterruptableCommands_H -#define PokemonAutomation_CommonTools_InterruptableCommands_H - -#include -#include -#include "Common/Cpp/CancellableScope.h" -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" - - -namespace PokemonAutomation{ - -class Logger; -class ProgramEnvironment; - - -template -class AsyncCommandSession final : private Cancellable{ - using ControllerContextType = typename ControllerType::ContextType; - -public: - AsyncCommandSession( - CancellableScope& scope, Logger& logger, AsyncDispatcher& dispatcher, - ControllerType& controller - ); - virtual ~AsyncCommandSession(); - - bool command_is_running(); - - // Stop the entire session. If an exception was thrown from the command - // thread, it will be rethrown here. - // - // It is important that exceptions in the command thread be passed up - // since it is how cancellations are implemented. Therefore you MUST - // call this prior to all natural* destruction points. - // - // *Do not call this during a stack-unwind as it's UB to throw while - // unwinding. In such cases, the exception from the command thread will be - // silently dropped in favor of the exception that's causing the current - // unwind. - void stop_session_and_rethrow(); - - -public: - // Stop the currently running command. - void stop_command(); - - // Dispath the following lambda. If something is already running, it will be - // stopped and replaced with this one. - void dispatch(std::function&& lambda); - - // Wait for currently running command to finish. - void wait(); - - -private: - virtual bool cancel(std::exception_ptr exception) noexcept override; - void thread_loop(); - - -private: - struct CommandSet; - - Logger& m_logger; - ControllerType& m_controller; - std::unique_ptr m_current; - - std::mutex m_lock; - std::condition_variable m_cv; - std::unique_ptr m_thread; - - LifetimeSanitizer m_sanitizer; -}; - - - - - - - -} -#endif +/* Interruptable Commands + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_InterruptableCommands_H +#define PokemonAutomation_CommonTools_InterruptableCommands_H + +#include +#include +#include "Common/Cpp/CancellableScope.h" +#include "Common/Cpp/Concurrency/AsyncDispatcher.h" + + +namespace PokemonAutomation{ + +class Logger; +class ProgramEnvironment; + + +template +class AsyncCommandSession final : private Cancellable{ + using ControllerContextType = typename ControllerType::ContextType; + +public: + AsyncCommandSession( + CancellableScope& scope, Logger& logger, AsyncDispatcher& dispatcher, + ControllerType& controller + ); + virtual ~AsyncCommandSession(); + + bool command_is_running(); + + // Stop the entire session. If an exception was thrown from the command + // thread, it will be rethrown here. + // + // It is important that exceptions in the command thread be passed up + // since it is how cancellations are implemented. Therefore you MUST + // call this prior to all natural* destruction points. + // + // *Do not call this during a stack-unwind as it's UB to throw while + // unwinding. In such cases, the exception from the command thread will be + // silently dropped in favor of the exception that's causing the current + // unwind. + void stop_session_and_rethrow(); + + +public: + // Stop the currently running command. + void stop_command(); + + // Dispath the following lambda. If something is already running, it will be + // stopped and replaced with this one. + void dispatch(std::function&& lambda); + + // Wait for currently running command to finish. + void wait(); + + +private: + virtual bool cancel(std::exception_ptr exception) noexcept override; + void thread_loop(); + + +private: + struct CommandSet; + + Logger& m_logger; + ControllerType& m_controller; + std::unique_ptr m_current; + + std::mutex m_lock; + std::condition_variable m_cv; + std::unique_ptr m_thread; + + LifetimeSanitizer m_sanitizer; +}; + + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Async/InterruptableCommands.tpp b/SerialPrograms/Source/CommonTools/Async/InterruptableCommands.tpp index 95632ecad6..c495909b76 100644 --- a/SerialPrograms/Source/CommonTools/Async/InterruptableCommands.tpp +++ b/SerialPrograms/Source/CommonTools/Async/InterruptableCommands.tpp @@ -1,205 +1,205 @@ -/* Async Command Set - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "InterruptableCommands.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -template -struct AsyncCommandSession::CommandSet{ - CommandSet( - CancellableScope& parent, ControllerType& controller, - std::function&& lambda - ); - CancellableHolder scope; - ControllerContextType context; - std::function commands; -}; - - - -template -AsyncCommandSession::CommandSet::CommandSet( - CancellableScope& parent, ControllerType& controller, - std::function&& lambda -) - : scope(parent) - , context(scope, controller) - , commands(std::move(lambda)) -{} - - - -template -AsyncCommandSession::AsyncCommandSession( - CancellableScope& scope, Logger& logger, AsyncDispatcher& dispatcher, - ControllerType& controller -) - : m_logger(logger) - , m_controller(controller) -{ - // Attach first. If scope is already cancelled, we exit here with nothing - // to clean up. - attach(scope); - - // Now start the thread. Destructor is guaranteed to run if this succeeds. - m_thread = dispatcher.dispatch([this]{ thread_loop(); }); -} -template -AsyncCommandSession::~AsyncCommandSession(){ -// cout << "~AsyncCommandSession()" << endl; - if (!cancelled() && std::uncaught_exceptions() == 0){ - m_logger.log("AsyncCommandSession::stop_session() not called before normal destruction.", COLOR_RED); - } - detach(); - AsyncCommandSession::cancel(nullptr); - - // Join the thread. - m_thread.reset(); -} - -template -bool AsyncCommandSession::command_is_running(){ - auto scope_check = m_sanitizer.check_scope(); - std::lock_guard lg(m_lock); - return m_current != nullptr; -} - -template -void AsyncCommandSession::stop_command(){ - auto scope_check = m_sanitizer.check_scope(); - - std::unique_lock lg(m_lock); - if (cancelled()){ - return; - } - - if (m_current){ - // Already a task running. Cancel it. - m_current->context.cancel_now(); - m_cv.wait(lg, [this]{ - return cancelled() || m_current == nullptr; - }); - } -} -template -void AsyncCommandSession::dispatch(std::function&& lambda){ - auto scope_check = m_sanitizer.check_scope(); - - // Construct the CommandSet outside the lock. - // If a cancellation comes from above while we are holding the lock, - // it will deadlock. - std::unique_ptr pending(new CommandSet( - *this->scope(), - m_controller, std::move(lambda) - )); - - std::unique_lock lg(m_lock); - if (cancelled()){ - return; - } - - if (m_current){ - // Already a task running. Cancel it. - m_current->context.cancel_lazy(); - m_cv.wait(lg, [this]{ - return cancelled() || m_current == nullptr; - }); - if (cancelled()){ - return; - } - } - - m_current = std::move(pending); - m_cv.notify_all(); -} - - -template -bool AsyncCommandSession::cancel(std::exception_ptr exception) noexcept{ -// cout << "AsyncCommandSession::cancel()" << endl; - if (Cancellable::cancel(exception)){ - return true; - } - std::lock_guard lg(m_lock); - if (m_current != nullptr){ - m_current->context.cancel(std::move(exception)); - } - m_cv.notify_all(); - return false; -} -template -void AsyncCommandSession::thread_loop(){ - while (true){ - CommandSet* current; - { - std::unique_lock lg(m_lock); - m_cv.wait(lg, [this]{ - return cancelled() || m_current != nullptr; - }); - if (cancelled()){ - break; - } - current = m_current.get(); - } - try{ - current->commands(current->context); - current->context.wait_for_all_requests(); - }catch (OperationCancelledException&){} - - // Destroy the CommandSet outside the lock. - // If a cancellation comes from above while we are holding the lock, - // it will deadlock. - std::unique_ptr done; - { - std::lock_guard lg(m_lock); - done = std::move(m_current); - m_cv.notify_all(); - } - } - - auto scope_check = m_sanitizer.check_scope(); -} - - - -#if 0 -template -void AsyncCommandSession::stop_commands(){ - std::lock_guard lg(m_lock); - if (m_current){ - m_current->context.cancel_now(); - } -} -#endif -template -void AsyncCommandSession::wait(){ - std::unique_lock lg(m_lock); -// cout << "wait() - start" << endl; - m_cv.wait(lg, [this]{ - return m_current == nullptr; - }); -// cout << "wait() - done" << endl; -} -template -void AsyncCommandSession::stop_session_and_rethrow(){ - cancel(nullptr); - m_thread->wait_and_rethrow_exceptions(); - throw_if_cancelled_with_exception(); -} - - - - -} - +/* Async Command Set + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "InterruptableCommands.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +template +struct AsyncCommandSession::CommandSet{ + CommandSet( + CancellableScope& parent, ControllerType& controller, + std::function&& lambda + ); + CancellableHolder scope; + ControllerContextType context; + std::function commands; +}; + + + +template +AsyncCommandSession::CommandSet::CommandSet( + CancellableScope& parent, ControllerType& controller, + std::function&& lambda +) + : scope(parent) + , context(scope, controller) + , commands(std::move(lambda)) +{} + + + +template +AsyncCommandSession::AsyncCommandSession( + CancellableScope& scope, Logger& logger, AsyncDispatcher& dispatcher, + ControllerType& controller +) + : m_logger(logger) + , m_controller(controller) +{ + // Attach first. If scope is already cancelled, we exit here with nothing + // to clean up. + attach(scope); + + // Now start the thread. Destructor is guaranteed to run if this succeeds. + m_thread = dispatcher.dispatch([this]{ thread_loop(); }); +} +template +AsyncCommandSession::~AsyncCommandSession(){ +// cout << "~AsyncCommandSession()" << endl; + if (!cancelled() && std::uncaught_exceptions() == 0){ + m_logger.log("AsyncCommandSession::stop_session() not called before normal destruction.", COLOR_RED); + } + detach(); + AsyncCommandSession::cancel(nullptr); + + // Join the thread. + m_thread.reset(); +} + +template +bool AsyncCommandSession::command_is_running(){ + auto scope_check = m_sanitizer.check_scope(); + std::lock_guard lg(m_lock); + return m_current != nullptr; +} + +template +void AsyncCommandSession::stop_command(){ + auto scope_check = m_sanitizer.check_scope(); + + std::unique_lock lg(m_lock); + if (cancelled()){ + return; + } + + if (m_current){ + // Already a task running. Cancel it. + m_current->context.cancel_now(); + m_cv.wait(lg, [this]{ + return cancelled() || m_current == nullptr; + }); + } +} +template +void AsyncCommandSession::dispatch(std::function&& lambda){ + auto scope_check = m_sanitizer.check_scope(); + + // Construct the CommandSet outside the lock. + // If a cancellation comes from above while we are holding the lock, + // it will deadlock. + std::unique_ptr pending(new CommandSet( + *this->scope(), + m_controller, std::move(lambda) + )); + + std::unique_lock lg(m_lock); + if (cancelled()){ + return; + } + + if (m_current){ + // Already a task running. Cancel it. + m_current->context.cancel_lazy(); + m_cv.wait(lg, [this]{ + return cancelled() || m_current == nullptr; + }); + if (cancelled()){ + return; + } + } + + m_current = std::move(pending); + m_cv.notify_all(); +} + + +template +bool AsyncCommandSession::cancel(std::exception_ptr exception) noexcept{ +// cout << "AsyncCommandSession::cancel()" << endl; + if (Cancellable::cancel(exception)){ + return true; + } + std::lock_guard lg(m_lock); + if (m_current != nullptr){ + m_current->context.cancel(std::move(exception)); + } + m_cv.notify_all(); + return false; +} +template +void AsyncCommandSession::thread_loop(){ + while (true){ + CommandSet* current; + { + std::unique_lock lg(m_lock); + m_cv.wait(lg, [this]{ + return cancelled() || m_current != nullptr; + }); + if (cancelled()){ + break; + } + current = m_current.get(); + } + try{ + current->commands(current->context); + current->context.wait_for_all_requests(); + }catch (OperationCancelledException&){} + + // Destroy the CommandSet outside the lock. + // If a cancellation comes from above while we are holding the lock, + // it will deadlock. + std::unique_ptr done; + { + std::lock_guard lg(m_lock); + done = std::move(m_current); + m_cv.notify_all(); + } + } + + auto scope_check = m_sanitizer.check_scope(); +} + + + +#if 0 +template +void AsyncCommandSession::stop_commands(){ + std::lock_guard lg(m_lock); + if (m_current){ + m_current->context.cancel_now(); + } +} +#endif +template +void AsyncCommandSession::wait(){ + std::unique_lock lg(m_lock); +// cout << "wait() - start" << endl; + m_cv.wait(lg, [this]{ + return m_current == nullptr; + }); +// cout << "wait() - done" << endl; +} +template +void AsyncCommandSession::stop_session_and_rethrow(){ + cancel(nullptr); + m_thread->wait_and_rethrow_exceptions(); + throw_if_cancelled_with_exception(); +} + + + + +} + diff --git a/SerialPrograms/Source/CommonTools/Async/SuperControlSession.h b/SerialPrograms/Source/CommonTools/Async/SuperControlSession.h index fa2ec02867..62d5ec99e3 100644 --- a/SerialPrograms/Source/CommonTools/Async/SuperControlSession.h +++ b/SerialPrograms/Source/CommonTools/Async/SuperControlSession.h @@ -1,106 +1,106 @@ -/* Super-Control Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_SuperControlSession_H -#define PokemonAutomation_CommonTools_SuperControlSession_H - -#include -#include -#include -#include -#include -#include "Common/Cpp/Time.h" - -namespace PokemonAutomation{ - -class ProgramEnvironment; -class VideoStream; -template class AsyncCommandSession; -class AudioInferenceCallback; -class VisualInferenceCallback; - - - -// -// Although this class asynchronously runs inference and commands, none of the -// public methods are actually thread-safe with each other. -// -// You must fully construct the class (register all the callbacks and actions) -// prior to calling "run_session()". -// -// "run_session()" will run the state machine which will periodically call -// "run_state()" at the user-specified period. -// -// Inside the child class' "run_state()" function, it will call "run_state_action()" -// with a registered enum/action. -// - -template -class SuperControlSession{ - using ControllerContextType = typename ControllerType::ContextType; - -public: - ~SuperControlSession(); - void run_session(); - -protected: - // Construction - SuperControlSession( - ProgramEnvironment& env, VideoStream& stream, ControllerContextType& context, - std::chrono::milliseconds state_period = std::chrono::milliseconds(100), - std::chrono::milliseconds visual_period = std::chrono::milliseconds(50), - std::chrono::milliseconds audio_period = std::chrono::milliseconds(20) - ); - - void operator+=(VisualInferenceCallback& callback); - void operator+=(AudioInferenceCallback& callback); - - void register_state_command(size_t state, std::function&& action); - - -protected: - WallClock start_time() const{ return m_start_time; } - - size_t last_state() const{ return m_last_state; } - WallClock last_state_change() const{ return m_last_state_change; } - - // Return true if we should stop. - virtual bool run_state(AsyncCommandSession& commands, WallClock timestamp) = 0; - - // Run the specified state. This is debounced such that the registered - // command will only run if we're not already in the state and the command - // session is still running. - bool run_state_action(size_t state); - - -protected: - ProgramEnvironment& m_env; - VideoStream& m_stream; - ControllerContextType& m_context; - std::unique_ptr> m_active_command; - -private: - const std::chrono::milliseconds m_state_period; - const std::chrono::milliseconds m_visual_period; - const std::chrono::milliseconds m_audio_period; - - std::vector m_visual_callbacks; - std::vector m_audio_callbacks; - - // These are actions - std::map> m_state_actions; - -private: - // Run-time state. - WallClock m_start_time; - size_t m_last_state; - WallClock m_last_state_change; -}; - - - -} -#endif +/* Super-Control Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_SuperControlSession_H +#define PokemonAutomation_CommonTools_SuperControlSession_H + +#include +#include +#include +#include +#include +#include "Common/Cpp/Time.h" + +namespace PokemonAutomation{ + +class ProgramEnvironment; +class VideoStream; +template class AsyncCommandSession; +class AudioInferenceCallback; +class VisualInferenceCallback; + + + +// +// Although this class asynchronously runs inference and commands, none of the +// public methods are actually thread-safe with each other. +// +// You must fully construct the class (register all the callbacks and actions) +// prior to calling "run_session()". +// +// "run_session()" will run the state machine which will periodically call +// "run_state()" at the user-specified period. +// +// Inside the child class' "run_state()" function, it will call "run_state_action()" +// with a registered enum/action. +// + +template +class SuperControlSession{ + using ControllerContextType = typename ControllerType::ContextType; + +public: + ~SuperControlSession(); + void run_session(); + +protected: + // Construction + SuperControlSession( + ProgramEnvironment& env, VideoStream& stream, ControllerContextType& context, + std::chrono::milliseconds state_period = std::chrono::milliseconds(100), + std::chrono::milliseconds visual_period = std::chrono::milliseconds(50), + std::chrono::milliseconds audio_period = std::chrono::milliseconds(20) + ); + + void operator+=(VisualInferenceCallback& callback); + void operator+=(AudioInferenceCallback& callback); + + void register_state_command(size_t state, std::function&& action); + + +protected: + WallClock start_time() const{ return m_start_time; } + + size_t last_state() const{ return m_last_state; } + WallClock last_state_change() const{ return m_last_state_change; } + + // Return true if we should stop. + virtual bool run_state(AsyncCommandSession& commands, WallClock timestamp) = 0; + + // Run the specified state. This is debounced such that the registered + // command will only run if we're not already in the state and the command + // session is still running. + bool run_state_action(size_t state); + + +protected: + ProgramEnvironment& m_env; + VideoStream& m_stream; + ControllerContextType& m_context; + std::unique_ptr> m_active_command; + +private: + const std::chrono::milliseconds m_state_period; + const std::chrono::milliseconds m_visual_period; + const std::chrono::milliseconds m_audio_period; + + std::vector m_visual_callbacks; + std::vector m_audio_callbacks; + + // These are actions + std::map> m_state_actions; + +private: + // Run-time state. + WallClock m_start_time; + size_t m_last_state; + WallClock m_last_state_change; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Async/SuperControlSession.tpp b/SerialPrograms/Source/CommonTools/Async/SuperControlSession.tpp index b5713e4bc4..717a559ddb 100644 --- a/SerialPrograms/Source/CommonTools/Async/SuperControlSession.tpp +++ b/SerialPrograms/Source/CommonTools/Async/SuperControlSession.tpp @@ -1,137 +1,137 @@ -/* Super-Control Session - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/InferenceCallbacks/AudioInferenceCallback.h" -#include "InterruptableCommands.h" -#include "InferenceSession.h" -#include "SuperControlSession.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -template -SuperControlSession::~SuperControlSession() = default; - -template -SuperControlSession::SuperControlSession( - ProgramEnvironment& env, VideoStream& stream, ControllerContextType& context, - std::chrono::milliseconds state_period, - std::chrono::milliseconds visual_period, - std::chrono::milliseconds audio_period -) - : m_env(env) - , m_stream(stream) - , m_context(context) - , m_state_period(state_period) - , m_visual_period(visual_period) - , m_audio_period(audio_period) - , m_last_state(0) - , m_last_state_change(current_time()) -{} - -template -void SuperControlSession::operator+=(VisualInferenceCallback& callback){ - m_visual_callbacks.emplace_back(&callback); -} -template -void SuperControlSession::operator+=(AudioInferenceCallback& callback){ - m_audio_callbacks.emplace_back(&callback); -} -template -void SuperControlSession::register_state_command(size_t state, std::function&& action){ - auto iter = m_state_actions.find(state); - if (iter != m_state_actions.end()){ - throw InternalProgramError(&m_stream.logger(), PA_CURRENT_FUNCTION, "Duplicate State Enum: " + std::to_string(state)); - } - m_state_actions.emplace(state, std::move(action)); -} -template -bool SuperControlSession::run_state_action(size_t state){ - auto iter = m_state_actions.find(state); - if (iter == m_state_actions.end()){ - throw InternalProgramError(&m_stream.logger(), PA_CURRENT_FUNCTION, "Unknown State Enum: " + std::to_string(state)); - } - - // Session isn't even active. - if (!m_active_command){ - return false; - } - - // If we're already in the state and a command is running, don't overwrite it. - if (state == m_last_state && m_active_command->command_is_running()){ - return false; - } - - // Run the state. - m_last_state = state; - m_last_state_change = current_time(); - return iter->second(); -} - -template -void SuperControlSession::run_session(){ - m_start_time = current_time(); - - m_active_command.reset( - new AsyncCommandSession( - m_context, m_env.logger(), m_env.realtime_dispatcher(), - m_context.controller() - ) - ); - - std::vector callbacks; - for (VisualInferenceCallback* callback : m_visual_callbacks){ - callbacks.emplace_back(PeriodicInferenceCallback{*callback, m_visual_period}); - } - for (AudioInferenceCallback* callback : m_audio_callbacks){ - callbacks.emplace_back(PeriodicInferenceCallback{*callback, m_audio_period}); - } - InferenceSession session( - m_context, m_stream, - callbacks, - m_visual_period - ); - - WallClock now = current_time(); - WallClock next_tick = now + m_state_period; - - m_last_state = 0; - - while (true){ - // Check stop conditions. - m_context.throw_if_cancelled(); - - if (run_state(*m_active_command, current_time())){ - break; - } - - now = current_time(); - if (now >= next_tick){ - next_tick = now + m_state_period; - }else{ - m_context.wait_until(next_tick); - next_tick += m_state_period; - } - } - m_context.throw_if_cancelled(); - - m_active_command->stop_session_and_rethrow(); -} - - - - - - -} +/* Super-Control Session + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/InferenceCallbacks/AudioInferenceCallback.h" +#include "InterruptableCommands.h" +#include "InferenceSession.h" +#include "SuperControlSession.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +template +SuperControlSession::~SuperControlSession() = default; + +template +SuperControlSession::SuperControlSession( + ProgramEnvironment& env, VideoStream& stream, ControllerContextType& context, + std::chrono::milliseconds state_period, + std::chrono::milliseconds visual_period, + std::chrono::milliseconds audio_period +) + : m_env(env) + , m_stream(stream) + , m_context(context) + , m_state_period(state_period) + , m_visual_period(visual_period) + , m_audio_period(audio_period) + , m_last_state(0) + , m_last_state_change(current_time()) +{} + +template +void SuperControlSession::operator+=(VisualInferenceCallback& callback){ + m_visual_callbacks.emplace_back(&callback); +} +template +void SuperControlSession::operator+=(AudioInferenceCallback& callback){ + m_audio_callbacks.emplace_back(&callback); +} +template +void SuperControlSession::register_state_command(size_t state, std::function&& action){ + auto iter = m_state_actions.find(state); + if (iter != m_state_actions.end()){ + throw InternalProgramError(&m_stream.logger(), PA_CURRENT_FUNCTION, "Duplicate State Enum: " + std::to_string(state)); + } + m_state_actions.emplace(state, std::move(action)); +} +template +bool SuperControlSession::run_state_action(size_t state){ + auto iter = m_state_actions.find(state); + if (iter == m_state_actions.end()){ + throw InternalProgramError(&m_stream.logger(), PA_CURRENT_FUNCTION, "Unknown State Enum: " + std::to_string(state)); + } + + // Session isn't even active. + if (!m_active_command){ + return false; + } + + // If we're already in the state and a command is running, don't overwrite it. + if (state == m_last_state && m_active_command->command_is_running()){ + return false; + } + + // Run the state. + m_last_state = state; + m_last_state_change = current_time(); + return iter->second(); +} + +template +void SuperControlSession::run_session(){ + m_start_time = current_time(); + + m_active_command.reset( + new AsyncCommandSession( + m_context, m_env.logger(), m_env.realtime_dispatcher(), + m_context.controller() + ) + ); + + std::vector callbacks; + for (VisualInferenceCallback* callback : m_visual_callbacks){ + callbacks.emplace_back(PeriodicInferenceCallback{*callback, m_visual_period}); + } + for (AudioInferenceCallback* callback : m_audio_callbacks){ + callbacks.emplace_back(PeriodicInferenceCallback{*callback, m_audio_period}); + } + InferenceSession session( + m_context, m_stream, + callbacks, + m_visual_period + ); + + WallClock now = current_time(); + WallClock next_tick = now + m_state_period; + + m_last_state = 0; + + while (true){ + // Check stop conditions. + m_context.throw_if_cancelled(); + + if (run_state(*m_active_command, current_time())){ + break; + } + + now = current_time(); + if (now >= next_tick){ + next_tick = now + m_state_period; + }else{ + m_context.wait_until(next_tick); + next_tick += m_state_period; + } + } + m_context.throw_if_cancelled(); + + m_active_command->stop_session_and_rethrow(); +} + + + + + + +} diff --git a/SerialPrograms/Source/CommonTools/Audio/AudioPerSpectrumDetectorBase.cpp b/SerialPrograms/Source/CommonTools/Audio/AudioPerSpectrumDetectorBase.cpp index a0c2a35614..5810dcb6eb 100644 --- a/SerialPrograms/Source/CommonTools/Audio/AudioPerSpectrumDetectorBase.cpp +++ b/SerialPrograms/Source/CommonTools/Audio/AudioPerSpectrumDetectorBase.cpp @@ -1,219 +1,222 @@ -/* Audio Template Cache - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/AudioPipeline/AudioFeed.h" -#include "SpectrogramMatcher.h" -#include "AudioPerSpectrumDetectorBase.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - -//std::atomic force_detected(false); - - - -AudioPerSpectrumDetectorBase::AudioPerSpectrumDetectorBase( - Logger& logger, - std::string label, - std::string audio_name, - Color detection_color, - DetectedCallback detected_callback -) - : AudioInferenceCallback(std::move(label)) - , m_audio_name(std::move(audio_name)) - , m_detection_color(detection_color) - , m_logger(logger) - , m_detected_callback(std::move(detected_callback)) - , m_start_timestamp(current_time()) - , m_spectrums_processed(0) -{} -AudioPerSpectrumDetectorBase::~AudioPerSpectrumDetectorBase(){ - try{ - log_results(); - }catch (...){} -} -void AudioPerSpectrumDetectorBase::throw_if_no_sound(std::chrono::milliseconds min_duration) const{ - if (m_start_timestamp + min_duration > current_time()){ - return; - } - if (m_lowest_error < 1.0){ - return; - } - if (m_spectrums_processed > 0){ - return; - } - throw UserSetupError(m_logger, "No sound detected."); -} - -void AudioPerSpectrumDetectorBase::log_results(){ - if (m_last_timestamp != WallClock::min()){ - m_logger.log(m_audio_name + " detected! Error Coefficient = " + tostr_default(m_lowest_error), COLOR_BLUE); - }else{ - m_logger.log(m_audio_name + " not detected. Error Coefficient = " + tostr_default(m_lowest_error), COLOR_PURPLE); - } - -#if 0 - if (m_lowest_error >= 1){ - std::stringstream ss; - ss << "AudioPerSpectrumDetectorBase ended with error of 1.0: " << endl; - ss << "Elapsed Time: "<< std::chrono::duration_cast(current_time() - m_start_timestamp).count() << endl; - ss << "m_spectrums_processed = "<< m_spectrums_processed << endl; - for (const auto& error : m_errors){ - ss << "[" << error.first << ":" << error.second << "]"; - } -// m_logger.log(ss.str(), COLOR_RED); - cout << ss.str() << endl; - } - #endif -} - -bool AudioPerSpectrumDetectorBase::process_spectrums( - const std::vector& new_spectrums, - AudioFeed& audio_feed -){ -// cout << m_audio_name << ": " << new_spectrums.size() << endl; - if (new_spectrums.empty()){ -// cout << "No new spectrums" << endl; - return false; - } -// cout << "New spectrums - " << new_spectrums.size() << endl; - - WallClock now = current_time(); - m_spectrums_processed += new_spectrums.size(); - - // Clear last detection. - if (m_last_timestamp + std::chrono::milliseconds(1000) <= now){ - m_last_error = 1.0; - m_last_reported = false; - } - - const size_t sample_rate = new_spectrums[0].sample_rate; - // Lazy initialization of the spectrogram matcher. - if (m_matcher == nullptr || m_matcher->sample_rate() != sample_rate){ - m_logger.log("Loading spectrogram..."); - m_matcher = build_spectrogram_matcher(sample_rate); - } - - // Feed spectrum one by one to the matcher: - // new_spectrums are ordered from newest (largest timestamp) to oldest (smallest timestamp). - // To feed the spectrum from old to new, we need to go through the vector in the reverse order: - - -//#define PA_DEBUG_FORCE_PLA_SOUND - -#ifdef PA_DEBUG_FORCE_PLA_SOUND - static int debug_count = 0; - debug_count++; - cout << "debug_count = " << debug_count << endl; -#endif - - bool found = false; - const float threshold = get_score_threshold(); - for (auto it = new_spectrums.rbegin(); it != new_spectrums.rend(); it++){ - std::vector single_spectrum = {*it}; - const float matcher_score = m_matcher->match(single_spectrum); - // std::cout << "error: " << matcherScore << std::endl; - - if (m_lowest_error < 1.0){ - m_errors.clear(); - }else{ - m_errors.emplace_back(matcher_score, now_to_filestring()); - } - - if (matcher_score == FLT_MAX){ -// cout << "Not enough history: " << m_lowest_error << endl; - continue; // error or not enough spectrum history - } -// cout << "Matcher Score: " << matcher_score << endl; - - // Record the lowest error found during the run - m_lowest_error = std::min(m_lowest_error, matcher_score); - - found = matcher_score <= threshold; - - uint64_t curStamp = m_matcher->latestTimestamp(); - -#ifdef PA_DEBUG_FORCE_PLA_SOUND - if (debug_count % 300 > 300 - 5){ - found = true; - } -#endif - - if (found){ - // Record the time of this match - // To avoid detect the same audio multiple times, use m_last_error >= 1.0 to - // make sure m_last_timestamp is only updated at the first match of the same audio. - if (m_last_error >= 1.0){ - m_last_timestamp = now; - } - // m_last_error tracks the lowest error found by the current match. - m_last_error = std::min(m_last_error, matcher_score); - - std::ostringstream os; - os << m_audio_name << " found, score " << matcher_score << "/" << threshold << ", scale: " << m_matcher->lastMatchedScale(); - m_logger.log(os.str(), COLOR_BLUE); - audio_feed.add_overlay(curStamp+1-m_matcher->numMatchedWindows(), curStamp+1, m_detection_color); - - // Since the target audio is found, no need to check detection on the rest of the spectrums in `new_spectrums`. - - // Tell m_matcher to skip the remaining spectrums so that if `process_spectrums()` gets - // called again on a newer batch of spectrums, m_matcher is happy. - m_matcher->skip(std::vector( - new_spectrums.begin(), - new_spectrums.begin() + std::distance(it + 1, new_spectrums.rend()) - )); - - // Skip the remaining spectrums. - break; - } - } - -// if (force_detected){ -// return true; -// } - - // No shiny detected. - if (m_last_error >= 1.0){ - return false; - } - - // Shiny detected, but haven't waited long enough to measure its magnitude. - if (m_last_timestamp + std::chrono::milliseconds(200) > now){ - return false; - } - - // Already reported a target match within one second. Defer reporting anything. - if (m_last_reported){ - return false; - } - - // No callback. Can't report. - if (m_detected_callback == nullptr){ - return false; - } - - m_last_reported = true; - return m_detected_callback(m_last_error); -} - -void AudioPerSpectrumDetectorBase::clear(){ - m_matcher->clear(); -} - - - - - - -} +/* Audio Template Cache + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/AudioPipeline/AudioFeed.h" +#include "SpectrogramMatcher.h" +#include "AudioPerSpectrumDetectorBase.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + +//std::atomic force_detected(false); + + + +AudioPerSpectrumDetectorBase::AudioPerSpectrumDetectorBase( + Logger& logger, + std::string label, + std::string audio_name, + Color detection_color, + DetectedCallback detected_callback +) + : AudioInferenceCallback(std::move(label)) + , m_audio_name(std::move(audio_name)) + , m_detection_color(detection_color) + , m_logger(logger) + , m_detected_callback(std::move(detected_callback)) + , m_start_timestamp(current_time()) + , m_spectrums_processed(0) +{} +void AudioPerSpectrumDetectorBase::set_detected_callback(DetectedCallback detected_callback){ + m_detected_callback = std::move(detected_callback); +} +AudioPerSpectrumDetectorBase::~AudioPerSpectrumDetectorBase(){ + try{ + log_results(); + }catch (...){} +} +void AudioPerSpectrumDetectorBase::throw_if_no_sound(std::chrono::milliseconds min_duration) const{ + if (m_start_timestamp + min_duration > current_time()){ + return; + } + if (m_lowest_error < 1.0){ + return; + } + if (m_spectrums_processed > 0){ + return; + } + throw UserSetupError(m_logger, "No sound detected."); +} + +void AudioPerSpectrumDetectorBase::log_results(){ + if (m_last_timestamp != WallClock::min()){ + m_logger.log(m_audio_name + " detected! Error Coefficient = " + tostr_default(m_lowest_error), COLOR_BLUE); + }else{ + m_logger.log(m_audio_name + " not detected. Error Coefficient = " + tostr_default(m_lowest_error), COLOR_PURPLE); + } + +#if 0 + if (m_lowest_error >= 1){ + std::stringstream ss; + ss << "AudioPerSpectrumDetectorBase ended with error of 1.0: " << endl; + ss << "Elapsed Time: "<< std::chrono::duration_cast(current_time() - m_start_timestamp).count() << endl; + ss << "m_spectrums_processed = "<< m_spectrums_processed << endl; + for (const auto& error : m_errors){ + ss << "[" << error.first << ":" << error.second << "]"; + } +// m_logger.log(ss.str(), COLOR_RED); + cout << ss.str() << endl; + } + #endif +} + +bool AudioPerSpectrumDetectorBase::process_spectrums( + const std::vector& new_spectrums, + AudioFeed& audio_feed +){ +// cout << m_audio_name << ": " << new_spectrums.size() << endl; + if (new_spectrums.empty()){ +// cout << "No new spectrums" << endl; + return false; + } +// cout << "New spectrums - " << new_spectrums.size() << endl; + + WallClock now = current_time(); + m_spectrums_processed += new_spectrums.size(); + + // Clear last detection. + if (m_last_timestamp + std::chrono::milliseconds(1000) <= now){ + m_last_error = 1.0; + m_last_reported = false; + } + + const size_t sample_rate = new_spectrums[0].sample_rate; + // Lazy initialization of the spectrogram matcher. + if (m_matcher == nullptr || m_matcher->sample_rate() != sample_rate){ + m_logger.log("Loading spectrogram..."); + m_matcher = build_spectrogram_matcher(sample_rate); + } + + // Feed spectrum one by one to the matcher: + // new_spectrums are ordered from newest (largest timestamp) to oldest (smallest timestamp). + // To feed the spectrum from old to new, we need to go through the vector in the reverse order: + + +//#define PA_DEBUG_FORCE_PLA_SOUND + +#ifdef PA_DEBUG_FORCE_PLA_SOUND + static int debug_count = 0; + debug_count++; + cout << "debug_count = " << debug_count << endl; +#endif + + bool found = false; + const float threshold = get_score_threshold(); + for (auto it = new_spectrums.rbegin(); it != new_spectrums.rend(); it++){ + std::vector single_spectrum = {*it}; + const float matcher_score = m_matcher->match(single_spectrum); + // std::cout << "error: " << matcherScore << std::endl; + + if (m_lowest_error < 1.0){ + m_errors.clear(); + }else{ + m_errors.emplace_back(matcher_score, now_to_filestring()); + } + + if (matcher_score == FLT_MAX){ +// cout << "Not enough history: " << m_lowest_error << endl; + continue; // error or not enough spectrum history + } +// cout << "Matcher Score: " << matcher_score << endl; + + // Record the lowest error found during the run + m_lowest_error = std::min(m_lowest_error, matcher_score); + + found = matcher_score <= threshold; + + uint64_t curStamp = m_matcher->latestTimestamp(); + +#ifdef PA_DEBUG_FORCE_PLA_SOUND + if (debug_count % 300 > 300 - 5){ + found = true; + } +#endif + + if (found){ + // Record the time of this match + // To avoid detect the same audio multiple times, use m_last_error >= 1.0 to + // make sure m_last_timestamp is only updated at the first match of the same audio. + if (m_last_error >= 1.0){ + m_last_timestamp = now; + } + // m_last_error tracks the lowest error found by the current match. + m_last_error = std::min(m_last_error, matcher_score); + + std::ostringstream os; + os << m_audio_name << " found, score " << matcher_score << "/" << threshold << ", scale: " << m_matcher->lastMatchedScale(); + m_logger.log(os.str(), COLOR_BLUE); + audio_feed.add_overlay(curStamp+1-m_matcher->numMatchedWindows(), curStamp+1, m_detection_color); + + // Since the target audio is found, no need to check detection on the rest of the spectrums in `new_spectrums`. + + // Tell m_matcher to skip the remaining spectrums so that if `process_spectrums()` gets + // called again on a newer batch of spectrums, m_matcher is happy. + m_matcher->skip(std::vector( + new_spectrums.begin(), + new_spectrums.begin() + std::distance(it + 1, new_spectrums.rend()) + )); + + // Skip the remaining spectrums. + break; + } + } + +// if (force_detected){ +// return true; +// } + + // No shiny detected. + if (m_last_error >= 1.0){ + return false; + } + + // Shiny detected, but haven't waited long enough to measure its magnitude. + if (m_last_timestamp + std::chrono::milliseconds(200) > now){ + return false; + } + + // Already reported a target match within one second. Defer reporting anything. + if (m_last_reported){ + return false; + } + + // No callback. Can't report. + if (m_detected_callback == nullptr){ + return false; + } + + m_last_reported = true; + return m_detected_callback(m_last_error); +} + +void AudioPerSpectrumDetectorBase::clear(){ + m_matcher->clear(); +} + + + + + + +} diff --git a/SerialPrograms/Source/CommonTools/Audio/AudioPerSpectrumDetectorBase.h b/SerialPrograms/Source/CommonTools/Audio/AudioPerSpectrumDetectorBase.h index 7fa2e21a3a..77c462f4c5 100644 --- a/SerialPrograms/Source/CommonTools/Audio/AudioPerSpectrumDetectorBase.h +++ b/SerialPrograms/Source/CommonTools/Audio/AudioPerSpectrumDetectorBase.h @@ -1,134 +1,136 @@ -/* Audio Per-Spectrum Detector Base - * - * From: https://github.com/PokemonAutomation/ - * - * A base class for audio detectors. - * - * It implements AudioInferenceCallback so that it can hook to an inference session - * and stop the session when a target audio is detected. - * The inference session calls process_spectrums(...) periodically and stops when - * the function returns true. - * This base class implements this function. - * - * This base class is called "PerSpectrum" because it tries to match the audio template starting at - * each incoming spectrum in the audio stream. - * For example, if called with three newest unseen spectrums from the audio feed, (i.e `new_spectrums` - * contains three spectrums when passed to AudioPerSpectrumDetectorBase::process_spectrums(...)) - * the detector will check whether the audio template matches the part of audio starting at the first - * of the three spectrums, then check starting at the second, and finally the third. - * Basically, it will try to match the audio template to any possible location in the current audio - * stream. So it will not miss any match even if the audio template is short in duration and the matching - * algorithm needs to be very precise. - * - * This is opposite to the other design choice that only matches the audio starting at the newest - * spectrum in `new_spectrums` when called. That design choice is better suited to non-time-critical - * audio matching and the matching algorithm can tolerate a few spectrums off on time axis. - */ - -#ifndef PokemonAutomation_CommonTools_AudioPerSpectrumDetectorBase_H -#define PokemonAutomation_CommonTools_AudioPerSpectrumDetectorBase_H - -#include -#include -#include "Common/Cpp/Color.h" -#include "Common/Cpp/Time.h" -#include "CommonTools/InferenceCallbacks/AudioInferenceCallback.h" - -namespace PokemonAutomation{ - - -class Logger; -class SpectrogramMatcher; - -// A virtual base class for audio detectors to match an audio template starting at each incoming -// spectrum in the audio stream. -// The derived classes need to implement two functions: -// - float get_score_threshold() const -// - std::unique_ptr build_spectrogram_matcher(size_t sample_rate) -class AudioPerSpectrumDetectorBase : public AudioInferenceCallback{ -public: - using DetectedCallback = std::function; - // label: a name for this detector. Used for logging and profiling. - // audio_name: the name of the audio to be detected (shiny sound etc). Capitalize first letter. - // detection_color: the color to visualize the detection on audio spectrogram UI. - // on_shiny_callback(float error_coefficient) -> bool: - // when the detector finds a match, it calls this callback function to decide whether to stop - // the inference session. The error coefficient of the found audio is passed to the callback - // function. If it returns true, the inference session will stop (by returning true from - // AudioPerSpectrumDetectorBase::process_spectrums()). - AudioPerSpectrumDetectorBase( - Logger& logger, - std::string label, - std::string audio_name, - Color detection_color, - DetectedCallback detected_callback - ); - - virtual ~AudioPerSpectrumDetectorBase(); - - WallClock last_detection() const{ - return m_last_timestamp; - } - - void throw_if_no_sound(std::chrono::milliseconds min_duration = std::chrono::milliseconds(5000)) const; - - // To be implemented by derived classes: - // The match threshold for the target audio. - virtual float get_score_threshold() const = 0; - - // Implement AudioInferenceCallback::process_spectrums() - virtual bool process_spectrums( - const std::vector& new_spectrums, - AudioFeed& audio_feed - ) override; - - // Clear internal data to be used on another audio stream. - void clear(); - - // Log whether the target audio is detected or not during the runtime of this detector. - // This function will always be called when the detector is destructed. - void log_results(); - - float lowest_error() const{ return m_lowest_error; } - -protected: - // To be implemented by derived classes: - // build the actual spectrogram matcher for the target audio. - virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) = 0; - - // Name of the target audio to be detected. Used for logging. - std::string m_audio_name; - // Color of the box to visualize the detection in the audio spectrogram UI. - Color m_detection_color; - - Logger& m_logger; - // Callback function to determine whether to stop the inference session when the target audio - // is detected. - DetectedCallback m_detected_callback; - - WallClock m_start_timestamp; - uint64_t m_spectrums_processed; - - // Record lowest error coefficient (i.e best match) during the runtime of this detector. - float m_lowest_error = 1.0f; - // Record the last timestamp when the target audio is detected. - // If no detection throughout the runtime, this will remain WallClock::min(). - WallClock m_last_timestamp = WallClock::min(); - // Record the last match error coefficient when the target audio is detected. - // It will be reset to 1.0f when one second has passed since the last detection. - float m_last_error = 1.0f; - // This is set to true when a match is found. It will remain true for one second - // so that the detector will not count the same detected audio multiple times. - bool m_last_reported = false; - - std::unique_ptr m_matcher; - - std::vector> m_errors; -}; - - - - - -} -#endif +/* Audio Per-Spectrum Detector Base + * + * From: https://github.com/PokemonAutomation/ + * + * A base class for audio detectors. + * + * It implements AudioInferenceCallback so that it can hook to an inference session + * and stop the session when a target audio is detected. + * The inference session calls process_spectrums(...) periodically and stops when + * the function returns true. + * This base class implements this function. + * + * This base class is called "PerSpectrum" because it tries to match the audio template starting at + * each incoming spectrum in the audio stream. + * For example, if called with three newest unseen spectrums from the audio feed, (i.e `new_spectrums` + * contains three spectrums when passed to AudioPerSpectrumDetectorBase::process_spectrums(...)) + * the detector will check whether the audio template matches the part of audio starting at the first + * of the three spectrums, then check starting at the second, and finally the third. + * Basically, it will try to match the audio template to any possible location in the current audio + * stream. So it will not miss any match even if the audio template is short in duration and the matching + * algorithm needs to be very precise. + * + * This is opposite to the other design choice that only matches the audio starting at the newest + * spectrum in `new_spectrums` when called. That design choice is better suited to non-time-critical + * audio matching and the matching algorithm can tolerate a few spectrums off on time axis. + */ + +#ifndef PokemonAutomation_CommonTools_AudioPerSpectrumDetectorBase_H +#define PokemonAutomation_CommonTools_AudioPerSpectrumDetectorBase_H + +#include +#include +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Time.h" +#include "CommonTools/InferenceCallbacks/AudioInferenceCallback.h" + +namespace PokemonAutomation{ + + +class Logger; +class SpectrogramMatcher; + +// A virtual base class for audio detectors to match an audio template starting at each incoming +// spectrum in the audio stream. +// The derived classes need to implement two functions: +// - float get_score_threshold() const +// - std::unique_ptr build_spectrogram_matcher(size_t sample_rate) +class AudioPerSpectrumDetectorBase : public AudioInferenceCallback{ +public: + virtual ~AudioPerSpectrumDetectorBase(); + + using DetectedCallback = std::function; + // label: a name for this detector. Used for logging and profiling. + // audio_name: the name of the audio to be detected (shiny sound etc). Capitalize first letter. + // detection_color: the color to visualize the detection on audio spectrogram UI. + // on_shiny_callback(float error_coefficient) -> bool: + // when the detector finds a match, it calls this callback function to decide whether to stop + // the inference session. The error coefficient of the found audio is passed to the callback + // function. If it returns true, the inference session will stop (by returning true from + // AudioPerSpectrumDetectorBase::process_spectrums()). + AudioPerSpectrumDetectorBase( + Logger& logger, + std::string label, + std::string audio_name, + Color detection_color, + DetectedCallback detected_callback = nullptr + ); + + void set_detected_callback(DetectedCallback detected_callback); + + WallClock last_detection() const{ + return m_last_timestamp; + } + + void throw_if_no_sound(std::chrono::milliseconds min_duration = std::chrono::milliseconds(5000)) const; + + // To be implemented by derived classes: + // The match threshold for the target audio. + virtual float get_score_threshold() const = 0; + + // Implement AudioInferenceCallback::process_spectrums() + virtual bool process_spectrums( + const std::vector& new_spectrums, + AudioFeed& audio_feed + ) override; + + // Clear internal data to be used on another audio stream. + void clear(); + + // Log whether the target audio is detected or not during the runtime of this detector. + // This function will always be called when the detector is destructed. + void log_results(); + + float lowest_error() const{ return m_lowest_error; } + +protected: + // To be implemented by derived classes: + // build the actual spectrogram matcher for the target audio. + virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) = 0; + + // Name of the target audio to be detected. Used for logging. + std::string m_audio_name; + // Color of the box to visualize the detection in the audio spectrogram UI. + Color m_detection_color; + + Logger& m_logger; + // Callback function to determine whether to stop the inference session when the target audio + // is detected. + DetectedCallback m_detected_callback; + + WallClock m_start_timestamp; + uint64_t m_spectrums_processed; + + // Record lowest error coefficient (i.e best match) during the runtime of this detector. + float m_lowest_error = 1.0f; + // Record the last timestamp when the target audio is detected. + // If no detection throughout the runtime, this will remain WallClock::min(). + WallClock m_last_timestamp = WallClock::min(); + // Record the last match error coefficient when the target audio is detected. + // It will be reset to 1.0f when one second has passed since the last detection. + float m_last_error = 1.0f; + // This is set to true when a match is found. It will remain true for one second + // so that the detector will not count the same detected audio multiple times. + bool m_last_reported = false; + + std::unique_ptr m_matcher; + + std::vector> m_errors; +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Audio/AudioTemplateCache.cpp b/SerialPrograms/Source/CommonTools/Audio/AudioTemplateCache.cpp index 06eb4c133d..448a6ff377 100644 --- a/SerialPrograms/Source/CommonTools/Audio/AudioTemplateCache.cpp +++ b/SerialPrograms/Source/CommonTools/Audio/AudioTemplateCache.cpp @@ -1,75 +1,75 @@ -/* Audio Template Cache - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/AlignedVector.tpp" -#include "CommonFramework/Globals.h" -#include "CommonFramework/AudioPipeline/AudioTemplate.h" -#include "AudioTemplateCache.h" - - -namespace PokemonAutomation{ - - -AudioTemplateCache::~AudioTemplateCache(){} -AudioTemplateCache::AudioTemplateCache(){} - -AudioTemplateCache& AudioTemplateCache::instance(){ - static AudioTemplateCache cache; - return cache; -} - - -const AudioTemplate* AudioTemplateCache::get_nothrow_internal(const std::string& full_path_no_ext, size_t sample_rate){ - WriteSpinLock lg(m_lock); - auto iter = m_cache.find(full_path_no_ext); - if (iter != m_cache.end()){ - return &iter->second; - } - - std::string full_path = full_path_no_ext + ".wav"; - if (!QFileInfo::exists(QString::fromStdString(full_path))){ - full_path = full_path_no_ext + ".mp3"; - } - - AudioTemplate audio_template = loadAudioTemplate(full_path, (int)sample_rate); - if (audio_template.numFrequencies() == 0){ - return nullptr; - } - - iter = m_cache.emplace( - std::move(full_path_no_ext), - std::move(audio_template) - ).first; - - return &iter->second; -} - - - -const AudioTemplate* AudioTemplateCache::get_nothrow(const std::string& path, size_t sample_rate){ - std::string full_path_no_ext = RESOURCE_PATH() + path + "-" + std::to_string(sample_rate); - return get_nothrow_internal(full_path_no_ext, sample_rate); -} -const AudioTemplate& AudioTemplateCache::get_throw(const std::string& path, size_t sample_rate){ - std::string full_path_no_ext = RESOURCE_PATH() + path + "-" + std::to_string(sample_rate); - const AudioTemplate* audio_template = get_nothrow_internal(full_path_no_ext, sample_rate); - if (audio_template == nullptr){ - throw FileException( - nullptr, PA_CURRENT_FUNCTION, - "Unable to open audio template file. (Sample Rate = " + std::to_string(sample_rate) + ")", - full_path_no_ext + ".(wav or mp3)" - ); - } - return *audio_template; -} - - - - -} +/* Audio Template Cache + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/AlignedVector.tpp" +#include "CommonFramework/Globals.h" +#include "CommonFramework/AudioPipeline/AudioTemplate.h" +#include "AudioTemplateCache.h" + + +namespace PokemonAutomation{ + + +AudioTemplateCache::~AudioTemplateCache(){} +AudioTemplateCache::AudioTemplateCache(){} + +AudioTemplateCache& AudioTemplateCache::instance(){ + static AudioTemplateCache cache; + return cache; +} + + +const AudioTemplate* AudioTemplateCache::get_nothrow_internal(const std::string& full_path_no_ext, size_t sample_rate){ + WriteSpinLock lg(m_lock); + auto iter = m_cache.find(full_path_no_ext); + if (iter != m_cache.end()){ + return &iter->second; + } + + std::string full_path = full_path_no_ext + ".wav"; + if (!QFileInfo::exists(QString::fromStdString(full_path))){ + full_path = full_path_no_ext + ".mp3"; + } + + AudioTemplate audio_template = loadAudioTemplate(full_path, (int)sample_rate); + if (audio_template.numFrequencies() == 0){ + return nullptr; + } + + iter = m_cache.emplace( + std::move(full_path_no_ext), + std::move(audio_template) + ).first; + + return &iter->second; +} + + + +const AudioTemplate* AudioTemplateCache::get_nothrow(const std::string& path, size_t sample_rate){ + std::string full_path_no_ext = RESOURCE_PATH() + path + "-" + std::to_string(sample_rate); + return get_nothrow_internal(full_path_no_ext, sample_rate); +} +const AudioTemplate& AudioTemplateCache::get_throw(const std::string& path, size_t sample_rate){ + std::string full_path_no_ext = RESOURCE_PATH() + path + "-" + std::to_string(sample_rate); + const AudioTemplate* audio_template = get_nothrow_internal(full_path_no_ext, sample_rate); + if (audio_template == nullptr){ + throw FileException( + nullptr, PA_CURRENT_FUNCTION, + "Unable to open audio template file. (Sample Rate = " + std::to_string(sample_rate) + ")", + full_path_no_ext + ".(wav or mp3)" + ); + } + return *audio_template; +} + + + + +} diff --git a/SerialPrograms/Source/CommonTools/Audio/AudioTemplateCache.h b/SerialPrograms/Source/CommonTools/Audio/AudioTemplateCache.h index 5c98194d03..ebdc8b4bac 100644 --- a/SerialPrograms/Source/CommonTools/Audio/AudioTemplateCache.h +++ b/SerialPrograms/Source/CommonTools/Audio/AudioTemplateCache.h @@ -1,55 +1,55 @@ -/* Audio Template Cache - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_AudioTemplateCache_H -#define PokemonAutomation_CommonTools_AudioTemplateCache_H - -#include -#include -#include "Common/Cpp/Concurrency/SpinLock.h" - -namespace PokemonAutomation{ - -class AudioTemplate; - - - -class AudioTemplateCache{ -public: - // path: the path of the basename of the audio template file relative to RESOURCE_PATH(). - // sample_rate: target sample rate. Used to locate the audio template file with the desired sample rate. - // - // The function will first try to load the file using .wav extension. If .wav not available, load .mp3. - // e.g. if `path` is "PokemonLA/ShinySound" and `sample_rate` is 48000, it will load - // RESOURCE_PATH/PokemonLA/ShinySound-48000.wav if it exists. If not, it will load - // RESOURCE_PATH/PokemonLA/ShinySound-48000.mp3 instead. - // Won't throw if cannot read or parse the template file. Return nullptr in this case. - const AudioTemplate* get_nothrow(const std::string& path, size_t sample_rate); - // See comment of AudioTemplateCache::get_nothrow(). - // Throw a FileException if cannot read or parse the template file. - const AudioTemplate& get_throw(const std::string& path, size_t sample_rate); - - static AudioTemplateCache& instance(); - -private: - ~AudioTemplateCache(); - AudioTemplateCache(); - - const AudioTemplate* get_nothrow_internal(const std::string& full_path_no_ext, size_t sample_rate); - - -private: - SpinLock m_lock; - std::map m_cache; -}; - - - - - - -} -#endif +/* Audio Template Cache + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_AudioTemplateCache_H +#define PokemonAutomation_CommonTools_AudioTemplateCache_H + +#include +#include +#include "Common/Cpp/Concurrency/SpinLock.h" + +namespace PokemonAutomation{ + +class AudioTemplate; + + + +class AudioTemplateCache{ +public: + // path: the path of the basename of the audio template file relative to RESOURCE_PATH(). + // sample_rate: target sample rate. Used to locate the audio template file with the desired sample rate. + // + // The function will first try to load the file using .wav extension. If .wav not available, load .mp3. + // e.g. if `path` is "PokemonLA/ShinySound" and `sample_rate` is 48000, it will load + // RESOURCE_PATH/PokemonLA/ShinySound-48000.wav if it exists. If not, it will load + // RESOURCE_PATH/PokemonLA/ShinySound-48000.mp3 instead. + // Won't throw if cannot read or parse the template file. Return nullptr in this case. + const AudioTemplate* get_nothrow(const std::string& path, size_t sample_rate); + // See comment of AudioTemplateCache::get_nothrow(). + // Throw a FileException if cannot read or parse the template file. + const AudioTemplate& get_throw(const std::string& path, size_t sample_rate); + + static AudioTemplateCache& instance(); + +private: + ~AudioTemplateCache(); + AudioTemplateCache(); + + const AudioTemplate* get_nothrow_internal(const std::string& full_path_no_ext, size_t sample_rate); + + +private: + SpinLock m_lock; + std::map m_cache; +}; + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Audio/SpectrogramMatcher.cpp b/SerialPrograms/Source/CommonTools/Audio/SpectrogramMatcher.cpp index dab4efe558..2f435426e6 100644 --- a/SerialPrograms/Source/CommonTools/Audio/SpectrogramMatcher.cpp +++ b/SerialPrograms/Source/CommonTools/Audio/SpectrogramMatcher.cpp @@ -1,404 +1,404 @@ - - -#include -#include -#include -#include -//#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/AlignedVector.tpp" -#include "Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch.h" -#include "Kernels/SpikeConvolution/Kernels_SpikeConvolution.h" -#include "CommonFramework/AudioPipeline/AudioFeed.h" -#include "CommonFramework/AudioPipeline/AudioTemplate.h" -#include "SpectrogramMatcher.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -std::vector buildSpikeKernel(size_t numFrequencies, size_t halfSampleRate){ - std::vector kernel; - // We find a good kernel when sample rate is 48K and numFrequencies is 2048: - // [-4.f, -3.f, -2.f, -1.f, 0.f, 1.f, 2.f, 3.f, 4.f, 4.f, 3.f, 2.f, 1.f, 0.f, -1.f, -2.f, -3.f, -4.f] - // This spans frenquency range of 17 * halfSampleRate / numFrequencies = 199.21875Hz, where 17 is the number of intervals in the above series. - // For another sample rate and numFrequencies combination, the number of intervals is - // 199.21875 * numFrequencies / halfSampleRate - size_t numKernelIntervals = int(199.21875 * numFrequencies / halfSampleRate + 0.5); - size_t slopeLen = numKernelIntervals / 2; - for(size_t i = 0; i <= slopeLen; i++){ - kernel.push_back(-4.0f + 8.f * i / (float)slopeLen); - } - for(size_t i = ((numKernelIntervals+1) % 2); i <= slopeLen; i++){ - kernel.push_back(-4.0f + 8.f * (slopeLen-i)/(float)slopeLen); - } - return kernel; -} - -// std::vector buildSmoothKernel(size_t numFrequencies, size_t halfSampleRate){ -// std::vector kernel; -// // We find a good kernel when sample rate is 48K and numFrequencies is 2048: -// // [0.0111, 0.135, 0.606, 1.0, 0.606, 0.135, 0.0111], built as Gaussian distribution with sigma(stddev) as 1.0 -// // The equation for Gaussian is exp(-x^2/(2 sigma^2)) -// // We can think sigma value as 1.0 * frequency_gap = 1.0 * halfSampleRate / numFrequencies = 11.71875 Hz -// } - - -SpectrogramMatcher::SpectrogramMatcher( - std::string name, - AudioTemplate audioTemplate, Mode mode, size_t sample_rate, - double low_frequency_filter, size_t templateSubdivision -) - : m_name(std::move(name)) - , m_template(std::move(audioTemplate)) - , m_sample_rate(sample_rate) - , m_mode(mode) -{ - const size_t numTemplateWindows = m_template.numWindows(); -// cout << "numTemplateWindows = " << numTemplateWindows << endl; - m_numOriginalFrequencies = m_template.numFrequencies(); - if (m_template.numFrequencies() == 0){ // Error case, failed to load template - std::cout << "Error: load audio template failed" << std::endl; - return; -// throw FileException(nullptr, PA_CURRENT_FUNCTION, "Unable to load audio template file.", templateFilename.toStdString()); - } - - const size_t halfSampleRate = sample_rate / 2; - - // The frequency range from [0.0, halfSampleRate / numFrequencies, 2.0 halfSampleRate / numFrequencies, ... (numFrequencies-1) halfSampleRate / numFrequencies] - // Since human can only hear as high as 20KHz sound, matching on frequencies >= 20KHz is meaningless. - // So the index i of the max frequency we should be matching is the one with - // i * halfSampleRate/numFrequencies <= 20KHz - // i <= numFrequencies * 20K / halfSampleRate - // We also have a cut-off threshold to remove lower frequencies. We set it to be at frequency index 5 when sample rate is 48K and numFrequencies is 2048. - // So 5.0 24K / 2048 = 58.59375Hz. For other sample rate and numFrequencies combinations, - // j * halfSampleRate/numFrequencies >= 58.59375 -> j >= 58.59375 * numFrequnecies / halfSampleRate - - m_originalFreqStart = int(low_frequency_filter * m_numOriginalFrequencies / halfSampleRate + 0.5); - m_originalFreqEnd = 20000 * m_numOriginalFrequencies / halfSampleRate + 1; - - // Initialize the spike convolution kernel: - m_convKernel = buildSpikeKernel(m_numOriginalFrequencies, halfSampleRate); - - switch(m_mode){ - case Mode::SPIKE_CONV: - { - // Do convolution on audio template - const size_t numConvedFrequencies = (m_originalFreqEnd - m_originalFreqStart) - m_convKernel.size() + 1; - - AudioTemplate audio_template(numConvedFrequencies, numTemplateWindows); - for (size_t i = 0; i < numTemplateWindows; i++){ - conv( - m_template.getWindow(i) + m_originalFreqStart, m_originalFreqEnd - m_originalFreqStart, - audio_template.getWindow(i) - ); - } - - m_template = std::move(audio_template); - m_freqStart = 0; - m_freqEnd = numConvedFrequencies; - break; - } - case Mode::AVERAGE_5: - { - // Avereage every 5 frequencies - const size_t numNewFreq = (m_originalFreqEnd - m_originalFreqStart) / 5; - - AudioTemplate audio_template(numNewFreq, numTemplateWindows); - for (size_t i = 0; i < numTemplateWindows; i++){ - for (size_t j = 0; j < numNewFreq; j++){ - const float * rawFreqMag = m_template.getWindow(i) + m_originalFreqStart + j*5; - const float newMag = (rawFreqMag[0] + rawFreqMag[1] + rawFreqMag[2] + rawFreqMag[3] + rawFreqMag[4]) / 5.0f; - audio_template.getWindow(i)[j] = newMag; - } - } - - m_template = std::move(audio_template); - m_freqStart = 0; - m_freqEnd = numNewFreq; - break; - } - case Mode::RAW: - m_freqStart = m_originalFreqStart; - m_freqEnd = m_originalFreqEnd; - break; - } - - if (templateSubdivision <= 1){ - m_templateRange.emplace_back(0, numTemplateWindows); - m_numSpectrumsNeeded = numTemplateWindows; - }else{ - // Number of subdivision cannot exceed number of windows in the template. - templateSubdivision = std::min(templateSubdivision, numTemplateWindows); - // num windows of each subdivided template - const size_t num_subWindows = numTemplateWindows / templateSubdivision; - m_numSpectrumsNeeded = num_subWindows; - for(size_t i = 0; i < templateSubdivision; i++){ - const size_t windowStart = i * num_subWindows; - const size_t windowEnd = (i+1) * num_subWindows; - m_templateRange.emplace_back(windowStart, windowEnd); - } - } -// cout << "m_templateRange = " << m_templateRange.size() << endl; -// cout << "m_numSpectrumsNeeded = " << m_numSpectrumsNeeded << endl; - - m_templateNorm = buildTemplateNorm(); -} - -uint64_t SpectrogramMatcher::latestTimestamp() const{ - if (m_spectrums.size() == 0){ - return SIZE_MAX; - } - return m_spectrums.front().stamp; -} - -void SpectrogramMatcher::conv(const float* src, size_t num, float* dst){ -// cout << (size_t)dst % 64 << endl; - - const size_t numConvedFrequencies = num - m_convKernel.size() + 1; - if (num < m_convKernel.size()){ - memset(dst, 0, numConvedFrequencies * sizeof(float)); - return; - } - -#if 0 - for (size_t i = 0; i < num-m_convKernel.size()+1; i++){ - dst[i] = 0.0f; - for (size_t j = 0; j < m_convKernel.size(); j++){ - dst[i] += src[i+j] * m_convKernel[j]; - } - } -#else - Kernels::SpikeConvolution::compute_spike_kernel( - dst, src, num, m_convKernel.data(), m_convKernel.size() - ); -#endif -} - -std::vector SpectrogramMatcher::buildTemplateNorm() const{ - std::vector ret(m_templateRange.size()); - - for (size_t sub_index = 0; sub_index < m_templateRange.size(); sub_index++){ - float sumSqr = 0.0f; - for (size_t i = m_templateRange[sub_index].first; i < m_templateRange[sub_index].second; i++){ - for(size_t j = m_freqStart; j < m_freqEnd; j++){ - const float v = m_template.getWindow(i)[j]; - sumSqr += v * v; - } - } - ret[sub_index] = std::sqrt(sumSqr); - } - - return ret; -} - -bool SpectrogramMatcher::update_to_new_spectrum(AudioSpectrum spectrum){ - if (m_numOriginalFrequencies != spectrum.magnitudes->size()){ - std::cout << "Error: number of frequencies don't match in SpectrogramMatcher::match() " << - m_numOriginalFrequencies << " " << spectrum.magnitudes->size() << std::endl; - return false; - } - - switch(m_mode){ - case Mode::SPIKE_CONV: - { - // Do the conv on new spectrum too. - AlignedVector convedSpectrum(m_template.bufferSize()); - conv(spectrum.magnitudes->data() + m_originalFreqStart, - m_originalFreqEnd - m_originalFreqStart, convedSpectrum.data()); - - spectrum.magnitudes = std::make_unique>(std::move(convedSpectrum)); - break; - } - case Mode::AVERAGE_5: - { - AlignedVector avgedSpectrum(m_template.bufferSize()); - for(size_t j = 0; j < m_template.numFrequencies(); j++){ - const float * rawFreqMag = spectrum.magnitudes->data() + m_originalFreqStart + j*5; - const float newMag = (rawFreqMag[0] + rawFreqMag[1] + rawFreqMag[2] + rawFreqMag[3] + rawFreqMag[4]) / 5.0f; - avgedSpectrum[j] = newMag; - } - spectrum.magnitudes = std::make_unique>(std::move(avgedSpectrum)); - break; - } - case Mode::RAW: - break; - } - - // Compute the norm square (= sum squares) of the spectrum, used for matching: - // TODO: if there will be multiple SpectrogramMatcher running on the same audio stream, can - // move this per-spectrum computation to a shared struct for those matchers to save computation. - float spectrumNormSqr = 0.0f; - for (size_t i = m_freqStart; i < m_freqEnd; i++){ - float mag = (*spectrum.magnitudes)[i]; - spectrumNormSqr += mag * mag; - } - m_spectrumNormSqrs.push_front(spectrumNormSqr); - - m_spectrums.emplace_front(std::move(spectrum)); - - return true; -} - -bool SpectrogramMatcher::update_to_new_spectrums(const std::vector& new_spectrums){ - for (auto it = new_spectrums.rbegin(); it != new_spectrums.rend(); it++){ - if(!update_to_new_spectrum(*it)){ - return false; - } - } - - // pop out too old spectrums - while (m_spectrums.size() > m_numSpectrumsNeeded){ - m_spectrums.pop_back(); - m_spectrumNormSqrs.pop_back(); - } - - return true; -} - -std::pair SpectrogramMatcher::match_sub_template(size_t sub_index) const{ -#if 0 - auto iter = m_spectrums.begin(); - auto iter2 = m_spectrumNormSqrs.begin(); - float streamSumSqr = 0.0f; - float sumMulti = 0.0f; - - const size_t template_start = m_templateRange[sub_index].first; - const size_t template_end = m_templateRange[sub_index].second; - for(size_t i = template_start; i < template_end; i++, iter++, iter2++){ - // match in order from latest window to oldest - const float* templateData = m_template.getWindow(template_end-1-i); - const float* streamData = iter->magnitudes->data(); - streamSumSqr += *iter2; - for(size_t j = m_freqStart; j < m_freqEnd; j++){ - sumMulti += templateData[j] * streamData[j]; - } - } -// cout << "sumMulti = " << sumMulti << ", streamSumSqr = " << streamSumSqr << endl; - const float scale = (streamSumSqr < 1e-6f ? 1.0f : sumMulti / streamSumSqr); - - iter = m_spectrums.begin(); - float sum = 0.0f; - for(size_t i = template_start; i < template_end; i++, iter++){ - // match in order from latest window to oldest - const float* templateData = m_template.getWindow(template_end-1-i); - const float* streamData = iter->magnitudes->data(); - for(size_t j = m_freqStart; j < m_freqEnd; j++){ - float d = templateData[j] - scale * streamData[j]; - sum += d * d; - } - } -#else - // Build matrix. - auto iter = m_spectrums.begin(); - const size_t template_start = m_templateRange[sub_index].first; - const size_t template_end = m_templateRange[sub_index].second; - size_t windows = template_end - template_start; -// cout << windows << endl; -// cout << m_spectrums.size() << " / " << windows << endl; - size_t freqs = m_freqEnd - m_freqStart; - std::vector matrixA(windows); - std::vector matrixT(windows); - for (size_t i = 0; i < windows; i++, iter++){ -// cout << "Template: " << ((size_t)m_template.getWindow(template_end - 1 - i) % 64) << endl; -// cout << "Samples: " << ((size_t)iter->magnitudes->data() % 64) << endl; - matrixT[i] = m_freqStart + m_template.getWindow(windows - 1 - i); - matrixA[i] = m_freqStart + iter->magnitudes->data(); -// cout << matrixT[i] << " : " << matrixA[i] << endl; - } - - // Compute scale. - float scale = Kernels::ScaleInvariantMatrixMatch::compute_scale( - freqs, windows, - matrixA.data(), matrixT.data() - ); - scale = std::min(scale, 1000000); - - // Compute error. - float sum = Kernels::ScaleInvariantMatrixMatch::compute_error( - freqs, windows, - scale, - matrixA.data(), matrixT.data() - ); -#endif - - - float score = sqrt(sum) / m_templateNorm[0]; -// cout << "score = " << score << endl; - score = std::min(score, 1.0); - - return std::make_pair(score, scale); -} - -float SpectrogramMatcher::match(const std::vector& new_spectrums){ - if (!update_to_new_spectrums(new_spectrums)){ - return FLT_MAX; - } - - if (m_spectrums.size() < m_numSpectrumsNeeded){ - return FLT_MAX; - } - - // Check whether the stored spectrums' timestamps are continuous: - size_t curStamp = m_spectrums.front().stamp; - size_t lastStamp = curStamp + 1; - for (const auto& s : m_spectrums){ - if (s.stamp != lastStamp - 1){ - std::cout << "Error: SpectrogramMatcher (" + m_name + ") spectrum timestamps are not continuous:" << std::endl; - - for(const auto& sp : m_spectrums){ - std::cout << sp.stamp << ", "; - } - std::cout << std::endl; - return FLT_MAX; - } - lastStamp--; - } - - if (m_lastStampTested != SIZE_MAX && curStamp <= m_lastStampTested){ - return FLT_MAX; - } - m_lastStampTested = curStamp; - - // Do the match: - float score = FLT_MAX; // the lower the score, the better the match - if (m_templateRange.size() == 1){ - // Match the full template - std::tie(score, m_lastScale) = match_sub_template(0); - }else{ - // Match each individual sub-template - for (size_t sub_template = 0; sub_template < m_templateRange.size(); sub_template++){ - float sub_template_score = FLT_MAX; - float sub_template_scale = 1.0f; - std::tie(sub_template_score, sub_template_scale) = match_sub_template(sub_template); - if (sub_template_score < score){ - score = sub_template_score; - m_lastScale = sub_template_scale; - } - } - } - - return score; -} - -bool SpectrogramMatcher::skip(const std::vector& new_spectrums){ - // Note: ideally we don't want to have any computation while skipping. - // But update_to_new_spectrums() may still do some filtering and vector norm computation. - // Since the computation is relatively small and we won't be skipping lots of frames anyway, - // this should be fine for now. - // We can improve this later. - return update_to_new_spectrums(new_spectrums); -} - -void SpectrogramMatcher::clear(){ - m_spectrums.clear(); - m_spectrumNormSqrs.clear(); - m_lastStampTested = SIZE_MAX; -} - - - - -} + + +#include +#include +#include +#include +//#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/AlignedVector.tpp" +#include "Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch.h" +#include "Kernels/SpikeConvolution/Kernels_SpikeConvolution.h" +#include "CommonFramework/AudioPipeline/AudioFeed.h" +#include "CommonFramework/AudioPipeline/AudioTemplate.h" +#include "SpectrogramMatcher.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +std::vector buildSpikeKernel(size_t numFrequencies, size_t halfSampleRate){ + std::vector kernel; + // We find a good kernel when sample rate is 48K and numFrequencies is 2048: + // [-4.f, -3.f, -2.f, -1.f, 0.f, 1.f, 2.f, 3.f, 4.f, 4.f, 3.f, 2.f, 1.f, 0.f, -1.f, -2.f, -3.f, -4.f] + // This spans frenquency range of 17 * halfSampleRate / numFrequencies = 199.21875Hz, where 17 is the number of intervals in the above series. + // For another sample rate and numFrequencies combination, the number of intervals is + // 199.21875 * numFrequencies / halfSampleRate + size_t numKernelIntervals = int(199.21875 * numFrequencies / halfSampleRate + 0.5); + size_t slopeLen = numKernelIntervals / 2; + for(size_t i = 0; i <= slopeLen; i++){ + kernel.push_back(-4.0f + 8.f * i / (float)slopeLen); + } + for(size_t i = ((numKernelIntervals+1) % 2); i <= slopeLen; i++){ + kernel.push_back(-4.0f + 8.f * (slopeLen-i)/(float)slopeLen); + } + return kernel; +} + +// std::vector buildSmoothKernel(size_t numFrequencies, size_t halfSampleRate){ +// std::vector kernel; +// // We find a good kernel when sample rate is 48K and numFrequencies is 2048: +// // [0.0111, 0.135, 0.606, 1.0, 0.606, 0.135, 0.0111], built as Gaussian distribution with sigma(stddev) as 1.0 +// // The equation for Gaussian is exp(-x^2/(2 sigma^2)) +// // We can think sigma value as 1.0 * frequency_gap = 1.0 * halfSampleRate / numFrequencies = 11.71875 Hz +// } + + +SpectrogramMatcher::SpectrogramMatcher( + std::string name, + AudioTemplate audioTemplate, Mode mode, size_t sample_rate, + double low_frequency_filter, size_t templateSubdivision +) + : m_name(std::move(name)) + , m_template(std::move(audioTemplate)) + , m_sample_rate(sample_rate) + , m_mode(mode) +{ + const size_t numTemplateWindows = m_template.numWindows(); +// cout << "numTemplateWindows = " << numTemplateWindows << endl; + m_numOriginalFrequencies = m_template.numFrequencies(); + if (m_template.numFrequencies() == 0){ // Error case, failed to load template + std::cout << "Error: load audio template failed" << std::endl; + return; +// throw FileException(nullptr, PA_CURRENT_FUNCTION, "Unable to load audio template file.", templateFilename.toStdString()); + } + + const size_t halfSampleRate = sample_rate / 2; + + // The frequency range from [0.0, halfSampleRate / numFrequencies, 2.0 halfSampleRate / numFrequencies, ... (numFrequencies-1) halfSampleRate / numFrequencies] + // Since human can only hear as high as 20KHz sound, matching on frequencies >= 20KHz is meaningless. + // So the index i of the max frequency we should be matching is the one with + // i * halfSampleRate/numFrequencies <= 20KHz + // i <= numFrequencies * 20K / halfSampleRate + // We also have a cut-off threshold to remove lower frequencies. We set it to be at frequency index 5 when sample rate is 48K and numFrequencies is 2048. + // So 5.0 24K / 2048 = 58.59375Hz. For other sample rate and numFrequencies combinations, + // j * halfSampleRate/numFrequencies >= 58.59375 -> j >= 58.59375 * numFrequnecies / halfSampleRate + + m_originalFreqStart = int(low_frequency_filter * m_numOriginalFrequencies / halfSampleRate + 0.5); + m_originalFreqEnd = 20000 * m_numOriginalFrequencies / halfSampleRate + 1; + + // Initialize the spike convolution kernel: + m_convKernel = buildSpikeKernel(m_numOriginalFrequencies, halfSampleRate); + + switch(m_mode){ + case Mode::SPIKE_CONV: + { + // Do convolution on audio template + const size_t numConvedFrequencies = (m_originalFreqEnd - m_originalFreqStart) - m_convKernel.size() + 1; + + AudioTemplate audio_template(numConvedFrequencies, numTemplateWindows); + for (size_t i = 0; i < numTemplateWindows; i++){ + conv( + m_template.getWindow(i) + m_originalFreqStart, m_originalFreqEnd - m_originalFreqStart, + audio_template.getWindow(i) + ); + } + + m_template = std::move(audio_template); + m_freqStart = 0; + m_freqEnd = numConvedFrequencies; + break; + } + case Mode::AVERAGE_5: + { + // Avereage every 5 frequencies + const size_t numNewFreq = (m_originalFreqEnd - m_originalFreqStart) / 5; + + AudioTemplate audio_template(numNewFreq, numTemplateWindows); + for (size_t i = 0; i < numTemplateWindows; i++){ + for (size_t j = 0; j < numNewFreq; j++){ + const float * rawFreqMag = m_template.getWindow(i) + m_originalFreqStart + j*5; + const float newMag = (rawFreqMag[0] + rawFreqMag[1] + rawFreqMag[2] + rawFreqMag[3] + rawFreqMag[4]) / 5.0f; + audio_template.getWindow(i)[j] = newMag; + } + } + + m_template = std::move(audio_template); + m_freqStart = 0; + m_freqEnd = numNewFreq; + break; + } + case Mode::RAW: + m_freqStart = m_originalFreqStart; + m_freqEnd = m_originalFreqEnd; + break; + } + + if (templateSubdivision <= 1){ + m_templateRange.emplace_back(0, numTemplateWindows); + m_numSpectrumsNeeded = numTemplateWindows; + }else{ + // Number of subdivision cannot exceed number of windows in the template. + templateSubdivision = std::min(templateSubdivision, numTemplateWindows); + // num windows of each subdivided template + const size_t num_subWindows = numTemplateWindows / templateSubdivision; + m_numSpectrumsNeeded = num_subWindows; + for(size_t i = 0; i < templateSubdivision; i++){ + const size_t windowStart = i * num_subWindows; + const size_t windowEnd = (i+1) * num_subWindows; + m_templateRange.emplace_back(windowStart, windowEnd); + } + } +// cout << "m_templateRange = " << m_templateRange.size() << endl; +// cout << "m_numSpectrumsNeeded = " << m_numSpectrumsNeeded << endl; + + m_templateNorm = buildTemplateNorm(); +} + +uint64_t SpectrogramMatcher::latestTimestamp() const{ + if (m_spectrums.size() == 0){ + return SIZE_MAX; + } + return m_spectrums.front().stamp; +} + +void SpectrogramMatcher::conv(const float* src, size_t num, float* dst){ +// cout << (size_t)dst % 64 << endl; + + const size_t numConvedFrequencies = num - m_convKernel.size() + 1; + if (num < m_convKernel.size()){ + memset(dst, 0, numConvedFrequencies * sizeof(float)); + return; + } + +#if 0 + for (size_t i = 0; i < num-m_convKernel.size()+1; i++){ + dst[i] = 0.0f; + for (size_t j = 0; j < m_convKernel.size(); j++){ + dst[i] += src[i+j] * m_convKernel[j]; + } + } +#else + Kernels::SpikeConvolution::compute_spike_kernel( + dst, src, num, m_convKernel.data(), m_convKernel.size() + ); +#endif +} + +std::vector SpectrogramMatcher::buildTemplateNorm() const{ + std::vector ret(m_templateRange.size()); + + for (size_t sub_index = 0; sub_index < m_templateRange.size(); sub_index++){ + float sumSqr = 0.0f; + for (size_t i = m_templateRange[sub_index].first; i < m_templateRange[sub_index].second; i++){ + for(size_t j = m_freqStart; j < m_freqEnd; j++){ + const float v = m_template.getWindow(i)[j]; + sumSqr += v * v; + } + } + ret[sub_index] = std::sqrt(sumSqr); + } + + return ret; +} + +bool SpectrogramMatcher::update_to_new_spectrum(AudioSpectrum spectrum){ + if (m_numOriginalFrequencies != spectrum.magnitudes->size()){ + std::cout << "Error: number of frequencies don't match in SpectrogramMatcher::match() " << + m_numOriginalFrequencies << " " << spectrum.magnitudes->size() << std::endl; + return false; + } + + switch(m_mode){ + case Mode::SPIKE_CONV: + { + // Do the conv on new spectrum too. + AlignedVector convedSpectrum(m_template.bufferSize()); + conv(spectrum.magnitudes->data() + m_originalFreqStart, + m_originalFreqEnd - m_originalFreqStart, convedSpectrum.data()); + + spectrum.magnitudes = std::make_unique>(std::move(convedSpectrum)); + break; + } + case Mode::AVERAGE_5: + { + AlignedVector avgedSpectrum(m_template.bufferSize()); + for(size_t j = 0; j < m_template.numFrequencies(); j++){ + const float * rawFreqMag = spectrum.magnitudes->data() + m_originalFreqStart + j*5; + const float newMag = (rawFreqMag[0] + rawFreqMag[1] + rawFreqMag[2] + rawFreqMag[3] + rawFreqMag[4]) / 5.0f; + avgedSpectrum[j] = newMag; + } + spectrum.magnitudes = std::make_unique>(std::move(avgedSpectrum)); + break; + } + case Mode::RAW: + break; + } + + // Compute the norm square (= sum squares) of the spectrum, used for matching: + // TODO: if there will be multiple SpectrogramMatcher running on the same audio stream, can + // move this per-spectrum computation to a shared struct for those matchers to save computation. + float spectrumNormSqr = 0.0f; + for (size_t i = m_freqStart; i < m_freqEnd; i++){ + float mag = (*spectrum.magnitudes)[i]; + spectrumNormSqr += mag * mag; + } + m_spectrumNormSqrs.push_front(spectrumNormSqr); + + m_spectrums.emplace_front(std::move(spectrum)); + + return true; +} + +bool SpectrogramMatcher::update_to_new_spectrums(const std::vector& new_spectrums){ + for (auto it = new_spectrums.rbegin(); it != new_spectrums.rend(); it++){ + if(!update_to_new_spectrum(*it)){ + return false; + } + } + + // pop out too old spectrums + while (m_spectrums.size() > m_numSpectrumsNeeded){ + m_spectrums.pop_back(); + m_spectrumNormSqrs.pop_back(); + } + + return true; +} + +std::pair SpectrogramMatcher::match_sub_template(size_t sub_index) const{ +#if 0 + auto iter = m_spectrums.begin(); + auto iter2 = m_spectrumNormSqrs.begin(); + float streamSumSqr = 0.0f; + float sumMulti = 0.0f; + + const size_t template_start = m_templateRange[sub_index].first; + const size_t template_end = m_templateRange[sub_index].second; + for(size_t i = template_start; i < template_end; i++, iter++, iter2++){ + // match in order from latest window to oldest + const float* templateData = m_template.getWindow(template_end-1-i); + const float* streamData = iter->magnitudes->data(); + streamSumSqr += *iter2; + for(size_t j = m_freqStart; j < m_freqEnd; j++){ + sumMulti += templateData[j] * streamData[j]; + } + } +// cout << "sumMulti = " << sumMulti << ", streamSumSqr = " << streamSumSqr << endl; + const float scale = (streamSumSqr < 1e-6f ? 1.0f : sumMulti / streamSumSqr); + + iter = m_spectrums.begin(); + float sum = 0.0f; + for(size_t i = template_start; i < template_end; i++, iter++){ + // match in order from latest window to oldest + const float* templateData = m_template.getWindow(template_end-1-i); + const float* streamData = iter->magnitudes->data(); + for(size_t j = m_freqStart; j < m_freqEnd; j++){ + float d = templateData[j] - scale * streamData[j]; + sum += d * d; + } + } +#else + // Build matrix. + auto iter = m_spectrums.begin(); + const size_t template_start = m_templateRange[sub_index].first; + const size_t template_end = m_templateRange[sub_index].second; + size_t windows = template_end - template_start; +// cout << windows << endl; +// cout << m_spectrums.size() << " / " << windows << endl; + size_t freqs = m_freqEnd - m_freqStart; + std::vector matrixA(windows); + std::vector matrixT(windows); + for (size_t i = 0; i < windows; i++, iter++){ +// cout << "Template: " << ((size_t)m_template.getWindow(template_end - 1 - i) % 64) << endl; +// cout << "Samples: " << ((size_t)iter->magnitudes->data() % 64) << endl; + matrixT[i] = m_freqStart + m_template.getWindow(windows - 1 - i); + matrixA[i] = m_freqStart + iter->magnitudes->data(); +// cout << matrixT[i] << " : " << matrixA[i] << endl; + } + + // Compute scale. + float scale = Kernels::ScaleInvariantMatrixMatch::compute_scale( + freqs, windows, + matrixA.data(), matrixT.data() + ); + scale = std::min(scale, 1000000); + + // Compute error. + float sum = Kernels::ScaleInvariantMatrixMatch::compute_error( + freqs, windows, + scale, + matrixA.data(), matrixT.data() + ); +#endif + + + float score = sqrt(sum) / m_templateNorm[0]; +// cout << "score = " << score << endl; + score = std::min(score, 1.0); + + return std::make_pair(score, scale); +} + +float SpectrogramMatcher::match(const std::vector& new_spectrums){ + if (!update_to_new_spectrums(new_spectrums)){ + return FLT_MAX; + } + + if (m_spectrums.size() < m_numSpectrumsNeeded){ + return FLT_MAX; + } + + // Check whether the stored spectrums' timestamps are continuous: + size_t curStamp = m_spectrums.front().stamp; + size_t lastStamp = curStamp + 1; + for (const auto& s : m_spectrums){ + if (s.stamp != lastStamp - 1){ + std::cout << "Error: SpectrogramMatcher (" + m_name + ") spectrum timestamps are not continuous:" << std::endl; + + for(const auto& sp : m_spectrums){ + std::cout << sp.stamp << ", "; + } + std::cout << std::endl; + return FLT_MAX; + } + lastStamp--; + } + + if (m_lastStampTested != SIZE_MAX && curStamp <= m_lastStampTested){ + return FLT_MAX; + } + m_lastStampTested = curStamp; + + // Do the match: + float score = FLT_MAX; // the lower the score, the better the match + if (m_templateRange.size() == 1){ + // Match the full template + std::tie(score, m_lastScale) = match_sub_template(0); + }else{ + // Match each individual sub-template + for (size_t sub_template = 0; sub_template < m_templateRange.size(); sub_template++){ + float sub_template_score = FLT_MAX; + float sub_template_scale = 1.0f; + std::tie(sub_template_score, sub_template_scale) = match_sub_template(sub_template); + if (sub_template_score < score){ + score = sub_template_score; + m_lastScale = sub_template_scale; + } + } + } + + return score; +} + +bool SpectrogramMatcher::skip(const std::vector& new_spectrums){ + // Note: ideally we don't want to have any computation while skipping. + // But update_to_new_spectrums() may still do some filtering and vector norm computation. + // Since the computation is relatively small and we won't be skipping lots of frames anyway, + // this should be fine for now. + // We can improve this later. + return update_to_new_spectrums(new_spectrums); +} + +void SpectrogramMatcher::clear(){ + m_spectrums.clear(); + m_spectrumNormSqrs.clear(); + m_lastStampTested = SIZE_MAX; +} + + + + +} diff --git a/SerialPrograms/Source/CommonTools/Audio/SpectrogramMatcher.h b/SerialPrograms/Source/CommonTools/Audio/SpectrogramMatcher.h index 499e15f904..e077e2fbea 100644 --- a/SerialPrograms/Source/CommonTools/Audio/SpectrogramMatcher.h +++ b/SerialPrograms/Source/CommonTools/Audio/SpectrogramMatcher.h @@ -1,134 +1,134 @@ -/* Spectrogram Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_SpectrogramMatcher_H -#define PokemonAutomation_CommonTools_SpectrogramMatcher_H - -#include -#include -#include -#include -#include -#include "CommonFramework/AudioPipeline/AudioFeed.h" -#include "CommonFramework/AudioPipeline/AudioTemplate.h" - -namespace PokemonAutomation{ - -class AudioSpectrum; - -// Load an audio template from disk and use its spectrogram to match the -// spectrogram of the incoming audio stream. -class SpectrogramMatcher{ -public: - enum class Mode{ - // Don't do any processing on each window of spectrum, matching raw spectrums. - RAW, - // Do convolution on each window of spectrum with a peak detection kernel, before matching spectrums. - SPIKE_CONV, - // Do convolution on each window of spectrum with a Gaussian smooth kernel, before matching spectrums. - // GAUSSIAN_CONV, - // Average every 5 frequencies to reduce computation. - AVERAGE_5, - }; - - // audioTemplate: the audio template for the audio stream to match against. - // Use AudioTemplate::loadAudioTemplate() to load a template from disk, or - // use AudioTemplateCache::instance().get_throw(audioResourceRelativePath, sample_rate) to get one from cache. - // mode: which type of spectrogram filtering to use before the actual match. - // sample_rate: audio sample rate. - // low_frequency_filter: only match the frequencies above this threshold. - // templateSubdivision: divide the template into how many sub-templates to match. <= 1 means no subdivision. - SpectrogramMatcher( - std::string name, - AudioTemplate audioTemplate, Mode mode, size_t sample_rate, - double low_frequency_filter, size_t templateSubdivision = 0 - ); - - size_t sample_rate() const{ return m_sample_rate; } - - // Match the newest spectrums and return a match score. - // Newer (larger timestamp) spectrums at beginning of `new_spectrums` while older (smaller - // timestamp) spectrums at the end. - // In invalid cases (internal error or not enough windows), return FLT_MAX - float match(const std::vector& new_spectrums); - - // Pass some spectrums in but don't run match on them. - // Used for skipping some spectrums to avoid unnecessary matching. - // Newer (larger timestamp) spectrums at beginning of `new_spectrums` while older (smaller - // timestamp) spectrums at the end. - // Return true if there is no error. - bool skip(const std::vector& new_spectrums); - - // Clear internal data to be used on another audio stream. - void clear(); - - // How many windows are used for matching. - size_t numMatchedWindows() const { return m_numSpectrumsNeeded; } - - // Return latest timestamp from the stored audio spectrum stream. - // Return SIZE_MAX if there is no stored spectrum yet. - uint64_t latestTimestamp() const; - - // Return the scale found by the matcher to scale the input audio stream to best - // match the template in the last `match()`. - // Return 0.0f if the last scale is not available. - float lastMatchedScale() const { return m_lastScale; } - -private: - void conv(const float* src, size_t num, float* dst); - - // The function to build `m_templateNorm` - std::vector buildTemplateNorm() const; - - // For a given sub-template, return its match score and scaling factor - std::pair match_sub_template(size_t sub_index) const; - - // Update internal data for the next new spectrum. Called by `update_to_new_spectrums()`. - // Return true if there is no error. - bool update_to_new_spectrum(AudioSpectrum newSpectrum); - - // Update internal data for the new specttrums. - // Return true if there is no error. - bool update_to_new_spectrums(const std::vector& new_spectrums); - - - -private: - std::string m_name; - AudioTemplate m_template; - - size_t m_sample_rate; - - size_t m_numOriginalFrequencies = 0; - size_t m_originalFreqStart = 0; - size_t m_originalFreqEnd = 0; - - size_t m_freqStart = 0; - size_t m_freqEnd = 0; - // Temporal ranges of the template to match with. Used when matching a subdivided template. - // If there is no subdivision, it will store only one pair: <0, m_template.numWindows()> - std::vector> m_templateRange; - // For each subdivided template, store its sepctrogram matrix norm - std::vector m_templateNorm; - - Mode m_mode = Mode::RAW; - - std::vector m_convKernel; - - // Spectrums from audio feed. They will be matched against the template. - std::list m_spectrums; - // Norm squares of each spectrum in `m_spectrums`. - std::list m_spectrumNormSqrs; - // How many spectrums needed to store. - size_t m_numSpectrumsNeeded = 0; - - size_t m_lastStampTested = SIZE_MAX; - float m_lastScale = 0.0f; -}; - - -} -#endif +/* Spectrogram Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_SpectrogramMatcher_H +#define PokemonAutomation_CommonTools_SpectrogramMatcher_H + +#include +#include +#include +#include +#include +#include "CommonFramework/AudioPipeline/AudioFeed.h" +#include "CommonFramework/AudioPipeline/AudioTemplate.h" + +namespace PokemonAutomation{ + +class AudioSpectrum; + +// Load an audio template from disk and use its spectrogram to match the +// spectrogram of the incoming audio stream. +class SpectrogramMatcher{ +public: + enum class Mode{ + // Don't do any processing on each window of spectrum, matching raw spectrums. + RAW, + // Do convolution on each window of spectrum with a peak detection kernel, before matching spectrums. + SPIKE_CONV, + // Do convolution on each window of spectrum with a Gaussian smooth kernel, before matching spectrums. + // GAUSSIAN_CONV, + // Average every 5 frequencies to reduce computation. + AVERAGE_5, + }; + + // audioTemplate: the audio template for the audio stream to match against. + // Use AudioTemplate::loadAudioTemplate() to load a template from disk, or + // use AudioTemplateCache::instance().get_throw(audioResourceRelativePath, sample_rate) to get one from cache. + // mode: which type of spectrogram filtering to use before the actual match. + // sample_rate: audio sample rate. + // low_frequency_filter: only match the frequencies above this threshold. + // templateSubdivision: divide the template into how many sub-templates to match. <= 1 means no subdivision. + SpectrogramMatcher( + std::string name, + AudioTemplate audioTemplate, Mode mode, size_t sample_rate, + double low_frequency_filter, size_t templateSubdivision = 0 + ); + + size_t sample_rate() const{ return m_sample_rate; } + + // Match the newest spectrums and return a match score. + // Newer (larger timestamp) spectrums at beginning of `new_spectrums` while older (smaller + // timestamp) spectrums at the end. + // In invalid cases (internal error or not enough windows), return FLT_MAX + float match(const std::vector& new_spectrums); + + // Pass some spectrums in but don't run match on them. + // Used for skipping some spectrums to avoid unnecessary matching. + // Newer (larger timestamp) spectrums at beginning of `new_spectrums` while older (smaller + // timestamp) spectrums at the end. + // Return true if there is no error. + bool skip(const std::vector& new_spectrums); + + // Clear internal data to be used on another audio stream. + void clear(); + + // How many windows are used for matching. + size_t numMatchedWindows() const { return m_numSpectrumsNeeded; } + + // Return latest timestamp from the stored audio spectrum stream. + // Return SIZE_MAX if there is no stored spectrum yet. + uint64_t latestTimestamp() const; + + // Return the scale found by the matcher to scale the input audio stream to best + // match the template in the last `match()`. + // Return 0.0f if the last scale is not available. + float lastMatchedScale() const { return m_lastScale; } + +private: + void conv(const float* src, size_t num, float* dst); + + // The function to build `m_templateNorm` + std::vector buildTemplateNorm() const; + + // For a given sub-template, return its match score and scaling factor + std::pair match_sub_template(size_t sub_index) const; + + // Update internal data for the next new spectrum. Called by `update_to_new_spectrums()`. + // Return true if there is no error. + bool update_to_new_spectrum(AudioSpectrum newSpectrum); + + // Update internal data for the new specttrums. + // Return true if there is no error. + bool update_to_new_spectrums(const std::vector& new_spectrums); + + + +private: + std::string m_name; + AudioTemplate m_template; + + size_t m_sample_rate; + + size_t m_numOriginalFrequencies = 0; + size_t m_originalFreqStart = 0; + size_t m_originalFreqEnd = 0; + + size_t m_freqStart = 0; + size_t m_freqEnd = 0; + // Temporal ranges of the template to match with. Used when matching a subdivided template. + // If there is no subdivision, it will store only one pair: <0, m_template.numWindows()> + std::vector> m_templateRange; + // For each subdivided template, store its sepctrogram matrix norm + std::vector m_templateNorm; + + Mode m_mode = Mode::RAW; + + std::vector m_convKernel; + + // Spectrums from audio feed. They will be matched against the template. + std::list m_spectrums; + // Norm squares of each spectrum in `m_spectrums`. + std::list m_spectrumNormSqrs; + // How many spectrums needed to store. + size_t m_numSpectrumsNeeded = 0; + + size_t m_lastStampTested = SIZE_MAX; + float m_lastScale = 0.0f; +}; + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/DetectionDebouncer.h b/SerialPrograms/Source/CommonTools/DetectionDebouncer.h index d451d9cb9a..ee4f41cf24 100644 --- a/SerialPrograms/Source/CommonTools/DetectionDebouncer.h +++ b/SerialPrograms/Source/CommonTools/DetectionDebouncer.h @@ -1,70 +1,70 @@ -/* Detection Debouncer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_DetectionDebouncer_H -#define PokemonAutomation_CommonTools_DetectionDebouncer_H - -#include -#include -#include "Common/Cpp/Time.h" - -namespace PokemonAutomation{ - - -template -class DetectionDebouncer{ -public: - DetectionDebouncer( - Type initial_state, - std::chrono::milliseconds min_streak, - std::function&& state_reporter - ) - : m_min_streak(min_streak) - , m_state_reporter(std::move(state_reporter)) - , m_current_reported(initial_state) - , m_last_match(current_time()) - {} - - // This is fully thread-safe. - Type get() const{ - return m_current_reported.load(std::memory_order_acquire); - } - - // Only one thread at a time is allowed to call this. - Type push_value(Type value, WallClock timestamp){ - Type current_reported = get(); - - // No change. - if (value == current_reported){ - m_last_match = timestamp; - return current_reported; - } - - // Not long enough. - if (m_last_match + m_min_streak > timestamp){ - return current_reported; - } - - m_state_reporter(value); - m_last_match = timestamp; - m_current_reported.store(value, std::memory_order_release); - return value; - } - - -private: - std::chrono::milliseconds m_min_streak; - std::function m_state_reporter; - - std::atomic m_current_reported; - WallClock m_last_match; -}; - - - - -} -#endif +/* Detection Debouncer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_DetectionDebouncer_H +#define PokemonAutomation_CommonTools_DetectionDebouncer_H + +#include +#include +#include "Common/Cpp/Time.h" + +namespace PokemonAutomation{ + + +template +class DetectionDebouncer{ +public: + DetectionDebouncer( + Type initial_state, + std::chrono::milliseconds min_streak, + std::function&& state_reporter + ) + : m_min_streak(min_streak) + , m_state_reporter(std::move(state_reporter)) + , m_current_reported(initial_state) + , m_last_match(current_time()) + {} + + // This is fully thread-safe. + Type get() const{ + return m_current_reported.load(std::memory_order_acquire); + } + + // Only one thread at a time is allowed to call this. + Type push_value(Type value, WallClock timestamp){ + Type current_reported = get(); + + // No change. + if (value == current_reported){ + m_last_match = timestamp; + return current_reported; + } + + // Not long enough. + if (m_last_match + m_min_streak > timestamp){ + return current_reported; + } + + m_state_reporter(value); + m_last_match = timestamp; + m_current_reported.store(value, std::memory_order_release); + return value; + } + + +private: + std::chrono::milliseconds m_min_streak; + std::function m_state_reporter; + + std::atomic m_current_reported; + WallClock m_last_match; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/FailureWatchdog.h b/SerialPrograms/Source/CommonTools/FailureWatchdog.h index c1ef88cf7d..05f330cdf2 100644 --- a/SerialPrograms/Source/CommonTools/FailureWatchdog.h +++ b/SerialPrograms/Source/CommonTools/FailureWatchdog.h @@ -1,112 +1,112 @@ -/* Failure Watchdog - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_FailureWatchdog_H -#define PokemonAutomation_CommonTools_FailureWatchdog_H - -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Time.h" -#include "Common/Cpp/Exceptions.h" - -namespace PokemonAutomation{ - - - - - -class FailureWatchdog{ -public: - FailureWatchdog( - Logger& logger, - std::string failure_message, - uint64_t min_count = 5, - double min_success_rate = 0.5, - std::chrono::seconds time_limit = std::chrono::seconds(120) - ) - : m_logger(logger) - , m_failure_message(std::move(failure_message)) - , m_min_count(min_count) - , m_min_success_rate(min_success_rate) - , m_time_limit(time_limit) - { - restart(); - } - void restart(){ - m_expiration = current_time() + m_time_limit; - m_expired = false; - m_successes = 0; - m_total = 0; - } - - void push_result(bool success){ - m_successes += success ? 1 : 0; - m_total++; - if (success || m_expired){ - return; - } - - WallClock current = current_time(); - if (current >= m_expiration){ - m_expired = true; - } - - if (m_total < m_min_count){ - return; - } - - double threshold = (double)m_total * m_min_success_rate; - if ((double)m_successes >= threshold){ - return; - } - - - throw UserSetupError(m_logger, m_failure_message); - } - - -private: - Logger& m_logger; - std::string m_failure_message; - uint64_t m_min_count; - double m_min_success_rate; - WallDuration m_time_limit; - WallClock m_expiration; - bool m_expired; - - uint64_t m_successes; - uint64_t m_total; -}; - - - - - -class OcrFailureWatchdog : public FailureWatchdog{ -public: - OcrFailureWatchdog( - Logger& logger, - std::string failure_message = "Too many text recognition errors. Did you set the correct language?", - uint64_t min_count = 5, - double min_success_rate = 0.5, - std::chrono::seconds time_limit = std::chrono::seconds(120) - ) - : FailureWatchdog( - logger, - std::move(failure_message), - min_count, - min_success_rate, - time_limit - ) - {} -}; - - - - - - -} -#endif +/* Failure Watchdog + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_FailureWatchdog_H +#define PokemonAutomation_CommonTools_FailureWatchdog_H + +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Time.h" +#include "Common/Cpp/Exceptions.h" + +namespace PokemonAutomation{ + + + + + +class FailureWatchdog{ +public: + FailureWatchdog( + Logger& logger, + std::string failure_message, + uint64_t min_count = 5, + double min_success_rate = 0.5, + std::chrono::seconds time_limit = std::chrono::seconds(120) + ) + : m_logger(logger) + , m_failure_message(std::move(failure_message)) + , m_min_count(min_count) + , m_min_success_rate(min_success_rate) + , m_time_limit(time_limit) + { + restart(); + } + void restart(){ + m_expiration = current_time() + m_time_limit; + m_expired = false; + m_successes = 0; + m_total = 0; + } + + void push_result(bool success){ + m_successes += success ? 1 : 0; + m_total++; + if (success || m_expired){ + return; + } + + WallClock current = current_time(); + if (current >= m_expiration){ + m_expired = true; + } + + if (m_total < m_min_count){ + return; + } + + double threshold = (double)m_total * m_min_success_rate; + if ((double)m_successes >= threshold){ + return; + } + + + throw UserSetupError(m_logger, m_failure_message); + } + + +private: + Logger& m_logger; + std::string m_failure_message; + uint64_t m_min_count; + double m_min_success_rate; + WallDuration m_time_limit; + WallClock m_expiration; + bool m_expired; + + uint64_t m_successes; + uint64_t m_total; +}; + + + + + +class OcrFailureWatchdog : public FailureWatchdog{ +public: + OcrFailureWatchdog( + Logger& logger, + std::string failure_message = "Too many text recognition errors. Did you set the correct language?", + uint64_t min_count = 5, + double min_success_rate = 0.5, + std::chrono::seconds time_limit = std::chrono::seconds(120) + ) + : FailureWatchdog( + logger, + std::move(failure_message), + min_count, + min_success_rate, + time_limit + ) + {} +}; + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/GlobalInferenceRunner.cpp b/SerialPrograms/Source/CommonTools/GlobalInferenceRunner.cpp deleted file mode 100644 index 4b9c28c83f..0000000000 --- a/SerialPrograms/Source/CommonTools/GlobalInferenceRunner.cpp +++ /dev/null @@ -1,27 +0,0 @@ -/* Global Inference Runner - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Options/Environment/PerformanceOptions.h" -#include "GlobalInferenceRunner.h" - -namespace PokemonAutomation{ - - - -ParallelTaskRunner& global_inference_runner(){ - static ParallelTaskRunner runner( - [](){ - GlobalSettings::instance().PERFORMANCE->NORMAL_INFERENCE_PRIORITY.set_on_this_thread(); - }, - 0, std::thread::hardware_concurrency() - ); - return runner; -} - - - -} diff --git a/SerialPrograms/Source/CommonTools/GlobalInferenceRunner.h b/SerialPrograms/Source/CommonTools/GlobalInferenceRunner.h deleted file mode 100644 index 98364e798b..0000000000 --- a/SerialPrograms/Source/CommonTools/GlobalInferenceRunner.h +++ /dev/null @@ -1,21 +0,0 @@ -/* Global Inference Runner - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_GlobalInferenceRunner_H -#define PokemonAutomation_CommonTools_GlobalInferenceRunner_H - -#include "Common/Cpp/Concurrency/ParallelTaskRunner.h" - -namespace PokemonAutomation{ - - - -ParallelTaskRunner& global_inference_runner(); - - - -} -#endif diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/CroppedImageDictionaryMatcher.cpp b/SerialPrograms/Source/CommonTools/ImageMatch/CroppedImageDictionaryMatcher.cpp index a638556fa2..40dd4daa72 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/CroppedImageDictionaryMatcher.cpp +++ b/SerialPrograms/Source/CommonTools/ImageMatch/CroppedImageDictionaryMatcher.cpp @@ -1,138 +1,138 @@ -/* Cropped Image Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Tools/DebugDumper.h" -#include "ImageCropper.h" -//#include "ImageDiff.h" -#include "CroppedImageDictionaryMatcher.h" - -#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace ImageMatch{ - - - -CroppedImageDictionaryMatcher::CroppedImageDictionaryMatcher(const WeightedExactImageMatcher::InverseStddevWeight& weight) - : m_weight(weight) -{} -void CroppedImageDictionaryMatcher::add(const std::string& slug, const ImageViewRGB32& image){ - if (!image){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Null image."); - } - auto iter = m_database.find(slug); - if (iter != m_database.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate slug: " + slug); - } - - ImageViewRGB32 cropped = trim_image_alpha(image); - -#if 0 - if (slug == "hamburger"){ - image.save("matcher-original.png"); - cropped.save("matcher-cropped.png"); - } -#endif - - iter = m_database.emplace( - std::piecewise_construct, - std::forward_as_tuple(slug), - std::forward_as_tuple(cropped.copy(), m_weight) - ).first; -// cout << iter->first << ": " << iter->second.stats().stddev.sum() << endl; -} - - - -ImageMatchResult CroppedImageDictionaryMatcher::match( - const ImageViewRGB32& image, - double alpha_spread -) const{ - ImageMatchResult results; - if (!image){ - return results; - } - - if (PreloadSettings::debug().IMAGE_DICTIONARY_MATCHING){ - std::cout << "CroppedImageDictionaryMatcher: match input image: " << std::endl; - dump_debug_image(global_logger_command_line(), "CommonFramework/CroppedImageDictionaryMatcher", "match_input", image); - } - - std::vector crops = get_crop_candidates(image); - - if (PreloadSettings::debug().IMAGE_DICTIONARY_MATCHING){ -// size_t c = 0; - for (const ImageViewRGB32& crop : crops){ -// std::cout << "CroppedImageDictionaryMatcher: process input" << c << "image with background " << crop.background.to_string() << std::endl; - dump_debug_image(global_logger_command_line(), "CommonFramework/CroppedImageDictionaryMatcher", "match_input_processed", crop); -// c++; - } - } - - - - for (const auto& item : m_database){ - for (const ImageViewRGB32& crop : crops){ - double alpha = item.second.diff(crop); - results.add(alpha, item.first); - results.clear_beyond_spread(alpha_spread); - } - } - - - -#if 0 - Color background; - ImageViewRGB32 processed = cropped[0].image; - background = cropped[0].background; - -// ImageRGB32 processed = process_image(image, background); - if (PreloadSettings::debug().IMAGE_DICTIONARY_MATCHING){ - std::cout << "CroppedImageDictionaryMatcher: process input image with background " << background.to_string() << std::endl; - dump_debug_image(global_logger_command_line(), "CommonFramework/CroppedImageDictionaryMatcher", "match_input_processed", processed); - } - - processed.save("processed.png"); - - for (const auto& item : m_database){ -#if 0 - if (item.first != "onion"){ - continue; - } -#endif - double alpha = item.second.diff(processed); - results.add(alpha, item.first); - results.clear_beyond_spread(alpha_spread); - } -#endif - - if (PreloadSettings::debug().IMAGE_DICTIONARY_MATCHING){ - std::cout << "CroppedImageDictionaryMatcher: results: " << std::endl; - size_t count = 0; - for(const auto& result : results.results){ - std::cout << "alpha=" << result.first << ", " << result.second << std::endl; - const auto& image_template = m_database.find(result.second)->second.image_template(); - dump_debug_image(global_logger_command_line(), "CommonFramework/CroppedImageDictionaryMatcher", "match_result_" + std::to_string(count) + "_" + result.second, image_template); - ++count; - } - } - return results; -} - - - - - - -} -} +/* Cropped Image Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Tools/DebugDumper.h" +#include "ImageCropper.h" +//#include "ImageDiff.h" +#include "CroppedImageDictionaryMatcher.h" + +#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace ImageMatch{ + + + +CroppedImageDictionaryMatcher::CroppedImageDictionaryMatcher(const WeightedExactImageMatcher::InverseStddevWeight& weight) + : m_weight(weight) +{} +void CroppedImageDictionaryMatcher::add(const std::string& slug, const ImageViewRGB32& image){ + if (!image){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Null image."); + } + auto iter = m_database.find(slug); + if (iter != m_database.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate slug: " + slug); + } + + ImageViewRGB32 cropped = trim_image_alpha(image); + +#if 0 + if (slug == "hamburger"){ + image.save("matcher-original.png"); + cropped.save("matcher-cropped.png"); + } +#endif + + iter = m_database.emplace( + std::piecewise_construct, + std::forward_as_tuple(slug), + std::forward_as_tuple(cropped.copy(), m_weight) + ).first; +// cout << iter->first << ": " << iter->second.stats().stddev.sum() << endl; +} + + + +ImageMatchResult CroppedImageDictionaryMatcher::match( + const ImageViewRGB32& image, + double alpha_spread +) const{ + ImageMatchResult results; + if (!image){ + return results; + } + + if (PreloadSettings::debug().IMAGE_DICTIONARY_MATCHING){ + std::cout << "CroppedImageDictionaryMatcher: match input image: " << std::endl; + dump_debug_image(global_logger_command_line(), "CommonFramework/CroppedImageDictionaryMatcher", "match_input", image); + } + + std::vector crops = get_crop_candidates(image); + + if (PreloadSettings::debug().IMAGE_DICTIONARY_MATCHING){ +// size_t c = 0; + for (const ImageViewRGB32& crop : crops){ +// std::cout << "CroppedImageDictionaryMatcher: process input" << c << "image with background " << crop.background.to_string() << std::endl; + dump_debug_image(global_logger_command_line(), "CommonFramework/CroppedImageDictionaryMatcher", "match_input_processed", crop); +// c++; + } + } + + + + for (const auto& item : m_database){ + for (const ImageViewRGB32& crop : crops){ + double alpha = item.second.diff(crop); + results.add(alpha, item.first); + results.clear_beyond_spread(alpha_spread); + } + } + + + +#if 0 + Color background; + ImageViewRGB32 processed = cropped[0].image; + background = cropped[0].background; + +// ImageRGB32 processed = process_image(image, background); + if (PreloadSettings::debug().IMAGE_DICTIONARY_MATCHING){ + std::cout << "CroppedImageDictionaryMatcher: process input image with background " << background.to_string() << std::endl; + dump_debug_image(global_logger_command_line(), "CommonFramework/CroppedImageDictionaryMatcher", "match_input_processed", processed); + } + + processed.save("processed.png"); + + for (const auto& item : m_database){ +#if 0 + if (item.first != "onion"){ + continue; + } +#endif + double alpha = item.second.diff(processed); + results.add(alpha, item.first); + results.clear_beyond_spread(alpha_spread); + } +#endif + + if (PreloadSettings::debug().IMAGE_DICTIONARY_MATCHING){ + std::cout << "CroppedImageDictionaryMatcher: results: " << std::endl; + size_t count = 0; + for(const auto& result : results.results){ + std::cout << "alpha=" << result.first << ", " << result.second << std::endl; + const auto& image_template = m_database.find(result.second)->second.image_template(); + dump_debug_image(global_logger_command_line(), "CommonFramework/CroppedImageDictionaryMatcher", "match_result_" + std::to_string(count) + "_" + result.second, image_template); + ++count; + } + } + return results; +} + + + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/CroppedImageDictionaryMatcher.h b/SerialPrograms/Source/CommonTools/ImageMatch/CroppedImageDictionaryMatcher.h index 0c2b21119f..575dfaca5d 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/CroppedImageDictionaryMatcher.h +++ b/SerialPrograms/Source/CommonTools/ImageMatch/CroppedImageDictionaryMatcher.h @@ -1,43 +1,43 @@ -/* Cropped Image Dictionary Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_CroppedImageDictionaryMatcher_H -#define PokemonAutomation_CommonTools_CroppedImageDictionaryMatcher_H - -#include -#include "ImageMatchResult.h" -#include "ExactImageMatcher.h" - -namespace PokemonAutomation{ -namespace ImageMatch{ - -// Similar to `ExactImageDictionaryMatcher` but will crop the image based on background pixel colors before matching. -class CroppedImageDictionaryMatcher{ -public: - CroppedImageDictionaryMatcher( - const WeightedExactImageMatcher::InverseStddevWeight& weight = WeightedExactImageMatcher::InverseStddevWeight() - ); - virtual ~CroppedImageDictionaryMatcher() = default; - - void add(const std::string& slug, const ImageViewRGB32& image); - - ImageMatchResult match(const ImageViewRGB32& image, double alpha_spread) const; - - -protected: - // Return potential crops for this image. - virtual std::vector get_crop_candidates(const ImageViewRGB32& image) const = 0; - - -private: - WeightedExactImageMatcher::InverseStddevWeight m_weight; - std::map m_database; -}; - - -} -} -#endif +/* Cropped Image Dictionary Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_CroppedImageDictionaryMatcher_H +#define PokemonAutomation_CommonTools_CroppedImageDictionaryMatcher_H + +#include +#include "ImageMatchResult.h" +#include "ExactImageMatcher.h" + +namespace PokemonAutomation{ +namespace ImageMatch{ + +// Similar to `ExactImageDictionaryMatcher` but will crop the image based on background pixel colors before matching. +class CroppedImageDictionaryMatcher{ +public: + CroppedImageDictionaryMatcher( + const WeightedExactImageMatcher::InverseStddevWeight& weight = WeightedExactImageMatcher::InverseStddevWeight() + ); + virtual ~CroppedImageDictionaryMatcher() = default; + + void add(const std::string& slug, const ImageViewRGB32& image); + + ImageMatchResult match(const ImageViewRGB32& image, double alpha_spread) const; + + +protected: + // Return potential crops for this image. + virtual std::vector get_crop_candidates(const ImageViewRGB32& image) const = 0; + + +private: + WeightedExactImageMatcher::InverseStddevWeight m_weight; + std::map m_database; +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageDictionaryMatcher.cpp b/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageDictionaryMatcher.cpp index 014d273a2a..a77a8793a9 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageDictionaryMatcher.cpp +++ b/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageDictionaryMatcher.cpp @@ -1,196 +1,196 @@ -/* Exact Image Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "ExactImageDictionaryMatcher.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace ImageMatch{ - - - -// Generate candidate images to be matched against by translating the input image area -// (`box` on `screen`) around. -// The returned candidate images are scaled to match template shape `dimension`. -// `tolerance`: how much translation variances to produce. -// e.g. tolerance of 1 means translating the candidate images around so that it can match -// the template with at most 1 pixel off on the template image. -std::vector make_image_set( - const ImageViewRGB32& screen, - const ImageFloatBox& box, - size_t width, size_t height, - size_t tolerance -){ - double num_template_pixels = (double)width * height; - double num_image_pixels = screen.width() * box.width * screen.height() * box.height; -// cout << std::sqrt(image / num_template_pixels) << endl; - // scale: roughly the relative size between the input image and the template. - // e.g. if the input image is 10 x 6 and template is 5 x 3, then `scale` is 2. - ptrdiff_t scale = (ptrdiff_t)(std::sqrt(num_image_pixels / num_template_pixels) + 0.5); - scale = std::max(scale, 1); - - std::vector ret; - ptrdiff_t limit = (ptrdiff_t)tolerance; - for (ptrdiff_t y = -limit; y <= limit; y++){ - for (ptrdiff_t x = -limit; x <= limit; x++){ -// if (x != 0 || y != -4){ -// continue; -// } - - ret.emplace_back( - extract_box_reference(screen, box, x * scale, y * scale).scale_to(width, height) - ); -// cout << "make_image_set(): image = " << ret.back().width() << " x " << ret.back().height() << endl; -// if (x == 0 && y == 0){ -// ret.back().save("image.png"); -// } - } - } -// cout << "size = " << ret.size() << endl; - return ret; -} - - - -ExactImageDictionaryMatcher::ExactImageDictionaryMatcher(const WeightedExactImageMatcher::InverseStddevWeight& weight) - : m_weight(weight) -{} -void ExactImageDictionaryMatcher::add(const std::string& slug, ImageRGB32 image){ - if (!image){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Null image."); - } - if (m_width != 0){ - if (image.width() != m_width || image.height() != m_height){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching dimensions."); - } - }else{ - m_width = image.width(); - m_height = image.height(); - } - auto iter = m_database.find(slug); - if (iter != m_database.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate slug: " + slug); - } - - m_database.emplace( - std::piecewise_construct, - std::forward_as_tuple(slug), - std::forward_as_tuple(std::move(image), m_weight) - ); -// if (slug == "linoone-galar" || slug == "coalossal"){ -// cout << slug << " = " << m_database.find(slug)->second.stats().stddev.sum() << endl; -// } -} - - -#if 0 -void ExactImageDictionaryMatcher::scale_to_dimensions(ImageRGB32& image) const{ - if (image.width() != m_width || image.height() != m_height){ - image = image.scale_to(m_width, m_height); - } - } -} -#endif - - -double ExactImageDictionaryMatcher::compare( - const WeightedExactImageMatcher& sprite, - const std::vector& images -){ -// sprite.m_image.save("sprite.png"); -// images[0].save("image.png"); - - double best = 10000; - for (const ImageRGB32& image : images){ - double rmsd_alpha = sprite.diff(image); -// cout << rmsd_alpha << endl; -// if (rmsd_alpha < 0.38){ -// sprite.m_image.save("sprite.png"); -// image.save("image.png"); -// } - best = std::min(best, rmsd_alpha); - } -// cout << best << endl; - return best; -} - -ImageMatchResult ExactImageDictionaryMatcher::match( - const ImageViewRGB32& image, const ImageFloatBox& box, - size_t tolerance, - double alpha_spread -) const{ - ImageMatchResult results; - if (!image){ - return results; - } - - // Translate the input image area a bit to careate matching candidates. - std::vector image_set = make_image_set(image, box, m_width, m_height, tolerance); - for (const auto& item : m_database){ -// if (item.first != "linoone-galar"){ -// continue; -// } - double alpha = compare(item.second, image_set); - results.add(alpha, item.first); - results.clear_beyond_spread(alpha_spread); - } - - return results; -} - -ImageMatchResult ExactImageDictionaryMatcher::subset_match( - const std::vector& subset, - const ImageViewRGB32& image, const ImageFloatBox& box, - size_t tolerance, - double alpha_spread -) const{ - ImageMatchResult results; - if (!image){ - return results; - } - - // Translate the input image area a bit to careate matching candidates. - std::vector image_set = make_image_set(image, box, m_width, m_height, tolerance); - for (const auto& slug : subset){ - const auto& matcher = image_matcher(slug); - double alpha = compare(matcher, image_set); - results.add(alpha, slug); - results.clear_beyond_spread(alpha_spread); - } - - return results; -} - -ImageViewRGB32 ExactImageDictionaryMatcher::image_template(const std::string& slug) const{ - auto it = m_database.find(slug); - if (it == m_database.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown slug: " + slug); - } - - return it->second.image_template(); -} - -const WeightedExactImageMatcher& ExactImageDictionaryMatcher::image_matcher(const std::string& slug) const{ - auto it = m_database.find(slug); - if (it == m_database.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown slug: " + slug); - } - - return it->second; -} - - -} -} +/* Exact Image Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "ExactImageDictionaryMatcher.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace ImageMatch{ + + + +// Generate candidate images to be matched against by translating the input image area +// (`box` on `screen`) around. +// The returned candidate images are scaled to match template shape `dimension`. +// `tolerance`: how much translation variances to produce. +// e.g. tolerance of 1 means translating the candidate images around so that it can match +// the template with at most 1 pixel off on the template image. +std::vector make_image_set( + const ImageViewRGB32& screen, + const ImageFloatBox& box, + size_t width, size_t height, + size_t tolerance +){ + double num_template_pixels = (double)width * height; + double num_image_pixels = screen.width() * box.width * screen.height() * box.height; +// cout << std::sqrt(image / num_template_pixels) << endl; + // scale: roughly the relative size between the input image and the template. + // e.g. if the input image is 10 x 6 and template is 5 x 3, then `scale` is 2. + ptrdiff_t scale = (ptrdiff_t)(std::sqrt(num_image_pixels / num_template_pixels) + 0.5); + scale = std::max(scale, 1); + + std::vector ret; + ptrdiff_t limit = (ptrdiff_t)tolerance; + for (ptrdiff_t y = -limit; y <= limit; y++){ + for (ptrdiff_t x = -limit; x <= limit; x++){ +// if (x != 0 || y != -4){ +// continue; +// } + + ret.emplace_back( + extract_box_reference(screen, box, x * scale, y * scale).scale_to(width, height) + ); +// cout << "make_image_set(): image = " << ret.back().width() << " x " << ret.back().height() << endl; +// if (x == 0 && y == 0){ +// ret.back().save("image.png"); +// } + } + } +// cout << "size = " << ret.size() << endl; + return ret; +} + + + +ExactImageDictionaryMatcher::ExactImageDictionaryMatcher(const WeightedExactImageMatcher::InverseStddevWeight& weight) + : m_weight(weight) +{} +void ExactImageDictionaryMatcher::add(const std::string& slug, ImageRGB32 image){ + if (!image){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Null image."); + } + if (m_width != 0){ + if (image.width() != m_width || image.height() != m_height){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching dimensions."); + } + }else{ + m_width = image.width(); + m_height = image.height(); + } + auto iter = m_database.find(slug); + if (iter != m_database.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate slug: " + slug); + } + + m_database.emplace( + std::piecewise_construct, + std::forward_as_tuple(slug), + std::forward_as_tuple(std::move(image), m_weight) + ); +// if (slug == "linoone-galar" || slug == "coalossal"){ +// cout << slug << " = " << m_database.find(slug)->second.stats().stddev.sum() << endl; +// } +} + + +#if 0 +void ExactImageDictionaryMatcher::scale_to_dimensions(ImageRGB32& image) const{ + if (image.width() != m_width || image.height() != m_height){ + image = image.scale_to(m_width, m_height); + } + } +} +#endif + + +double ExactImageDictionaryMatcher::compare( + const WeightedExactImageMatcher& sprite, + const std::vector& images +){ +// sprite.m_image.save("sprite.png"); +// images[0].save("image.png"); + + double best = 10000; + for (const ImageRGB32& image : images){ + double rmsd_alpha = sprite.diff(image); +// cout << rmsd_alpha << endl; +// if (rmsd_alpha < 0.38){ +// sprite.m_image.save("sprite.png"); +// image.save("image.png"); +// } + best = std::min(best, rmsd_alpha); + } +// cout << best << endl; + return best; +} + +ImageMatchResult ExactImageDictionaryMatcher::match( + const ImageViewRGB32& image, const ImageFloatBox& box, + size_t tolerance, + double alpha_spread +) const{ + ImageMatchResult results; + if (!image){ + return results; + } + + // Translate the input image area a bit to careate matching candidates. + std::vector image_set = make_image_set(image, box, m_width, m_height, tolerance); + for (const auto& item : m_database){ +// if (item.first != "linoone-galar"){ +// continue; +// } + double alpha = compare(item.second, image_set); + results.add(alpha, item.first); + results.clear_beyond_spread(alpha_spread); + } + + return results; +} + +ImageMatchResult ExactImageDictionaryMatcher::subset_match( + const std::vector& subset, + const ImageViewRGB32& image, const ImageFloatBox& box, + size_t tolerance, + double alpha_spread +) const{ + ImageMatchResult results; + if (!image){ + return results; + } + + // Translate the input image area a bit to careate matching candidates. + std::vector image_set = make_image_set(image, box, m_width, m_height, tolerance); + for (const auto& slug : subset){ + const auto& matcher = image_matcher(slug); + double alpha = compare(matcher, image_set); + results.add(alpha, slug); + results.clear_beyond_spread(alpha_spread); + } + + return results; +} + +ImageViewRGB32 ExactImageDictionaryMatcher::image_template(const std::string& slug) const{ + auto it = m_database.find(slug); + if (it == m_database.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown slug: " + slug); + } + + return it->second.image_template(); +} + +const WeightedExactImageMatcher& ExactImageDictionaryMatcher::image_matcher(const std::string& slug) const{ + auto it = m_database.find(slug); + if (it == m_database.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown slug: " + slug); + } + + return it->second; +} + + +} +} diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageDictionaryMatcher.h b/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageDictionaryMatcher.h index 7e72f7e272..94e1658d88 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageDictionaryMatcher.h +++ b/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageDictionaryMatcher.h @@ -1,89 +1,89 @@ -/* Exact Image Dictionary Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_ExactImageDictionaryMatcher_H -#define PokemonAutomation_CommonTools_ExactImageDictionaryMatcher_H - -#include -#include -#include -#include "CommonFramework/Logging/Logger.h" -#include "ImageMatchResult.h" -#include "ExactImageMatcher.h" - -namespace PokemonAutomation{ - class ImageViewRGB32; - struct ImageFloatBox; -namespace ImageMatch{ - - -// Build a dictionary of image templates and use them to match against images. -// All the image templates must have the same image shape. -class ExactImageDictionaryMatcher{ -public: - ExactImageDictionaryMatcher(const WeightedExactImageMatcher::InverseStddevWeight& weight); - - // Add an image template. - // Do not allow one slug to have more than one template. - void add(const std::string& slug, ImageRGB32 image_template); - -// QSize dimensions() const{ return m_dimensions; } - - // Scale image to match the size of the templates. -// void scale_to_dimensions(ImageRGB32& image) const; - - // Match the `box` area on `image` against the stored template dictionary. - // `tolerance`: how much translation noise to tolerate. tolerance of 1 means to allow 1 pixel - // off on the template when matching. - // `alpha_spread`: only retain match results that no larger than the best match score + - // `max_alpha_spread`. - // - // Note: the dictionary must contain at least one template. - // The input image area will be scaled to the template shape before matching. - // The brightness of the input image and the stddev of the template is compensated during - // matching. - ImageMatchResult match( - const ImageViewRGB32& image, const ImageFloatBox& box, - size_t tolerance, - double alpha_spread - ) const; - - // Match on a subset of the templates. - // See match() for deatils on how the matching is done against a template. - ImageMatchResult subset_match( - const std::vector& subset, - const ImageViewRGB32& image, const ImageFloatBox& box, - size_t tolerance, - double alpha_spread - ) const; - - ImageViewRGB32 image_template(const std::string& slug) const; - - const WeightedExactImageMatcher& image_matcher(const std::string& slug) const; - - -private: - static double compare( - const WeightedExactImageMatcher& sprite, - const std::vector& images - ); - - -private: - WeightedExactImageMatcher::InverseStddevWeight m_weight; - // The size of the image templates. - // Each template must have the same size. -// QSize m_dimensions; - size_t m_width = 0; - size_t m_height = 0; - std::map m_database; -}; - - - -} -} -#endif +/* Exact Image Dictionary Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_ExactImageDictionaryMatcher_H +#define PokemonAutomation_CommonTools_ExactImageDictionaryMatcher_H + +#include +#include +#include +#include "CommonFramework/Logging/Logger.h" +#include "ImageMatchResult.h" +#include "ExactImageMatcher.h" + +namespace PokemonAutomation{ + class ImageViewRGB32; + struct ImageFloatBox; +namespace ImageMatch{ + + +// Build a dictionary of image templates and use them to match against images. +// All the image templates must have the same image shape. +class ExactImageDictionaryMatcher{ +public: + ExactImageDictionaryMatcher(const WeightedExactImageMatcher::InverseStddevWeight& weight); + + // Add an image template. + // Do not allow one slug to have more than one template. + void add(const std::string& slug, ImageRGB32 image_template); + +// QSize dimensions() const{ return m_dimensions; } + + // Scale image to match the size of the templates. +// void scale_to_dimensions(ImageRGB32& image) const; + + // Match the `box` area on `image` against the stored template dictionary. + // `tolerance`: how much translation noise to tolerate. tolerance of 1 means to allow 1 pixel + // off on the template when matching. + // `alpha_spread`: only retain match results that no larger than the best match score + + // `max_alpha_spread`. + // + // Note: the dictionary must contain at least one template. + // The input image area will be scaled to the template shape before matching. + // The brightness of the input image and the stddev of the template is compensated during + // matching. + ImageMatchResult match( + const ImageViewRGB32& image, const ImageFloatBox& box, + size_t tolerance, + double alpha_spread + ) const; + + // Match on a subset of the templates. + // See match() for deatils on how the matching is done against a template. + ImageMatchResult subset_match( + const std::vector& subset, + const ImageViewRGB32& image, const ImageFloatBox& box, + size_t tolerance, + double alpha_spread + ) const; + + ImageViewRGB32 image_template(const std::string& slug) const; + + const WeightedExactImageMatcher& image_matcher(const std::string& slug) const; + + +private: + static double compare( + const WeightedExactImageMatcher& sprite, + const std::vector& images + ); + + +private: + WeightedExactImageMatcher::InverseStddevWeight m_weight; + // The size of the image templates. + // Each template must have the same size. +// QSize m_dimensions; + size_t m_width = 0; + size_t m_height = 0; + std::map m_database; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageMatcher.cpp b/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageMatcher.cpp index f08a44d16d..fc101bff81 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageMatcher.cpp +++ b/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageMatcher.cpp @@ -1,140 +1,140 @@ -/* Image Match Preprocessed Data - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "ExactImageMatcher.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace ImageMatch{ - - -ExactImageMatcher::ExactImageMatcher(ImageRGB32 image) - : m_image(std::move(image)) - , m_stats(image_stats(m_image)) -{ - if (!m_image){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is null."); - } -// cout << m_stats.stddev.sum() << endl; -} - -ImageRGB32 ExactImageMatcher::scale_template_brightness(const ImageViewRGB32& image) const{ - FloatPixel image_brightness = pixel_average(image, m_image); - FloatPixel scale = image_brightness / m_stats.average; - - if (std::isnan(scale.r)) scale.r = 1.0; - if (std::isnan(scale.g)) scale.g = 1.0; - if (std::isnan(scale.b)) scale.b = 1.0; - scale.bound(0.85, 1.15); - - ImageRGB32 ret = m_image.copy(); - scale_brightness(ret, scale); -// ret.save("test.png"); - return ret; -} - - -double ExactImageMatcher::rmsd(const ImageViewRGB32& image) const{ - if (!image){ - return 1000.; - } - -// image.save("test.png"); - -// cout << "ExactImageMatcher::rmsd(): image = " << image.width() << " x " << image.height() << endl; - ImageRGB32 scaled = image.scale_to(m_image.width(), m_image.height()); -// cout << "ExactImageMatcher::rmsd(): scaled = " << scaled.width() << " x " << scaled.height() << endl; - ImageRGB32 reference = scale_template_brightness(scaled); - -#if 0 - static int c = 0; - image.save("test-" + std::to_string(c) + "-image.png"); - reference.save("test-" + std::to_string(c) + "-sprite.png"); - c++; -#endif - - double rmsd = pixel_RMSD(reference, scaled); -// cout << "rmsd = " << rmsd << endl; - return rmsd; -} -double ExactImageMatcher::rmsd(const ImageViewRGB32& image, Color background) const{ - if (!image){ - return 1000.; - } - ImageRGB32 scaled = image.scale_to(m_image.width(), m_image.height()); - ImageRGB32 reference = scale_template_brightness(scaled); - -#if 0 - static int c = 0; - scaled.save("test-" + std::to_string(c) + "-image.png"); - reference.save("test-" + std::to_string(c) + "-sprite.png"); - c++; -#endif - - return pixel_RMSD(reference, scaled, background); -} -double ExactImageMatcher::rmsd_masked(const ImageViewRGB32& image) const{ - if (!image){ - return 1000.; - } - ImageRGB32 scaled = image.scale_to(m_image.width(), m_image.height()); - ImageRGB32 reference = scale_template_brightness(scaled); - return pixel_RMSD_masked(reference, scaled); -} - - - - -WeightedExactImageMatcher::WeightedExactImageMatcher(ImageRGB32 image, const InverseStddevWeight& weight) - : ExactImageMatcher(std::move(image)) - , m_multiplier(1. / (m_stats.stddev.sum() * weight.stddev_coefficient + weight.offset)) -{} - - -double WeightedExactImageMatcher::diff(const ImageViewRGB32& image) const{ - if (!image){ - return 1000.; - } - return rmsd(image) * m_multiplier; -} -double WeightedExactImageMatcher::diff(const ImageViewRGB32& image, Color background) const{ - if (!image){ - return 1000.; - } - return rmsd(image, background) * m_multiplier; -} -double WeightedExactImageMatcher::diff_masked(const ImageViewRGB32& image) const{ - if (!image){ - return 1000.; - } - return rmsd_masked(image) * m_multiplier; -} - - - - - - - - - - - - - - - - - - -} -} +/* Image Match Preprocessed Data + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "ExactImageMatcher.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace ImageMatch{ + + +ExactImageMatcher::ExactImageMatcher(ImageRGB32 image) + : m_image(std::move(image)) + , m_stats(image_stats(m_image)) +{ + if (!m_image){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is null."); + } +// cout << m_stats.stddev.sum() << endl; +} + +ImageRGB32 ExactImageMatcher::scale_template_brightness(const ImageViewRGB32& image) const{ + FloatPixel image_brightness = pixel_average(image, m_image); + FloatPixel scale = image_brightness / m_stats.average; + + if (std::isnan(scale.r)) scale.r = 1.0; + if (std::isnan(scale.g)) scale.g = 1.0; + if (std::isnan(scale.b)) scale.b = 1.0; + scale.bound(0.85, 1.15); + + ImageRGB32 ret = m_image.copy(); + scale_brightness(ret, scale); +// ret.save("test.png"); + return ret; +} + + +double ExactImageMatcher::rmsd(const ImageViewRGB32& image) const{ + if (!image){ + return 1000.; + } + +// image.save("test.png"); + +// cout << "ExactImageMatcher::rmsd(): image = " << image.width() << " x " << image.height() << endl; + ImageRGB32 scaled = image.scale_to(m_image.width(), m_image.height()); +// cout << "ExactImageMatcher::rmsd(): scaled = " << scaled.width() << " x " << scaled.height() << endl; + ImageRGB32 reference = scale_template_brightness(scaled); + +#if 0 + static int c = 0; + image.save("test-" + std::to_string(c) + "-image.png"); + reference.save("test-" + std::to_string(c) + "-sprite.png"); + c++; +#endif + + double rmsd = pixel_RMSD(reference, scaled); +// cout << "rmsd = " << rmsd << endl; + return rmsd; +} +double ExactImageMatcher::rmsd(const ImageViewRGB32& image, Color background) const{ + if (!image){ + return 1000.; + } + ImageRGB32 scaled = image.scale_to(m_image.width(), m_image.height()); + ImageRGB32 reference = scale_template_brightness(scaled); + +#if 0 + static int c = 0; + scaled.save("test-" + std::to_string(c) + "-image.png"); + reference.save("test-" + std::to_string(c) + "-sprite.png"); + c++; +#endif + + return pixel_RMSD(reference, scaled, background); +} +double ExactImageMatcher::rmsd_masked(const ImageViewRGB32& image) const{ + if (!image){ + return 1000.; + } + ImageRGB32 scaled = image.scale_to(m_image.width(), m_image.height()); + ImageRGB32 reference = scale_template_brightness(scaled); + return pixel_RMSD_masked(reference, scaled); +} + + + + +WeightedExactImageMatcher::WeightedExactImageMatcher(ImageRGB32 image, const InverseStddevWeight& weight) + : ExactImageMatcher(std::move(image)) + , m_multiplier(1. / (m_stats.stddev.sum() * weight.stddev_coefficient + weight.offset)) +{} + + +double WeightedExactImageMatcher::diff(const ImageViewRGB32& image) const{ + if (!image){ + return 1000.; + } + return rmsd(image) * m_multiplier; +} +double WeightedExactImageMatcher::diff(const ImageViewRGB32& image, Color background) const{ + if (!image){ + return 1000.; + } + return rmsd(image, background) * m_multiplier; +} +double WeightedExactImageMatcher::diff_masked(const ImageViewRGB32& image) const{ + if (!image){ + return 1000.; + } + return rmsd_masked(image) * m_multiplier; +} + + + + + + + + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageMatcher.h b/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageMatcher.h index c05ec2fc71..5288a03376 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageMatcher.h +++ b/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageMatcher.h @@ -1,100 +1,100 @@ -/* Exact Image Match Preprocessed Data - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_ExactImageMatcher_H -#define PokemonAutomation_CommonTools_ExactImageMatcher_H - -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" - -namespace PokemonAutomation{ -namespace ImageMatch{ - - -// Match images against a template. -// Before matching, resize the input image to the template shape and scale template brightness to -// match the input image. Alpha channels as used as masks in matching. -// No other treatment like tolerating translation or scaling based on stddevs, hence the name "Exact". -class ExactImageMatcher{ - ExactImageMatcher(ExactImageMatcher&&) = default; - ExactImageMatcher& operator=(ExactImageMatcher&&) = default; - ExactImageMatcher(const ExactImageMatcher&) = delete; - void operator=(const ExactImageMatcher&) = delete; - -public: - ExactImageMatcher(const std::string& image_template) - : ExactImageMatcher(ImageRGB32(image_template)) - {} - ExactImageMatcher(ImageRGB32 image_template); - - const ImageStats& stats() const{ return m_stats; } - - // Resize image to match the shape of the image template, scale the template brightness to match - // the input image, then compute their RMSD (root mean square deviation). - // The part of the image template where alpha is 0 is not used to compare with the corresponding - // part in the input image. - double rmsd(const ImageViewRGB32& image) const; - // Resize image to match the shape of the image template, scale the template brightness to match - // the input image, then compute their RMSD (root mean square deviation). - // The part of the image template where alpha is 0 is replace with `background` color when comparing - // against the corresponding part in the input image. - double rmsd(const ImageViewRGB32& image, Color background) const; - // Resize image to match the shape of the image template, scale the template brightness to match - // the input image, then compute their RMSD (root mean square deviation). - // Alpha channels from both the template and the input image are considered when computing RMSD. - // If only one of the two has alpha==255 on one pixel, that the deviation on that pixel is the max pixel - // distance. - // If both two images have alpha==0 on one pixel, that pixel is ignored. - double rmsd_masked(const ImageViewRGB32& image) const; - - const ImageRGB32& image_template() const { return m_image; } - -private: - // scale stored image template according to the brightness of `image`, assign - // the scaled template to `reference`. - ImageRGB32 scale_template_brightness(const ImageViewRGB32& image) const; - -protected: - ImageRGB32 m_image; - ImageStats m_stats; -}; - - -// Based on ExactImageMatcher, adds new stddev scaling. -// An image template with higher stddev tends to have lots of detail. RMSD against an input image tends to -// be high because high details will be skewered by stuff like compression artifacts and translational shifts. -// So a template with high stddev tends to give higher RMSD than one with low stddev. -// To compensate for this, when calling WeightedExactImageMatcher::diff...(), it scales the computed RMSD -// based on template stddev, tunable by additional parameters defined in -// WeightedExactImageMatcher::InverseStddevWeight. -class WeightedExactImageMatcher : public ExactImageMatcher{ -public: - // Used to tune RMSD based on stddev of the template - // Equation: - // RMSD_scaled = RMSD_original / (template_stddev * `stddev_coefficient` + `offset`) - // where template_stddev is the sum of the stddev on all three channels (RGB) of the template. - struct InverseStddevWeight{ - double stddev_coefficient = 0.0; - double offset = 1.0; - }; - - WeightedExactImageMatcher(ImageRGB32 image_template, const InverseStddevWeight& weight); - - // Like ExactImageMatcher::rmsd(image) but scale based on template stddev. - double diff(const ImageViewRGB32& image) const; - // Like ExactImageMatcher::rmsd(image, background) but scale based on template stddev. - double diff(const ImageViewRGB32& image, Color background) const; - // Like ExactImageMatcher::rmsd_masked(image) but scale based on template stddev. - double diff_masked(const ImageViewRGB32& image) const; - -public: - double m_multiplier; -}; - - -} -} -#endif +/* Exact Image Match Preprocessed Data + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_ExactImageMatcher_H +#define PokemonAutomation_CommonTools_ExactImageMatcher_H + +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" + +namespace PokemonAutomation{ +namespace ImageMatch{ + + +// Match images against a template. +// Before matching, resize the input image to the template shape and scale template brightness to +// match the input image. Alpha channels as used as masks in matching. +// No other treatment like tolerating translation or scaling based on stddevs, hence the name "Exact". +class ExactImageMatcher{ + ExactImageMatcher(ExactImageMatcher&&) = default; + ExactImageMatcher& operator=(ExactImageMatcher&&) = default; + ExactImageMatcher(const ExactImageMatcher&) = delete; + void operator=(const ExactImageMatcher&) = delete; + +public: + ExactImageMatcher(const std::string& image_template) + : ExactImageMatcher(ImageRGB32(image_template)) + {} + ExactImageMatcher(ImageRGB32 image_template); + + const ImageStats& stats() const{ return m_stats; } + + // Resize image to match the shape of the image template, scale the template brightness to match + // the input image, then compute their RMSD (root mean square deviation). + // The part of the image template where alpha is 0 is not used to compare with the corresponding + // part in the input image. + double rmsd(const ImageViewRGB32& image) const; + // Resize image to match the shape of the image template, scale the template brightness to match + // the input image, then compute their RMSD (root mean square deviation). + // The part of the image template where alpha is 0 is replace with `background` color when comparing + // against the corresponding part in the input image. + double rmsd(const ImageViewRGB32& image, Color background) const; + // Resize image to match the shape of the image template, scale the template brightness to match + // the input image, then compute their RMSD (root mean square deviation). + // Alpha channels from both the template and the input image are considered when computing RMSD. + // If only one of the two has alpha==255 on one pixel, that the deviation on that pixel is the max pixel + // distance. + // If both two images have alpha==0 on one pixel, that pixel is ignored. + double rmsd_masked(const ImageViewRGB32& image) const; + + const ImageRGB32& image_template() const { return m_image; } + +private: + // scale stored image template according to the brightness of `image`, assign + // the scaled template to `reference`. + ImageRGB32 scale_template_brightness(const ImageViewRGB32& image) const; + +protected: + ImageRGB32 m_image; + ImageStats m_stats; +}; + + +// Based on ExactImageMatcher, adds new stddev scaling. +// An image template with higher stddev tends to have lots of detail. RMSD against an input image tends to +// be high because high details will be skewered by stuff like compression artifacts and translational shifts. +// So a template with high stddev tends to give higher RMSD than one with low stddev. +// To compensate for this, when calling WeightedExactImageMatcher::diff...(), it scales the computed RMSD +// based on template stddev, tunable by additional parameters defined in +// WeightedExactImageMatcher::InverseStddevWeight. +class WeightedExactImageMatcher : public ExactImageMatcher{ +public: + // Used to tune RMSD based on stddev of the template + // Equation: + // RMSD_scaled = RMSD_original / (template_stddev * `stddev_coefficient` + `offset`) + // where template_stddev is the sum of the stddev on all three channels (RGB) of the template. + struct InverseStddevWeight{ + double stddev_coefficient = 0.0; + double offset = 1.0; + }; + + WeightedExactImageMatcher(ImageRGB32 image_template, const InverseStddevWeight& weight); + + // Like ExactImageMatcher::rmsd(image) but scale based on template stddev. + double diff(const ImageViewRGB32& image) const; + // Like ExactImageMatcher::rmsd(image, background) but scale based on template stddev. + double diff(const ImageViewRGB32& image, Color background) const; + // Like ExactImageMatcher::rmsd_masked(image) but scale based on template stddev. + double diff_masked(const ImageViewRGB32& image) const; + +public: + double m_multiplier; +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/FilterToAlpha.cpp b/SerialPrograms/Source/CommonTools/ImageMatch/FilterToAlpha.cpp index 57b29674bd..682bd1ffd9 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/FilterToAlpha.cpp +++ b/SerialPrograms/Source/CommonTools/ImageMatch/FilterToAlpha.cpp @@ -1,78 +1,78 @@ -/* Filter to Alpha - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/CpuId/CpuId.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "FilterToAlpha.h" - -#ifdef PA_ARCH_x86 -#include -#endif - -namespace PokemonAutomation{ -namespace ImageMatch{ - - - -void set_alpha_black(ImageRGB32& image, uint32_t max_rgb_sum){ - size_t words = image.bytes_per_row() / sizeof(uint32_t); - uint32_t* data = image.data(); - - size_t width = image.width(); - size_t height = image.height(); - -#ifdef PA_ARCH_x86 - __m128i threshold = _mm_set1_epi32(max_rgb_sum); -#endif - - uint32_t* row = data; - for (size_t r = 0; r < height; r++){ - size_t c = 0; -#ifdef PA_ARCH_x86 - while (c + 3 < width){ - __m128i pixel = _mm_loadu_si128((__m128i*)(row + c)); -// print8(pixel); cout << " ====> "; - - pixel = _mm_andnot_si128(_mm_set1_epi32(0xff000000), pixel); - - __m128i sum = _mm_and_si128(pixel, _mm_set1_epi32(0x000000ff)); - sum = _mm_add_epi32(sum, _mm_and_si128(_mm_srli_epi32(pixel, 8), _mm_set1_epi32(0x000000ff))); - sum = _mm_add_epi32(sum, _mm_and_si128(_mm_srli_epi32(pixel, 16), _mm_set1_epi32(0x000000ff))); - sum = _mm_cmpgt_epi32(sum, threshold); - sum = _mm_andnot_si128(sum, _mm_set1_epi32(0xff000000)); - pixel = _mm_or_si128(pixel, sum); - -// print8(pixel); cout << endl; - - _mm_storeu_si128((__m128i*)(row + c), pixel); - c += 4; - } -#endif - while (c < width){ - uint32_t pixel = row[c]; - // Set alpha channel to 0. - pixel &= 0x00ffffff; - - uint32_t sum = pixel & 0xff; - sum += (pixel >> 8) & 0xff; - sum += (pixel >> 16) & 0xff; - if (sum <= max_rgb_sum){ - // If dark, set alpha channel to 255. - pixel |= 0xff000000; - } - row[c] = pixel; - c++; - } - - - row += words; - } -} - - - -} -} +/* Filter to Alpha + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/CpuId/CpuId.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "FilterToAlpha.h" + +#ifdef PA_ARCH_x86 +#include +#endif + +namespace PokemonAutomation{ +namespace ImageMatch{ + + + +void set_alpha_black(ImageRGB32& image, uint32_t max_rgb_sum){ + size_t words = image.bytes_per_row() / sizeof(uint32_t); + uint32_t* data = image.data(); + + size_t width = image.width(); + size_t height = image.height(); + +#ifdef PA_ARCH_x86 + __m128i threshold = _mm_set1_epi32(max_rgb_sum); +#endif + + uint32_t* row = data; + for (size_t r = 0; r < height; r++){ + size_t c = 0; +#ifdef PA_ARCH_x86 + while (c + 3 < width){ + __m128i pixel = _mm_loadu_si128((__m128i*)(row + c)); +// print8(pixel); cout << " ====> "; + + pixel = _mm_andnot_si128(_mm_set1_epi32(0xff000000), pixel); + + __m128i sum = _mm_and_si128(pixel, _mm_set1_epi32(0x000000ff)); + sum = _mm_add_epi32(sum, _mm_and_si128(_mm_srli_epi32(pixel, 8), _mm_set1_epi32(0x000000ff))); + sum = _mm_add_epi32(sum, _mm_and_si128(_mm_srli_epi32(pixel, 16), _mm_set1_epi32(0x000000ff))); + sum = _mm_cmpgt_epi32(sum, threshold); + sum = _mm_andnot_si128(sum, _mm_set1_epi32(0xff000000)); + pixel = _mm_or_si128(pixel, sum); + +// print8(pixel); cout << endl; + + _mm_storeu_si128((__m128i*)(row + c), pixel); + c += 4; + } +#endif + while (c < width){ + uint32_t pixel = row[c]; + // Set alpha channel to 0. + pixel &= 0x00ffffff; + + uint32_t sum = pixel & 0xff; + sum += (pixel >> 8) & 0xff; + sum += (pixel >> 16) & 0xff; + if (sum <= max_rgb_sum){ + // If dark, set alpha channel to 255. + pixel |= 0xff000000; + } + row[c] = pixel; + c++; + } + + + row += words; + } +} + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/FilterToAlpha.h b/SerialPrograms/Source/CommonTools/ImageMatch/FilterToAlpha.h index 4ef660198d..4e7611ca45 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/FilterToAlpha.h +++ b/SerialPrograms/Source/CommonTools/ImageMatch/FilterToAlpha.h @@ -1,26 +1,26 @@ -/* Filter to Alpha - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_FilterToAlpha_H -#define PokemonAutomation_CommonTools_FilterToAlpha_H - -#include - -namespace PokemonAutomation{ - class ImageRGB32; -namespace ImageMatch{ - - - -// For each pixel, set the alpha channel to 255 if the RGB sum is no greater than "max_rgb_sum". -// The rest pixels are set to 0 alpha. -// This function is fast. -void set_alpha_black(ImageRGB32& image, uint32_t max_rgb_sum = 100); - - -} -} -#endif +/* Filter to Alpha + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_FilterToAlpha_H +#define PokemonAutomation_CommonTools_FilterToAlpha_H + +#include + +namespace PokemonAutomation{ + class ImageRGB32; +namespace ImageMatch{ + + + +// For each pixel, set the alpha channel to 255 if the RGB sum is no greater than "max_rgb_sum". +// The rest pixels are set to 0 alpha. +// This function is fast. +void set_alpha_black(ImageRGB32& image, uint32_t max_rgb_sum = 100); + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/ImageCropper.cpp b/SerialPrograms/Source/CommonTools/ImageMatch/ImageCropper.cpp index 0ddcf9eebd..7e3c66ea91 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/ImageCropper.cpp +++ b/SerialPrograms/Source/CommonTools/ImageMatch/ImageCropper.cpp @@ -1,75 +1,75 @@ -/* Image Cropper - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "ImageCropper.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace ImageMatch{ - - -// Scan one row to find if all pixels in the row are from background -bool is_background_row(const ImageViewRGB32& image, size_t row, const std::function& is_foreground){ - for (size_t c = 0; c < image.width(); c++){ - Color pixel(image.pixel(c, row)); - if (is_foreground(pixel)){ -// cout << "{" << c << "," << row << "}" << endl; - return false; - } - } - return true; -} - -// Scan one col to find if all pixels in the col are from background -bool is_background_col(const ImageViewRGB32& image, size_t col, const std::function& is_foreground){ - for (size_t r = 0; r < image.height(); r++){ - Color pixel(image.pixel(col, r)); - if (is_foreground(pixel)){ -// cout << "{" << col << "," << r << "}" << endl; - return false; - } - } - return true; -} - -ImageViewRGB32 trim_image_alpha(const ImageViewRGB32& image, uint8_t alpha_threshold){ - auto is_foreground = [=](Color pixel){ - return pixel.alpha() >= alpha_threshold; - }; - const auto box = enclosing_rectangle_with_pixel_filter(image, is_foreground); - - return extract_box_reference(image, box); -} - -ImagePixelBox enclosing_rectangle_with_pixel_filter(const ImageViewRGB32& image, const std::function& is_foreground){ - size_t rs = 0; - size_t re = image.height(); - size_t cs = 0; - size_t ce = image.width(); - -// cout << "Before: rs = " << rs << ", re = " << re << ", cs = " << cs << ", ce = " << ce << endl; - - // If we cannot find a foreground (aka, alpha != 0) pixel on one row or column, we trim it, until hitting a foreground pixel. - while (rs < re && is_background_row(image, rs , is_foreground)) rs++; - while (re > rs && is_background_row(image, re - 1, is_foreground)) re--; - while (cs < ce && is_background_col(image, cs , is_foreground)) cs++; - while (ce > cs && is_background_col(image, ce - 1, is_foreground)) ce--; - -// cout << "After: rs = " << rs << ", re = " << re << ", cs = " << cs << ", ce = " << ce << endl; - - return ImagePixelBox(cs, rs, ce, re); -} - - - - - - -} -} +/* Image Cropper + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "ImageCropper.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace ImageMatch{ + + +// Scan one row to find if all pixels in the row are from background +bool is_background_row(const ImageViewRGB32& image, size_t row, const std::function& is_foreground){ + for (size_t c = 0; c < image.width(); c++){ + Color pixel(image.pixel(c, row)); + if (is_foreground(pixel)){ +// cout << "{" << c << "," << row << "}" << endl; + return false; + } + } + return true; +} + +// Scan one col to find if all pixels in the col are from background +bool is_background_col(const ImageViewRGB32& image, size_t col, const std::function& is_foreground){ + for (size_t r = 0; r < image.height(); r++){ + Color pixel(image.pixel(col, r)); + if (is_foreground(pixel)){ +// cout << "{" << col << "," << r << "}" << endl; + return false; + } + } + return true; +} + +ImageViewRGB32 trim_image_alpha(const ImageViewRGB32& image, uint8_t alpha_threshold){ + auto is_foreground = [=](Color pixel){ + return pixel.alpha() >= alpha_threshold; + }; + const auto box = enclosing_rectangle_with_pixel_filter(image, is_foreground); + + return extract_box_reference(image, box); +} + +ImagePixelBox enclosing_rectangle_with_pixel_filter(const ImageViewRGB32& image, const std::function& is_foreground){ + size_t rs = 0; + size_t re = image.height(); + size_t cs = 0; + size_t ce = image.width(); + +// cout << "Before: rs = " << rs << ", re = " << re << ", cs = " << cs << ", ce = " << ce << endl; + + // If we cannot find a foreground (aka, alpha != 0) pixel on one row or column, we trim it, until hitting a foreground pixel. + while (rs < re && is_background_row(image, rs , is_foreground)) rs++; + while (re > rs && is_background_row(image, re - 1, is_foreground)) re--; + while (cs < ce && is_background_col(image, cs , is_foreground)) cs++; + while (ce > cs && is_background_col(image, ce - 1, is_foreground)) ce--; + +// cout << "After: rs = " << rs << ", re = " << re << ", cs = " << cs << ", ce = " << ce << endl; + + return ImagePixelBox(cs, rs, ce, re); +} + + + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/ImageCropper.h b/SerialPrograms/Source/CommonTools/ImageMatch/ImageCropper.h index bb3a92077e..843196d107 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/ImageCropper.h +++ b/SerialPrograms/Source/CommonTools/ImageMatch/ImageCropper.h @@ -1,34 +1,34 @@ -/* Image Cropper - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_ImageCropper_H -#define PokemonAutomation_CommonTools_ImageCropper_H - -#include -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" - -namespace PokemonAutomation{ -namespace ImageMatch{ - - -// Shrink image so that it perfectly fits the object. -// The alpha channel is used to determine what is object vs. background. -// background is defined as alpha < alpha_threshold. -ImageViewRGB32 trim_image_alpha(const ImageViewRGB32& image, uint8_t alpha_threshold = 128); - - -// Find a crop of the object based on background color. -// The pixels of the object are defined as is_object(pixel_color) == true. -// Return the rectangle enclosing the object. -ImagePixelBox enclosing_rectangle_with_pixel_filter(const ImageViewRGB32& image, const std::function& is_object); - - - -} -} -#endif +/* Image Cropper + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_ImageCropper_H +#define PokemonAutomation_CommonTools_ImageCropper_H + +#include +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" + +namespace PokemonAutomation{ +namespace ImageMatch{ + + +// Shrink image so that it perfectly fits the object. +// The alpha channel is used to determine what is object vs. background. +// background is defined as alpha < alpha_threshold. +ImageViewRGB32 trim_image_alpha(const ImageViewRGB32& image, uint8_t alpha_threshold = 128); + + +// Find a crop of the object based on background color. +// The pixels of the object are defined as is_object(pixel_color) == true. +// Return the rectangle enclosing the object. +ImagePixelBox enclosing_rectangle_with_pixel_filter(const ImageViewRGB32& image, const std::function& is_object); + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchOption.cpp b/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchOption.cpp index dc3668fcd2..a84a8ba519 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchOption.cpp +++ b/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchOption.cpp @@ -1,17 +1,17 @@ -/* Image Match Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "ImageMatchOption.h" - -namespace PokemonAutomation{ -namespace ImageMatch{ - - - - - -} -} +/* Image Match Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "ImageMatchOption.h" + +namespace PokemonAutomation{ +namespace ImageMatch{ + + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchOption.h b/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchOption.h index 9028dda0e8..cbca6c1648 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchOption.h +++ b/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchOption.h @@ -1,21 +1,21 @@ -/* Image Match Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_ImageMatchOption_H -#define PokemonAutomation_CommonTools_ImageMatchOption_H - -#include "Common/Cpp/Options/ConfigOption.h" - -namespace PokemonAutomation{ -namespace ImageMatch{ - - - - - -} -} -#endif +/* Image Match Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_ImageMatchOption_H +#define PokemonAutomation_CommonTools_ImageMatchOption_H + +#include "Common/Cpp/Options/ConfigOption.h" + +namespace PokemonAutomation{ +namespace ImageMatch{ + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchResult.cpp b/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchResult.cpp index a41fbe0997..a271140405 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchResult.cpp +++ b/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchResult.cpp @@ -1,84 +1,84 @@ -/* Image Match Result - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "ImageMatchResult.h" - -namespace PokemonAutomation{ -namespace ImageMatch{ - - -void ImageMatchResult::log(Logger& logger, double max_alpha) const{ - std::string str = "Image Match Result: "; - - if (results.empty()){ - str += "no matches"; - logger.log(str, COLOR_RED); - return; - } - - double best = results.begin()->first; - Color color = best <= max_alpha - ? COLOR_BLUE - : COLOR_RED; - - if (results.size() == 1){ - auto iter = results.begin(); - str += iter->second; - str += " (alpha = "; - str += std::to_string(iter->first); - str += ")"; - logger.log(str, color); - return; - } - - str += "Multiple Candidates =>\n"; - size_t printed = 0; - for (const auto& item : results){ - if (printed == 10){ - str += " (" + std::to_string(results.size() - 10) + " more...)\n"; - break; - } - str += " "; - str += std::to_string(item.first); - str += " : "; - str += item.second; - str += "\n"; - printed++; - } - - logger.log(str, color); -} - -void ImageMatchResult::add(double alpha, std::string slug){ - results.emplace(alpha, std::move(slug)); -} -void ImageMatchResult::clear_beyond_spread(double max_alpha_spread){ - auto best = results.begin(); - while (results.size() > 1){ - auto back = results.end(); - --back; - if (back->first <= best->first + max_alpha_spread){ - break; - } - results.erase(back); - } -} -void ImageMatchResult::clear_beyond_alpha(double max_alpha){ - while (!results.empty()){ - auto iter = results.end(); - --iter; - if (iter->first <= max_alpha){ - break; - } - results.erase(iter); - } -} - - - - -} -} +/* Image Match Result + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "ImageMatchResult.h" + +namespace PokemonAutomation{ +namespace ImageMatch{ + + +void ImageMatchResult::log(Logger& logger, double max_alpha) const{ + std::string str = "Image Match Result: "; + + if (results.empty()){ + str += "no matches"; + logger.log(str, COLOR_RED); + return; + } + + double best = results.begin()->first; + Color color = best <= max_alpha + ? COLOR_BLUE + : COLOR_RED; + + if (results.size() == 1){ + auto iter = results.begin(); + str += iter->second; + str += " (alpha = "; + str += std::to_string(iter->first); + str += ")"; + logger.log(str, color); + return; + } + + str += "Multiple Candidates =>\n"; + size_t printed = 0; + for (const auto& item : results){ + if (printed == 10){ + str += " (" + std::to_string(results.size() - 10) + " more...)\n"; + break; + } + str += " "; + str += std::to_string(item.first); + str += " : "; + str += item.second; + str += "\n"; + printed++; + } + + logger.log(str, color); +} + +void ImageMatchResult::add(double alpha, std::string slug){ + results.emplace(alpha, std::move(slug)); +} +void ImageMatchResult::clear_beyond_spread(double max_alpha_spread){ + auto best = results.begin(); + while (results.size() > 1){ + auto back = results.end(); + --back; + if (back->first <= best->first + max_alpha_spread){ + break; + } + results.erase(back); + } +} +void ImageMatchResult::clear_beyond_alpha(double max_alpha){ + while (!results.empty()){ + auto iter = results.end(); + --iter; + if (iter->first <= max_alpha){ + break; + } + results.erase(iter); + } +} + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchResult.h b/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchResult.h index 4766f3f28b..f8a744fb45 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchResult.h +++ b/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchResult.h @@ -1,41 +1,41 @@ -/* Image Match Result - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_ImageMatchResult_H -#define PokemonAutomation_CommonTools_ImageMatchResult_H - -#include -#include -#include "Common/Cpp/AbstractLogger.h" - -namespace PokemonAutomation{ -namespace ImageMatch{ - - -struct ImageMatchResult{ - // Stored match score (the lower the closer the match) -> slug of the image template that gives the score. - std::multimap results; - - // Write to log the current matching results stored in `results`. - // Use `max_alpha` to determine whether matches are found. - void log(Logger& logger, double max_alpha) const; - - // Add to `results`. - // alpha: the match score, the lower the closer the match. - // slug: slug of the image template that gives the score. - void add(double alpha, std::string slug); - - // Assume there is at least one result in `results`: - // Remove other weaker match results that have a score that's larger than the best match score + `max_alpha_spread`. - void clear_beyond_spread(double max_alpha_spread); - // Remove match results with scores > `max_alpha`. - void clear_beyond_alpha(double max_alpha); -}; - - -} -} -#endif +/* Image Match Result + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_ImageMatchResult_H +#define PokemonAutomation_CommonTools_ImageMatchResult_H + +#include +#include +#include "Common/Cpp/AbstractLogger.h" + +namespace PokemonAutomation{ +namespace ImageMatch{ + + +struct ImageMatchResult{ + // Stored match score (the lower the closer the match) -> slug of the image template that gives the score. + std::multimap results; + + // Write to log the current matching results stored in `results`. + // Use `max_alpha` to determine whether matches are found. + void log(Logger& logger, double max_alpha) const; + + // Add to `results`. + // alpha: the match score, the lower the closer the match. + // slug: slug of the image template that gives the score. + void add(double alpha, std::string slug); + + // Assume there is at least one result in `results`: + // Remove other weaker match results that have a score that's larger than the best match score + `max_alpha_spread`. + void clear_beyond_spread(double max_alpha_spread); + // Remove match results with scores > `max_alpha`. + void clear_beyond_alpha(double max_alpha); +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/SilhouetteDictionaryMatcher.cpp b/SerialPrograms/Source/CommonTools/ImageMatch/SilhouetteDictionaryMatcher.cpp index 2a59cb760a..0fa900f835 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/SilhouetteDictionaryMatcher.cpp +++ b/SerialPrograms/Source/CommonTools/ImageMatch/SilhouetteDictionaryMatcher.cpp @@ -1,86 +1,86 @@ -/* Cropped Silhouette Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "CommonTools/GlobalInferenceRunner.h" -#include "ImageCropper.h" -#include "SilhouetteDictionaryMatcher.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace ImageMatch{ - - -void SilhouetteDictionaryMatcher::add(const std::string& slug, const ImageViewRGB32& image){ - if (!image){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Null image."); - } - auto iter = m_database.find(slug); - if (iter != m_database.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate slug: " + slug); - } - - iter = m_database.emplace( - std::piecewise_construct, - std::forward_as_tuple(slug), - std::forward_as_tuple(trim_image_alpha(image).copy()) - ).first; - m_database_vector.emplace_back(&*iter); -} - - - -ImageMatchResult SilhouetteDictionaryMatcher::match( - const ImageViewRGB32& image, - double alpha_spread -) const{ - ImageMatchResult results; - if (!image){ - return results; - } - - SpinLock lock; - global_inference_runner().run_in_parallel( - [&](size_t index){ - const auto& matcher = *m_database_vector[index]; - double alpha = matcher.second.rmsd_masked(image); - WriteSpinLock lg(lock); - results.add(alpha, matcher.first); - results.clear_beyond_spread(alpha_spread); - }, - 0, m_database_vector.size(), - 100 - ); - - -#if 0 - for (const auto& item : m_database){ -// if (item.first != "solosis"){ -// continue; -// } - double alpha = item.second.rmsd_masked(image); -// WriteSpinLock lg(lock); - results.add(alpha, item.first); - results.clear_beyond_spread(alpha_spread); - } -#endif - - return results; -} - - - - - - -} -} +/* Cropped Silhouette Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonFramework/Tools/GlobalThreadPools.h" +#include "ImageCropper.h" +#include "SilhouetteDictionaryMatcher.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace ImageMatch{ + + +void SilhouetteDictionaryMatcher::add(const std::string& slug, const ImageViewRGB32& image){ + if (!image){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Null image."); + } + auto iter = m_database.find(slug); + if (iter != m_database.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate slug: " + slug); + } + + iter = m_database.emplace( + std::piecewise_construct, + std::forward_as_tuple(slug), + std::forward_as_tuple(trim_image_alpha(image).copy()) + ).first; + m_database_vector.emplace_back(&*iter); +} + + + +ImageMatchResult SilhouetteDictionaryMatcher::match( + const ImageViewRGB32& image, + double alpha_spread +) const{ + ImageMatchResult results; + if (!image){ + return results; + } + + SpinLock lock; + GlobalThreadPools::normal_inference().run_in_parallel( + [&](size_t index){ + const auto& matcher = *m_database_vector[index]; + double alpha = matcher.second.rmsd_masked(image); + WriteSpinLock lg(lock); + results.add(alpha, matcher.first); + results.clear_beyond_spread(alpha_spread); + }, + 0, m_database_vector.size(), + 100 + ); + + +#if 0 + for (const auto& item : m_database){ +// if (item.first != "solosis"){ +// continue; +// } + double alpha = item.second.rmsd_masked(image); +// WriteSpinLock lg(lock); + results.add(alpha, item.first); + results.clear_beyond_spread(alpha_spread); + } +#endif + + return results; +} + + + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/SilhouetteDictionaryMatcher.h b/SerialPrograms/Source/CommonTools/ImageMatch/SilhouetteDictionaryMatcher.h index 1368fe5b75..f44b4a377e 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/SilhouetteDictionaryMatcher.h +++ b/SerialPrograms/Source/CommonTools/ImageMatch/SilhouetteDictionaryMatcher.h @@ -1,56 +1,56 @@ -/* Silhouette Dictionary Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_SilhouetteDictionaryMatcher_H -#define PokemonAutomation_CommonTools_SilhouetteDictionaryMatcher_H - -//#include "Common/Compiler.h" -//#include "CommonFramework/ImageTools/FloatPixel.h" -#include "ImageMatchResult.h" -#include "ExactImageMatcher.h" - -namespace PokemonAutomation{ - class ImageViewRGB32; -namespace ImageMatch{ - - -// Match silhouette to several templates. -class SilhouetteDictionaryMatcher{ -public: - SilhouetteDictionaryMatcher(SilhouetteDictionaryMatcher&&) = default; - SilhouetteDictionaryMatcher& operator=(SilhouetteDictionaryMatcher&&) = default; - SilhouetteDictionaryMatcher(const SilhouetteDictionaryMatcher&) = delete; - void operator=(const SilhouetteDictionaryMatcher&) = delete; - -public: - SilhouetteDictionaryMatcher() = default; - virtual ~SilhouetteDictionaryMatcher() = default; - - // Add a silhouette template. The alpha==0 boundaries in the image will be trimmed when added. - void add(const std::string& slug, const ImageViewRGB32& image); - - // Match the input image with the templates. - // alpha_spread: used as tolerance for multiple match results. - // Apart from the best march result, other weaker match results are also returned in `ImageMatchResult` if - // their scores are not larger than the best match score + `alpha_spread`. - // Details of the match algorithm: - // Resize image first to match the shape of the image template. Then scale the template brightness to match - // the input image. Finally compute their RMSD (root mean square deviation). - // Alpha channels from both the template and the input image are considered when computing RMSD. - // If only one of the two has alpha==255 on one pixel, that the deviation on that pixel is the max pixel distance. - // If both two images have alpha==0 on one pixel, that pixel is ignored. - ImageMatchResult match(const ImageViewRGB32& image, double alpha_spread) const; - - -private: - std::map m_database; - std::vector*> m_database_vector; -}; - - -} -} -#endif +/* Silhouette Dictionary Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_SilhouetteDictionaryMatcher_H +#define PokemonAutomation_CommonTools_SilhouetteDictionaryMatcher_H + +//#include "Common/Compiler.h" +//#include "CommonFramework/ImageTools/FloatPixel.h" +#include "ImageMatchResult.h" +#include "ExactImageMatcher.h" + +namespace PokemonAutomation{ + class ImageViewRGB32; +namespace ImageMatch{ + + +// Match silhouette to several templates. +class SilhouetteDictionaryMatcher{ +public: + SilhouetteDictionaryMatcher(SilhouetteDictionaryMatcher&&) = default; + SilhouetteDictionaryMatcher& operator=(SilhouetteDictionaryMatcher&&) = default; + SilhouetteDictionaryMatcher(const SilhouetteDictionaryMatcher&) = delete; + void operator=(const SilhouetteDictionaryMatcher&) = delete; + +public: + SilhouetteDictionaryMatcher() = default; + virtual ~SilhouetteDictionaryMatcher() = default; + + // Add a silhouette template. The alpha==0 boundaries in the image will be trimmed when added. + void add(const std::string& slug, const ImageViewRGB32& image); + + // Match the input image with the templates. + // alpha_spread: used as tolerance for multiple match results. + // Apart from the best march result, other weaker match results are also returned in `ImageMatchResult` if + // their scores are not larger than the best match score + `alpha_spread`. + // Details of the match algorithm: + // Resize image first to match the shape of the image template. Then scale the template brightness to match + // the input image. Finally compute their RMSD (root mean square deviation). + // Alpha channels from both the template and the input image are considered when computing RMSD. + // If only one of the two has alpha==255 on one pixel, that the deviation on that pixel is the max pixel distance. + // If both two images have alpha==0 on one pixel, that pixel is ignored. + ImageMatchResult match(const ImageViewRGB32& image, double alpha_spread) const; + + +private: + std::map m_database; + std::vector*> m_database_vector; +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/SubObjectTemplateMatcher.cpp b/SerialPrograms/Source/CommonTools/ImageMatch/SubObjectTemplateMatcher.cpp index 8792a0ee79..de2887edc9 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/SubObjectTemplateMatcher.cpp +++ b/SerialPrograms/Source/CommonTools/ImageMatch/SubObjectTemplateMatcher.cpp @@ -1,166 +1,166 @@ -/* Sub-Object Template Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" -#include "CommonFramework/Globals.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "SubObjectTemplateMatcher.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace ImageMatch{ - - -SubObjectTemplateMatcher::SubObjectTemplateMatcher(const char* path, double max_rmsd) - : m_path(RESOURCE_PATH() + path) - , m_max_rmsd(max_rmsd) - , m_matcher(m_path) - , m_subobject_area_ratio(0) -{} - -SubObjectTemplateMatcher::SubObjectTemplateMatcher(const char* path, Color background_replacement, double max_rmsd) - : SubObjectTemplateMatcher(path, max_rmsd) -{ - m_background_replacement = background_replacement; -} - -ImagePixelBox SubObjectTemplateMatcher::object_from_subobject( - size_t width, size_t height, - const ImagePixelBox& subobject_in_image -) const{ - return extract_object_from_inner_feature( - width, height, - subobject_in_image, m_subobject_in_object_f - ); -} - -double SubObjectTemplateMatcher::rmsd( - ImagePixelBox& object_box, - const ImageViewRGB32& image, const ImagePixelBox& subobject_in_image -) const{ - object_box = object_from_subobject(image.width(), image.height(), subobject_in_image); -// cout << object_box.min_x << ", " -// << object_box.min_y << ", " -// << object_box.max_x << ", " -// << object_box.max_y << endl; - ImageViewRGB32 object = extract_box_reference(image, object_box); - -// object.save("test.png"); - - - if (!object || !check_image(object)){ - return 99999.; - } - - return m_matcher.rmsd(object); -} -double SubObjectTemplateMatcher::rmsd_with_background_replace( - ImagePixelBox& object_box, - const ImageViewRGB32& image, const PackedBinaryMatrix& binary_image, - const ImagePixelBox& subobject_in_image -) const{ - object_box = object_from_subobject(image.width(), image.height(), subobject_in_image); - ImageRGB32 object = extract_box_reference(image, object_box).copy(); - if (!object || !check_image(object)){ - return 99999.; - } - -// size_t width = binary_image.width(); -// size_t height = binary_image.height(); -// cout << width << " x " << height -// << ": " << object_box.min_x << "-" << object_box.width() -// << " " << object_box.min_y << "-" << object_box.height() << endl; - - filter_by_mask( - binary_image.submatrix( - object_box.min_x, object_box.min_y, - object_box.width(), object_box.height() - ), - object, - m_background_replacement, - true - ); - - return m_matcher.rmsd(object); -} - - -void SubObjectTemplateMatcher::set_subobject(const WaterfillObject& subobject_in_object){ - m_subobject_in_object_p = subobject_in_object; - m_subobject_in_object_f = pixelbox_to_floatbox(m_matcher.image_template(), m_subobject_in_object_p); - m_subobject_area_ratio = subobject_in_object.area_ratio(); -} -bool SubObjectTemplateMatcher::check_aspect_ratio(size_t candidate_width, size_t candidate_height) const{ -// double expected_aspect_ratio = (double)m_subobject_in_object_p.width() / m_subobject_in_object_p.height(); -// double actual_aspect_ratio = (double)width / height; -// double error = actual_aspect_ratio / expected_aspect_ratio; - -// cout << "expected_aspect_ratio = " << expected_aspect_ratio << endl; -// cout << "actual_aspect_ratio = " << actual_aspect_ratio << endl; - - double error = (double)m_subobject_in_object_p.width() * candidate_height; - error /= (double)m_subobject_in_object_p.height() * candidate_width; -// cout << "ratio = " << error << endl; - return m_aspect_ratio_lower <= error && error <= m_aspect_ratio_upper; -} -bool SubObjectTemplateMatcher::check_area_ratio(double candidate_area_ratio) const{ - if (m_subobject_area_ratio == 0){ - return true; - } - double error = candidate_area_ratio / m_subobject_area_ratio; - return m_area_ratio_lower <= error && error <= m_area_ratio_upper; -} - -bool SubObjectTemplateMatcher::matches( - ImagePixelBox& object_box, - const ImageViewRGB32& image, - const WaterfillObject& subobject_in_image -) const{ - if (!check_aspect_ratio(subobject_in_image.width(), subobject_in_image.height())){ - return false; - } - if (!check_area_ratio(subobject_in_image.area_ratio())){ - return false; - } - -// static int c = 0; -// cout << c++ << endl; - - double rmsd = this->rmsd(object_box, image, subobject_in_image); - -// cout << "rmsd = " << rmsd << endl; - -// if (rmsd <= m_max_rmsd){ -// static int c = 0; -// extract_box(image, object_box).save("test-" + std::to_string(c++) + "-" + std::to_string(rmsd) + ".png"); -// } - - return rmsd <= m_max_rmsd; -} -bool SubObjectTemplateMatcher::matches_with_background_replace( - ImagePixelBox& object_box, - const ImageViewRGB32& image, const PackedBinaryMatrix& binary_image, - const WaterfillObject& subobject_in_image -) const{ - if (!check_aspect_ratio(subobject_in_image.width(), subobject_in_image.height())){ - return false; - } - if (!check_area_ratio(subobject_in_image.area_ratio())){ - return false; - } - - double rmsd = this->rmsd_with_background_replace(object_box, image, binary_image, subobject_in_image); -// cout << "rmsd = " << rmsd << endl; - return rmsd <= m_max_rmsd; -} - - - -} -} +/* Sub-Object Template Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" +#include "CommonFramework/Globals.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "SubObjectTemplateMatcher.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace ImageMatch{ + + +SubObjectTemplateMatcher::SubObjectTemplateMatcher(const char* path, double max_rmsd) + : m_path(RESOURCE_PATH() + path) + , m_max_rmsd(max_rmsd) + , m_matcher(m_path) + , m_subobject_area_ratio(0) +{} + +SubObjectTemplateMatcher::SubObjectTemplateMatcher(const char* path, Color background_replacement, double max_rmsd) + : SubObjectTemplateMatcher(path, max_rmsd) +{ + m_background_replacement = background_replacement; +} + +ImagePixelBox SubObjectTemplateMatcher::object_from_subobject( + size_t width, size_t height, + const ImagePixelBox& subobject_in_image +) const{ + return extract_object_from_inner_feature( + width, height, + subobject_in_image, m_subobject_in_object_f + ); +} + +double SubObjectTemplateMatcher::rmsd( + ImagePixelBox& object_box, + const ImageViewRGB32& image, const ImagePixelBox& subobject_in_image +) const{ + object_box = object_from_subobject(image.width(), image.height(), subobject_in_image); +// cout << object_box.min_x << ", " +// << object_box.min_y << ", " +// << object_box.max_x << ", " +// << object_box.max_y << endl; + ImageViewRGB32 object = extract_box_reference(image, object_box); + +// object.save("test.png"); + + + if (!object || !check_image(object)){ + return 99999.; + } + + return m_matcher.rmsd(object); +} +double SubObjectTemplateMatcher::rmsd_with_background_replace( + ImagePixelBox& object_box, + const ImageViewRGB32& image, const PackedBinaryMatrix& binary_image, + const ImagePixelBox& subobject_in_image +) const{ + object_box = object_from_subobject(image.width(), image.height(), subobject_in_image); + ImageRGB32 object = extract_box_reference(image, object_box).copy(); + if (!object || !check_image(object)){ + return 99999.; + } + +// size_t width = binary_image.width(); +// size_t height = binary_image.height(); +// cout << width << " x " << height +// << ": " << object_box.min_x << "-" << object_box.width() +// << " " << object_box.min_y << "-" << object_box.height() << endl; + + filter_by_mask( + binary_image.submatrix( + object_box.min_x, object_box.min_y, + object_box.width(), object_box.height() + ), + object, + m_background_replacement, + true + ); + + return m_matcher.rmsd(object); +} + + +void SubObjectTemplateMatcher::set_subobject(const WaterfillObject& subobject_in_object){ + m_subobject_in_object_p = subobject_in_object; + m_subobject_in_object_f = pixelbox_to_floatbox(m_matcher.image_template(), m_subobject_in_object_p); + m_subobject_area_ratio = subobject_in_object.area_ratio(); +} +bool SubObjectTemplateMatcher::check_aspect_ratio(size_t candidate_width, size_t candidate_height) const{ +// double expected_aspect_ratio = (double)m_subobject_in_object_p.width() / m_subobject_in_object_p.height(); +// double actual_aspect_ratio = (double)width / height; +// double error = actual_aspect_ratio / expected_aspect_ratio; + +// cout << "expected_aspect_ratio = " << expected_aspect_ratio << endl; +// cout << "actual_aspect_ratio = " << actual_aspect_ratio << endl; + + double error = (double)m_subobject_in_object_p.width() * candidate_height; + error /= (double)m_subobject_in_object_p.height() * candidate_width; +// cout << "ratio = " << error << endl; + return m_aspect_ratio_lower <= error && error <= m_aspect_ratio_upper; +} +bool SubObjectTemplateMatcher::check_area_ratio(double candidate_area_ratio) const{ + if (m_subobject_area_ratio == 0){ + return true; + } + double error = candidate_area_ratio / m_subobject_area_ratio; + return m_area_ratio_lower <= error && error <= m_area_ratio_upper; +} + +bool SubObjectTemplateMatcher::matches( + ImagePixelBox& object_box, + const ImageViewRGB32& image, + const WaterfillObject& subobject_in_image +) const{ + if (!check_aspect_ratio(subobject_in_image.width(), subobject_in_image.height())){ + return false; + } + if (!check_area_ratio(subobject_in_image.area_ratio())){ + return false; + } + +// static int c = 0; +// cout << c++ << endl; + + double rmsd = this->rmsd(object_box, image, subobject_in_image); + +// cout << "rmsd = " << rmsd << endl; + +// if (rmsd <= m_max_rmsd){ +// static int c = 0; +// extract_box(image, object_box).save("test-" + std::to_string(c++) + "-" + std::to_string(rmsd) + ".png"); +// } + + return rmsd <= m_max_rmsd; +} +bool SubObjectTemplateMatcher::matches_with_background_replace( + ImagePixelBox& object_box, + const ImageViewRGB32& image, const PackedBinaryMatrix& binary_image, + const WaterfillObject& subobject_in_image +) const{ + if (!check_aspect_ratio(subobject_in_image.width(), subobject_in_image.height())){ + return false; + } + if (!check_area_ratio(subobject_in_image.area_ratio())){ + return false; + } + + double rmsd = this->rmsd_with_background_replace(object_box, image, binary_image, subobject_in_image); +// cout << "rmsd = " << rmsd << endl; + return rmsd <= m_max_rmsd; +} + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/SubObjectTemplateMatcher.h b/SerialPrograms/Source/CommonTools/ImageMatch/SubObjectTemplateMatcher.h index 46345e7465..aa16c21b1d 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/SubObjectTemplateMatcher.h +++ b/SerialPrograms/Source/CommonTools/ImageMatch/SubObjectTemplateMatcher.h @@ -1,99 +1,99 @@ -/* Sub-Object Template Matcher - * - * From: https://github.com/PokemonAutomation/ - * - * Suppose we have an object with a distinctive sub-feature. - * - * We want to find this object in an image. But instead of searching for the - * entire object as a whole, we search for that distinctive sub-feature. - * - * Once we've found that sub-feature and have it's bounding box, we want to - * verify that the rest of the object matches the template. - * - */ - -#ifndef PokemonAutomation_CommonTools_SubObjectTemplateMatcher_H -#define PokemonAutomation_CommonTools_SubObjectTemplateMatcher_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTypes/BinaryImage.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "ExactImageMatcher.h" - -namespace PokemonAutomation{ -namespace ImageMatch{ - - -class SubObjectTemplateMatcher{ -protected: - using WaterfillObject = Kernels::Waterfill::WaterfillObject; - -public: - virtual ~SubObjectTemplateMatcher() = default; - SubObjectTemplateMatcher(const char* path, double max_rmsd); - SubObjectTemplateMatcher(const char* path, Color background_replacement, double max_rmsd); - - ImagePixelBox object_from_subobject( - size_t width, size_t height, - const ImagePixelBox& subobject_in_image - ) const; - - // Compute RMSD of current object against the template as-is. - double rmsd( - ImagePixelBox& object_box, - const ImageViewRGB32& image, const ImagePixelBox& subobject_in_image - ) const; - - // Replace the background of the image with the "m_background_replacement". - // Then compute RMSD of it against the template. - // The background is defined by zero-bits in the binary matrix in "binary_image". - double rmsd_with_background_replace( - ImagePixelBox& object_box, - const ImageViewRGB32& image, const PackedBinaryMatrix& binary_image, - const ImagePixelBox& subobject_in_image - ) const; - - virtual bool matches( - ImagePixelBox& object_box, - const ImageViewRGB32& image, - const WaterfillObject& subobject_in_image - ) const; - virtual bool matches_with_background_replace( - ImagePixelBox& object_box, - const ImageViewRGB32& image, const PackedBinaryMatrix& binary_image, - const WaterfillObject& subobject_in_image - ) const; - - -protected: - virtual bool check_image(const ImageViewRGB32& image) const{ return true; }; - - void set_subobject(const WaterfillObject& subobject_in_object); - bool check_aspect_ratio(size_t candidate_width, size_t candidate_height) const; - bool check_area_ratio(double candidate_area_ratio) const; - -protected: - std::string m_path; - Color m_background_replacement; - - double m_max_rmsd; - double m_aspect_ratio_lower = 0.80; - double m_aspect_ratio_upper = 1.25; - double m_area_ratio_lower = 0.80; - double m_area_ratio_upper = 1.25; - - ExactImageMatcher m_matcher; - ImagePixelBox m_subobject_in_object_p; - ImageFloatBox m_subobject_in_object_f; - double m_subobject_area_ratio; -}; - - - - - - - -} -} -#endif +/* Sub-Object Template Matcher + * + * From: https://github.com/PokemonAutomation/ + * + * Suppose we have an object with a distinctive sub-feature. + * + * We want to find this object in an image. But instead of searching for the + * entire object as a whole, we search for that distinctive sub-feature. + * + * Once we've found that sub-feature and have it's bounding box, we want to + * verify that the rest of the object matches the template. + * + */ + +#ifndef PokemonAutomation_CommonTools_SubObjectTemplateMatcher_H +#define PokemonAutomation_CommonTools_SubObjectTemplateMatcher_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTypes/BinaryImage.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "ExactImageMatcher.h" + +namespace PokemonAutomation{ +namespace ImageMatch{ + + +class SubObjectTemplateMatcher{ +protected: + using WaterfillObject = Kernels::Waterfill::WaterfillObject; + +public: + virtual ~SubObjectTemplateMatcher() = default; + SubObjectTemplateMatcher(const char* path, double max_rmsd); + SubObjectTemplateMatcher(const char* path, Color background_replacement, double max_rmsd); + + ImagePixelBox object_from_subobject( + size_t width, size_t height, + const ImagePixelBox& subobject_in_image + ) const; + + // Compute RMSD of current object against the template as-is. + double rmsd( + ImagePixelBox& object_box, + const ImageViewRGB32& image, const ImagePixelBox& subobject_in_image + ) const; + + // Replace the background of the image with the "m_background_replacement". + // Then compute RMSD of it against the template. + // The background is defined by zero-bits in the binary matrix in "binary_image". + double rmsd_with_background_replace( + ImagePixelBox& object_box, + const ImageViewRGB32& image, const PackedBinaryMatrix& binary_image, + const ImagePixelBox& subobject_in_image + ) const; + + virtual bool matches( + ImagePixelBox& object_box, + const ImageViewRGB32& image, + const WaterfillObject& subobject_in_image + ) const; + virtual bool matches_with_background_replace( + ImagePixelBox& object_box, + const ImageViewRGB32& image, const PackedBinaryMatrix& binary_image, + const WaterfillObject& subobject_in_image + ) const; + + +protected: + virtual bool check_image(const ImageViewRGB32& image) const{ return true; }; + + void set_subobject(const WaterfillObject& subobject_in_object); + bool check_aspect_ratio(size_t candidate_width, size_t candidate_height) const; + bool check_area_ratio(double candidate_area_ratio) const; + +protected: + std::string m_path; + Color m_background_replacement; + + double m_max_rmsd; + double m_aspect_ratio_lower = 0.80; + double m_aspect_ratio_upper = 1.25; + double m_area_ratio_lower = 0.80; + double m_area_ratio_upper = 1.25; + + ExactImageMatcher m_matcher; + ImagePixelBox m_subobject_in_object_p; + ImageFloatBox m_subobject_in_object_f; + double m_subobject_area_ratio; +}; + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/WaterfillTemplateMatcher.cpp b/SerialPrograms/Source/CommonTools/ImageMatch/WaterfillTemplateMatcher.cpp index 33816ad9ba..fa87444d7b 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/WaterfillTemplateMatcher.cpp +++ b/SerialPrograms/Source/CommonTools/ImageMatch/WaterfillTemplateMatcher.cpp @@ -1,187 +1,187 @@ -/* Waterfill Template Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Kernels/Waterfill/Kernels_Waterfill.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/Tools/DebugDumper.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "WaterfillTemplateMatcher.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace ImageMatch{ - -using namespace Kernels; -using namespace Kernels::Waterfill; - - -WaterfillTemplateMatcher::WaterfillTemplateMatcher( - const char* path, - Color min_color, Color max_color, - size_t min_area -){ - std::string full_path = RESOURCE_PATH() + path; - ImageRGB32 reference(full_path); - - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( - reference, - (uint32_t)min_color, (uint32_t)max_color - ); - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - ImageRGB32 binaryImage = reference.copy(); - filter_by_mask(matrix, binaryImage, Color(COLOR_BLACK), true); - //filter_by_mask(matrix, binaryImage, Color(COLOR_WHITE), true); - dump_debug_image( - global_logger_command_line(), - "CommonFramework/WaterfillTemplateMatcher", - "waterfill_template_image_black_background", - binaryImage); - } - std::vector objects = find_objects_inplace(matrix, min_area); - if (objects.empty()){ - throw FileException( - nullptr, PA_CURRENT_FUNCTION, - "Failed to find any waterfill objects in resource template file.", - std::move(full_path) - ); - } - - const WaterfillObject* best = &objects[0]; - for (const WaterfillObject& object : objects){ - if (best->area < object.area){ - best = &object; - } - } - - m_matcher.reset(new ExactImageMatcher(extract_box_reference(reference, *best).copy())); - m_area_ratio = best->area_ratio(); - - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - const auto exact_image = extract_box_reference(reference, *best); - cout << "Build waterfil template matcher from " << full_path << ", W x H: " << exact_image.width() - << " x " << exact_image.height() << ", area ratio: " << m_area_ratio << ", Object area: " << best->area << endl; - dump_debug_image( - global_logger_command_line(), - "CommonFramework/WaterfillTemplateMatcher", - "waterfill_template_matcher_reference_image", - exact_image); - } -} - -double WaterfillTemplateMatcher::rmsd(const ImageViewRGB32& image) const{ - if (!image || !check_image(image)){ - return 99999.; - } - return m_matcher->rmsd(image); -} -bool WaterfillTemplateMatcher::check_aspect_ratio(size_t candidate_width, size_t candidate_height) const{ - ImageViewRGB32 image_template = m_matcher->image_template(); - - double error = (double)image_template.width() * candidate_height; - error /= (double)image_template.height() * candidate_width; - - bool pass = m_aspect_ratio_lower <= error && error <= m_aspect_ratio_upper; - - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - if (!pass){ - cout << "Failed to pass WaterfillTemplateMatcher aspect ratio check (W/H): "; - }else{ - cout << "Passed WaterfillTemplateMatcher aspect ratio check (W/H): "; - } - cout << "expected: " << image_template.width() << " : " << image_template.height() - << " (" << (double)image_template.width()/image_template.height() << "), " - << "actual: " << candidate_width << " : " << candidate_height - << " (" << (double)candidate_width/candidate_height << ") " - << "error: " << error << " bound [" << m_aspect_ratio_lower << ", " << m_aspect_ratio_upper << "]" << endl; - } - - return pass; -} -bool WaterfillTemplateMatcher::check_area_ratio(double candidate_area_ratio) const{ - if (m_area_ratio == 0){ - return true; - } - double error = candidate_area_ratio / m_area_ratio; - bool pass = m_area_ratio_lower <= error && error <= m_area_ratio_upper; - - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - if (!pass){ - cout << "Failed to pass WaterfillTemplateMatcher area ratio check: "; - }else{ - cout << "Passed WaterfillTemplateMatcher area ratio check: "; - } - cout << "Expected: " << m_area_ratio << ", actual: " << candidate_area_ratio << ", " - << "error: " << error << " bound [" << m_area_ratio_lower << ", " << m_area_ratio_upper << "]" << endl; - } - - return pass; -} -double WaterfillTemplateMatcher::rmsd_precropped(const ImageViewRGB32& cropped_image, const WaterfillObject& object) const{ - - // XXX - // dump_debug_image(global_logger_command_line(), "CommonFramework/WaterfillTemplateMatcher", "rmsd_precropped_input", cropped_image); - - if (!check_aspect_ratio(object.width(), object.height())){ - // cout << "bad aspect ratio" << endl; - return 99999.; - } - if (!check_area_ratio(object.area_ratio())){ - // cout << "bad area ratio" << endl; - return 99999.; - } - -// static int c = 0; -// cout << c << endl; - - double rmsd = this->rmsd(cropped_image); - -// cout << "rmsd = " << rmsd << endl; - -// if (rmsd <= m_max_rmsd){ -// static int c = 0; -// cropped_image.save("test-" + std::to_string(c++) + "-" + std::to_string(rmsd) + ".png"); -// } - - return rmsd; -} -double WaterfillTemplateMatcher::rmsd_original(const ImageViewRGB32& original_image, const WaterfillObject& object) const{ - - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - cout << "rmsd_original()" << endl; - dump_debug_image( - global_logger_command_line(), - "CommonFramework/WaterfillTemplateMatcher", - "waterfill_template_matcher_rmsd_original_input", - extract_box_reference(original_image, object) - ); - } - - if (!check_aspect_ratio(object.width(), object.height())){ - return 99999.; - } - if (!check_area_ratio(object.area_ratio())){ - return 99999.; - } - - double rmsd = this->rmsd(extract_box_reference(original_image, object)); - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - cout << "Passed aspect and area ratio check, rmsd = " << rmsd << endl; - } - - return rmsd; -} - - - - -} -} +/* Waterfill Template Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Kernels/Waterfill/Kernels_Waterfill.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/Tools/DebugDumper.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "WaterfillTemplateMatcher.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace ImageMatch{ + +using namespace Kernels; +using namespace Kernels::Waterfill; + + +WaterfillTemplateMatcher::WaterfillTemplateMatcher( + const char* path, + Color min_color, Color max_color, + size_t min_area +){ + std::string full_path = RESOURCE_PATH() + path; + ImageRGB32 reference(full_path); + + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( + reference, + (uint32_t)min_color, (uint32_t)max_color + ); + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + ImageRGB32 binaryImage = reference.copy(); + filter_by_mask(matrix, binaryImage, Color(COLOR_BLACK), true); + //filter_by_mask(matrix, binaryImage, Color(COLOR_WHITE), true); + dump_debug_image( + global_logger_command_line(), + "CommonFramework/WaterfillTemplateMatcher", + "waterfill_template_image_black_background", + binaryImage); + } + std::vector objects = find_objects_inplace(matrix, min_area); + if (objects.empty()){ + throw FileException( + nullptr, PA_CURRENT_FUNCTION, + "Failed to find any waterfill objects in resource template file.", + std::move(full_path) + ); + } + + const WaterfillObject* best = &objects[0]; + for (const WaterfillObject& object : objects){ + if (best->area < object.area){ + best = &object; + } + } + + m_matcher.reset(new ExactImageMatcher(extract_box_reference(reference, *best).copy())); + m_area_ratio = best->area_ratio(); + + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + const auto exact_image = extract_box_reference(reference, *best); + cout << "Build waterfil template matcher from " << full_path << ", W x H: " << exact_image.width() + << " x " << exact_image.height() << ", area ratio: " << m_area_ratio << ", Object area: " << best->area << endl; + dump_debug_image( + global_logger_command_line(), + "CommonFramework/WaterfillTemplateMatcher", + "waterfill_template_matcher_reference_image", + exact_image); + } +} + +double WaterfillTemplateMatcher::rmsd(const ImageViewRGB32& image) const{ + if (!image || !check_image(image)){ + return 99999.; + } + return m_matcher->rmsd(image); +} +bool WaterfillTemplateMatcher::check_aspect_ratio(size_t candidate_width, size_t candidate_height) const{ + ImageViewRGB32 image_template = m_matcher->image_template(); + + double error = (double)image_template.width() * candidate_height; + error /= (double)image_template.height() * candidate_width; + + bool pass = m_aspect_ratio_lower <= error && error <= m_aspect_ratio_upper; + + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + if (!pass){ + cout << "Failed to pass WaterfillTemplateMatcher aspect ratio check (W/H): "; + }else{ + cout << "Passed WaterfillTemplateMatcher aspect ratio check (W/H): "; + } + cout << "expected: " << image_template.width() << " : " << image_template.height() + << " (" << (double)image_template.width()/image_template.height() << "), " + << "actual: " << candidate_width << " : " << candidate_height + << " (" << (double)candidate_width/candidate_height << ") " + << "error: " << error << " bound [" << m_aspect_ratio_lower << ", " << m_aspect_ratio_upper << "]" << endl; + } + + return pass; +} +bool WaterfillTemplateMatcher::check_area_ratio(double candidate_area_ratio) const{ + if (m_area_ratio == 0){ + return true; + } + double error = candidate_area_ratio / m_area_ratio; + bool pass = m_area_ratio_lower <= error && error <= m_area_ratio_upper; + + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + if (!pass){ + cout << "Failed to pass WaterfillTemplateMatcher area ratio check: "; + }else{ + cout << "Passed WaterfillTemplateMatcher area ratio check: "; + } + cout << "Expected: " << m_area_ratio << ", actual: " << candidate_area_ratio << ", " + << "error: " << error << " bound [" << m_area_ratio_lower << ", " << m_area_ratio_upper << "]" << endl; + } + + return pass; +} +double WaterfillTemplateMatcher::rmsd_precropped(const ImageViewRGB32& cropped_image, const WaterfillObject& object) const{ + + // XXX + // dump_debug_image(global_logger_command_line(), "CommonFramework/WaterfillTemplateMatcher", "rmsd_precropped_input", cropped_image); + + if (!check_aspect_ratio(object.width(), object.height())){ + // cout << "bad aspect ratio" << endl; + return 99999.; + } + if (!check_area_ratio(object.area_ratio())){ + // cout << "bad area ratio" << endl; + return 99999.; + } + +// static int c = 0; +// cout << c << endl; + + double rmsd = this->rmsd(cropped_image); + +// cout << "rmsd = " << rmsd << endl; + +// if (rmsd <= m_max_rmsd){ +// static int c = 0; +// cropped_image.save("test-" + std::to_string(c++) + "-" + std::to_string(rmsd) + ".png"); +// } + + return rmsd; +} +double WaterfillTemplateMatcher::rmsd_original(const ImageViewRGB32& original_image, const WaterfillObject& object) const{ + + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + cout << "rmsd_original()" << endl; + dump_debug_image( + global_logger_command_line(), + "CommonFramework/WaterfillTemplateMatcher", + "waterfill_template_matcher_rmsd_original_input", + extract_box_reference(original_image, object) + ); + } + + if (!check_aspect_ratio(object.width(), object.height())){ + return 99999.; + } + if (!check_area_ratio(object.area_ratio())){ + return 99999.; + } + + double rmsd = this->rmsd(extract_box_reference(original_image, object)); + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + cout << "Passed aspect and area ratio check, rmsd = " << rmsd << endl; + } + + return rmsd; +} + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/WaterfillTemplateMatcher.h b/SerialPrograms/Source/CommonTools/ImageMatch/WaterfillTemplateMatcher.h index 61342d48db..120e652989 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/WaterfillTemplateMatcher.h +++ b/SerialPrograms/Source/CommonTools/ImageMatch/WaterfillTemplateMatcher.h @@ -1,96 +1,96 @@ -/* Waterfill Template Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_WaterfillTemplateMatcher_H -#define PokemonAutomation_CommonTools_WaterfillTemplateMatcher_H - -#include -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/ImageMatch/ExactImageMatcher.h" - -namespace PokemonAutomation{ -namespace ImageMatch{ - - -// Used to match an image or a waterfill object against a template object. -class WaterfillTemplateMatcher{ -protected: - using WaterfillObject = Kernels::Waterfill::WaterfillObject; - -public: - WaterfillTemplateMatcher(WaterfillTemplateMatcher&&) = default; - virtual ~WaterfillTemplateMatcher() = default; - - -public: - // Load a template image from disk, min_color and max_color denote the color range of the object - // displayed in the image file while min_area is the minimum number of pixels required for the - // object in the template to be loaded. - // - // The portion of the image holding the found object will get cropped and saved as the actual template image. - // So if someone changes the template image by padding it to make it larger, as long as the padded color - // does not fall into [min_color and max_color] range, it will not affect the template matching outcome - // in any way. - // - // Throw FileException when there is no object meeting the requirement in the template. - // If there are more than one objects meeting the requirement in the template, pick the one - // with the largest area (largest number of pixels). - WaterfillTemplateMatcher( - const char* path, - Color min_color, Color max_color, - size_t min_area - ); - - // Compute RMSD of the current image against the template as-is, using `ExactImageMatcher`. - // `ExactImageMatcher` will resize the image to match template size and scale template brightness to match the image - // before computing RMSD. - // In case the image is invalid, return a large value. - // It also calls the virtual function `check_image()` on the image. - // If the function returns false, then return a large value. - double rmsd(const ImageViewRGB32& image) const; - - // Compute RMSD of the object on the image against the template. - // The input `cropped_image` is already cropped from a full image using the bounding box of the input waterfill `object`. - // This cropped image is compared against the template as-is. - // The waterfill object's aspect ratio and area ratio are checked against template's. Return a large value - // if the check fails. - // See `double rmsd(const ImageViewRGB32& image) const` on the details of comparing the image against the template. - virtual double rmsd_precropped(const ImageViewRGB32& cropped_image, const WaterfillObject& object) const; - - // Compute RMSD of the object on the image against the template. - // It will crop the original image using the bounding box of the waterfill object, then compare the cropped - // image against the template as-is. - // The waterfill object's aspect ratio and area ratio are checked against template's. Return a large value - // if the check fails. - // See `double rmsd(const ImageViewRGB32& image) const` on the details of comparing the image against the template. - virtual double rmsd_original(const ImageViewRGB32& original_image, const WaterfillObject& object) const; - - // Return the image template mesh - const ImageRGB32& image_template() const { return m_matcher->image_template(); } - -protected: - virtual bool check_image(const ImageViewRGB32& image) const{ return true; }; - bool check_aspect_ratio(size_t candidate_width, size_t candidate_height) const; - bool check_area_ratio(double candidate_area_ratio) const; - -protected: - // Below are thresholds of aspect ratio and area ratio to reject a candidate. - // They are ususally set by the derived class of `WaterfillTemplateMatcher`. - double m_aspect_ratio_lower = 0.80; - double m_aspect_ratio_upper = 1.25; - double m_area_ratio_lower = 0.80; - double m_area_ratio_upper = 1.25; - - std::unique_ptr m_matcher; - double m_area_ratio; -}; - - - -} -} -#endif +/* Waterfill Template Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_WaterfillTemplateMatcher_H +#define PokemonAutomation_CommonTools_WaterfillTemplateMatcher_H + +#include +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/ImageMatch/ExactImageMatcher.h" + +namespace PokemonAutomation{ +namespace ImageMatch{ + + +// Used to match an image or a waterfill object against a template object. +class WaterfillTemplateMatcher{ +protected: + using WaterfillObject = Kernels::Waterfill::WaterfillObject; + +public: + WaterfillTemplateMatcher(WaterfillTemplateMatcher&&) = default; + virtual ~WaterfillTemplateMatcher() = default; + + +public: + // Load a template image from disk, min_color and max_color denote the color range of the object + // displayed in the image file while min_area is the minimum number of pixels required for the + // object in the template to be loaded. + // + // The portion of the image holding the found object will get cropped and saved as the actual template image. + // So if someone changes the template image by padding it to make it larger, as long as the padded color + // does not fall into [min_color and max_color] range, it will not affect the template matching outcome + // in any way. + // + // Throw FileException when there is no object meeting the requirement in the template. + // If there are more than one objects meeting the requirement in the template, pick the one + // with the largest area (largest number of pixels). + WaterfillTemplateMatcher( + const char* path, + Color min_color, Color max_color, + size_t min_area + ); + + // Compute RMSD of the current image against the template as-is, using `ExactImageMatcher`. + // `ExactImageMatcher` will resize the image to match template size and scale template brightness to match the image + // before computing RMSD. + // In case the image is invalid, return a large value. + // It also calls the virtual function `check_image()` on the image. + // If the function returns false, then return a large value. + double rmsd(const ImageViewRGB32& image) const; + + // Compute RMSD of the object on the image against the template. + // The input `cropped_image` is already cropped from a full image using the bounding box of the input waterfill `object`. + // This cropped image is compared against the template as-is. + // The waterfill object's aspect ratio and area ratio are checked against template's. Return a large value + // if the check fails. + // See `double rmsd(const ImageViewRGB32& image) const` on the details of comparing the image against the template. + virtual double rmsd_precropped(const ImageViewRGB32& cropped_image, const WaterfillObject& object) const; + + // Compute RMSD of the object on the image against the template. + // It will crop the original image using the bounding box of the waterfill object, then compare the cropped + // image against the template as-is. + // The waterfill object's aspect ratio and area ratio are checked against template's. Return a large value + // if the check fails. + // See `double rmsd(const ImageViewRGB32& image) const` on the details of comparing the image against the template. + virtual double rmsd_original(const ImageViewRGB32& original_image, const WaterfillObject& object) const; + + // Return the image template mesh + const ImageRGB32& image_template() const { return m_matcher->image_template(); } + +protected: + virtual bool check_image(const ImageViewRGB32& image) const{ return true; }; + bool check_aspect_ratio(size_t candidate_width, size_t candidate_height) const; + bool check_area_ratio(double candidate_area_ratio) const; + +protected: + // Below are thresholds of aspect ratio and area ratio to reject a candidate. + // They are ususally set by the derived class of `WaterfillTemplateMatcher`. + double m_aspect_ratio_lower = 0.80; + double m_aspect_ratio_upper = 1.25; + double m_area_ratio_lower = 0.80; + double m_area_ratio_upper = 1.25; + + std::unique_ptr m_matcher; + double m_area_ratio; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Images/BinaryImage_FilterRgb32.cpp b/SerialPrograms/Source/CommonTools/Images/BinaryImage_FilterRgb32.cpp index 284548a10c..a0d3cb2239 100644 --- a/SerialPrograms/Source/CommonTools/Images/BinaryImage_FilterRgb32.cpp +++ b/SerialPrograms/Source/CommonTools/Images/BinaryImage_FilterRgb32.cpp @@ -1,217 +1,217 @@ -/* Binary Image - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters.h" -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "BinaryImage_FilterRgb32.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -void filter_by_mask( - const PackedBinaryMatrix& matrix, - ImageRGB32& image, - Color replacement_color, - bool replace_zero_bits -){ - if (matrix.width() > image.width()){ - dump_image( - global_logger_tagged(), ProgramInfo(), - "filter_by_mask-width-matrix" + std::to_string(matrix.width()) + "x" + std::to_string(matrix.height()), - image - ); - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image width is too small."); - } - if (matrix.height() > image.height()){ - dump_image( - global_logger_tagged(), ProgramInfo(), - "filter_by_mask-width-matrix" + std::to_string(matrix.width()) + "x" + std::to_string(matrix.height()), - image - ); - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image height is too small."); - } - Kernels::filter_by_mask( - matrix, - image.data(), image.bytes_per_row(), - (uint32_t)replacement_color, replace_zero_bits - ); -} -void filter_by_mask( - const PackedBinaryMatrix& matrix, - ImageRGB32& image, size_t offset_x, size_t offset_y, - Color replacement_color, - bool replace_zero_bits -){ - if (matrix.width() > image.width()){ - dump_image( - global_logger_tagged(), ProgramInfo(), - "filter_by_mask-width-matrix" + std::to_string(matrix.width()) + "x" + std::to_string(matrix.height()), - image - ); - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image width is too small."); - } - if (matrix.height() > image.height()){ - dump_image( - global_logger_tagged(), ProgramInfo(), - "filter_by_mask-width-matrix" + std::to_string(matrix.width()) + "x" + std::to_string(matrix.height()), - image - ); - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image height is too small."); - } - size_t bytes_per_row = image.bytes_per_row(); - Kernels::filter_by_mask( - matrix, - (uint32_t*)((char*)image.data() + bytes_per_row * offset_y + offset_x * sizeof(uint32_t)), - bytes_per_row, - (uint32_t)replacement_color, replace_zero_bits - ); -} - - - - - -PackedBinaryMatrix compress_rgb32_to_binary_min( - const ImageViewRGB32& image, - uint8_t min_red, - uint8_t min_green, - uint8_t min_blue -){ - return compress_rgb32_to_binary_range( - image, - 255, 255, - min_red, 255, - min_green, 255, - min_blue, 255 - ); -} -PackedBinaryMatrix compress_rgb32_to_binary_max( - const ImageViewRGB32& image, - uint8_t max_red, - uint8_t max_green, - uint8_t max_blue -){ - return compress_rgb32_to_binary_range( - image, - 255, 255, - 0, max_red, - 0, max_green, - 0, max_blue - ); -} -PackedBinaryMatrix compress_rgb32_to_binary_range( - const ImageViewRGB32& image, - uint8_t min_red, uint8_t max_red, - uint8_t min_green, uint8_t max_green, - uint8_t min_blue, uint8_t max_blue -){ - return compress_rgb32_to_binary_range( - image, - 255, 255, - min_red, max_red, - min_green, max_green, - min_blue, max_blue - ); -} -PackedBinaryMatrix compress_rgb32_to_binary_range( - const ImageViewRGB32& image, - uint8_t min_alpha, uint8_t max_alpha, - uint8_t min_red, uint8_t max_red, - uint8_t min_green, uint8_t max_green, - uint8_t min_blue, uint8_t max_blue -){ - PackedBinaryMatrix ret(image.width(), image.height()); - Kernels::compress_rgb32_to_binary_range( - image.data(), image.bytes_per_row(), ret, - ((uint32_t)min_alpha << 24) | ((uint32_t)min_red << 16) | ((uint32_t)min_green << 8) | (uint32_t)min_blue, - ((uint32_t)max_alpha << 24) | ((uint32_t)max_red << 16) | ((uint32_t)max_green << 8) | (uint32_t)max_blue - ); - return ret; -} -PackedBinaryMatrix compress_rgb32_to_binary_range( - const ImageViewRGB32& image, - uint32_t mins, uint32_t maxs -){ - PackedBinaryMatrix ret(image.width(), image.height()); - Kernels::compress_rgb32_to_binary_range( - image.data(), image.bytes_per_row(), - ret, mins, maxs - ); - return ret; -} -std::vector compress_rgb32_to_binary_range( - const ImageViewRGB32& image, - const std::vector>& filters -){ - std::vector ret; - FixedLimitVector vec(filters.size()); - for (size_t c = 0; c < filters.size(); c++){ - ret.emplace_back(image.width(), image.height()); - vec.emplace_back(ret[c], filters[c].first, filters[c].second); - } - compress_rgb32_to_binary_range( - image.data(), image.bytes_per_row(), - vec.data(), vec.size() - ); - return ret; -} - - - -PackedBinaryMatrix compress_rgb32_to_binary_multirange( - const ImageViewRGB32& image, - const std::vector>& filters -){ - if (filters.empty()){ - PackedBinaryMatrix ret(image.width(), image.height()); - ret.set_zero(); - return ret; - } - PackedBinaryMatrix ret = compress_rgb32_to_binary_range(image, filters[0].first, filters[0].second); - for (size_t c = 1; c < filters.size(); c++){ - ret |= compress_rgb32_to_binary_range(image, filters[c].first, filters[c].second); - } - return ret; -} - - - - - - - -PackedBinaryMatrix compress_rgb32_to_binary_euclidean( - const ImageViewRGB32& image, - uint32_t expected, double max_euclidean_distance -){ - PackedBinaryMatrix ret(image.width(), image.height()); - Kernels::compress_rgb32_to_binary_euclidean( - image.data(), image.bytes_per_row(), - ret, expected, max_euclidean_distance - ); - return ret; -} - - - - - - - - - - -} +/* Binary Image + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "BinaryImage_FilterRgb32.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +void filter_by_mask( + const PackedBinaryMatrix& matrix, + ImageRGB32& image, + Color replacement_color, + bool replace_zero_bits +){ + if (matrix.width() > image.width()){ + dump_image( + global_logger_tagged(), ProgramInfo(), + "filter_by_mask-width-matrix" + std::to_string(matrix.width()) + "x" + std::to_string(matrix.height()), + image + ); + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image width is too small."); + } + if (matrix.height() > image.height()){ + dump_image( + global_logger_tagged(), ProgramInfo(), + "filter_by_mask-width-matrix" + std::to_string(matrix.width()) + "x" + std::to_string(matrix.height()), + image + ); + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image height is too small."); + } + Kernels::filter_by_mask( + matrix, + image.data(), image.bytes_per_row(), + (uint32_t)replacement_color, replace_zero_bits + ); +} +void filter_by_mask( + const PackedBinaryMatrix& matrix, + ImageRGB32& image, size_t offset_x, size_t offset_y, + Color replacement_color, + bool replace_zero_bits +){ + if (matrix.width() > image.width()){ + dump_image( + global_logger_tagged(), ProgramInfo(), + "filter_by_mask-width-matrix" + std::to_string(matrix.width()) + "x" + std::to_string(matrix.height()), + image + ); + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image width is too small."); + } + if (matrix.height() > image.height()){ + dump_image( + global_logger_tagged(), ProgramInfo(), + "filter_by_mask-width-matrix" + std::to_string(matrix.width()) + "x" + std::to_string(matrix.height()), + image + ); + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image height is too small."); + } + size_t bytes_per_row = image.bytes_per_row(); + Kernels::filter_by_mask( + matrix, + (uint32_t*)((char*)image.data() + bytes_per_row * offset_y + offset_x * sizeof(uint32_t)), + bytes_per_row, + (uint32_t)replacement_color, replace_zero_bits + ); +} + + + + + +PackedBinaryMatrix compress_rgb32_to_binary_min( + const ImageViewRGB32& image, + uint8_t min_red, + uint8_t min_green, + uint8_t min_blue +){ + return compress_rgb32_to_binary_range( + image, + 255, 255, + min_red, 255, + min_green, 255, + min_blue, 255 + ); +} +PackedBinaryMatrix compress_rgb32_to_binary_max( + const ImageViewRGB32& image, + uint8_t max_red, + uint8_t max_green, + uint8_t max_blue +){ + return compress_rgb32_to_binary_range( + image, + 255, 255, + 0, max_red, + 0, max_green, + 0, max_blue + ); +} +PackedBinaryMatrix compress_rgb32_to_binary_range( + const ImageViewRGB32& image, + uint8_t min_red, uint8_t max_red, + uint8_t min_green, uint8_t max_green, + uint8_t min_blue, uint8_t max_blue +){ + return compress_rgb32_to_binary_range( + image, + 255, 255, + min_red, max_red, + min_green, max_green, + min_blue, max_blue + ); +} +PackedBinaryMatrix compress_rgb32_to_binary_range( + const ImageViewRGB32& image, + uint8_t min_alpha, uint8_t max_alpha, + uint8_t min_red, uint8_t max_red, + uint8_t min_green, uint8_t max_green, + uint8_t min_blue, uint8_t max_blue +){ + PackedBinaryMatrix ret(image.width(), image.height()); + Kernels::compress_rgb32_to_binary_range( + image.data(), image.bytes_per_row(), ret, + ((uint32_t)min_alpha << 24) | ((uint32_t)min_red << 16) | ((uint32_t)min_green << 8) | (uint32_t)min_blue, + ((uint32_t)max_alpha << 24) | ((uint32_t)max_red << 16) | ((uint32_t)max_green << 8) | (uint32_t)max_blue + ); + return ret; +} +PackedBinaryMatrix compress_rgb32_to_binary_range( + const ImageViewRGB32& image, + uint32_t mins, uint32_t maxs +){ + PackedBinaryMatrix ret(image.width(), image.height()); + Kernels::compress_rgb32_to_binary_range( + image.data(), image.bytes_per_row(), + ret, mins, maxs + ); + return ret; +} +std::vector compress_rgb32_to_binary_range( + const ImageViewRGB32& image, + const std::vector>& filters +){ + std::vector ret; + FixedLimitVector vec(filters.size()); + for (size_t c = 0; c < filters.size(); c++){ + ret.emplace_back(image.width(), image.height()); + vec.emplace_back(ret[c], filters[c].first, filters[c].second); + } + compress_rgb32_to_binary_range( + image.data(), image.bytes_per_row(), + vec.data(), vec.size() + ); + return ret; +} + + + +PackedBinaryMatrix compress_rgb32_to_binary_multirange( + const ImageViewRGB32& image, + const std::vector>& filters +){ + if (filters.empty()){ + PackedBinaryMatrix ret(image.width(), image.height()); + ret.set_zero(); + return ret; + } + PackedBinaryMatrix ret = compress_rgb32_to_binary_range(image, filters[0].first, filters[0].second); + for (size_t c = 1; c < filters.size(); c++){ + ret |= compress_rgb32_to_binary_range(image, filters[c].first, filters[c].second); + } + return ret; +} + + + + + + + +PackedBinaryMatrix compress_rgb32_to_binary_euclidean( + const ImageViewRGB32& image, + uint32_t expected, double max_euclidean_distance +){ + PackedBinaryMatrix ret(image.width(), image.height()); + Kernels::compress_rgb32_to_binary_euclidean( + image.data(), image.bytes_per_row(), + ret, expected, max_euclidean_distance + ); + return ret; +} + + + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonTools/Images/BinaryImage_FilterRgb32.h b/SerialPrograms/Source/CommonTools/Images/BinaryImage_FilterRgb32.h index 4e0f67f80e..79cb8873a9 100644 --- a/SerialPrograms/Source/CommonTools/Images/BinaryImage_FilterRgb32.h +++ b/SerialPrograms/Source/CommonTools/Images/BinaryImage_FilterRgb32.h @@ -1,110 +1,110 @@ -/* Binary Image Filter RGB32 - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_BinaryImage_FilterRgb32_H -#define PokemonAutomation_CommonTools_BinaryImage_FilterRgb32_H - -#include -#include -#include "Common/Cpp/Color.h" -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix.h" -#include "Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTypes/BinaryImage.h" - -namespace PokemonAutomation{ - - -// Selectively replace pixels in `image` with the replacement color -// according to the respective bits in the binary matrix. -// If `replace_zero_bits` is true, replace pixels corresponding to the zero bits. -// Else, replace those with the one bits. -void filter_by_mask( - const PackedBinaryMatrix& matrix, - ImageRGB32& image, - Color replacement_color, - bool replace_zero_bits -); -// Selectively replace pixels in an area of the `image` with the replacement color -// according to the respective bits in the binary matrix. -// If `replace_zero_bits` is true, replace pixels corresponding to the zero bits. -// Else, replace those with the one bits. -// The image area starts at (offset_x, offset_y) with the same (width, height) as -// the matrix. -void filter_by_mask( - const PackedBinaryMatrix& matrix, - ImageRGB32& image, size_t offset_x, size_t offset_y, - Color replacement_color, - bool replace_zero_bits -); - - - - - -PackedBinaryMatrix compress_rgb32_to_binary_min( - const ImageViewRGB32& image, - uint8_t min_red, - uint8_t min_green, - uint8_t min_blue -); -PackedBinaryMatrix compress_rgb32_to_binary_max( - const ImageViewRGB32& image, - uint8_t max_red, - uint8_t max_green, - uint8_t max_blue -); -PackedBinaryMatrix compress_rgb32_to_binary_range( - const ImageViewRGB32& image, - uint8_t min_red, uint8_t max_red, - uint8_t min_green, uint8_t max_green, - uint8_t min_blue, uint8_t max_blue -); -PackedBinaryMatrix compress_rgb32_to_binary_range( - const ImageViewRGB32& image, - uint8_t min_alpha, uint8_t max_alpha, - uint8_t min_red, uint8_t max_red, - uint8_t min_green, uint8_t max_green, - uint8_t min_blue, uint8_t max_blue -); -PackedBinaryMatrix compress_rgb32_to_binary_range( - const ImageViewRGB32& image, - uint32_t mins, uint32_t maxs -); - - - -// Run multiple filters at once. This is more memory efficient than making -// multiple calls to one filter at a time. -// Pixels Within filter color ranges are marked as 1 in the corresponding binary matrices, -// while those output of range are 0. -std::vector compress_rgb32_to_binary_range( - const ImageViewRGB32& image, - const std::vector>& filters -); - - - -// Run multiple filters and OR them all together. (experimental) -PackedBinaryMatrix compress_rgb32_to_binary_multirange( - const ImageViewRGB32& image, - const std::vector>& filters -); - - - - - -PackedBinaryMatrix compress_rgb32_to_binary_euclidean( - const ImageViewRGB32& image, - uint32_t expected, double max_euclidean_distance -); - - - - -} -#endif +/* Binary Image Filter RGB32 + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_BinaryImage_FilterRgb32_H +#define PokemonAutomation_CommonTools_BinaryImage_FilterRgb32_H + +#include +#include +#include "Common/Cpp/Color.h" +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix.h" +#include "Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTypes/BinaryImage.h" + +namespace PokemonAutomation{ + + +// Selectively replace pixels in `image` with the replacement color +// according to the respective bits in the binary matrix. +// If `replace_zero_bits` is true, replace pixels corresponding to the zero bits. +// Else, replace those with the one bits. +void filter_by_mask( + const PackedBinaryMatrix& matrix, + ImageRGB32& image, + Color replacement_color, + bool replace_zero_bits +); +// Selectively replace pixels in an area of the `image` with the replacement color +// according to the respective bits in the binary matrix. +// If `replace_zero_bits` is true, replace pixels corresponding to the zero bits. +// Else, replace those with the one bits. +// The image area starts at (offset_x, offset_y) with the same (width, height) as +// the matrix. +void filter_by_mask( + const PackedBinaryMatrix& matrix, + ImageRGB32& image, size_t offset_x, size_t offset_y, + Color replacement_color, + bool replace_zero_bits +); + + + + + +PackedBinaryMatrix compress_rgb32_to_binary_min( + const ImageViewRGB32& image, + uint8_t min_red, + uint8_t min_green, + uint8_t min_blue +); +PackedBinaryMatrix compress_rgb32_to_binary_max( + const ImageViewRGB32& image, + uint8_t max_red, + uint8_t max_green, + uint8_t max_blue +); +PackedBinaryMatrix compress_rgb32_to_binary_range( + const ImageViewRGB32& image, + uint8_t min_red, uint8_t max_red, + uint8_t min_green, uint8_t max_green, + uint8_t min_blue, uint8_t max_blue +); +PackedBinaryMatrix compress_rgb32_to_binary_range( + const ImageViewRGB32& image, + uint8_t min_alpha, uint8_t max_alpha, + uint8_t min_red, uint8_t max_red, + uint8_t min_green, uint8_t max_green, + uint8_t min_blue, uint8_t max_blue +); +PackedBinaryMatrix compress_rgb32_to_binary_range( + const ImageViewRGB32& image, + uint32_t mins, uint32_t maxs +); + + + +// Run multiple filters at once. This is more memory efficient than making +// multiple calls to one filter at a time. +// Pixels Within filter color ranges are marked as 1 in the corresponding binary matrices, +// while those output of range are 0. +std::vector compress_rgb32_to_binary_range( + const ImageViewRGB32& image, + const std::vector>& filters +); + + + +// Run multiple filters and OR them all together. (experimental) +PackedBinaryMatrix compress_rgb32_to_binary_multirange( + const ImageViewRGB32& image, + const std::vector>& filters +); + + + + + +PackedBinaryMatrix compress_rgb32_to_binary_euclidean( + const ImageViewRGB32& image, + uint32_t expected, double max_euclidean_distance +); + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Images/ColorClustering.cpp b/SerialPrograms/Source/CommonTools/Images/ColorClustering.cpp index bd27390d14..b9ace1f81a 100644 --- a/SerialPrograms/Source/CommonTools/Images/ColorClustering.cpp +++ b/SerialPrograms/Source/CommonTools/Images/ColorClustering.cpp @@ -1,183 +1,183 @@ -/* Color Clustering - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "ColorClustering.h" - -#include -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - -void PixelEuclideanStatAccumulator::clear(){ - m_count = 0; - m_sum_x = 0; - m_sum_y = 0; - m_sum_z = 0; - m_sqr_x = 0; - m_sqr_y = 0; - m_sqr_z = 0; -} -void PixelEuclideanStatAccumulator::operator+=(FloatPixel pixel){ - m_count++; - m_sum_x += pixel.r; - m_sum_y += pixel.g; - m_sum_z += pixel.b; - m_sqr_x += pixel.r * pixel.r; - m_sqr_y += pixel.g * pixel.g; - m_sqr_z += pixel.b * pixel.b; -} -uint64_t PixelEuclideanStatAccumulator::count() const{ - return m_count; -} -FloatPixel PixelEuclideanStatAccumulator::center() const{ - return FloatPixel(m_sum_x / m_count, m_sum_y / m_count, m_sum_z / m_count); -} -double PixelEuclideanStatAccumulator::deviation() const{ - if (m_count < 1){ - return 0; - } - double variance = m_sqr_x + m_sqr_y + m_sqr_z; - variance -= (m_sum_x*m_sum_x + m_sum_y*m_sum_y + m_sum_z*m_sum_z) / m_count; - return std::sqrt(variance / (m_count - 1)); -} - - -double cluster_fit_2( - const ImageViewRGB32& image, - Color color0, PixelEuclideanStatAccumulator& cluster0, - Color color1, PixelEuclideanStatAccumulator& cluster1 -){ - size_t width = image.width(); - size_t height = image.height(); - - FloatPixel f0(color0); - FloatPixel f1(color1); - - PixelEuclideanStatAccumulator stats0; - PixelEuclideanStatAccumulator stats1; - -// image.save("points.png"); -// std::fstream ss("points.txt", std::fstream::out); - - for (size_t r = 0; r < height; r++){ - for (size_t c = 0; c < width; c++){ - Color pixel(image.pixel(c, r)); -// ss << "{" << (int)pixel.red() << ", " << (int)pixel.green() << ", " << (int)pixel.blue() << "}," << endl; - FloatPixel p0 = f0 - pixel; - FloatPixel p1 = f1 - pixel; - double distance0 = (p0 * p0).sum(); - double distance1 = (p1 * p1).sum(); - if (distance0 < distance1){ - stats0 += pixel; -// cout << (int)pixel.red() << ", " << (int)pixel.green() << ", " << (int)pixel.blue() << ": " << std::sqrt(distance0) << endl; - }else{ - stats1 += pixel; -// cout << (int)pixel.red() << ", " << (int)pixel.green() << ", " << (int)pixel.blue() << ": " << std::sqrt(distance1) << endl; -// cout << "stats = " << stats1.center() << endl; - } - } - } - -#if 0 - cout << "color0 = " << stats0.count() << ": " << stats0.center() << ", " << stats0.deviation() << endl; - cout << "color1 = " << stats1.count() << ": " << stats1.center() << ", " << stats1.deviation() << endl; -#endif - - cluster0 = stats0; - cluster1 = stats1; - -// cout << "stats = " << stats1.center() << endl; - - return (stats0.deviation() * stats0.count() + stats1.deviation() * stats1.count()) / (stats0.count() + stats1.count()); -} - -bool cluster_fit_2( - const ImageViewRGB32& image, - Color color0, double ratio0, - Color color1, double ratio1, - double ratio_threshold, - double deviation_threshold, - double distance_threshold -){ - const size_t NUM_CLUSTERS = 2; - - if (!image){ - return false; - } - size_t total = image.width() * image.height(); - - FloatPixel center_desired[NUM_CLUSTERS] = {color0, color1}; - double count_ratio_desired[NUM_CLUSTERS] = {ratio0, ratio1}; - - PixelEuclideanStatAccumulator cluster[NUM_CLUSTERS]; - cluster_fit_2(image, color0, cluster[0], color1, cluster[1]); - color0 = cluster[0].center().round(); - color1 = cluster[1].center().round(); - double deviation = cluster_fit_2(image, color0, cluster[0], color1, cluster[1]); -// cout << "deviation = " << deviation << ", threshold = " << deviation_threshold << endl; -// cout << cluster[0].count() << " / " << cluster[1].count() << endl; - if (deviation > deviation_threshold){ -// cout << "deviation out" << endl; -// image.save("test.png"); - return false; - } - - FloatPixel center_actual[NUM_CLUSTERS]; - double count_ratio_actual[NUM_CLUSTERS]; - - double ratio_sum = 0; - for (size_t c = 0; c < NUM_CLUSTERS; c++){ - ratio_sum += count_ratio_desired[c]; - center_actual[c] = cluster[c].center(); - } -// cout << "---------------" << endl; - for (size_t c = 0; c < NUM_CLUSTERS; c++){ -// cout << cluster[c].count() << ": " << cluster[c].center() << ", " << cluster[c].deviation() << endl; - - count_ratio_desired[c] /= ratio_sum; - count_ratio_actual[c] = (double)cluster[c].count() / total; - double diff = std::abs(count_ratio_actual[c] - count_ratio_desired[c]); -// cout << "Color Ratio Diff: " << diff << endl; - if (diff > ratio_threshold){ -// cout << "Color Ratio Diff is Too Large: " << diff << endl; -// cout << "desired = " << count_ratio_desired[c] << endl; -// cout << "actual = " << count_ratio_actual[c] << endl; - return false; - } - - if (center_desired[c].sum() < 50){ -// cout << "Black" << endl; - double distance = euclidean_distance(center_desired[c], center_actual[c]) * count_ratio_desired[c]; - if (distance > 40){ -// cout << "Black Distance is Too Large: " << distance << endl; - return false; - } - }else{ -// cout << "Not Black" << endl; - FloatPixel ratio_desired = center_desired[c] / center_desired[c].sum(); - FloatPixel ratio_actual = center_actual[c] / center_actual[c].sum(); - double distance = euclidean_distance(ratio_desired, ratio_actual); -// cout << ratio_desired << " / " << ratio_actual << " = " << distance << endl; - if (distance > distance_threshold){ -// cout << distance << " > " << distance_threshold << endl; - return false; - } - } - } - -// cout << "match" << endl; - return true; -} - - - - -} - +/* Color Clustering + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "ColorClustering.h" + +#include +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + +void PixelEuclideanStatAccumulator::clear(){ + m_count = 0; + m_sum_x = 0; + m_sum_y = 0; + m_sum_z = 0; + m_sqr_x = 0; + m_sqr_y = 0; + m_sqr_z = 0; +} +void PixelEuclideanStatAccumulator::operator+=(FloatPixel pixel){ + m_count++; + m_sum_x += pixel.r; + m_sum_y += pixel.g; + m_sum_z += pixel.b; + m_sqr_x += pixel.r * pixel.r; + m_sqr_y += pixel.g * pixel.g; + m_sqr_z += pixel.b * pixel.b; +} +uint64_t PixelEuclideanStatAccumulator::count() const{ + return m_count; +} +FloatPixel PixelEuclideanStatAccumulator::center() const{ + return FloatPixel(m_sum_x / m_count, m_sum_y / m_count, m_sum_z / m_count); +} +double PixelEuclideanStatAccumulator::deviation() const{ + if (m_count < 1){ + return 0; + } + double variance = m_sqr_x + m_sqr_y + m_sqr_z; + variance -= (m_sum_x*m_sum_x + m_sum_y*m_sum_y + m_sum_z*m_sum_z) / m_count; + return std::sqrt(variance / (m_count - 1)); +} + + +double cluster_fit_2( + const ImageViewRGB32& image, + Color color0, PixelEuclideanStatAccumulator& cluster0, + Color color1, PixelEuclideanStatAccumulator& cluster1 +){ + size_t width = image.width(); + size_t height = image.height(); + + FloatPixel f0(color0); + FloatPixel f1(color1); + + PixelEuclideanStatAccumulator stats0; + PixelEuclideanStatAccumulator stats1; + +// image.save("points.png"); +// std::fstream ss("points.txt", std::fstream::out); + + for (size_t r = 0; r < height; r++){ + for (size_t c = 0; c < width; c++){ + Color pixel(image.pixel(c, r)); +// ss << "{" << (int)pixel.red() << ", " << (int)pixel.green() << ", " << (int)pixel.blue() << "}," << endl; + FloatPixel p0 = f0 - pixel; + FloatPixel p1 = f1 - pixel; + double distance0 = (p0 * p0).sum(); + double distance1 = (p1 * p1).sum(); + if (distance0 < distance1){ + stats0 += pixel; +// cout << (int)pixel.red() << ", " << (int)pixel.green() << ", " << (int)pixel.blue() << ": " << std::sqrt(distance0) << endl; + }else{ + stats1 += pixel; +// cout << (int)pixel.red() << ", " << (int)pixel.green() << ", " << (int)pixel.blue() << ": " << std::sqrt(distance1) << endl; +// cout << "stats = " << stats1.center() << endl; + } + } + } + +#if 0 + cout << "color0 = " << stats0.count() << ": " << stats0.center() << ", " << stats0.deviation() << endl; + cout << "color1 = " << stats1.count() << ": " << stats1.center() << ", " << stats1.deviation() << endl; +#endif + + cluster0 = stats0; + cluster1 = stats1; + +// cout << "stats = " << stats1.center() << endl; + + return (stats0.deviation() * stats0.count() + stats1.deviation() * stats1.count()) / (stats0.count() + stats1.count()); +} + +bool cluster_fit_2( + const ImageViewRGB32& image, + Color color0, double ratio0, + Color color1, double ratio1, + double ratio_threshold, + double deviation_threshold, + double distance_threshold +){ + const size_t NUM_CLUSTERS = 2; + + if (!image){ + return false; + } + size_t total = image.width() * image.height(); + + FloatPixel center_desired[NUM_CLUSTERS] = {color0, color1}; + double count_ratio_desired[NUM_CLUSTERS] = {ratio0, ratio1}; + + PixelEuclideanStatAccumulator cluster[NUM_CLUSTERS]; + cluster_fit_2(image, color0, cluster[0], color1, cluster[1]); + color0 = cluster[0].center().round(); + color1 = cluster[1].center().round(); + double deviation = cluster_fit_2(image, color0, cluster[0], color1, cluster[1]); +// cout << "deviation = " << deviation << ", threshold = " << deviation_threshold << endl; +// cout << cluster[0].count() << " / " << cluster[1].count() << endl; + if (deviation > deviation_threshold){ +// cout << "deviation out" << endl; +// image.save("test.png"); + return false; + } + + FloatPixel center_actual[NUM_CLUSTERS]; + double count_ratio_actual[NUM_CLUSTERS]; + + double ratio_sum = 0; + for (size_t c = 0; c < NUM_CLUSTERS; c++){ + ratio_sum += count_ratio_desired[c]; + center_actual[c] = cluster[c].center(); + } +// cout << "---------------" << endl; + for (size_t c = 0; c < NUM_CLUSTERS; c++){ +// cout << cluster[c].count() << ": " << cluster[c].center() << ", " << cluster[c].deviation() << endl; + + count_ratio_desired[c] /= ratio_sum; + count_ratio_actual[c] = (double)cluster[c].count() / total; + double diff = std::abs(count_ratio_actual[c] - count_ratio_desired[c]); +// cout << "Color Ratio Diff: " << diff << endl; + if (diff > ratio_threshold){ +// cout << "Color Ratio Diff is Too Large: " << diff << endl; +// cout << "desired = " << count_ratio_desired[c] << endl; +// cout << "actual = " << count_ratio_actual[c] << endl; + return false; + } + + if (center_desired[c].sum() < 50){ +// cout << "Black" << endl; + double distance = euclidean_distance(center_desired[c], center_actual[c]) * count_ratio_desired[c]; + if (distance > 40){ +// cout << "Black Distance is Too Large: " << distance << endl; + return false; + } + }else{ +// cout << "Not Black" << endl; + FloatPixel ratio_desired = center_desired[c] / center_desired[c].sum(); + FloatPixel ratio_actual = center_actual[c] / center_actual[c].sum(); + double distance = euclidean_distance(ratio_desired, ratio_actual); +// cout << ratio_desired << " / " << ratio_actual << " = " << distance << endl; + if (distance > distance_threshold){ +// cout << distance << " > " << distance_threshold << endl; + return false; + } + } + } + +// cout << "match" << endl; + return true; +} + + + + +} + diff --git a/SerialPrograms/Source/CommonTools/Images/ColorClustering.h b/SerialPrograms/Source/CommonTools/Images/ColorClustering.h index 54d49d062a..4035dce92c 100644 --- a/SerialPrograms/Source/CommonTools/Images/ColorClustering.h +++ b/SerialPrograms/Source/CommonTools/Images/ColorClustering.h @@ -1,52 +1,52 @@ -/* Color Clustering - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_ColorClustering_H -#define PokemonAutomation_CommonTools_ColorClustering_H - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/FloatPixel.h" - -namespace PokemonAutomation{ - - -class PixelEuclideanStatAccumulator{ -public: - void clear(); - void operator+=(FloatPixel pixel); - - uint64_t count() const; - FloatPixel center() const; - double deviation() const; - -private: - uint64_t m_count = 0; - double m_sum_x = 0; - double m_sum_y = 0; - double m_sum_z = 0; - double m_sqr_x = 0; - double m_sqr_y = 0; - double m_sqr_z = 0; -}; - -double cluster_fit_2( - const ImageViewRGB32& image, - Color color0, PixelEuclideanStatAccumulator& cluster0, - Color color1, PixelEuclideanStatAccumulator& cluster1 -); - -bool cluster_fit_2( - const ImageViewRGB32& image, - Color color0, double ratio0, - Color color1, double ratio1, - double ratio_threshold = 0.2, - double deviation_threshold = 50, - double distance_threshold = 0.25 -); - - -} -#endif +/* Color Clustering + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_ColorClustering_H +#define PokemonAutomation_CommonTools_ColorClustering_H + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/FloatPixel.h" + +namespace PokemonAutomation{ + + +class PixelEuclideanStatAccumulator{ +public: + void clear(); + void operator+=(FloatPixel pixel); + + uint64_t count() const; + FloatPixel center() const; + double deviation() const; + +private: + uint64_t m_count = 0; + double m_sum_x = 0; + double m_sum_y = 0; + double m_sum_z = 0; + double m_sqr_x = 0; + double m_sqr_y = 0; + double m_sqr_z = 0; +}; + +double cluster_fit_2( + const ImageViewRGB32& image, + Color color0, PixelEuclideanStatAccumulator& cluster0, + Color color1, PixelEuclideanStatAccumulator& cluster1 +); + +bool cluster_fit_2( + const ImageViewRGB32& image, + Color color0, double ratio0, + Color color1, double ratio1, + double ratio_threshold = 0.2, + double deviation_threshold = 50, + double distance_threshold = 0.25 +); + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Images/DistanceToLine.h b/SerialPrograms/Source/CommonTools/Images/DistanceToLine.h index 83e3085372..8e56981674 100644 --- a/SerialPrograms/Source/CommonTools/Images/DistanceToLine.h +++ b/SerialPrograms/Source/CommonTools/Images/DistanceToLine.h @@ -1,58 +1,58 @@ -/* Distance to Line - * - * From: https://github.com/PokemonAutomation/ - * - * - * Return a set of connected clusters. - * - */ - -#ifndef PokemonAutomation_CommonTools_DistanceToLine_H -#define PokemonAutomation_CommonTools_DistanceToLine_H - -#include - -namespace PokemonAutomation{ - - -class DistanceToLine{ -public: - DistanceToLine( - ptrdiff_t vertex0_x, ptrdiff_t vertex0_y, - ptrdiff_t vertex1_x, ptrdiff_t vertex1_y - ) - : m_vertical(vertex0_x == vertex1_x) - , m_vertex0_x(vertex0_x) - , m_vertex0_y(vertex0_y) -// , m_vertex1_x(vertex1_x) -// , m_vertex1_y(vertex1_y) - , m_slope((double)(vertex1_y - vertex0_y) / (vertex1_x - vertex0_x)) - , m_inverse(1 / (m_slope*m_slope + 1)) - {} - - double distance_squared(ptrdiff_t x, ptrdiff_t y) const{ - if (m_vertical){ - ptrdiff_t distance = x - m_vertex0_x; - return (double)(distance * distance); - } - ptrdiff_t dx = x - m_vertex0_x; - ptrdiff_t dy = y - m_vertex0_y; - double top = m_slope * dx - dy; - double distance_sqr = top * top * m_inverse; - return distance_sqr; - } - -private: - bool m_vertical; - ptrdiff_t m_vertex0_x; - ptrdiff_t m_vertex0_y; -// ptrdiff_t m_vertex1_x; -// ptrdiff_t m_vertex1_y; - double m_slope; - double m_inverse; -}; - - - -} -#endif +/* Distance to Line + * + * From: https://github.com/PokemonAutomation/ + * + * + * Return a set of connected clusters. + * + */ + +#ifndef PokemonAutomation_CommonTools_DistanceToLine_H +#define PokemonAutomation_CommonTools_DistanceToLine_H + +#include + +namespace PokemonAutomation{ + + +class DistanceToLine{ +public: + DistanceToLine( + ptrdiff_t vertex0_x, ptrdiff_t vertex0_y, + ptrdiff_t vertex1_x, ptrdiff_t vertex1_y + ) + : m_vertical(vertex0_x == vertex1_x) + , m_vertex0_x(vertex0_x) + , m_vertex0_y(vertex0_y) +// , m_vertex1_x(vertex1_x) +// , m_vertex1_y(vertex1_y) + , m_slope((double)(vertex1_y - vertex0_y) / (vertex1_x - vertex0_x)) + , m_inverse(1 / (m_slope*m_slope + 1)) + {} + + double distance_squared(ptrdiff_t x, ptrdiff_t y) const{ + if (m_vertical){ + ptrdiff_t distance = x - m_vertex0_x; + return (double)(distance * distance); + } + ptrdiff_t dx = x - m_vertex0_x; + ptrdiff_t dy = y - m_vertex0_y; + double top = m_slope * dx - dy; + double distance_sqr = top * top * m_inverse; + return distance_sqr; + } + +private: + bool m_vertical; + ptrdiff_t m_vertex0_x; + ptrdiff_t m_vertex0_y; +// ptrdiff_t m_vertex1_x; +// ptrdiff_t m_vertex1_y; + double m_slope; + double m_inverse; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Images/ImageFilter.cpp b/SerialPrograms/Source/CommonTools/Images/ImageFilter.cpp index 0a201560e6..2c0c0033e4 100644 --- a/SerialPrograms/Source/CommonTools/Images/ImageFilter.cpp +++ b/SerialPrograms/Source/CommonTools/Images/ImageFilter.cpp @@ -1,223 +1,223 @@ -/* Image Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic.h" -#include "Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.h" -#include "Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.h" -#include "Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "ImageFilter.h" - -namespace PokemonAutomation{ - - - -ImageRGB32 filter_rgb32_range( - const ImageViewRGB32& image, - uint32_t mins, uint32_t maxs, Color replace_with, bool replace_color_within_range -){ - ImageRGB32 ret(image.width(), image.height()); - Kernels::filter_rgb32_range( - image.data(), image.bytes_per_row(), image.width(), image.height(), - ret.data(), ret.bytes_per_row(), - (uint32_t)replace_with, replace_color_within_range, - mins, maxs - ); - return ret; -} -ImageRGB32 filter_rgb32_range( - size_t& pixels_in_range, - const ImageViewRGB32& image, - uint32_t mins, uint32_t maxs, Color replace_with, bool replace_color_within_range -){ - ImageRGB32 ret(image.width(), image.height()); - pixels_in_range = Kernels::filter_rgb32_range( - image.data(), image.bytes_per_row(), image.width(), image.height(), - ret.data(), ret.bytes_per_row(), - (uint32_t)replace_with, replace_color_within_range, - mins, maxs - ); - return ret; -} -std::vector> filter_rgb32_range( - const ImageViewRGB32& image, - const std::vector& filters -){ - std::vector> ret(filters.size()); - FixedLimitVector subfilters(filters.size()); - for (size_t c = 0; c < filters.size(); c++){ - ImageRGB32& out = ret[c].first; - out = ImageRGB32(image.width(), image.height()); - subfilters.emplace_back( - out.data(), out.bytes_per_row(), - (uint32_t)filters[c].replacement_color, filters[c].replace_color_within_range, - filters[c].mins, filters[c].maxs - ); - } - Kernels::filter_rgb32_range( - image.data(), image.bytes_per_row(), image.width(), image.height(), - subfilters.data(), subfilters.size() - ); - for (size_t c = 0; c < filters.size(); c++){ - ret[c].second = subfilters[c].pixels_in_range; - } - return ret; -} - - - -ImageRGB32 to_blackwhite_rgb32_range( - const ImageViewRGB32& image, - bool in_range_black, - uint32_t mins, uint32_t maxs -){ - ImageRGB32 ret(image.width(), image.height()); - Kernels::to_blackwhite_rgb32_range( - image.data(), image.bytes_per_row(), image.width(), image.height(), - ret.data(), ret.bytes_per_row(), - in_range_black, - mins, maxs - ); - return ret; -} -ImageRGB32 to_blackwhite_rgb32_range( - size_t& pixels_in_range, - const ImageViewRGB32& image, - bool in_range_black, - uint32_t mins, uint32_t maxs -){ - ImageRGB32 ret(image.width(), image.height()); - pixels_in_range = Kernels::to_blackwhite_rgb32_range( - image.data(), image.bytes_per_row(), image.width(), image.height(), - ret.data(), ret.bytes_per_row(), - in_range_black, - mins, maxs - ); - return ret; -} -std::vector> to_blackwhite_rgb32_range( - const ImageViewRGB32& image, - const std::vector& filters -){ - std::vector> ret(filters.size()); - FixedLimitVector subfilters(filters.size()); - for (size_t c = 0; c < filters.size(); c++){ - ImageRGB32& out = ret[c].first; - out = ImageRGB32(image.width(), image.height()); - subfilters.emplace_back( - out.data(), out.bytes_per_row(), - filters[c].mins, filters[c].maxs, (uint32_t)filters[c].in_range_black - ); - } - Kernels::to_blackwhite_rgb32_range( - image.data(), image.bytes_per_row(), image.width(), image.height(), - subfilters.data(), subfilters.size() - ); - for (size_t c = 0; c < filters.size(); c++){ - ret[c].second = subfilters[c].pixels_in_range; - } - return ret; -} - - - - - - - - - -ImageRGB32 filter_rgb32_euclidean( - const ImageViewRGB32& image, - uint32_t expected, double max_euclidean_distance, - Color replace_with, bool replace_color_within_range -){ - ImageRGB32 ret(image.width(), image.height()); - Kernels::filter_rgb32_euclidean( - image.data(), image.bytes_per_row(), image.width(), image.height(), - ret.data(), ret.bytes_per_row(), - (uint32_t)replace_with, replace_color_within_range, - expected, max_euclidean_distance - ); - return ret; -} -ImageRGB32 filter_rgb32_euclidean( - size_t& pixels_in_range, - const ImageViewRGB32& image, - uint32_t expected, double max_euclidean_distance, - Color replace_with, bool replace_color_within_range -){ - ImageRGB32 ret(image.width(), image.height()); - pixels_in_range = Kernels::filter_rgb32_euclidean( - image.data(), image.bytes_per_row(), image.width(), image.height(), - ret.data(), ret.bytes_per_row(), - (uint32_t)replace_with, replace_color_within_range, - expected, max_euclidean_distance - ); - return ret; -} - - - - - - - - - -ImageRGB32 filter_rgb32_brightness( - const ImageViewRGB32& image, - Color replacement_color, bool replace_color_within_range, - Kernels::Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -){ - ImageRGB32 ret(image.width(), image.height()); - Kernels::filter_rgb32_brightness( - image.data(), image.bytes_per_row(), image.width(), image.height(), - ret.data(), ret.bytes_per_row(), - (uint32_t)replacement_color, replace_color_within_range, - weights, - min_brightness, max_brightness - ); - return ret; -} -ImageRGB32 to_blackwhite_rgb32_brightness( - const ImageViewRGB32& image, - bool in_range_black, - Kernels::Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -){ - ImageRGB32 ret(image.width(), image.height()); - Kernels::to_blackwhite_rgb32_brightness( - image.data(), image.bytes_per_row(), image.width(), image.height(), - ret.data(), ret.bytes_per_row(), - in_range_black, - weights, - min_brightness, max_brightness - ); - return ret; -} - - - -ImageRGB32 filter_green( - const ImageViewRGB32& image, - Color replace_with, - uint8_t rgb_gap -){ - ImageRGB32 ret(image.width(), image.height()); - Kernels::filter_green( - image.data(), image.bytes_per_row(), image.width(), image.height(), - ret.data(), ret.bytes_per_row(), (uint32_t)replace_with, rgb_gap - ); - return ret; -} - - - -} +/* Image Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic.h" +#include "Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.h" +#include "Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.h" +#include "Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "ImageFilter.h" + +namespace PokemonAutomation{ + + + +ImageRGB32 filter_rgb32_range( + const ImageViewRGB32& image, + uint32_t mins, uint32_t maxs, Color replace_with, bool replace_color_within_range +){ + ImageRGB32 ret(image.width(), image.height()); + Kernels::filter_rgb32_range( + image.data(), image.bytes_per_row(), image.width(), image.height(), + ret.data(), ret.bytes_per_row(), + (uint32_t)replace_with, replace_color_within_range, + mins, maxs + ); + return ret; +} +ImageRGB32 filter_rgb32_range( + size_t& pixels_in_range, + const ImageViewRGB32& image, + uint32_t mins, uint32_t maxs, Color replace_with, bool replace_color_within_range +){ + ImageRGB32 ret(image.width(), image.height()); + pixels_in_range = Kernels::filter_rgb32_range( + image.data(), image.bytes_per_row(), image.width(), image.height(), + ret.data(), ret.bytes_per_row(), + (uint32_t)replace_with, replace_color_within_range, + mins, maxs + ); + return ret; +} +std::vector> filter_rgb32_range( + const ImageViewRGB32& image, + const std::vector& filters +){ + std::vector> ret(filters.size()); + FixedLimitVector subfilters(filters.size()); + for (size_t c = 0; c < filters.size(); c++){ + ImageRGB32& out = ret[c].first; + out = ImageRGB32(image.width(), image.height()); + subfilters.emplace_back( + out.data(), out.bytes_per_row(), + (uint32_t)filters[c].replacement_color, filters[c].replace_color_within_range, + filters[c].mins, filters[c].maxs + ); + } + Kernels::filter_rgb32_range( + image.data(), image.bytes_per_row(), image.width(), image.height(), + subfilters.data(), subfilters.size() + ); + for (size_t c = 0; c < filters.size(); c++){ + ret[c].second = subfilters[c].pixels_in_range; + } + return ret; +} + + + +ImageRGB32 to_blackwhite_rgb32_range( + const ImageViewRGB32& image, + bool in_range_black, + uint32_t mins, uint32_t maxs +){ + ImageRGB32 ret(image.width(), image.height()); + Kernels::to_blackwhite_rgb32_range( + image.data(), image.bytes_per_row(), image.width(), image.height(), + ret.data(), ret.bytes_per_row(), + in_range_black, + mins, maxs + ); + return ret; +} +ImageRGB32 to_blackwhite_rgb32_range( + size_t& pixels_in_range, + const ImageViewRGB32& image, + bool in_range_black, + uint32_t mins, uint32_t maxs +){ + ImageRGB32 ret(image.width(), image.height()); + pixels_in_range = Kernels::to_blackwhite_rgb32_range( + image.data(), image.bytes_per_row(), image.width(), image.height(), + ret.data(), ret.bytes_per_row(), + in_range_black, + mins, maxs + ); + return ret; +} +std::vector> to_blackwhite_rgb32_range( + const ImageViewRGB32& image, + const std::vector& filters +){ + std::vector> ret(filters.size()); + FixedLimitVector subfilters(filters.size()); + for (size_t c = 0; c < filters.size(); c++){ + ImageRGB32& out = ret[c].first; + out = ImageRGB32(image.width(), image.height()); + subfilters.emplace_back( + out.data(), out.bytes_per_row(), + filters[c].mins, filters[c].maxs, (uint32_t)filters[c].in_range_black + ); + } + Kernels::to_blackwhite_rgb32_range( + image.data(), image.bytes_per_row(), image.width(), image.height(), + subfilters.data(), subfilters.size() + ); + for (size_t c = 0; c < filters.size(); c++){ + ret[c].second = subfilters[c].pixels_in_range; + } + return ret; +} + + + + + + + + + +ImageRGB32 filter_rgb32_euclidean( + const ImageViewRGB32& image, + uint32_t expected, double max_euclidean_distance, + Color replace_with, bool replace_color_within_range +){ + ImageRGB32 ret(image.width(), image.height()); + Kernels::filter_rgb32_euclidean( + image.data(), image.bytes_per_row(), image.width(), image.height(), + ret.data(), ret.bytes_per_row(), + (uint32_t)replace_with, replace_color_within_range, + expected, max_euclidean_distance + ); + return ret; +} +ImageRGB32 filter_rgb32_euclidean( + size_t& pixels_in_range, + const ImageViewRGB32& image, + uint32_t expected, double max_euclidean_distance, + Color replace_with, bool replace_color_within_range +){ + ImageRGB32 ret(image.width(), image.height()); + pixels_in_range = Kernels::filter_rgb32_euclidean( + image.data(), image.bytes_per_row(), image.width(), image.height(), + ret.data(), ret.bytes_per_row(), + (uint32_t)replace_with, replace_color_within_range, + expected, max_euclidean_distance + ); + return ret; +} + + + + + + + + + +ImageRGB32 filter_rgb32_brightness( + const ImageViewRGB32& image, + Color replacement_color, bool replace_color_within_range, + Kernels::Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +){ + ImageRGB32 ret(image.width(), image.height()); + Kernels::filter_rgb32_brightness( + image.data(), image.bytes_per_row(), image.width(), image.height(), + ret.data(), ret.bytes_per_row(), + (uint32_t)replacement_color, replace_color_within_range, + weights, + min_brightness, max_brightness + ); + return ret; +} +ImageRGB32 to_blackwhite_rgb32_brightness( + const ImageViewRGB32& image, + bool in_range_black, + Kernels::Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +){ + ImageRGB32 ret(image.width(), image.height()); + Kernels::to_blackwhite_rgb32_brightness( + image.data(), image.bytes_per_row(), image.width(), image.height(), + ret.data(), ret.bytes_per_row(), + in_range_black, + weights, + min_brightness, max_brightness + ); + return ret; +} + + + +ImageRGB32 filter_green( + const ImageViewRGB32& image, + Color replace_with, + uint8_t rgb_gap +){ + ImageRGB32 ret(image.width(), image.height()); + Kernels::filter_green( + image.data(), image.bytes_per_row(), image.width(), image.height(), + ret.data(), ret.bytes_per_row(), (uint32_t)replace_with, rgb_gap + ); + return ret; +} + + + +} diff --git a/SerialPrograms/Source/CommonTools/Images/ImageFilter.h b/SerialPrograms/Source/CommonTools/Images/ImageFilter.h index 149dbebe9c..5536dbac72 100644 --- a/SerialPrograms/Source/CommonTools/Images/ImageFilter.h +++ b/SerialPrograms/Source/CommonTools/Images/ImageFilter.h @@ -1,166 +1,166 @@ -/* Image Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_ImageFilter_H -#define PokemonAutomation_CommonTools_ImageFilter_H - -#include -#include -#include "Common/Cpp/Color.h" -#include "Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.h" - -namespace PokemonAutomation{ - -class ImageViewRGB32; -class ImageRGB32; - - -// If `replace_color_within_range` is true, replace the color range [mins, maxs] with the color `replacement_color`. -// If `replace_color_within_range` is false, replace the color outside of the range [mins, maxs] with the color -// `replacement_color`. -ImageRGB32 filter_rgb32_range( - const ImageViewRGB32& image, - uint32_t mins, uint32_t maxs, - Color replacement_color, bool replace_color_within_range -); -// If `replace_color_within_range` is true, replace the color range [mins, maxs] with the color `replacement_color`. -// If `replace_color_within_range` is false, replace the color outside of the range [mins, maxs] with the color -// `replacement_color`. -// Returns the # of pixels inside the range [mins, maxs] as `pixels_in_range` -ImageRGB32 filter_rgb32_range( - size_t& pixels_in_range, - const ImageViewRGB32& image, - uint32_t mins, uint32_t maxs, - Color replacement_color, bool replace_color_within_range -); -// Run multiple filters at once. This is more memory efficient than making -// multiple calls to one filter at a time. -// For each filter: -// If `replace_color_within_range` is true, replace the color range [mins, maxs] with the color `replacement_color`. -// If `replace_color_within_range` is false, replace the color outside of the range [mins, maxs] with the color -// `replacement_color`. -// For each filter, return the filtered image and the # of pixels inside the [mins, maxs] range of the filter. -struct FilterRgb32Range{ - Color replacement_color; - bool replace_color_within_range; - uint32_t mins; - uint32_t maxs; -}; -std::vector> filter_rgb32_range( - const ImageViewRGB32& image, - const std::vector& filters -); - - - -// Convert the image to black and white. -// Inside [mins, maxs] is white, otherwise it's black. -// Set "in_range_black" to true to invert the colors. -// Both white and black colors have alpha=255. -ImageRGB32 to_blackwhite_rgb32_range( - const ImageViewRGB32& image, - bool in_range_black, - uint32_t mins, uint32_t maxs -); -// Convert the image to black and white. -// Inside [mins, maxs] is white, otherwise it's black. -// Set "in_range_black" to true to invert the colors. -// Both white and black colors have alpha=255. -// Returns the # of pixels inside the distance as `pixels_in_range`. -ImageRGB32 to_blackwhite_rgb32_range( - size_t& pixels_in_range, - const ImageViewRGB32& image, - bool in_range_black, - uint32_t mins, uint32_t maxs -); -// Run multiple filters at once. This is more memory efficient than making -// multiple calls to one filter at a time. -// For each filter: -// If `in_range_black` is true, replace the color range [mins, maxs] with color black while the rest white. -// If `in_range_black` is false, replace the color range [mins, maxs] with color white while the rest black. -// Both white and black colors have alpha=255. -// For each filter, return the filtered image and the # of pixels inside the [mins, maxs] range of the filter. -struct BlackWhiteRgb32Range{ - bool in_range_black; - uint32_t mins; - uint32_t maxs; -}; -std::vector> to_blackwhite_rgb32_range( - const ImageViewRGB32& image, - const std::vector& filters -); - - - - - - - - - -// If `replace_color_within_range` is true, replace the colors within (<=) `max_euclidean_distance` of the -// `expected_color` with `replacement_color`. -// If `replace_color_within_range` is false, replace the color outside of the distance with the color `replacement_color`. -ImageRGB32 filter_rgb32_euclidean( - const ImageViewRGB32& image, - uint32_t expected_color, double max_euclidean_distance, - Color replacement_color, bool replace_color_within_range -); -// If `replace_color_within_range` is true, replace the colors within (<=) `max_euclidean_distance` of the -// `expected_color` with `replacement_color`. -// If `replace_color_within_range` is false, replace the color outside of the distance with the color `replacement_color`. -// Returns the # of pixels inside the distance as `pixels_in_range`. -// Note: the alpha channel of `image` and `expected_color` are ignored during computation. -ImageRGB32 filter_rgb32_euclidean( - size_t& pixels_in_range, - const ImageViewRGB32& image, - uint32_t expected_color, double max_euclidean_distance, - Color replacement_color, bool replace_color_within_range -); - - - - - - - - -// Similar to "filter_rgb32_range()". But instead of checking if each of -// the RGB components are within a range, we check if the dot product of the -// components and a set of weights is within a range. By selecting the weights, -// you can pick which components to check the brightness of. -ImageRGB32 filter_rgb32_brightness( - const ImageViewRGB32& image, - Color replacement_color, bool replace_color_within_range, - Kernels::Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -); -// Similar to "to_blackwhite_rgb32_range()". But instead of checking if each of -// the RGB components are within a range, we check if the dot product of the -// components and a set of weights is within a range. By selecting the weights, -// you can pick which components to check the brightness of. -ImageRGB32 to_blackwhite_rgb32_brightness( - const ImageViewRGB32& image, - bool in_range_black, - Kernels::Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -); - - - - -// keep all pixels where green is the dominant RGB value. otherwise, replace the pixel with `replace_with` -// `rgb_gap` is the amount that green has to exceed the red or blue value, in order to keep the pixel. -ImageRGB32 filter_green( - const ImageViewRGB32& image, - Color replace_with, - uint8_t rgb_gap = 0 -); - - - -} -#endif +/* Image Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_ImageFilter_H +#define PokemonAutomation_CommonTools_ImageFilter_H + +#include +#include +#include "Common/Cpp/Color.h" +#include "Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.h" + +namespace PokemonAutomation{ + +class ImageViewRGB32; +class ImageRGB32; + + +// If `replace_color_within_range` is true, replace the color range [mins, maxs] with the color `replacement_color`. +// If `replace_color_within_range` is false, replace the color outside of the range [mins, maxs] with the color +// `replacement_color`. +ImageRGB32 filter_rgb32_range( + const ImageViewRGB32& image, + uint32_t mins, uint32_t maxs, + Color replacement_color, bool replace_color_within_range +); +// If `replace_color_within_range` is true, replace the color range [mins, maxs] with the color `replacement_color`. +// If `replace_color_within_range` is false, replace the color outside of the range [mins, maxs] with the color +// `replacement_color`. +// Returns the # of pixels inside the range [mins, maxs] as `pixels_in_range` +ImageRGB32 filter_rgb32_range( + size_t& pixels_in_range, + const ImageViewRGB32& image, + uint32_t mins, uint32_t maxs, + Color replacement_color, bool replace_color_within_range +); +// Run multiple filters at once. This is more memory efficient than making +// multiple calls to one filter at a time. +// For each filter: +// If `replace_color_within_range` is true, replace the color range [mins, maxs] with the color `replacement_color`. +// If `replace_color_within_range` is false, replace the color outside of the range [mins, maxs] with the color +// `replacement_color`. +// For each filter, return the filtered image and the # of pixels inside the [mins, maxs] range of the filter. +struct FilterRgb32Range{ + Color replacement_color; + bool replace_color_within_range; + uint32_t mins; + uint32_t maxs; +}; +std::vector> filter_rgb32_range( + const ImageViewRGB32& image, + const std::vector& filters +); + + + +// Convert the image to black and white. +// Inside [mins, maxs] is white, otherwise it's black. +// Set "in_range_black" to true to invert the colors. +// Both white and black colors have alpha=255. +ImageRGB32 to_blackwhite_rgb32_range( + const ImageViewRGB32& image, + bool in_range_black, + uint32_t mins, uint32_t maxs +); +// Convert the image to black and white. +// Inside [mins, maxs] is white, otherwise it's black. +// Set "in_range_black" to true to invert the colors. +// Both white and black colors have alpha=255. +// Returns the # of pixels inside the distance as `pixels_in_range`. +ImageRGB32 to_blackwhite_rgb32_range( + size_t& pixels_in_range, + const ImageViewRGB32& image, + bool in_range_black, + uint32_t mins, uint32_t maxs +); +// Run multiple filters at once. This is more memory efficient than making +// multiple calls to one filter at a time. +// For each filter: +// If `in_range_black` is true, replace the color range [mins, maxs] with color black while the rest white. +// If `in_range_black` is false, replace the color range [mins, maxs] with color white while the rest black. +// Both white and black colors have alpha=255. +// For each filter, return the filtered image and the # of pixels inside the [mins, maxs] range of the filter. +struct BlackWhiteRgb32Range{ + bool in_range_black; + uint32_t mins; + uint32_t maxs; +}; +std::vector> to_blackwhite_rgb32_range( + const ImageViewRGB32& image, + const std::vector& filters +); + + + + + + + + + +// If `replace_color_within_range` is true, replace the colors within (<=) `max_euclidean_distance` of the +// `expected_color` with `replacement_color`. +// If `replace_color_within_range` is false, replace the color outside of the distance with the color `replacement_color`. +ImageRGB32 filter_rgb32_euclidean( + const ImageViewRGB32& image, + uint32_t expected_color, double max_euclidean_distance, + Color replacement_color, bool replace_color_within_range +); +// If `replace_color_within_range` is true, replace the colors within (<=) `max_euclidean_distance` of the +// `expected_color` with `replacement_color`. +// If `replace_color_within_range` is false, replace the color outside of the distance with the color `replacement_color`. +// Returns the # of pixels inside the distance as `pixels_in_range`. +// Note: the alpha channel of `image` and `expected_color` are ignored during computation. +ImageRGB32 filter_rgb32_euclidean( + size_t& pixels_in_range, + const ImageViewRGB32& image, + uint32_t expected_color, double max_euclidean_distance, + Color replacement_color, bool replace_color_within_range +); + + + + + + + + +// Similar to "filter_rgb32_range()". But instead of checking if each of +// the RGB components are within a range, we check if the dot product of the +// components and a set of weights is within a range. By selecting the weights, +// you can pick which components to check the brightness of. +ImageRGB32 filter_rgb32_brightness( + const ImageViewRGB32& image, + Color replacement_color, bool replace_color_within_range, + Kernels::Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +); +// Similar to "to_blackwhite_rgb32_range()". But instead of checking if each of +// the RGB components are within a range, we check if the dot product of the +// components and a set of weights is within a range. By selecting the weights, +// you can pick which components to check the brightness of. +ImageRGB32 to_blackwhite_rgb32_brightness( + const ImageViewRGB32& image, + bool in_range_black, + Kernels::Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +); + + + + +// keep all pixels where green is the dominant RGB value. otherwise, replace the pixel with `replace_with` +// `rgb_gap` is the amount that green has to exceed the red or blue value, in order to keep the pixel. +ImageRGB32 filter_green( + const ImageViewRGB32& image, + Color replace_with, + uint8_t rgb_gap = 0 +); + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Images/ImageGradient.cpp b/SerialPrograms/Source/CommonTools/Images/ImageGradient.cpp index b8d3be835b..84d3685ba2 100644 --- a/SerialPrograms/Source/CommonTools/Images/ImageGradient.cpp +++ b/SerialPrograms/Source/CommonTools/Images/ImageGradient.cpp @@ -1,160 +1,160 @@ -/* Image Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "ImageGradient.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - -size_t count_horizontal_translucent_border_pixels(const ImageViewRGB32& image, const Color& threshold, bool dark_top){ - // Gradient on each color channel at each pixel in one row - std::vector gradients(image.width() * 3, 0); - // Whether a color channel is zero for each pixel in one row - std::vector is_zero(image.width() * 3, false); - - if (image.height() == 0 || image.width() == 0){ - return 0; - } - - size_t num_rows = image.height() - 1; - for(size_t row_index = 0; row_index < num_rows; row_index++){ - for(size_t x = 0; x < image.width(); x++){ - uint32_t p_above = image.pixel(x, row_index); - uint32_t p_below = image.pixel(x, row_index+1); - - // If both two pixels are black, then we skip this case - if (p_above == 0 && p_below == 0){ - continue; - } - - // c1 may be darker, while c2 is not yet covered by the dark translucent region - Color c1(dark_top ? p_above : p_below); - Color c2(dark_top ? p_below : p_above); - if (c1.red() == 0){ - is_zero[3*x] = true; - } - if (c1.green() == 0){ - is_zero[3*x+1] = true; - } - if (c1.blue() == 0){ - is_zero[3*x+2] = true; - } - gradients[3*x] = std::max(gradients[3*x], int16_t((int)c2.red() - (int) c1.red())); - gradients[3*x+1] = std::max(gradients[3*x+1], int16_t((int)c2.green() - (int) c1.green())); - gradients[3*x+2] = std::max(gradients[3*x+2], int16_t((int)c2.blue() - (int) c1.blue())); - - - } - } - - int16_t thres_c[3] = {threshold.red(), threshold.green(), threshold.blue()}; - - size_t num_border_pixels = 0; - for(size_t x = 0; x < image.width(); x++){ - bool has_non_border_channel = false; - for(int c = 0; c < 3; c++){ - if (is_zero[3*x+c] == false && gradients[3*x+c] < thres_c[c]){ - has_non_border_channel = true; - break; - } - } - - num_border_pixels += !has_non_border_channel; - } - - // int16_t min_color[3] = {255, 255, 255}; - // for(size_t i = 0; i < image.width(); i++){ - // if (is_zero[3*i] == false || is_zero[3*i+1] == false || is_zero[3*i+2] == false){ - // cout << i << ": (" << gradients[3*i] << (is_zero[3*i] ? "*" : ""); - // cout << ", " << gradients[3*i+1] << (is_zero[3*i+1] ? "*" : ""); - // cout << ", " << gradients[3*i+2] << (is_zero[3*i+2] ? "*" : "") << ")\n"; - // for(int j = 0; j < 3; j++){ - // if (is_zero[3*i+j] == false){ - // min_color[j] = std::min(min_color[j], gradients[3*i + j]); - // } - // } - // } - // } - // cout << "min non-0 color " << min_color[0] << " " << min_color[1] << " " << min_color[2] << endl; - // cout << "num border pixels proportion: " << num_border_pixels / (float)image.width() << endl; - - return num_border_pixels; -} - - -size_t count_vertical_translucent_border_pixels(const ImageViewRGB32& image, const Color& threshold, bool dark_left){ - if (image.height() == 0 || image.width() == 0){ - return 0; - } - - size_t num_border_pixels = 0; - int16_t thres_c[3] = {threshold.red(), threshold.green(), threshold.blue()}; - - size_t num_cols = image.width() - 1; - // Go through each row in the image - for(size_t y = 0; y < image.height(); y++){ - // Record the border gradient of this row: - bool is_zero[3] = {false}; - int16_t gradients[3] = {0}; - for(size_t col_index = 0; col_index < num_cols; col_index++){ - uint32_t p_left = image.pixel(col_index, y); - uint32_t p_right = image.pixel(col_index+1, y); - - // If both two pixels are black, then we skip this case - if (p_left == 0 && p_right == 0){ - continue; - } - - // c1 may be darker, while c2 is not yet covered by the dark translucent region - Color c1(dark_left ? p_left : p_right); - Color c2(dark_left ? p_right : p_left); - - if (c1.red() == 0){ - is_zero[0] = true; - } - if (c1.green() == 0){ - is_zero[1] = true; - } - if (c1.blue() == 0){ - is_zero[2] = true; - } - - gradients[0] = std::max(gradients[0], int16_t((int)c2.red() - (int) c1.red())); - gradients[1] = std::max(gradients[1], int16_t((int)c2.green() - (int) c1.green())); - gradients[2] = std::max(gradients[2], int16_t((int)c2.blue() - (int) c1.blue())); - } - - bool has_non_border_channel = false; - for(int c = 0; c < 3; c++){ - if (is_zero[c] == false && gradients[c] < thres_c[c]){ - has_non_border_channel = true; - break; - } - } - num_border_pixels += !has_non_border_channel; - - // cout << y << ": (" << gradients[0] << (is_zero[0] ? "*" : ""); - // cout << ", " << gradients[1] << (is_zero[1] ? "*" : ""); - // cout << ", " << gradients[2] << (is_zero[2] ? "*" : "") << ")\n"; - // cout << "has_non_border_channel " << has_non_border_channel << endl; - } - - // cout << "num border pixels proportion: " << num_border_pixels / (float)image.height() << endl; - - return num_border_pixels; -} - - - - - -} +/* Image Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "ImageGradient.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + +size_t count_horizontal_translucent_border_pixels(const ImageViewRGB32& image, const Color& threshold, bool dark_top){ + // Gradient on each color channel at each pixel in one row + std::vector gradients(image.width() * 3, 0); + // Whether a color channel is zero for each pixel in one row + std::vector is_zero(image.width() * 3, false); + + if (image.height() == 0 || image.width() == 0){ + return 0; + } + + size_t num_rows = image.height() - 1; + for(size_t row_index = 0; row_index < num_rows; row_index++){ + for(size_t x = 0; x < image.width(); x++){ + uint32_t p_above = image.pixel(x, row_index); + uint32_t p_below = image.pixel(x, row_index+1); + + // If both two pixels are black, then we skip this case + if (p_above == 0 && p_below == 0){ + continue; + } + + // c1 may be darker, while c2 is not yet covered by the dark translucent region + Color c1(dark_top ? p_above : p_below); + Color c2(dark_top ? p_below : p_above); + if (c1.red() == 0){ + is_zero[3*x] = true; + } + if (c1.green() == 0){ + is_zero[3*x+1] = true; + } + if (c1.blue() == 0){ + is_zero[3*x+2] = true; + } + gradients[3*x] = std::max(gradients[3*x], int16_t((int)c2.red() - (int) c1.red())); + gradients[3*x+1] = std::max(gradients[3*x+1], int16_t((int)c2.green() - (int) c1.green())); + gradients[3*x+2] = std::max(gradients[3*x+2], int16_t((int)c2.blue() - (int) c1.blue())); + + + } + } + + int16_t thres_c[3] = {threshold.red(), threshold.green(), threshold.blue()}; + + size_t num_border_pixels = 0; + for(size_t x = 0; x < image.width(); x++){ + bool has_non_border_channel = false; + for(int c = 0; c < 3; c++){ + if (is_zero[3*x+c] == false && gradients[3*x+c] < thres_c[c]){ + has_non_border_channel = true; + break; + } + } + + num_border_pixels += !has_non_border_channel; + } + + // int16_t min_color[3] = {255, 255, 255}; + // for(size_t i = 0; i < image.width(); i++){ + // if (is_zero[3*i] == false || is_zero[3*i+1] == false || is_zero[3*i+2] == false){ + // cout << i << ": (" << gradients[3*i] << (is_zero[3*i] ? "*" : ""); + // cout << ", " << gradients[3*i+1] << (is_zero[3*i+1] ? "*" : ""); + // cout << ", " << gradients[3*i+2] << (is_zero[3*i+2] ? "*" : "") << ")\n"; + // for(int j = 0; j < 3; j++){ + // if (is_zero[3*i+j] == false){ + // min_color[j] = std::min(min_color[j], gradients[3*i + j]); + // } + // } + // } + // } + // cout << "min non-0 color " << min_color[0] << " " << min_color[1] << " " << min_color[2] << endl; + // cout << "num border pixels proportion: " << num_border_pixels / (float)image.width() << endl; + + return num_border_pixels; +} + + +size_t count_vertical_translucent_border_pixels(const ImageViewRGB32& image, const Color& threshold, bool dark_left){ + if (image.height() == 0 || image.width() == 0){ + return 0; + } + + size_t num_border_pixels = 0; + int16_t thres_c[3] = {threshold.red(), threshold.green(), threshold.blue()}; + + size_t num_cols = image.width() - 1; + // Go through each row in the image + for(size_t y = 0; y < image.height(); y++){ + // Record the border gradient of this row: + bool is_zero[3] = {false}; + int16_t gradients[3] = {0}; + for(size_t col_index = 0; col_index < num_cols; col_index++){ + uint32_t p_left = image.pixel(col_index, y); + uint32_t p_right = image.pixel(col_index+1, y); + + // If both two pixels are black, then we skip this case + if (p_left == 0 && p_right == 0){ + continue; + } + + // c1 may be darker, while c2 is not yet covered by the dark translucent region + Color c1(dark_left ? p_left : p_right); + Color c2(dark_left ? p_right : p_left); + + if (c1.red() == 0){ + is_zero[0] = true; + } + if (c1.green() == 0){ + is_zero[1] = true; + } + if (c1.blue() == 0){ + is_zero[2] = true; + } + + gradients[0] = std::max(gradients[0], int16_t((int)c2.red() - (int) c1.red())); + gradients[1] = std::max(gradients[1], int16_t((int)c2.green() - (int) c1.green())); + gradients[2] = std::max(gradients[2], int16_t((int)c2.blue() - (int) c1.blue())); + } + + bool has_non_border_channel = false; + for(int c = 0; c < 3; c++){ + if (is_zero[c] == false && gradients[c] < thres_c[c]){ + has_non_border_channel = true; + break; + } + } + num_border_pixels += !has_non_border_channel; + + // cout << y << ": (" << gradients[0] << (is_zero[0] ? "*" : ""); + // cout << ", " << gradients[1] << (is_zero[1] ? "*" : ""); + // cout << ", " << gradients[2] << (is_zero[2] ? "*" : "") << ")\n"; + // cout << "has_non_border_channel " << has_non_border_channel << endl; + } + + // cout << "num border pixels proportion: " << num_border_pixels / (float)image.height() << endl; + + return num_border_pixels; +} + + + + + +} diff --git a/SerialPrograms/Source/CommonTools/Images/ImageGradient.h b/SerialPrograms/Source/CommonTools/Images/ImageGradient.h index 1bb639f420..fd9981e96f 100644 --- a/SerialPrograms/Source/CommonTools/Images/ImageGradient.h +++ b/SerialPrograms/Source/CommonTools/Images/ImageGradient.h @@ -1,41 +1,41 @@ -/* Image Gradient - * - * From: https://github.com/PokemonAutomation/ - * - * Header for various image gradient related functions, mostly for visual inferences - */ - -#ifndef PokemonAutomation_CommonTools_ImageGradient_H -#define PokemonAutomation_CommonTools_ImageGradient_H - -#include -#include -#include "Common/Cpp/Color.h" - -namespace PokemonAutomation{ - -class ImageViewRGB32; -class ImageRGB32; - -// Used to detect a horizontal border line across an image. -// The border is defined as: -// If `dark_top` is true, the upper side of the border line is darker than the lower side. -// If `dark_top` is false, the lower side of the border line is darker than the upper side. -// It returns how many pixels on the border that are darker by the other side by at least `threshold` -// If it returns the same number as `image.width()`, then there is a clear horizontal border across the image. -// -// The image is supposed to have a very small height, as it only holds a horizontal border line. -size_t count_horizontal_translucent_border_pixels(const ImageViewRGB32& image, const Color& threshold, bool dark_top); - -// Used to detect a vertical border line across an image. -// The border is defined as: -// If `dark_left` is true, the left side of the border line is darker than the right side. -// If `dark_left` is false, the right side of the border line is darker than the left side. -// It returns how many pixels on the border that are darker by the other side by at least `threshold` -// If it returns the same number as `image.height()`, then there is a clear vertical border across the image. -// -// The image is supposed to have a very small width, as it only holds a vertical border line. -size_t count_vertical_translucent_border_pixels(const ImageViewRGB32& image, const Color& threshold, bool dark_left); - -} -#endif +/* Image Gradient + * + * From: https://github.com/PokemonAutomation/ + * + * Header for various image gradient related functions, mostly for visual inferences + */ + +#ifndef PokemonAutomation_CommonTools_ImageGradient_H +#define PokemonAutomation_CommonTools_ImageGradient_H + +#include +#include +#include "Common/Cpp/Color.h" + +namespace PokemonAutomation{ + +class ImageViewRGB32; +class ImageRGB32; + +// Used to detect a horizontal border line across an image. +// The border is defined as: +// If `dark_top` is true, the upper side of the border line is darker than the lower side. +// If `dark_top` is false, the lower side of the border line is darker than the upper side. +// It returns how many pixels on the border that are darker by the other side by at least `threshold` +// If it returns the same number as `image.width()`, then there is a clear horizontal border across the image. +// +// The image is supposed to have a very small height, as it only holds a horizontal border line. +size_t count_horizontal_translucent_border_pixels(const ImageViewRGB32& image, const Color& threshold, bool dark_top); + +// Used to detect a vertical border line across an image. +// The border is defined as: +// If `dark_left` is true, the left side of the border line is darker than the right side. +// If `dark_left` is false, the right side of the border line is darker than the left side. +// It returns how many pixels on the border that are darker by the other side by at least `threshold` +// If it returns the same number as `image.height()`, then there is a clear vertical border across the image. +// +// The image is supposed to have a very small width, as it only holds a vertical border line. +size_t count_vertical_translucent_border_pixels(const ImageViewRGB32& image, const Color& threshold, bool dark_left); + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Images/ImageManip.cpp b/SerialPrograms/Source/CommonTools/Images/ImageManip.cpp index 8b1beb6355..1fdd51b8c2 100644 --- a/SerialPrograms/Source/CommonTools/Images/ImageManip.cpp +++ b/SerialPrograms/Source/CommonTools/Images/ImageManip.cpp @@ -1,28 +1,28 @@ -/* Image Manipulation - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "ImageManip.h" - -namespace PokemonAutomation{ - - -ImageRGB32 pad_image(const ImageViewRGB32& image, size_t pixels_on_each_side, uint32_t pixel){ - size_t width = image.width(); - size_t height = image.height(); - ImageRGB32 ret(image.width() + 2*pixels_on_each_side, image.height() + 2*pixels_on_each_side); - ret.fill(pixel); - for (size_t r = 0; r < height; r++){ - size_t out_row = r + pixels_on_each_side; - uint32_t* out = (uint32_t*)((char*)ret.data() + ret.bytes_per_row() * out_row) + pixels_on_each_side; - const uint32_t* in = (const uint32_t*)((char*)image.data() + image.bytes_per_row() * r); - memcpy(out, in, width * sizeof(uint32_t)); - } - return ret; -} - - -} +/* Image Manipulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "ImageManip.h" + +namespace PokemonAutomation{ + + +ImageRGB32 pad_image(const ImageViewRGB32& image, size_t pixels_on_each_side, uint32_t pixel){ + size_t width = image.width(); + size_t height = image.height(); + ImageRGB32 ret(image.width() + 2*pixels_on_each_side, image.height() + 2*pixels_on_each_side); + ret.fill(pixel); + for (size_t r = 0; r < height; r++){ + size_t out_row = r + pixels_on_each_side; + uint32_t* out = (uint32_t*)((char*)ret.data() + ret.bytes_per_row() * out_row) + pixels_on_each_side; + const uint32_t* in = (const uint32_t*)((char*)image.data() + image.bytes_per_row() * r); + memcpy(out, in, width * sizeof(uint32_t)); + } + return ret; +} + + +} diff --git a/SerialPrograms/Source/CommonTools/Images/ImageManip.h b/SerialPrograms/Source/CommonTools/Images/ImageManip.h index d4bd836118..2d7894f820 100644 --- a/SerialPrograms/Source/CommonTools/Images/ImageManip.h +++ b/SerialPrograms/Source/CommonTools/Images/ImageManip.h @@ -1,19 +1,19 @@ -/* Image Manipulation - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_ImageManip_H -#define PokemonAutomation_CommonTools_ImageManip_H - -#include "CommonFramework/ImageTypes/ImageRGB32.h" - -namespace PokemonAutomation{ - - -ImageRGB32 pad_image(const ImageViewRGB32& image, size_t pixels_on_each_side, uint32_t pixel); - - -} -#endif +/* Image Manipulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_ImageManip_H +#define PokemonAutomation_CommonTools_ImageManip_H + +#include "CommonFramework/ImageTypes/ImageRGB32.h" + +namespace PokemonAutomation{ + + +ImageRGB32 pad_image(const ImageViewRGB32& image, size_t pixels_on_each_side, uint32_t pixel); + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Images/ImageTools.cpp b/SerialPrograms/Source/CommonTools/Images/ImageTools.cpp index 7cd5a755e2..bcea4fb53d 100644 --- a/SerialPrograms/Source/CommonTools/Images/ImageTools.cpp +++ b/SerialPrograms/Source/CommonTools/Images/ImageTools.cpp @@ -1,60 +1,60 @@ -/* Image Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/FloatPixel.h" -#include "ImageTools.h" - -namespace PokemonAutomation{ - - - -ImageRGB32 image_diff_greyscale(const ImageViewRGB32& x, const ImageViewRGB32& y){ - if (!x || !y){ - return ImageRGB32(); - } - if (x.width() != y.width()){ - return ImageRGB32(); - } - if (x.height() != y.height()){ - return ImageRGB32(); - } - - ImageRGB32 image(x.width(), x.height()); - size_t width = x.width(); - size_t height = x.height(); - for (size_t r = 0; r < height; r++){ - for (size_t c = 0; c < width; c++){ - Color px(x.pixel(c, r)); - Color py(y.pixel(c, r)); - if (px.alpha() == 0 || py.alpha() == 0){ - image.pixel(c, r) = 0xff000000; - }else{ - double distance = euclidean_distance(px, py); - distance *= 0.57735026918962576451; // 1 / sqrt(3) - uint32_t dist_int = std::min((uint32_t)distance, 255); - image.pixel(c, r) = 0xff000000 + dist_int * 0x010101; - } - } - } - return image; -} - - - - - - - - - - - - -} - +/* Image Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/FloatPixel.h" +#include "ImageTools.h" + +namespace PokemonAutomation{ + + + +ImageRGB32 image_diff_greyscale(const ImageViewRGB32& x, const ImageViewRGB32& y){ + if (!x || !y){ + return ImageRGB32(); + } + if (x.width() != y.width()){ + return ImageRGB32(); + } + if (x.height() != y.height()){ + return ImageRGB32(); + } + + ImageRGB32 image(x.width(), x.height()); + size_t width = x.width(); + size_t height = x.height(); + for (size_t r = 0; r < height; r++){ + for (size_t c = 0; c < width; c++){ + Color px(x.pixel(c, r)); + Color py(y.pixel(c, r)); + if (px.alpha() == 0 || py.alpha() == 0){ + image.pixel(c, r) = 0xff000000; + }else{ + double distance = euclidean_distance(px, py); + distance *= 0.57735026918962576451; // 1 / sqrt(3) + uint32_t dist_int = std::min((uint32_t)distance, 255); + image.pixel(c, r) = 0xff000000 + dist_int * 0x010101; + } + } + } + return image; +} + + + + + + + + + + + + +} + diff --git a/SerialPrograms/Source/CommonTools/Images/ImageTools.h b/SerialPrograms/Source/CommonTools/Images/ImageTools.h index c5c90adb13..00a574fd11 100644 --- a/SerialPrograms/Source/CommonTools/Images/ImageTools.h +++ b/SerialPrograms/Source/CommonTools/Images/ImageTools.h @@ -1,26 +1,26 @@ -/* Image Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_ImageTools_H -#define PokemonAutomation_CommonTools_ImageTools_H - - -namespace PokemonAutomation{ - -class ImageViewRGB32; -class ImageRGB32; - - -// Deprecated -ImageRGB32 image_diff_greyscale(const ImageViewRGB32& x, const ImageViewRGB32& y); - - - - - -} -#endif - +/* Image Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_ImageTools_H +#define PokemonAutomation_CommonTools_ImageTools_H + + +namespace PokemonAutomation{ + +class ImageViewRGB32; +class ImageRGB32; + + +// Deprecated +ImageRGB32 image_diff_greyscale(const ImageViewRGB32& x, const ImageViewRGB32& y); + + + + + +} +#endif + diff --git a/SerialPrograms/Source/CommonTools/Images/SolidColorTest.cpp b/SerialPrograms/Source/CommonTools/Images/SolidColorTest.cpp index 33ee860b9f..b4c4e10235 100644 --- a/SerialPrograms/Source/CommonTools/Images/SolidColorTest.cpp +++ b/SerialPrograms/Source/CommonTools/Images/SolidColorTest.cpp @@ -1,112 +1,112 @@ -/* Solid Color Test - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "SolidColorTest.h" - -#include -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - -bool is_white( - const ImageStats& stats, - double min_rgb_sum, - double max_stddev_sum -){ - if (stats.average.sum() < min_rgb_sum){ - return false; - } - return is_solid(stats, {0.333333, 0.333333, 0.333333}, 0.08, max_stddev_sum); -} -bool is_black( - const ImageStats& stats, - double max_rgb_sum, - double max_stddev_sum -){ - double average = stats.average.sum(); - double stddev = stats.stddev.sum(); - if (PreloadSettings::debug().COLOR_CHECK){ - cout << "is_black(): stats.average " << stats.average.to_string() << "(sum " << average << ") stats.stddev " << stats.stddev.to_string() - << "(sum " << stddev << ") max_rgb_sum " << max_rgb_sum << " max_stddev_sum " << max_stddev_sum << endl; - } -// cout << stats.average << stats.stddev << endl; - return average <= max_rgb_sum && stddev <= max_stddev_sum; -} -bool is_grey( - const ImageStats& stats, - double min_rgb_sum, double max_rgb_sum, - double max_stddev_sum -){ - double average = stats.average.sum(); - if (average < min_rgb_sum || average > max_rgb_sum){ - return false; - } - - double stddev = stats.stddev.sum(); - if (stddev > max_stddev_sum){ -// cout << "bad stddev = " << stddev << endl; - return false; - } - - // If it's too dark, color ratios will be unstable. - if (average < 100){ - return true; - } - - FloatPixel actual = stats.average / average; - double distance = euclidean_distance(actual, {0.333333, 0.333333, 0.333333}); - return distance <= 0.1; -} -bool is_solid( - const ImageStats& stats, - const FloatPixel& expected_color_ratio, - double max_euclidean_distance, - double max_stddev_sum -){ - double stddev = stats.stddev.sum(); - if (stddev > max_stddev_sum){ -// cout << "bad stddev = " << stddev << endl; - return false; - } - - double average = stats.average.sum(); - FloatPixel actual = stats.average / average; - double distance = euclidean_distance(actual, expected_color_ratio); -// cout << "actual color ratio " << actual << endl; -// cout << "distance = " << distance << endl; - - return distance <= max_euclidean_distance; -} - -bool ImageSolidCheck::check(const ImageViewRGB32& frame) const{ - ImageStats stats = image_stats(extract_box_reference(frame, box)); - return is_solid(stats, expected_color_ratio, max_euclidean_distance, max_stddev_sum); -} - -std::string ImageSolidCheck::debug_string(const ImageViewRGB32& frame) const{ - std::ostringstream oss; - ImageStats stats = image_stats(extract_box_reference(frame, box)); - oss << "Box (" << box.x << ", " << box.y << ", " << box.width << ", " << box.height << ") "; - - double average = stats.average.sum(); - FloatPixel actual_ratio = stats.average / average; - oss << "expected color ratio: " << expected_color_ratio.to_string() << " "; - oss << "actual color ratio: " << actual_ratio.to_string() << " "; - oss << "dist: " << euclidean_distance(actual_ratio, expected_color_ratio) << " "; - - double actual_stddev = stats.stddev.sum(); - oss << "max stddev sum: " << max_stddev_sum << " actual stddev sum: " << actual_stddev; - - return oss.str(); -} - - -} +/* Solid Color Test + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "SolidColorTest.h" + +#include +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + +bool is_white( + const ImageStats& stats, + double min_rgb_sum, + double max_stddev_sum +){ + if (stats.average.sum() < min_rgb_sum){ + return false; + } + return is_solid(stats, {0.333333, 0.333333, 0.333333}, 0.08, max_stddev_sum); +} +bool is_black( + const ImageStats& stats, + double max_rgb_sum, + double max_stddev_sum +){ + double average = stats.average.sum(); + double stddev = stats.stddev.sum(); + if (PreloadSettings::debug().COLOR_CHECK){ + cout << "is_black(): stats.average " << stats.average.to_string() << "(sum " << average << ") stats.stddev " << stats.stddev.to_string() + << "(sum " << stddev << ") max_rgb_sum " << max_rgb_sum << " max_stddev_sum " << max_stddev_sum << endl; + } +// cout << stats.average << stats.stddev << endl; + return average <= max_rgb_sum && stddev <= max_stddev_sum; +} +bool is_grey( + const ImageStats& stats, + double min_rgb_sum, double max_rgb_sum, + double max_stddev_sum +){ + double average = stats.average.sum(); + if (average < min_rgb_sum || average > max_rgb_sum){ + return false; + } + + double stddev = stats.stddev.sum(); + if (stddev > max_stddev_sum){ +// cout << "bad stddev = " << stddev << endl; + return false; + } + + // If it's too dark, color ratios will be unstable. + if (average < 100){ + return true; + } + + FloatPixel actual = stats.average / average; + double distance = euclidean_distance(actual, {0.333333, 0.333333, 0.333333}); + return distance <= 0.1; +} +bool is_solid( + const ImageStats& stats, + const FloatPixel& expected_color_ratio, + double max_euclidean_distance, + double max_stddev_sum +){ + double stddev = stats.stddev.sum(); + if (stddev > max_stddev_sum){ +// cout << "bad stddev = " << stddev << endl; + return false; + } + + double average = stats.average.sum(); + FloatPixel actual = stats.average / average; + double distance = euclidean_distance(actual, expected_color_ratio); +// cout << "actual color ratio " << actual << endl; +// cout << "distance = " << distance << endl; + + return distance <= max_euclidean_distance; +} + +bool ImageSolidCheck::check(const ImageViewRGB32& frame) const{ + ImageStats stats = image_stats(extract_box_reference(frame, box)); + return is_solid(stats, expected_color_ratio, max_euclidean_distance, max_stddev_sum); +} + +std::string ImageSolidCheck::debug_string(const ImageViewRGB32& frame) const{ + std::ostringstream oss; + ImageStats stats = image_stats(extract_box_reference(frame, box)); + oss << "Box (" << box.x << ", " << box.y << ", " << box.width << ", " << box.height << ") "; + + double average = stats.average.sum(); + FloatPixel actual_ratio = stats.average / average; + oss << "expected color ratio: " << expected_color_ratio.to_string() << " "; + oss << "actual color ratio: " << actual_ratio.to_string() << " "; + oss << "dist: " << euclidean_distance(actual_ratio, expected_color_ratio) << " "; + + double actual_stddev = stats.stddev.sum(); + oss << "max stddev sum: " << max_stddev_sum << " actual stddev sum: " << actual_stddev; + + return oss.str(); +} + + +} diff --git a/SerialPrograms/Source/CommonTools/Images/SolidColorTest.h b/SerialPrograms/Source/CommonTools/Images/SolidColorTest.h index 56840617b3..cd8fd76d92 100644 --- a/SerialPrograms/Source/CommonTools/Images/SolidColorTest.h +++ b/SerialPrograms/Source/CommonTools/Images/SolidColorTest.h @@ -1,106 +1,106 @@ -/* Solid Color Test - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_SolidColorTest_H -#define PokemonAutomation_CommonTools_SolidColorTest_H - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" - -namespace PokemonAutomation{ - - -bool is_white( - const ImageStats& stats, - double min_rgb_sum = 500, - double max_stddev_sum = 10 -); -bool is_black( - const ImageStats& stats, - double max_rgb_sum = 100, - double max_stddev_sum = 10 -); -bool is_grey( - const ImageStats& stats, - double min_rgb_sum, double max_rgb_sum, - double max_stddev_sum = 10 -); - -// expected_color_ratio: ratio of color channels to match, -// for a color {r, g, b}: the color ratio is {r/(r+g+b), g/(r+g+b), b/(r+g+b)} -// the sum of the ratios should add up to 1.0. -// e.g. if a color is (127, 127, 254), it's color ratio is (0.25, 0.25, 0.5) -bool is_solid( - const ImageStats& stats, - const FloatPixel& expected_color_ratio, - double max_euclidean_distance = 0.15, - double max_stddev_sum = 10 -); - - -inline bool is_white( - const ImageViewRGB32& image, - double min_rgb_sum = 500, - double max_stddev_sum = 10 -){ - return is_white(image_stats(image), min_rgb_sum, max_stddev_sum); -} -inline bool is_black( - const ImageViewRGB32& image, - double max_rgb_sum = 100, - double max_stddev_sum = 10 -){ - ImageStats stats = image_stats(image); -// cout << stats.average << stats.stddev << endl; - return is_black(stats, max_rgb_sum, max_stddev_sum); -} -inline bool is_grey( - const ImageViewRGB32& image, - double min_rgb_sum, double max_rgb_sum, - double max_stddev_sum = 10 -){ - return is_grey(image_stats(image), min_rgb_sum, max_rgb_sum, max_stddev_sum); -} - -// expected_color_ratio: ratio of color channels to match, e.g. if a color is (127, 127, 254), it's color ratio is (0.25, 0.25, 0.5) -inline bool is_solid( - const ImageViewRGB32& image, - const FloatPixel& expected_color_ratio, - double max_euclidean_distance = 0.15, - double max_stddev_sum = 10 -){ - return is_solid(image_stats(image), expected_color_ratio, max_euclidean_distance, max_stddev_sum); -} - -// A convenience struct to do solid checks on images. -struct ImageSolidCheck{ - ImageFloatBox box; - FloatPixel expected_color_ratio; - double max_euclidean_distance = 0.15; - double max_stddev_sum = 10; - - ImageSolidCheck( - double x, double y, double width, double height, - double r, double g, double b, - double max_distance = 0.15, double max_stddev_sum = 10) - : box(x, y, width, height) - , expected_color_ratio(r, g, b) - , max_euclidean_distance(max_distance) - , max_stddev_sum(max_stddev_sum) {} - - // Check if the area on the image is a solid color. - bool check(const ImageViewRGB32& image) const; - - // Return a debug string on the checks performed on the image. - std::string debug_string(const ImageViewRGB32& image) const; -}; - - - - -} -#endif +/* Solid Color Test + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_SolidColorTest_H +#define PokemonAutomation_CommonTools_SolidColorTest_H + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" + +namespace PokemonAutomation{ + + +bool is_white( + const ImageStats& stats, + double min_rgb_sum = 500, + double max_stddev_sum = 10 +); +bool is_black( + const ImageStats& stats, + double max_rgb_sum = 100, + double max_stddev_sum = 10 +); +bool is_grey( + const ImageStats& stats, + double min_rgb_sum, double max_rgb_sum, + double max_stddev_sum = 10 +); + +// expected_color_ratio: ratio of color channels to match, +// for a color {r, g, b}: the color ratio is {r/(r+g+b), g/(r+g+b), b/(r+g+b)} +// the sum of the ratios should add up to 1.0. +// e.g. if a color is (127, 127, 254), it's color ratio is (0.25, 0.25, 0.5) +bool is_solid( + const ImageStats& stats, + const FloatPixel& expected_color_ratio, + double max_euclidean_distance = 0.15, + double max_stddev_sum = 10 +); + + +inline bool is_white( + const ImageViewRGB32& image, + double min_rgb_sum = 500, + double max_stddev_sum = 10 +){ + return is_white(image_stats(image), min_rgb_sum, max_stddev_sum); +} +inline bool is_black( + const ImageViewRGB32& image, + double max_rgb_sum = 100, + double max_stddev_sum = 10 +){ + ImageStats stats = image_stats(image); +// cout << stats.average << stats.stddev << endl; + return is_black(stats, max_rgb_sum, max_stddev_sum); +} +inline bool is_grey( + const ImageViewRGB32& image, + double min_rgb_sum, double max_rgb_sum, + double max_stddev_sum = 10 +){ + return is_grey(image_stats(image), min_rgb_sum, max_rgb_sum, max_stddev_sum); +} + +// expected_color_ratio: ratio of color channels to match, e.g. if a color is (127, 127, 254), it's color ratio is (0.25, 0.25, 0.5) +inline bool is_solid( + const ImageViewRGB32& image, + const FloatPixel& expected_color_ratio, + double max_euclidean_distance = 0.15, + double max_stddev_sum = 10 +){ + return is_solid(image_stats(image), expected_color_ratio, max_euclidean_distance, max_stddev_sum); +} + +// A convenience struct to do solid checks on images. +struct ImageSolidCheck{ + ImageFloatBox box; + FloatPixel expected_color_ratio; + double max_euclidean_distance = 0.15; + double max_stddev_sum = 10; + + ImageSolidCheck( + double x, double y, double width, double height, + double r, double g, double b, + double max_distance = 0.15, double max_stddev_sum = 10) + : box(x, y, width, height) + , expected_color_ratio(r, g, b) + , max_euclidean_distance(max_distance) + , max_stddev_sum(max_stddev_sum) {} + + // Check if the area on the image is a solid color. + bool check(const ImageViewRGB32& image) const; + + // Return a debug string on the checks performed on the image. + std::string debug_string(const ImageViewRGB32& image) const; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Images/WaterfillUtilities.cpp b/SerialPrograms/Source/CommonTools/Images/WaterfillUtilities.cpp index 430c74e15a..046d171722 100644 --- a/SerialPrograms/Source/CommonTools/Images/WaterfillUtilities.cpp +++ b/SerialPrograms/Source/CommonTools/Images/WaterfillUtilities.cpp @@ -1,188 +1,188 @@ -/* Waterfill Process - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Color.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/Tools/DebugDumper.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "WaterfillUtilities.h" - -#include - - -namespace PokemonAutomation{ - - -std::pair remove_center_pixels( - const Kernels::Waterfill::WaterfillObject& object, - size_t num_pixels_to_remove -){ - PackedBinaryMatrix matrix = object.packed_matrix(); - size_t width = matrix.width(); - size_t height = matrix.height(); -// cout << matrix.dump() << endl; - - // Sort all pixels by distance from center. - size_t center_x = (size_t)(object.center_of_gravity_x() - object.min_x); - size_t center_y = (size_t)(object.center_of_gravity_y() - object.min_y); - std::map distances; - for (size_t r = 0; r < height; r++){ - for (size_t c = 0; c < width; c++){ - if (matrix.get(c, r)){ - size_t dist_x = c - center_x; - size_t dist_y = r - center_y; - uint64_t distance_sqr = (uint64_t)dist_x*dist_x + (uint64_t)dist_y*dist_y; - distances[distance_sqr]++; - } - } - } - - // Filter out pixels close to center - size_t count = 0; - uint64_t distance_sqr_th = 0; - for (auto& item : distances){ - count += item.second; - if (count >= num_pixels_to_remove){ - distance_sqr_th = item.first; - break; - } - } - for (size_t r = 0; r < height; r++){ - for (size_t c = 0; c < width; c++){ - size_t dist_x = c - center_x; - size_t dist_y = r - center_y; - uint64_t distance_sqr = (uint64_t)dist_x*dist_x + (uint64_t)dist_y*dist_y; - if (distance_sqr < distance_sqr_th){ - matrix.set(c, r, false); - } - } - } - - return std::pair(std::move(matrix), distance_sqr_th); -} - -bool match_template_by_waterfill( - const ImageViewRGB32 &image, - const ImageMatch::WaterfillTemplateMatcher &matcher, - const std::vector> &filters, - const std::pair &area_thresholds, - double rmsd_threshold, - std::function check_matched_object) -{ - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - dump_debug_image( - global_logger_command_line(), - "CommonFramework/WaterfillTemplateMatcher", - "match_template_by_waterfill_input_image", - image - ); - std::cout << "Match template by waterfill, " << filters.size() << " filter(s), size range (" - << area_thresholds.first << ", "; - if (area_thresholds.second == SIZE_MAX){ - std::cout << "SIZE_MAX"; - }else{ - std::cout << area_thresholds.second; - } - std::cout << ")" << std::endl; - } - std::vector matrices = compress_rgb32_to_binary_range(image, filters); - - bool detected = false; - bool stop_match = false; - for (size_t i_matrix = 0; i_matrix < matrices.size(); i_matrix++){ - PackedBinaryMatrix& matrix = matrices[i_matrix]; - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - ImageRGB32 binaryImage = image.copy(); - filter_by_mask(matrix, binaryImage, Color(COLOR_BLACK), true); - //filter_by_mask(matrix, binaryImage, Color(COLOR_WHITE), true); - dump_debug_image( - global_logger_command_line(), - "CommonFramework/WaterfillTemplateMatcher", - "match_template_by_waterfill_filtered_image_" + std::to_string(i_matrix), - binaryImage - ); - } - - std::unique_ptr session = Kernels::Waterfill::make_WaterfillSession(); - Kernels::Waterfill::WaterfillObject object; - const size_t min_area = area_thresholds.first; - session->set_source(matrix); - auto finder = session->make_iterator(min_area); - const bool keep_object_matrix = false; - while (finder->find_next(object, keep_object_matrix)){ - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - std::cout << "------------" << std::endl; - std::cout << "Object area: " << object.area << std::endl; - } - - if (object.area > area_thresholds.second){ - continue; - } - double rmsd = matcher.rmsd_original(image, object); - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - std::cout << "Object rmsd: " << rmsd << std::endl; - } - - if (rmsd < rmsd_threshold){ - detected = true; - - if (check_matched_object(object)){ - stop_match = true; - break; - } - } - } - - if (stop_match){ - break; - } - } - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - std::cout << "End match template by waterfill" << std::endl; - } - return detected; -} - - -void draw_matrix_on_image( - const PackedBinaryMatrix& matrix, - uint32_t color, ImageRGB32& image, size_t offset_x, size_t offset_y -){ - for (size_t x = 0; x < matrix.width(); x++){ - for (size_t y = 0; y < matrix.height(); y++){ - if (matrix.get(x, y)){ - image.pixel(offset_x + x, offset_y + y) = (uint32_t)color; - } - } - } -} - - -void draw_object_on_image( - const Kernels::Waterfill::WaterfillObject& obj, - const uint32_t& color, ImageRGB32& image, size_t offset_x, size_t offset_y -){ - for (size_t x = 0; x < obj.width(); x++){ - for (size_t y = 0; y < obj.height(); y++){ - if (obj.object->get(obj.min_x + x, obj.min_y + y)){ - image.pixel(offset_x + obj.min_x + x, offset_y + obj.min_y + y) = color; - // cout << "Set color at " << offset_x + object.min_x + obj.min_x + x << ", " << offset_y + object.min_y + obj.min_y + y << endl; - } - } - } -} - - - - -} +/* Waterfill Process + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Color.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Tools/DebugDumper.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "WaterfillUtilities.h" + +#include + + +namespace PokemonAutomation{ + + +std::pair remove_center_pixels( + const Kernels::Waterfill::WaterfillObject& object, + size_t num_pixels_to_remove +){ + PackedBinaryMatrix matrix = object.packed_matrix(); + size_t width = matrix.width(); + size_t height = matrix.height(); +// cout << matrix.dump() << endl; + + // Sort all pixels by distance from center. + size_t center_x = (size_t)(object.center_of_gravity_x() - object.min_x); + size_t center_y = (size_t)(object.center_of_gravity_y() - object.min_y); + std::map distances; + for (size_t r = 0; r < height; r++){ + for (size_t c = 0; c < width; c++){ + if (matrix.get(c, r)){ + size_t dist_x = c - center_x; + size_t dist_y = r - center_y; + uint64_t distance_sqr = (uint64_t)dist_x*dist_x + (uint64_t)dist_y*dist_y; + distances[distance_sqr]++; + } + } + } + + // Filter out pixels close to center + size_t count = 0; + uint64_t distance_sqr_th = 0; + for (auto& item : distances){ + count += item.second; + if (count >= num_pixels_to_remove){ + distance_sqr_th = item.first; + break; + } + } + for (size_t r = 0; r < height; r++){ + for (size_t c = 0; c < width; c++){ + size_t dist_x = c - center_x; + size_t dist_y = r - center_y; + uint64_t distance_sqr = (uint64_t)dist_x*dist_x + (uint64_t)dist_y*dist_y; + if (distance_sqr < distance_sqr_th){ + matrix.set(c, r, false); + } + } + } + + return std::pair(std::move(matrix), distance_sqr_th); +} + +bool match_template_by_waterfill( + const ImageViewRGB32 &image, + const ImageMatch::WaterfillTemplateMatcher &matcher, + const std::vector> &filters, + const std::pair &area_thresholds, + double rmsd_threshold, + std::function check_matched_object) +{ + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + dump_debug_image( + global_logger_command_line(), + "CommonFramework/WaterfillTemplateMatcher", + "match_template_by_waterfill_input_image", + image + ); + std::cout << "Match template by waterfill, " << filters.size() << " filter(s), size range (" + << area_thresholds.first << ", "; + if (area_thresholds.second == SIZE_MAX){ + std::cout << "SIZE_MAX"; + }else{ + std::cout << area_thresholds.second; + } + std::cout << ")" << std::endl; + } + std::vector matrices = compress_rgb32_to_binary_range(image, filters); + + bool detected = false; + bool stop_match = false; + for (size_t i_matrix = 0; i_matrix < matrices.size(); i_matrix++){ + PackedBinaryMatrix& matrix = matrices[i_matrix]; + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + ImageRGB32 binaryImage = image.copy(); + filter_by_mask(matrix, binaryImage, Color(COLOR_BLACK), true); + //filter_by_mask(matrix, binaryImage, Color(COLOR_WHITE), true); + dump_debug_image( + global_logger_command_line(), + "CommonFramework/WaterfillTemplateMatcher", + "match_template_by_waterfill_filtered_image_" + std::to_string(i_matrix), + binaryImage + ); + } + + std::unique_ptr session = Kernels::Waterfill::make_WaterfillSession(); + Kernels::Waterfill::WaterfillObject object; + const size_t min_area = area_thresholds.first; + session->set_source(matrix); + auto finder = session->make_iterator(min_area); + const bool keep_object_matrix = false; + while (finder->find_next(object, keep_object_matrix)){ + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + std::cout << "------------" << std::endl; + std::cout << "Object area: " << object.area << std::endl; + } + + if (object.area > area_thresholds.second){ + continue; + } + double rmsd = matcher.rmsd_original(image, object); + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + std::cout << "Object rmsd: " << rmsd << std::endl; + } + + if (rmsd < rmsd_threshold){ + detected = true; + + if (check_matched_object(object)){ + stop_match = true; + break; + } + } + } + + if (stop_match){ + break; + } + } + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + std::cout << "End match template by waterfill" << std::endl; + } + return detected; +} + + +void draw_matrix_on_image( + const PackedBinaryMatrix& matrix, + uint32_t color, ImageRGB32& image, size_t offset_x, size_t offset_y +){ + for (size_t x = 0; x < matrix.width(); x++){ + for (size_t y = 0; y < matrix.height(); y++){ + if (matrix.get(x, y)){ + image.pixel(offset_x + x, offset_y + y) = (uint32_t)color; + } + } + } +} + + +void draw_object_on_image( + const Kernels::Waterfill::WaterfillObject& obj, + const uint32_t& color, ImageRGB32& image, size_t offset_x, size_t offset_y +){ + for (size_t x = 0; x < obj.width(); x++){ + for (size_t y = 0; y < obj.height(); y++){ + if (obj.object->get(obj.min_x + x, obj.min_y + y)){ + image.pixel(offset_x + obj.min_x + x, offset_y + obj.min_y + y) = color; + // cout << "Set color at " << offset_x + object.min_x + obj.min_x + x << ", " << offset_y + object.min_y + obj.min_y + y << endl; + } + } + } +} + + + + +} diff --git a/SerialPrograms/Source/CommonTools/Images/WaterfillUtilities.h b/SerialPrograms/Source/CommonTools/Images/WaterfillUtilities.h index dfe53bf4cc..40c05bc048 100644 --- a/SerialPrograms/Source/CommonTools/Images/WaterfillUtilities.h +++ b/SerialPrograms/Source/CommonTools/Images/WaterfillUtilities.h @@ -1,82 +1,82 @@ -/* Waterfill Utilities - * - * From: https://github.com/PokemonAutomation/ - * - * Util functions that process waterfill objects and matrices. - */ - -#ifndef PokemonAutomation_CommonTools_WaterfillUtilities_H -#define PokemonAutomation_CommonTools_WaterfillUtilities_H - -#include -#include -#include "CommonFramework/ImageTypes/BinaryImage.h" - -namespace PokemonAutomation{ - class ImageRGB32; - class ImageViewRGB32; -namespace Kernels{ -namespace Waterfill{ - class WaterfillObject; -} -} - -namespace ImageMatch{ - class WaterfillTemplateMatcher; -} - -// Remove pixels close to center of mass of the water fill object. -// Pixels are removed based on the distance to the center of mass. The code will choose a distance threshold as large as possible -// while the number of the removed pixels is smaller than `num_removed_pixels_threshold`. -// Return a binary matrix representing the remaining pixels and the distance threshold which is defined as the minimum distance of -// the remaining pixels towards the original center of mass. -// Note: `object.object` must be constructed before calling this function. -// Example usage for analyzing the shape of the object: -// auto std::tie(matrix, distance) = remove_center_pixels(object, (size_t)(0.85 * object.area)); -// auto session = make_WaterfillSession(matrix); -// ... -std::pair remove_center_pixels( - const Kernels::Waterfill::WaterfillObject& object, - size_t num_removed_pixels_threshold -); - -// Given an image first run waterfill (aka use a color filter) on it to detect pixels of a color range. Then for each connected -// componet of the detected pixel region (aka waterfill object), we check if the object is close to an image template by -// checking aspect ratio thresholds, area thresholds and RMSD threshold. -// If a template match is found, call the function `check_matched_object()` on it. -// -// image: the image. -// matcher: the template matcher holding the template. It is also responsible for checking aspect ratio thresholds. -// filters: each filter is parameterized by min and max color thresholds for detected pixels. For each filter, the function checks -// the waterfill objects formed by the detected pixels. -// area_thresholds: min, max thresholds for number of pixels of a waterfill object. -// rmsd_threshold: RMSD threshold. If RMSD of the waterfill object and template is smaller than this threshold, consider it a match. -// check_matched_object: if a matcher is found, pass the matched object to this function. If the function returns true, stop the -// entire template matching operation. -bool match_template_by_waterfill( - const ImageViewRGB32 &image, - const ImageMatch::WaterfillTemplateMatcher &matcher, - const std::vector> &filters, - const std::pair &area_thresholds, - double rmsd_threshold, - std::function check_matched_object); - -// Draw matrix on an image. Used for debugging the matrix. -// color: color of the pixels from the matrix to render on the image. -// offset_x, offset_y: the offset of the matrix when rendered on the image. -void draw_matrix_on_image( - const PackedBinaryMatrix& matrix, - uint32_t color, ImageRGB32& image, size_t offset_x, size_t offset_y -); - -// Draw waterfill object on an image. Used for debugging the waterfill object. -// Note: the object must have WaterfillObject.object computed. -// color: color of the pixels from the object to render on the image. -// offset_x, offset_y: the offset of the object when rendered on the image. -void draw_object_on_image( - const Kernels::Waterfill::WaterfillObject& object, - const uint32_t& color, ImageRGB32& image, size_t offset_x, size_t offset_y -); - -} -#endif +/* Waterfill Utilities + * + * From: https://github.com/PokemonAutomation/ + * + * Util functions that process waterfill objects and matrices. + */ + +#ifndef PokemonAutomation_CommonTools_WaterfillUtilities_H +#define PokemonAutomation_CommonTools_WaterfillUtilities_H + +#include +#include +#include "CommonFramework/ImageTypes/BinaryImage.h" + +namespace PokemonAutomation{ + class ImageRGB32; + class ImageViewRGB32; +namespace Kernels{ +namespace Waterfill{ + class WaterfillObject; +} +} + +namespace ImageMatch{ + class WaterfillTemplateMatcher; +} + +// Remove pixels close to center of mass of the water fill object. +// Pixels are removed based on the distance to the center of mass. The code will choose a distance threshold as large as possible +// while the number of the removed pixels is smaller than `num_removed_pixels_threshold`. +// Return a binary matrix representing the remaining pixels and the distance threshold which is defined as the minimum distance of +// the remaining pixels towards the original center of mass. +// Note: `object.object` must be constructed before calling this function. +// Example usage for analyzing the shape of the object: +// auto std::tie(matrix, distance) = remove_center_pixels(object, (size_t)(0.85 * object.area)); +// auto session = make_WaterfillSession(matrix); +// ... +std::pair remove_center_pixels( + const Kernels::Waterfill::WaterfillObject& object, + size_t num_removed_pixels_threshold +); + +// Given an image first run waterfill (aka use a color filter) on it to detect pixels of a color range. Then for each connected +// componet of the detected pixel region (aka waterfill object), we check if the object is close to an image template by +// checking aspect ratio thresholds, area thresholds and RMSD threshold. +// If a template match is found, call the function `check_matched_object()` on it. +// +// image: the image. +// matcher: the template matcher holding the template. It is also responsible for checking aspect ratio thresholds. +// filters: each filter is parameterized by min and max color thresholds for detected pixels. For each filter, the function checks +// the waterfill objects formed by the detected pixels. +// area_thresholds: min, max thresholds for number of pixels of a waterfill object. +// rmsd_threshold: RMSD threshold. If RMSD of the waterfill object and template is smaller than this threshold, consider it a match. +// check_matched_object: if a matcher is found, pass the matched object to this function. If the function returns true, stop the +// entire template matching operation. +bool match_template_by_waterfill( + const ImageViewRGB32 &image, + const ImageMatch::WaterfillTemplateMatcher &matcher, + const std::vector> &filters, + const std::pair &area_thresholds, + double rmsd_threshold, + std::function check_matched_object); + +// Draw matrix on an image. Used for debugging the matrix. +// color: color of the pixels from the matrix to render on the image. +// offset_x, offset_y: the offset of the matrix when rendered on the image. +void draw_matrix_on_image( + const PackedBinaryMatrix& matrix, + uint32_t color, ImageRGB32& image, size_t offset_x, size_t offset_y +); + +// Draw waterfill object on an image. Used for debugging the waterfill object. +// Note: the object must have WaterfillObject.object computed. +// color: color of the pixels from the object to render on the image. +// offset_x, offset_y: the offset of the object when rendered on the image. +void draw_object_on_image( + const Kernels::Waterfill::WaterfillObject& object, + const uint32_t& color, ImageRGB32& image, size_t offset_x, size_t offset_y +); + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/InferenceCallbacks/AudioInferenceCallback.h b/SerialPrograms/Source/CommonTools/InferenceCallbacks/AudioInferenceCallback.h index 6f0ca78b18..281498e4dd 100644 --- a/SerialPrograms/Source/CommonTools/InferenceCallbacks/AudioInferenceCallback.h +++ b/SerialPrograms/Source/CommonTools/InferenceCallbacks/AudioInferenceCallback.h @@ -1,42 +1,42 @@ -/* Audio Inference Callback - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_AudioInferenceCallback_H -#define PokemonAutomation_CommonTools_AudioInferenceCallback_H - -#include -#include -#include "InferenceCallback.h" - -namespace PokemonAutomation{ - -class AudioSpectrum; -class AudioFeed; - -// Base class for an audio inference object to be called perioridically by -// inference routines in InferenceRoutines.h. -class AudioInferenceCallback : public InferenceCallback{ -public: - AudioInferenceCallback(std::string label) - : InferenceCallback(InferenceType::AUDIO, std::move(label)) - {} - - // Process new spectrums and do inferences on them. - // Return true if the inference session should stop. - // Input spectrums are ordered from newest (largest timestamp) to oldest (smallest timestamp) in the vector. - // If needed, access to `audioFeed` to render inference boxes. - virtual bool process_spectrums( - const std::vector& new_spectrums, - AudioFeed& audio_feed - ) = 0; - -}; - - - - -} -#endif +/* Audio Inference Callback + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_AudioInferenceCallback_H +#define PokemonAutomation_CommonTools_AudioInferenceCallback_H + +#include +#include +#include "InferenceCallback.h" + +namespace PokemonAutomation{ + +class AudioSpectrum; +class AudioFeed; + +// Base class for an audio inference object to be called perioridically by +// inference routines in InferenceRoutines.h. +class AudioInferenceCallback : public InferenceCallback{ +public: + AudioInferenceCallback(std::string label) + : InferenceCallback(InferenceType::AUDIO, std::move(label)) + {} + + // Process new spectrums and do inferences on them. + // Return true if the inference session should stop. + // Input spectrums are ordered from newest (largest timestamp) to oldest (smallest timestamp) in the vector. + // If needed, access to `audioFeed` to render inference boxes. + virtual bool process_spectrums( + const std::vector& new_spectrums, + AudioFeed& audio_feed + ) = 0; + +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/InferenceCallbacks/InferenceCallback.h b/SerialPrograms/Source/CommonTools/InferenceCallbacks/InferenceCallback.h index 4afe67f4f5..c13aac4ab0 100644 --- a/SerialPrograms/Source/CommonTools/InferenceCallbacks/InferenceCallback.h +++ b/SerialPrograms/Source/CommonTools/InferenceCallbacks/InferenceCallback.h @@ -1,91 +1,90 @@ -/* Inference Callback - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_InferenceCallback_H -#define PokemonAutomation_CommonTools_InferenceCallback_H - -#include -#include - -namespace PokemonAutomation{ - -enum class InferenceType{ - VISUAL, - AUDIO, -}; - -// Base class for an inference object to be called perioridically by -// inference routines in InferenceRoutines.h. -class InferenceCallback{ - // Disable these to prevent accidental copying/slicing. - InferenceCallback(const InferenceCallback&) = delete; - void operator=(const InferenceCallback&) = delete; - -public: - virtual ~InferenceCallback() = default; - - // Is it a visual or audio inference. - InferenceType type() const{ return m_type; } - // Name of the inference object. - const std::string& label() const{ return m_label; } - - -protected: - InferenceCallback(InferenceType type, std::string label) - : m_type(type) - , m_label(label) - {} - - -private: - InferenceType m_type; - std::string m_label; -}; - - - -// Used by inference routines in InferenceRoutines.h. -// The struct contains an inference callback and its inference period: how -// long should an inference routine wait before calling the callback object -// again. -struct PeriodicInferenceCallback{ - InferenceCallback* callback; - // inference period. 0 value means the inference routine should use the - // default inference period, which is set as a parameter to the inference - // routine. - std::chrono::milliseconds period; - - PeriodicInferenceCallback() - : callback(nullptr) - , period(std::chrono::milliseconds(0)) - {} - PeriodicInferenceCallback( - InferenceCallback& p_callback, - std::chrono::milliseconds p_period = std::chrono::milliseconds(0) - ) - : callback(&p_callback) - , period(p_period) - { -#if 0 - if (period > std::chrono::milliseconds(0)){ - return; - } - switch (callback->type()){ - case InferenceType::VISUAL: - period = std::chrono::milliseconds(50); - break; - case InferenceType::AUDIO: - period = std::chrono::milliseconds(20); - break; - } -#endif - } -}; - - - -} -#endif +/* Inference Callback + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_InferenceCallback_H +#define PokemonAutomation_CommonTools_InferenceCallback_H + +#include +#include + +namespace PokemonAutomation{ + +enum class InferenceType{ + VISUAL, + AUDIO, +}; + +// Base class for an inference object to be called perioridically by +// inference routines in InferenceRoutines.h. +class InferenceCallback{ + // Disable these to prevent accidental copying/slicing. + InferenceCallback(const InferenceCallback&) = delete; + void operator=(const InferenceCallback&) = delete; + +public: + virtual ~InferenceCallback() = default; + + // Is it a visual or audio inference. + InferenceType type() const{ return m_type; } + // Name of the inference object. + const std::string& label() const{ return m_label; } + + +protected: + InferenceCallback(InferenceType type, std::string label) + : m_type(type) + , m_label(label) + {} + + +private: + InferenceType m_type; + std::string m_label; +}; + + + +// Used by inference routines in InferenceRoutines.h. +// The struct contains an inference callback and its inference period: how long +// should an inference routine wait before calling the callback object again. +struct PeriodicInferenceCallback{ + InferenceCallback* callback; + // Inference period. 0 value means the inference routine should use the + // default inference period, which is set as a parameter to the inference + // routine. + std::chrono::milliseconds period; + + PeriodicInferenceCallback() + : callback(nullptr) + , period(std::chrono::milliseconds(0)) + {} + PeriodicInferenceCallback( + InferenceCallback& p_callback, + std::chrono::milliseconds p_period = std::chrono::milliseconds(0) + ) + : callback(&p_callback) + , period(p_period) + { +#if 0 + if (period > std::chrono::milliseconds(0)){ + return; + } + switch (callback->type()){ + case InferenceType::VISUAL: + period = std::chrono::milliseconds(50); + break; + case InferenceType::AUDIO: + period = std::chrono::milliseconds(20); + break; + } +#endif + } +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/InferenceCallbacks/VisualInferenceCallback.cpp b/SerialPrograms/Source/CommonTools/InferenceCallbacks/VisualInferenceCallback.cpp index 5b8e4e91a2..938a11f752 100644 --- a/SerialPrograms/Source/CommonTools/InferenceCallbacks/VisualInferenceCallback.cpp +++ b/SerialPrograms/Source/CommonTools/InferenceCallbacks/VisualInferenceCallback.cpp @@ -1,26 +1,25 @@ -/* Visual Inference Callback - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "VisualInferenceCallback.h" - -namespace PokemonAutomation{ - - -bool VisualInferenceCallback::process_frame(const VideoSnapshot& frame){ - return process_frame(*frame.frame, frame.timestamp); -} -bool VisualInferenceCallback::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "You must override one of the two process_frame() functions."); -} - - - - - -} +/* Visual Inference Callback + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "VisualInferenceCallback.h" + +namespace PokemonAutomation{ + + +bool VisualInferenceCallback::process_frame(const VideoSnapshot& frame){ + return process_frame(*frame.frame, frame.timestamp); +} +bool VisualInferenceCallback::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "You must override one of the two process_frame() functions."); +} + + + + + +} diff --git a/SerialPrograms/Source/CommonTools/InferenceCallbacks/VisualInferenceCallback.h b/SerialPrograms/Source/CommonTools/InferenceCallbacks/VisualInferenceCallback.h index a6cee16fdb..4e42e056b8 100644 --- a/SerialPrograms/Source/CommonTools/InferenceCallbacks/VisualInferenceCallback.h +++ b/SerialPrograms/Source/CommonTools/InferenceCallbacks/VisualInferenceCallback.h @@ -1,46 +1,46 @@ -/* Visual Inference Callback - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_VisualInferenceCallback_H -#define PokemonAutomation_CommonTools_VisualInferenceCallback_H - -#include -#include "Common/Cpp/Time.h" -#include "InferenceCallback.h" - -namespace PokemonAutomation{ - -class ImageViewRGB32; -class ImageRGB32; -struct VideoSnapshot; -class VideoOverlaySet; - -// Base class for a visual inference object to be called perioridically by -// inference routines in InferenceRoutines.h. -class VisualInferenceCallback : public InferenceCallback{ -public: - VisualInferenceCallback(std::string label) - : InferenceCallback(InferenceType::VISUAL, std::move(label)) - {} - - // The inference routines call this function to create video overlays to visualize - // regions of interest of the inference callback. - virtual void make_overlays(VideoOverlaySet& items) const = 0; - - // Return true if the inference session should stop. - // You must override at least one of the overloaded `process_frame()`. - virtual bool process_frame(const VideoSnapshot& frame); - // Return true if the inference session should stop. - // You must override at least one of the overloaded `process_frame()`. - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp); - -}; - - - - -} -#endif +/* Visual Inference Callback + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_VisualInferenceCallback_H +#define PokemonAutomation_CommonTools_VisualInferenceCallback_H + +#include +#include "Common/Cpp/Time.h" +#include "InferenceCallback.h" + +namespace PokemonAutomation{ + +class ImageViewRGB32; +class ImageRGB32; +struct VideoSnapshot; +class VideoOverlaySet; + +// Base class for a visual inference object to be called perioridically by +// inference routines in InferenceRoutines.h. +class VisualInferenceCallback : public InferenceCallback{ +public: + VisualInferenceCallback(std::string label) + : InferenceCallback(InferenceType::VISUAL, std::move(label)) + {} + + // The inference routines call this function to create video overlays to visualize + // regions of interest of the inference callback. + virtual void make_overlays(VideoOverlaySet& items) const = 0; + + // Return true if the inference session should stop. + // You must override at least one of the overloaded `process_frame()`. + virtual bool process_frame(const VideoSnapshot& frame); + // Return true if the inference session should stop. + // You must override at least one of the overloaded `process_frame()`. + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp); + +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/InferencePivots/AudioInferencePivot.cpp b/SerialPrograms/Source/CommonTools/InferencePivots/AudioInferencePivot.cpp index b088207650..294ac3e912 100644 --- a/SerialPrograms/Source/CommonTools/InferencePivots/AudioInferencePivot.cpp +++ b/SerialPrograms/Source/CommonTools/InferencePivots/AudioInferencePivot.cpp @@ -1,130 +1,130 @@ -/* Audio Inference Pivot - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/AudioPipeline/AudioFeed.h" -#include "AudioInferencePivot.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -struct AudioInferencePivot::PeriodicCallback{ - Cancellable& scope; - std::atomic* set_when_triggered; - AudioInferenceCallback& callback; - std::chrono::milliseconds period; - - uint64_t last_seqnum = ~(uint64_t)0; - - StatAccumulatorI32 stats; - - PeriodicCallback( - Cancellable& p_scope, - std::atomic* p_set_when_triggered, - AudioInferenceCallback& p_callback, - std::chrono::milliseconds p_period - ) - : scope(p_scope) - , set_when_triggered(p_set_when_triggered) - , callback(p_callback) - , period(p_period) - {} -}; - - -AudioInferencePivot::AudioInferencePivot(CancellableScope& scope, AudioFeed& feed, AsyncDispatcher& dispatcher) - : PeriodicRunner(dispatcher) - , m_feed(feed) -{ - attach(scope); -} -AudioInferencePivot::~AudioInferencePivot(){ - detach(); - stop_thread(); -} -void AudioInferencePivot::add_callback( - Cancellable& scope, - std::atomic* set_when_triggered, - AudioInferenceCallback& callback, - std::chrono::milliseconds period -){ - WriteSpinLock lg(m_lock); - auto iter = m_map.find(&callback); - if (iter != m_map.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to add the same callback twice."); - } - iter = m_map.emplace( - std::piecewise_construct, - std::forward_as_tuple(&callback), - std::forward_as_tuple(scope, set_when_triggered, callback, period) - ).first; - try{ - PeriodicRunner::add_event(&iter->second, period); - }catch (...){ - m_map.erase(iter); - throw; - } -} -StatAccumulatorI32 AudioInferencePivot::remove_callback(AudioInferenceCallback& callback){ - WriteSpinLock lg(m_lock); - auto iter = m_map.find(&callback); - if (iter == m_map.end()){ - return StatAccumulatorI32(); - } - StatAccumulatorI32 stats = iter->second.stats; - PeriodicRunner::remove_event(&iter->second); - m_map.erase(iter); - return stats; -} -void AudioInferencePivot::run(void* event, bool is_back_to_back) noexcept{ - PeriodicCallback& callback = *(PeriodicCallback*)event; - try{ - std::vector spectrums; - - if (callback.last_seqnum == ~(uint64_t)0){ -// cout << "m_last_timestamp == SIZE_MAX" << endl; - spectrums = m_feed.spectrums_latest(1); - }else{ -// cout << "(m_last_timestamp != SIZE_MAX" << endl; - // Note: in this file we never consider the case that stamp may overflow. - // It requires on the order of 1e10 years to overflow if we have about 25ms per stamp. - spectrums = m_feed.spectrums_since(callback.last_seqnum + 1); - } - if (spectrums.size() > 0){ - // spectrums[0] has the newest spectrum with the largest stamp: - callback.last_seqnum = spectrums[0].stamp; - } - - WallClock time0 = current_time(); - bool stop = callback.callback.process_spectrums(spectrums, m_feed); - WallClock time1 = current_time(); - callback.stats += (uint32_t)std::chrono::duration_cast(time1 - time0).count(); - if (stop){ - if (callback.set_when_triggered){ - InferenceCallback* expected = nullptr; - callback.set_when_triggered->compare_exchange_strong(expected, &callback.callback); - } - callback.scope.cancel(nullptr); - } - }catch (...){ - callback.scope.cancel(std::current_exception()); - } -} - - -OverlayStatSnapshot AudioInferencePivot::get_current(){ - return m_printer.get_snapshot("Audio Pivot Utilization:", this->current_utilization()); -} - - - - -} +/* Audio Inference Pivot + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/AudioPipeline/AudioFeed.h" +#include "AudioInferencePivot.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +struct AudioInferencePivot::PeriodicCallback{ + Cancellable& scope; + std::atomic* set_when_triggered; + AudioInferenceCallback& callback; + std::chrono::milliseconds period; + + uint64_t last_seqnum = ~(uint64_t)0; + + StatAccumulatorI32 stats; + + PeriodicCallback( + Cancellable& p_scope, + std::atomic* p_set_when_triggered, + AudioInferenceCallback& p_callback, + std::chrono::milliseconds p_period + ) + : scope(p_scope) + , set_when_triggered(p_set_when_triggered) + , callback(p_callback) + , period(p_period) + {} +}; + + +AudioInferencePivot::AudioInferencePivot(CancellableScope& scope, AudioFeed& feed, AsyncDispatcher& dispatcher) + : PeriodicRunner(dispatcher) + , m_feed(feed) +{ + attach(scope); +} +AudioInferencePivot::~AudioInferencePivot(){ + detach(); + stop_thread(); +} +void AudioInferencePivot::add_callback( + Cancellable& scope, + std::atomic* set_when_triggered, + AudioInferenceCallback& callback, + std::chrono::milliseconds period +){ + WriteSpinLock lg(m_lock); + auto iter = m_map.find(&callback); + if (iter != m_map.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to add the same callback twice."); + } + iter = m_map.emplace( + std::piecewise_construct, + std::forward_as_tuple(&callback), + std::forward_as_tuple(scope, set_when_triggered, callback, period) + ).first; + try{ + PeriodicRunner::add_event(&iter->second, period); + }catch (...){ + m_map.erase(iter); + throw; + } +} +StatAccumulatorI32 AudioInferencePivot::remove_callback(AudioInferenceCallback& callback){ + WriteSpinLock lg(m_lock); + auto iter = m_map.find(&callback); + if (iter == m_map.end()){ + return StatAccumulatorI32(); + } + StatAccumulatorI32 stats = iter->second.stats; + PeriodicRunner::remove_event(&iter->second); + m_map.erase(iter); + return stats; +} +void AudioInferencePivot::run(void* event, bool is_back_to_back) noexcept{ + PeriodicCallback& callback = *(PeriodicCallback*)event; + try{ + std::vector spectrums; + + if (callback.last_seqnum == ~(uint64_t)0){ +// cout << "m_last_timestamp == SIZE_MAX" << endl; + spectrums = m_feed.spectrums_latest(1); + }else{ +// cout << "(m_last_timestamp != SIZE_MAX" << endl; + // Note: in this file we never consider the case that stamp may overflow. + // It requires on the order of 1e10 years to overflow if we have about 25ms per stamp. + spectrums = m_feed.spectrums_since(callback.last_seqnum + 1); + } + if (spectrums.size() > 0){ + // spectrums[0] has the newest spectrum with the largest stamp: + callback.last_seqnum = spectrums[0].stamp; + } + + WallClock time0 = current_time(); + bool stop = callback.callback.process_spectrums(spectrums, m_feed); + WallClock time1 = current_time(); + callback.stats += (uint32_t)std::chrono::duration_cast(time1 - time0).count(); + if (stop){ + if (callback.set_when_triggered){ + InferenceCallback* expected = nullptr; + callback.set_when_triggered->compare_exchange_strong(expected, &callback.callback); + } + callback.scope.cancel(nullptr); + } + }catch (...){ + callback.scope.cancel(std::current_exception()); + } +} + + +OverlayStatSnapshot AudioInferencePivot::get_current(){ + return m_printer.get_snapshot("Audio Pivot Utilization:", this->current_utilization()); +} + + + + +} diff --git a/SerialPrograms/Source/CommonTools/InferencePivots/AudioInferencePivot.h b/SerialPrograms/Source/CommonTools/InferencePivots/AudioInferencePivot.h index 145266e9b1..ff6fd0b8bd 100644 --- a/SerialPrograms/Source/CommonTools/InferencePivots/AudioInferencePivot.h +++ b/SerialPrograms/Source/CommonTools/InferencePivots/AudioInferencePivot.h @@ -1,60 +1,60 @@ -/* Audio Inference Pivot - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_AudioInferencePivot_H -#define PokemonAutomation_CommonTools_AudioInferencePivot_H - -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Cpp/Concurrency/PeriodicScheduler.h" -#include "CommonFramework/Tools/StatAccumulator.h" -#include "CommonFramework/VideoPipeline/VideoOverlayTypes.h" -#include "CommonTools/InferenceCallbacks/AudioInferenceCallback.h" - -namespace PokemonAutomation{ - -class AudioFeed; - - - -class AudioInferencePivot final : public PeriodicRunner, public OverlayStat{ -public: - AudioInferencePivot(CancellableScope& scope, AudioFeed& feed, AsyncDispatcher& dispatcher); - virtual ~AudioInferencePivot(); - - // If this callback returns true: - // 1. Cancel "scope". - // 2. Set "set_when_triggered" to the callback. - // If the callback throws an exception, "scope" will be cancelled with that exception. - void add_callback( - Cancellable& scope, - std::atomic* set_when_triggered, - AudioInferenceCallback& callback, - std::chrono::milliseconds period - ); - - // Returns the latency stats for the callback. Units are microseconds. - StatAccumulatorI32 remove_callback(AudioInferenceCallback& callback); - -private: - virtual void run(void* event, bool is_back_to_back) noexcept override; - virtual OverlayStatSnapshot get_current() override; - -private: - struct PeriodicCallback; - - AudioFeed& m_feed; - SpinLock m_lock; - std::map m_map; - -// uint64_t m_last_seqnum = ~(uint64_t)0; - - OverlayStatUtilizationPrinter m_printer; -}; - - - -} -#endif +/* Audio Inference Pivot + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_AudioInferencePivot_H +#define PokemonAutomation_CommonTools_AudioInferencePivot_H + +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Cpp/Concurrency/PeriodicScheduler.h" +#include "CommonFramework/Tools/StatAccumulator.h" +#include "CommonFramework/VideoPipeline/VideoOverlayTypes.h" +#include "CommonTools/InferenceCallbacks/AudioInferenceCallback.h" + +namespace PokemonAutomation{ + +class AudioFeed; + + + +class AudioInferencePivot final : public PeriodicRunner, public OverlayStat{ +public: + AudioInferencePivot(CancellableScope& scope, AudioFeed& feed, AsyncDispatcher& dispatcher); + virtual ~AudioInferencePivot(); + + // If this callback returns true: + // 1. Cancel "scope". + // 2. Set "set_when_triggered" to the callback. + // If the callback throws an exception, "scope" will be cancelled with that exception. + void add_callback( + Cancellable& scope, + std::atomic* set_when_triggered, + AudioInferenceCallback& callback, + std::chrono::milliseconds period + ); + + // Returns the latency stats for the callback. Units are microseconds. + StatAccumulatorI32 remove_callback(AudioInferenceCallback& callback); + +private: + virtual void run(void* event, bool is_back_to_back) noexcept override; + virtual OverlayStatSnapshot get_current() override; + +private: + struct PeriodicCallback; + + AudioFeed& m_feed; + SpinLock m_lock; + std::map m_map; + +// uint64_t m_last_seqnum = ~(uint64_t)0; + + OverlayStatUtilizationPrinter m_printer; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/InferencePivots/VisualInferencePivot.cpp b/SerialPrograms/Source/CommonTools/InferencePivots/VisualInferencePivot.cpp index 0e8867fab9..9e4d13f16d 100644 --- a/SerialPrograms/Source/CommonTools/InferencePivots/VisualInferencePivot.cpp +++ b/SerialPrograms/Source/CommonTools/InferencePivots/VisualInferencePivot.cpp @@ -1,122 +1,133 @@ -/* Visual Inference Pivot - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "VisualInferencePivot.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - - -struct VisualInferencePivot::PeriodicCallback{ - Cancellable& scope; - std::atomic* set_when_triggered; - VisualInferenceCallback& callback; - std::chrono::milliseconds period; - StatAccumulatorI32 stats; - uint64_t last_seqnum; - - PeriodicCallback( - Cancellable& p_scope, - std::atomic* p_set_when_triggered, - VisualInferenceCallback& p_callback, - std::chrono::milliseconds p_period - ) - : scope(p_scope) - , set_when_triggered(p_set_when_triggered) - , callback(p_callback) - , period(p_period) - , last_seqnum(0) - {} -}; - - - -VisualInferencePivot::VisualInferencePivot(CancellableScope& scope, VideoFeed& feed, AsyncDispatcher& dispatcher) - : PeriodicRunner(dispatcher) - , m_feed(feed) -{ - attach(scope); -} -VisualInferencePivot::~VisualInferencePivot(){ - detach(); - stop_thread(); -} -void VisualInferencePivot::add_callback( - Cancellable& scope, - std::atomic* set_when_triggered, - VisualInferenceCallback& callback, - std::chrono::milliseconds period -){ - WriteSpinLock lg(m_lock); - auto iter = m_map.find(&callback); - if (iter != m_map.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to add the same callback twice."); - } - iter = m_map.emplace( - std::piecewise_construct, - std::forward_as_tuple(&callback), - std::forward_as_tuple(scope, set_when_triggered, callback, period) - ).first; - try{ - PeriodicRunner::add_event(&iter->second, period); - }catch (...){ - m_map.erase(iter); - throw; - } -} -StatAccumulatorI32 VisualInferencePivot::remove_callback(VisualInferenceCallback& callback){ - WriteSpinLock lg(m_lock); - auto iter = m_map.find(&callback); - if (iter == m_map.end()){ - return StatAccumulatorI32(); - } - StatAccumulatorI32 stats = iter->second.stats; - PeriodicRunner::remove_event(&iter->second); - m_map.erase(iter); - return stats; -} -void VisualInferencePivot::run(void* event, bool is_back_to_back) noexcept{ - PeriodicCallback& callback = *(PeriodicCallback*)event; - try{ - // Reuse the cached screenshot. - if (!is_back_to_back || callback.last_seqnum == m_seqnum){ -// cout << "back-to-back" << endl; - m_last = m_feed.snapshot(); - m_seqnum++; - } - - WallClock time0 = current_time(); - bool stop = callback.callback.process_frame(m_last); - WallClock time1 = current_time(); - callback.stats += (uint32_t)std::chrono::duration_cast(time1 - time0).count(); - callback.last_seqnum = m_seqnum; - if (stop){ - if (callback.set_when_triggered){ - InferenceCallback* expected = nullptr; - callback.set_when_triggered->compare_exchange_strong(expected, &callback.callback); - } - callback.scope.cancel(nullptr); - } - }catch (...){ - callback.scope.cancel(std::current_exception()); - } -} - - -OverlayStatSnapshot VisualInferencePivot::get_current(){ - return m_printer.get_snapshot("Video Pivot Utilization:", this->current_utilization()); -} - - - - -} +/* Visual Inference Pivot + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "VisualInferencePivot.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + + +struct VisualInferencePivot::PeriodicCallback{ + Cancellable& scope; + std::atomic* set_when_triggered; + VisualInferenceCallback& callback; + std::chrono::milliseconds period; + StatAccumulatorI32 stats; + WallClock last_timestamp; + + PeriodicCallback( + Cancellable& p_scope, + std::atomic* p_set_when_triggered, + VisualInferenceCallback& p_callback, + std::chrono::milliseconds p_period + ) + : scope(p_scope) + , set_when_triggered(p_set_when_triggered) + , callback(p_callback) + , period(p_period) + , last_timestamp(WallClock::min()) + {} +}; + + + +VisualInferencePivot::VisualInferencePivot(CancellableScope& scope, VideoFeed& feed, AsyncDispatcher& dispatcher) + : PeriodicRunner(dispatcher) + , m_feed(feed) +{ + attach(scope); +} +VisualInferencePivot::~VisualInferencePivot(){ + detach(); + stop_thread(); +} +void VisualInferencePivot::add_callback( + Cancellable& scope, + std::atomic* set_when_triggered, + VisualInferenceCallback& callback, + std::chrono::milliseconds period +){ + WriteSpinLock lg(m_lock); + auto iter = m_map.find(&callback); + if (iter != m_map.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to add the same callback twice."); + } + iter = m_map.emplace( + std::piecewise_construct, + std::forward_as_tuple(&callback), + std::forward_as_tuple(scope, set_when_triggered, callback, period) + ).first; + try{ + PeriodicRunner::add_event(&iter->second, period); + }catch (...){ + m_map.erase(iter); + throw; + } +} +StatAccumulatorI32 VisualInferencePivot::remove_callback(VisualInferenceCallback& callback){ + WriteSpinLock lg(m_lock); + auto iter = m_map.find(&callback); + if (iter == m_map.end()){ + return StatAccumulatorI32(); + } + StatAccumulatorI32 stats = iter->second.stats; + PeriodicRunner::remove_event(&iter->second); + m_map.erase(iter); + return stats; +} +void VisualInferencePivot::run(void* event, bool is_back_to_back) noexcept{ + PeriodicCallback& callback = *(PeriodicCallback*)event; + try{ + // Reuse the cached screenshot. + if (!is_back_to_back || callback.last_timestamp == m_last.timestamp){ +// cout << "back-to-back" << endl; +// m_last = m_feed.snapshot(); + + WallClock min_time = callback.last_timestamp; + if (min_time == WallClock::min()){ + min_time = current_time() - 2 * callback.period; + } + + m_last = m_feed.snapshot_recent_nonblocking(min_time); + } + + if (!m_last){ + return; + } + + WallClock time0 = current_time(); + bool stop = callback.callback.process_frame(m_last); + WallClock time1 = current_time(); + callback.stats += (uint32_t)std::chrono::duration_cast(time1 - time0).count(); + callback.last_timestamp = m_last.timestamp; + + if (stop){ + if (callback.set_when_triggered){ + InferenceCallback* expected = nullptr; + callback.set_when_triggered->compare_exchange_strong(expected, &callback.callback); + } + callback.scope.cancel(nullptr); + } + }catch (...){ + callback.scope.cancel(std::current_exception()); + } +} + + +OverlayStatSnapshot VisualInferencePivot::get_current(){ + return m_printer.get_snapshot("Video Pivot Utilization:", this->current_utilization()); +} + + + + +} diff --git a/SerialPrograms/Source/CommonTools/InferencePivots/VisualInferencePivot.h b/SerialPrograms/Source/CommonTools/InferencePivots/VisualInferencePivot.h index 796495b9ae..0d27a12fc1 100644 --- a/SerialPrograms/Source/CommonTools/InferencePivots/VisualInferencePivot.h +++ b/SerialPrograms/Source/CommonTools/InferencePivots/VisualInferencePivot.h @@ -1,61 +1,60 @@ -/* Visual Inference Pivot - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_VisualInferencePivot_H -#define PokemonAutomation_CommonTools_VisualInferencePivot_H - -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Cpp/Concurrency/PeriodicScheduler.h" -#include "CommonFramework/Tools/StatAccumulator.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayTypes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ - -class VideoFeed; - - - -class VisualInferencePivot final : public PeriodicRunner, public OverlayStat{ -public: - VisualInferencePivot(CancellableScope& scope, VideoFeed& feed, AsyncDispatcher& dispatcher); - virtual ~VisualInferencePivot(); - - // If this callback returns true: - // 1. Cancel "scope". - // 2. Set "set_when_triggered" to the callback. - // If the callback throws an exception, "scope" will be cancelled with that exception. - void add_callback( - Cancellable& scope, - std::atomic* set_when_triggered, - VisualInferenceCallback& callback, - std::chrono::milliseconds period - ); - - // Returns the latency stats for the callback. Units are microseconds. - StatAccumulatorI32 remove_callback(VisualInferenceCallback& callback); - -private: - virtual void run(void* event, bool is_back_to_back) noexcept override; - virtual OverlayStatSnapshot get_current() override; - -private: - struct PeriodicCallback; - - VideoFeed& m_feed; - SpinLock m_lock; - std::map m_map; - VideoSnapshot m_last; - uint64_t m_seqnum = 0; - - OverlayStatUtilizationPrinter m_printer; -}; - - - -} -#endif +/* Visual Inference Pivot + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_VisualInferencePivot_H +#define PokemonAutomation_CommonTools_VisualInferencePivot_H + +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Cpp/Concurrency/PeriodicScheduler.h" +#include "CommonFramework/Tools/StatAccumulator.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayTypes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ + +class VideoFeed; + + + +class VisualInferencePivot final : public PeriodicRunner, public OverlayStat{ +public: + VisualInferencePivot(CancellableScope& scope, VideoFeed& feed, AsyncDispatcher& dispatcher); + virtual ~VisualInferencePivot(); + + // If this callback returns true: + // 1. Cancel "scope". + // 2. Set "set_when_triggered" to the callback. + // If the callback throws an exception, "scope" will be cancelled with that exception. + void add_callback( + Cancellable& scope, + std::atomic* set_when_triggered, + VisualInferenceCallback& callback, + std::chrono::milliseconds period + ); + + // Returns the latency stats for the callback. Units are microseconds. + StatAccumulatorI32 remove_callback(VisualInferenceCallback& callback); + +private: + virtual void run(void* event, bool is_back_to_back) noexcept override; + virtual OverlayStatSnapshot get_current() override; + +private: + struct PeriodicCallback; + + VideoFeed& m_feed; + SpinLock m_lock; + std::map m_map; + VideoSnapshot m_last; + + OverlayStatUtilizationPrinter m_printer; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/InferenceThrottler.h b/SerialPrograms/Source/CommonTools/InferenceThrottler.h index a1ff066167..d549d3edc3 100644 --- a/SerialPrograms/Source/CommonTools/InferenceThrottler.h +++ b/SerialPrograms/Source/CommonTools/InferenceThrottler.h @@ -1,61 +1,61 @@ -/* Inference Throttler - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_InferenceThrottler_H -#define PokemonAutomation_CommonTools_InferenceThrottler_H - -#include -#include "Common/Cpp/CancellableScope.h" - -namespace PokemonAutomation{ - -class InferenceThrottler{ -public: - InferenceThrottler( - std::chrono::milliseconds timeout, - std::chrono::milliseconds period = std::chrono::milliseconds(50) - ) - : m_timeout(timeout) - , m_period(period) - , m_start(current_time()) - , m_wait_until(m_start + period) - {} - - // Call at the end of each loop iteration. This will wait until the - // time since the previous iteration has reached the specified period. - // - // Returns true if this loop has timed out. - bool end_iteration(CancellableScope& scope){ - auto now = current_time(); - if (m_timeout != std::chrono::milliseconds(0) && now - m_start >= m_timeout){ - return true; - } - - std::chrono::milliseconds wait = std::chrono::duration_cast(m_wait_until - now); - if (wait <= std::chrono::milliseconds(0)){ - m_wait_until = now + m_period; - }else{ - m_wait_until += m_period; - scope.wait_for(wait); - } - return false; - } - - void set_period(std::chrono::milliseconds period){ - m_period = period; - } - -private: - std::chrono::milliseconds m_timeout; - std::chrono::milliseconds m_period; - WallClock m_start; - WallClock m_wait_until; -}; - - - -} -#endif +/* Inference Throttler + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_InferenceThrottler_H +#define PokemonAutomation_CommonTools_InferenceThrottler_H + +#include +#include "Common/Cpp/CancellableScope.h" + +namespace PokemonAutomation{ + +class InferenceThrottler{ +public: + InferenceThrottler( + std::chrono::milliseconds timeout, + std::chrono::milliseconds period = std::chrono::milliseconds(50) + ) + : m_timeout(timeout) + , m_period(period) + , m_start(current_time()) + , m_wait_until(m_start + period) + {} + + // Call at the end of each loop iteration. This will wait until the + // time since the previous iteration has reached the specified period. + // + // Returns true if this loop has timed out. + bool end_iteration(CancellableScope& scope){ + auto now = current_time(); + if (m_timeout != std::chrono::milliseconds(0) && now - m_start >= m_timeout){ + return true; + } + + std::chrono::milliseconds wait = std::chrono::duration_cast(m_wait_until - now); + if (wait <= std::chrono::milliseconds(0)){ + m_wait_until = now + m_period; + }else{ + m_wait_until += m_period; + scope.wait_for(wait); + } + return false; + } + + void set_period(std::chrono::milliseconds period){ + m_period = period; + } + +private: + std::chrono::milliseconds m_timeout; + std::chrono::milliseconds m_period; + WallClock m_start; + WallClock m_wait_until; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/MultiConsoleErrors.cpp b/SerialPrograms/Source/CommonTools/MultiConsoleErrors.cpp index cbf4bc64ce..393d08e1fe 100644 --- a/SerialPrograms/Source/CommonTools/MultiConsoleErrors.cpp +++ b/SerialPrograms/Source/CommonTools/MultiConsoleErrors.cpp @@ -1,31 +1,31 @@ -/* Multi-Console Errors - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "MultiConsoleErrors.h" - -namespace PokemonAutomation{ - - - -void MultiConsoleErrorState::report_unrecoverable_error(VideoStream& stream, std::string msg){ - stream.log(msg, COLOR_RED); - bool expected = false; - if (m_unrecoverable_error.compare_exchange_strong(expected, true)){ - m_message = msg; - } - OperationFailedException::fire(ErrorReport::SEND_ERROR_REPORT, std::move(msg), stream); -} -void MultiConsoleErrorState::check_unrecoverable_error(Logger& logger){ - if (m_unrecoverable_error.load(std::memory_order_acquire)){ - logger.log("Unrecoverable error reported from a different console. Breaking out.", COLOR_RED); - throw_and_log(logger, ErrorReport::NO_ERROR_REPORT, m_message); - } -} - - - -} +/* Multi-Console Errors + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "MultiConsoleErrors.h" + +namespace PokemonAutomation{ + + + +void MultiConsoleErrorState::report_unrecoverable_error(VideoStream& stream, std::string msg){ + stream.log(msg, COLOR_RED); + bool expected = false; + if (m_unrecoverable_error.compare_exchange_strong(expected, true)){ + m_message = msg; + } + OperationFailedException::fire(ErrorReport::SEND_ERROR_REPORT, std::move(msg), stream); +} +void MultiConsoleErrorState::check_unrecoverable_error(Logger& logger){ + if (m_unrecoverable_error.load(std::memory_order_acquire)){ + logger.log("Unrecoverable error reported from a different console. Breaking out.", COLOR_RED); + throw_and_log(logger, ErrorReport::NO_ERROR_REPORT, m_message); + } +} + + + +} diff --git a/SerialPrograms/Source/CommonTools/MultiConsoleErrors.h b/SerialPrograms/Source/CommonTools/MultiConsoleErrors.h index c00362fcf2..573de98bb2 100644 --- a/SerialPrograms/Source/CommonTools/MultiConsoleErrors.h +++ b/SerialPrograms/Source/CommonTools/MultiConsoleErrors.h @@ -1,33 +1,33 @@ -/* Multi-Console Errors - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_MultiConsoleErrors_H -#define PokemonAutomation_CommonTools_MultiConsoleErrors_H - -#include -#include - -namespace PokemonAutomation{ - -class Logger; -class VideoStream; - - -class MultiConsoleErrorState{ -public: - void report_unrecoverable_error(VideoStream& stream, std::string msg); - void check_unrecoverable_error(Logger& logger); - -private: - std::atomic m_unrecoverable_error; - std::string m_message; -}; - - - - -} -#endif +/* Multi-Console Errors + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_MultiConsoleErrors_H +#define PokemonAutomation_CommonTools_MultiConsoleErrors_H + +#include +#include + +namespace PokemonAutomation{ + +class Logger; +class VideoStream; + + +class MultiConsoleErrorState{ +public: + void report_unrecoverable_error(VideoStream& stream, std::string msg); + void check_unrecoverable_error(Logger& logger); + +private: + std::atomic m_unrecoverable_error; + std::string m_message; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryMatcher.cpp b/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryMatcher.cpp index 3123bbe9f2..2c274a41d2 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryMatcher.cpp +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryMatcher.cpp @@ -1,65 +1,65 @@ -/* Dictionary Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "OCR_DictionaryMatcher.h" - -namespace PokemonAutomation{ -namespace OCR{ - - -const DictionaryOCR& DictionaryMatcher::dictionary(Language language) const{ - auto iter = m_database.find(language); - if (iter == m_database.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Language not loaded."); - } - return iter->second; -} -DictionaryOCR& DictionaryMatcher::dictionary(Language language){ - ReadSpinLock lg(m_lock, "LargeDictionaryMatcher::dictionary()"); - auto iter = m_database.find(language); - if (iter == m_database.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Language not loaded."); - } - return iter->second; -} - - -StringMatchResult DictionaryMatcher::match_substring( - Language language, - const std::string& text, - double log10p_spread -) const{ - return dictionary(language).match_substring(text, log10p_spread); -} - -OCR::StringMatchResult DictionaryMatcher::match_substring_from_image_multifiltered( - Logger* logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double max_log10p, double log10p_spread, - double min_text_ratio, double max_text_ratio -) const{ - OCR::StringMatchResult ret = OCR::multifiltered_OCR( - language, *this, image, - text_color_ranges, - log10p_spread, min_text_ratio, max_text_ratio - ); - if (logger){ - ret.log(*logger, max_log10p); - } - ret.clear_beyond_log10p(max_log10p); - return ret; -} - -void DictionaryMatcher::add_candidate(Language language, std::string token, const std::u32string& candidate){ - dictionary(language).add_candidate(std::move(token), candidate); -} - - -} -} +/* Dictionary Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "OCR_DictionaryMatcher.h" + +namespace PokemonAutomation{ +namespace OCR{ + + +const DictionaryOCR& DictionaryMatcher::dictionary(Language language) const{ + auto iter = m_database.find(language); + if (iter == m_database.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Language not loaded."); + } + return iter->second; +} +DictionaryOCR& DictionaryMatcher::dictionary(Language language){ + ReadSpinLock lg(m_lock, "LargeDictionaryMatcher::dictionary()"); + auto iter = m_database.find(language); + if (iter == m_database.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Language not loaded."); + } + return iter->second; +} + + +StringMatchResult DictionaryMatcher::match_substring( + Language language, + const std::string& text, + double log10p_spread +) const{ + return dictionary(language).match_substring(text, log10p_spread); +} + +OCR::StringMatchResult DictionaryMatcher::match_substring_from_image_multifiltered( + Logger* logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double max_log10p, double log10p_spread, + double min_text_ratio, double max_text_ratio +) const{ + OCR::StringMatchResult ret = OCR::multifiltered_OCR( + language, *this, image, + text_color_ranges, + log10p_spread, min_text_ratio, max_text_ratio + ); + if (logger){ + ret.log(*logger, max_log10p); + } + ret.clear_beyond_log10p(max_log10p); + return ret; +} + +void DictionaryMatcher::add_candidate(Language language, std::string token, const std::u32string& candidate){ + dictionary(language).add_candidate(std::move(token), candidate); +} + + +} +} diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryMatcher.h b/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryMatcher.h index 179e557a38..6890b7499b 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryMatcher.h +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryMatcher.h @@ -1,79 +1,79 @@ -/* Dictionary Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_OCR_DictionaryMatcher_H -#define PokemonAutomation_CommonTools_OCR_DictionaryMatcher_H - -#include -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "CommonFramework/Language.h" -#include "OCR_Routines.h" -#include "OCR_DictionaryOCR.h" - -namespace PokemonAutomation{ - class ImageViewRGB32; -namespace OCR{ - -// Base class for an OCR matcher. It matches a sub-string from a dictionary. -// The construction of the dictionary is left to the derived class. -class DictionaryMatcher{ -public: - const LanguageSet& languages() const{ return m_languages; } - - -public: - const DictionaryOCR& dictionary(Language language) const; - - - StringMatchResult match_substring( - Language language, - const std::string& text, double log10p_spread = 0.50 - ) const; - - // Match a substring from `image`. - // text_color_ranges: the function will try multiple attempts of separating - // text color and background color, and do OCR on the text with background color - // removed. The text color range of attempt is specified by each element in - // `text_color_ranges`. - // max_log10p: Threshold for finding any valid match. - // The raw OCR result gives a probability for each dictionary key. The probility p - // is that if this key is matched by accident. The lower this value, the closer - // the match. Apply log10() to it to get log10p. - // If all keys' log10p is above this `max_log10p`, there will be no match. - // log10p_spread: threshold for considering ambiguous match. - // It specifies the minimum separation between the best candidate and - // 2nd best candidate's log10p for it to not be considered ambiguous. - // min/max_text_ratio: min/max_text_ratio is the range where the ratio of text color - // pixel count to background color pixel count must fall into before the matcher - // even attempts to OCR. This is useful for pruning images with no appearant texts to - // reduce expensive OCR computation. - OCR::StringMatchResult match_substring_from_image_multifiltered( - Logger* logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double max_log10p, double log10p_spread = 0.5, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 - ) const; - - -public: - // These functions are thread-safe with themselves, but not with any other - // functions in this class. - DictionaryOCR& dictionary(Language language); - void add_candidate(Language language, std::string token, const std::u32string& candidate); - - -protected: - LanguageSet m_languages; - std::map m_database; - SpinLock m_lock; -}; - - -} -} -#endif +/* Dictionary Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_OCR_DictionaryMatcher_H +#define PokemonAutomation_CommonTools_OCR_DictionaryMatcher_H + +#include +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "CommonFramework/Language.h" +#include "OCR_Routines.h" +#include "OCR_DictionaryOCR.h" + +namespace PokemonAutomation{ + class ImageViewRGB32; +namespace OCR{ + +// Base class for an OCR matcher. It matches a sub-string from a dictionary. +// The construction of the dictionary is left to the derived class. +class DictionaryMatcher{ +public: + const LanguageSet& languages() const{ return m_languages; } + + +public: + const DictionaryOCR& dictionary(Language language) const; + + + StringMatchResult match_substring( + Language language, + const std::string& text, double log10p_spread = 0.50 + ) const; + + // Match a substring from `image`. + // text_color_ranges: the function will try multiple attempts of separating + // text color and background color, and do OCR on the text with background color + // removed. The text color range of attempt is specified by each element in + // `text_color_ranges`. + // max_log10p: Threshold for finding any valid match. + // The raw OCR result gives a probability for each dictionary key. The probility p + // is that if this key is matched by accident. The lower this value, the closer + // the match. Apply log10() to it to get log10p. + // If all keys' log10p is above this `max_log10p`, there will be no match. + // log10p_spread: threshold for considering ambiguous match. + // It specifies the minimum separation between the best candidate and + // 2nd best candidate's log10p for it to not be considered ambiguous. + // min/max_text_ratio: min/max_text_ratio is the range where the ratio of text color + // pixel count to background color pixel count must fall into before the matcher + // even attempts to OCR. This is useful for pruning images with no appearant texts to + // reduce expensive OCR computation. + OCR::StringMatchResult match_substring_from_image_multifiltered( + Logger* logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double max_log10p, double log10p_spread = 0.5, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 + ) const; + + +public: + // These functions are thread-safe with themselves, but not with any other + // functions in this class. + DictionaryOCR& dictionary(Language language); + void add_candidate(Language language, std::string token, const std::u32string& candidate); + + +protected: + LanguageSet m_languages; + std::map m_database; + SpinLock m_lock; +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryOCR.cpp b/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryOCR.cpp index f5752076b6..b658a94688 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryOCR.cpp +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryOCR.cpp @@ -1,131 +1,131 @@ -/* Dictionary OCR - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "Common/Qt/StringToolsQt.h" -#include "CommonFramework/Logging/Logger.h" -#include "OCR_StringNormalization.h" -#include "OCR_TextMatcher.h" -#include "OCR_DictionaryOCR.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace OCR{ - - - -DictionaryOCR::DictionaryOCR( - const JsonObject& json, - const std::set* subset, - double random_match_chance, - bool first_only -) - : m_random_match_chance(random_match_chance) -{ - for (const auto& item0 : json){ - const std::string& token = item0.first; - if (subset != nullptr && subset->find(token) == subset->end()){ - continue; - } - std::vector& candidates = m_database[token]; - for (const auto& item1 : item0.second.to_array_throw()){ - const std::string& candidate = item1.to_string_throw(); - std::u32string normalized = normalize_utf32(candidate); - std::set& set = m_candidate_to_token[normalized]; - if (!set.empty()){ - global_logger_tagged().log("DictionaryOCR - Duplicate Candidate: " + token + " (" + to_utf8(normalized) + ")"); -// cout << "Duplicate Candidate: " << candidate << endl; - } - set.insert(token); - candidates.emplace_back(candidate); - if (first_only){ - break; - } - } - } - global_logger_tagged().log( - "DictionaryOCR - Tokens: " + std::to_string(m_database.size()) + - ", Match Candidates: " + std::to_string(m_candidate_to_token.size()) - ); -// cout << "Tokens: " << m_database.size() << ", Match Candidates: " << m_candidate_to_token.size() << endl; -} -DictionaryOCR::DictionaryOCR( - const std::string& json_path, - const std::set* subset, - double random_match_chance, - bool first_only -) - : DictionaryOCR( - load_json_file(json_path).to_object_throw(json_path), - subset, - random_match_chance, - first_only - ) -{} - -JsonObject DictionaryOCR::to_json() const{ - JsonObject obj; - for (const auto& item : m_database){ - JsonArray list; - for (const std::string& candidate : item.second){ - list.push_back(candidate); - } - obj[item.first] = std::move(list); - } - return obj; -} -void DictionaryOCR::save_json(const std::string& json_path) const{ - to_json().dump(json_path); -} - - - -StringMatchResult DictionaryOCR::match_substring( - const std::string& text, - double log10p_spread -) const{ - return OCR::match_substring( - m_candidate_to_token, m_random_match_chance, - text, log10p_spread - ); -} -void DictionaryOCR::add_candidate(std::string token, const std::u32string& candidate){ - if (candidate.size() < 2){ - return; - } - - WriteSpinLock lg(m_lock, "DictionaryOCR::add_candidate()"); - - auto iter = m_candidate_to_token.find(candidate); - if (iter == m_candidate_to_token.end()){ - // New candidate. Add it to both maps. - m_database[token].emplace_back(to_utf8(candidate)); - m_candidate_to_token[candidate].insert(std::move(token)); - return; - } - - // Candidate already exists in table. - std::set& tokens = iter->second; - if (tokens.find(token) == tokens.end()){ - // Add to database only if it isn't already there. - m_database[token].emplace_back(to_utf8(candidate)); - } - - tokens.insert(std::move(token)); -} - - - - - - -} -} +/* Dictionary OCR + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Common/Qt/StringToolsQt.h" +#include "CommonFramework/Logging/Logger.h" +#include "OCR_StringNormalization.h" +#include "OCR_TextMatcher.h" +#include "OCR_DictionaryOCR.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace OCR{ + + + +DictionaryOCR::DictionaryOCR( + const JsonObject& json, + const std::set* subset, + double random_match_chance, + bool first_only +) + : m_random_match_chance(random_match_chance) +{ + for (const auto& item0 : json){ + const std::string& token = item0.first; + if (subset != nullptr && subset->find(token) == subset->end()){ + continue; + } + std::vector& candidates = m_database[token]; + for (const auto& item1 : item0.second.to_array_throw()){ + const std::string& candidate = item1.to_string_throw(); + std::u32string normalized = normalize_utf32(candidate); + std::set& set = m_candidate_to_token[normalized]; + if (!set.empty()){ + global_logger_tagged().log("DictionaryOCR - Duplicate Candidate: " + token + " (" + to_utf8(normalized) + ")"); +// cout << "Duplicate Candidate: " << candidate << endl; + } + set.insert(token); + candidates.emplace_back(candidate); + if (first_only){ + break; + } + } + } + global_logger_tagged().log( + "DictionaryOCR - Tokens: " + std::to_string(m_database.size()) + + ", Match Candidates: " + std::to_string(m_candidate_to_token.size()) + ); +// cout << "Tokens: " << m_database.size() << ", Match Candidates: " << m_candidate_to_token.size() << endl; +} +DictionaryOCR::DictionaryOCR( + const std::string& json_path, + const std::set* subset, + double random_match_chance, + bool first_only +) + : DictionaryOCR( + load_json_file(json_path).to_object_throw(json_path), + subset, + random_match_chance, + first_only + ) +{} + +JsonObject DictionaryOCR::to_json() const{ + JsonObject obj; + for (const auto& item : m_database){ + JsonArray list; + for (const std::string& candidate : item.second){ + list.push_back(candidate); + } + obj[item.first] = std::move(list); + } + return obj; +} +void DictionaryOCR::save_json(const std::string& json_path) const{ + to_json().dump(json_path); +} + + + +StringMatchResult DictionaryOCR::match_substring( + const std::string& text, + double log10p_spread +) const{ + return OCR::match_substring( + m_candidate_to_token, m_random_match_chance, + text, log10p_spread + ); +} +void DictionaryOCR::add_candidate(std::string token, const std::u32string& candidate){ + if (candidate.size() < 2){ + return; + } + + WriteSpinLock lg(m_lock, "DictionaryOCR::add_candidate()"); + + auto iter = m_candidate_to_token.find(candidate); + if (iter == m_candidate_to_token.end()){ + // New candidate. Add it to both maps. + m_database[token].emplace_back(to_utf8(candidate)); + m_candidate_to_token[candidate].insert(std::move(token)); + return; + } + + // Candidate already exists in table. + std::set& tokens = iter->second; + if (tokens.find(token) == tokens.end()){ + // Add to database only if it isn't already there. + m_database[token].emplace_back(to_utf8(candidate)); + } + + tokens.insert(std::move(token)); +} + + + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryOCR.h b/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryOCR.h index 7db1038743..b95e796fbb 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryOCR.h +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryOCR.h @@ -1,61 +1,61 @@ -/* Dictionary OCR - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_OCR_DictionaryOCR_H -#define PokemonAutomation_CommonTools_OCR_DictionaryOCR_H - -#include -#include -#include -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "OCR_StringMatchResult.h" - -namespace PokemonAutomation{ - class JsonObject; -namespace OCR{ - - -class DictionaryOCR{ -public: - DictionaryOCR( - const JsonObject& json, - const std::set* subset, - double random_match_chance, - bool first_only - ); - DictionaryOCR( - const std::string& json_path, - const std::set* subset, - double random_match_chance, - bool first_only - ); - - JsonObject to_json() const; - void save_json(const std::string& json_path) const; - - StringMatchResult match_substring(const std::string& text, double log10p_spread = 0.50) const; - - -public: - // This function is thread-safe with itself, but not with any other - // function in this class. - - void add_candidate(std::string token, const std::u32string& candidate); - - -private: - SpinLock m_lock; - double m_random_match_chance; - std::map> m_database; - std::map> m_candidate_to_token; -}; - - - - -} -} -#endif +/* Dictionary OCR + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_OCR_DictionaryOCR_H +#define PokemonAutomation_CommonTools_OCR_DictionaryOCR_H + +#include +#include +#include +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "OCR_StringMatchResult.h" + +namespace PokemonAutomation{ + class JsonObject; +namespace OCR{ + + +class DictionaryOCR{ +public: + DictionaryOCR( + const JsonObject& json, + const std::set* subset, + double random_match_chance, + bool first_only + ); + DictionaryOCR( + const std::string& json_path, + const std::set* subset, + double random_match_chance, + bool first_only + ); + + JsonObject to_json() const; + void save_json(const std::string& json_path) const; + + StringMatchResult match_substring(const std::string& text, double log10p_spread = 0.50) const; + + +public: + // This function is thread-safe with itself, but not with any other + // function in this class. + + void add_candidate(std::string token, const std::u32string& candidate); + + +private: + SpinLock m_lock; + double m_random_match_chance; + std::map> m_database; + std::map> m_candidate_to_token; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_LargeDictionaryMatcher.cpp b/SerialPrograms/Source/CommonTools/OCR/OCR_LargeDictionaryMatcher.cpp index 43c1513aff..f14f9a76bc 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_LargeDictionaryMatcher.cpp +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_LargeDictionaryMatcher.cpp @@ -1,49 +1,49 @@ -/* Large Database Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Globals.h" -#include "OCR_StringNormalization.h" -#include "OCR_TextMatcher.h" -#include "OCR_LargeDictionaryMatcher.h" - -namespace PokemonAutomation{ -namespace OCR{ - - - -LargeDictionaryMatcher::LargeDictionaryMatcher( - const std::string& json_file_prefix, - const std::set* subset, - bool first_only -){ - std::string prefix = RESOURCE_PATH() + json_file_prefix; - for (size_t c = 1; c < (size_t)Language::EndOfList; c++){ - Language language = (Language)c; - const LanguageData& data = language_data(language); - const std::string& code = data.code; - try{ - m_database.emplace( - std::piecewise_construct, - std::forward_as_tuple(language), - std::forward_as_tuple(prefix + code + ".json", subset, data.random_match_chance, first_only) - ); - m_languages += language; - }catch (FileException&){} - } -} - -void LargeDictionaryMatcher::save(Language language, const std::string& json_path) const{ - dictionary(language).save_json(json_path); -} - - - - - - -} -} +/* Large Database Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Globals.h" +#include "OCR_StringNormalization.h" +#include "OCR_TextMatcher.h" +#include "OCR_LargeDictionaryMatcher.h" + +namespace PokemonAutomation{ +namespace OCR{ + + + +LargeDictionaryMatcher::LargeDictionaryMatcher( + const std::string& json_file_prefix, + const std::set* subset, + bool first_only +){ + std::string prefix = RESOURCE_PATH() + json_file_prefix; + for (size_t c = 1; c < (size_t)Language::EndOfList; c++){ + Language language = (Language)c; + const LanguageData& data = language_data(language); + const std::string& code = data.code; + try{ + m_database.emplace( + std::piecewise_construct, + std::forward_as_tuple(language), + std::forward_as_tuple(prefix + code + ".json", subset, data.random_match_chance, first_only) + ); + m_languages += language; + }catch (FileException&){} + } +} + +void LargeDictionaryMatcher::save(Language language, const std::string& json_path) const{ + dictionary(language).save_json(json_path); +} + + + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_LargeDictionaryMatcher.h b/SerialPrograms/Source/CommonTools/OCR/OCR_LargeDictionaryMatcher.h index 850c0a0d09..94eaac1ea2 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_LargeDictionaryMatcher.h +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_LargeDictionaryMatcher.h @@ -1,47 +1,47 @@ -/* Large Dictionary Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_OCR_LargeDictionaryMatcher_H -#define PokemonAutomation_CommonTools_OCR_LargeDictionaryMatcher_H - -#include "OCR_DictionaryMatcher.h" - -namespace PokemonAutomation{ -namespace OCR{ - -// An OCR matcher with a small dictionary. -// Since the dictionary is large, each languages of the dictionary is stored as a -// separate JSON file. -class LargeDictionaryMatcher : public DictionaryMatcher{ -public: - // Load the JSON file to build the dictionary for all languages stored in each - // language JSON file. - // json_file_prefix: the file path prefix for all the language JSON files. - // subset: if not nullptr, only add keys in this `subset` to the dictionary. - // otherwise, add all keys found in the JSON to the dictionary. - // first_only: whether to use only the first value for each slug. - // This parameter is only useful for training the OCR. - // During inference, we set `first_only` to false so that each slug corresponds to - // all the values in that dictionary entry. - // e.g. if `first_only` is false, when loading Pokemon Abomasnow for traditional Chinese, - // "abomasnow": ["暴雪王", "繁霎王", "鬘粘王"], - // when OCR detects any of "暴雪王", "繁霎王" or "鬘粘王", the matcher returns Abomasnow. - // if 'first_only' is true, only when OCR detects "暴雪王" do the matcher return Abomasnow. - LargeDictionaryMatcher( - const std::string& json_file_prefix, - const std::set* subset, - bool first_only - ); - - void save(Language language, const std::string& json_path) const; - -private: -}; - - -} -} -#endif +/* Large Dictionary Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_OCR_LargeDictionaryMatcher_H +#define PokemonAutomation_CommonTools_OCR_LargeDictionaryMatcher_H + +#include "OCR_DictionaryMatcher.h" + +namespace PokemonAutomation{ +namespace OCR{ + +// An OCR matcher with a small dictionary. +// Since the dictionary is large, each languages of the dictionary is stored as a +// separate JSON file. +class LargeDictionaryMatcher : public DictionaryMatcher{ +public: + // Load the JSON file to build the dictionary for all languages stored in each + // language JSON file. + // json_file_prefix: the file path prefix for all the language JSON files. + // subset: if not nullptr, only add keys in this `subset` to the dictionary. + // otherwise, add all keys found in the JSON to the dictionary. + // first_only: whether to use only the first value for each slug. + // This parameter is only useful for training the OCR. + // During inference, we set `first_only` to false so that each slug corresponds to + // all the values in that dictionary entry. + // e.g. if `first_only` is false, when loading Pokemon Abomasnow for traditional Chinese, + // "abomasnow": ["暴雪王", "繁霎王", "鬘粘王"], + // when OCR detects any of "暴雪王", "繁霎王" or "鬘粘王", the matcher returns Abomasnow. + // if 'first_only' is true, only when OCR detects "暴雪王" do the matcher return Abomasnow. + LargeDictionaryMatcher( + const std::string& json_file_prefix, + const std::set* subset, + bool first_only + ); + + void save(Language language, const std::string& json_path) const; + +private: +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_NumberReader.cpp b/SerialPrograms/Source/CommonTools/OCR/OCR_NumberReader.cpp index 9291112345..fa5657437c 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_NumberReader.cpp +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_NumberReader.cpp @@ -1,252 +1,281 @@ -/* OCR Number Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Qt/StringToolsQt.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonFramework/Language.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/Images/ImageManip.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "OCR_RawOCR.h" -#include "OCR_NumberReader.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace OCR{ - - -std::string run_number_normalization(const std::string& input){ - static const std::map SUBSTITUTION_TABLE{ - {'0', '0'}, - {'1', '1'}, - {'2', '2'}, - {'3', '3'}, - {'4', '4'}, - {'5', '5'}, - {'6', '6'}, - {'7', '7'}, - {'8', '8'}, - {'9', '9'}, - - // Common misreads. - {'|', '1'}, - {']', '1'}, - {'l', '1'}, - {'i', '1'}, - {'A', '4'}, - {'a', '4'}, - {'S', '5'}, - {'s', '5'}, - {'/', '7'}, - {'g', '9'}, - - // Japanese OCR likes to do this. - {U'🄋', '0'}, - {U'①', '1'}, - {U'②', '2'}, - {U'③', '3'}, - {U'④', '4'}, - {U'⑤', '5'}, - {U'⑥', '6'}, - {U'⑦', '7'}, - {U'⑧', '8'}, - {U'⑨', '9'}, - }; - - std::string normalized; - for (char32_t ch : to_utf32(input)){ - auto iter = SUBSTITUTION_TABLE.find(ch); - if (iter == SUBSTITUTION_TABLE.end()){ - continue; - } - normalized += iter->second; - } - - return normalized; -} - - -int read_number(Logger& logger, const ImageViewRGB32& image, Language language){ - std::string ocr_text = OCR::ocr_read(language, image); - std::string normalized = run_number_normalization(ocr_text); - - std::string str; - for (char ch : ocr_text){ - if (ch != '\r' && ch != '\n'){ - str += ch; - } - } - - if (normalized.empty()){ - logger.log("OCR Text: \"" + str + "\" -> \"" + normalized + "\" -> Unable to read.", COLOR_RED); - return -1; - } - - int number = std::atoi(normalized.c_str()); - logger.log("OCR Text: \"" + str + "\" -> \"" + normalized + "\" -> " + std::to_string(number)); - - return number; -} - -int read_number_waterfill( - Logger& logger, const ImageViewRGB32& image, - uint32_t rgb32_min, uint32_t rgb32_max, - bool text_inside_range, - int8_t line_index -){ - std::string ocr_text = read_number_waterfill_no_normalization(logger, image, rgb32_min, rgb32_max, text_inside_range, UINT32_MAX, false); - - std::string normalized = run_number_normalization(ocr_text); - - std::string line_index_str = ""; - if (line_index != -1){ - line_index_str = "Line " + std::to_string(line_index) + ": "; - } - if (normalized.empty()){ - logger.log(line_index_str + "OCR Text: \"" + ocr_text + "\" -> \"" + normalized + "\" -> Unable to read.", COLOR_RED); - return -1; - } - - int number = std::atoi(normalized.c_str()); - logger.log(line_index_str + "OCR Text: \"" + ocr_text + "\" -> \"" + normalized + "\" -> " + std::to_string(number)); - - return number; -} - - -std::string read_number_waterfill_no_normalization( - Logger& logger, const ImageViewRGB32& image, - uint32_t rgb32_min, uint32_t rgb32_max, - bool text_inside_range, - uint32_t width_max, - bool check_empty_string -){ - using namespace Kernels::Waterfill; - - // Direct OCR is unreliable. Instead, we will waterfill each character - // to isolate them, then OCR them individually. - - ImageRGB32 filtered = to_blackwhite_rgb32_range( - image, - text_inside_range, - rgb32_min, rgb32_max - ); - -// static int c = 0; -// filtered.save("zztest-" + std::to_string(c++) + ".png"); -// int i = 0; - - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(filtered, 0xff000000, 0xff7f7f7f); - - std::map map; - { - std::unique_ptr session = make_WaterfillSession(matrix); - auto iter = session->make_iterator(20); - WaterfillObject object; - while (map.size() < 16 && iter->find_next(object, true)){ - if (object.width() > width_max){ - logger.log("OCR fail: one of characters exceeded max width.", COLOR_RED); - return ""; - } - map.emplace(object.min_x, std::move(object)); - } - } - - std::string ocr_text; - for (const auto& item : map){ - const WaterfillObject& object = item.second; - ImageRGB32 cropped = extract_box_reference(filtered, object).copy(); - PackedBinaryMatrix tmp(object.packed_matrix()); - filter_by_mask(tmp, cropped, Color(0xffffffff), true); - ImageRGB32 padded = pad_image(cropped, cropped.width(), 0xffffffff); - std::string ocr = OCR::ocr_read(Language::English, padded); - // padded.save("zztest-cropped" + std::to_string(c) + "-" + std::to_string(i++) + ".png"); - // std::cout << ocr[0] << std::endl; - if (!ocr.empty()){ - ocr_text += ocr[0]; - }else{ - if (check_empty_string){ - logger.log("OCR fail: one of characters read as empty string.", COLOR_RED); - return ""; - } - } - } - - return ocr_text; - -} - -bool is_digits(const std::string &str) -{ - return std::all_of(str.begin(), str.end(), ::isdigit); -} - -int read_number_waterfill_multifilter( - Logger& logger, const ImageViewRGB32& image, - std::vector> filters, - uint32_t width_max, - bool text_inside_range, - bool prioritize_numeric_only_results, - int8_t line_index -){ - std::string line_index_str = ""; - if (line_index != -1){ - line_index_str = "Line " + std::to_string(line_index) + ": "; - } - - std::map candidates; - for (std::pair filter : filters){ - - uint32_t rgb32_min = filter.first; - uint32_t rgb32_max = filter.second; - std::string ocr_text = read_number_waterfill_no_normalization(logger, image, rgb32_min, rgb32_max, text_inside_range, width_max, true); - - std::string normalized = run_number_normalization(ocr_text); - if (normalized.empty()){ - // logger.log("OCR Text: \"" + ocr_text + "\" -> \"" + normalized + "\" -> Unable to read.", COLOR_RED); - continue; - } - - int candidate = std::atoi(normalized.c_str()); - logger.log(line_index_str + "OCR Text: \"" + ocr_text + "\" -> \"" + normalized + "\" -> " + std::to_string(candidate)); - - if (prioritize_numeric_only_results && is_digits(ocr_text)){ - candidates[candidate] += 2; - }else{ - candidates[candidate]++; - } - } - - if (candidates.empty()){ - logger.log(line_index_str + "No valid OCR candidates. Unable to read number.", COLOR_ORANGE); - return -1; - } - - std::pair best; - for (const auto& item : candidates){ - logger.log(line_index_str + "Candidate " + std::to_string(item.first) + ": " + std::to_string(item.second) + " votes"); - if (item.second > best.second){ - best = item; - } - } - - logger.log(line_index_str + "Best candidate: --------------------------> " + std::to_string(best.first)); - return best.first; -} - - - - -} -} +/* OCR Number Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Qt/StringToolsQt.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonFramework/Language.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/Tools/GlobalThreadPools.h" +#include "CommonTools/Images/ImageManip.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "OCR_RawOCR.h" +#include "OCR_NumberReader.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace OCR{ + + +std::string run_number_normalization(const std::string& input){ + static const std::map SUBSTITUTION_TABLE{ + {'0', '0'}, + {'1', '1'}, + {'2', '2'}, + {'3', '3'}, + {'4', '4'}, + {'5', '5'}, + {'6', '6'}, + {'7', '7'}, + {'8', '8'}, + {'9', '9'}, + + // Common misreads. + {'|', '1'}, + {']', '1'}, + {'l', '1'}, + {'i', '1'}, + {'A', '4'}, + {'a', '4'}, + {'S', '5'}, + {'s', '5'}, + {'/', '7'}, + {'g', '9'}, + + // Japanese OCR likes to do this. + {U'🄋', '0'}, + {U'①', '1'}, + {U'②', '2'}, + {U'③', '3'}, + {U'④', '4'}, + {U'⑤', '5'}, + {U'⑥', '6'}, + {U'⑦', '7'}, + {U'⑧', '8'}, + {U'⑨', '9'}, + }; + + std::string normalized; + for (char32_t ch : to_utf32(input)){ + auto iter = SUBSTITUTION_TABLE.find(ch); + if (iter == SUBSTITUTION_TABLE.end()){ + continue; + } + normalized += iter->second; + } + + return normalized; +} + + +int read_number(Logger& logger, const ImageViewRGB32& image, Language language){ + std::string ocr_text = OCR::ocr_read(language, image); + std::string normalized = run_number_normalization(ocr_text); + + std::string str; + for (char ch : ocr_text){ + if (ch != '\r' && ch != '\n'){ + str += ch; + } + } + + if (normalized.empty()){ + logger.log("OCR Text: \"" + str + "\" -> \"" + normalized + "\" -> Unable to read.", COLOR_RED); + return -1; + } + + int number = std::atoi(normalized.c_str()); + logger.log("OCR Text: \"" + str + "\" -> \"" + normalized + "\" -> " + std::to_string(number)); + + return number; +} + +int read_number_waterfill( + Logger& logger, const ImageViewRGB32& image, + uint32_t rgb32_min, uint32_t rgb32_max, + bool text_inside_range, + int8_t line_index +){ + std::string ocr_text = read_number_waterfill_no_normalization( + logger, + image, + rgb32_min, rgb32_max, + text_inside_range + ); + + std::string normalized = run_number_normalization(ocr_text); + + std::string line_index_str = ""; + if (line_index != -1){ + line_index_str = "Line " + std::to_string(line_index) + ": "; + } + if (normalized.empty()){ + logger.log(line_index_str + "OCR Text: \"" + ocr_text + "\" -> \"" + normalized + "\" -> Unable to read.", COLOR_RED); + return -1; + } + + int number = std::atoi(normalized.c_str()); + logger.log(line_index_str + "OCR Text: \"" + ocr_text + "\" -> \"" + normalized + "\" -> " + std::to_string(number)); + + return number; +} + + +std::string read_number_waterfill_no_normalization( + Logger& logger, const ImageViewRGB32& image, + uint32_t rgb32_min, uint32_t rgb32_max, + bool text_inside_range, + size_t width_max, + bool check_empty_string +){ + using namespace Kernels::Waterfill; + + // Direct OCR is unreliable. Instead, we will waterfill each character + // to isolate them, then OCR them individually. + + ImageRGB32 filtered = to_blackwhite_rgb32_range( + image, + text_inside_range, + rgb32_min, rgb32_max + ); + +// static int c = 0; +// filtered.save("zztest-" + std::to_string(c++) + ".png"); +// int i = 0; + + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(filtered, 0xff000000, 0xff7f7f7f); + + std::map map; + { + std::unique_ptr session = make_WaterfillSession(matrix); + auto iter = session->make_iterator(20); + WaterfillObject object; + while (map.size() < 16 && iter->find_next(object, true)){ + if (object.width() > width_max){ + logger.log("OCR fail: one of characters exceeded max width.", COLOR_RED); + return ""; + } + map.emplace(object.min_x, std::move(object)); + } + } + + std::string ocr_text; + for (const auto& item : map){ + const WaterfillObject& object = item.second; + ImageRGB32 cropped = extract_box_reference(filtered, object).copy(); + PackedBinaryMatrix tmp(object.packed_matrix()); + filter_by_mask(tmp, cropped, Color(0xffffffff), true); + + // Tesseract doesn't like numbers that are too big. So scale it down. +// cout << "height = " << cropped.height() << endl; + if (cropped.height() > 60){ + cropped = cropped.scale_to(cropped.width() * 60 / cropped.height(), 60); + } + + ImageRGB32 padded = pad_image(cropped, 1 * cropped.width(), 0xffffffff); + std::string ocr = OCR::ocr_read(Language::English, padded); + +// padded.save("zztest-cropped" + std::to_string(c) + "-" + std::to_string(i++) + ".png"); + // std::cout << ocr[0] << std::endl; + if (!ocr.empty()){ + ocr_text += ocr[0]; + }else{ + if (check_empty_string){ + logger.log("OCR fail: one of characters read as empty string.", COLOR_RED); + return ""; + } + } + } + + return ocr_text; + +} + +bool is_digits(const std::string &str) +{ + return std::all_of(str.begin(), str.end(), ::isdigit); +} + +int read_number_waterfill_multifilter( + Logger& logger, const ImageViewRGB32& image, + std::vector> filters, + size_t width_max, + bool text_inside_range, + bool prioritize_numeric_only_results, + int8_t line_index +){ + std::string line_index_str = ""; + if (line_index != -1){ + line_index_str = "Line " + std::to_string(line_index) + ": "; + } + + SpinLock lock; + std::map candidates; + GlobalThreadPools::normal_inference().run_in_parallel( + [&](size_t index){ + std::pair filter = filters[index]; + + uint32_t rgb32_min = filter.first; + uint32_t rgb32_max = filter.second; + std::string ocr_text = read_number_waterfill_no_normalization( + logger, + image, + rgb32_min, rgb32_max, + text_inside_range, + width_max, + true + ); + + std::string normalized = run_number_normalization(ocr_text); + if (normalized.empty()){ + // logger.log("OCR Text: \"" + ocr_text + "\" -> \"" + normalized + "\" -> Unable to read.", COLOR_RED); + return; + } + + int candidate = std::atoi(normalized.c_str()); + logger.log(line_index_str + "OCR Text: \"" + ocr_text + "\" -> \"" + normalized + "\" -> " + std::to_string(candidate)); + + uint8_t weight = prioritize_numeric_only_results && is_digits(ocr_text) + ? 2 + : 1; + + WriteSpinLock lg(lock); + candidates[candidate] += weight; + + }, + 0, filters.size(), 1 + ); + + if (candidates.empty()){ + logger.log(line_index_str + "No valid OCR candidates. Unable to read number.", COLOR_ORANGE); + return -1; + } + + std::pair best; + for (const auto& item : candidates){ + logger.log(line_index_str + "Candidate " + std::to_string(item.first) + ": " + std::to_string(item.second) + " votes"); + if (item.second > best.second){ + best = item; + } + } + + logger.log(line_index_str + "Best candidate: --------------------------> " + std::to_string(best.first)); + return best.first; +} + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_NumberReader.h b/SerialPrograms/Source/CommonTools/OCR/OCR_NumberReader.h index bc22ce6b2f..3c841dbd96 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_NumberReader.h +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_NumberReader.h @@ -1,73 +1,73 @@ -/* OCR Number Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_OCR_NumberReader_H -#define PokemonAutomation_CommonTools_OCR_NumberReader_H - -#include -#include -#include "CommonFramework/Language.h" - -namespace PokemonAutomation{ - class Logger; - class ImageViewRGB32; -namespace OCR{ - - -// Returns -1 if no number is found. -// No processing is done on the image. It is OCR'ed directly. -// The best way to use read_number() is to not give Language as a parameter. -// This is because the default language is English, since it works best for OCR for numbers. -int read_number(Logger& logger, const ImageViewRGB32& image, Language language = Language::English); - - -// This version attempts to improve reliability by first isolating each number -// via waterfill. Then it OCRs each number by itself and recombines them at the -// end. This requires specifying the color range for the text. -// -// line_index: specifies the current number's row. for logging purposes, when multithreaded. -int read_number_waterfill( - Logger& logger, const ImageViewRGB32& image, - uint32_t rgb32_min, uint32_t rgb32_max, - bool text_inside_range = true, - int8_t line_index = -1 - ); - -// run OCR on each individual character in the string of numbers. -// return empty string if OCR fails -// -// text_inside_range: binary filter is applied to the image so that any pixels within the color range will be turned black, and everything else will be white -// width_max: return empty string if any character's width is greater than width_max (likely means that two characters are touching, and so are treated as one large character) -// check_empty_string: if set to true, return empty string (and stop evaluation) if any character returns an empty string from OCR - std::string read_number_waterfill_no_normalization( - Logger& logger, const ImageViewRGB32& image, - uint32_t rgb32_min, uint32_t rgb32_max, - bool text_inside_range = true, - uint32_t width_max = UINT32_MAX, - bool check_empty_string = false - ); - -// Try OCR with all the given color filters. still running OCR on each individual character -// Return the best majority candidate. return -1 if failed to read. -// -// prioritize_numeric_only_results: -// - if true: if OCR reads only numeric characters, the candidate gets 2 votes. If OCR reads non-numeric characters, the candidate gets only 1 vote. -// - if false: all reads only get 1 vote -// -// line_index: specifies the current number's row. for logging purposes, when multithreaded. -int read_number_waterfill_multifilter( - Logger& logger, const ImageViewRGB32& image, - std::vector> filters, - uint32_t width_max, - bool text_inside_range = true, - bool prioritize_numeric_only_results = true, - int8_t line_index = -1 - ); - - -} -} -#endif +/* OCR Number Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_OCR_NumberReader_H +#define PokemonAutomation_CommonTools_OCR_NumberReader_H + +#include +#include +#include "CommonFramework/Language.h" + +namespace PokemonAutomation{ + class Logger; + class ImageViewRGB32; +namespace OCR{ + + +// Returns -1 if no number is found. +// No processing is done on the image. It is OCR'ed directly. +// The best way to use read_number() is to not give Language as a parameter. +// This is because the default language is English, since it works best for OCR for numbers. +int read_number(Logger& logger, const ImageViewRGB32& image, Language language = Language::English); + + +// This version attempts to improve reliability by first isolating each number +// via waterfill. Then it OCRs each number by itself and recombines them at the +// end. This requires specifying the color range for the text. +// +// line_index: specifies the current number's row. for logging purposes, when multithreaded. +int read_number_waterfill( + Logger& logger, const ImageViewRGB32& image, + uint32_t rgb32_min, uint32_t rgb32_max, + bool text_inside_range = true, + int8_t line_index = -1 + ); + +// run OCR on each individual character in the string of numbers. +// return empty string if OCR fails +// +// text_inside_range: binary filter is applied to the image so that any pixels within the color range will be turned black, and everything else will be white +// width_max: return empty string if any character's width is greater than width_max (likely means that two characters are touching, and so are treated as one large character) +// check_empty_string: if set to true, return empty string (and stop evaluation) if any character returns an empty string from OCR + std::string read_number_waterfill_no_normalization( + Logger& logger, const ImageViewRGB32& image, + uint32_t rgb32_min, uint32_t rgb32_max, + bool text_inside_range = true, + size_t width_max = (size_t)-1, + bool check_empty_string = false + ); + +// Try OCR with all the given color filters. still running OCR on each individual character +// Return the best majority candidate. return -1 if failed to read. +// +// prioritize_numeric_only_results: +// - if true: if OCR reads only numeric characters, the candidate gets 2 votes. If OCR reads non-numeric characters, the candidate gets only 1 vote. +// - if false: all reads only get 1 vote +// +// line_index: specifies the current number's row. for logging purposes, when multithreaded. +int read_number_waterfill_multifilter( + Logger& logger, const ImageViewRGB32& image, + std::vector> filters, + size_t width_max = (size_t)-1, + bool text_inside_range = true, + bool prioritize_numeric_only_results = true, + int8_t line_index = -1 + ); + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_RawOCR.cpp b/SerialPrograms/Source/CommonTools/OCR/OCR_RawOCR.cpp index 95cc5bf17d..bb3a72505b 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_RawOCR.cpp +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_RawOCR.cpp @@ -1,205 +1,205 @@ -/* Raw Text Recognition - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "3rdParty/TesseractPA/TesseractPA.h" -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "OCR_RawOCR.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace OCR{ - - - - -bool language_available(Language language){ - std::string path = RESOURCE_PATH(); - path += "Tesseract/"; - path += language_data(language).code; - path += ".traineddata"; - QFile file(QString::fromStdString(path)); - return file.exists(); -} - - - -class TesseractPool{ -public: - TesseractPool(Language language) - : m_language_code(language_data(language).code) - , m_training_data_path( - QDir::current().relativeFilePath(QString::fromStdString(RESOURCE_PATH() + "Tesseract/")).toStdString() - ) - {} - - std::string run(const ImageViewRGB32& image){ - TesseractAPI* instance; - while (true){ - { - WriteSpinLock lg(m_lock, "TesseractPool::run()"); - if (!m_idle.empty()){ - instance = m_idle.back(); - m_idle.pop_back(); - break; - } - } - add_instance(); - } - -// auto start = current_time(); - TesseractString str = instance->read32( - (const unsigned char*)image.data(), - image.width(), - image.height(), - image.bytes_per_row() - ); -// auto end = current_time(); -// cout << std::chrono::duration_cast(end - start).count() << endl; - - { - WriteSpinLock lg(m_lock, "TesseractPool::run()"); - m_idle.emplace_back(instance); - } - - return str.c_str() == nullptr - ? std::string() - : str.c_str(); - } - - void add_instance(){ - // Check for non-ascii characters in path. - for (char ch : m_training_data_path){ - if (ch < 0){ - throw InternalSystemError( - nullptr, PA_CURRENT_FUNCTION, - "Detected non-ASCII character in Tesseract path. Please move the program to a path with only ASCII characters." - ); - } - } - - global_logger_tagged().log( - "Initializing TesseractAPI (" + m_language_code + "): " + m_training_data_path - ); - std::unique_ptr api( - new TesseractAPI(m_training_data_path.c_str(), m_language_code.c_str()) - ); - if (!api->valid()){ - throw InternalSystemError(nullptr, PA_CURRENT_FUNCTION, "Could not initialize TesseractAPI."); - } - - WriteSpinLock lg(m_lock, "TesseractPool::run()"); - - m_instances.emplace_back(std::move(api)); - try{ - m_idle.emplace_back(m_instances.back().get()); - }catch (...){ - m_instances.pop_back(); - throw; - } - } - - void ensure_instances(size_t instances){ - size_t current_instances; - while (true){ - { - ReadSpinLock lg(m_lock, "TesseractPool::run()"); - current_instances = m_instances.size(); - } - if (current_instances >= instances){ - break; - } - add_instance(); - } - } - -#ifdef __APPLE__ -#ifdef UNIX_LINK_TESSERACT - ~TesseractPool(){ - // As of Feb 05, 2022, the newest Tesseract (5.0.1) installed by HomeBrew on macOS - // has a bug that will crash the program when deleting internal Tesseract API instances, - // giving error: - // libc++abi.dylib: terminating with uncaught exception of type std::__1::system_error: mutex lock failed: Invalid argument - // A similar issue is posted on Tesseract Github: https://github.com/tesseract-ocr/tesseract/issues/3655 - // There is no way of using HomeBrew to reinstall the older version. - // Fortunately this class TesseractPool will not get built and destroyed repeatedly in - // runtime. It will only get initialized once for each supported language. So I am able - // to use this ugly workaround by not deleting the Tesseract API instances. - std::cout << "Warning: not release Tesseract API instance due to mutex bug similar to https://github.com/tesseract-ocr/tesseract/issues/3655" << std::endl; - for(auto& api : m_instances){ - api.release(); - } - } -#endif -#endif - -private: - const std::string& m_language_code; - const std::string m_training_data_path; - - SpinLock m_lock; - std::vector> m_instances; - std::vector m_idle; -}; - -SpinLock ocr_pool_lock; -std::map ocr_pool; - - -std::string ocr_read(Language language, const ImageViewRGB32& image){ -// static size_t c = 0; -// image.save("ocr-" + std::to_string(c++) + ".png"); - - if (language == Language::None){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to call OCR without a language."); - } - - std::map::iterator iter; - { - WriteSpinLock lg(ocr_pool_lock, "ocr_read()"); - iter = ocr_pool.find(language); - if (iter == ocr_pool.end()){ - iter = ocr_pool.emplace(language, language).first; - } - } - return iter->second.run(image); -} -void ensure_instances(Language language, size_t instances){ - if (language == Language::None){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to call OCR without a language."); - } - - std::map::iterator iter; - { - WriteSpinLock lg(ocr_pool_lock, "ocr_read()"); - iter = ocr_pool.find(language); - if (iter == ocr_pool.end()){ - iter = ocr_pool.emplace(language, language).first; - } - } - iter->second.ensure_instances(instances); -} - - - - - -} -} - - - - +/* Raw Text Recognition + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "3rdParty/TesseractPA/TesseractPA.h" +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "OCR_RawOCR.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace OCR{ + + + + +bool language_available(Language language){ + std::string path = RESOURCE_PATH(); + path += "Tesseract/"; + path += language_data(language).code; + path += ".traineddata"; + QFile file(QString::fromStdString(path)); + return file.exists(); +} + + + +class TesseractPool{ +public: + TesseractPool(Language language) + : m_language_code(language_data(language).code) + , m_training_data_path( + QDir::current().relativeFilePath(QString::fromStdString(RESOURCE_PATH() + "Tesseract/")).toStdString() + ) + {} + + std::string run(const ImageViewRGB32& image){ + TesseractAPI* instance; + while (true){ + { + WriteSpinLock lg(m_lock, "TesseractPool::run()"); + if (!m_idle.empty()){ + instance = m_idle.back(); + m_idle.pop_back(); + break; + } + } + add_instance(); + } + +// auto start = current_time(); + TesseractString str = instance->read32( + (const unsigned char*)image.data(), + image.width(), + image.height(), + image.bytes_per_row() + ); +// auto end = current_time(); +// cout << std::chrono::duration_cast(end - start).count() << endl; + + { + WriteSpinLock lg(m_lock, "TesseractPool::run()"); + m_idle.emplace_back(instance); + } + + return str.c_str() == nullptr + ? std::string() + : str.c_str(); + } + + void add_instance(){ + // Check for non-ascii characters in path. + for (char ch : m_training_data_path){ + if (ch < 0){ + throw InternalSystemError( + nullptr, PA_CURRENT_FUNCTION, + "Detected non-ASCII character in Tesseract path. Please move the program to a path with only ASCII characters." + ); + } + } + + global_logger_tagged().log( + "Initializing TesseractAPI (" + m_language_code + "): " + m_training_data_path + ); + std::unique_ptr api( + new TesseractAPI(m_training_data_path.c_str(), m_language_code.c_str()) + ); + if (!api->valid()){ + throw InternalSystemError(nullptr, PA_CURRENT_FUNCTION, "Could not initialize TesseractAPI."); + } + + WriteSpinLock lg(m_lock, "TesseractPool::run()"); + + m_instances.emplace_back(std::move(api)); + try{ + m_idle.emplace_back(m_instances.back().get()); + }catch (...){ + m_instances.pop_back(); + throw; + } + } + + void ensure_instances(size_t instances){ + size_t current_instances; + while (true){ + { + ReadSpinLock lg(m_lock, "TesseractPool::run()"); + current_instances = m_instances.size(); + } + if (current_instances >= instances){ + break; + } + add_instance(); + } + } + +#ifdef __APPLE__ +#ifdef UNIX_LINK_TESSERACT + ~TesseractPool(){ + // As of Feb 05, 2022, the newest Tesseract (5.0.1) installed by HomeBrew on macOS + // has a bug that will crash the program when deleting internal Tesseract API instances, + // giving error: + // libc++abi.dylib: terminating with uncaught exception of type std::__1::system_error: mutex lock failed: Invalid argument + // A similar issue is posted on Tesseract Github: https://github.com/tesseract-ocr/tesseract/issues/3655 + // There is no way of using HomeBrew to reinstall the older version. + // Fortunately this class TesseractPool will not get built and destroyed repeatedly in + // runtime. It will only get initialized once for each supported language. So I am able + // to use this ugly workaround by not deleting the Tesseract API instances. + std::cout << "Warning: not release Tesseract API instance due to mutex bug similar to https://github.com/tesseract-ocr/tesseract/issues/3655" << std::endl; + for(auto& api : m_instances){ + api.release(); + } + } +#endif +#endif + +private: + const std::string& m_language_code; + const std::string m_training_data_path; + + SpinLock m_lock; + std::vector> m_instances; + std::vector m_idle; +}; + +SpinLock ocr_pool_lock; +std::map ocr_pool; + + +std::string ocr_read(Language language, const ImageViewRGB32& image){ +// static size_t c = 0; +// image.save("ocr-" + std::to_string(c++) + ".png"); + + if (language == Language::None){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to call OCR without a language."); + } + + std::map::iterator iter; + { + WriteSpinLock lg(ocr_pool_lock, "ocr_read()"); + iter = ocr_pool.find(language); + if (iter == ocr_pool.end()){ + iter = ocr_pool.emplace(language, language).first; + } + } + return iter->second.run(image); +} +void ensure_instances(Language language, size_t instances){ + if (language == Language::None){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to call OCR without a language."); + } + + std::map::iterator iter; + { + WriteSpinLock lg(ocr_pool_lock, "ocr_read()"); + iter = ocr_pool.find(language); + if (iter == ocr_pool.end()){ + iter = ocr_pool.emplace(language, language).first; + } + } + iter->second.ensure_instances(instances); +} + + + + + +} +} + + + + diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_RawOCR.h b/SerialPrograms/Source/CommonTools/OCR/OCR_RawOCR.h index 1ab62f7ec1..4f1d2421a6 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_RawOCR.h +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_RawOCR.h @@ -1,32 +1,32 @@ -/* Raw Text Recognition - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_OCR_RawOCR_H -#define PokemonAutomation_CommonTools_OCR_RawOCR_H - -#include -#include "CommonFramework/Language.h" - -namespace PokemonAutomation{ - class ImageViewRGB32; -namespace OCR{ - - -bool language_available(Language language); - - -// OCR the image in the specified language. -std::string ocr_read(Language language, const ImageViewRGB32& image); - -// Ensure that there are this many parallel instances for this language. -// Call this if you expect to need to do many OCR instances in parallel and you -// want to preload the OCR instances. -void ensure_instances(Language language, size_t instances); - - -} -} -#endif +/* Raw Text Recognition + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_OCR_RawOCR_H +#define PokemonAutomation_CommonTools_OCR_RawOCR_H + +#include +#include "CommonFramework/Language.h" + +namespace PokemonAutomation{ + class ImageViewRGB32; +namespace OCR{ + + +bool language_available(Language language); + + +// OCR the image in the specified language. +std::string ocr_read(Language language, const ImageViewRGB32& image); + +// Ensure that there are this many parallel instances for this language. +// Call this if you expect to need to do many OCR instances in parallel and you +// want to preload the OCR instances. +void ensure_instances(Language language, size_t instances); + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_Routines.cpp b/SerialPrograms/Source/CommonTools/OCR/OCR_Routines.cpp index 24b8b05ac6..da4c2298e4 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_Routines.cpp +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_Routines.cpp @@ -1,119 +1,131 @@ -/* OCR Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonTools/Images/ImageFilter.h" -#include "OCR_RawOCR.h" -#include "OCR_DictionaryMatcher.h" -#include "OCR_Routines.h" - -namespace PokemonAutomation{ -namespace OCR{ - - -StringMatchResult multifiltered_OCR( - Language language, const DictionaryMatcher& dictionary, const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double log10p_spread, - double min_text_ratio, double max_text_ratio -){ - if (image.width() == 0 || image.height() == 0){ - return StringMatchResult(); - } - - std::vector bw_filters; - for (const auto& range : text_color_ranges){ - bw_filters.emplace_back( - BlackWhiteRgb32Range{true, range.mins, range.maxs} - ); - } - std::vector> filtered_images = to_blackwhite_rgb32_range(image, bw_filters); - - double pixels_inv = 1. / (image.width() * image.height()); - - // Run all the filters. - StringMatchResult ret; -// int c = 0; - for (const auto& filtered : filtered_images){ - std::string text = ocr_read(language, filtered.first); -// cout << text.toStdString() << endl; -// filtered.first.save("test" + QString::number(c++) + ".png"); - - // Compute ratio of image that matches text color. Skip if it's out of range. - double ratio = filtered.second * pixels_inv; -// cout << "ratio = " << ratio << endl; - if (ratio < min_text_ratio || ratio > max_text_ratio){ - continue; - } - - StringMatchResult current = dictionary.match_substring(language, text, log10p_spread); - ret.exact_match |= current.exact_match; - ret.results.insert(current.results.begin(), current.results.end()); - } - -// ret.log(global_logger_tagged(), -1.5); - - // Prune duplicates. - std::set tokens; - for (auto iter = ret.results.begin(); iter != ret.results.end();){ - if (tokens.find(iter->second.token) == tokens.end()){ - tokens.insert(iter->second.token); - ++iter; - }else{ - iter = ret.results.erase(iter); - } - } - - ret.clear_beyond_spread(log10p_spread); - return ret; -} - - - -const std::vector& BLACK_TEXT_FILTERS(){ - static std::vector filters{ - {0xff000000, 0xff404040}, - {0xff000000, 0xff606060}, - {0xff000000, 0xff808080}, - }; - return filters; -} -const std::vector& WHITE_TEXT_FILTERS(){ - static std::vector filters{ - {0xff808080, 0xffffffff}, - {0xffa0a0a0, 0xffffffff}, - {0xffc0c0c0, 0xffffffff}, - }; - return filters; -} -const std::vector& BLACK_OR_WHITE_TEXT_FILTERS(){ - static std::vector filters{ - {0xff000000, 0xff404040}, - {0xff000000, 0xff606060}, - {0xff000000, 0xff808080}, - {0xff808080, 0xffffffff}, - {0xffa0a0a0, 0xffffffff}, - }; - return filters; -} -const std::vector& BLUE_TEXT_FILTERS(){ - static std::vector filters{ - {0xFF3287A2, 0xFFA7F4FF}, - {0xFF2283A2, 0xFF8EF1FF}, - {0xFF428BA2, 0xFFC1F7FF}, - }; - return filters; -} - - - - - - - - -} -} +/* OCR Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/Tools/GlobalThreadPools.h" +#include "CommonTools/Images/ImageFilter.h" +#include "OCR_RawOCR.h" +#include "OCR_DictionaryMatcher.h" +#include "OCR_Routines.h" + +namespace PokemonAutomation{ +namespace OCR{ + + +StringMatchResult multifiltered_OCR( + Language language, const DictionaryMatcher& dictionary, const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double log10p_spread, + double min_text_ratio, double max_text_ratio +){ + if (image.width() == 0 || image.height() == 0){ + return StringMatchResult(); + } + + std::vector bw_filters; + for (const auto& range : text_color_ranges){ + bw_filters.emplace_back( + BlackWhiteRgb32Range{true, range.mins, range.maxs} + ); + } + std::vector> filtered_images = to_blackwhite_rgb32_range(image, bw_filters); + + double pixels_inv = 1. / (image.width() * image.height()); + + // Run all the filters. + SpinLock lock; + StringMatchResult ret; + GlobalThreadPools::normal_inference().run_in_parallel( + [&](size_t index){ + const std::pair& filtered = filtered_images[index]; + + std::string text = ocr_read(language, filtered.first); +// cout << text.toStdString() << endl; +// filtered.first.save("test" + QString::number(c++) + ".png"); + + // Compute ratio of image that matches text color. Skip if it's out of range. + double ratio = filtered.second * pixels_inv; +// cout << "ratio = " << ratio << endl; + if (ratio < min_text_ratio || ratio > max_text_ratio){ + return; + } + + StringMatchResult current = dictionary.match_substring(language, text, log10p_spread); + + WriteSpinLock lg(lock); + ret.exact_match |= current.exact_match; + ret.results.insert(current.results.begin(), current.results.end()); + + }, + 0, filtered_images.size(), 1 + ); +// int c = 0; +// for (const auto& filtered : filtered_images){ +// } + +// ret.log(global_logger_tagged(), -1.5); + + // Prune duplicates. + std::set tokens; + for (auto iter = ret.results.begin(); iter != ret.results.end();){ + if (tokens.find(iter->second.token) == tokens.end()){ + tokens.insert(iter->second.token); + ++iter; + }else{ + iter = ret.results.erase(iter); + } + } + + ret.clear_beyond_spread(log10p_spread); + return ret; +} + + + +const std::vector& BLACK_TEXT_FILTERS(){ + static std::vector filters{ + {0xff000000, 0xff404040}, + {0xff000000, 0xff606060}, + {0xff000000, 0xff808080}, + }; + return filters; +} +const std::vector& WHITE_TEXT_FILTERS(){ + static std::vector filters{ + {0xff808080, 0xffffffff}, + {0xffa0a0a0, 0xffffffff}, + {0xffc0c0c0, 0xffffffff}, + }; + return filters; +} +const std::vector& BLACK_OR_WHITE_TEXT_FILTERS(){ + static std::vector filters{ + {0xff000000, 0xff404040}, + {0xff000000, 0xff606060}, + {0xff000000, 0xff808080}, + {0xff808080, 0xffffffff}, + {0xffa0a0a0, 0xffffffff}, + }; + return filters; +} +const std::vector& BLUE_TEXT_FILTERS(){ + static std::vector filters{ + {0xFF3287A2, 0xFFA7F4FF}, + {0xFF2283A2, 0xFF8EF1FF}, + {0xFF428BA2, 0xFFC1F7FF}, + }; + return filters; +} + + + + + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_Routines.h b/SerialPrograms/Source/CommonTools/OCR/OCR_Routines.h index 60c7ba851e..6023598883 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_Routines.h +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_Routines.h @@ -1,51 +1,51 @@ -/* OCR Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_OCR_Routines_H -#define PokemonAutomation_CommonTools_OCR_Routines_H - -#include -#include -#include "CommonFramework/Language.h" - -namespace PokemonAutomation{ - class ImageViewRGB32; -namespace OCR{ - -struct StringMatchResult; -class DictionaryMatcher; - - - -struct TextColorRange{ - uint32_t mins; - uint32_t maxs; - - TextColorRange(uint32_t p_mins, uint32_t p_maxs) - : mins(p_mins) - , maxs(p_maxs) - {} -}; - - -StringMatchResult multifiltered_OCR( - Language language, const DictionaryMatcher& dictionary, const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double log10p_spread, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 -); - - -const std::vector& BLACK_TEXT_FILTERS(); -const std::vector& WHITE_TEXT_FILTERS(); -const std::vector& BLACK_OR_WHITE_TEXT_FILTERS(); -const std::vector& BLUE_TEXT_FILTERS(); - - - -} -} -#endif +/* OCR Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_OCR_Routines_H +#define PokemonAutomation_CommonTools_OCR_Routines_H + +#include +#include +#include "CommonFramework/Language.h" + +namespace PokemonAutomation{ + class ImageViewRGB32; +namespace OCR{ + +struct StringMatchResult; +class DictionaryMatcher; + + + +struct TextColorRange{ + uint32_t mins; + uint32_t maxs; + + TextColorRange(uint32_t p_mins, uint32_t p_maxs) + : mins(p_mins) + , maxs(p_maxs) + {} +}; + + +StringMatchResult multifiltered_OCR( + Language language, const DictionaryMatcher& dictionary, const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double log10p_spread, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 +); + + +const std::vector& BLACK_TEXT_FILTERS(); +const std::vector& WHITE_TEXT_FILTERS(); +const std::vector& BLACK_OR_WHITE_TEXT_FILTERS(); +const std::vector& BLUE_TEXT_FILTERS(); + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_SmallDictionaryMatcher.cpp b/SerialPrograms/Source/CommonTools/OCR/OCR_SmallDictionaryMatcher.cpp index b78760aa4e..b077808809 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_SmallDictionaryMatcher.cpp +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_SmallDictionaryMatcher.cpp @@ -1,51 +1,51 @@ -/* Small Database Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "OCR_StringNormalization.h" -#include "OCR_TextMatcher.h" -#include "OCR_SmallDictionaryMatcher.h" - -namespace PokemonAutomation{ -namespace OCR{ - - - -SmallDictionaryMatcher::SmallDictionaryMatcher(const std::string& json_path, bool first_only) - : SmallDictionaryMatcher( - load_json_file(RESOURCE_PATH() + json_path).to_object_throw(), - first_only - ) -{} -SmallDictionaryMatcher::SmallDictionaryMatcher(const JsonObject& json, bool first_only){ - for (const auto& item : json){ - Language language = language_code_to_enum(item.first); - const LanguageData& data = language_data(language); - m_database.emplace( - std::piecewise_construct, - std::forward_as_tuple(language), - std::forward_as_tuple(item.second.to_object_throw(), nullptr, data.random_match_chance, first_only) - ); - m_languages += language; - } -} - - -void SmallDictionaryMatcher::save(const std::string& json_path) const{ - JsonObject root; - for (const auto& item : m_database){ - root[language_data(item.first).code] = item.second.to_json(); - } - root.dump(json_path); -} - - - -} -} +/* Small Database Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "OCR_StringNormalization.h" +#include "OCR_TextMatcher.h" +#include "OCR_SmallDictionaryMatcher.h" + +namespace PokemonAutomation{ +namespace OCR{ + + + +SmallDictionaryMatcher::SmallDictionaryMatcher(const std::string& json_path, bool first_only) + : SmallDictionaryMatcher( + load_json_file(RESOURCE_PATH() + json_path).to_object_throw(), + first_only + ) +{} +SmallDictionaryMatcher::SmallDictionaryMatcher(const JsonObject& json, bool first_only){ + for (const auto& item : json){ + Language language = language_code_to_enum(item.first); + const LanguageData& data = language_data(language); + m_database.emplace( + std::piecewise_construct, + std::forward_as_tuple(language), + std::forward_as_tuple(item.second.to_object_throw(), nullptr, data.random_match_chance, first_only) + ); + m_languages += language; + } +} + + +void SmallDictionaryMatcher::save(const std::string& json_path) const{ + JsonObject root; + for (const auto& item : m_database){ + root[language_data(item.first).code] = item.second.to_json(); + } + root.dump(json_path); +} + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_SmallDictionaryMatcher.h b/SerialPrograms/Source/CommonTools/OCR/OCR_SmallDictionaryMatcher.h index 3dbb7b1d6a..05ceebfdfd 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_SmallDictionaryMatcher.h +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_SmallDictionaryMatcher.h @@ -1,43 +1,43 @@ -/* Small Dictionary Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_OCR_SmallDictionaryMatcher_H -#define PokemonAutomation_CommonTools_OCR_SmallDictionaryMatcher_H - -#include "OCR_DictionaryMatcher.h" - -namespace PokemonAutomation{ - class JsonObject; -namespace OCR{ - -// An OCR matcher with a small dictionary. -// Since the dictionary is small, all languages of this dictionary are stored in -// the same JSON file. -class SmallDictionaryMatcher : public DictionaryMatcher{ -public: - // Load the JSON file to build the dictionary for all languages stored in the JSON. - // first_only: whether to use only the first value for each slug. - // This parameter is only useful for training the OCR. - // During inference, we set `first_only` to false so that each slug corresponds to - // all the values in that dictionary entry. - // e.g. if `first_only` is false, when loading Pokemon Abomasnow for traditional Chinese, - // "abomasnow": ["暴雪王", "繁霎王", "鬘粘王"], - // when OCR detects any of "暴雪王", "繁霎王" or "鬘粘王", the matcher returns Abomasnow. - // if 'first_only' is true, only when OCR detects "暴雪王" do the matcher return Abomasnow. - SmallDictionaryMatcher(const std::string& json_path, bool first_only = false); - // Load JSON object to build the dictionary for all languages stored in the JSON. - // See the comments of - // `SmallDictionaryMatcher(const std::string& json_path, bool first_only = false)` - // to konw the usage of `first_only`. - SmallDictionaryMatcher(const JsonObject& json, bool first_only = false); - - void save(const std::string& json_path) const; -}; - - -} -} -#endif +/* Small Dictionary Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_OCR_SmallDictionaryMatcher_H +#define PokemonAutomation_CommonTools_OCR_SmallDictionaryMatcher_H + +#include "OCR_DictionaryMatcher.h" + +namespace PokemonAutomation{ + class JsonObject; +namespace OCR{ + +// An OCR matcher with a small dictionary. +// Since the dictionary is small, all languages of this dictionary are stored in +// the same JSON file. +class SmallDictionaryMatcher : public DictionaryMatcher{ +public: + // Load the JSON file to build the dictionary for all languages stored in the JSON. + // first_only: whether to use only the first value for each slug. + // This parameter is only useful for training the OCR. + // During inference, we set `first_only` to false so that each slug corresponds to + // all the values in that dictionary entry. + // e.g. if `first_only` is false, when loading Pokemon Abomasnow for traditional Chinese, + // "abomasnow": ["暴雪王", "繁霎王", "鬘粘王"], + // when OCR detects any of "暴雪王", "繁霎王" or "鬘粘王", the matcher returns Abomasnow. + // if 'first_only' is true, only when OCR detects "暴雪王" do the matcher return Abomasnow. + SmallDictionaryMatcher(const std::string& json_path, bool first_only = false); + // Load JSON object to build the dictionary for all languages stored in the JSON. + // See the comments of + // `SmallDictionaryMatcher(const std::string& json_path, bool first_only = false)` + // to konw the usage of `first_only`. + SmallDictionaryMatcher(const JsonObject& json, bool first_only = false); + + void save(const std::string& json_path) const; +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_StringMatchResult.cpp b/SerialPrograms/Source/CommonTools/OCR/OCR_StringMatchResult.cpp index ff7a986b6d..e1936376b1 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_StringMatchResult.cpp +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_StringMatchResult.cpp @@ -1,114 +1,114 @@ -/* String Match Results - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Qt/StringToolsQt.h" -#include "OCR_StringMatchResult.h" - -namespace PokemonAutomation{ -namespace OCR{ - - -std::string StringMatchData::to_str() const{ - std::string str; - - str += "\""; - for (char ch : original_text){ - if (ch != '\r' && ch != '\n'){ - str += ch; - } - } - str += "\" -> "; - str += "\"" + to_utf8(normalized_text) + "\" -> "; - - str += "(" + to_utf8(target) + "): "; - str += "(" + token + ")"; - return str; -} - -void StringMatchResult::log(Logger& logger, double max_log10p, const std::string& extra) const{ - std::string str = "String Match Result: "; - -#if 0 - if (!expected_token.empty()){ - str += "Expected ("; - str += QString::fromStdString(expected_token); - str += "): "; - } -#endif - - Color color; - if (results.empty()){ - str += "no matches"; - color = COLOR_RED; - }else{ - double best = results.begin()->first; - color = exact_match || best <= max_log10p - ? COLOR_BLUE - : COLOR_RED; - - if (results.size() == 1){ - auto iter = results.begin(); - str += iter->second.to_str(); - str += " (log10p = " + tostr_default(iter->first) +")"; - }else{ - str += "Multiple Candidates =>\n"; - size_t printed = 0; - for (const auto& item : results){ - if (printed == 10){ - str += " (" + std::to_string(results.size() - 10) + " more...)\n"; - break; - } - str += " " + tostr_default(item.first) + " : " + item.second.to_str() + "\n"; - printed++; - } - } - } - - if (!extra.empty()){ - str += " ===> "; - str += extra; - } - logger.log(str, color); -} - -void StringMatchResult::add(double log10p, StringMatchData data){ - results.emplace(log10p, std::move(data)); -} -void StringMatchResult::clear_beyond_spread(double log10p_spread){ - auto best = results.begin(); - while (results.size() > 1){ - auto back = results.rbegin(); - if (back->first <= best->first + log10p_spread){ - break; - } - results.erase(back->first); - } -} -void StringMatchResult::clear_beyond_log10p(double max_log10p){ - while (!results.empty()){ - auto iter = results.end(); - --iter; - if (iter->first <= max_log10p){ - break; - } - results.erase(iter); - } -} - - -void StringMatchResult::operator+=(const StringMatchResult& result){ - exact_match |= result.exact_match; - for (auto& item : result.results){ - results.insert(item); - } -} - - - - -} -} +/* String Match Results + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Qt/StringToolsQt.h" +#include "OCR_StringMatchResult.h" + +namespace PokemonAutomation{ +namespace OCR{ + + +std::string StringMatchData::to_str() const{ + std::string str; + + str += "\""; + for (char ch : original_text){ + if (ch != '\r' && ch != '\n'){ + str += ch; + } + } + str += "\" -> "; + str += "\"" + to_utf8(normalized_text) + "\" -> "; + + str += "(" + to_utf8(target) + "): "; + str += "(" + token + ")"; + return str; +} + +void StringMatchResult::log(Logger& logger, double max_log10p, const std::string& extra) const{ + std::string str = "String Match Result: "; + +#if 0 + if (!expected_token.empty()){ + str += "Expected ("; + str += QString::fromStdString(expected_token); + str += "): "; + } +#endif + + Color color; + if (results.empty()){ + str += "no matches"; + color = COLOR_RED; + }else{ + double best = results.begin()->first; + color = exact_match || best <= max_log10p + ? COLOR_BLUE + : COLOR_RED; + + if (results.size() == 1){ + auto iter = results.begin(); + str += iter->second.to_str(); + str += " (log10p = " + tostr_default(iter->first) +")"; + }else{ + str += "Multiple Candidates =>\n"; + size_t printed = 0; + for (const auto& item : results){ + if (printed == 10){ + str += " (" + std::to_string(results.size() - 10) + " more...)\n"; + break; + } + str += " " + tostr_default(item.first) + " : " + item.second.to_str() + "\n"; + printed++; + } + } + } + + if (!extra.empty()){ + str += " ===> "; + str += extra; + } + logger.log(str, color); +} + +void StringMatchResult::add(double log10p, StringMatchData data){ + results.emplace(log10p, std::move(data)); +} +void StringMatchResult::clear_beyond_spread(double log10p_spread){ + auto best = results.begin(); + while (results.size() > 1){ + auto back = results.rbegin(); + if (back->first <= best->first + log10p_spread){ + break; + } + results.erase(back->first); + } +} +void StringMatchResult::clear_beyond_log10p(double max_log10p){ + while (!results.empty()){ + auto iter = results.end(); + --iter; + if (iter->first <= max_log10p){ + break; + } + results.erase(iter); + } +} + + +void StringMatchResult::operator+=(const StringMatchResult& result){ + exact_match |= result.exact_match; + for (auto& item : result.results){ + results.insert(item); + } +} + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_StringMatchResult.h b/SerialPrograms/Source/CommonTools/OCR/OCR_StringMatchResult.h index 96f37683d6..a324fbfe15 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_StringMatchResult.h +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_StringMatchResult.h @@ -1,50 +1,50 @@ -/* String Match Results - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_OCR_StringMatchResult_H -#define PokemonAutomation_CommonTools_OCR_StringMatchResult_H - -#include -#include -#include "Common/Cpp/AbstractLogger.h" - -namespace PokemonAutomation{ -namespace OCR{ - - -struct StringMatchData{ - std::string original_text; - std::u32string normalized_text; - - std::u32string target; - std::string token; - - std::string to_str() const; -}; - -struct StringMatchResult{ - bool exact_match = false; - std::multimap results; - - void clear(){ - exact_match = false; - results.clear(); - } - void log(Logger& logger, double max_log10p, const std::string& extra = std::string()) const; - - void add(double log10p, StringMatchData data); - void clear_beyond_spread(double log10p_spread); - void clear_beyond_log10p(double max_log10p); - - void operator+=(const StringMatchResult& result); -}; - - - - -} -} -#endif +/* String Match Results + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_OCR_StringMatchResult_H +#define PokemonAutomation_CommonTools_OCR_StringMatchResult_H + +#include +#include +#include "Common/Cpp/AbstractLogger.h" + +namespace PokemonAutomation{ +namespace OCR{ + + +struct StringMatchData{ + std::string original_text; + std::u32string normalized_text; + + std::u32string target; + std::string token; + + std::string to_str() const; +}; + +struct StringMatchResult{ + bool exact_match = false; + std::multimap results; + + void clear(){ + exact_match = false; + results.clear(); + } + void log(Logger& logger, double max_log10p, const std::string& extra = std::string()) const; + + void add(double log10p, StringMatchData data); + void clear_beyond_spread(double log10p_spread); + void clear_beyond_log10p(double max_log10p); + + void operator+=(const StringMatchResult& result); +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_StringNormalization.cpp b/SerialPrograms/Source/CommonTools/OCR/OCR_StringNormalization.cpp index a6cab538e1..06bfa4d35c 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_StringNormalization.cpp +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_StringNormalization.cpp @@ -1,93 +1,93 @@ -/* String Normalization - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "Common/Qt/StringToolsQt.h" -#include "CommonFramework/Globals.h" -#include "OCR_StringNormalization.h" - -namespace PokemonAutomation{ -namespace OCR{ - - -std::u32string normalize_utf32(const std::string& text){ - QString qstr = QString::fromStdString(text); - qstr = qstr.normalized(QString::NormalizationForm_KD); - std::u32string u32 = remove_non_alphanumeric(qstr.toStdU32String()); - u32 = run_character_reductions(u32); - to_lower(u32); - return u32; -} - - - -std::u32string remove_non_alphanumeric(const std::u32string& text){ - std::u32string str; - for (char32_t ch : text){ - if (QChar::isLetterOrNumber(ch)){ - str += ch; - continue; - } - } - return str; -} - - - -std::map make_substitution_map32(){ - std::string path = RESOURCE_PATH() + "Tesseract/CharacterReductions.json"; - JsonValue json = load_json_file(path); - JsonObject& obj = json.to_object_throw(path); - - std::map map; - for (auto& item : obj){ - const std::string& target = item.first; - std::string& sources = item.second.to_string_throw(path); - for (char32_t ch : to_utf32(sources)){ - auto iter = map.find(ch); - if (iter != map.end()){ - throw FileException( - nullptr, PA_CURRENT_FUNCTION, - to_utf8(to_utf32("Duplicate character reduction: ") + ch), - std::move(path) - ); - } - map[ch] = to_utf32(target); - } - } - return map; -} -const std::map& SUBSTITUTION_MAP32(){ - static std::map map = make_substitution_map32(); - return map; -} -std::u32string run_character_reductions(const std::u32string& text){ - const std::map& map = SUBSTITUTION_MAP32(); - std::u32string str; - for (char32_t ch : text){ - auto iter = map.find(ch); - if (iter == map.end()){ - str += ch; - }else{ - str += iter->second; - } - } - return str; -} - - - - - - - -} -} - +/* String Normalization + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Common/Qt/StringToolsQt.h" +#include "CommonFramework/Globals.h" +#include "OCR_StringNormalization.h" + +namespace PokemonAutomation{ +namespace OCR{ + + +std::u32string normalize_utf32(const std::string& text){ + QString qstr = QString::fromStdString(text); + qstr = qstr.normalized(QString::NormalizationForm_KD); + std::u32string u32 = remove_non_alphanumeric(qstr.toStdU32String()); + u32 = run_character_reductions(u32); + to_lower(u32); + return u32; +} + + + +std::u32string remove_non_alphanumeric(const std::u32string& text){ + std::u32string str; + for (char32_t ch : text){ + if (QChar::isLetterOrNumber(ch)){ + str += ch; + continue; + } + } + return str; +} + + + +std::map make_substitution_map32(){ + std::string path = RESOURCE_PATH() + "Tesseract/CharacterReductions.json"; + JsonValue json = load_json_file(path); + JsonObject& obj = json.to_object_throw(path); + + std::map map; + for (auto& item : obj){ + const std::string& target = item.first; + std::string& sources = item.second.to_string_throw(path); + for (char32_t ch : to_utf32(sources)){ + auto iter = map.find(ch); + if (iter != map.end()){ + throw FileException( + nullptr, PA_CURRENT_FUNCTION, + to_utf8(to_utf32("Duplicate character reduction: ") + ch), + std::move(path) + ); + } + map[ch] = to_utf32(target); + } + } + return map; +} +const std::map& SUBSTITUTION_MAP32(){ + static std::map map = make_substitution_map32(); + return map; +} +std::u32string run_character_reductions(const std::u32string& text){ + const std::map& map = SUBSTITUTION_MAP32(); + std::u32string str; + for (char32_t ch : text){ + auto iter = map.find(ch); + if (iter == map.end()){ + str += ch; + }else{ + str += iter->second; + } + } + return str; +} + + + + + + + +} +} + diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_StringNormalization.h b/SerialPrograms/Source/CommonTools/OCR/OCR_StringNormalization.h index 7e69aa1ac6..3265b8db55 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_StringNormalization.h +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_StringNormalization.h @@ -1,25 +1,25 @@ -/* String Normalization - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_OCR_StringNormalization_H -#define PokemonAutomation_CommonTools_OCR_StringNormalization_H - -#include - -namespace PokemonAutomation{ -namespace OCR{ - - -std::u32string remove_non_alphanumeric(const std::u32string& text); -std::u32string run_character_reductions(const std::u32string& text); - -std::u32string normalize_utf32(const std::string& text); - - - -} -} -#endif +/* String Normalization + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_OCR_StringNormalization_H +#define PokemonAutomation_CommonTools_OCR_StringNormalization_H + +#include + +namespace PokemonAutomation{ +namespace OCR{ + + +std::u32string remove_non_alphanumeric(const std::u32string& text); +std::u32string run_character_reductions(const std::u32string& text); + +std::u32string normalize_utf32(const std::string& text); + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_TextMatcher.cpp b/SerialPrograms/Source/CommonTools/OCR/OCR_TextMatcher.cpp index cc2f56514b..e7d2be2d22 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_TextMatcher.cpp +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_TextMatcher.cpp @@ -1,311 +1,311 @@ -/* Text Inference Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Qt/StringToolsQt.h" -#include "OCR_StringNormalization.h" -#include "OCR_TextMatcher.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace OCR{ - -void print(const std::vector& v){ - std::string str = "{"; - bool first = true; - for (size_t x : v){ - if (!first){ - str += ", "; - } - first = false; - str += std::to_string(x); - } - str += "}"; - cout << str << endl; -} - - -size_t levenshtein_distance(const QString& x, const QString& y){ - size_t xlen = x.size(); - size_t ylen = y.size(); - - std::vector v0(ylen + 1); - std::vector v1(ylen + 1); - - for (size_t i = 0; i <= ylen; i++){ - v0[i] = i; - } - - for (size_t i = 0; i < xlen; i++){ - v1[0] = i + 1; - - for (size_t j = 0; j < ylen; j++){ - size_t delete_cost = v0[j + 1] + 1; - size_t insert_cost = v1[j] + 1; - size_t sub_cost = v0[j]; - if (x[(int)i] != y[(int)j]){ - sub_cost += 1; - } - v1[j + 1] = std::min({delete_cost, insert_cost, sub_cost}); - } - - std::swap(v0, v1); - } - - return v0[ylen]; -} -size_t levenshtein_distance_substring(const QString& substring, const QString& fullstring){ - size_t xlen = fullstring.size(); - size_t ylen = substring.size(); - - std::vector v0(ylen + 1); - std::vector v1(ylen + 1); - - for (size_t i = 0; i <= ylen; i++){ - v0[i] = i; - } -// print(v0); - - size_t min = ylen; - - for (size_t i = 0; i < xlen; i++){ - v1[0] = 0; - - for (size_t j = 0; j < ylen; j++){ - size_t delete_cost = v0[j + 1] + 1; - size_t insert_cost = v1[j] + 1; - size_t sub_cost = v0[j]; - if (fullstring[(int)i] != substring[(int)j]){ - sub_cost += 1; - } - v1[j + 1] = std::min({delete_cost, insert_cost, sub_cost}); - } - - std::swap(v0, v1); - - min = std::min(min, v0[ylen]); -// print(v0); - } - - return min; -} - -template -size_t levenshtein_distance(const StringType& x, const StringType& y){ - size_t xlen = x.size(); - size_t ylen = y.size(); - - std::vector v0(ylen + 1); - std::vector v1(ylen + 1); - - for (size_t i = 0; i <= ylen; i++){ - v0[i] = i; - } - - for (size_t i = 0; i < xlen; i++){ - v1[0] = i + 1; - - for (size_t j = 0; j < ylen; j++){ - size_t delete_cost = v0[j + 1] + 1; - size_t insert_cost = v1[j] + 1; - size_t sub_cost = v0[j]; - if (x[i] != y[j]){ - sub_cost += 1; - } - v1[j + 1] = std::min({delete_cost, insert_cost, sub_cost}); - } - - std::swap(v0, v1); - } - - return v0[ylen]; -} -template -size_t levenshtein_distance_substring(const StringType& substring, const StringType& fullstring){ - size_t xlen = fullstring.size(); - size_t ylen = substring.size(); - - std::vector v0(ylen + 1); - std::vector v1(ylen + 1); - - for (size_t i = 0; i <= ylen; i++){ - v0[i] = i; - } -// print(v0); - - size_t min = ylen; - - for (size_t i = 0; i < xlen; i++){ - v1[0] = 0; - - for (size_t j = 0; j < ylen; j++){ - size_t delete_cost = v0[j + 1] + 1; - size_t insert_cost = v1[j] + 1; - size_t sub_cost = v0[j]; - if (fullstring[i] != substring[j]){ - sub_cost += 1; - } - v1[j + 1] = std::min({delete_cost, insert_cost, sub_cost}); - } - - std::swap(v0, v1); - - min = std::min(min, v0[ylen]); -// print(v0); - } - - return min; -} -template size_t levenshtein_distance(const std::u32string& x, const std::u32string& y); -template size_t levenshtein_distance_substring(const std::u32string& x, const std::u32string& y); - - -std::map> binomial_table; -SpinLock binomial_lock; -std::vector binomial_row_u64(size_t degree){ - std::vector row; - - uint64_t a = (uint64_t)degree; - uint64_t b = 1; - { - row.emplace_back(1); - } - { - row.emplace_back(a); - a--; - b++; - } - while (a > b){ - row.emplace_back(row.back() * a / b); - a--; - b++; - } - - return row; -} -double binomial_coefficient_double(size_t degree, size_t index){ - if (degree > 1000){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Cannot go beyond degree 1000."); - } - - WriteSpinLock lg(binomial_lock, "binomial_coefficient_double()"); - - auto iter = binomial_table.find(degree); - std::vector& row = iter != binomial_table.end() - ? iter->second - : binomial_table[degree] = binomial_row_u64(degree); - - if (index > degree / 2){ - index = degree - index; - } - - return row[index]; -} - - -double random_match_probability(size_t total, size_t matched, double random_match_chance){ - if (total > 1000){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Cannot go beyond degree 1000."); - } - - double c_match = 1 - random_match_chance; - - double misses[62]; - { - double miss = 1; - misses[0] = miss; - for (size_t c = 1; c <= total - matched; c++){ - miss *= c_match; - misses[c] = miss; - } - } - - double hits = 1; - - size_t m = 0; - for (; m < matched; m++){ - hits *= random_match_chance; - } - - double probability = 0; - for (; m < total; m++){ - double binomial = (double)binomial_coefficient_double(total, m); - probability += hits * binomial * misses[total - m]; - hits *= random_match_chance; - } - probability += hits; - return probability; -} - - - -StringMatchResult match_substring( - const std::map>& database, double random_match_chance, - const std::string& text, double log10p_spread -){ - StringMatchResult results; -// result.original_text = text; -// result.normalized_text = normalize(text); - - std::u32string normalized = normalize_utf32(text); - - // Search for exact match of candidate. - auto iter = database.find(normalized); - if (iter != database.end()){ - results.exact_match = true; - double probability = random_match_probability(normalized.size(), normalized.size(), random_match_chance); - double log10p = std::log10(probability); - for (const auto& target : iter->second){ - results.add( - log10p, - StringMatchData{text, normalized, normalized, target} - ); - } - return results; - } - - - for (const auto& item : database){ - double token_length = item.first.size(); - - size_t distance = levenshtein_distance_substring(item.first, normalized); - size_t matched = token_length - distance; - if (matched == 0){ - continue; - } - - double probability = random_match_probability(token_length, matched, random_match_chance); - double log10p = std::log10(probability); - - if (distance == 0){ - results.exact_match = true; - } - - for (const auto& slug : item.second){ - results.add(log10p, StringMatchData{text, normalized, item.first, slug}); - results.clear_beyond_spread(log10p_spread); - } - } - - return results; -} - - - - - - - - -} -} - +/* Text Inference Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Qt/StringToolsQt.h" +#include "OCR_StringNormalization.h" +#include "OCR_TextMatcher.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace OCR{ + +void print(const std::vector& v){ + std::string str = "{"; + bool first = true; + for (size_t x : v){ + if (!first){ + str += ", "; + } + first = false; + str += std::to_string(x); + } + str += "}"; + cout << str << endl; +} + + +size_t levenshtein_distance(const QString& x, const QString& y){ + size_t xlen = x.size(); + size_t ylen = y.size(); + + std::vector v0(ylen + 1); + std::vector v1(ylen + 1); + + for (size_t i = 0; i <= ylen; i++){ + v0[i] = i; + } + + for (size_t i = 0; i < xlen; i++){ + v1[0] = i + 1; + + for (size_t j = 0; j < ylen; j++){ + size_t delete_cost = v0[j + 1] + 1; + size_t insert_cost = v1[j] + 1; + size_t sub_cost = v0[j]; + if (x[(int)i] != y[(int)j]){ + sub_cost += 1; + } + v1[j + 1] = std::min({delete_cost, insert_cost, sub_cost}); + } + + std::swap(v0, v1); + } + + return v0[ylen]; +} +size_t levenshtein_distance_substring(const QString& substring, const QString& fullstring){ + size_t xlen = fullstring.size(); + size_t ylen = substring.size(); + + std::vector v0(ylen + 1); + std::vector v1(ylen + 1); + + for (size_t i = 0; i <= ylen; i++){ + v0[i] = i; + } +// print(v0); + + size_t min = ylen; + + for (size_t i = 0; i < xlen; i++){ + v1[0] = 0; + + for (size_t j = 0; j < ylen; j++){ + size_t delete_cost = v0[j + 1] + 1; + size_t insert_cost = v1[j] + 1; + size_t sub_cost = v0[j]; + if (fullstring[(int)i] != substring[(int)j]){ + sub_cost += 1; + } + v1[j + 1] = std::min({delete_cost, insert_cost, sub_cost}); + } + + std::swap(v0, v1); + + min = std::min(min, v0[ylen]); +// print(v0); + } + + return min; +} + +template +size_t levenshtein_distance(const StringType& x, const StringType& y){ + size_t xlen = x.size(); + size_t ylen = y.size(); + + std::vector v0(ylen + 1); + std::vector v1(ylen + 1); + + for (size_t i = 0; i <= ylen; i++){ + v0[i] = i; + } + + for (size_t i = 0; i < xlen; i++){ + v1[0] = i + 1; + + for (size_t j = 0; j < ylen; j++){ + size_t delete_cost = v0[j + 1] + 1; + size_t insert_cost = v1[j] + 1; + size_t sub_cost = v0[j]; + if (x[i] != y[j]){ + sub_cost += 1; + } + v1[j + 1] = std::min({delete_cost, insert_cost, sub_cost}); + } + + std::swap(v0, v1); + } + + return v0[ylen]; +} +template +size_t levenshtein_distance_substring(const StringType& substring, const StringType& fullstring){ + size_t xlen = fullstring.size(); + size_t ylen = substring.size(); + + std::vector v0(ylen + 1); + std::vector v1(ylen + 1); + + for (size_t i = 0; i <= ylen; i++){ + v0[i] = i; + } +// print(v0); + + size_t min = ylen; + + for (size_t i = 0; i < xlen; i++){ + v1[0] = 0; + + for (size_t j = 0; j < ylen; j++){ + size_t delete_cost = v0[j + 1] + 1; + size_t insert_cost = v1[j] + 1; + size_t sub_cost = v0[j]; + if (fullstring[i] != substring[j]){ + sub_cost += 1; + } + v1[j + 1] = std::min({delete_cost, insert_cost, sub_cost}); + } + + std::swap(v0, v1); + + min = std::min(min, v0[ylen]); +// print(v0); + } + + return min; +} +template size_t levenshtein_distance(const std::u32string& x, const std::u32string& y); +template size_t levenshtein_distance_substring(const std::u32string& x, const std::u32string& y); + + +std::map> binomial_table; +SpinLock binomial_lock; +std::vector binomial_row_u64(size_t degree){ + std::vector row; + + uint64_t a = (uint64_t)degree; + uint64_t b = 1; + { + row.emplace_back(1); + } + { + row.emplace_back(a); + a--; + b++; + } + while (a > b){ + row.emplace_back(row.back() * a / b); + a--; + b++; + } + + return row; +} +double binomial_coefficient_double(size_t degree, size_t index){ + if (degree > 1000){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Cannot go beyond degree 1000."); + } + + WriteSpinLock lg(binomial_lock, "binomial_coefficient_double()"); + + auto iter = binomial_table.find(degree); + std::vector& row = iter != binomial_table.end() + ? iter->second + : binomial_table[degree] = binomial_row_u64(degree); + + if (index > degree / 2){ + index = degree - index; + } + + return row[index]; +} + + +double random_match_probability(size_t total, size_t matched, double random_match_chance){ + if (total > 1000){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Cannot go beyond degree 1000."); + } + + double c_match = 1 - random_match_chance; + + double misses[62]; + { + double miss = 1; + misses[0] = miss; + for (size_t c = 1; c <= total - matched; c++){ + miss *= c_match; + misses[c] = miss; + } + } + + double hits = 1; + + size_t m = 0; + for (; m < matched; m++){ + hits *= random_match_chance; + } + + double probability = 0; + for (; m < total; m++){ + double binomial = (double)binomial_coefficient_double(total, m); + probability += hits * binomial * misses[total - m]; + hits *= random_match_chance; + } + probability += hits; + return probability; +} + + + +StringMatchResult match_substring( + const std::map>& database, double random_match_chance, + const std::string& text, double log10p_spread +){ + StringMatchResult results; +// result.original_text = text; +// result.normalized_text = normalize(text); + + std::u32string normalized = normalize_utf32(text); + + // Search for exact match of candidate. + auto iter = database.find(normalized); + if (iter != database.end()){ + results.exact_match = true; + double probability = random_match_probability(normalized.size(), normalized.size(), random_match_chance); + double log10p = std::log10(probability); + for (const auto& target : iter->second){ + results.add( + log10p, + StringMatchData{text, normalized, normalized, target} + ); + } + return results; + } + + + for (const auto& item : database){ + double token_length = item.first.size(); + + size_t distance = levenshtein_distance_substring(item.first, normalized); + size_t matched = token_length - distance; + if (matched == 0){ + continue; + } + + double probability = random_match_probability(token_length, matched, random_match_chance); + double log10p = std::log10(probability); + + if (distance == 0){ + results.exact_match = true; + } + + for (const auto& slug : item.second){ + results.add(log10p, StringMatchData{text, normalized, item.first, slug}); + results.clear_beyond_spread(log10p_spread); + } + } + + return results; +} + + + + + + + + +} +} + diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_TextMatcher.h b/SerialPrograms/Source/CommonTools/OCR/OCR_TextMatcher.h index cddfa9ba77..0d721615f1 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_TextMatcher.h +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_TextMatcher.h @@ -1,44 +1,44 @@ -/* Text Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_OCR_TextMatcher_H -#define PokemonAutomation_CommonTools_OCR_TextMatcher_H - -#include -#include -#include -#include -#include "OCR_StringMatchResult.h" - -namespace PokemonAutomation{ -namespace OCR{ - - -size_t levenshtein_distance(const QString& x, const QString& y); -size_t levenshtein_distance_substring(const QString& substring, const QString& fullstring); - -template -size_t levenshtein_distance(const StringType& x, const StringType& y); -template -size_t levenshtein_distance_substring(const StringType& substring, const StringType& fullstring); - -// Mathematically equivalent to: -// BinomialCDF[total, 1 - random_match_chance, total - matched] -double random_match_probability(size_t total, size_t matched, double random_match_chance); - - - -StringMatchResult match_substring( - const std::map>& database, double random_match_chance, - const std::string& text, double log10p_spread -); - - - - -} -} -#endif +/* Text Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_OCR_TextMatcher_H +#define PokemonAutomation_CommonTools_OCR_TextMatcher_H + +#include +#include +#include +#include +#include "OCR_StringMatchResult.h" + +namespace PokemonAutomation{ +namespace OCR{ + + +size_t levenshtein_distance(const QString& x, const QString& y); +size_t levenshtein_distance_substring(const QString& substring, const QString& fullstring); + +template +size_t levenshtein_distance(const StringType& x, const StringType& y); +template +size_t levenshtein_distance_substring(const StringType& substring, const StringType& fullstring); + +// Mathematically equivalent to: +// BinomialCDF[total, 1 - random_match_chance, total - matched] +double random_match_probability(size_t total, size_t matched, double random_match_chance); + + + +StringMatchResult match_substring( + const std::map>& database, double random_match_chance, + const std::string& text, double log10p_spread +); + + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_TrainingTools.cpp b/SerialPrograms/Source/CommonTools/OCR/OCR_TrainingTools.cpp index 88f8203d55..d6fb1e32d8 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_TrainingTools.cpp +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_TrainingTools.cpp @@ -1,271 +1,281 @@ -/* Training Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Concurrency/ParallelTaskRunner.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Options/Environment/PerformanceOptions.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "OCR_SmallDictionaryMatcher.h" -#include "OCR_LargeDictionaryMatcher.h" -#include "OCR_TrainingTools.h" - -namespace PokemonAutomation{ -namespace OCR{ - - - -std::string extract_name(const std::string& filename){ - std::string name = filename; - while (!name.empty()){ - char ch = name.back(); - name.pop_back(); - if (ch == '.'){ - break; - } - } - while (!name.empty()){ - char ch = name.back(); - name.pop_back(); - if (ch == '-'){ - break; - } - } - while (!name.empty()){ - char ch = name.back(); - name.pop_back(); - if (ch == '-'){ - break; - } - } - return name; -} - - - -TrainingSession::TrainingSession( - Logger& logger, CancellableScope& scope, - const std::string& training_data_directory -) - : m_logger(logger) - , m_scope(scope) - , m_directory(TRAINING_PATH() + training_data_directory) - , m_total_samples(0) -{ - if (!m_directory.empty() && m_directory.back() != '/' && m_directory.back() != '\\'){ - m_directory += "/"; - } - - logger.log("Parsing training data in: " + m_directory); - - QDirIterator iter(QString::fromStdString(m_directory), QDir::AllDirs); - while (iter.hasNext()){ - iter.next(); - QString sample_directory = iter.fileName() + "/"; - for (size_t c = 1; c < (size_t)Language::EndOfList; c++){ - Language language = (Language)c; - const std::string& code = language_data(language).code; - QString folder = sample_directory + QString::fromStdString(code) + "/"; - QDirIterator iter1(QString::fromStdString(m_directory) + folder, QStringList() << "*.png", QDir::Files); - while (iter1.hasNext()){ - iter1.next(); -// QString file = iter.next(); - m_samples[language].emplace_back( - TrainingSample{ - OCR::extract_name(iter1.fileName().toStdString()), - (folder + iter1.fileName()).toStdString() - } - ); - m_total_samples++; - - scope.throw_if_cancelled(); - } - } - scope.throw_if_cancelled(); - } - - logger.log( - "Parsing Complete: Languages = " + tostr_u_commas(m_samples.size()) + - ", Samples = " + tostr_u_commas(m_total_samples) - ); -} - - -void TrainingSession::generate_small_dictionary( - const std::string& ocr_json_file, - const std::string& output_json_file, - bool incremental, - size_t threads, - const std::vector& text_color_ranges, - double max_log10p, double log10p_spread, - double min_text_ratio, double max_text_ratio -){ - m_logger.log("Generating OCR Data..."); - - OCR::SmallDictionaryMatcher baseline(ocr_json_file, !incremental); - OCR::SmallDictionaryMatcher trained(ocr_json_file, !incremental); - - ParallelTaskRunner task_runner( - [](){ GlobalSettings::instance().PERFORMANCE->COMPUTE_PRIORITY.set_on_this_thread(); }, - 0, threads - ); - - std::atomic matched(0); - std::atomic failed(0); - for (const auto& language : m_samples){ - const LanguageData& language_info = language_data(language.first); - m_logger.log("Starting Language: " + language_info.name); -// cout << (int)item.first << " : " << item.second.size() << endl; - for (const TrainingSample& sample : language.second){ - task_runner.dispatch([&]{ - ImageRGB32 image(m_directory + sample.filepath); - if (!image){ - m_logger.log("Skipping: " + sample.filepath); - return; - } - - OCR::StringMatchResult result = baseline.match_substring_from_image_multifiltered( - nullptr, language.first, image, - text_color_ranges, - 0, log10p_spread, - min_text_ratio, max_text_ratio - ); - - OCR::StringMatchResult result0 = result; - result.clear_beyond_log10p(max_log10p); - - if (result.results.empty()){ - failed++; - result0.log(m_logger, max_log10p, sample.filepath); - if (!result0.results.empty()){ - trained.add_candidate( - language.first, sample.token, - result0.results.begin()->second.normalized_text - ); - } - return; - } - - for (const auto& item : result.results){ - if (item.second.token == sample.token){ - matched++; - return; - } - } - - result.log(m_logger, -99999, sample.filepath); - trained.add_candidate( - language.first, sample.token, - result0.results.begin()->second.normalized_text - ); - }); - m_scope.throw_if_cancelled(); - } - task_runner.wait_for_everything(); - m_scope.throw_if_cancelled(); - } - - m_logger.log("Languages: " + tostr_u_commas(m_samples.size())); - m_logger.log("Samples: " + tostr_u_commas(m_total_samples)); - m_logger.log("Matched: " + tostr_u_commas(matched)); - m_logger.log("Missed: " + tostr_u_commas(failed)); - - trained.save(output_json_file); -} - -void TrainingSession::generate_large_dictionary( - const std::string& ocr_json_directory, - const std::string& output_prefix, - bool incremental, - size_t threads, - const std::vector& text_color_ranges, - double max_log10p, double log10p_spread, - double min_text_ratio, double max_text_ratio -) const{ - m_logger.log("Generating OCR Data..."); - - OCR::LargeDictionaryMatcher baseline(ocr_json_directory + output_prefix, nullptr, !incremental); - OCR::LargeDictionaryMatcher trained(ocr_json_directory + output_prefix, nullptr, !incremental); - - ParallelTaskRunner task_runner( - [](){ GlobalSettings::instance().PERFORMANCE->COMPUTE_PRIORITY.set_on_this_thread(); }, - 0, threads - ); - - std::atomic matched(0); - std::atomic failed(0); - for (const auto& language : m_samples){ - const LanguageData& language_info = language_data(language.first); - m_logger.log("Starting Language: " + language_info.name); -// cout << (int)item.first << " : " << item.second.size() << endl; - for (const TrainingSample& sample : language.second){ - task_runner.dispatch([&]{ - ImageRGB32 image(m_directory + sample.filepath); - if (!image){ - m_logger.log("Skipping: " + sample.filepath); - return; - } - - OCR::StringMatchResult result = baseline.match_substring_from_image_multifiltered( - nullptr, language.first, image, - text_color_ranges, - 0, log10p_spread, - min_text_ratio, max_text_ratio - ); - - OCR::StringMatchResult result0 = result; - result.clear_beyond_log10p(max_log10p); - - if (result.results.empty()){ - failed++; - result0.log(m_logger, max_log10p, sample.filepath); - if (!result0.results.empty()){ - trained.add_candidate( - language.first, sample.token, - result0.results.begin()->second.normalized_text - ); - } - return; - } - - for (const auto& item : result.results){ - if (item.second.token == sample.token){ - matched++; - return; - } - } - - result.log(m_logger, -99999, sample.filepath); - trained.add_candidate( - language.first, sample.token, - result0.results.begin()->second.normalized_text - ); - }); - m_scope.throw_if_cancelled(); - } - task_runner.wait_for_everything(); - - std::string json = output_prefix + language_info.code + ".json"; - trained.save(language.first, json); - m_scope.throw_if_cancelled(); - } - - m_logger.log("Languages: " + tostr_u_commas(m_samples.size())); - m_logger.log("Samples: " + tostr_u_commas(m_total_samples)); - m_logger.log("Matched: " + tostr_u_commas(matched)); - m_logger.log("Missed: " + tostr_u_commas(failed)); -} - - - - - - -} -} - +/* Training Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Concurrency/AsyncTask.h" +#include "Common/Cpp/Concurrency/ComputationThreadPool.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Options/Environment/PerformanceOptions.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "OCR_SmallDictionaryMatcher.h" +#include "OCR_LargeDictionaryMatcher.h" +#include "OCR_TrainingTools.h" + +namespace PokemonAutomation{ +namespace OCR{ + + + +std::string extract_name(const std::string& filename){ + std::string name = filename; + while (!name.empty()){ + char ch = name.back(); + name.pop_back(); + if (ch == '.'){ + break; + } + } + while (!name.empty()){ + char ch = name.back(); + name.pop_back(); + if (ch == '-'){ + break; + } + } + while (!name.empty()){ + char ch = name.back(); + name.pop_back(); + if (ch == '-'){ + break; + } + } + return name; +} + + + +TrainingSession::TrainingSession( + Logger& logger, CancellableScope& scope, + const std::string& training_data_directory +) + : m_logger(logger) + , m_scope(scope) + , m_directory(TRAINING_PATH() + training_data_directory) + , m_total_samples(0) +{ + if (!m_directory.empty() && m_directory.back() != '/' && m_directory.back() != '\\'){ + m_directory += "/"; + } + + logger.log("Parsing training data in: " + m_directory); + + QDirIterator iter(QString::fromStdString(m_directory), QDir::AllDirs); + while (iter.hasNext()){ + iter.next(); + QString sample_directory = iter.fileName() + "/"; + for (size_t c = 1; c < (size_t)Language::EndOfList; c++){ + Language language = (Language)c; + const std::string& code = language_data(language).code; + QString folder = sample_directory + QString::fromStdString(code) + "/"; + QDirIterator iter1(QString::fromStdString(m_directory) + folder, QStringList() << "*.png", QDir::Files); + while (iter1.hasNext()){ + iter1.next(); +// QString file = iter.next(); + m_samples[language].emplace_back( + TrainingSample{ + OCR::extract_name(iter1.fileName().toStdString()), + (folder + iter1.fileName()).toStdString() + } + ); + m_total_samples++; + + scope.throw_if_cancelled(); + } + } + scope.throw_if_cancelled(); + } + + logger.log( + "Parsing Complete: Languages = " + tostr_u_commas(m_samples.size()) + + ", Samples = " + tostr_u_commas(m_total_samples) + ); +} + + +void TrainingSession::generate_small_dictionary( + const std::string& ocr_json_file, + const std::string& output_json_file, + bool incremental, + size_t threads, + const std::vector& text_color_ranges, + double max_log10p, double log10p_spread, + double min_text_ratio, double max_text_ratio +){ + m_logger.log("Generating OCR Data..."); + + OCR::SmallDictionaryMatcher baseline(ocr_json_file, !incremental); + OCR::SmallDictionaryMatcher trained(ocr_json_file, !incremental); + + ComputationThreadPool task_runner( + [&](){ GlobalSettings::instance().PERFORMANCE->COMPUTE_PRIORITY.set_on_this_thread(m_logger); }, + 0, threads + ); + + std::atomic matched(0); + std::atomic failed(0); + for (const auto& language : m_samples){ + const LanguageData& language_info = language_data(language.first); + m_logger.log("Starting Language: " + language_info.name); +// cout << (int)item.first << " : " << item.second.size() << endl; + + task_runner.run_in_parallel( + [&](size_t index){ + m_scope.throw_if_cancelled(); + + const TrainingSample& sample = language.second[index]; + + ImageRGB32 image(m_directory + sample.filepath); + if (!image){ + m_logger.log("Skipping: " + sample.filepath); + return; + } + + OCR::StringMatchResult result = baseline.match_substring_from_image_multifiltered( + nullptr, language.first, image, + text_color_ranges, + 0, log10p_spread, + min_text_ratio, max_text_ratio + ); + + OCR::StringMatchResult result0 = result; + result.clear_beyond_log10p(max_log10p); + + if (result.results.empty()){ + failed++; + result0.log(m_logger, max_log10p, sample.filepath); + if (!result0.results.empty()){ + trained.add_candidate( + language.first, sample.token, + result0.results.begin()->second.normalized_text + ); + } + return; + } + + for (const auto& item : result.results){ + if (item.second.token == sample.token){ + matched++; + return; + } + } + + result.log(m_logger, -99999, sample.filepath); + trained.add_candidate( + language.first, sample.token, + result0.results.begin()->second.normalized_text + ); + }, + 0, language.second.size(), 1 + ); + + m_scope.throw_if_cancelled(); + } + + m_logger.log("Languages: " + tostr_u_commas(m_samples.size())); + m_logger.log("Samples: " + tostr_u_commas(m_total_samples)); + m_logger.log("Matched: " + tostr_u_commas(matched)); + m_logger.log("Missed: " + tostr_u_commas(failed)); + + trained.save(output_json_file); +} + +void TrainingSession::generate_large_dictionary( + const std::string& ocr_json_directory, + const std::string& output_prefix, + bool incremental, + size_t threads, + const std::vector& text_color_ranges, + double max_log10p, double log10p_spread, + double min_text_ratio, double max_text_ratio +) const{ + m_logger.log("Generating OCR Data..."); + + OCR::LargeDictionaryMatcher baseline(ocr_json_directory + output_prefix, nullptr, !incremental); + OCR::LargeDictionaryMatcher trained(ocr_json_directory + output_prefix, nullptr, !incremental); + + ComputationThreadPool task_runner( + [&](){ GlobalSettings::instance().PERFORMANCE->COMPUTE_PRIORITY.set_on_this_thread(m_logger); }, + 0, threads + ); + + std::atomic matched(0); + std::atomic failed(0); + for (const auto& language : m_samples){ + const LanguageData& language_info = language_data(language.first); + m_logger.log("Starting Language: " + language_info.name); +// cout << (int)item.first << " : " << item.second.size() << endl; + + task_runner.run_in_parallel( + [&](size_t index){ + m_scope.throw_if_cancelled(); + + const TrainingSample& sample = language.second[index]; + + ImageRGB32 image(m_directory + sample.filepath); + if (!image){ + m_logger.log("Skipping: " + sample.filepath); + return; + } + + OCR::StringMatchResult result = baseline.match_substring_from_image_multifiltered( + nullptr, language.first, image, + text_color_ranges, + 0, log10p_spread, + min_text_ratio, max_text_ratio + ); + + OCR::StringMatchResult result0 = result; + result.clear_beyond_log10p(max_log10p); + + if (result.results.empty()){ + failed++; + result0.log(m_logger, max_log10p, sample.filepath); + if (!result0.results.empty()){ + trained.add_candidate( + language.first, sample.token, + result0.results.begin()->second.normalized_text + ); + } + return; + } + + for (const auto& item : result.results){ + if (item.second.token == sample.token){ + matched++; + return; + } + } + + result.log(m_logger, -99999, sample.filepath); + trained.add_candidate( + language.first, sample.token, + result0.results.begin()->second.normalized_text + ); + }, + 0, language.second.size(), 1 + ); + + std::string json = output_prefix + language_info.code + ".json"; + trained.save(language.first, json); + m_scope.throw_if_cancelled(); + } + + m_logger.log("Languages: " + tostr_u_commas(m_samples.size())); + m_logger.log("Samples: " + tostr_u_commas(m_total_samples)); + m_logger.log("Matched: " + tostr_u_commas(matched)); + m_logger.log("Missed: " + tostr_u_commas(failed)); +} + + + + + + +} +} + diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_TrainingTools.h b/SerialPrograms/Source/CommonTools/OCR/OCR_TrainingTools.h index 542b6704b1..dc4d84d5e6 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_TrainingTools.h +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_TrainingTools.h @@ -1,73 +1,73 @@ -/* Training Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_OCR_TrainingTools_H -#define PokemonAutomation_CommonTools_OCR_TrainingTools_H - -#include -#include -#include -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/CancellableScope.h" -#include "CommonFramework/Language.h" -#include "OCR_Routines.h" - -namespace PokemonAutomation{ -namespace OCR{ - - -struct TrainingSample{ - std::string token; - std::string filepath; -}; - - -class TrainingSession{ - static constexpr double MAX_LOG10P = -1.90; - static constexpr double LOG10P_SPREAD = 0.10; - -public: - TrainingSession( - Logger& logger, CancellableScope& scope, - const std::string& training_data_directory - ); - - void generate_small_dictionary( - const std::string& ocr_json_file, - const std::string& output_json_file, - bool incremental, - size_t threads, - const std::vector& text_color_ranges, - double max_log10p, double log10p_spread, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 - ); - void generate_large_dictionary( - const std::string& ocr_json_directory, - const std::string& output_prefix, - bool incremental, - size_t threads, - const std::vector& text_color_ranges, - double max_log10p, double log10p_spread, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 - ) const; - -private: - Logger& m_logger; - CancellableScope& m_scope; - std::string m_directory; - size_t m_total_samples; - std::map> m_samples; -}; - - - - -std::string extract_name(const std::string& filename); - - -} -} -#endif +/* Training Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_OCR_TrainingTools_H +#define PokemonAutomation_CommonTools_OCR_TrainingTools_H + +#include +#include +#include +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/CancellableScope.h" +#include "CommonFramework/Language.h" +#include "OCR_Routines.h" + +namespace PokemonAutomation{ +namespace OCR{ + + +struct TrainingSample{ + std::string token; + std::string filepath; +}; + + +class TrainingSession{ + static constexpr double MAX_LOG10P = -1.90; + static constexpr double LOG10P_SPREAD = 0.10; + +public: + TrainingSession( + Logger& logger, CancellableScope& scope, + const std::string& training_data_directory + ); + + void generate_small_dictionary( + const std::string& ocr_json_file, + const std::string& output_json_file, + bool incremental, + size_t threads, + const std::vector& text_color_ranges, + double max_log10p, double log10p_spread, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 + ); + void generate_large_dictionary( + const std::string& ocr_json_directory, + const std::string& output_prefix, + bool incremental, + size_t threads, + const std::vector& text_color_ranges, + double max_log10p, double log10p_spread, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 + ) const; + +private: + Logger& m_logger; + CancellableScope& m_scope; + std::string m_directory; + size_t m_total_samples; + std::map> m_samples; +}; + + + + +std::string extract_name(const std::string& filename); + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Options/LanguageOCROption.cpp b/SerialPrograms/Source/CommonTools/Options/LanguageOCROption.cpp index 4cad788249..fea4c71118 100644 --- a/SerialPrograms/Source/CommonTools/Options/LanguageOCROption.cpp +++ b/SerialPrograms/Source/CommonTools/Options/LanguageOCROption.cpp @@ -1,133 +1,133 @@ -/* Language OCR Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonTools/OCR/OCR_RawOCR.h" -#include "LanguageOCROption.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace OCR{ - - - -LanguageOCRCell::LanguageOCRCell( - const LanguageSet& languages, - LockMode lock_while_running, - bool required -) - : ConfigOption(lock_while_running) - , m_default(0) - , m_current(0) -{ - size_t index = 0; - if (!required && !languages[Language::None]){ - m_case_list.emplace_back( - Language::None, - true - ); - m_case_map.emplace( - std::piecewise_construct, - std::forward_as_tuple(Language::None), - std::forward_as_tuple(index) - ); - index++; - } - for (Language language : languages){ - m_case_list.emplace_back( - language, - language == Language::None || OCR::language_available(language) - ); - m_case_map.emplace( - std::piecewise_construct, - std::forward_as_tuple(language), - std::forward_as_tuple(index) - ); - index++; - } -} - - -void LanguageOCRCell::set(Language language){ - auto iter = m_case_map.find(language); - if (iter == m_case_map.end()){ - return; - } - if (iter->second != m_current.exchange(iter->second, std::memory_order_relaxed)){ - report_value_changed(this); - } -} - - -void LanguageOCRCell::load_json(const JsonValue& json){ - const std::string* str = json.to_string(); - if (str == nullptr){ - return; - } - Language language; - try{ - language = language_code_to_enum(*str); - }catch (const InternalProgramError& e){ - global_logger_tagged().log("Error loading json for language OCR option: " + e.message(), COLOR_RED); - return; - } - - auto iter = m_case_map.find(language); - if (iter == m_case_map.end()){ - const auto& lan_data = language_data(language); - global_logger_tagged().log( - "Warning: no language data for loaded language option " + lan_data.name + " (" + lan_data.code + ").", - COLOR_RED - ); - return; - } - m_current.store(iter->second, std::memory_order_relaxed); - report_value_changed(this); -} -JsonValue LanguageOCRCell::to_json() const{ - return language_data((Language)*this).code; -} - -std::string LanguageOCRCell::check_validity() const{ - return m_case_list[m_current.load(std::memory_order_relaxed)].second ? std::string() : "Language data is not available."; -} -void LanguageOCRCell::restore_defaults(){ - m_current.store(m_default, std::memory_order_relaxed); - report_value_changed(this); -} - - - - - - - - - - - -LanguageOCROption::LanguageOCROption( - std::string label, - const LanguageSet& languages, - LockMode lock_while_running, - bool required -) - : LanguageOCRCell(languages, lock_while_running, required) - , m_label(std::move(label)) -{} - - - - - -} -} - +/* Language OCR Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonTools/OCR/OCR_RawOCR.h" +#include "LanguageOCROption.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace OCR{ + + + +LanguageOCRCell::LanguageOCRCell( + const LanguageSet& languages, + LockMode lock_while_running, + bool required +) + : ConfigOption(lock_while_running) + , m_default(0) + , m_current(0) +{ + size_t index = 0; + if (!required && !languages[Language::None]){ + m_case_list.emplace_back( + Language::None, + true + ); + m_case_map.emplace( + std::piecewise_construct, + std::forward_as_tuple(Language::None), + std::forward_as_tuple(index) + ); + index++; + } + for (Language language : languages){ + m_case_list.emplace_back( + language, + language == Language::None || OCR::language_available(language) + ); + m_case_map.emplace( + std::piecewise_construct, + std::forward_as_tuple(language), + std::forward_as_tuple(index) + ); + index++; + } +} + + +void LanguageOCRCell::set(Language language){ + auto iter = m_case_map.find(language); + if (iter == m_case_map.end()){ + return; + } + if (iter->second != m_current.exchange(iter->second, std::memory_order_relaxed)){ + report_value_changed(this); + } +} + + +void LanguageOCRCell::load_json(const JsonValue& json){ + const std::string* str = json.to_string(); + if (str == nullptr){ + return; + } + Language language; + try{ + language = language_code_to_enum(*str); + }catch (const InternalProgramError& e){ + global_logger_tagged().log("Error loading json for language OCR option: " + e.message(), COLOR_RED); + return; + } + + auto iter = m_case_map.find(language); + if (iter == m_case_map.end()){ + const auto& lan_data = language_data(language); + global_logger_tagged().log( + "Warning: no language data for loaded language option " + lan_data.name + " (" + lan_data.code + ").", + COLOR_RED + ); + return; + } + m_current.store(iter->second, std::memory_order_relaxed); + report_value_changed(this); +} +JsonValue LanguageOCRCell::to_json() const{ + return language_data((Language)*this).code; +} + +std::string LanguageOCRCell::check_validity() const{ + return m_case_list[m_current.load(std::memory_order_relaxed)].second ? std::string() : "Language data is not available."; +} +void LanguageOCRCell::restore_defaults(){ + m_current.store(m_default, std::memory_order_relaxed); + report_value_changed(this); +} + + + + + + + + + + + +LanguageOCROption::LanguageOCROption( + std::string label, + const LanguageSet& languages, + LockMode lock_while_running, + bool required +) + : LanguageOCRCell(languages, lock_while_running, required) + , m_label(std::move(label)) +{} + + + + + +} +} + diff --git a/SerialPrograms/Source/CommonTools/Options/LanguageOCROption.h b/SerialPrograms/Source/CommonTools/Options/LanguageOCROption.h index 413d036a3c..c63fabca98 100644 --- a/SerialPrograms/Source/CommonTools/Options/LanguageOCROption.h +++ b/SerialPrograms/Source/CommonTools/Options/LanguageOCROption.h @@ -1,79 +1,79 @@ -/* Language OCR Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_Options_LanguageOCROption_H -#define PokemonAutomation_CommonTools_Options_LanguageOCROption_H - -#include -#include -#include -#include "Common/Cpp/Options/ConfigOption.h" -#include "CommonFramework/Language.h" - -namespace PokemonAutomation{ -namespace OCR{ - - -class LanguageOCRCell : public ConfigOption{ -public: - LanguageOCRCell( - const LanguageSet& languages, - LockMode lock_while_running, - bool required = true - ); - -// explicit operator bool() const{ return m_case_list[m_current].first != Language::None && m_case_list[m_current].second; } - - operator size_t() const{ return m_current; } - operator Language() const{ return m_case_list[m_current.load(std::memory_order_relaxed)].first; } - void set(Language language); - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual std::string check_validity() const override; - virtual void restore_defaults() override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - friend class LanguageOCRCellWidget; - - std::vector> m_case_list; - std::map m_case_map; - const size_t m_default; - - std::atomic m_current; -}; - - - - -class LanguageOCROption : public LanguageOCRCell{ -public: - LanguageOCROption( - std::string label, - const LanguageSet& languages, - LockMode lock_while_running, - bool required = true - ); - - const std::string& label() const{ return m_label; } - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - friend class LanguageOCROptionWidget; - - const std::string m_label; -}; - - - - -} -} -#endif +/* Language OCR Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_Options_LanguageOCROption_H +#define PokemonAutomation_CommonTools_Options_LanguageOCROption_H + +#include +#include +#include +#include "Common/Cpp/Options/ConfigOption.h" +#include "CommonFramework/Language.h" + +namespace PokemonAutomation{ +namespace OCR{ + + +class LanguageOCRCell : public ConfigOption{ +public: + LanguageOCRCell( + const LanguageSet& languages, + LockMode lock_while_running, + bool required = true + ); + +// explicit operator bool() const{ return m_case_list[m_current].first != Language::None && m_case_list[m_current].second; } + + operator size_t() const{ return m_current; } + operator Language() const{ return m_case_list[m_current.load(std::memory_order_relaxed)].first; } + void set(Language language); + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual std::string check_validity() const override; + virtual void restore_defaults() override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + friend class LanguageOCRCellWidget; + + std::vector> m_case_list; + std::map m_case_map; + const size_t m_default; + + std::atomic m_current; +}; + + + + +class LanguageOCROption : public LanguageOCRCell{ +public: + LanguageOCROption( + std::string label, + const LanguageSet& languages, + LockMode lock_while_running, + bool required = true + ); + + const std::string& label() const{ return m_label; } + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + friend class LanguageOCROptionWidget; + + const std::string m_label; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Options/QtWidgets/LanguageOCRWidget.cpp b/SerialPrograms/Source/CommonTools/Options/QtWidgets/LanguageOCRWidget.cpp index 1f590e5c89..c9df0bac7b 100644 --- a/SerialPrograms/Source/CommonTools/Options/QtWidgets/LanguageOCRWidget.cpp +++ b/SerialPrograms/Source/CommonTools/Options/QtWidgets/LanguageOCRWidget.cpp @@ -1,148 +1,148 @@ -/* Language OCR Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include "CommonFramework/Globals.h" -#include "Common/Qt/NoWheelComboBox.h" -#include "LanguageOCRWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace OCR{ - - - -ConfigWidget* LanguageOCRCell::make_QtWidget(QWidget& parent){ - return new LanguageOCRCellWidget(parent, *this); -} -ConfigWidget* LanguageOCROption::make_QtWidget(QWidget& parent){ - return new LanguageOCROptionWidget(parent, *this); -} - - - - -LanguageOCRCellWidget::LanguageOCRCellWidget(QWidget& parent, LanguageOCRCell& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - QVBoxLayout* vbox = new QVBoxLayout(this); - vbox->setContentsMargins(0, 0, 0, 0); - m_box = new NoWheelComboBox(&parent); - - for (const auto& item : m_value.m_case_list){ -// m_enum_to_index[item.first] = (int)m_index_to_enum.size(); - m_index_to_enum.emplace_back(item.first); - m_box->addItem(QString::fromStdString(language_data(item.first).name)); - auto* model = qobject_cast(m_box->model()); - if (model == nullptr){ - continue; - } - QStandardItem* line_handle = model->item(m_box->count() - 1); - if (line_handle != nullptr){ -// line_handle->setEnabled(item.second); - if (!item.second){ - QFont font = line_handle->font(); - font.setStrikeOut(true); - line_handle->setFont(font); - - QBrush brush = line_handle->foreground(); - brush.setColor(Qt::red); - line_handle->setForeground(brush); - } - } - } - vbox->addWidget(m_box); - - m_status = new QLabel(this); - m_status->setTextFormat(Qt::RichText); - m_status->setTextInteractionFlags(Qt::TextBrowserInteraction); - m_status->setOpenExternalLinks(true); - vbox->addWidget(m_status); - - LanguageOCRCellWidget::update_value(); - - connect( - m_box, static_cast(&QComboBox::activated), - this, [this](int index){ - if (index < 0){ - m_value.restore_defaults(); - return; - } - m_value.set(m_index_to_enum[index]); - } - ); -} - - -void LanguageOCRCellWidget::update_value(){ - size_t index = m_value; - m_box->setCurrentIndex((int)index); - - const std::pair& item = m_value.m_case_list[index]; - const LanguageData& language = language_data(item.first); - if (item.second){ - m_status->setVisible(false); - }else{ - m_status->setText( - QString::fromStdString( - "No text recognition data found for " + language.name + ".\n" + - "Download from here." - ) - ); - m_status->setVisible(true); - } -} -void LanguageOCRCellWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(m_box, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - - - - -LanguageOCROptionWidget::~LanguageOCROptionWidget(){ - m_value.remove_listener(*this); -} -LanguageOCROptionWidget::LanguageOCROptionWidget(QWidget& parent, LanguageOCROption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_cell(new LanguageOCRCellWidget(*this, value)) -{ - QHBoxLayout* layout = new QHBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - QLabel* text = new QLabel(QString::fromStdString(value.label()), this); - text->setWordWrap(true); - layout->addWidget(text, 1); - layout->addWidget(m_cell, 1); - value.add_listener(*this); -} - - -void LanguageOCROptionWidget::update_value(){ - m_cell->update_value(); -} -void LanguageOCROptionWidget::on_config_value_changed(void* object){ - m_cell->on_config_value_changed(object); -} - - - - - -} -} +/* Language OCR Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "CommonFramework/Globals.h" +#include "Common/Qt/NoWheelComboBox.h" +#include "LanguageOCRWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace OCR{ + + + +ConfigWidget* LanguageOCRCell::make_QtWidget(QWidget& parent){ + return new LanguageOCRCellWidget(parent, *this); +} +ConfigWidget* LanguageOCROption::make_QtWidget(QWidget& parent){ + return new LanguageOCROptionWidget(parent, *this); +} + + + + +LanguageOCRCellWidget::LanguageOCRCellWidget(QWidget& parent, LanguageOCRCell& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + QVBoxLayout* vbox = new QVBoxLayout(this); + vbox->setContentsMargins(0, 0, 0, 0); + m_box = new NoWheelComboBox(&parent); + + for (const auto& item : m_value.m_case_list){ +// m_enum_to_index[item.first] = (int)m_index_to_enum.size(); + m_index_to_enum.emplace_back(item.first); + m_box->addItem(QString::fromStdString(language_data(item.first).name)); + auto* model = qobject_cast(m_box->model()); + if (model == nullptr){ + continue; + } + QStandardItem* line_handle = model->item(m_box->count() - 1); + if (line_handle != nullptr){ +// line_handle->setEnabled(item.second); + if (!item.second){ + QFont font = line_handle->font(); + font.setStrikeOut(true); + line_handle->setFont(font); + + QBrush brush = line_handle->foreground(); + brush.setColor(Qt::red); + line_handle->setForeground(brush); + } + } + } + vbox->addWidget(m_box); + + m_status = new QLabel(this); + m_status->setTextFormat(Qt::RichText); + m_status->setTextInteractionFlags(Qt::TextBrowserInteraction); + m_status->setOpenExternalLinks(true); + vbox->addWidget(m_status); + + LanguageOCRCellWidget::update_value(); + + connect( + m_box, static_cast(&QComboBox::activated), + this, [this](int index){ + if (index < 0){ + m_value.restore_defaults(); + return; + } + m_value.set(m_index_to_enum[index]); + } + ); +} + + +void LanguageOCRCellWidget::update_value(){ + size_t index = m_value; + m_box->setCurrentIndex((int)index); + + const std::pair& item = m_value.m_case_list[index]; + const LanguageData& language = language_data(item.first); + if (item.second){ + m_status->setVisible(false); + }else{ + m_status->setText( + QString::fromStdString( + "No text recognition data found for " + language.name + ".\n" + + "Download from here." + ) + ); + m_status->setVisible(true); + } +} +void LanguageOCRCellWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(m_box, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + + + + +LanguageOCROptionWidget::~LanguageOCROptionWidget(){ + m_value.remove_listener(*this); +} +LanguageOCROptionWidget::LanguageOCROptionWidget(QWidget& parent, LanguageOCROption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_cell(new LanguageOCRCellWidget(*this, value)) +{ + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + QLabel* text = new QLabel(QString::fromStdString(value.label()), this); + text->setWordWrap(true); + layout->addWidget(text, 1); + layout->addWidget(m_cell, 1); + value.add_listener(*this); +} + + +void LanguageOCROptionWidget::update_value(){ + m_cell->update_value(); +} +void LanguageOCROptionWidget::on_config_value_changed(void* object){ + m_cell->on_config_value_changed(object); +} + + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/Options/QtWidgets/LanguageOCRWidget.h b/SerialPrograms/Source/CommonTools/Options/QtWidgets/LanguageOCRWidget.h index c32130c599..28118eb0e6 100644 --- a/SerialPrograms/Source/CommonTools/Options/QtWidgets/LanguageOCRWidget.h +++ b/SerialPrograms/Source/CommonTools/Options/QtWidgets/LanguageOCRWidget.h @@ -1,54 +1,54 @@ -/* Language OCR Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_Options_LanguageOCRWidget_H -#define PokemonAutomation_CommonTools_Options_LanguageOCRWidget_H - -#include -#include "Common/Qt/Options/ConfigWidget.h" -#include "CommonTools/Options/LanguageOCROption.h" - -class QLabel; -class QComboBox; - -namespace PokemonAutomation{ -namespace OCR{ - - -class LanguageOCRCellWidget : public QWidget, public ConfigWidget{ -public: - LanguageOCRCellWidget(QWidget& parent, LanguageOCRCell& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - LanguageOCRCell& m_value; - QComboBox* m_box; - QLabel* m_status; - std::vector m_index_to_enum; -// std::map m_enum_to_index; -}; - - - -class LanguageOCROptionWidget : public QWidget, public ConfigWidget{ -public: - ~LanguageOCROptionWidget(); - LanguageOCROptionWidget(QWidget& parent, LanguageOCROption& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - LanguageOCRCellWidget* m_cell; -}; - - - -} -} -#endif +/* Language OCR Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_Options_LanguageOCRWidget_H +#define PokemonAutomation_CommonTools_Options_LanguageOCRWidget_H + +#include +#include "Common/Qt/Options/ConfigWidget.h" +#include "CommonTools/Options/LanguageOCROption.h" + +class QLabel; +class QComboBox; + +namespace PokemonAutomation{ +namespace OCR{ + + +class LanguageOCRCellWidget : public QWidget, public ConfigWidget{ +public: + LanguageOCRCellWidget(QWidget& parent, LanguageOCRCell& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + LanguageOCRCell& m_value; + QComboBox* m_box; + QLabel* m_status; + std::vector m_index_to_enum; +// std::map m_enum_to_index; +}; + + + +class LanguageOCROptionWidget : public QWidget, public ConfigWidget{ +public: + ~LanguageOCROptionWidget(); + LanguageOCROptionWidget(QWidget& parent, LanguageOCROption& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + LanguageOCRCellWidget* m_cell; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Options/QtWidgets/ScreenWatchWidget.cpp b/SerialPrograms/Source/CommonTools/Options/QtWidgets/ScreenWatchWidget.cpp index 7b3d7ce48c..3680f64bbf 100644 --- a/SerialPrograms/Source/CommonTools/Options/QtWidgets/ScreenWatchWidget.cpp +++ b/SerialPrograms/Source/CommonTools/Options/QtWidgets/ScreenWatchWidget.cpp @@ -1,235 +1,235 @@ -/* Screen Watch Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "ScreenWatchWidget.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - -ConfigWidget* ScreenWatchDisplay::make_QtWidget(QWidget& parent){ - return new ScreenWatchWidget(*this, parent); -} -ConfigWidget* ScreenWatchButtons::make_QtWidget(QWidget& parent){ - return new ScreenWatchButtonWidget(m_option, parent); -} - - -ScreenWatchDisplayWidget::ScreenWatchDisplayWidget(ScreenWatchOption& option, ScreenWatchWidget& parent) - : QWidget(&parent) - , m_holder(parent) - , m_option(option) - , m_stop(false) - , m_updater(&ScreenWatchDisplayWidget::thread_loop, this) -{} -ScreenWatchDisplayWidget::~ScreenWatchDisplayWidget(){ - { - std::lock_guard lg(m_lock); - m_stop = true; - m_cv.notify_all(); - } - m_updater.join(); -} -void ScreenWatchDisplayWidget::paintEvent(QPaintEvent* event){ -// cout << "ScreenWatchDisplayWidget::paintEvent: " << m_holder.width() << " x " << m_holder.height() << endl; - QWidget::paintEvent(event); - - VideoSnapshot snapshot = m_last_frame; - if (!snapshot){ - return; - } - - double aspect_ratio = (double)snapshot.frame->width() / snapshot.frame->height(); - if (aspect_ratio < 2.0){ -// cout << "ScreenWatchDisplayWidget::paintEvent: box " << m_holder.width() << " x " << m_holder.height() << endl; - m_holder.set_all(WidgetStackFixedAspectRatio::EXPAND_TO_BOX, aspect_ratio); - m_holder.setFixedHeight(m_holder.width() / 2); - }else{ -// cout << "ScreenWatchDisplayWidget::paintEvent: adjust " << m_holder.width() << " x " << m_holder.height() << endl; - m_holder.set_all(WidgetStackFixedAspectRatio::ADJUST_HEIGHT_TO_WIDTH, aspect_ratio); - } - - QRect rect(0, 0, this->width(), this->height()); - QPainter painter(this); - painter.drawImage(rect, snapshot.frame->to_QImage_ref()); -} - - -void ScreenWatchDisplayWidget::thread_loop(){ - std::unique_lock lg(m_lock); - while (!m_stop){ - m_last_frame = m_option.screenshot(); - QMetaObject::invokeMethod(this, [&]{ - this->update(); - }, Qt::QueuedConnection); - m_cv.wait_for(lg, std::chrono::milliseconds(100)); - } -} - -ScreenWatchWidget::ScreenWatchWidget(ScreenWatchDisplay& option, QWidget& parent) - : WidgetStackFixedAspectRatio(parent, ADJUST_HEIGHT_TO_WIDTH) - , ConfigWidget(option, *this) -{ - m_widget = new ScreenWatchDisplayWidget(option.m_option, *this); - add_widget(*m_widget); - m_overlay = new VideoOverlayWidget(*this, option.m_option.overlay()); - add_widget(*m_overlay); -} - - - -class SelectorOverlay : public QDialog{ -public: - SelectorOverlay(ScreenWatchOption& option, QWidget& parent, QScreen& screen) - : QDialog(&parent, Qt::FramelessWindowHint) - , m_screen(screen.size()) - { - setAttribute(Qt::WA_TranslucentBackground); - setGeometry(screen.geometry()); - } - - virtual void keyPressEvent(QKeyEvent* event) override{ -// cout << event->key() << endl; - switch (event->key()){ - case Qt::Key_Return: - case Qt::Key_Enter: - case Qt::Key_Escape: - this->accept(); - break; - default: - QDialog::keyPressEvent(event); - } - } - virtual void mousePressEvent(QMouseEvent* event) override{ -// cout << event->globalPos().x() << ", " << event->globalPos().y() << endl; - m_mouse_down = true; - m_selected_rect = QRect(); - m_selected_rect.setTopLeft(event->pos()); - m_selected_rect.setWidth(0); - m_selected_rect.setHeight(0); - } - virtual void mouseReleaseEvent(QMouseEvent* event) override{ - m_mouse_down = false; - } - virtual void mouseMoveEvent(QMouseEvent* event) override{ -// cout << event->globalPos().x() << ", " << event->globalPos().y() << endl; - if (m_mouse_down){ - m_selected_rect.setBottomRight(event->pos()); - } - update(); - } - virtual void paintEvent(QPaintEvent* event) override{ - QRect rect(0, 0, this->width(), this->height()); - QPainter painter(this); - painter.fillRect(rect, QColor::fromRgb(255, 255, 255, 128)); - - painter.setPen(Qt::red); - painter.fillRect(m_selected_rect, QColor::fromRgb(255, 255, 0, 192)); -// cout << m_selected_rect.x() << ", " << m_selected_rect.y() << " - " << m_selected_rect.width() << ", " << m_selected_rect.height() << endl; - } - - ImageFloatBox get_box() const{ - int x = m_selected_rect.x(); - int y = m_selected_rect.y(); - int w = m_selected_rect.width(); - int h = m_selected_rect.height(); - if (w < 0){ - x += w; - w = -w; - } - if (h < 0){ - y += h; - h = -h; - } - double inv_width = 1 / (double)m_screen.width(); - double inv_height = 1 / (double)m_screen.height(); - return { - x * inv_width, - y * inv_height, - w * inv_width, - h * inv_height, - }; - } - -private: - QSize m_screen; - bool m_mouse_down = false; - QRect m_selected_rect; -}; - - - - -ScreenWatchButtonWidget::ScreenWatchButtonWidget(ScreenWatchOption& option, QWidget& parent) - : QWidget(&parent) - , ConfigWidget(option, *this) -{ - QVBoxLayout* layout = new QVBoxLayout(this); - - QPushButton* draw_box = new QPushButton("Draw Box", this); - QPushButton* reset_button = new QPushButton("Reset to Full Screen", this); - - QHBoxLayout* buttons = new QHBoxLayout(); - layout->addLayout(buttons); - buttons->addWidget(draw_box); - buttons->addWidget(reset_button); - - layout->addWidget(new QLabel("Click on \"Draw Box\" and click+drag to select a region on the target monitor. Press ESC when done.")); - - connect( - draw_box, &QPushButton::clicked, - this, [&](bool){ - qsizetype index = (qsizetype)option.MONITOR_INDEX; - auto screens = QGuiApplication::screens(); - if (screens.size() <= index){ - return; - } - - SelectorOverlay w(option, *this, *screens[index]); - w.exec(); - - ImageFloatBox box = w.get_box(); - if (box.width == 0 || box.height == 0){ - return; - } - - option.X.set(box.x); - option.Y.set(box.y); - option.WIDTH.set(box.width); - option.HEIGHT.set(box.height); - } - ); - - connect( - reset_button, &QPushButton::clicked, - this, [&](bool){ - option.X.set(0.0); - option.Y.set(0.0); - option.WIDTH.set(1.0); - option.HEIGHT.set(1.0); - } - ); -} - - - - - - -} - +/* Screen Watch Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "ScreenWatchWidget.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + +ConfigWidget* ScreenWatchDisplay::make_QtWidget(QWidget& parent){ + return new ScreenWatchWidget(*this, parent); +} +ConfigWidget* ScreenWatchButtons::make_QtWidget(QWidget& parent){ + return new ScreenWatchButtonWidget(m_option, parent); +} + + +ScreenWatchDisplayWidget::ScreenWatchDisplayWidget(ScreenWatchOption& option, ScreenWatchWidget& parent) + : QWidget(&parent) + , m_holder(parent) + , m_option(option) + , m_stop(false) + , m_updater(&ScreenWatchDisplayWidget::thread_loop, this) +{} +ScreenWatchDisplayWidget::~ScreenWatchDisplayWidget(){ + { + std::lock_guard lg(m_lock); + m_stop = true; + m_cv.notify_all(); + } + m_updater.join(); +} +void ScreenWatchDisplayWidget::paintEvent(QPaintEvent* event){ +// cout << "ScreenWatchDisplayWidget::paintEvent: " << m_holder.width() << " x " << m_holder.height() << endl; + QWidget::paintEvent(event); + + VideoSnapshot snapshot = m_last_frame; + if (!snapshot){ + return; + } + + double aspect_ratio = (double)snapshot.frame->width() / snapshot.frame->height(); + if (aspect_ratio < 2.0){ +// cout << "ScreenWatchDisplayWidget::paintEvent: box " << m_holder.width() << " x " << m_holder.height() << endl; + m_holder.set_all(WidgetStackFixedAspectRatio::EXPAND_TO_BOX, aspect_ratio); + m_holder.setFixedHeight(m_holder.width() / 2); + }else{ +// cout << "ScreenWatchDisplayWidget::paintEvent: adjust " << m_holder.width() << " x " << m_holder.height() << endl; + m_holder.set_all(WidgetStackFixedAspectRatio::ADJUST_HEIGHT_TO_WIDTH, aspect_ratio); + } + + QRect rect(0, 0, this->width(), this->height()); + QPainter painter(this); + painter.drawImage(rect, snapshot.frame->to_QImage_ref()); +} + + +void ScreenWatchDisplayWidget::thread_loop(){ + std::unique_lock lg(m_lock); + while (!m_stop){ + m_last_frame = m_option.screenshot(); + QMetaObject::invokeMethod(this, [&]{ + this->update(); + }, Qt::QueuedConnection); + m_cv.wait_for(lg, std::chrono::milliseconds(100)); + } +} + +ScreenWatchWidget::ScreenWatchWidget(ScreenWatchDisplay& option, QWidget& parent) + : WidgetStackFixedAspectRatio(parent, ADJUST_HEIGHT_TO_WIDTH) + , ConfigWidget(option, *this) +{ + m_widget = new ScreenWatchDisplayWidget(option.m_option, *this); + add_widget(*m_widget); + m_overlay = new VideoOverlayWidget(*this, option.m_option.overlay()); + add_widget(*m_overlay); +} + + + +class SelectorOverlay : public QDialog{ +public: + SelectorOverlay(ScreenWatchOption& option, QWidget& parent, QScreen& screen) + : QDialog(&parent, Qt::FramelessWindowHint) + , m_screen(screen.size()) + { + setAttribute(Qt::WA_TranslucentBackground); + setGeometry(screen.geometry()); + } + + virtual void keyPressEvent(QKeyEvent* event) override{ +// cout << event->key() << endl; + switch (event->key()){ + case Qt::Key_Return: + case Qt::Key_Enter: + case Qt::Key_Escape: + this->accept(); + break; + default: + QDialog::keyPressEvent(event); + } + } + virtual void mousePressEvent(QMouseEvent* event) override{ +// cout << event->globalPos().x() << ", " << event->globalPos().y() << endl; + m_mouse_down = true; + m_selected_rect = QRect(); + m_selected_rect.setTopLeft(event->pos()); + m_selected_rect.setWidth(0); + m_selected_rect.setHeight(0); + } + virtual void mouseReleaseEvent(QMouseEvent* event) override{ + m_mouse_down = false; + } + virtual void mouseMoveEvent(QMouseEvent* event) override{ +// cout << event->globalPos().x() << ", " << event->globalPos().y() << endl; + if (m_mouse_down){ + m_selected_rect.setBottomRight(event->pos()); + } + update(); + } + virtual void paintEvent(QPaintEvent* event) override{ + QRect rect(0, 0, this->width(), this->height()); + QPainter painter(this); + painter.fillRect(rect, QColor::fromRgb(255, 255, 255, 128)); + + painter.setPen(Qt::red); + painter.fillRect(m_selected_rect, QColor::fromRgb(255, 255, 0, 192)); +// cout << m_selected_rect.x() << ", " << m_selected_rect.y() << " - " << m_selected_rect.width() << ", " << m_selected_rect.height() << endl; + } + + ImageFloatBox get_box() const{ + int x = m_selected_rect.x(); + int y = m_selected_rect.y(); + int w = m_selected_rect.width(); + int h = m_selected_rect.height(); + if (w < 0){ + x += w; + w = -w; + } + if (h < 0){ + y += h; + h = -h; + } + double inv_width = 1 / (double)m_screen.width(); + double inv_height = 1 / (double)m_screen.height(); + return { + x * inv_width, + y * inv_height, + w * inv_width, + h * inv_height, + }; + } + +private: + QSize m_screen; + bool m_mouse_down = false; + QRect m_selected_rect; +}; + + + + +ScreenWatchButtonWidget::ScreenWatchButtonWidget(ScreenWatchOption& option, QWidget& parent) + : QWidget(&parent) + , ConfigWidget(option, *this) +{ + QVBoxLayout* layout = new QVBoxLayout(this); + + QPushButton* draw_box = new QPushButton("Draw Box", this); + QPushButton* reset_button = new QPushButton("Reset to Full Screen", this); + + QHBoxLayout* buttons = new QHBoxLayout(); + layout->addLayout(buttons); + buttons->addWidget(draw_box); + buttons->addWidget(reset_button); + + layout->addWidget(new QLabel("Click on \"Draw Box\" and click+drag to select a region on the target monitor. Press ESC when done.")); + + connect( + draw_box, &QPushButton::clicked, + this, [&](bool){ + qsizetype index = (qsizetype)option.MONITOR_INDEX; + auto screens = QGuiApplication::screens(); + if (screens.size() <= index){ + return; + } + + SelectorOverlay w(option, *this, *screens[index]); + w.exec(); + + ImageFloatBox box = w.get_box(); + if (box.width == 0 || box.height == 0){ + return; + } + + option.X.set(box.x); + option.Y.set(box.y); + option.WIDTH.set(box.width); + option.HEIGHT.set(box.height); + } + ); + + connect( + reset_button, &QPushButton::clicked, + this, [&](bool){ + option.X.set(0.0); + option.Y.set(0.0); + option.WIDTH.set(1.0); + option.HEIGHT.set(1.0); + } + ); +} + + + + + + +} + diff --git a/SerialPrograms/Source/CommonTools/Options/QtWidgets/ScreenWatchWidget.h b/SerialPrograms/Source/CommonTools/Options/QtWidgets/ScreenWatchWidget.h index e7166a3f98..8a567fbf4b 100644 --- a/SerialPrograms/Source/CommonTools/Options/QtWidgets/ScreenWatchWidget.h +++ b/SerialPrograms/Source/CommonTools/Options/QtWidgets/ScreenWatchWidget.h @@ -1,60 +1,60 @@ -/* Screen Watch Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_Options_ScreenWatchWidget_H -#define PokemonAutomation_CommonTools_Options_ScreenWatchWidget_H - -#include -#include -#include -#include -#include "Common/Qt/WidgetStackFixedAspectRatio.h" -#include "Common/Qt/Options/ConfigWidget.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/UI/VideoOverlayWidget.h" -#include "CommonTools/Options/ScreenWatchOption.h" - -namespace PokemonAutomation{ - -class ScreenWatchWidget; - - -class ScreenWatchDisplayWidget : public QWidget{ -public: - ScreenWatchDisplayWidget(ScreenWatchOption& option, ScreenWatchWidget& parent); - ~ScreenWatchDisplayWidget(); - void paintEvent(QPaintEvent* event) override; - -private: - void thread_loop(); - -private: - ScreenWatchWidget& m_holder; - ScreenWatchOption& m_option; - std::mutex m_lock; - std::condition_variable m_cv; - bool m_stop; - VideoSnapshot m_last_frame; - std::thread m_updater; -}; - -class ScreenWatchWidget : public WidgetStackFixedAspectRatio, public ConfigWidget{ -public: - ScreenWatchWidget(ScreenWatchDisplay& option, QWidget& parent); - -private: - QWidget* m_widget; - VideoOverlayWidget* m_overlay; -}; - -class ScreenWatchButtonWidget : public QWidget, public ConfigWidget{ -public: - ScreenWatchButtonWidget(ScreenWatchOption& option, QWidget& parent); -}; - - -} -#endif +/* Screen Watch Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_Options_ScreenWatchWidget_H +#define PokemonAutomation_CommonTools_Options_ScreenWatchWidget_H + +#include +#include +#include +#include +#include "Common/Qt/WidgetStackFixedAspectRatio.h" +#include "Common/Qt/Options/ConfigWidget.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/UI/VideoOverlayWidget.h" +#include "CommonTools/Options/ScreenWatchOption.h" + +namespace PokemonAutomation{ + +class ScreenWatchWidget; + + +class ScreenWatchDisplayWidget : public QWidget{ +public: + ScreenWatchDisplayWidget(ScreenWatchOption& option, ScreenWatchWidget& parent); + ~ScreenWatchDisplayWidget(); + void paintEvent(QPaintEvent* event) override; + +private: + void thread_loop(); + +private: + ScreenWatchWidget& m_holder; + ScreenWatchOption& m_option; + std::mutex m_lock; + std::condition_variable m_cv; + bool m_stop; + VideoSnapshot m_last_frame; + std::thread m_updater; +}; + +class ScreenWatchWidget : public WidgetStackFixedAspectRatio, public ConfigWidget{ +public: + ScreenWatchWidget(ScreenWatchDisplay& option, QWidget& parent); + +private: + QWidget* m_widget; + VideoOverlayWidget* m_overlay; +}; + +class ScreenWatchButtonWidget : public QWidget, public ConfigWidget{ +public: + ScreenWatchButtonWidget(ScreenWatchOption& option, QWidget& parent); +}; + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Options/QtWidgets/StringSelectWidget.cpp b/SerialPrograms/Source/CommonTools/Options/QtWidgets/StringSelectWidget.cpp index 03138f60e6..01a4385768 100644 --- a/SerialPrograms/Source/CommonTools/Options/QtWidgets/StringSelectWidget.cpp +++ b/SerialPrograms/Source/CommonTools/Options/QtWidgets/StringSelectWidget.cpp @@ -1,192 +1,192 @@ -/* String Select - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Logging/Logger.h" -#include "StringSelectWidget.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - - -ConfigWidget* StringSelectCell::make_QtWidget(QWidget& parent){ - return new StringSelectCellWidget(parent, *this); -} -ConfigWidget* StringSelectOption::make_QtWidget(QWidget& parent){ - return new StringSelectOptionWidget(parent, *this); -} - - - - -StringSelectCellWidget::~StringSelectCellWidget(){ - m_value.remove_listener(*this); -} -StringSelectCellWidget::StringSelectCellWidget(QWidget& parent, StringSelectCell& value) - : NoWheelComboBox(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - this->setEditable(true); - this->setInsertPolicy(QComboBox::NoInsert); - this->completer()->setCompletionMode(QCompleter::PopupCompletion); - this->completer()->setFilterMode(Qt::MatchContains); - this->setIconSize(QSize(25, 25)); -// this->setFrame(false); - - const StringSelectEntry& entry = value.entry(); - QPixmap pixmap = QPixmap::fromImage(entry.icon.to_QImage_ref()); - this->addItem(pixmap, QString::fromStdString(entry.display_name)); - this->setCurrentIndex(0); -// this->setMinimumContentsLength((int)value.database().longest_text_length()); - - StringSelectCellWidget::update_value(); - - QPalette palette; - palette.setColor(QPalette::Text, QColor((uint32_t)entry.text_color)); - this->lineEdit()->setPalette(palette); - - connect( - this, static_cast(&QComboBox::activated), - this, [this](int index){ - if (index < 0){ - m_value.restore_defaults(); - return; - } - m_value.set_by_name(this->itemText(index).toStdString()); -// cout << "index = " << index << endl; - } - ); - - value.add_listener(*this); -} - -void StringSelectCellWidget::load_options(){ -// cout << "load_options()" << endl; - const std::vector& cases = m_value.database().case_list(); - if (this->count() <= 1){ - global_logger_tagged().log("Loading dropdown with " + tostr_u_commas(cases.size()) + " elements."); - this->clear(); - for (const StringSelectEntry& item : cases){ - QPixmap pixmap = QPixmap::fromImage(item.icon.to_QImage_ref()); - this->addItem(pixmap, QString::fromStdString(item.display_name)); - if (item.text_color){ - this->setItemData(this->count() - 1, QBrush(QColor((uint32_t)item.text_color)), Qt::ForegroundRole); - } - } - } - size_t index = m_value.index(); - this->setCurrentIndex((int)index); - - QPalette palette; - palette.setColor(QPalette::Text, QColor((uint32_t)cases[index].text_color)); -// palette.setColor(QPalette::Text, Qt::red); - this->lineEdit()->setPalette(palette); - - update_size_cache(); -} -void StringSelectCellWidget::hide_options(){ -// cout << "hide_options()" << endl; - do{ - // All options shown. - if (this->count() > 1){ - break; - } - - // No valid index. - int ui_index = this->currentIndex(); - if (ui_index < 0){ - break; - } - - // Mismatching selection. - std::string name = this->itemText(ui_index).toStdString(); - if (name != m_value.display_name()){ - break; - } - - return; - }while (false); - - // Remove all elements and add the one that is selected. - this->clear(); - const StringSelectEntry& entry = m_value.entry(); - QPixmap pixmap = QPixmap::fromImage(entry.icon.to_QImage_ref()); - this->addItem(pixmap, QString::fromStdString(entry.display_name)); - this->setCurrentIndex(0); - - QPalette palette; - palette.setColor(QPalette::Text, QColor((uint32_t)entry.text_color)); -// palette.setColor(QPalette::Text, Qt::red); - this->lineEdit()->setPalette(palette); - -} -QSize StringSelectCellWidget::sizeHint() const{ - QSize ret = NoWheelComboBox::sizeHint(); -// cout << ret.width() << " x " << ret.height() << endl; - - double width = ret.width(); - double height = ret.height(); - - width *= 1.25; - height *= 1.25; - - return QSize((int)width, (int)height); -} -void StringSelectCellWidget::focusInEvent(QFocusEvent* event){ -// cout << "focusInEvent()" << endl; - update_value(); - NoWheelComboBox::focusInEvent(event); -} -void StringSelectCellWidget::focusOutEvent(QFocusEvent* event){ -// cout << "focusOutEvent()" << endl; - NoWheelComboBox::focusOutEvent(event); -// update_value(); -} -void StringSelectCellWidget::update_value(){ - if (hasFocus()){ - load_options(); - }else{ - hide_options(); - } -} -void StringSelectCellWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(this, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - - - -StringSelectOptionWidget::StringSelectOptionWidget(QWidget& parent, StringSelectOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_cell(new StringSelectCellWidget(parent, value)) -{ - QHBoxLayout* layout = new QHBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - QLabel* text = new QLabel(QString::fromStdString(value.label()), this); - text->setWordWrap(true); - layout->addWidget(text, 1); - layout->addWidget(m_cell, 1); -} - - - - - -} +/* String Select + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Logging/Logger.h" +#include "StringSelectWidget.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + + +ConfigWidget* StringSelectCell::make_QtWidget(QWidget& parent){ + return new StringSelectCellWidget(parent, *this); +} +ConfigWidget* StringSelectOption::make_QtWidget(QWidget& parent){ + return new StringSelectOptionWidget(parent, *this); +} + + + + +StringSelectCellWidget::~StringSelectCellWidget(){ + m_value.remove_listener(*this); +} +StringSelectCellWidget::StringSelectCellWidget(QWidget& parent, StringSelectCell& value) + : NoWheelComboBox(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + this->setEditable(true); + this->setInsertPolicy(QComboBox::NoInsert); + this->completer()->setCompletionMode(QCompleter::PopupCompletion); + this->completer()->setFilterMode(Qt::MatchContains); + this->setIconSize(QSize(25, 25)); +// this->setFrame(false); + + const StringSelectEntry& entry = value.entry(); + QPixmap pixmap = QPixmap::fromImage(entry.icon.to_QImage_ref()); + this->addItem(pixmap, QString::fromStdString(entry.display_name)); + this->setCurrentIndex(0); +// this->setMinimumContentsLength((int)value.database().longest_text_length()); + + StringSelectCellWidget::update_value(); + + QPalette palette; + palette.setColor(QPalette::Text, QColor((uint32_t)entry.text_color)); + this->lineEdit()->setPalette(palette); + + connect( + this, static_cast(&QComboBox::activated), + this, [this](int index){ + if (index < 0){ + m_value.restore_defaults(); + return; + } + m_value.set_by_name(this->itemText(index).toStdString()); +// cout << "index = " << index << endl; + } + ); + + value.add_listener(*this); +} + +void StringSelectCellWidget::load_options(){ +// cout << "load_options()" << endl; + const std::vector& cases = m_value.database().case_list(); + if (this->count() <= 1){ + global_logger_tagged().log("Loading dropdown with " + tostr_u_commas(cases.size()) + " elements."); + this->clear(); + for (const StringSelectEntry& item : cases){ + QPixmap pixmap = QPixmap::fromImage(item.icon.to_QImage_ref()); + this->addItem(pixmap, QString::fromStdString(item.display_name)); + if (item.text_color){ + this->setItemData(this->count() - 1, QBrush(QColor((uint32_t)item.text_color)), Qt::ForegroundRole); + } + } + } + size_t index = m_value.index(); + this->setCurrentIndex((int)index); + + QPalette palette; + palette.setColor(QPalette::Text, QColor((uint32_t)cases[index].text_color)); +// palette.setColor(QPalette::Text, Qt::red); + this->lineEdit()->setPalette(palette); + + update_size_cache(); +} +void StringSelectCellWidget::hide_options(){ +// cout << "hide_options()" << endl; + do{ + // All options shown. + if (this->count() > 1){ + break; + } + + // No valid index. + int ui_index = this->currentIndex(); + if (ui_index < 0){ + break; + } + + // Mismatching selection. + std::string name = this->itemText(ui_index).toStdString(); + if (name != m_value.display_name()){ + break; + } + + return; + }while (false); + + // Remove all elements and add the one that is selected. + this->clear(); + const StringSelectEntry& entry = m_value.entry(); + QPixmap pixmap = QPixmap::fromImage(entry.icon.to_QImage_ref()); + this->addItem(pixmap, QString::fromStdString(entry.display_name)); + this->setCurrentIndex(0); + + QPalette palette; + palette.setColor(QPalette::Text, QColor((uint32_t)entry.text_color)); +// palette.setColor(QPalette::Text, Qt::red); + this->lineEdit()->setPalette(palette); + +} +QSize StringSelectCellWidget::sizeHint() const{ + QSize ret = NoWheelComboBox::sizeHint(); +// cout << ret.width() << " x " << ret.height() << endl; + + double width = ret.width(); + double height = ret.height(); + + width *= 1.25; + height *= 1.25; + + return QSize((int)width, (int)height); +} +void StringSelectCellWidget::focusInEvent(QFocusEvent* event){ +// cout << "focusInEvent()" << endl; + update_value(); + NoWheelComboBox::focusInEvent(event); +} +void StringSelectCellWidget::focusOutEvent(QFocusEvent* event){ +// cout << "focusOutEvent()" << endl; + NoWheelComboBox::focusOutEvent(event); +// update_value(); +} +void StringSelectCellWidget::update_value(){ + if (hasFocus()){ + load_options(); + }else{ + hide_options(); + } +} +void StringSelectCellWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(this, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + + + +StringSelectOptionWidget::StringSelectOptionWidget(QWidget& parent, StringSelectOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_cell(new StringSelectCellWidget(parent, value)) +{ + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + QLabel* text = new QLabel(QString::fromStdString(value.label()), this); + text->setWordWrap(true); + layout->addWidget(text, 1); + layout->addWidget(m_cell, 1); +} + + + + + +} diff --git a/SerialPrograms/Source/CommonTools/Options/QtWidgets/StringSelectWidget.h b/SerialPrograms/Source/CommonTools/Options/QtWidgets/StringSelectWidget.h index 90d5a9c3c5..e97469dbe3 100644 --- a/SerialPrograms/Source/CommonTools/Options/QtWidgets/StringSelectWidget.h +++ b/SerialPrograms/Source/CommonTools/Options/QtWidgets/StringSelectWidget.h @@ -1,51 +1,51 @@ -/* String Select - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_Options_StringSelectWidget_H -#define PokemonAutomation_CommonTools_Options_StringSelectWidget_H - -#include -#include "Common/Qt/NoWheelComboBox.h" -#include "Common/Qt/Options/ConfigWidget.h" -#include "CommonTools/Options/StringSelectOption.h" - -namespace PokemonAutomation{ - - -class StringSelectCellWidget : public NoWheelComboBox, public ConfigWidget{ -public: - ~StringSelectCellWidget(); - StringSelectCellWidget(QWidget& parent, StringSelectCell& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - void load_options(); - void hide_options(); - - virtual QSize sizeHint() const override; - virtual void focusInEvent(QFocusEvent* event) override; - virtual void focusOutEvent(QFocusEvent* event) override; - -private: - StringSelectCell& m_value; -}; - - - -class StringSelectOptionWidget : public QWidget, public ConfigWidget{ -public: - StringSelectOptionWidget(QWidget& parent, StringSelectOption& value); - -private: - StringSelectCellWidget* m_cell; -}; - - - -} -#endif +/* String Select + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_Options_StringSelectWidget_H +#define PokemonAutomation_CommonTools_Options_StringSelectWidget_H + +#include +#include "Common/Qt/NoWheelComboBox.h" +#include "Common/Qt/Options/ConfigWidget.h" +#include "CommonTools/Options/StringSelectOption.h" + +namespace PokemonAutomation{ + + +class StringSelectCellWidget : public NoWheelComboBox, public ConfigWidget{ +public: + ~StringSelectCellWidget(); + StringSelectCellWidget(QWidget& parent, StringSelectCell& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + void load_options(); + void hide_options(); + + virtual QSize sizeHint() const override; + virtual void focusInEvent(QFocusEvent* event) override; + virtual void focusOutEvent(QFocusEvent* event) override; + +private: + StringSelectCell& m_value; +}; + + + +class StringSelectOptionWidget : public QWidget, public ConfigWidget{ +public: + StringSelectOptionWidget(QWidget& parent, StringSelectOption& value); + +private: + StringSelectCellWidget* m_cell; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Options/ScreenWatchOption.cpp b/SerialPrograms/Source/CommonTools/Options/ScreenWatchOption.cpp index 0f8fa01944..f85fc31d69 100644 --- a/SerialPrograms/Source/CommonTools/Options/ScreenWatchOption.cpp +++ b/SerialPrograms/Source/CommonTools/Options/ScreenWatchOption.cpp @@ -1,120 +1,120 @@ -/* Screen Watch Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "ScreenWatchOption.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - - -ScreenWatchOption::~ScreenWatchOption() = default; -ScreenWatchOption::ScreenWatchOption( - std::string label, - double default_x, double default_y, - double default_width, double default_height -) - : GroupOption(std::move(label), LockMode::UNLOCK_WHILE_RUNNING) - , MONITOR_INDEX( - "Monitor Index: For multi-monitor setups, this lets you choose which monitor to watch.", - LockMode::UNLOCK_WHILE_RUNNING, - 0 - ) - , X( - "X Coordinate: The left edge of the box to watch.
" - "0.0 is the left edge of the monitor. 1.0 is the right edge of the monitor.", - LockMode::UNLOCK_WHILE_RUNNING, - default_x, 0.0, 1.0 - ) - , Y( - "Y Coordinate: The top edge of the box to watch.
" - "0.0 is the top edge of the monitor. 1.0 is the bottom edge of the monitor.", - LockMode::UNLOCK_WHILE_RUNNING, - default_y, 0.0, 1.0 - ) - , WIDTH( - "Width: The width of the box to watch.
" - "The number is between 0 and 1 and is the proportion of the full width of the monitor.", - LockMode::UNLOCK_WHILE_RUNNING, - default_width, 0.0, 1.0 - ) - , HEIGHT( - "Height: The height of the box to watch.
" - "The number is between 0 and 1 and is the proportion of the full height of the monitor.", - LockMode::UNLOCK_WHILE_RUNNING, - default_height, 0.0, 1.0 - ) - , m_display(*this) - , m_buttons(*this) - , m_overlay(m_overlay_option) -{ - PA_ADD_OPTION(m_display); - PA_ADD_OPTION(MONITOR_INDEX); - PA_ADD_OPTION(X); - PA_ADD_OPTION(Y); - PA_ADD_OPTION(WIDTH); - PA_ADD_OPTION(HEIGHT); - PA_ADD_OPTION(m_buttons); -} - - -double ScreenWatchOption::aspect_ratio(){ - qsizetype index = (qsizetype)MONITOR_INDEX; - auto screens = QGuiApplication::screens(); - if (screens.size() <= index){ - return 0; - } - - QScreen& screen = *screens[index]; - - QSize size = screen.size(); - int width = (int)(size.width() * WIDTH + 0.5); - int height = (int)(size.height() * HEIGHT + 0.5); - return (double)width / height; -} -VideoSnapshot ScreenWatchOption::screenshot(){ - qsizetype index = (qsizetype)MONITOR_INDEX; - auto screens = QGuiApplication::screens(); - if (screens.size() <= index){ - return VideoSnapshot(); - } - - QScreen& screen = *screens[index]; - - QSize size = screen.size(); -// int width = screen.size().width(); -// int height = screen.size().height(); - - int min_x = (int)(size.width() * X + 0.5); - int min_y = (int)(size.height() * Y + 0.5); - int width = (int)(size.width() * WIDTH + 0.5); - int height = (int)(size.height() * HEIGHT + 0.5); - WallClock now = current_time(); - QPixmap pm = screen.grabWindow(0, min_x, min_y, width, height); - return VideoSnapshot(pm.toImage(), now); -} - - -VideoOverlaySession& ScreenWatchOption::overlay(){ - return m_overlay; -} - - - - - -} +/* Screen Watch Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "ScreenWatchOption.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + + +ScreenWatchOption::~ScreenWatchOption() = default; +ScreenWatchOption::ScreenWatchOption( + std::string label, + double default_x, double default_y, + double default_width, double default_height +) + : GroupOption(std::move(label), LockMode::UNLOCK_WHILE_RUNNING) + , MONITOR_INDEX( + "Monitor Index: For multi-monitor setups, this lets you choose which monitor to watch.", + LockMode::UNLOCK_WHILE_RUNNING, + 0 + ) + , X( + "X Coordinate: The left edge of the box to watch.
" + "0.0 is the left edge of the monitor. 1.0 is the right edge of the monitor.", + LockMode::UNLOCK_WHILE_RUNNING, + default_x, 0.0, 1.0 + ) + , Y( + "Y Coordinate: The top edge of the box to watch.
" + "0.0 is the top edge of the monitor. 1.0 is the bottom edge of the monitor.", + LockMode::UNLOCK_WHILE_RUNNING, + default_y, 0.0, 1.0 + ) + , WIDTH( + "Width: The width of the box to watch.
" + "The number is between 0 and 1 and is the proportion of the full width of the monitor.", + LockMode::UNLOCK_WHILE_RUNNING, + default_width, 0.0, 1.0 + ) + , HEIGHT( + "Height: The height of the box to watch.
" + "The number is between 0 and 1 and is the proportion of the full height of the monitor.", + LockMode::UNLOCK_WHILE_RUNNING, + default_height, 0.0, 1.0 + ) + , m_display(*this) + , m_buttons(*this) + , m_overlay(m_overlay_option) +{ + PA_ADD_OPTION(m_display); + PA_ADD_OPTION(MONITOR_INDEX); + PA_ADD_OPTION(X); + PA_ADD_OPTION(Y); + PA_ADD_OPTION(WIDTH); + PA_ADD_OPTION(HEIGHT); + PA_ADD_OPTION(m_buttons); +} + + +double ScreenWatchOption::aspect_ratio(){ + qsizetype index = (qsizetype)MONITOR_INDEX; + auto screens = QGuiApplication::screens(); + if (screens.size() <= index){ + return 0; + } + + QScreen& screen = *screens[index]; + + QSize size = screen.size(); + int width = (int)(size.width() * WIDTH + 0.5); + int height = (int)(size.height() * HEIGHT + 0.5); + return (double)width / height; +} +VideoSnapshot ScreenWatchOption::screenshot(){ + qsizetype index = (qsizetype)MONITOR_INDEX; + auto screens = QGuiApplication::screens(); + if (screens.size() <= index){ + return VideoSnapshot(); + } + + QScreen& screen = *screens[index]; + + QSize size = screen.size(); +// int width = screen.size().width(); +// int height = screen.size().height(); + + int min_x = (int)(size.width() * X + 0.5); + int min_y = (int)(size.height() * Y + 0.5); + int width = (int)(size.width() * WIDTH + 0.5); + int height = (int)(size.height() * HEIGHT + 0.5); + WallClock now = current_time(); + QPixmap pm = screen.grabWindow(0, min_x, min_y, width, height); + return VideoSnapshot(pm.toImage(), now); +} + + +VideoOverlaySession& ScreenWatchOption::overlay(){ + return m_overlay; +} + + + + + +} diff --git a/SerialPrograms/Source/CommonTools/Options/ScreenWatchOption.h b/SerialPrograms/Source/CommonTools/Options/ScreenWatchOption.h index 4778a690e7..9fcf0ab5de 100644 --- a/SerialPrograms/Source/CommonTools/Options/ScreenWatchOption.h +++ b/SerialPrograms/Source/CommonTools/Options/ScreenWatchOption.h @@ -1,86 +1,86 @@ -/* Screen Watch Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_Options_ScreenWatchOption_H -#define PokemonAutomation_CommonTools_Options_ScreenWatchOption_H - -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "CommonFramework/VideoPipeline/VideoOverlaySession.h" - -namespace PokemonAutomation{ - -struct VideoSnapshot; -class ScreenWatchOption; - - -class ScreenWatchDisplay : public ConfigOption{ -public: - ScreenWatchDisplay(ScreenWatchOption& option) - : m_option(option) - {} - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - - ScreenWatchOption& m_option; -}; -class ScreenWatchButtons : public ConfigOption{ -public: - ScreenWatchButtons(ScreenWatchOption& option) - : m_option(option) - {} - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - - ScreenWatchOption& m_option; -}; - - - -class ScreenWatchOption : public GroupOption{ -public: - ~ScreenWatchOption(); - ScreenWatchOption( - std::string label, - double default_x = 0, double default_y = 0, - double default_width = 1, double default_height = 1 - ); - -// virtual void load_json(const JsonValue& json) override; -// virtual JsonValue to_json() const override; - -// virtual void restore_defaults() override; - -// virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - - double aspect_ratio(); - VideoSnapshot screenshot(); - - VideoOverlaySession& overlay(); - -public: - SimpleIntegerOption MONITOR_INDEX; - FloatingPointOption X; - FloatingPointOption Y; - FloatingPointOption WIDTH; - FloatingPointOption HEIGHT; - -private: - ScreenWatchDisplay m_display; - ScreenWatchButtons m_buttons; - - VideoOverlayOption m_overlay_option; - VideoOverlaySession m_overlay; -}; - - - - - - -} -#endif +/* Screen Watch Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_Options_ScreenWatchOption_H +#define PokemonAutomation_CommonTools_Options_ScreenWatchOption_H + +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "CommonFramework/VideoPipeline/VideoOverlaySession.h" + +namespace PokemonAutomation{ + +struct VideoSnapshot; +class ScreenWatchOption; + + +class ScreenWatchDisplay : public ConfigOption{ +public: + ScreenWatchDisplay(ScreenWatchOption& option) + : m_option(option) + {} + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + + ScreenWatchOption& m_option; +}; +class ScreenWatchButtons : public ConfigOption{ +public: + ScreenWatchButtons(ScreenWatchOption& option) + : m_option(option) + {} + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + + ScreenWatchOption& m_option; +}; + + + +class ScreenWatchOption : public GroupOption{ +public: + ~ScreenWatchOption(); + ScreenWatchOption( + std::string label, + double default_x = 0, double default_y = 0, + double default_width = 1, double default_height = 1 + ); + +// virtual void load_json(const JsonValue& json) override; +// virtual JsonValue to_json() const override; + +// virtual void restore_defaults() override; + +// virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + + double aspect_ratio(); + VideoSnapshot screenshot(); + + VideoOverlaySession& overlay(); + +public: + SimpleIntegerOption MONITOR_INDEX; + FloatingPointOption X; + FloatingPointOption Y; + FloatingPointOption WIDTH; + FloatingPointOption HEIGHT; + +private: + ScreenWatchDisplay m_display; + ScreenWatchButtons m_buttons; + + VideoOverlayOption m_overlay_option; + VideoOverlaySession m_overlay; +}; + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Options/StringSelectOption.cpp b/SerialPrograms/Source/CommonTools/Options/StringSelectOption.cpp index 53456ac0ca..8f96468bfa 100644 --- a/SerialPrograms/Source/CommonTools/Options/StringSelectOption.cpp +++ b/SerialPrograms/Source/CommonTools/Options/StringSelectOption.cpp @@ -1,259 +1,259 @@ -/* String Select - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Json/JsonValue.h" -#include "StringSelectOption.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -struct StringSelectDatabase::Data{ - size_t m_longest_text_length = 0; - std::vector m_list; - std::map m_slug_to_entry; - std::map m_display_name_to_entry; - - size_t search_index_by_slug(const std::string& slug) const{ - auto iter = m_slug_to_entry.find(slug); - if (iter == m_slug_to_entry.end()){ - return (size_t)0 - 1; - } - return iter->second; - } - size_t search_index_by_name(const std::string& display_name) const{ - auto iter = m_display_name_to_entry.find(display_name); - if (iter == m_display_name_to_entry.end()){ - return (size_t)0 - 1; - } - return iter->second; - } - void add_entry(StringSelectEntry entry){ - size_t index = m_list.size(); - StringSelectEntry& item = m_list.emplace_back(std::move(entry)); - - std::map::const_iterator iter0 = m_slug_to_entry.end(); - std::map::const_iterator iter1 = m_display_name_to_entry.end(); - - try{ - auto ret0 = m_slug_to_entry.emplace(item.slug, index); - if (ret0.second){ - iter0 = ret0.first; - }else{ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Slug: " + item.slug); - } - auto ret1 = m_display_name_to_entry.emplace(item.display_name, index); - if (ret1.second){ - iter1 = ret1.first; - }else{ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Display Name: " + item.display_name); - } - }catch (...){ - m_list.pop_back(); - if (iter0 != m_slug_to_entry.end()){ - m_slug_to_entry.erase(iter0); - } - if (iter1 != m_display_name_to_entry.end()){ - m_slug_to_entry.erase(iter1); - } - throw; - } - - m_longest_text_length = std::max(m_longest_text_length, item.display_name.size()); - } -}; - - - -StringSelectDatabase::~StringSelectDatabase() = default; -StringSelectDatabase::StringSelectDatabase(StringSelectDatabase&&) = default; -StringSelectDatabase& StringSelectDatabase::operator=(StringSelectDatabase&&) = default; -StringSelectDatabase::StringSelectDatabase(const StringSelectDatabase&) = default; -StringSelectDatabase& StringSelectDatabase::operator=(const StringSelectDatabase&) = default; -StringSelectDatabase::StringSelectDatabase() - : m_data(CONSTRUCT_TOKEN) -{} - -size_t StringSelectDatabase::longest_text_length() const{ - return m_data->m_longest_text_length; -} -const std::vector& StringSelectDatabase::case_list() const{ - return m_data->m_list; -} -const StringSelectEntry& StringSelectDatabase::operator[](size_t index) const{ - return m_data->m_list[index]; -} -size_t StringSelectDatabase::search_index_by_slug(const std::string& slug) const{ - return m_data->search_index_by_slug(slug); -} -size_t StringSelectDatabase::search_index_by_name(const std::string& display_name) const{ - return m_data->search_index_by_name(display_name); -} -void StringSelectDatabase::add_entry(StringSelectEntry entry){ - m_data->add_entry(std::move(entry)); -} - - - - - -struct StringSelectCell::Data{ - const StringSelectDatabase& m_database; - const size_t m_default; - std::atomic m_index; - - Data(const StringSelectDatabase& database, size_t default_index) - : m_database(database) - , m_default(default_index) - , m_index(default_index) - { - if (default_index >= database.case_list().size()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Default Index: " + std::to_string(default_index)); - } - } - Data(const StringSelectDatabase& database, const std::string& default_slug) - : m_database(database) - , m_default(default_slug == "" ? 0 : database.search_index_by_slug(default_slug)) - , m_index(m_default) - { - if (m_default == (size_t)0 - 1){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Default Slug: " + default_slug); - } - } - - bool load_json(const JsonValue& json){ - const std::string* str = json.to_string(); - if (str == nullptr){ - return false; - } - size_t index = m_database.search_index_by_slug(*str); - if (index == (size_t)0 - 1){ - return false; - } - m_index.store(index, std::memory_order_relaxed); - return true; - } - JsonValue to_json() const{ - return m_database.case_list()[m_index.load(std::memory_order_relaxed)].slug; - } - void restore_defaults(){ - m_index.store(m_default, std::memory_order_relaxed); - } -}; - - - - - -StringSelectCell::~StringSelectCell() = default; - - -StringSelectCell::StringSelectCell( - const StringSelectDatabase& database, - LockMode lock_while_running, - size_t default_index -) - : ConfigOption(lock_while_running) - , m_data(CONSTRUCT_TOKEN, database, default_index) -{} -StringSelectCell::StringSelectCell( - const StringSelectDatabase& database, - LockMode lock_while_running, - const std::string& default_slug -) - : ConfigOption(lock_while_running) - , m_data(CONSTRUCT_TOKEN, database, default_slug) -{} - - -size_t StringSelectCell::default_index() const{ - return m_data->m_default; -} -const std::string& StringSelectCell::default_slug() const{ - return m_data->m_database.case_list()[m_data->m_default].slug; -} - -size_t StringSelectCell::index() const{ - return m_data->m_index.load(std::memory_order_relaxed); -} - -void StringSelectCell::set_by_index(size_t index){ - if (index >= m_data->m_database.case_list().size()){ - index = m_data->m_default; - } - if (index != m_data->m_index.exchange(index, std::memory_order_relaxed)){ - report_value_changed(this); - } -} -std::string StringSelectCell::set_by_slug(const std::string& slug){ - size_t index = m_data->m_database.search_index_by_slug(slug); - if (index == (size_t)0 - 1){ - return "Invalid Slug: " + slug; - } - if (index != m_data->m_index.exchange(index, std::memory_order_relaxed)){ - report_value_changed(this); - } - return ""; -} -std::string StringSelectCell::set_by_name(const std::string& display_name){ - size_t index = m_data->m_database.search_index_by_name(display_name); - if (index == (size_t)0 - 1){ - return "Invalid Name: " + display_name; - } - if (index != m_data->m_index.exchange(index, std::memory_order_relaxed)){ - report_value_changed(this); - } - return ""; -} - -const StringSelectDatabase& StringSelectCell::database() const{ - return m_data->m_database; -} - -void StringSelectCell::load_json(const JsonValue& json){ - if (m_data->load_json(json)){ - report_value_changed(this); - } -} -JsonValue StringSelectCell::to_json() const{ - return m_data->to_json(); -} -void StringSelectCell::restore_defaults(){ - m_data->restore_defaults(); - report_value_changed(this); -} - - - - - - - - - - - - - - - - - - - - - -} +/* String Select + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Json/JsonValue.h" +#include "StringSelectOption.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +struct StringSelectDatabase::Data{ + size_t m_longest_text_length = 0; + std::vector m_list; + std::map m_slug_to_entry; + std::map m_display_name_to_entry; + + size_t search_index_by_slug(const std::string& slug) const{ + auto iter = m_slug_to_entry.find(slug); + if (iter == m_slug_to_entry.end()){ + return (size_t)0 - 1; + } + return iter->second; + } + size_t search_index_by_name(const std::string& display_name) const{ + auto iter = m_display_name_to_entry.find(display_name); + if (iter == m_display_name_to_entry.end()){ + return (size_t)0 - 1; + } + return iter->second; + } + void add_entry(StringSelectEntry entry){ + size_t index = m_list.size(); + StringSelectEntry& item = m_list.emplace_back(std::move(entry)); + + std::map::const_iterator iter0 = m_slug_to_entry.end(); + std::map::const_iterator iter1 = m_display_name_to_entry.end(); + + try{ + auto ret0 = m_slug_to_entry.emplace(item.slug, index); + if (ret0.second){ + iter0 = ret0.first; + }else{ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Slug: " + item.slug); + } + auto ret1 = m_display_name_to_entry.emplace(item.display_name, index); + if (ret1.second){ + iter1 = ret1.first; + }else{ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Display Name: " + item.display_name); + } + }catch (...){ + m_list.pop_back(); + if (iter0 != m_slug_to_entry.end()){ + m_slug_to_entry.erase(iter0); + } + if (iter1 != m_display_name_to_entry.end()){ + m_slug_to_entry.erase(iter1); + } + throw; + } + + m_longest_text_length = std::max(m_longest_text_length, item.display_name.size()); + } +}; + + + +StringSelectDatabase::~StringSelectDatabase() = default; +StringSelectDatabase::StringSelectDatabase(StringSelectDatabase&&) = default; +StringSelectDatabase& StringSelectDatabase::operator=(StringSelectDatabase&&) = default; +StringSelectDatabase::StringSelectDatabase(const StringSelectDatabase&) = default; +StringSelectDatabase& StringSelectDatabase::operator=(const StringSelectDatabase&) = default; +StringSelectDatabase::StringSelectDatabase() + : m_data(CONSTRUCT_TOKEN) +{} + +size_t StringSelectDatabase::longest_text_length() const{ + return m_data->m_longest_text_length; +} +const std::vector& StringSelectDatabase::case_list() const{ + return m_data->m_list; +} +const StringSelectEntry& StringSelectDatabase::operator[](size_t index) const{ + return m_data->m_list[index]; +} +size_t StringSelectDatabase::search_index_by_slug(const std::string& slug) const{ + return m_data->search_index_by_slug(slug); +} +size_t StringSelectDatabase::search_index_by_name(const std::string& display_name) const{ + return m_data->search_index_by_name(display_name); +} +void StringSelectDatabase::add_entry(StringSelectEntry entry){ + m_data->add_entry(std::move(entry)); +} + + + + + +struct StringSelectCell::Data{ + const StringSelectDatabase& m_database; + const size_t m_default; + std::atomic m_index; + + Data(const StringSelectDatabase& database, size_t default_index) + : m_database(database) + , m_default(default_index) + , m_index(default_index) + { + if (default_index >= database.case_list().size()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Default Index: " + std::to_string(default_index)); + } + } + Data(const StringSelectDatabase& database, const std::string& default_slug) + : m_database(database) + , m_default(default_slug == "" ? 0 : database.search_index_by_slug(default_slug)) + , m_index(m_default) + { + if (m_default == (size_t)0 - 1){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Default Slug: " + default_slug); + } + } + + bool load_json(const JsonValue& json){ + const std::string* str = json.to_string(); + if (str == nullptr){ + return false; + } + size_t index = m_database.search_index_by_slug(*str); + if (index == (size_t)0 - 1){ + return false; + } + m_index.store(index, std::memory_order_relaxed); + return true; + } + JsonValue to_json() const{ + return m_database.case_list()[m_index.load(std::memory_order_relaxed)].slug; + } + void restore_defaults(){ + m_index.store(m_default, std::memory_order_relaxed); + } +}; + + + + + +StringSelectCell::~StringSelectCell() = default; + + +StringSelectCell::StringSelectCell( + const StringSelectDatabase& database, + LockMode lock_while_running, + size_t default_index +) + : ConfigOption(lock_while_running) + , m_data(CONSTRUCT_TOKEN, database, default_index) +{} +StringSelectCell::StringSelectCell( + const StringSelectDatabase& database, + LockMode lock_while_running, + const std::string& default_slug +) + : ConfigOption(lock_while_running) + , m_data(CONSTRUCT_TOKEN, database, default_slug) +{} + + +size_t StringSelectCell::default_index() const{ + return m_data->m_default; +} +const std::string& StringSelectCell::default_slug() const{ + return m_data->m_database.case_list()[m_data->m_default].slug; +} + +size_t StringSelectCell::index() const{ + return m_data->m_index.load(std::memory_order_relaxed); +} + +void StringSelectCell::set_by_index(size_t index){ + if (index >= m_data->m_database.case_list().size()){ + index = m_data->m_default; + } + if (index != m_data->m_index.exchange(index, std::memory_order_relaxed)){ + report_value_changed(this); + } +} +std::string StringSelectCell::set_by_slug(const std::string& slug){ + size_t index = m_data->m_database.search_index_by_slug(slug); + if (index == (size_t)0 - 1){ + return "Invalid Slug: " + slug; + } + if (index != m_data->m_index.exchange(index, std::memory_order_relaxed)){ + report_value_changed(this); + } + return ""; +} +std::string StringSelectCell::set_by_name(const std::string& display_name){ + size_t index = m_data->m_database.search_index_by_name(display_name); + if (index == (size_t)0 - 1){ + return "Invalid Name: " + display_name; + } + if (index != m_data->m_index.exchange(index, std::memory_order_relaxed)){ + report_value_changed(this); + } + return ""; +} + +const StringSelectDatabase& StringSelectCell::database() const{ + return m_data->m_database; +} + +void StringSelectCell::load_json(const JsonValue& json){ + if (m_data->load_json(json)){ + report_value_changed(this); + } +} +JsonValue StringSelectCell::to_json() const{ + return m_data->to_json(); +} +void StringSelectCell::restore_defaults(){ + m_data->restore_defaults(); + report_value_changed(this); +} + + + + + + + + + + + + + + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonTools/Options/StringSelectOption.h b/SerialPrograms/Source/CommonTools/Options/StringSelectOption.h index 58c9c446ab..c709b4ece5 100644 --- a/SerialPrograms/Source/CommonTools/Options/StringSelectOption.h +++ b/SerialPrograms/Source/CommonTools/Options/StringSelectOption.h @@ -1,154 +1,154 @@ -/* String Select - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_Options_StringSelectOption_H -#define PokemonAutomation_CommonTools_Options_StringSelectOption_H - -#include -#include "Common/Cpp/Color.h" -#include "Common/Cpp/Containers/Pimpl.h" -#include "Common/Cpp/Options/ConfigOption.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" - -namespace PokemonAutomation{ - - - - -struct StringSelectEntry{ - std::string slug; - std::string display_name; - ImageViewRGB32 icon; - Color text_color; - - StringSelectEntry( - std::string p_slug, - std::string p_display_name, - ImageViewRGB32 p_icon = ImageViewRGB32(), - Color p_text_color = Color() - ) - : slug(std::move(p_slug)) - , display_name(std::move(p_display_name)) - , icon(std::move(p_icon)) - , text_color(p_text_color) - {} -}; - - - -class StringSelectDatabase{ -public: - ~StringSelectDatabase(); - StringSelectDatabase(StringSelectDatabase&&); - StringSelectDatabase& operator=(StringSelectDatabase&&); - StringSelectDatabase(const StringSelectDatabase&); - StringSelectDatabase& operator=(const StringSelectDatabase&); - -public: - StringSelectDatabase(); - void add_entry(StringSelectEntry entry); - -public: - const std::vector& case_list() const; - size_t longest_text_length() const; - - const StringSelectEntry& operator[](size_t index) const; - size_t search_index_by_slug(const std::string& slug) const; - size_t search_index_by_name(const std::string& display_name) const; - -private: - struct Data; - Pimpl m_data; -}; - - - -class StringSelectCell : public ConfigOption{ -public: - ~StringSelectCell(); - StringSelectCell(const StringSelectCell&) = delete; - void operator=(const StringSelectCell&) = delete; - -public: - StringSelectCell( - const StringSelectDatabase& database, - LockMode lock_while_running, - size_t default_index - ); - StringSelectCell( - const StringSelectDatabase& database, - LockMode lock_while_running, - const std::string& default_slug - ); - - size_t default_index() const; - const std::string& default_slug() const; - - size_t index() const; - const std::string& slug() const{ - return entry().slug; - } - const std::string& display_name() const{ - return entry().display_name; - } - const StringSelectEntry& entry() const{ - return database()[index()]; - } - - void set_by_index(size_t index); - std::string set_by_slug(const std::string& slug); - std::string set_by_name(const std::string& display_name); - - const StringSelectDatabase& database() const; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual void restore_defaults() override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - struct Data; - Pimpl m_data; -}; - - - -class StringSelectOption : public StringSelectCell{ -public: - StringSelectOption( - std::string label, - const StringSelectDatabase& database, - LockMode lock_while_running, - size_t default_index - ) - : StringSelectCell(database, lock_while_running, default_index) - , m_label(std::move(label)) - {} - StringSelectOption( - std::string label, - const StringSelectDatabase& database, - LockMode lock_while_running, - const std::string& default_slug - ) - : StringSelectCell(database, lock_while_running, default_slug) - , m_label(std::move(label)) - {} - - const std::string& label() const{ return m_label; } - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - std::string m_label; -}; - - - - - -} -#endif +/* String Select + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_Options_StringSelectOption_H +#define PokemonAutomation_CommonTools_Options_StringSelectOption_H + +#include +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Containers/Pimpl.h" +#include "Common/Cpp/Options/ConfigOption.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" + +namespace PokemonAutomation{ + + + + +struct StringSelectEntry{ + std::string slug; + std::string display_name; + ImageViewRGB32 icon; + Color text_color; + + StringSelectEntry( + std::string p_slug, + std::string p_display_name, + ImageViewRGB32 p_icon = ImageViewRGB32(), + Color p_text_color = Color() + ) + : slug(std::move(p_slug)) + , display_name(std::move(p_display_name)) + , icon(std::move(p_icon)) + , text_color(p_text_color) + {} +}; + + + +class StringSelectDatabase{ +public: + ~StringSelectDatabase(); + StringSelectDatabase(StringSelectDatabase&&); + StringSelectDatabase& operator=(StringSelectDatabase&&); + StringSelectDatabase(const StringSelectDatabase&); + StringSelectDatabase& operator=(const StringSelectDatabase&); + +public: + StringSelectDatabase(); + void add_entry(StringSelectEntry entry); + +public: + const std::vector& case_list() const; + size_t longest_text_length() const; + + const StringSelectEntry& operator[](size_t index) const; + size_t search_index_by_slug(const std::string& slug) const; + size_t search_index_by_name(const std::string& display_name) const; + +private: + struct Data; + Pimpl m_data; +}; + + + +class StringSelectCell : public ConfigOption{ +public: + ~StringSelectCell(); + StringSelectCell(const StringSelectCell&) = delete; + void operator=(const StringSelectCell&) = delete; + +public: + StringSelectCell( + const StringSelectDatabase& database, + LockMode lock_while_running, + size_t default_index + ); + StringSelectCell( + const StringSelectDatabase& database, + LockMode lock_while_running, + const std::string& default_slug + ); + + size_t default_index() const; + const std::string& default_slug() const; + + size_t index() const; + const std::string& slug() const{ + return entry().slug; + } + const std::string& display_name() const{ + return entry().display_name; + } + const StringSelectEntry& entry() const{ + return database()[index()]; + } + + void set_by_index(size_t index); + std::string set_by_slug(const std::string& slug); + std::string set_by_name(const std::string& display_name); + + const StringSelectDatabase& database() const; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual void restore_defaults() override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + struct Data; + Pimpl m_data; +}; + + + +class StringSelectOption : public StringSelectCell{ +public: + StringSelectOption( + std::string label, + const StringSelectDatabase& database, + LockMode lock_while_running, + size_t default_index + ) + : StringSelectCell(database, lock_while_running, default_index) + , m_label(std::move(label)) + {} + StringSelectOption( + std::string label, + const StringSelectDatabase& database, + LockMode lock_while_running, + const std::string& default_slug + ) + : StringSelectCell(database, lock_while_running, default_slug) + , m_label(std::move(label)) + {} + + const std::string& label() const{ return m_label; } + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + std::string m_label; +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Options/StringSelectTableOption.h b/SerialPrograms/Source/CommonTools/Options/StringSelectTableOption.h index cafeb26de1..8363afad12 100644 --- a/SerialPrograms/Source/CommonTools/Options/StringSelectTableOption.h +++ b/SerialPrograms/Source/CommonTools/Options/StringSelectTableOption.h @@ -1,76 +1,76 @@ -/* String Select Table - * - * From: https://github.com/PokemonAutomation/ - * - * A simple editable table of StringSelect options. - * - */ - -#ifndef PokemonAutomation_CommonTools_Options_StringSelectTableOption_H -#define PokemonAutomation_CommonTools_Options_StringSelectTableOption_H - -#include "Common/Cpp/Options/EditableTableOption.h" -#include "StringSelectOption.h" - -namespace PokemonAutomation{ - - -class StringSelectTableRow : public EditableTableRow{ -public: - StringSelectTableRow( - EditableTableOption& parent_table, - const StringSelectDatabase& database, const std::string& default_slug - ) - : EditableTableRow(parent_table) - , cell(database, LockMode::LOCK_WHILE_RUNNING, default_slug) - { - PA_ADD_OPTION(cell); - } - virtual std::unique_ptr clone() const{ - std::unique_ptr ret(new StringSelectTableRow(parent(), cell.database(), cell.default_slug())); - ret->cell.set_by_index(cell.index()); - return ret; - } - -public: - StringSelectCell cell; -}; - - -class StringSelectTableOption : public EditableTableOption{ -public: - StringSelectTableOption( - std::string label, - std::string header, const StringSelectDatabase& database, std::string default_slug - ) - : EditableTableOption(std::move(label), LockMode::LOCK_WHILE_RUNNING) - , m_header(std::move(header)) - , m_database(database) - , m_default_slug(std::move(default_slug)) - {} - - std::vector all_slugs() const{ - std::vector slugs; - for (const auto& item : copy_snapshot()){ - slugs.emplace_back(item->cell.slug()); - } - return slugs; - } - - virtual std::vector make_header() const{ - return {m_header}; - } - virtual std::unique_ptr make_row(){ - return std::make_unique(*this, m_database, m_default_slug); - } - -private: - const std::string m_header; - const StringSelectDatabase& m_database; - const std::string m_default_slug; -}; - - - -} -#endif +/* String Select Table + * + * From: https://github.com/PokemonAutomation/ + * + * A simple editable table of StringSelect options. + * + */ + +#ifndef PokemonAutomation_CommonTools_Options_StringSelectTableOption_H +#define PokemonAutomation_CommonTools_Options_StringSelectTableOption_H + +#include "Common/Cpp/Options/EditableTableOption.h" +#include "StringSelectOption.h" + +namespace PokemonAutomation{ + + +class StringSelectTableRow : public EditableTableRow{ +public: + StringSelectTableRow( + EditableTableOption& parent_table, + const StringSelectDatabase& database, const std::string& default_slug + ) + : EditableTableRow(parent_table) + , cell(database, LockMode::LOCK_WHILE_RUNNING, default_slug) + { + PA_ADD_OPTION(cell); + } + virtual std::unique_ptr clone() const{ + std::unique_ptr ret(new StringSelectTableRow(parent(), cell.database(), cell.default_slug())); + ret->cell.set_by_index(cell.index()); + return ret; + } + +public: + StringSelectCell cell; +}; + + +class StringSelectTableOption : public EditableTableOption{ +public: + StringSelectTableOption( + std::string label, + std::string header, const StringSelectDatabase& database, std::string default_slug + ) + : EditableTableOption(std::move(label), LockMode::LOCK_WHILE_RUNNING) + , m_header(std::move(header)) + , m_database(database) + , m_default_slug(std::move(default_slug)) + {} + + std::vector all_slugs() const{ + std::vector slugs; + for (const auto& item : copy_snapshot()){ + slugs.emplace_back(item->cell.slug()); + } + return slugs; + } + + virtual std::vector make_header() const{ + return {m_header}; + } + virtual std::unique_ptr make_row(){ + return std::make_unique(*this, m_database, m_default_slug); + } + +private: + const std::string m_header; + const StringSelectDatabase& m_database; + const std::string m_default_slug; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Options/TrainOCRModeOption.h b/SerialPrograms/Source/CommonTools/Options/TrainOCRModeOption.h index 3044ca9145..17294fe038 100644 --- a/SerialPrograms/Source/CommonTools/Options/TrainOCRModeOption.h +++ b/SerialPrograms/Source/CommonTools/Options/TrainOCRModeOption.h @@ -1,39 +1,39 @@ -/* Train OCR Mode Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_Options_TrainOCRModeOption_H -#define PokemonAutomation_CommonTools_Options_TrainOCRModeOption_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" - -namespace PokemonAutomation{ - -enum class TrainOCRMode{ - GENERATE_BASELINE, - START_FRESH, - INCREMENTAL, -}; - -class TrainOCRModeOption : public EnumDropdownOption{ -public: - TrainOCRModeOption() - : EnumDropdownOption( - "Mode:", - { - {TrainOCRMode::GENERATE_BASELINE, "baseline", "Generate Baseline: Generate baseline data using display names."}, - {TrainOCRMode::START_FRESH, "start-fresh", "Start Fresh: Use only baseline strings. (1st candidate of each entry in above path)"}, - {TrainOCRMode::INCREMENTAL, "incremental", "Incremental: Build off of the existing training data in the above path."}, - }, - LockMode::LOCK_WHILE_RUNNING, - TrainOCRMode::GENERATE_BASELINE - ) - {} -}; - - - -} -#endif +/* Train OCR Mode Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_Options_TrainOCRModeOption_H +#define PokemonAutomation_CommonTools_Options_TrainOCRModeOption_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" + +namespace PokemonAutomation{ + +enum class TrainOCRMode{ + GENERATE_BASELINE, + START_FRESH, + INCREMENTAL, +}; + +class TrainOCRModeOption : public EnumDropdownOption{ +public: + TrainOCRModeOption() + : EnumDropdownOption( + "Mode:", + { + {TrainOCRMode::GENERATE_BASELINE, "baseline", "Generate Baseline: Generate baseline data using display names."}, + {TrainOCRMode::START_FRESH, "start-fresh", "Start Fresh: Use only baseline strings. (1st candidate of each entry in above path)"}, + {TrainOCRMode::INCREMENTAL, "incremental", "Incremental: Build off of the existing training data in the above path."}, + }, + LockMode::LOCK_WHILE_RUNNING, + TrainOCRMode::GENERATE_BASELINE + ) + {} +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Resources/SpriteDatabase.cpp b/SerialPrograms/Source/CommonTools/Resources/SpriteDatabase.cpp index fadd2fee7b..c8a04f5f78 100644 --- a/SerialPrograms/Source/CommonTools/Resources/SpriteDatabase.cpp +++ b/SerialPrograms/Source/CommonTools/Resources/SpriteDatabase.cpp @@ -1,66 +1,66 @@ -/* Sprite Composite Image - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/ImageMatch/ImageCropper.h" -#include "SpriteDatabase.h" - -namespace PokemonAutomation{ - - - -SpriteDatabase::SpriteDatabase(const char* sprite_path, const char* json_path) - : m_backing_image(RESOURCE_PATH() + sprite_path) -{ - std::string path = RESOURCE_PATH() + json_path; - JsonValue json = load_json_file(path); - JsonObject& root = json.to_object_throw(path); - - int64_t width = root.get_integer_throw("spriteWidth", path); - int64_t height = root.get_integer_throw("spriteHeight", path); - if (width <= 0){ - throw FileException(nullptr, PA_CURRENT_FUNCTION, "Invalid width.", path); - } - if (height <= 0){ - throw FileException(nullptr, PA_CURRENT_FUNCTION, "Invalid height.", path); - } - - JsonObject& locations = root.get_object_throw("spriteLocations", path); - for (auto& item : locations){ - const std::string& slug = item.first; - JsonObject& obj = item.second.to_object_throw(path); - int y = (int)obj.get_integer_throw("top", path); - int x = (int)obj.get_integer_throw("left", path); - - ImageViewRGB32 sprite = extract_box_reference(m_backing_image, ImagePixelBox(x, y, x + width, y + height)); - m_database.emplace( - slug, - Sprite{sprite, ImageMatch::trim_image_alpha(sprite)} - ); - } -} - -const SpriteDatabase::Sprite& SpriteDatabase::get_throw(const std::string& slug) const{ - auto iter = m_database.find(slug); - if (iter == m_database.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Slug not found in database: " + slug); - } - return iter->second; -} -const SpriteDatabase::Sprite* SpriteDatabase::get_nothrow(const std::string& slug) const{ - auto iter = m_database.find(slug); - if (iter == m_database.end()){ - return nullptr; - } - return &iter->second; -} - - - -} +/* Sprite Composite Image + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/ImageMatch/ImageCropper.h" +#include "SpriteDatabase.h" + +namespace PokemonAutomation{ + + + +SpriteDatabase::SpriteDatabase(const char* sprite_path, const char* json_path) + : m_backing_image(RESOURCE_PATH() + sprite_path) +{ + std::string path = RESOURCE_PATH() + json_path; + JsonValue json = load_json_file(path); + JsonObject& root = json.to_object_throw(path); + + int64_t width = root.get_integer_throw("spriteWidth", path); + int64_t height = root.get_integer_throw("spriteHeight", path); + if (width <= 0){ + throw FileException(nullptr, PA_CURRENT_FUNCTION, "Invalid width.", path); + } + if (height <= 0){ + throw FileException(nullptr, PA_CURRENT_FUNCTION, "Invalid height.", path); + } + + JsonObject& locations = root.get_object_throw("spriteLocations", path); + for (auto& item : locations){ + const std::string& slug = item.first; + JsonObject& obj = item.second.to_object_throw(path); + int y = (int)obj.get_integer_throw("top", path); + int x = (int)obj.get_integer_throw("left", path); + + ImageViewRGB32 sprite = extract_box_reference(m_backing_image, ImagePixelBox(x, y, x + width, y + height)); + m_database.emplace( + slug, + Sprite{sprite, ImageMatch::trim_image_alpha(sprite)} + ); + } +} + +const SpriteDatabase::Sprite& SpriteDatabase::get_throw(const std::string& slug) const{ + auto iter = m_database.find(slug); + if (iter == m_database.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Slug not found in database: " + slug); + } + return iter->second; +} +const SpriteDatabase::Sprite* SpriteDatabase::get_nothrow(const std::string& slug) const{ + auto iter = m_database.find(slug); + if (iter == m_database.end()){ + return nullptr; + } + return &iter->second; +} + + + +} diff --git a/SerialPrograms/Source/CommonTools/Resources/SpriteDatabase.h b/SerialPrograms/Source/CommonTools/Resources/SpriteDatabase.h index 66b9420832..3136ffd6ec 100644 --- a/SerialPrograms/Source/CommonTools/Resources/SpriteDatabase.h +++ b/SerialPrograms/Source/CommonTools/Resources/SpriteDatabase.h @@ -1,64 +1,64 @@ -/* Sprite Composite Image - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_Resources_SpriteCompositeImage_H -#define PokemonAutomation_CommonTools_Resources_SpriteCompositeImage_H - -#include -#include "CommonFramework/ImageTypes/ImageRGB32.h" - -namespace PokemonAutomation{ - - -class SpriteDatabase{ -public: - // Build from a composite image. - // - // The location of each sprite on the image is specified by a json file. - // Return a map of pokemon slug name for each sprite -> QIcon of the sprite. - // - // The json file must have the following format: - // { - // "spriteWidth": , - // "spriteHeight": , - // "spriteLocations": { - // "" : { - // "top": , - // "left": - // }, - // (next pokemon) ... - // } - // } - SpriteDatabase(const char* sprite_path, const char* json_path); - -public: - struct Sprite{ - ImageViewRGB32 sprite; // The original sprite. - ImageViewRGB32 icon; // Sprite with 0-alpha boundaries cropped for better viewing. - }; - const Sprite& get_throw(const std::string& slug) const; - const Sprite* get_nothrow(const std::string& slug) const; - -public: - using const_iterator = std::map::const_iterator; - using iterator = std::map::iterator; - - const_iterator cbegin () const{ return m_database.cbegin(); } - const_iterator begin () const{ return m_database.begin(); } - iterator begin (){ return m_database.begin(); } - const_iterator cend () const{ return m_database.cend(); } - const_iterator end () const{ return m_database.end(); } - iterator end (){ return m_database.end(); } - -private: - std::map m_database; - ImageRGB32 m_backing_image; -}; - - - -} -#endif +/* Sprite Composite Image + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_Resources_SpriteCompositeImage_H +#define PokemonAutomation_CommonTools_Resources_SpriteCompositeImage_H + +#include +#include "CommonFramework/ImageTypes/ImageRGB32.h" + +namespace PokemonAutomation{ + + +class SpriteDatabase{ +public: + // Build from a composite image. + // + // The location of each sprite on the image is specified by a json file. + // Return a map of pokemon slug name for each sprite -> QIcon of the sprite. + // + // The json file must have the following format: + // { + // "spriteWidth": , + // "spriteHeight": , + // "spriteLocations": { + // "" : { + // "top": , + // "left": + // }, + // (next pokemon) ... + // } + // } + SpriteDatabase(const char* sprite_path, const char* json_path); + +public: + struct Sprite{ + ImageViewRGB32 sprite; // The original sprite. + ImageViewRGB32 icon; // Sprite with 0-alpha boundaries cropped for better viewing. + }; + const Sprite& get_throw(const std::string& slug) const; + const Sprite* get_nothrow(const std::string& slug) const; + +public: + using const_iterator = std::map::const_iterator; + using iterator = std::map::iterator; + + const_iterator cbegin () const{ return m_database.cbegin(); } + const_iterator begin () const{ return m_database.begin(); } + iterator begin (){ return m_database.begin(); } + const_iterator cend () const{ return m_database.cend(); } + const_iterator end () const{ return m_database.end(); } + iterator end (){ return m_database.end(); } + +private: + std::map m_database; + ImageRGB32 m_backing_image; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/StartupChecks/StartProgramChecks.cpp b/SerialPrograms/Source/CommonTools/StartupChecks/StartProgramChecks.cpp index ae55cf465f..0acac28aa4 100644 --- a/SerialPrograms/Source/CommonTools/StartupChecks/StartProgramChecks.cpp +++ b/SerialPrograms/Source/CommonTools/StartupChecks/StartProgramChecks.cpp @@ -1,71 +1,71 @@ -/* Start Program Checks - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -//#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/VisualDetectors/BlackBorderDetector.h" -#include "Controllers/ControllerCapability.h" -#include "StartProgramChecks.h" - -namespace PokemonAutomation{ -namespace StartProgramChecks{ - - -void check_feedback(VideoStream& stream, FeedbackType feedback){ - if (feedback == FeedbackType::NONE){ - return; - } - VideoSnapshot screen = stream.video().snapshot(); - if (screen){ - return; - } - if (feedback == FeedbackType::REQUIRED || feedback == FeedbackType::VIDEO_AUDIO){ - throw UserSetupError( - stream.logger(), - "This program requires video feedback. Please make sure the video is working." - ); - } -} - -void check_border(VideoStream& stream){ - BlackBorderDetector detector; - VideoOverlaySet set(stream.overlay()); - detector.make_overlays(set); - VideoSnapshot screen = stream.video().snapshot(); - if (!detector.detect(screen)){ - return; - } - throw UserSetupError( - stream.logger(), - "Black border detected! Please set your screen size to 100% in the TV Settings on your Nintendo Switch." - ); -} - - - -void check_controller_features( - Logger& logger, - const ControllerFeatures& capabilities, - const ControllerFeatures& required_features -){ - std::string missing_feature = capabilities.contains_all(required_features); - if (missing_feature.empty()){ - return; - } - throw UserSetupError( - logger, - "Cannot start program. The controller is missing the feature: " + missing_feature - ); -} - - - - -} -} +/* Start Program Checks + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +//#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/VisualDetectors/BlackBorderDetector.h" +#include "Controllers/ControllerCapability.h" +#include "StartProgramChecks.h" + +namespace PokemonAutomation{ +namespace StartProgramChecks{ + + +void check_feedback(VideoStream& stream, FeedbackType feedback){ + if (feedback == FeedbackType::NONE){ + return; + } + VideoSnapshot screen = stream.video().snapshot(); + if (screen){ + return; + } + if (feedback == FeedbackType::REQUIRED || feedback == FeedbackType::VIDEO_AUDIO){ + throw UserSetupError( + stream.logger(), + "This program requires video feedback. Please make sure the video is working." + ); + } +} + +void check_border(VideoStream& stream){ + BlackBorderDetector detector; + VideoOverlaySet set(stream.overlay()); + detector.make_overlays(set); + VideoSnapshot screen = stream.video().snapshot(); + if (!detector.detect(screen)){ + return; + } + throw UserSetupError( + stream.logger(), + "Black border detected! Please set your screen size to 100% in the TV Settings on your Nintendo Switch." + ); +} + + + +void check_controller_features( + Logger& logger, + const ControllerFeatures& capabilities, + const ControllerFeatures& required_features +){ + std::string missing_feature = capabilities.contains_all(required_features); + if (missing_feature.empty()){ + return; + } + throw UserSetupError( + logger, + "Cannot start program. The controller is missing the feature: " + missing_feature + ); +} + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/StartupChecks/StartProgramChecks.h b/SerialPrograms/Source/CommonTools/StartupChecks/StartProgramChecks.h index 847fa27b54..65153c7d99 100644 --- a/SerialPrograms/Source/CommonTools/StartupChecks/StartProgramChecks.h +++ b/SerialPrograms/Source/CommonTools/StartupChecks/StartProgramChecks.h @@ -1,34 +1,34 @@ -/* Start Program Checks - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_StartProgramChecks_H -#define PokemonAutomation_CommonTools_StartProgramChecks_H - -#include -#include "CommonFramework/Globals.h" - -namespace PokemonAutomation{ - class Logger; - class VideoStream; - class ControllerFeatures; -namespace StartProgramChecks{ - - - -void check_feedback(VideoStream& stream, FeedbackType feedback); -void check_border(VideoStream& stream); - -void check_controller_features( - Logger& logger, - const ControllerFeatures& capabilities, - const ControllerFeatures& required_features -); - - - -} -} -#endif +/* Start Program Checks + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_StartProgramChecks_H +#define PokemonAutomation_CommonTools_StartProgramChecks_H + +#include +#include "CommonFramework/Globals.h" + +namespace PokemonAutomation{ + class Logger; + class VideoStream; + class ControllerFeatures; +namespace StartProgramChecks{ + + + +void check_feedback(VideoStream& stream, FeedbackType feedback); +void check_border(VideoStream& stream); + +void check_controller_features( + Logger& logger, + const ControllerFeatures& capabilities, + const ControllerFeatures& required_features +); + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/StartupChecks/VideoResolutionCheck.cpp b/SerialPrograms/Source/CommonTools/StartupChecks/VideoResolutionCheck.cpp index 1ca277e443..cb01c5ee7e 100644 --- a/SerialPrograms/Source/CommonTools/StartupChecks/VideoResolutionCheck.cpp +++ b/SerialPrograms/Source/CommonTools/StartupChecks/VideoResolutionCheck.cpp @@ -1,49 +1,49 @@ -/* Video Resolution Check - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "VideoResolutionCheck.h" - -namespace PokemonAutomation{ - - -void assert_16_9_720p_min(Logger& logger, const ImageViewRGB32& frame){ - if (!frame){ - throw UserSetupError(logger, "No video detected."); - } - if (frame.height() < 720){ - throw UserSetupError(logger, "Video resolution must be at least 720p."); - } - double aspect_ratio = (double)frame.width() / frame.height(); - if (aspect_ratio < 1.77 || aspect_ratio > 1.78){ - throw UserSetupError(logger, "Video aspect ratio must be 16:9."); - } -} -void assert_16_9_720p_min(Logger& logger, VideoFeed& video){ - assert_16_9_720p_min(logger, video.snapshot()); -} - -void assert_16_9_1080p_min(Logger& logger, const ImageViewRGB32& frame){ - if (!frame){ - throw UserSetupError(logger, "No video detected."); - } - if (frame.height() < 1080){ - throw UserSetupError(logger, "Video resolution must be at least 1080p."); - } - double aspect_ratio = (double)frame.width() / frame.height(); - if (aspect_ratio < 1.77 || aspect_ratio > 1.78){ - throw UserSetupError(logger, "Video aspect ratio must be 16:9."); - } -} -void assert_16_9_1080p_min(Logger& logger, VideoFeed& video){ - assert_16_9_1080p_min(logger, video.snapshot()); -} - - - -} +/* Video Resolution Check + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "VideoResolutionCheck.h" + +namespace PokemonAutomation{ + + +void assert_16_9_720p_min(Logger& logger, const ImageViewRGB32& frame){ + if (!frame){ + throw UserSetupError(logger, "No video detected."); + } + if (frame.height() < 720){ + throw UserSetupError(logger, "Video resolution must be at least 720p."); + } + double aspect_ratio = (double)frame.width() / frame.height(); + if (aspect_ratio < 1.77 || aspect_ratio > 1.78){ + throw UserSetupError(logger, "Video aspect ratio must be 16:9."); + } +} +void assert_16_9_720p_min(Logger& logger, VideoFeed& video){ + assert_16_9_720p_min(logger, video.snapshot()); +} + +void assert_16_9_1080p_min(Logger& logger, const ImageViewRGB32& frame){ + if (!frame){ + throw UserSetupError(logger, "No video detected."); + } + if (frame.height() < 1080){ + throw UserSetupError(logger, "Video resolution must be at least 1080p."); + } + double aspect_ratio = (double)frame.width() / frame.height(); + if (aspect_ratio < 1.77 || aspect_ratio > 1.78){ + throw UserSetupError(logger, "Video aspect ratio must be 16:9."); + } +} +void assert_16_9_1080p_min(Logger& logger, VideoFeed& video){ + assert_16_9_1080p_min(logger, video.snapshot()); +} + + + +} diff --git a/SerialPrograms/Source/CommonTools/StartupChecks/VideoResolutionCheck.h b/SerialPrograms/Source/CommonTools/StartupChecks/VideoResolutionCheck.h index 7fe0836426..edf898e525 100644 --- a/SerialPrograms/Source/CommonTools/StartupChecks/VideoResolutionCheck.h +++ b/SerialPrograms/Source/CommonTools/StartupChecks/VideoResolutionCheck.h @@ -1,26 +1,26 @@ -/* Video Resolution Check - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_VideoResolutionCheck_H -#define PokemonAutomation_CommonTools_VideoResolutionCheck_H - -namespace PokemonAutomation{ - -class Logger; -class ImageViewRGB32; -class VideoFeed; - - -void assert_16_9_720p_min(Logger& logger, const ImageViewRGB32& frame); -void assert_16_9_720p_min(Logger& logger, VideoFeed& video); - -void assert_16_9_1080p_min(Logger& logger, const ImageViewRGB32& frame); -void assert_16_9_1080p_min(Logger& logger, VideoFeed& video); - - - -} -#endif +/* Video Resolution Check + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_VideoResolutionCheck_H +#define PokemonAutomation_CommonTools_VideoResolutionCheck_H + +namespace PokemonAutomation{ + +class Logger; +class ImageViewRGB32; +class VideoFeed; + + +void assert_16_9_720p_min(Logger& logger, const ImageViewRGB32& frame); +void assert_16_9_720p_min(Logger& logger, VideoFeed& video); + +void assert_16_9_1080p_min(Logger& logger, const ImageViewRGB32& frame); +void assert_16_9_1080p_min(Logger& logger, VideoFeed& video); + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/TrendInference/AnomalyDetector.cpp b/SerialPrograms/Source/CommonTools/TrendInference/AnomalyDetector.cpp index 9dca5e0996..5a3f17828f 100644 --- a/SerialPrograms/Source/CommonTools/TrendInference/AnomalyDetector.cpp +++ b/SerialPrograms/Source/CommonTools/TrendInference/AnomalyDetector.cpp @@ -1,125 +1,125 @@ -/* Differential Anomaly Detector_H - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "AnomalyDetector.h" - -namespace PokemonAutomation{ - - -AnomalyDetector::AnomalyDetector(size_t window_size, double min_value, double max_value) - : m_window_size(window_size) - , m_min_value(min_value) - , m_max_value(max_value) - , m_sum(0) - , m_sum_sqr(0) -{ - double range = max_value - min_value; - double max_size = range * range * window_size; - m_scale_to_fixedpoint = std::sqrt(((uint64_t)1 << 63) / max_size); - m_scale_to_double = 1. / m_scale_to_fixedpoint; -} -double AnomalyDetector::push(double x){ - if (m_window.size() >= m_window_size){ - uint32_t fixed = m_window.front(); - m_window.pop_front(); - m_sum -= fixed; - m_sum_sqr -= (uint64_t)fixed * fixed; - } - - x -= m_min_value; - x = std::max(x, 0.); - x = std::min(x, m_max_value - m_min_value); - - uint32_t fixed = (uint32_t)(x * m_scale_to_fixedpoint); - m_window.emplace_back(fixed); - m_sum += fixed; - m_sum_sqr += (uint64_t)fixed * fixed; - - return sigma(x); -} -double AnomalyDetector::mean() const{ - size_t count = m_window.size(); - return m_sum / (double)count * m_scale_to_double + m_min_value; -} -double AnomalyDetector::stddev() const{ - size_t count = m_window.size(); - return std::sqrt((m_sum_sqr - m_sum*m_sum / (double)count) / (count - 1)) * m_scale_to_double; -} -double AnomalyDetector::sigma(double x) const{ - return std::abs((x - mean()) / stddev()); -} - - - -TimeNormalizedDeltaAnomalyDetector::TimeNormalizedDeltaAnomalyDetector(size_t window_size, double max_value) - : m_window_size(window_size) - , m_max_value(max_value) - , m_sum(0) - , m_sum_sqr(0) -{ - double max_size = max_value * max_value * window_size; - m_scale_to_fixedpoint = std::sqrt(((uint64_t)1 << 63) / max_size); - m_scale_to_double = 1. / m_scale_to_fixedpoint; -} -double TimeNormalizedDeltaAnomalyDetector::push( - double x, - std::chrono::time_point timestamp -){ - if (m_window.size() >= m_window_size){ - uint32_t fixed = m_window.front().fixed_point_value; - m_window.pop_front(); - m_sum -= fixed; - m_sum_sqr -= (uint64_t)fixed * fixed; - } - - if (m_window.empty()){ - m_window.emplace_back(); - Frame& frame = m_window.back(); - frame.timestamp = timestamp; - frame.fixed_point_value = 0; - return 0; - } - - auto time_diff = timestamp - m_window.back().timestamp; - uint32_t millis = (uint32_t)std::chrono::duration_cast(time_diff).count(); - x /= millis; - x = std::min(x, m_max_value); - - uint32_t fixed = (uint32_t)(x * m_scale_to_fixedpoint); - - m_window.emplace_back(); - Frame& frame = m_window.back(); - frame.timestamp = timestamp; - frame.fixed_point_value = fixed; - m_sum += fixed; - m_sum_sqr += (uint64_t)fixed * fixed; - - -// cout << x << " / " << stddev() << " = " << sigma(x) << endl; -// cout << "count = " << m_window.size() << endl; -// cout << "sum = " << m_sum << endl; -// cout << "m_sum_sqr = " << m_sum_sqr << endl; - return sigma(x); -} - -double TimeNormalizedDeltaAnomalyDetector::mean() const{ - size_t count = m_window.size(); - return m_sum / (double)count * m_scale_to_double; -} -double TimeNormalizedDeltaAnomalyDetector::stddev() const{ - size_t count = m_window.size(); - return std::sqrt((m_sum_sqr - m_sum*m_sum / (double)count) / (count - 1)) * m_scale_to_double; -} -double TimeNormalizedDeltaAnomalyDetector::sigma(double x) const{ - return std::abs((x - mean()) / stddev()); -} - - - -} - +/* Differential Anomaly Detector_H + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "AnomalyDetector.h" + +namespace PokemonAutomation{ + + +AnomalyDetector::AnomalyDetector(size_t window_size, double min_value, double max_value) + : m_window_size(window_size) + , m_min_value(min_value) + , m_max_value(max_value) + , m_sum(0) + , m_sum_sqr(0) +{ + double range = max_value - min_value; + double max_size = range * range * window_size; + m_scale_to_fixedpoint = std::sqrt(((uint64_t)1 << 63) / max_size); + m_scale_to_double = 1. / m_scale_to_fixedpoint; +} +double AnomalyDetector::push(double x){ + if (m_window.size() >= m_window_size){ + uint32_t fixed = m_window.front(); + m_window.pop_front(); + m_sum -= fixed; + m_sum_sqr -= (uint64_t)fixed * fixed; + } + + x -= m_min_value; + x = std::max(x, 0.); + x = std::min(x, m_max_value - m_min_value); + + uint32_t fixed = (uint32_t)(x * m_scale_to_fixedpoint); + m_window.emplace_back(fixed); + m_sum += fixed; + m_sum_sqr += (uint64_t)fixed * fixed; + + return sigma(x); +} +double AnomalyDetector::mean() const{ + size_t count = m_window.size(); + return m_sum / (double)count * m_scale_to_double + m_min_value; +} +double AnomalyDetector::stddev() const{ + size_t count = m_window.size(); + return std::sqrt((m_sum_sqr - m_sum*m_sum / (double)count) / (count - 1)) * m_scale_to_double; +} +double AnomalyDetector::sigma(double x) const{ + return std::abs((x - mean()) / stddev()); +} + + + +TimeNormalizedDeltaAnomalyDetector::TimeNormalizedDeltaAnomalyDetector(size_t window_size, double max_value) + : m_window_size(window_size) + , m_max_value(max_value) + , m_sum(0) + , m_sum_sqr(0) +{ + double max_size = max_value * max_value * window_size; + m_scale_to_fixedpoint = std::sqrt(((uint64_t)1 << 63) / max_size); + m_scale_to_double = 1. / m_scale_to_fixedpoint; +} +double TimeNormalizedDeltaAnomalyDetector::push( + double x, + std::chrono::time_point timestamp +){ + if (m_window.size() >= m_window_size){ + uint32_t fixed = m_window.front().fixed_point_value; + m_window.pop_front(); + m_sum -= fixed; + m_sum_sqr -= (uint64_t)fixed * fixed; + } + + if (m_window.empty()){ + m_window.emplace_back(); + Frame& frame = m_window.back(); + frame.timestamp = timestamp; + frame.fixed_point_value = 0; + return 0; + } + + auto time_diff = timestamp - m_window.back().timestamp; + uint32_t millis = (uint32_t)std::chrono::duration_cast(time_diff).count(); + x /= millis; + x = std::min(x, m_max_value); + + uint32_t fixed = (uint32_t)(x * m_scale_to_fixedpoint); + + m_window.emplace_back(); + Frame& frame = m_window.back(); + frame.timestamp = timestamp; + frame.fixed_point_value = fixed; + m_sum += fixed; + m_sum_sqr += (uint64_t)fixed * fixed; + + +// cout << x << " / " << stddev() << " = " << sigma(x) << endl; +// cout << "count = " << m_window.size() << endl; +// cout << "sum = " << m_sum << endl; +// cout << "m_sum_sqr = " << m_sum_sqr << endl; + return sigma(x); +} + +double TimeNormalizedDeltaAnomalyDetector::mean() const{ + size_t count = m_window.size(); + return m_sum / (double)count * m_scale_to_double; +} +double TimeNormalizedDeltaAnomalyDetector::stddev() const{ + size_t count = m_window.size(); + return std::sqrt((m_sum_sqr - m_sum*m_sum / (double)count) / (count - 1)) * m_scale_to_double; +} +double TimeNormalizedDeltaAnomalyDetector::sigma(double x) const{ + return std::abs((x - mean()) / stddev()); +} + + + +} + diff --git a/SerialPrograms/Source/CommonTools/TrendInference/AnomalyDetector.h b/SerialPrograms/Source/CommonTools/TrendInference/AnomalyDetector.h index 2dffd4b1a9..f631c1481b 100644 --- a/SerialPrograms/Source/CommonTools/TrendInference/AnomalyDetector.h +++ b/SerialPrograms/Source/CommonTools/TrendInference/AnomalyDetector.h @@ -1,67 +1,67 @@ -/* Differential Anomaly Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_DifferentialAnomalyDetector_H -#define PokemonAutomation_CommonTools_DifferentialAnomalyDetector_H - -#include -#include "Common/Cpp/Time.h" - -namespace PokemonAutomation{ - - -class AnomalyDetector{ -public: - AnomalyDetector(size_t window_size, double min_value, double max_value); - double push(double x); - - double mean() const; - double stddev() const; - double sigma(double x) const; - -private: - size_t m_window_size; - double m_min_value; - double m_max_value; - double m_scale_to_fixedpoint; - double m_scale_to_double; - uint64_t m_sum; - uint64_t m_sum_sqr; - std::deque m_window; -}; - - -class TimeNormalizedDeltaAnomalyDetector{ -public: - TimeNormalizedDeltaAnomalyDetector(size_t window_size, double max_value); - double push(double x, WallClock timestamp = current_time()); - - double mean() const; - double stddev() const; - double sigma(double x) const; - -private: - struct Frame{ - WallClock timestamp; - uint32_t fixed_point_value; - }; - - size_t m_window_size; - double m_max_value; - double m_scale_to_fixedpoint; - double m_scale_to_double; - uint64_t m_sum; - uint64_t m_sum_sqr; - std::deque m_window; -}; - - - - - -} - -#endif +/* Differential Anomaly Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_DifferentialAnomalyDetector_H +#define PokemonAutomation_CommonTools_DifferentialAnomalyDetector_H + +#include +#include "Common/Cpp/Time.h" + +namespace PokemonAutomation{ + + +class AnomalyDetector{ +public: + AnomalyDetector(size_t window_size, double min_value, double max_value); + double push(double x); + + double mean() const; + double stddev() const; + double sigma(double x) const; + +private: + size_t m_window_size; + double m_min_value; + double m_max_value; + double m_scale_to_fixedpoint; + double m_scale_to_double; + uint64_t m_sum; + uint64_t m_sum_sqr; + std::deque m_window; +}; + + +class TimeNormalizedDeltaAnomalyDetector{ +public: + TimeNormalizedDeltaAnomalyDetector(size_t window_size, double max_value); + double push(double x, WallClock timestamp = current_time()); + + double mean() const; + double stddev() const; + double sigma(double x) const; + +private: + struct Frame{ + WallClock timestamp; + uint32_t fixed_point_value; + }; + + size_t m_window_size; + double m_max_value; + double m_scale_to_fixedpoint; + double m_scale_to_double; + uint64_t m_sum; + uint64_t m_sum_sqr; + std::deque m_window; +}; + + + + + +} + +#endif diff --git a/SerialPrograms/Source/CommonTools/TrendInference/TimeWindowStatTracker.h b/SerialPrograms/Source/CommonTools/TrendInference/TimeWindowStatTracker.h index 20679adb1f..a7fe560a39 100644 --- a/SerialPrograms/Source/CommonTools/TrendInference/TimeWindowStatTracker.h +++ b/SerialPrograms/Source/CommonTools/TrendInference/TimeWindowStatTracker.h @@ -1,142 +1,142 @@ -/* Time Window Stat Tracker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_TimeWindowStatTracker_H -#define PokemonAutomation_CommonTools_TimeWindowStatTracker_H - -#include -#include - -namespace PokemonAutomation{ - - -template -class TimeWindowStatTracker{ - using milliseconds = std::chrono::milliseconds; - using system_clock = std::chrono::system_clock; - using StatObject = typename StatAccumulator::StatObject; - -public: - TimeWindowStatTracker(milliseconds window) - : m_window(window) - {} - - milliseconds window() const{ - return m_window; - } - - const StatObject& oldest() const{ - return m_history.begin()->second; - } - const StatObject& newest() const{ - return m_history.rbegin()->second; - } - - system_clock::time_point push( - const StatObject& stats, - system_clock::time_point timestamp = system_clock::now() - ){ - m_history.emplace( - std::piecewise_construct, - std::forward_as_tuple(timestamp), - std::forward_as_tuple(stats) - ); - - system_clock::time_point tail = timestamp - m_window; - while (!m_history.empty() && m_history.begin()->first < tail){ - m_history.erase(m_history.begin()); - } - - return timestamp; - } - system_clock::time_point push( - StatObject&& stats, - system_clock::time_point timestamp = system_clock::now() - ){ - m_history.emplace( - std::piecewise_construct, - std::forward_as_tuple(timestamp), - std::forward_as_tuple(std::move(stats)) - ); - - system_clock::time_point tail = timestamp - m_window; - while (!m_history.empty() && m_history.begin()->first < tail){ - m_history.erase(m_history.begin()); - } - - return timestamp; - } - - // Accumulate entire history. - StatAccumulator accumulate_all() const{ - return accumulate(m_history.begin(), m_history.end()); - } - - // Accumulate [latest - duration, latest]. - StatAccumulator accumulate_last( - milliseconds duration - ) const{ - return accumulate( - m_history.empty() - ? m_history.end() - : m_history.lower_bound(m_history.rbegin()->first - duration), - m_history.end() - ); - } - - // Accumulate [oldest, point]. - StatAccumulator accumulate_start_to_point( - system_clock::time_point point - ) const{ - return accumulate(m_history.begin, m_history.upper_bound(point)); - } - - // Accumulate [oldest, latest - time_behind_latest]. - StatAccumulator accumulate_start_to_point( - milliseconds time_behind_latest - ) const{ - return accumulate( - m_history.begin(), - m_history.empty() - ? m_history.end() - : m_history.upper_bound(m_history.rbegin()->first - time_behind_latest) - ); - } - - // Accumulate [start, end]. - StatAccumulator accumulate( - system_clock::time_point start, - system_clock::time_point end - ) const{ - return accumulate(m_history.lower_bound(start), m_history.upper_bound(end)); - } - - -private: - using const_iterator_type = typename std::map::const_iterator; - - StatAccumulator accumulate( - const_iterator_type start, - const_iterator_type end - ) const{ - StatAccumulator accumulator; - for (; start != end; ++start){ - accumulator += start->second; - } - return accumulator; - } - - -private: - milliseconds m_window; - std::map m_history; - -}; - - - -} -#endif +/* Time Window Stat Tracker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_TimeWindowStatTracker_H +#define PokemonAutomation_CommonTools_TimeWindowStatTracker_H + +#include +#include + +namespace PokemonAutomation{ + + +template +class TimeWindowStatTracker{ + using milliseconds = std::chrono::milliseconds; + using system_clock = std::chrono::system_clock; + using StatObject = typename StatAccumulator::StatObject; + +public: + TimeWindowStatTracker(milliseconds window) + : m_window(window) + {} + + milliseconds window() const{ + return m_window; + } + + const StatObject& oldest() const{ + return m_history.begin()->second; + } + const StatObject& newest() const{ + return m_history.rbegin()->second; + } + + system_clock::time_point push( + const StatObject& stats, + system_clock::time_point timestamp = system_clock::now() + ){ + m_history.emplace( + std::piecewise_construct, + std::forward_as_tuple(timestamp), + std::forward_as_tuple(stats) + ); + + system_clock::time_point tail = timestamp - m_window; + while (!m_history.empty() && m_history.begin()->first < tail){ + m_history.erase(m_history.begin()); + } + + return timestamp; + } + system_clock::time_point push( + StatObject&& stats, + system_clock::time_point timestamp = system_clock::now() + ){ + m_history.emplace( + std::piecewise_construct, + std::forward_as_tuple(timestamp), + std::forward_as_tuple(std::move(stats)) + ); + + system_clock::time_point tail = timestamp - m_window; + while (!m_history.empty() && m_history.begin()->first < tail){ + m_history.erase(m_history.begin()); + } + + return timestamp; + } + + // Accumulate entire history. + StatAccumulator accumulate_all() const{ + return accumulate(m_history.begin(), m_history.end()); + } + + // Accumulate [latest - duration, latest]. + StatAccumulator accumulate_last( + milliseconds duration + ) const{ + return accumulate( + m_history.empty() + ? m_history.end() + : m_history.lower_bound(m_history.rbegin()->first - duration), + m_history.end() + ); + } + + // Accumulate [oldest, point]. + StatAccumulator accumulate_start_to_point( + system_clock::time_point point + ) const{ + return accumulate(m_history.begin, m_history.upper_bound(point)); + } + + // Accumulate [oldest, latest - time_behind_latest]. + StatAccumulator accumulate_start_to_point( + milliseconds time_behind_latest + ) const{ + return accumulate( + m_history.begin(), + m_history.empty() + ? m_history.end() + : m_history.upper_bound(m_history.rbegin()->first - time_behind_latest) + ); + } + + // Accumulate [start, end]. + StatAccumulator accumulate( + system_clock::time_point start, + system_clock::time_point end + ) const{ + return accumulate(m_history.lower_bound(start), m_history.upper_bound(end)); + } + + +private: + using const_iterator_type = typename std::map::const_iterator; + + StatAccumulator accumulate( + const_iterator_type start, + const_iterator_type end + ) const{ + StatAccumulator accumulator; + for (; start != end; ++start){ + accumulator += start->second; + } + return accumulator; + } + + +private: + milliseconds m_window; + std::map m_history; + +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/VisualDetector.h b/SerialPrograms/Source/CommonTools/VisualDetector.h index 660fe6e68d..5293d0c3ee 100644 --- a/SerialPrograms/Source/CommonTools/VisualDetector.h +++ b/SerialPrograms/Source/CommonTools/VisualDetector.h @@ -1,130 +1,143 @@ -/* Visual Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_VisualDetector_H -#define PokemonAutomation_CommonTools_VisualDetector_H - -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ - -class ImageViewRGB32; -class VideoOverlaySet; - - -class StaticScreenDetector{ -public: - virtual ~StaticScreenDetector() = default; - virtual void make_overlays(VideoOverlaySet& items) const = 0; - - // This is not const so that detectors can save/cache state. - virtual bool detect(const ImageViewRGB32& screen) = 0; -}; - - - -// Wrap a detector into a finder. -// This one requires the detector to return the same result consecutively for X time -// before returning true from process_frame(). -template -class DetectorToFinder : public Detector, public VisualInferenceCallback{ -public: - // Whether a finder is to find an object is detected by the detector or find - // that it's no longer detected. - enum class FinderType{ - PRESENT, // process_frame() returns true only when detected consecutively - GONE, // process_frame() returns true only when not detected consecutively - CONSISTENT, // process_frame() returns true when detected consecutively or not detected consecutively - }; - - template - DetectorToFinder( - std::string label, - std::chrono::milliseconds duration, - Args&&... args - ) - : Detector(std::forward(args)...) - , VisualInferenceCallback(std::move(label)) - , m_duration(duration) - , m_finder_type(FinderType::PRESENT) - {} - - - template - DetectorToFinder( - std::string label, - FinderType finder_type, - std::chrono::milliseconds duration, - Args&&... args - ) - : Detector(std::forward(args)...) - , VisualInferenceCallback(std::move(label)) - , m_duration(duration) - , m_finder_type(finder_type) - {} - - virtual void make_overlays(VideoOverlaySet& items) const override{ - Detector::make_overlays(items); - } - - // If m_finder_type is PRESENT, return true only when it is consecutively detected. - // If m_finder_type is GONE, return true only when it is consecutively not detected. - // if m_finder_type is CONSISTENT, return true when it is consecutively detected, or consecutively not detected. - using VisualInferenceCallback::process_frame; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override{ - switch (m_finder_type){ - case FinderType::PRESENT: - case FinderType::GONE: - if (this->detect(frame) == (m_finder_type == FinderType::GONE)){ - m_start_of_detection = WallClock::min(); - return false; - } - if (m_start_of_detection == WallClock::min()){ - m_start_of_detection = timestamp; - } - return timestamp - m_start_of_detection >= m_duration; - case FinderType::CONSISTENT:{ - const bool result = this->detect(frame); - const bool result_changed = (result && m_last_detected < 0) || (!result && m_last_detected > 0); - - m_last_detected = (result ? 1 : -1); - - if (result_changed){ - m_start_of_detection = WallClock::min(); - return false; - } - if (m_start_of_detection == WallClock::min()){ - m_start_of_detection = timestamp; - } - - const bool enough_time = timestamp - m_start_of_detection >= m_duration; - if (enough_time){ - m_consistent_result = m_last_detected > 0; - } - return enough_time; - } - default:; - } - return false; - } - - // If m_finder_type is CONSISTENT and process_frame() returns true, - // whether it is consecutively detected , or consecutively not detected. - bool consistent_result() const { return m_consistent_result; } - -private: - std::chrono::milliseconds m_duration; - FinderType m_finder_type; - WallClock m_start_of_detection = WallClock::min(); - int8_t m_last_detected = 0; // 0: no prior detection, 1: last detected positive, -1: last detected negative - bool m_consistent_result = false; -}; - - - - -} -#endif +/* Visual Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_VisualDetector_H +#define PokemonAutomation_CommonTools_VisualDetector_H + +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ + +class ImageViewRGB32; +class VideoOverlaySet; + + +class StaticScreenDetector{ +public: + virtual ~StaticScreenDetector() = default; + virtual void make_overlays(VideoOverlaySet& items) const = 0; + + // This is not const so that detectors can save/cache state. + virtual bool detect(const ImageViewRGB32& screen) = 0; + + virtual void commit_state(){} +}; + + + +// Wrap a detector into a finder. +// This one requires the detector to return the same result consecutively for X time +// before returning true from process_frame(). +template +class DetectorToFinder : public Detector, public VisualInferenceCallback{ +public: + // Whether a finder is to find an object is detected by the detector or find + // that it's no longer detected. + enum class FinderType{ + PRESENT, // process_frame() returns true only when detected consecutively + GONE, // process_frame() returns true only when not detected consecutively + CONSISTENT, // process_frame() returns true when detected consecutively or not detected consecutively + }; + + template + DetectorToFinder( + std::string label, + std::chrono::milliseconds duration, + Args&&... args + ) + : Detector(std::forward(args)...) + , VisualInferenceCallback(std::move(label)) + , m_duration(duration) + , m_finder_type(FinderType::PRESENT) + {} + + + template + DetectorToFinder( + std::string label, + FinderType finder_type, + std::chrono::milliseconds duration, + Args&&... args + ) + : Detector(std::forward(args)...) + , VisualInferenceCallback(std::move(label)) + , m_duration(duration) + , m_finder_type(finder_type) + {} + + virtual void make_overlays(VideoOverlaySet& items) const override{ + Detector::make_overlays(items); + } + + // If m_finder_type is PRESENT, return true only when it is consecutively detected. + // If m_finder_type is GONE, return true only when it is consecutively not detected. + // if m_finder_type is CONSISTENT, return true when it is consecutively detected, or consecutively not detected. + using VisualInferenceCallback::process_frame; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override{ + switch (m_finder_type){ + case FinderType::PRESENT: + case FinderType::GONE: + if (this->detect(frame) == (m_finder_type == FinderType::GONE)){ + m_start_of_detection = WallClock::min(); + return false; + } + if (m_start_of_detection == WallClock::min()){ + m_start_of_detection = timestamp; + } + + if (timestamp - m_start_of_detection >= m_duration){ + this->commit_state(); + return true; + }else{ + return false; + } + case FinderType::CONSISTENT:{ + const bool result = this->detect(frame); + const bool result_changed = (result && m_last_detected < 0) || (!result && m_last_detected > 0); + + m_last_detected = (result ? 1 : -1); + + if (result_changed){ + m_start_of_detection = WallClock::min(); + return false; + } + if (m_start_of_detection == WallClock::min()){ + m_start_of_detection = timestamp; + } + + const bool enough_time = timestamp - m_start_of_detection >= m_duration; + if (enough_time){ + m_consistent_result = m_last_detected > 0; + } + if (enough_time){ + this->commit_state(); + return true; + }else{ + return false; + } + } + default:; + } + return false; + } + + // If m_finder_type is CONSISTENT and process_frame() returns true, + // whether it is consecutively detected , or consecutively not detected. + bool consistent_result() const { return m_consistent_result; } + +private: + std::chrono::milliseconds m_duration; + FinderType m_finder_type; + WallClock m_start_of_detection = WallClock::min(); + int8_t m_last_detected = 0; // 0: no prior detection, 1: last detected positive, -1: last detected negative + bool m_consistent_result = false; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/VisualDetectors/BlackBorderDetector.cpp b/SerialPrograms/Source/CommonTools/VisualDetectors/BlackBorderDetector.cpp index b89e20514c..f48304e8c7 100644 --- a/SerialPrograms/Source/CommonTools/VisualDetectors/BlackBorderDetector.cpp +++ b/SerialPrograms/Source/CommonTools/VisualDetectors/BlackBorderDetector.cpp @@ -1,75 +1,75 @@ -/* Black Border Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "BlackBorderDetector.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - -BlackBorderDetector::BlackBorderDetector() - : m_top(0.001, 0.001, 0.997, 0.002) - , m_bottom(0.001, 0.997, 0.997, 0.002) - , m_left(0.001, 0.001, 0.002, 0.997) - , m_right(0.997, 0.001, 0.002, 0.997) -// , m_body(0.100, 0.100, 0.800, 0.800) -{} - -void BlackBorderDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_top); - items.add(COLOR_RED, m_bottom); - items.add(COLOR_RED, m_left); - items.add(COLOR_RED, m_right); -// items.add(COLOR_RED, m_body); -} -bool BlackBorderDetector::detect(const ImageViewRGB32& screen){ - const double MAX_SUM = 50; - const double MAX_STDDEV = 20; - - ImageStats top = image_stats(extract_box_reference(screen, m_top)); -// cout << "top = " << top.average << top.stddev << endl; -// extract_box(screen, m_top).save("top.png"); - if (!is_black(top, MAX_SUM, MAX_STDDEV)){ - return false; - } - ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); -// cout << "bottom = " << bottom.average << bottom.stddev << endl; - if (!is_black(bottom, MAX_SUM, MAX_STDDEV)){ - return false; - } - ImageStats left = image_stats(extract_box_reference(screen, m_left)); -// cout << "left = " << left.average << left.stddev << endl; - if (!is_black(left, MAX_SUM, MAX_STDDEV)){ - return false; - } - ImageStats right = image_stats(extract_box_reference(screen, m_right)); -// cout << "right = " << right.average << right.stddev << endl; - if (!is_black(right, MAX_SUM, MAX_STDDEV)){ - return false; - } -// ImageStats body = image_stats(extract_box_reference(screen, m_body)); -// cout << "body = " << body.average << body.stddev << endl; -// if (is_black(right, 30, 30)){ -// return false; -// } - - -// for (int c = 0; c < screen.width(); c++){ -// QRgb pixel = screen.pixel(c, 0); -// cout << "(" << qRed(pixel) << "," << qGreen(pixel) << "," << qBlue(pixel) << ")"; -// } - - return true; -} - - -} +/* Black Border Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "BlackBorderDetector.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + +BlackBorderDetector::BlackBorderDetector() + : m_top(0.001, 0.001, 0.997, 0.002) + , m_bottom(0.001, 0.997, 0.997, 0.002) + , m_left(0.001, 0.001, 0.002, 0.997) + , m_right(0.997, 0.001, 0.002, 0.997) +// , m_body(0.100, 0.100, 0.800, 0.800) +{} + +void BlackBorderDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_top); + items.add(COLOR_RED, m_bottom); + items.add(COLOR_RED, m_left); + items.add(COLOR_RED, m_right); +// items.add(COLOR_RED, m_body); +} +bool BlackBorderDetector::detect(const ImageViewRGB32& screen){ + const double MAX_SUM = 50; + const double MAX_STDDEV = 20; + + ImageStats top = image_stats(extract_box_reference(screen, m_top)); +// cout << "top = " << top.average << top.stddev << endl; +// extract_box(screen, m_top).save("top.png"); + if (!is_black(top, MAX_SUM, MAX_STDDEV)){ + return false; + } + ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); +// cout << "bottom = " << bottom.average << bottom.stddev << endl; + if (!is_black(bottom, MAX_SUM, MAX_STDDEV)){ + return false; + } + ImageStats left = image_stats(extract_box_reference(screen, m_left)); +// cout << "left = " << left.average << left.stddev << endl; + if (!is_black(left, MAX_SUM, MAX_STDDEV)){ + return false; + } + ImageStats right = image_stats(extract_box_reference(screen, m_right)); +// cout << "right = " << right.average << right.stddev << endl; + if (!is_black(right, MAX_SUM, MAX_STDDEV)){ + return false; + } +// ImageStats body = image_stats(extract_box_reference(screen, m_body)); +// cout << "body = " << body.average << body.stddev << endl; +// if (is_black(right, 30, 30)){ +// return false; +// } + + +// for (int c = 0; c < screen.width(); c++){ +// QRgb pixel = screen.pixel(c, 0); +// cout << "(" << qRed(pixel) << "," << qGreen(pixel) << "," << qBlue(pixel) << ")"; +// } + + return true; +} + + +} diff --git a/SerialPrograms/Source/CommonTools/VisualDetectors/BlackBorderDetector.h b/SerialPrograms/Source/CommonTools/VisualDetectors/BlackBorderDetector.h index 17e631dd3e..623310733f 100644 --- a/SerialPrograms/Source/CommonTools/VisualDetectors/BlackBorderDetector.h +++ b/SerialPrograms/Source/CommonTools/VisualDetectors/BlackBorderDetector.h @@ -1,34 +1,34 @@ -/* Black Screen Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_BlackBorderDetector_H -#define PokemonAutomation_CommonTools_BlackBorderDetector_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ - - -class BlackBorderDetector : public StaticScreenDetector{ -public: - BlackBorderDetector(); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - ImageFloatBox m_top; - ImageFloatBox m_bottom; - ImageFloatBox m_left; - ImageFloatBox m_right; -// ImageFloatBox m_body; -}; - - - -} -#endif +/* Black Screen Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_BlackBorderDetector_H +#define PokemonAutomation_CommonTools_BlackBorderDetector_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ + + +class BlackBorderDetector : public StaticScreenDetector{ +public: + BlackBorderDetector(); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + ImageFloatBox m_top; + ImageFloatBox m_bottom; + ImageFloatBox m_left; + ImageFloatBox m_right; +// ImageFloatBox m_body; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/VisualDetectors/BlackScreenDetector.cpp b/SerialPrograms/Source/CommonTools/VisualDetectors/BlackScreenDetector.cpp index a3fa6178c0..774fae59b2 100644 --- a/SerialPrograms/Source/CommonTools/VisualDetectors/BlackScreenDetector.cpp +++ b/SerialPrograms/Source/CommonTools/VisualDetectors/BlackScreenDetector.cpp @@ -1,128 +1,128 @@ -/* Black Border Detector - * - * From: https://github.com/PokemonAutomation/ - * - * - * Returns true after a black screen has been detected and - * the black screen has ended. - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "BlackScreenDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -BlackScreenDetector::BlackScreenDetector( - Color color, const ImageFloatBox& box, - double max_rgb_sum, - double max_stddev_sum -) - : m_color(color) - , m_box(box) - , m_max_rgb_sum(max_rgb_sum) - , m_max_stddev_sum(max_stddev_sum) -{} -void BlackScreenDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} -bool BlackScreenDetector::detect(const ImageViewRGB32& screen){ - return is_black(extract_box_reference(screen, m_box), m_max_rgb_sum, m_max_stddev_sum); -} - - - -WhiteScreenDetector::WhiteScreenDetector( - Color color, const ImageFloatBox& box, - double min_rgb_sum, - double max_stddev_sum -) - : m_color(color) - , m_box(box) - , m_min_rgb_sum(min_rgb_sum) - , m_max_stddev_sum(max_stddev_sum) -{} -void WhiteScreenDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} -bool WhiteScreenDetector::detect(const ImageViewRGB32& screen){ - return is_white(extract_box_reference(screen, m_box), m_min_rgb_sum, m_max_stddev_sum); -} - - - - - - -BlackScreenOverWatcher::BlackScreenOverWatcher( - Color color, const ImageFloatBox& box, - double max_rgb_sum, - double max_stddev_sum, - std::chrono::milliseconds hold_duration, - std::chrono::milliseconds release_duration -) - : VisualInferenceCallback("BlackScreenOverWatcher") - , m_on(color, box, max_rgb_sum, max_stddev_sum, BlackScreenWatcher::FinderType::PRESENT, hold_duration) - , m_off(color, box, max_rgb_sum, max_stddev_sum, BlackScreenWatcher::FinderType::GONE, release_duration) -{} -void BlackScreenOverWatcher::make_overlays(VideoOverlaySet& items) const{ - m_on.make_overlays(items); -} -bool BlackScreenOverWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - if (m_black_is_over.load(std::memory_order_acquire)){ - return true; - } - if (!m_has_been_black){ - m_has_been_black = m_on.process_frame(frame, timestamp); - return false; - } - - bool is_over = m_off.process_frame(frame, timestamp); - if (!is_over){ - return false; - } - m_black_is_over.store(true, std::memory_order_release); - return true; -} -bool BlackScreenOverWatcher::black_is_over(const ImageViewRGB32& frame){ - return m_black_is_over.load(std::memory_order_acquire); -} - - - - -WhiteScreenOverWatcher::WhiteScreenOverWatcher( - Color color, const ImageFloatBox& box, - double min_rgb_sum, - double max_stddev_sum -) - : VisualInferenceCallback("BlackScreenOverWatcher") - , m_detector(color, box, min_rgb_sum, max_stddev_sum) -{} -void WhiteScreenOverWatcher::make_overlays(VideoOverlaySet& items) const{ - m_detector.make_overlays(items); -} - -bool WhiteScreenOverWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return white_is_over(frame); -} -bool WhiteScreenOverWatcher::white_is_over(const ImageViewRGB32& frame){ - if (m_detector.detect(frame)){ - m_has_been_white = true; - return false; - } - return m_has_been_white; -} - - - - - - -} +/* Black Border Detector + * + * From: https://github.com/PokemonAutomation/ + * + * + * Returns true after a black screen has been detected and + * the black screen has ended. + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "BlackScreenDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +BlackScreenDetector::BlackScreenDetector( + Color color, const ImageFloatBox& box, + double max_rgb_sum, + double max_stddev_sum +) + : m_color(color) + , m_box(box) + , m_max_rgb_sum(max_rgb_sum) + , m_max_stddev_sum(max_stddev_sum) +{} +void BlackScreenDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} +bool BlackScreenDetector::detect(const ImageViewRGB32& screen){ + return is_black(extract_box_reference(screen, m_box), m_max_rgb_sum, m_max_stddev_sum); +} + + + +WhiteScreenDetector::WhiteScreenDetector( + Color color, const ImageFloatBox& box, + double min_rgb_sum, + double max_stddev_sum +) + : m_color(color) + , m_box(box) + , m_min_rgb_sum(min_rgb_sum) + , m_max_stddev_sum(max_stddev_sum) +{} +void WhiteScreenDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} +bool WhiteScreenDetector::detect(const ImageViewRGB32& screen){ + return is_white(extract_box_reference(screen, m_box), m_min_rgb_sum, m_max_stddev_sum); +} + + + + + + +BlackScreenOverWatcher::BlackScreenOverWatcher( + Color color, const ImageFloatBox& box, + double max_rgb_sum, + double max_stddev_sum, + std::chrono::milliseconds hold_duration, + std::chrono::milliseconds release_duration +) + : VisualInferenceCallback("BlackScreenOverWatcher") + , m_on(color, box, max_rgb_sum, max_stddev_sum, BlackScreenWatcher::FinderType::PRESENT, hold_duration) + , m_off(color, box, max_rgb_sum, max_stddev_sum, BlackScreenWatcher::FinderType::GONE, release_duration) +{} +void BlackScreenOverWatcher::make_overlays(VideoOverlaySet& items) const{ + m_on.make_overlays(items); +} +bool BlackScreenOverWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + if (m_black_is_over.load(std::memory_order_acquire)){ + return true; + } + if (!m_has_been_black){ + m_has_been_black = m_on.process_frame(frame, timestamp); + return false; + } + + bool is_over = m_off.process_frame(frame, timestamp); + if (!is_over){ + return false; + } + m_black_is_over.store(true, std::memory_order_release); + return true; +} +bool BlackScreenOverWatcher::black_is_over(const ImageViewRGB32& frame){ + return m_black_is_over.load(std::memory_order_acquire); +} + + + + +WhiteScreenOverWatcher::WhiteScreenOverWatcher( + Color color, const ImageFloatBox& box, + double min_rgb_sum, + double max_stddev_sum +) + : VisualInferenceCallback("BlackScreenOverWatcher") + , m_detector(color, box, min_rgb_sum, max_stddev_sum) +{} +void WhiteScreenOverWatcher::make_overlays(VideoOverlaySet& items) const{ + m_detector.make_overlays(items); +} + +bool WhiteScreenOverWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return white_is_over(frame); +} +bool WhiteScreenOverWatcher::white_is_over(const ImageViewRGB32& frame){ + if (m_detector.detect(frame)){ + m_has_been_white = true; + return false; + } + return m_has_been_white; +} + + + + + + +} diff --git a/SerialPrograms/Source/CommonTools/VisualDetectors/BlackScreenDetector.h b/SerialPrograms/Source/CommonTools/VisualDetectors/BlackScreenDetector.h index e1b385a7ac..12c99b2a01 100644 --- a/SerialPrograms/Source/CommonTools/VisualDetectors/BlackScreenDetector.h +++ b/SerialPrograms/Source/CommonTools/VisualDetectors/BlackScreenDetector.h @@ -1,126 +1,126 @@ -/* Black Screen Detector - * - * From: https://github.com/PokemonAutomation/ - * - * - * Returns true after a black screen has been detected and - * the black screen has ended. - * - */ - -#ifndef PokemonAutomation_CommonTools_BlackScreenDetector_H -#define PokemonAutomation_CommonTools_BlackScreenDetector_H - -#include -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ - - -class BlackScreenDetector : public StaticScreenDetector{ -public: - BlackScreenDetector( - Color color = COLOR_RED, - const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, - double max_rgb_sum = 100, - double max_stddev_sum = 10 - ); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_box; - double m_max_rgb_sum; - double m_max_stddev_sum; -}; -class WhiteScreenDetector : public StaticScreenDetector{ -public: - WhiteScreenDetector( - Color color = COLOR_RED, - const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, - double min_rgb_sum = 500, - double max_stddev_sum = 10 - ); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_box; - double m_min_rgb_sum; - double m_max_stddev_sum; -}; - - -class BlackScreenWatcher : public DetectorToFinder{ -public: - BlackScreenWatcher( - Color color = COLOR_RED, - const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, - double max_rgb_sum = 100, - double max_stddev_sum = 10, - FinderType finder_type = FinderType::PRESENT, - std::chrono::milliseconds duration = std::chrono::milliseconds(100) - ) - : DetectorToFinder("BlackScreenWatcher", finder_type, duration, color, box, max_rgb_sum, max_stddev_sum) - {} -}; - -// Detect when a period of black screen is over -class BlackScreenOverWatcher : public VisualInferenceCallback{ -public: - BlackScreenOverWatcher( - Color color = COLOR_RED, - const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, - double max_rgb_sum = 100, - double max_stddev_sum = 10, - std::chrono::milliseconds hold_duration = std::chrono::milliseconds(100), - std::chrono::milliseconds release_duration = std::chrono::milliseconds(100) - ); - - bool black_is_over(const ImageViewRGB32& frame); - - virtual void make_overlays(VideoOverlaySet& items) const override; - - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - BlackScreenWatcher m_on; - BlackScreenWatcher m_off; - bool m_has_been_black = false; - std::atomic m_black_is_over = false; -}; - - - - -class WhiteScreenOverWatcher : public VisualInferenceCallback{ -public: - WhiteScreenOverWatcher( - Color color = COLOR_RED, - const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, - double min_rgb_sum = 500, - double max_stddev_sum = 10 - ); - - bool white_is_over(const ImageViewRGB32& frame); - - virtual void make_overlays(VideoOverlaySet& items) const override; - - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - WhiteScreenDetector m_detector; - bool m_has_been_white = false; -}; - - - -} -#endif +/* Black Screen Detector + * + * From: https://github.com/PokemonAutomation/ + * + * + * Returns true after a black screen has been detected and + * the black screen has ended. + * + */ + +#ifndef PokemonAutomation_CommonTools_BlackScreenDetector_H +#define PokemonAutomation_CommonTools_BlackScreenDetector_H + +#include +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ + + +class BlackScreenDetector : public StaticScreenDetector{ +public: + BlackScreenDetector( + Color color = COLOR_RED, + const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, + double max_rgb_sum = 100, + double max_stddev_sum = 10 + ); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_box; + double m_max_rgb_sum; + double m_max_stddev_sum; +}; +class WhiteScreenDetector : public StaticScreenDetector{ +public: + WhiteScreenDetector( + Color color = COLOR_RED, + const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, + double min_rgb_sum = 500, + double max_stddev_sum = 10 + ); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_box; + double m_min_rgb_sum; + double m_max_stddev_sum; +}; + + +class BlackScreenWatcher : public DetectorToFinder{ +public: + BlackScreenWatcher( + Color color = COLOR_RED, + const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, + double max_rgb_sum = 100, + double max_stddev_sum = 10, + FinderType finder_type = FinderType::PRESENT, + std::chrono::milliseconds duration = std::chrono::milliseconds(100) + ) + : DetectorToFinder("BlackScreenWatcher", finder_type, duration, color, box, max_rgb_sum, max_stddev_sum) + {} +}; + +// Detect when a period of black screen is over +class BlackScreenOverWatcher : public VisualInferenceCallback{ +public: + BlackScreenOverWatcher( + Color color = COLOR_RED, + const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, + double max_rgb_sum = 100, + double max_stddev_sum = 10, + std::chrono::milliseconds hold_duration = std::chrono::milliseconds(100), + std::chrono::milliseconds release_duration = std::chrono::milliseconds(100) + ); + + bool black_is_over(const ImageViewRGB32& frame); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + BlackScreenWatcher m_on; + BlackScreenWatcher m_off; + bool m_has_been_black = false; + std::atomic m_black_is_over = false; +}; + + + + +class WhiteScreenOverWatcher : public VisualInferenceCallback{ +public: + WhiteScreenOverWatcher( + Color color = COLOR_RED, + const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, + double min_rgb_sum = 500, + double max_stddev_sum = 10 + ); + + bool white_is_over(const ImageViewRGB32& frame); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + WhiteScreenDetector m_detector; + bool m_has_been_white = false; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/VisualDetectors/FrozenImageDetector.cpp b/SerialPrograms/Source/CommonTools/VisualDetectors/FrozenImageDetector.cpp index f9609adb80..d3d07d81b7 100644 --- a/SerialPrograms/Source/CommonTools/VisualDetectors/FrozenImageDetector.cpp +++ b/SerialPrograms/Source/CommonTools/VisualDetectors/FrozenImageDetector.cpp @@ -1,63 +1,63 @@ -/* Frozen Screen Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "FrozenImageDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -FrozenImageDetector::FrozenImageDetector(std::chrono::milliseconds timeout, double rmsd_threshold) - : VisualInferenceCallback("FrozenImageDetector") - , m_color(COLOR_CYAN) - , m_box(0.0, 0.0, 1.0, 1.0) - , m_timeout(timeout) - , m_rmsd_threshold(rmsd_threshold) -{} -FrozenImageDetector::FrozenImageDetector( - Color color, const ImageFloatBox& box, - std::chrono::milliseconds timeout, double rmsd_threshold -) - : VisualInferenceCallback("FrozenImageDetector") - , m_color(color) - , m_box(box) - , m_timeout(timeout) - , m_rmsd_threshold(rmsd_threshold) -{} -void FrozenImageDetector::make_overlays(VideoOverlaySet& set) const{ - set.add(m_color, m_box); -} -bool FrozenImageDetector::process_frame(const VideoSnapshot& frame){ - if (m_previous->width() != frame->width() || m_previous->height() != frame->height()){ - m_previous = frame; - return false; - } - - double rmsd = ImageMatch::pixel_RMSD( - extract_box_reference(m_previous, m_box), - extract_box_reference(frame, m_box) - ); -// cout << "rmsd = " << rmsd << endl; - if (rmsd > m_rmsd_threshold){ - m_previous = frame; - return false; - } - - return frame.timestamp - m_previous.timestamp > m_timeout; -// return false; -} -bool FrozenImageDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return process_frame(VideoSnapshot(frame.copy(), timestamp)); -} - - -} +/* Frozen Screen Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "FrozenImageDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +FrozenImageDetector::FrozenImageDetector(std::chrono::milliseconds timeout, double rmsd_threshold) + : VisualInferenceCallback("FrozenImageDetector") + , m_color(COLOR_CYAN) + , m_box(0.0, 0.0, 1.0, 1.0) + , m_timeout(timeout) + , m_rmsd_threshold(rmsd_threshold) +{} +FrozenImageDetector::FrozenImageDetector( + Color color, const ImageFloatBox& box, + std::chrono::milliseconds timeout, double rmsd_threshold +) + : VisualInferenceCallback("FrozenImageDetector") + , m_color(color) + , m_box(box) + , m_timeout(timeout) + , m_rmsd_threshold(rmsd_threshold) +{} +void FrozenImageDetector::make_overlays(VideoOverlaySet& set) const{ + set.add(m_color, m_box); +} +bool FrozenImageDetector::process_frame(const VideoSnapshot& frame){ + if (m_previous->width() != frame->width() || m_previous->height() != frame->height()){ + m_previous = frame; + return false; + } + + double rmsd = ImageMatch::pixel_RMSD( + extract_box_reference(m_previous, m_box), + extract_box_reference(frame, m_box) + ); +// cout << "rmsd = " << rmsd << endl; + if (rmsd > m_rmsd_threshold){ + m_previous = frame; + return false; + } + + return frame.timestamp - m_previous.timestamp > m_timeout; +// return false; +} +bool FrozenImageDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return process_frame(VideoSnapshot(frame.copy(), timestamp)); +} + + +} diff --git a/SerialPrograms/Source/CommonTools/VisualDetectors/FrozenImageDetector.h b/SerialPrograms/Source/CommonTools/VisualDetectors/FrozenImageDetector.h index ae01bf41a9..8b14c133dd 100644 --- a/SerialPrograms/Source/CommonTools/VisualDetectors/FrozenImageDetector.h +++ b/SerialPrograms/Source/CommonTools/VisualDetectors/FrozenImageDetector.h @@ -1,43 +1,43 @@ -/* Frozen Screen Detector - * - * From: https://github.com/PokemonAutomation/ - * - * Detect if the entire screen is frozen. - */ - -#ifndef PokemonAutomation_CommonTools_FrozenImageDetector_H -#define PokemonAutomation_CommonTools_FrozenImageDetector_H - -#include "Common/Cpp/Color.h" -//#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ - - -class FrozenImageDetector : public VisualInferenceCallback{ -public: - FrozenImageDetector(std::chrono::milliseconds timeout, double rmsd_threshold); - FrozenImageDetector( - Color color, const ImageFloatBox& box, - std::chrono::milliseconds timeout, double rmsd_threshold - ); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const VideoSnapshot& frame) override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - Color m_color; - ImageFloatBox m_box; - std::chrono::milliseconds m_timeout; - double m_rmsd_threshold; - VideoSnapshot m_previous; -}; - - - -} -#endif +/* Frozen Screen Detector + * + * From: https://github.com/PokemonAutomation/ + * + * Detect if the entire screen is frozen. + */ + +#ifndef PokemonAutomation_CommonTools_FrozenImageDetector_H +#define PokemonAutomation_CommonTools_FrozenImageDetector_H + +#include "Common/Cpp/Color.h" +//#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ + + +class FrozenImageDetector : public VisualInferenceCallback{ +public: + FrozenImageDetector(std::chrono::milliseconds timeout, double rmsd_threshold); + FrozenImageDetector( + Color color, const ImageFloatBox& box, + std::chrono::milliseconds timeout, double rmsd_threshold + ); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const VideoSnapshot& frame) override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + Color m_color; + ImageFloatBox m_box; + std::chrono::milliseconds m_timeout; + double m_rmsd_threshold; + VideoSnapshot m_previous; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/VisualDetectors/ImageMatchDetector.cpp b/SerialPrograms/Source/CommonTools/VisualDetectors/ImageMatchDetector.cpp index a2819c9d7b..f9c9544e59 100644 --- a/SerialPrograms/Source/CommonTools/VisualDetectors/ImageMatchDetector.cpp +++ b/SerialPrograms/Source/CommonTools/VisualDetectors/ImageMatchDetector.cpp @@ -1,111 +1,111 @@ -/* Image Match Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "ImageMatchDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -ImageMatchDetector::ImageMatchDetector( - std::shared_ptr reference_image, const ImageFloatBox& box, - double max_rmsd, bool scale_brightness, - Color color -) - : m_reference_image(std::move(reference_image)) - , m_reference_image_cropped(extract_box_reference(*m_reference_image, box)) - , m_average_brightness(image_stats(m_reference_image_cropped).average) - , m_max_rmsd(max_rmsd) - , m_scale_brightness(scale_brightness) - , m_color(color) - , m_box(box) -{} - -double ImageMatchDetector::rmsd(const ImageViewRGB32& frame) const{ - if (!frame){ - return 1000; - } - ImageViewRGB32 image = extract_box_reference(frame, m_box); - ImageRGB32 scaled = image.scale_to(m_reference_image_cropped.width(), m_reference_image_cropped.height()); - -#if 0 - if (image.width() != (size_t)scaled.width() || image.height() != (size_t)scaled.height()){ - cout << image.width() << " x " << image.height() << " - " << scaled.width() << " x " << scaled.height() << endl; - dump_image(global_logger_tagged(), ProgramInfo(), "ImageMatchDetector-rmsd", frame); - } -#endif - - if (m_scale_brightness){ - FloatPixel image_brightness = ImageMatch::pixel_average(scaled, m_reference_image_cropped); - FloatPixel scale = m_average_brightness / image_brightness; - if (std::isnan(scale.r)) scale.r = 1.0; - if (std::isnan(scale.g)) scale.g = 1.0; - if (std::isnan(scale.b)) scale.b = 1.0; - scale.bound(0.8, 1.2); - ImageMatch::scale_brightness(scaled, scale); - } - -// cout << "asdf" << endl; - double ret = ImageMatch::pixel_RMSD(m_reference_image_cropped, scaled); -// cout << "rmsd = " << ret << endl; - return ret; -} - -void ImageMatchDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} -bool ImageMatchDetector::detect(const ImageViewRGB32& screen){ - return rmsd(screen) <= m_max_rmsd; -} - - - -ImageMatchWatcher::ImageMatchWatcher( - std::shared_ptr reference_image, const ImageFloatBox& box, - double max_rmsd, bool scale_brightness, - std::chrono::milliseconds hold_duration, - Color color -) - : ImageMatchDetector(std::move(reference_image), box, max_rmsd, scale_brightness, color) - , VisualInferenceCallback("ImageMatchWatcher") - , m_hold_duration(hold_duration) - , m_last_match(false) - , m_start_of_match(WallClock::min()) -{} - -void ImageMatchWatcher::make_overlays(VideoOverlaySet& items) const{ - ImageMatchDetector::make_overlays(items); -} -bool ImageMatchWatcher::process_frame(const ImageViewRGB32& frame, WallClock){ - if (!detect(frame)){ - m_last_match = false; - return false; - } - auto now = current_time(); - if (!m_last_match){ - m_last_match = true; - m_start_of_match = now; - return false; - } - return now - m_start_of_match >= m_hold_duration; -} - - - - - - -} +/* Image Match Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "ImageMatchDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +ImageMatchDetector::ImageMatchDetector( + std::shared_ptr reference_image, const ImageFloatBox& box, + double max_rmsd, bool scale_brightness, + Color color +) + : m_reference_image(std::move(reference_image)) + , m_reference_image_cropped(extract_box_reference(*m_reference_image, box)) + , m_average_brightness(image_stats(m_reference_image_cropped).average) + , m_max_rmsd(max_rmsd) + , m_scale_brightness(scale_brightness) + , m_color(color) + , m_box(box) +{} + +double ImageMatchDetector::rmsd(const ImageViewRGB32& frame) const{ + if (!frame){ + return 1000; + } + ImageViewRGB32 image = extract_box_reference(frame, m_box); + ImageRGB32 scaled = image.scale_to(m_reference_image_cropped.width(), m_reference_image_cropped.height()); + +#if 0 + if (image.width() != (size_t)scaled.width() || image.height() != (size_t)scaled.height()){ + cout << image.width() << " x " << image.height() << " - " << scaled.width() << " x " << scaled.height() << endl; + dump_image(global_logger_tagged(), ProgramInfo(), "ImageMatchDetector-rmsd", frame); + } +#endif + + if (m_scale_brightness){ + FloatPixel image_brightness = ImageMatch::pixel_average(scaled, m_reference_image_cropped); + FloatPixel scale = m_average_brightness / image_brightness; + if (std::isnan(scale.r)) scale.r = 1.0; + if (std::isnan(scale.g)) scale.g = 1.0; + if (std::isnan(scale.b)) scale.b = 1.0; + scale.bound(0.8, 1.2); + ImageMatch::scale_brightness(scaled, scale); + } + +// cout << "asdf" << endl; + double ret = ImageMatch::pixel_RMSD(m_reference_image_cropped, scaled); +// cout << "rmsd = " << ret << endl; + return ret; +} + +void ImageMatchDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} +bool ImageMatchDetector::detect(const ImageViewRGB32& screen){ + return rmsd(screen) <= m_max_rmsd; +} + + + +ImageMatchWatcher::ImageMatchWatcher( + std::shared_ptr reference_image, const ImageFloatBox& box, + double max_rmsd, bool scale_brightness, + std::chrono::milliseconds hold_duration, + Color color +) + : ImageMatchDetector(std::move(reference_image), box, max_rmsd, scale_brightness, color) + , VisualInferenceCallback("ImageMatchWatcher") + , m_hold_duration(hold_duration) + , m_last_match(false) + , m_start_of_match(WallClock::min()) +{} + +void ImageMatchWatcher::make_overlays(VideoOverlaySet& items) const{ + ImageMatchDetector::make_overlays(items); +} +bool ImageMatchWatcher::process_frame(const ImageViewRGB32& frame, WallClock){ + if (!detect(frame)){ + m_last_match = false; + return false; + } + auto now = current_time(); + if (!m_last_match){ + m_last_match = true; + m_start_of_match = now; + return false; + } + return now - m_start_of_match >= m_hold_duration; +} + + + + + + +} diff --git a/SerialPrograms/Source/CommonTools/VisualDetectors/ImageMatchDetector.h b/SerialPrograms/Source/CommonTools/VisualDetectors/ImageMatchDetector.h index 8eea66e608..099b582078 100644 --- a/SerialPrograms/Source/CommonTools/VisualDetectors/ImageMatchDetector.h +++ b/SerialPrograms/Source/CommonTools/VisualDetectors/ImageMatchDetector.h @@ -1,68 +1,68 @@ -/* Image Match Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_ImageMatchDetector_H -#define PokemonAutomation_CommonTools_ImageMatchDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/FloatPixel.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ - -class ImageMatchDetector : public StaticScreenDetector{ -public: - ImageMatchDetector( - std::shared_ptr reference_image, const ImageFloatBox& box, - double max_rmsd, bool scale_brightness = false, - Color color = COLOR_RED - ); - - double rmsd(const ImageViewRGB32& frame) const; - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - std::shared_ptr m_reference_image; - ImageViewRGB32 m_reference_image_cropped; - FloatPixel m_average_brightness; - - double m_max_rmsd; - bool m_scale_brightness; - - Color m_color; - ImageFloatBox m_box; -}; - - -class ImageMatchWatcher : public ImageMatchDetector, public VisualInferenceCallback{ -public: - ImageMatchWatcher( - std::shared_ptr reference_image, const ImageFloatBox& box, - double max_rmsd, bool scale_brightness = false, - std::chrono::milliseconds hold_duration = std::chrono::milliseconds(0), - Color color = COLOR_RED - ); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - std::chrono::milliseconds m_hold_duration; - - bool m_last_match; - WallClock m_start_of_match; -}; - - - - -} -#endif +/* Image Match Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_ImageMatchDetector_H +#define PokemonAutomation_CommonTools_ImageMatchDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/FloatPixel.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ + +class ImageMatchDetector : public StaticScreenDetector{ +public: + ImageMatchDetector( + std::shared_ptr reference_image, const ImageFloatBox& box, + double max_rmsd, bool scale_brightness = false, + Color color = COLOR_RED + ); + + double rmsd(const ImageViewRGB32& frame) const; + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + std::shared_ptr m_reference_image; + ImageViewRGB32 m_reference_image_cropped; + FloatPixel m_average_brightness; + + double m_max_rmsd; + bool m_scale_brightness; + + Color m_color; + ImageFloatBox m_box; +}; + + +class ImageMatchWatcher : public ImageMatchDetector, public VisualInferenceCallback{ +public: + ImageMatchWatcher( + std::shared_ptr reference_image, const ImageFloatBox& box, + double max_rmsd, bool scale_brightness = false, + std::chrono::milliseconds hold_duration = std::chrono::milliseconds(0), + Color color = COLOR_RED + ); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + std::chrono::milliseconds m_hold_duration; + + bool m_last_match; + WallClock m_start_of_match; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramSession.cpp b/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramSession.cpp index 129ddfe76f..d2fa7b5413 100644 --- a/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramSession.cpp +++ b/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramSession.cpp @@ -81,7 +81,7 @@ void ComputerProgramSession::internal_stop_program(){ } } void ComputerProgramSession::internal_run_program(){ - GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(); + GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(logger()); m_option.options().reset_state(); ProgramInfo program_info( diff --git a/SerialPrograms/Source/Controllers/Controller.h b/SerialPrograms/Source/Controllers/Controller.h index 937537177d..a154508a92 100644 --- a/SerialPrograms/Source/Controllers/Controller.h +++ b/SerialPrograms/Source/Controllers/Controller.h @@ -1,270 +1,270 @@ -/* Controller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_Controller_H -#define PokemonAutomation_Controllers_Controller_H - -#include "Common/Compiler.h" -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Time.h" -#include "Common/Cpp/CancellableScope.h" - -class QKeyEvent; - -namespace PokemonAutomation{ - -class RecursiveThrottler; -enum class ControllerType; -enum class ControllerPerformanceClass; -class ControllerFeatures; - - - -inline Milliseconds round_up_to_ticksize(Milliseconds ticksize, Milliseconds duration){ - if (ticksize == Milliseconds::zero()){ - return duration; - } - return (duration + ticksize - Milliseconds(1)) / ticksize * ticksize; -} - - - - -class AbstractController{ -public: - virtual ~AbstractController() = default; - - virtual Logger& logger() = 0; - virtual RecursiveThrottler& logging_throttler() = 0; - - -public: - // Static Information - - virtual ControllerType controller_type() const = 0; - virtual const ControllerFeatures& controller_features() const = 0; - virtual ControllerPerformanceClass performance_class() const = 0; - - // If the controller is polled at a fixed interval, this is that interval. - // Otherwise, returns zero. - virtual Milliseconds ticksize() const = 0; - - // The minimum amount of time between two state reports. This effectively - // limits how quickly you can change states. - // Controllers with non-zero ticksize will have (ticksize == cooldown). - virtual Milliseconds cooldown() const = 0; - - // Some controllers are imprecise. This returns the variation. - // Zero means "tick precise". - virtual Milliseconds timing_variation() const = 0; - - // If the controller can atomically press/release multiple buttons - // return true. This means that if the program presses A and B - // simultaneously, the console will never see an intermediate state where - // either A or B is pressed by itself before the other is pressed as well. - virtual bool atomic_multibutton() const = 0; - - -public: - // Status - - virtual bool is_ready() const = 0; - - -public: - // - // Cancellation - // - // These functions will return immediately and are thread-safe with - // everything. The intended use-case is for an inference thread to cancel - // a running sequence of commands on a program thread. - // - - // Cancel all commands. This returns the controller to the neutral button - // state and clears the command queue. - // This does not wait for the commands to finish cancelling. This is an - // asynchronous function that merely initiates the cancellation process. - virtual void cancel_all_commands() = 0; - - // Same as "cancel_all_commands()", but instead of cancelling the stream, - // it lets it keep running. Then on the next command issued after this - // cancel, it will atomically replace the stream without gapping. - // This lets you do stuff like suddenly change joystick movement in - // response to inference while simultaneously holding a button without - // ever releasing it during the transition. - virtual void replace_on_next_command() = 0; - - -public: - // - // Commands - // - // Commands are actions like button presses or joystick movements that are - // eventually sent to the console. - // - // All commands are prefixed with "issue_". - // Commands are not thread-safe with other commands. - // Commands are thread-safe with the cancellation functions above. - // - // Commands are asynchronous. When you call a command function on this, - // class it gets enqueued into a FIFO and immediately returns. It will only - // block if the FIFO is full. - // - // If a command is called with a cancelled "cancellable" parameter, it will - // throw an OperationCancelledException. - // If a cancellation happens while you are inside a command function, it - // will immediately stop and throw an OperationCancelledException. - // - - -public: - // - // Superscalar Commands (the "ssf" framework) - // - - // - // delay Time to wait before moving onto the next command. - // hold Time to hold the button/stick down for. - // cooldown After the button has been released, prevent it from being - // used again for this much time. - // - // For "normal" use, you should always set (delay == hold + cooldown). - // This is the easiest case to understand and is what the "pbf" interface - // exposes. - // - // If the button is busy (due to still being held down or is waiting out - // the cooldown), the command will wait until the button is ready. - // - // By setting (delay < hold), the command will "return" early and move onto - // the next command while the button is still being held down. - // - // If a command returns before it is finished (delay < hold + cooldown), - // it is considered a "hanging" command. - // - // This allows you to overlap buttons. But is confusing to use because it - // implies a non-trivial controller state with pending button presses that - // are scheduled to be released at a later time. - // - // Each button/stick has its own independent timeline/schedule. - // Users are responsible for understanding the controller state and - // managing the timeline/scheduling. - // - // It is important to remember that the "timeline" here is the timeline - // being fed to the Switch. Thus the timing parameters written in the C++ - // code here is what you will get on the console (or as close as possible). - // - // The actual calls to the methods in the class will return or block in an - // unspecified manner as they merely enqueue into a FIFO which is then - // "replayed" to the Switch in an implementation-dependent manner. - // - - // Wait for all unfinished commands to finish. This will also wait out - // hanging commands including their cooldown periods. - // This is not a true command function as it waits for the entire queue to - // empty out rather than entering itself into the queue. - // If a cancellation happens inside this function, it will immediately - // throw an OperationCancelledException. - virtual void wait_for_all(const Cancellable* cancellable) = 0; - - // Tell the scheduler to wait for all pending commands to finish - // (including cooldowns) before executing further instructions. - // This is used to prevent hanging commands from overlapping with new - // commands issued after this barrier. - virtual void issue_barrier(const Cancellable* cancellable) = 0; - - // Do nothing for this much time. - virtual void issue_nop(const Cancellable* cancellable, Milliseconds duration) = 0; - - -public: - // Keyboard Controls - - virtual void keyboard_release_all(){} - virtual void keyboard_press(const QKeyEvent& event){} - virtual void keyboard_release(const QKeyEvent& event){} -}; - - - - -// -// The context wrapper to support asynchronous cancel. -// -template -class ControllerContext final : public CancellableScope{ -public: - using ControllerType = Type; - -public: - ControllerContext(ControllerType& controller) - : m_controller(controller) - {} - ControllerContext(CancellableScope& parent, ControllerType& controller) - : m_controller(controller) - { - attach(parent); - } - virtual ~ControllerContext(){ - detach(); - } - - ControllerType* operator->(){ - m_lifetime_sanitizer.check_usage(); - return &m_controller; - } - - operator ControllerType&() const{ return m_controller; } - ControllerType& controller() const{ return m_controller; } - - void wait_for_all_requests() const{ - auto scope = m_lifetime_sanitizer.check_scope(); - m_controller.wait_for_all(this); - } - - // Stop all commands in this context now. - void cancel_now(){ - auto scope = m_lifetime_sanitizer.check_scope(); - CancellableScope::cancel(nullptr); - m_controller.cancel_all_commands(); - } - - // Stop the commands in this context, but do it lazily. - // - // 1. Stop new commands from being issued to the device from this context. - // 2. Tell the device that the next command that is issued should replace - // the command queue. - // - // This cancel is used when you need continuity from an ongoing - // sequence. - void cancel_lazy(){ - auto scope = m_lifetime_sanitizer.check_scope(); - CancellableScope::cancel(nullptr); - m_controller.replace_on_next_command(); - } - - virtual bool cancel(std::exception_ptr exception) noexcept override{ - auto scope = m_lifetime_sanitizer.check_scope(); - if (CancellableScope::cancel(std::move(exception))){ - return true; - } - try{ - m_controller.cancel_all_commands(); - }catch (...){} - return false; - } - - -private: - ControllerType& m_controller; - LifetimeSanitizer m_lifetime_sanitizer; -}; - - - - - -} -#endif +/* Controller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_Controller_H +#define PokemonAutomation_Controllers_Controller_H + +#include "Common/Compiler.h" +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Time.h" +#include "Common/Cpp/CancellableScope.h" + +class QKeyEvent; + +namespace PokemonAutomation{ + +class RecursiveThrottler; +enum class ControllerType; +enum class ControllerPerformanceClass; +class ControllerFeatures; + + + +inline Milliseconds round_up_to_ticksize(Milliseconds ticksize, Milliseconds duration){ + if (ticksize == Milliseconds::zero()){ + return duration; + } + return (duration + ticksize - Milliseconds(1)) / ticksize * ticksize; +} + + + + +class AbstractController{ +public: + virtual ~AbstractController() = default; + + virtual Logger& logger() = 0; + virtual RecursiveThrottler& logging_throttler() = 0; + + +public: + // Static Information + + virtual ControllerType controller_type() const = 0; + virtual const ControllerFeatures& controller_features() const = 0; + virtual ControllerPerformanceClass performance_class() const = 0; + + // If the controller is polled at a fixed interval, this is that interval. + // Otherwise, returns zero. + virtual Milliseconds ticksize() const = 0; + + // The minimum amount of time between two state reports. This effectively + // limits how quickly you can change states. + // Controllers with non-zero ticksize will have (ticksize == cooldown). + virtual Milliseconds cooldown() const = 0; + + // Some controllers are imprecise. This returns the variation. + // Zero means "tick precise". + virtual Milliseconds timing_variation() const = 0; + + // If the controller can atomically press/release multiple buttons + // return true. This means that if the program presses A and B + // simultaneously, the console will never see an intermediate state where + // either A or B is pressed by itself before the other is pressed as well. + virtual bool atomic_multibutton() const = 0; + + +public: + // Status + + virtual bool is_ready() const = 0; + + +public: + // + // Cancellation + // + // These functions will return immediately and are thread-safe with + // everything. The intended use-case is for an inference thread to cancel + // a running sequence of commands on a program thread. + // + + // Cancel all commands. This returns the controller to the neutral button + // state and clears the command queue. + // This does not wait for the commands to finish cancelling. This is an + // asynchronous function that merely initiates the cancellation process. + virtual void cancel_all_commands() = 0; + + // Same as "cancel_all_commands()", but instead of cancelling the stream, + // it lets it keep running. Then on the next command issued after this + // cancel, it will atomically replace the stream without gapping. + // This lets you do stuff like suddenly change joystick movement in + // response to inference while simultaneously holding a button without + // ever releasing it during the transition. + virtual void replace_on_next_command() = 0; + + +public: + // + // Commands + // + // Commands are actions like button presses or joystick movements that are + // eventually sent to the console. + // + // All commands are prefixed with "issue_". + // Commands are not thread-safe with other commands. + // Commands are thread-safe with the cancellation functions above. + // + // Commands are asynchronous. When you call a command function on this, + // class it gets enqueued into a FIFO and immediately returns. It will only + // block if the FIFO is full. + // + // If a command is called with a cancelled "cancellable" parameter, it will + // throw an OperationCancelledException. + // If a cancellation happens while you are inside a command function, it + // will immediately stop and throw an OperationCancelledException. + // + + +public: + // + // Superscalar Commands (the "ssf" framework) + // + + // + // delay Time to wait before moving onto the next command. + // hold Time to hold the button/stick down for. + // cooldown After the button has been released, prevent it from being + // used again for this much time. + // + // For "normal" use, you should always set (delay == hold + cooldown). + // This is the easiest case to understand and is what the "pbf" interface + // exposes. + // + // If the button is busy (due to still being held down or is waiting out + // the cooldown), the command will wait until the button is ready. + // + // By setting (delay < hold), the command will "return" early and move onto + // the next command while the button is still being held down. + // + // If a command returns before it is finished (delay < hold + cooldown), + // it is considered a "hanging" command. + // + // This allows you to overlap buttons. But is confusing to use because it + // implies a non-trivial controller state with pending button presses that + // are scheduled to be released at a later time. + // + // Each button/stick has its own independent timeline/schedule. + // Users are responsible for understanding the controller state and + // managing the timeline/scheduling. + // + // It is important to remember that the "timeline" here is the timeline + // being fed to the Switch. Thus the timing parameters written in the C++ + // code here is what you will get on the console (or as close as possible). + // + // The actual calls to the methods in the class will return or block in an + // unspecified manner as they merely enqueue into a FIFO which is then + // "replayed" to the Switch in an implementation-dependent manner. + // + + // Wait for all unfinished commands to finish. This will also wait out + // hanging commands including their cooldown periods. + // This is not a true command function as it waits for the entire queue to + // empty out rather than entering itself into the queue. + // If a cancellation happens inside this function, it will immediately + // throw an OperationCancelledException. + virtual void wait_for_all(const Cancellable* cancellable) = 0; + + // Tell the scheduler to wait for all pending commands to finish + // (including cooldowns) before executing further instructions. + // This is used to prevent hanging commands from overlapping with new + // commands issued after this barrier. + virtual void issue_barrier(const Cancellable* cancellable) = 0; + + // Do nothing for this much time. + virtual void issue_nop(const Cancellable* cancellable, Milliseconds duration) = 0; + + +public: + // Keyboard Controls + + virtual void keyboard_release_all(){} + virtual void keyboard_press(const QKeyEvent& event){} + virtual void keyboard_release(const QKeyEvent& event){} +}; + + + + +// +// The context wrapper to support asynchronous cancel. +// +template +class ControllerContext final : public CancellableScope{ +public: + using ControllerType = Type; + +public: + ControllerContext(ControllerType& controller) + : m_controller(controller) + {} + ControllerContext(CancellableScope& parent, ControllerType& controller) + : m_controller(controller) + { + attach(parent); + } + virtual ~ControllerContext(){ + detach(); + } + + ControllerType* operator->(){ + m_lifetime_sanitizer.check_usage(); + return &m_controller; + } + + operator ControllerType&() const{ return m_controller; } + ControllerType& controller() const{ return m_controller; } + + void wait_for_all_requests() const{ + auto scope = m_lifetime_sanitizer.check_scope(); + m_controller.wait_for_all(this); + } + + // Stop all commands in this context now. + void cancel_now(){ + auto scope = m_lifetime_sanitizer.check_scope(); + CancellableScope::cancel(nullptr); + m_controller.cancel_all_commands(); + } + + // Stop the commands in this context, but do it lazily. + // + // 1. Stop new commands from being issued to the device from this context. + // 2. Tell the device that the next command that is issued should replace + // the command queue. + // + // This cancel is used when you need continuity from an ongoing + // sequence. + void cancel_lazy(){ + auto scope = m_lifetime_sanitizer.check_scope(); + CancellableScope::cancel(nullptr); + m_controller.replace_on_next_command(); + } + + virtual bool cancel(std::exception_ptr exception) noexcept override{ + auto scope = m_lifetime_sanitizer.check_scope(); + if (CancellableScope::cancel(std::move(exception))){ + return true; + } + try{ + m_controller.cancel_all_commands(); + }catch (...){} + return false; + } + + +private: + ControllerType& m_controller; + LifetimeSanitizer m_lifetime_sanitizer; +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/ControllerCapability.cpp b/SerialPrograms/Source/Controllers/ControllerCapability.cpp index 5eba57e452..11ebc61b03 100644 --- a/SerialPrograms/Source/Controllers/ControllerCapability.cpp +++ b/SerialPrograms/Source/Controllers/ControllerCapability.cpp @@ -1,28 +1,28 @@ -/* Controller Capabilities - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "ControllerTypeStrings.h" -#include "ControllerCapability.h" - -namespace PokemonAutomation{ - - - -std::string ControllerFeatures::contains_all(const ControllerFeatures& features) const{ - auto scope_check = m_sanitizer.check_scope(); - for (ControllerFeature feature : features.m_features){ - if (!contains(feature)){ - return CONTROLLER_FEATURE_STRINGS.get_string(feature); - } - } - return ""; -} - - - - - -} +/* Controller Capabilities + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "ControllerTypeStrings.h" +#include "ControllerCapability.h" + +namespace PokemonAutomation{ + + + +std::string ControllerFeatures::contains_all(const ControllerFeatures& features) const{ + auto scope_check = m_sanitizer.check_scope(); + for (ControllerFeature feature : features.m_features){ + if (!contains(feature)){ + return CONTROLLER_FEATURE_STRINGS.get_string(feature); + } + } + return ""; +} + + + + + +} diff --git a/SerialPrograms/Source/Controllers/ControllerCapability.h b/SerialPrograms/Source/Controllers/ControllerCapability.h index 689ec2866c..105ee73822 100644 --- a/SerialPrograms/Source/Controllers/ControllerCapability.h +++ b/SerialPrograms/Source/Controllers/ControllerCapability.h @@ -1,57 +1,57 @@ -/* Controller Capabilities - * - * From: https://github.com/PokemonAutomation/ - * - * Represents optional features that each controller - * interface may have. - * - * For example, PABotBase has 3 different levels: - * - Not PABotBase (protocol only, no commands) - * - PABotBase-12KB (basic commands only) - * - PABotBase-31KB (basic commands + advanced RPC) - * - * This class allows programs to declare required features so that the - * controller interface can error if it lacks them. - * - */ - -#ifndef PokemonAutomation_Controllers_ControllerCapabilities_H -#define PokemonAutomation_Controllers_ControllerCapabilities_H - -#include -#include -#include -#include "Common/Cpp/LifetimeSanitizer.h" -#include "ControllerTypes.h" - -namespace PokemonAutomation{ - - -class ControllerFeatures{ -public: - ControllerFeatures() - : m_sanitizer("ControllerFeatures") - {} - ControllerFeatures(std::initializer_list list) - : m_features(std::move(list)) - , m_sanitizer("ControllerFeatures") - {} - - bool contains(ControllerFeature feature) const{ - return m_features.contains(feature); - } - - // Returns empty string if this class contains everything in "features". - // Otherwise, returns the name of one of the missing features. - std::string contains_all(const ControllerFeatures& features) const; - -private: - std::set m_features; - - LifetimeSanitizer m_sanitizer; -}; - - - -} -#endif +/* Controller Capabilities + * + * From: https://github.com/PokemonAutomation/ + * + * Represents optional features that each controller + * interface may have. + * + * For example, PABotBase has 3 different levels: + * - Not PABotBase (protocol only, no commands) + * - PABotBase-12KB (basic commands only) + * - PABotBase-31KB (basic commands + advanced RPC) + * + * This class allows programs to declare required features so that the + * controller interface can error if it lacks them. + * + */ + +#ifndef PokemonAutomation_Controllers_ControllerCapabilities_H +#define PokemonAutomation_Controllers_ControllerCapabilities_H + +#include +#include +#include +#include "Common/Cpp/LifetimeSanitizer.h" +#include "ControllerTypes.h" + +namespace PokemonAutomation{ + + +class ControllerFeatures{ +public: + ControllerFeatures() + : m_sanitizer("ControllerFeatures") + {} + ControllerFeatures(std::initializer_list list) + : m_features(std::move(list)) + , m_sanitizer("ControllerFeatures") + {} + + bool contains(ControllerFeature feature) const{ + return m_features.contains(feature); + } + + // Returns empty string if this class contains everything in "features". + // Otherwise, returns the name of one of the missing features. + std::string contains_all(const ControllerFeatures& features) const; + +private: + std::set m_features; + + LifetimeSanitizer m_sanitizer; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/ControllerConnection.cpp b/SerialPrograms/Source/Controllers/ControllerConnection.cpp index f0ff7eedeb..aca0b96f72 100644 --- a/SerialPrograms/Source/Controllers/ControllerConnection.cpp +++ b/SerialPrograms/Source/Controllers/ControllerConnection.cpp @@ -1,77 +1,77 @@ -/* Controller Connection - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" -#include "ControllerConnection.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -void ControllerConnection::add_status_listener(StatusListener& listener){ - m_status_listeners.add(listener); - if (m_ready.load(std::memory_order_acquire)){ - listener.post_connection_ready(*this, controller_mode_status()); - } -} -void ControllerConnection::remove_status_listener(StatusListener& listener){ - m_status_listeners.remove(listener); -} - -std::string ControllerConnection::status_text() const{ - SpinLockGuard lg(m_status_text_lock); - std::string str = m_status_line0; - if (!str.empty() && !m_status_line1.empty()){ - str += "
"; - str += m_status_line1; - } - return str; -} - - - -void ControllerConnection::set_status_line0(const std::string& text, Color color){ - { - WriteSpinLock lg(m_status_text_lock); - m_status_line0 = html_color_text(text, color); - } - signal_status_text_changed(status_text()); -} -void ControllerConnection::set_status_line1(const std::string& text, Color color){ - { - WriteSpinLock lg(m_status_text_lock); - m_status_line1 = html_color_text(text, color); - } - signal_status_text_changed(status_text()); -} -void ControllerConnection::declare_ready(const ControllerModeStatus& mode_status){ - m_ready.store(true, std::memory_order_release); - signal_post_ready(mode_status); -} - - -//void ControllerConnection::signal_pre_not_ready(){ -// m_status_listeners.run_method_unique(&StatusListener::pre_connection_not_ready, *this); -//} -void ControllerConnection::signal_post_ready(const ControllerModeStatus& mode_status){ - m_status_listeners.run_method_unique(&StatusListener::post_connection_ready, *this, mode_status); -} -void ControllerConnection::signal_status_text_changed(const std::string& text){ -// cout << "m_status_listeners.size() = " << m_status_listeners.count_unique() << endl; - m_status_listeners.run_method_unique(&StatusListener::status_text_changed, *this, text); -} -void ControllerConnection::signal_error(const std::string& text){ - m_status_listeners.run_method_unique(&StatusListener::on_error, *this, text); -} - - - - -} +/* Controller Connection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" +#include "ControllerConnection.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +void ControllerConnection::add_status_listener(StatusListener& listener){ + m_status_listeners.add(listener); + if (m_ready.load(std::memory_order_acquire)){ + listener.post_connection_ready(*this, controller_mode_status()); + } +} +void ControllerConnection::remove_status_listener(StatusListener& listener){ + m_status_listeners.remove(listener); +} + +std::string ControllerConnection::status_text() const{ + SpinLockGuard lg(m_status_text_lock); + std::string str = m_status_line0; + if (!str.empty() && !m_status_line1.empty()){ + str += "
"; + str += m_status_line1; + } + return str; +} + + + +void ControllerConnection::set_status_line0(const std::string& text, Color color){ + { + WriteSpinLock lg(m_status_text_lock); + m_status_line0 = html_color_text(text, color); + } + signal_status_text_changed(status_text()); +} +void ControllerConnection::set_status_line1(const std::string& text, Color color){ + { + WriteSpinLock lg(m_status_text_lock); + m_status_line1 = html_color_text(text, color); + } + signal_status_text_changed(status_text()); +} +void ControllerConnection::declare_ready(const ControllerModeStatus& mode_status){ + m_ready.store(true, std::memory_order_release); + signal_post_ready(mode_status); +} + + +//void ControllerConnection::signal_pre_not_ready(){ +// m_status_listeners.run_method_unique(&StatusListener::pre_connection_not_ready, *this); +//} +void ControllerConnection::signal_post_ready(const ControllerModeStatus& mode_status){ + m_status_listeners.run_method_unique(&StatusListener::post_connection_ready, *this, mode_status); +} +void ControllerConnection::signal_status_text_changed(const std::string& text){ +// cout << "m_status_listeners.size() = " << m_status_listeners.count_unique() << endl; + m_status_listeners.run_method_unique(&StatusListener::status_text_changed, *this, text); +} +void ControllerConnection::signal_error(const std::string& text){ + m_status_listeners.run_method_unique(&StatusListener::on_error, *this, text); +} + + + + +} diff --git a/SerialPrograms/Source/Controllers/ControllerConnection.h b/SerialPrograms/Source/Controllers/ControllerConnection.h index 252fb97cc5..052929aa3c 100644 --- a/SerialPrograms/Source/Controllers/ControllerConnection.h +++ b/SerialPrograms/Source/Controllers/ControllerConnection.h @@ -1,87 +1,87 @@ -/* Controller Connection - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_ControllerConnection_H -#define PokemonAutomation_Controllers_ControllerConnection_H - -#include "Common/Cpp/ListenerSet.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "ControllerDescriptor.h" - -namespace PokemonAutomation{ - - - -struct ControllerModeStatus{ - ControllerType current_controller = ControllerType::None; - std::map supported_controllers; -}; - - - -class ControllerConnection{ -public: - struct StatusListener{ -// virtual void pre_connection_not_ready(ControllerConnection& connection){} - virtual void post_connection_ready( - ControllerConnection& connection, - const ControllerModeStatus& mode_status - ){} - virtual void status_text_changed( - ControllerConnection& connection, const std::string& text - ){} - virtual void on_error( - ControllerConnection& connection, const std::string& text - ){}; - }; - - void add_status_listener(StatusListener& listener); - void remove_status_listener(StatusListener& listener); - - -public: - virtual ~ControllerConnection() = default; - - bool is_ready() const{ return m_ready.load(std::memory_order_acquire); } - std::string status_text() const; - - // Returns the current controller type and the list of supported controllers. - // The current controller may be "None" if there is only one supported - // controller since it is implied to be that. - virtual ControllerModeStatus controller_mode_status() const = 0; - - -public: - void set_status_line0(const std::string& text, Color color = Color()); - void set_status_line1(const std::string& text, Color color = Color()); - - -protected: - void declare_ready(const ControllerModeStatus& mode_status); - - -private: -// void signal_pre_not_ready(); - void signal_post_ready(const ControllerModeStatus& mode_status); - void signal_status_text_changed(const std::string& text); - void signal_error(const std::string& text); - - -protected: - std::atomic m_ready; - -private: - mutable SpinLock m_status_text_lock; - std::string m_status_line0; - std::string m_status_line1; - ListenerSet m_status_listeners; -}; - - - - -} -#endif +/* Controller Connection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_ControllerConnection_H +#define PokemonAutomation_Controllers_ControllerConnection_H + +#include "Common/Cpp/ListenerSet.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "ControllerDescriptor.h" + +namespace PokemonAutomation{ + + + +struct ControllerModeStatus{ + ControllerType current_controller = ControllerType::None; + std::map supported_controllers; +}; + + + +class ControllerConnection{ +public: + struct StatusListener{ +// virtual void pre_connection_not_ready(ControllerConnection& connection){} + virtual void post_connection_ready( + ControllerConnection& connection, + const ControllerModeStatus& mode_status + ){} + virtual void status_text_changed( + ControllerConnection& connection, const std::string& text + ){} + virtual void on_error( + ControllerConnection& connection, const std::string& text + ){}; + }; + + void add_status_listener(StatusListener& listener); + void remove_status_listener(StatusListener& listener); + + +public: + virtual ~ControllerConnection() = default; + + bool is_ready() const{ return m_ready.load(std::memory_order_acquire); } + std::string status_text() const; + + // Returns the current controller type and the list of supported controllers. + // The current controller may be "None" if there is only one supported + // controller since it is implied to be that. + virtual ControllerModeStatus controller_mode_status() const = 0; + + +public: + void set_status_line0(const std::string& text, Color color = Color()); + void set_status_line1(const std::string& text, Color color = Color()); + + +protected: + void declare_ready(const ControllerModeStatus& mode_status); + + +private: +// void signal_pre_not_ready(); + void signal_post_ready(const ControllerModeStatus& mode_status); + void signal_status_text_changed(const std::string& text); + void signal_error(const std::string& text); + + +protected: + std::atomic m_ready; + +private: + mutable SpinLock m_status_text_lock; + std::string m_status_line0; + std::string m_status_line1; + ListenerSet m_status_listeners; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/ControllerDescriptor.cpp b/SerialPrograms/Source/Controllers/ControllerDescriptor.cpp index 2f1ff68378..e06b431e2c 100644 --- a/SerialPrograms/Source/Controllers/ControllerDescriptor.cpp +++ b/SerialPrograms/Source/Controllers/ControllerDescriptor.cpp @@ -1,123 +1,123 @@ -/* Controller Interface - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "ControllerTypeStrings.h" -#include "ControllerDescriptor.h" -#include "NullController.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -// -// Here we store a map of all controller types in the program. -// -std::map> ALL_CONTROLLER_INTERFACES; - - -void InterfaceType::register_factory( - ControllerInterface controller_interface, - std::unique_ptr factory -){ - auto ret = ALL_CONTROLLER_INTERFACES.emplace(controller_interface, std::move(factory)); - if (!ret.second){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Duplicate Factory Name: " + CONTROLLER_INTERFACE_STRINGS.get_string(controller_interface) - ); - } -} - - - - -ControllerOption::ControllerOption() - : m_descriptor(new NullControllerDescriptor()) -{} - - -void ControllerOption::set_descriptor(std::shared_ptr descriptor){ - m_descriptor_cache[descriptor->interface_type] = descriptor; - m_descriptor = std::move(descriptor); -} - -std::shared_ptr ControllerOption::get_descriptor_from_cache(ControllerInterface interface_type) const{ - auto iter = m_descriptor_cache.find(interface_type); - if (iter == m_descriptor_cache.end()){ - return nullptr; - } - return iter->second; -} - - - -void ControllerOption::load_json(const JsonValue& json){ - std::shared_ptr descriptor; - do{ - if (json.is_null()){ - break; - } - - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - break; - } - const std::string* type = obj->get_string("Interface"); - if (type == nullptr){ - break; - } - - for (const auto& item : ALL_CONTROLLER_INTERFACES){ - const JsonValue* params = obj->get_value(CONTROLLER_INTERFACE_STRINGS.get_string(item.first)); - if (params == nullptr){ - continue; - } - m_descriptor_cache[item.first] = item.second->make(*params); - } - - auto iter = m_descriptor_cache.find(CONTROLLER_INTERFACE_STRINGS.get_enum(*type, ControllerInterface::None)); - if (iter == m_descriptor_cache.end()){ - break; - } - - descriptor = iter->second; - }while (false); - - if (descriptor == nullptr){ - descriptor.reset(new NullControllerDescriptor()); - } - - m_descriptor = std::move(descriptor); -} -JsonValue ControllerOption::to_json() const{ - if (!m_descriptor){ - return JsonValue(); - } - JsonObject obj; - obj["Interface"] = CONTROLLER_INTERFACE_STRINGS.get_string(m_descriptor->interface_type); - - for (const auto& item : m_descriptor_cache){ - obj[CONTROLLER_INTERFACE_STRINGS.get_string(item.first)] = item.second->to_json(); - } - - return obj; -} - - - - - - - - - -} +/* Controller Interface + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "ControllerTypeStrings.h" +#include "ControllerDescriptor.h" +#include "NullController.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +// +// Here we store a map of all controller types in the program. +// +std::map> ALL_CONTROLLER_INTERFACES; + + +void InterfaceType::register_factory( + ControllerInterface controller_interface, + std::unique_ptr factory +){ + auto ret = ALL_CONTROLLER_INTERFACES.emplace(controller_interface, std::move(factory)); + if (!ret.second){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Duplicate Factory Name: " + CONTROLLER_INTERFACE_STRINGS.get_string(controller_interface) + ); + } +} + + + + +ControllerOption::ControllerOption() + : m_descriptor(new NullControllerDescriptor()) +{} + + +void ControllerOption::set_descriptor(std::shared_ptr descriptor){ + m_descriptor_cache[descriptor->interface_type] = descriptor; + m_descriptor = std::move(descriptor); +} + +std::shared_ptr ControllerOption::get_descriptor_from_cache(ControllerInterface interface_type) const{ + auto iter = m_descriptor_cache.find(interface_type); + if (iter == m_descriptor_cache.end()){ + return nullptr; + } + return iter->second; +} + + + +void ControllerOption::load_json(const JsonValue& json){ + std::shared_ptr descriptor; + do{ + if (json.is_null()){ + break; + } + + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + break; + } + const std::string* type = obj->get_string("Interface"); + if (type == nullptr){ + break; + } + + for (const auto& item : ALL_CONTROLLER_INTERFACES){ + const JsonValue* params = obj->get_value(CONTROLLER_INTERFACE_STRINGS.get_string(item.first)); + if (params == nullptr){ + continue; + } + m_descriptor_cache[item.first] = item.second->make(*params); + } + + auto iter = m_descriptor_cache.find(CONTROLLER_INTERFACE_STRINGS.get_enum(*type, ControllerInterface::None)); + if (iter == m_descriptor_cache.end()){ + break; + } + + descriptor = iter->second; + }while (false); + + if (descriptor == nullptr){ + descriptor.reset(new NullControllerDescriptor()); + } + + m_descriptor = std::move(descriptor); +} +JsonValue ControllerOption::to_json() const{ + if (!m_descriptor){ + return JsonValue(); + } + JsonObject obj; + obj["Interface"] = CONTROLLER_INTERFACE_STRINGS.get_string(m_descriptor->interface_type); + + for (const auto& item : m_descriptor_cache){ + obj[CONTROLLER_INTERFACE_STRINGS.get_string(item.first)] = item.second->to_json(); + } + + return obj; +} + + + + + + + + + +} diff --git a/SerialPrograms/Source/Controllers/ControllerDescriptor.h b/SerialPrograms/Source/Controllers/ControllerDescriptor.h index 8fcbb64ed5..497572e7b5 100644 --- a/SerialPrograms/Source/Controllers/ControllerDescriptor.h +++ b/SerialPrograms/Source/Controllers/ControllerDescriptor.h @@ -1,162 +1,162 @@ -/* Controller Interface - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_ControllerDescriptor_H -#define PokemonAutomation_Controllers_ControllerDescriptor_H - -#include -#include -#include -#include -#include "Common/Cpp/AbstractLogger.h" -//#include "Common/Cpp/Json/JsonObject.h" -#include "ControllerCapability.h" -#include "Controller.h" - -class QWidget; - -namespace PokemonAutomation{ - -class JsonValue; -class InterfaceType; -class ControllerDescriptor; -class ControllerConnection; -class ControllerSelectorWidget; - - -// -// Represents an entire controller interface. -// -// For example: -// - Serial PABotBase -// - Direct USB to X (hypothetical) -// - Emulator IPC (hypothetical) -// -// One instance of this class exists for each interface. -// -class InterfaceType{ -public: - virtual ~InterfaceType() = default; - - // Construct a descriptor from a JSON config. (reloading saved controller settings) - virtual std::unique_ptr make(const JsonValue& json) const = 0; - -protected: - static void register_factory( - ControllerInterface controller_interface, - std::unique_ptr factory - ); -}; - - -// -// Subclass helper for ControllerType. -// -template -class InterfaceType_t : public InterfaceType{ -public: - virtual std::unique_ptr make(const JsonValue& json) const override{ - std::unique_ptr ptr(new DescriptorType()); - ptr->load_json(json); - return ptr; - } - -private: - static int register_class(){ - InterfaceType::register_factory( - DescriptorType::INTERFACE_NAME, - std::make_unique>() - ); - return 0; - } - static int initializer; -}; -template -int InterfaceType_t::initializer = register_class(); - - - - -// -// Represents a user-selectable controller. When the user clicks on the -// "Controller" dropdown, every item in that list corresponds to an instance -// of this class. -// -class ControllerDescriptor{ -public: - const ControllerInterface interface_type; - - ControllerDescriptor(ControllerInterface p_interface_type) - : interface_type(p_interface_type) - {} - virtual ~ControllerDescriptor() = default; - -public: - virtual bool operator==(const ControllerDescriptor& x) const = 0; - virtual std::string display_name() const = 0; - -public: - virtual void load_json(const JsonValue& json) = 0; - virtual JsonValue to_json() const = 0; - -public: - virtual std::unique_ptr open_connection( - Logger& logger, - std::optional change_controller - ) const = 0; - virtual std::unique_ptr make_controller( - Logger& logger, - ControllerConnection& connection, - ControllerType controller_type - ) const = 0; - - virtual QWidget* make_selector_QtWidget(ControllerSelectorWidget& parent) const = 0; -}; - - - - - - - - -// -// A configurable option type for the descriptor. -// -class ControllerOption{ -public: - ControllerOption(); - - std::shared_ptr descriptor() const{ - return m_descriptor; - } - void set_descriptor(std::shared_ptr descriptor); - - // Remember the last used descriptor for each interface type. That way when - // the user switches back-and-forth between two interfaces, it will reload - // the previous one. - std::shared_ptr get_descriptor_from_cache(ControllerInterface interface_type) const; - - -public: - void load_json(const JsonValue& json); - JsonValue to_json() const; - - -private: - std::shared_ptr m_descriptor; - std::map> m_descriptor_cache; -}; - - - - - - - - -} -#endif +/* Controller Interface + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_ControllerDescriptor_H +#define PokemonAutomation_Controllers_ControllerDescriptor_H + +#include +#include +#include +#include +#include "Common/Cpp/AbstractLogger.h" +//#include "Common/Cpp/Json/JsonObject.h" +#include "ControllerCapability.h" +#include "Controller.h" + +class QWidget; + +namespace PokemonAutomation{ + +class JsonValue; +class InterfaceType; +class ControllerDescriptor; +class ControllerConnection; +class ControllerSelectorWidget; + + +// +// Represents an entire controller interface. +// +// For example: +// - Serial PABotBase +// - Direct USB to X (hypothetical) +// - Emulator IPC (hypothetical) +// +// One instance of this class exists for each interface. +// +class InterfaceType{ +public: + virtual ~InterfaceType() = default; + + // Construct a descriptor from a JSON config. (reloading saved controller settings) + virtual std::unique_ptr make(const JsonValue& json) const = 0; + +protected: + static void register_factory( + ControllerInterface controller_interface, + std::unique_ptr factory + ); +}; + + +// +// Subclass helper for ControllerType. +// +template +class InterfaceType_t : public InterfaceType{ +public: + virtual std::unique_ptr make(const JsonValue& json) const override{ + std::unique_ptr ptr(new DescriptorType()); + ptr->load_json(json); + return ptr; + } + +private: + static int register_class(){ + InterfaceType::register_factory( + DescriptorType::INTERFACE_NAME, + std::make_unique>() + ); + return 0; + } + static int initializer; +}; +template +int InterfaceType_t::initializer = register_class(); + + + + +// +// Represents a user-selectable controller. When the user clicks on the +// "Controller" dropdown, every item in that list corresponds to an instance +// of this class. +// +class ControllerDescriptor{ +public: + const ControllerInterface interface_type; + + ControllerDescriptor(ControllerInterface p_interface_type) + : interface_type(p_interface_type) + {} + virtual ~ControllerDescriptor() = default; + +public: + virtual bool operator==(const ControllerDescriptor& x) const = 0; + virtual std::string display_name() const = 0; + +public: + virtual void load_json(const JsonValue& json) = 0; + virtual JsonValue to_json() const = 0; + +public: + virtual std::unique_ptr open_connection( + Logger& logger, + std::optional change_controller + ) const = 0; + virtual std::unique_ptr make_controller( + Logger& logger, + ControllerConnection& connection, + ControllerType controller_type + ) const = 0; + + virtual QWidget* make_selector_QtWidget(ControllerSelectorWidget& parent) const = 0; +}; + + + + + + + + +// +// A configurable option type for the descriptor. +// +class ControllerOption{ +public: + ControllerOption(); + + std::shared_ptr descriptor() const{ + return m_descriptor; + } + void set_descriptor(std::shared_ptr descriptor); + + // Remember the last used descriptor for each interface type. That way when + // the user switches back-and-forth between two interfaces, it will reload + // the previous one. + std::shared_ptr get_descriptor_from_cache(ControllerInterface interface_type) const; + + +public: + void load_json(const JsonValue& json); + JsonValue to_json() const; + + +private: + std::shared_ptr m_descriptor; + std::map> m_descriptor_cache; +}; + + + + + + + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/ControllerSelectorWidget.cpp b/SerialPrograms/Source/Controllers/ControllerSelectorWidget.cpp index 54dc01365a..6800886a75 100644 --- a/SerialPrograms/Source/Controllers/ControllerSelectorWidget.cpp +++ b/SerialPrograms/Source/Controllers/ControllerSelectorWidget.cpp @@ -1,216 +1,216 @@ -/* Controller Selector Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Qt/NoWheelComboBox.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "Controllers/ControllerTypeStrings.h" -#include "ControllerSelectorWidget.h" - -#include "SerialPABotBase/SerialPABotBase_SelectorWidget.h" -#include "NintendoSwitch/Controllers/SysbotBase/SysbotBase_SelectorWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - - -ControllerSelectorWidget::~ControllerSelectorWidget(){ - m_session.remove_listener(*this); -} -ControllerSelectorWidget::ControllerSelectorWidget(QWidget& parent, ControllerSession& session) - : QWidget(&parent) - , m_session(session) -{ - QHBoxLayout* serial_row = new QHBoxLayout(this); - serial_row->setContentsMargins(0, 0, 0, 0); - - serial_row->addWidget(new QLabel("Controller:", this), 1); - serial_row->addSpacing(5); - - m_dropdowns = new QHBoxLayout(); - serial_row->addLayout(m_dropdowns, 5); - serial_row->addSpacing(5); - - interface_dropdown = new NoWheelComboBox(this); - m_dropdowns->addWidget(interface_dropdown, 2); - - interface_dropdown->addItem(QString::fromStdString(CONTROLLER_INTERFACE_STRINGS.get_string(ControllerInterface::SerialPABotBase))); - interface_dropdown->addItem(QString::fromStdString(CONTROLLER_INTERFACE_STRINGS.get_string(ControllerInterface::TcpSysbotBase))); -// interface_dropdown->addItem(QString::fromStdString(CONTROLLER_INTERFACE_STRINGS.get_string(ControllerInterface::UsbSysbotBase))); - -// interface_dropdown->setHidden(true); - - auto current = session.descriptor(); - if (current == nullptr || current->interface_type == ControllerInterface::None){ - current.reset(new SerialPABotBase::SerialPABotBase_Descriptor()); - session.set_device(std::move(current)); - } - interface_dropdown->setCurrentIndex((int)current->interface_type - 1); - m_selector = current->make_selector_QtWidget(*this); - m_dropdowns->addWidget(m_selector); - - - m_dropdowns->addSpacing(5); - m_controllers_dropdown = new NoWheelComboBox(this); - m_dropdowns->addWidget(m_controllers_dropdown, 3); - refresh_controllers(session.controller_type(), session.available_controllers()); - - m_status_text = new QLabel(this); - serial_row->addWidget(m_status_text, 3); - serial_row->addSpacing(5); - - m_status_text->setText(QString::fromStdString(session.status_text())); - - m_reset_button = new QPushButton("Reset Ctrl.", this); - serial_row->addWidget(m_reset_button, 1); - - bool options_locked = session.options_locked(); - if (m_selector){ - m_selector->setEnabled(!options_locked); - } - m_reset_button->setEnabled(!options_locked); - - connect( - interface_dropdown, static_cast(&QComboBox::activated), - this, [this](int index){ - index = std::max(index, 0); -// index = std::min(index, (int)m_device_list.size() - 1); - - ControllerInterface incoming = (ControllerInterface)(index + 1); - ControllerInterface existing = m_session.descriptor()->interface_type; -// cout << "incoming = " << (int)incoming << endl; -// cout << "existing = " << (int)existing << endl; - if (incoming == existing){ - return; - } - - refresh_selection(incoming); - } - ); - connect( - m_controllers_dropdown, static_cast(&QComboBox::activated), - this, [this](int index){ - index = std::max(index, 0); - ControllerType new_value = CONTROLLER_TYPE_STRINGS.get_enum( - m_controllers_dropdown->itemText(index).toStdString(), - ControllerType::None - ); - if (new_value == m_session.controller_type()){ - return; - } - m_session.set_controller(new_value); - } - ); - connect( - m_reset_button, &QPushButton::clicked, - this, [this](bool){ - m_session.reset(); - } - ); - - session.add_listener(*this); -} - - - - -void ControllerSelectorWidget::refresh_selection(ControllerInterface interface_type){ -// cout << "refresh_selection(): "<< endl; - - if (interface_type == ControllerInterface::None){ - interface_type = ControllerInterface::SerialPABotBase; - } - interface_dropdown->setCurrentIndex((int)interface_type - 1); - - delete m_selector; - m_selector = nullptr; - -// m_status_text->setText(QString::fromStdString(html_color_text("Not Connected", COLOR_RED))); - - switch (interface_type){ - case ControllerInterface::SerialPABotBase: - m_selector = new SerialPABotBase::SerialPABotBase_SelectorWidget(*this, m_session.descriptor().get()); - m_dropdowns->insertWidget(1, m_selector); - break; - - case ControllerInterface::TcpSysbotBase: - m_selector = new SysbotBase::TcpSysbotBase_SelectorWidget(*this, m_session.descriptor().get()); - m_dropdowns->insertWidget(1, m_selector); - break; - - default:; - } - - -} - -void ControllerSelectorWidget::refresh_controllers( - ControllerType controller_type, - const std::vector& available_controllers -){ - if (m_controllers_dropdown == nullptr){ - return; - } -// cout << "refresh_controllers()" << endl; - - m_controllers_dropdown->clear(); - - size_t index = 0; - for (size_t c = 0; c < available_controllers.size(); c++){ - const std::string& name = CONTROLLER_TYPE_STRINGS.get_string(available_controllers[c]); - m_controllers_dropdown->addItem(QString::fromStdString(name)); - if (controller_type == available_controllers[c]){ - index = c; - } - } - m_controllers_dropdown->setCurrentIndex((int)index); -} - - - -void ControllerSelectorWidget::descriptor_changed( - const std::shared_ptr& descriptor -){ -// cout << "descriptor_changed()" << endl; - QMetaObject::invokeMethod(this, [=, this]{ - refresh_selection(descriptor->interface_type); - refresh_controllers(ControllerType::None, {}); - }, Qt::QueuedConnection); -} -void ControllerSelectorWidget::controller_changed( - ControllerType controller_type, - const std::vector& available_controllers -){ -// cout << "ControllerSelectorWidget::controller_changed()" << endl; - QMetaObject::invokeMethod(this, [=, this]{ - refresh_controllers(controller_type, available_controllers); - }, Qt::QueuedConnection); -} -void ControllerSelectorWidget::post_status_text_changed(const std::string& text){ -// cout << "ControllerSelectorWidget::status_text_changed(): " << text << endl; - QMetaObject::invokeMethod(this, [this, text]{ - m_status_text->setText(QString::fromStdString(text)); - }); -} -void ControllerSelectorWidget::options_locked(bool locked){ - QMetaObject::invokeMethod(this, [this, locked]{ - m_selector->setEnabled(!locked); - interface_dropdown->setEnabled(!locked); - m_controllers_dropdown->setEnabled(!locked); - m_reset_button->setEnabled(!locked); - }); -} - - - - - -} +/* Controller Selector Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Qt/NoWheelComboBox.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "Controllers/ControllerTypeStrings.h" +#include "ControllerSelectorWidget.h" + +#include "SerialPABotBase/SerialPABotBase_SelectorWidget.h" +#include "NintendoSwitch/Controllers/SysbotBase/SysbotBase_SelectorWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + + +ControllerSelectorWidget::~ControllerSelectorWidget(){ + m_session.remove_listener(*this); +} +ControllerSelectorWidget::ControllerSelectorWidget(QWidget& parent, ControllerSession& session) + : QWidget(&parent) + , m_session(session) +{ + QHBoxLayout* serial_row = new QHBoxLayout(this); + serial_row->setContentsMargins(0, 0, 0, 0); + + serial_row->addWidget(new QLabel("Controller:", this), 1); + serial_row->addSpacing(5); + + m_dropdowns = new QHBoxLayout(); + serial_row->addLayout(m_dropdowns, 5); + serial_row->addSpacing(5); + + interface_dropdown = new NoWheelComboBox(this); + m_dropdowns->addWidget(interface_dropdown, 2); + + interface_dropdown->addItem(QString::fromStdString(CONTROLLER_INTERFACE_STRINGS.get_string(ControllerInterface::SerialPABotBase))); + interface_dropdown->addItem(QString::fromStdString(CONTROLLER_INTERFACE_STRINGS.get_string(ControllerInterface::TcpSysbotBase))); +// interface_dropdown->addItem(QString::fromStdString(CONTROLLER_INTERFACE_STRINGS.get_string(ControllerInterface::UsbSysbotBase))); + +// interface_dropdown->setHidden(true); + + auto current = session.descriptor(); + if (current == nullptr || current->interface_type == ControllerInterface::None){ + current.reset(new SerialPABotBase::SerialPABotBase_Descriptor()); + session.set_device(std::move(current)); + } + interface_dropdown->setCurrentIndex((int)current->interface_type - 1); + m_selector = current->make_selector_QtWidget(*this); + m_dropdowns->addWidget(m_selector); + + + m_dropdowns->addSpacing(5); + m_controllers_dropdown = new NoWheelComboBox(this); + m_dropdowns->addWidget(m_controllers_dropdown, 3); + refresh_controllers(session.controller_type(), session.available_controllers()); + + m_status_text = new QLabel(this); + serial_row->addWidget(m_status_text, 3); + serial_row->addSpacing(5); + + m_status_text->setText(QString::fromStdString(session.status_text())); + + m_reset_button = new QPushButton("Reset Ctrl.", this); + serial_row->addWidget(m_reset_button, 1); + + bool options_locked = session.options_locked(); + if (m_selector){ + m_selector->setEnabled(!options_locked); + } + m_reset_button->setEnabled(!options_locked); + + connect( + interface_dropdown, static_cast(&QComboBox::activated), + this, [this](int index){ + index = std::max(index, 0); +// index = std::min(index, (int)m_device_list.size() - 1); + + ControllerInterface incoming = (ControllerInterface)(index + 1); + ControllerInterface existing = m_session.descriptor()->interface_type; +// cout << "incoming = " << (int)incoming << endl; +// cout << "existing = " << (int)existing << endl; + if (incoming == existing){ + return; + } + + refresh_selection(incoming); + } + ); + connect( + m_controllers_dropdown, static_cast(&QComboBox::activated), + this, [this](int index){ + index = std::max(index, 0); + ControllerType new_value = CONTROLLER_TYPE_STRINGS.get_enum( + m_controllers_dropdown->itemText(index).toStdString(), + ControllerType::None + ); + if (new_value == m_session.controller_type()){ + return; + } + m_session.set_controller(new_value); + } + ); + connect( + m_reset_button, &QPushButton::clicked, + this, [this](bool){ + m_session.reset(); + } + ); + + session.add_listener(*this); +} + + + + +void ControllerSelectorWidget::refresh_selection(ControllerInterface interface_type){ +// cout << "refresh_selection(): "<< endl; + + if (interface_type == ControllerInterface::None){ + interface_type = ControllerInterface::SerialPABotBase; + } + interface_dropdown->setCurrentIndex((int)interface_type - 1); + + delete m_selector; + m_selector = nullptr; + +// m_status_text->setText(QString::fromStdString(html_color_text("Not Connected", COLOR_RED))); + + switch (interface_type){ + case ControllerInterface::SerialPABotBase: + m_selector = new SerialPABotBase::SerialPABotBase_SelectorWidget(*this, m_session.descriptor().get()); + m_dropdowns->insertWidget(1, m_selector); + break; + + case ControllerInterface::TcpSysbotBase: + m_selector = new SysbotBase::TcpSysbotBase_SelectorWidget(*this, m_session.descriptor().get()); + m_dropdowns->insertWidget(1, m_selector); + break; + + default:; + } + + +} + +void ControllerSelectorWidget::refresh_controllers( + ControllerType controller_type, + const std::vector& available_controllers +){ + if (m_controllers_dropdown == nullptr){ + return; + } +// cout << "refresh_controllers()" << endl; + + m_controllers_dropdown->clear(); + + size_t index = 0; + for (size_t c = 0; c < available_controllers.size(); c++){ + const std::string& name = CONTROLLER_TYPE_STRINGS.get_string(available_controllers[c]); + m_controllers_dropdown->addItem(QString::fromStdString(name)); + if (controller_type == available_controllers[c]){ + index = c; + } + } + m_controllers_dropdown->setCurrentIndex((int)index); +} + + + +void ControllerSelectorWidget::descriptor_changed( + const std::shared_ptr& descriptor +){ +// cout << "descriptor_changed()" << endl; + QMetaObject::invokeMethod(this, [=, this]{ + refresh_selection(descriptor->interface_type); + refresh_controllers(ControllerType::None, {}); + }, Qt::QueuedConnection); +} +void ControllerSelectorWidget::controller_changed( + ControllerType controller_type, + const std::vector& available_controllers +){ +// cout << "ControllerSelectorWidget::controller_changed()" << endl; + QMetaObject::invokeMethod(this, [=, this]{ + refresh_controllers(controller_type, available_controllers); + }, Qt::QueuedConnection); +} +void ControllerSelectorWidget::post_status_text_changed(const std::string& text){ +// cout << "ControllerSelectorWidget::status_text_changed(): " << text << endl; + QMetaObject::invokeMethod(this, [this, text]{ + m_status_text->setText(QString::fromStdString(text)); + }); +} +void ControllerSelectorWidget::options_locked(bool locked){ + QMetaObject::invokeMethod(this, [this, locked]{ + m_selector->setEnabled(!locked); + interface_dropdown->setEnabled(!locked); + m_controllers_dropdown->setEnabled(!locked); + m_reset_button->setEnabled(!locked); + }); +} + + + + + +} diff --git a/SerialPrograms/Source/Controllers/ControllerSelectorWidget.h b/SerialPrograms/Source/Controllers/ControllerSelectorWidget.h index 8534eca212..d062d44f2c 100644 --- a/SerialPrograms/Source/Controllers/ControllerSelectorWidget.h +++ b/SerialPrograms/Source/Controllers/ControllerSelectorWidget.h @@ -1,64 +1,64 @@ -/* Controller Selector Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_ControllerWidget_H -#define PokemonAutomation_Controllers_ControllerWidget_H - -#include -#include -#include -#include -#include -#include "ControllerSession.h" - -namespace PokemonAutomation{ - - - - -class ControllerSelectorWidget : public QWidget, private ControllerSession::Listener{ -public: - ~ControllerSelectorWidget(); - ControllerSelectorWidget(QWidget& parent, ControllerSession& session); - - ControllerSession& session(){ - return m_session; - } - -public: - virtual void descriptor_changed( - const std::shared_ptr& descriptor - ) override; - virtual void controller_changed( - ControllerType controller_type, - const std::vector& available_controllers - ) override; - virtual void post_status_text_changed(const std::string& text) override; - virtual void options_locked(bool locked) override; - -private: - void refresh_selection(ControllerInterface interface_type); - void refresh_controllers( - ControllerType controller_type, - const std::vector& available_controllers - ); - -private: - ControllerSession& m_session; - - QHBoxLayout* m_dropdowns; - QWidget* m_selector = nullptr; - QComboBox* interface_dropdown = nullptr; - QComboBox* m_controllers_dropdown = nullptr; - QLabel* m_status_text = nullptr; - QPushButton* m_reset_button = nullptr; - - std::vector> m_device_list; -}; - - -} -#endif +/* Controller Selector Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_ControllerWidget_H +#define PokemonAutomation_Controllers_ControllerWidget_H + +#include +#include +#include +#include +#include +#include "ControllerSession.h" + +namespace PokemonAutomation{ + + + + +class ControllerSelectorWidget : public QWidget, private ControllerSession::Listener{ +public: + ~ControllerSelectorWidget(); + ControllerSelectorWidget(QWidget& parent, ControllerSession& session); + + ControllerSession& session(){ + return m_session; + } + +public: + virtual void descriptor_changed( + const std::shared_ptr& descriptor + ) override; + virtual void controller_changed( + ControllerType controller_type, + const std::vector& available_controllers + ) override; + virtual void post_status_text_changed(const std::string& text) override; + virtual void options_locked(bool locked) override; + +private: + void refresh_selection(ControllerInterface interface_type); + void refresh_controllers( + ControllerType controller_type, + const std::vector& available_controllers + ); + +private: + ControllerSession& m_session; + + QHBoxLayout* m_dropdowns; + QWidget* m_selector = nullptr; + QComboBox* interface_dropdown = nullptr; + QComboBox* m_controllers_dropdown = nullptr; + QLabel* m_status_text = nullptr; + QPushButton* m_reset_button = nullptr; + + std::vector> m_device_list; +}; + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/ControllerSession.cpp b/SerialPrograms/Source/Controllers/ControllerSession.cpp index 459fc311b3..20ee18f964 100644 --- a/SerialPrograms/Source/Controllers/ControllerSession.cpp +++ b/SerialPrograms/Source/Controllers/ControllerSession.cpp @@ -1,436 +1,436 @@ -/* Controller Interface - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "ControllerSession.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -void ControllerSession::add_listener(Listener& listener){ - std::lock_guard lg(m_state_lock); - m_listeners.add(listener); -// if (m_connection && m_connection->is_ready()){ -// signal_controller_changed(m_option.m_controller_type, m_available_controllers); -// } -} -void ControllerSession::remove_listener(Listener& listener){ - std::lock_guard lg(m_state_lock); - m_listeners.remove(listener); -} - - - -ControllerSession::~ControllerSession(){ - std::unique_ptr controller; - std::unique_ptr connection; - { - std::lock_guard lg(m_state_lock); - controller = std::move(m_controller); - connection = std::move(m_connection); - } - controller.reset(); - connection.reset(); -} -ControllerSession::ControllerSession( - Logger& logger, - ControllerOption& option, - const ControllerFeatures& required_features -) - : m_logger(logger) - , m_required_features(required_features) - , m_option(option) - , m_controller_type(ControllerType::None) - , m_options_locked(false) - , m_descriptor(option.descriptor()) - , m_connection(m_descriptor->open_connection(logger, {})) -{ - if (!m_connection){ - return; - } - - // Add listener first so we don't miss the ready signal. - m_connection->add_status_listener(*this); - try{ - // If we already missed it, run it ourselves. - if (m_connection->is_ready()){ - ControllerSession::post_connection_ready( - *m_connection, - m_connection->controller_mode_status() - ); - } - }catch (...){ - m_connection->remove_status_listener(*this); - throw; - } -} - - -std::vector ControllerSession::available_controllers() const{ - std::lock_guard lg(m_state_lock); - return m_available_controllers; -} - -void ControllerSession::get(ControllerOption& option){ - std::lock_guard lg(m_state_lock); - option = m_option; -} -void ControllerSession::set(const ControllerOption& option){ - set_device(option.descriptor()); -} - - - -bool ControllerSession::ready() const{ - std::lock_guard lg(m_state_lock); - if (!m_controller){ - return false; - } - return m_controller->is_ready(); -} -std::shared_ptr ControllerSession::descriptor() const{ - std::lock_guard lg(m_state_lock); - return m_descriptor; -} -ControllerType ControllerSession::controller_type() const{ - std::lock_guard lg(m_state_lock); - return m_controller_type; -} -std::string ControllerSession::status_text() const{ - std::lock_guard lg(m_state_lock); - if (!m_connection){ - return "No controller selected."; - } - return m_connection->status_text(); -} -ControllerConnection& ControllerSession::connection() const{ - if (m_connection){ - return *m_connection; - } - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Connection is null."); -} -AbstractController* ControllerSession::controller() const{ - return m_controller.get(); -} - - - - -std::string ControllerSession::user_input_blocked() const{ - std::lock_guard lg(m_state_lock); - if (!m_connection){ - return "No controller selected."; - } - if (!m_connection->is_ready()){ - return "Connection is not ready."; - } - if (!m_controller->is_ready()){ - return "Controller is not ready."; - } - return m_user_input_disallow_reason; -} -void ControllerSession::set_user_input_blocked(std::string disallow_reason){ - std::lock_guard lg(m_state_lock); -// cout << "set_user_input_blocked() = " << disallow_reason << endl; - m_user_input_disallow_reason = std::move(disallow_reason); -} - -bool ControllerSession::options_locked() const{ - std::lock_guard lg(m_state_lock); - return m_options_locked; -} -void ControllerSession::set_options_locked(bool locked){ - bool original_value; - { - std::lock_guard lg(m_state_lock); - original_value = m_options_locked; - m_options_locked = locked; - } - if (original_value != locked){ - signal_options_locked(locked); - } -} - - -void ControllerSession::make_controller(std::optional change_controller){ - // Must be called under "m_reset_lock". - - bool ready = false; - { - std::lock_guard lg(m_state_lock); - m_connection = m_descriptor->open_connection(m_logger, change_controller); - if (m_connection){ - m_connection->add_status_listener(*this); - ready = m_connection->is_ready(); - } - } - - // If we already missed it, run it ourselves. - if (ready){ - ControllerSession::post_connection_ready( - *m_connection, - m_connection->controller_mode_status() - ); - } - - signal_descriptor_changed(m_descriptor); -} - - - -bool ControllerSession::set_device(const std::shared_ptr& device){ -// cout << "set_device() = " << device->display_name() << endl; - { - std::lock_guard lg0(m_reset_lock); - - // Destroy the current connection+controller. - std::unique_ptr controller; - std::unique_ptr connection; - { - std::lock_guard lg1(m_state_lock); - if (m_options_locked){ - return false; - } - if (*m_descriptor == *device){ - return true; - } - - // Move these out to indicate that we should no longer access them. - controller = std::move(m_controller); - connection = std::move(m_connection); - -// cout << "setting..." << endl; - m_option.set_descriptor(device); - m_descriptor = device; - } - - // With the lock released, it is now safe to destroy them. - // We cannot destroy these under (m_state_lock) due to their asynchronous - // callbacks into this class which will also acquire the same lock. - controller.reset(); - connection.reset(); - - make_controller({}); - } - signal_descriptor_changed(device); - signal_status_text_changed(status_text()); - return true; -} -bool ControllerSession::set_controller(ControllerType controller_type){ -// cout << "set_controller()" << endl; - std::shared_ptr device; - { - std::lock_guard lg0(m_reset_lock); - - // Destroy the current connection+controller. - std::unique_ptr controller; - std::unique_ptr connection; - { - std::lock_guard lg1(m_state_lock); - if (m_options_locked){ - return false; - } - if (m_controller_type == controller_type){ - return true; - } - - // Move these out to indicate that we should no longer access them. - controller = std::move(m_controller); - connection = std::move(m_connection); - - m_controller_type = controller_type; - } - - // With the lock released, it is now safe to destroy them. - // We cannot destroy these under (m_state_lock) due to their asynchronous - // callbacks into this class which will also acquire the same lock. - controller.reset(); - connection.reset(); - - make_controller(controller_type); - device = m_descriptor; - } - signal_descriptor_changed(device); - signal_status_text_changed(status_text()); - return true; -} - - - -std::string ControllerSession::reset(){ -// cout << "ControllerSession::reset()" << endl; - - { - std::lock_guard lg0(m_reset_lock); - - // Destroy the current connection+controller. - std::unique_ptr controller; - std::unique_ptr connection; - { - std::lock_guard lg1(m_state_lock); - if (m_options_locked){ - return "Options are locked."; - } -// if (!m_connection){ -// cout << "ControllerSession::reset() - early return" << endl; -// return "No connection set."; -// } - - // Move these out to indicate that we should no longer access them. - controller = std::move(m_controller); - connection = std::move(m_connection); - } - - // With the lock released, it is now safe to destroy them. - // We cannot destroy these under (m_state_lock) due to their asynchronous - // callbacks into this class which will also acquire the same lock. - controller.reset(); - connection.reset(); - - make_controller(m_controller_type); - } - signal_status_text_changed(status_text()); - return ""; -} - - -//void ControllerSession::pre_connection_not_ready(ControllerConnection& connection){ -// m_listeners.run_method_unique(&Listener::pre_connection_not_ready, connection); -//} -void ControllerSession::post_connection_ready( - ControllerConnection& connection, - const ControllerModeStatus& mode_status -){ - const std::map& supported_controllers = mode_status.supported_controllers; - if (supported_controllers.empty()){ - return; - } - - ControllerType current_controller = mode_status.current_controller; - -// cout << "sleeping" << endl; -// Sleep(10000); - - - std::vector available_controllers; -// ControllerType selected_controller = ControllerType::None; - bool ready; - { - std::lock_guard lg(m_state_lock); - - // Connection has already been closed. - if (m_connection == nullptr){ - return; - } - - // Controller already constructed. - if (m_controller){ - return; - } - - // We only show the "none" option when there are multiple controllers - // to choose from. - if (supported_controllers.size() > 1){ - available_controllers.emplace_back(ControllerType::None); - } - for (const auto& item : supported_controllers){ - available_controllers.emplace_back(item.first); - } - - // Copy the list. One will be moved into "m_available_controllers". - // The other will be stored locally for the callbacks. - m_available_controllers = available_controllers; - - -#if 0 - auto iter = supported_controllers.begin(); - if (supported_controllers.size() == 1){ - // Only one controller available. Force the option to it. - current_controller = iter->first; - }else{ - // Keep the current controller only if it exists. - iter = supported_controllers.find(m_option.m_controller_type); - if (iter != supported_controllers.end()){ - current_controller = m_option.m_controller_type; - } - } -#endif - - // Construct the controller. - if (current_controller != ControllerType::None){ - m_controller = m_descriptor->make_controller( - m_logger, - *m_connection, - current_controller - ); - } - - // Commit all changes. -// cout << "current_controller = " << CONTROLLER_TYPE_STRINGS.get_string(current_controller) << endl; - m_controller_type = current_controller; - ready = m_controller && m_controller->is_ready(); - } - - signal_controller_changed(current_controller, available_controllers); - signal_ready_changed(ready); - signal_status_text_changed(status_text()); -} -void ControllerSession::status_text_changed( - ControllerConnection& connection, - const std::string& text -){ -// cout << "ControllerSession::status_text_changed() = " << text << endl; - std::string controller_error; - { - WriteSpinLock lg(m_message_lock); - controller_error = m_controller_error; - } -// cout << "ControllerSession::status_text_changed(): controller_error = " << controller_error << endl; - if (controller_error.empty()){ - m_listeners.run_method_unique(&Listener::post_status_text_changed, text); - }else{ - m_listeners.run_method_unique(&Listener::post_status_text_changed, controller_error); - } -} -void ControllerSession::on_error( - ControllerConnection& connection, - const std::string& text -){ - WriteSpinLock lg(m_message_lock); - m_controller_error = text; -} - - - - -void ControllerSession::signal_ready_changed(bool ready){ - m_listeners.run_method_unique(&Listener::ready_changed, ready); -} -void ControllerSession::signal_descriptor_changed( - const std::shared_ptr& descriptor -){ - m_listeners.run_method_unique(&Listener::descriptor_changed, descriptor); -} -void ControllerSession::signal_controller_changed( - ControllerType controller_type, - const std::vector& available_controllers -){ - m_listeners.run_method_unique(&Listener::controller_changed, controller_type, available_controllers); -} -void ControllerSession::signal_status_text_changed(const std::string& text){ -// cout << text << endl; - m_listeners.run_method_unique(&Listener::post_status_text_changed, text); -} -void ControllerSession::signal_options_locked(bool locked){ - m_listeners.run_method_unique(&Listener::options_locked, locked); -} - - -} +/* Controller Interface + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "ControllerSession.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +void ControllerSession::add_listener(Listener& listener){ + std::lock_guard lg(m_state_lock); + m_listeners.add(listener); +// if (m_connection && m_connection->is_ready()){ +// signal_controller_changed(m_option.m_controller_type, m_available_controllers); +// } +} +void ControllerSession::remove_listener(Listener& listener){ + std::lock_guard lg(m_state_lock); + m_listeners.remove(listener); +} + + + +ControllerSession::~ControllerSession(){ + std::unique_ptr controller; + std::unique_ptr connection; + { + std::lock_guard lg(m_state_lock); + controller = std::move(m_controller); + connection = std::move(m_connection); + } + controller.reset(); + connection.reset(); +} +ControllerSession::ControllerSession( + Logger& logger, + ControllerOption& option, + const ControllerFeatures& required_features +) + : m_logger(logger) + , m_required_features(required_features) + , m_option(option) + , m_controller_type(ControllerType::None) + , m_options_locked(false) + , m_descriptor(option.descriptor()) + , m_connection(m_descriptor->open_connection(logger, {})) +{ + if (!m_connection){ + return; + } + + // Add listener first so we don't miss the ready signal. + m_connection->add_status_listener(*this); + try{ + // If we already missed it, run it ourselves. + if (m_connection->is_ready()){ + ControllerSession::post_connection_ready( + *m_connection, + m_connection->controller_mode_status() + ); + } + }catch (...){ + m_connection->remove_status_listener(*this); + throw; + } +} + + +std::vector ControllerSession::available_controllers() const{ + std::lock_guard lg(m_state_lock); + return m_available_controllers; +} + +void ControllerSession::get(ControllerOption& option){ + std::lock_guard lg(m_state_lock); + option = m_option; +} +void ControllerSession::set(const ControllerOption& option){ + set_device(option.descriptor()); +} + + + +bool ControllerSession::ready() const{ + std::lock_guard lg(m_state_lock); + if (!m_controller){ + return false; + } + return m_controller->is_ready(); +} +std::shared_ptr ControllerSession::descriptor() const{ + std::lock_guard lg(m_state_lock); + return m_descriptor; +} +ControllerType ControllerSession::controller_type() const{ + std::lock_guard lg(m_state_lock); + return m_controller_type; +} +std::string ControllerSession::status_text() const{ + std::lock_guard lg(m_state_lock); + if (!m_connection){ + return "No controller selected."; + } + return m_connection->status_text(); +} +ControllerConnection& ControllerSession::connection() const{ + if (m_connection){ + return *m_connection; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Connection is null."); +} +AbstractController* ControllerSession::controller() const{ + return m_controller.get(); +} + + + + +std::string ControllerSession::user_input_blocked() const{ + std::lock_guard lg(m_state_lock); + if (!m_connection){ + return "No controller selected."; + } + if (!m_connection->is_ready()){ + return "Connection is not ready."; + } + if (!m_controller->is_ready()){ + return "Controller is not ready."; + } + return m_user_input_disallow_reason; +} +void ControllerSession::set_user_input_blocked(std::string disallow_reason){ + std::lock_guard lg(m_state_lock); +// cout << "set_user_input_blocked() = " << disallow_reason << endl; + m_user_input_disallow_reason = std::move(disallow_reason); +} + +bool ControllerSession::options_locked() const{ + std::lock_guard lg(m_state_lock); + return m_options_locked; +} +void ControllerSession::set_options_locked(bool locked){ + bool original_value; + { + std::lock_guard lg(m_state_lock); + original_value = m_options_locked; + m_options_locked = locked; + } + if (original_value != locked){ + signal_options_locked(locked); + } +} + + +void ControllerSession::make_controller(std::optional change_controller){ + // Must be called under "m_reset_lock". + + bool ready = false; + { + std::lock_guard lg(m_state_lock); + m_connection = m_descriptor->open_connection(m_logger, change_controller); + if (m_connection){ + m_connection->add_status_listener(*this); + ready = m_connection->is_ready(); + } + } + + // If we already missed it, run it ourselves. + if (ready){ + ControllerSession::post_connection_ready( + *m_connection, + m_connection->controller_mode_status() + ); + } + + signal_descriptor_changed(m_descriptor); +} + + + +bool ControllerSession::set_device(const std::shared_ptr& device){ +// cout << "set_device() = " << device->display_name() << endl; + { + std::lock_guard lg0(m_reset_lock); + + // Destroy the current connection+controller. + std::unique_ptr controller; + std::unique_ptr connection; + { + std::lock_guard lg1(m_state_lock); + if (m_options_locked){ + return false; + } + if (*m_descriptor == *device){ + return true; + } + + // Move these out to indicate that we should no longer access them. + controller = std::move(m_controller); + connection = std::move(m_connection); + +// cout << "setting..." << endl; + m_option.set_descriptor(device); + m_descriptor = device; + } + + // With the lock released, it is now safe to destroy them. + // We cannot destroy these under (m_state_lock) due to their asynchronous + // callbacks into this class which will also acquire the same lock. + controller.reset(); + connection.reset(); + + make_controller({}); + } + signal_descriptor_changed(device); + signal_status_text_changed(status_text()); + return true; +} +bool ControllerSession::set_controller(ControllerType controller_type){ +// cout << "set_controller()" << endl; + std::shared_ptr device; + { + std::lock_guard lg0(m_reset_lock); + + // Destroy the current connection+controller. + std::unique_ptr controller; + std::unique_ptr connection; + { + std::lock_guard lg1(m_state_lock); + if (m_options_locked){ + return false; + } + if (m_controller_type == controller_type){ + return true; + } + + // Move these out to indicate that we should no longer access them. + controller = std::move(m_controller); + connection = std::move(m_connection); + + m_controller_type = controller_type; + } + + // With the lock released, it is now safe to destroy them. + // We cannot destroy these under (m_state_lock) due to their asynchronous + // callbacks into this class which will also acquire the same lock. + controller.reset(); + connection.reset(); + + make_controller(controller_type); + device = m_descriptor; + } + signal_descriptor_changed(device); + signal_status_text_changed(status_text()); + return true; +} + + + +std::string ControllerSession::reset(){ +// cout << "ControllerSession::reset()" << endl; + + { + std::lock_guard lg0(m_reset_lock); + + // Destroy the current connection+controller. + std::unique_ptr controller; + std::unique_ptr connection; + { + std::lock_guard lg1(m_state_lock); + if (m_options_locked){ + return "Options are locked."; + } +// if (!m_connection){ +// cout << "ControllerSession::reset() - early return" << endl; +// return "No connection set."; +// } + + // Move these out to indicate that we should no longer access them. + controller = std::move(m_controller); + connection = std::move(m_connection); + } + + // With the lock released, it is now safe to destroy them. + // We cannot destroy these under (m_state_lock) due to their asynchronous + // callbacks into this class which will also acquire the same lock. + controller.reset(); + connection.reset(); + + make_controller(m_controller_type); + } + signal_status_text_changed(status_text()); + return ""; +} + + +//void ControllerSession::pre_connection_not_ready(ControllerConnection& connection){ +// m_listeners.run_method_unique(&Listener::pre_connection_not_ready, connection); +//} +void ControllerSession::post_connection_ready( + ControllerConnection& connection, + const ControllerModeStatus& mode_status +){ + const std::map& supported_controllers = mode_status.supported_controllers; + if (supported_controllers.empty()){ + return; + } + + ControllerType current_controller = mode_status.current_controller; + +// cout << "sleeping" << endl; +// Sleep(10000); + + + std::vector available_controllers; +// ControllerType selected_controller = ControllerType::None; + bool ready; + { + std::lock_guard lg(m_state_lock); + + // Connection has already been closed. + if (m_connection == nullptr){ + return; + } + + // Controller already constructed. + if (m_controller){ + return; + } + + // We only show the "none" option when there are multiple controllers + // to choose from. + if (supported_controllers.size() > 1){ + available_controllers.emplace_back(ControllerType::None); + } + for (const auto& item : supported_controllers){ + available_controllers.emplace_back(item.first); + } + + // Copy the list. One will be moved into "m_available_controllers". + // The other will be stored locally for the callbacks. + m_available_controllers = available_controllers; + + +#if 0 + auto iter = supported_controllers.begin(); + if (supported_controllers.size() == 1){ + // Only one controller available. Force the option to it. + current_controller = iter->first; + }else{ + // Keep the current controller only if it exists. + iter = supported_controllers.find(m_option.m_controller_type); + if (iter != supported_controllers.end()){ + current_controller = m_option.m_controller_type; + } + } +#endif + + // Construct the controller. + if (current_controller != ControllerType::None){ + m_controller = m_descriptor->make_controller( + m_logger, + *m_connection, + current_controller + ); + } + + // Commit all changes. +// cout << "current_controller = " << CONTROLLER_TYPE_STRINGS.get_string(current_controller) << endl; + m_controller_type = current_controller; + ready = m_controller && m_controller->is_ready(); + } + + signal_controller_changed(current_controller, available_controllers); + signal_ready_changed(ready); + signal_status_text_changed(status_text()); +} +void ControllerSession::status_text_changed( + ControllerConnection& connection, + const std::string& text +){ +// cout << "ControllerSession::status_text_changed() = " << text << endl; + std::string controller_error; + { + WriteSpinLock lg(m_message_lock); + controller_error = m_controller_error; + } +// cout << "ControllerSession::status_text_changed(): controller_error = " << controller_error << endl; + if (controller_error.empty()){ + m_listeners.run_method_unique(&Listener::post_status_text_changed, text); + }else{ + m_listeners.run_method_unique(&Listener::post_status_text_changed, controller_error); + } +} +void ControllerSession::on_error( + ControllerConnection& connection, + const std::string& text +){ + WriteSpinLock lg(m_message_lock); + m_controller_error = text; +} + + + + +void ControllerSession::signal_ready_changed(bool ready){ + m_listeners.run_method_unique(&Listener::ready_changed, ready); +} +void ControllerSession::signal_descriptor_changed( + const std::shared_ptr& descriptor +){ + m_listeners.run_method_unique(&Listener::descriptor_changed, descriptor); +} +void ControllerSession::signal_controller_changed( + ControllerType controller_type, + const std::vector& available_controllers +){ + m_listeners.run_method_unique(&Listener::controller_changed, controller_type, available_controllers); +} +void ControllerSession::signal_status_text_changed(const std::string& text){ +// cout << text << endl; + m_listeners.run_method_unique(&Listener::post_status_text_changed, text); +} +void ControllerSession::signal_options_locked(bool locked){ + m_listeners.run_method_unique(&Listener::options_locked, locked); +} + + +} diff --git a/SerialPrograms/Source/Controllers/ControllerSession.h b/SerialPrograms/Source/Controllers/ControllerSession.h index d97a4537f8..dda2d28abd 100644 --- a/SerialPrograms/Source/Controllers/ControllerSession.h +++ b/SerialPrograms/Source/Controllers/ControllerSession.h @@ -1,177 +1,177 @@ -/* Controller Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_ControllerSession_H -#define PokemonAutomation_Controllers_ControllerSession_H - -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/ListenerSet.h" -//#include "Common/Cpp/Exceptions.h" -#include "Controller.h" -#include "ControllerDescriptor.h" -#include "ControllerConnection.h" - -namespace PokemonAutomation{ - - - - -class ControllerSession : private ControllerConnection::StatusListener{ -public: - struct Listener{ - virtual void ready_changed(bool ready){} - virtual void descriptor_changed( - const std::shared_ptr& descriptor - ){} - virtual void controller_changed( - ControllerType controller_type, - const std::vector& available_controllers - ){} - virtual void post_status_text_changed(const std::string& text){} - virtual void options_locked(bool locked){} - }; - - void add_listener(Listener& listener); - void remove_listener(Listener& listener); - - -public: - ~ControllerSession(); - ControllerSession( - Logger& logger, - ControllerOption& option, - const ControllerFeatures& required_features - ); - - Logger& logger(){ - return m_logger; - } - const ControllerFeatures& required_features(){ - return m_required_features; - } - std::vector available_controllers() const; - - void get(ControllerOption& option); - void set(const ControllerOption& option); - - bool ready() const; - std::shared_ptr descriptor() const; - ControllerType controller_type() const; - std::string status_text() const; - - const ControllerOption& option() const{ - return m_option; - } - ControllerConnection& connection() const; - AbstractController* controller() const; - - -public: - // Empty String: User input is allowed. - // Non-empty String: User input is blocked. The string is the reason. - std::string user_input_blocked() const; - void set_user_input_blocked(std::string disallow_reason); - - bool options_locked() const; - void set_options_locked(bool locked); - - -public: - bool set_device(const std::shared_ptr& device); - bool set_controller(ControllerType controller_type); - - -public: - // Returns empty string on success. Otherwise returns error message. - std::string reset(); - - // Try to run the following lambda on the underlying controller type. - // Returns empty string if successful. Otherwise returns error message. - template - std::string try_run(Lambda&& function) noexcept{ - std::lock_guard lg(m_state_lock); - if (!m_controller){ - return "Controller is null."; - } - try{ - // This will be a cross-cast in most cases. - ControllerType* child = dynamic_cast(m_controller.get()); - if (child == nullptr){ - m_logger.log("ControllerSession::try_run(): Incompatible controller type cast.", COLOR_RED); - return "Incompatible controller type cast."; - } - if (!m_user_input_disallow_reason.empty()){ - return m_user_input_disallow_reason; - } - function(*child); - }catch (Exception& e){ - return e.to_str(); - }catch (...){ - return "Unknown exception."; - } - return ""; - } - - -private: - void make_controller(std::optional change_controller); - -// virtual void pre_connection_not_ready(ControllerConnection& connection) override; - virtual void post_connection_ready( - ControllerConnection& connection, - const ControllerModeStatus& mode_status - ) override; - virtual void status_text_changed( - ControllerConnection& connection, - const std::string& text - ) override; - virtual void on_error( - ControllerConnection& connection, - const std::string& text - ) override; - - void signal_ready_changed(bool ready); - void signal_descriptor_changed( - const std::shared_ptr& descriptor - ); - void signal_controller_changed( - ControllerType controller_type, - const std::vector& available_controllers - ); - void signal_status_text_changed(const std::string& text); - void signal_options_locked(bool locked); - - -private: - Logger& m_logger; - const ControllerFeatures& m_required_features; - ControllerOption& m_option; - ControllerType m_controller_type; - - std::mutex m_reset_lock; - mutable std::mutex m_state_lock; - - bool m_options_locked; - std::string m_user_input_disallow_reason; - - SpinLock m_message_lock; - std::string m_controller_error; - - std::vector m_available_controllers; - - std::shared_ptr m_descriptor; - std::unique_ptr m_connection; - std::unique_ptr m_controller; - - ListenerSet m_listeners; -}; - - - - -} -#endif +/* Controller Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_ControllerSession_H +#define PokemonAutomation_Controllers_ControllerSession_H + +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/ListenerSet.h" +//#include "Common/Cpp/Exceptions.h" +#include "Controller.h" +#include "ControllerDescriptor.h" +#include "ControllerConnection.h" + +namespace PokemonAutomation{ + + + + +class ControllerSession : private ControllerConnection::StatusListener{ +public: + struct Listener{ + virtual void ready_changed(bool ready){} + virtual void descriptor_changed( + const std::shared_ptr& descriptor + ){} + virtual void controller_changed( + ControllerType controller_type, + const std::vector& available_controllers + ){} + virtual void post_status_text_changed(const std::string& text){} + virtual void options_locked(bool locked){} + }; + + void add_listener(Listener& listener); + void remove_listener(Listener& listener); + + +public: + ~ControllerSession(); + ControllerSession( + Logger& logger, + ControllerOption& option, + const ControllerFeatures& required_features + ); + + Logger& logger(){ + return m_logger; + } + const ControllerFeatures& required_features(){ + return m_required_features; + } + std::vector available_controllers() const; + + void get(ControllerOption& option); + void set(const ControllerOption& option); + + bool ready() const; + std::shared_ptr descriptor() const; + ControllerType controller_type() const; + std::string status_text() const; + + const ControllerOption& option() const{ + return m_option; + } + ControllerConnection& connection() const; + AbstractController* controller() const; + + +public: + // Empty String: User input is allowed. + // Non-empty String: User input is blocked. The string is the reason. + std::string user_input_blocked() const; + void set_user_input_blocked(std::string disallow_reason); + + bool options_locked() const; + void set_options_locked(bool locked); + + +public: + bool set_device(const std::shared_ptr& device); + bool set_controller(ControllerType controller_type); + + +public: + // Returns empty string on success. Otherwise returns error message. + std::string reset(); + + // Try to run the following lambda on the underlying controller type. + // Returns empty string if successful. Otherwise returns error message. + template + std::string try_run(Lambda&& function) noexcept{ + std::lock_guard lg(m_state_lock); + if (!m_controller){ + return "Controller is null."; + } + try{ + // This will be a cross-cast in most cases. + ControllerType* child = dynamic_cast(m_controller.get()); + if (child == nullptr){ + m_logger.log("ControllerSession::try_run(): Incompatible controller type cast.", COLOR_RED); + return "Incompatible controller type cast."; + } + if (!m_user_input_disallow_reason.empty()){ + return m_user_input_disallow_reason; + } + function(*child); + }catch (Exception& e){ + return e.to_str(); + }catch (...){ + return "Unknown exception."; + } + return ""; + } + + +private: + void make_controller(std::optional change_controller); + +// virtual void pre_connection_not_ready(ControllerConnection& connection) override; + virtual void post_connection_ready( + ControllerConnection& connection, + const ControllerModeStatus& mode_status + ) override; + virtual void status_text_changed( + ControllerConnection& connection, + const std::string& text + ) override; + virtual void on_error( + ControllerConnection& connection, + const std::string& text + ) override; + + void signal_ready_changed(bool ready); + void signal_descriptor_changed( + const std::shared_ptr& descriptor + ); + void signal_controller_changed( + ControllerType controller_type, + const std::vector& available_controllers + ); + void signal_status_text_changed(const std::string& text); + void signal_options_locked(bool locked); + + +private: + Logger& m_logger; + const ControllerFeatures& m_required_features; + ControllerOption& m_option; + ControllerType m_controller_type; + + std::mutex m_reset_lock; + mutable std::mutex m_state_lock; + + bool m_options_locked; + std::string m_user_input_disallow_reason; + + SpinLock m_message_lock; + std::string m_controller_error; + + std::vector m_available_controllers; + + std::shared_ptr m_descriptor; + std::unique_ptr m_connection; + std::unique_ptr m_controller; + + ListenerSet m_listeners; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/ControllerTypeStrings.cpp b/SerialPrograms/Source/Controllers/ControllerTypeStrings.cpp index 98c3c4547f..029749116c 100644 --- a/SerialPrograms/Source/Controllers/ControllerTypeStrings.cpp +++ b/SerialPrograms/Source/Controllers/ControllerTypeStrings.cpp @@ -1,39 +1,39 @@ -/* Controller Type Strings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "ControllerTypeStrings.h" - -namespace PokemonAutomation{ - - - -const EnumStringMap CONTROLLER_INTERFACE_STRINGS{ - {ControllerInterface::None, "None"}, - {ControllerInterface::SerialPABotBase, "Serial: PABotBase"}, - {ControllerInterface::TcpSysbotBase, "TCP: sys-botbase"}, - {ControllerInterface::UsbSysbotBase, "USB: sys-botbase"}, -}; - -const EnumStringMap CONTROLLER_TYPE_STRINGS{ - {ControllerType::None, "None"}, - {ControllerType::NintendoSwitch_WiredProController, "NS: Wired Pro Controller"}, - {ControllerType::NintendoSwitch_WirelessProController, "NS: Wireless Pro Controller"}, - {ControllerType::NintendoSwitch_LeftJoycon, "NS: Left Joycon"}, - {ControllerType::NintendoSwitch_RightJoycon, "NS: Right Joycon"}, -}; - -const EnumStringMap CONTROLLER_FEATURE_STRINGS{ - {ControllerFeature::TickPrecise, "TickPrecise"}, - {ControllerFeature::NintendoSwitch_ProController, "NintendoSwitch_ProController"}, - {ControllerFeature::NintendoSwitch_LeftJoycon, "NintendoSwitch_LeftJoycon"}, - {ControllerFeature::NintendoSwitch_RightJoycon, "NintendoSwitch_RightJoycon"}, - {ControllerFeature::NintendoSwitch_DateSkip, "NintendoSwitch_DateSkip"}, -}; - - - - -} +/* Controller Type Strings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "ControllerTypeStrings.h" + +namespace PokemonAutomation{ + + + +const EnumStringMap CONTROLLER_INTERFACE_STRINGS{ + {ControllerInterface::None, "None"}, + {ControllerInterface::SerialPABotBase, "Serial: PABotBase"}, + {ControllerInterface::TcpSysbotBase, "TCP: sys-botbase"}, + {ControllerInterface::UsbSysbotBase, "USB: sys-botbase"}, +}; + +const EnumStringMap CONTROLLER_TYPE_STRINGS{ + {ControllerType::None, "None"}, + {ControllerType::NintendoSwitch_WiredProController, "NS: Wired Pro Controller"}, + {ControllerType::NintendoSwitch_WirelessProController, "NS: Wireless Pro Controller"}, + {ControllerType::NintendoSwitch_LeftJoycon, "NS: Left Joycon"}, + {ControllerType::NintendoSwitch_RightJoycon, "NS: Right Joycon"}, +}; + +const EnumStringMap CONTROLLER_FEATURE_STRINGS{ + {ControllerFeature::TickPrecise, "TickPrecise"}, + {ControllerFeature::NintendoSwitch_ProController, "NintendoSwitch_ProController"}, + {ControllerFeature::NintendoSwitch_LeftJoycon, "NintendoSwitch_LeftJoycon"}, + {ControllerFeature::NintendoSwitch_RightJoycon, "NintendoSwitch_RightJoycon"}, + {ControllerFeature::NintendoSwitch_DateSkip, "NintendoSwitch_DateSkip"}, +}; + + + + +} diff --git a/SerialPrograms/Source/Controllers/ControllerTypeStrings.h b/SerialPrograms/Source/Controllers/ControllerTypeStrings.h index 406aeeb64a..b78ae099e4 100644 --- a/SerialPrograms/Source/Controllers/ControllerTypeStrings.h +++ b/SerialPrograms/Source/Controllers/ControllerTypeStrings.h @@ -1,24 +1,24 @@ -/* Controller Type Strings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_ControllerTypeStrings_H -#define PokemonAutomation_Controllers_ControllerTypeStrings_H - -#include "Common/Cpp/EnumStringMap.h" -#include "ControllerTypes.h" - -namespace PokemonAutomation{ - - - -extern const EnumStringMap CONTROLLER_INTERFACE_STRINGS; -extern const EnumStringMap CONTROLLER_TYPE_STRINGS; -extern const EnumStringMap CONTROLLER_FEATURE_STRINGS; - - - -} -#endif +/* Controller Type Strings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_ControllerTypeStrings_H +#define PokemonAutomation_Controllers_ControllerTypeStrings_H + +#include "Common/Cpp/EnumStringMap.h" +#include "ControllerTypes.h" + +namespace PokemonAutomation{ + + + +extern const EnumStringMap CONTROLLER_INTERFACE_STRINGS; +extern const EnumStringMap CONTROLLER_TYPE_STRINGS; +extern const EnumStringMap CONTROLLER_FEATURE_STRINGS; + + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/ControllerTypes.h b/SerialPrograms/Source/Controllers/ControllerTypes.h index 8e413f2fd9..8ba6c97a8e 100644 --- a/SerialPrograms/Source/Controllers/ControllerTypes.h +++ b/SerialPrograms/Source/Controllers/ControllerTypes.h @@ -1,72 +1,71 @@ -/* Controller Types - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_ControllerTypes_H -#define PokemonAutomation_Controllers_ControllerTypes_H - -namespace PokemonAutomation{ - - -// This is used only for the UI to indicate if a program may be faster on -// tick-precise controllers. There is no functional effect. -enum class FasterIfTickPrecise{ - NOT_FASTER, - FASTER, - MUCH_FASTER, -}; - - -enum class ControllerInterface{ - None, - SerialPABotBase, - TcpSysbotBase, - UsbSysbotBase, -}; - - -enum class ControllerType{ - None, - - // There's a difference between the generic 3rd party wired controllers and - // a pro controller connected over USB. If/when we support the latter, we - // will need to split this controller type. - NintendoSwitch_WiredProController, - - NintendoSwitch_WirelessProController, - NintendoSwitch_LeftJoycon, - NintendoSwitch_RightJoycon, -}; - - -enum class ControllerFeature{ - TickPrecise, - TimingFlexibleMilliseconds, - - // If we add support gyro or rumble, we will need to split this feature - // since the Pokken controller doesn't support those. - NintendoSwitch_ProController, - - NintendoSwitch_LeftJoycon, - NintendoSwitch_RightJoycon, - - // This is leftover from the days of RPCs. But we keep it here as a hack to - // lock ESP32 out of the day skippers since it's too unstable to run those. - NintendoSwitch_DateSkip, -}; - - -enum class ControllerPerformanceClass{ - Unknown, - SerialPABotBase_Wired_125Hz, - SerialPABotBase_Wireless_ESP32, - SysbotBase, -}; - - - - -} -#endif +/* Controller Types + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_ControllerTypes_H +#define PokemonAutomation_Controllers_ControllerTypes_H + +namespace PokemonAutomation{ + + +// This is used only for the UI to indicate if a program may be faster on +// tick-precise controllers. There is no functional effect. +enum class FasterIfTickPrecise{ + NOT_FASTER, + FASTER, + MUCH_FASTER, +}; + + +enum class ControllerInterface{ + None, + SerialPABotBase, + TcpSysbotBase, + UsbSysbotBase, +}; + + +enum class ControllerType{ + None, + + // There's a difference between the generic 3rd party wired controllers and + // a pro controller connected over USB. If/when we support the latter, we + // will need to split this controller type. + NintendoSwitch_WiredProController, + + NintendoSwitch_WirelessProController, + NintendoSwitch_LeftJoycon, + NintendoSwitch_RightJoycon, +}; + + +enum class ControllerFeature{ + TickPrecise, + + // If we add support gyro or rumble, we will need to split this feature + // since the Pokken controller doesn't support those. + NintendoSwitch_ProController, + + NintendoSwitch_LeftJoycon, + NintendoSwitch_RightJoycon, + + // This is leftover from the days of RPCs. But we keep it here as a hack to + // lock ESP32 out of the day skippers since it's too unstable to run those. + NintendoSwitch_DateSkip, +}; + + +enum class ControllerPerformanceClass{ + Unknown, + SerialPABotBase_Wired, + SerialPABotBase_Wireless, + SysbotBase, +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/JoystickTools.h b/SerialPrograms/Source/Controllers/JoystickTools.h index 27df31b64e..5c4736234d 100644 --- a/SerialPrograms/Source/Controllers/JoystickTools.h +++ b/SerialPrograms/Source/Controllers/JoystickTools.h @@ -1,111 +1,123 @@ -/* Joystick Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_JoystickTools_H -#define PokemonAutomation_Controllers_JoystickTools_H - -#include -#include - -namespace PokemonAutomation{ -namespace JoystickTools{ - - -inline void max_out_magnitude(double& x, double& y){ - double mag = x*x + y*y; - if (mag == 0){ - return; - } - - double abs_x = std::abs(x); - double abs_y = std::abs(y); - - if (abs_x < abs_y){ - x /= abs_y; - y = y < 0 ? -1 : 1; - }else{ - y /= abs_x; - x = x < 0 ? -1 : 1; - } -} -inline double project_to_range(double x, double lo, double hi){ - if (x <= -1){ - return -1; - } - if (x >= 1){ - return 1; - } - return x * (hi - lo) + lo; -} - - - - -inline double linear_u8_to_float(uint8_t x){ - if (x <= 128){ - return (x - 128) * (1. / 128); - }else{ - return (x - 128) * (1. / 127); - } -} -inline uint8_t linear_float_to_u8(double f){ - if (f <= 0){ - f = std::max(f, -1); - f = f * 128 + 128; - return (uint8_t)(f + 0.5); - }else{ - f = std::min(f, +1); - f = f * 127 + 128; - return (uint8_t)(f + 0.5); - } -} -inline int16_t linear_float_to_s16(double f){ - if (f <= 0){ - f = std::max(f, -1); - f = f * 32768; - return (int16_t)(f + 0.5); - }else{ - f = std::min(f, +1); - f = f * 32767; - return (int16_t)(f + 0.5); - } -} -inline uint16_t linear_float_to_u16(double f){ - if (f <= 0){ - f = std::max(f, -1); - f = f * 32768 + 32768; - return (uint16_t)(f + 0.5); - }else{ - f = std::min(f, +1); - f = f * 32767 + 32768; - return (uint16_t)(f + 0.5); - } -} - - - -inline uint16_t linear_float_to_u12(double f){ - if (f <= 0){ - f = std::max(f, -1); - f = f * 2048 + 2048; - return (uint16_t)(f + 0.5); - }else{ - f = std::min(f, +1); - f = f * 2047 + 2048; - return (uint16_t)(f + 0.5); - } -} - - - - - - - - -} -} -#endif +/* Joystick Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_JoystickTools_H +#define PokemonAutomation_Controllers_JoystickTools_H + +#include +#include +#include + +namespace PokemonAutomation{ +namespace JoystickTools{ + + +inline void clip_magnitude(double& x, double& y){ + double mag = x*x + y*y; + if (mag <= 1.0){ + return; + } + + double scale = 1 / std::sqrt(mag); + + x *= scale; + y *= scale; +} +inline void max_out_magnitude(double& x, double& y){ + double mag = x*x + y*y; + if (mag == 0){ + return; + } + + double abs_x = std::abs(x); + double abs_y = std::abs(y); + + if (abs_x < abs_y){ + x /= abs_y; + y = y < 0 ? -1 : 1; + }else{ + y /= abs_x; + x = x < 0 ? -1 : 1; + } +} +inline double project_to_range(double x, double lo, double hi){ + if (x <= -1){ + return -1; + } + if (x >= 1){ + return 1; + } + return x * (hi - lo) + lo; +} + + + + +inline double linear_u8_to_float(uint8_t x){ + if (x <= 128){ + return (x - 128) * (1. / 128); + }else{ + return (x - 128) * (1. / 127); + } +} +inline uint8_t linear_float_to_u8(double f){ + if (f <= 0){ + f = std::max(f, -1); + f = f * 128 + 128; + return (uint8_t)(f + 0.5); + }else{ + f = std::min(f, +1); + f = f * 127 + 128; + return (uint8_t)(f + 0.5); + } +} +inline int16_t linear_float_to_s16(double f){ + if (f <= 0){ + f = std::max(f, -1); + f = f * 32768; + return (int16_t)(f + 0.5); + }else{ + f = std::min(f, +1); + f = f * 32767; + return (int16_t)(f + 0.5); + } +} +inline uint16_t linear_float_to_u16(double f){ + if (f <= 0){ + f = std::max(f, -1); + f = f * 32768 + 32768; + return (uint16_t)(f + 0.5); + }else{ + f = std::min(f, +1); + f = f * 32767 + 32768; + return (uint16_t)(f + 0.5); + } +} + + + +inline uint16_t linear_float_to_u12(double f){ + if (f <= 0){ + f = std::max(f, -1); + f = f * 2048 + 2048; + return (uint16_t)(f + 0.5); + }else{ + f = std::min(f, +1); + f = f * 2047 + 2048; + return (uint16_t)(f + 0.5); + } +} + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Controllers/KeyboardInput/GlobalQtKeyMap.cpp b/SerialPrograms/Source/Controllers/KeyboardInput/GlobalQtKeyMap.cpp index 32c8f1173e..8778f9f580 100644 --- a/SerialPrograms/Source/Controllers/KeyboardInput/GlobalQtKeyMap.cpp +++ b/SerialPrograms/Source/Controllers/KeyboardInput/GlobalQtKeyMap.cpp @@ -1,40 +1,40 @@ -/* Global Qt Key Map - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "GlobalQtKeyMap.h" - -namespace PokemonAutomation{ - - - -void QtKeyMap::record(const QKeyEvent& event){ - int qt_key = event.key(); - uint32_t native_key = event.nativeVirtualKey(); - if (native_key == 0 && (qt_key == 0 || qt_key == Qt::Key_unknown)){ - // both native key and Qt key event is 0 or unknown, meaning we really don't know - // what key event it is. Skip - return; - } - - Qt::Key qkey = (Qt::Key)qt_key; - WriteSpinLock lg(m_lock); - m_map[native_key].insert(qkey); -} - -std::set QtKeyMap::get_QtKeys(uint32_t native_key) const{ - ReadSpinLock lg(m_lock); - auto iter = m_map.find(native_key); - if (iter != m_map.end()){ - return iter->second; - } - return {}; -} - - - -} +/* Global Qt Key Map + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "GlobalQtKeyMap.h" + +namespace PokemonAutomation{ + + + +void QtKeyMap::record(const QKeyEvent& event){ + int qt_key = event.key(); + uint32_t native_key = event.nativeVirtualKey(); + if (native_key == 0 && (qt_key == 0 || qt_key == Qt::Key_unknown)){ + // both native key and Qt key event is 0 or unknown, meaning we really don't know + // what key event it is. Skip + return; + } + + Qt::Key qkey = (Qt::Key)qt_key; + WriteSpinLock lg(m_lock); + m_map[native_key].insert(qkey); +} + +std::set QtKeyMap::get_QtKeys(uint32_t native_key) const{ + ReadSpinLock lg(m_lock); + auto iter = m_map.find(native_key); + if (iter != m_map.end()){ + return iter->second; + } + return {}; +} + + + +} diff --git a/SerialPrograms/Source/Controllers/KeyboardInput/GlobalQtKeyMap.h b/SerialPrograms/Source/Controllers/KeyboardInput/GlobalQtKeyMap.h index 109a938215..c2b75d6070 100644 --- a/SerialPrograms/Source/Controllers/KeyboardInput/GlobalQtKeyMap.h +++ b/SerialPrograms/Source/Controllers/KeyboardInput/GlobalQtKeyMap.h @@ -1,45 +1,45 @@ -/* Global Qt Key Map - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_GlobalQtKeyMap_H -#define PokemonAutomation_Controllers_GlobalQtKeyMap_H - -#include -#include -#include -#include "Common/Cpp/Concurrency/SpinLock.h" - -namespace PokemonAutomation{ - - - - -class QtKeyMap{ -public: - static QtKeyMap& instance(){ - static QtKeyMap map; - return map; - } - - void record(const QKeyEvent& event); - - std::set get_QtKeys(uint32_t native_key) const; - - -private: - QtKeyMap() = default; - - -private: - mutable SpinLock m_lock; - // Map of native key to Qt's key ID. - std::map> m_map; -}; - - - -} -#endif +/* Global Qt Key Map + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_GlobalQtKeyMap_H +#define PokemonAutomation_Controllers_GlobalQtKeyMap_H + +#include +#include +#include +#include "Common/Cpp/Concurrency/SpinLock.h" + +namespace PokemonAutomation{ + + + + +class QtKeyMap{ +public: + static QtKeyMap& instance(){ + static QtKeyMap map; + return map; + } + + void record(const QKeyEvent& event); + + std::set get_QtKeys(uint32_t native_key) const; + + +private: + QtKeyMap() = default; + + +private: + mutable SpinLock m_lock; + // Map of native key to Qt's key ID. + std::map> m_map; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardInput.cpp b/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardInput.cpp index c3cc5489ad..5440ac8b9a 100644 --- a/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardInput.cpp +++ b/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardInput.cpp @@ -1,186 +1,187 @@ -/* Keyboard Input - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/PanicDump.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/Options/Environment/PerformanceOptions.h" -#include "Controllers/KeyboardInput/GlobalQtKeyMap.h" -#include "KeyboardInput.h" - -namespace PokemonAutomation{ - - - -KeyboardInputController::~KeyboardInputController() = default; -KeyboardInputController::KeyboardInputController(bool enabled) - : m_stop(false) -{} - -void KeyboardInputController::start(){ - m_thread = std::thread( - run_with_catch, - "KeyboardInputController::thread_loop()", - [this]{ thread_loop(); } - ); -} -void KeyboardInputController::stop() noexcept{ - bool expected = false; - if (!m_stop.compare_exchange_strong(expected, true)){ - // Already stopped. - return; - } - { - std::lock_guard lg(m_sleep_lock); - m_cv.notify_all(); - } - m_thread.join(); -} - -void KeyboardInputController::clear_state(){ - { - WriteSpinLock lg(m_state_lock); - m_state_tracker.clear(); - } - - std::lock_guard lg(m_sleep_lock); - m_cv.notify_all(); -} -void KeyboardInputController::on_key_press(const QKeyEvent& key){ -// cout << "press: " << key.key() << ", native = " << key.nativeVirtualKey() << endl; - -// QKeySequence seq((Qt::Key)key.key()); -// cout << "button: " << seq.toString().toStdString() << endl; - - QtKeyMap::instance().record(key); - { - WriteSpinLock lg(m_state_lock); - m_state_tracker.press(key.nativeVirtualKey()); - } - - std::lock_guard lg(m_sleep_lock); - m_cv.notify_all(); -} -void KeyboardInputController::on_key_release(const QKeyEvent& key){ -// cout << "release: " << key.key() << ", native = " << key.nativeVirtualKey() << endl; - QtKeyMap::instance().record(key); - { - WriteSpinLock lg(m_state_lock); - m_state_tracker.release(key.nativeVirtualKey()); - } - - std::lock_guard lg(m_sleep_lock); - m_cv.notify_all(); -} - - - -void KeyboardInputController::thread_loop(){ - GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(); - - std::unique_ptr last = make_state(); - std::unique_ptr current = make_state(); - - bool last_neutral = true; - WallClock last_press = current_time(); - while (true){ - if (m_stop.load(std::memory_order_acquire)){ - return; - } - -#if 0 - // Not accepting commands. - if (!m_enabled){ - last->clear(); - std::unique_lock lg(m_sleep_lock); - if (m_stop.load(std::memory_order_acquire)){ - return; - } - m_cv.wait(lg); - continue; - } -#endif - - // Get the raw keyboard state. - std::set pressed_native_keys; - WallClock next_wake; - { - ReadSpinLock lg(m_state_lock); - pressed_native_keys = m_state_tracker.get_currently_pressed(); - next_wake = m_state_tracker.next_state_change(); - } - - update_state(*current, pressed_native_keys); - bool neutral = current->is_neutral(); - - - // Send the command. - WallClock now; - do{ - now = current_time(); - if (neutral && last_neutral){ - continue; - } - try{ -// current.print(); - if (*current == *last && last_press + std::chrono::milliseconds(1000) > now){ -// cout << "No state change." << endl; - break; - } - - // If state is neutral, just issue a stop. - if (neutral){ - cancel_all_commands(); - last->clear(); - last_neutral = true; - last_press = now; - break; - } - - // If the new state is different, set next interrupt so the new - // new command can replace the current one without gaps. - if (!last_neutral && current != last){ - replace_on_next_command(); - } - - // Send the command. - send_state(*current); - - std::swap(last, current); - last_neutral = false; - last_press = now; - }catch (Exception& e){ - e.log(global_logger_tagged()); - } - }while (false); - - - // Wait for next event. - std::unique_lock lg(m_sleep_lock); - if (m_stop.load(std::memory_order_acquire)){ - return; - } - - // Nothing held down. - if (last_neutral && next_wake == WallClock::max()){ -// cout << "wait - long" << endl; - m_cv.wait(lg); - }else{ -// cout << "wait - short" << endl; - m_cv.wait_until(lg, std::min(next_wake, now + std::chrono::milliseconds(1000))); - } - } -} - - - - - - - - -} +/* Keyboard Input + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/PanicDump.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/Options/Environment/PerformanceOptions.h" +#include "Controllers/KeyboardInput/GlobalQtKeyMap.h" +#include "KeyboardInput.h" + +namespace PokemonAutomation{ + + + +KeyboardInputController::~KeyboardInputController() = default; +KeyboardInputController::KeyboardInputController(Logger& logger, bool enabled) + : m_logger(logger) + , m_stop(false) +{} + +void KeyboardInputController::start(){ + m_thread = std::thread( + run_with_catch, + "KeyboardInputController::thread_loop()", + [this]{ thread_loop(); } + ); +} +void KeyboardInputController::stop() noexcept{ + bool expected = false; + if (!m_stop.compare_exchange_strong(expected, true)){ + // Already stopped. + return; + } + { + std::lock_guard lg(m_sleep_lock); + m_cv.notify_all(); + } + m_thread.join(); +} + +void KeyboardInputController::clear_state(){ + { + WriteSpinLock lg(m_state_lock); + m_state_tracker.clear(); + } + + std::lock_guard lg(m_sleep_lock); + m_cv.notify_all(); +} +void KeyboardInputController::on_key_press(const QKeyEvent& key){ +// cout << "press: " << key.key() << ", native = " << key.nativeVirtualKey() << endl; + +// QKeySequence seq((Qt::Key)key.key()); +// cout << "button: " << seq.toString().toStdString() << endl; + + QtKeyMap::instance().record(key); + { + WriteSpinLock lg(m_state_lock); + m_state_tracker.press(key.nativeVirtualKey()); + } + + std::lock_guard lg(m_sleep_lock); + m_cv.notify_all(); +} +void KeyboardInputController::on_key_release(const QKeyEvent& key){ +// cout << "release: " << key.key() << ", native = " << key.nativeVirtualKey() << endl; + QtKeyMap::instance().record(key); + { + WriteSpinLock lg(m_state_lock); + m_state_tracker.release(key.nativeVirtualKey()); + } + + std::lock_guard lg(m_sleep_lock); + m_cv.notify_all(); +} + + + +void KeyboardInputController::thread_loop(){ + GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(m_logger); + + std::unique_ptr last = make_state(); + std::unique_ptr current = make_state(); + + bool last_neutral = true; + WallClock last_press = current_time(); + while (true){ + if (m_stop.load(std::memory_order_acquire)){ + return; + } + +#if 0 + // Not accepting commands. + if (!m_enabled){ + last->clear(); + std::unique_lock lg(m_sleep_lock); + if (m_stop.load(std::memory_order_acquire)){ + return; + } + m_cv.wait(lg); + continue; + } +#endif + + // Get the raw keyboard state. + std::set pressed_native_keys; + WallClock next_wake; + { + ReadSpinLock lg(m_state_lock); + pressed_native_keys = m_state_tracker.get_currently_pressed(); + next_wake = m_state_tracker.next_state_change(); + } + + update_state(*current, pressed_native_keys); + bool neutral = current->is_neutral(); + + + // Send the command. + WallClock now; + do{ + now = current_time(); + if (neutral && last_neutral){ + continue; + } + try{ +// current.print(); + if (*current == *last && last_press + std::chrono::milliseconds(1000) > now){ +// cout << "No state change." << endl; + break; + } + + // If state is neutral, just issue a stop. + if (neutral){ + cancel_all_commands(); + last->clear(); + last_neutral = true; + last_press = now; + break; + } + + // If the new state is different, set next interrupt so the new + // new command can replace the current one without gaps. + if (!last_neutral && current != last){ + replace_on_next_command(); + } + + // Send the command. + send_state(*current); + + std::swap(last, current); + last_neutral = false; + last_press = now; + }catch (Exception& e){ + e.log(global_logger_tagged()); + } + }while (false); + + + // Wait for next event. + std::unique_lock lg(m_sleep_lock); + if (m_stop.load(std::memory_order_acquire)){ + return; + } + + // Nothing held down. + if (last_neutral && next_wake == WallClock::max()){ +// cout << "wait - long" << endl; + m_cv.wait(lg); + }else{ +// cout << "wait - short" << endl; + m_cv.wait_until(lg, std::min(next_wake, now + std::chrono::milliseconds(1000))); + } + } +} + + + + + + + + +} diff --git a/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardInput.h b/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardInput.h index c327fe3c82..77aa4e5e88 100644 --- a/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardInput.h +++ b/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardInput.h @@ -1,148 +1,150 @@ -/* Keyboard Input - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_KeyboardInput_H -#define PokemonAutomation_Controllers_KeyboardInput_H - -#include -#include -#include -#include -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Controllers/Controller.h" -#include "Controllers/KeyboardInput/GlobalQtKeyMap.h" -#include "KeyboardStateTracker.h" - -class QKeyEvent; - -namespace PokemonAutomation{ - - -class ControllerSession; - - - - -class ControllerState{ -public: - virtual ~ControllerState() = default; - - virtual void clear() = 0; - - virtual bool operator==(const ControllerState& x) const = 0; - virtual bool operator!=(const ControllerState& x) const{ return !(*this == x); } - - virtual bool is_neutral() const = 0; -}; - - - - -class KeyboardInputController{ -public: - KeyboardInputController(bool enabled); - virtual ~KeyboardInputController(); - - -public: - void clear_state(); - - void on_key_press(const QKeyEvent& key); - void on_key_release(const QKeyEvent& key); - - -protected: - void start(); // Child class must call this at end of constructor. - void stop() noexcept; // Child class must call this at start of destructor. - - virtual std::unique_ptr make_state() const = 0; - virtual void update_state(ControllerState& state, const std::set& pressed_keys) = 0; - virtual void cancel_all_commands() = 0; - virtual void replace_on_next_command() = 0; - virtual void send_state(const ControllerState& state) = 0; - -private: - void thread_loop(); - - -private: - // Controller State - SpinLock m_state_lock; - KeyboardStateTracker m_state_tracker; - - std::atomic m_stop; - - std::mutex m_sleep_lock; - std::condition_variable m_cv; - std::thread m_thread; -}; - - - - -template -class KeyboardManager : public KeyboardInputController{ -public: - KeyboardManager(AbstractController& controller) - : KeyboardInputController(true) - , m_controller(&controller) - {} - void stop() noexcept{ - { - WriteSpinLock lg(m_lock); - if (m_controller == nullptr){ - return; - } - m_controller = nullptr; - } - KeyboardInputController::stop(); - } - - virtual std::unique_ptr make_state() const override{ - return std::make_unique(); - } - virtual void update_state(ControllerState& state, const std::set& pressed_keys) override{ - DeltaType deltas; - const QtKeyMap& qkey_map = QtKeyMap::instance(); - for (uint32_t native_key : pressed_keys){ - std::set qkeys = qkey_map.get_QtKeys(native_key); - for (Qt::Key qkey : qkeys){ - auto iter = m_mapping.find(qkey); - if (iter != m_mapping.end()){ - deltas += iter->second; - break; - } - } - } - deltas.to_state(static_cast(state)); - } - virtual void cancel_all_commands() override{ - WriteSpinLock lg(m_lock); - if (m_controller == nullptr){ - return; - } - m_controller->cancel_all_commands(); - } - virtual void replace_on_next_command() override{ - WriteSpinLock lg(m_lock); - if (m_controller == nullptr){ - return; - } - m_controller->replace_on_next_command(); - } - - -protected: - SpinLock m_lock; - AbstractController* m_controller; - std::map m_mapping; -}; - - - - -} -#endif +/* Keyboard Input + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_KeyboardInput_H +#define PokemonAutomation_Controllers_KeyboardInput_H + +#include +#include +#include +#include +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Controllers/Controller.h" +#include "Controllers/KeyboardInput/GlobalQtKeyMap.h" +#include "KeyboardStateTracker.h" + +class QKeyEvent; + +namespace PokemonAutomation{ + + +class ControllerSession; + + + + +class ControllerState{ +public: + virtual ~ControllerState() = default; + + virtual void clear() = 0; + + virtual bool operator==(const ControllerState& x) const = 0; + virtual bool operator!=(const ControllerState& x) const{ return !(*this == x); } + + virtual bool is_neutral() const = 0; +}; + + + + +class KeyboardInputController{ +public: + KeyboardInputController(Logger& logger, bool enabled); + virtual ~KeyboardInputController(); + + +public: + void clear_state(); + + void on_key_press(const QKeyEvent& key); + void on_key_release(const QKeyEvent& key); + + +protected: + void start(); // Child class must call this at end of constructor. + void stop() noexcept; // Child class must call this at start of destructor. + + virtual std::unique_ptr make_state() const = 0; + virtual void update_state(ControllerState& state, const std::set& pressed_keys) = 0; + virtual void cancel_all_commands() = 0; + virtual void replace_on_next_command() = 0; + virtual void send_state(const ControllerState& state) = 0; + +private: + void thread_loop(); + + +private: + Logger& m_logger; + + // Controller State + SpinLock m_state_lock; + KeyboardStateTracker m_state_tracker; + + std::atomic m_stop; + + std::mutex m_sleep_lock; + std::condition_variable m_cv; + std::thread m_thread; +}; + + + + +template +class KeyboardManager : public KeyboardInputController{ +public: + KeyboardManager(Logger& logger, AbstractController& controller) + : KeyboardInputController(logger, true) + , m_controller(&controller) + {} + void stop() noexcept{ + { + WriteSpinLock lg(m_lock); + if (m_controller == nullptr){ + return; + } + m_controller = nullptr; + } + KeyboardInputController::stop(); + } + + virtual std::unique_ptr make_state() const override{ + return std::make_unique(); + } + virtual void update_state(ControllerState& state, const std::set& pressed_keys) override{ + DeltaType deltas; + const QtKeyMap& qkey_map = QtKeyMap::instance(); + for (uint32_t native_key : pressed_keys){ + std::set qkeys = qkey_map.get_QtKeys(native_key); + for (Qt::Key qkey : qkeys){ + auto iter = m_mapping.find(qkey); + if (iter != m_mapping.end()){ + deltas += iter->second; + break; + } + } + } + deltas.to_state(static_cast(state)); + } + virtual void cancel_all_commands() override{ + WriteSpinLock lg(m_lock); + if (m_controller == nullptr){ + return; + } + m_controller->cancel_all_commands(); + } + virtual void replace_on_next_command() override{ + WriteSpinLock lg(m_lock); + if (m_controller == nullptr){ + return; + } + m_controller->replace_on_next_command(); + } + + +protected: + SpinLock m_lock; + AbstractController* m_controller; + std::map m_mapping; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardStateTracker.cpp b/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardStateTracker.cpp index 552ac3ee53..57bda53d09 100644 --- a/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardStateTracker.cpp +++ b/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardStateTracker.cpp @@ -1,85 +1,85 @@ -/* Keyboard State Tracker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "KeyboardStateTracker.h" - -namespace PokemonAutomation{ - - - -KeyboardStateTracker::KeyboardStateTracker(std::chrono::milliseconds debounce_period) - : m_debounce_period(debounce_period) -{} - - - -void KeyboardStateTracker::clear(){ - m_committed.clear(); - m_pending.clear(); -} -void KeyboardStateTracker::press(uint32_t key){ - WallClock now = current_time(); - m_pending.emplace_back(Event{now, true, key}); - move_old_events_unprotected(now); -} -void KeyboardStateTracker::release(uint32_t key){ - WallClock now = current_time(); - m_pending.emplace_back(Event{now, false, key}); - move_old_events_unprotected(now); -} - - - -WallClock KeyboardStateTracker::next_state_change() const{ - return m_pending.empty() - ? WallClock::max() - : m_pending.begin()->timestamp + m_debounce_period; -} -std::set KeyboardStateTracker::get_currently_pressed(){ - WallClock now = current_time(); - move_old_events_unprotected(now); - - // Copy the current committed set. - std::set ret = m_committed; - - // Now process all the pending ones - ignoring the release events. - for (const Event& event : m_pending){ - if (event.press){ - ret.insert(event.key); - } - } - - return ret; -} -void KeyboardStateTracker::move_old_events_unprotected(WallClock now){ - WallClock threshold = now - m_debounce_period; - while (!m_pending.empty()){ - Event& event = m_pending.front(); - - // Always commit presses. - if (event.press){ - m_committed.insert(event.key); - m_pending.pop_front(); - continue; - } - - // Release is old enough. Commit it. - if (event.timestamp < threshold){ - m_committed.erase(event.key); - m_pending.pop_front(); - continue; - } - - // We've hit an uncommittable release. We're done. - break; - } -} - - - - - -} +/* Keyboard State Tracker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "KeyboardStateTracker.h" + +namespace PokemonAutomation{ + + + +KeyboardStateTracker::KeyboardStateTracker(std::chrono::milliseconds debounce_period) + : m_debounce_period(debounce_period) +{} + + + +void KeyboardStateTracker::clear(){ + m_committed.clear(); + m_pending.clear(); +} +void KeyboardStateTracker::press(uint32_t key){ + WallClock now = current_time(); + m_pending.emplace_back(Event{now, true, key}); + move_old_events_unprotected(now); +} +void KeyboardStateTracker::release(uint32_t key){ + WallClock now = current_time(); + m_pending.emplace_back(Event{now, false, key}); + move_old_events_unprotected(now); +} + + + +WallClock KeyboardStateTracker::next_state_change() const{ + return m_pending.empty() + ? WallClock::max() + : m_pending.begin()->timestamp + m_debounce_period; +} +std::set KeyboardStateTracker::get_currently_pressed(){ + WallClock now = current_time(); + move_old_events_unprotected(now); + + // Copy the current committed set. + std::set ret = m_committed; + + // Now process all the pending ones - ignoring the release events. + for (const Event& event : m_pending){ + if (event.press){ + ret.insert(event.key); + } + } + + return ret; +} +void KeyboardStateTracker::move_old_events_unprotected(WallClock now){ + WallClock threshold = now - m_debounce_period; + while (!m_pending.empty()){ + Event& event = m_pending.front(); + + // Always commit presses. + if (event.press){ + m_committed.insert(event.key); + m_pending.pop_front(); + continue; + } + + // Release is old enough. Commit it. + if (event.timestamp < threshold){ + m_committed.erase(event.key); + m_pending.pop_front(); + continue; + } + + // We've hit an uncommittable release. We're done. + break; + } +} + + + + + +} diff --git a/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardStateTracker.h b/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardStateTracker.h index 698c6c6461..8ffdbd274e 100644 --- a/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardStateTracker.h +++ b/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardStateTracker.h @@ -1,58 +1,58 @@ -/* Keyboard State Tracker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_KeyboardStateTracker_H -#define PokemonAutomation_Controllers_KeyboardStateTracker_H - -#include -#include -#include "Common/Cpp/Time.h" - -namespace PokemonAutomation{ - - - -class KeyboardStateTracker{ -public: - KeyboardStateTracker(std::chrono::milliseconds debounce_period = std::chrono::milliseconds(10)); - - -public: - void clear(); - void press(uint32_t key); - void release(uint32_t key); - - -public: - WallClock next_state_change() const; - std::set get_currently_pressed(); - - -private: - // Move all pending events that are old enough to the committed set. - void move_old_events_unprotected(WallClock now); - - -private: - struct Event{ - WallClock timestamp; - bool press; - uint32_t key; - }; - const std::chrono::milliseconds m_debounce_period; - - std::set m_committed; - std::deque m_pending; -}; - - - - - - - -} -#endif +/* Keyboard State Tracker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_KeyboardStateTracker_H +#define PokemonAutomation_Controllers_KeyboardStateTracker_H + +#include +#include +#include "Common/Cpp/Time.h" + +namespace PokemonAutomation{ + + + +class KeyboardStateTracker{ +public: + KeyboardStateTracker(std::chrono::milliseconds debounce_period = std::chrono::milliseconds(10)); + + +public: + void clear(); + void press(uint32_t key); + void release(uint32_t key); + + +public: + WallClock next_state_change() const; + std::set get_currently_pressed(); + + +private: + // Move all pending events that are old enough to the committed set. + void move_old_events_unprotected(WallClock now); + + +private: + struct Event{ + WallClock timestamp; + bool press; + uint32_t key; + }; + const std::chrono::milliseconds m_debounce_period; + + std::set m_committed; + std::deque m_pending; +}; + + + + + + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/NullController.cpp b/SerialPrograms/Source/Controllers/NullController.cpp index 03c7fa7483..570e305bc5 100644 --- a/SerialPrograms/Source/Controllers/NullController.cpp +++ b/SerialPrograms/Source/Controllers/NullController.cpp @@ -1,51 +1,51 @@ -/* Null Controller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Json/JsonValue.h" -#include "ControllerConnection.h" -#include "ControllerSelectorWidget.h" -#include "NullController.h" - -namespace PokemonAutomation{ - - -template class InterfaceType_t; - - -bool NullControllerDescriptor::operator==(const ControllerDescriptor& x) const{ - return typeid(*this) == typeid(x); -} -std::string NullControllerDescriptor::display_name() const{ - return "(none)"; -} -void NullControllerDescriptor::load_json(const JsonValue& json){ - -} -JsonValue NullControllerDescriptor::to_json() const{ - return JsonValue(); -} -std::unique_ptr NullControllerDescriptor::open_connection( - Logger& logger, - std::optional change_controller -) const{ - return nullptr; -} -std::unique_ptr NullControllerDescriptor::make_controller( - Logger& logger, - ControllerConnection& connection, - ControllerType controller_type -) const{ - return nullptr; -} -QWidget* NullControllerDescriptor::make_selector_QtWidget(ControllerSelectorWidget& parent) const{ - return new QWidget(&parent); -} - - - - -} +/* Null Controller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "ControllerConnection.h" +#include "ControllerSelectorWidget.h" +#include "NullController.h" + +namespace PokemonAutomation{ + + +template class InterfaceType_t; + + +bool NullControllerDescriptor::operator==(const ControllerDescriptor& x) const{ + return typeid(*this) == typeid(x); +} +std::string NullControllerDescriptor::display_name() const{ + return "(none)"; +} +void NullControllerDescriptor::load_json(const JsonValue& json){ + +} +JsonValue NullControllerDescriptor::to_json() const{ + return JsonValue(); +} +std::unique_ptr NullControllerDescriptor::open_connection( + Logger& logger, + std::optional change_controller +) const{ + return nullptr; +} +std::unique_ptr NullControllerDescriptor::make_controller( + Logger& logger, + ControllerConnection& connection, + ControllerType controller_type +) const{ + return nullptr; +} +QWidget* NullControllerDescriptor::make_selector_QtWidget(ControllerSelectorWidget& parent) const{ + return new QWidget(&parent); +} + + + + +} diff --git a/SerialPrograms/Source/Controllers/NullController.h b/SerialPrograms/Source/Controllers/NullController.h index 5d409dd473..7e68ae4d2a 100644 --- a/SerialPrograms/Source/Controllers/NullController.h +++ b/SerialPrograms/Source/Controllers/NullController.h @@ -1,45 +1,45 @@ -/* Null Controller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_NullController_H -#define PokemonAutomation_Controllers_NullController_H - -#include "ControllerDescriptor.h" - -namespace PokemonAutomation{ - - - -class NullControllerDescriptor : public ControllerDescriptor{ -public: - static constexpr ControllerInterface INTERFACE_NAME = ControllerInterface::None; - -public: - NullControllerDescriptor() - : ControllerDescriptor(ControllerInterface::None) - {} - virtual bool operator==(const ControllerDescriptor& x) const override; - virtual std::string display_name() const override; - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual std::unique_ptr open_connection( - Logger& logger, - std::optional change_controller - ) const override; - virtual std::unique_ptr make_controller( - Logger& logger, - ControllerConnection& connection, - ControllerType controller_type - ) const override; - - virtual QWidget* make_selector_QtWidget(ControllerSelectorWidget& parent) const override; -}; - - - -} -#endif +/* Null Controller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_NullController_H +#define PokemonAutomation_Controllers_NullController_H + +#include "ControllerDescriptor.h" + +namespace PokemonAutomation{ + + + +class NullControllerDescriptor : public ControllerDescriptor{ +public: + static constexpr ControllerInterface INTERFACE_NAME = ControllerInterface::None; + +public: + NullControllerDescriptor() + : ControllerDescriptor(ControllerInterface::None) + {} + virtual bool operator==(const ControllerDescriptor& x) const override; + virtual std::string display_name() const override; + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual std::unique_ptr open_connection( + Logger& logger, + std::optional change_controller + ) const override; + virtual std::unique_ptr make_controller( + Logger& logger, + ControllerConnection& connection, + ControllerType controller_type + ) const override; + + virtual QWidget* make_selector_QtWidget(ControllerSelectorWidget& parent) const override; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase.cpp b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase.cpp index 9f37216859..002e15cede 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase.cpp +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase.cpp @@ -1,178 +1,169 @@ -/* Serial Port (PABotBase) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h" -#include "SerialPABotBase.h" - -namespace PokemonAutomation{ -namespace SerialPABotBase{ - - - - -// Defaults -const ControllerFeatures OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS{ - ControllerFeature::TickPrecise, - ControllerFeature::NintendoSwitch_ProController, -}; - - - - -std::string program_name(uint8_t id){ - switch (id){ - case PABB_PID_UNSPECIFIED: return "Microcontroller Program"; - - // Old (fat) PABotBase with scheduler. - case PABB_PID_PABOTBASE_12KB: return "PABotBase-AVR8-12KB"; - case PABB_PID_PABOTBASE_31KB: return "PABotBase-AVR8-31KB"; - - // New (slim) PABotBase. - case PABB_PID_PABOTBASE_ArduinoUnoR3: return "PABotBase-UnoR3"; - case PABB_PID_PABOTBASE_ArduinoLeonardo: return "PABotBase-Leonardo"; - case PABB_PID_PABOTBASE_ProMicro: return "PABotBase-ProMicro"; - case PABB_PID_PABOTBASE_Teensy2: return "PABotBase-Teensy2.0"; - case PABB_PID_PABOTBASE_TeensyPP2: return "PABotBase-Teensy++2.0"; - - case PABB_PID_PABOTBASE_CH552: return "PABotBase-CH552"; - - case PABB_PID_PABOTBASE_ESP32: return "PABotBase-ESP32"; - case PABB_PID_PABOTBASE_ESP32S3: return "PABotBase-ESP32-S3"; - - default: return "Unknown ID"; - } -} -ControllerType id_to_controller_type(uint32_t id){ - switch (id){ - case PABB_CID_NONE: - return ControllerType::None; - case PABB_CID_NINTENDO_SWITCH_WIRED_PRO_CONTROLLER: - return ControllerType::NintendoSwitch_WiredProController; - case PABB_CID_NINTENDO_SWITCH_WIRELESS_PRO_CONTROLLER: - return ControllerType::NintendoSwitch_WirelessProController; - case PABB_CID_NINTENDO_SWITCH_LEFT_JOYCON: - return ControllerType::NintendoSwitch_LeftJoycon; - case PABB_CID_NINTENDO_SWITCH_RIGHT_JOYCON: - return ControllerType::NintendoSwitch_RightJoycon; - } - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Invalid Controller ID: " + std::to_string(id) - ); -} -uint32_t controller_type_to_id(ControllerType controller_type){ - switch (controller_type){ - case ControllerType::None: - return PABB_CID_NONE; - case ControllerType::NintendoSwitch_WiredProController: - return PABB_CID_NINTENDO_SWITCH_WIRED_PRO_CONTROLLER; - case ControllerType::NintendoSwitch_WirelessProController: - return PABB_CID_NINTENDO_SWITCH_WIRELESS_PRO_CONTROLLER; - case ControllerType::NintendoSwitch_LeftJoycon: - return PABB_CID_NINTENDO_SWITCH_LEFT_JOYCON; - case ControllerType::NintendoSwitch_RightJoycon: - return PABB_CID_NINTENDO_SWITCH_RIGHT_JOYCON; - } - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Invalid Controller Enum: " + std::to_string((int)controller_type) - ); -} - - - -const std::map< - uint32_t, // Protocol Version - std::map< - uint32_t, // Program ID - std::map - > -> SUPPORTED_VERSIONS{ - {2025061202, { - {PABB_PID_PABOTBASE_ESP32, { - {ControllerType::NintendoSwitch_WirelessProController, { - ControllerFeature::TickPrecise, - ControllerFeature::TimingFlexibleMilliseconds, - ControllerFeature::NintendoSwitch_ProController, - }}, - {ControllerType::NintendoSwitch_LeftJoycon, { - ControllerFeature::TickPrecise, - ControllerFeature::TimingFlexibleMilliseconds, - ControllerFeature::NintendoSwitch_LeftJoycon, - }}, - {ControllerType::NintendoSwitch_RightJoycon, { - ControllerFeature::TickPrecise, - ControllerFeature::TimingFlexibleMilliseconds, - ControllerFeature::NintendoSwitch_RightJoycon, - }}, - }}, - }}, - {2025061303, { - {PABB_PID_PABOTBASE_ESP32S3, { - {ControllerType::NintendoSwitch_WiredProController, { - ControllerFeature::TickPrecise, - ControllerFeature::TimingFlexibleMilliseconds, - ControllerFeature::NintendoSwitch_ProController, - ControllerFeature::NintendoSwitch_DateSkip, - }}, - }}, - }}, - {2025061403, { - {PABB_PID_PABOTBASE_ArduinoUnoR3, { - {ControllerType::NintendoSwitch_WiredProController, { - ControllerFeature::TickPrecise, - ControllerFeature::TimingFlexibleMilliseconds, - ControllerFeature::NintendoSwitch_ProController, - ControllerFeature::NintendoSwitch_DateSkip, - }}, - }}, - {PABB_PID_PABOTBASE_ArduinoLeonardo, { - {ControllerType::NintendoSwitch_WiredProController, { - ControllerFeature::TickPrecise, - ControllerFeature::TimingFlexibleMilliseconds, - ControllerFeature::NintendoSwitch_ProController, - ControllerFeature::NintendoSwitch_DateSkip, - }}, - }}, - {PABB_PID_PABOTBASE_ProMicro, { - {ControllerType::NintendoSwitch_WiredProController, { - ControllerFeature::TickPrecise, - ControllerFeature::TimingFlexibleMilliseconds, - ControllerFeature::NintendoSwitch_ProController, - ControllerFeature::NintendoSwitch_DateSkip, - }}, - }}, - {PABB_PID_PABOTBASE_Teensy2, { - {ControllerType::NintendoSwitch_WiredProController, { - ControllerFeature::TickPrecise, - ControllerFeature::TimingFlexibleMilliseconds, - ControllerFeature::NintendoSwitch_ProController, - ControllerFeature::NintendoSwitch_DateSkip, - }}, - }}, - {PABB_PID_PABOTBASE_TeensyPP2, { - {ControllerType::NintendoSwitch_WiredProController, { - ControllerFeature::TickPrecise, - ControllerFeature::TimingFlexibleMilliseconds, - ControllerFeature::NintendoSwitch_ProController, - ControllerFeature::NintendoSwitch_DateSkip, - }}, - }}, - }}, -}; - - - - - - - - - - -} -} +/* Serial Port (PABotBase) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h" +#include "SerialPABotBase.h" + +namespace PokemonAutomation{ +namespace SerialPABotBase{ + + + + +// Defaults +const ControllerFeatures OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS{ + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_ProController, +}; + + + + +std::string program_name(uint8_t id){ + switch (id){ + case PABB_PID_UNSPECIFIED: return "Microcontroller Program"; + + // Old (fat) PABotBase with scheduler. + case PABB_PID_PABOTBASE_12KB: return "PABotBase-AVR8-12KB"; + case PABB_PID_PABOTBASE_31KB: return "PABotBase-AVR8-31KB"; + + // New (slim) PABotBase. + case PABB_PID_PABOTBASE_ArduinoUnoR3: return "PABotBase-UnoR3"; + case PABB_PID_PABOTBASE_ArduinoLeonardo: return "PABotBase-Leonardo"; + case PABB_PID_PABOTBASE_ProMicro: return "PABotBase-ProMicro"; + case PABB_PID_PABOTBASE_Teensy2: return "PABotBase-Teensy2.0"; + case PABB_PID_PABOTBASE_TeensyPP2: return "PABotBase-Teensy++2.0"; + + case PABB_PID_PABOTBASE_CH552: return "PABotBase-CH552"; + + case PABB_PID_PABOTBASE_ESP32: return "PABotBase-ESP32"; + case PABB_PID_PABOTBASE_ESP32S3: return "PABotBase-ESP32-S3"; + + default: return "Unknown ID"; + } +} +ControllerType id_to_controller_type(uint32_t id){ + switch (id){ + case PABB_CID_NONE: + return ControllerType::None; + case PABB_CID_NINTENDO_SWITCH_WIRED_PRO_CONTROLLER: + return ControllerType::NintendoSwitch_WiredProController; + case PABB_CID_NINTENDO_SWITCH_WIRELESS_PRO_CONTROLLER: + return ControllerType::NintendoSwitch_WirelessProController; + case PABB_CID_NINTENDO_SWITCH_LEFT_JOYCON: + return ControllerType::NintendoSwitch_LeftJoycon; + case PABB_CID_NINTENDO_SWITCH_RIGHT_JOYCON: + return ControllerType::NintendoSwitch_RightJoycon; + } + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Invalid Controller ID: " + std::to_string(id) + ); +} +uint32_t controller_type_to_id(ControllerType controller_type){ + switch (controller_type){ + case ControllerType::None: + return PABB_CID_NONE; + case ControllerType::NintendoSwitch_WiredProController: + return PABB_CID_NINTENDO_SWITCH_WIRED_PRO_CONTROLLER; + case ControllerType::NintendoSwitch_WirelessProController: + return PABB_CID_NINTENDO_SWITCH_WIRELESS_PRO_CONTROLLER; + case ControllerType::NintendoSwitch_LeftJoycon: + return PABB_CID_NINTENDO_SWITCH_LEFT_JOYCON; + case ControllerType::NintendoSwitch_RightJoycon: + return PABB_CID_NINTENDO_SWITCH_RIGHT_JOYCON; + } + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Invalid Controller Enum: " + std::to_string((int)controller_type) + ); +} + + + +const std::map< + uint32_t, // Protocol Version + std::map< + uint32_t, // Program ID + std::map + > +> SUPPORTED_VERSIONS{ + {2025061208, { + {PABB_PID_PABOTBASE_ESP32, { + {ControllerType::NintendoSwitch_WirelessProController, { + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_ProController, + }}, + {ControllerType::NintendoSwitch_LeftJoycon, { + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_LeftJoycon, + }}, + {ControllerType::NintendoSwitch_RightJoycon, { + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_RightJoycon, + }}, + }}, + }}, + {2025061307, { + {PABB_PID_PABOTBASE_ESP32S3, { + {ControllerType::NintendoSwitch_WiredProController, { + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_ProController, + ControllerFeature::NintendoSwitch_DateSkip, + }}, + }}, + }}, + {2025061406, { + {PABB_PID_PABOTBASE_ArduinoUnoR3, { + {ControllerType::NintendoSwitch_WiredProController, { + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_ProController, + ControllerFeature::NintendoSwitch_DateSkip, + }}, + }}, + {PABB_PID_PABOTBASE_ArduinoLeonardo, { + {ControllerType::NintendoSwitch_WiredProController, { + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_ProController, + ControllerFeature::NintendoSwitch_DateSkip, + }}, + }}, + {PABB_PID_PABOTBASE_ProMicro, { + {ControllerType::NintendoSwitch_WiredProController, { + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_ProController, + ControllerFeature::NintendoSwitch_DateSkip, + }}, + }}, + {PABB_PID_PABOTBASE_Teensy2, { + {ControllerType::NintendoSwitch_WiredProController, { + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_ProController, + ControllerFeature::NintendoSwitch_DateSkip, + }}, + }}, + {PABB_PID_PABOTBASE_TeensyPP2, { + {ControllerType::NintendoSwitch_WiredProController, { + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_ProController, + ControllerFeature::NintendoSwitch_DateSkip, + }}, + }}, + }}, +}; + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase.h b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase.h index 0e789cb3c8..e4aa6abf5a 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase.h +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase.h @@ -1,44 +1,44 @@ -/* Serial Port (PABotBase) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_SerialPABotBase_H -#define PokemonAutomation_Controllers_SerialPABotBase_H - -#include -#include -#include -#include "Controllers/ControllerCapability.h" - -namespace PokemonAutomation{ -namespace SerialPABotBase{ - - - -// Defaults -extern const ControllerFeatures OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS; - - - -std::string program_name(uint8_t id); -ControllerType id_to_controller_type(uint32_t id); -uint32_t controller_type_to_id(ControllerType controller_type); - - - -extern const std::map< - uint32_t, // Protocol Version - std::map< - uint32_t, // Program ID - std::map - > -> SUPPORTED_VERSIONS; - - - - -} -} -#endif +/* Serial Port (PABotBase) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_SerialPABotBase_H +#define PokemonAutomation_Controllers_SerialPABotBase_H + +#include +#include +#include +#include "Controllers/ControllerCapability.h" + +namespace PokemonAutomation{ +namespace SerialPABotBase{ + + + +// Defaults +extern const ControllerFeatures OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS; + + + +std::string program_name(uint8_t id); +ControllerType id_to_controller_type(uint32_t id); +uint32_t controller_type_to_id(ControllerType controller_type); + + + +extern const std::map< + uint32_t, // Protocol Version + std::map< + uint32_t, // Program ID + std::map + > +> SUPPORTED_VERSIONS; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Connection.cpp b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Connection.cpp index a6623bc29b..f199b69646 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Connection.cpp +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Connection.cpp @@ -1,304 +1,304 @@ -/* Serial Port (PABotBase) Connection - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/PanicDump.h" -#include "ClientSource/Libraries/MessageConverter.h" -#include "ClientSource/Connection/SerialConnection.h" -#include "ClientSource/Connection/PABotBase.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" -#include "Controllers/ControllerTypeStrings.h" -#include "Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.h" -#include "SerialPABotBase.h" -#include "SerialPABotBase_PostConnectActions.h" -#include "SerialPABotBase_Connection.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace SerialPABotBase{ - - - - - -SerialPABotBase_Connection::SerialPABotBase_Connection( - Logger& logger, - const QSerialPortInfo* port, - std::optional change_controller -) - : m_logger(logger, GlobalSettings::instance().LOG_EVERYTHING) -{ - set_status_line0("Not Connected", COLOR_RED); - - // No port selected. - if (port == nullptr || port->isNull()){ - return; - } - - // Prolific is banned. - if (port->description().indexOf("Prolific") != -1){ - QMessageBox box; - box.critical( - nullptr, - "Error", - "Cannot select Prolific controller.

" - "Prolific controllers do not work for Arduino and similar microcontrollers.
" - "You were warned of this in the setup instructions. Please buy a CP210x controller instead." - ); - std::string text = "Cannot connect to Prolific controller."; - m_logger.log(text, COLOR_RED); - set_status_line0(text, COLOR_RED); - return; - } - - m_device_name = port->portName().toStdString(); - std::string error; - try{ - set_status_line0("Connecting...", COLOR_DARKGREEN); - std::unique_ptr connection(new SerialConnection(port->systemLocation().toStdString(), PABB_BAUD_RATE)); - m_botbase.reset(new PABotBase(m_logger, std::move(connection), nullptr)); - }catch (const ConnectionException& e){ - error = e.message(); - }catch (const SerialProtocolException& e){ - error = e.message(); - }catch (const ProgramCancelledException& e){ - error = e.message(); - } - if (!error.empty()){ - set_status_line0("Unable to open port.", COLOR_RED); - return; - } - - m_status_thread = std::thread( - run_with_catch, - "SerialPABotBase_Connection::thread_body()", - [=, this]{ thread_body(change_controller); } - ); -} -SerialPABotBase_Connection::~SerialPABotBase_Connection(){ - m_ready.store(false, std::memory_order_release); -// signal_pre_not_ready(); - if (m_botbase == nullptr){ - return; - } - m_botbase->stop(); - { - std::lock_guard lg(m_lock); - m_cv.notify_all(); - } - if (m_status_thread.joinable()){ - m_status_thread.join(); - } - m_botbase.reset(); -} - - - -BotBaseController* SerialPABotBase_Connection::botbase(){ - BotBaseController* ret = m_botbase.get(); - if (ret == nullptr){ - m_logger.log("SerialPABotBase_Connection::botbase() called with null botbase...", COLOR_RED); - } - return ret; -} - - - -ControllerModeStatus SerialPABotBase_Connection::controller_mode_status() const{ - std::lock_guard lg(m_lock); - return m_mode_status; -} - - - -const std::map>& -SerialPABotBase_Connection::get_programs_for_protocol(uint32_t protocol){ - // (protocol_requested / 100) == (protocol_device / 100) - // (protocol_requested % 100) <= (protocol_device % 100) - auto iter = SUPPORTED_VERSIONS.upper_bound(protocol); - if (iter == SUPPORTED_VERSIONS.begin()){ - throw SerialProtocolException( - m_logger, PA_CURRENT_FUNCTION, - "Incompatible protocol. Device: " + std::to_string(protocol) + "
" - "Please flash the .hex/.bin that came with this version of the program." - ); - } - --iter; - if (iter->first < protocol / 100 * 100){ - throw SerialProtocolException( - m_logger, PA_CURRENT_FUNCTION, - "Incompatible protocol. Device: " + std::to_string(protocol) + "
" - "Please flash the .hex/.bin that came with this version of the program." - ); - } - - return iter->second; -} - -const std::map& -SerialPABotBase_Connection::get_controllers_for_program( - const std::map>& available_programs, - uint32_t program_id -){ - auto iter = available_programs.find(program_id); - if (iter == available_programs.end()){ - throw SerialProtocolException( - m_logger, PA_CURRENT_FUNCTION, - "Unrecognized Program ID: " + std::to_string(program_id) + "
" - "Please install the firmware that came with this version of the program." - ); - } - return iter->second; -} - -void SerialPABotBase_Connection::process_queue_size(){ - m_logger.log("Requesting queue size..."); - uint8_t queue_size = device_queue_size(*m_botbase); - m_logger.Logger::log("Requesting queue size... Queue Size = " + std::to_string(queue_size)); - - // For now we don't need to use that much queue size. - queue_size = std::min(queue_size, 32); - - m_logger.Logger::log("Setting queue size to: " + std::to_string(queue_size)); - m_botbase->set_queue_limit(queue_size); -} -ControllerType SerialPABotBase_Connection::get_controller_type( - const std::map& available_controllers -){ - m_logger.log("Reading Controller Mode..."); - ControllerType current_controller = ControllerType::None; - if (available_controllers.size() == 1){ - current_controller = available_controllers.begin()->first; - }else if (available_controllers.size() > 1){ - uint32_t type_id = read_controller_mode(*m_botbase); - current_controller = id_to_controller_type(type_id); - } - m_logger.Logger::log("Reading Controller Mode... Mode = " + CONTROLLER_TYPE_STRINGS.get_string(current_controller)); - return current_controller; -} - - - -ControllerModeStatus SerialPABotBase_Connection::read_device_specs( - std::optional change_controller -){ - // Protocol - { - m_logger.Logger::log("Checking Protocol Version..."); - m_protocol = protocol_version(*m_botbase); - m_logger.Logger::log("Checking Protocol Version... Protocol = " + std::to_string(m_protocol)); - } - const std::map>& PROGRAMS = - get_programs_for_protocol(m_protocol); - - - // Program ID - { - m_logger.Logger::log("Checking Program ID..."); - m_program_id = program_id(*m_botbase); - m_logger.Logger::log("Checking Program ID... Program ID = " + std::to_string(m_program_id)); - } - const std::map& CONTROLLERS = - get_controllers_for_program(PROGRAMS, m_program_id); - - // Firmware Version - { - m_logger.Logger::log("Checking Firmware Version..."); - m_version = program_version(*m_botbase); - m_logger.Logger::log("Checking Firmware Version... Version = " + std::to_string(m_version)); - } - - // Queue Size - process_queue_size(); - - // Controller Type - ControllerType current_controller = get_controller_type(CONTROLLERS); - - // Run any post-connection actions specific to this program. - ControllerModeStatus ret{current_controller, CONTROLLERS}; - run_post_connect_actions( - ret, - m_program_id, m_device_name, - *m_botbase, - change_controller - ); - return ret; -} - - - -void SerialPABotBase_Connection::thread_body( - std::optional change_controller -){ - using namespace PokemonAutomation; - - m_botbase->set_sniffer(&m_logger); - - // Connect - { - std::string error; - try{ - m_botbase->connect(); - }catch (InvalidConnectionStateException&){ - m_botbase->stop(); - set_status_line0(""); - return; - }catch (SerialProtocolException& e){ - error = e.message(); - }catch (ConnectionException& e){ - error = e.message(); - } - if (!error.empty()){ - m_botbase->stop(); - set_status_line0(error, COLOR_RED); - return; - } - } - - // Check protocol and version. - { - ControllerModeStatus mode_status; - std::string error; - try{ - mode_status = read_device_specs(change_controller); - std::lock_guard lg(m_lock); - m_mode_status = mode_status; - - // Stop pending commands. - m_botbase->stop_all_commands(); - }catch (InvalidConnectionStateException&){ - return; - }catch (SerialProtocolException& e){ - error = e.message(); - }catch (ConnectionException& e){ - error = e.message(); - } - if (error.empty()){ -// std::string text = "Program: " + program_name(m_program_id) + " (" + std::to_string(m_version) + ")"; - std::string text = program_name(m_program_id) + " (" + std::to_string(m_version) + ")"; - set_status_line0(text, theme_friendly_darkblue()); - declare_ready(mode_status); - }else{ - m_ready.store(false, std::memory_order_relaxed); - set_status_line0(error, COLOR_RED); -// signal_pre_not_ready(); - m_botbase->stop(); - return; - } - } -} - - - -} -} +/* Serial Port (PABotBase) Connection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/PanicDump.h" +#include "ClientSource/Libraries/MessageConverter.h" +#include "ClientSource/Connection/SerialConnection.h" +#include "ClientSource/Connection/PABotBase.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" +#include "Controllers/ControllerTypeStrings.h" +#include "Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.h" +#include "SerialPABotBase.h" +#include "SerialPABotBase_PostConnectActions.h" +#include "SerialPABotBase_Connection.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace SerialPABotBase{ + + + + + +SerialPABotBase_Connection::SerialPABotBase_Connection( + Logger& logger, + const QSerialPortInfo* port, + std::optional change_controller +) + : m_logger(logger, GlobalSettings::instance().LOG_EVERYTHING) +{ + set_status_line0("Not Connected", COLOR_RED); + + // No port selected. + if (port == nullptr || port->isNull()){ + return; + } + + // Prolific is banned. + if (port->description().indexOf("Prolific") != -1){ + QMessageBox box; + box.critical( + nullptr, + "Error", + "Cannot select Prolific controller.

" + "Prolific controllers do not work for Arduino and similar microcontrollers.
" + "You were warned of this in the setup instructions. Please buy a CP210x controller instead." + ); + std::string text = "Cannot connect to Prolific controller."; + m_logger.log(text, COLOR_RED); + set_status_line0(text, COLOR_RED); + return; + } + + m_device_name = port->portName().toStdString(); + std::string error; + try{ + set_status_line0("Connecting...", COLOR_DARKGREEN); + std::unique_ptr connection(new SerialConnection(port->systemLocation().toStdString(), PABB_BAUD_RATE)); + m_botbase.reset(new PABotBase(m_logger, std::move(connection), nullptr)); + }catch (const ConnectionException& e){ + error = e.message(); + }catch (const SerialProtocolException& e){ + error = e.message(); + }catch (const ProgramCancelledException& e){ + error = e.message(); + } + if (!error.empty()){ + set_status_line0("Unable to open port.", COLOR_RED); + return; + } + + m_status_thread = std::thread( + run_with_catch, + "SerialPABotBase_Connection::thread_body()", + [=, this]{ thread_body(change_controller); } + ); +} +SerialPABotBase_Connection::~SerialPABotBase_Connection(){ + m_ready.store(false, std::memory_order_release); +// signal_pre_not_ready(); + if (m_botbase == nullptr){ + return; + } + m_botbase->stop(); + { + std::lock_guard lg(m_lock); + m_cv.notify_all(); + } + if (m_status_thread.joinable()){ + m_status_thread.join(); + } + m_botbase.reset(); +} + + + +BotBaseController* SerialPABotBase_Connection::botbase(){ + BotBaseController* ret = m_botbase.get(); + if (ret == nullptr){ + m_logger.log("SerialPABotBase_Connection::botbase() called with null botbase...", COLOR_RED); + } + return ret; +} + + + +ControllerModeStatus SerialPABotBase_Connection::controller_mode_status() const{ + std::lock_guard lg(m_lock); + return m_mode_status; +} + + + +const std::map>& +SerialPABotBase_Connection::get_programs_for_protocol(uint32_t protocol){ + // (protocol_requested / 100) == (protocol_device / 100) + // (protocol_requested % 100) <= (protocol_device % 100) + auto iter = SUPPORTED_VERSIONS.upper_bound(protocol); + if (iter == SUPPORTED_VERSIONS.begin()){ + throw SerialProtocolException( + m_logger, PA_CURRENT_FUNCTION, + "Incompatible protocol. Device: " + std::to_string(protocol) + "
" + "Please flash the .hex/.bin that came with this version of the program." + ); + } + --iter; + if (iter->first < protocol / 100 * 100){ + throw SerialProtocolException( + m_logger, PA_CURRENT_FUNCTION, + "Incompatible protocol. Device: " + std::to_string(protocol) + "
" + "Please flash the .hex/.bin that came with this version of the program." + ); + } + + return iter->second; +} + +const std::map& +SerialPABotBase_Connection::get_controllers_for_program( + const std::map>& available_programs, + uint32_t program_id +){ + auto iter = available_programs.find(program_id); + if (iter == available_programs.end()){ + throw SerialProtocolException( + m_logger, PA_CURRENT_FUNCTION, + "Unrecognized Program ID: " + std::to_string(program_id) + "
" + "Please install the firmware that came with this version of the program." + ); + } + return iter->second; +} + +void SerialPABotBase_Connection::process_queue_size(){ + m_logger.log("Requesting queue size..."); + uint8_t queue_size = device_queue_size(*m_botbase); + m_logger.Logger::log("Requesting queue size... Queue Size = " + std::to_string(queue_size)); + + // For now we don't need to use that much queue size. + queue_size = std::min(queue_size, 32); + + m_logger.Logger::log("Setting queue size to: " + std::to_string(queue_size)); + m_botbase->set_queue_limit(queue_size); +} +ControllerType SerialPABotBase_Connection::get_controller_type( + const std::map& available_controllers +){ + m_logger.log("Reading Controller Mode..."); + ControllerType current_controller = ControllerType::None; + if (available_controllers.size() == 1){ + current_controller = available_controllers.begin()->first; + }else if (available_controllers.size() > 1){ + uint32_t type_id = read_controller_mode(*m_botbase); + current_controller = id_to_controller_type(type_id); + } + m_logger.Logger::log("Reading Controller Mode... Mode = " + CONTROLLER_TYPE_STRINGS.get_string(current_controller)); + return current_controller; +} + + + +ControllerModeStatus SerialPABotBase_Connection::read_device_specs( + std::optional change_controller +){ + // Protocol + { + m_logger.Logger::log("Checking Protocol Version..."); + m_protocol = protocol_version(*m_botbase); + m_logger.Logger::log("Checking Protocol Version... Protocol = " + std::to_string(m_protocol)); + } + const std::map>& PROGRAMS = + get_programs_for_protocol(m_protocol); + + + // Program ID + { + m_logger.Logger::log("Checking Program ID..."); + m_program_id = program_id(*m_botbase); + m_logger.Logger::log("Checking Program ID... Program ID = " + std::to_string(m_program_id)); + } + const std::map& CONTROLLERS = + get_controllers_for_program(PROGRAMS, m_program_id); + + // Firmware Version + { + m_logger.Logger::log("Checking Firmware Version..."); + m_version = program_version(*m_botbase); + m_logger.Logger::log("Checking Firmware Version... Version = " + std::to_string(m_version)); + } + + // Queue Size + process_queue_size(); + + // Controller Type + ControllerType current_controller = get_controller_type(CONTROLLERS); + + // Run any post-connection actions specific to this program. + ControllerModeStatus ret{current_controller, CONTROLLERS}; + run_post_connect_actions( + ret, + m_program_id, m_device_name, + *m_botbase, + change_controller + ); + return ret; +} + + + +void SerialPABotBase_Connection::thread_body( + std::optional change_controller +){ + using namespace PokemonAutomation; + + m_botbase->set_sniffer(&m_logger); + + // Connect + { + std::string error; + try{ + m_botbase->connect(); + }catch (InvalidConnectionStateException&){ + m_botbase->stop(); + set_status_line0(""); + return; + }catch (SerialProtocolException& e){ + error = e.message(); + }catch (ConnectionException& e){ + error = e.message(); + } + if (!error.empty()){ + m_botbase->stop(); + set_status_line0(error, COLOR_RED); + return; + } + } + + // Check protocol and version. + { + ControllerModeStatus mode_status; + std::string error; + try{ + mode_status = read_device_specs(change_controller); + std::lock_guard lg(m_lock); + m_mode_status = mode_status; + + // Stop pending commands. + m_botbase->stop_all_commands(); + }catch (InvalidConnectionStateException&){ + return; + }catch (SerialProtocolException& e){ + error = e.message(); + }catch (ConnectionException& e){ + error = e.message(); + } + if (error.empty()){ +// std::string text = "Program: " + program_name(m_program_id) + " (" + std::to_string(m_version) + ")"; + std::string text = program_name(m_program_id) + " (" + std::to_string(m_version) + ")"; + set_status_line0(text, theme_friendly_darkblue()); + declare_ready(mode_status); + }else{ + m_ready.store(false, std::memory_order_relaxed); + set_status_line0(error, COLOR_RED); +// signal_pre_not_ready(); + m_botbase->stop(); + return; + } + } +} + + + +} +} diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Connection.h b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Connection.h index 71b7dbbfc4..d868014235 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Connection.h +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Connection.h @@ -1,89 +1,89 @@ -/* Serial Port (PABotBase) Connection - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_SerialPABotBase_Connection_H -#define PokemonAutomation_Controllers_SerialPABotBase_Connection_H - -#include -#include -#include -#include -#include "ClientSource/Connection/BotBase.h" -#include "ClientSource/Connection/MessageLogger.h" -#include "Controllers/ControllerConnection.h" - -class QSerialPortInfo; - -namespace PokemonAutomation{ - class PABotBase; -namespace SerialPABotBase{ - - -class SerialPABotBase_Connection : public ControllerConnection{ -public: - SerialPABotBase_Connection( - Logger& logger, - const QSerialPortInfo* port, - std::optional change_controller - ); - ~SerialPABotBase_Connection(); - - -public: -// uint8_t program_id() const{ -// return m_program_id; -// } - BotBaseController* botbase(); - -public: - virtual ControllerModeStatus controller_mode_status() const override; - - -private: - const std::map>& - get_programs_for_protocol(uint32_t protocol); - - const std::map& - get_controllers_for_program( - const std::map>& available_programs, - uint32_t program_id - ); - - void process_queue_size(); - ControllerType get_controller_type( - const std::map& available_controllers - ); - - ControllerModeStatus read_device_specs( - std::optional change_controller - ); - - void thread_body( - std::optional change_controller - ); - - -private: - SerialLogger m_logger; - std::string m_device_name; - - uint32_t m_protocol = 0; - uint32_t m_version = 0; - uint8_t m_program_id = 0; - ControllerModeStatus m_mode_status; - - std::thread m_status_thread; - std::unique_ptr m_botbase; - mutable std::mutex m_lock; - std::mutex m_sleep_lock; - std::condition_variable m_cv; -}; - - - -} -} -#endif +/* Serial Port (PABotBase) Connection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_SerialPABotBase_Connection_H +#define PokemonAutomation_Controllers_SerialPABotBase_Connection_H + +#include +#include +#include +#include +#include "ClientSource/Connection/BotBase.h" +#include "ClientSource/Connection/MessageLogger.h" +#include "Controllers/ControllerConnection.h" + +class QSerialPortInfo; + +namespace PokemonAutomation{ + class PABotBase; +namespace SerialPABotBase{ + + +class SerialPABotBase_Connection : public ControllerConnection{ +public: + SerialPABotBase_Connection( + Logger& logger, + const QSerialPortInfo* port, + std::optional change_controller + ); + ~SerialPABotBase_Connection(); + + +public: +// uint8_t program_id() const{ +// return m_program_id; +// } + BotBaseController* botbase(); + +public: + virtual ControllerModeStatus controller_mode_status() const override; + + +private: + const std::map>& + get_programs_for_protocol(uint32_t protocol); + + const std::map& + get_controllers_for_program( + const std::map>& available_programs, + uint32_t program_id + ); + + void process_queue_size(); + ControllerType get_controller_type( + const std::map& available_controllers + ); + + ControllerModeStatus read_device_specs( + std::optional change_controller + ); + + void thread_body( + std::optional change_controller + ); + + +private: + SerialLogger m_logger; + std::string m_device_name; + + uint32_t m_protocol = 0; + uint32_t m_version = 0; + uint8_t m_program_id = 0; + ControllerModeStatus m_mode_status; + + std::thread m_status_thread; + std::unique_ptr m_botbase; + mutable std::mutex m_lock; + std::mutex m_sleep_lock; + std::condition_variable m_cv; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Descriptor.cpp b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Descriptor.cpp index aefa687f28..ef26168061 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Descriptor.cpp +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Descriptor.cpp @@ -1,118 +1,118 @@ -/* Serial Port (PABotBase) Interface - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Json/JsonValue.h" -#include "Controllers/ControllerTypeStrings.h" -#include "SerialPABotBase_Descriptor.h" -#include "SerialPABotBase_SelectorWidget.h" - -#include "NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.h" -#include "NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessProController.h" -#include "NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessJoycon.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - -template class InterfaceType_t; - -namespace SerialPABotBase{ - - - - -bool SerialPABotBase_Descriptor::operator==(const ControllerDescriptor& x) const{ - if (typeid(*this) != typeid(x)){ - return false; - } - return m_port.portName() == static_cast(x).m_port.portName(); -} - - -std::string SerialPABotBase_Descriptor::display_name() const{ - if (m_port.isNull()){ - return ""; - } -// if (PreloadSettings::instance().DEVELOPER_MODE){ - return m_port.portName().toStdString(); -// } -// return m_port.portName().toStdString() + " - " + m_port.description().toStdString(); -} -void SerialPABotBase_Descriptor::load_json(const JsonValue& json){ - const std::string* name = json.to_string(); - if (name == nullptr || name->empty()){ - return; - } - m_port = (QSerialPortInfo(QString::fromStdString(*name))); -} -JsonValue SerialPABotBase_Descriptor::to_json() const{ - return m_port.isNull() ? "" : m_port.portName().toStdString(); -} - -std::unique_ptr SerialPABotBase_Descriptor::open_connection( - Logger& logger, - std::optional change_controller -) const{ - return std::unique_ptr( - new SerialPABotBase_Connection(logger, &m_port, change_controller) - ); -} -std::unique_ptr SerialPABotBase_Descriptor::make_controller( - Logger& logger, - ControllerConnection& connection, - ControllerType controller_type -) const{ - switch (controller_type){ - case ControllerType::NintendoSwitch_WiredProController: - return std::unique_ptr( - new PokemonAutomation::NintendoSwitch::SerialPABotBase_PokkenController( - logger, - static_cast(connection) - ) - ); - - case ControllerType::NintendoSwitch_WirelessProController: - return std::unique_ptr( - new PokemonAutomation::NintendoSwitch::SerialPABotBase_WirelessProController( - logger, - static_cast(connection) - ) - ); - - case ControllerType::NintendoSwitch_LeftJoycon: - case ControllerType::NintendoSwitch_RightJoycon: - return std::unique_ptr( - new PokemonAutomation::NintendoSwitch::SerialPABotBase_WirelessJoycon( - logger, - static_cast(connection), - controller_type - ) - ); - - default:; - } - - logger.log( - std::string("Unsupported Controller Type: ") + CONTROLLER_TYPE_STRINGS.get_string(controller_type), - COLOR_RED - ); - return nullptr; -} - - - -QWidget* SerialPABotBase_Descriptor::make_selector_QtWidget(ControllerSelectorWidget& parent) const{ - return new SerialPABotBase_SelectorWidget(parent, this); -} - - - - -} -} +/* Serial Port (PABotBase) Interface + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Controllers/ControllerTypeStrings.h" +#include "SerialPABotBase_Descriptor.h" +#include "SerialPABotBase_SelectorWidget.h" + +#include "NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.h" +#include "NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessProController.h" +#include "NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessJoycon.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + +template class InterfaceType_t; + +namespace SerialPABotBase{ + + + + +bool SerialPABotBase_Descriptor::operator==(const ControllerDescriptor& x) const{ + if (typeid(*this) != typeid(x)){ + return false; + } + return m_port.portName() == static_cast(x).m_port.portName(); +} + + +std::string SerialPABotBase_Descriptor::display_name() const{ + if (m_port.isNull()){ + return ""; + } +// if (PreloadSettings::instance().DEVELOPER_MODE){ + return m_port.portName().toStdString(); +// } +// return m_port.portName().toStdString() + " - " + m_port.description().toStdString(); +} +void SerialPABotBase_Descriptor::load_json(const JsonValue& json){ + const std::string* name = json.to_string(); + if (name == nullptr || name->empty()){ + return; + } + m_port = (QSerialPortInfo(QString::fromStdString(*name))); +} +JsonValue SerialPABotBase_Descriptor::to_json() const{ + return m_port.isNull() ? "" : m_port.portName().toStdString(); +} + +std::unique_ptr SerialPABotBase_Descriptor::open_connection( + Logger& logger, + std::optional change_controller +) const{ + return std::unique_ptr( + new SerialPABotBase_Connection(logger, &m_port, change_controller) + ); +} +std::unique_ptr SerialPABotBase_Descriptor::make_controller( + Logger& logger, + ControllerConnection& connection, + ControllerType controller_type +) const{ + switch (controller_type){ + case ControllerType::NintendoSwitch_WiredProController: + return std::unique_ptr( + new PokemonAutomation::NintendoSwitch::SerialPABotBase_PokkenController( + logger, + static_cast(connection) + ) + ); + + case ControllerType::NintendoSwitch_WirelessProController: + return std::unique_ptr( + new PokemonAutomation::NintendoSwitch::SerialPABotBase_WirelessProController( + logger, + static_cast(connection) + ) + ); + + case ControllerType::NintendoSwitch_LeftJoycon: + case ControllerType::NintendoSwitch_RightJoycon: + return std::unique_ptr( + new PokemonAutomation::NintendoSwitch::SerialPABotBase_WirelessJoycon( + logger, + static_cast(connection), + controller_type + ) + ); + + default:; + } + + logger.log( + std::string("Unsupported Controller Type: ") + CONTROLLER_TYPE_STRINGS.get_string(controller_type), + COLOR_RED + ); + return nullptr; +} + + + +QWidget* SerialPABotBase_Descriptor::make_selector_QtWidget(ControllerSelectorWidget& parent) const{ + return new SerialPABotBase_SelectorWidget(parent, this); +} + + + + +} +} diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Descriptor.h b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Descriptor.h index 10a9d70805..694e8e26bc 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Descriptor.h +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Descriptor.h @@ -1,62 +1,62 @@ -/* Serial Port (PABotBase) Interface - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_SerialPABotBase_Descriptor_H -#define PokemonAutomation_Controllers_SerialPABotBase_Descriptor_H - -#include -#include "Controllers/ControllerDescriptor.h" - -namespace PokemonAutomation{ -namespace SerialPABotBase{ - - - -class SerialPABotBase_Descriptor : public ControllerDescriptor{ -public: - static constexpr ControllerInterface INTERFACE_NAME = ControllerInterface::SerialPABotBase; - - -public: - SerialPABotBase_Descriptor() - : ControllerDescriptor(INTERFACE_NAME) - {} - SerialPABotBase_Descriptor(const QSerialPortInfo& info) - : ControllerDescriptor(INTERFACE_NAME) - , m_port(info) - {} - - const QSerialPortInfo& port() const{ - return m_port; - } - - virtual bool operator==(const ControllerDescriptor& x) const override; - virtual std::string display_name() const override; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual std::unique_ptr open_connection( - Logger& logger, - std::optional change_controller - ) const override; - virtual std::unique_ptr make_controller( - Logger& logger, - ControllerConnection& connection, - ControllerType controller_type - ) const override; - - virtual QWidget* make_selector_QtWidget(ControllerSelectorWidget& parent) const override; - -private: - QSerialPortInfo m_port; -}; - - - -} -} -#endif +/* Serial Port (PABotBase) Interface + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_SerialPABotBase_Descriptor_H +#define PokemonAutomation_Controllers_SerialPABotBase_Descriptor_H + +#include +#include "Controllers/ControllerDescriptor.h" + +namespace PokemonAutomation{ +namespace SerialPABotBase{ + + + +class SerialPABotBase_Descriptor : public ControllerDescriptor{ +public: + static constexpr ControllerInterface INTERFACE_NAME = ControllerInterface::SerialPABotBase; + + +public: + SerialPABotBase_Descriptor() + : ControllerDescriptor(INTERFACE_NAME) + {} + SerialPABotBase_Descriptor(const QSerialPortInfo& info) + : ControllerDescriptor(INTERFACE_NAME) + , m_port(info) + {} + + const QSerialPortInfo& port() const{ + return m_port; + } + + virtual bool operator==(const ControllerDescriptor& x) const override; + virtual std::string display_name() const override; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual std::unique_ptr open_connection( + Logger& logger, + std::optional change_controller + ) const override; + virtual std::unique_ptr make_controller( + Logger& logger, + ControllerConnection& connection, + ControllerType controller_type + ) const override; + + virtual QWidget* make_selector_QtWidget(ControllerSelectorWidget& parent) const override; + +private: + QSerialPortInfo m_port; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_PostConnectActions.cpp b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_PostConnectActions.cpp index 4402953122..e010c576df 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_PostConnectActions.cpp +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_PostConnectActions.cpp @@ -1,144 +1,144 @@ -/* Serial Port (PABotBase) Post-Connect Actinos - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h" -#include "ClientSource/Connection/PABotBase.h" -#include "Controllers/ControllerTypeStrings.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "SerialPABotBase_Routines_Protocol.h" -#include "SerialPABotBase_Routines_ESP32.h" -#include "SerialPABotBase.h" -#include "SerialPABotBase_PostConnectActions.h" - -namespace PokemonAutomation{ -namespace SerialPABotBase{ - - - -void run_post_connect_actions_ESP32( - ControllerModeStatus& status, - const std::string& device_name, - PABotBase& botbase, - std::optional change_controller -){ - if (!change_controller){ - return; - } - - Logger& logger = botbase.logger(); - - ControllerType desired_controller = change_controller.value(); - switch (desired_controller){ - case ControllerType::NintendoSwitch_WiredProController: - case ControllerType::NintendoSwitch_WirelessProController: - case ControllerType::NintendoSwitch_LeftJoycon: - case ControllerType::NintendoSwitch_RightJoycon:{ - uint8_t controller_mac_address[6] = {}; - { - BotBaseMessage response = botbase.issue_request_and_wait( - MessageControllerReadSpi( - desired_controller, - 0x80000000, sizeof(controller_mac_address) - ), - nullptr - ); - if (response.body.size() == sizeof(seqnum_t) + sizeof(controller_mac_address)){ - memcpy( - controller_mac_address, - response.body.data() + sizeof(seqnum_t), - sizeof(controller_mac_address) - ); - }else{ - logger.log( - "Invalid response size to PABB_MSG_ESP32_REQUEST_READ_SPI: body = " + std::to_string(response.body.size()), - COLOR_RED - ); - } - } - - NintendoSwitch::ControllerProfile profile = - PokemonAutomation::NintendoSwitch::ConsoleSettings::instance().CONTROLLER_SETTINGS.get_or_make_profile( - controller_mac_address, - device_name, - desired_controller - ); - - PABB_NintendoSwitch_ControllerColors colors; - { - Color color(profile.body_color); - colors.body[0] = color.red(); - colors.body[1] = color.green(); - colors.body[2] = color.blue(); - } - { - Color color(profile.button_color); - colors.buttons[0] = color.red(); - colors.buttons[1] = color.green(); - colors.buttons[2] = color.blue(); - } - { - Color color(profile.left_grip); - colors.left_grip[0] = color.red(); - colors.left_grip[1] = color.green(); - colors.left_grip[2] = color.blue(); - } - { - Color color(profile.right_grip); - colors.right_grip[0] = color.red(); - colors.right_grip[1] = color.green(); - colors.right_grip[2] = color.blue(); - } - - botbase.issue_request_and_wait( - MessageControllerWriteSpi( - desired_controller, - 0x00006050, sizeof(PABB_NintendoSwitch_ControllerColors), - &colors - ), - nullptr - ); - } - default:; - } - - - uint32_t native_controller_id = controller_type_to_id(desired_controller); - botbase.issue_request_and_wait( - DeviceRequest_change_controller_mode(native_controller_id), - nullptr - ); - - // Re-read the controller. - logger.log("Reading Controller Mode..."); - uint32_t type_id = read_controller_mode(botbase); - status.current_controller = id_to_controller_type(type_id); - logger.log( - "Reading Controller Mode... Mode = " + - CONTROLLER_TYPE_STRINGS.get_string(status.current_controller) - ); -} - - - - -void run_post_connect_actions( - ControllerModeStatus& status, - uint32_t program_id, const std::string& device_name, - PABotBase& botbase, - std::optional change_controller -){ - switch (program_id){ - case PABB_PID_PABOTBASE_ESP32: - run_post_connect_actions_ESP32(status, device_name, botbase, change_controller); - return; - } -} - - - - -} -} +/* Serial Port (PABotBase) Post-Connect Actinos + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h" +#include "ClientSource/Connection/PABotBase.h" +#include "Controllers/ControllerTypeStrings.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "SerialPABotBase_Routines_Protocol.h" +#include "SerialPABotBase_Routines_ESP32.h" +#include "SerialPABotBase.h" +#include "SerialPABotBase_PostConnectActions.h" + +namespace PokemonAutomation{ +namespace SerialPABotBase{ + + + +void run_post_connect_actions_ESP32( + ControllerModeStatus& status, + const std::string& device_name, + PABotBase& botbase, + std::optional change_controller +){ + if (!change_controller){ + return; + } + + Logger& logger = botbase.logger(); + + ControllerType desired_controller = change_controller.value(); + switch (desired_controller){ + case ControllerType::NintendoSwitch_WiredProController: + case ControllerType::NintendoSwitch_WirelessProController: + case ControllerType::NintendoSwitch_LeftJoycon: + case ControllerType::NintendoSwitch_RightJoycon:{ + uint8_t controller_mac_address[6] = {}; + { + BotBaseMessage response = botbase.issue_request_and_wait( + MessageControllerReadSpi( + desired_controller, + 0x80000000, sizeof(controller_mac_address) + ), + nullptr + ); + if (response.body.size() == sizeof(seqnum_t) + sizeof(controller_mac_address)){ + memcpy( + controller_mac_address, + response.body.data() + sizeof(seqnum_t), + sizeof(controller_mac_address) + ); + }else{ + logger.log( + "Invalid response size to PABB_MSG_ESP32_REQUEST_READ_SPI: body = " + std::to_string(response.body.size()), + COLOR_RED + ); + } + } + + NintendoSwitch::ControllerProfile profile = + PokemonAutomation::NintendoSwitch::ConsoleSettings::instance().CONTROLLER_SETTINGS.get_or_make_profile( + controller_mac_address, + device_name, + desired_controller + ); + + PABB_NintendoSwitch_ControllerColors colors; + { + Color color(profile.body_color); + colors.body[0] = color.red(); + colors.body[1] = color.green(); + colors.body[2] = color.blue(); + } + { + Color color(profile.button_color); + colors.buttons[0] = color.red(); + colors.buttons[1] = color.green(); + colors.buttons[2] = color.blue(); + } + { + Color color(profile.left_grip); + colors.left_grip[0] = color.red(); + colors.left_grip[1] = color.green(); + colors.left_grip[2] = color.blue(); + } + { + Color color(profile.right_grip); + colors.right_grip[0] = color.red(); + colors.right_grip[1] = color.green(); + colors.right_grip[2] = color.blue(); + } + + botbase.issue_request_and_wait( + MessageControllerWriteSpi( + desired_controller, + 0x00006050, sizeof(PABB_NintendoSwitch_ControllerColors), + &colors + ), + nullptr + ); + } + default:; + } + + + uint32_t native_controller_id = controller_type_to_id(desired_controller); + botbase.issue_request_and_wait( + DeviceRequest_change_controller_mode(native_controller_id), + nullptr + ); + + // Re-read the controller. + logger.log("Reading Controller Mode..."); + uint32_t type_id = read_controller_mode(botbase); + status.current_controller = id_to_controller_type(type_id); + logger.log( + "Reading Controller Mode... Mode = " + + CONTROLLER_TYPE_STRINGS.get_string(status.current_controller) + ); +} + + + + +void run_post_connect_actions( + ControllerModeStatus& status, + uint32_t program_id, const std::string& device_name, + PABotBase& botbase, + std::optional change_controller +){ + switch (program_id){ + case PABB_PID_PABOTBASE_ESP32: + run_post_connect_actions_ESP32(status, device_name, botbase, change_controller); + return; + } +} + + + + +} +} diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_PostConnectActions.h b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_PostConnectActions.h index 326cb19be5..f62dc9f308 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_PostConnectActions.h +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_PostConnectActions.h @@ -1,29 +1,29 @@ -/* Serial Port (PABotBase) Post-Connect Actinos - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_SerialPABotBase_PostConnectActions_H -#define PokemonAutomation_Controllers_SerialPABotBase_PostConnectActions_H - -#include "Controllers/ControllerConnection.h" - -namespace PokemonAutomation{ - class PABotBase; -namespace SerialPABotBase{ - - -void run_post_connect_actions( - ControllerModeStatus& status, - uint32_t program_id, const std::string& device_name, - PABotBase& botbase, - std::optional change_controller -); - - - - -} -} -#endif +/* Serial Port (PABotBase) Post-Connect Actinos + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_SerialPABotBase_PostConnectActions_H +#define PokemonAutomation_Controllers_SerialPABotBase_PostConnectActions_H + +#include "Controllers/ControllerConnection.h" + +namespace PokemonAutomation{ + class PABotBase; +namespace SerialPABotBase{ + + +void run_post_connect_actions( + ControllerModeStatus& status, + uint32_t program_id, const std::string& device_name, + PABotBase& botbase, + std::optional change_controller +); + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_ESP32.cpp b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_ESP32.cpp index cabfb85022..971602e548 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_ESP32.cpp +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_ESP32.cpp @@ -1,145 +1,145 @@ -/* SerialPABotBase ESP32 Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h" -#include "ClientSource/Libraries/MessageConverter.h" -#include "CommonFramework/GlobalSettingsPanel.h" - -namespace PokemonAutomation{ -namespace SerialPABotBase{ - - - -int register_message_converters_ESP32(){ - register_message_converter( - PABB_MSG_REQUEST_STATUS, - [](const std::string& body){ - // Disable this by default since it's very spammy. - if (!GlobalSettings::instance().LOG_EVERYTHING){ - return std::string(); - } - std::ostringstream ss; - ss << "PABB_MSG_REQUEST_STATUS() - "; - if (body.size() != sizeof(pabb_Message_RequestStatus)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_Message_RequestStatus*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_ESP32_REQUEST_READ_SPI, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_ESP32_REQUEST_READ_SPI() - "; - if (body.size() != sizeof(pabb_Message_ESP32_ReadSpi)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_Message_ESP32_ReadSpi*)body.c_str(); - ss << "seqnum = " << params->seqnum; - ss << ", controller = " << params->controller_type; - ss << ", address = 0x" << tostr_hex(params->address); - ss << ", bytes = " << (size_t)params->bytes; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_ESP32_REQUEST_WRITE_SPI, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_ESP32_REQUEST_WRITE_SPI() - "; - if (body.size() <= sizeof(pabb_Message_ESP32_WriteSpi)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_Message_ESP32_WriteSpi*)body.c_str(); - ss << "seqnum = " << params->seqnum; - ss << ", controller = " << params->controller_type; - ss << ", address = 0x" << tostr_hex(params->address); - ss << ", bytes = " << (size_t)params->bytes; - return ss.str(); - } - ); -#if 0 - register_message_converter( - PABB_MSG_ESP32_REQUEST_GET_COLORS, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_ESP32_REQUEST_GET_COLORS() - "; - if (body.size() != sizeof(pabb_Message_ESP32_GetColors)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_Message_ESP32_GetColors*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - ss << ", controller = " << (uint64_t)params->controller_type; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_ESP32_REQUEST_SET_COLORS, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_ESP32_REQUEST_SET_COLORS() - "; - if (body.size() != sizeof(pabb_Message_ESP32_SetColors)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_Message_ESP32_SetColors*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - return ss.str(); - } - ); -#endif - register_message_converter( - PABB_MSG_ESP32_CONTROLLER_STATE_BUTTONS, - [](const std::string& body){ - // Disable this by default since it's very spammy. - if (!GlobalSettings::instance().LOG_EVERYTHING){ - return std::string(); - } - std::ostringstream ss; - ss << "PABB_MSG_ESP32_CONTROLLER_STATE_BUTTONS() - "; - if (body.size() != sizeof(pabb_Message_ESP32_CommandButtonState)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_Message_ESP32_CommandButtonState*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - ss << ", milliseconds = " << params->milliseconds; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_ESP32_CONTROLLER_STATE_FULL, - [](const std::string& body){ - // Disable this by default since it's very spammy. - if (!GlobalSettings::instance().LOG_EVERYTHING){ - return std::string(); - } - std::ostringstream ss; - ss << "PABB_MSG_ESP32_CONTROLLER_STATE_FULL() - "; - if (body.size() != sizeof(pabb_Message_ESP32_CommandFullState)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_Message_ESP32_CommandFullState*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - ss << ", milliseconds = " << params->milliseconds; - return ss.str(); - } - ); -#if 0 - register_message_converter( - PABB_MSG_ESP32_REPORT, - [](const std::string& body){ - // Disable this by default since it's very spammy. - if (!GlobalSettings::instance().LOG_EVERYTHING){ - return std::string(); - } - std::ostringstream ss; - ss << "ESP32_controller_state() - "; - if (body.size() != sizeof(pabb_esp32_report30)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_esp32_report30*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - ss << ", ticks = " << (int)params->ticks; - ss << ", active = " << (int)params->active; - return ss.str(); - } - ); -#endif - return 0; -} -int init_Messages_ESP32 = register_message_converters_ESP32(); - - - -} -} +/* SerialPABotBase ESP32 Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h" +#include "ClientSource/Libraries/MessageConverter.h" +#include "CommonFramework/GlobalSettingsPanel.h" + +namespace PokemonAutomation{ +namespace SerialPABotBase{ + + + +int register_message_converters_ESP32(){ + register_message_converter( + PABB_MSG_REQUEST_STATUS, + [](const std::string& body){ + // Disable this by default since it's very spammy. + if (!GlobalSettings::instance().LOG_EVERYTHING){ + return std::string(); + } + std::ostringstream ss; + ss << "PABB_MSG_REQUEST_STATUS() - "; + if (body.size() != sizeof(pabb_Message_RequestStatus)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_Message_RequestStatus*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_ESP32_REQUEST_READ_SPI, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_ESP32_REQUEST_READ_SPI() - "; + if (body.size() != sizeof(pabb_Message_ESP32_ReadSpi)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_Message_ESP32_ReadSpi*)body.c_str(); + ss << "seqnum = " << params->seqnum; + ss << ", controller = " << params->controller_type; + ss << ", address = 0x" << tostr_hex(params->address); + ss << ", bytes = " << (size_t)params->bytes; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_ESP32_REQUEST_WRITE_SPI, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_ESP32_REQUEST_WRITE_SPI() - "; + if (body.size() <= sizeof(pabb_Message_ESP32_WriteSpi)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_Message_ESP32_WriteSpi*)body.c_str(); + ss << "seqnum = " << params->seqnum; + ss << ", controller = " << params->controller_type; + ss << ", address = 0x" << tostr_hex(params->address); + ss << ", bytes = " << (size_t)params->bytes; + return ss.str(); + } + ); +#if 0 + register_message_converter( + PABB_MSG_ESP32_REQUEST_GET_COLORS, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_ESP32_REQUEST_GET_COLORS() - "; + if (body.size() != sizeof(pabb_Message_ESP32_GetColors)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_Message_ESP32_GetColors*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + ss << ", controller = " << (uint64_t)params->controller_type; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_ESP32_REQUEST_SET_COLORS, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_ESP32_REQUEST_SET_COLORS() - "; + if (body.size() != sizeof(pabb_Message_ESP32_SetColors)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_Message_ESP32_SetColors*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + return ss.str(); + } + ); +#endif + register_message_converter( + PABB_MSG_ESP32_CONTROLLER_STATE_BUTTONS, + [](const std::string& body){ + // Disable this by default since it's very spammy. + if (!GlobalSettings::instance().LOG_EVERYTHING){ + return std::string(); + } + std::ostringstream ss; + ss << "PABB_MSG_ESP32_CONTROLLER_STATE_BUTTONS() - "; + if (body.size() != sizeof(pabb_Message_ESP32_CommandButtonState)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_Message_ESP32_CommandButtonState*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + ss << ", milliseconds = " << params->milliseconds; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_ESP32_CONTROLLER_STATE_FULL, + [](const std::string& body){ + // Disable this by default since it's very spammy. + if (!GlobalSettings::instance().LOG_EVERYTHING){ + return std::string(); + } + std::ostringstream ss; + ss << "PABB_MSG_ESP32_CONTROLLER_STATE_FULL() - "; + if (body.size() != sizeof(pabb_Message_ESP32_CommandFullState)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_Message_ESP32_CommandFullState*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + ss << ", milliseconds = " << params->milliseconds; + return ss.str(); + } + ); +#if 0 + register_message_converter( + PABB_MSG_ESP32_REPORT, + [](const std::string& body){ + // Disable this by default since it's very spammy. + if (!GlobalSettings::instance().LOG_EVERYTHING){ + return std::string(); + } + std::ostringstream ss; + ss << "ESP32_controller_state() - "; + if (body.size() != sizeof(pabb_esp32_report30)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_esp32_report30*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + ss << ", ticks = " << (int)params->ticks; + ss << ", active = " << (int)params->active; + return ss.str(); + } + ); +#endif + return 0; +} +int init_Messages_ESP32 = register_message_converters_ESP32(); + + + +} +} diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_ESP32.h b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_ESP32.h index 7bce06a7e9..64e6d04e98 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_ESP32.h +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_ESP32.h @@ -1,122 +1,122 @@ -/* SerialPABotBase ESP32 Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SerialPABotBase_ESP32_Routines_H -#define PokemonAutomation_SerialPABotBase_ESP32_Routines_H - -#include "Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h" -#include "Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h" -#include "ClientSource/Connection/BotBaseMessage.h" -#include "Controllers/ControllerTypes.h" - -namespace PokemonAutomation{ -namespace SerialPABotBase{ - - - - -class MessageControllerReadSpi : public BotBaseRequest{ -public: - pabb_Message_ESP32_ReadSpi params; - MessageControllerReadSpi(ControllerType controller_type, uint32_t address, uint8_t bytes) - : BotBaseRequest(false) - { - uint32_t controller_id = PABB_CID_NONE; - switch (controller_type){ - case ControllerType::NintendoSwitch_WirelessProController: - controller_id = PABB_CID_NINTENDO_SWITCH_WIRELESS_PRO_CONTROLLER; - break; - case ControllerType::NintendoSwitch_LeftJoycon: - controller_id = PABB_CID_NINTENDO_SWITCH_LEFT_JOYCON; - break; - case ControllerType::NintendoSwitch_RightJoycon: - controller_id = PABB_CID_NINTENDO_SWITCH_RIGHT_JOYCON; - break; - default:; - } - params.seqnum = 0; - params.controller_type = controller_id; - params.address = address; - params.bytes = bytes; - } - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_ESP32_REQUEST_READ_SPI, params); - } -}; -class MessageControllerWriteSpi : public BotBaseRequest{ -public: - std::string data; - MessageControllerWriteSpi( - ControllerType controller_type, - uint32_t address, uint8_t bytes, - const void* p_data - ) - : BotBaseRequest(false) - { - uint32_t controller_id = PABB_CID_NONE; - switch (controller_type){ - case ControllerType::NintendoSwitch_WirelessProController: - controller_id = PABB_CID_NINTENDO_SWITCH_WIRELESS_PRO_CONTROLLER; - break; - case ControllerType::NintendoSwitch_LeftJoycon: - controller_id = PABB_CID_NINTENDO_SWITCH_LEFT_JOYCON; - break; - case ControllerType::NintendoSwitch_RightJoycon: - controller_id = PABB_CID_NINTENDO_SWITCH_RIGHT_JOYCON; - break; - default:; - } - pabb_Message_ESP32_WriteSpi params; - params.seqnum = 0; - params.controller_type = controller_id; - params.address = address; - params.bytes = bytes; - data = std::string((char*)¶ms, sizeof(params)); - data += std::string((const char*)p_data, bytes); - } - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_ESP32_REQUEST_WRITE_SPI, data); - } -}; -class MessageControllerStateButtons : public BotBaseRequest{ -public: - pabb_Message_ESP32_CommandButtonState params; - MessageControllerStateButtons(uint16_t milliseconds, const PABB_NintendoSwitch_ButtonState& state) - : BotBaseRequest(true) - { - params.seqnum = 0; - params.milliseconds = milliseconds; - params.buttons = state; - } - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_ESP32_CONTROLLER_STATE_BUTTONS, params); - } -}; -class MessageControllerStateFull : public BotBaseRequest{ -public: - pabb_Message_ESP32_CommandFullState params; - MessageControllerStateFull( - uint16_t milliseconds, - const PABB_NintendoSwitch_ButtonState& buttons, - const PABB_NintendoSwitch_GyroStateX3& gyro - ) - : BotBaseRequest(true) - { - params.seqnum = 0; - params.milliseconds = milliseconds; - params.buttons = buttons; - params.gyro = gyro; - } - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_ESP32_CONTROLLER_STATE_FULL, params); - } -}; - - - -} -} -#endif +/* SerialPABotBase ESP32 Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SerialPABotBase_ESP32_Routines_H +#define PokemonAutomation_SerialPABotBase_ESP32_Routines_H + +#include "Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h" +#include "Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h" +#include "ClientSource/Connection/BotBaseMessage.h" +#include "Controllers/ControllerTypes.h" + +namespace PokemonAutomation{ +namespace SerialPABotBase{ + + + + +class MessageControllerReadSpi : public BotBaseRequest{ +public: + pabb_Message_ESP32_ReadSpi params; + MessageControllerReadSpi(ControllerType controller_type, uint32_t address, uint8_t bytes) + : BotBaseRequest(false) + { + uint32_t controller_id = PABB_CID_NONE; + switch (controller_type){ + case ControllerType::NintendoSwitch_WirelessProController: + controller_id = PABB_CID_NINTENDO_SWITCH_WIRELESS_PRO_CONTROLLER; + break; + case ControllerType::NintendoSwitch_LeftJoycon: + controller_id = PABB_CID_NINTENDO_SWITCH_LEFT_JOYCON; + break; + case ControllerType::NintendoSwitch_RightJoycon: + controller_id = PABB_CID_NINTENDO_SWITCH_RIGHT_JOYCON; + break; + default:; + } + params.seqnum = 0; + params.controller_type = controller_id; + params.address = address; + params.bytes = bytes; + } + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_ESP32_REQUEST_READ_SPI, params); + } +}; +class MessageControllerWriteSpi : public BotBaseRequest{ +public: + std::string data; + MessageControllerWriteSpi( + ControllerType controller_type, + uint32_t address, uint8_t bytes, + const void* p_data + ) + : BotBaseRequest(false) + { + uint32_t controller_id = PABB_CID_NONE; + switch (controller_type){ + case ControllerType::NintendoSwitch_WirelessProController: + controller_id = PABB_CID_NINTENDO_SWITCH_WIRELESS_PRO_CONTROLLER; + break; + case ControllerType::NintendoSwitch_LeftJoycon: + controller_id = PABB_CID_NINTENDO_SWITCH_LEFT_JOYCON; + break; + case ControllerType::NintendoSwitch_RightJoycon: + controller_id = PABB_CID_NINTENDO_SWITCH_RIGHT_JOYCON; + break; + default:; + } + pabb_Message_ESP32_WriteSpi params; + params.seqnum = 0; + params.controller_type = controller_id; + params.address = address; + params.bytes = bytes; + data = std::string((char*)¶ms, sizeof(params)); + data += std::string((const char*)p_data, bytes); + } + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_ESP32_REQUEST_WRITE_SPI, data); + } +}; +class MessageControllerStateButtons : public BotBaseRequest{ +public: + pabb_Message_ESP32_CommandButtonState params; + MessageControllerStateButtons(uint16_t milliseconds, const PABB_NintendoSwitch_ButtonState& state) + : BotBaseRequest(true) + { + params.seqnum = 0; + params.milliseconds = milliseconds; + params.buttons = state; + } + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_ESP32_CONTROLLER_STATE_BUTTONS, params); + } +}; +class MessageControllerStateFull : public BotBaseRequest{ +public: + pabb_Message_ESP32_CommandFullState params; + MessageControllerStateFull( + uint16_t milliseconds, + const PABB_NintendoSwitch_ButtonState& buttons, + const PABB_NintendoSwitch_GyroStateX3& gyro + ) + : BotBaseRequest(true) + { + params.seqnum = 0; + params.milliseconds = milliseconds; + params.buttons = buttons; + params.gyro = gyro; + } + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_ESP32_CONTROLLER_STATE_FULL, params); + } +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_NS_Generic.cpp b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_NS_Generic.cpp index 848ac1dc16..c276dbcca5 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_NS_Generic.cpp +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_NS_Generic.cpp @@ -1,66 +1,50 @@ -/* SerialPABotBase AVR8 Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/SerialPABotBase/SerialPABotBase_Messages_NS_Generic.h" -#include "ClientSource/Libraries/MessageConverter.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerState.h" - -namespace PokemonAutomation{ -namespace SerialPABotBase{ - - - -int register_message_converters_push_button_framework(){ - register_message_converter( - PABB_MSG_NS_GENERIC_CONTROLLER_STATE_TICKS, - [](const std::string& body){ - // Disable this by default since it's very spammy. - if (!GlobalSettings::instance().LOG_EVERYTHING){ - return std::string(); - } - std::ostringstream ss; - ss << "controller_state_ticks() - "; - if (body.size() != sizeof(pabb_Message_NS_Generic_ControllerStateTicks)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_Message_NS_Generic_ControllerStateTicks*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - ss << ", buttons = " << params->buttons << "(" << button_to_string((NintendoSwitch::Button)params->buttons) << ")"; - ss << ", dpad = " << dpad_to_string((NintendoSwitch::DpadPosition)params->dpad); - ss << ", LJ = (" << (int)params->left_joystick_x << "," << (int)params->left_joystick_y << ")"; - ss << ", RJ = (" << (int)params->right_joystick_x << "," << (int)params->right_joystick_y << ")"; - ss << ", ticks = " << (int)params->ticks; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_NS_GENERIC_CONTROLLER_STATE_MS, - [](const std::string& body){ - // Disable this by default since it's very spammy. - if (!GlobalSettings::instance().LOG_EVERYTHING){ - return std::string(); - } - std::ostringstream ss; - ss << "controller_state_ms() - "; - if (body.size() != sizeof(pabb_Message_NS_Generic_ControllerStateMs)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_Message_NS_Generic_ControllerStateMs*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - ss << ", buttons = " << params->buttons << "(" << button_to_string((NintendoSwitch::Button)params->buttons) << ")"; - ss << ", dpad = " << dpad_to_string((NintendoSwitch::DpadPosition)params->dpad); - ss << ", LJ = (" << (int)params->left_joystick_x << "," << (int)params->left_joystick_y << ")"; - ss << ", RJ = (" << (int)params->right_joystick_x << "," << (int)params->right_joystick_y << ")"; - ss << ", milliseconds = " << params->milliseconds; - return ss.str(); - } - ); - return 0; -} -int init_PushButtonFramework = register_message_converters_push_button_framework(); - - - -} -} +/* SerialPABotBase AVR8 Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/SerialPABotBase/SerialPABotBase_Messages_NS_Generic.h" +#include "ClientSource/Libraries/MessageConverter.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerState.h" + +namespace PokemonAutomation{ +namespace SerialPABotBase{ + + + +int register_message_converters_push_button_framework(){ + register_message_converter( + PABB_MSG_NS_GENERIC_CONTROLLER_STATE_MS, + [](const std::string& body){ + // Disable this by default since it's very spammy. + if (!GlobalSettings::instance().LOG_EVERYTHING){ + return std::string(); + } + std::ostringstream ss; + ss << "controller_state_ms() - "; + if (body.size() != sizeof(pabb_Message_NS_Generic_ControllerStateMs)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_Message_NS_Generic_ControllerStateMs*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + + uint16_t buttons = params->report.buttons0; + buttons |= (uint16_t)params->report.buttons1 << 8; + ss << ", buttons = " << buttons << " (" << button_to_string((NintendoSwitch::Button)buttons) << ")"; + + ss << ", dpad = " << dpad_to_string((NintendoSwitch::DpadPosition)params->report.dpad); + ss << ", LJ = (" << (int)params->report.left_joystick_x << "," << (int)params->report.left_joystick_y << ")"; + ss << ", RJ = (" << (int)params->report.right_joystick_x << "," << (int)params->report.right_joystick_y << ")"; + ss << ", milliseconds = " << params->milliseconds; + return ss.str(); + } + ); + return 0; +} +int init_PushButtonFramework = register_message_converters_push_button_framework(); + + + +} +} diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_NS_Generic.h b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_NS_Generic.h index ccca96b5de..6ff785e805 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_NS_Generic.h +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_NS_Generic.h @@ -1,80 +1,56 @@ -/* SerialPABotBase (Nintendo Switch Generic Wired Controller) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SerialPABotBase_NS_Generic_H -#define PokemonAutomation_SerialPABotBase_NS_Generic_H - -#include "Common/SerialPABotBase/SerialPABotBase_Messages_NS_Generic.h" -#include "ClientSource/Connection/BotBaseMessage.h" - -namespace PokemonAutomation{ -namespace SerialPABotBase{ - - - -class DeviceRequest_NS_Generic_ControllerStateTicks : public BotBaseRequest{ -public: - pabb_Message_NS_Generic_ControllerStateTicks params; - DeviceRequest_NS_Generic_ControllerStateTicks( - uint16_t buttons, - uint8_t dpad, - uint8_t left_joystick_x, - uint8_t left_joystick_y, - uint8_t right_joystick_x, - uint8_t right_joystick_y, - uint8_t ticks - ) - : BotBaseRequest(true) - { - params.seqnum = 0; - params.buttons = buttons; - params.dpad = dpad; - params.left_joystick_x = left_joystick_x; - params.left_joystick_y = left_joystick_y; - params.right_joystick_x = right_joystick_x; - params.right_joystick_y = right_joystick_y; - params.ticks = ticks; - } - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_NS_GENERIC_CONTROLLER_STATE_TICKS, params); - } -}; - - - -class DeviceRequest_NS_Generic_ControllerStateMs : public BotBaseRequest{ -public: - pabb_Message_NS_Generic_ControllerStateMs params; - DeviceRequest_NS_Generic_ControllerStateMs( - uint16_t milliseconds, - uint16_t buttons, - uint8_t dpad, - uint8_t left_joystick_x, - uint8_t left_joystick_y, - uint8_t right_joystick_x, - uint8_t right_joystick_y - ) - : BotBaseRequest(true) - { - params.seqnum = 0; - params.milliseconds = milliseconds; - params.buttons = buttons; - params.dpad = dpad; - params.left_joystick_x = left_joystick_x; - params.left_joystick_y = left_joystick_y; - params.right_joystick_x = right_joystick_x; - params.right_joystick_y = right_joystick_y; - } - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_NS_GENERIC_CONTROLLER_STATE_MS, params); - } -}; - - - -} -} -#endif +/* SerialPABotBase (Nintendo Switch Generic Wired Controller) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SerialPABotBase_NS_Generic_H +#define PokemonAutomation_SerialPABotBase_NS_Generic_H + +#include "Common/SerialPABotBase/SerialPABotBase_Messages_NS_Generic.h" +#include "ClientSource/Connection/BotBaseMessage.h" + +namespace PokemonAutomation{ +namespace SerialPABotBase{ + + +class DeviceRequest_NS_Generic_ControllerStateMs : public BotBaseRequest{ +public: + pabb_Message_NS_Generic_ControllerStateMs params; + DeviceRequest_NS_Generic_ControllerStateMs( + uint16_t milliseconds, + uint16_t buttons, + uint8_t dpad, + uint8_t left_joystick_x, + uint8_t left_joystick_y, + uint8_t right_joystick_x, + uint8_t right_joystick_y + ) + : BotBaseRequest(true) + { + memset(¶ms, 0, sizeof(params)); + + params.seqnum = 0; + params.milliseconds = milliseconds; + + params.report.buttons0 = (uint8_t)buttons; + params.report.buttons1 = (uint8_t)(buttons >> 8); +// params.report.buttons2 = 0; +// params.report.buttons3 = 0; + + params.report.dpad = dpad; + params.report.left_joystick_x = left_joystick_x; + params.report.left_joystick_y = left_joystick_y; + params.report.right_joystick_x = right_joystick_x; + params.report.right_joystick_y = right_joystick_y; + } + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_NS_GENERIC_CONTROLLER_STATE_MS, params); + } +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.cpp b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.cpp index fd8aeeab73..b8b9c992fe 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.cpp +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.cpp @@ -1,59 +1,59 @@ -/* SerialPABotBase Routines (Protocol) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "SerialPABotBase_Routines_Protocol.h" - -namespace PokemonAutomation{ -namespace SerialPABotBase{ - - -uint32_t protocol_version(BotBaseController& botbase){ - pabb_MsgAckRequestI32 response; - botbase.issue_request_and_wait( - DeviceRequest_protocol_version() - ).convert(botbase.logger(), response); - return response.data; -} -uint32_t program_version(BotBaseController& botbase){ - pabb_MsgAckRequestI32 response; - botbase.issue_request_and_wait( - DeviceRequest_program_version() - ).convert(botbase.logger(), response); - return response.data; -} -uint8_t device_queue_size(BotBaseController& botbase){ - pabb_MsgAckRequestI8 response; - botbase.issue_request_and_wait( - DeviceRequest_queue_size() - ).convert(botbase.logger(), response); - return response.data; - -} -uint8_t program_id(BotBaseController& botbase){ - pabb_MsgAckRequestI8 response; - botbase.issue_request_and_wait( - DeviceRequest_program_id() - ).convert(botbase.logger(), response); - return response.data; -} -uint32_t read_controller_mode(BotBaseController& botbase){ - pabb_MsgAckRequestI32 response; - botbase.issue_request_and_wait( - DeviceRequest_read_controller_mode() - ).convert(botbase.logger(), response); - return response.data; -} -uint32_t change_controller_mode(BotBaseController& botbase, uint32_t mode){ - pabb_MsgAckRequestI32 response; - botbase.issue_request_and_wait( - DeviceRequest_change_controller_mode(mode) - ).convert(botbase.logger(), response); - return response.data; -} - - -} -} +/* SerialPABotBase Routines (Protocol) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "SerialPABotBase_Routines_Protocol.h" + +namespace PokemonAutomation{ +namespace SerialPABotBase{ + + +uint32_t protocol_version(BotBaseController& botbase){ + pabb_MsgAckRequestI32 response; + botbase.issue_request_and_wait( + DeviceRequest_protocol_version() + ).convert(botbase.logger(), response); + return response.data; +} +uint32_t program_version(BotBaseController& botbase){ + pabb_MsgAckRequestI32 response; + botbase.issue_request_and_wait( + DeviceRequest_program_version() + ).convert(botbase.logger(), response); + return response.data; +} +uint8_t device_queue_size(BotBaseController& botbase){ + pabb_MsgAckRequestI8 response; + botbase.issue_request_and_wait( + DeviceRequest_queue_size() + ).convert(botbase.logger(), response); + return response.data; + +} +uint8_t program_id(BotBaseController& botbase){ + pabb_MsgAckRequestI8 response; + botbase.issue_request_and_wait( + DeviceRequest_program_id() + ).convert(botbase.logger(), response); + return response.data; +} +uint32_t read_controller_mode(BotBaseController& botbase){ + pabb_MsgAckRequestI32 response; + botbase.issue_request_and_wait( + DeviceRequest_read_controller_mode() + ).convert(botbase.logger(), response); + return response.data; +} +uint32_t change_controller_mode(BotBaseController& botbase, uint32_t mode){ + pabb_MsgAckRequestI32 response; + botbase.issue_request_and_wait( + DeviceRequest_change_controller_mode(mode) + ).convert(botbase.logger(), response); + return response.data; +} + + +} +} diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.h b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.h index e7f443f2a1..637aa8455b 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.h +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.h @@ -1,146 +1,146 @@ -/* SerialPABotBase Routines (Protocol) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SerialPABotBase_Routines_Protocol_H -#define PokemonAutomation_SerialPABotBase_Routines_Protocol_H - -#include "Common/SerialPABotBase/SerialPABotBase_Protocol.h" -#include "ClientSource/Connection/BotBase.h" -#include "ClientSource/Connection/BotBaseMessage.h" - -namespace PokemonAutomation{ -namespace SerialPABotBase{ - -uint32_t protocol_version(BotBaseController& botbase); -uint32_t program_version(BotBaseController& botbase); -uint8_t device_queue_size(BotBaseController& botbase); -uint8_t program_id(BotBaseController& botbase); -uint32_t read_controller_mode(BotBaseController& botbase); -uint32_t change_controller_mode(BotBaseController& botbase, uint32_t mode); - - -class DeviceRequest_seqnum_reset : public BotBaseRequest{ -public: - pabb_MsgInfoSeqnumReset params; - DeviceRequest_seqnum_reset() - : BotBaseRequest(false) - {} - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_SEQNUM_RESET, params); - } -}; -class DeviceRequest_request_stop : public BotBaseRequest{ -public: - pabb_MsgRequestProtocolVersion params; - DeviceRequest_request_stop() - : BotBaseRequest(false) - {} - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_REQUEST_STOP, params); - } -}; -class DeviceRequest_next_command_interrupt : public BotBaseRequest{ -public: - pabb_MsgRequestNextCmdInterrupt params; - DeviceRequest_next_command_interrupt() - : BotBaseRequest(false) - {} - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_REQUEST_NEXT_CMD_INTERRUPT, params); - } -}; -class DeviceRequest_protocol_version : public BotBaseRequest{ -public: - pabb_MsgRequestProtocolVersion params; - DeviceRequest_protocol_version() - : BotBaseRequest(false) - {} - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_REQUEST_PROTOCOL_VERSION, params); - } -}; -class DeviceRequest_program_version : public BotBaseRequest{ -public: - pabb_MsgRequestProgramVersion params; - DeviceRequest_program_version() - : BotBaseRequest(false) - {} - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_REQUEST_PROGRAM_VERSION, params); - } -}; -class DeviceRequest_queue_size : public BotBaseRequest{ -public: - pabb_MsgRequestProgramVersion params; - DeviceRequest_queue_size() - : BotBaseRequest(false) - {} - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_REQUEST_QUEUE_SIZE, params); - } -}; -class DeviceRequest_system_clock : public BotBaseRequest{ -public: - pabb_system_clock params; - DeviceRequest_system_clock() - : BotBaseRequest(false) - { - params.seqnum = 0; - } - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_REQUEST_CLOCK, params); - } -}; -class DeviceRequest_program_id : public BotBaseRequest{ -public: - pabb_MsgRequestProgramID params; - DeviceRequest_program_id() - : BotBaseRequest(false) - {} - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_REQUEST_PROGRAM_ID, params); - } -}; -class DeviceRequest_read_controller_mode : public BotBaseRequest{ -public: - pabb_MsgRequestReadControllerMode params; - DeviceRequest_read_controller_mode() - : BotBaseRequest(false) - {} - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_REQUEST_READ_CONTROLLER_MODE, params); - } -}; -class DeviceRequest_change_controller_mode : public BotBaseRequest{ -public: - pabb_MsgRequestChangeControllerMode params; - DeviceRequest_change_controller_mode(uint32_t mode) - : BotBaseRequest(false) - { - params.mode = mode; - } - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_REQUEST_CHANGE_CONTROLLER_MODE, params); - } -}; -class MessageControllerStatus : public BotBaseRequest{ -public: - pabb_Message_RequestStatus params; - MessageControllerStatus() - : BotBaseRequest(false) - { - params.seqnum = 0; - } - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_REQUEST_STATUS, params); - } -}; - - - -} -} -#endif +/* SerialPABotBase Routines (Protocol) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SerialPABotBase_Routines_Protocol_H +#define PokemonAutomation_SerialPABotBase_Routines_Protocol_H + +#include "Common/SerialPABotBase/SerialPABotBase_Protocol.h" +#include "ClientSource/Connection/BotBase.h" +#include "ClientSource/Connection/BotBaseMessage.h" + +namespace PokemonAutomation{ +namespace SerialPABotBase{ + +uint32_t protocol_version(BotBaseController& botbase); +uint32_t program_version(BotBaseController& botbase); +uint8_t device_queue_size(BotBaseController& botbase); +uint8_t program_id(BotBaseController& botbase); +uint32_t read_controller_mode(BotBaseController& botbase); +uint32_t change_controller_mode(BotBaseController& botbase, uint32_t mode); + + +class DeviceRequest_seqnum_reset : public BotBaseRequest{ +public: + pabb_MsgInfoSeqnumReset params; + DeviceRequest_seqnum_reset() + : BotBaseRequest(false) + {} + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_SEQNUM_RESET, params); + } +}; +class DeviceRequest_request_stop : public BotBaseRequest{ +public: + pabb_MsgRequestProtocolVersion params; + DeviceRequest_request_stop() + : BotBaseRequest(false) + {} + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_REQUEST_STOP, params); + } +}; +class DeviceRequest_next_command_interrupt : public BotBaseRequest{ +public: + pabb_MsgRequestNextCmdInterrupt params; + DeviceRequest_next_command_interrupt() + : BotBaseRequest(false) + {} + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_REQUEST_NEXT_CMD_INTERRUPT, params); + } +}; +class DeviceRequest_protocol_version : public BotBaseRequest{ +public: + pabb_MsgRequestProtocolVersion params; + DeviceRequest_protocol_version() + : BotBaseRequest(false) + {} + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_REQUEST_PROTOCOL_VERSION, params); + } +}; +class DeviceRequest_program_version : public BotBaseRequest{ +public: + pabb_MsgRequestProgramVersion params; + DeviceRequest_program_version() + : BotBaseRequest(false) + {} + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_REQUEST_PROGRAM_VERSION, params); + } +}; +class DeviceRequest_queue_size : public BotBaseRequest{ +public: + pabb_MsgRequestProgramVersion params; + DeviceRequest_queue_size() + : BotBaseRequest(false) + {} + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_REQUEST_QUEUE_SIZE, params); + } +}; +class DeviceRequest_system_clock : public BotBaseRequest{ +public: + pabb_system_clock params; + DeviceRequest_system_clock() + : BotBaseRequest(false) + { + params.seqnum = 0; + } + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_REQUEST_CLOCK, params); + } +}; +class DeviceRequest_program_id : public BotBaseRequest{ +public: + pabb_MsgRequestProgramID params; + DeviceRequest_program_id() + : BotBaseRequest(false) + {} + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_REQUEST_PROGRAM_ID, params); + } +}; +class DeviceRequest_read_controller_mode : public BotBaseRequest{ +public: + pabb_MsgRequestReadControllerMode params; + DeviceRequest_read_controller_mode() + : BotBaseRequest(false) + {} + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_REQUEST_READ_CONTROLLER_MODE, params); + } +}; +class DeviceRequest_change_controller_mode : public BotBaseRequest{ +public: + pabb_MsgRequestChangeControllerMode params; + DeviceRequest_change_controller_mode(uint32_t mode) + : BotBaseRequest(false) + { + params.mode = mode; + } + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_REQUEST_CHANGE_CONTROLLER_MODE, params); + } +}; +class MessageControllerStatus : public BotBaseRequest{ +public: + pabb_Message_RequestStatus params; + MessageControllerStatus() + : BotBaseRequest(false) + { + params.seqnum = 0; + } + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_REQUEST_STATUS, params); + } +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_SelectorWidget.h b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_SelectorWidget.h index 34168cc479..9e9f33428c 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_SelectorWidget.h +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_SelectorWidget.h @@ -1,127 +1,127 @@ -/* SerialPABotBase Selector Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_SerialPABotBase_SelectorWidget_H -#define PokemonAutomation_Controllers_SerialPABotBase_SelectorWidget_H - -#include "Common/Qt/NoWheelComboBox.h" -#include "Controllers/ControllerDescriptor.h" -#include "Controllers/ControllerSelectorWidget.h" -#include "Controllers/NullController.h" -#include "SerialPABotBase_Descriptor.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace SerialPABotBase{ - - - - -class SerialPABotBase_SelectorWidget : public NoWheelComboBox{ -public: - SerialPABotBase_SelectorWidget( - ControllerSelectorWidget& parent, - const ControllerDescriptor* current - ) - : NoWheelComboBox(&parent) - , m_parent(parent) - { -// cout << "SerialPABotBase(): " << current << endl; - this->setMaxVisibleItems(32); - - if (current == nullptr || ( - current->interface_type != ControllerInterface::None && - current->interface_type != ControllerInterface::SerialPABotBase - ) - ){ - std::shared_ptr descriptor = - parent.session().option().get_descriptor_from_cache(ControllerInterface::SerialPABotBase); - if (!descriptor){ - descriptor.reset(new SerialPABotBase_Descriptor()); - } - parent.session().set_device(descriptor); - } - - refresh_devices(); - - connect( - this, static_cast(&QComboBox::activated), - &parent, [this, &parent](int index){ - if (index < 0){ - return; - } - index = std::min(index, (int)m_ports.size() - 1); - std::shared_ptr& selected = m_ports[index]; - - std::shared_ptr current = parent.session().descriptor(); - if (*current == *selected){ - return; - } - - parent.session().set_device(selected); - refresh_devices(); - } - ); - } - - void refresh_devices(){ -// cout << "Current = " << width() << " x " << height() << endl; -// cout << "sizeHint = " << sizeHint().width() << " x " << sizeHint().height() << endl; -// cout << "minimumContentsLength = " << this->minimumContentsLength() << endl; - - m_ports.clear(); - this->clear(); - -// cout << "SerialPABotBase_SelectorWidget::refresh_devices()" << endl; - - - m_ports.emplace_back(new NullControllerDescriptor()); - for (QSerialPortInfo& port : QSerialPortInfo::availablePorts()){ -#ifdef _WIN32 - // COM1 is never the correct port on Windows. - if (port.portName() == "COM1"){ - continue; - } -#endif - m_ports.emplace_back(new SerialPABotBase_Descriptor(port)); - } - - size_t width = 6; - int index = 0; - int c = 0; - for (const auto& port : m_ports){ - QString display_name = QString::fromStdString(port->display_name()); - width = std::max(width, display_name.size()); - this->addItem(display_name); - if (*m_parent.session().descriptor() == *m_ports[c]){ - index = c; - } - c++; - } - - if (this->count() > this->maxVisibleItems()){ - width++; - } - setMinimumContentsLength((int)width); - setCurrentIndex(index); - } - - -private: - ControllerSelectorWidget& m_parent; - std::vector> m_ports; -}; - - - - - -} -} -#endif +/* SerialPABotBase Selector Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_SerialPABotBase_SelectorWidget_H +#define PokemonAutomation_Controllers_SerialPABotBase_SelectorWidget_H + +#include "Common/Qt/NoWheelComboBox.h" +#include "Controllers/ControllerDescriptor.h" +#include "Controllers/ControllerSelectorWidget.h" +#include "Controllers/NullController.h" +#include "SerialPABotBase_Descriptor.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace SerialPABotBase{ + + + + +class SerialPABotBase_SelectorWidget : public NoWheelComboBox{ +public: + SerialPABotBase_SelectorWidget( + ControllerSelectorWidget& parent, + const ControllerDescriptor* current + ) + : NoWheelComboBox(&parent) + , m_parent(parent) + { +// cout << "SerialPABotBase(): " << current << endl; + this->setMaxVisibleItems(32); + + if (current == nullptr || ( + current->interface_type != ControllerInterface::None && + current->interface_type != ControllerInterface::SerialPABotBase + ) + ){ + std::shared_ptr descriptor = + parent.session().option().get_descriptor_from_cache(ControllerInterface::SerialPABotBase); + if (!descriptor){ + descriptor.reset(new SerialPABotBase_Descriptor()); + } + parent.session().set_device(descriptor); + } + + refresh_devices(); + + connect( + this, static_cast(&QComboBox::activated), + &parent, [this, &parent](int index){ + if (index < 0){ + return; + } + index = std::min(index, (int)m_ports.size() - 1); + std::shared_ptr& selected = m_ports[index]; + + std::shared_ptr current = parent.session().descriptor(); + if (*current == *selected){ + return; + } + + parent.session().set_device(selected); + refresh_devices(); + } + ); + } + + void refresh_devices(){ +// cout << "Current = " << width() << " x " << height() << endl; +// cout << "sizeHint = " << sizeHint().width() << " x " << sizeHint().height() << endl; +// cout << "minimumContentsLength = " << this->minimumContentsLength() << endl; + + m_ports.clear(); + this->clear(); + +// cout << "SerialPABotBase_SelectorWidget::refresh_devices()" << endl; + + + m_ports.emplace_back(new NullControllerDescriptor()); + for (QSerialPortInfo& port : QSerialPortInfo::availablePorts()){ +#ifdef _WIN32 + // COM1 is never the correct port on Windows. + if (port.portName() == "COM1"){ + continue; + } +#endif + m_ports.emplace_back(new SerialPABotBase_Descriptor(port)); + } + + size_t width = 6; + int index = 0; + int c = 0; + for (const auto& port : m_ports){ + QString display_name = QString::fromStdString(port->display_name()); + width = std::max(width, display_name.size()); + this->addItem(display_name); + if (*m_parent.session().descriptor() == *m_ports[c]){ + index = c; + } + c++; + } + + if (this->count() > this->maxVisibleItems()){ + width++; + } + setMinimumContentsLength((int)width); + setCurrentIndex(index); + } + + +private: + ControllerSelectorWidget& m_parent; + std::vector> m_ports; +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Controllers/SuperscalarScheduler.cpp b/SerialPrograms/Source/Controllers/SuperscalarScheduler.cpp index d154ac5f21..9cbb1b3e10 100644 --- a/SerialPrograms/Source/Controllers/SuperscalarScheduler.cpp +++ b/SerialPrograms/Source/Controllers/SuperscalarScheduler.cpp @@ -1,259 +1,278 @@ -/* Superscalar Scheduler - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Time.h" -#include "SuperscalarScheduler.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -SuperscalarScheduler::SuperscalarScheduler( - Logger& logger, - WallDuration flush_threshold, - std::vector resources -) - : m_logger(logger) - , m_flush_threshold(flush_threshold) - , m_resources(std::move(resources)) -{ - clear(); -} - - -void SuperscalarScheduler::clear() noexcept{ -// SpinLockGuard lg(m_lock); -// m_logger.log("Clearing schedule..."); - WallClock now = current_time(); - m_local_start = now; - m_local_last_activity = now; - m_device_issue_time = now; - m_device_sent_time = now; - m_max_free_time = now; - m_state_changes.clear(); - for (ExecutionResource* resource : m_resources){ - resource->m_is_busy = false; - resource->m_busy_time = now; - resource->m_done_time = now; - resource->m_free_time = now; -// cout << "issue_time = " << std::chrono::duration_cast((m_device_issue_time - m_local_start)).count() -// << ", sent_time = " << std::chrono::duration_cast((m_device_sent_time - m_local_start)).count() -// << ", free_time = " << std::chrono::duration_cast((resource->m_free_time - m_local_start)).count() -// << endl; - } - m_pending_clear.store(false, std::memory_order_release); -} - -bool SuperscalarScheduler::iterate_schedule(const Cancellable* cancellable){ - if (cancellable){ - cancellable->throw_if_cancelled(); - } - - if (m_state_changes.empty()){ -// cout << "State is empty." << endl; - m_device_sent_time = m_device_issue_time; - return false; - } - - auto iter = m_state_changes.begin(); - - WallClock next_state_change; - if (m_device_sent_time < *iter){ - next_state_change = *iter; - }else{ - auto next = iter; - ++next; - next_state_change = next == m_state_changes.end() - ? m_device_issue_time - : *next; - } - - // Things get complicated if we overshoot the issue time. - if (next_state_change > m_device_issue_time){ -// m_logger.log("SuperscalarScheduler: Overshoot due to unfinished early return.", COLOR_RED); - next_state_change = m_device_issue_time; - } - - WallDuration duration = next_state_change - m_device_sent_time; - if (duration == WallDuration::zero()){ - // This happens when the command has a delay of zero. A delay of zero - // is almost always immediately followed by another command that is - // intended to execute simultaneously. Thus we do not attempt to - // execute the schedule any further. -// m_logger.log("SuperscalarScheduler: Scheduler is stalled.", COLOR_RED); - return false; - } - - // Compute the resource state at this timestamp. - for (ExecutionResource* resource : m_resources){ - resource->m_is_busy = resource->m_busy_time <= m_device_sent_time && m_device_sent_time < resource->m_done_time; - } - - m_device_sent_time = next_state_change; - if (next_state_change >= *iter){ - m_state_changes.erase(iter); - } - - this->push_state(cancellable, duration); - -// SpinLockGuard lg(m_lock); - - WallClock now = current_time(); - m_local_last_activity = now; - - // If we are not dangling anything, we can return now. - if (m_device_sent_time >= m_device_issue_time){ - return true; - } - -#if 1 - // - // We are currently dangling a command. We don't know whether the current - // ongoing commands will run out, or if something new will join them in the - // near future. - // - // If it's been long enough since the last issue, we can assume that - // nothing will join and thus can gap. (We do require that dangling - // commands be resolved promptly or they may run out.) - // - // Thus we can fast forward whatever is scheduled into the future. - // - WallDuration time_since_last_activity = now - m_local_last_activity; - if (time_since_last_activity > m_flush_threshold){ - m_logger.log("SuperscalarScheduler: A dangling early-return issue has gapped.", COLOR_RED); - m_device_issue_time += time_since_last_activity; - - // Since we're gapping, we might as well gap a bit more to we don't - // re-enter here so quickly. - m_device_issue_time += m_flush_threshold; - - m_max_free_time = std::max(m_max_free_time, m_device_issue_time); - } - -#endif - - return true; -} -void SuperscalarScheduler::process_schedule(const Cancellable* cancellable){ - // Any exception is either an unrecoverable error, or an async-cancel. - // Both cases should clear the scheduler. - try{ - while (iterate_schedule(cancellable)); - }catch (...){ - clear(); - throw; - } -} - -void SuperscalarScheduler::issue_wait_for_all(const Cancellable* cancellable){ - if (m_pending_clear.load(std::memory_order_acquire)){ - clear(); - return; - } -// m_logger.log("issue_wait_for_all(): states = " + std::to_string(m_state_changes.size()), COLOR_DARKGREEN); -// cout << "issue_wait_for_all(): " << m_state_changes.size() << endl; -// cout << "issue_time = " << std::chrono::duration_cast((m_device_issue_time - m_local_start)).count() -// << ", sent_time = " << std::chrono::duration_cast((m_device_sent_time - m_local_start)).count() -// << ", max_free_time = " << std::chrono::duration_cast((m_max_free_time - m_local_start)).count() -// << endl; - m_device_issue_time = std::max(m_device_issue_time, m_max_free_time); - m_max_free_time = m_device_issue_time; - process_schedule(cancellable); -} -void SuperscalarScheduler::issue_nop(const Cancellable* cancellable, WallDuration delay){ - if (delay <= WallDuration::zero()){ - return; - } - if (m_pending_clear.load(std::memory_order_acquire)){ - clear(); - } -// cout << "issue_nop(): " << m_state_changes.size() << endl; -// cout << "issue_time = " << std::chrono::duration_cast((m_device_issue_time - m_local_start)).count() -// << ", sent_time = " << std::chrono::duration_cast((m_device_sent_time - m_local_start)).count() -// << ", max_free_time = " << std::chrono::duration_cast((m_max_free_time - m_local_start)).count() -// << endl; - WallClock next_issue_time = m_device_issue_time + delay; - m_state_changes.insert(next_issue_time); - m_device_issue_time = next_issue_time; - m_max_free_time = std::max(m_max_free_time, m_device_issue_time); - m_local_last_activity = current_time(); - process_schedule(cancellable); -} -void SuperscalarScheduler::issue_wait_for_resource(const Cancellable* cancellable, ExecutionResource& resource){ - if (m_pending_clear.load(std::memory_order_acquire)){ - clear(); - return; - } -// cout << "wait_for_resource()" << endl; -// cout << "issue_time = " << std::chrono::duration_cast((m_device_issue_time - m_local_start)).count() -// << ", sent_time = " << std::chrono::duration_cast((m_device_sent_time - m_local_start)).count() -// << ", free_time = " << std::chrono::duration_cast((resource.m_free_time - m_local_start)).count() -// << endl; - // Resource is not ready yet. Stall until it is. - if (resource.m_free_time > m_device_sent_time){ -// cout << "stall = " << std::chrono::duration_cast(resource.m_free_time - m_device_sent_time).count() << endl; - m_device_issue_time = resource.m_free_time; - m_local_last_activity = current_time(); - } - process_schedule(cancellable); -} -void SuperscalarScheduler::issue_to_resource( - const Cancellable* cancellable, ExecutionResource& resource, - WallDuration delay, WallDuration hold, WallDuration cooldown -){ - if (m_pending_clear.load(std::memory_order_acquire)){ - clear(); - } - - // Resource is busy. - if (m_device_sent_time < resource.m_free_time){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Attempted to issue resource that isn't ready." - ); - } - - delay = std::max(delay, WallDuration::zero()); - hold = std::max(hold, WallDuration::zero()); - cooldown = std::max(cooldown, WallDuration::zero()); - -// cout << "issue_to_resource(): delay = " << std::chrono::duration_cast(delay).count() -// << ", hold = " << std::chrono::duration_cast(hold).count() -// << ", cooldown = " << std::chrono::duration_cast(cooldown).count() -// << endl; -// cout << "issue_time = " << std::chrono::duration_cast((m_device_issue_time - m_local_start)).count() -// << ", sent_time = " << std::chrono::duration_cast((m_device_sent_time - m_local_start)).count() -// << endl; - - WallClock release_time = m_device_issue_time + hold; - WallClock free_time = release_time + cooldown; - - m_state_changes.insert(m_device_issue_time); - m_state_changes.insert(release_time); - - resource.m_busy_time = m_device_issue_time; - resource.m_done_time = release_time; - resource.m_free_time = free_time; - - m_device_issue_time += delay; - m_max_free_time = std::max(m_max_free_time, free_time); - m_max_free_time = std::max(m_max_free_time, m_device_issue_time); - m_local_last_activity = current_time(); - - process_schedule(cancellable); -} - - - - - - -} - +/* Superscalar Scheduler + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Time.h" +#include "SuperscalarScheduler.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +SuperscalarScheduler::SuperscalarScheduler( + Logger& logger, + WallDuration flush_threshold, + std::vector resources +) + : m_logger(logger) + , m_flush_threshold(flush_threshold) + , m_resources(std::move(resources)) +{ + clear(); +} + + +void SuperscalarScheduler::clear() noexcept{ +// SpinLockGuard lg(m_lock); +// m_logger.log("Clearing schedule..."); + WallClock now = current_time(); + m_local_start = now; + m_local_last_activity = now; + m_device_issue_time = now; + m_device_sent_time = now; + m_max_free_time = now; + m_state_changes.clear(); + for (ExecutionResource* resource : m_resources){ + resource->m_is_busy = false; + resource->m_busy_time = now; + resource->m_done_time = now; + resource->m_free_time = now; +// cout << "issue_time = " << std::chrono::duration_cast((m_device_issue_time - m_local_start)).count() +// << ", sent_time = " << std::chrono::duration_cast((m_device_sent_time - m_local_start)).count() +// << ", free_time = " << std::chrono::duration_cast((resource->m_free_time - m_local_start)).count() +// << endl; + } + m_pending_clear.store(false, std::memory_order_release); +} + +void SuperscalarScheduler::update_busy_states(){ + WallClock device_sent_time = m_device_sent_time; + for (ExecutionResource* resource : m_resources){ + resource->m_is_busy = resource->m_busy_time <= device_sent_time && device_sent_time < resource->m_done_time; + +#if 0 + if (resource->m_done_time >m_local_start){ + cout << "------------" << endl; + cout << "m_busy_time = " << std::chrono::duration_cast(resource->m_busy_time - m_local_start) << endl; + cout << "m_done_time = " << std::chrono::duration_cast(resource->m_done_time - m_local_start) << endl; + cout << "m_device_sent_time = " << std::chrono::duration_cast(m_device_sent_time - m_local_start) << endl; + cout << "m_is_busy = " << resource->m_is_busy << endl; + } +#endif + } +} +bool SuperscalarScheduler::iterate_schedule(const Cancellable* cancellable){ + if (cancellable){ + cancellable->throw_if_cancelled(); + } + +// cout << "----------------------------> " << m_state_changes.size() << endl; +// cout << "m_device_sent_time = " << std::chrono::duration_cast(m_device_sent_time - m_local_start) << endl; + + if (m_state_changes.empty()){ +// cout << "State is empty." << endl; + m_device_sent_time = m_device_issue_time; + return false; + } + + auto iter = m_state_changes.begin(); + + WallClock next_state_change; + if (m_device_sent_time < *iter){ + next_state_change = *iter; + }else{ + auto next = iter; + ++next; + next_state_change = next == m_state_changes.end() + ? m_device_issue_time + : *next; + } + + // Things get complicated if we overshoot the issue time. + if (next_state_change > m_device_issue_time){ +// m_logger.log("SuperscalarScheduler: Overshoot due to unfinished early return.", COLOR_RED); + next_state_change = m_device_issue_time; + } + + WallDuration duration = next_state_change - m_device_sent_time; + if (duration == WallDuration::zero()){ + // This happens when the command has a delay of zero. A delay of zero + // is almost always immediately followed by another command that is + // intended to execute simultaneously. Thus we do not attempt to + // execute the schedule any further. +// m_logger.log("SuperscalarScheduler: Scheduler is stalled.", COLOR_RED); + return false; + } + + // Compute the resource state at this timestamp. + update_busy_states(); + + m_device_sent_time = next_state_change; + if (next_state_change > *iter){ + m_state_changes.erase(iter); + } + + this->push_state(cancellable, duration); + +// SpinLockGuard lg(m_lock); + + WallClock now = current_time(); + m_local_last_activity = now; + + // If we are not dangling anything, we can return now. + if (m_device_sent_time >= m_device_issue_time){ + return true; + } + +#if 1 + // + // We are currently dangling a command. We don't know whether the current + // ongoing commands will run out, or if something new will join them in the + // near future. + // + // If it's been long enough since the last issue, we can assume that + // nothing will join and thus can gap. (We do require that dangling + // commands be resolved promptly or they may run out.) + // + // Thus we can fast forward whatever is scheduled into the future. + // + WallDuration time_since_last_activity = now - m_local_last_activity; + if (time_since_last_activity > m_flush_threshold){ + m_logger.log("SuperscalarScheduler: A dangling early-return issue has gapped.", COLOR_RED); + m_device_issue_time += time_since_last_activity; + + // Since we're gapping, we might as well gap a bit more to we don't + // re-enter here so quickly. + m_device_issue_time += m_flush_threshold; + + m_max_free_time = std::max(m_max_free_time, m_device_issue_time); + } + +#endif + + return true; +} +void SuperscalarScheduler::process_schedule(const Cancellable* cancellable){ + // Any exception is either an unrecoverable error, or an async-cancel. + // Both cases should clear the scheduler. + try{ + while (iterate_schedule(cancellable)); + }catch (...){ + clear(); + throw; + } +} + +void SuperscalarScheduler::issue_wait_for_all(const Cancellable* cancellable){ + if (m_pending_clear.load(std::memory_order_acquire)){ + clear(); + return; + } +// m_logger.log("issue_wait_for_all(): states = " + std::to_string(m_state_changes.size()), COLOR_DARKGREEN); +// cout << "issue_wait_for_all(): " << m_state_changes.size() << endl; +// cout << "issue_time = " << std::chrono::duration_cast((m_device_issue_time - m_local_start)).count() +// << ", sent_time = " << std::chrono::duration_cast((m_device_sent_time - m_local_start)).count() +// << ", max_free_time = " << std::chrono::duration_cast((m_max_free_time - m_local_start)).count() +// << endl; + m_device_issue_time = std::max(m_device_issue_time, m_max_free_time); + m_max_free_time = m_device_issue_time; + process_schedule(cancellable); +} +void SuperscalarScheduler::issue_nop(const Cancellable* cancellable, WallDuration delay){ + if (delay <= WallDuration::zero()){ + return; + } + if (m_pending_clear.load(std::memory_order_acquire)){ + clear(); + } +// cout << "issue_nop(): " << m_state_changes.size() << endl; +// cout << "issue_time = " << std::chrono::duration_cast((m_device_issue_time - m_local_start)).count() +// << ", sent_time = " << std::chrono::duration_cast((m_device_sent_time - m_local_start)).count() +// << ", max_free_time = " << std::chrono::duration_cast((m_max_free_time - m_local_start)).count() +// << endl; + WallClock next_issue_time = m_device_issue_time + delay; + m_state_changes.insert(next_issue_time); + m_device_issue_time = next_issue_time; + m_max_free_time = std::max(m_max_free_time, m_device_issue_time); + m_local_last_activity = current_time(); + process_schedule(cancellable); +} +void SuperscalarScheduler::issue_wait_for_resource(const Cancellable* cancellable, ExecutionResource& resource){ + if (m_pending_clear.load(std::memory_order_acquire)){ + clear(); + return; + } +// cout << "wait_for_resource()" << endl; +// cout << "issue_time = " << std::chrono::duration_cast((m_device_issue_time - m_local_start)).count() +// << ", sent_time = " << std::chrono::duration_cast((m_device_sent_time - m_local_start)).count() +// << ", free_time = " << std::chrono::duration_cast((resource.m_free_time - m_local_start)).count() +// << endl; + // Resource is not ready yet. Stall until it is. + if (resource.m_free_time > m_device_sent_time){ +// cout << "stall = " << std::chrono::duration_cast(resource.m_free_time - m_device_sent_time).count() << endl; + m_device_issue_time = resource.m_free_time; + m_local_last_activity = current_time(); + } + process_schedule(cancellable); +} +void SuperscalarScheduler::issue_to_resource( + const Cancellable* cancellable, ExecutionResource& resource, + WallDuration delay, WallDuration hold, WallDuration cooldown +){ + if (m_pending_clear.load(std::memory_order_acquire)){ + clear(); + } + + // Resource is busy. + if (m_device_sent_time < resource.m_free_time){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Attempted to issue resource that isn't ready." + ); + } + + delay = std::max(delay, WallDuration::zero()); + hold = std::max(hold, WallDuration::zero()); + cooldown = std::max(cooldown, WallDuration::zero()); + +#if 0 + cout << "issue_to_resource(): delay = " << std::chrono::duration_cast(delay).count() + << ", hold = " << std::chrono::duration_cast(hold).count() + << ", cooldown = " << std::chrono::duration_cast(cooldown).count() + << endl; + cout << "issue_time = " << std::chrono::duration_cast((m_device_issue_time - m_local_start)).count() + << ", sent_time = " << std::chrono::duration_cast((m_device_sent_time - m_local_start)).count() + << endl; +#endif + + WallClock release_time = m_device_issue_time + hold; + WallClock free_time = release_time + cooldown; + + m_state_changes.insert(m_device_issue_time); + m_state_changes.insert(release_time); + + resource.m_busy_time = m_device_issue_time; + resource.m_done_time = release_time; + resource.m_free_time = free_time; + + m_device_issue_time += delay; + m_max_free_time = std::max(m_max_free_time, free_time); + m_max_free_time = std::max(m_max_free_time, m_device_issue_time); + m_local_last_activity = current_time(); + + process_schedule(cancellable); +} + + + + + + +} + diff --git a/SerialPrograms/Source/Controllers/SuperscalarScheduler.h b/SerialPrograms/Source/Controllers/SuperscalarScheduler.h index cd5dd5343d..a6e089ff27 100644 --- a/SerialPrograms/Source/Controllers/SuperscalarScheduler.h +++ b/SerialPrograms/Source/Controllers/SuperscalarScheduler.h @@ -1,152 +1,153 @@ -/* Superscalar Scheduler - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_SuperscalarScheduler_H -#define PokemonAutomation_Controllers_SuperscalarScheduler_H - -#include -#include -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/CancellableScope.h" - -namespace PokemonAutomation{ - -class SuperscalarScheduler; - - -class ExecutionResource{ -public: - virtual ~ExecutionResource() = default; - ExecutionResource() - : m_busy_time(WallClock::min()) - , m_done_time(WallClock::min()) - , m_free_time(WallClock::min()) - {} - - bool is_busy() const{ - return m_is_busy; - } - WallClock free_time() const{ - return m_free_time; - } - -private: - friend class SuperscalarScheduler; - bool m_is_busy = false; - WallClock m_busy_time; // Timestamp of when resource will be become busy. - WallClock m_done_time; // Timestamp of when resource will be done being busy. - WallClock m_free_time; // Timestamp of when resource can be used again. -}; - - - - - -class SuperscalarScheduler{ -public: - SuperscalarScheduler( - Logger& logger, - WallDuration flush_threshold, - std::vector resources - ); - - -public: - // This is intended to be run on a different thread from the functions in - // the next section. So it is safe to run from anywhere. - - void clear_on_next(){ - m_pending_clear.store(true, std::memory_order_release); - } - - -public: - // These are the standard "issue" commands. - // - // These functions may or may not block. - // These are not thread-safe with each other. - // - - // Wait until the pipeline has completely cleared and all resources have - // returned to the ready state. - void issue_wait_for_all(const Cancellable* cancellable); - - // Issue a do-nothing command for the specified delay. - // This will advance the issue timestamp. - void issue_nop(const Cancellable* cancellable, WallDuration delay); - - // Wait until the specified resource is ready to be used. - // This will advance the issue timestamp until the resource is ready. - void issue_wait_for_resource(const Cancellable* cancellable, ExecutionResource& resource); - - // Issue a resource with the specified timing parameters. - // The resource must be ready to be used. - void issue_to_resource( - const Cancellable* cancellable, ExecutionResource& resource, - WallDuration delay, WallDuration hold, WallDuration cooldown - ); - - -protected: - // - // This class will automatically call "push_state()" when a state is ready. - // The child class should send/queue this state to the device/Switch. - // - // This function is allowed to block. In other words, it can wait until - // there is space in the queue before returning. - // - // This will always be called inside one of the above "issue_XXX()" - // functions. Implementations of this method should be aware of this - // re-entrancy when this gets called on them with respect to locking. - // - virtual void push_state(const Cancellable* cancellable, WallDuration duration) = 0; - - -private: - void clear() noexcept; - bool iterate_schedule(const Cancellable* cancellable); - void process_schedule(const Cancellable* cancellable); - - -private: - Logger& m_logger; - - // We are allowed to gap the timeline if nothing has been issued in this - // much time. - const WallDuration m_flush_threshold; - - std::atomic m_pending_clear; - - // The construction time of this object. This is only used for debugging - // purposes since it lets you print wall times relative to this. - WallClock m_local_start; - - // Wall clock of the last time "m_device_issue_time" was last updated. - // This is used to decide when to gap the timeline. - WallClock m_local_last_activity; - - // The current timestamp of what has been issued to the scheduler. - WallClock m_device_issue_time; - - // The current timestamp of what has been sent to the device. - WallClock m_device_sent_time; - - // Maximum of: m_resources[]->m_free_time - WallClock m_max_free_time; - - // A set of all the scheduled state changes that will happen. Between - // timestamps in this set, the state is constant. - std::set m_state_changes; - - std::vector m_resources; -}; - - - - - -} -#endif +/* Superscalar Scheduler + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_SuperscalarScheduler_H +#define PokemonAutomation_Controllers_SuperscalarScheduler_H + +#include +#include +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/CancellableScope.h" + +namespace PokemonAutomation{ + +class SuperscalarScheduler; + + +class ExecutionResource{ +public: + virtual ~ExecutionResource() = default; + ExecutionResource() + : m_busy_time(WallClock::min()) + , m_done_time(WallClock::min()) + , m_free_time(WallClock::min()) + {} + + bool is_busy() const{ + return m_is_busy; + } + WallClock free_time() const{ + return m_free_time; + } + +private: + friend class SuperscalarScheduler; + bool m_is_busy = false; + WallClock m_busy_time; // Timestamp of when resource will be become busy. + WallClock m_done_time; // Timestamp of when resource will be done being busy. + WallClock m_free_time; // Timestamp of when resource can be used again. +}; + + + + + +class SuperscalarScheduler{ +public: + SuperscalarScheduler( + Logger& logger, + WallDuration flush_threshold, + std::vector resources + ); + + +public: + // This is intended to be run on a different thread from the functions in + // the next section. So it is safe to run from anywhere. + + void clear_on_next(){ + m_pending_clear.store(true, std::memory_order_release); + } + + +public: + // These are the standard "issue" commands. + // + // These functions may or may not block. + // These are not thread-safe with each other. + // + + // Wait until the pipeline has completely cleared and all resources have + // returned to the ready state. + void issue_wait_for_all(const Cancellable* cancellable); + + // Issue a do-nothing command for the specified delay. + // This will advance the issue timestamp. + void issue_nop(const Cancellable* cancellable, WallDuration delay); + + // Wait until the specified resource is ready to be used. + // This will advance the issue timestamp until the resource is ready. + void issue_wait_for_resource(const Cancellable* cancellable, ExecutionResource& resource); + + // Issue a resource with the specified timing parameters. + // The resource must be ready to be used. + void issue_to_resource( + const Cancellable* cancellable, ExecutionResource& resource, + WallDuration delay, WallDuration hold, WallDuration cooldown + ); + + +protected: + // + // This class will automatically call "push_state()" when a state is ready. + // The child class should send/queue this state to the device/Switch. + // + // This function is allowed to block. In other words, it can wait until + // there is space in the queue before returning. + // + // This will always be called inside one of the above "issue_XXX()" + // functions. Implementations of this method should be aware of this + // re-entrancy when this gets called on them with respect to locking. + // + virtual void push_state(const Cancellable* cancellable, WallDuration duration) = 0; + + +private: + void clear() noexcept; + void update_busy_states(); + bool iterate_schedule(const Cancellable* cancellable); + void process_schedule(const Cancellable* cancellable); + + +private: + Logger& m_logger; + + // We are allowed to gap the timeline if nothing has been issued in this + // much time. + const WallDuration m_flush_threshold; + + std::atomic m_pending_clear; + + // The construction time of this object. This is only used for debugging + // purposes since it lets you print wall times relative to this. + WallClock m_local_start; + + // Wall clock of the last time "m_device_issue_time" was last updated. + // This is used to decide when to gap the timeline. + WallClock m_local_last_activity; + + // The current timestamp of what has been issued to the scheduler. + WallClock m_device_issue_time; + + // The current timestamp of what has been sent to the device. + WallClock m_device_sent_time; + + // Maximum of: m_resources[]->m_free_time + WallClock m_max_free_time; + + // A set of all the scheduled state changes that will happen. Between + // timestamps in this set, the state is constant. + std::set m_state_changes; + + std::vector m_resources; +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/Integrations/DiscordIntegrationSettings.cpp b/SerialPrograms/Source/Integrations/DiscordIntegrationSettings.cpp index 4ed3c7223c..b2b538a435 100644 --- a/SerialPrograms/Source/Integrations/DiscordIntegrationSettings.cpp +++ b/SerialPrograms/Source/Integrations/DiscordIntegrationSettings.cpp @@ -11,7 +11,6 @@ //#include "CommonFramework/Globals.h" //#include "CommonFramework/GlobalSettingsPanel.h" #include "DppIntegration/DppClient.h" -#include "SleepyDiscordRunner.h" #include "DiscordIntegrationSettings.h" //#include @@ -23,7 +22,6 @@ namespace Integration{ DiscordIntegrationSettingsOption::~DiscordIntegrationSettingsOption(){ - library0.remove_listener(*this); this->remove_listener(*this); } DiscordIntegrationSettingsOption::DiscordIntegrationSettingsOption() @@ -38,15 +36,6 @@ DiscordIntegrationSettingsOption::DiscordIntegrationSettingsOption() LockMode::LOCK_WHILE_RUNNING, false ) - , library0( - "Discord Integration Library:
Restart the program for this to take effect.", - { - {Library::SleepyDiscord, "sleepy", "Sleepy Discord (normal commands, deprecated)"}, - {Library::DPP, "dpp", "D++ (slash commands and normal commands)"}, - }, - LockMode::LOCK_WHILE_RUNNING, - Library::DPP - ) , command_type( "Discord Integration Command Type:
Restart the program for this to take effect.", { @@ -68,11 +57,6 @@ DiscordIntegrationSettingsOption::DiscordIntegrationSettingsOption() LockMode::LOCK_WHILE_RUNNING, "^", "^" ) - , use_suffix( - "Use Suffix (Sleepy):
Use a suffix instead of a prefix for commands.", - LockMode::LOCK_WHILE_RUNNING, - false - ) , game_status( false, "Discord Game Status:
Enter a status message your bot would display.", @@ -85,18 +69,6 @@ DiscordIntegrationSettingsOption::DiscordIntegrationSettingsOption() LockMode::LOCK_WHILE_RUNNING, "", "Automation at your service!" ) - , sudo( - false, - "Discord Sudo (Sleepy):
Enter user ID(s) to grant sudo access to.", - LockMode::LOCK_WHILE_RUNNING, - "", "123456789012345678" - ) - , owner( - false, - "Discord Owner (Sleepy):
Enter the bot owner's ID (your own ID).", - LockMode::LOCK_WHILE_RUNNING, - "", "123456789012345678" - ) , allow_buttons_from_users( "Allow Buttons from Users:
Allow other users to issue button presses.", LockMode::LOCK_WHILE_RUNNING, @@ -104,68 +76,32 @@ DiscordIntegrationSettingsOption::DiscordIntegrationSettingsOption() ) { PA_ADD_OPTION(run_on_start); - PA_ADD_OPTION(library0); PA_ADD_OPTION(command_type); PA_ADD_OPTION(token); PA_ADD_OPTION(command_prefix); - PA_ADD_OPTION(use_suffix); PA_ADD_OPTION(game_status); PA_ADD_OPTION(hello_message); - PA_ADD_OPTION(sudo); - PA_ADD_OPTION(owner); PA_ADD_OPTION(allow_buttons_from_users); PA_ADD_OPTION(channels); DiscordIntegrationSettingsOption::on_config_value_changed(this); this->add_listener(*this); - library0.add_listener(*this); } void DiscordIntegrationSettingsOption::on_config_value_changed([[maybe_unused]] void* object){ // cout << this->enabled() << endl; -#if (defined PA_SLEEPY || defined PA_DPP) - bool options_enabled = this->enabled(); - switch (library0){ -#ifdef PA_SLEEPY - case Library::SleepyDiscord:{ - options_enabled &= !SleepyDiscordRunner::is_running(); - ConfigOptionState state = options_enabled ? ConfigOptionState::ENABLED : ConfigOptionState::DISABLED; - - library0.set_visibility(state); - command_type.set_visibility(ConfigOptionState::HIDDEN); - token.set_visibility(state); - game_status.set_visibility(state); - hello_message.set_visibility(state); - - command_prefix.set_visibility(state); - use_suffix.set_visibility(state); - sudo.set_visibility(state); - owner.set_visibility(state); - allow_buttons_from_users.set_visibility(ConfigOptionState::HIDDEN); - break; - } -#endif #ifdef PA_DPP - case Library::DPP:{ - options_enabled &= !DppClient::Client::instance().is_initialized(); - ConfigOptionState state = options_enabled ? ConfigOptionState::ENABLED : ConfigOptionState::DISABLED; - - library0.set_visibility(state); - command_type.set_visibility(state); - token.set_visibility(state); - game_status.set_visibility(state); - hello_message.set_visibility(state); - allow_buttons_from_users.set_visibility(state); - - command_prefix.set_visibility(state); - use_suffix.set_visibility(ConfigOptionState::HIDDEN); - sudo.set_visibility(ConfigOptionState::HIDDEN); - owner.set_visibility(ConfigOptionState::HIDDEN); - break; - } -#endif - default:; - } + bool options_enabled = this->enabled(); + options_enabled &= !DppClient::Client::instance().is_initialized(); + ConfigOptionState state = options_enabled ? ConfigOptionState::ENABLED : ConfigOptionState::DISABLED; + + command_type.set_visibility(state); + token.set_visibility(state); + game_status.set_visibility(state); + hello_message.set_visibility(state); + allow_buttons_from_users.set_visibility(state); + + command_prefix.set_visibility(state); #endif } @@ -181,7 +117,7 @@ ConfigWidget* DiscordIntegrationSettingsOption::make_QtWidget(QWidget& parent){ DiscordIntegrationSettingsWidget::DiscordIntegrationSettingsWidget(QWidget& parent, DiscordIntegrationSettingsOption& value) : GroupWidget(parent, value) { -#if (defined PA_SLEEPY || defined PA_DPP) +#ifdef PA_DPP QWidget* control_buttons = new QWidget(this); m_options_layout->insertWidget(0, control_buttons); @@ -207,38 +143,14 @@ DiscordIntegrationSettingsWidget::DiscordIntegrationSettingsWidget(QWidget& pare connect( button_start, &QPushButton::clicked, this, [this, &value](bool){ - switch (value.library0){ -#ifdef PA_SLEEPY - case DiscordIntegrationSettingsOption::Library::SleepyDiscord: - SleepyDiscordRunner::sleepy_connect(); - break; -#endif -#ifdef PA_DPP - case DiscordIntegrationSettingsOption::Library::DPP: - DppClient::Client::instance().connect(); - break; -#endif - default:; - } + DppClient::Client::instance().connect(); value.on_config_value_changed(this); } ); connect( button_stop, &QPushButton::clicked, this, [this, &value](bool){ - switch (value.library0){ -#ifdef PA_SLEEPY - case DiscordIntegrationSettingsOption::Library::SleepyDiscord: - SleepyDiscordRunner::sleepy_terminate(); - break; -#endif -#ifdef PA_DPP - case DiscordIntegrationSettingsOption::Library::DPP: - DppClient::Client::instance().disconnect(); - break; -#endif - default:; - } + DppClient::Client::instance().disconnect(); value.on_config_value_changed(this); } ); diff --git a/SerialPrograms/Source/Integrations/DiscordIntegrationSettings.h b/SerialPrograms/Source/Integrations/DiscordIntegrationSettings.h index d488952e1b..4020189462 100644 --- a/SerialPrograms/Source/Integrations/DiscordIntegrationSettings.h +++ b/SerialPrograms/Source/Integrations/DiscordIntegrationSettings.h @@ -29,12 +29,6 @@ class DiscordIntegrationSettingsOption : public GroupOption, private ConfigOptio BooleanCheckBoxOption run_on_start; - enum class Library{ - SleepyDiscord, - DPP, - }; - EnumDropdownOption library0; - enum class CommandType{ SlashCommands, MessageCommands, @@ -43,11 +37,8 @@ class DiscordIntegrationSettingsOption : public GroupOption, private ConfigOptio StringOption token; StringOption command_prefix; - BooleanCheckBoxOption use_suffix; StringOption game_status; StringOption hello_message; - StringOption sudo; - StringOption owner; BooleanCheckBoxOption allow_buttons_from_users; DiscordIntegrationTable channels; }; diff --git a/SerialPrograms/Source/Integrations/DiscordSettingsOption.cpp b/SerialPrograms/Source/Integrations/DiscordSettingsOption.cpp index 5106f542c5..2785a93fcd 100644 --- a/SerialPrograms/Source/Integrations/DiscordSettingsOption.cpp +++ b/SerialPrograms/Source/Integrations/DiscordSettingsOption.cpp @@ -70,7 +70,7 @@ DiscordSettingsOption::DiscordSettingsOption() { PA_ADD_OPTION(message); PA_ADD_OPTION(webhooks); -#if defined PA_SLEEPY || defined PA_DPP +#ifdef PA_DPP PA_ADD_OPTION(integration); #endif } diff --git a/SerialPrograms/Source/Integrations/SleepyDiscordRunner.cpp b/SerialPrograms/Source/Integrations/SleepyDiscordRunner.cpp deleted file mode 100644 index 2e3203f0ef..0000000000 --- a/SerialPrograms/Source/Integrations/SleepyDiscordRunner.cpp +++ /dev/null @@ -1,634 +0,0 @@ - -#ifdef PA_SLEEPY - -#include -#include -#include -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/StringTools.h" -#include "Common/Cpp/PanicDump.h" -#include "Common/Cpp/Concurrency/ScheduledTaskRunner.h" -#include "Common/Qt/StringToolsQt.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/Notifications/EventNotificationOption.h" -#include "IntegrationsAPI.h" -#include "SleepyDiscordRunner.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace Integration{ -namespace SleepyDiscordRunner{ - -using namespace SleepyDiscord; -const char* enum_str_callback[] = { - "Fault", - "API", - "Disconnected", - "Connected", - "Settings Initialized", - "Settings Updated", - "Commands Initialized", - "Callbacks Set", - "Invalid Command", - "Terminating", - "Remove File", -}; - -const char* enum_str_command[] = { - "Click", - "Click DPad", - - "Left Stick", - "Right Stick", - - "Screenshot JPG", - "Screenshot PNG", - "Start", - "Stop", - "Shutdown", - "Get Connected Bots", - "Reload Settings", - "Reset Camera", - "Reset Serial", - "Terminate", - - "Hi", - "Ping", - "About", - "Help", -}; - -const char* enum_str_state[] = { - "STOPPED", - "RUNNING", - "FINISHED", - "STOPPING", -}; - -std::unordered_map str_buttons = { - { 1, "Y" }, - { 2, "B" }, - { 4, "A" }, - { 8, "X" }, - { 16, "L" }, - { 32, "R" }, - { 64, "ZL" }, - { 128, "ZR" }, - { 256, "MINUS" }, - { 512, "PLUS" }, - { 1024, "LStick" }, - { 2048, "RStick" }, - { 4096, "HOME" }, - { 8192, "Capture" }, -}; - -std::unordered_map str_dpad = { - { 0, "DUp" }, - { 2, "DRight" }, - { 4, "DDown" }, - { 6, "DLeft" }, -}; - - -Logger& sleepy_logger(){ - static TaggedLogger logger(global_logger_raw(), "SleepyDiscord"); - return logger; -} - - -struct SleepyDiscordRequest{ - SleepyDiscordRequest() = default; - SleepyDiscordRequest(std::string embed, std::string channels, std::string messages, std::shared_ptr file) : - embed(std::move(embed)), - channels(std::move(channels)), - messages(std::move(messages)), - file(std::move(file)) {} - - std::string embed; - std::string channels; - std::string messages; - std::shared_ptr file; -}; - -class SleepyDiscordSender{ -private: - SleepyDiscordSender() -// : m_stopping(false) -// , m_thread(run_with_catch, "SleepyDiscordSender::thread_loop()", [this]{ thread_loop(); }) - : m_dispatcher(nullptr, 1) - , m_queue(m_dispatcher) - {} - ~SleepyDiscordSender(){ -// { -// std::lock_guard lg(m_lock); -// m_stopping = true; -// m_cv.notify_all(); -// } -// m_thread.join(); - } - -public: - static SleepyDiscordSender& instance(){ - static SleepyDiscordSender sender; - return sender; - } - - void send( - std::string embed, - std::string channels, - std::chrono::milliseconds delay, - std::string messages, - std::shared_ptr file - ){ -// std::lock_guard lg(m_lock); - m_queue.add_event( - delay > std::chrono::milliseconds(10000) ? std::chrono::milliseconds(0) : delay, - [embed = std::move(embed), channels = std::move(channels), messages = std::move(messages), file = std::move(file)]() mutable { - if (file == nullptr || file->filepath().empty()){ - sendMessage(&channels[0], &messages[0], &embed[0], nullptr); - }else{ - std::string filepath = file->filepath(); - sendMessage(&channels[0], &messages[0], &embed[0], &filepath[0]); - } - } - ); - sleepy_logger().log("Sending notification... (queue = " + tostr_u_commas(m_queue.size()) + ")", COLOR_PURPLE); -// m_queue.emplace_back(embed, channels, messages, std::move(file)); -// m_cv.notify_all(); - - } - -private: -#if 0 - void thread_loop(){ - while (true){ - SleepyDiscordRequest item; - { - std::unique_lock lg(m_lock); - if (m_stopping){ - break; - } - if (m_queue.empty()){ - m_cv.wait(lg); - continue; - } - - item = std::move(m_queue.front()); - m_queue.pop_front(); - } - - if (item.file != nullptr && !item.file->filepath().empty()){ - std::string filepath = item.file->filepath(); - sendMessage(&item.channels[0], &item.messages[0], &item.embed[0], &filepath[0]); - }else sendMessage(&item.channels[0], &item.messages[0], &item.embed[0], nullptr); - } - } -#endif - -private: -// bool m_stopping; -// std::mutex m_lock; -// std::condition_variable m_cv; -// std::deque m_queue; -// std::thread m_thread; - AsyncDispatcher m_dispatcher; - ScheduledTaskRunner m_queue; -}; - -class SleepyDiscordClient; -std::unique_ptr m_sleepy_client; - -std::mutex m_connect_lock; -std::mutex m_client_lock; - - - - - -struct CommandArgs{ - uint64_t id; - uint16_t button; - uint16_t hold_ticks; - uint8_t x; - uint8_t y; -}; - - -class SleepyDiscordClient{ -public: - bool m_connected = false; - -public: - void send( - std::string embed, - std::string channels, - std::chrono::milliseconds delay, - std::string messages, - std::shared_ptr file - ){ - if (m_sleepy_client != nullptr){ - if (file){ -// cout << "Sending: " << file->filepath().toStdString() << endl; - m_active_list.emplace(file->filepath(), file); - } - SleepyDiscordSender::instance().send(embed, channels, delay, messages, std::move(file)); - }else{ - sleepy_logger().log("SleepyDiscordClient::send(): Not connected.", COLOR_RED); - } - } - - void callback(int response, const char* message){ - if (m_sleepy_client == nullptr){ - return; - } - - std::string msg = (std::string)message + " (Callback: " + (std::string)enum_str_callback[response] + ")"; - Color color = response == SleepyResponse::Disconnected || response == SleepyResponse::Fault ? COLOR_RED : COLOR_PURPLE; - - switch (response){ - case SleepyResponse::Connected: m_connected = true; break; - case SleepyResponse::Disconnected: m_connected = false; break; - case SleepyResponse::RemoveFile:{ -#if 1 - auto iter = m_active_list.find(message); -// cout << "Removing: " << message << endl; -// cout << "m_active_list = " << m_active_list.size() << endl; - if (iter != m_active_list.end()){ - msg = "Marking sent file as done. (Callback: " + (std::string)enum_str_callback[response] + ")"; - m_active_list.erase(iter); - }else{ - msg = "Unknown sent file. (Callback: " + (std::string)enum_str_callback[response] + ")"; -// color = COLOR_RED; - } - m_active_list.erase(message); -#else - bool success = QFile(message).remove(); - if (success){ - msg = "Removed sent file. (Callback: " + (std::string)enum_str_callback[response] + ")"; - }else{ - msg = "Failed to remove sent file. (Callback: " + (std::string)enum_str_callback[response] + ")"; - color = COLOR_RED; - } -#endif - break; - } - } - - sleepy_logger().log(msg, color); - } - - void cmd_callback(SleepyRequest request, char* channel, uint64_t id, uint16_t button, uint16_t hold_ticks, uint8_t x, uint8_t y){ - if (m_sleepy_client == nullptr){ - return; - } - - cout << "cmd_callback(): " << request << endl; - - std::string cmd = "Received command: " + (std::string)enum_str_command[request] + "."; - sleepy_logger().log(cmd, COLOR_PURPLE); - - switch (request){ - case SleepyRequest::Click: - run_Click(channel, id, hold_ticks, button); - break; - case SleepyRequest::DPad: - run_DPad(channel, id, hold_ticks, button); - break; - case SleepyRequest::SetLStick: - run_SetLStick(channel, id, hold_ticks, x, y); - return; - case SleepyRequest::SetRStick: - run_SetRStick(channel, id, hold_ticks, x, y); - return; - case SleepyRequest::ScreenshotJpg: - run_ScreenshotJpg(channel, id); - return; - case SleepyRequest::ScreenshotPng: - run_ScreenshotPng(channel, id); - return; - case SleepyRequest::Start: - run_start(channel, id); - break; - case SleepyRequest::Stop: - run_stop(channel, id); - break; - case SleepyRequest::Shutdown: - run_Shutdown(); - return; - case SleepyRequest::GetConnectedBots: - run_GetConnectedBots(channel); - return; - case SleepyRequest::ReloadSettings: - run_ReloadSettings(channel); - return; - case SleepyRequest::ResetCamera: - run_ResetCamera(channel, id); - return; - case SleepyRequest::ResetSerial: - run_ResetSerial(channel, id); - return; - } - } - - - -private: - void send_response(SleepyRequest request, char* channel, std::string message, std::shared_ptr file = nullptr){ - std::string filename = file == nullptr ? "" : file->filepath(); - if ((int)request <= 11){ - program_response(request, channel, &message[0], &filename[0]); - }else{ - send("", channel, std::chrono::milliseconds(0), &message[0], std::move(file)); - } - } - - void run_Click(char* channel, uint64_t id, uint16_t hold_ticks, uint16_t button){ - std::string message; - auto it = str_buttons.find(button); - if (it == str_buttons.end()){ - message = "Unrecognized button input"; - }else{ - message = Integration::press_button(id, button, hold_ticks); - } - if (message.empty()){ - message = "Console ID " + std::to_string(id) + " clicked " + it->second + "."; - } - send_response(SleepyRequest::Click, channel, message); - } - void run_DPad(char* channel, uint64_t id, uint16_t hold_ticks, uint16_t button){ - std::string message; - auto it = str_dpad.find(button); - if (it == str_dpad.end()){ - message = "Unrecognized button input"; - }else{ - message = Integration::press_dpad(id, button, hold_ticks); - } - if (message.empty()){ - message = "Console ID " + std::to_string(id) + " clicked " + it->second + "."; - } - send_response(SleepyRequest::DPad, channel, message); - } - void run_SetLStick(char* channel, uint64_t id, uint16_t hold_ticks, uint8_t x, uint8_t y){ - std::string message = Integration::press_left_joystick(id, x, y, hold_ticks); - if (message.empty()){ - message = "Console ID " + std::to_string(id) + " moved the left joystick."; - } - send_response(SleepyRequest::SetLStick, channel, message); - } - void run_SetRStick(char* channel, uint64_t id, uint16_t hold_ticks, uint8_t x, uint8_t y){ - std::string message = Integration::press_right_joystick(id, x, y, hold_ticks); - if (message.empty()){ - message = "Console ID " + std::to_string(id) + " moved the right joystick."; - } - send_response(SleepyRequest::SetRStick, channel, message); - } - void run_ScreenshotPng(char* channel, uint64_t id){ - std::string filepath = "capture.png"; - std::string message = Integration::screenshot(id, filepath.c_str()); - if (!message.empty()){ - send_response(SleepyRequest::ScreenshotPng, channel, message); - return; - }else{ - message = "Captured image from console ID " + std::to_string(id) + "."; - } - - std::shared_ptr file(new PendingFileSend(filepath, true)); - send_response(SleepyRequest::ScreenshotPng, channel, message, std::move(file)); - } - void run_ScreenshotJpg(char* channel, uint64_t id){ - std::string filepath = "capture.jpg"; - std::string message = Integration::screenshot(id, filepath.c_str()); - if (!message.empty()){ - send_response(SleepyRequest::ScreenshotJpg, channel, message); - return; - }else{ - message = "Captured image from console ID " + std::to_string(id) + "."; - } - - std::shared_ptr file(new PendingFileSend(filepath, true)); - send_response(SleepyRequest::ScreenshotJpg, channel, message, std::move(file)); - } - void run_start(char* channel, uint64_t id){ - std::string message = Integration::start_program(id); - if (!message.empty()){ - send_response(SleepyRequest::Start, channel, message); - return; - }else{ - message = "Console ID " + std::to_string(id) + " started the program."; - } - send_response(SleepyRequest::Start, channel, message); - } - void run_stop(char* channel, uint64_t id){ - std::string message = Integration::stop_program(id); - if (!message.empty()){ - send_response(SleepyRequest::Stop, channel, message); - return; - }else{ - message = "Console ID " + std::to_string(id) + " stopped the program."; - } - send_response(SleepyRequest::Stop, channel, message); - } - void run_Shutdown(){ - program_response(SleepyRequest::Terminate); - m_sleepy_client.reset(); - - // TODO: Can't do this since it skips all the shutdown sequence from all the other threads. - exit(0); - } - void run_GetConnectedBots(char* channel){ - std::string message = Integration::status(); - send_response(SleepyRequest::GetConnectedBots, channel, message); - } - void run_ReloadSettings(char* channel){ - std::string message = initialize_sleepy_settings() - ? "Successfully reloaded Discord settings." - : "Failed to reload Discord settings."; - send_response(SleepyRequest::ReloadSettings, channel, message); - } - void run_ResetCamera(char* channel, uint64_t id){ - std::string message = Integration::reset_camera(id); - send_response(SleepyRequest::ResetCamera, channel, message.empty() ? "Camera was reset." : message); - } - void run_ResetSerial(char* channel, uint64_t id){ - std::string message = Integration::reset_serial(id); - send_response(SleepyRequest::ResetSerial, channel, message); - } - - std::map> m_active_list; -}; - - - - - - - -bool is_running(){ - std::lock_guard lg(m_connect_lock); - return m_sleepy_client != nullptr; -} - -bool is_connected(){ - std::lock_guard lg(m_connect_lock); - return m_sleepy_client != nullptr && m_sleepy_client->m_connected; -} - -void sleepy_connect(){ - std::lock_guard lg(m_connect_lock); - { -// std::lock_guard lg(m_client_lock); -// if (!PreloadSettings::instance().DEVELOPER_MODE){ -// return; -// } - if (m_sleepy_client != nullptr){ - sleepy_logger().log("sleepy_connect(): Already initialized!", COLOR_PURPLE); - return; - } - if (!initialize_sleepy_settings()){ - sleepy_logger().log("sleepy_connect(): initialize_sleepy_settings() failed.", COLOR_RED); - return; - } - sleepy_logger().log("Connecting...", COLOR_PURPLE); - } - client_connect(); - sleepy_logger().log("Finished Connecting...", COLOR_PURPLE); -} - -void sleepy_terminate(){ - std::lock_guard lg(m_client_lock); - program_response(SleepyRequest::Terminate); - if (m_sleepy_client != nullptr){ - m_sleepy_client.reset(); - } -} - -void sleepy_response(int response, char* message){ - //std::lock_guard lg(m_client_lock); - if (m_sleepy_client != nullptr){ - return m_sleepy_client->callback(response, message); - } -} - -void sleepy_cmd_response(int request, char* channel, uint64_t console_id, uint16_t button, uint16_t hold_ticks, uint8_t x, uint8_t y){ - std::lock_guard lg(m_client_lock); - if (m_sleepy_client != nullptr){ - return m_sleepy_client->cmd_callback((SleepyRequest)request, channel, console_id, button, hold_ticks, x, y); - } -} - -void send_embed_sleepy( - bool should_ping, - const std::vector& tags, - const JsonObject& embed, - std::shared_ptr file -){ - DiscordSettingsOption& settings = GlobalSettings::instance().DISCORD; - if (!settings.integration.enabled()){ - return; - } - - std::lock_guard lg(m_client_lock); - if (m_sleepy_client == nullptr){ - return; - } - - MessageBuilder builder(tags); - const DiscordIntegrationTable& channels = settings.integration.channels; - - std::vector> table = channels.copy_snapshot(); - for (size_t i = 0; i < table.size(); i++){ - const Integration::DiscordIntegrationChannel& channel = *table[i]; - if (((std::string)channel.tags_text).empty() || !channel.enabled){ - continue; - } - if (!builder.should_send(EventNotificationOption::parse_tags(channel.tags_text))){ - continue; - } - - sleepy_logger().log("send_message_sleepy(): Sending...", COLOR_PURPLE); - std::chrono::seconds delay(channel.delay); - m_sleepy_client->send( - embed.dump(), - channel.channel_id, - std::chrono::seconds(delay), - builder.build_message( - std::chrono::seconds(delay), - should_ping && channel.ping, - settings.message.user_id, - settings.message.message - ), - file == nullptr ? nullptr : file - ); - } -} - - -bool initialize_sleepy_settings(){ - // Must be called inside lock. -// std::lock_guard lg(m_client_lock); - DiscordSettingsOption& settings = GlobalSettings::instance().DISCORD; - if (!check_if_empty(settings)){ - return false; - } - - bool suffix = settings.integration.use_suffix; - std::string param_string; - param_string += StringTools::replace(settings.integration.token, " ", "") + "|"; - param_string += (std::string)settings.integration.command_prefix + "|"; - param_string += StringTools::replace(settings.integration.owner, " ", "") + "|"; - param_string += (std::string)settings.integration.game_status + "|"; - param_string += StringTools::replace(settings.integration.hello_message, "@", "") + "|"; - param_string += PROGRAM_VERSION + "|"; - param_string += PROJECT_SOURCE_URL; - - std::string sudo = StringTools::replace(settings.integration.sudo, " ", ""); - -// std::string w_channels = StringTools::replace(settings.integration.channels_whitelist.get(), " ", ""); - std::string w_channels; - for (const std::string& channel_id : settings.integration.channels.command_channels()){ - if (!w_channels.empty()){ - w_channels += ","; - } - w_channels += channel_id; - } - - m_sleepy_client = std::unique_ptr(new SleepyDiscordClient()); - apply_settings(sleepy_response, sleepy_cmd_response, &w_channels[0], &sudo[0], ¶m_string[0], suffix); - return true; -} - -bool check_if_empty(const DiscordSettingsOption& settings){ - - if (!settings.integration.enabled()){ - return false; - } - if (((std::string)settings.integration.token).empty()){ - return false; - }else if (((std::string)settings.integration.token).find(",") != std::string::npos){ - sleepy_logger().log("\"Token\" must only contain one token. Stopping...", COLOR_RED); - return false; - }else if (((std::string)settings.integration.owner).find(",") != std::string::npos){ - sleepy_logger().log("\"Owner\" must only contain one Discord ID (yours). Stopping...", COLOR_RED); - return false; - }else if (((std::string)settings.integration.command_prefix).empty()){ - sleepy_logger().log("Please enter a Discord command prefix. Stopping...", COLOR_RED); - return false; - } - return true; -} - - - - - -} -} -} -#endif diff --git a/SerialPrograms/Source/Integrations/SleepyDiscordRunner.h b/SerialPrograms/Source/Integrations/SleepyDiscordRunner.h deleted file mode 100644 index 4c85fd79e0..0000000000 --- a/SerialPrograms/Source/Integrations/SleepyDiscordRunner.h +++ /dev/null @@ -1,105 +0,0 @@ -#ifndef PokemonAutomation_SleepyPA_H -#define PokemonAutomation_SleepyPA_H - -#include -#include "CommonFramework/PersistentSettings.h" -#include "CommonFramework/Options/ScreenshotFormatOption.h" -#include "CommonFramework/Notifications/MessageAttachment.h" -#include "Integrations/DiscordSettingsOption.h" - -#ifdef SLEEPY_STATIC - #define SLEEPY_EXPORT -#else - -#ifdef _WIN32 -#ifdef _WINDLL - #define SLEEPY_EXPORT __declspec(dllexport) -#else - #define SLEEPY_EXPORT __declspec(dllimport) -#endif - -#else - #define SLEEPY_EXPORT __attribute__((visibility("default"))) -#endif -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -namespace SleepyDiscord{ - typedef void (*SleepyCallback)(int response, char* message); - typedef void (*SleepyCommandCallback)(int request, char* channel, uint64_t console_id, uint16_t button, uint16_t hold_ticks, uint8_t x, uint8_t y); - SLEEPY_EXPORT void client_connect(); - SLEEPY_EXPORT void client_disconnect(); - SLEEPY_EXPORT void apply_settings(SleepyCallback callback, SleepyCommandCallback cmd_callback, char* w_channels, char* sudo, char* params, bool suffix); - SLEEPY_EXPORT void program_response(int response, char* channel = nullptr, char* message = nullptr, char* filepath = nullptr); - SLEEPY_EXPORT void sendMessage(char* channels, char* messages = nullptr, char* json = nullptr, char* filePath = nullptr); - void client_run(); - -enum SleepyResponse{ - Fault = 0, - API = 1, - Disconnected = 2, - Connected = 3, - SettingsInitialized = 4, - SettingsUpdated = 5, - CommandsInitialized = 6, - CallbacksSet = 7, - InvalidCommand = 8, - Terminating = 9, - RemoveFile = 10, -}; - -enum SleepyRequest{ - Click = 0, - DPad = 1, - - SetLStick = 2, - SetRStick = 3, - - ScreenshotJpg = 4, - ScreenshotPng = 5, - Start = 6, - Stop = 7, - Shutdown = 8, - GetConnectedBots = 9, - ReloadSettings = 10, - ResetCamera = 11, - ResetSerial = 12, - Terminate = 13, - - Hi = 14, - Ping = 15, - About = 16, - Help = 17, -}; -} - -#ifdef __cplusplus -} - -namespace PokemonAutomation{ -namespace Integration{ -namespace SleepyDiscordRunner{ - - bool is_running(); - bool is_connected(); - void send_embed_sleepy( - bool should_ping, - const std::vector& tags, - const JsonObject& embed, - std::shared_ptr file - ); - void sleepy_response(int response, char* message); - void sleepy_cmd_response(int request, char* channel, uint64_t console_id, uint16_t button, uint16_t hold_ticks, uint8_t x, uint8_t y); - void sleepy_connect(); - void sleepy_terminate(); - bool initialize_sleepy_settings(); - bool check_if_empty(const DiscordSettingsOption& settings); -} -} -} - -#endif -#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_ARM64_NEON.cpp b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_ARM64_NEON.cpp index 9372867f7b..b52f699ef7 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_ARM64_NEON.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_ARM64_NEON.cpp @@ -1,35 +1,35 @@ -/* Image Filters Basic (arm64 NEON) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_arm64_20_M1 - -#include -#include -#include "Kernels/Kernels_arm64_NEON.h" -// #include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h" -#include "Kernels_ImageFilter_Basic_Routines.h" - -#include -#include - -namespace PokemonAutomation{ -namespace Kernels{ - - - - - - - - - - - - - -} -} -#endif +/* Image Filters Basic (arm64 NEON) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_arm64_20_M1 + +#include +#include +#include "Kernels/Kernels_arm64_NEON.h" +// #include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h" +#include "Kernels_ImageFilter_Basic_Routines.h" + +#include +#include + +namespace PokemonAutomation{ +namespace Kernels{ + + + + + + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_ARM64_NEON.h b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_ARM64_NEON.h index f3b363d411..fcaa6ebd36 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_ARM64_NEON.h +++ b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_ARM64_NEON.h @@ -1,154 +1,154 @@ -/* Image Filters Basic Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Compiler.h" -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h" -#include "Kernels/Kernels_arm64_NEON.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - - -template -class FilterImage_Rgb32_ARM64_NEON{ -public: - static const size_t VECTOR_SIZE = 4; - using Mask = size_t; - -public: - FilterImage_Rgb32_ARM64_NEON( - const PixelTester& tester, - uint32_t replacement_color, bool replace_color_within_range - ) - : m_tester(tester) - , m_replacement_color_u32(vdupq_n_u32(replacement_color)) - , m_replace_color_within_range(replace_color_within_range) - , m_count_u32(vdupq_n_u32(0)) - {} - - PA_FORCE_INLINE size_t count() const{ - // long pairwise add - uint64x2_t sum_u64 = vpaddlq_u32(m_count_u32); - return sum_u64[0] + sum_u64[1]; - } - - // Given 4 pixels from in[4], apply color range comparison and count the pixels that are in range. - // The counts are stored in m_count_u32. - // If a per-pixel mask, cmp_mask_u32 is not nullptr, it only counts the pixels covered by the mask. - // It also changes pixels in or out of the range to have the new color m_replacement_color_u32. - // The resulting pixels are saved in out[4] - PA_FORCE_INLINE void process_full(uint32_t out[4], const uint32_t in[4], const uint32x4_t* cmp_mask_u32 = nullptr){ - uint32x4_t pixel = vld1q_u32(in); - // If a pixel is within [mins, maxs], its uint32_t in `cmp_u32` is all 1 bits, otherwise, all 0 bits - uint32x4_t cmp_u32 = m_tester.test_word(pixel); - if (cmp_mask_u32) { - cmp_u32 = vandq_u32(cmp_u32, *cmp_mask_u32); - } - // Increase count for each pixel in range. Each uint32 lane is counted separately. - // We achieve +=1 by substracting 0xFFFFFFFF - m_count_u32 = vsubq_u32(m_count_u32, cmp_u32); - // select replacement color or in_u8 based on cmp_u32: - uint32x4_t out_u32; - if (m_replace_color_within_range){ - // vbslq_u32(a, b, c) for 1 bits in a, choose b; for 0 bits in a, choose c - out_u32 = vbslq_u32(cmp_u32, m_replacement_color_u32, pixel); - }else{ - out_u32 = vbslq_u32(cmp_u32, pixel, m_replacement_color_u32); - } - vst1q_u32(out, out_u32); - } - // Same as `process_full()` but only process `left` (< 4) pixels - PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, size_t left){ - uint32x4_t cmp_mask_u32 = vreinterpretq_u32_u8(PartialWordAccess_arm64_NEON::create_front_mask(left * 4)); - uint32_t buffer_in[4], buffer_out[4]; - memcpy(buffer_in, in, sizeof(uint32_t) * left); - process_full(buffer_out, buffer_in, &cmp_mask_u32); - memcpy(out, buffer_out, sizeof(uint32_t) * left); - } - -private: - const PixelTester m_tester; - uint32x4_t m_replacement_color_u32; - bool m_replace_color_within_range; - uint32x4_t m_count_u32; -}; - - - - - - - -template -class ToBlackWhite_Rgb32_ARM64_NEON{ -public: - static const size_t VECTOR_SIZE = 4; - using Mask = size_t; - -public: - ToBlackWhite_Rgb32_ARM64_NEON( - const PixelTester& tester, - bool in_range_black - ) - : m_tester(tester) - , m_in_range_color_u32(vdupq_n_u32(in_range_black ? 0xFF000000 : 0xFFFFFFFF)) - , m_out_of_range_color_u32(vdupq_n_u32(in_range_black ? 0xFFFFFFFF : 0xFF000000)) - , m_count_u32(vdupq_n_u32(0)) - {} - - PA_FORCE_INLINE size_t count() const{ - uint64x2_t sum_u64 = vpaddlq_u32(m_count_u32); - return sum_u64[0] + sum_u64[1]; - } - - // Given 4 pixels from in[4], apply color range comparison and count the pixels that are in range. - // The counts are stored in m_count_u32. - // If a per-pixel mask, cmp_mask_u32 is not nullptr, it only counts the pixels covered by the mask. - // It also changes pixels into black or white depending on whether they are in range. - // The resulting pixels are saved in out[4] - PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in, const uint32x4_t* cmp_mask_u32 = nullptr){ - uint32x4_t pixel = vld1q_u32(in); - // If a pixel is within [mins, maxs], its uint32_t in `cmp_u32` is all 1 bits, otherwise, all 0 bits - uint32x4_t cmp_u32 = m_tester.test_word(pixel); - if (cmp_mask_u32) { - cmp_u32 = vandq_u32(cmp_u32, *cmp_mask_u32); - } - // Increase count for each pixel in range. Each uint32 lane is counted separately. - // We achieve +=1 by substracting 0xFFFFFFFF - m_count_u32 = vsubq_u32(m_count_u32, cmp_u32); - // select replacement color or in_u8 based on cmp_u32: - uint32x4_t out_u32; - // vbslq_u32(a, b, c) for 1 bits in a, choose b; for 0 bits in a, choose c - out_u32 = vbslq_u32(cmp_u32, m_in_range_color_u32, m_out_of_range_color_u32); - - vst1q_u32(out, out_u32); - } - - // Same as `process_full()` but only process `left` (< 4) pixels - PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, size_t left){ - uint32x4_t cmp_mask_u32 = vreinterpretq_u32_u8(PartialWordAccess_arm64_NEON::create_front_mask(left * 4)); - uint32_t buffer_in[4], buffer_out[4]; - memcpy(buffer_in, in, sizeof(uint32_t) * left); - process_full(buffer_out, buffer_in, &cmp_mask_u32); - memcpy(out, buffer_out, sizeof(uint32_t) * left); - } - -private: - const PixelTester m_tester; - uint32x4_t m_in_range_color_u32; - uint32x4_t m_out_of_range_color_u32; - uint32x4_t m_count_u32; -}; - - - - - -} -} +/* Image Filters Basic Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Compiler.h" +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h" +#include "Kernels/Kernels_arm64_NEON.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + + +template +class FilterImage_Rgb32_ARM64_NEON{ +public: + static const size_t VECTOR_SIZE = 4; + using Mask = size_t; + +public: + FilterImage_Rgb32_ARM64_NEON( + const PixelTester& tester, + uint32_t replacement_color, bool replace_color_within_range + ) + : m_tester(tester) + , m_replacement_color_u32(vdupq_n_u32(replacement_color)) + , m_replace_color_within_range(replace_color_within_range) + , m_count_u32(vdupq_n_u32(0)) + {} + + PA_FORCE_INLINE size_t count() const{ + // long pairwise add + uint64x2_t sum_u64 = vpaddlq_u32(m_count_u32); + return sum_u64[0] + sum_u64[1]; + } + + // Given 4 pixels from in[4], apply color range comparison and count the pixels that are in range. + // The counts are stored in m_count_u32. + // If a per-pixel mask, cmp_mask_u32 is not nullptr, it only counts the pixels covered by the mask. + // It also changes pixels in or out of the range to have the new color m_replacement_color_u32. + // The resulting pixels are saved in out[4] + PA_FORCE_INLINE void process_full(uint32_t out[4], const uint32_t in[4], const uint32x4_t* cmp_mask_u32 = nullptr){ + uint32x4_t pixel = vld1q_u32(in); + // If a pixel is within [mins, maxs], its uint32_t in `cmp_u32` is all 1 bits, otherwise, all 0 bits + uint32x4_t cmp_u32 = m_tester.test_word(pixel); + if (cmp_mask_u32) { + cmp_u32 = vandq_u32(cmp_u32, *cmp_mask_u32); + } + // Increase count for each pixel in range. Each uint32 lane is counted separately. + // We achieve +=1 by substracting 0xFFFFFFFF + m_count_u32 = vsubq_u32(m_count_u32, cmp_u32); + // select replacement color or in_u8 based on cmp_u32: + uint32x4_t out_u32; + if (m_replace_color_within_range){ + // vbslq_u32(a, b, c) for 1 bits in a, choose b; for 0 bits in a, choose c + out_u32 = vbslq_u32(cmp_u32, m_replacement_color_u32, pixel); + }else{ + out_u32 = vbslq_u32(cmp_u32, pixel, m_replacement_color_u32); + } + vst1q_u32(out, out_u32); + } + // Same as `process_full()` but only process `left` (< 4) pixels + PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, size_t left){ + uint32x4_t cmp_mask_u32 = vreinterpretq_u32_u8(PartialWordAccess_arm64_NEON::create_front_mask(left * 4)); + uint32_t buffer_in[4], buffer_out[4]; + memcpy(buffer_in, in, sizeof(uint32_t) * left); + process_full(buffer_out, buffer_in, &cmp_mask_u32); + memcpy(out, buffer_out, sizeof(uint32_t) * left); + } + +private: + const PixelTester m_tester; + uint32x4_t m_replacement_color_u32; + bool m_replace_color_within_range; + uint32x4_t m_count_u32; +}; + + + + + + + +template +class ToBlackWhite_Rgb32_ARM64_NEON{ +public: + static const size_t VECTOR_SIZE = 4; + using Mask = size_t; + +public: + ToBlackWhite_Rgb32_ARM64_NEON( + const PixelTester& tester, + bool in_range_black + ) + : m_tester(tester) + , m_in_range_color_u32(vdupq_n_u32(in_range_black ? 0xFF000000 : 0xFFFFFFFF)) + , m_out_of_range_color_u32(vdupq_n_u32(in_range_black ? 0xFFFFFFFF : 0xFF000000)) + , m_count_u32(vdupq_n_u32(0)) + {} + + PA_FORCE_INLINE size_t count() const{ + uint64x2_t sum_u64 = vpaddlq_u32(m_count_u32); + return sum_u64[0] + sum_u64[1]; + } + + // Given 4 pixels from in[4], apply color range comparison and count the pixels that are in range. + // The counts are stored in m_count_u32. + // If a per-pixel mask, cmp_mask_u32 is not nullptr, it only counts the pixels covered by the mask. + // It also changes pixels into black or white depending on whether they are in range. + // The resulting pixels are saved in out[4] + PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in, const uint32x4_t* cmp_mask_u32 = nullptr){ + uint32x4_t pixel = vld1q_u32(in); + // If a pixel is within [mins, maxs], its uint32_t in `cmp_u32` is all 1 bits, otherwise, all 0 bits + uint32x4_t cmp_u32 = m_tester.test_word(pixel); + if (cmp_mask_u32) { + cmp_u32 = vandq_u32(cmp_u32, *cmp_mask_u32); + } + // Increase count for each pixel in range. Each uint32 lane is counted separately. + // We achieve +=1 by substracting 0xFFFFFFFF + m_count_u32 = vsubq_u32(m_count_u32, cmp_u32); + // select replacement color or in_u8 based on cmp_u32: + uint32x4_t out_u32; + // vbslq_u32(a, b, c) for 1 bits in a, choose b; for 0 bits in a, choose c + out_u32 = vbslq_u32(cmp_u32, m_in_range_color_u32, m_out_of_range_color_u32); + + vst1q_u32(out, out_u32); + } + + // Same as `process_full()` but only process `left` (< 4) pixels + PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, size_t left){ + uint32x4_t cmp_mask_u32 = vreinterpretq_u32_u8(PartialWordAccess_arm64_NEON::create_front_mask(left * 4)); + uint32_t buffer_in[4], buffer_out[4]; + memcpy(buffer_in, in, sizeof(uint32_t) * left); + process_full(buffer_out, buffer_in, &cmp_mask_u32); + memcpy(out, buffer_out, sizeof(uint32_t) * left); + } + +private: + const PixelTester m_tester; + uint32x4_t m_in_range_color_u32; + uint32x4_t m_out_of_range_color_u32; + uint32x4_t m_count_u32; +}; + + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_Default.h b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_Default.h index b929df98db..94635b245c 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_Default.h +++ b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_Default.h @@ -1,102 +1,102 @@ -/* Image Filters Basic Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Compiler.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - - - -template -class FilterImage_Rgb32_Default{ -public: - static const size_t VECTOR_SIZE = 1; - using Mask = size_t; - -public: - FilterImage_Rgb32_Default( - const PixelTester& tester, - uint32_t replacement_color, bool replace_color_within_range - ) - : m_tester(tester) - , m_replacement_color(replacement_color) - , m_replace_color_within_range(replace_color_within_range) - , m_count(0) - {} - - PA_FORCE_INLINE size_t count() const{ - return m_count; - } - - PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ - uint32_t pixel = in[0]; - bool passed = m_tester.test_word(pixel); - m_count += passed; - passed ^= m_replace_color_within_range; - out[0] = passed ? pixel : m_replacement_color; - } - PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, size_t left){ - process_full(out, in); - } - -private: - const PixelTester m_tester; - const uint32_t m_replacement_color; - const bool m_replace_color_within_range; - size_t m_count; -}; - - - - - - -template -class ToBlackWhite_Rgb32_Default{ -public: - static const size_t VECTOR_SIZE = 1; - using Mask = size_t; - -public: - ToBlackWhite_Rgb32_Default( - const PixelTester& tester, - bool in_range_black - ) - : m_tester(tester) - , m_in_range_black(in_range_black ? 1 : 0) - , m_count(0) - {} - - PA_FORCE_INLINE size_t count() const{ - return m_count; - } - - PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ - uint32_t pixel = in[0]; - bool passed = m_tester.test_word(pixel); - m_count += passed; - passed ^= m_in_range_black; - out[0] = passed ? 0xffffffff : 0xff000000; - } - PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, size_t left){ - process_full(out, in); - } - -private: - const PixelTester m_tester; - const bool m_in_range_black; - size_t m_count; -}; - - - - -} -} +/* Image Filters Basic Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Compiler.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + + + +template +class FilterImage_Rgb32_Default{ +public: + static const size_t VECTOR_SIZE = 1; + using Mask = size_t; + +public: + FilterImage_Rgb32_Default( + const PixelTester& tester, + uint32_t replacement_color, bool replace_color_within_range + ) + : m_tester(tester) + , m_replacement_color(replacement_color) + , m_replace_color_within_range(replace_color_within_range) + , m_count(0) + {} + + PA_FORCE_INLINE size_t count() const{ + return m_count; + } + + PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ + uint32_t pixel = in[0]; + bool passed = m_tester.test_word(pixel); + m_count += passed; + passed ^= m_replace_color_within_range; + out[0] = passed ? pixel : m_replacement_color; + } + PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, size_t left){ + process_full(out, in); + } + +private: + const PixelTester m_tester; + const uint32_t m_replacement_color; + const bool m_replace_color_within_range; + size_t m_count; +}; + + + + + + +template +class ToBlackWhite_Rgb32_Default{ +public: + static const size_t VECTOR_SIZE = 1; + using Mask = size_t; + +public: + ToBlackWhite_Rgb32_Default( + const PixelTester& tester, + bool in_range_black + ) + : m_tester(tester) + , m_in_range_black(in_range_black ? 1 : 0) + , m_count(0) + {} + + PA_FORCE_INLINE size_t count() const{ + return m_count; + } + + PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ + uint32_t pixel = in[0]; + bool passed = m_tester.test_word(pixel); + m_count += passed; + passed ^= m_in_range_black; + out[0] = passed ? 0xffffffff : 0xff000000; + } + PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, size_t left){ + process_full(out, in); + } + +private: + const PixelTester m_tester; + const bool m_in_range_black; + size_t m_count; +}; + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX2.h b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX2.h index b4d38f8187..bd20966008 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX2.h +++ b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX2.h @@ -1,132 +1,132 @@ -/* Image Filters Basic Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Compiler.h" -#include "Kernels/Kernels_x64_AVX2.h" -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - -template -class FilterImage_Rgb32_x64_AVX2{ -public: - static const size_t VECTOR_SIZE = 8; - using Mask = PartialWordAccess32_x64_AVX2; - -public: - FilterImage_Rgb32_x64_AVX2( - const PixelTester& tester, - uint32_t replacement, bool replace_color_within_range - ) - : m_tester(tester) - , m_replacement(_mm256_set1_epi32(replacement)) - , m_invert(replace_color_within_range ? _mm256_set1_epi32(-1) : _mm256_setzero_si256()) - , m_count(_mm256_setzero_si256()) - {} - - PA_FORCE_INLINE size_t count() const{ - return reduce_add32_x64_AVX2(m_count); - } - - PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ - __m256i pixel = _mm256_loadu_si256((const __m256i*)in); - __m256i in_range_pixels = process_word(pixel); - m_count = _mm256_sub_epi32(m_count, in_range_pixels); - _mm256_storeu_si256((__m256i*)out, pixel); - } - PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, const Mask& mask){ - __m256i pixel = mask.load_i32(in); - __m256i in_range_pixels = process_word(pixel); - in_range_pixels = _mm256_and_si256(in_range_pixels, mask.mask()); - m_count = _mm256_sub_epi32(m_count, in_range_pixels); - mask.store(out, pixel); - } - -private: - // Process the pixel in-place. - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __m256i process_word(__m256i& pixel) const{ - __m256i mask = m_tester.test_word(pixel); - pixel = _mm256_blendv_epi8( - m_replacement, - pixel, - _mm256_xor_si256(mask, m_invert) - ); - return mask; - } - -private: - const PixelTester m_tester; - const __m256i m_replacement; - const __m256i m_invert; - __m256i m_count; -}; - - - - -template -class ToBlackWhite_Rgb32_x64_AVX2{ -public: - static const size_t VECTOR_SIZE = 8; - using Mask = PartialWordAccess32_x64_AVX2; - -public: - ToBlackWhite_Rgb32_x64_AVX2( - const PixelTester& tester, - bool in_range_black - ) - : m_tester(tester) - , m_in_range_black(_mm256_set1_epi32(in_range_black ? -1 : 0)) - , m_count(_mm256_setzero_si256()) - {} - - PA_FORCE_INLINE size_t count() const{ - return reduce_add32_x64_AVX2(m_count); - } - - PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ - __m256i pixel = _mm256_loadu_si256((const __m256i*)in); - __m256i in_range_pixels = process_word(pixel); - m_count = _mm256_sub_epi32(m_count, in_range_pixels); - _mm256_storeu_si256((__m256i*)out, pixel); - } - PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, const Mask& mask){ - __m256i pixel = mask.load_i32(in); - __m256i in_range_pixels = process_word(pixel); - in_range_pixels = _mm256_and_si256(in_range_pixels, mask.mask()); - m_count = _mm256_sub_epi32(m_count, in_range_pixels); - mask.store(out, pixel); - } - -private: - // Process the pixel in-place. - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __m256i process_word(__m256i& pixel) const{ - __m256i mask = m_tester.test_word(pixel); - pixel = _mm256_or_si256( - _mm256_xor_si256(mask, m_in_range_black), - _mm256_set1_epi32(0xff000000) - ); - return mask; - } - -private: - const PixelTester m_tester; - const __m256i m_in_range_black; - __m256i m_count; -}; - - - - -} -} +/* Image Filters Basic Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Compiler.h" +#include "Kernels/Kernels_x64_AVX2.h" +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + +template +class FilterImage_Rgb32_x64_AVX2{ +public: + static const size_t VECTOR_SIZE = 8; + using Mask = PartialWordAccess32_x64_AVX2; + +public: + FilterImage_Rgb32_x64_AVX2( + const PixelTester& tester, + uint32_t replacement, bool replace_color_within_range + ) + : m_tester(tester) + , m_replacement(_mm256_set1_epi32(replacement)) + , m_invert(replace_color_within_range ? _mm256_set1_epi32(-1) : _mm256_setzero_si256()) + , m_count(_mm256_setzero_si256()) + {} + + PA_FORCE_INLINE size_t count() const{ + return reduce_add32_x64_AVX2(m_count); + } + + PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ + __m256i pixel = _mm256_loadu_si256((const __m256i*)in); + __m256i in_range_pixels = process_word(pixel); + m_count = _mm256_sub_epi32(m_count, in_range_pixels); + _mm256_storeu_si256((__m256i*)out, pixel); + } + PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, const Mask& mask){ + __m256i pixel = mask.load_i32(in); + __m256i in_range_pixels = process_word(pixel); + in_range_pixels = _mm256_and_si256(in_range_pixels, mask.mask()); + m_count = _mm256_sub_epi32(m_count, in_range_pixels); + mask.store(out, pixel); + } + +private: + // Process the pixel in-place. + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __m256i process_word(__m256i& pixel) const{ + __m256i mask = m_tester.test_word(pixel); + pixel = _mm256_blendv_epi8( + m_replacement, + pixel, + _mm256_xor_si256(mask, m_invert) + ); + return mask; + } + +private: + const PixelTester m_tester; + const __m256i m_replacement; + const __m256i m_invert; + __m256i m_count; +}; + + + + +template +class ToBlackWhite_Rgb32_x64_AVX2{ +public: + static const size_t VECTOR_SIZE = 8; + using Mask = PartialWordAccess32_x64_AVX2; + +public: + ToBlackWhite_Rgb32_x64_AVX2( + const PixelTester& tester, + bool in_range_black + ) + : m_tester(tester) + , m_in_range_black(_mm256_set1_epi32(in_range_black ? -1 : 0)) + , m_count(_mm256_setzero_si256()) + {} + + PA_FORCE_INLINE size_t count() const{ + return reduce_add32_x64_AVX2(m_count); + } + + PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ + __m256i pixel = _mm256_loadu_si256((const __m256i*)in); + __m256i in_range_pixels = process_word(pixel); + m_count = _mm256_sub_epi32(m_count, in_range_pixels); + _mm256_storeu_si256((__m256i*)out, pixel); + } + PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, const Mask& mask){ + __m256i pixel = mask.load_i32(in); + __m256i in_range_pixels = process_word(pixel); + in_range_pixels = _mm256_and_si256(in_range_pixels, mask.mask()); + m_count = _mm256_sub_epi32(m_count, in_range_pixels); + mask.store(out, pixel); + } + +private: + // Process the pixel in-place. + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __m256i process_word(__m256i& pixel) const{ + __m256i mask = m_tester.test_word(pixel); + pixel = _mm256_or_si256( + _mm256_xor_si256(mask, m_in_range_black), + _mm256_set1_epi32(0xff000000) + ); + return mask; + } + +private: + const PixelTester m_tester; + const __m256i m_in_range_black; + __m256i m_count; +}; + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX512.h b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX512.h index c43c9dbb46..35071ab3c9 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX512.h +++ b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX512.h @@ -1,147 +1,147 @@ -/* Image Filters Basic Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Compiler.h" - - -namespace PokemonAutomation{ -namespace Kernels{ - - - -struct PartialWordMask{ - __mmask16 m; - - PA_FORCE_INLINE PartialWordMask(size_t left) - : m(((__mmask16)1 << left) - 1) - {} -}; - - - - -template -class FilterImage_Rgb32_x64_AVX512{ -public: - static const size_t VECTOR_SIZE = 16; - using Mask = PartialWordMask; - -public: - FilterImage_Rgb32_x64_AVX512( - const PixelTester& tester, - uint32_t replacement, bool replace_color_within_range - ) - : m_tester(tester) - , m_replacement(_mm512_set1_epi32(replacement)) - , m_invert(replace_color_within_range ? 0xffff : 0) - , m_count(_mm512_setzero_si512()) - {} - - PA_FORCE_INLINE size_t count() const{ - return _mm512_reduce_add_epi32(m_count); - } - - PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ - __m512i pixel = _mm512_loadu_si512((const __m512i*)in); - __mmask16 in_range_pixels = process_word(pixel); - m_count = _mm512_mask_sub_epi32(m_count, in_range_pixels, m_count, _mm512_set1_epi32(-1)); - _mm512_storeu_si512((__m512i*)out, pixel); - } - PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, const Mask& mask){ - __m512i pixel = _mm512_maskz_loadu_epi32(mask.m, in); - __mmask16 in_range_pixels = process_word(pixel); - in_range_pixels &= mask.m; - m_count = _mm512_mask_sub_epi32(m_count, in_range_pixels, m_count, _mm512_set1_epi32(-1)); - _mm512_mask_storeu_epi32(out, mask.m, pixel); - } - -private: - // Process the pixel in-place. - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __mmask16 process_word(__m512i& pixel) const{ - __mmask16 mask = m_tester.test_word(pixel); - pixel = _mm512_mask_blend_epi32( - mask ^ m_invert, - m_replacement, - pixel - ); - return mask; - } - -private: - const PixelTester m_tester; - const __m512i m_replacement; - const __mmask16 m_invert; - __m512i m_count; -}; - - - - - -template -class ToBlackWhite_Rgb32_x64_AVX512{ -public: - static const size_t VECTOR_SIZE = 16; - using Mask = PartialWordMask; - -public: - ToBlackWhite_Rgb32_x64_AVX512( - const PixelTester& tester, - bool in_range_black - ) - : m_tester(tester) - , m_in_range_color(_mm512_set1_epi32(in_range_black ? 0xff000000 : 0xffffffff)) - , m_out_range_color(_mm512_set1_epi32(in_range_black ? 0xffffffff : 0xff000000)) - , m_count(_mm512_setzero_si512()) - {} - - PA_FORCE_INLINE size_t count() const{ - return _mm512_reduce_add_epi32(m_count); - } - - PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ - __m512i pixel = _mm512_loadu_si512((const __m512i*)in); - __mmask16 in_range_pixels = process_word(pixel); - m_count = _mm512_mask_sub_epi32(m_count, in_range_pixels, m_count, _mm512_set1_epi32(-1)); - _mm512_storeu_si512((__m512i*)out, pixel); - } - PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, const Mask& mask){ - __m512i pixel = _mm512_maskz_loadu_epi32(mask.m, in); - __mmask16 in_range_pixels = process_word(pixel); - in_range_pixels &= mask.m; - m_count = _mm512_mask_sub_epi32(m_count, in_range_pixels, m_count, _mm512_set1_epi32(-1)); - _mm512_mask_storeu_epi32(out, mask.m, pixel); - } - -private: - // Process the pixel in-place. - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __mmask16 process_word(__m512i& pixel) const{ - __mmask16 mask = m_tester.test_word(pixel); - pixel = _mm512_mask_blend_epi32( - mask, - m_out_range_color, - m_in_range_color - ); - return mask; - } - -private: - const PixelTester m_tester; - const __m512i m_in_range_color; - const __m512i m_out_range_color; - __m512i m_count; -}; - - - - - -} -} +/* Image Filters Basic Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Compiler.h" + + +namespace PokemonAutomation{ +namespace Kernels{ + + + +struct PartialWordMask{ + __mmask16 m; + + PA_FORCE_INLINE PartialWordMask(size_t left) + : m(((__mmask16)1 << left) - 1) + {} +}; + + + + +template +class FilterImage_Rgb32_x64_AVX512{ +public: + static const size_t VECTOR_SIZE = 16; + using Mask = PartialWordMask; + +public: + FilterImage_Rgb32_x64_AVX512( + const PixelTester& tester, + uint32_t replacement, bool replace_color_within_range + ) + : m_tester(tester) + , m_replacement(_mm512_set1_epi32(replacement)) + , m_invert(replace_color_within_range ? 0xffff : 0) + , m_count(_mm512_setzero_si512()) + {} + + PA_FORCE_INLINE size_t count() const{ + return _mm512_reduce_add_epi32(m_count); + } + + PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ + __m512i pixel = _mm512_loadu_si512((const __m512i*)in); + __mmask16 in_range_pixels = process_word(pixel); + m_count = _mm512_mask_sub_epi32(m_count, in_range_pixels, m_count, _mm512_set1_epi32(-1)); + _mm512_storeu_si512((__m512i*)out, pixel); + } + PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, const Mask& mask){ + __m512i pixel = _mm512_maskz_loadu_epi32(mask.m, in); + __mmask16 in_range_pixels = process_word(pixel); + in_range_pixels &= mask.m; + m_count = _mm512_mask_sub_epi32(m_count, in_range_pixels, m_count, _mm512_set1_epi32(-1)); + _mm512_mask_storeu_epi32(out, mask.m, pixel); + } + +private: + // Process the pixel in-place. + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __mmask16 process_word(__m512i& pixel) const{ + __mmask16 mask = m_tester.test_word(pixel); + pixel = _mm512_mask_blend_epi32( + mask ^ m_invert, + m_replacement, + pixel + ); + return mask; + } + +private: + const PixelTester m_tester; + const __m512i m_replacement; + const __mmask16 m_invert; + __m512i m_count; +}; + + + + + +template +class ToBlackWhite_Rgb32_x64_AVX512{ +public: + static const size_t VECTOR_SIZE = 16; + using Mask = PartialWordMask; + +public: + ToBlackWhite_Rgb32_x64_AVX512( + const PixelTester& tester, + bool in_range_black + ) + : m_tester(tester) + , m_in_range_color(_mm512_set1_epi32(in_range_black ? 0xff000000 : 0xffffffff)) + , m_out_range_color(_mm512_set1_epi32(in_range_black ? 0xffffffff : 0xff000000)) + , m_count(_mm512_setzero_si512()) + {} + + PA_FORCE_INLINE size_t count() const{ + return _mm512_reduce_add_epi32(m_count); + } + + PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ + __m512i pixel = _mm512_loadu_si512((const __m512i*)in); + __mmask16 in_range_pixels = process_word(pixel); + m_count = _mm512_mask_sub_epi32(m_count, in_range_pixels, m_count, _mm512_set1_epi32(-1)); + _mm512_storeu_si512((__m512i*)out, pixel); + } + PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, const Mask& mask){ + __m512i pixel = _mm512_maskz_loadu_epi32(mask.m, in); + __mmask16 in_range_pixels = process_word(pixel); + in_range_pixels &= mask.m; + m_count = _mm512_mask_sub_epi32(m_count, in_range_pixels, m_count, _mm512_set1_epi32(-1)); + _mm512_mask_storeu_epi32(out, mask.m, pixel); + } + +private: + // Process the pixel in-place. + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __mmask16 process_word(__m512i& pixel) const{ + __mmask16 mask = m_tester.test_word(pixel); + pixel = _mm512_mask_blend_epi32( + mask, + m_out_range_color, + m_in_range_color + ); + return mask; + } + +private: + const PixelTester m_tester; + const __m512i m_in_range_color; + const __m512i m_out_range_color; + __m512i m_count; +}; + + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_SSE42.h b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_SSE42.h index 53fed09a76..cef34c66ca 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_SSE42.h +++ b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_SSE42.h @@ -1,169 +1,169 @@ -/* Image Filters Basic Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Compiler.h" -#include "Kernels/Kernels_x64_SSE41.h" -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - -struct PartialWordMask{ - size_t left; - PartialWordAccess_x64_SSE41 loader; - - PA_FORCE_INLINE PartialWordMask(size_t p_left) - : left(p_left) - , loader(left * sizeof(uint32_t)) - {} -}; - - - - - -template -class FilterImage_Rgb32_x64_SSE42{ -public: - static const size_t VECTOR_SIZE = 4; - using Mask = PartialWordMask; - -public: - FilterImage_Rgb32_x64_SSE42( - const PixelTester& tester, - uint32_t replacement, bool replace_color_within_range - ) - : m_tester(tester) - , m_replacement(_mm_set1_epi32(replacement)) - , m_invert(replace_color_within_range ? _mm_set1_epi32(-1) : _mm_setzero_si128()) - , m_count(_mm_setzero_si128()) - {} - - PA_FORCE_INLINE size_t count() const{ - return reduce32_x64_SSE41(m_count); - } - - PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ - __m128i pixel = _mm_loadu_si128((const __m128i*)in); - __m128i in_range_pixels = process_word(pixel); - m_count = _mm_sub_epi32(m_count, in_range_pixels); - _mm_storeu_si128((__m128i*)out, pixel); - } - PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, const Mask& mask){ - __m128i vmask = _mm_cmpgt_epi32( - _mm_set1_epi32((uint32_t)mask.left), - _mm_setr_epi32(0, 1, 2, 3) - ); - - __m128i pixel = mask.loader.load(in); - __m128i in_range_pixels = process_word(pixel); - in_range_pixels = _mm_and_si128(in_range_pixels, vmask); - m_count = _mm_sub_epi32(m_count, in_range_pixels); - size_t left = mask.left; - do{ - out[0] = _mm_cvtsi128_si32(pixel); - pixel = _mm_srli_si128(pixel, 4); - out++; - }while(--left); - } - -private: - // Process the pixel in-place. - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __m128i process_word(__m128i& pixel) const{ - __m128i mask = m_tester.test_word(pixel); - pixel = _mm_blendv_epi8( - m_replacement, - pixel, - _mm_xor_si128(mask, m_invert) - ); - return mask; - } - -private: - const PixelTester m_tester; - const __m128i m_replacement; - const __m128i m_invert; - __m128i m_count; -}; - - - - - - - -template -class ToBlackWhite_Rgb32_x64_SSE42{ -public: - static const size_t VECTOR_SIZE = 4; - using Mask = PartialWordMask; - -public: - ToBlackWhite_Rgb32_x64_SSE42( - const PixelTester& tester, - bool in_range_black - ) - : m_tester(tester) - , m_in_range_black(_mm_set1_epi32(in_range_black ? -1 : 0)) - , m_count(_mm_setzero_si128()) - {} - - PA_FORCE_INLINE size_t count() const{ - return reduce32_x64_SSE41(m_count); - } - - PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ - __m128i pixel = _mm_loadu_si128((const __m128i*)in); - __m128i in_range_pixels = process_word(pixel); - m_count = _mm_sub_epi32(m_count, in_range_pixels); - _mm_storeu_si128((__m128i*)out, pixel); - } - PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, const Mask& mask){ - __m128i vmask = _mm_cmpgt_epi32( - _mm_set1_epi32((uint32_t)mask.left), - _mm_setr_epi32(0, 1, 2, 3) - ); - - __m128i pixel = mask.loader.load(in); - __m128i in_range_pixels = process_word(pixel); - in_range_pixels = _mm_and_si128(in_range_pixels, vmask); - m_count = _mm_sub_epi32(m_count, in_range_pixels); - size_t left = mask.left; - do{ - out[0] = _mm_cvtsi128_si32(pixel); - pixel = _mm_srli_si128(pixel, 4); - out++; - }while(--left); - } - -private: - // Process the pixel in-place. - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __m128i process_word(__m128i& pixel) const{ - __m128i mask = m_tester.test_word(pixel); - pixel = _mm_or_si128( - _mm_xor_si128(mask, m_in_range_black), - _mm_set1_epi32(0xff000000) - ); - return mask; - } - -private: - const PixelTester m_tester; - const __m128i m_in_range_black; - __m128i m_count; -}; - - - - -} -} +/* Image Filters Basic Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Compiler.h" +#include "Kernels/Kernels_x64_SSE41.h" +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + +struct PartialWordMask{ + size_t left; + PartialWordAccess_x64_SSE41 loader; + + PA_FORCE_INLINE PartialWordMask(size_t p_left) + : left(p_left) + , loader(left * sizeof(uint32_t)) + {} +}; + + + + + +template +class FilterImage_Rgb32_x64_SSE42{ +public: + static const size_t VECTOR_SIZE = 4; + using Mask = PartialWordMask; + +public: + FilterImage_Rgb32_x64_SSE42( + const PixelTester& tester, + uint32_t replacement, bool replace_color_within_range + ) + : m_tester(tester) + , m_replacement(_mm_set1_epi32(replacement)) + , m_invert(replace_color_within_range ? _mm_set1_epi32(-1) : _mm_setzero_si128()) + , m_count(_mm_setzero_si128()) + {} + + PA_FORCE_INLINE size_t count() const{ + return reduce32_x64_SSE41(m_count); + } + + PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ + __m128i pixel = _mm_loadu_si128((const __m128i*)in); + __m128i in_range_pixels = process_word(pixel); + m_count = _mm_sub_epi32(m_count, in_range_pixels); + _mm_storeu_si128((__m128i*)out, pixel); + } + PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, const Mask& mask){ + __m128i vmask = _mm_cmpgt_epi32( + _mm_set1_epi32((uint32_t)mask.left), + _mm_setr_epi32(0, 1, 2, 3) + ); + + __m128i pixel = mask.loader.load(in); + __m128i in_range_pixels = process_word(pixel); + in_range_pixels = _mm_and_si128(in_range_pixels, vmask); + m_count = _mm_sub_epi32(m_count, in_range_pixels); + size_t left = mask.left; + do{ + out[0] = _mm_cvtsi128_si32(pixel); + pixel = _mm_srli_si128(pixel, 4); + out++; + }while(--left); + } + +private: + // Process the pixel in-place. + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __m128i process_word(__m128i& pixel) const{ + __m128i mask = m_tester.test_word(pixel); + pixel = _mm_blendv_epi8( + m_replacement, + pixel, + _mm_xor_si128(mask, m_invert) + ); + return mask; + } + +private: + const PixelTester m_tester; + const __m128i m_replacement; + const __m128i m_invert; + __m128i m_count; +}; + + + + + + + +template +class ToBlackWhite_Rgb32_x64_SSE42{ +public: + static const size_t VECTOR_SIZE = 4; + using Mask = PartialWordMask; + +public: + ToBlackWhite_Rgb32_x64_SSE42( + const PixelTester& tester, + bool in_range_black + ) + : m_tester(tester) + , m_in_range_black(_mm_set1_epi32(in_range_black ? -1 : 0)) + , m_count(_mm_setzero_si128()) + {} + + PA_FORCE_INLINE size_t count() const{ + return reduce32_x64_SSE41(m_count); + } + + PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ + __m128i pixel = _mm_loadu_si128((const __m128i*)in); + __m128i in_range_pixels = process_word(pixel); + m_count = _mm_sub_epi32(m_count, in_range_pixels); + _mm_storeu_si128((__m128i*)out, pixel); + } + PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, const Mask& mask){ + __m128i vmask = _mm_cmpgt_epi32( + _mm_set1_epi32((uint32_t)mask.left), + _mm_setr_epi32(0, 1, 2, 3) + ); + + __m128i pixel = mask.loader.load(in); + __m128i in_range_pixels = process_word(pixel); + in_range_pixels = _mm_and_si128(in_range_pixels, vmask); + m_count = _mm_sub_epi32(m_count, in_range_pixels); + size_t left = mask.left; + do{ + out[0] = _mm_cvtsi128_si32(pixel); + pixel = _mm_srli_si128(pixel, 4); + out++; + }while(--left); + } + +private: + // Process the pixel in-place. + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __m128i process_word(__m128i& pixel) const{ + __m128i mask = m_tester.test_word(pixel); + pixel = _mm_or_si128( + _mm_xor_si128(mask, m_in_range_black), + _mm_set1_epi32(0xff000000) + ); + return mask; + } + +private: + const PixelTester m_tester; + const __m128i m_in_range_black; + __m128i m_count; +}; + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Green_Default.cpp b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Green_Default.cpp index 0bc498510d..ce6050377a 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Green_Default.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Green_Default.cpp @@ -1,91 +1,91 @@ -/* Image Filters Basic (Default) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Kernels_ImageFilter_Basic_Routines.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -class ImageFilter_Green_Default{ -public: - static const size_t VECTOR_SIZE = 1; - using Mask = size_t; - -public: - ImageFilter_Green_Default(uint32_t replacement_color, uint8_t rgb_gap) - : m_replacement_color(replacement_color) - , m_rgb_gap(rgb_gap) - , m_count(0) - {} - - PA_FORCE_INLINE size_t count() const{ - return m_count; - } - - PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ - uint32_t pixel = in[0]; - uint64_t ret = 1; - - uint16_t red = ((pixel >> 16) & 0xff); - uint16_t green = ((pixel >> 8) & 0xff); - uint16_t blue = ((pixel) & 0xff); - - ret &= (green >= red + m_rgb_gap) && (green >= blue + m_rgb_gap); - - - m_count += ret; - out[0] = ret ? pixel : m_replacement_color; - } - PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, size_t left){ - process_full(out, in); - } - -private: - const uint32_t m_replacement_color; - const uint16_t m_rgb_gap; - size_t m_count; -}; - - -size_t filter_green_Default( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement_color, uint8_t rgb_gap -){ - ImageFilter_Green_Default filter(replacement_color, rgb_gap); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - - - - - - - - - - - - - - - - - - - - - - -} -} +/* Image Filters Basic (Default) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Kernels_ImageFilter_Basic_Routines.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +class ImageFilter_Green_Default{ +public: + static const size_t VECTOR_SIZE = 1; + using Mask = size_t; + +public: + ImageFilter_Green_Default(uint32_t replacement_color, uint8_t rgb_gap) + : m_replacement_color(replacement_color) + , m_rgb_gap(rgb_gap) + , m_count(0) + {} + + PA_FORCE_INLINE size_t count() const{ + return m_count; + } + + PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ + uint32_t pixel = in[0]; + uint64_t ret = 1; + + uint16_t red = ((pixel >> 16) & 0xff); + uint16_t green = ((pixel >> 8) & 0xff); + uint16_t blue = ((pixel) & 0xff); + + ret &= (green >= red + m_rgb_gap) && (green >= blue + m_rgb_gap); + + + m_count += ret; + out[0] = ret ? pixel : m_replacement_color; + } + PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, size_t left){ + process_full(out, in); + } + +private: + const uint32_t m_replacement_color; + const uint16_t m_rgb_gap; + size_t m_count; +}; + + +size_t filter_green_Default( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement_color, uint8_t rgb_gap +){ + ImageFilter_Green_Default filter(replacement_color, rgb_gap); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + + + + + + + + + + + + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.cpp index 6b56f3bfd1..a26aac47bc 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.cpp @@ -1,174 +1,174 @@ -/* Image Filters RGB32 Brightness - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/CpuId/CpuId.h" -#include "Kernels_ImageFilter_RGB32_Brightness.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - -size_t filter_rgb32_brightness_x64_AVX512VNNI( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -); -size_t filter_rgb32_brightness_x64_AVX2( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -); -size_t filter_rgb32_brightness_x64_SSE42( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -); -size_t filter_rgb32_brightness_Default( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -); -size_t filter_rgb32_brightness( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -){ - if (width * height > 0xffffffff){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); - } -#ifdef PA_AutoDispatch_x64_19_IceLake - if (CPU_CAPABILITY_CURRENT.OK_19_IceLake){ - return filter_rgb32_brightness_x64_AVX512VNNI( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - weights, min_brightness, max_brightness - ); - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ - return filter_rgb32_brightness_x64_AVX2( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - weights, min_brightness, max_brightness - ); - } -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - return filter_rgb32_brightness_x64_SSE42( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - weights, min_brightness, max_brightness - ); - } -#endif - return filter_rgb32_brightness_Default( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - weights, min_brightness, max_brightness - ); -} - - - -size_t to_blackwhite_rgb32_brightness_x64_AVX512VNNI( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -); -size_t to_blackwhite_rgb32_brightness_x64_AVX2( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -); -size_t to_blackwhite_rgb32_brightness_x64_SSE42( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -); -size_t to_blackwhite_rgb32_brightness_Default( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -); -size_t to_blackwhite_rgb32_brightness( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -){ - if (width * height > 0xffffffff){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); - } -#ifdef PA_AutoDispatch_x64_19_IceLake - if (CPU_CAPABILITY_CURRENT.OK_19_IceLake){ - return to_blackwhite_rgb32_brightness_x64_AVX512VNNI( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - in_range_black, - weights, min_brightness, max_brightness - ); - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ - return to_blackwhite_rgb32_brightness_x64_AVX2( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - in_range_black, - weights, min_brightness, max_brightness - ); - } -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - return to_blackwhite_rgb32_brightness_x64_SSE42( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - in_range_black, - weights, min_brightness, max_brightness - ); - } -#endif - return to_blackwhite_rgb32_brightness_Default( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - in_range_black, - weights, min_brightness, max_brightness - ); -} - - - - -} -} +/* Image Filters RGB32 Brightness + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/CpuId/CpuId.h" +#include "Kernels_ImageFilter_RGB32_Brightness.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + +size_t filter_rgb32_brightness_x64_AVX512VNNI( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +); +size_t filter_rgb32_brightness_x64_AVX2( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +); +size_t filter_rgb32_brightness_x64_SSE42( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +); +size_t filter_rgb32_brightness_Default( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +); +size_t filter_rgb32_brightness( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +){ + if (width * height > 0xffffffff){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); + } +#ifdef PA_AutoDispatch_x64_19_IceLake + if (CPU_CAPABILITY_CURRENT.OK_19_IceLake){ + return filter_rgb32_brightness_x64_AVX512VNNI( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + weights, min_brightness, max_brightness + ); + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ + return filter_rgb32_brightness_x64_AVX2( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + weights, min_brightness, max_brightness + ); + } +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + return filter_rgb32_brightness_x64_SSE42( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + weights, min_brightness, max_brightness + ); + } +#endif + return filter_rgb32_brightness_Default( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + weights, min_brightness, max_brightness + ); +} + + + +size_t to_blackwhite_rgb32_brightness_x64_AVX512VNNI( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +); +size_t to_blackwhite_rgb32_brightness_x64_AVX2( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +); +size_t to_blackwhite_rgb32_brightness_x64_SSE42( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +); +size_t to_blackwhite_rgb32_brightness_Default( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +); +size_t to_blackwhite_rgb32_brightness( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +){ + if (width * height > 0xffffffff){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); + } +#ifdef PA_AutoDispatch_x64_19_IceLake + if (CPU_CAPABILITY_CURRENT.OK_19_IceLake){ + return to_blackwhite_rgb32_brightness_x64_AVX512VNNI( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + in_range_black, + weights, min_brightness, max_brightness + ); + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ + return to_blackwhite_rgb32_brightness_x64_AVX2( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + in_range_black, + weights, min_brightness, max_brightness + ); + } +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + return to_blackwhite_rgb32_brightness_x64_SSE42( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + in_range_black, + weights, min_brightness, max_brightness + ); + } +#endif + return to_blackwhite_rgb32_brightness_Default( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + in_range_black, + weights, min_brightness, max_brightness + ); +} + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.h b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.h index 7aa89cca1d..46eb9fd967 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.h +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.h @@ -1,70 +1,70 @@ -/* Image Filters RGB32 Brightness - * - * From: https://github.com/PokemonAutomation/ - * - * Perform a filter over an image and replace pixels that match the filter. - * - */ - -#ifndef PokemonAutomation_Kernels_ImageFilter_RGB32_Brightness_H -#define PokemonAutomation_Kernels_ImageFilter_RGB32_Brightness_H - -#include -#include -#include "Common/Cpp/PixelRGB32.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - -union Rgb32BrightnessWeights{ - struct{ - int8_t blue; - int8_t green; - int8_t red; - int8_t alpha; - } parts; - uint32_t u32; - - Rgb32BrightnessWeights(uint32_t value) - : u32(value) - {} - Rgb32BrightnessWeights(uint8_t red, uint8_t green, uint8_t blue){ - parts.alpha = 0; - parts.red = red; - parts.green = green; - parts.blue = blue; - } - Rgb32BrightnessWeights(uint8_t alpha, uint8_t red, uint8_t green, uint8_t blue){ - parts.alpha = alpha; - parts.red = red; - parts.green = green; - parts.blue = blue; - } -}; - - - -size_t filter_rgb32_brightness( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -); - -size_t to_blackwhite_rgb32_brightness( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -); - - - - -} -} -#endif +/* Image Filters RGB32 Brightness + * + * From: https://github.com/PokemonAutomation/ + * + * Perform a filter over an image and replace pixels that match the filter. + * + */ + +#ifndef PokemonAutomation_Kernels_ImageFilter_RGB32_Brightness_H +#define PokemonAutomation_Kernels_ImageFilter_RGB32_Brightness_H + +#include +#include +#include "Common/Cpp/PixelRGB32.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + +union Rgb32BrightnessWeights{ + struct{ + int8_t blue; + int8_t green; + int8_t red; + int8_t alpha; + } parts; + uint32_t u32; + + Rgb32BrightnessWeights(uint32_t value) + : u32(value) + {} + Rgb32BrightnessWeights(uint8_t red, uint8_t green, uint8_t blue){ + parts.alpha = 0; + parts.red = red; + parts.green = green; + parts.blue = blue; + } + Rgb32BrightnessWeights(uint8_t alpha, uint8_t red, uint8_t green, uint8_t blue){ + parts.alpha = alpha; + parts.red = red; + parts.green = green; + parts.blue = blue; + } +}; + + + +size_t filter_rgb32_brightness( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +); + +size_t to_blackwhite_rgb32_brightness( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +); + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_Default.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_Default.cpp index 70e9cb3d41..24ea06a05f 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_Default.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_Default.cpp @@ -1,94 +1,94 @@ -/* Image Filters RGB32 Brightness - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_Default.h" -#include "Kernels_ImageFilter_RGB32_Brightness.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - -class PixelTest_Rgb32Brightness_Default{ -public: - PA_FORCE_INLINE PixelTest_Rgb32Brightness_Default( - Rgb32BrightnessWeights weights, int32_t min_sum, int32_t max_sum - ) - : m_weight_a(weights.parts.alpha) - , m_weight_r(weights.parts.red) - , m_weight_g(weights.parts.green) - , m_weight_b(weights.parts.blue) - , m_shift(min_sum) - , m_threshold(max_sum - min_sum) - {} - PA_FORCE_INLINE bool test_word(uint32_t pixel) const{ - uint32_t brightness = 0; - brightness += ((pixel >> 24) & 0x000000ff) * m_weight_a; - brightness += ((pixel >> 16) & 0x000000ff) * m_weight_r; - brightness += ((pixel >> 8) & 0x000000ff) * m_weight_g; - brightness += ((pixel >> 0) & 0x000000ff) * m_weight_b; - return brightness - m_shift <= m_threshold; - } - -private: - int32_t m_weight_a; - int32_t m_weight_r; - int32_t m_weight_g; - int32_t m_weight_b; - uint32_t m_shift; - uint32_t m_threshold; -}; - - - - - - - -size_t filter_rgb32_brightness_Default( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -){ - PixelTest_Rgb32Brightness_Default tester( - weights, - min_brightness, max_brightness - ); - FilterImage_Rgb32_Default filter( - tester, replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_brightness_Default( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -){ - PixelTest_Rgb32Brightness_Default tester( - weights, - min_brightness, max_brightness - ); - ToBlackWhite_Rgb32_Default filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - -} -} +/* Image Filters RGB32 Brightness + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_Default.h" +#include "Kernels_ImageFilter_RGB32_Brightness.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + +class PixelTest_Rgb32Brightness_Default{ +public: + PA_FORCE_INLINE PixelTest_Rgb32Brightness_Default( + Rgb32BrightnessWeights weights, int32_t min_sum, int32_t max_sum + ) + : m_weight_a(weights.parts.alpha) + , m_weight_r(weights.parts.red) + , m_weight_g(weights.parts.green) + , m_weight_b(weights.parts.blue) + , m_shift(min_sum) + , m_threshold(max_sum - min_sum) + {} + PA_FORCE_INLINE bool test_word(uint32_t pixel) const{ + uint32_t brightness = 0; + brightness += ((pixel >> 24) & 0x000000ff) * m_weight_a; + brightness += ((pixel >> 16) & 0x000000ff) * m_weight_r; + brightness += ((pixel >> 8) & 0x000000ff) * m_weight_g; + brightness += ((pixel >> 0) & 0x000000ff) * m_weight_b; + return brightness - m_shift <= m_threshold; + } + +private: + int32_t m_weight_a; + int32_t m_weight_r; + int32_t m_weight_g; + int32_t m_weight_b; + uint32_t m_shift; + uint32_t m_threshold; +}; + + + + + + + +size_t filter_rgb32_brightness_Default( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +){ + PixelTest_Rgb32Brightness_Default tester( + weights, + min_brightness, max_brightness + ); + FilterImage_Rgb32_Default filter( + tester, replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_brightness_Default( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +){ + PixelTest_Rgb32Brightness_Default tester( + weights, + min_brightness, max_brightness + ); + ToBlackWhite_Rgb32_Default filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_AVX2.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_AVX2.cpp index e04b35be3e..9723c610ba 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_AVX2.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_AVX2.cpp @@ -1,107 +1,107 @@ -/* Image Filters RGB32 Brightness - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_13_Haswell - -#include -#include -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX2.h" -#include "Kernels_ImageFilter_RGB32_Brightness.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - - -class PixelTest_Rgb32Brightness_x64_AVX2{ -public: - static const size_t VECTOR_SIZE = 8; - using Mask = PartialWordAccess32_x64_AVX2; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Brightness_x64_AVX2( - Rgb32BrightnessWeights weights, int32_t min_sum, int32_t max_sum - ) - : m_weightsL(_mm256_srai_epi16(_mm256_set1_epi32((weights.u32 << 8) & 0xff00ff00), 8)) - , m_weightsH(_mm256_srai_epi16(_mm256_set1_epi32((weights.u32 ) & 0xff00ff00), 8)) - , m_min(_mm256_set1_epi32(min_sum == std::numeric_limits::min() ? min_sum : min_sum - 1)) - , m_max(_mm256_set1_epi32(max_sum == std::numeric_limits::max() ? max_sum : max_sum + 1)) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __m256i test_word(__m256i pixel) const{ - __m256i rb = _mm256_and_si256(pixel, _mm256_set1_epi32(0x00ff00ff)); - __m256i ag = _mm256_and_si256(_mm256_srli_epi16(pixel, 8), _mm256_set1_epi32(0x00ff00ff)); - - rb = _mm256_madd_epi16(rb, m_weightsL); - ag = _mm256_madd_epi16(ag, m_weightsH); - pixel = _mm256_add_epi32(rb, ag); - - __m256i cmp0 = _mm256_cmpgt_epi32(pixel, m_min); - __m256i cmp1 = _mm256_cmpgt_epi32(m_max, pixel); - return _mm256_and_si256(cmp0, cmp1); - } - -private: - const __m256i m_weightsL; - const __m256i m_weightsH; - const __m256i m_min; - const __m256i m_max; -}; - - - - -size_t filter_rgb32_brightness_x64_AVX2( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -){ - PixelTest_Rgb32Brightness_x64_AVX2 tester( - weights, - min_brightness, max_brightness - ); - FilterImage_Rgb32_x64_AVX2 filter( - tester, replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_brightness_x64_AVX2( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -){ - PixelTest_Rgb32Brightness_x64_AVX2 tester( - weights, - min_brightness, max_brightness - ); - ToBlackWhite_Rgb32_x64_AVX2 filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - - - - - -} -} -#endif +/* Image Filters RGB32 Brightness + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_13_Haswell + +#include +#include +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX2.h" +#include "Kernels_ImageFilter_RGB32_Brightness.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + + +class PixelTest_Rgb32Brightness_x64_AVX2{ +public: + static const size_t VECTOR_SIZE = 8; + using Mask = PartialWordAccess32_x64_AVX2; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Brightness_x64_AVX2( + Rgb32BrightnessWeights weights, int32_t min_sum, int32_t max_sum + ) + : m_weightsL(_mm256_srai_epi16(_mm256_set1_epi32((weights.u32 << 8) & 0xff00ff00), 8)) + , m_weightsH(_mm256_srai_epi16(_mm256_set1_epi32((weights.u32 ) & 0xff00ff00), 8)) + , m_min(_mm256_set1_epi32(min_sum == std::numeric_limits::min() ? min_sum : min_sum - 1)) + , m_max(_mm256_set1_epi32(max_sum == std::numeric_limits::max() ? max_sum : max_sum + 1)) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __m256i test_word(__m256i pixel) const{ + __m256i rb = _mm256_and_si256(pixel, _mm256_set1_epi32(0x00ff00ff)); + __m256i ag = _mm256_and_si256(_mm256_srli_epi16(pixel, 8), _mm256_set1_epi32(0x00ff00ff)); + + rb = _mm256_madd_epi16(rb, m_weightsL); + ag = _mm256_madd_epi16(ag, m_weightsH); + pixel = _mm256_add_epi32(rb, ag); + + __m256i cmp0 = _mm256_cmpgt_epi32(pixel, m_min); + __m256i cmp1 = _mm256_cmpgt_epi32(m_max, pixel); + return _mm256_and_si256(cmp0, cmp1); + } + +private: + const __m256i m_weightsL; + const __m256i m_weightsH; + const __m256i m_min; + const __m256i m_max; +}; + + + + +size_t filter_rgb32_brightness_x64_AVX2( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +){ + PixelTest_Rgb32Brightness_x64_AVX2 tester( + weights, + min_brightness, max_brightness + ); + FilterImage_Rgb32_x64_AVX2 filter( + tester, replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_brightness_x64_AVX2( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +){ + PixelTest_Rgb32Brightness_x64_AVX2 tester( + weights, + min_brightness, max_brightness + ); + ToBlackWhite_Rgb32_x64_AVX2 filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_AVX512-VNNI.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_AVX512-VNNI.cpp index 5aca808826..c225c6391e 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_AVX512-VNNI.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_AVX512-VNNI.cpp @@ -1,110 +1,110 @@ -/* Image Filters RGB32 Brightness - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_19_IceLake - -#include -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX512.h" -#include "Kernels_ImageFilter_RGB32_Brightness.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - - -class PixelTest_Rgb32Brightness_x64_AVX512VNNI{ -public: - static const size_t VECTOR_SIZE = 16; - using Mask = PartialWordMask; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Brightness_x64_AVX512VNNI( - Rgb32BrightnessWeights weights, int32_t min_sum, int32_t max_sum - ) - : m_weights(_mm512_set1_epi32(weights.u32)) - , m_shift(_mm512_set1_epi32(-min_sum)) - , m_threshold(_mm512_set1_epi32(max_sum - min_sum)) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __mmask16 test_word(__m512i pixel) const{ - pixel = _mm512_dpbusd_epi32(m_shift, pixel, m_weights); - return _mm512_cmple_epu32_mask(pixel, m_threshold); - } - -private: - const __m512i m_weights; - const __m512i m_shift; - const __m512i m_threshold; -}; - - - - - -size_t filter_rgb32_brightness_x64_AVX512VNNI( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -){ - PixelTest_Rgb32Brightness_x64_AVX512VNNI tester( - weights, - min_brightness, max_brightness - ); - FilterImage_Rgb32_x64_AVX512 filter( - tester, replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_brightness_x64_AVX512VNNI( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -){ - PixelTest_Rgb32Brightness_x64_AVX512VNNI tester( - weights, - min_brightness, max_brightness - ); - ToBlackWhite_Rgb32_x64_AVX512 filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - - - - - - - - - - - - - - - - - - -} -} -#endif +/* Image Filters RGB32 Brightness + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_19_IceLake + +#include +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX512.h" +#include "Kernels_ImageFilter_RGB32_Brightness.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + + +class PixelTest_Rgb32Brightness_x64_AVX512VNNI{ +public: + static const size_t VECTOR_SIZE = 16; + using Mask = PartialWordMask; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Brightness_x64_AVX512VNNI( + Rgb32BrightnessWeights weights, int32_t min_sum, int32_t max_sum + ) + : m_weights(_mm512_set1_epi32(weights.u32)) + , m_shift(_mm512_set1_epi32(-min_sum)) + , m_threshold(_mm512_set1_epi32(max_sum - min_sum)) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __mmask16 test_word(__m512i pixel) const{ + pixel = _mm512_dpbusd_epi32(m_shift, pixel, m_weights); + return _mm512_cmple_epu32_mask(pixel, m_threshold); + } + +private: + const __m512i m_weights; + const __m512i m_shift; + const __m512i m_threshold; +}; + + + + + +size_t filter_rgb32_brightness_x64_AVX512VNNI( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +){ + PixelTest_Rgb32Brightness_x64_AVX512VNNI tester( + weights, + min_brightness, max_brightness + ); + FilterImage_Rgb32_x64_AVX512 filter( + tester, replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_brightness_x64_AVX512VNNI( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +){ + PixelTest_Rgb32Brightness_x64_AVX512VNNI tester( + weights, + min_brightness, max_brightness + ); + ToBlackWhite_Rgb32_x64_AVX512 filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + + + + + + + + + + + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_SSE42.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_SSE42.cpp index 1f653a5d0f..fb31879dfa 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_SSE42.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_SSE42.cpp @@ -1,107 +1,107 @@ -/* Image Filters RGB32 Brightness - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_08_Nehalem - -#include -#include -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_SSE42.h" -#include "Kernels_ImageFilter_RGB32_Brightness.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - - -class PixelTest_Rgb32Brightness_x64_SSE42{ -public: - static const size_t VECTOR_SIZE = 4; - using Mask = PartialWordMask; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Brightness_x64_SSE42( - Rgb32BrightnessWeights weights, int32_t min_sum, int32_t max_sum - ) - : m_weightsL(_mm_srai_epi16(_mm_set1_epi32((weights.u32 << 8) & 0xff00ff00), 8)) - , m_weightsH(_mm_srai_epi16(_mm_set1_epi32((weights.u32 ) & 0xff00ff00), 8)) - , m_min(_mm_set1_epi32(min_sum == std::numeric_limits::min() ? min_sum : min_sum - 1)) - , m_max(_mm_set1_epi32(max_sum == std::numeric_limits::max() ? max_sum : max_sum + 1)) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __m128i test_word(__m128i pixel) const{ - __m128i rb = _mm_and_si128(pixel, _mm_set1_epi32(0x00ff00ff)); - __m128i ag = _mm_and_si128(_mm_srli_epi16(pixel, 8), _mm_set1_epi32(0x00ff00ff)); - - rb = _mm_madd_epi16(rb, m_weightsL); - ag = _mm_madd_epi16(ag, m_weightsH); - pixel = _mm_add_epi32(rb, ag); - - __m128i cmp0 = _mm_cmpgt_epi32(pixel, m_min); - __m128i cmp1 = _mm_cmpgt_epi32(m_max, pixel); - return _mm_and_si128(cmp0, cmp1); - } - -private: - const __m128i m_weightsL; - const __m128i m_weightsH; - const __m128i m_min; - const __m128i m_max; -}; - - - - -size_t filter_rgb32_brightness_x64_SSE42( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -){ - PixelTest_Rgb32Brightness_x64_SSE42 tester( - weights, - min_brightness, max_brightness - ); - FilterImage_Rgb32_x64_SSE42 filter( - tester, replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_brightness_x64_SSE42( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -){ - PixelTest_Rgb32Brightness_x64_SSE42 tester( - weights, - min_brightness, max_brightness - ); - ToBlackWhite_Rgb32_x64_SSE42 filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - - - - - -} -} -#endif +/* Image Filters RGB32 Brightness + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_08_Nehalem + +#include +#include +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_SSE42.h" +#include "Kernels_ImageFilter_RGB32_Brightness.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + + +class PixelTest_Rgb32Brightness_x64_SSE42{ +public: + static const size_t VECTOR_SIZE = 4; + using Mask = PartialWordMask; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Brightness_x64_SSE42( + Rgb32BrightnessWeights weights, int32_t min_sum, int32_t max_sum + ) + : m_weightsL(_mm_srai_epi16(_mm_set1_epi32((weights.u32 << 8) & 0xff00ff00), 8)) + , m_weightsH(_mm_srai_epi16(_mm_set1_epi32((weights.u32 ) & 0xff00ff00), 8)) + , m_min(_mm_set1_epi32(min_sum == std::numeric_limits::min() ? min_sum : min_sum - 1)) + , m_max(_mm_set1_epi32(max_sum == std::numeric_limits::max() ? max_sum : max_sum + 1)) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __m128i test_word(__m128i pixel) const{ + __m128i rb = _mm_and_si128(pixel, _mm_set1_epi32(0x00ff00ff)); + __m128i ag = _mm_and_si128(_mm_srli_epi16(pixel, 8), _mm_set1_epi32(0x00ff00ff)); + + rb = _mm_madd_epi16(rb, m_weightsL); + ag = _mm_madd_epi16(ag, m_weightsH); + pixel = _mm_add_epi32(rb, ag); + + __m128i cmp0 = _mm_cmpgt_epi32(pixel, m_min); + __m128i cmp1 = _mm_cmpgt_epi32(m_max, pixel); + return _mm_and_si128(cmp0, cmp1); + } + +private: + const __m128i m_weightsL; + const __m128i m_weightsH; + const __m128i m_min; + const __m128i m_max; +}; + + + + +size_t filter_rgb32_brightness_x64_SSE42( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +){ + PixelTest_Rgb32Brightness_x64_SSE42 tester( + weights, + min_brightness, max_brightness + ); + FilterImage_Rgb32_x64_SSE42 filter( + tester, replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_brightness_x64_SSE42( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +){ + PixelTest_Rgb32Brightness_x64_SSE42 tester( + weights, + min_brightness, max_brightness + ); + ToBlackWhite_Rgb32_x64_SSE42 filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.cpp index 0f54d9b325..6fe7d5c0ea 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.cpp @@ -1,109 +1,109 @@ -/* Image Filters RGB32 Range - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/CpuId/CpuId.h" -#include "Kernels_ImageFilter_RGB32_Euclidean.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -size_t filter_rgb32_euclidean_Default( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -); -size_t filter_rgb32_euclidean_x64_SSE42( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -); -size_t filter_rgb32_euclidean_x64_AVX2( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -); -size_t filter_rgb32_euclidean_x64_AVX512( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -); -size_t filter_rgb32_euclidean_ARM64_NEON( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -); -size_t filter_rgb32_euclidean( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -){ - if (width * height > 0xffffffff){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); - } -#ifdef PA_AutoDispatch_x64_17_Skylake - if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ - return filter_rgb32_euclidean_x64_AVX512( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - expected, max_euclidean_distance - ); - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ - return filter_rgb32_euclidean_x64_AVX2( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - expected, max_euclidean_distance - ); - } -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - return filter_rgb32_euclidean_x64_SSE42( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - expected, max_euclidean_distance - ); - } -#endif -#ifdef PA_AutoDispatch_arm64_20_M1 - if (CPU_CAPABILITY_CURRENT.OK_M1){ - return filter_rgb32_euclidean_ARM64_NEON( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - expected, max_euclidean_distance - ); - } -#endif - return filter_rgb32_euclidean_Default( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - expected, max_euclidean_distance - ); -} - - - - - - - -} -} +/* Image Filters RGB32 Range + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/CpuId/CpuId.h" +#include "Kernels_ImageFilter_RGB32_Euclidean.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +size_t filter_rgb32_euclidean_Default( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +); +size_t filter_rgb32_euclidean_x64_SSE42( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +); +size_t filter_rgb32_euclidean_x64_AVX2( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +); +size_t filter_rgb32_euclidean_x64_AVX512( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +); +size_t filter_rgb32_euclidean_ARM64_NEON( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +); +size_t filter_rgb32_euclidean( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +){ + if (width * height > 0xffffffff){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); + } +#ifdef PA_AutoDispatch_x64_17_Skylake + if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ + return filter_rgb32_euclidean_x64_AVX512( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + expected, max_euclidean_distance + ); + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ + return filter_rgb32_euclidean_x64_AVX2( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + expected, max_euclidean_distance + ); + } +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + return filter_rgb32_euclidean_x64_SSE42( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + expected, max_euclidean_distance + ); + } +#endif +#ifdef PA_AutoDispatch_arm64_20_M1 + if (CPU_CAPABILITY_CURRENT.OK_M1){ + return filter_rgb32_euclidean_ARM64_NEON( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + expected, max_euclidean_distance + ); + } +#endif + return filter_rgb32_euclidean_Default( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + expected, max_euclidean_distance + ); +} + + + + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.h b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.h index 284278ddbc..91125a15a9 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.h +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.h @@ -1,32 +1,32 @@ -/* Image Filters RGB32 Euclidean Distance - * - * From: https://github.com/PokemonAutomation/ - * - * Perform a filter over an image and replace pixels that match the filter. - * - */ - -#ifndef PokemonAutomation_Kernels_ImageFilter_RGB32_Euclidean_H -#define PokemonAutomation_Kernels_ImageFilter_RGB32_Euclidean_H - -#include -#include - -namespace PokemonAutomation{ -namespace Kernels{ - - - -size_t filter_rgb32_euclidean( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -); - - - - -} -} -#endif +/* Image Filters RGB32 Euclidean Distance + * + * From: https://github.com/PokemonAutomation/ + * + * Perform a filter over an image and replace pixels that match the filter. + * + */ + +#ifndef PokemonAutomation_Kernels_ImageFilter_RGB32_Euclidean_H +#define PokemonAutomation_Kernels_ImageFilter_RGB32_Euclidean_H + +#include +#include + +namespace PokemonAutomation{ +namespace Kernels{ + + + +size_t filter_rgb32_euclidean( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +); + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_ARM64_NEON.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_ARM64_NEON.cpp index ccd1f887c2..c29bd73d32 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_ARM64_NEON.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_ARM64_NEON.cpp @@ -1,204 +1,204 @@ -/* Image Filters RGB32 Euclidean - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_arm64_20_M1 - -#include "Kernels/Kernels_arm64_NEON.h" -#include "Kernels_ImageFilter_RGB32_Euclidean.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_ARM64_NEON.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - -class PixelTest_Rgb32Euclidean_ARM64_NEON{ -public: - static const size_t VECTOR_SIZE = 4; - using Mask = size_t; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Euclidean_ARM64_NEON( - uint32_t expected_color, double max_euclidean_distance - ) - : m_expected_color_rgb_u8(vreinterpretq_u8_u32(vdupq_n_u32(expected_color & 0x00ffffff))) - , m_distance_squared_u32(vdupq_n_u32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE uint32x4_t test_word(uint32x4_t& pixel) const{ - uint32x4_t& in_u32 = pixel; - // subtract the expected values - uint32x4_t in_dif_u32 = vreinterpretq_u32_u8(vabdq_u8(vreinterpretq_u8_u32(in_u32), m_expected_color_rgb_u8)); - - // Get green channel - uint32x4_t in_g_u32 = vandq_u32(in_dif_u32, vdupq_n_u32(0x0000ff00)); - // Move green channel to the lower end of the 16-bit regions - uint16x8_t in_g_u16 = vshrq_n_u16(vreinterpretq_u16_u32(in_g_u32), 8); - // in_rb_u16 contains the red and blue channels. Each channel occupies a 16-bit region - uint16x8_t in_rb_u16 = vandq_u16(vreinterpretq_u16_u32(in_dif_u32), vdupq_n_u16(0x00ff)); - - // Square operation - uint16x8_t in_g2_u16 = vmulq_u16(in_g_u16, in_g_u16); - uint16x8_t in_r2b2_u16 = vmulq_u16(in_rb_u16, in_rb_u16); - - uint32x4_t in_g2_u32 = vreinterpretq_u32_u16(in_g2_u16); - // Use pairwise addition and accumulate to add r2, g2, and b2 together - uint32x4_t sum_sqr_u32 = vpadalq_u16(in_g2_u32, in_r2b2_u16); - - // cmp_u32: if each pixel is within the range, its uint32_t in `cmp_u32` is all 1 bits, otherwise, all 0 bits - return vcleq_u32(sum_sqr_u32, m_distance_squared_u32); - } - -private: - uint8x16_t m_expected_color_rgb_u8; - uint32x4_t m_distance_squared_u32; -}; - - - -size_t filter_rgb32_euclidean_ARM64_NEON( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -){ - PixelTest_Rgb32Euclidean_ARM64_NEON tester( - expected, max_euclidean_distance - ); - FilterImage_Rgb32_ARM64_NEON filter( - tester, replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_euclidean_ARM64_NEON( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t expected, double max_euclidean_distance -){ - PixelTest_Rgb32Euclidean_ARM64_NEON tester( - expected, max_euclidean_distance - ); - ToBlackWhite_Rgb32_ARM64_NEON filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - -#if 0 - -class ImageFilter_RgbEuclidean_arm64_NEON{ -public: - static const size_t VECTOR_SIZE = 4; - using Mask = size_t; - -public: - ImageFilter_RgbEuclidean_arm64_NEON( - uint32_t replacement_color, bool replace_color_within_range, - uint32_t expected_color, double max_euclidean_distance - ) - : m_expected_color_rgb_u8(vreinterpretq_u8_u32(vdupq_n_u32(expected_color & 0x00ffffff))) - , m_distance_squared_u32(vdupq_n_u32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) - , m_replacement_color_u32(vdupq_n_u32(replacement_color)) - , m_replace_color_within_range(replace_color_within_range) - , m_count_u32(vdupq_n_u32(0)) - {} - - PA_FORCE_INLINE size_t count() const{ - uint64x2_t sum_u64 = vpaddlq_u32(m_count_u32); - return sum_u64[0] + sum_u64[1]; - } - - // Given 4 pixels from in[4], apply color range comparison and count the pixels that are in range. - // The counts are stored in m_count_u32. - // If a per-pixel mask, cmp_mask_u32 is not nullptr, it only counts the pixels covered by the mask. - // It also changes pixels in or out of the range to have the new color m_replacement_color_u32. - // The resulting pixels are saved in out[4] - PA_FORCE_INLINE void process_full(uint32_t out[4], const uint32_t in[4], const uint32x4_t* cmp_mask_u32 = nullptr){ - uint32x4_t in_u32 = vld1q_u32(in); - // subtract the expected values - uint32x4_t in_dif_u32 = vreinterpretq_u32_u8(vabdq_u8(vreinterpretq_u8_u32(in_u32), m_expected_color_rgb_u8)); - - // Get green channel - uint32x4_t in_g_u32 = vandq_u32(in_dif_u32, vdupq_n_u32(0x0000ff00)); - // Move green channel to the lower end of the 16-bit regions - uint16x8_t in_g_u16 = vshrq_n_u16(vreinterpretq_u16_u32(in_g_u32), 8); - // in_rb_u16 contains the red and blue channels. Each channel occupies a 16-bit region - uint16x8_t in_rb_u16 = vandq_u16(vreinterpretq_u16_u32(in_dif_u32), vdupq_n_u16(0x00ff)); - - // Square operation - uint16x8_t in_g2_u16 = vmulq_u16(in_g_u16, in_g_u16); - uint16x8_t in_r2b2_u16 = vmulq_u16(in_rb_u16, in_rb_u16); - - uint32x4_t in_g2_u32 = vreinterpretq_u32_u16(in_g2_u16); - // Use pairwise addition and accumulate to add r2, g2, and b2 together - uint32x4_t sum_sqr_u32 = vpadalq_u16(in_g2_u32, in_r2b2_u16); - - // cmp_u32: if each pixel is within the range, its uint32_t in `cmp_u32` is all 1 bits, otherwise, all 0 bits - uint32x4_t cmp_u32 = vcleq_u32(sum_sqr_u32, m_distance_squared_u32); - if (cmp_mask_u32) { - cmp_u32 = vandq_u32(cmp_u32, *cmp_mask_u32); - } - // Increase count for each pixel in range. Each uint32 lane is counted separately. - // We achieve +=1 by subtracting 0xFFFFFFFF - m_count_u32 = vsubq_u32(m_count_u32, cmp_u32); - // select replacement color or in_u8 based on cmp_u32: - uint32x4_t out_u32; - if (m_replace_color_within_range){ - // vbslq_u32(a, b, c) for 1 bits in a, choose b; for 0 bits in a, choose c - out_u32 = vbslq_u32(cmp_u32, m_replacement_color_u32, in_u32); - }else{ - out_u32 = vbslq_u32(cmp_u32, in_u32, m_replacement_color_u32); - } - vst1q_u32(out, out_u32); - } - // Same as `process_full()` but only process `left` (< 4) pixels - PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, size_t left){ - uint32x4_t cmp_mask_u32 = vreinterpretq_u32_u8(PartialWordAccess_arm64_NEON::create_front_mask(left * 4)); - uint32_t buffer_in[4], buffer_out[4]; - memcpy(buffer_in, in, sizeof(uint32_t) * left); - process_full(buffer_out, buffer_in, &cmp_mask_u32); - memcpy(out, buffer_out, sizeof(uint32_t) * left); - } - -private: - uint8x16_t m_expected_color_rgb_u8; - uint32x4_t m_distance_squared_u32; - uint32x4_t m_replacement_color_u32; - bool m_replace_color_within_range; - uint32x4_t m_count_u32; - -private: - -}; -size_t filter_rgb32_euclidean_arm64_NEON( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -){ - ImageFilter_RgbEuclidean_arm64_NEON filter( - replacement, replace_color_within_range, - expected, max_euclidean_distance - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -#endif - - - - -} -} -#endif +/* Image Filters RGB32 Euclidean + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_arm64_20_M1 + +#include "Kernels/Kernels_arm64_NEON.h" +#include "Kernels_ImageFilter_RGB32_Euclidean.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_ARM64_NEON.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + +class PixelTest_Rgb32Euclidean_ARM64_NEON{ +public: + static const size_t VECTOR_SIZE = 4; + using Mask = size_t; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Euclidean_ARM64_NEON( + uint32_t expected_color, double max_euclidean_distance + ) + : m_expected_color_rgb_u8(vreinterpretq_u8_u32(vdupq_n_u32(expected_color & 0x00ffffff))) + , m_distance_squared_u32(vdupq_n_u32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE uint32x4_t test_word(uint32x4_t& pixel) const{ + uint32x4_t& in_u32 = pixel; + // subtract the expected values + uint32x4_t in_dif_u32 = vreinterpretq_u32_u8(vabdq_u8(vreinterpretq_u8_u32(in_u32), m_expected_color_rgb_u8)); + + // Get green channel + uint32x4_t in_g_u32 = vandq_u32(in_dif_u32, vdupq_n_u32(0x0000ff00)); + // Move green channel to the lower end of the 16-bit regions + uint16x8_t in_g_u16 = vshrq_n_u16(vreinterpretq_u16_u32(in_g_u32), 8); + // in_rb_u16 contains the red and blue channels. Each channel occupies a 16-bit region + uint16x8_t in_rb_u16 = vandq_u16(vreinterpretq_u16_u32(in_dif_u32), vdupq_n_u16(0x00ff)); + + // Square operation + uint16x8_t in_g2_u16 = vmulq_u16(in_g_u16, in_g_u16); + uint16x8_t in_r2b2_u16 = vmulq_u16(in_rb_u16, in_rb_u16); + + uint32x4_t in_g2_u32 = vreinterpretq_u32_u16(in_g2_u16); + // Use pairwise addition and accumulate to add r2, g2, and b2 together + uint32x4_t sum_sqr_u32 = vpadalq_u16(in_g2_u32, in_r2b2_u16); + + // cmp_u32: if each pixel is within the range, its uint32_t in `cmp_u32` is all 1 bits, otherwise, all 0 bits + return vcleq_u32(sum_sqr_u32, m_distance_squared_u32); + } + +private: + uint8x16_t m_expected_color_rgb_u8; + uint32x4_t m_distance_squared_u32; +}; + + + +size_t filter_rgb32_euclidean_ARM64_NEON( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +){ + PixelTest_Rgb32Euclidean_ARM64_NEON tester( + expected, max_euclidean_distance + ); + FilterImage_Rgb32_ARM64_NEON filter( + tester, replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_euclidean_ARM64_NEON( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t expected, double max_euclidean_distance +){ + PixelTest_Rgb32Euclidean_ARM64_NEON tester( + expected, max_euclidean_distance + ); + ToBlackWhite_Rgb32_ARM64_NEON filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + +#if 0 + +class ImageFilter_RgbEuclidean_arm64_NEON{ +public: + static const size_t VECTOR_SIZE = 4; + using Mask = size_t; + +public: + ImageFilter_RgbEuclidean_arm64_NEON( + uint32_t replacement_color, bool replace_color_within_range, + uint32_t expected_color, double max_euclidean_distance + ) + : m_expected_color_rgb_u8(vreinterpretq_u8_u32(vdupq_n_u32(expected_color & 0x00ffffff))) + , m_distance_squared_u32(vdupq_n_u32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) + , m_replacement_color_u32(vdupq_n_u32(replacement_color)) + , m_replace_color_within_range(replace_color_within_range) + , m_count_u32(vdupq_n_u32(0)) + {} + + PA_FORCE_INLINE size_t count() const{ + uint64x2_t sum_u64 = vpaddlq_u32(m_count_u32); + return sum_u64[0] + sum_u64[1]; + } + + // Given 4 pixels from in[4], apply color range comparison and count the pixels that are in range. + // The counts are stored in m_count_u32. + // If a per-pixel mask, cmp_mask_u32 is not nullptr, it only counts the pixels covered by the mask. + // It also changes pixels in or out of the range to have the new color m_replacement_color_u32. + // The resulting pixels are saved in out[4] + PA_FORCE_INLINE void process_full(uint32_t out[4], const uint32_t in[4], const uint32x4_t* cmp_mask_u32 = nullptr){ + uint32x4_t in_u32 = vld1q_u32(in); + // subtract the expected values + uint32x4_t in_dif_u32 = vreinterpretq_u32_u8(vabdq_u8(vreinterpretq_u8_u32(in_u32), m_expected_color_rgb_u8)); + + // Get green channel + uint32x4_t in_g_u32 = vandq_u32(in_dif_u32, vdupq_n_u32(0x0000ff00)); + // Move green channel to the lower end of the 16-bit regions + uint16x8_t in_g_u16 = vshrq_n_u16(vreinterpretq_u16_u32(in_g_u32), 8); + // in_rb_u16 contains the red and blue channels. Each channel occupies a 16-bit region + uint16x8_t in_rb_u16 = vandq_u16(vreinterpretq_u16_u32(in_dif_u32), vdupq_n_u16(0x00ff)); + + // Square operation + uint16x8_t in_g2_u16 = vmulq_u16(in_g_u16, in_g_u16); + uint16x8_t in_r2b2_u16 = vmulq_u16(in_rb_u16, in_rb_u16); + + uint32x4_t in_g2_u32 = vreinterpretq_u32_u16(in_g2_u16); + // Use pairwise addition and accumulate to add r2, g2, and b2 together + uint32x4_t sum_sqr_u32 = vpadalq_u16(in_g2_u32, in_r2b2_u16); + + // cmp_u32: if each pixel is within the range, its uint32_t in `cmp_u32` is all 1 bits, otherwise, all 0 bits + uint32x4_t cmp_u32 = vcleq_u32(sum_sqr_u32, m_distance_squared_u32); + if (cmp_mask_u32) { + cmp_u32 = vandq_u32(cmp_u32, *cmp_mask_u32); + } + // Increase count for each pixel in range. Each uint32 lane is counted separately. + // We achieve +=1 by subtracting 0xFFFFFFFF + m_count_u32 = vsubq_u32(m_count_u32, cmp_u32); + // select replacement color or in_u8 based on cmp_u32: + uint32x4_t out_u32; + if (m_replace_color_within_range){ + // vbslq_u32(a, b, c) for 1 bits in a, choose b; for 0 bits in a, choose c + out_u32 = vbslq_u32(cmp_u32, m_replacement_color_u32, in_u32); + }else{ + out_u32 = vbslq_u32(cmp_u32, in_u32, m_replacement_color_u32); + } + vst1q_u32(out, out_u32); + } + // Same as `process_full()` but only process `left` (< 4) pixels + PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, size_t left){ + uint32x4_t cmp_mask_u32 = vreinterpretq_u32_u8(PartialWordAccess_arm64_NEON::create_front_mask(left * 4)); + uint32_t buffer_in[4], buffer_out[4]; + memcpy(buffer_in, in, sizeof(uint32_t) * left); + process_full(buffer_out, buffer_in, &cmp_mask_u32); + memcpy(out, buffer_out, sizeof(uint32_t) * left); + } + +private: + uint8x16_t m_expected_color_rgb_u8; + uint32x4_t m_distance_squared_u32; + uint32x4_t m_replacement_color_u32; + bool m_replace_color_within_range; + uint32x4_t m_count_u32; + +private: + +}; +size_t filter_rgb32_euclidean_arm64_NEON( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +){ + ImageFilter_RgbEuclidean_arm64_NEON filter( + replacement, replace_color_within_range, + expected, max_euclidean_distance + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +#endif + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_Default.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_Default.cpp index 11fc35691b..cbfb1504d1 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_Default.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_Default.cpp @@ -1,100 +1,100 @@ -/* Image Filters RGB32 Euclidean - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_Default.h" -#include "Kernels_ImageFilter_RGB32_Euclidean.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - - -class PixelTest_Rgb32Euclidean_Default{ -public: - static const size_t VECTOR_SIZE = 1; - using Mask = size_t; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Euclidean_Default( - uint32_t expected, double max_euclidean_distance - ) - : m_expected_r((expected & 0x00ff0000) >> 16) - , m_expected_g((expected & 0x0000ff00) >> 8) - , m_expected_b(expected & 0x000000ff) - , m_max_distance_squared((uint32_t)(max_euclidean_distance * max_euclidean_distance)) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE bool test_word(uint32_t pixel) const{ - uint32_t sum_sqr = 0; - { - uint32_t p = (pixel & 0x00ff0000) >> 16; - p -= m_expected_r; - sum_sqr += p * p; - } - { - uint32_t p = (pixel & 0x0000ff00) >> 8; - p -= m_expected_g; - sum_sqr += p * p; - } - { - uint32_t p = pixel & 0x000000ff; - p -= m_expected_b; - sum_sqr += p * p; - } - return sum_sqr <= m_max_distance_squared; - } - -private: - uint32_t m_expected_r; - uint32_t m_expected_g; - uint32_t m_expected_b; - uint32_t m_max_distance_squared; -}; - - - -size_t filter_rgb32_euclidean_Default( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -){ - PixelTest_Rgb32Euclidean_Default tester( - expected, max_euclidean_distance - ); - FilterImage_Rgb32_Default filter( - tester, replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_euclidean_Default( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t expected, double max_euclidean_distance -){ - PixelTest_Rgb32Euclidean_Default tester( - expected, max_euclidean_distance - ); - ToBlackWhite_Rgb32_Default filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - - - - -} -} +/* Image Filters RGB32 Euclidean + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_Default.h" +#include "Kernels_ImageFilter_RGB32_Euclidean.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + + +class PixelTest_Rgb32Euclidean_Default{ +public: + static const size_t VECTOR_SIZE = 1; + using Mask = size_t; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Euclidean_Default( + uint32_t expected, double max_euclidean_distance + ) + : m_expected_r((expected & 0x00ff0000) >> 16) + , m_expected_g((expected & 0x0000ff00) >> 8) + , m_expected_b(expected & 0x000000ff) + , m_max_distance_squared((uint32_t)(max_euclidean_distance * max_euclidean_distance)) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE bool test_word(uint32_t pixel) const{ + uint32_t sum_sqr = 0; + { + uint32_t p = (pixel & 0x00ff0000) >> 16; + p -= m_expected_r; + sum_sqr += p * p; + } + { + uint32_t p = (pixel & 0x0000ff00) >> 8; + p -= m_expected_g; + sum_sqr += p * p; + } + { + uint32_t p = pixel & 0x000000ff; + p -= m_expected_b; + sum_sqr += p * p; + } + return sum_sqr <= m_max_distance_squared; + } + +private: + uint32_t m_expected_r; + uint32_t m_expected_g; + uint32_t m_expected_b; + uint32_t m_max_distance_squared; +}; + + + +size_t filter_rgb32_euclidean_Default( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +){ + PixelTest_Rgb32Euclidean_Default tester( + expected, max_euclidean_distance + ); + FilterImage_Rgb32_Default filter( + tester, replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_euclidean_Default( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t expected, double max_euclidean_distance +){ + PixelTest_Rgb32Euclidean_Default tester( + expected, max_euclidean_distance + ); + ToBlackWhite_Rgb32_Default filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_AVX2.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_AVX2.cpp index ea4833d072..dbf9de431f 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_AVX2.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_AVX2.cpp @@ -1,97 +1,97 @@ -/* Image Filters RGB32 Euclidean - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_13_Haswell - -#include -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX2.h" -#include "Kernels_ImageFilter_RGB32_Euclidean.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - -class PixelTest_Rgb32Euclidean_x64_AVX2{ -public: - static const size_t VECTOR_SIZE = 8; - using Mask = PartialWordAccess32_x64_AVX2; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Euclidean_x64_AVX2( - uint32_t expected, double max_euclidean_distance - ) - : m_expected_ag(_mm256_set1_epi32((expected >> 8) & 0x000000ff)) - , m_expected_rb(_mm256_set1_epi32(expected & 0x00ff00ff)) - , m_distance_squared(_mm256_set1_epi32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __m256i test_word(__m256i pixel) const{ - __m256i ag = _mm256_and_si256(_mm256_srli_epi16(pixel, 8), _mm256_set1_epi32(0x000000ff)); - __m256i rb = _mm256_and_si256(pixel, _mm256_set1_epi32(0x00ff00ff)); - - ag = _mm256_sub_epi16(ag, m_expected_ag); - rb = _mm256_sub_epi16(rb, m_expected_rb); - - __m256i g = _mm256_mullo_epi16(ag, ag); - rb = _mm256_mullo_epi16(rb, rb); - __m256i r = _mm256_srli_epi32(rb, 16); - __m256i b = _mm256_and_si256(rb, _mm256_set1_epi32(0x0000ffff)); - - __m256i sum_sqr = _mm256_add_epi32(r, g); - sum_sqr = _mm256_add_epi32(sum_sqr, b); - - return _mm256_cmpgt_epi32(m_distance_squared, sum_sqr); - } - -private: - const __m256i m_expected_ag; - const __m256i m_expected_rb; - const __m256i m_distance_squared; -}; - - - -size_t filter_rgb32_euclidean_x64_AVX2( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -){ - PixelTest_Rgb32Euclidean_x64_AVX2 tester( - expected, max_euclidean_distance - ); - FilterImage_Rgb32_x64_AVX2 filter( - tester, replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_euclidean_x64_AVX2( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t expected, double max_euclidean_distance -){ - PixelTest_Rgb32Euclidean_x64_AVX2 tester( - expected, max_euclidean_distance - ); - ToBlackWhite_Rgb32_x64_AVX2 filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - -} -} -#endif +/* Image Filters RGB32 Euclidean + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_13_Haswell + +#include +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX2.h" +#include "Kernels_ImageFilter_RGB32_Euclidean.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + +class PixelTest_Rgb32Euclidean_x64_AVX2{ +public: + static const size_t VECTOR_SIZE = 8; + using Mask = PartialWordAccess32_x64_AVX2; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Euclidean_x64_AVX2( + uint32_t expected, double max_euclidean_distance + ) + : m_expected_ag(_mm256_set1_epi32((expected >> 8) & 0x000000ff)) + , m_expected_rb(_mm256_set1_epi32(expected & 0x00ff00ff)) + , m_distance_squared(_mm256_set1_epi32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __m256i test_word(__m256i pixel) const{ + __m256i ag = _mm256_and_si256(_mm256_srli_epi16(pixel, 8), _mm256_set1_epi32(0x000000ff)); + __m256i rb = _mm256_and_si256(pixel, _mm256_set1_epi32(0x00ff00ff)); + + ag = _mm256_sub_epi16(ag, m_expected_ag); + rb = _mm256_sub_epi16(rb, m_expected_rb); + + __m256i g = _mm256_mullo_epi16(ag, ag); + rb = _mm256_mullo_epi16(rb, rb); + __m256i r = _mm256_srli_epi32(rb, 16); + __m256i b = _mm256_and_si256(rb, _mm256_set1_epi32(0x0000ffff)); + + __m256i sum_sqr = _mm256_add_epi32(r, g); + sum_sqr = _mm256_add_epi32(sum_sqr, b); + + return _mm256_cmpgt_epi32(m_distance_squared, sum_sqr); + } + +private: + const __m256i m_expected_ag; + const __m256i m_expected_rb; + const __m256i m_distance_squared; +}; + + + +size_t filter_rgb32_euclidean_x64_AVX2( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +){ + PixelTest_Rgb32Euclidean_x64_AVX2 tester( + expected, max_euclidean_distance + ); + FilterImage_Rgb32_x64_AVX2 filter( + tester, replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_euclidean_x64_AVX2( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t expected, double max_euclidean_distance +){ + PixelTest_Rgb32Euclidean_x64_AVX2 tester( + expected, max_euclidean_distance + ); + ToBlackWhite_Rgb32_x64_AVX2 filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_AVX512.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_AVX512.cpp index 1e7be0e457..fcca03a2d4 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_AVX512.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_AVX512.cpp @@ -1,97 +1,97 @@ -/* Image Filters RGB32 Euclidean - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_17_Skylake - -#include -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX512.h" -#include "Kernels_ImageFilter_RGB32_Euclidean.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - - -class PixelTest_Rgb32Euclidean_x64_AVX512{ -public: - static const size_t VECTOR_SIZE = 16; - using Mask = PartialWordMask; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Euclidean_x64_AVX512( - uint32_t expected, double max_euclidean_distance - ) - : m_expected_ag(_mm512_set1_epi32((expected >> 8) & 0x000000ff)) - , m_expected_rb(_mm512_set1_epi32(expected & 0x00ff00ff)) - , m_distance_squared(_mm512_set1_epi32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __mmask16 test_word(__m512i pixel) const{ - __m512i ag = _mm512_and_si512(_mm512_srli_epi16(pixel, 8), _mm512_set1_epi32(0x000000ff)); - __m512i rb = _mm512_and_si512(pixel, _mm512_set1_epi32(0x00ff00ff)); - - ag = _mm512_sub_epi16(ag, m_expected_ag); - rb = _mm512_sub_epi16(rb, m_expected_rb); - - __m512i g = _mm512_mullo_epi16(ag, ag); - rb = _mm512_mullo_epi16(rb, rb); - __m512i r = _mm512_srli_epi32(rb, 16); - __m512i b = _mm512_and_si512(rb, _mm512_set1_epi32(0x0000ffff)); - - __m512i sum_sqr = _mm512_add_epi32(r, g); - sum_sqr = _mm512_add_epi32(sum_sqr, b); - - return _mm512_cmpgt_epi32_mask(m_distance_squared, sum_sqr); - } - -private: - const __m512i m_expected_ag; - const __m512i m_expected_rb; - const __m512i m_distance_squared; -}; - - - -size_t filter_rgb32_euclidean_x64_AVX512( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -){ - PixelTest_Rgb32Euclidean_x64_AVX512 tester( - expected, max_euclidean_distance - ); - FilterImage_Rgb32_x64_AVX512 filter( - tester, replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_euclidean_x64_AVX512( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t expected, double max_euclidean_distance -){ - PixelTest_Rgb32Euclidean_x64_AVX512 tester( - expected, max_euclidean_distance - ); - ToBlackWhite_Rgb32_x64_AVX512 filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - -} -} -#endif +/* Image Filters RGB32 Euclidean + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_17_Skylake + +#include +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX512.h" +#include "Kernels_ImageFilter_RGB32_Euclidean.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + + +class PixelTest_Rgb32Euclidean_x64_AVX512{ +public: + static const size_t VECTOR_SIZE = 16; + using Mask = PartialWordMask; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Euclidean_x64_AVX512( + uint32_t expected, double max_euclidean_distance + ) + : m_expected_ag(_mm512_set1_epi32((expected >> 8) & 0x000000ff)) + , m_expected_rb(_mm512_set1_epi32(expected & 0x00ff00ff)) + , m_distance_squared(_mm512_set1_epi32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __mmask16 test_word(__m512i pixel) const{ + __m512i ag = _mm512_and_si512(_mm512_srli_epi16(pixel, 8), _mm512_set1_epi32(0x000000ff)); + __m512i rb = _mm512_and_si512(pixel, _mm512_set1_epi32(0x00ff00ff)); + + ag = _mm512_sub_epi16(ag, m_expected_ag); + rb = _mm512_sub_epi16(rb, m_expected_rb); + + __m512i g = _mm512_mullo_epi16(ag, ag); + rb = _mm512_mullo_epi16(rb, rb); + __m512i r = _mm512_srli_epi32(rb, 16); + __m512i b = _mm512_and_si512(rb, _mm512_set1_epi32(0x0000ffff)); + + __m512i sum_sqr = _mm512_add_epi32(r, g); + sum_sqr = _mm512_add_epi32(sum_sqr, b); + + return _mm512_cmpgt_epi32_mask(m_distance_squared, sum_sqr); + } + +private: + const __m512i m_expected_ag; + const __m512i m_expected_rb; + const __m512i m_distance_squared; +}; + + + +size_t filter_rgb32_euclidean_x64_AVX512( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +){ + PixelTest_Rgb32Euclidean_x64_AVX512 tester( + expected, max_euclidean_distance + ); + FilterImage_Rgb32_x64_AVX512 filter( + tester, replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_euclidean_x64_AVX512( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t expected, double max_euclidean_distance +){ + PixelTest_Rgb32Euclidean_x64_AVX512 tester( + expected, max_euclidean_distance + ); + ToBlackWhite_Rgb32_x64_AVX512 filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_SSE42.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_SSE42.cpp index cc238db2e9..447575ed81 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_SSE42.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_SSE42.cpp @@ -1,114 +1,114 @@ -/* Image Filters RGB32 Euclidean - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_08_Nehalem - -#include -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_SSE42.h" -#include "Kernels_ImageFilter_RGB32_Euclidean.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - - - -class PixelTest_Rgb32Euclidean_x64_SSE42{ -public: - static const size_t VECTOR_SIZE = 4; - using Mask = PartialWordMask; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Euclidean_x64_SSE42( - uint32_t expected, double max_euclidean_distance - ) - : m_expected_g(_mm_set1_epi32((expected >> 8) & 0x000000ff)) - , m_expected_rb(_mm_set1_epi32(expected & 0x00ff00ff)) - , m_distance_squared(_mm_set1_epi32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __m128i test_word(__m128i pixel) const{ - // _mm_srli_epi16: Shift 16-bit integers in pixels right by 8 while shifting in zeros, - // ng: green channels of each pixel, but shifted right by 8 bits - __m128i ng = _mm_and_si128(_mm_srli_epi16(pixel, 8), _mm_set1_epi32(0x000000ff)); - // rb: the red and blue channels of each pixel - __m128i rb = _mm_and_si128(pixel, _mm_set1_epi32(0x00ff00ff)); - // g: the difference between input pixel channels and the expected values - ng = _mm_sub_epi16(ng, m_expected_g); - rb = _mm_sub_epi16(rb, m_expected_rb); - // compute square operation: - // now each 16-bit region is a squared channel difference - // here we assume alpha channel from input image is the same as the expected, - // so the alpha channel difference is always 0, therefore: - // g: each 32-bit integer contains the green channel squared difference - __m128i g = _mm_mullo_epi16(ng, ng); - rb = _mm_mullo_epi16(rb, rb); - // r: each 32-bit integer contains the red channel squared difference - __m128i r = _mm_srli_epi32(rb, 16); - // b: each 32-bit integer contains the blue channel squared difference - __m128i b = _mm_and_si128(rb, _mm_set1_epi32(0x0000ffff)); - // compute r^2 + g^2 + b^2 - __m128i sum_sqr = _mm_add_epi32(r, g); - sum_sqr = _mm_add_epi32(sum_sqr, b); - - return _mm_cmpgt_epi32(m_distance_squared, sum_sqr); - } - -private: - const __m128i m_expected_g; - const __m128i m_expected_rb; - const __m128i m_distance_squared; -}; - - - -size_t filter_rgb32_euclidean_x64_SSE42( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -){ - PixelTest_Rgb32Euclidean_x64_SSE42 tester( - expected, max_euclidean_distance - ); - FilterImage_Rgb32_x64_SSE42 filter( - tester, replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_euclidean_x64_SSE42( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t expected, double max_euclidean_distance -){ - PixelTest_Rgb32Euclidean_x64_SSE42 tester( - expected, max_euclidean_distance - ); - ToBlackWhite_Rgb32_x64_SSE42 filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - - - - - -} -} -#endif +/* Image Filters RGB32 Euclidean + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_08_Nehalem + +#include +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_SSE42.h" +#include "Kernels_ImageFilter_RGB32_Euclidean.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + + + +class PixelTest_Rgb32Euclidean_x64_SSE42{ +public: + static const size_t VECTOR_SIZE = 4; + using Mask = PartialWordMask; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Euclidean_x64_SSE42( + uint32_t expected, double max_euclidean_distance + ) + : m_expected_g(_mm_set1_epi32((expected >> 8) & 0x000000ff)) + , m_expected_rb(_mm_set1_epi32(expected & 0x00ff00ff)) + , m_distance_squared(_mm_set1_epi32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __m128i test_word(__m128i pixel) const{ + // _mm_srli_epi16: Shift 16-bit integers in pixels right by 8 while shifting in zeros, + // ng: green channels of each pixel, but shifted right by 8 bits + __m128i ng = _mm_and_si128(_mm_srli_epi16(pixel, 8), _mm_set1_epi32(0x000000ff)); + // rb: the red and blue channels of each pixel + __m128i rb = _mm_and_si128(pixel, _mm_set1_epi32(0x00ff00ff)); + // g: the difference between input pixel channels and the expected values + ng = _mm_sub_epi16(ng, m_expected_g); + rb = _mm_sub_epi16(rb, m_expected_rb); + // compute square operation: + // now each 16-bit region is a squared channel difference + // here we assume alpha channel from input image is the same as the expected, + // so the alpha channel difference is always 0, therefore: + // g: each 32-bit integer contains the green channel squared difference + __m128i g = _mm_mullo_epi16(ng, ng); + rb = _mm_mullo_epi16(rb, rb); + // r: each 32-bit integer contains the red channel squared difference + __m128i r = _mm_srli_epi32(rb, 16); + // b: each 32-bit integer contains the blue channel squared difference + __m128i b = _mm_and_si128(rb, _mm_set1_epi32(0x0000ffff)); + // compute r^2 + g^2 + b^2 + __m128i sum_sqr = _mm_add_epi32(r, g); + sum_sqr = _mm_add_epi32(sum_sqr, b); + + return _mm_cmpgt_epi32(m_distance_squared, sum_sqr); + } + +private: + const __m128i m_expected_g; + const __m128i m_expected_rb; + const __m128i m_distance_squared; +}; + + + +size_t filter_rgb32_euclidean_x64_SSE42( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +){ + PixelTest_Rgb32Euclidean_x64_SSE42 tester( + expected, max_euclidean_distance + ); + FilterImage_Rgb32_x64_SSE42 filter( + tester, replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_euclidean_x64_SSE42( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t expected, double max_euclidean_distance +){ + PixelTest_Rgb32Euclidean_x64_SSE42 tester( + expected, max_euclidean_distance + ); + ToBlackWhite_Rgb32_x64_SSE42 filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.cpp index 1fab584590..0c5943a5ec 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.cpp @@ -1,349 +1,349 @@ -/* Image Filters RGB32 Range - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/CpuId/CpuId.h" -#include "Kernels_ImageFilter_RGB32_Range.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - - - -size_t filter_rgb32_range_Default( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t mins, uint32_t maxs -); -size_t filter_rgb32_range_x64_SSE42( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t mins, uint32_t maxs -); -size_t filter_rgb32_range_x64_AVX2( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t mins, uint32_t maxs -); -size_t filter_rgb32_range_x64_AVX512( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t mins, uint32_t maxs -); -size_t filter_rgb32_range_arm64_NEON( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t mins, uint32_t maxs -); -size_t filter_rgb32_range( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t mins, uint32_t maxs -){ - if (width * height > 0xffffffff){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); - } -#ifdef PA_AutoDispatch_x64_17_Skylake - if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ - return filter_rgb32_range_x64_AVX512( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - mins, maxs - ); - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ - return filter_rgb32_range_x64_AVX2( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - mins, maxs - ); - } -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - return filter_rgb32_range_x64_SSE42( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - mins, maxs - ); - } -#endif -#ifdef PA_AutoDispatch_arm64_20_M1 - if (CPU_CAPABILITY_CURRENT.OK_M1){ - return filter_rgb32_range_arm64_NEON( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - mins, maxs - ); - } -#endif - return filter_rgb32_range_Default( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - mins, maxs - ); -} - - -#if 0 -void filter_rgb32_range_Default( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - FilterRgb32RangeFilter* filter, size_t filter_count -); -void filter_rgb32_range_x64_SSE42( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - FilterRgb32RangeFilter* filter, size_t filter_count -); -void filter_rgb32_range_x64_AVX2( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - FilterRgb32RangeFilter* filter, size_t filter_count -); -void filter_rgb32_range_x64_AVX512( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - FilterRgb32RangeFilter* filter, size_t filter_count -); -void filter_rgb32_range_arm64_NEON( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - FilterRgb32RangeFilter* filter, size_t filter_count -); -void filter_rgb32_range( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - FilterRgb32RangeFilter* filter, size_t filter_count -){ - if (width * height > 0xffffffff){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); - } -#ifdef PA_AutoDispatch_x64_17_Skylake - if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ - filter_rgb32_range_x64_AVX512(image, bytes_per_row, width, height, filter, filter_count); - return; - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ - filter_rgb32_range_x64_AVX2(image, bytes_per_row, width, height, filter, filter_count); - return; - } -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - filter_rgb32_range_x64_SSE42(image, bytes_per_row, width, height, filter, filter_count); - return; - } -#endif -#ifdef PA_AutoDispatch_arm64_20_M1 - if (CPU_CAPABILITY_CURRENT.OK_M1){ - filter_rgb32_range_arm64_NEON(image, bytes_per_row, width, height, filter, filter_count); - return; - } -#endif - filter_rgb32_range_Default(image, bytes_per_row, width, height, filter, filter_count); -} -#endif - -void filter_rgb32_range( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - FilterRgb32RangeFilter* filter, size_t filter_count -){ - for (size_t c = 0; c < filter_count; c++){ - filter[c].pixels_in_range = filter_rgb32_range( - image, bytes_per_row, width, height, - filter[c].data, filter[c].bytes_per_row, - filter[c].replacement, - filter[c].pixels_in_range, - filter[c].mins, - filter[c].maxs - ); - } -} - - - - - - -size_t to_blackwhite_rgb32_range_Default( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t mins, uint32_t maxs -); -size_t to_blackwhite_rgb32_range_x64_SSE42( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t mins, uint32_t maxs -); -size_t to_blackwhite_rgb32_range_x64_AVX2( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t mins, uint32_t maxs -); -size_t to_blackwhite_rgb32_range_x64_AVX512( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t mins, uint32_t maxs -); -size_t to_blackwhite_rgb32_range_arm64_NEON( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t mins, uint32_t maxs -); -size_t to_blackwhite_rgb32_range( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t mins, uint32_t maxs -){ - if (width * height > 0xffffffff){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); - } -#ifdef PA_AutoDispatch_x64_17_Skylake - if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ - return to_blackwhite_rgb32_range_x64_AVX512( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - in_range_black, - mins, maxs - ); - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ - return to_blackwhite_rgb32_range_x64_AVX2( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - in_range_black, - mins, maxs - ); - } -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - return to_blackwhite_rgb32_range_x64_SSE42( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - in_range_black, - mins, maxs - ); - } -#endif -#ifdef PA_AutoDispatch_arm64_20_M1 - if (CPU_CAPABILITY_CURRENT.OK_M1){ - return to_blackwhite_rgb32_range_arm64_NEON( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - in_range_black, - mins, maxs - ); - } -#endif - return to_blackwhite_rgb32_range_Default( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - in_range_black, - mins, maxs - ); -} - - - -#if 0 -void to_blackwhite_rgb32_range_Default( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count -); -void to_blackwhite_rgb32_range_x64_SSE42( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count -); -void to_blackwhite_rgb32_range_x64_AVX2( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count -); -void to_blackwhite_rgb32_range_x64_AVX512( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count -); -void to_blackwhite_rgb32_range_arm64_NEON( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count -); -void to_blackwhite_rgb32_range( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count -){ -#ifdef PA_AutoDispatch_x64_17_Skylake - if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ - return to_blackwhite_rgb32_range_x64_AVX512(image, bytes_per_row, width, height, filter, filter_count); - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ - return to_blackwhite_rgb32_range_x64_AVX2(image, bytes_per_row, width, height, filter, filter_count); - } -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - return to_blackwhite_rgb32_range_x64_SSE42(image, bytes_per_row, width, height, filter, filter_count); - } -#endif -#ifdef PA_AutoDispatch_arm64_20_M1 - if (CPU_CAPABILITY_CURRENT.OK_M1){ - return to_blackwhite_rgb32_range_arm64_NEON(image, bytes_per_row, width, height, filter, filter_count); - } -#endif - return to_blackwhite_rgb32_range_Default(image, bytes_per_row, width, height, filter, filter_count); -} -#endif - -void to_blackwhite_rgb32_range( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count -){ - for (size_t c = 0; c < filter_count; c++){ - filter[c].pixels_in_range = to_blackwhite_rgb32_range( - image, bytes_per_row, width, height, - filter[c].data, filter[c].bytes_per_row, - filter[c].in_range_black, - filter[c].mins, - filter[c].maxs - ); - } -} - - - - - - - - - - -} -} +/* Image Filters RGB32 Range + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/CpuId/CpuId.h" +#include "Kernels_ImageFilter_RGB32_Range.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + + + +size_t filter_rgb32_range_Default( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t mins, uint32_t maxs +); +size_t filter_rgb32_range_x64_SSE42( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t mins, uint32_t maxs +); +size_t filter_rgb32_range_x64_AVX2( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t mins, uint32_t maxs +); +size_t filter_rgb32_range_x64_AVX512( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t mins, uint32_t maxs +); +size_t filter_rgb32_range_arm64_NEON( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t mins, uint32_t maxs +); +size_t filter_rgb32_range( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t mins, uint32_t maxs +){ + if (width * height > 0xffffffff){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); + } +#ifdef PA_AutoDispatch_x64_17_Skylake + if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ + return filter_rgb32_range_x64_AVX512( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + mins, maxs + ); + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ + return filter_rgb32_range_x64_AVX2( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + mins, maxs + ); + } +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + return filter_rgb32_range_x64_SSE42( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + mins, maxs + ); + } +#endif +#ifdef PA_AutoDispatch_arm64_20_M1 + if (CPU_CAPABILITY_CURRENT.OK_M1){ + return filter_rgb32_range_arm64_NEON( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + mins, maxs + ); + } +#endif + return filter_rgb32_range_Default( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + mins, maxs + ); +} + + +#if 0 +void filter_rgb32_range_Default( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + FilterRgb32RangeFilter* filter, size_t filter_count +); +void filter_rgb32_range_x64_SSE42( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + FilterRgb32RangeFilter* filter, size_t filter_count +); +void filter_rgb32_range_x64_AVX2( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + FilterRgb32RangeFilter* filter, size_t filter_count +); +void filter_rgb32_range_x64_AVX512( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + FilterRgb32RangeFilter* filter, size_t filter_count +); +void filter_rgb32_range_arm64_NEON( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + FilterRgb32RangeFilter* filter, size_t filter_count +); +void filter_rgb32_range( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + FilterRgb32RangeFilter* filter, size_t filter_count +){ + if (width * height > 0xffffffff){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); + } +#ifdef PA_AutoDispatch_x64_17_Skylake + if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ + filter_rgb32_range_x64_AVX512(image, bytes_per_row, width, height, filter, filter_count); + return; + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ + filter_rgb32_range_x64_AVX2(image, bytes_per_row, width, height, filter, filter_count); + return; + } +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + filter_rgb32_range_x64_SSE42(image, bytes_per_row, width, height, filter, filter_count); + return; + } +#endif +#ifdef PA_AutoDispatch_arm64_20_M1 + if (CPU_CAPABILITY_CURRENT.OK_M1){ + filter_rgb32_range_arm64_NEON(image, bytes_per_row, width, height, filter, filter_count); + return; + } +#endif + filter_rgb32_range_Default(image, bytes_per_row, width, height, filter, filter_count); +} +#endif + +void filter_rgb32_range( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + FilterRgb32RangeFilter* filter, size_t filter_count +){ + for (size_t c = 0; c < filter_count; c++){ + filter[c].pixels_in_range = filter_rgb32_range( + image, bytes_per_row, width, height, + filter[c].data, filter[c].bytes_per_row, + filter[c].replacement, + filter[c].pixels_in_range, + filter[c].mins, + filter[c].maxs + ); + } +} + + + + + + +size_t to_blackwhite_rgb32_range_Default( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t mins, uint32_t maxs +); +size_t to_blackwhite_rgb32_range_x64_SSE42( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t mins, uint32_t maxs +); +size_t to_blackwhite_rgb32_range_x64_AVX2( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t mins, uint32_t maxs +); +size_t to_blackwhite_rgb32_range_x64_AVX512( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t mins, uint32_t maxs +); +size_t to_blackwhite_rgb32_range_arm64_NEON( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t mins, uint32_t maxs +); +size_t to_blackwhite_rgb32_range( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t mins, uint32_t maxs +){ + if (width * height > 0xffffffff){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); + } +#ifdef PA_AutoDispatch_x64_17_Skylake + if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ + return to_blackwhite_rgb32_range_x64_AVX512( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + in_range_black, + mins, maxs + ); + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ + return to_blackwhite_rgb32_range_x64_AVX2( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + in_range_black, + mins, maxs + ); + } +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + return to_blackwhite_rgb32_range_x64_SSE42( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + in_range_black, + mins, maxs + ); + } +#endif +#ifdef PA_AutoDispatch_arm64_20_M1 + if (CPU_CAPABILITY_CURRENT.OK_M1){ + return to_blackwhite_rgb32_range_arm64_NEON( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + in_range_black, + mins, maxs + ); + } +#endif + return to_blackwhite_rgb32_range_Default( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + in_range_black, + mins, maxs + ); +} + + + +#if 0 +void to_blackwhite_rgb32_range_Default( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count +); +void to_blackwhite_rgb32_range_x64_SSE42( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count +); +void to_blackwhite_rgb32_range_x64_AVX2( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count +); +void to_blackwhite_rgb32_range_x64_AVX512( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count +); +void to_blackwhite_rgb32_range_arm64_NEON( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count +); +void to_blackwhite_rgb32_range( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count +){ +#ifdef PA_AutoDispatch_x64_17_Skylake + if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ + return to_blackwhite_rgb32_range_x64_AVX512(image, bytes_per_row, width, height, filter, filter_count); + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ + return to_blackwhite_rgb32_range_x64_AVX2(image, bytes_per_row, width, height, filter, filter_count); + } +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + return to_blackwhite_rgb32_range_x64_SSE42(image, bytes_per_row, width, height, filter, filter_count); + } +#endif +#ifdef PA_AutoDispatch_arm64_20_M1 + if (CPU_CAPABILITY_CURRENT.OK_M1){ + return to_blackwhite_rgb32_range_arm64_NEON(image, bytes_per_row, width, height, filter, filter_count); + } +#endif + return to_blackwhite_rgb32_range_Default(image, bytes_per_row, width, height, filter, filter_count); +} +#endif + +void to_blackwhite_rgb32_range( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count +){ + for (size_t c = 0; c < filter_count; c++){ + filter[c].pixels_in_range = to_blackwhite_rgb32_range( + image, bytes_per_row, width, height, + filter[c].data, filter[c].bytes_per_row, + filter[c].in_range_black, + filter[c].mins, + filter[c].maxs + ); + } +} + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.h b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.h index 545eca4c35..d312e22151 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.h +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.h @@ -1,110 +1,110 @@ -/* Image Filters RGB32 Range - * - * From: https://github.com/PokemonAutomation/ - * - * Perform a filter over an image and replace pixels that match the filter. - * - */ - -#ifndef PokemonAutomation_Kernels_ImageFilter_RGB32_Range_H -#define PokemonAutomation_Kernels_ImageFilter_RGB32_Range_H - -#include -#include - -namespace PokemonAutomation{ -namespace Kernels{ - - -// Change certain color in `image_in` and save output to `image_out`. -// If `replace_color_within_range` is true, replace the color within range [mins, maxs] with the color `replacement`. -// If `replace_color_within_range` is false, replace the color outside of the range with the color `replacement`. -// Returns the # of pixels inside the range [mins, maxs]. -size_t filter_rgb32_range( - const uint32_t* image_in, size_t image_in_bytes_per_row, size_t width, size_t height, - uint32_t* image_out, size_t image_out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t mins, uint32_t maxs -); - - -// Same as above, but multiple filters. -// The purpose is to reduce passes over the entire image. -// All matricies must have the same dimensions. -struct FilterRgb32RangeFilter{ - uint32_t* data; // Pointer will be overwritten. - const size_t bytes_per_row; - const uint32_t replacement; - const bool invert; - const uint32_t mins; - const uint32_t maxs; - - size_t pixels_in_range; - - FilterRgb32RangeFilter( - uint32_t* p_data, size_t p_bytes_per_row, - uint32_t p_replacement, bool p_invert, - uint32_t p_mins, uint32_t p_maxs - ) - : data(p_data) - , bytes_per_row(p_bytes_per_row) - , replacement(p_replacement) - , invert(p_invert) - , mins(p_mins) - , maxs(p_maxs) - {} -}; -void filter_rgb32_range( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - FilterRgb32RangeFilter* filter, size_t filter_count -); - - - - - - - -size_t to_blackwhite_rgb32_range( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t mins, uint32_t maxs -); - - -// Same as above, but multiple filters. -// The purpose is to reduce passes over the entire image. -// All matricies must have the same dimensions. -struct ToBlackWhiteRgb32RangeFilter{ - uint32_t* const data; - const size_t bytes_per_row; - const uint32_t mins; - const uint32_t maxs; - const bool in_range_black; - - size_t pixels_in_range; - - ToBlackWhiteRgb32RangeFilter( - uint32_t* p_data, size_t p_bytes_per_row, - uint32_t p_mins, uint32_t p_maxs, bool p_in_range_black - ) - : data(p_data) - , bytes_per_row(p_bytes_per_row) - , mins(p_mins) - , maxs(p_maxs) - , in_range_black(p_in_range_black) - {} -}; -void to_blackwhite_rgb32_range( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count -); - - - - - -} -} -#endif +/* Image Filters RGB32 Range + * + * From: https://github.com/PokemonAutomation/ + * + * Perform a filter over an image and replace pixels that match the filter. + * + */ + +#ifndef PokemonAutomation_Kernels_ImageFilter_RGB32_Range_H +#define PokemonAutomation_Kernels_ImageFilter_RGB32_Range_H + +#include +#include + +namespace PokemonAutomation{ +namespace Kernels{ + + +// Change certain color in `image_in` and save output to `image_out`. +// If `replace_color_within_range` is true, replace the color within range [mins, maxs] with the color `replacement`. +// If `replace_color_within_range` is false, replace the color outside of the range with the color `replacement`. +// Returns the # of pixels inside the range [mins, maxs]. +size_t filter_rgb32_range( + const uint32_t* image_in, size_t image_in_bytes_per_row, size_t width, size_t height, + uint32_t* image_out, size_t image_out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t mins, uint32_t maxs +); + + +// Same as above, but multiple filters. +// The purpose is to reduce passes over the entire image. +// All matricies must have the same dimensions. +struct FilterRgb32RangeFilter{ + uint32_t* data; // Pointer will be overwritten. + const size_t bytes_per_row; + const uint32_t replacement; + const bool invert; + const uint32_t mins; + const uint32_t maxs; + + size_t pixels_in_range; + + FilterRgb32RangeFilter( + uint32_t* p_data, size_t p_bytes_per_row, + uint32_t p_replacement, bool p_invert, + uint32_t p_mins, uint32_t p_maxs + ) + : data(p_data) + , bytes_per_row(p_bytes_per_row) + , replacement(p_replacement) + , invert(p_invert) + , mins(p_mins) + , maxs(p_maxs) + {} +}; +void filter_rgb32_range( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + FilterRgb32RangeFilter* filter, size_t filter_count +); + + + + + + + +size_t to_blackwhite_rgb32_range( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t mins, uint32_t maxs +); + + +// Same as above, but multiple filters. +// The purpose is to reduce passes over the entire image. +// All matricies must have the same dimensions. +struct ToBlackWhiteRgb32RangeFilter{ + uint32_t* const data; + const size_t bytes_per_row; + const uint32_t mins; + const uint32_t maxs; + const bool in_range_black; + + size_t pixels_in_range; + + ToBlackWhiteRgb32RangeFilter( + uint32_t* p_data, size_t p_bytes_per_row, + uint32_t p_mins, uint32_t p_maxs, bool p_in_range_black + ) + : data(p_data) + , bytes_per_row(p_bytes_per_row) + , mins(p_mins) + , maxs(p_maxs) + , in_range_black(p_in_range_black) + {} +}; +void to_blackwhite_rgb32_range( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count +); + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_ARM64_NEON.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_ARM64_NEON.cpp index c02f5851cf..97c070c8d9 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_ARM64_NEON.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_ARM64_NEON.cpp @@ -1,106 +1,106 @@ -/* Image Filters RGB32 Range - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_arm64_20_M1 - -#include "Kernels/Kernels_arm64_NEON.h" -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_ARM64_NEON.h" -#include "Kernels_ImageFilter_RGB32_Range_Routines.h" -#include "Kernels_ImageFilter_RGB32_Range.h" - - - -namespace PokemonAutomation{ -namespace Kernels{ - - - - -class PixelTest_Rgb32Range_ARM64_NEON{ -public: - static const size_t VECTOR_SIZE = 4; - using Mask = size_t; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Range_ARM64_NEON( - uint32_t mins, uint32_t maxs - ) - : m_mins_u8(vreinterpretq_u8_u32(vdupq_n_u32(mins))) - , m_maxs_u8(vreinterpretq_u8_u32(vdupq_n_u32(maxs))) - , m_zeros_u8(vreinterpretq_u32_u8(vdupq_n_u8(0))) - {} - PA_FORCE_INLINE PixelTest_Rgb32Range_ARM64_NEON( - const ToBlackWhiteRgb32RangeFilter& filter - ) - : m_mins_u8(vreinterpretq_u8_u32(vdupq_n_u32(filter.mins))) - , m_maxs_u8(vreinterpretq_u8_u32(vdupq_n_u32(filter.maxs))) - , m_zeros_u8(vreinterpretq_u32_u8(vdupq_n_u8(0))) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE uint32x4_t test_word(uint32x4_t& pixel) const{ - uint8x16_t in_u8 = vreinterpretq_u8_u32(pixel); - - // Check if mins > pixel per color channel - uint8x16_t cmp0 = vcgtq_u8(m_mins_u8, in_u8); - // Check if pixel > maxs per color channel - uint8x16_t cmp1 = vcgtq_u8(in_u8, m_maxs_u8); - // cmp: if mins > pixel or pixel > maxs per color channel - uint8x16_t cmp_u8 = vorrq_u8(cmp0, cmp1); - // vceqq_u32: compare bitwise equal - // cmp_u32: if each pixel is within the range - // If a pixel is within [mins, maxs], its uint32_t in `cmp_u32` is all 1 bits, otherwise, all 0 bits - return vceqq_u32(vreinterpretq_u32_u8(cmp_u8), vreinterpretq_u32_u8(m_zeros_u8)); - } - -private: - uint8x16_t m_mins_u8; - uint8x16_t m_maxs_u8; - uint8x16_t m_zeros_u8; -}; - - - - - -size_t filter_rgb32_range_arm64_NEON( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t mins, uint32_t maxs -){ - PixelTest_Rgb32Range_ARM64_NEON tester(mins, maxs); - FilterImage_Rgb32_ARM64_NEON filter( - tester, - replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_range_arm64_NEON( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t mins, uint32_t maxs -){ - PixelTest_Rgb32Range_ARM64_NEON tester(mins, maxs); - ToBlackWhite_Rgb32_ARM64_NEON filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - - - -} -} -#endif +/* Image Filters RGB32 Range + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_arm64_20_M1 + +#include "Kernels/Kernels_arm64_NEON.h" +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_ARM64_NEON.h" +#include "Kernels_ImageFilter_RGB32_Range_Routines.h" +#include "Kernels_ImageFilter_RGB32_Range.h" + + + +namespace PokemonAutomation{ +namespace Kernels{ + + + + +class PixelTest_Rgb32Range_ARM64_NEON{ +public: + static const size_t VECTOR_SIZE = 4; + using Mask = size_t; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Range_ARM64_NEON( + uint32_t mins, uint32_t maxs + ) + : m_mins_u8(vreinterpretq_u8_u32(vdupq_n_u32(mins))) + , m_maxs_u8(vreinterpretq_u8_u32(vdupq_n_u32(maxs))) + , m_zeros_u8(vreinterpretq_u32_u8(vdupq_n_u8(0))) + {} + PA_FORCE_INLINE PixelTest_Rgb32Range_ARM64_NEON( + const ToBlackWhiteRgb32RangeFilter& filter + ) + : m_mins_u8(vreinterpretq_u8_u32(vdupq_n_u32(filter.mins))) + , m_maxs_u8(vreinterpretq_u8_u32(vdupq_n_u32(filter.maxs))) + , m_zeros_u8(vreinterpretq_u32_u8(vdupq_n_u8(0))) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE uint32x4_t test_word(uint32x4_t& pixel) const{ + uint8x16_t in_u8 = vreinterpretq_u8_u32(pixel); + + // Check if mins > pixel per color channel + uint8x16_t cmp0 = vcgtq_u8(m_mins_u8, in_u8); + // Check if pixel > maxs per color channel + uint8x16_t cmp1 = vcgtq_u8(in_u8, m_maxs_u8); + // cmp: if mins > pixel or pixel > maxs per color channel + uint8x16_t cmp_u8 = vorrq_u8(cmp0, cmp1); + // vceqq_u32: compare bitwise equal + // cmp_u32: if each pixel is within the range + // If a pixel is within [mins, maxs], its uint32_t in `cmp_u32` is all 1 bits, otherwise, all 0 bits + return vceqq_u32(vreinterpretq_u32_u8(cmp_u8), vreinterpretq_u32_u8(m_zeros_u8)); + } + +private: + uint8x16_t m_mins_u8; + uint8x16_t m_maxs_u8; + uint8x16_t m_zeros_u8; +}; + + + + + +size_t filter_rgb32_range_arm64_NEON( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t mins, uint32_t maxs +){ + PixelTest_Rgb32Range_ARM64_NEON tester(mins, maxs); + FilterImage_Rgb32_ARM64_NEON filter( + tester, + replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_range_arm64_NEON( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t mins, uint32_t maxs +){ + PixelTest_Rgb32Range_ARM64_NEON tester(mins, maxs); + ToBlackWhite_Rgb32_ARM64_NEON filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_Default.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_Default.cpp index 68ee22dbc9..9a1dfedf36 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_Default.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_Default.cpp @@ -1,109 +1,109 @@ -/* Image Filters RGB32 Range - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_Default.h" -#include "Kernels_ImageFilter_RGB32_Range.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - - -class PixelTest_Rgb32Range_Default{ -public: - static const size_t VECTOR_SIZE = 1; - using Mask = size_t; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Range_Default( - uint32_t mins, uint32_t maxs - ) - : m_shiftB(mins & 0x000000ff) - , m_shiftG(mins & 0x0000ff00) - , m_shiftR(mins & 0x00ff0000) - , m_shiftA(mins & 0xff000000) - , m_thresholdB((maxs & 0x000000ff) - m_shiftB) - , m_thresholdG((maxs & 0x0000ff00) - m_shiftG) - , m_thresholdR((maxs & 0x00ff0000) - m_shiftR) - , m_thresholdA((maxs & 0xff000000) - m_shiftA) - {} - PA_FORCE_INLINE PixelTest_Rgb32Range_Default( - const ToBlackWhiteRgb32RangeFilter& filter - ) - : m_shiftB(filter.mins & 0x000000ff) - , m_shiftG(filter.mins & 0x0000ff00) - , m_shiftR(filter.mins & 0x00ff0000) - , m_shiftA(filter.mins & 0xff000000) - , m_thresholdB((filter.maxs & 0x000000ff) - m_shiftB) - , m_thresholdG((filter.maxs & 0x0000ff00) - m_shiftG) - , m_thresholdR((filter.maxs & 0x00ff0000) - m_shiftR) - , m_thresholdA((filter.maxs & 0xff000000) - m_shiftA) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE bool test_word(uint32_t pixel) const{ - bool ret = true; - ret &= (pixel & 0x000000ff) - m_shiftB <= m_thresholdB; - ret &= (pixel & 0x0000ff00) - m_shiftG <= m_thresholdG; - ret &= (pixel & 0x00ff0000) - m_shiftR <= m_thresholdR; - ret &= (pixel & 0xff000000) - m_shiftA <= m_thresholdA; - return ret; - } - -private: - const uint32_t m_shiftB; - const uint32_t m_shiftG; - const uint32_t m_shiftR; - const uint32_t m_shiftA; - const uint32_t m_thresholdB; - const uint32_t m_thresholdG; - const uint32_t m_thresholdR; - const uint32_t m_thresholdA; -}; - - - - - - -size_t filter_rgb32_range_Default( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t mins, uint32_t maxs -){ - PixelTest_Rgb32Range_Default tester(mins, maxs); - FilterImage_Rgb32_Default filter( - tester, - replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_range_Default( - const uint32_t* image, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t mins, uint32_t maxs -){ - PixelTest_Rgb32Range_Default tester(mins, maxs); - ToBlackWhite_Rgb32_Default filter( - tester, in_range_black - ); - filter_per_pixel(image, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - -} -} +/* Image Filters RGB32 Range + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_Default.h" +#include "Kernels_ImageFilter_RGB32_Range.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + + +class PixelTest_Rgb32Range_Default{ +public: + static const size_t VECTOR_SIZE = 1; + using Mask = size_t; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Range_Default( + uint32_t mins, uint32_t maxs + ) + : m_shiftB(mins & 0x000000ff) + , m_shiftG(mins & 0x0000ff00) + , m_shiftR(mins & 0x00ff0000) + , m_shiftA(mins & 0xff000000) + , m_thresholdB((maxs & 0x000000ff) - m_shiftB) + , m_thresholdG((maxs & 0x0000ff00) - m_shiftG) + , m_thresholdR((maxs & 0x00ff0000) - m_shiftR) + , m_thresholdA((maxs & 0xff000000) - m_shiftA) + {} + PA_FORCE_INLINE PixelTest_Rgb32Range_Default( + const ToBlackWhiteRgb32RangeFilter& filter + ) + : m_shiftB(filter.mins & 0x000000ff) + , m_shiftG(filter.mins & 0x0000ff00) + , m_shiftR(filter.mins & 0x00ff0000) + , m_shiftA(filter.mins & 0xff000000) + , m_thresholdB((filter.maxs & 0x000000ff) - m_shiftB) + , m_thresholdG((filter.maxs & 0x0000ff00) - m_shiftG) + , m_thresholdR((filter.maxs & 0x00ff0000) - m_shiftR) + , m_thresholdA((filter.maxs & 0xff000000) - m_shiftA) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE bool test_word(uint32_t pixel) const{ + bool ret = true; + ret &= (pixel & 0x000000ff) - m_shiftB <= m_thresholdB; + ret &= (pixel & 0x0000ff00) - m_shiftG <= m_thresholdG; + ret &= (pixel & 0x00ff0000) - m_shiftR <= m_thresholdR; + ret &= (pixel & 0xff000000) - m_shiftA <= m_thresholdA; + return ret; + } + +private: + const uint32_t m_shiftB; + const uint32_t m_shiftG; + const uint32_t m_shiftR; + const uint32_t m_shiftA; + const uint32_t m_thresholdB; + const uint32_t m_thresholdG; + const uint32_t m_thresholdR; + const uint32_t m_thresholdA; +}; + + + + + + +size_t filter_rgb32_range_Default( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t mins, uint32_t maxs +){ + PixelTest_Rgb32Range_Default tester(mins, maxs); + FilterImage_Rgb32_Default filter( + tester, + replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_range_Default( + const uint32_t* image, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t mins, uint32_t maxs +){ + PixelTest_Rgb32Range_Default tester(mins, maxs); + ToBlackWhite_Rgb32_Default filter( + tester, in_range_black + ); + filter_per_pixel(image, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_Routines.h b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_Routines.h index b37bec2a46..e215b95764 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_Routines.h +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_Routines.h @@ -1,115 +1,115 @@ -/* Image Filters Basic Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_ImageFilter_RGB32_Range_Routines_H -#define PokemonAutomation_Kernels_ImageFilter_RGB32_Range_Routines_H - -#include "Common/Compiler.h" -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "Kernels_ImageFilter_RGB32_Range.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - -template -PA_FORCE_INLINE void filter_per_pixel( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - FilterRgb32RangeFilter* filters, size_t filter_count -){ - if (width == 0 || height == 0){ - return; - } - -// cout << "filter_per_pixel(" << filter_count << "): " << width << " x " << height << endl; - - FixedLimitVector entries(filter_count); - for (size_t c = 0; c < filter_count; c++){ - FilterRgb32RangeFilter& filter = filters[c]; - entries.emplace_back(filter); - } - - const size_t VECTOR_SIZE = Runner::VECTOR_SIZE; - do{ - // Less than vector width. No need for steady-state loop. - if (width < VECTOR_SIZE){ - typename Runner::Mask mask(width); - do{ - const uint32_t* in = image; - for (size_t c = 0; c < filter_count; c++){ - entries[c].process_partial(filters[c].data, in, mask); - } - image = (const uint32_t*)((const char*)image + bytes_per_row); - for (size_t c = 0; c < filter_count; c++){ - FilterRgb32RangeFilter& filter = filters[c]; - filter.data = (uint32_t*)((const char*)filter.data + filter.bytes_per_row); - } - }while (--height); - break; - } - - // Divisible by vector width. No need for peel loop. - size_t left = width % VECTOR_SIZE; - if (left == 0){ - do{ - const uint32_t* in = image; - size_t shift = 0; - size_t lc = width / VECTOR_SIZE; - do{ - for (size_t c = 0; c < filter_count; c++){ - entries[c].process_full(filters[c].data + shift, in); - } - in += VECTOR_SIZE; - shift += VECTOR_SIZE; - }while (--lc); - image = (const uint32_t*)((const char*)image + bytes_per_row); - for (size_t c = 0; c < filter_count; c++){ - FilterRgb32RangeFilter& filter = filters[c]; - filter.data = (uint32_t*)((const char*)filter.data + filter.bytes_per_row); - } - }while (--height); - break; - } - - // Need both steady-state and peel loops. - { - typename Runner::Mask mask(left); - do{ - const uint32_t* in = image; - size_t shift = 0; - size_t lc = width / VECTOR_SIZE; - do{ - for (size_t c = 0; c < filter_count; c++){ - entries[c].process_full(filters[c].data + shift, in); - } - in += VECTOR_SIZE; - shift += VECTOR_SIZE; - }while (--lc); - for (size_t c = 0; c < filter_count; c++){ - entries[c].process_partial(filters[c].data + shift, in, mask); - } - image = (const uint32_t*)((const char*)image + bytes_per_row); - for (size_t c = 0; c < filter_count; c++){ - FilterRgb32RangeFilter& filter = filters[c]; - filter.data = (uint32_t*)((const char*)filter.data + filter.bytes_per_row); - } - }while (--height); - break; - } - }while (false); - - for (size_t c = 0; c < filter_count; c++){ - filters[c].pixels_in_range = entries[c].count(); - } -} - - - - -} -} -#endif +/* Image Filters Basic Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_ImageFilter_RGB32_Range_Routines_H +#define PokemonAutomation_Kernels_ImageFilter_RGB32_Range_Routines_H + +#include "Common/Compiler.h" +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "Kernels_ImageFilter_RGB32_Range.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + +template +PA_FORCE_INLINE void filter_per_pixel( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + FilterRgb32RangeFilter* filters, size_t filter_count +){ + if (width == 0 || height == 0){ + return; + } + +// cout << "filter_per_pixel(" << filter_count << "): " << width << " x " << height << endl; + + FixedLimitVector entries(filter_count); + for (size_t c = 0; c < filter_count; c++){ + FilterRgb32RangeFilter& filter = filters[c]; + entries.emplace_back(filter); + } + + const size_t VECTOR_SIZE = Runner::VECTOR_SIZE; + do{ + // Less than vector width. No need for steady-state loop. + if (width < VECTOR_SIZE){ + typename Runner::Mask mask(width); + do{ + const uint32_t* in = image; + for (size_t c = 0; c < filter_count; c++){ + entries[c].process_partial(filters[c].data, in, mask); + } + image = (const uint32_t*)((const char*)image + bytes_per_row); + for (size_t c = 0; c < filter_count; c++){ + FilterRgb32RangeFilter& filter = filters[c]; + filter.data = (uint32_t*)((const char*)filter.data + filter.bytes_per_row); + } + }while (--height); + break; + } + + // Divisible by vector width. No need for peel loop. + size_t left = width % VECTOR_SIZE; + if (left == 0){ + do{ + const uint32_t* in = image; + size_t shift = 0; + size_t lc = width / VECTOR_SIZE; + do{ + for (size_t c = 0; c < filter_count; c++){ + entries[c].process_full(filters[c].data + shift, in); + } + in += VECTOR_SIZE; + shift += VECTOR_SIZE; + }while (--lc); + image = (const uint32_t*)((const char*)image + bytes_per_row); + for (size_t c = 0; c < filter_count; c++){ + FilterRgb32RangeFilter& filter = filters[c]; + filter.data = (uint32_t*)((const char*)filter.data + filter.bytes_per_row); + } + }while (--height); + break; + } + + // Need both steady-state and peel loops. + { + typename Runner::Mask mask(left); + do{ + const uint32_t* in = image; + size_t shift = 0; + size_t lc = width / VECTOR_SIZE; + do{ + for (size_t c = 0; c < filter_count; c++){ + entries[c].process_full(filters[c].data + shift, in); + } + in += VECTOR_SIZE; + shift += VECTOR_SIZE; + }while (--lc); + for (size_t c = 0; c < filter_count; c++){ + entries[c].process_partial(filters[c].data + shift, in, mask); + } + image = (const uint32_t*)((const char*)image + bytes_per_row); + for (size_t c = 0; c < filter_count; c++){ + FilterRgb32RangeFilter& filter = filters[c]; + filter.data = (uint32_t*)((const char*)filter.data + filter.bytes_per_row); + } + }while (--height); + break; + } + }while (false); + + for (size_t c = 0; c < filter_count; c++){ + filters[c].pixels_in_range = entries[c].count(); + } +} + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_AVX2.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_AVX2.cpp index 828e3f44d7..4e81e4d6ad 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_AVX2.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_AVX2.cpp @@ -1,99 +1,99 @@ -/* Image Filters RGB32 Range - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_13_Haswell - -#include -#include "Kernels/Kernels_x64_AVX2.h" -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX2.h" -#include "Kernels_ImageFilter_RGB32_Range.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - - - - -class PixelTest_Rgb32Range_x64_AVX2{ -public: - static const size_t VECTOR_SIZE = 8; - using Mask = PartialWordAccess32_x64_AVX2; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Range_x64_AVX2( - uint32_t mins, uint32_t maxs - ) - : m_mins(_mm256_set1_epi32(mins ^ 0x80808080)) - , m_maxs(_mm256_set1_epi32(maxs ^ 0x80808080)) - {} - PA_FORCE_INLINE PixelTest_Rgb32Range_x64_AVX2( - const ToBlackWhiteRgb32RangeFilter& filter - ) - : m_mins(_mm256_set1_epi32(filter.mins ^ 0x80808080)) - , m_maxs(_mm256_set1_epi32(filter.maxs ^ 0x80808080)) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __m256i test_word(__m256i pixel) const{ - __m256i adj = _mm256_xor_si256(pixel, _mm256_set1_epi8((uint8_t)0x80)); - __m256i cmp0 = _mm256_cmpgt_epi8(m_mins, adj); - __m256i cmp1 = _mm256_cmpgt_epi8(adj, m_maxs); - cmp0 = _mm256_or_si256(cmp0, cmp1); - return _mm256_cmpeq_epi32(cmp0, _mm256_setzero_si256()); - } - -private: - const __m256i m_mins; - const __m256i m_maxs; -}; - - - - - - - -size_t filter_rgb32_range_x64_AVX2( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t mins, uint32_t maxs -){ - PixelTest_Rgb32Range_x64_AVX2 tester(mins, maxs); - FilterImage_Rgb32_x64_AVX2 filter( - tester, - replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_range_x64_AVX2( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t mins, uint32_t maxs -){ - PixelTest_Rgb32Range_x64_AVX2 tester(mins, maxs); - ToBlackWhite_Rgb32_x64_AVX2 filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - -} -} -#endif +/* Image Filters RGB32 Range + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_13_Haswell + +#include +#include "Kernels/Kernels_x64_AVX2.h" +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX2.h" +#include "Kernels_ImageFilter_RGB32_Range.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + + + + +class PixelTest_Rgb32Range_x64_AVX2{ +public: + static const size_t VECTOR_SIZE = 8; + using Mask = PartialWordAccess32_x64_AVX2; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Range_x64_AVX2( + uint32_t mins, uint32_t maxs + ) + : m_mins(_mm256_set1_epi32(mins ^ 0x80808080)) + , m_maxs(_mm256_set1_epi32(maxs ^ 0x80808080)) + {} + PA_FORCE_INLINE PixelTest_Rgb32Range_x64_AVX2( + const ToBlackWhiteRgb32RangeFilter& filter + ) + : m_mins(_mm256_set1_epi32(filter.mins ^ 0x80808080)) + , m_maxs(_mm256_set1_epi32(filter.maxs ^ 0x80808080)) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __m256i test_word(__m256i pixel) const{ + __m256i adj = _mm256_xor_si256(pixel, _mm256_set1_epi8((uint8_t)0x80)); + __m256i cmp0 = _mm256_cmpgt_epi8(m_mins, adj); + __m256i cmp1 = _mm256_cmpgt_epi8(adj, m_maxs); + cmp0 = _mm256_or_si256(cmp0, cmp1); + return _mm256_cmpeq_epi32(cmp0, _mm256_setzero_si256()); + } + +private: + const __m256i m_mins; + const __m256i m_maxs; +}; + + + + + + + +size_t filter_rgb32_range_x64_AVX2( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t mins, uint32_t maxs +){ + PixelTest_Rgb32Range_x64_AVX2 tester(mins, maxs); + FilterImage_Rgb32_x64_AVX2 filter( + tester, + replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_range_x64_AVX2( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t mins, uint32_t maxs +){ + PixelTest_Rgb32Range_x64_AVX2 tester(mins, maxs); + ToBlackWhite_Rgb32_x64_AVX2 filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_AVX512.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_AVX512.cpp index ca2eb64e09..e9c6863678 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_AVX512.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_AVX512.cpp @@ -1,106 +1,106 @@ -/* Image Filters RGB32 Range - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_17_Skylake - -#include -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX512.h" -#include "Kernels_ImageFilter_RGB32_Range.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - - - - -class PixelTest_Rgb32Range_x64_AVX512{ -public: - static const size_t VECTOR_SIZE = 16; - using Mask = PartialWordMask; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Range_x64_AVX512( - uint32_t mins, uint32_t maxs - ) - : m_shift(_mm512_set1_epi32(mins)) - , m_threshold(_mm512_sub_epi8(_mm512_set1_epi32(maxs), m_shift)) - {} - PA_FORCE_INLINE PixelTest_Rgb32Range_x64_AVX512( - const ToBlackWhiteRgb32RangeFilter& filter - ) - : m_shift(_mm512_set1_epi32(filter.mins)) - , m_threshold(_mm512_sub_epi8(_mm512_set1_epi32(filter.maxs), m_shift)) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __mmask16 test_word(__m512i pixel) const{ - pixel = _mm512_sub_epi8(pixel, m_shift); - __mmask64 cmp64 = _mm512_cmple_epu8_mask(pixel, m_threshold); - __m512i mask = _mm512_movm_epi8(cmp64); - return _mm512_cmpeq_epi32_mask(mask, _mm512_set1_epi32(-1)); - } - -private: - const __m512i m_shift; - const __m512i m_threshold; -}; - - - - - -size_t filter_rgb32_range_x64_AVX512( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t mins, uint32_t maxs -){ - PixelTest_Rgb32Range_x64_AVX512 tester(mins, maxs); - FilterImage_Rgb32_x64_AVX512 filter( - tester, - replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_range_x64_AVX512( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t mins, uint32_t maxs -){ - PixelTest_Rgb32Range_x64_AVX512 tester(mins, maxs); - ToBlackWhite_Rgb32_x64_AVX512 filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - - - - - - - - - - - - - -} -} -#endif +/* Image Filters RGB32 Range + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_17_Skylake + +#include +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX512.h" +#include "Kernels_ImageFilter_RGB32_Range.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + + + + +class PixelTest_Rgb32Range_x64_AVX512{ +public: + static const size_t VECTOR_SIZE = 16; + using Mask = PartialWordMask; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Range_x64_AVX512( + uint32_t mins, uint32_t maxs + ) + : m_shift(_mm512_set1_epi32(mins)) + , m_threshold(_mm512_sub_epi8(_mm512_set1_epi32(maxs), m_shift)) + {} + PA_FORCE_INLINE PixelTest_Rgb32Range_x64_AVX512( + const ToBlackWhiteRgb32RangeFilter& filter + ) + : m_shift(_mm512_set1_epi32(filter.mins)) + , m_threshold(_mm512_sub_epi8(_mm512_set1_epi32(filter.maxs), m_shift)) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __mmask16 test_word(__m512i pixel) const{ + pixel = _mm512_sub_epi8(pixel, m_shift); + __mmask64 cmp64 = _mm512_cmple_epu8_mask(pixel, m_threshold); + __m512i mask = _mm512_movm_epi8(cmp64); + return _mm512_cmpeq_epi32_mask(mask, _mm512_set1_epi32(-1)); + } + +private: + const __m512i m_shift; + const __m512i m_threshold; +}; + + + + + +size_t filter_rgb32_range_x64_AVX512( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t mins, uint32_t maxs +){ + PixelTest_Rgb32Range_x64_AVX512 tester(mins, maxs); + FilterImage_Rgb32_x64_AVX512 filter( + tester, + replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_range_x64_AVX512( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t mins, uint32_t maxs +){ + PixelTest_Rgb32Range_x64_AVX512 tester(mins, maxs); + ToBlackWhite_Rgb32_x64_AVX512 filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + + + + + + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_SSE42.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_SSE42.cpp index 068842c523..a74546c4ae 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_SSE42.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_SSE42.cpp @@ -1,100 +1,100 @@ -/* Image Filters RGB32 Range - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_08_Nehalem - -#include -#include "Kernels/Kernels_x64_SSE41.h" -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_SSE42.h" -#include "Kernels_ImageFilter_RGB32_Range.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - - - - -class PixelTest_Rgb32Range_x64_SSE42{ -public: - static const size_t VECTOR_SIZE = 4; - using Mask = PartialWordMask; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Range_x64_SSE42( - uint32_t mins, uint32_t maxs - ) - : m_mins(_mm_set1_epi32(mins ^ 0x80808080)) - , m_maxs(_mm_set1_epi32(maxs ^ 0x80808080)) - {} - PA_FORCE_INLINE PixelTest_Rgb32Range_x64_SSE42( - const ToBlackWhiteRgb32RangeFilter& filter - ) - : m_mins(_mm_set1_epi32(filter.mins ^ 0x80808080)) - , m_maxs(_mm_set1_epi32(filter.maxs ^ 0x80808080)) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __m128i test_word(__m128i pixel) const{ - __m128i adj = _mm_xor_si128(pixel, _mm_set1_epi8((uint8_t)0x80)); - __m128i cmp0 = _mm_cmpgt_epi8(m_mins, adj); - __m128i cmp1 = _mm_cmpgt_epi8(adj, m_maxs); - cmp0 = _mm_or_si128(cmp0, cmp1); - return _mm_cmpeq_epi32(cmp0, _mm_setzero_si128()); - } - -private: - const __m128i m_mins; - const __m128i m_maxs; -}; - - - - - - - -size_t filter_rgb32_range_x64_SSE42( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t mins, uint32_t maxs -){ - PixelTest_Rgb32Range_x64_SSE42 tester(mins, maxs); - FilterImage_Rgb32_x64_SSE42 filter( - tester, - replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_range_x64_SSE42( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t mins, uint32_t maxs -){ - PixelTest_Rgb32Range_x64_SSE42 tester(mins, maxs); - ToBlackWhite_Rgb32_x64_SSE42 filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - - -} -} -#endif +/* Image Filters RGB32 Range + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_08_Nehalem + +#include +#include "Kernels/Kernels_x64_SSE41.h" +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_SSE42.h" +#include "Kernels_ImageFilter_RGB32_Range.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + + + + +class PixelTest_Rgb32Range_x64_SSE42{ +public: + static const size_t VECTOR_SIZE = 4; + using Mask = PartialWordMask; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Range_x64_SSE42( + uint32_t mins, uint32_t maxs + ) + : m_mins(_mm_set1_epi32(mins ^ 0x80808080)) + , m_maxs(_mm_set1_epi32(maxs ^ 0x80808080)) + {} + PA_FORCE_INLINE PixelTest_Rgb32Range_x64_SSE42( + const ToBlackWhiteRgb32RangeFilter& filter + ) + : m_mins(_mm_set1_epi32(filter.mins ^ 0x80808080)) + , m_maxs(_mm_set1_epi32(filter.maxs ^ 0x80808080)) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __m128i test_word(__m128i pixel) const{ + __m128i adj = _mm_xor_si128(pixel, _mm_set1_epi8((uint8_t)0x80)); + __m128i cmp0 = _mm_cmpgt_epi8(m_mins, adj); + __m128i cmp1 = _mm_cmpgt_epi8(adj, m_maxs); + cmp0 = _mm_or_si128(cmp0, cmp1); + return _mm_cmpeq_epi32(cmp0, _mm_setzero_si128()); + } + +private: + const __m128i m_mins; + const __m128i m_maxs; +}; + + + + + + + +size_t filter_rgb32_range_x64_SSE42( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t mins, uint32_t maxs +){ + PixelTest_Rgb32Range_x64_SSE42 tester(mins, maxs); + FilterImage_Rgb32_x64_SSE42 filter( + tester, + replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_range_x64_SSE42( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t mins, uint32_t maxs +){ + PixelTest_Rgb32Range_x64_SSE42 tester(mins, maxs); + ToBlackWhite_Rgb32_x64_SSE42 filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/ML/DataLabeling/ML_AnnotationIO.cpp b/SerialPrograms/Source/ML/DataLabeling/ML_AnnotationIO.cpp new file mode 100644 index 0000000000..cb139b88e3 --- /dev/null +++ b/SerialPrograms/Source/ML/DataLabeling/ML_AnnotationIO.cpp @@ -0,0 +1,82 @@ +/* ML Annotation IO + * + * From: https://github.com/PokemonAutomation/ + * + * Functions for IO of annotation related files + */ + +#include +#include +#include +#include + +#include "ML_AnnotationIO.h" +#include "ML_SegmentAnythingModelConstants.h" + +namespace PokemonAutomation{ +namespace ML{ + +// save the image embedding as a file with path .embedding +void save_image_embedding_to_disk(const std::string& image_filepath, const std::vector& embedding){ + const std::string embedding_path = image_filepath + ".embedding"; + std::ofstream fout(embedding_path, std::ios::binary); + // write embedding shape + fout.write(reinterpret_cast(&SAM_EMBEDDER_OUTPUT_N_CHANNELS), sizeof(SAM_EMBEDDER_OUTPUT_N_CHANNELS)); + fout.write(reinterpret_cast(&SAM_EMBEDDER_OUTPUT_IMAGE_SIZE), sizeof(SAM_EMBEDDER_OUTPUT_IMAGE_SIZE)); + fout.write(reinterpret_cast(&SAM_EMBEDDER_OUTPUT_IMAGE_SIZE), sizeof(SAM_EMBEDDER_OUTPUT_IMAGE_SIZE)); + fout.write(reinterpret_cast(embedding.data()), sizeof(float) * embedding.size()); + fout.close(); + std::cout << "Saved image embedding as " << embedding_path << std::endl; +} + + +bool load_image_embedding(const std::string& image_filepath, std::vector& image_embedding){ + std::string emebdding_path = image_filepath + ".embedding"; + std::ifstream fin(emebdding_path, std::ios::binary); + if (!fin.is_open()){ + std::cout << "No embedding for image " << image_filepath << std::endl; + return false; + } + + int embedding_n_channels = 0, embedding_height = 0, emebedding_width = 0; + fin.read(reinterpret_cast(&embedding_n_channels), sizeof(int)); + fin.read(reinterpret_cast(&embedding_height), sizeof(int)); + fin.read(reinterpret_cast(&emebedding_width), sizeof(int)); + + std::cout << "Image embedding shape [" << embedding_n_channels << ", " << embedding_height + << ", " << emebedding_width << "]" << std::endl; + if (embedding_n_channels <= 0 || embedding_height <= 0 || emebedding_width <= 0){ + std::string err_msg = "Image embedding wrong dimension from " + emebdding_path; + std::cerr << err_msg << std::endl; + throw std::runtime_error(err_msg); + } + + const int size = embedding_n_channels * embedding_height * emebedding_width; + image_embedding.resize(size); + fin.read(reinterpret_cast(image_embedding.data()), sizeof(float) * size); + std::cout << "Loaded image embedding from " << emebdding_path << std::endl; + return true; +} + + +std::vector find_images_in_folder(const std::string& folder_path, bool recursive){ + QDir image_dir(folder_path.c_str()); + if (!image_dir.exists()){ + std::cerr << "Error: input image folder path " << folder_path << " does not exist." << std::endl; + return {}; + } + + auto flag = recursive ? QDirIterator::Subdirectories : QDirIterator::NoIteratorFlags; + QDirIterator image_file_iter(image_dir.absolutePath(), {"*.png", "*.jpg", "*.jpeg"}, QDir::Files, flag); + std::vector all_image_paths; + while (image_file_iter.hasNext()){ + all_image_paths.emplace_back(image_file_iter.next().toStdString()); + } + std::cout << "Found " << all_image_paths.size() << " images " << (recursive ? "recursively " : "") << + "in folder " << folder_path << std::endl; + return all_image_paths; +} + + +} +} \ No newline at end of file diff --git a/SerialPrograms/Source/ML/DataLabeling/ML_AnnotationIO.h b/SerialPrograms/Source/ML/DataLabeling/ML_AnnotationIO.h new file mode 100644 index 0000000000..2ffcd74e3d --- /dev/null +++ b/SerialPrograms/Source/ML/DataLabeling/ML_AnnotationIO.h @@ -0,0 +1,31 @@ +/* ML Annotation IO + * + * From: https://github.com/PokemonAutomation/ + * + * Functions for IO of annotation related files + */ + +#ifndef PokemonAutomation_ML_AnnotationIO_H +#define PokemonAutomation_ML_AnnotationIO_H + +#include +#include + +namespace PokemonAutomation{ +namespace ML{ + +// Load pre-computed image embedding from disk +// Return true if there is the embedding file. +// The embedding is stored in a file in the same folder as the image, having the same name but with a suffix ".embedding". +bool load_image_embedding(const std::string& image_filepath, std::vector& image_embedding); + +// Save the image embedding as a file with path .embedding. +void save_image_embedding_to_disk(const std::string& image_filepath, const std::vector& embedding); + +// Find image paths stored in a folder. The search can be recursive into child folders or not. +std::vector find_images_in_folder(const std::string& folder_path, bool recursive); + +} +} + +#endif \ No newline at end of file diff --git a/SerialPrograms/Source/ML/DataLabeling/SegmentAnythingModel.cpp b/SerialPrograms/Source/ML/DataLabeling/ML_SegmentAnythingModel.cpp similarity index 73% rename from SerialPrograms/Source/ML/DataLabeling/SegmentAnythingModel.cpp rename to SerialPrograms/Source/ML/DataLabeling/ML_SegmentAnythingModel.cpp index 3ea6bed00d..dfc29a7a9f 100644 --- a/SerialPrograms/Source/ML/DataLabeling/SegmentAnythingModel.cpp +++ b/SerialPrograms/Source/ML/DataLabeling/ML_SegmentAnythingModel.cpp @@ -5,33 +5,22 @@ * Run Segment Anything Model (SAM) to segment objects on images */ +#include +#include #include #include +#include #include #include +#include #include "3rdParty/ONNX/OnnxToolsPA.h" -#include "SegmentAnythingModel.h" +#include "ML_SegmentAnythingModelConstants.h" +#include "ML_SegmentAnythingModel.h" +#include "ML_AnnotationIO.h" namespace PokemonAutomation{ namespace ML{ - - - -const int SAM_EMBEDDER_INPUT_IMAGE_WIDTH = 1024; -const int SAM_EMBEDDER_INPUT_IMAGE_HEIGHT = 576; -const int SAM_EMBEDDER_OUTPUT_N_CHANNELS = 256; -const int SAM_EMBEDDER_OUTPUT_IMAGE_SIZE = 64; - -const int SAM_EMBEDDER_INPUT_SIZE = SAM_EMBEDDER_INPUT_IMAGE_HEIGHT * SAM_EMBEDDER_INPUT_IMAGE_WIDTH * 3; -const int SAM_EMBEDDER_OUTPUT_SIZE = SAM_EMBEDDER_OUTPUT_N_CHANNELS * SAM_EMBEDDER_OUTPUT_IMAGE_SIZE * SAM_EMBEDDER_OUTPUT_IMAGE_SIZE; - -const int SAM_N_INPUT_TENSORS = 6; -const int SAM_N_OUTPUT_TENSORS = 3; -const int SAM_LOW_RES_MASK_SIZE = 256; -const float SAM_OUTPUT_MASK_THRESHOLD = 0.0; - - Ort::SessionOptions create_session_option(){ return Ort::SessionOptions{}; @@ -203,48 +192,55 @@ void SAMSession::run( } -// save the image embedding as a file with path .embedding -void save_image_embedding_to_disk(const std::string& image_filepath, const std::vector& embedding){ - std::string embedding_path = image_filepath + ".embedding"; - std::ofstream fout(embedding_path, std::ios::binary); - // write embedding shape - fout.write(reinterpret_cast(&SAM_EMBEDDER_OUTPUT_N_CHANNELS), sizeof(SAM_EMBEDDER_OUTPUT_N_CHANNELS)); - fout.write(reinterpret_cast(&SAM_EMBEDDER_OUTPUT_IMAGE_SIZE), sizeof(SAM_EMBEDDER_OUTPUT_IMAGE_SIZE)); - fout.write(reinterpret_cast(&SAM_EMBEDDER_OUTPUT_IMAGE_SIZE), sizeof(SAM_EMBEDDER_OUTPUT_IMAGE_SIZE)); - fout.write(reinterpret_cast(embedding.data()), sizeof(float) * embedding.size()); - fout.close(); - std::cout << "Saved image embedding as " << embedding_path << std::endl; -} +void compute_embeddings_for_folder(const std::string& embedding_model_path, const std::string& image_folder_path){ + const bool recursive_search = true; + std::vector all_image_paths = find_images_in_folder(image_folder_path, recursive_search); + if (all_image_paths.size() == 0){ + return; + } + + SAMEmbedderSession embedding_session(embedding_model_path); + std::vector output_image_embedding; + for (size_t i = 0; i < all_image_paths.size(); i++){ + const auto& image_path = all_image_paths[i]; + std::cout << (i+1) << "/" << all_image_paths.size() << ": "; + const std::string embedding_path = image_path + ".embedding"; + if (std::filesystem::exists(embedding_path)){ + std::cout << "skip already computed embedding " << embedding_path << "." << std::endl; + continue; + } + std::cout << "computing embedding for " << image_path << "..." << std::endl; + cv::Mat image_bgr = cv::imread(image_path); + if (image_bgr.empty()){ + std::cerr << "Error: image empty. Probably the file is not an image?" << std::endl; + QMessageBox box; + box.warning(nullptr, "Unable To Open Image", + QString::fromStdString("Cannot open image file " + image_path + ". Probably not an actual image?")); + return; + } + cv::Mat image; + if (image_bgr.channels() == 4){ + cv::cvtColor(image_bgr, image, cv::COLOR_BGRA2RGB); + } else if (image_bgr.channels() == 3){ + cv::cvtColor(image_bgr, image, cv::COLOR_BGR2RGB); + } else{ + std::cerr << "Error: wrong image channels. Only work with RGB or RGBA images." << std::endl; + QMessageBox box; + box.warning(nullptr, "Wrong Image Channels", + QString::fromStdString("Image has " + std::to_string(image_bgr.channels()) + " channels. Only support 3 or 4 channels.")); + return; + } + cv::Mat resized_mat; // resize to the shape for the ML model input + cv::resize(image, resized_mat, cv::Size(SAM_EMBEDDER_INPUT_IMAGE_WIDTH, SAM_EMBEDDER_INPUT_IMAGE_HEIGHT)); -bool load_image_embedding(const std::string& image_filepath, std::vector& image_embedding){ - std::string emebdding_path = image_filepath + ".embedding"; - std::ifstream fin(emebdding_path, std::ios::binary); - if (!fin.is_open()){ - std::cout << "No embedding for image " << image_filepath << std::endl; - return false; + output_image_embedding.clear(); + embedding_session.run(resized_mat, output_image_embedding); + save_image_embedding_to_disk(image_path, output_image_embedding); } - int embedding_n_channels = 0, embedding_height = 0, emebedding_width = 0; - fin.read(reinterpret_cast(&embedding_n_channels), sizeof(int)); - fin.read(reinterpret_cast(&embedding_height), sizeof(int)); - fin.read(reinterpret_cast(&emebedding_width), sizeof(int)); - - std::cout << "Image embedding shape [" << embedding_n_channels << ", " << embedding_height - << ", " << emebedding_width << "]" << std::endl; - if (embedding_n_channels <= 0 || embedding_height <= 0 || emebedding_width <= 0){ - std::string err_msg = "Image embedding wrong dimension from " + emebdding_path; - std::cerr << err_msg << std::endl; - throw std::runtime_error(err_msg); - } - const int size = embedding_n_channels * embedding_height * emebedding_width; - image_embedding.resize(size); - fin.read(reinterpret_cast(image_embedding.data()), sizeof(float) * size); - std::cout << "Loaded image embedding from " << emebdding_path << std::endl; - return true; } - } } diff --git a/SerialPrograms/Source/ML/DataLabeling/SegmentAnythingModel.h b/SerialPrograms/Source/ML/DataLabeling/ML_SegmentAnythingModel.h similarity index 85% rename from SerialPrograms/Source/ML/DataLabeling/SegmentAnythingModel.h rename to SerialPrograms/Source/ML/DataLabeling/ML_SegmentAnythingModel.h index 0f71c07632..be227cb5db 100644 --- a/SerialPrograms/Source/ML/DataLabeling/SegmentAnythingModel.h +++ b/SerialPrograms/Source/ML/DataLabeling/ML_SegmentAnythingModel.h @@ -5,8 +5,8 @@ * Run Segment Anything Model (SAM) to segment objects on images */ -#ifndef PokemonAutomation_ML_SEGMENTANYTHINGMODEL_H -#define PokemonAutomation_ML_SEGMENTANYTHINGMODEL_H +#ifndef PokemonAutomation_ML_SegmentAnythingModel_H +#define PokemonAutomation_ML_SegmentAnythingModel_H #include @@ -21,12 +21,9 @@ namespace PokemonAutomation{ namespace ML{ -// load pre-computed image embedding from disk -// return true if there is the embedding file -bool load_image_embedding(const std::string& image_filepath, std::vector& image_embedding); - -// save the image embedding as a file with path .embedding -void save_image_embedding_to_disk(const std::string& image_filepath, const std::vector& embedding); +// Compute embeddings for all images in a folder. Only support .png, .jpg and .jpeg filename extensions so far. +// This can be very slow! +void compute_embeddings_for_folder(const std::string& embedding_model_path, const std::string& image_folder_path); class SAMEmbedderSession{ diff --git a/SerialPrograms/Source/ML/DataLabeling/ML_SegmentAnythingModelConstants.h b/SerialPrograms/Source/ML/DataLabeling/ML_SegmentAnythingModelConstants.h new file mode 100644 index 0000000000..d39cef3031 --- /dev/null +++ b/SerialPrograms/Source/ML/DataLabeling/ML_SegmentAnythingModelConstants.h @@ -0,0 +1,27 @@ +/* ML Segment Anything Model Constants + * + * From: https://github.com/PokemonAutomation/ + * + * Constants for Segment Anything Model (SAM) to segment objects on images + */ + +#ifndef PokemonAutomation_ML_SegmentAnythingModelConstants_H +#define PokemonAutomation_ML_SegmentAnythingModelConstants_H + + +const int SAM_EMBEDDER_INPUT_IMAGE_WIDTH = 1024; +const int SAM_EMBEDDER_INPUT_IMAGE_HEIGHT = 576; +const int SAM_EMBEDDER_OUTPUT_N_CHANNELS = 256; +const int SAM_EMBEDDER_OUTPUT_IMAGE_SIZE = 64; + +const int SAM_EMBEDDER_INPUT_SIZE = SAM_EMBEDDER_INPUT_IMAGE_HEIGHT * SAM_EMBEDDER_INPUT_IMAGE_WIDTH * 3; +const int SAM_EMBEDDER_OUTPUT_SIZE = SAM_EMBEDDER_OUTPUT_N_CHANNELS * SAM_EMBEDDER_OUTPUT_IMAGE_SIZE * SAM_EMBEDDER_OUTPUT_IMAGE_SIZE; + +const int SAM_N_INPUT_TENSORS = 6; +const int SAM_N_OUTPUT_TENSORS = 3; +const int SAM_LOW_RES_MASK_SIZE = 256; +const float SAM_OUTPUT_MASK_THRESHOLD = 0.0; + + + +#endif diff --git a/SerialPrograms/Source/ML/Programs/ML_LabelImages.cpp b/SerialPrograms/Source/ML/Programs/ML_LabelImages.cpp index 908b4cf0e3..1ae25b34b6 100644 --- a/SerialPrograms/Source/ML/Programs/ML_LabelImages.cpp +++ b/SerialPrograms/Source/ML/Programs/ML_LabelImages.cpp @@ -4,8 +4,10 @@ * */ +#include #include #include +#include #include #include #include @@ -19,6 +21,7 @@ #include #include #include "CommonFramework/Globals.h" +#include "Common/Cpp/BitmapConversion.h" #include "Common/Cpp/Json/JsonArray.h" #include "Common/Cpp/Json/JsonObject.h" #include "Common/Cpp/Json/JsonValue.h" @@ -26,13 +29,14 @@ #include "Common/Qt/CollapsibleGroupBox.h" #include "Pokemon/Resources/Pokemon_PokemonForms.h" #include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget.h" +#include "ML/UI/ML_ImageAnnotationDisplayWidget.h" #include "CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.5.h" #include "CommonFramework/VideoPipeline/VideoSources/VideoSource_StillImage.h" #include "ML_LabelImages.h" #include "Pokemon/Pokemon_Strings.h" #include "Common/Qt/Options/ConfigWidget.h" -#include "ML/DataLabeling/SegmentAnythingModel.h" +#include "ML/DataLabeling/ML_SegmentAnythingModel.h" +#include "ML/DataLabeling/ML_AnnotationIO.h" @@ -64,11 +68,15 @@ ObjectAnnotation json_to_object_annotation(const JsonValue& value){ size_t(mask_box_array[2].to_integer_throw()), size_t(mask_box_array[3].to_integer_throw()) ); - size_t mask_width = anno_obj.mask_box.width(), mask_height = anno_obj.mask_box.height(); - anno_obj.mask.resize(mask_width * mask_height); - const JsonArray& mask_values = json_obj.get_array_throw("Mask"); - for(size_t i = 0; i < anno_obj.mask.size(); i++){ - anno_obj.mask[i] = bool(mask_values[i].to_integer_throw()); + const size_t mask_width = anno_obj.mask_box.width(), mask_height = anno_obj.mask_box.height(); + const size_t num_mask_ele = mask_width * mask_height; + + const std::string mask_base64 = json_obj.get_string_throw("Mask"); + anno_obj.mask = unpack_bit_vector_from_base64(mask_base64, num_mask_ele); + if (anno_obj.mask.size() != num_mask_ele){ + std::string err_msg = "wrong decoded object annotation mask size: decoded " + std::to_string(anno_obj.mask.size()) + + " but should be " + std::to_string(num_mask_ele); + throw ParseException(err_msg); } anno_obj.label = json_obj.get_string_throw("Label"); @@ -92,11 +100,7 @@ JsonObject object_annotation_to_json(const ObjectAnnotation& object_annotation){ mask_box_arr.push_back(int64_t(object_annotation.mask_box.max_y)); json_obj["MaskBox"] = std::move(mask_box_arr); - JsonArray mask_arr; - for(size_t i = 0; i < object_annotation.mask.size(); i++){ - mask_arr.push_back(int64_t(object_annotation.mask[i])); - } - json_obj["Mask"] = std::move(mask_arr); + json_obj["Mask"] = pack_bit_vector_to_base64(object_annotation.mask); json_obj["Label"] = object_annotation.label; @@ -194,7 +198,7 @@ LabelImages_Descriptor::LabelImages_Descriptor() LabelImages::LabelImages(const LabelImages_Descriptor& descriptor) : PanelInstance(descriptor) - , m_switch_control_option({}, false) + , m_display_session(m_display_option) , m_options(LockMode::UNLOCK_WHILE_RUNNING) , X("X Coordinate:", LockMode::UNLOCK_WHILE_RUNNING, 0.3, 0.0, 1.0) , Y("Y Coordinate:", LockMode::UNLOCK_WHILE_RUNNING, 0.3, 0.0, 1.0) @@ -214,27 +218,43 @@ void LabelImages::from_json(const JsonValue& json){ if (obj == nullptr){ return; } - const JsonValue* value = obj->get_value("SwitchSetup"); + const JsonValue* value = obj->get_value("ImageSetup"); if (value){ - m_switch_control_option.load_json(*value); + m_display_option.load_json(*value); } m_options.load_json(json); } JsonValue LabelImages::to_json() const{ JsonObject obj = std::move(*m_options.to_json().to_object()); - obj["SwitchSetup"] = m_switch_control_option.to_json(); + obj["ImageSetup"] = m_display_option.to_json(); + + save_annotation_to_file(); + return obj; +} +void LabelImages::save_annotation_to_file() const{ // m_annotation_file_path if (m_annotation_file_path.size() > 0 && !m_fail_to_load_annotation_file){ JsonArray anno_json_arr; - for(const auto& anno_obj: m_annotated_objects){ + for(const auto& anno_obj: m_annotations){ anno_json_arr.push_back(object_annotation_to_json(anno_obj)); } cout << "Saving annotation to " << m_annotation_file_path << endl; anno_json_arr.dump(m_annotation_file_path); } - return obj; } + +void LabelImages::clear_for_new_image(){ + source_image_width = source_image_height = 0; + m_image_embedding.clear(); + m_output_boolean_mask.clear(); + m_mask_image = ImageRGB32(); + m_annotations.clear(); + m_last_object_idx = 0; + m_annotation_file_path = ""; + m_fail_to_load_annotation_file = false; +} + QWidget* LabelImages::make_widget(QWidget& parent, PanelHolder& holder){ return new LabelImages_Widget(parent, *this, holder); } @@ -250,6 +270,7 @@ void LabelImages::load_image_related_data(const std::string& image_path, size_t if (!embedding_loaded){ return; // no embedding, then no way for us to annotate } + // see if we can load the previously created labels const std::string anno_filename = std::filesystem::path(image_path).filename().replace_extension(".json").string(); @@ -270,7 +291,7 @@ void LabelImages::load_image_related_data(const std::string& image_path, size_t return; } - JsonValue loaded_json = parse_json(json_content); + const JsonValue loaded_json = parse_json(json_content); const JsonArray* json_array = loaded_json.to_array(); if (json_array == nullptr){ m_fail_to_load_annotation_file = true; @@ -283,7 +304,7 @@ void LabelImages::load_image_related_data(const std::string& image_path, size_t for(size_t i = 0; i < json_array->size(); i++){ try{ ObjectAnnotation anno_obj = json_to_object_annotation((*json_array)[i]); - m_annotated_objects.emplace_back(std::move(anno_obj)); + m_annotations.emplace_back(std::move(anno_obj)); } catch(JsonParseException&){ m_fail_to_load_annotation_file = true; QMessageBox box; @@ -295,7 +316,7 @@ void LabelImages::load_image_related_data(const std::string& image_path, size_t ); } } - m_last_object_idx = m_annotated_objects.size(); + m_last_object_idx = m_annotations.size(); cout << "Loaded existing annotation file " << m_annotation_file_path << endl; } @@ -303,8 +324,8 @@ void LabelImages::update_rendered_objects(VideoOverlaySet& overlay_set){ overlay_set.clear(); overlay_set.add(COLOR_RED, {X, Y, WIDTH, HEIGHT}); - for(size_t i_obj = 0; i_obj < m_annotated_objects.size(); i_obj++){ - const auto& obj = m_annotated_objects[i_obj]; + for(size_t i_obj = 0; i_obj < m_annotations.size(); i_obj++){ + const auto& obj = m_annotations[i_obj]; // overlayset.add(COLOR_RED, pixelbox_to_floatbox(source_image_width, source_image_height, obj.user_box)); const auto mask_float_box = pixelbox_to_floatbox(source_image_width, source_image_height, obj.mask_box); std::string label = obj.label; @@ -399,29 +420,40 @@ void LabelImages::compute_mask(VideoOverlaySet& overlay_set){ } annotation.label = label; - m_last_object_idx = m_annotated_objects.size(); - m_annotated_objects.emplace_back(std::move(annotation)); + m_last_object_idx = m_annotations.size(); + m_annotations.emplace_back(std::move(annotation)); update_rendered_objects(overlay_set); } } +void LabelImages::compute_embeddings_for_folder(const std::string& image_folder_path){ + std::string embedding_model_path = RESOURCE_PATH() + "ML/sam_embedder_cpu.onnx"; + std::cout << "Use SAM Embedding model " << embedding_model_path << std::endl; + ML::compute_embeddings_for_folder(embedding_model_path, image_folder_path); +} + + + LabelImages_Widget::~LabelImages_Widget(){ m_program.FORM_LABEL.remove_listener(*this); - delete m_switch_widget; + delete m_image_display_widget; } LabelImages_Widget::LabelImages_Widget( QWidget& parent, - LabelImages& instance, + LabelImages& program, PanelHolder& holder ) - : PanelWidget(parent, instance, holder) - , m_program(instance) - , m_session(instance.m_switch_control_option, 0, 0) - , m_overlay_set(m_session.overlay()) - , m_drawn_box(*this, m_session.overlay()) + : PanelWidget(parent, program, holder) + , m_program(program) + , m_display_session(m_program.m_display_session) + , m_overlay_set(m_display_session.overlay()) + , m_drawn_box(*this, m_display_session.overlay()) { m_program.FORM_LABEL.add_listener(*this); + m_display_session.video_session().add_state_listener(*this); + + m_embedding_info_label = new QLabel(this); QVBoxLayout* layout = new QVBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); @@ -436,46 +468,92 @@ LabelImages_Widget::LabelImages_Widget( QVBoxLayout* scroll_layout = new QVBoxLayout(scroll_inner); scroll_layout->setAlignment(Qt::AlignTop); - m_switch_widget = new NintendoSwitch::SwitchSystemWidget(*this, m_session, 0); - scroll_layout->addWidget(m_switch_widget); + m_image_display_widget = new ImageAnnotationDisplayWidget(*this, m_display_session, 0); + scroll_layout->addWidget(m_image_display_widget); + + QHBoxLayout* embedding_info_row = new QHBoxLayout(); + scroll_layout->addLayout(embedding_info_row); + embedding_info_row->addWidget(new QLabel("Image Embedding File: ", this)); + embedding_info_row->addWidget(m_embedding_info_label); QPushButton* button = new QPushButton("Delete Last Mask", scroll_inner); scroll_layout->addWidget(button); connect(button, &QPushButton::clicked, this, [this](bool){ auto& program = this->m_program; - if (program.m_annotated_objects.size() > 0){ - program.m_annotated_objects.pop_back(); + if (program.m_annotations.size() > 0){ + program.m_annotations.pop_back(); } - if (program.m_annotated_objects.size() > 0){ - program.m_last_object_idx = program.m_annotated_objects.size() - 1; + if (program.m_annotations.size() > 0){ + program.m_last_object_idx = program.m_annotations.size() - 1; } program.update_rendered_objects(this->m_overlay_set); }); - m_option_widget = instance.m_options.make_QtWidget(*scroll_inner); + // Add all option UI elements defined by LabelImage program. + m_option_widget = program.m_options.make_QtWidget(*scroll_inner); scroll_layout->addWidget(&m_option_widget->widget()); - const VideoSourceDescriptor* video_source_desc = instance.m_switch_control_option.m_video.descriptor().get(); - auto image_source_desc = dynamic_cast(video_source_desc); - if (image_source_desc != nullptr){ - const std::string image_path = image_source_desc->path(); - const size_t source_image_height = image_source_desc->source_image_height(); - const size_t source_image_width = image_source_desc->source_image_width(); - m_program.load_image_related_data(image_path, source_image_width, source_image_height); - m_program.update_rendered_objects(m_overlay_set); - } + button = new QPushButton("Compute Image Embeddings (SLOW!)", scroll_inner); + scroll_layout->addWidget(button); + connect(button, &QPushButton::clicked, this, [this](bool){ + std::string folder_path = QFileDialog::getExistingDirectory( + nullptr, "Open image folder", ".").toStdString(); + + if (folder_path.size() > 0){ + this->m_program.compute_embeddings_for_folder(folder_path); + } + }); cout << "LabelImages_Widget built" << endl; } +void LabelImages_Widget::clear_for_new_image(){ + m_overlay_set.clear(); + m_program.clear_for_new_image(); +} + void LabelImages_Widget::on_config_value_changed(void* object){ - if (m_program.m_annotated_objects.size() > 0 && m_program.m_last_object_idx < m_program.m_annotated_objects.size()){ - std::string& cur_label = m_program.m_annotated_objects[m_program.m_last_object_idx].label; + if (m_program.m_annotations.size() > 0 && m_program.m_last_object_idx < m_program.m_annotations.size()){ + std::string& cur_label = m_program.m_annotations[m_program.m_last_object_idx].label; cur_label = m_program.FORM_LABEL.slug(); m_program.update_rendered_objects(m_overlay_set); } } +// This callback function will be called whenever the display source (the image source) is loaded or reloaded: +void LabelImages_Widget::post_startup(VideoSource* source){ + const std::string& image_path = m_display_session.option().m_image_path; + + m_program.save_annotation_to_file(); // save the current annotation file + clear_for_new_image(); + if (image_path.size() == 0){ + m_embedding_info_label->setText(""); + return; + } + + const std::string embedding_path = image_path + ".embedding"; + const std::string embedding_path_display = "/" + std::filesystem::path(embedding_path).filename().string(); + if (!std::filesystem::exists(embedding_path)){ + m_embedding_info_label->setText(QString::fromStdString(embedding_path_display + " Dose Not Exist. Cannot Annotate The Image!")); + m_embedding_info_label->setStyleSheet("color: red"); + return; + } + + m_embedding_info_label->setText(QString::fromStdString(embedding_path_display)); + m_embedding_info_label->setStyleSheet("color: blue"); + + const auto cur_res = m_display_session.video_session().current_resolution(); + if (cur_res.width == 0 || cur_res.height == 0){ + QMessageBox box; + box.warning(nullptr, "Invalid Image Dimension", + QString::fromStdString("Loaded image " + image_path + " has invalid dimension: " + cur_res.to_string())); + return; + } + + m_program.load_image_related_data(image_path, cur_res.width, cur_res.height); + m_program.update_rendered_objects(m_overlay_set); +} + } diff --git a/SerialPrograms/Source/ML/Programs/ML_LabelImages.h b/SerialPrograms/Source/ML/Programs/ML_LabelImages.h index 57002fbb8c..0197937387 100644 --- a/SerialPrograms/Source/ML/Programs/ML_LabelImages.h +++ b/SerialPrograms/Source/ML/Programs/ML_LabelImages.h @@ -7,6 +7,7 @@ #ifndef PokemonAutomation_ML_LabelImages_H #define PokemonAutomation_ML_LabelImages_H +#include #include "Common/Cpp/Options/BatchOption.h" #include "Common/Cpp/Options/FloatingPointOption.h" #include "CommonFramework/Panels/PanelInstance.h" @@ -18,24 +19,25 @@ #include "NintendoSwitch/Framework/NintendoSwitch_SwitchSystemOption.h" #include "NintendoSwitch/Framework/NintendoSwitch_SwitchSystemSession.h" #include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include -#include "ML/DataLabeling/SegmentAnythingModel.h" + +#include "ML/DataLabeling/ML_SegmentAnythingModel.h" +#include "ML/UI/ML_ImageAnnotationDisplayOption.h" +#include "ML/UI/ML_ImageAnnotationDisplaySession.h" class QGraphicsView; class QGraphicsPixmapItem; +class QLabel; namespace PokemonAutomation{ class ConfigWidget; -namespace NintendoSwitch{ - class SwitchSystemWidget; -} namespace ML{ +class ImageAnnotationDisplayWidget; class LabelImages_Widget; @@ -43,7 +45,8 @@ class LabelImages_Widget; // also include the related overlay rendering. // Since it owns rendering objects and the rendering framework needs // the address of the rendering objects to keep track of them, -// never copy or move this ObjectAnnotation object! +// never copy or move these ObjectAnnotation objects after rendering code has +// access to them! struct ObjectAnnotation{ ImagePixelBox user_box; // user drawn loose bounding box ImagePixelBox mask_box; @@ -59,29 +62,47 @@ class LabelImages_Descriptor : public PanelDescriptor{ LabelImages_Descriptor(); }; -// label image program + +// Program to annoatation images for training ML models class LabelImages : public PanelInstance{ public: LabelImages(const LabelImages_Descriptor& descriptor); virtual QWidget* make_widget(QWidget& parent, PanelHolder& holder) override; public: - // Serialization + // Serialization virtual void from_json(const JsonValue& json) override; virtual JsonValue to_json() const override; + void save_annotation_to_file() const; + + // called after loading a new image, clean up all internal data + void clear_for_new_image(); + + // Load image related data: + // - Image SAM embedding data file, which has the same file path but with a name suffix ".embedding" + // - Existing annotation file, which is stored in a pre-defined ML_ANNOTATION_PATH() and with the same filename as + // the image but with name extension replaced to be ".json". void load_image_related_data(const std::string& image_path, const size_t source_image_width, const size_t source_image_height); + // Update rendering data reflect the current annotation void update_rendered_objects(VideoOverlaySet& overlayset); + // Use user currently drawn box to compute per-pixel masks on the image using SAM model void compute_mask(VideoOverlaySet& overlay_set); + // Compute embeddings for all images in a folder. + // This can be very slow! + void compute_embeddings_for_folder(const std::string& image_folder); + private: friend class LabelImages_Widget; friend class DrawnBoundingBox; - // switch control options like what micro-controller - // and what video source to use - NintendoSwitch::SwitchSystemOption m_switch_control_option; + + // image display options like what image file is loaded + ImageAnnotationDisplayOption m_display_option; + // handles image display session, holding a reference to m_display_option + ImageAnnotationDisplaySession m_display_session; // the group option that holds rest of the options defined below: BatchOption m_options; @@ -100,7 +121,7 @@ class LabelImages : public PanelInstance{ ImageRGB32 m_mask_image; SAMSession m_sam_session; - std::vector m_annotated_objects; + std::vector m_annotations; size_t m_last_object_idx = 0; std::string m_annotation_file_path; // if we find an annotation file that is supposed to be created by user in a previous session, but @@ -131,7 +152,7 @@ class DrawnBoundingBox : public ConfigOption::Listener, public VideoOverlay::Mou }; -class LabelImages_Widget : public PanelWidget, public ConfigOption::Listener{ +class LabelImages_Widget : public PanelWidget, public ConfigOption::Listener, public VideoSession::StateListener{ public: ~LabelImages_Widget(); LabelImages_Widget( @@ -140,14 +161,24 @@ class LabelImages_Widget : public PanelWidget, public ConfigOption::Listener{ PanelHolder& holder ); + // called after loading a new image, clean up all internal data + void clear_for_new_image(); + virtual void on_config_value_changed(void* object) override; + // Overwrites VideoSession::StateListener::post_startup(). + virtual void post_startup(VideoSource* source) override; + private: LabelImages& m_program; - NintendoSwitch::SwitchSystemSession m_session; - NintendoSwitch::SwitchSystemWidget* m_switch_widget; + ImageAnnotationDisplaySession& m_display_session; + + ImageAnnotationDisplayWidget* m_image_display_widget; + VideoOverlaySet m_overlay_set; DrawnBoundingBox m_drawn_box; + + QLabel* m_embedding_info_label = nullptr; ConfigWidget* m_option_widget; friend class DrawnBoundingBox; diff --git a/SerialPrograms/Source/ML/UI/ML_ImageAnnotationCommandRow.cpp b/SerialPrograms/Source/ML/UI/ML_ImageAnnotationCommandRow.cpp new file mode 100644 index 0000000000..5728f67742 --- /dev/null +++ b/SerialPrograms/Source/ML/UI/ML_ImageAnnotationCommandRow.cpp @@ -0,0 +1,216 @@ +/* Command Row + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Qt/Options/ConfigWidget.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" +#include "CommonFramework/Recording/StreamHistoryOption.h" +#include "ML_ImageAnnotationCommandRow.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace ML{ + + +ImageAnnotationCommandRow::~ImageAnnotationCommandRow(){ + m_session.remove_listener(*this); +} +ImageAnnotationCommandRow::ImageAnnotationCommandRow( + QWidget& parent, + VideoOverlaySession& session +) + : QWidget(&parent) + , m_session(session) + , m_last_known_focus(false) + , m_last_known_state(ProgramState::STOPPED) +{ + QHBoxLayout* command_row = new QHBoxLayout(this); + command_row->setContentsMargins(0, 0, 0, 0); + QHBoxLayout* row = new QHBoxLayout(); + command_row->addLayout(row, 12); + + +#if 0 + row->addWidget(new QLabel("Keyboard Input:", this), 2); + row->addSpacing(5); +#endif + + row->addStretch(100); + + m_status = new QLabel(this); +// m_status->setVisible(false); + row->addWidget(m_status); + row->addSpacing(5); + +// row->addWidget(new QLabel("Overlays:", this)); + + m_overlay_boxes = new QCheckBox("Boxes", this); + m_overlay_boxes->setChecked(session.enabled_boxes()); + row->addWidget(m_overlay_boxes); + + m_overlay_text = new QCheckBox("Text", this); + m_overlay_text->setHidden(true); // Nothing uses text overlay yet. + m_overlay_text->setChecked(session.enabled_text()); + row->addWidget(m_overlay_text); + + if (PreloadSettings::instance().DEVELOPER_MODE){ + m_overlay_images = new QCheckBox("Masks", this); + m_overlay_images->setChecked(session.enabled_images()); + row->addWidget(m_overlay_images); + } + + m_overlay_log = new QCheckBox("Log", this); + m_overlay_log->setChecked(session.enabled_log()); + row->addWidget(m_overlay_log); + + m_overlay_stats = new QCheckBox("Stats", this); + m_overlay_stats->setChecked(session.enabled_stats()); + row->addWidget(m_overlay_stats); + + row->addSpacing(5); + +// m_test_button = new QPushButton("Test Button", this); +// row->addWidget(m_test_button, 3); + + update_ui(); + + connect( + m_overlay_boxes, &QCheckBox::clicked, + this, [this](bool checked){ m_session.set_enabled_boxes(checked); } + ); +#if QT_VERSION < 0x060700 + connect( + m_overlay_text, &QCheckBox::stateChanged, + this, [this](bool checked){ m_session.set_enabled_text(checked); } + ); + connect( + m_overlay_images, &QCheckBox::stateChanged, + this, [this](bool checked){ m_session.set_enabled_images(checked); } + ); + connect( + m_overlay_log, &QCheckBox::stateChanged, + this, [this](bool checked){ m_session.set_enabled_log(checked); } + ); + connect( + m_overlay_stats, &QCheckBox::stateChanged, + this, [this](bool checked){ m_session.set_enabled_stats(checked); } + ); +#else + connect( + m_overlay_text, &QCheckBox::checkStateChanged, + this, [this](Qt::CheckState state){ m_session.set_enabled_text(state == Qt::Checked); } + ); + if (PreloadSettings::instance().DEVELOPER_MODE){ + connect( + m_overlay_images, &QCheckBox::checkStateChanged, + this, [this](Qt::CheckState state){ m_session.set_enabled_images(state == Qt::Checked); } + ); + } + connect( + m_overlay_log, &QCheckBox::checkStateChanged, + this, [this](Qt::CheckState state){ m_session.set_enabled_log(state == Qt::Checked); } + ); + connect( + m_overlay_stats, &QCheckBox::checkStateChanged, + this, [this](Qt::CheckState state){ m_session.set_enabled_stats(state == Qt::Checked); } + ); +#endif + + m_session.add_listener(*this); +} + +void ImageAnnotationCommandRow::on_key_press(const QKeyEvent& key){ + if (!m_last_known_focus){ + m_session.add_log("Keyboard Command Suppressed: Not in focus.", COLOR_RED); + return; + } +} +void ImageAnnotationCommandRow::on_key_release(const QKeyEvent& key){} + +void ImageAnnotationCommandRow::set_focus(bool focused){ + if (m_last_known_focus == focused){ + return; + } + m_last_known_focus = focused; + update_ui(); +} + +void ImageAnnotationCommandRow::update_ui(){ + if (!m_last_known_focus){ + m_status->setText( + QString::fromStdString( + "Keyboard: " + html_color_text("⬤", COLOR_PURPLE) + ) + ); + return; + } + + m_status->setText( + QString::fromStdString( + "Keyboard: " + html_color_text("⬤", COLOR_DARKGREEN) + ) + ); +} + +void ImageAnnotationCommandRow::on_state_changed(ProgramState state){ + m_last_known_state = state; + update_ui(); +} + + +void ImageAnnotationCommandRow::on_overlay_enabled_boxes(bool enabled){ + QMetaObject::invokeMethod(this, [this, enabled]{ + this->m_overlay_boxes->setChecked(enabled); + }, Qt::QueuedConnection); +} +void ImageAnnotationCommandRow::on_overlay_enabled_text(bool enabled){ + QMetaObject::invokeMethod(this, [this, enabled]{ + this->m_overlay_text->setChecked(enabled); + }, Qt::QueuedConnection); +} +void ImageAnnotationCommandRow::on_overlay_enabled_images(bool enabled){ + QMetaObject::invokeMethod(this, [this, enabled]{ + this->m_overlay_images->setChecked(enabled); + }, Qt::QueuedConnection); +} +void ImageAnnotationCommandRow::on_overlay_enabled_log(bool enabled){ + QMetaObject::invokeMethod(this, [this, enabled]{ + this->m_overlay_log->setChecked(enabled); + }, Qt::QueuedConnection); +} +void ImageAnnotationCommandRow::on_overlay_enabled_stats(bool enabled){ + QMetaObject::invokeMethod(this, [this, enabled]{ + this->m_overlay_stats->setChecked(enabled); + }, Qt::QueuedConnection); +} +void ImageAnnotationCommandRow::ready_changed(bool ready){ +// cout << "ImageAnnotationCommandRow::ready_changed(): " << ready << endl; + QMetaObject::invokeMethod(this, [this]{ + update_ui(); + }, Qt::QueuedConnection); +} + + + + +} +} + + + + + + + + + + + + diff --git a/SerialPrograms/Source/ML/UI/ML_ImageAnnotationCommandRow.h b/SerialPrograms/Source/ML/UI/ML_ImageAnnotationCommandRow.h new file mode 100644 index 0000000000..0ea7a8203d --- /dev/null +++ b/SerialPrograms/Source/ML/UI/ML_ImageAnnotationCommandRow.h @@ -0,0 +1,73 @@ +/* ML Image Annotation Command Row + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef POKEMON_AUTOMATION_ML_ImageAnnotationCommandRow_H +#define POKEMON_AUTOMATION_ML_ImageAnnotationCommandRow_H + +#include +#include +#include +#include +#include "CommonFramework/Globals.h" +#include "CommonFramework/VideoPipeline/VideoOverlaySession.h" +#include "Controllers/ControllerSession.h" +#include "NintendoSwitch/Options/NintendoSwitch_ModelType.h" + +namespace PokemonAutomation{ +namespace ML{ + + +// UI that shows the checkerboxes to control whether to show video overlay elements. +// e.g. checkerbox to toggle on/off overlay boxes +class ImageAnnotationCommandRow : + public QWidget, + public VideoOverlaySession::ContentListener, + public ControllerSession::Listener +{ + Q_OBJECT + +public: + ~ImageAnnotationCommandRow(); + ImageAnnotationCommandRow( + QWidget& parent, + VideoOverlaySession& session + ); + + void on_key_press(const QKeyEvent& key); + void on_key_release(const QKeyEvent& key); + +public: + void set_focus(bool focused); + void update_ui(); + void on_state_changed(ProgramState state); + +private: + virtual void on_overlay_enabled_boxes (bool enabled) override; + virtual void on_overlay_enabled_text (bool enabled) override; + virtual void on_overlay_enabled_images (bool enabled) override; + virtual void on_overlay_enabled_log (bool enabled) override; + virtual void on_overlay_enabled_stats (bool enabled) override; + virtual void ready_changed(bool ready) override; + +private: + VideoOverlaySession& m_session; + QComboBox* m_command_box; + QLabel* m_status; + + QCheckBox* m_overlay_log; + QCheckBox* m_overlay_text; + QCheckBox* m_overlay_images; + QCheckBox* m_overlay_boxes; + QCheckBox* m_overlay_stats; + + bool m_last_known_focus; + ProgramState m_last_known_state; +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/ML/UI/ML_ImageAnnotationDisplayOption.cpp b/SerialPrograms/Source/ML/UI/ML_ImageAnnotationDisplayOption.cpp new file mode 100644 index 0000000000..e813d3757a --- /dev/null +++ b/SerialPrograms/Source/ML/UI/ML_ImageAnnotationDisplayOption.cpp @@ -0,0 +1,56 @@ +/* Switch System + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "ML_ImageAnnotationDisplayOption.h" + +namespace PokemonAutomation{ +namespace ML{ + +static const std::string JSON_IMAGE_PATH = "ImagePath"; +static const std::string JSON_OVERLAY = "Overlay"; + + +ImageAnnotationDisplayOption::ImageAnnotationDisplayOption() +{} +ImageAnnotationDisplayOption::ImageAnnotationDisplayOption(const JsonValue& json) +{ + load_json(json); +} +void ImageAnnotationDisplayOption::load_json(const JsonValue& json){ + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + return; + } + + const std::string* json_str = obj->get_string(JSON_IMAGE_PATH); + if (json_str){ + m_image_path = *json_str; + } + const JsonValue* value = obj->get_value(JSON_OVERLAY); + if (value){ + m_overlay.load_json(*value); + } +} +JsonValue ImageAnnotationDisplayOption::to_json() const{ + JsonObject root; + root[JSON_IMAGE_PATH] = m_image_path; + root[JSON_OVERLAY] = m_overlay.to_json(); + + return root; +} + + + + + + + +} +} + diff --git a/SerialPrograms/Source/ML/UI/ML_ImageAnnotationDisplayOption.h b/SerialPrograms/Source/ML/UI/ML_ImageAnnotationDisplayOption.h new file mode 100644 index 0000000000..e449dcccb7 --- /dev/null +++ b/SerialPrograms/Source/ML/UI/ML_ImageAnnotationDisplayOption.h @@ -0,0 +1,49 @@ +/* ML Image Annotation Display Option + * + * From: https://github.com/PokemonAutomation/ + * + * This class represents the serializable state of an image display and label UI. + * + * This class is not thread-safe. To access internal state of an image display session + * in a thread-safe way, use ImageAnnotationDisplaySession. + * + */ + +#ifndef POKEMON_AUTOMATION_ML_ImageAnnotationDisplayOption_H +#define POKEMON_AUTOMATION_ML_ImageAnnotationDisplayOption_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/AudioPipeline/AudioOption.h" +#include "CommonFramework/VideoPipeline/VideoSourceDescriptor.h" +#include "CommonFramework/VideoPipeline/VideoOverlayOption.h" +#include "Controllers/ControllerCapability.h" +#include "Controllers/ControllerDescriptor.h" +#include "NintendoSwitch/Options/NintendoSwitch_ModelType.h" + +namespace PokemonAutomation{ + class ControllerRequirements; +namespace ML{ + + +// options to load an image for image labeling purposes +class ImageAnnotationDisplayOption{ +public: + ImageAnnotationDisplayOption(); + ImageAnnotationDisplayOption(const JsonValue& json); + + void load_json(const JsonValue& json); + JsonValue to_json() const; + + +public: + std::string m_image_path; + VideoOverlayOption m_overlay; +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/ML/UI/ML_ImageAnnotationDisplaySession.cpp b/SerialPrograms/Source/ML/UI/ML_ImageAnnotationDisplaySession.cpp new file mode 100644 index 0000000000..efa3e911d6 --- /dev/null +++ b/SerialPrograms/Source/ML/UI/ML_ImageAnnotationDisplaySession.cpp @@ -0,0 +1,61 @@ +/* Switch System Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/Stats/CpuUtilizationStats.h" +#include "CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.h" +#include "Integrations/ProgramTracker.h" +#include "ML_ImageAnnotationDisplayOption.h" +#include "ML_ImageAnnotationDisplaySession.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace ML{ + +VideoSourceOption create_still_image_video_source_option(){ + VideoSourceOption option; + option.set_descriptor(option.get_descriptor_from_cache(VideoSourceType::StillImage)); + return option; +} + +ImageAnnotationDisplaySession::~ImageAnnotationDisplaySession(){ + try{ + m_logger.log("Shutting down ImageAnnotationDisplaySession..."); + }catch (...){} + + m_overlay.remove_stat(*m_main_thread_utilization); + m_overlay.remove_stat(*m_cpu_utilization); +} +ImageAnnotationDisplaySession::ImageAnnotationDisplaySession(ImageAnnotationDisplayOption& option) + : m_logger(global_logger_raw(), "ML") + , m_display_option(option) + , m_still_image_option(create_still_image_video_source_option()) + , m_video_session(m_logger, m_still_image_option) + , m_overlay(option.m_overlay) + , m_cpu_utilization(new CpuUtilizationStat()) + , m_main_thread_utilization(new ThreadUtilizationStat(current_thread_handle(), "Main Qt Thread:")) +{ + m_overlay.add_stat(*m_cpu_utilization); + m_overlay.add_stat(*m_main_thread_utilization); + + m_still_image_descriptor = std::make_shared(); +} + + +void ImageAnnotationDisplaySession::set_image_source(const std::string& path){ + m_display_option.m_image_path = path; + m_still_image_descriptor->set_path(path); + m_video_session.set_source(m_still_image_descriptor); +} + + + + + +} +} diff --git a/SerialPrograms/Source/ML/UI/ML_ImageAnnotationDisplaySession.h b/SerialPrograms/Source/ML/UI/ML_ImageAnnotationDisplaySession.h new file mode 100644 index 0000000000..35a656d457 --- /dev/null +++ b/SerialPrograms/Source/ML/UI/ML_ImageAnnotationDisplaySession.h @@ -0,0 +1,74 @@ +/* ML Image Annotation Display Session + * + * From: https://github.com/PokemonAutomation/ + * + * This class holds the run-time state of an image display session + * + * This class is fully thread-safe. You can call any functions from anywhere at + * anytime. + * + * Warning: Constructing this class requires an "option" parameter. It is not + * safe to modify this "option" parameter during the lifetime of this class. + * + */ + +#ifndef POKEMON_AUTOMATION_ML_ImageAnnotationDisplaySession_H +#define POKEMON_AUTOMATION_ML_ImageAnnotationDisplaySession_H + +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/AudioPipeline/AudioSession.h" +#include "CommonFramework/VideoPipeline/VideoSession.h" +#include "CommonFramework/VideoPipeline/VideoOverlaySession.h" +#include "CommonFramework/Recording/StreamHistorySession.h" +#include "CommonFramework/VideoPipeline/VideoSources/VideoSource_StillImage.h" +#include "Controllers/ControllerSession.h" +#include "Integrations/ProgramTrackerInterfaces.h" +#include "ML_ImageAnnotationDisplayOption.h" + + +namespace PokemonAutomation{ + class CpuUtilizationStat; + class ThreadUtilizationStat; +namespace ML{ + + + + +class ImageAnnotationDisplaySession { +public: + ~ImageAnnotationDisplaySession(); + ImageAnnotationDisplaySession(ImageAnnotationDisplayOption& option); + +public: + Logger& logger(){ return m_logger; } + virtual VideoFeed& video() { return m_video_session; } + VideoOverlay& overlay(){ return m_overlay; } + + void set_image_source(const std::string& path); + + const ImageAnnotationDisplayOption& option() const { return m_display_option; } + +public: + + VideoSession& video_session(){ return m_video_session; } + VideoOverlaySession& overlay_session(){ return m_overlay; } + +private: + TaggedLogger m_logger; + + ImageAnnotationDisplayOption& m_display_option; + VideoSourceOption m_still_image_option; + VideoSession m_video_session; + VideoOverlaySession m_overlay; + + std::shared_ptr m_still_image_descriptor; + + std::unique_ptr m_cpu_utilization; + std::unique_ptr m_main_thread_utilization; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/ML/UI/ML_ImageAnnotationDisplayWidget.cpp b/SerialPrograms/Source/ML/UI/ML_ImageAnnotationDisplayWidget.cpp new file mode 100644 index 0000000000..f370055618 --- /dev/null +++ b/SerialPrograms/Source/ML/UI/ML_ImageAnnotationDisplayWidget.cpp @@ -0,0 +1,132 @@ +/* ML Image Display Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Concurrency/FireForgetDispatcher.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Qt/CollapsibleGroupBox.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/VideoPipeline/UI/VideoDisplayWidget.h" +#include "NintendoSwitch/Framework/NintendoSwitch_SwitchSystemSession.h" +#include "NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget.h" +#include "NintendoSwitch/Framework/UI/NintendoSwitch_CommandRow.h" +#include "ML_ImageAnnotationDisplayWidget.h" +#include "ML_ImageAnnotationDisplaySession.h" +#include "ML_ImageAnnotationDisplayOption.h" +#include "ML_ImageAnnotationCommandRow.h" +#include "ML_ImageAnnotationSourceSelectorWidget.h" + +// #include +// using std::cout; +// using std::endl; + +namespace PokemonAutomation{ +namespace ML{ + + +ImageAnnotationDisplayWidget::~ImageAnnotationDisplayWidget(){ + // Delete all the UI elements first since they reference the states. + delete m_video_display; + delete m_selector_widget; +} + +ImageAnnotationDisplayWidget::ImageAnnotationDisplayWidget( + QWidget& parent, + ImageAnnotationDisplaySession& session, + uint64_t program_id +) + : QWidget(&parent) + , m_session(session) +{ + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + layout->setAlignment(Qt::AlignTop); + + m_group_box = new CollapsibleGroupBox(*this, "Image Settings"); + layout->addWidget(m_group_box); + + QWidget* widget = new QWidget(m_group_box); + m_group_box->set_widget(widget); + { + QVBoxLayout* video_holder = new QVBoxLayout(); + layout->addLayout(video_holder); + video_holder->setContentsMargins(0, 0, 0, 0); + + m_video_display = new VideoDisplayWidget( + *this, *video_holder, + 0, // display source ID. We only display one image for annotation. So 0. + *this, + m_session.video_session(), + m_session.overlay_session() + ); + video_holder->addWidget(m_video_display); + } + { + QVBoxLayout* group_layout = new QVBoxLayout(widget); + group_layout->setAlignment(Qt::AlignTop); + group_layout->setContentsMargins(0, 0, 0, 0); + + m_selector_widget = new ImageAnnotationSourceSelectorWidget(m_session); + group_layout->addWidget(m_selector_widget); + + m_command = new ImageAnnotationCommandRow( + *widget, + m_session.overlay_session() + ); + group_layout->addWidget(m_command); + } + + setFocusPolicy(Qt::StrongFocus); +} + + +void ImageAnnotationDisplayWidget::update_ui(ProgramState state){ + m_command->on_state_changed(state); +} + +void ImageAnnotationDisplayWidget::key_press(QKeyEvent* event){ +// cout << "press: " << event->nativeVirtualKey() << endl; + m_command->on_key_press(*event); +} + +void ImageAnnotationDisplayWidget::key_release(QKeyEvent* event){ +// cout << "release: " << event->nativeVirtualKey() << endl; + m_command->on_key_release(*event); +} + +void ImageAnnotationDisplayWidget::focus_in(QFocusEvent* event){ + m_command->set_focus(true); +} + +void ImageAnnotationDisplayWidget::focus_out(QFocusEvent* event){ + m_command->set_focus(false); +} + +void ImageAnnotationDisplayWidget::keyPressEvent(QKeyEvent* event){ + key_press(event); +} +void ImageAnnotationDisplayWidget::keyReleaseEvent(QKeyEvent* event){ + key_release(event); +} +void ImageAnnotationDisplayWidget::focusInEvent(QFocusEvent* event){ +// cout << "focusInEvent" << endl; + focus_in(event); + QWidget::focusInEvent(event); +} +void ImageAnnotationDisplayWidget::focusOutEvent(QFocusEvent* event){ +// cout << "focusOutEvent" << endl; + focus_out(event); + QWidget::focusOutEvent(event); +} + + + +} +} diff --git a/SerialPrograms/Source/ML/UI/ML_ImageAnnotationDisplayWidget.h b/SerialPrograms/Source/ML/UI/ML_ImageAnnotationDisplayWidget.h new file mode 100644 index 0000000000..4fd14bb9ba --- /dev/null +++ b/SerialPrograms/Source/ML/UI/ML_ImageAnnotationDisplayWidget.h @@ -0,0 +1,79 @@ +/* ML Image Annotation Display Widget + * + * From: https://github.com/PokemonAutomation/ + * + * This is the Qt Widget for displaying images for ML annotation purposes. + * This is modified from NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget. + */ + +#ifndef POKEMON_AUTOMATION_ML_ImageAnnotationDisplayWidget_H +#define POKEMON_AUTOMATION_ML_ImageAnnotationDisplayWidget_H + +#include +#include "CommonFramework/VideoPipeline/UI/VideoDisplayWidget.h" +#include "CommonFramework/Globals.h" + +namespace PokemonAutomation{ + class CollapsibleGroupBox; + class VideoDisplayWidget; + class VideoOverlay; + +namespace ML{ + +class ImageAnnotationSourceSelectorWidget; +class ImageAnnotationDisplaySession; +class ImageAnnotationCommandRow; + +// UI widget for loading and displaying an image for image annotation for training ML models +// It includes: +// - Image file selection UI +// - Image display window +// It also owns an ImageAnnotationDisplaySession that manages the life time of the image display +// session. +// It inherits `CommandReceiver` to handle keyboard and focus events happened on the image display +// window. +class ImageAnnotationDisplayWidget final : public QWidget, public CommandReceiver{ +public: + virtual ~ImageAnnotationDisplayWidget(); + ImageAnnotationDisplayWidget( + QWidget& parent, + ImageAnnotationDisplaySession& session, + uint64_t program_id + ); + +public: + void update_ui(ProgramState state); + + // The public versions of the private QWidget key and focus event handling functions. + // They are needed to accept key and focus passed from CommonFramework/VideoPipeline/UI:VideoDisplayWindow. + + virtual void key_press(QKeyEvent* event) override; + virtual void key_release(QKeyEvent* event) override; + + virtual void focus_in(QFocusEvent* event) override; + virtual void focus_out(QFocusEvent* event) override; + +private: + virtual void keyPressEvent(QKeyEvent* event) override; + virtual void keyReleaseEvent(QKeyEvent* event) override; + virtual void focusInEvent(QFocusEvent* event) override; + virtual void focusOutEvent(QFocusEvent* event) override; + +private: + ImageAnnotationDisplaySession& m_session; + + CollapsibleGroupBox* m_group_box; + + VideoDisplayWidget* m_video_display; + + ImageAnnotationCommandRow* m_command; + + ImageAnnotationSourceSelectorWidget* m_selector_widget; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/ML/UI/ML_ImageAnnotationSourceSelectorWidget.cpp b/SerialPrograms/Source/ML/UI/ML_ImageAnnotationSourceSelectorWidget.cpp new file mode 100644 index 0000000000..754beb606c --- /dev/null +++ b/SerialPrograms/Source/ML/UI/ML_ImageAnnotationSourceSelectorWidget.cpp @@ -0,0 +1,170 @@ +/* Video Source Selector Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Qt/NoWheelComboBox.h" +#include "CommonFramework/VideoPipeline/Backends/CameraImplementations.h" + +// #include "CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.h" +// #include "CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.h" + +#include "ML_ImageAnnotationSourceSelectorWidget.h" +#include "ML_ImageAnnotationDisplaySession.h" + +#include "ML/DataLabeling/ML_AnnotationIO.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace ML{ + + +ImageAnnotationSourceSelectorWidget::~ImageAnnotationSourceSelectorWidget(){ + m_session.video_session().remove_state_listener(*this); +} +ImageAnnotationSourceSelectorWidget::ImageAnnotationSourceSelectorWidget(ImageAnnotationDisplaySession& session) + : m_session(session) +{ + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + + QHBoxLayout* image_path_row = new QHBoxLayout(this); + layout->addLayout(image_path_row); + + image_path_row->setContentsMargins(0, 0, 0, 0); + + // image_path_row->addWidget(new QLabel("Video Input:", this), 1); + + image_path_row->addWidget(new QLabel("Image File Path: ", this)); + // image_path_row->addSpacing(5); + + m_source_file_path_label = new QLabel(this); + + image_path_row->addWidget(m_source_file_path_label, 5); + image_path_row->addSpacing(5); + + QPushButton* load_image_button = new QPushButton("Open Image", this); + image_path_row->addWidget(load_image_button, 0); + + QPushButton* reload_image_button = new QPushButton("Reload Image", this); + image_path_row->addWidget(reload_image_button, 0); + + QHBoxLayout* folder_info_row = new QHBoxLayout(this); + layout->addLayout(folder_info_row); + + m_folder_info_label = new QLabel(this); + folder_info_row->addWidget(m_folder_info_label, 3); + folder_info_row->addSpacing(3); + + QPushButton* prev_image_button = new QPushButton("Prev Image in Folder", this); + QPushButton* next_image_button = new QPushButton("Next Image in Folder", this); + folder_info_row->addWidget(prev_image_button, 2); + folder_info_row->addSpacing(2); + folder_info_row->addWidget(next_image_button, 2); + folder_info_row->addSpacing(10); + folder_info_row->addWidget(new QLabel(" ", this), 10); + + + // Set the action for the video reset button + connect( + load_image_button, &QPushButton::clicked, + this, [this](bool){ + const std::string& image_path = m_session.option().m_image_path; + std::string starting_dir = "."; + if (image_path.size() > 0){ + starting_dir = std::filesystem::path(image_path).parent_path().string(); + } + const std::string path = QFileDialog::getOpenFileName( + nullptr, "Open image file", QString::fromStdString(starting_dir), "*.png *.jpg *.jpeg" + ).toStdString(); + cout << "File dialog returns path " << path << endl; + + if (path.size() > 0){ + m_session.set_image_source(path); + } + } + ); + connect( + reload_image_button, &QPushButton::clicked, + this, [this](bool){ + const std::string& image_path = m_session.option().m_image_path; + if (image_path.size()){ + m_session.set_image_source(image_path); + } + } + ); + connect( + prev_image_button, &QPushButton::clicked, + this, [this](bool){ + if (m_cur_image_file_idx_in_folder != SIZE_MAX && m_cur_image_file_idx_in_folder > 0){ + m_cur_image_file_idx_in_folder--; + m_session.set_image_source(m_image_paths_in_folder[m_cur_image_file_idx_in_folder]); + } + } + ); + connect( + next_image_button, &QPushButton::clicked, + this, [this](bool){ + if (m_cur_image_file_idx_in_folder != SIZE_MAX && m_cur_image_file_idx_in_folder + 1 < m_image_paths_in_folder.size()){ + m_cur_image_file_idx_in_folder++; + m_session.set_image_source(m_image_paths_in_folder[m_cur_image_file_idx_in_folder]); + } + } + ); + + m_session.video_session().add_state_listener(*this); + + const std::string& image_path = m_session.option().m_image_path; + if(image_path.size() > 0){ + m_source_file_path_label->setText(QString::fromStdString(image_path)); + m_session.set_image_source(image_path); + } +} + + +// This callback function will be called whenever the display source (the image source) is loaded or reloaded: +void ImageAnnotationSourceSelectorWidget::post_startup(VideoSource* source){ + const std::string& image_path = m_session.option().m_image_path; + m_source_file_path_label->setText(QString::fromStdString(image_path)); + + const auto path = std::filesystem::path(image_path); + const auto filename = path.filename(); + const std::string folder_path = path.parent_path().string(); + const bool recursive_search = false; + m_image_paths_in_folder = find_images_in_folder(folder_path, recursive_search); + const size_t num_images = m_image_paths_in_folder.size(); + m_cur_image_file_idx_in_folder = SIZE_MAX; + for (size_t i = 0; i < num_images; i++){ + if (std::filesystem::path(m_image_paths_in_folder[i]).filename() == filename){ + m_cur_image_file_idx_in_folder = i; + } + } + if (m_cur_image_file_idx_in_folder == SIZE_MAX){ + std::cerr << "When searching the loaded image folder " << folder_path << ", cannot find the loaded image filename " + << filename << "." << std::endl; + m_folder_info_label->setText(QString::fromStdString("\?\?\?/" + std::to_string(num_images) + " in folder")); + } else{ + m_folder_info_label->setText(QString::fromStdString( + std::to_string(m_cur_image_file_idx_in_folder+1) + "/" + std::to_string(num_images) + " in folder")); + } +} + + + + + + + +} +} diff --git a/SerialPrograms/Source/ML/UI/ML_ImageAnnotationSourceSelectorWidget.h b/SerialPrograms/Source/ML/UI/ML_ImageAnnotationSourceSelectorWidget.h new file mode 100644 index 0000000000..525ad77813 --- /dev/null +++ b/SerialPrograms/Source/ML/UI/ML_ImageAnnotationSourceSelectorWidget.h @@ -0,0 +1,50 @@ +/* ML Image Annotation Source Selector Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ML_ImageAnnotationSourceSelectorWidget_H +#define PokemonAutomation_ML_ImageAnnotationSourceSelectorWidget_H + +#include +#include +#include "CommonFramework/VideoPipeline/VideoSession.h" + +class QComboBox; +class QPushButton; + +namespace PokemonAutomation{ +namespace ML{ + +class ImageAnnotationDisplaySession; + +// UI to select what image file to use for image annotation +// This class inherits VideoSession::StateListener so it has callbacks for state change +// in the video session. +class ImageAnnotationSourceSelectorWidget : public QWidget, public VideoSession::StateListener{ +public: + ~ImageAnnotationSourceSelectorWidget(); + ImageAnnotationSourceSelectorWidget(ImageAnnotationDisplaySession& session); + + +private: + // Overwrites VideoSession::StateListener::post_startup(). + virtual void post_startup(VideoSource* source) override; + + +private: + ImageAnnotationDisplaySession& m_session; + + QLabel* m_source_file_path_label; + QLabel* m_folder_info_label; + + std::vector m_image_paths_in_folder; + std::size_t m_cur_image_file_idx_in_folder = 0; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.cpp b/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.cpp index 5e082dbf58..4622fdebf4 100644 --- a/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.cpp @@ -20,25 +20,13 @@ void pbf_wait(ProControllerContext& context, Milliseconds duration){ ssf_do_nothing(context, duration); } void pbf_press_button(ProControllerContext& context, Button button, uint16_t hold_ticks, uint16_t release_ticks){ - uint32_t delay = (uint32_t)hold_ticks + release_ticks; - if ((uint16_t)delay == delay){ - ssf_press_button(context, button, (uint16_t)delay, hold_ticks, 0); - }else{ - ssf_press_button(context, button, hold_ticks, hold_ticks, 0); - ssf_do_nothing(context, release_ticks); - } + ssf_press_button(context, button, (hold_ticks + release_ticks) * 8ms, hold_ticks * 8ms, 0ms); } void pbf_press_button(ProControllerContext& context, Button button, Milliseconds hold, Milliseconds release){ ssf_press_button(context, button, hold + release, hold, 0ms); } void pbf_press_dpad(ProControllerContext& context, DpadPosition position, uint16_t hold_ticks, uint16_t release_ticks){ - uint32_t delay = (uint32_t)hold_ticks + release_ticks; - if ((uint16_t)delay == delay){ - ssf_press_dpad(context, position, (uint16_t)delay, hold_ticks, 0); - }else{ - ssf_press_dpad(context, position, hold_ticks, hold_ticks, 0); - ssf_do_nothing(context, release_ticks); - } + ssf_press_dpad(context, position, (hold_ticks + release_ticks) * 8ms, hold_ticks * 8ms, 0ms); } void pbf_press_dpad(ProControllerContext& context, DpadPosition position, Milliseconds hold, Milliseconds release){ ssf_press_dpad(context, position, hold + release, hold, 0ms); diff --git a/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.cpp b/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.cpp index 016c04b292..2744036930 100644 --- a/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.cpp @@ -171,6 +171,46 @@ void ssf_press_joystick( void ssf_mash1_button(JoyconContext& context, Button button, Milliseconds duration){ context->issue_mash_button(&context, button, duration); } +void ssf_issue_scroll( + JoyconContext& context, + DpadPosition direction, + Milliseconds delay +){ + ssf_issue_scroll(context, direction, delay, 2*delay, delay); +} +void ssf_issue_scroll( + JoyconContext& context, + DpadPosition direction, + Milliseconds delay, Milliseconds hold, Milliseconds cool +){ + switch (direction){ + case DpadPosition::DPAD_UP: + ssf_press_joystick(context, 128, 0, delay, hold, cool); + break; + case DpadPosition::DPAD_UP_RIGHT: + ssf_press_joystick(context, 255, 0, delay, hold, cool); + break; + case DpadPosition::DPAD_RIGHT: + ssf_press_joystick(context, 255, 128, delay, hold, cool); + break; + case DpadPosition::DPAD_DOWN_RIGHT: + ssf_press_joystick(context, 255, 255, delay, hold, cool); + break; + case DpadPosition::DPAD_DOWN: + ssf_press_joystick(context, 128, 255, delay, hold, cool); + break; + case DpadPosition::DPAD_DOWN_LEFT: + ssf_press_joystick(context, 0, 255, delay, hold, cool); + break; + case DpadPosition::DPAD_LEFT: + ssf_press_joystick(context, 0, 128, delay, hold, cool); + break; + case DpadPosition::DPAD_UP_LEFT: + ssf_press_joystick(context, 0, 0, delay, hold, cool); + break; + default:; + } +} diff --git a/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h b/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h index 9815c8d738..c9e99e7ed5 100644 --- a/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h +++ b/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h @@ -29,23 +29,11 @@ void ssf_do_nothing (ProControllerContext& context, uint16_t ticks); void ssf_do_nothing (ProControllerContext& context, Milliseconds duration); - -void ssf_press_button( - ProControllerContext& context, - Button button, - uint16_t delay, uint16_t hold = 5, uint8_t cool = 3 -); void ssf_press_button( ProControllerContext& context, Button button, Milliseconds delay = 24ms, Milliseconds hold = 48ms, Milliseconds cool = 24ms ); - -void ssf_press_dpad( - ProControllerContext& context, - DpadPosition position, - uint16_t delay, uint16_t hold = 5, uint8_t cool = 3 -); void ssf_press_dpad( ProControllerContext& context, DpadPosition position, @@ -91,11 +79,6 @@ void ssf_mash_AZs (ProControllerContext& context, Milliseconds duration); #define SSF_SCROLL_RIGHT DPAD_RIGHT #define SSF_SCROLL_DOWN DPAD_DOWN #define SSF_SCROLL_LEFT DPAD_LEFT -void ssf_issue_scroll( - ProControllerContext& context, - DpadPosition direction, - uint16_t delay, uint16_t hold = 5, uint8_t cool = 3 -); void ssf_issue_scroll( ProControllerContext& context, DpadPosition direction, @@ -188,60 +171,6 @@ inline void ssf_issue_scroll_ptv( -// -// The C API used by the MC programs. (no overloading allowed there) -// - -inline void ssf_press_button2( - ProControllerContext& context, - Button button, uint16_t duration, uint16_t hold -){ - ssf_press_button(context, button, duration, hold); -} -inline void ssf_press_button1( - ProControllerContext& context, - Button button, uint16_t duration -){ - ssf_press_button(context, button, duration); -} -inline void ssf_press_dpad2( - ProControllerContext& context, - DpadPosition dpad, uint16_t duration, uint16_t hold -){ - ssf_press_dpad(context, dpad, duration, hold); -} -inline void ssf_press_dpad1( - ProControllerContext& context, - DpadPosition dpad, uint16_t duration -){ - ssf_press_dpad(context, dpad, duration); -} -inline void ssf_press_joystick2( - ProControllerContext& context, - bool left, uint8_t x, uint8_t y, - uint16_t duration, uint16_t hold -){ - if (left){ - ssf_press_left_joystick(context, x, y, duration, hold); - }else{ - ssf_press_right_joystick(context, x, y, duration, hold); - } -} -inline void ssf_hold_joystick1( - ProControllerContext& context, - bool left, uint8_t x, uint8_t y, - uint16_t hold -){ - if (left){ - ssf_press_left_joystick(context, x, y, hold, hold); - }else{ - ssf_press_right_joystick(context, x, y, hold, hold); - } -} - - - - void ssf_flush_pipeline (JoyconContext& context); void ssf_do_nothing (JoyconContext& context, Milliseconds duration); @@ -256,6 +185,16 @@ void ssf_press_joystick( Milliseconds delay, Milliseconds hold, Milliseconds cool = 0ms ); void ssf_mash1_button (JoyconContext& context, Button button, Milliseconds duration); +void ssf_issue_scroll( + JoyconContext& context, + DpadPosition direction, + Milliseconds delay +); +void ssf_issue_scroll( + JoyconContext& context, + DpadPosition direction, + Milliseconds delay, Milliseconds hold, Milliseconds cool +); diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerSettings.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerSettings.cpp index 05da722c84..0f72328a21 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerSettings.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerSettings.cpp @@ -1,364 +1,364 @@ -/* Nintendo Switch Controller Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/CRC32.h" -#include "NintendoSwitch_ControllerSettings.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -uint32_t average_colors(uint32_t x, uint32_t y){ - // Average the two button colors. - uint32_t red = ((x >> 16) & 0xff) + ((y >> 16) & 0xff); - uint32_t green = ((x >> 8) & 0xff) + ((y >> 8) & 0xff); - uint32_t blue = ((x >> 0) & 0xff) + ((y >> 0) & 0xff); - red /= 2; - green /= 2; - blue /= 2; - return (red << 16) | (green << 8) | (blue << 0); -} - - -struct OfficialJoyconColors{ - std::string name; - uint32_t left_body; - uint32_t left_buttons; - uint32_t right_body; - uint32_t right_buttons; - - void write_to_profile(ControllerProfile& profile, ControllerType controller) const{ - profile.official_name = name; - switch (controller){ - case ControllerType::NintendoSwitch_WirelessProController:{ - // Set the grips to the joycon colors. - profile.left_grip = left_body; - profile.right_grip = right_body; - profile.body_color = average_colors(left_buttons, right_buttons); - profile.button_color = average_colors(left_body, right_body); - break; - } - case ControllerType::NintendoSwitch_LeftJoycon: - profile.button_color = left_buttons; - profile.body_color = left_body; - break; - case ControllerType::NintendoSwitch_RightJoycon: - profile.button_color = right_buttons; - profile.body_color = right_body; - break; - default:; - } - - } -}; - -const std::vector& OFFICIAL_JOYCON_COLORS(){ - // From: https://switchbrew.org/wiki/Joy-Con#Colors - const static std::vector database{ - {"Developer Black", 0x313131, 0x0F0F0F, 0x313131, 0x0F0F0F}, - - {"Stock: Grey / Grey", 0x828282, 0x0F0F0F, 0x828282, 0x0F0F0F}, - {"Stock: Neon Blue / Neon Red", 0x0AB9E6, 0x001E1E, 0xFF3C28, 0x1E0A0A}, - {"Stock: OLED White", 0xE6E6E6, 0x323232, 0xE6E6E6, 0x323232}, - - {"Neon Red / Neon Blue", 0xFF3C28, 0x1E0A0A, 0x0AB9E6, 0x001E1E}, - {"Blue / Neon Yellow", 0x4655F5, 0x00000A, 0xE6FF00, 0x142800}, - {"Neon Pink / Green Pink", 0xFF3278, 0x28001E, 0x1EDC00, 0x002800}, - {"Neon Green / Neon Pink", 0x1EDC00, 0x002800, 0xFF3278, 0x28001E}, - {"Neon Purple / Neon Orange", 0xB400E6, 0x140014, 0xFAA005, 0x0F0A00}, - {"Pastel Pink / Pastel Pink", 0xFFAFAF, 0x372D2D, 0xFFAFAF, 0x372D2D}, - {"Pastel Pink / Pastel Yellow", 0xFFAFAF, 0x372D2D, 0xF5FF82, 0x32332D}, - {"Pastel Purple / Pastel Green", 0xF0CBEB, 0x373037, 0xBCFFC8, 0x2D322D}, - - {"Super Mario Odyssey Edition Red", 0xE10F00, 0x280A0A, 0xE10F00, 0x280A0A}, - {"Let's Go! Pikachu and Eevee", 0xC88C32, 0x281900, 0xFFDC00, 0x322800}, - {"Nintendo Labo Creators Contest Edition", 0xD7AA73, 0x1E1914, 0xD7AA73, 0x1E1914}, - {"Dragon Quest XI S Lotto Edition", 0x1473FA, 0x00000F, 0x1473FA, 0x00000F}, -// {"Disney Tsum Tsum Festival Edition", 0xB400E6, 0x140014, 0xFF3278, 0x28001E}, - {"Animal Crossing: New Horizons Edition", 0x82FF96, 0x0A1E0A, 0x96F5F5, 0x0A1E28}, - {"Fortnite Wildcat Edition", 0xFFCC00, 0x1A1100, 0x0084FF, 0x000F1E}, - {"Mario Red x Blue Edition", 0xF04614, 0x1E1914, 0xF04614, 0x1E1914}, - {"Fortnite Fleet Force Edition", 0x0084FF, 0x000F1E, 0xFFCC00, 0x1A1100}, - {"Legend of Zelda: Skyward Sword Edition", 0x2D50F0, 0x1E0F46, 0x500FC8, 0x00051E}, - {"Splatoon 3 OLED Edition", 0x6455F5, 0x28282D, 0xC3FA05, 0x1E1E28}, - {"Pokémon: Scarlet x Violet OLED Edition", 0xF07341, 0x322D1E, 0x9650AA, 0x32322D}, - {"Legend of Zelda: Tears of the Kingdom Edition", 0xD2BE69, 0x32322D, 0xD2BE69, 0x32322D}, - }; - return database; -} - - -StringSelectDatabase make_JOYCON_DATABASE(){ - StringSelectDatabase database; - database.add_entry(StringSelectEntry("Custom", "Custom")); - for (const OfficialJoyconColors& item : OFFICIAL_JOYCON_COLORS()){ - database.add_entry( - StringSelectEntry(item.name, item.name) - ); - } - return database; -} -const StringSelectDatabase& JOYCON_DATABASE(){ - static const StringSelectDatabase database = make_JOYCON_DATABASE(); - return database; -} - - - - - -const EnumDropdownDatabase& ControllerSettingsType_Database(){ - static const EnumDropdownDatabase database({ - {ControllerType::NintendoSwitch_WirelessProController, "pro-controller", "Pro Controller"}, - {ControllerType::NintendoSwitch_LeftJoycon, "left-joycon", "Left Joycon"}, - {ControllerType::NintendoSwitch_RightJoycon, "right-joycon", "Right Joycon"}, - }); - return database; -} - - - -ControllerSettingsRow::~ControllerSettingsRow(){ - official_color.remove_listener(*this); -#if 1 - right_grip.remove_listener(*this); - left_grip.remove_listener(*this); -// body_color.remove_listener(*this); - button_color.remove_listener(*this); -#endif - controller.remove_listener(*this); -} -ControllerSettingsRow::ControllerSettingsRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , name(false, LockMode::UNLOCK_WHILE_RUNNING, "", "COM3") - , controller_mac_address(LockMode::UNLOCK_WHILE_RUNNING, 6, nullptr) - , controller( - ControllerSettingsType_Database(), - LockMode::UNLOCK_WHILE_RUNNING, - ControllerType::NintendoSwitch_WirelessProController - ) - , button_color( - LockMode::UNLOCK_WHILE_RUNNING, - false, - 0x0A1E19, 0x0A1E19 - ) - , body_color( - LockMode::UNLOCK_WHILE_RUNNING, - false, - 0xd0d0d0, 0xd0d0d0 - ) - , left_grip( - LockMode::UNLOCK_WHILE_RUNNING, - false, - 0x82FF96, 0x82FF96 - ) - , right_grip( - LockMode::UNLOCK_WHILE_RUNNING, - false, - 0x96F5F5, 0x96F5F5 - ) - , official_color( - JOYCON_DATABASE(), - LockMode::UNLOCK_WHILE_RUNNING, - 0 - ) - , m_pending_official_load(0) -{ - add_option(name, "Name"); - add_option(controller_mac_address, "Controller MAC Address"); - add_option(controller, "Controller"); - add_option(button_color, "Button"); - add_option(body_color, "Body"); - add_option(left_grip, "Left Grip"); - add_option(right_grip, "Right Grip"); - add_option(official_color, "Official Color"); - - set_profile(ControllerSettingsTable::random_profile(controller)); - - controller.add_listener(*this); -#if 1 - button_color.add_listener(*this); -// body_color.add_listener(*this); - left_grip.add_listener(*this); - right_grip.add_listener(*this); -#endif - official_color.add_listener(*this); -} -std::unique_ptr ControllerSettingsRow::clone() const{ - std::unique_ptr ret(new ControllerSettingsRow(parent())); - ret->name.set((std::string)name); - ret->controller_mac_address = controller_mac_address; - ret->controller.set(controller); - ret->button_color.set(button_color); - ret->body_color.set(body_color); - ret->left_grip.set(left_grip); - ret->right_grip.set(right_grip); - ret->official_color.set_by_index(official_color.index()); - return ret; -} -void ControllerSettingsRow::on_config_value_changed(void* object){ - if (object == &button_color || -// object == &body_color || - object == &left_grip || - object == &right_grip - ){ - if (m_pending_official_load.load(std::memory_order_relaxed) == 0){ - official_color.set_by_index(0); - } - return; - } - - if (object == &controller){ - ConfigOptionState state = controller == ControllerType::NintendoSwitch_WirelessProController - ? ConfigOptionState::ENABLED - : ConfigOptionState::HIDDEN; - left_grip.set_visibility(state); - right_grip.set_visibility(state); - - // Force an update on the chosen theme. - object = &official_color; - } - - if (object != &official_color){ - return; - } - - size_t index = official_color.index(); - if (index == 0){ - return; - } - - try{ - m_pending_official_load++; - - ControllerProfile profile{}; - OFFICIAL_JOYCON_COLORS()[index - 1].write_to_profile(profile, controller); - this->set_profile(profile); - - m_pending_official_load--; - }catch (...){ - m_pending_official_load--; - throw; - } - -} - - - - -ControllerSettingsTable::ControllerSettingsTable() - : EditableTableOption_t( - "Wireless Controller Settings:
Changes take effect after resetting the device.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) -{} -std::vector ControllerSettingsTable::make_header() const{ - return std::vector{ - "Name", - "MAC Address", - "Controller", - "Button", - "Body", - "Left Grip", - "Right Grip", - "Quick Select", - }; -} - - - -ControllerProfile ControllerSettingsTable::random_profile(ControllerType controller){ - const std::vector& DATABASE = OFFICIAL_JOYCON_COLORS(); - - ControllerProfile profile; - - uint64_t seed = std::chrono::high_resolution_clock::now().time_since_epoch().count(); - seed = pabb_crc32(0, &seed, sizeof(seed)); - seed %= DATABASE.size(); - - DATABASE[(size_t)seed].write_to_profile(profile, controller); - return profile; -} -ControllerProfile ControllerSettingsTable::get_or_make_profile( - const uint8_t mac_address[6], - const std::string& name, - ControllerType controller -){ -// cout << "ControllerSettingsTable::get_or_make_profile(): " << this << endl; - - ControllerProfile profile{}; - - // Only relevant to Switch controllers. - switch (controller){ - case ControllerType::NintendoSwitch_WiredProController: - case ControllerType::NintendoSwitch_WirelessProController: - case ControllerType::NintendoSwitch_LeftJoycon: - case ControllerType::NintendoSwitch_RightJoycon: - break; - default: - return profile; - } - - bool found = false; - this->run_on_all_rows([&, controller](ControllerSettingsRow& row){ - if (row.controller_mac_address == mac_address){ -// row.name.set(name); - row.controller_mac_address.set(mac_address); - row.controller.set(controller); - found = true; - profile = row; - return true; - } - if ((std::string)row.name != name){ - return false; - } - if (row.controller != controller){ - return false; - } - - row.controller_mac_address.set(mac_address); - found = true; - profile = row; - return true; - }); - - if (found){ - return profile; - } - - profile = random_profile(controller); - - std::unique_ptr row(new ControllerSettingsRow(*this)); - row->name.set(name); - row->controller_mac_address.set(mac_address); - row->controller.set(controller); - row->set_profile(profile); - - this->append_row(std::move(row)); - - return profile; -} - - - - - - - - - - - - - -} -} +/* Nintendo Switch Controller Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/CRC32.h" +#include "NintendoSwitch_ControllerSettings.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +uint32_t average_colors(uint32_t x, uint32_t y){ + // Average the two button colors. + uint32_t red = ((x >> 16) & 0xff) + ((y >> 16) & 0xff); + uint32_t green = ((x >> 8) & 0xff) + ((y >> 8) & 0xff); + uint32_t blue = ((x >> 0) & 0xff) + ((y >> 0) & 0xff); + red /= 2; + green /= 2; + blue /= 2; + return (red << 16) | (green << 8) | (blue << 0); +} + + +struct OfficialJoyconColors{ + std::string name; + uint32_t left_body; + uint32_t left_buttons; + uint32_t right_body; + uint32_t right_buttons; + + void write_to_profile(ControllerProfile& profile, ControllerType controller) const{ + profile.official_name = name; + switch (controller){ + case ControllerType::NintendoSwitch_WirelessProController:{ + // Set the grips to the joycon colors. + profile.left_grip = left_body; + profile.right_grip = right_body; + profile.body_color = average_colors(left_buttons, right_buttons); + profile.button_color = average_colors(left_body, right_body); + break; + } + case ControllerType::NintendoSwitch_LeftJoycon: + profile.button_color = left_buttons; + profile.body_color = left_body; + break; + case ControllerType::NintendoSwitch_RightJoycon: + profile.button_color = right_buttons; + profile.body_color = right_body; + break; + default:; + } + + } +}; + +const std::vector& OFFICIAL_JOYCON_COLORS(){ + // From: https://switchbrew.org/wiki/Joy-Con#Colors + const static std::vector database{ + {"Developer Black", 0x313131, 0x0F0F0F, 0x313131, 0x0F0F0F}, + + {"Stock: Grey / Grey", 0x828282, 0x0F0F0F, 0x828282, 0x0F0F0F}, + {"Stock: Neon Blue / Neon Red", 0x0AB9E6, 0x001E1E, 0xFF3C28, 0x1E0A0A}, + {"Stock: OLED White", 0xE6E6E6, 0x323232, 0xE6E6E6, 0x323232}, + + {"Neon Red / Neon Blue", 0xFF3C28, 0x1E0A0A, 0x0AB9E6, 0x001E1E}, + {"Blue / Neon Yellow", 0x4655F5, 0x00000A, 0xE6FF00, 0x142800}, + {"Neon Pink / Green Pink", 0xFF3278, 0x28001E, 0x1EDC00, 0x002800}, + {"Neon Green / Neon Pink", 0x1EDC00, 0x002800, 0xFF3278, 0x28001E}, + {"Neon Purple / Neon Orange", 0xB400E6, 0x140014, 0xFAA005, 0x0F0A00}, + {"Pastel Pink / Pastel Pink", 0xFFAFAF, 0x372D2D, 0xFFAFAF, 0x372D2D}, + {"Pastel Pink / Pastel Yellow", 0xFFAFAF, 0x372D2D, 0xF5FF82, 0x32332D}, + {"Pastel Purple / Pastel Green", 0xF0CBEB, 0x373037, 0xBCFFC8, 0x2D322D}, + + {"Super Mario Odyssey Edition Red", 0xE10F00, 0x280A0A, 0xE10F00, 0x280A0A}, + {"Let's Go! Pikachu and Eevee", 0xC88C32, 0x281900, 0xFFDC00, 0x322800}, + {"Nintendo Labo Creators Contest Edition", 0xD7AA73, 0x1E1914, 0xD7AA73, 0x1E1914}, + {"Dragon Quest XI S Lotto Edition", 0x1473FA, 0x00000F, 0x1473FA, 0x00000F}, +// {"Disney Tsum Tsum Festival Edition", 0xB400E6, 0x140014, 0xFF3278, 0x28001E}, + {"Animal Crossing: New Horizons Edition", 0x82FF96, 0x0A1E0A, 0x96F5F5, 0x0A1E28}, + {"Fortnite Wildcat Edition", 0xFFCC00, 0x1A1100, 0x0084FF, 0x000F1E}, + {"Mario Red x Blue Edition", 0xF04614, 0x1E1914, 0xF04614, 0x1E1914}, + {"Fortnite Fleet Force Edition", 0x0084FF, 0x000F1E, 0xFFCC00, 0x1A1100}, + {"Legend of Zelda: Skyward Sword Edition", 0x2D50F0, 0x1E0F46, 0x500FC8, 0x00051E}, + {"Splatoon 3 OLED Edition", 0x6455F5, 0x28282D, 0xC3FA05, 0x1E1E28}, + {"Pokémon: Scarlet x Violet OLED Edition", 0xF07341, 0x322D1E, 0x9650AA, 0x32322D}, + {"Legend of Zelda: Tears of the Kingdom Edition", 0xD2BE69, 0x32322D, 0xD2BE69, 0x32322D}, + }; + return database; +} + + +StringSelectDatabase make_JOYCON_DATABASE(){ + StringSelectDatabase database; + database.add_entry(StringSelectEntry("Custom", "Custom")); + for (const OfficialJoyconColors& item : OFFICIAL_JOYCON_COLORS()){ + database.add_entry( + StringSelectEntry(item.name, item.name) + ); + } + return database; +} +const StringSelectDatabase& JOYCON_DATABASE(){ + static const StringSelectDatabase database = make_JOYCON_DATABASE(); + return database; +} + + + + + +const EnumDropdownDatabase& ControllerSettingsType_Database(){ + static const EnumDropdownDatabase database({ + {ControllerType::NintendoSwitch_WirelessProController, "pro-controller", "Pro Controller"}, + {ControllerType::NintendoSwitch_LeftJoycon, "left-joycon", "Left Joycon"}, + {ControllerType::NintendoSwitch_RightJoycon, "right-joycon", "Right Joycon"}, + }); + return database; +} + + + +ControllerSettingsRow::~ControllerSettingsRow(){ + official_color.remove_listener(*this); +#if 1 + right_grip.remove_listener(*this); + left_grip.remove_listener(*this); +// body_color.remove_listener(*this); + button_color.remove_listener(*this); +#endif + controller.remove_listener(*this); +} +ControllerSettingsRow::ControllerSettingsRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , name(false, LockMode::UNLOCK_WHILE_RUNNING, "", "COM3") + , controller_mac_address(LockMode::UNLOCK_WHILE_RUNNING, 6, nullptr) + , controller( + ControllerSettingsType_Database(), + LockMode::UNLOCK_WHILE_RUNNING, + ControllerType::NintendoSwitch_WirelessProController + ) + , button_color( + LockMode::UNLOCK_WHILE_RUNNING, + false, + 0x0A1E19, 0x0A1E19 + ) + , body_color( + LockMode::UNLOCK_WHILE_RUNNING, + false, + 0xd0d0d0, 0xd0d0d0 + ) + , left_grip( + LockMode::UNLOCK_WHILE_RUNNING, + false, + 0x82FF96, 0x82FF96 + ) + , right_grip( + LockMode::UNLOCK_WHILE_RUNNING, + false, + 0x96F5F5, 0x96F5F5 + ) + , official_color( + JOYCON_DATABASE(), + LockMode::UNLOCK_WHILE_RUNNING, + 0 + ) + , m_pending_official_load(0) +{ + add_option(name, "Name"); + add_option(controller_mac_address, "Controller MAC Address"); + add_option(controller, "Controller"); + add_option(button_color, "Button"); + add_option(body_color, "Body"); + add_option(left_grip, "Left Grip"); + add_option(right_grip, "Right Grip"); + add_option(official_color, "Official Color"); + + set_profile(ControllerSettingsTable::random_profile(controller)); + + controller.add_listener(*this); +#if 1 + button_color.add_listener(*this); +// body_color.add_listener(*this); + left_grip.add_listener(*this); + right_grip.add_listener(*this); +#endif + official_color.add_listener(*this); +} +std::unique_ptr ControllerSettingsRow::clone() const{ + std::unique_ptr ret(new ControllerSettingsRow(parent())); + ret->name.set((std::string)name); + ret->controller_mac_address = controller_mac_address; + ret->controller.set(controller); + ret->button_color.set(button_color); + ret->body_color.set(body_color); + ret->left_grip.set(left_grip); + ret->right_grip.set(right_grip); + ret->official_color.set_by_index(official_color.index()); + return ret; +} +void ControllerSettingsRow::on_config_value_changed(void* object){ + if (object == &button_color || +// object == &body_color || + object == &left_grip || + object == &right_grip + ){ + if (m_pending_official_load.load(std::memory_order_relaxed) == 0){ + official_color.set_by_index(0); + } + return; + } + + if (object == &controller){ + ConfigOptionState state = controller == ControllerType::NintendoSwitch_WirelessProController + ? ConfigOptionState::ENABLED + : ConfigOptionState::HIDDEN; + left_grip.set_visibility(state); + right_grip.set_visibility(state); + + // Force an update on the chosen theme. + object = &official_color; + } + + if (object != &official_color){ + return; + } + + size_t index = official_color.index(); + if (index == 0){ + return; + } + + try{ + m_pending_official_load++; + + ControllerProfile profile{}; + OFFICIAL_JOYCON_COLORS()[index - 1].write_to_profile(profile, controller); + this->set_profile(profile); + + m_pending_official_load--; + }catch (...){ + m_pending_official_load--; + throw; + } + +} + + + + +ControllerSettingsTable::ControllerSettingsTable() + : EditableTableOption_t( + "Wireless Controller Settings:
Changes take effect after resetting the device.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) +{} +std::vector ControllerSettingsTable::make_header() const{ + return std::vector{ + "Name", + "MAC Address", + "Controller", + "Button", + "Body", + "Left Grip", + "Right Grip", + "Quick Select", + }; +} + + + +ControllerProfile ControllerSettingsTable::random_profile(ControllerType controller){ + const std::vector& DATABASE = OFFICIAL_JOYCON_COLORS(); + + ControllerProfile profile; + + uint64_t seed = std::chrono::high_resolution_clock::now().time_since_epoch().count(); + seed = pabb_crc32(0, &seed, sizeof(seed)); + seed %= DATABASE.size(); + + DATABASE[(size_t)seed].write_to_profile(profile, controller); + return profile; +} +ControllerProfile ControllerSettingsTable::get_or_make_profile( + const uint8_t mac_address[6], + const std::string& name, + ControllerType controller +){ +// cout << "ControllerSettingsTable::get_or_make_profile(): " << this << endl; + + ControllerProfile profile{}; + + // Only relevant to Switch controllers. + switch (controller){ + case ControllerType::NintendoSwitch_WiredProController: + case ControllerType::NintendoSwitch_WirelessProController: + case ControllerType::NintendoSwitch_LeftJoycon: + case ControllerType::NintendoSwitch_RightJoycon: + break; + default: + return profile; + } + + bool found = false; + this->run_on_all_rows([&, controller](ControllerSettingsRow& row){ + if (row.controller_mac_address == mac_address){ +// row.name.set(name); + row.controller_mac_address.set(mac_address); + row.controller.set(controller); + found = true; + profile = row; + return true; + } + if ((std::string)row.name != name){ + return false; + } + if (row.controller != controller){ + return false; + } + + row.controller_mac_address.set(mac_address); + found = true; + profile = row; + return true; + }); + + if (found){ + return profile; + } + + profile = random_profile(controller); + + std::unique_ptr row(new ControllerSettingsRow(*this)); + row->name.set(name); + row->controller_mac_address.set(mac_address); + row->controller.set(controller); + row->set_profile(profile); + + this->append_row(std::move(row)); + + return profile; +} + + + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerSettings.h b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerSettings.h index 1cb8cb94d3..9d5ba89665 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerSettings.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerSettings.h @@ -1,87 +1,87 @@ -/* Nintendo Switch Controller Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_ControllerSettings_H -#define PokemonAutomation_NintendoSwitch_ControllerSettings_H - -#include "Common/Cpp/Options/StringOption.h" -#include "Common/Cpp/Options/ColorOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/MacAddressOption.h" -#include "Common/Cpp/Options/EditableTableOption.h" -#include "CommonTools/Options/StringSelectOption.h" -#include "Controllers/ControllerTypes.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -struct ControllerProfile{ - uint32_t button_color; - uint32_t body_color; - uint32_t left_grip; - uint32_t right_grip; - std::string official_name; -}; - -class ControllerSettingsRow : public EditableTableRow, public ConfigOption::Listener{ -public: - ~ControllerSettingsRow(); - ControllerSettingsRow(EditableTableOption& parent_table); - virtual std::unique_ptr clone() const override; - virtual void on_config_value_changed(void* object) override; - - operator ControllerProfile() const{ - return { - button_color, - body_color, - left_grip, - right_grip, - official_color.slug(), - }; - } - void set_profile(const ControllerProfile& profile){ - button_color.set(profile.button_color); - body_color.set(profile.body_color); - left_grip.set(profile.left_grip); - right_grip.set(profile.right_grip); - official_color.set_by_slug(profile.official_name); - } - -public: - StringCell name; - MacAddressCell controller_mac_address; - EnumDropdownCell controller; - ColorCell button_color; - ColorCell body_color; - ColorCell left_grip; - ColorCell right_grip; - StringSelectCell official_color; - -private: - std::atomic m_pending_official_load; -}; - - -class ControllerSettingsTable : public EditableTableOption_t{ -public: - ControllerSettingsTable(); - virtual std::vector make_header() const override; - - static ControllerProfile random_profile(ControllerType controller); - ControllerProfile get_or_make_profile( - const uint8_t mac_address[6], - const std::string& name, - ControllerType controller - ); - -}; - - -} -} -#endif +/* Nintendo Switch Controller Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_ControllerSettings_H +#define PokemonAutomation_NintendoSwitch_ControllerSettings_H + +#include "Common/Cpp/Options/StringOption.h" +#include "Common/Cpp/Options/ColorOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/MacAddressOption.h" +#include "Common/Cpp/Options/EditableTableOption.h" +#include "CommonTools/Options/StringSelectOption.h" +#include "Controllers/ControllerTypes.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +struct ControllerProfile{ + uint32_t button_color; + uint32_t body_color; + uint32_t left_grip; + uint32_t right_grip; + std::string official_name; +}; + +class ControllerSettingsRow : public EditableTableRow, public ConfigOption::Listener{ +public: + ~ControllerSettingsRow(); + ControllerSettingsRow(EditableTableOption& parent_table); + virtual std::unique_ptr clone() const override; + virtual void on_config_value_changed(void* object) override; + + operator ControllerProfile() const{ + return { + button_color, + body_color, + left_grip, + right_grip, + official_color.slug(), + }; + } + void set_profile(const ControllerProfile& profile){ + button_color.set(profile.button_color); + body_color.set(profile.body_color); + left_grip.set(profile.left_grip); + right_grip.set(profile.right_grip); + official_color.set_by_slug(profile.official_name); + } + +public: + StringCell name; + MacAddressCell controller_mac_address; + EnumDropdownCell controller; + ColorCell button_color; + ColorCell body_color; + ColorCell left_grip; + ColorCell right_grip; + StringSelectCell official_color; + +private: + std::atomic m_pending_official_load; +}; + + +class ControllerSettingsTable : public EditableTableOption_t{ +public: + ControllerSettingsTable(); + virtual std::vector make_header() const override; + + static ControllerProfile random_profile(ControllerType controller); + ControllerProfile get_or_make_profile( + const uint8_t mac_address[6], + const std::string& name, + ControllerType controller + ); + +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerState.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerState.cpp index 85b0133214..65373e890c 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerState.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerState.cpp @@ -1,63 +1,65 @@ -/* Nintendo Switch Controller State - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch_ControllerState.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -std::string button_to_string(Button button){ - std::string str; - if (button & BUTTON_Y) str += "Y "; - if (button & BUTTON_B) str += "B "; - if (button & BUTTON_A) str += "A "; - if (button & BUTTON_X) str += "X "; - if (button & BUTTON_L) str += "L "; - if (button & BUTTON_R) str += "R "; - if (button & BUTTON_ZL) str += "ZL "; - if (button & BUTTON_ZR) str += "ZR "; - if (button & BUTTON_MINUS) str += "- "; - if (button & BUTTON_PLUS) str += "+ "; - if (button & BUTTON_LCLICK) str += "LJ "; - if (button & BUTTON_RCLICK) str += "RJ "; - if (button & BUTTON_HOME) str += "HOME "; - if (button & BUTTON_CAPTURE) str += "CAPTURE "; - if (button & BUTTON_UP) str += "Up "; - if (button & BUTTON_RIGHT) str += "Right "; - if (button & BUTTON_DOWN) str += "Down "; - if (button & BUTTON_LEFT) str += "Left "; - if (button & BUTTON_LEFT_SL) str += "Left-SL"; - if (button & BUTTON_LEFT_SR) str += "Left-SR"; - if (button & BUTTON_RIGHT_SL) str += "Right-SL"; - if (button & BUTTON_RIGHT_SR) str += "Right-SR"; - if (str.empty()){ - str = "none"; - } - if (str.back() == ' '){ - str.pop_back(); - } - return str; -} -std::string dpad_to_string(DpadPosition dpad){ - switch (dpad){ - case DPAD_UP : return "up"; - case DPAD_UP_RIGHT : return "up-right"; - case DPAD_RIGHT : return "right"; - case DPAD_DOWN_RIGHT : return "down-right"; - case DPAD_DOWN : return "down"; - case DPAD_DOWN_LEFT : return "down-left"; - case DPAD_LEFT : return "left"; - case DPAD_UP_LEFT : return "up-left"; - case DPAD_NONE : return "none"; - } - return "unknown"; -} - - - -} -} +/* Nintendo Switch Controller State + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch_ControllerState.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +std::string button_to_string(Button button){ + std::string str; + if (button & BUTTON_Y) str += "Y "; + if (button & BUTTON_B) str += "B "; + if (button & BUTTON_A) str += "A "; + if (button & BUTTON_X) str += "X "; + if (button & BUTTON_L) str += "L "; + if (button & BUTTON_R) str += "R "; + if (button & BUTTON_ZL) str += "ZL "; + if (button & BUTTON_ZR) str += "ZR "; + if (button & BUTTON_MINUS) str += "- "; + if (button & BUTTON_PLUS) str += "+ "; + if (button & BUTTON_LCLICK) str += "LJ "; + if (button & BUTTON_RCLICK) str += "RJ "; + if (button & BUTTON_HOME) str += "HOME "; + if (button & BUTTON_CAPTURE) str += "CAPTURE "; + if (button & BUTTON_GR) str += "GR "; + if (button & BUTTON_GL) str += "GL "; + if (button & BUTTON_UP) str += "Up "; + if (button & BUTTON_RIGHT) str += "Right "; + if (button & BUTTON_DOWN) str += "Down "; + if (button & BUTTON_LEFT) str += "Left "; + if (button & BUTTON_LEFT_SL) str += "Left-SL"; + if (button & BUTTON_LEFT_SR) str += "Left-SR"; + if (button & BUTTON_RIGHT_SL) str += "Right-SL"; + if (button & BUTTON_RIGHT_SR) str += "Right-SR"; + if (str.empty()){ + str = "none"; + } + if (str.back() == ' '){ + str.pop_back(); + } + return str; +} +std::string dpad_to_string(DpadPosition dpad){ + switch (dpad){ + case DPAD_UP : return "up"; + case DPAD_UP_RIGHT : return "up-right"; + case DPAD_RIGHT : return "right"; + case DPAD_DOWN_RIGHT : return "down-right"; + case DPAD_DOWN : return "down"; + case DPAD_DOWN_LEFT : return "down-left"; + case DPAD_LEFT : return "left"; + case DPAD_UP_LEFT : return "up-left"; + case DPAD_NONE : return "none"; + } + return "unknown"; +} + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerState.h b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerState.h index 21fd95f6db..d97ae77c8e 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerState.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerState.h @@ -1,94 +1,96 @@ -/* Nintendo Switch Controller State - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_ControllerState_H -#define PokemonAutomation_NintendoSwitch_ControllerState_H - -#include -#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -// Legacy tick type. This comes from the refresh rate of the wired controller. -// One second = 125 ticks. Thus each tick is 8 milliseconds. -constexpr uint16_t TICKS_PER_SECOND = 125; - - -// Buttons -constexpr size_t TOTAL_BUTTONS = 22; -using ButtonFlagType = uint32_t; -enum Button : ButtonFlagType{ - BUTTON_NONE = 0, - BUTTON_Y = ((uint32_t)1 << 0), - BUTTON_B = ((uint32_t)1 << 1), - BUTTON_A = ((uint32_t)1 << 2), - BUTTON_X = ((uint32_t)1 << 3), - BUTTON_L = ((uint32_t)1 << 4), - BUTTON_R = ((uint32_t)1 << 5), - BUTTON_ZL = ((uint32_t)1 << 6), - BUTTON_ZR = ((uint32_t)1 << 7), - BUTTON_MINUS = ((uint32_t)1 << 8), - BUTTON_PLUS = ((uint32_t)1 << 9), - BUTTON_LCLICK = ((uint32_t)1 << 10), - BUTTON_RCLICK = ((uint32_t)1 << 11), - BUTTON_HOME = ((uint32_t)1 << 12), - BUTTON_CAPTURE = ((uint32_t)1 << 13), - BUTTON_UP = ((uint32_t)1 << 14), - BUTTON_RIGHT = ((uint32_t)1 << 15), - BUTTON_DOWN = ((uint32_t)1 << 16), - BUTTON_LEFT = ((uint32_t)1 << 17), - BUTTON_LEFT_SL = ((uint32_t)1 << 18), - BUTTON_LEFT_SR = ((uint32_t)1 << 19), - BUTTON_RIGHT_SL = ((uint32_t)1 << 20), - BUTTON_RIGHT_SR = ((uint32_t)1 << 21), -}; -inline constexpr Button operator|(Button x, Button y){ - return (Button)((ButtonFlagType)x | (ButtonFlagType)y); -} -inline constexpr void operator|=(Button& x, Button y){ - x = (Button)((ButtonFlagType)x | (ButtonFlagType)y); -} -inline constexpr Button operator&(Button x, Button y){ - return (Button)((ButtonFlagType)x & (ButtonFlagType)y); -} -inline constexpr void operator&=(Button& x, Button y){ - x = (Button)((ButtonFlagType)x & (ButtonFlagType)y); -} - -std::string button_to_string(Button button); - - - - -// Dpad -enum DpadPosition : uint8_t{ - DPAD_UP = 0, - DPAD_UP_RIGHT = 1, - DPAD_RIGHT = 2, - DPAD_DOWN_RIGHT = 3, - DPAD_DOWN = 4, - DPAD_DOWN_LEFT = 5, - DPAD_LEFT = 6, - DPAD_UP_LEFT = 7, - DPAD_NONE = 8, -}; - -std::string dpad_to_string(DpadPosition dpad); - - - -// Joysticks -constexpr uint8_t STICK_MIN = 0x00; -constexpr uint8_t STICK_CENTER = 0x80; -constexpr uint8_t STICK_MAX = 0xff; - - - -} -} -#endif +/* Nintendo Switch Controller State + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_ControllerState_H +#define PokemonAutomation_NintendoSwitch_ControllerState_H + +#include +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +// Legacy tick type. This comes from the refresh rate of the wired controller. +// One second = 125 ticks. Thus each tick is 8 milliseconds. +constexpr uint16_t TICKS_PER_SECOND = 125; + + +// Buttons +constexpr size_t TOTAL_BUTTONS = 24; +using ButtonFlagType = uint32_t; +enum Button : ButtonFlagType{ + BUTTON_NONE = 0, + BUTTON_Y = ((uint32_t)1 << 0), + BUTTON_B = ((uint32_t)1 << 1), + BUTTON_A = ((uint32_t)1 << 2), + BUTTON_X = ((uint32_t)1 << 3), + BUTTON_L = ((uint32_t)1 << 4), + BUTTON_R = ((uint32_t)1 << 5), + BUTTON_ZL = ((uint32_t)1 << 6), + BUTTON_ZR = ((uint32_t)1 << 7), + BUTTON_MINUS = ((uint32_t)1 << 8), + BUTTON_PLUS = ((uint32_t)1 << 9), + BUTTON_LCLICK = ((uint32_t)1 << 10), + BUTTON_RCLICK = ((uint32_t)1 << 11), + BUTTON_HOME = ((uint32_t)1 << 12), + BUTTON_CAPTURE = ((uint32_t)1 << 13), + BUTTON_GR = ((uint32_t)1 << 14), + BUTTON_GL = ((uint32_t)1 << 15), + BUTTON_UP = ((uint32_t)1 << 16), + BUTTON_RIGHT = ((uint32_t)1 << 17), + BUTTON_DOWN = ((uint32_t)1 << 18), + BUTTON_LEFT = ((uint32_t)1 << 19), + BUTTON_LEFT_SL = ((uint32_t)1 << 20), + BUTTON_LEFT_SR = ((uint32_t)1 << 21), + BUTTON_RIGHT_SL = ((uint32_t)1 << 22), + BUTTON_RIGHT_SR = ((uint32_t)1 << 23), +}; +inline constexpr Button operator|(Button x, Button y){ + return (Button)((ButtonFlagType)x | (ButtonFlagType)y); +} +inline constexpr void operator|=(Button& x, Button y){ + x = (Button)((ButtonFlagType)x | (ButtonFlagType)y); +} +inline constexpr Button operator&(Button x, Button y){ + return (Button)((ButtonFlagType)x & (ButtonFlagType)y); +} +inline constexpr void operator&=(Button& x, Button y){ + x = (Button)((ButtonFlagType)x & (ButtonFlagType)y); +} + +std::string button_to_string(Button button); + + + + +// Dpad +enum DpadPosition : uint8_t{ + DPAD_UP = 0, + DPAD_UP_RIGHT = 1, + DPAD_RIGHT = 2, + DPAD_DOWN_RIGHT = 3, + DPAD_DOWN = 4, + DPAD_DOWN_LEFT = 5, + DPAD_LEFT = 6, + DPAD_UP_LEFT = 7, + DPAD_NONE = 8, +}; + +std::string dpad_to_string(DpadPosition dpad); + + + +// Joysticks +constexpr uint8_t STICK_MIN = 0x00; +constexpr uint8_t STICK_CENTER = 0x80; +constexpr uint8_t STICK_MAX = 0xff; + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.cpp index a4d44659f3..2cbddd645f 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.cpp @@ -1,458 +1,458 @@ -/* Nintendo Switch Controller (With Scheduler) - * - * From: https://github.com/PokemonAutomation/ - * - * This implements most of the SwitchController API using only the controller - * state function. It uses SuperscalarScheduler to do this. - * - */ - -#include "NintendoSwitch_ControllerWithScheduler.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -using namespace std::chrono_literals; - - - - -ControllerWithScheduler::ControllerWithScheduler(Logger& logger) - : SuperscalarScheduler( - logger, Milliseconds(4), - make_resource_list() - ) - , m_logger(logger) -// , m_logging_suppress(0) -{} - - - -void ControllerWithScheduler::issue_barrier(const Cancellable* cancellable){ - std::lock_guard lg0(m_issue_lock); - std::lock_guard lg1(m_state_lock); - this->issue_wait_for_all(cancellable); - if (m_logging_throttler){ - m_logger.log("issue_barrier()", COLOR_DARKGREEN); - } -} -void ControllerWithScheduler::issue_nop(const Cancellable* cancellable, Milliseconds duration){ - std::lock_guard lg0(m_issue_lock); - std::lock_guard lg1(m_state_lock); - if (cancellable){ - cancellable->throw_if_cancelled(); - } - this->SuperscalarScheduler::issue_nop(cancellable, WallDuration(duration)); - if (m_logging_throttler){ - m_logger.log( - "issue_nop(): duration = " + std::to_string(duration.count()) + "ms", - COLOR_DARKGREEN - ); - } -} -void ControllerWithScheduler::issue_buttons( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - Button button -){ - std::lock_guard lg0(m_issue_lock); - std::lock_guard lg1(m_state_lock); - if (cancellable){ - cancellable->throw_if_cancelled(); - } - - for (size_t c = 0; c < TOTAL_BUTTONS; c++){ - ButtonFlagType mask = (ButtonFlagType)1 << c; - if (button & mask){ - this->issue_wait_for_resource(cancellable, m_buttons[c]); - } - } - for (size_t c = 0; c < TOTAL_BUTTONS; c++){ - ButtonFlagType mask = (ButtonFlagType)1 << c; - if (button & mask){ - this->issue_to_resource( - cancellable, m_buttons[c], - WallDuration::zero(), hold, cooldown - ); - } - } - this->SuperscalarScheduler::issue_nop(cancellable, delay); - - if (m_logging_throttler){ - m_logger.log( - "issue_buttons(): " + button_to_string(button) + - ", delay = " + std::to_string(delay.count()) + "ms" + - ", hold = " + std::to_string(hold.count()) + "ms" + - ", cooldown = " + std::to_string(cooldown.count()) + "ms", - COLOR_DARKGREEN - ); - } -} -void ControllerWithScheduler::issue_dpad( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition position -){ - std::lock_guard lg0(m_issue_lock); - std::lock_guard lg1(m_state_lock); - if (cancellable){ - cancellable->throw_if_cancelled(); - } - - this->issue_wait_for_resource(cancellable, m_dpad); - m_dpad.position = position; - this->issue_to_resource(cancellable, m_dpad, delay, hold, cooldown); - - if (m_logging_throttler){ - m_logger.log( - "issue_dpad(): " + dpad_to_string(position) + - ", delay = " + std::to_string(delay.count()) + "ms" + - ", hold = " + std::to_string(hold.count()) + "ms" + - ", cooldown = " + std::to_string(cooldown.count()) + "ms", - COLOR_DARKGREEN - ); - } -} -void ControllerWithScheduler::issue_left_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y -){ - std::lock_guard lg0(m_issue_lock); - std::lock_guard lg1(m_state_lock); - - if (cancellable){ - cancellable->throw_if_cancelled(); - } - - this->issue_wait_for_resource(cancellable, m_left_joystick); - m_left_joystick.x = x; - m_left_joystick.y = y; - this->issue_to_resource(cancellable, m_left_joystick, delay, hold, cooldown); - - if (m_logging_throttler){ - m_logger.log( - "issue_left_joystick(): (" + std::to_string(x) + "," + std::to_string(y) + ")" + - ", delay = " + std::to_string(delay.count()) + "ms" + - ", hold = " + std::to_string(hold.count()) + "ms" + - ", cooldown = " + std::to_string(cooldown.count()) + "ms", - COLOR_DARKGREEN - ); - } -} -void ControllerWithScheduler::issue_right_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y -){ - std::lock_guard lg0(m_issue_lock); - std::lock_guard lg1(m_state_lock); - if (cancellable){ - cancellable->throw_if_cancelled(); - } - - this->issue_wait_for_resource(cancellable, m_right_joystick); - m_right_joystick.x = x; - m_right_joystick.y = y; - this->issue_to_resource(cancellable, m_right_joystick, delay, hold, cooldown); - - if (m_logging_throttler){ - m_logger.log( - "issue_right_joystick(): (" + std::to_string(x) + "," + std::to_string(y) + ")" + - ", delay = " + std::to_string(delay.count()) + "ms" + - ", hold = " + std::to_string(hold.count()) + "ms" + - ", cooldown = " + std::to_string(cooldown.count()) + "ms", - COLOR_DARKGREEN - ); - } -} - - - -void ControllerWithScheduler::issue_gyro( - const Cancellable* cancellable, - SwitchGyro& gyro, const char* name, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value -){ - std::lock_guard lg0(m_issue_lock); - std::lock_guard lg1(m_state_lock); - if (cancellable){ - cancellable->throw_if_cancelled(); - } - - this->issue_wait_for_resource(cancellable, gyro); - gyro.value = value; - this->issue_to_resource(cancellable, gyro, delay, hold, cooldown); - - if (m_logging_throttler){ - m_logger.log( - std::string(name) + "(): (" + std::to_string(value) + ")" + - ", delay = " + std::to_string(delay.count()) + "ms" + - ", hold = " + std::to_string(hold.count()) + "ms" + - ", cooldown = " + std::to_string(cooldown.count()) + "ms", - COLOR_DARKGREEN - ); - } -} - - - -void ControllerWithScheduler::issue_full_controller_state( - const Cancellable* cancellable, - Milliseconds hold, - Button button, - DpadPosition position, - uint8_t left_x, uint8_t left_y, - uint8_t right_x, uint8_t right_y -){ - std::lock_guard lg0(m_issue_lock); - std::lock_guard lg1(m_state_lock); - if (cancellable){ - cancellable->throw_if_cancelled(); - } - - for (size_t c = 0; c < TOTAL_BUTTONS; c++){ - ButtonFlagType mask = (ButtonFlagType)1 << c; - if (button & mask){ - this->issue_wait_for_resource(cancellable, m_buttons[c]); - } - } - this->issue_wait_for_resource(cancellable, m_dpad); - this->issue_wait_for_resource(cancellable, m_left_joystick); - this->issue_wait_for_resource(cancellable, m_right_joystick); - - m_dpad.position = position; - m_left_joystick.x = left_x; - m_left_joystick.y = left_y; - m_right_joystick.x = right_x; - m_right_joystick.y = right_y; - - for (size_t c = 0; c < TOTAL_BUTTONS; c++){ - ButtonFlagType mask = (ButtonFlagType)1 << c; - if (button & mask){ - this->issue_to_resource( - cancellable, m_buttons[c], - WallDuration::zero(), hold, WallDuration::zero() - ); - } - } - this->issue_to_resource( - cancellable, m_dpad, - WallDuration::zero(), hold, WallDuration::zero() - ); - this->issue_to_resource( - cancellable, m_left_joystick, - WallDuration::zero(), hold, WallDuration::zero() - ); - this->issue_to_resource( - cancellable, m_right_joystick, - hold, hold, WallDuration::zero() - ); - - if (m_logging_throttler){ - m_logger.log( - "issue_controller_state(): (" + button_to_string(button) + - "), dpad(" + dpad_to_string(position) + - "), LJ(" + std::to_string(left_x) + "," + std::to_string(left_y) + - "), RJ(" + std::to_string(right_x) + "," + std::to_string(right_y) + - "), hold = " + std::to_string(hold.count()) + "ms", - COLOR_DARKGREEN - ); - } -} - - -void ControllerWithScheduler::issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button -){ - if (cancellable){ - cancellable->throw_if_cancelled(); - } - ThrottleScope scope(m_logging_throttler); - bool log = true; - while (duration > Milliseconds::zero()){ - issue_buttons(cancellable, 8*8ms, 5*8ms, 3*8ms, button); - - // We never log before the first issue to avoid delaying the critical path. - // But we do want to log before the mash spam. So we log after the first - // issue, but before the second. - if (log && scope){ - m_logger.log( - "issue_mash_button(): " + button_to_string(button) + - ", duration = " + std::to_string(duration.count()) + "ms", - COLOR_DARKGREEN - ); - } - log = false; - - duration = duration >= 8*8ms - ? duration - 8*8ms - : Milliseconds::zero(); - } -} -void ControllerWithScheduler::issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button0, Button button1 -){ - if (cancellable){ - cancellable->throw_if_cancelled(); - } - ThrottleScope scope(m_logging_throttler); - bool log = true; - while (duration > Milliseconds::zero()){ - issue_buttons(cancellable, 4*8ms, 5*8ms, 3*8ms, button0); - issue_buttons(cancellable, 4*8ms, 5*8ms, 3*8ms, button1); - - // We never log before the first issue to avoid delaying the critical path. - // But we do want to log before the mash spam. So we log after the first - // issue, but before the second. - if (log && scope){ - m_logger.log( - "issue_mash_button(): (" + button_to_string(button0) + - "), (" + button_to_string(button1) + - "), duration = " + std::to_string(duration.count()) + "ms", - COLOR_DARKGREEN - ); - } - log = false; - - duration -= std::min(8*8ms, duration); - } -} -void ControllerWithScheduler::issue_mash_AZs( - const Cancellable* cancellable, - Milliseconds duration -){ - if (cancellable){ - cancellable->throw_if_cancelled(); - } - ThrottleScope scope(m_logging_throttler); - bool log = true; - while (true){ - if (duration <= Milliseconds::zero()){ - break; - } - issue_buttons(cancellable, 3*8ms, 6*8ms, 3*8ms, BUTTON_A); - - // We never log before the first issue to avoid delaying the critical path. - // But we do want to log before the mash spam. So we log after the first - // issue, but before the second. - if (log && scope){ - m_logger.log( - "issue_mash_AZs(): duration = " + std::to_string(duration.count()) + "ms", - COLOR_DARKGREEN - ); - } - log = false; - - duration -= std::min(3*8ms, duration); - if (duration <= Milliseconds::zero()){ - break; - } - issue_buttons(cancellable, 3*8ms, 6*8ms, 3*8ms, BUTTON_ZL); - duration -= std::min(3*8ms, duration); - - if (duration <= Milliseconds::zero()){ - break; - } - issue_buttons(cancellable, 3*8ms, 6*8ms, 3*8ms, BUTTON_ZR); - duration -= std::min(3*8ms, duration); - } -} -void ControllerWithScheduler::issue_system_scroll( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition direction // Diagonals not allowed. -){ - if (cancellable){ - cancellable->throw_if_cancelled(); - } - - ThrottleScope scope(m_logging_throttler); - - WallClock dpad = m_dpad.free_time(); - WallClock left_joystick = m_left_joystick.free_time(); - WallClock right_joystick = m_right_joystick.free_time(); - - do{ - if (dpad <= left_joystick && dpad <= right_joystick){ - issue_dpad( - cancellable, - delay, hold, cooldown, - direction - ); - break; - } - - uint8_t x = 128; - uint8_t y = 128; - switch (direction){ - case DPAD_NONE: - x = 128; - y = 128; - break; - case DPAD_UP: - x = 128; - y = 0; - break; - case DPAD_RIGHT: - x = 255; - y = 128; - break; - case DPAD_DOWN: - x = 128; - y = 255; - break; - case DPAD_LEFT: - x = 0; - y = 128; - break; - - // These diagonal ones probably don't work. - case DPAD_UP_RIGHT: - x = 255; - y = 0; - break; - case DPAD_DOWN_RIGHT: - x = 255; - y = 255; - break; - case DPAD_DOWN_LEFT: - x = 0; - y = 255; - break; - case DPAD_UP_LEFT: - x = 0; - y = 0; - break; - } - - if (left_joystick <= dpad && left_joystick <= right_joystick){ - issue_left_joystick(cancellable, delay, hold, cooldown, x, y); - }else{ - issue_right_joystick(cancellable, delay, hold, cooldown, x, y); - } - }while (false); - - if (scope){ - m_logger.log( - "issue_system_scroll(): " + dpad_to_string(direction) + - ", delay = " + std::to_string(delay.count()) + "ms" + - ", hold = " + std::to_string(hold.count()) + "ms" + - ", cooldown = " + std::to_string(cooldown.count()) + "ms", - COLOR_DARKGREEN - ); - } - -} - - - - - -} -} +/* Nintendo Switch Controller (With Scheduler) + * + * From: https://github.com/PokemonAutomation/ + * + * This implements most of the SwitchController API using only the controller + * state function. It uses SuperscalarScheduler to do this. + * + */ + +#include "NintendoSwitch_ControllerWithScheduler.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +using namespace std::chrono_literals; + + + + +ControllerWithScheduler::ControllerWithScheduler(Logger& logger) + : SuperscalarScheduler( + logger, Milliseconds(4), + make_resource_list() + ) + , m_logger(logger) +// , m_logging_suppress(0) +{} + + + +void ControllerWithScheduler::issue_barrier(const Cancellable* cancellable){ + std::lock_guard lg0(m_issue_lock); + std::lock_guard lg1(m_state_lock); + this->issue_wait_for_all(cancellable); + if (m_logging_throttler){ + m_logger.log("issue_barrier()", COLOR_DARKGREEN); + } +} +void ControllerWithScheduler::issue_nop(const Cancellable* cancellable, Milliseconds duration){ + std::lock_guard lg0(m_issue_lock); + std::lock_guard lg1(m_state_lock); + if (cancellable){ + cancellable->throw_if_cancelled(); + } + this->SuperscalarScheduler::issue_nop(cancellable, WallDuration(duration)); + if (m_logging_throttler){ + m_logger.log( + "issue_nop(): duration = " + std::to_string(duration.count()) + "ms", + COLOR_DARKGREEN + ); + } +} +void ControllerWithScheduler::issue_buttons( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + Button button +){ + std::lock_guard lg0(m_issue_lock); + std::lock_guard lg1(m_state_lock); + if (cancellable){ + cancellable->throw_if_cancelled(); + } + + for (size_t c = 0; c < TOTAL_BUTTONS; c++){ + ButtonFlagType mask = (ButtonFlagType)1 << c; + if (button & mask){ + this->issue_wait_for_resource(cancellable, m_buttons[c]); + } + } + for (size_t c = 0; c < TOTAL_BUTTONS; c++){ + ButtonFlagType mask = (ButtonFlagType)1 << c; + if (button & mask){ + this->issue_to_resource( + cancellable, m_buttons[c], + WallDuration::zero(), hold, cooldown + ); + } + } + this->SuperscalarScheduler::issue_nop(cancellable, delay); + + if (m_logging_throttler){ + m_logger.log( + "issue_buttons(): " + button_to_string(button) + + ", delay = " + std::to_string(delay.count()) + "ms" + + ", hold = " + std::to_string(hold.count()) + "ms" + + ", cooldown = " + std::to_string(cooldown.count()) + "ms", + COLOR_DARKGREEN + ); + } +} +void ControllerWithScheduler::issue_dpad( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition position +){ + std::lock_guard lg0(m_issue_lock); + std::lock_guard lg1(m_state_lock); + if (cancellable){ + cancellable->throw_if_cancelled(); + } + + this->issue_wait_for_resource(cancellable, m_dpad); + m_dpad.position = position; + this->issue_to_resource(cancellable, m_dpad, delay, hold, cooldown); + + if (m_logging_throttler){ + m_logger.log( + "issue_dpad(): " + dpad_to_string(position) + + ", delay = " + std::to_string(delay.count()) + "ms" + + ", hold = " + std::to_string(hold.count()) + "ms" + + ", cooldown = " + std::to_string(cooldown.count()) + "ms", + COLOR_DARKGREEN + ); + } +} +void ControllerWithScheduler::issue_left_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y +){ + std::lock_guard lg0(m_issue_lock); + std::lock_guard lg1(m_state_lock); + + if (cancellable){ + cancellable->throw_if_cancelled(); + } + + this->issue_wait_for_resource(cancellable, m_left_joystick); + m_left_joystick.x = x; + m_left_joystick.y = y; + this->issue_to_resource(cancellable, m_left_joystick, delay, hold, cooldown); + + if (m_logging_throttler){ + m_logger.log( + "issue_left_joystick(): (" + std::to_string(x) + "," + std::to_string(y) + ")" + + ", delay = " + std::to_string(delay.count()) + "ms" + + ", hold = " + std::to_string(hold.count()) + "ms" + + ", cooldown = " + std::to_string(cooldown.count()) + "ms", + COLOR_DARKGREEN + ); + } +} +void ControllerWithScheduler::issue_right_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y +){ + std::lock_guard lg0(m_issue_lock); + std::lock_guard lg1(m_state_lock); + if (cancellable){ + cancellable->throw_if_cancelled(); + } + + this->issue_wait_for_resource(cancellable, m_right_joystick); + m_right_joystick.x = x; + m_right_joystick.y = y; + this->issue_to_resource(cancellable, m_right_joystick, delay, hold, cooldown); + + if (m_logging_throttler){ + m_logger.log( + "issue_right_joystick(): (" + std::to_string(x) + "," + std::to_string(y) + ")" + + ", delay = " + std::to_string(delay.count()) + "ms" + + ", hold = " + std::to_string(hold.count()) + "ms" + + ", cooldown = " + std::to_string(cooldown.count()) + "ms", + COLOR_DARKGREEN + ); + } +} + + + +void ControllerWithScheduler::issue_gyro( + const Cancellable* cancellable, + SwitchGyro& gyro, const char* name, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value +){ + std::lock_guard lg0(m_issue_lock); + std::lock_guard lg1(m_state_lock); + if (cancellable){ + cancellable->throw_if_cancelled(); + } + + this->issue_wait_for_resource(cancellable, gyro); + gyro.value = value; + this->issue_to_resource(cancellable, gyro, delay, hold, cooldown); + + if (m_logging_throttler){ + m_logger.log( + std::string(name) + "(): (" + std::to_string(value) + ")" + + ", delay = " + std::to_string(delay.count()) + "ms" + + ", hold = " + std::to_string(hold.count()) + "ms" + + ", cooldown = " + std::to_string(cooldown.count()) + "ms", + COLOR_DARKGREEN + ); + } +} + + + +void ControllerWithScheduler::issue_full_controller_state( + const Cancellable* cancellable, + Milliseconds hold, + Button button, + DpadPosition position, + uint8_t left_x, uint8_t left_y, + uint8_t right_x, uint8_t right_y +){ + std::lock_guard lg0(m_issue_lock); + std::lock_guard lg1(m_state_lock); + if (cancellable){ + cancellable->throw_if_cancelled(); + } + + for (size_t c = 0; c < TOTAL_BUTTONS; c++){ + ButtonFlagType mask = (ButtonFlagType)1 << c; + if (button & mask){ + this->issue_wait_for_resource(cancellable, m_buttons[c]); + } + } + this->issue_wait_for_resource(cancellable, m_dpad); + this->issue_wait_for_resource(cancellable, m_left_joystick); + this->issue_wait_for_resource(cancellable, m_right_joystick); + + m_dpad.position = position; + m_left_joystick.x = left_x; + m_left_joystick.y = left_y; + m_right_joystick.x = right_x; + m_right_joystick.y = right_y; + + for (size_t c = 0; c < TOTAL_BUTTONS; c++){ + ButtonFlagType mask = (ButtonFlagType)1 << c; + if (button & mask){ + this->issue_to_resource( + cancellable, m_buttons[c], + WallDuration::zero(), hold, WallDuration::zero() + ); + } + } + this->issue_to_resource( + cancellable, m_dpad, + WallDuration::zero(), hold, WallDuration::zero() + ); + this->issue_to_resource( + cancellable, m_left_joystick, + WallDuration::zero(), hold, WallDuration::zero() + ); + this->issue_to_resource( + cancellable, m_right_joystick, + hold, hold, WallDuration::zero() + ); + + if (m_logging_throttler){ + m_logger.log( + "issue_controller_state(): (" + button_to_string(button) + + "), dpad(" + dpad_to_string(position) + + "), LJ(" + std::to_string(left_x) + "," + std::to_string(left_y) + + "), RJ(" + std::to_string(right_x) + "," + std::to_string(right_y) + + "), hold = " + std::to_string(hold.count()) + "ms", + COLOR_DARKGREEN + ); + } +} + + +void ControllerWithScheduler::issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button +){ + if (cancellable){ + cancellable->throw_if_cancelled(); + } + ThrottleScope scope(m_logging_throttler); + bool log = true; + while (duration > Milliseconds::zero()){ + issue_buttons(cancellable, 8*8ms, 5*8ms, 3*8ms, button); + + // We never log before the first issue to avoid delaying the critical path. + // But we do want to log before the mash spam. So we log after the first + // issue, but before the second. + if (log && scope){ + m_logger.log( + "issue_mash_button(): " + button_to_string(button) + + ", duration = " + std::to_string(duration.count()) + "ms", + COLOR_DARKGREEN + ); + } + log = false; + + duration = duration >= 8*8ms + ? duration - 8*8ms + : Milliseconds::zero(); + } +} +void ControllerWithScheduler::issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button0, Button button1 +){ + if (cancellable){ + cancellable->throw_if_cancelled(); + } + ThrottleScope scope(m_logging_throttler); + bool log = true; + while (duration > Milliseconds::zero()){ + issue_buttons(cancellable, 4*8ms, 5*8ms, 3*8ms, button0); + issue_buttons(cancellable, 4*8ms, 5*8ms, 3*8ms, button1); + + // We never log before the first issue to avoid delaying the critical path. + // But we do want to log before the mash spam. So we log after the first + // issue, but before the second. + if (log && scope){ + m_logger.log( + "issue_mash_button(): (" + button_to_string(button0) + + "), (" + button_to_string(button1) + + "), duration = " + std::to_string(duration.count()) + "ms", + COLOR_DARKGREEN + ); + } + log = false; + + duration -= std::min(8*8ms, duration); + } +} +void ControllerWithScheduler::issue_mash_AZs( + const Cancellable* cancellable, + Milliseconds duration +){ + if (cancellable){ + cancellable->throw_if_cancelled(); + } + ThrottleScope scope(m_logging_throttler); + bool log = true; + while (true){ + if (duration <= Milliseconds::zero()){ + break; + } + issue_buttons(cancellable, 3*8ms, 6*8ms, 3*8ms, BUTTON_A); + + // We never log before the first issue to avoid delaying the critical path. + // But we do want to log before the mash spam. So we log after the first + // issue, but before the second. + if (log && scope){ + m_logger.log( + "issue_mash_AZs(): duration = " + std::to_string(duration.count()) + "ms", + COLOR_DARKGREEN + ); + } + log = false; + + duration -= std::min(3*8ms, duration); + if (duration <= Milliseconds::zero()){ + break; + } + issue_buttons(cancellable, 3*8ms, 6*8ms, 3*8ms, BUTTON_ZL); + duration -= std::min(3*8ms, duration); + + if (duration <= Milliseconds::zero()){ + break; + } + issue_buttons(cancellable, 3*8ms, 6*8ms, 3*8ms, BUTTON_ZR); + duration -= std::min(3*8ms, duration); + } +} +void ControllerWithScheduler::issue_system_scroll( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition direction // Diagonals not allowed. +){ + if (cancellable){ + cancellable->throw_if_cancelled(); + } + + ThrottleScope scope(m_logging_throttler); + + WallClock dpad = m_dpad.free_time(); + WallClock left_joystick = m_left_joystick.free_time(); + WallClock right_joystick = m_right_joystick.free_time(); + + do{ + if (dpad <= left_joystick && dpad <= right_joystick){ + issue_dpad( + cancellable, + delay, hold, cooldown, + direction + ); + break; + } + + uint8_t x = 128; + uint8_t y = 128; + switch (direction){ + case DPAD_NONE: + x = 128; + y = 128; + break; + case DPAD_UP: + x = 128; + y = 0; + break; + case DPAD_RIGHT: + x = 255; + y = 128; + break; + case DPAD_DOWN: + x = 128; + y = 255; + break; + case DPAD_LEFT: + x = 0; + y = 128; + break; + + // These diagonal ones probably don't work. + case DPAD_UP_RIGHT: + x = 255; + y = 0; + break; + case DPAD_DOWN_RIGHT: + x = 255; + y = 255; + break; + case DPAD_DOWN_LEFT: + x = 0; + y = 255; + break; + case DPAD_UP_LEFT: + x = 0; + y = 0; + break; + } + + if (left_joystick <= dpad && left_joystick <= right_joystick){ + issue_left_joystick(cancellable, delay, hold, cooldown, x, y); + }else{ + issue_right_joystick(cancellable, delay, hold, cooldown, x, y); + } + }while (false); + + if (scope){ + m_logger.log( + "issue_system_scroll(): " + dpad_to_string(direction) + + ", delay = " + std::to_string(delay.count()) + "ms" + + ", hold = " + std::to_string(hold.count()) + "ms" + + ", cooldown = " + std::to_string(cooldown.count()) + "ms", + COLOR_DARKGREEN + ); + } + +} + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.h b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.h index 59a6f2860a..2121239917 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.h @@ -1,280 +1,280 @@ -/* Nintendo Switch Controller (With Scheduler) - * - * From: https://github.com/PokemonAutomation/ - * - * This implements most of the SwitchController API using only the controller - * state function. It uses SuperscalarScheduler to do this. - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_ControllerWithScheduler_H -#define PokemonAutomation_NintendoSwitch_ControllerWithScheduler_H - -#include -#include "Common/Cpp/RecursiveThrottler.h" -#include "Controllers/SuperscalarScheduler.h" -#include "NintendoSwitch_ControllerState.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -struct SwitchButton_Dpad : public ExecutionResource{ - DpadPosition position; -}; -struct SwitchButton_Joystick : public ExecutionResource{ - uint8_t x; - uint8_t y; -}; -struct SwitchGyro : public ExecutionResource{ - int16_t value; -}; -struct ControllerSchedulerState{ - ExecutionResource m_buttons[TOTAL_BUTTONS]; - SwitchButton_Dpad m_dpad; - SwitchButton_Joystick m_left_joystick; - SwitchButton_Joystick m_right_joystick; - - SwitchGyro m_accel_x; - SwitchGyro m_accel_y; - SwitchGyro m_accel_z; - SwitchGyro m_rotation_x; - SwitchGyro m_rotation_y; - SwitchGyro m_rotation_z; - - bool is_active() const{ - for (size_t c = 0; c < TOTAL_BUTTONS; c++){ - if (m_buttons[c].is_busy()){ - return true; - } - } - if (m_dpad.is_busy()) return true; - if (m_left_joystick.is_busy()) return true; - if (m_right_joystick.is_busy()) return true; - - if (m_accel_x.is_busy()) return true; - if (m_accel_y.is_busy()) return true; - if (m_accel_z.is_busy()) return true; - if (m_rotation_x.is_busy()) return true; - if (m_rotation_y.is_busy()) return true; - if (m_rotation_z.is_busy()) return true; - - return false; - } - - std::vector make_resource_list(){ - std::vector ret; - for (size_t c = 0; c < TOTAL_BUTTONS; c++){ - ret.emplace_back(m_buttons + c); - } - ret.emplace_back(&m_dpad); - ret.emplace_back(&m_left_joystick); - ret.emplace_back(&m_right_joystick); - ret.emplace_back(&m_accel_x); - ret.emplace_back(&m_accel_y); - ret.emplace_back(&m_accel_z); - ret.emplace_back(&m_rotation_x); - ret.emplace_back(&m_rotation_y); - ret.emplace_back(&m_rotation_z); - return ret; - } -}; - - -struct SplitDpad{ - bool up = false; - bool right = false; - bool down = false; - bool left = false; -}; -inline SplitDpad convert_unified_to_split_dpad(DpadPosition dpad){ - switch (dpad){ - case DpadPosition::DPAD_UP: - return {true, false, false, false}; - case DpadPosition::DPAD_UP_RIGHT: - return {true, true, false, false}; - case DpadPosition::DPAD_RIGHT: - return {false, true, false, false}; - case DpadPosition::DPAD_DOWN_RIGHT: - return {false, true, true, false}; - case DpadPosition::DPAD_DOWN: - return {false, false, true, false}; - case DpadPosition::DPAD_DOWN_LEFT: - return {false, false, true, true}; - case DpadPosition::DPAD_LEFT: - return {false, false, false, true}; - case DpadPosition::DPAD_UP_LEFT: - return {true, false, false, true}; - default: - return {false, false, false, false}; - } -} - - - - - -class ControllerWithScheduler : - protected ControllerSchedulerState, - protected SuperscalarScheduler -{ -public: - ControllerWithScheduler(Logger& logger); - - RecursiveThrottler& logging_throttler(){ - return m_logging_throttler; - } - - -public: - // Superscalar Commands (the "ssf" framework) - - void issue_barrier(const Cancellable* cancellable); - void issue_nop(const Cancellable* cancellable, Milliseconds duration); - void issue_buttons( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - Button button - ); - void issue_dpad( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition position - ); - void issue_left_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y - ); - void issue_right_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y - ); - - void issue_gyro( - const Cancellable* cancellable, - SwitchGyro& gyro, const char* name, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ); - void issue_gyro_accel_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ){ - issue_gyro(cancellable, m_accel_x, "issue_gyro_accel_x", delay, hold, cooldown, value); - } - void issue_gyro_accel_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ){ - issue_gyro(cancellable, m_accel_y, "issue_gyro_accel_y", delay, hold, cooldown, value); - } - void issue_gyro_accel_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ){ - issue_gyro(cancellable, m_accel_z, "issue_gyro_accel_z", delay, hold, cooldown, value); - } - void issue_gyro_rotate_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ){ - issue_gyro(cancellable, m_rotation_x, "issue_gyro_rotate_x", delay, hold, cooldown, value); - } - void issue_gyro_rotate_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ){ - issue_gyro(cancellable, m_rotation_y, "issue_gyro_rotate_y", delay, hold, cooldown, value); - } - void issue_gyro_rotate_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ){ - issue_gyro(cancellable, m_rotation_z, "issue_gyro_rotate_z", delay, hold, cooldown, value); - } - - void issue_full_controller_state( - const Cancellable* cancellable, - Milliseconds hold, - Button button, - DpadPosition position, - uint8_t left_x, uint8_t left_y, - uint8_t right_x, uint8_t right_y - ); - - -public: - // High speed RPCs. - - void issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button - ); - void issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button0, Button button1 - ); - void issue_mash_AZs( - const Cancellable* cancellable, - Milliseconds duration - ); - void issue_system_scroll( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition direction // Diagonals not allowed. - ); - - -protected: -#if 0 - class LoggingSuppressScope{ - public: - LoggingSuppressScope(std::atomic& counter) - : m_counter(counter) - { - m_counter++; - } - ~LoggingSuppressScope(){ - m_counter--; - } - private: - std::atomic& m_counter; - }; -#endif - -// virtual void push_state(const Cancellable* cancellable, WallDuration duration) override; - - -protected: - Logger& m_logger; -// std::atomic m_logging_suppress; - RecursiveThrottler m_logging_throttler; - - // If you need both of these locks, always acquire "m_issue_lock" first. - - // This lock makes sure that only one command is issued at a time. It can - // be held for long periods of time if the command queue is full. - std::mutex m_issue_lock; - - // This lock protects the state/fields of this class and subclasses. - // This lock is never held for a long time. - std::mutex m_state_lock; -}; - - - - -} -} -#endif +/* Nintendo Switch Controller (With Scheduler) + * + * From: https://github.com/PokemonAutomation/ + * + * This implements most of the SwitchController API using only the controller + * state function. It uses SuperscalarScheduler to do this. + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_ControllerWithScheduler_H +#define PokemonAutomation_NintendoSwitch_ControllerWithScheduler_H + +#include +#include "Common/Cpp/RecursiveThrottler.h" +#include "Controllers/SuperscalarScheduler.h" +#include "NintendoSwitch_ControllerState.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +struct SwitchButton_Dpad : public ExecutionResource{ + DpadPosition position; +}; +struct SwitchButton_Joystick : public ExecutionResource{ + uint8_t x; + uint8_t y; +}; +struct SwitchGyro : public ExecutionResource{ + int16_t value; +}; +struct ControllerSchedulerState{ + ExecutionResource m_buttons[TOTAL_BUTTONS]; + SwitchButton_Dpad m_dpad; + SwitchButton_Joystick m_left_joystick; + SwitchButton_Joystick m_right_joystick; + + SwitchGyro m_accel_x; + SwitchGyro m_accel_y; + SwitchGyro m_accel_z; + SwitchGyro m_rotation_x; + SwitchGyro m_rotation_y; + SwitchGyro m_rotation_z; + + bool is_active() const{ + for (size_t c = 0; c < TOTAL_BUTTONS; c++){ + if (m_buttons[c].is_busy()){ + return true; + } + } + if (m_dpad.is_busy()) return true; + if (m_left_joystick.is_busy()) return true; + if (m_right_joystick.is_busy()) return true; + + if (m_accel_x.is_busy()) return true; + if (m_accel_y.is_busy()) return true; + if (m_accel_z.is_busy()) return true; + if (m_rotation_x.is_busy()) return true; + if (m_rotation_y.is_busy()) return true; + if (m_rotation_z.is_busy()) return true; + + return false; + } + + std::vector make_resource_list(){ + std::vector ret; + for (size_t c = 0; c < TOTAL_BUTTONS; c++){ + ret.emplace_back(m_buttons + c); + } + ret.emplace_back(&m_dpad); + ret.emplace_back(&m_left_joystick); + ret.emplace_back(&m_right_joystick); + ret.emplace_back(&m_accel_x); + ret.emplace_back(&m_accel_y); + ret.emplace_back(&m_accel_z); + ret.emplace_back(&m_rotation_x); + ret.emplace_back(&m_rotation_y); + ret.emplace_back(&m_rotation_z); + return ret; + } +}; + + +struct SplitDpad{ + bool up = false; + bool right = false; + bool down = false; + bool left = false; +}; +inline SplitDpad convert_unified_to_split_dpad(DpadPosition dpad){ + switch (dpad){ + case DpadPosition::DPAD_UP: + return {true, false, false, false}; + case DpadPosition::DPAD_UP_RIGHT: + return {true, true, false, false}; + case DpadPosition::DPAD_RIGHT: + return {false, true, false, false}; + case DpadPosition::DPAD_DOWN_RIGHT: + return {false, true, true, false}; + case DpadPosition::DPAD_DOWN: + return {false, false, true, false}; + case DpadPosition::DPAD_DOWN_LEFT: + return {false, false, true, true}; + case DpadPosition::DPAD_LEFT: + return {false, false, false, true}; + case DpadPosition::DPAD_UP_LEFT: + return {true, false, false, true}; + default: + return {false, false, false, false}; + } +} + + + + + +class ControllerWithScheduler : + protected ControllerSchedulerState, + protected SuperscalarScheduler +{ +public: + ControllerWithScheduler(Logger& logger); + + RecursiveThrottler& logging_throttler(){ + return m_logging_throttler; + } + + +public: + // Superscalar Commands (the "ssf" framework) + + void issue_barrier(const Cancellable* cancellable); + void issue_nop(const Cancellable* cancellable, Milliseconds duration); + void issue_buttons( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + Button button + ); + void issue_dpad( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition position + ); + void issue_left_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y + ); + void issue_right_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y + ); + + void issue_gyro( + const Cancellable* cancellable, + SwitchGyro& gyro, const char* name, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ); + void issue_gyro_accel_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ){ + issue_gyro(cancellable, m_accel_x, "issue_gyro_accel_x", delay, hold, cooldown, value); + } + void issue_gyro_accel_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ){ + issue_gyro(cancellable, m_accel_y, "issue_gyro_accel_y", delay, hold, cooldown, value); + } + void issue_gyro_accel_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ){ + issue_gyro(cancellable, m_accel_z, "issue_gyro_accel_z", delay, hold, cooldown, value); + } + void issue_gyro_rotate_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ){ + issue_gyro(cancellable, m_rotation_x, "issue_gyro_rotate_x", delay, hold, cooldown, value); + } + void issue_gyro_rotate_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ){ + issue_gyro(cancellable, m_rotation_y, "issue_gyro_rotate_y", delay, hold, cooldown, value); + } + void issue_gyro_rotate_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ){ + issue_gyro(cancellable, m_rotation_z, "issue_gyro_rotate_z", delay, hold, cooldown, value); + } + + void issue_full_controller_state( + const Cancellable* cancellable, + Milliseconds hold, + Button button, + DpadPosition position, + uint8_t left_x, uint8_t left_y, + uint8_t right_x, uint8_t right_y + ); + + +public: + // High speed RPCs. + + void issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button + ); + void issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button0, Button button1 + ); + void issue_mash_AZs( + const Cancellable* cancellable, + Milliseconds duration + ); + void issue_system_scroll( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition direction // Diagonals not allowed. + ); + + +protected: +#if 0 + class LoggingSuppressScope{ + public: + LoggingSuppressScope(std::atomic& counter) + : m_counter(counter) + { + m_counter++; + } + ~LoggingSuppressScope(){ + m_counter--; + } + private: + std::atomic& m_counter; + }; +#endif + +// virtual void push_state(const Cancellable* cancellable, WallDuration duration) override; + + +protected: + Logger& m_logger; +// std::atomic m_logging_suppress; + RecursiveThrottler m_logging_throttler; + + // If you need both of these locks, always acquire "m_issue_lock" first. + + // This lock makes sure that only one command is issued at a time. It can + // be held for long periods of time if the command queue is full. + std::mutex m_issue_lock; + + // This lock protects the state/fields of this class and subclasses. + // This lock is never held for a long time. + std::mutex m_state_lock; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_Joycon.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_Joycon.cpp index 829494e00c..d81fc96cfd 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_Joycon.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_Joycon.cpp @@ -1,111 +1,111 @@ -/* Nintendo Switch Joycon - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "CommonTools/Async/InterruptableCommands.tpp" -#include "CommonTools/Async/SuperControlSession.tpp" -#include "Controllers/ControllerTypes.h" -#include "Controllers/KeyboardInput/KeyboardInput.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch_VirtualControllerState.h" -#include "NintendoSwitch_Joycon.h" - -namespace PokemonAutomation{ - -// Instantiate some template helper classes. -template class AsyncCommandSession; -template class SuperControlSession; - -namespace NintendoSwitch{ - -using namespace std::chrono_literals; - - - -class JoyconController::KeyboardManager final : - public PokemonAutomation::KeyboardManager -{ -public: - KeyboardManager(JoyconController& controller, ControllerType controller_type) - : PokemonAutomation::KeyboardManager(controller) - { - std::vector> mapping; - switch (controller_type){ - case ControllerType::NintendoSwitch_LeftJoycon: - mapping = ConsoleSettings::instance().KEYBOARD_MAPPINGS.LEFT_JOYCON.current_refs(); - break; - case ControllerType::NintendoSwitch_RightJoycon: - mapping = ConsoleSettings::instance().KEYBOARD_MAPPINGS.RIGHT_JOYCON.current_refs(); - break; - default:; - } - for (const auto& deltas : mapping){ - const JoyconKeyMapTableRow& row = static_cast(*deltas); - m_mapping[(Qt::Key)(uint32_t)row.key] += row.snapshot(); - } - start(); - } - ~KeyboardManager(){ - stop(); - } - virtual void send_state(const ControllerState& state) override{ - const JoyconState& switch_state = static_cast(state); -#if 0 - m_controller->logger().log( - "VirtualController: (" + button_to_string(switch_state.buttons) + - "), LJ(" + std::to_string(switch_state.joystick_x) + "," + std::to_string(switch_state.joystick_y) + - ")", - COLOR_DARKGREEN - ); -#endif - WriteSpinLock lg(m_lock); - if (m_controller == nullptr){ - return; - } - Milliseconds ticksize = m_controller->ticksize(); - static_cast(m_controller)->issue_full_controller_state( - nullptr, - switch_state.buttons, - switch_state.joystick_x, - switch_state.joystick_y, - ticksize == Milliseconds::zero() ? 2000ms : ticksize * 255 - ); - } -}; - - - -JoyconController::JoyconController(ControllerType controller_type) - : m_keyboard_manager(CONSTRUCT_TOKEN, *this, controller_type) -{ - -} -JoyconController::~JoyconController(){ - -} -void JoyconController::stop() noexcept{ - m_keyboard_manager->stop(); -} - - -void JoyconController::keyboard_release_all(){ - m_keyboard_manager->clear_state(); -} -void JoyconController::keyboard_press(const QKeyEvent& event){ - m_keyboard_manager->on_key_press(event); -} -void JoyconController::keyboard_release(const QKeyEvent& event){ - m_keyboard_manager->on_key_release(event); -} - - - - - - - -} -} +/* Nintendo Switch Joycon + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "CommonTools/Async/InterruptableCommands.tpp" +#include "CommonTools/Async/SuperControlSession.tpp" +#include "Controllers/ControllerTypes.h" +#include "Controllers/KeyboardInput/KeyboardInput.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch_VirtualControllerState.h" +#include "NintendoSwitch_Joycon.h" + +namespace PokemonAutomation{ + +// Instantiate some template helper classes. +template class AsyncCommandSession; +template class SuperControlSession; + +namespace NintendoSwitch{ + +using namespace std::chrono_literals; + + + +class JoyconController::KeyboardManager final : + public PokemonAutomation::KeyboardManager +{ +public: + KeyboardManager(Logger& logger, JoyconController& controller, ControllerType controller_type) + : PokemonAutomation::KeyboardManager(logger, controller) + { + std::vector> mapping; + switch (controller_type){ + case ControllerType::NintendoSwitch_LeftJoycon: + mapping = ConsoleSettings::instance().KEYBOARD_MAPPINGS.LEFT_JOYCON0.current_refs(); + break; + case ControllerType::NintendoSwitch_RightJoycon: + mapping = ConsoleSettings::instance().KEYBOARD_MAPPINGS.RIGHT_JOYCON0.current_refs(); + break; + default:; + } + for (const auto& deltas : mapping){ + const JoyconKeyMapTableRow& row = static_cast(*deltas); + m_mapping[(Qt::Key)(uint32_t)row.key] += row.snapshot(); + } + start(); + } + ~KeyboardManager(){ + stop(); + } + virtual void send_state(const ControllerState& state) override{ + const JoyconState& switch_state = static_cast(state); +#if 0 + m_controller->logger().log( + "VirtualController: (" + button_to_string(switch_state.buttons) + + "), LJ(" + std::to_string(switch_state.joystick_x) + "," + std::to_string(switch_state.joystick_y) + + ")", + COLOR_DARKGREEN + ); +#endif + WriteSpinLock lg(m_lock); + if (m_controller == nullptr){ + return; + } + Milliseconds ticksize = m_controller->ticksize(); + static_cast(m_controller)->issue_full_controller_state( + nullptr, + switch_state.buttons, + switch_state.joystick_x, + switch_state.joystick_y, + ticksize == Milliseconds::zero() ? 2000ms : ticksize * 255 + ); + } +}; + + + +JoyconController::JoyconController(Logger& logger, ControllerType controller_type) + : m_keyboard_manager(CONSTRUCT_TOKEN, logger, *this, controller_type) +{ + +} +JoyconController::~JoyconController(){ + +} +void JoyconController::stop() noexcept{ + m_keyboard_manager->stop(); +} + + +void JoyconController::keyboard_release_all(){ + m_keyboard_manager->clear_state(); +} +void JoyconController::keyboard_press(const QKeyEvent& event){ + m_keyboard_manager->on_key_press(event); +} +void JoyconController::keyboard_release(const QKeyEvent& event){ + m_keyboard_manager->on_key_release(event); +} + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_Joycon.h b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_Joycon.h index 50722c8bcf..7bbc1d2f89 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_Joycon.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_Joycon.h @@ -1,178 +1,178 @@ -/* Nintendo Switch Joycon - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_Joycon_H -#define PokemonAutomation_NintendoSwitch_Joycon_H - -#include "Common/Cpp/Containers/Pimpl.h" -#include "NintendoSwitch_ControllerState.h" -#include "Controllers/Controller.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class JoyconController; -using JoyconContext = ControllerContext; - - - -constexpr Button VALID_LEFT_JOYCON_BUTTONS = - BUTTON_DOWN | - BUTTON_UP | - BUTTON_RIGHT | - BUTTON_LEFT | - BUTTON_LEFT_SR | - BUTTON_LEFT_SL | - BUTTON_L | - BUTTON_ZL | - BUTTON_MINUS | - BUTTON_LCLICK | - BUTTON_CAPTURE; - -constexpr Button VALID_RIGHT_JOYCON_BUTTONS = - BUTTON_Y | - BUTTON_X | - BUTTON_B | - BUTTON_A | - BUTTON_RIGHT_SR | - BUTTON_RIGHT_SL | - BUTTON_R | - BUTTON_ZR | - BUTTON_PLUS | - BUTTON_RCLICK | - BUTTON_HOME; - - - -class JoyconController : public AbstractController{ -public: - using ContextType = JoyconContext; - - JoyconController(ControllerType controller_type); - virtual ~JoyconController(); - - // Must call before destruction begins. - void stop() noexcept; - - -public: - // Press all the buttons set in the bitfield simultaneously. - // This command will wait until all the selected buttons are ready to - // ensure that they are all dispatched simultaneously. - virtual void issue_buttons( - const Cancellable* cancellable, - Button button, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown - ) = 0; - - virtual void issue_joystick( - const Cancellable* cancellable, - uint8_t x, uint8_t y, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown - ) = 0; - - // Gyro: Accelerometer (experimental - API subject to change) - virtual void issue_gyro_accel_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) = 0; - virtual void issue_gyro_accel_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) = 0; - virtual void issue_gyro_accel_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) = 0; - virtual void issue_gyro_rotate_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) = 0; - virtual void issue_gyro_rotate_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) = 0; - virtual void issue_gyro_rotate_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) = 0; - - // - // Press all the following buttons/joysticks simultaneously for the - // specified duration. No wait is added at the end. Thus you can issue - // these back-to-back to simulate buttons being pressed and released - // concurrently with other buttons being held down the whole time. - // - // This command will wait until the controller is fully idle (including - // cooldowns) before it starts. This ensures that everything is issued - // simultaneously. In other words, there is an implied call to - // "issue_barrier()" before executing the state. - // - // The sole purpose of this function is for keyboard commands. - // For programs, it is easier to use the individual button/joystick - // functions above. - // - // If we need to support new Switch controller functionality - // (such as Joycon gyro or new stuff in Switch 2), we can simply add - // overloads to this and gate them behind features. - // - virtual void issue_full_controller_state( - const Cancellable* cancellable, - Button button, - uint8_t joystick_x, uint8_t joystick_y, - Milliseconds hold - ) = 0; - - -public: - // - // High speed Macros - // - // Be mindful when calling these mashing functions on a tick imprecise - // controller. You can guarantee that some (most) of them will be dropped. - // - // Even if you are on a tick-precise controller, it is not advised to call - // these if you are micromanaging with tick-level granularity. The exact - // timing characteristics and button selection is not specified and may be - // context and implementation-dependent. - // - - // Mash a button as quickly as possible. - virtual void issue_mash_button( - const Cancellable* cancellable, - Button button, Milliseconds duration - ) = 0; - - -public: - // Keyboard Input - - virtual void keyboard_release_all() override; - virtual void keyboard_press(const QKeyEvent& event) override; - virtual void keyboard_release(const QKeyEvent& event) override; - - -private: - class KeyboardManager; - Pimpl m_keyboard_manager; -}; - - - - - - - -} -} -#endif +/* Nintendo Switch Joycon + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_Joycon_H +#define PokemonAutomation_NintendoSwitch_Joycon_H + +#include "Common/Cpp/Containers/Pimpl.h" +#include "NintendoSwitch_ControllerState.h" +#include "Controllers/Controller.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class JoyconController; +using JoyconContext = ControllerContext; + + + +constexpr Button VALID_LEFT_JOYCON_BUTTONS = + BUTTON_DOWN | + BUTTON_UP | + BUTTON_RIGHT | + BUTTON_LEFT | + BUTTON_LEFT_SR | + BUTTON_LEFT_SL | + BUTTON_L | + BUTTON_ZL | + BUTTON_MINUS | + BUTTON_LCLICK | + BUTTON_CAPTURE; + +constexpr Button VALID_RIGHT_JOYCON_BUTTONS = + BUTTON_Y | + BUTTON_X | + BUTTON_B | + BUTTON_A | + BUTTON_RIGHT_SR | + BUTTON_RIGHT_SL | + BUTTON_R | + BUTTON_ZR | + BUTTON_PLUS | + BUTTON_RCLICK | + BUTTON_HOME; + + + +class JoyconController : public AbstractController{ +public: + using ContextType = JoyconContext; + + JoyconController(Logger& logger, ControllerType controller_type); + virtual ~JoyconController(); + + // Must call before destruction begins. + void stop() noexcept; + + +public: + // Press all the buttons set in the bitfield simultaneously. + // This command will wait until all the selected buttons are ready to + // ensure that they are all dispatched simultaneously. + virtual void issue_buttons( + const Cancellable* cancellable, + Button button, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown + ) = 0; + + virtual void issue_joystick( + const Cancellable* cancellable, + uint8_t x, uint8_t y, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown + ) = 0; + + // Gyro: Accelerometer (experimental - API subject to change) + virtual void issue_gyro_accel_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) = 0; + virtual void issue_gyro_accel_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) = 0; + virtual void issue_gyro_accel_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) = 0; + virtual void issue_gyro_rotate_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) = 0; + virtual void issue_gyro_rotate_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) = 0; + virtual void issue_gyro_rotate_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) = 0; + + // + // Press all the following buttons/joysticks simultaneously for the + // specified duration. No wait is added at the end. Thus you can issue + // these back-to-back to simulate buttons being pressed and released + // concurrently with other buttons being held down the whole time. + // + // This command will wait until the controller is fully idle (including + // cooldowns) before it starts. This ensures that everything is issued + // simultaneously. In other words, there is an implied call to + // "issue_barrier()" before executing the state. + // + // The sole purpose of this function is for keyboard commands. + // For programs, it is easier to use the individual button/joystick + // functions above. + // + // If we need to support new Switch controller functionality + // (such as Joycon gyro or new stuff in Switch 2), we can simply add + // overloads to this and gate them behind features. + // + virtual void issue_full_controller_state( + const Cancellable* cancellable, + Button button, + uint8_t joystick_x, uint8_t joystick_y, + Milliseconds hold + ) = 0; + + +public: + // + // High speed Macros + // + // Be mindful when calling these mashing functions on a tick imprecise + // controller. You can guarantee that some (most) of them will be dropped. + // + // Even if you are on a tick-precise controller, it is not advised to call + // these if you are micromanaging with tick-level granularity. The exact + // timing characteristics and button selection is not specified and may be + // context and implementation-dependent. + // + + // Mash a button as quickly as possible. + virtual void issue_mash_button( + const Cancellable* cancellable, + Button button, Milliseconds duration + ) = 0; + + +public: + // Keyboard Input + + virtual void keyboard_release_all() override; + virtual void keyboard_press(const QKeyEvent& event) override; + virtual void keyboard_release(const QKeyEvent& event) override; + + +private: + class KeyboardManager; + Pimpl m_keyboard_manager; +}; + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_KeyboardMapping.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_KeyboardMapping.cpp index f0c7a2e494..ed1ed6df2f 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_KeyboardMapping.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_KeyboardMapping.cpp @@ -1,503 +1,507 @@ -/* Nintendo Keyboard Mapping - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "NintendoSwitch_VirtualControllerState.h" -#include "NintendoSwitch_KeyboardMapping.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -ProControllerKeyMapTableRow::ProControllerKeyMapTableRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , label(false, LockMode::UNLOCK_WHILE_RUNNING, "", "") - , key(LockMode::UNLOCK_WHILE_RUNNING) - , buttons(LockMode::UNLOCK_WHILE_RUNNING, 0, 0, ((uint32_t)1 << TOTAL_BUTTONS) - 1) - , dpad_x(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) - , dpad_y(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) - , left_stick_x(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) - , left_stick_y(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) - , right_stick_x(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) - , right_stick_y(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) -{ - add_option(label, "Description"); - add_option(key, "Key"); - add_option(buttons, "Button Bit-Field"); - add_option(dpad_x, "Dpad x"); - add_option(dpad_y, "Dpad y"); - add_option(left_stick_x, "Left-Stick x"); - add_option(left_stick_y, "Left-Stick y"); - add_option(right_stick_x, "Right-Stick x"); - add_option(right_stick_y, "Right-Stick y"); - set_advanced_mode(static_cast(parent_table).advanced_mode()); -} -ProControllerKeyMapTableRow::ProControllerKeyMapTableRow( - EditableTableOption& parent_table, - bool advanced_mode, - std::string description, - Qt::Key key, - const ProControllerDeltas& deltas -) - : ProControllerKeyMapTableRow(parent_table) -{ - label.set(std::move(description)); - this->key.set(key); - buttons.set(deltas.buttons); - dpad_x.set(deltas.dpad_x); - dpad_y.set(deltas.dpad_y); - left_stick_x.set(deltas.left_x); - left_stick_y.set(deltas.left_y); - right_stick_x.set(deltas.right_x); - right_stick_y.set(deltas.right_y); - set_advanced_mode(advanced_mode); -} -std::unique_ptr ProControllerKeyMapTableRow::clone() const{ - std::unique_ptr ret(new ProControllerKeyMapTableRow(parent())); - ret->label.set(label); - ret->key.set((uint32_t)key); - ret->buttons.set(buttons); - ret->dpad_x.set(dpad_x); - ret->dpad_y.set(dpad_y); - ret->left_stick_x.set(left_stick_x); - ret->left_stick_y.set(left_stick_y); - ret->right_stick_x.set(right_stick_x); - ret->right_stick_y.set(right_stick_y); - ret->set_advanced_mode(m_advanced_mode.load(std::memory_order_relaxed)); - return ret; -} -ProControllerDeltas ProControllerKeyMapTableRow::snapshot() const{ - return { - .buttons = (Button)buttons.current_value(), - .dpad_x = dpad_x, - .dpad_y = dpad_y, - .left_x = left_stick_x, - .left_y = left_stick_y, - .right_x = right_stick_x, - .right_y = right_stick_y, - }; -} -void ProControllerKeyMapTableRow::set_advanced_mode(bool enabled){ - m_advanced_mode.store(enabled, std::memory_order_relaxed); - if (enabled){ - label.set_locked(false); - buttons.set_visibility(ConfigOptionState::ENABLED); - dpad_x.set_visibility(ConfigOptionState::ENABLED); - dpad_y.set_visibility(ConfigOptionState::ENABLED); - left_stick_x.set_visibility(ConfigOptionState::ENABLED); - left_stick_y.set_visibility(ConfigOptionState::ENABLED); - right_stick_x.set_visibility(ConfigOptionState::ENABLED); - right_stick_y.set_visibility(ConfigOptionState::ENABLED); - }else{ - label.set_locked(true); - buttons.set_visibility(ConfigOptionState::DISABLED); - dpad_x.set_visibility(ConfigOptionState::DISABLED); - dpad_y.set_visibility(ConfigOptionState::DISABLED); - left_stick_x.set_visibility(ConfigOptionState::DISABLED); - left_stick_y.set_visibility(ConfigOptionState::DISABLED); - right_stick_x.set_visibility(ConfigOptionState::DISABLED); - right_stick_y.set_visibility(ConfigOptionState::DISABLED); - } -} - - - - - -ProControllerKeyboardMappingTable::ProControllerKeyboardMappingTable() - : EditableTableOption_t( - "Pro Controller:", - LockMode::UNLOCK_WHILE_RUNNING, - true, - make_defaults() - ) - , m_advanced_mode(false) -{} -std::vector ProControllerKeyboardMappingTable::make_header() const{ - return std::vector{ - "Description", - "Key", - "Button Bit-Field", - "Dpad x", - "Dpad y", - "Left-Stick x", - "Left-Stick y", - "Right-Stick x", - "Right-Stick y", - }; -} -void ProControllerKeyboardMappingTable::set_advanced_mode(bool enabled){ - m_advanced_mode.store(enabled, std::memory_order_relaxed); - run_on_all_rows([enabled](ProControllerKeyMapTableRow& row){ - row.set_advanced_mode(enabled); - return false; - }); -} - - -std::unique_ptr ProControllerKeyboardMappingTable::make_mapping( - std::string description, - Qt::Key key, - const ProControllerDeltas& deltas -){ - return std::make_unique( - *this, - m_advanced_mode.load(std::memory_order_relaxed), - std::move(description), - key, - deltas - ); -} -std::vector> ProControllerKeyboardMappingTable::make_defaults(){ - std::vector> ret; - - ret.emplace_back(make_mapping("Dpad Up", Qt::Key::Key_8, ProControllerDeltas{.dpad_x = 0, .dpad_y = -1})); - ret.emplace_back(make_mapping("Dpad Up+Right", Qt::Key::Key_9, ProControllerDeltas{.dpad_x = +1, .dpad_y = -1})); - ret.emplace_back(make_mapping("Dpad Right", Qt::Key::Key_6, ProControllerDeltas{.dpad_x = +1, .dpad_y = 0})); - ret.emplace_back(make_mapping("Dpad Down+Right", Qt::Key::Key_3, ProControllerDeltas{.dpad_x = +1, .dpad_y = +1})); - ret.emplace_back(make_mapping("Dpad Down", Qt::Key::Key_2, ProControllerDeltas{.dpad_x = 0, .dpad_y = +1})); - ret.emplace_back(make_mapping("Dpad Down+Left", Qt::Key::Key_1, ProControllerDeltas{.dpad_x = -1, .dpad_y = +1})); - ret.emplace_back(make_mapping("Dpad Left", Qt::Key::Key_4, ProControllerDeltas{.dpad_x = -1, .dpad_y = 0})); - ret.emplace_back(make_mapping("Dpad Up+Left", Qt::Key::Key_7, ProControllerDeltas{.dpad_x = -1, .dpad_y = -1})); - - ret.emplace_back(make_mapping("Left-Stick Up", Qt::Key::Key_W, ProControllerDeltas{.left_x = 0, .left_y = -1})); - ret.emplace_back(make_mapping("Left-Stick Left", Qt::Key::Key_A, ProControllerDeltas{.left_x = -1, .left_y = 0})); - ret.emplace_back(make_mapping("Left-Stick Down", Qt::Key::Key_S, ProControllerDeltas{.left_x = 0, .left_y = +1})); - ret.emplace_back(make_mapping("Left-Stick Right", Qt::Key::Key_D, ProControllerDeltas{.left_x = +1, .left_y = 0})); - ret.emplace_back(make_mapping("Right-Stick Up", Qt::Key::Key_Up, ProControllerDeltas{.right_x = 0, .right_y = -1})); - ret.emplace_back(make_mapping("Right-Stick Right", Qt::Key::Key_Right, ProControllerDeltas{.right_x = +1, .right_y = 0})); - ret.emplace_back(make_mapping("Right-Stick Down", Qt::Key::Key_Down, ProControllerDeltas{.right_x = 0, .right_y = +1})); - ret.emplace_back(make_mapping("Right-Stick Left", Qt::Key::Key_Left, ProControllerDeltas{.right_x = -1, .right_y = 0})); - - ret.emplace_back(make_mapping("Y", Qt::Key::Key_Slash, ProControllerDeltas{.buttons = BUTTON_Y})); - ret.emplace_back(make_mapping("Y", Qt::Key::Key_Question, ProControllerDeltas{.buttons = BUTTON_Y})); - - ret.emplace_back(make_mapping("B", Qt::Key::Key_Shift, ProControllerDeltas{.buttons = BUTTON_B})); - ret.emplace_back(make_mapping("B", Qt::Key::Key_Control, ProControllerDeltas{.buttons = BUTTON_B})); - - ret.emplace_back(make_mapping("A", Qt::Key::Key_Enter, ProControllerDeltas{.buttons = BUTTON_A})); - ret.emplace_back(make_mapping("A", Qt::Key::Key_Return, ProControllerDeltas{.buttons = BUTTON_A})); - - ret.emplace_back(make_mapping("X", Qt::Key::Key_Apostrophe,ProControllerDeltas{.buttons = BUTTON_X})); - ret.emplace_back(make_mapping("X", Qt::Key::Key_QuoteDbl, ProControllerDeltas{.buttons = BUTTON_X})); - - ret.emplace_back(make_mapping("L", Qt::Key::Key_Q, ProControllerDeltas{.buttons = BUTTON_L})); - ret.emplace_back(make_mapping("R", Qt::Key::Key_E, ProControllerDeltas{.buttons = BUTTON_R})); - ret.emplace_back(make_mapping("ZL", Qt::Key::Key_R, ProControllerDeltas{.buttons = BUTTON_ZL})); - ret.emplace_back(make_mapping("R", Qt::Key::Key_BraceRight, ProControllerDeltas{.buttons = BUTTON_R})); - ret.emplace_back(make_mapping("R", Qt::Key::Key_BracketRight, ProControllerDeltas{.buttons = BUTTON_R})); - ret.emplace_back(make_mapping("ZR", Qt::Key::Key_Backslash, ProControllerDeltas{.buttons = BUTTON_ZR})); - ret.emplace_back(make_mapping("ZR", Qt::Key::Key_Bar, ProControllerDeltas{.buttons = BUTTON_ZR})); - - ret.emplace_back(make_mapping("-", Qt::Key::Key_Minus, ProControllerDeltas{.buttons = BUTTON_MINUS})); - ret.emplace_back(make_mapping("-", Qt::Key::Key_Underscore, ProControllerDeltas{.buttons = BUTTON_MINUS})); - ret.emplace_back(make_mapping("+", Qt::Key::Key_Plus, ProControllerDeltas{.buttons = BUTTON_PLUS})); - ret.emplace_back(make_mapping("+", Qt::Key::Key_Equal, ProControllerDeltas{.buttons = BUTTON_PLUS})); - - ret.emplace_back(make_mapping("L-Click", Qt::Key::Key_C, ProControllerDeltas{.buttons = BUTTON_LCLICK})); - ret.emplace_back(make_mapping("R-Click", Qt::Key::Key_0, ProControllerDeltas{.buttons = BUTTON_RCLICK})); - - ret.emplace_back(make_mapping("Home", Qt::Key::Key_Home, ProControllerDeltas{.buttons = BUTTON_HOME})); - ret.emplace_back(make_mapping("Home", Qt::Key::Key_Escape, ProControllerDeltas{.buttons = BUTTON_HOME})); - ret.emplace_back(make_mapping("Home", Qt::Key::Key_H, ProControllerDeltas{.buttons = BUTTON_HOME})); - - ret.emplace_back(make_mapping("Capture", Qt::Key::Key_Insert, ProControllerDeltas{.buttons = BUTTON_CAPTURE})); - - ret.emplace_back(make_mapping("A+R (for CFW)", Qt::Key::Key_Y, ProControllerDeltas{.buttons = BUTTON_A | BUTTON_R})); - - return ret; -} - - - - -JoyconKeyMapTableRow::JoyconKeyMapTableRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , label(false, LockMode::UNLOCK_WHILE_RUNNING, "", "") - , key(LockMode::UNLOCK_WHILE_RUNNING) - , buttons(LockMode::UNLOCK_WHILE_RUNNING, 0, 0, ((uint32_t)1 << TOTAL_BUTTONS) - 1) - , joystick_x(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) - , joystick_y(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) -{ - add_option(label, "Description"); - add_option(key, "Key"); - add_option(buttons, "Button Bit-Field"); - add_option(joystick_x, "Joystick x"); - add_option(joystick_y, "Joystick y"); - set_advanced_mode(static_cast(parent_table).advanced_mode()); -} -JoyconKeyMapTableRow::JoyconKeyMapTableRow( - EditableTableOption& parent_table, - bool advanced_mode, - std::string description, - Qt::Key key, - const JoyconDeltas& deltas -) - : JoyconKeyMapTableRow(parent_table) -{ - label.set(std::move(description)); - this->key.set(key); - buttons.set(deltas.buttons); - joystick_x.set(deltas.joystick_x); - joystick_y.set(deltas.joystick_y); - set_advanced_mode(advanced_mode); -} -std::unique_ptr JoyconKeyMapTableRow::clone() const{ - std::unique_ptr ret(new JoyconKeyMapTableRow(parent())); - ret->label.set(label); - ret->key.set((uint32_t)key); - ret->buttons.set(buttons); - ret->joystick_x.set(joystick_x); - ret->joystick_y.set(joystick_y); - ret->set_advanced_mode(m_advanced_mode.load(std::memory_order_relaxed)); - return ret; -} -JoyconDeltas JoyconKeyMapTableRow::snapshot() const{ - return { - .buttons = (Button)buttons.current_value(), - .joystick_x = joystick_x, - .joystick_y = joystick_y, - }; -} -void JoyconKeyMapTableRow::set_advanced_mode(bool enabled){ - m_advanced_mode.store(enabled, std::memory_order_relaxed); - if (enabled){ - label.set_locked(false); - buttons.set_visibility(ConfigOptionState::ENABLED); - joystick_x.set_visibility(ConfigOptionState::ENABLED); - joystick_y.set_visibility(ConfigOptionState::ENABLED); - }else{ - label.set_locked(true); - buttons.set_visibility(ConfigOptionState::DISABLED); - joystick_x.set_visibility(ConfigOptionState::DISABLED); - joystick_y.set_visibility(ConfigOptionState::DISABLED); - } -} - - - -JoyconKeyboardMappingTable::JoyconKeyboardMappingTable(bool left) - : EditableTableOption_t( - left ? "Left Joycon:" : "Right Joycon:", - LockMode::UNLOCK_WHILE_RUNNING, - true, - make_defaults(left) - ) - , m_advanced_mode(false) -{} -std::vector JoyconKeyboardMappingTable::make_header() const{ - return std::vector{ - "Description", - "Key", - "Button Bit-Field", - "Joystick x", - "Joystick y", - }; -} -void JoyconKeyboardMappingTable::set_advanced_mode(bool enabled){ - m_advanced_mode.store(enabled, std::memory_order_relaxed); - run_on_all_rows([enabled](JoyconKeyMapTableRow& row){ - row.set_advanced_mode(enabled); - return false; - }); -} - - -std::unique_ptr JoyconKeyboardMappingTable::make_mapping( - std::string description, - Qt::Key key, - const JoyconDeltas& deltas -){ - return std::make_unique( - *this, - m_advanced_mode.load(std::memory_order_relaxed), - std::move(description), - key, - deltas - ); -} -std::vector> JoyconKeyboardMappingTable::make_defaults(bool left){ - std::vector> ret; - - if (left){ - ret.emplace_back(make_mapping("Vertical: JS Up", Qt::Key::Key_W, JoyconDeltas{.joystick_x = 0, .joystick_y = -1})); - ret.emplace_back(make_mapping("Vertical: JS Left", Qt::Key::Key_A, JoyconDeltas{.joystick_x = -1, .joystick_y = 0})); - ret.emplace_back(make_mapping("Vertical: JS Down", Qt::Key::Key_S, JoyconDeltas{.joystick_x = 0, .joystick_y = +1})); - ret.emplace_back(make_mapping("Vertical: JS Right", Qt::Key::Key_D, JoyconDeltas{.joystick_x = +1, .joystick_y = 0})); - - ret.emplace_back(make_mapping("Vertical: Up", Qt::Key::Key_Up, JoyconDeltas{.buttons = BUTTON_UP})); - ret.emplace_back(make_mapping("Vertical: Right", Qt::Key::Key_Right, JoyconDeltas{.buttons = BUTTON_RIGHT})); - ret.emplace_back(make_mapping("Vertical: Down", Qt::Key::Key_Down, JoyconDeltas{.buttons = BUTTON_DOWN})); - ret.emplace_back(make_mapping("Vertical: Left", Qt::Key::Key_Left, JoyconDeltas{.buttons = BUTTON_LEFT})); - - ret.emplace_back(make_mapping("Vertical: L", Qt::Key::Key_Q, JoyconDeltas{.buttons = BUTTON_L})); - ret.emplace_back(make_mapping("Vertical: ZL", Qt::Key::Key_E, JoyconDeltas{.buttons = BUTTON_ZL})); - ret.emplace_back(make_mapping("Vertical: JS-Click", Qt::Key::Key_C, JoyconDeltas{.buttons = BUTTON_LCLICK})); - - ret.emplace_back(make_mapping("Sideways: JS Up", Qt::Key::Key_T, JoyconDeltas{.joystick_x = +1, .joystick_y = 0})); - ret.emplace_back(make_mapping("Sideways: JS Left", Qt::Key::Key_F, JoyconDeltas{.joystick_x = 0, .joystick_y = -1})); - ret.emplace_back(make_mapping("Sideways: JS Down", Qt::Key::Key_G, JoyconDeltas{.joystick_x = -1, .joystick_y = 0})); - ret.emplace_back(make_mapping("Sideways: JS Right", Qt::Key::Key_H, JoyconDeltas{.joystick_x = 0, .joystick_y = +1})); - - ret.emplace_back(make_mapping("Sideways: Up", Qt::Key::Key_Apostrophe,JoyconDeltas{.buttons = BUTTON_RIGHT})); - ret.emplace_back(make_mapping("Sideways: Up", Qt::Key::Key_QuoteDbl, JoyconDeltas{.buttons = BUTTON_RIGHT})); - ret.emplace_back(make_mapping("Sideways: Right", Qt::Key::Key_Enter, JoyconDeltas{.buttons = BUTTON_DOWN})); - ret.emplace_back(make_mapping("Sideways: Right", Qt::Key::Key_Return, JoyconDeltas{.buttons = BUTTON_DOWN})); - ret.emplace_back(make_mapping("Sideways: Down", Qt::Key::Key_Shift, JoyconDeltas{.buttons = BUTTON_LEFT})); - ret.emplace_back(make_mapping("Sideways: Down", Qt::Key::Key_Control, JoyconDeltas{.buttons = BUTTON_LEFT})); - ret.emplace_back(make_mapping("Sideways: Left", Qt::Key::Key_Slash, JoyconDeltas{.buttons = BUTTON_UP})); - ret.emplace_back(make_mapping("Sideways: Left", Qt::Key::Key_Question, JoyconDeltas{.buttons = BUTTON_UP})); - - ret.emplace_back(make_mapping("Sideways: L", Qt::Key::Key_R, JoyconDeltas{.buttons = BUTTON_L})); - ret.emplace_back(make_mapping("Sideways: ZL", Qt::Key::Key_Y, JoyconDeltas{.buttons = BUTTON_ZL})); - ret.emplace_back(make_mapping("Sideways: JS-Click", Qt::Key::Key_N, JoyconDeltas{.buttons = BUTTON_LCLICK})); - - // Other - ret.emplace_back(make_mapping("-", Qt::Key::Key_Minus, JoyconDeltas{.buttons = BUTTON_MINUS})); - ret.emplace_back(make_mapping("-", Qt::Key::Key_Underscore,JoyconDeltas{.buttons = BUTTON_MINUS})); - - ret.emplace_back(make_mapping("Capture", Qt::Key::Key_Insert, JoyconDeltas{.buttons = BUTTON_CAPTURE})); - - ret.emplace_back(make_mapping("SL", Qt::Key::Key_F1, JoyconDeltas{.buttons = BUTTON_LEFT_SL})); - ret.emplace_back(make_mapping("SR", Qt::Key::Key_F3, JoyconDeltas{.buttons = BUTTON_LEFT_SR})); - }else{ - ret.emplace_back(make_mapping("Vertical: JS Up", Qt::Key::Key_W, JoyconDeltas{.joystick_x = 0, .joystick_y = -1})); - ret.emplace_back(make_mapping("Vertical: JS Left", Qt::Key::Key_A, JoyconDeltas{.joystick_x = -1, .joystick_y = 0})); - ret.emplace_back(make_mapping("Vertical: JS Down", Qt::Key::Key_S, JoyconDeltas{.joystick_x = 0, .joystick_y = +1})); - ret.emplace_back(make_mapping("Vertical: JS Right", Qt::Key::Key_D, JoyconDeltas{.joystick_x = +1, .joystick_y = 0})); - - ret.emplace_back(make_mapping("Vertical: X", Qt::Key::Key_Apostrophe,JoyconDeltas{.buttons = BUTTON_X})); - ret.emplace_back(make_mapping("Vertical: X", Qt::Key::Key_QuoteDbl, JoyconDeltas{.buttons = BUTTON_X})); - - ret.emplace_back(make_mapping("Vertical: A", Qt::Key::Key_Enter, JoyconDeltas{.buttons = BUTTON_A})); - ret.emplace_back(make_mapping("Vertical: A", Qt::Key::Key_Return, JoyconDeltas{.buttons = BUTTON_A})); - - ret.emplace_back(make_mapping("Vertical: B", Qt::Key::Key_Shift, JoyconDeltas{.buttons = BUTTON_B})); - ret.emplace_back(make_mapping("Vertical: B", Qt::Key::Key_Control, JoyconDeltas{.buttons = BUTTON_B})); - - ret.emplace_back(make_mapping("Vertical: Y", Qt::Key::Key_Slash, JoyconDeltas{.buttons = BUTTON_Y})); - ret.emplace_back(make_mapping("Vertical: Y", Qt::Key::Key_Question, JoyconDeltas{.buttons = BUTTON_Y})); - - ret.emplace_back(make_mapping("Vertical: R", Qt::Key::Key_Q, JoyconDeltas{.buttons = BUTTON_R})); - ret.emplace_back(make_mapping("Vertical: ZR", Qt::Key::Key_E, JoyconDeltas{.buttons = BUTTON_ZR})); - ret.emplace_back(make_mapping("Vertical: JS-Click", Qt::Key::Key_C, JoyconDeltas{.buttons = BUTTON_RCLICK})); - - ret.emplace_back(make_mapping("Sideways: JS Up", Qt::Key::Key_T, JoyconDeltas{.joystick_x = -1, .joystick_y = 0})); - ret.emplace_back(make_mapping("Sideways: JS Left", Qt::Key::Key_F, JoyconDeltas{.joystick_x = 0, .joystick_y = +1})); - ret.emplace_back(make_mapping("Sideways: JS Down", Qt::Key::Key_G, JoyconDeltas{.joystick_x = +1, .joystick_y = 0})); - ret.emplace_back(make_mapping("Sideways: JS Right", Qt::Key::Key_H, JoyconDeltas{.joystick_x = 0, .joystick_y = -1})); - - ret.emplace_back(make_mapping("Sideways: X", Qt::Key::Key_Up, JoyconDeltas{.buttons = BUTTON_Y})); - ret.emplace_back(make_mapping("Sideways: A", Qt::Key::Key_Right, JoyconDeltas{.buttons = BUTTON_X})); - ret.emplace_back(make_mapping("Sideways: B", Qt::Key::Key_Down, JoyconDeltas{.buttons = BUTTON_A})); - ret.emplace_back(make_mapping("Sideways: Y", Qt::Key::Key_Left, JoyconDeltas{.buttons = BUTTON_B})); - - ret.emplace_back(make_mapping("Sideways: R", Qt::Key::Key_R, JoyconDeltas{.buttons = BUTTON_R})); - ret.emplace_back(make_mapping("Sideways: ZR", Qt::Key::Key_Y, JoyconDeltas{.buttons = BUTTON_ZR})); - ret.emplace_back(make_mapping("Sideways: JS-Click", Qt::Key::Key_N, JoyconDeltas{.buttons = BUTTON_RCLICK})); - - // Other - ret.emplace_back(make_mapping("+", Qt::Key::Key_Plus, JoyconDeltas{.buttons = BUTTON_PLUS})); - ret.emplace_back(make_mapping("+", Qt::Key::Key_Equal, JoyconDeltas{.buttons = BUTTON_PLUS})); - - ret.emplace_back(make_mapping("Home", Qt::Key::Key_Home, JoyconDeltas{.buttons = BUTTON_HOME})); - ret.emplace_back(make_mapping("Home", Qt::Key::Key_Escape, JoyconDeltas{.buttons = BUTTON_HOME})); - - ret.emplace_back(make_mapping("SL", Qt::Key::Key_F1, JoyconDeltas{.buttons = BUTTON_RIGHT_SL})); - ret.emplace_back(make_mapping("SR", Qt::Key::Key_F3, JoyconDeltas{.buttons = BUTTON_RIGHT_SR})); - } - - return ret; -} - - - - - - - - - - - - - - - - - - - - - - - -KeyboardMappingOption::~KeyboardMappingOption(){ - ADVANCED_MODE.remove_listener(*this); -} -KeyboardMappingOption::KeyboardMappingOption() - : BatchOption(LockMode::UNLOCK_WHILE_RUNNING) - , DESCRIPTION( - "The following table is the mapping of keyboard keys to Switch controller presses. " - "If you wish to remap a key, click on the cell in the \"Key\" column and press the desired key. " - "You do not need to edit any of the other columns.

" - "Note for keys that change behavior when combined with " - "SHIFT or CTRL, you should include all of those combinations as well. " - "For example, the default mapping for the Y button is both '/' and '?' " - "because they are treated as different keys depending on whether SHIFT " - "is held down. Letters are exempt from this as both lower and upper case " - "letters are considered the same." - "

" - "Advanced users are free to edit the rest of the table. You can create " - "new mappings or mappings that result in multiple buttons. " - "For example, there is a special mapping for pressing A + R " - "simultaneously that is useful for CFW users who are remotely " - "controlling the program over Team Viewer." - ) - , ADVANCED_MODE( - "Unlock entire table (Advanced Mode):", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , LEFT_JOYCON(true) - , RIGHT_JOYCON(false) -{ - PA_ADD_STATIC(DESCRIPTION); - PA_ADD_OPTION(ADVANCED_MODE); - PA_ADD_OPTION(PRO_CONTROLLER); - PA_ADD_OPTION(LEFT_JOYCON); - PA_ADD_OPTION(RIGHT_JOYCON); - ADVANCED_MODE.add_listener(*this); -} - - -void KeyboardMappingOption::load_json(const JsonValue& json){ - BatchOption::load_json(json); - KeyboardMappingOption::on_config_value_changed(this); -} -void KeyboardMappingOption::on_config_value_changed(void* object){ - PRO_CONTROLLER.set_advanced_mode(ADVANCED_MODE); - LEFT_JOYCON.set_advanced_mode(ADVANCED_MODE); - RIGHT_JOYCON.set_advanced_mode(ADVANCED_MODE); -} - - - - - - - - - - - - -} -} +/* Nintendo Keyboard Mapping + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "NintendoSwitch_VirtualControllerState.h" +#include "NintendoSwitch_KeyboardMapping.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +ProControllerKeyMapTableRow::ProControllerKeyMapTableRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , label(false, LockMode::UNLOCK_WHILE_RUNNING, "", "") + , key(LockMode::UNLOCK_WHILE_RUNNING) + , buttons(LockMode::UNLOCK_WHILE_RUNNING, 0, 0, ((uint32_t)1 << TOTAL_BUTTONS) - 1) + , dpad_x(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) + , dpad_y(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) + , left_stick_x(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) + , left_stick_y(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) + , right_stick_x(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) + , right_stick_y(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) +{ + add_option(label, "Description"); + add_option(key, "Key"); + add_option(buttons, "Button Bit-Field"); + add_option(dpad_x, "Dpad x"); + add_option(dpad_y, "Dpad y"); + add_option(left_stick_x, "Left-Stick x"); + add_option(left_stick_y, "Left-Stick y"); + add_option(right_stick_x, "Right-Stick x"); + add_option(right_stick_y, "Right-Stick y"); + set_advanced_mode(static_cast(parent_table).advanced_mode()); +} +ProControllerKeyMapTableRow::ProControllerKeyMapTableRow( + EditableTableOption& parent_table, + bool advanced_mode, + std::string description, + Qt::Key key, + const ProControllerDeltas& deltas +) + : ProControllerKeyMapTableRow(parent_table) +{ + label.set(std::move(description)); + this->key.set(key); + buttons.set(deltas.buttons); + dpad_x.set(deltas.dpad_x); + dpad_y.set(deltas.dpad_y); + left_stick_x.set(deltas.left_x); + left_stick_y.set(deltas.left_y); + right_stick_x.set(deltas.right_x); + right_stick_y.set(deltas.right_y); + set_advanced_mode(advanced_mode); +} +std::unique_ptr ProControllerKeyMapTableRow::clone() const{ + std::unique_ptr ret(new ProControllerKeyMapTableRow(parent())); + ret->label.set(label); + ret->key.set((uint32_t)key); + ret->buttons.set(buttons); + ret->dpad_x.set(dpad_x); + ret->dpad_y.set(dpad_y); + ret->left_stick_x.set(left_stick_x); + ret->left_stick_y.set(left_stick_y); + ret->right_stick_x.set(right_stick_x); + ret->right_stick_y.set(right_stick_y); + ret->set_advanced_mode(m_advanced_mode.load(std::memory_order_relaxed)); + return ret; +} +ProControllerDeltas ProControllerKeyMapTableRow::snapshot() const{ + return { + .buttons = (Button)buttons.current_value(), + .dpad_x = dpad_x, + .dpad_y = dpad_y, + .left_x = left_stick_x, + .left_y = left_stick_y, + .right_x = right_stick_x, + .right_y = right_stick_y, + }; +} +void ProControllerKeyMapTableRow::set_advanced_mode(bool enabled){ + m_advanced_mode.store(enabled, std::memory_order_relaxed); + if (enabled){ + label.set_locked(false); + buttons.set_visibility(ConfigOptionState::ENABLED); + dpad_x.set_visibility(ConfigOptionState::ENABLED); + dpad_y.set_visibility(ConfigOptionState::ENABLED); + left_stick_x.set_visibility(ConfigOptionState::ENABLED); + left_stick_y.set_visibility(ConfigOptionState::ENABLED); + right_stick_x.set_visibility(ConfigOptionState::ENABLED); + right_stick_y.set_visibility(ConfigOptionState::ENABLED); + }else{ + label.set_locked(true); + buttons.set_visibility(ConfigOptionState::DISABLED); + dpad_x.set_visibility(ConfigOptionState::DISABLED); + dpad_y.set_visibility(ConfigOptionState::DISABLED); + left_stick_x.set_visibility(ConfigOptionState::DISABLED); + left_stick_y.set_visibility(ConfigOptionState::DISABLED); + right_stick_x.set_visibility(ConfigOptionState::DISABLED); + right_stick_y.set_visibility(ConfigOptionState::DISABLED); + } +} + + + + + +ProControllerKeyboardMappingTable::ProControllerKeyboardMappingTable() + : EditableTableOption_t( + "Pro Controller:", + LockMode::UNLOCK_WHILE_RUNNING, + true, + make_defaults() + ) + , m_advanced_mode(false) +{} +std::vector ProControllerKeyboardMappingTable::make_header() const{ + return std::vector{ + "Description", + "Key", + "Button Bit-Field", + "Dpad x", + "Dpad y", + "Left-Stick x", + "Left-Stick y", + "Right-Stick x", + "Right-Stick y", + }; +} +void ProControllerKeyboardMappingTable::set_advanced_mode(bool enabled){ + m_advanced_mode.store(enabled, std::memory_order_relaxed); + run_on_all_rows([enabled](ProControllerKeyMapTableRow& row){ + row.set_advanced_mode(enabled); + return false; + }); +} + + +std::unique_ptr ProControllerKeyboardMappingTable::make_mapping( + std::string description, + Qt::Key key, + const ProControllerDeltas& deltas +){ + return std::make_unique( + *this, + m_advanced_mode.load(std::memory_order_relaxed), + std::move(description), + key, + deltas + ); +} +std::vector> ProControllerKeyboardMappingTable::make_defaults(){ + std::vector> ret; + + ret.emplace_back(make_mapping("Dpad Up", Qt::Key::Key_8, ProControllerDeltas{.dpad_x = 0, .dpad_y = -1})); + ret.emplace_back(make_mapping("Dpad Up+Right", Qt::Key::Key_9, ProControllerDeltas{.dpad_x = +1, .dpad_y = -1})); + ret.emplace_back(make_mapping("Dpad Right", Qt::Key::Key_6, ProControllerDeltas{.dpad_x = +1, .dpad_y = 0})); + ret.emplace_back(make_mapping("Dpad Down+Right", Qt::Key::Key_3, ProControllerDeltas{.dpad_x = +1, .dpad_y = +1})); + ret.emplace_back(make_mapping("Dpad Down", Qt::Key::Key_2, ProControllerDeltas{.dpad_x = 0, .dpad_y = +1})); + ret.emplace_back(make_mapping("Dpad Down+Left", Qt::Key::Key_1, ProControllerDeltas{.dpad_x = -1, .dpad_y = +1})); + ret.emplace_back(make_mapping("Dpad Left", Qt::Key::Key_4, ProControllerDeltas{.dpad_x = -1, .dpad_y = 0})); + ret.emplace_back(make_mapping("Dpad Up+Left", Qt::Key::Key_7, ProControllerDeltas{.dpad_x = -1, .dpad_y = -1})); + + ret.emplace_back(make_mapping("Left-Stick Up", Qt::Key::Key_W, ProControllerDeltas{.left_x = 0, .left_y = -1})); + ret.emplace_back(make_mapping("Left-Stick Left", Qt::Key::Key_A, ProControllerDeltas{.left_x = -1, .left_y = 0})); + ret.emplace_back(make_mapping("Left-Stick Down", Qt::Key::Key_S, ProControllerDeltas{.left_x = 0, .left_y = +1})); + ret.emplace_back(make_mapping("Left-Stick Right", Qt::Key::Key_D, ProControllerDeltas{.left_x = +1, .left_y = 0})); + ret.emplace_back(make_mapping("Right-Stick Up", Qt::Key::Key_Up, ProControllerDeltas{.right_x = 0, .right_y = -1})); + ret.emplace_back(make_mapping("Right-Stick Right", Qt::Key::Key_Right, ProControllerDeltas{.right_x = +1, .right_y = 0})); + ret.emplace_back(make_mapping("Right-Stick Down", Qt::Key::Key_Down, ProControllerDeltas{.right_x = 0, .right_y = +1})); + ret.emplace_back(make_mapping("Right-Stick Left", Qt::Key::Key_Left, ProControllerDeltas{.right_x = -1, .right_y = 0})); + + ret.emplace_back(make_mapping("Y", Qt::Key::Key_Slash, ProControllerDeltas{.buttons = BUTTON_Y})); + ret.emplace_back(make_mapping("Y", Qt::Key::Key_Question, ProControllerDeltas{.buttons = BUTTON_Y})); + + ret.emplace_back(make_mapping("B", Qt::Key::Key_Shift, ProControllerDeltas{.buttons = BUTTON_B})); + ret.emplace_back(make_mapping("B", Qt::Key::Key_Control, ProControllerDeltas{.buttons = BUTTON_B})); + + ret.emplace_back(make_mapping("A", Qt::Key::Key_Enter, ProControllerDeltas{.buttons = BUTTON_A})); + ret.emplace_back(make_mapping("A", Qt::Key::Key_Return, ProControllerDeltas{.buttons = BUTTON_A})); + + ret.emplace_back(make_mapping("X", Qt::Key::Key_Apostrophe,ProControllerDeltas{.buttons = BUTTON_X})); + ret.emplace_back(make_mapping("X", Qt::Key::Key_QuoteDbl, ProControllerDeltas{.buttons = BUTTON_X})); + + ret.emplace_back(make_mapping("L", Qt::Key::Key_Q, ProControllerDeltas{.buttons = BUTTON_L})); + ret.emplace_back(make_mapping("R", Qt::Key::Key_E, ProControllerDeltas{.buttons = BUTTON_R})); + ret.emplace_back(make_mapping("ZL", Qt::Key::Key_R, ProControllerDeltas{.buttons = BUTTON_ZL})); + ret.emplace_back(make_mapping("R", Qt::Key::Key_BraceRight, ProControllerDeltas{.buttons = BUTTON_R})); + ret.emplace_back(make_mapping("R", Qt::Key::Key_BracketRight, ProControllerDeltas{.buttons = BUTTON_R})); + ret.emplace_back(make_mapping("ZR", Qt::Key::Key_Backslash, ProControllerDeltas{.buttons = BUTTON_ZR})); + ret.emplace_back(make_mapping("ZR", Qt::Key::Key_Bar, ProControllerDeltas{.buttons = BUTTON_ZR})); + + ret.emplace_back(make_mapping("GL (Switch 2)", Qt::Key::Key_V, ProControllerDeltas{.buttons = BUTTON_GL})); + ret.emplace_back(make_mapping("GR (Switch 2)", Qt::Key::Key_Period, ProControllerDeltas{.buttons = BUTTON_GR})); + ret.emplace_back(make_mapping("GR (Switch 2)", Qt::Key::Key_Greater, ProControllerDeltas{.buttons = BUTTON_GR})); + + ret.emplace_back(make_mapping("-", Qt::Key::Key_Minus, ProControllerDeltas{.buttons = BUTTON_MINUS})); + ret.emplace_back(make_mapping("-", Qt::Key::Key_Underscore, ProControllerDeltas{.buttons = BUTTON_MINUS})); + ret.emplace_back(make_mapping("+", Qt::Key::Key_Plus, ProControllerDeltas{.buttons = BUTTON_PLUS})); + ret.emplace_back(make_mapping("+", Qt::Key::Key_Equal, ProControllerDeltas{.buttons = BUTTON_PLUS})); + + ret.emplace_back(make_mapping("L-Click", Qt::Key::Key_C, ProControllerDeltas{.buttons = BUTTON_LCLICK})); + ret.emplace_back(make_mapping("R-Click", Qt::Key::Key_0, ProControllerDeltas{.buttons = BUTTON_RCLICK})); + + ret.emplace_back(make_mapping("Home", Qt::Key::Key_Home, ProControllerDeltas{.buttons = BUTTON_HOME})); + ret.emplace_back(make_mapping("Home", Qt::Key::Key_Escape, ProControllerDeltas{.buttons = BUTTON_HOME})); + ret.emplace_back(make_mapping("Home", Qt::Key::Key_H, ProControllerDeltas{.buttons = BUTTON_HOME})); + + ret.emplace_back(make_mapping("Capture", Qt::Key::Key_Insert, ProControllerDeltas{.buttons = BUTTON_CAPTURE})); + + ret.emplace_back(make_mapping("A+R (for CFW)", Qt::Key::Key_Y, ProControllerDeltas{.buttons = BUTTON_A | BUTTON_R})); + + return ret; +} + + + + +JoyconKeyMapTableRow::JoyconKeyMapTableRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , label(false, LockMode::UNLOCK_WHILE_RUNNING, "", "") + , key(LockMode::UNLOCK_WHILE_RUNNING) + , buttons(LockMode::UNLOCK_WHILE_RUNNING, 0, 0, ((uint32_t)1 << TOTAL_BUTTONS) - 1) + , joystick_x(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) + , joystick_y(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) +{ + add_option(label, "Description"); + add_option(key, "Key"); + add_option(buttons, "Button Bit-Field"); + add_option(joystick_x, "Joystick x"); + add_option(joystick_y, "Joystick y"); + set_advanced_mode(static_cast(parent_table).advanced_mode()); +} +JoyconKeyMapTableRow::JoyconKeyMapTableRow( + EditableTableOption& parent_table, + bool advanced_mode, + std::string description, + Qt::Key key, + const JoyconDeltas& deltas +) + : JoyconKeyMapTableRow(parent_table) +{ + label.set(std::move(description)); + this->key.set(key); + buttons.set(deltas.buttons); + joystick_x.set(deltas.joystick_x); + joystick_y.set(deltas.joystick_y); + set_advanced_mode(advanced_mode); +} +std::unique_ptr JoyconKeyMapTableRow::clone() const{ + std::unique_ptr ret(new JoyconKeyMapTableRow(parent())); + ret->label.set(label); + ret->key.set((uint32_t)key); + ret->buttons.set(buttons); + ret->joystick_x.set(joystick_x); + ret->joystick_y.set(joystick_y); + ret->set_advanced_mode(m_advanced_mode.load(std::memory_order_relaxed)); + return ret; +} +JoyconDeltas JoyconKeyMapTableRow::snapshot() const{ + return { + .buttons = (Button)buttons.current_value(), + .joystick_x = joystick_x, + .joystick_y = joystick_y, + }; +} +void JoyconKeyMapTableRow::set_advanced_mode(bool enabled){ + m_advanced_mode.store(enabled, std::memory_order_relaxed); + if (enabled){ + label.set_locked(false); + buttons.set_visibility(ConfigOptionState::ENABLED); + joystick_x.set_visibility(ConfigOptionState::ENABLED); + joystick_y.set_visibility(ConfigOptionState::ENABLED); + }else{ + label.set_locked(true); + buttons.set_visibility(ConfigOptionState::DISABLED); + joystick_x.set_visibility(ConfigOptionState::DISABLED); + joystick_y.set_visibility(ConfigOptionState::DISABLED); + } +} + + + +JoyconKeyboardMappingTable::JoyconKeyboardMappingTable(bool left) + : EditableTableOption_t( + left ? "Left Joycon:" : "Right Joycon:", + LockMode::UNLOCK_WHILE_RUNNING, + true, + make_defaults(left) + ) + , m_advanced_mode(false) +{} +std::vector JoyconKeyboardMappingTable::make_header() const{ + return std::vector{ + "Description", + "Key", + "Button Bit-Field", + "Joystick x", + "Joystick y", + }; +} +void JoyconKeyboardMappingTable::set_advanced_mode(bool enabled){ + m_advanced_mode.store(enabled, std::memory_order_relaxed); + run_on_all_rows([enabled](JoyconKeyMapTableRow& row){ + row.set_advanced_mode(enabled); + return false; + }); +} + + +std::unique_ptr JoyconKeyboardMappingTable::make_mapping( + std::string description, + Qt::Key key, + const JoyconDeltas& deltas +){ + return std::make_unique( + *this, + m_advanced_mode.load(std::memory_order_relaxed), + std::move(description), + key, + deltas + ); +} +std::vector> JoyconKeyboardMappingTable::make_defaults(bool left){ + std::vector> ret; + + if (left){ + ret.emplace_back(make_mapping("Vertical: JS Up", Qt::Key::Key_W, JoyconDeltas{.joystick_x = 0, .joystick_y = -1})); + ret.emplace_back(make_mapping("Vertical: JS Left", Qt::Key::Key_A, JoyconDeltas{.joystick_x = -1, .joystick_y = 0})); + ret.emplace_back(make_mapping("Vertical: JS Down", Qt::Key::Key_S, JoyconDeltas{.joystick_x = 0, .joystick_y = +1})); + ret.emplace_back(make_mapping("Vertical: JS Right", Qt::Key::Key_D, JoyconDeltas{.joystick_x = +1, .joystick_y = 0})); + + ret.emplace_back(make_mapping("Vertical: Up", Qt::Key::Key_Up, JoyconDeltas{.buttons = BUTTON_UP})); + ret.emplace_back(make_mapping("Vertical: Right", Qt::Key::Key_Right, JoyconDeltas{.buttons = BUTTON_RIGHT})); + ret.emplace_back(make_mapping("Vertical: Down", Qt::Key::Key_Down, JoyconDeltas{.buttons = BUTTON_DOWN})); + ret.emplace_back(make_mapping("Vertical: Left", Qt::Key::Key_Left, JoyconDeltas{.buttons = BUTTON_LEFT})); + + ret.emplace_back(make_mapping("Vertical: L", Qt::Key::Key_Q, JoyconDeltas{.buttons = BUTTON_L})); + ret.emplace_back(make_mapping("Vertical: ZL", Qt::Key::Key_E, JoyconDeltas{.buttons = BUTTON_ZL})); + ret.emplace_back(make_mapping("Vertical: JS-Click", Qt::Key::Key_C, JoyconDeltas{.buttons = BUTTON_LCLICK})); + + ret.emplace_back(make_mapping("Sideways: JS Up", Qt::Key::Key_T, JoyconDeltas{.joystick_x = +1, .joystick_y = 0})); + ret.emplace_back(make_mapping("Sideways: JS Left", Qt::Key::Key_F, JoyconDeltas{.joystick_x = 0, .joystick_y = -1})); + ret.emplace_back(make_mapping("Sideways: JS Down", Qt::Key::Key_G, JoyconDeltas{.joystick_x = -1, .joystick_y = 0})); + ret.emplace_back(make_mapping("Sideways: JS Right", Qt::Key::Key_H, JoyconDeltas{.joystick_x = 0, .joystick_y = +1})); + + ret.emplace_back(make_mapping("Sideways: Up", Qt::Key::Key_Apostrophe,JoyconDeltas{.buttons = BUTTON_RIGHT})); + ret.emplace_back(make_mapping("Sideways: Up", Qt::Key::Key_QuoteDbl, JoyconDeltas{.buttons = BUTTON_RIGHT})); + ret.emplace_back(make_mapping("Sideways: Right", Qt::Key::Key_Enter, JoyconDeltas{.buttons = BUTTON_DOWN})); + ret.emplace_back(make_mapping("Sideways: Right", Qt::Key::Key_Return, JoyconDeltas{.buttons = BUTTON_DOWN})); + ret.emplace_back(make_mapping("Sideways: Down", Qt::Key::Key_Shift, JoyconDeltas{.buttons = BUTTON_LEFT})); + ret.emplace_back(make_mapping("Sideways: Down", Qt::Key::Key_Control, JoyconDeltas{.buttons = BUTTON_LEFT})); + ret.emplace_back(make_mapping("Sideways: Left", Qt::Key::Key_Slash, JoyconDeltas{.buttons = BUTTON_UP})); + ret.emplace_back(make_mapping("Sideways: Left", Qt::Key::Key_Question, JoyconDeltas{.buttons = BUTTON_UP})); + + ret.emplace_back(make_mapping("Sideways: L", Qt::Key::Key_R, JoyconDeltas{.buttons = BUTTON_L})); + ret.emplace_back(make_mapping("Sideways: ZL", Qt::Key::Key_Y, JoyconDeltas{.buttons = BUTTON_ZL})); + ret.emplace_back(make_mapping("Sideways: JS-Click", Qt::Key::Key_N, JoyconDeltas{.buttons = BUTTON_LCLICK})); + + // Other + ret.emplace_back(make_mapping("-", Qt::Key::Key_Minus, JoyconDeltas{.buttons = BUTTON_MINUS})); + ret.emplace_back(make_mapping("-", Qt::Key::Key_Underscore,JoyconDeltas{.buttons = BUTTON_MINUS})); + + ret.emplace_back(make_mapping("Capture", Qt::Key::Key_Insert, JoyconDeltas{.buttons = BUTTON_CAPTURE})); + + ret.emplace_back(make_mapping("SL", Qt::Key::Key_F1, JoyconDeltas{.buttons = BUTTON_LEFT_SL})); + ret.emplace_back(make_mapping("SR", Qt::Key::Key_F3, JoyconDeltas{.buttons = BUTTON_LEFT_SR})); + }else{ + ret.emplace_back(make_mapping("Vertical: JS Up", Qt::Key::Key_W, JoyconDeltas{.joystick_x = 0, .joystick_y = -1})); + ret.emplace_back(make_mapping("Vertical: JS Left", Qt::Key::Key_A, JoyconDeltas{.joystick_x = -1, .joystick_y = 0})); + ret.emplace_back(make_mapping("Vertical: JS Down", Qt::Key::Key_S, JoyconDeltas{.joystick_x = 0, .joystick_y = +1})); + ret.emplace_back(make_mapping("Vertical: JS Right", Qt::Key::Key_D, JoyconDeltas{.joystick_x = +1, .joystick_y = 0})); + + ret.emplace_back(make_mapping("Vertical: X", Qt::Key::Key_Apostrophe,JoyconDeltas{.buttons = BUTTON_X})); + ret.emplace_back(make_mapping("Vertical: X", Qt::Key::Key_QuoteDbl, JoyconDeltas{.buttons = BUTTON_X})); + + ret.emplace_back(make_mapping("Vertical: A", Qt::Key::Key_Enter, JoyconDeltas{.buttons = BUTTON_A})); + ret.emplace_back(make_mapping("Vertical: A", Qt::Key::Key_Return, JoyconDeltas{.buttons = BUTTON_A})); + + ret.emplace_back(make_mapping("Vertical: B", Qt::Key::Key_Shift, JoyconDeltas{.buttons = BUTTON_B})); + ret.emplace_back(make_mapping("Vertical: B", Qt::Key::Key_Control, JoyconDeltas{.buttons = BUTTON_B})); + + ret.emplace_back(make_mapping("Vertical: Y", Qt::Key::Key_Slash, JoyconDeltas{.buttons = BUTTON_Y})); + ret.emplace_back(make_mapping("Vertical: Y", Qt::Key::Key_Question, JoyconDeltas{.buttons = BUTTON_Y})); + + ret.emplace_back(make_mapping("Vertical: R", Qt::Key::Key_Q, JoyconDeltas{.buttons = BUTTON_R})); + ret.emplace_back(make_mapping("Vertical: ZR", Qt::Key::Key_E, JoyconDeltas{.buttons = BUTTON_ZR})); + ret.emplace_back(make_mapping("Vertical: JS-Click", Qt::Key::Key_C, JoyconDeltas{.buttons = BUTTON_RCLICK})); + + ret.emplace_back(make_mapping("Sideways: JS Up", Qt::Key::Key_T, JoyconDeltas{.joystick_x = -1, .joystick_y = 0})); + ret.emplace_back(make_mapping("Sideways: JS Left", Qt::Key::Key_F, JoyconDeltas{.joystick_x = 0, .joystick_y = +1})); + ret.emplace_back(make_mapping("Sideways: JS Down", Qt::Key::Key_G, JoyconDeltas{.joystick_x = +1, .joystick_y = 0})); + ret.emplace_back(make_mapping("Sideways: JS Right", Qt::Key::Key_H, JoyconDeltas{.joystick_x = 0, .joystick_y = -1})); + + ret.emplace_back(make_mapping("Sideways: X", Qt::Key::Key_Up, JoyconDeltas{.buttons = BUTTON_Y})); + ret.emplace_back(make_mapping("Sideways: A", Qt::Key::Key_Right, JoyconDeltas{.buttons = BUTTON_X})); + ret.emplace_back(make_mapping("Sideways: B", Qt::Key::Key_Down, JoyconDeltas{.buttons = BUTTON_A})); + ret.emplace_back(make_mapping("Sideways: Y", Qt::Key::Key_Left, JoyconDeltas{.buttons = BUTTON_B})); + + ret.emplace_back(make_mapping("Sideways: R", Qt::Key::Key_R, JoyconDeltas{.buttons = BUTTON_R})); + ret.emplace_back(make_mapping("Sideways: ZR", Qt::Key::Key_Y, JoyconDeltas{.buttons = BUTTON_ZR})); + ret.emplace_back(make_mapping("Sideways: JS-Click", Qt::Key::Key_N, JoyconDeltas{.buttons = BUTTON_RCLICK})); + + // Other + ret.emplace_back(make_mapping("+", Qt::Key::Key_Plus, JoyconDeltas{.buttons = BUTTON_PLUS})); + ret.emplace_back(make_mapping("+", Qt::Key::Key_Equal, JoyconDeltas{.buttons = BUTTON_PLUS})); + + ret.emplace_back(make_mapping("Home", Qt::Key::Key_Home, JoyconDeltas{.buttons = BUTTON_HOME})); + ret.emplace_back(make_mapping("Home", Qt::Key::Key_Escape, JoyconDeltas{.buttons = BUTTON_HOME})); + + ret.emplace_back(make_mapping("SL", Qt::Key::Key_F1, JoyconDeltas{.buttons = BUTTON_RIGHT_SL})); + ret.emplace_back(make_mapping("SR", Qt::Key::Key_F3, JoyconDeltas{.buttons = BUTTON_RIGHT_SR})); + } + + return ret; +} + + + + + + + + + + + + + + + + + + + + + + + +KeyboardMappingOption::~KeyboardMappingOption(){ + ADVANCED_MODE.remove_listener(*this); +} +KeyboardMappingOption::KeyboardMappingOption() + : BatchOption(LockMode::UNLOCK_WHILE_RUNNING) + , DESCRIPTION( + "The following table is the mapping of keyboard keys to Switch controller presses. " + "If you wish to remap a key, click on the cell in the \"Key\" column and press the desired key. " + "You do not need to edit any of the other columns.

" + "Note for keys that change behavior when combined with " + "SHIFT or CTRL, you should include all of those combinations as well. " + "For example, the default mapping for the Y button is both '/' and '?' " + "because they are treated as different keys depending on whether SHIFT " + "is held down. Letters are exempt from this as both lower and upper case " + "letters are considered the same." + "

" + "Advanced users are free to edit the rest of the table. You can create " + "new mappings or mappings that result in multiple buttons. " + "For example, there is a special mapping for pressing A + R " + "simultaneously that is useful for CFW users who are remotely " + "controlling the program over Team Viewer." + ) + , ADVANCED_MODE( + "Unlock entire table (Advanced Mode):", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , LEFT_JOYCON0(true) + , RIGHT_JOYCON0(false) +{ + PA_ADD_STATIC(DESCRIPTION); + PA_ADD_OPTION(ADVANCED_MODE); + PA_ADD_OPTION(PRO_CONTROLLER0); + PA_ADD_OPTION(LEFT_JOYCON0); + PA_ADD_OPTION(RIGHT_JOYCON0); + ADVANCED_MODE.add_listener(*this); +} + + +void KeyboardMappingOption::load_json(const JsonValue& json){ + BatchOption::load_json(json); + KeyboardMappingOption::on_config_value_changed(this); +} +void KeyboardMappingOption::on_config_value_changed(void* object){ + PRO_CONTROLLER0.set_advanced_mode(ADVANCED_MODE); + LEFT_JOYCON0.set_advanced_mode(ADVANCED_MODE); + RIGHT_JOYCON0.set_advanced_mode(ADVANCED_MODE); +} + + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_KeyboardMapping.h b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_KeyboardMapping.h index cfbe23153a..b114ddd78f 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_KeyboardMapping.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_KeyboardMapping.h @@ -1,154 +1,154 @@ -/* Nintendo Keyboard Mapping - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_KeyboardMapping_H -#define PokemonAutomation_NintendoSwitch_KeyboardMapping_H - -#include -#include "Common/Cpp/Options/BatchOption.h" -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/StringOption.h" -#include "Common/Cpp/Options/EditableTableOption.h" -#include "Common/Cpp/Options/KeyBindingOption.h" -#include "NintendoSwitch_ControllerState.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -struct ProControllerDeltas; -struct JoyconDeltas; - - - -class ProControllerKeyMapTableRow : public EditableTableRow{ -public: - ProControllerKeyMapTableRow(EditableTableOption& parent_table); - ProControllerKeyMapTableRow( - EditableTableOption& parent_table, - bool advanced_mode, - std::string description, - Qt::Key key, - const ProControllerDeltas& deltas - ); - virtual std::unique_ptr clone() const override; - ProControllerDeltas snapshot() const; - - void set_advanced_mode(bool enabled); - -private: - std::atomic m_advanced_mode; - -public: - StringCell label; - KeyBindingCell key; - SimpleIntegerCell buttons; - SimpleIntegerCell dpad_x; - SimpleIntegerCell dpad_y; - SimpleIntegerCell left_stick_x; - SimpleIntegerCell left_stick_y; - SimpleIntegerCell right_stick_x; - SimpleIntegerCell right_stick_y; -}; - -class ProControllerKeyboardMappingTable : public EditableTableOption_t{ -public: - ProControllerKeyboardMappingTable(); - virtual std::vector make_header() const override; - - bool advanced_mode() const{ return m_advanced_mode.load(std::memory_order_relaxed); } - void set_advanced_mode(bool enabled); - - std::unique_ptr make_mapping( - std::string description, - Qt::Key key, - const ProControllerDeltas& deltas - ); - std::vector> make_defaults(); - -private: - std::atomic m_advanced_mode; -}; - - - - -class JoyconKeyMapTableRow : public EditableTableRow{ -public: - JoyconKeyMapTableRow(EditableTableOption& parent_table); - JoyconKeyMapTableRow( - EditableTableOption& parent_table, - bool advanced_mode, - std::string description, - Qt::Key key, - const JoyconDeltas& deltas - ); - virtual std::unique_ptr clone() const override; - JoyconDeltas snapshot() const; - - void set_advanced_mode(bool enabled); - -private: - std::atomic m_advanced_mode; - -public: - StringCell label; - KeyBindingCell key; - SimpleIntegerCell buttons; - SimpleIntegerCell joystick_x; - SimpleIntegerCell joystick_y; -}; - -class JoyconKeyboardMappingTable : public EditableTableOption_t{ -public: - JoyconKeyboardMappingTable(bool left); - virtual std::vector make_header() const override; - - bool advanced_mode() const{ return m_advanced_mode.load(std::memory_order_relaxed); } - void set_advanced_mode(bool enabled); - - std::unique_ptr make_mapping( - std::string description, - Qt::Key key, - const JoyconDeltas& deltas - ); - std::vector> make_defaults(bool left); - -private: - std::atomic m_advanced_mode; -}; - - - - - - - - -class KeyboardMappingOption : public BatchOption, private ConfigOption::Listener{ -public: - ~KeyboardMappingOption(); - KeyboardMappingOption(); - -private: - virtual void load_json(const JsonValue& json) override; - virtual void on_config_value_changed(void* object) override; - -public: - StaticTextOption DESCRIPTION; - BooleanCheckBoxOption ADVANCED_MODE; - ProControllerKeyboardMappingTable PRO_CONTROLLER; - JoyconKeyboardMappingTable LEFT_JOYCON; - JoyconKeyboardMappingTable RIGHT_JOYCON; -}; - - - -} -} -#endif +/* Nintendo Keyboard Mapping + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_KeyboardMapping_H +#define PokemonAutomation_NintendoSwitch_KeyboardMapping_H + +#include +#include "Common/Cpp/Options/BatchOption.h" +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/StringOption.h" +#include "Common/Cpp/Options/EditableTableOption.h" +#include "Common/Cpp/Options/KeyBindingOption.h" +#include "NintendoSwitch_ControllerState.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +struct ProControllerDeltas; +struct JoyconDeltas; + + + +class ProControllerKeyMapTableRow : public EditableTableRow{ +public: + ProControllerKeyMapTableRow(EditableTableOption& parent_table); + ProControllerKeyMapTableRow( + EditableTableOption& parent_table, + bool advanced_mode, + std::string description, + Qt::Key key, + const ProControllerDeltas& deltas + ); + virtual std::unique_ptr clone() const override; + ProControllerDeltas snapshot() const; + + void set_advanced_mode(bool enabled); + +private: + std::atomic m_advanced_mode; + +public: + StringCell label; + KeyBindingCell key; + SimpleIntegerCell buttons; + SimpleIntegerCell dpad_x; + SimpleIntegerCell dpad_y; + SimpleIntegerCell left_stick_x; + SimpleIntegerCell left_stick_y; + SimpleIntegerCell right_stick_x; + SimpleIntegerCell right_stick_y; +}; + +class ProControllerKeyboardMappingTable : public EditableTableOption_t{ +public: + ProControllerKeyboardMappingTable(); + virtual std::vector make_header() const override; + + bool advanced_mode() const{ return m_advanced_mode.load(std::memory_order_relaxed); } + void set_advanced_mode(bool enabled); + + std::unique_ptr make_mapping( + std::string description, + Qt::Key key, + const ProControllerDeltas& deltas + ); + std::vector> make_defaults(); + +private: + std::atomic m_advanced_mode; +}; + + + + +class JoyconKeyMapTableRow : public EditableTableRow{ +public: + JoyconKeyMapTableRow(EditableTableOption& parent_table); + JoyconKeyMapTableRow( + EditableTableOption& parent_table, + bool advanced_mode, + std::string description, + Qt::Key key, + const JoyconDeltas& deltas + ); + virtual std::unique_ptr clone() const override; + JoyconDeltas snapshot() const; + + void set_advanced_mode(bool enabled); + +private: + std::atomic m_advanced_mode; + +public: + StringCell label; + KeyBindingCell key; + SimpleIntegerCell buttons; + SimpleIntegerCell joystick_x; + SimpleIntegerCell joystick_y; +}; + +class JoyconKeyboardMappingTable : public EditableTableOption_t{ +public: + JoyconKeyboardMappingTable(bool left); + virtual std::vector make_header() const override; + + bool advanced_mode() const{ return m_advanced_mode.load(std::memory_order_relaxed); } + void set_advanced_mode(bool enabled); + + std::unique_ptr make_mapping( + std::string description, + Qt::Key key, + const JoyconDeltas& deltas + ); + std::vector> make_defaults(bool left); + +private: + std::atomic m_advanced_mode; +}; + + + + + + + + +class KeyboardMappingOption : public BatchOption, private ConfigOption::Listener{ +public: + ~KeyboardMappingOption(); + KeyboardMappingOption(); + +private: + virtual void load_json(const JsonValue& json) override; + virtual void on_config_value_changed(void* object) override; + +public: + StaticTextOption DESCRIPTION; + BooleanCheckBoxOption ADVANCED_MODE; + ProControllerKeyboardMappingTable PRO_CONTROLLER0; + JoyconKeyboardMappingTable LEFT_JOYCON0; + JoyconKeyboardMappingTable RIGHT_JOYCON0; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ProController.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ProController.cpp index 20a97aef13..abb43b8595 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ProController.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ProController.cpp @@ -1,110 +1,110 @@ -/* Nintendo Switch Controller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "CommonTools/Async/InterruptableCommands.tpp" -#include "CommonTools/Async/SuperControlSession.tpp" -#include "Controllers/KeyboardInput/KeyboardInput.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch_VirtualControllerState.h" -#include "NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - -// Instantiate some template helper classes. -template class AsyncCommandSession; -template class SuperControlSession; - -namespace NintendoSwitch{ - -using namespace std::chrono_literals; - - - - - - -class ProController::KeyboardManager final : - public PokemonAutomation::KeyboardManager -{ -public: - KeyboardManager(ProController& controller) - : PokemonAutomation::KeyboardManager(controller) - { - std::vector> mapping = - ConsoleSettings::instance().KEYBOARD_MAPPINGS.PRO_CONTROLLER.current_refs(); - for (const auto& deltas : mapping){ - const ProControllerKeyMapTableRow& row = static_cast(*deltas); - m_mapping[(Qt::Key)(uint32_t)row.key] += row.snapshot(); - } - start(); - } - ~KeyboardManager(){ - stop(); - } - virtual void send_state(const ControllerState& state) override{ - const ProControllerState& switch_state = static_cast(state); -#if 0 - m_controller.logger().log( - "VirtualController: (" + button_to_string(switch_state.buttons) + - "), dpad(" + dpad_to_string(switch_state.dpad) + - "), LJ(" + std::to_string(switch_state.left_x) + "," + std::to_string(switch_state.left_y) + - "), RJ(" + std::to_string(switch_state.right_x) + "," + std::to_string(switch_state.right_y) + - ")", - COLOR_DARKGREEN - ); -#endif - WriteSpinLock lg(m_lock); - if (m_controller == nullptr){ - return; - } - Milliseconds ticksize = m_controller->ticksize(); - static_cast(m_controller)->issue_full_controller_state( - nullptr, - ticksize == Milliseconds::zero() ? 2000ms : ticksize * 255, - switch_state.buttons, - switch_state.dpad, - switch_state.left_x, - switch_state.left_y, - switch_state.right_x, - switch_state.right_y - ); - } -}; - - - -ProController::ProController() - : m_keyboard_manager(CONSTRUCT_TOKEN, *this) -{ - -} -ProController::~ProController(){ - -} -void ProController::stop() noexcept{ - m_keyboard_manager->stop(); -} - - -void ProController::keyboard_release_all(){ - m_keyboard_manager->clear_state(); -} -void ProController::keyboard_press(const QKeyEvent& event){ - m_keyboard_manager->on_key_press(event); -} -void ProController::keyboard_release(const QKeyEvent& event){ - m_keyboard_manager->on_key_release(event); -} - - - - - - - -} -} +/* Nintendo Switch Controller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "CommonTools/Async/InterruptableCommands.tpp" +#include "CommonTools/Async/SuperControlSession.tpp" +#include "Controllers/KeyboardInput/KeyboardInput.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch_VirtualControllerState.h" +#include "NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + +// Instantiate some template helper classes. +template class AsyncCommandSession; +template class SuperControlSession; + +namespace NintendoSwitch{ + +using namespace std::chrono_literals; + + + + + + +class ProController::KeyboardManager final : + public PokemonAutomation::KeyboardManager +{ +public: + KeyboardManager(Logger& logger, ProController& controller) + : PokemonAutomation::KeyboardManager(logger, controller) + { + std::vector> mapping = + ConsoleSettings::instance().KEYBOARD_MAPPINGS.PRO_CONTROLLER0.current_refs(); + for (const auto& deltas : mapping){ + const ProControllerKeyMapTableRow& row = static_cast(*deltas); + m_mapping[(Qt::Key)(uint32_t)row.key] += row.snapshot(); + } + start(); + } + ~KeyboardManager(){ + stop(); + } + virtual void send_state(const ControllerState& state) override{ + const ProControllerState& switch_state = static_cast(state); +#if 0 + m_controller.logger().log( + "VirtualController: (" + button_to_string(switch_state.buttons) + + "), dpad(" + dpad_to_string(switch_state.dpad) + + "), LJ(" + std::to_string(switch_state.left_x) + "," + std::to_string(switch_state.left_y) + + "), RJ(" + std::to_string(switch_state.right_x) + "," + std::to_string(switch_state.right_y) + + ")", + COLOR_DARKGREEN + ); +#endif + WriteSpinLock lg(m_lock); + if (m_controller == nullptr){ + return; + } + Milliseconds ticksize = m_controller->ticksize(); + static_cast(m_controller)->issue_full_controller_state( + nullptr, + ticksize == Milliseconds::zero() ? 2000ms : ticksize * 255, + switch_state.buttons, + switch_state.dpad, + switch_state.left_x, + switch_state.left_y, + switch_state.right_x, + switch_state.right_y + ); + } +}; + + + +ProController::ProController(Logger& logger) + : m_keyboard_manager(CONSTRUCT_TOKEN, logger, *this) +{ + +} +ProController::~ProController(){ + +} +void ProController::stop() noexcept{ + m_keyboard_manager->stop(); +} + + +void ProController::keyboard_release_all(){ + m_keyboard_manager->clear_state(); +} +void ProController::keyboard_press(const QKeyEvent& event){ + m_keyboard_manager->on_key_press(event); +} +void ProController::keyboard_release(const QKeyEvent& event){ + m_keyboard_manager->on_key_release(event); +} + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ProController.h b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ProController.h index 16c6724d89..16a3c01ddc 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ProController.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ProController.h @@ -1,233 +1,235 @@ -/* Nintendo Switch Pro Controller - * - * From: https://github.com/PokemonAutomation/ - * - * This is the raw (full) controller API that is exposed to programs. - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_Controller_H -#define PokemonAutomation_NintendoSwitch_Controller_H - -#include "Common/Cpp/Containers/Pimpl.h" -#include "NintendoSwitch_ControllerState.h" -#include "Controllers/Controller.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class ProController; -using ProControllerContext = ControllerContext; - - -constexpr Button VALID_PRO_CONTROLLER_BUTTONS = - BUTTON_Y | - BUTTON_B | - BUTTON_A | - BUTTON_X | - BUTTON_L | - BUTTON_R | - BUTTON_ZL | - BUTTON_ZR | - BUTTON_MINUS | - BUTTON_PLUS | - BUTTON_LCLICK | - BUTTON_RCLICK | - BUTTON_HOME | - BUTTON_CAPTURE | - BUTTON_UP | - BUTTON_RIGHT | - BUTTON_DOWN | - BUTTON_LEFT; - - - -// -// This is the generic interface to a Switch pro controller. -// -class ProController : public AbstractController{ -public: - using ContextType = ProControllerContext; - - ProController(); - virtual ~ProController(); - - // Must call before destruction begins. - void stop() noexcept; - - -public: - // Standard Commands - - // Press all the buttons set in the bitfield simultaneously. - // This command will wait until all the selected buttons are ready to - // ensure that they are all dispatched simultaneously. - virtual void issue_buttons( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - Button button - ) = 0; - - // Dpad - virtual void issue_dpad( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition position - ) = 0; - - // Joysticks - virtual void issue_left_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y - ) = 0; - virtual void issue_right_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y - ) = 0; - - // Gyro: Accelerometer (experimental - API subject to change) - virtual void issue_gyro_accel_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) = 0; - virtual void issue_gyro_accel_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) = 0; - virtual void issue_gyro_accel_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) = 0; - virtual void issue_gyro_rotate_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) = 0; - virtual void issue_gyro_rotate_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) = 0; - virtual void issue_gyro_rotate_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) = 0; - - // - // Press all the following buttons/joysticks simultaneously for the - // specified duration. No wait is added at the end. Thus you can issue - // these back-to-back to simulate buttons being pressed and released - // concurrently with other buttons being held down the whole time. - // - // This command will wait until the controller is fully idle (including - // cooldowns) before it starts. This ensures that everything is issued - // simultaneously. In other words, there is an implied call to - // "issue_barrier()" before executing the state. - // - // The sole purpose of this function is for keyboard commands. - // For programs, it is easier to use the individual button/joystick - // functions above. - // - // If we need to support new Switch controller functionality - // (such as Joycon gyro or new stuff in Switch 2), we can simply add - // overloads to this and gate them behind features. - // - virtual void issue_full_controller_state( - const Cancellable* cancellable, - Milliseconds duration, - Button button, - DpadPosition position, - uint8_t left_x, uint8_t left_y, - uint8_t right_x, uint8_t right_y - ) = 0; - - -public: - // - // High speed Macros - // - // Be mindful when calling these mashing functions on a tick imprecise - // controller. You can guarantee that some (most) of them will be dropped. - // - // Even if you are on a tick-precise controller, it is not advised to call - // these if you are micromanaging with tick-level granularity. The exact - // timing characteristics and button selection is not specified and may be - // context and implementation-dependent. - // - - // Mash a button as quickly as possible. - virtual void issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button - ) = 0; - - // Alternate pressing "button0" and "button1" as quickly as possible. - // "button0" will always be pressed first. - // Both buttons will be pressed at least once. - virtual void issue_mash_button( - const Cancellable* cancellable, - Milliseconds dutation, - Button button0, Button button1 - ) = 0; - - // In situations where A, ZL, and RL all do the same thing, use all 3 of - // them to logically mash A much faster than is possible with just one - // button. - virtual void issue_mash_AZs( - const Cancellable* cancellable, - Milliseconds duration - ) = 0; - - // - // Send a scroll command in the specified direction. - // - // This will use either the dpad or either joystick - whichever is - // available first in the pipeline. - // - // The intended use-case of this for fast scrolling in the system menu - // where all 3 buttons have the same effect and can be used at the same - // time. - // - virtual void issue_system_scroll( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition direction // Diagonals not allowed. - ) = 0; - - -public: - // Keyboard Input - - virtual void keyboard_release_all() override; - virtual void keyboard_press(const QKeyEvent& event) override; - virtual void keyboard_release(const QKeyEvent& event) override; - - -private: - class KeyboardManager; - Pimpl m_keyboard_manager; -}; - - - - - - - - - -} -} -#endif +/* Nintendo Switch Pro Controller + * + * From: https://github.com/PokemonAutomation/ + * + * This is the raw (full) controller API that is exposed to programs. + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_Controller_H +#define PokemonAutomation_NintendoSwitch_Controller_H + +#include "Common/Cpp/Containers/Pimpl.h" +#include "NintendoSwitch_ControllerState.h" +#include "Controllers/Controller.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class ProController; +using ProControllerContext = ControllerContext; + + +constexpr Button VALID_PRO_CONTROLLER_BUTTONS = + BUTTON_Y | + BUTTON_B | + BUTTON_A | + BUTTON_X | + BUTTON_L | + BUTTON_R | + BUTTON_ZL | + BUTTON_ZR | + BUTTON_MINUS | + BUTTON_PLUS | + BUTTON_LCLICK | + BUTTON_RCLICK | + BUTTON_HOME | + BUTTON_CAPTURE | + BUTTON_UP | + BUTTON_RIGHT | + BUTTON_DOWN | + BUTTON_LEFT | + BUTTON_GR | + BUTTON_GL; + + + +// +// This is the generic interface to a Switch pro controller. +// +class ProController : public AbstractController{ +public: + using ContextType = ProControllerContext; + + ProController(Logger& logger); + virtual ~ProController(); + + // Must call before destruction begins. + void stop() noexcept; + + +public: + // Standard Commands + + // Press all the buttons set in the bitfield simultaneously. + // This command will wait until all the selected buttons are ready to + // ensure that they are all dispatched simultaneously. + virtual void issue_buttons( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + Button button + ) = 0; + + // Dpad + virtual void issue_dpad( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition position + ) = 0; + + // Joysticks + virtual void issue_left_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y + ) = 0; + virtual void issue_right_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y + ) = 0; + + // Gyro: Accelerometer (experimental - API subject to change) + virtual void issue_gyro_accel_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) = 0; + virtual void issue_gyro_accel_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) = 0; + virtual void issue_gyro_accel_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) = 0; + virtual void issue_gyro_rotate_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) = 0; + virtual void issue_gyro_rotate_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) = 0; + virtual void issue_gyro_rotate_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) = 0; + + // + // Press all the following buttons/joysticks simultaneously for the + // specified duration. No wait is added at the end. Thus you can issue + // these back-to-back to simulate buttons being pressed and released + // concurrently with other buttons being held down the whole time. + // + // This command will wait until the controller is fully idle (including + // cooldowns) before it starts. This ensures that everything is issued + // simultaneously. In other words, there is an implied call to + // "issue_barrier()" before executing the state. + // + // The sole purpose of this function is for keyboard commands. + // For programs, it is easier to use the individual button/joystick + // functions above. + // + // If we need to support new Switch controller functionality + // (such as Joycon gyro or new stuff in Switch 2), we can simply add + // overloads to this and gate them behind features. + // + virtual void issue_full_controller_state( + const Cancellable* cancellable, + Milliseconds duration, + Button button, + DpadPosition position, + uint8_t left_x, uint8_t left_y, + uint8_t right_x, uint8_t right_y + ) = 0; + + +public: + // + // High speed Macros + // + // Be mindful when calling these mashing functions on a tick imprecise + // controller. You can guarantee that some (most) of them will be dropped. + // + // Even if you are on a tick-precise controller, it is not advised to call + // these if you are micromanaging with tick-level granularity. The exact + // timing characteristics and button selection is not specified and may be + // context and implementation-dependent. + // + + // Mash a button as quickly as possible. + virtual void issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button + ) = 0; + + // Alternate pressing "button0" and "button1" as quickly as possible. + // "button0" will always be pressed first. + // Both buttons will be pressed at least once. + virtual void issue_mash_button( + const Cancellable* cancellable, + Milliseconds dutation, + Button button0, Button button1 + ) = 0; + + // In situations where A, ZL, and RL all do the same thing, use all 3 of + // them to logically mash A much faster than is possible with just one + // button. + virtual void issue_mash_AZs( + const Cancellable* cancellable, + Milliseconds duration + ) = 0; + + // + // Send a scroll command in the specified direction. + // + // This will use either the dpad or either joystick - whichever is + // available first in the pipeline. + // + // The intended use-case of this for fast scrolling in the system menu + // where all 3 buttons have the same effect and can be used at the same + // time. + // + virtual void issue_system_scroll( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition direction // Diagonals not allowed. + ) = 0; + + +public: + // Keyboard Input + + virtual void keyboard_release_all() override; + virtual void keyboard_press(const QKeyEvent& event) override; + virtual void keyboard_release(const QKeyEvent& event) override; + + +private: + class KeyboardManager; + Pimpl m_keyboard_manager; +}; + + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.cpp index 2af3cb9758..6a82c41331 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.cpp @@ -1,209 +1,209 @@ -/* Virtual Controller State - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch_VirtualControllerState.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -using namespace std::chrono_literals; - - - - - -void ProControllerState::clear(){ - buttons = BUTTON_NONE; - dpad = DPAD_NONE; - left_x = 128; - left_y = 128; - right_x = 128; - right_y = 128; -} -bool ProControllerState::operator==(const ControllerState& x) const{ - if (typeid(*this) != typeid(x)){ - return false; - } - - const ProControllerState& r = static_cast(x); - - if (buttons != r.buttons){ - return false; - } - if (dpad != r.dpad){ - return false; - } - if (left_x != r.left_x){ - return false; - } - if (left_y != r.left_y){ - return false; - } - if (right_x != r.right_x){ - return false; - } - if (right_y != r.right_y){ - return false; - } - return true; -} -bool ProControllerState::is_neutral() const{ - return buttons == 0 - && dpad == DPAD_NONE - && left_x == 128 - && left_y == 128 - && right_x == 128 - && right_y == 128; -} - - -void ProControllerDeltas::operator+=(const ProControllerDeltas& x){ - buttons |= x.buttons; - dpad_x += x.dpad_x; - dpad_y += x.dpad_y; - left_x += x.left_x; - left_y += x.left_y; - right_x += x.right_x; - right_y += x.right_y; -} -bool ProControllerDeltas::to_state(ProControllerState& state) const{ - bool neutral; - - state.buttons = buttons; - neutral = buttons == 0; - - state.dpad = DPAD_NONE; - if (dpad_x != 0 || dpad_y != 0){ - neutral = false; - do{ - if (dpad_x == 0){ - state.dpad = dpad_y > 0 ? DPAD_DOWN : DPAD_UP; - break; - } - if (dpad_y == 0){ - state.dpad = dpad_x > 0 ? DPAD_RIGHT : DPAD_LEFT; - break; - } - if (dpad_x < 0 && dpad_y < 0){ - state.dpad = DPAD_UP_LEFT; - break; - } - if (dpad_x < 0 && dpad_y > 0){ - state.dpad = DPAD_DOWN_LEFT; - break; - } - if (dpad_x > 0 && dpad_y > 0){ - state.dpad = DPAD_DOWN_RIGHT; - break; - } - if (dpad_x > 0 && dpad_y < 0){ - state.dpad = DPAD_UP_RIGHT; - break; - } - }while (false); - } - - state.left_x = 128; - state.left_y = 128; - if (left_x != 0 || left_y != 0){ - neutral = false; - int mag = std::abs(left_x) > std::abs(left_y) - ? std::abs(left_x) - : std::abs(left_y); - state.left_x = (uint8_t)std::min(128 * left_x / mag + 128, 255); - state.left_y = (uint8_t)std::min(128 * left_y / mag + 128, 255); - } - - state.right_x = 128; - state.right_y = 128; - if (right_x != 0 || right_y != 0){ - neutral = false; - int mag = std::abs(right_x) > std::abs(right_y) - ? std::abs(right_x) - : std::abs(right_y); - state.right_x = (uint8_t)std::min(128 * right_x / mag + 128, 255); - state.right_y = (uint8_t)std::min(128 * right_y / mag + 128, 255); - } - - return neutral; -} - - - - - - -void JoyconState::clear(){ - buttons = BUTTON_NONE; - joystick_x = 128; - joystick_y = 128; -} -bool JoyconState::operator==(const ControllerState& x) const{ - if (typeid(*this) != typeid(x)){ - return false; - } - - const JoyconState& r = static_cast(x); - - if (buttons != r.buttons){ - return false; - } - if (joystick_x != r.joystick_x){ - return false; - } - if (joystick_y != r.joystick_y){ - return false; - } - return true; -} -bool JoyconState::is_neutral() const{ - return buttons == 0 - && joystick_x == 128 - && joystick_y == 128; -} - - -void JoyconDeltas::operator+=(const JoyconDeltas& x){ - buttons |= x.buttons; - joystick_x += x.joystick_x; - joystick_y += x.joystick_y; -} -bool JoyconDeltas::to_state(JoyconState& state) const{ - bool neutral; - - state.buttons = buttons; - neutral = buttons == 0; - - state.joystick_x = 128; - state.joystick_y = 128; - if (joystick_x != 0 || joystick_y != 0){ - neutral = false; - int mag = std::abs(joystick_x) > std::abs(joystick_y) - ? std::abs(joystick_x) - : std::abs(joystick_y); - state.joystick_x = (uint8_t)std::min(128 * joystick_x / mag + 128, 255); - state.joystick_y = (uint8_t)std::min(128 * joystick_y / mag + 128, 255); - } - - return neutral; -} - - - - - - - - - - - -} -} +/* Virtual Controller State + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch_VirtualControllerState.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +using namespace std::chrono_literals; + + + + + +void ProControllerState::clear(){ + buttons = BUTTON_NONE; + dpad = DPAD_NONE; + left_x = 128; + left_y = 128; + right_x = 128; + right_y = 128; +} +bool ProControllerState::operator==(const ControllerState& x) const{ + if (typeid(*this) != typeid(x)){ + return false; + } + + const ProControllerState& r = static_cast(x); + + if (buttons != r.buttons){ + return false; + } + if (dpad != r.dpad){ + return false; + } + if (left_x != r.left_x){ + return false; + } + if (left_y != r.left_y){ + return false; + } + if (right_x != r.right_x){ + return false; + } + if (right_y != r.right_y){ + return false; + } + return true; +} +bool ProControllerState::is_neutral() const{ + return buttons == 0 + && dpad == DPAD_NONE + && left_x == 128 + && left_y == 128 + && right_x == 128 + && right_y == 128; +} + + +void ProControllerDeltas::operator+=(const ProControllerDeltas& x){ + buttons |= x.buttons; + dpad_x += x.dpad_x; + dpad_y += x.dpad_y; + left_x += x.left_x; + left_y += x.left_y; + right_x += x.right_x; + right_y += x.right_y; +} +bool ProControllerDeltas::to_state(ProControllerState& state) const{ + bool neutral; + + state.buttons = buttons; + neutral = buttons == 0; + + state.dpad = DPAD_NONE; + if (dpad_x != 0 || dpad_y != 0){ + neutral = false; + do{ + if (dpad_x == 0){ + state.dpad = dpad_y > 0 ? DPAD_DOWN : DPAD_UP; + break; + } + if (dpad_y == 0){ + state.dpad = dpad_x > 0 ? DPAD_RIGHT : DPAD_LEFT; + break; + } + if (dpad_x < 0 && dpad_y < 0){ + state.dpad = DPAD_UP_LEFT; + break; + } + if (dpad_x < 0 && dpad_y > 0){ + state.dpad = DPAD_DOWN_LEFT; + break; + } + if (dpad_x > 0 && dpad_y > 0){ + state.dpad = DPAD_DOWN_RIGHT; + break; + } + if (dpad_x > 0 && dpad_y < 0){ + state.dpad = DPAD_UP_RIGHT; + break; + } + }while (false); + } + + state.left_x = 128; + state.left_y = 128; + if (left_x != 0 || left_y != 0){ + neutral = false; + int mag = std::abs(left_x) > std::abs(left_y) + ? std::abs(left_x) + : std::abs(left_y); + state.left_x = (uint8_t)std::min(128 * left_x / mag + 128, 255); + state.left_y = (uint8_t)std::min(128 * left_y / mag + 128, 255); + } + + state.right_x = 128; + state.right_y = 128; + if (right_x != 0 || right_y != 0){ + neutral = false; + int mag = std::abs(right_x) > std::abs(right_y) + ? std::abs(right_x) + : std::abs(right_y); + state.right_x = (uint8_t)std::min(128 * right_x / mag + 128, 255); + state.right_y = (uint8_t)std::min(128 * right_y / mag + 128, 255); + } + + return neutral; +} + + + + + + +void JoyconState::clear(){ + buttons = BUTTON_NONE; + joystick_x = 128; + joystick_y = 128; +} +bool JoyconState::operator==(const ControllerState& x) const{ + if (typeid(*this) != typeid(x)){ + return false; + } + + const JoyconState& r = static_cast(x); + + if (buttons != r.buttons){ + return false; + } + if (joystick_x != r.joystick_x){ + return false; + } + if (joystick_y != r.joystick_y){ + return false; + } + return true; +} +bool JoyconState::is_neutral() const{ + return buttons == 0 + && joystick_x == 128 + && joystick_y == 128; +} + + +void JoyconDeltas::operator+=(const JoyconDeltas& x){ + buttons |= x.buttons; + joystick_x += x.joystick_x; + joystick_y += x.joystick_y; +} +bool JoyconDeltas::to_state(JoyconState& state) const{ + bool neutral; + + state.buttons = buttons; + neutral = buttons == 0; + + state.joystick_x = 128; + state.joystick_y = 128; + if (joystick_x != 0 || joystick_y != 0){ + neutral = false; + int mag = std::abs(joystick_x) > std::abs(joystick_y) + ? std::abs(joystick_x) + : std::abs(joystick_y); + state.joystick_x = (uint8_t)std::min(128 * joystick_x / mag + 128, 255); + state.joystick_y = (uint8_t)std::min(128 * joystick_y / mag + 128, 255); + } + + return neutral; +} + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.h b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.h index 92358bb845..01b07f25a0 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.h @@ -1,79 +1,79 @@ -/* Virtual Controller State - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_VirtualControllerState_H -#define PokemonAutomation_NintendoSwitch_VirtualControllerState_H - -#include "Controllers/KeyboardInput/KeyboardInput.h" -#include "NintendoSwitch_ControllerState.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class ProControllerState : public ControllerState{ -public: - virtual void clear() override; - virtual bool operator==(const ControllerState& x) const override; - virtual bool is_neutral() const override; - -public: - Button buttons = BUTTON_NONE; - DpadPosition dpad = DPAD_NONE; - uint8_t left_x = 128; - uint8_t left_y = 128; - uint8_t right_x = 128; - uint8_t right_y = 128; -}; - -struct ProControllerDeltas{ - Button buttons = BUTTON_NONE; - int dpad_x = 0; - int dpad_y = 0; - int left_x = 0; - int left_y = 0; - int right_x = 0; - int right_y = 0; - - void operator+=(const ProControllerDeltas& x); - - // Returns true if neutral. - bool to_state(ProControllerState& state) const; -}; - - - -class JoyconState : public ControllerState{ -public: - virtual void clear() override; - virtual bool operator==(const ControllerState& x) const override; - virtual bool is_neutral() const override; - -public: - Button buttons = BUTTON_NONE; - uint8_t joystick_x = 128; - uint8_t joystick_y = 128; -}; - -struct JoyconDeltas{ - Button buttons = BUTTON_NONE; - int joystick_x = 0; - int joystick_y = 0; - - void operator+=(const JoyconDeltas& x); - - // Returns true if neutral. - bool to_state(JoyconState& state) const; -}; - - - - - - -} -} -#endif +/* Virtual Controller State + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_VirtualControllerState_H +#define PokemonAutomation_NintendoSwitch_VirtualControllerState_H + +#include "Controllers/KeyboardInput/KeyboardInput.h" +#include "NintendoSwitch_ControllerState.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class ProControllerState : public ControllerState{ +public: + virtual void clear() override; + virtual bool operator==(const ControllerState& x) const override; + virtual bool is_neutral() const override; + +public: + Button buttons = BUTTON_NONE; + DpadPosition dpad = DPAD_NONE; + uint8_t left_x = 128; + uint8_t left_y = 128; + uint8_t right_x = 128; + uint8_t right_y = 128; +}; + +struct ProControllerDeltas{ + Button buttons = BUTTON_NONE; + int dpad_x = 0; + int dpad_y = 0; + int left_x = 0; + int left_y = 0; + int right_x = 0; + int right_y = 0; + + void operator+=(const ProControllerDeltas& x); + + // Returns true if neutral. + bool to_state(ProControllerState& state) const; +}; + + + +class JoyconState : public ControllerState{ +public: + virtual void clear() override; + virtual bool operator==(const ControllerState& x) const override; + virtual bool is_neutral() const override; + +public: + Button buttons = BUTTON_NONE; + uint8_t joystick_x = 128; + uint8_t joystick_y = 128; +}; + +struct JoyconDeltas{ + Button buttons = BUTTON_NONE; + int joystick_x = 0; + int joystick_y = 0; + + void operator+=(const JoyconDeltas& x); + + // Returns true if neutral. + bool to_state(JoyconState& state) const; +}; + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_Controller.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_Controller.cpp index 9e44ef6d34..6dee96bfad 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_Controller.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_Controller.cpp @@ -1,106 +1,106 @@ -/* SerialPABotBase: Controller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "ClientSource/Connection/BotBaseMessage.h" -#include "Controllers/ControllerTypeStrings.h" -#include "Controllers/ControllerCapability.h" -#include "NintendoSwitch_SerialPABotBase_Controller.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -using namespace std::chrono_literals; - - - - -SerialPABotBase_Controller::SerialPABotBase_Controller( - Logger& logger, - ControllerType controller_type, - SerialPABotBase::SerialPABotBase_Connection& connection -) - : ControllerWithScheduler(logger) - , m_handle(connection) - , m_serial(connection.botbase()) -{ - if (!connection.is_ready()){ - return; - } - - // Check compatibility. - - ControllerModeStatus mode_status = connection.controller_mode_status(); - logger.log( - "SerialPABotBase_Controller(): ControllerType = " + - CONTROLLER_TYPE_STRINGS.get_string(mode_status.current_controller) - ); - - std::map& controllers = mode_status.supported_controllers; - auto iter = controllers.find(controller_type); - if (iter != controllers.end()){ - m_supported_features = std::move(iter->second); - } -} - - - - -void SerialPABotBase_Controller::cancel_all_commands(){ - std::lock_guard lg(m_state_lock); - if (!is_ready()){ - throw InvalidConnectionStateException(error_string()); - } - m_serial->stop_all_commands(); - this->clear_on_next(); -} -void SerialPABotBase_Controller::replace_on_next_command(){ - std::lock_guard lg(m_state_lock); - if (!is_ready()){ - throw InvalidConnectionStateException(error_string()); - } - m_serial->next_command_interrupt(); - this->clear_on_next(); -} - - -void SerialPABotBase_Controller::wait_for_all(const Cancellable* cancellable){ - std::lock_guard lg0(m_issue_lock); - { - std::lock_guard lg1(m_state_lock); - - ThrottleScope scope(m_logging_throttler); - if (scope){ - m_logger.log("wait_for_all()", COLOR_DARKGREEN); - } - - if (!is_ready()){ - throw InvalidConnectionStateException(error_string()); - } - - this->issue_wait_for_all(cancellable); - } - m_serial->wait_for_all_requests(cancellable); -} - - - - - - - - - - - - - -} -} +/* SerialPABotBase: Controller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "ClientSource/Connection/BotBaseMessage.h" +#include "Controllers/ControllerTypeStrings.h" +#include "Controllers/ControllerCapability.h" +#include "NintendoSwitch_SerialPABotBase_Controller.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +using namespace std::chrono_literals; + + + + +SerialPABotBase_Controller::SerialPABotBase_Controller( + Logger& logger, + ControllerType controller_type, + SerialPABotBase::SerialPABotBase_Connection& connection +) + : ControllerWithScheduler(logger) + , m_handle(connection) + , m_serial(connection.botbase()) +{ + if (!connection.is_ready()){ + return; + } + + // Check compatibility. + + ControllerModeStatus mode_status = connection.controller_mode_status(); + logger.log( + "SerialPABotBase_Controller(): ControllerType = " + + CONTROLLER_TYPE_STRINGS.get_string(mode_status.current_controller) + ); + + std::map& controllers = mode_status.supported_controllers; + auto iter = controllers.find(controller_type); + if (iter != controllers.end()){ + m_supported_features = std::move(iter->second); + } +} + + + + +void SerialPABotBase_Controller::cancel_all_commands(){ + std::lock_guard lg(m_state_lock); + if (!is_ready()){ + throw InvalidConnectionStateException(error_string()); + } + m_serial->stop_all_commands(); + this->clear_on_next(); +} +void SerialPABotBase_Controller::replace_on_next_command(){ + std::lock_guard lg(m_state_lock); + if (!is_ready()){ + throw InvalidConnectionStateException(error_string()); + } + m_serial->next_command_interrupt(); + this->clear_on_next(); +} + + +void SerialPABotBase_Controller::wait_for_all(const Cancellable* cancellable){ + std::lock_guard lg0(m_issue_lock); + { + std::lock_guard lg1(m_state_lock); + + ThrottleScope scope(m_logging_throttler); + if (scope){ + m_logger.log("wait_for_all()", COLOR_DARKGREEN); + } + + if (!is_ready()){ + throw InvalidConnectionStateException(error_string()); + } + + this->issue_wait_for_all(cancellable); + } + m_serial->wait_for_all_requests(cancellable); +} + + + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_Controller.h b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_Controller.h index 953e73c3c2..4e0d9d884d 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_Controller.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_Controller.h @@ -1,68 +1,68 @@ -/* SerialPABotBase: Pro Controller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_SerialPABotBase_Controller_H -#define PokemonAutomation_NintendoSwitch_SerialPABotBase_Controller_H - -#include "ClientSource/Connection/BotBase.h" -#include "Controllers/SerialPABotBase/SerialPABotBase_Connection.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class SerialPABotBase_Controller : public ControllerWithScheduler{ -public: - SerialPABotBase_Controller( - Logger& logger, - ControllerType controller_type, - SerialPABotBase::SerialPABotBase_Connection& connection - ); - - void stop_with_error(std::string error_message){ - { - WriteSpinLock lg(m_error_lock); - m_error_string = error_message; - } - m_serial->stop(std::move(error_message)); - } - - bool is_ready() const{ - return m_serial - && m_serial->state() == BotBaseController::State::RUNNING - && m_handle.is_ready(); - } - std::string error_string() const{ - ReadSpinLock lg(m_error_lock); - return m_error_string; - } - - -public: - void cancel_all_commands(); - void replace_on_next_command(); - - void wait_for_all(const Cancellable* cancellable); - - -protected: - // These are set on construction and never changed again. So it is safe to - // access these asynchronously. - SerialPABotBase::SerialPABotBase_Connection& m_handle; - BotBaseController* m_serial; - ControllerFeatures m_supported_features; - - mutable SpinLock m_error_lock; - std::string m_error_string; -}; - - - - -} -} -#endif +/* SerialPABotBase: Pro Controller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SerialPABotBase_Controller_H +#define PokemonAutomation_NintendoSwitch_SerialPABotBase_Controller_H + +#include "ClientSource/Connection/BotBase.h" +#include "Controllers/SerialPABotBase/SerialPABotBase_Connection.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class SerialPABotBase_Controller : public ControllerWithScheduler{ +public: + SerialPABotBase_Controller( + Logger& logger, + ControllerType controller_type, + SerialPABotBase::SerialPABotBase_Connection& connection + ); + + void stop_with_error(std::string error_message){ + { + WriteSpinLock lg(m_error_lock); + m_error_string = error_message; + } + m_serial->stop(std::move(error_message)); + } + + bool is_ready() const{ + return m_serial + && m_serial->state() == BotBaseController::State::RUNNING + && m_handle.is_ready(); + } + std::string error_string() const{ + ReadSpinLock lg(m_error_lock); + return m_error_string; + } + + +public: + void cancel_all_commands(); + void replace_on_next_command(); + + void wait_for_all(const Cancellable* cancellable); + + +protected: + // These are set on construction and never changed again. So it is safe to + // access these asynchronously. + SerialPABotBase::SerialPABotBase_Connection& m_handle; + BotBaseController* m_serial; + ControllerFeatures m_supported_features; + + mutable SpinLock m_error_lock; + std::string m_error_string; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.cpp index 417cd004f8..aa3ed261c2 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.cpp @@ -1,445 +1,429 @@ -/* SerialPABotBase: Pokken Controller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Concurrency/ReverseLockGuard.h" -#include "Common/Cpp/Options/TimeExpressionOption.h" -#include "Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h" -#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" -#include "Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.h" -#include "Controllers/SerialPABotBase/SerialPABotBase_Routines_NS_Generic.h" -#include "NintendoSwitch_SerialPABotBase_PokkenController.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -using namespace std::chrono_literals; - - - - -SerialPABotBase_PokkenController::SerialPABotBase_PokkenController( - Logger& logger, - SerialPABotBase::SerialPABotBase_Connection& connection -) - : SerialPABotBase_Controller( - logger, - ControllerType::NintendoSwitch_WiredProController, - connection - ) - , m_use_milliseconds(m_supported_features.contains(ControllerFeature::TimingFlexibleMilliseconds)) - , m_stopping(false) - , m_status_thread(&SerialPABotBase_PokkenController::status_thread, this) -{} -SerialPABotBase_PokkenController::~SerialPABotBase_PokkenController(){ - stop(); - m_status_thread.join(); -} -void SerialPABotBase_PokkenController::stop(){ - if (m_stopping.exchange(true)){ - return; - } - ProController::stop(); - m_scope.cancel(nullptr); - { - std::unique_lock lg(m_sleep_lock); - if (m_serial){ - m_serial->notify_all(); - } - m_cv.notify_all(); - } -} - - - - - -void SerialPABotBase_PokkenController::push_state(const Cancellable* cancellable, WallDuration duration){ - // Must be called inside "m_state_lock". - - if (!is_ready()){ - throw InvalidConnectionStateException(error_string()); - } - - int dpad_x = 0; - int dpad_y = 0; - uint16_t buttons = 0; - for (size_t c = 0; c < TOTAL_BUTTONS; c++){ - if (!m_buttons[c].is_busy()){ - continue; - } - Button button = (Button)((ButtonFlagType)1 << c); - switch (button){ - case BUTTON_Y: buttons |= 1 << 0; break; - case BUTTON_B: buttons |= 1 << 1; break; - case BUTTON_A: buttons |= 1 << 2; break; - case BUTTON_X: buttons |= 1 << 3; break; - case BUTTON_L: buttons |= 1 << 4; break; - case BUTTON_R: buttons |= 1 << 5; break; - case BUTTON_ZL: buttons |= 1 << 6; break; - case BUTTON_ZR: buttons |= 1 << 7; break; - case BUTTON_MINUS: buttons |= 1 << 8; break; - case BUTTON_PLUS: buttons |= 1 << 9; break; - case BUTTON_LCLICK: buttons |= 1 << 10; break; - case BUTTON_RCLICK: buttons |= 1 << 11; break; - case BUTTON_HOME: buttons |= 1 << 12; break; - case BUTTON_CAPTURE: buttons |= 1 << 13; break; - case BUTTON_UP: dpad_y--; break; - case BUTTON_RIGHT: dpad_x++; break; - case BUTTON_DOWN: dpad_y++; break; - case BUTTON_LEFT: dpad_x--; break; - default:; - } - } - - - // Merge the dpad states. - DpadPosition dpad = m_dpad.is_busy() ? m_dpad.position : DPAD_NONE; - { - switch (dpad){ - case DpadPosition::DPAD_UP: - dpad_y--; - break; - case DpadPosition::DPAD_UP_RIGHT: - dpad_x++; - dpad_y--; - break; - case DpadPosition::DPAD_RIGHT: - dpad_x++; - break; - case DpadPosition::DPAD_DOWN_RIGHT: - dpad_x++; - dpad_y++; - break; - case DpadPosition::DPAD_DOWN: - dpad_y++; - break; - case DpadPosition::DPAD_DOWN_LEFT: - dpad_x--; - dpad_y++; - break; - case DpadPosition::DPAD_LEFT: - dpad_x--; - break; - case DpadPosition::DPAD_UP_LEFT: - dpad_x--; - dpad_y--; - break; - default:; - } - - if (dpad_x < 0){ - if (dpad_y < 0){ - dpad = DpadPosition::DPAD_UP_LEFT; - }else if (dpad_y > 0){ - dpad = DpadPosition::DPAD_DOWN_LEFT; - }else{ - dpad = DpadPosition::DPAD_LEFT; - } - }else if (dpad_x > 0){ - if (dpad_y < 0){ - dpad = DpadPosition::DPAD_UP_RIGHT; - }else if (dpad_y > 0){ - dpad = DpadPosition::DPAD_DOWN_RIGHT; - }else{ - dpad = DpadPosition::DPAD_RIGHT; - } - }else{ - if (dpad_y < 0){ - dpad = DpadPosition::DPAD_UP; - }else if (dpad_y > 0){ - dpad = DpadPosition::DPAD_DOWN; - }else{ - dpad = DPAD_NONE; - } - } - } - - - - uint8_t left_x = 128; - uint8_t left_y = 128; - uint8_t right_x = 128; - uint8_t right_y = 128; - if (m_left_joystick.is_busy()){ - left_x = m_left_joystick.x; - left_y = m_left_joystick.y; - } - if (m_right_joystick.is_busy()){ - right_x = m_right_joystick.x; - right_y = m_right_joystick.y; - } - - - // Release the state lock since we are no longer touching state. - // This loop can block indefinitely if the command queue is full. - ReverseLockGuard lg(m_state_lock); - - // Divide the controller state into smaller chunks that fit into the report - // duration. - Milliseconds time_left = std::chrono::duration_cast(duration); - - if (m_use_milliseconds){ - while (time_left > Milliseconds::zero()){ - Milliseconds current = std::min(time_left, 65535ms); - m_serial->issue_request( - SerialPABotBase::DeviceRequest_NS_Generic_ControllerStateMs( - (uint16_t)current.count(), - buttons, - dpad, - left_x, left_y, - right_x, right_y - ), - cancellable - ); - time_left -= current; - } - }else{ - while (time_left > Milliseconds::zero()){ - Milliseconds current_ms = std::min(time_left, 255 * 8ms); - uint8_t current_ticks = (uint8_t)milliseconds_to_ticks_8ms(current_ms.count()); - m_serial->issue_request( - SerialPABotBase::DeviceRequest_NS_Generic_ControllerStateTicks( - buttons, - dpad, - left_x, left_y, - right_x, right_y, - current_ticks - ), - cancellable - ); - time_left -= current_ms; - } - } -} - - -// -// Given a regularly reported 32-bit counter that wraps around, infer its true -// 64-bit value. -// -class ExtendedLengthCounter{ -public: - ExtendedLengthCounter() - : m_high_bits(0) - , m_last_received(0) - {} - - uint64_t push_short_value(uint32_t counter){ - if (counter < m_last_received && counter - m_last_received < 0x40000000){ - m_high_bits++; - } - m_last_received = counter; - return ((uint64_t)m_high_bits << 32) | counter; - } - -private: - uint32_t m_high_bits; - uint32_t m_last_received; -}; - - -#if 0 -class TickRateTracker{ -public: - TickRateTracker(double expected_ticks_per_second) - : m_expected_ticks_per_second(expected_ticks_per_second) -// , m_history(10) - {} - - - double push_ticks(uint64_t ticks){ - WallClock now = current_time(); - -// if (m_history.full()){ -// m_history.pop_front(); -// } - - if (ticks <= m_last_ticks){ - m_last_push = WallClock::min(); - m_last_ticks = 0; - m_consecutive_off = 0; - } - - double ticks_per_second = 0; - - if (m_last_push != WallClock::min()){ - uint64_t elapsed_ticks = ticks - m_last_ticks; - double elapsed_seconds = std::chrono::duration_cast(now - m_last_push).count() * 0.000001; - ticks_per_second = elapsed_ticks / elapsed_seconds; -// m_history.push_back(ticks_per_second); - - double rate_error = std::abs(ticks_per_second - m_expected_ticks_per_second) / m_expected_ticks_per_second; - if (rate_error > 0.1){ - m_consecutive_off++; - }else{ - m_consecutive_off = 0; - } - - } - - m_last_push = now; - m_last_ticks = ticks; - - return ticks_per_second; - } - - size_t consecutive_off_readings() const{ - return m_consecutive_off; - } - - -private: - double m_expected_ticks_per_second; - WallClock m_last_push = WallClock::min(); - uint64_t m_last_ticks = 0; - - size_t m_consecutive_off = 0; - -// CircularBuffer m_history; -}; -#endif - - -void SerialPABotBase_PokkenController::status_thread(){ - constexpr std::chrono::milliseconds PERIOD(1000); - std::atomic last_ack(current_time()); - - std::thread watchdog([&, this]{ - WallClock next_ping = current_time(); - while (true){ - if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ - break; - } - - auto last = current_time() - last_ack.load(std::memory_order_relaxed); - std::chrono::duration seconds = last; - if (last > 2 * PERIOD && is_ready()){ - std::string text = "Last Ack: " + tostr_fixed(seconds.count(), 3) + " seconds ago"; - m_handle.set_status_line1(text, COLOR_RED); -// m_logger.log("Connection issue detected. Turning on all logging..."); -// settings.log_everything.store(true, std::memory_order_release); - } - - std::unique_lock lg(m_sleep_lock); - if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ - break; - } - - WallClock now = current_time(); - next_ping += PERIOD; - if (now + PERIOD < next_ping){ - next_ping = now + PERIOD; - } - m_cv.wait_until(lg, next_ping); - } - }); - - - ExtendedLengthCounter clock_tracker; -// TickRateTracker tick_rate_tracker(m_use_milliseconds ? 1000 : TICKS_PER_SECOND); - WallClock next_ping = current_time(); - while (true){ - if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ - break; - } - - std::string error; - try{ - pabb_MsgAckRequestI32 response; - m_serial->issue_request_and_wait( - SerialPABotBase::MessageControllerStatus(), - &m_scope - ).convert(m_logger, response); - last_ack.store(current_time(), std::memory_order_relaxed); - - uint32_t status = response.data; - bool status_connected = status & 1; - bool status_ready = status & 2; - - std::string str; - str += "Connected: " + (status_connected - ? html_color_text("Yes", theme_friendly_darkblue()) - : html_color_text("No", COLOR_RED) - ); - str += " - Ready: " + (status_ready - ? html_color_text("Yes", theme_friendly_darkblue()) - : html_color_text("No", COLOR_RED) - ); - - m_handle.set_status_line1(str); - - -#if 0 - pabb_MsgAckRequestI32 response; - m_serial->issue_request_and_wait( - SerialPABotBase::DeviceRequest_system_clock(), - &m_scope - ).convert(logger(), response); - last_ack.store(current_time(), std::memory_order_relaxed); - - uint64_t wallclock = clock_tracker.push_short_value(response.data); -// double ticks_per_second = tick_rate_tracker.push_ticks(wallclock); - m_handle.set_status_line1( - "Device Clock: " + tostr_u_commas(wallclock), - theme_friendly_darkblue() - ); -#endif - -// if (tick_rate_tracker.consecutive_off_readings() >= 10){ -// error = "Tick rate is erratic. Arduino/Teensy is not reliable on Switch 2."; -// } - - }catch (OperationCancelledException&){ - break; - }catch (InvalidConnectionStateException&){ - break; - }catch (SerialProtocolException& e){ - error = e.message(); - }catch (ConnectionException& e){ - error = e.message(); - }catch (...){ - error = "Unknown error."; - } - if (!error.empty()){ - m_handle.set_status_line1(error, COLOR_RED); - stop_with_error(std::move(error)); - } - -// cout << "lock()" << endl; - std::unique_lock lg(m_sleep_lock); -// cout << "lock() - done" << endl; - if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ - break; - } - - WallClock now = current_time(); - next_ping += PERIOD; - if (now + PERIOD < next_ping){ - next_ping = now + PERIOD; - } - m_cv.wait_until(lg, next_ping); - } - - { - std::unique_lock lg(m_sleep_lock); - m_cv.notify_all(); - } - watchdog.join(); -} - - - - - - -} -} +/* SerialPABotBase: Pokken Controller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Concurrency/ReverseLockGuard.h" +#include "Common/Cpp/Options/TimeExpressionOption.h" +#include "Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h" +#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" +#include "Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.h" +#include "Controllers/SerialPABotBase/SerialPABotBase_Routines_NS_Generic.h" +#include "NintendoSwitch_SerialPABotBase_PokkenController.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +using namespace std::chrono_literals; + + + + +SerialPABotBase_PokkenController::SerialPABotBase_PokkenController( + Logger& logger, + SerialPABotBase::SerialPABotBase_Connection& connection +) + : ProController(logger) + , SerialPABotBase_Controller( + logger, + ControllerType::NintendoSwitch_WiredProController, + connection + ) + , m_stopping(false) + , m_status_thread(&SerialPABotBase_PokkenController::status_thread, this) +{} +SerialPABotBase_PokkenController::~SerialPABotBase_PokkenController(){ + stop(); + m_status_thread.join(); +} +void SerialPABotBase_PokkenController::stop(){ + if (m_stopping.exchange(true)){ + return; + } + ProController::stop(); + m_scope.cancel(nullptr); + { + std::unique_lock lg(m_sleep_lock); + if (m_serial){ + m_serial->notify_all(); + } + m_cv.notify_all(); + } +} + + + + + +void SerialPABotBase_PokkenController::push_state(const Cancellable* cancellable, WallDuration duration){ + // Must be called inside "m_state_lock". + + if (!is_ready()){ + throw InvalidConnectionStateException(error_string()); + } + + int dpad_x = 0; + int dpad_y = 0; + uint16_t buttons = 0; + for (size_t c = 0; c < TOTAL_BUTTONS; c++){ + if (!m_buttons[c].is_busy()){ + continue; + } + Button button = (Button)((ButtonFlagType)1 << c); + switch (button){ + case BUTTON_Y: buttons |= 1 << 0; break; + case BUTTON_B: buttons |= 1 << 1; break; + case BUTTON_A: buttons |= 1 << 2; break; + case BUTTON_X: buttons |= 1 << 3; break; + case BUTTON_L: buttons |= 1 << 4; break; + case BUTTON_R: buttons |= 1 << 5; break; + case BUTTON_ZL: buttons |= 1 << 6; break; + case BUTTON_ZR: buttons |= 1 << 7; break; + case BUTTON_MINUS: buttons |= 1 << 8; break; + case BUTTON_PLUS: buttons |= 1 << 9; break; + case BUTTON_LCLICK: buttons |= 1 << 10; break; + case BUTTON_RCLICK: buttons |= 1 << 11; break; + case BUTTON_HOME: buttons |= 1 << 12; break; + case BUTTON_CAPTURE: buttons |= 1 << 13; break; + case BUTTON_GR: buttons |= 1 << 14; break; + case BUTTON_GL: buttons |= 1 << 15; break; + case BUTTON_UP: dpad_y--; break; + case BUTTON_RIGHT: dpad_x++; break; + case BUTTON_DOWN: dpad_y++; break; + case BUTTON_LEFT: dpad_x--; break; + default:; + } + } + + + // Merge the dpad states. + DpadPosition dpad = m_dpad.is_busy() ? m_dpad.position : DPAD_NONE; + { + switch (dpad){ + case DpadPosition::DPAD_UP: + dpad_y--; + break; + case DpadPosition::DPAD_UP_RIGHT: + dpad_x++; + dpad_y--; + break; + case DpadPosition::DPAD_RIGHT: + dpad_x++; + break; + case DpadPosition::DPAD_DOWN_RIGHT: + dpad_x++; + dpad_y++; + break; + case DpadPosition::DPAD_DOWN: + dpad_y++; + break; + case DpadPosition::DPAD_DOWN_LEFT: + dpad_x--; + dpad_y++; + break; + case DpadPosition::DPAD_LEFT: + dpad_x--; + break; + case DpadPosition::DPAD_UP_LEFT: + dpad_x--; + dpad_y--; + break; + default:; + } + + if (dpad_x < 0){ + if (dpad_y < 0){ + dpad = DpadPosition::DPAD_UP_LEFT; + }else if (dpad_y > 0){ + dpad = DpadPosition::DPAD_DOWN_LEFT; + }else{ + dpad = DpadPosition::DPAD_LEFT; + } + }else if (dpad_x > 0){ + if (dpad_y < 0){ + dpad = DpadPosition::DPAD_UP_RIGHT; + }else if (dpad_y > 0){ + dpad = DpadPosition::DPAD_DOWN_RIGHT; + }else{ + dpad = DpadPosition::DPAD_RIGHT; + } + }else{ + if (dpad_y < 0){ + dpad = DpadPosition::DPAD_UP; + }else if (dpad_y > 0){ + dpad = DpadPosition::DPAD_DOWN; + }else{ + dpad = DPAD_NONE; + } + } + } + + + + uint8_t left_x = 128; + uint8_t left_y = 128; + uint8_t right_x = 128; + uint8_t right_y = 128; + if (m_left_joystick.is_busy()){ + left_x = m_left_joystick.x; + left_y = m_left_joystick.y; + } + if (m_right_joystick.is_busy()){ + right_x = m_right_joystick.x; + right_y = m_right_joystick.y; + } + + + // Release the state lock since we are no longer touching state. + // This loop can block indefinitely if the command queue is full. + ReverseLockGuard lg(m_state_lock); + + // Divide the controller state into smaller chunks that fit into the report + // duration. + Milliseconds time_left = std::chrono::duration_cast(duration); + + while (time_left > Milliseconds::zero()){ + Milliseconds current = std::min(time_left, 65535ms); + m_serial->issue_request( + SerialPABotBase::DeviceRequest_NS_Generic_ControllerStateMs( + (uint16_t)current.count(), + buttons, + dpad, + left_x, left_y, + right_x, right_y + ), + cancellable + ); + time_left -= current; + } +} + + +// +// Given a regularly reported 32-bit counter that wraps around, infer its true +// 64-bit value. +// +class ExtendedLengthCounter{ +public: + ExtendedLengthCounter() + : m_high_bits(0) + , m_last_received(0) + {} + + uint64_t push_short_value(uint32_t counter){ + if (counter < m_last_received && counter - m_last_received < 0x40000000){ + m_high_bits++; + } + m_last_received = counter; + return ((uint64_t)m_high_bits << 32) | counter; + } + +private: + uint32_t m_high_bits; + uint32_t m_last_received; +}; + + +#if 0 +class TickRateTracker{ +public: + TickRateTracker(double expected_ticks_per_second) + : m_expected_ticks_per_second(expected_ticks_per_second) +// , m_history(10) + {} + + + double push_ticks(uint64_t ticks){ + WallClock now = current_time(); + +// if (m_history.full()){ +// m_history.pop_front(); +// } + + if (ticks <= m_last_ticks){ + m_last_push = WallClock::min(); + m_last_ticks = 0; + m_consecutive_off = 0; + } + + double ticks_per_second = 0; + + if (m_last_push != WallClock::min()){ + uint64_t elapsed_ticks = ticks - m_last_ticks; + double elapsed_seconds = std::chrono::duration_cast(now - m_last_push).count() * 0.000001; + ticks_per_second = elapsed_ticks / elapsed_seconds; +// m_history.push_back(ticks_per_second); + + double rate_error = std::abs(ticks_per_second - m_expected_ticks_per_second) / m_expected_ticks_per_second; + if (rate_error > 0.1){ + m_consecutive_off++; + }else{ + m_consecutive_off = 0; + } + + } + + m_last_push = now; + m_last_ticks = ticks; + + return ticks_per_second; + } + + size_t consecutive_off_readings() const{ + return m_consecutive_off; + } + + +private: + double m_expected_ticks_per_second; + WallClock m_last_push = WallClock::min(); + uint64_t m_last_ticks = 0; + + size_t m_consecutive_off = 0; + +// CircularBuffer m_history; +}; +#endif + + +void SerialPABotBase_PokkenController::status_thread(){ + constexpr std::chrono::milliseconds PERIOD(1000); + std::atomic last_ack(current_time()); + + std::thread watchdog([&, this]{ + WallClock next_ping = current_time(); + while (true){ + if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ + break; + } + + auto last = current_time() - last_ack.load(std::memory_order_relaxed); + std::chrono::duration seconds = last; + if (last > 2 * PERIOD && is_ready()){ + std::string text = "Last Ack: " + tostr_fixed(seconds.count(), 3) + " seconds ago"; + m_handle.set_status_line1(text, COLOR_RED); +// m_logger.log("Connection issue detected. Turning on all logging..."); +// settings.log_everything.store(true, std::memory_order_release); + } + + std::unique_lock lg(m_sleep_lock); + if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ + break; + } + + WallClock now = current_time(); + next_ping += PERIOD; + if (now + PERIOD < next_ping){ + next_ping = now + PERIOD; + } + m_cv.wait_until(lg, next_ping); + } + }); + + + ExtendedLengthCounter clock_tracker; +// TickRateTracker tick_rate_tracker(m_use_milliseconds ? 1000 : TICKS_PER_SECOND); + WallClock next_ping = current_time(); + while (true){ + if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ + break; + } + + std::string error; + try{ + pabb_MsgAckRequestI32 response; + m_serial->issue_request_and_wait( + SerialPABotBase::MessageControllerStatus(), + &m_scope + ).convert(m_logger, response); + last_ack.store(current_time(), std::memory_order_relaxed); + + uint32_t status = response.data; + bool status_connected = status & 1; + bool status_ready = status & 2; + + std::string str; + str += "Connected: " + (status_connected + ? html_color_text("Yes", theme_friendly_darkblue()) + : html_color_text("No", COLOR_RED) + ); + str += " - Ready: " + (status_ready + ? html_color_text("Yes", theme_friendly_darkblue()) + : html_color_text("No", COLOR_RED) + ); + + m_handle.set_status_line1(str); + + +#if 0 + pabb_MsgAckRequestI32 response; + m_serial->issue_request_and_wait( + SerialPABotBase::DeviceRequest_system_clock(), + &m_scope + ).convert(logger(), response); + last_ack.store(current_time(), std::memory_order_relaxed); + + uint64_t wallclock = clock_tracker.push_short_value(response.data); +// double ticks_per_second = tick_rate_tracker.push_ticks(wallclock); + m_handle.set_status_line1( + "Device Clock: " + tostr_u_commas(wallclock), + theme_friendly_darkblue() + ); +#endif + +// if (tick_rate_tracker.consecutive_off_readings() >= 10){ +// error = "Tick rate is erratic. Arduino/Teensy is not reliable on Switch 2."; +// } + + }catch (OperationCancelledException&){ + break; + }catch (InvalidConnectionStateException&){ + break; + }catch (SerialProtocolException& e){ + error = e.message(); + }catch (ConnectionException& e){ + error = e.message(); + }catch (...){ + error = "Unknown error."; + } + if (!error.empty()){ + m_handle.set_status_line1(error, COLOR_RED); + stop_with_error(std::move(error)); + } + +// cout << "lock()" << endl; + std::unique_lock lg(m_sleep_lock); +// cout << "lock() - done" << endl; + if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ + break; + } + + WallClock now = current_time(); + next_ping += PERIOD; + if (now + PERIOD < next_ping){ + next_ping = now + PERIOD; + } + m_cv.wait_until(lg, next_ping); + } + + { + std::unique_lock lg(m_sleep_lock); + m_cv.notify_all(); + } + watchdog.join(); +} + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.h b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.h index 2191bfdcd0..7dc4aaede6 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.h @@ -1,244 +1,243 @@ -/* SerialPABotBase: Pokken Controller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_SerialPABotBase_PokkenController_H -#define PokemonAutomation_NintendoSwitch_SerialPABotBase_PokkenController_H - -#include "Controllers/ControllerCapability.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch_SerialPABotBase_Controller.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class SerialPABotBase_PokkenController final : - public ProController, - public SerialPABotBase_Controller -{ -public: - using ContextType = ProControllerContext; - - -public: - SerialPABotBase_PokkenController( - Logger& logger, - SerialPABotBase::SerialPABotBase_Connection& connection - ); - ~SerialPABotBase_PokkenController(); - void stop(); - - virtual Logger& logger() override{ - return m_logger; - } - virtual RecursiveThrottler& logging_throttler() override{ - return m_logging_throttler; - } - virtual bool is_ready() const override{ - return SerialPABotBase_Controller::is_ready(); - } - - -public: - virtual ControllerType controller_type() const override{ - return ControllerType::NintendoSwitch_WiredProController; - } - virtual const ControllerFeatures& controller_features() const override{ - return m_supported_features; - } - virtual ControllerPerformanceClass performance_class() const override{ - return ControllerPerformanceClass::SerialPABotBase_Wired_125Hz; - } - - virtual Milliseconds ticksize() const override{ - return m_use_milliseconds ? Milliseconds(0) : Milliseconds(8); - } - virtual Milliseconds cooldown() const override{ - return Milliseconds(8); - } - virtual Milliseconds timing_variation() const override{ - return ConsoleSettings::instance().TIMING_OPTIONS.WIRED_MICROCONTROLLER; - } - virtual bool atomic_multibutton() const override{ - return true; - } - - -public: - virtual void cancel_all_commands() override{ - SerialPABotBase_Controller::cancel_all_commands(); - } - virtual void replace_on_next_command() override{ - SerialPABotBase_Controller::replace_on_next_command(); - } - - virtual void wait_for_all(const Cancellable* cancellable) override{ - SerialPABotBase_Controller::wait_for_all(cancellable); - } - - -public: - // Superscalar Commands (the "ssf" framework) - - virtual void issue_barrier(const Cancellable* cancellable) override{ - ControllerWithScheduler::issue_barrier(cancellable); - } - virtual void issue_nop(const Cancellable* cancellable, Milliseconds duration) override{ - ControllerWithScheduler::issue_nop(cancellable, duration); - } - virtual void issue_buttons( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - Button button - ) override{ - button &= VALID_PRO_CONTROLLER_BUTTONS; - ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); - } - virtual void issue_dpad( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition position - ) override{ - ControllerWithScheduler::issue_dpad(cancellable, delay, hold, cooldown, position); - } - virtual void issue_left_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y - ) override{ - ControllerWithScheduler::issue_left_joystick(cancellable, delay, hold, cooldown, x, y); - } - virtual void issue_right_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y - ) override{ - ControllerWithScheduler::issue_right_joystick(cancellable, delay, hold, cooldown, x, y); - } - - virtual void issue_gyro_accel_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_x(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_accel_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_y(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_accel_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_z(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_x(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_y(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_z(cancellable, delay, hold, cooldown, value); - } - - virtual void issue_full_controller_state( - const Cancellable* cancellable, - Milliseconds hold, - Button button, - DpadPosition position, - uint8_t left_x, uint8_t left_y, - uint8_t right_x, uint8_t right_y - ) override{ - ControllerWithScheduler::issue_full_controller_state( - cancellable, - hold, - button, - position, - left_x, left_y, - right_x, right_y - ); - } - - -public: - // High speed RPCs. - - virtual void issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button - ) override{ - button &= VALID_PRO_CONTROLLER_BUTTONS; - ControllerWithScheduler::issue_mash_button(cancellable, duration, button); - } - virtual void issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button0, Button button1 - ) override{ - button0 &= VALID_PRO_CONTROLLER_BUTTONS; - button1 &= VALID_PRO_CONTROLLER_BUTTONS; - ControllerWithScheduler::issue_mash_button(cancellable, duration, button0, button1); - } - virtual void issue_mash_AZs( - const Cancellable* cancellable, - Milliseconds duration - ) override{ - ControllerWithScheduler::issue_mash_AZs(cancellable, duration); - } - virtual void issue_system_scroll( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition direction // Diagonals not allowed. - ) override{ - ControllerWithScheduler::issue_system_scroll(cancellable, delay, hold, cooldown, direction); - } - - -private: - template - PA_FORCE_INLINE Type milliseconds_to_ticks_8ms(Type milliseconds){ - return milliseconds / 8 + (milliseconds % 8 + 7) / 8; - } - virtual void push_state(const Cancellable* cancellable, WallDuration duration) override; - - void status_thread(); - - -private: - bool m_use_milliseconds; - CancellableHolder m_scope; - std::atomic m_stopping; - std::mutex m_sleep_lock; - std::condition_variable m_cv; - std::thread m_status_thread; -}; - - - - -} -} -#endif +/* SerialPABotBase: Pokken Controller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SerialPABotBase_PokkenController_H +#define PokemonAutomation_NintendoSwitch_SerialPABotBase_PokkenController_H + +#include "Controllers/ControllerCapability.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch_SerialPABotBase_Controller.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class SerialPABotBase_PokkenController final : + public ProController, + public SerialPABotBase_Controller +{ +public: + using ContextType = ProControllerContext; + + +public: + SerialPABotBase_PokkenController( + Logger& logger, + SerialPABotBase::SerialPABotBase_Connection& connection + ); + ~SerialPABotBase_PokkenController(); + void stop(); + + virtual Logger& logger() override{ + return m_logger; + } + virtual RecursiveThrottler& logging_throttler() override{ + return m_logging_throttler; + } + virtual bool is_ready() const override{ + return SerialPABotBase_Controller::is_ready(); + } + + +public: + virtual ControllerType controller_type() const override{ + return ControllerType::NintendoSwitch_WiredProController; + } + virtual const ControllerFeatures& controller_features() const override{ + return m_supported_features; + } + virtual ControllerPerformanceClass performance_class() const override{ + return ControllerPerformanceClass::SerialPABotBase_Wired; + } + + virtual Milliseconds ticksize() const override{ + return Milliseconds(0); + } + virtual Milliseconds cooldown() const override{ + return Milliseconds(8); + } + virtual Milliseconds timing_variation() const override{ + return ConsoleSettings::instance().TIMING_OPTIONS.WIRED_MICROCONTROLLER; + } + virtual bool atomic_multibutton() const override{ + return true; + } + + +public: + virtual void cancel_all_commands() override{ + SerialPABotBase_Controller::cancel_all_commands(); + } + virtual void replace_on_next_command() override{ + SerialPABotBase_Controller::replace_on_next_command(); + } + + virtual void wait_for_all(const Cancellable* cancellable) override{ + SerialPABotBase_Controller::wait_for_all(cancellable); + } + + +public: + // Superscalar Commands (the "ssf" framework) + + virtual void issue_barrier(const Cancellable* cancellable) override{ + ControllerWithScheduler::issue_barrier(cancellable); + } + virtual void issue_nop(const Cancellable* cancellable, Milliseconds duration) override{ + ControllerWithScheduler::issue_nop(cancellable, duration); + } + virtual void issue_buttons( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + Button button + ) override{ + button &= VALID_PRO_CONTROLLER_BUTTONS; + ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); + } + virtual void issue_dpad( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition position + ) override{ + ControllerWithScheduler::issue_dpad(cancellable, delay, hold, cooldown, position); + } + virtual void issue_left_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y + ) override{ + ControllerWithScheduler::issue_left_joystick(cancellable, delay, hold, cooldown, x, y); + } + virtual void issue_right_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y + ) override{ + ControllerWithScheduler::issue_right_joystick(cancellable, delay, hold, cooldown, x, y); + } + + virtual void issue_gyro_accel_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_x(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_accel_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_y(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_accel_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_z(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_x(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_y(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_z(cancellable, delay, hold, cooldown, value); + } + + virtual void issue_full_controller_state( + const Cancellable* cancellable, + Milliseconds hold, + Button button, + DpadPosition position, + uint8_t left_x, uint8_t left_y, + uint8_t right_x, uint8_t right_y + ) override{ + ControllerWithScheduler::issue_full_controller_state( + cancellable, + hold, + button, + position, + left_x, left_y, + right_x, right_y + ); + } + + +public: + // High speed RPCs. + + virtual void issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button + ) override{ + button &= VALID_PRO_CONTROLLER_BUTTONS; + ControllerWithScheduler::issue_mash_button(cancellable, duration, button); + } + virtual void issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button0, Button button1 + ) override{ + button0 &= VALID_PRO_CONTROLLER_BUTTONS; + button1 &= VALID_PRO_CONTROLLER_BUTTONS; + ControllerWithScheduler::issue_mash_button(cancellable, duration, button0, button1); + } + virtual void issue_mash_AZs( + const Cancellable* cancellable, + Milliseconds duration + ) override{ + ControllerWithScheduler::issue_mash_AZs(cancellable, duration); + } + virtual void issue_system_scroll( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition direction // Diagonals not allowed. + ) override{ + ControllerWithScheduler::issue_system_scroll(cancellable, delay, hold, cooldown, direction); + } + + +private: + template + PA_FORCE_INLINE Type milliseconds_to_ticks_8ms(Type milliseconds){ + return milliseconds / 8 + (milliseconds % 8 + 7) / 8; + } + virtual void push_state(const Cancellable* cancellable, WallDuration duration) override; + + void status_thread(); + + +private: + CancellableHolder m_scope; + std::atomic m_stopping; + std::mutex m_sleep_lock; + std::condition_variable m_cv; + std::thread m_status_thread; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessController.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessController.cpp index 41787d2833..c751318703 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessController.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessController.cpp @@ -1,405 +1,405 @@ -/* SerialPABotBase: Wireless Controller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Concurrency/ReverseLockGuard.h" -#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" -#include "Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.h" -#include "Controllers/SerialPABotBase/SerialPABotBase_Routines_ESP32.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch_SerialPABotBase_WirelessController.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -using namespace std::chrono_literals; - - - - - - - -SerialPABotBase_WirelessController::SerialPABotBase_WirelessController( - Logger& logger, - SerialPABotBase::SerialPABotBase_Connection& connection, - ControllerType controller_type -) - : SerialPABotBase_Controller( - logger, - controller_type, - connection - ) - , m_controller_type(controller_type) - , m_timing_variation(ConsoleSettings::instance().TIMING_OPTIONS.WIRELESS_ESP32) - , m_stopping(false) - , m_status_thread(&SerialPABotBase_WirelessController::status_thread, this) -{} -SerialPABotBase_WirelessController::~SerialPABotBase_WirelessController(){ - stop(); - m_status_thread.join(); -} -void SerialPABotBase_WirelessController::stop(){ - if (m_stopping.exchange(true)){ - return; - } - m_scope.cancel(nullptr); - { - std::unique_lock lg(m_sleep_lock); - if (m_serial){ - m_serial->notify_all(); - } - m_cv.notify_all(); - } -} - - - - - -Button SerialPABotBase_WirelessController::populate_report_buttons(PABB_NintendoSwitch_ButtonState& buttons){ - // https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/bluetooth_hid_notes.md - - Button all_buttons = BUTTON_NONE; - for (size_t c = 0; c < TOTAL_BUTTONS; c++){ - if (!m_buttons[c].is_busy()){ - continue; - } - Button button = (Button)((ButtonFlagType)1 << c); - all_buttons |= button; - switch (button){ - // Right - case BUTTON_Y: buttons.button3 |= 1 << 0; break; - case BUTTON_X: buttons.button3 |= 1 << 1; break; - case BUTTON_B: buttons.button3 |= 1 << 2; break; - case BUTTON_A: buttons.button3 |= 1 << 3; break; - case BUTTON_RIGHT_SR: buttons.button3 |= 1 << 4; break; - case BUTTON_RIGHT_SL: buttons.button3 |= 1 << 5; break; - case BUTTON_R: buttons.button3 |= 1 << 6; break; - case BUTTON_ZR: buttons.button3 |= 1 << 7; break; - - // Shared - case BUTTON_MINUS: buttons.button4 |= 1 << 0; break; - case BUTTON_PLUS: buttons.button4 |= 1 << 1; break; - case BUTTON_RCLICK: buttons.button4 |= 1 << 2; break; - case BUTTON_LCLICK: buttons.button4 |= 1 << 3; break; - case BUTTON_HOME: buttons.button4 |= 1 << 4; break; - case BUTTON_CAPTURE: buttons.button4 |= 1 << 5; break; - - // Left - case BUTTON_DOWN: buttons.button5 |= 1 << 0; break; - case BUTTON_UP: buttons.button5 |= 1 << 1; break; - case BUTTON_RIGHT: buttons.button5 |= 1 << 2; break; - case BUTTON_LEFT: buttons.button5 |= 1 << 3; break; - case BUTTON_LEFT_SR: buttons.button5 |= 1 << 4; break; - case BUTTON_LEFT_SL: buttons.button5 |= 1 << 5; break; - case BUTTON_L: buttons.button5 |= 1 << 6; break; - case BUTTON_ZL: buttons.button5 |= 1 << 7; break; - - default:; - } - } - return all_buttons; -} -bool SerialPABotBase_WirelessController::populate_report_gyro(PABB_NintendoSwitch_GyroState& gyro){ - bool gyro_active = false; - { - if (m_accel_x.is_busy()){ - gyro.accel_x = m_accel_x.value; - gyro_active = true; - } - if (m_accel_y.is_busy()){ - gyro.accel_y = m_accel_y.value; - gyro_active = true; - } - if (m_accel_z.is_busy()){ - gyro.accel_z = m_accel_z.value; - gyro_active = true; - } - if (m_rotation_x.is_busy()){ - gyro.rotation_x = m_rotation_x.value; - gyro_active = true; - } - if (m_rotation_y.is_busy()){ - gyro.rotation_y = m_rotation_y.value; - gyro_active = true; - } - if (m_rotation_z.is_busy()){ - gyro.rotation_z = m_rotation_z.value; - gyro_active = true; - } - } - return gyro_active; -} - - -void SerialPABotBase_WirelessController::issue_report( - const Cancellable* cancellable, - WallDuration duration, - const PABB_NintendoSwitch_ButtonState& buttons -){ - // Release the state lock since we are no longer touching state. - // This loop can block indefinitely if the command queue is full. - ReverseLockGuard lg(m_state_lock); - - // We will not do any throttling or timing adjustments here. We'll defer - // to the microcontroller to do that for us. - - // Divide the controller state into smaller chunks of 65535 milliseconds. - Milliseconds time_left = std::chrono::duration_cast(duration); - - while (time_left > Milliseconds::zero()){ - Milliseconds current = std::min(time_left, 65535ms); - m_serial->issue_request( - SerialPABotBase::MessageControllerStateButtons( - (uint16_t)current.count(), - buttons - ), - cancellable - ); - time_left -= current; - } -} -void SerialPABotBase_WirelessController::issue_report( - const Cancellable* cancellable, - WallDuration duration, - const PABB_NintendoSwitch_ButtonState& buttons, - const PABB_NintendoSwitch_GyroState& gyro -){ - // Release the state lock since we are no longer touching state. - // This loop can block indefinitely if the command queue is full. - ReverseLockGuard lg(m_state_lock); - - // TODO: For now we duplicate the gyro data to all 3 5ms segments. - PABB_NintendoSwitch_GyroStateX3 gyro3{ - gyro, gyro, gyro - }; - -#if 0 - // Purturb results to show the Switch that they are not stuck. - if (gyro3.time1.accel_x > 0){ - gyro3.time0.accel_x--; - gyro3.time2.accel_x--; - }else if (gyro3.time1.accel_x < 0){ - gyro3.time0.accel_x++; - gyro3.time2.accel_x++; - }else{ - gyro3.time0.accel_x--; - gyro3.time2.accel_x++; - } - if (gyro3.time1.accel_y > 0){ - gyro3.time0.accel_y--; - gyro3.time2.accel_y--; - }else if (gyro3.time1.accel_y < 0){ - gyro3.time0.accel_y++; - gyro3.time2.accel_y++; - }else{ - gyro3.time0.accel_y--; - gyro3.time2.accel_y++; - } - if (gyro3.time1.accel_z > 0){ - gyro3.time0.accel_z--; - gyro3.time2.accel_z--; - }else if (gyro3.time1.accel_z < 0){ - gyro3.time0.accel_z++; - gyro3.time2.accel_z++; - }else{ - gyro3.time0.accel_z--; - gyro3.time2.accel_z++; - } -#endif - - // We will not do any throttling or timing adjustments here. We'll defer - // to the microcontroller to do that for us. - - // Divide the controller state into smaller chunks of 65535 milliseconds. - Milliseconds time_left = std::chrono::duration_cast(duration); - - while (time_left > Milliseconds::zero()){ - Milliseconds current = std::min(time_left, 65535ms); - m_serial->issue_request( - SerialPABotBase::MessageControllerStateFull( - (uint16_t)current.count(), - buttons, gyro3 - ), - cancellable - ); - time_left -= current; - } -} - - - - -void SerialPABotBase_WirelessController::status_thread(){ - constexpr std::chrono::milliseconds PERIOD(1000); - std::atomic last_ack(current_time()); - - // Read controller colors. - std::string color_html; -#if 1 - try{ - m_logger.log("Reading Controller Colors..."); - - using ControllerColors = PABB_NintendoSwitch_ControllerColors; - - BotBaseMessage response = m_serial->issue_request_and_wait( - SerialPABotBase::MessageControllerReadSpi( - m_controller_type, - 0x00006050, sizeof(ControllerColors) - ), - &m_scope - ); - - ControllerColors colors{}; - if (response.body.size() == sizeof(seqnum_t) + sizeof(ControllerColors)){ - memcpy(&colors, response.body.data() + sizeof(seqnum_t), sizeof(ControllerColors)); - }else{ - m_logger.log( - "Invalid response size to PABB_MSG_ESP32_REQUEST_READ_SPI: body = " + std::to_string(response.body.size()), - COLOR_RED - ); - m_handle.set_status_line1("Error: See log for more information.", COLOR_RED); - return; - } - m_logger.log("Reading Controller Colors... Done"); - - switch (m_controller_type){ - case ControllerType::NintendoSwitch_WirelessProController:{ - Color left(colors.left_grip[0], colors.left_grip[1], colors.left_grip[2]); - Color body(colors.body[0], colors.body[1], colors.body[2]); - Color right(colors.right_grip[0], colors.right_grip[1], colors.right_grip[2]); - color_html += html_color_text("⬤", left); - color_html += " " + html_color_text("⬤", body); - color_html += " " + html_color_text("⬤", right); - break; - } - case ControllerType::NintendoSwitch_LeftJoycon: - case ControllerType::NintendoSwitch_RightJoycon:{ - Color body(colors.body[0], colors.body[1], colors.body[2]); - color_html = html_color_text("⬤", body); - break; - } - default:; - } - - }catch (Exception& e){ - e.log(m_logger); - m_handle.set_status_line1("Error: See log for more information.", COLOR_RED); - return; - } -#endif - - - std::thread watchdog([&, this]{ - WallClock next_ping = current_time(); - while (true){ - if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ - break; - } - - auto last = current_time() - last_ack.load(std::memory_order_relaxed); - std::chrono::duration seconds = last; - if (last > 2 * PERIOD){ - std::string text = "Last Ack: " + tostr_fixed(seconds.count(), 3) + " seconds ago"; - m_handle.set_status_line1(text, COLOR_RED); -// m_logger.log("Connection issue detected. Turning on all logging..."); -// settings.log_everything.store(true, std::memory_order_release); - } - - std::unique_lock lg(m_sleep_lock); - if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ - break; - } - - WallClock now = current_time(); - next_ping += PERIOD; - if (now + PERIOD < next_ping){ - next_ping = now + PERIOD; - } - m_cv.wait_until(lg, next_ping); - } - }); - - WallClock next_ping = current_time(); - while (true){ - if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ - break; - } - - std::string error; - try{ - pabb_MsgAckRequestI32 response; - m_serial->issue_request_and_wait( - SerialPABotBase::MessageControllerStatus(), - &m_scope - ).convert(m_logger, response); - last_ack.store(current_time(), std::memory_order_relaxed); - - uint32_t status = response.data; - bool status_connected = status & 1; - bool status_ready = status & 2; - - std::string str; - str += "Connected: " + (status_connected - ? html_color_text("Yes", theme_friendly_darkblue()) - : html_color_text("No", COLOR_RED) - ); - str += " - Ready: " + (status_ready - ? html_color_text("Yes", theme_friendly_darkblue()) - : html_color_text("No", COLOR_RED) - ); - str += " - " + color_html; - - m_handle.set_status_line1(str); - }catch (OperationCancelledException&){ - break; - }catch (InvalidConnectionStateException&){ - break; - }catch (SerialProtocolException& e){ - error = e.message(); - }catch (ConnectionException& e){ - error = e.message(); - }catch (...){ - error = "Unknown error."; - } - if (!error.empty()){ - stop(); - m_handle.set_status_line1(error, COLOR_RED); - break; - } - -// cout << "lock()" << endl; - std::unique_lock lg(m_sleep_lock); -// cout << "lock() - done" << endl; - if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ - break; - } - - WallClock now = current_time(); - next_ping += PERIOD; - if (now + PERIOD < next_ping){ - next_ping = now + PERIOD; - } - m_cv.wait_until(lg, next_ping); - } - - { - std::unique_lock lg(m_sleep_lock); - m_cv.notify_all(); - } - watchdog.join(); -} - - - - -} -} +/* SerialPABotBase: Wireless Controller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Concurrency/ReverseLockGuard.h" +#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" +#include "Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.h" +#include "Controllers/SerialPABotBase/SerialPABotBase_Routines_ESP32.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch_SerialPABotBase_WirelessController.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +using namespace std::chrono_literals; + + + + + + + +SerialPABotBase_WirelessController::SerialPABotBase_WirelessController( + Logger& logger, + SerialPABotBase::SerialPABotBase_Connection& connection, + ControllerType controller_type +) + : SerialPABotBase_Controller( + logger, + controller_type, + connection + ) + , m_controller_type(controller_type) + , m_timing_variation(ConsoleSettings::instance().TIMING_OPTIONS.WIRELESS_ESP32) + , m_stopping(false) + , m_status_thread(&SerialPABotBase_WirelessController::status_thread, this) +{} +SerialPABotBase_WirelessController::~SerialPABotBase_WirelessController(){ + stop(); + m_status_thread.join(); +} +void SerialPABotBase_WirelessController::stop(){ + if (m_stopping.exchange(true)){ + return; + } + m_scope.cancel(nullptr); + { + std::unique_lock lg(m_sleep_lock); + if (m_serial){ + m_serial->notify_all(); + } + m_cv.notify_all(); + } +} + + + + + +Button SerialPABotBase_WirelessController::populate_report_buttons(PABB_NintendoSwitch_ButtonState& buttons){ + // https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/bluetooth_hid_notes.md + + Button all_buttons = BUTTON_NONE; + for (size_t c = 0; c < TOTAL_BUTTONS; c++){ + if (!m_buttons[c].is_busy()){ + continue; + } + Button button = (Button)((ButtonFlagType)1 << c); + all_buttons |= button; + switch (button){ + // Right + case BUTTON_Y: buttons.button3 |= 1 << 0; break; + case BUTTON_X: buttons.button3 |= 1 << 1; break; + case BUTTON_B: buttons.button3 |= 1 << 2; break; + case BUTTON_A: buttons.button3 |= 1 << 3; break; + case BUTTON_RIGHT_SR: buttons.button3 |= 1 << 4; break; + case BUTTON_RIGHT_SL: buttons.button3 |= 1 << 5; break; + case BUTTON_R: buttons.button3 |= 1 << 6; break; + case BUTTON_ZR: buttons.button3 |= 1 << 7; break; + + // Shared + case BUTTON_MINUS: buttons.button4 |= 1 << 0; break; + case BUTTON_PLUS: buttons.button4 |= 1 << 1; break; + case BUTTON_RCLICK: buttons.button4 |= 1 << 2; break; + case BUTTON_LCLICK: buttons.button4 |= 1 << 3; break; + case BUTTON_HOME: buttons.button4 |= 1 << 4; break; + case BUTTON_CAPTURE: buttons.button4 |= 1 << 5; break; + + // Left + case BUTTON_DOWN: buttons.button5 |= 1 << 0; break; + case BUTTON_UP: buttons.button5 |= 1 << 1; break; + case BUTTON_RIGHT: buttons.button5 |= 1 << 2; break; + case BUTTON_LEFT: buttons.button5 |= 1 << 3; break; + case BUTTON_LEFT_SR: buttons.button5 |= 1 << 4; break; + case BUTTON_LEFT_SL: buttons.button5 |= 1 << 5; break; + case BUTTON_L: buttons.button5 |= 1 << 6; break; + case BUTTON_ZL: buttons.button5 |= 1 << 7; break; + + default:; + } + } + return all_buttons; +} +bool SerialPABotBase_WirelessController::populate_report_gyro(PABB_NintendoSwitch_GyroState& gyro){ + bool gyro_active = false; + { + if (m_accel_x.is_busy()){ + gyro.accel_x = m_accel_x.value; + gyro_active = true; + } + if (m_accel_y.is_busy()){ + gyro.accel_y = m_accel_y.value; + gyro_active = true; + } + if (m_accel_z.is_busy()){ + gyro.accel_z = m_accel_z.value; + gyro_active = true; + } + if (m_rotation_x.is_busy()){ + gyro.rotation_x = m_rotation_x.value; + gyro_active = true; + } + if (m_rotation_y.is_busy()){ + gyro.rotation_y = m_rotation_y.value; + gyro_active = true; + } + if (m_rotation_z.is_busy()){ + gyro.rotation_z = m_rotation_z.value; + gyro_active = true; + } + } + return gyro_active; +} + + +void SerialPABotBase_WirelessController::issue_report( + const Cancellable* cancellable, + WallDuration duration, + const PABB_NintendoSwitch_ButtonState& buttons +){ + // Release the state lock since we are no longer touching state. + // This loop can block indefinitely if the command queue is full. + ReverseLockGuard lg(m_state_lock); + + // We will not do any throttling or timing adjustments here. We'll defer + // to the microcontroller to do that for us. + + // Divide the controller state into smaller chunks of 65535 milliseconds. + Milliseconds time_left = std::chrono::duration_cast(duration); + + while (time_left > Milliseconds::zero()){ + Milliseconds current = std::min(time_left, 65535ms); + m_serial->issue_request( + SerialPABotBase::MessageControllerStateButtons( + (uint16_t)current.count(), + buttons + ), + cancellable + ); + time_left -= current; + } +} +void SerialPABotBase_WirelessController::issue_report( + const Cancellable* cancellable, + WallDuration duration, + const PABB_NintendoSwitch_ButtonState& buttons, + const PABB_NintendoSwitch_GyroState& gyro +){ + // Release the state lock since we are no longer touching state. + // This loop can block indefinitely if the command queue is full. + ReverseLockGuard lg(m_state_lock); + + // TODO: For now we duplicate the gyro data to all 3 5ms segments. + PABB_NintendoSwitch_GyroStateX3 gyro3{ + gyro, gyro, gyro + }; + +#if 0 + // Purturb results to show the Switch that they are not stuck. + if (gyro3.time1.accel_x > 0){ + gyro3.time0.accel_x--; + gyro3.time2.accel_x--; + }else if (gyro3.time1.accel_x < 0){ + gyro3.time0.accel_x++; + gyro3.time2.accel_x++; + }else{ + gyro3.time0.accel_x--; + gyro3.time2.accel_x++; + } + if (gyro3.time1.accel_y > 0){ + gyro3.time0.accel_y--; + gyro3.time2.accel_y--; + }else if (gyro3.time1.accel_y < 0){ + gyro3.time0.accel_y++; + gyro3.time2.accel_y++; + }else{ + gyro3.time0.accel_y--; + gyro3.time2.accel_y++; + } + if (gyro3.time1.accel_z > 0){ + gyro3.time0.accel_z--; + gyro3.time2.accel_z--; + }else if (gyro3.time1.accel_z < 0){ + gyro3.time0.accel_z++; + gyro3.time2.accel_z++; + }else{ + gyro3.time0.accel_z--; + gyro3.time2.accel_z++; + } +#endif + + // We will not do any throttling or timing adjustments here. We'll defer + // to the microcontroller to do that for us. + + // Divide the controller state into smaller chunks of 65535 milliseconds. + Milliseconds time_left = std::chrono::duration_cast(duration); + + while (time_left > Milliseconds::zero()){ + Milliseconds current = std::min(time_left, 65535ms); + m_serial->issue_request( + SerialPABotBase::MessageControllerStateFull( + (uint16_t)current.count(), + buttons, gyro3 + ), + cancellable + ); + time_left -= current; + } +} + + + + +void SerialPABotBase_WirelessController::status_thread(){ + constexpr std::chrono::milliseconds PERIOD(1000); + std::atomic last_ack(current_time()); + + // Read controller colors. + std::string color_html; +#if 1 + try{ + m_logger.log("Reading Controller Colors..."); + + using ControllerColors = PABB_NintendoSwitch_ControllerColors; + + BotBaseMessage response = m_serial->issue_request_and_wait( + SerialPABotBase::MessageControllerReadSpi( + m_controller_type, + 0x00006050, sizeof(ControllerColors) + ), + &m_scope + ); + + ControllerColors colors{}; + if (response.body.size() == sizeof(seqnum_t) + sizeof(ControllerColors)){ + memcpy(&colors, response.body.data() + sizeof(seqnum_t), sizeof(ControllerColors)); + }else{ + m_logger.log( + "Invalid response size to PABB_MSG_ESP32_REQUEST_READ_SPI: body = " + std::to_string(response.body.size()), + COLOR_RED + ); + m_handle.set_status_line1("Error: See log for more information.", COLOR_RED); + return; + } + m_logger.log("Reading Controller Colors... Done"); + + switch (m_controller_type){ + case ControllerType::NintendoSwitch_WirelessProController:{ + Color left(colors.left_grip[0], colors.left_grip[1], colors.left_grip[2]); + Color body(colors.body[0], colors.body[1], colors.body[2]); + Color right(colors.right_grip[0], colors.right_grip[1], colors.right_grip[2]); + color_html += html_color_text("⬤", left); + color_html += " " + html_color_text("⬤", body); + color_html += " " + html_color_text("⬤", right); + break; + } + case ControllerType::NintendoSwitch_LeftJoycon: + case ControllerType::NintendoSwitch_RightJoycon:{ + Color body(colors.body[0], colors.body[1], colors.body[2]); + color_html = html_color_text("⬤", body); + break; + } + default:; + } + + }catch (Exception& e){ + e.log(m_logger); + m_handle.set_status_line1("Error: See log for more information.", COLOR_RED); + return; + } +#endif + + + std::thread watchdog([&, this]{ + WallClock next_ping = current_time(); + while (true){ + if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ + break; + } + + auto last = current_time() - last_ack.load(std::memory_order_relaxed); + std::chrono::duration seconds = last; + if (last > 2 * PERIOD){ + std::string text = "Last Ack: " + tostr_fixed(seconds.count(), 3) + " seconds ago"; + m_handle.set_status_line1(text, COLOR_RED); +// m_logger.log("Connection issue detected. Turning on all logging..."); +// settings.log_everything.store(true, std::memory_order_release); + } + + std::unique_lock lg(m_sleep_lock); + if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ + break; + } + + WallClock now = current_time(); + next_ping += PERIOD; + if (now + PERIOD < next_ping){ + next_ping = now + PERIOD; + } + m_cv.wait_until(lg, next_ping); + } + }); + + WallClock next_ping = current_time(); + while (true){ + if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ + break; + } + + std::string error; + try{ + pabb_MsgAckRequestI32 response; + m_serial->issue_request_and_wait( + SerialPABotBase::MessageControllerStatus(), + &m_scope + ).convert(m_logger, response); + last_ack.store(current_time(), std::memory_order_relaxed); + + uint32_t status = response.data; + bool status_connected = status & 1; + bool status_ready = status & 2; + + std::string str; + str += "Connected: " + (status_connected + ? html_color_text("Yes", theme_friendly_darkblue()) + : html_color_text("No", COLOR_RED) + ); + str += " - Ready: " + (status_ready + ? html_color_text("Yes", theme_friendly_darkblue()) + : html_color_text("No", COLOR_RED) + ); + str += " - " + color_html; + + m_handle.set_status_line1(str); + }catch (OperationCancelledException&){ + break; + }catch (InvalidConnectionStateException&){ + break; + }catch (SerialProtocolException& e){ + error = e.message(); + }catch (ConnectionException& e){ + error = e.message(); + }catch (...){ + error = "Unknown error."; + } + if (!error.empty()){ + stop(); + m_handle.set_status_line1(error, COLOR_RED); + break; + } + +// cout << "lock()" << endl; + std::unique_lock lg(m_sleep_lock); +// cout << "lock() - done" << endl; + if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ + break; + } + + WallClock now = current_time(); + next_ping += PERIOD; + if (now + PERIOD < next_ping){ + next_ping = now + PERIOD; + } + m_cv.wait_until(lg, next_ping); + } + + { + std::unique_lock lg(m_sleep_lock); + m_cv.notify_all(); + } + watchdog.join(); +} + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessController.h b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessController.h index 367d09a4ba..1cf6222c82 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessController.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessController.h @@ -1,143 +1,143 @@ -/* SerialPABotBase: Wireless Controller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_SerialPABotBase_WirelessController_H -#define PokemonAutomation_NintendoSwitch_SerialPABotBase_WirelessController_H - -#include -#include "Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h" -#include "Controllers/JoystickTools.h" -#include "NintendoSwitch_SerialPABotBase_Controller.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -class SerialPABotBase_WirelessController : public SerialPABotBase_Controller{ -public: - SerialPABotBase_WirelessController( - Logger& logger, - SerialPABotBase::SerialPABotBase_Connection& connection, - ControllerType controller_type - ); - ~SerialPABotBase_WirelessController(); - void stop(); - - -public: - Milliseconds ticksize() const{ - return Milliseconds(0); - } - Milliseconds cooldown() const{ - return Milliseconds(15); - } - Milliseconds timing_variation() const{ - return m_timing_variation; - } - - -protected: - template - void encode_joystick(uint8_t data[3], uint8_t x, uint8_t y){ - // 2048 is the neutral position. - // - // 1897 is the point where the joystick calibrator will register it as - // off-center. - // - // ~320 is where it reaches the maximum value. - // - // If we linearly interpolate between 1897 and 320, we seem to match - // the wired controller's behavior. - // - // I suspect the need to offset by 151 from 2048 -> 1897 is Nintendo's - // way to alleviate the joycon drift problem. - // - // The values 320 and 1897 are for the pro controller. Joycons are - // slightly different. - // - - double fx = JoystickTools::linear_u8_to_float(x); - double fy = -JoystickTools::linear_u8_to_float(y); -// cout << "fx = " << fx << ", fy = " << fy << endl; - double mag_squared = fx*fx + fy*fy; - - uint16_t wx, wy; - if (mag_squared == 0){ - wx = 2048; - wy = 2048; - }else if (mag_squared >= 1){ - JoystickTools::max_out_magnitude(fx, fy); - wx = JoystickTools::linear_float_to_u12(fx); - wy = JoystickTools::linear_float_to_u12(fy); - }else{ - constexpr double lo = 1 - min_threshold / 2048.; - constexpr double hi = 1 - max_threshold / 2048.; - - double true_mag = std::sqrt(mag_squared); - double report_mag = JoystickTools::project_to_range(true_mag, lo, hi); - double scale = report_mag / true_mag; - wx = JoystickTools::linear_float_to_u12(fx * scale); - wy = JoystickTools::linear_float_to_u12(fy * scale); - } - -// cout << "wx = " << wx << ", wy = " << wy << endl; -// wy = 2048; -// wx = 1874; -// wx = 320; - - data[0] = (uint8_t)wx; - data[1] = (uint8_t)(wx >> 8 | wy << 4); - data[2] = (uint8_t)(wy >> 4); - } - - Button populate_report_buttons(PABB_NintendoSwitch_ButtonState& buttons); - bool populate_report_gyro(PABB_NintendoSwitch_GyroState& gyro); - - void issue_report( - const Cancellable* cancellable, - WallDuration duration, - const PABB_NintendoSwitch_ButtonState& buttons - ); - void issue_report( - const Cancellable* cancellable, - WallDuration duration, - const PABB_NintendoSwitch_ButtonState& buttons, - const PABB_NintendoSwitch_GyroState& gyro - ); - - -private: -#if 0 - template - PA_FORCE_INLINE Type milliseconds_to_ticks_15ms(Type milliseconds){ - return milliseconds / 15 + (milliseconds % 15 + 14) / 15; - } -#endif - - void status_thread(); - - -protected: - const ControllerType m_controller_type; - Milliseconds m_timing_variation; -private: - CancellableHolder m_scope; - std::atomic m_stopping; - std::mutex m_sleep_lock; - std::condition_variable m_cv; - std::thread m_status_thread; -}; - - - -} -} -#endif +/* SerialPABotBase: Wireless Controller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SerialPABotBase_WirelessController_H +#define PokemonAutomation_NintendoSwitch_SerialPABotBase_WirelessController_H + +#include +#include "Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h" +#include "Controllers/JoystickTools.h" +#include "NintendoSwitch_SerialPABotBase_Controller.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +class SerialPABotBase_WirelessController : public SerialPABotBase_Controller{ +public: + SerialPABotBase_WirelessController( + Logger& logger, + SerialPABotBase::SerialPABotBase_Connection& connection, + ControllerType controller_type + ); + ~SerialPABotBase_WirelessController(); + void stop(); + + +public: + Milliseconds ticksize() const{ + return Milliseconds(0); + } + Milliseconds cooldown() const{ + return Milliseconds(15); + } + Milliseconds timing_variation() const{ + return m_timing_variation; + } + + +protected: + template + void encode_joystick(uint8_t data[3], uint8_t x, uint8_t y){ + // 2048 is the neutral position. + // + // 1897 is the point where the joystick calibrator will register it as + // off-center. + // + // ~320 is where it reaches the maximum value. + // + // If we linearly interpolate between 1897 and 320, we seem to match + // the wired controller's behavior. + // + // I suspect the need to offset by 151 from 2048 -> 1897 is Nintendo's + // way to alleviate the joycon drift problem. + // + // The values 320 and 1897 are for the pro controller. Joycons are + // slightly different. + // + + double fx = JoystickTools::linear_u8_to_float(x); + double fy = -JoystickTools::linear_u8_to_float(y); +// cout << "fx = " << fx << ", fy = " << fy << endl; + double mag_squared = fx*fx + fy*fy; + + uint16_t wx, wy; + if (mag_squared == 0){ + wx = 2048; + wy = 2048; + }else if (mag_squared >= 1){ + JoystickTools::max_out_magnitude(fx, fy); + wx = JoystickTools::linear_float_to_u12(fx); + wy = JoystickTools::linear_float_to_u12(fy); + }else{ + constexpr double lo = 1 - min_threshold / 2048.; + constexpr double hi = 1 - max_threshold / 2048.; + + double true_mag = std::sqrt(mag_squared); + double report_mag = JoystickTools::project_to_range(true_mag, lo, hi); + double scale = report_mag / true_mag; + wx = JoystickTools::linear_float_to_u12(fx * scale); + wy = JoystickTools::linear_float_to_u12(fy * scale); + } + +// cout << "wx = " << wx << ", wy = " << wy << endl; +// wy = 2048; +// wx = 1874; +// wx = 320; + + data[0] = (uint8_t)wx; + data[1] = (uint8_t)(wx >> 8 | wy << 4); + data[2] = (uint8_t)(wy >> 4); + } + + Button populate_report_buttons(PABB_NintendoSwitch_ButtonState& buttons); + bool populate_report_gyro(PABB_NintendoSwitch_GyroState& gyro); + + void issue_report( + const Cancellable* cancellable, + WallDuration duration, + const PABB_NintendoSwitch_ButtonState& buttons + ); + void issue_report( + const Cancellable* cancellable, + WallDuration duration, + const PABB_NintendoSwitch_ButtonState& buttons, + const PABB_NintendoSwitch_GyroState& gyro + ); + + +private: +#if 0 + template + PA_FORCE_INLINE Type milliseconds_to_ticks_15ms(Type milliseconds){ + return milliseconds / 15 + (milliseconds % 15 + 14) / 15; + } +#endif + + void status_thread(); + + +protected: + const ControllerType m_controller_type; + Milliseconds m_timing_variation; +private: + CancellableHolder m_scope; + std::atomic m_stopping; + std::mutex m_sleep_lock; + std::condition_variable m_cv; + std::thread m_status_thread; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessJoycon.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessJoycon.cpp index 77574ddc9f..745c187db4 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessJoycon.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessJoycon.cpp @@ -1,205 +1,207 @@ -/* SerialPABotBase: Wireless Joycon - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "ClientSource/Libraries/MessageConverter.h" -#include "NintendoSwitch_SerialPABotBase_WirelessJoycon.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -SerialPABotBase_WirelessJoycon::SerialPABotBase_WirelessJoycon( - Logger& logger, - SerialPABotBase::SerialPABotBase_Connection& connection, - ControllerType controller_type -) - : JoyconController(controller_type) - , SerialPABotBase_WirelessController( - logger, - connection, - controller_type - ) - , m_controller_type(controller_type) -{ - switch (controller_type){ - case ControllerType::NintendoSwitch_LeftJoycon: - m_valid_buttons = VALID_LEFT_JOYCON_BUTTONS; - break; - case ControllerType::NintendoSwitch_RightJoycon: - m_valid_buttons = VALID_RIGHT_JOYCON_BUTTONS; - break; - default: - throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Invalid joycon type."); - } -} -SerialPABotBase_WirelessJoycon::~SerialPABotBase_WirelessJoycon(){ - JoyconController::stop(); - SerialPABotBase_WirelessController::stop(); -} - - - -void SerialPABotBase_WirelessJoycon::issue_buttons( - const Cancellable* cancellable, - Button button, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown -){ - button &= m_valid_buttons; - switch (m_controller_type){ - case ControllerType::NintendoSwitch_LeftJoycon: - ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); - break; - case ControllerType::NintendoSwitch_RightJoycon: - ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); - break; - default: - throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Invalid joycon type."); - } -} -void SerialPABotBase_WirelessJoycon::issue_joystick( - const Cancellable* cancellable, - uint8_t x, uint8_t y, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown -){ - switch (m_controller_type){ - case ControllerType::NintendoSwitch_LeftJoycon: - ControllerWithScheduler::issue_left_joystick(cancellable, delay, hold, cooldown, x, y); - break; - case ControllerType::NintendoSwitch_RightJoycon: - ControllerWithScheduler::issue_right_joystick(cancellable, delay, hold, cooldown, x, y); - break; - default: - throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Invalid joycon type."); - } -} -void SerialPABotBase_WirelessJoycon::issue_full_controller_state( - const Cancellable* cancellable, - Button button, - uint8_t joystick_x, uint8_t joystick_y, - Milliseconds hold -){ - button &= m_valid_buttons; - switch (m_controller_type){ - case ControllerType::NintendoSwitch_LeftJoycon: - ControllerWithScheduler::issue_full_controller_state( - cancellable, - hold, - button, - DPAD_NONE, - joystick_x, joystick_y, - 0x80, 0x80 - ); - break; - case ControllerType::NintendoSwitch_RightJoycon: - ControllerWithScheduler::issue_full_controller_state( - cancellable, - hold, - button, - DPAD_NONE, - 0x80, 0x80, - joystick_x, joystick_y - ); - break; - default:; - } -} - - - -void SerialPABotBase_WirelessJoycon::issue_mash_button( - const Cancellable* cancellable, - Button button, Milliseconds duration -){ - button &= m_valid_buttons; - ControllerWithScheduler::issue_mash_button(cancellable, duration, button); -} - - - - -void SerialPABotBase_WirelessJoycon::push_state_left_joycon(const Cancellable* cancellable, WallDuration duration){ - PABB_NintendoSwitch_ButtonState buttons{ - .button3 = 0, - .button4 = 0, - .button5 = 0, - .left_joystick = {0x00, 0x08, 0x80}, - .right_joystick = {0x00, 0x08, 0x80}, - .vibrator = 0x00, - }; - - populate_report_buttons(buttons); - - // Left Stick - if (m_left_joystick.is_busy()){ - encode_joystick( - buttons.left_joystick, - m_left_joystick.x, m_left_joystick.y - ); - } - - PABB_NintendoSwitch_GyroState gyro{}; - bool gyro_active = populate_report_gyro(gyro); - - if (!gyro_active){ - issue_report(cancellable, duration, buttons); - }else{ - issue_report(cancellable, duration, buttons, gyro); - } -} -void SerialPABotBase_WirelessJoycon::push_state_right_joycon(const Cancellable* cancellable, WallDuration duration){ - PABB_NintendoSwitch_ButtonState buttons{ - .button3 = 0, - .button4 = 0, - .button5 = 0, - .left_joystick = {0x00, 0x08, 0x80}, - .right_joystick = {0x00, 0x08, 0x80}, - .vibrator = 0x00, - }; - - populate_report_buttons(buttons); - - // Right Stick - if (m_right_joystick.is_busy()){ - encode_joystick( - buttons.right_joystick, - m_right_joystick.x, m_right_joystick.y - ); - } - - PABB_NintendoSwitch_GyroState gyro{}; - bool gyro_active = populate_report_gyro(gyro); - - if (!gyro_active){ - issue_report(cancellable, duration, buttons); - }else{ - issue_report(cancellable, duration, buttons, gyro); - } -} -void SerialPABotBase_WirelessJoycon::push_state(const Cancellable* cancellable, WallDuration duration){ - switch (m_controller_type){ - case ControllerType::NintendoSwitch_LeftJoycon: - push_state_left_joycon(cancellable, duration); - break; - case ControllerType::NintendoSwitch_RightJoycon: - push_state_right_joycon(cancellable, duration); - break; - default: - throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Invalid joycon type."); - } -} - - - - - -} -} +/* SerialPABotBase: Wireless Joycon + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "ClientSource/Libraries/MessageConverter.h" +#include "NintendoSwitch_SerialPABotBase_WirelessJoycon.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +SerialPABotBase_WirelessJoycon::SerialPABotBase_WirelessJoycon( + Logger& logger, + SerialPABotBase::SerialPABotBase_Connection& connection, + ControllerType controller_type +) + : JoyconController(logger, controller_type) + , SerialPABotBase_WirelessController( + logger, + connection, + controller_type + ) + , m_controller_type(controller_type) +{ + switch (controller_type){ + case ControllerType::NintendoSwitch_LeftJoycon: + m_valid_buttons = VALID_LEFT_JOYCON_BUTTONS; + break; + case ControllerType::NintendoSwitch_RightJoycon: + m_valid_buttons = VALID_RIGHT_JOYCON_BUTTONS; + break; + default: + throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Invalid joycon type."); + } +} +SerialPABotBase_WirelessJoycon::~SerialPABotBase_WirelessJoycon(){ + JoyconController::stop(); + SerialPABotBase_WirelessController::stop(); +} + + + +void SerialPABotBase_WirelessJoycon::issue_buttons( + const Cancellable* cancellable, + Button button, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown +){ + button &= m_valid_buttons; + switch (m_controller_type){ + case ControllerType::NintendoSwitch_LeftJoycon: + ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); + break; + case ControllerType::NintendoSwitch_RightJoycon: + ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); + break; + default: + throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Invalid joycon type."); + } +} +void SerialPABotBase_WirelessJoycon::issue_joystick( + const Cancellable* cancellable, + uint8_t x, uint8_t y, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown +){ + switch (m_controller_type){ + case ControllerType::NintendoSwitch_LeftJoycon: + ControllerWithScheduler::issue_left_joystick(cancellable, delay, hold, cooldown, x, y); + break; + case ControllerType::NintendoSwitch_RightJoycon: + ControllerWithScheduler::issue_right_joystick(cancellable, delay, hold, cooldown, x, y); + break; + default: + throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Invalid joycon type."); + } +} +void SerialPABotBase_WirelessJoycon::issue_full_controller_state( + const Cancellable* cancellable, + Button button, + uint8_t joystick_x, uint8_t joystick_y, + Milliseconds hold +){ + button &= m_valid_buttons; + switch (m_controller_type){ + case ControllerType::NintendoSwitch_LeftJoycon: + ControllerWithScheduler::issue_full_controller_state( + cancellable, + hold, + button, + DPAD_NONE, + joystick_x, joystick_y, + 0x80, 0x80 + ); + break; + case ControllerType::NintendoSwitch_RightJoycon: + ControllerWithScheduler::issue_full_controller_state( + cancellable, + hold, + button, + DPAD_NONE, + 0x80, 0x80, + joystick_x, joystick_y + ); + break; + default:; + } +} + + + +void SerialPABotBase_WirelessJoycon::issue_mash_button( + const Cancellable* cancellable, + Button button, Milliseconds duration +){ + button &= m_valid_buttons; + ControllerWithScheduler::issue_mash_button(cancellable, duration, button); +} + + + + +void SerialPABotBase_WirelessJoycon::push_state_left_joycon(const Cancellable* cancellable, WallDuration duration){ + PABB_NintendoSwitch_ButtonState buttons{ + .button3 = 0, + .button4 = 0, + .button5 = 0, + .left_joystick = {0x00, 0x08, 0x80}, + .right_joystick = {0x00, 0x08, 0x80}, + .vibrator = 0x00, + }; + + populate_report_buttons(buttons); + + // Left Stick + if (m_left_joystick.is_busy()){ + encode_joystick( + buttons.left_joystick, + m_left_joystick.x, m_left_joystick.y + ); + } + + PABB_NintendoSwitch_GyroState gyro{}; + bool gyro_active = populate_report_gyro(gyro); + + if (!gyro_active){ + issue_report(cancellable, duration, buttons); + }else{ + issue_report(cancellable, duration, buttons, gyro); + } +} +void SerialPABotBase_WirelessJoycon::push_state_right_joycon(const Cancellable* cancellable, WallDuration duration){ + PABB_NintendoSwitch_ButtonState buttons{ + .button3 = 0, + .button4 = 0, + .button5 = 0, + .left_joystick = {0x00, 0x08, 0x80}, + .right_joystick = {0x00, 0x08, 0x80}, + .vibrator = 0x00, + }; + + populate_report_buttons(buttons); + + // Right Stick + if (m_right_joystick.is_busy()){ + encode_joystick( + buttons.right_joystick, + m_right_joystick.x, m_right_joystick.y + ); + } + +// cout << (int)m_right_joystick.x << " - " << (int)m_right_joystick.y << ": " << std::chrono::duration_cast(duration).count() << endl; + + PABB_NintendoSwitch_GyroState gyro{}; + bool gyro_active = populate_report_gyro(gyro); + + if (!gyro_active){ + issue_report(cancellable, duration, buttons); + }else{ + issue_report(cancellable, duration, buttons, gyro); + } +} +void SerialPABotBase_WirelessJoycon::push_state(const Cancellable* cancellable, WallDuration duration){ + switch (m_controller_type){ + case ControllerType::NintendoSwitch_LeftJoycon: + push_state_left_joycon(cancellable, duration); + break; + case ControllerType::NintendoSwitch_RightJoycon: + push_state_right_joycon(cancellable, duration); + break; + default: + throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Invalid joycon type."); + } +} + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessJoycon.h b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessJoycon.h index a6dba0d875..36db7f697a 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessJoycon.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessJoycon.h @@ -1,176 +1,176 @@ -/* SerialPABotBase: Wireless Joycon - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_SerialPABotBase_WirelessJoycon_H -#define PokemonAutomation_NintendoSwitch_SerialPABotBase_WirelessJoycon_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch_SerialPABotBase_Controller.h" -#include "NintendoSwitch_SerialPABotBase_WirelessController.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class SerialPABotBase_WirelessJoycon final : - public JoyconController, - public SerialPABotBase_WirelessController -{ - static constexpr uint16_t JOYSTICK_MIN_THRESHOLD = 1874; - static constexpr uint16_t JOYSTICK_MAX_THRESHOLD = 260; - -public: - SerialPABotBase_WirelessJoycon( - Logger& logger, - SerialPABotBase::SerialPABotBase_Connection& connection, - ControllerType controller_type - ); - ~SerialPABotBase_WirelessJoycon(); - - virtual Logger& logger() override{ - return m_logger; - } - virtual RecursiveThrottler& logging_throttler() override{ - return m_logging_throttler; - } - virtual bool is_ready() const override{ - return SerialPABotBase_Controller::is_ready(); - } - - -public: - virtual ControllerType controller_type() const override{ - return m_controller_type; - } - virtual const ControllerFeatures& controller_features() const override{ - return m_supported_features; - } - virtual ControllerPerformanceClass performance_class() const override{ - return ControllerPerformanceClass::SerialPABotBase_Wireless_ESP32; - } - - virtual Milliseconds ticksize() const override{ - return SerialPABotBase_WirelessController::ticksize(); - } - virtual Milliseconds cooldown() const override{ - return SerialPABotBase_WirelessController::cooldown(); - } - virtual Milliseconds timing_variation() const override{ - return SerialPABotBase_WirelessController::timing_variation(); - } - virtual bool atomic_multibutton() const override{ - return true; - } - - -public: - virtual void cancel_all_commands() override{ - SerialPABotBase_Controller::cancel_all_commands(); - } - virtual void replace_on_next_command() override{ - SerialPABotBase_Controller::replace_on_next_command(); - } - - virtual void wait_for_all(const Cancellable* cancellable) override{ - SerialPABotBase_Controller::wait_for_all(cancellable); - } - - -public: - // Superscalar Commands (the "ssf" framework) - - virtual void issue_barrier(const Cancellable* cancellable) override{ - ControllerWithScheduler::issue_barrier(cancellable); - } - virtual void issue_nop(const Cancellable* cancellable, Milliseconds duration) override{ - ControllerWithScheduler::issue_nop(cancellable, duration); - } - - virtual void issue_buttons( - const Cancellable* cancellable, - Button button, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown - ) override; - virtual void issue_joystick( - const Cancellable* cancellable, - uint8_t x, uint8_t y, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown - ) override; - - virtual void issue_gyro_accel_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_x(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_accel_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_y(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_accel_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_z(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_x(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_y(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_z(cancellable, delay, hold, cooldown, value); - } - - virtual void issue_full_controller_state( - const Cancellable* cancellable, - Button button, - uint8_t joystick_x, uint8_t joystick_y, - Milliseconds hold - ) override; - - -public: - // High speed RPCs. - - virtual void issue_mash_button( - const Cancellable* cancellable, - Button button, Milliseconds duration - ) override; - - -private: - void push_state_left_joycon(const Cancellable* cancellable, WallDuration duration); - void push_state_right_joycon(const Cancellable* cancellable, WallDuration duration); - virtual void push_state(const Cancellable* cancellable, WallDuration duration) override; - - ControllerType m_controller_type; - Button m_valid_buttons; -}; - - - -} -} -#endif +/* SerialPABotBase: Wireless Joycon + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SerialPABotBase_WirelessJoycon_H +#define PokemonAutomation_NintendoSwitch_SerialPABotBase_WirelessJoycon_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch_SerialPABotBase_Controller.h" +#include "NintendoSwitch_SerialPABotBase_WirelessController.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class SerialPABotBase_WirelessJoycon final : + public JoyconController, + public SerialPABotBase_WirelessController +{ + static constexpr uint16_t JOYSTICK_MIN_THRESHOLD = 1874; + static constexpr uint16_t JOYSTICK_MAX_THRESHOLD = 260; + +public: + SerialPABotBase_WirelessJoycon( + Logger& logger, + SerialPABotBase::SerialPABotBase_Connection& connection, + ControllerType controller_type + ); + ~SerialPABotBase_WirelessJoycon(); + + virtual Logger& logger() override{ + return m_logger; + } + virtual RecursiveThrottler& logging_throttler() override{ + return m_logging_throttler; + } + virtual bool is_ready() const override{ + return SerialPABotBase_Controller::is_ready(); + } + + +public: + virtual ControllerType controller_type() const override{ + return m_controller_type; + } + virtual const ControllerFeatures& controller_features() const override{ + return m_supported_features; + } + virtual ControllerPerformanceClass performance_class() const override{ + return ControllerPerformanceClass::SerialPABotBase_Wireless; + } + + virtual Milliseconds ticksize() const override{ + return SerialPABotBase_WirelessController::ticksize(); + } + virtual Milliseconds cooldown() const override{ + return SerialPABotBase_WirelessController::cooldown(); + } + virtual Milliseconds timing_variation() const override{ + return SerialPABotBase_WirelessController::timing_variation(); + } + virtual bool atomic_multibutton() const override{ + return true; + } + + +public: + virtual void cancel_all_commands() override{ + SerialPABotBase_Controller::cancel_all_commands(); + } + virtual void replace_on_next_command() override{ + SerialPABotBase_Controller::replace_on_next_command(); + } + + virtual void wait_for_all(const Cancellable* cancellable) override{ + SerialPABotBase_Controller::wait_for_all(cancellable); + } + + +public: + // Superscalar Commands (the "ssf" framework) + + virtual void issue_barrier(const Cancellable* cancellable) override{ + ControllerWithScheduler::issue_barrier(cancellable); + } + virtual void issue_nop(const Cancellable* cancellable, Milliseconds duration) override{ + ControllerWithScheduler::issue_nop(cancellable, duration); + } + + virtual void issue_buttons( + const Cancellable* cancellable, + Button button, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown + ) override; + virtual void issue_joystick( + const Cancellable* cancellable, + uint8_t x, uint8_t y, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown + ) override; + + virtual void issue_gyro_accel_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_x(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_accel_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_y(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_accel_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_z(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_x(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_y(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_z(cancellable, delay, hold, cooldown, value); + } + + virtual void issue_full_controller_state( + const Cancellable* cancellable, + Button button, + uint8_t joystick_x, uint8_t joystick_y, + Milliseconds hold + ) override; + + +public: + // High speed RPCs. + + virtual void issue_mash_button( + const Cancellable* cancellable, + Button button, Milliseconds duration + ) override; + + +private: + void push_state_left_joycon(const Cancellable* cancellable, WallDuration duration); + void push_state_right_joycon(const Cancellable* cancellable, WallDuration duration); + virtual void push_state(const Cancellable* cancellable, WallDuration duration) override; + + ControllerType m_controller_type; + Button m_valid_buttons; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessProController.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessProController.cpp index a541a3d403..90b6903745 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessProController.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessProController.cpp @@ -1,112 +1,113 @@ -/* SerialPABotBase: Wireless Pro Controller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h" -#include "ClientSource/Libraries/MessageConverter.h" -#include "NintendoSwitch_SerialPABotBase_WirelessProController.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -SerialPABotBase_WirelessProController::SerialPABotBase_WirelessProController( - Logger& logger, - SerialPABotBase::SerialPABotBase_Connection& connection -) - : SerialPABotBase_WirelessController( - logger, - connection, - ControllerType::NintendoSwitch_WirelessProController - ) -{} -SerialPABotBase_WirelessProController::~SerialPABotBase_WirelessProController(){ - ProController::stop(); - SerialPABotBase_WirelessController::stop(); -} - - -void SerialPABotBase_WirelessProController::push_state(const Cancellable* cancellable, WallDuration duration){ - // https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/bluetooth_hid_notes.md - - PABB_NintendoSwitch_ButtonState buttons{ - .button3 = 0, - .button4 = 0, - .button5 = 0, - .left_joystick = {0x00, 0x08, 0x80}, - .right_joystick = {0x00, 0x08, 0x80}, - .vibrator = 0x00, - }; - -// Button all_buttons = - populate_report_buttons(buttons); - - if (m_dpad.is_busy()){ - SplitDpad dpad = convert_unified_to_split_dpad(m_dpad.position); - buttons.button5 |= (dpad.down ? 1 : 0) << 0; - buttons.button5 |= (dpad.up ? 1 : 0) << 1; - buttons.button5 |= (dpad.right ? 1 : 0) << 2; - buttons.button5 |= (dpad.left ? 1 : 0) << 3; - } - - // Left Stick - if (m_left_joystick.is_busy()){ - encode_joystick( - buttons.left_joystick, - m_left_joystick.x, m_left_joystick.y - ); - } - - // Right Stick - if (m_right_joystick.is_busy()){ - encode_joystick( - buttons.right_joystick, - m_right_joystick.x, m_right_joystick.y - ); - } - - PABB_NintendoSwitch_GyroState gyro{ - 0x0000, - 0x0000, - 0x0000, - 0x0000, - 0x0000, - 0x0000, - }; - bool gyro_active = populate_report_gyro(gyro); - -// gyro_active = true; -// gyro.rotation_y = 0x00ff; -// gyro.rotation_z = 0x000f; - - if (!gyro_active){ - issue_report(cancellable, duration, buttons); - }else{ - issue_report(cancellable, duration, buttons, gyro); - } - -#if 0 - m_logger.log( - "push_state(): (" + button_to_string(all_buttons) + - "), dpad(" + dpad_to_string(m_dpad.position) + - "), LJ(" + std::to_string(m_left_joystick.x) + "," + std::to_string(m_left_joystick.y) + - "), RJ(" + std::to_string(m_right_joystick.x) + "," + std::to_string(m_right_joystick.y) + - "), hold = " + std::to_string(std::chrono::duration_cast(duration).count()) + "ms", - COLOR_DARKGREEN - ); -#endif -} - - - - - -} -} +/* SerialPABotBase: Wireless Pro Controller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h" +#include "ClientSource/Libraries/MessageConverter.h" +#include "NintendoSwitch_SerialPABotBase_WirelessProController.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +SerialPABotBase_WirelessProController::SerialPABotBase_WirelessProController( + Logger& logger, + SerialPABotBase::SerialPABotBase_Connection& connection +) + : ProController(logger) + , SerialPABotBase_WirelessController( + logger, + connection, + ControllerType::NintendoSwitch_WirelessProController + ) +{} +SerialPABotBase_WirelessProController::~SerialPABotBase_WirelessProController(){ + ProController::stop(); + SerialPABotBase_WirelessController::stop(); +} + + +void SerialPABotBase_WirelessProController::push_state(const Cancellable* cancellable, WallDuration duration){ + // https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/bluetooth_hid_notes.md + + PABB_NintendoSwitch_ButtonState buttons{ + .button3 = 0, + .button4 = 0, + .button5 = 0, + .left_joystick = {0x00, 0x08, 0x80}, + .right_joystick = {0x00, 0x08, 0x80}, + .vibrator = 0x00, + }; + +// Button all_buttons = + populate_report_buttons(buttons); + + if (m_dpad.is_busy()){ + SplitDpad dpad = convert_unified_to_split_dpad(m_dpad.position); + buttons.button5 |= (dpad.down ? 1 : 0) << 0; + buttons.button5 |= (dpad.up ? 1 : 0) << 1; + buttons.button5 |= (dpad.right ? 1 : 0) << 2; + buttons.button5 |= (dpad.left ? 1 : 0) << 3; + } + + // Left Stick + if (m_left_joystick.is_busy()){ + encode_joystick( + buttons.left_joystick, + m_left_joystick.x, m_left_joystick.y + ); + } + + // Right Stick + if (m_right_joystick.is_busy()){ + encode_joystick( + buttons.right_joystick, + m_right_joystick.x, m_right_joystick.y + ); + } + + PABB_NintendoSwitch_GyroState gyro{ + 0x0000, + 0x0000, + 0x0000, + 0x0000, + 0x0000, + 0x0000, + }; + bool gyro_active = populate_report_gyro(gyro); + +// gyro_active = true; +// gyro.rotation_y = 0x00ff; +// gyro.rotation_z = 0x000f; + + if (!gyro_active){ + issue_report(cancellable, duration, buttons); + }else{ + issue_report(cancellable, duration, buttons, gyro); + } + +#if 0 + m_logger.log( + "push_state(): (" + button_to_string(all_buttons) + + "), dpad(" + dpad_to_string(m_dpad.position) + + "), LJ(" + std::to_string(m_left_joystick.x) + "," + std::to_string(m_left_joystick.y) + + "), RJ(" + std::to_string(m_right_joystick.x) + "," + std::to_string(m_right_joystick.y) + + "), hold = " + std::to_string(std::chrono::duration_cast(duration).count()) + "ms", + COLOR_DARKGREEN + ); +#endif +} + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessProController.h b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessProController.h index c09ec9808f..486ed271a1 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessProController.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessProController.h @@ -1,222 +1,222 @@ -/* SerialPABotBase: Wireless Pro Controller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_SerialPABotBase_WirelessProController_H -#define PokemonAutomation_NintendoSwitch_SerialPABotBase_WirelessProController_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch_SerialPABotBase_Controller.h" -#include "NintendoSwitch_SerialPABotBase_WirelessController.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class SerialPABotBase_WirelessProController final : - public ProController, - public SerialPABotBase_WirelessController -{ - static constexpr uint16_t JOYSTICK_MIN_THRESHOLD = 1874; - static constexpr uint16_t JOYSTICK_MAX_THRESHOLD = 320; - -public: - SerialPABotBase_WirelessProController( - Logger& logger, - SerialPABotBase::SerialPABotBase_Connection& connection - ); - ~SerialPABotBase_WirelessProController(); - - virtual Logger& logger() override{ - return m_logger; - } - virtual RecursiveThrottler& logging_throttler() override{ - return m_logging_throttler; - } - virtual bool is_ready() const override{ - return SerialPABotBase_Controller::is_ready(); - } - - -public: - virtual ControllerType controller_type() const override{ - return ControllerType::NintendoSwitch_WirelessProController; - } - virtual const ControllerFeatures& controller_features() const override{ - return m_supported_features; - } - virtual ControllerPerformanceClass performance_class() const override{ - return ControllerPerformanceClass::SerialPABotBase_Wireless_ESP32; - } - - virtual Milliseconds ticksize() const override{ - return SerialPABotBase_WirelessController::ticksize(); - } - virtual Milliseconds cooldown() const override{ - return SerialPABotBase_WirelessController::cooldown(); - } - virtual Milliseconds timing_variation() const override{ - return SerialPABotBase_WirelessController::timing_variation(); - } - virtual bool atomic_multibutton() const override{ - return true; - } - - -public: - virtual void cancel_all_commands() override{ - SerialPABotBase_Controller::cancel_all_commands(); - } - virtual void replace_on_next_command() override{ - SerialPABotBase_Controller::replace_on_next_command(); - } - - virtual void wait_for_all(const Cancellable* cancellable) override{ - SerialPABotBase_Controller::wait_for_all(cancellable); - } - - -public: - // Superscalar Commands (the "ssf" framework) - - virtual void issue_barrier(const Cancellable* cancellable) override{ - ControllerWithScheduler::issue_barrier(cancellable); - } - virtual void issue_nop(const Cancellable* cancellable, Milliseconds duration) override{ - ControllerWithScheduler::issue_nop(cancellable, duration); - } - - virtual void issue_buttons( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - Button button - ) override{ - ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); - } - virtual void issue_dpad( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition position - ) override{ - ControllerWithScheduler::issue_dpad(cancellable, delay, hold, cooldown, position); - } - virtual void issue_left_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y - ) override{ - ControllerWithScheduler::issue_left_joystick(cancellable, delay, hold, cooldown, x, y); - } - virtual void issue_right_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y - ) override{ - ControllerWithScheduler::issue_right_joystick(cancellable, delay, hold, cooldown, x, y); - } - - virtual void issue_gyro_accel_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_x(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_accel_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_y(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_accel_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_z(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_x(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_y(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_z(cancellable, delay, hold, cooldown, value); - } - - virtual void issue_full_controller_state( - const Cancellable* cancellable, - Milliseconds hold, - Button button, - DpadPosition position, - uint8_t left_x, uint8_t left_y, - uint8_t right_x, uint8_t right_y - ) override{ - ControllerWithScheduler::issue_full_controller_state( - cancellable, - hold, - button, - position, - left_x, left_y, - right_x, right_y - ); - } - - -public: - // High speed RPCs. - - virtual void issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button - ) override{ - ControllerWithScheduler::issue_mash_button(cancellable, duration, button); - } - virtual void issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button0, Button button1 - ) override{ - ControllerWithScheduler::issue_mash_button(cancellable, duration, button0, button1); - } - virtual void issue_mash_AZs( - const Cancellable* cancellable, - Milliseconds duration - ) override{ - ControllerWithScheduler::issue_mash_AZs(cancellable, duration); - } - virtual void issue_system_scroll( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition direction // Diagonals not allowed. - ) override{ - ControllerWithScheduler::issue_system_scroll(cancellable, delay, hold, cooldown, direction); - } - - -private: - virtual void push_state(const Cancellable* cancellable, WallDuration duration) override; -}; - - - -} -} -#endif +/* SerialPABotBase: Wireless Pro Controller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SerialPABotBase_WirelessProController_H +#define PokemonAutomation_NintendoSwitch_SerialPABotBase_WirelessProController_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch_SerialPABotBase_Controller.h" +#include "NintendoSwitch_SerialPABotBase_WirelessController.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class SerialPABotBase_WirelessProController final : + public ProController, + public SerialPABotBase_WirelessController +{ + static constexpr uint16_t JOYSTICK_MIN_THRESHOLD = 1874; + static constexpr uint16_t JOYSTICK_MAX_THRESHOLD = 320; + +public: + SerialPABotBase_WirelessProController( + Logger& logger, + SerialPABotBase::SerialPABotBase_Connection& connection + ); + ~SerialPABotBase_WirelessProController(); + + virtual Logger& logger() override{ + return m_logger; + } + virtual RecursiveThrottler& logging_throttler() override{ + return m_logging_throttler; + } + virtual bool is_ready() const override{ + return SerialPABotBase_Controller::is_ready(); + } + + +public: + virtual ControllerType controller_type() const override{ + return ControllerType::NintendoSwitch_WirelessProController; + } + virtual const ControllerFeatures& controller_features() const override{ + return m_supported_features; + } + virtual ControllerPerformanceClass performance_class() const override{ + return ControllerPerformanceClass::SerialPABotBase_Wireless; + } + + virtual Milliseconds ticksize() const override{ + return SerialPABotBase_WirelessController::ticksize(); + } + virtual Milliseconds cooldown() const override{ + return SerialPABotBase_WirelessController::cooldown(); + } + virtual Milliseconds timing_variation() const override{ + return SerialPABotBase_WirelessController::timing_variation(); + } + virtual bool atomic_multibutton() const override{ + return true; + } + + +public: + virtual void cancel_all_commands() override{ + SerialPABotBase_Controller::cancel_all_commands(); + } + virtual void replace_on_next_command() override{ + SerialPABotBase_Controller::replace_on_next_command(); + } + + virtual void wait_for_all(const Cancellable* cancellable) override{ + SerialPABotBase_Controller::wait_for_all(cancellable); + } + + +public: + // Superscalar Commands (the "ssf" framework) + + virtual void issue_barrier(const Cancellable* cancellable) override{ + ControllerWithScheduler::issue_barrier(cancellable); + } + virtual void issue_nop(const Cancellable* cancellable, Milliseconds duration) override{ + ControllerWithScheduler::issue_nop(cancellable, duration); + } + + virtual void issue_buttons( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + Button button + ) override{ + ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); + } + virtual void issue_dpad( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition position + ) override{ + ControllerWithScheduler::issue_dpad(cancellable, delay, hold, cooldown, position); + } + virtual void issue_left_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y + ) override{ + ControllerWithScheduler::issue_left_joystick(cancellable, delay, hold, cooldown, x, y); + } + virtual void issue_right_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y + ) override{ + ControllerWithScheduler::issue_right_joystick(cancellable, delay, hold, cooldown, x, y); + } + + virtual void issue_gyro_accel_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_x(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_accel_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_y(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_accel_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_z(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_x(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_y(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_z(cancellable, delay, hold, cooldown, value); + } + + virtual void issue_full_controller_state( + const Cancellable* cancellable, + Milliseconds hold, + Button button, + DpadPosition position, + uint8_t left_x, uint8_t left_y, + uint8_t right_x, uint8_t right_y + ) override{ + ControllerWithScheduler::issue_full_controller_state( + cancellable, + hold, + button, + position, + left_x, left_y, + right_x, right_y + ); + } + + +public: + // High speed RPCs. + + virtual void issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button + ) override{ + ControllerWithScheduler::issue_mash_button(cancellable, duration, button); + } + virtual void issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button0, Button button1 + ) override{ + ControllerWithScheduler::issue_mash_button(cancellable, duration, button0, button1); + } + virtual void issue_mash_AZs( + const Cancellable* cancellable, + Milliseconds duration + ) override{ + ControllerWithScheduler::issue_mash_AZs(cancellable, duration); + } + virtual void issue_system_scroll( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition direction // Diagonals not allowed. + ) override{ + ControllerWithScheduler::issue_system_scroll(cancellable, delay, hold, cooldown, direction); + } + + +private: + virtual void push_state(const Cancellable* cancellable, WallDuration duration) override; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ControllerState.h b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ControllerState.h index e1e3502e07..5ad91e8461 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ControllerState.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ControllerState.h @@ -1,76 +1,76 @@ -/* Controller State - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Sysbotbase3_ControllerState_H -#define PokemonAutomation_Sysbotbase3_ControllerState_H - -#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -struct Sysbotbase3_ControllerState{ - uint64_t buttons = 0; - int16_t left_joystick_x = 0; - int16_t left_joystick_y = 0; - int16_t right_joystick_x = 0; - int16_t right_joystick_y = 0; - - bool is_neutral() const{ - return buttons == 0 - && left_joystick_x == 0 - && left_joystick_y == 0 - && right_joystick_x == 0 - && right_joystick_y == 0; - } - void clear(){ - buttons = 0; - left_joystick_x = 0; - left_joystick_y = 0; - right_joystick_x = 0; - right_joystick_y = 0; - } -}; - - - -struct Sysbotbase3_ControllerCommand{ - uint64_t seqnum; - uint64_t milliseconds; - Sysbotbase3_ControllerState state; - - void write_to_hex(char str[64]) const{ - const char HEX_DIGITS[] = "0123456789abcdef"; - const char* ptr = (const char*)this; - for (size_t c = 0; c < 64; c += 2){ - uint8_t hi = (uint8_t)ptr[0] >> 4; - uint8_t lo = (uint8_t)ptr[0] & 0x0f; - str[c + 0] = HEX_DIGITS[hi]; - str[c + 1] = HEX_DIGITS[lo]; - ptr++; - } - } - void parse_from_hex(const char str[64]){ - char* ptr = (char*)this; - for (size_t c = 0; c < 64; c += 2){ - char hi = str[c + 0]; - char lo = str[c + 1]; - hi = hi < 'a' ? hi - '0' : hi - 'a' + 10; - lo = lo < 'a' ? lo - '0' : lo - 'a' + 10; - ptr[0] = hi << 4 | lo; - ptr++; - } - } -}; - - - - -} -} -#endif +/* Controller State + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Sysbotbase3_ControllerState_H +#define PokemonAutomation_Sysbotbase3_ControllerState_H + +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +struct Sysbotbase3_ControllerState{ + uint64_t buttons = 0; + int16_t left_joystick_x = 0; + int16_t left_joystick_y = 0; + int16_t right_joystick_x = 0; + int16_t right_joystick_y = 0; + + bool is_neutral() const{ + return buttons == 0 + && left_joystick_x == 0 + && left_joystick_y == 0 + && right_joystick_x == 0 + && right_joystick_y == 0; + } + void clear(){ + buttons = 0; + left_joystick_x = 0; + left_joystick_y = 0; + right_joystick_x = 0; + right_joystick_y = 0; + } +}; + + + +struct Sysbotbase3_ControllerCommand{ + uint64_t seqnum; + uint64_t milliseconds; + Sysbotbase3_ControllerState state; + + void write_to_hex(char str[64]) const{ + const char HEX_DIGITS[] = "0123456789abcdef"; + const char* ptr = (const char*)this; + for (size_t c = 0; c < 64; c += 2){ + uint8_t hi = (uint8_t)ptr[0] >> 4; + uint8_t lo = (uint8_t)ptr[0] & 0x0f; + str[c + 0] = HEX_DIGITS[hi]; + str[c + 1] = HEX_DIGITS[lo]; + ptr++; + } + } + void parse_from_hex(const char str[64]){ + char* ptr = (char*)this; + for (size_t c = 0; c < 64; c += 2){ + char hi = str[c + 0]; + char lo = str[c + 1]; + hi = hi < 'a' ? hi - '0' : hi - 'a' + 10; + lo = lo < 'a' ? lo - '0' : lo - 'a' + 10; + ptr[0] = hi << 4 | lo; + ptr++; + } + } +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ProController.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ProController.cpp index a0113d041d..62c192cdb9 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ProController.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ProController.cpp @@ -1,260 +1,301 @@ -/* Nintendo Switch Pro Controller (SysbotBase 3) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -//#include "Common/Cpp/Concurrency/ReverseLockGuard.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "Controllers/JoystickTools.h" -#include "SysbotBase3_ControllerState.h" -#include "SysbotBase3_ProController.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -ProController_SysbotBase3::ProController_SysbotBase3( - Logger& logger, - SysbotBase::TcpSysbotBase_Connection& connection -) - : ControllerWithScheduler(logger) - , m_connection(connection) - , m_stopping(false) - , m_next_seqnum(1) - , m_next_expected_seqnum_ack(1) -{ - if (!connection.is_ready()){ - return; - } - connection.add_listener(*this); -} -ProController_SysbotBase3::~ProController_SysbotBase3(){ - m_connection.remove_listener(*this); -} - -const ControllerFeatures& ProController_SysbotBase3::controller_features() const{ - static const ControllerFeatures features{ - ControllerFeature::TickPrecise, - ControllerFeature::TimingFlexibleMilliseconds, - ControllerFeature::NintendoSwitch_ProController, - ControllerFeature::NintendoSwitch_DateSkip, - }; - return features; -} - -void ProController_SysbotBase3::cancel_all_commands(){ - std::lock_guard lg(m_state_lock); - if (m_stopping){ - throw InvalidConnectionStateException(""); - } - - uint64_t queued = m_next_seqnum - m_next_expected_seqnum_ack; - m_next_expected_seqnum_ack = m_next_seqnum; - - m_connection.write_data("cqCancel\r\n"); - - this->clear_on_next(); - m_cv.notify_all(); - m_logger.log("cancel_all_commands(): Command Queue Size = " + std::to_string(queued), COLOR_DARKGREEN); -} -void ProController_SysbotBase3::replace_on_next_command(){ - std::lock_guard lg(m_state_lock); - if (m_stopping){ - throw InvalidConnectionStateException(""); - } - - uint64_t queued = m_next_seqnum - m_next_expected_seqnum_ack; - m_next_expected_seqnum_ack = m_next_seqnum; - - m_connection.write_data("cqReplaceOnNext\r\n"); - - this->clear_on_next(); - m_cv.notify_all(); - m_logger.log("replace_on_next_command(): Command Queue Size = " + std::to_string(queued), COLOR_DARKGREEN); -} -void ProController_SysbotBase3::wait_for_all(const Cancellable* cancellable){ - std::unique_lock lg(m_state_lock); - while (true){ - if (m_stopping){ - throw InvalidConnectionStateException(""); - } - if (cancellable){ - cancellable->throw_if_cancelled(); - } - if (m_next_seqnum == m_next_expected_seqnum_ack){ - break; - } - m_cv.wait(lg); - } -} - - -void ProController_SysbotBase3::on_message(const std::string& message){ - const std::string TOKEN = "cqCommandFinished"; - auto pos = message.find(TOKEN); - if (pos == std::string::npos){ - return; - } - - const char* ptr = message.c_str(); - ptr += pos; - ptr += TOKEN.size(); - uint64_t parsed; - while (true){ - char ch = *ptr; - switch (ch){ - case '\0': - return; - case ' ': - case '\t': - ptr++; - continue; - } - parsed = std::atoll(ptr); - break; - } - - std::lock_guard lg(m_state_lock); - - if (GlobalSettings::instance().LOG_EVERYTHING){ - m_logger.log( - "Command Finished: " + std::to_string(parsed) + - " (queue size = " + std::to_string(m_next_seqnum - m_next_expected_seqnum_ack) + ")" - ); - } - - // Old ack - if (parsed < m_next_expected_seqnum_ack){ - m_logger.log( - "Received Old Ack: Expected = " + std::to_string(m_next_expected_seqnum_ack) + - ", Actual = " + std::to_string(parsed), - COLOR_RED - ); - return; - } - - // Ack is ahead of what has been dispatched. - if (parsed >= m_next_seqnum){ - m_logger.log( - "Received Future Ack: Expected = " + std::to_string(m_next_expected_seqnum_ack) + - ", Actual = " + std::to_string(parsed), - COLOR_RED - ); - return; - } - - m_next_expected_seqnum_ack = parsed + 1; - m_cv.notify_all(); -} - -void ProController_SysbotBase3::push_state(const Cancellable* cancellable, WallDuration duration){ - // Must be called inside "m_state_lock". - - if (cancellable){ - cancellable->throw_if_cancelled(); - } - if (m_stopping){ - throw InvalidConnectionStateException(""); - } - - // Flags map to: https://github.com/switchbrew/libnx/blob/master/nx/include/switch/services/hid.h#L584 - uint64_t nx_button = 0; - if (m_buttons[ 0].is_busy()) nx_button |= (uint64_t)1 << 3; // Y - if (m_buttons[ 1].is_busy()) nx_button |= (uint64_t)1 << 1; // B - if (m_buttons[ 2].is_busy()) nx_button |= (uint64_t)1 << 0; // A - if (m_buttons[ 3].is_busy()) nx_button |= (uint64_t)1 << 2; // X - if (m_buttons[ 4].is_busy()) nx_button |= (uint64_t)1 << 6; // L - if (m_buttons[ 5].is_busy()) nx_button |= (uint64_t)1 << 7; // R - if (m_buttons[ 6].is_busy()) nx_button |= (uint64_t)1 << 8; // ZL - if (m_buttons[ 7].is_busy()) nx_button |= (uint64_t)1 << 9; // ZR - if (m_buttons[ 8].is_busy()) nx_button |= (uint64_t)1 << 11; // - - if (m_buttons[ 9].is_busy()) nx_button |= (uint64_t)1 << 10; // + - if (m_buttons[10].is_busy()) nx_button |= (uint64_t)1 << 4; // L-click - if (m_buttons[11].is_busy()) nx_button |= (uint64_t)1 << 5; // R-click - if (m_buttons[12].is_busy()) nx_button |= (uint64_t)1 << 18; // Home - if (m_buttons[13].is_busy()) nx_button |= (uint64_t)1 << 19; // Capture - if (m_buttons[14].is_busy()) nx_button |= (uint64_t)1 << 13; // Up - if (m_buttons[15].is_busy()) nx_button |= (uint64_t)1 << 14; // Right - if (m_buttons[16].is_busy()) nx_button |= (uint64_t)1 << 15; // Down - if (m_buttons[17].is_busy()) nx_button |= (uint64_t)1 << 12; // Left -#if 0 // Don't exist on pro controller. - if (m_buttons[18].is_busy()) nx_button |= (uint64_t)1 << 24; // Left SL - if (m_buttons[19].is_busy()) nx_button |= (uint64_t)1 << 25; // Left SR - if (m_buttons[20].is_busy()) nx_button |= (uint64_t)1 << 26; // Right SL - if (m_buttons[21].is_busy()) nx_button |= (uint64_t)1 << 27; // Right SR -#endif - - { - DpadPosition dpad = m_dpad.is_busy() ? m_dpad.position : DPAD_NONE; - SplitDpad split_dpad = convert_unified_to_split_dpad(dpad); - if (split_dpad.up) nx_button |= (uint64_t)1 << 13; - if (split_dpad.right) nx_button |= (uint64_t)1 << 14; - if (split_dpad.down) nx_button |= (uint64_t)1 << 15; - if (split_dpad.left) nx_button |= (uint64_t)1 << 12; - } - - int16_t left_x = 0; - int16_t left_y = 0; - int16_t right_x = 0; - int16_t right_y = 0; - if (m_left_joystick.is_busy()){ - double fx = JoystickTools::linear_u8_to_float(m_left_joystick.x); - double fy = -JoystickTools::linear_u8_to_float(m_left_joystick.y); - left_x = JoystickTools::linear_float_to_s16(fx); - left_y = JoystickTools::linear_float_to_s16(fy); - } - if (m_right_joystick.is_busy()){ - double fx = JoystickTools::linear_u8_to_float(m_right_joystick.x); - double fy = -JoystickTools::linear_u8_to_float(m_right_joystick.y); - right_x = JoystickTools::linear_float_to_s16(fx); - right_y = JoystickTools::linear_float_to_s16(fy); - } - - std::unique_lock lg(m_state_lock, std::adopt_lock_t()); - - // Wait until there is space. - m_cv.wait(lg, [this, cancellable]{ - if (cancellable && cancellable->cancelled()){ - return true; - } - return m_stopping || m_next_seqnum - m_next_expected_seqnum_ack < QUEUE_SIZE; - }); - - lg.release(); - - if (cancellable){ - cancellable->throw_if_cancelled(); - } - - Sysbotbase3_ControllerCommand command; - command.milliseconds = std::chrono::duration_cast(duration).count(); - command.seqnum = m_next_seqnum++; - command.state.buttons = nx_button; - command.state.left_joystick_x = left_x; - command.state.left_joystick_y = left_y; - command.state.right_joystick_x = right_x; - command.state.right_joystick_y = right_y; - - std::string message; - message.resize(64); - command.write_to_hex(message.data()); - message = "cqControllerState " + message + "\r\n"; - - m_connection.write_data(message); - - if (GlobalSettings::instance().LOG_EVERYTHING){ - m_logger.log("sys-botbase3: " + message); - } -} - - - - - - - -} -} +/* Nintendo Switch Pro Controller (SysbotBase 3) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +//#include "Common/Cpp/Concurrency/ReverseLockGuard.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "Controllers/JoystickTools.h" +#include "SysbotBase3_ControllerState.h" +#include "SysbotBase3_ProController.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +ProController_SysbotBase3::ProController_SysbotBase3( + Logger& logger, + SysbotBase::TcpSysbotBase_Connection& connection +) + : ProController(logger) + , ControllerWithScheduler(logger) + , m_connection(connection) + , m_stopping(false) + , m_pending_replace(false) + , m_next_seqnum(1) + , m_next_expected_seqnum_ack(1) +{ + if (!connection.is_ready()){ + return; + } + connection.add_listener(*this); +} +ProController_SysbotBase3::~ProController_SysbotBase3(){ + m_connection.remove_listener(*this); +} + +const ControllerFeatures& ProController_SysbotBase3::controller_features() const{ + static const ControllerFeatures features{ + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_ProController, + ControllerFeature::NintendoSwitch_DateSkip, + }; + return features; +} + +void ProController_SysbotBase3::cancel_all_commands(){ + std::lock_guard lg(m_state_lock); + if (m_stopping){ + throw InvalidConnectionStateException(""); + } + + uint64_t queued = m_next_seqnum - m_next_expected_seqnum_ack; + m_next_expected_seqnum_ack = m_next_seqnum; + + m_connection.write_data("cqCancel\r\n"); + if (GlobalSettings::instance().LOG_EVERYTHING){ + m_logger.log("sys-botbase3: cqCancel"); + } + + this->clear_on_next(); + m_cv.notify_all(); + m_logger.log("cancel_all_commands(): Command Queue Size = " + std::to_string(queued), COLOR_DARKGREEN); +} +void ProController_SysbotBase3::replace_on_next_command(){ + std::lock_guard lg(m_state_lock); + if (m_stopping){ + throw InvalidConnectionStateException(""); + } + + uint64_t queued = m_next_seqnum - m_next_expected_seqnum_ack; +// m_next_expected_seqnum_ack = m_next_seqnum; + + m_pending_replace = true; + +#if 0 + m_connection.write_data("cqReplaceOnNext\r\n"); + if (GlobalSettings::instance().LOG_EVERYTHING){ + m_logger.log("sys-botbase3: cqReplaceOnNext"); + } +#endif + + this->clear_on_next(); + m_cv.notify_all(); + m_logger.log("replace_on_next_command(): Command Queue Size = " + std::to_string(queued), COLOR_DARKGREEN); +} +void ProController_SysbotBase3::wait_for_all(const Cancellable* cancellable){ + std::lock_guard lg0(m_issue_lock); + std::unique_lock lg1(m_state_lock); + +// cout << "wait_for_all() - start" << endl; + + if (m_stopping){ + throw InvalidConnectionStateException(""); + } + this->issue_wait_for_all(cancellable); + + while (true){ + if (m_stopping){ + throw InvalidConnectionStateException(""); + } + if (cancellable){ + cancellable->throw_if_cancelled(); + } + if (m_next_seqnum == m_next_expected_seqnum_ack){ + break; + } + m_cv.wait(lg1); + } + +// cout << "wait_for_all() - done" << endl; +} + + +void ProController_SysbotBase3::on_message(const std::string& message){ + const std::string TOKEN = "cqCommandFinished"; + auto pos = message.find(TOKEN); + if (pos == std::string::npos){ + return; + } + + const char* ptr = message.c_str(); + ptr += pos; + ptr += TOKEN.size(); + uint64_t parsed; + while (true){ + char ch = *ptr; + switch (ch){ + case '\0': + return; + case ' ': + case '\t': + ptr++; + continue; + } + parsed = std::atoll(ptr); + break; + } + + std::lock_guard lg(m_state_lock); + +// cout << "parsed = " << parsed << endl; +// cout << "m_next_seqnum = " << m_next_seqnum << endl; +// cout << "m_next_expected_seqnum_ack = " << m_next_expected_seqnum_ack << endl; + + if (GlobalSettings::instance().LOG_EVERYTHING){ + m_logger.log( + "Command Finished: " + std::to_string(parsed) + + " (queue size = " + std::to_string(m_next_seqnum - m_next_expected_seqnum_ack) + ")" + ); + } + + // Old ack + if (parsed < m_next_expected_seqnum_ack){ + m_logger.log( + "Received Old Ack: Expected = " + std::to_string(m_next_expected_seqnum_ack) + + ", Actual = " + std::to_string(parsed), + COLOR_DARKGREEN + ); + return; + } + + // Ack is ahead of what has been dispatched. + if (parsed >= m_next_seqnum){ + m_logger.log( + "Received Future Ack: Expected = " + std::to_string(m_next_expected_seqnum_ack) + + ", Actual = " + std::to_string(parsed), + COLOR_RED + ); + return; + } + + m_next_expected_seqnum_ack = parsed + 1; + m_cv.notify_all(); +} + +void ProController_SysbotBase3::push_state(const Cancellable* cancellable, WallDuration duration){ + // Must be called inside "m_state_lock". + + if (cancellable){ + cancellable->throw_if_cancelled(); + } + if (m_stopping){ + throw InvalidConnectionStateException(""); + } + + // Flags map to: https://github.com/switchbrew/libnx/blob/master/nx/include/switch/services/hid.h#L584 + uint64_t nx_button = 0; + if (m_buttons[ 0].is_busy()) nx_button |= (uint64_t)1 << 3; // Y + if (m_buttons[ 1].is_busy()) nx_button |= (uint64_t)1 << 1; // B + if (m_buttons[ 2].is_busy()) nx_button |= (uint64_t)1 << 0; // A + if (m_buttons[ 3].is_busy()) nx_button |= (uint64_t)1 << 2; // X + if (m_buttons[ 4].is_busy()) nx_button |= (uint64_t)1 << 6; // L + if (m_buttons[ 5].is_busy()) nx_button |= (uint64_t)1 << 7; // R + if (m_buttons[ 6].is_busy()) nx_button |= (uint64_t)1 << 8; // ZL + if (m_buttons[ 7].is_busy()) nx_button |= (uint64_t)1 << 9; // ZR + if (m_buttons[ 8].is_busy()) nx_button |= (uint64_t)1 << 11; // - + if (m_buttons[ 9].is_busy()) nx_button |= (uint64_t)1 << 10; // + + if (m_buttons[10].is_busy()) nx_button |= (uint64_t)1 << 4; // L-click + if (m_buttons[11].is_busy()) nx_button |= (uint64_t)1 << 5; // R-click + if (m_buttons[12].is_busy()) nx_button |= (uint64_t)1 << 18; // Home + if (m_buttons[13].is_busy()) nx_button |= (uint64_t)1 << 19; // Capture + if (m_buttons[14].is_busy()) nx_button |= (uint64_t)1 << 13; // Up + if (m_buttons[15].is_busy()) nx_button |= (uint64_t)1 << 14; // Right + if (m_buttons[16].is_busy()) nx_button |= (uint64_t)1 << 15; // Down + if (m_buttons[17].is_busy()) nx_button |= (uint64_t)1 << 12; // Left +#if 0 // Don't exist on pro controller. + if (m_buttons[18].is_busy()) nx_button |= (uint64_t)1 << 24; // Left SL + if (m_buttons[19].is_busy()) nx_button |= (uint64_t)1 << 25; // Left SR + if (m_buttons[20].is_busy()) nx_button |= (uint64_t)1 << 26; // Right SL + if (m_buttons[21].is_busy()) nx_button |= (uint64_t)1 << 27; // Right SR +#endif + + { + DpadPosition dpad = m_dpad.is_busy() ? m_dpad.position : DPAD_NONE; + SplitDpad split_dpad = convert_unified_to_split_dpad(dpad); + if (split_dpad.up) nx_button |= (uint64_t)1 << 13; + if (split_dpad.right) nx_button |= (uint64_t)1 << 14; + if (split_dpad.down) nx_button |= (uint64_t)1 << 15; + if (split_dpad.left) nx_button |= (uint64_t)1 << 12; + } + + int16_t left_x = 0; + int16_t left_y = 0; + int16_t right_x = 0; + int16_t right_y = 0; + if (m_left_joystick.is_busy()){ + double fx = JoystickTools::linear_u8_to_float(m_left_joystick.x); + double fy = -JoystickTools::linear_u8_to_float(m_left_joystick.y); + JoystickTools::clip_magnitude(fx, fy); + left_x = JoystickTools::linear_float_to_s16(fx); + left_y = JoystickTools::linear_float_to_s16(fy); + } + if (m_right_joystick.is_busy()){ + double fx = JoystickTools::linear_u8_to_float(m_right_joystick.x); + double fy = -JoystickTools::linear_u8_to_float(m_right_joystick.y); + JoystickTools::clip_magnitude(fx, fy); + right_x = JoystickTools::linear_float_to_s16(fx); + right_y = JoystickTools::linear_float_to_s16(fy); + } + + std::string message; + if (m_pending_replace){ + m_pending_replace = false; + m_next_expected_seqnum_ack = m_next_seqnum; + message += "cqReplaceOnNext\r\n"; + } + + std::unique_lock lg(m_state_lock, std::adopt_lock_t()); + + // Wait until there is space. + m_cv.wait(lg, [this, cancellable]{ + if (cancellable && cancellable->cancelled()){ + return true; + } + return m_stopping || m_next_seqnum - m_next_expected_seqnum_ack < QUEUE_SIZE; + }); + + lg.release(); + + if (cancellable){ + cancellable->throw_if_cancelled(); + } + + Sysbotbase3_ControllerCommand command; + command.milliseconds = std::chrono::duration_cast(duration).count(); + command.seqnum = m_next_seqnum++; + command.state.buttons = nx_button; + command.state.left_joystick_x = left_x; + command.state.left_joystick_y = left_y; + command.state.right_joystick_x = right_x; + command.state.right_joystick_y = right_y; + + { + std::string command_message; + command_message.resize(64); + command.write_to_hex(command_message.data()); + message += "cqControllerState " + command_message + "\r\n"; + } + + m_connection.write_data(message); + + if (GlobalSettings::instance().LOG_EVERYTHING){ + m_logger.log("sys-botbase3: " + message); + } +} + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ProController.h b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ProController.h index 25f1f12b4c..ad933c2c9e 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ProController.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ProController.h @@ -1,240 +1,241 @@ -/* Nintendo Switch Pro Controller (SysbotBase 3) - * - * From: https://github.com/PokemonAutomation/ - * - */ - - -#ifndef PokemonAutomation_NintendoSwitch_ProController_SysbotBase3_H -#define PokemonAutomation_NintendoSwitch_ProController_SysbotBase3_H - -#include "NintendoSwitch/NintendoSwitch_Settings.h" -//#include "NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.h" -#include "SysbotBase_Connection.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -class ProController_SysbotBase3 final : - public ProController, - public ControllerWithScheduler, - private SysbotBase::TcpSysbotBase_Connection::Listener -{ -public: - using ContextType = ProControllerContext; - - static constexpr size_t QUEUE_SIZE = 256; - - -public: - ProController_SysbotBase3( - Logger& logger, - SysbotBase::TcpSysbotBase_Connection& connection - ); - ~ProController_SysbotBase3(); - - -public: - virtual ControllerType controller_type() const override{ - return ControllerType::NintendoSwitch_WiredProController; - } - virtual const ControllerFeatures& controller_features() const override; - virtual ControllerPerformanceClass performance_class() const override{ - // TODO: Change to SerialPABotBase_Wired_125Hz when we prove it is stable. - return ControllerPerformanceClass::SerialPABotBase_Wired_125Hz; -// return ControllerPerformanceClass::SysbotBase; - } - - virtual Milliseconds ticksize() const override{ - return Milliseconds::zero(); - } - virtual Milliseconds cooldown() const override{ - return Milliseconds(8); - } - virtual Milliseconds timing_variation() const override{ - // TODO: Verify it is actually this stable. - return ConsoleSettings::instance().TIMING_OPTIONS.WIRED_MICROCONTROLLER; -// return ConsoleSettings::instance().TIMING_OPTIONS.SYSBOTBASE; -// return Milliseconds(8); - } - virtual bool atomic_multibutton() const override{ - return true; - } - - -public: - virtual void cancel_all_commands() override; - virtual void replace_on_next_command() override; - - virtual void wait_for_all(const Cancellable* cancellable) override; - - -public: - // Superscalar Commands (the "ssf" framework) - - virtual void issue_barrier(const Cancellable* cancellable) override{ - ControllerWithScheduler::issue_barrier(cancellable); - } - virtual void issue_nop(const Cancellable* cancellable, Milliseconds duration) override{ - ControllerWithScheduler::issue_nop(cancellable, duration); - } - - virtual void issue_buttons( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - Button button - ) override{ - ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); - } - virtual void issue_dpad( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition position - ) override{ - ControllerWithScheduler::issue_dpad(cancellable, delay, hold, cooldown, position); - } - virtual void issue_left_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y - ) override{ - ControllerWithScheduler::issue_left_joystick(cancellable, delay, hold, cooldown, x, y); - } - virtual void issue_right_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y - ) override{ - ControllerWithScheduler::issue_right_joystick(cancellable, delay, hold, cooldown, x, y); - } - - virtual void issue_gyro_accel_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_x(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_accel_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_y(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_accel_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_z(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_x(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_y(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_z(cancellable, delay, hold, cooldown, value); - } - - virtual void issue_full_controller_state( - const Cancellable* cancellable, - Milliseconds hold, - Button button, - DpadPosition position, - uint8_t left_x, uint8_t left_y, - uint8_t right_x, uint8_t right_y - ) override{ - ControllerWithScheduler::issue_full_controller_state( - cancellable, - hold, - button, - position, - left_x, left_y, - right_x, right_y - ); - } - - -public: - // High speed RPCs. - - virtual void issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button - ) override{ - ControllerWithScheduler::issue_mash_button(cancellable, duration, button); - } - virtual void issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button0, Button button1 - ) override{ - ControllerWithScheduler::issue_mash_button(cancellable, duration, button0, button1); - } - virtual void issue_mash_AZs( - const Cancellable* cancellable, - Milliseconds duration - ) override{ - ControllerWithScheduler::issue_mash_AZs(cancellable, duration); - } - virtual void issue_system_scroll( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition direction // Diagonals not allowed. - ) override{ - ControllerWithScheduler::issue_system_scroll(cancellable, delay, hold, cooldown, direction); - } - - -public: - virtual Logger& logger() override{ - return m_logger; - } - virtual RecursiveThrottler& logging_throttler() override{ - return m_logging_throttler; - } - virtual bool is_ready() const override{ - return m_connection.is_ready(); - } - - -private: - virtual void on_message(const std::string& message) override; - virtual void push_state(const Cancellable* cancellable, WallDuration duration) override; - - -private: - SysbotBase::TcpSysbotBase_Connection& m_connection; - - bool m_stopping; - uint64_t m_next_seqnum; - uint64_t m_next_expected_seqnum_ack; - - std::condition_variable m_cv; -}; - - - -} -} -#endif +/* Nintendo Switch Pro Controller (SysbotBase 3) + * + * From: https://github.com/PokemonAutomation/ + * + */ + + +#ifndef PokemonAutomation_NintendoSwitch_ProController_SysbotBase3_H +#define PokemonAutomation_NintendoSwitch_ProController_SysbotBase3_H + +#include "NintendoSwitch/NintendoSwitch_Settings.h" +//#include "NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.h" +#include "SysbotBase_Connection.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +class ProController_SysbotBase3 final : + public ProController, + public ControllerWithScheduler, + private SysbotBase::TcpSysbotBase_Connection::Listener +{ +public: + using ContextType = ProControllerContext; + + static constexpr size_t QUEUE_SIZE = 64; + + +public: + ProController_SysbotBase3( + Logger& logger, + SysbotBase::TcpSysbotBase_Connection& connection + ); + ~ProController_SysbotBase3(); + + +public: + virtual ControllerType controller_type() const override{ + return ControllerType::NintendoSwitch_WiredProController; + } + virtual const ControllerFeatures& controller_features() const override; + virtual ControllerPerformanceClass performance_class() const override{ + // TODO: Change to SerialPABotBase_Wired when we prove it is stable. + return ControllerPerformanceClass::SerialPABotBase_Wired; +// return ControllerPerformanceClass::SysbotBase; + } + + virtual Milliseconds ticksize() const override{ + return Milliseconds::zero(); + } + virtual Milliseconds cooldown() const override{ + return Milliseconds(8); + } + virtual Milliseconds timing_variation() const override{ + // TODO: Verify it is actually this stable. + return ConsoleSettings::instance().TIMING_OPTIONS.WIRED_MICROCONTROLLER; +// return ConsoleSettings::instance().TIMING_OPTIONS.SYSBOTBASE; +// return Milliseconds(8); + } + virtual bool atomic_multibutton() const override{ + return true; + } + + +public: + virtual void cancel_all_commands() override; + virtual void replace_on_next_command() override; + + virtual void wait_for_all(const Cancellable* cancellable) override; + + +public: + // Superscalar Commands (the "ssf" framework) + + virtual void issue_barrier(const Cancellable* cancellable) override{ + ControllerWithScheduler::issue_barrier(cancellable); + } + virtual void issue_nop(const Cancellable* cancellable, Milliseconds duration) override{ + ControllerWithScheduler::issue_nop(cancellable, duration); + } + + virtual void issue_buttons( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + Button button + ) override{ + ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); + } + virtual void issue_dpad( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition position + ) override{ + ControllerWithScheduler::issue_dpad(cancellable, delay, hold, cooldown, position); + } + virtual void issue_left_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y + ) override{ + ControllerWithScheduler::issue_left_joystick(cancellable, delay, hold, cooldown, x, y); + } + virtual void issue_right_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y + ) override{ + ControllerWithScheduler::issue_right_joystick(cancellable, delay, hold, cooldown, x, y); + } + + virtual void issue_gyro_accel_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_x(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_accel_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_y(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_accel_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_z(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_x(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_y(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_z(cancellable, delay, hold, cooldown, value); + } + + virtual void issue_full_controller_state( + const Cancellable* cancellable, + Milliseconds hold, + Button button, + DpadPosition position, + uint8_t left_x, uint8_t left_y, + uint8_t right_x, uint8_t right_y + ) override{ + ControllerWithScheduler::issue_full_controller_state( + cancellable, + hold, + button, + position, + left_x, left_y, + right_x, right_y + ); + } + + +public: + // High speed RPCs. + + virtual void issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button + ) override{ + ControllerWithScheduler::issue_mash_button(cancellable, duration, button); + } + virtual void issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button0, Button button1 + ) override{ + ControllerWithScheduler::issue_mash_button(cancellable, duration, button0, button1); + } + virtual void issue_mash_AZs( + const Cancellable* cancellable, + Milliseconds duration + ) override{ + ControllerWithScheduler::issue_mash_AZs(cancellable, duration); + } + virtual void issue_system_scroll( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition direction // Diagonals not allowed. + ) override{ + ControllerWithScheduler::issue_system_scroll(cancellable, delay, hold, cooldown, direction); + } + + +public: + virtual Logger& logger() override{ + return m_logger; + } + virtual RecursiveThrottler& logging_throttler() override{ + return m_logging_throttler; + } + virtual bool is_ready() const override{ + return m_connection.is_ready(); + } + + +private: + virtual void on_message(const std::string& message) override; + virtual void push_state(const Cancellable* cancellable, WallDuration duration) override; + + +private: + SysbotBase::TcpSysbotBase_Connection& m_connection; + + bool m_stopping; + bool m_pending_replace; + uint64_t m_next_seqnum; + uint64_t m_next_expected_seqnum_ack; + + std::condition_variable m_cv; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Connection.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Connection.cpp index af66c5420f..c1fb207888 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Connection.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Connection.cpp @@ -1,263 +1,310 @@ -/* sys-botbase Connection - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Time.h" -//#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" -#include "SysbotBase_Connection.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace SysbotBase{ - -using namespace std::chrono_literals; - - - -bool parse_ip_and_port(const std::string& str, QHostAddress& address, int& port){ - // IPv4 - QStringList parts = QString::fromStdString(str).split(":"); - if (parts.size() != 2){ - return false; - } - address = QHostAddress(parts[0]); - bool ok; - port = parts[1].toUInt(&ok); - if (!ok){ - return false; - } - - // TODO: IPv6 - - return true; -} - - - - -TcpSysbotBase_Connection::TcpSysbotBase_Connection( - Logger& logger, - const std::string& url -) - : m_logger(logger) - , m_supports_command_queue(false) - , m_last_receive(WallClock::min()) -{ - QHostAddress address; - int port; - if (!parse_ip_and_port(url, address, port)){ - set_status_line0(html_color_text("Invalid IP address + port.", COLOR_RED)); - return; - } - - set_status_line0(html_color_text("Connecting...", COLOR_DARKGREEN)); - - m_connecting_message = - "Connecting To: " + address.toString().toStdString() + - " - Port: " + std::to_string(port); - m_logger.log(m_connecting_message); - - // Attach ourselves as listener first since it might immediately return as - // connected. - m_socket.add_listener(*this); - - try{ - m_socket.connect(address.toString().toStdString(), port); - }catch (...){ - m_socket.remove_listener(*this); - throw; - } -} - -TcpSysbotBase_Connection::~TcpSysbotBase_Connection(){ - try{ - write_data("detachController\r\n"); - }catch (...){} - m_socket.remove_listener(*this); - m_socket.close(); - { - std::lock_guard lg(m_lock); - m_cv.notify_all(); - } - if (m_thread.joinable()){ - m_thread.join(); - } -} - - -ControllerModeStatus TcpSysbotBase_Connection::controller_mode_status() const{ - return { - ControllerType::NintendoSwitch_WiredProController, - { - {ControllerType::NintendoSwitch_WiredProController, { - ControllerFeature::NintendoSwitch_ProController - }}, - } - }; -} - -void TcpSysbotBase_Connection::write_data(const std::string& data){ - WriteSpinLock lg(m_send_lock); -// cout << "Sending: " << data << endl; - m_socket.blocking_send(data.data(), data.size()); -} - - -std::string pretty_print(uint64_t x){ - auto ms = x / 1000; - auto us = x - ms * 1000; - std::string str_ms = std::to_string(ms); - std::string str_us = std::to_string(us); - return str_ms + "." + std::string(3 - str_us.size(), '0') + str_us; -} - - -void TcpSysbotBase_Connection::thread_loop(){ - std::unique_lock lg(m_lock); - WallClock send_time = current_time(); - while (true){ - ClientSocket::State state = m_socket.state(); - if (state == ClientSocket::State::DESTRUCTING || state == ClientSocket::State::NOT_RUNNING){ - break; - } - - WallClock now = current_time(); - - if (m_last_receive == WallClock::min()){ - send_time = now; - write_data("getVersion\r\n"); - }else if (send_time < m_last_receive && now - m_last_receive < std::chrono::seconds(1)){ - std::chrono::microseconds latency = std::chrono::duration_cast(m_last_receive - send_time); - std::string str = "Response Time: " + pretty_print(latency.count()) + " ms"; - if (latency < 10ms){ - set_status_line1(str, COLOR_BLUE); - }else if (latency < 50ms){ - set_status_line1(str, COLOR_DARKGREEN); - }else{ - set_status_line1(str, COLOR_ORANGE); - } - send_time = current_time(); - write_data("getVersion\r\n"); -// cout << std::chrono::duration_cast(current_time() - send_time) << endl; - }else{ - std::chrono::milliseconds time_since = std::chrono::duration_cast(now - m_last_receive); - std::string str = "Last Ack: " + pretty_print(time_since.count()) + " seconds ago"; - set_status_line1(str, COLOR_RED); - send_time = current_time(); - write_data("getVersion\r\n"); -// cout << std::chrono::duration_cast(current_time() - send_time) << endl; - } - m_cv.wait_for(lg, std::chrono::seconds(1)); - } -} - - - -void TcpSysbotBase_Connection::on_connect_finished(const std::string& error_message){ - try{ - if (!error_message.empty()){ - m_logger.log(m_connecting_message, COLOR_RED); - set_status_line0(m_connecting_message, COLOR_RED); - return; - } - - m_logger.log(m_connecting_message + " (Success)", COLOR_BLUE); - - write_data("configure echoCommands 0\r\n"); - write_data("getVersion\r\n"); - -// m_thread = std::thread(&TcpSysbotBase_Connection::thread_loop, this); - -// set_status_line0(m_version); - -// declare_ready(controller_mode_status()); - }catch (...){} -} -void TcpSysbotBase_Connection::on_receive_data(const void* data, size_t bytes){ -// cout << "on_receive_data(): " << std::string((const char*)data, bytes - 2) << endl; - - WallClock now = current_time(); - { - std::lock_guard lg(m_lock); - m_last_receive = now; - } - - - try{ - const char* ptr = (const char*)data; - for (size_t c = 0; c < bytes; c++){ - char ch = ptr[c]; - if (ch == '\r'){ - continue; - } - if (ch != '\n'){ - m_receive_buffer.emplace_back(ch); - continue; - } - process_message( - std::string( - m_receive_buffer.begin(), - m_receive_buffer.end() - ) - ); - m_receive_buffer.clear(); - } - -// m_listeners.run_method_unique(&Listener::on_receive_data, data, bytes); - - }catch (...){} -} -void TcpSysbotBase_Connection::process_message(const std::string& message){ -// cout << "sys-botbase Response: " << message << endl; - - m_listeners.run_method_unique(&Listener::on_message, message); - - // Version # - std::string str = message; - if (str.find('.') != std::string::npos){ - while (!str.empty() && str.back() <= 32){ - str.pop_back(); - } - set_status_line0("sys-botbase: Version " + str, COLOR_BLUE); - - std::lock_guard lg(m_lock); - if (!m_thread.joinable()){ - set_mode(str); - } - } - -} -void TcpSysbotBase_Connection::set_mode(const std::string& sbb_version){ - if (sbb_version.rfind("2.", 0) == 0){ - m_logger.log("Detected sbb2. Using old (slow) command set.", COLOR_ORANGE); - write_data("configure mainLoopSleepTime 0\r\n"); - m_supports_command_queue = false; - }else if (PreloadSettings::instance().DEVELOPER_MODE && sbb_version.rfind("3.", 0) == 0){ - m_logger.log("Detected sbb3. Using CC command queue.", COLOR_BLUE); - write_data("configure enablePA 1\r\n"); - m_supports_command_queue = true; - }else{ - m_logger.log("Unrecognized sbb version: " + sbb_version, COLOR_RED); - return; - } - - m_thread = std::thread(&TcpSysbotBase_Connection::thread_loop, this); - declare_ready(controller_mode_status()); -} - - - - - - - -} -} +/* sys-botbase Connection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Time.h" +//#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "SysbotBase_Connection.h" + +//#include +//using std::cout; +//using std::endl; + + +namespace PokemonAutomation{ +namespace SysbotBase{ + +using namespace std::chrono_literals; + + + +bool parse_ip_and_port(const std::string& str, QHostAddress& address, int& port){ + // IPv4 + QStringList parts = QString::fromStdString(str).split(":"); + if (parts.size() != 2){ + return false; + } + address = QHostAddress(parts[0]); + bool ok; + port = parts[1].toUInt(&ok); + if (!ok){ + return false; + } + + // TODO: IPv6 + + return true; +} + + + + +TcpSysbotBase_Connection::TcpSysbotBase_Connection( + Logger& logger, + const std::string& url +) + : m_logger(logger) + , m_supports_command_queue(false) + , m_last_ping_send(WallClock::min()) + , m_last_ping_receive(WallClock::min()) +{ + QHostAddress address; + int port; + if (!parse_ip_and_port(url, address, port)){ + set_status_line0(html_color_text("Invalid IP address + port.", COLOR_RED)); + return; + } + + set_status_line0(html_color_text("Connecting...", COLOR_DARKGREEN)); + + m_connecting_message = + "Connecting To: " + address.toString().toStdString() + + " - Port: " + std::to_string(port); + m_logger.log(m_connecting_message); + + // Attach ourselves as listener first since it might immediately return as + // connected. + m_socket.add_listener(*this); + + try{ + m_socket.connect(address.toString().toStdString(), port); + }catch (...){ + m_socket.remove_listener(*this); + throw; + } +} + +TcpSysbotBase_Connection::~TcpSysbotBase_Connection(){ + try{ + write_data("detachController\r\n"); + }catch (...){} + m_socket.remove_listener(*this); + m_socket.close(); + { + std::lock_guard lg(m_lock); + m_cv.notify_all(); + } + if (m_thread.joinable()){ + m_thread.join(); + } +} + + +ControllerModeStatus TcpSysbotBase_Connection::controller_mode_status() const{ + return { + ControllerType::NintendoSwitch_WiredProController, + { + {ControllerType::NintendoSwitch_WiredProController, { + ControllerFeature::NintendoSwitch_ProController + }}, + } + }; +} + +void TcpSysbotBase_Connection::write_data(const std::string& data){ + WriteSpinLock lg(m_send_lock, "TcpSysbotBase_Connection::write_data()"); +// cout << "Sending: " << data << endl; + m_socket.send(data.data(), data.size()); +} + + +std::string pretty_print(uint64_t x){ + auto ms = x / 1000; + auto us = x - ms * 1000; + std::string str_ms = std::to_string(ms); + std::string str_us = std::to_string(us); + return str_ms + "." + std::string(3 - str_us.size(), '0') + str_us; +} + + +void TcpSysbotBase_Connection::thread_loop(){ + std::unique_lock lg(m_lock); + m_last_ping_send = current_time(); + while (true){ + ClientSocket::State state = m_socket.state(); + if (state == ClientSocket::State::DESTRUCTING || state == ClientSocket::State::NOT_RUNNING){ + break; + } + + WallClock now = current_time(); + + std::chrono::milliseconds time_since = std::chrono::duration_cast(now - m_last_ping_receive); + if (time_since > std::chrono::seconds(5)){ + std::string str = "Last Ack: " + pretty_print(time_since.count()) + " seconds ago"; + set_status_line1(str, COLOR_RED); + } + + m_last_ping_send = current_time(); + if (supports_command_queue() && NintendoSwitch::ConsoleSettings::instance().ENABLE_SBB3_PINGS){ + // If we're more than 60 pings behind, just start clearing them. + while (m_active_pings.size() > 60){ + m_active_pings.erase(m_active_pings.begin()); + } + + m_active_pings[m_ping_seqnum] = m_last_ping_send; + write_data("ping " + std::to_string(m_ping_seqnum) + "\r\n"); + m_ping_seqnum++; + }else{ + write_data("getVersion\r\n"); + } + m_cv.wait_for(lg, std::chrono::seconds(1)); + } +} + + + +void TcpSysbotBase_Connection::on_connect_finished(const std::string& error_message){ + try{ + if (!error_message.empty()){ + m_logger.log(m_connecting_message, COLOR_RED); + set_status_line0(m_connecting_message, COLOR_RED); + return; + } + + m_logger.log(m_connecting_message + " (Success)", COLOR_BLUE); + + write_data("configure echoCommands 0\r\n"); + write_data("getVersion\r\n"); + +// m_thread = std::thread(&TcpSysbotBase_Connection::thread_loop, this); + +// set_status_line0(m_version); + +// declare_ready(controller_mode_status()); + }catch (...){} +} +void TcpSysbotBase_Connection::on_receive_data(const void* data, size_t bytes){ +// cout << "on_receive_data(): " << std::string((const char*)data, bytes - 2) << endl; + + WallClock now = current_time(); + + try{ + const char* ptr = (const char*)data; + for (size_t c = 0; c < bytes; c++){ + char ch = ptr[c]; + if (ch == '\r'){ + continue; + } + if (ch != '\n'){ + m_receive_buffer.emplace_back(ch); + continue; + } + process_message( + std::string( + m_receive_buffer.begin(), + m_receive_buffer.end() + ), + now + ); + m_receive_buffer.clear(); + } + +// m_listeners.run_method_unique(&Listener::on_receive_data, data, bytes); + + }catch (...){} +} +void TcpSysbotBase_Connection::process_message(const std::string& message, WallClock timestamp){ + if (GlobalSettings::instance().LOG_EVERYTHING){ + m_logger.log("Received: " + message, COLOR_DARKGREEN); + } + + m_listeners.run_method_unique(&Listener::on_message, message); + + // Version # + std::string str = message; + if (str.find('.') != std::string::npos){ + while (!str.empty() && str.back() <= 32){ + str.pop_back(); + } + set_status_line0("sys-botbase: Version " + str, COLOR_BLUE); + + std::lock_guard lg(m_lock); + m_last_ping_receive = timestamp; + + if (m_last_ping_send != WallClock::min()){ + std::chrono::microseconds latency = std::chrono::duration_cast(timestamp - m_last_ping_send); + std::string text = "Response Time: " + pretty_print(latency.count()) + " ms"; + if (latency < 10ms){ + set_status_line1(text, COLOR_BLUE); + }else if (latency < 50ms){ + set_status_line1(text, COLOR_DARKGREEN); + }else{ + set_status_line1(text, COLOR_ORANGE); + } + } + + if (!m_thread.joinable()){ + set_mode(str); + } + } + + size_t pos = str.find("ping"); + if (pos != std::string::npos){ + const char* ptr = &str[pos + 4]; + while (true){ + char ch = ptr[0]; + if (ch < 32 || ch == ' ' || ch == '\t'){ + ptr++; + continue; + } + break; + } + size_t ping_seqnum = atoll(ptr); + + std::lock_guard lg(m_lock); + m_last_ping_receive = timestamp; + auto iter = m_active_pings.find(ping_seqnum); + if (iter == m_active_pings.end()){ + m_logger.log("Received Unexpected Ping: " + std::to_string(ping_seqnum)); + return; + } + + std::chrono::microseconds latency = std::chrono::duration_cast(timestamp - iter->second); + std::string text = "Response Time: " + pretty_print(latency.count()) + " ms"; + if (latency < 10ms){ + set_status_line1(text, COLOR_BLUE); + }else if (latency < 50ms){ + set_status_line1(text, COLOR_DARKGREEN); + }else{ + set_status_line1(text, COLOR_ORANGE); + } + + m_active_pings.erase(iter); + } + +} +void TcpSysbotBase_Connection::set_mode(const std::string& sbb_version){ + if (sbb_version.rfind("2.", 0) == 0){ + m_logger.log("Detected sbb2. Using old (slow) command set.", COLOR_ORANGE); + write_data("configure mainLoopSleepTime 0\r\n"); + m_supports_command_queue.store(false, std::memory_order_relaxed); + }else if (sbb_version.rfind("3.", 0) == 0){ + m_logger.log("Detected sbb3. Using CC command queue.", COLOR_BLUE); + if (NintendoSwitch::ConsoleSettings::instance().ENABLE_SBB3_LOGGING){ + write_data("configure enableLogs 1\r\n"); + } + write_data("configure enablePA 1\r\n"); + m_supports_command_queue.store(true, std::memory_order_relaxed); + }else{ + m_logger.log("Unrecognized sbb version: " + sbb_version, COLOR_RED); + return; + } + + m_thread = std::thread(&TcpSysbotBase_Connection::thread_loop, this); + declare_ready(controller_mode_status()); +} + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Connection.h b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Connection.h index 1dc2f99008..0181a656d5 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Connection.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Connection.h @@ -1,84 +1,89 @@ -/* sys-botbase Connection - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_SysbotBase_Connection_H -#define PokemonAutomation_Controllers_SysbotBase_Connection_H - -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Time.h" -#include "Common/Cpp/Sockets/ClientSocket.h" -#include "Controllers/ControllerConnection.h" - -namespace PokemonAutomation{ -namespace SysbotBase{ - - -class TcpSysbotBase_Connection : public ControllerConnection, private ClientSocket::Listener{ -public: - struct Listener{ - virtual void on_message(const std::string& message) = 0; - }; - - void add_listener(Listener& listener){ - m_listeners.add(listener); - } - void remove_listener(Listener& listener){ - m_listeners.add(listener); - } - -public: - TcpSysbotBase_Connection( - Logger& logger, - const std::string& url - ); - ~TcpSysbotBase_Connection(); - - virtual ControllerModeStatus controller_mode_status() const override; - bool supports_command_queue() const{ - return m_supports_command_queue; - } - - void write_data(const std::string& data); - -private: - void thread_loop(); - - virtual void on_connect_finished(const std::string& error_message) override; - virtual void on_receive_data(const void* data, size_t bytes) override; - - void process_message(const std::string& message); - void set_mode(const std::string& sbb_version); - -private: - Logger& m_logger; - ClientSocket m_socket; - - bool m_supports_command_queue; - - std::string m_connecting_message; -// std::string m_version; - WallClock m_last_receive; - std::deque m_receive_buffer; - - SpinLock m_send_lock; - std::mutex m_lock; - std::condition_variable m_cv; - std::thread m_thread; - - ListenerSet m_listeners; -}; - - - -} -} -#endif +/* sys-botbase Connection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_SysbotBase_Connection_H +#define PokemonAutomation_Controllers_SysbotBase_Connection_H + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/Sockets/ClientSocket.h" +#include "Controllers/ControllerConnection.h" + +namespace PokemonAutomation{ +namespace SysbotBase{ + + +class TcpSysbotBase_Connection : public ControllerConnection, private ClientSocket::Listener{ +public: + struct Listener{ + virtual void on_message(const std::string& message) = 0; + }; + + void add_listener(Listener& listener){ + m_listeners.add(listener); + } + void remove_listener(Listener& listener){ + m_listeners.remove(listener); + } + +public: + TcpSysbotBase_Connection( + Logger& logger, + const std::string& url + ); + ~TcpSysbotBase_Connection(); + + virtual ControllerModeStatus controller_mode_status() const override; + bool supports_command_queue() const{ + return m_supports_command_queue.load(std::memory_order_relaxed); + } + + void write_data(const std::string& data); + +private: + void thread_loop(); + + virtual void on_connect_finished(const std::string& error_message) override; + virtual void on_receive_data(const void* data, size_t bytes) override; + + void process_message(const std::string& message, WallClock timestamp); + void set_mode(const std::string& sbb_version); + +private: + Logger& m_logger; + ClientSocket m_socket; + + std::atomic m_supports_command_queue; + + std::string m_connecting_message; +// std::string m_version; + WallClock m_last_ping_send; + WallClock m_last_ping_receive; + + uint64_t m_ping_seqnum = 0; + std::map m_active_pings; + + std::deque m_receive_buffer; + + SpinLock m_send_lock; + std::mutex m_lock; + std::condition_variable m_cv; + std::thread m_thread; + + ListenerSet m_listeners; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Descriptor.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Descriptor.cpp index 6306503989..21173acd68 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Descriptor.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Descriptor.cpp @@ -1,85 +1,85 @@ -/* sys-botbase Descriptor - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "SysbotBase_Descriptor.h" -#include "SysbotBase_Connection.h" -#include "SysbotBase_ProController.h" -#include "SysbotBase3_ProController.h" -#include "SysbotBase_SelectorWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - -template class InterfaceType_t; - -namespace SysbotBase{ - - - -bool TcpSysbotBase_Descriptor::operator==(const ControllerDescriptor& x) const{ - if (typeid(*this) != typeid(x)){ - return false; - } - return m_url == static_cast(x).m_url; -} - -std::string TcpSysbotBase_Descriptor::display_name() const{ - return m_url; -} - -void TcpSysbotBase_Descriptor::load_json(const JsonValue& json){ - const std::string* url = json.to_string(); - if (url == nullptr || url->empty()){ - return; - } - m_url = *url; -} -JsonValue TcpSysbotBase_Descriptor::to_json() const{ - return m_url; -} - - - -std::unique_ptr TcpSysbotBase_Descriptor::open_connection( - Logger& logger, - std::optional change_controller -) const{ - return std::unique_ptr( - new TcpSysbotBase_Connection(logger, m_url) - ); -} -std::unique_ptr TcpSysbotBase_Descriptor::make_controller( - Logger& logger, - ControllerConnection& connection, - ControllerType controller_type -) const{ - TcpSysbotBase_Connection& sbb_connection = static_cast(connection); - if (sbb_connection.supports_command_queue()){ - return std::unique_ptr( - new NintendoSwitch::ProController_SysbotBase3(logger, sbb_connection) - ); - }else{ - return std::unique_ptr( - new NintendoSwitch::ProController_SysbotBase(logger, sbb_connection) - ); - } -} - - - -QWidget* TcpSysbotBase_Descriptor::make_selector_QtWidget(ControllerSelectorWidget& parent) const{ - return new TcpSysbotBase_SelectorWidget(parent, this); -} - - - - -} -} +/* sys-botbase Descriptor + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "SysbotBase_Descriptor.h" +#include "SysbotBase_Connection.h" +#include "SysbotBase_ProController.h" +#include "SysbotBase3_ProController.h" +#include "SysbotBase_SelectorWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + +template class InterfaceType_t; + +namespace SysbotBase{ + + + +bool TcpSysbotBase_Descriptor::operator==(const ControllerDescriptor& x) const{ + if (typeid(*this) != typeid(x)){ + return false; + } + return m_url == static_cast(x).m_url; +} + +std::string TcpSysbotBase_Descriptor::display_name() const{ + return m_url; +} + +void TcpSysbotBase_Descriptor::load_json(const JsonValue& json){ + const std::string* url = json.to_string(); + if (url == nullptr || url->empty()){ + return; + } + m_url = *url; +} +JsonValue TcpSysbotBase_Descriptor::to_json() const{ + return m_url; +} + + + +std::unique_ptr TcpSysbotBase_Descriptor::open_connection( + Logger& logger, + std::optional change_controller +) const{ + return std::unique_ptr( + new TcpSysbotBase_Connection(logger, m_url) + ); +} +std::unique_ptr TcpSysbotBase_Descriptor::make_controller( + Logger& logger, + ControllerConnection& connection, + ControllerType controller_type +) const{ + TcpSysbotBase_Connection& sbb_connection = static_cast(connection); + if (sbb_connection.supports_command_queue()){ + return std::unique_ptr( + new NintendoSwitch::ProController_SysbotBase3(logger, sbb_connection) + ); + }else{ + return std::unique_ptr( + new NintendoSwitch::ProController_SysbotBase(logger, sbb_connection) + ); + } +} + + + +QWidget* TcpSysbotBase_Descriptor::make_selector_QtWidget(ControllerSelectorWidget& parent) const{ + return new TcpSysbotBase_SelectorWidget(parent, this); +} + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Descriptor.h b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Descriptor.h index d1c8beac39..2a70cb4599 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Descriptor.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Descriptor.h @@ -1,65 +1,65 @@ -/* sys-botbase Descriptor - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_SysbotBase_Descriptor_H -#define PokemonAutomation_Controllers_SysbotBase_Descriptor_H - -#include "Controllers/ControllerDescriptor.h" - -namespace PokemonAutomation{ -namespace SysbotBase{ - - - -class TcpSysbotBase_Descriptor : public ControllerDescriptor{ -public: - static constexpr ControllerInterface INTERFACE_NAME = ControllerInterface::TcpSysbotBase; - - -public: - TcpSysbotBase_Descriptor() - : ControllerDescriptor(INTERFACE_NAME) - {} - TcpSysbotBase_Descriptor(std::string url) - : ControllerDescriptor(INTERFACE_NAME) - , m_url(std::move(url)) - {} - - const std::string& url() const{ - return m_url; - } - - virtual bool operator==(const ControllerDescriptor& x) const override; - virtual std::string display_name() const override; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual std::unique_ptr open_connection( - Logger& logger, - std::optional change_controller - ) const override; - virtual std::unique_ptr make_controller( - Logger& logger, - ControllerConnection& connection, - ControllerType controller_type - ) const override; - - virtual QWidget* make_selector_QtWidget(ControllerSelectorWidget& parent) const override; - -private: - std::string m_url; -}; - - - - - - - -} -} -#endif +/* sys-botbase Descriptor + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_SysbotBase_Descriptor_H +#define PokemonAutomation_Controllers_SysbotBase_Descriptor_H + +#include "Controllers/ControllerDescriptor.h" + +namespace PokemonAutomation{ +namespace SysbotBase{ + + + +class TcpSysbotBase_Descriptor : public ControllerDescriptor{ +public: + static constexpr ControllerInterface INTERFACE_NAME = ControllerInterface::TcpSysbotBase; + + +public: + TcpSysbotBase_Descriptor() + : ControllerDescriptor(INTERFACE_NAME) + {} + TcpSysbotBase_Descriptor(std::string url) + : ControllerDescriptor(INTERFACE_NAME) + , m_url(std::move(url)) + {} + + const std::string& url() const{ + return m_url; + } + + virtual bool operator==(const ControllerDescriptor& x) const override; + virtual std::string display_name() const override; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual std::unique_ptr open_connection( + Logger& logger, + std::optional change_controller + ) const override; + virtual std::unique_ptr make_controller( + Logger& logger, + ControllerConnection& connection, + ControllerType controller_type + ) const override; + + virtual QWidget* make_selector_QtWidget(ControllerSelectorWidget& parent) const override; + +private: + std::string m_url; +}; + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_ProController.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_ProController.cpp index 6834f24400..51e4cb81d4 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_ProController.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_ProController.cpp @@ -1,365 +1,368 @@ -/* Nintendo Switch Pro Controller (SysbotBase) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Concurrency/SpinPause.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Options/Environment/PerformanceOptions.h" -#include "Controllers/JoystickTools.h" -#include "SysbotBase_ProController.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -ProController_SysbotBase::ProController_SysbotBase( - Logger& logger, - SysbotBase::TcpSysbotBase_Connection& connection -) - : ControllerWithScheduler(logger) - , m_connection(connection) - , m_stopping(false) - , m_replace_on_next(false) - , m_command_queue(QUEUE_SIZE) - , m_next_state_change(WallClock::max()) -{ - if (!connection.is_ready()){ - return; - } - - // Check compatibility. - - ControllerModeStatus mode_status = connection.controller_mode_status(); - auto iter = mode_status.supported_controllers.find(ControllerType::NintendoSwitch_WiredProController); - if (iter != mode_status.supported_controllers.end()){ - m_dispatch_thread = std::thread(&ProController_SysbotBase::thread_body, this); - } -} -ProController_SysbotBase::~ProController_SysbotBase(){ - stop(); - if (m_dispatch_thread.joinable()){ - m_dispatch_thread.join(); - } -} -void ProController_SysbotBase::stop(){ - if (m_stopping.exchange(true)){ - return; - } - ProController::stop(); - { - std::lock_guard lg(m_state_lock); - m_cv.notify_all(); - } -} - - -const ControllerFeatures& ProController_SysbotBase::controller_features() const{ - static const ControllerFeatures features{ - ControllerFeature::NintendoSwitch_ProController, - }; - return features; -} - - - -void ProController_SysbotBase::cancel_all_commands(){ -// cout << "ProController_SysbotBase::cancel_all_commands()" << endl; - std::lock_guard lg(m_state_lock); - size_t queue_size = m_command_queue.size(); - m_next_state_change = WallClock::min(); - m_command_queue.clear(); - m_cv.notify_all(); - this->clear_on_next(); - m_logger.log("cancel_all_commands(): Command Queue Size = " + std::to_string(queue_size), COLOR_DARKGREEN); -} -void ProController_SysbotBase::replace_on_next_command(){ -// cout << "ProController_SysbotBase::replace_on_next_command - Enter()" << endl; - std::lock_guard lg(m_state_lock); - m_cv.notify_all(); - m_replace_on_next = true; - this->clear_on_next(); - m_logger.log("replace_on_next_command(): Command Queue Size = " + std::to_string(m_command_queue.size()), COLOR_DARKGREEN); -} - - -void ProController_SysbotBase::wait_for_all(const Cancellable* cancellable){ -// cout << "ProController_SysbotBase::wait_for_all - Enter()" << endl; - std::lock_guard lg0(m_issue_lock); - std::unique_lock lg1(m_state_lock); - m_logger.log("wait_for_all(): Command Queue Size = " + std::to_string(m_command_queue.size()), COLOR_DARKGREEN); - this->issue_wait_for_all(cancellable); - m_cv.wait(lg1, [this]{ - return m_next_state_change == WallClock::max() || m_replace_on_next; - }); - if (cancellable){ - cancellable->throw_if_cancelled(); - } -// cout << "ProController_SysbotBase::wait_for_all - Exit()" << endl; -} -void ProController_SysbotBase::push_state(const Cancellable* cancellable, WallDuration duration){ - // Must be called inside "m_state_lock". - - if (cancellable){ - cancellable->throw_if_cancelled(); - } - if (!is_ready()){ - throw InvalidConnectionStateException(""); - } - - Button buttons = BUTTON_NONE; - for (size_t c = 0; c < 14; c++){ - buttons |= m_buttons[c].is_busy() - ? (Button)((uint16_t)1 << c) - : BUTTON_NONE; - } - - DpadPosition dpad = m_dpad.is_busy() ? m_dpad.position : DPAD_NONE; - - uint8_t left_x = 128; - uint8_t left_y = 128; - uint8_t right_x = 128; - uint8_t right_y = 128; - if (m_left_joystick.is_busy()){ - left_x = m_left_joystick.x; - left_y = m_left_joystick.y; - } - if (m_right_joystick.is_busy()){ - right_x = m_right_joystick.x; - right_y = m_right_joystick.y; - } - - std::unique_lock lg(m_state_lock, std::adopt_lock_t()); - - m_cv.wait(lg, [this]{ - return m_command_queue.size() < QUEUE_SIZE || m_replace_on_next; - }); - - lg.release(); - - if (cancellable){ - cancellable->throw_if_cancelled(); - } - - if (m_replace_on_next){ -// cout << "executing replace" << endl; - m_replace_on_next = false; - m_command_queue.clear(); - m_next_state_change = WallClock::min(); - m_cv.notify_all(); - } - - // Enqueuing into empty+idle queue. - if (m_next_state_change == WallClock::max()){ - m_next_state_change = WallClock::min(); - m_cv.notify_all(); - } - - Command& command = m_command_queue.push_back(); - - command.state.buttons = buttons; - command.state.dpad = dpad; - command.state.left_x = left_x; - command.state.left_y = left_y; - command.state.right_x = right_x; - command.state.right_y = right_y; - - command.duration = std::chrono::duration_cast(duration); -} - - - -void ProController_SysbotBase::send_diff( - const ProControllerState& old_state, - const ProControllerState& new_state -){ -#if 0 - m_logger.log( - "send_diff(): (" + button_to_string(new_state.buttons) + - "), dpad(" + dpad_to_string(new_state.dpad) + - "), LJ(" + std::to_string(new_state.left_x) + "," + std::to_string(new_state.left_y) + - "), RJ(" + std::to_string(new_state.right_x) + "," + std::to_string(new_state.right_y) + - ")", - COLOR_DARKGREEN - ); -#endif - - // These need to match: - // https://github.com/olliz0r/sys-botbase/blob/master/sys-botbase/source/util.c#L145 - static const std::vector> BUTTON_MAP{ - {BUTTON_Y, "Y"}, - {BUTTON_B, "B"}, - {BUTTON_A, "A"}, - {BUTTON_X, "X"}, - {BUTTON_L, "L"}, - {BUTTON_R, "R"}, - {BUTTON_ZL, "ZL"}, - {BUTTON_ZR, "ZR"}, - {BUTTON_MINUS, "MINUS"}, - {BUTTON_PLUS, "PLUS"}, - {BUTTON_LCLICK, "LSTICK"}, - {BUTTON_RCLICK, "RSTICK"}, - {BUTTON_HOME, "HOME"}, - {BUTTON_CAPTURE, "CAPTURE"}, - {BUTTON_UP, "DU"}, - {BUTTON_RIGHT, "DR"}, - {BUTTON_DOWN, "DD"}, - {BUTTON_LEFT, "DL"}, - }; - - std::string message; - - - // Merge the dpad states. - ButtonFlagType old_buttons = old_state.buttons; - ButtonFlagType new_buttons = new_state.buttons; - - SplitDpad old_dpad = convert_unified_to_split_dpad(old_state.dpad); - if (old_dpad.up) old_buttons |= BUTTON_UP; - if (old_dpad.right) old_buttons |= BUTTON_RIGHT; - if (old_dpad.down) old_buttons |= BUTTON_DOWN; - if (old_dpad.left) old_buttons |= BUTTON_LEFT; - - SplitDpad new_dpad = convert_unified_to_split_dpad(new_state.dpad); - if (new_dpad.up) new_buttons |= BUTTON_UP; - if (new_dpad.right) new_buttons |= BUTTON_RIGHT; - if (new_dpad.down) new_buttons |= BUTTON_DOWN; - if (new_dpad.left) new_buttons |= BUTTON_LEFT; - - - if (old_buttons != new_buttons){ - for (const auto& button : BUTTON_MAP){ - ButtonFlagType mask = (ButtonFlagType)button.first; - bool before = (ButtonFlagType)old_buttons & mask; - bool after = (ButtonFlagType)new_buttons & mask; - if (before == after){ - continue; - } - if (after){ - message += "press " + button.second + "\r\n"; - }else{ - message += "release " + button.second + "\r\n"; - } - } - } - - if (old_state.left_x != new_state.left_x || - old_state.left_y != new_state.left_y - ){ - double fx = JoystickTools::linear_u8_to_float(new_state.left_x); - double fy = -JoystickTools::linear_u8_to_float(new_state.left_y); -// cout << "fx = " << fx << ", fy = " << fy << endl; - int16_t ix = JoystickTools::linear_float_to_s16(fx); - int16_t iy = JoystickTools::linear_float_to_s16(fy); -// cout << "ix = " << ix << ", iy = " << iy << endl; - message += "setStick LEFT "; - message += std::to_string(ix); - message += " "; - message += std::to_string(iy); - message += "\r\n"; - } - if (old_state.right_x != new_state.right_x || - old_state.right_y != new_state.right_y - ){ - double fx = JoystickTools::linear_u8_to_float(new_state.right_x); - double fy = -JoystickTools::linear_u8_to_float(new_state.right_y); - int16_t ix = JoystickTools::linear_float_to_s16(fx); - int16_t iy = JoystickTools::linear_float_to_s16(fy); - message += "setStick RIGHT "; - message += std::to_string(ix); - message += " "; - message += std::to_string(iy); - message += "\r\n"; - } - - if (message.empty()){ - return; - } - -// cout << message << endl; - m_connection.write_data(message); - - if (GlobalSettings::instance().LOG_EVERYTHING){ - m_logger.log("sys-botbase: " + message); - } -} - - -void ProController_SysbotBase::thread_body(){ - GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(); - std::chrono::microseconds EARLY_WAKE = GlobalSettings::instance().PERFORMANCE->PRECISE_WAKE_MARGIN; - - ProControllerState current_state; - - std::unique_lock lg(m_state_lock); - while (!m_stopping.load(std::memory_order_relaxed)){ - WallClock now = current_time(); - - // State change. - if (now >= m_next_state_change){ - if (m_command_queue.empty()){ - send_diff(current_state, ProControllerState()); - current_state.clear(); - m_next_state_change = WallClock::max(); - }else{ - Command& command = m_command_queue.front(); - send_diff(current_state, command.state); - current_state = command.state; - if (m_next_state_change == WallClock::min()){ - m_next_state_change = now; - } - m_next_state_change += command.duration; - m_command_queue.pop_front(); - } - m_cv.notify_all(); - continue; - } - - if (now + EARLY_WAKE >= m_next_state_change){ - pause(); - continue; - } - - m_cv.wait_until(lg, m_next_state_change - EARLY_WAKE); - - // Check how much we shot passed the expiration time. -// WallDuration delay = now - expiration; - -// cout << "Delay = " << std::chrono::duration_cast(delay) << endl; - } - - ProControllerState neutral_state; - send_diff(current_state, neutral_state); -} - - - - - - - - - - - - - - - - - - - - - - - -} -} +/* Nintendo Switch Pro Controller (SysbotBase) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Concurrency/SpinPause.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Options/Environment/PerformanceOptions.h" +#include "Controllers/JoystickTools.h" +#include "SysbotBase_ProController.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +ProController_SysbotBase::ProController_SysbotBase( + Logger& logger, + SysbotBase::TcpSysbotBase_Connection& connection +) + : ProController(logger) + , ControllerWithScheduler(logger) + , m_connection(connection) + , m_stopping(false) + , m_replace_on_next(false) + , m_command_queue(QUEUE_SIZE) + , m_next_state_change(WallClock::max()) +{ + if (!connection.is_ready()){ + return; + } + + // Check compatibility. + + ControllerModeStatus mode_status = connection.controller_mode_status(); + auto iter = mode_status.supported_controllers.find(ControllerType::NintendoSwitch_WiredProController); + if (iter != mode_status.supported_controllers.end()){ + m_dispatch_thread = std::thread(&ProController_SysbotBase::thread_body, this); + } +} +ProController_SysbotBase::~ProController_SysbotBase(){ + stop(); + if (m_dispatch_thread.joinable()){ + m_dispatch_thread.join(); + } +} +void ProController_SysbotBase::stop(){ + if (m_stopping.exchange(true)){ + return; + } + ProController::stop(); + { + std::lock_guard lg(m_state_lock); + m_cv.notify_all(); + } +} + + +const ControllerFeatures& ProController_SysbotBase::controller_features() const{ + static const ControllerFeatures features{ + ControllerFeature::NintendoSwitch_ProController, + }; + return features; +} + + + +void ProController_SysbotBase::cancel_all_commands(){ +// cout << "ProController_SysbotBase::cancel_all_commands()" << endl; + std::lock_guard lg(m_state_lock); + size_t queue_size = m_command_queue.size(); + m_next_state_change = WallClock::min(); + m_command_queue.clear(); + m_cv.notify_all(); + this->clear_on_next(); + m_logger.log("cancel_all_commands(): Command Queue Size = " + std::to_string(queue_size), COLOR_DARKGREEN); +} +void ProController_SysbotBase::replace_on_next_command(){ +// cout << "ProController_SysbotBase::replace_on_next_command - Enter()" << endl; + std::lock_guard lg(m_state_lock); + m_cv.notify_all(); + m_replace_on_next = true; + this->clear_on_next(); + m_logger.log("replace_on_next_command(): Command Queue Size = " + std::to_string(m_command_queue.size()), COLOR_DARKGREEN); +} + + +void ProController_SysbotBase::wait_for_all(const Cancellable* cancellable){ +// cout << "ProController_SysbotBase::wait_for_all - Enter()" << endl; + std::lock_guard lg0(m_issue_lock); + std::unique_lock lg1(m_state_lock); + m_logger.log("wait_for_all(): Command Queue Size = " + std::to_string(m_command_queue.size()), COLOR_DARKGREEN); + this->issue_wait_for_all(cancellable); + m_cv.wait(lg1, [this]{ + return m_next_state_change == WallClock::max() || m_replace_on_next; + }); + if (cancellable){ + cancellable->throw_if_cancelled(); + } +// cout << "ProController_SysbotBase::wait_for_all - Exit()" << endl; +} +void ProController_SysbotBase::push_state(const Cancellable* cancellable, WallDuration duration){ + // Must be called inside "m_state_lock". + + if (cancellable){ + cancellable->throw_if_cancelled(); + } + if (!is_ready()){ + throw InvalidConnectionStateException(""); + } + + Button buttons = BUTTON_NONE; + for (size_t c = 0; c < 14; c++){ + buttons |= m_buttons[c].is_busy() + ? (Button)((uint16_t)1 << c) + : BUTTON_NONE; + } + + DpadPosition dpad = m_dpad.is_busy() ? m_dpad.position : DPAD_NONE; + + uint8_t left_x = 128; + uint8_t left_y = 128; + uint8_t right_x = 128; + uint8_t right_y = 128; + if (m_left_joystick.is_busy()){ + left_x = m_left_joystick.x; + left_y = m_left_joystick.y; + } + if (m_right_joystick.is_busy()){ + right_x = m_right_joystick.x; + right_y = m_right_joystick.y; + } + + std::unique_lock lg(m_state_lock, std::adopt_lock_t()); + + m_cv.wait(lg, [this]{ + return m_command_queue.size() < QUEUE_SIZE || m_replace_on_next; + }); + + lg.release(); + + if (cancellable){ + cancellable->throw_if_cancelled(); + } + + if (m_replace_on_next){ +// cout << "executing replace" << endl; + m_replace_on_next = false; + m_command_queue.clear(); + m_next_state_change = WallClock::min(); + m_cv.notify_all(); + } + + // Enqueuing into empty+idle queue. + if (m_next_state_change == WallClock::max()){ + m_next_state_change = WallClock::min(); + m_cv.notify_all(); + } + + Command& command = m_command_queue.push_back(); + + command.state.buttons = buttons; + command.state.dpad = dpad; + command.state.left_x = left_x; + command.state.left_y = left_y; + command.state.right_x = right_x; + command.state.right_y = right_y; + + command.duration = std::chrono::duration_cast(duration); +} + + + +void ProController_SysbotBase::send_diff( + const ProControllerState& old_state, + const ProControllerState& new_state +){ +#if 0 + m_logger.log( + "send_diff(): (" + button_to_string(new_state.buttons) + + "), dpad(" + dpad_to_string(new_state.dpad) + + "), LJ(" + std::to_string(new_state.left_x) + "," + std::to_string(new_state.left_y) + + "), RJ(" + std::to_string(new_state.right_x) + "," + std::to_string(new_state.right_y) + + ")", + COLOR_DARKGREEN + ); +#endif + + // These need to match: + // https://github.com/olliz0r/sys-botbase/blob/master/sys-botbase/source/util.c#L145 + static const std::vector> BUTTON_MAP{ + {BUTTON_Y, "Y"}, + {BUTTON_B, "B"}, + {BUTTON_A, "A"}, + {BUTTON_X, "X"}, + {BUTTON_L, "L"}, + {BUTTON_R, "R"}, + {BUTTON_ZL, "ZL"}, + {BUTTON_ZR, "ZR"}, + {BUTTON_MINUS, "MINUS"}, + {BUTTON_PLUS, "PLUS"}, + {BUTTON_LCLICK, "LSTICK"}, + {BUTTON_RCLICK, "RSTICK"}, + {BUTTON_HOME, "HOME"}, + {BUTTON_CAPTURE, "CAPTURE"}, + {BUTTON_UP, "DU"}, + {BUTTON_RIGHT, "DR"}, + {BUTTON_DOWN, "DD"}, + {BUTTON_LEFT, "DL"}, + }; + + std::string message; + + + // Merge the dpad states. + ButtonFlagType old_buttons = old_state.buttons; + ButtonFlagType new_buttons = new_state.buttons; + + SplitDpad old_dpad = convert_unified_to_split_dpad(old_state.dpad); + if (old_dpad.up) old_buttons |= BUTTON_UP; + if (old_dpad.right) old_buttons |= BUTTON_RIGHT; + if (old_dpad.down) old_buttons |= BUTTON_DOWN; + if (old_dpad.left) old_buttons |= BUTTON_LEFT; + + SplitDpad new_dpad = convert_unified_to_split_dpad(new_state.dpad); + if (new_dpad.up) new_buttons |= BUTTON_UP; + if (new_dpad.right) new_buttons |= BUTTON_RIGHT; + if (new_dpad.down) new_buttons |= BUTTON_DOWN; + if (new_dpad.left) new_buttons |= BUTTON_LEFT; + + + if (old_buttons != new_buttons){ + for (const auto& button : BUTTON_MAP){ + ButtonFlagType mask = (ButtonFlagType)button.first; + bool before = (ButtonFlagType)old_buttons & mask; + bool after = (ButtonFlagType)new_buttons & mask; + if (before == after){ + continue; + } + if (after){ + message += "press " + button.second + "\r\n"; + }else{ + message += "release " + button.second + "\r\n"; + } + } + } + + if (old_state.left_x != new_state.left_x || + old_state.left_y != new_state.left_y + ){ + double fx = JoystickTools::linear_u8_to_float(new_state.left_x); + double fy = -JoystickTools::linear_u8_to_float(new_state.left_y); + JoystickTools::clip_magnitude(fx, fy); +// cout << "fx = " << fx << ", fy = " << fy << endl; + int16_t ix = JoystickTools::linear_float_to_s16(fx); + int16_t iy = JoystickTools::linear_float_to_s16(fy); +// cout << "ix = " << ix << ", iy = " << iy << endl; + message += "setStick LEFT "; + message += std::to_string(ix); + message += " "; + message += std::to_string(iy); + message += "\r\n"; + } + if (old_state.right_x != new_state.right_x || + old_state.right_y != new_state.right_y + ){ + double fx = JoystickTools::linear_u8_to_float(new_state.right_x); + double fy = -JoystickTools::linear_u8_to_float(new_state.right_y); + JoystickTools::clip_magnitude(fx, fy); + int16_t ix = JoystickTools::linear_float_to_s16(fx); + int16_t iy = JoystickTools::linear_float_to_s16(fy); + message += "setStick RIGHT "; + message += std::to_string(ix); + message += " "; + message += std::to_string(iy); + message += "\r\n"; + } + + if (message.empty()){ + return; + } + +// cout << message << endl; + m_connection.write_data(message); + + if (GlobalSettings::instance().LOG_EVERYTHING){ + m_logger.log("sys-botbase: " + message); + } +} + + +void ProController_SysbotBase::thread_body(){ + GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(m_logger); + std::chrono::microseconds EARLY_WAKE = GlobalSettings::instance().PERFORMANCE->PRECISE_WAKE_MARGIN; + + ProControllerState current_state; + + std::unique_lock lg(m_state_lock); + while (!m_stopping.load(std::memory_order_relaxed)){ + WallClock now = current_time(); + + // State change. + if (now >= m_next_state_change){ + if (m_command_queue.empty()){ + send_diff(current_state, ProControllerState()); + current_state.clear(); + m_next_state_change = WallClock::max(); + }else{ + Command& command = m_command_queue.front(); + send_diff(current_state, command.state); + current_state = command.state; + if (m_next_state_change == WallClock::min()){ + m_next_state_change = now; + } + m_next_state_change += command.duration; + m_command_queue.pop_front(); + } + m_cv.notify_all(); + continue; + } + + if (now + EARLY_WAKE >= m_next_state_change){ + pause(); + continue; + } + + m_cv.wait_until(lg, m_next_state_change - EARLY_WAKE); + + // Check how much we shot passed the expiration time. +// WallDuration delay = now - expiration; + +// cout << "Delay = " << std::chrono::duration_cast(delay) << endl; + } + + ProControllerState neutral_state; + send_diff(current_state, neutral_state); +} + + + + + + + + + + + + + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_ProController.h b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_ProController.h index ecaacf8e3c..a5d4f25bcb 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_ProController.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_ProController.h @@ -1,253 +1,253 @@ -/* Nintendo Switch Pro Controller (SysbotBase) - * - * From: https://github.com/PokemonAutomation/ - * - */ - - -#ifndef PokemonAutomation_NintendoSwitch_ProController_SysbotBase_H -#define PokemonAutomation_NintendoSwitch_ProController_SysbotBase_H - -#include -#include "Common/Cpp/Containers/CircularBuffer.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.h" -#include "SysbotBase_Connection.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -class ProController_SysbotBase final : - public ProController, - public ControllerWithScheduler -{ -public: - using ContextType = ProControllerContext; - - static constexpr size_t QUEUE_SIZE = 4; - - -public: - ProController_SysbotBase( - Logger& logger, - SysbotBase::TcpSysbotBase_Connection& connection - ); - ~ProController_SysbotBase(); - void stop(); - - -public: - virtual ControllerType controller_type() const override{ - return ControllerType::NintendoSwitch_WiredProController; - } - virtual const ControllerFeatures& controller_features() const override; - virtual ControllerPerformanceClass performance_class() const override{ - return ControllerPerformanceClass::SysbotBase; - } - - virtual Milliseconds ticksize() const override{ - return Milliseconds::zero(); - } - virtual Milliseconds cooldown() const override{ - return Milliseconds(150); - } - virtual Milliseconds timing_variation() const override{ - return ConsoleSettings::instance().TIMING_OPTIONS.SYSBOTBASE; - } - virtual bool atomic_multibutton() const override{ - return false; - } - - -public: - virtual Logger& logger() override{ - return m_logger; - } - virtual RecursiveThrottler& logging_throttler() override{ - return m_logging_throttler; - } - virtual bool is_ready() const override{ - return m_connection.is_ready(); - } - - -public: - virtual void cancel_all_commands() override; - virtual void replace_on_next_command() override; - - virtual void wait_for_all(const Cancellable* cancellable) override; - - -public: - // Superscalar Commands (the "ssf" framework) - - virtual void issue_barrier(const Cancellable* cancellable) override{ - ControllerWithScheduler::issue_barrier(cancellable); - } - virtual void issue_nop(const Cancellable* cancellable, Milliseconds duration) override{ - ControllerWithScheduler::issue_nop(cancellable, duration); - } - - virtual void issue_buttons( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - Button button - ) override{ - ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); - } - virtual void issue_dpad( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition position - ) override{ - ControllerWithScheduler::issue_dpad(cancellable, delay, hold, cooldown, position); - } - virtual void issue_left_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y - ) override{ - ControllerWithScheduler::issue_left_joystick(cancellable, delay, hold, cooldown, x, y); - } - virtual void issue_right_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y - ) override{ - ControllerWithScheduler::issue_right_joystick(cancellable, delay, hold, cooldown, x, y); - } - - virtual void issue_gyro_accel_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_x(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_accel_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_y(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_accel_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_z(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_x(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_y(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_z(cancellable, delay, hold, cooldown, value); - } - - virtual void issue_full_controller_state( - const Cancellable* cancellable, - Milliseconds hold, - Button button, - DpadPosition position, - uint8_t left_x, uint8_t left_y, - uint8_t right_x, uint8_t right_y - ) override{ - ControllerWithScheduler::issue_full_controller_state( - cancellable, - hold, - button, - position, - left_x, left_y, - right_x, right_y - ); - } - - -public: - // High speed RPCs. - - virtual void issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button - ) override{ - ControllerWithScheduler::issue_mash_button(cancellable, duration, button); - } - virtual void issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button0, Button button1 - ) override{ - ControllerWithScheduler::issue_mash_button(cancellable, duration, button0, button1); - } - virtual void issue_mash_AZs( - const Cancellable* cancellable, - Milliseconds duration - ) override{ - ControllerWithScheduler::issue_mash_AZs(cancellable, duration); - } - virtual void issue_system_scroll( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition direction // Diagonals not allowed. - ) override{ - ControllerWithScheduler::issue_system_scroll(cancellable, delay, hold, cooldown, direction); - } - - -private: - virtual void push_state(const Cancellable* cancellable, WallDuration duration) override; - - void send_diff( - const ProControllerState& old_state, - const ProControllerState& new_state - ); - void thread_body(); - - -private: - SysbotBase::TcpSysbotBase_Connection& m_connection; - - std::atomic m_stopping; - bool m_replace_on_next; - - struct Command{ - ProControllerState state; - Milliseconds duration; - }; - CircularBuffer m_command_queue; - - // WallClock::max() means the queue is empty. - // WallClock::min() means the state has suddently changed. - WallClock m_next_state_change; - - std::condition_variable m_cv; - std::thread m_dispatch_thread; -}; - - - - -} -} -#endif +/* Nintendo Switch Pro Controller (SysbotBase) + * + * From: https://github.com/PokemonAutomation/ + * + */ + + +#ifndef PokemonAutomation_NintendoSwitch_ProController_SysbotBase_H +#define PokemonAutomation_NintendoSwitch_ProController_SysbotBase_H + +#include +#include "Common/Cpp/Containers/CircularBuffer.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.h" +#include "SysbotBase_Connection.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +class ProController_SysbotBase final : + public ProController, + public ControllerWithScheduler +{ +public: + using ContextType = ProControllerContext; + + static constexpr size_t QUEUE_SIZE = 4; + + +public: + ProController_SysbotBase( + Logger& logger, + SysbotBase::TcpSysbotBase_Connection& connection + ); + ~ProController_SysbotBase(); + void stop(); + + +public: + virtual ControllerType controller_type() const override{ + return ControllerType::NintendoSwitch_WiredProController; + } + virtual const ControllerFeatures& controller_features() const override; + virtual ControllerPerformanceClass performance_class() const override{ + return ControllerPerformanceClass::SysbotBase; + } + + virtual Milliseconds ticksize() const override{ + return Milliseconds::zero(); + } + virtual Milliseconds cooldown() const override{ + return Milliseconds(150); + } + virtual Milliseconds timing_variation() const override{ + return ConsoleSettings::instance().TIMING_OPTIONS.SYSBOTBASE; + } + virtual bool atomic_multibutton() const override{ + return false; + } + + +public: + virtual Logger& logger() override{ + return m_logger; + } + virtual RecursiveThrottler& logging_throttler() override{ + return m_logging_throttler; + } + virtual bool is_ready() const override{ + return m_connection.is_ready(); + } + + +public: + virtual void cancel_all_commands() override; + virtual void replace_on_next_command() override; + + virtual void wait_for_all(const Cancellable* cancellable) override; + + +public: + // Superscalar Commands (the "ssf" framework) + + virtual void issue_barrier(const Cancellable* cancellable) override{ + ControllerWithScheduler::issue_barrier(cancellable); + } + virtual void issue_nop(const Cancellable* cancellable, Milliseconds duration) override{ + ControllerWithScheduler::issue_nop(cancellable, duration); + } + + virtual void issue_buttons( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + Button button + ) override{ + ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); + } + virtual void issue_dpad( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition position + ) override{ + ControllerWithScheduler::issue_dpad(cancellable, delay, hold, cooldown, position); + } + virtual void issue_left_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y + ) override{ + ControllerWithScheduler::issue_left_joystick(cancellable, delay, hold, cooldown, x, y); + } + virtual void issue_right_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y + ) override{ + ControllerWithScheduler::issue_right_joystick(cancellable, delay, hold, cooldown, x, y); + } + + virtual void issue_gyro_accel_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_x(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_accel_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_y(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_accel_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_z(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_x(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_y(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_z(cancellable, delay, hold, cooldown, value); + } + + virtual void issue_full_controller_state( + const Cancellable* cancellable, + Milliseconds hold, + Button button, + DpadPosition position, + uint8_t left_x, uint8_t left_y, + uint8_t right_x, uint8_t right_y + ) override{ + ControllerWithScheduler::issue_full_controller_state( + cancellable, + hold, + button, + position, + left_x, left_y, + right_x, right_y + ); + } + + +public: + // High speed RPCs. + + virtual void issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button + ) override{ + ControllerWithScheduler::issue_mash_button(cancellable, duration, button); + } + virtual void issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button0, Button button1 + ) override{ + ControllerWithScheduler::issue_mash_button(cancellable, duration, button0, button1); + } + virtual void issue_mash_AZs( + const Cancellable* cancellable, + Milliseconds duration + ) override{ + ControllerWithScheduler::issue_mash_AZs(cancellable, duration); + } + virtual void issue_system_scroll( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition direction // Diagonals not allowed. + ) override{ + ControllerWithScheduler::issue_system_scroll(cancellable, delay, hold, cooldown, direction); + } + + +private: + virtual void push_state(const Cancellable* cancellable, WallDuration duration) override; + + void send_diff( + const ProControllerState& old_state, + const ProControllerState& new_state + ); + void thread_body(); + + +private: + SysbotBase::TcpSysbotBase_Connection& m_connection; + + std::atomic m_stopping; + bool m_replace_on_next; + + struct Command{ + ProControllerState state; + Milliseconds duration; + }; + CircularBuffer m_command_queue; + + // WallClock::max() means the queue is empty. + // WallClock::min() means the state has suddently changed. + WallClock m_next_state_change; + + std::condition_variable m_cv; + std::thread m_dispatch_thread; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_SelectorWidget.h b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_SelectorWidget.h index 85dd1cb350..b841d28805 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_SelectorWidget.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_SelectorWidget.h @@ -1,72 +1,72 @@ -/* sys-botbase Selector Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_SysbotBase_SelectorWidget_H -#define PokemonAutomation_Controllers_SysbotBase_SelectorWidget_H - -#include -#include "Controllers/ControllerDescriptor.h" -#include "Controllers/ControllerSelectorWidget.h" -#include "SysbotBase_Descriptor.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace SysbotBase{ - - - -class TcpSysbotBase_SelectorWidget : public QLineEdit{ -public: - TcpSysbotBase_SelectorWidget( - ControllerSelectorWidget& parent, - const ControllerDescriptor* current - ) - : QLineEdit(&parent) - { -// cout << "TcpSysbotBase()" << endl; - - QSizePolicy policy; - policy.setHorizontalStretch(3); - this->setSizePolicy(policy); - - this->setPlaceholderText("192.168.0.100:6000"); - - if (current == nullptr || current->interface_type != ControllerInterface::TcpSysbotBase){ - std::shared_ptr descriptor = - parent.session().option().get_descriptor_from_cache(ControllerInterface::TcpSysbotBase); - if (!descriptor){ - descriptor.reset(new TcpSysbotBase_Descriptor()); - } - parent.session().set_device(descriptor); - } - this->setText(QString::fromStdString(parent.session().descriptor()->display_name())); - - connect( - this, &QLineEdit::editingFinished, - &parent, [this, &parent](){ - std::shared_ptr selected(new TcpSysbotBase_Descriptor( - this->text().toStdString() - )); - - std::shared_ptr current = parent.session().descriptor(); - if (*current == *selected){ - return; - } - - parent.session().set_device(std::move(selected)); - } - ); - } -}; - - - -} -} -#endif +/* sys-botbase Selector Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_SysbotBase_SelectorWidget_H +#define PokemonAutomation_Controllers_SysbotBase_SelectorWidget_H + +#include +#include "Controllers/ControllerDescriptor.h" +#include "Controllers/ControllerSelectorWidget.h" +#include "SysbotBase_Descriptor.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace SysbotBase{ + + + +class TcpSysbotBase_SelectorWidget : public QLineEdit{ +public: + TcpSysbotBase_SelectorWidget( + ControllerSelectorWidget& parent, + const ControllerDescriptor* current + ) + : QLineEdit(&parent) + { +// cout << "TcpSysbotBase()" << endl; + + QSizePolicy policy; + policy.setHorizontalStretch(3); + this->setSizePolicy(policy); + + this->setPlaceholderText("192.168.0.100:6000"); + + if (current == nullptr || current->interface_type != ControllerInterface::TcpSysbotBase){ + std::shared_ptr descriptor = + parent.session().option().get_descriptor_from_cache(ControllerInterface::TcpSysbotBase); + if (!descriptor){ + descriptor.reset(new TcpSysbotBase_Descriptor()); + } + parent.session().set_device(descriptor); + } + this->setText(QString::fromStdString(parent.session().descriptor()->display_name())); + + connect( + this, &QLineEdit::editingFinished, + &parent, [this, &parent](){ + std::shared_ptr selected(new TcpSysbotBase_Descriptor( + this->text().toStdString() + )); + + std::shared_ptr current = parent.session().descriptor(); + if (*current == *selected){ + return; + } + + parent.session().set_device(std::move(selected)); + } + ); + } +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/DevPrograms/JoyconProgram.cpp b/SerialPrograms/Source/NintendoSwitch/DevPrograms/JoyconProgram.cpp index fca1451ca7..ca2bb5ba9f 100644 --- a/SerialPrograms/Source/NintendoSwitch/DevPrograms/JoyconProgram.cpp +++ b/SerialPrograms/Source/NintendoSwitch/DevPrograms/JoyconProgram.cpp @@ -1,68 +1,68 @@ -/* Joycon Test Program - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "JoyconProgram.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -JoyconProgram_Descriptor::JoyconProgram_Descriptor() - : SingleSwitchProgramDescriptor( - "NintendoSwitch:JoyconProgram", - "Nintendo Switch", "Joycon Program", - "", - "Template for a joycon program.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_RightJoycon}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - -JoyconProgram::JoyconProgram(){} -void JoyconProgram::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ - JoyconContext context(scope, env.console.controller()); - - // - // Sample joycon program. - // - // This will start from the grip menu and enter the system settings. - // Note that the joycon is horizontal. - // - // You can press any button, but if it doesn't exist, it won't do anything. - // - // No support for gyro yet. That's coming later. - // - - pbf_move_joystick(context, 64, 64, 10000ms, 0ms); - -#if 0 - pbf_press_button(context, BUTTON_A, 200ms, 2000ms); - pbf_press_button(context, BUTTON_HOME, 200ms, 2000ms); - pbf_move_joystick(context, 128, 0, 100ms, 100ms); - pbf_move_joystick(context, 128, 0, 100ms, 100ms); - pbf_move_joystick(context, 255, 128, 100ms, 100ms); - pbf_move_joystick(context, 128, 0, 100ms, 100ms); - pbf_press_button(context, BUTTON_X, 200ms, 2000ms); -#endif - -} - - - - - - -} -} +/* Joycon Test Program + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "JoyconProgram.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +JoyconProgram_Descriptor::JoyconProgram_Descriptor() + : SingleSwitchProgramDescriptor( + "NintendoSwitch:JoyconProgram", + "Nintendo Switch", "Joycon Program", + "", + "Template for a joycon program.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_RightJoycon}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + +JoyconProgram::JoyconProgram(){} +void JoyconProgram::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ + JoyconContext context(scope, env.console.controller()); + + // + // Sample joycon program. + // + // This will start from the grip menu and enter the system settings. + // Note that the joycon is horizontal. + // + // You can press any button, but if it doesn't exist, it won't do anything. + // + // No support for gyro yet. That's coming later. + // + + pbf_move_joystick(context, 64, 64, 10000ms, 0ms); + +#if 0 + pbf_press_button(context, BUTTON_A, 200ms, 2000ms); + pbf_press_button(context, BUTTON_HOME, 200ms, 2000ms); + pbf_move_joystick(context, 128, 0, 100ms, 100ms); + pbf_move_joystick(context, 128, 0, 100ms, 100ms); + pbf_move_joystick(context, 255, 128, 100ms, 100ms); + pbf_move_joystick(context, 128, 0, 100ms, 100ms); + pbf_press_button(context, BUTTON_X, 200ms, 2000ms); +#endif + +} + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/DevPrograms/JoyconProgram.h b/SerialPrograms/Source/NintendoSwitch/DevPrograms/JoyconProgram.h index 5d0c860c23..2df094aa33 100644 --- a/SerialPrograms/Source/NintendoSwitch/DevPrograms/JoyconProgram.h +++ b/SerialPrograms/Source/NintendoSwitch/DevPrograms/JoyconProgram.h @@ -1,38 +1,38 @@ -/* Joycon Test Program - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_JoyconProgram_H -#define PokemonAutomation_NintendoSwitch_JoyconProgram_H - -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class JoyconProgram_Descriptor : public SingleSwitchProgramDescriptor{ -public: - JoyconProgram_Descriptor(); -}; - - - -class JoyconProgram : public SingleSwitchProgramInstance{ -public: - JoyconProgram(); - virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; - -}; - - - - -} -} -#endif - - - +/* Joycon Test Program + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_JoyconProgram_H +#define PokemonAutomation_NintendoSwitch_JoyconProgram_H + +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class JoyconProgram_Descriptor : public SingleSwitchProgramDescriptor{ +public: + JoyconProgram_Descriptor(); +}; + + + +class JoyconProgram : public SingleSwitchProgramInstance{ +public: + JoyconProgram(); + virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; + +}; + + + + +} +} +#endif + + + diff --git a/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestDudunsparceFormDetector.cpp b/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestDudunsparceFormDetector.cpp index 05fc562ce1..537318b1c6 100644 --- a/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestDudunsparceFormDetector.cpp +++ b/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestDudunsparceFormDetector.cpp @@ -1,184 +1,184 @@ -/* Test Dudunsparce Form Detector - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#include "3rdParty/ONNX/OnnxToolsPA.h" -#include "Common/Cpp/Time.h" -#include "ClientSource/Connection/BotBase.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/Async/InferenceSession.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "TestDudunsparceFormDetector.h" - -#include -#include - -#include - -#include -#include -#include -using std::cout, std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -class DudunsparceFormDetector : public VisualInferenceCallback{ -public: - DudunsparceFormDetector(VideoOverlay& overlay); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; - - std::string get_label() const { - int detected_label_id = m_detected.load(std::memory_order_acquire); - return labels[detected_label_id]; - } - -private: - VideoOverlaySet m_overlay_set; - std::string model_path; - ImagePixelBox m_pixel_box_1080p; - ImageFloatBox m_float_box; - std::atomic m_detected; - - Ort::Env env; - Ort::RunOptions runOptions; - Ort::Session session; - - const char* labels[3]{"none", "three", "two"}; -}; - - -DudunsparceFormDetector::DudunsparceFormDetector(VideoOverlay& overlay) - : VisualInferenceCallback("DudunsparceFormDetector") - , m_overlay_set(overlay) - , model_path("../../PAMLExperiments/dudunsparce/dudunsparce_form_detector.onnx") - , m_detected(0) - , session(nullptr) -{ - // The input data for the ML model is created by cropping an 1080P frame from Switch - // The crop is at image[500:750, 1500:1750]. - m_pixel_box_1080p = ImagePixelBox(1500, 500, 1750, 750); - m_float_box = pixelbox_to_floatbox(1920, 1080, m_pixel_box_1080p); - - // learned from ONN Runtime example: https://github.com/cassiebreviu/cpp-onnxruntime-resnet-console-app/blob/main/OnnxRuntimeResNet/OnnxRuntimeResNet.cpp - session = Ort::Session(env, str_to_onnx_str(model_path).c_str(), Ort::SessionOptions{nullptr}); -} - -void DudunsparceFormDetector::make_overlays(VideoOverlaySet& items) const {} - -bool DudunsparceFormDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - m_overlay_set.clear(); - - ImageViewRGB32 cropped_frame = (frame.height() == 1080) ? extract_box_reference(frame, m_pixel_box_1080p) - : extract_box_reference(frame, m_float_box); - cv::Mat cropped_mat = cropped_frame.to_opencv_Mat(); - cv::Mat resized_mat; // resize to the shape for the ML model input - cv::resize(cropped_mat, resized_mat, cv::Size(25, 25)); - cv::Mat resized_mat_gray; - cv::cvtColor(resized_mat, resized_mat_gray, cv::COLOR_BGRA2GRAY); - - // cv::imwrite("./model_input.png", resized_mat_gray); - - cv::Mat float_mat; - resized_mat_gray.convertTo(float_mat, CV_32F, 1./255); - - // ML stuff: prepare ML model input and output - const std::array inputShape = {1, 25, 25}; - const std::array outputShape = {1, 3}; - - std::array modelInput; - std::array modelOutput; - auto memoryInfo = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU); - auto inputTensor = Ort::Value::CreateTensor(memoryInfo, modelInput.data(), modelInput.size(), inputShape.data(), inputShape.size()); - auto outputTensor = Ort::Value::CreateTensor(memoryInfo, modelOutput.data(), modelOutput.size(), outputShape.data(), outputShape.size()); - - for (int row = 0, p_loc=0; row < 25; row++){ - for(int col = 0; col < 25; col++){ - float p = float_mat.at(row, col); - modelInput[p_loc++] = p; - } - } - - Ort::AllocatorWithDefaultOptions ort_alloc; - Ort::AllocatedStringPtr inputName = session.GetInputNameAllocated(0, ort_alloc); - Ort::AllocatedStringPtr outputName = session.GetOutputNameAllocated(0, ort_alloc); - const std::array inputNames = {inputName.get()}; - const std::array outputNames = {outputName.get()}; - - session.Run(runOptions, inputNames.data(), &inputTensor, 1, outputNames.data(), &outputTensor, 1); - - float max_value = -std::numeric_limits::max(); - int max_value_label = 0; - for (int i = 0; i < 3; i++){ - // cout << labels[i] << ": " << modelOutput[i] << ", "; - if (modelOutput[i] > max_value){ - max_value = modelOutput[i]; - max_value_label = i; - } - } - cout << "Detector dudunsparce form: " << labels[max_value_label] << endl; - m_detected.store(max_value_label); - - return false; -} - - -TestDudunsparceFormDetector_Descriptor::TestDudunsparceFormDetector_Descriptor() - : SingleSwitchProgramDescriptor( - "NintendoSwitch:DudunsparceFormDetector", - "Nintendo Switch", "Test Dudunsparce Form Detector", - "", - "Test ML model on Dudunsparce form in SV box system", - FeedbackType::NONE, AllowCommandsWhenRunning::ENABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController} - ) -{} - -TestDudunsparceFormDetector::TestDudunsparceFormDetector(){} - - -void TestDudunsparceFormDetector::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - - DudunsparceFormDetector detector(env.console.overlay()); - - // ImageRGB32 test_image("../../datasets/Bidoof/images/test/im0005.png"); - // detector.process_frame(test_image, current_time()); - - // return; - // InferenceSession session( - // context, env.console, - // {{detector, std::chrono::milliseconds(100)}} - // ); - // context.wait_until_cancel(); - - std::string last_label = ""; - run_until( - env.console, context, [&](ProControllerContext& context){ - while (true){ - std::string cur_label = detector.get_label(); - if (cur_label != last_label){ - last_label = cur_label; - env.console.overlay().add_log("Detected " + last_label); - } - context.wait_for(std::chrono::milliseconds(100)); - } - }, - {detector}, - std::chrono::milliseconds(100) - ); - - - std::cout << "ML detection test program finished." << std::endl; -} - - -} -} +/* Test Dudunsparce Form Detector + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#include "3rdParty/ONNX/OnnxToolsPA.h" +#include "Common/Cpp/Time.h" +#include "ClientSource/Connection/BotBase.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/Async/InferenceSession.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "TestDudunsparceFormDetector.h" + +#include +#include + +#include + +#include +#include +#include +using std::cout, std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +class DudunsparceFormDetector : public VisualInferenceCallback{ +public: + DudunsparceFormDetector(VideoOverlay& overlay); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; + + std::string get_label() const { + int detected_label_id = m_detected.load(std::memory_order_acquire); + return labels[detected_label_id]; + } + +private: + VideoOverlaySet m_overlay_set; + std::string model_path; + ImagePixelBox m_pixel_box_1080p; + ImageFloatBox m_float_box; + std::atomic m_detected; + + Ort::Env env; + Ort::RunOptions runOptions; + Ort::Session session; + + const char* labels[3]{"none", "three", "two"}; +}; + + +DudunsparceFormDetector::DudunsparceFormDetector(VideoOverlay& overlay) + : VisualInferenceCallback("DudunsparceFormDetector") + , m_overlay_set(overlay) + , model_path("../../PAMLExperiments/dudunsparce/dudunsparce_form_detector.onnx") + , m_detected(0) + , session(nullptr) +{ + // The input data for the ML model is created by cropping an 1080P frame from Switch + // The crop is at image[500:750, 1500:1750]. + m_pixel_box_1080p = ImagePixelBox(1500, 500, 1750, 750); + m_float_box = pixelbox_to_floatbox(1920, 1080, m_pixel_box_1080p); + + // learned from ONN Runtime example: https://github.com/cassiebreviu/cpp-onnxruntime-resnet-console-app/blob/main/OnnxRuntimeResNet/OnnxRuntimeResNet.cpp + session = Ort::Session(env, str_to_onnx_str(model_path).c_str(), Ort::SessionOptions{nullptr}); +} + +void DudunsparceFormDetector::make_overlays(VideoOverlaySet& items) const {} + +bool DudunsparceFormDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + m_overlay_set.clear(); + + ImageViewRGB32 cropped_frame = (frame.height() == 1080) ? extract_box_reference(frame, m_pixel_box_1080p) + : extract_box_reference(frame, m_float_box); + cv::Mat cropped_mat = cropped_frame.to_opencv_Mat(); + cv::Mat resized_mat; // resize to the shape for the ML model input + cv::resize(cropped_mat, resized_mat, cv::Size(25, 25)); + cv::Mat resized_mat_gray; + cv::cvtColor(resized_mat, resized_mat_gray, cv::COLOR_BGRA2GRAY); + + // cv::imwrite("./model_input.png", resized_mat_gray); + + cv::Mat float_mat; + resized_mat_gray.convertTo(float_mat, CV_32F, 1./255); + + // ML stuff: prepare ML model input and output + const std::array inputShape = {1, 25, 25}; + const std::array outputShape = {1, 3}; + + std::array modelInput; + std::array modelOutput; + auto memoryInfo = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU); + auto inputTensor = Ort::Value::CreateTensor(memoryInfo, modelInput.data(), modelInput.size(), inputShape.data(), inputShape.size()); + auto outputTensor = Ort::Value::CreateTensor(memoryInfo, modelOutput.data(), modelOutput.size(), outputShape.data(), outputShape.size()); + + for (int row = 0, p_loc=0; row < 25; row++){ + for(int col = 0; col < 25; col++){ + float p = float_mat.at(row, col); + modelInput[p_loc++] = p; + } + } + + Ort::AllocatorWithDefaultOptions ort_alloc; + Ort::AllocatedStringPtr inputName = session.GetInputNameAllocated(0, ort_alloc); + Ort::AllocatedStringPtr outputName = session.GetOutputNameAllocated(0, ort_alloc); + const std::array inputNames = {inputName.get()}; + const std::array outputNames = {outputName.get()}; + + session.Run(runOptions, inputNames.data(), &inputTensor, 1, outputNames.data(), &outputTensor, 1); + + float max_value = -std::numeric_limits::max(); + int max_value_label = 0; + for (int i = 0; i < 3; i++){ + // cout << labels[i] << ": " << modelOutput[i] << ", "; + if (modelOutput[i] > max_value){ + max_value = modelOutput[i]; + max_value_label = i; + } + } + cout << "Detector dudunsparce form: " << labels[max_value_label] << endl; + m_detected.store(max_value_label); + + return false; +} + + +TestDudunsparceFormDetector_Descriptor::TestDudunsparceFormDetector_Descriptor() + : SingleSwitchProgramDescriptor( + "NintendoSwitch:DudunsparceFormDetector", + "Nintendo Switch", "Test Dudunsparce Form Detector", + "", + "Test ML model on Dudunsparce form in SV box system", + FeedbackType::NONE, AllowCommandsWhenRunning::ENABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController} + ) +{} + +TestDudunsparceFormDetector::TestDudunsparceFormDetector(){} + + +void TestDudunsparceFormDetector::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + + DudunsparceFormDetector detector(env.console.overlay()); + + // ImageRGB32 test_image("../../datasets/Bidoof/images/test/im0005.png"); + // detector.process_frame(test_image, current_time()); + + // return; + // InferenceSession session( + // context, env.console, + // {{detector, std::chrono::milliseconds(100)}} + // ); + // context.wait_until_cancel(); + + std::string last_label = ""; + run_until( + env.console, context, [&](ProControllerContext& context){ + while (true){ + std::string cur_label = detector.get_label(); + if (cur_label != last_label){ + last_label = cur_label; + env.console.overlay().add_log("Detected " + last_label); + } + context.wait_for(std::chrono::milliseconds(100)); + } + }, + {detector}, + std::chrono::milliseconds(100) + ); + + + std::cout << "ML detection test program finished." << std::endl; +} + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestDudunsparceFormDetector.h b/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestDudunsparceFormDetector.h index 6946b6be2a..edef834e82 100644 --- a/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestDudunsparceFormDetector.h +++ b/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestDudunsparceFormDetector.h @@ -1,36 +1,36 @@ -/* Test Dudunsparce Form Detector - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - - #ifndef PokemonAutomation_NintendoSwitch_TestDudunsparceFormDetector_H - #define PokemonAutomation_NintendoSwitch_TestDudunsparceFormDetector_H - - #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - - namespace PokemonAutomation{ - namespace NintendoSwitch{ - - - class TestDudunsparceFormDetector_Descriptor : public SingleSwitchProgramDescriptor{ - public: - TestDudunsparceFormDetector_Descriptor(); - }; - - - class TestDudunsparceFormDetector : public SingleSwitchProgramInstance{ - public: - TestDudunsparceFormDetector(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - private: - }; - - - - } - } - #endif // TESTPATHMAKER_H +/* Test Dudunsparce Form Detector + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + + #ifndef PokemonAutomation_NintendoSwitch_TestDudunsparceFormDetector_H + #define PokemonAutomation_NintendoSwitch_TestDudunsparceFormDetector_H + + #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + + namespace PokemonAutomation{ + namespace NintendoSwitch{ + + + class TestDudunsparceFormDetector_Descriptor : public SingleSwitchProgramDescriptor{ + public: + TestDudunsparceFormDetector_Descriptor(); + }; + + + class TestDudunsparceFormDetector : public SingleSwitchProgramInstance{ + public: + TestDudunsparceFormDetector(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + private: + }; + + + + } + } + #endif // TESTPATHMAKER_H \ No newline at end of file diff --git a/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramSwitch.cpp b/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramSwitch.cpp index 829723945e..398af312e8 100644 --- a/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramSwitch.cpp +++ b/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramSwitch.cpp @@ -133,6 +133,10 @@ #include "NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.h" #include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" #include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSV/Inference/Battles/PokemonSV_StartBattleYellowBar.h" +#include "PokemonLA/Inference/Map/PokemonLA_SelectedRegionDetector.h" +#include "PokemonHome/Inference/PokemonHome_BallReader.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSide.h" #include #include @@ -192,32 +196,6 @@ TestProgram::TestProgram() , IMAGE_PATH(false, "Path to image for testing", LockMode::UNLOCK_WHILE_RUNNING, "default.png", "default.png") , STATIC_TEXT("Test text...") // , PLAYER_LIST("Test Table", LockMode::UNLOCK_WHILE_RUNNING, "Notes") - , DATE0( - "Date", - LockMode::UNLOCK_WHILE_RUNNING, - DateTimeOption::DATE_HOUR_MIN, - DateTime{2000, 1, 1, 0, 0, 0}, - DateTime{2060, 12, 31, 23, 59, 59}, - DateTime{2024, 4, 12, 2, 16, 30} - ) - , DATE1( - "Date", - LockMode::UNLOCK_WHILE_RUNNING, - DateTimeOption::DATE_HOUR_MIN, - DateTime{2000, 1, 1, 0, 0, 0}, - DateTime{2060, 12, 31, 23, 59, 59}, - DateTime{2048, 1, 13, 20, 48} - ) - , DURATION( - "Duration", - LockMode::UNLOCK_WHILE_RUNNING, - "100" - ) - , COLOR( - LockMode::UNLOCK_WHILE_RUNNING, - false, - 0x000000, 0x000000 - ) , NOTIFICATION_TEST("Test", true, true, ImageAttachmentMode::JPG) , NOTIFICATIONS({ &NOTIFICATION_TEST, @@ -233,11 +211,6 @@ TestProgram::TestProgram() PA_ADD_OPTION(STATIC_TEXT); // PA_ADD_OPTION(PLAYER_LIST); // PA_ADD_OPTION(battle_AI); - PA_ADD_OPTION(DATE0); - PA_ADD_OPTION(DATE1); - PA_ADD_OPTION(DURATION); - PA_ADD_OPTION(COLOR); - PA_ADD_OPTION(CONTROLLER_TABLE); PA_ADD_OPTION(NOTIFICATIONS); BUTTON0.add_listener(*this); BUTTON1.add_listener(*this); @@ -262,10 +235,6 @@ void TestProgram::on_press(){ - - - - void TestProgram::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ using namespace Kernels; using namespace Kernels::Waterfill; @@ -285,19 +254,80 @@ void TestProgram::program(MultiSwitchProgramEnvironment& env, CancellableScope& ProControllerContext context(scope, console.pro_controller()); VideoOverlaySet overlays(overlay); + auto screenshot = feed.snapshot(); + + PokemonSwSh::MaxLairInternal::PathSelectDetector detector; + detector.detect(screenshot); +// int ret = PokemonSwSh::MaxLairInternal::read_side(screenshot); +// cout << "ret = " << ret << endl; -#if 1 + + +#if 0 + ImageRGB32 image("20250717-121112090631.png"); + + AdvanceDialogDetector detector; + detector.make_overlays(overlays); + cout << detector.detect(image) << endl; +#endif + +#if 0 + ImageRGB32 image(RESOURCE_PATH() + "PokemonHome/PokeballSprites.png"); + image = remove_white_border(image); + image.save("test.png"); +#endif + + +#if 0 + auto screenshot = feed.snapshot(); + + PokemonHome::BallReader reader(console); + + reader.read_ball(screenshot); +#endif + + + +// pbf_press_button(context, ); + + + + +// PokemonLA::detect_selected_region(console, scope); + + + + +#if 0 + auto screenshot = feed.snapshot(); + + + StartBattleYellowBarDetector detector(COLOR_RED); + cout << detector.detect(screenshot) << endl; +#endif + + + +// cout << "asdf" << endl; +// cout << (int)settings_detect_console_type(console, context) << endl; + + + +// DateReader_Switch2_US reader(COLOR_RED); +// reader.read_date(logger, screenshot); + +#if 0 HomeMenuDetector detector0(console); - StartGameUserSelectDetector detector1(console); - UpdatePopupDetector detector2(console); +// StartGameUserSelectDetector detector1(console); +// UpdatePopupDetector detector2(console); detector0.make_overlays(overlays); - detector1.make_overlays(overlays); - detector2.make_overlays(overlays); +// detector1.make_overlays(overlays); +// detector2.make_overlays(overlays); cout << detector0.detect(feed.snapshot()) << endl; - cout << detector1.detect(feed.snapshot()) << endl; - cout << detector2.detect(feed.snapshot()) << endl; +// cout << detector1.detect(feed.snapshot()) << endl; +// cout << detector2.detect(feed.snapshot()) << endl; #endif @@ -319,7 +349,7 @@ void TestProgram::program(MultiSwitchProgramEnvironment& env, CancellableScope& auto screenshot = feed.snapshot(); - BinarySliderDetector detector(COLOR_RED, {0.831784, 0.140496, 0.088290, 0.671074}); + BinarySliderDetector detector(COLOR_RED, {0.836431, 0.097521, 0.069703, 0.796694}); auto sliders = detector.detect(screenshot); for (auto& item : sliders){ diff --git a/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramSwitch.h b/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramSwitch.h index 530d975661..01e73ed009 100644 --- a/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramSwitch.h +++ b/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramSwitch.h @@ -73,15 +73,6 @@ class TestProgram : public MultiSwitchProgramInstance, public ButtonListener{ StaticTextOption STATIC_TEXT; -// PokemonSV::PlayerListTable PLAYER_LIST; - DateTimeOption DATE0; - DateTimeOption DATE1; -// ConsoleModelOption CONSOLE_MODEL; - - MillisecondsOption DURATION; - ColorCell COLOR; - ControllerSettingsTable CONTROLLER_TABLE; - // PokemonSV::SinglesAIOption battle_AI; diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramSession.cpp b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramSession.cpp index 4076518718..0b0b9d3932 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramSession.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramSession.cpp @@ -25,13 +25,11 @@ namespace NintendoSwitch{ void MultiSwitchProgramSession::add_listener(Listener& listener){ auto ScopeCheck = m_sanitizer.check_scope(); - WriteSpinLock lg(m_lock); - m_listeners.insert(&listener); + m_listeners.add(listener); } void MultiSwitchProgramSession::remove_listener(Listener& listener){ auto ScopeCheck = m_sanitizer.check_scope(); - WriteSpinLock lg(m_lock); - m_listeners.erase(&listener); + m_listeners.remove(listener); } @@ -100,7 +98,13 @@ void MultiSwitchProgramSession::run_program_instance(MultiSwitchProgramEnvironme ); } - m_scope.store(&scope, std::memory_order_release); + { + std::lock_guard lg(program_lock()); + if (current_state() != ProgramState::RUNNING){ + return; + } + m_scope.store(&scope, std::memory_order_release); + } try{ m_option.instance().program(env, scope); @@ -114,35 +118,32 @@ void MultiSwitchProgramSession::run_program_instance(MultiSwitchProgramEnvironme env.consoles[c].controller().cancel_all_commands(); }catch (...){} } + std::lock_guard lg(program_lock()); m_scope.store(nullptr, std::memory_order_release); throw; } + + std::lock_guard lg(program_lock()); m_scope.store(nullptr, std::memory_order_release); } void MultiSwitchProgramSession::internal_stop_program(){ auto ScopeCheck = m_sanitizer.check_scope(); - WriteSpinLock lg(m_lock); -// size_t consoles = m_system.count(); -// for (size_t c = 0; c < consoles; c++){ -// m_system[c].serial_session().stop(); -// } - CancellableScope* scope = m_scope.load(std::memory_order_acquire); - if (scope != nullptr){ - scope->cancel(std::make_exception_ptr(ProgramCancelledException())); + { + std::lock_guard lg(program_lock()); + CancellableScope* scope = m_scope.load(std::memory_order_acquire); + if (scope != nullptr){ + scope->cancel(std::make_exception_ptr(ProgramCancelledException())); + } } // Wait for program thread to finish. while (m_scope.load(std::memory_order_acquire) != nullptr){ pause(); } - -// for (size_t c = 0; c < consoles; c++){ -// m_system[c].serial_session().reset(); -// } } void MultiSwitchProgramSession::internal_run_program(){ auto ScopeCheck = m_sanitizer.check_scope(); - GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(); + GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(logger()); m_option.options().reset_state(); SleepSuppressScope sleep_scope(GlobalSettings::instance().SLEEP_SUPPRESS->PROGRAM_RUNNING); @@ -273,11 +274,8 @@ void MultiSwitchProgramSession::shutdown(){ } void MultiSwitchProgramSession::startup(size_t switch_count){ auto ScopeCheck = m_sanitizer.check_scope(); - WriteSpinLock lg(m_lock); m_option.instance().update_active_consoles(switch_count); - for (Listener* listener : m_listeners){ - listener->redraw_options(); - } + m_listeners.run_method_unique(&Listener::redraw_options); } diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramSession.h b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramSession.h index 0110c71a27..78328a8909 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramSession.h +++ b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramSession.h @@ -59,10 +59,9 @@ class MultiSwitchProgramSession final : public ProgramSession, private MultiSwit MultiSwitchProgramOption& m_option; MultiSwitchSystemSession m_system; - SpinLock m_lock; std::atomic m_scope; - std::set m_listeners; + ListenerSet m_listeners; LifetimeSanitizer m_sanitizer; }; diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramSession.cpp b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramSession.cpp index 2803426aee..bf55cfd90a 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramSession.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramSession.cpp @@ -79,7 +79,13 @@ void SingleSwitchProgramSession::run_program_instance(SingleSwitchProgramEnviron ); ControllerContext context(scope, env.console.controller()); - m_scope.store(&context, std::memory_order_release); + { + std::lock_guard lg(program_lock()); + if (current_state() != ProgramState::RUNNING){ + return; + } + m_scope.store(&context, std::memory_order_release); + } #ifdef PA_CATCH_PROGRAM_SYSTEM_EXCEPTIONS try{ @@ -94,18 +100,21 @@ void SingleSwitchProgramSession::run_program_instance(SingleSwitchProgramEnviron } #else { - m_option.instance().program(env, scope); - env.console.controller().wait_for_all(&scope); + m_option.instance().program(env, context); + context.wait_for_all_requests(); } #endif + + std::lock_guard lg(program_lock()); m_scope.store(nullptr, std::memory_order_release); } void SingleSwitchProgramSession::internal_stop_program(){ - WriteSpinLock lg(m_lock); - - CancellableScope* scope = m_scope.load(std::memory_order_acquire); - if (scope != nullptr){ - scope->cancel(std::make_exception_ptr(ProgramCancelledException())); + { + std::lock_guard lg(program_lock()); + CancellableScope* scope = m_scope.load(std::memory_order_acquire); + if (scope != nullptr){ + scope->cancel(std::make_exception_ptr(ProgramCancelledException())); + } } // Wait for program thread to finish. @@ -114,7 +123,7 @@ void SingleSwitchProgramSession::internal_stop_program(){ } } void SingleSwitchProgramSession::internal_run_program(){ - GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(); + GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(logger()); m_option.options().reset_state(); if (!m_system.controller_session().ready()){ diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramSession.h b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramSession.h index 4545b0026b..0a6b58cb3b 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramSession.h +++ b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramSession.h @@ -15,7 +15,6 @@ #ifndef PokemonAutomation_NintendoSwitch_SingleSwitchProgramSession_H #define PokemonAutomation_NintendoSwitch_SingleSwitchProgramSession_H -#include "Common/Cpp/Concurrency/SpinLock.h" #include "CommonFramework/ProgramSession.h" #include "NintendoSwitch_SwitchSystemSession.h" #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" @@ -50,7 +49,6 @@ class SingleSwitchProgramSession final : public ProgramSession{ SingleSwitchProgramOption& m_option; SwitchSystemSession m_system; - SpinLock m_lock; std::atomic m_scope; }; diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_CommandRow.cpp b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_CommandRow.cpp index 91b1f769bc..cdf2e4966d 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_CommandRow.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_CommandRow.cpp @@ -74,10 +74,11 @@ CommandRow::CommandRow( m_overlay_text->setChecked(session.enabled_text()); row->addWidget(m_overlay_text); - m_overlay_images = new QCheckBox("Masks", this); - m_overlay_images->setChecked(session.enabled_images()); - row->addWidget(m_overlay_images); - + if (PreloadSettings::instance().DEVELOPER_MODE){ + m_overlay_images = new QCheckBox("Masks", this); + m_overlay_images->setChecked(session.enabled_images()); + row->addWidget(m_overlay_images); + } m_overlay_log = new QCheckBox("Log", this); m_overlay_log->setChecked(session.enabled_log()); @@ -131,10 +132,12 @@ CommandRow::CommandRow( m_overlay_text, &QCheckBox::checkStateChanged, this, [this](Qt::CheckState state){ m_session.set_enabled_text(state == Qt::Checked); } ); - connect( - m_overlay_images, &QCheckBox::checkStateChanged, - this, [this](Qt::CheckState state){ m_session.set_enabled_images(state == Qt::Checked); } - ); + if (PreloadSettings::instance().DEVELOPER_MODE){ + connect( + m_overlay_images, &QCheckBox::checkStateChanged, + this, [this](Qt::CheckState state){ m_session.set_enabled_images(state == Qt::Checked); } + ); + } connect( m_overlay_log, &QCheckBox::checkStateChanged, this, [this](Qt::CheckState state){ m_session.set_enabled_log(state == Qt::Checked); } diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchProgramWidget.cpp b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchProgramWidget.cpp index 65ccd44767..1c0b17dad0 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchProgramWidget.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchProgramWidget.cpp @@ -65,6 +65,15 @@ MultiSwitchProgramWidget2::MultiSwitchProgramWidget2( ); layout->addWidget(header); + if (descriptor.deprecated()){ + QMessageBox box; + box.warning( + nullptr, + "Deprecation Notice", + "This program is deprecated and no longer maintained. Please consider using a newer alternative." + ); + } + { QScrollArea* scroll_outer = new QScrollArea(this); diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_SingleSwitchProgramWidget.cpp b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_SingleSwitchProgramWidget.cpp index 4cca7d04c2..e1691ef301 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_SingleSwitchProgramWidget.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_SingleSwitchProgramWidget.cpp @@ -57,6 +57,15 @@ SingleSwitchProgramWidget2::SingleSwitchProgramWidget2( ); layout->addWidget(header); + if (descriptor.deprecated()){ + QMessageBox box; + box.warning( + nullptr, + "Deprecation Notice", + "This program is deprecated and no longer maintained. Please consider using a newer alternative." + ); + } + { QScrollArea* scroll_outer = new QScrollArea(this); diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget.h b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget.h index 0216c143c0..80439d8d88 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget.h +++ b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget.h @@ -30,6 +30,7 @@ namespace PokemonAutomation{ class VideoSourceSelectorWidget; class VideoDisplayWidget; class AudioDisplayWidget; + class AudioSelectorWidget; class VideoOverlay; namespace NintendoSwitch{ diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.cpp b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.cpp index 5e5ad212f3..eafcdcbbdf 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.cpp @@ -1,89 +1,113 @@ -/* Binary Slider Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/ImageMatch/ExactImageMatcher.h" -#include "NintendoSwitch2_BinarySliderDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -BinarySliderDetector::BinarySliderDetector(Color color, const ImageFloatBox& box) - : m_color(color) - , m_box(box) -{} -void BinarySliderDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} - -std::vector> BinarySliderDetector::detect(const ImageViewRGB32& image) const{ - using namespace Kernels::Waterfill; - - static ImageMatch::ExactImageMatcher LIGHT_OFF_CURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Light-Off-Cursor.png"); - static ImageMatch::ExactImageMatcher LIGHT_OFF_NOCURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Light-Off-NoCursor.png"); - static ImageMatch::ExactImageMatcher LIGHT_ON_CURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Light-On-Cursor.png"); - static ImageMatch::ExactImageMatcher LIGHT_ON_NOCURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Light-On-NoCursor.png"); - static ImageMatch::ExactImageMatcher DARK_OFF_CURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Dark-Off-Cursor.png"); - static ImageMatch::ExactImageMatcher DARK_OFF_NOCURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Dark-Off-NoCursor.png"); - static ImageMatch::ExactImageMatcher DARK_ON_CURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Dark-On-Cursor.png"); - static ImageMatch::ExactImageMatcher DARK_ON_NOCURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Dark-On-NoCursor.png"); - - ImageViewRGB32 region = extract_box_reference(image, m_box); - - auto matrix = compress_rgb32_to_binary_range(region, 0xffc0c0c0, 0xffffffff); - auto session = make_WaterfillSession(matrix); - auto iter = session->make_iterator(200); - WaterfillObject object; - - std::vector> ret; - - while (iter->find_next(object, false)){ - double aspect_ratio = object.aspect_ratio(); - if (aspect_ratio < 0.9 || aspect_ratio > 1.1){ - continue; - } - ImageViewRGB32 cropped = extract_box_reference(region, object); - - double best_off_rmsd = 9999; - best_off_rmsd = std::min(best_off_rmsd, LIGHT_OFF_CURSOR.rmsd(cropped)); - best_off_rmsd = std::min(best_off_rmsd, LIGHT_OFF_NOCURSOR.rmsd(cropped)); - best_off_rmsd = std::min(best_off_rmsd, DARK_OFF_CURSOR.rmsd(cropped)); - best_off_rmsd = std::min(best_off_rmsd, DARK_OFF_NOCURSOR.rmsd(cropped)); - - double best_on_rmsd = 9999; - best_on_rmsd = std::min(best_on_rmsd, LIGHT_ON_CURSOR.rmsd(cropped)); - best_on_rmsd = std::min(best_on_rmsd, LIGHT_ON_NOCURSOR.rmsd(cropped)); - best_on_rmsd = std::min(best_on_rmsd, DARK_ON_CURSOR.rmsd(cropped)); - best_on_rmsd = std::min(best_on_rmsd, DARK_ON_NOCURSOR.rmsd(cropped)); - -// cout << "best_off_rmsd = " << best_off_rmsd << endl; -// cout << "best_on_rmsd = " << best_on_rmsd << endl; - - bool on = best_on_rmsd < best_off_rmsd; - double best = on ? best_on_rmsd : best_off_rmsd; - - if (best < 60){ - ret.emplace_back(on, object); - } - - } - - return ret; -} - - - -} -} +/* Binary Slider Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/ImageMatch/ExactImageMatcher.h" +#include "NintendoSwitch2_BinarySliderDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +BinarySliderDetector::BinarySliderDetector(Color color, const ImageFloatBox& box) + : m_color(color) + , m_box(box) +{} +void BinarySliderDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} + +std::vector> BinarySliderDetector::detect(const ImageViewRGB32& image) const{ + using namespace Kernels::Waterfill; + + static ImageMatch::ExactImageMatcher LIGHT_OFF_CURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Light-Off-Cursor.png"); + static ImageMatch::ExactImageMatcher LIGHT_OFF_NOCURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Light-Off-NoCursor.png"); + static ImageMatch::ExactImageMatcher LIGHT_ON_CURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Light-On-Cursor.png"); + static ImageMatch::ExactImageMatcher LIGHT_ON_NOCURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Light-On-NoCursor.png"); + static ImageMatch::ExactImageMatcher DARK_OFF_CURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Dark-Off-Cursor.png"); + static ImageMatch::ExactImageMatcher DARK_OFF_NOCURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Dark-Off-NoCursor.png"); + static ImageMatch::ExactImageMatcher DARK_ON_CURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Dark-On-Cursor.png"); + static ImageMatch::ExactImageMatcher DARK_ON_NOCURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Dark-On-NoCursor.png"); + + ImageViewRGB32 region = extract_box_reference(image, m_box); + + std::vector matrices = compress_rgb32_to_binary_range( + region, + { + {0xffc0c0c0, 0xffffffff}, + {0xffd0d0d0, 0xffffffff}, + {0xffe0e0e0, 0xffffffff}, + {0xfff0f0f0, 0xffffffff}, + } + ); + + auto session = make_WaterfillSession(); + + std::vector> best; + + for (PackedBinaryMatrix& matrix : matrices){ +// cout << "-----------------" << endl; + session->set_source(matrix); + auto iter = session->make_iterator(200); + WaterfillObject object; + + std::vector> sliders; + + while (iter->find_next(object, false)){ + double aspect_ratio = object.aspect_ratio(); + if (aspect_ratio < 0.9 || aspect_ratio > 1.1){ + continue; + } + ImageViewRGB32 cropped = extract_box_reference(region, object); + + double best_off_rmsd = 9999; + best_off_rmsd = std::min(best_off_rmsd, LIGHT_OFF_CURSOR.rmsd(cropped)); + best_off_rmsd = std::min(best_off_rmsd, LIGHT_OFF_NOCURSOR.rmsd(cropped)); + best_off_rmsd = std::min(best_off_rmsd, DARK_OFF_CURSOR.rmsd(cropped)); + best_off_rmsd = std::min(best_off_rmsd, DARK_OFF_NOCURSOR.rmsd(cropped)); + + double best_on_rmsd = 9999; + best_on_rmsd = std::min(best_on_rmsd, LIGHT_ON_CURSOR.rmsd(cropped)); + best_on_rmsd = std::min(best_on_rmsd, LIGHT_ON_NOCURSOR.rmsd(cropped)); + best_on_rmsd = std::min(best_on_rmsd, DARK_ON_CURSOR.rmsd(cropped)); + best_on_rmsd = std::min(best_on_rmsd, DARK_ON_NOCURSOR.rmsd(cropped)); + + // cout << "best_off_rmsd = " << best_off_rmsd << endl; + // cout << "best_on_rmsd = " << best_on_rmsd << endl; + + bool on = best_on_rmsd < best_off_rmsd; + double best_rmsd = on ? best_on_rmsd : best_off_rmsd; + + if (best_rmsd < 60){ + sliders.emplace_back(on, object); + } + +// for (auto& item : sliders){ +// cout << item.first << " : " << item.second.max_y << endl; +// } + + } + + if (best.size() < sliders.size()){ + best = std::move(sliders); + } + } + + return best; +} + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.h b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.h index 561022ed62..0c45c26087 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.h +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.h @@ -1,37 +1,37 @@ -/* Binary Slider Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch2_BinarySliderDetector_H -#define PokemonAutomation_NintendoSwitch2_BinarySliderDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - -class BinarySliderDetector{ -public: - BinarySliderDetector(Color color, const ImageFloatBox& box); - void make_overlays(VideoOverlaySet& items) const; - - std::vector> detect(const ImageViewRGB32& image) const; - -private: - Color m_color; - ImageFloatBox m_box; -}; - - - - -} -} -#endif +/* Binary Slider Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch2_BinarySliderDetector_H +#define PokemonAutomation_NintendoSwitch2_BinarySliderDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + +class BinarySliderDetector{ +public: + BinarySliderDetector(Color color, const ImageFloatBox& box); + void make_overlays(VideoOverlaySet& items) const; + + std::vector> detect(const ImageViewRGB32& image) const; + +private: + Color m_color; + ImageFloatBox m_box; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.cpp b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.cpp index 127ff5256e..87a8398d3e 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.cpp @@ -1,90 +1,90 @@ -/* Console Type Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "NintendoSwitch_ConsoleTypeDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -ConsoleTypeDetector_Home::ConsoleTypeDetector_Home(ConsoleHandle& console, Color color) - : m_console(console) - , m_color(color) - , m_bottom_line(0.10, 0.88, 0.80, 0.03) - , m_last(ConsoleType::Unknown) -{} -void ConsoleTypeDetector_Home::make_overlays(VideoOverlaySet& items) const{ - ConsoleType known_state = m_console.state().console_type(); - if (known_state != ConsoleType::Unknown){ - return; - } - items.add(m_color, m_bottom_line); -} -ConsoleType ConsoleTypeDetector_Home::detect_only(const ImageViewRGB32& screen){ - if (m_console.state().console_type_confirmed()){ - ConsoleType state = m_console.state().console_type(); - m_last = state; - return state; - } - - ImageStats stats = image_stats(extract_box_reference(screen, m_bottom_line)); -// cout << "ConsoleTypeDetector: " << stats.stddev.sum() << endl; - ConsoleType state; - if (stats.stddev.sum() < 10){ - state = ConsoleType::Switch2_Unknown; - }else{ - state = ConsoleType::Switch1; - } - m_last = state; - return state; -} -void ConsoleTypeDetector_Home::commit_to_cache(){ - if (m_last != ConsoleType::Unknown){ - m_console.state().set_console_type(m_console, m_last); - } -} - - - -ConsoleTypeDetector_StartGameUserSelect::ConsoleTypeDetector_StartGameUserSelect(ConsoleHandle& console, Color color) - : m_console(console) - , m_color(color) - , m_bottom_line(0.02, 0.53, 0.96, 0.03) -{} -void ConsoleTypeDetector_StartGameUserSelect::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_bottom_line); -} -ConsoleType ConsoleTypeDetector_StartGameUserSelect::detect_only(const ImageViewRGB32& screen){ - if (m_console.state().console_type_confirmed()){ - return m_console.state().console_type(); - } - - ImageStats stats = image_stats(extract_box_reference(screen, m_bottom_line)); -// cout << "ConsoleTypeDetector: " << stats.stddev.sum() << endl; - ConsoleType state; - if (stats.stddev.sum() < 10){ - state = ConsoleType::Switch2_Unknown; - }else{ - state = ConsoleType::Switch1; - } - m_last = state; - return state; -} -void ConsoleTypeDetector_StartGameUserSelect::commit_to_cache(){ - m_console.state().set_console_type(m_console, m_last); -} - - - - -} -} +/* Console Type Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "NintendoSwitch_ConsoleTypeDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +ConsoleTypeDetector_Home::ConsoleTypeDetector_Home(ConsoleHandle& console, Color color) + : m_console(console) + , m_color(color) + , m_bottom_line(0.10, 0.88, 0.80, 0.03) + , m_last(ConsoleType::Unknown) +{} +void ConsoleTypeDetector_Home::make_overlays(VideoOverlaySet& items) const{ + ConsoleType known_state = m_console.state().console_type(); + if (known_state != ConsoleType::Unknown){ + return; + } + items.add(m_color, m_bottom_line); +} +ConsoleType ConsoleTypeDetector_Home::detect_only(const ImageViewRGB32& screen){ + if (m_console.state().console_type_confirmed()){ + ConsoleType state = m_console.state().console_type(); + m_last = state; + return state; + } + + ImageStats stats = image_stats(extract_box_reference(screen, m_bottom_line)); +// cout << "ConsoleTypeDetector: " << stats.stddev.sum() << endl; + ConsoleType state; + if (stats.stddev.sum() < 10){ + state = ConsoleType::Switch2_Unknown; + }else{ + state = ConsoleType::Switch1; + } + m_last = state; + return state; +} +void ConsoleTypeDetector_Home::commit_to_cache(){ + if (m_last != ConsoleType::Unknown){ + m_console.state().set_console_type(m_console, m_last); + } +} + + + +ConsoleTypeDetector_StartGameUserSelect::ConsoleTypeDetector_StartGameUserSelect(ConsoleHandle& console, Color color) + : m_console(console) + , m_color(color) + , m_bottom_line(0.02, 0.53, 0.96, 0.03) +{} +void ConsoleTypeDetector_StartGameUserSelect::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_bottom_line); +} +ConsoleType ConsoleTypeDetector_StartGameUserSelect::detect_only(const ImageViewRGB32& screen){ + if (m_console.state().console_type_confirmed()){ + return m_console.state().console_type(); + } + + ImageStats stats = image_stats(extract_box_reference(screen, m_bottom_line)); +// cout << "ConsoleTypeDetector: " << stats.stddev.sum() << endl; + ConsoleType state; + if (stats.stddev.sum() < 10){ + state = ConsoleType::Switch2_Unknown; + }else{ + state = ConsoleType::Switch1; + } + m_last = state; + return state; +} +void ConsoleTypeDetector_StartGameUserSelect::commit_to_cache(){ + m_console.state().set_console_type(m_console, m_last); +} + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.h b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.h index 2b9dad8356..47d34fc5e5 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.h +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.h @@ -1,58 +1,58 @@ -/* Console Type Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_ConsoleTypeDetector_H -#define PokemonAutomation_NintendoSwitch_ConsoleTypeDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - -class ConsoleTypeDetector_Home{ -public: - ConsoleTypeDetector_Home(ConsoleHandle& console, Color color = COLOR_RED); - - void make_overlays(VideoOverlaySet& items) const; - ConsoleType detect_only(const ImageViewRGB32& screen); - void commit_to_cache(); - -private: - ConsoleHandle& m_console; - Color m_color; - ImageFloatBox m_bottom_line; - ConsoleType m_last; -}; - -class ConsoleTypeDetector_StartGameUserSelect{ -public: - ConsoleTypeDetector_StartGameUserSelect(ConsoleHandle& console, Color color = COLOR_RED); - - void make_overlays(VideoOverlaySet& items) const; - ConsoleType detect_only(const ImageViewRGB32& screen); - void commit_to_cache(); - -private: - ConsoleHandle& m_console; - Color m_color; - ImageFloatBox m_bottom_line; - ConsoleType m_last; -}; - - - - - -} -} -#endif +/* Console Type Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_ConsoleTypeDetector_H +#define PokemonAutomation_NintendoSwitch_ConsoleTypeDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + +class ConsoleTypeDetector_Home{ +public: + ConsoleTypeDetector_Home(ConsoleHandle& console, Color color = COLOR_RED); + + void make_overlays(VideoOverlaySet& items) const; + ConsoleType detect_only(const ImageViewRGB32& screen); + void commit_to_cache(); + +private: + ConsoleHandle& m_console; + Color m_color; + ImageFloatBox m_bottom_line; + ConsoleType m_last; +}; + +class ConsoleTypeDetector_StartGameUserSelect{ +public: + ConsoleTypeDetector_StartGameUserSelect(ConsoleHandle& console, Color color = COLOR_RED); + + void make_overlays(VideoOverlaySet& items) const; + ConsoleType detect_only(const ImageViewRGB32& screen); + void commit_to_cache(); + +private: + ConsoleHandle& m_console; + Color m_color; + ImageFloatBox m_bottom_line; + ConsoleType m_last; +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.cpp b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.cpp index 9c14ba016f..d2436234b1 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.cpp @@ -1,173 +1,173 @@ -/* Date Change Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "NintendoSwitch_DateChangeDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - -DateChangeDetector_Switch1::DateChangeDetector_Switch1(Color color) - : m_color(color) - , m_background_top(0.50, 0.02, 0.45, 0.08) - , m_window_top(0.50, 0.36, 0.45, 0.07) - , m_window_text(0.05, 0.36, 0.10, 0.07) - , m_jp_year(0.136, 0.61, 0.11, 0.09) - , m_us_hour(0.473, 0.61, 0.06, 0.09) - , m_jp_month_arrow(0.30, 0.50, 0.05, 0.06) -{} -void DateChangeDetector_Switch1::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_background_top); - items.add(m_color, m_window_top); - items.add(m_color, m_window_text); - items.add(m_color, m_jp_year); - items.add(m_color, m_us_hour); - items.add(m_color, m_jp_month_arrow); -} -bool DateChangeDetector_Switch1::detect(const ImageViewRGB32& screen){ - ImageStats stats_background_top = image_stats(extract_box_reference(screen, m_background_top)); - if (stats_background_top.stddev.sum() > 10){ -// cout << "asdf" << endl; - return false; - } - ImageStats stats_window_top = image_stats(extract_box_reference(screen, m_window_top)); -// cout << stats_window_top.average << stats_window_top.stddev << endl; - if (stats_window_top.stddev.sum() > 10){ -// cout << "qwer" << endl; - return false; - } - ImageStats stats_window_text = image_stats(extract_box_reference(screen, m_window_text)); -// cout << stats_window_text.stddev << endl; - if (stats_window_text.stddev.sum() < 100){ -// cout << "zxcv" << endl; - return false; - } -// cout << "stats_background_top: " << stats_background_top.average.sum() << endl; -// cout << "stats_window_top: " << stats_window_top.average.sum() << endl; - if (std::abs(stats_background_top.average.sum() - stats_window_top.average.sum()) < 50){ -// cout << "xcvb" << endl; - return false; - } - -// bool white_theme = stats_window_top.average.sum() > 600; - - ImageViewRGB32 year_box = extract_box_reference(screen, m_jp_year); - ImageStats year_stats = image_stats(year_box); -// cout << year_stats.average << year_stats.stddev << endl; - - double stddev = year_stats.stddev.sum(); - if (stddev < 80){ -// cout << "sdfg" << endl; - return false; - } - - return true; -} -DateFormat DateChangeDetector_Switch1::detect_date_format(const ImageViewRGB32& screen) const{ - ImageViewRGB32 us_hours = extract_box_reference(screen, m_us_hour); - ImageStats stats_us_hours = image_stats(us_hours); - - if (stats_us_hours.stddev.sum() > 30){ - return DateFormat::US; - } - - ImageViewRGB32 jp_arrow = extract_box_reference(screen, m_jp_month_arrow); - ImageStats stats_arrow = image_stats(jp_arrow); - if (stats_arrow.stddev.sum() > 30){ - return DateFormat::JP; - } - - return DateFormat::EU; -} - - - -DateChangeDetector_Switch2::DateChangeDetector_Switch2(Color color) - : m_color(color) - , m_background_top(0.50, 0.02, 0.45, 0.08) - , m_window_bottom(0.50, 0.80, 0.45, 0.07) - , m_window_text(0.05, 0.02, 0.10, 0.08) - , m_jp_year(0.139, 0.436, 0.088, 0.095) - , m_us_hour(0.473, 0.61, 0.06, 0.09) - , m_jp_month_arrow(0.291705, 0.331675, 0.054986, 0.069652) -{} -void DateChangeDetector_Switch2::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_background_top); - items.add(m_color, m_window_bottom); - items.add(m_color, m_window_text); - items.add(m_color, m_jp_year); - items.add(m_color, m_us_hour); - items.add(m_color, m_jp_month_arrow); -} -bool DateChangeDetector_Switch2::detect(const ImageViewRGB32& screen){ - ImageStats stats_background_top = image_stats(extract_box_reference(screen, m_background_top)); - if (stats_background_top.stddev.sum() > 10){ -// cout << "asdf" << endl; - return false; - } - ImageStats stats_window_bottom = image_stats(extract_box_reference(screen, m_window_bottom)); -// cout << stats_window_bottom.average << stats_window_top.stddev << endl; - if (stats_window_bottom.stddev.sum() > 10){ -// cout << "qwer" << endl; - return false; - } - ImageStats stats_window_text = image_stats(extract_box_reference(screen, m_window_text)); -// cout << stats_window_text.stddev << endl; - if (stats_window_text.stddev.sum() < 100){ -// cout << "zxcv" << endl; - return false; - } -// cout << "stats_background_top: " << stats_background_top.average.sum() << endl; -// cout << "stats_window_top: " << stats_window_top.average.sum() << endl; - - if (euclidean_distance(stats_background_top.average, stats_window_bottom.average) > 10){ -// cout << "xcvb" << endl; - return false; - } - -// bool white_theme = stats_window_top.average.sum() > 600; - - ImageViewRGB32 year_box = extract_box_reference(screen, m_jp_year); - ImageStats year_stats = image_stats(year_box); -// cout << year_stats.average << year_stats.stddev << endl; - - double stddev = year_stats.stddev.sum(); - if (stddev < 80){ -// cout << "sdfg" << endl; - return false; - } - - return true; -} -DateFormat DateChangeDetector_Switch2::detect_date_format(const ImageViewRGB32& screen) const{ - ImageViewRGB32 us_hours = extract_box_reference(screen, m_us_hour); - ImageStats stats_us_hours = image_stats(us_hours); - - if (stats_us_hours.stddev.sum() > 30){ - return DateFormat::US; - } - - ImageViewRGB32 jp_arrow = extract_box_reference(screen, m_jp_month_arrow); - ImageStats stats_arrow = image_stats(jp_arrow); - if (stats_arrow.stddev.sum() > 30){ - return DateFormat::JP; - } - - return DateFormat::EU; -} - - - - - - - -} -} +/* Date Change Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "NintendoSwitch_DateChangeDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + +DateChangeDetector_Switch1::DateChangeDetector_Switch1(Color color) + : m_color(color) + , m_background_top(0.50, 0.02, 0.45, 0.08) + , m_window_top(0.50, 0.36, 0.45, 0.07) + , m_window_text(0.05, 0.36, 0.10, 0.07) + , m_jp_year(0.136, 0.61, 0.11, 0.09) + , m_us_hour(0.473, 0.61, 0.06, 0.09) + , m_jp_month_arrow(0.30, 0.50, 0.05, 0.06) +{} +void DateChangeDetector_Switch1::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_background_top); + items.add(m_color, m_window_top); + items.add(m_color, m_window_text); + items.add(m_color, m_jp_year); + items.add(m_color, m_us_hour); + items.add(m_color, m_jp_month_arrow); +} +bool DateChangeDetector_Switch1::detect(const ImageViewRGB32& screen){ + ImageStats stats_background_top = image_stats(extract_box_reference(screen, m_background_top)); + if (stats_background_top.stddev.sum() > 10){ +// cout << "asdf" << endl; + return false; + } + ImageStats stats_window_top = image_stats(extract_box_reference(screen, m_window_top)); +// cout << stats_window_top.average << stats_window_top.stddev << endl; + if (stats_window_top.stddev.sum() > 10){ +// cout << "qwer" << endl; + return false; + } + ImageStats stats_window_text = image_stats(extract_box_reference(screen, m_window_text)); +// cout << stats_window_text.stddev << endl; + if (stats_window_text.stddev.sum() < 100){ +// cout << "zxcv" << endl; + return false; + } +// cout << "stats_background_top: " << stats_background_top.average.sum() << endl; +// cout << "stats_window_top: " << stats_window_top.average.sum() << endl; + if (std::abs(stats_background_top.average.sum() - stats_window_top.average.sum()) < 50){ +// cout << "xcvb" << endl; + return false; + } + +// bool white_theme = stats_window_top.average.sum() > 600; + + ImageViewRGB32 year_box = extract_box_reference(screen, m_jp_year); + ImageStats year_stats = image_stats(year_box); +// cout << year_stats.average << year_stats.stddev << endl; + + double stddev = year_stats.stddev.sum(); + if (stddev < 80){ +// cout << "sdfg" << endl; + return false; + } + + return true; +} +DateFormat DateChangeDetector_Switch1::detect_date_format(const ImageViewRGB32& screen) const{ + ImageViewRGB32 us_hours = extract_box_reference(screen, m_us_hour); + ImageStats stats_us_hours = image_stats(us_hours); + + if (stats_us_hours.stddev.sum() > 30){ + return DateFormat::US; + } + + ImageViewRGB32 jp_arrow = extract_box_reference(screen, m_jp_month_arrow); + ImageStats stats_arrow = image_stats(jp_arrow); + if (stats_arrow.stddev.sum() > 30){ + return DateFormat::JP; + } + + return DateFormat::EU; +} + + + +DateChangeDetector_Switch2::DateChangeDetector_Switch2(Color color) + : m_color(color) + , m_background_top(0.50, 0.02, 0.45, 0.08) + , m_window_bottom(0.50, 0.80, 0.45, 0.07) + , m_window_text(0.05, 0.02, 0.10, 0.08) + , m_jp_year(0.139, 0.436, 0.088, 0.095) + , m_us_hour(0.473, 0.61, 0.06, 0.09) + , m_jp_month_arrow(0.291705, 0.331675, 0.054986, 0.069652) +{} +void DateChangeDetector_Switch2::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_background_top); + items.add(m_color, m_window_bottom); + items.add(m_color, m_window_text); + items.add(m_color, m_jp_year); + items.add(m_color, m_us_hour); + items.add(m_color, m_jp_month_arrow); +} +bool DateChangeDetector_Switch2::detect(const ImageViewRGB32& screen){ + ImageStats stats_background_top = image_stats(extract_box_reference(screen, m_background_top)); + if (stats_background_top.stddev.sum() > 10){ +// cout << "asdf" << endl; + return false; + } + ImageStats stats_window_bottom = image_stats(extract_box_reference(screen, m_window_bottom)); +// cout << stats_window_bottom.average << stats_window_top.stddev << endl; + if (stats_window_bottom.stddev.sum() > 10){ +// cout << "qwer" << endl; + return false; + } + ImageStats stats_window_text = image_stats(extract_box_reference(screen, m_window_text)); +// cout << stats_window_text.stddev << endl; + if (stats_window_text.stddev.sum() < 100){ +// cout << "zxcv" << endl; + return false; + } +// cout << "stats_background_top: " << stats_background_top.average.sum() << endl; +// cout << "stats_window_top: " << stats_window_top.average.sum() << endl; + + if (euclidean_distance(stats_background_top.average, stats_window_bottom.average) > 10){ +// cout << "xcvb" << endl; + return false; + } + +// bool white_theme = stats_window_top.average.sum() > 600; + + ImageViewRGB32 year_box = extract_box_reference(screen, m_jp_year); + ImageStats year_stats = image_stats(year_box); +// cout << year_stats.average << year_stats.stddev << endl; + + double stddev = year_stats.stddev.sum(); + if (stddev < 80){ +// cout << "sdfg" << endl; + return false; + } + + return true; +} +DateFormat DateChangeDetector_Switch2::detect_date_format(const ImageViewRGB32& screen) const{ + ImageViewRGB32 us_hours = extract_box_reference(screen, m_us_hour); + ImageStats stats_us_hours = image_stats(us_hours); + + if (stats_us_hours.stddev.sum() > 30){ + return DateFormat::US; + } + + ImageViewRGB32 jp_arrow = extract_box_reference(screen, m_jp_month_arrow); + ImageStats stats_arrow = image_stats(jp_arrow); + if (stats_arrow.stddev.sum() > 30){ + return DateFormat::JP; + } + + return DateFormat::EU; +} + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.h b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.h index 7515de0658..4336f25bb6 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.h +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.h @@ -1,71 +1,71 @@ -/* Date Change Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_DateChangeDetector_H -#define PokemonAutomation_NintendoSwitch_DateChangeDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -enum class DateFormat{ - US, - EU, - JP, -}; - - - - -class DateChangeDetector : public StaticScreenDetector{ -public: - virtual DateFormat detect_date_format(const ImageViewRGB32& screen) const = 0; -}; -class DateChangeDetector_Switch1 : public DateChangeDetector{ -public: - DateChangeDetector_Switch1(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - virtual DateFormat detect_date_format(const ImageViewRGB32& screen) const override; - -private: - Color m_color; - ImageFloatBox m_background_top; - ImageFloatBox m_window_top; - ImageFloatBox m_window_text; - ImageFloatBox m_jp_year; - ImageFloatBox m_us_hour; - ImageFloatBox m_jp_month_arrow; -}; -class DateChangeDetector_Switch2 : public DateChangeDetector{ -public: - DateChangeDetector_Switch2(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - virtual DateFormat detect_date_format(const ImageViewRGB32& screen) const override; - -private: - Color m_color; - ImageFloatBox m_background_top; - ImageFloatBox m_window_bottom; - ImageFloatBox m_window_text; - ImageFloatBox m_jp_year; - ImageFloatBox m_us_hour; - ImageFloatBox m_jp_month_arrow; -}; - - - - -} -} -#endif +/* Date Change Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_DateChangeDetector_H +#define PokemonAutomation_NintendoSwitch_DateChangeDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +enum class DateFormat{ + US, + EU, + JP, +}; + + + + +class DateChangeDetector : public StaticScreenDetector{ +public: + virtual DateFormat detect_date_format(const ImageViewRGB32& screen) const = 0; +}; +class DateChangeDetector_Switch1 : public DateChangeDetector{ +public: + DateChangeDetector_Switch1(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + virtual DateFormat detect_date_format(const ImageViewRGB32& screen) const override; + +private: + Color m_color; + ImageFloatBox m_background_top; + ImageFloatBox m_window_top; + ImageFloatBox m_window_text; + ImageFloatBox m_jp_year; + ImageFloatBox m_us_hour; + ImageFloatBox m_jp_month_arrow; +}; +class DateChangeDetector_Switch2 : public DateChangeDetector{ +public: + DateChangeDetector_Switch2(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + virtual DateFormat detect_date_format(const ImageViewRGB32& screen) const override; + +private: + Color m_color; + ImageFloatBox m_background_top; + ImageFloatBox m_window_bottom; + ImageFloatBox m_window_text; + ImageFloatBox m_jp_year; + ImageFloatBox m_us_hour; + ImageFloatBox m_jp_month_arrow; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.cpp b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.cpp index e794fdd6cb..d278ba28c7 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.cpp @@ -1,141 +1,160 @@ -/* Home Menu Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "NintendoSwitch_HomeMenuDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - -HomeMenuDetector::HomeMenuDetector(ConsoleHandle& console, Color color) - : m_color(color) - , m_console_type(console, color) - , m_top(0.510223, 0.019835, 0.441450, 0.034711) - , m_bottom_row(0.10, 0.92, 0.10, 0.05) - , m_bottom_icons(0.70, 0.92, 0.28, 0.05) - , m_bottom_left(0.02, 0.70, 0.15, 0.15) - , m_bottom_right(0.83, 0.70, 0.15, 0.15) - , m_user_icons(0.05, 0.05, 0.2, 0.08) - , m_game_slot(0.08, 0.25, 0.10, 0.38) -{} -void HomeMenuDetector::make_overlays(VideoOverlaySet& items) const{ - m_console_type.make_overlays(items); - items.add(m_color, m_top); - items.add(m_color, m_bottom_row); - items.add(m_color, m_bottom_icons); - items.add(m_color, m_bottom_left); - items.add(m_color, m_bottom_right); - items.add(m_color, m_user_icons); - items.add(m_color, m_game_slot); -} - -// -// This miraculously works on both Switch 1 and Switch 2. -// -bool HomeMenuDetector::detect(const ImageViewRGB32& screen){ - if (detect_only(screen)){ - m_console_type.commit_to_cache(); - return true; - }else{ - return false; - } -} -bool HomeMenuDetector::detect_only(const ImageViewRGB32& screen){ - ImageStats stats_bottom_row = image_stats(extract_box_reference(screen, m_bottom_row)); -// cout << stats_bottom_row.average << stats_bottom_row.stddev << endl; - bool white; -// cout << "stats_bottom_row.average.sum() = " << stats_bottom_row.average.sum() << endl; - if (stats_bottom_row.average.sum() < 200){ - white = false; - }else if (stats_bottom_row.average.sum() > 500){ - white = true; - }else{ - return false; - } - -// cout << "white: " << white << endl; - - ImageStats stats_top = image_stats(extract_box_reference(screen, m_top)); -// cout << stats_top.average << stats_top.stddev << endl; - if (stats_top.stddev.sum() > 20){ - return false; - } - - ImageStats stats_bottom_icons = image_stats(extract_box_reference(screen, m_bottom_icons)); -// cout << stats_bottom_icons.average << stats_bottom_icons.stddev << endl; - if (stats_bottom_icons.stddev.sum() < 50){ - return false; - } - - ImageStats stats_bottom_left = image_stats(extract_box_reference(screen, m_bottom_left)); - ImageStats stats_bottom_right = image_stats(extract_box_reference(screen, m_bottom_right)); -// cout << stats_bottom_left.average << stats_bottom_left.stddev << endl; -// cout << stats_bottom_right.average << stats_bottom_right.stddev << endl; - if (white){ - if (!is_white(stats_bottom_left) || !is_white(stats_bottom_right)){ -// cout << "asdf" << endl; - return false; - } - }else{ - if (!is_grey(stats_bottom_left, 0, 200) || !is_grey(stats_bottom_right, 0, 200)){ -// cout << "qwer" << endl; - return false; - } - } - -// cout << euclidean_distance(stats_bottom_row.average, stats_bottom_left.average) << endl; - if (euclidean_distance(stats_bottom_row.average, stats_bottom_left.average) > 20){ -// cout << "qwer = " << euclidean_distance(stats_bottom_row.average, stats_bottom_left.average) << endl; - return false; - } -// cout << euclidean_distance(stats_bottom_row.average, stats_bottom_right.average) << endl; - if (euclidean_distance(stats_bottom_row.average, stats_bottom_right.average) > 20){ -// cout << "asdf" << endl; - return false; - } -// cout << euclidean_distance(stats_bottom_left.average, stats_bottom_left.average) << endl; - if (euclidean_distance(stats_bottom_left.average, stats_bottom_right.average) > 20){ -// cout << "zxcv" << endl; - return false; - } -// cout << euclidean_distance(stats_top.average, stats_bottom_left.average) << endl; - if (euclidean_distance(stats_top.average, stats_bottom_left.average) > 20){ -// cout << "xcvb" << endl; - return false; - } - - ImageStats stats_user_icons = image_stats(extract_box_reference(screen, m_user_icons)); -// cout << stats_user_icons.stddev << endl; - if (stats_user_icons.stddev.sum() < 40){ - return false; - } - ImageStats stats_game_slot = image_stats(extract_box_reference(screen, m_game_slot)); -// cout << stats_game_slot.stddev << endl; - if (stats_game_slot.stddev.sum() < 50){ - return false; - } - - // Read the console type only when we have confirmed the home menu. - m_console_type.detect_only(screen); - - return true; -} - - - - - - -} -} +/* Home Menu Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "NintendoSwitch_HomeMenuDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + +HomeMenuDetector::HomeMenuDetector(ConsoleHandle& console, Color color) + : m_color(color) + , m_console_type(console, color) + , m_top(0.510223, 0.019835, 0.441450, 0.034711) + , m_bottom_row(0.10, 0.92, 0.10, 0.05) + , m_bottom_icons(0.70, 0.92, 0.28, 0.05) + , m_bottom_left(0.02, 0.70, 0.15, 0.15) + , m_bottom_right(0.83, 0.70, 0.15, 0.15) + , m_bottom_middle(0.20, 0.70, 0.60, 0.15) + , m_user_icons(0.05, 0.05, 0.2, 0.08) + , m_game_slot(0.08, 0.25, 0.10, 0.38) +{} +void HomeMenuDetector::make_overlays(VideoOverlaySet& items) const{ + m_console_type.make_overlays(items); + items.add(m_color, m_top); + items.add(m_color, m_bottom_row); + items.add(m_color, m_bottom_icons); + items.add(m_color, m_bottom_left); + items.add(m_color, m_bottom_right); + items.add(m_color, m_bottom_middle); + items.add(m_color, m_user_icons); + items.add(m_color, m_game_slot); +} + +// +// This miraculously works on both Switch 1 and Switch 2. +// +bool HomeMenuDetector::detect(const ImageViewRGB32& screen){ + return detect_only(screen); + +#if 0 + if (!detect_only(screen)){ + return false; + } + try{ + m_console_type.commit_to_cache(); + }catch (UserSetupError&){ + screen.save("HomeMenuDetector-Failure.png"); + throw; + } + return true; +#endif +} +void HomeMenuDetector::commit_state(){ + m_console_type.commit_to_cache(); +} + +bool HomeMenuDetector::detect_only(const ImageViewRGB32& screen){ + ImageStats stats_bottom_row = image_stats(extract_box_reference(screen, m_bottom_row)); +// cout << stats_bottom_row.average << stats_bottom_row.stddev << endl; + bool white; +// cout << "stats_bottom_row.average.sum() = " << stats_bottom_row.average.sum() << endl; + if (stats_bottom_row.average.sum() < 200){ + white = false; + }else if (stats_bottom_row.average.sum() > 500){ + white = true; + }else{ + return false; + } + +// cout << "white: " << white << endl; + + ImageStats stats_top = image_stats(extract_box_reference(screen, m_top)); +// cout << stats_top.average << stats_top.stddev << endl; + if (stats_top.stddev.sum() > 20){ + return false; + } + + ImageStats stats_bottom_icons = image_stats(extract_box_reference(screen, m_bottom_icons)); +// cout << stats_bottom_icons.average << stats_bottom_icons.stddev << endl; + if (stats_bottom_icons.stddev.sum() < 50){ + return false; + } + + ImageStats stats_bottom_left = image_stats(extract_box_reference(screen, m_bottom_left)); + ImageStats stats_bottom_right = image_stats(extract_box_reference(screen, m_bottom_right)); +// cout << stats_bottom_left.average << stats_bottom_left.stddev << endl; +// cout << stats_bottom_right.average << stats_bottom_right.stddev << endl; + if (white){ + if (!is_white(stats_bottom_left) || !is_white(stats_bottom_right)){ +// cout << "asdf" << endl; + return false; + } + }else{ + if (!is_grey(stats_bottom_left, 0, 200) || !is_grey(stats_bottom_right, 0, 200)){ +// cout << "qwer" << endl; + return false; + } + } + + ImageStats stats_bottom_middle = image_stats(extract_box_reference(screen, m_bottom_middle)); + if (stats_bottom_middle.stddev.sum() < 50){ + return false; + } + +// cout << euclidean_distance(stats_bottom_row.average, stats_bottom_left.average) << endl; + if (euclidean_distance(stats_bottom_row.average, stats_bottom_left.average) > 20){ +// cout << "qwer = " << euclidean_distance(stats_bottom_row.average, stats_bottom_left.average) << endl; + return false; + } +// cout << euclidean_distance(stats_bottom_row.average, stats_bottom_right.average) << endl; + if (euclidean_distance(stats_bottom_row.average, stats_bottom_right.average) > 20){ +// cout << "asdf" << endl; + return false; + } +// cout << euclidean_distance(stats_bottom_left.average, stats_bottom_left.average) << endl; + if (euclidean_distance(stats_bottom_left.average, stats_bottom_right.average) > 20){ +// cout << "zxcv" << endl; + return false; + } +// cout << euclidean_distance(stats_top.average, stats_bottom_left.average) << endl; + if (euclidean_distance(stats_top.average, stats_bottom_left.average) > 20){ +// cout << "xcvb" << endl; + return false; + } + + ImageStats stats_user_icons = image_stats(extract_box_reference(screen, m_user_icons)); +// cout << stats_user_icons.stddev << endl; + if (stats_user_icons.stddev.sum() < 40){ + return false; + } + ImageStats stats_game_slot = image_stats(extract_box_reference(screen, m_game_slot)); +// cout << stats_game_slot.stddev << endl; + if (stats_game_slot.stddev.sum() < 50){ + return false; + } + + // Read the console type only when we have confirmed the home menu. + m_console_type.detect_only(screen); + + return true; +} + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h index 85285b42b0..eac23c265c 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h @@ -1,55 +1,57 @@ -/* Home Menu Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_HomeMenuDetector_H -#define PokemonAutomation_NintendoSwitch_HomeMenuDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "NintendoSwitch_ConsoleTypeDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -class HomeMenuDetector : public StaticScreenDetector{ -public: - HomeMenuDetector(ConsoleHandle& console, Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - bool detect_only(const ImageViewRGB32& screen); - -private: - Color m_color; - ConsoleTypeDetector_Home m_console_type; - ImageFloatBox m_top; - ImageFloatBox m_bottom_row; - ImageFloatBox m_bottom_icons; - ImageFloatBox m_bottom_left; - ImageFloatBox m_bottom_right; - ImageFloatBox m_user_icons; - ImageFloatBox m_game_slot; -}; -class HomeMenuWatcher : public DetectorToFinder{ -public: - HomeMenuWatcher( - ConsoleHandle& console, - std::chrono::milliseconds hold_duration = std::chrono::milliseconds(250) - ) - : DetectorToFinder("HomeMenuWatcher", hold_duration, console) - {} -}; - - - - -} -} -#endif +/* Home Menu Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_HomeMenuDetector_H +#define PokemonAutomation_NintendoSwitch_HomeMenuDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "NintendoSwitch_ConsoleTypeDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +class HomeMenuDetector : public StaticScreenDetector{ +public: + HomeMenuDetector(ConsoleHandle& console, Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + virtual void commit_state() override; + bool detect_only(const ImageViewRGB32& screen); + +private: + Color m_color; + ConsoleTypeDetector_Home m_console_type; + ImageFloatBox m_top; + ImageFloatBox m_bottom_row; + ImageFloatBox m_bottom_icons; + ImageFloatBox m_bottom_left; + ImageFloatBox m_bottom_right; + ImageFloatBox m_bottom_middle; + ImageFloatBox m_user_icons; + ImageFloatBox m_game_slot; +}; +class HomeMenuWatcher : public DetectorToFinder{ +public: + HomeMenuWatcher( + ConsoleHandle& console, + std::chrono::milliseconds hold_duration = std::chrono::milliseconds(250) + ) + : DetectorToFinder("HomeMenuWatcher", hold_duration, console) + {} +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.cpp b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.cpp index 47ed10181c..43c8c15e93 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.cpp @@ -1,79 +1,79 @@ -/* Detect Home - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "NintendoSwitch_SelectedSettingDetector.h" - -// -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -SelectedSettingWatcher::~SelectedSettingWatcher() = default; - -SelectedSettingWatcher::SelectedSettingWatcher( - ImageFloatBox selected_box, - ImageFloatBox not_selected_box1, - ImageFloatBox not_selected_box2 -) - : VisualInferenceCallback("SelectedSettingWatcher") - , m_selected_box(selected_box) - , m_not_selected_box1(not_selected_box1) - , m_not_selected_box2(not_selected_box2) -{} - -void SelectedSettingWatcher::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_selected_box); - items.add(COLOR_BLUE, m_not_selected_box1); - items.add(COLOR_BLUE, m_not_selected_box2); -} - -bool is_white_theme(const ImageViewRGB32& screen){ - ImageFloatBox window_top(0.60, 0.02, 0.35, 0.05); - ImageStats stats_window_top = image_stats(extract_box_reference(screen, window_top)); - bool white_theme = stats_window_top.average.sum() > 500; - return white_theme; -} - -bool SelectedSettingWatcher::process_frame(const ImageViewRGB32& screen, WallClock timestamp){ - - ImageStats stats_unselected_box1 = image_stats(extract_box_reference(screen, m_not_selected_box1)); - double unselected1_average_sum = stats_unselected_box1.average.sum(); -// cout << "unselected_average_sum1: " << std::to_string(unselected1_average_sum) << endl; - - ImageStats stats_unselected_box2 = image_stats(extract_box_reference(screen, m_not_selected_box2)); - double unselected2_average_sum = stats_unselected_box2.average.sum(); -// cout << "unselected_average_sum2: " << std::to_string(unselected2_average_sum) << endl; - - double average_sum_unselected_diff = std::abs(unselected1_average_sum - unselected2_average_sum); - - ImageStats stats_selected_box = image_stats(extract_box_reference(screen, m_selected_box)); - double selected_average_sum = stats_selected_box.average.sum(); -// cout << "selected_average_sum: " << std::to_string(selected_average_sum) << endl; - - bool is_selected = false; - if (is_white_theme(screen)){ // light mode - // unselected should be brighter than selected - is_selected = selected_average_sum < std::min(unselected1_average_sum, unselected2_average_sum) - average_sum_unselected_diff - 20 ; - }else{ // dark mode - // selected should be brighter than unselected - is_selected = selected_average_sum > std::max(unselected1_average_sum, unselected2_average_sum) + average_sum_unselected_diff + 20; - } - - return is_selected; -} - - - - - - -} -} +/* Detect Home + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "NintendoSwitch_SelectedSettingDetector.h" + +// +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +SelectedSettingWatcher::~SelectedSettingWatcher() = default; + +SelectedSettingWatcher::SelectedSettingWatcher( + ImageFloatBox selected_box, + ImageFloatBox not_selected_box1, + ImageFloatBox not_selected_box2 +) + : VisualInferenceCallback("SelectedSettingWatcher") + , m_selected_box(selected_box) + , m_not_selected_box1(not_selected_box1) + , m_not_selected_box2(not_selected_box2) +{} + +void SelectedSettingWatcher::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_selected_box); + items.add(COLOR_BLUE, m_not_selected_box1); + items.add(COLOR_BLUE, m_not_selected_box2); +} + +bool is_white_theme(const ImageViewRGB32& screen){ + ImageFloatBox window_top(0.60, 0.02, 0.35, 0.05); + ImageStats stats_window_top = image_stats(extract_box_reference(screen, window_top)); + bool white_theme = stats_window_top.average.sum() > 500; + return white_theme; +} + +bool SelectedSettingWatcher::process_frame(const ImageViewRGB32& screen, WallClock timestamp){ + + ImageStats stats_unselected_box1 = image_stats(extract_box_reference(screen, m_not_selected_box1)); + double unselected1_average_sum = stats_unselected_box1.average.sum(); +// cout << "unselected_average_sum1: " << std::to_string(unselected1_average_sum) << endl; + + ImageStats stats_unselected_box2 = image_stats(extract_box_reference(screen, m_not_selected_box2)); + double unselected2_average_sum = stats_unselected_box2.average.sum(); +// cout << "unselected_average_sum2: " << std::to_string(unselected2_average_sum) << endl; + + double average_sum_unselected_diff = std::abs(unselected1_average_sum - unselected2_average_sum); + + ImageStats stats_selected_box = image_stats(extract_box_reference(screen, m_selected_box)); + double selected_average_sum = stats_selected_box.average.sum(); +// cout << "selected_average_sum: " << std::to_string(selected_average_sum) << endl; + + bool is_selected = false; + if (is_white_theme(screen)){ // light mode + // unselected should be brighter than selected + is_selected = selected_average_sum < std::min(unselected1_average_sum, unselected2_average_sum) - average_sum_unselected_diff - 20 ; + }else{ // dark mode + // selected should be brighter than unselected + is_selected = selected_average_sum > std::max(unselected1_average_sum, unselected2_average_sum) + average_sum_unselected_diff + 20; + } + + return is_selected; +} + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.h b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.h index 0134638273..5d3858ed84 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.h +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.h @@ -1,47 +1,47 @@ -/* Selected Setting Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_SelectedSettingDetector_H -#define PokemonAutomation_NintendoSwitch_SelectedSettingDetector_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class SelectedSettingWatcher : public VisualInferenceCallback{ -public: - SelectedSettingWatcher( - ImageFloatBox selected_box, - ImageFloatBox not_selected_box1, - ImageFloatBox not_selected_box2 - ); - virtual ~SelectedSettingWatcher(); - - virtual void make_overlays(VideoOverlaySet& items) const override; - - // return true if the area within the selected_box is highlighted, compared with the area within unselected_box - // This compares the brightness of the selected_box with the unselected_box. - // selected_box: the box where we expect the screen should be highlighted - // not_selected_box 1 and 2: the boxes where we expect the screen should NOT be highlighted. These acts as the control, for comparison. - // the average sum of selected_box should be greater than the absolute difference of average sum between unselected_box 1 and 2. - virtual bool process_frame(const ImageViewRGB32& screen, WallClock timestamp) override; - - -protected: - ImageFloatBox m_selected_box; - ImageFloatBox m_not_selected_box1; - ImageFloatBox m_not_selected_box2; -}; - - -} -} -#endif - +/* Selected Setting Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SelectedSettingDetector_H +#define PokemonAutomation_NintendoSwitch_SelectedSettingDetector_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class SelectedSettingWatcher : public VisualInferenceCallback{ +public: + SelectedSettingWatcher( + ImageFloatBox selected_box, + ImageFloatBox not_selected_box1, + ImageFloatBox not_selected_box2 + ); + virtual ~SelectedSettingWatcher(); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + // return true if the area within the selected_box is highlighted, compared with the area within unselected_box + // This compares the brightness of the selected_box with the unselected_box. + // selected_box: the box where we expect the screen should be highlighted + // not_selected_box 1 and 2: the boxes where we expect the screen should NOT be highlighted. These acts as the control, for comparison. + // the average sum of selected_box should be greater than the absolute difference of average sum between unselected_box 1 and 2. + virtual bool process_frame(const ImageViewRGB32& screen, WallClock timestamp) override; + + +protected: + ImageFloatBox m_selected_box; + ImageFloatBox m_not_selected_box1; + ImageFloatBox m_not_selected_box2; +}; + + +} +} +#endif + diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.cpp b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.cpp index 9f8a1718d6..c54db25f48 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.cpp @@ -1,208 +1,214 @@ -/* Start Game User-Select Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "NintendoSwitch_StartGameUserSelectDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - -StartGameUserSelectDetector::StartGameUserSelectDetector(ConsoleHandle& console, Color color) - : m_console(console) - , m_type_detector(console, color) - , m_switch1(color) - , m_switch2(color) -{} -void StartGameUserSelectDetector::make_overlays(VideoOverlaySet& items) const{ - m_type_detector.make_overlays(items); - m_switch1.make_overlays(items); - m_switch2.make_overlays(items); -} -bool StartGameUserSelectDetector::detect(const ImageViewRGB32& screen){ - if (detect_only(screen)){ - m_console.state().set_console_type(m_console, m_console_type); - return true; - }else{ - return false; - } -} -bool StartGameUserSelectDetector::detect_only(const ImageViewRGB32& screen){ - ConsoleType type = m_type_detector.detect_only(screen); - m_console_type = type; - - if (type == ConsoleType::Unknown){ - return false; - } - if (is_switch1(type)){ - return m_switch1.detect(screen); - } - if (is_switch2(type)){ - return m_switch2.detect(screen); - } - - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Invalid ConsoleType: " + std::to_string((int)type) - ); -} - - - - - - - - -StartGameUserSelectDetector_Switch1::StartGameUserSelectDetector_Switch1(Color color) - : m_color(color) - , m_bottom_row(0.10, 0.92, 0.10, 0.05) - , m_bottom_icons(0.70, 0.92, 0.28, 0.05) - , m_top_row(0.50, 0.47, 0.45, 0.05) - , m_mid_row(0.10, 0.55, 0.80, 0.02) - , m_user_slot(0.45, 0.55, 0.10, 0.35) -{} -void StartGameUserSelectDetector_Switch1::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_bottom_row); - items.add(m_color, m_bottom_icons); - items.add(m_color, m_top_row); - items.add(m_color, m_mid_row); - items.add(m_color, m_user_slot); -} -bool StartGameUserSelectDetector_Switch1::detect(const ImageViewRGB32& screen){ - ImageStats stats_bottom_row = image_stats(extract_box_reference(screen, m_bottom_row)); -// cout << stats_bottom_row.average << stats_bottom_row.stddev << endl; - if (stats_bottom_row.stddev.sum() > 10){ - return false; - } - bool white; - if (is_grey(stats_bottom_row, 50, 300)){ - white = false; - }else if (stats_bottom_row.average.sum() > 500){ - white = true; - }else{ - return false; - } - - ImageStats stats_bottom_icons = image_stats(extract_box_reference(screen, m_bottom_icons)); -// cout << stats_bottom_icons.average << stats_bottom_icons.stddev << endl; - if (stats_bottom_icons.stddev.sum() < 50){ - return false; - } - - ImageStats stats_top_row = image_stats(extract_box_reference(screen, m_top_row)); - ImageStats stats_mid_row = image_stats(extract_box_reference(screen, m_mid_row)); -// cout << stats_top_row.average << stats_top_row.stddev << endl; - if (stats_top_row.stddev.sum() > 10 || stats_mid_row.stddev.sum() > 10){ - return false; - } - if (white){ - if (!is_white(stats_top_row) || !is_white(stats_mid_row)){ - return false; - } - }else{ - if (!is_grey(stats_top_row, 50, 300) || !is_grey(stats_mid_row, 50, 300)){ - return false; - } - } - - if (euclidean_distance(stats_bottom_row.average, stats_top_row.average) > 20){ - return false; - } - - ImageStats stats_user_slot = image_stats(extract_box_reference(screen, m_user_slot)); -// cout << stats_user_slot.average << stats_user_slot.stddev << endl; - if (stats_user_slot.stddev.sum() < 50){ - return false; - } - - return true; -} - - -StartGameUserSelectDetector_Switch2::StartGameUserSelectDetector_Switch2(Color color) - : m_color(color) - , m_bottom_row(0.10, 0.92, 0.10, 0.05) - , m_bottom_icons(0.70, 0.92, 0.28, 0.05) - , m_top_row(0.50, 0.45, 0.45, 0.05) - , m_mid_row(0.10, 0.53, 0.80, 0.02) - , m_user_slot(0.45, 0.55, 0.10, 0.30) -{} -void StartGameUserSelectDetector_Switch2::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_bottom_row); - items.add(m_color, m_bottom_icons); - items.add(m_color, m_top_row); - items.add(m_color, m_mid_row); - items.add(m_color, m_user_slot); -} -bool StartGameUserSelectDetector_Switch2::detect(const ImageViewRGB32& screen){ - ImageStats stats_bottom_row = image_stats(extract_box_reference(screen, m_bottom_row)); -// cout << stats_bottom_row.average << stats_bottom_row.stddev << endl; - if (stats_bottom_row.stddev.sum() > 10){ - return false; - } - bool white; - if (is_grey(stats_bottom_row, 0, 300)){ - white = false; - }else if (stats_bottom_row.average.sum() > 500){ - white = true; - }else{ - return false; - } - - ImageStats stats_bottom_icons = image_stats(extract_box_reference(screen, m_bottom_icons)); -// cout << stats_bottom_icons.average << stats_bottom_icons.stddev << endl; - if (stats_bottom_icons.stddev.sum() < 50){ - return false; - } - - ImageStats stats_top_row = image_stats(extract_box_reference(screen, m_top_row)); - ImageStats stats_mid_row = image_stats(extract_box_reference(screen, m_mid_row)); -// cout << stats_top_row.average << stats_top_row.stddev << endl; - if (stats_top_row.stddev.sum() > 10 || stats_mid_row.stddev.sum() > 10){ - return false; - } - if (white){ - if (!is_white(stats_top_row) || !is_white(stats_mid_row)){ - return false; - } - }else{ - if (!is_grey(stats_top_row, 0, 300) || !is_grey(stats_mid_row, 0, 300)){ - return false; - } - } - - if (euclidean_distance(stats_bottom_row.average, stats_top_row.average) > 20){ - return false; - } - - ImageStats stats_user_slot = image_stats(extract_box_reference(screen, m_user_slot)); -// cout << stats_user_slot.average << stats_user_slot.stddev << endl; - if (stats_user_slot.stddev.sum() < 50){ - return false; - } - - return true; -} - - - - - - - - - -} -} +/* Start Game User-Select Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "NintendoSwitch_StartGameUserSelectDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + +StartGameUserSelectDetector::StartGameUserSelectDetector(ConsoleHandle& console, Color color) + : m_console(console) + , m_type_detector(console, color) + , m_switch1(color) + , m_switch2(color) +{} +void StartGameUserSelectDetector::make_overlays(VideoOverlaySet& items) const{ + m_type_detector.make_overlays(items); + m_switch1.make_overlays(items); + m_switch2.make_overlays(items); +} +bool StartGameUserSelectDetector::detect(const ImageViewRGB32& screen){ + return detect_only(screen); +#if 0 + if (detect_only(screen)){ + m_console.state().set_console_type(m_console, m_console_type); + return true; + }else{ + return false; + } +#endif +} +void StartGameUserSelectDetector::commit_state(){ + m_console.state().set_console_type(m_console, m_console_type); +} +bool StartGameUserSelectDetector::detect_only(const ImageViewRGB32& screen){ + ConsoleType type = m_type_detector.detect_only(screen); + m_console_type = type; + + if (type == ConsoleType::Unknown){ + return false; + } + if (is_switch1(type)){ + return m_switch1.detect(screen); + } + if (is_switch2(type)){ + return m_switch2.detect(screen); + } + + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Invalid ConsoleType: " + std::to_string((int)type) + ); +} + + + + + + + + +StartGameUserSelectDetector_Switch1::StartGameUserSelectDetector_Switch1(Color color) + : m_color(color) + , m_bottom_row(0.10, 0.92, 0.10, 0.05) + , m_bottom_icons(0.70, 0.92, 0.28, 0.05) + , m_top_row(0.50, 0.47, 0.45, 0.05) + , m_mid_row(0.10, 0.55, 0.80, 0.02) + , m_user_slot(0.45, 0.55, 0.10, 0.35) +{} +void StartGameUserSelectDetector_Switch1::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_bottom_row); + items.add(m_color, m_bottom_icons); + items.add(m_color, m_top_row); + items.add(m_color, m_mid_row); + items.add(m_color, m_user_slot); +} +bool StartGameUserSelectDetector_Switch1::detect(const ImageViewRGB32& screen){ + ImageStats stats_bottom_row = image_stats(extract_box_reference(screen, m_bottom_row)); +// cout << stats_bottom_row.average << stats_bottom_row.stddev << endl; + if (stats_bottom_row.stddev.sum() > 10){ + return false; + } + bool white; + if (is_grey(stats_bottom_row, 50, 300)){ + white = false; + }else if (stats_bottom_row.average.sum() > 500){ + white = true; + }else{ + return false; + } + + ImageStats stats_bottom_icons = image_stats(extract_box_reference(screen, m_bottom_icons)); +// cout << stats_bottom_icons.average << stats_bottom_icons.stddev << endl; + if (stats_bottom_icons.stddev.sum() < 50){ + return false; + } + + ImageStats stats_top_row = image_stats(extract_box_reference(screen, m_top_row)); + ImageStats stats_mid_row = image_stats(extract_box_reference(screen, m_mid_row)); +// cout << stats_top_row.average << stats_top_row.stddev << endl; + if (stats_top_row.stddev.sum() > 10 || stats_mid_row.stddev.sum() > 10){ + return false; + } + if (white){ + if (!is_white(stats_top_row) || !is_white(stats_mid_row)){ + return false; + } + }else{ + if (!is_grey(stats_top_row, 50, 300) || !is_grey(stats_mid_row, 50, 300)){ + return false; + } + } + + if (euclidean_distance(stats_bottom_row.average, stats_top_row.average) > 20){ + return false; + } + + ImageStats stats_user_slot = image_stats(extract_box_reference(screen, m_user_slot)); +// cout << stats_user_slot.average << stats_user_slot.stddev << endl; + if (stats_user_slot.stddev.sum() < 50){ + return false; + } + + return true; +} + + +StartGameUserSelectDetector_Switch2::StartGameUserSelectDetector_Switch2(Color color) + : m_color(color) + , m_bottom_row(0.10, 0.92, 0.10, 0.05) + , m_bottom_icons(0.70, 0.92, 0.28, 0.05) + , m_top_row(0.50, 0.45, 0.45, 0.05) + , m_mid_row(0.10, 0.53, 0.80, 0.02) + , m_user_slot(0.45, 0.55, 0.10, 0.30) +{} +void StartGameUserSelectDetector_Switch2::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_bottom_row); + items.add(m_color, m_bottom_icons); + items.add(m_color, m_top_row); + items.add(m_color, m_mid_row); + items.add(m_color, m_user_slot); +} +bool StartGameUserSelectDetector_Switch2::detect(const ImageViewRGB32& screen){ + ImageStats stats_bottom_row = image_stats(extract_box_reference(screen, m_bottom_row)); +// cout << stats_bottom_row.average << stats_bottom_row.stddev << endl; + if (stats_bottom_row.stddev.sum() > 10){ + return false; + } + bool white; + if (is_grey(stats_bottom_row, 0, 300)){ + white = false; + }else if (stats_bottom_row.average.sum() > 500){ + white = true; + }else{ + return false; + } + + ImageStats stats_bottom_icons = image_stats(extract_box_reference(screen, m_bottom_icons)); +// cout << stats_bottom_icons.average << stats_bottom_icons.stddev << endl; + if (stats_bottom_icons.stddev.sum() < 50){ + return false; + } + + ImageStats stats_top_row = image_stats(extract_box_reference(screen, m_top_row)); + ImageStats stats_mid_row = image_stats(extract_box_reference(screen, m_mid_row)); +// cout << stats_top_row.average << stats_top_row.stddev << endl; + if (stats_top_row.stddev.sum() > 10 || stats_mid_row.stddev.sum() > 10){ + return false; + } + if (white){ + if (!is_white(stats_top_row) || !is_white(stats_mid_row)){ + return false; + } + }else{ + if (!is_grey(stats_top_row, 0, 300) || !is_grey(stats_mid_row, 0, 300)){ + return false; + } + } + + if (euclidean_distance(stats_bottom_row.average, stats_top_row.average) > 20){ + return false; + } + + ImageStats stats_user_slot = image_stats(extract_box_reference(screen, m_user_slot)); +// cout << stats_user_slot.average << stats_user_slot.stddev << endl; + if (stats_user_slot.stddev.sum() < 50){ + return false; + } + + return true; +} + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.h b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.h index 8519893cdf..71d02f0e96 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.h +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.h @@ -1,87 +1,88 @@ -/* Start Game User-Select Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_StartGameUserSelectDetector_H -#define PokemonAutomation_NintendoSwitch_StartGameUserSelectDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "NintendoSwitch_ConsoleTypeDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - -class StartGameUserSelectDetector_Switch1 : public StaticScreenDetector{ -public: - StartGameUserSelectDetector_Switch1(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_bottom_row; - ImageFloatBox m_bottom_icons; - ImageFloatBox m_top_row; - ImageFloatBox m_mid_row; - ImageFloatBox m_user_slot; -}; -class StartGameUserSelectDetector_Switch2 : public StaticScreenDetector{ -public: - StartGameUserSelectDetector_Switch2(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_bottom_row; - ImageFloatBox m_bottom_icons; - ImageFloatBox m_top_row; - ImageFloatBox m_mid_row; - ImageFloatBox m_user_slot; -}; - - - - - -class StartGameUserSelectDetector : public StaticScreenDetector{ -public: - StartGameUserSelectDetector(ConsoleHandle& console, Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - bool detect_only(const ImageViewRGB32& screen); - -private: - ConsoleHandle& m_console; - ConsoleTypeDetector_StartGameUserSelect m_type_detector; - StartGameUserSelectDetector_Switch1 m_switch1; - StartGameUserSelectDetector_Switch2 m_switch2; - - ConsoleType m_console_type; -}; -class StartGameUserSelectWatcher : public DetectorToFinder{ -public: - StartGameUserSelectWatcher(ConsoleHandle& console, Color color = COLOR_RED) - : DetectorToFinder("StartGameUserSelectWatcher", std::chrono::milliseconds(250), console, color) - {} -}; - - - - - - -} -} -#endif +/* Start Game User-Select Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_StartGameUserSelectDetector_H +#define PokemonAutomation_NintendoSwitch_StartGameUserSelectDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "NintendoSwitch_ConsoleTypeDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + +class StartGameUserSelectDetector_Switch1 : public StaticScreenDetector{ +public: + StartGameUserSelectDetector_Switch1(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_bottom_row; + ImageFloatBox m_bottom_icons; + ImageFloatBox m_top_row; + ImageFloatBox m_mid_row; + ImageFloatBox m_user_slot; +}; +class StartGameUserSelectDetector_Switch2 : public StaticScreenDetector{ +public: + StartGameUserSelectDetector_Switch2(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_bottom_row; + ImageFloatBox m_bottom_icons; + ImageFloatBox m_top_row; + ImageFloatBox m_mid_row; + ImageFloatBox m_user_slot; +}; + + + + + +class StartGameUserSelectDetector : public StaticScreenDetector{ +public: + StartGameUserSelectDetector(ConsoleHandle& console, Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + virtual void commit_state() override; + bool detect_only(const ImageViewRGB32& screen); + +private: + ConsoleHandle& m_console; + ConsoleTypeDetector_StartGameUserSelect m_type_detector; + StartGameUserSelectDetector_Switch1 m_switch1; + StartGameUserSelectDetector_Switch2 m_switch2; + + ConsoleType m_console_type; +}; +class StartGameUserSelectWatcher : public DetectorToFinder{ +public: + StartGameUserSelectWatcher(ConsoleHandle& console, Color color = COLOR_RED) + : DetectorToFinder("StartGameUserSelectWatcher", std::chrono::milliseconds(250), console, color) + {} +}; + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.cpp b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.cpp index f508ecd1f4..8631a38e73 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.cpp @@ -1,247 +1,254 @@ -/* Update Popup Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "NintendoSwitch_UpdatePopupDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -UpdatePopupDetector::UpdatePopupDetector(ConsoleHandle& console, Color color) - : m_type_detector(console, color) - , m_switch1(color) - , m_switch2(color) -{} -void UpdatePopupDetector::make_overlays(VideoOverlaySet& items) const{ - m_type_detector.make_overlays(items); - m_switch1.make_overlays(items); - m_switch2.make_overlays(items); -} -bool UpdatePopupDetector::detect(const ImageViewRGB32& screen){ - if (detect_only(screen)){ - m_type_detector.commit_to_cache(); - return true; - }else{ - return false; - } -} -bool UpdatePopupDetector::detect_only(const ImageViewRGB32& screen){ - ConsoleType type = m_type_detector.detect_only(screen); - - if (type == ConsoleType::Unknown){ - return false; - } - if (is_switch1(type)){ - return m_switch1.detect(screen); - } - if (is_switch2(type)){ - return m_switch2.detect(screen); - } - - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Invalid ConsoleType: " + std::to_string((int)type) - ); -} - - - - - - - - -UpdatePopupDetector_Switch1::UpdatePopupDetector_Switch1(Color color) - : m_color(color) - , m_box_top(0.25, 0.26, 0.50, 0.02) - , m_box_mid(0.25, 0.52, 0.50, 0.02) - , m_top(0.10, 0.15, 0.80, 0.03) - , m_left(0.08, 0.25, 0.10, 0.38) - , m_bottom_solid(0.10, 0.84, 0.80, 0.04) - , m_bottom_buttons(0.70, 0.92, 0.28, 0.05) -{} -void UpdatePopupDetector_Switch1::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box_top); - items.add(m_color, m_box_mid); - items.add(m_color, m_top); - items.add(m_color, m_left); - items.add(m_color, m_bottom_solid); - items.add(m_color, m_bottom_buttons); -} -bool UpdatePopupDetector_Switch1::detect(const ImageViewRGB32& screen){ - ImageStats stats_box_top = image_stats(extract_box_reference(screen, m_box_top)); -// cout << stats_box_top.average << stats_box_top.stddev << endl; - bool white; - if (stats_box_top.average.sum() < 300){ - white = false; - }else if (stats_box_top.average.sum() > 500){ - white = true; - }else{ - return false; - } - if (stats_box_top.stddev.sum() > 10){ - return false; - } - -// cout << "white: " << white << endl; - - ImageStats stats_box_mid = image_stats(extract_box_reference(screen, m_box_mid)); - if (stats_box_mid.stddev.sum() > 10){ - return false; - } - if (euclidean_distance(stats_box_top.average, stats_box_mid.average) > 10){ - return false; - } - - ImageStats stats_left = image_stats(extract_box_reference(screen, m_left)); -// cout << stats_left.stddev << endl; - if (stats_left.stddev.sum() < 30){ -// cout << "zxcv" << endl; - return false; - } - - ImageStats stats_top = image_stats(extract_box_reference(screen, m_top)); -// cout << stats_top.average << stats_top.stddev << endl; - - ImageStats bottom_solid = image_stats(extract_box_reference(screen, m_bottom_solid)); -// cout << bottom_solid.average << bottom_solid.stddev << endl; - - if (euclidean_distance(stats_top.average, bottom_solid.average) > 10){ -// cout << "qwer" << endl; - return false; - } - - if (white){ - if (!is_grey(stats_top, 100, 300) || !is_grey(bottom_solid, 100, 300)){ -// cout << "asdf" << endl; - return false; - } - }else{ - if (!is_grey(stats_top, 0, 100) || !is_grey(bottom_solid, 0, 100)){ -// cout << "zxcv" << endl; - return false; - } - } - - ImageStats stats_bottom_buttons = image_stats(extract_box_reference(screen, m_bottom_buttons)); -// cout << stats_bottom_buttons.average << stats_bottom_buttons.stddev << endl; - if (stats_bottom_buttons.stddev.sum() < 30){ - return false; - } - - return true; -} - - - - -UpdatePopupDetector_Switch2::UpdatePopupDetector_Switch2(Color color) - : m_color(color) - , m_box_top(0.25, 0.31, 0.50, 0.02) -// , m_box_mid(0.25, 0.482, 0.50, 0.02) - , m_top(0.10, 0.17, 0.80, 0.03) - , m_left(0.08, 0.25, 0.10, 0.38) - , m_bottom_solid(0.10, 0.86, 0.80, 0.04) - , m_bottom_buttons(0.70, 0.92, 0.28, 0.05) -{} - -void UpdatePopupDetector_Switch2::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box_top); -// items.add(m_color, m_box_mid); - items.add(m_color, m_top); - items.add(m_color, m_left); - items.add(m_color, m_bottom_solid); - items.add(m_color, m_bottom_buttons); -} -bool UpdatePopupDetector_Switch2::detect(const ImageViewRGB32& screen){ - ImageStats stats_box_top = image_stats(extract_box_reference(screen, m_box_top)); -// cout << stats_box_top.average << stats_box_top.stddev << endl; - bool white; - if (stats_box_top.average.sum() < 300){ - white = false; - }else if (stats_box_top.average.sum() > 500){ - white = true; - }else{ - return false; - } - if (stats_box_top.stddev.sum() > 10){ - return false; - } - -// cout << "white: " << white << endl; - -#if 0 - ImageStats stats_box_mid = image_stats(extract_box_reference(screen, m_box_mid)); - if (stats_box_mid.stddev.sum() > 10){ - return false; - } - if (euclidean_distance(stats_box_top.average, stats_box_mid.average) > 10){ - return false; - } -#endif - - ImageStats stats_left = image_stats(extract_box_reference(screen, m_left)); -// cout << stats_left.stddev << endl; - if (stats_left.stddev.sum() < 30){ -// cout << "zxcv" << endl; - return false; - } - - ImageStats stats_top = image_stats(extract_box_reference(screen, m_top)); -// cout << stats_top.average << stats_top.stddev << endl; - - ImageStats bottom_solid = image_stats(extract_box_reference(screen, m_bottom_solid)); -// cout << bottom_solid.average << bottom_solid.stddev << endl; - - if (euclidean_distance(stats_top.average, bottom_solid.average) > 10){ -// cout << "qwer" << endl; - return false; - } - - do{ - if (white){ - if (is_grey(stats_top, 200, 765) && is_grey(bottom_solid, 200, 765)){ - break; - } - }else{ - if (is_grey(stats_top, 0, 100) && is_grey(bottom_solid, 0, 100)){ - break; - } - if (is_grey(stats_top, 200, 500) && is_grey(bottom_solid, 200, 500)){ - break; - } - } - - return false; - }while (false); - - ImageStats stats_bottom_buttons = image_stats(extract_box_reference(screen, m_bottom_buttons)); -// cout << stats_bottom_buttons.average << stats_bottom_buttons.stddev << endl; - if (stats_bottom_buttons.stddev.sum() < 30){ - return false; - } - - return true; -} - - - - - - - - - -} -} +/* Update Popup Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "NintendoSwitch_UpdatePopupDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +UpdatePopupDetector::UpdatePopupDetector(ConsoleHandle& console, Color color) + : m_type_detector(console, color) + , m_switch1(color) + , m_switch2(color) +{} +void UpdatePopupDetector::make_overlays(VideoOverlaySet& items) const{ + m_type_detector.make_overlays(items); + m_switch1.make_overlays(items); + m_switch2.make_overlays(items); +} +bool UpdatePopupDetector::detect(const ImageViewRGB32& screen){ + return detect_only(screen); + +#if 0 + if (detect_only(screen)){ + m_type_detector.commit_to_cache(); + return true; + }else{ + return false; + } +#endif +} +void UpdatePopupDetector::commit_state(){ + m_type_detector.commit_to_cache(); +} +bool UpdatePopupDetector::detect_only(const ImageViewRGB32& screen){ + ConsoleType type = m_type_detector.detect_only(screen); + + if (type == ConsoleType::Unknown){ + return false; + } + if (is_switch1(type)){ + return m_switch1.detect(screen); + } + if (is_switch2(type)){ + return m_switch2.detect(screen); + } + + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Invalid ConsoleType: " + std::to_string((int)type) + ); +} + + + + + + + + +UpdatePopupDetector_Switch1::UpdatePopupDetector_Switch1(Color color) + : m_color(color) + , m_box_top(0.25, 0.26, 0.50, 0.02) + , m_box_mid(0.25, 0.52, 0.50, 0.02) + , m_top(0.10, 0.15, 0.80, 0.03) + , m_left(0.08, 0.25, 0.10, 0.38) + , m_bottom_solid(0.10, 0.84, 0.80, 0.04) + , m_bottom_buttons(0.70, 0.92, 0.28, 0.05) +{} +void UpdatePopupDetector_Switch1::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box_top); + items.add(m_color, m_box_mid); + items.add(m_color, m_top); + items.add(m_color, m_left); + items.add(m_color, m_bottom_solid); + items.add(m_color, m_bottom_buttons); +} +bool UpdatePopupDetector_Switch1::detect(const ImageViewRGB32& screen){ + ImageStats stats_box_top = image_stats(extract_box_reference(screen, m_box_top)); +// cout << stats_box_top.average << stats_box_top.stddev << endl; + bool white; + if (stats_box_top.average.sum() < 300){ + white = false; + }else if (stats_box_top.average.sum() > 500){ + white = true; + }else{ + return false; + } + if (stats_box_top.stddev.sum() > 10){ + return false; + } + +// cout << "white: " << white << endl; + + ImageStats stats_box_mid = image_stats(extract_box_reference(screen, m_box_mid)); + if (stats_box_mid.stddev.sum() > 10){ + return false; + } + if (euclidean_distance(stats_box_top.average, stats_box_mid.average) > 10){ + return false; + } + + ImageStats stats_left = image_stats(extract_box_reference(screen, m_left)); +// cout << stats_left.stddev << endl; + if (stats_left.stddev.sum() < 30){ +// cout << "zxcv" << endl; + return false; + } + + ImageStats stats_top = image_stats(extract_box_reference(screen, m_top)); +// cout << stats_top.average << stats_top.stddev << endl; + + ImageStats bottom_solid = image_stats(extract_box_reference(screen, m_bottom_solid)); +// cout << bottom_solid.average << bottom_solid.stddev << endl; + + if (euclidean_distance(stats_top.average, bottom_solid.average) > 10){ +// cout << "qwer" << endl; + return false; + } + + if (white){ + if (!is_grey(stats_top, 100, 300) || !is_grey(bottom_solid, 100, 300)){ +// cout << "asdf" << endl; + return false; + } + }else{ + if (!is_grey(stats_top, 0, 100) || !is_grey(bottom_solid, 0, 100)){ +// cout << "zxcv" << endl; + return false; + } + } + + ImageStats stats_bottom_buttons = image_stats(extract_box_reference(screen, m_bottom_buttons)); +// cout << stats_bottom_buttons.average << stats_bottom_buttons.stddev << endl; + if (stats_bottom_buttons.stddev.sum() < 30){ + return false; + } + + return true; +} + + + + +UpdatePopupDetector_Switch2::UpdatePopupDetector_Switch2(Color color) + : m_color(color) + , m_box_top(0.25, 0.31, 0.50, 0.02) +// , m_box_mid(0.25, 0.482, 0.50, 0.02) + , m_top(0.10, 0.17, 0.80, 0.03) + , m_left(0.08, 0.25, 0.10, 0.38) + , m_bottom_solid(0.10, 0.86, 0.80, 0.04) + , m_bottom_buttons(0.70, 0.92, 0.28, 0.05) +{} + +void UpdatePopupDetector_Switch2::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box_top); +// items.add(m_color, m_box_mid); + items.add(m_color, m_top); + items.add(m_color, m_left); + items.add(m_color, m_bottom_solid); + items.add(m_color, m_bottom_buttons); +} +bool UpdatePopupDetector_Switch2::detect(const ImageViewRGB32& screen){ + ImageStats stats_box_top = image_stats(extract_box_reference(screen, m_box_top)); +// cout << stats_box_top.average << stats_box_top.stddev << endl; + bool white; + if (stats_box_top.average.sum() < 300){ + white = false; + }else if (stats_box_top.average.sum() > 500){ + white = true; + }else{ + return false; + } + if (stats_box_top.stddev.sum() > 10){ + return false; + } + +// cout << "white: " << white << endl; + +#if 0 + ImageStats stats_box_mid = image_stats(extract_box_reference(screen, m_box_mid)); + if (stats_box_mid.stddev.sum() > 10){ + return false; + } + if (euclidean_distance(stats_box_top.average, stats_box_mid.average) > 10){ + return false; + } +#endif + + ImageStats stats_left = image_stats(extract_box_reference(screen, m_left)); +// cout << stats_left.stddev << endl; + if (stats_left.stddev.sum() < 30){ +// cout << "zxcv" << endl; + return false; + } + + ImageStats stats_top = image_stats(extract_box_reference(screen, m_top)); +// cout << stats_top.average << stats_top.stddev << endl; + + ImageStats bottom_solid = image_stats(extract_box_reference(screen, m_bottom_solid)); +// cout << bottom_solid.average << bottom_solid.stddev << endl; + + if (euclidean_distance(stats_top.average, bottom_solid.average) > 10){ +// cout << "qwer" << endl; + return false; + } + + do{ + if (white){ + if (is_grey(stats_top, 200, 765) && is_grey(bottom_solid, 200, 765)){ + break; + } + }else{ + if (is_grey(stats_top, 0, 100) && is_grey(bottom_solid, 0, 100)){ + break; + } + if (is_grey(stats_top, 200, 500) && is_grey(bottom_solid, 200, 500)){ + break; + } + } + + return false; + }while (false); + + ImageStats stats_bottom_buttons = image_stats(extract_box_reference(screen, m_bottom_buttons)); +// cout << stats_bottom_buttons.average << stats_bottom_buttons.stddev << endl; + if (stats_bottom_buttons.stddev.sum() < 30){ + return false; + } + + return true; +} + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.h b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.h index ee8a1dfb82..8a7b921fd3 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.h +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.h @@ -1,86 +1,87 @@ -/* Update Popup Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_UpdatePopupDetector_H -#define PokemonAutomation_NintendoSwitch_UpdatePopupDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "NintendoSwitch_ConsoleTypeDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -class UpdatePopupDetector_Switch1 : public StaticScreenDetector{ -public: - UpdatePopupDetector_Switch1(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_box_top; - ImageFloatBox m_box_mid; - ImageFloatBox m_top; - ImageFloatBox m_left; - ImageFloatBox m_bottom_solid; - ImageFloatBox m_bottom_buttons; -}; -class UpdatePopupDetector_Switch2 : public StaticScreenDetector{ -public: - UpdatePopupDetector_Switch2(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_box_top; -// ImageFloatBox m_box_mid; - ImageFloatBox m_top; - ImageFloatBox m_left; - ImageFloatBox m_bottom_solid; - ImageFloatBox m_bottom_buttons; -}; - - - - - -// Detect the Switch system update screen when you are about to enter a game from Switch Home screen -class UpdatePopupDetector : public StaticScreenDetector{ -public: - UpdatePopupDetector(ConsoleHandle& console, Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - bool detect_only(const ImageViewRGB32& screen); - -private: - ConsoleTypeDetector_Home m_type_detector; - UpdatePopupDetector_Switch1 m_switch1; - UpdatePopupDetector_Switch2 m_switch2; -}; -class UpdateMenuWatcher : public DetectorToFinder{ -public: - UpdateMenuWatcher(ConsoleHandle& console, Color color = COLOR_RED) - : DetectorToFinder("UpdateMenuWatcher", std::chrono::milliseconds(250), console, color) - {} -}; - - - - - - -} -} -#endif +/* Update Popup Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_UpdatePopupDetector_H +#define PokemonAutomation_NintendoSwitch_UpdatePopupDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "NintendoSwitch_ConsoleTypeDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +class UpdatePopupDetector_Switch1 : public StaticScreenDetector{ +public: + UpdatePopupDetector_Switch1(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_box_top; + ImageFloatBox m_box_mid; + ImageFloatBox m_top; + ImageFloatBox m_left; + ImageFloatBox m_bottom_solid; + ImageFloatBox m_bottom_buttons; +}; +class UpdatePopupDetector_Switch2 : public StaticScreenDetector{ +public: + UpdatePopupDetector_Switch2(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_box_top; +// ImageFloatBox m_box_mid; + ImageFloatBox m_top; + ImageFloatBox m_left; + ImageFloatBox m_bottom_solid; + ImageFloatBox m_bottom_buttons; +}; + + + + + +// Detect the Switch system update screen when you are about to enter a game from Switch Home screen +class UpdatePopupDetector : public StaticScreenDetector{ +public: + UpdatePopupDetector(ConsoleHandle& console, Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + virtual void commit_state() override; + bool detect_only(const ImageViewRGB32& screen); + +private: + ConsoleTypeDetector_Home m_type_detector; + UpdatePopupDetector_Switch1 m_switch1; + UpdatePopupDetector_Switch2 m_switch2; +}; +class UpdateMenuWatcher : public DetectorToFinder{ +public: + UpdateMenuWatcher(ConsoleHandle& console, Color color = COLOR_RED) + : DetectorToFinder("UpdateMenuWatcher", std::chrono::milliseconds(250), console, color) + {} +}; + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleHandle.cpp b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleHandle.cpp index 40ae43b548..208171c870 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleHandle.cpp +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleHandle.cpp @@ -1,50 +1,72 @@ -/* Console Handle - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.h" -#include "CommonTools/InferencePivots/VisualInferencePivot.h" -#include "CommonTools/InferencePivots/AudioInferencePivot.h" -#include "CommonFramework/Recording/StreamHistorySession.h" -#include "NintendoSwitch_ConsoleHandle.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -//ConsoleHandle::ConsoleHandle(ConsoleHandle&& x) = default; -ConsoleHandle::~ConsoleHandle(){ - overlay().remove_stat(*m_thread_utilization); -} - - -ConsoleHandle::ConsoleHandle( - size_t index, - Logger& logger, - AbstractController& controller, - VideoFeed& video, - VideoOverlay& overlay, - AudioFeed& audio, - const StreamHistorySession& history -) - : VideoStream(logger, audio, video, history, overlay) - , m_index(index) - , m_controller(controller) - , m_thread_utilization(new ThreadUtilizationStat(current_thread_handle(), "Program Thread:")) -{ - overlay.add_stat(*m_thread_utilization); -} - - - - - -} -} +/* Console Handle + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Tools/GlobalThreadPools.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.h" +#include "CommonTools/InferencePivots/VisualInferencePivot.h" +#include "CommonTools/InferencePivots/AudioInferencePivot.h" +#include "CommonFramework/Recording/StreamHistorySession.h" +#include "NintendoSwitch_ConsoleHandle.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +//ConsoleHandle::ConsoleHandle(ConsoleHandle&& x) = default; +ConsoleHandle::~ConsoleHandle(){ + overlay().remove_stat(*m_thread_utilization); + overlay().remove_stat(*m_normal_inference_utilization); + overlay().remove_stat(*m_realtime_inference_utilization); +} + + +ConsoleHandle::ConsoleHandle( + size_t index, + Logger& logger, + AbstractController& controller, + VideoFeed& video, + VideoOverlay& overlay, + AudioFeed& audio, + const StreamHistorySession& history +) + : VideoStream(logger, audio, video, history, overlay) + , m_index(index) + , m_controller(controller) + , m_realtime_inference_utilization( + new ThreadPoolUtilizationStat( + GlobalThreadPools::realtime_inference(), + "Real-Time Pool" + ) + ) + , m_normal_inference_utilization( + new ThreadPoolUtilizationStat( + GlobalThreadPools::normal_inference(), + "Normal Pool" + ) + ) + , m_thread_utilization( + new ThreadUtilizationStat( + current_thread_handle(), + "Program Thread:" + ) + ) +{ + overlay.add_stat(*m_realtime_inference_utilization); + overlay.add_stat(*m_normal_inference_utilization); + overlay.add_stat(*m_thread_utilization); +} + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleHandle.h b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleHandle.h index 2acd30f3cd..adc4ca7f12 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleHandle.h +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleHandle.h @@ -1,88 +1,91 @@ -/* Console Handle - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_ConsoleHandle_H -#define PokemonAutomation_NintendoSwitch_ConsoleHandle_H - -#include -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch_ConsoleState.h" - -namespace PokemonAutomation{ - class ThreadHandle; - class ThreadUtilizationStat; -namespace NintendoSwitch{ - -class ConsoleHandle : public VideoStream{ -public: - ~ConsoleHandle(); -// ConsoleHandle(ConsoleHandle&& x); -// void operator=(ConsoleHandle&& x) = delete; - ConsoleHandle(const ConsoleHandle& x) = delete; - void operator=(const ConsoleHandle& x) = delete; - - -public: - ConsoleHandle( - size_t index, - Logger& logger, - AbstractController& controller, - VideoFeed& video, - VideoOverlay& overlay, - AudioFeed& audio, - const StreamHistorySession& history - ); - - size_t index() const{ return m_index; } - - template - ControllerType& controller(){ - ControllerType* ret = dynamic_cast(&m_controller); - if (ret){ - return *ret; - } - throw InternalProgramError(&logger(), PA_CURRENT_FUNCTION, "Unable to cast controller."); - } - - // REMOVE: Temporary for refactor. - ProController& pro_controller(){ - ProController* ret = dynamic_cast(&m_controller); - if (ret){ - return *ret; - } - throw InternalProgramError(&logger(), PA_CURRENT_FUNCTION, "Unable to cast to ProController."); - } - - - operator Logger&(){ return logger(); } - operator VideoFeed&(){ return video(); } - operator VideoOverlay&(){ return overlay(); } - operator AudioFeed&() { return audio(); } - operator const StreamHistorySession&() const{ return history(); } - - ConsoleState& state(){ return m_console_state; } - operator ConsoleState&(){ return m_console_state; } - - -private: - size_t m_index; - AbstractController& m_controller; - - ConsoleState m_console_state; - - std::unique_ptr m_thread_utilization; -}; - - - - -} -} -#endif - - +/* Console Handle + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_ConsoleHandle_H +#define PokemonAutomation_NintendoSwitch_ConsoleHandle_H + +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch_ConsoleState.h" + +namespace PokemonAutomation{ + class ThreadHandle; + class ThreadUtilizationStat; + class ThreadPoolUtilizationStat; +namespace NintendoSwitch{ + +class ConsoleHandle : public VideoStream{ +public: + ~ConsoleHandle(); +// ConsoleHandle(ConsoleHandle&& x); +// void operator=(ConsoleHandle&& x) = delete; + ConsoleHandle(const ConsoleHandle& x) = delete; + void operator=(const ConsoleHandle& x) = delete; + + +public: + ConsoleHandle( + size_t index, + Logger& logger, + AbstractController& controller, + VideoFeed& video, + VideoOverlay& overlay, + AudioFeed& audio, + const StreamHistorySession& history + ); + + size_t index() const{ return m_index; } + + template + ControllerType& controller(){ + ControllerType* ret = dynamic_cast(&m_controller); + if (ret){ + return *ret; + } + throw InternalProgramError(&logger(), PA_CURRENT_FUNCTION, "Unable to cast controller."); + } + + // REMOVE: Temporary for refactor. + ProController& pro_controller(){ + ProController* ret = dynamic_cast(&m_controller); + if (ret){ + return *ret; + } + throw InternalProgramError(&logger(), PA_CURRENT_FUNCTION, "Unable to cast to ProController."); + } + + + operator Logger&(){ return logger(); } + operator VideoFeed&(){ return video(); } + operator VideoOverlay&(){ return overlay(); } + operator AudioFeed&() { return audio(); } + operator const StreamHistorySession&() const{ return history(); } + + ConsoleState& state(){ return m_console_state; } + operator ConsoleState&(){ return m_console_state; } + + +private: + size_t m_index; + AbstractController& m_controller; + + ConsoleState m_console_state; + + std::unique_ptr m_realtime_inference_utilization; + std::unique_ptr m_normal_inference_utilization; + std::unique_ptr m_thread_utilization; +}; + + + + +} +} +#endif + + diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleState.cpp b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleState.cpp index e9e3859455..13ccc194d4 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleState.cpp +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleState.cpp @@ -1,182 +1,182 @@ -/* Console State - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "NintendoSwitch_ConsoleState.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -const std::string& ConsoleType_strings(ConsoleType type){ - static std::string STRINGS[] = { - "Unknown", - "Switch 1 + OLED", - "Switch 2 (unknown model)", - "Switch 2 (FW19, international)", - "Switch 2 (FW19, Japan-locked)", - "Switch 2 (FW20, international)", - "Switch 2 (FW20, Japan-locked)", - }; - size_t index = (size_t)type; - if (index < sizeof(STRINGS) / sizeof(std::string)){ - return STRINGS[(size_t)type]; - } - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Invalid ConsoleType enum: " + std::to_string(index) - ); -} - -[[noreturn]] void throw_conflict( - Logger& logger, - ConsoleType user_type, - ConsoleType detected_type -){ - throw UserSetupError( - logger, - std::string("Conflicting Console Types:") + - "\n User Selected: " + ConsoleType_strings(user_type) + - "\n Detected Type: " + ConsoleType_strings(detected_type) + - "\n\nIf you think this is a bug, please report it to either our Github or our Discord server!" - ); -} - - - -void check_for_conflict( - Logger& logger, - ConsoleType user_type, - ConsoleType detected_type -){ - if (user_type == detected_type){ - return; - } - if (user_type == ConsoleType::Unknown || detected_type == ConsoleType::Unknown){ - return; - } - - if (is_switch1(user_type) && is_switch1(detected_type)){ - return; - } - - if (is_switch2(user_type) && is_switch2(detected_type)){ - if (user_type == ConsoleType::Switch2_Unknown || detected_type == ConsoleType::Switch2_Unknown){ - return; - } - if (user_type != detected_type){ - throw_conflict(logger, user_type, detected_type); - } - return; - } - - throw_conflict(logger, user_type, detected_type); -} - - - - - - -struct ConsoleState::Data{ - Data() - : m_console_type_confirmed(false) - , m_console_type(ConsoleType::Unknown) - , m_text_size_standard(false) - {} - - std::atomic m_console_type_confirmed; - std::atomic m_console_type; - - std::atomic m_text_size_standard; -}; - - - -ConsoleState::~ConsoleState() = default; -ConsoleState::ConsoleState() - : m_data(CONSTRUCT_TOKEN) -{} - -bool ConsoleState::console_type_confirmed() const{ - return m_data->m_console_type_confirmed.load(std::memory_order_relaxed); -} -ConsoleType ConsoleState::console_type() const{ - return m_data->m_console_type.load(std::memory_order_relaxed); -} -void ConsoleState::set_console_type_user(ConsoleType type){ - m_data->m_console_type_confirmed.store(false, std::memory_order_relaxed); - m_data->m_console_type.store(type, std::memory_order_relaxed); -} -void ConsoleState::set_console_type(Logger& logger, ConsoleType type){ - ConsoleType current = console_type(); - bool confirmed = m_data->m_console_type_confirmed.load(std::memory_order_relaxed); - if (!confirmed){ - check_for_conflict(logger, current, type); - } - - do{ - if (type == ConsoleType::Unknown){ - return; - } - if (current == ConsoleType::Unknown){ - break; - } - - if (type == ConsoleType::Switch2_Unknown){ - return; - } - - }while (false); - - if (!confirmed || current != type){ - logger.log( - std::string("Setting console type to: ") + ConsoleType_strings(type), - COLOR_BLUE - ); - } - - m_data->m_console_type.store(type, std::memory_order_relaxed); - m_data->m_console_type_confirmed.store(true, std::memory_order_relaxed); -} - - - -bool ConsoleState::text_size_ok() const{ - return m_data->m_text_size_standard.load(std::memory_order_relaxed); -} -void ConsoleState::set_text_size_ok(bool ok){ - m_data->m_text_size_standard.store(ok, std::memory_order_relaxed); -} - - - - - - - - - - - - - - - - - - - - - - - - -} -} +/* Console State + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "NintendoSwitch_ConsoleState.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +const std::string& ConsoleType_strings(ConsoleType type){ + static std::string STRINGS[] = { + "Unknown", + "Switch 1 + OLED", + "Switch 2 (unknown model)", + "Switch 2 (FW19, international)", + "Switch 2 (FW19, Japan-locked)", + "Switch 2 (FW20, international)", + "Switch 2 (FW20, Japan-locked)", + }; + size_t index = (size_t)type; + if (index < sizeof(STRINGS) / sizeof(std::string)){ + return STRINGS[(size_t)type]; + } + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Invalid ConsoleType enum: " + std::to_string(index) + ); +} + +[[noreturn]] void throw_conflict( + Logger& logger, + ConsoleType user_type, + ConsoleType detected_type +){ + throw UserSetupError( + logger, + std::string("Conflicting Console Types:") + + "\n User Selected: " + ConsoleType_strings(user_type) + + "\n Detected Type: " + ConsoleType_strings(detected_type) + + "\n\nIf you think this is a bug, please report it to either our Github or our Discord server!" + ); +} + + + +void check_for_conflict( + Logger& logger, + ConsoleType user_type, + ConsoleType detected_type +){ + if (user_type == detected_type){ + return; + } + if (user_type == ConsoleType::Unknown || detected_type == ConsoleType::Unknown){ + return; + } + + if (is_switch1(user_type) && is_switch1(detected_type)){ + return; + } + + if (is_switch2(user_type) && is_switch2(detected_type)){ + if (user_type == ConsoleType::Switch2_Unknown || detected_type == ConsoleType::Switch2_Unknown){ + return; + } + if (user_type != detected_type){ + throw_conflict(logger, user_type, detected_type); + } + return; + } + + throw_conflict(logger, user_type, detected_type); +} + + + + + + +struct ConsoleState::Data{ + Data() + : m_console_type_confirmed(false) + , m_console_type(ConsoleType::Unknown) + , m_text_size_standard(false) + {} + + std::atomic m_console_type_confirmed; + std::atomic m_console_type; + + std::atomic m_text_size_standard; +}; + + + +ConsoleState::~ConsoleState() = default; +ConsoleState::ConsoleState() + : m_data(CONSTRUCT_TOKEN) +{} + +bool ConsoleState::console_type_confirmed() const{ + return m_data->m_console_type_confirmed.load(std::memory_order_relaxed); +} +ConsoleType ConsoleState::console_type() const{ + return m_data->m_console_type.load(std::memory_order_relaxed); +} +void ConsoleState::set_console_type_user(ConsoleType type){ + m_data->m_console_type_confirmed.store(false, std::memory_order_relaxed); + m_data->m_console_type.store(type, std::memory_order_relaxed); +} +void ConsoleState::set_console_type(Logger& logger, ConsoleType type){ + ConsoleType current = console_type(); + bool confirmed = m_data->m_console_type_confirmed.load(std::memory_order_relaxed); + if (!confirmed){ + check_for_conflict(logger, current, type); + } + + do{ + if (type == ConsoleType::Unknown){ + return; + } + if (current == ConsoleType::Unknown){ + break; + } + + if (type == ConsoleType::Switch2_Unknown){ + return; + } + + }while (false); + + if (!confirmed || current != type){ + logger.log( + std::string("Setting console type to: ") + ConsoleType_strings(type), + COLOR_BLUE + ); + } + + m_data->m_console_type.store(type, std::memory_order_relaxed); + m_data->m_console_type_confirmed.store(true, std::memory_order_relaxed); +} + + + +bool ConsoleState::text_size_ok() const{ + return m_data->m_text_size_standard.load(std::memory_order_relaxed); +} +void ConsoleState::set_text_size_ok(bool ok){ + m_data->m_text_size_standard.store(ok, std::memory_order_relaxed); +} + + + + + + + + + + + + + + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleState.h b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleState.h index f1319c4618..c6f6750906 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleState.h +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleState.h @@ -1,72 +1,72 @@ -/* Console State - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_ConsoleState_H -#define PokemonAutomation_NintendoSwitch_ConsoleState_H - -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Containers/Pimpl.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -enum class ConsoleType{ - Unknown, - Switch1, - Switch2_Unknown, - Switch2_FW19_International, - Switch2_FW19_JapanLocked, - Switch2_FW20_International, - Switch2_FW20_JapanLocked, -}; -const std::string& ConsoleType_strings(ConsoleType type); - -inline bool is_switch1(ConsoleType type){ - return type == ConsoleType::Switch1; -} -inline bool is_switch2(ConsoleType type){ - return type == ConsoleType::Switch2_Unknown - || type == ConsoleType::Switch2_FW19_International - || type == ConsoleType::Switch2_FW19_JapanLocked - || type == ConsoleType::Switch2_FW20_International - || type == ConsoleType::Switch2_FW20_JapanLocked; -} -void check_for_conflict( - Logger& logger, - ConsoleType user_type, - ConsoleType detected_type -); - - - - -class ConsoleState{ -public: - ~ConsoleState(); - ConsoleState(); - - - bool console_type_confirmed() const; - ConsoleType console_type() const; - void set_console_type_user(ConsoleType type); - void set_console_type(Logger& logger, ConsoleType type); - - bool text_size_ok() const; - void set_text_size_ok(bool ok); - -private: - struct Data; - Pimpl m_data; -}; - - - - -} -} -#endif +/* Console State + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_ConsoleState_H +#define PokemonAutomation_NintendoSwitch_ConsoleState_H + +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Containers/Pimpl.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +enum class ConsoleType{ + Unknown, + Switch1, + Switch2_Unknown, + Switch2_FW19_International, + Switch2_FW19_JapanLocked, + Switch2_FW20_International, + Switch2_FW20_JapanLocked, +}; +const std::string& ConsoleType_strings(ConsoleType type); + +inline bool is_switch1(ConsoleType type){ + return type == ConsoleType::Switch1; +} +inline bool is_switch2(ConsoleType type){ + return type == ConsoleType::Switch2_Unknown + || type == ConsoleType::Switch2_FW19_International + || type == ConsoleType::Switch2_FW19_JapanLocked + || type == ConsoleType::Switch2_FW20_International + || type == ConsoleType::Switch2_FW20_JapanLocked; +} +void check_for_conflict( + Logger& logger, + ConsoleType user_type, + ConsoleType detected_type +); + + + + +class ConsoleState{ +public: + ~ConsoleState(); + ConsoleState(); + + + bool console_type_confirmed() const; + ConsoleType console_type() const; + void set_console_type_user(ConsoleType type); + void set_console_type(Logger& logger, ConsoleType type); + + bool text_size_ok() const; + void set_text_size_ok(bool ok); + +private: + struct Data; + Pimpl m_data; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_MultiSwitchProgram.cpp b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_MultiSwitchProgram.cpp index 7b7715c6e6..6cefc59585 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_MultiSwitchProgram.cpp +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_MultiSwitchProgram.cpp @@ -115,7 +115,8 @@ MultiSwitchProgramDescriptor::MultiSwitchProgramDescriptor( FasterIfTickPrecise faster_if_tick_precise, size_t min_switches, size_t max_switches, - size_t default_switches + size_t default_switches, + bool deprecated ) : ProgramDescriptor( pick_color(required_features, faster_if_tick_precise), @@ -128,6 +129,7 @@ MultiSwitchProgramDescriptor::MultiSwitchProgramDescriptor( , m_required_features(std::move(required_features)) , m_faster_if_tick_precise(faster_if_tick_precise) , m_allow_commands_while_running(allow_commands_while_running == AllowCommandsWhenRunning::ENABLE_COMMANDS) + , m_deprecated(deprecated) , m_min_switches(min_switches) , m_max_switches(max_switches) , m_default_switches(default_switches) diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h index 0613c06187..7447b5b4c7 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h @@ -82,13 +82,15 @@ class MultiSwitchProgramDescriptor : public ProgramDescriptor{ FasterIfTickPrecise faster_if_tick_precise, size_t min_switches, size_t max_switches, - size_t default_switches + size_t default_switches, + bool deprecated = false ); FeedbackType feedback() const{ return m_feedback; } const ControllerFeatures& required_features() const{ return m_required_features; } FasterIfTickPrecise faster_if_tick_precise() const{ return m_faster_if_tick_precise; } bool allow_commands_while_running() const{ return m_allow_commands_while_running; } + bool deprecated() const{ return m_deprecated; } size_t min_switches() const{ return m_min_switches; } size_t max_switches() const{ return m_max_switches; } @@ -102,6 +104,7 @@ class MultiSwitchProgramDescriptor : public ProgramDescriptor{ const ControllerFeatures m_required_features; const FasterIfTickPrecise m_faster_if_tick_precise; const bool m_allow_commands_while_running; + const bool m_deprecated; const size_t m_min_switches; const size_t m_max_switches; diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_Settings.cpp b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_Settings.cpp index 85a77c689c..c68a0f4fd2 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_Settings.cpp +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_Settings.cpp @@ -98,12 +98,24 @@ ConsoleSettings::ConsoleSettings() true ) , TOLERATE_SYSTEM_UPDATE_MENU_SLOW( - "Tolerate System Update Menu (slow):Some programs can bypass the system update menu, but will take a noticeable performance hit. " + "Tolerate System Update Menu (slow):
" + "Some programs can bypass the system update menu, but will take a noticeable performance hit. " "Setting this to true enables this.", LockMode::LOCK_WHILE_RUNNING, false ) + , ENABLE_SBB3_PINGS( + "Enable sys-botbase 3 Pings:
" + "Use sys-botbase's ping command for latency measurement instead of \"getVersion\".", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , ENABLE_SBB3_LOGGING( + "Enable sys-botbase 3 Logging:
" + "Tell sys-botbase 3 to log its activity to its own log.", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) , SWITCH1_DIGIT_ENTRY(false) , SWITCH1_KEYBOARD_ENTRY(false) , SWITCH2_DIGIT_ENTRY(true) @@ -117,6 +129,8 @@ ConsoleSettings::ConsoleSettings() PA_ADD_OPTION(START_GAME_INTERNET_CHECK_DELAY0); PA_ADD_OPTION(TOLERATE_SYSTEM_UPDATE_MENU_FAST); PA_ADD_OPTION(TOLERATE_SYSTEM_UPDATE_MENU_SLOW); + PA_ADD_OPTION(ENABLE_SBB3_PINGS); + PA_ADD_OPTION(ENABLE_SBB3_LOGGING); PA_ADD_OPTION(TIMING_OPTIONS); if (PreloadSettings::instance().DEVELOPER_MODE){ PA_ADD_OPTION(SWITCH1_DIGIT_ENTRY); diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_Settings.h b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_Settings.h index 791d24124e..51cacd4f9d 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_Settings.h +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_Settings.h @@ -49,6 +49,9 @@ class ConsoleSettings : public BatchOption{ BooleanCheckBoxOption TOLERATE_SYSTEM_UPDATE_MENU_FAST; BooleanCheckBoxOption TOLERATE_SYSTEM_UPDATE_MENU_SLOW; + BooleanCheckBoxOption ENABLE_SBB3_PINGS; + BooleanCheckBoxOption ENABLE_SBB3_LOGGING; + TimingOptions TIMING_OPTIONS; DigitEntryTimingsOption SWITCH1_DIGIT_ENTRY; diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.cpp b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.cpp index c66ad0706f..b4ada52682 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.cpp +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.cpp @@ -25,7 +25,8 @@ SingleSwitchProgramDescriptor::SingleSwitchProgramDescriptor( FeedbackType feedback, AllowCommandsWhenRunning allow_commands_while_running, ControllerFeatures required_features, - FasterIfTickPrecise faster_if_tick_precise + FasterIfTickPrecise faster_if_tick_precise, + bool deprecated ) : ProgramDescriptor( pick_color(required_features, faster_if_tick_precise), @@ -38,6 +39,7 @@ SingleSwitchProgramDescriptor::SingleSwitchProgramDescriptor( , m_required_features(std::move(required_features)) , m_faster_if_tick_precise(faster_if_tick_precise) , m_allow_commands_while_running(allow_commands_while_running == AllowCommandsWhenRunning::ENABLE_COMMANDS) + , m_deprecated(deprecated) {} std::unique_ptr SingleSwitchProgramDescriptor::make_panel() const{ return std::make_unique(*this); @@ -59,14 +61,14 @@ SingleSwitchProgramInstance::SingleSwitchProgramInstance( , NOTIFICATION_ERROR_RECOVERABLE( "Program Error (Recoverable)", true, false, - ImageAttachmentMode::PNG, + ImageAttachmentMode::JPG, error_notification_tags ) , NOTIFICATION_ERROR_FATAL( "Program Error (Fatal)", true, true, - ImageAttachmentMode::PNG, + ImageAttachmentMode::JPG, error_notification_tags ) {} diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h index 064c85b4ce..6100f3cf82 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h @@ -59,13 +59,15 @@ class SingleSwitchProgramDescriptor : public ProgramDescriptor{ FeedbackType feedback, AllowCommandsWhenRunning allow_commands_while_running, ControllerFeatures required_features, - FasterIfTickPrecise faster_if_tick_precise = FasterIfTickPrecise::NOT_FASTER + FasterIfTickPrecise faster_if_tick_precise = FasterIfTickPrecise::NOT_FASTER, + bool deprecated = false ); FeedbackType feedback() const{ return m_feedback; } const ControllerFeatures& required_features() const{ return m_required_features; } FasterIfTickPrecise faster_if_tick_precise() const{ return m_faster_if_tick_precise; } bool allow_commands_while_running() const{ return m_allow_commands_while_running; } + bool deprecated() const{ return m_deprecated; } virtual std::unique_ptr make_panel() const override; virtual std::unique_ptr make_instance() const = 0; @@ -75,6 +77,7 @@ class SingleSwitchProgramDescriptor : public ProgramDescriptor{ const ControllerFeatures m_required_features; const FasterIfTickPrecise m_faster_if_tick_precise; const bool m_allow_commands_while_running; + const bool m_deprecated; }; diff --git a/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.cpp b/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.cpp index 5839290924..0586f9655d 100644 --- a/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.cpp @@ -1,139 +1,139 @@ -/* Code Entry Settings Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/GlobalSettingsPanel.h" -#include "NintendoSwitch_CodeEntrySettingsOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -KeyboardLayoutOption::KeyboardLayoutOption() - : EnumDropdownOption( - "Keyboard Layout:", - { - {KeyboardLayout::QWERTY, "qwerty", "QWERTY"}, - {KeyboardLayout::AZERTY, "azerty", "AZERTY"}, - }, - LockMode::LOCK_WHILE_RUNNING, - KeyboardLayout::QWERTY - ) -{} -KeyboardLayoutOption::KeyboardLayoutOption(std::string label) - : EnumDropdownOption( - std::move(label), - { - {KeyboardLayout::QWERTY, "qwerty", "QWERTY"}, - {KeyboardLayout::AZERTY, "azerty", "AZERTY"}, - }, - LockMode::LOCK_WHILE_RUNNING, - KeyboardLayout::QWERTY - ) -{} - -CodeEntrySkipPlusOption::CodeEntrySkipPlusOption() - : BooleanCheckBoxOption( - "Skip the Plus:
Don't press + to finalize the code. Useful for testing.", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) -{} - - - - - -DigitEntryTimingsOption::DigitEntryTimingsOption(bool switch2) - : GroupOption( - switch2 - ? "Switch 2 Digit Entry Timings" - : "Switch 1 Digit Entry Timings", - LockMode::UNLOCK_WHILE_RUNNING, - GroupOption::EnableMode::ALWAYS_ENABLED, true - ) - , REORDERING( - "Digit Reordering:
Allow digits to be entered out of order.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , TIME_UNIT( - "Time Unit:
Timesteps should increment in multiples of this unit.
" - "Controller timing variation will be added to this number.", - LockMode::UNLOCK_WHILE_RUNNING, - switch2 - ? "48ms" - : PreloadSettings::instance().DEVELOPER_MODE ? "24 ms" : "40ms" - ) - , HOLD( - "Hold:
Duration to hold each button press down.
" - "Controller timing variation will be added to this number.", - LockMode::UNLOCK_WHILE_RUNNING, - PreloadSettings::instance().DEVELOPER_MODE ? "48 ms" : "80ms" - ) - , COOLDOWN( - "Hold:
Do not reuse a button until this long after it is reused.
" - "Controller timing variation will be added to this number.", - LockMode::UNLOCK_WHILE_RUNNING, - PreloadSettings::instance().DEVELOPER_MODE ? "24 ms" : "40ms" - ) -{ - PA_ADD_OPTION(REORDERING); - PA_ADD_OPTION(TIME_UNIT); - PA_ADD_OPTION(HOLD); - PA_ADD_OPTION(COOLDOWN); -} - - - -KeyboardEntryTimingsOption::KeyboardEntryTimingsOption(bool switch2) - : GroupOption( - switch2 - ? "Switch 2 Keyboard Entry Timings" - : "Switch 1 Keyboard Entry Timings", - LockMode::UNLOCK_WHILE_RUNNING, - GroupOption::EnableMode::ALWAYS_ENABLED, true - ) - , REORDERING( - "Character Reordering:
Allow characters to be entered out of order.", - LockMode::UNLOCK_WHILE_RUNNING, - PreloadSettings::instance().DEVELOPER_MODE - ) - , TIME_UNIT( - "Time Unit:
Timesteps should increment in multiples of this unit.
" - "Controller timing variation will be added to this number.", - LockMode::UNLOCK_WHILE_RUNNING, - switch2 - ? "48ms" - : PreloadSettings::instance().DEVELOPER_MODE ? "24 ms" : "40ms" - ) - , HOLD( - "Hold:
Duration to hold each button press down.
" - "Controller timing variation will be added to this number.", - LockMode::UNLOCK_WHILE_RUNNING, - PreloadSettings::instance().DEVELOPER_MODE ? "48 ms" : "80ms" - ) - , COOLDOWN( - "Hold:
Do not reuse a button until this long after it is reused.
" - "Controller timing variation will be added to this number.", - LockMode::UNLOCK_WHILE_RUNNING, - PreloadSettings::instance().DEVELOPER_MODE ? "24 ms" : "40ms" - ) -{ - PA_ADD_OPTION(REORDERING); - PA_ADD_OPTION(TIME_UNIT); - PA_ADD_OPTION(HOLD); - PA_ADD_OPTION(COOLDOWN); -} - - - - - - - -} -} +/* Code Entry Settings Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "NintendoSwitch_CodeEntrySettingsOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +KeyboardLayoutOption::KeyboardLayoutOption() + : EnumDropdownOption( + "Keyboard Layout:", + { + {KeyboardLayout::QWERTY, "qwerty", "QWERTY"}, + {KeyboardLayout::AZERTY, "azerty", "AZERTY"}, + }, + LockMode::LOCK_WHILE_RUNNING, + KeyboardLayout::QWERTY + ) +{} +KeyboardLayoutOption::KeyboardLayoutOption(std::string label) + : EnumDropdownOption( + std::move(label), + { + {KeyboardLayout::QWERTY, "qwerty", "QWERTY"}, + {KeyboardLayout::AZERTY, "azerty", "AZERTY"}, + }, + LockMode::LOCK_WHILE_RUNNING, + KeyboardLayout::QWERTY + ) +{} + +CodeEntrySkipPlusOption::CodeEntrySkipPlusOption() + : BooleanCheckBoxOption( + "Skip the Plus:
Don't press + to finalize the code. Useful for testing.", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) +{} + + + + + +DigitEntryTimingsOption::DigitEntryTimingsOption(bool switch2) + : GroupOption( + switch2 + ? "Switch 2 Digit Entry Timings" + : "Switch 1 Digit Entry Timings", + LockMode::UNLOCK_WHILE_RUNNING, + GroupOption::EnableMode::ALWAYS_ENABLED, true + ) + , REORDERING( + "Digit Reordering:
Allow digits to be entered out of order.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , TIME_UNIT( + "Time Unit:
Timesteps should increment in multiples of this unit.
" + "Controller timing variation will be added to this number.", + LockMode::UNLOCK_WHILE_RUNNING, + switch2 + ? "48ms" + : PreloadSettings::instance().DEVELOPER_MODE ? "24 ms" : "40ms" + ) + , HOLD( + "Hold:
Duration to hold each button press down.
" + "Controller timing variation will be added to this number.", + LockMode::UNLOCK_WHILE_RUNNING, + PreloadSettings::instance().DEVELOPER_MODE ? "48 ms" : "80ms" + ) + , COOLDOWN( + "Hold:
Do not reuse a button until this long after it is reused.
" + "Controller timing variation will be added to this number.", + LockMode::UNLOCK_WHILE_RUNNING, + PreloadSettings::instance().DEVELOPER_MODE ? "24 ms" : "40ms" + ) +{ + PA_ADD_OPTION(REORDERING); + PA_ADD_OPTION(TIME_UNIT); + PA_ADD_OPTION(HOLD); + PA_ADD_OPTION(COOLDOWN); +} + + + +KeyboardEntryTimingsOption::KeyboardEntryTimingsOption(bool switch2) + : GroupOption( + switch2 + ? "Switch 2 Keyboard Entry Timings" + : "Switch 1 Keyboard Entry Timings", + LockMode::UNLOCK_WHILE_RUNNING, + GroupOption::EnableMode::ALWAYS_ENABLED, true + ) + , REORDERING( + "Character Reordering:
Allow characters to be entered out of order.", + LockMode::UNLOCK_WHILE_RUNNING, + PreloadSettings::instance().DEVELOPER_MODE + ) + , TIME_UNIT( + "Time Unit:
Timesteps should increment in multiples of this unit.
" + "Controller timing variation will be added to this number.", + LockMode::UNLOCK_WHILE_RUNNING, + switch2 + ? "48ms" + : PreloadSettings::instance().DEVELOPER_MODE ? "24 ms" : "40ms" + ) + , HOLD( + "Hold:
Duration to hold each button press down.
" + "Controller timing variation will be added to this number.", + LockMode::UNLOCK_WHILE_RUNNING, + PreloadSettings::instance().DEVELOPER_MODE ? "48 ms" : "80ms" + ) + , COOLDOWN( + "Hold:
Do not reuse a button until this long after it is reused.
" + "Controller timing variation will be added to this number.", + LockMode::UNLOCK_WHILE_RUNNING, + PreloadSettings::instance().DEVELOPER_MODE ? "24 ms" : "40ms" + ) +{ + PA_ADD_OPTION(REORDERING); + PA_ADD_OPTION(TIME_UNIT); + PA_ADD_OPTION(HOLD); + PA_ADD_OPTION(COOLDOWN); +} + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h b/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h index 299091299a..baf8b5356f 100644 --- a/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h +++ b/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h @@ -1,67 +1,67 @@ -/* Code Entry Settings Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_CodeEntrySettingsOption_H -#define PokemonAutomation_NintendoSwitch_CodeEntrySettingsOption_H - -#include "Common/Cpp/Options/GroupOption.h" -//#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -enum class KeyboardLayout{ - QWERTY, - AZERTY -}; -class KeyboardLayoutOption : public EnumDropdownOption{ -public: - KeyboardLayoutOption(); - KeyboardLayoutOption(std::string label); -}; - -class CodeEntrySkipPlusOption : public BooleanCheckBoxOption{ -public: - CodeEntrySkipPlusOption(); -}; - - - - -class DigitEntryTimingsOption : public GroupOption{ -public: - DigitEntryTimingsOption(bool switch2); - -public: - BooleanCheckBoxOption REORDERING; - MillisecondsOption TIME_UNIT; - MillisecondsOption HOLD; - MillisecondsOption COOLDOWN; -}; - -class KeyboardEntryTimingsOption : public GroupOption{ -public: - KeyboardEntryTimingsOption(bool switch2); - -public: - BooleanCheckBoxOption REORDERING; - MillisecondsOption TIME_UNIT; - MillisecondsOption HOLD; - MillisecondsOption COOLDOWN; -}; - - - - - -} -} -#endif +/* Code Entry Settings Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_CodeEntrySettingsOption_H +#define PokemonAutomation_NintendoSwitch_CodeEntrySettingsOption_H + +#include "Common/Cpp/Options/GroupOption.h" +//#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +enum class KeyboardLayout{ + QWERTY, + AZERTY +}; +class KeyboardLayoutOption : public EnumDropdownOption{ +public: + KeyboardLayoutOption(); + KeyboardLayoutOption(std::string label); +}; + +class CodeEntrySkipPlusOption : public BooleanCheckBoxOption{ +public: + CodeEntrySkipPlusOption(); +}; + + + + +class DigitEntryTimingsOption : public GroupOption{ +public: + DigitEntryTimingsOption(bool switch2); + +public: + BooleanCheckBoxOption REORDERING; + MillisecondsOption TIME_UNIT; + MillisecondsOption HOLD; + MillisecondsOption COOLDOWN; +}; + +class KeyboardEntryTimingsOption : public GroupOption{ +public: + KeyboardEntryTimingsOption(bool switch2); + +public: + BooleanCheckBoxOption REORDERING; + MillisecondsOption TIME_UNIT; + MillisecondsOption HOLD; + MillisecondsOption COOLDOWN; +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_ModelType.h b/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_ModelType.h index 290cc8bcfe..423fddd62e 100644 --- a/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_ModelType.h +++ b/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_ModelType.h @@ -1,67 +1,67 @@ -/* Model Type - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_ModelType_H -#define PokemonAutomation_NintendoSwitch_ModelType_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleState.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -inline const EnumDropdownDatabase& CONSOLE_MODEL_DATABASE(){ - static const EnumDropdownDatabase database{ - {ConsoleType::Unknown, "unknown", "Auto-detect if possible."}, - {ConsoleType::Switch1, "switch1", ConsoleType_strings(ConsoleType::Switch1)}, - {ConsoleType::Switch2_Unknown, "switch2-unknown", ConsoleType_strings(ConsoleType::Switch2_Unknown)}, -// {ConsoleType::Switch2_FW19_International, "switch2-FW19-international", ConsoleType_strings(ConsoleType::Switch2_FW19_International)}, -// {ConsoleType::Switch2_FW19_JapanLocked, "switch2-FW19-japan", ConsoleType_strings(ConsoleType::Switch2_FW19_JapanLocked)}, - {ConsoleType::Switch2_FW20_International, "switch2-FW20-international", ConsoleType_strings(ConsoleType::Switch2_FW20_International)}, - {ConsoleType::Switch2_FW20_JapanLocked, "switch2-FW20-japan", ConsoleType_strings(ConsoleType::Switch2_FW20_JapanLocked)}, - }; - return database; -} - - - -class ConsoleModelCell : public EnumDropdownCell{ -public: - ConsoleModelCell() - : EnumDropdownCell( - CONSOLE_MODEL_DATABASE(), - LockMode::LOCK_WHILE_RUNNING, - ConsoleType::Unknown - ) - {} - -private: -}; - - -class ConsoleModelOption : public EnumDropdownOption{ -public: - ConsoleModelOption(std::string label = "Console Type:") - : EnumDropdownOption( - std::move(label), - CONSOLE_MODEL_DATABASE(), - LockMode::LOCK_WHILE_RUNNING, - ConsoleType::Unknown - ) - {} - -private: -}; - - - - - - -} -} -#endif +/* Model Type + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_ModelType_H +#define PokemonAutomation_NintendoSwitch_ModelType_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleState.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +inline const EnumDropdownDatabase& CONSOLE_MODEL_DATABASE(){ + static const EnumDropdownDatabase database{ + {ConsoleType::Unknown, "unknown", "Auto-detect if possible."}, + {ConsoleType::Switch1, "switch1", ConsoleType_strings(ConsoleType::Switch1)}, + {ConsoleType::Switch2_Unknown, "switch2-unknown", ConsoleType_strings(ConsoleType::Switch2_Unknown)}, +// {ConsoleType::Switch2_FW19_International, "switch2-FW19-international", ConsoleType_strings(ConsoleType::Switch2_FW19_International)}, +// {ConsoleType::Switch2_FW19_JapanLocked, "switch2-FW19-japan", ConsoleType_strings(ConsoleType::Switch2_FW19_JapanLocked)}, + {ConsoleType::Switch2_FW20_International, "switch2-FW20-international", ConsoleType_strings(ConsoleType::Switch2_FW20_International)}, + {ConsoleType::Switch2_FW20_JapanLocked, "switch2-FW20-japan", ConsoleType_strings(ConsoleType::Switch2_FW20_JapanLocked)}, + }; + return database; +} + + + +class ConsoleModelCell : public EnumDropdownCell{ +public: + ConsoleModelCell() + : EnumDropdownCell( + CONSOLE_MODEL_DATABASE(), + LockMode::LOCK_WHILE_RUNNING, + ConsoleType::Unknown + ) + {} + +private: +}; + + +class ConsoleModelOption : public EnumDropdownOption{ +public: + ConsoleModelOption(std::string label = "Console Type:") + : EnumDropdownOption( + std::move(label), + CONSOLE_MODEL_DATABASE(), + LockMode::LOCK_WHILE_RUNNING, + ConsoleType::Unknown + ) + {} + +private: +}; + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.cpp index 839c8dba37..aff6a4bdd5 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.cpp @@ -1,271 +1,268 @@ -/* Date Manip - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "NintendoSwitch_DateManip.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -//using namespace std::chrono_literals; - - - - - - - - -DateReader::DateReader(ConsoleHandle& console) - : m_console(console) - , m_switch1(COLOR_RED) - , m_switch2(COLOR_MAGENTA) - , m_background_top(0.50, 0.02, 0.45, 0.08) - , m_window_top(0.50, 0.36, 0.45, 0.07) - , m_window_text(0.05, 0.36, 0.10, 0.07) - , m_us_hour(0.473, 0.61, 0.06, 0.09) - , m_jp_year(0.136, 0.61, 0.11, 0.09) - , m_jp_month_arrow(0.30, 0.50, 0.05, 0.06) - , m_switch1_US(COLOR_YELLOW) - , m_switch1_EU(COLOR_CYAN) - , m_switch1_JP(COLOR_PURPLE) - , m_switch2_US(COLOR_YELLOW) - , m_switch2_EU(COLOR_CYAN) - , m_switch2_JP(COLOR_PURPLE) -{} -void DateReader::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_background_top); - items.add(COLOR_RED, m_window_top); - items.add(COLOR_RED, m_window_text); - items.add(COLOR_RED, m_us_hour); - items.add(COLOR_RED, m_jp_year); - items.add(COLOR_RED, m_jp_month_arrow); - m_switch1_US.make_overlays(items); - m_switch1_EU.make_overlays(items); - m_switch1_JP.make_overlays(items); - m_switch2_US.make_overlays(items); - m_switch2_EU.make_overlays(items); - m_switch2_JP.make_overlays(items); -} -bool DateReader::detect(const ImageViewRGB32& screen){ - ConsoleType type = m_console.state().console_type(); - - if (is_switch1(type)){ - return m_switch1.detect(screen); - } - - if (is_switch2(type)){ - return m_switch2.detect(screen); - } - - throw UserSetupError( - m_console, - "Please select a valid Switch console type." - ); -} - - -std::pair DateReader::read_date(Logger& logger, std::shared_ptr screen){ - if (!detect(*screen)){ - throw_and_log( - logger, ErrorReport::SEND_ERROR_REPORT, - "Not on date change screen.", - nullptr, - std::move(screen) - ); - } - - ConsoleType type = m_console.state().console_type(); - - if (is_switch1(type)){ - switch (m_switch1.detect_date_format(*screen)){ - case DateFormat::US: - return {DateFormat::US, m_switch1_US.read_date(logger, std::move(screen))}; - case DateFormat::EU: - return {DateFormat::EU, m_switch1_EU.read_date(logger, std::move(screen))}; - case DateFormat::JP: - return {DateFormat::JP, m_switch1_JP.read_date(logger, std::move(screen))}; - } - } - - if (is_switch2(type)){ - switch (m_switch2.detect_date_format(*screen)){ - case DateFormat::US: - return {DateFormat::US, m_switch2_US.read_date(logger, std::move(screen))}; - case DateFormat::EU: - return {DateFormat::EU, m_switch2_EU.read_date(logger, std::move(screen))}; - case DateFormat::JP: - return {DateFormat::JP, m_switch2_JP.read_date(logger, std::move(screen))}; - } - } - - throw InternalProgramError( - nullptr, - PA_CURRENT_FUNCTION, - "Unrecognized Console Type: " + std::to_string((int)type) - ); -} - -void DateReader::set_date( - const ProgramInfo& info, ConsoleHandle& console, ProControllerContext& context, - const DateTime& date -){ - context.wait_for_all_requests(); - context.wait_for(std::chrono::milliseconds(250)); - -#if 0 - { - auto snapshot = console.video().snapshot(); - if (!detect(snapshot)){ - throw_and_log( - console.logger(), ErrorReport::SEND_ERROR_REPORT, - "Expected date change menu.", - &console, - snapshot - ); - } - } -#endif - - auto snapshot = console.video().snapshot(); - - if (!detect(snapshot)){ - throw_and_log( - console, ErrorReport::SEND_ERROR_REPORT, - "Not on date change screen.", - nullptr, - snapshot - ); - } - - ConsoleType type = m_console.state().console_type(); - - if (is_switch1(type)){ - switch (m_switch1.detect_date_format(snapshot)){ - case DateFormat::US: - m_switch1_US.set_date(info, console, context, date); - return; - case DateFormat::EU: - m_switch1_EU.set_date(info, console, context, date); - return; - case DateFormat::JP: - m_switch1_JP.set_date(info, console, context, date); - return; - } - } - - if (is_switch2(type)){ - switch (m_switch2.detect_date_format(snapshot)){ - case DateFormat::US: - m_switch2_US.set_date(info, console, context, date); - return; - case DateFormat::EU: - m_switch2_EU.set_date(info, console, context, date); - return; - case DateFormat::JP: - m_switch2_JP.set_date(info, console, context, date); - return; - } - } - - throw InternalProgramError( - nullptr, - PA_CURRENT_FUNCTION, - "Unrecognized Console Type: " + std::to_string((int)type) - ); - - -} - -void change_date( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - const DateTime& date -){ - Milliseconds timing_variation = context->timing_variation(); - while (true){ - context.wait_for_all_requests(); - - HomeMenuWatcher home(env.console); - DateChangeWatcher date_reader(env.console); - int ret = wait_until( - env.console, context, std::chrono::seconds(10), - { - home, - date_reader - } - ); - switch (ret){ - case 0: - home_to_date_time(env.console, context, true); - pbf_press_button(context, BUTTON_A, 80ms + timing_variation, 240ms + timing_variation); - context.wait_for_all_requests(); - continue; - case 1:{ - env.log("Detected date change."); - - // Set the date - VideoOverlaySet overlays(env.console.overlay()); - date_reader.make_overlays(overlays); - date_reader.set_date(env.program_info(), env.console, context, date); - - // Commit the date. - pbf_press_button(context, BUTTON_A, 160ms + timing_variation, 340ms + timing_variation); - - // Re-enter the game. - pbf_press_button(context, BUTTON_HOME, 160ms + timing_variation, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - - return; - } - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to set date", - env.console - ); - } - } -} - - - - - - - - - - - - - - - - - - - - - - - -} -} +/* Date Manip + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "NintendoSwitch_DateManip.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +//using namespace std::chrono_literals; + + + + + + + + +DateReader::DateReader(ConsoleHandle& console) + : m_console(console) + , m_switch1(COLOR_RED) + , m_switch2(COLOR_MAGENTA) + , m_background_top(0.50, 0.02, 0.45, 0.08) + , m_window_top(0.50, 0.36, 0.45, 0.07) + , m_window_text(0.05, 0.36, 0.10, 0.07) + , m_us_hour(0.473, 0.61, 0.06, 0.09) + , m_jp_year(0.136, 0.61, 0.11, 0.09) + , m_jp_month_arrow(0.30, 0.50, 0.05, 0.06) + , m_switch1_US(COLOR_YELLOW) + , m_switch1_EU(COLOR_CYAN) + , m_switch1_JP(COLOR_PURPLE) + , m_switch2_US(COLOR_YELLOW) + , m_switch2_EU(COLOR_CYAN) + , m_switch2_JP(COLOR_PURPLE) +{} +void DateReader::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_background_top); + items.add(COLOR_RED, m_window_top); + items.add(COLOR_RED, m_window_text); + items.add(COLOR_RED, m_us_hour); + items.add(COLOR_RED, m_jp_year); + items.add(COLOR_RED, m_jp_month_arrow); + m_switch1_US.make_overlays(items); + m_switch1_EU.make_overlays(items); + m_switch1_JP.make_overlays(items); + m_switch2_US.make_overlays(items); + m_switch2_EU.make_overlays(items); + m_switch2_JP.make_overlays(items); +} +bool DateReader::detect(const ImageViewRGB32& screen){ + ConsoleType type = m_console.state().console_type(); + + if (is_switch1(type)){ + return m_switch1.detect(screen); + } + + if (is_switch2(type)){ + return m_switch2.detect(screen); + } + + return false; +} + + +std::pair DateReader::read_date(Logger& logger, std::shared_ptr screen){ + if (!detect(*screen)){ + throw_and_log( + logger, ErrorReport::SEND_ERROR_REPORT, + "Not on date change screen.", + nullptr, + std::move(screen) + ); + } + + ConsoleType type = m_console.state().console_type(); + + if (is_switch1(type)){ + switch (m_switch1.detect_date_format(*screen)){ + case DateFormat::US: + return {DateFormat::US, m_switch1_US.read_date(logger, std::move(screen))}; + case DateFormat::EU: + return {DateFormat::EU, m_switch1_EU.read_date(logger, std::move(screen))}; + case DateFormat::JP: + return {DateFormat::JP, m_switch1_JP.read_date(logger, std::move(screen))}; + } + } + + if (is_switch2(type)){ + switch (m_switch2.detect_date_format(*screen)){ + case DateFormat::US: + return {DateFormat::US, m_switch2_US.read_date(logger, std::move(screen))}; + case DateFormat::EU: + return {DateFormat::EU, m_switch2_EU.read_date(logger, std::move(screen))}; + case DateFormat::JP: + return {DateFormat::JP, m_switch2_JP.read_date(logger, std::move(screen))}; + } + } + + throw InternalProgramError( + nullptr, + PA_CURRENT_FUNCTION, + "Unrecognized Console Type: " + std::to_string((int)type) + ); +} + +void DateReader::set_date( + const ProgramInfo& info, ConsoleHandle& console, ProControllerContext& context, + const DateTime& date +){ + context.wait_for_all_requests(); + context.wait_for(std::chrono::milliseconds(250)); + +#if 0 + { + auto snapshot = console.video().snapshot(); + if (!detect(snapshot)){ + throw_and_log( + console.logger(), ErrorReport::SEND_ERROR_REPORT, + "Expected date change menu.", + &console, + snapshot + ); + } + } +#endif + + auto snapshot = console.video().snapshot(); + + if (!detect(snapshot)){ + throw_and_log( + console, ErrorReport::SEND_ERROR_REPORT, + "Not on date change screen.", + nullptr, + snapshot + ); + } + + ConsoleType type = m_console.state().console_type(); + + if (is_switch1(type)){ + switch (m_switch1.detect_date_format(snapshot)){ + case DateFormat::US: + m_switch1_US.set_date(info, console, context, date); + return; + case DateFormat::EU: + m_switch1_EU.set_date(info, console, context, date); + return; + case DateFormat::JP: + m_switch1_JP.set_date(info, console, context, date); + return; + } + } + + if (is_switch2(type)){ + switch (m_switch2.detect_date_format(snapshot)){ + case DateFormat::US: + m_switch2_US.set_date(info, console, context, date); + return; + case DateFormat::EU: + m_switch2_EU.set_date(info, console, context, date); + return; + case DateFormat::JP: + m_switch2_JP.set_date(info, console, context, date); + return; + } + } + + throw InternalProgramError( + nullptr, + PA_CURRENT_FUNCTION, + "Unrecognized Console Type: " + std::to_string((int)type) + ); + + +} + +void change_date( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const DateTime& date +){ + Milliseconds timing_variation = context->timing_variation(); + while (true){ + context.wait_for_all_requests(); + + HomeMenuWatcher home(env.console); + DateChangeWatcher date_reader(env.console); + int ret = wait_until( + env.console, context, std::chrono::seconds(10), + { + home, + date_reader + } + ); + switch (ret){ + case 0: + home_to_date_time(env.console, context, true); + pbf_press_button(context, BUTTON_A, 80ms + timing_variation, 240ms + timing_variation); + context.wait_for_all_requests(); + continue; + case 1:{ + env.log("Detected date change."); + + // Set the date + VideoOverlaySet overlays(env.console.overlay()); + date_reader.make_overlays(overlays); + date_reader.set_date(env.program_info(), env.console, context, date); + + // Commit the date. + pbf_press_button(context, BUTTON_A, 160ms + timing_variation, 340ms + timing_variation); + + // Re-enter the game. + pbf_press_button(context, BUTTON_HOME, 160ms + timing_variation, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + + return; + } + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to set date", + env.console + ); + } + } +} + + + + + + + + + + + + + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h index 5f9b0c5a06..e1803c1b5c 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h @@ -1,85 +1,85 @@ -/* Date Manip - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_DateManip_H -#define PokemonAutomation_NintendoSwitch_DateManip_H - -#include "Common/Cpp/DateTime.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.h" -#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.h" -#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.h" - -namespace PokemonAutomation{ - struct ProgramInfo; - class Logger; -namespace NintendoSwitch{ - - - - -class DateReader : public StaticScreenDetector{ -public: - DateReader(ConsoleHandle& console); - - virtual void make_overlays(VideoOverlaySet& items) const override; - - // Returns true if we are on the date change window. - virtual bool detect(const ImageViewRGB32& screen) override; - - - std::pair read_date(Logger& logger, std::shared_ptr screen); - void set_date( - const ProgramInfo& info, ConsoleHandle& console, ProControllerContext& context, - const DateTime& date // Seconds is ignored. - ); - -private: - ConsoleHandle& m_console; - - DateChangeDetector_Switch1 m_switch1; - DateChangeDetector_Switch2 m_switch2; - - ImageFloatBox m_background_top; - ImageFloatBox m_window_top; - ImageFloatBox m_window_text; - - ImageFloatBox m_us_hour; - ImageFloatBox m_jp_year; - ImageFloatBox m_jp_month_arrow; - - DateReader_Switch1_US m_switch1_US; - DateReader_Switch1_EU m_switch1_EU; - DateReader_Switch1_JP m_switch1_JP; - - DateReader_Switch2_US m_switch2_US; - DateReader_Switch2_EU m_switch2_EU; - DateReader_Switch2_JP m_switch2_JP; -}; - -class DateChangeWatcher : public DetectorToFinder{ -public: - DateChangeWatcher(ConsoleHandle& console, std::chrono::milliseconds duration = std::chrono::milliseconds(250)) - : DetectorToFinder("DateChangeWatcher", duration, console) - {} -}; - -// starting from Home screen, change the date to the desired date -// then go back to the home screen -void change_date( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - const DateTime& date -); - - - -} -} -#endif +/* Date Manip + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_DateManip_H +#define PokemonAutomation_NintendoSwitch_DateManip_H + +#include "Common/Cpp/DateTime.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.h" +#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.h" +#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.h" + +namespace PokemonAutomation{ + struct ProgramInfo; + class Logger; +namespace NintendoSwitch{ + + + + +class DateReader : public StaticScreenDetector{ +public: + DateReader(ConsoleHandle& console); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + // Returns true if we are on the date change window. + virtual bool detect(const ImageViewRGB32& screen) override; + + + std::pair read_date(Logger& logger, std::shared_ptr screen); + void set_date( + const ProgramInfo& info, ConsoleHandle& console, ProControllerContext& context, + const DateTime& date // Seconds is ignored. + ); + +private: + ConsoleHandle& m_console; + + DateChangeDetector_Switch1 m_switch1; + DateChangeDetector_Switch2 m_switch2; + + ImageFloatBox m_background_top; + ImageFloatBox m_window_top; + ImageFloatBox m_window_text; + + ImageFloatBox m_us_hour; + ImageFloatBox m_jp_year; + ImageFloatBox m_jp_month_arrow; + + DateReader_Switch1_US m_switch1_US; + DateReader_Switch1_EU m_switch1_EU; + DateReader_Switch1_JP m_switch1_JP; + + DateReader_Switch2_US m_switch2_US; + DateReader_Switch2_EU m_switch2_EU; + DateReader_Switch2_JP m_switch2_JP; +}; + +class DateChangeWatcher : public DetectorToFinder{ +public: + DateChangeWatcher(ConsoleHandle& console, std::chrono::milliseconds duration = std::chrono::milliseconds(250)) + : DetectorToFinder("DateChangeWatcher", duration, console) + {} +}; + +// starting from Home screen, change the date to the desired date +// then go back to the home screen +void change_date( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + const DateTime& date +); + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipBase.h b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipBase.h index 36fb99f28a..8eeff57fea 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipBase.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipBase.h @@ -1,41 +1,41 @@ -/* Date Manipulation - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_DateManipBase_H -#define PokemonAutomation_NintendoSwitch_DateManipBase_H - -#include -#include "Common/Cpp/DateTime.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - struct ProgramInfo; - class Logger; - class ImageRGB32; - class VideoOverlaySet; - class VideoStream; -namespace NintendoSwitch{ - - -class DateReaderBase{ -public: - virtual void make_overlays(VideoOverlaySet& items) const = 0; - virtual DateTime read_date( - Logger& logger, - std::shared_ptr screen - ) = 0; - virtual void set_date( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - const DateTime& date // Seconds is ignored. - ) = 0; -}; - - - - -} -} -#endif +/* Date Manipulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_DateManipBase_H +#define PokemonAutomation_NintendoSwitch_DateManipBase_H + +#include +#include "Common/Cpp/DateTime.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + struct ProgramInfo; + class Logger; + class ImageRGB32; + class VideoOverlaySet; + class VideoStream; +namespace NintendoSwitch{ + + +class DateReaderBase{ +public: + virtual void make_overlays(VideoOverlaySet& items) const = 0; + virtual DateTime read_date( + Logger& logger, + std::shared_ptr screen + ) = 0; + virtual void set_date( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + const DateTime& date // Seconds is ignored. + ) = 0; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipTools.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipTools.cpp index 6a21695ea4..7f8232ace3 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipTools.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipTools.cpp @@ -1,197 +1,197 @@ -/* Date Manipulation Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonTools/Images/ImageFilter.h" -//#include "CommonTools/OCR/OCR_RawOCR.h" -#include "CommonTools/OCR/OCR_NumberReader.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch_DateManipTools.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace DateReaderTools{ - - - -ImageRGB32 filter_image(const ImageViewRGB32& image){ - double brightness = image_stats(image).average.sum(); - bool white_theme = brightness > 600; - - ImageRGB32 filtered = to_blackwhite_rgb32_range( - image, - white_theme, - 0xff000000, white_theme ? 0xffff7fff : 0xff7f7f7f - ); - return filtered; -} -int read_box( - Logger& logger, - int min, int max, - const ImageViewRGB32& screen, const ImageFloatBox& box -){ - ImageViewRGB32 cropped = extract_box_reference(screen, box); - double brightness = image_stats(cropped).average.sum(); - bool white_theme = brightness > 600; - - int value; - if (white_theme){ - value = OCR::read_number_waterfill( - logger, cropped, - 0xff000000, 0xffff7fff, true - ); - }else{ - value = OCR::read_number_waterfill( - logger, cropped, - 0xff000000, 0xff7f7f7f, false - ); - } - - if (value < min || value > max){ - value = -1; - } - return value; -} - - - -void move_horizontal(ProControllerContext& context, int current, int desired){ - while (current < desired){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - current++; - } - while (current > desired){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT); - current--; - } -} - -void adjust_no_wrap_Switch1(ProControllerContext& context, int current, int desired){ -// cout << "adjust_no_wrap_Switch1(): " << current << " -> " << desired << endl; - - // Invalid read. Change something and hope the next attempt fixes it. - if (current < 0){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); - return; - } - - while (current < desired){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); - current++; - } - while (current > desired){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); - current--; - } -} -void adjust_no_wrap_Switch2(ProControllerContext& context, int current, int desired){ - - // Invalid read. Change something and hope the next attempt fixes it. - if (current < 0){ - ssf_issue_scroll(context, SSF_SCROLL_UP, 112ms, 48ms, 24ms); - return; - } - - while (current < desired){ - ssf_issue_scroll(context, SSF_SCROLL_UP, 112ms, 48ms, 24ms); - current++; - } - while (current > desired){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 112ms, 48ms, 24ms); - current--; - } -} - -void adjust_wrap_Switch1(ProControllerContext& context, int min, int max, int current, int desired){ - // Invalid read. Change something and hope the next attempt fixes it. - if (current < min || current > max){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); - return; - } - - int total = max - min + 1; - int half = total / 2; - - int diff = desired - current; - if ((diff >= 0 && diff <= half) || (diff < 0 && diff < -half)){ - while (current != desired){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); - current++; - if (current > max){ - current -= total; - } - } - }else{ - while (current != desired){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); - current--; - if (current < min){ - current += total; - } - } - } -} -void adjust_wrap_Switch2(ProControllerContext& context, int min, int max, int current, int desired){ - // Invalid read. Change something and hope the next attempt fixes it. - if (current < min || current > max){ - ssf_issue_scroll(context, SSF_SCROLL_UP, 112ms, 48ms, 24ms); - return; - } - - int total = max - min + 1; - int half = total / 2; - - int diff = desired - current; - if ((diff >= 0 && diff <= half) || (diff < 0 && diff < -half)){ - while (current != desired){ - ssf_issue_scroll(context, SSF_SCROLL_UP, 112ms, 48ms, 24ms); - current++; - if (current > max){ - current -= total; - } - } - }else{ - while (current != desired){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 112ms, 48ms, 24ms); - current--; - if (current < min){ - current += total; - } - } - } -} - - - - - - - - - - - - - - - - - - - - - - - - -} -} -} +/* Date Manipulation Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonTools/Images/ImageFilter.h" +//#include "CommonTools/OCR/OCR_RawOCR.h" +#include "CommonTools/OCR/OCR_NumberReader.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch_DateManipTools.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace DateReaderTools{ + + + +ImageRGB32 filter_image(const ImageViewRGB32& image){ + double brightness = image_stats(image).average.sum(); + bool white_theme = brightness > 600; + + ImageRGB32 filtered = to_blackwhite_rgb32_range( + image, + white_theme, + 0xff000000, white_theme ? 0xffff7fff : 0xff7f7f7f + ); + return filtered; +} +int read_box( + Logger& logger, + int min, int max, + const ImageViewRGB32& screen, const ImageFloatBox& box +){ + ImageViewRGB32 cropped = extract_box_reference(screen, box); + double brightness = image_stats(cropped).average.sum(); + bool white_theme = brightness > 600; + + int value; + if (white_theme){ + value = OCR::read_number_waterfill( + logger, cropped, + 0xff000000, 0xffff7fff, true + ); + }else{ + value = OCR::read_number_waterfill( + logger, cropped, + 0xff000000, 0xff7f7f7f, false + ); + } + + if (value < min || value > max){ + value = -1; + } + return value; +} + + + +void move_horizontal(ProControllerContext& context, int current, int desired){ + while (current < desired){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + current++; + } + while (current > desired){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT); + current--; + } +} + +void adjust_no_wrap_Switch1(ProControllerContext& context, int current, int desired){ +// cout << "adjust_no_wrap_Switch1(): " << current << " -> " << desired << endl; + + // Invalid read. Change something and hope the next attempt fixes it. + if (current < 0){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); + return; + } + + while (current < desired){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); + current++; + } + while (current > desired){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + current--; + } +} +void adjust_no_wrap_Switch2(ProControllerContext& context, int current, int desired){ + + // Invalid read. Change something and hope the next attempt fixes it. + if (current < 0){ + ssf_issue_scroll(context, SSF_SCROLL_UP, 112ms, 48ms, 24ms); + return; + } + + while (current < desired){ + ssf_issue_scroll(context, SSF_SCROLL_UP, 112ms, 48ms, 24ms); + current++; + } + while (current > desired){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 112ms, 48ms, 24ms); + current--; + } +} + +void adjust_wrap_Switch1(ProControllerContext& context, int min, int max, int current, int desired){ + // Invalid read. Change something and hope the next attempt fixes it. + if (current < min || current > max){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); + return; + } + + int total = max - min + 1; + int half = total / 2; + + int diff = desired - current; + if ((diff >= 0 && diff <= half) || (diff < 0 && diff < -half)){ + while (current != desired){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); + current++; + if (current > max){ + current -= total; + } + } + }else{ + while (current != desired){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + current--; + if (current < min){ + current += total; + } + } + } +} +void adjust_wrap_Switch2(ProControllerContext& context, int min, int max, int current, int desired){ + // Invalid read. Change something and hope the next attempt fixes it. + if (current < min || current > max){ + ssf_issue_scroll(context, SSF_SCROLL_UP, 112ms, 48ms, 24ms); + return; + } + + int total = max - min + 1; + int half = total / 2; + + int diff = desired - current; + if ((diff >= 0 && diff <= half) || (diff < 0 && diff < -half)){ + while (current != desired){ + ssf_issue_scroll(context, SSF_SCROLL_UP, 112ms, 48ms, 24ms); + current++; + if (current > max){ + current -= total; + } + } + }else{ + while (current != desired){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 112ms, 48ms, 24ms); + current--; + if (current < min){ + current += total; + } + } + } +} + + + + + + + + + + + + + + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipTools.h b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipTools.h index 63c72e09f4..48baa578cd 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipTools.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipTools.h @@ -1,39 +1,39 @@ -/* Date Manipulation Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_DateManipTools_H -#define PokemonAutomation_NintendoSwitch_DateManipTools_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "NintendoSwitch_DateManipBase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace DateReaderTools{ - - - -ImageRGB32 filter_image(const ImageViewRGB32& image); -int read_box( - Logger& logger, - int min, int max, - const ImageViewRGB32& screen, const ImageFloatBox& box -); - -void move_horizontal(ProControllerContext& context, int current, int desired); - -void adjust_no_wrap_Switch1(ProControllerContext& context, int current, int desired); -void adjust_no_wrap_Switch2(ProControllerContext& context, int current, int desired); - -void adjust_wrap_Switch1(ProControllerContext& context, int min, int max, int current, int desired); -void adjust_wrap_Switch2(ProControllerContext& context, int min, int max, int current, int desired); - - - -} -} -} -#endif +/* Date Manipulation Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_DateManipTools_H +#define PokemonAutomation_NintendoSwitch_DateManipTools_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "NintendoSwitch_DateManipBase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace DateReaderTools{ + + + +ImageRGB32 filter_image(const ImageViewRGB32& image); +int read_box( + Logger& logger, + int min, int max, + const ImageViewRGB32& screen, const ImageFloatBox& box +); + +void move_horizontal(ProControllerContext& context, int current, int desired); + +void adjust_no_wrap_Switch1(ProControllerContext& context, int current, int desired); +void adjust_no_wrap_Switch2(ProControllerContext& context, int current, int desired); + +void adjust_wrap_Switch1(ProControllerContext& context, int min, int max, int current, int desired); +void adjust_wrap_Switch2(ProControllerContext& context, int min, int max, int current, int desired); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.cpp index 4d573e4241..ef5e670db8 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.cpp @@ -1,197 +1,197 @@ -/* Date Manipulation (24h) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch_DateManipTools.h" -#include "NintendoSwitch_DateManip_24h.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -DateReader_24h::DateReader_24h(Color color) - : m_color(color) -{} -void DateReader_24h::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_day); - items.add(m_color, m_month); - items.add(m_color, m_year); - items.add(m_color, m_hour); - items.add(m_color, m_minute); -} -DateTime DateReader_24h::read_date(Logger& logger, std::shared_ptr screen){ - logger.log("Attempting to read EU date..."); - - DateTime date; - - date.day = (int8_t)DateReaderTools::read_box(logger, 1, 31, *screen, m_day); - date.month = (int8_t)DateReaderTools::read_box(logger, 1, 12, *screen, m_month); - date.year = (int16_t)DateReaderTools::read_box(logger, 2000, 2060, *screen, m_year); - date.hour = (int8_t)DateReaderTools::read_box(logger, 0, 23, *screen, m_hour); - date.minute = (int8_t)DateReaderTools::read_box(logger, 0, 59, *screen, m_minute); - - return date; -} - - - -DateReader_EU::DateReader_EU(Color color) - : DateReader_24h(color) -{} -void DateReader_EU::set_date( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - const DateTime& date -){ - stream.log("DateReader_EU::set_date()"); - - int cursor_position = 0; - - for (size_t attempts = 0; attempts < 10; attempts++){ - context.wait_for_all_requests(); - context.wait_for(std::chrono::milliseconds(250)); - - auto snapshot = stream.video().snapshot(); - DateTime current = read_date(stream.logger(), snapshot); - if (current.year == date.year && - current.month == date.month && - current.day == date.day && - current.hour == date.hour && - current.minute == date.minute - ){ - move_horizontal(context, cursor_position, 5); - return; - } - - move_horizontal(context, cursor_position, 0); - adjust_no_wrap(context, current.day, date.day); - - move_horizontal(context, cursor_position, 1); - adjust_wrap(context, 1, 12, current.month, date.month); - - move_horizontal(context, cursor_position, 2); - adjust_no_wrap(context, current.year, date.year); - - move_horizontal(context, cursor_position, 3); - adjust_wrap(context, 0, 23, current.hour, date.hour); - - move_horizontal(context, cursor_position, 4); - adjust_wrap(context, 0, 59, current.minute, date.minute); - - move_horizontal(context, cursor_position, 5); - } - - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "Failed to set the hour after 10 attempts.", - stream - ); -} - - -DateReader_Switch1_EU::DateReader_Switch1_EU(Color color) - : DateReader_EU(color) -{ - m_day = ImageFloatBox(0.145, 0.61, 0.06, 0.09); - m_month = ImageFloatBox(0.247, 0.61, 0.06, 0.09); - m_year = ImageFloatBox(0.355, 0.61, 0.11, 0.09); - m_hour = ImageFloatBox(0.528, 0.61, 0.06, 0.09); - m_minute = ImageFloatBox(0.629, 0.61, 0.06, 0.09); -} -DateReader_Switch2_EU::DateReader_Switch2_EU(Color color) - : DateReader_EU(color) -{ - m_day = ImageFloatBox(0.139, 0.436, 0.053, 0.095); - m_month = ImageFloatBox(0.246, 0.436, 0.053, 0.095); - m_year = ImageFloatBox(0.355, 0.436, 0.088, 0.095); - m_hour = ImageFloatBox(0.532, 0.436, 0.053, 0.095); - m_minute = ImageFloatBox(0.645, 0.436, 0.053, 0.095); -} - - - -DateReader_JP::DateReader_JP(Color color) - : DateReader_24h(color) -{} -void DateReader_JP::set_date( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - const DateTime& date -){ - stream.log("DateReader_JP::set_date()"); - - int cursor_position = 0; - - for (size_t attempts = 0; attempts < 10; attempts++){ - context.wait_for_all_requests(); - context.wait_for(std::chrono::milliseconds(250)); - - auto snapshot = stream.video().snapshot(); - DateTime current = read_date(stream.logger(), snapshot); - if (current.year == date.year && - current.month == date.month && - current.day == date.day && - current.hour == date.hour && - current.minute == date.minute - ){ - move_horizontal(context, cursor_position, 5); - return; - } - - move_horizontal(context, cursor_position, 0); - adjust_no_wrap(context, current.year, date.year); - - move_horizontal(context, cursor_position, 1); - adjust_wrap(context, 1, 12, current.month, date.month); - - move_horizontal(context, cursor_position, 2); - adjust_no_wrap(context, current.day, date.day); - - move_horizontal(context, cursor_position, 3); - adjust_wrap(context, 0, 23, current.hour, date.hour); - - move_horizontal(context, cursor_position, 4); - adjust_wrap(context, 0, 59, current.minute, date.minute); - - move_horizontal(context, cursor_position, 5); - } - - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "Failed to set the hour after 10 attempts.", - stream - ); -} - - -DateReader_Switch1_JP::DateReader_Switch1_JP(Color color) - : DateReader_JP(color) -{ - m_year = ImageFloatBox(0.136, 0.61, 0.11, 0.09); - m_month = ImageFloatBox(0.295, 0.61, 0.06, 0.09); - m_day = ImageFloatBox(0.395, 0.61, 0.06, 0.09); - m_hour = ImageFloatBox(0.528, 0.61, 0.06, 0.09); - m_minute = ImageFloatBox(0.629, 0.61, 0.06, 0.09); -} -DateReader_Switch2_JP::DateReader_Switch2_JP(Color color) - : DateReader_JP(color) -{ - m_year = ImageFloatBox(0.139, 0.436, 0.088, 0.095); - m_month = ImageFloatBox(0.292, 0.436, 0.053, 0.095); - m_day = ImageFloatBox(0.410, 0.436, 0.053, 0.095); - m_hour = ImageFloatBox(0.532, 0.436, 0.053, 0.095); - m_minute = ImageFloatBox(0.645, 0.436, 0.053, 0.095); -} - - - - - -} -} +/* Date Manipulation (24h) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch_DateManipTools.h" +#include "NintendoSwitch_DateManip_24h.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +DateReader_24h::DateReader_24h(Color color) + : m_color(color) +{} +void DateReader_24h::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_day); + items.add(m_color, m_month); + items.add(m_color, m_year); + items.add(m_color, m_hour); + items.add(m_color, m_minute); +} +DateTime DateReader_24h::read_date(Logger& logger, std::shared_ptr screen){ + logger.log("Attempting to read EU date..."); + + DateTime date; + + date.day = (int8_t)DateReaderTools::read_box(logger, 1, 31, *screen, m_day); + date.month = (int8_t)DateReaderTools::read_box(logger, 1, 12, *screen, m_month); + date.year = (int16_t)DateReaderTools::read_box(logger, 2000, 2060, *screen, m_year); + date.hour = (int8_t)DateReaderTools::read_box(logger, 0, 23, *screen, m_hour); + date.minute = (int8_t)DateReaderTools::read_box(logger, 0, 59, *screen, m_minute); + + return date; +} + + + +DateReader_EU::DateReader_EU(Color color) + : DateReader_24h(color) +{} +void DateReader_EU::set_date( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + const DateTime& date +){ + stream.log("DateReader_EU::set_date()"); + + int cursor_position = 0; + + for (size_t attempts = 0; attempts < 10; attempts++){ + context.wait_for_all_requests(); + context.wait_for(std::chrono::milliseconds(250)); + + auto snapshot = stream.video().snapshot(); + DateTime current = read_date(stream.logger(), snapshot); + if (current.year == date.year && + current.month == date.month && + current.day == date.day && + current.hour == date.hour && + current.minute == date.minute + ){ + move_horizontal(context, cursor_position, 5); + return; + } + + move_horizontal(context, cursor_position, 0); + adjust_no_wrap(context, current.day, date.day); + + move_horizontal(context, cursor_position, 1); + adjust_wrap(context, 1, 12, current.month, date.month); + + move_horizontal(context, cursor_position, 2); + adjust_no_wrap(context, current.year, date.year); + + move_horizontal(context, cursor_position, 3); + adjust_wrap(context, 0, 23, current.hour, date.hour); + + move_horizontal(context, cursor_position, 4); + adjust_wrap(context, 0, 59, current.minute, date.minute); + + move_horizontal(context, cursor_position, 5); + } + + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "Failed to set the hour after 10 attempts.", + stream + ); +} + + +DateReader_Switch1_EU::DateReader_Switch1_EU(Color color) + : DateReader_EU(color) +{ + m_day = ImageFloatBox(0.145, 0.61, 0.06, 0.09); + m_month = ImageFloatBox(0.247, 0.61, 0.06, 0.09); + m_year = ImageFloatBox(0.355, 0.61, 0.11, 0.09); + m_hour = ImageFloatBox(0.528, 0.61, 0.06, 0.09); + m_minute = ImageFloatBox(0.629, 0.61, 0.06, 0.09); +} +DateReader_Switch2_EU::DateReader_Switch2_EU(Color color) + : DateReader_EU(color) +{ + m_day = ImageFloatBox(0.139, 0.436, 0.053, 0.095); + m_month = ImageFloatBox(0.246, 0.436, 0.053, 0.095); + m_year = ImageFloatBox(0.355, 0.436, 0.088, 0.095); + m_hour = ImageFloatBox(0.532, 0.436, 0.053, 0.095); + m_minute = ImageFloatBox(0.645, 0.436, 0.053, 0.095); +} + + + +DateReader_JP::DateReader_JP(Color color) + : DateReader_24h(color) +{} +void DateReader_JP::set_date( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + const DateTime& date +){ + stream.log("DateReader_JP::set_date()"); + + int cursor_position = 0; + + for (size_t attempts = 0; attempts < 10; attempts++){ + context.wait_for_all_requests(); + context.wait_for(std::chrono::milliseconds(250)); + + auto snapshot = stream.video().snapshot(); + DateTime current = read_date(stream.logger(), snapshot); + if (current.year == date.year && + current.month == date.month && + current.day == date.day && + current.hour == date.hour && + current.minute == date.minute + ){ + move_horizontal(context, cursor_position, 5); + return; + } + + move_horizontal(context, cursor_position, 0); + adjust_no_wrap(context, current.year, date.year); + + move_horizontal(context, cursor_position, 1); + adjust_wrap(context, 1, 12, current.month, date.month); + + move_horizontal(context, cursor_position, 2); + adjust_no_wrap(context, current.day, date.day); + + move_horizontal(context, cursor_position, 3); + adjust_wrap(context, 0, 23, current.hour, date.hour); + + move_horizontal(context, cursor_position, 4); + adjust_wrap(context, 0, 59, current.minute, date.minute); + + move_horizontal(context, cursor_position, 5); + } + + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "Failed to set the hour after 10 attempts.", + stream + ); +} + + +DateReader_Switch1_JP::DateReader_Switch1_JP(Color color) + : DateReader_JP(color) +{ + m_year = ImageFloatBox(0.136, 0.61, 0.11, 0.09); + m_month = ImageFloatBox(0.295, 0.61, 0.06, 0.09); + m_day = ImageFloatBox(0.395, 0.61, 0.06, 0.09); + m_hour = ImageFloatBox(0.528, 0.61, 0.06, 0.09); + m_minute = ImageFloatBox(0.629, 0.61, 0.06, 0.09); +} +DateReader_Switch2_JP::DateReader_Switch2_JP(Color color) + : DateReader_JP(color) +{ + m_year = ImageFloatBox(0.139, 0.436, 0.088, 0.095); + m_month = ImageFloatBox(0.292, 0.436, 0.053, 0.095); + m_day = ImageFloatBox(0.410, 0.436, 0.053, 0.095); + m_hour = ImageFloatBox(0.532, 0.436, 0.053, 0.095); + m_minute = ImageFloatBox(0.645, 0.436, 0.053, 0.095); +} + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.h b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.h index 1cd6b815aa..aa8d379fdc 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.h @@ -1,131 +1,131 @@ -/* Date Manipulation (24h) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_DateManip_24h_H -#define PokemonAutomation_NintendoSwitch_DateManip_24h_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "NintendoSwitch_DateManipTools.h" -#include "NintendoSwitch_DateManipBase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - -class DateReader_24h : public DateReaderBase{ -public: - DateReader_24h(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual DateTime read_date( - Logger& logger, - std::shared_ptr screen - ) override; - -protected: - virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const = 0; - virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const = 0; - virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const = 0; - - -protected: - Color m_color; - ImageFloatBox m_year; - ImageFloatBox m_month; - ImageFloatBox m_day; - ImageFloatBox m_hour; - ImageFloatBox m_minute; -}; - - - - -class DateReader_EU : public DateReader_24h{ -public: - DateReader_EU(Color color); - virtual void set_date( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - const DateTime& date // Seconds is ignored. - ) override; -}; -class DateReader_Switch1_EU : public DateReader_EU{ -public: - DateReader_Switch1_EU(Color color); - virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const override{ - DateReaderTools::move_horizontal(context, current, desired); - current = desired; - } - virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const override{ - DateReaderTools::adjust_no_wrap_Switch1(context, current, desired); - } - virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const override{ - DateReaderTools::adjust_wrap_Switch1(context, min, max, current, desired); - } -}; -class DateReader_Switch2_EU : public DateReader_EU{ -public: - DateReader_Switch2_EU(Color color); - virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const override{ - DateReaderTools::move_horizontal(context, current, desired); - current = desired; - } - virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const override{ - DateReaderTools::adjust_no_wrap_Switch2(context, current, desired); - } - virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const override{ - DateReaderTools::adjust_wrap_Switch2(context, min, max, current, desired); - } -}; - - - - -class DateReader_JP : public DateReader_24h{ -public: - DateReader_JP(Color color); - virtual void set_date( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - const DateTime& date // Seconds is ignored. - ) override; -}; -class DateReader_Switch1_JP : public DateReader_JP{ -public: - DateReader_Switch1_JP(Color color); - virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const override{ - DateReaderTools::move_horizontal(context, current, desired); - current = desired; - } - virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const override{ - DateReaderTools::adjust_no_wrap_Switch1(context, current, desired); - } - virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const override{ - DateReaderTools::adjust_wrap_Switch1(context, min, max, current, desired); - } -}; -class DateReader_Switch2_JP : public DateReader_JP{ -public: - DateReader_Switch2_JP(Color color); - virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const override{ - DateReaderTools::move_horizontal(context, current, desired); - current = desired; - } - virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const override{ - DateReaderTools::adjust_no_wrap_Switch2(context, current, desired); - } - virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const override{ - DateReaderTools::adjust_wrap_Switch2(context, min, max, current, desired); - } -}; - - - - - -} -} -#endif +/* Date Manipulation (24h) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_DateManip_24h_H +#define PokemonAutomation_NintendoSwitch_DateManip_24h_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "NintendoSwitch_DateManipTools.h" +#include "NintendoSwitch_DateManipBase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + +class DateReader_24h : public DateReaderBase{ +public: + DateReader_24h(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual DateTime read_date( + Logger& logger, + std::shared_ptr screen + ) override; + +protected: + virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const = 0; + virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const = 0; + virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const = 0; + + +protected: + Color m_color; + ImageFloatBox m_year; + ImageFloatBox m_month; + ImageFloatBox m_day; + ImageFloatBox m_hour; + ImageFloatBox m_minute; +}; + + + + +class DateReader_EU : public DateReader_24h{ +public: + DateReader_EU(Color color); + virtual void set_date( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + const DateTime& date // Seconds is ignored. + ) override; +}; +class DateReader_Switch1_EU : public DateReader_EU{ +public: + DateReader_Switch1_EU(Color color); + virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const override{ + DateReaderTools::move_horizontal(context, current, desired); + current = desired; + } + virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const override{ + DateReaderTools::adjust_no_wrap_Switch1(context, current, desired); + } + virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const override{ + DateReaderTools::adjust_wrap_Switch1(context, min, max, current, desired); + } +}; +class DateReader_Switch2_EU : public DateReader_EU{ +public: + DateReader_Switch2_EU(Color color); + virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const override{ + DateReaderTools::move_horizontal(context, current, desired); + current = desired; + } + virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const override{ + DateReaderTools::adjust_no_wrap_Switch2(context, current, desired); + } + virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const override{ + DateReaderTools::adjust_wrap_Switch2(context, min, max, current, desired); + } +}; + + + + +class DateReader_JP : public DateReader_24h{ +public: + DateReader_JP(Color color); + virtual void set_date( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + const DateTime& date // Seconds is ignored. + ) override; +}; +class DateReader_Switch1_JP : public DateReader_JP{ +public: + DateReader_Switch1_JP(Color color); + virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const override{ + DateReaderTools::move_horizontal(context, current, desired); + current = desired; + } + virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const override{ + DateReaderTools::adjust_no_wrap_Switch1(context, current, desired); + } + virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const override{ + DateReaderTools::adjust_wrap_Switch1(context, min, max, current, desired); + } +}; +class DateReader_Switch2_JP : public DateReader_JP{ +public: + DateReader_Switch2_JP(Color color); + virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const override{ + DateReaderTools::move_horizontal(context, current, desired); + current = desired; + } + virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const override{ + DateReaderTools::adjust_no_wrap_Switch2(context, current, desired); + } + virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const override{ + DateReaderTools::adjust_wrap_Switch2(context, min, max, current, desired); + } +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.cpp index a1e0f3c9f6..1a856e47e8 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.cpp @@ -1,188 +1,188 @@ -/* Date Manipulation (US) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Qt/StringToolsQt.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/OCR/OCR_RawOCR.h" -#include "CommonTools/OCR/OCR_StringNormalization.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch_DateManipTools.h" -#include "NintendoSwitch_DateManip_US.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - -DateReader_US::DateReader_US(Color color) - : m_color(color) -{} -void DateReader_US::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_month); - items.add(m_color, m_day); - items.add(m_color, m_year); - items.add(m_color, m_hour); - items.add(m_color, m_minute); - items.add(m_color, m_ampm); -} -DateTime DateReader_US::read_date(Logger& logger, std::shared_ptr screen){ - logger.log("Attempting to read US date..."); - - DateTime date; - - date.month = (int8_t)DateReaderTools::read_box(logger, 1, 12, *screen, m_month); - date.day = (int8_t)DateReaderTools::read_box(logger, 1, 31, *screen, m_day); - date.year = (int16_t)DateReaderTools::read_box(logger, 2000, 2060, *screen, m_year); - date.minute = (int8_t)DateReaderTools::read_box(logger, 0, 59, *screen, m_minute); - - // Hour - { - int hour = DateReaderTools::read_box(logger, 1, 12, *screen, m_hour); - if (hour == 12){ - hour = 0; - } - - ImageRGB32 us_ampm_filtered = DateReaderTools::filter_image( - extract_box_reference(*screen, m_ampm) - ); - - std::string ampm_ocr = OCR::ocr_read(Language::English, us_ampm_filtered); - if (ampm_ocr.back() == '\n'){ - ampm_ocr.pop_back(); - } - std::string ampm = to_utf8(OCR::normalize_utf32(ampm_ocr)); - - auto has_a = ampm.find('a') != std::string::npos; - auto has_p = ampm.find('p') != std::string::npos; - - if (has_a && !has_p){ - // Do nothing. - logger.log("OCR Text: \"" + ampm_ocr + "\" -> \"" + ampm + "\" -> AM"); - }else if (!has_a && has_p){ - logger.log("OCR Text: \"" + ampm_ocr + "\" -> \"" + ampm + "\" -> PM"); - hour += 12; - }else{ - logger.log("OCR Text: \"" + ampm_ocr + "\" -> \"" + ampm + "\" -> ??", COLOR_RED); - hour = -1; - } - - date.hour = (int8_t)hour; - } - - return date; -} -void DateReader_US::set_date( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - const DateTime& date -){ - stream.log("DateReader_US::set_date()"); - - int cursor_position = 0; - - for (size_t attempts = 0; attempts < 10; attempts++){ - context.wait_for_all_requests(); - context.wait_for(std::chrono::milliseconds(250)); - - auto snapshot = stream.video().snapshot(); - DateTime current = read_date(stream.logger(), snapshot); - if (current.year == date.year && - current.month == date.month && - current.day == date.day && - current.hour == date.hour && - current.minute == date.minute - ){ - move_horizontal(context, cursor_position, 6); - return; - } - - move_horizontal(context, cursor_position, 0); - adjust_wrap(context, 1, 12, current.month, date.month); - - move_horizontal(context, cursor_position, 1); - adjust_no_wrap(context, current.day, date.day); - - move_horizontal(context, cursor_position, 2); - adjust_no_wrap(context, current.year, date.year); - - move_horizontal(context, cursor_position, 3); - { - int8_t c = current.hour; - int8_t t = date.hour; - if (c >= 12) c -= 12; - if (t >= 12) t -= 12; - adjust_wrap(context, 0, 11, c, t); - } - - move_horizontal(context, cursor_position, 4); - adjust_wrap(context, 0, 59, current.minute, date.minute); - - move_horizontal(context, cursor_position, 5); - if ((date.hour < 12) != (current.hour < 12)){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); - } - - move_horizontal(context, cursor_position, 6); - } - - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "Failed to set the hour after 10 attempts.", - stream - ); -} - - - - -DateReader_Switch1_US::DateReader_Switch1_US(Color color) - : DateReader_US(color) -{ - m_month = ImageFloatBox(0.090, 0.61, 0.06, 0.09); - m_day = ImageFloatBox(0.193, 0.61, 0.06, 0.09); - m_year = ImageFloatBox(0.300, 0.61, 0.11, 0.09); - m_hour = ImageFloatBox(0.473, 0.61, 0.06, 0.09); - m_minute = ImageFloatBox(0.574, 0.61, 0.06, 0.09); - m_ampm = ImageFloatBox(0.663, 0.61, 0.07, 0.09); -} -DateReader_Switch2_US::DateReader_Switch2_US(Color color) - : DateReader_US(color) -{ - m_month = ImageFloatBox(0.080, 0.436, 0.053, 0.095); - m_day = ImageFloatBox(0.188, 0.436, 0.053, 0.095); - m_year = ImageFloatBox(0.298, 0.436, 0.088, 0.095); - m_hour = ImageFloatBox(0.463, 0.436, 0.053, 0.095); - m_minute = ImageFloatBox(0.575, 0.436, 0.053, 0.095); - m_ampm = ImageFloatBox(0.671, 0.436, 0.080, 0.095); -} - - - - - - - - - - - - - - - - - - - - - - -} -} +/* Date Manipulation (US) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Qt/StringToolsQt.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/OCR/OCR_RawOCR.h" +#include "CommonTools/OCR/OCR_StringNormalization.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch_DateManipTools.h" +#include "NintendoSwitch_DateManip_US.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + +DateReader_US::DateReader_US(Color color) + : m_color(color) +{} +void DateReader_US::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_month); + items.add(m_color, m_day); + items.add(m_color, m_year); + items.add(m_color, m_hour); + items.add(m_color, m_minute); + items.add(m_color, m_ampm); +} +DateTime DateReader_US::read_date(Logger& logger, std::shared_ptr screen){ + logger.log("Attempting to read US date..."); + + DateTime date; + + date.month = (int8_t)DateReaderTools::read_box(logger, 1, 12, *screen, m_month); + date.day = (int8_t)DateReaderTools::read_box(logger, 1, 31, *screen, m_day); + date.year = (int16_t)DateReaderTools::read_box(logger, 2000, 2060, *screen, m_year); + date.minute = (int8_t)DateReaderTools::read_box(logger, 0, 59, *screen, m_minute); + + // Hour + { + int hour = DateReaderTools::read_box(logger, 1, 12, *screen, m_hour); + if (hour == 12){ + hour = 0; + } + + ImageRGB32 us_ampm_filtered = DateReaderTools::filter_image( + extract_box_reference(*screen, m_ampm) + ); + + std::string ampm_ocr = OCR::ocr_read(Language::English, us_ampm_filtered); + if (ampm_ocr.back() == '\n'){ + ampm_ocr.pop_back(); + } + std::string ampm = to_utf8(OCR::normalize_utf32(ampm_ocr)); + + auto has_a = ampm.find('a') != std::string::npos; + auto has_p = ampm.find('p') != std::string::npos; + + if (has_a && !has_p){ + // Do nothing. + logger.log("OCR Text: \"" + ampm_ocr + "\" -> \"" + ampm + "\" -> AM"); + }else if (!has_a && has_p){ + logger.log("OCR Text: \"" + ampm_ocr + "\" -> \"" + ampm + "\" -> PM"); + hour += 12; + }else{ + logger.log("OCR Text: \"" + ampm_ocr + "\" -> \"" + ampm + "\" -> ??", COLOR_RED); + hour = -1; + } + + date.hour = (int8_t)hour; + } + + return date; +} +void DateReader_US::set_date( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + const DateTime& date +){ + stream.log("DateReader_US::set_date()"); + + int cursor_position = 0; + + for (size_t attempts = 0; attempts < 10; attempts++){ + context.wait_for_all_requests(); + context.wait_for(std::chrono::milliseconds(250)); + + auto snapshot = stream.video().snapshot(); + DateTime current = read_date(stream.logger(), snapshot); + if (current.year == date.year && + current.month == date.month && + current.day == date.day && + current.hour == date.hour && + current.minute == date.minute + ){ + move_horizontal(context, cursor_position, 6); + return; + } + + move_horizontal(context, cursor_position, 0); + adjust_wrap(context, 1, 12, current.month, date.month); + + move_horizontal(context, cursor_position, 1); + adjust_no_wrap(context, current.day, date.day); + + move_horizontal(context, cursor_position, 2); + adjust_no_wrap(context, current.year, date.year); + + move_horizontal(context, cursor_position, 3); + { + int8_t c = current.hour; + int8_t t = date.hour; + if (c >= 12) c -= 12; + if (t >= 12) t -= 12; + adjust_wrap(context, 0, 11, c, t); + } + + move_horizontal(context, cursor_position, 4); + adjust_wrap(context, 0, 59, current.minute, date.minute); + + move_horizontal(context, cursor_position, 5); + if ((date.hour < 12) != (current.hour < 12)){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + } + + move_horizontal(context, cursor_position, 6); + } + + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "Failed to set the hour after 10 attempts.", + stream + ); +} + + + + +DateReader_Switch1_US::DateReader_Switch1_US(Color color) + : DateReader_US(color) +{ + m_month = ImageFloatBox(0.090, 0.61, 0.06, 0.09); + m_day = ImageFloatBox(0.193, 0.61, 0.06, 0.09); + m_year = ImageFloatBox(0.300, 0.61, 0.11, 0.09); + m_hour = ImageFloatBox(0.473, 0.61, 0.06, 0.09); + m_minute = ImageFloatBox(0.574, 0.61, 0.06, 0.09); + m_ampm = ImageFloatBox(0.663, 0.61, 0.07, 0.09); +} +DateReader_Switch2_US::DateReader_Switch2_US(Color color) + : DateReader_US(color) +{ + m_month = ImageFloatBox(0.080, 0.436, 0.053, 0.095); + m_day = ImageFloatBox(0.188, 0.436, 0.053, 0.095); + m_year = ImageFloatBox(0.298, 0.436, 0.088, 0.095); + m_hour = ImageFloatBox(0.463, 0.436, 0.053, 0.095); + m_minute = ImageFloatBox(0.575, 0.436, 0.053, 0.095); + m_ampm = ImageFloatBox(0.671, 0.436, 0.080, 0.095); +} + + + + + + + + + + + + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.h b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.h index 51b57cf8af..8dfec7e86a 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.h @@ -1,87 +1,87 @@ -/* Date Manipulation (US) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_DateManip_US_H -#define PokemonAutomation_NintendoSwitch_DateManip_US_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "NintendoSwitch_DateManipTools.h" -#include "NintendoSwitch_DateManipBase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -class DateReader_US : public DateReaderBase{ -public: - DateReader_US(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual DateTime read_date( - Logger& logger, - std::shared_ptr screen - ) override; - virtual void set_date( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - const DateTime& date // Seconds is ignored. - ) override; - -protected: - virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const = 0; - virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const = 0; - virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const = 0; - -protected: - Color m_color; - ImageFloatBox m_month; - ImageFloatBox m_day; - ImageFloatBox m_year; - ImageFloatBox m_hour; - ImageFloatBox m_minute; - ImageFloatBox m_ampm; -}; - - - -class DateReader_Switch1_US : public DateReader_US{ -public: - DateReader_Switch1_US(Color color); - virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const override{ - DateReaderTools::move_horizontal(context, current, desired); - current = desired; - } - virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const override{ - DateReaderTools::adjust_no_wrap_Switch1(context, current, desired); - } - virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const override{ - DateReaderTools::adjust_wrap_Switch1(context, min, max, current, desired); - } -}; -class DateReader_Switch2_US : public DateReader_US{ -public: - DateReader_Switch2_US(Color color); - virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const override{ - DateReaderTools::move_horizontal(context, current, desired); - current = desired; - } - virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const override{ - DateReaderTools::adjust_no_wrap_Switch2(context, current, desired); - } - virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const override{ - DateReaderTools::adjust_wrap_Switch2(context, min, max, current, desired); - } -}; - - - - - - - -} -} -#endif +/* Date Manipulation (US) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_DateManip_US_H +#define PokemonAutomation_NintendoSwitch_DateManip_US_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "NintendoSwitch_DateManipTools.h" +#include "NintendoSwitch_DateManipBase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +class DateReader_US : public DateReaderBase{ +public: + DateReader_US(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual DateTime read_date( + Logger& logger, + std::shared_ptr screen + ) override; + virtual void set_date( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + const DateTime& date // Seconds is ignored. + ) override; + +protected: + virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const = 0; + virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const = 0; + virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const = 0; + +protected: + Color m_color; + ImageFloatBox m_month; + ImageFloatBox m_day; + ImageFloatBox m_year; + ImageFloatBox m_hour; + ImageFloatBox m_minute; + ImageFloatBox m_ampm; +}; + + + +class DateReader_Switch1_US : public DateReader_US{ +public: + DateReader_Switch1_US(Color color); + virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const override{ + DateReaderTools::move_horizontal(context, current, desired); + current = desired; + } + virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const override{ + DateReaderTools::adjust_no_wrap_Switch1(context, current, desired); + } + virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const override{ + DateReaderTools::adjust_wrap_Switch1(context, min, max, current, desired); + } +}; +class DateReader_Switch2_US : public DateReader_US{ +public: + DateReader_Switch2_US(Color color); + virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const override{ + DateReaderTools::move_horizontal(context, current, desired); + current = desired; + } + virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const override{ + DateReaderTools::adjust_no_wrap_Switch2(context, current, desired); + } + virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const override{ + DateReaderTools::adjust_wrap_Switch2(context, min, max, current, desired); + } +}; + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch1_HomeToDateTime.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch1_HomeToDateTime.cpp index 400e70084f..4db8d50f1d 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch1_HomeToDateTime.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch1_HomeToDateTime.cpp @@ -1,337 +1,398 @@ -/* Nintendo Switch 2 Home To Date-Time - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -//#include "CommonFramework/VideoPipeline/VideoFeed.h" -//#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -//#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" -#include "NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - -void home_to_date_time_Switch1_wired_blind( - Logger& logger, ProControllerContext& context, bool to_date_change -){ - logger.log("home_to_date_time_Switch1_wired_blind()"); - - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 4); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 4); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 4); - - // Down twice in case we drop one. - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 3); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 4); - - ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0); - - // Two A presses in case we drop the 1st one. - ssf_press_button(context, BUTTON_A, 3); - ssf_press_button(context, BUTTON_A, 3); - - // Just button mash it. lol - { - auto iterations = Milliseconds(1200) / 24ms + 1; - do{ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); - }while (--iterations); - } - - // Scroll left and press A to exit the sleep menu if we happened to - // land there. - ssf_issue_scroll(context, SSF_SCROLL_LEFT, 3); - ssf_press_button(context, BUTTON_A, 3); - - { - auto iterations = Milliseconds(312) / 24ms + 1; - do{ - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms); - }while (--iterations); - } - - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 3); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 3); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 10); - ssf_press_dpad(context, DPAD_DOWN, 45, 40); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 3); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 3); - - if (!to_date_change){ - // Triple up this A press to make sure it gets through. - ssf_press_button(context, BUTTON_A, 3); - ssf_press_button(context, BUTTON_A, 3); - ssf_press_button(context, BUTTON_A, 45); - return; - } - - // Triple up this A press to make sure it gets through. - ssf_press_button(context, BUTTON_A, 3); - ssf_press_button(context, BUTTON_A, 3); - ssf_press_button(context, BUTTON_A, 3); - { - auto iterations = Milliseconds(250) / 24ms + 1; - do{ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); - }while (--iterations); - } -// ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0); - - // Left scroll in case we missed and landed in the language change or sleep - // confirmation menus. - ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms); -} -void home_to_date_time_Switch1_wireless_esp32_blind( - Logger& logger, ProControllerContext& context, bool to_date_change -){ - logger.log("home_to_date_time_Switch1_wireless_esp32_blind()"); - - Milliseconds tv = context->timing_variation(); - Milliseconds unit = 24ms + tv; - - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - - // Down twice in case we drop one. - ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); - - ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms, 2*unit, unit); - - // Press A multiple times to make sure one goes through. - pbf_press_button(context, BUTTON_A, 2*unit, unit); - pbf_press_button(context, BUTTON_A, 2*unit, unit); - pbf_press_button(context, BUTTON_A, 2*unit, unit); - - // Just button mash it. lol - { - auto iterations = Milliseconds(1100) / unit + 1; - do{ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); - }while (--iterations); - } - - // Scroll left and press A to exit the sleep menu if we happened to - // land there. - ssf_issue_scroll(context, SSF_SCROLL_LEFT, unit); - ssf_press_button(context, BUTTON_A, unit, 2*unit, unit); - - { - auto iterations = Milliseconds(312) / unit + 1; - do{ - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - }while (--iterations); - } - - ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 400ms, 2*unit, unit); - ssf_press_dpad(context, DPAD_DOWN, 360ms, 304ms); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); - - if (!to_date_change){ - // Triple up this A press to make sure it gets through. - ssf_press_button(context, BUTTON_A, unit); - ssf_press_button(context, BUTTON_A, unit); - ssf_press_button(context, BUTTON_A, 360ms, 2*unit, unit); - return; - } - - // Triple up this A press to make sure it gets through. - ssf_press_button(context, BUTTON_A, unit); - ssf_press_button(context, BUTTON_A, unit); - ssf_press_button(context, BUTTON_A, unit); - { - auto iterations = Milliseconds(250) / unit + 1; - do{ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); - }while (--iterations); - } - - // Left scroll in case we missed landed in the language change or sleep - // confirmation menus. - ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms, 2*unit, unit); - -} -void home_to_date_time_Switch1_sbb_blind( - Logger& logger, ProControllerContext& context, bool to_date_change -){ - logger.log("home_to_date_time_Switch1_sbb_blind()"); - - Milliseconds tv = context->timing_variation(); -// ssf_do_nothing(context, 1500ms); - - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - - // Down twice in case we drop one. - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); -// ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); - - ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT); - - // Press A multiple times to make sure one goes through. - ssf_mash1_button(context, BUTTON_A, 200ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN, 2500ms, 2500ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT, 500ms, 500ms); - - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 500ms, tv, tv); - ssf_press_right_joystick(context, 128, 224, 1000ms, 300ms, tv); -// ssf_issue_scroll(context, SSF_SCROLL_DOWN, 1000ms, 250ms, tv); // Scroll down - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); - - if (!to_date_change){ - ssf_press_button_ptv(context, BUTTON_A); - return; - } - - ssf_press_button_ptv(context, BUTTON_A, 1000ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); -} - - - - - -void home_to_date_time_Switch1_wired_feedback( - VideoStream& stream, ProControllerContext& context, bool to_date_change -){ - stream.log("home_to_date_time_Switch1_wired_with_feedback()"); - - size_t max_attempts = 5; - for (size_t i = 0; i < max_attempts; i++){ - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 4); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 4); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 4); - - // Down twice in case we drop one. - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 3); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 4); - - // if (i > 0){ // intentionally create a failure, for testing - ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0); - // } - - - // ImageFloatBox system_icon(0.685, 0.69, 0.05, 0.03); - // ImageFloatBox other_setting1(0.615, 0.69, 0.05, 0.03); - // ImageFloatBox other_setting2(0.545, 0.69, 0.05, 0.03); - - // Two A presses in case we drop the 1st one. - // the program can self recover even if the second button press is registered. - ssf_press_button(context, BUTTON_A, 3); - ssf_press_button(context, BUTTON_A, 3); - - // Just button mash it. lol - { - auto iterations = Milliseconds(1200) / 24ms + 1; - do{ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); - }while (--iterations); - } - - context.wait_for_all_requests(); - // Should now be in System Settings, with System highlighted - ImageFloatBox system_setting_box(0.056, 0.74, 0.01, 0.1); - ImageFloatBox other_setting1(0.04, 0.74, 0.01, 0.1); - ImageFloatBox other_setting2(0.02, 0.74, 0.01, 0.1); - SelectedSettingWatcher system_setting_selected(system_setting_box, other_setting1, other_setting2); - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - for (int i = 0; i < 10; i++){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); - } - }, - {system_setting_selected} - ); - if (ret < 0){ // failed to detect "System" being highlighted. press home and re-try - pbf_press_button(context, BUTTON_HOME, 100ms, 2000ms); - continue; - } - - - { - auto iterations = Milliseconds(312) / 24ms + 1; - do{ - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms); - }while (--iterations); - } - - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 3); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 3); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 10); - ssf_press_dpad(context, DPAD_DOWN, 45, 40); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 3); - // if (i > 1){ // intentionally create a failure, for testing - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 3); - // } - - // only one ButtonA press since the program can self-recover if the button is dropped. - // furthermore, the program can't self-recover if a second button press is registered. - ssf_press_button(context, BUTTON_A, 3); - - context.wait_for_all_requests(); - context.wait_for(Milliseconds(300)); - // we expect to be within "Date and Time", with "Synchronize Clock via Internet" being highlighted - ImageFloatBox sync_clock_box(0.168, 0.185, 0.01, 0.1); - ImageFloatBox other_setting3(0.1, 0.185, 0.01, 0.1); - ImageFloatBox other_setting4(0.05, 0.185, 0.01, 0.1); - SelectedSettingWatcher sync_clock_selected(sync_clock_box, other_setting3, other_setting4); - ret = wait_until( - stream, context, - Milliseconds(2000), - {sync_clock_selected} - ); - if (ret < 0){ // failed to detect "Synchronize clock" being highlighted. press home and re-try - pbf_press_button(context, BUTTON_HOME, 100ms, 2000ms); - continue; - } - - - if (!to_date_change){ - return; - } - - { - auto iterations = Milliseconds(250) / 24ms + 1; - do{ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); - }while (--iterations); - } - - // Left scroll in case we missed landed in the language change or sleep - // confirmation menus. - ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms); - - return; - } - - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "home_to_date_time(): Failed to reach Date and Time after several attempts.", - stream - ); - -} - - - -} -} +/* Nintendo Switch 2 Home To Date-Time + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +//#include "CommonFramework/VideoPipeline/VideoFeed.h" +//#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +//#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + +void home_to_date_time_Switch1_wired_blind( + Logger& logger, ProControllerContext& context, bool to_date_change +){ + logger.log("home_to_date_time_Switch1_wired_blind()"); + + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 32ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 32ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 32ms); + + // Down twice in case we drop one. + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 32ms); + + ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms, 48ms, 24ms); + + // Two A presses in case we drop the 1st one. + ssf_press_button(context, BUTTON_A, 24ms, 40ms, 24ms); + ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); + + // Just button mash it. lol + { + auto iterations = Milliseconds(1200) / 24ms + 1; + do{ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + }while (--iterations); + } + + // Scroll left and press A to exit the sleep menu if we happened to + // land there. + ssf_issue_scroll(context, SSF_SCROLL_LEFT, 24ms); + ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); + + { + auto iterations = Milliseconds(312) / 24ms + 1; + do{ + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms); + }while (--iterations); + } + + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 80ms, 40ms, 24ms); + ssf_press_dpad(context, DPAD_DOWN, 360ms, 320ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + + if (!to_date_change){ + // Triple up this A press to make sure it gets through. + ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_A, 360ms, 48ms, 24ms); + return; + } + + // Triple up this A press to make sure it gets through. + ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); + { + auto iterations = Milliseconds(250) / 24ms + 1; + do{ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + }while (--iterations); + } +// ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0); + + // Left scroll in case we missed and landed in the language change or sleep + // confirmation menus. + ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms); +} +void home_to_date_time_Switch1_wireless_esp32_blind( + Logger& logger, ProControllerContext& context, bool to_date_change +){ + logger.log("home_to_date_time_Switch1_wireless_esp32_blind()"); + + Milliseconds tv = context->timing_variation(); + Milliseconds unit = 24ms + tv; + + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + + // Down twice in case we drop one. + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + + ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms, 2*unit, unit); + + // Press A multiple times to make sure one goes through. + pbf_press_button(context, BUTTON_A, 2*unit, unit); + pbf_press_button(context, BUTTON_A, 2*unit, unit); + pbf_press_button(context, BUTTON_A, 2*unit, unit); + + // Just button mash it. lol + { + auto iterations = Milliseconds(1100) / unit + 1; + do{ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + }while (--iterations); + } + + // Scroll left and press A to exit the sleep menu if we happened to + // land there. + ssf_issue_scroll(context, SSF_SCROLL_LEFT, unit); + ssf_press_button(context, BUTTON_A, unit, 2*unit, unit); + + { + auto iterations = Milliseconds(312) / unit + 1; + do{ + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + }while (--iterations); + } + + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 400ms, 2*unit, unit); + ssf_press_dpad(context, DPAD_DOWN, 360ms, 304ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + + if (!to_date_change){ + // Triple up this A press to make sure it gets through. + ssf_press_button(context, BUTTON_A, unit); + ssf_press_button(context, BUTTON_A, unit); + ssf_press_button(context, BUTTON_A, 360ms, 2*unit, unit); + return; + } + + // Triple up this A press to make sure it gets through. + ssf_press_button(context, BUTTON_A, unit); + ssf_press_button(context, BUTTON_A, unit); + ssf_press_button(context, BUTTON_A, unit); + { + auto iterations = Milliseconds(250) / unit + 1; + do{ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + }while (--iterations); + } + + // Left scroll in case we missed landed in the language change or sleep + // confirmation menus. + ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms, 2*unit, unit); + +} +void home_to_date_time_Switch1_sbb_blind( + Logger& logger, ProControllerContext& context, bool to_date_change +){ + logger.log("home_to_date_time_Switch1_sbb_blind()"); + + Milliseconds tv = context->timing_variation(); +// ssf_do_nothing(context, 1500ms); + + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + + // Down twice in case we drop one. + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); +// ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + + ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT); + + // Press A multiple times to make sure one goes through. + ssf_mash1_button(context, BUTTON_A, 200ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN, 2500ms, 2500ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT, 500ms, 500ms); + + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 500ms, tv, tv); + ssf_press_right_joystick(context, 128, 224, 1000ms, 300ms, tv); +// ssf_issue_scroll(context, SSF_SCROLL_DOWN, 1000ms, 250ms, tv); // Scroll down + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + + if (!to_date_change){ + ssf_press_button_ptv(context, BUTTON_A); + return; + } + + ssf_press_button_ptv(context, BUTTON_A, 1000ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); +} + + +void home_to_date_time_Switch1_wired_feedback( + VideoStream& stream, ProControllerContext& context, bool to_date_change +){ + stream.log("home_to_date_time_Switch1_wired_with_feedback()"); + + size_t max_attempts = 5; + for (size_t i = 0; i < max_attempts; i++){ + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 32ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 32ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 32ms); + + // Down twice in case we drop one. + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 32ms); + + // if (i > 0){ // intentionally create a failure, for testing + ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms, 40ms, 24ms); + // } + + + // ImageFloatBox system_icon(0.685, 0.69, 0.05, 0.03); + // ImageFloatBox other_setting1(0.615, 0.69, 0.05, 0.03); + // ImageFloatBox other_setting2(0.545, 0.69, 0.05, 0.03); + + // Two A presses in case we drop the 1st one. + // the program can self recover even if the second button press is registered. + ssf_press_button(context, BUTTON_A, 24ms, 40ms, 24ms); + ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); + + // Just button mash it. lol + { + auto iterations = Milliseconds(1200) / 24ms + 1; + do{ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + }while (--iterations); + } + + context.wait_for_all_requests(); + // Should now be in System Settings, with System highlighted + ImageFloatBox system_setting_box(0.056, 0.74, 0.01, 0.1); + ImageFloatBox other_setting1(0.04, 0.74, 0.01, 0.1); + ImageFloatBox other_setting2(0.02, 0.74, 0.01, 0.1); + SelectedSettingWatcher system_setting_selected(system_setting_box, other_setting1, other_setting2); + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + for (int i = 0; i < 10; i++){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + } + }, + {system_setting_selected} + ); + if (ret < 0){ // failed to detect "System" being highlighted. press home and re-try + pbf_press_button(context, BUTTON_HOME, 100ms, 2000ms); + continue; + } + + + { + auto iterations = Milliseconds(312) / 24ms + 1; + do{ + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms); + }while (--iterations); + } + + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 80ms, 40ms, 24ms); + ssf_press_dpad(context, DPAD_DOWN, 360ms, 320ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + // if (i > 1){ // intentionally create a failure, for testing + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + // } + + // only one ButtonA press since the program can self-recover if the button is dropped. + // furthermore, the program can't self-recover if a second button press is registered. + ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); + + context.wait_for_all_requests(); + context.wait_for(Milliseconds(300)); + // we expect to be within "Date and Time", with "Synchronize Clock via Internet" being highlighted + ImageFloatBox sync_clock_box(0.168, 0.185, 0.01, 0.1); + ImageFloatBox other_setting3(0.1, 0.185, 0.01, 0.1); + ImageFloatBox other_setting4(0.05, 0.185, 0.01, 0.1); + SelectedSettingWatcher sync_clock_selected(sync_clock_box, other_setting3, other_setting4); + ret = wait_until( + stream, context, + Milliseconds(2000), + {sync_clock_selected} + ); + if (ret < 0){ // failed to detect "Synchronize clock" being highlighted. press home and re-try + pbf_press_button(context, BUTTON_HOME, 100ms, 2000ms); + continue; + } + + + if (!to_date_change){ + return; + } + + { + auto iterations = Milliseconds(250) / 24ms + 1; + do{ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + }while (--iterations); + } + + // Left scroll in case we missed landed in the language change or sleep + // confirmation menus. + ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms); + + return; + } + + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "home_to_date_time(): Failed to reach Date and Time after several attempts.", + stream + ); + +} + + + + + + +void home_to_date_time_Switch1_joycon_blind(JoyconContext& context, bool to_date_change){ + Milliseconds tv = context->timing_variation(); + Milliseconds unit = 100ms + tv; + + //From ControllerPerformanceClass::SerialPABotBase_Wireless + //as Joycon will only have that controller type + + pbf_move_joystick(context, 255, 128, 2*unit, unit); + pbf_move_joystick(context, 255, 128, 2*unit, unit); + pbf_move_joystick(context, 255, 128, 2*unit, unit); + + // Down twice in case we drop one. + pbf_move_joystick(context, 128, 255, 2*unit, unit); + pbf_move_joystick(context, 128, 255, 2*unit, unit); + + pbf_move_joystick(context, 0, 128, 2*unit, unit); + + // Press A multiple times to make sure one goes through. + pbf_press_button(context, BUTTON_A, 2*unit, unit); + pbf_press_button(context, BUTTON_A, 2*unit, unit); + pbf_press_button(context, BUTTON_A, 2*unit, unit); + + // Scroll to System, move right to top option (update) + pbf_move_joystick(context, 128, 255, 2500ms, unit); + pbf_move_joystick(context, 255, 128, 500ms, unit); + + // To date/time + pbf_move_joystick(context, 128, 255, 2*unit, unit); + pbf_move_joystick(context, 128, 255, 2*unit, unit); + context.wait_for_all_requests(); + pbf_move_joystick(context, 128, 255, 525ms, unit); + //pbf_move_joystick(context, 128, 255, 365ms, 305ms); + pbf_move_joystick(context, 128, 255, 2*unit, unit); + //pbf_move_joystick(context, 128, 255, 2*unit, unit); + context.wait_for_all_requests(); + + if (!to_date_change){ + ssf_press_button(context, BUTTON_A, 360ms, 2*unit, unit); + return; + } + + //ssf_press_button(context, BUTTON_A, unit); + pbf_press_button(context, BUTTON_A, 2*unit, unit); + context.wait_for_all_requests(); + { + auto iterations = Milliseconds(216) / unit + 1; + do{ + pbf_move_joystick(context, 128, 255, 2*unit, unit); + }while (--iterations); + } + pbf_move_joystick(context, 128, 255, 2*unit, 0ms); +} + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch2_HomeToDateTime.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch2_HomeToDateTime.cpp index cbd1999ad7..5cc1fd17d2 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch2_HomeToDateTime.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch2_HomeToDateTime.cpp @@ -1,190 +1,259 @@ -/* Nintendo Switch 2 Home To Date-Time - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -void home_to_settings_Switch2_wired_blind( - ProControllerContext& context -){ - Milliseconds delay = 24ms; - Milliseconds hold = 48ms; - Milliseconds cool = 24ms; - - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay, hold, cool); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay, hold, cool); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay, hold, cool); - - // Down twice in case we drop one. - ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay, hold, cool); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay, hold, cool); - - ssf_issue_scroll(context, SSF_SCROLL_LEFT, delay, hold, cool); - - // Two A presses in case we drop the 1st one. - ssf_press_button(context, BUTTON_A, delay, hold, cool); - ssf_press_button(context, BUTTON_A, delay, hold, cool); - - for (size_t c = 0; c < 40; c++){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay, hold, cool); - } - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 1000ms, 1000ms, cool); - - // Scroll left and press A to exit the sleep menu if we happened to - // land there. - ssf_issue_scroll(context, SSF_SCROLL_LEFT, delay, hold, cool); - ssf_press_button(context, BUTTON_A, 3); - - for (size_t c = 0; c < 2; c++){ - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay, hold, cool); - } -} -void settings_to_date_time_Switch2_wired_blind( - Logger& logger, ProControllerContext& context, - ConsoleType console_type, bool to_date_change -){ - Milliseconds delay = 24ms; - Milliseconds hold = 48ms; - Milliseconds cool = 24ms; - - ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay, hold, cool); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay, hold, cool); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 192ms, hold, cool); - - - switch (console_type){ - case ConsoleType::Switch2_FW19_International: - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); - break; - case ConsoleType::Switch2_FW19_JapanLocked: - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); - break; - case ConsoleType::Switch2_FW20_International: - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); - break; - case ConsoleType::Switch2_FW20_JapanLocked: - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); - break; - default: - throw UserSetupError( - logger, - "You need to specify a specific Switch 2 model." - ); - } - - - if (!to_date_change){ - // Triple up this A press to make sure it gets through. - ssf_press_button(context, BUTTON_A, delay, hold, cool); - ssf_press_button(context, BUTTON_A, delay, hold, cool); - ssf_press_button(context, BUTTON_A, 360ms, hold, cool); - return; - } - - // Triple up this A press to make sure it gets through. - ssf_press_button(context, BUTTON_A, delay, hold, cool); - ssf_press_button(context, BUTTON_A, delay, hold, cool); - ssf_press_button(context, BUTTON_A, delay, hold, cool); - - for (size_t c = 0; c < 5; c++){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay, hold, cool); - } - - // Left scroll in case we missed and landed in the language change or sleep - // confirmation menus. - ssf_issue_scroll(context, SSF_SCROLL_LEFT, delay, hold, cool); -} -ConsoleType settings_detect_console_type( - ConsoleHandle& console, ProControllerContext& context -){ - ConsoleType console_type = console.state().console_type(); - console.log(std::string("Console Type: ") + ConsoleType_strings(console_type)); - - // We already know for sure the Switch type. - if (console_type != ConsoleType::Switch2_Unknown && - console.state().console_type_confirmed() - ){ - return console_type; - } - - console.log("Console type unknown or not confirmed. Attempting to detect..."); - - VideoOverlaySet overlays(console.overlay()); - BinarySliderDetector detector(COLOR_BLUE, {0.836431, 0.097521, 0.069703, 0.796694}); - detector.make_overlays(overlays); - - ssf_do_nothing(context, 500ms); - for (size_t c = 0; c < 5; c++){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 200ms, 100ms, 100ms); - } - ssf_do_nothing(context, 500ms); - context.wait_for_all_requests(); - - auto snapshot = console.video().snapshot(); - size_t sliders = detector.detect(snapshot).size(); - switch (sliders){ - case 2: - console.state().set_console_type(console, ConsoleType::Switch2_FW20_International); - break; - case 3: - console.state().set_console_type(console, ConsoleType::Switch2_FW20_JapanLocked); - break; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to detect if this Switch 2 model is international or Japan-locked.", - console, std::move(snapshot) - ); - } - console_type = console.state().console_type(); - console.log(std::string("Detected console type as: ") + ConsoleType_strings(console_type)); - - // Scroll back up. - for (size_t c = 0; c < 6; c++){ - ssf_issue_scroll(context, SSF_SCROLL_UP, 200ms, 100ms, 100ms); - } - ssf_do_nothing(context, 500ms); - - return console_type; -} - -void home_to_date_time_Switch2_wired_blind( - Logger& logger, ProControllerContext& context, - ConsoleType console_type, bool to_date_change -){ - logger.log("home_to_date_time_Switch2_wired_blind()"); - home_to_settings_Switch2_wired_blind(context); - settings_to_date_time_Switch2_wired_blind(logger, context, console_type, to_date_change); -} -void home_to_date_time_Switch2_wired_feedback( - ConsoleHandle& console, ProControllerContext& context, - bool to_date_change -){ - console.log("home_to_date_time_Switch2_wired_feedback()"); - home_to_settings_Switch2_wired_blind(context); - ConsoleType console_type = settings_detect_console_type(console, context); - settings_to_date_time_Switch2_wired_blind(console, context, console_type, to_date_change); -} - - - -} -} +/* Nintendo Switch 2 Home To Date-Time + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +template +ConsoleType settings_detect_console_type( + ConsoleHandle& console, ControllerContext& context +){ + ConsoleType console_type = console.state().console_type(); + console.log(std::string("Console Type: ") + ConsoleType_strings(console_type)); + + // We already know for sure the Switch type. + if (console_type != ConsoleType::Switch2_Unknown && + console.state().console_type_confirmed() + ){ + return console_type; + } + + console.log("Console type unknown or not confirmed. Attempting to detect..."); + + VideoOverlaySet overlays(console.overlay()); + BinarySliderDetector detector(COLOR_BLUE, {0.836431, 0.097521, 0.069703, 0.796694}); + detector.make_overlays(overlays); + + ssf_do_nothing(context, 500ms); + for (size_t c = 0; c < 5; c++){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 200ms, 100ms, 100ms); + } + ssf_do_nothing(context, 500ms); + context.wait_for_all_requests(); + + auto snapshot = console.video().snapshot(); +// snapshot->save("screenshot.png"); + size_t sliders = detector.detect(snapshot).size(); + switch (sliders){ + case 2: + console.state().set_console_type(console, ConsoleType::Switch2_FW20_International); + break; + case 3: + console.state().set_console_type(console, ConsoleType::Switch2_FW20_JapanLocked); + break; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to detect if this Switch 2 model is international or Japan-locked.", + console, std::move(snapshot) + ); + } + console_type = console.state().console_type(); + console.log(std::string("Detected console type as: ") + ConsoleType_strings(console_type)); + + // Scroll back up. + for (size_t c = 0; c < 6; c++){ + ssf_issue_scroll(context, SSF_SCROLL_UP, 200ms, 100ms, 100ms); + } + ssf_do_nothing(context, 500ms); + + return console_type; +} + + + + + + +void home_to_settings_Switch2_procon_blind( + ProControllerContext& context +){ + Milliseconds tv = context->timing_variation(); + Milliseconds unit = 24ms + tv; + + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + + // Down twice in case we drop one. + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + + ssf_issue_scroll(context, SSF_SCROLL_LEFT, unit); + + // Two A presses in case we drop the 1st one. + ssf_press_button(context, BUTTON_A, unit); + ssf_press_button(context, BUTTON_A, unit); + + for (size_t c = 0; c < 40; c++){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + } + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 1000ms, 1000ms, unit); + + // Scroll left and press A to exit the sleep menu if we happened to + // land there. + ssf_issue_scroll(context, SSF_SCROLL_LEFT, unit); + ssf_press_button(context, BUTTON_A, unit); + + for (size_t c = 0; c < 2; c++){ + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + } +} +void home_to_settings_Switch2_joycon_blind( + JoyconContext& context +){ + Milliseconds tv = context->timing_variation(); + Milliseconds unit = 24ms + tv; + + pbf_move_joystick(context, 255, 128, 2*unit, unit); + pbf_move_joystick(context, 255, 128, 2*unit, unit); + pbf_move_joystick(context, 255, 128, 2*unit, unit); + + // Down twice in case we drop one. + pbf_move_joystick(context, 128, 255, 2*unit, unit); + pbf_move_joystick(context, 128, 255, 2*unit, unit); + + pbf_move_joystick(context, 0, 128, 2*unit, unit); + + // Press A multiple times to make sure one goes through. + pbf_press_button(context, BUTTON_A, 2*unit, unit); + pbf_press_button(context, BUTTON_A, 2*unit, unit); + pbf_press_button(context, BUTTON_A, 2*unit, unit); + + pbf_move_joystick(context, 128, 255, 2000ms, 0ms); + + // Scroll left and press A to exit the sleep menu if we happened to + // land there. + pbf_move_joystick(context, 0, 128, 2*unit, unit); + pbf_press_button(context, BUTTON_A, 2*unit, unit); + + for (size_t c = 0; c < 2; c++){ + pbf_move_joystick(context, 255, 128, 2*unit, unit); + } +} + + +template +void settings_to_date_time_Switch2_all_blind( + Logger& logger, ControllerContext& context, + ConsoleType console_type, bool to_date_change +){ + Milliseconds tv = context->timing_variation(); + Milliseconds unit = 24ms + tv; + + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 192ms, 2*unit, unit); + + + switch (console_type){ + case ConsoleType::Switch2_FW19_International: + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, 2*unit, unit); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, 2*unit, unit); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, 2*unit, unit); + break; + case ConsoleType::Switch2_FW19_JapanLocked: + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, 2*unit, unit); + break; + case ConsoleType::Switch2_FW20_International: + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, 2*unit, unit); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, 2*unit, unit); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, 2*unit, unit); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, 2*unit, unit); + break; + case ConsoleType::Switch2_FW20_JapanLocked: + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, 2*unit, unit); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, 2*unit, unit); + break; + default: + throw UserSetupError( + logger, + "You need to specify a specific Switch 2 model." + ); + } + + + if (!to_date_change){ + // Triple up this A press to make sure it gets through. + ssf_press_button(context, BUTTON_A, unit); + ssf_press_button(context, BUTTON_A, unit); + ssf_press_button(context, BUTTON_A, 360ms, 2*unit, unit); + return; + } + + // Triple up this A press to make sure it gets through. + ssf_press_button(context, BUTTON_A, unit); + ssf_press_button(context, BUTTON_A, unit); + ssf_press_button(context, BUTTON_A, unit); + + for (size_t c = 0; c < 5; c++){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + } + + // Left scroll in case we missed and landed in the language change or sleep + // confirmation menus. + ssf_issue_scroll(context, SSF_SCROLL_LEFT, unit); +} + + + + + + + + +void home_to_date_time_Switch2_procon_blind( + Logger& logger, ProControllerContext& context, + ConsoleType console_type, bool to_date_change +){ + logger.log("home_to_date_time_Switch2_procon_blind()"); + home_to_settings_Switch2_procon_blind(context); + settings_to_date_time_Switch2_all_blind(logger, context, console_type, to_date_change); +} +void home_to_date_time_Switch2_procon_feedback( + ConsoleHandle& console, ProControllerContext& context, + bool to_date_change +){ + console.log("home_to_date_time_Switch2_procon_feedback()"); + home_to_settings_Switch2_procon_blind(context); + ConsoleType console_type = settings_detect_console_type(console, context); + settings_to_date_time_Switch2_all_blind(console, context, console_type, to_date_change); +} + + + + + +void home_to_date_time_Switch2_joycon_feedback( + ConsoleHandle& console, JoyconContext& context, + bool to_date_change +){ + console.log("home_to_date_time_Switch2_joycon_feedback()"); + home_to_settings_Switch2_joycon_blind(context); + ConsoleType console_type = settings_detect_console_type(console, context); + settings_to_date_time_Switch2_all_blind(console, context, console_type, to_date_change); +} + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.cpp index 84cb770ca4..382e20e84f 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.cpp @@ -1,172 +1,174 @@ -/* Nintendo Switch Home To Date-Time - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -//#include "CommonFramework/Exceptions/OperationFailedException.h" -//#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -//#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -//#include "CommonTools/Async/InferenceRoutines.h" -#include "Controllers/ControllerTypes.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -//#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" -//#include "NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.h" -#include "NintendoSwitch_HomeToDateTime.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - -void home_to_date_time_Switch1_blind(Logger& logger, ProControllerContext& context, bool to_date_change){ - switch (context->performance_class()){ - case ControllerPerformanceClass::SerialPABotBase_Wired_125Hz: - home_to_date_time_Switch1_wired_blind(logger, context, to_date_change); - return; - case ControllerPerformanceClass::SerialPABotBase_Wireless_ESP32: - home_to_date_time_Switch1_wireless_esp32_blind(logger, context, to_date_change); - return; - default: - // Slow version for tick-imprecise controllers. - home_to_date_time_Switch1_sbb_blind(logger, context, to_date_change); - return; - } -} -bool home_to_date_time_Switch1_feedback(ConsoleHandle& console, ProControllerContext& context, bool to_date_change){ - switch (context->performance_class()){ - case ControllerPerformanceClass::SerialPABotBase_Wired_125Hz: - home_to_date_time_Switch1_wired_feedback(console, context, to_date_change); - return true; - default:; - return false; - } -} - - - - -// Returns true if success. False if not supported. -bool home_to_date_time_with_feedback(ConsoleHandle& console, ProControllerContext& context, bool to_date_change){ - wait_for_home(console, context); - - ConsoleTypeDetector_Home detector(console); - ConsoleType console_type = detector.detect_only(console.video().snapshot()); - switch (console_type){ - case ConsoleType::Switch1: - return home_to_date_time_Switch1_feedback(console, context, to_date_change); - case ConsoleType::Switch2_Unknown: - case ConsoleType::Switch2_FW19_International: - case ConsoleType::Switch2_FW19_JapanLocked: - case ConsoleType::Switch2_FW20_International: - case ConsoleType::Switch2_FW20_JapanLocked: - home_to_date_time_Switch2_wired_feedback(console, context, to_date_change); - return true; - default:; - } - - return false; -} -void home_to_date_time(ConsoleHandle& console, ProControllerContext& context, bool to_date_change){ - if (console.video().snapshot() && home_to_date_time_with_feedback(console, context, to_date_change)){ - return; - } - - // No feedback available. - - ConsoleType console_type = console.state().console_type(); - - switch (console_type){ - case ConsoleType::Unknown: - throw UserSetupError(console, "Switch type is not specified and feedback is not available."); - case ConsoleType::Switch1: - home_to_date_time_Switch1_blind(console, context, to_date_change); - return; - case ConsoleType::Switch2_Unknown: - case ConsoleType::Switch2_FW19_International: - case ConsoleType::Switch2_FW19_JapanLocked: - case ConsoleType::Switch2_FW20_International: - case ConsoleType::Switch2_FW20_JapanLocked: - home_to_date_time_Switch2_wired_blind(console, context, console_type, to_date_change); - return; - } -} - - - - - - - - - - - - - - - -void home_to_date_time(JoyconContext& context, bool to_date_change){ - Milliseconds tv = context->timing_variation(); - Milliseconds unit = 100ms + tv; - - //From ControllerPerformanceClass::SerialPABotBase_Wireless_ESP32 - //as Joycon will only have that controller type - - pbf_move_joystick(context, 255, 128, 2*unit, unit); - pbf_move_joystick(context, 255, 128, 2*unit, unit); - pbf_move_joystick(context, 255, 128, 2*unit, unit); - - // Down twice in case we drop one. - pbf_move_joystick(context, 128, 255, 2*unit, unit); - pbf_move_joystick(context, 128, 255, 2*unit, unit); - - pbf_move_joystick(context, 0, 128, 2*unit, unit); - - // Press A multiple times to make sure one goes through. - pbf_press_button(context, BUTTON_A, 2*unit, unit); - pbf_press_button(context, BUTTON_A, 2*unit, unit); - pbf_press_button(context, BUTTON_A, 2*unit, unit); - - // Scroll to System, move right to top option (update) - pbf_move_joystick(context, 128, 255, 2500ms, unit); - pbf_move_joystick(context, 255, 128, 500ms, unit); - - // To date/time - pbf_move_joystick(context, 128, 255, 2*unit, unit); - pbf_move_joystick(context, 128, 255, 2*unit, unit); - context.wait_for_all_requests(); - pbf_move_joystick(context, 128, 255, 525ms, unit); - //pbf_move_joystick(context, 128, 255, 365ms, 305ms); - pbf_move_joystick(context, 128, 255, 2*unit, unit); - //pbf_move_joystick(context, 128, 255, 2*unit, unit); - context.wait_for_all_requests(); - - if (!to_date_change){ - ssf_press_button(context, BUTTON_A, 360ms, 2*unit, unit); - return; - } - - //ssf_press_button(context, BUTTON_A, unit); - pbf_press_button(context, BUTTON_A, 2*unit, unit); - context.wait_for_all_requests(); - { - auto iterations = Milliseconds(216) / unit + 1; - do{ - pbf_move_joystick(context, 128, 255, 2*unit, unit); - }while (--iterations); - } - pbf_move_joystick(context, 128, 255, 2*unit, 0ms); -} - - - - -} -} +/* Nintendo Switch Home To Date-Time + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +//#include "CommonFramework/Exceptions/OperationFailedException.h" +//#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +//#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +//#include "CommonTools/Async/InferenceRoutines.h" +#include "Controllers/ControllerTypes.h" +//#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +//#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +//#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" +//#include "NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.h" +#include "NintendoSwitch_HomeToDateTime.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + +void home_to_date_time_Switch1_blind(Logger& logger, ProControllerContext& context, bool to_date_change){ + switch (context->performance_class()){ + case ControllerPerformanceClass::SerialPABotBase_Wired: + home_to_date_time_Switch1_wired_blind(logger, context, to_date_change); + return; + case ControllerPerformanceClass::SerialPABotBase_Wireless: + home_to_date_time_Switch1_wireless_esp32_blind(logger, context, to_date_change); + return; + default: + // Slow version for tick-imprecise controllers. + home_to_date_time_Switch1_sbb_blind(logger, context, to_date_change); + return; + } +} +bool home_to_date_time_Switch1_feedback(ConsoleHandle& console, ProControllerContext& context, bool to_date_change){ + switch (context->performance_class()){ + case ControllerPerformanceClass::SerialPABotBase_Wired: + home_to_date_time_Switch1_wired_feedback(console, context, to_date_change); + return true; + default:; + return false; + } +} + + +void home_to_date_time_Switch2_blind( + Logger& logger, ProControllerContext& context, + ConsoleType console_type, bool to_date_change +){ + switch (context->performance_class()){ + case ControllerPerformanceClass::SerialPABotBase_Wired: + case ControllerPerformanceClass::SerialPABotBase_Wireless: + home_to_date_time_Switch2_procon_blind(logger, context, console_type, to_date_change); + return; + default: + throw InternalProgramError( + &logger, PA_CURRENT_FUNCTION, + "Unsupported ControllerPerformanceClass: " + std::to_string((int)context->performance_class()) + ); + } +} +bool home_to_date_time_Switch2_feedback( + ConsoleHandle& console, ProControllerContext& context, + ConsoleType console_type, bool to_date_change +){ + switch (context->performance_class()){ + case ControllerPerformanceClass::SerialPABotBase_Wired: + case ControllerPerformanceClass::SerialPABotBase_Wireless: + home_to_date_time_Switch2_procon_feedback(console, context, to_date_change); + return true; + default:; + return false; + } +} + + + + +// Returns true if success. False if not supported. +bool home_to_date_time_with_feedback(ConsoleHandle& console, ProControllerContext& context, bool to_date_change){ + ensure_at_home(console, context); + + ConsoleTypeDetector_Home detector(console); + ConsoleType console_type = detector.detect_only(console.video().snapshot()); + switch (console_type){ + case ConsoleType::Switch1: + return home_to_date_time_Switch1_feedback(console, context, to_date_change); + case ConsoleType::Switch2_Unknown: + case ConsoleType::Switch2_FW19_International: + case ConsoleType::Switch2_FW19_JapanLocked: + case ConsoleType::Switch2_FW20_International: + case ConsoleType::Switch2_FW20_JapanLocked: + home_to_date_time_Switch2_feedback(console, context, console_type, to_date_change); + return true; + default:; + } + + return false; +} +void home_to_date_time(ConsoleHandle& console, ProControllerContext& context, bool to_date_change){ + if (console.video().snapshot() && home_to_date_time_with_feedback(console, context, to_date_change)){ + return; + } + + // No feedback available. + + ConsoleType console_type = console.state().console_type(); + + switch (console_type){ + case ConsoleType::Unknown: + throw UserSetupError(console, "Switch type is not specified and feedback is not available."); + case ConsoleType::Switch1: + home_to_date_time_Switch1_blind(console, context, to_date_change); + return; + case ConsoleType::Switch2_Unknown: + case ConsoleType::Switch2_FW19_International: + case ConsoleType::Switch2_FW19_JapanLocked: + case ConsoleType::Switch2_FW20_International: + case ConsoleType::Switch2_FW20_JapanLocked: + home_to_date_time_Switch2_blind(console, context, console_type, to_date_change); + return; + } +} + + + + + + + + + + + + + + + + +void home_to_date_time(ConsoleHandle& console, JoyconContext& context, bool to_date_change){ + ensure_at_home(console, context); + + ConsoleTypeDetector_Home detector(console); + ConsoleType console_type = detector.detect_only(console.video().snapshot()); + switch (console_type){ + case ConsoleType::Switch1: + home_to_date_time_Switch1_joycon_blind(context, to_date_change); + return; + case ConsoleType::Switch2_Unknown: + case ConsoleType::Switch2_FW19_International: + case ConsoleType::Switch2_FW19_JapanLocked: + case ConsoleType::Switch2_FW20_International: + case ConsoleType::Switch2_FW20_JapanLocked: + home_to_date_time_Switch2_joycon_feedback(console, context, to_date_change); + return; + default:; + } + throw UserSetupError( + console.logger(), + "Unsupported console type: " + ConsoleType_strings(console_type) + ); +} + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h index 3919f07882..1716a638f3 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h @@ -1,64 +1,88 @@ -/* Nintendo Switch Home To Date-Time - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_HomeToDateTime_H -#define PokemonAutomation_NintendoSwitch_HomeToDateTime_H - -//#include "CommonFramework/ImageTools/ImageBoxes.h" -//#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -//// Navigates from Home screen to the Date and Time screen. Using visual inference. -//void home_to_date_time(VideoStream& stream, ProControllerContext& context, bool to_date_change); - -//// Navigates from Home screen to the Date and Time screen. Done blind, without inference. -//void home_to_date_time(Logger& logger, ProControllerContext& context, bool to_date_change); - - -void home_to_date_time_Switch1_wired_blind( - Logger& logger, ProControllerContext& context, bool to_date_change -); -void home_to_date_time_Switch1_wireless_esp32_blind( - Logger& logger, ProControllerContext& context, bool to_date_change -); -void home_to_date_time_Switch1_sbb_blind( - Logger& logger, ProControllerContext& context, bool to_date_change -); -void home_to_date_time_Switch1_wired_feedback( - VideoStream& stream, ProControllerContext& context, bool to_date_change -); - - - -void home_to_date_time_Switch2_wired_blind( - Logger& logger, ProControllerContext& context, - ConsoleType console_type, bool to_date_change -); -void home_to_date_time_Switch2_wired_feedback( - ConsoleHandle& console, ProControllerContext& context, - bool to_date_change -); - - - -void home_to_date_time(ConsoleHandle& console, ProControllerContext& context, bool to_date_change); - - - -//Joycon must not be sideways -void home_to_date_time(JoyconContext& context, bool to_date_change); - - - -} -} -#endif +/* Nintendo Switch Home To Date-Time + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_HomeToDateTime_H +#define PokemonAutomation_NintendoSwitch_HomeToDateTime_H + +//#include "CommonFramework/ImageTools/ImageBoxes.h" +//#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +void home_to_date_time( + ConsoleHandle& console, ProControllerContext& context, + bool to_date_change +); + +void home_to_date_time( + ConsoleHandle& console, JoyconContext& context, + bool to_date_change +); + + + + + +// +// Internal Headers +// + + +void home_to_date_time_Switch1_wired_blind( + Logger& logger, ProControllerContext& context, bool to_date_change +); +void home_to_date_time_Switch1_wireless_esp32_blind( + Logger& logger, ProControllerContext& context, bool to_date_change +); +void home_to_date_time_Switch1_sbb_blind( + Logger& logger, ProControllerContext& context, bool to_date_change +); +void home_to_date_time_Switch1_wired_feedback( + VideoStream& stream, ProControllerContext& context, bool to_date_change +); + + + +void home_to_date_time_Switch2_procon_blind( + Logger& logger, ProControllerContext& context, + ConsoleType console_type, bool to_date_change +); +void home_to_date_time_Switch2_procon_feedback( + ConsoleHandle& console, ProControllerContext& context, + bool to_date_change +); + + +ConsoleType settings_detect_console_type( + ConsoleHandle& console, ProControllerContext& context +); + + + + + + +// Joycon must not be sideways +void home_to_date_time_Switch1_joycon_blind( + JoyconContext& context, bool to_date_change +); +void home_to_date_time_Switch2_joycon_feedback( + ConsoleHandle& console, JoyconContext& context, + bool to_date_change +); + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_NeutralDateSkip.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_NeutralDateSkip.cpp index 7f19952b57..6d401366d6 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_NeutralDateSkip.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_NeutralDateSkip.cpp @@ -1,133 +1,168 @@ -/* Nintendo Switch Neutral Date Skip - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Controllers/ControllerTypes.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -void neutral_date_skip_switch1_wired(ProControllerContext& context){ - ssf_press_button(context, BUTTON_A, 20, 10); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 3); - ssf_issue_scroll(context, SSF_SCROLL_UP, 0); - ssf_press_button(context, BUTTON_A, 2); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 3); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 3); -// ssf_press_button(context, BUTTON_A, 2); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 3); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 0); - ssf_press_button(context, BUTTON_A, 20, 10); - ssf_press_button(context, BUTTON_A, 20, 10); - for (uint8_t c = 0; c < 6; c++){ - ssf_issue_scroll(context, SSF_SCROLL_LEFT, 3); - } - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 3); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0); -} -void neutral_date_skip_switch1_wireless(ProControllerContext& context){ - Milliseconds tv = context->timing_variation(); - Milliseconds unit = 24ms + tv; - - ssf_press_button(context, BUTTON_A, 20, 10); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_issue_scroll(context, SSF_SCROLL_UP, 0); - ssf_press_button(context, BUTTON_A, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); -// ssf_press_button(context, BUTTON_A, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_press_button(context, BUTTON_A, 20, 10); - ssf_press_button(context, BUTTON_A, 20, 10); - for (uint8_t c = 0; c < 6; c++){ - ssf_issue_scroll(context, SSF_SCROLL_LEFT, unit); - } - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0); -} -void neutral_date_skip_switch1_sbb(ProControllerContext& context){ - ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); - ssf_press_button_ptv(context, BUTTON_A); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); - ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); - for (uint8_t c = 0; c < 6; c++){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT); - } - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); -} -void neutral_date_skip_switch2_wired(ProControllerContext& context){ - ssf_press_button(context, BUTTON_A, 216ms, 80ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_UP, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_press_button(context, BUTTON_A, 264ms, 80ms); - ssf_press_button(context, BUTTON_A, 216ms, 80ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_press_button(context, BUTTON_A, 264ms, 80ms); -} - - -void neutral_date_skip(ConsoleHandle& console, ProControllerContext& context){ - ConsoleType type = console.state().console_type(); - - if (is_switch1(type)){ - switch (context->performance_class()){ - case ControllerPerformanceClass::SerialPABotBase_Wired_125Hz: - neutral_date_skip_switch1_wired(context); - return; - case ControllerPerformanceClass::SerialPABotBase_Wireless_ESP32: - neutral_date_skip_switch1_wireless(context); - return; - case ControllerPerformanceClass::SysbotBase: - neutral_date_skip_switch1_sbb(context); - return; - default: - throw InternalProgramError( - &console.logger(), PA_CURRENT_FUNCTION, - "Unsupported ControllerPerformanceClass: " + std::to_string((int)context->performance_class()) - ); - } - } - - if (is_switch2(type)){ - neutral_date_skip_switch2_wired(context); - return; - } - - throw UserSetupError( - console.logger(), - "Please select a valid Switch console type." - ); -} - - - - - -} -} +/* Nintendo Switch Neutral Date Skip + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Controllers/ControllerTypes.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +void neutral_date_skip_switch1_wired(ProControllerContext& context){ + ssf_press_button(context, BUTTON_A, 160ms, 80ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_UP, 0ms, 40ms, 24ms); + ssf_press_button(context, BUTTON_A, 16ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); +// ssf_press_button(context, BUTTON_A, 2); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 0ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_A, 160ms, 80ms); + ssf_press_button(context, BUTTON_A, 160ms, 80ms); + for (uint8_t c = 0; c < 6; c++){ + ssf_issue_scroll(context, SSF_SCROLL_LEFT, 24ms, 48ms, 24ms); + } + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0ms, 48ms, 24ms); +} +void neutral_date_skip_switch1_wireless(ProControllerContext& context){ + Milliseconds tv = context->timing_variation(); + Milliseconds unit = 24ms + tv; + + ssf_press_button(context, BUTTON_A, 160ms, 80ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_UP, 0ms, 2*unit, unit); + ssf_press_button(context, BUTTON_A, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); +// ssf_press_button(context, BUTTON_A, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_press_button(context, BUTTON_A, 160ms, 80ms); + ssf_press_button(context, BUTTON_A, 160ms, 80ms); + for (uint8_t c = 0; c < 6; c++){ + ssf_issue_scroll(context, SSF_SCROLL_LEFT, unit); + } + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0ms, 2*unit, unit); +} +void neutral_date_skip_switch1_sbb(ProControllerContext& context){ + ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); + ssf_press_button_ptv(context, BUTTON_A); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); + ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); + for (uint8_t c = 0; c < 6; c++){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT); + } + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); +} +void neutral_date_skip_switch2_wired(ProControllerContext& context){ + ssf_press_button(context, BUTTON_A, 216ms, 80ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_UP, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_A, 264ms, 80ms); + ssf_press_button(context, BUTTON_A, 216ms, 80ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_A, 264ms, 80ms); +} +void neutral_date_skip_switch2_wireless(ProControllerContext& context){ + Milliseconds tv = context->timing_variation(); + Milliseconds unit = 24ms + tv; + + ssf_press_button(context, BUTTON_A, 216ms, 80ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_UP, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_press_button(context, BUTTON_A, 264ms, 80ms); + ssf_press_button(context, BUTTON_A, 216ms, 80ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_press_button(context, BUTTON_A, 264ms, 80ms); +} + + +void neutral_date_skip(ConsoleHandle& console, ProControllerContext& context){ + ConsoleType type = console.state().console_type(); + + if (is_switch1(type)){ + switch (context->performance_class()){ + case ControllerPerformanceClass::SerialPABotBase_Wired: + neutral_date_skip_switch1_wired(context); + return; + case ControllerPerformanceClass::SerialPABotBase_Wireless: + neutral_date_skip_switch1_wireless(context); + return; + case ControllerPerformanceClass::SysbotBase: + neutral_date_skip_switch1_sbb(context); + return; + default: + throw InternalProgramError( + &console.logger(), PA_CURRENT_FUNCTION, + "Unsupported ControllerPerformanceClass: " + std::to_string((int)context->performance_class()) + ); + } + } + + if (is_switch2(type)){ + switch (context->performance_class()){ + case ControllerPerformanceClass::SerialPABotBase_Wired: + neutral_date_skip_switch2_wired(context); + return; + case ControllerPerformanceClass::SerialPABotBase_Wireless: + neutral_date_skip_switch2_wireless(context); + return; + default: + throw InternalProgramError( + &console.logger(), PA_CURRENT_FUNCTION, + "Unsupported ControllerPerformanceClass: " + std::to_string((int)context->performance_class()) + ); + } + return; + } + + throw UserSetupError( + console.logger(), + "Please select a valid Switch console type." + ); +} + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_NeutralDateSkip.h b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_NeutralDateSkip.h index a8f0ba08ae..2575f7cbb4 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_NeutralDateSkip.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_NeutralDateSkip.h @@ -1,26 +1,26 @@ -/* Nintendo Switch Neutral Date Skip - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_NeutralDateSkip_H -#define PokemonAutomation_NintendoSwitch_NeutralDateSkip_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -void neutral_date_skip(ConsoleHandle& console, ProControllerContext& context); - - - - - -} -} -#endif +/* Nintendo Switch Neutral Date Skip + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_NeutralDateSkip_H +#define PokemonAutomation_NintendoSwitch_NeutralDateSkip_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +void neutral_date_skip(ConsoleHandle& console, ProControllerContext& context); + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.cpp index e8b7e3b60c..6f3f67bcf8 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.cpp @@ -1,200 +1,238 @@ -/* Nintendo Switch Roll Date Backward N - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Controllers/ControllerTypes.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch_RollDateBackwardN.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -void roll_date_backward_N_Switch1_wired(ProControllerContext& context, uint8_t skips, bool fast){ - uint8_t scroll_delay = fast ? 3 : 4; - uint8_t up_delay = 3; - ssf_press_button(context, BUTTON_A, 20, 10); - for (uint8_t c = 0; c < skips - 1; c++){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, up_delay); - } -#if 0 - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0); -// ssf_press_button(context, BUTTON_A, up_delay); -#else - ssf_issue_scroll(context, SSF_SCROLL_DOWN, up_delay); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, scroll_delay); -#endif - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, scroll_delay); - for (uint8_t c = 0; c < skips - 1; c++){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, up_delay); - } -#if 0 - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0); - ssf_press_button(context, BUTTON_A, up_delay); -#else - ssf_issue_scroll(context, SSF_SCROLL_DOWN, up_delay); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, scroll_delay); -#endif - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, scroll_delay); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, scroll_delay); - -#if 0 -// ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 0); -#else - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, scroll_delay); - ssf_issue_scroll(context, SSF_SCROLL_LEFT, scroll_delay); - ssf_press_button(context, BUTTON_A); -#endif - - ssf_press_button(context, BUTTON_A, 20, 10); -} -void roll_date_backward_N_Switch1_wireless(ProControllerContext& context, uint8_t skips){ - Milliseconds tv = context->timing_variation(); - Milliseconds unit = 24ms + tv; - - ssf_press_button(context, BUTTON_A, 160ms, 3*unit); - - for (uint8_t c = 0; c < skips - 1; c++){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); - } - -#if 0 - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0ms, 2*unit, unit); - ssf_press_button(context, BUTTON_A, unit); -#else - ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); -#endif - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - for (uint8_t c = 0; c < skips - 1; c++){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); - } -#if 0 - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0ms, 2*unit, unit); - ssf_press_button(context, BUTTON_A, unit); -#else - ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); -#endif - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 0ms, 2*unit, unit); - ssf_press_button(context, BUTTON_A, 160ms, 3*unit); -} -void roll_date_backward_N_Switch1_sbb(ProControllerContext& context, uint8_t skips){ - ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); - if (skips >= 60){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN, 6000ms, 6000ms); - }else{ - for (uint8_t c = 0; c < skips; c++){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); - } - } - - // Left scroll in case we missed the date menu and landed in the - // language change. - ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT); - - ssf_press_button_ptv(context, BUTTON_A); -// ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - if (skips >= 60){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN, 6000ms, 6000ms); - }else{ - for (uint8_t c = 0; c < skips; c++){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); - } - } - ssf_press_button_ptv(context, BUTTON_A); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); -} -void roll_date_backward_N_Switch2_wired(ProControllerContext& context, uint8_t skips){ - ssf_press_button(context, BUTTON_A, 216ms, 80ms); - if (skips >= 60){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 4160ms, 4160ms, 24ms); - }else{ - for (uint8_t c = 0; c < skips; c++){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 112ms, 48ms, 24ms); - } - } - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - if (skips >= 60){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 4160ms, 4160ms, 24ms); - }else{ - for (uint8_t c = 0; c < skips; c++){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 112ms, 48ms, 24ms); - } - } - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_press_button(context, BUTTON_A, 264ms, 80ms); -} -void roll_date_backward_N( - ConsoleHandle& console, ProControllerContext& context, - uint8_t skips, bool fast -){ - ConsoleType type = console.state().console_type(); - - if (is_switch1(type)){ - switch (context->performance_class()){ - case ControllerPerformanceClass::SerialPABotBase_Wired_125Hz: - roll_date_backward_N_Switch1_wired(context, skips, fast); - return; - case ControllerPerformanceClass::SerialPABotBase_Wireless_ESP32: - roll_date_backward_N_Switch1_wireless(context, skips); - return; - case ControllerPerformanceClass::SysbotBase: - roll_date_backward_N_Switch1_sbb(context, skips); - return; - default: - throw InternalProgramError( - &console.logger(), PA_CURRENT_FUNCTION, - "Unsupported ControllerPerformanceClass: " + std::to_string((int)context->performance_class()) - ); - } - } - - if (is_switch2(type)){ - roll_date_backward_N_Switch2_wired(context, skips); - return; - } - - throw UserSetupError( - console.logger(), - "Please select a valid Switch console type." - ); -} - - - - - - - - - - - - -} -} - - - - - - - - - - +/* Nintendo Switch Roll Date Backward N + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Controllers/ControllerTypes.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch_RollDateBackwardN.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +void roll_date_backward_N_Switch1_wired(ProControllerContext& context, uint8_t skips, bool fast){ + Milliseconds delay = 24ms; + ssf_press_button(context, BUTTON_A, 160ms, 80ms); + for (uint8_t c = 0; c < skips - 1; c++){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay); + } +#if 0 + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0); +// ssf_press_button(context, BUTTON_A, delay); +#else + ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); +#endif + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); + for (uint8_t c = 0; c < skips - 1; c++){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay); + } +#if 0 + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0); + ssf_press_button(context, BUTTON_A, up_delay); +#else + ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); +#endif + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); + +#if 0 +// ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 0); +#else + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); + ssf_issue_scroll(context, SSF_SCROLL_LEFT, delay); + ssf_press_button(context, BUTTON_A); +#endif + + ssf_press_button(context, BUTTON_A, 160ms, 80ms); +} +void roll_date_backward_N_Switch1_wireless(ProControllerContext& context, uint8_t skips){ + Milliseconds tv = context->timing_variation(); + Milliseconds unit = 24ms + tv; + + ssf_press_button(context, BUTTON_A, 160ms, 3*unit); + + for (uint8_t c = 0; c < skips - 1; c++){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + } + +#if 0 + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0ms, 2*unit, unit); + ssf_press_button(context, BUTTON_A, unit); +#else + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); +#endif + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + for (uint8_t c = 0; c < skips - 1; c++){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + } +#if 0 + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0ms, 2*unit, unit); + ssf_press_button(context, BUTTON_A, unit); +#else + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); +#endif + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 0ms, 2*unit, unit); + ssf_press_button(context, BUTTON_A, 160ms, 3*unit); +} +void roll_date_backward_N_Switch1_sbb(ProControllerContext& context, uint8_t skips){ + ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); + if (skips >= 60){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN, 6000ms, 6000ms); + }else{ + for (uint8_t c = 0; c < skips; c++){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + } + } + + // Left scroll in case we missed the date menu and landed in the + // language change. + ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT); + + ssf_press_button_ptv(context, BUTTON_A); +// ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + if (skips >= 60){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN, 6000ms, 6000ms); + }else{ + for (uint8_t c = 0; c < skips; c++){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + } + } + ssf_press_button_ptv(context, BUTTON_A); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); +} +void roll_date_backward_N_Switch2_wired(ProControllerContext& context, uint8_t skips){ + ssf_press_button(context, BUTTON_A, 216ms, 80ms); + if (skips >= 60){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 4160ms, 4160ms, 24ms); + }else{ + for (uint8_t c = 0; c < skips; c++){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 112ms, 48ms, 24ms); + } + } + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + if (skips >= 60){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 4160ms, 4160ms, 24ms); + }else{ + for (uint8_t c = 0; c < skips; c++){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 112ms, 48ms, 24ms); + } + } + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_A, 264ms, 80ms); +} +void roll_date_backward_N_Switch2_wireless(ProControllerContext& context, uint8_t skips){ + Milliseconds tv = context->timing_variation(); + Milliseconds unit = 24ms + tv; + + ssf_press_button(context, BUTTON_A, 216ms, 80ms); + if (skips >= 60){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 4160ms, 4160ms, unit); + }else{ + for (uint8_t c = 0; c < skips; c++){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 112ms, 2*unit, unit); + } + } + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + if (skips >= 60){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 4160ms, 4160ms, unit); + }else{ + for (uint8_t c = 0; c < skips; c++){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 112ms, 2*unit, unit); + } + } + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_press_button(context, BUTTON_A, 264ms, 80ms); +} +void roll_date_backward_N( + ConsoleHandle& console, ProControllerContext& context, + uint8_t skips, bool fast +){ + ConsoleType type = console.state().console_type(); + + if (is_switch1(type)){ + switch (context->performance_class()){ + case ControllerPerformanceClass::SerialPABotBase_Wired: + roll_date_backward_N_Switch1_wired(context, skips, fast); + return; + case ControllerPerformanceClass::SerialPABotBase_Wireless: + roll_date_backward_N_Switch1_wireless(context, skips); + return; + case ControllerPerformanceClass::SysbotBase: + roll_date_backward_N_Switch1_sbb(context, skips); + return; + default: + throw InternalProgramError( + &console.logger(), PA_CURRENT_FUNCTION, + "Unsupported ControllerPerformanceClass: " + std::to_string((int)context->performance_class()) + ); + } + } + + if (is_switch2(type)){ + switch (context->performance_class()){ + case ControllerPerformanceClass::SerialPABotBase_Wired: + roll_date_backward_N_Switch2_wired(context, skips); + return; + case ControllerPerformanceClass::SerialPABotBase_Wireless: + roll_date_backward_N_Switch2_wireless(context, skips); + return; + default: + throw InternalProgramError( + &console.logger(), PA_CURRENT_FUNCTION, + "Unsupported ControllerPerformanceClass: " + std::to_string((int)context->performance_class()) + ); + } + return; + } + + throw UserSetupError( + console.logger(), + "Please select a valid Switch console type." + ); +} + + + + + + + + + + + + +} +} + + + + + + + + + + diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.h b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.h index 00f55057c2..bfd6f43d03 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.h @@ -1,29 +1,29 @@ -/* Nintendo Switch Roll Date Backward N - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_RollDateBackwardN_H -#define PokemonAutomation_NintendoSwitch_RollDateBackwardN_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -void roll_date_backward_N( - ConsoleHandle& console, ProControllerContext& context, - uint8_t skips, bool fast -); - - - - - -} -} -#endif +/* Nintendo Switch Roll Date Backward N + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_RollDateBackwardN_H +#define PokemonAutomation_NintendoSwitch_RollDateBackwardN_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +void roll_date_backward_N( + ConsoleHandle& console, ProControllerContext& context, + uint8_t skips, bool fast +); + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.cpp index 4f3e09ef06..f3e405a76d 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.cpp @@ -1,132 +1,158 @@ -/* Nintendo Switch Roll Date Forward 1 - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Controllers/ControllerTypes.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch_RollDateForward1.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -void roll_date_forward_1_Switch1_wired(ProControllerContext& context, bool fast){ - uint8_t scroll_delay = fast ? 3 : 4; - uint8_t up_delay = fast ? 2 : 3; - - ssf_press_button(context, BUTTON_A, 20, 10); - ssf_issue_scroll(context, SSF_SCROLL_UP, 0); - ssf_press_button(context, BUTTON_A, up_delay); -// ssf_issue_scroll(context, SSF_SCROLL_RIGHT, scroll_delay); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, scroll_delay); - ssf_issue_scroll(context, SSF_SCROLL_UP, up_delay); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, scroll_delay); - ssf_press_button(context, BUTTON_A, 0); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, scroll_delay); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, scroll_delay); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 0); - ssf_press_button(context, BUTTON_A, 20, 10); -} -void roll_date_forward_1_Switch1_wireless(ProControllerContext& context){ - Milliseconds tv = context->timing_variation(); - Milliseconds unit = 24ms + tv; - - ssf_press_button(context, BUTTON_A, 160ms, 3*unit); - ssf_issue_scroll(context, SSF_SCROLL_UP, unit); - - // Left scroll in case we missed the date menu and landed in the - // language change. - ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms, 2*unit, unit); - - ssf_press_button(context, BUTTON_A, unit); -// ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_issue_scroll(context, SSF_SCROLL_UP, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_press_button(context, BUTTON_A, 0ms, 2*unit, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 0ms, 2*unit, unit); - ssf_press_button(context, BUTTON_A, 160ms, 3*unit); -} -void roll_date_forward_1_Switch1_sbb(ProControllerContext& context){ - ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); - - // Left scroll in case we missed the date menu and landed in the - // language change. - ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT); - - ssf_press_button_ptv(context, BUTTON_A); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_press_button_ptv(context, BUTTON_A); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); -} -void roll_date_forward_1_Switch2_wired(ProControllerContext& context){ - ssf_press_button(context, BUTTON_A, 216ms, 80ms); - ssf_issue_scroll(context, SSF_SCROLL_UP, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_UP, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_press_button(context, BUTTON_A, 264ms, 80ms); -} -void roll_date_forward_1( - ConsoleHandle& console, ProControllerContext& context, - bool fast -){ - ConsoleType type = console.state().console_type(); - - if (is_switch1(type)){ - switch (context->performance_class()){ - case ControllerPerformanceClass::SerialPABotBase_Wired_125Hz: - roll_date_forward_1_Switch1_wired(context, fast); - return; - case ControllerPerformanceClass::SerialPABotBase_Wireless_ESP32: - roll_date_forward_1_Switch1_wireless(context); - return; - case ControllerPerformanceClass::SysbotBase: - roll_date_forward_1_Switch1_sbb(context); - return; - default: - throw InternalProgramError( - &console.logger(), PA_CURRENT_FUNCTION, - "Unsupported ControllerPerformanceClass: " + std::to_string((int)context->performance_class()) - ); - } - } - - if (is_switch2(type)){ - roll_date_forward_1_Switch2_wired(context); - return; - } - - throw UserSetupError( - console.logger(), - "Please select a valid Switch console type." - ); -} - - - - - - - - - - - -} -} +/* Nintendo Switch Roll Date Forward 1 + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Controllers/ControllerTypes.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch_RollDateForward1.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +void roll_date_forward_1_Switch1_wired(ProControllerContext& context, bool fast){ + Milliseconds delay = 24ms; + + ssf_press_button(context, BUTTON_A, 160ms, 80ms); + ssf_issue_scroll(context, SSF_SCROLL_UP, 0ms, 2*delay, delay); + ssf_press_button(context, BUTTON_A, delay); +// ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); + ssf_issue_scroll(context, SSF_SCROLL_UP, delay); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); + ssf_press_button(context, BUTTON_A, 0ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 0ms, 2*delay, delay); + ssf_press_button(context, BUTTON_A, 160ms, 80ms); +} +void roll_date_forward_1_Switch1_wireless(ProControllerContext& context){ + Milliseconds tv = context->timing_variation(); + Milliseconds unit = 24ms + tv; + + ssf_press_button(context, BUTTON_A, 160ms, 3*unit); + ssf_issue_scroll(context, SSF_SCROLL_UP, unit); + + // Left scroll in case we missed the date menu and landed in the + // language change. + ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms, 2*unit, unit); + + ssf_press_button(context, BUTTON_A, unit); +// ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_UP, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_press_button(context, BUTTON_A, 0ms, 2*unit, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 0ms, 2*unit, unit); + ssf_press_button(context, BUTTON_A, 160ms, 3*unit); +} +void roll_date_forward_1_Switch1_sbb(ProControllerContext& context){ + ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); + + // Left scroll in case we missed the date menu and landed in the + // language change. + ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT); + + ssf_press_button_ptv(context, BUTTON_A); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_press_button_ptv(context, BUTTON_A); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); +} +void roll_date_forward_1_Switch2_wired(ProControllerContext& context){ + ssf_press_button(context, BUTTON_A, 216ms, 80ms); + ssf_issue_scroll(context, SSF_SCROLL_UP, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_UP, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_A, 264ms, 80ms); +} +void roll_date_forward_1_Switch2_wireless(ProControllerContext& context){ + Milliseconds tv = context->timing_variation(); + Milliseconds unit = 24ms + tv; + + ssf_press_button(context, BUTTON_A, 216ms, 80ms); + ssf_issue_scroll(context, SSF_SCROLL_UP, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_UP, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_press_button(context, BUTTON_A, 264ms, 80ms); +} +void roll_date_forward_1( + ConsoleHandle& console, ProControllerContext& context, + bool fast +){ + ConsoleType type = console.state().console_type(); + + if (is_switch1(type)){ + switch (context->performance_class()){ + case ControllerPerformanceClass::SerialPABotBase_Wired: + roll_date_forward_1_Switch1_wired(context, fast); + return; + case ControllerPerformanceClass::SerialPABotBase_Wireless: + roll_date_forward_1_Switch1_wireless(context); + return; + case ControllerPerformanceClass::SysbotBase: + roll_date_forward_1_Switch1_sbb(context); + return; + default: + throw InternalProgramError( + &console.logger(), PA_CURRENT_FUNCTION, + "Unsupported ControllerPerformanceClass: " + std::to_string((int)context->performance_class()) + ); + } + } + + if (is_switch2(type)){ + switch (context->performance_class()){ + case ControllerPerformanceClass::SerialPABotBase_Wired: + roll_date_forward_1_Switch2_wired(context); + return; + case ControllerPerformanceClass::SerialPABotBase_Wireless: + roll_date_forward_1_Switch2_wireless(context); + return; + default: + throw InternalProgramError( + &console.logger(), PA_CURRENT_FUNCTION, + "Unsupported ControllerPerformanceClass: " + std::to_string((int)context->performance_class()) + ); + } + return; + } + + throw UserSetupError( + console.logger(), + "Please select a valid Switch console type." + ); +} + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.h b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.h index 0fefab9761..7032e08c22 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.h @@ -1,29 +1,29 @@ -/* Nintendo Switch Roll Date Forward 1 - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_RollDateForward1_H -#define PokemonAutomation_NintendoSwitch_RollDateForward1_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -void roll_date_forward_1( - ConsoleHandle& console, ProControllerContext& context, - bool fast -); - - - - - -} -} -#endif +/* Nintendo Switch Roll Date Forward 1 + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_RollDateForward1_H +#define PokemonAutomation_NintendoSwitch_RollDateForward1_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +void roll_date_forward_1( + ConsoleHandle& console, ProControllerContext& context, + bool fast +); + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_CodeEntryTools.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_CodeEntryTools.cpp index ba5d89c540..9e4fdb4b02 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_CodeEntryTools.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_CodeEntryTools.cpp @@ -1,138 +1,138 @@ -/* Code Entry Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch_CodeEntryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace FastCodeEntry{ - - - - -void codeboard_populate_delays( - bool switch2, - std::vector& path_with_delays, - const std::vector& path, - const CodeEntryDelays& delays, - bool optimize -){ - // Populate and assign default delays first. - path_with_delays.resize(path.size()); - for (size_t c = 0; c < path_with_delays.size(); c++){ - CodeEntryAction action = path[c]; - Milliseconds delay; - if (action == CodeEntryAction::ENTER_CHAR){ - delay = delays.press_delay; - }else if (action == CodeEntryAction::SCROLL_LEFT){ - delay = delays.scroll_delay; - }else{ - delay = delays.move_delay; - } - - // If we are wrapping and the previous action is a move, then we can't - // overlap. - if (is_wrap(action) && c != 0){ - CodeEntryActionWithDelay& previous = path_with_delays[c - 1]; - if (is_move(previous.action)){ - previous.delay = delays.hold; - } - } - - path_with_delays[c].action = action; - path_with_delays[c].delay = delay; - } - - - // Pad out the stalls. - Milliseconds A_to_A_delay = std::max(delays.press_delay, delays.hold + delays.cool); - Milliseconds last_A_time = -1000ms; - Milliseconds current_time = 0ms; - for (size_t c = 1; c < path_with_delays.size(); c++){ - CodeEntryActionWithDelay& previous = path_with_delays[c - 1]; - CodeEntryActionWithDelay& current = path_with_delays[c]; - - // The Switch doesn't like overlapping the scroll with the A press. - // So we treat the left-scroll like an A press for timing purposes. - - if (current.action == CodeEntryAction::ENTER_CHAR || - (switch2 && current.action == CodeEntryAction::SCROLL_LEFT) - ){ - Milliseconds time_since_last_A = current_time - last_A_time; - if (time_since_last_A < A_to_A_delay){ - Milliseconds stall = A_to_A_delay - time_since_last_A; - previous.delay += stall; - current_time += stall; - } - last_A_time = current_time; - } - - current_time += current.delay; - } - - - // Optimize - - if (!optimize || path_with_delays.empty() || switch2){ - return; - } - - // These only work on the Switch 1. - for (size_t c = 1; c < path_with_delays.size(); c++){ - // Zero the delay for any L press. - CodeEntryActionWithDelay& current = path_with_delays[c]; - if (current.action == CodeEntryAction::SCROLL_LEFT){ - current.delay = 0ms; - continue; - } - - // Zero the delay for any scroll immediately preceding an A press. - CodeEntryActionWithDelay& previous = path_with_delays[c - 1]; - if (current.action == CodeEntryAction::ENTER_CHAR && - previous.action != CodeEntryAction::ENTER_CHAR && - previous.action != CodeEntryAction::SCROLL_LEFT - ){ - previous.delay = 0ms; - } - } -} - - - - -void codeboard_execute_path( - ProControllerContext& context, - const CodeEntryDelays& delays, - const std::vector& path -){ - for (const CodeEntryActionWithDelay& action : path){ - switch (action.action){ - case CodeEntryAction::ENTER_CHAR: - ssf_press_button(context, BUTTON_A, action.delay, delays.hold, delays.cool); - break; - case CodeEntryAction::SCROLL_LEFT: - ssf_press_button(context, BUTTON_L, action.delay, delays.hold, delays.cool); - break; - default: - ssf_issue_scroll( - context, - (DpadPosition)((uint8_t)action.action & 0x7f), - action.delay, delays.hold, delays.cool - ); - break; - } - } -} - - - - - - -} -} -} +/* Code Entry Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch_CodeEntryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace FastCodeEntry{ + + + + +void codeboard_populate_delays( + bool switch2, + std::vector& path_with_delays, + const std::vector& path, + const CodeEntryDelays& delays, + bool optimize +){ + // Populate and assign default delays first. + path_with_delays.resize(path.size()); + for (size_t c = 0; c < path_with_delays.size(); c++){ + CodeEntryAction action = path[c]; + Milliseconds delay; + if (action == CodeEntryAction::ENTER_CHAR){ + delay = delays.press_delay; + }else if (action == CodeEntryAction::SCROLL_LEFT){ + delay = delays.scroll_delay; + }else{ + delay = delays.move_delay; + } + + // If we are wrapping and the previous action is a move, then we can't + // overlap. + if (is_wrap(action) && c != 0){ + CodeEntryActionWithDelay& previous = path_with_delays[c - 1]; + if (is_move(previous.action)){ + previous.delay = delays.hold; + } + } + + path_with_delays[c].action = action; + path_with_delays[c].delay = delay; + } + + + // Pad out the stalls. + Milliseconds A_to_A_delay = std::max(delays.press_delay, delays.hold + delays.cool); + Milliseconds last_A_time = -1000ms; + Milliseconds current_time = 0ms; + for (size_t c = 1; c < path_with_delays.size(); c++){ + CodeEntryActionWithDelay& previous = path_with_delays[c - 1]; + CodeEntryActionWithDelay& current = path_with_delays[c]; + + // The Switch doesn't like overlapping the scroll with the A press. + // So we treat the left-scroll like an A press for timing purposes. + + if (current.action == CodeEntryAction::ENTER_CHAR || + (switch2 && current.action == CodeEntryAction::SCROLL_LEFT) + ){ + Milliseconds time_since_last_A = current_time - last_A_time; + if (time_since_last_A < A_to_A_delay){ + Milliseconds stall = A_to_A_delay - time_since_last_A; + previous.delay += stall; + current_time += stall; + } + last_A_time = current_time; + } + + current_time += current.delay; + } + + + // Optimize + + if (!optimize || path_with_delays.empty() || switch2){ + return; + } + + // These only work on the Switch 1. + for (size_t c = 1; c < path_with_delays.size(); c++){ + // Zero the delay for any L press. + CodeEntryActionWithDelay& current = path_with_delays[c]; + if (current.action == CodeEntryAction::SCROLL_LEFT){ + current.delay = 0ms; + continue; + } + + // Zero the delay for any scroll immediately preceding an A press. + CodeEntryActionWithDelay& previous = path_with_delays[c - 1]; + if (current.action == CodeEntryAction::ENTER_CHAR && + previous.action != CodeEntryAction::ENTER_CHAR && + previous.action != CodeEntryAction::SCROLL_LEFT + ){ + previous.delay = 0ms; + } + } +} + + + + +void codeboard_execute_path( + ProControllerContext& context, + const CodeEntryDelays& delays, + const std::vector& path +){ + for (const CodeEntryActionWithDelay& action : path){ + switch (action.action){ + case CodeEntryAction::ENTER_CHAR: + ssf_press_button(context, BUTTON_A, action.delay, delays.hold, delays.cool); + break; + case CodeEntryAction::SCROLL_LEFT: + ssf_press_button(context, BUTTON_L, action.delay, delays.hold, delays.cool); + break; + default: + ssf_issue_scroll( + context, + (DpadPosition)((uint8_t)action.action & 0x7f), + action.delay, delays.hold, delays.cool + ); + break; + } + } +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_CodeEntryTools.h b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_CodeEntryTools.h index 5e1518276e..6478a30976 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_CodeEntryTools.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_CodeEntryTools.h @@ -1,134 +1,134 @@ -/* Code Entry Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_CodeEntryTools_H -#define PokemonAutomation_NintendoSwitch_CodeEntryTools_H - -#include -#include -#include "Common/Cpp/Time.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerState.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace FastCodeEntry{ - - - - -enum class CodeEntryAction : uint8_t{ - ENTER_CHAR = 0xf0, - SCROLL_LEFT = 0xf1, - NORM_MOVE_UP = (uint8_t)DpadPosition::DPAD_UP, - NORM_MOVE_RIGHT = (uint8_t)DpadPosition::DPAD_RIGHT, - NORM_MOVE_DOWN = (uint8_t)DpadPosition::DPAD_DOWN, - NORM_MOVE_LEFT = (uint8_t)DpadPosition::DPAD_LEFT, - WRAP_MOVE_UP = 0x80 | (uint8_t)DpadPosition::DPAD_UP, - WRAP_MOVE_RIGHT = 0x80 | (uint8_t)DpadPosition::DPAD_RIGHT, - WRAP_MOVE_DOWN = 0x80 | (uint8_t)DpadPosition::DPAD_DOWN, - WRAP_MOVE_LEFT = 0x80 | (uint8_t)DpadPosition::DPAD_LEFT, -}; -inline bool is_button_press(CodeEntryAction action){ - switch (action){ - case CodeEntryAction::ENTER_CHAR: - case CodeEntryAction::SCROLL_LEFT: - return true; - default: - return false; - } -} -inline bool is_move(CodeEntryAction action){ - switch (action){ - case CodeEntryAction::NORM_MOVE_UP: - case CodeEntryAction::NORM_MOVE_RIGHT: - case CodeEntryAction::NORM_MOVE_DOWN: - case CodeEntryAction::NORM_MOVE_LEFT: - case CodeEntryAction::WRAP_MOVE_UP: - case CodeEntryAction::WRAP_MOVE_RIGHT: - case CodeEntryAction::WRAP_MOVE_DOWN: - case CodeEntryAction::WRAP_MOVE_LEFT: - return true; - default: - return false; - } -} -inline bool is_wrap(CodeEntryAction action){ - switch (action){ - case CodeEntryAction::WRAP_MOVE_UP: - case CodeEntryAction::WRAP_MOVE_RIGHT: - case CodeEntryAction::WRAP_MOVE_DOWN: - case CodeEntryAction::WRAP_MOVE_LEFT: - return true; - default: - return false; - } -} - - -struct CodeEntryDelays{ - Milliseconds hold; - Milliseconds cool; - Milliseconds press_delay; - Milliseconds move_delay; - Milliseconds scroll_delay; - Milliseconds wrap_delay; -}; - - -struct CodeEntryActionWithDelay{ - CodeEntryAction action; - Milliseconds delay; -}; - - - - -// Given a path, optimize it and fully populate the delays. -void codeboard_populate_delays( - bool switch2, - std::vector& path_with_delays, - const std::vector& path, - const CodeEntryDelays& delays, - bool optimize -); - - - - - -//inline Milliseconds calculate_path_delay(const std::vector& path){ - -//} - - - -// Actually execute a path and enter it into the Switch. -void codeboard_execute_path( - ProControllerContext& context, - const CodeEntryDelays& delays, - const std::vector& path -); - - - - - - - - - - - - - - - - -} -} -} -#endif +/* Code Entry Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_CodeEntryTools_H +#define PokemonAutomation_NintendoSwitch_CodeEntryTools_H + +#include +#include +#include "Common/Cpp/Time.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerState.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace FastCodeEntry{ + + + + +enum class CodeEntryAction : uint8_t{ + ENTER_CHAR = 0xf0, + SCROLL_LEFT = 0xf1, + NORM_MOVE_UP = (uint8_t)DpadPosition::DPAD_UP, + NORM_MOVE_RIGHT = (uint8_t)DpadPosition::DPAD_RIGHT, + NORM_MOVE_DOWN = (uint8_t)DpadPosition::DPAD_DOWN, + NORM_MOVE_LEFT = (uint8_t)DpadPosition::DPAD_LEFT, + WRAP_MOVE_UP = 0x80 | (uint8_t)DpadPosition::DPAD_UP, + WRAP_MOVE_RIGHT = 0x80 | (uint8_t)DpadPosition::DPAD_RIGHT, + WRAP_MOVE_DOWN = 0x80 | (uint8_t)DpadPosition::DPAD_DOWN, + WRAP_MOVE_LEFT = 0x80 | (uint8_t)DpadPosition::DPAD_LEFT, +}; +inline bool is_button_press(CodeEntryAction action){ + switch (action){ + case CodeEntryAction::ENTER_CHAR: + case CodeEntryAction::SCROLL_LEFT: + return true; + default: + return false; + } +} +inline bool is_move(CodeEntryAction action){ + switch (action){ + case CodeEntryAction::NORM_MOVE_UP: + case CodeEntryAction::NORM_MOVE_RIGHT: + case CodeEntryAction::NORM_MOVE_DOWN: + case CodeEntryAction::NORM_MOVE_LEFT: + case CodeEntryAction::WRAP_MOVE_UP: + case CodeEntryAction::WRAP_MOVE_RIGHT: + case CodeEntryAction::WRAP_MOVE_DOWN: + case CodeEntryAction::WRAP_MOVE_LEFT: + return true; + default: + return false; + } +} +inline bool is_wrap(CodeEntryAction action){ + switch (action){ + case CodeEntryAction::WRAP_MOVE_UP: + case CodeEntryAction::WRAP_MOVE_RIGHT: + case CodeEntryAction::WRAP_MOVE_DOWN: + case CodeEntryAction::WRAP_MOVE_LEFT: + return true; + default: + return false; + } +} + + +struct CodeEntryDelays{ + Milliseconds hold; + Milliseconds cool; + Milliseconds press_delay; + Milliseconds move_delay; + Milliseconds scroll_delay; + Milliseconds wrap_delay; +}; + + +struct CodeEntryActionWithDelay{ + CodeEntryAction action; + Milliseconds delay; +}; + + + + +// Given a path, optimize it and fully populate the delays. +void codeboard_populate_delays( + bool switch2, + std::vector& path_with_delays, + const std::vector& path, + const CodeEntryDelays& delays, + bool optimize +); + + + + + +//inline Milliseconds calculate_path_delay(const std::vector& path){ + +//} + + + +// Actually execute a path and enter it into the Switch. +void codeboard_execute_path( + ProControllerContext& context, + const CodeEntryDelays& delays, + const std::vector& path +); + + + + + + + + + + + + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.cpp index c2141b06e0..447307b9c8 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.cpp @@ -1,369 +1,369 @@ -/* Fast Code Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h" -#include "NintendoSwitch_CodeEntryTools.h" -#include "NintendoSwitch_KeyboardCodeEntry.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace FastCodeEntry{ - - -struct KeyboardEntryPosition{ - uint8_t row; - uint8_t col; -}; - -static const std::map& KEYBOARD_POSITIONS_QWERTY(){ - static const std::map map{ - {'1', {0, 0}}, - {'2', {0, 1}}, - {'3', {0, 2}}, - {'4', {0, 3}}, - {'5', {0, 4}}, - {'6', {0, 5}}, - {'7', {0, 6}}, - {'8', {0, 7}}, - {'9', {0, 8}}, - {'0', {0, 9}}, - - {'Q', {1, 0}}, - {'W', {1, 1}}, - {'E', {1, 2}}, - {'R', {1, 3}}, - {'T', {1, 4}}, - {'Y', {1, 5}}, - {'U', {1, 6}}, - {'P', {1, 9}}, - - {'A', {2, 0}}, - {'S', {2, 1}}, - {'D', {2, 2}}, - {'F', {2, 3}}, - {'G', {2, 4}}, - {'H', {2, 5}}, - {'J', {2, 6}}, - {'K', {2, 7}}, - {'L', {2, 8}}, - - {'X', {3, 1}}, - {'C', {3, 2}}, - {'V', {3, 3}}, - {'B', {3, 4}}, - {'N', {3, 5}}, - {'M', {3, 6}}, - }; - return map; -} -static const std::map& KEYBOARD_POSITIONS_AZERTY(){ - static const std::map map{ - {'1', {0, 0}}, - {'2', {0, 1}}, - {'3', {0, 2}}, - {'4', {0, 3}}, - {'5', {0, 4}}, - {'6', {0, 5}}, - {'7', {0, 6}}, - {'8', {0, 7}}, - {'9', {0, 8}}, - {'0', {0, 9}}, - - {'A', {1, 0}}, - {'E', {1, 2}}, - {'R', {1, 3}}, - {'T', {1, 4}}, - {'Y', {1, 5}}, - {'U', {1, 6}}, - {'P', {1, 9}}, - - {'Q', {2, 0}}, - {'S', {2, 1}}, - {'D', {2, 2}}, - {'F', {2, 3}}, - {'G', {2, 4}}, - {'H', {2, 5}}, - {'J', {2, 6}}, - {'K', {2, 7}}, - {'L', {2, 8}}, - {'M', {2, 9}}, - - {'W', {3, 0}}, - {'X', {3, 1}}, - {'C', {3, 2}}, - {'V', {3, 3}}, - {'B', {3, 4}}, - {'N', {3, 5}}, - }; - return map; -} - - - - - - -// Return the path from "source" to "destination". -std::vector keyboard_get_path( - KeyboardEntryPosition source, - KeyboardEntryPosition destination -){ - std::vector path; - - // Vertical is easy since there's no wrapping and no hazards. - if (source.row < destination.row){ - size_t diff = destination.row - source.row; - for (size_t c = 0; c < diff; c++){ - path.emplace_back(CodeEntryAction::NORM_MOVE_DOWN); - } - }else{ - size_t diff = source.row - destination.row; - for (size_t c = 0; c < diff; c++){ - path.emplace_back(CodeEntryAction::NORM_MOVE_UP); - } - } - - // Horizontal is messy because we need extra delay on wrapping. - uint8_t col = source.col; - while (true){ - if (col == destination.col){ - break; - } - - CodeEntryAction action; - if (destination.col > col){ - if (destination.col - col <= 6){ - action = CodeEntryAction::NORM_MOVE_RIGHT; - col++; - }else{ - action = CodeEntryAction::NORM_MOVE_LEFT; - col--; - } - }else{ - if (col - destination.col <= 6){ - action = CodeEntryAction::NORM_MOVE_LEFT; - col--; - }else{ - action = CodeEntryAction::NORM_MOVE_RIGHT; - col++; - } - } - - // Wrap around the sides. - if (col == (uint8_t)-1){ - col = 11; - action = (CodeEntryAction)((uint8_t)action | 0x80); - } - if (col == 12){ - col = 0; - action = (CodeEntryAction)((uint8_t)action | 0x80); - } - - path.emplace_back(action); - } - - path.emplace_back(CodeEntryAction::ENTER_CHAR); - - return path; -} - - -// Get all possible paths from "start" to cover everything [positions, positions + length). -std::vector> keyboard_get_all_paths( - KeyboardEntryPosition start, - const KeyboardEntryPosition* positions, size_t length, - bool reordering -){ - if (length == 1){ - return {keyboard_get_path(start, positions[0])}; - } - - std::vector> paths; - { - KeyboardEntryPosition position = positions[0]; - std::vector current = keyboard_get_path(start, position); - std::vector> subpaths = keyboard_get_all_paths( - position, - positions + 1, length - 1, - reordering - ); - for (std::vector& path : subpaths){ - path.insert(path.begin(), current.begin(), current.end()); - paths.emplace_back(std::move(path)); - } - } - if (reordering){ - KeyboardEntryPosition position = positions[length - 1]; - std::vector current = keyboard_get_path(start, position); - current.emplace_back(CodeEntryAction::SCROLL_LEFT); - std::vector> subpaths = keyboard_get_all_paths( - position, - positions, length - 1, - reordering - ); - for (std::vector& path : subpaths){ - path.insert(path.begin(), current.begin(), current.end()); - paths.emplace_back(std::move(path)); - } - } - - return paths; -} - - - - -// Given a set of paths, find the best one and return it with fully populated -// delays. -std::vector keyboard_get_best_path( - bool switch2, - const std::vector>& paths, - const CodeEntryDelays& delays, - bool optimize -){ - std::vector best_path; - Milliseconds best_time = Milliseconds::max(); - for (const std::vector& path : paths){ - std::vector current_path; - codeboard_populate_delays(switch2, current_path, path, delays, optimize); - Milliseconds current_time = 0ms; - for (CodeEntryActionWithDelay& action : current_path){ - current_time += action.delay; - } - if (best_time > current_time){ - best_time = current_time; - best_path = std::move(current_path); - } - } - return best_path; -} - - - - -void keyboard_enter_code( - ConsoleHandle& console, ProControllerContext& context, - KeyboardLayout keyboard_layout, const std::string& code, - bool include_plus -){ - // Calculate the coordinates. - auto get_keyboard_layout = [](KeyboardLayout keyboard_layout){ - switch (keyboard_layout){ - case KeyboardLayout::QWERTY: - return KEYBOARD_POSITIONS_QWERTY(); - case KeyboardLayout::AZERTY: - return KEYBOARD_POSITIONS_AZERTY(); - default: - return KEYBOARD_POSITIONS_QWERTY(); - } - }; - - const std::map& POSITION_MAP = get_keyboard_layout(keyboard_layout); - std::vector positions; - for (char ch : code){ - auto iter = POSITION_MAP.find(ch); - if (iter == POSITION_MAP.end()){ - throw_and_log( - console, ErrorReport::NO_ERROR_REPORT, - "Invalid code character." - ); - } - positions.emplace_back(iter->second); - } - - - ConsoleType console_type = console.state().console_type(); - bool switch2; - if (is_switch1(console_type)){ - switch2 = false; - }else if (is_switch2(console_type)){ - switch2 = true; - }else{ - throw UserSetupError( - console, - "Please select a valid Switch console type." - ); - } - - - // Compute the delays. - - Milliseconds unit; - Milliseconds hold; - Milliseconds cool; - bool reordering; - if (switch2){ - unit = ConsoleSettings::instance().SWITCH2_KEYBOARD_ENTRY.TIME_UNIT; - hold = ConsoleSettings::instance().SWITCH2_KEYBOARD_ENTRY.HOLD; - cool = ConsoleSettings::instance().SWITCH2_KEYBOARD_ENTRY.COOLDOWN; - reordering = ConsoleSettings::instance().SWITCH2_KEYBOARD_ENTRY.REORDERING; - }else{ - unit = ConsoleSettings::instance().SWITCH1_KEYBOARD_ENTRY.TIME_UNIT; - hold = ConsoleSettings::instance().SWITCH1_KEYBOARD_ENTRY.HOLD; - cool = ConsoleSettings::instance().SWITCH1_KEYBOARD_ENTRY.COOLDOWN; - reordering = ConsoleSettings::instance().SWITCH1_KEYBOARD_ENTRY.REORDERING; - } - - Milliseconds tv = context->timing_variation(); - unit += tv; - - CodeEntryDelays delays{ - .hold = hold, - .cool = cool, - .press_delay = unit, - .move_delay = unit, - .scroll_delay = unit, - .wrap_delay = 2*unit, - }; - - // Get all the possible paths. - std::vector> all_paths = keyboard_get_all_paths( - {0, 0}, - positions.data(), positions.size(), - reordering - ); - - // Pick the best path. - std::vector best_path = keyboard_get_best_path( - switch2, - all_paths, - delays, - !switch2 && context->atomic_multibutton() - ); - - codeboard_execute_path(context, delays, best_path); - - if (include_plus){ - ssf_press_button_ptv(context, BUTTON_PLUS); - ssf_press_button_ptv(context, BUTTON_PLUS); - } - - ssf_flush_pipeline(context); -} - - - - - - - - - - - - -} -} -} +/* Fast Code Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h" +#include "NintendoSwitch_CodeEntryTools.h" +#include "NintendoSwitch_KeyboardCodeEntry.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace FastCodeEntry{ + + +struct KeyboardEntryPosition{ + uint8_t row; + uint8_t col; +}; + +static const std::map& KEYBOARD_POSITIONS_QWERTY(){ + static const std::map map{ + {'1', {0, 0}}, + {'2', {0, 1}}, + {'3', {0, 2}}, + {'4', {0, 3}}, + {'5', {0, 4}}, + {'6', {0, 5}}, + {'7', {0, 6}}, + {'8', {0, 7}}, + {'9', {0, 8}}, + {'0', {0, 9}}, + + {'Q', {1, 0}}, + {'W', {1, 1}}, + {'E', {1, 2}}, + {'R', {1, 3}}, + {'T', {1, 4}}, + {'Y', {1, 5}}, + {'U', {1, 6}}, + {'P', {1, 9}}, + + {'A', {2, 0}}, + {'S', {2, 1}}, + {'D', {2, 2}}, + {'F', {2, 3}}, + {'G', {2, 4}}, + {'H', {2, 5}}, + {'J', {2, 6}}, + {'K', {2, 7}}, + {'L', {2, 8}}, + + {'X', {3, 1}}, + {'C', {3, 2}}, + {'V', {3, 3}}, + {'B', {3, 4}}, + {'N', {3, 5}}, + {'M', {3, 6}}, + }; + return map; +} +static const std::map& KEYBOARD_POSITIONS_AZERTY(){ + static const std::map map{ + {'1', {0, 0}}, + {'2', {0, 1}}, + {'3', {0, 2}}, + {'4', {0, 3}}, + {'5', {0, 4}}, + {'6', {0, 5}}, + {'7', {0, 6}}, + {'8', {0, 7}}, + {'9', {0, 8}}, + {'0', {0, 9}}, + + {'A', {1, 0}}, + {'E', {1, 2}}, + {'R', {1, 3}}, + {'T', {1, 4}}, + {'Y', {1, 5}}, + {'U', {1, 6}}, + {'P', {1, 9}}, + + {'Q', {2, 0}}, + {'S', {2, 1}}, + {'D', {2, 2}}, + {'F', {2, 3}}, + {'G', {2, 4}}, + {'H', {2, 5}}, + {'J', {2, 6}}, + {'K', {2, 7}}, + {'L', {2, 8}}, + {'M', {2, 9}}, + + {'W', {3, 0}}, + {'X', {3, 1}}, + {'C', {3, 2}}, + {'V', {3, 3}}, + {'B', {3, 4}}, + {'N', {3, 5}}, + }; + return map; +} + + + + + + +// Return the path from "source" to "destination". +std::vector keyboard_get_path( + KeyboardEntryPosition source, + KeyboardEntryPosition destination +){ + std::vector path; + + // Vertical is easy since there's no wrapping and no hazards. + if (source.row < destination.row){ + size_t diff = destination.row - source.row; + for (size_t c = 0; c < diff; c++){ + path.emplace_back(CodeEntryAction::NORM_MOVE_DOWN); + } + }else{ + size_t diff = source.row - destination.row; + for (size_t c = 0; c < diff; c++){ + path.emplace_back(CodeEntryAction::NORM_MOVE_UP); + } + } + + // Horizontal is messy because we need extra delay on wrapping. + uint8_t col = source.col; + while (true){ + if (col == destination.col){ + break; + } + + CodeEntryAction action; + if (destination.col > col){ + if (destination.col - col <= 6){ + action = CodeEntryAction::NORM_MOVE_RIGHT; + col++; + }else{ + action = CodeEntryAction::NORM_MOVE_LEFT; + col--; + } + }else{ + if (col - destination.col <= 6){ + action = CodeEntryAction::NORM_MOVE_LEFT; + col--; + }else{ + action = CodeEntryAction::NORM_MOVE_RIGHT; + col++; + } + } + + // Wrap around the sides. + if (col == (uint8_t)-1){ + col = 11; + action = (CodeEntryAction)((uint8_t)action | 0x80); + } + if (col == 12){ + col = 0; + action = (CodeEntryAction)((uint8_t)action | 0x80); + } + + path.emplace_back(action); + } + + path.emplace_back(CodeEntryAction::ENTER_CHAR); + + return path; +} + + +// Get all possible paths from "start" to cover everything [positions, positions + length). +std::vector> keyboard_get_all_paths( + KeyboardEntryPosition start, + const KeyboardEntryPosition* positions, size_t length, + bool reordering +){ + if (length == 1){ + return {keyboard_get_path(start, positions[0])}; + } + + std::vector> paths; + { + KeyboardEntryPosition position = positions[0]; + std::vector current = keyboard_get_path(start, position); + std::vector> subpaths = keyboard_get_all_paths( + position, + positions + 1, length - 1, + reordering + ); + for (std::vector& path : subpaths){ + path.insert(path.begin(), current.begin(), current.end()); + paths.emplace_back(std::move(path)); + } + } + if (reordering){ + KeyboardEntryPosition position = positions[length - 1]; + std::vector current = keyboard_get_path(start, position); + current.emplace_back(CodeEntryAction::SCROLL_LEFT); + std::vector> subpaths = keyboard_get_all_paths( + position, + positions, length - 1, + reordering + ); + for (std::vector& path : subpaths){ + path.insert(path.begin(), current.begin(), current.end()); + paths.emplace_back(std::move(path)); + } + } + + return paths; +} + + + + +// Given a set of paths, find the best one and return it with fully populated +// delays. +std::vector keyboard_get_best_path( + bool switch2, + const std::vector>& paths, + const CodeEntryDelays& delays, + bool optimize +){ + std::vector best_path; + Milliseconds best_time = Milliseconds::max(); + for (const std::vector& path : paths){ + std::vector current_path; + codeboard_populate_delays(switch2, current_path, path, delays, optimize); + Milliseconds current_time = 0ms; + for (CodeEntryActionWithDelay& action : current_path){ + current_time += action.delay; + } + if (best_time > current_time){ + best_time = current_time; + best_path = std::move(current_path); + } + } + return best_path; +} + + + + +void keyboard_enter_code( + ConsoleHandle& console, ProControllerContext& context, + KeyboardLayout keyboard_layout, const std::string& code, + bool include_plus +){ + // Calculate the coordinates. + auto get_keyboard_layout = [](KeyboardLayout keyboard_layout){ + switch (keyboard_layout){ + case KeyboardLayout::QWERTY: + return KEYBOARD_POSITIONS_QWERTY(); + case KeyboardLayout::AZERTY: + return KEYBOARD_POSITIONS_AZERTY(); + default: + return KEYBOARD_POSITIONS_QWERTY(); + } + }; + + const std::map& POSITION_MAP = get_keyboard_layout(keyboard_layout); + std::vector positions; + for (char ch : code){ + auto iter = POSITION_MAP.find(ch); + if (iter == POSITION_MAP.end()){ + throw_and_log( + console, ErrorReport::NO_ERROR_REPORT, + "Invalid code character." + ); + } + positions.emplace_back(iter->second); + } + + + ConsoleType console_type = console.state().console_type(); + bool switch2; + if (is_switch1(console_type)){ + switch2 = false; + }else if (is_switch2(console_type)){ + switch2 = true; + }else{ + throw UserSetupError( + console, + "Please select a valid Switch console type." + ); + } + + + // Compute the delays. + + Milliseconds unit; + Milliseconds hold; + Milliseconds cool; + bool reordering; + if (switch2){ + unit = ConsoleSettings::instance().SWITCH2_KEYBOARD_ENTRY.TIME_UNIT; + hold = ConsoleSettings::instance().SWITCH2_KEYBOARD_ENTRY.HOLD; + cool = ConsoleSettings::instance().SWITCH2_KEYBOARD_ENTRY.COOLDOWN; + reordering = ConsoleSettings::instance().SWITCH2_KEYBOARD_ENTRY.REORDERING; + }else{ + unit = ConsoleSettings::instance().SWITCH1_KEYBOARD_ENTRY.TIME_UNIT; + hold = ConsoleSettings::instance().SWITCH1_KEYBOARD_ENTRY.HOLD; + cool = ConsoleSettings::instance().SWITCH1_KEYBOARD_ENTRY.COOLDOWN; + reordering = ConsoleSettings::instance().SWITCH1_KEYBOARD_ENTRY.REORDERING; + } + + Milliseconds tv = context->timing_variation(); + unit += tv; + + CodeEntryDelays delays{ + .hold = hold + tv, + .cool = cool, + .press_delay = unit, + .move_delay = unit, + .scroll_delay = unit, + .wrap_delay = 2*unit, + }; + + // Get all the possible paths. + std::vector> all_paths = keyboard_get_all_paths( + {0, 0}, + positions.data(), positions.size(), + reordering + ); + + // Pick the best path. + std::vector best_path = keyboard_get_best_path( + switch2, + all_paths, + delays, + !switch2 && context->atomic_multibutton() + ); + + codeboard_execute_path(context, delays, best_path); + + if (include_plus){ + ssf_press_button_ptv(context, BUTTON_PLUS); + ssf_press_button_ptv(context, BUTTON_PLUS); + } + + ssf_flush_pipeline(context); +} + + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h index 6271a82bfc..f30d61f004 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h @@ -1,32 +1,32 @@ -/* Keyboard Code Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_KeyboardCodeEntry_H -#define PokemonAutomation_NintendoSwitch_KeyboardCodeEntry_H - -#include -#include "NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace FastCodeEntry{ - - - -void keyboard_enter_code( - ConsoleHandle& console, ProControllerContext& context, - KeyboardLayout keyboard_layout, const std::string& code, - bool include_plus -); - - - -} -} -} -#endif +/* Keyboard Code Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_KeyboardCodeEntry_H +#define PokemonAutomation_NintendoSwitch_KeyboardCodeEntry_H + +#include +#include "NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace FastCodeEntry{ + + + +void keyboard_enter_code( + ConsoleHandle& console, ProControllerContext& context, + KeyboardLayout keyboard_layout, const std::string& code, + bool include_plus +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.cpp index 2680b7731c..adf50b0fc0 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.cpp @@ -1,273 +1,273 @@ -/* Number Code Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h" -#include "NintendoSwitch_CodeEntryTools.h" -#include "NintendoSwitch_NumberCodeEntry.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace FastCodeEntry{ - - -struct NumberEntryPosition{ - uint8_t row; - uint8_t col; -}; - -static const std::map& NUMBER_POSITIONS(){ - static const std::map map{ - {1, {0, 0}}, - {2, {0, 1}}, - {3, {0, 2}}, - {4, {1, 0}}, - {5, {1, 1}}, - {6, {1, 2}}, - {7, {2, 0}}, - {8, {2, 1}}, - {9, {2, 2}}, - {0, {3, 1}}, - - {'1', {0, 0}}, - {'2', {0, 1}}, - {'3', {0, 2}}, - {'4', {1, 0}}, - {'5', {1, 1}}, - {'6', {1, 2}}, - {'7', {2, 0}}, - {'8', {2, 1}}, - {'9', {2, 2}}, - {'0', {3, 1}}, - }; - return map; -} - - - - - -// Return the path from "source" to "destination". -std::vector numberpad_get_path( - NumberEntryPosition source, - NumberEntryPosition destination -){ - std::vector path; - - uint8_t row = source.row; - uint8_t col = source.col; - - // Do vertical first since it may auto-center the horizontal position. - while (row < destination.row){ - path.emplace_back(CodeEntryAction::NORM_MOVE_DOWN); - row++; - } - while (row > destination.row){ - path.emplace_back(CodeEntryAction::NORM_MOVE_UP); - row--; - } - - // Moving to the zero automatically changes the column. - if (row == 3){ - col = 1; - } - - while (col < destination.col){ - path.emplace_back(CodeEntryAction::NORM_MOVE_RIGHT); - col++; - } - while (col > destination.col){ - path.emplace_back(CodeEntryAction::NORM_MOVE_LEFT); - col--; - } - - path.emplace_back(CodeEntryAction::ENTER_CHAR); - - return path; -} - - -// Get all possible paths from "start" to cover everything [positions, positions + length). -std::vector> numberpad_get_all_paths( - NumberEntryPosition start, - const NumberEntryPosition* positions, size_t length, - bool reordering -){ - if (length == 1){ - return {numberpad_get_path(start, positions[0])}; - } - - std::vector> paths; - { - NumberEntryPosition position = positions[0]; - std::vector current = numberpad_get_path(start, position); - std::vector> subpaths = numberpad_get_all_paths( - position, - positions + 1, length - 1, - reordering - ); - for (std::vector& path : subpaths){ - path.insert(path.begin(), current.begin(), current.end()); - paths.emplace_back(std::move(path)); - } - } - if (reordering){ - NumberEntryPosition position = positions[length - 1]; - std::vector current = numberpad_get_path(start, position); - current.emplace_back(CodeEntryAction::SCROLL_LEFT); - std::vector> subpaths = numberpad_get_all_paths( - position, - positions, length - 1, - reordering - ); - for (std::vector& path : subpaths){ - path.insert(path.begin(), current.begin(), current.end()); - paths.emplace_back(std::move(path)); - } - } - - return paths; -} - - - -// Given a set of paths, find the best one and return it with fully populated -// delays. -std::vector numberpad_get_best_path( - bool switch2, - const std::vector>& paths, - const CodeEntryDelays& delays, - bool optimize -){ - std::vector best_path; - Milliseconds best_time = Milliseconds::max(); - for (const std::vector& path : paths){ - std::vector current_path; - codeboard_populate_delays(switch2, current_path, path, delays, optimize); - Milliseconds current_time = 0ms; - for (CodeEntryActionWithDelay& action : current_path){ - current_time += action.delay; - if (action.action == CodeEntryAction::SCROLL_LEFT){ -// action.delay = - } - } - if (best_time > current_time){ - best_time = current_time; - best_path = std::move(current_path); - } - } - return best_path; -} - - - - -void numberpad_enter_code( - ConsoleHandle& console, ProControllerContext& context, - const std::string& code, - bool include_plus -){ - // Calculate the coordinates. - const std::map& POSITION_MAP = NUMBER_POSITIONS(); - std::vector positions; - for (char ch : code){ - auto iter = POSITION_MAP.find(ch); - if (iter == POSITION_MAP.end()){ - throw_and_log( - console, ErrorReport::NO_ERROR_REPORT, - "Invalid code character." - ); - } - positions.emplace_back(iter->second); - } - - - ConsoleType console_type = console.state().console_type(); - bool switch2; - if (is_switch1(console_type)){ - switch2 = false; - }else if (is_switch2(console_type)){ - switch2 = true; - }else{ - throw UserSetupError( - console, - "Please select a valid Switch console type." - ); - } - - - // Fetch the delays. - - Milliseconds unit; - Milliseconds hold; - Milliseconds cool; - bool reordering; - if (switch2){ - unit = ConsoleSettings::instance().SWITCH2_DIGIT_ENTRY.TIME_UNIT; - hold = ConsoleSettings::instance().SWITCH2_DIGIT_ENTRY.HOLD; - cool = ConsoleSettings::instance().SWITCH2_DIGIT_ENTRY.COOLDOWN; - reordering = ConsoleSettings::instance().SWITCH2_DIGIT_ENTRY.REORDERING; - }else{ - unit = ConsoleSettings::instance().SWITCH1_DIGIT_ENTRY.TIME_UNIT; - hold = ConsoleSettings::instance().SWITCH1_DIGIT_ENTRY.HOLD; - cool = ConsoleSettings::instance().SWITCH1_DIGIT_ENTRY.COOLDOWN; - reordering = ConsoleSettings::instance().SWITCH1_DIGIT_ENTRY.REORDERING; - } - - Milliseconds tv = context->timing_variation(); - unit += tv; - - CodeEntryDelays delays{ - .hold = hold, - .cool = cool, - .press_delay = unit, - .move_delay = unit, - .scroll_delay = unit, - .wrap_delay = 2*unit, - }; - - - // Get all the possible paths. - std::vector> all_paths = numberpad_get_all_paths( - {0, 0}, - positions.data(), positions.size(), - reordering - ); - - // Pick the best path. - std::vector best_path = numberpad_get_best_path( - switch2, - all_paths, - delays, - !switch2 && context->atomic_multibutton() - ); - - codeboard_execute_path(context, delays, best_path); - - if (include_plus){ - ssf_press_button_ptv(context, BUTTON_PLUS); - ssf_press_button_ptv(context, BUTTON_PLUS); - } - - ssf_flush_pipeline(context); -} - - - - - - - -} -} -} +/* Number Code Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h" +#include "NintendoSwitch_CodeEntryTools.h" +#include "NintendoSwitch_NumberCodeEntry.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace FastCodeEntry{ + + +struct NumberEntryPosition{ + uint8_t row; + uint8_t col; +}; + +static const std::map& NUMBER_POSITIONS(){ + static const std::map map{ + {1, {0, 0}}, + {2, {0, 1}}, + {3, {0, 2}}, + {4, {1, 0}}, + {5, {1, 1}}, + {6, {1, 2}}, + {7, {2, 0}}, + {8, {2, 1}}, + {9, {2, 2}}, + {0, {3, 1}}, + + {'1', {0, 0}}, + {'2', {0, 1}}, + {'3', {0, 2}}, + {'4', {1, 0}}, + {'5', {1, 1}}, + {'6', {1, 2}}, + {'7', {2, 0}}, + {'8', {2, 1}}, + {'9', {2, 2}}, + {'0', {3, 1}}, + }; + return map; +} + + + + + +// Return the path from "source" to "destination". +std::vector numberpad_get_path( + NumberEntryPosition source, + NumberEntryPosition destination +){ + std::vector path; + + uint8_t row = source.row; + uint8_t col = source.col; + + // Do vertical first since it may auto-center the horizontal position. + while (row < destination.row){ + path.emplace_back(CodeEntryAction::NORM_MOVE_DOWN); + row++; + } + while (row > destination.row){ + path.emplace_back(CodeEntryAction::NORM_MOVE_UP); + row--; + } + + // Moving to the zero automatically changes the column. + if (row == 3){ + col = 1; + } + + while (col < destination.col){ + path.emplace_back(CodeEntryAction::NORM_MOVE_RIGHT); + col++; + } + while (col > destination.col){ + path.emplace_back(CodeEntryAction::NORM_MOVE_LEFT); + col--; + } + + path.emplace_back(CodeEntryAction::ENTER_CHAR); + + return path; +} + + +// Get all possible paths from "start" to cover everything [positions, positions + length). +std::vector> numberpad_get_all_paths( + NumberEntryPosition start, + const NumberEntryPosition* positions, size_t length, + bool reordering +){ + if (length == 1){ + return {numberpad_get_path(start, positions[0])}; + } + + std::vector> paths; + { + NumberEntryPosition position = positions[0]; + std::vector current = numberpad_get_path(start, position); + std::vector> subpaths = numberpad_get_all_paths( + position, + positions + 1, length - 1, + reordering + ); + for (std::vector& path : subpaths){ + path.insert(path.begin(), current.begin(), current.end()); + paths.emplace_back(std::move(path)); + } + } + if (reordering){ + NumberEntryPosition position = positions[length - 1]; + std::vector current = numberpad_get_path(start, position); + current.emplace_back(CodeEntryAction::SCROLL_LEFT); + std::vector> subpaths = numberpad_get_all_paths( + position, + positions, length - 1, + reordering + ); + for (std::vector& path : subpaths){ + path.insert(path.begin(), current.begin(), current.end()); + paths.emplace_back(std::move(path)); + } + } + + return paths; +} + + + +// Given a set of paths, find the best one and return it with fully populated +// delays. +std::vector numberpad_get_best_path( + bool switch2, + const std::vector>& paths, + const CodeEntryDelays& delays, + bool optimize +){ + std::vector best_path; + Milliseconds best_time = Milliseconds::max(); + for (const std::vector& path : paths){ + std::vector current_path; + codeboard_populate_delays(switch2, current_path, path, delays, optimize); + Milliseconds current_time = 0ms; + for (CodeEntryActionWithDelay& action : current_path){ + current_time += action.delay; + if (action.action == CodeEntryAction::SCROLL_LEFT){ +// action.delay = + } + } + if (best_time > current_time){ + best_time = current_time; + best_path = std::move(current_path); + } + } + return best_path; +} + + + + +void numberpad_enter_code( + ConsoleHandle& console, ProControllerContext& context, + const std::string& code, + bool include_plus +){ + // Calculate the coordinates. + const std::map& POSITION_MAP = NUMBER_POSITIONS(); + std::vector positions; + for (char ch : code){ + auto iter = POSITION_MAP.find(ch); + if (iter == POSITION_MAP.end()){ + throw_and_log( + console, ErrorReport::NO_ERROR_REPORT, + "Invalid code character." + ); + } + positions.emplace_back(iter->second); + } + + + ConsoleType console_type = console.state().console_type(); + bool switch2; + if (is_switch1(console_type)){ + switch2 = false; + }else if (is_switch2(console_type)){ + switch2 = true; + }else{ + throw UserSetupError( + console, + "Please select a valid Switch console type." + ); + } + + + // Fetch the delays. + + Milliseconds unit; + Milliseconds hold; + Milliseconds cool; + bool reordering; + if (switch2){ + unit = ConsoleSettings::instance().SWITCH2_DIGIT_ENTRY.TIME_UNIT; + hold = ConsoleSettings::instance().SWITCH2_DIGIT_ENTRY.HOLD; + cool = ConsoleSettings::instance().SWITCH2_DIGIT_ENTRY.COOLDOWN; + reordering = ConsoleSettings::instance().SWITCH2_DIGIT_ENTRY.REORDERING; + }else{ + unit = ConsoleSettings::instance().SWITCH1_DIGIT_ENTRY.TIME_UNIT; + hold = ConsoleSettings::instance().SWITCH1_DIGIT_ENTRY.HOLD; + cool = ConsoleSettings::instance().SWITCH1_DIGIT_ENTRY.COOLDOWN; + reordering = ConsoleSettings::instance().SWITCH1_DIGIT_ENTRY.REORDERING; + } + + Milliseconds tv = context->timing_variation(); + unit += tv; + + CodeEntryDelays delays{ + .hold = hold + tv, + .cool = cool, + .press_delay = unit, + .move_delay = unit, + .scroll_delay = unit, + .wrap_delay = 2*unit, + }; + + + // Get all the possible paths. + std::vector> all_paths = numberpad_get_all_paths( + {0, 0}, + positions.data(), positions.size(), + reordering + ); + + // Pick the best path. + std::vector best_path = numberpad_get_best_path( + switch2, + all_paths, + delays, + !switch2 && context->atomic_multibutton() + ); + + codeboard_execute_path(context, delays, best_path); + + if (include_plus){ + ssf_press_button_ptv(context, BUTTON_PLUS); + ssf_press_button_ptv(context, BUTTON_PLUS); + } + + ssf_flush_pipeline(context); +} + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h index 78cc1afd77..462241a506 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h @@ -1,31 +1,31 @@ -/* Number Code Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_NumberCodeEntry_H -#define PokemonAutomation_NintendoSwitch_NumberCodeEntry_H - -#include -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace FastCodeEntry{ - - - -void numberpad_enter_code( - ConsoleHandle& console, ProControllerContext& context, - const std::string& code, - bool include_plus -); - - - -} -} -} -#endif +/* Number Code Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_NumberCodeEntry_H +#define PokemonAutomation_NintendoSwitch_NumberCodeEntry_H + +#include +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace FastCodeEntry{ + + + +void numberpad_enter_code( + ConsoleHandle& console, ProControllerContext& context, + const std::string& code, + bool include_plus +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_DateSkippers.h b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_DateSkippers.h index 7eb737bb15..dd00acc076 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_DateSkippers.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_DateSkippers.h @@ -1,43 +1,43 @@ -/* Date Skippers - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_DateSkippers_H -#define PokemonAutomation_NintendoSwitch_DateSkippers_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "CommonFramework/Tools/VideoStream.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace DateSkippers{ - - -namespace Switch1{ - void init_view(ProControllerContext& context); - void auto_recovery(ProControllerContext& context); - void increment_day_with_feedback(VideoStream& stream, ProControllerContext& context, bool date_us); - void increment_day(ProControllerContext& context, bool date_us); - void rollback_year_full(ProControllerContext& context, bool date_us); - void rollback_year_sync(ProControllerContext& context); - void increment_monthday(ProControllerContext& context); - void increment_daymonth(ProControllerContext& context); - void increment_month(ProControllerContext& context, uint8_t days); - void increment_all(ProControllerContext& context); - void increment_all_rollback(ProControllerContext& context); -} -namespace Switch2{ - void init_view(ProControllerContext& context); - void increment_day_us(ProControllerContext& context); - void increment_day_eu(ProControllerContext& context); - void increment_day_jp(ProControllerContext& context); -} - - - -} -} -} -#endif +/* Date Skippers + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_DateSkippers_H +#define PokemonAutomation_NintendoSwitch_DateSkippers_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "CommonFramework/Tools/VideoStream.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace DateSkippers{ + + +namespace Switch1{ + void init_view(ProControllerContext& context); + void auto_recovery(ProControllerContext& context); + void increment_day_with_feedback(VideoStream& stream, ProControllerContext& context, bool date_us); + void increment_day(ProControllerContext& context, bool date_us); + void rollback_year_full(ProControllerContext& context, bool date_us); + void rollback_year_sync(ProControllerContext& context); + void increment_monthday(ProControllerContext& context); + void increment_daymonth(ProControllerContext& context); + void increment_month(ProControllerContext& context, uint8_t days); + void increment_all(ProControllerContext& context); + void increment_all_rollback(ProControllerContext& context); +} +namespace Switch2{ + void init_view(ProControllerContext& context); + void increment_day_us(ProControllerContext& context); + void increment_day_eu(ProControllerContext& context); + void increment_day_jp(ProControllerContext& context); +} + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_FriendCodeAdder.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_FriendCodeAdder.cpp index 2b2ecd526f..059312b9da 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_FriendCodeAdder.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_FriendCodeAdder.cpp @@ -8,6 +8,7 @@ #include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" #include "NintendoSwitch/NintendoSwitch_Settings.h" #include "NintendoSwitch_FriendCodeAdder.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" #include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h" #include "PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.h" @@ -72,6 +73,8 @@ FriendCodeAdder::FriendCodeAdder() void FriendCodeAdder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ grip_menu_connect_go_home(context); + ensure_at_home(env.console, context); + ConsoleType type = env.console.state().console_type(); uint8_t scroll_down_slots = 0; if (is_switch1(type)){ diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_GameEntry.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_GameEntry.cpp index 6f92e9463b..13b2658aff 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_GameEntry.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_GameEntry.cpp @@ -32,31 +32,50 @@ namespace NintendoSwitch{ +void go_home(ConsoleHandle& console, ProControllerContext& context){ + pbf_press_button(context, BUTTON_HOME, 160ms, 0ms); + if (!console.video().snapshot()){ + pbf_wait(context, 640ms); + return; + } + + ensure_at_home(console, context); +} -void wait_for_home(ConsoleHandle& console, ProControllerContext& context){ +template +void ensure_at_home(ConsoleHandle& console, ControllerContext& context){ // Feedback not available. Just assume we're already on Home. if (!console.video().snapshot()){ + pbf_wait(context, 640ms); return; } - for (size_t attempts = 0;; attempts++){ + for (size_t attempts = 0; attempts < 10; attempts++){ HomeMenuWatcher home_menu(console, 100ms); int ret = wait_until( console, context, 5000ms, {home_menu} ); if (ret == 0){ - break; - } - if (attempts == 2){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to find Switch Home", - console - ); + return; } + console.log("Unable to detect Home. Pressing Home button...", COLOR_RED); + pbf_press_button(context, BUTTON_HOME, 160ms, 0ms); } + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to find Switch Home", + console + ); +} + + +void ensure_at_home(ConsoleHandle& console, ProControllerContext& context){ + ensure_at_home(console, context); +} +void ensure_at_home(ConsoleHandle& console, JoyconContext& context){ + ensure_at_home(console, context); } diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_GameEntry.h b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_GameEntry.h index be8ad300ea..a2f3f7efa7 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_GameEntry.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_GameEntry.h @@ -16,7 +16,9 @@ namespace PokemonAutomation{ namespace NintendoSwitch{ -void wait_for_home(ConsoleHandle& console, ProControllerContext& context); +void go_home(ConsoleHandle& console, ProControllerContext& context); +void ensure_at_home(ConsoleHandle& console, ProControllerContext& context); +void ensure_at_home(ConsoleHandle& console, JoyconContext& context); diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_MenuStabilityTester.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_MenuStabilityTester.cpp index 126b08c5b1..d73a88ec24 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_MenuStabilityTester.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_MenuStabilityTester.cpp @@ -1,177 +1,177 @@ -/* Friend Delete - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch_MenuStabilityTester.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -MenuStabilityTester_Descriptor::MenuStabilityTester_Descriptor() - : SingleSwitchProgramDescriptor( - "NintendoSwitch:MenuStabilityTester", - "Nintendo Switch", "Menu Stability Tester", - "", - "Test the speed and stability of various fast menu movements.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - -MenuStabilityTester::~MenuStabilityTester(){ - TEST_TYPE.remove_listener(*this); -} -MenuStabilityTester::MenuStabilityTester() - : TEST_TYPE( - std::move("Console Type:"), - { - {TestType::Vertical, "vertical", "Vertical Up-Down"}, - {TestType::Horizontal, "horizontal", "Horizontal Side-to-Side"}, - {TestType::SimultaneousScrollA, "scroll-A", "Simultaneous Scroll + A"}, - }, - LockMode::LOCK_WHILE_RUNNING, - TestType::Vertical - ) - , VERTICAL_RANGE( - "Vertical Scroll Range:", - LockMode::LOCK_WHILE_RUNNING, - 20 - ) - , HORIZONTAL_RANGE( - "Horizontal Scroll Range:", - LockMode::LOCK_WHILE_RUNNING, - 4 - ) - , PAUSE_BEFORE_UTURN( - "Pause Before Turning Around:", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , DELAY_TO_NEXT( - "Delay to Next Button:", - LockMode::LOCK_WHILE_RUNNING, - "24 ms" - ) - , HOLD_DURATION( - "Hold Duration:", - LockMode::LOCK_WHILE_RUNNING, - "48 ms" - ) - , COOLDOWN( - "Cooldown:", - LockMode::LOCK_WHILE_RUNNING, - "24 ms" - ) -{ - PA_ADD_OPTION(TEST_TYPE); - - PA_ADD_OPTION(VERTICAL_RANGE); - PA_ADD_OPTION(HORIZONTAL_RANGE); - PA_ADD_OPTION(PAUSE_BEFORE_UTURN); - - PA_ADD_OPTION(DELAY_TO_NEXT); - PA_ADD_OPTION(HOLD_DURATION); - PA_ADD_OPTION(COOLDOWN); - - MenuStabilityTester::on_config_value_changed(this); - - TEST_TYPE.add_listener(*this); -} -void MenuStabilityTester::on_config_value_changed(void* object){ - switch (TEST_TYPE){ - case TestType::Vertical: - VERTICAL_RANGE.set_visibility(ConfigOptionState::ENABLED); - HORIZONTAL_RANGE.set_visibility(ConfigOptionState::HIDDEN); - PAUSE_BEFORE_UTURN.set_visibility(ConfigOptionState::ENABLED); - break; - case TestType::Horizontal: - VERTICAL_RANGE.set_visibility(ConfigOptionState::HIDDEN); - HORIZONTAL_RANGE.set_visibility(ConfigOptionState::ENABLED); - PAUSE_BEFORE_UTURN.set_visibility(ConfigOptionState::ENABLED); - break; - case TestType::SimultaneousScrollA: - VERTICAL_RANGE.set_visibility(ConfigOptionState::HIDDEN); - HORIZONTAL_RANGE.set_visibility(ConfigOptionState::HIDDEN); - PAUSE_BEFORE_UTURN.set_visibility(ConfigOptionState::HIDDEN); - break; - } -} - - - - -void MenuStabilityTester::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - switch (TEST_TYPE){ - case TestType::Vertical: - while (true){ - for (size_t c = 0; c < VERTICAL_RANGE; c++){ - ssf_issue_scroll(context, DPAD_DOWN, DELAY_TO_NEXT, HOLD_DURATION, COOLDOWN); - } - if (PAUSE_BEFORE_UTURN){ - ssf_do_nothing(context, 1000ms); - } - for (size_t c = 0; c < VERTICAL_RANGE; c++){ - ssf_issue_scroll(context, DPAD_UP, DELAY_TO_NEXT, HOLD_DURATION, COOLDOWN); - } - if (PAUSE_BEFORE_UTURN){ - ssf_do_nothing(context, 1000ms); - } - } - break; - - case TestType::Horizontal: - while (true){ - for (size_t c = 0; c < HORIZONTAL_RANGE; c++){ - ssf_issue_scroll(context, DPAD_RIGHT, DELAY_TO_NEXT, HOLD_DURATION, COOLDOWN); - } - if (PAUSE_BEFORE_UTURN){ - ssf_do_nothing(context, 1000ms); - } - for (size_t c = 0; c < HORIZONTAL_RANGE; c++){ - ssf_issue_scroll(context, DPAD_LEFT, DELAY_TO_NEXT, HOLD_DURATION, COOLDOWN); - } - if (PAUSE_BEFORE_UTURN){ - ssf_do_nothing(context, 1000ms); - } - } - break; - - case TestType::SimultaneousScrollA: - while (true){ - ssf_press_button(context, BUTTON_A, 0ms, HOLD_DURATION, COOLDOWN); - ssf_issue_scroll(context, DPAD_UP, DELAY_TO_NEXT, HOLD_DURATION, COOLDOWN); - ssf_do_nothing(context, 1000ms); - } - break; - - } -} - - - - - - - - - - - - - - - - - - - - -} -} +/* Friend Delete + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch_MenuStabilityTester.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +MenuStabilityTester_Descriptor::MenuStabilityTester_Descriptor() + : SingleSwitchProgramDescriptor( + "NintendoSwitch:MenuStabilityTester", + "Nintendo Switch", "Menu Stability Tester", + "", + "Test the speed and stability of various fast menu movements.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + +MenuStabilityTester::~MenuStabilityTester(){ + TEST_TYPE.remove_listener(*this); +} +MenuStabilityTester::MenuStabilityTester() + : TEST_TYPE( + std::move("Console Type:"), + { + {TestType::Vertical, "vertical", "Vertical Up-Down"}, + {TestType::Horizontal, "horizontal", "Horizontal Side-to-Side"}, + {TestType::SimultaneousScrollA, "scroll-A", "Simultaneous Scroll + A"}, + }, + LockMode::LOCK_WHILE_RUNNING, + TestType::Vertical + ) + , VERTICAL_RANGE( + "Vertical Scroll Range:", + LockMode::LOCK_WHILE_RUNNING, + 20 + ) + , HORIZONTAL_RANGE( + "Horizontal Scroll Range:", + LockMode::LOCK_WHILE_RUNNING, + 4 + ) + , PAUSE_BEFORE_UTURN( + "Pause Before Turning Around:", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , DELAY_TO_NEXT( + "Delay to Next Button:", + LockMode::LOCK_WHILE_RUNNING, + "24 ms" + ) + , HOLD_DURATION( + "Hold Duration:", + LockMode::LOCK_WHILE_RUNNING, + "48 ms" + ) + , COOLDOWN( + "Cooldown:", + LockMode::LOCK_WHILE_RUNNING, + "24 ms" + ) +{ + PA_ADD_OPTION(TEST_TYPE); + + PA_ADD_OPTION(VERTICAL_RANGE); + PA_ADD_OPTION(HORIZONTAL_RANGE); + PA_ADD_OPTION(PAUSE_BEFORE_UTURN); + + PA_ADD_OPTION(DELAY_TO_NEXT); + PA_ADD_OPTION(HOLD_DURATION); + PA_ADD_OPTION(COOLDOWN); + + MenuStabilityTester::on_config_value_changed(this); + + TEST_TYPE.add_listener(*this); +} +void MenuStabilityTester::on_config_value_changed(void* object){ + switch (TEST_TYPE){ + case TestType::Vertical: + VERTICAL_RANGE.set_visibility(ConfigOptionState::ENABLED); + HORIZONTAL_RANGE.set_visibility(ConfigOptionState::HIDDEN); + PAUSE_BEFORE_UTURN.set_visibility(ConfigOptionState::ENABLED); + break; + case TestType::Horizontal: + VERTICAL_RANGE.set_visibility(ConfigOptionState::HIDDEN); + HORIZONTAL_RANGE.set_visibility(ConfigOptionState::ENABLED); + PAUSE_BEFORE_UTURN.set_visibility(ConfigOptionState::ENABLED); + break; + case TestType::SimultaneousScrollA: + VERTICAL_RANGE.set_visibility(ConfigOptionState::HIDDEN); + HORIZONTAL_RANGE.set_visibility(ConfigOptionState::HIDDEN); + PAUSE_BEFORE_UTURN.set_visibility(ConfigOptionState::HIDDEN); + break; + } +} + + + + +void MenuStabilityTester::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + switch (TEST_TYPE){ + case TestType::Vertical: + while (true){ + for (size_t c = 0; c < VERTICAL_RANGE; c++){ + ssf_issue_scroll(context, DPAD_DOWN, DELAY_TO_NEXT, HOLD_DURATION, COOLDOWN); + } + if (PAUSE_BEFORE_UTURN){ + ssf_do_nothing(context, 1000ms); + } + for (size_t c = 0; c < VERTICAL_RANGE; c++){ + ssf_issue_scroll(context, DPAD_UP, DELAY_TO_NEXT, HOLD_DURATION, COOLDOWN); + } + if (PAUSE_BEFORE_UTURN){ + ssf_do_nothing(context, 1000ms); + } + } + break; + + case TestType::Horizontal: + while (true){ + for (size_t c = 0; c < HORIZONTAL_RANGE; c++){ + ssf_issue_scroll(context, DPAD_RIGHT, DELAY_TO_NEXT, HOLD_DURATION, COOLDOWN); + } + if (PAUSE_BEFORE_UTURN){ + ssf_do_nothing(context, 1000ms); + } + for (size_t c = 0; c < HORIZONTAL_RANGE; c++){ + ssf_issue_scroll(context, DPAD_LEFT, DELAY_TO_NEXT, HOLD_DURATION, COOLDOWN); + } + if (PAUSE_BEFORE_UTURN){ + ssf_do_nothing(context, 1000ms); + } + } + break; + + case TestType::SimultaneousScrollA: + while (true){ + ssf_press_button(context, BUTTON_A, 0ms, HOLD_DURATION, COOLDOWN); + ssf_issue_scroll(context, DPAD_UP, DELAY_TO_NEXT, HOLD_DURATION, COOLDOWN); + ssf_do_nothing(context, 1000ms); + } + break; + + } +} + + + + + + + + + + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_MenuStabilityTester.h b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_MenuStabilityTester.h index 29754710ff..32812cba04 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_MenuStabilityTester.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_MenuStabilityTester.h @@ -1,65 +1,65 @@ -/* Menu Stability Tester - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_MenuStabilityTester_H -#define PokemonAutomation_NintendoSwitch_MenuStabilityTester_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - -class MenuStabilityTester_Descriptor : public SingleSwitchProgramDescriptor{ -public: - MenuStabilityTester_Descriptor(); -}; - - - -class MenuStabilityTester : public SingleSwitchProgramInstance, private ConfigOption::Listener{ -public: - ~MenuStabilityTester(); - MenuStabilityTester(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - virtual void on_config_value_changed(void* object) override; - -private: - enum class TestType{ - Vertical, - Horizontal, - SimultaneousScrollA, - }; - - EnumDropdownOption TEST_TYPE; - SimpleIntegerOption VERTICAL_RANGE; - SimpleIntegerOption HORIZONTAL_RANGE; - BooleanCheckBoxOption PAUSE_BEFORE_UTURN; - - MillisecondsOption DELAY_TO_NEXT; - MillisecondsOption HOLD_DURATION; - MillisecondsOption COOLDOWN; - -}; - - - - -} -} -#endif - - - +/* Menu Stability Tester + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_MenuStabilityTester_H +#define PokemonAutomation_NintendoSwitch_MenuStabilityTester_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + +class MenuStabilityTester_Descriptor : public SingleSwitchProgramDescriptor{ +public: + MenuStabilityTester_Descriptor(); +}; + + + +class MenuStabilityTester : public SingleSwitchProgramInstance, private ConfigOption::Listener{ +public: + ~MenuStabilityTester(); + MenuStabilityTester(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + virtual void on_config_value_changed(void* object) override; + +private: + enum class TestType{ + Vertical, + Horizontal, + SimultaneousScrollA, + }; + + EnumDropdownOption TEST_TYPE; + SimpleIntegerOption VERTICAL_RANGE; + SimpleIntegerOption HORIZONTAL_RANGE; + BooleanCheckBoxOption PAUSE_BEFORE_UTURN; + + MillisecondsOption DELAY_TO_NEXT; + MillisecondsOption HOLD_DURATION; + MillisecondsOption COOLDOWN; + +}; + + + + +} +} +#endif + + + diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_PreventSleep.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_PreventSleep.cpp index 5aca84212a..9cddc3f3ef 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_PreventSleep.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_PreventSleep.cpp @@ -29,7 +29,7 @@ PreventSleep::PreventSleep(){} void PreventSleep::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ while (true){ - ssf_press_button2(context, BUTTON_B, 15 * TICKS_PER_SECOND, 10); + ssf_press_button(context, BUTTON_B, 15000ms, 80ms); } } diff --git a/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokeballNames.cpp b/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokeballNames.cpp index 8b4b278f9f..bd47ad0911 100644 --- a/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokeballNames.cpp +++ b/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokeballNames.cpp @@ -42,11 +42,17 @@ PokeballNameDatabase::PokeballNameDatabase(){ std::string& slug = item.to_string_throw(path_slugs); ordered_list.emplace_back(slug); - JsonObject& languages = item_disp.get_object_throw(slug, path_disp); - std::string& display_name = languages.get_string_throw("eng", path_disp); - - database[slug].m_display_name = display_name; - reverse_lookup[std::move(display_name)] = std::move(slug); + JsonObject* languages = item_disp.get_object(slug); + std::string* display_name; + if (languages != nullptr){ + // TODO: REMOVE: Display names for PLA balls. + display_name = &languages->get_string_throw("eng", path_disp); + }else{ + display_name = &slug; + } + + database[slug].m_display_name = *display_name; + reverse_lookup[*display_name] = slug; } } diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_DialogDetector.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_DialogDetector.cpp index 3097ab5c85..22781e6b26 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_DialogDetector.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_DialogDetector.cpp @@ -59,17 +59,6 @@ bool ShortDialogDetector::detect(const ImageViewRGB32& screen){ } -ShortDialogWatcher::ShortDialogWatcher(Color color) - : ShortDialogDetector(color) - , VisualInferenceCallback("ShortDialogWatcher") -{} -void ShortDialogWatcher::make_overlays(VideoOverlaySet& items) const{ - ShortDialogDetector::make_overlays(items); -} -bool ShortDialogWatcher::process_frame(const ImageViewRGB32& frame, WallClock){ - return detect(frame); -} - diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h index 06d3e29e40..fe7c90cbb0 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h @@ -33,12 +33,11 @@ class ShortDialogDetector : public StaticScreenDetector{ ImageFloatBox m_right_white; ImageFloatBox m_right; }; -class ShortDialogWatcher : public ShortDialogDetector, public VisualInferenceCallback{ +class ShortDialogWatcher : public DetectorToFinder{ public: - ShortDialogWatcher(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + ShortDialogWatcher(Color color = COLOR_RED) + : DetectorToFinder("ShortDialogWatcher", std::chrono::milliseconds(250), color) + {} }; diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_PokeballSpriteMatcher.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_PokeballSpriteMatcher.cpp index 3e405bda89..dd883c3fef 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_PokeballSpriteMatcher.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_PokeballSpriteMatcher.cpp @@ -22,8 +22,6 @@ PokeballSpriteMatcher::PokeballSpriteMatcher(double min_euclidean_distance) add(item.first, item.second.sprite); } } - - auto PokeballSpriteMatcher::get_crop_candidates(const ImageViewRGB32& image) const -> std::vector{ ImageStats border = image_border_stats(image); ImagePixelBox box = ImageMatch::enclosing_rectangle_with_pixel_filter( diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinySparkleSet.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinySparkleSet.cpp index 7a741b023f..1799517c8e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinySparkleSet.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinySparkleSet.cpp @@ -5,7 +5,9 @@ */ #include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Concurrency/SpinLock.h" #include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonFramework/Tools/GlobalThreadPools.h" #include "CommonTools/Images/BinaryImage_FilterRgb32.h" #include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorRadial.h" #include "PokemonBDSP_ShinySparkleSet.h" @@ -116,19 +118,25 @@ void ShinySparkleSetBDSP::read_from_image(size_t screen_area, const ImageViewRGB {0xff909000, 0xffffffff}, } ); - auto session = make_WaterfillSession(); + SpinLock lock; double best_alpha = 0; - for (PackedBinaryMatrix& matrix : matrices){ - session->set_source(matrix); - ShinySparkleSetBDSP sparkles = find_sparkles(screen_area, *session); - sparkles.update_alphas(); - double alpha = sparkles.alpha_overall(); - if (best_alpha < alpha){ - best_alpha = alpha; - *this = std::move(sparkles); - } - } + GlobalThreadPools::realtime_inference().run_in_parallel( + [&](size_t index){ + auto session = make_WaterfillSession(); + session->set_source(matrices[index]); + ShinySparkleSetBDSP sparkles = find_sparkles(screen_area, *session); + sparkles.update_alphas(); + double alpha = sparkles.alpha_overall(); + + WriteSpinLock lg(lock); + if (best_alpha < alpha){ + best_alpha = alpha; + *this = std::move(sparkles); + } + }, + 0, matrices.size(), 1 + ); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggRoutines.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggRoutines.cpp index 61473435be..7b212d5310 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggRoutines.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggRoutines.cpp @@ -29,7 +29,7 @@ void egg_spin(ProControllerContext& context, Milliseconds duration){ } void egg_spin_with_A(ProControllerContext& context, Milliseconds duration){ for (Milliseconds c = 0ms; c < duration; c += 42*8ms){ - ssf_press_button(context, BUTTON_ZL, 0, 10); + ssf_press_button(context, BUTTON_ZL, 0ms, 80ms); pbf_move_left_joystick(context, 0, 0, 5, 0); pbf_move_left_joystick(context, 128, 0, 5, 0); pbf_move_left_joystick(context, 255, 0, 5, 0); @@ -45,7 +45,7 @@ void pickup_column(ProControllerContext& context){ // const uint16_t BOX_SCROLL_DELAY = GameSettings::instance().BOX_SCROLL_DELAY_0; pbf_press_button(context, BUTTON_ZL, 20, 50); for (size_t c = 0; c < 30; c++){ - ssf_issue_scroll(context, DPAD_DOWN, 3); + ssf_issue_scroll(context, DPAD_DOWN, 24ms); } pbf_press_button(context, BUTTON_ZL, 160ms, GameSettings::instance().BOX_PICKUP_DROP_DELAY0); } diff --git a/SerialPrograms/Source/PokemonHome/Inference/PokemonHome_BallReader.cpp b/SerialPrograms/Source/PokemonHome/Inference/PokemonHome_BallReader.cpp index 611eea9c30..279f48acca 100644 --- a/SerialPrograms/Source/PokemonHome/Inference/PokemonHome_BallReader.cpp +++ b/SerialPrograms/Source/PokemonHome/Inference/PokemonHome_BallReader.cpp @@ -4,11 +4,15 @@ * */ +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" #include "CommonFramework/ImageTypes/ImageViewRGB32.h" #include "CommonFramework/Notifications/ProgramInfo.h" #include "CommonFramework/Tools/ErrorDumper.h" -#include "PokemonSwSh/Resources/PokemonSwSh_PokeballSprites.h" -#include "PokemonBDSP/Inference/PokemonBDSP_PokeballSpriteMatcher.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/ImageMatch/ImageCropper.h" +#include "PokemonHome/Resources/PokemonHome_PokeballSprites.h" +//#include "PokemonSwSh/Resources/PokemonSwSh_PokeballSprites.h" +//#include "PokemonBDSP/Inference/PokemonBDSP_PokeballSpriteMatcher.h" #include "PokemonHome_BallReader.h" namespace PokemonAutomation{ @@ -16,12 +20,70 @@ namespace NintendoSwitch{ namespace PokemonHome{ + + +PokeballSpriteMatcher::PokeballSpriteMatcher(double min_euclidean_distance) + : CroppedImageDictionaryMatcher({1, 128}) + , m_min_euclidean_distance_squared(min_euclidean_distance * min_euclidean_distance) +{ + for (const auto& item : PokemonHome::ALL_POKEBALL_SPRITES()){ + add(item.first, remove_white_border(item.second.sprite)); + } +} +ImageRGB32 PokeballSpriteMatcher::remove_white_border(const ImageViewRGB32& image){ + using namespace Kernels::Waterfill; + + ImageRGB32 ret = image.copy(); + { + auto matrix = compress_rgb32_to_binary_range(ret, 0x00000000, 0x7f000000); + auto session = make_WaterfillSession(matrix); + auto iter = session->make_iterator(200); + WaterfillObject object; + if (!iter->find_next(object, true)){ + return ret; + } + filter_by_mask(object.packed_matrix(), ret, Color(0xffffffff), false); + } + { + auto matrix = compress_rgb32_to_binary_range(ret, 0x00808080, 0xffffffff); + auto session = make_WaterfillSession(matrix); + auto iter = session->make_iterator(200); + WaterfillObject object; + if (!iter->find_next(object, true)){ + return ret; + } + filter_by_mask(object.packed_matrix(), ret, Color(0x00000000), false); + } + return ret; +} +auto PokeballSpriteMatcher::get_crop_candidates(const ImageViewRGB32& image) const -> std::vector{ + ImageStats border = image_border_stats(image); + ImagePixelBox box = ImageMatch::enclosing_rectangle_with_pixel_filter( + image, + [&](Color pixel){ + double r = (double)pixel.red() - border.average.r; + double g = (double)pixel.green() - border.average.g; + double b = (double)pixel.blue() - border.average.b; + bool stop = r*r + g*g + b*b >= m_min_euclidean_distance_squared; + return stop; + } + ); + std::vector ret; + ret.emplace_back(extract_box_reference(image, box)); + return ret; +} + + + + + + const double BallReader::MAX_ALPHA = 0.40; const double BallReader::ALPHA_SPREAD = 0.02; -const PokemonBDSP::PokeballSpriteMatcher& BALL_SPRITE_MATCHER(){ - static PokemonBDSP::PokeballSpriteMatcher matcher; +const PokeballSpriteMatcher& BALL_SPRITE_MATCHER(){ + static PokeballSpriteMatcher matcher; return matcher; } diff --git a/SerialPrograms/Source/PokemonHome/Inference/PokemonHome_BallReader.h b/SerialPrograms/Source/PokemonHome/Inference/PokemonHome_BallReader.h index a844692685..632a811300 100644 --- a/SerialPrograms/Source/PokemonHome/Inference/PokemonHome_BallReader.h +++ b/SerialPrograms/Source/PokemonHome/Inference/PokemonHome_BallReader.h @@ -8,6 +8,7 @@ #define PokemonAutomation_PokemonHome_BallReader_H #include +#include "CommonFramework/ImageTypes/ImageRGB32.h" #include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" #include "CommonFramework/Tools/VideoStream.h" #include "CommonTools/ImageMatch/CroppedImageDictionaryMatcher.h" @@ -17,6 +18,22 @@ namespace NintendoSwitch{ namespace PokemonHome{ + +class PokeballSpriteMatcher : public ImageMatch::CroppedImageDictionaryMatcher{ +public: + PokeballSpriteMatcher(double min_euclidean_distance = 100); + +private: + static ImageRGB32 remove_white_border(const ImageViewRGB32& image); + virtual std::vector get_crop_candidates(const ImageViewRGB32& image) const override; + +private: + double m_min_euclidean_distance_squared; +}; + + + + class BallReader{ static const double MAX_ALPHA; static const double ALPHA_SPREAD; diff --git a/SerialPrograms/Source/PokemonHome/Resources/PokemonHome_PokeballSprites.cpp b/SerialPrograms/Source/PokemonHome/Resources/PokemonHome_PokeballSprites.cpp new file mode 100644 index 0000000000..7fe7987655 --- /dev/null +++ b/SerialPrograms/Source/PokemonHome/Resources/PokemonHome_PokeballSprites.cpp @@ -0,0 +1,23 @@ +/* Pokemon Home Pokeball Sprites + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonHome_PokeballSprites.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonHome{ + + +const SpriteDatabase& ALL_POKEBALL_SPRITES(){ + static const SpriteDatabase database("PokemonHome/PokeballSprites.png", "PokemonHome/PokeballSprites.json"); + return database; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonHome/Resources/PokemonHome_PokeballSprites.h b/SerialPrograms/Source/PokemonHome/Resources/PokemonHome_PokeballSprites.h new file mode 100644 index 0000000000..175429e27e --- /dev/null +++ b/SerialPrograms/Source/PokemonHome/Resources/PokemonHome_PokeballSprites.h @@ -0,0 +1,24 @@ +/* Pokemon s Pokeball Sprites + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonHome_PokeballSprites_H +#define PokemonAutomation_PokemonHome_PokeballSprites_H + +#include "CommonTools/Resources/SpriteDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonHome{ + + +const SpriteDatabase& ALL_POKEBALL_SPRITES(); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_SelectedRegionDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_SelectedRegionDetector.cpp index bbccc429c4..732316214e 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_SelectedRegionDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_SelectedRegionDetector.cpp @@ -12,6 +12,10 @@ #include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" #include "PokemonLA_SelectedRegionDetector.h" +//#include +//using std::cout; +//using std::endl; + namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonLA{ @@ -42,6 +46,7 @@ class MapLocationDetector : public VisualInferenceCallback{ reload_reference(frame.frame); } + MapRegion current_region = MapRegion::NONE; for (RegionState& region : m_regions){ ImageViewRGB32 current = extract_box_reference(frame, region.box); @@ -52,11 +57,19 @@ class MapLocationDetector : public VisualInferenceCallback{ double rmsd = ImageMatch::pixel_RMSD(region.start, current); if (rmsd > 20){ - m_current_region = region.region; - return true; + if (current_region == MapRegion::NONE){ + current_region = region.region; + }else{ + // Multiple large diffs. Frame isn't stable. +// cout << "Multiple diffs: " << rmsd << endl; + reload_reference(frame.frame); + return false; + } } } - return false; + + m_current_region = current_region; + return current_region != MapRegion::NONE; } void reload_reference(std::shared_ptr screen){ diff --git a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_MMORoutines.cpp b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_MMORoutines.cpp index dff72c48e5..c4b78f7e6d 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_MMORoutines.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_MMORoutines.cpp @@ -1,305 +1,305 @@ -/* Pokemon LA MMO Routines - * - * Functions to run MMO related tasks - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonLA/Inference/Map/PokemonLA_PokemonMapSpriteReader.h" -#include "PokemonLA/Inference/Map/PokemonLA_MapDetector.h" -#include "PokemonLA/Inference/Map/PokemonLA_MapMissionTabReader.h" -#include "PokemonLA/Inference/Map/PokemonLA_MapZoomLevelReader.h" -#include "PokemonLA/Inference/Map/PokemonLA_MMOSpriteStarSymbolDetector.h" -#include "PokemonLA/Inference/Objects/PokemonLA_MMOQuestionMarkDetector.h" -#include "PokemonLA/Inference/PokemonLA_DialogDetector.h" -#include "PokemonLA/PokemonLA_Locations.h" -#include "PokemonLA/PokemonLA_TravelLocations.h" -#include "PokemonLA/Programs/PokemonLA_RegionNavigation.h" -#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -std::vector load_mmo_names(){ - return { - "fieldlands-mmo", - "mirelands-mmo", - "coastlands-mmo", - "highlands-mmo", - "icelands-mmo" - }; -} - -const std::vector& MMO_NAMES(){ - const static std::vector mmo_names = load_mmo_names(); - return mmo_names; -} - - -std::set enter_region_and_read_MMO( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - const std::string& mmo_name, - const std::set& desired_MMOs, - const std::set& desired_star_MMOs, - bool debug_mode, - int& num_mmo_pokemon_found, - int& num_star_mmo_found -){ - MapRegion region = MapRegion::NONE; - TravelLocation location = TravelLocations::instance().Fieldlands_Fieldlands; - Camp camp = Camp::FIELDLANDS_FIELDLANDS; - // When you open the map in a region, the map cursor is initialized at your current location - // on map. But when you land in a region, the initial location is a camp, the map cursor - // will show a text box "xxx Camp - Take a rest or do some crafting". This may occlude some - // MMO question marks. So we have to move the map cursor away after we land in the region. - uint8_t map_cursor_move_x = 0; - uint8_t map_cursor_move_y = 0; - const int map_cursor_move_duration = 50; - - for(size_t i = 0; i < 5; i++){ - if (mmo_name == MMO_NAMES()[i]){ - switch (i){ - case 0: - region = MapRegion::FIELDLANDS; - location = TravelLocations::instance().Fieldlands_Fieldlands; - camp = Camp::FIELDLANDS_FIELDLANDS; - map_cursor_move_x = 128; - map_cursor_move_y = 0; - break; - case 1: - region = MapRegion::MIRELANDS; - location = TravelLocations::instance().Mirelands_Mirelands; - camp = Camp::MIRELANDS_MIRELANDS; - map_cursor_move_x = 0; - map_cursor_move_y = 128; - break; - case 2: - region = MapRegion::COASTLANDS; - location = TravelLocations::instance().Coastlands_Beachside; - camp = Camp::COASTLANDS_BEACHSIDE; - map_cursor_move_x = 0; - map_cursor_move_y = 128; - break; - case 3: - region = MapRegion::HIGHLANDS; - location = TravelLocations::instance().Highlands_Highlands; - camp = Camp::HIGHLANDS_HIGHLANDS; - map_cursor_move_x = 128; - map_cursor_move_y = 255; - break; - case 4: - region = MapRegion::ICELANDS; - location = TravelLocations::instance().Icelands_Snowfields; - camp = Camp::ICELANDS_SNOWFIELDS; - map_cursor_move_x = 128; - map_cursor_move_y = 255; - break; - } - } - } - if (region == MapRegion::NONE){ - throw InternalProgramError(&env.console.logger(), PA_CURRENT_FUNCTION, "No MMO region name found."); - } - - env.log("Go to " + std::string(MAP_REGION_NAMES[int(region)]) + " to check MMO."); - goto_camp_from_jubilife(env, env.console, context, location); - - // Open map - pbf_press_button(context, BUTTON_MINUS, 50, 100); - context.wait_for_all_requests(); - - // Take a photo of the map before - VideoSnapshot question_mark_image = env.console.video().snapshot(); - - // Fix zoom level: - const int zoom_level = read_map_zoom_level(question_mark_image); - if (zoom_level < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Canot read map zoom level.", - env.console - ); - } - if (zoom_level == 0){ - pbf_press_button(context, BUTTON_ZR, 50, 50); - context.wait_for_all_requests(); - question_mark_image = env.console.video().snapshot(); - }else if (zoom_level == 2){ - pbf_press_button(context, BUTTON_ZL, 50, 50); - context.wait_for_all_requests(); - question_mark_image = env.console.video().snapshot(); - } - - // Move cursor away so that it does not show a text box that occludes MMO sprites. - pbf_move_left_joystick(context, map_cursor_move_x, map_cursor_move_y, map_cursor_move_duration, 30); - context.wait_for_all_requests(); - - // Fix Missions & Requests tab: - if (is_map_mission_tab_raised(question_mark_image)){ - pbf_press_button(context, BUTTON_R, 50, 100); - context.wait_for_all_requests(); - question_mark_image = env.console.video().snapshot(); - } - - // Now detect question marks: - MMOQuestionMarkDetector question_mark_detector(env.logger()); - - const auto quest_results = question_mark_detector.detect_MMOs_on_region_map(question_mark_image); - env.log("Detected MMO question marks:"); - for(const auto& box : quest_results){ - std::ostringstream os; - os << "- " << box.center_x() << ", " << box.center_y() << " " << box.width() << " x " << box.height(); - env.log(os.str()); - } - - // Clean the detected boxes, make them square. - std::vector new_boxes; - for (size_t i = 0; i < quest_results.size(); i++){ - const auto& box = quest_results[i]; - - pxint_t radius = (pxint_t)((box.width() + box.height()) / 4 + 0.5); - pxint_t center_x = (pxint_t)box.center_x(); - pxint_t center_y = (pxint_t)box.center_y(); - auto new_box = ImagePixelBox(center_x - radius, center_y - radius, center_x + radius, center_y + radius); - new_boxes.push_back(new_box); - } - - // Leave map view, back to overworld - pbf_press_button(context, BUTTON_B, 20, 50); - - // Now go to Mai to see the reviewed map - goto_Mai_from_camp(env.logger(), context, camp); - - pbf_mash_button(context, BUTTON_A, 350); - context.wait_for_all_requests(); - - // Wait for the last dialog box before the MMO pokemon sprites are revealed. - { - EventDialogDetector event_dialog_detector(env.logger(), env.console.overlay(), true); - int ret = wait_until(env.console, context, std::chrono::seconds(10), {{event_dialog_detector}}); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Dialog box not detected when waiting for MMO map.", - env.console - ); - } - } - pbf_press_button(context, BUTTON_B, 50, 50); - - while (true){ - EventDialogDetector event_dialog_detector(env.logger(), env.console.overlay(), true); - MapDetector map_detector; - context.wait_for_all_requests(); - int ret = wait_until( - env.console, context, std::chrono::seconds(10), - {event_dialog_detector, map_detector} - ); - switch (ret){ - case 0: - env.console.log("Detected dialog."); - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - case 1: - env.console.log("Found revealed map thanks to Munchlax!"); - break; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Map not detected after talking to Mai.", - env.console - ); - } - break; - } - -#if 0 - MapDetector map_detector; - ret = wait_until(env.console, context, std::chrono::seconds(5), {{map_detector}}); - if (ret < 0){ - OperationFailedException::fire( - env.console, ErrorReport::SEND_ERROR_REPORT, - "Map not detected after talking to Mai.", - true - ); - } - env.console.log("Found revealed map thanks to Munchlax!"); -#endif - - VideoOverlaySet mmo_sprites_overlay(env.console); - for (size_t i = 0; i < new_boxes.size(); i++){ - mmo_sprites_overlay.add(COLOR_BLUE, pixelbox_to_floatbox(question_mark_image, new_boxes[i])); - } - - // Move cursor away so that it does not show a text box that occludes MMO sprites. - pbf_move_left_joystick(context, map_cursor_move_x, map_cursor_move_y, map_cursor_move_duration, 30); - context.wait_for_all_requests(); - - std::set found; - - // Check MMO results: - std::vector sprites; - VideoSnapshot sprites_screen = env.console.video().snapshot(); - for (size_t i = 0; i < new_boxes.size(); i++){ - auto result = match_sprite_on_map(env.logger(), sprites_screen, new_boxes[i], region, debug_mode); - env.console.log("Found MMO sprite " + result.slug); - num_mmo_pokemon_found++; - - sprites.push_back(result.slug); - if (desired_MMOs.find(result.slug) != desired_MMOs.end()){ - found.insert(result.slug); - } - } - - // Check star MMO results: - std::vector star_boxes; - for (size_t i = 0; i < new_boxes.size(); i++){ - const auto& sprite_box = new_boxes[i]; - pxint_t radius = (pxint_t)sprite_box.width() / 2; - pxint_t center_x = (pxint_t)sprite_box.center_x(); - pxint_t center_y = (pxint_t)sprite_box.center_y(); - ImagePixelBox star_box( - center_x + radius/10, - center_y - radius*16/10, - center_x + radius * 5/4, - center_y - ); - star_boxes.push_back(std::move(star_box)); - } - - MMOSpriteStarSymbolDetector star_detector(sprites_screen, star_boxes); - - env.log("Detect star symbols..."); - wait_until(env.console, context, std::chrono::seconds(5), {{star_detector}}); - for (size_t i = 0; i < new_boxes.size(); i++){ - std::ostringstream os; - os << "- " << sprites[i] << " box [" << star_boxes[i].min_x << ", " << star_boxes[i].min_y - << star_boxes[i].max_x << ", " << star_boxes[i].max_y << "]" - << " motion: " << star_detector.animation_value(i) - << " color: " << star_detector.symbol_color(i); - if (star_detector.is_star(i)){ - num_star_mmo_found++; - os << ", has star"; - if (desired_star_MMOs.find(sprites[i]) != desired_star_MMOs.end()){ - found.insert(sprites[i]); - } - } - env.log(os.str()); - } - return found; -} - - - -} -} -} +/* Pokemon LA MMO Routines + * + * Functions to run MMO related tasks + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonLA/Inference/Map/PokemonLA_PokemonMapSpriteReader.h" +#include "PokemonLA/Inference/Map/PokemonLA_MapDetector.h" +#include "PokemonLA/Inference/Map/PokemonLA_MapMissionTabReader.h" +#include "PokemonLA/Inference/Map/PokemonLA_MapZoomLevelReader.h" +#include "PokemonLA/Inference/Map/PokemonLA_MMOSpriteStarSymbolDetector.h" +#include "PokemonLA/Inference/Objects/PokemonLA_MMOQuestionMarkDetector.h" +#include "PokemonLA/Inference/PokemonLA_DialogDetector.h" +#include "PokemonLA/PokemonLA_Locations.h" +#include "PokemonLA/PokemonLA_TravelLocations.h" +#include "PokemonLA/Programs/PokemonLA_RegionNavigation.h" +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +std::vector load_mmo_names(){ + return { + "fieldlands-mmo", + "mirelands-mmo", + "coastlands-mmo", + "highlands-mmo", + "icelands-mmo" + }; +} + +const std::vector& MMO_NAMES(){ + const static std::vector mmo_names = load_mmo_names(); + return mmo_names; +} + + +std::set enter_region_and_read_MMO( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const std::string& mmo_name, + const std::set& desired_MMOs, + const std::set& desired_star_MMOs, + bool debug_mode, + int& num_mmo_pokemon_found, + int& num_star_mmo_found +){ + MapRegion region = MapRegion::NONE; + TravelLocation location = TravelLocations::instance().Fieldlands_Fieldlands; + Camp camp = Camp::FIELDLANDS_FIELDLANDS; + // When you open the map in a region, the map cursor is initialized at your current location + // on map. But when you land in a region, the initial location is a camp, the map cursor + // will show a text box "xxx Camp - Take a rest or do some crafting". This may occlude some + // MMO question marks. So we have to move the map cursor away after we land in the region. + uint8_t map_cursor_move_x = 0; + uint8_t map_cursor_move_y = 0; + const int map_cursor_move_duration = 50; + + for(size_t i = 0; i < 5; i++){ + if (mmo_name == MMO_NAMES()[i]){ + switch (i){ + case 0: + region = MapRegion::FIELDLANDS; + location = TravelLocations::instance().Fieldlands_Fieldlands; + camp = Camp::FIELDLANDS_FIELDLANDS; + map_cursor_move_x = 128; + map_cursor_move_y = 0; + break; + case 1: + region = MapRegion::MIRELANDS; + location = TravelLocations::instance().Mirelands_Mirelands; + camp = Camp::MIRELANDS_MIRELANDS; + map_cursor_move_x = 0; + map_cursor_move_y = 128; + break; + case 2: + region = MapRegion::COASTLANDS; + location = TravelLocations::instance().Coastlands_Beachside; + camp = Camp::COASTLANDS_BEACHSIDE; + map_cursor_move_x = 0; + map_cursor_move_y = 128; + break; + case 3: + region = MapRegion::HIGHLANDS; + location = TravelLocations::instance().Highlands_Highlands; + camp = Camp::HIGHLANDS_HIGHLANDS; + map_cursor_move_x = 128; + map_cursor_move_y = 255; + break; + case 4: + region = MapRegion::ICELANDS; + location = TravelLocations::instance().Icelands_Snowfields; + camp = Camp::ICELANDS_SNOWFIELDS; + map_cursor_move_x = 128; + map_cursor_move_y = 255; + break; + } + } + } + if (region == MapRegion::NONE){ + throw InternalProgramError(&env.console.logger(), PA_CURRENT_FUNCTION, "No MMO region name found."); + } + + env.log("Go to " + std::string(MAP_REGION_NAMES[int(region)]) + " to check MMO."); + goto_camp_from_jubilife(env, env.console, context, location); + + // Open map + pbf_press_button(context, BUTTON_MINUS, 50, 100); + context.wait_for_all_requests(); + + // Take a photo of the map before + VideoSnapshot question_mark_image = env.console.video().snapshot(); + + // Fix zoom level: + const int zoom_level = read_map_zoom_level(question_mark_image); + if (zoom_level < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Canot read map zoom level.", + env.console + ); + } + if (zoom_level == 0){ + pbf_press_button(context, BUTTON_ZR, 50, 50); + context.wait_for_all_requests(); + question_mark_image = env.console.video().snapshot(); + }else if (zoom_level == 2){ + pbf_press_button(context, BUTTON_ZL, 50, 50); + context.wait_for_all_requests(); + question_mark_image = env.console.video().snapshot(); + } + + // Move cursor away so that it does not show a text box that occludes MMO sprites. + pbf_move_left_joystick(context, map_cursor_move_x, map_cursor_move_y, map_cursor_move_duration, 30); + context.wait_for_all_requests(); + + // Fix Missions & Requests tab: + if (is_map_mission_tab_raised(question_mark_image)){ + pbf_press_button(context, BUTTON_R, 50, 100); + context.wait_for_all_requests(); + question_mark_image = env.console.video().snapshot(); + } + + // Now detect question marks: + MMOQuestionMarkDetector question_mark_detector(env.logger()); + + const auto quest_results = question_mark_detector.detect_MMOs_on_region_map(question_mark_image); + env.log("Detected MMO question marks:"); + for(const auto& box : quest_results){ + std::ostringstream os; + os << "- " << box.center_x() << ", " << box.center_y() << " " << box.width() << " x " << box.height(); + env.log(os.str()); + } + + // Clean the detected boxes, make them square. + std::vector new_boxes; + for (size_t i = 0; i < quest_results.size(); i++){ + const auto& box = quest_results[i]; + + pxint_t radius = (pxint_t)((box.width() + box.height()) / 4 + 0.5); + pxint_t center_x = (pxint_t)box.center_x(); + pxint_t center_y = (pxint_t)box.center_y(); + auto new_box = ImagePixelBox(center_x - radius, center_y - radius, center_x + radius, center_y + radius); + new_boxes.push_back(new_box); + } + + // Leave map view, back to overworld + pbf_press_button(context, BUTTON_B, 20, 50); + + // Now go to Mai to see the reviewed map + goto_Mai_from_camp(env.logger(), context, camp); + + pbf_mash_button(context, BUTTON_A, 350); + context.wait_for_all_requests(); + + // Wait for the last dialog box before the MMO pokemon sprites are revealed. + { + EventDialogDetector event_dialog_detector(env.logger(), env.console.overlay(), true); + int ret = wait_until(env.console, context, std::chrono::seconds(10), {{event_dialog_detector}}); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Dialog box not detected when waiting for MMO map.", + env.console + ); + } + } + pbf_press_button(context, BUTTON_B, 50, 50); + + while (true){ + EventDialogDetector event_dialog_detector(env.logger(), env.console.overlay(), true); + MapDetector map_detector; + context.wait_for_all_requests(); + int ret = wait_until( + env.console, context, std::chrono::seconds(10), + {event_dialog_detector, map_detector} + ); + switch (ret){ + case 0: + env.console.log("Detected dialog."); + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + case 1: + env.console.log("Found revealed map thanks to Munchlax!"); + break; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Map not detected after talking to Mai.", + env.console + ); + } + break; + } + +#if 0 + MapDetector map_detector; + ret = wait_until(env.console, context, std::chrono::seconds(5), {{map_detector}}); + if (ret < 0){ + OperationFailedException::fire( + env.console, ErrorReport::SEND_ERROR_REPORT, + "Map not detected after talking to Mai.", + true + ); + } + env.console.log("Found revealed map thanks to Munchlax!"); +#endif + + VideoOverlaySet mmo_sprites_overlay(env.console); + for (size_t i = 0; i < new_boxes.size(); i++){ + mmo_sprites_overlay.add(COLOR_BLUE, pixelbox_to_floatbox(question_mark_image, new_boxes[i])); + } + + // Move cursor away so that it does not show a text box that occludes MMO sprites. + pbf_move_left_joystick(context, map_cursor_move_x, map_cursor_move_y, map_cursor_move_duration, 30); + context.wait_for_all_requests(); + + std::set found; + + // Check MMO results: + std::vector sprites; + VideoSnapshot sprites_screen = env.console.video().snapshot(); + for (size_t i = 0; i < new_boxes.size(); i++){ + auto result = match_sprite_on_map(env.logger(), sprites_screen, new_boxes[i], region, debug_mode); + env.console.log("Found MMO sprite " + result.slug); + num_mmo_pokemon_found++; + + sprites.push_back(result.slug); + if (desired_MMOs.find(result.slug) != desired_MMOs.end()){ + found.insert(result.slug); + } + } + + // Check star MMO results: + std::vector star_boxes; + for (size_t i = 0; i < new_boxes.size(); i++){ + const auto& sprite_box = new_boxes[i]; + pxint_t radius = (pxint_t)sprite_box.width() / 2; + pxint_t center_x = (pxint_t)sprite_box.center_x(); + pxint_t center_y = (pxint_t)sprite_box.center_y(); + ImagePixelBox star_box( + center_x + radius/10, + center_y - radius*16/10, + center_x + radius * 5/4, + center_y + ); + star_boxes.push_back(std::move(star_box)); + } + + MMOSpriteStarSymbolDetector star_detector(sprites_screen, star_boxes); + + env.log("Detect star symbols..."); + wait_until(env.console, context, std::chrono::seconds(5), {{star_detector}}); + for (size_t i = 0; i < new_boxes.size(); i++){ + std::ostringstream os; + os << "- " << sprites[i] << " box [" << star_boxes[i].min_x << ", " << star_boxes[i].min_y + << star_boxes[i].max_x << ", " << star_boxes[i].max_y << "]" + << " motion: " << star_detector.animation_value(i) + << " color: " << star_detector.symbol_color(i); + if (star_detector.is_star(i)){ + num_star_mmo_found++; + os << ", has star"; + if (desired_star_MMOs.find(sprites[i]) != desired_star_MMOs.end()){ + found.insert(sprites[i]); + } + } + env.log(os.str()); + } + return found; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_MMORoutines.h b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_MMORoutines.h index 29f6666a48..f7367d7c17 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_MMORoutines.h +++ b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_MMORoutines.h @@ -1,52 +1,52 @@ -/* Pokemon LA MMO Routines - * - * Functions to run MMO related tasks - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include -#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -class SingleSwitchProgramEnvironment; - -namespace PokemonLA{ - -// The name of each MMO event happening at each region. Their slugs are: -// - "fieldlands-mmo" -// - "mirelands-mmo" -// - "coastlands-mmo" -// - "highlands-mmo" -// - "icelands-mmo" -const std::vector& MMO_NAMES(); - - -// After we find an MMO on map specified by `mmo_name`, -// start from Jubilife Village gate, with camera facing towards the village, run towards the gate -// and travel to the region with that MMO. Go to Mai to show all MMO pokemon on map and read their -// sprites and star symbols. -// The function returns when the map opened by Mai is shown with all pokemon revealed. -// Return true if an MMO pokemon matches slugs in `desired_MMOs`, or if an MMO pokemon with a star -// matches slugs in `desired_star_MMOs`. -// - mmo_name: MMO event slug, e.g. "fieldlands-mmo" -// - num_mmo_found: update this value by adding how many MMO pokemon found during this function. -// - num_star_mmo_found: update this value by adding how many MMO pokemon with star symbol found. -std::set enter_region_and_read_MMO( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - const std::string& mmo_name, - const std::set& desired_MMOs, - const std::set& desired_star_MMOs, - bool debug, - int& num_mmo_found, - int& num_star_mmo_found -); - - -} -} +/* Pokemon LA MMO Routines + * + * Functions to run MMO related tasks + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +class SingleSwitchProgramEnvironment; + +namespace PokemonLA{ + +// The name of each MMO event happening at each region. Their slugs are: +// - "fieldlands-mmo" +// - "mirelands-mmo" +// - "coastlands-mmo" +// - "highlands-mmo" +// - "icelands-mmo" +const std::vector& MMO_NAMES(); + + +// After we find an MMO on map specified by `mmo_name`, +// start from Jubilife Village gate, with camera facing towards the village, run towards the gate +// and travel to the region with that MMO. Go to Mai to show all MMO pokemon on map and read their +// sprites and star symbols. +// The function returns when the map opened by Mai is shown with all pokemon revealed. +// Return true if an MMO pokemon matches slugs in `desired_MMOs`, or if an MMO pokemon with a star +// matches slugs in `desired_star_MMOs`. +// - mmo_name: MMO event slug, e.g. "fieldlands-mmo" +// - num_mmo_found: update this value by adding how many MMO pokemon found during this function. +// - num_star_mmo_found: update this value by adding how many MMO pokemon with star symbol found. +std::set enter_region_and_read_MMO( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const std::string& mmo_name, + const std::set& desired_MMOs, + const std::set& desired_star_MMOs, + bool debug, + int& num_mmo_found, + int& num_star_mmo_found +); + + +} +} } \ No newline at end of file diff --git a/SerialPrograms/Source/PokemonLGPE/Commands/PokemonLGPE_DateSpam.cpp b/SerialPrograms/Source/PokemonLGPE/Commands/PokemonLGPE_DateSpam.cpp index d42da73c9f..559db5f332 100644 --- a/SerialPrograms/Source/PokemonLGPE/Commands/PokemonLGPE_DateSpam.cpp +++ b/SerialPrograms/Source/PokemonLGPE/Commands/PokemonLGPE_DateSpam.cpp @@ -1,71 +1,71 @@ -/* Auto Host Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "ClientSource/Libraries/MessageConverter.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "PokemonLGPE_DateSpam.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -void roll_date_forward_1(JoyconContext& context){ - Milliseconds tv = context->timing_variation(); - Milliseconds unit = 24ms + tv; - - pbf_press_button(context, BUTTON_A, 2*unit, unit); - pbf_move_joystick(context, 128, 0, 2*unit, unit); - pbf_press_button(context, BUTTON_A, 2*unit, unit); - - pbf_move_joystick(context, 255, 128, 2*unit, unit); - pbf_move_joystick(context, 128, 0, 2*unit, unit); - pbf_move_joystick(context, 255, 128, 2*unit, unit); - pbf_press_button(context, BUTTON_A, 2*unit, unit); - pbf_move_joystick(context, 255, 128, 2*unit, unit); - pbf_move_joystick(context, 255, 128, 2*unit, unit); - pbf_press_button(context, BUTTON_A, 2*unit, unit); -} - -void roll_date_backward_N(JoyconContext& context, uint8_t skips){ - if (skips == 0){ - return; - } - - Milliseconds tv = context->timing_variation(); - Milliseconds unit = 24ms + tv; - - pbf_press_button(context, BUTTON_A, 2*unit, unit); - - for (uint8_t c = 0; c < skips - 1; c++){ - pbf_move_joystick(context, 128, 255, 2*unit, unit); - } - - pbf_press_button(context, BUTTON_A, 2*unit, unit); - pbf_move_joystick(context, 255, 128, 2*unit, unit); - - for (uint8_t c = 0; c < skips - 1; c++){ - pbf_move_joystick(context, 128, 255, 2*unit, unit); - } - - pbf_press_button(context, BUTTON_A, 2*unit, unit); - pbf_move_joystick(context, 255, 128, 2*unit, unit); - pbf_move_joystick(context, 255, 128, 2*unit, unit); - pbf_press_button(context, BUTTON_A, 2*unit, unit); - pbf_press_button(context, BUTTON_A, 2*unit, unit); -} - - - - - -} - -} -} - +/* Auto Host Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "ClientSource/Libraries/MessageConverter.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "PokemonLGPE_DateSpam.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +void roll_date_forward_1(JoyconContext& context){ + Milliseconds tv = context->timing_variation(); + Milliseconds unit = 24ms + tv; + + pbf_press_button(context, BUTTON_A, 2*unit, unit); + pbf_move_joystick(context, 128, 0, 2*unit, unit); + pbf_press_button(context, BUTTON_A, 2*unit, unit); + + pbf_move_joystick(context, 255, 128, 2*unit, unit); + pbf_move_joystick(context, 128, 0, 2*unit, unit); + pbf_move_joystick(context, 255, 128, 2*unit, unit); + pbf_press_button(context, BUTTON_A, 2*unit, unit); + pbf_move_joystick(context, 255, 128, 2*unit, unit); + pbf_move_joystick(context, 255, 128, 2*unit, unit); + pbf_press_button(context, BUTTON_A, 2*unit, unit); +} + +void roll_date_backward_N(JoyconContext& context, uint8_t skips){ + if (skips == 0){ + return; + } + + Milliseconds tv = context->timing_variation(); + Milliseconds unit = 24ms + tv; + + pbf_press_button(context, BUTTON_A, 2*unit, unit); + + for (uint8_t c = 0; c < skips - 1; c++){ + pbf_move_joystick(context, 128, 255, 2*unit, unit); + } + + pbf_press_button(context, BUTTON_A, 2*unit, unit); + pbf_move_joystick(context, 255, 128, 2*unit, unit); + + for (uint8_t c = 0; c < skips - 1; c++){ + pbf_move_joystick(context, 128, 255, 2*unit, unit); + } + + pbf_press_button(context, BUTTON_A, 2*unit, unit); + pbf_move_joystick(context, 255, 128, 2*unit, unit); + pbf_move_joystick(context, 255, 128, 2*unit, unit); + pbf_press_button(context, BUTTON_A, 2*unit, unit); + pbf_press_button(context, BUTTON_A, 2*unit, unit); +} + + + + + +} + +} +} + diff --git a/SerialPrograms/Source/PokemonLGPE/Commands/PokemonLGPE_DateSpam.h b/SerialPrograms/Source/PokemonLGPE/Commands/PokemonLGPE_DateSpam.h index f692cdf07f..d9534ef6bc 100644 --- a/SerialPrograms/Source/PokemonLGPE/Commands/PokemonLGPE_DateSpam.h +++ b/SerialPrograms/Source/PokemonLGPE/Commands/PokemonLGPE_DateSpam.h @@ -1,24 +1,24 @@ -/* Date Spamming Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLGPE_Commands_DateSpam_H -#define PokemonAutomation_PokemonLGPE_Commands_DateSpam_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -void roll_date_forward_1 (JoyconContext& context); -void roll_date_backward_N (JoyconContext& context, uint8_t skips); - -} - -} -} -#endif +/* Date Spamming Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLGPE_Commands_DateSpam_H +#define PokemonAutomation_PokemonLGPE_Commands_DateSpam_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +void roll_date_forward_1 (JoyconContext& context); +void roll_date_backward_N (JoyconContext& context, uint8_t skips); + +} + +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLGPE/Inference/Battles/PokemonLGPE_BattleArrowDetector.cpp b/SerialPrograms/Source/PokemonLGPE/Inference/Battles/PokemonLGPE_BattleArrowDetector.cpp index 62beae17e4..d890c4ac94 100644 --- a/SerialPrograms/Source/PokemonLGPE/Inference/Battles/PokemonLGPE_BattleArrowDetector.cpp +++ b/SerialPrograms/Source/PokemonLGPE/Inference/Battles/PokemonLGPE_BattleArrowDetector.cpp @@ -1,69 +1,69 @@ -/* Battle Arrow Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/ImageMatch/ExactImageMatcher.h" -#include "PokemonLGPE_BattleArrowDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -const ImageMatch::ExactImageMatcher& BATTLE_ARROW(){ - static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonLGPE/BattleArrow.png"); - return matcher; -} - -BattleArrowDetector::BattleArrowDetector(Color color, const ImageFloatBox& box) - : m_color(color) - , m_box(box) -{} -void BattleArrowDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} -bool BattleArrowDetector::detect(const ImageViewRGB32& screen){ - using namespace Kernels::Waterfill; - - ImageViewRGB32 region = extract_box_reference(screen, m_box); - - const ImageMatch::ExactImageMatcher& matcher = BATTLE_ARROW(); - - auto matrix = compress_rgb32_to_binary_range(region, 0xffc0c0c0, 0xffffffff); - auto session = make_WaterfillSession(matrix); - auto iter = session->make_iterator(100); - WaterfillObject object; - - //static int c = 0; - while (iter->find_next(object, false)){ - double aspect_ratio = object.aspect_ratio(); - if (aspect_ratio < 1.0 || aspect_ratio > 1.3){ - continue; - } - ImageViewRGB32 cropped = extract_box_reference(region, object); - //cropped.save("test-object-" + std::to_string(c++) + ".png"); - double rmsd = matcher.rmsd(cropped); - //cout << rmsd << endl; - if (rmsd < 116){ - return true; - } - } - - return false; -} - - - -} -} -} +/* Battle Arrow Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/ImageMatch/ExactImageMatcher.h" +#include "PokemonLGPE_BattleArrowDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +const ImageMatch::ExactImageMatcher& BATTLE_ARROW(){ + static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonLGPE/BattleArrow.png"); + return matcher; +} + +BattleArrowDetector::BattleArrowDetector(Color color, const ImageFloatBox& box) + : m_color(color) + , m_box(box) +{} +void BattleArrowDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} +bool BattleArrowDetector::detect(const ImageViewRGB32& screen){ + using namespace Kernels::Waterfill; + + ImageViewRGB32 region = extract_box_reference(screen, m_box); + + const ImageMatch::ExactImageMatcher& matcher = BATTLE_ARROW(); + + auto matrix = compress_rgb32_to_binary_range(region, 0xffc0c0c0, 0xffffffff); + auto session = make_WaterfillSession(matrix); + auto iter = session->make_iterator(100); + WaterfillObject object; + + //static int c = 0; + while (iter->find_next(object, false)){ + double aspect_ratio = object.aspect_ratio(); + if (aspect_ratio < 1.0 || aspect_ratio > 1.3){ + continue; + } + ImageViewRGB32 cropped = extract_box_reference(region, object); + //cropped.save("test-object-" + std::to_string(c++) + ".png"); + double rmsd = matcher.rmsd(cropped); + //cout << rmsd << endl; + if (rmsd < 116){ + return true; + } + } + + return false; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLGPE/Inference/Battles/PokemonLGPE_BattleArrowDetector.h b/SerialPrograms/Source/PokemonLGPE/Inference/Battles/PokemonLGPE_BattleArrowDetector.h index f977aff304..c4debd4002 100644 --- a/SerialPrograms/Source/PokemonLGPE/Inference/Battles/PokemonLGPE_BattleArrowDetector.h +++ b/SerialPrograms/Source/PokemonLGPE/Inference/Battles/PokemonLGPE_BattleArrowDetector.h @@ -1,53 +1,53 @@ -/* Battle Arrow Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLGPE_BattleArrowDetector_H -#define PokemonAutomation_PokemonLGPE_BattleArrowDetector_H - -#include -#include -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/VisualDetector.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -class BattleArrowDetector : public StaticScreenDetector{ -public: - /* - |Fight|Pokemon|Bag|Run| for wild battle - |---|Fight|Pokemon|Bag| for trainer battle - (align right) - Don't know what changes for a double battle. - */ - //Arrow bounces back and forth. - BattleArrowDetector(Color color, const ImageFloatBox& box); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -protected: - Color m_color; - ImageFloatBox m_box; -}; -class BattleArrowWatcher : public DetectorToFinder{ -public: - BattleArrowWatcher(Color color = COLOR_RED, ImageFloatBox box = {0.546, 0.863, 0.045, 0.068}) - : DetectorToFinder("BattleArrowWatcher", std::chrono::milliseconds(100), color, box) - {} -}; - - - -} -} -} - -#endif +/* Battle Arrow Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLGPE_BattleArrowDetector_H +#define PokemonAutomation_PokemonLGPE_BattleArrowDetector_H + +#include +#include +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/VisualDetector.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +class BattleArrowDetector : public StaticScreenDetector{ +public: + /* + |Fight|Pokemon|Bag|Run| for wild battle + |---|Fight|Pokemon|Bag| for trainer battle + (align right) + Don't know what changes for a double battle. + */ + //Arrow bounces back and forth. + BattleArrowDetector(Color color, const ImageFloatBox& box); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +protected: + Color m_color; + ImageFloatBox m_box; +}; +class BattleArrowWatcher : public DetectorToFinder{ +public: + BattleArrowWatcher(Color color = COLOR_RED, ImageFloatBox box = {0.546, 0.863, 0.045, 0.068}) + : DetectorToFinder("BattleArrowWatcher", std::chrono::milliseconds(100), color, box) + {} +}; + + + +} +} +} + +#endif diff --git a/SerialPrograms/Source/PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.cpp b/SerialPrograms/Source/PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.cpp index 374a6c2bb4..92704d1e67 100644 --- a/SerialPrograms/Source/PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.cpp +++ b/SerialPrograms/Source/PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.cpp @@ -1,49 +1,49 @@ -/* Shiny Symbol Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/ImageFilter.h" -#include "PokemonLGPE_ShinySymbolDetector.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -ShinySymbolDetector::ShinySymbolDetector(Color color) - : m_box_star(0.666, 0.779, 0.028, 0.044) -{} -void ShinySymbolDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_box_star); -} -bool ShinySymbolDetector::read(Logger& logger, const ImageViewRGB32& frame){ - /* - Shiny (charizard): - Add infer box: (0.6660, 0.7790, 0.0280, 0.0440), RGB avg [159, 123, 125] avg sum 408 ratio [0.391, 0.301, 0.308] stddev [74.898, 54.696, 53.354] sum 182.948 crop size (54, 48) - - Not shiny (chansey): - Add infer box: (0.6660, 0.7790, 0.0280, 0.0440), RGB avg [82, 113, 100] avg sum 295 ratio [0.276, 0.384, 0.340] stddev [15.477, 2.178, 2.648] sum 20.303 crop size (54, 48) - - Only had the two to test with for now. - */ - - const auto stats = image_stats(extract_box_reference(frame, m_box_star)); - return stats.stddev.sum() > 100; -} - - -} -} -} - +/* Shiny Symbol Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/ImageFilter.h" +#include "PokemonLGPE_ShinySymbolDetector.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +ShinySymbolDetector::ShinySymbolDetector(Color color) + : m_box_star(0.666, 0.779, 0.028, 0.044) +{} +void ShinySymbolDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_box_star); +} +bool ShinySymbolDetector::read(Logger& logger, const ImageViewRGB32& frame){ + /* + Shiny (charizard): + Add infer box: (0.6660, 0.7790, 0.0280, 0.0440), RGB avg [159, 123, 125] avg sum 408 ratio [0.391, 0.301, 0.308] stddev [74.898, 54.696, 53.354] sum 182.948 crop size (54, 48) + + Not shiny (chansey): + Add infer box: (0.6660, 0.7790, 0.0280, 0.0440), RGB avg [82, 113, 100] avg sum 295 ratio [0.276, 0.384, 0.340] stddev [15.477, 2.178, 2.648] sum 20.303 crop size (54, 48) + + Only had the two to test with for now. + */ + + const auto stats = image_stats(extract_box_reference(frame, m_box_star)); + return stats.stddev.sum() > 100; +} + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h b/SerialPrograms/Source/PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h index 73b565b7d6..2fa78427b3 100644 --- a/SerialPrograms/Source/PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h +++ b/SerialPrograms/Source/PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h @@ -1,35 +1,35 @@ -/* Shiny Symbol Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonRSE_ShinyNumberDetector_H -#define PokemonAutomation_PokemonRSE_ShinyNumberDetector_H - -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -//Check for the red shiny star on a Pokemon's summary from the Party/Box menu. -//This does not work for the summary that appears after a catch. -class ShinySymbolDetector{ -public: - ShinySymbolDetector(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const; - bool read(Logger& logger, const ImageViewRGB32& frame); - -private: - ImageFloatBox m_box_star; -}; - - - -} -} -} -#endif +/* Shiny Symbol Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonRSE_ShinyNumberDetector_H +#define PokemonAutomation_PokemonRSE_ShinyNumberDetector_H + +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +//Check for the red shiny star on a Pokemon's summary from the Party/Box menu. +//This does not work for the summary that appears after a catch. +class ShinySymbolDetector{ +public: + ShinySymbolDetector(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const; + bool read(Logger& logger, const ImageViewRGB32& frame); + +private: + ImageFloatBox m_box_star; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.cpp b/SerialPrograms/Source/PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.cpp index f1d9cdb9c7..4b24aef49d 100644 --- a/SerialPrograms/Source/PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.cpp +++ b/SerialPrograms/Source/PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.cpp @@ -1,47 +1,47 @@ -/* Shiny Sound Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Audio/AudioTemplateCache.h" -#include "CommonTools/Audio/SpectrogramMatcher.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" -#include "PokemonLGPE/PokemonLGPE_Settings.h" -#include "PokemonLGPE_ShinySoundDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - - -ShinySoundDetector::ShinySoundDetector(Logger& logger, DetectedCallback detected_callback) - // Use a yellow as the detection color because the shiny animation is yellow. - : AudioPerSpectrumDetectorBase( - logger, - "ShinySoundDetector", - "Shiny sound", - COLOR_YELLOW, - detected_callback - ) -{} - - -float ShinySoundDetector::get_score_threshold() const{ - return (float)GameSettings::instance().SHINY_SOUND_THRESHOLD; -} - -std::unique_ptr ShinySoundDetector::build_spectrogram_matcher(size_t sample_rate){ - return std::make_unique( - "Shiny Sound", - AudioTemplateCache::instance().get_throw("PokemonLGPE/ShinySound", sample_rate), - SpectrogramMatcher::Mode::SPIKE_CONV, sample_rate, - GameSettings::instance().SHINY_SOUND_LOW_FREQUENCY - ); -} - - - -} -} -} +/* Shiny Sound Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Audio/AudioTemplateCache.h" +#include "CommonTools/Audio/SpectrogramMatcher.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "PokemonLGPE/PokemonLGPE_Settings.h" +#include "PokemonLGPE_ShinySoundDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + + +ShinySoundDetector::ShinySoundDetector(Logger& logger, DetectedCallback detected_callback) + // Use a yellow as the detection color because the shiny animation is yellow. + : AudioPerSpectrumDetectorBase( + logger, + "ShinySoundDetector", + "Shiny sound", + COLOR_YELLOW, + detected_callback + ) +{} + + +float ShinySoundDetector::get_score_threshold() const{ + return (float)GameSettings::instance().SHINY_SOUND_THRESHOLD; +} + +std::unique_ptr ShinySoundDetector::build_spectrogram_matcher(size_t sample_rate){ + return std::make_unique( + "Shiny Sound", + AudioTemplateCache::instance().get_throw("PokemonLGPE/ShinySound", sample_rate), + SpectrogramMatcher::Mode::SPIKE_CONV, sample_rate, + GameSettings::instance().SHINY_SOUND_LOW_FREQUENCY + ); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.h b/SerialPrograms/Source/PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.h index cd76bcd059..46b3ef0d93 100644 --- a/SerialPrograms/Source/PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.h +++ b/SerialPrograms/Source/PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.h @@ -1,36 +1,36 @@ -/* Shiny Sound Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLGPE_ShinySoundDetector_H -#define PokemonAutomation_PokemonLGPE_ShinySoundDetector_H - -#include "CommonTools/Audio/AudioPerSpectrumDetectorBase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - - -class ShinySoundDetector : public AudioPerSpectrumDetectorBase{ -public: - // Warning: The callback will be called from the audio inference thread. - ShinySoundDetector(Logger& logger, DetectedCallback detected_callback); - - // Implement AudioPerSpectrumDetectorBase::get_score_threshold() - virtual float get_score_threshold() const override; - -protected: - // Implement AudioPerSpectrumDetectorBase::build_spectrogram_matcher() - virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) override; -}; - - - - -} -} -} -#endif +/* Shiny Sound Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLGPE_ShinySoundDetector_H +#define PokemonAutomation_PokemonLGPE_ShinySoundDetector_H + +#include "CommonTools/Audio/AudioPerSpectrumDetectorBase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + + +class ShinySoundDetector : public AudioPerSpectrumDetectorBase{ +public: + // Warning: The callback will be called from the audio inference thread. + ShinySoundDetector(Logger& logger, DetectedCallback detected_callback); + + // Implement AudioPerSpectrumDetectorBase::get_score_threshold() + virtual float get_score_threshold() const override; + +protected: + // Implement AudioPerSpectrumDetectorBase::build_spectrogram_matcher() + virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) override; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Panels.cpp b/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Panels.cpp index e0d229ac79..e51bbcf0d7 100644 --- a/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Panels.cpp +++ b/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Panels.cpp @@ -1,56 +1,56 @@ -/* Pokemon LGPE Panels - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/GlobalSettingsPanel.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLGPE_Panels.h" -#include "PokemonLGPE_Settings.h" - -#include "Programs/Farming/PokemonLGPE_DailyItemFarmer.h" -#include "Programs/ShinyHunting/PokemonLGPE_AlolanTrade.h" -#include "Programs/ShinyHunting/PokemonLGPE_FossilRevival.h" -#include "Programs/ShinyHunting/PokemonLGPE_GiftReset.h" -#include "Programs/ShinyHunting/PokemonLGPE_LegendaryReset.h" - -#include "Programs/TestPrograms/PokemonLGPE_SoundListener.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -PanelListFactory::PanelListFactory() - : PanelListDescriptor(Pokemon::STRING_POKEMON + " Let's Go Pikachu and Eevee") -{} - -std::vector PanelListFactory::make_panels() const{ - std::vector ret; - - ret.emplace_back("---- Settings ----"); - ret.emplace_back(make_settings()); - - ret.emplace_back("---- General ----"); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- Shiny Hunting ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - if (PreloadSettings::instance().DEVELOPER_MODE){ - ret.emplace_back("---- Developer Tools ----"); - ret.emplace_back(make_single_switch_program()); - } - - return ret; -} - - - - -} -} -} +/* Pokemon LGPE Panels + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLGPE_Panels.h" +#include "PokemonLGPE_Settings.h" + +#include "Programs/Farming/PokemonLGPE_DailyItemFarmer.h" +#include "Programs/ShinyHunting/PokemonLGPE_AlolanTrade.h" +#include "Programs/ShinyHunting/PokemonLGPE_FossilRevival.h" +#include "Programs/ShinyHunting/PokemonLGPE_GiftReset.h" +#include "Programs/ShinyHunting/PokemonLGPE_LegendaryReset.h" + +#include "Programs/TestPrograms/PokemonLGPE_SoundListener.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +PanelListFactory::PanelListFactory() + : PanelListDescriptor(Pokemon::STRING_POKEMON + " Let's Go Pikachu and Eevee") +{} + +std::vector PanelListFactory::make_panels() const{ + std::vector ret; + + ret.emplace_back("---- Settings ----"); + ret.emplace_back(make_settings()); + + ret.emplace_back("---- General ----"); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- Shiny Hunting ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + if (PreloadSettings::instance().DEVELOPER_MODE){ + ret.emplace_back("---- Developer Tools ----"); + ret.emplace_back(make_single_switch_program()); + } + + return ret; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Panels.h b/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Panels.h index 8d2eb1108f..4c5d0b925e 100644 --- a/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Panels.h +++ b/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Panels.h @@ -1,28 +1,28 @@ -/* Pokemon LGPE Panels - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLGPE_Panels_H -#define PokemonAutomation_PokemonLGPE_Panels_H - -#include "CommonFramework/Panels/PanelList.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -class PanelListFactory : public PanelListDescriptor{ -public: - PanelListFactory(); -private: - virtual std::vector make_panels() const override; -}; - - - -} -} -} -#endif +/* Pokemon LGPE Panels + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLGPE_Panels_H +#define PokemonAutomation_PokemonLGPE_Panels_H + +#include "CommonFramework/Panels/PanelList.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +class PanelListFactory : public PanelListDescriptor{ +public: + PanelListFactory(); +private: + virtual std::vector make_panels() const override; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Settings.cpp b/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Settings.cpp index db04e2536b..a977100c30 100644 --- a/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Settings.cpp +++ b/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Settings.cpp @@ -1,114 +1,114 @@ -/* Pokemon Let's Go Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLGPE_Settings.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - using namespace Pokemon; - - - -GameSettings& GameSettings::instance(){ - static GameSettings settings; - return settings; -} -GameSettings::GameSettings() - : BatchOption(LockMode::LOCK_WHILE_RUNNING) - , m_general("General Settings:") - , m_menu_navigation("Menu Navigation Timings:") - , GAME_TO_HOME_DELAY0( - "Game to Home Delay:
Delay from pressing home to entering the the Switch home menu.", - LockMode::LOCK_WHILE_RUNNING, - "1000 ms" - ) - , m_start_game_timings("Start Game Timings:") - , START_GAME_MASH0( - "1. Start Game Mash:
Mash A for this long to start the game.", - LockMode::LOCK_WHILE_RUNNING, - "2000 ms" - ) - , START_GAME_WAIT1( - "2. Start Game Wait:
Wait this long for the game to load.", - LockMode::LOCK_WHILE_RUNNING, - "20 s" - ) - , ENTER_GAME_MASH0( - "3. Enter Game Mash:
Mash A for this long to enter the game.", - LockMode::LOCK_WHILE_RUNNING, - "5 s" - ) - , ENTER_GAME_WAIT0( - "4. Enter Game Wait:
Wait this long for the opening animations to finish.", - LockMode::LOCK_WHILE_RUNNING, - "15 s" - ) - , m_shiny_audio_settings("Shiny Audio Settings:") - , SHINY_SOUND_THRESHOLD( - "Shiny Sound Threshold:
Maximum error coefficient to trigger a shiny detection.", - LockMode::LOCK_WHILE_RUNNING, - 0.95, 0, 1.0 - ) - , SHINY_SOUND_LOW_FREQUENCY( - "Shiny Sound Low Frequency (Hz):
High pass filter frequency for shiny sound.", - LockMode::LOCK_WHILE_RUNNING, - 1000, 0, 48000 - ) -{ - PA_ADD_STATIC(m_general); - - PA_ADD_STATIC(m_menu_navigation); - PA_ADD_OPTION(GAME_TO_HOME_DELAY0); - - PA_ADD_STATIC(m_start_game_timings); - PA_ADD_OPTION(START_GAME_MASH0); - PA_ADD_OPTION(START_GAME_WAIT1); - PA_ADD_OPTION(ENTER_GAME_MASH0); - PA_ADD_OPTION(ENTER_GAME_WAIT0); - - PA_ADD_STATIC(m_shiny_audio_settings); - PA_ADD_OPTION(SHINY_SOUND_THRESHOLD); - PA_ADD_OPTION(SHINY_SOUND_LOW_FREQUENCY); -} - - - - - -GameSettings_Descriptor::GameSettings_Descriptor() - : PanelDescriptor( - Color(), - "PokemonLGPE:GlobalSettings", - STRING_POKEMON + " LGPE", "Game Settings", - "ComputerControl/blob/master/Wiki/Programs/PokemonLGPE/PokemonSettings.md", - "Global " + STRING_POKEMON + " Let's Go Settings" - ) -{} - - - -GameSettingsPanel::GameSettingsPanel(const GameSettings_Descriptor& descriptor) - : SettingsPanelInstance(descriptor) - , settings(GameSettings::instance()) -{ - PA_ADD_OPTION(settings); -} - - - - - -} -} -} - - - - - - +/* Pokemon Let's Go Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLGPE_Settings.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + using namespace Pokemon; + + + +GameSettings& GameSettings::instance(){ + static GameSettings settings; + return settings; +} +GameSettings::GameSettings() + : BatchOption(LockMode::LOCK_WHILE_RUNNING) + , m_general("General Settings:") + , m_menu_navigation("Menu Navigation Timings:") + , GAME_TO_HOME_DELAY0( + "Game to Home Delay:
Delay from pressing home to entering the the Switch home menu.", + LockMode::LOCK_WHILE_RUNNING, + "1000 ms" + ) + , m_start_game_timings("Start Game Timings:") + , START_GAME_MASH0( + "1. Start Game Mash:
Mash A for this long to start the game.", + LockMode::LOCK_WHILE_RUNNING, + "2000 ms" + ) + , START_GAME_WAIT1( + "2. Start Game Wait:
Wait this long for the game to load.", + LockMode::LOCK_WHILE_RUNNING, + "20 s" + ) + , ENTER_GAME_MASH0( + "3. Enter Game Mash:
Mash A for this long to enter the game.", + LockMode::LOCK_WHILE_RUNNING, + "5 s" + ) + , ENTER_GAME_WAIT0( + "4. Enter Game Wait:
Wait this long for the opening animations to finish.", + LockMode::LOCK_WHILE_RUNNING, + "15 s" + ) + , m_shiny_audio_settings("Shiny Audio Settings:") + , SHINY_SOUND_THRESHOLD( + "Shiny Sound Threshold:
Maximum error coefficient to trigger a shiny detection.", + LockMode::LOCK_WHILE_RUNNING, + 0.95, 0, 1.0 + ) + , SHINY_SOUND_LOW_FREQUENCY( + "Shiny Sound Low Frequency (Hz):
High pass filter frequency for shiny sound.", + LockMode::LOCK_WHILE_RUNNING, + 1000, 0, 48000 + ) +{ + PA_ADD_STATIC(m_general); + + PA_ADD_STATIC(m_menu_navigation); + PA_ADD_OPTION(GAME_TO_HOME_DELAY0); + + PA_ADD_STATIC(m_start_game_timings); + PA_ADD_OPTION(START_GAME_MASH0); + PA_ADD_OPTION(START_GAME_WAIT1); + PA_ADD_OPTION(ENTER_GAME_MASH0); + PA_ADD_OPTION(ENTER_GAME_WAIT0); + + PA_ADD_STATIC(m_shiny_audio_settings); + PA_ADD_OPTION(SHINY_SOUND_THRESHOLD); + PA_ADD_OPTION(SHINY_SOUND_LOW_FREQUENCY); +} + + + + + +GameSettings_Descriptor::GameSettings_Descriptor() + : PanelDescriptor( + Color(), + "PokemonLGPE:GlobalSettings", + STRING_POKEMON + " LGPE", "Game Settings", + "ComputerControl/blob/master/Wiki/Programs/PokemonLGPE/PokemonSettings.md", + "Global " + STRING_POKEMON + " Let's Go Settings" + ) +{} + + + +GameSettingsPanel::GameSettingsPanel(const GameSettings_Descriptor& descriptor) + : SettingsPanelInstance(descriptor) + , settings(GameSettings::instance()) +{ + PA_ADD_OPTION(settings); +} + + + + + +} +} +} + + + + + + diff --git a/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Settings.h b/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Settings.h index cbaa1135e6..4380f298d6 100644 --- a/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Settings.h +++ b/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Settings.h @@ -1,61 +1,61 @@ -/* Pokemon Let's Go Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLGPE_Settings_H -#define PokemonAutomation_PokemonLGPE_Settings_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Panels/SettingsPanel.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - - -class GameSettings : public BatchOption{ - GameSettings(); -public: - static GameSettings& instance(); - - SectionDividerOption m_general; - - SectionDividerOption m_menu_navigation; - MillisecondsOption GAME_TO_HOME_DELAY0; - - SectionDividerOption m_start_game_timings; - MillisecondsOption START_GAME_MASH0; - MillisecondsOption START_GAME_WAIT1; - MillisecondsOption ENTER_GAME_MASH0; - MillisecondsOption ENTER_GAME_WAIT0; - - SectionDividerOption m_shiny_audio_settings; - FloatingPointOption SHINY_SOUND_THRESHOLD; - FloatingPointOption SHINY_SOUND_LOW_FREQUENCY; -}; - - - - -class GameSettings_Descriptor : public PanelDescriptor{ -public: - GameSettings_Descriptor(); -}; - - -class GameSettingsPanel : public SettingsPanelInstance{ -public: - GameSettingsPanel(const GameSettings_Descriptor& descriptor); -private: - GameSettings& settings; -}; - - -} -} -} -#endif +/* Pokemon Let's Go Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLGPE_Settings_H +#define PokemonAutomation_PokemonLGPE_Settings_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Panels/SettingsPanel.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + + +class GameSettings : public BatchOption{ + GameSettings(); +public: + static GameSettings& instance(); + + SectionDividerOption m_general; + + SectionDividerOption m_menu_navigation; + MillisecondsOption GAME_TO_HOME_DELAY0; + + SectionDividerOption m_start_game_timings; + MillisecondsOption START_GAME_MASH0; + MillisecondsOption START_GAME_WAIT1; + MillisecondsOption ENTER_GAME_MASH0; + MillisecondsOption ENTER_GAME_WAIT0; + + SectionDividerOption m_shiny_audio_settings; + FloatingPointOption SHINY_SOUND_THRESHOLD; + FloatingPointOption SHINY_SOUND_LOW_FREQUENCY; +}; + + + + +class GameSettings_Descriptor : public PanelDescriptor{ +public: + GameSettings_Descriptor(); +}; + + +class GameSettingsPanel : public SettingsPanelInstance{ +public: + GameSettingsPanel(const GameSettings_Descriptor& descriptor); +private: + GameSettings& settings; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/Farming/PokemonLGPE_DailyItemFarmer.cpp b/SerialPrograms/Source/PokemonLGPE/Programs/Farming/PokemonLGPE_DailyItemFarmer.cpp index 409a990fdc..63c61d739f 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/Farming/PokemonLGPE_DailyItemFarmer.cpp +++ b/SerialPrograms/Source/PokemonLGPE/Programs/Farming/PokemonLGPE_DailyItemFarmer.cpp @@ -1,237 +1,237 @@ -/* LGPE Daily Item Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "PokemonLGPE/Commands/PokemonLGPE_DateSpam.h" -#include "PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h" -#include "PokemonLGPE/Programs/PokemonLGPE_GameEntry.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonLGPE_DailyItemFarmer.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -DailyItemFarmer_Descriptor::DailyItemFarmer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLGPE:DailyItemFarmer", - Pokemon::STRING_POKEMON + " LGPE", "Daily Item Farmer", - "ComputerControl/blob/master/Wiki/Programs/PokemonLGPE/DailyItemFarmer.md", - "Farm daily item respawns (ex. fossils) by date-skipping.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_RightJoycon}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - -struct DailyItemFarmer_Descriptor::Stats : public StatsTracker{ - Stats() - : skips(m_stats["Skips"]) - { - m_display_order.emplace_back("Skips"); - } - std::atomic& skips; -}; -std::unique_ptr DailyItemFarmer_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -DailyItemFarmer::DailyItemFarmer() - : ATTEMPTS( - "Number of attempts:", - LockMode::LOCK_WHILE_RUNNING, - 30, 1 - ) - , LINK_CODE( - "Link Code:
The link code used when matching for a trade/battle. This only needs to be changed when running multiple LGPE date-skip programs at the same time.", - { //Combinations of 3 different symbols is possible but 10 choices seems like enough. - {LinkCode::Pikachu, "pikachu", "Pikachu"}, - {LinkCode::Eevee, "eevee", "Eevee"}, - {LinkCode::Bulbasaur, "bulbasaur", "Bulbasaur"}, - {LinkCode::Charmander, "charmander", "Charmander"}, - {LinkCode::Squirtle, "squirtle", "Squirtle"}, - {LinkCode::Pidgey, "pidgey", "Pidgey"}, - {LinkCode::Caterpie, "caterpie", "Caterpie"}, - {LinkCode::Rattata, "rattata", "Rattata"}, - {LinkCode::Jigglypuff, "jigglypuff", "Jigglypuff"}, - {LinkCode::Diglett, "diglett", "Diglett"}, - }, - LockMode::LOCK_WHILE_RUNNING, - LinkCode::Pikachu - ) - , FIX_TIME_WHEN_DONE( - "Fix Time when Done:
Fix the time after the program finishes.", - LockMode::UNLOCK_WHILE_RUNNING, false - ) - , GO_HOME_WHEN_DONE(false) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(ATTEMPTS); - PA_ADD_OPTION(LINK_CODE); - PA_ADD_OPTION(FIX_TIME_WHEN_DONE); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void DailyItemFarmer::start_local_trade(SingleSwitchProgramEnvironment& env, JoyconContext& context){ - env.log("Starting local trade."); - //Open Menu -> Communication -> Nearby player -> Local Trade - pbf_press_button(context, BUTTON_X, 200ms, 500ms); - pbf_move_joystick(context, 255, 128, 100ms, 100ms); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_wait(context, 1000ms); //Black screen - context.wait_for_all_requests(); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - - //Enter link code - switch(LINK_CODE) { - case LinkCode::Pikachu: - break; - case LinkCode::Eevee: - pbf_move_joystick(context, 255, 128, 100ms, 100ms); - break; - case LinkCode::Bulbasaur: - pbf_move_joystick(context, 255, 128, 100ms, 100ms); - pbf_move_joystick(context, 255, 128, 100ms, 100ms); - break; - case LinkCode::Charmander: - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - break; - case LinkCode::Squirtle: - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - break; - case LinkCode::Pidgey: - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - break; - case LinkCode::Caterpie: - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_move_joystick(context, 255, 128, 100ms, 100ms); - break; - case LinkCode::Rattata: - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - break; - case LinkCode::Jigglypuff: - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - break; - case LinkCode::Diglett: - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - break; - default: - env.log("Invalid link code selection. Defaulting to Pikachu."); - break; - } - //Select symbol three times, then enter link search - pbf_press_button(context, BUTTON_A, 200ms, 100ms); - pbf_press_button(context, BUTTON_A, 200ms, 100ms); - pbf_press_button(context, BUTTON_A, 200ms, 100ms); - pbf_wait(context, 1000ms); //let search start - context.wait_for_all_requests(); -} - -void DailyItemFarmer::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ - JoyconContext context(scope, env.console.controller()); - assert_16_9_720p_min(env.logger(), env.console); - DailyItemFarmer_Descriptor::Stats& stats = env.current_stats(); - - /* Stand in front of the fossil spawn near Mewtwo. - * Use a repel to keep wild encounters away. - * Start program in-game. - * 100% daily spawn. Only works near Mewtwo. - * Other cave item spawns are tied to steps taken. - * Should work for other hidden daily items, game corner, mt moon moonstones, etc. - */ - - uint8_t year = MAX_YEAR; - - //Roll the date back before doing anything else. - start_local_trade(env, context); - pbf_press_button(context, BUTTON_HOME, 160ms, 1000ms); - home_to_date_time(context, true); - env.log("Rolling date back."); - roll_date_backward_N(context, MAX_YEAR); - year = 0; - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - pbf_mash_button(context, BUTTON_B, 5000ms); - context.wait_for_all_requests(); - - env.log("Starting pickup loop."); - for (uint32_t count = 0; count < ATTEMPTS; count++) { - env.log("Pick up item."); - pbf_mash_button(context, BUTTON_A, 4000ms); - context.wait_for_all_requests(); - - start_local_trade(env, context); - - //Dateskip - pbf_press_button(context, BUTTON_HOME, 160ms, 1000ms); - home_to_date_time(context, true); - if (year >= MAX_YEAR){ - env.log("Rolling date back."); - roll_date_backward_N(context, MAX_YEAR); - year = 0; - }else{ - env.log("Rolling date forward."); - roll_date_forward_1(context); - year++; - } - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - - //Re-enter game and close out link menu - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - pbf_mash_button(context, BUTTON_B, 5000ms); - context.wait_for_all_requests(); - - stats.skips++; - env.update_stats(); - } - - if (FIX_TIME_WHEN_DONE){ - pbf_press_button(context, BUTTON_HOME, 80ms, 1000ms); - home_to_date_time(context, false); - pbf_press_button(context, BUTTON_A, 50ms, 500ms); - pbf_press_button(context, BUTTON_A, 50ms, 500ms); - pbf_wait(context, 100ms); - context.wait_for_all_requests(); - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_from_home(env.console, context); - } - - if (GO_HOME_WHEN_DONE) { - pbf_press_button(context, BUTTON_HOME, 200ms, 1000ms); - } - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - -} -} -} +/* LGPE Daily Item Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "PokemonLGPE/Commands/PokemonLGPE_DateSpam.h" +#include "PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h" +#include "PokemonLGPE/Programs/PokemonLGPE_GameEntry.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonLGPE_DailyItemFarmer.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +DailyItemFarmer_Descriptor::DailyItemFarmer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLGPE:DailyItemFarmer", + Pokemon::STRING_POKEMON + " LGPE", "Daily Item Farmer", + "ComputerControl/blob/master/Wiki/Programs/PokemonLGPE/DailyItemFarmer.md", + "Farm daily item respawns (ex. fossils) by date-skipping.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_RightJoycon}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + +struct DailyItemFarmer_Descriptor::Stats : public StatsTracker{ + Stats() + : skips(m_stats["Skips"]) + { + m_display_order.emplace_back("Skips"); + } + std::atomic& skips; +}; +std::unique_ptr DailyItemFarmer_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +DailyItemFarmer::DailyItemFarmer() + : ATTEMPTS( + "Number of attempts:", + LockMode::LOCK_WHILE_RUNNING, + 30, 1 + ) + , LINK_CODE( + "Link Code:
The link code used when matching for a trade/battle. This only needs to be changed when running multiple LGPE date-skip programs at the same time.", + { //Combinations of 3 different symbols is possible but 10 choices seems like enough. + {LinkCode::Pikachu, "pikachu", "Pikachu"}, + {LinkCode::Eevee, "eevee", "Eevee"}, + {LinkCode::Bulbasaur, "bulbasaur", "Bulbasaur"}, + {LinkCode::Charmander, "charmander", "Charmander"}, + {LinkCode::Squirtle, "squirtle", "Squirtle"}, + {LinkCode::Pidgey, "pidgey", "Pidgey"}, + {LinkCode::Caterpie, "caterpie", "Caterpie"}, + {LinkCode::Rattata, "rattata", "Rattata"}, + {LinkCode::Jigglypuff, "jigglypuff", "Jigglypuff"}, + {LinkCode::Diglett, "diglett", "Diglett"}, + }, + LockMode::LOCK_WHILE_RUNNING, + LinkCode::Pikachu + ) + , FIX_TIME_WHEN_DONE( + "Fix Time when Done:
Fix the time after the program finishes.", + LockMode::UNLOCK_WHILE_RUNNING, false + ) + , GO_HOME_WHEN_DONE(false) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(ATTEMPTS); + PA_ADD_OPTION(LINK_CODE); + PA_ADD_OPTION(FIX_TIME_WHEN_DONE); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void DailyItemFarmer::start_local_trade(SingleSwitchProgramEnvironment& env, JoyconContext& context){ + env.log("Starting local trade."); + //Open Menu -> Communication -> Nearby player -> Local Trade + pbf_press_button(context, BUTTON_X, 200ms, 500ms); + pbf_move_joystick(context, 255, 128, 100ms, 100ms); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_wait(context, 1000ms); //Black screen + context.wait_for_all_requests(); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + + //Enter link code + switch(LINK_CODE) { + case LinkCode::Pikachu: + break; + case LinkCode::Eevee: + pbf_move_joystick(context, 255, 128, 100ms, 100ms); + break; + case LinkCode::Bulbasaur: + pbf_move_joystick(context, 255, 128, 100ms, 100ms); + pbf_move_joystick(context, 255, 128, 100ms, 100ms); + break; + case LinkCode::Charmander: + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + break; + case LinkCode::Squirtle: + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + break; + case LinkCode::Pidgey: + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + break; + case LinkCode::Caterpie: + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_move_joystick(context, 255, 128, 100ms, 100ms); + break; + case LinkCode::Rattata: + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + break; + case LinkCode::Jigglypuff: + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + break; + case LinkCode::Diglett: + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + break; + default: + env.log("Invalid link code selection. Defaulting to Pikachu."); + break; + } + //Select symbol three times, then enter link search + pbf_press_button(context, BUTTON_A, 200ms, 100ms); + pbf_press_button(context, BUTTON_A, 200ms, 100ms); + pbf_press_button(context, BUTTON_A, 200ms, 100ms); + pbf_wait(context, 1000ms); //let search start + context.wait_for_all_requests(); +} + +void DailyItemFarmer::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ + JoyconContext context(scope, env.console.controller()); + assert_16_9_720p_min(env.logger(), env.console); + DailyItemFarmer_Descriptor::Stats& stats = env.current_stats(); + + /* Stand in front of the fossil spawn near Mewtwo. + * Use a repel to keep wild encounters away. + * Start program in-game. + * 100% daily spawn. Only works near Mewtwo. + * Other cave item spawns are tied to steps taken. + * Should work for other hidden daily items, game corner, mt moon moonstones, etc. + */ + + uint8_t year = MAX_YEAR; + + //Roll the date back before doing anything else. + start_local_trade(env, context); + pbf_press_button(context, BUTTON_HOME, 160ms, 1000ms); + home_to_date_time(env.console, context, true); + env.log("Rolling date back."); + roll_date_backward_N(context, MAX_YEAR); + year = 0; + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + pbf_mash_button(context, BUTTON_B, 5000ms); + context.wait_for_all_requests(); + + env.log("Starting pickup loop."); + for (uint32_t count = 0; count < ATTEMPTS; count++) { + env.log("Pick up item."); + pbf_mash_button(context, BUTTON_A, 4000ms); + context.wait_for_all_requests(); + + start_local_trade(env, context); + + //Dateskip + pbf_press_button(context, BUTTON_HOME, 160ms, 1000ms); + home_to_date_time(env.console, context, true); + if (year >= MAX_YEAR){ + env.log("Rolling date back."); + roll_date_backward_N(context, MAX_YEAR); + year = 0; + }else{ + env.log("Rolling date forward."); + roll_date_forward_1(context); + year++; + } + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + + //Re-enter game and close out link menu + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + pbf_mash_button(context, BUTTON_B, 5000ms); + context.wait_for_all_requests(); + + stats.skips++; + env.update_stats(); + } + + if (FIX_TIME_WHEN_DONE){ + pbf_press_button(context, BUTTON_HOME, 80ms, 1000ms); + home_to_date_time(env.console, context, false); + pbf_press_button(context, BUTTON_A, 50ms, 500ms); + pbf_press_button(context, BUTTON_A, 50ms, 500ms); + pbf_wait(context, 100ms); + context.wait_for_all_requests(); + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_from_home(env.console, context); + } + + if (GO_HOME_WHEN_DONE) { + pbf_press_button(context, BUTTON_HOME, 200ms, 1000ms); + } + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/Farming/PokemonLGPE_DailyItemFarmer.h b/SerialPrograms/Source/PokemonLGPE/Programs/Farming/PokemonLGPE_DailyItemFarmer.h index c16c64db1c..e03be6751d 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/Farming/PokemonLGPE_DailyItemFarmer.h +++ b/SerialPrograms/Source/PokemonLGPE/Programs/Farming/PokemonLGPE_DailyItemFarmer.h @@ -1,67 +1,67 @@ -/* LGPE Daily Item Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLGPE_DailyItemFarmer_H -#define PokemonAutomation_PokemonLGPE_DailyItemFarmer_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -class DailyItemFarmer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - DailyItemFarmer_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class DailyItemFarmer : public SingleSwitchProgramInstance{ -public: - DailyItemFarmer(); - virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; - -private: - void start_local_trade(SingleSwitchProgramEnvironment& env, JoyconContext& context); - - SimpleIntegerOption ATTEMPTS; - - enum class LinkCode{ - Pikachu, - Eevee, - Bulbasaur, - Charmander, - Squirtle, - Pidgey, - Caterpie, - Rattata, - Jigglypuff, - Diglett, - }; - EnumDropdownOption LINK_CODE; - - BooleanCheckBoxOption FIX_TIME_WHEN_DONE; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif - - - +/* LGPE Daily Item Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLGPE_DailyItemFarmer_H +#define PokemonAutomation_PokemonLGPE_DailyItemFarmer_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +class DailyItemFarmer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + DailyItemFarmer_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class DailyItemFarmer : public SingleSwitchProgramInstance{ +public: + DailyItemFarmer(); + virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; + +private: + void start_local_trade(SingleSwitchProgramEnvironment& env, JoyconContext& context); + + SimpleIntegerOption ATTEMPTS; + + enum class LinkCode{ + Pikachu, + Eevee, + Bulbasaur, + Charmander, + Squirtle, + Pidgey, + Caterpie, + Rattata, + Jigglypuff, + Diglett, + }; + EnumDropdownOption LINK_CODE; + + BooleanCheckBoxOption FIX_TIME_WHEN_DONE; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/PokemonLGPE_GameEntry.cpp b/SerialPrograms/Source/PokemonLGPE/Programs/PokemonLGPE_GameEntry.cpp index 29d1631af7..dadf6f694b 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/PokemonLGPE_GameEntry.cpp +++ b/SerialPrograms/Source/PokemonLGPE/Programs/PokemonLGPE_GameEntry.cpp @@ -1,134 +1,134 @@ -/* Game Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "Controllers/ControllerCapability.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "NintendoSwitch/Inference/NintendoSwitch_DetectHome.h" -#include "PokemonLGPE/PokemonLGPE_Settings.h" -#include "PokemonLGPE_GameEntry.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - - -bool reset_game_to_gamemenu( - ConsoleHandle& console, JoyconContext& context -){ - close_game(console, context); - start_game_from_home_with_inference( - console, - context, - 0, 0, - GameSettings::instance().START_GAME_MASH0 - ); - - // Now the game has opened: - return openedgame_to_gamemenu(console, context, GameSettings::instance().START_GAME_WAIT1); -} - -bool gamemenu_to_ingame( - VideoStream& stream, JoyconContext& context, - Milliseconds mash_duration, Milliseconds enter_game_timeout -){ - //Includes choosing the controller. - //Controllers are disconnected? on selection screen so make sure to mash. - stream.log("Mashing A to enter game and select controller..."); - pbf_mash_button(context, BUTTON_A, mash_duration); - context.wait_for_all_requests(); - - //White screen, Pikachu/Eevee running across the screen. Mash will not speed it up. - //Mash A at then end to enter continue screen - BlackScreenOverWatcher detector(COLOR_RED, {0.2, 0.2, 0.6, 0.6}); - stream.log("Waiting to enter game..."); - int ret = run_until( - stream, context, - [&enter_game_timeout](JoyconContext& context){ - pbf_wait(context, enter_game_timeout); - pbf_press_button(context, BUTTON_A, 400ms, 10ms); - pbf_wait(context, 5000ms); - }, - {detector} - ); - context.wait_for_all_requests(); - if (ret == 0){ - stream.log("At continue screen."); - }else{ - stream.log("Timed out waiting to enter game and select continue.", COLOR_RED); - return false; - } - pbf_wait(context, 1000ms); - context.wait_for_all_requests(); - - //Continue your adventure. - BlackScreenOverWatcher detector2(COLOR_YELLOW, {0.2, 0.2, 0.6, 0.6}); - int ret2 = run_until( - stream, context, - [](JoyconContext& context){ - pbf_press_button(context, BUTTON_A, 400ms, 10ms); - pbf_wait(context, 5000ms); - }, - {detector2} - ); - context.wait_for_all_requests(); - if (ret2 == 0){ - stream.log("Entered game!"); - return true; - }else{ - stream.log("Timed out waiting to enter game.", COLOR_RED); - return false; - } -} - -bool reset_game_from_home( - ProgramEnvironment& env, - ConsoleHandle& console, JoyconContext& context, - Milliseconds post_wait_time -){ - if (!(context.controller().controller_type() == ControllerType::NintendoSwitch_RightJoycon)) { - console.log("Right Joycon required!", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "reset_game_from_home(): Right Joycon required.", - console - ); - } - bool ok = true; - ok &= reset_game_to_gamemenu(console, context); - ok &= gamemenu_to_ingame( - console, context, - GameSettings::instance().ENTER_GAME_MASH0, - GameSettings::instance().ENTER_GAME_WAIT0 - ); - if (!ok){ - dump_image(console.logger(), env.program_info(), console.video(), "StartGame"); - } - console.log("Entered game! Waiting out grace period."); - pbf_wait(context, post_wait_time); - context.wait_for_all_requests(); - return ok; -} - - - - - -} -} -} +/* Game Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "Controllers/ControllerCapability.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "NintendoSwitch/Inference/NintendoSwitch_DetectHome.h" +#include "PokemonLGPE/PokemonLGPE_Settings.h" +#include "PokemonLGPE_GameEntry.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + + +bool reset_game_to_gamemenu( + ConsoleHandle& console, JoyconContext& context +){ + close_game(console, context); + start_game_from_home_with_inference( + console, + context, + 0, 0, + GameSettings::instance().START_GAME_MASH0 + ); + + // Now the game has opened: + return openedgame_to_gamemenu(console, context, GameSettings::instance().START_GAME_WAIT1); +} + +bool gamemenu_to_ingame( + VideoStream& stream, JoyconContext& context, + Milliseconds mash_duration, Milliseconds enter_game_timeout +){ + //Includes choosing the controller. + //Controllers are disconnected? on selection screen so make sure to mash. + stream.log("Mashing A to enter game and select controller..."); + pbf_mash_button(context, BUTTON_A, mash_duration); + context.wait_for_all_requests(); + + //White screen, Pikachu/Eevee running across the screen. Mash will not speed it up. + //Mash A at then end to enter continue screen + BlackScreenOverWatcher detector(COLOR_RED, {0.2, 0.2, 0.6, 0.6}); + stream.log("Waiting to enter game..."); + int ret = run_until( + stream, context, + [&enter_game_timeout](JoyconContext& context){ + pbf_wait(context, enter_game_timeout); + pbf_press_button(context, BUTTON_A, 400ms, 10ms); + pbf_wait(context, 5000ms); + }, + {detector} + ); + context.wait_for_all_requests(); + if (ret == 0){ + stream.log("At continue screen."); + }else{ + stream.log("Timed out waiting to enter game and select continue.", COLOR_RED); + return false; + } + pbf_wait(context, 1000ms); + context.wait_for_all_requests(); + + //Continue your adventure. + BlackScreenOverWatcher detector2(COLOR_YELLOW, {0.2, 0.2, 0.6, 0.6}); + int ret2 = run_until( + stream, context, + [](JoyconContext& context){ + pbf_press_button(context, BUTTON_A, 400ms, 10ms); + pbf_wait(context, 5000ms); + }, + {detector2} + ); + context.wait_for_all_requests(); + if (ret2 == 0){ + stream.log("Entered game!"); + return true; + }else{ + stream.log("Timed out waiting to enter game.", COLOR_RED); + return false; + } +} + +bool reset_game_from_home( + ProgramEnvironment& env, + ConsoleHandle& console, JoyconContext& context, + Milliseconds post_wait_time +){ + if (!(context.controller().controller_type() == ControllerType::NintendoSwitch_RightJoycon)) { + console.log("Right Joycon required!", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "reset_game_from_home(): Right Joycon required.", + console + ); + } + bool ok = true; + ok &= reset_game_to_gamemenu(console, context); + ok &= gamemenu_to_ingame( + console, context, + GameSettings::instance().ENTER_GAME_MASH0, + GameSettings::instance().ENTER_GAME_WAIT0 + ); + if (!ok){ + dump_image(console.logger(), env.program_info(), console.video(), "StartGame"); + } + console.log("Entered game! Waiting out grace period."); + pbf_wait(context, post_wait_time); + context.wait_for_all_requests(); + return ok; +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/PokemonLGPE_GameEntry.h b/SerialPrograms/Source/PokemonLGPE/Programs/PokemonLGPE_GameEntry.h index d139cb2965..d2114a8b51 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/PokemonLGPE_GameEntry.h +++ b/SerialPrograms/Source/PokemonLGPE/Programs/PokemonLGPE_GameEntry.h @@ -1,49 +1,49 @@ -/* Game Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLGPE_GameEntry_H -#define PokemonAutomation_PokemonLGPE_GameEntry_H - -#include -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ - class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonLGPE{ - - - -// From Switch Home menu, reset game and wait until the game menu screen (where -// "Press A" is displayed to enter the game) is shown. -bool reset_game_to_gamemenu( - ConsoleHandle& console, JoyconContext& context -); - -// From the game menu screen (where "Press A" is displayed to enter the game), -// mash A to enter the game and wait until the black screen is gone. -bool gamemenu_to_ingame( - VideoStream& stream, JoyconContext& context, - Milliseconds mash_duration, Milliseconds enter_game_timeout -); - -// From Switch Home menu, start game and wait until the player character appears in game. -// post_wait_time: how many ticks to wait after the black screen (shown when loading the map) is over. -bool reset_game_from_home( - ProgramEnvironment& env, - ConsoleHandle& console, JoyconContext& context, - Milliseconds post_wait_time = std::chrono::milliseconds(125) -); - - - - -} -} -} -#endif +/* Game Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLGPE_GameEntry_H +#define PokemonAutomation_PokemonLGPE_GameEntry_H + +#include +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ + class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonLGPE{ + + + +// From Switch Home menu, reset game and wait until the game menu screen (where +// "Press A" is displayed to enter the game) is shown. +bool reset_game_to_gamemenu( + ConsoleHandle& console, JoyconContext& context +); + +// From the game menu screen (where "Press A" is displayed to enter the game), +// mash A to enter the game and wait until the black screen is gone. +bool gamemenu_to_ingame( + VideoStream& stream, JoyconContext& context, + Milliseconds mash_duration, Milliseconds enter_game_timeout +); + +// From Switch Home menu, start game and wait until the player character appears in game. +// post_wait_time: how many ticks to wait after the black screen (shown when loading the map) is over. +bool reset_game_from_home( + ProgramEnvironment& env, + ConsoleHandle& console, JoyconContext& context, + Milliseconds post_wait_time = std::chrono::milliseconds(125) +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_AlolanTrade.cpp b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_AlolanTrade.cpp index 7b7456f0bb..e7cdb9d606 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_AlolanTrade.cpp +++ b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_AlolanTrade.cpp @@ -1,303 +1,303 @@ -/* LGPE Alolan Trade - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "Pokemon/Pokemon_Strings.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h" -#include "PokemonLGPE/Programs/PokemonLGPE_GameEntry.h" -#include "PokemonLGPE_AlolanTrade.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -AlolanTrade_Descriptor::AlolanTrade_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLGPE:AlolanTrade", - Pokemon::STRING_POKEMON + " LGPE", "Alolan Trade", - "ComputerControl/blob/master/Wiki/Programs/PokemonLGPE/AlolanTrade.md", - "Shiny hunt Alolan forms by trading in-game.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_RightJoycon}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - -struct AlolanTrade_Descriptor::Stats : public StatsTracker{ - Stats() - : trades(m_stats["Trades"]) - , resets(m_stats["Resets"]) - , shinies(m_stats["Shinies"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Trades"); - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Shinies"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& trades; - std::atomic& resets; - std::atomic& shinies; - std::atomic& errors; -}; -std::unique_ptr AlolanTrade_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -AlolanTrade::AlolanTrade() - : NUM_TRADES( - "Number of Pokemon to trade:", - LockMode::LOCK_WHILE_RUNNING, - 30, 1 - ) - , GO_HOME_WHEN_DONE(false) - , NOTIFICATION_SHINY( - "Shiny Found", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_SHINY, - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(NUM_TRADES); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void AlolanTrade::run_trade(SingleSwitchProgramEnvironment& env, JoyconContext& context){ - AlolanTrade_Descriptor::Stats& stats = env.current_stats(); - //Talk to NPC, say Yes, select Pokemon from box. - BlackScreenOverWatcher trade_started(COLOR_RED); - int ret = run_until( - env.console, context, - [](JoyconContext& context){ - pbf_mash_button(context, BUTTON_A, 15000ms); - }, - {trade_started} - ); - context.wait_for_all_requests(); - if (ret != 0){ - env.log("Failed to start trade.", COLOR_RED); - stats.errors++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to start trade.", - env.console - ); - } - else { - env.log("Trade started."); - } - - //Wait for trade to complete. - BlackScreenOverWatcher trade_completed(COLOR_YELLOW); - int ret2 = wait_until( - env.console, context, - std::chrono::seconds(120), - {trade_completed} - ); - context.wait_for_all_requests(); - if (ret2 != 0){ - stats.errors++; - env.update_stats(); - env.log("Did not detect end of trade.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Did not detect end of trade.", - env.console - ); - } - else { - env.log("Trade completed."); - } - - //Summary will appear the first time you trade in a session(?) - //Sometimes it appears anyway, don't know what determines it - //Exit menu and dialog. - pbf_mash_button(context, BUTTON_B, 3000ms); - context.wait_for_all_requests(); -} - -void AlolanTrade::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ - JoyconContext context(scope, env.console.controller()); - assert_16_9_720p_min(env.logger(), env.console); - AlolanTrade_Descriptor::Stats& stats = env.current_stats(); - - /* - WARNING: JOYCON TEST PROGRAM. Not well tested. Bare minimum in general. - - Right joycon required for home button (this means no on-switch screenshots). - Also don't remap any of the buttons in the switch button mapping settings. - - Preconditions: - DO NOT have any Pokemon you want to keep in your boxes. Move them out to Home first. - Favoriting a Pokemon does not prevent it from being traded. - ?This must not be your first time doing the trade? (I've done all the trades, so I can't check first time trade behavior.) - - Setup: - Catch the Kanto variant of the target. Put this number in NUM_TRADES. - Stand in front of trade NPC. - Save the game. - Start the program in-game. - - Future additions?: - skip favorited pokemon - they have a symbol to indicate fav status (imo still risky to do, just move them out) - detect when all pokemon traded - trading screen will open but text will appear in the center - "you don't have any pokemon your trading partner wants" - detect dialog box, detect yes/no confirm box - actual enter game and start screen detectors - menu detectors, etc. - get rid of all this blindly mashing A in general...so need everything really. - */ - - bool shiny_found = false; - while (!shiny_found) { - //Run trades - for (uint16_t i = 0; i < NUM_TRADES; i++) { - env.log("Running trade."); - run_trade(env, context); - - stats.trades++; - env.update_stats(); - } - - env.log("Done trading. Checking boxes."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Done trading. Checking boxes." - ); - - //To check pokemon in menu boxes - //Open menu - always defaults to center (Party) - //Menu: - // --Play with Partner--(centered) - //Pokedex - Bag - Party - Communicate - Save (these all have a colored line under when selected + an arrow to indicate) - //(Press Y for options) - - //Make sure any extra dialog is closed - pbf_mash_button(context, BUTTON_B, 3000ms); - context.wait_for_all_requests(); - - //Wait a bit. - pbf_wait(context, 2500ms); - context.wait_for_all_requests(); - - //Open menu, open party, open boxes - env.log("Opening boxes."); - pbf_press_button(context, BUTTON_X, 200ms, 500ms); - pbf_press_button(context, BUTTON_A, 200ms, 1500ms); - pbf_press_button(context, BUTTON_Y, 200ms, 2000ms); - context.wait_for_all_requests(); - - //Sort by order caught - env.log("Sorting by order caught."); - pbf_press_button(context, BUTTON_Y, 200ms, 1000ms); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - context.wait_for_all_requests(); - - //Press left to go to last (most recent) Pokemon - env.log("Opening summary of most recent Pokemon."); - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - context.wait_for_all_requests(); - - //View summary - it takes a moment to load - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_press_button(context, BUTTON_A, 200ms, 100ms); - context.wait_for_all_requests(); - - pbf_wait(context, 5000ms); - context.wait_for_all_requests(); - - //Now check for shinies. Check everything that was traded. - env.log("Checking received Pokemon."); - for (uint16_t i = 0; i < NUM_TRADES; i++) { - VideoSnapshot screen = env.console.video().snapshot(); - ShinySymbolDetector shiny_checker(COLOR_YELLOW); - bool check = shiny_checker.read(env.console.logger(), screen); - - if (check) { - env.log("Shiny detected!"); - stats.shinies++; - env.update_stats(); - send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", screen, true); - shiny_found = true; - - //Back out to menu and favorite the shiny. - env.log("Favoriting shiny."); - pbf_press_button(context, BUTTON_B, 200ms, 5000ms); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_move_joystick(context, 128, 0, 100ms, 100ms); - pbf_move_joystick(context, 128, 0, 100ms, 100ms); - pbf_move_joystick(context, 128, 0, 100ms, 200ms); - pbf_press_button(context, BUTTON_A, 200ms, 800ms); - pbf_press_button(context, BUTTON_A, 200ms, 800ms); - pbf_press_button(context, BUTTON_B, 200ms, 800ms); - - //Go into summary again - env.log("Navigating back into summary."); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_press_button(context, BUTTON_A, 200ms, 100ms); - context.wait_for_all_requests(); - pbf_wait(context, 5000ms); - context.wait_for_all_requests(); - } - else { - env.log("Not shiny."); - } - - //Move left, check next. - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - pbf_press_button(context, BUTTON_X, 0ms, 1000ms); - context.wait_for_all_requests(); - } - - if (!shiny_found) { - env.log("Out of Pokemon to trade and no shiny found. Resetting game."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Out of Pokemon to trade and no shiny found. Resetting game." - ); - - //Reset game - pbf_press_button(context, BUTTON_HOME, 200ms, 2000ms); - reset_game_from_home(env, env.console, context, 3000ms); - context.wait_for_all_requests(); - - stats.resets++; - env.update_stats(); - } - } - - if (GO_HOME_WHEN_DONE) { - pbf_press_button(context, BUTTON_HOME, 200ms, 1000ms); - } - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - -} -} -} +/* LGPE Alolan Trade + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "Pokemon/Pokemon_Strings.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h" +#include "PokemonLGPE/Programs/PokemonLGPE_GameEntry.h" +#include "PokemonLGPE_AlolanTrade.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +AlolanTrade_Descriptor::AlolanTrade_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLGPE:AlolanTrade", + Pokemon::STRING_POKEMON + " LGPE", "Alolan Trade", + "ComputerControl/blob/master/Wiki/Programs/PokemonLGPE/AlolanTrade.md", + "Shiny hunt Alolan forms by trading in-game.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_RightJoycon}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + +struct AlolanTrade_Descriptor::Stats : public StatsTracker{ + Stats() + : trades(m_stats["Trades"]) + , resets(m_stats["Resets"]) + , shinies(m_stats["Shinies"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Trades"); + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Shinies"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& trades; + std::atomic& resets; + std::atomic& shinies; + std::atomic& errors; +}; +std::unique_ptr AlolanTrade_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +AlolanTrade::AlolanTrade() + : NUM_TRADES( + "Number of Pokemon to trade:", + LockMode::LOCK_WHILE_RUNNING, + 30, 1 + ) + , GO_HOME_WHEN_DONE(false) + , NOTIFICATION_SHINY( + "Shiny Found", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_SHINY, + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(NUM_TRADES); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void AlolanTrade::run_trade(SingleSwitchProgramEnvironment& env, JoyconContext& context){ + AlolanTrade_Descriptor::Stats& stats = env.current_stats(); + //Talk to NPC, say Yes, select Pokemon from box. + BlackScreenOverWatcher trade_started(COLOR_RED); + int ret = run_until( + env.console, context, + [](JoyconContext& context){ + pbf_mash_button(context, BUTTON_A, 15000ms); + }, + {trade_started} + ); + context.wait_for_all_requests(); + if (ret != 0){ + env.log("Failed to start trade.", COLOR_RED); + stats.errors++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to start trade.", + env.console + ); + } + else { + env.log("Trade started."); + } + + //Wait for trade to complete. + BlackScreenOverWatcher trade_completed(COLOR_YELLOW); + int ret2 = wait_until( + env.console, context, + std::chrono::seconds(120), + {trade_completed} + ); + context.wait_for_all_requests(); + if (ret2 != 0){ + stats.errors++; + env.update_stats(); + env.log("Did not detect end of trade.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Did not detect end of trade.", + env.console + ); + } + else { + env.log("Trade completed."); + } + + //Summary will appear the first time you trade in a session(?) + //Sometimes it appears anyway, don't know what determines it + //Exit menu and dialog. + pbf_mash_button(context, BUTTON_B, 3000ms); + context.wait_for_all_requests(); +} + +void AlolanTrade::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ + JoyconContext context(scope, env.console.controller()); + assert_16_9_720p_min(env.logger(), env.console); + AlolanTrade_Descriptor::Stats& stats = env.current_stats(); + + /* + WARNING: JOYCON TEST PROGRAM. Not well tested. Bare minimum in general. + + Right joycon required for home button (this means no on-switch screenshots). + Also don't remap any of the buttons in the switch button mapping settings. + + Preconditions: + DO NOT have any Pokemon you want to keep in your boxes. Move them out to Home first. + Favoriting a Pokemon does not prevent it from being traded. + ?This must not be your first time doing the trade? (I've done all the trades, so I can't check first time trade behavior.) + + Setup: + Catch the Kanto variant of the target. Put this number in NUM_TRADES. + Stand in front of trade NPC. + Save the game. + Start the program in-game. + + Future additions?: + skip favorited pokemon - they have a symbol to indicate fav status (imo still risky to do, just move them out) + detect when all pokemon traded - trading screen will open but text will appear in the center + "you don't have any pokemon your trading partner wants" + detect dialog box, detect yes/no confirm box + actual enter game and start screen detectors + menu detectors, etc. + get rid of all this blindly mashing A in general...so need everything really. + */ + + bool shiny_found = false; + while (!shiny_found) { + //Run trades + for (uint16_t i = 0; i < NUM_TRADES; i++) { + env.log("Running trade."); + run_trade(env, context); + + stats.trades++; + env.update_stats(); + } + + env.log("Done trading. Checking boxes."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Done trading. Checking boxes." + ); + + //To check pokemon in menu boxes + //Open menu - always defaults to center (Party) + //Menu: + // --Play with Partner--(centered) + //Pokedex - Bag - Party - Communicate - Save (these all have a colored line under when selected + an arrow to indicate) + //(Press Y for options) + + //Make sure any extra dialog is closed + pbf_mash_button(context, BUTTON_B, 3000ms); + context.wait_for_all_requests(); + + //Wait a bit. + pbf_wait(context, 2500ms); + context.wait_for_all_requests(); + + //Open menu, open party, open boxes + env.log("Opening boxes."); + pbf_press_button(context, BUTTON_X, 200ms, 500ms); + pbf_press_button(context, BUTTON_A, 200ms, 1500ms); + pbf_press_button(context, BUTTON_Y, 200ms, 2000ms); + context.wait_for_all_requests(); + + //Sort by order caught + env.log("Sorting by order caught."); + pbf_press_button(context, BUTTON_Y, 200ms, 1000ms); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + context.wait_for_all_requests(); + + //Press left to go to last (most recent) Pokemon + env.log("Opening summary of most recent Pokemon."); + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + context.wait_for_all_requests(); + + //View summary - it takes a moment to load + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_press_button(context, BUTTON_A, 200ms, 100ms); + context.wait_for_all_requests(); + + pbf_wait(context, 5000ms); + context.wait_for_all_requests(); + + //Now check for shinies. Check everything that was traded. + env.log("Checking received Pokemon."); + for (uint16_t i = 0; i < NUM_TRADES; i++) { + VideoSnapshot screen = env.console.video().snapshot(); + ShinySymbolDetector shiny_checker(COLOR_YELLOW); + bool check = shiny_checker.read(env.console.logger(), screen); + + if (check) { + env.log("Shiny detected!"); + stats.shinies++; + env.update_stats(); + send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", screen, true); + shiny_found = true; + + //Back out to menu and favorite the shiny. + env.log("Favoriting shiny."); + pbf_press_button(context, BUTTON_B, 200ms, 5000ms); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_move_joystick(context, 128, 0, 100ms, 100ms); + pbf_move_joystick(context, 128, 0, 100ms, 100ms); + pbf_move_joystick(context, 128, 0, 100ms, 200ms); + pbf_press_button(context, BUTTON_A, 200ms, 800ms); + pbf_press_button(context, BUTTON_A, 200ms, 800ms); + pbf_press_button(context, BUTTON_B, 200ms, 800ms); + + //Go into summary again + env.log("Navigating back into summary."); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_press_button(context, BUTTON_A, 200ms, 100ms); + context.wait_for_all_requests(); + pbf_wait(context, 5000ms); + context.wait_for_all_requests(); + } + else { + env.log("Not shiny."); + } + + //Move left, check next. + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + pbf_press_button(context, BUTTON_X, 0ms, 1000ms); + context.wait_for_all_requests(); + } + + if (!shiny_found) { + env.log("Out of Pokemon to trade and no shiny found. Resetting game."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Out of Pokemon to trade and no shiny found. Resetting game." + ); + + //Reset game + pbf_press_button(context, BUTTON_HOME, 200ms, 2000ms); + reset_game_from_home(env, env.console, context, 3000ms); + context.wait_for_all_requests(); + + stats.resets++; + env.update_stats(); + } + } + + if (GO_HOME_WHEN_DONE) { + pbf_press_button(context, BUTTON_HOME, 200ms, 1000ms); + } + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_AlolanTrade.h b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_AlolanTrade.h index acebc8c3f4..9b24061d3e 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_AlolanTrade.h +++ b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_AlolanTrade.h @@ -1,53 +1,53 @@ -/* LGPE Alolan Trade - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLGPE_AlolanTrade_H -#define PokemonAutomation_PokemonLGPE_AlolanTrade_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -class AlolanTrade_Descriptor : public SingleSwitchProgramDescriptor{ -public: - AlolanTrade_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class AlolanTrade : public SingleSwitchProgramInstance{ -public: - AlolanTrade(); - virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; - -private: - void run_trade(SingleSwitchProgramEnvironment& env, JoyconContext& context); - - SimpleIntegerOption NUM_TRADES; - - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif - - - +/* LGPE Alolan Trade + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLGPE_AlolanTrade_H +#define PokemonAutomation_PokemonLGPE_AlolanTrade_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +class AlolanTrade_Descriptor : public SingleSwitchProgramDescriptor{ +public: + AlolanTrade_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class AlolanTrade : public SingleSwitchProgramInstance{ +public: + AlolanTrade(); + virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; + +private: + void run_trade(SingleSwitchProgramEnvironment& env, JoyconContext& context); + + SimpleIntegerOption NUM_TRADES; + + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_FossilRevival.cpp b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_FossilRevival.cpp index 6769d4daa2..0251229dc2 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_FossilRevival.cpp +++ b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_FossilRevival.cpp @@ -1,310 +1,310 @@ -/* LGPE Fossil Revival - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "Pokemon/Pokemon_Strings.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h" -#include "PokemonLGPE/Programs/PokemonLGPE_GameEntry.h" -#include "PokemonLGPE_FossilRevival.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -FossilRevival_Descriptor::FossilRevival_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLGPE:FossilRevival", - Pokemon::STRING_POKEMON + " LGPE", "Fossil Revival", - "ComputerControl/blob/master/Wiki/Programs/PokemonLGPE/FossilRevival.md", - "Shiny hunt fossil Pokemon by reviving and resetting.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_RightJoycon}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - -struct FossilRevival_Descriptor::Stats : public StatsTracker{ - Stats() - : revives(m_stats["Revives"]) - , resets(m_stats["Resets"]) - , shinies(m_stats["Shinies"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Revives"); - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Shinies"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& revives; - std::atomic& resets; - std::atomic& shinies; - std::atomic& errors; -}; -std::unique_ptr FossilRevival_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -FossilRevival::FossilRevival() - : SLOT( - "Fossil slot:
Position of the fossil in the selection dialog.", - { - {0, "slot0", "Slot 1"}, - {1, "slot1", "Slot 2"}, - {2, "slot2", "Slot 3"}, - }, - LockMode::LOCK_WHILE_RUNNING, - 0 - ) - ,NUM_REVIVALS( - "Number of fossils to revive:", - LockMode::LOCK_WHILE_RUNNING, - 30, 1 - ) - , GO_HOME_WHEN_DONE(false) - , NOTIFICATION_SHINY( - "Shiny Found", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_SHINY, - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(SLOT); - PA_ADD_OPTION(NUM_REVIVALS); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void FossilRevival::run_revives(SingleSwitchProgramEnvironment& env, JoyconContext& context){ - FossilRevival_Descriptor::Stats& stats = env.current_stats(); - //Press A to get to selection - env.log("Starting dialog."); - pbf_press_button(context, BUTTON_A, 100ms, 800ms); - pbf_wait(context, 1000ms); //Wait for scientist to turn and face player - context.wait_for_all_requests(); - pbf_press_button(context, BUTTON_A, 100ms, 500ms); - pbf_press_button(context, BUTTON_A, 100ms, 500ms); - pbf_press_button(context, BUTTON_A, 100ms, 500ms); - pbf_press_button(context, BUTTON_A, 100ms, 500ms); - context.wait_for_all_requests(); - - pbf_wait(context, 500ms); - context.wait_for_all_requests(); - - //Select fossil slot - env.log("Selecting fossil."); - for (uint16_t c = 0; c < (uint16_t)SLOT.current_value(); c++){ - pbf_move_joystick(context, 128, 255, 100ms, 200ms); - } - context.wait_for_all_requests(); - - //Mash A until revival over - BlackScreenOverWatcher revival_over(COLOR_RED); - int ret = run_until( - env.console, context, - [](JoyconContext& context){ - pbf_mash_button(context, BUTTON_A, 15000ms); - }, - {revival_over} - ); - context.wait_for_all_requests(); - if (ret != 0){ - stats.errors++; - env.update_stats(); - env.log("Failed to revive fossil.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to revive fossil.", - env.console - ); - } - else { - env.log("Fossil revived."); - } - - //Now mash B until next black screen (end of summary/tucked pokemon away) - BlackScreenOverWatcher summary_over(COLOR_YELLOW); - int ret2 = run_until( - env.console, context, - [](JoyconContext& context){ - pbf_mash_button(context, BUTTON_B, 15000ms); - }, - {summary_over} - ); - context.wait_for_all_requests(); - if (ret2 != 0){ - stats.errors++; - env.update_stats(); - env.log("Did not detect summary over.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Did not detect summary over.", - env.console - ); - } - else { - env.log("Summary closed/Pokemon tucked away in box/team."); - } - - //Close out come back soon text. - pbf_mash_button(context, BUTTON_B, 1000ms); - context.wait_for_all_requests(); -} - -void FossilRevival::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ - JoyconContext context(scope, env.console.controller()); - assert_16_9_720p_min(env.logger(), env.console); - FossilRevival_Descriptor::Stats& stats = env.current_stats(); - - /* - Settings: - Text speed fast - - is first time dialog different? clear it out first. - selection dialog still appears if only one fossil type - - Setup: - Stand in front of the scientist in cinnebar. - Save the game. - Start the program in-game. - */ - - bool shiny_found = false; - while (!shiny_found) { - //Run revives - for (uint16_t i = 0; i < NUM_REVIVALS; i++) { - env.log("Running trade."); - run_revives(env, context); - - stats.revives++; - env.update_stats(); - } - - env.log("Done reviving. Checking boxes."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Done reviving. Checking boxes." - ); - - //Wait a bit. - pbf_wait(context, 2500ms); - context.wait_for_all_requests(); - - //Open menu, open party, open boxes - env.log("Opening boxes."); - pbf_press_button(context, BUTTON_X, 200ms, 500ms); - pbf_press_button(context, BUTTON_A, 200ms, 1500ms); - pbf_press_button(context, BUTTON_Y, 200ms, 2000ms); - context.wait_for_all_requests(); - - //Sort by order caught - env.log("Sorting by order caught."); - pbf_press_button(context, BUTTON_Y, 200ms, 1000ms); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - context.wait_for_all_requests(); - - //Press left to go to last (most recent) Pokemon - env.log("Opening summary of most recent Pokemon."); - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - context.wait_for_all_requests(); - - //View summary - it takes a moment to load - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_press_button(context, BUTTON_A, 200ms, 100ms); - context.wait_for_all_requests(); - - pbf_wait(context, 5000ms); - context.wait_for_all_requests(); - - //Now check for shinies. Check everything that was traded. - env.log("Checking received Pokemon."); - for (uint16_t i = 0; i < NUM_REVIVALS; i++) { - VideoSnapshot screen = env.console.video().snapshot(); - ShinySymbolDetector shiny_checker(COLOR_YELLOW); - bool check = shiny_checker.read(env.console.logger(), screen); - - if (check) { - env.log("Shiny detected!"); - stats.shinies++; - env.update_stats(); - send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", screen, true); - shiny_found = true; - - //Back out to menu and favorite the shiny. - env.log("Favoriting shiny."); - pbf_press_button(context, BUTTON_B, 200ms, 5000ms); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_move_joystick(context, 128, 0, 100ms, 100ms); - pbf_move_joystick(context, 128, 0, 100ms, 100ms); - pbf_move_joystick(context, 128, 0, 100ms, 200ms); - pbf_press_button(context, BUTTON_A, 200ms, 800ms); - pbf_press_button(context, BUTTON_A, 200ms, 800ms); - pbf_press_button(context, BUTTON_B, 200ms, 800ms); - - //Go into summary again - env.log("Navigating back into summary."); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_press_button(context, BUTTON_A, 200ms, 100ms); - context.wait_for_all_requests(); - pbf_wait(context, 5000ms); - context.wait_for_all_requests(); - } - else { - env.log("Not shiny."); - } - - //Move left, check next. - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - pbf_press_button(context, BUTTON_X, 0ms, 1000ms); - context.wait_for_all_requests(); - } - - if (!shiny_found) { - env.log("Out of Pokemon to check and no shiny found. Resetting game."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Out of Pokemon to check and no shiny found. Resetting game." - ); - - //Reset game - pbf_press_button(context, BUTTON_HOME, 200ms, 2000ms); - reset_game_from_home(env, env.console, context, 3000ms); - context.wait_for_all_requests(); - - stats.resets++; - env.update_stats(); - } - } - - if (GO_HOME_WHEN_DONE) { - pbf_press_button(context, BUTTON_HOME, 200ms, 1000ms); - } - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - -} -} -} +/* LGPE Fossil Revival + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "Pokemon/Pokemon_Strings.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h" +#include "PokemonLGPE/Programs/PokemonLGPE_GameEntry.h" +#include "PokemonLGPE_FossilRevival.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +FossilRevival_Descriptor::FossilRevival_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLGPE:FossilRevival", + Pokemon::STRING_POKEMON + " LGPE", "Fossil Revival", + "ComputerControl/blob/master/Wiki/Programs/PokemonLGPE/FossilRevival.md", + "Shiny hunt fossil Pokemon by reviving and resetting.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_RightJoycon}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + +struct FossilRevival_Descriptor::Stats : public StatsTracker{ + Stats() + : revives(m_stats["Revives"]) + , resets(m_stats["Resets"]) + , shinies(m_stats["Shinies"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Revives"); + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Shinies"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& revives; + std::atomic& resets; + std::atomic& shinies; + std::atomic& errors; +}; +std::unique_ptr FossilRevival_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +FossilRevival::FossilRevival() + : SLOT( + "Fossil slot:
Position of the fossil in the selection dialog.", + { + {0, "slot0", "Slot 1"}, + {1, "slot1", "Slot 2"}, + {2, "slot2", "Slot 3"}, + }, + LockMode::LOCK_WHILE_RUNNING, + 0 + ) + ,NUM_REVIVALS( + "Number of fossils to revive:", + LockMode::LOCK_WHILE_RUNNING, + 30, 1 + ) + , GO_HOME_WHEN_DONE(false) + , NOTIFICATION_SHINY( + "Shiny Found", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_SHINY, + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(SLOT); + PA_ADD_OPTION(NUM_REVIVALS); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void FossilRevival::run_revives(SingleSwitchProgramEnvironment& env, JoyconContext& context){ + FossilRevival_Descriptor::Stats& stats = env.current_stats(); + //Press A to get to selection + env.log("Starting dialog."); + pbf_press_button(context, BUTTON_A, 100ms, 800ms); + pbf_wait(context, 1000ms); //Wait for scientist to turn and face player + context.wait_for_all_requests(); + pbf_press_button(context, BUTTON_A, 100ms, 500ms); + pbf_press_button(context, BUTTON_A, 100ms, 500ms); + pbf_press_button(context, BUTTON_A, 100ms, 500ms); + pbf_press_button(context, BUTTON_A, 100ms, 500ms); + context.wait_for_all_requests(); + + pbf_wait(context, 500ms); + context.wait_for_all_requests(); + + //Select fossil slot + env.log("Selecting fossil."); + for (uint16_t c = 0; c < (uint16_t)SLOT.current_value(); c++){ + pbf_move_joystick(context, 128, 255, 100ms, 200ms); + } + context.wait_for_all_requests(); + + //Mash A until revival over + BlackScreenOverWatcher revival_over(COLOR_RED); + int ret = run_until( + env.console, context, + [](JoyconContext& context){ + pbf_mash_button(context, BUTTON_A, 15000ms); + }, + {revival_over} + ); + context.wait_for_all_requests(); + if (ret != 0){ + stats.errors++; + env.update_stats(); + env.log("Failed to revive fossil.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to revive fossil.", + env.console + ); + } + else { + env.log("Fossil revived."); + } + + //Now mash B until next black screen (end of summary/tucked pokemon away) + BlackScreenOverWatcher summary_over(COLOR_YELLOW); + int ret2 = run_until( + env.console, context, + [](JoyconContext& context){ + pbf_mash_button(context, BUTTON_B, 15000ms); + }, + {summary_over} + ); + context.wait_for_all_requests(); + if (ret2 != 0){ + stats.errors++; + env.update_stats(); + env.log("Did not detect summary over.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Did not detect summary over.", + env.console + ); + } + else { + env.log("Summary closed/Pokemon tucked away in box/team."); + } + + //Close out come back soon text. + pbf_mash_button(context, BUTTON_B, 1000ms); + context.wait_for_all_requests(); +} + +void FossilRevival::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ + JoyconContext context(scope, env.console.controller()); + assert_16_9_720p_min(env.logger(), env.console); + FossilRevival_Descriptor::Stats& stats = env.current_stats(); + + /* + Settings: + Text speed fast + + is first time dialog different? clear it out first. + selection dialog still appears if only one fossil type + + Setup: + Stand in front of the scientist in cinnebar. + Save the game. + Start the program in-game. + */ + + bool shiny_found = false; + while (!shiny_found) { + //Run revives + for (uint16_t i = 0; i < NUM_REVIVALS; i++) { + env.log("Running trade."); + run_revives(env, context); + + stats.revives++; + env.update_stats(); + } + + env.log("Done reviving. Checking boxes."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Done reviving. Checking boxes." + ); + + //Wait a bit. + pbf_wait(context, 2500ms); + context.wait_for_all_requests(); + + //Open menu, open party, open boxes + env.log("Opening boxes."); + pbf_press_button(context, BUTTON_X, 200ms, 500ms); + pbf_press_button(context, BUTTON_A, 200ms, 1500ms); + pbf_press_button(context, BUTTON_Y, 200ms, 2000ms); + context.wait_for_all_requests(); + + //Sort by order caught + env.log("Sorting by order caught."); + pbf_press_button(context, BUTTON_Y, 200ms, 1000ms); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + context.wait_for_all_requests(); + + //Press left to go to last (most recent) Pokemon + env.log("Opening summary of most recent Pokemon."); + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + context.wait_for_all_requests(); + + //View summary - it takes a moment to load + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_press_button(context, BUTTON_A, 200ms, 100ms); + context.wait_for_all_requests(); + + pbf_wait(context, 5000ms); + context.wait_for_all_requests(); + + //Now check for shinies. Check everything that was traded. + env.log("Checking received Pokemon."); + for (uint16_t i = 0; i < NUM_REVIVALS; i++) { + VideoSnapshot screen = env.console.video().snapshot(); + ShinySymbolDetector shiny_checker(COLOR_YELLOW); + bool check = shiny_checker.read(env.console.logger(), screen); + + if (check) { + env.log("Shiny detected!"); + stats.shinies++; + env.update_stats(); + send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", screen, true); + shiny_found = true; + + //Back out to menu and favorite the shiny. + env.log("Favoriting shiny."); + pbf_press_button(context, BUTTON_B, 200ms, 5000ms); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_move_joystick(context, 128, 0, 100ms, 100ms); + pbf_move_joystick(context, 128, 0, 100ms, 100ms); + pbf_move_joystick(context, 128, 0, 100ms, 200ms); + pbf_press_button(context, BUTTON_A, 200ms, 800ms); + pbf_press_button(context, BUTTON_A, 200ms, 800ms); + pbf_press_button(context, BUTTON_B, 200ms, 800ms); + + //Go into summary again + env.log("Navigating back into summary."); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_press_button(context, BUTTON_A, 200ms, 100ms); + context.wait_for_all_requests(); + pbf_wait(context, 5000ms); + context.wait_for_all_requests(); + } + else { + env.log("Not shiny."); + } + + //Move left, check next. + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + pbf_press_button(context, BUTTON_X, 0ms, 1000ms); + context.wait_for_all_requests(); + } + + if (!shiny_found) { + env.log("Out of Pokemon to check and no shiny found. Resetting game."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Out of Pokemon to check and no shiny found. Resetting game." + ); + + //Reset game + pbf_press_button(context, BUTTON_HOME, 200ms, 2000ms); + reset_game_from_home(env, env.console, context, 3000ms); + context.wait_for_all_requests(); + + stats.resets++; + env.update_stats(); + } + } + + if (GO_HOME_WHEN_DONE) { + pbf_press_button(context, BUTTON_HOME, 200ms, 1000ms); + } + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_FossilRevival.h b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_FossilRevival.h index 101ce30935..8e9d6570cd 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_FossilRevival.h +++ b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_FossilRevival.h @@ -1,55 +1,55 @@ -/* LGPE Fossil Revival - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLGPE_FossilRevival_H -#define PokemonAutomation_PokemonLGPE_FossilRevival_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -class FossilRevival_Descriptor : public SingleSwitchProgramDescriptor{ -public: - FossilRevival_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class FossilRevival : public SingleSwitchProgramInstance{ -public: - FossilRevival(); - virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; - -private: - void run_revives(SingleSwitchProgramEnvironment& env, JoyconContext& context); - - IntegerEnumDropdownOption SLOT; - SimpleIntegerOption NUM_REVIVALS; - - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif - - - +/* LGPE Fossil Revival + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLGPE_FossilRevival_H +#define PokemonAutomation_PokemonLGPE_FossilRevival_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +class FossilRevival_Descriptor : public SingleSwitchProgramDescriptor{ +public: + FossilRevival_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class FossilRevival : public SingleSwitchProgramInstance{ +public: + FossilRevival(); + virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; + +private: + void run_revives(SingleSwitchProgramEnvironment& env, JoyconContext& context); + + IntegerEnumDropdownOption SLOT; + SimpleIntegerOption NUM_REVIVALS; + + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_GiftReset.cpp b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_GiftReset.cpp index 8f91fe1a26..581754e8a9 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_GiftReset.cpp +++ b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_GiftReset.cpp @@ -1,205 +1,205 @@ -/* LGPE Gift Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "Pokemon/Pokemon_Strings.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h" -#include "PokemonLGPE/Programs/PokemonLGPE_GameEntry.h" -#include "PokemonLGPE_GiftReset.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -GiftReset_Descriptor::GiftReset_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLGPE:GiftReset", - Pokemon::STRING_POKEMON + " LGPE", "Gift Reset", - "ComputerControl/blob/master/Wiki/Programs/PokemonLGPE/GiftReset.md", - "Shiny hunt gift Pokemon by resetting the game.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_RightJoycon}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - -struct GiftReset_Descriptor::Stats : public StatsTracker{ - Stats() - : resets(m_stats["Resets"]) - , shinies(m_stats["Shinies"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Shinies"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& resets; - std::atomic& shinies; - std::atomic& errors; -}; -std::unique_ptr GiftReset_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -GiftReset::GiftReset() - : EXTRA_DIALOG( - "Persian/Arcanine:
Check this if the gift Pokemon is Persian or Arcanine.", - LockMode::UNLOCK_WHILE_RUNNING, false - ) - , GO_HOME_WHEN_DONE(false) - , NOTIFICATION_SHINY( - "Shiny Found", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_SHINY, - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(EXTRA_DIALOG); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void GiftReset::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ - JoyconContext context(scope, env.console.controller()); - assert_16_9_720p_min(env.logger(), env.console); - GiftReset_Descriptor::Stats& stats = env.current_stats(); - - /* - Setup: - Stand in front of trade NPC. - Start the program in-game. - - Must have 500yen for magikarp. - Gift Pokemon: https://www.serebii.net/letsgopikachueevee/gift.shtml - Tested with Magikarp on a new save. Should work with most of the others. - Can always add a dropdown with target if it doesn't. - Fossils will be handled in a different program. - */ - - bool shiny_found = false; - while (!shiny_found) { - //Purchase Magikarp - BlackScreenOverWatcher gift_obtained(COLOR_RED); - int ret = run_until( - env.console, context, - [](JoyconContext& context){ - pbf_mash_button(context, BUTTON_A, 20000ms); - }, - {gift_obtained} - ); - context.wait_for_all_requests(); - if (ret != 0){ - stats.errors++; - env.update_stats(); - env.log("Failed to receive gift Pokemon.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to receive gift Pokemon.", - env.console - ); - } - else { - env.log("Received gift Pokemon."); - } - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Received gift Pokemon." - ); - - if (EXTRA_DIALOG){ - env.log("Persian/Arcanine selected. Mashing B to exit dialog."); - pbf_mash_button(context, BUTTON_B, 4100ms); - context.wait_for_all_requests(); - } - - //Wait a bit. - pbf_wait(context, 2500ms); - context.wait_for_all_requests(); - - //Open menu, open party, open boxes - env.log("Opening boxes."); - pbf_press_button(context, BUTTON_X, 200ms, 500ms); - pbf_press_button(context, BUTTON_A, 200ms, 1500ms); - pbf_press_button(context, BUTTON_Y, 200ms, 2000ms); - context.wait_for_all_requests(); - - //Sort by order caught - env.log("Sorting by order caught."); - pbf_press_button(context, BUTTON_Y, 200ms, 1000ms); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - context.wait_for_all_requests(); - - //Press left to go to last (most recent) Pokemon - env.log("Opening summary of most recent Pokemon."); - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - context.wait_for_all_requests(); - - //View summary - it takes a moment to load - env.log("Viewing summary."); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_press_button(context, BUTTON_A, 200ms, 100ms); - context.wait_for_all_requests(); - - pbf_wait(context, 5000ms); - context.wait_for_all_requests(); - - //Now check for shinies. Check everything that was traded. - VideoSnapshot screen = env.console.video().snapshot(); - ShinySymbolDetector shiny_checker(COLOR_YELLOW); - bool check = shiny_checker.read(env.console.logger(), screen); - - if (check) { - env.log("Shiny detected!"); - stats.shinies++; - env.update_stats(); - send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", screen, true); - shiny_found = true; - } - else { - env.log("Not shiny. Resetting game."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Not shiny. Resetting game." - ); - - //Reset game - pbf_press_button(context, BUTTON_HOME, 200ms, 2000ms); - reset_game_from_home(env, env.console, context, 3000ms); - context.wait_for_all_requests(); - - stats.resets++; - env.update_stats(); - } - } - - if (GO_HOME_WHEN_DONE) { - pbf_press_button(context, BUTTON_HOME, 200ms, 1000ms); - } - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - -} -} -} +/* LGPE Gift Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "Pokemon/Pokemon_Strings.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h" +#include "PokemonLGPE/Programs/PokemonLGPE_GameEntry.h" +#include "PokemonLGPE_GiftReset.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +GiftReset_Descriptor::GiftReset_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLGPE:GiftReset", + Pokemon::STRING_POKEMON + " LGPE", "Gift Reset", + "ComputerControl/blob/master/Wiki/Programs/PokemonLGPE/GiftReset.md", + "Shiny hunt gift Pokemon by resetting the game.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_RightJoycon}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + +struct GiftReset_Descriptor::Stats : public StatsTracker{ + Stats() + : resets(m_stats["Resets"]) + , shinies(m_stats["Shinies"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Shinies"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& resets; + std::atomic& shinies; + std::atomic& errors; +}; +std::unique_ptr GiftReset_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +GiftReset::GiftReset() + : EXTRA_DIALOG( + "Persian/Arcanine:
Check this if the gift Pokemon is Persian or Arcanine.", + LockMode::UNLOCK_WHILE_RUNNING, false + ) + , GO_HOME_WHEN_DONE(false) + , NOTIFICATION_SHINY( + "Shiny Found", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_SHINY, + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(EXTRA_DIALOG); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void GiftReset::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ + JoyconContext context(scope, env.console.controller()); + assert_16_9_720p_min(env.logger(), env.console); + GiftReset_Descriptor::Stats& stats = env.current_stats(); + + /* + Setup: + Stand in front of trade NPC. + Start the program in-game. + + Must have 500yen for magikarp. + Gift Pokemon: https://www.serebii.net/letsgopikachueevee/gift.shtml + Tested with Magikarp on a new save. Should work with most of the others. + Can always add a dropdown with target if it doesn't. + Fossils will be handled in a different program. + */ + + bool shiny_found = false; + while (!shiny_found) { + //Purchase Magikarp + BlackScreenOverWatcher gift_obtained(COLOR_RED); + int ret = run_until( + env.console, context, + [](JoyconContext& context){ + pbf_mash_button(context, BUTTON_A, 20000ms); + }, + {gift_obtained} + ); + context.wait_for_all_requests(); + if (ret != 0){ + stats.errors++; + env.update_stats(); + env.log("Failed to receive gift Pokemon.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to receive gift Pokemon.", + env.console + ); + } + else { + env.log("Received gift Pokemon."); + } + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Received gift Pokemon." + ); + + if (EXTRA_DIALOG){ + env.log("Persian/Arcanine selected. Mashing B to exit dialog."); + pbf_mash_button(context, BUTTON_B, 4100ms); + context.wait_for_all_requests(); + } + + //Wait a bit. + pbf_wait(context, 2500ms); + context.wait_for_all_requests(); + + //Open menu, open party, open boxes + env.log("Opening boxes."); + pbf_press_button(context, BUTTON_X, 200ms, 500ms); + pbf_press_button(context, BUTTON_A, 200ms, 1500ms); + pbf_press_button(context, BUTTON_Y, 200ms, 2000ms); + context.wait_for_all_requests(); + + //Sort by order caught + env.log("Sorting by order caught."); + pbf_press_button(context, BUTTON_Y, 200ms, 1000ms); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + context.wait_for_all_requests(); + + //Press left to go to last (most recent) Pokemon + env.log("Opening summary of most recent Pokemon."); + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + context.wait_for_all_requests(); + + //View summary - it takes a moment to load + env.log("Viewing summary."); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_press_button(context, BUTTON_A, 200ms, 100ms); + context.wait_for_all_requests(); + + pbf_wait(context, 5000ms); + context.wait_for_all_requests(); + + //Now check for shinies. Check everything that was traded. + VideoSnapshot screen = env.console.video().snapshot(); + ShinySymbolDetector shiny_checker(COLOR_YELLOW); + bool check = shiny_checker.read(env.console.logger(), screen); + + if (check) { + env.log("Shiny detected!"); + stats.shinies++; + env.update_stats(); + send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", screen, true); + shiny_found = true; + } + else { + env.log("Not shiny. Resetting game."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Not shiny. Resetting game." + ); + + //Reset game + pbf_press_button(context, BUTTON_HOME, 200ms, 2000ms); + reset_game_from_home(env, env.console, context, 3000ms); + context.wait_for_all_requests(); + + stats.resets++; + env.update_stats(); + } + } + + if (GO_HOME_WHEN_DONE) { + pbf_press_button(context, BUTTON_HOME, 200ms, 1000ms); + } + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_GiftReset.h b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_GiftReset.h index c78b69b2f7..fa86dae3a9 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_GiftReset.h +++ b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_GiftReset.h @@ -1,50 +1,50 @@ -/* LGPE Gift Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLGPE_GiftReset_H -#define PokemonAutomation_PokemonLGPE_GiftReset_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -class GiftReset_Descriptor : public SingleSwitchProgramDescriptor{ -public: - GiftReset_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class GiftReset : public SingleSwitchProgramInstance{ -public: - GiftReset(); - virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; - -private: - BooleanCheckBoxOption EXTRA_DIALOG; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif - - - +/* LGPE Gift Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLGPE_GiftReset_H +#define PokemonAutomation_PokemonLGPE_GiftReset_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +class GiftReset_Descriptor : public SingleSwitchProgramDescriptor{ +public: + GiftReset_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class GiftReset : public SingleSwitchProgramInstance{ +public: + GiftReset(); + virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; + +private: + BooleanCheckBoxOption EXTRA_DIALOG; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_LegendaryReset.cpp b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_LegendaryReset.cpp index 8e95208d84..9bb6624721 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_LegendaryReset.cpp +++ b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_LegendaryReset.cpp @@ -1,285 +1,285 @@ -/* LGPE Legendary Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "Pokemon/Pokemon_Strings.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "PokemonLGPE/Inference/Battles/PokemonLGPE_BattleArrowDetector.h" -#include "PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.h" -#include "PokemonLGPE/Programs/PokemonLGPE_GameEntry.h" -#include "PokemonLGPE_LegendaryReset.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -LegendaryReset_Descriptor::LegendaryReset_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLGPE:LegendaryReset", - Pokemon::STRING_POKEMON + " LGPE", "Legendary Reset", - "ComputerControl/blob/master/Wiki/Programs/PokemonLGPE/LegendaryReset.md", - "Shiny hunt Legendary Pokemon by resetting the game.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_RightJoycon}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - -struct LegendaryReset_Descriptor::Stats : public StatsTracker{ - Stats() - : resets(m_stats["Resets"]) - , shinies(m_stats["Shinies"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Shinies"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& resets; - std::atomic& shinies; - std::atomic& errors; -}; -std::unique_ptr LegendaryReset_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -LegendaryReset::LegendaryReset() - : TARGET( - "Target:
", - { - {Target::mewtwo, "mewtwo", "Mewtwo, Articuno, Zapdos, Moltres"}, - {Target::snorlax, "snorlax", "Snorlax"}, - {Target::electrode, "electrode", "Electrode"}, - //{Target::snorlax2, "snorlax2", "Snorlax (w/Fuji)"}, - }, - LockMode::LOCK_WHILE_RUNNING, - Target::mewtwo - ) - , GO_HOME_WHEN_DONE(true) - , NOTIFICATION_SHINY( - "Shiny Found", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_SHINY, - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(TARGET); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(NOTIFICATIONS); -} - -bool LegendaryReset::run_encounter(SingleSwitchProgramEnvironment& env, JoyconContext& context){ - LegendaryReset_Descriptor::Stats& stats = env.current_stats(); - float shiny_coefficient = 1.0; - ShinySoundDetector shiny_detector(env.logger(), [&](float error_coefficient) -> bool{ - shiny_coefficient = error_coefficient; - return true; - }); - BattleArrowWatcher battle_started(COLOR_RED, {0.546, 0.863, 0.045, 0.068}); - - env.log("Starting battle."); - switch (TARGET) { - case Target::mewtwo: - pbf_mash_button(context, BUTTON_A, 3000ms); - context.wait_for_all_requests(); - pbf_press_button(context, BUTTON_PLUS, 500ms, 100ms); - break; - case Target::snorlax: - pbf_mash_button(context, BUTTON_A, 5000ms); - context.wait_for_all_requests(); - pbf_mash_button(context, BUTTON_B, 10000ms); - break; - case Target::electrode: - pbf_press_button(context, BUTTON_A, 200ms, 200ms); - pbf_mash_button(context, BUTTON_B, 5000ms); - break; - } - context.wait_for_all_requests(); - - int res = run_until( - env.console, context, - [&](JoyconContext& context) { - int ret = wait_until( - env.console, context, - std::chrono::seconds(90), - {{battle_started}} - ); - if (ret == 0) { - env.log("HP boxes detected."); - } else { - stats.errors++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "run_battle(): Did not detect battle start.", - env.console - ); - } - context.wait_for_all_requests(); - }, - {{shiny_detector}} - ); - shiny_detector.throw_if_no_sound(); - if (res == 0){ - env.log("Shiny detected!"); - return true; - } - env.log("Shiny not found."); - - return false; -} - -void LegendaryReset::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ - JoyconContext context(scope, env.console.controller()); - assert_16_9_720p_min(env.logger(), env.console); - LegendaryReset_Descriptor::Stats& stats = env.current_stats(); - - /* - Setup: - Stand in front of encounter. (And save) - Start the program in game. - Your lead must not be shiny. - - Settings: - Text Speed fast - Skip cutscene On - Skip move animation On - - Mewtwo, Articuno, Zapdos, Moltres, Snorlax, Electrode(?) - Don't do it on the first Snorlax, otherwise have to sit through fuji tutorial - */ - - size_t consecutive_failures = 0; - - while (true) { - env.update_stats(); - - if (consecutive_failures >= 3){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed 3 times in the row.", - env.console - ); - } - - try{ - bool encounter_battle = run_encounter(env, context); - if (encounter_battle) { - stats.shinies++; - env.update_stats(); - send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", env.console.video().snapshot(), true); - break; - } - - env.log("No shiny found. Resetting game."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "No shiny found. Resetting game." - ); - context.wait_for_all_requests(); - consecutive_failures = 0; - }catch (OperationFailedException& e){ - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - consecutive_failures++; - } - - //Reset game - pbf_press_button(context, BUTTON_HOME, 200ms, 2000ms); - reset_game_from_home(env, env.console, context, 3000ms); - context.wait_for_all_requests(); - - stats.resets++; - } - //Shiny found, complete the battle - WallClock start = current_time(); - BattleArrowWatcher catching_started(COLOR_RED, {0.005, 0.662, 0.049, 0.069}); - int res = run_until( - env.console, context, - [&](JoyconContext& context) { - while(true){ - if (current_time() - start > std::chrono::minutes(5)){ - stats.errors++; - env.update_stats(); - env.log("Timed out during battle after 5 minutes.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Timed out during battle after 5 minutes.", - env.console - ); - } - BattleArrowWatcher battle_menu(COLOR_YELLOW, {0.546, 0.863, 0.045, 0.068}); - context.wait_for_all_requests(); - - int ret = wait_until( - env.console, context, - std::chrono::seconds(30), - { battle_menu } - ); - switch (ret){ - case 0: - env.log("Detected battle menu. Mashing A to attack."); - pbf_mash_button(context, BUTTON_A, 3000ms); - context.wait_for_all_requests(); - break; - default: - stats.errors++; - env.update_stats(); - env.log("Timed out during battle. Stuck, crashed, or took more than 30 seconds for a turn.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Timed out during battle. Stuck, crashed, or took more than 30 seconds for a turn.", - env.console - ); - } - } - }, - {{catching_started}} - ); - switch (res){ - case 0: - env.log("Catching menu detected."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Catching menu detected." - ); - break; - default: - stats.errors++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to detect catching menu.", - env.console - ); - break; - } - - if (GO_HOME_WHEN_DONE) { - pbf_press_button(context, BUTTON_HOME, 200ms, 1000ms); - } - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - -} -} -} +/* LGPE Legendary Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "Pokemon/Pokemon_Strings.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "PokemonLGPE/Inference/Battles/PokemonLGPE_BattleArrowDetector.h" +#include "PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.h" +#include "PokemonLGPE/Programs/PokemonLGPE_GameEntry.h" +#include "PokemonLGPE_LegendaryReset.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +LegendaryReset_Descriptor::LegendaryReset_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLGPE:LegendaryReset", + Pokemon::STRING_POKEMON + " LGPE", "Legendary Reset", + "ComputerControl/blob/master/Wiki/Programs/PokemonLGPE/LegendaryReset.md", + "Shiny hunt Legendary Pokemon by resetting the game.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_RightJoycon}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + +struct LegendaryReset_Descriptor::Stats : public StatsTracker{ + Stats() + : resets(m_stats["Resets"]) + , shinies(m_stats["Shinies"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Shinies"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& resets; + std::atomic& shinies; + std::atomic& errors; +}; +std::unique_ptr LegendaryReset_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +LegendaryReset::LegendaryReset() + : TARGET( + "Target:
", + { + {Target::mewtwo, "mewtwo", "Mewtwo, Articuno, Zapdos, Moltres"}, + {Target::snorlax, "snorlax", "Snorlax"}, + {Target::electrode, "electrode", "Electrode"}, + //{Target::snorlax2, "snorlax2", "Snorlax (w/Fuji)"}, + }, + LockMode::LOCK_WHILE_RUNNING, + Target::mewtwo + ) + , GO_HOME_WHEN_DONE(true) + , NOTIFICATION_SHINY( + "Shiny Found", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_SHINY, + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(TARGET); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); +} + +bool LegendaryReset::run_encounter(SingleSwitchProgramEnvironment& env, JoyconContext& context){ + LegendaryReset_Descriptor::Stats& stats = env.current_stats(); + float shiny_coefficient = 1.0; + ShinySoundDetector shiny_detector(env.logger(), [&](float error_coefficient) -> bool{ + shiny_coefficient = error_coefficient; + return true; + }); + BattleArrowWatcher battle_started(COLOR_RED, {0.546, 0.863, 0.045, 0.068}); + + env.log("Starting battle."); + switch (TARGET) { + case Target::mewtwo: + pbf_mash_button(context, BUTTON_A, 3000ms); + context.wait_for_all_requests(); + pbf_press_button(context, BUTTON_PLUS, 500ms, 100ms); + break; + case Target::snorlax: + pbf_mash_button(context, BUTTON_A, 5000ms); + context.wait_for_all_requests(); + pbf_mash_button(context, BUTTON_B, 10000ms); + break; + case Target::electrode: + pbf_press_button(context, BUTTON_A, 200ms, 200ms); + pbf_mash_button(context, BUTTON_B, 5000ms); + break; + } + context.wait_for_all_requests(); + + int res = run_until( + env.console, context, + [&](JoyconContext& context) { + int ret = wait_until( + env.console, context, + std::chrono::seconds(90), + {{battle_started}} + ); + if (ret == 0) { + env.log("HP boxes detected."); + } else { + stats.errors++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "run_battle(): Did not detect battle start.", + env.console + ); + } + context.wait_for_all_requests(); + }, + {{shiny_detector}} + ); + shiny_detector.throw_if_no_sound(); + if (res == 0){ + env.log("Shiny detected!"); + return true; + } + env.log("Shiny not found."); + + return false; +} + +void LegendaryReset::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ + JoyconContext context(scope, env.console.controller()); + assert_16_9_720p_min(env.logger(), env.console); + LegendaryReset_Descriptor::Stats& stats = env.current_stats(); + + /* + Setup: + Stand in front of encounter. (And save) + Start the program in game. + Your lead must not be shiny. + + Settings: + Text Speed fast + Skip cutscene On + Skip move animation On + + Mewtwo, Articuno, Zapdos, Moltres, Snorlax, Electrode(?) + Don't do it on the first Snorlax, otherwise have to sit through fuji tutorial + */ + + size_t consecutive_failures = 0; + + while (true) { + env.update_stats(); + + if (consecutive_failures >= 3){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed 3 times in the row.", + env.console + ); + } + + try{ + bool encounter_battle = run_encounter(env, context); + if (encounter_battle) { + stats.shinies++; + env.update_stats(); + send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", env.console.video().snapshot(), true); + break; + } + + env.log("No shiny found. Resetting game."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "No shiny found. Resetting game." + ); + context.wait_for_all_requests(); + consecutive_failures = 0; + }catch (OperationFailedException& e){ + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + consecutive_failures++; + } + + //Reset game + pbf_press_button(context, BUTTON_HOME, 200ms, 2000ms); + reset_game_from_home(env, env.console, context, 3000ms); + context.wait_for_all_requests(); + + stats.resets++; + } + //Shiny found, complete the battle + WallClock start = current_time(); + BattleArrowWatcher catching_started(COLOR_RED, {0.005, 0.662, 0.049, 0.069}); + int res = run_until( + env.console, context, + [&](JoyconContext& context) { + while(true){ + if (current_time() - start > std::chrono::minutes(5)){ + stats.errors++; + env.update_stats(); + env.log("Timed out during battle after 5 minutes.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Timed out during battle after 5 minutes.", + env.console + ); + } + BattleArrowWatcher battle_menu(COLOR_YELLOW, {0.546, 0.863, 0.045, 0.068}); + context.wait_for_all_requests(); + + int ret = wait_until( + env.console, context, + std::chrono::seconds(30), + { battle_menu } + ); + switch (ret){ + case 0: + env.log("Detected battle menu. Mashing A to attack."); + pbf_mash_button(context, BUTTON_A, 3000ms); + context.wait_for_all_requests(); + break; + default: + stats.errors++; + env.update_stats(); + env.log("Timed out during battle. Stuck, crashed, or took more than 30 seconds for a turn.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Timed out during battle. Stuck, crashed, or took more than 30 seconds for a turn.", + env.console + ); + } + } + }, + {{catching_started}} + ); + switch (res){ + case 0: + env.log("Catching menu detected."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Catching menu detected." + ); + break; + default: + stats.errors++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to detect catching menu.", + env.console + ); + break; + } + + if (GO_HOME_WHEN_DONE) { + pbf_press_button(context, BUTTON_HOME, 200ms, 1000ms); + } + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_LegendaryReset.h b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_LegendaryReset.h index 69c0250b78..511a2dca9c 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_LegendaryReset.h +++ b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_LegendaryReset.h @@ -1,59 +1,59 @@ -/* LGPE Legendary Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLGPE_LegendaryReset_H -#define PokemonAutomation_PokemonLGPE_LegendaryReset_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -class LegendaryReset_Descriptor : public SingleSwitchProgramDescriptor{ -public: - LegendaryReset_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class LegendaryReset : public SingleSwitchProgramInstance{ -public: - LegendaryReset(); - virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; - -private: - bool run_encounter(SingleSwitchProgramEnvironment& env, JoyconContext& context); - - enum class Target{ - mewtwo, - snorlax, - electrode, - //snorlax2, - }; - EnumDropdownOption TARGET; - - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif - - - +/* LGPE Legendary Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLGPE_LegendaryReset_H +#define PokemonAutomation_PokemonLGPE_LegendaryReset_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +class LegendaryReset_Descriptor : public SingleSwitchProgramDescriptor{ +public: + LegendaryReset_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class LegendaryReset : public SingleSwitchProgramInstance{ +public: + LegendaryReset(); + virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; + +private: + bool run_encounter(SingleSwitchProgramEnvironment& env, JoyconContext& context); + + enum class Target{ + mewtwo, + snorlax, + electrode, + //snorlax2, + }; + EnumDropdownOption TARGET; + + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/TestPrograms/PokemonLGPE_SoundListener.cpp b/SerialPrograms/Source/PokemonLGPE/Programs/TestPrograms/PokemonLGPE_SoundListener.cpp index f47c2e6c48..d2c4e31e2c 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/TestPrograms/PokemonLGPE_SoundListener.cpp +++ b/SerialPrograms/Source/PokemonLGPE/Programs/TestPrograms/PokemonLGPE_SoundListener.cpp @@ -1,100 +1,100 @@ -/* Sound Listener - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/AlignedVector.tpp" -#include "CommonFramework/AudioPipeline/AudioFeed.h" -#include "CommonFramework/AudioPipeline/AudioTemplate.h" -#include "CommonTools/Audio/AudioTemplateCache.h" -#include "CommonTools/Audio/SpectrogramMatcher.h" -#include "CommonTools/Async/InferenceSession.h" -#include "Pokemon/Pokemon_Strings.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.h" -#include "PokemonLGPE_SoundListener.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - using namespace Pokemon; - - -SoundListener_Descriptor::SoundListener_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLGPE:SoundListener", - STRING_POKEMON + " LGPE", "Sound Listener", - "", - "Test sound detectors listening to audio stream.", - FeedbackType::REQUIRED, AllowCommandsWhenRunning::ENABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_RightJoycon}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - -SoundListener::SoundListener() - : SOUND_TYPE("Which Sound to Detect", - { - {SoundType::SHINY, "shiny", "Shiny Sound"}, - }, - LockMode::LOCK_WHILE_RUNNING, - SoundType::SHINY - ) - , STOP_ON_DETECTED_SOUND( - "Stop on the detected sound
Stop program when the sound is detected.", - LockMode::LOCK_WHILE_RUNNING, - false - ) -{ - PA_ADD_OPTION(SOUND_TYPE); - PA_ADD_OPTION(STOP_ON_DETECTED_SOUND); -} - -void SoundListener::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ - JoyconContext context(scope, env.console.controller()); - - std::cout << "Running audio test program." << std::endl; - - std::shared_ptr detector; - auto action = [&](float error_coefficient) -> bool{ - // This lambda function will be called when the sound is detected. - // Its return will determine whether to stop the program: - return STOP_ON_DETECTED_SOUND; - }; - - SoundType type = SOUND_TYPE; - switch (type){ - case SoundType::SHINY: - detector = std::make_shared(env.console, action); - break; - default: - throw InternalProgramError( - &env.logger(), PA_CURRENT_FUNCTION, - "No such sound detector as sound type " + std::to_string((size_t)type) - ); - return; - } - - InferenceSession session( - context, env.console, - {{*detector, std::chrono::milliseconds(20)}} - ); - context.wait_until_cancel(); - - std::cout << "Audio test program Sound listener finished." << std::endl; -} - - - -} -} -} +/* Sound Listener + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/AlignedVector.tpp" +#include "CommonFramework/AudioPipeline/AudioFeed.h" +#include "CommonFramework/AudioPipeline/AudioTemplate.h" +#include "CommonTools/Audio/AudioTemplateCache.h" +#include "CommonTools/Audio/SpectrogramMatcher.h" +#include "CommonTools/Async/InferenceSession.h" +#include "Pokemon/Pokemon_Strings.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.h" +#include "PokemonLGPE_SoundListener.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + using namespace Pokemon; + + +SoundListener_Descriptor::SoundListener_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLGPE:SoundListener", + STRING_POKEMON + " LGPE", "Sound Listener", + "", + "Test sound detectors listening to audio stream.", + FeedbackType::REQUIRED, AllowCommandsWhenRunning::ENABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_RightJoycon}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + +SoundListener::SoundListener() + : SOUND_TYPE("Which Sound to Detect", + { + {SoundType::SHINY, "shiny", "Shiny Sound"}, + }, + LockMode::LOCK_WHILE_RUNNING, + SoundType::SHINY + ) + , STOP_ON_DETECTED_SOUND( + "Stop on the detected sound
Stop program when the sound is detected.", + LockMode::LOCK_WHILE_RUNNING, + false + ) +{ + PA_ADD_OPTION(SOUND_TYPE); + PA_ADD_OPTION(STOP_ON_DETECTED_SOUND); +} + +void SoundListener::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ + JoyconContext context(scope, env.console.controller()); + + std::cout << "Running audio test program." << std::endl; + + std::shared_ptr detector; + auto action = [&](float error_coefficient) -> bool{ + // This lambda function will be called when the sound is detected. + // Its return will determine whether to stop the program: + return STOP_ON_DETECTED_SOUND; + }; + + SoundType type = SOUND_TYPE; + switch (type){ + case SoundType::SHINY: + detector = std::make_shared(env.console, action); + break; + default: + throw InternalProgramError( + &env.logger(), PA_CURRENT_FUNCTION, + "No such sound detector as sound type " + std::to_string((size_t)type) + ); + return; + } + + InferenceSession session( + context, env.console, + {{*detector, std::chrono::milliseconds(20)}} + ); + context.wait_until_cancel(); + + std::cout << "Audio test program Sound listener finished." << std::endl; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/TestPrograms/PokemonLGPE_SoundListener.h b/SerialPrograms/Source/PokemonLGPE/Programs/TestPrograms/PokemonLGPE_SoundListener.h index 109c342f3b..ac3c233ba6 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/TestPrograms/PokemonLGPE_SoundListener.h +++ b/SerialPrograms/Source/PokemonLGPE/Programs/TestPrograms/PokemonLGPE_SoundListener.h @@ -1,52 +1,52 @@ -/* Sound Listener - * - * From: https://github.com/PokemonAutomation/ - * - * Debug program to test all kinds of sound detectors. - */ - -#ifndef PokemonAutomation_PokemonLGPE_SoundListener_H -#define PokemonAutomation_PokemonLGPE_SoundListener_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -//#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - - -class SoundListener_Descriptor : public SingleSwitchProgramDescriptor{ -public: - SoundListener_Descriptor(); -}; - - -class SoundListener : public SingleSwitchProgramInstance{ -public: - SoundListener(); - virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; - - virtual void start_program_border_check( - VideoStream& stream, - FeedbackType feedback_type - ) override{} - -private: - enum class SoundType{ - SHINY, - }; - - EnumDropdownOption SOUND_TYPE; - BooleanCheckBoxOption STOP_ON_DETECTED_SOUND; -}; - - - - -} -} -} -#endif +/* Sound Listener + * + * From: https://github.com/PokemonAutomation/ + * + * Debug program to test all kinds of sound detectors. + */ + +#ifndef PokemonAutomation_PokemonLGPE_SoundListener_H +#define PokemonAutomation_PokemonLGPE_SoundListener_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +//#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + + +class SoundListener_Descriptor : public SingleSwitchProgramDescriptor{ +public: + SoundListener_Descriptor(); +}; + + +class SoundListener : public SingleSwitchProgramInstance{ +public: + SoundListener(); + virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; + + virtual void start_program_border_check( + VideoStream& stream, + FeedbackType feedback_type + ) override{} + +private: + enum class SoundType{ + SHINY, + }; + + EnumDropdownOption SOUND_TYPE; + BooleanCheckBoxOption STOP_ON_DETECTED_SOUND; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.cpp b/SerialPrograms/Source/PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.cpp index ee21536ccd..fe4113ecc7 100644 --- a/SerialPrograms/Source/PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.cpp +++ b/SerialPrograms/Source/PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.cpp @@ -1,124 +1,124 @@ -/* Dialog Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "PokemonRSE_DialogDetector.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -/* -DialogDetector::DialogDetector(Color color) - : m_left_box(0.155, 0.727, 0.015, 0.168) - , m_right_box(0.837, 0.729, 0.008, 0.161) -{} -void DialogDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_left_box); - items.add(COLOR_RED, m_right_box); -} -bool DialogDetector::detect(const ImageViewRGB32& screen) const{ - ImageViewRGB32 left_image = extract_box_reference(screen, m_left_box); - ImageViewRGB32 right_image = extract_box_reference(screen, m_right_box); - if (is_solid(left_image, { 0.335, 0.331, 0.332 }) && is_solid(right_image, { 0.335, 0.331, 0.332 })){ - return true; - } - return false; -} -*/ - -BattleDialogDetector::BattleDialogDetector(Color color) - : m_left_box(0.158, 0.725, 0.011, 0.176) - , m_right_box(0.827, 0.722, 0.013, 0.178) -{} -void BattleDialogDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_left_box); - items.add(COLOR_RED, m_right_box); -} -bool BattleDialogDetector::detect(const ImageViewRGB32& screen){ - ImageViewRGB32 left_image = extract_box_reference(screen, m_left_box); - ImageViewRGB32 right_image = extract_box_reference(screen, m_right_box); - if (is_solid(left_image, { 0.335, 0.331, 0.332 }) && is_solid(right_image, { 0.335, 0.331, 0.332 })){ - return true; - } - return false; -} - - -BattleMenuDetector::BattleMenuDetector(Color color) - : m_left_box(0.439, 0.717, 0.021, 0.192) - , m_right_box(0.821, 0.725, 0.030, 0.181) -{} -void BattleMenuDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_left_box); - items.add(COLOR_RED, m_right_box); -} -bool BattleMenuDetector::detect(const ImageViewRGB32& screen){ - ImageViewRGB32 left_image = extract_box_reference(screen, m_left_box); - ImageViewRGB32 right_image = extract_box_reference(screen, m_right_box); - if (is_solid(left_image, { 0.335, 0.331, 0.332 }) && is_solid(right_image, { 0.25, 0.38, 0.369 })){ - return true; - } - return false; -} - - -AdvanceBattleDialogDetector::AdvanceBattleDialogDetector(Color color) - : m_dialog_box(0.156, 0.715, 0.686, 0.193) - , m_left_box(0.156, 0.724, 0.010, 0.176) - , m_right_box(0.836, 0.717, 0.008, 0.189) -{} -void AdvanceBattleDialogDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_dialog_box); - items.add(COLOR_RED, m_left_box); - items.add(COLOR_RED, m_right_box); -} -bool AdvanceBattleDialogDetector::detect(const ImageViewRGB32& screen){ - const bool replace_color_within_range = false; - - //Filter out background - ImageRGB32 filtered_region = filter_rgb32_range( - extract_box_reference(screen, m_dialog_box), - combine_rgb(185, 0, 1), combine_rgb(255, 32, 33), Color(0), replace_color_within_range - ); - ImageStats stats = image_stats(filtered_region); - - /* - filtered_region.save("./filtered_only.png"); - cout << stats.average.r << endl; - cout << stats.average.g << endl; - cout << stats.average.b << endl; - */ - - ImageViewRGB32 left_image = extract_box_reference(screen, m_left_box); - ImageViewRGB32 right_image = extract_box_reference(screen, m_right_box); - - if (is_solid(left_image, { 0.335, 0.331, 0.332 }) - && is_solid(right_image, { 0.335, 0.331, 0.332 }) - && (stats.average.r > stats.average.b + 200) - && (stats.average.r > stats.average.g + 200) - ) - { - return true; - } - return false; -} - - - -} -} -} +/* Dialog Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "PokemonRSE_DialogDetector.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +/* +DialogDetector::DialogDetector(Color color) + : m_left_box(0.155, 0.727, 0.015, 0.168) + , m_right_box(0.837, 0.729, 0.008, 0.161) +{} +void DialogDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_left_box); + items.add(COLOR_RED, m_right_box); +} +bool DialogDetector::detect(const ImageViewRGB32& screen) const{ + ImageViewRGB32 left_image = extract_box_reference(screen, m_left_box); + ImageViewRGB32 right_image = extract_box_reference(screen, m_right_box); + if (is_solid(left_image, { 0.335, 0.331, 0.332 }) && is_solid(right_image, { 0.335, 0.331, 0.332 })){ + return true; + } + return false; +} +*/ + +BattleDialogDetector::BattleDialogDetector(Color color) + : m_left_box(0.158, 0.725, 0.011, 0.176) + , m_right_box(0.827, 0.722, 0.013, 0.178) +{} +void BattleDialogDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_left_box); + items.add(COLOR_RED, m_right_box); +} +bool BattleDialogDetector::detect(const ImageViewRGB32& screen){ + ImageViewRGB32 left_image = extract_box_reference(screen, m_left_box); + ImageViewRGB32 right_image = extract_box_reference(screen, m_right_box); + if (is_solid(left_image, { 0.335, 0.331, 0.332 }) && is_solid(right_image, { 0.335, 0.331, 0.332 })){ + return true; + } + return false; +} + + +BattleMenuDetector::BattleMenuDetector(Color color) + : m_left_box(0.439, 0.717, 0.021, 0.192) + , m_right_box(0.821, 0.725, 0.030, 0.181) +{} +void BattleMenuDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_left_box); + items.add(COLOR_RED, m_right_box); +} +bool BattleMenuDetector::detect(const ImageViewRGB32& screen){ + ImageViewRGB32 left_image = extract_box_reference(screen, m_left_box); + ImageViewRGB32 right_image = extract_box_reference(screen, m_right_box); + if (is_solid(left_image, { 0.335, 0.331, 0.332 }) && is_solid(right_image, { 0.25, 0.38, 0.369 })){ + return true; + } + return false; +} + + +AdvanceBattleDialogDetector::AdvanceBattleDialogDetector(Color color) + : m_dialog_box(0.156, 0.715, 0.686, 0.193) + , m_left_box(0.156, 0.724, 0.010, 0.176) + , m_right_box(0.836, 0.717, 0.008, 0.189) +{} +void AdvanceBattleDialogDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_dialog_box); + items.add(COLOR_RED, m_left_box); + items.add(COLOR_RED, m_right_box); +} +bool AdvanceBattleDialogDetector::detect(const ImageViewRGB32& screen){ + const bool replace_color_within_range = false; + + //Filter out background + ImageRGB32 filtered_region = filter_rgb32_range( + extract_box_reference(screen, m_dialog_box), + combine_rgb(185, 0, 1), combine_rgb(255, 32, 33), Color(0), replace_color_within_range + ); + ImageStats stats = image_stats(filtered_region); + + /* + filtered_region.save("./filtered_only.png"); + cout << stats.average.r << endl; + cout << stats.average.g << endl; + cout << stats.average.b << endl; + */ + + ImageViewRGB32 left_image = extract_box_reference(screen, m_left_box); + ImageViewRGB32 right_image = extract_box_reference(screen, m_right_box); + + if (is_solid(left_image, { 0.335, 0.331, 0.332 }) + && is_solid(right_image, { 0.335, 0.331, 0.332 }) + && (stats.average.r > stats.average.b + 200) + && (stats.average.r > stats.average.g + 200) + ) + { + return true; + } + return false; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h b/SerialPrograms/Source/PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h index 8651e9c01d..c059e368b8 100644 --- a/SerialPrograms/Source/PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h +++ b/SerialPrograms/Source/PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h @@ -1,117 +1,117 @@ -/* Dialog Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonRSE_DialogDetector_H -#define PokemonAutomation_PokemonRSE_DialogDetector_H - -#include -#include -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/VisualDetector.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ - class CancellableScope; - class VideoFeed; -namespace NintendoSwitch{ -namespace PokemonRSE{ - -/* -// TODO: Detect that a dialog box is on screen by looking for the white of the box -class DialogDetector : public StaticScreenDetector{ -public: - DialogDetector(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) const override; - -private: - ImageFloatBox m_left_box; - ImageFloatBox m_right_box; -}; -class DialogWatcher : public DetectorToFinder{ -public: - DialogWatcher(Color color) - : DetectorToFinder("DialogWatcher", std::chrono::milliseconds(250), color) - {} -}; -*/ - -// Battle dialog boxes are teal -class BattleDialogDetector : public StaticScreenDetector{ -public: - BattleDialogDetector(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - ImageFloatBox m_left_box; - ImageFloatBox m_right_box; -}; -class BattleDialogWatcher : public DetectorToFinder{ -public: - BattleDialogWatcher(Color color) - : DetectorToFinder("BattleDialogWatcher", std::chrono::milliseconds(250), color) - {} -}; - - -// Battle menu is up when it is white on the right and teal on the left -// For emerald the text is more flush to the left, so we target the right of the battle menu box -class BattleMenuDetector : public StaticScreenDetector{ -public: - BattleMenuDetector(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - ImageFloatBox m_left_box; - ImageFloatBox m_right_box; -}; -class BattleMenuWatcher : public DetectorToFinder{ -public: - BattleMenuWatcher(Color color) - : DetectorToFinder("BattleMenuWatcher", std::chrono::milliseconds(250), color) - {} -}; - - - -// Detect the red advancement arrow by filtering for red. -// This works for now, I don't think there's colored text? -// TODO: Change this to detect that the dialog arrow is in the dialog box by filtering for the red arrow -class AdvanceBattleDialogDetector : public StaticScreenDetector{ -public: - AdvanceBattleDialogDetector(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - ImageFloatBox m_dialog_box; - ImageFloatBox m_left_box; - ImageFloatBox m_right_box; -}; -class AdvanceBattleDialogWatcher : public DetectorToFinder{ -public: - AdvanceBattleDialogWatcher(Color color) - : DetectorToFinder("AdvanceBattleDialogWatcher", std::chrono::milliseconds(250), color) - {} -}; - -// Future note: when given a choice popup, there is no advance arrow. -// FRLG doesn't have an advance arrow, that's a future issue. - - -} -} -} - -#endif +/* Dialog Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonRSE_DialogDetector_H +#define PokemonAutomation_PokemonRSE_DialogDetector_H + +#include +#include +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/VisualDetector.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ + class CancellableScope; + class VideoFeed; +namespace NintendoSwitch{ +namespace PokemonRSE{ + +/* +// TODO: Detect that a dialog box is on screen by looking for the white of the box +class DialogDetector : public StaticScreenDetector{ +public: + DialogDetector(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) const override; + +private: + ImageFloatBox m_left_box; + ImageFloatBox m_right_box; +}; +class DialogWatcher : public DetectorToFinder{ +public: + DialogWatcher(Color color) + : DetectorToFinder("DialogWatcher", std::chrono::milliseconds(250), color) + {} +}; +*/ + +// Battle dialog boxes are teal +class BattleDialogDetector : public StaticScreenDetector{ +public: + BattleDialogDetector(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + ImageFloatBox m_left_box; + ImageFloatBox m_right_box; +}; +class BattleDialogWatcher : public DetectorToFinder{ +public: + BattleDialogWatcher(Color color) + : DetectorToFinder("BattleDialogWatcher", std::chrono::milliseconds(250), color) + {} +}; + + +// Battle menu is up when it is white on the right and teal on the left +// For emerald the text is more flush to the left, so we target the right of the battle menu box +class BattleMenuDetector : public StaticScreenDetector{ +public: + BattleMenuDetector(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + ImageFloatBox m_left_box; + ImageFloatBox m_right_box; +}; +class BattleMenuWatcher : public DetectorToFinder{ +public: + BattleMenuWatcher(Color color) + : DetectorToFinder("BattleMenuWatcher", std::chrono::milliseconds(250), color) + {} +}; + + + +// Detect the red advancement arrow by filtering for red. +// This works for now, I don't think there's colored text? +// TODO: Change this to detect that the dialog arrow is in the dialog box by filtering for the red arrow +class AdvanceBattleDialogDetector : public StaticScreenDetector{ +public: + AdvanceBattleDialogDetector(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + ImageFloatBox m_dialog_box; + ImageFloatBox m_left_box; + ImageFloatBox m_right_box; +}; +class AdvanceBattleDialogWatcher : public DetectorToFinder{ +public: + AdvanceBattleDialogWatcher(Color color) + : DetectorToFinder("AdvanceBattleDialogWatcher", std::chrono::milliseconds(250), color) + {} +}; + +// Future note: when given a choice popup, there is no advance arrow. +// FRLG doesn't have an advance arrow, that's a future issue. + + +} +} +} + +#endif diff --git a/SerialPrograms/Source/PokemonRSE/Inference/PokemonRSE_ShinyNumberDetector.cpp b/SerialPrograms/Source/PokemonRSE/Inference/PokemonRSE_ShinyNumberDetector.cpp index bc4bd0be1a..46d394d68b 100644 --- a/SerialPrograms/Source/PokemonRSE/Inference/PokemonRSE_ShinyNumberDetector.cpp +++ b/SerialPrograms/Source/PokemonRSE/Inference/PokemonRSE_ShinyNumberDetector.cpp @@ -1,64 +1,64 @@ -/* Shiny Number Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/ImageFilter.h" -#include "PokemonRSE_ShinyNumberDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -ShinyNumberDetector::ShinyNumberDetector(Color color) - : m_box_number(0.136, 0.156, 0.123, 0.072) -{} -void ShinyNumberDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_box_number); -} -bool ShinyNumberDetector::read(Logger& logger, const ImageViewRGB32& frame){ - const bool replace_color_within_range = true; - - //Filter out background - ImageRGB32 filtered_region = filter_rgb32_range( - extract_box_reference(frame, m_box_number), - combine_rgb(138, 97, 221), combine_rgb(200, 181, 239), Color(0), replace_color_within_range - ); - ImageStats stats = image_stats(filtered_region); - - /* - filtered_region.save("./filtered_only.png"); - cout << stats.average.r << endl; - cout << stats.average.g << endl; - cout << stats.average.b << endl; - */ - - /* - Shiny: - R: 196.632, G: 196.771, B: 145.863 - Not shiny: - R: 181.862, G: 180.686, B: 193.999 - */ - - if (stats.average.b + 20 < stats.average.r){ - return true; - } - return false; -} - - -} -} -} - +/* Shiny Number Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/ImageFilter.h" +#include "PokemonRSE_ShinyNumberDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +ShinyNumberDetector::ShinyNumberDetector(Color color) + : m_box_number(0.136, 0.156, 0.123, 0.072) +{} +void ShinyNumberDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_box_number); +} +bool ShinyNumberDetector::read(Logger& logger, const ImageViewRGB32& frame){ + const bool replace_color_within_range = true; + + //Filter out background + ImageRGB32 filtered_region = filter_rgb32_range( + extract_box_reference(frame, m_box_number), + combine_rgb(138, 97, 221), combine_rgb(200, 181, 239), Color(0), replace_color_within_range + ); + ImageStats stats = image_stats(filtered_region); + + /* + filtered_region.save("./filtered_only.png"); + cout << stats.average.r << endl; + cout << stats.average.g << endl; + cout << stats.average.b << endl; + */ + + /* + Shiny: + R: 196.632, G: 196.771, B: 145.863 + Not shiny: + R: 181.862, G: 180.686, B: 193.999 + */ + + if (stats.average.b + 20 < stats.average.r){ + return true; + } + return false; +} + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonRSE/Inference/PokemonRSE_ShinyNumberDetector.h b/SerialPrograms/Source/PokemonRSE/Inference/PokemonRSE_ShinyNumberDetector.h index 52a1f6ce9c..0328f0cf3b 100644 --- a/SerialPrograms/Source/PokemonRSE/Inference/PokemonRSE_ShinyNumberDetector.h +++ b/SerialPrograms/Source/PokemonRSE/Inference/PokemonRSE_ShinyNumberDetector.h @@ -1,36 +1,36 @@ -/* Shiny Number Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonRSE_ShinyNumberDetector_H -#define PokemonAutomation_PokemonRSE_ShinyNumberDetector_H - -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -// In the summary screen, the dex number will be yellow if a shiny, white if not. -// Additionally, the background behind the sprite will be white if shiny, grey if not. -// Number is easier to check as the background is scan lines. -class ShinyNumberDetector{ -public: - ShinyNumberDetector(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const; - bool read(Logger& logger, const ImageViewRGB32& frame); - -private: - ImageFloatBox m_box_number; -}; - - - -} -} -} -#endif +/* Shiny Number Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonRSE_ShinyNumberDetector_H +#define PokemonAutomation_PokemonRSE_ShinyNumberDetector_H + +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +// In the summary screen, the dex number will be yellow if a shiny, white if not. +// Additionally, the background behind the sprite will be white if shiny, grey if not. +// Number is easier to check as the background is scan lines. +class ShinyNumberDetector{ +public: + ShinyNumberDetector(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const; + bool read(Logger& logger, const ImageViewRGB32& frame); + +private: + ImageFloatBox m_box_number; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.cpp b/SerialPrograms/Source/PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.cpp index a0d184f89c..6c504843a0 100644 --- a/SerialPrograms/Source/PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.cpp +++ b/SerialPrograms/Source/PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.cpp @@ -1,47 +1,47 @@ -/* Shiny Sound Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Audio/AudioTemplateCache.h" -#include "CommonTools/Audio/SpectrogramMatcher.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" -#include "PokemonRSE/PokemonRSE_Settings.h" -#include "PokemonRSE_ShinySoundDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - - -ShinySoundDetector::ShinySoundDetector(Logger& logger, DetectedCallback detected_callback) - // Use a yellow as the detection color because the shiny animation is yellow. - : AudioPerSpectrumDetectorBase( - logger, - "ShinySoundDetector", - "Shiny sound", - COLOR_YELLOW, - detected_callback - ) -{} - - -float ShinySoundDetector::get_score_threshold() const{ - return (float)GameSettings::instance().SHINY_SOUND_THRESHOLD; -} - -std::unique_ptr ShinySoundDetector::build_spectrogram_matcher(size_t sample_rate){ - return std::make_unique( - "Shiny Sound", - AudioTemplateCache::instance().get_throw("PokemonRSE/ShinySound", sample_rate), - SpectrogramMatcher::Mode::SPIKE_CONV, sample_rate, - GameSettings::instance().SHINY_SOUND_LOW_FREQUENCY - ); -} - - - -} -} -} +/* Shiny Sound Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Audio/AudioTemplateCache.h" +#include "CommonTools/Audio/SpectrogramMatcher.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "PokemonRSE/PokemonRSE_Settings.h" +#include "PokemonRSE_ShinySoundDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + + +ShinySoundDetector::ShinySoundDetector(Logger& logger, DetectedCallback detected_callback) + // Use a yellow as the detection color because the shiny animation is yellow. + : AudioPerSpectrumDetectorBase( + logger, + "ShinySoundDetector", + "Shiny sound", + COLOR_YELLOW, + detected_callback + ) +{} + + +float ShinySoundDetector::get_score_threshold() const{ + return (float)GameSettings::instance().SHINY_SOUND_THRESHOLD; +} + +std::unique_ptr ShinySoundDetector::build_spectrogram_matcher(size_t sample_rate){ + return std::make_unique( + "Shiny Sound", + AudioTemplateCache::instance().get_throw("PokemonRSE/ShinySound", sample_rate), + SpectrogramMatcher::Mode::SPIKE_CONV, sample_rate, + GameSettings::instance().SHINY_SOUND_LOW_FREQUENCY + ); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.h b/SerialPrograms/Source/PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.h index eebdae6944..662612cd58 100644 --- a/SerialPrograms/Source/PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.h +++ b/SerialPrograms/Source/PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.h @@ -1,36 +1,36 @@ -/* Shiny Sound Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonRSE_ShinySoundDetector_H -#define PokemonAutomation_PokemonRSE_ShinySoundDetector_H - -#include "CommonTools/Audio/AudioPerSpectrumDetectorBase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - - -class ShinySoundDetector : public AudioPerSpectrumDetectorBase{ -public: - // Warning: The callback will be called from the audio inference thread. - ShinySoundDetector(Logger& logger, DetectedCallback detected_callback); - - // Implement AudioPerSpectrumDetectorBase::get_score_threshold() - virtual float get_score_threshold() const override; - -protected: - // Implement AudioPerSpectrumDetectorBase::build_spectrogram_matcher() - virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) override; -}; - - - - -} -} -} -#endif +/* Shiny Sound Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonRSE_ShinySoundDetector_H +#define PokemonAutomation_PokemonRSE_ShinySoundDetector_H + +#include "CommonTools/Audio/AudioPerSpectrumDetectorBase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + + +class ShinySoundDetector : public AudioPerSpectrumDetectorBase{ +public: + // Warning: The callback will be called from the audio inference thread. + ShinySoundDetector(Logger& logger, DetectedCallback detected_callback); + + // Implement AudioPerSpectrumDetectorBase::get_score_threshold() + virtual float get_score_threshold() const override; + +protected: + // Implement AudioPerSpectrumDetectorBase::build_spectrogram_matcher() + virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) override; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonRSE/PokemonRSE_Navigation.cpp b/SerialPrograms/Source/PokemonRSE/PokemonRSE_Navigation.cpp index 3c3dd355fb..78ff8f6a60 100644 --- a/SerialPrograms/Source/PokemonRSE/PokemonRSE_Navigation.cpp +++ b/SerialPrograms/Source/PokemonRSE/PokemonRSE_Navigation.cpp @@ -1,165 +1,165 @@ -/* Pokemon RSE Navigation - * - * From: https://github.com/PokemonAutomation/ - * - * Soft reset, menus, etc. - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h" -#include "PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.h" -#include "PokemonRSE/PokemonRSE_Settings.h" -#include "PokemonRSE_Navigation.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - - -void soft_reset(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - // A + B + Select + Start - pbf_press_button(context, BUTTON_B | BUTTON_Y | BUTTON_MINUS | BUTTON_PLUS, 10, 180); - - pbf_mash_button(context, BUTTON_PLUS, GameSettings::instance().START_BUTTON_MASH0); - context.wait_for_all_requests(); - - pbf_press_button(context, BUTTON_A, 20, 40); - - //Wait for game to load in - BlackScreenOverWatcher detector(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - int ret = wait_until( - stream, context, - GameSettings::instance().ENTER_GAME_WAIT0, - {detector} - ); - if (ret == 0){ - stream.log("Entered game!"); - }else{ - stream.log("Timed out waiting to enter game.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "soft_reset(): Timed out waiting to enter game.", - stream - ); - } - context.wait_for_all_requests(); -} - -void flee_battle(VideoStream& stream, ProControllerContext& context) { - stream.log("Navigate to Run."); - pbf_press_dpad(context, DPAD_RIGHT, 20, 20); - pbf_press_dpad(context, DPAD_DOWN, 20, 20); - pbf_press_button(context, BUTTON_A, 20, 40); - - AdvanceBattleDialogWatcher ran_away(COLOR_YELLOW); - int ret2 = wait_until( - stream, context, - std::chrono::seconds(5), - {{ran_away}} - ); - if (ret2 == 0) { - stream.log("Running away..."); - } else { - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "handle_encounter(): Unable to navigate to flee button.", - stream - ); - } - - pbf_press_button(context, BUTTON_A, 40, 40); - BlackScreenOverWatcher battle_over(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - int ret3 = wait_until( - stream, context, - std::chrono::seconds(5), - {{battle_over}} - ); - if (ret3 == 0) { - stream.log("Ran from battle."); - } else { - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "handle_encounter(): Unable to flee from battle.", - stream - ); - } -} - -bool handle_encounter(VideoStream& stream, ProControllerContext& context, bool send_out_lead) { - float shiny_coefficient = 1.0; - ShinySoundDetector shiny_detector(stream.logger(), [&](float error_coefficient) -> bool{ - shiny_coefficient = error_coefficient; - return true; - }); - AdvanceBattleDialogWatcher legendary_appeared(COLOR_YELLOW); - - stream.log("Starting battle."); - pbf_mash_button(context, BUTTON_A, 540); - context.wait_for_all_requests(); - - int res = run_until( - stream, context, - [&](ProControllerContext& context) { - int ret = wait_until( - stream, context, - std::chrono::seconds(30), - {{legendary_appeared}} - ); - if (ret == 0) { - stream.log("Advance arrow detected."); - } else { - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "handle_encounter(): Did not detect battle start.", - stream - ); - } - pbf_wait(context, 125); - context.wait_for_all_requests(); - }, - {{shiny_detector}} - ); - shiny_detector.throw_if_no_sound(); - if (res == 0){ - stream.log("Shiny detected!"); - return true; - } - stream.log("Shiny not found."); - - if (send_out_lead) { - //Send out lead, no shiny detection needed. - BattleMenuWatcher battle_menu(COLOR_RED); - stream.log("Sending out lead Pokemon."); - pbf_press_button(context, BUTTON_A, 40, 40); - - int ret = wait_until( - stream, context, - std::chrono::seconds(15), - { {battle_menu} } - ); - if (ret == 0) { - stream.log("Battle menu detecteed!"); - } - else { - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "handle_encounter(): Did not detect battle menu.", - stream - ); - } - pbf_wait(context, 125); - context.wait_for_all_requests(); - } - - return false; -} - - -} -} -} +/* Pokemon RSE Navigation + * + * From: https://github.com/PokemonAutomation/ + * + * Soft reset, menus, etc. + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h" +#include "PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.h" +#include "PokemonRSE/PokemonRSE_Settings.h" +#include "PokemonRSE_Navigation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + + +void soft_reset(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + // A + B + Select + Start + pbf_press_button(context, BUTTON_B | BUTTON_Y | BUTTON_MINUS | BUTTON_PLUS, 10, 180); + + pbf_mash_button(context, BUTTON_PLUS, GameSettings::instance().START_BUTTON_MASH0); + context.wait_for_all_requests(); + + pbf_press_button(context, BUTTON_A, 20, 40); + + //Wait for game to load in + BlackScreenOverWatcher detector(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + int ret = wait_until( + stream, context, + GameSettings::instance().ENTER_GAME_WAIT0, + {detector} + ); + if (ret == 0){ + stream.log("Entered game!"); + }else{ + stream.log("Timed out waiting to enter game.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "soft_reset(): Timed out waiting to enter game.", + stream + ); + } + context.wait_for_all_requests(); +} + +void flee_battle(VideoStream& stream, ProControllerContext& context) { + stream.log("Navigate to Run."); + pbf_press_dpad(context, DPAD_RIGHT, 20, 20); + pbf_press_dpad(context, DPAD_DOWN, 20, 20); + pbf_press_button(context, BUTTON_A, 20, 40); + + AdvanceBattleDialogWatcher ran_away(COLOR_YELLOW); + int ret2 = wait_until( + stream, context, + std::chrono::seconds(5), + {{ran_away}} + ); + if (ret2 == 0) { + stream.log("Running away..."); + } else { + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "handle_encounter(): Unable to navigate to flee button.", + stream + ); + } + + pbf_press_button(context, BUTTON_A, 40, 40); + BlackScreenOverWatcher battle_over(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + int ret3 = wait_until( + stream, context, + std::chrono::seconds(5), + {{battle_over}} + ); + if (ret3 == 0) { + stream.log("Ran from battle."); + } else { + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "handle_encounter(): Unable to flee from battle.", + stream + ); + } +} + +bool handle_encounter(VideoStream& stream, ProControllerContext& context, bool send_out_lead) { + float shiny_coefficient = 1.0; + ShinySoundDetector shiny_detector(stream.logger(), [&](float error_coefficient) -> bool{ + shiny_coefficient = error_coefficient; + return true; + }); + AdvanceBattleDialogWatcher legendary_appeared(COLOR_YELLOW); + + stream.log("Starting battle."); + pbf_mash_button(context, BUTTON_A, 540); + context.wait_for_all_requests(); + + int res = run_until( + stream, context, + [&](ProControllerContext& context) { + int ret = wait_until( + stream, context, + std::chrono::seconds(30), + {{legendary_appeared}} + ); + if (ret == 0) { + stream.log("Advance arrow detected."); + } else { + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "handle_encounter(): Did not detect battle start.", + stream + ); + } + pbf_wait(context, 125); + context.wait_for_all_requests(); + }, + {{shiny_detector}} + ); + shiny_detector.throw_if_no_sound(); + if (res == 0){ + stream.log("Shiny detected!"); + return true; + } + stream.log("Shiny not found."); + + if (send_out_lead) { + //Send out lead, no shiny detection needed. + BattleMenuWatcher battle_menu(COLOR_RED); + stream.log("Sending out lead Pokemon."); + pbf_press_button(context, BUTTON_A, 40, 40); + + int ret = wait_until( + stream, context, + std::chrono::seconds(15), + { {battle_menu} } + ); + if (ret == 0) { + stream.log("Battle menu detecteed!"); + } + else { + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "handle_encounter(): Did not detect battle menu.", + stream + ); + } + pbf_wait(context, 125); + context.wait_for_all_requests(); + } + + return false; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonRSE/PokemonRSE_Navigation.h b/SerialPrograms/Source/PokemonRSE/PokemonRSE_Navigation.h index 17cc31500f..fd3b6d9cb4 100644 --- a/SerialPrograms/Source/PokemonRSE/PokemonRSE_Navigation.h +++ b/SerialPrograms/Source/PokemonRSE/PokemonRSE_Navigation.h @@ -1,36 +1,36 @@ -/* Pokemon RSE Navigation - * - * From: https://github.com/PokemonAutomation/ - * - * Soft reset, menus, etc. - * - */ - -#ifndef PokemonAutomation_PokemonRSE_Navigation_H -#define PokemonAutomation_PokemonRSE_Navigation_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonRSE{ - -// Press A+B+Select+Start at the same time to soft reset, then re-enters the game. -// For now this assumes no dry battery. -void soft_reset(const ProgramInfo& info, VideoStream& stream, ProControllerContext &context); - -// Run from battle. Cursor must start on the FIGHT button. Assumes fleeing will always work. (Smoke Ball) -void flee_battle(VideoStream& stream, ProControllerContext& context); - -// After press A/walking up to enter a battle, run this handle the battle start and to check if opponent is shiny. -// Set send_out_lead to true and then use flee_battle() after if game is Emerald. -// For R/S, send_out_lead as false and then soft_reset() to save time. -bool handle_encounter(VideoStream& stream, ProControllerContext& context, bool send_out_lead); - - -} -} -} -#endif +/* Pokemon RSE Navigation + * + * From: https://github.com/PokemonAutomation/ + * + * Soft reset, menus, etc. + * + */ + +#ifndef PokemonAutomation_PokemonRSE_Navigation_H +#define PokemonAutomation_PokemonRSE_Navigation_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonRSE{ + +// Press A+B+Select+Start at the same time to soft reset, then re-enters the game. +// For now this assumes no dry battery. +void soft_reset(const ProgramInfo& info, VideoStream& stream, ProControllerContext &context); + +// Run from battle. Cursor must start on the FIGHT button. Assumes fleeing will always work. (Smoke Ball) +void flee_battle(VideoStream& stream, ProControllerContext& context); + +// After press A/walking up to enter a battle, run this handle the battle start and to check if opponent is shiny. +// Set send_out_lead to true and then use flee_battle() after if game is Emerald. +// For R/S, send_out_lead as false and then soft_reset() to save time. +bool handle_encounter(VideoStream& stream, ProControllerContext& context, bool send_out_lead); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonRSE/PokemonRSE_Panels.cpp b/SerialPrograms/Source/PokemonRSE/PokemonRSE_Panels.cpp index b94624a7ac..8e34831079 100644 --- a/SerialPrograms/Source/PokemonRSE/PokemonRSE_Panels.cpp +++ b/SerialPrograms/Source/PokemonRSE/PokemonRSE_Panels.cpp @@ -1,64 +1,64 @@ -/* Pokemon RSE Panels - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/GlobalSettingsPanel.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonRSE_Panels.h" - -#include "PokemonRSE_Settings.h" - -#include "Programs/ShinyHunting/PokemonRSE_AudioStarterReset.h" -#include "Programs/ShinyHunting/PokemonRSE_LegendaryHunt-Emerald.h" -#include "Programs/ShinyHunting/PokemonRSE_ShinyHunt-Deoxys.h" -#include "Programs/ShinyHunting/PokemonRSE_ShinyHunt-Mew.h" - -#include "Programs/ShinyHunting/PokemonRSE_StarterReset.h" -#include "Programs/TestPrograms/PokemonRSE_SoundListener.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - - - -PanelListFactory::PanelListFactory() - : PanelListDescriptor(Pokemon::STRING_POKEMON + " Ruby, Sapphire, and Emerald") -{} - -std::vector PanelListFactory::make_panels() const{ - std::vector ret; - - ret.emplace_back("---- Settings ----"); - ret.emplace_back(make_settings()); - - //ret.emplace_back("---- General ----"); - - ret.emplace_back("---- Shiny Hunting (Ruby/Sapphire) ----"); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- Shiny Hunting (Emerald) ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - - if (PreloadSettings::instance().DEVELOPER_MODE){ - ret.emplace_back("---- Test ----"); - ret.emplace_back(make_single_switch_program()); //outdated early test program - - ret.emplace_back("---- Developer Tools ----"); - ret.emplace_back(make_single_switch_program()); - } - - return ret; -} - - - - -} -} -} +/* Pokemon RSE Panels + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonRSE_Panels.h" + +#include "PokemonRSE_Settings.h" + +#include "Programs/ShinyHunting/PokemonRSE_AudioStarterReset.h" +#include "Programs/ShinyHunting/PokemonRSE_LegendaryHunt-Emerald.h" +#include "Programs/ShinyHunting/PokemonRSE_ShinyHunt-Deoxys.h" +#include "Programs/ShinyHunting/PokemonRSE_ShinyHunt-Mew.h" + +#include "Programs/ShinyHunting/PokemonRSE_StarterReset.h" +#include "Programs/TestPrograms/PokemonRSE_SoundListener.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + + + +PanelListFactory::PanelListFactory() + : PanelListDescriptor(Pokemon::STRING_POKEMON + " Ruby, Sapphire, and Emerald") +{} + +std::vector PanelListFactory::make_panels() const{ + std::vector ret; + + ret.emplace_back("---- Settings ----"); + ret.emplace_back(make_settings()); + + //ret.emplace_back("---- General ----"); + + ret.emplace_back("---- Shiny Hunting (Ruby/Sapphire) ----"); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- Shiny Hunting (Emerald) ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + + if (PreloadSettings::instance().DEVELOPER_MODE){ + ret.emplace_back("---- Test ----"); + ret.emplace_back(make_single_switch_program()); //outdated early test program + + ret.emplace_back("---- Developer Tools ----"); + ret.emplace_back(make_single_switch_program()); + } + + return ret; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonRSE/PokemonRSE_Panels.h b/SerialPrograms/Source/PokemonRSE/PokemonRSE_Panels.h index f40d7774aa..6d28f52e32 100644 --- a/SerialPrograms/Source/PokemonRSE/PokemonRSE_Panels.h +++ b/SerialPrograms/Source/PokemonRSE/PokemonRSE_Panels.h @@ -1,30 +1,30 @@ -/* Pokemon RSE Panels - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonRSE_Panels_H -#define PokemonAutomation_PokemonRSE_Panels_H - -#include "CommonFramework/Panels/PanelList.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - - - -class PanelListFactory : public PanelListDescriptor{ -public: - PanelListFactory(); -private: - virtual std::vector make_panels() const override; -}; - - - -} -} -} -#endif +/* Pokemon RSE Panels + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonRSE_Panels_H +#define PokemonAutomation_PokemonRSE_Panels_H + +#include "CommonFramework/Panels/PanelList.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + + + +class PanelListFactory : public PanelListDescriptor{ +public: + PanelListFactory(); +private: + virtual std::vector make_panels() const override; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonRSE/PokemonRSE_Settings.cpp b/SerialPrograms/Source/PokemonRSE/PokemonRSE_Settings.cpp index a6a4af9370..865fb83f6e 100644 --- a/SerialPrograms/Source/PokemonRSE/PokemonRSE_Settings.cpp +++ b/SerialPrograms/Source/PokemonRSE/PokemonRSE_Settings.cpp @@ -1,91 +1,91 @@ -/* Pokemon RSE Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Pokemon/Pokemon_Strings.h" - -#include "PokemonRSE_Settings.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -using namespace Pokemon; - - - -GameSettings& GameSettings::instance(){ - static GameSettings settings; - return settings; -} -GameSettings::GameSettings() - : BatchOption(LockMode::LOCK_WHILE_RUNNING) - , m_soft_reset_timings("Soft Reset Timings:") - , START_BUTTON_MASH0( - "Start Button Mash:
Mash Start for this long after a soft reset to get to the main menu.", - LockMode::LOCK_WHILE_RUNNING, - "5000 ms" - ) - , ENTER_GAME_WAIT0( - "Enter Game Wait:
Wait this long for the game to load.", - LockMode::LOCK_WHILE_RUNNING, - "3000 ms" - ) - , m_shiny_audio_settings("Shiny Audio Settings:") - , SHINY_SOUND_THRESHOLD( - "Shiny Sound Threshold:
Maximum error coefficient to trigger a shiny detection.", - LockMode::LOCK_WHILE_RUNNING, - 0.97, 0, 1.0 - ) - , SHINY_SOUND_LOW_FREQUENCY( - "Shiny Sound Low Frequency (Hz):
High pass filter frequency for shiny sound.", - LockMode::LOCK_WHILE_RUNNING, - 5000, 0, 48000 - ) -{ - PA_ADD_STATIC(m_soft_reset_timings); - PA_ADD_OPTION(START_BUTTON_MASH0); - PA_ADD_OPTION(ENTER_GAME_WAIT0); - PA_ADD_STATIC(m_shiny_audio_settings); - PA_ADD_OPTION(SHINY_SOUND_THRESHOLD); - PA_ADD_OPTION(SHINY_SOUND_LOW_FREQUENCY); -} - - - - - -GameSettings_Descriptor::GameSettings_Descriptor() - : PanelDescriptor( - Color(), - "PokemonRSE:GlobalSettings", - STRING_POKEMON + " RSE", "Game Settings", - "ComputerControl/blob/master/Wiki/Programs/PokemonRSE/RSESettings.md", - "Global " + STRING_POKEMON + " Ruby, Sapphire, and Emerald Settings" - ) -{} - - - -GameSettingsPanel::GameSettingsPanel(const GameSettings_Descriptor& descriptor) - : SettingsPanelInstance(descriptor) - , settings(GameSettings::instance()) -{ - PA_ADD_OPTION(settings); -} - - - - - -} -} -} - - - - - - +/* Pokemon RSE Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon/Pokemon_Strings.h" + +#include "PokemonRSE_Settings.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +using namespace Pokemon; + + + +GameSettings& GameSettings::instance(){ + static GameSettings settings; + return settings; +} +GameSettings::GameSettings() + : BatchOption(LockMode::LOCK_WHILE_RUNNING) + , m_soft_reset_timings("Soft Reset Timings:") + , START_BUTTON_MASH0( + "Start Button Mash:
Mash Start for this long after a soft reset to get to the main menu.", + LockMode::LOCK_WHILE_RUNNING, + "5000 ms" + ) + , ENTER_GAME_WAIT0( + "Enter Game Wait:
Wait this long for the game to load.", + LockMode::LOCK_WHILE_RUNNING, + "3000 ms" + ) + , m_shiny_audio_settings("Shiny Audio Settings:") + , SHINY_SOUND_THRESHOLD( + "Shiny Sound Threshold:
Maximum error coefficient to trigger a shiny detection.", + LockMode::LOCK_WHILE_RUNNING, + 0.97, 0, 1.0 + ) + , SHINY_SOUND_LOW_FREQUENCY( + "Shiny Sound Low Frequency (Hz):
High pass filter frequency for shiny sound.", + LockMode::LOCK_WHILE_RUNNING, + 5000, 0, 48000 + ) +{ + PA_ADD_STATIC(m_soft_reset_timings); + PA_ADD_OPTION(START_BUTTON_MASH0); + PA_ADD_OPTION(ENTER_GAME_WAIT0); + PA_ADD_STATIC(m_shiny_audio_settings); + PA_ADD_OPTION(SHINY_SOUND_THRESHOLD); + PA_ADD_OPTION(SHINY_SOUND_LOW_FREQUENCY); +} + + + + + +GameSettings_Descriptor::GameSettings_Descriptor() + : PanelDescriptor( + Color(), + "PokemonRSE:GlobalSettings", + STRING_POKEMON + " RSE", "Game Settings", + "ComputerControl/blob/master/Wiki/Programs/PokemonRSE/RSESettings.md", + "Global " + STRING_POKEMON + " Ruby, Sapphire, and Emerald Settings" + ) +{} + + + +GameSettingsPanel::GameSettingsPanel(const GameSettings_Descriptor& descriptor) + : SettingsPanelInstance(descriptor) + , settings(GameSettings::instance()) +{ + PA_ADD_OPTION(settings); +} + + + + + +} +} +} + + + + + + diff --git a/SerialPrograms/Source/PokemonRSE/PokemonRSE_Settings.h b/SerialPrograms/Source/PokemonRSE/PokemonRSE_Settings.h index 35d73b3422..74d1a114f8 100644 --- a/SerialPrograms/Source/PokemonRSE/PokemonRSE_Settings.h +++ b/SerialPrograms/Source/PokemonRSE/PokemonRSE_Settings.h @@ -1,55 +1,55 @@ -/* Pokemon RSE Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonRSE_Settings_H -#define PokemonAutomation_PokemonRSE_Settings_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Panels/SettingsPanel.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - - -class GameSettings : public BatchOption{ - GameSettings(); -public: - static GameSettings& instance(); - - SectionDividerOption m_soft_reset_timings; - MillisecondsOption START_BUTTON_MASH0; - MillisecondsOption ENTER_GAME_WAIT0; - - SectionDividerOption m_shiny_audio_settings; - FloatingPointOption SHINY_SOUND_THRESHOLD; - FloatingPointOption SHINY_SOUND_LOW_FREQUENCY; - -}; - - - - -class GameSettings_Descriptor : public PanelDescriptor{ -public: - GameSettings_Descriptor(); -}; - - -class GameSettingsPanel : public SettingsPanelInstance{ -public: - GameSettingsPanel(const GameSettings_Descriptor& descriptor); -private: - GameSettings& settings; -}; - - -} -} -} -#endif +/* Pokemon RSE Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonRSE_Settings_H +#define PokemonAutomation_PokemonRSE_Settings_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Panels/SettingsPanel.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + + +class GameSettings : public BatchOption{ + GameSettings(); +public: + static GameSettings& instance(); + + SectionDividerOption m_soft_reset_timings; + MillisecondsOption START_BUTTON_MASH0; + MillisecondsOption ENTER_GAME_WAIT0; + + SectionDividerOption m_shiny_audio_settings; + FloatingPointOption SHINY_SOUND_THRESHOLD; + FloatingPointOption SHINY_SOUND_LOW_FREQUENCY; + +}; + + + + +class GameSettings_Descriptor : public PanelDescriptor{ +public: + GameSettings_Descriptor(); +}; + + +class GameSettingsPanel : public SettingsPanelInstance{ +public: + GameSettingsPanel(const GameSettings_Descriptor& descriptor); +private: + GameSettings& settings; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_AudioStarterReset.cpp b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_AudioStarterReset.cpp index 78457e2aef..a7dfeef161 100644 --- a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_AudioStarterReset.cpp +++ b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_AudioStarterReset.cpp @@ -1,221 +1,221 @@ -/* RS Starter Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h" -#include "PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.h" -#include "PokemonRSE/PokemonRSE_Navigation.h" -#include "PokemonRSE_AudioStarterReset.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -AudioStarterReset_Descriptor::AudioStarterReset_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonRSE:AudioStarterReset", - Pokemon::STRING_POKEMON + " RSE", "Starter Reset", - "ComputerControl/blob/master/Wiki/Programs/PokemonRSE/AudioStarterReset.md", - "Soft reset for a shiny starter. Ruby and Sapphire only.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} - -struct AudioStarterReset_Descriptor::Stats : public StatsTracker{ - Stats() - : resets(m_stats["Resets"]) - , poochyena(m_stats["Shiny Poochyena"]) - , shinystarter(m_stats["Shiny Starter"]) - { - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Shiny Poochyena"); - m_display_order.emplace_back("Shiny Starter"); - } - std::atomic& resets; - std::atomic& poochyena; - std::atomic& shinystarter; -}; -std::unique_ptr AudioStarterReset_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -AudioStarterReset::AudioStarterReset() - : TARGET( - "Starter:
", - { - {Target::treecko, "treecko", "Treecko"}, - {Target::torchic, "torchic", "Torchic"}, - {Target::mudkip, "mudkip", "Mudkip"}, - }, - LockMode::LOCK_WHILE_RUNNING, - Target::treecko - ) - , NOTIFICATION_SHINY_POOCH( - "Shiny Poochyena", - false, false, ImageAttachmentMode::JPG, - {"Notifs"} - ) - , NOTIFICATION_SHINY_STARTER( - "Shiny Starter", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_SHINY_POOCH, - &NOTIFICATION_SHINY_STARTER, - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(TARGET); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void AudioStarterReset::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - AudioStarterReset_Descriptor::Stats& stats = env.current_stats(); - - /* - * Settings: Text Speed fast. - * Full screen, no filter? The device I'm using to test has similar looking output, but I don't have switch online+. - * If on a retro handheld, make sure the screen matches that of NSO+. - * - * Setup: Stand in front of the Professor's bag and save the game. - * - * Required to fight, so have to do the SR method instead of run away - * Soft reset programs are only for Ruby/Sapphire, as Emerald has the 0 seed issue. - * - * This also assumes no dry battery. - */ - - bool shiny_starter = false; - while (!shiny_starter) { - float shiny_coefficient = 1.0; - ShinySoundDetector pooch_detector(env.console, [&](float error_coefficient) -> bool{ - shiny_coefficient = error_coefficient; - return true; - }); - - env.log("Opening bag and selecting starter."); - pbf_press_button(context, BUTTON_A, 40, 180); - - switch (TARGET) { - case Target::treecko: - pbf_press_dpad(context, DPAD_LEFT, 40, 100); - break; - case Target::torchic: - //Default cursor position, do nothing. - break; - case Target::mudkip: - pbf_press_dpad(context, DPAD_RIGHT, 40, 100); - break; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "AudioStarterReset: Invalid target.", - env.console - ); - break; - } - pbf_mash_button(context, BUTTON_A, 540); - context.wait_for_all_requests(); - - env.log("Starter selected. Checking for shiny Poochyena."); - AdvanceBattleDialogWatcher pooch_appeared(COLOR_YELLOW); - - int res = run_until( - env.console, context, - [&](ProControllerContext& context) { - int ret = wait_until( - env.console, context, - std::chrono::seconds(20), - {{pooch_appeared}} - ); - if (ret == 0) { - env.log("Advance arrow detected."); - } - pbf_wait(context, 125); - context.wait_for_all_requests(); - }, - {{pooch_detector}} - ); - pooch_detector.throw_if_no_sound(); - if (res == 0){ - env.log("Shiny Poochyena detected!"); - stats.poochyena++; - env.update_stats(); - send_program_notification(env, NOTIFICATION_SHINY_POOCH, COLOR_YELLOW, "Shiny Poochyena found", {}, "", env.console.video().snapshot(), true); - } - else { - env.log("Poochyena is not shiny."); - } - context.wait_for_all_requests(); - - float shiny_coefficient2 = 1.0; - ShinySoundDetector starter_detector(env.console, [&](float error_coefficient) -> bool{ - shiny_coefficient2 = error_coefficient; - return true; - }); - - BattleMenuWatcher battle_menu(COLOR_RED); - int res2 = run_until( - env.console, context, - [&](ProControllerContext& context) { - env.log("Sending out selected starter."); - pbf_press_button(context, BUTTON_A, 40, 40); - - int ret = wait_until( - env.console, context, - std::chrono::seconds(20), - {{battle_menu}} - ); - if (ret == 0) { - env.log("Battle menu detecteed!"); - } - pbf_wait(context, 125); - context.wait_for_all_requests(); - }, - {{starter_detector}} - ); - starter_detector.throw_if_no_sound(); - context.wait_for_all_requests(); - if (res2 == 0){ - env.log("Shiny starter detected!"); - stats.shinystarter++; - env.update_stats(); - send_program_notification(env, NOTIFICATION_SHINY_STARTER, COLOR_YELLOW, "Shiny starter found!", {}, "", env.console.video().snapshot(), true); - shiny_starter = true; - } - else { - env.log("Starter is not shiny."); - env.log("Soft resetting."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Soft resetting." - ); - stats.resets++; - env.update_stats(); - soft_reset(env.program_info(), env.console, context); - } - } - - //if system set to nintendo switch, have go home when done option? - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - -} -} -} - +/* RS Starter Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h" +#include "PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.h" +#include "PokemonRSE/PokemonRSE_Navigation.h" +#include "PokemonRSE_AudioStarterReset.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +AudioStarterReset_Descriptor::AudioStarterReset_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonRSE:AudioStarterReset", + Pokemon::STRING_POKEMON + " RSE", "Starter Reset", + "ComputerControl/blob/master/Wiki/Programs/PokemonRSE/AudioStarterReset.md", + "Soft reset for a shiny starter. Ruby and Sapphire only.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} + +struct AudioStarterReset_Descriptor::Stats : public StatsTracker{ + Stats() + : resets(m_stats["Resets"]) + , poochyena(m_stats["Shiny Poochyena"]) + , shinystarter(m_stats["Shiny Starter"]) + { + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Shiny Poochyena"); + m_display_order.emplace_back("Shiny Starter"); + } + std::atomic& resets; + std::atomic& poochyena; + std::atomic& shinystarter; +}; +std::unique_ptr AudioStarterReset_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +AudioStarterReset::AudioStarterReset() + : TARGET( + "Starter:
", + { + {Target::treecko, "treecko", "Treecko"}, + {Target::torchic, "torchic", "Torchic"}, + {Target::mudkip, "mudkip", "Mudkip"}, + }, + LockMode::LOCK_WHILE_RUNNING, + Target::treecko + ) + , NOTIFICATION_SHINY_POOCH( + "Shiny Poochyena", + false, false, ImageAttachmentMode::JPG, + {"Notifs"} + ) + , NOTIFICATION_SHINY_STARTER( + "Shiny Starter", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_SHINY_POOCH, + &NOTIFICATION_SHINY_STARTER, + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(TARGET); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void AudioStarterReset::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + AudioStarterReset_Descriptor::Stats& stats = env.current_stats(); + + /* + * Settings: Text Speed fast. + * Full screen, no filter? The device I'm using to test has similar looking output, but I don't have switch online+. + * If on a retro handheld, make sure the screen matches that of NSO+. + * + * Setup: Stand in front of the Professor's bag and save the game. + * + * Required to fight, so have to do the SR method instead of run away + * Soft reset programs are only for Ruby/Sapphire, as Emerald has the 0 seed issue. + * + * This also assumes no dry battery. + */ + + bool shiny_starter = false; + while (!shiny_starter) { + float shiny_coefficient = 1.0; + ShinySoundDetector pooch_detector(env.console, [&](float error_coefficient) -> bool{ + shiny_coefficient = error_coefficient; + return true; + }); + + env.log("Opening bag and selecting starter."); + pbf_press_button(context, BUTTON_A, 40, 180); + + switch (TARGET) { + case Target::treecko: + pbf_press_dpad(context, DPAD_LEFT, 40, 100); + break; + case Target::torchic: + //Default cursor position, do nothing. + break; + case Target::mudkip: + pbf_press_dpad(context, DPAD_RIGHT, 40, 100); + break; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "AudioStarterReset: Invalid target.", + env.console + ); + break; + } + pbf_mash_button(context, BUTTON_A, 540); + context.wait_for_all_requests(); + + env.log("Starter selected. Checking for shiny Poochyena."); + AdvanceBattleDialogWatcher pooch_appeared(COLOR_YELLOW); + + int res = run_until( + env.console, context, + [&](ProControllerContext& context) { + int ret = wait_until( + env.console, context, + std::chrono::seconds(20), + {{pooch_appeared}} + ); + if (ret == 0) { + env.log("Advance arrow detected."); + } + pbf_wait(context, 125); + context.wait_for_all_requests(); + }, + {{pooch_detector}} + ); + pooch_detector.throw_if_no_sound(); + if (res == 0){ + env.log("Shiny Poochyena detected!"); + stats.poochyena++; + env.update_stats(); + send_program_notification(env, NOTIFICATION_SHINY_POOCH, COLOR_YELLOW, "Shiny Poochyena found", {}, "", env.console.video().snapshot(), true); + } + else { + env.log("Poochyena is not shiny."); + } + context.wait_for_all_requests(); + + float shiny_coefficient2 = 1.0; + ShinySoundDetector starter_detector(env.console, [&](float error_coefficient) -> bool{ + shiny_coefficient2 = error_coefficient; + return true; + }); + + BattleMenuWatcher battle_menu(COLOR_RED); + int res2 = run_until( + env.console, context, + [&](ProControllerContext& context) { + env.log("Sending out selected starter."); + pbf_press_button(context, BUTTON_A, 40, 40); + + int ret = wait_until( + env.console, context, + std::chrono::seconds(20), + {{battle_menu}} + ); + if (ret == 0) { + env.log("Battle menu detecteed!"); + } + pbf_wait(context, 125); + context.wait_for_all_requests(); + }, + {{starter_detector}} + ); + starter_detector.throw_if_no_sound(); + context.wait_for_all_requests(); + if (res2 == 0){ + env.log("Shiny starter detected!"); + stats.shinystarter++; + env.update_stats(); + send_program_notification(env, NOTIFICATION_SHINY_STARTER, COLOR_YELLOW, "Shiny starter found!", {}, "", env.console.video().snapshot(), true); + shiny_starter = true; + } + else { + env.log("Starter is not shiny."); + env.log("Soft resetting."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Soft resetting." + ); + stats.resets++; + env.update_stats(); + soft_reset(env.program_info(), env.console, context); + } + } + + //if system set to nintendo switch, have go home when done option? + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + +} +} +} + diff --git a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_AudioStarterReset.h b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_AudioStarterReset.h index 992180cb86..9e890300dd 100644 --- a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_AudioStarterReset.h +++ b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_AudioStarterReset.h @@ -1,54 +1,54 @@ -/* RS Starter Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonRSE_AudioStarterReset_H -#define PokemonAutomation_PokemonRSE_AudioStarterReset_H - -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -class AudioStarterReset_Descriptor : public SingleSwitchProgramDescriptor{ -public: - AudioStarterReset_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class AudioStarterReset : public SingleSwitchProgramInstance{ -public: - AudioStarterReset(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - virtual void start_program_border_check( - VideoStream& stream, - FeedbackType feedback_type - ) override{} - -private: - enum class Target{ - treecko, - torchic, - mudkip, - }; - EnumDropdownOption TARGET; - - EventNotificationOption NOTIFICATION_SHINY_POOCH; - EventNotificationOption NOTIFICATION_SHINY_STARTER; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - -} -} -} -#endif - - - +/* RS Starter Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonRSE_AudioStarterReset_H +#define PokemonAutomation_PokemonRSE_AudioStarterReset_H + +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +class AudioStarterReset_Descriptor : public SingleSwitchProgramDescriptor{ +public: + AudioStarterReset_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class AudioStarterReset : public SingleSwitchProgramInstance{ +public: + AudioStarterReset(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + virtual void start_program_border_check( + VideoStream& stream, + FeedbackType feedback_type + ) override{} + +private: + enum class Target{ + treecko, + torchic, + mudkip, + }; + EnumDropdownOption TARGET; + + EventNotificationOption NOTIFICATION_SHINY_POOCH; + EventNotificationOption NOTIFICATION_SHINY_STARTER; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_LegendaryHunt-Emerald.cpp b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_LegendaryHunt-Emerald.cpp index 30336c3e7c..ea6a6b31cc 100644 --- a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_LegendaryHunt-Emerald.cpp +++ b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_LegendaryHunt-Emerald.cpp @@ -1,530 +1,530 @@ -/* Legendary Hunt - Emerald - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "Pokemon/Pokemon_Strings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h" -#include "PokemonRSE/PokemonRSE_Navigation.h" -#include "PokemonRSE_LegendaryHunt-Emerald.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -LegendaryHuntEmerald_Descriptor::LegendaryHuntEmerald_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonRSE:LegendaryHuntEmerald", - Pokemon::STRING_POKEMON + " RSE", "Legendary Hunt (Emerald)", - "ComputerControl/blob/master/Wiki/Programs/PokemonRSE/LegendaryHuntEmerald.md", - "Use the Run Away method to shiny hunt legendaries in Emerald.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} - -struct LegendaryHuntEmerald_Descriptor::Stats : public StatsTracker{ - Stats() - : resets(m_stats["Resets"]) - , shinies(m_stats["Shinies"]) - { - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Shinies"); - } - std::atomic& resets; - std::atomic& shinies; -}; -std::unique_ptr LegendaryHuntEmerald_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -LegendaryHuntEmerald::LegendaryHuntEmerald() - : TARGET( - "Target:
", - { - {Target::regis, "regis", "Regirock/Regice/Registeel"}, - {Target::groudon, "groudon", "Groudon"}, - {Target::kyogre, "kyogre", "Kyogre"}, - {Target::hooh, "hooh", "Ho-Oh"}, - {Target::lugia, "lugia", "Lugia"}, - }, - LockMode::LOCK_WHILE_RUNNING, - Target::regis - ) - , NOTIFICATION_SHINY( - "Shiny Found", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_SHINY, - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(TARGET); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void LegendaryHuntEmerald::reset_regi(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - //turn around, walk down 4/until black screen over - BlackScreenOverWatcher exit_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - BlackScreenOverWatcher enter_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - ssf_press_button(context, BUTTON_B, 0, 120); - pbf_press_dpad(context, DPAD_DOWN, 120, 20); - pbf_wait(context, 300); - }, - {exit_area} - ); - context.wait_for_all_requests(); - if (ret != 0){ - env.log("Failed to exit area.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to exit area.", - env.console - ); - } - else { - env.log("Left area."); - } - pbf_wait(context, 50); - context.wait_for_all_requests(); - - //turn around, up one/black screen over - int ret2 = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_press_dpad(context, DPAD_UP, 120, 20); - pbf_wait(context, 300); - }, - {enter_area} - ); - context.wait_for_all_requests(); - if (ret2 != 0){ - env.log("Failed to enter area.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to enter area.", - env.console - ); - } - else { - env.log("Entered area."); - } - - //walk back up to the regi - ssf_press_button(context, BUTTON_B, 0, 60); - pbf_press_dpad(context, DPAD_UP, 60, 20); - - context.wait_for_all_requests(); -} - -void LegendaryHuntEmerald::reset_groudon(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - //Turn left. Take 10 steps. - ssf_press_button(context, BUTTON_B, 0, 180); - pbf_press_dpad(context, DPAD_LEFT, 180, 20); - - //Turn up. Take 14 steps. (Bump into wall.) - ssf_press_button(context, BUTTON_B, 0, 240); - pbf_press_dpad(context, DPAD_UP, 240, 20); - - //Turn right. Take 2 steps. - ssf_press_button(context, BUTTON_B, 0, 40); - pbf_press_dpad(context, DPAD_RIGHT, 40, 20); - - //Turn up. Take 8 steps (Bump into wall.) - ssf_press_button(context, BUTTON_B, 0, 140); - pbf_press_dpad(context, DPAD_UP, 140, 20); - - //Turn left. Take 4 steps. - ssf_press_button(context, BUTTON_B, 0, 80); - pbf_press_dpad(context, DPAD_LEFT, 80, 20); - context.wait_for_all_requests(); - - //Turn down. Exit. Black screen over. - BlackScreenOverWatcher exit_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - ssf_press_button(context, BUTTON_B, 0, 90); - pbf_press_dpad(context, DPAD_DOWN, 90, 20); - pbf_wait(context, 300); - }, - {exit_area} - ); - context.wait_for_all_requests(); - if (ret != 0){ - env.log("Failed to exit area.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to exit area.", - env.console - ); - } - else { - env.log("Left area."); - } - - //Reverse above steps. - BlackScreenOverWatcher enter_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - int ret2 = run_until( - env.console, context, - [](ProControllerContext& context){ - ssf_press_button(context, BUTTON_B, 0, 90); - pbf_press_dpad(context, DPAD_UP, 90, 20); - pbf_wait(context, 300); - }, - {enter_area} - ); - context.wait_for_all_requests(); - if (ret2 != 0){ - env.log("Failed to enter area.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to enter area.", - env.console - ); - } - else { - env.log("Entered area."); - } - ssf_press_button(context, BUTTON_B, 0, 80); - pbf_press_dpad(context, DPAD_RIGHT, 80, 20); - - ssf_press_button(context, BUTTON_B, 0, 140); - pbf_press_dpad(context, DPAD_DOWN, 140, 20); - - ssf_press_button(context, BUTTON_B, 0, 40); - pbf_press_dpad(context, DPAD_LEFT, 40, 20); - - ssf_press_button(context, BUTTON_B, 0, 240); - pbf_press_dpad(context, DPAD_DOWN, 240, 20); - - ssf_press_button(context, BUTTON_B, 0, 180); - pbf_press_dpad(context, DPAD_RIGHT, 180, 20); - - context.wait_for_all_requests(); -} - -void LegendaryHuntEmerald::reset_kyogre(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - //Turn down. Take 1 step. - ssf_press_button(context, BUTTON_B, 0, 20); - pbf_press_dpad(context, DPAD_DOWN, 20, 20); - - //Turn right. Take 9 steps. - ssf_press_button(context, BUTTON_B, 0, 160); - pbf_press_dpad(context, DPAD_RIGHT, 160, 20); - - //Turn up. 13 steps. Wall. - ssf_press_button(context, BUTTON_B, 0, 220); - pbf_press_dpad(context, DPAD_UP, 220, 20); - - //Turn left. 4 steps. Wall. - ssf_press_button(context, BUTTON_B, 0, 80); - pbf_press_dpad(context, DPAD_LEFT, 80, 20); - - //Turn up. 10 steps. - ssf_press_button(context, BUTTON_B, 0, 180); - pbf_press_dpad(context, DPAD_UP, 180, 20); - - //Turn right. 6 steps. - ssf_press_button(context, BUTTON_B, 0, 110); - pbf_press_dpad(context, DPAD_RIGHT, 110, 20); - - //Turn down. Exit. Black screen over. - BlackScreenOverWatcher exit_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - ssf_press_button(context, BUTTON_B, 0, 90); - pbf_press_dpad(context, DPAD_DOWN, 90, 20); - pbf_wait(context, 300); - }, - {exit_area} - ); - context.wait_for_all_requests(); - if (ret != 0){ - env.log("Failed to exit area.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to exit area.", - env.console - ); - } - else { - env.log("Left area."); - } - - BlackScreenOverWatcher enter_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - int ret2 = run_until( - env.console, context, - [](ProControllerContext& context){ - ssf_press_button(context, BUTTON_B, 0, 90); - pbf_press_dpad(context, DPAD_UP, 90, 20); - pbf_wait(context, 300); - }, - {enter_area} - ); - context.wait_for_all_requests(); - if (ret2 != 0){ - env.log("Failed to enter area.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to enter area.", - env.console - ); - } - else { - env.log("Entered area."); - } - - ssf_press_button(context, BUTTON_B, 0, 110); - pbf_press_dpad(context, DPAD_LEFT, 110, 20); - - ssf_press_button(context, BUTTON_B, 0, 180); - pbf_press_dpad(context, DPAD_DOWN, 180, 20); - - ssf_press_button(context, BUTTON_B, 0, 80); - pbf_press_dpad(context, DPAD_RIGHT, 80, 20); - - ssf_press_button(context, BUTTON_B, 0, 220); - pbf_press_dpad(context, DPAD_DOWN, 220, 20); - - ssf_press_button(context, BUTTON_B, 0, 160); - pbf_press_dpad(context, DPAD_LEFT, 160, 20); - - ssf_press_button(context, BUTTON_B, 0, 20); - pbf_press_dpad(context, DPAD_UP, 20, 20); - - context.wait_for_all_requests(); -} - -void LegendaryHuntEmerald::reset_hooh(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - BlackScreenOverWatcher exit_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - //Turn around, 10 steps down - ssf_press_button(context, BUTTON_B, 0, 180); - pbf_press_dpad(context, DPAD_DOWN, 180, 20); - - //Turn right, take 1 step. Wait for black screen over. - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - ssf_press_button(context, BUTTON_B, 0, 30); - pbf_press_dpad(context, DPAD_RIGHT, 30, 20); - pbf_wait(context, 300); - }, - {exit_area} - ); - context.wait_for_all_requests(); - if (ret != 0){ - env.log("Failed to exit area.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to exit area.", - env.console - ); - } - else { - env.log("Left area."); - } - - BlackScreenOverWatcher enter_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - //turn left, take one step. now turn back right and take a step. wait for black screen over. - int ret2 = run_until( - env.console, context, - [](ProControllerContext& context){ - ssf_press_button(context, BUTTON_B, 0, 40); - pbf_press_dpad(context, DPAD_LEFT, 40, 20); - - ssf_press_button(context, BUTTON_B, 0, 40); - pbf_press_dpad(context, DPAD_RIGHT, 40, 20); - pbf_wait(context, 300); - }, - {enter_area} - ); - context.wait_for_all_requests(); - if (ret2 != 0){ - env.log("Failed to enter area.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to enter area.", - env.console - ); - } - else { - env.log("Entered area."); - } - - //reverse above steps, but only take 9 steps up - //doesn't really matter since we want to trigger the encounter anyway - ssf_press_button(context, BUTTON_B, 0, 30); - pbf_press_dpad(context, DPAD_LEFT, 30, 20); - - ssf_press_button(context, BUTTON_B, 0, 170); - pbf_press_dpad(context, DPAD_UP, 170, 20); - - context.wait_for_all_requests(); -} - -void LegendaryHuntEmerald::reset_lugia(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - BlackScreenOverWatcher exit_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - //Turn around, 5 steps down - ssf_press_button(context, BUTTON_B, 0, 90); - pbf_press_dpad(context, DPAD_DOWN, 90, 20); - - //Turn right, 3 steps right. Wait for black screen over. - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - ssf_press_button(context, BUTTON_B, 0, 90); - pbf_press_dpad(context, DPAD_RIGHT, 90, 20); - pbf_wait(context, 300); - }, - {exit_area} - ); - context.wait_for_all_requests(); - if (ret != 0){ - env.log("Failed to exit area.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to exit area.", - env.console - ); - } - else { - env.log("Left area."); - } - - BlackScreenOverWatcher enter_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - //turn up, take one step. then turn back down and take a step. wait for black screen over. - int ret2 = run_until( - env.console, context, - [](ProControllerContext& context){ - ssf_press_button(context, BUTTON_B, 0, 40); - pbf_press_dpad(context, DPAD_UP, 40, 20); - - ssf_press_button(context, BUTTON_B, 0, 40); - pbf_press_dpad(context, DPAD_DOWN, 40, 20); - pbf_wait(context, 300); - }, - {enter_area} - ); - context.wait_for_all_requests(); - if (ret2 != 0){ - env.log("Failed to enter area.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to enter area.", - env.console - ); - } - else { - env.log("Entered area."); - } - - //reverse above steps - ssf_press_button(context, BUTTON_B, 0, 70); - pbf_press_dpad(context, DPAD_LEFT, 70, 20); - - ssf_press_button(context, BUTTON_B, 0, 90); - pbf_press_dpad(context, DPAD_UP, 90, 20); - - context.wait_for_all_requests(); -} - -void LegendaryHuntEmerald::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - LegendaryHuntEmerald_Descriptor::Stats& stats = env.current_stats(); - - /* - * Text speed fast, battle animations off - * smoke ball or fast pokemon req. no entry effects. - * - * Don't need to worry about PokeNav or random encounters for any of these targets. - * - * Stand in front of Regis/Ho-Oh/Lugia. Save the game. - */ - - while (true) { - switch (TARGET) { - case Target::hooh: - case Target::kyogre: - case Target::groudon: - //Step forward to start the encounter. - pbf_press_dpad(context, DPAD_UP, 20, 50); - break; - //case Target::groudon: //Step up is easier. - // pbf_press_dpad(context, DPAD_RIGHT, 20, 50); - // break; - //case Target::kyogre: - // pbf_press_dpad(context, DPAD_LEFT, 20, 50); - // break; - default:; - } - //handle_encounter presses A already for everything else - - bool legendary_shiny = handle_encounter(env.console, context, true); - if (legendary_shiny) { - stats.shinies++; - env.update_stats(); - send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", env.console.video().snapshot(), true); - break; - } - env.log("No shiny found."); - flee_battle(env.console, context); - - //Close out dialog box - pbf_mash_button(context, BUTTON_B, 250); - context.wait_for_all_requests(); - - //Exit and re-enter the room - switch (TARGET) { - case Target::regis: - reset_regi(env, context); - break; - case Target::groudon: - reset_groudon(env, context); - break; - case Target::kyogre: - reset_kyogre(env, context); - break; - case Target::hooh: - reset_hooh(env, context); - break; - case Target::lugia: - reset_lugia(env, context); - break; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Invalid target!", - env.console - ); - break; - } - - stats.resets++; - env.update_stats(); - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - -} -} -} +/* Legendary Hunt - Emerald + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "Pokemon/Pokemon_Strings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h" +#include "PokemonRSE/PokemonRSE_Navigation.h" +#include "PokemonRSE_LegendaryHunt-Emerald.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +LegendaryHuntEmerald_Descriptor::LegendaryHuntEmerald_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonRSE:LegendaryHuntEmerald", + Pokemon::STRING_POKEMON + " RSE", "Legendary Hunt (Emerald)", + "ComputerControl/blob/master/Wiki/Programs/PokemonRSE/LegendaryHuntEmerald.md", + "Use the Run Away method to shiny hunt legendaries in Emerald.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} + +struct LegendaryHuntEmerald_Descriptor::Stats : public StatsTracker{ + Stats() + : resets(m_stats["Resets"]) + , shinies(m_stats["Shinies"]) + { + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Shinies"); + } + std::atomic& resets; + std::atomic& shinies; +}; +std::unique_ptr LegendaryHuntEmerald_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +LegendaryHuntEmerald::LegendaryHuntEmerald() + : TARGET( + "Target:
", + { + {Target::regis, "regis", "Regirock/Regice/Registeel"}, + {Target::groudon, "groudon", "Groudon"}, + {Target::kyogre, "kyogre", "Kyogre"}, + {Target::hooh, "hooh", "Ho-Oh"}, + {Target::lugia, "lugia", "Lugia"}, + }, + LockMode::LOCK_WHILE_RUNNING, + Target::regis + ) + , NOTIFICATION_SHINY( + "Shiny Found", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_SHINY, + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(TARGET); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void LegendaryHuntEmerald::reset_regi(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + //turn around, walk down 4/until black screen over + BlackScreenOverWatcher exit_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + BlackScreenOverWatcher enter_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + ssf_press_button(context, BUTTON_B, 0ms, 960ms); + pbf_press_dpad(context, DPAD_DOWN, 120, 20); + pbf_wait(context, 300); + }, + {exit_area} + ); + context.wait_for_all_requests(); + if (ret != 0){ + env.log("Failed to exit area.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to exit area.", + env.console + ); + } + else { + env.log("Left area."); + } + pbf_wait(context, 50); + context.wait_for_all_requests(); + + //turn around, up one/black screen over + int ret2 = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_press_dpad(context, DPAD_UP, 120, 20); + pbf_wait(context, 300); + }, + {enter_area} + ); + context.wait_for_all_requests(); + if (ret2 != 0){ + env.log("Failed to enter area.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to enter area.", + env.console + ); + } + else { + env.log("Entered area."); + } + + //walk back up to the regi + ssf_press_button(context, BUTTON_B, 0ms, 480ms); + pbf_press_dpad(context, DPAD_UP, 60, 20); + + context.wait_for_all_requests(); +} + +void LegendaryHuntEmerald::reset_groudon(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + //Turn left. Take 10 steps. + ssf_press_button(context, BUTTON_B, 0ms, 1440ms); + pbf_press_dpad(context, DPAD_LEFT, 180, 20); + + //Turn up. Take 14 steps. (Bump into wall.) + ssf_press_button(context, BUTTON_B, 0ms, 1920ms); + pbf_press_dpad(context, DPAD_UP, 240, 20); + + //Turn right. Take 2 steps. + ssf_press_button(context, BUTTON_B, 0ms, 320ms); + pbf_press_dpad(context, DPAD_RIGHT, 40, 20); + + //Turn up. Take 8 steps (Bump into wall.) + ssf_press_button(context, BUTTON_B, 0ms, 1120ms); + pbf_press_dpad(context, DPAD_UP, 140, 20); + + //Turn left. Take 4 steps. + ssf_press_button(context, BUTTON_B, 0ms, 640ms); + pbf_press_dpad(context, DPAD_LEFT, 80, 20); + context.wait_for_all_requests(); + + //Turn down. Exit. Black screen over. + BlackScreenOverWatcher exit_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + ssf_press_button(context, BUTTON_B, 0ms, 720ms); + pbf_press_dpad(context, DPAD_DOWN, 90, 20); + pbf_wait(context, 300); + }, + {exit_area} + ); + context.wait_for_all_requests(); + if (ret != 0){ + env.log("Failed to exit area.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to exit area.", + env.console + ); + } + else { + env.log("Left area."); + } + + //Reverse above steps. + BlackScreenOverWatcher enter_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + int ret2 = run_until( + env.console, context, + [](ProControllerContext& context){ + ssf_press_button(context, BUTTON_B, 0ms, 720ms); + pbf_press_dpad(context, DPAD_UP, 90, 20); + pbf_wait(context, 300); + }, + {enter_area} + ); + context.wait_for_all_requests(); + if (ret2 != 0){ + env.log("Failed to enter area.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to enter area.", + env.console + ); + } + else { + env.log("Entered area."); + } + ssf_press_button(context, BUTTON_B, 0ms, 640ms); + pbf_press_dpad(context, DPAD_RIGHT, 80, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 1120ms); + pbf_press_dpad(context, DPAD_DOWN, 140, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 320ms); + pbf_press_dpad(context, DPAD_LEFT, 40, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 1920ms); + pbf_press_dpad(context, DPAD_DOWN, 240, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 1440ms); + pbf_press_dpad(context, DPAD_RIGHT, 180, 20); + + context.wait_for_all_requests(); +} + +void LegendaryHuntEmerald::reset_kyogre(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + //Turn down. Take 1 step. + ssf_press_button(context, BUTTON_B, 0ms, 160ms); + pbf_press_dpad(context, DPAD_DOWN, 20, 20); + + //Turn right. Take 9 steps. + ssf_press_button(context, BUTTON_B, 0ms, 1280ms); + pbf_press_dpad(context, DPAD_RIGHT, 160, 20); + + //Turn up. 13 steps. Wall. + ssf_press_button(context, BUTTON_B, 0ms, 1760ms); + pbf_press_dpad(context, DPAD_UP, 220, 20); + + //Turn left. 4 steps. Wall. + ssf_press_button(context, BUTTON_B, 0ms, 640ms); + pbf_press_dpad(context, DPAD_LEFT, 80, 20); + + //Turn up. 10 steps. + ssf_press_button(context, BUTTON_B, 0ms, 1440ms); + pbf_press_dpad(context, DPAD_UP, 180, 20); + + //Turn right. 6 steps. + ssf_press_button(context, BUTTON_B, 0ms, 880ms); + pbf_press_dpad(context, DPAD_RIGHT, 110, 20); + + //Turn down. Exit. Black screen over. + BlackScreenOverWatcher exit_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + ssf_press_button(context, BUTTON_B, 0ms, 720ms); + pbf_press_dpad(context, DPAD_DOWN, 90, 20); + pbf_wait(context, 300); + }, + {exit_area} + ); + context.wait_for_all_requests(); + if (ret != 0){ + env.log("Failed to exit area.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to exit area.", + env.console + ); + } + else { + env.log("Left area."); + } + + BlackScreenOverWatcher enter_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + int ret2 = run_until( + env.console, context, + [](ProControllerContext& context){ + ssf_press_button(context, BUTTON_B, 0ms, 720ms); + pbf_press_dpad(context, DPAD_UP, 90, 20); + pbf_wait(context, 300); + }, + {enter_area} + ); + context.wait_for_all_requests(); + if (ret2 != 0){ + env.log("Failed to enter area.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to enter area.", + env.console + ); + } + else { + env.log("Entered area."); + } + + ssf_press_button(context, BUTTON_B, 0ms, 880ms); + pbf_press_dpad(context, DPAD_LEFT, 110, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 1440ms); + pbf_press_dpad(context, DPAD_DOWN, 180, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 640ms); + pbf_press_dpad(context, DPAD_RIGHT, 80, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 1760ms); + pbf_press_dpad(context, DPAD_DOWN, 220, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 1280ms); + pbf_press_dpad(context, DPAD_LEFT, 160, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 160ms); + pbf_press_dpad(context, DPAD_UP, 20, 20); + + context.wait_for_all_requests(); +} + +void LegendaryHuntEmerald::reset_hooh(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + BlackScreenOverWatcher exit_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + //Turn around, 10 steps down + ssf_press_button(context, BUTTON_B, 0ms, 1440ms); + pbf_press_dpad(context, DPAD_DOWN, 180, 20); + + //Turn right, take 1 step. Wait for black screen over. + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + ssf_press_button(context, BUTTON_B, 0ms, 240ms); + pbf_press_dpad(context, DPAD_RIGHT, 30, 20); + pbf_wait(context, 300); + }, + {exit_area} + ); + context.wait_for_all_requests(); + if (ret != 0){ + env.log("Failed to exit area.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to exit area.", + env.console + ); + } + else { + env.log("Left area."); + } + + BlackScreenOverWatcher enter_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + //turn left, take one step. now turn back right and take a step. wait for black screen over. + int ret2 = run_until( + env.console, context, + [](ProControllerContext& context){ + ssf_press_button(context, BUTTON_B, 0ms, 320ms); + pbf_press_dpad(context, DPAD_LEFT, 40, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 320ms); + pbf_press_dpad(context, DPAD_RIGHT, 40, 20); + pbf_wait(context, 300); + }, + {enter_area} + ); + context.wait_for_all_requests(); + if (ret2 != 0){ + env.log("Failed to enter area.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to enter area.", + env.console + ); + } + else { + env.log("Entered area."); + } + + //reverse above steps, but only take 9 steps up + //doesn't really matter since we want to trigger the encounter anyway + ssf_press_button(context, BUTTON_B, 0ms, 240ms); + pbf_press_dpad(context, DPAD_LEFT, 30, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 1360ms); + pbf_press_dpad(context, DPAD_UP, 170, 20); + + context.wait_for_all_requests(); +} + +void LegendaryHuntEmerald::reset_lugia(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + BlackScreenOverWatcher exit_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + //Turn around, 5 steps down + ssf_press_button(context, BUTTON_B, 0ms, 720ms); + pbf_press_dpad(context, DPAD_DOWN, 90, 20); + + //Turn right, 3 steps right. Wait for black screen over. + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + ssf_press_button(context, BUTTON_B, 0ms, 720ms); + pbf_press_dpad(context, DPAD_RIGHT, 90, 20); + pbf_wait(context, 300); + }, + {exit_area} + ); + context.wait_for_all_requests(); + if (ret != 0){ + env.log("Failed to exit area.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to exit area.", + env.console + ); + } + else { + env.log("Left area."); + } + + BlackScreenOverWatcher enter_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + //turn up, take one step. then turn back down and take a step. wait for black screen over. + int ret2 = run_until( + env.console, context, + [](ProControllerContext& context){ + ssf_press_button(context, BUTTON_B, 0ms, 320ms); + pbf_press_dpad(context, DPAD_UP, 40, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 320ms); + pbf_press_dpad(context, DPAD_DOWN, 40, 20); + pbf_wait(context, 300); + }, + {enter_area} + ); + context.wait_for_all_requests(); + if (ret2 != 0){ + env.log("Failed to enter area.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to enter area.", + env.console + ); + } + else { + env.log("Entered area."); + } + + //reverse above steps + ssf_press_button(context, BUTTON_B, 0ms, 560ms); + pbf_press_dpad(context, DPAD_LEFT, 70, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 720ms); + pbf_press_dpad(context, DPAD_UP, 90, 20); + + context.wait_for_all_requests(); +} + +void LegendaryHuntEmerald::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + LegendaryHuntEmerald_Descriptor::Stats& stats = env.current_stats(); + + /* + * Text speed fast, battle animations off + * smoke ball or fast pokemon req. no entry effects. + * + * Don't need to worry about PokeNav or random encounters for any of these targets. + * + * Stand in front of Regis/Ho-Oh/Lugia. Save the game. + */ + + while (true) { + switch (TARGET) { + case Target::hooh: + case Target::kyogre: + case Target::groudon: + //Step forward to start the encounter. + pbf_press_dpad(context, DPAD_UP, 20, 50); + break; + //case Target::groudon: //Step up is easier. + // pbf_press_dpad(context, DPAD_RIGHT, 20, 50); + // break; + //case Target::kyogre: + // pbf_press_dpad(context, DPAD_LEFT, 20, 50); + // break; + default:; + } + //handle_encounter presses A already for everything else + + bool legendary_shiny = handle_encounter(env.console, context, true); + if (legendary_shiny) { + stats.shinies++; + env.update_stats(); + send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", env.console.video().snapshot(), true); + break; + } + env.log("No shiny found."); + flee_battle(env.console, context); + + //Close out dialog box + pbf_mash_button(context, BUTTON_B, 250); + context.wait_for_all_requests(); + + //Exit and re-enter the room + switch (TARGET) { + case Target::regis: + reset_regi(env, context); + break; + case Target::groudon: + reset_groudon(env, context); + break; + case Target::kyogre: + reset_kyogre(env, context); + break; + case Target::hooh: + reset_hooh(env, context); + break; + case Target::lugia: + reset_lugia(env, context); + break; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Invalid target!", + env.console + ); + break; + } + + stats.resets++; + env.update_stats(); + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_LegendaryHunt-Emerald.h b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_LegendaryHunt-Emerald.h index 6642058a6f..1409ef1d5e 100644 --- a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_LegendaryHunt-Emerald.h +++ b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_LegendaryHunt-Emerald.h @@ -1,61 +1,61 @@ -/* Legendary Hunt - Emerald - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonRSE_LegendaryHuntEmerald_H -#define PokemonAutomation_PokemonRSE_LegendaryHuntEmerald_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/TimeExpressionOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -class LegendaryHuntEmerald_Descriptor : public SingleSwitchProgramDescriptor{ -public: - LegendaryHuntEmerald_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class LegendaryHuntEmerald : public SingleSwitchProgramInstance{ -public: - LegendaryHuntEmerald(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - virtual void start_program_border_check( - VideoStream& stream, - FeedbackType feedback_type - ) override{} - -private: - enum class Target{ - regis, - groudon, - kyogre, - hooh, - lugia, - }; - EnumDropdownOption TARGET; - - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; - - void reset_regi(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void reset_groudon(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void reset_kyogre(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void reset_hooh(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void reset_lugia(SingleSwitchProgramEnvironment& env, ProControllerContext& context); -}; - -} -} -} -#endif - +/* Legendary Hunt - Emerald + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonRSE_LegendaryHuntEmerald_H +#define PokemonAutomation_PokemonRSE_LegendaryHuntEmerald_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/TimeExpressionOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +class LegendaryHuntEmerald_Descriptor : public SingleSwitchProgramDescriptor{ +public: + LegendaryHuntEmerald_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class LegendaryHuntEmerald : public SingleSwitchProgramInstance{ +public: + LegendaryHuntEmerald(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + virtual void start_program_border_check( + VideoStream& stream, + FeedbackType feedback_type + ) override{} + +private: + enum class Target{ + regis, + groudon, + kyogre, + hooh, + lugia, + }; + EnumDropdownOption TARGET; + + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; + + void reset_regi(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void reset_groudon(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void reset_kyogre(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void reset_hooh(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void reset_lugia(SingleSwitchProgramEnvironment& env, ProControllerContext& context); +}; + +} +} +} +#endif + diff --git a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Deoxys.cpp b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Deoxys.cpp index cbd41e73a3..e2c81d35a0 100644 --- a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Deoxys.cpp +++ b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Deoxys.cpp @@ -1,279 +1,279 @@ -/* E Shiny Deoxys - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "Pokemon/Pokemon_Strings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h" -#include "PokemonRSE/PokemonRSE_Navigation.h" -#include "PokemonRSE_ShinyHunt-Deoxys.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -ShinyHuntDeoxys_Descriptor::ShinyHuntDeoxys_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonRSE:ShinyHuntDeoxys", - Pokemon::STRING_POKEMON + " RSE", "Shiny Hunt - Deoxys", - "ComputerControl/blob/master/Wiki/Programs/PokemonRSE/ShinyHuntDeoxys.md", - "Use the Run Away method to shiny hunt Deoxys in Emerald.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} - -struct ShinyHuntDeoxys_Descriptor::Stats : public StatsTracker{ - Stats() - : resets(m_stats["Resets"]) - , shinies(m_stats["Shinies"]) - { - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Shinies"); - } - std::atomic& resets; - std::atomic& shinies; -}; -std::unique_ptr ShinyHuntDeoxys_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -ShinyHuntDeoxys::ShinyHuntDeoxys() - : STARTPOS( - "Starting Position:
", - { - {StartPos::boat, "boat", "Boat/Walk up"}, - {StartPos::rock_unsolved, "rock_unsolved", "Triangle rock, puzzle is unsolved"}, - {StartPos::rock_solved, "rock_solved", "Triangle rock, puzzle is already solved"}, - }, - LockMode::LOCK_WHILE_RUNNING, - StartPos::rock_unsolved - ) - , WALK_UP_DOWN_TIME0( - "Walk up/down time
Spend this long to run up to the triangle rock.", - LockMode::LOCK_WHILE_RUNNING, - "3520 ms" - ) - , NOTIFICATION_SHINY( - "Shiny Found", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_SHINY, - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(STARTPOS); - PA_ADD_OPTION(WALK_UP_DOWN_TIME0); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void ShinyHuntDeoxys::solve_puzzle(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - env.log("Step 1: Press A from below."); - pbf_press_button(context, BUTTON_A, 20, 40); - - env.log("Step 2: 5 Left, 1 Down."); - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - - pbf_press_dpad(context, DPAD_DOWN, 10, 80); - - pbf_press_button(context, BUTTON_A, 20, 40); - context.wait_for_all_requests(); - - env.log("Step 3: 5 Right, 5 Up."); - pbf_press_dpad(context, DPAD_RIGHT, 10, 50); - pbf_press_dpad(context, DPAD_RIGHT, 10, 50); - pbf_press_dpad(context, DPAD_RIGHT, 10, 50); - pbf_press_dpad(context, DPAD_RIGHT, 10, 50); - pbf_press_dpad(context, DPAD_RIGHT, 10, 50); - - ssf_press_button(context, BUTTON_B, 0, 90); - pbf_press_dpad(context, DPAD_UP, 90, 50); - - pbf_press_button(context, BUTTON_A, 20, 40); - context.wait_for_all_requests(); - - env.log("Step 4: 5 Right, 5 Down"); - pbf_press_dpad(context, DPAD_RIGHT, 10, 50); - pbf_press_dpad(context, DPAD_RIGHT, 10, 50); - pbf_press_dpad(context, DPAD_RIGHT, 10, 50); - pbf_press_dpad(context, DPAD_RIGHT, 10, 50); - pbf_press_dpad(context, DPAD_RIGHT, 10, 50); - - ssf_press_button(context, BUTTON_B, 0, 90); - pbf_press_dpad(context, DPAD_DOWN, 90, 50); - - pbf_press_button(context, BUTTON_A, 20, 40); - context.wait_for_all_requests(); - - env.log("Step 5: 3 Up, 7 Left"); - pbf_press_dpad(context, DPAD_UP, 10, 50); - pbf_press_dpad(context, DPAD_UP, 10, 50); - pbf_press_dpad(context, DPAD_UP, 10, 50); - - ssf_press_button(context, BUTTON_B, 0, 115); - pbf_press_dpad(context, DPAD_LEFT, 115, 50); - - pbf_press_button(context, BUTTON_A, 20, 40); - context.wait_for_all_requests(); - - env.log("Step 6: 5 Right."); - ssf_press_button(context, BUTTON_B, 0, 100); - pbf_press_dpad(context, DPAD_RIGHT, 100, 50); - - pbf_press_button(context, BUTTON_A, 20, 40); - context.wait_for_all_requests(); - - env.log("Step 7: 3 Left, 2 Down."); - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - - ssf_press_button(context, BUTTON_B, 0, 60); - pbf_press_dpad(context, DPAD_DOWN, 60, 50); - - pbf_press_button(context, BUTTON_A, 20, 40); - context.wait_for_all_requests(); - - env.log("Step 8: 1 Down, 4 Left."); - pbf_press_dpad(context, DPAD_DOWN, 10, 50); - - ssf_press_button(context, BUTTON_B, 0, 80); - pbf_press_dpad(context, DPAD_LEFT, 80, 50); - - pbf_press_button(context, BUTTON_A, 20, 40); - context.wait_for_all_requests(); - - env.log("Step 8: 7 Right."); - ssf_press_button(context, BUTTON_B, 0, 115); - pbf_press_dpad(context, DPAD_RIGHT, 115, 50); - - pbf_press_button(context, BUTTON_A, 20, 40); - context.wait_for_all_requests(); - - env.log("Step 9: 4 Left, Down 1."); - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - - pbf_press_dpad(context, DPAD_DOWN, 10, 50); - - pbf_press_button(context, BUTTON_A, 20, 40); - context.wait_for_all_requests(); - - env.log("Step 10: 4 Up."); - ssf_press_button(context, BUTTON_B, 0, 80); - pbf_press_dpad(context, DPAD_UP, 80, 80); - context.wait_for_all_requests(); -} - -void ShinyHuntDeoxys::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - ShinyHuntDeoxys_Descriptor::Stats& stats = env.current_stats(); - - /* - * Settings: Text Speed fast. Turn off animations. - * Full screen, no filter. - * If on a retro handheld, make sure the screen matches that of NSO+. - * - * Setup: Lead is faster or has a Smoke Ball. - * No abilities or items that activate on entry. - * Lead cannot be shiny. - * Stand enter Birth Island and stay at the door. Save the game. - * - * Emerald only. This uses the Run Away method due to the game's RNG issues. - * If powering off your game/resetting, try to start with different timing to avoid repeated frames. - * - * Do not have to handle random PokeNav calls for deoxys/mew. - * Would have to handle both PokeNav and random encounters for ray/others? Why is PokeNav a thing??? - */ - - bool first_run = true; - - while (true) { - if (first_run) { - switch (STARTPOS) { - case StartPos::rock_solved: - env.log("StartPos: Already in position."); - break; - case StartPos::boat: - env.log("StartPos: Walking up to Deoxys."); - //Walk up to the triangle rock from the ship. No bike allowed. - ssf_press_button(context, BUTTON_B, 0ms, WALK_UP_DOWN_TIME0); - pbf_press_dpad(context, DPAD_UP, WALK_UP_DOWN_TIME0, 160ms); - context.wait_for_all_requests(); - case StartPos::rock_unsolved: - env.log("StartPos: Solving puzzle."); - solve_puzzle(env, context); - break; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Invalid starting position selected.", - env.console - ); - break; - } - first_run = false; - } - - //Start battle - bool legendary_shiny = handle_encounter(env.console, context, true); - if (legendary_shiny) { - stats.shinies++; - env.update_stats(); - send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", env.console.video().snapshot(), true); - break; - } - env.log("No shiny found."); - flee_battle(env.console, context); - - //After pressing the flee button, additional dialog box pops up for Deoxys - pbf_mash_button(context, BUTTON_B, 250); - context.wait_for_all_requests(); - - //Walk down from the triangle rock to the ship. - env.log("Walking down to ship."); - ssf_press_button(context, BUTTON_B, 0ms, WALK_UP_DOWN_TIME0); - pbf_press_dpad(context, DPAD_DOWN, WALK_UP_DOWN_TIME0, 160ms); - context.wait_for_all_requests(); - - env.log("Walking up to Deoxys rock."); - //Walk up to the triangle rock from the ship. Bike is not allowed on Birth Island. - ssf_press_button(context, BUTTON_B, 0ms, WALK_UP_DOWN_TIME0); - pbf_press_dpad(context, DPAD_UP, WALK_UP_DOWN_TIME0, 160ms); - context.wait_for_all_requests(); - - env.log("Solving puzzle."); - solve_puzzle(env, context); - - stats.resets++; - env.update_stats(); - } - - //switch - go home when done - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - -} -} -} +/* E Shiny Deoxys + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "Pokemon/Pokemon_Strings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h" +#include "PokemonRSE/PokemonRSE_Navigation.h" +#include "PokemonRSE_ShinyHunt-Deoxys.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +ShinyHuntDeoxys_Descriptor::ShinyHuntDeoxys_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonRSE:ShinyHuntDeoxys", + Pokemon::STRING_POKEMON + " RSE", "Shiny Hunt - Deoxys", + "ComputerControl/blob/master/Wiki/Programs/PokemonRSE/ShinyHuntDeoxys.md", + "Use the Run Away method to shiny hunt Deoxys in Emerald.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} + +struct ShinyHuntDeoxys_Descriptor::Stats : public StatsTracker{ + Stats() + : resets(m_stats["Resets"]) + , shinies(m_stats["Shinies"]) + { + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Shinies"); + } + std::atomic& resets; + std::atomic& shinies; +}; +std::unique_ptr ShinyHuntDeoxys_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +ShinyHuntDeoxys::ShinyHuntDeoxys() + : STARTPOS( + "Starting Position:
", + { + {StartPos::boat, "boat", "Boat/Walk up"}, + {StartPos::rock_unsolved, "rock_unsolved", "Triangle rock, puzzle is unsolved"}, + {StartPos::rock_solved, "rock_solved", "Triangle rock, puzzle is already solved"}, + }, + LockMode::LOCK_WHILE_RUNNING, + StartPos::rock_unsolved + ) + , WALK_UP_DOWN_TIME0( + "Walk up/down time
Spend this long to run up to the triangle rock.", + LockMode::LOCK_WHILE_RUNNING, + "3520 ms" + ) + , NOTIFICATION_SHINY( + "Shiny Found", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_SHINY, + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(STARTPOS); + PA_ADD_OPTION(WALK_UP_DOWN_TIME0); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void ShinyHuntDeoxys::solve_puzzle(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + env.log("Step 1: Press A from below."); + pbf_press_button(context, BUTTON_A, 20, 40); + + env.log("Step 2: 5 Left, 1 Down."); + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + + pbf_press_dpad(context, DPAD_DOWN, 10, 80); + + pbf_press_button(context, BUTTON_A, 20, 40); + context.wait_for_all_requests(); + + env.log("Step 3: 5 Right, 5 Up."); + pbf_press_dpad(context, DPAD_RIGHT, 10, 50); + pbf_press_dpad(context, DPAD_RIGHT, 10, 50); + pbf_press_dpad(context, DPAD_RIGHT, 10, 50); + pbf_press_dpad(context, DPAD_RIGHT, 10, 50); + pbf_press_dpad(context, DPAD_RIGHT, 10, 50); + + ssf_press_button(context, BUTTON_B, 0ms, 720ms); + pbf_press_dpad(context, DPAD_UP, 90, 50); + + pbf_press_button(context, BUTTON_A, 20, 40); + context.wait_for_all_requests(); + + env.log("Step 4: 5 Right, 5 Down"); + pbf_press_dpad(context, DPAD_RIGHT, 10, 50); + pbf_press_dpad(context, DPAD_RIGHT, 10, 50); + pbf_press_dpad(context, DPAD_RIGHT, 10, 50); + pbf_press_dpad(context, DPAD_RIGHT, 10, 50); + pbf_press_dpad(context, DPAD_RIGHT, 10, 50); + + ssf_press_button(context, BUTTON_B, 0ms, 720ms); + pbf_press_dpad(context, DPAD_DOWN, 90, 50); + + pbf_press_button(context, BUTTON_A, 20, 40); + context.wait_for_all_requests(); + + env.log("Step 5: 3 Up, 7 Left"); + pbf_press_dpad(context, DPAD_UP, 10, 50); + pbf_press_dpad(context, DPAD_UP, 10, 50); + pbf_press_dpad(context, DPAD_UP, 10, 50); + + ssf_press_button(context, BUTTON_B, 0ms, 920ms); + pbf_press_dpad(context, DPAD_LEFT, 115, 50); + + pbf_press_button(context, BUTTON_A, 20, 40); + context.wait_for_all_requests(); + + env.log("Step 6: 5 Right."); + ssf_press_button(context, BUTTON_B, 0ms, 800ms); + pbf_press_dpad(context, DPAD_RIGHT, 100, 50); + + pbf_press_button(context, BUTTON_A, 20, 40); + context.wait_for_all_requests(); + + env.log("Step 7: 3 Left, 2 Down."); + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + + ssf_press_button(context, BUTTON_B, 0ms, 480ms); + pbf_press_dpad(context, DPAD_DOWN, 60, 50); + + pbf_press_button(context, BUTTON_A, 20, 40); + context.wait_for_all_requests(); + + env.log("Step 8: 1 Down, 4 Left."); + pbf_press_dpad(context, DPAD_DOWN, 10, 50); + + ssf_press_button(context, BUTTON_B, 0ms, 640ms); + pbf_press_dpad(context, DPAD_LEFT, 80, 50); + + pbf_press_button(context, BUTTON_A, 20, 40); + context.wait_for_all_requests(); + + env.log("Step 8: 7 Right."); + ssf_press_button(context, BUTTON_B, 0ms, 920ms); + pbf_press_dpad(context, DPAD_RIGHT, 115, 50); + + pbf_press_button(context, BUTTON_A, 20, 40); + context.wait_for_all_requests(); + + env.log("Step 9: 4 Left, Down 1."); + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + + pbf_press_dpad(context, DPAD_DOWN, 10, 50); + + pbf_press_button(context, BUTTON_A, 20, 40); + context.wait_for_all_requests(); + + env.log("Step 10: 4 Up."); + ssf_press_button(context, BUTTON_B, 0ms, 640ms); + pbf_press_dpad(context, DPAD_UP, 80, 80); + context.wait_for_all_requests(); +} + +void ShinyHuntDeoxys::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + ShinyHuntDeoxys_Descriptor::Stats& stats = env.current_stats(); + + /* + * Settings: Text Speed fast. Turn off animations. + * Full screen, no filter. + * If on a retro handheld, make sure the screen matches that of NSO+. + * + * Setup: Lead is faster or has a Smoke Ball. + * No abilities or items that activate on entry. + * Lead cannot be shiny. + * Stand enter Birth Island and stay at the door. Save the game. + * + * Emerald only. This uses the Run Away method due to the game's RNG issues. + * If powering off your game/resetting, try to start with different timing to avoid repeated frames. + * + * Do not have to handle random PokeNav calls for deoxys/mew. + * Would have to handle both PokeNav and random encounters for ray/others? Why is PokeNav a thing??? + */ + + bool first_run = true; + + while (true) { + if (first_run) { + switch (STARTPOS) { + case StartPos::rock_solved: + env.log("StartPos: Already in position."); + break; + case StartPos::boat: + env.log("StartPos: Walking up to Deoxys."); + //Walk up to the triangle rock from the ship. No bike allowed. + ssf_press_button(context, BUTTON_B, 0ms, WALK_UP_DOWN_TIME0); + pbf_press_dpad(context, DPAD_UP, WALK_UP_DOWN_TIME0, 160ms); + context.wait_for_all_requests(); + case StartPos::rock_unsolved: + env.log("StartPos: Solving puzzle."); + solve_puzzle(env, context); + break; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Invalid starting position selected.", + env.console + ); + break; + } + first_run = false; + } + + //Start battle + bool legendary_shiny = handle_encounter(env.console, context, true); + if (legendary_shiny) { + stats.shinies++; + env.update_stats(); + send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", env.console.video().snapshot(), true); + break; + } + env.log("No shiny found."); + flee_battle(env.console, context); + + //After pressing the flee button, additional dialog box pops up for Deoxys + pbf_mash_button(context, BUTTON_B, 250); + context.wait_for_all_requests(); + + //Walk down from the triangle rock to the ship. + env.log("Walking down to ship."); + ssf_press_button(context, BUTTON_B, 0ms, WALK_UP_DOWN_TIME0); + pbf_press_dpad(context, DPAD_DOWN, WALK_UP_DOWN_TIME0, 160ms); + context.wait_for_all_requests(); + + env.log("Walking up to Deoxys rock."); + //Walk up to the triangle rock from the ship. Bike is not allowed on Birth Island. + ssf_press_button(context, BUTTON_B, 0ms, WALK_UP_DOWN_TIME0); + pbf_press_dpad(context, DPAD_UP, WALK_UP_DOWN_TIME0, 160ms); + context.wait_for_all_requests(); + + env.log("Solving puzzle."); + solve_puzzle(env, context); + + stats.resets++; + env.update_stats(); + } + + //switch - go home when done + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Deoxys.h b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Deoxys.h index b87e6ccc8a..62b7454d0a 100644 --- a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Deoxys.h +++ b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Deoxys.h @@ -1,56 +1,56 @@ -/* E Shiny Deoxys - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonRSE_ShinyHuntDeoxys_H -#define PokemonAutomation_PokemonRSE_ShinyHuntDeoxys_H - -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -class ShinyHuntDeoxys_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntDeoxys_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class ShinyHuntDeoxys : public SingleSwitchProgramInstance{ -public: - ShinyHuntDeoxys(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - virtual void start_program_border_check( - VideoStream& stream, - FeedbackType feedback_type - ) override{} - -private: - enum class StartPos{ - boat, - rock_unsolved, - rock_solved, - }; - EnumDropdownOption STARTPOS; - - MillisecondsOption WALK_UP_DOWN_TIME0; - - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; - - void solve_puzzle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); -}; - -} -} -} -#endif - +/* E Shiny Deoxys + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonRSE_ShinyHuntDeoxys_H +#define PokemonAutomation_PokemonRSE_ShinyHuntDeoxys_H + +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +class ShinyHuntDeoxys_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntDeoxys_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class ShinyHuntDeoxys : public SingleSwitchProgramInstance{ +public: + ShinyHuntDeoxys(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + virtual void start_program_border_check( + VideoStream& stream, + FeedbackType feedback_type + ) override{} + +private: + enum class StartPos{ + boat, + rock_unsolved, + rock_solved, + }; + EnumDropdownOption STARTPOS; + + MillisecondsOption WALK_UP_DOWN_TIME0; + + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; + + void solve_puzzle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); +}; + +} +} +} +#endif + diff --git a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Mew.cpp b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Mew.cpp index a9b1d3986e..11ac24e9ae 100644 --- a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Mew.cpp +++ b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Mew.cpp @@ -1,230 +1,230 @@ -/* E Shiny Mew - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "Pokemon/Pokemon_Strings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h" -#include "PokemonRSE/PokemonRSE_Navigation.h" -#include "PokemonRSE_ShinyHunt-Mew.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -ShinyHuntMew_Descriptor::ShinyHuntMew_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonRSE:ShinyHuntMew", - Pokemon::STRING_POKEMON + " RSE", "Shiny Hunt - Mew", - "ComputerControl/blob/master/Wiki/Programs/PokemonRSE/ShinyHuntMew.md", - "Use the Run Away method to shiny hunt Mew in Emerald.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} - -struct ShinyHuntMew_Descriptor::Stats : public StatsTracker{ - Stats() - : resets(m_stats["Resets"]) - , shinies(m_stats["Shinies"]) - { - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Shinies"); - } - std::atomic& resets; - std::atomic& shinies; -}; -std::unique_ptr ShinyHuntMew_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -ShinyHuntMew::ShinyHuntMew() - : NOTIFICATION_SHINY( - "Shiny Found", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_SHINY, - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , MEW_WAIT_TIME( - "Mew wait time:
Wait this long after entering for Mew to hide in the grass.", - LockMode::LOCK_WHILE_RUNNING, - "2000 ms" - ) - , DOOR_TO_GRASS_TIME( - "Door to grass time:
Time it takes to run from the door to the edge of the tall grass. Three steps up.", - LockMode::LOCK_WHILE_RUNNING, - "400 ms" - ) - , RIGHT_GRASS_1_TIME( - "First Right time:
Time it takes to turn right and take three steps. This follows the edge of the grass.", - LockMode::LOCK_WHILE_RUNNING, - "450 ms" - ) - , UP_GRASS_1_TIME( - "Move Up time::
Time it takes turn up and take one step.", - LockMode::LOCK_WHILE_RUNNING, - "200 ms" - ) - , RIGHT_GRASS_2_TIME( - "Second Right time:
Time it takes to turn right and take two steps.", - LockMode::LOCK_WHILE_RUNNING, - "260 ms" - ) - , FACE_UP_TIME( - "Face Up time:
Time it takes to tap the up button and face up, without taking a step.", - LockMode::LOCK_WHILE_RUNNING, - "150 ms" - ) -{ - PA_ADD_OPTION(NOTIFICATIONS); - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(MEW_WAIT_TIME); - PA_ADD_OPTION(DOOR_TO_GRASS_TIME); - PA_ADD_OPTION(RIGHT_GRASS_1_TIME); - PA_ADD_OPTION(UP_GRASS_1_TIME); - PA_ADD_OPTION(RIGHT_GRASS_2_TIME); - PA_ADD_OPTION(FACE_UP_TIME); -} - -void ShinyHuntMew::enter_mew(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - BlackScreenOverWatcher enter_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_press_dpad(context, DPAD_UP, 250, 20); - pbf_wait(context, 300); - }, - {enter_area} - ); - context.wait_for_all_requests(); - if (ret != 0){ - env.log("Failed to enter area.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to enter area.", - env.console - ); - } - else { - env.log("Entered area."); - } - - //Wait for Mew ! animation to finish - pbf_wait(context, MEW_WAIT_TIME); - context.wait_for_all_requests(); - - //DO NOT pause while running! - //Run up toward the extra tall grass - 3 steps - ssf_press_button(context, BUTTON_B, 0ms, DOOR_TO_GRASS_TIME); - pbf_press_dpad(context, DPAD_UP, DOOR_TO_GRASS_TIME, 0ms); - - //Turn right, take 3 steps - ssf_press_button(context, BUTTON_B, 0ms, RIGHT_GRASS_1_TIME); - pbf_press_dpad(context, DPAD_RIGHT, RIGHT_GRASS_1_TIME, 0ms); - - //Turn up, take 1 step - ssf_press_button(context, BUTTON_B, 0ms, UP_GRASS_1_TIME); - pbf_press_dpad(context, DPAD_UP, UP_GRASS_1_TIME, 0ms); - - //Turn right, take 2 steps - ssf_press_button(context, BUTTON_B, 0ms, RIGHT_GRASS_2_TIME); - pbf_press_dpad(context, DPAD_RIGHT, RIGHT_GRASS_2_TIME, 0ms); - - //Turn up. Start battle. - pbf_press_dpad(context, DPAD_UP, FACE_UP_TIME, 0ms); - - context.wait_for_all_requests(); -} - -void ShinyHuntMew::exit_mew(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - ssf_press_button(context, BUTTON_B, 0, 50); - pbf_press_dpad(context, DPAD_DOWN, 50, 20); - - ssf_press_button(context, BUTTON_B, 0, 90); - pbf_press_dpad(context, DPAD_LEFT, 90, 20); - - ssf_press_button(context, BUTTON_B, 0, 100); - pbf_press_dpad(context, DPAD_DOWN, 100, 20); - - BlackScreenOverWatcher exit_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_press_dpad(context, DPAD_DOWN, 250, 20); - pbf_wait(context, 300); - }, - {exit_area} - ); - context.wait_for_all_requests(); - if (ret != 0){ - env.log("Failed to exit area.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to exit area.", - env.console - ); - } - else { - env.log("Exited area."); - } -} - -void ShinyHuntMew::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - ShinyHuntMew_Descriptor::Stats& stats = env.current_stats(); - - /* - * Requires more precision to ensure a Mew encounter every time. - * Movement is very configurable due to this. - * Enter on the left side, run up and hug the grass to the edge just after the flower on the right - * This but without the bike: - * https://old.reddit.com/r/ShinyPokemon/comments/1c773oi/gen3_discuss_is_this_the_fastest_way_to_encounter/ - */ - - while (true) { - enter_mew(env, context); - - bool legendary_shiny = handle_encounter(env.console, context, true); - if (legendary_shiny) { - stats.shinies++; - env.update_stats(); - send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", env.console.video().snapshot(), true); - break; - } - env.log("No shiny found."); - flee_battle(env.console, context); - - //Close dialog - pbf_mash_button(context, BUTTON_B, 250); - context.wait_for_all_requests(); - - exit_mew(env, context); - - stats.resets++; - env.update_stats(); - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - -} -} -} +/* E Shiny Mew + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "Pokemon/Pokemon_Strings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h" +#include "PokemonRSE/PokemonRSE_Navigation.h" +#include "PokemonRSE_ShinyHunt-Mew.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +ShinyHuntMew_Descriptor::ShinyHuntMew_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonRSE:ShinyHuntMew", + Pokemon::STRING_POKEMON + " RSE", "Shiny Hunt - Mew", + "ComputerControl/blob/master/Wiki/Programs/PokemonRSE/ShinyHuntMew.md", + "Use the Run Away method to shiny hunt Mew in Emerald.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} + +struct ShinyHuntMew_Descriptor::Stats : public StatsTracker{ + Stats() + : resets(m_stats["Resets"]) + , shinies(m_stats["Shinies"]) + { + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Shinies"); + } + std::atomic& resets; + std::atomic& shinies; +}; +std::unique_ptr ShinyHuntMew_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +ShinyHuntMew::ShinyHuntMew() + : NOTIFICATION_SHINY( + "Shiny Found", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_SHINY, + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , MEW_WAIT_TIME( + "Mew wait time:
Wait this long after entering for Mew to hide in the grass.", + LockMode::LOCK_WHILE_RUNNING, + "2000 ms" + ) + , DOOR_TO_GRASS_TIME( + "Door to grass time:
Time it takes to run from the door to the edge of the tall grass. Three steps up.", + LockMode::LOCK_WHILE_RUNNING, + "400 ms" + ) + , RIGHT_GRASS_1_TIME( + "First Right time:
Time it takes to turn right and take three steps. This follows the edge of the grass.", + LockMode::LOCK_WHILE_RUNNING, + "450 ms" + ) + , UP_GRASS_1_TIME( + "Move Up time::
Time it takes turn up and take one step.", + LockMode::LOCK_WHILE_RUNNING, + "200 ms" + ) + , RIGHT_GRASS_2_TIME( + "Second Right time:
Time it takes to turn right and take two steps.", + LockMode::LOCK_WHILE_RUNNING, + "260 ms" + ) + , FACE_UP_TIME( + "Face Up time:
Time it takes to tap the up button and face up, without taking a step.", + LockMode::LOCK_WHILE_RUNNING, + "150 ms" + ) +{ + PA_ADD_OPTION(NOTIFICATIONS); + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(MEW_WAIT_TIME); + PA_ADD_OPTION(DOOR_TO_GRASS_TIME); + PA_ADD_OPTION(RIGHT_GRASS_1_TIME); + PA_ADD_OPTION(UP_GRASS_1_TIME); + PA_ADD_OPTION(RIGHT_GRASS_2_TIME); + PA_ADD_OPTION(FACE_UP_TIME); +} + +void ShinyHuntMew::enter_mew(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + BlackScreenOverWatcher enter_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_press_dpad(context, DPAD_UP, 250, 20); + pbf_wait(context, 300); + }, + {enter_area} + ); + context.wait_for_all_requests(); + if (ret != 0){ + env.log("Failed to enter area.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to enter area.", + env.console + ); + } + else { + env.log("Entered area."); + } + + //Wait for Mew ! animation to finish + pbf_wait(context, MEW_WAIT_TIME); + context.wait_for_all_requests(); + + //DO NOT pause while running! + //Run up toward the extra tall grass - 3 steps + ssf_press_button(context, BUTTON_B, 0ms, DOOR_TO_GRASS_TIME); + pbf_press_dpad(context, DPAD_UP, DOOR_TO_GRASS_TIME, 0ms); + + //Turn right, take 3 steps + ssf_press_button(context, BUTTON_B, 0ms, RIGHT_GRASS_1_TIME); + pbf_press_dpad(context, DPAD_RIGHT, RIGHT_GRASS_1_TIME, 0ms); + + //Turn up, take 1 step + ssf_press_button(context, BUTTON_B, 0ms, UP_GRASS_1_TIME); + pbf_press_dpad(context, DPAD_UP, UP_GRASS_1_TIME, 0ms); + + //Turn right, take 2 steps + ssf_press_button(context, BUTTON_B, 0ms, RIGHT_GRASS_2_TIME); + pbf_press_dpad(context, DPAD_RIGHT, RIGHT_GRASS_2_TIME, 0ms); + + //Turn up. Start battle. + pbf_press_dpad(context, DPAD_UP, FACE_UP_TIME, 0ms); + + context.wait_for_all_requests(); +} + +void ShinyHuntMew::exit_mew(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + ssf_press_button(context, BUTTON_B, 0ms, 400ms); + pbf_press_dpad(context, DPAD_DOWN, 50, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 720ms); + pbf_press_dpad(context, DPAD_LEFT, 90, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 800ms); + pbf_press_dpad(context, DPAD_DOWN, 100, 20); + + BlackScreenOverWatcher exit_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_press_dpad(context, DPAD_DOWN, 250, 20); + pbf_wait(context, 300); + }, + {exit_area} + ); + context.wait_for_all_requests(); + if (ret != 0){ + env.log("Failed to exit area.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to exit area.", + env.console + ); + } + else { + env.log("Exited area."); + } +} + +void ShinyHuntMew::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + ShinyHuntMew_Descriptor::Stats& stats = env.current_stats(); + + /* + * Requires more precision to ensure a Mew encounter every time. + * Movement is very configurable due to this. + * Enter on the left side, run up and hug the grass to the edge just after the flower on the right + * This but without the bike: + * https://old.reddit.com/r/ShinyPokemon/comments/1c773oi/gen3_discuss_is_this_the_fastest_way_to_encounter/ + */ + + while (true) { + enter_mew(env, context); + + bool legendary_shiny = handle_encounter(env.console, context, true); + if (legendary_shiny) { + stats.shinies++; + env.update_stats(); + send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", env.console.video().snapshot(), true); + break; + } + env.log("No shiny found."); + flee_battle(env.console, context); + + //Close dialog + pbf_mash_button(context, BUTTON_B, 250); + context.wait_for_all_requests(); + + exit_mew(env, context); + + stats.resets++; + env.update_stats(); + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Mew.h b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Mew.h index 9d438bdb1e..6d8f81e086 100644 --- a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Mew.h +++ b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Mew.h @@ -1,59 +1,59 @@ -/* E Shiny Mew - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonRSE_ShinyHuntMew_H -#define PokemonAutomation_PokemonRSE_ShinyHuntMew_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -class ShinyHuntMew_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntMew_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class ShinyHuntMew : public SingleSwitchProgramInstance{ -public: - ShinyHuntMew(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - virtual void start_program_border_check( - VideoStream& stream, - FeedbackType feedback_type - ) override{} - -private: - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - - MillisecondsOption MEW_WAIT_TIME; - MillisecondsOption DOOR_TO_GRASS_TIME; - MillisecondsOption RIGHT_GRASS_1_TIME; - MillisecondsOption UP_GRASS_1_TIME; - MillisecondsOption RIGHT_GRASS_2_TIME; - MillisecondsOption FACE_UP_TIME; - - void enter_mew(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void exit_mew(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -}; - -} -} -} -#endif - +/* E Shiny Mew + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonRSE_ShinyHuntMew_H +#define PokemonAutomation_PokemonRSE_ShinyHuntMew_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +class ShinyHuntMew_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntMew_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class ShinyHuntMew : public SingleSwitchProgramInstance{ +public: + ShinyHuntMew(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + virtual void start_program_border_check( + VideoStream& stream, + FeedbackType feedback_type + ) override{} + +private: + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + + MillisecondsOption MEW_WAIT_TIME; + MillisecondsOption DOOR_TO_GRASS_TIME; + MillisecondsOption RIGHT_GRASS_1_TIME; + MillisecondsOption UP_GRASS_1_TIME; + MillisecondsOption RIGHT_GRASS_2_TIME; + MillisecondsOption FACE_UP_TIME; + + void enter_mew(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void exit_mew(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +}; + +} +} +} +#endif + diff --git a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_StarterReset.cpp b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_StarterReset.cpp index 5d73850c5e..37539aa6ed 100644 --- a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_StarterReset.cpp +++ b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_StarterReset.cpp @@ -1,207 +1,207 @@ -/* RS Starter Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "Pokemon/Pokemon_Strings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h" -#include "PokemonRSE/Inference/PokemonRSE_ShinyNumberDetector.h" -#include "PokemonRSE/PokemonRSE_Navigation.h" -#include "PokemonRSE_StarterReset.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -StarterReset_Descriptor::StarterReset_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonRSE:StarterReset", - Pokemon::STRING_POKEMON + " RSE", "[RS]Starter Reset - Video", - "ComputerControl/blob/master/Wiki/Programs/PokemonRSE/StarterReset.md", - "Soft reset for a shiny starter. Ruby and Sapphire only.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} - -struct StarterReset_Descriptor::Stats : public StatsTracker{ - Stats() - : resets(m_stats["Resets"]) - , shinystarter(m_stats["Shiny Starter"]) - { - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Shiny Starter"); - } - std::atomic& resets; - std::atomic& shinystarter; -}; -std::unique_ptr StarterReset_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -StarterReset::StarterReset() - : TARGET( - "Starter:
", - { - {Target::treecko, "treecko", "Treecko"}, - {Target::torchic, "torchic", "Torchic"}, - {Target::mudkip, "mudkip", "Mudkip"}, - }, - LockMode::LOCK_WHILE_RUNNING, - Target::treecko - ) -// , STARTER_WAIT0( -// "Send out starter wait:
After pressing A to send out your selected starter, wait this long for the animation. Make sure to add extra time in case it is shiny.", -// LockMode::LOCK_WHILE_RUNNING, -// "6000 ms" -// ) - , NOTIFICATION_SHINY_STARTER( - "Shiny Starter", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_SHINY_STARTER, - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(TARGET); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void StarterReset::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - StarterReset_Descriptor::Stats& stats = env.current_stats(); - - /* - * Settings: Text Speed fast. - * Full screen, no filter? The device I'm using to test has similar looking output, but I don't have switch online+. - * If on a retro handheld, make sure the screen matches that of NSO+. - * - * Setup: Stand in front of the Professor's bag and save the game. - * - * Required to fight, so have to do the SR method instead of run away - * Soft reset programs are only for Ruby/Sapphire, as Emerald has the 0 seed issue. - * - * This also assumes no dry battery. - * - * WARNING: Timings in Emerald for the battle menu are slightly different. This won't work with Emerald at all. - */ - - bool shiny_starter = false; - while (!shiny_starter) { - env.log("Opening bag and selecting starter."); - pbf_press_button(context, BUTTON_A, 40, 180); - - switch (TARGET) { - case Target::treecko: - pbf_press_dpad(context, DPAD_LEFT, 40, 100); - break; - case Target::torchic: - //Default cursor position, do nothing. - break; - case Target::mudkip: - pbf_press_dpad(context, DPAD_RIGHT, 40, 100); - break; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "StarterReset: Invalid target.", - env.console - ); - break; - } - pbf_mash_button(context, BUTTON_A, 540); - context.wait_for_all_requests(); - - env.log("Starting battle."); - - //Now mash B until the battle menu appears - BattleMenuWatcher battle_menu(COLOR_RED); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 1000); - }, - {battle_menu} - ); - context.wait_for_all_requests(); - if (ret != 0){ - env.console.log("Failed to detect battle menu.", COLOR_RED); - } - else { - env.log("Battle menu detected."); - } - - //Open the summary and check the color of the number - pbf_press_dpad(context, DPAD_DOWN, 40, 80); - pbf_press_button(context, BUTTON_A, 40, 80); - - BlackScreenOverWatcher detector(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - int ret2 = wait_until( - env.console, context, - std::chrono::milliseconds(3000), - {{detector}} - ); - if (ret2 == 0){ - env.log("Entered party menu."); - }else{ - env.log("Timed out waiting to enter party menu.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "StarterReset: Timed out waiting to enter party menu.", - env.console - ); - } - - pbf_press_button(context, BUTTON_A, 20, 180); - pbf_press_dpad(context, DPAD_DOWN, 40, 80); - pbf_press_button(context, BUTTON_A, 40, 80); - - //Check second party member - used for testing with hacked in shiny starter - //pbf_press_dpad(context, DPAD_DOWN, 40, 80); - - pbf_wait(context, 125); - context.wait_for_all_requests(); - - VideoSnapshot screen = env.console.video().snapshot(); - ShinyNumberDetector shiny_checker(COLOR_YELLOW); - shiny_starter = shiny_checker.read(env.console.logger(), screen); - - if (shiny_starter) { - env.log("Shiny starter detected!"); - stats.shinystarter++; - send_program_status_notification(env, NOTIFICATION_SHINY_STARTER, "Shiny starter found!", screen, true); - } - else { - env.log("Starter is not shiny."); - env.log("Soft resetting."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Soft resetting." - ); - soft_reset(env.program_info(), env.console, context); - stats.resets++; - } - } - - //if system set to nintendo switch, have go home when done option? - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - -} -} -} - +/* RS Starter Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "Pokemon/Pokemon_Strings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h" +#include "PokemonRSE/Inference/PokemonRSE_ShinyNumberDetector.h" +#include "PokemonRSE/PokemonRSE_Navigation.h" +#include "PokemonRSE_StarterReset.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +StarterReset_Descriptor::StarterReset_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonRSE:StarterReset", + Pokemon::STRING_POKEMON + " RSE", "[RS]Starter Reset - Video", + "ComputerControl/blob/master/Wiki/Programs/PokemonRSE/StarterReset.md", + "Soft reset for a shiny starter. Ruby and Sapphire only.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} + +struct StarterReset_Descriptor::Stats : public StatsTracker{ + Stats() + : resets(m_stats["Resets"]) + , shinystarter(m_stats["Shiny Starter"]) + { + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Shiny Starter"); + } + std::atomic& resets; + std::atomic& shinystarter; +}; +std::unique_ptr StarterReset_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +StarterReset::StarterReset() + : TARGET( + "Starter:
", + { + {Target::treecko, "treecko", "Treecko"}, + {Target::torchic, "torchic", "Torchic"}, + {Target::mudkip, "mudkip", "Mudkip"}, + }, + LockMode::LOCK_WHILE_RUNNING, + Target::treecko + ) +// , STARTER_WAIT0( +// "Send out starter wait:
After pressing A to send out your selected starter, wait this long for the animation. Make sure to add extra time in case it is shiny.", +// LockMode::LOCK_WHILE_RUNNING, +// "6000 ms" +// ) + , NOTIFICATION_SHINY_STARTER( + "Shiny Starter", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_SHINY_STARTER, + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(TARGET); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void StarterReset::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + StarterReset_Descriptor::Stats& stats = env.current_stats(); + + /* + * Settings: Text Speed fast. + * Full screen, no filter? The device I'm using to test has similar looking output, but I don't have switch online+. + * If on a retro handheld, make sure the screen matches that of NSO+. + * + * Setup: Stand in front of the Professor's bag and save the game. + * + * Required to fight, so have to do the SR method instead of run away + * Soft reset programs are only for Ruby/Sapphire, as Emerald has the 0 seed issue. + * + * This also assumes no dry battery. + * + * WARNING: Timings in Emerald for the battle menu are slightly different. This won't work with Emerald at all. + */ + + bool shiny_starter = false; + while (!shiny_starter) { + env.log("Opening bag and selecting starter."); + pbf_press_button(context, BUTTON_A, 40, 180); + + switch (TARGET) { + case Target::treecko: + pbf_press_dpad(context, DPAD_LEFT, 40, 100); + break; + case Target::torchic: + //Default cursor position, do nothing. + break; + case Target::mudkip: + pbf_press_dpad(context, DPAD_RIGHT, 40, 100); + break; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "StarterReset: Invalid target.", + env.console + ); + break; + } + pbf_mash_button(context, BUTTON_A, 540); + context.wait_for_all_requests(); + + env.log("Starting battle."); + + //Now mash B until the battle menu appears + BattleMenuWatcher battle_menu(COLOR_RED); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 1000); + }, + {battle_menu} + ); + context.wait_for_all_requests(); + if (ret != 0){ + env.console.log("Failed to detect battle menu.", COLOR_RED); + } + else { + env.log("Battle menu detected."); + } + + //Open the summary and check the color of the number + pbf_press_dpad(context, DPAD_DOWN, 40, 80); + pbf_press_button(context, BUTTON_A, 40, 80); + + BlackScreenOverWatcher detector(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + int ret2 = wait_until( + env.console, context, + std::chrono::milliseconds(3000), + {{detector}} + ); + if (ret2 == 0){ + env.log("Entered party menu."); + }else{ + env.log("Timed out waiting to enter party menu.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "StarterReset: Timed out waiting to enter party menu.", + env.console + ); + } + + pbf_press_button(context, BUTTON_A, 20, 180); + pbf_press_dpad(context, DPAD_DOWN, 40, 80); + pbf_press_button(context, BUTTON_A, 40, 80); + + //Check second party member - used for testing with hacked in shiny starter + //pbf_press_dpad(context, DPAD_DOWN, 40, 80); + + pbf_wait(context, 125); + context.wait_for_all_requests(); + + VideoSnapshot screen = env.console.video().snapshot(); + ShinyNumberDetector shiny_checker(COLOR_YELLOW); + shiny_starter = shiny_checker.read(env.console.logger(), screen); + + if (shiny_starter) { + env.log("Shiny starter detected!"); + stats.shinystarter++; + send_program_status_notification(env, NOTIFICATION_SHINY_STARTER, "Shiny starter found!", screen, true); + } + else { + env.log("Starter is not shiny."); + env.log("Soft resetting."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Soft resetting." + ); + soft_reset(env.program_info(), env.console, context); + stats.resets++; + } + } + + //if system set to nintendo switch, have go home when done option? + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + +} +} +} + diff --git a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_StarterReset.h b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_StarterReset.h index 866d3035df..12644eaf8f 100644 --- a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_StarterReset.h +++ b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_StarterReset.h @@ -1,56 +1,56 @@ -/* RS Starter Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonRSE_StarterReset_H -#define PokemonAutomation_PokemonRSE_StarterReset_H - -//#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -class StarterReset_Descriptor : public SingleSwitchProgramDescriptor{ -public: - StarterReset_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class StarterReset : public SingleSwitchProgramInstance{ -public: - StarterReset(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext &context) override; - - virtual void start_program_border_check( - VideoStream& stream, - FeedbackType feedback_type - ) override{} - -private: - enum class Target{ - treecko, - torchic, - mudkip, - }; - EnumDropdownOption TARGET; - -// MillisecondsOption STARTER_WAIT0; - - EventNotificationOption NOTIFICATION_SHINY_STARTER; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - -} -} -} -#endif - - - +/* RS Starter Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonRSE_StarterReset_H +#define PokemonAutomation_PokemonRSE_StarterReset_H + +//#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +class StarterReset_Descriptor : public SingleSwitchProgramDescriptor{ +public: + StarterReset_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class StarterReset : public SingleSwitchProgramInstance{ +public: + StarterReset(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext &context) override; + + virtual void start_program_border_check( + VideoStream& stream, + FeedbackType feedback_type + ) override{} + +private: + enum class Target{ + treecko, + torchic, + mudkip, + }; + EnumDropdownOption TARGET; + +// MillisecondsOption STARTER_WAIT0; + + EventNotificationOption NOTIFICATION_SHINY_STARTER; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonRSE/Programs/TestPrograms/PokemonRSE_SoundListener.cpp b/SerialPrograms/Source/PokemonRSE/Programs/TestPrograms/PokemonRSE_SoundListener.cpp index 63e2d4cac3..d2fc7e1e84 100644 --- a/SerialPrograms/Source/PokemonRSE/Programs/TestPrograms/PokemonRSE_SoundListener.cpp +++ b/SerialPrograms/Source/PokemonRSE/Programs/TestPrograms/PokemonRSE_SoundListener.cpp @@ -1,100 +1,100 @@ -/* Sound Listener - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/AlignedVector.tpp" -#include "CommonFramework/AudioPipeline/AudioFeed.h" -#include "CommonFramework/AudioPipeline/AudioTemplate.h" -#include "CommonTools/Audio/AudioTemplateCache.h" -#include "CommonTools/Audio/SpectrogramMatcher.h" -#include "CommonTools/Async/InferenceSession.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.h" -#include "PokemonRSE_SoundListener.h" - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - using namespace Pokemon; - - -SoundListener_Descriptor::SoundListener_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonRSE:SoundListener", - STRING_POKEMON + " RSE", "Sound Listener", - "", - "Test sound detectors listening to audio stream.", - FeedbackType::REQUIRED, AllowCommandsWhenRunning::ENABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController} - ) -{} - - -SoundListener::SoundListener() - : SOUND_TYPE("Which Sound to Detect", - { - {SoundType::SHINY, "shiny", "Shiny Sound"}, - }, - LockMode::LOCK_WHILE_RUNNING, - SoundType::SHINY - ) - , STOP_ON_DETECTED_SOUND( - "Stop on the detected sound
Stop program when the sound is detected.", - LockMode::LOCK_WHILE_RUNNING, - false - ) -{ - PA_ADD_OPTION(SOUND_TYPE); - PA_ADD_OPTION(STOP_ON_DETECTED_SOUND); -} - -void SoundListener::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // search_alpha_roar_from_audio_dump(); - // return; - - std::cout << "Running audio test program." << std::endl; - - std::shared_ptr detector; - auto action = [&](float error_coefficient) -> bool{ - // This lambda function will be called when the sound is detected. - // Its return will determine whether to stop the program: - return STOP_ON_DETECTED_SOUND; - }; - - SoundType type = SOUND_TYPE; - switch (type){ - case SoundType::SHINY: - detector = std::make_shared(env.console, action); - break; - default: - throw InternalProgramError( - &env.logger(), PA_CURRENT_FUNCTION, - "Not such sound detector as sound type " + std::to_string((size_t)type) - ); - return; - } - - InferenceSession session( - context, env.console, - {{*detector, std::chrono::milliseconds(20)}} - ); - context.wait_until_cancel(); - - std::cout << "Audio test program Sound listener finished." << std::endl; -} - - - -} -} -} +/* Sound Listener + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/AlignedVector.tpp" +#include "CommonFramework/AudioPipeline/AudioFeed.h" +#include "CommonFramework/AudioPipeline/AudioTemplate.h" +#include "CommonTools/Audio/AudioTemplateCache.h" +#include "CommonTools/Audio/SpectrogramMatcher.h" +#include "CommonTools/Async/InferenceSession.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.h" +#include "PokemonRSE_SoundListener.h" + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + using namespace Pokemon; + + +SoundListener_Descriptor::SoundListener_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonRSE:SoundListener", + STRING_POKEMON + " RSE", "Sound Listener", + "", + "Test sound detectors listening to audio stream.", + FeedbackType::REQUIRED, AllowCommandsWhenRunning::ENABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController} + ) +{} + + +SoundListener::SoundListener() + : SOUND_TYPE("Which Sound to Detect", + { + {SoundType::SHINY, "shiny", "Shiny Sound"}, + }, + LockMode::LOCK_WHILE_RUNNING, + SoundType::SHINY + ) + , STOP_ON_DETECTED_SOUND( + "Stop on the detected sound
Stop program when the sound is detected.", + LockMode::LOCK_WHILE_RUNNING, + false + ) +{ + PA_ADD_OPTION(SOUND_TYPE); + PA_ADD_OPTION(STOP_ON_DETECTED_SOUND); +} + +void SoundListener::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // search_alpha_roar_from_audio_dump(); + // return; + + std::cout << "Running audio test program." << std::endl; + + std::shared_ptr detector; + auto action = [&](float error_coefficient) -> bool{ + // This lambda function will be called when the sound is detected. + // Its return will determine whether to stop the program: + return STOP_ON_DETECTED_SOUND; + }; + + SoundType type = SOUND_TYPE; + switch (type){ + case SoundType::SHINY: + detector = std::make_shared(env.console, action); + break; + default: + throw InternalProgramError( + &env.logger(), PA_CURRENT_FUNCTION, + "Not such sound detector as sound type " + std::to_string((size_t)type) + ); + return; + } + + InferenceSession session( + context, env.console, + {{*detector, std::chrono::milliseconds(20)}} + ); + context.wait_until_cancel(); + + std::cout << "Audio test program Sound listener finished." << std::endl; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonRSE/Programs/TestPrograms/PokemonRSE_SoundListener.h b/SerialPrograms/Source/PokemonRSE/Programs/TestPrograms/PokemonRSE_SoundListener.h index 107bf308b2..4264629acf 100644 --- a/SerialPrograms/Source/PokemonRSE/Programs/TestPrograms/PokemonRSE_SoundListener.h +++ b/SerialPrograms/Source/PokemonRSE/Programs/TestPrograms/PokemonRSE_SoundListener.h @@ -1,53 +1,53 @@ -/* Sound Listener - * - * From: https://github.com/PokemonAutomation/ - * - * Debug program to test all kinds of sound detectors. - */ - -#ifndef PokemonAutomation_PokemonRSE_SoundListener_H -#define PokemonAutomation_PokemonRSE_SoundListener_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -//#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - - -class SoundListener_Descriptor : public SingleSwitchProgramDescriptor{ -public: - SoundListener_Descriptor(); -}; - - -class SoundListener : public SingleSwitchProgramInstance{ -public: - SoundListener(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - virtual void start_program_border_check( - VideoStream& stream, - FeedbackType feedback_type - ) override{} - -private: - enum class SoundType{ - SHINY, - }; - - EnumDropdownOption SOUND_TYPE; - BooleanCheckBoxOption STOP_ON_DETECTED_SOUND; -}; - - - - -} -} -} -#endif +/* Sound Listener + * + * From: https://github.com/PokemonAutomation/ + * + * Debug program to test all kinds of sound detectors. + */ + +#ifndef PokemonAutomation_PokemonRSE_SoundListener_H +#define PokemonAutomation_PokemonRSE_SoundListener_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +//#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + + +class SoundListener_Descriptor : public SingleSwitchProgramDescriptor{ +public: + SoundListener_Descriptor(); +}; + + +class SoundListener : public SingleSwitchProgramInstance{ +public: + SoundListener(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + virtual void start_program_border_check( + VideoStream& stream, + FeedbackType feedback_type + ) override{} + +private: + enum class SoundType{ + SHINY, + }; + + EnumDropdownOption SOUND_TYPE; + BooleanCheckBoxOption STOP_ON_DETECTED_SOUND; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h index 024e4676a4..80b10951c2 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h @@ -18,7 +18,9 @@ namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonSV{ - +// +// This class is now deprecated. +// class EncounterWatcher : public VisualInferenceCallback, public AudioInferenceCallback{ public: EncounterWatcher(VideoStream& stream, Color color = COLOR_RED); diff --git a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_StartBattleYellowBar.cpp b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_StartBattleYellowBar.cpp new file mode 100644 index 0000000000..5415e39a4b --- /dev/null +++ b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_StartBattleYellowBar.cpp @@ -0,0 +1,84 @@ +/* Start Battle Yellow Bar + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonSV_StartBattleYellowBar.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +StartBattleYellowBarDetector::StartBattleYellowBarDetector(Color color) + : m_color(color) + , m_top(0.100000, 0.001000, 0.800000, 0.004000) + , m_bot(0.100000, 0.995000, 0.800000, 0.004000) + , m_mid(0.1, 0.1, 0.8, 0.8) +{} +void StartBattleYellowBarDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_top); + items.add(m_color, m_bot); +} + +bool StartBattleYellowBarDetector::detect(const ImageViewRGB32& screen){ + ImageStats top = image_stats(extract_box_reference(screen, m_top)); + ImageStats bot = image_stats(extract_box_reference(screen, m_bot)); +// cout << "top = " << top.average << top.stddev << endl; +// cout << "bot = " << bot.average << top.stddev << endl; + if (!is_solid(top, {0.554825, 0.445175, 0.})){ + return false; + } + if (!is_solid(bot, {0.554825, 0.445175, 0.})){ + return false; + } + + if (euclidean_distance(top.average, bot.average) > 10){ + return false; + } + + ImageStats mid = image_stats(extract_box_reference(screen, m_mid)); +// cout << "mid = " << mid.average << mid.stddev << endl; + if (mid.stddev.sum() < 10){ + return false; + } + + return true; +} + + + + +void StartBattleYellowBarWatcher::make_overlays(VideoOverlaySet& items) const{ + StartBattleYellowBarDetector::make_overlays(items); +} +bool StartBattleYellowBarWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + if (!detect(frame)){ + m_start_detection = WallClock::min(); + return false; + } + + // Not long enough. + if (m_start_detection + std::chrono::milliseconds(100) > timestamp){ + return false; + } + + m_last_detected = timestamp; +// cout << "Detected yellow bar." << endl; + return false; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_StartBattleYellowBar.h b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_StartBattleYellowBar.h new file mode 100644 index 0000000000..82f9a77cd1 --- /dev/null +++ b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_StartBattleYellowBar.h @@ -0,0 +1,61 @@ +/* Start Battle Yellow Bar + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_StartBattleYellowBar_H +#define PokemonAutomation_PokemonSV_StartBattleYellowBar_H + +#include +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class StartBattleYellowBarDetector : public StaticScreenDetector{ +public: + StartBattleYellowBarDetector(Color color); + virtual void make_overlays(VideoOverlaySet& items) const override; + + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_top; + ImageFloatBox m_bot; + ImageFloatBox m_mid; +}; +class StartBattleYellowBarWatcher : public StartBattleYellowBarDetector, public VisualInferenceCallback{ +public: + StartBattleYellowBarWatcher(Color color) + : StartBattleYellowBarDetector(color) + , VisualInferenceCallback("StartBattleYellowBarWatcher") + , m_start_detection(WallClock::min()) + , m_last_detected(WallClock::min()) + {} + + WallClock last_detected() const{ + return m_last_detected.load(std::memory_order_relaxed); + } + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + WallClock m_start_detection; + std::atomic m_last_detected; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogArrowDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogArrowDetector.cpp index 1583a01703..8322006a48 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogArrowDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogArrowDetector.cpp @@ -72,7 +72,6 @@ bool is_dialog_arrow(const ImageViewRGB32& image, const WaterfillObject& object, double rmsd = black_arrow ? DIALOG_ARROW_BLACK().rmsd(cropped) : DIALOG_ARROW_WHITE().rmsd(cropped); -// cout << "rmsd = " << rmsd << endl; return rmsd <= 120; } diff --git a/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.cpp index bdf267e2b9..63c56c283a 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.cpp @@ -85,7 +85,7 @@ bool DialogBoxDetector::detect(const ImageViewRGB32& screen){ AdvanceDialogDetector::AdvanceDialogDetector(Color color, DialogType type) : m_box(color, true, type) - , m_arrow(0.710, 0.850, 0.030, 0.042) + , m_arrow(0.710, 0.850, 0.030, 0.045) {} void AdvanceDialogDetector::make_overlays(VideoOverlaySet& items) const{ m_box.make_overlays(items); diff --git a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.cpp index 4b850eb572..2f14b4f115 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.cpp @@ -6,10 +6,11 @@ #include #include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" +#include "Common/Cpp/Concurrency/AsyncTask.h" #include "CommonFramework/Exceptions/OperationFailedException.h" #include "CommonFramework/ImageTypes/ImageViewRGB32.h" #include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/Tools/GlobalThreadPools.h" #include "CommonFramework/VideoPipeline/VideoFeed.h" #include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" #include "CommonTools/Images/ImageFilter.h" @@ -33,7 +34,7 @@ void ItemPrinterJobsDetector::make_overlays(VideoOverlaySet& items) const{ items.add(m_color, m_box_bonus); } std::pair ItemPrinterJobsDetector::read_box( - Logger& logger, AsyncDispatcher& dispatcher, + Logger& logger, const ImageViewRGB32& screen, const ImageFloatBox& box ) const{ ImageViewRGB32 cropped = extract_box_reference(screen, box); @@ -54,10 +55,10 @@ std::pair ItemPrinterJobsDetector::read_box( SpinLock lock; std::map candidates; - std::vector> tasks(filtered.size()); - for (size_t c = 0; c < filtered.size(); c++){ - tasks[c] = dispatcher.dispatch([&, c]{ - int num = OCR::read_number(logger, filtered[c].first); + + GlobalThreadPools::normal_inference().run_in_parallel( + [&](size_t index){ + int num = OCR::read_number(logger, filtered[index].first); std::string str = std::to_string(num); WriteSpinLock lg(lock); if (str == "1"){ @@ -74,13 +75,9 @@ std::pair ItemPrinterJobsDetector::read_box( }else if (str[0] == '1'){ candidates[1]++; } - }); - } - - // Wait for everything. - for (auto& task : tasks){ - task->wait_and_rethrow_exceptions(); - } + }, + 0, filtered.size(), 1 + ); std::pair best; for (const auto& item : candidates){ @@ -112,12 +109,12 @@ std::pair ItemPrinterJobsDetector::read_box( return 0; #endif } -uint8_t ItemPrinterJobsDetector::detect_jobs(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& screen) const{ - std::pair normal = read_box(logger, dispatcher, screen, m_box_normal); +uint8_t ItemPrinterJobsDetector::detect_jobs(Logger& logger, const ImageViewRGB32& screen) const{ + std::pair normal = read_box(logger, screen, m_box_normal); if (normal.second > 6){ return normal.first; } - std::pair bonus = read_box(logger, dispatcher, screen, m_box_bonus); + std::pair bonus = read_box(logger, screen, m_box_bonus); if (normal.second + 2 > bonus.second){ return normal.first; }else{ @@ -127,14 +124,13 @@ uint8_t ItemPrinterJobsDetector::detect_jobs(Logger& logger, AsyncDispatcher& di void ItemPrinterJobsDetector::set_print_jobs( - AsyncDispatcher& dispatcher, VideoStream& stream, ProControllerContext& context, uint8_t jobs ) const{ VideoSnapshot snapshot; for (size_t c = 0; c < 10; c++){ context.wait_for_all_requests(); snapshot = stream.video().snapshot(); - uint8_t current_jobs = detect_jobs(stream.logger(), dispatcher, snapshot); + uint8_t current_jobs = detect_jobs(stream.logger(), snapshot); if (current_jobs == jobs){ return; } diff --git a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.h b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.h index 1361104938..c1c02429ab 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.h @@ -15,7 +15,6 @@ namespace PokemonAutomation{ class Logger; - class AsyncDispatcher; namespace NintendoSwitch{ namespace PokemonSV{ @@ -24,18 +23,17 @@ class ItemPrinterJobsDetector{ ItemPrinterJobsDetector(Color color); void make_overlays(VideoOverlaySet& items) const; - uint8_t detect_jobs(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& screen) const; + uint8_t detect_jobs(Logger& logger, const ImageViewRGB32& screen) const; // "jobs" jobs must be 1, 5, or 10. void set_print_jobs( - AsyncDispatcher& dispatcher, VideoStream& stream, ProControllerContext& context, uint8_t jobs ) const; private: std::pair read_box( - Logger& logger, AsyncDispatcher& dispatcher, + Logger& logger, const ImageViewRGB32& screen, const ImageFloatBox& box ) const; diff --git a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMaterialDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMaterialDetector.cpp index af21270cad..8bf668d091 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMaterialDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMaterialDetector.cpp @@ -1,261 +1,270 @@ -/* Tournament Prize Jobs Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/OCR/OCR_NumberReader.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV_ItemPrinterMaterialDetector.h" - -// #include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -MaterialNameReader& MaterialNameReader::instance(){ - static MaterialNameReader reader; - return reader; -} - -// MaterialNameReader has a very limited dictionary, -// so it can only reliably read the material names with 68% value -// (i.e. Ditto Goo, Happiny Dust, Magby Hair, Beldum Claw) -MaterialNameReader::MaterialNameReader() - : SmallDictionaryMatcher("PokemonSV/ItemPrinterMaterialOCR.json") -{} - -OCR::StringMatchResult MaterialNameReader::read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio, double max_text_ratio -) const{ - return match_substring_from_image_multifiltered( - &logger, language, image, text_color_ranges, - MAX_LOG10P, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio - ); -} - - -ItemPrinterMaterialDetector::ItemPrinterMaterialDetector(Color color, Language language) - : m_color(color) - , m_language(language) - , m_box_mat_value(Material_Boxes(ImageFloatBox(0.39, 0.176758, 0.025, 0.050))) - , m_box_mat_quantity(Material_Boxes(ImageFloatBox(0.485, 0.176758, 0.037, 0.050))) - , m_box_mat_name(Material_Boxes(ImageFloatBox(0.090, 0.176758, 0.275, 0.050))) -{} - -std::array ItemPrinterMaterialDetector::Material_Boxes(ImageFloatBox initial_box){ - std::array material_boxes; - double x = initial_box.x; - double width = initial_box.width; - double height = initial_box.height; - double initial_y = initial_box.y; - double y_spacing = 0.074219; - for (size_t i = 0; i < 10; i++){ - double y = initial_y + i*y_spacing; - material_boxes[i] = ImageFloatBox(x, y, width, height); - // std::cout << "{" << x << "," << y << "," << width << "," << height << "}, "; - } - // std::cout << std::endl; - return material_boxes; -} - -void ItemPrinterMaterialDetector::make_overlays(VideoOverlaySet& items) const{ - for (size_t i = 0; i < 10; i++){ - items.add(m_color, m_box_mat_value[i]); - items.add(m_color, m_box_mat_quantity[i]); - items.add(m_color, m_box_mat_name[i]); - } -} - -int16_t ItemPrinterMaterialDetector::read_number( - Logger& logger, AsyncDispatcher& dispatcher, - const ImageViewRGB32& screen, const ImageFloatBox& box, - int8_t row_index -) const{ - - ImageViewRGB32 cropped = extract_box_reference(screen, box); - ImageRGB32 filtered = to_blackwhite_rgb32_range( - cropped, - true, - 0xff000000, 0xff808080 - ); - // filtered.save("DebugDumps/test-one-filter-1.png"); - bool is_dark_text_light_background = image_stats(filtered).average.sum() > 400; - // std::cout << "Average sum of filtered: "<< std::to_string(image_stats(filtered).average.sum()) << std::endl; - - const std::vector> filters = - [&](){ - if (is_dark_text_light_background){ - return std::vector>{ - // {0xff000000, 0xffb0b0b0}, - {0xff000000, 0xffa0a0a0}, - {0xff000000, 0xff959595}, - {0xff000000, 0xff909090}, - {0xff000000, 0xff858585}, - {0xff000000, 0xff808080}, - // {0xff000000, 0xff707070}, - // {0xff000000, 0xff606060}, - // {0xff000000, 0xff505050}, - // {0xff000000, 0xff404040}, - // {0xff000000, 0xff303030}, - // {0xff000000, 0xff202020}, - // {0xff000000, 0xff101010}, - }; - }else{ - return std::vector>{ - {0xff808080, 0xffffffff}, - {0xff858585, 0xffffffff}, - {0xff909090, 0xffffffff}, - {0xff959595, 0xffffffff}, - {0xffa0a0a0, 0xffffffff}, - // {0xffb0b0b0, 0xffffffff}, - // {0xffc0c0c0, 0xffffffff}, - // {0xffd0d0d0, 0xffffffff}, - // {0xffe0e0e0, 0xffffffff}, - // {0xfff0f0f0, 0xffffffff}, - }; - } - }(); - - int16_t number = (int16_t)OCR::read_number_waterfill_multifilter(logger, cropped, filters, 24, true, true, row_index); - - if (number < 1 || number > 999){ - number = -1; - } - return (int16_t)number; -} - - -// return row number where Happiny dust is located on screen -// keep pressing DPAD_RIGHT until Happiny dust is on screen -// check each row on the screen for Happiny Dust -int8_t ItemPrinterMaterialDetector::find_happiny_dust_row_index( - AsyncDispatcher& dispatcher, - VideoStream& stream, ProControllerContext& context -) const{ - int8_t value_68_row_index; - for (size_t c = 0; c < 30; c++){ - context.wait_for_all_requests(); - std::vector value_68_row_index_list = find_material_value_row_index(dispatcher, stream, context, 68); - for (size_t i = 0; i < value_68_row_index_list.size(); i++){ - value_68_row_index = value_68_row_index_list[i]; - if (detect_material_name(stream, context, value_68_row_index) == "happiny-dust"){ - // found screen and row number with Happiny dust. - // std::cout << "Happiny dust found. Row number: " << std::to_string(value_68_row_index) << std::endl; - return value_68_row_index; - } - } - - // keep searching for Happiny dust - pbf_press_dpad(context, DPAD_RIGHT, 20, 30); - } - - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to find Happiny dust after 10 tries.", - stream - ); - -} - -// detects the material name at the given row_index -// MaterialNameReader has a very limited dictionary, -// so it can only reliably read the material names with 68% value -// (i.e. Ditto Goo, Happiny Dust, Magby Hair, Beldum Claw) -std::string ItemPrinterMaterialDetector::detect_material_name( - VideoStream& stream, - ProControllerContext& context, - int8_t row_index -) const{ - VideoSnapshot snapshot = stream.video().snapshot(); - ImageFloatBox material_name_box = m_box_mat_name[row_index]; - ImageViewRGB32 material_name_image = extract_box_reference(snapshot, material_name_box); - const auto ocr_result = MaterialNameReader::instance().read_substring( - stream.logger(), m_language, - material_name_image, OCR::BLACK_OR_WHITE_TEXT_FILTERS() - ); - - std::multimap results; - if (!ocr_result.results.empty()){ - for (const auto& result : ocr_result.results){ - results.emplace(result.first, result.second); - } - } - - if (results.empty()){ - return ""; - } - - if (results.size() > 1){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "ItemPrinterMaterialDetector::detect_material_name(): Unable to read selected item. Ambiguous or multiple results.", - stream - ); - } - - return results.begin()->second.token; -} - -// return vector of row index(es) that matches given material_value. -std::vector ItemPrinterMaterialDetector::find_material_value_row_index( - AsyncDispatcher& dispatcher, - VideoStream& stream, - ProControllerContext& context, - int16_t material_value -) const{ - context.wait_for_all_requests(); - VideoSnapshot snapshot = stream.video().snapshot(); - int8_t total_rows = 10; - std::vector row_indexes; - SpinLock lock; - std::vector> tasks(total_rows); - for (int8_t row_index = 0; row_index < total_rows; row_index++){ - tasks[row_index] = dispatcher.dispatch([&, row_index]{ - int16_t value = read_number(stream.logger(), dispatcher, snapshot, m_box_mat_value[row_index], row_index); - if (value == material_value){ - WriteSpinLock lg(lock); - row_indexes.push_back(row_index); - } - }); - } - - return row_indexes; - -} - -// detect the quantity of material at the given row number -int16_t ItemPrinterMaterialDetector::detect_material_quantity( - AsyncDispatcher& dispatcher, - VideoStream& stream, - ProControllerContext& context, - int8_t row_index -) const{ - context.wait_for_all_requests(); - VideoSnapshot snapshot = stream.video().snapshot(); - int16_t value = read_number(stream.logger(), dispatcher, snapshot, m_box_mat_quantity[row_index], row_index); - return value; -} - - - - -} -} -} +/* Tournament Prize Jobs Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Cpp/Concurrency/AsyncTask.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/Tools/GlobalThreadPools.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/OCR/OCR_NumberReader.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV_ItemPrinterMaterialDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +MaterialNameReader& MaterialNameReader::instance(){ + static MaterialNameReader reader; + return reader; +} + +// MaterialNameReader has a very limited dictionary, +// so it can only reliably read the material names with 68% value +// (i.e. Ditto Goo, Happiny Dust, Magby Hair, Beldum Claw) +MaterialNameReader::MaterialNameReader() + : SmallDictionaryMatcher("PokemonSV/ItemPrinterMaterialOCR.json") +{} + +OCR::StringMatchResult MaterialNameReader::read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio, double max_text_ratio +) const{ + return match_substring_from_image_multifiltered( + &logger, language, image, text_color_ranges, + MAX_LOG10P, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio + ); +} + + +ItemPrinterMaterialDetector::ItemPrinterMaterialDetector(Color color, Language language) + : m_color(color) + , m_language(language) + , m_box_mat_value(Material_Boxes(ImageFloatBox(0.39, 0.176758, 0.025, 0.050))) + , m_box_mat_quantity(Material_Boxes(ImageFloatBox(0.485, 0.176758, 0.037, 0.050))) + , m_box_mat_name(Material_Boxes(ImageFloatBox(0.090, 0.176758, 0.275, 0.050))) +{} + +std::array ItemPrinterMaterialDetector::Material_Boxes(ImageFloatBox initial_box){ + std::array material_boxes; + double x = initial_box.x; + double width = initial_box.width; + double height = initial_box.height; + double initial_y = initial_box.y; + double y_spacing = 0.074219; + for (size_t i = 0; i < 10; i++){ + double y = initial_y + i*y_spacing; + material_boxes[i] = ImageFloatBox(x, y, width, height); + // std::cout << "{" << x << "," << y << "," << width << "," << height << "}, "; + } + // std::cout << std::endl; + return material_boxes; +} + +void ItemPrinterMaterialDetector::make_overlays(VideoOverlaySet& items) const{ + for (size_t i = 0; i < 10; i++){ + items.add(m_color, m_box_mat_value[i]); + items.add(m_color, m_box_mat_quantity[i]); + items.add(m_color, m_box_mat_name[i]); + } +} + +int16_t ItemPrinterMaterialDetector::read_number( + Logger& logger, + const ImageViewRGB32& screen, const ImageFloatBox& box, + int8_t row_index +) const{ + + ImageViewRGB32 cropped = extract_box_reference(screen, box); + ImageRGB32 filtered = to_blackwhite_rgb32_range( + cropped, + true, + 0xff000000, 0xff808080 + ); + // filtered.save("DebugDumps/test-one-filter-1.png"); + bool is_dark_text_light_background = image_stats(filtered).average.sum() > 400; + // std::cout << "Average sum of filtered: "<< std::to_string(image_stats(filtered).average.sum()) << std::endl; + + const std::vector> filters = + [&](){ + if (is_dark_text_light_background){ + return std::vector>{ + // {0xff000000, 0xffb0b0b0}, + {0xff000000, 0xffa0a0a0}, + {0xff000000, 0xff959595}, + {0xff000000, 0xff909090}, + {0xff000000, 0xff858585}, + {0xff000000, 0xff808080}, + // {0xff000000, 0xff707070}, + // {0xff000000, 0xff606060}, + // {0xff000000, 0xff505050}, + // {0xff000000, 0xff404040}, + // {0xff000000, 0xff303030}, + // {0xff000000, 0xff202020}, + // {0xff000000, 0xff101010}, + }; + }else{ + return std::vector>{ + {0xff808080, 0xffffffff}, + {0xff858585, 0xffffffff}, + {0xff909090, 0xffffffff}, + {0xff959595, 0xffffffff}, + {0xffa0a0a0, 0xffffffff}, + // {0xffb0b0b0, 0xffffffff}, + // {0xffc0c0c0, 0xffffffff}, + // {0xffd0d0d0, 0xffffffff}, + // {0xffe0e0e0, 0xffffffff}, + // {0xfff0f0f0, 0xffffffff}, + }; + } + }(); + + size_t max_width = (size_t)((double)24 * screen.width() / 1080); + + int16_t number = (int16_t)OCR::read_number_waterfill_multifilter( + logger, + cropped, filters, + max_width, + true, true, + row_index + ); + + if (number < 1 || number > 999){ + number = -1; + } + return (int16_t)number; +} + + +// return row number where Happiny dust is located on screen +// keep pressing DPAD_RIGHT until Happiny dust is on screen +// check each row on the screen for Happiny Dust +int8_t ItemPrinterMaterialDetector::find_happiny_dust_row_index( + VideoStream& stream, ProControllerContext& context +) const{ + int8_t value_68_row_index; + for (size_t c = 0; c < 30; c++){ + context.wait_for_all_requests(); + std::vector value_68_row_index_list = find_material_value_row_index(stream, context, 68); + for (size_t i = 0; i < value_68_row_index_list.size(); i++){ + value_68_row_index = value_68_row_index_list[i]; + if (detect_material_name(stream, context, value_68_row_index) == "happiny-dust"){ + // found screen and row number with Happiny dust. + // std::cout << "Happiny dust found. Row number: " << std::to_string(value_68_row_index) << std::endl; + return value_68_row_index; + } + } + + // keep searching for Happiny dust + pbf_press_dpad(context, DPAD_RIGHT, 20, 30); + } + + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to find Happiny dust after 10 tries.", + stream + ); + +} + +// detects the material name at the given row_index +// MaterialNameReader has a very limited dictionary, +// so it can only reliably read the material names with 68% value +// (i.e. Ditto Goo, Happiny Dust, Magby Hair, Beldum Claw) +std::string ItemPrinterMaterialDetector::detect_material_name( + VideoStream& stream, + ProControllerContext& context, + int8_t row_index +) const{ + VideoSnapshot snapshot = stream.video().snapshot(); + ImageFloatBox material_name_box = m_box_mat_name[row_index]; + ImageViewRGB32 material_name_image = extract_box_reference(snapshot, material_name_box); + const auto ocr_result = MaterialNameReader::instance().read_substring( + stream.logger(), m_language, + material_name_image, OCR::BLACK_OR_WHITE_TEXT_FILTERS() + ); + + std::multimap results; + if (!ocr_result.results.empty()){ + for (const auto& result : ocr_result.results){ + results.emplace(result.first, result.second); + } + } + + if (results.empty()){ + return ""; + } + + if (results.size() > 1){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "ItemPrinterMaterialDetector::detect_material_name(): Unable to read selected item. Ambiguous or multiple results.", + stream + ); + } + + return results.begin()->second.token; +} + +// return vector of row index(es) that matches given material_value. +std::vector ItemPrinterMaterialDetector::find_material_value_row_index( + VideoStream& stream, + ProControllerContext& context, + int16_t material_value +) const{ + context.wait_for_all_requests(); + VideoSnapshot snapshot = stream.video().snapshot(); + int8_t total_rows = 10; + std::vector row_indexes; + SpinLock lock; + + GlobalThreadPools::normal_inference().run_in_parallel( + [&](size_t index){ + int16_t value = read_number(stream.logger(), snapshot, m_box_mat_value[index], (int8_t)index); + if (value == material_value){ + WriteSpinLock lg(lock); + row_indexes.push_back((int8_t)index); + } + }, + 0, total_rows, 1 + ); + + return row_indexes; + +} + +// detect the quantity of material at the given row number +int16_t ItemPrinterMaterialDetector::detect_material_quantity( + VideoStream& stream, + ProControllerContext& context, + int8_t row_index +) const{ + context.wait_for_all_requests(); + VideoSnapshot snapshot = stream.video().snapshot(); + int16_t value = read_number(stream.logger(), snapshot, m_box_mat_quantity[row_index], row_index); + return value; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMaterialDetector.h b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMaterialDetector.h index b41f8b5217..f3b2960b72 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMaterialDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMaterialDetector.h @@ -1,99 +1,95 @@ -/* Item Printer Jobs Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_ItemPrinterMaterialDetector_H -#define PokemonAutomation_PokemonSV_ItemPrinterMaterialDetector_H - -#include -#include "Common/Cpp/Color.h" -#include "CommonFramework/Language.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" -#include "CommonTools/VisualDetector.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - class Logger; - class AsyncDispatcher; -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class MaterialNameReader : public OCR::SmallDictionaryMatcher{ - static constexpr double MAX_LOG10P = -1.40; - static constexpr double MAX_LOG10P_SPREAD = 0.50; - -public: - MaterialNameReader(); - - static MaterialNameReader& instance(); - - OCR::StringMatchResult read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 - ) const; -}; - -class ItemPrinterMaterialDetector{ -public: - ItemPrinterMaterialDetector(Color color, Language language); - - void make_overlays(VideoOverlaySet& items) const; - - std::array Material_Boxes(ImageFloatBox initial_box); - - int8_t find_happiny_dust_row_index( - AsyncDispatcher& dispatcher, - VideoStream& stream, ProControllerContext& context - ) const; - - std::vector find_material_value_row_index( - AsyncDispatcher& dispatcher, - VideoStream& stream, - ProControllerContext& context, - int16_t material_value - ) const; - - int16_t detect_material_quantity( - AsyncDispatcher& dispatcher, - VideoStream& stream, - ProControllerContext& context, - int8_t row_index - ) const; - - std::string detect_material_name( - VideoStream& stream, - ProControllerContext& context, - int8_t row_index - ) const; - - int16_t read_number( - Logger& logger, AsyncDispatcher& dispatcher, - const ImageViewRGB32& screen, const ImageFloatBox& box, - int8_t row_index - ) const; - - -private: - Color m_color; - Language m_language; - std::array m_box_mat_value; // {0.39,0.176758,0.025,0.05}, {0.39,0.250977,0.025,0.05}, {0.39,0.325196,0.025,0.05}, {0.39,0.399415,0.025,0.05}, {0.39,0.473634,0.025,0.05}, {0.39,0.547853,0.025,0.05}, {0.39,0.622072,0.025,0.05}, {0.39,0.696291,0.025,0.05}, {0.39,0.77051,0.025,0.05}, {0.39,0.844729,0.025,0.05}, - std::array m_box_mat_quantity; // {0.485,0.176758,0.037,0.05}, {0.485,0.250977,0.037,0.05}, {0.485,0.325196,0.037,0.05}, {0.485,0.399415,0.037,0.05}, {0.485,0.473634,0.037,0.05}, {0.485,0.547853,0.037,0.05}, {0.485,0.622072,0.037,0.05}, {0.485,0.696291,0.037,0.05}, {0.485,0.77051,0.037,0.05}, {0.485,0.844729,0.037,0.05}, - std::array m_box_mat_name; // {0.09,0.176758,0.275,0.05}, {0.09,0.250977,0.275,0.05}, {0.09,0.325196,0.275,0.05}, {0.09,0.399415,0.275,0.05}, {0.09,0.473634,0.275,0.05}, {0.09,0.547853,0.275,0.05}, {0.09,0.622072,0.275,0.05}, {0.09,0.696291,0.275,0.05}, {0.09,0.77051,0.275,0.05}, {0.09,0.844729,0.275,0.05}, - - -}; - - - -} -} -} -#endif +/* Item Printer Jobs Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_ItemPrinterMaterialDetector_H +#define PokemonAutomation_PokemonSV_ItemPrinterMaterialDetector_H + +#include +#include "Common/Cpp/Color.h" +#include "CommonFramework/Language.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" +#include "CommonTools/VisualDetector.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + class Logger; +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class MaterialNameReader : public OCR::SmallDictionaryMatcher{ + static constexpr double MAX_LOG10P = -1.40; + static constexpr double MAX_LOG10P_SPREAD = 0.50; + +public: + MaterialNameReader(); + + static MaterialNameReader& instance(); + + OCR::StringMatchResult read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 + ) const; +}; + +class ItemPrinterMaterialDetector{ +public: + ItemPrinterMaterialDetector(Color color, Language language); + + void make_overlays(VideoOverlaySet& items) const; + + std::array Material_Boxes(ImageFloatBox initial_box); + + int8_t find_happiny_dust_row_index( + VideoStream& stream, ProControllerContext& context + ) const; + + std::vector find_material_value_row_index( + VideoStream& stream, + ProControllerContext& context, + int16_t material_value + ) const; + + int16_t detect_material_quantity( + VideoStream& stream, + ProControllerContext& context, + int8_t row_index + ) const; + + std::string detect_material_name( + VideoStream& stream, + ProControllerContext& context, + int8_t row_index + ) const; + + int16_t read_number( + Logger& logger, + const ImageViewRGB32& screen, const ImageFloatBox& box, + int8_t row_index + ) const; + + +private: + Color m_color; + Language m_language; + std::array m_box_mat_value; // {0.39,0.176758,0.025,0.05}, {0.39,0.250977,0.025,0.05}, {0.39,0.325196,0.025,0.05}, {0.39,0.399415,0.025,0.05}, {0.39,0.473634,0.025,0.05}, {0.39,0.547853,0.025,0.05}, {0.39,0.622072,0.025,0.05}, {0.39,0.696291,0.025,0.05}, {0.39,0.77051,0.025,0.05}, {0.39,0.844729,0.025,0.05}, + std::array m_box_mat_quantity; // {0.485,0.176758,0.037,0.05}, {0.485,0.250977,0.037,0.05}, {0.485,0.325196,0.037,0.05}, {0.485,0.399415,0.037,0.05}, {0.485,0.473634,0.037,0.05}, {0.485,0.547853,0.037,0.05}, {0.485,0.622072,0.037,0.05}, {0.485,0.696291,0.037,0.05}, {0.485,0.77051,0.037,0.05}, {0.485,0.844729,0.037,0.05}, + std::array m_box_mat_name; // {0.09,0.176758,0.275,0.05}, {0.09,0.250977,0.275,0.05}, {0.09,0.325196,0.275,0.05}, {0.09,0.399415,0.275,0.05}, {0.09,0.473634,0.275,0.05}, {0.09,0.547853,0.275,0.05}, {0.09,0.622072,0.275,0.05}, {0.09,0.696291,0.275,0.05}, {0.09,0.77051,0.275,0.05}, {0.09,0.844729,0.275,0.05}, + + +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMenuDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMenuDetector.cpp index 7c30af4b16..1621083f88 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMenuDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMenuDetector.cpp @@ -1,40 +1,40 @@ -/* Main Menu Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonSV_ItemPrinterMenuDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -ItemPrinterMenuDetector::ItemPrinterMenuDetector(Color color) - : m_color(color) - , m_bottom(0.05, 0.945, 0.50, 0.04) - , m_buttons(color, WhiteButton::ButtonX, {0.63, 0.93, 0.17, 0.06}) -{} - -void ItemPrinterMenuDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_bottom); - m_buttons.make_overlays(items); -} -bool ItemPrinterMenuDetector::detect(const ImageViewRGB32& screen){ - ImageViewRGB32 bottom = extract_box_reference(screen, m_bottom); - ImageStats bottom_stats = image_stats(bottom); - if (!is_solid(bottom_stats, {0, 0.318898, 0.681102})){ - return false; - } - if (!m_buttons.detect(screen)){ - return false; - } - return true; -} - - -} -} -} +/* Main Menu Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonSV_ItemPrinterMenuDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +ItemPrinterMenuDetector::ItemPrinterMenuDetector(Color color) + : m_color(color) + , m_bottom(0.05, 0.945, 0.50, 0.04) + , m_buttons(color, WhiteButton::ButtonX, {0.63, 0.93, 0.17, 0.06}) +{} + +void ItemPrinterMenuDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_bottom); + m_buttons.make_overlays(items); +} +bool ItemPrinterMenuDetector::detect(const ImageViewRGB32& screen){ + ImageViewRGB32 bottom = extract_box_reference(screen, m_bottom); + ImageStats bottom_stats = image_stats(bottom); + if (!is_solid(bottom_stats, {0, 0.318898, 0.681102})){ + return false; + } + if (!m_buttons.detect(screen)){ + return false; + } + return true; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMenuDetector.h b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMenuDetector.h index 31067a9882..9ef1f47f12 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMenuDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMenuDetector.h @@ -1,45 +1,45 @@ -/* Main Menu Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_ItemPrinterMenuDetector_H -#define PokemonAutomation_PokemonSV_ItemPrinterMenuDetector_H - -#include "CommonTools/VisualDetector.h" -#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class ItemPrinterMenuDetector : public StaticScreenDetector{ -public: - ItemPrinterMenuDetector(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - -private: - Color m_color; - ImageFloatBox m_bottom; - WhiteButtonWatcher m_buttons; -}; -class ItemPrinterMenuWatcher : public DetectorToFinder{ -public: - ItemPrinterMenuWatcher(Color color) - : DetectorToFinder("ItemPrinterMenuWatcher", std::chrono::milliseconds(250), color) - {} -}; - - - - -} -} -} -#endif +/* Main Menu Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_ItemPrinterMenuDetector_H +#define PokemonAutomation_PokemonSV_ItemPrinterMenuDetector_H + +#include "CommonTools/VisualDetector.h" +#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class ItemPrinterMenuDetector : public StaticScreenDetector{ +public: + ItemPrinterMenuDetector(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + +private: + Color m_color; + ImageFloatBox m_bottom; + WhiteButtonWatcher m_buttons; +}; +class ItemPrinterMenuWatcher : public DetectorToFinder{ +public: + ItemPrinterMenuWatcher(Color color) + : DetectorToFinder("ItemPrinterMenuWatcher", std::chrono::milliseconds(250), color) + {} +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterPrizeReader.cpp b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterPrizeReader.cpp index e71e0bbad6..a576119222 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterPrizeReader.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterPrizeReader.cpp @@ -4,9 +4,10 @@ * */ -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" +#include "Common/Cpp/Concurrency/AsyncTask.h" #include "CommonFramework/ImageTypes/ImageRGB32.h" #include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/Tools/GlobalThreadPools.h" #include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" #include "CommonTools/Images/ImageFilter.h" #include "CommonTools/OCR/OCR_RawOCR.h" @@ -78,35 +79,29 @@ void ItemPrinterPrizeReader::make_overlays(VideoOverlaySet& items) const{ } } std::array ItemPrinterPrizeReader::read_prizes( - Logger& logger, AsyncDispatcher& dispatcher, - const ImageViewRGB32& screen + Logger& logger, const ImageViewRGB32& screen ) const{ // OCR 20 things in parallel. OCR::StringMatchResult results[20]; - std::unique_ptr tasks[20]; - for (size_t c = 0; c < 10; c++){ - tasks[c] = dispatcher.dispatch([=, this, &results]{ - results[c] = ItemPrinterPrizeOCR::instance().read_substring( - nullptr, m_language, - extract_box_reference(screen, m_boxes_normal[c]), - OCR::WHITE_TEXT_FILTERS() - ); - }); - } - for (size_t c = 0; c < 10; c++){ - tasks[10 + c] = dispatcher.dispatch([=, this, &results]{ - results[10 + c] = ItemPrinterPrizeOCR::instance().read_substring( - nullptr, m_language, - extract_box_reference(screen, m_boxes_bonus[c]), - OCR::WHITE_TEXT_FILTERS() - ); - }); - } - // Wait for everything. - for (size_t c = 0; c < 20; c++){ - tasks[c]->wait_and_rethrow_exceptions(); - } + GlobalThreadPools::normal_inference().run_in_parallel( + [&](size_t index){ + if (index < 10){ + results[index] = ItemPrinterPrizeOCR::instance().read_substring( + nullptr, m_language, + extract_box_reference(screen, m_boxes_normal[index]), + OCR::WHITE_TEXT_FILTERS() + ); + }else{ + results[index] = ItemPrinterPrizeOCR::instance().read_substring( + nullptr, m_language, + extract_box_reference(screen, m_boxes_bonus[index - 10]), + OCR::WHITE_TEXT_FILTERS() + ); + } + }, + 0, 20, 1 + ); std::array ret; for (size_t c = 0; c < 10; c++){ @@ -127,8 +122,7 @@ std::array ItemPrinterPrizeReader::read_prizes( std::array ItemPrinterPrizeReader::read_quantity( - Logger& logger, AsyncDispatcher& dispatcher, - const ImageViewRGB32& screen + Logger& logger, const ImageViewRGB32& screen ) const{ size_t total_rows = 10; @@ -154,23 +148,13 @@ std::array ItemPrinterPrizeReader::read_quantity( : m_boxes_normal_quantity; std::array results; - std::vector> tasks(total_rows); - for (size_t i = 0; i < total_rows; i++){ - // ImageRGB32 filtered = to_blackwhite_rgb32_range( - // extract_box_reference(screen, m_boxes_bonus_quantity[i]), - // 0xff808000, 0xffffffff, - // true - // ); - // filtered.save("DebugDumps/test"+ std::to_string(i) +".png"); - - tasks[i] = dispatcher.dispatch([&, i]{ - results[i] = read_number(logger, screen, boxes[i], (int8_t)i); - }); - } - for (size_t c = 0; c < total_rows; c++){ - tasks[c]->wait_and_rethrow_exceptions(); - } + GlobalThreadPools::normal_inference().run_in_parallel( + [&](size_t index){ + results[index] = read_number(logger, screen, boxes[index], (int8_t)index); + }, + 0, total_rows, 1 + ); return results; } diff --git a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterPrizeReader.h b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterPrizeReader.h index 86508a6cf6..99334ede8e 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterPrizeReader.h +++ b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterPrizeReader.h @@ -14,7 +14,6 @@ namespace PokemonAutomation{ class Logger; - class AsyncDispatcher; namespace NintendoSwitch{ namespace PokemonSV{ @@ -31,13 +30,11 @@ class ItemPrinterPrizeReader{ void make_overlays(VideoOverlaySet& items) const; std::array read_prizes( - Logger& logger, AsyncDispatcher& dispatcher, - const ImageViewRGB32& screen + Logger& logger, const ImageViewRGB32& screen ) const; std::array read_quantity( - Logger& logger, AsyncDispatcher& dispatcher, - const ImageViewRGB32& screen + Logger& logger, const ImageViewRGB32& screen ) const; int16_t read_number( diff --git a/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.cpp index 1c70f6ee22..3db683ede7 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.cpp @@ -1,163 +1,163 @@ -/* Destination Marker Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/WaterfillUtilities.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "PokemonSV_DestinationMarkerDetector.h" - -// #include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class DestinationMarkerMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - - DestinationMarkerMatcher() : WaterfillTemplateMatcher( - "PokemonSV/Map/DestinationMarkerIcon-Template.png", Color(180,80,0), Color(255, 130, 50), 50 - ){ - m_aspect_ratio_lower = 0.8; - m_aspect_ratio_upper = 1.2; - m_area_ratio_lower = 0.8; - m_area_ratio_upper = 1.2; - - } - - static const ImageMatch::WaterfillTemplateMatcher& instance(){ - static DestinationMarkerMatcher matcher; - return matcher; - } -}; - -class DestinationMarkerYellowMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - - DestinationMarkerYellowMatcher() : WaterfillTemplateMatcher( - "PokemonSV/Map/DestinationMarkerIcon-Yellow.png", Color(180,80,0), Color(255, 200, 50), 50 - ){ - m_aspect_ratio_lower = 0.8; - m_aspect_ratio_upper = 1.2; - m_area_ratio_lower = 0.8; - m_area_ratio_upper = 1.2; - - } - - static const ImageMatch::WaterfillTemplateMatcher& instance(){ - static DestinationMarkerYellowMatcher matcher; - return matcher; - } -}; - - -DestinationMarkerDetector::~DestinationMarkerDetector() = default; - -DestinationMarkerDetector::DestinationMarkerDetector(Color color, const ImageFloatBox& box, bool check_yellow) - : m_color(color) - , m_box(box) - , m_check_yellow(check_yellow) -{} - -void DestinationMarkerDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} - -bool DestinationMarkerDetector::detect(const ImageViewRGB32& screen){ - std::vector hits = detect_all(screen); - if (!m_check_yellow){ - return !hits.empty(); - }else{ - std::vector hits_yellow = detect_all_yellow(screen); - return !hits.empty() || !hits_yellow.empty(); - } -} - -std::vector DestinationMarkerDetector::detect_all(const ImageViewRGB32& screen) const{ - const std::vector> filters = { - {combine_rgb(180, 80, 0), combine_rgb(255, 130, 50)}, - - }; - - - const double rmsd_threshold = 65.0; // from my testing: RMSD is 15 at 1080p, 60 at 720p - const double min_object_size = 150.0; - - const double screen_rel_size = (screen.height() / 1080.0); - const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); - - std::vector found_locations; - - ImagePixelBox pixel_search_area = floatbox_to_pixelbox(screen.width(), screen.height(), m_box); - match_template_by_waterfill( - extract_box_reference(screen, m_box), - DestinationMarkerMatcher::instance(), - filters, - {min_size, SIZE_MAX}, - rmsd_threshold, - [&](Kernels::Waterfill::WaterfillObject& object) -> bool { - ImagePixelBox found_box( - object.min_x + pixel_search_area.min_x, object.min_y + pixel_search_area.min_y, - object.max_x + pixel_search_area.min_x, object.max_y + pixel_search_area.min_y); - found_locations.emplace_back(pixelbox_to_floatbox(screen.width(), screen.height(), found_box)); - return true; - } - ); - - return found_locations; -} - - - -std::vector DestinationMarkerDetector::detect_all_yellow(const ImageViewRGB32& screen) const{ - const std::vector> filters = { - {combine_rgb(180, 100, 0), combine_rgb(255, 190, 50)}, // to detect the marker within the minimap, when the radar beam is covering the marker - }; - - - const double rmsd_threshold = 60.0; // from my testing, RMSD ranges from 15-50, even at 720p - /* - - min object size restrictions also helps to filter out false positives - at pokemon centers - */ - const double min_object_size = 150.0; - - const double screen_rel_size = (screen.height() / 1080.0); - const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); - - std::vector found_locations; - - ImagePixelBox pixel_search_area = floatbox_to_pixelbox(screen.width(), screen.height(), m_box); - match_template_by_waterfill( - extract_box_reference(screen, m_box), - DestinationMarkerYellowMatcher::instance(), - filters, - {min_size, SIZE_MAX}, - rmsd_threshold, - [&](Kernels::Waterfill::WaterfillObject& object) -> bool { - ImagePixelBox found_box( - object.min_x + pixel_search_area.min_x, object.min_y + pixel_search_area.min_y, - object.max_x + pixel_search_area.min_x, object.max_y + pixel_search_area.min_y); - found_locations.emplace_back(pixelbox_to_floatbox(screen.width(), screen.height(), found_box)); - return true; - } - ); - - return found_locations; -} - - - - - - -} -} -} +/* Destination Marker Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/WaterfillUtilities.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "PokemonSV_DestinationMarkerDetector.h" + +// #include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class DestinationMarkerMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + + DestinationMarkerMatcher() : WaterfillTemplateMatcher( + "PokemonSV/Map/DestinationMarkerIcon-Template.png", Color(180,80,0), Color(255, 130, 50), 50 + ){ + m_aspect_ratio_lower = 0.8; + m_aspect_ratio_upper = 1.2; + m_area_ratio_lower = 0.8; + m_area_ratio_upper = 1.2; + + } + + static const ImageMatch::WaterfillTemplateMatcher& instance(){ + static DestinationMarkerMatcher matcher; + return matcher; + } +}; + +class DestinationMarkerYellowMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + + DestinationMarkerYellowMatcher() : WaterfillTemplateMatcher( + "PokemonSV/Map/DestinationMarkerIcon-Yellow.png", Color(180,80,0), Color(255, 200, 50), 50 + ){ + m_aspect_ratio_lower = 0.8; + m_aspect_ratio_upper = 1.2; + m_area_ratio_lower = 0.8; + m_area_ratio_upper = 1.2; + + } + + static const ImageMatch::WaterfillTemplateMatcher& instance(){ + static DestinationMarkerYellowMatcher matcher; + return matcher; + } +}; + + +DestinationMarkerDetector::~DestinationMarkerDetector() = default; + +DestinationMarkerDetector::DestinationMarkerDetector(Color color, const ImageFloatBox& box, bool check_yellow) + : m_color(color) + , m_box(box) + , m_check_yellow(check_yellow) +{} + +void DestinationMarkerDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} + +bool DestinationMarkerDetector::detect(const ImageViewRGB32& screen){ + std::vector hits = detect_all(screen); + if (!m_check_yellow){ + return !hits.empty(); + }else{ + std::vector hits_yellow = detect_all_yellow(screen); + return !hits.empty() || !hits_yellow.empty(); + } +} + +std::vector DestinationMarkerDetector::detect_all(const ImageViewRGB32& screen) const{ + const std::vector> filters = { + {combine_rgb(180, 80, 0), combine_rgb(255, 130, 50)}, + + }; + + + const double rmsd_threshold = 65.0; // from my testing: RMSD is 15 at 1080p, 60 at 720p + const double min_object_size = 150.0; + + const double screen_rel_size = (screen.height() / 1080.0); + const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); + + std::vector found_locations; + + ImagePixelBox pixel_search_area = floatbox_to_pixelbox(screen.width(), screen.height(), m_box); + match_template_by_waterfill( + extract_box_reference(screen, m_box), + DestinationMarkerMatcher::instance(), + filters, + {min_size, SIZE_MAX}, + rmsd_threshold, + [&](Kernels::Waterfill::WaterfillObject& object) -> bool { + ImagePixelBox found_box( + object.min_x + pixel_search_area.min_x, object.min_y + pixel_search_area.min_y, + object.max_x + pixel_search_area.min_x, object.max_y + pixel_search_area.min_y); + found_locations.emplace_back(pixelbox_to_floatbox(screen.width(), screen.height(), found_box)); + return true; + } + ); + + return found_locations; +} + + + +std::vector DestinationMarkerDetector::detect_all_yellow(const ImageViewRGB32& screen) const{ + const std::vector> filters = { + {combine_rgb(180, 100, 0), combine_rgb(255, 190, 50)}, // to detect the marker within the minimap, when the radar beam is covering the marker + }; + + + const double rmsd_threshold = 60.0; // from my testing, RMSD ranges from 15-50, even at 720p + /* + - min object size restrictions also helps to filter out false positives + at pokemon centers + */ + const double min_object_size = 150.0; + + const double screen_rel_size = (screen.height() / 1080.0); + const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); + + std::vector found_locations; + + ImagePixelBox pixel_search_area = floatbox_to_pixelbox(screen.width(), screen.height(), m_box); + match_template_by_waterfill( + extract_box_reference(screen, m_box), + DestinationMarkerYellowMatcher::instance(), + filters, + {min_size, SIZE_MAX}, + rmsd_threshold, + [&](Kernels::Waterfill::WaterfillObject& object) -> bool { + ImagePixelBox found_box( + object.min_x + pixel_search_area.min_x, object.min_y + pixel_search_area.min_y, + object.max_x + pixel_search_area.min_x, object.max_y + pixel_search_area.min_y); + found_locations.emplace_back(pixelbox_to_floatbox(screen.width(), screen.height(), found_box)); + return true; + } + ); + + return found_locations; +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.h index 23c72f2ea0..107cf3bc61 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.h @@ -1,65 +1,65 @@ -/* Destination Marker Detector - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_DestinationMarkerDetector_H -#define PokemonAutomation_PokemonSV_DestinationMarkerDetector_H - -#include -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ - -class VideoOverlaySet; -class VideoOverlay; -class OverlayBoxScope; - -namespace NintendoSwitch{ -namespace PokemonSV{ - -class DestinationMarkerDetector : public StaticScreenDetector{ -public: - DestinationMarkerDetector(Color color, const ImageFloatBox& box, bool check_yellow); - virtual ~DestinationMarkerDetector(); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - std::vector detect_all(const ImageViewRGB32& screen) const; - - // for detecting the marker within the minimap - // ImageFloatBox for detecting within the minimap {0.815, 0.645, 0.180, 0.320}. needs to be slightly higher up than the minimap since the marker will stick up past the minimap - std::vector detect_all_yellow(const ImageViewRGB32& screen) const; - -protected: - Color m_color; - ImageFloatBox m_box; - bool m_check_yellow; -}; - - - -class DestinationMarkerWatcher : public DetectorToFinder{ - public: - DestinationMarkerWatcher( - Color color, - const ImageFloatBox& box, - bool check_yellow = false, - std::chrono::milliseconds duration = std::chrono::milliseconds(250) - ) - : DetectorToFinder("DestinationMarkerWatcher", std::chrono::milliseconds(250), color, box, check_yellow) - {} -}; - - - - -} -} -} -#endif +/* Destination Marker Detector + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_DestinationMarkerDetector_H +#define PokemonAutomation_PokemonSV_DestinationMarkerDetector_H + +#include +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ + +class VideoOverlaySet; +class VideoOverlay; +class OverlayBoxScope; + +namespace NintendoSwitch{ +namespace PokemonSV{ + +class DestinationMarkerDetector : public StaticScreenDetector{ +public: + DestinationMarkerDetector(Color color, const ImageFloatBox& box, bool check_yellow); + virtual ~DestinationMarkerDetector(); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + std::vector detect_all(const ImageViewRGB32& screen) const; + + // for detecting the marker within the minimap + // ImageFloatBox for detecting within the minimap {0.815, 0.645, 0.180, 0.320}. needs to be slightly higher up than the minimap since the marker will stick up past the minimap + std::vector detect_all_yellow(const ImageViewRGB32& screen) const; + +protected: + Color m_color; + ImageFloatBox m_box; + bool m_check_yellow; +}; + + + +class DestinationMarkerWatcher : public DetectorToFinder{ + public: + DestinationMarkerWatcher( + Color color, + const ImageFloatBox& box, + bool check_yellow = false, + std::chrono::milliseconds duration = std::chrono::milliseconds(250) + ) + : DetectorToFinder("DestinationMarkerWatcher", std::chrono::milliseconds(250), color, box, check_yellow) + {} +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.cpp index 4d2afcf0b9..d2f56f3dec 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.cpp @@ -1,242 +1,242 @@ -/* Direction Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/Tools/DebugDumper.h" -#include "CommonTools/Images/WaterfillUtilities.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV_DirectionDetector.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class DirectionMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - - DirectionMatcher() : WaterfillTemplateMatcher( - "PokemonSV/Map/DirectionIcon-Template.png", Color(0, 100, 30), Color(50, 230, 85), 50 - ){ - m_aspect_ratio_lower = 0.8; - m_aspect_ratio_upper = 1.2; - m_area_ratio_lower = 0.8; - m_area_ratio_upper = 1.2; - - } - - static const ImageMatch::WaterfillTemplateMatcher& instance(){ - static DirectionMatcher matcher; - return matcher; - } -}; - - -DirectionDetector::~DirectionDetector() = default; - -DirectionDetector::DirectionDetector(Color color, const ImageFloatBox& box) - : m_color(color) - , m_minimap_box(box) -{} - - -bool DirectionDetector::detect_north(Logger& logger, const ImageViewRGB32& screen) const{ - std::pair north_location = locate_north(logger, screen); - - return !(north_location.first == 0 && north_location.second == 0); -} - - -std::pair DirectionDetector::locate_north(Logger& logger, const ImageViewRGB32& screen) const{ - assert_16_9_720p_min(logger, screen); - - const std::vector> filters = { - {combine_rgb(0, 100, 0), combine_rgb(50, 230, 80)}, - - }; - - const double min_object_size = 50.0; - const double rmsd_threshold = 60.0; - - const double screen_rel_size = (screen.height() / 1080.0); - const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); - - std::pair north_location(0, 0); - OverworldDetector detector; - std::pair zero_coord = detector.locate_ball(screen, true); // 0.9061, 0.8328 - if (zero_coord.first > 0.91 || zero_coord.first < 0.90 || - zero_coord.second > 0.84 || zero_coord.second < 0.82) - { - logger.log("Unable to locate the overworld radar ball, falling back on hard coded location.", COLOR_ORANGE); - zero_coord.first = 0.9061; - zero_coord.second = 0.8328; - // throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unable to locate the overworld radar ball."); - } - - ImagePixelBox pixel_search_area = floatbox_to_pixelbox(screen.width(), screen.height(), m_minimap_box); - match_template_by_waterfill( - extract_box_reference(screen, m_minimap_box), - DirectionMatcher::instance(), - filters, - {min_size, SIZE_MAX}, - rmsd_threshold, - [&](Kernels::Waterfill::WaterfillObject& object) -> bool { - - // relative coord wrt upper left corner - double x1 = (object.center_of_gravity_x() + pixel_search_area.min_x) / (double)screen.width(); - double y1 = (object.center_of_gravity_y() + pixel_search_area.min_y) / (double)screen.height(); - // relative coord wrt minimap radar - double x2 = x1 - zero_coord.first; - double y2 = zero_coord.second - y1; // subtract y from zero_coord since I want north to be positive - // absolute coord wrt minimap radar, scaled to screen size - double x3 = x2 * (double)screen.width() / screen_rel_size; - double y3 = y2 * (double)screen.height() / screen_rel_size; - - double hypotenuse = std::hypot(x3, y3); - // std::cout << "hypotenuse: " << std::to_string(hypotenuse) << std::endl; - if (hypotenuse < 135 || hypotenuse > 155){ - return false; - } - north_location = std::make_pair(x3, y3); - return true; - } - ); - - // std::cout << "north location: " << std::to_string(north_location.first) << ", " << std::to_string(north_location.second) << std::endl; - - return north_location; -} - - -double DirectionDetector::get_current_direction(VideoStream& stream, const ImageViewRGB32& screen) const{ - std::pair north_location = locate_north(stream.logger(), screen); - if (north_location.first == 0 && north_location.second == 0){ // unable to locate north - return -1; - } - double direction = std::atan2(north_location.first, north_location.second); // swap x and y to use north-clockwise convention - // std::cout << std::to_string(direction) << std::endl; - direction = (direction < 0) ? (direction + 2 * PI) : direction; // change (-pi, pi] to [0, 2pi) - // std::cout << "current_direction: " << std::to_string(direction) << std::endl; - return direction; -} - -// return true if the given direction is pointing north -bool is_pointing_north(double direction){ - return (direction < 0.1 && direction >= 0.0) || (direction <= 2 * PI && direction > 2 * PI - 0.1); -} - -// return true if current_direction is pointing north -// if the above applies, the minimap might be locked. but we will need is_minimap_definitely_locked() to confirm. -bool DirectionDetector::is_minimap_possibly_locked(double current_direction) const{ - return is_pointing_north(current_direction); -} - -// - push the joystick to change its position. if still pointing North, then we know it's locked. -bool DirectionDetector::is_minimap_definitely_locked(VideoStream& stream, ProControllerContext& context, double current_direction) const { - bool pointing_north = is_pointing_north(current_direction); - if (!pointing_north){ - return false; - } - pbf_move_right_joystick(context, 0, 128, 100, 20); - context.wait_for_all_requests(); - double new_direction = get_current_direction(stream, stream.video().snapshot()); - - return is_pointing_north(new_direction); -} - -void DirectionDetector::change_direction( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - double direction -) const{ - size_t i = 0; - size_t MAX_ATTEMPTS = 20; - bool is_minimap_definitely_unlocked = false; - uint8_t scale_factor = 80; - double push_magnitude_scale_factor = 1; - while (i < MAX_ATTEMPTS){ // 10 attempts to move the direction to the target - context.wait_for_all_requests(); - VideoSnapshot screen = stream.video().snapshot(); - double current = get_current_direction(stream, screen); - if (current < 0){ - stream.log("Unable to detect current direction."); - return; - } - double target = std::fmod(direction, (2 * PI)); - - // try to find the shortest path around the circle - double diff = target - current; - if(diff > PI) { - diff -= (2 * PI); - } - if(diff <= -PI) { - diff += (2 * PI); - } - double abs_diff = std::abs(diff); - stream.log("current direction: " + std::to_string(current)); - stream.log("target: " + std::to_string(target) + ", diff: " + std::to_string(diff)); - - if (!is_minimap_definitely_unlocked && is_minimap_possibly_locked(current)){ - stream.log("Minimap may be locked. Check if definitely locked."); - if (is_minimap_definitely_locked(stream, context, current)){ - stream.log("Minimap locked. Try to unlock the minimap. Then try again."); - open_map_from_overworld(info, stream, context); - pbf_press_button(context, BUTTON_RCLICK, 20, 20); - pbf_press_button(context, BUTTON_RCLICK, 20, 20); - pbf_press_button(context, BUTTON_B, 20, 100); - press_Bs_to_back_to_overworld(info, stream, context, 7); - }else{ - stream.log("Minimap not locked. Try again"); - } - - is_minimap_definitely_unlocked = true; - i = 0; // even if not locked, we reset the attempt counter since the first attempt is most impactful in terms of cursor movement - continue; - } - is_minimap_definitely_unlocked = true; - - if (abs_diff < 0.0105){ - // return when we're close enough to the target - return; - } - - - if (scale_factor > 40 && abs_diff < 0.05){ - scale_factor = 40; - } - - if (abs_diff < 0.05){ - push_magnitude_scale_factor = 0.5; - } - - uint16_t push_duration = std::max(uint16_t(std::abs(diff * scale_factor)), uint16_t(8)); - int16_t push_direction = (diff > 0) ? -1 : 1; - double push_magnitude = std::max(double((128 * push_magnitude_scale_factor) / (i + 1)), double(15)); // push less with each iteration/attempt - uint8_t push_x = uint8_t(std::max(std::min(int(128 + (push_direction * push_magnitude)), 255), 0)); - stream.log("push magnitude: " + std::to_string(push_x) + ", push duration: " + std::to_string(push_duration)); - pbf_move_right_joystick(context, push_x, 128, push_duration, 100); - i++; - } - -} - - - - -} -} -} +/* Direction Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Tools/DebugDumper.h" +#include "CommonTools/Images/WaterfillUtilities.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV_DirectionDetector.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class DirectionMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + + DirectionMatcher() : WaterfillTemplateMatcher( + "PokemonSV/Map/DirectionIcon-Template.png", Color(0, 100, 30), Color(50, 230, 85), 50 + ){ + m_aspect_ratio_lower = 0.8; + m_aspect_ratio_upper = 1.2; + m_area_ratio_lower = 0.8; + m_area_ratio_upper = 1.2; + + } + + static const ImageMatch::WaterfillTemplateMatcher& instance(){ + static DirectionMatcher matcher; + return matcher; + } +}; + + +DirectionDetector::~DirectionDetector() = default; + +DirectionDetector::DirectionDetector(Color color, const ImageFloatBox& box) + : m_color(color) + , m_minimap_box(box) +{} + + +bool DirectionDetector::detect_north(Logger& logger, const ImageViewRGB32& screen) const{ + std::pair north_location = locate_north(logger, screen); + + return !(north_location.first == 0 && north_location.second == 0); +} + + +std::pair DirectionDetector::locate_north(Logger& logger, const ImageViewRGB32& screen) const{ + assert_16_9_720p_min(logger, screen); + + const std::vector> filters = { + {combine_rgb(0, 100, 0), combine_rgb(50, 230, 80)}, + + }; + + const double min_object_size = 50.0; + const double rmsd_threshold = 60.0; + + const double screen_rel_size = (screen.height() / 1080.0); + const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); + + std::pair north_location(0, 0); + OverworldDetector detector; + std::pair zero_coord = detector.locate_ball(screen, true); // 0.9061, 0.8328 + if (zero_coord.first > 0.91 || zero_coord.first < 0.90 || + zero_coord.second > 0.84 || zero_coord.second < 0.82) + { + logger.log("Unable to locate the overworld radar ball, falling back on hard coded location.", COLOR_ORANGE); + zero_coord.first = 0.9061; + zero_coord.second = 0.8328; + // throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unable to locate the overworld radar ball."); + } + + ImagePixelBox pixel_search_area = floatbox_to_pixelbox(screen.width(), screen.height(), m_minimap_box); + match_template_by_waterfill( + extract_box_reference(screen, m_minimap_box), + DirectionMatcher::instance(), + filters, + {min_size, SIZE_MAX}, + rmsd_threshold, + [&](Kernels::Waterfill::WaterfillObject& object) -> bool { + + // relative coord wrt upper left corner + double x1 = (object.center_of_gravity_x() + pixel_search_area.min_x) / (double)screen.width(); + double y1 = (object.center_of_gravity_y() + pixel_search_area.min_y) / (double)screen.height(); + // relative coord wrt minimap radar + double x2 = x1 - zero_coord.first; + double y2 = zero_coord.second - y1; // subtract y from zero_coord since I want north to be positive + // absolute coord wrt minimap radar, scaled to screen size + double x3 = x2 * (double)screen.width() / screen_rel_size; + double y3 = y2 * (double)screen.height() / screen_rel_size; + + double hypotenuse = std::hypot(x3, y3); + // std::cout << "hypotenuse: " << std::to_string(hypotenuse) << std::endl; + if (hypotenuse < 135 || hypotenuse > 155){ + return false; + } + north_location = std::make_pair(x3, y3); + return true; + } + ); + + // std::cout << "north location: " << std::to_string(north_location.first) << ", " << std::to_string(north_location.second) << std::endl; + + return north_location; +} + + +double DirectionDetector::get_current_direction(VideoStream& stream, const ImageViewRGB32& screen) const{ + std::pair north_location = locate_north(stream.logger(), screen); + if (north_location.first == 0 && north_location.second == 0){ // unable to locate north + return -1; + } + double direction = std::atan2(north_location.first, north_location.second); // swap x and y to use north-clockwise convention + // std::cout << std::to_string(direction) << std::endl; + direction = (direction < 0) ? (direction + 2 * PI) : direction; // change (-pi, pi] to [0, 2pi) + // std::cout << "current_direction: " << std::to_string(direction) << std::endl; + return direction; +} + +// return true if the given direction is pointing north +bool is_pointing_north(double direction){ + return (direction < 0.1 && direction >= 0.0) || (direction <= 2 * PI && direction > 2 * PI - 0.1); +} + +// return true if current_direction is pointing north +// if the above applies, the minimap might be locked. but we will need is_minimap_definitely_locked() to confirm. +bool DirectionDetector::is_minimap_possibly_locked(double current_direction) const{ + return is_pointing_north(current_direction); +} + +// - push the joystick to change its position. if still pointing North, then we know it's locked. +bool DirectionDetector::is_minimap_definitely_locked(VideoStream& stream, ProControllerContext& context, double current_direction) const { + bool pointing_north = is_pointing_north(current_direction); + if (!pointing_north){ + return false; + } + pbf_move_right_joystick(context, 0, 128, 100, 20); + context.wait_for_all_requests(); + double new_direction = get_current_direction(stream, stream.video().snapshot()); + + return is_pointing_north(new_direction); +} + +void DirectionDetector::change_direction( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + double direction +) const{ + size_t i = 0; + size_t MAX_ATTEMPTS = 20; + bool is_minimap_definitely_unlocked = false; + uint8_t scale_factor = 80; + double push_magnitude_scale_factor = 1; + while (i < MAX_ATTEMPTS){ // 10 attempts to move the direction to the target + context.wait_for_all_requests(); + VideoSnapshot screen = stream.video().snapshot(); + double current = get_current_direction(stream, screen); + if (current < 0){ + stream.log("Unable to detect current direction."); + return; + } + double target = std::fmod(direction, (2 * PI)); + + // try to find the shortest path around the circle + double diff = target - current; + if(diff > PI) { + diff -= (2 * PI); + } + if(diff <= -PI) { + diff += (2 * PI); + } + double abs_diff = std::abs(diff); + stream.log("current direction: " + std::to_string(current)); + stream.log("target: " + std::to_string(target) + ", diff: " + std::to_string(diff)); + + if (!is_minimap_definitely_unlocked && is_minimap_possibly_locked(current)){ + stream.log("Minimap may be locked. Check if definitely locked."); + if (is_minimap_definitely_locked(stream, context, current)){ + stream.log("Minimap locked. Try to unlock the minimap. Then try again."); + open_map_from_overworld(info, stream, context); + pbf_press_button(context, BUTTON_RCLICK, 20, 20); + pbf_press_button(context, BUTTON_RCLICK, 20, 20); + pbf_press_button(context, BUTTON_B, 20, 100); + press_Bs_to_back_to_overworld(info, stream, context, 7); + }else{ + stream.log("Minimap not locked. Try again"); + } + + is_minimap_definitely_unlocked = true; + i = 0; // even if not locked, we reset the attempt counter since the first attempt is most impactful in terms of cursor movement + continue; + } + is_minimap_definitely_unlocked = true; + + if (abs_diff < 0.0105){ + // return when we're close enough to the target + return; + } + + + if (scale_factor > 40 && abs_diff < 0.05){ + scale_factor = 40; + } + + if (abs_diff < 0.05){ + push_magnitude_scale_factor = 0.5; + } + + uint16_t push_duration = std::max(uint16_t(std::abs(diff * scale_factor)), uint16_t(8)); + int16_t push_direction = (diff > 0) ? -1 : 1; + double push_magnitude = std::max(double((128 * push_magnitude_scale_factor) / (i + 1)), double(15)); // push less with each iteration/attempt + uint8_t push_x = uint8_t(std::max(std::min(int(128 + (push_direction * push_magnitude)), 255), 0)); + stream.log("push magnitude: " + std::to_string(push_x) + ", push duration: " + std::to_string(push_duration)); + pbf_move_right_joystick(context, push_x, 128, push_duration, 100); + i++; + } + +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h index 8c459de238..fbfe505e27 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h @@ -1,68 +1,68 @@ -/* Direction Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_DirectionDetector_H -#define PokemonAutomation_PokemonSV_DirectionDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - -class VideoOverlaySet; -class VideoOverlay; -class OverlayBoxScope; - -namespace NintendoSwitch{ -namespace PokemonSV{ - -static constexpr double PI = 3.14159265358979323846; - -class DirectionDetector { -public: - DirectionDetector(Color color = COLOR_RED, const ImageFloatBox& box = ImageFloatBox(0.815, 0.680, 0.180, 0.310)); - virtual ~DirectionDetector(); - - bool detect_north(Logger& logger, const ImageViewRGB32& screen) const; - - // return the coordinates of the N symbol, where the coordinates are measured in absolute pixels (scaled to 1080/height) - // with respect to the radar ball - // return 0,0 if unable to locate the N symbol - std::pair locate_north(Logger& logger, const ImageViewRGB32& screen) const; - - // return the direction of the N symbol, in radians, using North-clockwise convention. [0, 2pi) - // return -1 if unable to locate the N symbol - double get_current_direction(VideoStream& stream, const ImageViewRGB32& screen) const; - - bool is_minimap_possibly_locked(double current_direction) const; - - bool is_minimap_definitely_locked(VideoStream& stream, ProControllerContext& context, double current_direction) const; - - // given direction in radians (North-clockwise), rotate the camera so N is pointing in the desired direction. - // mini-map must be unlocked. - void change_direction( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - double direction - ) const; - -protected: - Color m_color; - ImageFloatBox m_minimap_box; -}; - - - -} -} -} -#endif +/* Direction Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_DirectionDetector_H +#define PokemonAutomation_PokemonSV_DirectionDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + +class VideoOverlaySet; +class VideoOverlay; +class OverlayBoxScope; + +namespace NintendoSwitch{ +namespace PokemonSV{ + +static constexpr double PI = 3.14159265358979323846; + +class DirectionDetector { +public: + DirectionDetector(Color color = COLOR_RED, const ImageFloatBox& box = ImageFloatBox(0.815, 0.680, 0.180, 0.310)); + virtual ~DirectionDetector(); + + bool detect_north(Logger& logger, const ImageViewRGB32& screen) const; + + // return the coordinates of the N symbol, where the coordinates are measured in absolute pixels (scaled to 1080/height) + // with respect to the radar ball + // return 0,0 if unable to locate the N symbol + std::pair locate_north(Logger& logger, const ImageViewRGB32& screen) const; + + // return the direction of the N symbol, in radians, using North-clockwise convention. [0, 2pi) + // return -1 if unable to locate the N symbol + double get_current_direction(VideoStream& stream, const ImageViewRGB32& screen) const; + + bool is_minimap_possibly_locked(double current_direction) const; + + bool is_minimap_definitely_locked(VideoStream& stream, ProControllerContext& context, double current_direction) const; + + // given direction in radians (North-clockwise), rotate the camera so N is pointing in the desired direction. + // mini-map must be unlocked. + void change_direction( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + double direction + ) const; + +protected: + Color m_color; + ImageFloatBox m_minimap_box; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.cpp b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.cpp index 30a07bd1c3..2ff868d1d5 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.cpp @@ -23,7 +23,7 @@ using namespace Pokemon; LetsGoHpWatcher::LetsGoHpWatcher(Color color) : VisualInferenceCallback("LetsGoHpWatcher") , m_color(color) - , m_box(0.055, 0.928, 0.067, 0.012) + , m_box(0.057, 0.930, 0.065, 0.010) // , m_last_known_value(-1) {} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.h index 4dbf24909b..24e0d0ff32 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.h @@ -62,7 +62,7 @@ class LetsGoKillWatcher : public DetectorToFinder{ class LetsGoKillSoundDetector : public AudioPerSpectrumDetectorBase{ public: - LetsGoKillSoundDetector(Logger& logger, DetectedCallback detected_callback); + LetsGoKillSoundDetector(Logger& logger, DetectedCallback detected_callback = nullptr); virtual float get_score_threshold() const override; diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.cpp index 73493c8be7..3a581ce7b3 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.cpp @@ -1,37 +1,37 @@ -/* No Minimap Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "PokemonSV_NoMinimapDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -NoMinimapDetector::NoMinimapDetector(Logger& logger, Color color) - : m_color(color) - , m_ball(0.890, 0.800, 0.030, 0.060) - , m_overworld(color) -{} -void NoMinimapDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_ball); -} -bool NoMinimapDetector::detect(const ImageViewRGB32& screen){ - return !m_overworld.detect(screen); -} - - - - -} -} -} +/* No Minimap Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "PokemonSV_NoMinimapDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +NoMinimapDetector::NoMinimapDetector(Logger& logger, Color color) + : m_color(color) + , m_ball(0.890, 0.800, 0.030, 0.060) + , m_overworld(color) +{} +void NoMinimapDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_ball); +} +bool NoMinimapDetector::detect(const ImageViewRGB32& screen){ + return !m_overworld.detect(screen); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.h index d57e99c7c2..ba0c88a055 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.h @@ -1,52 +1,52 @@ -/* No Minimap Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_NoMinimapDetector_H -#define PokemonAutomation_PokemonSV_NoMinimapDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "PokemonSV_OverworldDetector.h" - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -// Detect that the minimap is not visible -class NoMinimapDetector : public StaticScreenDetector{ -public: - NoMinimapDetector(Logger& logger, Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - -protected: - const Color m_color; - const ImageFloatBox m_ball; - OverworldDetector m_overworld; -}; - -class NoMinimapWatcher : public DetectorToFinder{ -public: - NoMinimapWatcher( - Logger& logger, - Color color = COLOR_RED, - std::chrono::milliseconds hold_duration = std::chrono::milliseconds(5000) - ) - : DetectorToFinder("GradientArrowWatcher", hold_duration, logger, color) - {} - -}; - - -} -} -} -#endif +/* No Minimap Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_NoMinimapDetector_H +#define PokemonAutomation_PokemonSV_NoMinimapDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "PokemonSV_OverworldDetector.h" + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +// Detect that the minimap is not visible +class NoMinimapDetector : public StaticScreenDetector{ +public: + NoMinimapDetector(Logger& logger, Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + +protected: + const Color m_color; + const ImageFloatBox m_ball; + OverworldDetector m_overworld; +}; + +class NoMinimapWatcher : public DetectorToFinder{ +public: + NoMinimapWatcher( + Logger& logger, + Color color = COLOR_RED, + std::chrono::milliseconds hold_duration = std::chrono::milliseconds(5000) + ) + : DetectorToFinder("GradientArrowWatcher", hold_duration, logger, color) + {} + +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.cpp index 0bf2a387eb..196ab42bf1 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.cpp @@ -1,382 +1,382 @@ -/* Olive Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/Images/WaterfillUtilities.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Programs/AutoStory/PokemonSV_OliveActionFailedException.h" -#include "PokemonSV_OliveDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class OliveMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - OliveMatcher() : WaterfillTemplateMatcher( - "PokemonSV/Olive.png", Color(0,0,0), Color(255, 255, 255), 5 - ){ - m_aspect_ratio_lower = 0.35; - m_aspect_ratio_upper = 3; - m_area_ratio_lower = 0.5; - m_area_ratio_upper = 1.5; - } - - static const ImageMatch::WaterfillTemplateMatcher& instance(){ - static OliveMatcher matcher; - return matcher; - } -}; - - -OliveDetector::OliveDetector(VideoStream& stream, Color color) - : m_overlays(stream.overlay()) - , m_color(color) -{} -void OliveDetector::make_overlays(VideoOverlaySet& items) const{ -} - - -std::pair OliveDetector::olive_location(VideoStream& stream, ProControllerContext& context, ImageFloatBox box){ - context.wait_for_all_requests(); - ImageFloatBox location = get_olive_floatbox(stream, context, 30, box); - double x = location.x + (location.width / 2); - double y = location.y + (location.height / 2); - - return std::make_pair(x, y); -} - -std::pair box_center(ImageFloatBox& box){ - double x = box.x + (box.width / 2); - double y = box.y + (box.height / 2); - - return std::make_pair(x, y); -} - -ImageFloatBox OliveDetector::get_olive_floatbox(const ImageViewRGB32& screen, ProControllerContext& context, uint8_t rgb_gap, ImageFloatBox box){ - const std::vector> filters = { - {combine_rgb(0, 10, 0), combine_rgb(255, 255, 255)}, - }; - - ImageRGB32 green_only = filter_green(screen, Color(0xff000000), rgb_gap); - - const double min_object_size = 1000; - const double rmsd_threshold = 100; - - const double screen_rel_size = (screen.height() / 1080.0); - const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); - - size_t largest_size = 0; - ImageFloatBox largest_green(0, 0, 0, 0); - ImageViewRGB32 cropped = extract_box_reference(green_only, box); - ImagePixelBox pixel_search_area = floatbox_to_pixelbox(screen.width(), screen.height(), box); - match_template_by_waterfill( - cropped, - OliveMatcher::instance(), - filters, - {min_size, SIZE_MAX}, - rmsd_threshold, - [&](Kernels::Waterfill::WaterfillObject& object) -> bool { - size_t object_area = object.area; - if (object_area > largest_size){ - largest_size = object_area; - // cout << largest_size << endl; - ImagePixelBox found_box( - object.min_x + pixel_search_area.min_x, object.min_y + pixel_search_area.min_y, - object.max_x + pixel_search_area.min_x, object.max_y + pixel_search_area.min_y); - largest_green = pixelbox_to_floatbox(screen.width(), screen.height(), found_box); - } - - return false; - } - ); - - m_overlays.clear(); - m_overlays.add(m_color, largest_green); - - return largest_green; -} - -ImageFloatBox OliveDetector::get_olive_floatbox(VideoStream& stream, ProControllerContext& context, uint8_t rgb_gap, ImageFloatBox box){ - size_t MAX_ATTEMPTS = 2; - for (size_t i = 0; i < MAX_ATTEMPTS; i++){ - context.wait_for_all_requests(); - auto snapshot = stream.video().snapshot(); - const ImageViewRGB32& screen = snapshot; - ImageFloatBox olive_box = get_olive_floatbox(screen, context, rgb_gap, box); - if (olive_box.x == 0 && olive_box.y == 0){ - // Olive not detected. try again. may have been obscured by the player's head/hat - context.wait_for(Milliseconds(2000)); - continue; - } - return olive_box; - } - - // dump_snapshot(stream); - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "get_olive_floatbox(): Olive not detected.", - stream, - OliveFail::NO_OLIVE_DETECTED - ); -} - -ImageFloatBox OliveDetector::align_to_olive( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - double direction_facing, - uint8_t rgb_gap, - ImageFloatBox area_to_check -){ - size_t MAX_ATTEMPTS = 10; - // size_t olive_unchanged_count = 0; - ImageFloatBox olive_box; - DirectionDetector direction; - uint16_t scale_factor = 130; - int16_t prev_push_direction = 0; - for (size_t i = 0; i < MAX_ATTEMPTS; i++){ - direction.change_direction(info, stream, context, direction_facing); - pbf_move_left_joystick(context, 128, 0, 5, 20); - - olive_box = get_olive_floatbox(stream, context, rgb_gap, area_to_check); - - std::pair olive = box_center(olive_box); - double olive_x = olive.first; - double olive_y = olive.second; - double olive_area = olive_box.width * olive_box.height; - - double diff_from_center = olive_x - 0.5; - stream.log("olive_x: " + std::to_string(olive_x) + ", olive_y: " + std::to_string(olive_y) + ", olive_area: " + std::to_string(olive_area)); - if (std::abs(diff_from_center) < 0.01){ - return olive_box; - } - - - int16_t push_direction = (diff_from_center > 0) ? 1 : -1; - if (olive_y > 0.50 && scale_factor > 100){ - scale_factor = 100; - } - if (olive_box.height > 0.35 && scale_factor > 50){ - scale_factor = 50; - } - if (push_direction * -1 == prev_push_direction){ - // if you overshot the olive, and are now pushing in the opposite direction - // then reduce the push_duration. - scale_factor = int16_t(scale_factor * 0.5); - } - - // cout << "olive_height" << olive_box.height << endl; - // if (olive_box.height > 0.4){ - // scale_factor = 50; - // } - - - uint16_t push_duration = std::max(uint16_t((std::abs(diff_from_center) + 0.02) * scale_factor / (olive_y)), uint16_t(15)); - double push_magnitude = 128; // std::max(double(128 / (i + 1)), double(20)); // push less with each iteration/attempt - uint8_t push_x = uint8_t(std::max(std::min(int(128 + (push_direction * push_magnitude)), 255), 0)); - stream.log("scale_factor: " + std::to_string(scale_factor)); - stream.log("push x: " + std::to_string(push_x) + ", push duration: " + std::to_string(push_duration)); - // pbf_wait(context, 100); - uint16_t wait_ticks = 50; - if (std::abs(diff_from_center) < 0.05){ - wait_ticks = 100; - } - pbf_move_left_joystick(context, push_x, 128, push_duration, wait_ticks); - prev_push_direction = push_direction; - - - // // check if we're making progress towards centering on the olive. - // ImageFloatBox olive_box_2 = get_olive_floatbox(console, context, rgb_gap, area_to_check); - // double box_1_area = olive_box.width * olive_box.height; - // double box_2_area = olive_box_2.width * olive_box_2.height; - // double area_diff = std::abs(box_1_area - box_2_area); - // double x_diff = std::abs(olive_box.x - olive_box_2.x); - // double y_diff = std::abs(olive_box.y - olive_box_2.y); - - // if (area_diff < 0.02 && x_diff < 0.01 && y_diff < 0.01){ - // olive_unchanged_count++; - // // not moving closer to the olive. either wall/fence is in the way, or we are right next the olive. - // console.log("Can't align to Olive. Try moving backwards and try again."); - // pbf_move_left_joystick(context, 128, 255, 75, 100); // walk backwards - // if (olive_unchanged_count == 2){ - // throw OliveActionFailedException( - // console, ErrorReport::SEND_ERROR_REPORT, - // "align_to_olive(): Failed to align to olive.", - // true, - // OliveFail::FAILED_ALIGN_TO_OLIVE - // ); - // } - // }else{ - // olive_unchanged_count = 0; - // } - } - return olive_box; - - // don't throw an exception, since sometimes the program has trouble detecting the olive's exact location with the white logo on the olive. - // so we rely on maxing out the attempts to move on. - // throw OliveActionFailedException( - // console, ErrorReport::SEND_ERROR_REPORT, - // "align_to_olive(): Failed to align to olive.", - // true, - // OliveFail::FAILED_ALIGN_TO_OLIVE - // ); -} - - -// todo: detect and handle case where olive is stuck. -// todo: detect and handle case where olive is slightly to the left, and so we need to move on to the next phase -uint16_t OliveDetector::push_olive_forward( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - double direction_facing, - uint16_t total_forward_distance, - uint16_t push_olive, - uint8_t rgb_gap, - ImageFloatBox area_to_check -){ - stream.log("push_olive_forward(): Total distance: " + std::to_string(total_forward_distance)); - // uint16_t initial_push_olive = push_olive; - uint16_t ticks_walked = 0; - size_t MAX_ATTEMPTS = 10; - for (size_t i = 0; i < MAX_ATTEMPTS; i++){ - align_to_olive(info, stream, context, direction_facing, rgb_gap, area_to_check); - ticks_walked += walk_up_to_olive(info, stream, context, direction_facing, rgb_gap, area_to_check); - - - if (ticks_walked >= total_forward_distance){ - stream.log("Distance walked: " + std::to_string(ticks_walked) + "/" + std::to_string(total_forward_distance)); - return ticks_walked; - } - - align_to_olive(info, stream, context, direction_facing, rgb_gap, area_to_check); - // check location of olive before and after push - // if olive is approximately in the same location, then the olive is stuck. try moving backward and running forward again. - ImageFloatBox olive_box_1 = get_olive_floatbox(stream, context, rgb_gap, area_to_check); - for (size_t j = 0; j < 3; j++){ - stream.log("Distance walked: " + std::to_string(ticks_walked) + "/" + std::to_string(total_forward_distance)); - stream.log("Push the olive."); - pbf_move_left_joystick(context, 128, 0, push_olive, 7 * TICKS_PER_SECOND); - - ticks_walked += push_olive; - ImageFloatBox olive_box_2 = get_olive_floatbox(stream, context, rgb_gap, area_to_check); - double box_1_area = olive_box_1.width * olive_box_1.height; - double box_2_area = olive_box_2.width * olive_box_2.height; - double area_diff = std::abs(box_1_area - box_2_area); - double x_diff = std::abs(olive_box_1.x - olive_box_2.x); - double y_diff = std::abs(olive_box_1.y - olive_box_2.y); - - if (area_diff < 0.02 && x_diff < 0.05 && y_diff < 0.05){ - stream.log("Olive is stuck? Move backwards and try pushing again."); - stream.log("Olive 1: area: " + std::to_string(box_1_area) + ", x: " + std::to_string(olive_box_1.x) + ", y: " + std::to_string(olive_box_1.y)); - stream.log("Olive 2: area: " + std::to_string(box_2_area) + ", x: " + std::to_string(olive_box_2.x) + ", y: " + std::to_string(olive_box_2.y)); - pbf_move_left_joystick(context, 128, 255, 75, 100); // walk backwards - ticks_walked -= push_olive; - push_olive = 200; // run forward more on the next push - - if (j == 2){ - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "push_olive_forward(): Olive stuck.", - stream, - OliveFail::OLIVE_STUCK - ); - } - }else{ - break; - } - } - - if (ticks_walked > total_forward_distance){ - stream.log("Distance walked: " + std::to_string(ticks_walked) + "/" + std::to_string(total_forward_distance)); - return ticks_walked; - } - - stream.log("Distance walked: " + std::to_string(ticks_walked) + "/" + std::to_string(total_forward_distance)); - - } - - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "push_olive_forward(): Something went wrong. Failed to walk the Olive forward as expected.", - stream, - OliveFail::FAILED_PUSH_OLIVE_TOTAL_DISTANCE - ); - -} - -uint16_t OliveDetector::walk_up_to_olive( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - double direction_facing, - uint8_t rgb_gap, - ImageFloatBox area_to_check -){ - uint16_t ticks_walked = 0; - size_t MAX_ATTEMPTS = 20; - for (size_t i = 0; i < MAX_ATTEMPTS; i++){ - ImageFloatBox olive_box = get_olive_floatbox(stream, context, rgb_gap, area_to_check); - std::pair olive = box_center(olive_box); - // double olive_x = olive.first; - double olive_y = olive.second; - - uint16_t scale_factor = 2000; - uint16_t push_duration = std::max(uint16_t((0.57 - olive_y)*(0.57 - olive_y) * scale_factor), uint16_t(20)); - stream.log("walk_up_to_olive(): olive_y: " + std::to_string(olive_y)); - if (olive_y > 0.515){ - return ticks_walked; - } - stream.log("push duration: " + std::to_string(push_duration)); - // when push durations are low, the player moves less than expected - // once above 45, you walk about as much as expected - double walking_factor = 1; - if (push_duration <= 20){ - walking_factor = 0.40; - }else if (push_duration <= 25){ - walking_factor = 0.53; - }else if (push_duration <= 30){ - walking_factor = 0.69; - }else if (push_duration <= 35){ - walking_factor = 0.83; - }else if (push_duration <= 40){ - walking_factor = 0.91; - } - ticks_walked += uint16_t(push_duration * walking_factor); - - uint16_t wait_ticks = 50; - if (olive_y > 0.4){ - wait_ticks = 100; - } - pbf_move_left_joystick(context, 128, 0, push_duration, wait_ticks); - } - - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "walk_up_to_olive(): Something went wrong. Failed to walk up to the Olive", - stream, - OliveFail::FAILED_WALK_TO_OLIVE - ); - -} - - - -} -} -} +/* Olive Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/Images/WaterfillUtilities.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Programs/AutoStory/PokemonSV_OliveActionFailedException.h" +#include "PokemonSV_OliveDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class OliveMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + OliveMatcher() : WaterfillTemplateMatcher( + "PokemonSV/Olive.png", Color(0,0,0), Color(255, 255, 255), 5 + ){ + m_aspect_ratio_lower = 0.35; + m_aspect_ratio_upper = 3; + m_area_ratio_lower = 0.5; + m_area_ratio_upper = 1.5; + } + + static const ImageMatch::WaterfillTemplateMatcher& instance(){ + static OliveMatcher matcher; + return matcher; + } +}; + + +OliveDetector::OliveDetector(VideoStream& stream, Color color) + : m_overlays(stream.overlay()) + , m_color(color) +{} +void OliveDetector::make_overlays(VideoOverlaySet& items) const{ +} + + +std::pair OliveDetector::olive_location(VideoStream& stream, ProControllerContext& context, ImageFloatBox box){ + context.wait_for_all_requests(); + ImageFloatBox location = get_olive_floatbox(stream, context, 30, box); + double x = location.x + (location.width / 2); + double y = location.y + (location.height / 2); + + return std::make_pair(x, y); +} + +std::pair box_center(ImageFloatBox& box){ + double x = box.x + (box.width / 2); + double y = box.y + (box.height / 2); + + return std::make_pair(x, y); +} + +ImageFloatBox OliveDetector::get_olive_floatbox(const ImageViewRGB32& screen, ProControllerContext& context, uint8_t rgb_gap, ImageFloatBox box){ + const std::vector> filters = { + {combine_rgb(0, 10, 0), combine_rgb(255, 255, 255)}, + }; + + ImageRGB32 green_only = filter_green(screen, Color(0xff000000), rgb_gap); + + const double min_object_size = 1000; + const double rmsd_threshold = 100; + + const double screen_rel_size = (screen.height() / 1080.0); + const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); + + size_t largest_size = 0; + ImageFloatBox largest_green(0, 0, 0, 0); + ImageViewRGB32 cropped = extract_box_reference(green_only, box); + ImagePixelBox pixel_search_area = floatbox_to_pixelbox(screen.width(), screen.height(), box); + match_template_by_waterfill( + cropped, + OliveMatcher::instance(), + filters, + {min_size, SIZE_MAX}, + rmsd_threshold, + [&](Kernels::Waterfill::WaterfillObject& object) -> bool { + size_t object_area = object.area; + if (object_area > largest_size){ + largest_size = object_area; + // cout << largest_size << endl; + ImagePixelBox found_box( + object.min_x + pixel_search_area.min_x, object.min_y + pixel_search_area.min_y, + object.max_x + pixel_search_area.min_x, object.max_y + pixel_search_area.min_y); + largest_green = pixelbox_to_floatbox(screen.width(), screen.height(), found_box); + } + + return false; + } + ); + + m_overlays.clear(); + m_overlays.add(m_color, largest_green); + + return largest_green; +} + +ImageFloatBox OliveDetector::get_olive_floatbox(VideoStream& stream, ProControllerContext& context, uint8_t rgb_gap, ImageFloatBox box){ + size_t MAX_ATTEMPTS = 2; + for (size_t i = 0; i < MAX_ATTEMPTS; i++){ + context.wait_for_all_requests(); + auto snapshot = stream.video().snapshot(); + const ImageViewRGB32& screen = snapshot; + ImageFloatBox olive_box = get_olive_floatbox(screen, context, rgb_gap, box); + if (olive_box.x == 0 && olive_box.y == 0){ + // Olive not detected. try again. may have been obscured by the player's head/hat + context.wait_for(Milliseconds(2000)); + continue; + } + return olive_box; + } + + // dump_snapshot(stream); + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "get_olive_floatbox(): Olive not detected.", + stream, + OliveFail::NO_OLIVE_DETECTED + ); +} + +ImageFloatBox OliveDetector::align_to_olive( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + double direction_facing, + uint8_t rgb_gap, + ImageFloatBox area_to_check +){ + size_t MAX_ATTEMPTS = 10; + // size_t olive_unchanged_count = 0; + ImageFloatBox olive_box; + DirectionDetector direction; + uint16_t scale_factor = 130; + int16_t prev_push_direction = 0; + for (size_t i = 0; i < MAX_ATTEMPTS; i++){ + direction.change_direction(info, stream, context, direction_facing); + pbf_move_left_joystick(context, 128, 0, 5, 20); + + olive_box = get_olive_floatbox(stream, context, rgb_gap, area_to_check); + + std::pair olive = box_center(olive_box); + double olive_x = olive.first; + double olive_y = olive.second; + double olive_area = olive_box.width * olive_box.height; + + double diff_from_center = olive_x - 0.5; + stream.log("olive_x: " + std::to_string(olive_x) + ", olive_y: " + std::to_string(olive_y) + ", olive_area: " + std::to_string(olive_area)); + if (std::abs(diff_from_center) < 0.01){ + return olive_box; + } + + + int16_t push_direction = (diff_from_center > 0) ? 1 : -1; + if (olive_y > 0.50 && scale_factor > 100){ + scale_factor = 100; + } + if (olive_box.height > 0.35 && scale_factor > 50){ + scale_factor = 50; + } + if (push_direction * -1 == prev_push_direction){ + // if you overshot the olive, and are now pushing in the opposite direction + // then reduce the push_duration. + scale_factor = int16_t(scale_factor * 0.5); + } + + // cout << "olive_height" << olive_box.height << endl; + // if (olive_box.height > 0.4){ + // scale_factor = 50; + // } + + + uint16_t push_duration = std::max(uint16_t((std::abs(diff_from_center) + 0.02) * scale_factor / (olive_y)), uint16_t(15)); + double push_magnitude = 128; // std::max(double(128 / (i + 1)), double(20)); // push less with each iteration/attempt + uint8_t push_x = uint8_t(std::max(std::min(int(128 + (push_direction * push_magnitude)), 255), 0)); + stream.log("scale_factor: " + std::to_string(scale_factor)); + stream.log("push x: " + std::to_string(push_x) + ", push duration: " + std::to_string(push_duration)); + // pbf_wait(context, 100); + uint16_t wait_ticks = 50; + if (std::abs(diff_from_center) < 0.05){ + wait_ticks = 100; + } + pbf_move_left_joystick(context, push_x, 128, push_duration, wait_ticks); + prev_push_direction = push_direction; + + + // // check if we're making progress towards centering on the olive. + // ImageFloatBox olive_box_2 = get_olive_floatbox(console, context, rgb_gap, area_to_check); + // double box_1_area = olive_box.width * olive_box.height; + // double box_2_area = olive_box_2.width * olive_box_2.height; + // double area_diff = std::abs(box_1_area - box_2_area); + // double x_diff = std::abs(olive_box.x - olive_box_2.x); + // double y_diff = std::abs(olive_box.y - olive_box_2.y); + + // if (area_diff < 0.02 && x_diff < 0.01 && y_diff < 0.01){ + // olive_unchanged_count++; + // // not moving closer to the olive. either wall/fence is in the way, or we are right next the olive. + // console.log("Can't align to Olive. Try moving backwards and try again."); + // pbf_move_left_joystick(context, 128, 255, 75, 100); // walk backwards + // if (olive_unchanged_count == 2){ + // throw OliveActionFailedException( + // console, ErrorReport::SEND_ERROR_REPORT, + // "align_to_olive(): Failed to align to olive.", + // true, + // OliveFail::FAILED_ALIGN_TO_OLIVE + // ); + // } + // }else{ + // olive_unchanged_count = 0; + // } + } + return olive_box; + + // don't throw an exception, since sometimes the program has trouble detecting the olive's exact location with the white logo on the olive. + // so we rely on maxing out the attempts to move on. + // throw OliveActionFailedException( + // console, ErrorReport::SEND_ERROR_REPORT, + // "align_to_olive(): Failed to align to olive.", + // true, + // OliveFail::FAILED_ALIGN_TO_OLIVE + // ); +} + + +// todo: detect and handle case where olive is stuck. +// todo: detect and handle case where olive is slightly to the left, and so we need to move on to the next phase +uint16_t OliveDetector::push_olive_forward( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + double direction_facing, + uint16_t total_forward_distance, + uint16_t push_olive, + uint8_t rgb_gap, + ImageFloatBox area_to_check +){ + stream.log("push_olive_forward(): Total distance: " + std::to_string(total_forward_distance)); + // uint16_t initial_push_olive = push_olive; + uint16_t ticks_walked = 0; + size_t MAX_ATTEMPTS = 10; + for (size_t i = 0; i < MAX_ATTEMPTS; i++){ + align_to_olive(info, stream, context, direction_facing, rgb_gap, area_to_check); + ticks_walked += walk_up_to_olive(info, stream, context, direction_facing, rgb_gap, area_to_check); + + + if (ticks_walked >= total_forward_distance){ + stream.log("Distance walked: " + std::to_string(ticks_walked) + "/" + std::to_string(total_forward_distance)); + return ticks_walked; + } + + align_to_olive(info, stream, context, direction_facing, rgb_gap, area_to_check); + // check location of olive before and after push + // if olive is approximately in the same location, then the olive is stuck. try moving backward and running forward again. + ImageFloatBox olive_box_1 = get_olive_floatbox(stream, context, rgb_gap, area_to_check); + for (size_t j = 0; j < 3; j++){ + stream.log("Distance walked: " + std::to_string(ticks_walked) + "/" + std::to_string(total_forward_distance)); + stream.log("Push the olive."); + pbf_move_left_joystick(context, 128, 0, push_olive, 7 * TICKS_PER_SECOND); + + ticks_walked += push_olive; + ImageFloatBox olive_box_2 = get_olive_floatbox(stream, context, rgb_gap, area_to_check); + double box_1_area = olive_box_1.width * olive_box_1.height; + double box_2_area = olive_box_2.width * olive_box_2.height; + double area_diff = std::abs(box_1_area - box_2_area); + double x_diff = std::abs(olive_box_1.x - olive_box_2.x); + double y_diff = std::abs(olive_box_1.y - olive_box_2.y); + + if (area_diff < 0.02 && x_diff < 0.05 && y_diff < 0.05){ + stream.log("Olive is stuck? Move backwards and try pushing again."); + stream.log("Olive 1: area: " + std::to_string(box_1_area) + ", x: " + std::to_string(olive_box_1.x) + ", y: " + std::to_string(olive_box_1.y)); + stream.log("Olive 2: area: " + std::to_string(box_2_area) + ", x: " + std::to_string(olive_box_2.x) + ", y: " + std::to_string(olive_box_2.y)); + pbf_move_left_joystick(context, 128, 255, 75, 100); // walk backwards + ticks_walked -= push_olive; + push_olive = 200; // run forward more on the next push + + if (j == 2){ + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "push_olive_forward(): Olive stuck.", + stream, + OliveFail::OLIVE_STUCK + ); + } + }else{ + break; + } + } + + if (ticks_walked > total_forward_distance){ + stream.log("Distance walked: " + std::to_string(ticks_walked) + "/" + std::to_string(total_forward_distance)); + return ticks_walked; + } + + stream.log("Distance walked: " + std::to_string(ticks_walked) + "/" + std::to_string(total_forward_distance)); + + } + + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "push_olive_forward(): Something went wrong. Failed to walk the Olive forward as expected.", + stream, + OliveFail::FAILED_PUSH_OLIVE_TOTAL_DISTANCE + ); + +} + +uint16_t OliveDetector::walk_up_to_olive( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + double direction_facing, + uint8_t rgb_gap, + ImageFloatBox area_to_check +){ + uint16_t ticks_walked = 0; + size_t MAX_ATTEMPTS = 20; + for (size_t i = 0; i < MAX_ATTEMPTS; i++){ + ImageFloatBox olive_box = get_olive_floatbox(stream, context, rgb_gap, area_to_check); + std::pair olive = box_center(olive_box); + // double olive_x = olive.first; + double olive_y = olive.second; + + uint16_t scale_factor = 2000; + uint16_t push_duration = std::max(uint16_t((0.57 - olive_y)*(0.57 - olive_y) * scale_factor), uint16_t(20)); + stream.log("walk_up_to_olive(): olive_y: " + std::to_string(olive_y)); + if (olive_y > 0.515){ + return ticks_walked; + } + stream.log("push duration: " + std::to_string(push_duration)); + // when push durations are low, the player moves less than expected + // once above 45, you walk about as much as expected + double walking_factor = 1; + if (push_duration <= 20){ + walking_factor = 0.40; + }else if (push_duration <= 25){ + walking_factor = 0.53; + }else if (push_duration <= 30){ + walking_factor = 0.69; + }else if (push_duration <= 35){ + walking_factor = 0.83; + }else if (push_duration <= 40){ + walking_factor = 0.91; + } + ticks_walked += uint16_t(push_duration * walking_factor); + + uint16_t wait_ticks = 50; + if (olive_y > 0.4){ + wait_ticks = 100; + } + pbf_move_left_joystick(context, 128, 0, push_duration, wait_ticks); + } + + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "walk_up_to_olive(): Something went wrong. Failed to walk up to the Olive", + stream, + OliveFail::FAILED_WALK_TO_OLIVE + ); + +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.h index c78a2afc26..48f9aa06e6 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.h @@ -1,88 +1,88 @@ -/* Olive Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_OliveDetector_H -#define PokemonAutomation_PokemonSV_OliveDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class OliveDetector { -public: - OliveDetector(VideoStream& stream, Color color = COLOR_RED); - - void make_overlays(VideoOverlaySet& items) const; - - std::pair olive_location(VideoStream& stream, ProControllerContext& context, ImageFloatBox box = {0, 0.15, 1, 0.7}); - - ImageFloatBox get_olive_floatbox( - const ImageViewRGB32& screen, - ProControllerContext& context, - uint8_t rgb_gap, - ImageFloatBox box - ); - - // return ImageFloatBox of the of the Olive, based on the largest blob of green - ImageFloatBox get_olive_floatbox( - VideoStream& stream, - ProControllerContext& context, - uint8_t rgb_gap, - ImageFloatBox box - ); - - ImageFloatBox align_to_olive( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - double direction_facing, - uint8_t rgb_gap = 20, - ImageFloatBox area_to_check = {0, 0.3, 1.0, 0.40} - ); - - // push the olive forward. - // move forward a certain number of ticks, as per total_forward_distance - // always face a certain direction, as per direction_facing - // return number of ticks walked - uint16_t push_olive_forward( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - double direction_facing, - uint16_t total_forward_distance, - uint16_t push_olive = 75, - uint8_t rgb_gap = 20, - ImageFloatBox area_to_check = {0, 0.3, 1.0, 0.40} // {0, 0.15, 1, 0.7} - ); - - uint16_t walk_up_to_olive( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - double direction_facing, - uint8_t rgb_gap = 20, - ImageFloatBox area_to_check = {0, 0.3, 1.0, 0.40} - ); - - -protected: - VideoOverlaySet m_overlays; - const Color m_color; -}; - - - -} -} -} -#endif +/* Olive Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_OliveDetector_H +#define PokemonAutomation_PokemonSV_OliveDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class OliveDetector { +public: + OliveDetector(VideoStream& stream, Color color = COLOR_RED); + + void make_overlays(VideoOverlaySet& items) const; + + std::pair olive_location(VideoStream& stream, ProControllerContext& context, ImageFloatBox box = {0, 0.15, 1, 0.7}); + + ImageFloatBox get_olive_floatbox( + const ImageViewRGB32& screen, + ProControllerContext& context, + uint8_t rgb_gap, + ImageFloatBox box + ); + + // return ImageFloatBox of the of the Olive, based on the largest blob of green + ImageFloatBox get_olive_floatbox( + VideoStream& stream, + ProControllerContext& context, + uint8_t rgb_gap, + ImageFloatBox box + ); + + ImageFloatBox align_to_olive( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + double direction_facing, + uint8_t rgb_gap = 20, + ImageFloatBox area_to_check = {0, 0.3, 1.0, 0.40} + ); + + // push the olive forward. + // move forward a certain number of ticks, as per total_forward_distance + // always face a certain direction, as per direction_facing + // return number of ticks walked + uint16_t push_olive_forward( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + double direction_facing, + uint16_t total_forward_distance, + uint16_t push_olive = 75, + uint8_t rgb_gap = 20, + ImageFloatBox area_to_check = {0, 0.3, 1.0, 0.40} // {0, 0.15, 1, 0.7} + ); + + uint16_t walk_up_to_olive( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + double direction_facing, + uint8_t rgb_gap = 20, + ImageFloatBox area_to_check = {0, 0.3, 1.0, 0.40} + ); + + +protected: + VideoOverlaySet m_overlays; + const Color m_color; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OverworldSensors.cpp b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OverworldSensors.cpp new file mode 100644 index 0000000000..f581cf2863 --- /dev/null +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OverworldSensors.cpp @@ -0,0 +1,177 @@ +/* Overworld Sensors + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/AbstractLogger.h" +#include "CommonTools/Images/ImageFilter.h" +#include "PokemonSV_OverworldSensors.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +ShinySoundTracker::ShinySoundTracker(Logger& logger) + : ShinySoundDetector(logger, [this](float error){ +// cout << "New: Shiny Sound" << endl; + on_shiny_detected(error); + return false; + }) + , VisualInferenceCallback("ShinyScreenshotTracker") + , m_last_detection(WallClock::min()) + , m_last_error(1.0) +{} +bool ShinySoundTracker::last_detection( + WallClock& timestamp, float& error, + VideoSnapshot& screenshot +) const{ + ReadSpinLock lg(m_lock); + if (m_last_detection == WallClock::min()){ + return false; + } + timestamp = m_last_detection; + error = m_last_error; + screenshot = m_last_screenshot; + return true; +} +void ShinySoundTracker::on_shiny_detected(float error){ + WallClock now = current_time(); + WallClock threshold = now - std::chrono::seconds(1); + + // Find the brightest frame. + ReadSpinLock lg(m_lock); + + VideoSnapshot best_snapshot; + double best_bright_portion = 0; + + for (const VideoSnapshot& frame : m_history){ + if (frame.timestamp >= threshold){ + break; + } + size_t bright_pixels; + filter_rgb32_range(bright_pixels, frame, 0xffe0e000, 0xffffffff, Color(0xff000000), false); + double bright_portion = bright_pixels / (double)(frame->width() * frame->height()); + if (best_bright_portion < bright_portion){ + best_bright_portion = bright_portion; + best_snapshot = frame; + } + } + + m_last_screenshot = std::move(best_snapshot); + m_last_detection = now; + m_last_error = error; +} +bool ShinySoundTracker::process_frame(const VideoSnapshot& frame){ + if (!frame){ + return false; + } + + WriteSpinLock lg(m_lock); + + // Clear old history. + while (!m_history.empty() && m_history.front().timestamp + std::chrono::milliseconds(2000) < frame.timestamp){ + m_history.pop_front(); + } + + // Add current frame if it has been long enough since the previous. + if (m_history.empty() || m_history.back().timestamp + std::chrono::milliseconds(250) < frame.timestamp){ + m_history.push_back(frame); + } + + return false; +} + + + + + + + + + + + +OverworldBattleTracker::OverworldBattleTracker(Logger& logger, OverworldSensors& sensors) + : m_logger(logger) + , m_sensors(sensors) + , m_start_time(current_time()) + , m_last_known_in_battle(false) +{} +auto OverworldBattleTracker::report_battle_menu_detected() -> Detection{ + bool is_shiny = false; + WallClock last_shiny_sound; + float last_shiny_error; + VideoSnapshot last_shiny_screenshot; + if (m_sensors.shiny_sound.last_detection(last_shiny_sound, last_shiny_error, last_shiny_screenshot)){ + is_shiny = m_start_time < last_shiny_sound; + } + + bool start_battle = m_start_time < m_sensors.start_battle.last_detected(); + + if (is_shiny && !start_battle){ + m_logger.log("Detected a shiny without a start of battle.", COLOR_RED); + } + if (!m_last_known_in_battle && !start_battle){ + m_logger.log("Detected a battle menu without a start of battle.", COLOR_RED); + } + + if (is_shiny){ + return Detection::NEW_SHINY_BATTLE; + } + if (start_battle){ + return Detection::NEW_BATTLE; + } + return Detection::CONTINUE_BATTLE; +} +auto OverworldBattleTracker::report_battle_menu_detected(VideoSnapshot& shiny_screenshot, float& shiny_error) -> Detection{ + bool is_shiny = false; + WallClock last_shiny_sound; + if (m_sensors.shiny_sound.last_detection(last_shiny_sound, shiny_error, shiny_screenshot)){ + is_shiny = m_start_time < last_shiny_sound; + } + + bool start_battle = m_start_time < m_sensors.start_battle.last_detected(); + + if (is_shiny && !start_battle){ + m_logger.log("Detected a shiny without a start of battle.", COLOR_RED); + } + if (!m_last_known_in_battle && !start_battle){ + m_logger.log("Detected a battle menu without a start of battle.", COLOR_RED); + } + + if (is_shiny){ + return Detection::NEW_SHINY_BATTLE; + } + if (start_battle){ + return Detection::NEW_BATTLE; + } + return Detection::CONTINUE_BATTLE; +} + + + + + + + + + + + + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OverworldSensors.h b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OverworldSensors.h new file mode 100644 index 0000000000..cd64778304 --- /dev/null +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OverworldSensors.h @@ -0,0 +1,164 @@ +/* Overworld Sensors + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_OverworldSensors_H +#define PokemonAutomation_PokemonSV_OverworldSensors_H + +#include "Common/Cpp/CancellableScope.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceSession.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "PokemonSV/Inference/Battles/PokemonSV_StartBattleYellowBar.h" +#include "PokemonSV/Inference/Battles/PokemonSV_ShinySoundDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class ShinySoundTracker : public ShinySoundDetector, public VisualInferenceCallback{ +public: + ShinySoundTracker(Logger& logger); + + bool last_detection( + WallClock& timestamp, float& error, + VideoSnapshot& screenshot + ) const; + + virtual void make_overlays(VideoOverlaySet& items) const override{} + virtual bool process_frame(const VideoSnapshot& frame) override; + +private: + void on_shiny_detected(float error); + +private: + mutable SpinLock m_lock; + + WallClock m_last_detection; + float m_last_error; + VideoSnapshot m_last_screenshot; + + std::deque m_history; +}; + + + + + + +class OverworldSensors{ +public: + using DetectedCallback = AudioPerSpectrumDetectorBase::DetectedCallback; + + OverworldSensors( + Logger& logger, VideoStream& stream, CancellableScope& scope + ) + : lets_go_hp(COLOR_RED) + , lets_go_kill(logger) + , start_battle(COLOR_RED) + , shiny_sound(logger) + , m_session( + scope, stream, + { + lets_go_hp, + lets_go_kill, + start_battle, + static_cast(shiny_sound), + static_cast(shiny_sound), +// shiny_screenshot, + } + ) + { + } + + void throw_if_no_sound(Milliseconds min_duration = Milliseconds(10000)) const{ + lets_go_kill.throw_if_no_sound(min_duration); + shiny_sound.throw_if_no_sound(min_duration); + } + +public: + LetsGoHpWatcher lets_go_hp; + LetsGoKillSoundDetector lets_go_kill; + StartBattleYellowBarWatcher start_battle; + ShinySoundTracker shiny_sound; +// ShinyScreenshotTracker shiny_screenshot; + + +private: + InferenceSession m_session; +}; + + + + + + + + + + +class OverworldBattleTracker{ +public: + enum class Detection{ + CONTINUE_BATTLE, + NEW_BATTLE, + NEW_SHINY_BATTLE, + }; + +public: + OverworldBattleTracker(Logger& logger, OverworldSensors& sensors); + + void report_in_battle(){ + m_start_time = current_time(); + m_last_known_in_battle = true; + } + void report_out_of_battle(){ + m_start_time = current_time(); + m_last_known_in_battle = false; + } + + Detection report_battle_menu_detected(); + Detection report_battle_menu_detected(VideoSnapshot& shiny_screenshot, float& shiny_error); + +private: + Logger& m_logger; + OverworldSensors& m_sensors; + WallClock m_start_time; + bool m_last_known_in_battle; +}; + + + + + + + + + + + + + + + + + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.cpp b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.cpp index 4105e8cd8a..c5344bef91 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.cpp @@ -1,72 +1,72 @@ -/* Stationary Overworld Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/WaterfillUtilities.h" -#include "PokemonSV_StationaryOverworldWatcher.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - - -StationaryOverworldWatcher::StationaryOverworldWatcher(Color color, ImageFloatBox box, size_t seconds_stationary) - : VisualInferenceCallback("StationaryOverworldWatcher") - , m_color(color) - , m_box(box) - , m_overworld_detector(color) - , m_map_hold_duration(std::chrono::milliseconds(seconds_stationary * 1000)) -{} - -void StationaryOverworldWatcher::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} - -bool StationaryOverworldWatcher::process_frame(const VideoSnapshot& frame){ - if (!m_overworld_detector.detect(frame)){ - m_snapshot_start.clear(); - return false; - } - - if (!m_snapshot_start){ - m_snapshot_start = frame; - return false; - } - - // Check if radar map stays still for `m_map_hold_duration` - - // Mismatching image sizes. - ImageViewRGB32 start = extract_box_reference(m_snapshot_start, m_box); - ImageViewRGB32 current = extract_box_reference(frame, m_box); - if (start.width() != current.width() || start.height() != current.height()){ - m_snapshot_start = frame; - return false; - } - - double rmsd = ImageMatch::pixel_RMSD(start, current); -// cout << "rmsd = " << rmsd << endl; - if (rmsd > 2.0){ // Image of radar map has changed too much. - m_snapshot_start = frame; - return false; - } - - // Make sure radar map held for long enough. - return frame.timestamp - m_snapshot_start.timestamp >= m_map_hold_duration; -} - - - -} -} -} +/* Stationary Overworld Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/WaterfillUtilities.h" +#include "PokemonSV_StationaryOverworldWatcher.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + + +StationaryOverworldWatcher::StationaryOverworldWatcher(Color color, ImageFloatBox box, size_t seconds_stationary) + : VisualInferenceCallback("StationaryOverworldWatcher") + , m_color(color) + , m_box(box) + , m_overworld_detector(color) + , m_map_hold_duration(std::chrono::milliseconds(seconds_stationary * 1000)) +{} + +void StationaryOverworldWatcher::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} + +bool StationaryOverworldWatcher::process_frame(const VideoSnapshot& frame){ + if (!m_overworld_detector.detect(frame)){ + m_snapshot_start.clear(); + return false; + } + + if (!m_snapshot_start){ + m_snapshot_start = frame; + return false; + } + + // Check if radar map stays still for `m_map_hold_duration` + + // Mismatching image sizes. + ImageViewRGB32 start = extract_box_reference(m_snapshot_start, m_box); + ImageViewRGB32 current = extract_box_reference(frame, m_box); + if (start.width() != current.width() || start.height() != current.height()){ + m_snapshot_start = frame; + return false; + } + + double rmsd = ImageMatch::pixel_RMSD(start, current); +// cout << "rmsd = " << rmsd << endl; + if (rmsd > 2.0){ // Image of radar map has changed too much. + m_snapshot_start = frame; + return false; + } + + // Make sure radar map held for long enough. + return frame.timestamp - m_snapshot_start.timestamp >= m_map_hold_duration; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.h b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.h index c6d8a98571..78654f1253 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.h @@ -1,45 +1,45 @@ -/* Stationary Overworld Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_StationaryOverworldWatcher_H -#define PokemonAutomation_PokemonSV_StationaryOverworldWatcher_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class StationaryOverworldWatcher : public VisualInferenceCallback{ -public: - StationaryOverworldWatcher(Color color = COLOR_RED, ImageFloatBox box = {0.865, 0.82, 0.08, 0.1}, size_t seconds_stationary = 5); - - virtual void make_overlays(VideoOverlaySet& items) const override; - // return true if the screen within `m_box` doesn't change for am amount of time as per `seconds_stationary` - // the overworld must be detected throughout this. - virtual bool process_frame(const VideoSnapshot& frame) override; - - -private: - const Color m_color; - const ImageFloatBox m_box; - OverworldDetector m_overworld_detector; - const std::chrono::milliseconds m_map_hold_duration; - VideoSnapshot m_snapshot_start; -}; - - -} -} -} -#endif +/* Stationary Overworld Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_StationaryOverworldWatcher_H +#define PokemonAutomation_PokemonSV_StationaryOverworldWatcher_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class StationaryOverworldWatcher : public VisualInferenceCallback{ +public: + StationaryOverworldWatcher(Color color = COLOR_RED, ImageFloatBox box = {0.865, 0.82, 0.08, 0.1}, size_t seconds_stationary = 5); + + virtual void make_overlays(VideoOverlaySet& items) const override; + // return true if the screen within `m_box` doesn't change for am amount of time as per `seconds_stationary` + // the overworld must be detected throughout this. + virtual bool process_frame(const VideoSnapshot& frame) override; + + +private: + const Color m_color; + const ImageFloatBox m_box; + OverworldDetector m_overworld_detector; + const std::chrono::milliseconds m_map_hold_duration; + VideoSnapshot m_snapshot_start; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.h index 1060f206bf..40dc881533 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.h @@ -133,7 +133,7 @@ class SandwichCondimentMatcher : public ImageMatch::CroppedImageDictionaryMatche class SandwichFillingOCR : public OCR::SmallDictionaryMatcher{ public: - static constexpr double MAX_LOG10P = -2.0; + static constexpr double MAX_LOG10P = -1.5; static constexpr double MAX_LOG10P_SPREAD = 0.5; public: @@ -152,7 +152,7 @@ class SandwichFillingOCR : public OCR::SmallDictionaryMatcher{ }; class SandwichCondimentOCR : public OCR::SmallDictionaryMatcher{ public: - static constexpr double MAX_LOG10P = -2.0; + static constexpr double MAX_LOG10P = -1.5; static constexpr double MAX_LOG10P_SPREAD = 0.5; public: diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MenuOptionReader.cpp b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MenuOptionReader.cpp index e33fcf1f71..1ff5983ee9 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MenuOptionReader.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MenuOptionReader.cpp @@ -1,45 +1,45 @@ -/* Menu Option Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSV_MenuOptionReader.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -MenuOptionReader& MenuOptionReader::instance(){ - static MenuOptionReader reader; - return reader; -} - -MenuOptionReader::MenuOptionReader() - : SmallDictionaryMatcher("PokemonSV/MenuOptionsOCR.json") -{} - -OCR::StringMatchResult MenuOptionReader::read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio, double max_text_ratio -) const{ - return match_substring_from_image_multifiltered( - &logger, language, image, text_color_ranges, - MAX_LOG10P, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio - ); -} - - - -} -} -} +/* Menu Option Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSV_MenuOptionReader.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +MenuOptionReader& MenuOptionReader::instance(){ + static MenuOptionReader reader; + return reader; +} + +MenuOptionReader::MenuOptionReader() + : SmallDictionaryMatcher("PokemonSV/MenuOptionsOCR.json") +{} + +OCR::StringMatchResult MenuOptionReader::read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio, double max_text_ratio +) const{ + return match_substring_from_image_multifiltered( + &logger, language, image, text_color_ranges, + MAX_LOG10P, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio + ); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MenuOptionReader.h b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MenuOptionReader.h index c51a1e07cb..e2307af9b9 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MenuOptionReader.h +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MenuOptionReader.h @@ -1,41 +1,40 @@ -/* Menu Option Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_MenuOptionReader_H -#define PokemonAutomation_PokemonSV_MenuOptionReader_H - -#include "CommonFramework/Language.h" -#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" - -namespace PokemonAutomation{ - class AsyncDispatcher; -namespace NintendoSwitch{ -namespace PokemonSV{ - -class MenuOptionReader : public OCR::SmallDictionaryMatcher{ - static constexpr double MAX_LOG10P = -1.30; - static constexpr double MAX_LOG10P_SPREAD = 0.50; - -public: - MenuOptionReader(); - - static MenuOptionReader& instance(); - - OCR::StringMatchResult read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 - ) const; -}; - - - -} -} -} -#endif +/* Menu Option Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_MenuOptionReader_H +#define PokemonAutomation_PokemonSV_MenuOptionReader_H + +#include "CommonFramework/Language.h" +#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class MenuOptionReader : public OCR::SmallDictionaryMatcher{ + static constexpr double MAX_LOG10P = -1.30; + static constexpr double MAX_LOG10P_SPREAD = 0.50; + +public: + MenuOptionReader(); + + static MenuOptionReader& instance(); + + OCR::StringMatchResult read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 + ) const; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokemonMovesReader.cpp b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokemonMovesReader.cpp index c75ddac894..971c0b4e2b 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokemonMovesReader.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokemonMovesReader.cpp @@ -1,90 +1,90 @@ -/* Pokemon Moves Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "PokemonSV_PokemonMovesReader.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -PokemonMovesOCR& PokemonMovesOCR::instance(){ - static PokemonMovesOCR reader; - return reader; -} - -PokemonMovesOCR::PokemonMovesOCR() - : SmallDictionaryMatcher("PokemonSV/PokemonMovesOCR.json") -{} - -OCR::StringMatchResult PokemonMovesOCR::read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio, double max_text_ratio -) const{ - return match_substring_from_image_multifiltered( - &logger, language, image, text_color_ranges, - MAX_LOG10P, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio - ); -} - -PokemonMovesReader::PokemonMovesReader(Language language) - : m_language(language) -{ - for (size_t c = 0; c < 4; c++){ - m_boxes_rearrange[c] = ImageFloatBox(0.345, 0.245 + c * 0.074, 0.250, 0.065); - } -} - -void PokemonMovesReader::make_overlays(VideoOverlaySet& items) const{ - for (size_t c = 0; c < 4; c++){ - items.add(COLOR_GREEN, m_boxes_rearrange[c]); - } -} - -std::string PokemonMovesReader::read_move(Logger& logger, const ImageViewRGB32& screen, int8_t index) const{ - ImageViewRGB32 cropped = extract_box_reference(screen, m_boxes_rearrange[index]); - const auto ocr_result = PokemonMovesOCR::instance().read_substring( - logger, m_language, - cropped, OCR::BLACK_OR_WHITE_TEXT_FILTERS() - ); - - std::multimap results; - if (!ocr_result.results.empty()){ - for (const auto& result : ocr_result.results){ - results.emplace(result.first, result.second); - } - } - - if (results.empty()){ - return ""; - } - - if (results.size() > 1){ - throw_and_log( - logger, ErrorReport::SEND_ERROR_REPORT, - "MenuOption::read_option(): Unable to read item. Ambiguous or multiple results." - ); - } - - return results.begin()->second.token; -} - - - -} -} -} +/* Pokemon Moves Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "PokemonSV_PokemonMovesReader.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +PokemonMovesOCR& PokemonMovesOCR::instance(){ + static PokemonMovesOCR reader; + return reader; +} + +PokemonMovesOCR::PokemonMovesOCR() + : SmallDictionaryMatcher("PokemonSV/PokemonMovesOCR.json") +{} + +OCR::StringMatchResult PokemonMovesOCR::read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio, double max_text_ratio +) const{ + return match_substring_from_image_multifiltered( + &logger, language, image, text_color_ranges, + MAX_LOG10P, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio + ); +} + +PokemonMovesReader::PokemonMovesReader(Language language) + : m_language(language) +{ + for (size_t c = 0; c < 4; c++){ + m_boxes_rearrange[c] = ImageFloatBox(0.345, 0.245 + c * 0.074, 0.250, 0.065); + } +} + +void PokemonMovesReader::make_overlays(VideoOverlaySet& items) const{ + for (size_t c = 0; c < 4; c++){ + items.add(COLOR_GREEN, m_boxes_rearrange[c]); + } +} + +std::string PokemonMovesReader::read_move(Logger& logger, const ImageViewRGB32& screen, int8_t index) const{ + ImageViewRGB32 cropped = extract_box_reference(screen, m_boxes_rearrange[index]); + const auto ocr_result = PokemonMovesOCR::instance().read_substring( + logger, m_language, + cropped, OCR::BLACK_OR_WHITE_TEXT_FILTERS() + ); + + std::multimap results; + if (!ocr_result.results.empty()){ + for (const auto& result : ocr_result.results){ + results.emplace(result.first, result.second); + } + } + + if (results.empty()){ + return ""; + } + + if (results.size() > 1){ + throw_and_log( + logger, ErrorReport::SEND_ERROR_REPORT, + "MenuOption::read_option(): Unable to read item. Ambiguous or multiple results." + ); + } + + return results.begin()->second.token; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokemonMovesReader.h b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokemonMovesReader.h index 35b89dece5..3df38bbf2d 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokemonMovesReader.h +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokemonMovesReader.h @@ -1,59 +1,58 @@ -/* Pokemon Moves Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_PokemonMovesReader_H -#define PokemonAutomation_PokemonSV_PokemonMovesReader_H - -#include -#include "CommonFramework/Language.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" - -namespace PokemonAutomation{ - class AsyncDispatcher; -namespace NintendoSwitch{ -namespace PokemonSV{ - -class PokemonMovesOCR : public OCR::SmallDictionaryMatcher{ - static constexpr double MAX_LOG10P = -1.30; - static constexpr double MAX_LOG10P_SPREAD = 0.50; - -public: - PokemonMovesOCR(); - - static PokemonMovesOCR& instance(); - - OCR::StringMatchResult read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 - ) const; - - -}; - -class PokemonMovesReader{ - -public: - PokemonMovesReader(Language language); - - void make_overlays(VideoOverlaySet& items) const; - - std::string read_move(Logger& logger, const ImageViewRGB32& screen, int8_t index) const; - -private: - Language m_language; - std::array m_boxes_rearrange; -}; - - - -} -} -} -#endif +/* Pokemon Moves Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_PokemonMovesReader_H +#define PokemonAutomation_PokemonSV_PokemonMovesReader_H + +#include +#include "CommonFramework/Language.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class PokemonMovesOCR : public OCR::SmallDictionaryMatcher{ + static constexpr double MAX_LOG10P = -1.30; + static constexpr double MAX_LOG10P_SPREAD = 0.50; + +public: + PokemonMovesOCR(); + + static PokemonMovesOCR& instance(); + + OCR::StringMatchResult read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 + ) const; + + +}; + +class PokemonMovesReader{ + +public: + PokemonMovesReader(Language language); + + void make_overlays(VideoOverlaySet& items) const; + + std::string read_move(Logger& logger, const ImageViewRGB32& screen, int8_t index) const; + +private: + Language m_language; + std::array m_boxes_rearrange; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_TutorialDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_TutorialDetector.cpp index 8143c9f844..dd56a61922 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_TutorialDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_TutorialDetector.cpp @@ -1,48 +1,48 @@ -/* Tutorial Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonSV_TutorialDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -TutorialDetector::TutorialDetector(Color color) - : m_color(color) - , m_bottom(0.235, 0.87, 0.10, 0.035) - , m_left(0.230, 0.18, 0.02, 0.72) -{} -void TutorialDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_bottom); - items.add(m_color, m_left); -} - -// detect solid beige color along the side and bottom of the tutorial -bool TutorialDetector::detect(const ImageViewRGB32& screen){ - ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); - ImageStats left = image_stats(extract_box_reference(screen, m_left)); - // cout << "bottom.average.sum(): " << bottom.average.sum() << endl; - // cout << "left.average.sum(): " << left.average.sum() << endl; - - // expected color is {255, 255, 235} - return is_solid(bottom, {0.342282, 0.342282, 0.315436}) - && bottom.average.sum() > 500 - && is_solid(left, {0.342282, 0.342282, 0.315436}) - && left.average.sum() > 500; -} - - - -} -} -} +/* Tutorial Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonSV_TutorialDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +TutorialDetector::TutorialDetector(Color color) + : m_color(color) + , m_bottom(0.235, 0.87, 0.10, 0.035) + , m_left(0.230, 0.18, 0.02, 0.72) +{} +void TutorialDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_bottom); + items.add(m_color, m_left); +} + +// detect solid beige color along the side and bottom of the tutorial +bool TutorialDetector::detect(const ImageViewRGB32& screen){ + ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); + ImageStats left = image_stats(extract_box_reference(screen, m_left)); + // cout << "bottom.average.sum(): " << bottom.average.sum() << endl; + // cout << "left.average.sum(): " << left.average.sum() << endl; + + // expected color is {255, 255, 235} + return is_solid(bottom, {0.342282, 0.342282, 0.315436}) + && bottom.average.sum() > 500 + && is_solid(left, {0.342282, 0.342282, 0.315436}) + && left.average.sum() > 500; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_TutorialDetector.h b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_TutorialDetector.h index d350173e58..3f36b37feb 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_TutorialDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_TutorialDetector.h @@ -1,49 +1,49 @@ -/* Tutorial Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_TutorialDetector_H -#define PokemonAutomation_PokemonSV_TutorialDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class TutorialDetector : public StaticScreenDetector{ -public: - TutorialDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - -protected: - Color m_color; - ImageFloatBox m_bottom; - ImageFloatBox m_left; -}; -class TutorialWatcher : public DetectorToFinder{ -public: - TutorialWatcher(Color color = COLOR_RED) - : DetectorToFinder("TutorialWatcher", std::chrono::milliseconds(250), color) - {} -}; - - - - - - -} -} -} -#endif +/* Tutorial Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_TutorialDetector_H +#define PokemonAutomation_PokemonSV_TutorialDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class TutorialDetector : public StaticScreenDetector{ +public: + TutorialDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + +protected: + Color m_color; + ImageFloatBox m_bottom; + ImageFloatBox m_left; +}; +class TutorialWatcher : public DetectorToFinder{ +public: + TutorialWatcher(Color color = COLOR_RED) + : DetectorToFinder("TutorialWatcher", std::chrono::milliseconds(250), color) + {} +}; + + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.cpp index 1e5b50844a..0521e8adcb 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.cpp @@ -268,9 +268,8 @@ std::string TeraLobbyNameMatchResult::to_str() const{ -TeraLobbyReader::TeraLobbyReader(Logger& logger, AsyncDispatcher& dispatcher, Color color) +TeraLobbyReader::TeraLobbyReader(Logger& logger, Color color) : m_logger(logger) - , m_dispatcher(dispatcher) , m_color(color) , m_bottom_right(0.73, 0.85, 0.12, 0.02) , m_label(TeraCardReader::CARD_LABEL_BOX()) @@ -317,7 +316,7 @@ bool TeraLobbyReader::detect(const ImageViewRGB32& screen){ return false; } - if (seconds_left(m_logger, m_dispatcher, screen) < 0){ + if (seconds_left(m_logger, screen) < 0){ return false; } @@ -359,13 +358,13 @@ uint8_t TeraLobbyReader::ready_joiners(const ImageViewRGB32& screen, uint8_t hos return total; } -int16_t TeraLobbyReader::seconds_left(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& screen) const{ +int16_t TeraLobbyReader::seconds_left(Logger& logger, const ImageViewRGB32& screen) const{ ImageViewRGB32 image = extract_box_reference(screen, m_timer); - return read_raid_timer(logger, dispatcher, image); + return read_raid_timer(logger, image); } -std::string TeraLobbyReader::raid_code(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& screen) const{ +std::string TeraLobbyReader::raid_code(Logger& logger, const ImageViewRGB32& screen) const{ ImageViewRGB32 image = extract_box_reference(screen, m_code); - return read_raid_code(logger, dispatcher, image); + return read_raid_code(logger, image); } ImageRGB32 filter_name_image(const ImageViewRGB32& image){ @@ -457,32 +456,6 @@ std::array, 4> TeraLobbyReader::read_names( -#if 0 -TeraLobbyReadyWaiter::TeraLobbyReadyWaiter( - Logger& logger, AsyncDispatcher& dispatcher, - Color color, uint8_t desired_players -) - : TeraLobbyReader(logger, dispatcher, color) - , VisualInferenceCallback("TeraLobbyReadyWaiter") - , m_desired_players(desired_players) - , m_last_known_total_players(-1) -{} - -void TeraLobbyReadyWaiter::make_overlays(VideoOverlaySet& items) const{ - TeraLobbyReader::make_overlays(items); -} -bool TeraLobbyReadyWaiter::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - if (!detect(frame)){ - return false; - } - uint8_t total_players = this->total_players(frame); - uint8_t ready_players = this->ready_players(frame); - m_last_known_total_players.store(total_players); - return ready_players + 1 >= m_desired_players; -} -#endif - - diff --git a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.h index 9a142d4374..84ccad6c9a 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.h @@ -10,14 +10,12 @@ #include "Common/Cpp/Color.h" #include "Common/Cpp/AbstractLogger.h" #include "CommonFramework/ImageTools/ImageBoxes.h" -//#include "CommonFramework/InferenceInfra/VisualInferenceCallback.h" #include "CommonTools/VisualDetector.h" #include "PokemonSV/Options/PokemonSV_PlayerList.h" #include "PokemonSV_TeraTypeReader.h" #include "PokemonSV_TeraSilhouetteReader.h" namespace PokemonAutomation{ - class AsyncDispatcher; struct ProgramInfo; namespace NintendoSwitch{ namespace PokemonSV{ @@ -86,7 +84,7 @@ struct TeraLobbyNameMatchResult{ class TeraLobbyReader : public StaticScreenDetector{ public: - TeraLobbyReader(Logger& logger, AsyncDispatcher& dispatcher, Color color = COLOR_RED); + TeraLobbyReader(Logger& logger, Color color = COLOR_RED); virtual void make_overlays(VideoOverlaySet& items) const override; @@ -97,8 +95,8 @@ class TeraLobbyReader : public StaticScreenDetector{ // uint8_t ready_players(const ImageViewRGB32& screen) const; uint8_t ready_joiners(const ImageViewRGB32& screen, uint8_t host_players); - int16_t seconds_left(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& screen) const; - std::string raid_code(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& screen) const; + int16_t seconds_left(Logger& logger, const ImageViewRGB32& screen) const; + std::string raid_code(Logger& logger, const ImageViewRGB32& screen) const; // OCR the player names in all the specified languages. // The returned strings are raw OCR output and are unprocessed. @@ -111,7 +109,6 @@ class TeraLobbyReader : public StaticScreenDetector{ private: Logger& m_logger; - AsyncDispatcher& m_dispatcher; Color m_color; ImageFloatBox m_bottom_right; ImageFloatBox m_label; @@ -129,37 +126,14 @@ class TeraLobbyReader : public StaticScreenDetector{ class TeraLobbyWatcher : public DetectorToFinder{ public: TeraLobbyWatcher( - Logger& logger, AsyncDispatcher& dispatcher, - Color color = COLOR_RED, std::chrono::milliseconds duration = std::chrono::milliseconds(250) + Logger& logger, + Color color = COLOR_RED, + std::chrono::milliseconds duration = std::chrono::milliseconds(250) ) - : DetectorToFinder("TeraLobbyFinder", duration, logger, dispatcher, color) + : DetectorToFinder("TeraLobbyFinder", duration, logger, color) {} }; -#if 0 -class TeraLobbyReadyWaiter : public TeraLobbyReader, public VisualInferenceCallback{ -public: - TeraLobbyReadyWaiter( - Logger& logger, AsyncDispatcher& dispatcher, - Color color, uint8_t desired_players - ); - - int8_t last_known_total_players() const{ - return m_last_known_total_players.load(std::memory_order_relaxed); - } - int8_t last_known_ready_players() const{ - return m_last_known_ready_players.load(std::memory_order_relaxed); - } - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - uint8_t m_desired_players; - std::atomic m_last_known_total_players; - std::atomic m_last_known_ready_players; -}; -#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCodeReader.cpp b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCodeReader.cpp index 55e9d7e483..518f283dbf 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCodeReader.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCodeReader.cpp @@ -6,11 +6,11 @@ #include #include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" #include "Kernels/Waterfill/Kernels_Waterfill_Session.h" #include "CommonFramework/Globals.h" #include "CommonFramework/ImageTypes/ImageRGB32.h" #include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/Tools/GlobalThreadPools.h" #include "CommonTools/Images/ImageManip.h" #include "CommonTools/Images/ImageFilter.h" #include "CommonTools/Images/BinaryImage_FilterRgb32.h" @@ -146,7 +146,6 @@ struct WaterfillOCRResult{ std::vector waterfill_OCR( - AsyncDispatcher& dispatcher, const ImageViewRGB32& image, uint32_t threshold ){ @@ -173,8 +172,7 @@ std::vector waterfill_OCR( ret.emplace_back(WaterfillOCRResult{std::move(item.second), ""}); } - dispatcher.run_in_parallel( - 0, ret.size(), + GlobalThreadPools::realtime_inference().run_in_parallel( [&](size_t index){ WaterfillObject& object = ret[index].object; ImageRGB32 cropped = extract_box_reference(filtered, object).copy(); @@ -182,7 +180,8 @@ std::vector waterfill_OCR( filter_by_mask(tmp, cropped, Color(0xffffffff), true); ImageRGB32 padded = pad_image(cropped, cropped.width(), 0xffffffff); ret[index].ocr = OCR::ocr_read(Language::English, padded); - } + }, + 0, ret.size() ); #ifdef PA_ENABLE_CODE_DEBUG @@ -201,8 +200,8 @@ std::vector waterfill_OCR( } -int16_t read_raid_timer(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& image){ - std::vector characters = waterfill_OCR(dispatcher, image, 0xff7f7f7f); +int16_t read_raid_timer(Logger& logger, const ImageViewRGB32& image){ + std::vector characters = waterfill_OCR(image, 0xff7f7f7f); // cout << "map.size() = " << map.size() << endl; // for (auto& item : map){ @@ -262,14 +261,14 @@ int16_t read_raid_timer(Logger& logger, AsyncDispatcher& dispatcher, const Image } -std::string read_raid_code(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& image){ +std::string read_raid_code(Logger& logger, const ImageViewRGB32& image){ std::vector filters{ 0xff5f5f5f, 0xff7f7f7f, }; for (uint32_t filter : filters){ - std::vector characters = waterfill_OCR(dispatcher, image, filter); + std::vector characters = waterfill_OCR(image, filter); static const std::map SUBSTITUTIONS{ {'I', '1'}, diff --git a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCodeReader.h b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCodeReader.h index d5bc03ad7b..e0441039f5 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCodeReader.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCodeReader.h @@ -11,7 +11,6 @@ namespace PokemonAutomation{ class Logger; - class AsyncDispatcher; namespace NintendoSwitch{ namespace PokemonSV{ @@ -20,10 +19,10 @@ void preload_code_templates(); // Returns # of seconds left. Returns -1 if unable to read. -int16_t read_raid_timer(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& image); +int16_t read_raid_timer(Logger& logger, const ImageViewRGB32& image); // Returns empty string if unable to read. -std::string read_raid_code(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& image); +std::string read_raid_code(Logger& logger, const ImageViewRGB32& image); diff --git a/SerialPrograms/Source/PokemonSV/PokemonSV_Panels.cpp b/SerialPrograms/Source/PokemonSV/PokemonSV_Panels.cpp index 8f79cb58b4..799eab550d 100644 --- a/SerialPrograms/Source/PokemonSV/PokemonSV_Panels.cpp +++ b/SerialPrograms/Source/PokemonSV/PokemonSV_Panels.cpp @@ -31,7 +31,6 @@ #include "Programs/Farming/PokemonSV_FlyingTrialFarmer.h" #include "Programs/Farming/PokemonSV_BBQSoloFarmer.h" #include "Programs/Farming/PokemonSV_MaterialFarmer.h" -#include "Programs/ItemPrinter/PokemonSV_AutoItemPrinter.h" #include "Programs/ItemPrinter/PokemonSV_ItemPrinterRNG.h" #include "Programs/Eggs/PokemonSV_EggFetcher.h" @@ -59,8 +58,10 @@ #include "Programs/Glitches/PokemonSV_RideCloner-1.0.1.h" #include "Programs/Glitches/PokemonSV_CloneItems-1.0.1.h" -#include "Programs/TestPrograms/PokemonSV_SoundListener.h" +// Deprecated +#include "Programs/ItemPrinter/PokemonSV_AutoItemPrinter.h" +#include "Programs/TestPrograms/PokemonSV_SoundListener.h" #include "Programs/FormHunting/PokemonSV_ThreeSegmentDudunsparceFinder.h" #ifdef PA_OFFICIAL @@ -88,7 +89,6 @@ std::vector PanelListFactory::make_panels() const{ ret.emplace_back(make_single_switch_program()); ret.emplace_back(make_single_switch_program()); ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); // ret.emplace_back("---- Trading ----"); ret.emplace_back(make_multi_switch_program()); @@ -147,6 +147,9 @@ std::vector PanelListFactory::make_panels() const{ ret.emplace_back("---- Public Betas ----"); ret.emplace_back(make_single_switch_program()); + ret.emplace_back("---- Deprecated Programs ----"); + ret.emplace_back(make_single_switch_program()); + if (PreloadSettings::instance().DEVELOPER_MODE || IS_BETA_VERSION){ ret.emplace_back("---- Untested/Beta/WIP ----"); } diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp index 78c28b93ba..1cddcfabb2 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp @@ -1,796 +1,809 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" -#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStory_Segment_00.h" -#include "PokemonSV_AutoStory_Segment_01.h" -#include "PokemonSV_AutoStory_Segment_02.h" -#include "PokemonSV_AutoStory_Segment_03.h" -#include "PokemonSV_AutoStory_Segment_04.h" -#include "PokemonSV_AutoStory_Segment_05.h" -#include "PokemonSV_AutoStory_Segment_06.h" -#include "PokemonSV_AutoStory_Segment_07.h" -#include "PokemonSV_AutoStory_Segment_08.h" -#include "PokemonSV_AutoStory_Segment_09.h" -#include "PokemonSV_AutoStory_Segment_10.h" -#include "PokemonSV_AutoStory_Segment_11.h" -#include "PokemonSV_AutoStory_Segment_12.h" -#include "PokemonSV_AutoStory_Segment_13.h" -#include "PokemonSV_AutoStory_Segment_14.h" -#include "PokemonSV_AutoStory_Segment_15.h" -#include "PokemonSV_AutoStory_Segment_16.h" -#include "PokemonSV_AutoStory_Segment_17.h" -#include "PokemonSV_AutoStory_Segment_18.h" -#include "PokemonSV_AutoStory_Segment_19.h" -#include "PokemonSV_AutoStory_Segment_20.h" -#include "PokemonSV_AutoStory_Segment_21.h" -#include "PokemonSV_AutoStory_Segment_22.h" -#include "PokemonSV_AutoStory_Segment_23.h" -#include "PokemonSV_AutoStory_Segment_24.h" -#include "PokemonSV_AutoStory.h" - -#include -using std::cout; -using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - -static constexpr size_t INDEX_OF_LAST_TUTORIAL_SEGMENT = 9; - - -std::vector> make_autoStory_segment_list(){ - std::vector> segment_list; - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - // segment_list.emplace_back(std::make_unique()); - // segment_list.emplace_back(std::make_unique()); - // segment_list.emplace_back(std::make_unique()); - - return segment_list; -}; - -const std::vector>& ALL_AUTO_STORY_SEGMENT_LIST(){ - static std::vector> segment_list = make_autoStory_segment_list(); - return segment_list; -} - - -StringSelectDatabase make_all_segments_database(){ - StringSelectDatabase ret; - int index_num = 0; - for (const auto& segment : ALL_AUTO_STORY_SEGMENT_LIST()){ - ret.add_entry(StringSelectEntry(std::to_string(index_num), segment->name())); - index_num++; - } - return ret; -} -const StringSelectDatabase& ALL_SEGMENTS_SELECT_DATABASE(){ - static StringSelectDatabase database = make_all_segments_database(); - return database; -} - -StringSelectDatabase make_tutorial_segments_database(){ - StringSelectDatabase ret; - const StringSelectDatabase& all_segments = ALL_SEGMENTS_SELECT_DATABASE(); - size_t start = 0; - size_t end = INDEX_OF_LAST_TUTORIAL_SEGMENT + 1; - for (size_t i = start; i < end; i++){ - const auto& segment = all_segments[i]; - ret.add_entry(segment); - } - return ret; -} - -const StringSelectDatabase& TUTORIAL_SEGMENTS_SELECT_DATABASE(){ - static StringSelectDatabase database = make_tutorial_segments_database(); - return database; -} - -StringSelectDatabase make_mainstory_segments_database(){ - StringSelectDatabase ret; - const StringSelectDatabase& all_segments = ALL_SEGMENTS_SELECT_DATABASE(); - size_t start = INDEX_OF_LAST_TUTORIAL_SEGMENT + 1; - size_t end = all_segments.case_list().size(); - for (size_t i = start; i < end; i++){ - const auto& segment = all_segments[i]; - ret.add_entry(segment); - } - return ret; -} - -const StringSelectDatabase& MAINSTORY_SEGMENTS_SELECT_DATABASE(){ - static StringSelectDatabase database = make_mainstory_segments_database(); - return database; -} - - -AutoStory_Descriptor::AutoStory_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:AutoStory", - STRING_POKEMON + " SV", "Auto Story", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/AutoStory.md", - "Progress through the mainstory of SV.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} - -std::unique_ptr AutoStory_Descriptor::make_stats() const{ - return std::unique_ptr(new AutoStoryStats()); -} - - - -AutoStory::~AutoStory(){ - STARTPOINT_TUTORIAL.remove_listener(*this); - ENDPOINT_TUTORIAL.remove_listener(*this); -} - -AutoStory::AutoStory() - : LANGUAGE( - "Game Language:", - PokemonSwSh::IV_READER().languages(), - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , STORY_SECTION( - "Story Section:", - { - {StorySection::TUTORIAL, "tutorial", "Tutorial"}, - {StorySection::MAIN_STORY, "main-story", "Main Story"}, - }, - LockMode::LOCK_WHILE_RUNNING, - StorySection::TUTORIAL - ) - , STARTPOINT_TUTORIAL( - "Start Point:
Program will start with this segment.", - TUTORIAL_SEGMENTS_SELECT_DATABASE(), - LockMode::UNLOCK_WHILE_RUNNING, - "0" - ) - , ENDPOINT_TUTORIAL( - "End Point:
Program will stop after completing this segment.", - TUTORIAL_SEGMENTS_SELECT_DATABASE(), - LockMode::UNLOCK_WHILE_RUNNING, - "9" - ) - , STARTPOINT_MAINSTORY( - "Start Point:
Program will start with this segment.", - MAINSTORY_SEGMENTS_SELECT_DATABASE(), - LockMode::UNLOCK_WHILE_RUNNING, - "10" - ) - , ENDPOINT_MAINSTORY( - "End Point:
Program will stop after completing this segment.", - MAINSTORY_SEGMENTS_SELECT_DATABASE(), - LockMode::UNLOCK_WHILE_RUNNING, - "10" - ) - , MAINSTORY_NOTE{ - "Ensure you have a level 100 Gardevoir with the moves in the following order: Moonblast, Dazzling Gleam, Psychic, Mystical Fire.
" - "Also, make sure you have two other strong pokemon (e.g. level 100 Talonflames)
" - "Refer to the documentation on github for more details." - } - , START_DESCRIPTION( - "" - ) - , END_DESCRIPTION( - "" - ) - , STARTERCHOICE( - "Starter " + STRING_POKEMON + ":", - { - {StarterChoice::SPRIGATITO, "sprigatito", "Sprigatito (Grass)"}, - {StarterChoice::FUECOCO, "fuecoco", "Fuecoco (Fire)"}, - {StarterChoice::QUAXLY, "quaxly", "Quaxly (Water)"}, - }, - LockMode::LOCK_WHILE_RUNNING, - StarterChoice::FUECOCO - ) - , GO_HOME_WHEN_DONE(true) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(30)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: (developer only)" - ) - , m_advanced_options_end( - "" - ) - , CHANGE_SETTINGS( - "Change settings at Program Start:
" - "This is to ensure the program has the correct settings, particularly with Autosave turned off.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , ENABLE_TEST_CHECKPOINTS( - "TEST: test_checkpoints():", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , START_CHECKPOINT( - "--Start checkpoint:
Start testing with this checkpoint number.", - LockMode::UNLOCK_WHILE_RUNNING, - 0 - ) - , END_CHECKPOINT( - "--End checkpoint:
Stop testing when done this checkpoint number.", - LockMode::UNLOCK_WHILE_RUNNING, - 11 - ) - , LOOP_CHECKPOINT( - "--Loop checkpoints:
Loop the checkpoints from \"Start loop\" to \"End loop\", inclusive. Loop these checkpoints this number of times.", - LockMode::UNLOCK_WHILE_RUNNING, - 1, 1 - ) - , START_LOOP( - "--Start loop:
Start looping with this checkpoint number.", - LockMode::UNLOCK_WHILE_RUNNING, - 0 - ) - , END_LOOP( - "--End loop:
Stop looping when done this checkpoint number.", - LockMode::UNLOCK_WHILE_RUNNING, - 11 - ) - , ENABLE_TEST_REALIGN( - "TEST: realign_player():", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , REALIGN_MODE( - "--REALIGN_MODE:", - { - {PlayerRealignMode::REALIGN_NEW_MARKER, "realign_new", "Realign New Marker"}, - {PlayerRealignMode::REALIGN_NO_MARKER, "realign_no", "Realign No Marker"}, - {PlayerRealignMode::REALIGN_OLD_MARKER, "realign_old", "Realign Old Marker"}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - PlayerRealignMode::REALIGN_NEW_MARKER - ) - , X_REALIGN( - "--X_REALIGN:
x = 0 : left, x = 128 : neutral, x = 255 : right.", - LockMode::UNLOCK_WHILE_RUNNING, - 128 - ) - , Y_REALIGN( - "--Y_REALIGN:
y = 0 : up, y = 128 : neutral, y = 255 : down.", - LockMode::UNLOCK_WHILE_RUNNING, - 128 - ) - , REALIGN_DURATION( - "--REALIGN_DURATION", - LockMode::UNLOCK_WHILE_RUNNING, - 0 - ) - , ENABLE_MISC_TEST( - "TEST: Miscellaneous test code:", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , FORWARD_TICKS( - "--FORWARD_TICKS:", - LockMode::UNLOCK_WHILE_RUNNING, - 0 - ) - , TEST_PBF_LEFT_JOYSTICK( - "TEST: pbf_move_left_joystick():", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , X_MOVE( - "--X_MOVE:
x = 0 : left, x = 128 : neutral, x = 255 : right.", - LockMode::UNLOCK_WHILE_RUNNING, - 128 - ) - , Y_MOVE( - "--Y_MOVE:
y = 0 : up, y = 128 : neutral, y = 255 : down.", - LockMode::UNLOCK_WHILE_RUNNING, - 128 - ) - , HOLD_TICKS( - "--HOLD_TICKS:", - LockMode::UNLOCK_WHILE_RUNNING, - 0 - ) - , RELEASE_TICKS( - "--RELEASE_TICKS:", - LockMode::UNLOCK_WHILE_RUNNING, - 0 - ) - , TEST_PBF_LEFT_JOYSTICK2( - "TEST2: pbf_move_left_joystick():", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , X_MOVE2( - "--X_MOVE:
x = 0 : left, x = 128 : neutral, x = 255 : right.", - LockMode::UNLOCK_WHILE_RUNNING, - 128 - ) - , Y_MOVE2( - "--Y_MOVE:
y = 0 : up, y = 128 : neutral, y = 255 : down.", - LockMode::UNLOCK_WHILE_RUNNING, - 128 - ) - , HOLD_TICKS2( - "--HOLD_TICKS:", - LockMode::UNLOCK_WHILE_RUNNING, - 0 - ) - , RELEASE_TICKS2( - "--RELEASE_TICKS:", - LockMode::UNLOCK_WHILE_RUNNING, - 0 - ) - , TEST_CURRENT_DIRECTION( - "TEST: get_current_direction():", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , TEST_CHANGE_DIRECTION( - "TEST: change_direction():", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , DIR_RADIANS( - "direction in radians", - LockMode::UNLOCK_WHILE_RUNNING, - 0 - ) -{ - - if (PreloadSettings::instance().DEVELOPER_MODE){ - PA_ADD_OPTION(m_advanced_options); - PA_ADD_OPTION(CHANGE_SETTINGS); - - PA_ADD_OPTION(TEST_CURRENT_DIRECTION); - PA_ADD_OPTION(TEST_CHANGE_DIRECTION); - PA_ADD_OPTION(DIR_RADIANS); - - PA_ADD_OPTION(TEST_PBF_LEFT_JOYSTICK); - PA_ADD_OPTION(X_MOVE); - PA_ADD_OPTION(Y_MOVE); - PA_ADD_OPTION(HOLD_TICKS); - PA_ADD_OPTION(RELEASE_TICKS); - - PA_ADD_OPTION(TEST_PBF_LEFT_JOYSTICK2); - PA_ADD_OPTION(X_MOVE2); - PA_ADD_OPTION(Y_MOVE2); - PA_ADD_OPTION(HOLD_TICKS2); - PA_ADD_OPTION(RELEASE_TICKS2); - - PA_ADD_OPTION(ENABLE_TEST_CHECKPOINTS); - PA_ADD_OPTION(START_CHECKPOINT); - PA_ADD_OPTION(END_CHECKPOINT); - PA_ADD_OPTION(LOOP_CHECKPOINT); - PA_ADD_OPTION(START_LOOP); - PA_ADD_OPTION(END_LOOP); - - // PA_ADD_OPTION(ENABLE_TEST_REALIGN); - // PA_ADD_OPTION(REALIGN_MODE); - // PA_ADD_OPTION(X_REALIGN); - // PA_ADD_OPTION(Y_REALIGN); - // PA_ADD_OPTION(REALIGN_DURATION); - - PA_ADD_OPTION(ENABLE_MISC_TEST); - // PA_ADD_OPTION(FORWARD_TICKS); - PA_ADD_OPTION(m_advanced_options_end); - } - - - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(STORY_SECTION); - PA_ADD_OPTION(STARTPOINT_TUTORIAL); - PA_ADD_OPTION(MAINSTORY_NOTE); - PA_ADD_OPTION(STARTPOINT_MAINSTORY); - PA_ADD_OPTION(START_DESCRIPTION); - PA_ADD_OPTION(ENDPOINT_TUTORIAL); - PA_ADD_OPTION(ENDPOINT_MAINSTORY); - PA_ADD_OPTION(END_DESCRIPTION); - PA_ADD_OPTION(STARTERCHOICE); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(NOTIFICATIONS); - - - AutoStory::on_config_value_changed(this); - - STORY_SECTION.add_listener(*this); - STARTPOINT_TUTORIAL.add_listener(*this); - ENDPOINT_TUTORIAL.add_listener(*this); - STARTPOINT_MAINSTORY.add_listener(*this); - ENDPOINT_MAINSTORY.add_listener(*this); - ENABLE_TEST_CHECKPOINTS.add_listener(*this); - ENABLE_TEST_REALIGN.add_listener(*this); - ENABLE_MISC_TEST.add_listener(*this); - TEST_PBF_LEFT_JOYSTICK.add_listener(*this); - TEST_PBF_LEFT_JOYSTICK2.add_listener(*this); - TEST_CURRENT_DIRECTION.add_listener(*this); - TEST_CHANGE_DIRECTION.add_listener(*this); -} - -void AutoStory::on_config_value_changed(void* object){ - ConfigOptionState state = (STARTPOINT_TUTORIAL.index() <= 1) - ? ConfigOptionState::ENABLED - : ConfigOptionState::HIDDEN; - STARTERCHOICE.set_visibility(state); - - if (STORY_SECTION == StorySection::TUTORIAL){ - STARTPOINT_TUTORIAL.set_visibility(ConfigOptionState::ENABLED); - ENDPOINT_TUTORIAL.set_visibility(ConfigOptionState::ENABLED); - - STARTPOINT_MAINSTORY.set_visibility(ConfigOptionState::HIDDEN); - ENDPOINT_MAINSTORY.set_visibility(ConfigOptionState::HIDDEN); - }else if (STORY_SECTION == StorySection::MAIN_STORY){ - STARTPOINT_TUTORIAL.set_visibility(ConfigOptionState::HIDDEN); - ENDPOINT_TUTORIAL.set_visibility(ConfigOptionState::HIDDEN); - - STARTPOINT_MAINSTORY.set_visibility(ConfigOptionState::ENABLED); - ENDPOINT_MAINSTORY.set_visibility(ConfigOptionState::ENABLED); - } - - MAINSTORY_NOTE.set_visibility(STORY_SECTION == StorySection::TUTORIAL ? ConfigOptionState::HIDDEN : ConfigOptionState::ENABLED); - START_DESCRIPTION.set_text(start_segment_description()); - END_DESCRIPTION.set_text(end_segment_description()); - - if (ENABLE_TEST_CHECKPOINTS){ - START_CHECKPOINT.set_visibility(ConfigOptionState::ENABLED); - END_CHECKPOINT.set_visibility(ConfigOptionState::ENABLED); - LOOP_CHECKPOINT.set_visibility(ConfigOptionState::ENABLED); - START_LOOP.set_visibility(ConfigOptionState::ENABLED); - END_LOOP.set_visibility(ConfigOptionState::ENABLED); - }else{ - START_CHECKPOINT.set_visibility(ConfigOptionState::DISABLED); - END_CHECKPOINT.set_visibility(ConfigOptionState::DISABLED); - LOOP_CHECKPOINT.set_visibility(ConfigOptionState::DISABLED); - START_LOOP.set_visibility(ConfigOptionState::DISABLED); - END_LOOP.set_visibility(ConfigOptionState::DISABLED); - } - - if (ENABLE_TEST_REALIGN){ - REALIGN_MODE.set_visibility(ConfigOptionState::ENABLED); - X_REALIGN.set_visibility(ConfigOptionState::ENABLED); - Y_REALIGN.set_visibility(ConfigOptionState::ENABLED); - REALIGN_DURATION.set_visibility(ConfigOptionState::ENABLED); - }else{ - REALIGN_MODE.set_visibility(ConfigOptionState::DISABLED); - X_REALIGN.set_visibility(ConfigOptionState::DISABLED); - Y_REALIGN.set_visibility(ConfigOptionState::DISABLED); - REALIGN_DURATION.set_visibility(ConfigOptionState::DISABLED); - } - - if (ENABLE_MISC_TEST){ - FORWARD_TICKS.set_visibility(ConfigOptionState::ENABLED); - }else{ - FORWARD_TICKS.set_visibility(ConfigOptionState::DISABLED); - } - - if (TEST_PBF_LEFT_JOYSTICK){ - X_MOVE.set_visibility(ConfigOptionState::ENABLED); - Y_MOVE.set_visibility(ConfigOptionState::ENABLED); - HOLD_TICKS.set_visibility(ConfigOptionState::ENABLED); - RELEASE_TICKS.set_visibility(ConfigOptionState::ENABLED); - }else{ - X_MOVE.set_visibility(ConfigOptionState::DISABLED); - Y_MOVE.set_visibility(ConfigOptionState::DISABLED); - HOLD_TICKS.set_visibility(ConfigOptionState::DISABLED); - RELEASE_TICKS.set_visibility(ConfigOptionState::DISABLED); - } - - if (TEST_PBF_LEFT_JOYSTICK2){ - X_MOVE2.set_visibility(ConfigOptionState::ENABLED); - Y_MOVE2.set_visibility(ConfigOptionState::ENABLED); - HOLD_TICKS2.set_visibility(ConfigOptionState::ENABLED); - RELEASE_TICKS2.set_visibility(ConfigOptionState::ENABLED); - }else{ - X_MOVE2.set_visibility(ConfigOptionState::DISABLED); - Y_MOVE2.set_visibility(ConfigOptionState::DISABLED); - HOLD_TICKS2.set_visibility(ConfigOptionState::DISABLED); - RELEASE_TICKS2.set_visibility(ConfigOptionState::DISABLED); - } - - - if (TEST_CHANGE_DIRECTION){ - DIR_RADIANS.set_visibility(ConfigOptionState::ENABLED); - }else{ - DIR_RADIANS.set_visibility(ConfigOptionState::DISABLED); - } - - -} - - - - - - -void AutoStory::test_checkpoints( - SingleSwitchProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context, - int start, int end, - int loop, int start_loop, int end_loop -){ - EventNotificationOption& notif_status_update = NOTIFICATION_STATUS_UPDATE; - Language language = LANGUAGE; - StarterChoice starter_choice = STARTERCHOICE; - std::vector> checkpoint_list; - checkpoint_list.push_back([&](){checkpoint_00(env, context);}); - checkpoint_list.push_back([&](){checkpoint_01(env, context, notif_status_update, language);}); - checkpoint_list.push_back([&](){checkpoint_02(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_03(env, context, notif_status_update, language, starter_choice);}); - checkpoint_list.push_back([&](){checkpoint_04(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_05(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_06(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_07(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_08(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_09(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_10(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_11(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_12(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_13(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_14(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_15(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_16(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_17(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_18(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_19(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_20(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_21(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_22(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_23(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_24(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_25(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_26(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_27(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_28(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_29(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_30(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_31(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_32(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_33(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_34(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_35(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_36(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_37(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_38(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_39(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_40(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_41(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_42(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_43(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_44(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_45(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_46(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_47(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_48(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_49(env, context, notif_status_update);}); - - for (int checkpoint = start; checkpoint <= end; checkpoint++){ - if (checkpoint == 0){ - stream.log("checkpoint_0"); - checkpoint_list[checkpoint](); - continue; - } - bool has_minimap = true; - if (checkpoint < 3){ - has_minimap = false; - } - - const size_t DIGITS = 3; - std::string number = std::to_string(checkpoint); - if (number.size() < DIGITS){ - number = std::string(DIGITS - number.size(), '0') + number; - } - if (checkpoint >= start_loop && checkpoint <= end_loop){ - for (int i = 0; i < loop; i++){ - if (i > 0){ - try { - reset_game(env.program_info(), env.console, context); - enter_menu_from_overworld(env.program_info(), env.console, context, -1, MenuSide::NONE, has_minimap); - // we wait 5 seconds then save, so that the initial conditions are slightly different on each reset. - env.log("Wait 5 seconds."); - context.wait_for(Milliseconds(5 * 1000)); - }catch(...){ - // try one more time - reset_game(env.program_info(), env.console, context); - enter_menu_from_overworld(env.program_info(), env.console, context, -1, MenuSide::NONE, has_minimap); - // we wait 5 seconds then save, so that the initial conditions are slightly different on each reset. - env.log("Wait 5 seconds."); - context.wait_for(Milliseconds(5 * 1000)); - - } - } - stream.log("checkpoint_" + number + ": loop " + std::to_string(i)); - checkpoint_list[checkpoint](); - } - }else{ - stream.log("checkpoint_" + number + "."); - checkpoint_list[checkpoint](); - } - - } - -} - -std::string AutoStory::start_segment_description(){ - size_t segment_index = 0; - if (STORY_SECTION == StorySection::TUTORIAL){ - segment_index = STARTPOINT_TUTORIAL.index(); - }else if (STORY_SECTION == StorySection::MAIN_STORY){ - segment_index = STARTPOINT_MAINSTORY.index() + (INDEX_OF_LAST_TUTORIAL_SEGMENT + 1); - } - return ALL_AUTO_STORY_SEGMENT_LIST()[segment_index]->start_text(); -} - -std::string AutoStory::end_segment_description(){ - size_t segment_index = 0; - if (STORY_SECTION == StorySection::TUTORIAL){ - segment_index = ENDPOINT_TUTORIAL.index(); - }else if (STORY_SECTION == StorySection::MAIN_STORY){ - segment_index = ENDPOINT_MAINSTORY.index() + (INDEX_OF_LAST_TUTORIAL_SEGMENT + 1); - } - return ALL_AUTO_STORY_SEGMENT_LIST()[segment_index]->end_text(); -} - - -void AutoStory::run_autostory(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - AutoStoryOptions options{ - LANGUAGE, - STARTERCHOICE, - NOTIFICATION_STATUS_UPDATE - }; - - size_t start = STARTPOINT_TUTORIAL.index(); - size_t end = ENDPOINT_TUTORIAL.index(); - - if (STORY_SECTION == StorySection::TUTORIAL){ - start = STARTPOINT_TUTORIAL.index(); - end = ENDPOINT_TUTORIAL.index(); - }else if (STORY_SECTION == StorySection::MAIN_STORY){ - start = (INDEX_OF_LAST_TUTORIAL_SEGMENT + 1) + STARTPOINT_MAINSTORY.index(); - end = (INDEX_OF_LAST_TUTORIAL_SEGMENT + 1) + ENDPOINT_MAINSTORY.index(); - } - - for (size_t segment_index = start; segment_index <= end; segment_index++){ - ALL_AUTO_STORY_SEGMENT_LIST()[segment_index]->run_segment(env, context, options); - } -} - -void AutoStory::test_code(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (TEST_CURRENT_DIRECTION){ - DirectionDetector direction; - // direction.change_direction(env.program_info(), env.console, context, DIR_RADIANS); - VideoSnapshot snapshot = env.console.video().snapshot(); - env.console.log("current direction: " + std::to_string(direction.get_current_direction(env.console, snapshot))); - return; - } - - if (TEST_CHANGE_DIRECTION){ - DirectionDetector direction; - direction.change_direction(env.program_info(), env.console, context, DIR_RADIANS); - // VideoSnapshot snapshot = env.console.video().snapshot(); - // env.console.log("current direction: " + std::to_string(direction.get_current_direction(env.console, snapshot))); - return; - } - - if (TEST_PBF_LEFT_JOYSTICK){ - pbf_move_left_joystick(context, X_MOVE, Y_MOVE, HOLD_TICKS, RELEASE_TICKS); - return; - } - - if (TEST_PBF_LEFT_JOYSTICK2){ - pbf_move_left_joystick(context, X_MOVE2, Y_MOVE2, HOLD_TICKS2, RELEASE_TICKS2); - return; - } - - if (ENABLE_TEST_CHECKPOINTS){ - // test individual checkpoints - test_checkpoints(env, env.console, context, START_CHECKPOINT, END_CHECKPOINT, LOOP_CHECKPOINT, START_LOOP, END_LOOP); - return; - } - - - if (ENABLE_TEST_REALIGN){ - // clear realign marker - // realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 128, 128, 0); - realign_player(env.program_info(), env.console, context, REALIGN_MODE, X_REALIGN, Y_REALIGN, REALIGN_DURATION); - return; - } - - if (ENABLE_MISC_TEST){ - // walk_forward_while_clear_front_path(env.program_info(), env.console, context, FORWARD_TICKS); - - // overworld_navigation(env.program_info(), env.console, context, - // NavigationStopCondition::STOP_MARKER, NavigationMovementMode::CLEAR_WITH_LETS_GO, - // 128, 0, 60, 10, false); - - DirectionDetector direction; - - return; - } - - // context.wait_for(Milliseconds(1000000)); - - -} - -void AutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - // AutoStoryStats& stats = env.current_stats(); - - - // test code - if (ENABLE_TEST_CHECKPOINTS || ENABLE_TEST_REALIGN || ENABLE_MISC_TEST || TEST_PBF_LEFT_JOYSTICK || TEST_PBF_LEFT_JOYSTICK2 || TEST_CHANGE_DIRECTION || TEST_CURRENT_DIRECTION){ - test_code(env, context); - return; - } - - // Connect controller - pbf_press_button(context, BUTTON_L, 20, 20); - - // Set settings. to ensure autosave is off. - if (CHANGE_SETTINGS){ - change_settings_prior_to_autostory(env, context, STARTPOINT_TUTORIAL.index(), LANGUAGE); - } - - run_autostory(env, context); - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" +#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStory_Segment_00.h" +#include "PokemonSV_AutoStory_Segment_01.h" +#include "PokemonSV_AutoStory_Segment_02.h" +#include "PokemonSV_AutoStory_Segment_03.h" +#include "PokemonSV_AutoStory_Segment_04.h" +#include "PokemonSV_AutoStory_Segment_05.h" +#include "PokemonSV_AutoStory_Segment_06.h" +#include "PokemonSV_AutoStory_Segment_07.h" +#include "PokemonSV_AutoStory_Segment_08.h" +#include "PokemonSV_AutoStory_Segment_09.h" +#include "PokemonSV_AutoStory_Segment_10.h" +#include "PokemonSV_AutoStory_Segment_11.h" +#include "PokemonSV_AutoStory_Segment_12.h" +#include "PokemonSV_AutoStory_Segment_13.h" +#include "PokemonSV_AutoStory_Segment_14.h" +#include "PokemonSV_AutoStory_Segment_15.h" +#include "PokemonSV_AutoStory_Segment_16.h" +#include "PokemonSV_AutoStory_Segment_17.h" +#include "PokemonSV_AutoStory_Segment_18.h" +#include "PokemonSV_AutoStory_Segment_19.h" +#include "PokemonSV_AutoStory_Segment_20.h" +#include "PokemonSV_AutoStory_Segment_21.h" +#include "PokemonSV_AutoStory_Segment_22.h" +#include "PokemonSV_AutoStory_Segment_23.h" +#include "PokemonSV_AutoStory_Segment_24.h" +#include "PokemonSV_AutoStory.h" + +#include +using std::cout; +using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + +static constexpr size_t INDEX_OF_LAST_TUTORIAL_SEGMENT = 9; + + +std::vector> make_autoStory_segment_list(){ + std::vector> segment_list; + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + // segment_list.emplace_back(std::make_unique()); + // segment_list.emplace_back(std::make_unique()); + // segment_list.emplace_back(std::make_unique()); + + return segment_list; +}; + +const std::vector>& ALL_AUTO_STORY_SEGMENT_LIST(){ + static std::vector> segment_list = make_autoStory_segment_list(); + return segment_list; +} + + +StringSelectDatabase make_all_segments_database(){ + StringSelectDatabase ret; + int index_num = 0; + for (const auto& segment : ALL_AUTO_STORY_SEGMENT_LIST()){ + ret.add_entry(StringSelectEntry(std::to_string(index_num), segment->name())); + index_num++; + } + return ret; +} +const StringSelectDatabase& ALL_SEGMENTS_SELECT_DATABASE(){ + static StringSelectDatabase database = make_all_segments_database(); + return database; +} + +StringSelectDatabase make_tutorial_segments_database(){ + StringSelectDatabase ret; + const StringSelectDatabase& all_segments = ALL_SEGMENTS_SELECT_DATABASE(); + size_t start = 0; + size_t end = INDEX_OF_LAST_TUTORIAL_SEGMENT + 1; + for (size_t i = start; i < end; i++){ + const auto& segment = all_segments[i]; + ret.add_entry(segment); + } + return ret; +} + +const StringSelectDatabase& TUTORIAL_SEGMENTS_SELECT_DATABASE(){ + static StringSelectDatabase database = make_tutorial_segments_database(); + return database; +} + +StringSelectDatabase make_mainstory_segments_database(){ + StringSelectDatabase ret; + const StringSelectDatabase& all_segments = ALL_SEGMENTS_SELECT_DATABASE(); + size_t start = INDEX_OF_LAST_TUTORIAL_SEGMENT + 1; + size_t end = all_segments.case_list().size(); + for (size_t i = start; i < end; i++){ + const auto& segment = all_segments[i]; + ret.add_entry(segment); + } + return ret; +} + +const StringSelectDatabase& MAINSTORY_SEGMENTS_SELECT_DATABASE(){ + static StringSelectDatabase database = make_mainstory_segments_database(); + return database; +} + + +AutoStory_Descriptor::AutoStory_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:AutoStory", + STRING_POKEMON + " SV", "Auto Story", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/AutoStory.md", + "Progress through the mainstory of SV.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} + +std::unique_ptr AutoStory_Descriptor::make_stats() const{ + return std::unique_ptr(new AutoStoryStats()); +} + + + +AutoStory::~AutoStory(){ + STARTPOINT_TUTORIAL.remove_listener(*this); + ENDPOINT_TUTORIAL.remove_listener(*this); +} + +AutoStory::AutoStory() + : LANGUAGE( + "Game Language:", + PokemonSwSh::IV_READER().languages(), + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , STORY_SECTION( + "Story Section:", + { + {StorySection::TUTORIAL, "tutorial", "Tutorial"}, + {StorySection::MAIN_STORY, "main-story", "Main Story"}, + }, + LockMode::LOCK_WHILE_RUNNING, + StorySection::TUTORIAL + ) + , STARTPOINT_TUTORIAL( + "Start Point:
Program will start with this segment.", + TUTORIAL_SEGMENTS_SELECT_DATABASE(), + LockMode::LOCK_WHILE_RUNNING, + "0" + ) + , ENDPOINT_TUTORIAL( + "End Point:
Program will stop after completing this segment.", + TUTORIAL_SEGMENTS_SELECT_DATABASE(), + LockMode::UNLOCK_WHILE_RUNNING, + "9" + ) + , STARTPOINT_MAINSTORY( + "Start Point:
Program will start with this segment.", + MAINSTORY_SEGMENTS_SELECT_DATABASE(), + LockMode::UNLOCK_WHILE_RUNNING, + "10" + ) + , ENDPOINT_MAINSTORY( + "End Point:
Program will stop after completing this segment.", + MAINSTORY_SEGMENTS_SELECT_DATABASE(), + LockMode::UNLOCK_WHILE_RUNNING, + "10" + ) + , MAINSTORY_NOTE{ + "Ensure you have a level 100 Gardevoir with the moves in the following order: Moonblast, Dazzling Gleam, Psychic, Mystical Fire.
" + "Also, make sure you have two other strong pokemon (e.g. level 100 Talonflames)
" + "Refer to the documentation on github for more details." + } + , START_DESCRIPTION( + "" + ) + , END_DESCRIPTION( + "" + ) + , STARTERCHOICE( + "Starter " + STRING_POKEMON + ":", + { + {StarterChoice::SPRIGATITO, "sprigatito", "Sprigatito (Grass)"}, + {StarterChoice::FUECOCO, "fuecoco", "Fuecoco (Fire)"}, + {StarterChoice::QUAXLY, "quaxly", "Quaxly (Water)"}, + }, + LockMode::LOCK_WHILE_RUNNING, + StarterChoice::FUECOCO + ) + , GO_HOME_WHEN_DONE(true) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(30)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: (developer only)" + ) + , m_advanced_options_end( + "" + ) + , CHANGE_SETTINGS( + "Change settings at Program Start:
" + "This is to ensure the program has the correct settings, particularly with Autosave turned off.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , ENABLE_TEST_CHECKPOINTS( + "TEST: test_checkpoints():", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , START_CHECKPOINT( + "--Start checkpoint:
Start testing with this checkpoint number.", + LockMode::UNLOCK_WHILE_RUNNING, + 0 + ) + , END_CHECKPOINT( + "--End checkpoint:
Stop testing when done this checkpoint number.", + LockMode::UNLOCK_WHILE_RUNNING, + 11 + ) + , LOOP_CHECKPOINT( + "--Loop checkpoints:
Loop the checkpoints from \"Start loop\" to \"End loop\", inclusive. Loop these checkpoints this number of times.", + LockMode::UNLOCK_WHILE_RUNNING, + 1, 1 + ) + , START_LOOP( + "--Start loop:
Start looping with this checkpoint number.", + LockMode::UNLOCK_WHILE_RUNNING, + 0 + ) + , END_LOOP( + "--End loop:
Stop looping when done this checkpoint number.", + LockMode::UNLOCK_WHILE_RUNNING, + 11 + ) + , ENABLE_TEST_REALIGN( + "TEST: realign_player():", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , REALIGN_MODE( + "--REALIGN_MODE:", + { + {PlayerRealignMode::REALIGN_NEW_MARKER, "realign_new", "Realign New Marker"}, + {PlayerRealignMode::REALIGN_NO_MARKER, "realign_no", "Realign No Marker"}, + {PlayerRealignMode::REALIGN_OLD_MARKER, "realign_old", "Realign Old Marker"}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + PlayerRealignMode::REALIGN_NEW_MARKER + ) + , X_REALIGN( + "--X_REALIGN:
x = 0 : left, x = 128 : neutral, x = 255 : right.", + LockMode::UNLOCK_WHILE_RUNNING, + 128 + ) + , Y_REALIGN( + "--Y_REALIGN:
y = 0 : up, y = 128 : neutral, y = 255 : down.", + LockMode::UNLOCK_WHILE_RUNNING, + 128 + ) + , REALIGN_DURATION( + "--REALIGN_DURATION", + LockMode::UNLOCK_WHILE_RUNNING, + 0 + ) + , ENABLE_MISC_TEST( + "TEST: Miscellaneous test code:", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , FORWARD_TICKS( + "--FORWARD_TICKS:", + LockMode::UNLOCK_WHILE_RUNNING, + 0 + ) + , TEST_PBF_LEFT_JOYSTICK( + "TEST: pbf_move_left_joystick():", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , X_MOVE( + "--X_MOVE:
x = 0 : left, x = 128 : neutral, x = 255 : right.", + LockMode::UNLOCK_WHILE_RUNNING, + 128 + ) + , Y_MOVE( + "--Y_MOVE:
y = 0 : up, y = 128 : neutral, y = 255 : down.", + LockMode::UNLOCK_WHILE_RUNNING, + 128 + ) + , HOLD_TICKS( + "--HOLD_TICKS:", + LockMode::UNLOCK_WHILE_RUNNING, + 0 + ) + , RELEASE_TICKS( + "--RELEASE_TICKS:", + LockMode::UNLOCK_WHILE_RUNNING, + 0 + ) + , TEST_PBF_LEFT_JOYSTICK2( + "TEST2: pbf_move_left_joystick():", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , X_MOVE2( + "--X_MOVE:
x = 0 : left, x = 128 : neutral, x = 255 : right.", + LockMode::UNLOCK_WHILE_RUNNING, + 128 + ) + , Y_MOVE2( + "--Y_MOVE:
y = 0 : up, y = 128 : neutral, y = 255 : down.", + LockMode::UNLOCK_WHILE_RUNNING, + 128 + ) + , HOLD_TICKS2( + "--HOLD_TICKS:", + LockMode::UNLOCK_WHILE_RUNNING, + 0 + ) + , RELEASE_TICKS2( + "--RELEASE_TICKS:", + LockMode::UNLOCK_WHILE_RUNNING, + 0 + ) + , TEST_CURRENT_DIRECTION( + "TEST: get_current_direction():", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , TEST_CHANGE_DIRECTION( + "TEST: change_direction():", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , DIR_RADIANS( + "direction in radians", + LockMode::UNLOCK_WHILE_RUNNING, + 0 + ) +{ + + if (PreloadSettings::instance().DEVELOPER_MODE){ + PA_ADD_OPTION(m_advanced_options); + PA_ADD_OPTION(CHANGE_SETTINGS); + + PA_ADD_OPTION(TEST_CURRENT_DIRECTION); + PA_ADD_OPTION(TEST_CHANGE_DIRECTION); + PA_ADD_OPTION(DIR_RADIANS); + + PA_ADD_OPTION(TEST_PBF_LEFT_JOYSTICK); + PA_ADD_OPTION(X_MOVE); + PA_ADD_OPTION(Y_MOVE); + PA_ADD_OPTION(HOLD_TICKS); + PA_ADD_OPTION(RELEASE_TICKS); + + PA_ADD_OPTION(TEST_PBF_LEFT_JOYSTICK2); + PA_ADD_OPTION(X_MOVE2); + PA_ADD_OPTION(Y_MOVE2); + PA_ADD_OPTION(HOLD_TICKS2); + PA_ADD_OPTION(RELEASE_TICKS2); + + PA_ADD_OPTION(ENABLE_TEST_CHECKPOINTS); + PA_ADD_OPTION(START_CHECKPOINT); + PA_ADD_OPTION(END_CHECKPOINT); + PA_ADD_OPTION(LOOP_CHECKPOINT); + PA_ADD_OPTION(START_LOOP); + PA_ADD_OPTION(END_LOOP); + + // PA_ADD_OPTION(ENABLE_TEST_REALIGN); + // PA_ADD_OPTION(REALIGN_MODE); + // PA_ADD_OPTION(X_REALIGN); + // PA_ADD_OPTION(Y_REALIGN); + // PA_ADD_OPTION(REALIGN_DURATION); + + PA_ADD_OPTION(ENABLE_MISC_TEST); + // PA_ADD_OPTION(FORWARD_TICKS); + PA_ADD_OPTION(m_advanced_options_end); + } + + + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(STORY_SECTION); + PA_ADD_OPTION(STARTPOINT_TUTORIAL); + PA_ADD_OPTION(MAINSTORY_NOTE); + PA_ADD_OPTION(STARTPOINT_MAINSTORY); + PA_ADD_OPTION(START_DESCRIPTION); + PA_ADD_OPTION(ENDPOINT_TUTORIAL); + PA_ADD_OPTION(ENDPOINT_MAINSTORY); + PA_ADD_OPTION(END_DESCRIPTION); + PA_ADD_OPTION(STARTERCHOICE); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); + + + AutoStory::on_config_value_changed(this); + + STORY_SECTION.add_listener(*this); + STARTPOINT_TUTORIAL.add_listener(*this); + ENDPOINT_TUTORIAL.add_listener(*this); + STARTPOINT_MAINSTORY.add_listener(*this); + ENDPOINT_MAINSTORY.add_listener(*this); + ENABLE_TEST_CHECKPOINTS.add_listener(*this); + ENABLE_TEST_REALIGN.add_listener(*this); + ENABLE_MISC_TEST.add_listener(*this); + TEST_PBF_LEFT_JOYSTICK.add_listener(*this); + TEST_PBF_LEFT_JOYSTICK2.add_listener(*this); + TEST_CURRENT_DIRECTION.add_listener(*this); + TEST_CHANGE_DIRECTION.add_listener(*this); +} + +void AutoStory::on_config_value_changed(void* object){ + ConfigOptionState state = (STARTPOINT_TUTORIAL.index() <= 1) + ? ConfigOptionState::ENABLED + : ConfigOptionState::HIDDEN; + STARTERCHOICE.set_visibility(state); + + if (STORY_SECTION == StorySection::TUTORIAL){ + STARTPOINT_TUTORIAL.set_visibility(ConfigOptionState::ENABLED); + ENDPOINT_TUTORIAL.set_visibility(ConfigOptionState::ENABLED); + + STARTPOINT_MAINSTORY.set_visibility(ConfigOptionState::HIDDEN); + ENDPOINT_MAINSTORY.set_visibility(ConfigOptionState::HIDDEN); + }else if (STORY_SECTION == StorySection::MAIN_STORY){ + STARTPOINT_TUTORIAL.set_visibility(ConfigOptionState::HIDDEN); + ENDPOINT_TUTORIAL.set_visibility(ConfigOptionState::HIDDEN); + + STARTPOINT_MAINSTORY.set_visibility(ConfigOptionState::ENABLED); + ENDPOINT_MAINSTORY.set_visibility(ConfigOptionState::ENABLED); + } + + MAINSTORY_NOTE.set_visibility(STORY_SECTION == StorySection::TUTORIAL ? ConfigOptionState::HIDDEN : ConfigOptionState::ENABLED); + START_DESCRIPTION.set_text(start_segment_description()); + END_DESCRIPTION.set_text(end_segment_description()); + + if (ENABLE_TEST_CHECKPOINTS){ + START_CHECKPOINT.set_visibility(ConfigOptionState::ENABLED); + END_CHECKPOINT.set_visibility(ConfigOptionState::ENABLED); + LOOP_CHECKPOINT.set_visibility(ConfigOptionState::ENABLED); + START_LOOP.set_visibility(ConfigOptionState::ENABLED); + END_LOOP.set_visibility(ConfigOptionState::ENABLED); + }else{ + START_CHECKPOINT.set_visibility(ConfigOptionState::DISABLED); + END_CHECKPOINT.set_visibility(ConfigOptionState::DISABLED); + LOOP_CHECKPOINT.set_visibility(ConfigOptionState::DISABLED); + START_LOOP.set_visibility(ConfigOptionState::DISABLED); + END_LOOP.set_visibility(ConfigOptionState::DISABLED); + } + + if (ENABLE_TEST_REALIGN){ + REALIGN_MODE.set_visibility(ConfigOptionState::ENABLED); + X_REALIGN.set_visibility(ConfigOptionState::ENABLED); + Y_REALIGN.set_visibility(ConfigOptionState::ENABLED); + REALIGN_DURATION.set_visibility(ConfigOptionState::ENABLED); + }else{ + REALIGN_MODE.set_visibility(ConfigOptionState::DISABLED); + X_REALIGN.set_visibility(ConfigOptionState::DISABLED); + Y_REALIGN.set_visibility(ConfigOptionState::DISABLED); + REALIGN_DURATION.set_visibility(ConfigOptionState::DISABLED); + } + + if (ENABLE_MISC_TEST){ + FORWARD_TICKS.set_visibility(ConfigOptionState::ENABLED); + }else{ + FORWARD_TICKS.set_visibility(ConfigOptionState::DISABLED); + } + + if (TEST_PBF_LEFT_JOYSTICK){ + X_MOVE.set_visibility(ConfigOptionState::ENABLED); + Y_MOVE.set_visibility(ConfigOptionState::ENABLED); + HOLD_TICKS.set_visibility(ConfigOptionState::ENABLED); + RELEASE_TICKS.set_visibility(ConfigOptionState::ENABLED); + }else{ + X_MOVE.set_visibility(ConfigOptionState::DISABLED); + Y_MOVE.set_visibility(ConfigOptionState::DISABLED); + HOLD_TICKS.set_visibility(ConfigOptionState::DISABLED); + RELEASE_TICKS.set_visibility(ConfigOptionState::DISABLED); + } + + if (TEST_PBF_LEFT_JOYSTICK2){ + X_MOVE2.set_visibility(ConfigOptionState::ENABLED); + Y_MOVE2.set_visibility(ConfigOptionState::ENABLED); + HOLD_TICKS2.set_visibility(ConfigOptionState::ENABLED); + RELEASE_TICKS2.set_visibility(ConfigOptionState::ENABLED); + }else{ + X_MOVE2.set_visibility(ConfigOptionState::DISABLED); + Y_MOVE2.set_visibility(ConfigOptionState::DISABLED); + HOLD_TICKS2.set_visibility(ConfigOptionState::DISABLED); + RELEASE_TICKS2.set_visibility(ConfigOptionState::DISABLED); + } + + + if (TEST_CHANGE_DIRECTION){ + DIR_RADIANS.set_visibility(ConfigOptionState::ENABLED); + }else{ + DIR_RADIANS.set_visibility(ConfigOptionState::DISABLED); + } + + +} + + + + + + +void AutoStory::test_checkpoints( + SingleSwitchProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context, + int start, int end, + int loop, int start_loop, int end_loop +){ + EventNotificationOption& notif_status_update = NOTIFICATION_STATUS_UPDATE; + Language language = LANGUAGE; + StarterChoice starter_choice = STARTERCHOICE; + std::vector> checkpoint_list; + checkpoint_list.push_back([&](){checkpoint_00(env, context);}); + checkpoint_list.push_back([&](){checkpoint_01(env, context, notif_status_update, language);}); + checkpoint_list.push_back([&](){checkpoint_02(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_03(env, context, notif_status_update, language, starter_choice);}); + checkpoint_list.push_back([&](){checkpoint_04(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_05(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_06(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_07(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_08(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_09(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_10(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_11(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_12(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_13(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_14(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_15(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_16(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_17(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_18(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_19(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_20(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_21(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_22(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_23(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_24(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_25(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_26(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_27(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_28(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_29(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_30(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_31(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_32(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_33(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_34(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_35(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_36(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_37(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_38(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_39(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_40(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_41(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_42(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_43(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_44(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_45(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_46(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_47(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_48(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_49(env, context, notif_status_update);}); + + for (int checkpoint = start; checkpoint <= end; checkpoint++){ + if (checkpoint == 0){ + stream.log("checkpoint_0"); + checkpoint_list[checkpoint](); + continue; + } + bool has_minimap = true; + if (checkpoint < 3){ + has_minimap = false; + } + + const size_t DIGITS = 3; + std::string number = std::to_string(checkpoint); + if (number.size() < DIGITS){ + number = std::string(DIGITS - number.size(), '0') + number; + } + if (checkpoint >= start_loop && checkpoint <= end_loop){ + for (int i = 0; i < loop; i++){ + if (i > 0){ + try { + reset_game(env.program_info(), env.console, context); + enter_menu_from_overworld(env.program_info(), env.console, context, -1, MenuSide::NONE, has_minimap); + // we wait 5 seconds then save, so that the initial conditions are slightly different on each reset. + env.log("Wait 5 seconds."); + context.wait_for(Milliseconds(5 * 1000)); + }catch(...){ + // try one more time + reset_game(env.program_info(), env.console, context); + enter_menu_from_overworld(env.program_info(), env.console, context, -1, MenuSide::NONE, has_minimap); + // we wait 5 seconds then save, so that the initial conditions are slightly different on each reset. + env.log("Wait 5 seconds."); + context.wait_for(Milliseconds(5 * 1000)); + + } + } + stream.log("checkpoint_" + number + ": loop " + std::to_string(i)); + checkpoint_list[checkpoint](); + } + }else{ + stream.log("checkpoint_" + number + "."); + checkpoint_list[checkpoint](); + } + + } + +} + +std::string AutoStory::start_segment_description(){ + size_t segment_index = 0; + if (STORY_SECTION == StorySection::TUTORIAL){ + segment_index = STARTPOINT_TUTORIAL.index(); + }else if (STORY_SECTION == StorySection::MAIN_STORY){ + segment_index = STARTPOINT_MAINSTORY.index() + (INDEX_OF_LAST_TUTORIAL_SEGMENT + 1); + } + return ALL_AUTO_STORY_SEGMENT_LIST()[segment_index]->start_text(); +} + +std::string AutoStory::end_segment_description(){ + size_t segment_index = 0; + if (STORY_SECTION == StorySection::TUTORIAL){ + segment_index = ENDPOINT_TUTORIAL.index(); + }else if (STORY_SECTION == StorySection::MAIN_STORY){ + segment_index = ENDPOINT_MAINSTORY.index() + (INDEX_OF_LAST_TUTORIAL_SEGMENT + 1); + } + return ALL_AUTO_STORY_SEGMENT_LIST()[segment_index]->end_text(); +} + +size_t AutoStory::get_start_segment_index(){ + size_t start = 0; + + if (STORY_SECTION == StorySection::TUTORIAL){ + start = STARTPOINT_TUTORIAL.index(); + }else if (STORY_SECTION == StorySection::MAIN_STORY){ + start = (INDEX_OF_LAST_TUTORIAL_SEGMENT + 1) + STARTPOINT_MAINSTORY.index(); + } + + return start; +} + +size_t AutoStory::get_end_segment_index(){ + size_t end = 0; + + if (STORY_SECTION == StorySection::TUTORIAL){ + end = ENDPOINT_TUTORIAL.index(); + }else if (STORY_SECTION == StorySection::MAIN_STORY){ + end = (INDEX_OF_LAST_TUTORIAL_SEGMENT + 1) + ENDPOINT_MAINSTORY.index(); + } + + return end; +} + + +void AutoStory::run_autostory(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + AutoStoryOptions options{ + LANGUAGE, + STARTERCHOICE, + NOTIFICATION_STATUS_UPDATE + }; + + for (size_t segment_index = get_start_segment_index(); segment_index <= get_end_segment_index(); segment_index++){ + ALL_AUTO_STORY_SEGMENT_LIST()[segment_index]->run_segment(env, context, options); + } +} + +void AutoStory::test_code(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (TEST_CURRENT_DIRECTION){ + DirectionDetector direction; + // direction.change_direction(env.program_info(), env.console, context, DIR_RADIANS); + VideoSnapshot snapshot = env.console.video().snapshot(); + env.console.log("current direction: " + std::to_string(direction.get_current_direction(env.console, snapshot))); + return; + } + + if (TEST_CHANGE_DIRECTION){ + DirectionDetector direction; + direction.change_direction(env.program_info(), env.console, context, DIR_RADIANS); + // VideoSnapshot snapshot = env.console.video().snapshot(); + // env.console.log("current direction: " + std::to_string(direction.get_current_direction(env.console, snapshot))); + return; + } + + if (TEST_PBF_LEFT_JOYSTICK){ + pbf_move_left_joystick(context, X_MOVE, Y_MOVE, HOLD_TICKS, RELEASE_TICKS); + return; + } + + if (TEST_PBF_LEFT_JOYSTICK2){ + pbf_move_left_joystick(context, X_MOVE2, Y_MOVE2, HOLD_TICKS2, RELEASE_TICKS2); + return; + } + + if (ENABLE_TEST_CHECKPOINTS){ + // test individual checkpoints + test_checkpoints(env, env.console, context, START_CHECKPOINT, END_CHECKPOINT, LOOP_CHECKPOINT, START_LOOP, END_LOOP); + return; + } + + + if (ENABLE_TEST_REALIGN){ + // clear realign marker + // realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 128, 128, 0); + realign_player(env.program_info(), env.console, context, REALIGN_MODE, X_REALIGN, Y_REALIGN, REALIGN_DURATION); + return; + } + + if (ENABLE_MISC_TEST){ + // walk_forward_while_clear_front_path(env.program_info(), env.console, context, FORWARD_TICKS); + + // overworld_navigation(env.program_info(), env.console, context, + // NavigationStopCondition::STOP_MARKER, NavigationMovementMode::CLEAR_WITH_LETS_GO, + // 128, 0, 60, 10, false); + + DirectionDetector direction; + + return; + } + + // context.wait_for(Milliseconds(1000000)); + + +} + +void AutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + // AutoStoryStats& stats = env.current_stats(); + + + // test code + if (ENABLE_TEST_CHECKPOINTS || ENABLE_TEST_REALIGN || ENABLE_MISC_TEST || TEST_PBF_LEFT_JOYSTICK || TEST_PBF_LEFT_JOYSTICK2 || TEST_CHANGE_DIRECTION || TEST_CURRENT_DIRECTION){ + test_code(env, context); + return; + } + + // Connect controller + pbf_press_button(context, BUTTON_L, 20, 20); + + // Set settings. to ensure autosave is off. + if (CHANGE_SETTINGS){ + change_settings_prior_to_autostory(env, context, get_start_segment_index(), LANGUAGE); + } + + run_autostory(env, context); + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.h index b4da42d53b..1d3be15268 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.h @@ -1,134 +1,137 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_H -#define PokemonAutomation_PokemonSV_AutoStory_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/StringSelectOption.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class AutoStory_Descriptor : public SingleSwitchProgramDescriptor{ -public: - AutoStory_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class AutoStory : public SingleSwitchProgramInstance, public ConfigOption::Listener{ -public: - ~AutoStory(); - AutoStory(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - void test_code(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - - // test the checkpoints from start to end, inclusive - // test each checkpoints "loop" number of times - void test_checkpoints( - SingleSwitchProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context, - int start, int end, - int loop, int start_loop, int end_loop - ); - - void run_autostory(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -private: - virtual void on_config_value_changed(void* object) override; - - std::string start_segment_description(); - std::string end_segment_description(); - -private: - OCR::LanguageOCROption LANGUAGE; - - enum class StorySection{ - TUTORIAL, - MAIN_STORY, - }; - - EnumDropdownOption STORY_SECTION; - - StringSelectOption STARTPOINT_TUTORIAL; - StringSelectOption ENDPOINT_TUTORIAL; - - StringSelectOption STARTPOINT_MAINSTORY; - StringSelectOption ENDPOINT_MAINSTORY; - - StaticTextOption MAINSTORY_NOTE; - - StaticTextOption START_DESCRIPTION; - StaticTextOption END_DESCRIPTION; - - - EnumDropdownOption STARTERCHOICE; - - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - SectionDividerOption m_advanced_options_end; - BooleanCheckBoxOption CHANGE_SETTINGS; - - BooleanCheckBoxOption ENABLE_TEST_CHECKPOINTS; - SimpleIntegerOption START_CHECKPOINT; - SimpleIntegerOption END_CHECKPOINT; - SimpleIntegerOption LOOP_CHECKPOINT; - SimpleIntegerOption START_LOOP; - SimpleIntegerOption END_LOOP; - - BooleanCheckBoxOption ENABLE_TEST_REALIGN; - EnumDropdownOption REALIGN_MODE; - SimpleIntegerOption X_REALIGN; - SimpleIntegerOption Y_REALIGN; - SimpleIntegerOption REALIGN_DURATION; - - BooleanCheckBoxOption ENABLE_MISC_TEST; - SimpleIntegerOption FORWARD_TICKS; - - BooleanCheckBoxOption TEST_PBF_LEFT_JOYSTICK; - SimpleIntegerOption X_MOVE; - SimpleIntegerOption Y_MOVE; - SimpleIntegerOption HOLD_TICKS; - SimpleIntegerOption RELEASE_TICKS; - - BooleanCheckBoxOption TEST_PBF_LEFT_JOYSTICK2; - SimpleIntegerOption X_MOVE2; - SimpleIntegerOption Y_MOVE2; - SimpleIntegerOption HOLD_TICKS2; - SimpleIntegerOption RELEASE_TICKS2; - - BooleanCheckBoxOption TEST_CURRENT_DIRECTION; - BooleanCheckBoxOption TEST_CHANGE_DIRECTION; - FloatingPointOption DIR_RADIANS; -}; - - - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_H +#define PokemonAutomation_PokemonSV_AutoStory_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/StringSelectOption.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class AutoStory_Descriptor : public SingleSwitchProgramDescriptor{ +public: + AutoStory_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class AutoStory : public SingleSwitchProgramInstance, public ConfigOption::Listener{ +public: + ~AutoStory(); + AutoStory(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + void test_code(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + + // test the checkpoints from start to end, inclusive + // test each checkpoints "loop" number of times + void test_checkpoints( + SingleSwitchProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context, + int start, int end, + int loop, int start_loop, int end_loop + ); + + size_t get_start_segment_index(); + size_t get_end_segment_index(); + + void run_autostory(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + virtual void on_config_value_changed(void* object) override; + + std::string start_segment_description(); + std::string end_segment_description(); + +private: + OCR::LanguageOCROption LANGUAGE; + + enum class StorySection{ + TUTORIAL, + MAIN_STORY, + }; + + EnumDropdownOption STORY_SECTION; + + StringSelectOption STARTPOINT_TUTORIAL; + StringSelectOption ENDPOINT_TUTORIAL; + + StringSelectOption STARTPOINT_MAINSTORY; + StringSelectOption ENDPOINT_MAINSTORY; + + StaticTextOption MAINSTORY_NOTE; + + StaticTextOption START_DESCRIPTION; + StaticTextOption END_DESCRIPTION; + + + EnumDropdownOption STARTERCHOICE; + + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + SectionDividerOption m_advanced_options_end; + BooleanCheckBoxOption CHANGE_SETTINGS; + + BooleanCheckBoxOption ENABLE_TEST_CHECKPOINTS; + SimpleIntegerOption START_CHECKPOINT; + SimpleIntegerOption END_CHECKPOINT; + SimpleIntegerOption LOOP_CHECKPOINT; + SimpleIntegerOption START_LOOP; + SimpleIntegerOption END_LOOP; + + BooleanCheckBoxOption ENABLE_TEST_REALIGN; + EnumDropdownOption REALIGN_MODE; + SimpleIntegerOption X_REALIGN; + SimpleIntegerOption Y_REALIGN; + SimpleIntegerOption REALIGN_DURATION; + + BooleanCheckBoxOption ENABLE_MISC_TEST; + SimpleIntegerOption FORWARD_TICKS; + + BooleanCheckBoxOption TEST_PBF_LEFT_JOYSTICK; + SimpleIntegerOption X_MOVE; + SimpleIntegerOption Y_MOVE; + SimpleIntegerOption HOLD_TICKS; + SimpleIntegerOption RELEASE_TICKS; + + BooleanCheckBoxOption TEST_PBF_LEFT_JOYSTICK2; + SimpleIntegerOption X_MOVE2; + SimpleIntegerOption Y_MOVE2; + SimpleIntegerOption HOLD_TICKS2; + SimpleIntegerOption RELEASE_TICKS2; + + BooleanCheckBoxOption TEST_CURRENT_DIRECTION; + BooleanCheckBoxOption TEST_CHANGE_DIRECTION; + FloatingPointOption DIR_RADIANS; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp index 6a0c79f2da..1b74969e3d 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp @@ -1,1156 +1,1192 @@ -/* AutoStoryTools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Exceptions/UnexpectedBattleException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/OCR/OCR_NumberReader.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.h" -#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/Battles/PokemonSV_Battles.h" -#include "PokemonSV/Programs/AutoStory/PokemonSV_MenuOption.h" -#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" -#include "PokemonSV/Inference/PokemonSV_PokemonMovesReader.h" -#include "PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.h" -#include "PokemonSV/Inference/Map/PokemonSV_MapPokeCenterIconDetector.h" -#include "PokemonSV_AutoStoryTools.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - - -void run_battle_press_A( - VideoStream& stream, - ProControllerContext& context, - BattleStopCondition stop_condition, - std::vector enum_optional_callbacks, - bool detect_wipeout -){ - int16_t num_times_seen_overworld = 0; - size_t consecutive_move_select = 0; - while (true){ - NormalBattleMenuWatcher battle(COLOR_BLUE); - SwapMenuWatcher fainted(COLOR_PURPLE); - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - AdvanceDialogWatcher dialog(COLOR_RED); - DialogArrowWatcher dialog_arrow(COLOR_RED, stream.overlay(), {0.850, 0.820, 0.020, 0.050}, 0.8365, 0.846); - GradientArrowWatcher next_pokemon(COLOR_BLUE, GradientArrowType::RIGHT, {0.50, 0.51, 0.30, 0.10}); - MoveSelectWatcher move_select_menu(COLOR_YELLOW); - - std::vector callbacks; - // mandatory callbacks: Battle, Overworld, Advance Dialog, Swap menu, Move select - std::vector enum_all_callbacks{CallbackEnum::BATTLE, CallbackEnum::OVERWORLD, CallbackEnum::ADVANCE_DIALOG, CallbackEnum::SWAP_MENU, CallbackEnum::MOVE_SELECT}; // mandatory callbacks - enum_all_callbacks.insert(enum_all_callbacks.end(), enum_optional_callbacks.begin(), enum_optional_callbacks.end()); // append the mandatory and optional callback vectors together - for (const CallbackEnum& enum_callback : enum_all_callbacks){ - switch(enum_callback){ - case CallbackEnum::ADVANCE_DIALOG: - callbacks.emplace_back(dialog); - break; - case CallbackEnum::OVERWORLD: - callbacks.emplace_back(overworld); - break; - case CallbackEnum::DIALOG_ARROW: - callbacks.emplace_back(dialog_arrow); - break; - case CallbackEnum::BATTLE: - callbacks.emplace_back(battle); - break; - case CallbackEnum::GRADIENT_ARROW: - callbacks.emplace_back(next_pokemon); - break; - case CallbackEnum::SWAP_MENU: - callbacks.emplace_back(fainted); - break; - case CallbackEnum::MOVE_SELECT: - callbacks.emplace_back(move_select_menu); - break; - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "run_battle_press_A: Unknown callback requested."); - } - } - context.wait_for_all_requests(); - - int ret = wait_until( - stream, context, - std::chrono::seconds(90), - callbacks - ); - context.wait_for(std::chrono::milliseconds(100)); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "run_battle_press_A(): Timed out. Did not detect expected stop condition.", - stream - ); - } - - CallbackEnum enum_callback = enum_all_callbacks[ret]; - switch (enum_callback){ - case CallbackEnum::BATTLE: // battle - stream.log("Detected battle menu."); - consecutive_move_select = 0; - pbf_press_button(context, BUTTON_A, 20, 105); - break; - case CallbackEnum::MOVE_SELECT: - stream.log("Detected move select. Spam first move"); - consecutive_move_select++; - select_top_move(stream, context, consecutive_move_select); - break; - case CallbackEnum::OVERWORLD: // overworld - stream.log("Detected overworld, battle over."); - num_times_seen_overworld++; - if (stop_condition == BattleStopCondition::STOP_OVERWORLD){ - return; - } - if(num_times_seen_overworld > 30){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "run_battle_press_A(): Stuck in overworld. Did not detect expected stop condition.", - stream - ); - } - break; - case CallbackEnum::ADVANCE_DIALOG: // advance dialog - stream.log("Detected dialog."); - - if (detect_wipeout){ - context.wait_for_all_requests(); - WipeoutDetector wipeout; - VideoSnapshot screen = stream.video().snapshot(); - // dump_snapshot(console); - if (wipeout.detect(screen)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "run_battle_press_A(): Detected wipeout. All pokemon fainted.", - stream - ); - } - } - - if (stop_condition == BattleStopCondition::STOP_DIALOG){ - return; - } - pbf_press_button(context, BUTTON_A, 20, 105); - break; - case CallbackEnum::DIALOG_ARROW: // dialog arrow - stream.log("run_battle_press_A: Detected dialog arrow."); - pbf_press_button(context, BUTTON_A, 20, 105); - break; - case CallbackEnum::GRADIENT_ARROW: - stream.log("run_battle_press_A: Detected prompt for bringing in next pokemon. Keep current pokemon."); - pbf_mash_button(context, BUTTON_B, 100); - break; - case CallbackEnum::SWAP_MENU: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "run_battle_press_A(): Lead pokemon fainted.", - stream - ); - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "run_battle_press_A: Unknown callback triggered."); - - } - } -} - -void select_top_move(VideoStream& stream, ProControllerContext& context, size_t consecutive_move_select){ - if (consecutive_move_select > 3){ - // to handle case where move is disabled/out of PP/taunted - stream.log("Failed to select a move 3 times. Choosing a different move.", COLOR_RED); - pbf_press_dpad(context, DPAD_DOWN, 20, 40); - } - pbf_mash_button(context, BUTTON_A, 100); - -} - -void clear_tutorial(VideoStream& stream, ProControllerContext& context, uint16_t seconds_timeout){ - bool seen_tutorial = false; - while (true){ - TutorialWatcher tutorial; - context.wait_for_all_requests(); - - int ret = wait_until( - stream, context, - std::chrono::seconds(seconds_timeout), - {tutorial} - ); - context.wait_for(std::chrono::milliseconds(100)); - - switch (ret){ - case 0: - stream.log("clear_tutorial: Detected tutorial screen."); - seen_tutorial = true; - pbf_press_button(context, BUTTON_A, 20, 105); - break; - default: - stream.log("clear_tutorial: Timed out."); - if(!seen_tutorial){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "clear_tutorial(): Tutorial screen never detected.", - stream - ); - } - return; - } - } -} - -void clear_dialog(VideoStream& stream, ProControllerContext& context, - ClearDialogMode mode, uint16_t seconds_timeout, - std::vector enum_optional_callbacks -){ - bool seen_dialog = false; - WallClock start = current_time(); - while (true){ - if (current_time() - start > std::chrono::minutes(3)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "clear_dialog(): Failed to clear dialog after 3 minutes.", - stream - ); - } - - AdvanceDialogWatcher advance_dialog(COLOR_RED); - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - PromptDialogWatcher prompt(COLOR_YELLOW); - WhiteButtonWatcher whitebutton(COLOR_GREEN, WhiteButton::ButtonA_DarkBackground, {0.725, 0.833, 0.024, 0.045}); // {0.650, 0.650, 0.140, 0.240} - DialogArrowWatcher dialog_arrow(COLOR_RED, stream.overlay(), {0.850, 0.820, 0.020, 0.050}, 0.8365, 0.846); - NormalBattleMenuWatcher battle(COLOR_ORANGE); - TutorialWatcher tutorial(COLOR_BLUE); - DialogBoxWatcher black_dialog_box(COLOR_BLACK, true, std::chrono::milliseconds(250), DialogType::DIALOG_BLACK); - context.wait_for_all_requests(); - - std::vector callbacks; - std::vector enum_all_callbacks{CallbackEnum::ADVANCE_DIALOG}; // mandatory callbacks - enum_all_callbacks.insert(enum_all_callbacks.end(), enum_optional_callbacks.begin(), enum_optional_callbacks.end()); // append the mandatory and optional callback vectors together - for (const CallbackEnum& enum_callback : enum_all_callbacks){ - switch(enum_callback){ - case CallbackEnum::ADVANCE_DIALOG: - callbacks.emplace_back(advance_dialog); - break; - case CallbackEnum::OVERWORLD: - callbacks.emplace_back(overworld); - break; - case CallbackEnum::PROMPT_DIALOG: - callbacks.emplace_back(prompt); - break; - case CallbackEnum::WHITE_A_BUTTON: - callbacks.emplace_back(whitebutton); - break; - case CallbackEnum::DIALOG_ARROW: - callbacks.emplace_back(dialog_arrow); - break; - case CallbackEnum::BATTLE: - callbacks.emplace_back(battle); - break; - case CallbackEnum::TUTORIAL: - callbacks.emplace_back(tutorial); - break; - case CallbackEnum::BLACK_DIALOG_BOX: - callbacks.emplace_back(black_dialog_box); - break; - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "clear_dialog: Unknown callback requested."); - } - } - - - int ret = wait_until( - stream, context, - std::chrono::seconds(seconds_timeout), - callbacks - ); - // int ret = run_until( - // console, context, - // [&](ProControllerContext& context){ - // for (size_t j = 0; j < seconds_timeout/3; j++){ - // pbf_press_button(context, BUTTON_A, 20, 3*TICKS_PER_SECOND-20); - // } - // }, - // {overworld, prompt, whitebutton, advance_dialog, battle} - // ); - context.wait_for(std::chrono::milliseconds(100)); - if (ret < 0){ - stream.log("clear_dialog(): Timed out."); - if (seen_dialog && mode == ClearDialogMode::STOP_TIMEOUT){ - return; - } - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "clear_dialog(): Timed out. Did not detect dialog or did not detect the expected stop condition.", - stream - ); - } - - CallbackEnum enum_callback = enum_all_callbacks[ret]; - switch(enum_callback){ - case CallbackEnum::ADVANCE_DIALOG: - stream.log("clear_dialog: Detected advance dialog."); - seen_dialog = true; - pbf_press_button(context, BUTTON_A, 20, 105); - break; - case CallbackEnum::OVERWORLD: - stream.log("clear_dialog: Detected overworld."); - if (seen_dialog && mode == ClearDialogMode::STOP_OVERWORLD){ - return; - } - break; - case CallbackEnum::PROMPT_DIALOG: - stream.log("clear_dialog: Detected prompt."); - seen_dialog = true; - if (mode == ClearDialogMode::STOP_PROMPT){ - return; - } - pbf_press_button(context, BUTTON_A, 20, 105); - break; - case CallbackEnum::WHITE_A_BUTTON: - stream.log("clear_dialog: Detected white A button."); - seen_dialog = true; - if (mode == ClearDialogMode::STOP_WHITEBUTTON){ - return; - } - pbf_press_button(context, BUTTON_A, 20, 105); - break; - case CallbackEnum::DIALOG_ARROW: - stream.log("clear_dialog: Detected dialog arrow."); - seen_dialog = true; - pbf_press_button(context, BUTTON_A, 20, 105); - break; - case CallbackEnum::BATTLE: - stream.log("clear_dialog: Detected battle."); - if (mode == ClearDialogMode::STOP_BATTLE){ - return; - } - break; - case CallbackEnum::TUTORIAL: - stream.log("clear_dialog: Detected tutorial."); - pbf_press_button(context, BUTTON_A, 20, 105); - break; - case CallbackEnum::BLACK_DIALOG_BOX: - stream.log("clear_dialog: Detected black dialog box."); - seen_dialog = true; - pbf_press_button(context, BUTTON_A, 20, 105); - break; - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "clear_dialog: Unknown callback triggered."); - - } - - } -} - -bool confirm_marker_present( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context -){ - while (true){ - DestinationMarkerWatcher marker(COLOR_RED, {0.815, 0.645, 0.180, 0.320}, true); - NormalBattleMenuWatcher battle(COLOR_BLUE); - - int ret = wait_until( - stream, context, - std::chrono::seconds(5), - {marker, battle} - ); - switch (ret){ - case 0: // marker - stream.log("Confirmed that marker is still present."); - return true; - case 1: // battle - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "confirm_marker_present(): Unexpectedly detected battle.", - stream - ); - default: - stream.log("Destination marker not detected."); - return false; - } - } - -} - -void overworld_navigation( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - NavigationStopCondition stop_condition, - NavigationMovementMode movement_mode, - uint8_t x, uint8_t y, - uint16_t seconds_timeout, uint16_t seconds_realign, - bool auto_heal, - bool detect_wipeout -){ - bool should_realign = true; - if (seconds_timeout <= seconds_realign){ - seconds_realign = seconds_timeout; - should_realign = false; - } - uint16_t forward_ticks = seconds_realign * TICKS_PER_SECOND; - // WallClock start = current_time(); - - if (stop_condition == NavigationStopCondition::STOP_MARKER){ - context.wait_for(Milliseconds(2000)); // the "Destination arrived" notification can sometimes reappear if you opened the map too quickly after you reached the previous marker. - } - - - while (true){ - NormalBattleMenuWatcher battle(COLOR_BLUE); - DialogBoxWatcher dialog(COLOR_RED, true); - DestinationMarkerWatcher marker(COLOR_CYAN, {0.717, 0.165, 0.03, 0.061}); - context.wait_for_all_requests(); - std::vector callbacks = {battle, dialog}; - if (stop_condition == NavigationStopCondition::STOP_MARKER){ - callbacks.emplace_back(marker); - } - // uint16_t ticks_passed = std::chrono::duration_cast(current_time() - start).count() * TICKS_PER_SECOND / 1000; - // forward_ticks = seconds_realign * TICKS_PER_SECOND - ticks_passed; - - int ret = run_until( - stream, context, - [&](ProControllerContext& context){ - - for (int i = 0; i < seconds_timeout / seconds_realign; i++){ - if (movement_mode == NavigationMovementMode::CLEAR_WITH_LETS_GO){ - walk_forward_while_clear_front_path(info, stream, context, forward_ticks, y); - }else{ - ssf_press_left_joystick(context, x, y, 0, seconds_realign * TICKS_PER_SECOND); - if (movement_mode == NavigationMovementMode::DIRECTIONAL_ONLY){ - pbf_wait(context, seconds_realign * TICKS_PER_SECOND); - } else if (movement_mode == NavigationMovementMode::DIRECTIONAL_SPAM_A){ - for (size_t j = 0; j < seconds_realign; j++){ - pbf_press_button(context, BUTTON_A, 20, 105); - } - } - } - context.wait_for_all_requests(); - if (should_realign){ - try { - realign_player(info, stream, context, PlayerRealignMode::REALIGN_OLD_MARKER); - - }catch (UnexpectedBattleException&){ - pbf_wait(context, 30 * TICKS_PER_SECOND); // catch exception to allow the battle callback to take over. - } - - } - } - }, - callbacks - ); - context.wait_for(std::chrono::milliseconds(100)); - - switch (ret){ - case 0: // battle - stream.log("overworld_navigation: Detected start of battle."); - if (stop_condition == NavigationStopCondition::STOP_BATTLE){ - return; - } - - run_battle_press_A(stream, context, BattleStopCondition::STOP_OVERWORLD, {}, detect_wipeout); - if (auto_heal){ - auto_heal_from_menu_or_overworld(info, stream, context, 0, true); - } - context.wait_for_all_requests(); - try { - realign_player(info, stream, context, PlayerRealignMode::REALIGN_OLD_MARKER); - if (stop_condition == NavigationStopCondition::STOP_MARKER && !confirm_marker_present(info, stream, context)){ - // if marker not present when using marker based navigation, don't keep walking forward. - return; - } - - break; - }catch (UnexpectedBattleException&){ - break; - } - case 1: // dialog - stream.log("overworld_navigation: Detected dialog."); - if (stop_condition == NavigationStopCondition::STOP_DIALOG){ - return; - } - if (stop_condition == NavigationStopCondition::STOP_MARKER){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "overworld_navigation(): Unexpectedly detected dialog.", - stream - ); - } - pbf_press_button(context, BUTTON_A, 20, 20); - break; - case 2: // marker - stream.log("overworld_navigation: Detected marker."); - if (stop_condition == NavigationStopCondition::STOP_MARKER){ - return; - } - break; - default: - stream.log("overworld_navigation(): Timed out."); - if (stop_condition == NavigationStopCondition::STOP_TIME){ - return; - } - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "overworld_navigation(): Timed out. Did not detect expected stop condition.", - stream - ); - } - } -} - -void config_option(ProControllerContext& context, int change_option_value){ - for (int i = 0; i < change_option_value; i++){ - pbf_press_dpad(context, DPAD_RIGHT, 15, 20); - } - pbf_press_dpad(context, DPAD_DOWN, 15, 20); -} - -void swap_starter_moves(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, Language language){ - WallClock start = current_time(); - while (true){ - if (current_time() - start > std::chrono::minutes(3)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "swap_starter_moves(): Failed to swap the starter moves after 3 minutes.", - stream - ); - } - // start in the overworld - press_Bs_to_back_to_overworld(info, stream, context); - - // open menu, select your starter - enter_menu_from_overworld(info, stream, context, 0, MenuSide::LEFT); - - // enter Pokemon summary screen - pbf_press_button(context, BUTTON_A, 20, 5 * TICKS_PER_SECOND); - pbf_press_dpad(context, DPAD_RIGHT, 15, 1 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_Y, 20, 40); - - // select move 1 - pbf_press_button(context, BUTTON_A, 20, 40); - pbf_press_dpad(context, DPAD_DOWN, 15, 40); - pbf_press_dpad(context, DPAD_DOWN, 15, 40); - // extra button presses to avoid drops - pbf_press_dpad(context, DPAD_DOWN, 15, 40); - pbf_press_dpad(context, DPAD_DOWN, 15, 40); - - // select move 3. swap move 1 and move 3. - pbf_press_button(context, BUTTON_A, 20, 40); - - // confirm that Ember/Leafage/Water Gun is in slot 1 - context.wait_for_all_requests(); - VideoSnapshot screen = stream.video().snapshot(); - PokemonMovesReader reader(language); - std::string top_move = reader.read_move(stream.logger(), screen, 0); - stream.log("Current top move: " + top_move); - if (top_move != "ember" && top_move != "leafage" && top_move != "water-gun"){ - stream.log("Failed to swap moves. Re-try."); - continue; - } - - - break; - } - -} - - -void change_settings_prior_to_autostory( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - size_t current_segment_num, - Language language -){ - if (current_segment_num == 0){ // can't change settings in the intro cutscene - return; - } - - // get index of `Options` in the Main Menu, which depends on where you are in Autostory - int8_t options_index; - switch(current_segment_num){ - case 0: - options_index = 0; - break; - case 1: - options_index = 1; - break; - default: - options_index = 2; - break; - } - - bool has_minimap = current_segment_num > 1; // the minimap only shows up in segment 2 and beyond - - enter_menu_from_overworld(env.program_info(), env.console, context, options_index, MenuSide::RIGHT, has_minimap); - change_settings(env, context, language); - if(has_minimap){ - pbf_mash_button(context, BUTTON_B, 2 * TICKS_PER_SECOND); - }else{ - press_Bs_to_back_to_overworld(env.program_info(), env.console, context); - } -} - - -void change_settings(SingleSwitchProgramEnvironment& env, ProControllerContext& context, Language language, bool use_inference){ - env.console.log("Update settings."); - if (use_inference){ - MenuOption session(env.console, context, language); - - std::vector>> options = { - {MenuOptionItemEnum::TEXT_SPEED, {MenuOptionToggleEnum::FAST}}, - {MenuOptionItemEnum::SKIP_MOVE_LEARNING, {MenuOptionToggleEnum::ON}}, - {MenuOptionItemEnum::SEND_TO_BOXES, {MenuOptionToggleEnum::AUTOMATIC, MenuOptionToggleEnum::ON}}, - {MenuOptionItemEnum::GIVE_NICKNAMES, {MenuOptionToggleEnum::OFF}}, - {MenuOptionItemEnum::VERTICAL_CAMERA_CONTROLS, {MenuOptionToggleEnum::REGULAR, MenuOptionToggleEnum::NORMAL}}, - {MenuOptionItemEnum::HORIZONTAL_CAMERA_CONTROLS, {MenuOptionToggleEnum::REGULAR, MenuOptionToggleEnum::NORMAL}}, - {MenuOptionItemEnum::CAMERA_SUPPORT, {MenuOptionToggleEnum::OFF}}, - {MenuOptionItemEnum::CAMERA_INTERPOLATION, {MenuOptionToggleEnum::NORMAL, MenuOptionToggleEnum::AVERAGE}}, - {MenuOptionItemEnum::CAMERA_DISTANCE, {MenuOptionToggleEnum::CLOSE}}, - {MenuOptionItemEnum::AUTOSAVE, {MenuOptionToggleEnum::OFF}}, - {MenuOptionItemEnum::SHOW_NICKNAMES, {MenuOptionToggleEnum::OFF, MenuOptionToggleEnum::DONT_SHOW}}, - {MenuOptionItemEnum::SKIP_CUTSCENES, {MenuOptionToggleEnum::ON}}, - {MenuOptionItemEnum::CONTROLLER_RUMBLE, {MenuOptionToggleEnum::ON}}, - {MenuOptionItemEnum::HELPING_FUNCTIONS, {MenuOptionToggleEnum::OFF}}, - - }; - session.set_options(options); - }else{ - config_option(context, 1); // Text Speed: Fast - config_option(context, 1); // Skip Move Learning: On - config_option(context, 1); // Send to Boxes: Automatic - config_option(context, 1); // Give Nicknames: Off - config_option(context, 0); // Vertical Camera Controls: Regular - config_option(context, 0); // Horiztontal Camera Controls: Regular - config_option(context, 1); // Camera Support: Off - config_option(context, 0); // Camera Interpolation: Normal - config_option(context, 0); // Camera Distance: Close - config_option(context, 1); // Autosave: Off - config_option(context, 1); // Show Nicknames: Don't show - config_option(context, 1); // Skip Cutscenes: On - config_option(context, 0); // Background Music: 10 - config_option(context, 0); // Sound Effects: 10 - config_option(context, 0); // Pokemon Cries: 10 - config_option(context, 0); // Controller Rumble: On - config_option(context, 1); // Helping Functions: Off - } - - pbf_mash_button(context, BUTTON_A, 1 * TICKS_PER_SECOND); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 5, {CallbackEnum::PROMPT_DIALOG}); - -} - -void do_action_and_monitor_for_battles( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - std::function< - void(const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context) - >&& action -){ - NormalBattleMenuWatcher battle_menu(COLOR_RED); - int ret = run_until( - stream, context, - [&](ProControllerContext& context){ - context.wait_for_all_requests(); - action(info, stream, context); - }, - {battle_menu} - ); - if (ret == 0){ // battle detected - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "do_action_and_monitor_for_battles(): Detected battle. Failed to complete action.", - stream - ); - - } -} - - -void handle_unexpected_battles( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - std::function< - void(const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context) - >&& action -){ - while (true){ - try { - context.wait_for_all_requests(); - action(info, stream, context); - return; - }catch (UnexpectedBattleException&){ - run_battle_press_A(stream, context, BattleStopCondition::STOP_OVERWORLD); - } - } -} - -void handle_when_stationary_in_overworld( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - std::function< - void(const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context) - >&& action, - std::function< - void(const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context) - >&& recovery_action, - size_t seconds_stationary, - uint16_t minutes_timeout, - size_t max_failures -){ - - WallClock start = current_time(); - size_t num_failures = 0; - while (true){ - if (current_time() - start > std::chrono::minutes(minutes_timeout)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "handle_when_stationary_in_overworld(): Failed to complete action after " + std::to_string(minutes_timeout) + " minutes.", - stream - ); - } - StationaryOverworldWatcher stationary_overworld(COLOR_RED, {0.865, 0.825, 0.08, 0.1}, seconds_stationary); - - int ret = run_until( - stream, context, - [&](ProControllerContext& context){ - context.wait_for_all_requests(); - action(info, stream, context); - }, - {stationary_overworld} - ); - if (ret < 0){ - // successfully completed action without being stuck in a position where the overworld is stationary. - return; - }else if (ret == 0){ - // if stationary in overworld, run recovery action then try action again - stream.log("Detected stationary overworld."); - num_failures++; - if (num_failures > max_failures){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "handle_when_stationary_in_overworld(): Failed to complete action within " + std::to_string(max_failures) + " attempts.", - stream - ); - } - context.wait_for_all_requests(); - recovery_action(info, stream, context); - } - } -} - - -void handle_failed_action( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - std::function< - void(const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context) - >&& action, - std::function< - void(const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context) - >&& recovery_action, - size_t max_failures -){ - size_t num_failures = 0; - while (true){ - try { - context.wait_for_all_requests(); - action(info, stream, context); - return; - }catch (OperationFailedException& e){ - num_failures++; - if (num_failures > max_failures){ - throw e; - } - recovery_action(info, stream, context); - } - } -} - - -void wait_for_gradient_arrow( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - ImageFloatBox box_area_to_check, - uint16_t seconds_timeout -){ - context.wait_for_all_requests(); - GradientArrowWatcher arrow(COLOR_RED, GradientArrowType::RIGHT, box_area_to_check); - int ret = wait_until( - stream, context, - Milliseconds(seconds_timeout * 1000), - { arrow } - ); - if (ret == 0){ - stream.log("Gradient arrow detected."); - }else{ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to detect gradient arrow.", - stream - ); - } -} - -void wait_for_overworld( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - uint16_t seconds_timeout -){ - context.wait_for_all_requests(); - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - int ret = wait_until( - stream, context, - Milliseconds(seconds_timeout * 1000), - { overworld } - ); - if (ret == 0){ - stream.log("Overworld detected."); - }else{ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to detect overworld.", - stream - ); - } - -} - -void press_A_until_dialog( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - uint16_t seconds_between_button_presses -){ - context.wait_for_all_requests(); - AdvanceDialogWatcher advance_dialog(COLOR_RED); - int ret = run_until( - stream, context, - [seconds_between_button_presses](ProControllerContext& context){ - pbf_wait(context, seconds_between_button_presses * TICKS_PER_SECOND); // avoiding pressing A if dialog already present - for (size_t c = 0; c < 10; c++){ - pbf_press_button(context, BUTTON_A, 20, seconds_between_button_presses * TICKS_PER_SECOND); - } - }, - {advance_dialog} - ); - if (ret == 0){ - stream.log("press_A_until_dialog: Detected dialog."); - }else{ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "press_A_until_dialog(): Unable to detect dialog after 10 button presses.", - stream - ); - } -} - -bool is_ride_active(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - while (true){ - try { - // open main menu - enter_menu_from_overworld(info, stream, context, -1, MenuSide::NONE, true); - context.wait_for_all_requests(); - ImageStats ride_indicator = image_stats( - extract_box_reference( - stream.video().snapshot(), - ImageFloatBox(0.05, 0.995, 0.25, 0.003) - ) - ); - - bool is_ride_active = !is_black(ride_indicator); // ride is active if the ride indicator isn't black. - pbf_press_button(context, BUTTON_B, 30, 100); - press_Bs_to_back_to_overworld(info, stream, context, 7); - if (is_ride_active){ - stream.log("Ride is active."); - }else{ - stream.log("Ride is not active."); - } - return is_ride_active; - - }catch(UnexpectedBattleException&){ - run_battle_press_A(stream, context, BattleStopCondition::STOP_OVERWORLD); - } - } - -} - -void get_on_ride(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - get_on_or_off_ride(info, stream, context, true); -} - -void get_off_ride(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - get_on_or_off_ride(info, stream, context, false); -} - -void get_on_or_off_ride(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, bool get_on){ - pbf_press_button(context, BUTTON_PLUS, 20, 20); - - WallClock start = current_time(); - while (get_on != is_ride_active(info, stream, context)){ - if (current_time() - start > std::chrono::minutes(3)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "get_on_or_off_ride(): Failed to get on/off ride after 3 minutes.", - stream - ); - } - pbf_press_button(context, BUTTON_PLUS, 30, 100); - } -} - -void checkpoint_save(SingleSwitchProgramEnvironment& env, ProControllerContext& context, EventNotificationOption& notif_status_update){ - AutoStoryStats& stats = env.current_stats(); - save_game_from_overworld(env.program_info(), env.console, context); - stats.m_checkpoint++; - env.update_stats(); - send_program_status_notification(env, notif_status_update, "Saved at checkpoint."); -} - - -void realign_player_from_landmark( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - MoveCursor move_cursor_near_landmark, - MoveCursor move_cursor_to_target -){ - - stream.log("Realigning player direction, using a landmark..."); - WallClock start = current_time(); - - while (true){ - if (current_time() - start > std::chrono::minutes(5)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "realign_player_from_landmark(): Failed to realign player after 5 minutes.", - stream - ); - } - - try { - open_map_from_overworld(info, stream, context, false); - - // move cursor near landmark (pokecenter) - switch(move_cursor_near_landmark.zoom_change){ - case ZoomChange::ZOOM_IN: - pbf_press_button(context, BUTTON_ZR, 20, 105); - break; - case ZoomChange::ZOOM_IN_TWICE: - pbf_press_button(context, BUTTON_ZR, 20, 105); - pbf_press_button(context, BUTTON_ZR, 20, 105); - break; - case ZoomChange::ZOOM_OUT: - pbf_press_button(context, BUTTON_ZL, 20, 105); - break; - case ZoomChange::ZOOM_OUT_TWICE: - pbf_press_button(context, BUTTON_ZL, 20, 105); - pbf_press_button(context, BUTTON_ZL, 20, 105); - break; - case ZoomChange::KEEP_ZOOM: - break; - } - uint8_t move_x1 = move_cursor_near_landmark.move_x; - uint8_t move_y1 = move_cursor_near_landmark.move_y; - uint16_t move_duration1 = move_cursor_near_landmark.move_duration; - pbf_move_left_joystick(context, move_x1, move_y1, move_duration1, 1 * TICKS_PER_SECOND); - - // move cursor to pokecenter - if (!detect_closest_pokecenter_and_move_map_cursor_there(info, stream, context, 0.29)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "realign_player_from_landmark(): No visible pokecenter found on map.", - stream - ); - } - - confirm_cursor_centered_on_pokecenter(info, stream, context); // throws exception if fails - - // move cursor from landmark to target - switch(move_cursor_to_target.zoom_change){ - case ZoomChange::ZOOM_IN: - pbf_press_button(context, BUTTON_ZR, 20, 105); - break; - case ZoomChange::ZOOM_IN_TWICE: - pbf_press_button(context, BUTTON_ZR, 20, 105); - pbf_press_button(context, BUTTON_ZR, 20, 105); - break; - case ZoomChange::ZOOM_OUT: - pbf_press_button(context, BUTTON_ZL, 20, 105); - break; - case ZoomChange::ZOOM_OUT_TWICE: - pbf_press_button(context, BUTTON_ZL, 20, 105); - pbf_press_button(context, BUTTON_ZL, 20, 105); - break; - case ZoomChange::KEEP_ZOOM: - break; - } - uint8_t move_x2 = move_cursor_to_target.move_x; - uint8_t move_y2 = move_cursor_to_target.move_y; - uint16_t move_duration2 = move_cursor_to_target.move_duration; - pbf_move_left_joystick(context, move_x2, move_y2, move_duration2, 1 * TICKS_PER_SECOND); - - // place down marker - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_A, 20, 105); - leave_phone_to_overworld(info, stream, context); - - return; - - }catch (OperationFailedException&){ - // reset to overworld if failed to center on the pokecenter, and re-try - leave_phone_to_overworld(info, stream, context); - }catch (UnexpectedBattleException&){ - run_battle_press_A(stream, context, BattleStopCondition::STOP_OVERWORLD); - } - } - - -} - - -void confirm_cursor_centered_on_pokecenter(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - context.wait_for_all_requests(); - context.wait_for(Milliseconds(500)); - ImageFloatBox center_cursor{0.484, 0.472, 0.030, 0.053}; - MapPokeCenterIconDetector pokecenter(COLOR_RED, center_cursor); - if (!pokecenter.detect(stream.video().snapshot())){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "confirm_cursor_centered_on_pokecenter(): Cursor is not centered on a pokecenter.", - stream - ); - } - - stream.log("Confirmed that the cursor is centered on a pokecenter."); -} - -void move_cursor_towards_flypoint_and_go_there( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - MoveCursor move_cursor_near_flypoint -){ - WallClock start = current_time(); - - while (true){ - if (current_time() - start > std::chrono::minutes(5)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "move_cursor_towards_flypoint_and_go_there(): Failed to fly after 5 minutes.", - stream - ); - } - - try { - open_map_from_overworld(info, stream, context, false); - - // move cursor near landmark (pokecenter) - switch(move_cursor_near_flypoint.zoom_change){ - case ZoomChange::ZOOM_IN: - pbf_press_button(context, BUTTON_ZR, 20, 105); - break; - case ZoomChange::ZOOM_IN_TWICE: - pbf_press_button(context, BUTTON_ZR, 20, 105); - pbf_press_button(context, BUTTON_ZR, 20, 105); - break; - case ZoomChange::ZOOM_OUT: - pbf_press_button(context, BUTTON_ZL, 20, 105); - break; - case ZoomChange::ZOOM_OUT_TWICE: - pbf_press_button(context, BUTTON_ZL, 20, 105); - pbf_press_button(context, BUTTON_ZL, 20, 105); - break; - case ZoomChange::KEEP_ZOOM: - break; - } - uint8_t move_x1 = move_cursor_near_flypoint.move_x; - uint8_t move_y1 = move_cursor_near_flypoint.move_y; - uint16_t move_duration1 = move_cursor_near_flypoint.move_duration; - pbf_move_left_joystick(context, move_x1, move_y1, move_duration1, 1 * TICKS_PER_SECOND); - - if (!fly_to_visible_closest_pokecenter_cur_zoom_level(info, stream, context)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "move_cursor_towards_flypoint_and_go_there(): No visible pokecenter found on map.", - stream - ); - } - - return; - - }catch (OperationFailedException&){ - // reset to overworld if failed to center on the pokecenter, and re-try - leave_phone_to_overworld(info, stream, context); - }catch (UnexpectedBattleException&){ - run_battle_press_A(stream, context, BattleStopCondition::STOP_OVERWORLD); - } - } - - -} - - - -void check_num_sunflora_found(SingleSwitchProgramEnvironment& env, ProControllerContext& context, int expected_number){ - context.wait_for_all_requests(); - VideoSnapshot screen = env.console.video().snapshot(); - ImageFloatBox num_sunflora_box = {0.27, 0.02, 0.04, 0.055}; - int number = OCR::read_number_waterfill(env.console, extract_box_reference(screen, num_sunflora_box), 0xff000000, 0xff808080); - - if (number != expected_number){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "The number of sunflora found is different than expected.", - env.console - ); - }else{ - env.console.log("Number of sunflora found: " + std::to_string(number)); - } - - -} - - - -} -} -} +/* AutoStoryTools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Exceptions/UnexpectedBattleException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/OCR/OCR_NumberReader.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.h" +#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/Battles/PokemonSV_Battles.h" +#include "PokemonSV/Programs/AutoStory/PokemonSV_MenuOption.h" +#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" +#include "PokemonSV/Inference/PokemonSV_PokemonMovesReader.h" +#include "PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.h" +#include "PokemonSV/Inference/Map/PokemonSV_MapPokeCenterIconDetector.h" +#include "PokemonSV_AutoStoryTools.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + + +void run_battle_press_A( + VideoStream& stream, + ProControllerContext& context, + BattleStopCondition stop_condition, + std::vector enum_optional_callbacks, + bool detect_wipeout +){ + int16_t num_times_seen_overworld = 0; + size_t consecutive_move_select = 0; + while (true){ + NormalBattleMenuWatcher battle(COLOR_BLUE); + SwapMenuWatcher fainted(COLOR_PURPLE); + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + AdvanceDialogWatcher dialog(COLOR_RED); + DialogArrowWatcher dialog_arrow(COLOR_RED, stream.overlay(), {0.850, 0.820, 0.020, 0.050}, 0.8365, 0.846); + GradientArrowWatcher next_pokemon(COLOR_BLUE, GradientArrowType::RIGHT, {0.50, 0.51, 0.30, 0.10}); + MoveSelectWatcher move_select_menu(COLOR_YELLOW); + + std::vector callbacks; + // mandatory callbacks: Battle, Overworld, Advance Dialog, Swap menu, Move select + std::vector enum_all_callbacks{CallbackEnum::BATTLE, CallbackEnum::OVERWORLD, CallbackEnum::ADVANCE_DIALOG, CallbackEnum::SWAP_MENU, CallbackEnum::MOVE_SELECT}; // mandatory callbacks + enum_all_callbacks.insert(enum_all_callbacks.end(), enum_optional_callbacks.begin(), enum_optional_callbacks.end()); // append the mandatory and optional callback vectors together + for (const CallbackEnum& enum_callback : enum_all_callbacks){ + switch(enum_callback){ + case CallbackEnum::ADVANCE_DIALOG: + callbacks.emplace_back(dialog); + break; + case CallbackEnum::OVERWORLD: + callbacks.emplace_back(overworld); + break; + case CallbackEnum::DIALOG_ARROW: + callbacks.emplace_back(dialog_arrow); + break; + case CallbackEnum::BATTLE: + callbacks.emplace_back(battle); + break; + case CallbackEnum::GRADIENT_ARROW: + callbacks.emplace_back(next_pokemon); + break; + case CallbackEnum::SWAP_MENU: + callbacks.emplace_back(fainted); + break; + case CallbackEnum::MOVE_SELECT: + callbacks.emplace_back(move_select_menu); + break; + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "run_battle_press_A: Unknown callback requested."); + } + } + context.wait_for_all_requests(); + + int ret = wait_until( + stream, context, + std::chrono::seconds(90), + callbacks + ); + context.wait_for(std::chrono::milliseconds(100)); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "run_battle_press_A(): Timed out. Did not detect expected stop condition.", + stream + ); + } + + CallbackEnum enum_callback = enum_all_callbacks[ret]; + switch (enum_callback){ + case CallbackEnum::BATTLE: // battle + stream.log("Detected battle menu."); + consecutive_move_select = 0; + pbf_press_button(context, BUTTON_A, 20, 105); + break; + case CallbackEnum::MOVE_SELECT: + stream.log("Detected move select. Spam first move"); + consecutive_move_select++; + select_top_move(stream, context, consecutive_move_select); + break; + case CallbackEnum::OVERWORLD: // overworld + stream.log("Detected overworld, battle over."); + num_times_seen_overworld++; + if (stop_condition == BattleStopCondition::STOP_OVERWORLD){ + return; + } + if(num_times_seen_overworld > 30){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "run_battle_press_A(): Stuck in overworld. Did not detect expected stop condition.", + stream + ); + } + break; + case CallbackEnum::ADVANCE_DIALOG: // advance dialog + stream.log("Detected dialog."); + + if (detect_wipeout){ + context.wait_for_all_requests(); + WipeoutDetector wipeout; + VideoSnapshot screen = stream.video().snapshot(); + // dump_snapshot(console); + if (wipeout.detect(screen)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "run_battle_press_A(): Detected wipeout. All pokemon fainted.", + stream + ); + } + } + + if (stop_condition == BattleStopCondition::STOP_DIALOG){ + return; + } + pbf_press_button(context, BUTTON_A, 20, 105); + break; + case CallbackEnum::DIALOG_ARROW: // dialog arrow + stream.log("run_battle_press_A: Detected dialog arrow."); + pbf_press_button(context, BUTTON_A, 20, 105); + break; + case CallbackEnum::GRADIENT_ARROW: + stream.log("run_battle_press_A: Detected prompt for bringing in next pokemon. Keep current pokemon."); + pbf_mash_button(context, BUTTON_B, 100); + break; + case CallbackEnum::SWAP_MENU: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "run_battle_press_A(): Lead pokemon fainted.", + stream + ); + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "run_battle_press_A: Unknown callback triggered."); + + } + } +} + +void select_top_move(VideoStream& stream, ProControllerContext& context, size_t consecutive_move_select){ + if (consecutive_move_select > 3){ + // to handle case where move is disabled/out of PP/taunted + stream.log("Failed to select a move 3 times. Choosing a different move.", COLOR_RED); + pbf_press_dpad(context, DPAD_DOWN, 20, 40); + } + pbf_mash_button(context, BUTTON_A, 100); + +} + +void clear_tutorial(VideoStream& stream, ProControllerContext& context, uint16_t seconds_timeout){ + bool seen_tutorial = false; + while (true){ + TutorialWatcher tutorial; + context.wait_for_all_requests(); + + int ret = wait_until( + stream, context, + std::chrono::seconds(seconds_timeout), + {tutorial} + ); + context.wait_for(std::chrono::milliseconds(100)); + + switch (ret){ + case 0: + stream.log("clear_tutorial: Detected tutorial screen."); + seen_tutorial = true; + pbf_press_button(context, BUTTON_A, 20, 105); + break; + default: + stream.log("clear_tutorial: Timed out."); + if(!seen_tutorial){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "clear_tutorial(): Tutorial screen never detected.", + stream + ); + } + return; + } + } +} + +void clear_dialog(VideoStream& stream, ProControllerContext& context, + ClearDialogMode mode, uint16_t seconds_timeout, + std::vector enum_optional_callbacks +){ + bool seen_dialog = false; + WallClock start = current_time(); + while (true){ + if (current_time() - start > std::chrono::minutes(3)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "clear_dialog(): Failed to clear dialog after 3 minutes.", + stream + ); + } + + AdvanceDialogWatcher advance_dialog(COLOR_RED); + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + PromptDialogWatcher prompt(COLOR_YELLOW); + WhiteButtonWatcher whitebutton(COLOR_GREEN, WhiteButton::ButtonA_DarkBackground, {0.725, 0.833, 0.024, 0.045}); // {0.650, 0.650, 0.140, 0.240} + DialogArrowWatcher dialog_arrow(COLOR_RED, stream.overlay(), {0.850, 0.820, 0.020, 0.050}, 0.8365, 0.846); + NormalBattleMenuWatcher battle(COLOR_ORANGE); + TutorialWatcher tutorial(COLOR_BLUE); + DialogBoxWatcher black_dialog_box(COLOR_BLACK, true, std::chrono::milliseconds(250), DialogType::DIALOG_BLACK); + context.wait_for_all_requests(); + + std::vector callbacks; + std::vector enum_all_callbacks{CallbackEnum::ADVANCE_DIALOG}; // mandatory callbacks + enum_all_callbacks.insert(enum_all_callbacks.end(), enum_optional_callbacks.begin(), enum_optional_callbacks.end()); // append the mandatory and optional callback vectors together + for (const CallbackEnum& enum_callback : enum_all_callbacks){ + switch(enum_callback){ + case CallbackEnum::ADVANCE_DIALOG: + callbacks.emplace_back(advance_dialog); + break; + case CallbackEnum::OVERWORLD: + callbacks.emplace_back(overworld); + break; + case CallbackEnum::PROMPT_DIALOG: + callbacks.emplace_back(prompt); + break; + case CallbackEnum::WHITE_A_BUTTON: + callbacks.emplace_back(whitebutton); + break; + case CallbackEnum::DIALOG_ARROW: + callbacks.emplace_back(dialog_arrow); + break; + case CallbackEnum::BATTLE: + callbacks.emplace_back(battle); + break; + case CallbackEnum::TUTORIAL: + callbacks.emplace_back(tutorial); + break; + case CallbackEnum::BLACK_DIALOG_BOX: + callbacks.emplace_back(black_dialog_box); + break; + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "clear_dialog: Unknown callback requested."); + } + } + + + int ret = wait_until( + stream, context, + std::chrono::seconds(seconds_timeout), + callbacks + ); + // int ret = run_until( + // console, context, + // [&](ProControllerContext& context){ + // for (size_t j = 0; j < seconds_timeout/3; j++){ + // pbf_press_button(context, BUTTON_A, 20, 3*TICKS_PER_SECOND-20); + // } + // }, + // {overworld, prompt, whitebutton, advance_dialog, battle} + // ); + context.wait_for(std::chrono::milliseconds(100)); + if (ret < 0){ + stream.log("clear_dialog(): Timed out."); + if (seen_dialog && mode == ClearDialogMode::STOP_TIMEOUT){ + return; + } + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "clear_dialog(): Timed out. Did not detect dialog or did not detect the expected stop condition.", + stream + ); + } + + CallbackEnum enum_callback = enum_all_callbacks[ret]; + switch(enum_callback){ + case CallbackEnum::ADVANCE_DIALOG: + stream.log("clear_dialog: Detected advance dialog."); + seen_dialog = true; + pbf_press_button(context, BUTTON_A, 20, 105); + break; + case CallbackEnum::OVERWORLD: + stream.log("clear_dialog: Detected overworld."); + if (seen_dialog && mode == ClearDialogMode::STOP_OVERWORLD){ + return; + } + break; + case CallbackEnum::PROMPT_DIALOG: + stream.log("clear_dialog: Detected prompt."); + seen_dialog = true; + if (mode == ClearDialogMode::STOP_PROMPT){ + return; + } + pbf_press_button(context, BUTTON_A, 20, 105); + break; + case CallbackEnum::WHITE_A_BUTTON: + stream.log("clear_dialog: Detected white A button."); + seen_dialog = true; + if (mode == ClearDialogMode::STOP_WHITEBUTTON){ + return; + } + pbf_press_button(context, BUTTON_A, 20, 105); + break; + case CallbackEnum::DIALOG_ARROW: + stream.log("clear_dialog: Detected dialog arrow."); + seen_dialog = true; + pbf_press_button(context, BUTTON_A, 20, 105); + break; + case CallbackEnum::BATTLE: + stream.log("clear_dialog: Detected battle."); + if (mode == ClearDialogMode::STOP_BATTLE){ + return; + } + break; + case CallbackEnum::TUTORIAL: + stream.log("clear_dialog: Detected tutorial."); + pbf_press_button(context, BUTTON_A, 20, 105); + break; + case CallbackEnum::BLACK_DIALOG_BOX: + stream.log("clear_dialog: Detected black dialog box."); + seen_dialog = true; + pbf_press_button(context, BUTTON_A, 20, 105); + break; + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "clear_dialog: Unknown callback triggered."); + + } + + } +} + +bool confirm_marker_present( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context +){ + while (true){ + DestinationMarkerWatcher marker(COLOR_RED, {0.815, 0.645, 0.180, 0.320}, true); + NormalBattleMenuWatcher battle(COLOR_BLUE); + + int ret = wait_until( + stream, context, + std::chrono::seconds(5), + {marker, battle} + ); + switch (ret){ + case 0: // marker + stream.log("Confirmed that marker is still present."); + return true; + case 1: // battle + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "confirm_marker_present(): Unexpectedly detected battle.", + stream + ); + default: + stream.log("Destination marker not detected."); + return false; + } + } + +} + +void overworld_navigation( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + NavigationStopCondition stop_condition, + NavigationMovementMode movement_mode, + uint8_t x, uint8_t y, + uint16_t seconds_timeout, uint16_t seconds_realign, + bool auto_heal, + bool detect_wipeout +){ + bool should_realign = true; + if (seconds_timeout <= seconds_realign){ + seconds_realign = seconds_timeout; + should_realign = false; + } + uint16_t forward_ticks = seconds_realign * TICKS_PER_SECOND; + // WallClock start = current_time(); + + if (stop_condition == NavigationStopCondition::STOP_MARKER){ + context.wait_for(Milliseconds(2000)); // the "Destination arrived" notification can sometimes reappear if you opened the map too quickly after you reached the previous marker. + } + + + while (true){ + NormalBattleMenuWatcher battle(COLOR_BLUE); + DialogBoxWatcher dialog(COLOR_RED, true); + DestinationMarkerWatcher marker(COLOR_CYAN, {0.717, 0.165, 0.03, 0.061}); + context.wait_for_all_requests(); + std::vector callbacks = {battle, dialog}; + if (stop_condition == NavigationStopCondition::STOP_MARKER){ + callbacks.emplace_back(marker); + } + // uint16_t ticks_passed = std::chrono::duration_cast(current_time() - start).count() * TICKS_PER_SECOND / 1000; + // forward_ticks = seconds_realign * TICKS_PER_SECOND - ticks_passed; + + int ret = run_until( + stream, context, + [&](ProControllerContext& context){ + + for (int i = 0; i < seconds_timeout / seconds_realign; i++){ + if (movement_mode == NavigationMovementMode::CLEAR_WITH_LETS_GO){ + walk_forward_while_clear_front_path(info, stream, context, forward_ticks, y); + }else{ + ssf_press_left_joystick(context, x, y, 0, seconds_realign * TICKS_PER_SECOND); + if (movement_mode == NavigationMovementMode::DIRECTIONAL_ONLY){ + pbf_wait(context, seconds_realign * TICKS_PER_SECOND); + } else if (movement_mode == NavigationMovementMode::DIRECTIONAL_SPAM_A){ + for (size_t j = 0; j < seconds_realign; j++){ + pbf_press_button(context, BUTTON_A, 20, 105); + } + } + } + context.wait_for_all_requests(); + if (should_realign){ + try { + realign_player(info, stream, context, PlayerRealignMode::REALIGN_OLD_MARKER); + + }catch (UnexpectedBattleException&){ + pbf_wait(context, 30 * TICKS_PER_SECOND); // catch exception to allow the battle callback to take over. + } + + } + } + }, + callbacks + ); + context.wait_for(std::chrono::milliseconds(100)); + + switch (ret){ + case 0: // battle + stream.log("overworld_navigation: Detected start of battle."); + if (stop_condition == NavigationStopCondition::STOP_BATTLE){ + return; + } + + run_battle_press_A(stream, context, BattleStopCondition::STOP_OVERWORLD, {}, detect_wipeout); + if (auto_heal){ + auto_heal_from_menu_or_overworld(info, stream, context, 0, true); + } + context.wait_for_all_requests(); + try { + realign_player(info, stream, context, PlayerRealignMode::REALIGN_OLD_MARKER); + if (stop_condition == NavigationStopCondition::STOP_MARKER && !confirm_marker_present(info, stream, context)){ + // if marker not present when using marker based navigation, don't keep walking forward. + return; + } + + break; + }catch (UnexpectedBattleException&){ + break; + } + case 1: // dialog + stream.log("overworld_navigation: Detected dialog."); + if (stop_condition == NavigationStopCondition::STOP_DIALOG){ + return; + } + if (stop_condition == NavigationStopCondition::STOP_MARKER){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "overworld_navigation(): Unexpectedly detected dialog.", + stream + ); + } + pbf_press_button(context, BUTTON_A, 20, 20); + break; + case 2: // marker + stream.log("overworld_navigation: Detected marker."); + if (stop_condition == NavigationStopCondition::STOP_MARKER){ + return; + } + break; + default: + stream.log("overworld_navigation(): Timed out."); + if (stop_condition == NavigationStopCondition::STOP_TIME){ + return; + } + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "overworld_navigation(): Timed out. Did not detect expected stop condition.", + stream + ); + } + } +} + +void config_option(ProControllerContext& context, int change_option_value){ + for (int i = 0; i < change_option_value; i++){ + pbf_press_dpad(context, DPAD_RIGHT, 15, 20); + } + pbf_press_dpad(context, DPAD_DOWN, 15, 20); +} + +void swap_starter_moves(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, Language language){ + WallClock start = current_time(); + while (true){ + if (current_time() - start > std::chrono::minutes(3)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "swap_starter_moves(): Failed to swap the starter moves after 3 minutes.", + stream + ); + } + // start in the overworld + press_Bs_to_back_to_overworld(info, stream, context); + + // open menu, select your starter + enter_menu_from_overworld(info, stream, context, 0, MenuSide::LEFT); + + // enter Pokemon summary screen + pbf_press_button(context, BUTTON_A, 20, 5 * TICKS_PER_SECOND); + pbf_press_dpad(context, DPAD_RIGHT, 15, 1 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_Y, 20, 40); + + // select move 1 + pbf_press_button(context, BUTTON_A, 20, 40); + pbf_press_dpad(context, DPAD_DOWN, 15, 40); + pbf_press_dpad(context, DPAD_DOWN, 15, 40); + // extra button presses to avoid drops + pbf_press_dpad(context, DPAD_DOWN, 15, 40); + pbf_press_dpad(context, DPAD_DOWN, 15, 40); + + // select move 3. swap move 1 and move 3. + pbf_press_button(context, BUTTON_A, 20, 40); + + // confirm that Ember/Leafage/Water Gun is in slot 1 + context.wait_for_all_requests(); + VideoSnapshot screen = stream.video().snapshot(); + PokemonMovesReader reader(language); + std::string top_move = reader.read_move(stream.logger(), screen, 0); + stream.log("Current top move: " + top_move); + if (top_move != "ember" && top_move != "leafage" && top_move != "water-gun"){ + stream.log("Failed to swap moves. Re-try."); + continue; + } + + + break; + } + +} + + +void change_settings_prior_to_autostory( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + size_t current_segment_num, + Language language +){ + + // get index of `Options` in the Main Menu, which depends on where you are in Autostory + int8_t options_index; + switch(current_segment_num){ + case 0: + return; // can't change settings in the intro cutscene + case 1: + // after Intro cutscene done, in room + // Menu + // - Options + // - Save + options_index = 0; + break; + case 2: + // Menu + // - Bag --> unlocked after picked up bag/hat in room. Segment 01, checkpoint 02 + // - Options + // - Save + options_index = 1; + break; + case 3: + case 4: + case 5: + case 6: + // Menu + // - Bag + // - Boxes --> unlocked after battling Nemona and receiving Pokedex app. Segment 02, checkpoint 04 + // - Options + // - Save + options_index = 2; + break; + case 7: + case 8: + case 9: + // Menu + // - Bag + // - Boxes + // - Poke Portal --> unlocked after arriving at Los Platos and talking to Nemona. Segment 06, checkpoint 11 + // - Options + // - Save + options_index = 3; + break; + default: + // Menu + // - Bag + // - Boxes + // - Picnic --> unlocked after finishing tutorial. Segment 09, checkpoint 20 + // - Poke Portal + // - Options + // - Save + options_index = 4; + break; + } + + bool has_minimap = current_segment_num >= 2; // the minimap only shows up in segment 2 and beyond + + enter_menu_from_overworld(env.program_info(), env.console, context, options_index, MenuSide::RIGHT, has_minimap); + change_settings(env, context, language); + if(!has_minimap){ + pbf_mash_button(context, BUTTON_B, 2 * TICKS_PER_SECOND); + }else{ + press_Bs_to_back_to_overworld(env.program_info(), env.console, context); + } +} + + +void change_settings(SingleSwitchProgramEnvironment& env, ProControllerContext& context, Language language, bool use_inference){ + env.console.log("Update settings."); + if (use_inference){ + MenuOption session(env.console, context, language); + + std::vector>> options = { + {MenuOptionItemEnum::TEXT_SPEED, {MenuOptionToggleEnum::FAST}}, + {MenuOptionItemEnum::SKIP_MOVE_LEARNING, {MenuOptionToggleEnum::ON}}, + {MenuOptionItemEnum::SEND_TO_BOXES, {MenuOptionToggleEnum::AUTOMATIC, MenuOptionToggleEnum::ON}}, + {MenuOptionItemEnum::GIVE_NICKNAMES, {MenuOptionToggleEnum::OFF}}, + {MenuOptionItemEnum::VERTICAL_CAMERA_CONTROLS, {MenuOptionToggleEnum::REGULAR, MenuOptionToggleEnum::NORMAL}}, + {MenuOptionItemEnum::HORIZONTAL_CAMERA_CONTROLS, {MenuOptionToggleEnum::REGULAR, MenuOptionToggleEnum::NORMAL}}, + {MenuOptionItemEnum::CAMERA_SUPPORT, {MenuOptionToggleEnum::OFF}}, + {MenuOptionItemEnum::CAMERA_INTERPOLATION, {MenuOptionToggleEnum::NORMAL, MenuOptionToggleEnum::AVERAGE}}, + {MenuOptionItemEnum::CAMERA_DISTANCE, {MenuOptionToggleEnum::CLOSE}}, + {MenuOptionItemEnum::AUTOSAVE, {MenuOptionToggleEnum::OFF}}, + {MenuOptionItemEnum::SHOW_NICKNAMES, {MenuOptionToggleEnum::OFF, MenuOptionToggleEnum::DONT_SHOW}}, + {MenuOptionItemEnum::SKIP_CUTSCENES, {MenuOptionToggleEnum::ON}}, + {MenuOptionItemEnum::CONTROLLER_RUMBLE, {MenuOptionToggleEnum::ON}}, + {MenuOptionItemEnum::HELPING_FUNCTIONS, {MenuOptionToggleEnum::OFF}}, + + }; + session.set_options(options); + }else{ + config_option(context, 1); // Text Speed: Fast + config_option(context, 1); // Skip Move Learning: On + config_option(context, 1); // Send to Boxes: Automatic + config_option(context, 1); // Give Nicknames: Off + config_option(context, 0); // Vertical Camera Controls: Regular + config_option(context, 0); // Horiztontal Camera Controls: Regular + config_option(context, 1); // Camera Support: Off + config_option(context, 0); // Camera Interpolation: Normal + config_option(context, 0); // Camera Distance: Close + config_option(context, 1); // Autosave: Off + config_option(context, 1); // Show Nicknames: Don't show + config_option(context, 1); // Skip Cutscenes: On + config_option(context, 0); // Background Music: 10 + config_option(context, 0); // Sound Effects: 10 + config_option(context, 0); // Pokemon Cries: 10 + config_option(context, 0); // Controller Rumble: On + config_option(context, 1); // Helping Functions: Off + } + + pbf_mash_button(context, BUTTON_A, 1 * TICKS_PER_SECOND); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 5, {CallbackEnum::PROMPT_DIALOG}); + +} + +void do_action_and_monitor_for_battles( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + std::function< + void(const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context) + >&& action +){ + NormalBattleMenuWatcher battle_menu(COLOR_RED); + int ret = run_until( + stream, context, + [&](ProControllerContext& context){ + context.wait_for_all_requests(); + action(info, stream, context); + }, + {battle_menu} + ); + if (ret == 0){ // battle detected + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "do_action_and_monitor_for_battles(): Detected battle. Failed to complete action.", + stream + ); + + } +} + + +void handle_unexpected_battles( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + std::function< + void(const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context) + >&& action +){ + while (true){ + try { + context.wait_for_all_requests(); + action(info, stream, context); + return; + }catch (UnexpectedBattleException&){ + run_battle_press_A(stream, context, BattleStopCondition::STOP_OVERWORLD); + } + } +} + +void handle_when_stationary_in_overworld( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + std::function< + void(const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context) + >&& action, + std::function< + void(const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context) + >&& recovery_action, + size_t seconds_stationary, + uint16_t minutes_timeout, + size_t max_failures +){ + + WallClock start = current_time(); + size_t num_failures = 0; + while (true){ + if (current_time() - start > std::chrono::minutes(minutes_timeout)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "handle_when_stationary_in_overworld(): Failed to complete action after " + std::to_string(minutes_timeout) + " minutes.", + stream + ); + } + StationaryOverworldWatcher stationary_overworld(COLOR_RED, {0.865, 0.825, 0.08, 0.1}, seconds_stationary); + + int ret = run_until( + stream, context, + [&](ProControllerContext& context){ + context.wait_for_all_requests(); + action(info, stream, context); + }, + {stationary_overworld} + ); + if (ret < 0){ + // successfully completed action without being stuck in a position where the overworld is stationary. + return; + }else if (ret == 0){ + // if stationary in overworld, run recovery action then try action again + stream.log("Detected stationary overworld."); + num_failures++; + if (num_failures > max_failures){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "handle_when_stationary_in_overworld(): Failed to complete action within " + std::to_string(max_failures) + " attempts.", + stream + ); + } + context.wait_for_all_requests(); + recovery_action(info, stream, context); + } + } +} + + +void handle_failed_action( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + std::function< + void(const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context) + >&& action, + std::function< + void(const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context) + >&& recovery_action, + size_t max_failures +){ + size_t num_failures = 0; + while (true){ + try { + context.wait_for_all_requests(); + action(info, stream, context); + return; + }catch (OperationFailedException& e){ + num_failures++; + if (num_failures > max_failures){ + throw e; + } + recovery_action(info, stream, context); + } + } +} + + +void wait_for_gradient_arrow( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + ImageFloatBox box_area_to_check, + uint16_t seconds_timeout +){ + context.wait_for_all_requests(); + GradientArrowWatcher arrow(COLOR_RED, GradientArrowType::RIGHT, box_area_to_check); + int ret = wait_until( + stream, context, + Milliseconds(seconds_timeout * 1000), + { arrow } + ); + if (ret == 0){ + stream.log("Gradient arrow detected."); + }else{ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to detect gradient arrow.", + stream + ); + } +} + +void wait_for_overworld( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + uint16_t seconds_timeout +){ + context.wait_for_all_requests(); + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + int ret = wait_until( + stream, context, + Milliseconds(seconds_timeout * 1000), + { overworld } + ); + if (ret == 0){ + stream.log("Overworld detected."); + }else{ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to detect overworld.", + stream + ); + } + +} + +void press_A_until_dialog( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + uint16_t seconds_between_button_presses +){ + context.wait_for_all_requests(); + AdvanceDialogWatcher advance_dialog(COLOR_RED); + int ret = run_until( + stream, context, + [seconds_between_button_presses](ProControllerContext& context){ + pbf_wait(context, seconds_between_button_presses * TICKS_PER_SECOND); // avoiding pressing A if dialog already present + for (size_t c = 0; c < 10; c++){ + pbf_press_button(context, BUTTON_A, 20, seconds_between_button_presses * TICKS_PER_SECOND); + } + }, + {advance_dialog} + ); + if (ret == 0){ + stream.log("press_A_until_dialog: Detected dialog."); + }else{ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "press_A_until_dialog(): Unable to detect dialog after 10 button presses.", + stream + ); + } +} + +bool is_ride_active(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + while (true){ + try { + // open main menu + enter_menu_from_overworld(info, stream, context, -1, MenuSide::NONE, true); + context.wait_for_all_requests(); + ImageStats ride_indicator = image_stats( + extract_box_reference( + stream.video().snapshot(), + ImageFloatBox(0.05, 0.995, 0.25, 0.003) + ) + ); + + bool is_ride_active = !is_black(ride_indicator); // ride is active if the ride indicator isn't black. + pbf_press_button(context, BUTTON_B, 30, 100); + press_Bs_to_back_to_overworld(info, stream, context, 7); + if (is_ride_active){ + stream.log("Ride is active."); + }else{ + stream.log("Ride is not active."); + } + return is_ride_active; + + }catch(UnexpectedBattleException&){ + run_battle_press_A(stream, context, BattleStopCondition::STOP_OVERWORLD); + } + } + +} + +void get_on_ride(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + get_on_or_off_ride(info, stream, context, true); +} + +void get_off_ride(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + get_on_or_off_ride(info, stream, context, false); +} + +void get_on_or_off_ride(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, bool get_on){ + pbf_press_button(context, BUTTON_PLUS, 20, 20); + + WallClock start = current_time(); + while (get_on != is_ride_active(info, stream, context)){ + if (current_time() - start > std::chrono::minutes(3)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "get_on_or_off_ride(): Failed to get on/off ride after 3 minutes.", + stream + ); + } + pbf_press_button(context, BUTTON_PLUS, 30, 100); + } +} + +void checkpoint_save(SingleSwitchProgramEnvironment& env, ProControllerContext& context, EventNotificationOption& notif_status_update){ + AutoStoryStats& stats = env.current_stats(); + save_game_from_overworld(env.program_info(), env.console, context); + stats.m_checkpoint++; + env.update_stats(); + send_program_status_notification(env, notif_status_update, "Saved at checkpoint."); +} + + +void realign_player_from_landmark( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + MoveCursor move_cursor_near_landmark, + MoveCursor move_cursor_to_target +){ + + stream.log("Realigning player direction, using a landmark..."); + WallClock start = current_time(); + + while (true){ + if (current_time() - start > std::chrono::minutes(5)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "realign_player_from_landmark(): Failed to realign player after 5 minutes.", + stream + ); + } + + try { + open_map_from_overworld(info, stream, context, false); + + // move cursor near landmark (pokecenter) + switch(move_cursor_near_landmark.zoom_change){ + case ZoomChange::ZOOM_IN: + pbf_press_button(context, BUTTON_ZR, 20, 105); + break; + case ZoomChange::ZOOM_IN_TWICE: + pbf_press_button(context, BUTTON_ZR, 20, 105); + pbf_press_button(context, BUTTON_ZR, 20, 105); + break; + case ZoomChange::ZOOM_OUT: + pbf_press_button(context, BUTTON_ZL, 20, 105); + break; + case ZoomChange::ZOOM_OUT_TWICE: + pbf_press_button(context, BUTTON_ZL, 20, 105); + pbf_press_button(context, BUTTON_ZL, 20, 105); + break; + case ZoomChange::KEEP_ZOOM: + break; + } + uint8_t move_x1 = move_cursor_near_landmark.move_x; + uint8_t move_y1 = move_cursor_near_landmark.move_y; + uint16_t move_duration1 = move_cursor_near_landmark.move_duration; + pbf_move_left_joystick(context, move_x1, move_y1, move_duration1, 1 * TICKS_PER_SECOND); + + // move cursor to pokecenter + if (!detect_closest_pokecenter_and_move_map_cursor_there(info, stream, context, 0.29)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "realign_player_from_landmark(): No visible pokecenter found on map.", + stream + ); + } + + confirm_cursor_centered_on_pokecenter(info, stream, context); // throws exception if fails + + // move cursor from landmark to target + switch(move_cursor_to_target.zoom_change){ + case ZoomChange::ZOOM_IN: + pbf_press_button(context, BUTTON_ZR, 20, 105); + break; + case ZoomChange::ZOOM_IN_TWICE: + pbf_press_button(context, BUTTON_ZR, 20, 105); + pbf_press_button(context, BUTTON_ZR, 20, 105); + break; + case ZoomChange::ZOOM_OUT: + pbf_press_button(context, BUTTON_ZL, 20, 105); + break; + case ZoomChange::ZOOM_OUT_TWICE: + pbf_press_button(context, BUTTON_ZL, 20, 105); + pbf_press_button(context, BUTTON_ZL, 20, 105); + break; + case ZoomChange::KEEP_ZOOM: + break; + } + uint8_t move_x2 = move_cursor_to_target.move_x; + uint8_t move_y2 = move_cursor_to_target.move_y; + uint16_t move_duration2 = move_cursor_to_target.move_duration; + pbf_move_left_joystick(context, move_x2, move_y2, move_duration2, 1 * TICKS_PER_SECOND); + + // place down marker + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_A, 20, 105); + leave_phone_to_overworld(info, stream, context); + + return; + + }catch (OperationFailedException&){ + // reset to overworld if failed to center on the pokecenter, and re-try + leave_phone_to_overworld(info, stream, context); + }catch (UnexpectedBattleException&){ + run_battle_press_A(stream, context, BattleStopCondition::STOP_OVERWORLD); + } + } + + +} + + +void confirm_cursor_centered_on_pokecenter(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + context.wait_for_all_requests(); + context.wait_for(Milliseconds(500)); + ImageFloatBox center_cursor{0.484, 0.472, 0.030, 0.053}; + MapPokeCenterIconDetector pokecenter(COLOR_RED, center_cursor); + if (!pokecenter.detect(stream.video().snapshot())){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "confirm_cursor_centered_on_pokecenter(): Cursor is not centered on a pokecenter.", + stream + ); + } + + stream.log("Confirmed that the cursor is centered on a pokecenter."); +} + +void move_cursor_towards_flypoint_and_go_there( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + MoveCursor move_cursor_near_flypoint +){ + WallClock start = current_time(); + + while (true){ + if (current_time() - start > std::chrono::minutes(5)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "move_cursor_towards_flypoint_and_go_there(): Failed to fly after 5 minutes.", + stream + ); + } + + try { + open_map_from_overworld(info, stream, context, false); + + // move cursor near landmark (pokecenter) + switch(move_cursor_near_flypoint.zoom_change){ + case ZoomChange::ZOOM_IN: + pbf_press_button(context, BUTTON_ZR, 20, 105); + break; + case ZoomChange::ZOOM_IN_TWICE: + pbf_press_button(context, BUTTON_ZR, 20, 105); + pbf_press_button(context, BUTTON_ZR, 20, 105); + break; + case ZoomChange::ZOOM_OUT: + pbf_press_button(context, BUTTON_ZL, 20, 105); + break; + case ZoomChange::ZOOM_OUT_TWICE: + pbf_press_button(context, BUTTON_ZL, 20, 105); + pbf_press_button(context, BUTTON_ZL, 20, 105); + break; + case ZoomChange::KEEP_ZOOM: + break; + } + uint8_t move_x1 = move_cursor_near_flypoint.move_x; + uint8_t move_y1 = move_cursor_near_flypoint.move_y; + uint16_t move_duration1 = move_cursor_near_flypoint.move_duration; + pbf_move_left_joystick(context, move_x1, move_y1, move_duration1, 1 * TICKS_PER_SECOND); + + if (!fly_to_visible_closest_pokecenter_cur_zoom_level(info, stream, context)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "move_cursor_towards_flypoint_and_go_there(): No visible pokecenter found on map.", + stream + ); + } + + return; + + }catch (OperationFailedException&){ + // reset to overworld if failed to center on the pokecenter, and re-try + leave_phone_to_overworld(info, stream, context); + }catch (UnexpectedBattleException&){ + run_battle_press_A(stream, context, BattleStopCondition::STOP_OVERWORLD); + } + } + + +} + + + +void check_num_sunflora_found(SingleSwitchProgramEnvironment& env, ProControllerContext& context, int expected_number){ + context.wait_for_all_requests(); + VideoSnapshot screen = env.console.video().snapshot(); + ImageFloatBox num_sunflora_box = {0.27, 0.02, 0.04, 0.055}; + int number = OCR::read_number_waterfill(env.console, extract_box_reference(screen, num_sunflora_box), 0xff000000, 0xff808080); + + if (number != expected_number){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "The number of sunflora found is different than expected.", + env.console + ); + }else{ + env.console.log("Number of sunflora found: " + std::to_string(number)); + } + + +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h index 644c10d2b0..6bdb72dfc3 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h @@ -1,329 +1,329 @@ -/* AutostoryTools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStoryTools_H -#define PokemonAutomation_PokemonSV_AutoStoryTools_H - -#include -#include "CommonFramework/Language.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -// #include "PokemonSV/Programs/PokemonSV_Navigation.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -struct AutoStoryStats : public StatsTracker{ - AutoStoryStats() - : m_checkpoint(m_stats["Checkpoint"]) - , m_segment(m_stats["Segment"]) - , m_reset(m_stats["Reset"]) - { - m_display_order.emplace_back("Checkpoint"); - m_display_order.emplace_back("Segment"); - m_display_order.emplace_back("Reset"); - } - std::atomic& m_checkpoint; - std::atomic& m_segment; - std::atomic& m_reset; -}; - - -enum class BattleStopCondition{ - STOP_OVERWORLD, - STOP_DIALOG, -}; - -enum class ClearDialogMode{ - STOP_OVERWORLD, - STOP_PROMPT, - STOP_WHITEBUTTON, - STOP_TIMEOUT, - STOP_BATTLE, -}; - - -enum class CallbackEnum{ - ADVANCE_DIALOG, - OVERWORLD, - PROMPT_DIALOG, - WHITE_A_BUTTON, - DIALOG_ARROW, - BATTLE, - TUTORIAL, - BLACK_DIALOG_BOX, - GRADIENT_ARROW, - SWAP_MENU, - MOVE_SELECT, -}; - -enum class StartPoint{ - INTRO_CUTSCENE, - PICK_STARTER, - NEMONA_FIRST_BATTLE, - CATCH_TUTORIAL, - LEGENDARY_RESCUE, - ARVEN_FIRST_BATTLE, - LOS_PLATOS, - MESAGOZA_SOUTH, -}; - -enum class StarterChoice{ - SPRIGATITO, - FUECOCO, - QUAXLY, -}; - -enum class PlayerRealignMode{ - REALIGN_NEW_MARKER, - REALIGN_OLD_MARKER, - REALIGN_NO_MARKER, -}; - -enum class NavigationStopCondition{ - STOP_DIALOG, - STOP_MARKER, - STOP_TIME, - STOP_BATTLE, -}; - -enum class NavigationMovementMode{ - DIRECTIONAL_ONLY, - DIRECTIONAL_SPAM_A, - CLEAR_WITH_LETS_GO, -}; - -struct AutoStoryOptions{ - Language language; - StarterChoice starter_choice; - EventNotificationOption& notif_status_update; -}; - -class AutoStory_Segment { -public: - virtual ~AutoStory_Segment() = default; - virtual std::string name() const = 0; - virtual std::string start_text() const = 0; - virtual std::string end_text() const = 0; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options) const = 0; -}; - -// spam A button to choose the first move -// throw exception if wipeout. -void run_battle_press_A( - VideoStream& stream, - ProControllerContext& context, - BattleStopCondition stop_condition, - std::vector optional_callbacks = {}, - bool detect_wipeout = false -); - -void select_top_move(VideoStream& stream, ProControllerContext& context, size_t consecutive_move_select); - -// press A to clear tutorial screens -// throw exception if tutorial screen never detected -void clear_tutorial(VideoStream& stream, ProControllerContext& context, uint16_t seconds_timeout = 5); - -// spam the A button to clear dialog. -// stop depending on ClearDialogMode: stop when detect overworld, or dialog prompt, or A button prompt. Or if times out -// throw exception if times out, unless this is the intended stop condition. -// also throw exception if dialog is never detected. -void clear_dialog(VideoStream& stream, ProControllerContext& context, - ClearDialogMode mode, uint16_t seconds_timeout = 60, - std::vector optional_callbacks = {} -); - - -// return true if the destination marker is present within the minimap area -bool confirm_marker_present( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context -); - -// move character with ssf left joystick, as per given x, y, until -// stop_condition is met (e.g. Dialog detected). -// throw exception if reaches timeout before detecting stop condition -void overworld_navigation(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - NavigationStopCondition stop_condition, - NavigationMovementMode movement_mode, - uint8_t x, uint8_t y, - uint16_t seconds_timeout = 60, uint16_t seconds_realign = 60, - bool auto_heal = false, - bool detect_wipeout = false -); - -void config_option(ProControllerContext& context, int change_option_value); - -// enter menu and swap the first and third moves for your starter -void swap_starter_moves(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, Language language); - -// run the given `action`. if detect a battle, stop the action, and throw exception -void do_action_and_monitor_for_battles( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - std::function< - void(const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context) - >&& action -); - -// catch any UnexpectedBattle exceptions from `action`. then use run_battle_press_A until overworld, and re-try the `action`. -void handle_unexpected_battles( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - std::function< - void(const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context) - >&& action -); - -// if stationary in overworld for an amount of time (seconds_stationary), run `recovery_action` then try `action` again -// return once successfully completed `action` -// throw exception if fails to complete `action` within a certain amount of time (minutes_timeout). -// NOTE: if using this function to wrap overworld_navigation(), keep in mind that -// confirm_marker_present() will keep the player still for 5 seconds before moving. Therefore, seconds_stationary should be greater than 5 seconds in this case. -void handle_when_stationary_in_overworld( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - std::function< - void(const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context) - >&& action, - std::function< - void(const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context) - >&& recovery_action, - size_t seconds_stationary = 6, - uint16_t minutes_timeout = 5, - size_t max_attempts = 2 -); - -// do action. if error is thrown, catch the error and try the recovery action -void handle_failed_action( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - std::function< - void(const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context) - >&& action, - std::function< - void(const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context) - >&& recovery_action, - size_t max_failures -); - -void wait_for_gradient_arrow( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - ImageFloatBox box_area_to_check, - uint16_t seconds_timeout -); - -void wait_for_overworld( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - uint16_t seconds_timeout = 30 -); - -void press_A_until_dialog( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - uint16_t seconds_between_button_presses -); - -// return true if ride is active. i.e. if you are on your ride -bool is_ride_active(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -void get_on_ride(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -void get_off_ride(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -void get_on_or_off_ride(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, bool get_on); - - -// change the settings prior to Autostory -// Assumes that `current_segment` represents where we currently are in the story. -void change_settings_prior_to_autostory( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - size_t current_segment_num, - Language language -); - -// from within the Settings/Options menu, change the settings -void change_settings(SingleSwitchProgramEnvironment& env, ProControllerContext& context, Language language, bool use_inference = true); - - -void checkpoint_save(SingleSwitchProgramEnvironment& env, ProControllerContext& context, EventNotificationOption& notif_status_update); - -enum class ZoomChange{ - ZOOM_IN, - ZOOM_IN_TWICE, - ZOOM_OUT, - ZOOM_OUT_TWICE, - KEEP_ZOOM, -}; - -struct MoveCursor{ - ZoomChange zoom_change; - uint8_t move_x; - uint8_t move_y; - uint16_t move_duration; -}; - -// place a marker on the map, not relative to the current player position, but based on a fixed landmark, such as a pokecenter -// How this works: -// - cursor is moved to a point near the landmark, as per `move_cursor_near_landmark` -// - move the cursor onto the landmark using `detect_closest_pokecenter_and_move_map_cursor_there`. -// - confirm that the pokecenter is centered within cursor. If not, close map app, and re-try. -// - cursor is moved to target location, as per `move_cursor_to_target`. A marker is placed down here. -void realign_player_from_landmark( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - MoveCursor move_cursor_near_landmark, - MoveCursor move_cursor_to_target -); - -// confirm that the cursor is centered on the pokecenter, within the map app -// else throw exception -void confirm_cursor_centered_on_pokecenter(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// open map, then move cursor to a point near a flypoint as per `move_cursor_near_flypoint` -// then fly to the closest pokecenter near the cursor -void move_cursor_towards_flypoint_and_go_there( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - MoveCursor move_cursor_near_flypoint -); - - -void check_num_sunflora_found(SingleSwitchProgramEnvironment& env, ProControllerContext& context, int expected_number); - -} -} -} -#endif +/* AutostoryTools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStoryTools_H +#define PokemonAutomation_PokemonSV_AutoStoryTools_H + +#include +#include "CommonFramework/Language.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +// #include "PokemonSV/Programs/PokemonSV_Navigation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +struct AutoStoryStats : public StatsTracker{ + AutoStoryStats() + : m_checkpoint(m_stats["Checkpoint"]) + , m_segment(m_stats["Segment"]) + , m_reset(m_stats["Reset"]) + { + m_display_order.emplace_back("Checkpoint"); + m_display_order.emplace_back("Segment"); + m_display_order.emplace_back("Reset"); + } + std::atomic& m_checkpoint; + std::atomic& m_segment; + std::atomic& m_reset; +}; + + +enum class BattleStopCondition{ + STOP_OVERWORLD, + STOP_DIALOG, +}; + +enum class ClearDialogMode{ + STOP_OVERWORLD, + STOP_PROMPT, + STOP_WHITEBUTTON, + STOP_TIMEOUT, + STOP_BATTLE, +}; + + +enum class CallbackEnum{ + ADVANCE_DIALOG, + OVERWORLD, + PROMPT_DIALOG, + WHITE_A_BUTTON, + DIALOG_ARROW, + BATTLE, + TUTORIAL, + BLACK_DIALOG_BOX, + GRADIENT_ARROW, + SWAP_MENU, + MOVE_SELECT, +}; + +enum class StartPoint{ + INTRO_CUTSCENE, + PICK_STARTER, + NEMONA_FIRST_BATTLE, + CATCH_TUTORIAL, + LEGENDARY_RESCUE, + ARVEN_FIRST_BATTLE, + LOS_PLATOS, + MESAGOZA_SOUTH, +}; + +enum class StarterChoice{ + SPRIGATITO, + FUECOCO, + QUAXLY, +}; + +enum class PlayerRealignMode{ + REALIGN_NEW_MARKER, + REALIGN_OLD_MARKER, + REALIGN_NO_MARKER, +}; + +enum class NavigationStopCondition{ + STOP_DIALOG, + STOP_MARKER, + STOP_TIME, + STOP_BATTLE, +}; + +enum class NavigationMovementMode{ + DIRECTIONAL_ONLY, + DIRECTIONAL_SPAM_A, + CLEAR_WITH_LETS_GO, +}; + +struct AutoStoryOptions{ + Language language; + StarterChoice starter_choice; + EventNotificationOption& notif_status_update; +}; + +class AutoStory_Segment { +public: + virtual ~AutoStory_Segment() = default; + virtual std::string name() const = 0; + virtual std::string start_text() const = 0; + virtual std::string end_text() const = 0; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options) const = 0; +}; + +// spam A button to choose the first move +// throw exception if wipeout. +void run_battle_press_A( + VideoStream& stream, + ProControllerContext& context, + BattleStopCondition stop_condition, + std::vector optional_callbacks = {}, + bool detect_wipeout = false +); + +void select_top_move(VideoStream& stream, ProControllerContext& context, size_t consecutive_move_select); + +// press A to clear tutorial screens +// throw exception if tutorial screen never detected +void clear_tutorial(VideoStream& stream, ProControllerContext& context, uint16_t seconds_timeout = 5); + +// spam the A button to clear dialog. +// stop depending on ClearDialogMode: stop when detect overworld, or dialog prompt, or A button prompt. Or if times out +// throw exception if times out, unless this is the intended stop condition. +// also throw exception if dialog is never detected. +void clear_dialog(VideoStream& stream, ProControllerContext& context, + ClearDialogMode mode, uint16_t seconds_timeout = 60, + std::vector optional_callbacks = {} +); + + +// return true if the destination marker is present within the minimap area +bool confirm_marker_present( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context +); + +// move character with ssf left joystick, as per given x, y, until +// stop_condition is met (e.g. Dialog detected). +// throw exception if reaches timeout before detecting stop condition +void overworld_navigation(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + NavigationStopCondition stop_condition, + NavigationMovementMode movement_mode, + uint8_t x, uint8_t y, + uint16_t seconds_timeout = 60, uint16_t seconds_realign = 60, + bool auto_heal = false, + bool detect_wipeout = false +); + +void config_option(ProControllerContext& context, int change_option_value); + +// enter menu and swap the first and third moves for your starter +void swap_starter_moves(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, Language language); + +// run the given `action`. if detect a battle, stop the action, and throw exception +void do_action_and_monitor_for_battles( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + std::function< + void(const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context) + >&& action +); + +// catch any UnexpectedBattle exceptions from `action`. then use run_battle_press_A until overworld, and re-try the `action`. +void handle_unexpected_battles( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + std::function< + void(const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context) + >&& action +); + +// if stationary in overworld for an amount of time (seconds_stationary), run `recovery_action` then try `action` again +// return once successfully completed `action` +// throw exception if fails to complete `action` within a certain amount of time (minutes_timeout). +// NOTE: if using this function to wrap overworld_navigation(), keep in mind that +// confirm_marker_present() will keep the player still for 5 seconds before moving. Therefore, seconds_stationary should be greater than 5 seconds in this case. +void handle_when_stationary_in_overworld( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + std::function< + void(const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context) + >&& action, + std::function< + void(const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context) + >&& recovery_action, + size_t seconds_stationary = 6, + uint16_t minutes_timeout = 5, + size_t max_attempts = 2 +); + +// do action. if error is thrown, catch the error and try the recovery action +void handle_failed_action( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + std::function< + void(const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context) + >&& action, + std::function< + void(const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context) + >&& recovery_action, + size_t max_failures +); + +void wait_for_gradient_arrow( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + ImageFloatBox box_area_to_check, + uint16_t seconds_timeout +); + +void wait_for_overworld( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + uint16_t seconds_timeout = 30 +); + +void press_A_until_dialog( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + uint16_t seconds_between_button_presses +); + +// return true if ride is active. i.e. if you are on your ride +bool is_ride_active(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +void get_on_ride(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +void get_off_ride(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +void get_on_or_off_ride(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, bool get_on); + + +// change the settings prior to Autostory +// Assumes that `current_segment` represents where we currently are in the story. +void change_settings_prior_to_autostory( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + size_t current_segment_num, + Language language +); + +// from within the Settings/Options menu, change the settings +void change_settings(SingleSwitchProgramEnvironment& env, ProControllerContext& context, Language language, bool use_inference = true); + + +void checkpoint_save(SingleSwitchProgramEnvironment& env, ProControllerContext& context, EventNotificationOption& notif_status_update); + +enum class ZoomChange{ + ZOOM_IN, + ZOOM_IN_TWICE, + ZOOM_OUT, + ZOOM_OUT_TWICE, + KEEP_ZOOM, +}; + +struct MoveCursor{ + ZoomChange zoom_change; + uint8_t move_x; + uint8_t move_y; + uint16_t move_duration; +}; + +// place a marker on the map, not relative to the current player position, but based on a fixed landmark, such as a pokecenter +// How this works: +// - cursor is moved to a point near the landmark, as per `move_cursor_near_landmark` +// - move the cursor onto the landmark using `detect_closest_pokecenter_and_move_map_cursor_there`. +// - confirm that the pokecenter is centered within cursor. If not, close map app, and re-try. +// - cursor is moved to target location, as per `move_cursor_to_target`. A marker is placed down here. +void realign_player_from_landmark( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + MoveCursor move_cursor_near_landmark, + MoveCursor move_cursor_to_target +); + +// confirm that the cursor is centered on the pokecenter, within the map app +// else throw exception +void confirm_cursor_centered_on_pokecenter(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// open map, then move cursor to a point near a flypoint as per `move_cursor_near_flypoint` +// then fly to the closest pokecenter near the cursor +void move_cursor_towards_flypoint_and_go_there( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + MoveCursor move_cursor_near_flypoint +); + + +void check_num_sunflora_found(SingleSwitchProgramEnvironment& env, ProControllerContext& context, int expected_number); + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_00.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_00.cpp index c0e55267ac..3ffaf6e96d 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_00.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_00.cpp @@ -1,83 +1,81 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_00.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -std::string AutoStory_Segment_00::name() const{ - return "00: Intro Cutscene"; -} - - -std::string AutoStory_Segment_00::start_text() const{ - return "Start: Intro cutscene."; -} - -std::string AutoStory_Segment_00::end_text() const{ - return "End: Finished cutscene."; -} - -void AutoStory_Segment_00::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 00: Intro Cutscene", COLOR_ORANGE); - env.console.overlay().add_log("Start Segment 00: Intro Cutscene", COLOR_ORANGE); - - checkpoint_00(env, context); - - context.wait_for_all_requests(); - env.console.log("End Segment 00: Intro Cutscene", COLOR_GREEN); - env.console.overlay().add_log("End Segment 00: Intro Cutscene", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); -} - - -void checkpoint_00(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - - - // Mash A through intro cutscene, until the L stick button is detected - WhiteButtonWatcher leftstick(COLOR_GREEN, WhiteButton::ButtonLStick, {0.435, 0.912, 0.046, 0.047}); - context.wait_for_all_requests(); - run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 240 * TICKS_PER_SECOND); - }, - {leftstick} - ); - - // Stand up from chair and walk to left side of room - pbf_move_left_joystick(context, 128, 255, 3 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 0, 128, 6 * TICKS_PER_SECOND, 1 * TICKS_PER_SECOND); - -} - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_00.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +std::string AutoStory_Segment_00::name() const{ + return "00: Intro Cutscene"; +} + + +std::string AutoStory_Segment_00::start_text() const{ + return "Start: Intro cutscene."; +} + +std::string AutoStory_Segment_00::end_text() const{ + return "End: Finished cutscene."; +} + +void AutoStory_Segment_00::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 00: Intro Cutscene", COLOR_ORANGE); + + checkpoint_00(env, context); + + context.wait_for_all_requests(); + env.console.log("End Segment 00: Intro Cutscene", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); +} + + +void checkpoint_00(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + + + // Mash A through intro cutscene, until the L stick button is detected + WhiteButtonWatcher leftstick(COLOR_GREEN, WhiteButton::ButtonLStick, {0.435, 0.912, 0.046, 0.047}); + context.wait_for_all_requests(); + run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 240 * TICKS_PER_SECOND); + }, + {leftstick} + ); + + // Stand up from chair and walk to left side of room + pbf_move_left_joystick(context, 128, 255, 3 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 0, 128, 6 * TICKS_PER_SECOND, 1 * TICKS_PER_SECOND); + +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_00.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_00.h index f39edbf6a4..e9abe3156c 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_00.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_00.h @@ -1,36 +1,36 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_00_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_00_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_00 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - -// start: after selecting character name, style and the cutscene has started -// end: stood up from chair. Walked to left side of room. -void checkpoint_00(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_00_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_00_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_00 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + +// start: after selecting character name, style and the cutscene has started +// end: stood up from chair. Walked to left side of room. +void checkpoint_00(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_01.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_01.cpp index 13c426f191..aa8cf395ae 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_01.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_01.cpp @@ -1,299 +1,297 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" -#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_01.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - - -std::string AutoStory_Segment_01::name() const{ - return "01: Pick Starter"; -} - - -std::string AutoStory_Segment_01::start_text() const{ - return "Start: Finished cutscene."; -} - -std::string AutoStory_Segment_01::end_text() const{ - return "End: Picked the starter."; -} - -void AutoStory_Segment_01::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 01: Pick Starter", COLOR_ORANGE); - env.console.overlay().add_log("Start Segment 01: Pick Starter", COLOR_ORANGE); - - checkpoint_01(env, context, options.notif_status_update, options.language); - checkpoint_02(env, context, options.notif_status_update); - checkpoint_03(env, context, options.notif_status_update, options.language, options.starter_choice); - - context.wait_for_all_requests(); - env.console.log("End Segment 02: Pick Starter", COLOR_GREEN); - env.console.overlay().add_log("End Segment 02: Pick Starter", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - -void checkpoint_01( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update, - Language language -){ -AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if(first_attempt){ - save_game_tutorial(env.program_info(), env.console, context); - stats.m_checkpoint++; - env.update_stats(); - send_program_status_notification(env, notif_status_update, "Saved at checkpoint."); - } - - context.wait_for_all_requests(); - // set settings - enter_menu_from_overworld(env.program_info(), env.console, context, 0, MenuSide::RIGHT, false); - change_settings(env, context, language, first_attempt); - pbf_mash_button(context, BUTTON_B, 2 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - - break; - }catch(...){ - // (void)e; - first_attempt = false; - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } -} - -void checkpoint_02( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if(first_attempt){ - save_game_tutorial(env.program_info(), env.console, context); - stats.m_checkpoint++; - env.update_stats(); - send_program_status_notification(env, notif_status_update, "Saved at checkpoint."); - first_attempt = false; - } - - context.wait_for_all_requests(); - env.console.log("Go downstairs, get stopped by Skwovet"); - env.console.overlay().add_log("Go downstairs, get stopped by Skwovet", COLOR_WHITE); - pbf_move_left_joystick(context, 128, 0, 3 * TICKS_PER_SECOND, 20); - pbf_move_left_joystick(context, 0, 128, 3 * TICKS_PER_SECOND, 20); - pbf_move_left_joystick(context, 128, 255, 3 * TICKS_PER_SECOND, 20); - pbf_wait(context, 5 * TICKS_PER_SECOND); - // clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 5, {}); - - context.wait_for_all_requests(); - env.console.log("Go to the kitchen, talk with mom"); - env.console.overlay().add_log("Go to the kitchen, talk with mom", COLOR_WHITE); - pbf_move_left_joystick(context, 128, 255, 2 * TICKS_PER_SECOND, 20); - overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 0, 128); - - env.console.log("clear_dialog: Talk with Mom."); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 5, {}); - - context.wait_for_all_requests(); - env.console.log("Go to the front door, talk with Clavell"); - env.console.overlay().add_log("Go to the front door, talk with Clavell", COLOR_WHITE); - pbf_move_left_joystick(context, 230, 200, 2 * TICKS_PER_SECOND, 20); - overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 255, 128); - - env.console.log("clear_dialog: Talk with Clavell at front door."); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 5, {}); - - context.wait_for_all_requests(); - env.console.log("Go upstairs, dress up"); - env.console.overlay().add_log("Go upstairs, dress up", COLOR_WHITE); - pbf_move_left_joystick(context, 255, 128, 2 * TICKS_PER_SECOND, 20); - pbf_move_left_joystick(context, 185, 10, 1 * TICKS_PER_SECOND, 20); - pbf_move_left_joystick(context, 128, 0, 4 * TICKS_PER_SECOND, 20); - pbf_move_left_joystick(context, 255, 128, 4 * TICKS_PER_SECOND, 20); - pbf_move_left_joystick(context, 110, 200, 3 * TICKS_PER_SECOND, 20); - pbf_move_left_joystick(context, 255, 128, 2 * TICKS_PER_SECOND, 20); - pbf_mash_button(context, BUTTON_A, 20 * TICKS_PER_SECOND); - - context.wait_for_all_requests(); - env.console.log("Go to the living room, talk with Clavell"); - env.console.overlay().add_log("Go to the living room, talk with Clavell", COLOR_WHITE); - pbf_move_left_joystick(context, 0, 0, 3 * TICKS_PER_SECOND, 20); - pbf_move_left_joystick(context, 0, 128, 3 * TICKS_PER_SECOND, 20); - pbf_move_left_joystick(context, 128, 255, 4 * TICKS_PER_SECOND, 20); - overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 0, 128); - - env.console.log("clear_dialog: Talk with Clavell at living room."); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10, {}); - - context.wait_for_all_requests(); - env.console.log("Go outside, receive Rotom Phone"); - env.console.overlay().add_log("Go outside, receive Rotom Phone", COLOR_WHITE); - overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 245, 230); - - env.console.log("clear_dialog: Talk with Clavell outside. Receive Rotom phone. Stop when detect overworld."); - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD, CallbackEnum::WHITE_A_BUTTON}); - - context.wait_for_all_requests(); - env.console.log("Clear map tutorial"); - open_map_from_overworld(env.program_info(), env.console, context, true); - leave_phone_to_overworld(env.program_info(), env.console, context); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } -} - -void checkpoint_03( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update, - Language language, - StarterChoice starter_choice -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - - context.wait_for_all_requests(); - DirectionDetector direction; - direction.change_direction(env.program_info(), env.console, context, 4.62); - pbf_move_left_joystick(context, 128, 0, 3600, 50); - pbf_move_left_joystick(context, 0, 128, 30, 50); - - direction.change_direction(env.program_info(), env.console, context, 4.62); - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20); - - context.wait_for_all_requests(); - env.console.log("Entered Nemona's house"); - mash_button_till_overworld(env.console, context); - context.wait_for_all_requests(); - env.console.log("Picking a starter..."); - switch(starter_choice){ - case StarterChoice::SPRIGATITO: - env.console.log("Picking Sprigatito..."); - pbf_move_left_joystick(context, 75, 0, 80, 20); - break; - case StarterChoice::FUECOCO: - env.console.log("Picking Fuecoco..."); - pbf_move_left_joystick(context, 180, 0, 80, 20); - break; - case StarterChoice::QUAXLY: - env.console.log("Picking Quaxly..."); - pbf_move_left_joystick(context, 128, 0, 80, 20); - break; - } - pbf_press_button(context, BUTTON_A, 20, 105); // choose the starter - env.console.log("clear_dialog: Choose starter. Stop when detect prompt to receive starter."); - clear_dialog(env.console, context, ClearDialogMode::STOP_PROMPT, 20, {CallbackEnum::PROMPT_DIALOG}); - - pbf_press_button(context, BUTTON_A, 20, 105); // accept the pokemon - env.console.log("clear_dialog: Stop when detect prompt to give nickname to starter."); - clear_dialog(env.console, context, ClearDialogMode::STOP_PROMPT, 20, {CallbackEnum::PROMPT_DIALOG}); - - pbf_mash_button(context, BUTTON_B, 100); // Don't give a nickname - env.console.log("clear_dialog: Talk to Nemona and Clavell. Stop when detect overworld."); - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 20, {CallbackEnum::OVERWORLD}); - - context.wait_for_all_requests(); - env.console.log("Clear auto heal tutorial."); - // Press X until Auto heal tutorial shows up - TutorialWatcher tutorial; - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - for (int i = 0; i < 10; i++){ - pbf_press_button(context, BUTTON_X, 20, 250); - } - }, - {tutorial} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Stuck trying to clear auto heal tutorial.", - env.console - ); - } - clear_tutorial(env.console, context); - - env.console.log("Change move order."); - swap_starter_moves(env.program_info(), env.console, context, language); - leave_box_system_to_overworld(env.program_info(), env.console, context); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" +#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_01.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + + +std::string AutoStory_Segment_01::name() const{ + return "01: Pick Starter"; +} + + +std::string AutoStory_Segment_01::start_text() const{ + return "Start: Finished cutscene."; +} + +std::string AutoStory_Segment_01::end_text() const{ + return "End: Picked the starter."; +} + +void AutoStory_Segment_01::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 01: Pick Starter", COLOR_ORANGE); + + checkpoint_01(env, context, options.notif_status_update, options.language); + checkpoint_02(env, context, options.notif_status_update); + checkpoint_03(env, context, options.notif_status_update, options.language, options.starter_choice); + + context.wait_for_all_requests(); + env.console.log("End Segment 01: Pick Starter", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + +void checkpoint_01( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update, + Language language +){ +AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if(first_attempt){ + save_game_tutorial(env.program_info(), env.console, context); + stats.m_checkpoint++; + env.update_stats(); + send_program_status_notification(env, notif_status_update, "Saved at checkpoint."); + } + + context.wait_for_all_requests(); + // set settings + enter_menu_from_overworld(env.program_info(), env.console, context, 0, MenuSide::RIGHT, false); + change_settings(env, context, language, first_attempt); + pbf_mash_button(context, BUTTON_B, 2 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + + break; + }catch(...){ + // (void)e; + first_attempt = false; + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } +} + +void checkpoint_02( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if(first_attempt){ + save_game_tutorial(env.program_info(), env.console, context); + stats.m_checkpoint++; + env.update_stats(); + send_program_status_notification(env, notif_status_update, "Saved at checkpoint."); + first_attempt = false; + } + + context.wait_for_all_requests(); + env.console.log("Go downstairs, get stopped by Skwovet"); + env.console.overlay().add_log("Go downstairs, get stopped by Skwovet", COLOR_WHITE); + pbf_move_left_joystick(context, 128, 0, 3 * TICKS_PER_SECOND, 20); + pbf_move_left_joystick(context, 0, 128, 3 * TICKS_PER_SECOND, 20); + pbf_move_left_joystick(context, 128, 255, 3 * TICKS_PER_SECOND, 20); + pbf_wait(context, 5 * TICKS_PER_SECOND); + // clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 5, {}); + + context.wait_for_all_requests(); + env.console.log("Go to the kitchen, talk with mom"); + env.console.overlay().add_log("Go to the kitchen, talk with mom", COLOR_WHITE); + pbf_move_left_joystick(context, 128, 255, 2 * TICKS_PER_SECOND, 20); + overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 0, 128); + + env.console.log("clear_dialog: Talk with Mom."); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 5, {}); + + context.wait_for_all_requests(); + env.console.log("Go to the front door, talk with Clavell"); + env.console.overlay().add_log("Go to the front door, talk with Clavell", COLOR_WHITE); + pbf_move_left_joystick(context, 230, 200, 2 * TICKS_PER_SECOND, 20); + overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 255, 128); + + env.console.log("clear_dialog: Talk with Clavell at front door."); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 5, {}); + + context.wait_for_all_requests(); + env.console.log("Go upstairs, dress up"); + env.console.overlay().add_log("Go upstairs, dress up", COLOR_WHITE); + pbf_move_left_joystick(context, 255, 128, 2 * TICKS_PER_SECOND, 20); + pbf_move_left_joystick(context, 185, 10, 1 * TICKS_PER_SECOND, 20); + pbf_move_left_joystick(context, 128, 0, 4 * TICKS_PER_SECOND, 20); + pbf_move_left_joystick(context, 255, 128, 4 * TICKS_PER_SECOND, 20); + pbf_move_left_joystick(context, 110, 200, 3 * TICKS_PER_SECOND, 20); + pbf_move_left_joystick(context, 255, 128, 2 * TICKS_PER_SECOND, 20); + pbf_mash_button(context, BUTTON_A, 20 * TICKS_PER_SECOND); + + context.wait_for_all_requests(); + env.console.log("Go to the living room, talk with Clavell"); + env.console.overlay().add_log("Go to the living room, talk with Clavell", COLOR_WHITE); + pbf_move_left_joystick(context, 0, 0, 3 * TICKS_PER_SECOND, 20); + pbf_move_left_joystick(context, 0, 128, 3 * TICKS_PER_SECOND, 20); + pbf_move_left_joystick(context, 128, 255, 4 * TICKS_PER_SECOND, 20); + overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 0, 128); + + env.console.log("clear_dialog: Talk with Clavell at living room."); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10, {}); + + context.wait_for_all_requests(); + env.console.log("Go outside, receive Rotom Phone"); + env.console.overlay().add_log("Go outside, receive Rotom Phone", COLOR_WHITE); + overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 245, 230); + + env.console.log("clear_dialog: Talk with Clavell outside. Receive Rotom phone. Stop when detect overworld."); + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD, CallbackEnum::WHITE_A_BUTTON}); + + context.wait_for_all_requests(); + env.console.log("Clear map tutorial"); + open_map_from_overworld(env.program_info(), env.console, context, true); + leave_phone_to_overworld(env.program_info(), env.console, context); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } +} + +void checkpoint_03( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update, + Language language, + StarterChoice starter_choice +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + + context.wait_for_all_requests(); + DirectionDetector direction; + direction.change_direction(env.program_info(), env.console, context, 4.62); + pbf_move_left_joystick(context, 128, 0, 3600, 50); + pbf_move_left_joystick(context, 0, 128, 30, 50); + + direction.change_direction(env.program_info(), env.console, context, 4.62); + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20); + + context.wait_for_all_requests(); + env.console.log("Entered Nemona's house"); + mash_button_till_overworld(env.console, context); + context.wait_for_all_requests(); + env.console.log("Picking a starter..."); + switch(starter_choice){ + case StarterChoice::SPRIGATITO: + env.console.log("Picking Sprigatito..."); + pbf_move_left_joystick(context, 75, 0, 80, 20); + break; + case StarterChoice::FUECOCO: + env.console.log("Picking Fuecoco..."); + pbf_move_left_joystick(context, 180, 0, 80, 20); + break; + case StarterChoice::QUAXLY: + env.console.log("Picking Quaxly..."); + pbf_move_left_joystick(context, 128, 0, 80, 20); + break; + } + pbf_press_button(context, BUTTON_A, 20, 105); // choose the starter + env.console.log("clear_dialog: Choose starter. Stop when detect prompt to receive starter."); + clear_dialog(env.console, context, ClearDialogMode::STOP_PROMPT, 20, {CallbackEnum::PROMPT_DIALOG}); + + pbf_press_button(context, BUTTON_A, 20, 105); // accept the pokemon + env.console.log("clear_dialog: Stop when detect prompt to give nickname to starter."); + clear_dialog(env.console, context, ClearDialogMode::STOP_PROMPT, 20, {CallbackEnum::PROMPT_DIALOG}); + + pbf_mash_button(context, BUTTON_B, 100); // Don't give a nickname + env.console.log("clear_dialog: Talk to Nemona and Clavell. Stop when detect overworld."); + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 20, {CallbackEnum::OVERWORLD}); + + context.wait_for_all_requests(); + env.console.log("Clear auto heal tutorial."); + // Press X until Auto heal tutorial shows up + TutorialWatcher tutorial; + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + for (int i = 0; i < 10; i++){ + pbf_press_button(context, BUTTON_X, 20, 250); + } + }, + {tutorial} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Stuck trying to clear auto heal tutorial.", + env.console + ); + } + clear_tutorial(env.console, context); + + env.console.log("Change move order."); + swap_starter_moves(env.program_info(), env.console, context, language); + leave_box_system_to_overworld(env.program_info(), env.console, context); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_01.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_01.h index 024cabf697..0a58727f29 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_01.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_01.h @@ -1,59 +1,59 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_01_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_01_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_01 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - -// start: stood up from chair. Walked to left side of room. -// end: standing in room. updated settings -void checkpoint_01( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update, - Language language -); - -// start: standing in room. updated settings -// end: standing in front of power of science NPC. Cleared map tutorial. -void checkpoint_02( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: standing in front of power of science NPC. Cleared map tutorial. -// end: received starter, changed move order -void checkpoint_03( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update, - Language language, - StarterChoice starter_choice -); - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_01_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_01_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_01 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + +// start: stood up from chair. Walked to left side of room. +// end: standing in room. updated settings +void checkpoint_01( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update, + Language language +); + +// start: standing in room. updated settings +// end: standing in front of power of science NPC. Cleared map tutorial. +void checkpoint_02( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: standing in front of power of science NPC. Cleared map tutorial. +// end: received starter, changed move order +void checkpoint_03( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update, + Language language, + StarterChoice starter_choice +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_02.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_02.cpp index ed23389bd2..1c2b515b1a 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_02.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_02.cpp @@ -1,114 +1,112 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_02.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - - -std::string AutoStory_Segment_02::name() const{ - return "02: First Nemona Battle"; -} - -std::string AutoStory_Segment_02::start_text() const{ - return "Start: Picked the starter."; -} - -std::string AutoStory_Segment_02::end_text() const{ - return "End: Battled Nemona on the beach."; -} - -void AutoStory_Segment_02::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 02: First Nemona Battle", COLOR_ORANGE); - env.console.overlay().add_log("Start Segment 02: First Nemona Battle", COLOR_ORANGE); - - checkpoint_04(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 02: First Nemona Battle", COLOR_GREEN); - env.console.overlay().add_log("End Segment 02: First Nemona Battle", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - -void checkpoint_04( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - DirectionDetector direction; - direction.change_direction(env.program_info(), env.console, context, 3.72); - pbf_move_left_joystick(context, 128, 0, 400, 50); - direction.change_direction(env.program_info(), env.console, context, 4.55); - pbf_move_left_joystick(context, 128, 0, 600, 50); - direction.change_direction(env.program_info(), env.console, context, 5.27); - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 20); - - context.wait_for_all_requests(); - env.console.log("Starting battle..."); - // TODO: Battle start prompt detection - // can lose this battle, and story will continue - mash_button_till_overworld(env.console, context); - context.wait_for_all_requests(); - env.console.log("Finished battle."); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_02.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + + +std::string AutoStory_Segment_02::name() const{ + return "02: First Nemona Battle"; +} + +std::string AutoStory_Segment_02::start_text() const{ + return "Start: Picked the starter."; +} + +std::string AutoStory_Segment_02::end_text() const{ + return "End: Battled Nemona on the beach."; +} + +void AutoStory_Segment_02::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 02: First Nemona Battle", COLOR_ORANGE); + + checkpoint_04(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 02: First Nemona Battle", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + +void checkpoint_04( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + DirectionDetector direction; + direction.change_direction(env.program_info(), env.console, context, 3.72); + pbf_move_left_joystick(context, 128, 0, 400, 50); + direction.change_direction(env.program_info(), env.console, context, 4.55); + pbf_move_left_joystick(context, 128, 0, 600, 50); + direction.change_direction(env.program_info(), env.console, context, 5.27); + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 20); + + context.wait_for_all_requests(); + env.console.log("Starting battle..."); + // TODO: Battle start prompt detection + // can lose this battle, and story will continue + mash_button_till_overworld(env.console, context); + context.wait_for_all_requests(); + env.console.log("Finished battle."); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_02.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_02.h index c440327663..0409ae8ca8 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_02.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_02.h @@ -1,41 +1,41 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_02_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_02_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_02 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: Received starter pokemon and changed move order. Cleared autoheal tutorial. -// end: Battled Nemona on the beach. -void checkpoint_04( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_02_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_02_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_02 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: Received starter pokemon and changed move order. Cleared autoheal tutorial. +// end: Battled Nemona on the beach. +void checkpoint_04( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_03.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_03.cpp index cfa74b3fa8..73becf4f43 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_03.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_03.cpp @@ -1,208 +1,206 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_03.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - - -std::string AutoStory_Segment_03::name() const{ - return "03: Catch Tutorial"; -} - -std::string AutoStory_Segment_03::start_text() const{ - return "Start: Battled Nemona on the beach."; -} - -std::string AutoStory_Segment_03::end_text() const{ - return "End: Finished catch tutorial. Walked to the cliff and heard mystery cry."; -} - -void AutoStory_Segment_03::run_segment(SingleSwitchProgramEnvironment& env, ProControllerContext& context, AutoStoryOptions options) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 03: Catch Tutorial", COLOR_ORANGE); - env.console.overlay().add_log("Start Segment 03: Catch Tutorial", COLOR_ORANGE); - - checkpoint_05(env, context, options.notif_status_update); - checkpoint_06(env, context, options.notif_status_update); - checkpoint_07(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 03: Catch Tutorial", COLOR_GREEN); - env.console.overlay().add_log("End Segment 03: Catch Tutorial", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - -void checkpoint_05( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - DirectionDetector direction; - direction.change_direction(env.program_info(), env.console, context, 1.92); - pbf_move_left_joystick(context, 128, 0, 7 * TICKS_PER_SECOND, 50); - direction.change_direction(env.program_info(), env.console, context, 1.13); - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20); - - context.wait_for_all_requests(); - env.console.log("Get mom's sandwich"); - env.console.overlay().add_log("Get mom's sandwich", COLOR_WHITE); - mash_button_till_overworld(env.console, context); - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } -} - -void checkpoint_06( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - - context.wait_for_all_requests(); - - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 40, 82, 60); - pbf_move_left_joystick(context, 128, 0, 6 * TICKS_PER_SECOND, 20); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 110, 10, 60); - env.console.log("overworld_navigation: Go to Nemona."); - overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 128, 0, 20, 20, true, true); - - context.wait_for_all_requests(); - env.console.log("clear_dialog: Talk with Nemona to start catch tutorial. Stop when detect battle."); - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, - {CallbackEnum::WHITE_A_BUTTON, CallbackEnum::TUTORIAL, CallbackEnum::BATTLE}); - - // can die in catch tutorial, and the story will continue - env.console.log("run_battle_press_A: Battle Lechonk in catch tutorial. Stop when detect dialog."); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG); - - env.console.log("clear_dialog: Talk with Nemona to finish catch tutorial. Stop when detect overworld."); - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, - {CallbackEnum::TUTORIAL, CallbackEnum::OVERWORLD}); - - context.wait_for_all_requests(); - env.console.log("Finished catch tutorial"); - env.console.overlay().add_log("Finished catch tutorial", COLOR_WHITE); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } -} - -void checkpoint_07( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - - context.wait_for_all_requests(); - env.console.log("Move to cliff"); - env.console.overlay().add_log("Move to cliff", COLOR_WHITE); - - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 70, 100); - env.console.log("overworld_navigation: Go to cliff."); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, - 135, 0, 24, 12, true, true); - - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 128, 0, 80); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 24, 12, true, true); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD}); - - context.wait_for_all_requests(); - env.console.log("Mystery cry"); - env.console.overlay().add_log("Mystery cry", COLOR_WHITE); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } -} - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_03.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + + +std::string AutoStory_Segment_03::name() const{ + return "03: Catch Tutorial"; +} + +std::string AutoStory_Segment_03::start_text() const{ + return "Start: Battled Nemona on the beach."; +} + +std::string AutoStory_Segment_03::end_text() const{ + return "End: Finished catch tutorial. Walked to the cliff and heard mystery cry."; +} + +void AutoStory_Segment_03::run_segment(SingleSwitchProgramEnvironment& env, ProControllerContext& context, AutoStoryOptions options) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 03: Catch Tutorial", COLOR_ORANGE); + + checkpoint_05(env, context, options.notif_status_update); + checkpoint_06(env, context, options.notif_status_update); + checkpoint_07(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 03: Catch Tutorial", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + +void checkpoint_05( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + DirectionDetector direction; + direction.change_direction(env.program_info(), env.console, context, 1.92); + pbf_move_left_joystick(context, 128, 0, 7 * TICKS_PER_SECOND, 50); + direction.change_direction(env.program_info(), env.console, context, 1.13); + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20); + + context.wait_for_all_requests(); + env.console.log("Get mom's sandwich"); + env.console.overlay().add_log("Get mom's sandwich", COLOR_WHITE); + mash_button_till_overworld(env.console, context); + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } +} + +void checkpoint_06( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + + context.wait_for_all_requests(); + + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 40, 82, 60); + pbf_move_left_joystick(context, 128, 0, 6 * TICKS_PER_SECOND, 20); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 110, 10, 60); + env.console.log("overworld_navigation: Go to Nemona."); + overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 128, 0, 20, 20, true, true); + + context.wait_for_all_requests(); + env.console.log("clear_dialog: Talk with Nemona to start catch tutorial. Stop when detect battle."); + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, + {CallbackEnum::WHITE_A_BUTTON, CallbackEnum::TUTORIAL, CallbackEnum::BATTLE}); + + // can die in catch tutorial, and the story will continue + env.console.log("run_battle_press_A: Battle Lechonk in catch tutorial. Stop when detect dialog."); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG); + + env.console.log("clear_dialog: Talk with Nemona to finish catch tutorial. Stop when detect overworld."); + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, + {CallbackEnum::TUTORIAL, CallbackEnum::OVERWORLD}); + + context.wait_for_all_requests(); + env.console.log("Finished catch tutorial"); + env.console.overlay().add_log("Finished catch tutorial", COLOR_WHITE); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } +} + +void checkpoint_07( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + + context.wait_for_all_requests(); + env.console.log("Move to cliff"); + env.console.overlay().add_log("Move to cliff", COLOR_WHITE); + + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 70, 100); + env.console.log("overworld_navigation: Go to cliff."); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, + 135, 0, 24, 12, true, true); + + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 128, 0, 80); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 24, 12, true, true); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD}); + + context.wait_for_all_requests(); + env.console.log("Mystery cry"); + env.console.overlay().add_log("Mystery cry", COLOR_WHITE); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_03.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_03.h index 3fdca90f92..949f113349 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_03.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_03.h @@ -1,56 +1,56 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_03_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_03_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_03 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options) const override; -}; - - -// start: Battled Nemona on the beach. -// end: Met mom at gate. Received mom's sandwich. -void checkpoint_05( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Met mom at gate. Received mom's sandwich. -// end: Cleared catch tutorial. -void checkpoint_06( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Cleared catch tutorial. -// end: Moved to cliff. Heard mystery cry. -void checkpoint_07( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_03_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_03_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_03 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options) const override; +}; + + +// start: Battled Nemona on the beach. +// end: Met mom at gate. Received mom's sandwich. +void checkpoint_05( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Met mom at gate. Received mom's sandwich. +// end: Cleared catch tutorial. +void checkpoint_06( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Cleared catch tutorial. +// end: Moved to cliff. Heard mystery cry. +void checkpoint_07( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_04.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_04.cpp index fbfc9c2445..a1d9345c37 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_04.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_04.cpp @@ -1,213 +1,211 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_04.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - - -std::string AutoStory_Segment_04::name() const{ - return "04: Rescue Legendary"; -} - -std::string AutoStory_Segment_04::start_text() const{ - return "Start: Finished catch tutorial. Walked to the cliff and heard mystery cry."; -} - -std::string AutoStory_Segment_04::end_text() const{ - return "End: Saved the Legendary. Escaped from the Houndoom cave."; -} - -void AutoStory_Segment_04::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 04: Rescue Legendary", COLOR_ORANGE); - env.console.overlay().add_log("Start Segment 04: Rescue Legendary", COLOR_ORANGE); - - checkpoint_08(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 04: Rescue Legendary", COLOR_GREEN); - env.console.overlay().add_log("End Segment 04: Rescue Legendary", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - -void checkpoint_08( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 230, 70, 100); - env.console.log("overworld_navigation: Go to cliff."); - overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 128, 0, 30, 30, true, true); - - env.console.log("Look over the injured Miraidon/Koraidon on the beach."); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 5, {}); - env.console.log("Fall down the cliff."); - pbf_wait(context, 20 * TICKS_PER_SECOND); // long animation - context.wait_for_all_requests(); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10, {}); - env.console.log("Go to Legendary pokemon laying on the beach."); - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 30); - - env.console.log("clear_dialog: Offer Miraidon/Koraidon a sandwich."); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10, {}); - - // TODO: Bag menu navigation - context.wait_for_all_requests(); - env.console.log("Feed mom's sandwich"); - env.console.overlay().add_log("Feed mom's sandwich", COLOR_WHITE); - - GradientArrowWatcher arrow(COLOR_RED, GradientArrowType::RIGHT, {0.104, 0.312, 0.043, 0.08}); - context.wait_for_all_requests(); - - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - for (int i = 0; i < 10; i++){ - pbf_press_dpad(context, DPAD_UP, 20, 250); - } - }, - {arrow} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to feed mom's sandwich.", - env.console - ); - } - - // only press A when the sandwich is selected - pbf_mash_button(context, BUTTON_A, 100); - - env.console.log("Miraidon/Koraidon eats the sandwich."); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 25, {}); - env.console.log("Miraidon/Koraidon gets up and walks to cave entrance."); // long animation - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10, {}); - - // First Nemona cave conversation - context.wait_for_all_requests(); - env.console.log("Enter cave"); - env.console.overlay().add_log("Enter cave", COLOR_WHITE); - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 600, 50); - realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 150, 20, 20); - pbf_move_left_joystick(context, 128, 0, 1000, 50); - realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 160, 20, 20); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 20, true, true); - } - ); - - env.console.log("clear_dialog: Talk to Nemona yelling down, while you're down in the cave."); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10, {CallbackEnum::PROMPT_DIALOG}); - - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - // Legendary rock break - context.wait_for_all_requests(); - stream.log("Rock break"); - stream.overlay().add_log("Rock break", COLOR_WHITE); - pbf_move_left_joystick(context, 128, 20, 3 * TICKS_PER_SECOND, 20); - realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 230, 25, 30); - pbf_move_left_joystick(context, 128, 0, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); - - // Houndour wave - context.wait_for_all_requests(); - stream.log("Houndour wave"); - stream.overlay().add_log("Houndour wave", COLOR_WHITE); - // walk to room entrance - realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 150, 15, 30); - pbf_move_left_joystick(context, 128, 20, 4 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); - - realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 210, 15, 30); - pbf_move_left_joystick(context, 128, 20, 3 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 128, 20, 2 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 128, 20, 6 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); - - realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 200, 25, 20); - pbf_move_left_joystick(context, 128, 20, 4 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 128, 20, 4 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); - - realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 210, 25, 25); - pbf_move_left_joystick(context, 128, 20, 6 * TICKS_PER_SECOND, 20 * TICKS_PER_SECOND); - - // Houndoom encounter - context.wait_for_all_requests(); - stream.log("Houndoom encounter"); - stream.overlay().add_log("Houndoom encounter", COLOR_WHITE); - pbf_move_left_joystick(context, 128, 20, 4 * TICKS_PER_SECOND, 20); - realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 245, 20, 20); - pbf_move_left_joystick(context, 128, 20, 2 * TICKS_PER_SECOND, 20); - realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 255, 90, 20); - pbf_move_left_joystick(context, 128, 20, 8 * TICKS_PER_SECOND, 8 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_L, 20, 20); - } - ); - - env.console.log("overworld_navigation: Go to Houndoom."); - overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 128, 0, 20, 20, true, true); - - mash_button_till_overworld(env.console, context, BUTTON_A); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_04.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + + +std::string AutoStory_Segment_04::name() const{ + return "04: Rescue Legendary"; +} + +std::string AutoStory_Segment_04::start_text() const{ + return "Start: Finished catch tutorial. Walked to the cliff and heard mystery cry."; +} + +std::string AutoStory_Segment_04::end_text() const{ + return "End: Saved the Legendary. Escaped from the Houndoom cave."; +} + +void AutoStory_Segment_04::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 04: Rescue Legendary", COLOR_ORANGE); + + checkpoint_08(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 04: Rescue Legendary", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + +void checkpoint_08( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 230, 70, 100); + env.console.log("overworld_navigation: Go to cliff."); + overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 128, 0, 30, 30, true, true); + + env.console.log("Look over the injured Miraidon/Koraidon on the beach."); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 5, {}); + env.console.log("Fall down the cliff."); + pbf_wait(context, 20 * TICKS_PER_SECOND); // long animation + context.wait_for_all_requests(); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10, {}); + env.console.log("Go to Legendary pokemon laying on the beach."); + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 30); + + env.console.log("clear_dialog: Offer Miraidon/Koraidon a sandwich."); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10, {}); + + // TODO: Bag menu navigation + context.wait_for_all_requests(); + env.console.log("Feed mom's sandwich"); + env.console.overlay().add_log("Feed mom's sandwich", COLOR_WHITE); + + GradientArrowWatcher arrow(COLOR_RED, GradientArrowType::RIGHT, {0.104, 0.312, 0.043, 0.08}); + context.wait_for_all_requests(); + + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + for (int i = 0; i < 10; i++){ + pbf_press_dpad(context, DPAD_UP, 20, 250); + } + }, + {arrow} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to feed mom's sandwich.", + env.console + ); + } + + // only press A when the sandwich is selected + pbf_mash_button(context, BUTTON_A, 100); + + env.console.log("Miraidon/Koraidon eats the sandwich."); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 25, {}); + env.console.log("Miraidon/Koraidon gets up and walks to cave entrance."); // long animation + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10, {}); + + // First Nemona cave conversation + context.wait_for_all_requests(); + env.console.log("Enter cave"); + env.console.overlay().add_log("Enter cave", COLOR_WHITE); + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 600, 50); + realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 150, 20, 20); + pbf_move_left_joystick(context, 128, 0, 1000, 50); + realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 160, 20, 20); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 20, true, true); + } + ); + + env.console.log("clear_dialog: Talk to Nemona yelling down, while you're down in the cave."); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10, {CallbackEnum::PROMPT_DIALOG}); + + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + // Legendary rock break + context.wait_for_all_requests(); + stream.log("Rock break"); + stream.overlay().add_log("Rock break", COLOR_WHITE); + pbf_move_left_joystick(context, 128, 20, 3 * TICKS_PER_SECOND, 20); + realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 230, 25, 30); + pbf_move_left_joystick(context, 128, 0, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); + + // Houndour wave + context.wait_for_all_requests(); + stream.log("Houndour wave"); + stream.overlay().add_log("Houndour wave", COLOR_WHITE); + // walk to room entrance + realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 150, 15, 30); + pbf_move_left_joystick(context, 128, 20, 4 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); + + realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 210, 15, 30); + pbf_move_left_joystick(context, 128, 20, 3 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 128, 20, 2 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 128, 20, 6 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); + + realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 200, 25, 20); + pbf_move_left_joystick(context, 128, 20, 4 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 128, 20, 4 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); + + realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 210, 25, 25); + pbf_move_left_joystick(context, 128, 20, 6 * TICKS_PER_SECOND, 20 * TICKS_PER_SECOND); + + // Houndoom encounter + context.wait_for_all_requests(); + stream.log("Houndoom encounter"); + stream.overlay().add_log("Houndoom encounter", COLOR_WHITE); + pbf_move_left_joystick(context, 128, 20, 4 * TICKS_PER_SECOND, 20); + realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 245, 20, 20); + pbf_move_left_joystick(context, 128, 20, 2 * TICKS_PER_SECOND, 20); + realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 255, 90, 20); + pbf_move_left_joystick(context, 128, 20, 8 * TICKS_PER_SECOND, 8 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_L, 20, 20); + } + ); + + env.console.log("overworld_navigation: Go to Houndoom."); + overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 128, 0, 20, 20, true, true); + + mash_button_till_overworld(env.console, context, BUTTON_A); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_04.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_04.h index e4219391a8..1879b5cf2b 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_04.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_04.h @@ -1,41 +1,41 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_04_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_04_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_04 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: Moved to cliff. Heard mystery cry. -// end: Rescued Koraidon/Miraidon and escaped from the Houndoom Cave. -void checkpoint_08( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_04_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_04_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_04 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: Moved to cliff. Heard mystery cry. +// end: Rescued Koraidon/Miraidon and escaped from the Houndoom Cave. +void checkpoint_08( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_05.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_05.cpp index 34d3e912e3..575bdd013f 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_05.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_05.cpp @@ -1,163 +1,161 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_05.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - - -std::string AutoStory_Segment_05::name() const{ - return "05: First Arven Battle"; -} - -std::string AutoStory_Segment_05::start_text() const{ - return "Start: Saved the Legendary. Escaped from the Houndoom cave."; -} - -std::string AutoStory_Segment_05::end_text() const{ - return "End: Battled Arven, received Legendary's Pokeball. Talked to Nemona at Lighthouse."; -} - -void AutoStory_Segment_05::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 05: First Arven Battle", COLOR_ORANGE); - env.console.overlay().add_log("Start Segment 05: First Arven Battle", COLOR_ORANGE); - - checkpoint_09(env, context, options.notif_status_update); - checkpoint_10(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 05: First Arven Battle", COLOR_GREEN); - env.console.overlay().add_log("End Segment 05: First Arven Battle", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - -void checkpoint_09( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 110, 50); - env.console.log("overworld_navigation: Go to Arven at the tower."); - - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 60, 30, true, true); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - context.wait_for_all_requests(); - env.console.log("Found Arven"); - env.console.overlay().add_log("Found Arven", COLOR_WHITE); - // can lose battle, and story will still continue - mash_button_till_overworld(env.console, context, BUTTON_A); - context.wait_for_all_requests(); - env.console.log("Receive legendary ball"); - env.console.overlay().add_log("Receive legendary ball", COLOR_WHITE); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } -} - -void checkpoint_10( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - env.console.log("Lighthouse view"); - env.console.overlay().add_log("Lighthouse view", COLOR_WHITE); - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NEW_MARKER, 230, 110, 100); - pbf_move_left_joystick(context, 128, 0, 6 * TICKS_PER_SECOND, 8 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 128, 0, 4 * TICKS_PER_SECOND, 20); - } - ); - DirectionDetector direction; - direction.change_direction(env.program_info(), env.console, context, 5.41); - - env.console.log("overworld_navigation: Go to Nemona on the lighthouse."); - overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_SPAM_A, 128, 0, 20, 20, true, true); - - mash_button_till_overworld(env.console, context, BUTTON_A); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } -} - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_05.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + + +std::string AutoStory_Segment_05::name() const{ + return "05: First Arven Battle"; +} + +std::string AutoStory_Segment_05::start_text() const{ + return "Start: Saved the Legendary. Escaped from the Houndoom cave."; +} + +std::string AutoStory_Segment_05::end_text() const{ + return "End: Battled Arven, received Legendary's Pokeball. Talked to Nemona at Lighthouse."; +} + +void AutoStory_Segment_05::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 05: First Arven Battle", COLOR_ORANGE); + + checkpoint_09(env, context, options.notif_status_update); + checkpoint_10(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 05: First Arven Battle", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + +void checkpoint_09( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 110, 50); + env.console.log("overworld_navigation: Go to Arven at the tower."); + + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 60, 30, true, true); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + context.wait_for_all_requests(); + env.console.log("Found Arven"); + env.console.overlay().add_log("Found Arven", COLOR_WHITE); + // can lose battle, and story will still continue + mash_button_till_overworld(env.console, context, BUTTON_A); + context.wait_for_all_requests(); + env.console.log("Receive legendary ball"); + env.console.overlay().add_log("Receive legendary ball", COLOR_WHITE); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } +} + +void checkpoint_10( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + env.console.log("Lighthouse view"); + env.console.overlay().add_log("Lighthouse view", COLOR_WHITE); + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NEW_MARKER, 230, 110, 100); + pbf_move_left_joystick(context, 128, 0, 6 * TICKS_PER_SECOND, 8 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 128, 0, 4 * TICKS_PER_SECOND, 20); + } + ); + DirectionDetector direction; + direction.change_direction(env.program_info(), env.console, context, 5.41); + + env.console.log("overworld_navigation: Go to Nemona on the lighthouse."); + overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_SPAM_A, 128, 0, 20, 20, true, true); + + mash_button_till_overworld(env.console, context, BUTTON_A); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_05.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_05.h index 9f07103b7c..4e3e6103cf 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_05.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_05.h @@ -1,48 +1,48 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_05_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_05_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_05 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: Rescued Koraidon/Miraidon and escaped from the Houndoom Cave. -// end: Battled Arven and received Legendary's Pokeball. -void checkpoint_09( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Battled Arven and received Legendary's Pokeball. -// end: Talked to Nemona at the Lighthouse. -void checkpoint_10( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_05_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_05_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_05 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: Rescued Koraidon/Miraidon and escaped from the Houndoom Cave. +// end: Battled Arven and received Legendary's Pokeball. +void checkpoint_09( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Battled Arven and received Legendary's Pokeball. +// end: Talked to Nemona at the Lighthouse. +void checkpoint_10( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_06.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_06.cpp index 7d55c80b94..0500b7a65e 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_06.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_06.cpp @@ -1,130 +1,128 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_06.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - - -std::string AutoStory_Segment_06::name() const{ - return "06: Go to Los Platos"; -} - -std::string AutoStory_Segment_06::start_text() const{ - return "Start: Battled Arven, received Legendary's Pokeball. Talked to Nemona at Lighthouse."; -} - -std::string AutoStory_Segment_06::end_text() const{ - return "End: At Los Platos Pokecenter."; -} - -void AutoStory_Segment_06::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 06: Go to Los Platos", COLOR_ORANGE); - env.console.overlay().add_log("Start Segment 06: Go to Los Platos", COLOR_ORANGE); - - checkpoint_11(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 06: Go to Los Platos", COLOR_GREEN); - env.console.overlay().add_log("End Segment 06: Go to Los Platos", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - - -void checkpoint_11( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - - context.wait_for_all_requests(); - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - realign_player(info, stream, context, PlayerRealignMode::REALIGN_NEW_MARKER, 100, 210, 100); - pbf_move_left_joystick(context, 128, 0, 187, 20); - pbf_move_left_joystick(context, 0, 128, 30, 8 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 128, 0, 1 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); - - realign_player(info, stream, context, PlayerRealignMode::REALIGN_NEW_MARKER, 100, 60, 200); - } - ); - - env.console.log("overworld_navigation: Go to Los Platos."); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 75, 75, true, true); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - - env.console.log("clear_dialog: Talk with Nemona at Los Platos. Clear Let's go tutorial. Stop when detect overworld."); - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::TUTORIAL, CallbackEnum::OVERWORLD}); - - context.wait_for_all_requests(); - - env.console.log("Reached Los Platos"); - env.console.overlay().add_log("Reached Los Platos", COLOR_WHITE); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_06.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + + +std::string AutoStory_Segment_06::name() const{ + return "06: Go to Los Platos"; +} + +std::string AutoStory_Segment_06::start_text() const{ + return "Start: Battled Arven, received Legendary's Pokeball. Talked to Nemona at Lighthouse."; +} + +std::string AutoStory_Segment_06::end_text() const{ + return "End: At Los Platos Pokecenter."; +} + +void AutoStory_Segment_06::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 06: Go to Los Platos", COLOR_ORANGE); + + checkpoint_11(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 06: Go to Los Platos", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + + +void checkpoint_11( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + + context.wait_for_all_requests(); + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + realign_player(info, stream, context, PlayerRealignMode::REALIGN_NEW_MARKER, 100, 210, 100); + pbf_move_left_joystick(context, 128, 0, 187, 20); + pbf_move_left_joystick(context, 0, 128, 30, 8 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 128, 0, 1 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); + + realign_player(info, stream, context, PlayerRealignMode::REALIGN_NEW_MARKER, 100, 60, 200); + } + ); + + env.console.log("overworld_navigation: Go to Los Platos."); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 75, 75, true, true); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + + env.console.log("clear_dialog: Talk with Nemona at Los Platos. Clear Let's go tutorial. Stop when detect overworld."); + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::TUTORIAL, CallbackEnum::OVERWORLD}); + + context.wait_for_all_requests(); + + env.console.log("Reached Los Platos"); + env.console.overlay().add_log("Reached Los Platos", COLOR_WHITE); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_06.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_06.h index 9d424ea682..a608b5f770 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_06.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_06.h @@ -1,40 +1,40 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_06_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_06_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_06 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: Talked to Nemona at the Lighthouse. -// end: Arrived at Los Platos pokecenter. Cleared Let's go tutorial. -void checkpoint_11( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_06_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_06_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_06 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: Talked to Nemona at the Lighthouse. +// end: Arrived at Los Platos pokecenter. Cleared Let's go tutorial. +void checkpoint_11( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_07.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_07.cpp index cf0a8c8fcd..74ff02c30f 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_07.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_07.cpp @@ -1,140 +1,138 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_07.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_07::name() const{ - return "07: Go to Mesagoza South"; -} - -std::string AutoStory_Segment_07::start_text() const{ - return "Start: At Los Platos Pokecenter."; -} - -std::string AutoStory_Segment_07::end_text() const{ - return "End: At Mesagoza South Pokecenter."; -} - -void AutoStory_Segment_07::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 07: Go to Mesagoza South", COLOR_ORANGE); - env.console.overlay().add_log("Start Segment 07: Go to Mesagoza South", COLOR_ORANGE); - - checkpoint_12(env, context, options.notif_status_update); - - // // Mystery Gift, delete later - // enter_menu_from_overworld(env.program_info(), env.console, context, 2); - // pbf_press_button(context, BUTTON_A, 20, 4 * TICKS_PER_SECOND); - // pbf_press_dpad(context, DPAD_UP, 20, 105); - // pbf_press_button(context, BUTTON_A, 20, 4 * TICKS_PER_SECOND); - // pbf_press_dpad(context, DPAD_DOWN, 20, 105); - // pbf_press_button(context, BUTTON_A, 20, 4 * TICKS_PER_SECOND); - // pbf_press_button(context, BUTTON_A, 20, 10 * TICKS_PER_SECOND); - // clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10); - - context.wait_for_all_requests(); - env.console.log("End Segment 07: Go to Mesagoza South", COLOR_GREEN); - env.console.overlay().add_log("End Segment 07: Go to Mesagoza South", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - -void checkpoint_12( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - // reset rate: ~25%. 12 resets out of 52. - // resets due to: getting attacked by wild pokemon, either from behind, - // or when lead pokemon not strong enough to clear them with Let's go - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - context.wait_for_all_requests(); - - // re-orient camera - pbf_press_button(context, BUTTON_L, 20, 20); - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - walk_forward_while_clear_front_path(env.program_info(), env.console, context, 35); - - // place the marker elsewhere - realign_player(info, env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 128, 50); - - DirectionDetector direction; - direction.change_direction(info, env.console, context, 0); - walk_forward_while_clear_front_path(info, env.console, context, 3300, 0, 125, 125); - - // check we're not still at the Los Platos Pokecenter. - confirm_no_overlapping_flypoint(info, env.console, context); - // not stuck at Los Platos Pokecenter - pbf_press_button(context, BUTTON_B, 20, 1 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_B, 20, 1 * TICKS_PER_SECOND); - press_Bs_to_back_to_overworld(info, env.console, context, 7); - - direction.change_direction(info, env.console, context, 0.29); - walk_forward_while_clear_front_path(info, env.console, context, 1200, 0, 125, 125); - direction.change_direction(info, env.console, context, 0.61); - walk_forward_while_clear_front_path(info, env.console, context, 1200, 0, 125, 125); - - fly_to_overlapping_flypoint(info, env.console, context); - } - ); - - env.console.log("Reached Mesagoza (South) Pokecenter."); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_07.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_07::name() const{ + return "07: Go to Mesagoza South"; +} + +std::string AutoStory_Segment_07::start_text() const{ + return "Start: At Los Platos Pokecenter."; +} + +std::string AutoStory_Segment_07::end_text() const{ + return "End: At Mesagoza South Pokecenter."; +} + +void AutoStory_Segment_07::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 07: Go to Mesagoza South", COLOR_ORANGE); + + checkpoint_12(env, context, options.notif_status_update); + + // // Mystery Gift, delete later + // enter_menu_from_overworld(env.program_info(), env.console, context, 2); + // pbf_press_button(context, BUTTON_A, 20, 4 * TICKS_PER_SECOND); + // pbf_press_dpad(context, DPAD_UP, 20, 105); + // pbf_press_button(context, BUTTON_A, 20, 4 * TICKS_PER_SECOND); + // pbf_press_dpad(context, DPAD_DOWN, 20, 105); + // pbf_press_button(context, BUTTON_A, 20, 4 * TICKS_PER_SECOND); + // pbf_press_button(context, BUTTON_A, 20, 10 * TICKS_PER_SECOND); + // clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10); + + context.wait_for_all_requests(); + env.console.log("End Segment 07: Go to Mesagoza South", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + +void checkpoint_12( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + // reset rate: ~25%. 12 resets out of 52. + // resets due to: getting attacked by wild pokemon, either from behind, + // or when lead pokemon not strong enough to clear them with Let's go + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + context.wait_for_all_requests(); + + // re-orient camera + pbf_press_button(context, BUTTON_L, 20, 20); + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + walk_forward_while_clear_front_path(env.program_info(), env.console, context, 35); + + // place the marker elsewhere + realign_player(info, env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 128, 50); + + DirectionDetector direction; + direction.change_direction(info, env.console, context, 0); + walk_forward_while_clear_front_path(info, env.console, context, 3300, 0, 125, 125); + + // check we're not still at the Los Platos Pokecenter. + confirm_no_overlapping_flypoint(info, env.console, context); + // not stuck at Los Platos Pokecenter + pbf_press_button(context, BUTTON_B, 20, 1 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_B, 20, 1 * TICKS_PER_SECOND); + press_Bs_to_back_to_overworld(info, env.console, context, 7); + + direction.change_direction(info, env.console, context, 0.29); + walk_forward_while_clear_front_path(info, env.console, context, 1200, 0, 125, 125); + direction.change_direction(info, env.console, context, 0.61); + walk_forward_while_clear_front_path(info, env.console, context, 1200, 0, 125, 125); + + fly_to_overlapping_flypoint(info, env.console, context); + } + ); + + env.console.log("Reached Mesagoza (South) Pokecenter."); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_07.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_07.h index b944d79f95..a059221d8b 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_07.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_07.h @@ -1,40 +1,40 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_07_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_07_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_07 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: Arrived at Los Platos pokecenter. Cleared Let's go tutorial. -// end: Arrived at Mesagoza (South) Pokecenter -void checkpoint_12( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_07_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_07_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_07 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: Arrived at Los Platos pokecenter. Cleared Let's go tutorial. +// end: Arrived at Mesagoza (South) Pokecenter +void checkpoint_12( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_08.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_08.cpp index d6b1911299..44e2a39401 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_08.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_08.cpp @@ -1,219 +1,219 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_08.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_08::name() const{ - return "08: Beat Team Star and arrive at School"; -} - -std::string AutoStory_Segment_08::start_text() const{ - return "Start: At Mesagoza South Pokecenter."; -} - -std::string AutoStory_Segment_08::end_text() const{ - return "End: Battled Team Star, talked to Jacq, standing in classroom."; -} - -void AutoStory_Segment_08::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 08: Beat Team Star and arrive at School", COLOR_ORANGE); - - checkpoint_13(env, context, options.notif_status_update); - checkpoint_14(env, context, options.notif_status_update); - checkpoint_15(env, context, options.notif_status_update); - - - context.wait_for_all_requests(); - env.console.log("End Segment 08: Beat Team Star and arrive at School", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - -void checkpoint_13( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - // reset rate: 0%. 0 resets out of 70. - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - - fly_to_overlapping_flypoint(info, env.console, context); - - context.wait_for_all_requests(); - realign_player(info, env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 80, 50); - walk_forward_while_clear_front_path(info, env.console, context, 500); - walk_forward_until_dialog(info, env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 30); - }); - - env.console.log("clear_dialog: Talk with Nemona at Mesagoza gate. Stop when detect battle."); - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, - {CallbackEnum::PROMPT_DIALOG, CallbackEnum::DIALOG_ARROW, CallbackEnum::BATTLE}); - - env.console.log("run_battle_press_A: Battle with Nemona at Mesagoza gate. Stop when detect dialog."); - // story continues even if you lose - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG); - - env.console.log("clear_dialog: Talk with Nemona within Mesagoza. Stop when detect overworld."); - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, - {CallbackEnum::OVERWORLD, CallbackEnum::PROMPT_DIALOG, CallbackEnum::WHITE_A_BUTTON}); - - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_14( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - // realign diagonally to the left - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 80, 0, 100); - // walk forward so you're off center - pbf_move_left_joystick(context, 128, 0, 100, 100); - // realign going straight - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 128, 0, 100); - // walk forward, while still off center - pbf_move_left_joystick(context, 128, 0, 2000, 100); - // realign diagonally to the right - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 178, 0, 100); - // walk forward so you're closer to the center - pbf_move_left_joystick(context, 128, 0, 150, 100); - // realign going straight - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 128, 0, 100); - // walk forward until hit dialog at top of stairs - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 60); - // clear dialog until battle. with prompt, battle - env.console.log("clear_dialog: Talk with Team Star at the top of the stairs. Stop when detect battle."); - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::PROMPT_DIALOG, CallbackEnum::BATTLE, CallbackEnum::DIALOG_ARROW}); - // run battle until dialog - env.console.log("run_battle_press_A: Battle with Team Star grunt 1. Stop when detect dialog."); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {}, true); - // clear dialog until battle, with prompt, white button, tutorial, battle - env.console.log("clear_dialog: Talk with Team Star and Nemona. Receive Tera orb. Stop when detect battle."); - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, - {CallbackEnum::PROMPT_DIALOG, CallbackEnum::WHITE_A_BUTTON, CallbackEnum::TUTORIAL, CallbackEnum::BATTLE, CallbackEnum::DIALOG_ARROW}); - // run battle until dialog - env.console.log("run_battle_press_A: Battle with Team Star grunt 2. Stop when detect dialog."); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {}, true); - // clear dialog until overworld - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD}); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_15( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - // realign diagonally to the right - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 178, 0, 100); - // walk forward so you're closer to the center - pbf_move_left_joystick(context, 128, 0, 100, 100); - // realign going straight - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 128, 0, 100); - // walk forward up stairs - pbf_move_left_joystick(context, 128, 0, 1000, 100); - // realign going straight - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - // walk forward until hit dialog inside the school - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 60); - - env.console.log("clear_dialog: Talk with Nemona, Clavell, and Jacq inside the school. Stop when detect overworld."); - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, - {CallbackEnum::PROMPT_DIALOG, CallbackEnum::OVERWORLD}); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_08.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_08::name() const{ + return "08: Beat Team Star and arrive at School"; +} + +std::string AutoStory_Segment_08::start_text() const{ + return "Start: At Mesagoza South Pokecenter."; +} + +std::string AutoStory_Segment_08::end_text() const{ + return "End: Battled Team Star, talked to Jacq, standing in classroom."; +} + +void AutoStory_Segment_08::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 08: Beat Team Star and arrive at School", COLOR_ORANGE); + + checkpoint_13(env, context, options.notif_status_update); + checkpoint_14(env, context, options.notif_status_update); + checkpoint_15(env, context, options.notif_status_update); + + + context.wait_for_all_requests(); + env.console.log("End Segment 08: Beat Team Star and arrive at School", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + +void checkpoint_13( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + // reset rate: 0%. 0 resets out of 70. + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + + fly_to_overlapping_flypoint(info, env.console, context); + + context.wait_for_all_requests(); + realign_player(info, env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 80, 50); + walk_forward_while_clear_front_path(info, env.console, context, 500); + walk_forward_until_dialog(info, env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 30); + }); + + env.console.log("clear_dialog: Talk with Nemona at Mesagoza gate. Stop when detect battle."); + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, + {CallbackEnum::PROMPT_DIALOG, CallbackEnum::DIALOG_ARROW, CallbackEnum::BATTLE}); + + env.console.log("run_battle_press_A: Battle with Nemona at Mesagoza gate. Stop when detect dialog."); + // story continues even if you lose + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG); + + env.console.log("clear_dialog: Talk with Nemona within Mesagoza. Stop when detect overworld."); + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, + {CallbackEnum::OVERWORLD, CallbackEnum::PROMPT_DIALOG, CallbackEnum::WHITE_A_BUTTON}); + + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_14( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + // realign diagonally to the left + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 80, 0, 100); + // walk forward so you're off center + pbf_move_left_joystick(context, 128, 0, 100, 100); + // realign going straight + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 128, 0, 100); + // walk forward, while still off center + pbf_move_left_joystick(context, 128, 0, 2000, 100); + // realign diagonally to the right + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 178, 0, 100); + // walk forward so you're closer to the center + pbf_move_left_joystick(context, 128, 0, 150, 100); + // realign going straight + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 128, 0, 100); + // walk forward until hit dialog at top of stairs + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 60); + // clear dialog until battle. with prompt, battle + env.console.log("clear_dialog: Talk with Team Star at the top of the stairs. Stop when detect battle."); + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::PROMPT_DIALOG, CallbackEnum::BATTLE, CallbackEnum::DIALOG_ARROW}); + // run battle until dialog + env.console.log("run_battle_press_A: Battle with Team Star grunt 1. Stop when detect dialog."); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {}, true); + // clear dialog until battle, with prompt, white button, tutorial, battle + env.console.log("clear_dialog: Talk with Team Star and Nemona. Receive Tera orb. Stop when detect battle."); + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, + {CallbackEnum::PROMPT_DIALOG, CallbackEnum::WHITE_A_BUTTON, CallbackEnum::TUTORIAL, CallbackEnum::BATTLE, CallbackEnum::DIALOG_ARROW}); + // run battle until dialog + env.console.log("run_battle_press_A: Battle with Team Star grunt 2. Stop when detect dialog."); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {}, true); + // clear dialog until overworld + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD}); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_15( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + // realign diagonally to the right + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 178, 0, 100); + // walk forward so you're closer to the center + pbf_move_left_joystick(context, 128, 0, 100, 100); + // realign going straight + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 128, 0, 100); + // walk forward up stairs + pbf_move_left_joystick(context, 128, 0, 1000, 100); + // realign going straight + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + // walk forward until hit dialog inside the school + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 60); + + env.console.log("clear_dialog: Talk with Nemona, Clavell, and Jacq inside the school. Stop when detect overworld."); + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, + {CallbackEnum::PROMPT_DIALOG, CallbackEnum::OVERWORLD}); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_08.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_08.h index 5ce89fc278..7f9dbffae7 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_08.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_08.h @@ -1,57 +1,57 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_08_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_08_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_08 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - -// start: Arrived at Mesagoza (South) Pokecenter -// end: Battled Nemona at Mesagoza gate. Entered Mesagoza. -void checkpoint_13( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Battled Nemona at Mesagoza gate. Entered Mesagoza. -// end: Battled Team Star at school entrance. -void checkpoint_14( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Battled Team Star at school entrance. -// end: Talked to Jacq in classroom. Standing in classroom. -void checkpoint_15( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_08_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_08_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_08 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + +// start: Arrived at Mesagoza (South) Pokecenter +// end: Battled Nemona at Mesagoza gate. Entered Mesagoza. +void checkpoint_13( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Battled Nemona at Mesagoza gate. Entered Mesagoza. +// end: Battled Team Star at school entrance. +void checkpoint_14( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Battled Team Star at school entrance. +// end: Talked to Jacq in classroom. Standing in classroom. +void checkpoint_15( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_09.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_09.cpp index 0671f97fc5..5ea17d0e09 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_09.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_09.cpp @@ -1,323 +1,323 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_09.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_09::name() const{ - return "09: Complete tutorial"; -} - -std::string AutoStory_Segment_09::start_text() const{ - return "Start: Battled Team Star, talked to Jacq, standing in classroom."; -} - -std::string AutoStory_Segment_09::end_text() const{ - return "End: Finished tutorial. Acquired all 3 questlines. Got on ride for first time."; -} - -void AutoStory_Segment_09::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.overlay().add_log("Start Segment 09: Complete tutorial", COLOR_ORANGE); - - checkpoint_16(env, context, options.notif_status_update); - checkpoint_17(env, context, options.notif_status_update); - checkpoint_18(env, context, options.notif_status_update); - checkpoint_19(env, context, options.notif_status_update); - checkpoint_20(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 09: Complete tutorial", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - - - -void checkpoint_16( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - // walk left - pbf_move_left_joystick(context, 0, 128, 400, 100); - // walk down to classroom exit. - pbf_move_left_joystick(context, 128, 255, 300, 100); - env.console.log("clear_dialog: Leave classroom."); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 5); - - // Wait for detection of school navigation menu - wait_for_gradient_arrow(env.program_info(), env.console, context, {0.031, 0.193, 0.047, 0.078}, 5); - - // enter Cafeteria - pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); - pbf_wait(context, 3 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - - // walk forward - pbf_move_left_joystick(context, 128, 0, 600, 100); - // turn left - pbf_move_left_joystick(context, 0, 128, 20, 100); - - // talk to Arven. stop at overworld. need prompt, overworld, white button A. and book? - env.console.log("Talk with Arven. Receive Titan questline (Path of Legends)."); - press_A_until_dialog(env.program_info(), env.console, context, 1); - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_17( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - // walk backwards until dialog - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20, 128, 255); - env.console.log("Talk with Cassiopeia."); - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - // re-orient camera - pbf_press_button(context, BUTTON_L, 20, 100); - // move backwards towards front desk - pbf_move_left_joystick(context, 128, 255, 200, 100); - // re-orient camera - pbf_press_button(context, BUTTON_L, 20, 100); - // move right towards navigation kiosk - pbf_move_left_joystick(context, 255, 128, 100, 100); - // open school navigation screen - press_button_until_gradient_arrow(env.program_info(), env.console, context, {0.031, 0.193, 0.047, 0.078}); - // go to staff room - navigate_school_layout_menu(env.program_info(), env.console, context, {0.031, 0.193, 0.047, 0.078}, - {0.031, 0.193 + 0.074219, 0.047, 0.078}, DPAD_DOWN, 1); - // enter staff room - pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); - pbf_wait(context, 3 * TICKS_PER_SECOND); - - env.console.log("clear_dialog: See Geeta. Talk to Nemona. Receive Gym/Elite Four questline (Victory Road)."); - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, - {CallbackEnum::OVERWORLD, CallbackEnum::PROMPT_DIALOG}); - - - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_18( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - // walk down - pbf_move_left_joystick(context, 128, 255, 200, 100); - // walk left towards door - pbf_move_left_joystick(context, 0, 128, 100, 100); - - // wait for school navigation menu - context.wait_for_all_requests(); - wait_for_gradient_arrow(env.program_info(), env.console, context, {0.031, 0.193, 0.047, 0.078}, 10); - // enter Directors office - pbf_mash_button(context, BUTTON_A, 6 * TICKS_PER_SECOND); - - env.console.log("Talk to Clavell in his office, and the professor."); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 25, - {CallbackEnum::PROMPT_DIALOG}); // max time between dialog: 17s. set timeout to 25 seconds for buffer. - // mash A to get through the Random A press that you need. when the professor shows you area zero. - pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, - {CallbackEnum::OVERWORLD, CallbackEnum::PROMPT_DIALOG}); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_19( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - // walk right - pbf_move_left_joystick(context, 255, 128, 50, 100); - // walk down towards door - pbf_move_left_joystick(context, 128, 255, 200, 100); - - env.console.log("Talk to Nemona and go to dorm."); - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - // walk forward - pbf_move_left_joystick(context, 128, 0, 100, 100); - // walk left towards bed - pbf_move_left_joystick(context, 0, 128, 100, 100); - - env.console.log("Go to bed. Time passes until treasure hunt."); - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - -void checkpoint_20( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - //walk right towards door - pbf_move_left_joystick(context, 255, 128, 200, 100); - - wait_for_gradient_arrow(env.program_info(), env.console, context, {0.031, 0.193, 0.047, 0.078}, 10); - - env.console.log("Leave dorm for schoolyard."); - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 60, 128, 0); - - env.console.log("Talk to Nemona, Arven, Cassiopeia."); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 16, - {CallbackEnum::PROMPT_DIALOG, CallbackEnum::BLACK_DIALOG_BOX}); // max time between dialog: 11 - - // mash A to get through the Random A press that you need. when the Nemona shows you a Poke Gym. - pbf_mash_button(context, BUTTON_A, 250); - - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10, - {CallbackEnum::TUTORIAL}); // max time between dialog: 3 - - env.console.log("Get on ride."); - pbf_mash_button(context, BUTTON_PLUS, 1 * TICKS_PER_SECOND); - - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_09.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_09::name() const{ + return "09: Complete tutorial"; +} + +std::string AutoStory_Segment_09::start_text() const{ + return "Start: Battled Team Star, talked to Jacq, standing in classroom."; +} + +std::string AutoStory_Segment_09::end_text() const{ + return "End: Finished tutorial. Acquired all 3 questlines. Got on ride for first time."; +} + +void AutoStory_Segment_09::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 09: Complete tutorial", COLOR_ORANGE); + + checkpoint_16(env, context, options.notif_status_update); + checkpoint_17(env, context, options.notif_status_update); + checkpoint_18(env, context, options.notif_status_update); + checkpoint_19(env, context, options.notif_status_update); + checkpoint_20(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 09: Complete tutorial", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + + + +void checkpoint_16( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + // walk left + pbf_move_left_joystick(context, 0, 128, 400, 100); + // walk down to classroom exit. + pbf_move_left_joystick(context, 128, 255, 300, 100); + env.console.log("clear_dialog: Leave classroom."); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 5); + + // Wait for detection of school navigation menu + wait_for_gradient_arrow(env.program_info(), env.console, context, {0.031, 0.193, 0.047, 0.078}, 5); + + // enter Cafeteria + pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); + pbf_wait(context, 3 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + + // walk forward + pbf_move_left_joystick(context, 128, 0, 600, 100); + // turn left + pbf_move_left_joystick(context, 0, 128, 20, 100); + + // talk to Arven. stop at overworld. need prompt, overworld, white button A. and book? + env.console.log("Talk with Arven. Receive Titan questline (Path of Legends)."); + press_A_until_dialog(env.program_info(), env.console, context, 1); + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_17( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + // walk backwards until dialog + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20, 128, 255); + env.console.log("Talk with Cassiopeia."); + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + // re-orient camera + pbf_press_button(context, BUTTON_L, 20, 100); + // move backwards towards front desk + pbf_move_left_joystick(context, 128, 255, 200, 100); + // re-orient camera + pbf_press_button(context, BUTTON_L, 20, 100); + // move right towards navigation kiosk + pbf_move_left_joystick(context, 255, 128, 100, 100); + // open school navigation screen + press_button_until_gradient_arrow(env.program_info(), env.console, context, {0.031, 0.193, 0.047, 0.078}); + // go to staff room + navigate_school_layout_menu(env.program_info(), env.console, context, {0.031, 0.193, 0.047, 0.078}, + {0.031, 0.193 + 0.074219, 0.047, 0.078}, DPAD_DOWN, 1); + // enter staff room + pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); + pbf_wait(context, 3 * TICKS_PER_SECOND); + + env.console.log("clear_dialog: See Geeta. Talk to Nemona. Receive Gym/Elite Four questline (Victory Road)."); + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, + {CallbackEnum::OVERWORLD, CallbackEnum::PROMPT_DIALOG}); + + + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_18( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + // walk down + pbf_move_left_joystick(context, 128, 255, 200, 100); + // walk left towards door + pbf_move_left_joystick(context, 0, 128, 100, 100); + + // wait for school navigation menu + context.wait_for_all_requests(); + wait_for_gradient_arrow(env.program_info(), env.console, context, {0.031, 0.193, 0.047, 0.078}, 10); + // enter Directors office + pbf_mash_button(context, BUTTON_A, 6 * TICKS_PER_SECOND); + + env.console.log("Talk to Clavell in his office, and the professor."); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 25, + {CallbackEnum::PROMPT_DIALOG}); // max time between dialog: 17s. set timeout to 25 seconds for buffer. + // mash A to get through the Random A press that you need. when the professor shows you area zero. + pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, + {CallbackEnum::OVERWORLD, CallbackEnum::PROMPT_DIALOG}); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_19( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + // walk right + pbf_move_left_joystick(context, 255, 128, 50, 100); + // walk down towards door + pbf_move_left_joystick(context, 128, 255, 200, 100); + + env.console.log("Talk to Nemona and go to dorm."); + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + // walk forward + pbf_move_left_joystick(context, 128, 0, 100, 100); + // walk left towards bed + pbf_move_left_joystick(context, 0, 128, 100, 100); + + env.console.log("Go to bed. Time passes until treasure hunt."); + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + +void checkpoint_20( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + //walk right towards door + pbf_move_left_joystick(context, 255, 128, 200, 100); + + wait_for_gradient_arrow(env.program_info(), env.console, context, {0.031, 0.193, 0.047, 0.078}, 10); + + env.console.log("Leave dorm for schoolyard."); + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 60, 128, 0); + + env.console.log("Talk to Nemona, Arven, Cassiopeia."); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 16, + {CallbackEnum::PROMPT_DIALOG, CallbackEnum::BLACK_DIALOG_BOX}); // max time between dialog: 11 + + // mash A to get through the Random A press that you need. when the Nemona shows you a Poke Gym. + pbf_mash_button(context, BUTTON_A, 250); + + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10, + {CallbackEnum::TUTORIAL}); // max time between dialog: 3 + + env.console.log("Get on ride."); + pbf_mash_button(context, BUTTON_PLUS, 1 * TICKS_PER_SECOND); + + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_09.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_09.h index f4719142f8..f2f97eadac 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_09.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_09.h @@ -1,73 +1,73 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_09_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_09_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_09 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: Talked to Jacq in classroom. Standing in classroom. -// end: Talked to Arven. Received Titan questline (Path of Legends). Talked to Cassiopeia. Standing in main hall. -void checkpoint_16( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Talked to Arven. Received Titan questline (Path of Legends). -// end: Talked to Cassiopeia. Saw Geeta. Talked to Nemona. Received Gym/Elite Four questline (Victory Road). Standing in staff room. -void checkpoint_17( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Talked to Cassiopeia. Saw Geeta. Talked to Nemona. Received Gym/Elite Four questline (Victory Road). Standing in staff room. -// end: Talked to Clavell and the professor. -void checkpoint_18( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Talked to Clavell and the professor. -// end: Talked to Nemona, visited dorm, time passed. -void checkpoint_19( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Talked to Nemona, visited dorm, time passed. -// end: Get on ride for first time. -void checkpoint_20( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_09_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_09_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_09 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: Talked to Jacq in classroom. Standing in classroom. +// end: Talked to Arven. Received Titan questline (Path of Legends). Talked to Cassiopeia. Standing in main hall. +void checkpoint_16( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Talked to Arven. Received Titan questline (Path of Legends). +// end: Talked to Cassiopeia. Saw Geeta. Talked to Nemona. Received Gym/Elite Four questline (Victory Road). Standing in staff room. +void checkpoint_17( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Talked to Cassiopeia. Saw Geeta. Talked to Nemona. Received Gym/Elite Four questline (Victory Road). Standing in staff room. +// end: Talked to Clavell and the professor. +void checkpoint_18( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Talked to Clavell and the professor. +// end: Talked to Nemona, visited dorm, time passed. +void checkpoint_19( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Talked to Nemona, visited dorm, time passed. +// end: Get on ride for first time. +void checkpoint_20( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_10.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_10.cpp index 1a5347b46d..ef5d26d23b 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_10.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_10.cpp @@ -1,321 +1,321 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_10.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_10::name() const{ - return "10.1: Cortondo Gym - Go to Cortondo city"; -} - -std::string AutoStory_Segment_10::start_text() const{ - return "Start: After the break, with level 100 Gardevoir. At Mesagoza West pokecenter."; -} - -std::string AutoStory_Segment_10::end_text() const{ - return "End: At Cortondo East Pokecenter."; -} - -void AutoStory_Segment_10::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.overlay().add_log("Start Segment 10.1: Cortondo Gym - Go to Cortondo city", COLOR_ORANGE); - - checkpoint_21(env, context, options.notif_status_update); - checkpoint_22(env, context, options.notif_status_update); - checkpoint_23(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 10.1: Cortondo Gym - Go to Cortondo city", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - -void checkpoint_21( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - context.wait_for_all_requests(); - pbf_press_button(context, BUTTON_L, 20, 20); - // move forward - pbf_move_left_joystick(context, 128, 0, 30, 100); - // get on ride - get_on_ride(env.program_info(), env.console, context); - // turn left - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NO_MARKER, 0, 128, 50); - // move forward - pbf_move_left_joystick(context, 128, 0, 100, 100); - - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 200, 70); - pbf_move_left_joystick(context, 128, 0, 400, 100); - - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 128, 70); - pbf_move_left_joystick(context, 128, 0, 700, 100); - - // turn towards wall - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 128, 0, 50); - pbf_move_left_joystick(context, 128, 0, 200, 100); - // run and jump over wall - pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 100); - - BlackScreenOverWatcher black_screen(COLOR_RED, { 0.2, 0.2, 0.6, 0.6 }); - int ret = wait_until( - env.console, context, - std::chrono::seconds(30), - { black_screen } - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "checkpoint_21(): Failed to jump the East Mesagoza wall.", - env.console - ); - } - context.wait_for_all_requests(); - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_22( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - // section 1 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 128, 80}, - {ZoomChange::KEEP_ZOOM, 255, 80, 37} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 40, 20); - - // section 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 128, 40}, - {ZoomChange::KEEP_ZOOM, 255, 255, 27} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 15); - - // section 3. set marker to pokecenter - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 128, 128, 0}, - {ZoomChange::KEEP_ZOOM, 128, 128, 0} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 15); - - // section 3. set marker past pokecenter - handle_unexpected_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 70, 30); - }); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 20, 12, 12); - - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - -void checkpoint_23( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - // section 1 - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 110, 0, 30); - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10); - - // section 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 128, 80}, - {ZoomChange::KEEP_ZOOM, 255, 95, 100} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 255, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 3 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 128, 80}, - {ZoomChange::KEEP_ZOOM, 255, 75, 65} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 255, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 4 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 128, 50}, - {ZoomChange::KEEP_ZOOM, 255, 180, 17} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 40, 10); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 255, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 5. set marker to pokecenter - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 128, 128, 0}, - {ZoomChange::KEEP_ZOOM, 128, 128, 0} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 255, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 6. set marker past pokecenter - handle_unexpected_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 110, 50); - }); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 15, 12, 12); - - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_10.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_10::name() const{ + return "10.1: Cortondo Gym - Go to Cortondo city"; +} + +std::string AutoStory_Segment_10::start_text() const{ + return "Start: After the break, with level 100 Gardevoir. At Mesagoza West pokecenter."; +} + +std::string AutoStory_Segment_10::end_text() const{ + return "End: At Cortondo East Pokecenter."; +} + +void AutoStory_Segment_10::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 10.1: Cortondo Gym - Go to Cortondo city", COLOR_ORANGE); + + checkpoint_21(env, context, options.notif_status_update); + checkpoint_22(env, context, options.notif_status_update); + checkpoint_23(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 10.1: Cortondo Gym - Go to Cortondo city", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + +void checkpoint_21( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + context.wait_for_all_requests(); + pbf_press_button(context, BUTTON_L, 20, 20); + // move forward + pbf_move_left_joystick(context, 128, 0, 30, 100); + // get on ride + get_on_ride(env.program_info(), env.console, context); + // turn left + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NO_MARKER, 0, 128, 50); + // move forward + pbf_move_left_joystick(context, 128, 0, 100, 100); + + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 200, 70); + pbf_move_left_joystick(context, 128, 0, 400, 100); + + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 128, 70); + pbf_move_left_joystick(context, 128, 0, 700, 100); + + // turn towards wall + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 128, 0, 50); + pbf_move_left_joystick(context, 128, 0, 200, 100); + // run and jump over wall + pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 100); + + BlackScreenOverWatcher black_screen(COLOR_RED, { 0.2, 0.2, 0.6, 0.6 }); + int ret = wait_until( + env.console, context, + std::chrono::seconds(30), + { black_screen } + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "checkpoint_21(): Failed to jump the East Mesagoza wall.", + env.console + ); + } + context.wait_for_all_requests(); + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_22( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + // section 1 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 128, 80}, + {ZoomChange::KEEP_ZOOM, 255, 80, 37} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 40, 20); + + // section 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 128, 40}, + {ZoomChange::KEEP_ZOOM, 255, 255, 27} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 15); + + // section 3. set marker to pokecenter + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 128, 128, 0}, + {ZoomChange::KEEP_ZOOM, 128, 128, 0} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 15); + + // section 3. set marker past pokecenter + handle_unexpected_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 70, 30); + }); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 20, 12, 12); + + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + +void checkpoint_23( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + // section 1 + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 110, 0, 30); + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10); + + // section 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 128, 80}, + {ZoomChange::KEEP_ZOOM, 255, 95, 100} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 255, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 3 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 128, 80}, + {ZoomChange::KEEP_ZOOM, 255, 75, 65} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 255, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 4 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 128, 50}, + {ZoomChange::KEEP_ZOOM, 255, 180, 17} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 40, 10); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 255, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 5. set marker to pokecenter + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 128, 128, 0}, + {ZoomChange::KEEP_ZOOM, 128, 128, 0} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 255, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 6. set marker past pokecenter + handle_unexpected_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 110, 50); + }); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 15, 12, 12); + + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_10.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_10.h index a007e24fe3..e7026478e7 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_10.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_10.h @@ -1,57 +1,57 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_10_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_10_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_10 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: After the break, with level 100 Gardevoir. At Mesagoza West pokecenter. -// end: At Mesagoza West gate flypoint -void checkpoint_21( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: At Mesagoza West gate flypoint -// end: At South Province Area Two Pokecenter. -void checkpoint_22( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: At South Province Area Two Pokecenter. -// end: At Cortondo East Pokecenter -void checkpoint_23( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_10_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_10_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_10 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: After the break, with level 100 Gardevoir. At Mesagoza West pokecenter. +// end: At Mesagoza West gate flypoint +void checkpoint_21( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: At Mesagoza West gate flypoint +// end: At South Province Area Two Pokecenter. +void checkpoint_22( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: At South Province Area Two Pokecenter. +// end: At Cortondo East Pokecenter +void checkpoint_23( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_11.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_11.cpp index b2c507e2b1..aadc8cd65d 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_11.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_11.cpp @@ -1,625 +1,625 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h" -#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_OliveActionFailedException.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_11.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - - -std::string AutoStory_Segment_11::name() const{ - return "10.2: Cortondo Gym - Gym challenge"; -} - -std::string AutoStory_Segment_11::start_text() const{ - return "Start: At Cortondo East Pokecenter."; -} - -std::string AutoStory_Segment_11::end_text() const{ - return "End: Beat Cortondo Gym challenge. At Cortondo West Pokecenter."; -} - -void AutoStory_Segment_11::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.overlay().add_log("Start Segment 10.2: Cortondo Gym - Gym challenge", COLOR_ORANGE); - - checkpoint_24(env, context, options.notif_status_update); - checkpoint_25(env, context, options.notif_status_update); - checkpoint_26(env, context, options.notif_status_update); - checkpoint_27(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 10.2: Cortondo Gym - Gym challenge", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - -void checkpoint_24( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - DirectionDetector direction; - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - direction.change_direction(env.program_info(), env.console, context, 2.71); - pbf_move_left_joystick(context, 128, 0, 375, 100); - direction.change_direction(env.program_info(), env.console, context, 1.26); - pbf_move_left_joystick(context, 128, 0, 1750, 100); - }); - - direction.change_direction(env.program_info(), env.console, context, 2.73); - pbf_move_left_joystick(context, 128, 0, 200, 100); - pbf_wait(context, 5 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 0, 100, 20); - }, - 5, 5 - ); - // enter gym building. talk go Nemona - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - // talk to receptionist - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10); - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD}); - - pbf_move_left_joystick(context, 128, 255, 500, 100); - pbf_wait(context, 3 * TICKS_PER_SECOND); - // wait for overworld after leaving gym - wait_for_overworld(env.program_info(), env.console, context, 30); - - pbf_move_left_joystick(context, 128, 0, 450, 100); - direction.change_direction(env.program_info(), env.console, context, 1.26); - pbf_move_left_joystick(context, 128, 0, 1600, 100); - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - -void checkpoint_25( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - // section 1. align to Olive roll NPC - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 157, 0, 40); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 40, 10); - - // section 1.1. keep walking forward and talk to Olive roll NPC - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10); - } - ); - mash_button_till_overworld(env.console, context, BUTTON_A); - - // section 2 - pbf_move_left_joystick(context, 128, 0, 1300, 100); - - // section 3 - DirectionDetector direction; - direction.change_direction(env.program_info(), env.console, context, 6.0); - pbf_move_left_joystick(context, 128, 0, 700, 100); - - // section 4. align to corner - direction.change_direction(env.program_info(), env.console, context, 4.69); - pbf_move_left_joystick(context, 128, 0, 150, 100); - - // section 5. battle first NPC - direction.change_direction(env.program_info(), env.console, context, 1.485); - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10, 128, 20); - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::DIALOG_ARROW}); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG); - mash_button_till_overworld(env.console, context, BUTTON_A); - - // section 6 - direction.change_direction(env.program_info(), env.console, context, 5.95); - pbf_move_left_joystick(context, 128, 0, 1000, 100); - - // section 7 - direction.change_direction(env.program_info(), env.console, context, 1.327); - pbf_move_left_joystick(context, 128, 0, 700, 100); - - // section 8 - direction.change_direction(env.program_info(), env.console, context, 6.106); - pbf_move_left_joystick(context, 128, 0, 200, 100); - - // section 9. battle second NPC - direction.change_direction(env.program_info(), env.console, context, 4.275); - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10, 128, 20); - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::DIALOG_ARROW}); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG); - mash_button_till_overworld(env.console, context, BUTTON_A); - - // section 10. leave Olive roll - pbf_mash_button(context, BUTTON_Y, 100); - clear_dialog(env.console, context, ClearDialogMode::STOP_PROMPT, 60, {CallbackEnum::PROMPT_DIALOG}); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 15, {CallbackEnum::PROMPT_DIALOG}); - wait_for_overworld(env.program_info(), env.console, context); - enter_menu_from_overworld(env.program_info(), env.console, context, -1); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_26( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - // change the time of day: close game, change time to 5:45 am. - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - change_date(env, context, {2025, 1, 1, 5, 45, 0}); - reset_game_from_home(env.program_info(), env.console, context); - - // talk to Olive roll NPC - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10, 128, 20); - mash_button_till_overworld(env.console, context, BUTTON_A); - - // section 1 - pbf_move_left_joystick(context, 128, 0, 400, 50); - OliveDetector green(env.console); - size_t MAX_ATTEMPTS_SECTION_1 = 2; - uint16_t ticks_to_walk_for_section1 = 650; - uint16_t push_strength_section_1 = 75; - for (size_t i = 0; i < MAX_ATTEMPTS_SECTION_1; i++){ - try{ - green.push_olive_forward(env.program_info(), env.console, context, 4.38, ticks_to_walk_for_section1, push_strength_section_1); - // green.align_to_olive(env.program_info(), env.console, context, 4.38); - green.walk_up_to_olive(env.program_info(), env.console, context, 4.38); - break; - }catch (OliveActionFailedException& e){ - if (e.m_fail_reason == OliveFail::OLIVE_STUCK){ - // if olive is stuck, we might have pushed the olive all the way to the end. so we can try moving on. - break; - } - - if (i >= MAX_ATTEMPTS_SECTION_1-1){ - throw e; - } - if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED || e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE){ - // may have walked past olive - pbf_move_left_joystick(context, 128, 255, 200, 50); - pbf_wait(context, 5 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - ticks_to_walk_for_section1 = 100; - push_strength_section_1 = 50; - }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE - throw e; - } - - } - } - - - // section 1b. realign using fence corner - DirectionDetector direction; - direction.change_direction(env.program_info(), env.console, context, 2.74); - pbf_move_left_joystick(context, 128, 0, 200, 50); - direction.change_direction(env.program_info(), env.console, context, 4.328); - pbf_move_left_joystick(context, 128, 0, 200, 50); - direction.change_direction(env.program_info(), env.console, context, 1.22); - pbf_move_left_joystick(context, 128, 0, 75, 50); - - // section 2.1 nudge olive straight - size_t MAX_ATTEMPTS_SECTION_2_1 = 2; - for (size_t i = 0; i < MAX_ATTEMPTS_SECTION_2_1; i++){ - try{ - green.push_olive_forward(env.program_info(), env.console, context, 5.95, 50, 50); - break; - }catch (OliveActionFailedException& e){ - if (i >= MAX_ATTEMPTS_SECTION_2_1-1){ - throw e; - } - - if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED){ - pbf_move_left_joystick(context, 128, 255, 250, 50); - pbf_move_left_joystick(context, 128, 0, 50, 50); // move forward slight in case the olive is undetectable since it's right in front of the character - pbf_wait(context, 5 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - }else if (e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE || e.m_fail_reason == OliveFail::OLIVE_STUCK){ - // try moving back and then ramming forward - pbf_move_left_joystick(context, 128, 255, 50, 50); - pbf_move_left_joystick(context, 128, 0, 150, 50); - pbf_wait(context, 7 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - break; // then move on to next section - }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE, - throw e; - } - - } - } - - pbf_move_left_joystick(context, 128, 255, 100, 50); - green.align_to_olive(env.program_info(), env.console, context, 5.95); - pbf_move_left_joystick(context, 128, 255, 500, 50); - - // section 2.2 push at angle towards outer fence - size_t MAX_ATTEMPTS_SECTION_2_2 = 2; - // uint16_t ticks_walked_section2_2 = 0; - for (size_t i = 0; i < MAX_ATTEMPTS_SECTION_2_2; i++){ - try{ - green.push_olive_forward(env.program_info(), env.console, context, 5.8, 250, 50); - break; - }catch (OliveActionFailedException& e){ - if (i >= MAX_ATTEMPTS_SECTION_2_2-1){ - throw e; - } - - if (e.m_fail_reason == OliveFail::OLIVE_STUCK){ // olive possibly stuck on fence - pbf_move_left_joystick(context, 128, 255, 20, 50); - pbf_move_left_joystick(context, 0, 128, 100, 50); - pbf_move_left_joystick(context, 128, 0, 200, 50); - // push olive parallel to fence - green.align_to_olive(env.program_info(), env.console, context, 4.28, 20); - green.walk_up_to_olive(env.program_info(), env.console, context, 4.28); - green.push_olive_forward(env.program_info(), env.console, context, 4.28, 100); - green.align_to_olive(env.program_info(), env.console, context, 4.28, 20); - green.walk_up_to_olive(env.program_info(), env.console, context, 4.28); - // back off - pbf_move_left_joystick(context, 128, 255, 50, 50); - // realign using fence corner - direction.change_direction(env.program_info(), env.console, context, 2.74); - pbf_move_left_joystick(context, 128, 0, 400, 50); - direction.change_direction(env.program_info(), env.console, context, 4.328); - pbf_move_left_joystick(context, 128, 0, 400, 50); - direction.change_direction(env.program_info(), env.console, context, 1.22); - pbf_move_left_joystick(context, 128, 0, 100, 50); - }else if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED){ - pbf_move_left_joystick(context, 128, 255, 200, 50); - pbf_wait(context, 5 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - - }else if (e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE){ - // try moving back and then ramming forward - pbf_move_left_joystick(context, 128, 255, 50, 50); - pbf_move_left_joystick(context, 128, 0, 150, 50); - pbf_wait(context, 7 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE, - // continue trying to push the olive. at a different angle - break; - } - } - } - - pbf_move_left_joystick(context, 128, 255, 100, 50); - green.align_to_olive(env.program_info(), env.console, context, 5.95); - pbf_move_left_joystick(context, 128, 255, 500, 50); - - // section 2.3 push olive past first NPC - uint16_t ticks_to_walk_for_section2_3 = 950; - size_t MAX_ATTEMPTS = 2; - for (size_t i = 0; i < MAX_ATTEMPTS; i++){ - try{ - green.push_olive_forward(env.program_info(), env.console, context, 5.95, ticks_to_walk_for_section2_3, 75, 10); - // green.align_to_olive(env.program_info(), env.console, context, 5.95, 10); - green.walk_up_to_olive(env.program_info(), env.console, context, 5.95, 10); - break; - }catch (OliveActionFailedException& e){ - if (e.m_fail_reason == OliveFail::OLIVE_STUCK){ - // if olive is stuck, we might have pushed the olive all the way to the end. so we can try moving on. - break; - } - - if (i >= MAX_ATTEMPTS-1){ - throw e; - } - if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED || e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE){ - // may have walked past olive - pbf_move_left_joystick(context, 128, 255, 200, 50); - pbf_wait(context, 5 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - // ticks_to_walk_for_section2_3 = 500; - }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE - throw e; - } - - } - } - - // section 2b. realign using fence corner - direction.change_direction(env.program_info(), env.console, context, 4.5); - pbf_move_left_joystick(context, 128, 0, 200, 50); - direction.change_direction(env.program_info(), env.console, context, 5.86); - pbf_move_left_joystick(context, 128, 0, 300, 50); - direction.change_direction(env.program_info(), env.console, context, 2.76); - pbf_move_left_joystick(context, 128, 0, 50, 50); - - // section 3.1 push olive across the hump - uint16_t ticks_to_walk_for_section3_1 = 350; - uint16_t ticks_walked_section3_1 = 0; - for (size_t i = 0; i < MAX_ATTEMPTS; i++){ - try{ - ticks_walked_section3_1 = green.push_olive_forward(env.program_info(), env.console, context, 1.27, ticks_to_walk_for_section3_1, 125); - break; - }catch (OliveActionFailedException& e){ - // may have failed to push the olive past the hump. and walked past it - if (i >= MAX_ATTEMPTS-1){ - throw e; - } - - if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED){ - pbf_move_left_joystick(context, 128, 255, 250, 50); - pbf_move_left_joystick(context, 128, 0, 50, 50); // move forward slight in case the olive is undetectable since it's right in front of the character - pbf_wait(context, 5 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - ticks_to_walk_for_section3_1 = 200; - }else if (e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE || e.m_fail_reason == OliveFail::OLIVE_STUCK){ - // try moving back and then ramming forward - pbf_move_left_joystick(context, 128, 255, 50, 50); - pbf_move_left_joystick(context, 128, 0, 150, 50); - pbf_wait(context, 7 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - ticks_to_walk_for_section3_1 = 200; - }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE, - throw e; - } - - } - } - - - // section 3.2 push olive across the hump and into fence - uint16_t total_ticks_to_walk_for_section3 = 550; - uint16_t ticks_to_walk_for_section3_2 = 0; - if (ticks_walked_section3_1 < total_ticks_to_walk_for_section3){ - ticks_to_walk_for_section3_2 = (total_ticks_to_walk_for_section3 - ticks_walked_section3_1); - } - for (size_t i = 0; i < MAX_ATTEMPTS; i++){ - try{ - green.push_olive_forward(env.program_info(), env.console, context, 1.27, ticks_to_walk_for_section3_2, 125); - pbf_move_left_joystick(context, 128, 255, 100, 50); - green.align_to_olive(env.program_info(), env.console, context, 1.27); - green.walk_up_to_olive(env.program_info(), env.console, context, 1.27); - break; - }catch (OliveActionFailedException& e){ - // may have failed to push the olive past the hump. and walked past it - if (i >= MAX_ATTEMPTS-1){ - throw e; - } - if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED){ - pbf_move_left_joystick(context, 128, 255, 200, 50); - pbf_wait(context, 7 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - ticks_to_walk_for_section3_2 += 200; - }else if (e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE || e.m_fail_reason == OliveFail::OLIVE_STUCK){ - // try moving back and then ramming forward - pbf_move_left_joystick(context, 128, 255, 50, 50); - pbf_move_left_joystick(context, 128, 0, 150, 50); - pbf_wait(context, 7 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE, - throw e; - } - - } - } - - - // section 3b. realign using fence. - direction.change_direction(env.program_info(), env.console, context, 3.0); - pbf_move_left_joystick(context, 128, 0, 75, 50); - direction.change_direction(env.program_info(), env.console, context, 1.17); - pbf_move_left_joystick(context, 128, 0, 100, 50); - - // section 4.1 last stretch. nudge the olive - for (size_t i = 0; i < MAX_ATTEMPTS; i++){ - try{ - green.align_to_olive(env.program_info(), env.console, context, 6.0); - green.walk_up_to_olive(env.program_info(), env.console, context, 6.0); - green.push_olive_forward(env.program_info(), env.console, context, 6.0, 50, 50); - break; - }catch (OliveActionFailedException& e){ - // may have failed to push the olive. and walked past it - if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED){ - pbf_move_left_joystick(context, 128, 255, 200, 50); - pbf_wait(context, 7 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - }else if (e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE || e.m_fail_reason == OliveFail::OLIVE_STUCK){ - // try moving back and then ramming forward - pbf_move_left_joystick(context, 128, 255, 50, 50); - pbf_move_left_joystick(context, 128, 0, 100, 50); - pbf_wait(context, 7 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE, - throw e; - } - } - } - - // section 4.2 past second NPC and into the finish line - NoMinimapWatcher no_minimap(env.console, COLOR_RED, Milliseconds(5000)); - size_t MAX_ATTEMPTS_SECTION_4 = 3; - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - for (size_t i = 0; i < MAX_ATTEMPTS_SECTION_4; i++){ - try{ - green.push_olive_forward(env.program_info(), env.console, context, 6.0, 250); - green.push_olive_forward(env.program_info(), env.console, context, 5.8, 100); - green.push_olive_forward(env.program_info(), env.console, context, 6.0, 200); - green.push_olive_forward(env.program_info(), env.console, context, 6.1, 200); - break; - }catch (OliveActionFailedException& e){ - // may have failed to push the olive. and walked past it - if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED){ - pbf_move_left_joystick(context, 128, 255, 200, 50); - pbf_wait(context, 7 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - }else if (e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE || e.m_fail_reason == OliveFail::OLIVE_STUCK){ - // try moving back and then ramming forward - pbf_move_left_joystick(context, 128, 255, 50, 50); - pbf_move_left_joystick(context, 128, 0, 150, 50); - pbf_wait(context, 7 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - // then push angled towards the right - green.push_olive_forward(env.program_info(), env.console, context, 5.8, 100); - }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE, - throw e; - } - } - } - }, - {no_minimap} - ); - if (ret < 0){ - throw_and_log( - env.logger(), ErrorReport::SEND_ERROR_REPORT, - "Failed to finish Olive roll in the last stretch.", - env.console - ); - } - env.log("No minimap seen. Likely finished the Olive roll."); - - // section 8. finish olive roll - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - // fix the time - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - home_to_date_time(env.console, context, false); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_from_home(env.console, context); - - enter_menu_from_overworld(env.program_info(), env.console, context, -1); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - // reset_game(env.program_info(), env.console, context); // the checkpoint itself already resets the game, so need to reset twice - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_27( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - move_cursor_towards_flypoint_and_go_there(env.program_info(), env.console, context, {ZoomChange::KEEP_ZOOM, 255, 128, 40}); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h" +#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_OliveActionFailedException.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_11.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + + +std::string AutoStory_Segment_11::name() const{ + return "10.2: Cortondo Gym - Gym challenge"; +} + +std::string AutoStory_Segment_11::start_text() const{ + return "Start: At Cortondo East Pokecenter."; +} + +std::string AutoStory_Segment_11::end_text() const{ + return "End: Beat Cortondo Gym challenge. At Cortondo West Pokecenter."; +} + +void AutoStory_Segment_11::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 10.2: Cortondo Gym - Gym challenge", COLOR_ORANGE); + + checkpoint_24(env, context, options.notif_status_update); + checkpoint_25(env, context, options.notif_status_update); + checkpoint_26(env, context, options.notif_status_update); + checkpoint_27(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 10.2: Cortondo Gym - Gym challenge", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + +void checkpoint_24( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + DirectionDetector direction; + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + direction.change_direction(env.program_info(), env.console, context, 2.71); + pbf_move_left_joystick(context, 128, 0, 375, 100); + direction.change_direction(env.program_info(), env.console, context, 1.26); + pbf_move_left_joystick(context, 128, 0, 1750, 100); + }); + + direction.change_direction(env.program_info(), env.console, context, 2.73); + pbf_move_left_joystick(context, 128, 0, 200, 100); + pbf_wait(context, 5 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 0, 100, 20); + }, + 5, 5 + ); + // enter gym building. talk go Nemona + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + // talk to receptionist + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10); + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD}); + + pbf_move_left_joystick(context, 128, 255, 500, 100); + pbf_wait(context, 3 * TICKS_PER_SECOND); + // wait for overworld after leaving gym + wait_for_overworld(env.program_info(), env.console, context, 30); + + pbf_move_left_joystick(context, 128, 0, 450, 100); + direction.change_direction(env.program_info(), env.console, context, 1.26); + pbf_move_left_joystick(context, 128, 0, 1600, 100); + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + +void checkpoint_25( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + // section 1. align to Olive roll NPC + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 157, 0, 40); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 40, 10); + + // section 1.1. keep walking forward and talk to Olive roll NPC + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10); + } + ); + mash_button_till_overworld(env.console, context, BUTTON_A); + + // section 2 + pbf_move_left_joystick(context, 128, 0, 1300, 100); + + // section 3 + DirectionDetector direction; + direction.change_direction(env.program_info(), env.console, context, 6.0); + pbf_move_left_joystick(context, 128, 0, 700, 100); + + // section 4. align to corner + direction.change_direction(env.program_info(), env.console, context, 4.69); + pbf_move_left_joystick(context, 128, 0, 150, 100); + + // section 5. battle first NPC + direction.change_direction(env.program_info(), env.console, context, 1.485); + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10, 128, 20); + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::DIALOG_ARROW}); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG); + mash_button_till_overworld(env.console, context, BUTTON_A); + + // section 6 + direction.change_direction(env.program_info(), env.console, context, 5.95); + pbf_move_left_joystick(context, 128, 0, 1000, 100); + + // section 7 + direction.change_direction(env.program_info(), env.console, context, 1.327); + pbf_move_left_joystick(context, 128, 0, 700, 100); + + // section 8 + direction.change_direction(env.program_info(), env.console, context, 6.106); + pbf_move_left_joystick(context, 128, 0, 200, 100); + + // section 9. battle second NPC + direction.change_direction(env.program_info(), env.console, context, 4.275); + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10, 128, 20); + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::DIALOG_ARROW}); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG); + mash_button_till_overworld(env.console, context, BUTTON_A); + + // section 10. leave Olive roll + pbf_mash_button(context, BUTTON_Y, 100); + clear_dialog(env.console, context, ClearDialogMode::STOP_PROMPT, 60, {CallbackEnum::PROMPT_DIALOG}); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 15, {CallbackEnum::PROMPT_DIALOG}); + wait_for_overworld(env.program_info(), env.console, context); + enter_menu_from_overworld(env.program_info(), env.console, context, -1); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_26( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + // change the time of day: close game, change time to 5:45 am. + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + change_date(env, context, {2025, 1, 1, 5, 45, 0}); + reset_game_from_home(env.program_info(), env.console, context); + + // talk to Olive roll NPC + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10, 128, 20); + mash_button_till_overworld(env.console, context, BUTTON_A); + + // section 1 + pbf_move_left_joystick(context, 128, 0, 400, 50); + OliveDetector green(env.console); + size_t MAX_ATTEMPTS_SECTION_1 = 2; + uint16_t ticks_to_walk_for_section1 = 650; + uint16_t push_strength_section_1 = 75; + for (size_t i = 0; i < MAX_ATTEMPTS_SECTION_1; i++){ + try{ + green.push_olive_forward(env.program_info(), env.console, context, 4.38, ticks_to_walk_for_section1, push_strength_section_1); + // green.align_to_olive(env.program_info(), env.console, context, 4.38); + green.walk_up_to_olive(env.program_info(), env.console, context, 4.38); + break; + }catch (OliveActionFailedException& e){ + if (e.m_fail_reason == OliveFail::OLIVE_STUCK){ + // if olive is stuck, we might have pushed the olive all the way to the end. so we can try moving on. + break; + } + + if (i >= MAX_ATTEMPTS_SECTION_1-1){ + throw e; + } + if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED || e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE){ + // may have walked past olive + pbf_move_left_joystick(context, 128, 255, 200, 50); + pbf_wait(context, 5 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + ticks_to_walk_for_section1 = 100; + push_strength_section_1 = 50; + }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE + throw e; + } + + } + } + + + // section 1b. realign using fence corner + DirectionDetector direction; + direction.change_direction(env.program_info(), env.console, context, 2.74); + pbf_move_left_joystick(context, 128, 0, 200, 50); + direction.change_direction(env.program_info(), env.console, context, 4.328); + pbf_move_left_joystick(context, 128, 0, 200, 50); + direction.change_direction(env.program_info(), env.console, context, 1.22); + pbf_move_left_joystick(context, 128, 0, 75, 50); + + // section 2.1 nudge olive straight + size_t MAX_ATTEMPTS_SECTION_2_1 = 2; + for (size_t i = 0; i < MAX_ATTEMPTS_SECTION_2_1; i++){ + try{ + green.push_olive_forward(env.program_info(), env.console, context, 5.95, 50, 50); + break; + }catch (OliveActionFailedException& e){ + if (i >= MAX_ATTEMPTS_SECTION_2_1-1){ + throw e; + } + + if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED){ + pbf_move_left_joystick(context, 128, 255, 250, 50); + pbf_move_left_joystick(context, 128, 0, 50, 50); // move forward slight in case the olive is undetectable since it's right in front of the character + pbf_wait(context, 5 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + }else if (e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE || e.m_fail_reason == OliveFail::OLIVE_STUCK){ + // try moving back and then ramming forward + pbf_move_left_joystick(context, 128, 255, 50, 50); + pbf_move_left_joystick(context, 128, 0, 150, 50); + pbf_wait(context, 7 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + break; // then move on to next section + }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE, + throw e; + } + + } + } + + pbf_move_left_joystick(context, 128, 255, 100, 50); + green.align_to_olive(env.program_info(), env.console, context, 5.95); + pbf_move_left_joystick(context, 128, 255, 500, 50); + + // section 2.2 push at angle towards outer fence + size_t MAX_ATTEMPTS_SECTION_2_2 = 2; + // uint16_t ticks_walked_section2_2 = 0; + for (size_t i = 0; i < MAX_ATTEMPTS_SECTION_2_2; i++){ + try{ + green.push_olive_forward(env.program_info(), env.console, context, 5.8, 250, 50); + break; + }catch (OliveActionFailedException& e){ + if (i >= MAX_ATTEMPTS_SECTION_2_2-1){ + throw e; + } + + if (e.m_fail_reason == OliveFail::OLIVE_STUCK){ // olive possibly stuck on fence + pbf_move_left_joystick(context, 128, 255, 20, 50); + pbf_move_left_joystick(context, 0, 128, 100, 50); + pbf_move_left_joystick(context, 128, 0, 200, 50); + // push olive parallel to fence + green.align_to_olive(env.program_info(), env.console, context, 4.28, 20); + green.walk_up_to_olive(env.program_info(), env.console, context, 4.28); + green.push_olive_forward(env.program_info(), env.console, context, 4.28, 100); + green.align_to_olive(env.program_info(), env.console, context, 4.28, 20); + green.walk_up_to_olive(env.program_info(), env.console, context, 4.28); + // back off + pbf_move_left_joystick(context, 128, 255, 50, 50); + // realign using fence corner + direction.change_direction(env.program_info(), env.console, context, 2.74); + pbf_move_left_joystick(context, 128, 0, 400, 50); + direction.change_direction(env.program_info(), env.console, context, 4.328); + pbf_move_left_joystick(context, 128, 0, 400, 50); + direction.change_direction(env.program_info(), env.console, context, 1.22); + pbf_move_left_joystick(context, 128, 0, 100, 50); + }else if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED){ + pbf_move_left_joystick(context, 128, 255, 200, 50); + pbf_wait(context, 5 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + + }else if (e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE){ + // try moving back and then ramming forward + pbf_move_left_joystick(context, 128, 255, 50, 50); + pbf_move_left_joystick(context, 128, 0, 150, 50); + pbf_wait(context, 7 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE, + // continue trying to push the olive. at a different angle + break; + } + } + } + + pbf_move_left_joystick(context, 128, 255, 100, 50); + green.align_to_olive(env.program_info(), env.console, context, 5.95); + pbf_move_left_joystick(context, 128, 255, 500, 50); + + // section 2.3 push olive past first NPC + uint16_t ticks_to_walk_for_section2_3 = 950; + size_t MAX_ATTEMPTS = 2; + for (size_t i = 0; i < MAX_ATTEMPTS; i++){ + try{ + green.push_olive_forward(env.program_info(), env.console, context, 5.95, ticks_to_walk_for_section2_3, 75, 10); + // green.align_to_olive(env.program_info(), env.console, context, 5.95, 10); + green.walk_up_to_olive(env.program_info(), env.console, context, 5.95, 10); + break; + }catch (OliveActionFailedException& e){ + if (e.m_fail_reason == OliveFail::OLIVE_STUCK){ + // if olive is stuck, we might have pushed the olive all the way to the end. so we can try moving on. + break; + } + + if (i >= MAX_ATTEMPTS-1){ + throw e; + } + if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED || e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE){ + // may have walked past olive + pbf_move_left_joystick(context, 128, 255, 200, 50); + pbf_wait(context, 5 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + // ticks_to_walk_for_section2_3 = 500; + }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE + throw e; + } + + } + } + + // section 2b. realign using fence corner + direction.change_direction(env.program_info(), env.console, context, 4.5); + pbf_move_left_joystick(context, 128, 0, 200, 50); + direction.change_direction(env.program_info(), env.console, context, 5.86); + pbf_move_left_joystick(context, 128, 0, 300, 50); + direction.change_direction(env.program_info(), env.console, context, 2.76); + pbf_move_left_joystick(context, 128, 0, 50, 50); + + // section 3.1 push olive across the hump + uint16_t ticks_to_walk_for_section3_1 = 350; + uint16_t ticks_walked_section3_1 = 0; + for (size_t i = 0; i < MAX_ATTEMPTS; i++){ + try{ + ticks_walked_section3_1 = green.push_olive_forward(env.program_info(), env.console, context, 1.27, ticks_to_walk_for_section3_1, 125); + break; + }catch (OliveActionFailedException& e){ + // may have failed to push the olive past the hump. and walked past it + if (i >= MAX_ATTEMPTS-1){ + throw e; + } + + if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED){ + pbf_move_left_joystick(context, 128, 255, 250, 50); + pbf_move_left_joystick(context, 128, 0, 50, 50); // move forward slight in case the olive is undetectable since it's right in front of the character + pbf_wait(context, 5 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + ticks_to_walk_for_section3_1 = 200; + }else if (e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE || e.m_fail_reason == OliveFail::OLIVE_STUCK){ + // try moving back and then ramming forward + pbf_move_left_joystick(context, 128, 255, 50, 50); + pbf_move_left_joystick(context, 128, 0, 150, 50); + pbf_wait(context, 7 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + ticks_to_walk_for_section3_1 = 200; + }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE, + throw e; + } + + } + } + + + // section 3.2 push olive across the hump and into fence + uint16_t total_ticks_to_walk_for_section3 = 550; + uint16_t ticks_to_walk_for_section3_2 = 0; + if (ticks_walked_section3_1 < total_ticks_to_walk_for_section3){ + ticks_to_walk_for_section3_2 = (total_ticks_to_walk_for_section3 - ticks_walked_section3_1); + } + for (size_t i = 0; i < MAX_ATTEMPTS; i++){ + try{ + green.push_olive_forward(env.program_info(), env.console, context, 1.27, ticks_to_walk_for_section3_2, 125); + pbf_move_left_joystick(context, 128, 255, 100, 50); + green.align_to_olive(env.program_info(), env.console, context, 1.27); + green.walk_up_to_olive(env.program_info(), env.console, context, 1.27); + break; + }catch (OliveActionFailedException& e){ + // may have failed to push the olive past the hump. and walked past it + if (i >= MAX_ATTEMPTS-1){ + throw e; + } + if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED){ + pbf_move_left_joystick(context, 128, 255, 200, 50); + pbf_wait(context, 7 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + ticks_to_walk_for_section3_2 += 200; + }else if (e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE || e.m_fail_reason == OliveFail::OLIVE_STUCK){ + // try moving back and then ramming forward + pbf_move_left_joystick(context, 128, 255, 50, 50); + pbf_move_left_joystick(context, 128, 0, 150, 50); + pbf_wait(context, 7 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE, + throw e; + } + + } + } + + + // section 3b. realign using fence. + direction.change_direction(env.program_info(), env.console, context, 3.0); + pbf_move_left_joystick(context, 128, 0, 75, 50); + direction.change_direction(env.program_info(), env.console, context, 1.17); + pbf_move_left_joystick(context, 128, 0, 100, 50); + + // section 4.1 last stretch. nudge the olive + for (size_t i = 0; i < MAX_ATTEMPTS; i++){ + try{ + green.align_to_olive(env.program_info(), env.console, context, 6.0); + green.walk_up_to_olive(env.program_info(), env.console, context, 6.0); + green.push_olive_forward(env.program_info(), env.console, context, 6.0, 50, 50); + break; + }catch (OliveActionFailedException& e){ + // may have failed to push the olive. and walked past it + if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED){ + pbf_move_left_joystick(context, 128, 255, 200, 50); + pbf_wait(context, 7 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + }else if (e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE || e.m_fail_reason == OliveFail::OLIVE_STUCK){ + // try moving back and then ramming forward + pbf_move_left_joystick(context, 128, 255, 50, 50); + pbf_move_left_joystick(context, 128, 0, 100, 50); + pbf_wait(context, 7 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE, + throw e; + } + } + } + + // section 4.2 past second NPC and into the finish line + NoMinimapWatcher no_minimap(env.console, COLOR_RED, Milliseconds(5000)); + size_t MAX_ATTEMPTS_SECTION_4 = 3; + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + for (size_t i = 0; i < MAX_ATTEMPTS_SECTION_4; i++){ + try{ + green.push_olive_forward(env.program_info(), env.console, context, 6.0, 250); + green.push_olive_forward(env.program_info(), env.console, context, 5.8, 100); + green.push_olive_forward(env.program_info(), env.console, context, 6.0, 200); + green.push_olive_forward(env.program_info(), env.console, context, 6.1, 200); + break; + }catch (OliveActionFailedException& e){ + // may have failed to push the olive. and walked past it + if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED){ + pbf_move_left_joystick(context, 128, 255, 200, 50); + pbf_wait(context, 7 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + }else if (e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE || e.m_fail_reason == OliveFail::OLIVE_STUCK){ + // try moving back and then ramming forward + pbf_move_left_joystick(context, 128, 255, 50, 50); + pbf_move_left_joystick(context, 128, 0, 150, 50); + pbf_wait(context, 7 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + // then push angled towards the right + green.push_olive_forward(env.program_info(), env.console, context, 5.8, 100); + }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE, + throw e; + } + } + } + }, + {no_minimap} + ); + if (ret < 0){ + throw_and_log( + env.logger(), ErrorReport::SEND_ERROR_REPORT, + "Failed to finish Olive roll in the last stretch.", + env.console + ); + } + env.log("No minimap seen. Likely finished the Olive roll."); + + // section 8. finish olive roll + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + // fix the time + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + home_to_date_time(env.console, context, false); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_from_home(env.console, context); + + enter_menu_from_overworld(env.program_info(), env.console, context, -1); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + // reset_game(env.program_info(), env.console, context); // the checkpoint itself already resets the game, so need to reset twice + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_27( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + move_cursor_towards_flypoint_and_go_there(env.program_info(), env.console, context, {ZoomChange::KEEP_ZOOM, 255, 128, 40}); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_11.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_11.h index 4a5eb11259..5b17aaf4f9 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_11.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_11.h @@ -1,66 +1,66 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_11_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_11_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_11 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: At Cortondo East Pokecenter -// end: Spoke to Cortondo Gym reception. At Cortondo West Pokecenter. -void checkpoint_24( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Spoke to Cortondo Gym reception. At Cortondo West Pokecenter. -// end: Defeated the trainers at Olive Roll, but left Olive unmoved. Then backed out, standing in front of the Olive Roll NPC. -void checkpoint_25( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Defeated the trainers at Olive Roll, but left Olive unmoved. Then backed out, standing in front of the Olive Roll NPC. -// end: Completed Olive roll gym challenge. -void checkpoint_26( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Completed Olive roll gym challenge. -// end: At Cortondo East Pokecenter. -void checkpoint_27( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_11_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_11_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_11 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: At Cortondo East Pokecenter +// end: Spoke to Cortondo Gym reception. At Cortondo West Pokecenter. +void checkpoint_24( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Spoke to Cortondo Gym reception. At Cortondo West Pokecenter. +// end: Defeated the trainers at Olive Roll, but left Olive unmoved. Then backed out, standing in front of the Olive Roll NPC. +void checkpoint_25( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Defeated the trainers at Olive Roll, but left Olive unmoved. Then backed out, standing in front of the Olive Roll NPC. +// end: Completed Olive roll gym challenge. +void checkpoint_26( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Completed Olive roll gym challenge. +// end: At Cortondo East Pokecenter. +void checkpoint_27( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_12.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_12.cpp index 7be5599d6c..94cda1507c 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_12.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_12.cpp @@ -1,154 +1,154 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_12.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_12::name() const{ - return "10.3: Cortondo Gym - Gym battle"; -} - -std::string AutoStory_Segment_12::start_text() const{ - return "Start: Beat Cortondo Gym challenge."; -} - -std::string AutoStory_Segment_12::end_text() const{ - return "End: Beat Cortondo Gym battle. At Cortondo West Pokecenter."; -} - - -void AutoStory_Segment_12::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.overlay().add_log("Start Segment 10.3: Cortondo Gym - Gym battle", COLOR_ORANGE); - - checkpoint_28(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 10.3: Cortondo Gym - Gym battle", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - -void checkpoint_28( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - DirectionDetector direction; - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - direction.change_direction(env.program_info(), env.console, context, 2.71); - pbf_move_left_joystick(context, 128, 0, 375, 100); - direction.change_direction(env.program_info(), env.console, context, 1.26); - pbf_move_left_joystick(context, 128, 0, 1750, 100); - }); - - direction.change_direction(env.program_info(), env.console, context, 2.73); - - NoMinimapWatcher no_minimap(env.console, COLOR_RED, Milliseconds(2000)); - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 10 * TICKS_PER_SECOND, 100); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 0, 100, 20); - }, - 5, 3 - ); - }, - {no_minimap} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to enter Cortondo Gym.", - env.console - ); - } - - wait_for_overworld(env.program_info(), env.console, context); - - // talk to receptionist - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10); - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::PROMPT_DIALOG, CallbackEnum::DIALOG_ARROW}); - - // battle Katy - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::GRADIENT_ARROW}, true); - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - // leave gym building - pbf_move_left_joystick(context, 128, 255, 500, 100); - pbf_wait(context, 3 * TICKS_PER_SECOND); - // wait for overworld after leaving gym - wait_for_overworld(env.program_info(), env.console, context, 30); - - pbf_move_left_joystick(context, 128, 0, 450, 100); - direction.change_direction(env.program_info(), env.console, context, 1.26); - pbf_move_left_joystick(context, 128, 0, 1600, 100); - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_12.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_12::name() const{ + return "10.3: Cortondo Gym - Gym battle"; +} + +std::string AutoStory_Segment_12::start_text() const{ + return "Start: Beat Cortondo Gym challenge."; +} + +std::string AutoStory_Segment_12::end_text() const{ + return "End: Beat Cortondo Gym battle. At Cortondo West Pokecenter."; +} + + +void AutoStory_Segment_12::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 10.3: Cortondo Gym - Gym battle", COLOR_ORANGE); + + checkpoint_28(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 10.3: Cortondo Gym - Gym battle", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + +void checkpoint_28( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + DirectionDetector direction; + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + direction.change_direction(env.program_info(), env.console, context, 2.71); + pbf_move_left_joystick(context, 128, 0, 375, 100); + direction.change_direction(env.program_info(), env.console, context, 1.26); + pbf_move_left_joystick(context, 128, 0, 1750, 100); + }); + + direction.change_direction(env.program_info(), env.console, context, 2.73); + + NoMinimapWatcher no_minimap(env.console, COLOR_RED, Milliseconds(2000)); + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 10 * TICKS_PER_SECOND, 100); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 0, 100, 20); + }, + 5, 3 + ); + }, + {no_minimap} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to enter Cortondo Gym.", + env.console + ); + } + + wait_for_overworld(env.program_info(), env.console, context); + + // talk to receptionist + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10); + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::PROMPT_DIALOG, CallbackEnum::DIALOG_ARROW}); + + // battle Katy + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::GRADIENT_ARROW}, true); + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + // leave gym building + pbf_move_left_joystick(context, 128, 255, 500, 100); + pbf_wait(context, 3 * TICKS_PER_SECOND); + // wait for overworld after leaving gym + wait_for_overworld(env.program_info(), env.console, context, 30); + + pbf_move_left_joystick(context, 128, 0, 450, 100); + direction.change_direction(env.program_info(), env.console, context, 1.26); + pbf_move_left_joystick(context, 128, 0, 1600, 100); + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_12.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_12.h index e61480d5fa..0e7d277412 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_12.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_12.h @@ -1,39 +1,39 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_12_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_12_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_12 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - -// start: At Cortondo East Pokecenter. -// end: Beat Cortondo Gym. At Cortondo West Pokecenter. -void checkpoint_28( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_12_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_12_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_12 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + +// start: At Cortondo East Pokecenter. +// end: Beat Cortondo Gym. At Cortondo West Pokecenter. +void checkpoint_28( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_13.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_13.cpp index be3502181f..0d76a94460 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_13.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_13.cpp @@ -1,331 +1,331 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_13.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_13::name() const{ - return "11.1: Bombirdier Titan: Go to West Province Area One Central Pokecenter"; -} - -std::string AutoStory_Segment_13::start_text() const{ - return "Start: At Cortondo West Pokecenter"; -} - -std::string AutoStory_Segment_13::end_text() const{ - return "End: At West Province Area One Central Pokecenter"; -} - -void AutoStory_Segment_13::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.overlay().add_log("Start Segment 11.1: Bombirdier Titan: Go to West Province Area One Central Pokecenter", COLOR_ORANGE); - - checkpoint_29(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 11.1: Bombirdier Titan: Go to West Province Area One Central Pokecenter", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - -// todo: shift all checkpoint numbers to make space for the Cortondo checkpoints -void checkpoint_29( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - // align for long stretch 1, part 1 - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 70, 0, 60); - - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 15, false); - - // align for long stretch 1, part 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 128, 255, 40}, - {ZoomChange::KEEP_ZOOM, 80, 0, 75} - ); - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 12, 12, false); - - // align for long stretch 1, part 3 - - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 128, 255, 60}, - {ZoomChange::KEEP_ZOOM, 95, 0, 115} - ); - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 36, 12, false); - - // align for long stretch 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 128, 255, 100}, - {ZoomChange::KEEP_ZOOM, 0, 105, 65} - ); - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 45, 15, false); - - // align for long stretch 3, part 1 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 128, 65}, - {ZoomChange::KEEP_ZOOM, 0, 50, 87} - ); - - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // align for long stretch 3, part 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 160, 65}, - {ZoomChange::KEEP_ZOOM, 20, 0, 110} - ); - - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - - // align for long stretch 3, part 3 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 60, 110}, - {ZoomChange::KEEP_ZOOM, 255, 128, 115} - ); - - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - - // align for long stretch 3, part 4 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 128, 100}, - {ZoomChange::KEEP_ZOOM, 255, 67, 90} //{ZoomChange::KEEP_ZOOM, 255, 70, 90} - ); - - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 36, 12, false); - - // align to cross bridge - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 128, 90}, - {ZoomChange::KEEP_ZOOM, 255, 35, 67} - ); - - - // attempt to cross bridge. If fall into water, go back to start position (just before bridge) and try again - WallClock start_to_cross_bridge = current_time(); - while (true){ - if (current_time() - start_to_cross_bridge > std::chrono::minutes(6)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "checkpoint_26(): Failed to cross bridge after 6 minutes.", - env.console - ); - } - - try { - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::CLEAR_WITH_LETS_GO, - 128, 0, 20, 20, false); - - break; - - }catch (...){ // try again if fall into water - pbf_mash_button(context, BUTTON_A, 250); - - // walk back to start position before bridge - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 255, 180}, - {ZoomChange::KEEP_ZOOM, 33, 0, 180} - ); - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::CLEAR_WITH_LETS_GO, - 128, 0, 20, 20, false); - - - // align to cross bridge - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 128, 90}, - {ZoomChange::KEEP_ZOOM, 255, 35, 67} - ); - - - } - } - - confirm_no_overlapping_flypoint(env.program_info(), env.console, context); - pbf_press_button(context, BUTTON_B, 20, 100); - handle_unexpected_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - press_Bs_to_back_to_overworld(env.program_info(), env.console, context); - }); - - env.console.log("Successfully crossed the bridge."); - - // align for post-bridge section 1 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 150, 60}, - {ZoomChange::KEEP_ZOOM, 255, 60, 50} // {ZoomChange::KEEP_ZOOM, 255, 60, 50} - ); - - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // align for post-bridge section 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 150, 60}, - {ZoomChange::KEEP_ZOOM, 255, 105, 50} - ); - - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // align for post-bridge section 3. move up towards tree - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 128, 50}, - {ZoomChange::KEEP_ZOOM, 255, 90, 35} - ); - - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // align for post-bridge section 4 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 128, 50}, - {ZoomChange::KEEP_ZOOM, 255, 55, 25} - ); - - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - - - // align for post-bridge section 5. set marker to pokecenter. - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 128, 50}, - {ZoomChange::KEEP_ZOOM, 128, 128, 0} - ); - - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - - - // align for post-bridge section 6. set marker past pokecenter - handle_unexpected_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 200, 30); - }); - // realign_player_from_landmark( - // env.program_info(), env.console, context, - // {ZoomChange::ZOOM_IN, 128, 128, 0}, - // {ZoomChange::KEEP_ZOOM, 0, 180, 20} - // ); - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 15, 12, 12, false); - - - - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_13.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_13::name() const{ + return "11.1: Bombirdier Titan: Go to West Province Area One Central Pokecenter"; +} + +std::string AutoStory_Segment_13::start_text() const{ + return "Start: At Cortondo West Pokecenter"; +} + +std::string AutoStory_Segment_13::end_text() const{ + return "End: At West Province Area One Central Pokecenter"; +} + +void AutoStory_Segment_13::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 11.1: Bombirdier Titan: Go to West Province Area One Central Pokecenter", COLOR_ORANGE); + + checkpoint_29(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 11.1: Bombirdier Titan: Go to West Province Area One Central Pokecenter", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + +// todo: shift all checkpoint numbers to make space for the Cortondo checkpoints +void checkpoint_29( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + // align for long stretch 1, part 1 + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 70, 0, 60); + + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 15, false); + + // align for long stretch 1, part 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 128, 255, 40}, + {ZoomChange::KEEP_ZOOM, 80, 0, 75} + ); + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 12, 12, false); + + // align for long stretch 1, part 3 + + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 128, 255, 60}, + {ZoomChange::KEEP_ZOOM, 95, 0, 115} + ); + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 36, 12, false); + + // align for long stretch 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 128, 255, 100}, + {ZoomChange::KEEP_ZOOM, 0, 105, 65} + ); + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 45, 15, false); + + // align for long stretch 3, part 1 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 128, 65}, + {ZoomChange::KEEP_ZOOM, 0, 50, 87} + ); + + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // align for long stretch 3, part 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 160, 65}, + {ZoomChange::KEEP_ZOOM, 20, 0, 110} + ); + + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + + // align for long stretch 3, part 3 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 60, 110}, + {ZoomChange::KEEP_ZOOM, 255, 128, 115} + ); + + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + + // align for long stretch 3, part 4 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 128, 100}, + {ZoomChange::KEEP_ZOOM, 255, 67, 90} //{ZoomChange::KEEP_ZOOM, 255, 70, 90} + ); + + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 36, 12, false); + + // align to cross bridge + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 128, 90}, + {ZoomChange::KEEP_ZOOM, 255, 35, 67} + ); + + + // attempt to cross bridge. If fall into water, go back to start position (just before bridge) and try again + WallClock start_to_cross_bridge = current_time(); + while (true){ + if (current_time() - start_to_cross_bridge > std::chrono::minutes(6)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "checkpoint_26(): Failed to cross bridge after 6 minutes.", + env.console + ); + } + + try { + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::CLEAR_WITH_LETS_GO, + 128, 0, 20, 20, false); + + break; + + }catch (...){ // try again if fall into water + pbf_mash_button(context, BUTTON_A, 250); + + // walk back to start position before bridge + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 255, 180}, + {ZoomChange::KEEP_ZOOM, 33, 0, 180} + ); + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::CLEAR_WITH_LETS_GO, + 128, 0, 20, 20, false); + + + // align to cross bridge + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 128, 90}, + {ZoomChange::KEEP_ZOOM, 255, 35, 67} + ); + + + } + } + + confirm_no_overlapping_flypoint(env.program_info(), env.console, context); + pbf_press_button(context, BUTTON_B, 20, 100); + handle_unexpected_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + press_Bs_to_back_to_overworld(env.program_info(), env.console, context); + }); + + env.console.log("Successfully crossed the bridge."); + + // align for post-bridge section 1 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 150, 60}, + {ZoomChange::KEEP_ZOOM, 255, 60, 50} // {ZoomChange::KEEP_ZOOM, 255, 60, 50} + ); + + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // align for post-bridge section 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 150, 60}, + {ZoomChange::KEEP_ZOOM, 255, 105, 50} + ); + + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // align for post-bridge section 3. move up towards tree + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 128, 50}, + {ZoomChange::KEEP_ZOOM, 255, 90, 35} + ); + + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // align for post-bridge section 4 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 128, 50}, + {ZoomChange::KEEP_ZOOM, 255, 55, 25} + ); + + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + + + // align for post-bridge section 5. set marker to pokecenter. + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 128, 50}, + {ZoomChange::KEEP_ZOOM, 128, 128, 0} + ); + + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + + + // align for post-bridge section 6. set marker past pokecenter + handle_unexpected_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 200, 30); + }); + // realign_player_from_landmark( + // env.program_info(), env.console, context, + // {ZoomChange::ZOOM_IN, 128, 128, 0}, + // {ZoomChange::KEEP_ZOOM, 0, 180, 20} + // ); + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 15, 12, 12, false); + + + + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_13.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_13.h index 31252d4a2d..ce4330a4b6 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_13.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_13.h @@ -1,43 +1,43 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_13_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_13_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_13 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: At Cortondo West Pokecenter. -// end: At West Province Area One Central Pokecenter -void checkpoint_29( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_13_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_13_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_13 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: At Cortondo West Pokecenter. +// end: At West Province Area One Central Pokecenter +void checkpoint_29( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_14.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_14.cpp index bb7d6338ff..756a8fa92c 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_14.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_14.cpp @@ -1,319 +1,319 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_14.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_14::name() const{ - return "11.2: Bombirdier Titan: Battle Bombirdier"; -} - -std::string AutoStory_Segment_14::start_text() const{ - return "Start: At West Province Area One Central Pokecenter"; -} - -std::string AutoStory_Segment_14::end_text() const{ - return "End: Defeated Bombirder. At West Province Area One North Pokecenter"; -} - -void AutoStory_Segment_14::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.overlay().add_log("Start Segment 11.2: Bombirdier Titan: Battle Bombirdier", COLOR_ORANGE); - - checkpoint_30(env, context, options.notif_status_update); - checkpoint_31(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 11.2: Bombirdier Titan: Battle Bombirdier", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - - -void checkpoint_30( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - // section 1 - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 128, 17); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - - // section 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 200, 200}, - {ZoomChange::KEEP_ZOOM, 0, 65, 220} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // section 3 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 200, 200}, - {ZoomChange::KEEP_ZOOM, 0, 80, 235} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // section 4. walk until Arven dialog - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 200, 200}, - {ZoomChange::KEEP_ZOOM, 0, 60, 280} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 30, {CallbackEnum::OVERWORLD, CallbackEnum::BLACK_DIALOG_BOX}); - - // after Arven dialog. section 5 - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 18, 6, false); - - // section 6 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 0, 0}, - {ZoomChange::KEEP_ZOOM, 0, 20, 65} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - get_on_ride(env.program_info(), env.console, context); - - // section 7 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 0, 0}, - {ZoomChange::KEEP_ZOOM, 0, 30, 80} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // section 8. enter left side of boulder field - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 255, 50}, - {ZoomChange::KEEP_ZOOM, 0, 40, 95} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 18, 6, false); - - // section 8.1. move up - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 0, 50); - pbf_move_left_joystick(context, 128, 0, 100, 100); - - // section 9. go to middle-right of boulder field - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 255, 50}, - {ZoomChange::KEEP_ZOOM, 0, 15, 110} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 40, 5, false); - - // // section 9.1. go to right edge of boulder field - // realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 140, 0, 50); - // pbf_move_left_joystick(context, 128, 0, 200, 100); - - // section 10. walk up right edge - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 255, 80}, - {ZoomChange::KEEP_ZOOM, 0, 12, 130} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 40, 5, false); - - // section 10.1 walk up right edge. until hit rock - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 15, 50); - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, - 140, 0, 10, 5, false); - - // section 10.2. move away from rock. - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 80, 255, 50); - pbf_move_left_joystick(context, 128, 0, 200, 100); - - // section 11 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 255, 100}, - {ZoomChange::KEEP_ZOOM, 0, 5, 150} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 40, 5, false); - - // section 12. reach the top. battle Bombirdier - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 255, 100}, - {ZoomChange::KEEP_ZOOM, 50, 0, 170} - ); - try{ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_BATTLE, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 40, 5, false); - }catch (OperationFailedException& e){ - (void) e; - // likely attempted to open/close phone to realign, but failed - // likely already reached cutscene to battle Bombirdeier. - - // keep waiting until battle detected. - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_BATTLE, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 128, 30, 30, false); - - } - - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG); - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 30, {CallbackEnum::BATTLE}); - // round 2 of battle - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::DIALOG_ARROW}); - // get ride upgrade - mash_button_till_overworld(env.console, context, BUTTON_A); - - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - -void checkpoint_31( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - // section 1. fall down the mountain - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 80, 180}, - {ZoomChange::KEEP_ZOOM, 0, 170, 120} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 50, 10, false); - // section 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 80, 100}, - {ZoomChange::KEEP_ZOOM, 0, 255, 55} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 40, 10, false); - // section 3. align to pokecenter - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 0, 40}, - {ZoomChange::KEEP_ZOOM, 0, 0, 0} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 40, 10, false); - - // section 4. set marker past pokecenter - handle_unexpected_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 60, 40); - }); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 15, 12, 12, false); - - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_14.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_14::name() const{ + return "11.2: Bombirdier Titan: Battle Bombirdier"; +} + +std::string AutoStory_Segment_14::start_text() const{ + return "Start: At West Province Area One Central Pokecenter"; +} + +std::string AutoStory_Segment_14::end_text() const{ + return "End: Defeated Bombirder. At West Province Area One North Pokecenter"; +} + +void AutoStory_Segment_14::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 11.2: Bombirdier Titan: Battle Bombirdier", COLOR_ORANGE); + + checkpoint_30(env, context, options.notif_status_update); + checkpoint_31(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 11.2: Bombirdier Titan: Battle Bombirdier", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + + +void checkpoint_30( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + // section 1 + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 128, 17); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + + // section 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 200, 200}, + {ZoomChange::KEEP_ZOOM, 0, 65, 220} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // section 3 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 200, 200}, + {ZoomChange::KEEP_ZOOM, 0, 80, 235} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // section 4. walk until Arven dialog + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 200, 200}, + {ZoomChange::KEEP_ZOOM, 0, 60, 280} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 30, {CallbackEnum::OVERWORLD, CallbackEnum::BLACK_DIALOG_BOX}); + + // after Arven dialog. section 5 + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 18, 6, false); + + // section 6 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 0, 0}, + {ZoomChange::KEEP_ZOOM, 0, 20, 65} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + get_on_ride(env.program_info(), env.console, context); + + // section 7 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 0, 0}, + {ZoomChange::KEEP_ZOOM, 0, 30, 80} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // section 8. enter left side of boulder field + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 255, 50}, + {ZoomChange::KEEP_ZOOM, 0, 40, 95} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 18, 6, false); + + // section 8.1. move up + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 0, 50); + pbf_move_left_joystick(context, 128, 0, 100, 100); + + // section 9. go to middle-right of boulder field + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 255, 50}, + {ZoomChange::KEEP_ZOOM, 0, 15, 110} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 40, 5, false); + + // // section 9.1. go to right edge of boulder field + // realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 140, 0, 50); + // pbf_move_left_joystick(context, 128, 0, 200, 100); + + // section 10. walk up right edge + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 255, 80}, + {ZoomChange::KEEP_ZOOM, 0, 12, 130} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 40, 5, false); + + // section 10.1 walk up right edge. until hit rock + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 15, 50); + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, + 140, 0, 10, 5, false); + + // section 10.2. move away from rock. + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 80, 255, 50); + pbf_move_left_joystick(context, 128, 0, 200, 100); + + // section 11 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 255, 100}, + {ZoomChange::KEEP_ZOOM, 0, 5, 150} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 40, 5, false); + + // section 12. reach the top. battle Bombirdier + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 255, 100}, + {ZoomChange::KEEP_ZOOM, 50, 0, 170} + ); + try{ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_BATTLE, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 40, 5, false); + }catch (OperationFailedException& e){ + (void) e; + // likely attempted to open/close phone to realign, but failed + // likely already reached cutscene to battle Bombirdeier. + + // keep waiting until battle detected. + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_BATTLE, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 128, 30, 30, false); + + } + + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG); + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 30, {CallbackEnum::BATTLE}); + // round 2 of battle + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::DIALOG_ARROW}); + // get ride upgrade + mash_button_till_overworld(env.console, context, BUTTON_A); + + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + +void checkpoint_31( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + // section 1. fall down the mountain + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 80, 180}, + {ZoomChange::KEEP_ZOOM, 0, 170, 120} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 50, 10, false); + // section 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 80, 100}, + {ZoomChange::KEEP_ZOOM, 0, 255, 55} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 40, 10, false); + // section 3. align to pokecenter + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 0, 40}, + {ZoomChange::KEEP_ZOOM, 0, 0, 0} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 40, 10, false); + + // section 4. set marker past pokecenter + handle_unexpected_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 60, 40); + }); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 15, 12, 12, false); + + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_14.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_14.h index 96fba8e84b..d4c5128c8a 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_14.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_14.h @@ -1,51 +1,51 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_14_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_14_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_14 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: At West Province Area One Central Pokecenter -// end: Defeated Bombirdier -void checkpoint_30( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Defeated Bombirdier -// end: At West Province Area One North Pokecenter -void checkpoint_31( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_14_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_14_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_14 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: At West Province Area One Central Pokecenter +// end: Defeated Bombirdier +void checkpoint_30( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Defeated Bombirdier +// end: At West Province Area One North Pokecenter +void checkpoint_31( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_15.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_15.cpp index ac332850c7..f7fb3e8fbb 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_15.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_15.cpp @@ -1,344 +1,344 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_15.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_15::name() const{ - return "12: Team Star (Dark)"; -} - -std::string AutoStory_Segment_15::start_text() const{ - return "Start: Defeated Bombirder. At West Province Area One North Pokecenter."; -} - -std::string AutoStory_Segment_15::end_text() const{ - return "End: Defeated Team Star (Dark). At Cascarrafa (West) Pokecenter."; -} - -void AutoStory_Segment_15::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.overlay().add_log("Start Segment 12: Team Star (Dark)", COLOR_ORANGE); - - checkpoint_32(env, context, options.notif_status_update); - checkpoint_33(env, context, options.notif_status_update); - checkpoint_34(env, context, options.notif_status_update); - - - context.wait_for_all_requests(); - env.console.log("End Segment 12: Team Star (Dark)", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - - -void checkpoint_32( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - // section 1 - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 50, 0, 25); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // section 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 255, 0, 80}, - {ZoomChange::ZOOM_IN, 5, 230, 145} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // section 3 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 255, 0, 60}, - {ZoomChange::ZOOM_IN, 5, 205, 100} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // section 4 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 128, 255, 40}, - {ZoomChange::KEEP_ZOOM, 255, 0, 110} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - // section 5 - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 255, 50); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 30, false); - - // battle team star grunts - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::PROMPT_DIALOG, CallbackEnum::DIALOG_ARROW}); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG); - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD, CallbackEnum::BLACK_DIALOG_BOX}); - - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_33( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - // enter the base - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 255, 50); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_SPAM_A, - 128, 0, 20, 20, false); - - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD, CallbackEnum::PROMPT_DIALOG, CallbackEnum::TUTORIAL}); - AdvanceDialogWatcher dialog(COLOR_RED); - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - - DirectionDetector direction; - uint16_t seconds_wait = 6; - - pbf_move_left_joystick(context, 128, 0, 250, 100); - direction.change_direction(env.program_info(), env.console, context, 3); - pbf_move_left_joystick(context, 128, 0, 10, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - direction.change_direction(env.program_info(), env.console, context, 4.1); - pbf_move_left_joystick(context, 128, 0, 750, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - direction.change_direction(env.program_info(), env.console, context, 5.04); - pbf_move_left_joystick(context, 128, 0, 250, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - pbf_move_left_joystick(context, 128, 0, 500, 100); - direction.change_direction(env.program_info(), env.console, context, 5.39); - pbf_move_left_joystick(context, 128, 0, 10, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - direction.change_direction(env.program_info(), env.console, context, 5.076); - pbf_move_left_joystick(context, 128, 0, 500, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - pbf_move_left_joystick(context, 128, 0, 250, 100); - direction.change_direction(env.program_info(), env.console, context, 4.800); - pbf_move_left_joystick(context, 128, 0, 250, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - pbf_move_left_joystick(context, 128, 0, 500, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - direction.change_direction(env.program_info(), env.console, context, 5.32); - pbf_move_left_joystick(context, 128, 0, 250, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - direction.change_direction(env.program_info(), env.console, context, 6.16); - pbf_move_left_joystick(context, 128, 0, 250, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - - direction.change_direction(env.program_info(), env.console, context, 0.541); - pbf_move_left_joystick(context, 128, 0, 500, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - direction.change_direction(env.program_info(), env.console, context, 1.41); - pbf_move_left_joystick(context, 128, 0, 350, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - direction.change_direction(env.program_info(), env.console, context, 2.34); - pbf_move_left_joystick(context, 128, 0, 250, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - direction.change_direction(env.program_info(), env.console, context, 1.556); - pbf_move_left_joystick(context, 128, 0, 500, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - }, - {dialog} - ); - context.wait_for(std::chrono::milliseconds(100)); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "checkpoint_33(): Failed to kill 30 pokemon with Let's go.", - env.console - ); - } - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::DIALOG_ARROW}); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {}, true); - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_34( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - // section 1 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 0, 128, 40}, - {ZoomChange::ZOOM_IN, 230, 0, 100} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 40, 10, false); - - // section 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 255, 100, 30}, - {ZoomChange::ZOOM_IN, 0, 240, 40} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // section 3. set marker to pokecenter - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 0, 0, 0}, - {ZoomChange::ZOOM_IN, 0, 0, 0} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // section 4. set marker past pokecenter - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 40, 100); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 15, 12, 12, false); - - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_15.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_15::name() const{ + return "12: Team Star (Dark)"; +} + +std::string AutoStory_Segment_15::start_text() const{ + return "Start: Defeated Bombirder. At West Province Area One North Pokecenter."; +} + +std::string AutoStory_Segment_15::end_text() const{ + return "End: Defeated Team Star (Dark). At Cascarrafa (West) Pokecenter."; +} + +void AutoStory_Segment_15::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 12: Team Star (Dark)", COLOR_ORANGE); + + checkpoint_32(env, context, options.notif_status_update); + checkpoint_33(env, context, options.notif_status_update); + checkpoint_34(env, context, options.notif_status_update); + + + context.wait_for_all_requests(); + env.console.log("End Segment 12: Team Star (Dark)", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + + +void checkpoint_32( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + // section 1 + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 50, 0, 25); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // section 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 255, 0, 80}, + {ZoomChange::ZOOM_IN, 5, 230, 145} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // section 3 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 255, 0, 60}, + {ZoomChange::ZOOM_IN, 5, 205, 100} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // section 4 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 128, 255, 40}, + {ZoomChange::KEEP_ZOOM, 255, 0, 110} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + // section 5 + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 255, 50); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 30, false); + + // battle team star grunts + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::PROMPT_DIALOG, CallbackEnum::DIALOG_ARROW}); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG); + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD, CallbackEnum::BLACK_DIALOG_BOX}); + + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_33( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + // enter the base + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 255, 50); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_SPAM_A, + 128, 0, 20, 20, false); + + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD, CallbackEnum::PROMPT_DIALOG, CallbackEnum::TUTORIAL}); + AdvanceDialogWatcher dialog(COLOR_RED); + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + + DirectionDetector direction; + uint16_t seconds_wait = 6; + + pbf_move_left_joystick(context, 128, 0, 250, 100); + direction.change_direction(env.program_info(), env.console, context, 3); + pbf_move_left_joystick(context, 128, 0, 10, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + direction.change_direction(env.program_info(), env.console, context, 4.1); + pbf_move_left_joystick(context, 128, 0, 750, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + direction.change_direction(env.program_info(), env.console, context, 5.04); + pbf_move_left_joystick(context, 128, 0, 250, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + pbf_move_left_joystick(context, 128, 0, 500, 100); + direction.change_direction(env.program_info(), env.console, context, 5.39); + pbf_move_left_joystick(context, 128, 0, 10, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + direction.change_direction(env.program_info(), env.console, context, 5.076); + pbf_move_left_joystick(context, 128, 0, 500, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + pbf_move_left_joystick(context, 128, 0, 250, 100); + direction.change_direction(env.program_info(), env.console, context, 4.800); + pbf_move_left_joystick(context, 128, 0, 250, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + pbf_move_left_joystick(context, 128, 0, 500, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + direction.change_direction(env.program_info(), env.console, context, 5.32); + pbf_move_left_joystick(context, 128, 0, 250, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + direction.change_direction(env.program_info(), env.console, context, 6.16); + pbf_move_left_joystick(context, 128, 0, 250, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + + direction.change_direction(env.program_info(), env.console, context, 0.541); + pbf_move_left_joystick(context, 128, 0, 500, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + direction.change_direction(env.program_info(), env.console, context, 1.41); + pbf_move_left_joystick(context, 128, 0, 350, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + direction.change_direction(env.program_info(), env.console, context, 2.34); + pbf_move_left_joystick(context, 128, 0, 250, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + direction.change_direction(env.program_info(), env.console, context, 1.556); + pbf_move_left_joystick(context, 128, 0, 500, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + }, + {dialog} + ); + context.wait_for(std::chrono::milliseconds(100)); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "checkpoint_33(): Failed to kill 30 pokemon with Let's go.", + env.console + ); + } + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::DIALOG_ARROW}); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {}, true); + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_34( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + // section 1 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 0, 128, 40}, + {ZoomChange::ZOOM_IN, 230, 0, 100} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 40, 10, false); + + // section 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 255, 100, 30}, + {ZoomChange::ZOOM_IN, 0, 240, 40} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // section 3. set marker to pokecenter + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 0, 0, 0}, + {ZoomChange::ZOOM_IN, 0, 0, 0} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // section 4. set marker past pokecenter + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 40, 100); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 15, 12, 12, false); + + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_15.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_15.h index 455d92b7d2..ae8b01571a 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_15.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_15.h @@ -1,59 +1,59 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_15_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_15_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_15 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - - -// start: At West Province Area One North Pokecenter -// end: Defeated Team Star (Dark) grunts at base entrance -void checkpoint_32( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Defeated Team star dark grunts at base entrance -// end: Defeated Team Star (Dark) boss -void checkpoint_33( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Defeated Team Star (Dark) boss -// end: At Cascarrafa (West) Pokecenter. -void checkpoint_34( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_15_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_15_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_15 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + + +// start: At West Province Area One North Pokecenter +// end: Defeated Team Star (Dark) grunts at base entrance +void checkpoint_32( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Defeated Team star dark grunts at base entrance +// end: Defeated Team Star (Dark) boss +void checkpoint_33( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Defeated Team Star (Dark) boss +// end: At Cascarrafa (West) Pokecenter. +void checkpoint_34( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_16.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_16.cpp index d00024c357..c38e5a7806 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_16.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_16.cpp @@ -1,197 +1,197 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_16.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_16::name() const{ - return "13.1: Cascarrafa Gym (Water): Get Kofu's wallet"; -} - -std::string AutoStory_Segment_16::start_text() const{ - return "Start: Defeated Team Star (Dark). At Cascarrafa (West) Pokecenter."; -} - -std::string AutoStory_Segment_16::end_text() const{ - return "End: Received Kofu's wallet. At Porto Marinada Pokecenter."; -} - -void AutoStory_Segment_16::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.overlay().add_log("Start Segment 13.1: Cascarrafa Gym (Water): Get Kofu's wallet", COLOR_ORANGE); - - checkpoint_35(env, context, options.notif_status_update); - checkpoint_36(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 13.1: Cascarrafa Gym (Water): Get Kofu's wallet", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - -void checkpoint_35( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - DirectionDetector direction; - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - direction.change_direction(env.program_info(), env.console, context, 0.3491); - pbf_move_left_joystick(context, 128, 0, 400, 100); - direction.change_direction(env.program_info(), env.console, context, 5.075911); - pbf_move_left_joystick(context, 128, 0, 525, 100); - }); - - direction.change_direction(env.program_info(), env.console, context, 3.771252); - get_on_ride(env.program_info(), env.console, context); - // walk towards elevator - pbf_move_left_joystick(context, 128, 0, 700, 100); - // jump to ensure you get on elevator - pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 200); - pbf_wait(context, 3 * TICKS_PER_SECOND); - // wait for overworld to reappear after stepping off elevator - wait_for_overworld(env.program_info(), env.console, context, 30); - - pbf_move_left_joystick(context, 128, 0, 120, 100); - direction.change_direction(env.program_info(), env.console, context, 5.11); - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20); - mash_button_till_overworld(env.console, context, BUTTON_A); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_36( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - move_cursor_towards_flypoint_and_go_there(env.program_info(), env.console, context, {ZoomChange::ZOOM_IN, 100, 0, 80}); - - // section 1 - // warning: can't reliably set the marker when in Cascarrafa, possibly due to too many NPCs. worse when sandstorm is up. - // what happens is that the program doesn't reliably push the cursor as much as it should - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 135, 410); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 60, 20, false); - // talk to Arven over phone - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - // section 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 0, 0, 80}, - {ZoomChange::ZOOM_IN, 255, 255, 110} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 60, 20, false); - - // section 3 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 0, 0, 40}, - {ZoomChange::ZOOM_IN, 255, 128, 45} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - - // cutscene with Kofu looking at flowers - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - // section 4. set marker to pokecenter - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 0, 0, 0}, - {ZoomChange::ZOOM_IN, 0, 0, 0} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // section 5. set marker past pokecenter - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 100, 30); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 15, 12, 12, false); - - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_16.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_16::name() const{ + return "13.1: Cascarrafa Gym (Water): Get Kofu's wallet"; +} + +std::string AutoStory_Segment_16::start_text() const{ + return "Start: Defeated Team Star (Dark). At Cascarrafa (West) Pokecenter."; +} + +std::string AutoStory_Segment_16::end_text() const{ + return "End: Received Kofu's wallet. At Porto Marinada Pokecenter."; +} + +void AutoStory_Segment_16::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 13.1: Cascarrafa Gym (Water): Get Kofu's wallet", COLOR_ORANGE); + + checkpoint_35(env, context, options.notif_status_update); + checkpoint_36(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 13.1: Cascarrafa Gym (Water): Get Kofu's wallet", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + +void checkpoint_35( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + DirectionDetector direction; + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + direction.change_direction(env.program_info(), env.console, context, 0.3491); + pbf_move_left_joystick(context, 128, 0, 400, 100); + direction.change_direction(env.program_info(), env.console, context, 5.075911); + pbf_move_left_joystick(context, 128, 0, 525, 100); + }); + + direction.change_direction(env.program_info(), env.console, context, 3.771252); + get_on_ride(env.program_info(), env.console, context); + // walk towards elevator + pbf_move_left_joystick(context, 128, 0, 700, 100); + // jump to ensure you get on elevator + pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 200); + pbf_wait(context, 3 * TICKS_PER_SECOND); + // wait for overworld to reappear after stepping off elevator + wait_for_overworld(env.program_info(), env.console, context, 30); + + pbf_move_left_joystick(context, 128, 0, 120, 100); + direction.change_direction(env.program_info(), env.console, context, 5.11); + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20); + mash_button_till_overworld(env.console, context, BUTTON_A); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_36( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + move_cursor_towards_flypoint_and_go_there(env.program_info(), env.console, context, {ZoomChange::ZOOM_IN, 100, 0, 80}); + + // section 1 + // warning: can't reliably set the marker when in Cascarrafa, possibly due to too many NPCs. worse when sandstorm is up. + // what happens is that the program doesn't reliably push the cursor as much as it should + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 135, 410); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 60, 20, false); + // talk to Arven over phone + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + // section 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 0, 0, 80}, + {ZoomChange::ZOOM_IN, 255, 255, 110} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 60, 20, false); + + // section 3 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 0, 0, 40}, + {ZoomChange::ZOOM_IN, 255, 128, 45} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + + // cutscene with Kofu looking at flowers + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + // section 4. set marker to pokecenter + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 0, 0, 0}, + {ZoomChange::ZOOM_IN, 0, 0, 0} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // section 5. set marker past pokecenter + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 100, 30); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 15, 12, 12, false); + + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_16.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_16.h index 74ba92f801..a6d5ddcb8c 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_16.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_16.h @@ -1,52 +1,52 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_16_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_16_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_16 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: At Cascarrafa (West) Pokecenter. -// end: At Cascarrafa Gym. Received Kofu's wallet. -void checkpoint_35( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: At Cascarrafa Gym. Received Kofu's wallet. -// end: At Porto Marinada Pokecenter. -void checkpoint_36( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_16_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_16_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_16 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: At Cascarrafa (West) Pokecenter. +// end: At Cascarrafa Gym. Received Kofu's wallet. +void checkpoint_35( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: At Cascarrafa Gym. Received Kofu's wallet. +// end: At Porto Marinada Pokecenter. +void checkpoint_36( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_17.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_17.cpp index 99eae6b512..1d4574d920 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_17.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_17.cpp @@ -1,190 +1,190 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_17.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_17::name() const{ - return "13.2: Cascarrafa Gym (Water): Gym challenge and Gym battle"; -} - -std::string AutoStory_Segment_17::start_text() const{ - return "Start: Received Kofu's wallet. At Porto Marinada Pokecenter."; -} - -std::string AutoStory_Segment_17::end_text() const{ - return "End: Defeated Cascarrafa Gym (Water). At Cascarrafa Gym."; -} - -void AutoStory_Segment_17::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.overlay().add_log("Start Segment 13.2: Cascarrafa Gym (Water): Gym battle", COLOR_ORANGE); - - checkpoint_37(env, context, options.notif_status_update); - checkpoint_38(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 13.2: Cascarrafa Gym (Water): Gym battle", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - -void checkpoint_37( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - DirectionDetector direction; - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 255, 50); - - // section 1 - direction.change_direction(env.program_info(), env.console, context, 1.606); - pbf_move_left_joystick(context, 128, 0, 200, 100); - - get_on_ride(env.program_info(), env.console, context); - - // section 2 - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - }); - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - // section 3. set marker to shop/Kofu - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 140, 27); - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20); - - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::PROMPT_DIALOG, CallbackEnum::DIALOG_ARROW}); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::GRADIENT_ARROW}); - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_38( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - move_cursor_towards_flypoint_and_go_there(env.program_info(), env.console, context, {ZoomChange::KEEP_ZOOM, 255, 180, 170}); - DirectionDetector direction; - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - direction.change_direction(env.program_info(), env.console, context, 0.3491); - pbf_move_left_joystick(context, 128, 0, 400, 100); - direction.change_direction(env.program_info(), env.console, context, 5.075911); - pbf_move_left_joystick(context, 128, 0, 525, 100); - }); - - direction.change_direction(env.program_info(), env.console, context, 3.771252); - get_on_ride(env.program_info(), env.console, context); - // walk towards elevator - pbf_move_left_joystick(context, 128, 0, 700, 100); - // jump to ensure you get on elevator - pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 200); - pbf_wait(context, 3 * TICKS_PER_SECOND); - // wait for overworld to reappear after stepping off elevator - wait_for_overworld(env.program_info(), env.console, context, 30); - - pbf_move_left_joystick(context, 128, 0, 120, 100); - - direction.change_direction(env.program_info(), env.console, context, 5.11); - pbf_move_left_joystick(context, 128, 0, 1600, 100); - direction.change_direction(env.program_info(), env.console, context, 3.2245); - - - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 18); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 255, 0, 100, 50); - pbf_move_left_joystick(context, 0, 0, 100, 50); - } - ); - // talk to Nemona - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - // talk to reception. Battle Kofu - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10); - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::PROMPT_DIALOG, CallbackEnum::DIALOG_ARROW}); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::GRADIENT_ARROW}, true); - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_17.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_17::name() const{ + return "13.2: Cascarrafa Gym (Water): Gym challenge and Gym battle"; +} + +std::string AutoStory_Segment_17::start_text() const{ + return "Start: Received Kofu's wallet. At Porto Marinada Pokecenter."; +} + +std::string AutoStory_Segment_17::end_text() const{ + return "End: Defeated Cascarrafa Gym (Water). At Cascarrafa Gym."; +} + +void AutoStory_Segment_17::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 13.2: Cascarrafa Gym (Water): Gym battle", COLOR_ORANGE); + + checkpoint_37(env, context, options.notif_status_update); + checkpoint_38(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 13.2: Cascarrafa Gym (Water): Gym battle", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + +void checkpoint_37( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + DirectionDetector direction; + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 255, 50); + + // section 1 + direction.change_direction(env.program_info(), env.console, context, 1.606); + pbf_move_left_joystick(context, 128, 0, 200, 100); + + get_on_ride(env.program_info(), env.console, context); + + // section 2 + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + }); + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + // section 3. set marker to shop/Kofu + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 140, 27); + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20); + + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::PROMPT_DIALOG, CallbackEnum::DIALOG_ARROW}); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::GRADIENT_ARROW}); + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_38( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + move_cursor_towards_flypoint_and_go_there(env.program_info(), env.console, context, {ZoomChange::KEEP_ZOOM, 255, 180, 170}); + DirectionDetector direction; + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + direction.change_direction(env.program_info(), env.console, context, 0.3491); + pbf_move_left_joystick(context, 128, 0, 400, 100); + direction.change_direction(env.program_info(), env.console, context, 5.075911); + pbf_move_left_joystick(context, 128, 0, 525, 100); + }); + + direction.change_direction(env.program_info(), env.console, context, 3.771252); + get_on_ride(env.program_info(), env.console, context); + // walk towards elevator + pbf_move_left_joystick(context, 128, 0, 700, 100); + // jump to ensure you get on elevator + pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 200); + pbf_wait(context, 3 * TICKS_PER_SECOND); + // wait for overworld to reappear after stepping off elevator + wait_for_overworld(env.program_info(), env.console, context, 30); + + pbf_move_left_joystick(context, 128, 0, 120, 100); + + direction.change_direction(env.program_info(), env.console, context, 5.11); + pbf_move_left_joystick(context, 128, 0, 1600, 100); + direction.change_direction(env.program_info(), env.console, context, 3.2245); + + + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 18); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 255, 0, 100, 50); + pbf_move_left_joystick(context, 0, 0, 100, 50); + } + ); + // talk to Nemona + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + // talk to reception. Battle Kofu + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10); + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::PROMPT_DIALOG, CallbackEnum::DIALOG_ARROW}); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::GRADIENT_ARROW}, true); + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_17.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_17.h index 0153ed5bb6..95db8b3f35 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_17.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_17.h @@ -1,50 +1,50 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_17_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_17_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_17 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: At Porto Marinada Pokecenter. -// end: Won auction at Porto Marinada, passed Gym challenge. -void checkpoint_37( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Won auction at Porto Marinada, passed Gym challenge. -// end: Defeat Cascarrafa Gym -void checkpoint_38( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_17_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_17_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_17 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: At Porto Marinada Pokecenter. +// end: Won auction at Porto Marinada, passed Gym challenge. +void checkpoint_37( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Won auction at Porto Marinada, passed Gym challenge. +// end: Defeat Cascarrafa Gym +void checkpoint_38( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_18.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_18.cpp index 0557f8e4b2..d406383e8e 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_18.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_18.cpp @@ -1,373 +1,373 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_18.h" - -// #include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_18::name() const{ - return "14: Great Tusk/Iron Treads titan"; -} - -std::string AutoStory_Segment_18::start_text() const{ - return "Start: Defeated Cascarrafa Gym (Water). At Cascarrafa Gym."; -} - -std::string AutoStory_Segment_18::end_text() const{ - return "End: Defeated Great Tusk/Iron Treads. At South Province (Area Three) Pokecenter."; -} - -void AutoStory_Segment_18::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.overlay().add_log("Start Segment 14: Great Tusk/Iron Treads titan", COLOR_ORANGE); - - checkpoint_39(env, context, options.notif_status_update); - checkpoint_40(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 14: Great Tusk/Iron Treads titan", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - -void checkpoint_39( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - pbf_move_left_joystick(context, 128, 255, 500, 100); - pbf_wait(context, 3 * TICKS_PER_SECOND); - // wait for overworld after leaving Gym - wait_for_overworld(env.program_info(), env.console, context, 30); - - // fly to Porto Marinada pokecenter - move_cursor_towards_flypoint_and_go_there(env.program_info(), env.console, context, {ZoomChange::KEEP_ZOOM, 0, 80, 150}); - - DirectionDetector direction; - - // section 1 - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - direction.change_direction(env.program_info(), env.console, context, 4.677921); - pbf_move_left_joystick(context, 128, 0, 150, 100); - }); - - // section 2 - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 230, 120); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 60, 10, false); - - // section 3. enter circle - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 0, 0, 50}, - {ZoomChange::ZOOM_IN, 175, 255, 120} - ); - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 60, 10, false); - - DialogBoxWatcher dialog(COLOR_RED, true); - - // section 4 - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - // run around in circles until you run into the titan - WallClock start = current_time(); - - while (true){ - if (current_time() - start > std::chrono::minutes(30)){ - break; - } - // std::cout << "1:00" << std::endl; - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 128, 0, 50}, - {ZoomChange::ZOOM_IN, 160, 255, 90} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 36, 12, false); - - - // std::cout << "11:00" << std::endl; - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 128, 0, 50}, - {ZoomChange::ZOOM_IN, 135, 255, 90} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - - - // std::cout << "10:00" << std::endl; - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 128, 0, 50}, - {ZoomChange::ZOOM_IN, 120, 255, 105} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - - // std::cout << "7:00" << std::endl; - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 128, 0, 50}, - {ZoomChange::ZOOM_IN, 115, 255, 127} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 48, 12, false); - - // std::cout << "6:00" << std::endl; - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 128, 0, 50}, - {ZoomChange::ZOOM_IN, 135, 255, 137} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - - // std::cout << "2:00" << std::endl; - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 128, 0, 50}, - {ZoomChange::ZOOM_IN, 200, 255, 120} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 50, 10, false); - } - - }, - {dialog} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "checkpoint_39(): Failed to run into Great Tusk/Iron Treads.", - env.console - ); - } - - // battle the titan phase 1 - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::BLACK_DIALOG_BOX}); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_OVERWORLD); - - // section 5 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 128, 0, 40}, - {ZoomChange::ZOOM_IN, 122, 255, 130} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // section 6 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 128, 0, 50}, - {ZoomChange::ZOOM_IN, 90, 255, 170} - ); - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 40, 40, false); - - // battle the titan phase 2 - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE}); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::DIALOG_ARROW}); - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_40( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - // fly to Mesagoza East - move_cursor_towards_flypoint_and_go_there(env.program_info(), env.console, context, {ZoomChange::KEEP_ZOOM, 255, 185, 440}); - - // place down marker, for section 1 - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 180, 90); - - DirectionDetector direction; - direction.change_direction(env.program_info(), env.console, context, 5.60); - - get_on_ride(env.program_info(), env.console, context); - - // jump over the fence to exit Mesagoza - pbf_move_left_joystick(context, 128, 0, 200, 50); - pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 200); - - wait_for_overworld(env.program_info(), env.console, context); - - // section 1 - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 255, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 0, 128, 40}, - {ZoomChange::ZOOM_IN, 255, 140, 100} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 255, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 3 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 0, 150, 50}, - {ZoomChange::ZOOM_IN, 255, 90, 120} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 0, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 4. set marker to pokecenter - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 50, 30}, - {ZoomChange::KEEP_ZOOM, 0, 0, 0} - ); - - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 255, 0, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 5. set marker past pokecenter - handle_unexpected_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 160, 40); - }); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 15, 12, 12, false); // can't wrap in handle_when_stationary_in_overworld(), since we expect to be stationary when walking into the pokecenter - - - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_18.h" + +// #include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_18::name() const{ + return "14: Great Tusk/Iron Treads titan"; +} + +std::string AutoStory_Segment_18::start_text() const{ + return "Start: Defeated Cascarrafa Gym (Water). At Cascarrafa Gym."; +} + +std::string AutoStory_Segment_18::end_text() const{ + return "End: Defeated Great Tusk/Iron Treads. At South Province (Area Three) Pokecenter."; +} + +void AutoStory_Segment_18::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 14: Great Tusk/Iron Treads titan", COLOR_ORANGE); + + checkpoint_39(env, context, options.notif_status_update); + checkpoint_40(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 14: Great Tusk/Iron Treads titan", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + +void checkpoint_39( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + pbf_move_left_joystick(context, 128, 255, 500, 100); + pbf_wait(context, 3 * TICKS_PER_SECOND); + // wait for overworld after leaving Gym + wait_for_overworld(env.program_info(), env.console, context, 30); + + // fly to Porto Marinada pokecenter + move_cursor_towards_flypoint_and_go_there(env.program_info(), env.console, context, {ZoomChange::KEEP_ZOOM, 0, 80, 150}); + + DirectionDetector direction; + + // section 1 + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + direction.change_direction(env.program_info(), env.console, context, 4.677921); + pbf_move_left_joystick(context, 128, 0, 150, 100); + }); + + // section 2 + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 230, 120); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 60, 10, false); + + // section 3. enter circle + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 0, 0, 50}, + {ZoomChange::ZOOM_IN, 175, 255, 120} + ); + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 60, 10, false); + + DialogBoxWatcher dialog(COLOR_RED, true); + + // section 4 + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + // run around in circles until you run into the titan + WallClock start = current_time(); + + while (true){ + if (current_time() - start > std::chrono::minutes(30)){ + break; + } + // std::cout << "1:00" << std::endl; + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 128, 0, 50}, + {ZoomChange::ZOOM_IN, 160, 255, 90} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 36, 12, false); + + + // std::cout << "11:00" << std::endl; + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 128, 0, 50}, + {ZoomChange::ZOOM_IN, 135, 255, 90} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + + + // std::cout << "10:00" << std::endl; + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 128, 0, 50}, + {ZoomChange::ZOOM_IN, 120, 255, 105} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + + // std::cout << "7:00" << std::endl; + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 128, 0, 50}, + {ZoomChange::ZOOM_IN, 115, 255, 127} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 48, 12, false); + + // std::cout << "6:00" << std::endl; + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 128, 0, 50}, + {ZoomChange::ZOOM_IN, 135, 255, 137} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + + // std::cout << "2:00" << std::endl; + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 128, 0, 50}, + {ZoomChange::ZOOM_IN, 200, 255, 120} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 50, 10, false); + } + + }, + {dialog} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "checkpoint_39(): Failed to run into Great Tusk/Iron Treads.", + env.console + ); + } + + // battle the titan phase 1 + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::BLACK_DIALOG_BOX}); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_OVERWORLD); + + // section 5 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 128, 0, 40}, + {ZoomChange::ZOOM_IN, 122, 255, 130} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // section 6 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 128, 0, 50}, + {ZoomChange::ZOOM_IN, 90, 255, 170} + ); + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 40, 40, false); + + // battle the titan phase 2 + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE}); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::DIALOG_ARROW}); + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_40( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + // fly to Mesagoza East + move_cursor_towards_flypoint_and_go_there(env.program_info(), env.console, context, {ZoomChange::KEEP_ZOOM, 255, 185, 440}); + + // place down marker, for section 1 + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 180, 90); + + DirectionDetector direction; + direction.change_direction(env.program_info(), env.console, context, 5.60); + + get_on_ride(env.program_info(), env.console, context); + + // jump over the fence to exit Mesagoza + pbf_move_left_joystick(context, 128, 0, 200, 50); + pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 200); + + wait_for_overworld(env.program_info(), env.console, context); + + // section 1 + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 255, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 0, 128, 40}, + {ZoomChange::ZOOM_IN, 255, 140, 100} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 255, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 3 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 0, 150, 50}, + {ZoomChange::ZOOM_IN, 255, 90, 120} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 0, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 4. set marker to pokecenter + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 50, 30}, + {ZoomChange::KEEP_ZOOM, 0, 0, 0} + ); + + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 255, 0, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 5. set marker past pokecenter + handle_unexpected_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 160, 40); + }); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 15, 12, 12, false); // can't wrap in handle_when_stationary_in_overworld(), since we expect to be stationary when walking into the pokecenter + + + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_18.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_18.h index f0181b8edb..e2660a7e4a 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_18.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_18.h @@ -1,51 +1,51 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_18_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_18_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_18 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: Defeated Cascarrafa Gym (Water). At Cascarrafa Gym. -// end: Defeated Great Tusk/Iron Treads. -void checkpoint_39( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Defeated Great Tusk/Iron Treads. -// end: At South Province (Area Three) Pokecenter. -void checkpoint_40( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_18_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_18_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_18 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: Defeated Cascarrafa Gym (Water). At Cascarrafa Gym. +// end: Defeated Great Tusk/Iron Treads. +void checkpoint_39( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Defeated Great Tusk/Iron Treads. +// end: At South Province (Area Three) Pokecenter. +void checkpoint_40( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_19.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_19.cpp index 19c71e41f9..3b1cf9f720 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_19.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_19.cpp @@ -1,376 +1,376 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_19.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_19::name() const{ - return "15.1: Klawf Titan: Battle Klawf"; -} - -std::string AutoStory_Segment_19::start_text() const{ - return "Start: At South Province (Area Three) Pokecenter."; -} - -std::string AutoStory_Segment_19::end_text() const{ - return "End: Defeated Klawf. At Artazon (West) Pokecenter."; -} - -void AutoStory_Segment_19::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.overlay().add_log("Start Segment 15.2: Klawf Titan: Battle Klawf", COLOR_ORANGE); - - checkpoint_41(env, context, options.notif_status_update); - checkpoint_42(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 15.2: Klawf Titan: Battle Klawf", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - - -void checkpoint_41( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - // section 1 - DirectionDetector direction; - direction.change_direction(env.program_info(), env.console, context, 0.14); - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 200, 100); - }); - - // section 2. walk until hit dialog - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 0, 128, 70}, - {ZoomChange::ZOOM_IN, 255, 93, 170} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - // clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::BLACK_DIALOG_BOX}); - mash_button_till_overworld(env.console, context, BUTTON_A); - - - // section 3. - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 4 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 255, 128, 100}, - {ZoomChange::ZOOM_IN, 0, 90, 157} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 255, 50, 50); - pbf_move_left_joystick(context, 255, 128, 50, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 5 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 255, 150, 70}, - {ZoomChange::ZOOM_IN, 0, 95, 112} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 6 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 255, 128, 60}, - {ZoomChange::ZOOM_IN, 0, 50, 105} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 24, 8, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 255, 50, 50); - pbf_move_left_joystick(context, 255, 128, 50, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 7. walk up to Klawf on the lower wall, so it moves to the high ground - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 255, 150, 50}, - {ZoomChange::ZOOM_IN, 0, 40, 110} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 255, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 8. walk up to Klawf on lower wall - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 255, 150, 50}, - {ZoomChange::ZOOM_IN, 30, 30, 135} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 10, 10, false); - - // section 9 - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_right_joystick(context, 255, 128, 100, 50); - direction.change_direction(env.program_info(), env.console, context, 4.467); - pbf_move_left_joystick(context, 128, 0, 700, 50); - pbf_move_left_joystick(context, 0, 128, 100, 50); - pbf_move_left_joystick(context, 0, 0, 500, 50); - direction.change_direction(env.program_info(), env.console, context, 2.795); - pbf_move_left_joystick(context, 128, 0, 200, 50); - direction.change_direction(env.program_info(), env.console, context, 4.747); - pbf_move_left_joystick(context, 128, 0, 600, 50); - direction.change_direction(env.program_info(), env.console, context, 5.479); - pbf_move_left_joystick(context, 128, 0, 400, 50); - direction.change_direction(env.program_info(), env.console, context, 0.33); - pbf_move_left_joystick(context, 128, 0, 900, 50); - direction.change_direction(env.program_info(), env.console, context, 2.325); - }); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_BATTLE, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 25, 25, false); - - - // battle Klawf phase 1 - run_battle_press_A(env.console, context, BattleStopCondition::STOP_OVERWORLD); - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - direction.change_direction(env.program_info(), env.console, context, 2.83); - // pbf_move_left_joystick(context, 128, 0, 800, 50); - }); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 35, 35, false); - - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 30, {CallbackEnum::BATTLE}); - // Klawf battle phase 2 - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::DIALOG_ARROW}); - // get ride upgrade - mash_button_till_overworld(env.console, context, BUTTON_A); - - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_42( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - // section 1 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 255, 180, 50}, - {ZoomChange::ZOOM_IN, 0, 80, 110} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 24, 12, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 255, 150, 50}, - {ZoomChange::ZOOM_IN, 0, 80, 38} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 36, 12, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 255, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 3 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 0, 0, 0}, - {ZoomChange::ZOOM_IN, 65, 0, 45} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 24, 12, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 255, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 4. set marker to pokecenter - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 0, 0, 0}, - {ZoomChange::ZOOM_IN, 0, 0, 0} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 5. set marker past pokecenter - handle_unexpected_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 255, 30); - }); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 15, 12, 12, false); // can't wrap in handle_when_stationary_in_overworld(), since we expect to be stationary when walking into the pokecenter - - - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_19.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_19::name() const{ + return "15.1: Klawf Titan: Battle Klawf"; +} + +std::string AutoStory_Segment_19::start_text() const{ + return "Start: At South Province (Area Three) Pokecenter."; +} + +std::string AutoStory_Segment_19::end_text() const{ + return "End: Defeated Klawf. At Artazon (West) Pokecenter."; +} + +void AutoStory_Segment_19::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 15.2: Klawf Titan: Battle Klawf", COLOR_ORANGE); + + checkpoint_41(env, context, options.notif_status_update); + checkpoint_42(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 15.2: Klawf Titan: Battle Klawf", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + + +void checkpoint_41( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + // section 1 + DirectionDetector direction; + direction.change_direction(env.program_info(), env.console, context, 0.14); + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 200, 100); + }); + + // section 2. walk until hit dialog + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 0, 128, 70}, + {ZoomChange::ZOOM_IN, 255, 93, 170} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + // clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::BLACK_DIALOG_BOX}); + mash_button_till_overworld(env.console, context, BUTTON_A); + + + // section 3. + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 4 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 255, 128, 100}, + {ZoomChange::ZOOM_IN, 0, 90, 157} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 255, 50, 50); + pbf_move_left_joystick(context, 255, 128, 50, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 5 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 255, 150, 70}, + {ZoomChange::ZOOM_IN, 0, 95, 112} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 6 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 255, 128, 60}, + {ZoomChange::ZOOM_IN, 0, 50, 105} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 24, 8, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 255, 50, 50); + pbf_move_left_joystick(context, 255, 128, 50, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 7. walk up to Klawf on the lower wall, so it moves to the high ground + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 255, 150, 50}, + {ZoomChange::ZOOM_IN, 0, 40, 110} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 255, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 8. walk up to Klawf on lower wall + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 255, 150, 50}, + {ZoomChange::ZOOM_IN, 30, 30, 135} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 10, 10, false); + + // section 9 + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_right_joystick(context, 255, 128, 100, 50); + direction.change_direction(env.program_info(), env.console, context, 4.467); + pbf_move_left_joystick(context, 128, 0, 700, 50); + pbf_move_left_joystick(context, 0, 128, 100, 50); + pbf_move_left_joystick(context, 0, 0, 500, 50); + direction.change_direction(env.program_info(), env.console, context, 2.795); + pbf_move_left_joystick(context, 128, 0, 200, 50); + direction.change_direction(env.program_info(), env.console, context, 4.747); + pbf_move_left_joystick(context, 128, 0, 600, 50); + direction.change_direction(env.program_info(), env.console, context, 5.479); + pbf_move_left_joystick(context, 128, 0, 400, 50); + direction.change_direction(env.program_info(), env.console, context, 0.33); + pbf_move_left_joystick(context, 128, 0, 900, 50); + direction.change_direction(env.program_info(), env.console, context, 2.325); + }); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_BATTLE, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 25, 25, false); + + + // battle Klawf phase 1 + run_battle_press_A(env.console, context, BattleStopCondition::STOP_OVERWORLD); + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + direction.change_direction(env.program_info(), env.console, context, 2.83); + // pbf_move_left_joystick(context, 128, 0, 800, 50); + }); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 35, 35, false); + + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 30, {CallbackEnum::BATTLE}); + // Klawf battle phase 2 + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::DIALOG_ARROW}); + // get ride upgrade + mash_button_till_overworld(env.console, context, BUTTON_A); + + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_42( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + // section 1 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 255, 180, 50}, + {ZoomChange::ZOOM_IN, 0, 80, 110} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 24, 12, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 255, 150, 50}, + {ZoomChange::ZOOM_IN, 0, 80, 38} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 36, 12, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 255, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 3 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 0, 0, 0}, + {ZoomChange::ZOOM_IN, 65, 0, 45} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 24, 12, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 255, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 4. set marker to pokecenter + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 0, 0, 0}, + {ZoomChange::ZOOM_IN, 0, 0, 0} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 5. set marker past pokecenter + handle_unexpected_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 255, 30); + }); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 15, 12, 12, false); // can't wrap in handle_when_stationary_in_overworld(), since we expect to be stationary when walking into the pokecenter + + + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_19.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_19.h index e7b35e2f58..49aa9afc03 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_19.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_19.h @@ -1,50 +1,50 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_19_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_19_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_19 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: At South Province (Area Three) Pokecenter. -// end: Defeated Klawf. -void checkpoint_41( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Defeated Klawf. -// end: Defeated Klawf. At Artazon (West) Pokecenter. -void checkpoint_42( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_19_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_19_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_19 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: At South Province (Area Three) Pokecenter. +// end: Defeated Klawf. +void checkpoint_41( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Defeated Klawf. +// end: Defeated Klawf. At Artazon (West) Pokecenter. +void checkpoint_42( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_20.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_20.cpp index 11343d9257..8dd367fd2d 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_20.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_20.cpp @@ -1,559 +1,559 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_20.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_20::name() const{ - return "16: Artazon Gym (Grass)"; -} - -std::string AutoStory_Segment_20::start_text() const{ - return "Start: Defeated Klawf. At Artazon (West) Pokecenter."; -} - -std::string AutoStory_Segment_20::end_text() const{ - return "End: Defeated Artazon Gym (Grass). Inside gym building."; -} - -void AutoStory_Segment_20::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.overlay().add_log("Start Segment ", COLOR_ORANGE); - - checkpoint_43(env, context, options.notif_status_update); - checkpoint_44(env, context, options.notif_status_update); - checkpoint_45(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment ", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - -void checkpoint_43( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - }else{ - enter_menu_from_overworld(env.program_info(), env.console, context, -1); - // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. - env.log("Wait 10 seconds."); - context.wait_for(Milliseconds(10 * 1000)); - save_game_from_overworld(env.program_info(), env.console, context); - } - context.wait_for_all_requests(); - - // place the marker somewhere else. the current location disrupts the Stationary detector - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 128, 50); - - DirectionDetector direction; - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - direction.change_direction(env.program_info(), env.console, context, 6.198); - pbf_move_left_joystick(context, 128, 0, 400, 100); - direction.change_direction(env.program_info(), env.console, context, 4.693); - pbf_move_left_joystick(context, 128, 0, 1000, 100); - }); - // walk up right set of stairs - direction.change_direction(env.program_info(), env.console, context, 4.276); - pbf_move_left_joystick(context, 128, 0, 700, 100); - - // realign using lamp-post - direction.change_direction(env.program_info(), env.console, context, 2.34); - pbf_move_left_joystick(context, 128, 0, 200, 100); - direction.change_direction(env.program_info(), env.console, context, 1.81); - pbf_move_left_joystick(context, 255, 0, 600, 100); - - // move toward gym building - direction.change_direction(env.program_info(), env.console, context, 4.26); - pbf_move_left_joystick(context, 128, 0, 900, 100); - direction.change_direction(env.program_info(), env.console, context, 3.05); - pbf_move_left_joystick(context, 128, 0, 200, 100); - pbf_wait(context, 7 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 0, 100, 50); - }, - 5, 5 - ); - - // enter gym building. talk go Nemona and battle her. - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BLACK_DIALOG_BOX, CallbackEnum::PROMPT_DIALOG, CallbackEnum::DIALOG_ARROW, CallbackEnum::BATTLE}); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::GRADIENT_ARROW}); - mash_button_till_overworld(env.console, context, BUTTON_A); - - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_44( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - }else{ - enter_menu_from_overworld(env.program_info(), env.console, context, -1); - // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. - env.log("Wait 10 seconds."); - context.wait_for(Milliseconds(10 * 1000)); - save_game_from_overworld(env.program_info(), env.console, context); - } - - context.wait_for_all_requests(); - - // talk to receptionist - env.console.log("Talk to Artazon gym receptionist."); - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10); - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD}); - - pbf_move_left_joystick(context, 128, 255, 500, 100); - pbf_wait(context, 3 * TICKS_PER_SECOND); - // wait for overworld after leaving gym - wait_for_overworld(env.program_info(), env.console, context, 30); - - // talk to Sunflora NPC - DirectionDetector direction; - direction.change_direction(env.program_info(), env.console, context, 4.91); - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10); - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD, CallbackEnum::PROMPT_DIALOG}); - - // realign to wall - direction.change_direction(env.program_info(), env.console, context, 1.477); - pbf_move_left_joystick(context, 128, 0, 500, 100); - direction.change_direction(env.program_info(), env.console, context, 2.166); - pbf_move_left_joystick(context, 0, 0, 300, 100); - - // get sunflora 1 - direction.change_direction(env.program_info(), env.console, context, 4.85); - pbf_move_left_joystick(context, 128, 0, 300, 100); - handle_failed_action(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 500); - check_num_sunflora_found(env, context, 1); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 30, 100); - }, - 3 - ); - - // get sunflora 2 - direction.change_direction(env.program_info(), env.console, context, 0.384); - pbf_move_left_joystick(context, 128, 0, 120, 100); - handle_failed_action(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 500); - check_num_sunflora_found(env, context, 2); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 30, 100); - }, - 3 - ); - - // get sunflora 3 - direction.change_direction(env.program_info(), env.console, context, 5.377); - pbf_move_left_joystick(context, 128, 0, 120, 100); - handle_failed_action(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 500); - check_num_sunflora_found(env, context, 3); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 30, 100); - }, - 3 - ); - - get_on_ride(env.program_info(), env.console, context); - - // get sunflora 4 - // align to corner 4.1 - direction.change_direction(env.program_info(), env.console, context, 1.90); - pbf_move_left_joystick(context, 128, 0, 200, 100); - direction.change_direction(env.program_info(), env.console, context, 2.166); - pbf_move_left_joystick(context, 0, 0, 300, 100); - - // align to corner 4.2 - direction.change_direction(env.program_info(), env.console, context, 6.056); - pbf_move_left_joystick(context, 128, 0, 670, 100); - direction.change_direction(env.program_info(), env.console, context, 1.22); - pbf_move_left_joystick(context, 128, 0, 200, 100); - direction.change_direction(env.program_info(), env.console, context, 1.69); - pbf_move_left_joystick(context, 0, 0, 500, 100); - - direction.change_direction(env.program_info(), env.console, context, 5.85); - pbf_move_left_joystick(context, 128, 0, 60, 100); - handle_failed_action(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 500); - check_num_sunflora_found(env, context, 4); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 30, 100); - }, - 3 - ); - - // get sunflora 5 - // align to corner 5.1 - direction.change_direction(env.program_info(), env.console, context, 1.59); - pbf_move_left_joystick(context, 128, 0, 200, 100); - direction.change_direction(env.program_info(), env.console, context, 1.79); - pbf_move_left_joystick(context, 0, 0, 500, 100); - direction.change_direction(env.program_info(), env.console, context, 6.055); - pbf_move_left_joystick(context, 128, 0, 400, 100); - direction.change_direction(env.program_info(), env.console, context, 5.06); - pbf_move_left_joystick(context, 128, 0, 600, 100); - direction.change_direction(env.program_info(), env.console, context, 4.38); - pbf_move_left_joystick(context, 0, 0, 700, 100); - - direction.change_direction(env.program_info(), env.console, context, 2.53); - pbf_move_left_joystick(context, 128, 0, 160, 100); - direction.change_direction(env.program_info(), env.console, context, 0.78); - pbf_move_left_joystick(context, 128, 0, 90, 100); // todo: adjust this. 80 -> 90? - handle_failed_action(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 500); - check_num_sunflora_found(env, context, 5); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 30, 100); - }, - 3 - ); - - // sunflora 6 - // align to corner 6.1 - direction.change_direction(env.program_info(), env.console, context, 4.2); - pbf_move_left_joystick(context, 128, 0, 200, 100); - direction.change_direction(env.program_info(), env.console, context, 4.38); - pbf_move_left_joystick(context, 0, 0, 700, 100); - - direction.change_direction(env.program_info(), env.console, context, 0.96); - pbf_move_left_joystick(context, 128, 0, 300, 100); - direction.change_direction(env.program_info(), env.console, context, 5.17); - pbf_move_left_joystick(context, 128, 0, 100, 100); - direction.change_direction(env.program_info(), env.console, context, 3.86); - handle_failed_action(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 500); - check_num_sunflora_found(env, context, 6); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 30, 100); - }, - 3 - ); - - // sunflora 7 - // align to corner 7.1 - direction.change_direction(env.program_info(), env.console, context, 2.06); - pbf_move_left_joystick(context, 128, 0, 80, 100); - direction.change_direction(env.program_info(), env.console, context, 4.7); - pbf_move_left_joystick(context, 128, 0, 100, 100); - direction.change_direction(env.program_info(), env.console, context, 5.01); - pbf_move_left_joystick(context, 128, 0, 1600, 100); - - // align to corner 7.2. bush - direction.change_direction(env.program_info(), env.console, context, 2.34); - pbf_move_left_joystick(context, 128, 0, 700, 100); - direction.change_direction(env.program_info(), env.console, context, 3.42); - pbf_move_left_joystick(context, 128, 0, 400, 100); - - // align to corner 7.3. lamp-post - // todo: adjust routine to get to lampost. go behind the sculpture and goat? - direction.change_direction(env.program_info(), env.console, context, 0); - pbf_move_left_joystick(context, 128, 0, 120, 100); - direction.change_direction(env.program_info(), env.console, context, 1.75); - pbf_move_left_joystick(context, 128, 0, 400, 100); - direction.change_direction(env.program_info(), env.console, context, 2.95); - pbf_move_left_joystick(context, 128, 0, 300, 100); - direction.change_direction(env.program_info(), env.console, context, 2.22); - pbf_move_left_joystick(context, 128, 0, 400, 100); - direction.change_direction(env.program_info(), env.console, context, 1.01); - pbf_move_left_joystick(context, 128, 0, 300, 100); - - // align to corner 7.4. wall corner - direction.change_direction(env.program_info(), env.console, context, 3.70); - pbf_move_left_joystick(context, 128, 0, 400, 100); - direction.change_direction(env.program_info(), env.console, context, 4.28); - pbf_move_left_joystick(context, 128, 0, 400, 100); - direction.change_direction(env.program_info(), env.console, context, 3.54); - pbf_move_left_joystick(context, 128, 0, 600, 100); - - // align to corner 7.5. bush - direction.change_direction(env.program_info(), env.console, context, 3.11); - pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 150); - pbf_move_left_joystick(context, 128, 0, 60, 100); - direction.change_direction(env.program_info(), env.console, context, 4.28); - pbf_move_left_joystick(context, 128, 0, 200, 100); - direction.change_direction(env.program_info(), env.console, context, 3.60); - pbf_move_left_joystick(context, 128, 0, 400, 100); - - direction.change_direction(env.program_info(), env.console, context, 1.17); - pbf_move_left_joystick(context, 128, 0, 130, 100); - handle_failed_action(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 500); - check_num_sunflora_found(env, context, 7); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 30, 100); - }, - 3 - ); - - // sunflora 8 - // align to corner 8.1. bush - direction.change_direction(env.program_info(), env.console, context, 4.54); - pbf_move_left_joystick(context, 128, 0, 200, 100); - pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 150); - pbf_move_left_joystick(context, 128, 0, 200, 100); - direction.change_direction(env.program_info(), env.console, context, 3.60); - pbf_move_left_joystick(context, 128, 0, 400, 100); - - direction.change_direction(env.program_info(), env.console, context, 1.64); - pbf_move_left_joystick(context, 128, 0, 350, 100); - direction.change_direction(env.program_info(), env.console, context, 4.36); - pbf_move_left_joystick(context, 128, 0, 100, 100); - - handle_failed_action(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_press_button(context, BUTTON_A, 50, 50); - pbf_press_button(context, BUTTON_A, 50, 50); // extra press in case one is dropped - pbf_press_button(context, BUTTON_A, 50, 50); - pbf_wait(context, 250); - press_Bs_to_back_to_overworld(env.program_info(), env.console, context); - check_num_sunflora_found(env, context, 8); - pbf_wait(context, 3 * TICKS_PER_SECOND); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 30, 100); - }, - 3 - ); - - // // sunflora 9 - // // align to corner 9.1. bush - pbf_move_left_joystick(context, 128, 255, 200, 100); - direction.change_direction(env.program_info(), env.console, context, 4.89); - pbf_move_left_joystick(context, 128, 0, 350, 100); - pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 180); - get_off_ride(env.program_info(), env.console, context); - direction.change_direction(env.program_info(), env.console, context, 3.60); - pbf_move_left_joystick(context, 128, 0, 600, 100); - - - direction.change_direction(env.program_info(), env.console, context, 1.48); - pbf_move_left_joystick(context, 128, 0, 50, 100); - direction.change_direction(env.program_info(), env.console, context, 3.11); - pbf_move_left_joystick(context, 128, 0, 180, 100); - direction.change_direction(env.program_info(), env.console, context, 4.75); - pbf_move_left_joystick(context, 128, 0, 100, 100); - get_on_ride(env.program_info(), env.console, context); - direction.change_direction(env.program_info(), env.console, context, 5.53); - pbf_move_left_joystick(context, 128, 0, 600, 100); - handle_failed_action(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 500); - check_num_sunflora_found(env, context, 9); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 30, 100); - }, - 3 - ); - - // sunflora 10 - // align to corner 10.1. bush - pbf_move_left_joystick(context, 0, 128, 200, 100); - - direction.change_direction(env.program_info(), env.console, context, 4.02); - pbf_move_left_joystick(context, 128, 0, 250, 100); - handle_failed_action(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 500); - check_num_sunflora_found(env, context, 10); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 30, 100); - }, - 3 - ); - - // go back to Sunflora NPC - // align to corner 11.1. bush - direction.change_direction(env.program_info(), env.console, context, 0.65); - pbf_move_left_joystick(context, 128, 0, 200, 100); - pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 150); - pbf_move_left_joystick(context, 128, 0, 800, 100); - - direction.change_direction(env.program_info(), env.console, context, 4.49); - pbf_move_left_joystick(context, 128, 0, 100, 100); - direction.change_direction(env.program_info(), env.console, context, 5.53); - - NoMinimapWatcher no_minimap(env.console, COLOR_RED, Milliseconds(5000)); - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 30 * TICKS_PER_SECOND, 100); - }, - {no_minimap} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to finish reach the Sunflora NPC.", - env.console - ); - } - env.log("No minimap seen. Likely finished the Artazon gym challenge."); - - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD}); - - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_45( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - }else{ - enter_menu_from_overworld(env.program_info(), env.console, context, -1); - // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. - env.log("Wait 10 seconds."); - context.wait_for(Milliseconds(10 * 1000)); - save_game_from_overworld(env.program_info(), env.console, context); - } - - context.wait_for_all_requests(); - - get_on_ride(env.program_info(), env.console, context); - - DirectionDetector direction; - direction.change_direction(env.program_info(), env.console, context, 1.52); - pbf_move_left_joystick(context, 128, 0, 400, 100); - direction.change_direction(env.program_info(), env.console, context, 2.62); - pbf_move_left_joystick(context, 128, 0, 400, 100); - - direction.change_direction(env.program_info(), env.console, context, 2.18); - pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 150); - pbf_move_left_joystick(context, 128, 0, 400, 100); - direction.change_direction(env.program_info(), env.console, context, 3.16); - pbf_move_left_joystick(context, 0, 0, 100, 50); - - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 20); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 0, 100, 50); - pbf_move_left_joystick(context, 255, 0, 100, 50); - }, - 5, 2, 2 - ); - - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::PROMPT_DIALOG, CallbackEnum::BATTLE, CallbackEnum::DIALOG_ARROW}); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::GRADIENT_ARROW}); - mash_button_till_overworld(env.console, context, BUTTON_A); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_20.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_20::name() const{ + return "16: Artazon Gym (Grass)"; +} + +std::string AutoStory_Segment_20::start_text() const{ + return "Start: Defeated Klawf. At Artazon (West) Pokecenter."; +} + +std::string AutoStory_Segment_20::end_text() const{ + return "End: Defeated Artazon Gym (Grass). Inside gym building."; +} + +void AutoStory_Segment_20::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment ", COLOR_ORANGE); + + checkpoint_43(env, context, options.notif_status_update); + checkpoint_44(env, context, options.notif_status_update); + checkpoint_45(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment ", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + +void checkpoint_43( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + }else{ + enter_menu_from_overworld(env.program_info(), env.console, context, -1); + // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. + env.log("Wait 10 seconds."); + context.wait_for(Milliseconds(10 * 1000)); + save_game_from_overworld(env.program_info(), env.console, context); + } + context.wait_for_all_requests(); + + // place the marker somewhere else. the current location disrupts the Stationary detector + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 128, 50); + + DirectionDetector direction; + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + direction.change_direction(env.program_info(), env.console, context, 6.198); + pbf_move_left_joystick(context, 128, 0, 400, 100); + direction.change_direction(env.program_info(), env.console, context, 4.693); + pbf_move_left_joystick(context, 128, 0, 1000, 100); + }); + // walk up right set of stairs + direction.change_direction(env.program_info(), env.console, context, 4.276); + pbf_move_left_joystick(context, 128, 0, 700, 100); + + // realign using lamp-post + direction.change_direction(env.program_info(), env.console, context, 2.34); + pbf_move_left_joystick(context, 128, 0, 200, 100); + direction.change_direction(env.program_info(), env.console, context, 1.81); + pbf_move_left_joystick(context, 255, 0, 600, 100); + + // move toward gym building + direction.change_direction(env.program_info(), env.console, context, 4.26); + pbf_move_left_joystick(context, 128, 0, 900, 100); + direction.change_direction(env.program_info(), env.console, context, 3.05); + pbf_move_left_joystick(context, 128, 0, 200, 100); + pbf_wait(context, 7 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 0, 100, 50); + }, + 5, 5 + ); + + // enter gym building. talk go Nemona and battle her. + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BLACK_DIALOG_BOX, CallbackEnum::PROMPT_DIALOG, CallbackEnum::DIALOG_ARROW, CallbackEnum::BATTLE}); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::GRADIENT_ARROW}); + mash_button_till_overworld(env.console, context, BUTTON_A); + + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_44( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + }else{ + enter_menu_from_overworld(env.program_info(), env.console, context, -1); + // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. + env.log("Wait 10 seconds."); + context.wait_for(Milliseconds(10 * 1000)); + save_game_from_overworld(env.program_info(), env.console, context); + } + + context.wait_for_all_requests(); + + // talk to receptionist + env.console.log("Talk to Artazon gym receptionist."); + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10); + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD}); + + pbf_move_left_joystick(context, 128, 255, 500, 100); + pbf_wait(context, 3 * TICKS_PER_SECOND); + // wait for overworld after leaving gym + wait_for_overworld(env.program_info(), env.console, context, 30); + + // talk to Sunflora NPC + DirectionDetector direction; + direction.change_direction(env.program_info(), env.console, context, 4.91); + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10); + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD, CallbackEnum::PROMPT_DIALOG}); + + // realign to wall + direction.change_direction(env.program_info(), env.console, context, 1.477); + pbf_move_left_joystick(context, 128, 0, 500, 100); + direction.change_direction(env.program_info(), env.console, context, 2.166); + pbf_move_left_joystick(context, 0, 0, 300, 100); + + // get sunflora 1 + direction.change_direction(env.program_info(), env.console, context, 4.85); + pbf_move_left_joystick(context, 128, 0, 300, 100); + handle_failed_action(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 500); + check_num_sunflora_found(env, context, 1); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 30, 100); + }, + 3 + ); + + // get sunflora 2 + direction.change_direction(env.program_info(), env.console, context, 0.384); + pbf_move_left_joystick(context, 128, 0, 120, 100); + handle_failed_action(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 500); + check_num_sunflora_found(env, context, 2); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 30, 100); + }, + 3 + ); + + // get sunflora 3 + direction.change_direction(env.program_info(), env.console, context, 5.377); + pbf_move_left_joystick(context, 128, 0, 120, 100); + handle_failed_action(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 500); + check_num_sunflora_found(env, context, 3); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 30, 100); + }, + 3 + ); + + get_on_ride(env.program_info(), env.console, context); + + // get sunflora 4 + // align to corner 4.1 + direction.change_direction(env.program_info(), env.console, context, 1.90); + pbf_move_left_joystick(context, 128, 0, 200, 100); + direction.change_direction(env.program_info(), env.console, context, 2.166); + pbf_move_left_joystick(context, 0, 0, 300, 100); + + // align to corner 4.2 + direction.change_direction(env.program_info(), env.console, context, 6.056); + pbf_move_left_joystick(context, 128, 0, 670, 100); + direction.change_direction(env.program_info(), env.console, context, 1.22); + pbf_move_left_joystick(context, 128, 0, 200, 100); + direction.change_direction(env.program_info(), env.console, context, 1.69); + pbf_move_left_joystick(context, 0, 0, 500, 100); + + direction.change_direction(env.program_info(), env.console, context, 5.85); + pbf_move_left_joystick(context, 128, 0, 60, 100); + handle_failed_action(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 500); + check_num_sunflora_found(env, context, 4); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 30, 100); + }, + 3 + ); + + // get sunflora 5 + // align to corner 5.1 + direction.change_direction(env.program_info(), env.console, context, 1.59); + pbf_move_left_joystick(context, 128, 0, 200, 100); + direction.change_direction(env.program_info(), env.console, context, 1.79); + pbf_move_left_joystick(context, 0, 0, 500, 100); + direction.change_direction(env.program_info(), env.console, context, 6.055); + pbf_move_left_joystick(context, 128, 0, 400, 100); + direction.change_direction(env.program_info(), env.console, context, 5.06); + pbf_move_left_joystick(context, 128, 0, 600, 100); + direction.change_direction(env.program_info(), env.console, context, 4.38); + pbf_move_left_joystick(context, 0, 0, 700, 100); + + direction.change_direction(env.program_info(), env.console, context, 2.53); + pbf_move_left_joystick(context, 128, 0, 160, 100); + direction.change_direction(env.program_info(), env.console, context, 0.78); + pbf_move_left_joystick(context, 128, 0, 90, 100); // todo: adjust this. 80 -> 90? + handle_failed_action(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 500); + check_num_sunflora_found(env, context, 5); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 30, 100); + }, + 3 + ); + + // sunflora 6 + // align to corner 6.1 + direction.change_direction(env.program_info(), env.console, context, 4.2); + pbf_move_left_joystick(context, 128, 0, 200, 100); + direction.change_direction(env.program_info(), env.console, context, 4.38); + pbf_move_left_joystick(context, 0, 0, 700, 100); + + direction.change_direction(env.program_info(), env.console, context, 0.96); + pbf_move_left_joystick(context, 128, 0, 300, 100); + direction.change_direction(env.program_info(), env.console, context, 5.17); + pbf_move_left_joystick(context, 128, 0, 100, 100); + direction.change_direction(env.program_info(), env.console, context, 3.86); + handle_failed_action(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 500); + check_num_sunflora_found(env, context, 6); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 30, 100); + }, + 3 + ); + + // sunflora 7 + // align to corner 7.1 + direction.change_direction(env.program_info(), env.console, context, 2.06); + pbf_move_left_joystick(context, 128, 0, 80, 100); + direction.change_direction(env.program_info(), env.console, context, 4.7); + pbf_move_left_joystick(context, 128, 0, 100, 100); + direction.change_direction(env.program_info(), env.console, context, 5.01); + pbf_move_left_joystick(context, 128, 0, 1600, 100); + + // align to corner 7.2. bush + direction.change_direction(env.program_info(), env.console, context, 2.34); + pbf_move_left_joystick(context, 128, 0, 700, 100); + direction.change_direction(env.program_info(), env.console, context, 3.42); + pbf_move_left_joystick(context, 128, 0, 400, 100); + + // align to corner 7.3. lamp-post + // todo: adjust routine to get to lampost. go behind the sculpture and goat? + direction.change_direction(env.program_info(), env.console, context, 0); + pbf_move_left_joystick(context, 128, 0, 120, 100); + direction.change_direction(env.program_info(), env.console, context, 1.75); + pbf_move_left_joystick(context, 128, 0, 400, 100); + direction.change_direction(env.program_info(), env.console, context, 2.95); + pbf_move_left_joystick(context, 128, 0, 300, 100); + direction.change_direction(env.program_info(), env.console, context, 2.22); + pbf_move_left_joystick(context, 128, 0, 400, 100); + direction.change_direction(env.program_info(), env.console, context, 1.01); + pbf_move_left_joystick(context, 128, 0, 300, 100); + + // align to corner 7.4. wall corner + direction.change_direction(env.program_info(), env.console, context, 3.70); + pbf_move_left_joystick(context, 128, 0, 400, 100); + direction.change_direction(env.program_info(), env.console, context, 4.28); + pbf_move_left_joystick(context, 128, 0, 400, 100); + direction.change_direction(env.program_info(), env.console, context, 3.54); + pbf_move_left_joystick(context, 128, 0, 600, 100); + + // align to corner 7.5. bush + direction.change_direction(env.program_info(), env.console, context, 3.11); + pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 150); + pbf_move_left_joystick(context, 128, 0, 60, 100); + direction.change_direction(env.program_info(), env.console, context, 4.28); + pbf_move_left_joystick(context, 128, 0, 200, 100); + direction.change_direction(env.program_info(), env.console, context, 3.60); + pbf_move_left_joystick(context, 128, 0, 400, 100); + + direction.change_direction(env.program_info(), env.console, context, 1.17); + pbf_move_left_joystick(context, 128, 0, 130, 100); + handle_failed_action(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 500); + check_num_sunflora_found(env, context, 7); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 30, 100); + }, + 3 + ); + + // sunflora 8 + // align to corner 8.1. bush + direction.change_direction(env.program_info(), env.console, context, 4.54); + pbf_move_left_joystick(context, 128, 0, 200, 100); + pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 150); + pbf_move_left_joystick(context, 128, 0, 200, 100); + direction.change_direction(env.program_info(), env.console, context, 3.60); + pbf_move_left_joystick(context, 128, 0, 400, 100); + + direction.change_direction(env.program_info(), env.console, context, 1.64); + pbf_move_left_joystick(context, 128, 0, 350, 100); + direction.change_direction(env.program_info(), env.console, context, 4.36); + pbf_move_left_joystick(context, 128, 0, 100, 100); + + handle_failed_action(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_press_button(context, BUTTON_A, 50, 50); + pbf_press_button(context, BUTTON_A, 50, 50); // extra press in case one is dropped + pbf_press_button(context, BUTTON_A, 50, 50); + pbf_wait(context, 250); + press_Bs_to_back_to_overworld(env.program_info(), env.console, context); + check_num_sunflora_found(env, context, 8); + pbf_wait(context, 3 * TICKS_PER_SECOND); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 30, 100); + }, + 3 + ); + + // // sunflora 9 + // // align to corner 9.1. bush + pbf_move_left_joystick(context, 128, 255, 200, 100); + direction.change_direction(env.program_info(), env.console, context, 4.89); + pbf_move_left_joystick(context, 128, 0, 350, 100); + pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 180); + get_off_ride(env.program_info(), env.console, context); + direction.change_direction(env.program_info(), env.console, context, 3.60); + pbf_move_left_joystick(context, 128, 0, 600, 100); + + + direction.change_direction(env.program_info(), env.console, context, 1.48); + pbf_move_left_joystick(context, 128, 0, 50, 100); + direction.change_direction(env.program_info(), env.console, context, 3.11); + pbf_move_left_joystick(context, 128, 0, 180, 100); + direction.change_direction(env.program_info(), env.console, context, 4.75); + pbf_move_left_joystick(context, 128, 0, 100, 100); + get_on_ride(env.program_info(), env.console, context); + direction.change_direction(env.program_info(), env.console, context, 5.53); + pbf_move_left_joystick(context, 128, 0, 600, 100); + handle_failed_action(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 500); + check_num_sunflora_found(env, context, 9); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 30, 100); + }, + 3 + ); + + // sunflora 10 + // align to corner 10.1. bush + pbf_move_left_joystick(context, 0, 128, 200, 100); + + direction.change_direction(env.program_info(), env.console, context, 4.02); + pbf_move_left_joystick(context, 128, 0, 250, 100); + handle_failed_action(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 500); + check_num_sunflora_found(env, context, 10); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 30, 100); + }, + 3 + ); + + // go back to Sunflora NPC + // align to corner 11.1. bush + direction.change_direction(env.program_info(), env.console, context, 0.65); + pbf_move_left_joystick(context, 128, 0, 200, 100); + pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 150); + pbf_move_left_joystick(context, 128, 0, 800, 100); + + direction.change_direction(env.program_info(), env.console, context, 4.49); + pbf_move_left_joystick(context, 128, 0, 100, 100); + direction.change_direction(env.program_info(), env.console, context, 5.53); + + NoMinimapWatcher no_minimap(env.console, COLOR_RED, Milliseconds(5000)); + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 30 * TICKS_PER_SECOND, 100); + }, + {no_minimap} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to finish reach the Sunflora NPC.", + env.console + ); + } + env.log("No minimap seen. Likely finished the Artazon gym challenge."); + + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD}); + + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_45( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + }else{ + enter_menu_from_overworld(env.program_info(), env.console, context, -1); + // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. + env.log("Wait 10 seconds."); + context.wait_for(Milliseconds(10 * 1000)); + save_game_from_overworld(env.program_info(), env.console, context); + } + + context.wait_for_all_requests(); + + get_on_ride(env.program_info(), env.console, context); + + DirectionDetector direction; + direction.change_direction(env.program_info(), env.console, context, 1.52); + pbf_move_left_joystick(context, 128, 0, 400, 100); + direction.change_direction(env.program_info(), env.console, context, 2.62); + pbf_move_left_joystick(context, 128, 0, 400, 100); + + direction.change_direction(env.program_info(), env.console, context, 2.18); + pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 150); + pbf_move_left_joystick(context, 128, 0, 400, 100); + direction.change_direction(env.program_info(), env.console, context, 3.16); + pbf_move_left_joystick(context, 0, 0, 100, 50); + + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 20); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 0, 100, 50); + pbf_move_left_joystick(context, 255, 0, 100, 50); + }, + 5, 2, 2 + ); + + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::PROMPT_DIALOG, CallbackEnum::BATTLE, CallbackEnum::DIALOG_ARROW}); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::GRADIENT_ARROW}); + mash_button_till_overworld(env.console, context, BUTTON_A); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_20.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_20.h index a344db5dc6..9c43729401 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_20.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_20.h @@ -1,57 +1,57 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_20_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_20_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_20 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options) const override; -}; - - -// start: Defeated Klawf. At Artazon (West) Pokecenter. -// end: At Artazon Gym building. Battled Nemona. Received Sunflora gym challenge. -void checkpoint_43( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: At Artazon Gym building. Battled Nemona. Received Sunflora gym challenge. -// end: Finished Sunflora gym challenge. -void checkpoint_44( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Finished Sunflora gym challenge. -// end: Defeated Artazon Gym (Grass). Inside gym building. -void checkpoint_45( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_20_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_20_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_20 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options) const override; +}; + + +// start: Defeated Klawf. At Artazon (West) Pokecenter. +// end: At Artazon Gym building. Battled Nemona. Received Sunflora gym challenge. +void checkpoint_43( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: At Artazon Gym building. Battled Nemona. Received Sunflora gym challenge. +// end: Finished Sunflora gym challenge. +void checkpoint_44( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Finished Sunflora gym challenge. +// end: Defeated Artazon Gym (Grass). Inside gym building. +void checkpoint_45( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_21.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_21.cpp index b6424651ad..daa7d080bc 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_21.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_21.cpp @@ -1,128 +1,128 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_21.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_21::name() const{ - return "17.1: Team Star (Fire): Go to East Province (Area One) Pokecenter"; -} - -std::string AutoStory_Segment_21::start_text() const{ - return "Start: Defeated Artazon Gym (Grass). Inside gym building."; -} - -std::string AutoStory_Segment_21::end_text() const{ - return "End: At East Province (Area One) Pokecenter."; -} - -void AutoStory_Segment_21::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.overlay().add_log("Start Segment ", COLOR_ORANGE); - - checkpoint_46(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment ", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - -void checkpoint_46( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - }else{ - enter_menu_from_overworld(env.program_info(), env.console, context, -1); - // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. - env.log("Wait 10 seconds."); - context.wait_for(Milliseconds(10 * 1000)); - save_game_from_overworld(env.program_info(), env.console, context); - } - - context.wait_for_all_requests(); - - pbf_move_left_joystick(context, 128, 255, 500, 100); - pbf_wait(context, 3 * TICKS_PER_SECOND); - // wait for overworld after leaving Gym - wait_for_overworld(env.program_info(), env.console, context, 30); - - // fly to Porto Marinada pokecenter - move_cursor_towards_flypoint_and_go_there(env.program_info(), env.console, context, {ZoomChange::ZOOM_IN, 255, 128, 50}); - - // section 1. set marker to pokecenter - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 255, 0, 50}, - {ZoomChange::ZOOM_IN, 0, 0, 0} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 80, 20, false); - - // section 2. set marker past pokecenter - handle_unexpected_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 180, 0, 30); - }); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 15, 12, 12, false); - - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_21.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_21::name() const{ + return "17.1: Team Star (Fire): Go to East Province (Area One) Pokecenter"; +} + +std::string AutoStory_Segment_21::start_text() const{ + return "Start: Defeated Artazon Gym (Grass). Inside gym building."; +} + +std::string AutoStory_Segment_21::end_text() const{ + return "End: At East Province (Area One) Pokecenter."; +} + +void AutoStory_Segment_21::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment ", COLOR_ORANGE); + + checkpoint_46(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment ", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + +void checkpoint_46( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + }else{ + enter_menu_from_overworld(env.program_info(), env.console, context, -1); + // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. + env.log("Wait 10 seconds."); + context.wait_for(Milliseconds(10 * 1000)); + save_game_from_overworld(env.program_info(), env.console, context); + } + + context.wait_for_all_requests(); + + pbf_move_left_joystick(context, 128, 255, 500, 100); + pbf_wait(context, 3 * TICKS_PER_SECOND); + // wait for overworld after leaving Gym + wait_for_overworld(env.program_info(), env.console, context, 30); + + // fly to Porto Marinada pokecenter + move_cursor_towards_flypoint_and_go_there(env.program_info(), env.console, context, {ZoomChange::ZOOM_IN, 255, 128, 50}); + + // section 1. set marker to pokecenter + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 255, 0, 50}, + {ZoomChange::ZOOM_IN, 0, 0, 0} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 80, 20, false); + + // section 2. set marker past pokecenter + handle_unexpected_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 180, 0, 30); + }); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 15, 12, 12, false); + + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_21.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_21.h index 131dde5af8..43ad7672a4 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_21.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_21.h @@ -1,40 +1,40 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_21_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_21_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_21 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - -// start: Defeated Artazon Gym (Grass). Inside gym building. -// end: At East Province (Area One) Pokecenter. -void checkpoint_46( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_21_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_21_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_21 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + +// start: Defeated Artazon Gym (Grass). Inside gym building. +// end: At East Province (Area One) Pokecenter. +void checkpoint_46( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_22.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_22.cpp index 768059ecc0..693f1eb20e 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_22.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_22.cpp @@ -1,177 +1,177 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_22.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_22::name() const{ - return "17.1: Team Star (Fire): Beat Team Star"; -} - -std::string AutoStory_Segment_22::start_text() const{ - return "Start: At East Province (Area One) Pokecenter."; -} - -std::string AutoStory_Segment_22::end_text() const{ - return "End: "; -} - -void AutoStory_Segment_22::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.overlay().add_log("Start Segment ", COLOR_ORANGE); - - // checkpoint_(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment ", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - -// todo: uncomment checkpoint_save -void checkpoint_47( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - // checkpoint_save(env, context, notif_status_update); - first_attempt = false; - }else{ - enter_menu_from_overworld(env.program_info(), env.console, context, -1); - // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. - env.log("Wait 10 seconds."); - context.wait_for(Milliseconds(10 * 1000)); - save_game_from_overworld(env.program_info(), env.console, context); - } - - context.wait_for_all_requests(); - - - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - -// todo: uncomment checkpoint_save -void checkpoint_48( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - // checkpoint_save(env, context, notif_status_update); - first_attempt = false; - }else{ - enter_menu_from_overworld(env.program_info(), env.console, context, -1); - // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. - env.log("Wait 10 seconds."); - context.wait_for(Milliseconds(10 * 1000)); - save_game_from_overworld(env.program_info(), env.console, context); - } - - context.wait_for_all_requests(); - - - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - -// todo: uncomment checkpoint_save -void checkpoint_49( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - // checkpoint_save(env, context, notif_status_update); - first_attempt = false; - }else{ - enter_menu_from_overworld(env.program_info(), env.console, context, -1); - // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. - env.log("Wait 10 seconds."); - context.wait_for(Milliseconds(10 * 1000)); - save_game_from_overworld(env.program_info(), env.console, context); - } - - context.wait_for_all_requests(); - - - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_22.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_22::name() const{ + return "17.1: Team Star (Fire): Beat Team Star"; +} + +std::string AutoStory_Segment_22::start_text() const{ + return "Start: At East Province (Area One) Pokecenter."; +} + +std::string AutoStory_Segment_22::end_text() const{ + return "End: "; +} + +void AutoStory_Segment_22::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment ", COLOR_ORANGE); + + // checkpoint_(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment ", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + +// todo: uncomment checkpoint_save +void checkpoint_47( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + // checkpoint_save(env, context, notif_status_update); + first_attempt = false; + }else{ + enter_menu_from_overworld(env.program_info(), env.console, context, -1); + // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. + env.log("Wait 10 seconds."); + context.wait_for(Milliseconds(10 * 1000)); + save_game_from_overworld(env.program_info(), env.console, context); + } + + context.wait_for_all_requests(); + + + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + +// todo: uncomment checkpoint_save +void checkpoint_48( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + // checkpoint_save(env, context, notif_status_update); + first_attempt = false; + }else{ + enter_menu_from_overworld(env.program_info(), env.console, context, -1); + // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. + env.log("Wait 10 seconds."); + context.wait_for(Milliseconds(10 * 1000)); + save_game_from_overworld(env.program_info(), env.console, context); + } + + context.wait_for_all_requests(); + + + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + +// todo: uncomment checkpoint_save +void checkpoint_49( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + // checkpoint_save(env, context, notif_status_update); + first_attempt = false; + }else{ + enter_menu_from_overworld(env.program_info(), env.console, context, -1); + // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. + env.log("Wait 10 seconds."); + context.wait_for(Milliseconds(10 * 1000)); + save_game_from_overworld(env.program_info(), env.console, context); + } + + context.wait_for_all_requests(); + + + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_22.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_22.h index 3fe4b57e06..fe55075349 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_22.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_22.h @@ -1,59 +1,59 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_22_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_22_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_22 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: At East Province (Area One) Pokecenter. -// end: -void checkpoint_47( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: -// end: -void checkpoint_48( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: -// end: -void checkpoint_49( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_22_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_22_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_22 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: At East Province (Area One) Pokecenter. +// end: +void checkpoint_47( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: +// end: +void checkpoint_48( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: +// end: +void checkpoint_49( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_23.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_23.cpp index 759db0465e..0850353eab 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_23.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_23.cpp @@ -1,61 +1,61 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_23.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_23::name() const{ - return ""; -} - -std::string AutoStory_Segment_23::start_text() const{ - return "Start: "; -} - -std::string AutoStory_Segment_23::end_text() const{ - return "End: "; -} - -void AutoStory_Segment_23::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.overlay().add_log("Start Segment ", COLOR_ORANGE); - - // checkpoint_(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment ", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_23.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_23::name() const{ + return ""; +} + +std::string AutoStory_Segment_23::start_text() const{ + return "Start: "; +} + +std::string AutoStory_Segment_23::end_text() const{ + return "End: "; +} + +void AutoStory_Segment_23::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment ", COLOR_ORANGE); + + // checkpoint_(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment ", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_23.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_23.h index b6226218c7..4855f0afb3 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_23.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_23.h @@ -1,34 +1,34 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_23_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_23_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_23 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_23_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_23_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_23 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_24.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_24.cpp index 660f0a7826..93f7a96131 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_24.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_24.cpp @@ -1,61 +1,61 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_24.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_24::name() const{ - return ""; -} - -std::string AutoStory_Segment_24::start_text() const{ - return "Start: "; -} - -std::string AutoStory_Segment_24::end_text() const{ - return "End: "; -} - -void AutoStory_Segment_24::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.overlay().add_log("Start Segment ", COLOR_ORANGE); - - // checkpoint_(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment ", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_24.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_24::name() const{ + return ""; +} + +std::string AutoStory_Segment_24::start_text() const{ + return "Start: "; +} + +std::string AutoStory_Segment_24::end_text() const{ + return "End: "; +} + +void AutoStory_Segment_24::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment ", COLOR_ORANGE); + + // checkpoint_(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment ", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_24.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_24.h index e0c4305f92..d3bca07ba5 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_24.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_24.h @@ -1,34 +1,34 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_24_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_24_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_24 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_24_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_24_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_24 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOption.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOption.cpp index 066e0a6bf5..10acb64e80 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOption.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOption.cpp @@ -1,214 +1,214 @@ -/* Menu Option Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/OCR/OCR_NumberReader.h" -#include "PokemonSV_MenuOption.h" -#include "PokemonSV/Inference/PokemonSV_MenuOptionReader.h" - -//#include -// using std::cout; -// using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -MenuOption::~MenuOption() = default; - -MenuOption::MenuOption( - VideoStream& stream, - ProControllerContext& context, - Language language -) - : m_stream(stream) - , m_context(context) - , m_language(language) - , m_overlays(stream.overlay()) - , m_arrow(COLOR_CYAN, GradientArrowType::RIGHT, {0.02, 0.10, 0.05, 0.80}) -{ - // reader.make_overlays(m_overlays); - for (size_t c = 0; c < 10; c++){ - m_boxes_item[c] = ImageFloatBox(0.055, 0.135 + c * 0.0739, 0.260, 0.060); - m_boxes_toggle[c] = ImageFloatBox(0.345, 0.135 + c * 0.0739, 0.175, 0.060); - m_overlays.add(COLOR_BLUE, m_boxes_item[c]); - m_overlays.add(COLOR_BLUE, m_boxes_toggle[c]); - } -} - -void MenuOption::set_options( - const std::vector>>& options -) const{ - for (std::pair> option : options){ - move_to_option(option.first); - set_target_option(option.second); - } -} - -void MenuOption::set_target_option(const std::vector& target_option_toggle_list) const{ - - for (size_t attempt = 0; attempt < 10; attempt++){ - std::string current_option_slug = read_option_toggle(); - MenuOptionToggleEnum current_option_toggle_enum = menu_option_toggle_lookup_by_slug(current_option_slug).enum_value; - - if (std::find(target_option_toggle_list.begin(), target_option_toggle_list.end(), current_option_toggle_enum) != target_option_toggle_list.end()){ - return; - } - - pbf_press_dpad(m_context, DPAD_RIGHT, 10, 50); - } - - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "MenuOption::set_target_option(): Unable to set option to the correct toggle.", - m_stream - ); - -} - -int8_t MenuOption::get_selected_index(const ImageViewRGB32& screen) const { - m_context.wait_for_all_requests(); - ImageFloatBox box; - if (!m_arrow.detect(box, screen)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "MenuOption::get_selected_index(): Unable to find cursor.", - m_stream - ); - } - -// cout << box.y << endl; - double slot = (box.y - 0.135185) / 0.0739; - int8_t selected_index = (int8_t)(slot + 0.5); - - if (selected_index < 0 || selected_index >= 10){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "MenuOption::get_selected_index(): Invalid cursor slot.", - m_stream - ); - } - // cout << "selected index:" + std::to_string(selected_index) << endl; - - return selected_index; -} - -std::string MenuOption::read_option(const ImageViewRGB32& cropped) const{ - // cropped.save("test.png"); - const auto ocr_result = MenuOptionReader::instance().read_substring( - m_stream.logger(), - m_language, - cropped, OCR::BLACK_TEXT_FILTERS() - ); - - std::multimap results; - if (!ocr_result.results.empty()){ - for (const auto& result : ocr_result.results){ - results.emplace(result.first, result.second); - } - } - - if (results.empty()){ - if (m_language == Language::German){ - // German Menu Option uses numbers for text speed settings, which string OCR has trouble with detecting. - int16_t number = read_number(m_stream.logger(), cropped); - switch (number){ - case 1: - return "slow"; - case 2: - return "normal"; - case 3: - return "fast"; - } - } - return ""; - } - - if (results.size() > 1){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "MenuOption::read_option(): Unable to read item. Ambiguous or multiple results.", - m_stream - ); - } - - return results.begin()->second.token; -} - -int16_t MenuOption::read_number( - Logger& logger, - const ImageViewRGB32& cropped -) const{ - - int16_t number = (int16_t)OCR::read_number_waterfill(logger, cropped, 0xff000000, 0xff808080); - - if (number < 1 || number > 3){ - number = -1; - } - return (int16_t)number; -} - -std::string MenuOption::read_option_item() const{ - m_context.wait_for_all_requests(); - VideoSnapshot screen = m_stream.video().snapshot(); - - ImageFloatBox selected_box = m_boxes_item[get_selected_index(screen)]; - ImageViewRGB32 cropped = extract_box_reference(screen, selected_box); - return read_option(cropped); - -} - -std::string MenuOption::read_option_toggle() const{ - m_context.wait_for_all_requests(); - VideoSnapshot screen = m_stream.video().snapshot(); - - ImageFloatBox selected_box = m_boxes_toggle[get_selected_index(screen)]; - ImageViewRGB32 cropped = extract_box_reference(screen, selected_box); - - return read_option(cropped); -} - - -void MenuOption::move_to_option(const MenuOptionItemEnum target_option_enum) const{ - std::string current_option_slug = read_option_item(); - MenuOptionItem current_option = menu_option_item_lookup_by_slug(current_option_slug); - - const MenuOptionItem& target_option = menu_option_item_lookup_by_enum(target_option_enum); - std::string target_option_slug = target_option.slug; - int diff = target_option.index - current_option.index; - // cout << "target_option diff: " << std::to_string(target_option.index) << endl; - // cout << "current_option diff: " << std::to_string(current_option.index) << endl; - // cout << "diff: " << std::to_string(diff) << endl; - while (diff != 0){ - // move cursor in direction of target_option - if (diff > 0){ - for (size_t i = 0; i < (size_t)diff; i++){ - pbf_press_dpad(m_context, DPAD_DOWN, 10, 50); - } - } - if (diff < 0){ - for (size_t i = 0; i < (size_t)-diff; i++){ - pbf_press_dpad(m_context, DPAD_UP, 10, 50); - } - } - current_option_slug = read_option_item(); - current_option = menu_option_item_lookup_by_slug(current_option_slug); - diff = target_option.index - current_option.index; - // cout << "diff: " << std::to_string(diff) << endl; - } -} - - - - - - -} -} -} +/* Menu Option Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/OCR/OCR_NumberReader.h" +#include "PokemonSV_MenuOption.h" +#include "PokemonSV/Inference/PokemonSV_MenuOptionReader.h" + +//#include +// using std::cout; +// using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +MenuOption::~MenuOption() = default; + +MenuOption::MenuOption( + VideoStream& stream, + ProControllerContext& context, + Language language +) + : m_stream(stream) + , m_context(context) + , m_language(language) + , m_overlays(stream.overlay()) + , m_arrow(COLOR_CYAN, GradientArrowType::RIGHT, {0.02, 0.10, 0.05, 0.80}) +{ + // reader.make_overlays(m_overlays); + for (size_t c = 0; c < 10; c++){ + m_boxes_item[c] = ImageFloatBox(0.055, 0.135 + c * 0.0739, 0.260, 0.060); + m_boxes_toggle[c] = ImageFloatBox(0.345, 0.135 + c * 0.0739, 0.175, 0.060); + m_overlays.add(COLOR_BLUE, m_boxes_item[c]); + m_overlays.add(COLOR_BLUE, m_boxes_toggle[c]); + } +} + +void MenuOption::set_options( + const std::vector>>& options +) const{ + for (std::pair> option : options){ + move_to_option(option.first); + set_target_option(option.second); + } +} + +void MenuOption::set_target_option(const std::vector& target_option_toggle_list) const{ + + for (size_t attempt = 0; attempt < 10; attempt++){ + std::string current_option_slug = read_option_toggle(); + MenuOptionToggleEnum current_option_toggle_enum = menu_option_toggle_lookup_by_slug(current_option_slug).enum_value; + + if (std::find(target_option_toggle_list.begin(), target_option_toggle_list.end(), current_option_toggle_enum) != target_option_toggle_list.end()){ + return; + } + + pbf_press_dpad(m_context, DPAD_RIGHT, 10, 50); + } + + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "MenuOption::set_target_option(): Unable to set option to the correct toggle.", + m_stream + ); + +} + +int8_t MenuOption::get_selected_index(const ImageViewRGB32& screen) const { + m_context.wait_for_all_requests(); + ImageFloatBox box; + if (!m_arrow.detect(box, screen)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "MenuOption::get_selected_index(): Unable to find cursor.", + m_stream + ); + } + +// cout << box.y << endl; + double slot = (box.y - 0.135185) / 0.0739; + int8_t selected_index = (int8_t)(slot + 0.5); + + if (selected_index < 0 || selected_index >= 10){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "MenuOption::get_selected_index(): Invalid cursor slot.", + m_stream + ); + } + // cout << "selected index:" + std::to_string(selected_index) << endl; + + return selected_index; +} + +std::string MenuOption::read_option(const ImageViewRGB32& cropped) const{ + // cropped.save("test.png"); + const auto ocr_result = MenuOptionReader::instance().read_substring( + m_stream.logger(), + m_language, + cropped, OCR::BLACK_TEXT_FILTERS() + ); + + std::multimap results; + if (!ocr_result.results.empty()){ + for (const auto& result : ocr_result.results){ + results.emplace(result.first, result.second); + } + } + + if (results.empty()){ + if (m_language == Language::German){ + // German Menu Option uses numbers for text speed settings, which string OCR has trouble with detecting. + int16_t number = read_number(m_stream.logger(), cropped); + switch (number){ + case 1: + return "slow"; + case 2: + return "normal"; + case 3: + return "fast"; + } + } + return ""; + } + + if (results.size() > 1){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "MenuOption::read_option(): Unable to read item. Ambiguous or multiple results.", + m_stream + ); + } + + return results.begin()->second.token; +} + +int16_t MenuOption::read_number( + Logger& logger, + const ImageViewRGB32& cropped +) const{ + + int16_t number = (int16_t)OCR::read_number_waterfill(logger, cropped, 0xff000000, 0xff808080); + + if (number < 1 || number > 3){ + number = -1; + } + return (int16_t)number; +} + +std::string MenuOption::read_option_item() const{ + m_context.wait_for_all_requests(); + VideoSnapshot screen = m_stream.video().snapshot(); + + ImageFloatBox selected_box = m_boxes_item[get_selected_index(screen)]; + ImageViewRGB32 cropped = extract_box_reference(screen, selected_box); + return read_option(cropped); + +} + +std::string MenuOption::read_option_toggle() const{ + m_context.wait_for_all_requests(); + VideoSnapshot screen = m_stream.video().snapshot(); + + ImageFloatBox selected_box = m_boxes_toggle[get_selected_index(screen)]; + ImageViewRGB32 cropped = extract_box_reference(screen, selected_box); + + return read_option(cropped); +} + + +void MenuOption::move_to_option(const MenuOptionItemEnum target_option_enum) const{ + std::string current_option_slug = read_option_item(); + MenuOptionItem current_option = menu_option_item_lookup_by_slug(current_option_slug); + + const MenuOptionItem& target_option = menu_option_item_lookup_by_enum(target_option_enum); + std::string target_option_slug = target_option.slug; + int diff = target_option.index - current_option.index; + // cout << "target_option diff: " << std::to_string(target_option.index) << endl; + // cout << "current_option diff: " << std::to_string(current_option.index) << endl; + // cout << "diff: " << std::to_string(diff) << endl; + while (diff != 0){ + // move cursor in direction of target_option + if (diff > 0){ + for (size_t i = 0; i < (size_t)diff; i++){ + pbf_press_dpad(m_context, DPAD_DOWN, 10, 50); + } + } + if (diff < 0){ + for (size_t i = 0; i < (size_t)-diff; i++){ + pbf_press_dpad(m_context, DPAD_UP, 10, 50); + } + } + current_option_slug = read_option_item(); + current_option = menu_option_item_lookup_by_slug(current_option_slug); + diff = target_option.index - current_option.index; + // cout << "diff: " << std::to_string(diff) << endl; + } +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOption.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOption.h index 3919bc71c3..4ee5ddeb52 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOption.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOption.h @@ -1,82 +1,81 @@ -/* Menu Option Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_MenuOption_H -#define PokemonAutomation_PokemonSV_MenuOption_H - -#include -#include "CommonFramework/Language.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" -#include "PokemonSV_MenuOptionDatabase.h" - -namespace PokemonAutomation{ - class AsyncDispatcher; -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class MenuOption{ -public: - ~MenuOption(); - MenuOption( - VideoStream& stream, ProControllerContext& context, - Language language - ); - - // change all settings as per options - void set_options( - const std::vector>>& options) const; - -private: - - // set the current selected option, to one of the option_toggle in the given list. - // We need a list of option_toggle since the mapping for the options in each language is slightly different. - // - e.g. For "Send to Boxes", the options may be Manual/Automatic in English, but may be On/Off in other languages. - // the program keeps cycling the options, until it matches one of the option_toggles in the list. - void set_target_option( - const std::vector& target_option_toggle_list - ) const; - - // Move to the target_option. - // Returns empty string if not found. - void move_to_option(const MenuOptionItemEnum target_option) const; - - std::string read_option(const ImageViewRGB32& cropped) const; - - int16_t read_number(Logger& logger, const ImageViewRGB32& cropped) const; - - // return the slug for the selected menu option item - std::string read_option_item() const; - - // return the slug for the selected menu option toggle - std::string read_option_toggle() const; - - // return the index row of the currently selected item. - // this detects the gradient arrow. - int8_t get_selected_index(const ImageViewRGB32& screen) const; - - -private: - VideoStream& m_stream; - ProControllerContext& m_context; - Language m_language; - VideoOverlaySet m_overlays; - GradientArrowDetector m_arrow; - std::array m_boxes_item; - std::array m_boxes_toggle; -}; - - - - -} -} -} -#endif +/* Menu Option Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_MenuOption_H +#define PokemonAutomation_PokemonSV_MenuOption_H + +#include +#include "CommonFramework/Language.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" +#include "PokemonSV_MenuOptionDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class MenuOption{ +public: + ~MenuOption(); + MenuOption( + VideoStream& stream, ProControllerContext& context, + Language language + ); + + // change all settings as per options + void set_options( + const std::vector>>& options) const; + +private: + + // set the current selected option, to one of the option_toggle in the given list. + // We need a list of option_toggle since the mapping for the options in each language is slightly different. + // - e.g. For "Send to Boxes", the options may be Manual/Automatic in English, but may be On/Off in other languages. + // the program keeps cycling the options, until it matches one of the option_toggles in the list. + void set_target_option( + const std::vector& target_option_toggle_list + ) const; + + // Move to the target_option. + // Returns empty string if not found. + void move_to_option(const MenuOptionItemEnum target_option) const; + + std::string read_option(const ImageViewRGB32& cropped) const; + + int16_t read_number(Logger& logger, const ImageViewRGB32& cropped) const; + + // return the slug for the selected menu option item + std::string read_option_item() const; + + // return the slug for the selected menu option toggle + std::string read_option_toggle() const; + + // return the index row of the currently selected item. + // this detects the gradient arrow. + int8_t get_selected_index(const ImageViewRGB32& screen) const; + + +private: + VideoStream& m_stream; + ProControllerContext& m_context; + Language m_language; + VideoOverlaySet m_overlays; + GradientArrowDetector m_arrow; + std::array m_boxes_item; + std::array m_boxes_toggle; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOptionDatabase.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOptionDatabase.cpp index 3ad10e57a2..5a9d31f8e6 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOptionDatabase.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOptionDatabase.cpp @@ -1,148 +1,148 @@ -/* Menu Option Database - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "PokemonSV_MenuOptionDatabase.h" -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -static const std::vector& MenuOption_AllItems(){ - static const std::vector database{ - {MenuOptionItemEnum::TEXT_SPEED, "text-speed", 0}, - {MenuOptionItemEnum::SKIP_MOVE_LEARNING, "skip-move-learning", 1}, - {MenuOptionItemEnum::SEND_TO_BOXES, "send-to-boxes", 2}, - {MenuOptionItemEnum::GIVE_NICKNAMES, "give-nicknames", 3}, - {MenuOptionItemEnum::VERTICAL_CAMERA_CONTROLS, "vertical-camera-controls", 4}, - {MenuOptionItemEnum::HORIZONTAL_CAMERA_CONTROLS, "horizontal-camera-controls", 5}, - {MenuOptionItemEnum::CAMERA_SUPPORT, "camera-support", 6}, - {MenuOptionItemEnum::CAMERA_INTERPOLATION, "camera-interpolation", 7}, - {MenuOptionItemEnum::CAMERA_DISTANCE, "camera-distance", 8}, - {MenuOptionItemEnum::AUTOSAVE, "autosave", 9}, - {MenuOptionItemEnum::SHOW_NICKNAMES, "show-nicknames", 10}, - {MenuOptionItemEnum::SKIP_CUTSCENES, "skip-cutscenes", 11}, - {MenuOptionItemEnum::BACKGROUN_MUSIC, "background-music", 12}, - {MenuOptionItemEnum::SOUND_EFFECTS, "sound-effects", 13}, - {MenuOptionItemEnum::POKEMON_CRIES, "pokemon-cries", 14}, - {MenuOptionItemEnum::CONTROLLER_RUMBLE, "controller-rumble", 15}, - {MenuOptionItemEnum::HELPING_FUNCTIONS, "helping-functions", 16}, - {MenuOptionItemEnum::CONTROLS_WHILE_FLYING, "controls-while-flying", 17}, - }; - - return database; - -} - -static const std::vector& MenuOption_AllToggles(){ - static const std::vector database{ - {MenuOptionToggleEnum::SLOW, "slow"}, - {MenuOptionToggleEnum::AVERAGE, "average"}, - {MenuOptionToggleEnum::NORMAL, "normal"}, - {MenuOptionToggleEnum::FAST, "fast"}, - {MenuOptionToggleEnum::ON, "on"}, - {MenuOptionToggleEnum::OFF, "off"}, - {MenuOptionToggleEnum::MANUAL, "manual"}, - {MenuOptionToggleEnum::AUTOMATIC, "automatic"}, - {MenuOptionToggleEnum::REGULAR, "regular"}, - {MenuOptionToggleEnum::INVERTED, "inverted"}, - {MenuOptionToggleEnum::CLOSE, "close"}, - {MenuOptionToggleEnum::FAR, "far"}, - {MenuOptionToggleEnum::DONT_SHOW, "dont-show"}, - {MenuOptionToggleEnum::SHOW, "show"}, - }; - - return database; - -} - -static std::map make_MenuOptionItem_lookup_by_enum(){ - std::map ret; - for (const MenuOptionItem& item : MenuOption_AllItems()){ - if (!ret.emplace(item.enum_value, &item).second){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum: " + std::to_string((int)item.enum_value)); - } - } - return ret; -} -const MenuOptionItem& menu_option_item_lookup_by_enum(MenuOptionItemEnum enum_value){ - static const std::map database = make_MenuOptionItem_lookup_by_enum(); - auto iter = database.find(enum_value); - if (iter != database.end()){ - return *iter->second; - }else{ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Enum: " + std::to_string((int)enum_value)); - } -} -static std::map make_MenuOptionItem_lookup_by_slug(){ - std::map ret; - for (const MenuOptionItem& item : MenuOption_AllItems()){ - if (!ret.emplace(item.slug, &item).second){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum: " + item.slug); - } - } - return ret; -} -const MenuOptionItem& menu_option_item_lookup_by_slug(std::string& slug){ - static const std::map database = make_MenuOptionItem_lookup_by_slug(); - auto iter = database.find(slug); - if (iter != database.end()){ - return *iter->second; - }else{ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Enum: " + slug); - } -} - -static std::map make_MenuOptionToggle_lookup_by_enum(){ - std::map ret; - for (const MenuOptionToggle& item : MenuOption_AllToggles()){ - if (!ret.emplace(item.enum_value, &item).second){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum: " + std::to_string((int)item.enum_value)); - } - } - return ret; -} -const MenuOptionToggle& menu_option_toggle_lookup_by_enum(MenuOptionToggleEnum enum_value){ - static const std::map database = make_MenuOptionToggle_lookup_by_enum(); - auto iter = database.find(enum_value); - if (iter != database.end()){ - return *iter->second; - }else{ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Enum: " + std::to_string((int)enum_value)); - } -} - -static std::map make_MenuOptionToggle_lookup_by_slug(){ - std::map ret; - for (const MenuOptionToggle& item : MenuOption_AllToggles()){ - if (!ret.emplace(item.slug, &item).second){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum: " + item.slug); - } - } - return ret; -} -const MenuOptionToggle& menu_option_toggle_lookup_by_slug(std::string& slug){ - static const std::map database = make_MenuOptionToggle_lookup_by_slug(); - auto iter = database.find(slug); - if (iter != database.end()){ - return *iter->second; - }else{ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Enum: " + slug); - } -} - - - - -} -} -} +/* Menu Option Database + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "PokemonSV_MenuOptionDatabase.h" +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +static const std::vector& MenuOption_AllItems(){ + static const std::vector database{ + {MenuOptionItemEnum::TEXT_SPEED, "text-speed", 0}, + {MenuOptionItemEnum::SKIP_MOVE_LEARNING, "skip-move-learning", 1}, + {MenuOptionItemEnum::SEND_TO_BOXES, "send-to-boxes", 2}, + {MenuOptionItemEnum::GIVE_NICKNAMES, "give-nicknames", 3}, + {MenuOptionItemEnum::VERTICAL_CAMERA_CONTROLS, "vertical-camera-controls", 4}, + {MenuOptionItemEnum::HORIZONTAL_CAMERA_CONTROLS, "horizontal-camera-controls", 5}, + {MenuOptionItemEnum::CAMERA_SUPPORT, "camera-support", 6}, + {MenuOptionItemEnum::CAMERA_INTERPOLATION, "camera-interpolation", 7}, + {MenuOptionItemEnum::CAMERA_DISTANCE, "camera-distance", 8}, + {MenuOptionItemEnum::AUTOSAVE, "autosave", 9}, + {MenuOptionItemEnum::SHOW_NICKNAMES, "show-nicknames", 10}, + {MenuOptionItemEnum::SKIP_CUTSCENES, "skip-cutscenes", 11}, + {MenuOptionItemEnum::BACKGROUN_MUSIC, "background-music", 12}, + {MenuOptionItemEnum::SOUND_EFFECTS, "sound-effects", 13}, + {MenuOptionItemEnum::POKEMON_CRIES, "pokemon-cries", 14}, + {MenuOptionItemEnum::CONTROLLER_RUMBLE, "controller-rumble", 15}, + {MenuOptionItemEnum::HELPING_FUNCTIONS, "helping-functions", 16}, + {MenuOptionItemEnum::CONTROLS_WHILE_FLYING, "controls-while-flying", 17}, + }; + + return database; + +} + +static const std::vector& MenuOption_AllToggles(){ + static const std::vector database{ + {MenuOptionToggleEnum::SLOW, "slow"}, + {MenuOptionToggleEnum::AVERAGE, "average"}, + {MenuOptionToggleEnum::NORMAL, "normal"}, + {MenuOptionToggleEnum::FAST, "fast"}, + {MenuOptionToggleEnum::ON, "on"}, + {MenuOptionToggleEnum::OFF, "off"}, + {MenuOptionToggleEnum::MANUAL, "manual"}, + {MenuOptionToggleEnum::AUTOMATIC, "automatic"}, + {MenuOptionToggleEnum::REGULAR, "regular"}, + {MenuOptionToggleEnum::INVERTED, "inverted"}, + {MenuOptionToggleEnum::CLOSE, "close"}, + {MenuOptionToggleEnum::FAR, "far"}, + {MenuOptionToggleEnum::DONT_SHOW, "dont-show"}, + {MenuOptionToggleEnum::SHOW, "show"}, + }; + + return database; + +} + +static std::map make_MenuOptionItem_lookup_by_enum(){ + std::map ret; + for (const MenuOptionItem& item : MenuOption_AllItems()){ + if (!ret.emplace(item.enum_value, &item).second){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum: " + std::to_string((int)item.enum_value)); + } + } + return ret; +} +const MenuOptionItem& menu_option_item_lookup_by_enum(MenuOptionItemEnum enum_value){ + static const std::map database = make_MenuOptionItem_lookup_by_enum(); + auto iter = database.find(enum_value); + if (iter != database.end()){ + return *iter->second; + }else{ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Enum: " + std::to_string((int)enum_value)); + } +} +static std::map make_MenuOptionItem_lookup_by_slug(){ + std::map ret; + for (const MenuOptionItem& item : MenuOption_AllItems()){ + if (!ret.emplace(item.slug, &item).second){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum: " + item.slug); + } + } + return ret; +} +const MenuOptionItem& menu_option_item_lookup_by_slug(std::string& slug){ + static const std::map database = make_MenuOptionItem_lookup_by_slug(); + auto iter = database.find(slug); + if (iter != database.end()){ + return *iter->second; + }else{ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Enum: " + slug); + } +} + +static std::map make_MenuOptionToggle_lookup_by_enum(){ + std::map ret; + for (const MenuOptionToggle& item : MenuOption_AllToggles()){ + if (!ret.emplace(item.enum_value, &item).second){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum: " + std::to_string((int)item.enum_value)); + } + } + return ret; +} +const MenuOptionToggle& menu_option_toggle_lookup_by_enum(MenuOptionToggleEnum enum_value){ + static const std::map database = make_MenuOptionToggle_lookup_by_enum(); + auto iter = database.find(enum_value); + if (iter != database.end()){ + return *iter->second; + }else{ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Enum: " + std::to_string((int)enum_value)); + } +} + +static std::map make_MenuOptionToggle_lookup_by_slug(){ + std::map ret; + for (const MenuOptionToggle& item : MenuOption_AllToggles()){ + if (!ret.emplace(item.slug, &item).second){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum: " + item.slug); + } + } + return ret; +} +const MenuOptionToggle& menu_option_toggle_lookup_by_slug(std::string& slug){ + static const std::map database = make_MenuOptionToggle_lookup_by_slug(); + auto iter = database.find(slug); + if (iter != database.end()){ + return *iter->second; + }else{ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Enum: " + slug); + } +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOptionDatabase.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOptionDatabase.h index 860fa89c56..51e41dc881 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOptionDatabase.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOptionDatabase.h @@ -1,80 +1,79 @@ -/* Menu Option Database - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_MenuOptionDatabase_H -#define PokemonAutomation_PokemonSV_MenuOptionDatabase_H - -#include - -namespace PokemonAutomation{ - class AsyncDispatcher; -namespace NintendoSwitch{ -namespace PokemonSV{ - - -enum class MenuOptionItemEnum{ - TEXT_SPEED, - SKIP_MOVE_LEARNING, - SEND_TO_BOXES, - GIVE_NICKNAMES, - VERTICAL_CAMERA_CONTROLS, - HORIZONTAL_CAMERA_CONTROLS, - CAMERA_SUPPORT, - CAMERA_INTERPOLATION, - CAMERA_DISTANCE, - AUTOSAVE, - SHOW_NICKNAMES, - SKIP_CUTSCENES, - BACKGROUN_MUSIC, - SOUND_EFFECTS, - POKEMON_CRIES, - CONTROLLER_RUMBLE, - HELPING_FUNCTIONS, - CONTROLS_WHILE_FLYING, -}; - -enum class MenuOptionToggleEnum{ - SLOW, - AVERAGE, - NORMAL, - FAST, - ON, - OFF, - MANUAL, - AUTOMATIC, - REGULAR, - INVERTED, - CLOSE, - FAR, - DONT_SHOW, - SHOW, - -}; - -struct MenuOptionItem{ - MenuOptionItemEnum enum_value; - std::string slug; - int8_t index; -}; - -struct MenuOptionToggle{ - MenuOptionToggleEnum enum_value; - std::string slug; - -}; - -const MenuOptionItem& menu_option_item_lookup_by_enum(MenuOptionItemEnum enum_value); - -const MenuOptionItem& menu_option_item_lookup_by_slug(std::string& slug); - -const MenuOptionToggle& menu_option_toggle_lookup_by_enum(MenuOptionToggleEnum enum_value); - -const MenuOptionToggle& menu_option_toggle_lookup_by_slug(std::string& slug); - -} -} -} -#endif +/* Menu Option Database + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_MenuOptionDatabase_H +#define PokemonAutomation_PokemonSV_MenuOptionDatabase_H + +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +enum class MenuOptionItemEnum{ + TEXT_SPEED, + SKIP_MOVE_LEARNING, + SEND_TO_BOXES, + GIVE_NICKNAMES, + VERTICAL_CAMERA_CONTROLS, + HORIZONTAL_CAMERA_CONTROLS, + CAMERA_SUPPORT, + CAMERA_INTERPOLATION, + CAMERA_DISTANCE, + AUTOSAVE, + SHOW_NICKNAMES, + SKIP_CUTSCENES, + BACKGROUN_MUSIC, + SOUND_EFFECTS, + POKEMON_CRIES, + CONTROLLER_RUMBLE, + HELPING_FUNCTIONS, + CONTROLS_WHILE_FLYING, +}; + +enum class MenuOptionToggleEnum{ + SLOW, + AVERAGE, + NORMAL, + FAST, + ON, + OFF, + MANUAL, + AUTOMATIC, + REGULAR, + INVERTED, + CLOSE, + FAR, + DONT_SHOW, + SHOW, + +}; + +struct MenuOptionItem{ + MenuOptionItemEnum enum_value; + std::string slug; + int8_t index; +}; + +struct MenuOptionToggle{ + MenuOptionToggleEnum enum_value; + std::string slug; + +}; + +const MenuOptionItem& menu_option_item_lookup_by_enum(MenuOptionItemEnum enum_value); + +const MenuOptionItem& menu_option_item_lookup_by_slug(std::string& slug); + +const MenuOptionToggle& menu_option_toggle_lookup_by_enum(MenuOptionToggleEnum enum_value); + +const MenuOptionToggle& menu_option_toggle_lookup_by_slug(std::string& slug); + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_OliveActionFailedException.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_OliveActionFailedException.h index 5eddccb907..5ab0d6f4ce 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_OliveActionFailedException.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_OliveActionFailedException.h @@ -1,53 +1,53 @@ -/* Operation Failed Exception - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_OliveActionFailedException_H -#define PokemonAutomation_OliveActionFailedException_H - -#include "CommonFramework/Exceptions/OperationFailedException.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class FatalProgramException; - -enum class OliveFail{ - NONE, - FAILED_ALIGN_TO_OLIVE, - FAILED_PUSH_OLIVE_TOTAL_DISTANCE, - NO_OLIVE_DETECTED, - FAILED_WALK_TO_OLIVE, - OLIVE_STUCK, -}; - -// Thrown by subroutines if they fail for an in-game reason. -// These include recoverable errors which can be consumed by the program. -class OliveActionFailedException : public OperationFailedException{ -public: - OliveActionFailedException( - ErrorReport error_report, - std::string message, - VideoStream& stream, - OliveFail fail_reason = OliveFail::NONE - ) - : OperationFailedException(error_report, std::move(message), stream) - , m_fail_reason(fail_reason) - {} - virtual const char* name() const override{ return "OliveActionFailedException"; } - -public: - OliveFail m_fail_reason; - -}; - - - - -} -} -} -#endif +/* Operation Failed Exception + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_OliveActionFailedException_H +#define PokemonAutomation_OliveActionFailedException_H + +#include "CommonFramework/Exceptions/OperationFailedException.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class FatalProgramException; + +enum class OliveFail{ + NONE, + FAILED_ALIGN_TO_OLIVE, + FAILED_PUSH_OLIVE_TOTAL_DISTANCE, + NO_OLIVE_DETECTED, + FAILED_WALK_TO_OLIVE, + OLIVE_STUCK, +}; + +// Thrown by subroutines if they fail for an in-game reason. +// These include recoverable errors which can be consumed by the program. +class OliveActionFailedException : public OperationFailedException{ +public: + OliveActionFailedException( + ErrorReport error_report, + std::string message, + VideoStream& stream, + OliveFail fail_reason = OliveFail::NONE + ) + : OperationFailedException(error_report, std::move(message), stream) + , m_fail_reason(fail_reason) + {} + virtual const char* name() const override{ return "OliveActionFailedException"; } + +public: + OliveFail m_fail_reason; + +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_Battles.cpp b/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_Battles.cpp index e03e8b4584..fdf46969f6 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_Battles.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_Battles.cpp @@ -4,14 +4,22 @@ * */ +#include +#include "CommonFramework/Exceptions/ProgramFinishedException.h" #include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Exceptions/FatalProgramException.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" #include "CommonTools/Async/InferenceRoutines.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_DataTypes.h" #include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Pokemon_Notification.h" +#include "PokemonSV/Options/PokemonSV_EncounterBotCommon.h" #include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" #include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" #include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" #include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "PokemonSV_BasicCatcher.h" #include "PokemonSV_Battles.h" namespace PokemonAutomation{ @@ -85,7 +93,9 @@ void auto_heal_from_menu_or_overworld( -int run_from_battle(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ +int run_from_battle( + VideoStream& stream, ProControllerContext& context +){ stream.log("Attempting to run away..."); int attempts = 0; @@ -139,6 +149,232 @@ int run_from_battle(const ProgramInfo& info, VideoStream& stream, ProControllerC } +int run_from_battle( + VideoStream& stream, ProControllerContext& context, + OverworldBattleTracker& tracker +){ + stream.log("Attempting to run away..."); + + int attempts = 0; + for (size_t c = 0; c < 10; c++){ + OverworldWatcher overworld(stream.logger(), COLOR_RED); + NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); + GradientArrowWatcher next_pokemon(COLOR_GREEN, GradientArrowType::RIGHT, {0.50, 0.51, 0.30, 0.10}); + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, std::chrono::seconds(60), + { + overworld, + battle_menu, + next_pokemon, + } + ); + + switch (ret){ + case 0: + stream.log("Detected overworld..."); + tracker.report_out_of_battle(); + return attempts; + case 1:{ + stream.log("Detected battle menu..."); + OverworldBattleTracker::Detection result = tracker.report_battle_menu_detected(); + if (result != OverworldBattleTracker::Detection::CONTINUE_BATTLE){ + stream.log("Successfully ran away, but were chain attacked.", COLOR_ORANGE); + return attempts; + } + + battle_menu.move_to_slot(stream, context, 3); +// pbf_press_dpad(context, DPAD_DOWN, 250, 0); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_B, 20, 1 * TICKS_PER_SECOND); + attempts++; + continue; + } + case 2: + stream.log("Detected own " + STRING_POKEMON + " fainted..."); + tracker.report_in_battle(); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Your " + STRING_POKEMON + " fainted while attempting to run away.", + stream + ); + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "run_from_battle(): No state detected after 60 seconds.", + stream + ); + } + } + + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to run away after 10 attempts.", + stream + ); +} + + + + + + +void process_battle( + bool& caught, bool& should_save, + ProgramEnvironment& env, + EncounterBotCommonOptions& settings, + VideoStream& stream, ProControllerContext& context, + OverworldBattleTracker& tracker, + EncounterFrequencies& encounter_frequencies, + std::atomic& shiny_counter, + Language language +){ + std::set slugs; + if (language != Language::None){ + slugs = read_singles_opponent(env.program_info(), stream, context, language); + encounter_frequencies += slugs; + stream.log(encounter_frequencies.dump_sorted_map("Encounter Stats:\n")); + } + + VideoSnapshot shiny_screenshot; + float shiny_error; + OverworldBattleTracker::Detection type = tracker.report_battle_menu_detected(shiny_screenshot, shiny_error); + bool is_shiny = type == OverworldBattleTracker::Detection::NEW_SHINY_BATTLE; + if (is_shiny){ + shiny_counter++; + if (settings.VIDEO_ON_SHINY){ + context.wait_for(std::chrono::seconds(3)); + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 0); + } + } + env.update_stats(); + + send_encounter_notification( + env, + settings.NOTIFICATION_NONSHINY, + settings.NOTIFICATION_SHINY, + language != Language::None, + is_shiny, + {{slugs, is_shiny ? ShinyType::UNKNOWN_SHINY : ShinyType::NOT_SHINY}}, + is_shiny ? shiny_error : std::nan(""), + shiny_screenshot, + &encounter_frequencies + ); + + tracker.report_in_battle(); + + // Set default action: stop program if shiny, otherwise run away. + EncounterActionsEntry action; + action.action = is_shiny + ? EncounterActionsAction::STOP_PROGRAM + : EncounterActionsAction::RUN_AWAY; + + // Iterate the actions table. If found an entry matches the pokemon species, + // set the action to be what specified in the entry. + for (EncounterActionsEntry& entry : settings.ACTIONS_TABLE.snapshot()){ + if (language == Language::None){ + throw UserSetupError(stream.logger(), "You must set the game language to use the actions table."); + } + + // See if Pokemon name matches. + auto iter = slugs.find(entry.pokemon); + if (iter == slugs.end()){ + continue; + } + + switch (entry.shininess){ + case EncounterActionsShininess::ANYTHING: + break; + case EncounterActionsShininess::NOT_SHINY: + if (is_shiny){ + continue; + } + break; + case EncounterActionsShininess::SHINY: + if (!is_shiny){ + continue; + } + break; + } + + action = std::move(entry); + } + + // Run the chosen action. + switch (action.action){ + case EncounterActionsAction::RUN_AWAY: + try{ + run_from_battle(stream, context, tracker); + }catch (OperationFailedException& e){ + throw FatalProgramException(std::move(e)); + } + caught = false; + should_save = false; + return; + case EncounterActionsAction::STOP_PROGRAM: + throw ProgramFinishedException(); +// throw ProgramFinishedException(m_stream, "", true); + case EncounterActionsAction::THROW_BALLS: + case EncounterActionsAction::THROW_BALLS_AND_SAVE: + if (language == Language::None){ + throw InternalProgramError(&stream.logger(), PA_CURRENT_FUNCTION, "Language is not set."); + } + + CatchResults result = basic_catcher( + stream, context, + language, + action.ball, action.ball_limit, + settings.USE_FIRST_MOVE_IF_CANNOT_THROW_BALL + ); + send_catch_notification( + env, + settings.NOTIFICATION_CATCH_SUCCESS, + settings.NOTIFICATION_CATCH_FAILED, + &slugs, + action.ball, + result.balls_used, + result.result + ); + + switch (result.result){ + case CatchResult::POKEMON_CAUGHT: + case CatchResult::POKEMON_FAINTED: + break; + default: + throw_and_log( + stream.logger(), ErrorReport::NO_ERROR_REPORT, + "Unable to recover from failed catch.", + stream + ); + } + + caught = result.result == CatchResult::POKEMON_CAUGHT; + should_save = caught && action.action == EncounterActionsAction::THROW_BALLS_AND_SAVE; + return; + } + + caught = false; + should_save = false; +} + + + + + + + + + + + + + + + + + + + } } } diff --git a/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_Battles.h b/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_Battles.h index ea76487c43..5390bd2e67 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_Battles.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_Battles.h @@ -9,14 +9,19 @@ #include #include "CommonFramework/Tools/VideoStream.h" +#include "CommonFramework/Language.h" #include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "Pokemon/Pokemon_EncounterStats.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldSensors.h" namespace PokemonAutomation{ struct ProgramInfo; + class ProgramEnvironment; namespace NintendoSwitch{ + using namespace Pokemon; namespace PokemonSV{ - +class EncounterBotCommonOptions; void auto_heal_from_menu_or_overworld( @@ -28,7 +33,27 @@ void auto_heal_from_menu_or_overworld( // Returns the # of attempts it took to run. -int run_from_battle(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); +int run_from_battle( + VideoStream& stream, ProControllerContext& context +); +int run_from_battle( + VideoStream& stream, ProControllerContext& context, + OverworldBattleTracker& tracker +); + + + +void process_battle( + bool& caught, bool& should_save, + ProgramEnvironment& env, + EncounterBotCommonOptions& settings, + VideoStream& stream, ProControllerContext& context, + OverworldBattleTracker& tracker, + EncounterFrequencies& encounter_frequencies, + std::atomic& shiny_counter, + Language language +); + diff --git a/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRelease.cpp b/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRelease.cpp index 374118cf91..bab0a47019 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRelease.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRelease.cpp @@ -40,12 +40,15 @@ void release_one_pokemon( ); } + // The advance dialog is ambiguous against 2 other states. Therefore, + // if we see it, we do not decide that is the state unless it holds for + // 1 second without any of the other states firing. SomethingInBoxSlotDetector exists(COLOR_BLUE); // GradientArrowDetector change_marks(COLOR_MAGENTA, GradientArrowType::DOWN, {0.28, 0.38, 0.30, 0.10}); BoxWatcher box_detector(COLOR_RED); BoxSelectWatcher selected(COLOR_YELLOW, std::chrono::milliseconds(100)); PromptDialogWatcher confirm(COLOR_CYAN, std::chrono::milliseconds(100)); - AdvanceDialogWatcher advance_dialog(COLOR_GREEN, DialogType::DIALOG_ALL, std::chrono::milliseconds(250)); + AdvanceDialogWatcher advance_dialog(COLOR_GREEN, DialogType::DIALOG_ALL, std::chrono::milliseconds(1000)); context.wait_for_all_requests(); int ret = wait_until( @@ -58,7 +61,8 @@ void release_one_pokemon( advance_dialog } ); - context.wait_for(std::chrono::milliseconds(50)); +// cout << "ret0 = " << ret << endl; + context.wait_for(std::chrono::milliseconds(100)); if (ret == 3){ // Make sure we're not mistakening this for the other dialogs. auto screenshot = stream.video().snapshot(); @@ -68,6 +72,7 @@ void release_one_pokemon( ret = 2; } } +// cout << "ret1 = " << ret << endl; // cout << "consecutive_box_neutrals = " << consecutive_box_neutrals << endl; switch (ret){ @@ -101,6 +106,7 @@ void release_one_pokemon( if (exists.detect(screenshot)){ if (release_attempted && release_completed){ +// cout << "return 0" << endl; return; } release_attempted = false; @@ -110,6 +116,7 @@ void release_one_pokemon( continue; }else{ stream.log("Slot is empty."); +// cout << "return 1" << endl; return; } } @@ -148,6 +155,7 @@ void release_one_pokemon( stream.log("Detected advance dialog. (unexpected)", COLOR_RED); errors++; } + pbf_press_dpad(context, DPAD_UP, 10, 10); pbf_press_button(context, BUTTON_A, 20, 20); release_completed = true; expected = 0; diff --git a/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.cpp b/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.cpp index 2d14485165..dbd283796f 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.cpp @@ -201,7 +201,7 @@ void hold_one_column(const ProgramInfo& info, VideoStream& stream, ProController // Select rest of the pary // Press down multiple times to make sure we select full party in case the game drops some presses for(int i = 0; i < 15; i++){ - ssf_press_dpad(context, DPAD_DOWN, 4, 5, 3); + ssf_press_dpad(context, DPAD_DOWN, 32ms); ssf_press_left_joystick(context, 128, 255, 4, 5, 3); } // Hold rest of the party diff --git a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggAutonomous.cpp b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggAutonomous.cpp index b071f455d2..8ae5fe2919 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggAutonomous.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggAutonomous.cpp @@ -9,6 +9,7 @@ #include "CommonFramework/Exceptions/ProgramFinishedException.h" #include "CommonFramework/Exceptions/FatalProgramException.h" #include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Exceptions/UnexpectedBattleException.h" #include "CommonFramework/Options/Environment/ThemeSelectorOption.h" #include "CommonFramework/Notifications/ProgramNotifications.h" #include "CommonFramework/ProgramStats/StatsTracking.h" @@ -92,6 +93,15 @@ EggAutonomous::EggAutonomous() LockMode::LOCK_WHILE_RUNNING, true ) + , LOCATION( + "Location:
The location to hatch eggs.", + { + {EggAutoLocation::ZeroGate, "zero-gate", "Zero Gate"}, + {EggAutoLocation::NorthLighthouse, "north-lighthouse", "North Province (Area Three) Lighthouse"} + }, + LockMode::LOCK_WHILE_RUNNING, + EggAutoLocation::ZeroGate + ) , MAX_KEEPERS( "Max Keepers:
Stop the program after keeping this many " + STRING_POKEMON + ". " "The program will put them into a box neighboring the current box.", @@ -172,6 +182,7 @@ EggAutonomous::EggAutonomous() PA_ADD_OPTION(GO_HOME_WHEN_DONE); PA_ADD_OPTION(LANGUAGE); PA_ADD_OPTION(EGG_SANDWICH); + PA_ADD_OPTION(LOCATION); PA_ADD_OPTION(MAX_KEEPERS); PA_ADD_OPTION(AUTO_SAVING); PA_ADD_OPTION(KEEP_BOX_LOCATION); @@ -211,7 +222,7 @@ void EggAutonomous::program(SingleSwitchProgramEnvironment& env, ProControllerCo m_num_sandwich_spent = 0; m_num_kept = 0; size_t consecutive_failures = 0; - while(true){ + while (true){ m_saved_after_fetched_eggs = false; m_in_critical_to_save_stage = false; @@ -227,24 +238,42 @@ void EggAutonomous::program(SingleSwitchProgramEnvironment& env, ProControllerCo // Recoverable loop to fetch eggs: int num_party_eggs = -1; - while(true){ + while (true){ try{ num_party_eggs = fetch_eggs_full_routine(env, context); break; - }catch (OperationFailedException& e){ - handle_recoverable_error(env, context, NOTIFICATION_ERROR_RECOVERABLE, e, consecutive_failures); + }catch (ScreenshotException& e){ + if (handle_recoverable_error( + env, context, + NOTIFICATION_ERROR_RECOVERABLE, + e, + consecutive_failures + )){ + throw; + } } // end try catch } // end recoverable loop to fetch eggs: // Recoverable loop to hatch eggs bool game_already_resetted = false; - while(true){ + while (true){ try{ hatch_eggs_full_routine(env, context, num_party_eggs); consecutive_failures = 0; break; - }catch (OperationFailedException& e){ - handle_recoverable_error(env, context, NOTIFICATION_ERROR_RECOVERABLE, e, consecutive_failures); + }catch (ProgramFinishedException&){ + env.update_stats(); + GO_HOME_WHEN_DONE.run_end_of_program(context); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + return; + }catch (ScreenshotException& e){ + if (handle_recoverable_error( + env, context, + NOTIFICATION_ERROR_RECOVERABLE, + e, consecutive_failures + )){ + throw; + } // After resetting the game, we don't know how many eggs in party num_party_eggs = -1; @@ -255,11 +284,6 @@ void EggAutonomous::program(SingleSwitchProgramEnvironment& env, ProControllerCo game_already_resetted = true; break; } - }catch (ProgramFinishedException&){ - env.update_stats(); - GO_HOME_WHEN_DONE.run_end_of_program(context); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - return; } // end try catch } // end recoverable loop to hatch eggs @@ -298,7 +322,12 @@ void EggAutonomous::program(SingleSwitchProgramEnvironment& env, ProControllerCo int EggAutonomous::fetch_eggs_full_routine(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ auto& stats = env.current_stats(); - picnic_at_zero_gate(env.program_info(), env.console, context); + if (LOCATION == EggAutoLocation::ZeroGate) { + picnic_at_zero_gate(env.program_info(), env.console, context); + } else { + pbf_press_button(context, BUTTON_L, 50, 40); + picnic_from_overworld(env.program_info(), env.console, context); + } // Now we are at picnic. We are at one end of picnic table while the egg basket is at the other end bool can_make_sandwich = eat_egg_sandwich_at_picnic(env, env.console, context, EGG_SANDWICH.EGG_SANDWICH_TYPE, LANGUAGE); @@ -324,7 +353,13 @@ int EggAutonomous::fetch_eggs_full_routine(SingleSwitchProgramEnvironment& env, leave_picnic(env.program_info(), env.console, context); // Reset position to flying spot: - reset_position_to_flying_spot(env, context); + if (LOCATION == EggAutoLocation::ZeroGate) { + reset_position_to_flying_spot(env, context); + } else { + //Lighthouse: We haven't moved much so just fly. + open_map_from_overworld(env.program_info(), env.console, context); + fly_to_overworld_from_map(env.program_info(), env.console, context); + } return picnic_party_to_hatch_party(env, context); } @@ -422,8 +457,16 @@ void EggAutonomous::hatch_eggs_full_routine(SingleSwitchProgramEnvironment& env, stats.m_hatched++; env.update_stats(); }; - hatch_eggs_at_zero_gate(env.program_info(), env.console, context, (uint8_t)num_eggs_in_party, hatched_callback); - reset_position_to_flying_spot(env, context); + if (LOCATION == EggAutoLocation::ZeroGate) { + hatch_eggs_at_zero_gate(env.program_info(), env.console, context, (uint8_t)num_eggs_in_party, hatched_callback); + reset_position_to_flying_spot(env, context); + } else { + hatch_eggs_at_area_three_lighthouse(env.program_info(), env.console, context, (uint8_t)num_eggs_in_party, hatched_callback); + reset_position_to_flying_spot(env, context); + //Clear spawns - over time floette/vivillon drift over past the fence (usually aroudn the 3rd batch) + picnic_from_overworld(env.program_info(), env.console, context); + leave_picnic(env.program_info(), env.console, context); + } enter_box_system_from_overworld(env.program_info(), env.console, context); @@ -633,7 +676,12 @@ bool EggAutonomous::move_pokemon_to_keep(SingleSwitchProgramEnvironment& env, Pr void EggAutonomous::reset_position_to_flying_spot(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ // Use map to fly back to the flying spot open_map_from_overworld(env.program_info(), env.console, context); - pbf_move_left_joystick(context, 128, 160, 20, 50); + if (LOCATION == EggAutoLocation::ZeroGate) { + pbf_move_left_joystick(context, 128, 160, 20, 50); + } else { //lighthouse + pbf_move_left_joystick(context, 130, 0, 150ms, 50ms); + pbf_press_button(context, BUTTON_ZL, 40, 100); + } fly_to_overworld_from_map(env.program_info(), env.console, context); } @@ -689,10 +737,10 @@ void EggAutonomous::save_game(SingleSwitchProgramEnvironment& env, ProController } -void EggAutonomous::handle_recoverable_error( +bool EggAutonomous::handle_recoverable_error( SingleSwitchProgramEnvironment& env, ProControllerContext& context, EventNotificationOption& notification, - OperationFailedException& e, + const ScreenshotException& e, size_t& consecutive_failures ){ auto& stats = env.current_stats(); @@ -707,7 +755,7 @@ void EggAutonomous::handle_recoverable_error( } // if there is no auto save, then we shouldn't reset game to lose previous progress. if (AUTO_SAVING == AutoSave::NoAutoSave){ - throw std::move(e); + return true; } if (AUTO_SAVING == AutoSave::AfterStartAndKeep && m_in_critical_to_save_stage){ @@ -717,7 +765,7 @@ void EggAutonomous::handle_recoverable_error( // in this auto saving mode, every batch of eggs have been saved beforehand. env.log("Found an error before we can save the game to protect the newly kept pokemon.", COLOR_RED); env.log("Don't reset game to protect it.", COLOR_RED); - throw std::move(e); + return true; } consecutive_failures++; @@ -731,6 +779,8 @@ void EggAutonomous::handle_recoverable_error( env.log("Reset game to handle recoverable error"); reset_game(env.program_info(), env.console, context); + + return false; } diff --git a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggAutonomous.h b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggAutonomous.h index 2e533563ab..69de407f5c 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggAutonomous.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggAutonomous.h @@ -19,6 +19,7 @@ namespace PokemonAutomation{ +class ScreenshotException; class OperationFailedException; namespace NintendoSwitch{ @@ -58,10 +59,11 @@ class EggAutonomous : public SingleSwitchProgramInstance{ void save_game(SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool from_overworld); - void handle_recoverable_error( + // Return true if you should rethrow. + bool handle_recoverable_error( SingleSwitchProgramEnvironment& env, ProControllerContext& context, EventNotificationOption& notification, - OperationFailedException& e, + const ScreenshotException& e, size_t& consecutive_failures ); @@ -74,6 +76,13 @@ class EggAutonomous : public SingleSwitchProgramInstance{ GoHomeWhenDoneOption GO_HOME_WHEN_DONE; OCR::LanguageOCROption LANGUAGE; + + enum class EggAutoLocation{ + ZeroGate, + NorthLighthouse, + }; + EnumDropdownOption LOCATION; + SimpleIntegerOption MAX_KEEPERS; enum class AutoSave{ diff --git a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggHatcher.cpp b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggHatcher.cpp index 3ccc1b7981..9248a6bd2a 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggHatcher.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggHatcher.cpp @@ -204,7 +204,7 @@ void EggHatcher::program(SingleSwitchProgramEnvironment& env, ProControllerConte hatch_one_box(env, context); } - } catch(OperationFailedException&){ + } catch(Exception&){ stats.m_errors++; env.update_stats(); throw; diff --git a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.cpp b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.cpp index bfaa6a14fd..f65c59a122 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.cpp @@ -5,6 +5,7 @@ */ #include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" #include "CommonFramework/Tools/ErrorDumper.h" #include "CommonFramework/VideoPipeline/VideoFeed.h" #include "CommonFramework/VideoPipeline/VideoOverlay.h" @@ -22,6 +23,7 @@ #include "PokemonSV/Inference/Boxes/PokemonSV_BoxNatureDetector.h" #include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" #include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" +#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" #include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" #include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" #include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" @@ -122,6 +124,7 @@ void do_egg_cycle_motion( VideoStream& stream, ProControllerContext& context ){ AdvanceDialogWatcher dialog(COLOR_RED); + NormalBattleMenuWatcher battle_menu(COLOR_GREEN); int ret = run_until( stream, context, [&](ProControllerContext& context){ @@ -132,9 +135,22 @@ void do_egg_cycle_motion( ssf_press_right_joystick(context, 255, 128, 0ms, std::chrono::minutes(10)); pbf_press_button(context, BUTTON_LCLICK, std::chrono::minutes(10), 0ms); }, - {dialog} + { + dialog, + battle_menu, + } ); - if (ret < 0){ + switch (ret){ + case 0: + break; + case 1: + OperationFailedException::fire( + ErrorReport::NO_ERROR_REPORT, + "Detected battle menu. You got attacked!", + stream + ); + break; + case 2: dump_image_and_throw_recoverable_exception( info, stream, "NoEggToHatch", "hatch_eggs_at_zero_gate(): No more egg hatch after 10 minutes." @@ -306,7 +322,7 @@ bool eat_egg_sandwich_at_picnic( throw UserSetupError(stream.logger(), "Must set game language option to read ingredient lists to make herb sandwich."); } make_two_herbs_sandwich( - env.program_info(), env.realtime_inference_dispatcher(), + env, stream, context, sandwich_type, language @@ -603,6 +619,70 @@ void hatch_eggs_at_zero_gate( } // end hatching each egg } +void hatch_eggs_at_area_three_lighthouse( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + uint8_t num_eggs_in_party, + std::function egg_hatched_callback) +{ + bool got_off_ramp = false; + for(uint8_t egg_idx = 0; egg_idx < num_eggs_in_party; egg_idx++){ + stream.log("Hatching egg " + std::to_string(egg_idx+1) + "/" + std::to_string(num_eggs_in_party) + "."); + stream.overlay().add_log("Hatching egg " + std::to_string(egg_idx+1) + "/" + std::to_string(num_eggs_in_party), COLOR_BLUE); + + // Orient camera to look at same direction as player character + // This is needed because when save-load the game, the camera is reset + // to this location. + pbf_press_button(context, BUTTON_L, 50, 40); + + context.wait_for_all_requests(); + + if (got_off_ramp == false){ + AdvanceDialogWatcher dialog(COLOR_RED); + // first, navigate to a clear area in the team star base for circling motions + int ret = run_until( + stream, context, + [&](ProControllerContext& context){ + if (egg_idx == 0){ + //Run forward a bit + pbf_move_left_joystick(context, 128, 0, 150, 20); + //Face at an angle, to avoid the tent to the left + pbf_move_left_joystick(context, 0, 0, 50, 50); + //Get on your mount + pbf_press_button(context, BUTTON_L, 50, 40); + pbf_press_button(context, BUTTON_PLUS, 50, 100); + //Go in deep, spawns outside the fence like to come in otherwise + pbf_move_left_joystick(context, 128, 0, 750, 0); + pbf_move_left_joystick(context, 0, 0, 50, 50); + pbf_press_button(context, BUTTON_L, 50, 40); + pbf_move_left_joystick(context, 128, 0, 550, 0); + } + }, + {dialog} + ); + if (ret == 0){ + // egg hatching when going off ramp: + handle_egg_hatching(info, stream, context, num_eggs_in_party, egg_idx, egg_hatched_callback); + + stream.log("Reset location by flying back to lighthouse."); + // Use map to fly back to the flying spot + open_map_from_overworld(info, stream, context); + pbf_move_left_joystick(context, 200, 0, 20, 50); + fly_to_overworld_from_map(info, stream, context); + continue; + } + + got_off_ramp = true; + stream.log("Got off ramp"); + } + + // Circular motions: + do_egg_cycle_motion(info, stream, context); + + handle_egg_hatching(info, stream, context, num_eggs_in_party, egg_idx, egg_hatched_callback); + } // end hatching each egg +} + void hatch_eggs_anywhere( const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, diff --git a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h index b4d6b74f26..a4bef8f465 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h @@ -17,7 +17,6 @@ namespace PokemonAutomation{ struct ProgramInfo; - class AsyncDispatcher; class ImageViewRGB32; namespace OCR{ @@ -77,6 +76,18 @@ void hatch_eggs_at_zero_gate( std::function egg_hatched_callback = nullptr ); +// Start at North Province (Area Three) Lighthouse flying spot, go in circles in Ruchbah (fairy) Squad's base to hatch eggs. +// Switch 2 only, this is an alternate egg hatch spot as Zero Gate now has spawns in the way. +// Switch 1 is untested in this location but the area is extremely laggy. +// This is a minor modification to hatch_eggs_at_zero_gate +// `egg_hatched_callback` will be called after each egg hatched, with egg index (0-indexed) +void hatch_eggs_at_area_three_lighthouse( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + uint8_t num_eggs_in_party, + std::function egg_hatched_callback = nullptr +); + // From overworld, go in circles to hatch eggs. // `egg_hatched_callback` will be called after each egg hatched, with egg index (0-indexed) // `already_on_ride`: whether the player character is on ride when starting the function. diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryCatchPhoto.cpp b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryCatchPhoto.cpp index 8aea2e01b6..29fe5f4d73 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryCatchPhoto.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryCatchPhoto.cpp @@ -82,9 +82,9 @@ CameraAngle quest_photo_navi( //Jump down pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - ssf_press_button(context, BUTTON_B, 0, 100); - ssf_press_button(context, BUTTON_B, 0, 20, 10); - ssf_press_button(context, BUTTON_B, 0, 20); + ssf_press_button(context, BUTTON_B, 0ms, 800ms); + ssf_press_button(context, BUTTON_B, 0ms, 160ms, 80ms); + ssf_press_button(context, BUTTON_B, 0ms, 160ms); pbf_wait(context, 100); context.wait_for_all_requests(); @@ -126,7 +126,11 @@ CameraAngle quest_photo_navi( pbf_press_button(context, BUTTON_L, 20, 50); pbf_move_left_joystick(context, 128, 0, 100, 50); - pbf_move_left_joystick(context, 0, 0, 20, 50); + + //Turn slightly for switch 1 + if (console.state().console_type() == ConsoleType::Switch1) { + pbf_move_left_joystick(context, 0, 0, 20, 50); + } break; case BBQuests::photo_bug: case BBQuests::photo_rock: @@ -179,8 +183,8 @@ CameraAngle quest_photo_navi( pbf_press_button(context, BUTTON_L, 20, 50); break; - case BBQuests::photo_flying: case BBQuests::photo_dark: - console.log("Photo: Dark/Flying"); + case BBQuests::photo_flying: + console.log("Photo: Flying"); //Vullaby/Mandibuzz central_to_savanna_plaza(info, console, context); @@ -224,8 +228,8 @@ CameraAngle quest_photo_navi( context.wait_for_all_requests(); break; - case BBQuests::photo_poison: - console.log("Photo: Poison"); + case BBQuests::photo_poison: case BBQuests::photo_dark: + console.log("Photo: Poison/Dark"); //Muk-A - area a bit laggy but consistently so central_to_coastal_plaza(info, console, context); @@ -400,8 +404,11 @@ void quest_catch_navi( pbf_press_button(context, BUTTON_L, 20, 50); pbf_move_left_joystick(context, 128, 0, 100, 50); - pbf_move_left_joystick(context, 0, 0, 20, 50); - pbf_press_button(context, BUTTON_L, 20, 50); + //Turn slightly for switch 1 + if (console.state().console_type() == ConsoleType::Switch1) { + pbf_move_left_joystick(context, 0, 0, 20, 50); + pbf_press_button(context, BUTTON_L, 20, 50); + } break; @@ -430,9 +437,9 @@ void quest_catch_navi( //Jump down pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - ssf_press_button(context, BUTTON_B, 0, 100); - ssf_press_button(context, BUTTON_B, 0, 20, 10); - ssf_press_button(context, BUTTON_B, 0, 20); + ssf_press_button(context, BUTTON_B, 0ms, 800ms); + ssf_press_button(context, BUTTON_B, 0ms, 160ms, 80ms); + ssf_press_button(context, BUTTON_B, 0ms, 160ms); pbf_wait(context, 100); context.wait_for_all_requests(); @@ -504,8 +511,8 @@ void quest_catch_navi( jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 1000, 1650, 500); break; - case BBQuests::catch_dark: case BBQuests::catch_flying: - console.log("Catch: Dark/Flying"); + case BBQuests::catch_flying: + console.log("Catch: Flying"); //Vullaby/Mandibuzz central_to_savanna_plaza(info, console, context); @@ -577,8 +584,8 @@ void quest_catch_navi( pbf_move_left_joystick(context, 128, 0, 50, 50); break; - case BBQuests::catch_poison: - console.log("Catch: Poison"); + case BBQuests::catch_poison: case BBQuests::catch_dark: + console.log("Catch: Poison/Dark"); //Muk-A - area a bit laggy but consistently so central_to_coastal_plaza(info, console, context); @@ -595,18 +602,18 @@ void quest_catch_navi( pbf_press_button(context, BUTTON_PLUS, 20, 105); //Extra throws for this one - ssf_press_button(context, BUTTON_ZR, 0, 200); - ssf_press_button(context, BUTTON_ZL, 100, 50); - ssf_press_button(context, BUTTON_ZL, 150, 50); + ssf_press_button(context, BUTTON_ZR, 0ms, 1600ms); + ssf_press_button(context, BUTTON_ZL, 800ms, 400ms); + ssf_press_button(context, BUTTON_ZL, 1200ms, 400ms); pbf_wait(context, 200); context.wait_for_all_requests(); pbf_press_button(context, BUTTON_ZR, 20, 50); //Withdraw pokemon pbf_move_left_joystick(context, 255, 128, 20, 50); pbf_press_button(context, BUTTON_L, 20, 50); - ssf_press_button(context, BUTTON_ZR, 0, 200); - ssf_press_button(context, BUTTON_ZL, 100, 50); - ssf_press_button(context, BUTTON_ZL, 150, 50); + ssf_press_button(context, BUTTON_ZR, 0ms, 1600ms); + ssf_press_button(context, BUTTON_ZL, 800ms, 400ms); + ssf_press_button(context, BUTTON_ZL, 1200ms, 400ms); pbf_wait(context, 200); context.wait_for_all_requests(); pbf_press_button(context, BUTTON_ZR, 20, 50); //Withdraw pokemon @@ -641,9 +648,9 @@ void quest_catch_navi( } //Lock on and throw ball - ssf_press_button(context, BUTTON_ZR, 0, 200); - ssf_press_button(context, BUTTON_ZL, 100, 50); - ssf_press_button(context, BUTTON_ZL, 150, 50); + ssf_press_button(context, BUTTON_ZR, 0ms, 1600ms); + ssf_press_button(context, BUTTON_ZL, 800ms, 400ms); + ssf_press_button(context, BUTTON_ZL, 1200ms, 400ms); pbf_wait(context, 300); context.wait_for_all_requests(); diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.cpp b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.cpp index 6abc56f210..d77127e9da 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.cpp @@ -27,6 +27,7 @@ #include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" #include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" #include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldSensors.h" #include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" #include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" #include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" @@ -664,9 +665,9 @@ void quest_tera_self_defeat( jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 1000, 1600, 300); } - ssf_press_button(context, BUTTON_ZR, 0, 200); - ssf_press_button(context, BUTTON_ZL, 100, 50); - ssf_press_button(context, BUTTON_ZL, 150, 50); + ssf_press_button(context, BUTTON_ZR, 0ms, 1600ms); + ssf_press_button(context, BUTTON_ZL, 800ms, 400ms); + ssf_press_button(context, BUTTON_ZL, 1200ms, 400ms); pbf_wait(context, 300); context.wait_for_all_requests(); @@ -764,9 +765,9 @@ void quest_sneak_up( pbf_press_button(context, BUTTON_L, 20, 50); } - ssf_press_button(context, BUTTON_ZR, 0, 200); - ssf_press_button(context, BUTTON_ZL, 100, 50); - ssf_press_button(context, BUTTON_ZL, 150, 50); + ssf_press_button(context, BUTTON_ZR, 0ms, 1600ms); + ssf_press_button(context, BUTTON_ZL, 800ms, 400ms); + ssf_press_button(context, BUTTON_ZL, 1200ms, 400ms); pbf_wait(context, 300); context.wait_for_all_requests(); @@ -884,9 +885,9 @@ void quest_wild_tera( pbf_press_button(context, BUTTON_L, 20, 50); } - ssf_press_button(context, BUTTON_ZR, 0, 200); - ssf_press_button(context, BUTTON_ZL, 100, 50); - ssf_press_button(context, BUTTON_ZL, 150, 50); + ssf_press_button(context, BUTTON_ZR, 0ms, 1600ms); + ssf_press_button(context, BUTTON_ZL, 800ms, 400ms); + ssf_press_button(context, BUTTON_ZL, 1200ms, 400ms); pbf_wait(context, 300); context.wait_for_all_requests(); @@ -1001,12 +1002,12 @@ void quest_wash_pokemon(const ProgramInfo& info, VideoStream& stream, ProControl case 2: stream.log("In wash. Scrubbing."); - ssf_press_button(context, BUTTON_A, 0, 200, 0); + ssf_press_button(context, BUTTON_A, 0ms, 1600ms, 0ms); ssf_press_left_joystick(context, 0, 128, 0, 50); ssf_press_left_joystick(context, 255, 128, 50, 100); ssf_press_left_joystick(context, 0, 128, 150, 50); - ssf_press_button(context, BUTTON_A, 0, 200, 0); + ssf_press_button(context, BUTTON_A, 0ms, 1600ms, 0ms); ssf_press_left_joystick(context, 128, 0, 0, 50); ssf_press_left_joystick(context, 128, 255, 50, 100); ssf_press_left_joystick(context, 128, 0, 150, 50); @@ -1026,12 +1027,12 @@ void quest_wash_pokemon(const ProgramInfo& info, VideoStream& stream, ProControl stream.log("Failed to finish rinse after 1 minute.", COLOR_RED); break; } - ssf_press_button(context, BUTTON_A, 0, 200, 0); + ssf_press_button(context, BUTTON_A, 0ms, 1600ms, 0ms); ssf_press_left_joystick(context, 0, 128, 0, 50); ssf_press_left_joystick(context, 255, 128, 50, 100); ssf_press_left_joystick(context, 0, 128, 150, 50); - ssf_press_button(context, BUTTON_A, 0, 200, 0); + ssf_press_button(context, BUTTON_A, 0ms, 1600ms, 0ms); ssf_press_left_joystick(context, 128, 0, 0, 50); ssf_press_left_joystick(context, 128, 255, 50, 100); ssf_press_left_joystick(context, 128, 0, 150, 50); @@ -1325,8 +1326,17 @@ void quest_auto_battle( ){ stream.log("Quest: Auto Battle 10/30"); + + OverworldSensors sensors( + env.logger(), stream, context + ); + LetsGoEncounterBotStats stats; - LetsGoEncounterBotTracker tracker(env, stream, context, stats, BBQ_OPTIONS.LANGUAGE); + LetsGoEncounterBotTracker tracker( + env, stream, + stats, + sensors.lets_go_kill + ); uint64_t target_number = 10; diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.h b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.h index 48d187b6b6..32344f4f9e 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.h @@ -49,7 +49,7 @@ const std::set gold_quests = { //Quests that are not currently supported. Gold quests currently excluded as this is singleplayer only right now. const std::set not_possible_quests = { - BBQuests::UnableToDetect, BBQuests::pickup_10 + BBQuests::UnableToDetect, BBQuests::pickup_10, BBQuests::photo_flying, BBQuests::catch_flying }; diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmer.cpp b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmer.cpp index c2e1eb43aa..78888fe266 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmer.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmer.cpp @@ -1,110 +1,110 @@ -/* Material Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_MaterialFarmer.h" - -// #include -// using std::cout; -// using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - -MaterialFarmer_Descriptor::MaterialFarmer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:MaterialFarmer", - STRING_POKEMON + " SV", "Material Farmer", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/MaterialFarmer.md", - "Farm materials - Happiny dust from Chanseys/Blisseys, for Item Printer.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController} - ) -{} - -std::unique_ptr MaterialFarmer_Descriptor::make_stats() const{ - return std::unique_ptr(new MaterialFarmerStats()); -} - - -MaterialFarmer::MaterialFarmer() - : GO_HOME_WHEN_DONE(true) - , MATERIAL_FARMER_OPTIONS( - GroupOption::EnableMode::ALWAYS_ENABLED, - nullptr, - NOTIFICATION_STATUS_UPDATE, - NOTIFICATION_PROGRAM_FINISH, - NOTIFICATION_ERROR_RECOVERABLE, - NOTIFICATION_ERROR_FATAL - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(MATERIAL_FARMER_OPTIONS); - PA_ADD_OPTION(NOTIFICATIONS); -} - - -void MaterialFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - - // Connect the controller. - pbf_press_button(context, BUTTON_L, 10, 50); - - // Throw user setup errors early in program - // - Ensure language is set - const Language language = MATERIAL_FARMER_OPTIONS.LANGUAGE; - if (language == Language::None) { - throw UserSetupError(env.console.logger(), "Must set game language option to read ingredient lists."); - } - - // - Ensure audio input is enabled - LetsGoKillSoundDetector audio_detector(env.console, [](float){ return true; }); - wait_until( - env.console, context, - std::chrono::milliseconds(1100), - {audio_detector} - ); - audio_detector.throw_if_no_sound(std::chrono::milliseconds(1000)); - - // start by warping to pokecenter for positioning reasons - if (!MATERIAL_FARMER_OPTIONS.SKIP_WARP_TO_POKECENTER){ - reset_to_pokecenter(env.program_info(), env.console, context); - } - - MaterialFarmerStats& stats = env.current_stats(); - - try{ - run_material_farmer(env, env.console, context, MATERIAL_FARMER_OPTIONS, stats); - }catch (ProgramFinishedException&){} - - GO_HOME_WHEN_DONE.run_end_of_program(context); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - -} -} -} +/* Material Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_MaterialFarmer.h" + +// #include +// using std::cout; +// using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + +MaterialFarmer_Descriptor::MaterialFarmer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:MaterialFarmer", + STRING_POKEMON + " SV", "Material Farmer", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/MaterialFarmer.md", + "Farm materials - Happiny dust from Chanseys/Blisseys, for Item Printer.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController} + ) +{} + +std::unique_ptr MaterialFarmer_Descriptor::make_stats() const{ + return std::unique_ptr(new MaterialFarmerStats()); +} + + +MaterialFarmer::MaterialFarmer() + : GO_HOME_WHEN_DONE(true) + , MATERIAL_FARMER_OPTIONS( + GroupOption::EnableMode::ALWAYS_ENABLED, + nullptr, + NOTIFICATION_STATUS_UPDATE, + NOTIFICATION_PROGRAM_FINISH, + NOTIFICATION_ERROR_RECOVERABLE, + NOTIFICATION_ERROR_FATAL + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(MATERIAL_FARMER_OPTIONS); + PA_ADD_OPTION(NOTIFICATIONS); +} + + +void MaterialFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + + // Connect the controller. + pbf_press_button(context, BUTTON_L, 10, 50); + + // Throw user setup errors early in program + // - Ensure language is set + const Language language = MATERIAL_FARMER_OPTIONS.LANGUAGE; + if (language == Language::None) { + throw UserSetupError(env.console.logger(), "Must set game language option to read ingredient lists."); + } + + // - Ensure audio input is enabled + LetsGoKillSoundDetector audio_detector(env.console, [](float){ return true; }); + wait_until( + env.console, context, + std::chrono::milliseconds(1100), + {audio_detector} + ); + audio_detector.throw_if_no_sound(std::chrono::milliseconds(1000)); + + // start by warping to pokecenter for positioning reasons + if (!MATERIAL_FARMER_OPTIONS.SKIP_WARP_TO_POKECENTER){ + reset_to_pokecenter(env.program_info(), env.console, context); + } + + MaterialFarmerStats& stats = env.current_stats(); + + try{ + run_material_farmer(env, env.console, context, MATERIAL_FARMER_OPTIONS, stats); + }catch (ProgramFinishedException&){} + + GO_HOME_WHEN_DONE.run_end_of_program(context); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmer.h b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmer.h index a2b2edd1f1..30b85f4d9b 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmer.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmer.h @@ -1,50 +1,50 @@ -/* Material Farmer - Happiny dust - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_MaterialFarmer_H -#define PokemonAutomation_PokemonSV_MaterialFarmer_H - -#include -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "PokemonSV/Options/PokemonSV_SandwichMakerOption.h" -#include "PokemonSV_MaterialFarmerTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class MaterialFarmer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - MaterialFarmer_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - -class MaterialFarmer : public SingleSwitchProgramInstance{ -public: - MaterialFarmer(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - MaterialFarmerOptions MATERIAL_FARMER_OPTIONS; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - - -} -} -} -#endif +/* Material Farmer - Happiny dust + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_MaterialFarmer_H +#define PokemonAutomation_PokemonSV_MaterialFarmer_H + +#include +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "PokemonSV/Options/PokemonSV_SandwichMakerOption.h" +#include "PokemonSV_MaterialFarmerTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class MaterialFarmer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + MaterialFarmer_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + +class MaterialFarmer : public SingleSwitchProgramInstance{ +public: + MaterialFarmer(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + MaterialFarmerOptions MATERIAL_FARMER_OPTIONS; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.cpp b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.cpp index d0a7075b27..fa5caa6d70 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.cpp @@ -1,870 +1,883 @@ -/* Material Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Exceptions/FatalProgramException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/Battles/PokemonSV_Battles.h" -#include "PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h" -#include "PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h" -#include "PokemonSV_MaterialFarmerTools.h" - -// #include -// using std::cout; -// using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -MaterialFarmerOptions::~MaterialFarmerOptions(){ -// ENABLE_SANDWICH.remove_listener(*this); -} - -MaterialFarmerOptions::MaterialFarmerOptions( - GroupOption::EnableMode enable_mode, - OCR::LanguageOCROption* language_option, - EventNotificationOption& notif_status_update_option, - EventNotificationOption& notif_program_finish_option, - EventNotificationOption& notif_error_recoverable_option, - EventNotificationOption& notif_error_fatal_option -) - : GroupOption( - "Material Farmer", - LockMode::UNLOCK_WHILE_RUNNING, - enable_mode - ) - , m_language_owner(language_option == nullptr - ? new OCR::LanguageOCROption( - "Game Language:
Required to read sandwich ingredients.", - IV_READER().languages(), - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - : nullptr - ) - , RUN_TIME_IN_MINUTES( - "Run Duration:
Run the material farmer for this many minutes.", - LockMode::UNLOCK_WHILE_RUNNING, - 32 - ) -// , SAVE_GAME_BEFORE_SANDWICH( -// "Save Game before each round:", -// LockMode::UNLOCK_WHILE_RUNNING, -// true -// ) -// , SAVE_GAME_BEFORE_SANDWICH_STATIC_TEXT("") -// , NUM_SANDWICH_ROUNDS_STATIC_TEXT("") - , LANGUAGE(language_option == nullptr ? *m_language_owner : *language_option) - , SANDWICH_OPTIONS( - "Make a Sandwich", - &LANGUAGE, - BaseRecipe::non_shiny, - true, - GroupOption::EnableMode::DEFAULT_DISABLED - ) - , AUTO_HEAL_PERCENT( - "Auto-Heal %
Auto-heal if your HP drops below this percentage.", - LockMode::UNLOCK_WHILE_RUNNING, - 75, 0, 100 - ) - , m_advanced_options( - "Advanced Options: (developer only)" - ) - , SAVE_DEBUG_VIDEO( - "Save debug videos to Switch:
" - "Set this on to save a Switch video everytime an error occurs. You can send the video to developers to help them debug later.", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , SKIP_WARP_TO_POKECENTER( - "Skip warping to closest PokeCenter:
" - "This is for debugging the program without waiting for the initial warp.", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) -// , ENABLE_SANDWICH( -// "Enable Sandwich making:
" -// "This is for boosting spawn rates of specific Pokemon.", -// LockMode::UNLOCK_WHILE_RUNNING, -// false -// ) - , TIME_PER_SANDWICH( - "Time per sandwich:
Number of minutes before resetting sandwich.", - LockMode::UNLOCK_WHILE_RUNNING, - 30, 1, 30 - ) - , NUM_FORWARD_MOVES_PER_LETS_GO_ITERATION( - "Number of forward moves per lets go iteration:
" - "During Let's go autobattling sequence, the number of forward movements before resetting to Pokecenter.", - LockMode::UNLOCK_WHILE_RUNNING, - 13 - ) - , NOTIFICATION_STATUS_UPDATE(notif_status_update_option) - , NOTIFICATION_PROGRAM_FINISH(notif_program_finish_option) - , NOTIFICATION_ERROR_RECOVERABLE(notif_error_recoverable_option) - , NOTIFICATION_ERROR_FATAL(notif_error_fatal_option) -{ - PA_ADD_OPTION(RUN_TIME_IN_MINUTES); -// PA_ADD_OPTION(ENABLE_SANDWICH); -// PA_ADD_OPTION(SAVE_GAME_BEFORE_SANDWICH); -// PA_ADD_OPTION(SAVE_GAME_BEFORE_SANDWICH_STATIC_TEXT); -// PA_ADD_OPTION(NUM_SANDWICH_ROUNDS_STATIC_TEXT); - if (m_language_owner){ - PA_ADD_OPTION(LANGUAGE); - } - PA_ADD_OPTION(SANDWICH_OPTIONS); - PA_ADD_OPTION(AUTO_HEAL_PERCENT); - - if (PreloadSettings::instance().DEVELOPER_MODE){ - PA_ADD_OPTION(m_advanced_options); - PA_ADD_OPTION(SAVE_DEBUG_VIDEO); - PA_ADD_OPTION(SKIP_WARP_TO_POKECENTER); - PA_ADD_OPTION(TIME_PER_SANDWICH); - PA_ADD_OPTION(NUM_FORWARD_MOVES_PER_LETS_GO_ITERATION); - } - - MaterialFarmerOptions::on_config_value_changed(this); -// ENABLE_SANDWICH.add_listener(*this); -} - -void MaterialFarmerOptions::on_config_value_changed(void* object){ - -// if (MaterialFarmerOptions::ENABLE_SANDWICH){ -// SAVE_GAME_BEFORE_SANDWICH_STATIC_TEXT.set_text( -// "Saves the game before each sandwich.
" -// "Recommended to leave on, as the sandwich maker will reset the game if it detects an error.
" -// ); -// NUM_SANDWICH_ROUNDS_STATIC_TEXT.set_text( -// "One sandwich per round.
" -// "400-650 Happiny dust per sandwich, with Normal Encounter power level 2.
" -// "(e.g. Chorizo x4, Banana x2, Mayo x3, Whipped Cream x1)
" -// ); -// MaterialFarmerOptions::SANDWICH_OPTIONS.set_visibility(ConfigOptionState::ENABLED); -// }else{ -// SAVE_GAME_BEFORE_SANDWICH_STATIC_TEXT.set_text(""); -// NUM_SANDWICH_ROUNDS_STATIC_TEXT.set_text("30 minutes per round.
"); -// MaterialFarmerOptions::SANDWICH_OPTIONS.set_visibility(ConfigOptionState::DISABLED); -// } - -} - -// return new start time, so that minutes remaining is rounded up to a multiple of 32 -WallClock new_start_time_after_reset(WallClock old_start_time, uint16_t run_time_in_minutes){ - auto farming_time_remaining = minutes_remaining(old_start_time, std::chrono::minutes(run_time_in_minutes)); - // round up the time to multiple of 32 (30 minutes per sandwich, plus 2 minutes for sandwich making) - size_t desired_minutes_remaining = ((farming_time_remaining.count()/32)+1)*32; - WallClock new_start_time = current_time() + std::chrono::minutes(desired_minutes_remaining) - std::chrono::minutes(run_time_in_minutes); - return new_start_time; -} - - -void run_material_farmer( - ProgramEnvironment& env, - ConsoleHandle& console, ProControllerContext& context, - MaterialFarmerOptions& options, - MaterialFarmerStats& stats -){ - LetsGoEncounterBotTracker encounter_tracker( - env, console, context, - stats, - options.LANGUAGE - ); - WallClock start_time = current_time(); - WallClock last_sandwich_time = WallClock::min(); - LetsGoHpWatcher hp_watcher(COLOR_RED); - - // ensure we save before running the material farmer. - // but no need to save if already saving prior to each sandwich - if (!(options.SANDWICH_OPTIONS.enabled() && options.SANDWICH_OPTIONS.SAVE_GAME_BEFORE_SANDWICH)){ - save_game_from_overworld(env.program_info(), console, context); - } - - /* - - Use Let's Go along the path. Fly back to pokecenter when it reaches the end of the path. - - Keeping repeating this for RUN_TIME_IN_MINUTES minutes - */ - size_t consecutive_failures = 0; - size_t max_consecutive_failures = 15; - while (true){ - try{ - while (true){ - // check time left on material farming - auto farming_time_remaining = minutes_remaining(start_time, std::chrono::minutes(options.RUN_TIME_IN_MINUTES)); - console.log( - "Time left in Material Farming: " + - std::to_string(farming_time_remaining.count()) + " min", - COLOR_PURPLE - ); - if (farming_time_remaining < std::chrono::minutes(0)){ - console.log("Time's up. Stop the Material farming program.", COLOR_RED); - return; - } - - // Check time left on sandwich - if (options.SANDWICH_OPTIONS.enabled()){ - auto sandwich_time_remaining = minutes_remaining(last_sandwich_time, std::chrono::minutes(options.TIME_PER_SANDWICH)); - console.log( - "Time left on sandwich: " + - std::to_string(sandwich_time_remaining.count()) + " min", - COLOR_PURPLE - ); - if (sandwich_time_remaining < std::chrono::minutes(0)){ - console.log("Sandwich not active. Make a sandwich."); - last_sandwich_time = make_sandwich_material_farm(env, console, context, options, stats); - console.overlay().add_log("Sandwich made."); - - // Log time remaining in Material farming - farming_time_remaining = minutes_remaining(start_time, std::chrono::minutes(options.RUN_TIME_IN_MINUTES)); - console.log( - "Time left in Material Farming: " + - std::to_string(farming_time_remaining.count()) + " min", - COLOR_PURPLE - ); - // Log time remaining on Sandwich - sandwich_time_remaining = minutes_remaining(last_sandwich_time, std::chrono::minutes(options.TIME_PER_SANDWICH)); - console.log( - "Time left on sandwich: " + - std::to_string(sandwich_time_remaining.count()) + " min", - COLOR_PURPLE - ); - } - } - - // heal before starting Let's go - console.log("Heal before starting Let's go", COLOR_PURPLE); - console.log("Heal threshold: " + tostr_default(options.AUTO_HEAL_PERCENT), COLOR_PURPLE); - check_hp(env, console, context, options, hp_watcher, stats); - - /* - - Starts from pokemon center. - - Flies to start position. Runs a Let's Go iteration. - - Then returns to pokemon center, regardless of whether - it completes the action or gets caught in a battle - */ - run_from_battles_and_back_to_pokecenter(env, console, context, stats, - [&](ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context){ - // Move to starting position for Let's Go hunting path - stream.log("Move to starting position for Let's Go hunting path.", COLOR_PURPLE); - move_to_start_position_for_letsgo1(env.program_info(), stream, context); - - // run let's go while updating the HP watcher - stream.log("Starting Let's Go hunting path.", COLOR_PURPLE); - run_until( - stream, context, - [&](ProControllerContext& context){ - run_lets_go_iteration(stream, context, encounter_tracker, options.NUM_FORWARD_MOVES_PER_LETS_GO_ITERATION); - }, - {hp_watcher} - ); - } - ); - - context.wait_for_all_requests(); - } - }catch (OperationFailedException& e){ - stats.m_errors++; - env.update_stats(); - e.send_notification(env, options.NOTIFICATION_ERROR_RECOVERABLE); - - // save screenshot after operation failed, - // dump_snapshot(console); - - if (options.SAVE_DEBUG_VIDEO){ - // Take a video to give more context for debugging - pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - } - - consecutive_failures++; - if (consecutive_failures >= max_consecutive_failures){ - throw e; - } - - env.log("Reset game to handle recoverable error."); - reset_game(env.program_info(), console, context); - stats.m_game_resets++; - env.update_stats(); - - // update start time, so that minutes remaining is rounded up to a multiple of 32 - start_time = new_start_time_after_reset(start_time, options.RUN_TIME_IN_MINUTES); - // also update last sandwich time - last_sandwich_time = WallClock::min(); - } - } -} - - - -void check_hp( - ProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context, - MaterialFarmerOptions& options, - LetsGoHpWatcher& hp_watcher, - MaterialFarmerStats& stats -){ - double hp = hp_watcher.last_known_value() * 100; - if (0 < hp){ - stream.log("Last Known HP: " + tostr_default(hp) + "%", COLOR_BLUE); - }else{ - stream.log("Last Known HP: ?", COLOR_RED); - } - if (0 < hp && hp < options.AUTO_HEAL_PERCENT){ - auto_heal_from_menu_or_overworld(env.program_info(), stream, context, 0, true); - stats.m_autoheals++; - env.update_stats(); - send_program_status_notification(env, options.NOTIFICATION_STATUS_UPDATE); - } -} - - - -// make sandwich then go back to Pokecenter to reset position -// if gets caught up in a battle, try again. -WallClock make_sandwich_material_farm( - ProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context, - MaterialFarmerOptions& options, - MaterialFarmerStats& stats -){ - - if (options.SANDWICH_OPTIONS.SAVE_GAME_BEFORE_SANDWICH){ - save_game_from_overworld(env.program_info(), stream, context); - } - - WallClock last_sandwich_time = WallClock::min(); - while(last_sandwich_time == WallClock::min()){ - run_from_battles_and_back_to_pokecenter(env, stream, context, stats, - [&](ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context){ - // Orient camera to look at same direction as player character - // - This is needed because when save-load the game, - // the camera angle is different than when just flying to pokecenter - pbf_press_button(context, BUTTON_L, 50, 40); - - // move up towards pokecenter counter - pbf_move_left_joystick(context, 128, 255, 180, 10); - // Orient camera to look at same direction as player character - pbf_press_button(context, BUTTON_L, 50, 40); - // look left - pbf_move_right_joystick(context, 0, 128, 120, 0); - // move toward clearing besides the pokecenter - pbf_move_left_joystick(context, 128, 0, 300, 0); - - // make sandwich - picnic_from_overworld(env.program_info(), stream, context); - pbf_move_left_joystick(context, 128, 0, 100, 40); // walk forward to picnic table - enter_sandwich_recipe_list(env.program_info(), stream, context); - make_sandwich_option(env, stream, context, options.SANDWICH_OPTIONS); - last_sandwich_time = current_time(); - leave_picnic(env.program_info(), stream, context); - - stats.m_sandwiches++; - env.update_stats(); - - } - ); - } - - return last_sandwich_time; -} - -// given the start time, and duration in minutes, return the number of remaining minutes -std::chrono::minutes minutes_remaining(WallClock start_time, std::chrono::minutes minutes_duration){ - return std::chrono::minutes(minutes_duration) - - std::chrono::duration_cast(current_time() - start_time); -} - -// from the North Province (Area 3) pokecenter, move to start position for Happiny dust farming -void move_to_start_position_for_letsgo0( - VideoStream& stream, - ProControllerContext& context -){ - // Orient camera to look at same direction as player character - // - This is needed because when save-load the game, - // the camera angle is different than when just flying to pokecenter - pbf_press_button(context, BUTTON_L, 50, 40); - - // move up towards pokecenter counter - pbf_move_left_joystick(context, 128, 255, 180, 10); - // Orient camera to look at same direction as player character - pbf_press_button(context, BUTTON_L, 50, 40); - // look left - pbf_move_right_joystick(context, 0, 128, 120, 10); - // move toward clearing besides the pokecenter - pbf_move_left_joystick(context, 128, 0, 300, 10); - - // look right, towards the start position - pbf_move_right_joystick(context, 255, 128, 120, 10); - pbf_move_left_joystick(context, 128, 0, 10, 10); - - // get on ride - pbf_press_button(context, BUTTON_PLUS, 50, 50); - - // Jump - pbf_press_button(context, BUTTON_B, 125, 100); - - // Fly - pbf_press_button(context, BUTTON_B, 50, 10); // Double up this press - pbf_press_button(context, BUTTON_B, 50, 10); // in case one is dropped. - pbf_press_button(context, BUTTON_LCLICK, 50, 0); - // you automatically move forward without pressing any buttons. so just wait - pbf_wait(context, 1400); - - // Glide forward - // pbf_move_left_joystick(context, 128, 0, 2500, 10); - - // arrived at start position. stop flying - pbf_press_button(context, BUTTON_B, 50, 400); - // get off ride - pbf_press_button(context, BUTTON_PLUS, 50, 50); - - // look right - pbf_move_right_joystick(context, 255, 128, 30, 10); - pbf_move_left_joystick(context, 128, 0, 50, 10); - - stream.log("Arrived at Let's go start position", COLOR_PURPLE); - - -} - -// from the North Province (Area 3) pokecenter, move to start position for Happiny dust farming -void move_to_start_position_for_letsgo1( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context -){ - // Orient camera to look at same direction as player character - // - This is needed because when save-load the game, - // the camera angle is different than when just flying to pokecenter - pbf_press_button(context, BUTTON_L, 50, 40); - - // move up towards pokecenter counter - pbf_move_left_joystick(context, 128, 255, 180, 10); - // Orient camera to look at same direction as player character - pbf_press_button(context, BUTTON_L, 50, 40); - // look left - pbf_move_right_joystick(context, 0, 128, 120, 10); - // move toward clearing besides the pokecenter - pbf_move_left_joystick(context, 128, 0, 300, 10); - - // look right, towards the start position - DirectionDetector direction; - direction.change_direction(info, stream, context, 5.76); - // pbf_move_right_joystick(context, 255, 128, 130, 10); - pbf_move_left_joystick(context, 128, 0, 10, 10); - - // get on ride - pbf_press_button(context, BUTTON_PLUS, 50, 50); - - // Jump - pbf_press_button(context, BUTTON_B, 125, 30); - - // Fly - pbf_press_button(context, BUTTON_B, 50, 10); - pbf_press_button(context, BUTTON_B, 50, 50); // Double click in case of drop - pbf_press_button(context, BUTTON_LCLICK, 50, 0); - - // you automatically move forward when flying without pressing any buttons. - // so, just wait. - pbf_wait(context, 2200); - - // arrived at start position. stop flying - pbf_press_button(context, BUTTON_B, 50, 400); - // get off ride - pbf_press_button(context, BUTTON_PLUS, 50, 50); - - // extra B presses to ensure we stop flying, in case the previous B press - // was dropped. This way, you eventually reset back to Pokecenter, instead - // of flying until an exception is thrown. - pbf_press_button(context, BUTTON_B, 50, 10); - pbf_press_button(context, BUTTON_B, 50, 10); - - // look right - // pbf_move_right_joystick(context, 255, 128, 20, 10); - direction.change_direction(info, stream, context, 5.3); - - // move forward slightly - pbf_move_left_joystick(context, 128, 0, 50, 10); - - stream.log("Arrived at Let's go start position", COLOR_PURPLE); -} - - -// wait, then move forward quickly -void lets_go_movement0(ProControllerContext& context){ - pbf_wait(context, 500); - pbf_move_left_joystick(context, 128, 0, 200, 10); -} - -// wait, then move forward quickly, then wait some more. -void lets_go_movement1(ProControllerContext& context){ - pbf_wait(context, 500); - pbf_move_left_joystick(context, 128, 0, 100, 10); - pbf_wait(context, 100); -} - - -/* -- One iteration of the hunt: -- start at North Province (Area 3) pokecenter, go out and use Let's Go to battle -- move forward and send out lead pokemon to autobattle. When it runs out of pokemon to battle, -move forward again to repeat the cycle. It does this as many times as per num_forward_moves_per_lets_go_iteration. - */ -void run_lets_go_iteration( - VideoStream& stream, - ProControllerContext& context, - LetsGoEncounterBotTracker& encounter_tracker, - int num_forward_moves_per_lets_go_iteration -){ - // - Orient camera to look at same direction as player character - // - This is needed because when save-load the game, the camera points - // in the same direction as the player. - // - But when warping to pokecenter, the camera is facing the player. - pbf_press_button(context, BUTTON_L, 50, 40); - - // zoom out camera - pbf_move_right_joystick(context, 128, 255, 45, 10); - - const bool throw_ball_if_bubble = false; - const int total_iterations = num_forward_moves_per_lets_go_iteration; - - context.wait_for_all_requests(); - for(int i = 0; i < total_iterations; i++){ - use_lets_go_to_clear_in_front(stream, context, encounter_tracker, throw_ball_if_bubble, [&](ProControllerContext& context){ - // Do the following movement while the Let's Go pokemon clearing wild pokemon. - stream.log("Move-forward iteration number: " + std::to_string(i + 1) + "/" + std::to_string(total_iterations), COLOR_PURPLE); - - lets_go_movement1(context); - }); - } - -} - -/* -- This function wraps around an action (e.g. leave the PokeCenter to make a sandwich) so that -we can handle pokemon wild encounters when executing the action. - - note that returning to the PokeCenter is also wrapped, since it's possible to get caught - in a wild encounter when trying to return to the PokeCenter. -- Whenever a battle happens, we run away and after the battle ends, move back to the PokeCenter -- When `action` ends, go back to the PokeCenter. -- i.e. return to Pokecenter regardless of whether the action succeeds or not. -- NOTE: This works differently than `handle_battles_and_back_to_pokecenter` from the Scatterbug program, -where the action will be attempted infinite times if you keep failing. In contrast, this function -only gives you one attempt before returning to the Pokecenter -*/ -void run_from_battles_and_back_to_pokecenter( - ProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context, - MaterialFarmerStats& stats, - std::function< - void(ProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context) - >&& action -){ - bool attempted_action = false; - // a flag for the case that the action has finished but not yet returned to pokecenter - bool returned_to_pokecenter = false; - while(returned_to_pokecenter == false){ - NormalBattleMenuWatcher battle_menu(COLOR_RED); - int ret = run_until( - stream, context, - [&](ProControllerContext& context){ - if (!attempted_action){ // We still need to carry out `action` - attempted_action = true; - context.wait_for_all_requests(); - action(env, stream, context); - context.wait_for_all_requests(); - } - - // we have already attempted the action, - // so reset to the Pokecenter - stream.log("Go back to PokeCenter."); - reset_to_pokecenter(env.program_info(), stream, context); - returned_to_pokecenter = true; - }, - {battle_menu} - ); - if (ret == 0){ // battle detected - stats.m_encounters++; - env.update_stats(); - stream.log("Detected battle. Now running away.", COLOR_PURPLE); - stream.overlay().add_log("Detected battle. Now running away."); - try{ - run_from_battle(env.program_info(), stream, context); - }catch (OperationFailedException& e){ - throw FatalProgramException(std::move(e)); - } - } - } -} - - - - -void move_from_material_farming_to_item_printer(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - stream.log("Start moving from material farming to item printer."); - fly_from_paldea_to_blueberry_entrance(info, stream, context); - move_from_blueberry_entrance_to_league_club(info, stream, context); - move_from_league_club_entrance_to_item_printer(info, stream, context); -} - -void fly_from_paldea_to_blueberry_entrance(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - int numAttempts = 0; - const int maxAttempts = 11; - bool isFlySuccessful = false; - - // in order to land on the target fly point semi-consistently, - // the push magnitude can range from 69 to 85 (range of 16). - // On each failure, try increasing/decreasing the push by 1/4 of the max range, - // then 1/2 of the range, then the full range, then back to re-attempts with no adjustment - const std::array adjustment_table = {0, 0, 0, 4, -4, 8, -8, 16, -16, 0, 0, 0}; - while (!isFlySuccessful && numAttempts < maxAttempts){ - // close all menus - pbf_mash_button(context, BUTTON_B, 100); - - numAttempts++; - - open_map_from_overworld(info, stream, context); - - // change from Paldea map to Blueberry map - pbf_press_button(context, BUTTON_L, 50, 300); - - // move cursor to bottom right corner - pbf_move_left_joystick(context, 255, 255, TICKS_PER_SECOND*5, 50); - - // move cursor to Blueberry academy fast travel point (up-left) - // try different magnitudes of cursor push with each failure. - int push_magnitude = 105 + adjustment_table[numAttempts]; - pbf_move_left_joystick(context, 64, 64, (uint16_t)push_magnitude, 50); - - // press A to fly to Blueberry academy - isFlySuccessful = fly_to_overworld_from_map(info, stream, context, true); - if (!isFlySuccessful){ - stream.log("Failed to fly to Blueberry academy."); - // dump_snapshot(stream); - } - } - - if (!isFlySuccessful){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to fly to Blueberry academy, five times in a row.", - stream - ); - } -} - -void move_from_blueberry_entrance_to_league_club(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - - int numAttempts = 0; - int maxAttempts = 5; - bool isSuccessful = false; - - while (!isSuccessful && numAttempts < maxAttempts){ - if (numAttempts > 0){ // failed at least once - pbf_mash_button(context, BUTTON_B, 100); - open_map_from_overworld(info, stream, context); - fly_to_overworld_from_map(info, stream, context, false); - } - - numAttempts++; - - // move toward entrance gates - pbf_move_left_joystick(context, 190, 0, 200, 50); - - context.wait_for_all_requests(); - - // Wait for detection of Blueberry navigation menu - ImageFloatBox select_entrance_box(0.031, 0.193, 0.047, 0.078); - GradientArrowWatcher select_entrance(COLOR_RED, GradientArrowType::RIGHT, select_entrance_box); - int ret = wait_until(stream, context, Milliseconds(5000), { select_entrance }); - if (ret == 0){ - stream.log("Blueberry navigation menu detected."); - }else{ - stream.log("Failed to detect Blueberry navigation menu."); - continue; - } - - // Move selector to League club room - pbf_press_dpad(context, DPAD_UP, 20, 50); - - // Confirm to League club room is selected - ImageFloatBox select_league_club_box(0.038, 0.785, 0.043, 0.081); - GradientArrowWatcher select_league_club(COLOR_RED, GradientArrowType::RIGHT, select_league_club_box, Milliseconds(1000)); - ret = wait_until(stream, context, Milliseconds(5000), { select_league_club }); - if (ret == 0){ - stream.log("League club room selected."); - }else{ - stream.log("Failed to select League club room in navigation menu."); - continue; - } - // press A - pbf_mash_button(context, BUTTON_A, 100); - - // check for overworld - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - ret = wait_until(stream, context, Milliseconds(10000), { overworld }); - if (ret == 0){ - stream.log("Entered League club room."); - }else{ - stream.log("Failed to enter League club room from menu selection."); - continue; - } - - isSuccessful = true; - } - - if (!isSuccessful){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to enter League club room, five times in a row.", - stream - ); - } - -} - -void move_from_league_club_entrance_to_item_printer(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - context.wait_for_all_requests(); - - // move forwards towards table next to item printer - pbf_move_left_joystick(context, 120, 0, 200, 50); - - // look left towards item printer - pbf_move_left_joystick(context, 0, 128, 10, 50); -} - -void move_from_item_printer_to_material_farming(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - stream.log("Start moving from item printer to material farming."); - move_from_item_printer_to_blueberry_entrance(info, stream, context); - fly_from_blueberry_to_north_province_3(info, stream, context); -} - -// assumes you start in the position in front of the item printer, as if you finished using it. -void move_from_item_printer_to_blueberry_entrance(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - context.wait_for_all_requests(); - - // look left towards door - pbf_move_left_joystick(context, 0, 128, 10, 50); - - // re-orient camera to look same direction as player - pbf_press_button(context, BUTTON_L, 50, 50); - - // move forward towards door - pbf_move_left_joystick(context, 128, 0, 700, 50); - - context.wait_for_all_requests(); - - stream.log("Wait for detection of Blueberry navigation menu."); - - // Wait for detection of Blueberry navigation menu - ImageFloatBox select_entrance_box(0.031, 0.193, 0.047, 0.078); - GradientArrowWatcher select_entrance(COLOR_RED, GradientArrowType::RIGHT, select_entrance_box); - int ret = wait_until(stream, context, Milliseconds(5000), { select_entrance }, Milliseconds(1000)); - if (ret == 0){ - stream.log("Blueberry navigation menu detected."); - }else{ - stream.log("Failed to detect Blueberry navigation menu."); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to find the exit from the League room.", - stream - ); - } - - // press A - pbf_mash_button(context, BUTTON_A, 100); - - // check for overworld - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - ret = wait_until(stream, context, std::chrono::seconds(30), { overworld }); - if (ret == 0){ - stream.log("Overworld detected"); - }else{ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to detect overworld.", - stream - ); - } -} - - -void fly_from_blueberry_to_north_province_3(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - int numAttempts = 0; - const int maxAttempts = 11; - bool isFlySuccessful = false; - - // in order to land on the target fly point, the push magnitude can range from - // 156 to 172 (range of 16). - // On each failure, try increasing/decreasing the push by 1/4 of the max range, - // then 1/2 of the range, then the full range, then back to re-attempts with no adjustment - const std::array adjustment_table = {0, 0, 0, 4, -4, 8, -8, 16, -16, 0, 0, 0}; - while (!isFlySuccessful && numAttempts < maxAttempts){ - numAttempts++; - - // close all menus - pbf_mash_button(context, BUTTON_B, 100); - - open_map_from_overworld(info, stream, context); - - // change from Blueberry map to Paldea map - pbf_press_button(context, BUTTON_R, 50, 300); - - // zoom out - pbf_press_button(context, BUTTON_ZL, 25, 200); - - // move cursor up-left - // try different magnitudes of cursor push with each failure. - int push_magnitude = 168 + adjustment_table[numAttempts]; - pbf_move_left_joystick(context, 112, 0, (uint16_t)push_magnitude, 50); - - // press A to fly to North province area 3 - isFlySuccessful = fly_to_overworld_from_map(info, stream, context, true); - - if (!isFlySuccessful){ - stream.log("Failed to fly to North province area 3."); - // dump_snapshot(console); - } - } - - if (!isFlySuccessful){ - - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to fly to North province area 3, ten times in a row.", - stream - ); - - } -} - - - -} -} -} +/* Material Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Exceptions/FatalProgramException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldSensors.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/Battles/PokemonSV_Battles.h" +#include "PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h" +#include "PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h" +#include "PokemonSV_MaterialFarmerTools.h" + +// #include +// using std::cout; +// using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +MaterialFarmerOptions::~MaterialFarmerOptions(){ +// ENABLE_SANDWICH.remove_listener(*this); +} + +MaterialFarmerOptions::MaterialFarmerOptions( + GroupOption::EnableMode enable_mode, + OCR::LanguageOCROption* language_option, + EventNotificationOption& notif_status_update_option, + EventNotificationOption& notif_program_finish_option, + EventNotificationOption& notif_error_recoverable_option, + EventNotificationOption& notif_error_fatal_option +) + : GroupOption( + "Material Farmer", + LockMode::UNLOCK_WHILE_RUNNING, + enable_mode + ) + , m_language_owner(language_option == nullptr + ? new OCR::LanguageOCROption( + "Game Language:
Required to read sandwich ingredients.", + IV_READER().languages(), + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + : nullptr + ) + , RUN_TIME_IN_MINUTES( + "Run Duration:
Run the material farmer for this many minutes.", + LockMode::UNLOCK_WHILE_RUNNING, + 32 + ) +// , SAVE_GAME_BEFORE_SANDWICH( +// "Save Game before each round:", +// LockMode::UNLOCK_WHILE_RUNNING, +// true +// ) +// , SAVE_GAME_BEFORE_SANDWICH_STATIC_TEXT("") +// , NUM_SANDWICH_ROUNDS_STATIC_TEXT("") + , LANGUAGE(language_option == nullptr ? *m_language_owner : *language_option) + , SANDWICH_OPTIONS( + "Make a Sandwich", + &LANGUAGE, + BaseRecipe::non_shiny, + true, + GroupOption::EnableMode::DEFAULT_DISABLED + ) + , AUTO_HEAL_PERCENT( + "Auto-Heal %
Auto-heal if your HP drops below this percentage.", + LockMode::UNLOCK_WHILE_RUNNING, + 75, 0, 100 + ) + , m_advanced_options( + "Advanced Options: (developer only)" + ) + , SAVE_DEBUG_VIDEO( + "Save debug videos to Switch:
" + "Set this on to save a Switch video everytime an error occurs. You can send the video to developers to help them debug later.", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , SKIP_WARP_TO_POKECENTER( + "Skip warping to closest PokeCenter:
" + "This is for debugging the program without waiting for the initial warp.", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) +// , ENABLE_SANDWICH( +// "Enable Sandwich making:
" +// "This is for boosting spawn rates of specific Pokemon.", +// LockMode::UNLOCK_WHILE_RUNNING, +// false +// ) + , TIME_PER_SANDWICH( + "Time per sandwich:
Number of minutes before resetting sandwich.", + LockMode::UNLOCK_WHILE_RUNNING, + 30, 1, 30 + ) + , NUM_FORWARD_MOVES_PER_LETS_GO_ITERATION( + "Number of forward moves per lets go iteration:
" + "During Let's go autobattling sequence, the number of forward movements before resetting to Pokecenter.", + LockMode::UNLOCK_WHILE_RUNNING, + 13 + ) + , NOTIFICATION_STATUS_UPDATE(notif_status_update_option) + , NOTIFICATION_PROGRAM_FINISH(notif_program_finish_option) + , NOTIFICATION_ERROR_RECOVERABLE(notif_error_recoverable_option) + , NOTIFICATION_ERROR_FATAL(notif_error_fatal_option) +{ + PA_ADD_OPTION(RUN_TIME_IN_MINUTES); +// PA_ADD_OPTION(ENABLE_SANDWICH); +// PA_ADD_OPTION(SAVE_GAME_BEFORE_SANDWICH); +// PA_ADD_OPTION(SAVE_GAME_BEFORE_SANDWICH_STATIC_TEXT); +// PA_ADD_OPTION(NUM_SANDWICH_ROUNDS_STATIC_TEXT); + if (m_language_owner){ + PA_ADD_OPTION(LANGUAGE); + } + PA_ADD_OPTION(SANDWICH_OPTIONS); + PA_ADD_OPTION(AUTO_HEAL_PERCENT); + + if (PreloadSettings::instance().DEVELOPER_MODE){ + PA_ADD_OPTION(m_advanced_options); + PA_ADD_OPTION(SAVE_DEBUG_VIDEO); + PA_ADD_OPTION(SKIP_WARP_TO_POKECENTER); + PA_ADD_OPTION(TIME_PER_SANDWICH); + PA_ADD_OPTION(NUM_FORWARD_MOVES_PER_LETS_GO_ITERATION); + } + + MaterialFarmerOptions::on_config_value_changed(this); +// ENABLE_SANDWICH.add_listener(*this); +} + +void MaterialFarmerOptions::on_config_value_changed(void* object){ + +// if (MaterialFarmerOptions::ENABLE_SANDWICH){ +// SAVE_GAME_BEFORE_SANDWICH_STATIC_TEXT.set_text( +// "Saves the game before each sandwich.
" +// "Recommended to leave on, as the sandwich maker will reset the game if it detects an error.
" +// ); +// NUM_SANDWICH_ROUNDS_STATIC_TEXT.set_text( +// "One sandwich per round.
" +// "400-650 Happiny dust per sandwich, with Normal Encounter power level 2.
" +// "(e.g. Chorizo x4, Banana x2, Mayo x3, Whipped Cream x1)
" +// ); +// MaterialFarmerOptions::SANDWICH_OPTIONS.set_visibility(ConfigOptionState::ENABLED); +// }else{ +// SAVE_GAME_BEFORE_SANDWICH_STATIC_TEXT.set_text(""); +// NUM_SANDWICH_ROUNDS_STATIC_TEXT.set_text("30 minutes per round.
"); +// MaterialFarmerOptions::SANDWICH_OPTIONS.set_visibility(ConfigOptionState::DISABLED); +// } + +} + +// return new start time, so that minutes remaining is rounded up to a multiple of 32 +WallClock new_start_time_after_reset(WallClock old_start_time, uint16_t run_time_in_minutes){ + auto farming_time_remaining = minutes_remaining(old_start_time, std::chrono::minutes(run_time_in_minutes)); + // round up the time to multiple of 32 (30 minutes per sandwich, plus 2 minutes for sandwich making) + size_t desired_minutes_remaining = ((farming_time_remaining.count()/32)+1)*32; + WallClock new_start_time = current_time() + std::chrono::minutes(desired_minutes_remaining) - std::chrono::minutes(run_time_in_minutes); + return new_start_time; +} + + +void run_material_farmer( + ProgramEnvironment& env, + ConsoleHandle& console, ProControllerContext& context, + MaterialFarmerOptions& options, + MaterialFarmerStats& stats +){ + OverworldSensors sensors( + env.logger(), console, context + ); + LetsGoEncounterBotTracker encounter_tracker( + env, console, + stats, + sensors.lets_go_kill + ); + WallClock start_time = current_time(); + WallClock last_sandwich_time = WallClock::min(); + LetsGoHpWatcher hp_watcher(COLOR_RED); + + // ensure we save before running the material farmer. + // but no need to save if already saving prior to each sandwich + if (!(options.SANDWICH_OPTIONS.enabled() && options.SANDWICH_OPTIONS.SAVE_GAME_BEFORE_SANDWICH)){ + save_game_from_overworld(env.program_info(), console, context); + } + + /* + - Use Let's Go along the path. Fly back to pokecenter when it reaches the end of the path. + - Keeping repeating this for RUN_TIME_IN_MINUTES minutes + */ + size_t consecutive_failures = 0; + size_t max_consecutive_failures = 15; + while (true){ + try{ + while (true){ + // check time left on material farming + auto farming_time_remaining = minutes_remaining(start_time, std::chrono::minutes(options.RUN_TIME_IN_MINUTES)); + console.log( + "Time left in Material Farming: " + + std::to_string(farming_time_remaining.count()) + " min", + COLOR_PURPLE + ); + if (farming_time_remaining <= std::chrono::minutes(0)){ + console.log("Time's up. Stop the Material farming program.", COLOR_RED); + return; + } + + // Check time left on sandwich + if (options.SANDWICH_OPTIONS.enabled()){ + auto sandwich_time_remaining = minutes_remaining(last_sandwich_time, std::chrono::minutes(options.TIME_PER_SANDWICH)); + console.log( + "Time left on sandwich: " + + std::to_string(sandwich_time_remaining.count()) + " min", + COLOR_PURPLE + ); + if (sandwich_time_remaining <= std::chrono::minutes(0)){ + console.log("Sandwich not active. Make a sandwich."); + last_sandwich_time = make_sandwich_material_farm(env, console, context, options, stats); + console.overlay().add_log("Sandwich made."); + + // Log time remaining in Material farming + farming_time_remaining = minutes_remaining(start_time, std::chrono::minutes(options.RUN_TIME_IN_MINUTES)); + console.log( + "Time left in Material Farming: " + + std::to_string(farming_time_remaining.count()) + " min", + COLOR_PURPLE + ); + // Log time remaining on Sandwich + sandwich_time_remaining = minutes_remaining(last_sandwich_time, std::chrono::minutes(options.TIME_PER_SANDWICH)); + console.log( + "Time left on sandwich: " + + std::to_string(sandwich_time_remaining.count()) + " min", + COLOR_PURPLE + ); + }else{ + console.log("Sandwich is still active. Continue material farming.", COLOR_ORANGE); + } + }else{ + console.log("Sandwich making disabled. Skip sandwich checks.", COLOR_ORANGE); + } + + // heal before starting Let's go + console.log("Heal before starting Let's go", COLOR_PURPLE); + console.log("Heal threshold: " + tostr_default(options.AUTO_HEAL_PERCENT), COLOR_PURPLE); + check_hp(env, console, context, options, hp_watcher, stats); + + /* + - Starts from pokemon center. + - Flies to start position. Runs a Let's Go iteration. + - Then returns to pokemon center, regardless of whether + it completes the action or gets caught in a battle + */ + run_from_battles_and_back_to_pokecenter(env, console, context, stats, + [&](ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context){ + // Move to starting position for Let's Go hunting path + stream.log("Move to starting position for Let's Go hunting path.", COLOR_PURPLE); + move_to_start_position_for_letsgo1(env.program_info(), stream, context); + + // run let's go while updating the HP watcher + stream.log("Starting Let's Go hunting path.", COLOR_PURPLE); + run_until( + stream, context, + [&](ProControllerContext& context){ + run_lets_go_iteration(stream, context, encounter_tracker, options.NUM_FORWARD_MOVES_PER_LETS_GO_ITERATION); + }, + {hp_watcher} + ); + } + ); + + context.wait_for_all_requests(); + } + }catch (OperationFailedException& e){ + stats.m_errors++; + env.update_stats(); + e.send_notification(env, options.NOTIFICATION_ERROR_RECOVERABLE); + + // save screenshot after operation failed, + // dump_snapshot(console); + + if (options.SAVE_DEBUG_VIDEO){ + // Take a video to give more context for debugging + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + } + + consecutive_failures++; + if (consecutive_failures >= max_consecutive_failures){ + throw e; + } + + env.log("Reset game to handle recoverable error."); + reset_game(env.program_info(), console, context); + stats.m_game_resets++; + env.update_stats(); + + // update start time, so that minutes remaining is rounded up to a multiple of 32 + start_time = new_start_time_after_reset(start_time, options.RUN_TIME_IN_MINUTES); + // also update last sandwich time + last_sandwich_time = WallClock::min(); + } + } +} + + + +void check_hp( + ProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context, + MaterialFarmerOptions& options, + LetsGoHpWatcher& hp_watcher, + MaterialFarmerStats& stats +){ + double hp = hp_watcher.last_known_value() * 100; + if (0 < hp){ + stream.log("Last Known HP: " + tostr_default(hp) + "%", COLOR_BLUE); + }else{ + stream.log("Last Known HP: ?", COLOR_RED); + } + if (0 < hp && hp < options.AUTO_HEAL_PERCENT){ + auto_heal_from_menu_or_overworld(env.program_info(), stream, context, 0, true); + stats.m_autoheals++; + env.update_stats(); + send_program_status_notification(env, options.NOTIFICATION_STATUS_UPDATE); + } +} + + + +// make sandwich then go back to Pokecenter to reset position +// if gets caught up in a battle, try again. +WallClock make_sandwich_material_farm( + ProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context, + MaterialFarmerOptions& options, + MaterialFarmerStats& stats +){ + + if (options.SANDWICH_OPTIONS.SAVE_GAME_BEFORE_SANDWICH){ + save_game_from_overworld(env.program_info(), stream, context); + } + + WallClock last_sandwich_time = WallClock::min(); + while(last_sandwich_time == WallClock::min()){ + run_from_battles_and_back_to_pokecenter(env, stream, context, stats, + [&](ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context){ + // Orient camera to look at same direction as player character + // - This is needed because when save-load the game, + // the camera angle is different than when just flying to pokecenter + pbf_press_button(context, BUTTON_L, 50, 40); + + // move up towards pokecenter counter + pbf_move_left_joystick(context, 128, 255, 180, 10); + // Orient camera to look at same direction as player character + pbf_press_button(context, BUTTON_L, 50, 40); + // look left + pbf_move_right_joystick(context, 0, 128, 120, 0); + // move toward clearing besides the pokecenter + pbf_move_left_joystick(context, 128, 0, 300, 0); + + // make sandwich + picnic_from_overworld(env.program_info(), stream, context); + pbf_move_left_joystick(context, 128, 0, 100, 40); // walk forward to picnic table + enter_sandwich_recipe_list(env.program_info(), stream, context); + make_sandwich_option(env, stream, context, options.SANDWICH_OPTIONS); + last_sandwich_time = current_time(); + leave_picnic(env.program_info(), stream, context); + + stats.m_sandwiches++; + env.update_stats(); + + } + ); + } + + return last_sandwich_time; +} + +// given the start time, and duration in minutes, return the number of remaining minutes +// WARNING: this function may silently overflow if start_time is near WallClock::min() or WallClock::max() +std::chrono::minutes minutes_remaining(WallClock start_time, std::chrono::minutes minutes_duration){ + if (start_time == WallClock::min()){ + return std::chrono::minutes(0); + }else{ + auto elapsed_time = std::chrono::duration_cast(current_time() - start_time); + return minutes_duration - elapsed_time; + } +} + +// from the North Province (Area 3) pokecenter, move to start position for Happiny dust farming +void move_to_start_position_for_letsgo0( + VideoStream& stream, + ProControllerContext& context +){ + // Orient camera to look at same direction as player character + // - This is needed because when save-load the game, + // the camera angle is different than when just flying to pokecenter + pbf_press_button(context, BUTTON_L, 50, 40); + + // move up towards pokecenter counter + pbf_move_left_joystick(context, 128, 255, 180, 10); + // Orient camera to look at same direction as player character + pbf_press_button(context, BUTTON_L, 50, 40); + // look left + pbf_move_right_joystick(context, 0, 128, 120, 10); + // move toward clearing besides the pokecenter + pbf_move_left_joystick(context, 128, 0, 300, 10); + + // look right, towards the start position + pbf_move_right_joystick(context, 255, 128, 120, 10); + pbf_move_left_joystick(context, 128, 0, 10, 10); + + // get on ride + pbf_press_button(context, BUTTON_PLUS, 50, 50); + + // Jump + pbf_press_button(context, BUTTON_B, 125, 100); + + // Fly + pbf_press_button(context, BUTTON_B, 50, 10); // Double up this press + pbf_press_button(context, BUTTON_B, 50, 10); // in case one is dropped. + pbf_press_button(context, BUTTON_LCLICK, 50, 0); + // you automatically move forward without pressing any buttons. so just wait + pbf_wait(context, 1400); + + // Glide forward + // pbf_move_left_joystick(context, 128, 0, 2500, 10); + + // arrived at start position. stop flying + pbf_press_button(context, BUTTON_B, 50, 400); + // get off ride + pbf_press_button(context, BUTTON_PLUS, 50, 50); + + // look right + pbf_move_right_joystick(context, 255, 128, 30, 10); + pbf_move_left_joystick(context, 128, 0, 50, 10); + + stream.log("Arrived at Let's go start position", COLOR_PURPLE); + + +} + +// from the North Province (Area 3) pokecenter, move to start position for Happiny dust farming +void move_to_start_position_for_letsgo1( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context +){ + // Orient camera to look at same direction as player character + // - This is needed because when save-load the game, + // the camera angle is different than when just flying to pokecenter + pbf_press_button(context, BUTTON_L, 50, 40); + + // move up towards pokecenter counter + pbf_move_left_joystick(context, 128, 255, 180, 10); + // Orient camera to look at same direction as player character + pbf_press_button(context, BUTTON_L, 50, 40); + // look left + pbf_move_right_joystick(context, 0, 128, 120, 10); + // move toward clearing besides the pokecenter + pbf_move_left_joystick(context, 128, 0, 300, 10); + + // look right, towards the start position + DirectionDetector direction; + direction.change_direction(info, stream, context, 5.76); + // pbf_move_right_joystick(context, 255, 128, 130, 10); + pbf_move_left_joystick(context, 128, 0, 10, 10); + + // get on ride + pbf_press_button(context, BUTTON_PLUS, 50, 50); + + // Jump + pbf_press_button(context, BUTTON_B, 125, 30); + + // Fly + pbf_press_button(context, BUTTON_B, 50, 10); + pbf_press_button(context, BUTTON_B, 50, 50); // Double click in case of drop + pbf_press_button(context, BUTTON_LCLICK, 50, 0); + + // you automatically move forward when flying without pressing any buttons. + // so, just wait. + pbf_wait(context, 2200); + + // arrived at start position. stop flying + pbf_press_button(context, BUTTON_B, 50, 400); + // get off ride + pbf_press_button(context, BUTTON_PLUS, 50, 50); + + // extra B presses to ensure we stop flying, in case the previous B press + // was dropped. This way, you eventually reset back to Pokecenter, instead + // of flying until an exception is thrown. + pbf_press_button(context, BUTTON_B, 50, 10); + pbf_press_button(context, BUTTON_B, 50, 10); + + // look right + // pbf_move_right_joystick(context, 255, 128, 20, 10); + direction.change_direction(info, stream, context, 5.3); + + // move forward slightly + pbf_move_left_joystick(context, 128, 0, 50, 10); + + stream.log("Arrived at Let's go start position", COLOR_PURPLE); +} + + +// wait, then move forward quickly +void lets_go_movement0(ProControllerContext& context){ + pbf_wait(context, 500); + pbf_move_left_joystick(context, 128, 0, 200, 10); +} + +// wait, then move forward quickly, then wait some more. +void lets_go_movement1(ProControllerContext& context){ + pbf_wait(context, 500); + pbf_move_left_joystick(context, 128, 0, 100, 10); + pbf_wait(context, 100); +} + + +/* +- One iteration of the hunt: +- start at North Province (Area 3) pokecenter, go out and use Let's Go to battle +- move forward and send out lead pokemon to autobattle. When it runs out of pokemon to battle, +move forward again to repeat the cycle. It does this as many times as per num_forward_moves_per_lets_go_iteration. + */ +void run_lets_go_iteration( + VideoStream& stream, + ProControllerContext& context, + LetsGoEncounterBotTracker& encounter_tracker, + int num_forward_moves_per_lets_go_iteration +){ + // - Orient camera to look at same direction as player character + // - This is needed because when save-load the game, the camera points + // in the same direction as the player. + // - But when warping to pokecenter, the camera is facing the player. + pbf_press_button(context, BUTTON_L, 50, 40); + + // zoom out camera + pbf_move_right_joystick(context, 128, 255, 45, 10); + + const bool throw_ball_if_bubble = false; + const int total_iterations = num_forward_moves_per_lets_go_iteration; + + context.wait_for_all_requests(); + for(int i = 0; i < total_iterations; i++){ + use_lets_go_to_clear_in_front(stream, context, encounter_tracker, throw_ball_if_bubble, [&](ProControllerContext& context){ + // Do the following movement while the Let's Go pokemon clearing wild pokemon. + stream.log("Move-forward iteration number: " + std::to_string(i + 1) + "/" + std::to_string(total_iterations), COLOR_PURPLE); + + lets_go_movement1(context); + }); + } + +} + +/* +- This function wraps around an action (e.g. leave the PokeCenter to make a sandwich) so that +we can handle pokemon wild encounters when executing the action. + - note that returning to the PokeCenter is also wrapped, since it's possible to get caught + in a wild encounter when trying to return to the PokeCenter. +- Whenever a battle happens, we run away and after the battle ends, move back to the PokeCenter +- When `action` ends, go back to the PokeCenter. +- i.e. return to Pokecenter regardless of whether the action succeeds or not. +- NOTE: This works differently than `handle_battles_and_back_to_pokecenter` from the Scatterbug program, +where the action will be attempted infinite times if you keep failing. In contrast, this function +only gives you one attempt before returning to the Pokecenter +*/ +void run_from_battles_and_back_to_pokecenter( + ProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context, + MaterialFarmerStats& stats, + std::function< + void(ProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context) + >&& action +){ + bool attempted_action = false; + // a flag for the case that the action has finished but not yet returned to pokecenter + bool returned_to_pokecenter = false; + while(returned_to_pokecenter == false){ + NormalBattleMenuWatcher battle_menu(COLOR_RED); + int ret = run_until( + stream, context, + [&](ProControllerContext& context){ + if (!attempted_action){ // We still need to carry out `action` + attempted_action = true; + context.wait_for_all_requests(); + action(env, stream, context); + context.wait_for_all_requests(); + } + + // we have already attempted the action, + // so reset to the Pokecenter + stream.log("Go back to PokeCenter."); + reset_to_pokecenter(env.program_info(), stream, context); + returned_to_pokecenter = true; + }, + {battle_menu} + ); + if (ret == 0){ // battle detected + stats.m_encounters++; + env.update_stats(); + stream.log("Detected battle. Now running away.", COLOR_PURPLE); + stream.overlay().add_log("Detected battle. Now running away."); + try{ + run_from_battle(stream, context); + }catch (OperationFailedException& e){ + throw FatalProgramException(std::move(e)); + } + } + } +} + + + + +void move_from_material_farming_to_item_printer(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + stream.log("Start moving from material farming to item printer."); + fly_from_paldea_to_blueberry_entrance(info, stream, context); + move_from_blueberry_entrance_to_league_club(info, stream, context); + move_from_league_club_entrance_to_item_printer(info, stream, context); +} + +void fly_from_paldea_to_blueberry_entrance(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + int numAttempts = 0; + const int maxAttempts = 11; + bool isFlySuccessful = false; + + // in order to land on the target fly point semi-consistently, + // the push magnitude can range from 69 to 85 (range of 16). + // On each failure, try increasing/decreasing the push by 1/4 of the max range, + // then 1/2 of the range, then the full range, then back to re-attempts with no adjustment + const std::array adjustment_table = {0, 0, 0, 4, -4, 8, -8, 16, -16, 0, 0, 0}; + while (!isFlySuccessful && numAttempts < maxAttempts){ + // close all menus + pbf_mash_button(context, BUTTON_B, 100); + + numAttempts++; + + open_map_from_overworld(info, stream, context); + + // change from Paldea map to Blueberry map + pbf_press_button(context, BUTTON_L, 50, 300); + + // move cursor to bottom right corner + pbf_move_left_joystick(context, 255, 255, TICKS_PER_SECOND*5, 50); + + // move cursor to Blueberry academy fast travel point (up-left) + // try different magnitudes of cursor push with each failure. + int push_magnitude = 105 + adjustment_table[numAttempts]; + pbf_move_left_joystick(context, 64, 64, (uint16_t)push_magnitude, 50); + + // press A to fly to Blueberry academy + isFlySuccessful = fly_to_overworld_from_map(info, stream, context, true); + if (!isFlySuccessful){ + stream.log("Failed to fly to Blueberry academy."); + // dump_snapshot(stream); + } + } + + if (!isFlySuccessful){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to fly to Blueberry academy, five times in a row.", + stream + ); + } +} + +void move_from_blueberry_entrance_to_league_club(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + + int numAttempts = 0; + int maxAttempts = 5; + bool isSuccessful = false; + + while (!isSuccessful && numAttempts < maxAttempts){ + if (numAttempts > 0){ // failed at least once + pbf_mash_button(context, BUTTON_B, 100); + open_map_from_overworld(info, stream, context); + fly_to_overworld_from_map(info, stream, context, false); + } + + numAttempts++; + + // move toward entrance gates + pbf_move_left_joystick(context, 190, 0, 200, 50); + + context.wait_for_all_requests(); + + // Wait for detection of Blueberry navigation menu + ImageFloatBox select_entrance_box(0.031, 0.193, 0.047, 0.078); + GradientArrowWatcher select_entrance(COLOR_RED, GradientArrowType::RIGHT, select_entrance_box); + int ret = wait_until(stream, context, Milliseconds(5000), { select_entrance }); + if (ret == 0){ + stream.log("Blueberry navigation menu detected."); + }else{ + stream.log("Failed to detect Blueberry navigation menu."); + continue; + } + + // Move selector to League club room + pbf_press_dpad(context, DPAD_UP, 20, 50); + + // Confirm to League club room is selected + ImageFloatBox select_league_club_box(0.038, 0.785, 0.043, 0.081); + GradientArrowWatcher select_league_club(COLOR_RED, GradientArrowType::RIGHT, select_league_club_box, Milliseconds(1000)); + ret = wait_until(stream, context, Milliseconds(5000), { select_league_club }); + if (ret == 0){ + stream.log("League club room selected."); + }else{ + stream.log("Failed to select League club room in navigation menu."); + continue; + } + // press A + pbf_mash_button(context, BUTTON_A, 100); + + // check for overworld + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + ret = wait_until(stream, context, Milliseconds(10000), { overworld }); + if (ret == 0){ + stream.log("Entered League club room."); + }else{ + stream.log("Failed to enter League club room from menu selection."); + continue; + } + + isSuccessful = true; + } + + if (!isSuccessful){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to enter League club room, five times in a row.", + stream + ); + } + +} + +void move_from_league_club_entrance_to_item_printer(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + context.wait_for_all_requests(); + + // move forwards towards table next to item printer + pbf_move_left_joystick(context, 120, 0, 200, 50); + + // look left towards item printer + pbf_move_left_joystick(context, 0, 128, 10, 50); +} + +void move_from_item_printer_to_material_farming(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + stream.log("Start moving from item printer to material farming."); + move_from_item_printer_to_blueberry_entrance(info, stream, context); + fly_from_blueberry_to_north_province_3(info, stream, context); +} + +// assumes you start in the position in front of the item printer, as if you finished using it. +void move_from_item_printer_to_blueberry_entrance(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + context.wait_for_all_requests(); + + // look left towards door + pbf_move_left_joystick(context, 0, 128, 10, 50); + + // re-orient camera to look same direction as player + pbf_press_button(context, BUTTON_L, 50, 50); + + // move forward towards door + pbf_move_left_joystick(context, 128, 0, 700, 50); + + context.wait_for_all_requests(); + + stream.log("Wait for detection of Blueberry navigation menu."); + + // Wait for detection of Blueberry navigation menu + ImageFloatBox select_entrance_box(0.031, 0.193, 0.047, 0.078); + GradientArrowWatcher select_entrance(COLOR_RED, GradientArrowType::RIGHT, select_entrance_box); + int ret = wait_until(stream, context, Milliseconds(5000), { select_entrance }, Milliseconds(1000)); + if (ret == 0){ + stream.log("Blueberry navigation menu detected."); + }else{ + stream.log("Failed to detect Blueberry navigation menu."); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to find the exit from the League room.", + stream + ); + } + + // press A + pbf_mash_button(context, BUTTON_A, 100); + + // check for overworld + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + ret = wait_until(stream, context, std::chrono::seconds(30), { overworld }); + if (ret == 0){ + stream.log("Overworld detected"); + }else{ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to detect overworld.", + stream + ); + } +} + + +void fly_from_blueberry_to_north_province_3(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + int numAttempts = 0; + const int maxAttempts = 11; + bool isFlySuccessful = false; + + // in order to land on the target fly point, the push magnitude can range from + // 156 to 172 (range of 16). + // On each failure, try increasing/decreasing the push by 1/4 of the max range, + // then 1/2 of the range, then the full range, then back to re-attempts with no adjustment + const std::array adjustment_table = {0, 0, 0, 4, -4, 8, -8, 16, -16, 0, 0, 0}; + while (!isFlySuccessful && numAttempts < maxAttempts){ + numAttempts++; + + // close all menus + pbf_mash_button(context, BUTTON_B, 100); + + open_map_from_overworld(info, stream, context); + + // change from Blueberry map to Paldea map + pbf_press_button(context, BUTTON_R, 50, 300); + + // zoom out + pbf_press_button(context, BUTTON_ZL, 25, 200); + + // move cursor up-left + // try different magnitudes of cursor push with each failure. + int push_magnitude = 168 + adjustment_table[numAttempts]; + pbf_move_left_joystick(context, 112, 0, (uint16_t)push_magnitude, 50); + + // press A to fly to North province area 3 + isFlySuccessful = fly_to_overworld_from_map(info, stream, context, true); + + if (!isFlySuccessful){ + stream.log("Failed to fly to North province area 3."); + // dump_snapshot(console); + } + } + + if (!isFlySuccessful){ + + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to fly to North province area 3, ten times in a row.", + stream + ); + + } +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.h b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.h index 1313a862f4..5fd9960ea3 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.h @@ -1,164 +1,164 @@ -/* Material Farmer - Happiny dust - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_MaterialFarmerTools_H -#define PokemonAutomation_PokemonSV_MaterialFarmerTools_H - -#include -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationOption.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" -#include "PokemonSV/Options/PokemonSV_SandwichMakerOption.h" -#include "PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -struct MaterialFarmerStats : public LetsGoEncounterBotStats{ - MaterialFarmerStats() - : m_sandwiches(m_stats["Sandwiches"]) - , m_autoheals(m_stats["Auto Heals"]) - , m_game_resets(m_stats["Game Resets"]) - , m_errors(m_stats["Errors"]) - { - m_display_order.insert(m_display_order.begin() + 2, {"Sandwiches", HIDDEN_IF_ZERO}); - m_display_order.insert(m_display_order.begin() + 3, {"Auto Heals", HIDDEN_IF_ZERO}); - m_display_order.insert(m_display_order.begin() + 4, {"Game Resets", HIDDEN_IF_ZERO}); - m_display_order.insert(m_display_order.begin() + 5, {"Errors", HIDDEN_IF_ZERO}); - } - std::atomic& m_sandwiches; - std::atomic& m_autoheals; - std::atomic& m_game_resets; - std::atomic& m_errors; -}; - -class MaterialFarmerOptions : public GroupOption, public ConfigOption::Listener{ -public: - ~MaterialFarmerOptions(); - MaterialFarmerOptions( - GroupOption::EnableMode enable_mode, - OCR::LanguageOCROption* language_option, - EventNotificationOption& notif_status_update_option, - EventNotificationOption& notif_program_finish_option, - EventNotificationOption& notif_error_recoverable_option, - EventNotificationOption& notif_error_fatal_option - ); - virtual void on_config_value_changed(void* object) override; - -private: - std::unique_ptr m_language_owner; - -public: - SimpleIntegerOption RUN_TIME_IN_MINUTES; - - -// BooleanCheckBoxOption SAVE_GAME_BEFORE_SANDWICH; -// StaticTextOption SAVE_GAME_BEFORE_SANDWICH_STATIC_TEXT; - -// StaticTextOption NUM_SANDWICH_ROUNDS_STATIC_TEXT; - - OCR::LanguageOCROption& LANGUAGE; - SandwichMakerOption SANDWICH_OPTIONS; - FloatingPointOption AUTO_HEAL_PERCENT; - - // Debug options - SectionDividerOption m_advanced_options; - BooleanCheckBoxOption SAVE_DEBUG_VIDEO; - BooleanCheckBoxOption SKIP_WARP_TO_POKECENTER; -// BooleanCheckBoxOption ENABLE_SANDWICH; - SimpleIntegerOption TIME_PER_SANDWICH; - SimpleIntegerOption NUM_FORWARD_MOVES_PER_LETS_GO_ITERATION; - - EventNotificationOption& NOTIFICATION_STATUS_UPDATE; - EventNotificationOption& NOTIFICATION_PROGRAM_FINISH; - EventNotificationOption& NOTIFICATION_ERROR_RECOVERABLE; - EventNotificationOption& NOTIFICATION_ERROR_FATAL; -}; - - - -void run_material_farmer( - ProgramEnvironment& env, - ConsoleHandle& console, ProControllerContext& context, - MaterialFarmerOptions& options, - MaterialFarmerStats& stats -); - -void check_hp( - ProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context, - MaterialFarmerOptions& options, - LetsGoHpWatcher& hp_watcher, - MaterialFarmerStats& stats -); - -WallClock make_sandwich_material_farm( - ProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context, - MaterialFarmerOptions& options, - MaterialFarmerStats& stats -); - -void move_to_start_position_for_letsgo0(VideoStream& stream, ProControllerContext& context); - -void move_to_start_position_for_letsgo1(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -void lets_go_movement0(ProControllerContext& context); - -void lets_go_movement1(ProControllerContext& context); - -std::chrono::minutes minutes_remaining(WallClock start_time, std::chrono::minutes minutes_duration); - -void run_lets_go_iteration( - VideoStream& stream, - ProControllerContext& context, - LetsGoEncounterBotTracker& encounter_tracker, - int num_forward_moves_per_lets_go_iteration -); - -void run_from_battles_and_back_to_pokecenter( - ProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context, - MaterialFarmerStats& stats, - std::function< - void(ProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context) - >&& action -); - - - -void move_from_material_farming_to_item_printer(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -void fly_from_paldea_to_blueberry_entrance(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -void move_from_blueberry_entrance_to_league_club(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -void move_from_league_club_entrance_to_item_printer(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - - - -void move_from_item_printer_to_material_farming(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -void move_from_item_printer_to_blueberry_entrance(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -void fly_from_blueberry_to_north_province_3(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - - - -} -} -} -#endif +/* Material Farmer - Happiny dust + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_MaterialFarmerTools_H +#define PokemonAutomation_PokemonSV_MaterialFarmerTools_H + +#include +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "PokemonSV/Options/PokemonSV_SandwichMakerOption.h" +#include "PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +struct MaterialFarmerStats : public LetsGoEncounterBotStats{ + MaterialFarmerStats() + : m_sandwiches(m_stats["Sandwiches"]) + , m_autoheals(m_stats["Auto Heals"]) + , m_game_resets(m_stats["Game Resets"]) + , m_errors(m_stats["Errors"]) + { + m_display_order.insert(m_display_order.begin() + 2, {"Sandwiches", HIDDEN_IF_ZERO}); + m_display_order.insert(m_display_order.begin() + 3, {"Auto Heals", HIDDEN_IF_ZERO}); + m_display_order.insert(m_display_order.begin() + 4, {"Game Resets", HIDDEN_IF_ZERO}); + m_display_order.insert(m_display_order.begin() + 5, {"Errors", HIDDEN_IF_ZERO}); + } + std::atomic& m_sandwiches; + std::atomic& m_autoheals; + std::atomic& m_game_resets; + std::atomic& m_errors; +}; + +class MaterialFarmerOptions : public GroupOption, public ConfigOption::Listener{ +public: + ~MaterialFarmerOptions(); + MaterialFarmerOptions( + GroupOption::EnableMode enable_mode, + OCR::LanguageOCROption* language_option, + EventNotificationOption& notif_status_update_option, + EventNotificationOption& notif_program_finish_option, + EventNotificationOption& notif_error_recoverable_option, + EventNotificationOption& notif_error_fatal_option + ); + virtual void on_config_value_changed(void* object) override; + +private: + std::unique_ptr m_language_owner; + +public: + SimpleIntegerOption RUN_TIME_IN_MINUTES; + + +// BooleanCheckBoxOption SAVE_GAME_BEFORE_SANDWICH; +// StaticTextOption SAVE_GAME_BEFORE_SANDWICH_STATIC_TEXT; + +// StaticTextOption NUM_SANDWICH_ROUNDS_STATIC_TEXT; + + OCR::LanguageOCROption& LANGUAGE; + SandwichMakerOption SANDWICH_OPTIONS; + FloatingPointOption AUTO_HEAL_PERCENT; + + // Debug options + SectionDividerOption m_advanced_options; + BooleanCheckBoxOption SAVE_DEBUG_VIDEO; + BooleanCheckBoxOption SKIP_WARP_TO_POKECENTER; +// BooleanCheckBoxOption ENABLE_SANDWICH; + SimpleIntegerOption TIME_PER_SANDWICH; + SimpleIntegerOption NUM_FORWARD_MOVES_PER_LETS_GO_ITERATION; + + EventNotificationOption& NOTIFICATION_STATUS_UPDATE; + EventNotificationOption& NOTIFICATION_PROGRAM_FINISH; + EventNotificationOption& NOTIFICATION_ERROR_RECOVERABLE; + EventNotificationOption& NOTIFICATION_ERROR_FATAL; +}; + + + +void run_material_farmer( + ProgramEnvironment& env, + ConsoleHandle& console, ProControllerContext& context, + MaterialFarmerOptions& options, + MaterialFarmerStats& stats +); + +void check_hp( + ProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context, + MaterialFarmerOptions& options, + LetsGoHpWatcher& hp_watcher, + MaterialFarmerStats& stats +); + +WallClock make_sandwich_material_farm( + ProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context, + MaterialFarmerOptions& options, + MaterialFarmerStats& stats +); + +void move_to_start_position_for_letsgo0(VideoStream& stream, ProControllerContext& context); + +void move_to_start_position_for_letsgo1(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +void lets_go_movement0(ProControllerContext& context); + +void lets_go_movement1(ProControllerContext& context); + +std::chrono::minutes minutes_remaining(WallClock start_time, std::chrono::minutes minutes_duration); + +void run_lets_go_iteration( + VideoStream& stream, + ProControllerContext& context, + LetsGoEncounterBotTracker& encounter_tracker, + int num_forward_moves_per_lets_go_iteration +); + +void run_from_battles_and_back_to_pokecenter( + ProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context, + MaterialFarmerStats& stats, + std::function< + void(ProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context) + >&& action +); + + + +void move_from_material_farming_to_item_printer(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +void fly_from_paldea_to_blueberry_entrance(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +void move_from_blueberry_entrance_to_league_club(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +void move_from_league_club_entrance_to_item_printer(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + + + +void move_from_item_printer_to_material_farming(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +void move_from_item_printer_to_blueberry_entrance(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +void fly_from_blueberry_to_north_province_3(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_VideoFastCodeEntry.cpp b/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_VideoFastCodeEntry.cpp index 2f599cc6dd..bdc220f937 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_VideoFastCodeEntry.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_VideoFastCodeEntry.cpp @@ -5,9 +5,9 @@ */ #include "Common/Cpp/CancellableScope.h" -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" #include "CommonFramework/Notifications/ProgramNotifications.h" #include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonFramework/Tools/GlobalThreadPools.h" #include "CommonFramework/VideoPipeline/VideoFeed.h" #include "CommonTools/Images/ImageFilter.h" #include "CommonTools/OCR/OCR_RawOCR.h" @@ -103,7 +103,7 @@ void wait_for_video_code_and_join( break; } case VideoFceOcrMethod::TERA_CARD: - code = read_raid_code(env.logger(), env.realtime_dispatcher(), snapshot); + code = read_raid_code(env.logger(), snapshot); } const char* error = enter_code(env, scope, settings, code, false, false); if (error == nullptr){ @@ -160,7 +160,8 @@ VideoFastCodeEntry::VideoFastCodeEntry() PA_ADD_OPTION(SETTINGS); PA_ADD_OPTION(NOTIFICATIONS); - // Preload the OCR data. + // Preload + GlobalThreadPools::realtime_inference().ensure_threads(6); OCR::ensure_instances(Language::English, 6); preload_code_templates(); } @@ -171,7 +172,7 @@ void VideoFastCodeEntry::update_active_consoles(size_t switch_count){ void VideoFastCodeEntry::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ if (MODE == Mode::MANUAL){ - std::string code = read_raid_code(env.logger(), env.realtime_dispatcher(), SCREEN_WATCHER.screenshot()); + std::string code = read_raid_code(env.logger(), SCREEN_WATCHER.screenshot()); const char* error = enter_code(env, scope, SETTINGS, code, false, !SKIP_CONNECT_TO_CONTROLLER); if (error){ env.log("No valid code found: " + std::string(error), COLOR_RED); @@ -185,7 +186,7 @@ void VideoFastCodeEntry::program(MultiSwitchProgramEnvironment& env, Cancellable }); // Preload 6 threads to OCR the code. - env.realtime_dispatcher().ensure_threads(6); +// env.realtime_dispatcher().ensure_threads(6); wait_for_video_code_and_join(env, scope, SCREEN_WATCHER, JOIN_METHOD, SETTINGS); diff --git a/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_WildItemFarmer.cpp b/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_WildItemFarmer.cpp index 5faa402c02..ff51e3a3aa 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_WildItemFarmer.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_WildItemFarmer.cpp @@ -1,471 +1,471 @@ -/* Wild Item Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" -#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" -#include "PokemonSV/Inference/PokemonSV_PokemonSummaryReader.h" -#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV_WildItemFarmer.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -WildItemFarmer_Descriptor::WildItemFarmer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:WildItemFarmer", - Pokemon::STRING_POKEMON + " SV", "Wild Item Farmer", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/WildItemFarmer.md", - "Farm an item held by a wild " + Pokemon::STRING_POKEMON + ".", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - -struct WildItemFarmer_Descriptor::Stats : public StatsTracker{ - Stats() - : battles(m_stats["Battles"]) - , items(m_stats["Items Cloned"]) - , failed(m_stats["Clone Failed"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Battles"); - m_display_order.emplace_back("Items Cloned"); - m_display_order.emplace_back("Clone Failed", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& battles; - std::atomic& items; - std::atomic& failed; - std::atomic& errors; -}; -std::unique_ptr WildItemFarmer_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - - -WildItemFarmer::WildItemFarmer() - : ITEMS_TO_CLONE( - "Items to Clone:", - LockMode::UNLOCK_WHILE_RUNNING, - 999, 0, 999 - ) -#if 0 - , TRICK_MOVE_SLOT( - "Trick Move Slot:", - { - {0, "slot1", "Slot 1"}, - {1, "slot2", "Slot 2"}, - {2, "slot3", "Slot 3"}, - {3, "slot4", "Slot 4"}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - 0 - ) -#endif - , INITIAL_TRICK_PP( - "Initial Trick PP:", - LockMode::UNLOCK_WHILE_RUNNING, - 1, 0, 16 - ) - , VERIFY_ITEM_CLONED( - "Verify Item Cloned:
Verify each run that the item has actually been cloned. " - "This will slow each iteration by a few seconds, but will better detect errors.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , ENABLE_FORWARD_RUN( - "Forward Run:
Run forward a bit before throwing ball. This will correct for " - "the clone moving away, but may cause your position to wander more.", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(ITEMS_TO_CLONE); -// PA_ADD_OPTION(TRICK_MOVE_SLOT); - PA_ADD_OPTION(INITIAL_TRICK_PP); - PA_ADD_OPTION(VERIFY_ITEM_CLONED); - PA_ADD_OPTION(ENABLE_FORWARD_RUN); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void WildItemFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - try{ - run_program(env, context); - }catch (...){ - pbf_press_button(context, BUTTON_HOME, 20, 105); - throw; - } -} - -void WildItemFarmer::refresh_pp(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - int move_overwrites = 0; - bool move_selected = false; - while (true){ - WhiteButtonWatcher summary( - COLOR_RED, WhiteButton::ButtonA, - {0.12, 0.67, 0.20, 0.06}, - WhiteButtonWatcher::FinderType::PRESENT, - std::chrono::milliseconds(500) - ); - AdvanceDialogWatcher dialog(COLOR_RED); - GradientArrowWatcher action_select(COLOR_GREEN, GradientArrowType::RIGHT, {0.515, 0.33, 0.05, 0.09}); - GradientArrowWatcher move_select(COLOR_YELLOW, GradientArrowType::RIGHT, {0.05, 0.20, 0.05, 0.09}); - context.wait_for_all_requests(); - - int ret = wait_until( - env.console, context, std::chrono::seconds(10), - { - summary, - dialog, - action_select, - move_select, - } - ); - if (move_overwrites >= 2){ - pbf_mash_button(context, BUTTON_B, 50); - return; - } - - switch (ret){ - case 0: - if (move_selected){ - move_overwrites++; - } - move_selected = false; - env.log("Detected Change Moves button. Overwrite count = " + std::to_string(move_overwrites)); - if (move_overwrites >= 2){ - continue; - } - pbf_press_button(context, BUTTON_A, 20, 105); - continue; - - case 1: - env.log("Detected dialog."); - pbf_press_button(context, BUTTON_A, 20, 105); - continue; - - case 2: - env.log("Detected action select."); - pbf_press_button(context, BUTTON_A, 20, 105); - continue; - - case 3: - env.log("Detected move select."); - pbf_press_button(context, BUTTON_A, 20, 105); - move_selected = true; - continue; - - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No state detected while changing moves after 10 seconds.", - env.console - ); - } - } -} - -bool WildItemFarmer::verify_item_held(SingleSwitchProgramEnvironment& env, ProControllerContext& context, NormalBattleMenuWatcher& battle_menu){ - env.log("Verifying that item has been taken..."); - - while (true){ - SwapMenuWatcher swap_menu(COLOR_BLUE); - context.wait_for_all_requests(); - int ret = wait_until( - env.console, context, std::chrono::seconds(10), - {battle_menu, swap_menu} - ); - context.wait_for(std::chrono::milliseconds(100)); - switch (ret){ - case 0: - env.log("Detected battle menu..."); - if (!battle_menu.move_to_slot(env.console, context, 1)){ - return false; - } - pbf_press_button(context, BUTTON_A, 20, 105); - continue; - - case 1: - env.log("Detected swap menu..."); - break; - - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to detect " + Pokemon::STRING_POKEMON + " select menu.", - env.console - ); - } - - break; - } - - VideoSnapshot screen = env.console.video().snapshot(); - ImageViewRGB32 box = extract_box_reference(screen, ImageFloatBox(0.28, 0.20, 0.03, 0.055)); - ImageStats stats = image_stats(box); - bool item_held = !is_solid(stats, {0.550405, 0.449595, 0.}, 0.20); - - { - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 500); - }, - {battle_menu} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to back out to battle menu.", - env.console - ); - } - } - - return item_held; -} - - -void WildItemFarmer::run_program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - WildItemFarmer_Descriptor::Stats& stats = env.current_stats(); - - const std::vector> MANUVERS{ - {128, 0}, - {96, 0}, - {160, 0}, - }; - - uint16_t items_cloned = 0; - bool trick_used = false; - bool overworld_seen = false; - int8_t trick_PP = INITIAL_TRICK_PP; - uint8_t consecutive_throw_attempts = 0; - WallClock last_trick_attempt = WallClock::min(); - while (items_cloned < ITEMS_TO_CLONE){ - OverworldWatcher overworld(env.console, COLOR_CYAN); - NormalBattleMenuWatcher battle_menu(COLOR_RED); - MoveSelectWatcher move_select(COLOR_YELLOW); - MainMenuWatcher main_menu(COLOR_GREEN); - PokemonSummaryWatcher summary(COLOR_BLUE); - - context.wait_for_all_requests(); - - int ret = wait_until( - env.console, context, std::chrono::seconds(120), - { - overworld, - battle_menu, - move_select, - main_menu, - summary, - } - ); - context.wait_for(std::chrono::milliseconds(100)); - switch (ret){ - case 0: - env.log("Detected overworld."); - if (trick_used && trick_PP > 0){ - trick_PP--; - if (!VERIFY_ITEM_CLONED){ - items_cloned++; - stats.items++; - env.update_stats(); - } - } - if (!overworld_seen){ - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - } - overworld_seen = true; - trick_used = false; - - env.log("Trick PP: " + std::to_string(trick_PP)); - - if (trick_PP <= 0){ - pbf_press_button(context, BUTTON_X, 20, 105); - continue; - } - - if (consecutive_throw_attempts >= MANUVERS.size()){ - stats.errors++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::NO_ERROR_REPORT, - "Failed to start battle after " + std::to_string(MANUVERS.size()) + " attempts.", - env.console - ); - } - - pbf_press_button(context, BUTTON_L, 20, 23); - if (ENABLE_FORWARD_RUN){ - const std::pair& direction = MANUVERS[consecutive_throw_attempts]; - pbf_move_left_joystick(context, (uint8_t)direction.first, (uint8_t)direction.second, 50, 0); - } - pbf_mash_button(context, BUTTON_ZR, 250); - pbf_wait(context, 350); - - consecutive_throw_attempts++; - - continue; - - case 1: - env.log("Detected battle menu."); - if (current_time() - std::chrono::seconds(5) < last_trick_attempt){ - env.log("Unable to use move. Assume out of PP."); - trick_PP = 0; -// pbf_mash_button(context, BUTTON_B, 30); -// continue; - } - - consecutive_throw_attempts = 0; - if (overworld_seen){ - stats.battles++; - env.update_stats(); - } - overworld_seen = false; - - if (trick_used && trick_PP > 0 && VERIFY_ITEM_CLONED){ - if (verify_item_held(env, context, battle_menu)){ - items_cloned++; - stats.items++; - env.update_stats(); - }else{ - stats.failed++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::NO_ERROR_REPORT, - "Failed to clone item. Possible incorrect encounter.", - env.console - ); - } - } - - if (trick_used || trick_PP <= 0){ - env.log("Running away..."); - if (battle_menu.move_to_slot(env.console, context, 3)){ - pbf_press_button(context, BUTTON_A, 20, 30); - }else{ - stats.errors++; - env.update_stats(); - pbf_mash_button(context, BUTTON_B, 125); - } - }else{ - env.log("Attempt to select a move."); - if (battle_menu.move_to_slot(env.console, context, 0)){ - pbf_press_button(context, BUTTON_A, 20, 30); - }else{ - stats.errors++; - env.update_stats(); - pbf_mash_button(context, BUTTON_B, 125); - } - } - continue; - - case 2: - env.log("Detected move select."); - if (current_time() - std::chrono::seconds(5) < last_trick_attempt){ - env.log("Unable to use move. Assume out of PP."); - trick_PP = 0; - pbf_mash_button(context, BUTTON_B, 30); - continue; - } - if (move_select.move_to_slot(env.console, context, 0)){ - pbf_press_button(context, BUTTON_A, 20, 30); - trick_used = true; - last_trick_attempt = current_time(); - }else{ - stats.errors++; - env.update_stats(); - pbf_mash_button(context, BUTTON_B, 125); - } - continue; - - case 3: - env.log("Detected main menu."); - if (trick_PP > 0){ - env.log("Backing out to overworld..."); - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - } - - if (!main_menu.move_cursor(env.program_info(), env.console, context, MenuSide::LEFT, 0)){ - stats.errors++; - env.update_stats(); - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - } - - env.log("Attempting to enter summary..."); - - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_A, 20, 105); - - continue; - - case 4: - env.log("Detected " + Pokemon::STRING_POKEMON + " summary."); - - if (trick_PP > 0){ - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - } - - pbf_press_dpad(context, DPAD_RIGHT, 20, 230); - - refresh_pp(env, context); - trick_PP = 10; - - pbf_press_button(context, BUTTON_B, 20, 105); - -// throw ProgramFinishedException(env.console, "Out of PP."); - continue; - - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No state detected after 120 seconds.", - env.console - ); - } - - - } - - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - -} -} -} +/* Wild Item Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" +#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" +#include "PokemonSV/Inference/PokemonSV_PokemonSummaryReader.h" +#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV_WildItemFarmer.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +WildItemFarmer_Descriptor::WildItemFarmer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:WildItemFarmer", + Pokemon::STRING_POKEMON + " SV", "Wild Item Farmer", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/WildItemFarmer.md", + "Farm an item held by a wild " + Pokemon::STRING_POKEMON + ".", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + +struct WildItemFarmer_Descriptor::Stats : public StatsTracker{ + Stats() + : battles(m_stats["Battles"]) + , items(m_stats["Items Cloned"]) + , failed(m_stats["Clone Failed"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Battles"); + m_display_order.emplace_back("Items Cloned"); + m_display_order.emplace_back("Clone Failed", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& battles; + std::atomic& items; + std::atomic& failed; + std::atomic& errors; +}; +std::unique_ptr WildItemFarmer_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + + +WildItemFarmer::WildItemFarmer() + : ITEMS_TO_CLONE( + "Items to Clone:", + LockMode::UNLOCK_WHILE_RUNNING, + 999, 0, 999 + ) +#if 0 + , TRICK_MOVE_SLOT( + "Trick Move Slot:", + { + {0, "slot1", "Slot 1"}, + {1, "slot2", "Slot 2"}, + {2, "slot3", "Slot 3"}, + {3, "slot4", "Slot 4"}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + 0 + ) +#endif + , INITIAL_TRICK_PP( + "Initial Trick PP:", + LockMode::UNLOCK_WHILE_RUNNING, + 1, 0, 16 + ) + , VERIFY_ITEM_CLONED( + "Verify Item Cloned:
Verify each run that the item has actually been cloned. " + "This will slow each iteration by a few seconds, but will better detect errors.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , ENABLE_FORWARD_RUN( + "Forward Run:
Run forward a bit before throwing ball. This will correct for " + "the clone moving away, but may cause your position to wander more.", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(ITEMS_TO_CLONE); +// PA_ADD_OPTION(TRICK_MOVE_SLOT); + PA_ADD_OPTION(INITIAL_TRICK_PP); + PA_ADD_OPTION(VERIFY_ITEM_CLONED); + PA_ADD_OPTION(ENABLE_FORWARD_RUN); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void WildItemFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + try{ + run_program(env, context); + }catch (...){ + pbf_press_button(context, BUTTON_HOME, 20, 105); + throw; + } +} + +void WildItemFarmer::refresh_pp(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + int move_overwrites = 0; + bool move_selected = false; + while (true){ + WhiteButtonWatcher summary( + COLOR_RED, WhiteButton::ButtonA, + {0.12, 0.67, 0.20, 0.06}, + WhiteButtonWatcher::FinderType::PRESENT, + std::chrono::milliseconds(500) + ); + AdvanceDialogWatcher dialog(COLOR_RED); + GradientArrowWatcher action_select(COLOR_GREEN, GradientArrowType::RIGHT, {0.515, 0.33, 0.05, 0.09}); + GradientArrowWatcher move_select(COLOR_YELLOW, GradientArrowType::RIGHT, {0.05, 0.20, 0.05, 0.09}); + context.wait_for_all_requests(); + + int ret = wait_until( + env.console, context, std::chrono::seconds(10), + { + summary, + dialog, + action_select, + move_select, + } + ); + if (move_overwrites >= 2){ + pbf_mash_button(context, BUTTON_B, 50); + return; + } + + switch (ret){ + case 0: + if (move_selected){ + move_overwrites++; + } + move_selected = false; + env.log("Detected Change Moves button. Overwrite count = " + std::to_string(move_overwrites)); + if (move_overwrites >= 2){ + continue; + } + pbf_press_button(context, BUTTON_A, 20, 105); + continue; + + case 1: + env.log("Detected dialog."); + pbf_press_button(context, BUTTON_A, 20, 105); + continue; + + case 2: + env.log("Detected action select."); + pbf_press_button(context, BUTTON_A, 20, 105); + continue; + + case 3: + env.log("Detected move select."); + pbf_press_button(context, BUTTON_A, 20, 105); + move_selected = true; + continue; + + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No state detected while changing moves after 10 seconds.", + env.console + ); + } + } +} + +bool WildItemFarmer::verify_item_held(SingleSwitchProgramEnvironment& env, ProControllerContext& context, NormalBattleMenuWatcher& battle_menu){ + env.log("Verifying that item has been taken..."); + + while (true){ + SwapMenuWatcher swap_menu(COLOR_BLUE); + context.wait_for_all_requests(); + int ret = wait_until( + env.console, context, std::chrono::seconds(10), + {battle_menu, swap_menu} + ); + context.wait_for(std::chrono::milliseconds(100)); + switch (ret){ + case 0: + env.log("Detected battle menu..."); + if (!battle_menu.move_to_slot(env.console, context, 1)){ + return false; + } + pbf_press_button(context, BUTTON_A, 20, 105); + continue; + + case 1: + env.log("Detected swap menu..."); + break; + + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to detect " + Pokemon::STRING_POKEMON + " select menu.", + env.console + ); + } + + break; + } + + VideoSnapshot screen = env.console.video().snapshot(); + ImageViewRGB32 box = extract_box_reference(screen, ImageFloatBox(0.28, 0.20, 0.03, 0.055)); + ImageStats stats = image_stats(box); + bool item_held = !is_solid(stats, {0.550405, 0.449595, 0.}, 0.20); + + { + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 500); + }, + {battle_menu} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to back out to battle menu.", + env.console + ); + } + } + + return item_held; +} + + +void WildItemFarmer::run_program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + WildItemFarmer_Descriptor::Stats& stats = env.current_stats(); + + const std::vector> MANUVERS{ + {128, 0}, + {96, 0}, + {160, 0}, + }; + + uint16_t items_cloned = 0; + bool trick_used = false; + bool overworld_seen = false; + int8_t trick_PP = INITIAL_TRICK_PP; + uint8_t consecutive_throw_attempts = 0; + WallClock last_trick_attempt = WallClock::min(); + while (items_cloned < ITEMS_TO_CLONE){ + OverworldWatcher overworld(env.console, COLOR_CYAN); + NormalBattleMenuWatcher battle_menu(COLOR_RED); + MoveSelectWatcher move_select(COLOR_YELLOW); + MainMenuWatcher main_menu(COLOR_GREEN); + PokemonSummaryWatcher summary(COLOR_BLUE); + + context.wait_for_all_requests(); + + int ret = wait_until( + env.console, context, std::chrono::seconds(120), + { + overworld, + battle_menu, + move_select, + main_menu, + summary, + } + ); + context.wait_for(std::chrono::milliseconds(100)); + switch (ret){ + case 0: + env.log("Detected overworld."); + if (trick_used && trick_PP > 0){ + trick_PP--; + if (!VERIFY_ITEM_CLONED){ + items_cloned++; + stats.items++; + env.update_stats(); + } + } + if (!overworld_seen){ + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + } + overworld_seen = true; + trick_used = false; + + env.log("Trick PP: " + std::to_string(trick_PP)); + + if (trick_PP <= 0){ + pbf_press_button(context, BUTTON_X, 20, 105); + continue; + } + + if (consecutive_throw_attempts >= MANUVERS.size()){ + stats.errors++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::NO_ERROR_REPORT, + "Failed to start battle after " + std::to_string(MANUVERS.size()) + " attempts.", + env.console + ); + } + + pbf_press_button(context, BUTTON_L, 20, 23); + if (ENABLE_FORWARD_RUN){ + const std::pair& direction = MANUVERS[consecutive_throw_attempts]; + pbf_move_left_joystick(context, (uint8_t)direction.first, (uint8_t)direction.second, 50, 0); + } + pbf_mash_button(context, BUTTON_ZR, 250); + pbf_wait(context, 350); + + consecutive_throw_attempts++; + + continue; + + case 1: + env.log("Detected battle menu."); + if (current_time() - std::chrono::seconds(5) < last_trick_attempt){ + env.log("Unable to use move. Assume out of PP."); + trick_PP = 0; +// pbf_mash_button(context, BUTTON_B, 30); +// continue; + } + + consecutive_throw_attempts = 0; + if (overworld_seen){ + stats.battles++; + env.update_stats(); + } + overworld_seen = false; + + if (trick_used && trick_PP > 0 && VERIFY_ITEM_CLONED){ + if (verify_item_held(env, context, battle_menu)){ + items_cloned++; + stats.items++; + env.update_stats(); + }else{ + stats.failed++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::NO_ERROR_REPORT, + "Failed to clone item. Possible incorrect encounter.", + env.console + ); + } + } + + if (trick_used || trick_PP <= 0){ + env.log("Running away..."); + if (battle_menu.move_to_slot(env.console, context, 3)){ + pbf_press_button(context, BUTTON_A, 20, 30); + }else{ + stats.errors++; + env.update_stats(); + pbf_mash_button(context, BUTTON_B, 125); + } + }else{ + env.log("Attempt to select a move."); + if (battle_menu.move_to_slot(env.console, context, 0)){ + pbf_press_button(context, BUTTON_A, 20, 30); + }else{ + stats.errors++; + env.update_stats(); + pbf_mash_button(context, BUTTON_B, 125); + } + } + continue; + + case 2: + env.log("Detected move select."); + if (current_time() - std::chrono::seconds(5) < last_trick_attempt){ + env.log("Unable to use move. Assume out of PP."); + trick_PP = 0; + pbf_mash_button(context, BUTTON_B, 30); + continue; + } + if (move_select.move_to_slot(env.console, context, 0)){ + pbf_press_button(context, BUTTON_A, 20, 30); + trick_used = true; + last_trick_attempt = current_time(); + }else{ + stats.errors++; + env.update_stats(); + pbf_mash_button(context, BUTTON_B, 125); + } + continue; + + case 3: + env.log("Detected main menu."); + if (trick_PP > 0){ + env.log("Backing out to overworld..."); + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + } + + if (!main_menu.move_cursor(env.program_info(), env.console, context, MenuSide::LEFT, 0)){ + stats.errors++; + env.update_stats(); + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + } + + env.log("Attempting to enter summary..."); + + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_A, 20, 105); + + continue; + + case 4: + env.log("Detected " + Pokemon::STRING_POKEMON + " summary."); + + if (trick_PP > 0){ + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + } + + pbf_press_dpad(context, DPAD_RIGHT, 20, 230); + + refresh_pp(env, context); + trick_PP = 10; + + pbf_press_button(context, BUTTON_B, 20, 105); + +// throw ProgramFinishedException(env.console, "Out of PP."); + continue; + + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No state detected after 120 seconds.", + env.console + ); + } + + + } + + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_WildItemFarmer.h b/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_WildItemFarmer.h index 1c6ef9964a..396532485d 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_WildItemFarmer.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_WildItemFarmer.h @@ -1,55 +1,55 @@ -/* Wild Item Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_WildItemFarmer_H -#define PokemonAutomation_PokemonSwSh_WildItemFarmer_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class NormalBattleMenuWatcher; - - -class WildItemFarmer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - WildItemFarmer_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class WildItemFarmer : public SingleSwitchProgramInstance{ -public: - WildItemFarmer(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void refresh_pp(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - bool verify_item_held(SingleSwitchProgramEnvironment& env, ProControllerContext& context, NormalBattleMenuWatcher& battle_menu); - void run_program(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -private: - SimpleIntegerOption ITEMS_TO_CLONE; -// IntegerEnumDropdownOption TRICK_MOVE_SLOT; - SimpleIntegerOption INITIAL_TRICK_PP; - BooleanCheckBoxOption VERIFY_ITEM_CLONED; - BooleanCheckBoxOption ENABLE_FORWARD_RUN; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - -} -} -} -#endif - - - +/* Wild Item Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_WildItemFarmer_H +#define PokemonAutomation_PokemonSwSh_WildItemFarmer_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class NormalBattleMenuWatcher; + + +class WildItemFarmer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + WildItemFarmer_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class WildItemFarmer : public SingleSwitchProgramInstance{ +public: + WildItemFarmer(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void refresh_pp(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + bool verify_item_held(SingleSwitchProgramEnvironment& env, ProControllerContext& context, NormalBattleMenuWatcher& battle_menu); + void run_program(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + SimpleIntegerOption ITEMS_TO_CLONE; +// IntegerEnumDropdownOption TRICK_MOVE_SLOT; + SimpleIntegerOption INITIAL_TRICK_PP; + BooleanCheckBoxOption VERIFY_ITEM_CLONED; + BooleanCheckBoxOption ENABLE_FORWARD_RUN; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_AutoItemPrinter.cpp b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_AutoItemPrinter.cpp index 5caf2fd1ac..43ff1ee8d5 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_AutoItemPrinter.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_AutoItemPrinter.cpp @@ -37,7 +37,8 @@ AutoItemPrinter_Descriptor::AutoItemPrinter_Descriptor() FeedbackType::REQUIRED, AllowCommandsWhenRunning::DISABLE_COMMANDS, {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER + FasterIfTickPrecise::NOT_FASTER, + true ) {} struct AutoItemPrinter_Descriptor::Stats : public StatsTracker{ @@ -135,12 +136,10 @@ void AutoItemPrinter::program(SingleSwitchProgramEnvironment& env, ProController for (uint16_t i = 0; i < NUM_ROUNDS; i++){ item_printer_start_print( - env.normal_inference_dispatcher(), env.console, context, LANGUAGE, ItemPrinterJobs::Jobs_10 ); item_printer_finish_print( - env.normal_inference_dispatcher(), env.console, context, Language::None ); diff --git a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNG.cpp b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNG.cpp index 263f24b18d..fc41093152 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNG.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNG.cpp @@ -340,6 +340,7 @@ ItemPrinterPrizeResult ItemPrinterRNG::run_print_at_date( material, } ); + context.wait_for(std::chrono::milliseconds(250)); next_wait_time = std::chrono::seconds(120); switch (ret){ case 0: @@ -396,8 +397,12 @@ ItemPrinterPrizeResult ItemPrinterRNG::run_print_at_date( pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); resume_game_from_home(env.console, context, false); - if (!prompt.detect(env.console.video().snapshot())){ + context.wait_for(250ms); + + VideoSnapshot snapshot = env.console.video().snapshot(); + if (!prompt.detect(snapshot)){ env.log("Expected to be on prompt menu. Backing out.", COLOR_RED); +// snapshot->save("noprompt.png"); stats.errors++; env.update_stats(); pbf_mash_button(context, BUTTON_B, 500); @@ -406,7 +411,7 @@ ItemPrinterPrizeResult ItemPrinterRNG::run_print_at_date( // Wait for trigger time. context.wait_until(trigger_time); - pbf_press_button(context, BUTTON_A, 10, 10); + pbf_press_button(context, BUTTON_A, 80ms, 500ms); continue; } case 4:{ @@ -418,11 +423,11 @@ ItemPrinterPrizeResult ItemPrinterRNG::run_print_at_date( pbf_press_button(context, BUTTON_B, 20, 30); continue; } - item_printer_start_print(env.normal_inference_dispatcher(), env.console, context, LANGUAGE, jobs); + item_printer_start_print(env.console, context, LANGUAGE, jobs); stats.prints++; env.update_stats(); printed = true; - prize_result = item_printer_finish_print(env.normal_inference_dispatcher(), env.console, context, LANGUAGE); + prize_result = item_printer_finish_print(env.console, context, LANGUAGE); std::array print_results = prize_result.prizes; uint64_t seed = to_seconds_since_epoch(date); int distance_from_target = get_distance_from_target(env.console, stats, print_results, seed); @@ -609,11 +614,11 @@ void ItemPrinterRNG::print_again( if (printed){ return; } - item_printer_start_print(env.normal_inference_dispatcher(), env.console, context, LANGUAGE, jobs); + item_printer_start_print(env.console, context, LANGUAGE, jobs); stats.prints++; env.update_stats(); printed = true; - item_printer_finish_print(env.normal_inference_dispatcher(), env.console, context, LANGUAGE); + item_printer_finish_print(env.console, context, LANGUAGE); continue; } default: @@ -986,11 +991,9 @@ uint32_t ItemPrinterRNG::check_num_happiny_dust( ItemPrinterMaterialDetector detector(COLOR_RED, LANGUAGE); int8_t happiny_dust_row_num = detector.find_happiny_dust_row_index( - env.normal_inference_dispatcher(), env.console, context ); num_happiny_dust = detector.detect_material_quantity( - env.normal_inference_dispatcher(), env.console, context, happiny_dust_row_num ); diff --git a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNGTable.cpp b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNGTable.cpp index 9aa7c6cdb3..d225d65b5f 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNGTable.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNGTable.cpp @@ -172,7 +172,6 @@ ItemPrinterDesiredItemRow::ItemPrinterDesiredItemRow(EditableTableOption& parent ItemPrinter::PrebuiltOptions::ABILITY_PATCH ) , desired_quantity( - "", LockMode::UNLOCK_WHILE_RUNNING, 999, 1, 999 ) diff --git a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNGTable.h b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNGTable.h index f94ef86310..1778e3261d 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNGTable.h +++ b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNGTable.h @@ -76,7 +76,6 @@ struct ItemPrinterDesiredItemRowSnapshot{ class ItemPrinterDesiredItemRow : public EditableTableRow, public ConfigOption::Listener{ public: - ItemPrinterDesiredItemRow(EditableTableOption& parent_table); ItemPrinterDesiredItemRow( @@ -91,7 +90,7 @@ class ItemPrinterDesiredItemRow : public EditableTableRow, public ConfigOption:: public: EnumDropdownCell desired_item; - SimpleIntegerOption desired_quantity; + SimpleIntegerCell desired_quantity; }; diff --git a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterTools.cpp b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterTools.cpp index 61faccc4cd..68e7fbc3a6 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterTools.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterTools.cpp @@ -31,7 +31,6 @@ const EnumDropdownDatabase& ItemPrinterJobs_Database(){ void item_printer_start_print( - AsyncDispatcher& dispatcher, VideoStream& stream, ProControllerContext& context, Language language, ItemPrinterJobs jobs ){ @@ -61,7 +60,7 @@ void item_printer_start_print( ItemPrinterJobsDetector detector(COLOR_RED); VideoOverlaySet overlays(stream.overlay()); detector.make_overlays(overlays); - detector.set_print_jobs(dispatcher, stream, context, (uint8_t)jobs); + detector.set_print_jobs(stream, context, (uint8_t)jobs); pbf_press_button(context, BUTTON_X, 20, 230); continue; } @@ -75,7 +74,6 @@ void item_printer_start_print( } } ItemPrinterPrizeResult item_printer_finish_print( - AsyncDispatcher& dispatcher, VideoStream& stream, ProControllerContext& context, Language language ){ @@ -116,8 +114,8 @@ ItemPrinterPrizeResult item_printer_finish_print( VideoOverlaySet overlays(stream.overlay()); reader.make_overlays(overlays); auto snapshot = stream.video().snapshot(); - std::array prizes = reader.read_prizes(stream.logger(), dispatcher, snapshot); - std::array quantities = reader.read_quantity(stream.logger(), dispatcher, snapshot); + std::array prizes = reader.read_prizes(stream.logger(), snapshot); + std::array quantities = reader.read_quantity(stream.logger(), snapshot); prize_result = {prizes, quantities}; // static int c = 0; // snapshot->save("test-" + std::to_string(c) + ".png"); diff --git a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterTools.h b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterTools.h index 1374aab845..d6aeff3bb0 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterTools.h +++ b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterTools.h @@ -14,7 +14,6 @@ #include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" namespace PokemonAutomation{ - class AsyncDispatcher; namespace NintendoSwitch{ namespace PokemonSV{ @@ -33,12 +32,10 @@ struct ItemPrinterPrizeResult{ void item_printer_start_print( - AsyncDispatcher& dispatcher, VideoStream& stream, ProControllerContext& context, Language language, ItemPrinterJobs jobs ); ItemPrinterPrizeResult item_printer_finish_print( - AsyncDispatcher& dispatcher, VideoStream& stream, ProControllerContext& context, Language language ); diff --git a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_AreaZero.cpp b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_AreaZero.cpp index 0b0edf0f9b..ad9109f082 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_AreaZero.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_AreaZero.cpp @@ -279,29 +279,29 @@ void inside_zero_gate_to_secret_cave_entrance( // Leg 1 - ssf_press_button(context, BUTTON_LCLICK, 0, 500); + ssf_press_button(context, BUTTON_LCLICK, 0ms, 4000ms); ssf_press_left_joystick(context, 128, 0, 60, 1250); // Jump - ssf_press_button(context, BUTTON_B, 125, 100); + ssf_press_button(context, BUTTON_B, 1000ms, 800ms); // Fly - ssf_press_button(context, BUTTON_B, 0, 20, 10); // Double up this press in - ssf_press_button(context, BUTTON_B, 0, 20); // case one is dropped. + ssf_press_button(context, BUTTON_B, 0ms, 160ms, 80ms); // Double up this press in + ssf_press_button(context, BUTTON_B, 0ms, 160ms); // case one is dropped. pbf_move_left_joystick(context, 128, 0, 1125, 300); // Leg 2 - ssf_press_button(context, BUTTON_LCLICK, 0, 500); + ssf_press_button(context, BUTTON_LCLICK, 0ms, 4000ms); ssf_press_left_joystick(context, 128, 0, 60, 250); // Jump - ssf_press_button(context, BUTTON_B, 125, 100); + ssf_press_button(context, BUTTON_B, 1000ms, 800ms); // Fly - ssf_press_button(context, BUTTON_B, 0, 20, 10); // Double up this press in - ssf_press_button(context, BUTTON_B, 0, 20); // case one is dropped. + ssf_press_button(context, BUTTON_B, 0ms, 160ms, 80ms); // Double up this press in + ssf_press_button(context, BUTTON_B, 0ms, 160ms); // case one is dropped. pbf_move_left_joystick(context, 128, 0, 250, 0); pbf_move_left_joystick(context, 112, 0, 250, 0); @@ -313,12 +313,12 @@ void inside_zero_gate_to_secret_cave_entrance( // Leg 3 - ssf_press_button(context, BUTTON_LCLICK, 0, 500); + ssf_press_button(context, BUTTON_LCLICK, 0ms, 4000ms); ssf_press_left_joystick(context, 128, 0, 180, 550); // Fly - ssf_press_button(context, BUTTON_B, 0, 20, 10); // Double up this press in - ssf_press_button(context, BUTTON_B, 0, 20); // case one is dropped. + ssf_press_button(context, BUTTON_B, 0ms, 160ms, 80ms); // Double up this press in + ssf_press_button(context, BUTTON_B, 0ms, 160ms); // case one is dropped. pbf_move_left_joystick(context, 48, 0, 200, 0); pbf_move_left_joystick(context, 128, 0, 250, 0); diff --git a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_MenuNavigation.cpp b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_MenuNavigation.cpp index 486c01fb0c..2adfb6c03d 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_MenuNavigation.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_MenuNavigation.cpp @@ -49,17 +49,16 @@ void set_time_to_12am_from_home(const ProgramInfo& info, ConsoleHandle& console, // resume_game_from_home(console, context); } -void day_skip_from_overworld(ConsoleHandle& console, ProControllerContext& context){ - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - home_to_date_time(console, context, true); +void neutral_day_skip_switch1(ConsoleHandle& console, ProControllerContext& context){ + console.log("PokemonSV::neutral_day_skip_switch1()"); Milliseconds tv = context->timing_variation(); if (tv == 0ms){ - ssf_press_button(context, BUTTON_A, 20, 10); + ssf_press_button(context, BUTTON_A, 160ms, 80ms); // Left scroll in case we missed the date menu and landed in the // language change. - ssf_issue_scroll(context, DPAD_LEFT, 0ms); + ssf_issue_scroll(context, DPAD_LEFT, 0ms, 48ms, 24ms); ssf_press_button(context, BUTTON_A, 24ms); ssf_issue_scroll(context, DPAD_RIGHT, 24ms); @@ -68,8 +67,8 @@ void day_skip_from_overworld(ConsoleHandle& console, ProControllerContext& conte ssf_issue_scroll(context, DPAD_RIGHT, 24ms); ssf_issue_scroll(context, DPAD_RIGHT, 24ms); ssf_issue_scroll(context, DPAD_RIGHT, 24ms); - ssf_issue_scroll(context, DPAD_RIGHT, 0); - ssf_press_button(context, BUTTON_A, 20, 10); + ssf_issue_scroll(context, DPAD_RIGHT, 0ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_A, 160ms, 80ms); }else{ ssf_press_button_ptv(context, BUTTON_A, 160ms); @@ -87,6 +86,35 @@ void day_skip_from_overworld(ConsoleHandle& console, ProControllerContext& conte ssf_issue_scroll_ptv(context, DPAD_RIGHT); ssf_press_button_ptv(context, BUTTON_A, 160ms); } +} +void neutral_day_skip_switch2(ConsoleHandle& console, ProControllerContext& context){ + console.log("PokemonSV::neutral_day_skip_switch2()"); + + ssf_press_button(context, BUTTON_A, 216ms, 80ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_press_button(context, BUTTON_A, 264ms, 80ms); +} + +void day_skip_from_overworld(ConsoleHandle& console, ProControllerContext& context){ + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + home_to_date_time(console, context, true); + + ConsoleType console_type = console.state().console_type(); + if (is_switch1(console_type)){ + neutral_day_skip_switch1(console, context); + }else if (is_switch2(console_type)){ + neutral_day_skip_switch2(console, context); + }else{ + throw UserSetupError( + console, + "Please select a valid Switch console type." + ); + } pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); resume_game_from_home(console, context); @@ -137,12 +165,13 @@ void open_map_from_overworld( {overworld, battle} ); context.wait_for(std::chrono::milliseconds(100)); + if (ret == 0){ stream.log("Detected overworld."); pbf_press_button(context, BUTTON_Y, 20, 105); // open map }else if (ret == 1){ throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, + stream.logger(), ErrorReport::NO_ERROR_REPORT, "open_map_from_overworld(): Unexpectedly detected battle.", stream ); @@ -178,6 +207,7 @@ void open_map_from_overworld( {overworld, advance_dialog, prompt_dialog, map, battle} ); context.wait_for(std::chrono::milliseconds(100)); + switch (ret){ case 0: stream.log("Detected overworld."); @@ -208,7 +238,7 @@ void open_map_from_overworld( case 4: stream.log("Detected battle."); throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, + stream.logger(), ErrorReport::NO_ERROR_REPORT, "open_map_from_overworld(): Unexpectedly detected battle.", stream ); diff --git a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_Terarium.cpp b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_Terarium.cpp index c9da89718a..05ebec19a7 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_Terarium.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_Terarium.cpp @@ -42,8 +42,8 @@ void return_to_plaza(const ProgramInfo& info, VideoStream& stream, ProController [&](ProControllerContext& context){ pbf_mash_button(context, BUTTON_B, 10000); }, - { overworld } - ); + {overworld} + ); if (ret_overworld == 0){ stream.log("Overworld detected."); } @@ -189,9 +189,9 @@ void jump_glide_fly( ){ stream.log("Jump, glide, fly."); - ssf_press_button(context, BUTTON_B, 0, 100); - ssf_press_button(context, BUTTON_B, 0, 20, 10); - ssf_press_button(context, BUTTON_B, 0, 20); + ssf_press_button(context, BUTTON_B, 0ms, 800ms); + ssf_press_button(context, BUTTON_B, 0ms, 160ms, 80ms); + ssf_press_button(context, BUTTON_B, 0ms, 160ms); pbf_wait(context, 100); context.wait_for_all_requests(); pbf_press_button(context, BUTTON_LCLICK, 50, 0); diff --git a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_WorldNavigation.cpp b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_WorldNavigation.cpp index 218dc868db..f218ddc05d 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_WorldNavigation.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_WorldNavigation.cpp @@ -210,7 +210,7 @@ void leave_picnic(const ProgramInfo& info, VideoStream& stream, ProControllerCon if (ret < 0){ OperationFailedException::fire( ErrorReport::SEND_ERROR_REPORT, - "leave_picnic(): Failed to detecxt overworld after 20 seconds.", + "leave_picnic(): Failed to detect overworld after 20 seconds.", stream ); } @@ -264,8 +264,8 @@ bool detect_closest_pokecenter_and_move_map_cursor_there( } // Convert the vector from center to the PokeCenter icon into a left joystick movement - const double dif_x = closest_icon_x - center_x; - const double dif_y = closest_icon_y - center_y; + const double dif_x = (closest_icon_x - center_x) * 1920/ screen_width; + const double dif_y = (closest_icon_y - center_y) * 1080/ screen_height; const double magnitude = std::max(std::sqrt(max_dist), 1.0); const double push_x = dif_x * 64 / magnitude, push_y = dif_y * 64 / magnitude; diff --git a/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.cpp b/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.cpp index c533a7724a..ea5aad3ad6 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.cpp @@ -6,10 +6,10 @@ #include #include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" #include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Tools/GlobalThreadPools.h" #include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" #include "PokemonSV/Resources/PokemonSV_Ingredients.h" #include "PokemonSV_IngredientSession.h" #include "Common/Cpp/PrettyPrint.h" @@ -25,12 +25,10 @@ namespace PokemonSV{ IngredientSession::~IngredientSession() = default; IngredientSession::IngredientSession( - AsyncDispatcher& dispatcher, VideoStream& stream, ProControllerContext& context, Language language, SandwichIngredientType type ) - : m_dispatcher(dispatcher) - , m_stream(stream) + : m_stream(stream) , m_context(context) , m_language(language) , m_overlays(stream.overlay()) @@ -71,23 +69,26 @@ PageIngredients IngredientSession::read_screen(std::shared_ptr // Read the names of every line and the sprite of the selected line. ImageMatch::ImageMatchResult image_result; SandwichIngredientReader reader(m_type); - m_dispatcher.run_in_parallel(0, SandwichIngredientReader::INGREDIENT_PAGE_LINES + 1, [&](size_t index){ - if (index < SandwichIngredientReader::INGREDIENT_PAGE_LINES){ - // Read text at line `index` - OCR::StringMatchResult result = reader.read_ingredient_page_with_ocr(*screen, m_stream.logger(), m_language, index); - result.clear_beyond_log10p(SandwichFillingOCR::MAX_LOG10P); - result.clear_beyond_spread(SandwichFillingOCR::MAX_LOG10P_SPREAD); - for (auto& item : result.results){ - ret.item[index].insert(item.second.token); + GlobalThreadPools::normal_inference().run_in_parallel( + [&](size_t index){ + if (index < SandwichIngredientReader::INGREDIENT_PAGE_LINES){ + // Read text at line `index` + OCR::StringMatchResult result = reader.read_ingredient_page_with_ocr(*screen, m_stream.logger(), m_language, index); + result.clear_beyond_log10p(SandwichFillingOCR::MAX_LOG10P); + result.clear_beyond_spread(SandwichFillingOCR::MAX_LOG10P_SPREAD); + for (auto& item : result.results){ + ret.item[index].insert(item.second.token); + } + }else{ + // Read current selected icon + image_result = reader.read_ingredient_page_with_icon_matcher(*screen, ret.selected); + image_result.clear_beyond_spread(SandwichIngredientReader::ALPHA_SPREAD); + image_result.log(m_stream.logger(), SandwichIngredientReader::MAX_ALPHA); + image_result.clear_beyond_alpha(SandwichIngredientReader::MAX_ALPHA); } - }else{ - // Read current selected icon - image_result = reader.read_ingredient_page_with_icon_matcher(*screen, ret.selected); - image_result.clear_beyond_spread(SandwichIngredientReader::ALPHA_SPREAD); - image_result.log(m_stream.logger(), SandwichIngredientReader::MAX_ALPHA); - image_result.clear_beyond_alpha(SandwichIngredientReader::MAX_ALPHA); - } - }); + }, + 0, SandwichIngredientReader::INGREDIENT_PAGE_LINES + 1 + ); #if 1 do{ @@ -316,20 +317,19 @@ void IngredientSession::add_ingredients( void add_sandwich_ingredients( - AsyncDispatcher& dispatcher, VideoStream& stream, ProControllerContext& context, Language language, std::map&& fillings, std::map&& condiments ){ { - IngredientSession session(dispatcher, stream, context, language, SandwichIngredientType::FILLING); + IngredientSession session(stream, context, language, SandwichIngredientType::FILLING); session.add_ingredients(stream, context, std::move(fillings)); pbf_press_button(context, BUTTON_PLUS, 20, 230); } { - IngredientSession session(dispatcher, stream, context, language, SandwichIngredientType::CONDIMENT); + IngredientSession session(stream, context, language, SandwichIngredientType::CONDIMENT); // If there are herbs, we search first from bottom if (std::any_of(condiments.begin(), condiments.end(), [&](const auto& p){return p.first.find("herba") != std::string::npos;})){ pbf_press_dpad(context, DPAD_UP, 20, 105); diff --git a/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.h b/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.h index 1d29831119..8928241244 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.h @@ -16,7 +16,6 @@ #include "PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.h" namespace PokemonAutomation{ - class AsyncDispatcher; namespace NintendoSwitch{ namespace PokemonSV{ @@ -36,7 +35,6 @@ class IngredientSession{ public: ~IngredientSession(); IngredientSession( - AsyncDispatcher& dispatcher, VideoStream& stream, ProControllerContext& context, Language language, SandwichIngredientType type ); @@ -61,7 +59,6 @@ class IngredientSession{ private: - AsyncDispatcher& m_dispatcher; VideoStream& m_stream; ProControllerContext& m_context; Language m_language; @@ -78,7 +75,6 @@ class IngredientSession{ // user must stack the fillings. // If any ingredient is not found or insuffient, it will OperationFailedException::fire. void add_sandwich_ingredients( - AsyncDispatcher& dispatcher, VideoStream& stream, ProControllerContext& context, Language language, std::map&& fillings, // {slug, quantity} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.cpp b/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.cpp index 0ae6bd7ff7..5e41efd971 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.cpp @@ -9,7 +9,6 @@ #include #include #include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" #include "CommonFramework/GlobalSettingsPanel.h" #include "CommonFramework/Exceptions/OperationFailedException.h" #include "CommonFramework/VideoPipeline/VideoFeed.h" @@ -392,8 +391,7 @@ Then updates the current location of expanded_hand_bb. Then moves the sandwich hand closer towards end_box. */ HandMoveData move_sandwich_hand_and_check_if_plates_empty( - const ProgramInfo& info, - AsyncDispatcher& dispatcher, + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, SandwichHandType hand_type, @@ -416,7 +414,7 @@ HandMoveData move_sandwich_hand_and_check_if_plates_empty( AsyncCommandSession move_session( context, stream.logger(), - dispatcher, + env.realtime_dispatcher(), context.controller() ); @@ -472,7 +470,7 @@ HandMoveData move_sandwich_hand_and_check_if_plates_empty( ); if(move_then_recover_sandwich_hand_position( - info, stream, context, hand_type, hand_watcher, move_session + env.program_info(), stream, context, hand_type, hand_watcher, move_session )){ continue; } @@ -553,7 +551,7 @@ HandMoveData move_sandwich_hand_and_check_if_plates_empty( if (pressing_A){ // Note: joystick_x and joystick_y must be defined to outlive `move_session`. // pbf_controller_state(context, BUTTON_A, DPAD_NONE, joystick_x, joystick_y, 128, 128, 20); - ssf_press_button(context, BUTTON_A, 0, 1000, 0); + ssf_press_button(context, BUTTON_A, 0ms, 8000ms, 0ms); } pbf_move_left_joystick(context, joystick_x, joystick_y, 20, 0); }); @@ -567,8 +565,7 @@ HandMoveData move_sandwich_hand_and_check_if_plates_empty( } ImageFloatBox move_sandwich_hand( - const ProgramInfo& info, - AsyncDispatcher& dispatcher, + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, SandwichHandType hand_type, @@ -577,7 +574,7 @@ ImageFloatBox move_sandwich_hand( const ImageFloatBox& end_box ){ return move_sandwich_hand_and_check_if_plates_empty( - info, dispatcher, + env, stream, context, hand_type, pressing_A, start_box, end_box, @@ -706,16 +703,16 @@ void enter_custom_sandwich_mode( namespace{ void finish_two_herbs_sandwich( - const ProgramInfo& info, AsyncDispatcher& dispatcher, + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context ){ stream.log("Finish determining ingredients for two-sweet-herb sandwich."); stream.overlay().add_log("Finish picking ingredients", COLOR_WHITE); - wait_for_initial_hand(info, stream, context); + wait_for_initial_hand(env.program_info(), stream, context); stream.overlay().add_log("Start making sandwich", COLOR_WHITE); - move_sandwich_hand(info, dispatcher, stream, context, SandwichHandType::FREE, false, HAND_INITIAL_BOX, INGREDIENT_BOX); + move_sandwich_hand(env, stream, context, SandwichHandType::FREE, false, HAND_INITIAL_BOX, INGREDIENT_BOX); // Mash button A to pick and drop ingredients, upper bread and pick. // Egg Power 3 is applied with only two sweet herb condiments! pbf_mash_button(context, BUTTON_A, 8 * TICKS_PER_SECOND); @@ -726,7 +723,8 @@ void finish_two_herbs_sandwich( } // anonymous namespace void make_two_herbs_sandwich( - const ProgramInfo& info, AsyncDispatcher& dispatcher, VideoStream& stream, ProControllerContext& context, + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, EggSandwichType sandwich_type, size_t sweet_herb_index_last, size_t salty_herb_index_last, size_t bitter_herb_index_last ){ // The game has at most 5 herbs, in the order of sweet, salty, sour, bitter, spicy: @@ -766,7 +764,7 @@ void make_two_herbs_sandwich( // Press button A to add first filling, assumed to be lettuce DeterminedSandwichIngredientWatcher filling_watcher(SandwichIngredientType::FILLING, 0); repeat_button_press_until( - info, stream, context, BUTTON_A, 40, 50, {filling_watcher}, + env.program_info(), stream, context, BUTTON_A, 40, 50, {filling_watcher}, "DeterminedIngredientNotDetected", "make_two_herbs_sandwich(): cannot detect determined lettuce after 50 seconds." ); } @@ -775,7 +773,7 @@ void make_two_herbs_sandwich( // Press button + to go to condiments page SandwichCondimentsPageWatcher condiments_page_watcher; repeat_button_press_until( - info, stream, context, BUTTON_PLUS, 40, 60, {condiments_page_watcher}, + env.program_info(), stream, context, BUTTON_PLUS, 40, 60, {condiments_page_watcher}, "CondimentsPageNotDetected", "make_two_herbs_sandwich(): cannot detect condiments page after 50 seconds." ); } @@ -799,7 +797,7 @@ void make_two_herbs_sandwich( auto move_one_up_to_row = [&](size_t row){ stream.log("Move arrow to row " + std::to_string(row)); SandwichIngredientArrowWatcher arrow(row); - repeat_dpad_press_until(info, stream, context, DPAD_UP, 10, 30, {arrow}, "IngredientArrowNotDetected", + repeat_dpad_press_until(env.program_info(), stream, context, DPAD_UP, 10, 30, {arrow}, "IngredientArrowNotDetected", "make_two_herbs_sandwich(): cannot detect ingredient selection arrow at row " + std::to_string(row) + " after 50 seconds." ); }; @@ -807,7 +805,7 @@ void make_two_herbs_sandwich( auto press_a_to_determine_herb = [&](size_t herb_index){ DeterminedSandwichIngredientWatcher herb_watcher(SandwichIngredientType::CONDIMENT, herb_index); repeat_button_press_until( - info, stream, context, BUTTON_A, 40, 60, {herb_watcher}, "CondimentsPageNotDetected", + env.program_info(), stream, context, BUTTON_A, 40, 60, {herb_watcher}, "CondimentsPageNotDetected", "make_two_herbs_sandwich(): cannot detect determined herb at cell " + std::to_string(herb_index) + " after 50 seconds." ); }; @@ -827,7 +825,7 @@ void make_two_herbs_sandwich( // Press button + to go to picks page SandwichPicksPageWatcher picks_page_watcher; repeat_button_press_until( - info, stream, context, BUTTON_PLUS, 40, 60, {picks_page_watcher}, + env.program_info(), stream, context, BUTTON_PLUS, 40, 60, {picks_page_watcher}, "CondimentsPageNotDetected", "make_two_herbs_sandwich(): cannot detect picks page after 50 seconds." ); } @@ -836,11 +834,12 @@ void make_two_herbs_sandwich( pbf_mash_button(context, BUTTON_A, 80); context.wait_for_all_requests(); - finish_two_herbs_sandwich(info, dispatcher, stream, context); + finish_two_herbs_sandwich(env, stream, context); } void make_two_herbs_sandwich( - const ProgramInfo& info, AsyncDispatcher& dispatcher, VideoStream& stream, ProControllerContext& context, + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, EggSandwichType sandwich_type, Language language ){ std::map fillings = {{"lettuce", (uint8_t)1}}; @@ -862,14 +861,13 @@ void make_two_herbs_sandwich( ); } add_sandwich_ingredients( - dispatcher, stream, context, language, std::move(fillings), std::move(condiments) ); - finish_two_herbs_sandwich(info, dispatcher, stream, context); + finish_two_herbs_sandwich(env, stream, context); } void make_sandwich_option(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, SandwichMakerOption& SANDWICH_OPTIONS){ @@ -1053,7 +1051,6 @@ void make_sandwich_preset(ProgramEnvironment& env, VideoStream& stream, ProContr std::map fillings_copy(fillings); //Making a copy as we need the map for later enter_custom_sandwich_mode(env.program_info(), stream, context); add_sandwich_ingredients( - env.normal_inference_dispatcher(), stream, context, language, std::move(fillings_copy), @@ -1063,7 +1060,14 @@ void make_sandwich_preset(ProgramEnvironment& env, VideoStream& stream, ProContr run_sandwich_maker(env, stream, context, language, fillings, fillings_sorted, plates); } -void run_sandwich_maker(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, Language language, std::map& fillings, std::vector& fillings_sorted, int& plates){ +void run_sandwich_maker( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + Language language, + std::map& fillings, + std::vector& fillings_sorted, + int& plates +){ wait_for_initial_hand(env.program_info(), stream, context); @@ -1191,7 +1195,7 @@ void run_sandwich_maker(ProgramEnvironment& env, VideoStream& stream, ProControl ImageFloatBox target_plate = center_plate; //Initial position handling auto end_box = move_sandwich_hand( - env.program_info(), env.realtime_inference_dispatcher(), + env, stream, context, SandwichHandType::FREE, false, @@ -1199,7 +1203,7 @@ void run_sandwich_maker(ProgramEnvironment& env, VideoStream& stream, ProControl HAND_INITIAL_BOX ); move_sandwich_hand( - env.program_info(), env.realtime_inference_dispatcher(), + env, stream, context, SandwichHandType::GRABBING, true, @@ -1270,7 +1274,7 @@ void run_sandwich_maker(ProgramEnvironment& env, VideoStream& stream, ProControl } end_box = move_sandwich_hand( - env.program_info(), env.realtime_inference_dispatcher(), + env, stream, context, SandwichHandType::FREE, false, @@ -1284,7 +1288,7 @@ void run_sandwich_maker(ProgramEnvironment& env, VideoStream& stream, ProControl (int)fillings.find(i)->second).at(placement_number); HandMoveData hand_move_data = move_sandwich_hand_and_check_if_plates_empty( - env.program_info(), env.realtime_inference_dispatcher(), + env, stream, context, SandwichHandType::GRABBING, true, @@ -1333,7 +1337,7 @@ void run_sandwich_maker(ProgramEnvironment& env, VideoStream& stream, ProControl auto hand_box = hand_location_to_box(grabbing_hand.location()); end_box = move_sandwich_hand( - env.program_info(), env.realtime_inference_dispatcher(), + env, stream, context, SandwichHandType::GRABBING, false, diff --git a/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h b/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h index d0bc78c238..27ce5ac1f5 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h @@ -18,7 +18,6 @@ namespace PokemonAutomation{ struct ProgramInfo; - class AsyncDispatcher; class ProgramEnvironment; namespace NintendoSwitch{ @@ -72,7 +71,7 @@ enum class EggSandwichType{ // It will use the first sandwich pick in the sandwich pick selection list. // After entering sandiwich mini game, it will drop the filling to quickly make a two-herb only sandwich to gain egg power lv 3. void make_two_herbs_sandwich( - const ProgramInfo& info, AsyncDispatcher& dispatcher, + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, EggSandwichType sandwich_type, size_t sweet_herb_index_last, @@ -84,9 +83,8 @@ void make_two_herbs_sandwich( // It will use the first sandwich pick in the sandwich pick selection list. // After entering sandiwich mini game, it will drop the filling to quickly make a two-herb only sandwich to gain egg power lv 3. void make_two_herbs_sandwich( - const ProgramInfo& info, - AsyncDispatcher& dispatcher, VideoStream& stream, - ProControllerContext& context, + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, EggSandwichType sandwich_type, Language language ); @@ -119,7 +117,8 @@ void run_sandwich_maker( ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, Language language, - std::map& fillings, std::vector& fillings_sorted, + std::map& fillings, + std::vector& fillings_sorted, int& plates ); diff --git a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_AreaZeroPlatform.cpp b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_AreaZeroPlatform.cpp index 482845bf7c..579d481401 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_AreaZeroPlatform.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_AreaZeroPlatform.cpp @@ -200,7 +200,7 @@ void inside_zero_gate_to_platform( pbf_move_left_joystick(context, 192, 0, 20, 105); pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - ssf_press_button(context, BUTTON_LCLICK, 0, 500); + ssf_press_button(context, BUTTON_LCLICK, 0ms, 4000ms); if (!flying_unlocked){ ssf_press_left_joystick(context, 128, 0, 125, 1250); }else{ @@ -208,11 +208,11 @@ void inside_zero_gate_to_platform( } // Jump - ssf_press_button(context, BUTTON_B, 125, 100); + ssf_press_button(context, BUTTON_B, 1000ms, 800ms); // Fly - ssf_press_button(context, BUTTON_B, 0, 20, 10); // Double up this press in - ssf_press_button(context, BUTTON_B, 0, 20); // case one is dropped. + ssf_press_button(context, BUTTON_B, 0ms, 160ms, 80ms); // Double up this press in + ssf_press_button(context, BUTTON_B, 0ms, 160ms); // case one is dropped. if (!flying_unlocked){ // ssf_press_left_joystick(context, 128, 0, 375, 875); @@ -334,7 +334,7 @@ void area_zero_platform_run_path0( break; } - ssf_press_button(context, BUTTON_L, 0, 20); + ssf_press_button(context, BUTTON_L, 0ms, 160ms); pbf_move_left_joystick(context, x, 0, duration, 0); }); use_lets_go_to_clear_in_front(stream, context, tracker, true, [&](ProControllerContext& context){ diff --git a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.cpp b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.cpp index 9398761bd6..fcb8898d11 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.cpp @@ -152,162 +152,25 @@ void DiscontiguousTimeTracker::add_block(WallClock start, WallClock end){ LetsGoEncounterBotTracker::LetsGoEncounterBotTracker( ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, + VideoStream& stream, LetsGoEncounterBotStats& stats, - OCR::LanguageOCROption& language + LetsGoKillSoundDetector& kill_sound ) - : m_env(env) - , m_stream(stream) - , m_context(context) - , m_stats(stats) - , m_language(language) - , m_kill_sound(stream.logger(), [&](float){ + : m_kill_sound(kill_sound) +{ + m_kill_sound.set_detected_callback([&](float){ stream.log("Detected kill."); m_encounter_rate.report_kill(); stats.m_kills++; env.update_stats(); return false; - }) - , m_session(context, stream, {m_kill_sound}) -{} -void LetsGoEncounterBotTracker::process_battle( - bool& caught, bool& should_save, - EncounterWatcher& watcher, EncounterBotCommonOptions& settings -){ - m_encounter_rate.report_encounter(); - m_stats.m_encounters++; - - Language language = m_language; - - std::set slugs; - if (language != Language::None){ - slugs = read_singles_opponent(m_env.program_info(), m_stream, m_context, language); - m_encounter_frequencies += slugs; - m_env.log(m_encounter_frequencies.dump_sorted_map("Encounter Stats:\n")); - } - - bool is_shiny = (bool)watcher.shiny_screenshot(); - if (is_shiny){ - m_stats.m_shinies++; - if (settings.VIDEO_ON_SHINY){ - m_context.wait_for(std::chrono::seconds(3)); - pbf_press_button(m_context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 0); - } - } - m_env.update_stats(); - - send_encounter_notification( - m_env, - settings.NOTIFICATION_NONSHINY, - settings.NOTIFICATION_SHINY, - language != Language::None, - is_shiny, - {{slugs, is_shiny ? ShinyType::UNKNOWN_SHINY : ShinyType::NOT_SHINY}}, - watcher.lowest_error_coefficient(), - watcher.shiny_screenshot(), - &m_encounter_frequencies - ); - - // Set default action: stop program if shiny, otherwise run away. - EncounterActionsEntry action; - action.action = is_shiny - ? EncounterActionsAction::STOP_PROGRAM - : EncounterActionsAction::RUN_AWAY; - - // Iterate the actions table. If found an entry matches the pokemon species, - // set the action to be what specified in the entry. - for (EncounterActionsEntry& entry : settings.ACTIONS_TABLE.snapshot()){ - if (language == Language::None){ - throw UserSetupError(m_stream.logger(), "You must set the game language to use the actions table."); - } - - // See if Pokemon name matches. - auto iter = slugs.find(entry.pokemon); - if (iter == slugs.end()){ - continue; - } - - switch (entry.shininess){ - case EncounterActionsShininess::ANYTHING: - break; - case EncounterActionsShininess::NOT_SHINY: - if (is_shiny){ - continue; - } - break; - case EncounterActionsShininess::SHINY: - if (!is_shiny){ - continue; - } - break; - } - - action = std::move(entry); - } - - // Run the chosen action. - switch (action.action){ - case EncounterActionsAction::RUN_AWAY: - try{ - run_from_battle(m_env.program_info(), m_stream, m_context); - }catch (OperationFailedException& e){ - throw FatalProgramException(std::move(e)); - } - caught = false; - should_save = false; - return; - case EncounterActionsAction::STOP_PROGRAM: - throw ProgramFinishedException(); -// throw ProgramFinishedException(m_stream, "", true); - case EncounterActionsAction::THROW_BALLS: - case EncounterActionsAction::THROW_BALLS_AND_SAVE: - if (language == Language::None){ - throw InternalProgramError(&m_stream.logger(), PA_CURRENT_FUNCTION, "Language is not set."); - } - - CatchResults result = basic_catcher( - m_stream, m_context, - language, - action.ball, action.ball_limit, - settings.USE_FIRST_MOVE_IF_CANNOT_THROW_BALL - ); - send_catch_notification( - m_env, - settings.NOTIFICATION_CATCH_SUCCESS, - settings.NOTIFICATION_CATCH_FAILED, - &slugs, - action.ball, - result.balls_used, - result.result - ); - - switch (result.result){ - case CatchResult::POKEMON_CAUGHT: - case CatchResult::POKEMON_FAINTED: - break; - default: - throw_and_log( - m_stream.logger(), ErrorReport::NO_ERROR_REPORT, - "Unable to recover from failed catch.", - m_stream - ); - } - - caught = result.result == CatchResult::POKEMON_CAUGHT; - should_save = caught && action.action == EncounterActionsAction::THROW_BALLS_AND_SAVE; - return; - } - - caught = false; - should_save = false; + }); } - - bool use_lets_go_to_clear_in_front( VideoStream& stream, ProControllerContext& context, LetsGoEncounterBotTracker& tracker, diff --git a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h index fe1a18a319..fc6a3ed1e9 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h +++ b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h @@ -18,6 +18,10 @@ #include "PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.h" #include "PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h" +//#include +//using std::cout; +//using std::endl; + namespace PokemonAutomation{ class CancellableScope; class ProgramEnvironment; @@ -112,9 +116,9 @@ class LetsGoEncounterBotTracker{ public: LetsGoEncounterBotTracker( ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, + VideoStream& stream, LetsGoEncounterBotStats& stats, - OCR::LanguageOCROption& language + LetsGoKillSoundDetector& kill_sound ); void throw_if_no_sound(std::chrono::milliseconds min_duration = std::chrono::milliseconds(10000)) const{ @@ -127,7 +131,10 @@ class LetsGoEncounterBotTracker{ WallClock last_kill() const{ return m_kill_sound.last_kill(); } - const EncounterFrequencies& encounter_frequencies() const{ + EncounterRateTracker& encounter_rate_tracker(){ + return m_encounter_rate; + } + EncounterFrequencies& encounter_frequencies(){ return m_encounter_frequencies; } @@ -143,25 +150,12 @@ class LetsGoEncounterBotTracker{ m_encounter_rate.report_start(); } - // Returns true if you should save the game. - void process_battle( - bool& caught, bool& should_save, - EncounterWatcher& watcher, EncounterBotCommonOptions& settings - ); - private: - ProgramEnvironment& m_env; - VideoStream& m_stream; - ProControllerContext& m_context; - LetsGoEncounterBotStats& m_stats; - - OCR::LanguageOCROption& m_language; + LetsGoKillSoundDetector& m_kill_sound; EncounterRateTracker m_encounter_rate; EncounterFrequencies m_encounter_frequencies; - LetsGoKillSoundDetector m_kill_sound; - InferenceSession m_session; }; @@ -182,6 +176,32 @@ bool use_lets_go_to_clear_in_front( + + + + + + + + + + + + + + + + + + + + + + + + + + } } } diff --git a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.cpp b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.cpp index 5db0934358..3cf1360c36 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.cpp @@ -19,7 +19,6 @@ #include "PokemonSV/PokemonSV_Settings.h" #include "PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.h" #include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" -#include "PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h" #include "PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h" #include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" #include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" @@ -189,6 +188,15 @@ void ShinyHuntAreaZeroPlatform::on_config_value_changed(void* object){ + + + + + + + + + bool ShinyHuntAreaZeroPlatform::run_traversal(ProControllerContext& context){ ShinyHuntAreaZeroPlatform_Descriptor::Stats& stats = m_env->current_stats(); @@ -201,7 +209,7 @@ bool ShinyHuntAreaZeroPlatform::run_traversal(ProControllerContext& context){ // m_last_save = SavedLocation::AREA_ZERO; // } - double hp = m_hp_watcher->last_known_value() * 100; + double hp = m_sensors->lets_go_hp.last_known_value() * 100; if (0 < hp){ stream.log("Last Known HP: " + tostr_default(hp) + "%", COLOR_BLUE); }else{ @@ -333,7 +341,9 @@ void ShinyHuntAreaZeroPlatform::set_flags(SingleSwitchProgramEnvironment& env){ ); } -void ShinyHuntAreaZeroPlatform::run_state(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ +void ShinyHuntAreaZeroPlatform::run_state( + SingleSwitchProgramEnvironment& env, ProControllerContext& context +){ ShinyHuntAreaZeroPlatform_Descriptor::Stats& stats = m_env->current_stats(); const ProgramInfo& info = m_env->program_info(); VideoStream& stream = m_env->console; @@ -437,7 +447,9 @@ void ShinyHuntAreaZeroPlatform::run_state(SingleSwitchProgramEnvironment& env, P return; } } -void ShinyHuntAreaZeroPlatform::set_flags_and_run_state(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ +void ShinyHuntAreaZeroPlatform::set_flags_and_run_state( + SingleSwitchProgramEnvironment& env, ProControllerContext& context +){ set_flags(env); ShinyHuntAreaZeroPlatform_Descriptor::Stats& stats = m_env->current_stats(); @@ -461,6 +473,12 @@ void ShinyHuntAreaZeroPlatform::set_flags_and_run_state(SingleSwitchProgramEnvir } } + + + + + + void ShinyHuntAreaZeroPlatform::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ m_env = &env; @@ -470,16 +488,20 @@ void ShinyHuntAreaZeroPlatform::program(SingleSwitchProgramEnvironment& env, Pro m_iterations = 0; - LetsGoHpWatcher hp_watcher(COLOR_RED); - m_hp_watcher = &hp_watcher; + OverworldSensors sensors( + env.logger(), env.console, context + ); + m_sensors = &sensors; + + OverworldBattleTracker battle_tracker(env.logger(), sensors); DiscontiguousTimeTracker time_tracker; m_time_tracker = &time_tracker; LetsGoEncounterBotTracker encounter_tracker( - env, env.console, context, + env, env.console, stats, - LANGUAGE + sensors.lets_go_kill ); m_encounter_tracker = &encounter_tracker; @@ -519,7 +541,7 @@ void ShinyHuntAreaZeroPlatform::program(SingleSwitchProgramEnvironment& env, Pro while (true){ try{ env.console.log("Starting encounter loop...", COLOR_PURPLE); - EncounterWatcher encounter_watcher(env.console, COLOR_RED); + NormalBattleMenuWatcher battle_menu(COLOR_RED); run_until( env.console, context, [&](ProControllerContext& context){ @@ -528,20 +550,27 @@ void ShinyHuntAreaZeroPlatform::program(SingleSwitchProgramEnvironment& env, Pro set_flags_and_run_state(env, context); } }, - { - static_cast(encounter_watcher), - static_cast(encounter_watcher), - hp_watcher, - } + {battle_menu} ); - encounter_watcher.throw_if_no_sound(); + sensors.throw_if_no_sound(); env.console.log("Detected battle.", COLOR_PURPLE); + stats.m_encounters++; + env.update_stats(); + encounter_tracker.encounter_rate_tracker().report_encounter(); + bool caught, should_save; - encounter_tracker.process_battle( + process_battle( caught, should_save, - encounter_watcher, ENCOUNTER_BOT_OPTIONS + env, + ENCOUNTER_BOT_OPTIONS, + env.console, context, + battle_tracker, + encounter_tracker.encounter_frequencies(), + stats.m_shinies, + LANGUAGE ); + m_pending_save |= should_save; if (caught){ m_reset_on_next_sandwich = false; diff --git a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.h b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.h index 20ed9c9b7c..9b46f95134 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.h +++ b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.h @@ -7,7 +7,7 @@ #ifndef PokemonAutomation_PokemonSV_ShinyHuntAreaZeroPlatform_H #define PokemonAutomation_PokemonSV_ShinyHuntAreaZeroPlatform_H -#include +//#include //#include "Common/Cpp/Options/BooleanCheckBoxOption.h" //#include "Common/Cpp/Options/SimpleIntegerOption.h" #include "Common/Cpp/Options/FloatingPointOption.h" @@ -18,6 +18,8 @@ #include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" #include "PokemonSV/Options/PokemonSV_EncounterBotCommon.h" #include "PokemonSV/Options/PokemonSV_SandwichMakerOption.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldSensors.h" +#include "PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h" #include "PokemonSV_AreaZeroPlatform.h" namespace PokemonAutomation{ @@ -66,8 +68,12 @@ class ShinyHuntAreaZeroPlatform : public SingleSwitchProgramInstance, public Con // }; void set_flags(SingleSwitchProgramEnvironment& env); - void run_state(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void set_flags_and_run_state(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void run_state( + SingleSwitchProgramEnvironment& env, ProControllerContext& context + ); + void set_flags_and_run_state( + SingleSwitchProgramEnvironment& env, ProControllerContext& context + ); // Returns true on success. bool run_traversal(ProControllerContext& context); @@ -107,7 +113,8 @@ class ShinyHuntAreaZeroPlatform : public SingleSwitchProgramInstance, public Con SingleSwitchProgramEnvironment* m_env; - LetsGoHpWatcher* m_hp_watcher; + OverworldSensors* m_sensors; +// LetsGoHpWatcher* m_hp_watcher; DiscontiguousTimeTracker* m_time_tracker; LetsGoEncounterBotTracker* m_encounter_tracker; diff --git a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.cpp b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.cpp index 0ff07ac4ab..0bb6d3af3d 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.cpp @@ -16,9 +16,10 @@ #include "CommonTools/StartupChecks/VideoResolutionCheck.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" #include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.h" #include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" #include "PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldSensors.h" #include "PokemonSV/Programs/PokemonSV_GameEntry.h" #include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" #include "PokemonSV/Programs/PokemonSV_SaveGame.h" @@ -168,10 +169,18 @@ void ShinyHuntScatterbug::program(SingleSwitchProgramEnvironment& env, ProContro save_game_from_overworld(env.program_info(), env.console, context); } + OverworldSensors sensors( + env.logger(), env.console, context + ); + m_sensors = &sensors; + + OverworldBattleTracker battle_tracker(env.logger(), sensors); + m_battle_tracker = &battle_tracker; + LetsGoEncounterBotTracker encounter_tracker( - env, env.console, context, + env, env.console, stats, - LANGUAGE + sensors.lets_go_kill ); m_encounter_tracker = &encounter_tracker; @@ -226,21 +235,22 @@ void ShinyHuntScatterbug::program(SingleSwitchProgramEnvironment& env, ProContro // back to PokeCenter to start the `action` again. // `action` must be an action starting at the PokeCenter void ShinyHuntScatterbug::handle_battles_and_back_to_pokecenter( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, + SingleSwitchProgramEnvironment& env, ProControllerContext& context, std::function&& action ){ if (m_encounter_tracker == nullptr){ throw InternalProgramError(&env.logger(), PA_CURRENT_FUNCTION, "m_encounter_tracker == nullptr"); } + ShinyHuntScatterbug_Descriptor::Stats& stats = env.current_stats(); + bool action_finished = false; bool first_iteration = true; // a flag for the case that the action has finished but not yet returned to pokecenter bool returned_to_pokecenter = false; while(action_finished == false || returned_to_pokecenter == false){ // env.console.overlay().add_log("Calculate what to do next"); - EncounterWatcher encounter_watcher(env.console, COLOR_RED); + NormalBattleMenuWatcher battle_menu(COLOR_RED); int ret = run_until( env.console, context, [&](ProControllerContext& context){ @@ -266,24 +276,29 @@ void ShinyHuntScatterbug::handle_battles_and_back_to_pokecenter( context.wait_for_all_requests(); action_finished = true; }, - { - static_cast(encounter_watcher), - static_cast(encounter_watcher), - } + {battle_menu} ); - encounter_watcher.throw_if_no_sound(); + m_sensors->throw_if_no_sound(); if (ret >= 0){ env.console.log("Detected battle.", COLOR_PURPLE); env.console.overlay().add_log("Detected battle"); + stats.m_encounters++; + env.update_stats(); + m_encounter_tracker->encounter_rate_tracker().report_encounter(); try{ bool caught, should_save; - m_encounter_tracker->process_battle( + process_battle( caught, should_save, - encounter_watcher, ENCOUNTER_BOT_OPTIONS + env, + ENCOUNTER_BOT_OPTIONS, + env.console, context, + *m_battle_tracker, + m_encounter_tracker->encounter_frequencies(), + stats.m_shinies, + LANGUAGE ); - if (should_save){ - m_pending_save = should_save; - } + + m_pending_save |= should_save; }catch (ProgramFinishedException&){ GO_HOME_WHEN_DONE.run_end_of_program(context); throw; @@ -295,7 +310,9 @@ void ShinyHuntScatterbug::handle_battles_and_back_to_pokecenter( // Start at Mesagoza South Gate pokecenter, make a sandwich, then use let's go repeatedly until 30 min passes. // If -void ShinyHuntScatterbug::run_one_sandwich_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ +void ShinyHuntScatterbug::run_one_sandwich_iteration( + SingleSwitchProgramEnvironment& env, ProControllerContext& context +){ ShinyHuntScatterbug_Descriptor::Stats& stats = env.current_stats(); bool saved_after_this_sandwich = false; @@ -310,7 +327,8 @@ void ShinyHuntScatterbug::run_one_sandwich_iteration(SingleSwitchProgramEnvironm } }; - handle_battles_and_back_to_pokecenter(env, context, + handle_battles_and_back_to_pokecenter( + env, context, [this, &last_sandwich_time](SingleSwitchProgramEnvironment& env, ProControllerContext& context){ // Orient camera to look at same direction as player character // This is needed because when save-load the game, the camera is reset @@ -364,7 +382,8 @@ void ShinyHuntScatterbug::run_one_sandwich_iteration(SingleSwitchProgramEnvironm send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); } - handle_battles_and_back_to_pokecenter(env, context, + handle_battles_and_back_to_pokecenter( + env, context, [this, &path_id, &hp_watcher](SingleSwitchProgramEnvironment& env, ProControllerContext& context){ run_until( env.console, context, diff --git a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.h b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.h index 4b29bb9721..b2e5653b0c 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.h +++ b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.h @@ -9,11 +9,11 @@ #include #include "Common/Cpp/Options/FloatingPointOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" #include "CommonFramework/Notifications/EventNotificationsTable.h" #include "CommonTools/Options/LanguageOCROption.h" #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldSensors.h" #include "PokemonSV/Options/PokemonSV_EncounterBotCommon.h" #include "PokemonSV/Options/PokemonSV_SandwichMakerOption.h" @@ -41,12 +41,19 @@ class ShinyHuntScatterbug : public SingleSwitchProgramInstance{ virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; private: - void run_one_sandwich_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void run_one_sandwich_iteration( + SingleSwitchProgramEnvironment& env, ProControllerContext& context + ); - void run_lets_go_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context, size_t path_id); + void run_lets_go_iteration( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + size_t path_id + ); - void handle_battles_and_back_to_pokecenter(SingleSwitchProgramEnvironment& env, ProControllerContext& context, - std::function&& action); + void handle_battles_and_back_to_pokecenter( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + std::function&& action + ); BooleanCheckBoxOption SAVE_GAME_AT_START; @@ -67,6 +74,8 @@ class ShinyHuntScatterbug : public SingleSwitchProgramInstance{ EventNotificationOption NOTIFICATION_STATUS_UPDATE; EventNotificationsOption NOTIFICATIONS; + OverworldSensors* m_sensors; + OverworldBattleTracker* m_battle_tracker; LetsGoEncounterBotTracker* m_encounter_tracker; // Set to true if we should save on the first available opportunity. diff --git a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHost.cpp b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHost.cpp index a69ac7e60e..6d695e2b67 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHost.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHost.cpp @@ -134,7 +134,7 @@ WallClock AutoHost::wait_for_lobby_open( ){ VideoOverlaySet overlays(env.console.overlay()); - TeraLobbyWatcher lobby(env.logger(), env.normal_inference_dispatcher(), COLOR_RED); + TeraLobbyWatcher lobby(env.logger(), COLOR_RED); lobby.make_overlays(overlays); int ret = wait_until( @@ -153,8 +153,8 @@ WallClock AutoHost::wait_for_lobby_open( context.wait_for(std::chrono::seconds(1)); VideoSnapshot snapshot = env.console.video().snapshot(); - lobby_code = lobby.raid_code(env.logger(), env.normal_inference_dispatcher(), snapshot); - std::string code = lobby.raid_code(env.logger(), env.normal_inference_dispatcher(), snapshot); + lobby_code = lobby.raid_code(env.logger(), snapshot); + std::string code = lobby.raid_code(env.logger(), snapshot); normalize_code(lobby_code, code); send_host_announcement( diff --git a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostLobbyWaiter.cpp b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostLobbyWaiter.cpp index cfe7b93219..8964374e52 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostLobbyWaiter.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostLobbyWaiter.cpp @@ -40,8 +40,8 @@ TeraLobbyWaiter::TeraLobbyWaiter( , m_notification_raid_start(NOTIFICATION_RAID_START) , m_dialog(COLOR_YELLOW) , m_start_raid(COLOR_BLUE) - , m_join_watcher(stream.logger(), env.normal_inference_dispatcher(), COLOR_RED, host_players) - , m_name_watcher(stream.logger(), env.normal_inference_dispatcher(), COLOR_RED, JOIN_REPORT, BAN_LIST, host_players) + , m_join_watcher(stream.logger(), COLOR_RED, host_players) + , m_name_watcher(stream.logger(), COLOR_RED, JOIN_REPORT, BAN_LIST, host_players) {} VideoSnapshot TeraLobbyWaiter::synchronize_state(){ diff --git a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_JoinTracker.cpp b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_JoinTracker.cpp index 772e7d208f..2c617d245c 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_JoinTracker.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_JoinTracker.cpp @@ -318,10 +318,10 @@ void MultiLanguageJoinTracker::dump(const std::string& filename) const{ TeraLobbyJoinWatcher2::TeraLobbyJoinWatcher2( - Logger& logger, AsyncDispatcher& dispatcher, Color color, + Logger& logger, Color color, uint8_t host_players ) - : TeraLobbyReader(logger, dispatcher, color) + : TeraLobbyReader(logger, color) , VisualInferenceCallback("TeraLobbyJoinWatcher2") , m_host_players(host_players) {} @@ -346,13 +346,13 @@ bool TeraLobbyJoinWatcher2::process_frame(const ImageViewRGB32& frame, WallClock TeraLobbyNameWatcher::TeraLobbyNameWatcher( - Logger& logger, AsyncDispatcher& dispatcher, + Logger& logger, Color color, RaidJoinReportOption& report_settings, RaidPlayerBanList& ban_settings, uint8_t host_players ) - : TeraLobbyReader(logger, dispatcher, color) + : TeraLobbyReader(logger, color) , VisualInferenceCallback("TeraLobbyNameWatcher") , m_logger(logger) , m_report_settings(report_settings) diff --git a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_JoinTracker.h b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_JoinTracker.h index daeb9ff7ab..d278c1e567 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_JoinTracker.h +++ b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_JoinTracker.h @@ -99,7 +99,7 @@ class MultiLanguageJoinTracker{ class TeraLobbyJoinWatcher2 : public TeraLobbyReader, public VisualInferenceCallback{ public: TeraLobbyJoinWatcher2( - Logger& logger, AsyncDispatcher& dispatcher, Color color, + Logger& logger, Color color, uint8_t host_players ); @@ -121,7 +121,7 @@ class TeraLobbyJoinWatcher2 : public TeraLobbyReader, public VisualInferenceCall class TeraLobbyNameWatcher : public TeraLobbyReader, public VisualInferenceCallback{ public: TeraLobbyNameWatcher( - Logger& logger, AsyncDispatcher& dispatcher, Color color, + Logger& logger, Color color, RaidJoinReportOption& report_settings, RaidPlayerBanList& ban_settings, uint8_t host_players diff --git a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraMultiFarmer.cpp b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraMultiFarmer.cpp index 43666908b8..13cb121762 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraMultiFarmer.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraMultiFarmer.cpp @@ -344,7 +344,7 @@ void TeraMultiFarmer::join_lobby( } CodeEntryWatcher code_entry(COLOR_GREEN); - TeraLobbyWatcher lobby(console.logger(), env.normal_inference_dispatcher(), COLOR_RED); + TeraLobbyWatcher lobby(console.logger(), COLOR_RED); AdvanceDialogWatcher dialog(COLOR_YELLOW); TeraRaidSearchWatcher raid_search(COLOR_CYAN, std::chrono::seconds(5)); context.wait_for_all_requests(); @@ -452,7 +452,7 @@ bool TeraMultiFarmer::run_raid( // Open lobby and read code. WallClock lobby_start_time; try{ - TeraLobbyReader lobby_reader(host_console.logger(), env.normal_inference_dispatcher()); + TeraLobbyReader lobby_reader(host_console.logger()); open_hosting_lobby( env, host_console, host_context, HOSTING_MODE == Mode::HOST_ONLINE @@ -462,7 +462,6 @@ bool TeraMultiFarmer::run_raid( lobby_start_time = current_time(); std::string code = lobby_reader.raid_code( env.logger(), - env.normal_inference_dispatcher(), host_console.video().snapshot() ); diff --git a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.cpp b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.cpp index cc44a732be..6831d98dd4 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.cpp @@ -145,7 +145,7 @@ void open_hosting_lobby( // AdvanceDialogWatcher dialog(COLOR_GREEN); TeraCardWatcher card_detector(COLOR_YELLOW); - TeraLobbyWatcher lobby(stream.logger(), env.normal_inference_dispatcher(), COLOR_BLUE); + TeraLobbyWatcher lobby(stream.logger(), COLOR_BLUE); context.wait_for_all_requests(); int ret = wait_until( stream, context, @@ -685,13 +685,22 @@ void run_from_tera_battle(const ProgramInfo& info, VideoStream& stream, ProContr } TeraBattleMenuWatcher battle_menu(COLOR_GREEN); + GradientArrowWatcher leave_confirm( + COLOR_RED, + GradientArrowType::RIGHT, + {0.557621, 0.471074, 0.388476, 0.247934} + ); OverworldWatcher overworld(stream.logger(), COLOR_CYAN); context.wait_for_all_requests(); int ret = wait_until( stream, context, std::chrono::minutes(1), - {battle_menu, overworld} + { + battle_menu, + leave_confirm, + overworld, + } ); context.wait_for(std::chrono::milliseconds(100)); @@ -700,9 +709,13 @@ void run_from_tera_battle(const ProgramInfo& info, VideoStream& stream, ProContr stream.log("Detected tera raid battle menu, running away..."); stream.overlay().add_log("Running away...", COLOR_WHITE); battle_menu.move_to_slot(stream, context, 2); - pbf_mash_button(context, BUTTON_A, 800); + pbf_press_button(context, BUTTON_A, 160ms, 80ms); continue; case 1: + stream.log("Detected leave confirm."); + pbf_press_button(context, BUTTON_A, 160ms, 80ms); + continue; + case 2: stream.log("Detected overworld."); return; default: diff --git a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.cpp b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.cpp index 2a43583099..5f49a45fd9 100644 --- a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.cpp @@ -32,12 +32,12 @@ void connect_to_internet( // Move the cursor as far away from Link Trade and Surprise Trade as possible. // This is added safety in case connect to internet takes too long. - ssf_issue_scroll(context, SSF_SCROLL_UP, 5); - ssf_issue_scroll(context, SSF_SCROLL_UP, 5); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 5); + ssf_issue_scroll(context, SSF_SCROLL_UP, 40ms, 40ms, 40ms); + ssf_issue_scroll(context, SSF_SCROLL_UP, 40ms, 40ms, 40ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 40ms, 40ms, 40ms); // Connect to internet. - ssf_press_button(context, BUTTON_PLUS, 3); + ssf_press_button(context, BUTTON_PLUS, 24ms); // Mash B to get out of YCOMM. ssf_mash1_button(context, BUTTON_B, connect_to_internet_delay); diff --git a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.cpp b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.cpp index 7d531ce069..bd72c9c9c4 100644 --- a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.cpp @@ -119,23 +119,23 @@ void touch_date_from_home_switch2( home_to_date_time(console, context, true); ssf_press_button(context, BUTTON_A, 216ms, 80ms); - ssf_issue_scroll(context, SSF_SCROLL_UP, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); ssf_press_button(context, BUTTON_A, 264ms, 80ms); ssf_press_button(context, BUTTON_A, 216ms, 80ms); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); ssf_press_button(context, BUTTON_A, 264ms, 80ms); ssf_press_button(context, BUTTON_HOME, settings_to_home_delay, 80ms); @@ -144,7 +144,7 @@ void touch_date_from_home( ConsoleHandle& console, ProControllerContext& context, Milliseconds settings_to_home_delay ){ - wait_for_home(console, context); + ensure_at_home(console, context); ConsoleType type = console.state().console_type(); @@ -194,16 +194,19 @@ void rollback_hours_from_home_switch2( ){ home_to_date_time(console, context, true); + Milliseconds tv = context->timing_variation(); + Milliseconds unit = 24ms + tv; + ssf_press_button(context, BUTTON_A, 216ms, 80ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); for (uint8_t c = 0; c < hours; c++){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 112ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 112ms + tv, 2*unit, unit); } - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); ssf_press_button(context, BUTTON_A, 264ms, 80ms); ssf_press_button(context, BUTTON_HOME, settings_to_home_delay, 80ms); @@ -215,7 +218,7 @@ void rollback_hours_from_home( uint8_t hours, Milliseconds settings_to_home_delay ){ - wait_for_home(console, context); + ensure_at_home(console, context); ConsoleType type = console.state().console_type(); diff --git a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.cpp b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.cpp index 5e8a24b802..ce95d41c21 100644 --- a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.cpp @@ -16,9 +16,9 @@ namespace NintendoSwitch{ void eggfetcher_loop(ProControllerContext& context){ ssf_press_left_joystick(context, STICK_MAX, STICK_MAX, 50, 50); ssf_press_left_joystick(context, STICK_MAX, 160, 0, 510); - ssf_press_button(context, BUTTON_A, 170); - ssf_press_button(context, BUTTON_A, 170); - ssf_press_button(context, BUTTON_A, 170); + ssf_press_button(context, BUTTON_A, 1360ms); + ssf_press_button(context, BUTTON_A, 1360ms); + ssf_press_button(context, BUTTON_A, 1360ms); ssf_press_left_joystick(context, STICK_MIN, STICK_CENTER, 50, 390); ssf_mash1_button(context, BUTTON_B, 90); ssf_do_nothing(context, 300); @@ -54,8 +54,8 @@ void spin_and_mash_A(ProControllerContext& context, Milliseconds duration){ } void travel_to_spin_location(ProControllerContext& context){ ssf_press_left_joystick(context, STICK_MAX, 144, 100, 250); - ssf_press_button(context, BUTTON_A, 100); - ssf_press_button(context, BUTTON_A, 50); + ssf_press_button(context, BUTTON_A, 800ms); + ssf_press_button(context, BUTTON_A, 400ms); ssf_press_left_joystick(context, STICK_MAX, STICK_MAX, 50, 50); } void travel_back_to_lady(ProControllerContext& context){ diff --git a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.cpp b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.cpp index 4d779634fe..281c54a9bb 100644 --- a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.cpp @@ -105,17 +105,17 @@ void settings_to_enter_game_den_lobby( // home home // ssf_press_button2(BUTTON_HOME, 100, 10); // lobby-switch update-yes - ssf_press_dpad(context, DPAD_DOWN, 10); - ssf_press_dpad(context, DPAD_UP, 10); + ssf_press_dpad(context, DPAD_DOWN, 80ms); + ssf_press_dpad(context, DPAD_UP, 80ms); // lobby-switch update-start ssf_press_button(context, BUTTON_A, enter_switch_pokemon_delay, 80ms); // lobby-select lobby-switch - ssf_press_dpad(context, DPAD_LEFT, 10); + ssf_press_dpad(context, DPAD_LEFT, 80ms); // lobby-select lobby-switch ssf_press_button(context, BUTTON_A, enter_switch_pokemon_delay); // lobby-confirm lobby-select - ssf_press_button(context, BUTTON_Y, 10); - ssf_press_dpad(context, DPAD_LEFT, 10); + ssf_press_button(context, BUTTON_Y, 80ms); + ssf_press_dpad(context, DPAD_LEFT, 80ms); // lobby-confirm lobby-select ssf_press_button(context, BUTTON_A, exit_switch_pokemon_delay); // lobby-switch lobby-switch diff --git a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_Misc.cpp b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_Misc.cpp index 98ef6157d3..bc1f0f8277 100644 --- a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_Misc.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_Misc.cpp @@ -16,9 +16,9 @@ void IoA_backout(ProControllerContext& context, Milliseconds pokemon_to_menu_del // Back out to menu. // Prepend each B press by a DOWN press so that the B gets // swallowed while in the summary. - ssf_press_dpad(context, DPAD_DOWN, 5, 15); - ssf_press_button(context, BUTTON_B, 60, 10); - ssf_press_dpad(context, DPAD_DOWN, 5, 15); + ssf_press_dpad(context, DPAD_DOWN, 40ms, 120ms); + ssf_press_button(context, BUTTON_B, 480ms, 80ms); + ssf_press_dpad(context, DPAD_DOWN, 40ms, 120ms); ssf_press_button(context, BUTTON_B, pokemon_to_menu_delay, 80ms); } diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinySparkleSet.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinySparkleSet.cpp index f8ab279659..ba9f9326bd 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinySparkleSet.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinySparkleSet.cpp @@ -5,7 +5,9 @@ */ #include +#include "Common/Cpp/Concurrency/SpinLock.h" #include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonFramework/Tools/GlobalThreadPools.h" #include "CommonTools/Images/BinaryImage_FilterRgb32.h" #include "PokemonSwSh/PokemonSwSh_Settings.h" #include "PokemonSwSh_SparkleDetectorRadial.h" @@ -124,6 +126,27 @@ void ShinySparkleSetSwSh::read_from_image(size_t screen_area, const ImageViewRGB {0xffd0d000, 0xffffffff}, } ); + + SpinLock lock; + double best_alpha = 0; + GlobalThreadPools::realtime_inference().run_in_parallel( + [&](size_t index){ + auto session = make_WaterfillSession(); + session->set_source(matrices[index]); + ShinySparkleSetSwSh sparkles = find_sparkles(screen_area, *session); + sparkles.update_alphas(); + double alpha = sparkles.alpha_overall(); + + WriteSpinLock lg(lock); + if (best_alpha < alpha){ + best_alpha = alpha; + *this = std::move(sparkles); + } + }, + 0, matrices.size(), 1 + ); + +#if 0 auto session = make_WaterfillSession(); double best_alpha = 0; @@ -137,6 +160,7 @@ void ShinySparkleSetSwSh::read_from_image(size_t screen_area, const ImageViewRGB *this = std::move(sparkles); } } +#endif } diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.cpp index d3296b3bb6..41fb6ad25a 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.cpp @@ -98,6 +98,7 @@ PathSelectDetector::PathSelectDetector() , m_dialog_middle(0.500, 0.880, 0.180, 0.050) // , m_dialog_right(0.710, 0.880, 0.030, 0.050) , m_left(0.050, 0.100, 0.200, 0.700) + , m_path_box(0.150, 0.020, 0.800, 0.780) {} void PathSelectDetector::make_overlays(VideoOverlaySet& items) const{ items.add(COLOR_CYAN, m_bottom_right); @@ -147,6 +148,14 @@ bool PathSelectDetector::detect(const ImageViewRGB32& screen) const{ // if (dialog_right.average.sum() > dialog_middle.average.sum()){ // return false; // } + + ImageViewRGB32 path_box = extract_box_reference(screen, m_path_box); + if (read_side(path_box) < 0){ +// cout << "PathSelectDetector(): read_side(screen) < 0" << endl; + return false; + } + +// cout << "PathSelectDetector(): Passed" << endl; return true; } bool PathSelectDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ @@ -168,8 +177,7 @@ bool PathSelectDetector::process_frame(const ImageViewRGB32& frame, WallClock ti PathReader::PathReader(VideoOverlay& overlay, size_t player_index) - : m_player_index(player_index) - , m_path(overlay, {0.150, 0.020, 0.800, 0.780}) + : m_path(overlay, {0.150, 0.020, 0.800, 0.780}) , m_sprite0(overlay, {0.002, 0.345 + 0*0.16315, 0.071, 0.102}) , m_sprite1(overlay, {0.002, 0.345 + 1*0.16315, 0.071, 0.102}) , m_sprite2(overlay, {0.002, 0.345 + 2*0.16315, 0.071, 0.102}) diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h index b76a50dd0d..4a0c404c4d 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h @@ -56,6 +56,7 @@ class PathSelectDetector : public PathScreenDetector{ ImageFloatBox m_dialog_middle; // ImageFloatBox m_dialog_right; ImageFloatBox m_left; + ImageFloatBox m_path_box; }; @@ -99,10 +100,8 @@ class PathReader{ void read_sprites(Logger& logger, const ImageViewRGB32& screen, std::string slugs[4]) const; void read_hp(Logger& logger, const ImageViewRGB32& screen, double hp[4]) const; - static int8_t read_side(const ImageViewRGB32& image, int p_min_rgb_sum); - private: - size_t m_player_index; +// size_t m_player_index; OverlayBoxScope m_path; OverlayBoxScope m_sprite0; OverlayBoxScope m_sprite1; diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSide.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSide.cpp index 00a4908ab3..fcdba0d9b7 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSide.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSide.cpp @@ -325,15 +325,19 @@ int8_t read_side(WaterfillSession& session, const ImageViewRGB32& image, uint8_t // cout << "pixel_threshold = " << (int)pixel_threshold << endl; session.set_source(matrix); - auto finder = session.make_iterator(300); + size_t min_area = image.total_pixels(); + min_area = (size_t)((double)300 * min_area / 1293312); + + auto finder = session.make_iterator(min_area); WaterfillObject arrow; WaterfillObject object; size_t count = 0; while (finder->find_next(object, true)){ - if (is_arrow(image, object)){ - count++; - arrow = object; + if (!is_arrow(image, object)){ + continue; } + count++; + arrow = object; } // cout << "count = " << count << endl; if (count != 1){ @@ -348,6 +352,7 @@ int8_t read_side(WaterfillSession& session, const ImageViewRGB32& image, uint8_t } int8_t read_side(const ImageViewRGB32& image){ +// cout << image.width() * image.height() << endl; auto session = make_WaterfillSession(); int8_t ret; if ((ret = read_side(*session, image, 160)) != -1) return ret; diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Consoles.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Consoles.cpp index 0b205ff98c..cd8db35d2f 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Consoles.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Consoles.cpp @@ -65,7 +65,8 @@ CaughtScreenActionsOption::CaughtScreenActionsOption( "Boss/Legendary is Shiny:
If there are multiple shinies where one is the boss, this option still applies.

" "For safety reasons, this program will NEVER automatically take a boss. " "Likewise, the settings here are intentionally worded so that it's impossible to ask the program to take a boss. " - "Because taking a boss is irreversible, we refuse to automate it and require you to do it manually to avoid any mistakes.", + "Taking a boss is irreversible, therefore we refuse to automate it. We require you to do it manually to avoid any mistakes.

" + "Please DO NOT ask us to implement the ability to automatically take a boss. Thank you.", default_shiny_boss ) , description( diff --git a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_BallSelectOption.cpp b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_BallSelectOption.cpp index 07ab046b64..5fcdf6cec7 100644 --- a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_BallSelectOption.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_BallSelectOption.cpp @@ -26,11 +26,11 @@ StringSelectDatabase make_all_balls_database(){ // cout << "slug = " << slug << endl; const PokeballNames& data = get_pokeball_name(slug); const SpriteDatabase::Sprite* sprite = ALL_POKEBALL_SPRITES().get_nothrow(slug); - if (sprite == nullptr){ - ret.add_entry(StringSelectEntry(slug, data.display_name())); - global_logger_tagged().log("Missing sprite for: " + slug, COLOR_RED); - }else{ + if (sprite != nullptr){ ret.add_entry(StringSelectEntry(slug, data.display_name(), sprite->icon)); + }else{ +// ret.add_entry(StringSelectEntry(slug, data.display_name())); +// global_logger_tagged().log("Missing sprite for: " + slug, COLOR_RED); } } return ret; diff --git a/SerialPrograms/Source/PokemonSwSh/PokemonSwSh_Panels.cpp b/SerialPrograms/Source/PokemonSwSh/PokemonSwSh_Panels.cpp index b70948dfe2..02eea1fc5c 100644 --- a/SerialPrograms/Source/PokemonSwSh/PokemonSwSh_Panels.cpp +++ b/SerialPrograms/Source/PokemonSwSh/PokemonSwSh_Panels.cpp @@ -116,7 +116,6 @@ std::vector PanelListFactory::make_panels() const{ ret.emplace_back(make_single_switch_program()); ret.emplace_back(make_single_switch_program()); ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); ret.emplace_back(make_single_switch_program()); ret.emplace_back(make_single_switch_program()); ret.emplace_back(make_single_switch_program()); @@ -191,6 +190,7 @@ std::vector PanelListFactory::make_panels() const{ ret.emplace_back(make_multi_switch_program()); ret.emplace_back("---- Deprecated Programs ----"); + ret.emplace_back(make_single_switch_program()); ret.emplace_back(make_single_switch_program()); ret.emplace_back(make_single_switch_program()); ret.emplace_back(make_single_switch_program()); diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattTraderFarmer.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattTraderFarmer.cpp index 62e78e34bb..38cfadbce1 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattTraderFarmer.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattTraderFarmer.cpp @@ -1,194 +1,194 @@ -/* Watt Trader Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh/Inference/PokemonSwSh_DialogTriangleDetector.h" -#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" -#include "PokemonSwSh_DateSpam-WattTraderFarmer.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -WattTraderFarmer_Descriptor::WattTraderFarmer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:WattTraderFarmer", - STRING_POKEMON + " SwSh", "Date Spam - Watt Trader Farmer", - "", - "Buy as much stuff from a watt trader as possible - day skipping as needed to reroll items.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER - ) -{} - -class WattTraderFarmer_Descriptor::Stats : public StatsTracker{ -public: - Stats() - : day_skips(m_stats["Day Skips"]) - , items_probed(m_stats["Items Probed"]) - , failed(m_stats["Failed"]) - , success(m_stats["Success"]) - , errors(m_stats["Errors"]) - { - m_display_order.insert(m_display_order.begin() + 0, Stat("Day Skips")); - m_display_order.insert(m_display_order.begin() + 1, Stat("Items Probed")); - m_display_order.insert(m_display_order.begin() + 2, Stat("Failed")); - m_display_order.insert(m_display_order.begin() + 3, Stat("Success")); - m_display_order.insert(m_display_order.begin() + 4, Stat("Errors")); - } - -public: - std::atomic& day_skips; - std::atomic& items_probed; - std::atomic& failed; - std::atomic& success; - std::atomic& errors; -}; -std::unique_ptr WattTraderFarmer_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -WattTraderFarmer::WattTraderFarmer(){ - -} - - - -class BuyCursorDetector : public SelectionArrowFinder{ -public: - BuyCursorDetector(VideoOverlay& overlay) - : SelectionArrowFinder(overlay, ImageFloatBox(0.448775, 0.087129, 0.062361, 0.596040)) - {} -}; -class BuyQuantityDetector : public VisualInferenceCallback{ -public: - BuyQuantityDetector() - : VisualInferenceCallback("BuyQuantityDetector") - , m_box(0.814031, 0.681188, 0.170379, 0.045545) - {} - virtual void make_overlays(VideoOverlaySet& items) const override{ - items.add(COLOR_GREEN, m_box); - } - virtual bool process_frame(const VideoSnapshot& frame) override{ - ImageStats stats = image_stats(extract_box_reference(frame, m_box)); - return is_solid(stats, {0.62963, 0.37037, 0.}); - } - -private: - ImageFloatBox m_box; -}; - - - -void WattTraderFarmer::buy_one(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - WattTraderFarmer_Descriptor::Stats& stats = env.current_stats(); - - bool purchased = false; - while (true){ - DialogTriangleDetector dialog(env.logger(), env.console, true); - BuyCursorDetector item_select(env.console); - BuyQuantityDetector quantity; - context.wait_for_all_requests(); - int ret = wait_until( - env.console, context, - std::chrono::seconds(10), - { - dialog, - item_select, - quantity, - } - ); - context.wait_for(200ms); - switch (ret){ - case 0: - env.log("Detected dialog...", COLOR_BLUE); - if (!purchased){ - stats.failed++; - env.update_stats(); - } - pbf_press_button(context, BUTTON_B, 200ms, 800ms); - return; - case 1: - env.log("Detected item select...", COLOR_BLUE); - if (purchased){ - return; - } - pbf_press_button(context, BUTTON_A, 200ms, 800ms); - continue; - case 2: - env.log("Detected quantity select...", COLOR_BLUE); - stats.success++; - env.update_stats(); - pbf_press_dpad(context, DPAD_DOWN, 200ms, 800ms); - pbf_press_button(context, BUTTON_A, 200ms, 800ms); - pbf_press_button(context, BUTTON_A, 200ms, 800ms); - purchased = true; - continue; - default: - env.log("No recognized state after 5 seconds.", COLOR_RED); - stats.errors++; - env.update_stats(); - pbf_mash_button(context, BUTTON_B, 5000ms); - pbf_press_button(context, BUTTON_A, 200ms, 800ms); - pbf_press_button(context, BUTTON_A, 200ms, 800ms); - continue; - } - } -} - - - -void WattTraderFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - WattTraderFarmer_Descriptor::Stats& stats = env.current_stats(); - - uint8_t year = MAX_YEAR; - while (true){ - pbf_press_button(context, BUTTON_A, 200ms, 800ms); - pbf_press_button(context, BUTTON_A, 200ms, 800ms); - - for (size_t c = 0; c < 7; c++){ - buy_one(env, context); - stats.items_probed++; - env.update_stats(); - pbf_press_dpad(context, DPAD_DOWN, 200ms, 200ms); - } - - pbf_mash_button(context, BUTTON_B, 5000ms); - - // Tap HOME and quickly spam B. The B spamming ensures that we don't - // accidentally update the system if the system update window pops up. - ssf_press_button(context, BUTTON_HOME, 120ms, 160ms); - pbf_mash_button(context, BUTTON_B, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0.get() - 120ms); - - home_roll_date_enter_game_autorollback(env.console, context, year); - pbf_mash_button(context, BUTTON_B, 90); - stats.day_skips++; - env.update_stats(); - } -} - - - - - -} -} -} +/* Watt Trader Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh/Inference/PokemonSwSh_DialogTriangleDetector.h" +#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" +#include "PokemonSwSh_DateSpam-WattTraderFarmer.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +WattTraderFarmer_Descriptor::WattTraderFarmer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:WattTraderFarmer", + STRING_POKEMON + " SwSh", "Date Spam - Watt Trader Farmer", + "", + "Buy as much stuff from a watt trader as possible - day skipping as needed to reroll items.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER + ) +{} + +class WattTraderFarmer_Descriptor::Stats : public StatsTracker{ +public: + Stats() + : day_skips(m_stats["Day Skips"]) + , items_probed(m_stats["Items Probed"]) + , failed(m_stats["Failed"]) + , success(m_stats["Success"]) + , errors(m_stats["Errors"]) + { + m_display_order.insert(m_display_order.begin() + 0, Stat("Day Skips")); + m_display_order.insert(m_display_order.begin() + 1, Stat("Items Probed")); + m_display_order.insert(m_display_order.begin() + 2, Stat("Failed")); + m_display_order.insert(m_display_order.begin() + 3, Stat("Success")); + m_display_order.insert(m_display_order.begin() + 4, Stat("Errors")); + } + +public: + std::atomic& day_skips; + std::atomic& items_probed; + std::atomic& failed; + std::atomic& success; + std::atomic& errors; +}; +std::unique_ptr WattTraderFarmer_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +WattTraderFarmer::WattTraderFarmer(){ + +} + + + +class BuyCursorDetector : public SelectionArrowFinder{ +public: + BuyCursorDetector(VideoOverlay& overlay) + : SelectionArrowFinder(overlay, ImageFloatBox(0.448775, 0.087129, 0.062361, 0.596040)) + {} +}; +class BuyQuantityDetector : public VisualInferenceCallback{ +public: + BuyQuantityDetector() + : VisualInferenceCallback("BuyQuantityDetector") + , m_box(0.814031, 0.681188, 0.170379, 0.045545) + {} + virtual void make_overlays(VideoOverlaySet& items) const override{ + items.add(COLOR_GREEN, m_box); + } + virtual bool process_frame(const VideoSnapshot& frame) override{ + ImageStats stats = image_stats(extract_box_reference(frame, m_box)); + return is_solid(stats, {0.62963, 0.37037, 0.}); + } + +private: + ImageFloatBox m_box; +}; + + + +void WattTraderFarmer::buy_one(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + WattTraderFarmer_Descriptor::Stats& stats = env.current_stats(); + + bool purchased = false; + while (true){ + DialogTriangleDetector dialog(env.logger(), env.console, true); + BuyCursorDetector item_select(env.console); + BuyQuantityDetector quantity; + context.wait_for_all_requests(); + int ret = wait_until( + env.console, context, + std::chrono::seconds(10), + { + dialog, + item_select, + quantity, + } + ); + context.wait_for(200ms); + switch (ret){ + case 0: + env.log("Detected dialog...", COLOR_BLUE); + if (!purchased){ + stats.failed++; + env.update_stats(); + } + pbf_press_button(context, BUTTON_B, 200ms, 800ms); + return; + case 1: + env.log("Detected item select...", COLOR_BLUE); + if (purchased){ + return; + } + pbf_press_button(context, BUTTON_A, 200ms, 800ms); + continue; + case 2: + env.log("Detected quantity select...", COLOR_BLUE); + stats.success++; + env.update_stats(); + pbf_press_dpad(context, DPAD_DOWN, 200ms, 800ms); + pbf_press_button(context, BUTTON_A, 200ms, 800ms); + pbf_press_button(context, BUTTON_A, 200ms, 800ms); + purchased = true; + continue; + default: + env.log("No recognized state after 5 seconds.", COLOR_RED); + stats.errors++; + env.update_stats(); + pbf_mash_button(context, BUTTON_B, 5000ms); + pbf_press_button(context, BUTTON_A, 200ms, 800ms); + pbf_press_button(context, BUTTON_A, 200ms, 800ms); + continue; + } + } +} + + + +void WattTraderFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + WattTraderFarmer_Descriptor::Stats& stats = env.current_stats(); + + uint8_t year = MAX_YEAR; + while (true){ + pbf_press_button(context, BUTTON_A, 200ms, 800ms); + pbf_press_button(context, BUTTON_A, 200ms, 800ms); + + for (size_t c = 0; c < 7; c++){ + buy_one(env, context); + stats.items_probed++; + env.update_stats(); + pbf_press_dpad(context, DPAD_DOWN, 200ms, 200ms); + } + + pbf_mash_button(context, BUTTON_B, 5000ms); + + // Tap HOME and quickly spam B. The B spamming ensures that we don't + // accidentally update the system if the system update window pops up. + ssf_press_button(context, BUTTON_HOME, 120ms, 160ms); + pbf_mash_button(context, BUTTON_B, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0.get() - 120ms); + + home_roll_date_enter_game_autorollback(env.console, context, year); + pbf_mash_button(context, BUTTON_B, 90); + stats.day_skips++; + env.update_stats(); + } +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattTraderFarmer.h b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattTraderFarmer.h index 5ec1db3b76..11727252c3 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattTraderFarmer.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattTraderFarmer.h @@ -1,47 +1,47 @@ -/* Watt Trader Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_WattTraderFarmer_H -#define PokemonAutomation_PokemonSwSh_WattTraderFarmer_H - -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class WattTraderFarmer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - WattTraderFarmer_Descriptor(); - - class Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class WattTraderFarmer : public SingleSwitchProgramInstance{ -public: - WattTraderFarmer(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void buy_one(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - - -}; - - - -} -} -} -#endif - - - +/* Watt Trader Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_WattTraderFarmer_H +#define PokemonAutomation_PokemonSwSh_WattTraderFarmer_H + +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class WattTraderFarmer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + WattTraderFarmer_Descriptor(); + + class Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class WattTraderFarmer : public SingleSwitchProgramInstance{ +public: + WattTraderFarmer(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void buy_one(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + + +}; + + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_BeamReset.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_BeamReset.cpp index c9c7519f15..a32ae10986 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_BeamReset.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_BeamReset.cpp @@ -26,7 +26,9 @@ BeamReset_Descriptor::BeamReset_Descriptor() "Reset a beam until you see a purple beam.", FeedbackType::NONE, AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS}, + FasterIfTickPrecise::NOT_FASTER, + true ) {} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperEU.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperEU.cpp index 8febcd0ace..fe1cb5daa3 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperEU.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperEU.cpp @@ -82,7 +82,7 @@ DaySkipperEU::DaySkipperEU() void DaySkipperEU::run_switch1(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ using namespace DateSkippers::Switch1; - bool needs_inference = context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired_125Hz; + bool needs_inference = context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired; SkipperStats& stats = env.current_stats(); stats.total_skips = SKIPS; @@ -143,13 +143,13 @@ void DaySkipperEU::run_switch1(SingleSwitchProgramEnvironment& env, ProControlle pbf_wait(context, 15 * TICKS_PER_SECOND); while (true){ - ssf_press_button1(context, BUTTON_A, 15 * TICKS_PER_SECOND); + ssf_press_button(context, BUTTON_A, 15000ms); } } void DaySkipperEU::run_switch2(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ using namespace DateSkippers::Switch2; - if (context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired_125Hz){ + if (context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired){ throw UserSetupError( env.logger(), "This program requires a tick precise wired controller." diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN-7.8k.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN-7.8k.cpp index 5acd37df1b..ae9db584b3 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN-7.8k.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN-7.8k.cpp @@ -155,7 +155,7 @@ void DaySkipperJPN7p8k::program(SingleSwitchProgramEnvironment& env, ProControll "This program only works on the Switch 1." ); } - if (context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired_125Hz){ + if (context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired){ throw UserSetupError( env.logger(), "This program requires a tick precise wired controller." @@ -219,7 +219,7 @@ void DaySkipperJPN7p8k::program(SingleSwitchProgramEnvironment& env, ProControll pbf_wait(context, 15 * TICKS_PER_SECOND); while (true){ - ssf_press_button1(context, BUTTON_A, 15 * TICKS_PER_SECOND); + ssf_press_button(context, BUTTON_A, 15000ms); } } diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN.cpp index f0a1eda0e4..7c94629394 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN.cpp @@ -75,7 +75,7 @@ DaySkipperJPN::DaySkipperJPN() void DaySkipperJPN::run_switch1(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ using namespace DateSkippers::Switch1; - bool needs_inference = context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired_125Hz; + bool needs_inference = context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired; SkipperStats& stats = env.current_stats(); stats.total_skips = SKIPS; @@ -124,13 +124,13 @@ void DaySkipperJPN::run_switch1(SingleSwitchProgramEnvironment& env, ProControll pbf_wait(context, 15 * TICKS_PER_SECOND); while (true){ - ssf_press_button1(context, BUTTON_A, 15 * TICKS_PER_SECOND); + ssf_press_button(context, BUTTON_A, 15000ms); } } void DaySkipperJPN::run_switch2(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ using namespace DateSkippers::Switch2; - if (context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired_125Hz){ + if (context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired){ throw UserSetupError( env.logger(), "This program requires a tick precise wired controller." diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperUS.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperUS.cpp index bdefe5058d..553ea236d3 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperUS.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperUS.cpp @@ -81,7 +81,7 @@ DaySkipperUS::DaySkipperUS() void DaySkipperUS::run_switch1(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ using namespace DateSkippers::Switch1; - bool needs_inference = context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired_125Hz; + bool needs_inference = context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired; SkipperStats& stats = env.current_stats(); stats.total_skips = SKIPS; @@ -142,13 +142,13 @@ void DaySkipperUS::run_switch1(SingleSwitchProgramEnvironment& env, ProControlle pbf_wait(context, 15 * TICKS_PER_SECOND); while (true){ - ssf_press_button1(context, BUTTON_A, 15 * TICKS_PER_SECOND); + ssf_press_button(context, BUTTON_A, 15000ms); } } void DaySkipperUS::run_switch2(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ using namespace DateSkippers::Switch2; - if (context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired_125Hz){ + if (context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired){ throw UserSetupError( env.logger(), "This program requires a tick precise wired controller." diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_EventBeamFinder.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_EventBeamFinder.cpp index 33d9a762f5..42a59ba057 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_EventBeamFinder.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_EventBeamFinder.cpp @@ -46,27 +46,27 @@ EventBeamFinder::EventBeamFinder() void EventBeamFinder::goto_near_den(ProControllerContext& context) const{ - ssf_hold_joystick1(context, true, STICK_CENTER, STICK_MIN, 375); + ssf_press_left_joystick(context, STICK_CENTER, STICK_MIN, 375, 375); pbf_wait(context, 50); - ssf_press_button1(context, BUTTON_PLUS, 100); - ssf_press_joystick2(context, true, STICK_MAX, STICK_CENTER, 100, 5); - ssf_press_button1(context, BUTTON_L, 100); - ssf_press_button1(context, BUTTON_PLUS, 100); - ssf_hold_joystick1(context, true, STICK_CENTER, STICK_MIN, 370); + ssf_press_button(context, BUTTON_PLUS, 800ms); + ssf_press_left_joystick(context, STICK_MAX, STICK_CENTER, 100, 5); + ssf_press_button(context, BUTTON_L, 800ms); + ssf_press_button(context, BUTTON_PLUS, 800ms); + ssf_press_left_joystick(context, STICK_CENTER, STICK_MIN, 370, 370); } void EventBeamFinder::goto_far_den(ProControllerContext& context) const{ - ssf_hold_joystick1(context, true, STICK_CENTER, STICK_MIN, 992); + ssf_press_left_joystick(context, STICK_CENTER, STICK_MIN, 992, 992); pbf_wait(context, 50); - ssf_press_button1(context, BUTTON_PLUS, 100); - ssf_press_joystick2(context, true, STICK_MIN, STICK_CENTER, 100, 5); - ssf_press_button1(context, BUTTON_L, 100); - ssf_press_button1(context, BUTTON_PLUS, 100); - ssf_hold_joystick1(context, true, STICK_CENTER, STICK_MIN, 300); + ssf_press_button(context, BUTTON_PLUS, 800ms); + ssf_press_left_joystick(context, STICK_MIN, STICK_CENTER, 100, 5); + ssf_press_button(context, BUTTON_L, 800ms); + ssf_press_button(context, BUTTON_PLUS, 800ms); + ssf_press_left_joystick(context, STICK_CENTER, STICK_MIN, 300, 300); } void EventBeamFinder::drop_wishing_piece(ProControllerContext& context) const{ - ssf_press_button(context, BUTTON_A, 200, 10); - ssf_press_button(context, BUTTON_A, 150, 10); - ssf_press_button(context, BUTTON_A, 5); + ssf_press_button(context, BUTTON_A, 1600ms, 80ms); + ssf_press_button(context, BUTTON_A, 1200ms, 80ms); + ssf_press_button(context, BUTTON_A, 40ms); pbf_mash_button(context, BUTTON_B, 500); ssf_press_button(context, BUTTON_A, WAIT_TIME_IN_DEN0, 80ms); pbf_mash_button(context, BUTTON_B, 600); diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggCombined2.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggCombined2.cpp index 863f505efa..2bdf2f9fbd 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggCombined2.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggCombined2.cpp @@ -24,7 +24,9 @@ EggCombined2_Descriptor::EggCombined2_Descriptor() "Fetch and hatch eggs at the same time. (Fastest - 1700 eggs/day for 5120-step)", FeedbackType::NONE, AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS}, + FasterIfTickPrecise::NOT_FASTER, + true ) {} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggHelpers.h b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggHelpers.h index d7bb67ced2..09cfca6746 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggHelpers.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggHelpers.h @@ -23,11 +23,11 @@ namespace PokemonSwSh{ // Collect egg. static void collect_egg(ProControllerContext& context){ - ssf_press_button(context, BUTTON_A, 120); + ssf_press_button(context, BUTTON_A, 960ms); if (GameSettings::instance().EGG_FETCH_EXTRA_LINE){ - ssf_press_button(context, BUTTON_A, 120); + ssf_press_button(context, BUTTON_A, 960ms); } - ssf_press_button(context, BUTTON_A, 10, 10); + ssf_press_button(context, BUTTON_A, 80ms, 80ms); } static void collect_egg_mash_out(ProControllerContext& context, bool deposit_automatically){ Milliseconds FETCH_EGG_MASH_DELAY = GameSettings::instance().FETCH_EGG_MASH_DELAY0; @@ -42,12 +42,12 @@ static void collect_egg_mash_out(ProControllerContext& context, bool deposit_aut // Fly Home: Used by everything. -// Assume the selected app in the menu is Twon Map. +// Assume the selected app in the menu is Town Map. static void fly_home(ProControllerContext& context, char from_overworld){ if (from_overworld){ ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); } - ssf_press_button(context, BUTTON_A, 400, 20); + ssf_press_button(context, BUTTON_A, 3200ms, 160ms); ssf_press_right_joystick(context, 160, 96, 160ms, 160ms); pbf_mash_button(context, BUTTON_A, 480); } diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggSuperCombined2.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggSuperCombined2.cpp index 1b2ca0383d..eb25835cfb 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggSuperCombined2.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggSuperCombined2.cpp @@ -26,7 +26,9 @@ EggSuperCombined2_Descriptor::EggSuperCombined2_Descriptor() "Fetch and hatch eggs at the same time. (Fastest - 1700 eggs/day for 5120-step)", FeedbackType::NONE, AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS}, + FasterIfTickPrecise::NOT_FASTER, + true ) {} @@ -111,13 +113,13 @@ void EggSuperCombined2::program(SingleSwitchProgramEnvironment& env, ProControll // Mass Release ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); - ssf_press_button1(context, BUTTON_A, 200); - ssf_press_button1(context, BUTTON_R, 250); + ssf_press_button(context, BUTTON_A, 1600ms); + ssf_press_button(context, BUTTON_R, 2000ms); release_boxes(context, BOXES_TO_RELEASE); // Skip Boxes for (uint8_t c = 0; c <= BOXES_TO_SKIP; c++){ - ssf_press_button1(context, BUTTON_R, 60); + ssf_press_button(context, BUTTON_R, 480ms); } pbf_mash_button(context, BUTTON_B, 600); diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggItemDupe.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggItemDupe.cpp index d495d7f1f8..2bc756a994 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggItemDupe.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggItemDupe.cpp @@ -103,23 +103,23 @@ void GodEggItemDupe::collect_godegg( if (DETACH_BEFORE_RELEASE){ // Detach item - ssf_press_button(context, BUTTON_A, 50, 20); + ssf_press_button(context, BUTTON_A, 400ms, 160ms); ssf_press_dpad_ptv(context, DPAD_DOWN, 80ms); ssf_press_dpad_ptv(context, DPAD_DOWN, 80ms); - ssf_press_button(context, BUTTON_A, 150, 20); - ssf_press_button(context, BUTTON_A, 150, 20); - ssf_press_button(context, BUTTON_A, 100, 20); + ssf_press_button(context, BUTTON_A, 1200ms, 160ms); + ssf_press_button(context, BUTTON_A, 1200ms, 160ms); + ssf_press_button(context, BUTTON_A, 800ms, 160ms); // Release release(context); }else{ // Release (item detaches automatically) - ssf_press_button(context, BUTTON_A, 60, 20); + ssf_press_button(context, BUTTON_A, 480ms, 160ms); ssf_press_dpad_ptv(context, DPAD_DOWN, 120ms); ssf_press_dpad_ptv(context, DPAD_DOWN, 120ms); ssf_press_dpad_ptv(context, DPAD_DOWN, 120ms); ssf_press_dpad_ptv(context, DPAD_DOWN, 120ms); - ssf_press_button(context, BUTTON_A, 125, 20); + ssf_press_button(context, BUTTON_A, 1000ms, 160ms); ssf_press_dpad_ptv(context, DPAD_UP, 80ms); ssf_mash_AZs(context, 180); } diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_AutonomousBallThrower.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_AutonomousBallThrower.cpp index 3e90466244..9e539d65b6 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_AutonomousBallThrower.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_AutonomousBallThrower.cpp @@ -29,8 +29,7 @@ AutonomousBallThrower_Descriptor::AutonomousBallThrower_Descriptor() "Repeatedly throw a ball and reset until you catch the pokemon.", FeedbackType::REQUIRED, AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER + {ControllerFeature::NintendoSwitch_ProController} ) {} struct AutonomousBallThrower_Descriptor::Stats : public StatsTracker{ diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_BallThrower.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_BallThrower.cpp index ab79d3ee4d..b6c84cb6f0 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_BallThrower.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_BallThrower.cpp @@ -24,7 +24,8 @@ BallThrower_Descriptor::BallThrower_Descriptor() FeedbackType::NONE, AllowCommandsWhenRunning::DISABLE_COMMANDS, {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER + FasterIfTickPrecise::NOT_FASTER, + true ) {} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_SurpriseTrade.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_SurpriseTrade.cpp index f9dc5a7c43..47c9a2e336 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_SurpriseTrade.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_SurpriseTrade.cpp @@ -70,8 +70,8 @@ SurpriseTrade::SurpriseTrade() void SurpriseTrade::trade_slot(ProControllerContext& context, uint8_t slot, bool next_box) const{ ssf_press_button(context, BUTTON_Y, GameSettings::instance().OPEN_YCOMM_DELAY0, 400ms); - ssf_press_dpad1(context, DPAD_DOWN, 10); - ssf_press_button2(context, BUTTON_A, 280, 20); + ssf_press_dpad(context, DPAD_DOWN, 80ms); + ssf_press_button(context, BUTTON_A, 2240ms, 160ms); if (next_box){ ssf_press_button(context, BUTTON_R, GameSettings::instance().BOX_CHANGE_DELAY0); @@ -87,10 +87,10 @@ void SurpriseTrade::trade_slot(ProControllerContext& context, uint8_t slot, bool slot--; } - ssf_press_button1(context, BUTTON_A, 50); - ssf_press_button1(context, BUTTON_A, 500); - ssf_press_button1(context, BUTTON_A, 100); - ssf_press_button1(context, BUTTON_A, 100); + ssf_press_button(context, BUTTON_A, 400ms); + ssf_press_button(context, BUTTON_A, 4000ms); + ssf_press_button(context, BUTTON_A, 800ms); + ssf_press_button(context, BUTTON_A, 800ms); pbf_mash_button(context, BUTTON_B, INITIAL_WAIT0); @@ -129,12 +129,12 @@ void SurpriseTrade::program(SingleSwitchProgramEnvironment& env, ProControllerCo // because the trade is in progress. The 2nd iteration finishes it. // 4. No partner was ever found. The 1st iteration will cancel the trade. for (uint8_t c = 0; c < 2; c++){ - ssf_press_button1(context, BUTTON_Y, 250); - ssf_press_dpad1(context, DPAD_DOWN, 20); - ssf_press_button1(context, BUTTON_A, 280); - ssf_press_button1(context, BUTTON_B, 280); - ssf_press_button1(context, BUTTON_B, 200); - ssf_press_button1(context, BUTTON_A, 100); + ssf_press_button(context, BUTTON_Y, 2000ms); + ssf_press_dpad(context, DPAD_DOWN, 160ms); + ssf_press_button(context, BUTTON_A, 2240ms); + ssf_press_button(context, BUTTON_B, 2240ms); + ssf_press_button(context, BUTTON_B, 1600ms); + ssf_press_button(context, BUTTON_A, 800ms); pbf_mash_button(context, BUTTON_B, TRADE_ANIMATION0); } diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_TradeBot.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_TradeBot.cpp index 712dd020f7..dab05ce56d 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_TradeBot.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_TradeBot.cpp @@ -104,29 +104,29 @@ void TradeBot::trade_slot( const std::string& code, uint8_t slot ) const{ ssf_press_button(context, BUTTON_Y, GameSettings::instance().OPEN_YCOMM_DELAY0, 400ms); - ssf_press_button2(context, BUTTON_A, 150, 20); - ssf_press_dpad1(context, DPAD_DOWN, 10); - ssf_press_button2(context, BUTTON_A, 200, 20); + ssf_press_button(context, BUTTON_A, 1200ms, 160ms); + ssf_press_dpad(context, DPAD_DOWN, 80ms); + ssf_press_button(context, BUTTON_A, 1600ms, 160ms); if (LINK_TRADE_EXTRA_LINE){ - ssf_press_button2(context, BUTTON_B, 50, 20); + ssf_press_button(context, BUTTON_B, 400ms, 160ms); } - ssf_press_button2(context, BUTTON_B, 200, 20); - ssf_press_dpad1(context, DPAD_UP, 10); - ssf_press_button1(context, BUTTON_A, 5); - ssf_press_button1(context, BUTTON_B, 5); + ssf_press_button(context, BUTTON_B, 1600ms, 160ms); + ssf_press_dpad(context, DPAD_UP, 80ms); + ssf_press_button(context, BUTTON_A, 40ms); + ssf_press_button(context, BUTTON_B, 40ms); FastCodeEntry::numberpad_enter_code(console, context, code, true); - ssf_press_button1(context, BUTTON_PLUS, 200); - ssf_press_button2(context, BUTTON_B, 125, 10); - ssf_press_button2(context, BUTTON_A, 50, 10); + ssf_press_button(context, BUTTON_PLUS, 1600ms); + ssf_press_button(context, BUTTON_B, 1000ms, 80ms); + ssf_press_button(context, BUTTON_A, 400ms, 80ms); pbf_mash_button(context, BUTTON_B, 400); pbf_wait(context, SEARCH_DELAY0); // If we're not in a trade, enter Y-COMM to avoid a connection at this point. ssf_press_button(context, BUTTON_Y, GameSettings::instance().OPEN_YCOMM_DELAY0, 400ms); - ssf_press_button2(context, BUTTON_A, 200, 20); - ssf_press_button2(context, BUTTON_B, 80, 10); + ssf_press_button(context, BUTTON_A, 1600ms, 160ms); + ssf_press_button(context, BUTTON_B, 640ms, 80ms); // Move to slot while (slot >= 6){ @@ -139,7 +139,7 @@ void TradeBot::trade_slot( } // Select Pokemon - ssf_press_button1(context, BUTTON_A, 100); + ssf_press_button(context, BUTTON_A, 800ms); ssf_press_button(context, BUTTON_A, CONFIRM_DELAY0); // Start Trade @@ -177,11 +177,11 @@ void TradeBot::program(SingleSwitchProgramEnvironment& env, ProControllerContext // because the trade is in progress. The 2nd iteration finishes it. // 4. No partner was ever found. The 1st iteration will cancel the trade. for (uint8_t c = 0; c < 2; c++){ - ssf_press_button1(context, BUTTON_Y, 250); - ssf_press_button1(context, BUTTON_A, 280); - ssf_press_button1(context, BUTTON_B, 280); - ssf_press_button1(context, BUTTON_B, 200); - ssf_press_button1(context, BUTTON_A, 100); + ssf_press_button(context, BUTTON_Y, 2000ms); + ssf_press_button(context, BUTTON_A, 2240ms); + ssf_press_button(context, BUTTON_B, 2240ms); + ssf_press_button(context, BUTTON_B, 1600ms); + ssf_press_button(context, BUTTON_A, 800ms); pbf_mash_button(context, BUTTON_B, TRADE_ANIMATION0); } diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenTools.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenTools.cpp index eaf57ca32a..51e86d5899 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenTools.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenTools.cpp @@ -40,7 +40,7 @@ void enter_den( ssf_press_button(context, BUTTON_A, ENTER_ONLINE_DEN_DELAY, 400ms); }else{ ssf_press_button(context, BUTTON_A, GameSettings::instance().COLLECT_WATTS_ONLINE_DELAY0, 400ms); - ssf_press_button(context, BUTTON_B, 100, 50); + ssf_press_button(context, BUTTON_B, 800ms, 400ms); ssf_press_button(context, BUTTON_B, ENTER_ONLINE_DEN_DELAY, 400ms); } } @@ -76,12 +76,12 @@ void enter_lobby( if (!GameSettings::instance().DODGE_UNCATCHABLE_PROMPT_FAST){ // lobby-switch switch-box - ssf_press_dpad1(context, DPAD_LEFT, 10); + ssf_press_dpad(context, DPAD_LEFT, 80ms); // lobby-switch switch-party-red ssf_press_button(context, BUTTON_A, GameSettings::instance().ENTER_SWITCH_POKEMON0); // switch-box switch-confirm - ssf_press_button1(context, BUTTON_Y, 10); - ssf_press_dpad1(context, DPAD_LEFT, 10); + ssf_press_button(context, BUTTON_Y, 80ms); + ssf_press_dpad(context, DPAD_LEFT, 80ms); // switch-party-blue switch-confirm ssf_press_button(context, BUTTON_A, GameSettings::instance().EXIT_SWITCH_POKEMON0); // lobby-switch lobby-switch @@ -129,7 +129,7 @@ void roll_den( } // Exit Raid - ssf_press_button2(context, BUTTON_B, 120, 50); + ssf_press_button(context, BUTTON_B, 960ms, 400ms); ssf_press_button(context, BUTTON_A, GameSettings::instance().REENTER_DEN_DELAY0, 400ms); } } diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_ShinyHuntAutonomous-Overworld.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_ShinyHuntAutonomous-Overworld.cpp index c7c8cc4d52..50c6fd7d90 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_ShinyHuntAutonomous-Overworld.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_ShinyHuntAutonomous-Overworld.cpp @@ -246,6 +246,7 @@ bool ShinyHuntAutonomousOverworld::find_encounter( switch (result){ case 0: stream.log("Unexpected Battle.", COLOR_RED); + run_away(stream, context, EXIT_BATTLE_TIMEOUT0); return false; case 1: stream.log("Battle started!"); diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h index f3da662fb2..86ca1d2fea 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h @@ -1,26 +1,26 @@ -/* Box Helpers - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_BoxHelpers_H -#define PokemonAutomation_PokemonSwSh_BoxHelpers_H - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -static inline void box_scroll(ProControllerContext& context, DpadPosition direction){ - ssf_press_dpad_ptv(context, direction, 200ms, 104ms); -} - - - -} -} -} -#endif +/* Box Helpers + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_BoxHelpers_H +#define PokemonAutomation_PokemonSwSh_BoxHelpers_H + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +static inline void box_scroll(ProControllerContext& context, DpadPosition direction){ + ssf_press_dpad_ptv(context, direction, 200ms, 104ms); +} + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_ReleaseHelpers.h b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_ReleaseHelpers.h index b31d5cf417..49a065cbbf 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_ReleaseHelpers.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_ReleaseHelpers.h @@ -1,70 +1,70 @@ -/* Mass Release Helpers - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_ReleaseHelpers_H -#define PokemonAutomation_PokemonSwSh_ReleaseHelpers_H - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh_BoxHelpers.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -// Release one pokemon in box -static void release(ProControllerContext& context){ - ssf_press_button(context, BUTTON_A, 600ms, 80ms); - ssf_press_dpad_ptv(context, DPAD_UP, 160ms, 80ms); - ssf_press_dpad_ptv(context, DPAD_UP, 160ms, 80ms); - ssf_press_button(context, BUTTON_A, 1000ms, 80ms); - ssf_press_dpad_ptv(context, DPAD_DOWN, 120ms, 80ms); -// ssf_press_button(context, BUTTON_A, 150); -// ssf_press_button(context, BUTTON_A, 40); - ssf_mash_AZs(context, 230); -} -static void release_box(ProControllerContext& context){ - for (uint8_t row = 0; row < 5; row++){ - if (row != 0){ - box_scroll(context, DPAD_DOWN); - box_scroll(context, DPAD_RIGHT); - box_scroll(context, DPAD_RIGHT); - } - for (uint8_t col = 0; col < 6; col++){ - if (col != 0){ - box_scroll(context, DPAD_RIGHT); - } - release(context); - } - } -} -static void release_boxes(ProControllerContext& context, uint8_t boxes){ - if (boxes == 0){ - return; - } - release_box(context); - - Milliseconds box_change_delay = GameSettings::instance().BOX_CHANGE_DELAY0; - for (uint8_t box = 1; box < boxes; box++){ - box_scroll(context, DPAD_DOWN); - box_scroll(context, DPAD_DOWN); - box_scroll(context, DPAD_DOWN); - box_scroll(context, DPAD_RIGHT); - box_scroll(context, DPAD_RIGHT); - ssf_press_button_ptv(context, BUTTON_R, box_change_delay, 104ms); - release_box(context); - } -} - - - -} -} -} -#endif - +/* Mass Release Helpers + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_ReleaseHelpers_H +#define PokemonAutomation_PokemonSwSh_ReleaseHelpers_H + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh_BoxHelpers.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +// Release one pokemon in box +static void release(ProControllerContext& context){ + ssf_press_button(context, BUTTON_A, 600ms, 80ms); + ssf_press_dpad_ptv(context, DPAD_UP, 160ms, 80ms); + ssf_press_dpad_ptv(context, DPAD_UP, 160ms, 80ms); + ssf_press_button(context, BUTTON_A, 1000ms, 80ms); + ssf_press_dpad_ptv(context, DPAD_DOWN, 120ms, 80ms); +// ssf_press_button(context, BUTTON_A, 150); +// ssf_press_button(context, BUTTON_A, 40); + ssf_mash_AZs(context, 230); +} +static void release_box(ProControllerContext& context){ + for (uint8_t row = 0; row < 5; row++){ + if (row != 0){ + box_scroll(context, DPAD_DOWN); + box_scroll(context, DPAD_RIGHT); + box_scroll(context, DPAD_RIGHT); + } + for (uint8_t col = 0; col < 6; col++){ + if (col != 0){ + box_scroll(context, DPAD_RIGHT); + } + release(context); + } + } +} +static void release_boxes(ProControllerContext& context, uint8_t boxes){ + if (boxes == 0){ + return; + } + release_box(context); + + Milliseconds box_change_delay = GameSettings::instance().BOX_CHANGE_DELAY0; + for (uint8_t box = 1; box < boxes; box++){ + box_scroll(context, DPAD_DOWN); + box_scroll(context, DPAD_DOWN); + box_scroll(context, DPAD_DOWN); + box_scroll(context, DPAD_RIGHT); + box_scroll(context, DPAD_RIGHT); + ssf_press_button_ptv(context, BUTTON_R, box_change_delay, 104ms); + release_box(context); + } +} + + + +} +} +} +#endif + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_CramomaticRNG.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_CramomaticRNG.cpp index ee108d314c..49798c1307 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_CramomaticRNG.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_CramomaticRNG.cpp @@ -507,7 +507,12 @@ void CramomaticRNG::program(SingleSwitchProgramEnvironment& env, ProControllerCo env.console ); } - send_program_recoverable_error_notification(env, NOTIFICATION_ERROR_RECOVERABLE, e.message(), e.screenshot()); + send_program_recoverable_error_notification( + env, + NOTIFICATION_ERROR_RECOVERABLE, + e.message(), + e.screenshot_view() + ); is_state_valid = false; recover_from_wrong_state(env, context); continue; diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_DailyHighlightRNG.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_DailyHighlightRNG.cpp index bb62d08012..afc895a93b 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_DailyHighlightRNG.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_DailyHighlightRNG.cpp @@ -1,580 +1,585 @@ -/* RNG Manipulation of the Highlight Watt Trader in the Snowslide Slope area in the Crown Tundra - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - * Based on Anubis' findings: https://docs.google.com/spreadsheets/u/0/d/1pNYtCJKRh_efX9LvzjCiA-0n2lGSFnVmSWwmPzgSOMw - * - */ - -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" -#include "PokemonSwSh/Inference/PokemonSwSh_YCommDetector.h" -#include "PokemonSwSh/Programs/PokemonSwSh_MenuNavigation.h" -#include "PokemonSwSh/Programs/RNG/PokemonSwSh_BasicRNG.h" -#include "PokemonSwSh/Programs/RNG/PokemonSwSh_DailyHighlightRNG.h" - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -using namespace Pokemon; - - -const DailyHighlightDatabase& DAILY_HIGHLIGHT_DATABASE() { - static DailyHighlightDatabase database("PokemonSwSh/DailyHighlights.json"); - return database; -} - - -DailyHighlightRNG_Descriptor::DailyHighlightRNG_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:DailyHighlightRNG", - STRING_POKEMON + " SwSh", "Daily Highlight RNG", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DailyHighlightRNG.md", - "Perform RNG manipulation to get rare items from the daily highlight trader.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER - ) -{} - -struct DailyHighlightRNG_Descriptor::Stats : public StatsTracker{ -public: - Stats() - : iterations(m_stats["Iterations"]) - , reads(m_stats["Seed Reads"]) - , errors(m_stats["Errors"]) - , highlights(m_stats["Highlights"]) - { - m_display_order.emplace_back("Iterations"); - m_display_order.emplace_back("Seed Reads"); - m_display_order.emplace_back("Highlights"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - -public: - std::atomic& iterations; - std::atomic& reads; - std::atomic& errors; - std::atomic& highlights; -}; -std::unique_ptr DailyHighlightRNG_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -DailyHighlightRNG::DailyHighlightRNG() - : NUM_HIGHLIGHTS( - "Number of Highlights:
How many daily highlights should be bought.
Zero will run until you stop the program.", - LockMode::UNLOCK_WHILE_RUNNING, 0) - , FIX_TIME_WHEN_DONE( - "Fix Time when Done:
Fix the time after the program finishes.
Doesn't do anything if Number of Highlights is 0.", - LockMode::UNLOCK_WHILE_RUNNING, false) - , GO_HOME_WHEN_DONE(false) - , SAVE_INTERVAL( - "Save Every this Many Day Skips:
Zero disables saving.", - LockMode::UNLOCK_WHILE_RUNNING, - 20 - ) - , CALIBRATION_INTERAVAL( - "Calibrate the Number of NPCs this Many Day Skips:
Zero will only calibrate once.", - LockMode::UNLOCK_WHILE_RUNNING, - 10 - ) - , HIGHLIGHT_SELECTION( - "Desired Highlights:", - "Highlight", - DAILY_HIGHLIGHT_DATABASE().database(), - "dream-ball") - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , MAX_EXPECTED_NPCS( - "Max Expected NPCs:
How many NPCs are expected in the area at most.", - LockMode::LOCK_WHILE_RUNNING, - 8 - ) - , CALIBRATION_REPEATS( - "Calibration Repeats:
How many times the number of NPCs is checked per calibration.", - LockMode::LOCK_WHILE_RUNNING, - 5 - ) - , CALIBRATION_THRESHOLD( - "Calibration Treshold:
How many NPC counts need to be the same.
This needs to be less than or equal to Calibration Repeats.", - LockMode::LOCK_WHILE_RUNNING, - 3 - ) - , MAX_UNKNOWN_ADVANCES( - "Max Unknown Advances:
How many advances to check when updating the rng state.", - LockMode::LOCK_WHILE_RUNNING, - 100000 - ) - , ADVANCE_PRESS_DURATION( - "Advance Press Duration:
Hold the button down for this long to advance once.", - LockMode::LOCK_WHILE_RUNNING, - "80 ms" - ) - , ADVANCE_RELEASE_DURATION( - "Advance Release Duration:
After releasing the button, wait this long before pressing it again.", - LockMode::LOCK_WHILE_RUNNING, - "80 ms" - ) - , SAVE_SCREENSHOTS( - "Save Debug Screenshots:", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , LOG_VALUES( - "Log Animation Values:
", - LockMode::LOCK_WHILE_RUNNING, - false - ) -{ - PA_ADD_OPTION(START_LOCATION); - - PA_ADD_OPTION(NUM_HIGHLIGHTS); - PA_ADD_OPTION(FIX_TIME_WHEN_DONE); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(SAVE_INTERVAL); - PA_ADD_OPTION(CALIBRATION_INTERAVAL); - PA_ADD_OPTION(HIGHLIGHT_SELECTION); - - PA_ADD_OPTION(NOTIFICATIONS); - - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(CALIBRATION_REPEATS); - PA_ADD_OPTION(CALIBRATION_THRESHOLD); - PA_ADD_OPTION(MAX_EXPECTED_NPCS); - PA_ADD_OPTION(MAX_UNKNOWN_ADVANCES); - PA_ADD_OPTION(ADVANCE_PRESS_DURATION); - PA_ADD_OPTION(ADVANCE_RELEASE_DURATION); - PA_ADD_OPTION(SAVE_SCREENSHOTS); - PA_ADD_OPTION(LOG_VALUES); -} - -void DailyHighlightRNG::move_to_trader(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - pbf_move_right_joystick(context, 255, 128, 460ms, 80ms); - pbf_move_left_joystick(context, 128, 0, 1280ms, 80ms); -} - -void DailyHighlightRNG::interact_with_trader(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - VideoOverlaySet boxes(env.console); - SelectionArrowFinder arrow_detector(env.console, ImageFloatBox(0.5, 0.58, 0.2, 0.08)); - arrow_detector.make_overlays(boxes); - YCommIconDetector y_comm_icon_detector(true); - size_t tries = 0; - - while (true) { - if (tries >= 5) { - DailyHighlightRNG_Descriptor::Stats& stats = env.current_stats(); - stats.errors++; - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to talk to the trader.", - env.console - ); - } - context.wait_for_all_requests(); - int ret = wait_until(env.console, context, 500ms, { y_comm_icon_detector, arrow_detector }); - if (ret == -1 || ret == 0) { - tries++; - pbf_press_button(context, BUTTON_A, 80ms, 80ms); - } - else if (ret == 1) { - return; - } - } -} - -void DailyHighlightRNG::buy_highlight(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - // The player is expected to be in main dialog of the trader - env.log("Buying Highlight."); - env.console.overlay().add_log("Buying Highlight!", COLOR_WHITE); - pbf_press_dpad(context, DPAD_DOWN, 160ms, 160ms); - - pbf_press_button(context, BUTTON_A, 160ms, 160ms); - context.wait_for_all_requests(); - - VideoOverlaySet boxes(env.console); - SelectionArrowFinder arrow_detector(env.console, ImageFloatBox(0.5, 0.58, 0.2, 0.08)); - arrow_detector.make_overlays(boxes); - - int ret = run_until( - env.console, - context, - [](ProControllerContext& context) { - pbf_mash_button(context, BUTTON_A, 20000ms); - }, - { {arrow_detector} } - ); - - if (ret < 0) { - DailyHighlightRNG_Descriptor::Stats& stats = env.current_stats(); - stats.errors++; - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Could not detect dialog.", - env.console - ); - } -} - -void DailyHighlightRNG::navigate_to_party(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - pbf_press_button(context, BUTTON_X, 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - pbf_wait(context, 200ms); - navigate_to_menu_app(env, env.console, context, 1, NOTIFICATION_ERROR_FATAL); - pbf_press_button(context, BUTTON_A, 80ms, 3000ms); -} - -void DailyHighlightRNG::save_game(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - env.log("Saving."); - env.console.overlay().add_log("Saving!", COLOR_WHITE); - pbf_press_button(context, BUTTON_X, 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - pbf_wait(context, 200ms); - pbf_press_button(context, BUTTON_R, 80ms, 2000ms); - pbf_mash_button(context, BUTTON_A, 500ms); - - return_to_overworld(env, context); -} - -uint8_t DailyHighlightRNG::calibrate_num_npc_from_party(SingleSwitchProgramEnvironment& env, ProControllerContext& context, Pokemon::Xoroshiro128Plus& rng) { - env.log("Calibrating NPC count."); - env.console.overlay().add_log("Calibrating NPC count.", COLOR_WHITE); - - DailyHighlightRNG_Descriptor::Stats& stats = env.current_stats(); - size_t max_expected_npcs = MAX_EXPECTED_NPCS; - size_t calibration_repeats = CALIBRATION_REPEATS; - size_t calibration_threshold = CALIBRATION_THRESHOLD; - size_t finished_calibration_steps = 0; - std::vector npc_counts(max_expected_npcs, 0); - while (finished_calibration_steps < calibration_repeats) { - env.log("Calibration: " + std::to_string(finished_calibration_steps+1) + "/" + std::to_string(calibration_repeats)); - env.console.overlay().add_log("Calibration: " + std::to_string(finished_calibration_steps+1) + "/" + std::to_string(calibration_repeats), COLOR_WHITE); - - return_to_overworld(env, context); - navigate_to_party(env, context); - - Xoroshiro128PlusState state_before_menu_close(rng.get_state()); - std::pair result = refind_rng_state_and_animations(env.console, context, rng.get_state(), 0, 100, SAVE_SCREENSHOTS, LOG_VALUES); - Xoroshiro128PlusState new_state = result.first; - uint64_t additional_advances = result.second; - - // Calculate state for possible NPC counts - std::vector rng_states; - - for (uint8_t npcs = 0; npcs <= max_expected_npcs; npcs++) { - Xoroshiro128PlusState temp_state = predict_state_after_menu_close(state_before_menu_close, npcs); - Xoroshiro128Plus temp_rng(temp_state); - - // Do advances that were needed to refind current state - for (size_t i = 0; i < additional_advances; i++) { - temp_rng.next(); - } - rng_states.push_back(temp_rng.get_state()); - } - - // Compare current state to expected states - uint8_t num_npcs = 0; - uint8_t possible_choices = 0; - for (uint8_t i = 0; i <= max_expected_npcs; i++) { - if (rng_states[i].s0 == new_state.s0 && rng_states[i].s1 == new_state.s1) { - num_npcs = i; - possible_choices++; - } - } - rng.state = new_state; - - stats.reads++; - - // Add another calibration round if multiple npcs counts are possible - if (possible_choices > 1) { - env.log("NPC count is ambiguous."); - env.console.overlay().add_log("NPC count is ambiguous. Repeat calibration.", COLOR_WHITE); - continue; - } - - env.console.log("Calculated there are " + std::to_string(num_npcs) + " NPCs."); - env.console.overlay().add_log(std::to_string(num_npcs) + " NPCs", COLOR_WHITE); - npc_counts[num_npcs]++; - finished_calibration_steps++; - - if (npc_counts[num_npcs] >= calibration_threshold) { - env.console.log("Final Calibration: " + std::to_string(num_npcs) + " NPCs."); - env.console.overlay().add_log("Final Calibration: " + std::to_string(num_npcs) + " NPCs", COLOR_WHITE); - - return num_npcs; - } - } - - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "NPC is in the wrong state or an unexpected number of NPCs is in the area.", - env.console - ); -} - -size_t DailyHighlightRNG::calculate_target(SingleSwitchProgramEnvironment& env, Xoroshiro128PlusState state, uint8_t num_npcs, std::vector wanted_highlights) { - Xoroshiro128Plus rng(state); - size_t advances = 0; - bool found_advance_amount = false; - - std::vector> ranges; - for (std::string slug : wanted_highlights) { - ranges.push_back(DAILY_HIGHLIGHT_DATABASE().get_range_for_slug(slug)); - } - - while (!found_advance_amount) { - // Calculate the result for the current temp_rng state - - Xoroshiro128PlusState temp_state = predict_state_after_menu_close(rng.get_state(), num_npcs); - Xoroshiro128Plus temp_rng(temp_state); - - uint64_t highlight_roll = temp_rng.nextInt(1000); - - for (auto& range : ranges) { - if (range.first <= highlight_roll && range.second >= highlight_roll) { - found_advance_amount = true; - env.console.log("Target highlight roll: " + std::to_string(highlight_roll)); - } - } - - if (!found_advance_amount) { - rng.next(); - advances++; - } - } - - return advances; -} - -void DailyHighlightRNG::prepare_game_state(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - env.log("Prepare player position."); - env.console.overlay().add_log("Reset Player Position.", COLOR_WHITE); - - // Open map - pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - pbf_wait(context, 200ms); - navigate_to_menu_app(env, env.console, context, 5, NOTIFICATION_ERROR_RECOVERABLE); - pbf_wait(context, 200ms); - pbf_press_button(context, BUTTON_A, 160ms, 4000ms); - - // Fly to Snowslide Slope - pbf_move_left_joystick(context, 200, 210, 160ms, 160ms); - pbf_move_left_joystick(context, 150, 165, 160ms, 160ms); - pbf_mash_button(context, BUTTON_A, 1500ms); - return_to_overworld(env, context); -} - -void DailyHighlightRNG::return_to_overworld(SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool wait_after_detection) { - context.wait_for_all_requests(); - env.console.log("Returning to the overworld."); - YCommIconDetector y_comm_icon_detector(true); - int ret = run_until( - env.console, context, - [](ProControllerContext& context) { - pbf_mash_button(context, BUTTON_B, 20000ms); - }, - { {y_comm_icon_detector} } - ); - if (ret != 0) { - DailyHighlightRNG_Descriptor::Stats& stats = env.current_stats(); - stats.errors++; - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Cannot detect the Y-Comm icon.", - env.console - ); - } - - // Sometimes Y-Comm is detected before button presses are accepted again - if (wait_after_detection) { - context.wait_for(300ms); - } -} - -void DailyHighlightRNG::advance_date(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint8_t& year) { - context.wait_for(200ms); - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - home_to_date_time(env.console, context, true); - pbf_press_button(context, BUTTON_A, 160ms, 240ms); - context.wait_for_all_requests(); - - VideoOverlaySet overlays(env.console.overlay()); - DateChangeWatcher date_reader(env.console); - date_reader.make_overlays(overlays); - - DateTime date{ 2000, 12, 31, 1, 0, 0 }; // 31st December for fixed Normal weather - - if (year >= MAX_YEAR) { - date_reader.set_date(env.program_info(), env.console, context, date); - pbf_press_button(context, BUTTON_A, 160ms, 240ms); - pbf_press_button(context, BUTTON_A, 160ms, 240ms); - year = 1; - } - - date.year += year; - date_reader.set_date(env.program_info(), env.console, context, date); - pbf_press_button(context, BUTTON_A, 160ms, 240ms); - - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_from_home(env.console, context, false); - year++; -} - - -void DailyHighlightRNG::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - DailyHighlightRNG_Descriptor::Stats& stats = env.current_stats(); - env.update_stats(); - - std::vector wanted_highlights = HIGHLIGHT_SELECTION.all_slugs(); - if (wanted_highlights.empty()){ - throw UserSetupError(env.console, "At least one highlight item needs to be selected!"); - } - - if (START_LOCATION.start_in_grip_menu()) { - grip_menu_connect_go_home(context); - } - else { - pbf_press_button(context, BUTTON_B, 80ms, 80ms); - } - - - Xoroshiro128Plus rng(0, 0); - uint8_t num_npcs = 0; - size_t iterations = 0; - size_t assumed_successful_iterations = 0; - size_t bought_highlights = 0; - uint8_t year = MAX_YEAR; - uint16_t state_errors = 0; - - while (bought_highlights < NUM_HIGHLIGHTS || NUM_HIGHLIGHTS <= 0){ - iterations++; - stats.iterations++; - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - env.console.log("Daily Highlight RNG iteration: " + std::to_string(iterations)); - env.console.overlay().add_log("Iteration: " + std::to_string(iterations), COLOR_WHITE); - - if (SAVE_INTERVAL > 0 && iterations % SAVE_INTERVAL == 0) { - save_game(env, context); - } - - return_to_overworld(env, context); - - if (assumed_successful_iterations <= 0) { - prepare_game_state(env, context); - - // open and close the menu and immediately walk to the trader - pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - return_to_overworld(env, context); - move_to_trader(env, context); - interact_with_trader(env, context); - - return_to_overworld(env, context); - } - - advance_date(env, context, year); - navigate_to_party(env, context); - context.wait_for_all_requests(); - - // (Re-)Find RNG state - if (assumed_successful_iterations <= 0) { - env.log("Finding initial rng state."); - env.console.overlay().add_log("Initial RNG state:", COLOR_WHITE); - rng = Xoroshiro128Plus(find_rng_state(env.console, context, SAVE_SCREENSHOTS, LOG_VALUES)); - stats.reads++; - } else { - env.log("Refinding rng state."); - env.console.overlay().add_log("New RNG state:", COLOR_WHITE); - rng = Xoroshiro128Plus(refind_rng_state(env.console, context, rng.get_state(), 0, MAX_UNKNOWN_ADVANCES, SAVE_SCREENSHOTS, LOG_VALUES)); - stats.reads++; - } - - Xoroshiro128PlusState rng_state = rng.get_state(); - if (rng_state.s0 == 0 && rng_state.s1 == 0){ - stats.errors++; - env.update_stats(); - - state_errors++; - if (state_errors >= 3){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Detected invalid RNG state three times in a row.", - env.console - ); - } - VideoSnapshot screen = env.console.video().snapshot(); - send_program_recoverable_error_notification(env, NOTIFICATION_ERROR_RECOVERABLE, "Detected invalid RNG state.", screen); - assumed_successful_iterations = 0; - continue; - } - - // Calibrate number of NPCs in the area and check whether the trader is in the slow state - if ((CALIBRATION_INTERAVAL > 0 && assumed_successful_iterations % CALIBRATION_INTERAVAL == 0) || assumed_successful_iterations <= 0) { - try { - num_npcs = calibrate_num_npc_from_party(env, context, rng); - } - catch (OperationFailedException& exception) { - send_program_recoverable_error_notification(env, NOTIFICATION_ERROR_RECOVERABLE, exception.message(), exception.screenshot()); - assumed_successful_iterations = 0; - stats.errors++; - continue; - } - } - - // Do required advances - size_t target_advances = calculate_target(env, rng.get_state(), num_npcs, HIGHLIGHT_SELECTION.all_slugs()); - env.console.log("Needed advances: " + std::to_string(target_advances)); - do_rng_advances(env.console, context, rng, target_advances, ADVANCE_PRESS_DURATION, ADVANCE_RELEASE_DURATION); - - // Talk to NPC and buy highlight - return_to_overworld(env, context, false); - interact_with_trader(env, context); - if (assumed_successful_iterations >= 2) { - buy_highlight(env, context); - bought_highlights++; - stats.highlights++; - } - return_to_overworld(env, context); - - env.update_stats(); - assumed_successful_iterations++; - state_errors = 0; - } - - if (FIX_TIME_WHEN_DONE) { - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - home_to_date_time(env.console, context, false); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_from_home(env.console, context); - } - GO_HOME_WHEN_DONE.run_end_of_program(context); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH, "Finished buying " + std::to_string(bought_highlights) + " daily highlights!", env.console.video().snapshot()); -} - - -} -} -} +/* RNG Manipulation of the Highlight Watt Trader in the Snowslide Slope area in the Crown Tundra + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + * Based on Anubis' findings: https://docs.google.com/spreadsheets/u/0/d/1pNYtCJKRh_efX9LvzjCiA-0n2lGSFnVmSWwmPzgSOMw + * + */ + +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" +#include "PokemonSwSh/Inference/PokemonSwSh_YCommDetector.h" +#include "PokemonSwSh/Programs/PokemonSwSh_MenuNavigation.h" +#include "PokemonSwSh/Programs/RNG/PokemonSwSh_BasicRNG.h" +#include "PokemonSwSh/Programs/RNG/PokemonSwSh_DailyHighlightRNG.h" + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +using namespace Pokemon; + + +const DailyHighlightDatabase& DAILY_HIGHLIGHT_DATABASE() { + static DailyHighlightDatabase database("PokemonSwSh/DailyHighlights.json"); + return database; +} + + +DailyHighlightRNG_Descriptor::DailyHighlightRNG_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:DailyHighlightRNG", + STRING_POKEMON + " SwSh", "Daily Highlight RNG", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DailyHighlightRNG.md", + "Perform RNG manipulation to get rare items from the daily highlight trader.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER + ) +{} + +struct DailyHighlightRNG_Descriptor::Stats : public StatsTracker{ +public: + Stats() + : iterations(m_stats["Iterations"]) + , reads(m_stats["Seed Reads"]) + , errors(m_stats["Errors"]) + , highlights(m_stats["Highlights"]) + { + m_display_order.emplace_back("Iterations"); + m_display_order.emplace_back("Seed Reads"); + m_display_order.emplace_back("Highlights"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + +public: + std::atomic& iterations; + std::atomic& reads; + std::atomic& errors; + std::atomic& highlights; +}; +std::unique_ptr DailyHighlightRNG_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +DailyHighlightRNG::DailyHighlightRNG() + : NUM_HIGHLIGHTS( + "Number of Highlights:
How many daily highlights should be bought.
Zero will run until you stop the program.", + LockMode::UNLOCK_WHILE_RUNNING, 0) + , FIX_TIME_WHEN_DONE( + "Fix Time when Done:
Fix the time after the program finishes.
Doesn't do anything if Number of Highlights is 0.", + LockMode::UNLOCK_WHILE_RUNNING, false) + , GO_HOME_WHEN_DONE(false) + , SAVE_INTERVAL( + "Save Every this Many Day Skips:
Zero disables saving.", + LockMode::UNLOCK_WHILE_RUNNING, + 20 + ) + , CALIBRATION_INTERAVAL( + "Calibrate the Number of NPCs this Many Day Skips:
Zero will only calibrate once.", + LockMode::UNLOCK_WHILE_RUNNING, + 10 + ) + , HIGHLIGHT_SELECTION( + "Desired Highlights:", + "Highlight", + DAILY_HIGHLIGHT_DATABASE().database(), + "dream-ball") + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , MAX_EXPECTED_NPCS( + "Max Expected NPCs:
How many NPCs are expected in the area at most.", + LockMode::LOCK_WHILE_RUNNING, + 8 + ) + , CALIBRATION_REPEATS( + "Calibration Repeats:
How many times the number of NPCs is checked per calibration.", + LockMode::LOCK_WHILE_RUNNING, + 5 + ) + , CALIBRATION_THRESHOLD( + "Calibration Treshold:
How many NPC counts need to be the same.
This needs to be less than or equal to Calibration Repeats.", + LockMode::LOCK_WHILE_RUNNING, + 3 + ) + , MAX_UNKNOWN_ADVANCES( + "Max Unknown Advances:
How many advances to check when updating the rng state.", + LockMode::LOCK_WHILE_RUNNING, + 100000 + ) + , ADVANCE_PRESS_DURATION( + "Advance Press Duration:
Hold the button down for this long to advance once.", + LockMode::LOCK_WHILE_RUNNING, + "80 ms" + ) + , ADVANCE_RELEASE_DURATION( + "Advance Release Duration:
After releasing the button, wait this long before pressing it again.", + LockMode::LOCK_WHILE_RUNNING, + "80 ms" + ) + , SAVE_SCREENSHOTS( + "Save Debug Screenshots:", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , LOG_VALUES( + "Log Animation Values:
", + LockMode::LOCK_WHILE_RUNNING, + false + ) +{ + PA_ADD_OPTION(START_LOCATION); + + PA_ADD_OPTION(NUM_HIGHLIGHTS); + PA_ADD_OPTION(FIX_TIME_WHEN_DONE); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(SAVE_INTERVAL); + PA_ADD_OPTION(CALIBRATION_INTERAVAL); + PA_ADD_OPTION(HIGHLIGHT_SELECTION); + + PA_ADD_OPTION(NOTIFICATIONS); + + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(CALIBRATION_REPEATS); + PA_ADD_OPTION(CALIBRATION_THRESHOLD); + PA_ADD_OPTION(MAX_EXPECTED_NPCS); + PA_ADD_OPTION(MAX_UNKNOWN_ADVANCES); + PA_ADD_OPTION(ADVANCE_PRESS_DURATION); + PA_ADD_OPTION(ADVANCE_RELEASE_DURATION); + PA_ADD_OPTION(SAVE_SCREENSHOTS); + PA_ADD_OPTION(LOG_VALUES); +} + +void DailyHighlightRNG::move_to_trader(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + pbf_move_right_joystick(context, 255, 128, 460ms, 80ms); + pbf_move_left_joystick(context, 128, 0, 1280ms, 80ms); +} + +void DailyHighlightRNG::interact_with_trader(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + VideoOverlaySet boxes(env.console); + SelectionArrowFinder arrow_detector(env.console, ImageFloatBox(0.5, 0.58, 0.2, 0.08)); + arrow_detector.make_overlays(boxes); + YCommIconDetector y_comm_icon_detector(true); + size_t tries = 0; + + while (true) { + if (tries >= 5) { + DailyHighlightRNG_Descriptor::Stats& stats = env.current_stats(); + stats.errors++; + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to talk to the trader.", + env.console + ); + } + context.wait_for_all_requests(); + int ret = wait_until(env.console, context, 500ms, { y_comm_icon_detector, arrow_detector }); + if (ret == -1 || ret == 0) { + tries++; + pbf_press_button(context, BUTTON_A, 80ms, 80ms); + } + else if (ret == 1) { + return; + } + } +} + +void DailyHighlightRNG::buy_highlight(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + // The player is expected to be in main dialog of the trader + env.log("Buying Highlight."); + env.console.overlay().add_log("Buying Highlight!", COLOR_WHITE); + pbf_press_dpad(context, DPAD_DOWN, 160ms, 160ms); + + pbf_press_button(context, BUTTON_A, 160ms, 160ms); + context.wait_for_all_requests(); + + VideoOverlaySet boxes(env.console); + SelectionArrowFinder arrow_detector(env.console, ImageFloatBox(0.5, 0.58, 0.2, 0.08)); + arrow_detector.make_overlays(boxes); + + int ret = run_until( + env.console, + context, + [](ProControllerContext& context) { + pbf_mash_button(context, BUTTON_A, 20000ms); + }, + { {arrow_detector} } + ); + + if (ret < 0) { + DailyHighlightRNG_Descriptor::Stats& stats = env.current_stats(); + stats.errors++; + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Could not detect dialog.", + env.console + ); + } +} + +void DailyHighlightRNG::navigate_to_party(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + pbf_press_button(context, BUTTON_X, 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + pbf_wait(context, 200ms); + navigate_to_menu_app(env, env.console, context, 1, NOTIFICATION_ERROR_FATAL); + pbf_press_button(context, BUTTON_A, 80ms, 3000ms); +} + +void DailyHighlightRNG::save_game(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + env.log("Saving."); + env.console.overlay().add_log("Saving!", COLOR_WHITE); + pbf_press_button(context, BUTTON_X, 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + pbf_wait(context, 200ms); + pbf_press_button(context, BUTTON_R, 80ms, 2000ms); + pbf_mash_button(context, BUTTON_A, 500ms); + + return_to_overworld(env, context); +} + +uint8_t DailyHighlightRNG::calibrate_num_npc_from_party(SingleSwitchProgramEnvironment& env, ProControllerContext& context, Pokemon::Xoroshiro128Plus& rng) { + env.log("Calibrating NPC count."); + env.console.overlay().add_log("Calibrating NPC count.", COLOR_WHITE); + + DailyHighlightRNG_Descriptor::Stats& stats = env.current_stats(); + size_t max_expected_npcs = MAX_EXPECTED_NPCS; + size_t calibration_repeats = CALIBRATION_REPEATS; + size_t calibration_threshold = CALIBRATION_THRESHOLD; + size_t finished_calibration_steps = 0; + std::vector npc_counts(max_expected_npcs, 0); + while (finished_calibration_steps < calibration_repeats) { + env.log("Calibration: " + std::to_string(finished_calibration_steps+1) + "/" + std::to_string(calibration_repeats)); + env.console.overlay().add_log("Calibration: " + std::to_string(finished_calibration_steps+1) + "/" + std::to_string(calibration_repeats), COLOR_WHITE); + + return_to_overworld(env, context); + navigate_to_party(env, context); + + Xoroshiro128PlusState state_before_menu_close(rng.get_state()); + std::pair result = refind_rng_state_and_animations(env.console, context, rng.get_state(), 0, 100, SAVE_SCREENSHOTS, LOG_VALUES); + Xoroshiro128PlusState new_state = result.first; + uint64_t additional_advances = result.second; + + // Calculate state for possible NPC counts + std::vector rng_states; + + for (uint8_t npcs = 0; npcs <= max_expected_npcs; npcs++) { + Xoroshiro128PlusState temp_state = predict_state_after_menu_close(state_before_menu_close, npcs); + Xoroshiro128Plus temp_rng(temp_state); + + // Do advances that were needed to refind current state + for (size_t i = 0; i < additional_advances; i++) { + temp_rng.next(); + } + rng_states.push_back(temp_rng.get_state()); + } + + // Compare current state to expected states + uint8_t num_npcs = 0; + uint8_t possible_choices = 0; + for (uint8_t i = 0; i <= max_expected_npcs; i++) { + if (rng_states[i].s0 == new_state.s0 && rng_states[i].s1 == new_state.s1) { + num_npcs = i; + possible_choices++; + } + } + rng.state = new_state; + + stats.reads++; + + // Add another calibration round if multiple npcs counts are possible + if (possible_choices > 1) { + env.log("NPC count is ambiguous."); + env.console.overlay().add_log("NPC count is ambiguous. Repeat calibration.", COLOR_WHITE); + continue; + } + + env.console.log("Calculated there are " + std::to_string(num_npcs) + " NPCs."); + env.console.overlay().add_log(std::to_string(num_npcs) + " NPCs", COLOR_WHITE); + npc_counts[num_npcs]++; + finished_calibration_steps++; + + if (npc_counts[num_npcs] >= calibration_threshold) { + env.console.log("Final Calibration: " + std::to_string(num_npcs) + " NPCs."); + env.console.overlay().add_log("Final Calibration: " + std::to_string(num_npcs) + " NPCs", COLOR_WHITE); + + return num_npcs; + } + } + + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "NPC is in the wrong state or an unexpected number of NPCs is in the area.", + env.console + ); +} + +size_t DailyHighlightRNG::calculate_target(SingleSwitchProgramEnvironment& env, Xoroshiro128PlusState state, uint8_t num_npcs, std::vector wanted_highlights) { + Xoroshiro128Plus rng(state); + size_t advances = 0; + bool found_advance_amount = false; + + std::vector> ranges; + for (std::string slug : wanted_highlights) { + ranges.push_back(DAILY_HIGHLIGHT_DATABASE().get_range_for_slug(slug)); + } + + while (!found_advance_amount) { + // Calculate the result for the current temp_rng state + + Xoroshiro128PlusState temp_state = predict_state_after_menu_close(rng.get_state(), num_npcs); + Xoroshiro128Plus temp_rng(temp_state); + + uint64_t highlight_roll = temp_rng.nextInt(1000); + + for (auto& range : ranges) { + if (range.first <= highlight_roll && range.second >= highlight_roll) { + found_advance_amount = true; + env.console.log("Target highlight roll: " + std::to_string(highlight_roll)); + } + } + + if (!found_advance_amount) { + rng.next(); + advances++; + } + } + + return advances; +} + +void DailyHighlightRNG::prepare_game_state(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + env.log("Prepare player position."); + env.console.overlay().add_log("Reset Player Position.", COLOR_WHITE); + + // Open map + pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + pbf_wait(context, 200ms); + navigate_to_menu_app(env, env.console, context, 5, NOTIFICATION_ERROR_RECOVERABLE); + pbf_wait(context, 200ms); + pbf_press_button(context, BUTTON_A, 160ms, 4000ms); + + // Fly to Snowslide Slope + pbf_move_left_joystick(context, 200, 210, 160ms, 160ms); + pbf_move_left_joystick(context, 150, 165, 160ms, 160ms); + pbf_mash_button(context, BUTTON_A, 1500ms); + return_to_overworld(env, context); +} + +void DailyHighlightRNG::return_to_overworld(SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool wait_after_detection) { + context.wait_for_all_requests(); + env.console.log("Returning to the overworld."); + YCommIconDetector y_comm_icon_detector(true); + int ret = run_until( + env.console, context, + [](ProControllerContext& context) { + pbf_mash_button(context, BUTTON_B, 20000ms); + }, + { {y_comm_icon_detector} } + ); + if (ret != 0) { + DailyHighlightRNG_Descriptor::Stats& stats = env.current_stats(); + stats.errors++; + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Cannot detect the Y-Comm icon.", + env.console + ); + } + + // Sometimes Y-Comm is detected before button presses are accepted again + if (wait_after_detection) { + context.wait_for(300ms); + } +} + +void DailyHighlightRNG::advance_date(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint8_t& year) { + context.wait_for(200ms); + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + home_to_date_time(env.console, context, true); + pbf_press_button(context, BUTTON_A, 160ms, 240ms); + context.wait_for_all_requests(); + + VideoOverlaySet overlays(env.console.overlay()); + DateChangeWatcher date_reader(env.console); + date_reader.make_overlays(overlays); + + DateTime date{ 2000, 12, 31, 1, 0, 0 }; // 31st December for fixed Normal weather + + if (year >= MAX_YEAR) { + date_reader.set_date(env.program_info(), env.console, context, date); + pbf_press_button(context, BUTTON_A, 160ms, 240ms); + pbf_press_button(context, BUTTON_A, 160ms, 240ms); + year = 1; + } + + date.year += year; + date_reader.set_date(env.program_info(), env.console, context, date); + pbf_press_button(context, BUTTON_A, 160ms, 240ms); + + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_from_home(env.console, context, false); + year++; +} + + +void DailyHighlightRNG::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + DailyHighlightRNG_Descriptor::Stats& stats = env.current_stats(); + env.update_stats(); + + std::vector wanted_highlights = HIGHLIGHT_SELECTION.all_slugs(); + if (wanted_highlights.empty()){ + throw UserSetupError(env.console, "At least one highlight item needs to be selected!"); + } + + if (START_LOCATION.start_in_grip_menu()) { + grip_menu_connect_go_home(context); + } + else { + pbf_press_button(context, BUTTON_B, 80ms, 80ms); + } + + + Xoroshiro128Plus rng(0, 0); + uint8_t num_npcs = 0; + size_t iterations = 0; + size_t assumed_successful_iterations = 0; + size_t bought_highlights = 0; + uint8_t year = MAX_YEAR; + uint16_t state_errors = 0; + + while (bought_highlights < NUM_HIGHLIGHTS || NUM_HIGHLIGHTS <= 0){ + iterations++; + stats.iterations++; + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + env.console.log("Daily Highlight RNG iteration: " + std::to_string(iterations)); + env.console.overlay().add_log("Iteration: " + std::to_string(iterations), COLOR_WHITE); + + if (SAVE_INTERVAL > 0 && iterations % SAVE_INTERVAL == 0) { + save_game(env, context); + } + + return_to_overworld(env, context); + + if (assumed_successful_iterations <= 0) { + prepare_game_state(env, context); + + // open and close the menu and immediately walk to the trader + pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + return_to_overworld(env, context); + move_to_trader(env, context); + interact_with_trader(env, context); + + return_to_overworld(env, context); + } + + advance_date(env, context, year); + navigate_to_party(env, context); + context.wait_for_all_requests(); + + // (Re-)Find RNG state + if (assumed_successful_iterations <= 0) { + env.log("Finding initial rng state."); + env.console.overlay().add_log("Initial RNG state:", COLOR_WHITE); + rng = Xoroshiro128Plus(find_rng_state(env.console, context, SAVE_SCREENSHOTS, LOG_VALUES)); + stats.reads++; + } else { + env.log("Refinding rng state."); + env.console.overlay().add_log("New RNG state:", COLOR_WHITE); + rng = Xoroshiro128Plus(refind_rng_state(env.console, context, rng.get_state(), 0, MAX_UNKNOWN_ADVANCES, SAVE_SCREENSHOTS, LOG_VALUES)); + stats.reads++; + } + + Xoroshiro128PlusState rng_state = rng.get_state(); + if (rng_state.s0 == 0 && rng_state.s1 == 0){ + stats.errors++; + env.update_stats(); + + state_errors++; + if (state_errors >= 3){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Detected invalid RNG state three times in a row.", + env.console + ); + } + VideoSnapshot screen = env.console.video().snapshot(); + send_program_recoverable_error_notification(env, NOTIFICATION_ERROR_RECOVERABLE, "Detected invalid RNG state.", screen); + assumed_successful_iterations = 0; + continue; + } + + // Calibrate number of NPCs in the area and check whether the trader is in the slow state + if ((CALIBRATION_INTERAVAL > 0 && assumed_successful_iterations % CALIBRATION_INTERAVAL == 0) || assumed_successful_iterations <= 0) { + try { + num_npcs = calibrate_num_npc_from_party(env, context, rng); + } + catch (OperationFailedException& exception) { + send_program_recoverable_error_notification( + env, + NOTIFICATION_ERROR_RECOVERABLE, + exception.message(), + exception.screenshot_view() + ); + assumed_successful_iterations = 0; + stats.errors++; + continue; + } + } + + // Do required advances + size_t target_advances = calculate_target(env, rng.get_state(), num_npcs, HIGHLIGHT_SELECTION.all_slugs()); + env.console.log("Needed advances: " + std::to_string(target_advances)); + do_rng_advances(env.console, context, rng, target_advances, ADVANCE_PRESS_DURATION, ADVANCE_RELEASE_DURATION); + + // Talk to NPC and buy highlight + return_to_overworld(env, context, false); + interact_with_trader(env, context); + if (assumed_successful_iterations >= 2) { + buy_highlight(env, context); + bought_highlights++; + stats.highlights++; + } + return_to_overworld(env, context); + + env.update_stats(); + assumed_successful_iterations++; + state_errors = 0; + } + + if (FIX_TIME_WHEN_DONE) { + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + home_to_date_time(env.console, context, false); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_from_home(env.console, context); + } + GO_HOME_WHEN_DONE.run_end_of_program(context); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH, "Finished buying " + std::to_string(bought_highlights) + " daily highlights!", env.console.video().snapshot()); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_DailyHighlightRNG.h b/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_DailyHighlightRNG.h index 3176a3923e..5bbc37a1d8 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_DailyHighlightRNG.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_DailyHighlightRNG.h @@ -1,88 +1,88 @@ -/* RNG Manipulation of the Highlight Watt Trader in the Snowslide Slope area in the Crown Tundra - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - * Based on Anubis' findings: https://docs.google.com/spreadsheets/u/0/d/1pNYtCJKRh_efX9LvzjCiA-0n2lGSFnVmSWwmPzgSOMw/htmlview - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_DailyHighlightRNG_H -#define PokemonAutomation_PokemonSwSh_DailyHighlightRNG_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "CommonTools/Options/StringSelectTableOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "Pokemon/Pokemon_Xoroshiro128Plus.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" -#include "PokemonSwSh/Resources/PokemonSwSh_DailyHighlightDatabase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class DailyHighlightRNG_Descriptor : public SingleSwitchProgramDescriptor{ -public: - DailyHighlightRNG_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class DailyHighlightRNG : public SingleSwitchProgramInstance{ -public: - DailyHighlightRNG(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - SimpleIntegerOption NUM_HIGHLIGHTS; - BooleanCheckBoxOption FIX_TIME_WHEN_DONE; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - SimpleIntegerOption SAVE_INTERVAL; - SimpleIntegerOption CALIBRATION_INTERAVAL; - StringSelectTableOption HIGHLIGHT_SELECTION; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - SimpleIntegerOption MAX_EXPECTED_NPCS; - SimpleIntegerOption CALIBRATION_REPEATS; - SimpleIntegerOption CALIBRATION_THRESHOLD; - SimpleIntegerOption MAX_UNKNOWN_ADVANCES; - MillisecondsOption ADVANCE_PRESS_DURATION; - MillisecondsOption ADVANCE_RELEASE_DURATION; - BooleanCheckBoxOption SAVE_SCREENSHOTS; - BooleanCheckBoxOption LOG_VALUES; - - void move_to_trader(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void interact_with_trader(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void return_to_overworld(SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool wait_after_detection = true); - void buy_highlight(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - uint8_t calibrate_num_npc_from_party(SingleSwitchProgramEnvironment& env, ProControllerContext& context, Pokemon::Xoroshiro128Plus& rng); - void navigate_to_party(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - size_t calculate_target(SingleSwitchProgramEnvironment& env, Pokemon::Xoroshiro128PlusState state, uint8_t num_npcs, std::vector wanted_highlights); - void prepare_game_state(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void save_game(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void advance_date(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint8_t& year); -}; - - - - -} -} -} -#endif - - - +/* RNG Manipulation of the Highlight Watt Trader in the Snowslide Slope area in the Crown Tundra + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + * Based on Anubis' findings: https://docs.google.com/spreadsheets/u/0/d/1pNYtCJKRh_efX9LvzjCiA-0n2lGSFnVmSWwmPzgSOMw/htmlview + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_DailyHighlightRNG_H +#define PokemonAutomation_PokemonSwSh_DailyHighlightRNG_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "CommonTools/Options/StringSelectTableOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Pokemon_Xoroshiro128Plus.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" +#include "PokemonSwSh/Resources/PokemonSwSh_DailyHighlightDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class DailyHighlightRNG_Descriptor : public SingleSwitchProgramDescriptor{ +public: + DailyHighlightRNG_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class DailyHighlightRNG : public SingleSwitchProgramInstance{ +public: + DailyHighlightRNG(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + SimpleIntegerOption NUM_HIGHLIGHTS; + BooleanCheckBoxOption FIX_TIME_WHEN_DONE; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + SimpleIntegerOption SAVE_INTERVAL; + SimpleIntegerOption CALIBRATION_INTERAVAL; + StringSelectTableOption HIGHLIGHT_SELECTION; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + SimpleIntegerOption MAX_EXPECTED_NPCS; + SimpleIntegerOption CALIBRATION_REPEATS; + SimpleIntegerOption CALIBRATION_THRESHOLD; + SimpleIntegerOption MAX_UNKNOWN_ADVANCES; + MillisecondsOption ADVANCE_PRESS_DURATION; + MillisecondsOption ADVANCE_RELEASE_DURATION; + BooleanCheckBoxOption SAVE_SCREENSHOTS; + BooleanCheckBoxOption LOG_VALUES; + + void move_to_trader(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void interact_with_trader(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void return_to_overworld(SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool wait_after_detection = true); + void buy_highlight(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + uint8_t calibrate_num_npc_from_party(SingleSwitchProgramEnvironment& env, ProControllerContext& context, Pokemon::Xoroshiro128Plus& rng); + void navigate_to_party(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + size_t calculate_target(SingleSwitchProgramEnvironment& env, Pokemon::Xoroshiro128PlusState state, uint8_t num_npcs, std::vector wanted_highlights); + void prepare_game_state(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void save_game(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void advance_date(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint8_t& year); +}; + + + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_MultiGameFossil.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_MultiGameFossil.cpp index c6e91bbc9c..4cf8136d0d 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_MultiGameFossil.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_MultiGameFossil.cpp @@ -135,8 +135,8 @@ void run_fossil_batch( // Save game. ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); - ssf_press_button(context, BUTTON_R, 150, 20); - ssf_press_button(context, BUTTON_A, 500, 10); + ssf_press_button(context, BUTTON_R, 1200ms, 160ms); + ssf_press_button(context, BUTTON_A, 4000ms, 80ms); // Exit game. ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 80ms); diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-IoATrade.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-IoATrade.cpp index 4629f6cae2..33284c9829 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-IoATrade.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-IoATrade.cpp @@ -28,7 +28,9 @@ ShinyHuntUnattendedIoATrade_Descriptor::ShinyHuntUnattendedIoATrade_Descriptor() "Hunt for shiny Isle of Armor trade. Stop when a shiny is found.", FeedbackType::NONE, AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS}, + FasterIfTickPrecise::NOT_FASTER, + true ) {} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regi.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regi.cpp index 2de16f250f..c5de4250f8 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regi.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regi.cpp @@ -28,7 +28,9 @@ ShinyHuntUnattendedRegi_Descriptor::ShinyHuntUnattendedRegi_Descriptor() "Hunt for shiny Regis. Stop when a shiny is found.", FeedbackType::NONE, AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS}, + FasterIfTickPrecise::NOT_FASTER, + true ) {} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regigigas2.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regigigas2.cpp index ed4df32bc8..24459ac14a 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regigigas2.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regigigas2.cpp @@ -27,7 +27,9 @@ ShinyHuntUnattendedRegigigas2_Descriptor::ShinyHuntUnattendedRegigigas2_Descript "A new version of the Regigigas program that is faster.", FeedbackType::NONE, AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS}, + FasterIfTickPrecise::NOT_FASTER, + true ) {} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-StrongSpawn.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-StrongSpawn.cpp index 6458a2735b..7aa08684bf 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-StrongSpawn.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-StrongSpawn.cpp @@ -27,7 +27,9 @@ ShinyHuntUnattendedStrongSpawn_Descriptor::ShinyHuntUnattendedStrongSpawn_Descri "Hunt for shiny strong spawns. Stop when a shiny is found.", FeedbackType::NONE, AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS}, + FasterIfTickPrecise::NOT_FASTER, + true ) {} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-SwordsOfJustice.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-SwordsOfJustice.cpp index de6f2f2e8e..bb8e0237ea 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-SwordsOfJustice.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-SwordsOfJustice.cpp @@ -28,7 +28,9 @@ ShinyHuntUnattendedSwordsOfJustice_Descriptor::ShinyHuntUnattendedSwordsOfJustic "Hunt for shiny SOJs. Stop when a shiny is found.", FeedbackType::NONE, AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS}, + FasterIfTickPrecise::NOT_FASTER, + true ) {} diff --git a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_DailyHighlightDatabase.cpp b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_DailyHighlightDatabase.cpp index bed61cca1b..77aa6cc8a9 100644 --- a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_DailyHighlightDatabase.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_DailyHighlightDatabase.cpp @@ -1,53 +1,53 @@ -/* Daily Highlight Database - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/Logging/Logger.h" -#include "PokemonSwSh_DailyHighlightDatabase.h" - -namespace PokemonAutomation { -namespace NintendoSwitch { -namespace PokemonSwSh { - - - -DailyHighlightDatabase::DailyHighlightDatabase(const char* resource_path) { - std::string filepath = RESOURCE_PATH() + resource_path; - JsonValue json = load_json_file(filepath); - JsonObject& root = json.to_object_throw(filepath); - - for (auto& item : root) { - const std::string& slug = item.first; - JsonObject& obj = item.second.to_object_throw(filepath); - - uint16_t min = (uint16_t)obj.get_integer_throw("min", filepath); - uint16_t max = (uint16_t)obj.get_integer_throw("max", filepath); - m_slug_to_range[slug] = std::pair(min, max); - - std::string display_name = obj.get_string_throw("display_name", filepath); - StringSelectEntry string_select_entry(slug, display_name); - m_stringselect_database.add_entry(string_select_entry); - } -} - -std::pair DailyHighlightDatabase::get_range_for_slug(const std::string& slug) const { - auto iter = m_slug_to_range.find(slug); - if (iter == m_slug_to_range.end()) { - throw InternalProgramError( - nullptr, - PA_CURRENT_FUNCTION, - std::string("Invalid daily highlight slug: " + slug) - ); - } - return iter->second; -} - - - -} -} -} +/* Daily Highlight Database + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/Logging/Logger.h" +#include "PokemonSwSh_DailyHighlightDatabase.h" + +namespace PokemonAutomation { +namespace NintendoSwitch { +namespace PokemonSwSh { + + + +DailyHighlightDatabase::DailyHighlightDatabase(const char* resource_path) { + std::string filepath = RESOURCE_PATH() + resource_path; + JsonValue json = load_json_file(filepath); + JsonObject& root = json.to_object_throw(filepath); + + for (auto& item : root) { + const std::string& slug = item.first; + JsonObject& obj = item.second.to_object_throw(filepath); + + uint16_t min = (uint16_t)obj.get_integer_throw("min", filepath); + uint16_t max = (uint16_t)obj.get_integer_throw("max", filepath); + m_slug_to_range[slug] = std::pair(min, max); + + std::string display_name = obj.get_string_throw("display_name", filepath); + StringSelectEntry string_select_entry(slug, display_name); + m_stringselect_database.add_entry(string_select_entry); + } +} + +std::pair DailyHighlightDatabase::get_range_for_slug(const std::string& slug) const { + auto iter = m_slug_to_range.find(slug); + if (iter == m_slug_to_range.end()) { + throw InternalProgramError( + nullptr, + PA_CURRENT_FUNCTION, + std::string("Invalid daily highlight slug: " + slug) + ); + } + return iter->second; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_DailyHighlightDatabase.h b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_DailyHighlightDatabase.h index 5c9052744b..e7219fce37 100644 --- a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_DailyHighlightDatabase.h +++ b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_DailyHighlightDatabase.h @@ -1,38 +1,38 @@ -/* Daily Highlight Database - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_DailyHighlightDatabase_H -#define PokemonAutomation_PokemonSwSh_DailyHighlightDatabase_H - -#include -#include "CommonTools/Options/StringSelectOption.h" - -namespace PokemonAutomation { -namespace NintendoSwitch { -namespace PokemonSwSh { - - -class DailyHighlightDatabase { -public: - DailyHighlightDatabase(const char* resource_path); - - std::pair get_range_for_slug(const std::string& slug) const; - const StringSelectDatabase& database() const { - return m_stringselect_database; - } - -private: - std::map> m_slug_to_range; - StringSelectDatabase m_stringselect_database; -}; - - - - -} -} -} -#endif +/* Daily Highlight Database + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_DailyHighlightDatabase_H +#define PokemonAutomation_PokemonSwSh_DailyHighlightDatabase_H + +#include +#include "CommonTools/Options/StringSelectOption.h" + +namespace PokemonAutomation { +namespace NintendoSwitch { +namespace PokemonSwSh { + + +class DailyHighlightDatabase { +public: + DailyHighlightDatabase(const char* resource_path); + + std::pair get_range_for_slug(const std::string& slug) const; + const StringSelectDatabase& database() const { + return m_stringselect_database; + } + +private: + std::map> m_slug_to_range; + StringSelectDatabase m_stringselect_database; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Tests/PokemonLZA_Tests.cpp b/SerialPrograms/Source/Tests/PokemonLZA_Tests.cpp index dfea312a8f..2788c523d4 100644 --- a/SerialPrograms/Source/Tests/PokemonLZA_Tests.cpp +++ b/SerialPrograms/Source/Tests/PokemonLZA_Tests.cpp @@ -1,49 +1,49 @@ -/* PokemonLZA Tests -* -* From: https://github.com/PokemonAutomation/ -* -*/ - -#include "Common/Compiler.h" -#include "PokemonLZA_Tests.h" -#include "TestUtils.h" -#include "CommonFramework/Language.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/Recording/StreamHistorySession.h" -#include "Controllers/ControllerCapability.h" -#include "NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" -#include "PokemonLZA/Inference/PokemonLZA_DialogDetector.h" -#include -#include -#include -#include -#include -#include -#include -#include -using std::cout; -using std::cerr; -using std::endl; - - -namespace PokemonAutomation{ - - -using namespace NintendoSwitch; -using namespace NintendoSwitch::PokemonLZA; - - - -int test_pokemonZLA_NormalDialogBoxDetector(const ImageViewRGB32& image, bool target){ - auto& logger = global_logger_command_line(); - auto overlay = DummyVideoOverlay(); - const bool stop_on_detected = true; - NormalDialogDetector detector(logger, overlay, stop_on_detected); - bool result = detector.process_frame(image, current_time()); - TEST_RESULT_EQUAL(result, target); - return 0; -} - - +/* PokemonLZA Tests +* +* From: https://github.com/PokemonAutomation/ +* +*/ + +#include "Common/Compiler.h" +#include "PokemonLZA_Tests.h" +#include "TestUtils.h" +#include "CommonFramework/Language.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/Recording/StreamHistorySession.h" +#include "Controllers/ControllerCapability.h" +#include "NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "PokemonLZA/Inference/PokemonLZA_DialogDetector.h" +#include +#include +#include +#include +#include +#include +#include +#include +using std::cout; +using std::cerr; +using std::endl; + + +namespace PokemonAutomation{ + + +using namespace NintendoSwitch; +using namespace NintendoSwitch::PokemonLZA; + + + +int test_pokemonZLA_NormalDialogBoxDetector(const ImageViewRGB32& image, bool target){ + auto& logger = global_logger_command_line(); + auto overlay = DummyVideoOverlay(); + const bool stop_on_detected = true; + NormalDialogDetector detector(logger, overlay, stop_on_detected); + bool result = detector.process_frame(image, current_time()); + TEST_RESULT_EQUAL(result, target); + return 0; +} + + } \ No newline at end of file diff --git a/SerialPrograms/Source/Tests/PokemonLZA_Tests.h b/SerialPrograms/Source/Tests/PokemonLZA_Tests.h index 324f7e1992..709c1704f0 100644 --- a/SerialPrograms/Source/Tests/PokemonLZA_Tests.h +++ b/SerialPrograms/Source/Tests/PokemonLZA_Tests.h @@ -1,27 +1,27 @@ -/* PokemonLZA Tests - * - * From: https://github.com/PokemonAutomation/ - * - * - */ - - - #ifndef PokemonAutomation_Tests_PokemonLZA_Tests_H - #define PokemonAutomation_Tests_PokemonLZA_Tests_H - - #include - #include - - #include "CommonFramework/AudioPipeline/AudioFeed.h" - - namespace PokemonAutomation{ - - class ImageViewRGB32; - - - int test_pokemonZLA_NormalDialogBoxDetector(const ImageViewRGB32& image, bool target); - - } - - #endif +/* PokemonLZA Tests + * + * From: https://github.com/PokemonAutomation/ + * + * + */ + + + #ifndef PokemonAutomation_Tests_PokemonLZA_Tests_H + #define PokemonAutomation_Tests_PokemonLZA_Tests_H + + #include + #include + + #include "CommonFramework/AudioPipeline/AudioFeed.h" + + namespace PokemonAutomation{ + + class ImageViewRGB32; + + + int test_pokemonZLA_NormalDialogBoxDetector(const ImageViewRGB32& image, bool target); + + } + + #endif \ No newline at end of file diff --git a/SerialPrograms/Source/Tests/TestUtils.h b/SerialPrograms/Source/Tests/TestUtils.h index 8c8e31a296..6deaaa4e65 100644 --- a/SerialPrograms/Source/Tests/TestUtils.h +++ b/SerialPrograms/Source/Tests/TestUtils.h @@ -98,7 +98,8 @@ class DummyVideoFeed: public VideoFeed{ // Can call from anywhere. virtual void reset() override{} - virtual VideoSnapshot snapshot() override{ return VideoSnapshot(); } + virtual VideoSnapshot snapshot_latest_blocking() override{ return VideoSnapshot(); } + virtual VideoSnapshot snapshot_recent_nonblocking(WallClock min_time) override{ return VideoSnapshot(); } virtual double fps_source() const override{ return 0; } virtual double fps_display() const override{ return 0; } diff --git a/SerialPrograms/Source/ZeldaTotK/Programs/ZeldaTotK_MineruItemDuper.cpp b/SerialPrograms/Source/ZeldaTotK/Programs/ZeldaTotK_MineruItemDuper.cpp index 24269202ea..18c7d53f5b 100644 --- a/SerialPrograms/Source/ZeldaTotK/Programs/ZeldaTotK_MineruItemDuper.cpp +++ b/SerialPrograms/Source/ZeldaTotK/Programs/ZeldaTotK_MineruItemDuper.cpp @@ -112,8 +112,8 @@ void MineruItemDuper::program(SingleSwitchProgramEnvironment& env, ProController } // Now press Y (sort) and B (exit) at the same time - ssf_press_button(context, BUTTON_B, 0, 10); - pbf_press_button(context, BUTTON_Y, 10, 40); + ssf_press_button(context, BUTTON_B, 0ms, 80ms); + pbf_press_button(context, BUTTON_Y, 80ms, 320ms); // There is no need to pick up Zonai devices if (!IS_ZONAI_DEVICE){ diff --git a/SerialPrograms/Source/ZeldaTotK/Programs/ZeldaTotK_ParaglideItemDuper.cpp b/SerialPrograms/Source/ZeldaTotK/Programs/ZeldaTotK_ParaglideItemDuper.cpp index 40e8750e10..5d50cfd4d0 100644 --- a/SerialPrograms/Source/ZeldaTotK/Programs/ZeldaTotK_ParaglideItemDuper.cpp +++ b/SerialPrograms/Source/ZeldaTotK/Programs/ZeldaTotK_ParaglideItemDuper.cpp @@ -122,8 +122,8 @@ void ParaglideItemDuper::program(SingleSwitchProgramEnvironment& env, ProControl pbf_press_button(context, BUTTON_A, 20, 20); //Now press Y (sort) and B (exit) at the same time - ssf_press_button(context, BUTTON_B, 0, 10); - pbf_press_button(context, BUTTON_Y, 10, 40); + ssf_press_button(context, BUTTON_B, 0ms, 80ms); + pbf_press_button(context, BUTTON_Y, 80ms, 320ms); //Close paraglider and drop to the ground pbf_press_button(context, BUTTON_B, 20, 50); diff --git a/SerialPrograms/Source/ZeldaTotK/Programs/ZeldaTotK_SurfItemDuper.cpp b/SerialPrograms/Source/ZeldaTotK/Programs/ZeldaTotK_SurfItemDuper.cpp index 744f9743a7..08fd61ebd6 100644 --- a/SerialPrograms/Source/ZeldaTotK/Programs/ZeldaTotK_SurfItemDuper.cpp +++ b/SerialPrograms/Source/ZeldaTotK/Programs/ZeldaTotK_SurfItemDuper.cpp @@ -89,9 +89,9 @@ void SurfItemDuper::program(SingleSwitchProgramEnvironment& env, ProControllerCo env.log("Current Attempts: " + tostr_u_commas(c)); //Initiate Shield Surf - ssf_press_button(context, BUTTON_ZL, 0, 80); - ssf_press_button(context, BUTTON_X, 5, 30); - ssf_press_button(context, BUTTON_A, 10, 80); + ssf_press_button(context, BUTTON_ZL, 0ms, 640ms); + ssf_press_button(context, BUTTON_X, 40ms, 240ms); + ssf_press_button(context, BUTTON_A, 80ms, 640ms); //Open menu pbf_press_button(context, BUTTON_PLUS, 20, 100);